{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2004 Ferdinando Ametrano\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file actual365fixed.hpp\n    \\brief Actual/365 (Fixed) day counter\n*/\n\n#ifndef quantlib_actual365fixed_day_counter_h\n#define quantlib_actual365fixed_day_counter_h\n\n#include <ql/time/daycounter.hpp>\n\nnamespace QuantLib {\n\n    //! Actual/365 (Fixed) day count convention\n    /*! \"Actual/365 (Fixed)\" day count convention, also know as\n        \"Act/365 (Fixed)\", \"A/365 (Fixed)\", or \"A/365F\".\n\n        \\warning According to ISDA, \"Actual/365\" (without \"Fixed\") is\n                 an alias for \"Actual/Actual (ISDA)\" (see\n                 ActualActual.)  If Actual/365 is not explicitly\n                 specified as fixed in an instrument specification,\n                 you might want to double-check its meaning.\n\n        \\ingroup daycounters\n    */\n    class Actual365Fixed : public DayCounter {\n      public:\n        enum Convention { Standard, Canadian, NoLeap };\n        explicit Actual365Fixed(Convention c = Actual365Fixed::Standard)\n        : DayCounter(implementation(c)) {}\n\n      private:\n        class Impl : public DayCounter::Impl {\n          public:\n            std::string name() const { return std::string(\"Actual/365 (Fixed)\"); }\n            Time yearFraction(const Date& d1,\n                              const Date& d2,\n                              const Date&,\n                              const Date&) const {\n                return daysBetween(d1,d2)/365.0;\n            }\n        };\n        class CA_Impl : public DayCounter::Impl {\n          public:\n            std::string name() const {\n                return std::string(\"Actual/365 (Fixed) Canadian Bond\");\n            }\n            Time yearFraction(const Date& d1,\n                              const Date& d2,\n                              const Date& refPeriodStart,\n                              const Date& refPeriodEnd) const;\n        };\n        class NL_Impl : public DayCounter::Impl {\n          public:\n            std::string name() const {\n                return std::string(\"Actual/365 (No Leap)\");\n            }\n            Date::serial_type dayCount(const Date& d1,\n                                       const Date& d2) const;\n            Time yearFraction(const Date& d1,\n                              const Date& d2,\n                              const Date& refPeriodStart,\n                              const Date& refPeriodEnd) const;\n        };\n        static boost::shared_ptr<DayCounter::Impl> implementation(Convention);\n    };\n\n}\n\n/* -*- 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\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    inline boost::shared_ptr<DayCounter::Impl>\n    Actual365Fixed::implementation(Actual365Fixed::Convention c) {\n        switch (c) {\n          case Standard:\n            return boost::shared_ptr<DayCounter::Impl>(new Impl);\n          case Canadian:\n            return boost::shared_ptr<DayCounter::Impl>(new CA_Impl);\n          case NoLeap:\n            return boost::shared_ptr<DayCounter::Impl>(new NL_Impl);\n          default:\n            QL_FAIL(\"unknown Actual/365 (Fixed) convention\");\n        }\n    }\n\n    inline Time Actual365Fixed::CA_Impl::yearFraction(const Date& d1,\n                                               const Date& d2,\n                                               const Date& refPeriodStart,\n                                               const Date& refPeriodEnd) const {\n        // Need the period to calculate frequency\n        QL_REQUIRE(refPeriodStart != Date(),\"invalid refPeriodStart\");\n        QL_REQUIRE(refPeriodEnd != Date(),\"invalid refPeriodEnd\");\n\n        Time dcs = daysBetween(d1,d2);\n        Time dcc = daysBetween(refPeriodStart,refPeriodEnd);\n        Integer months = Integer(0.5+12*dcc/365);\n        Integer frequency = Integer( 12/months);\n\n        if ( dcs < 365/frequency)\n            return dcs/365.0;\n\n        return 1./frequency - (dcc-dcs)/365.0;\n\n    }\n\n    inline Date::serial_type Actual365Fixed::NL_Impl::dayCount(const Date& d1,\n                                                        const Date& d2) const {\n\n        static const Integer MonthOffset[] = {\n            0,  31,  59,  90, 120, 151,  // Jan - Jun\n            181, 212, 243, 273, 304, 334   // Jun - Dec\n        };\n\n        Date::serial_type s1 = d1.dayOfMonth()\n                             + MonthOffset[d1.month()-1] + (d1.year() * 365);\n        Date::serial_type s2 = d2.dayOfMonth()\n                             + MonthOffset[d2.month()-1] + (d2.year() * 365);\n\n        if (d1.month() == Feb && d1.dayOfMonth() == 29) {\n            --s1;\n        }\n\n        if (d2.month() == Feb && d2.dayOfMonth() == 29) {\n            --s2;\n        }\n\n        return s2 - s1;\n    }\n\n    inline Time Actual365Fixed::NL_Impl::yearFraction(const Date& d1,\n                                               const Date& d2,\n                                               const Date& d3,\n                                               const Date& d4) const {\n        return dayCount(d1, d2)/365.0;\n    }\n\n}\n\n\n\n#endif\n\n", "meta": {"hexsha": "ac9bf8c20d94877f05e29bda57ce3a0e12863805", "size": 6587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/time/daycounters/actual365fixed.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/time/daycounters/actual365fixed.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/time/daycounters/actual365fixed.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 36.1923076923, "max_line_length": 82, "alphanum_fraction": 0.5712767572, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.10230471336665163, "lm_q1q2_score": 0.04995369279743582}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\r\n *    All rights reserved.\r\n *\r\n *    Redistribution and use in source and binary forms, with or without modification, are\r\n *    permitted provided that the following conditions are met:\r\n *      - Redistributions of source code must retain the above copyright notice, this list of\r\n *        conditions and the following disclaimer.\r\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\r\n *        conditions and the following disclaimer in the documentation and/or other materials\r\n *        provided with the distribution.\r\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\r\n *        may be used to endorse or promote products derived from this software without specific\r\n *        prior written permission.\r\n *\r\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\r\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\r\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\r\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\r\n *    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\r\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *    Changelog\r\n *      YYMMDD    Author            Comment\r\n *      120717    D. Dirkx          Creation of file.\r\n *      120921    M.I. Ganeff       Added the functions getTotalCountOfKernelsLoaded and\r\n *                                  clearSpiceKernels.\r\n *\r\n *    References\r\n *\r\n *    Notes\r\n *\r\n */\r\n\r\n\r\n#include <boost/lexical_cast.hpp>\r\n\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h\"\r\n#include \"Tudat/External/SpiceInterface/spiceInterface.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace spice_interface\r\n{\r\n\r\nusing basic_mathematics::Vector6d;\r\n\r\n//! Convert a Julian date to ephemeris time (equivalent to TDB in Spice).\r\ndouble convertJulianDateToEphemerisTime( const double julianDate )\r\n{\r\n    return ( julianDate - j2000_c( ) ) * spd_c( );\r\n}\r\n\r\n//! Convert ephemeris time (equivalent to TDB) to a Julian date.\r\ndouble convertEphemerisTimeToJulianDate( const double ephemerisTime )\r\n{\r\n    return j2000_c( ) + ( ephemerisTime ) / spd_c( );\r\n}\r\n\r\n//! Converts a date string to ephemeris time.\r\ndouble convertDateStringToEphemerisTime( const std::string& dateString )\r\n{\r\n    double ephemerisTime = 0.0;\r\n    str2et_c( dateString.c_str( ), &ephemerisTime );\r\n    return ephemerisTime;\r\n}\r\n\r\n//! Get Cartesian state of a body, as observed from another body.\r\nVector6d getBodyCartesianStateAtEpoch(\r\n        const std::string& targetBodyName, const std::string& observerBodyName,\r\n        const std::string& referenceFrameName, const std::string& abberationCorrections,\r\n        const double ephemerisTime )\r\n{\r\n\r\n    // Declare variables for cartesian state and light-time to be determined by Spice.\r\n    double stateAtEpoch[ 6 ];\r\n    double lightTime;\r\n\r\n    // Call Spice function to calculate state and light-time.\r\n    spkezr_c( targetBodyName.c_str( ), ephemerisTime, referenceFrameName.c_str( ),\r\n              abberationCorrections.c_str( ), observerBodyName.c_str( ), stateAtEpoch,\r\n              &lightTime );\r\n\r\n    // Put result in Eigen Vector.\r\n    Vector6d cartesianStateVector;\r\n    for ( unsigned int i = 0; i < 6 ; i++ )\r\n    {\r\n        cartesianStateVector( i ) = stateAtEpoch[ i ];\r\n    }\r\n\r\n    // Convert from km(/s) to m(/s).\r\n    return unit_conversions::convertKilometersToMeters< Vector6d >(\r\n                cartesianStateVector );\r\n}\r\n\r\n//! Get Cartesian position of a body, as observed from another body.\r\nEigen::Vector3d getBodyCartesianPositionAtEpoch( const std::string& targetBodyName,\r\n                                                 const std::string& observerBodyName,\r\n                                                 const std::string& referenceFrameName,\r\n                                                 const std::string& abberationCorrections,\r\n                                                 const double ephemerisTime )\r\n{\r\n    // Declare variables for cartesian position and light-time to be determined by Spice.\r\n    double positionAtEpoch[ 3 ];\r\n    double lightTime;\r\n\r\n    // Call Spice function to calculate position and light-time.\r\n    spkpos_c( targetBodyName.c_str( ), ephemerisTime, referenceFrameName.c_str( ),\r\n              abberationCorrections.c_str( ), observerBodyName.c_str( ), positionAtEpoch,\r\n              &lightTime );\r\n\r\n    // Put result in Eigen Vector.\r\n    Eigen::Vector3d cartesianPositionVector;\r\n    for ( unsigned int i = 0; i < 3 ; i++ )\r\n    {\r\n        cartesianPositionVector( i ) = positionAtEpoch[ i ];\r\n    }\r\n\r\n    // Convert from km to m.\r\n    return unit_conversions::convertKilometersToMeters< Eigen::Vector3d >(\r\n                cartesianPositionVector );\r\n}\r\n\r\n//! Compute quaternion of rotation between two frames.\r\nEigen::Quaterniond computeRotationQuaternionBetweenFrames( const std::string& originalFrame,\r\n                                                           const std::string& newFrame,\r\n                                                           const double ephemerisTime )\r\n{\r\n    // Declare rotation matrix.\r\n    double rotationArray[ 3 ][ 3 ];\r\n\r\n    // Calculate rotation matrix.\r\n    pxform_c( originalFrame.c_str( ), newFrame.c_str( ), ephemerisTime, rotationArray );\r\n\r\n    // Put rotation matrix in Eigen Matrix3d.\r\n    Eigen::Matrix3d rotationMatrix;\r\n    for ( unsigned int i = 0; i < 3; i++ )\r\n    {\r\n        for ( unsigned int j = 0; j < 3; j++ )\r\n        {\r\n            rotationMatrix( i, j ) = rotationArray[ i ][ j ];\r\n        }\r\n    }\r\n\r\n    // Convert matrix3d to Quaternion.\r\n    return Eigen::Quaterniond( rotationMatrix );\r\n}\r\n\r\n//! Computes time derivative of rotation matrix between two frames.\r\nEigen::Matrix3d computeRotationMatrixDerivativeBetweenFrames( const std::string& originalFrame,\r\n                                                              const std::string& newFrame,\r\n                                                              const double ephemerisTime )\r\n{\r\n    double stateTransition[ 6 ][ 6 ];\r\n\r\n    // Calculate state transition matrix.\r\n    sxform_c( originalFrame.c_str( ), newFrame.c_str( ), ephemerisTime, stateTransition );\r\n\r\n    // Put rotation matrix derivative in Eigen Matrix3d\r\n    Eigen::Matrix3d matrixDerivative = Eigen::Matrix3d::Zero( );\r\n    for( unsigned int i = 0; i < 3; i++ )\r\n    {\r\n        for( unsigned int j = 0; j < 3; j++ )\r\n        {\r\n            matrixDerivative( i, j ) = stateTransition[ i + 3 ][ j ];\r\n        }\r\n    }\r\n\r\n    return matrixDerivative;\r\n}\r\n\r\n//! Computes the angular velocity of one frame w.r.t. to another frame.\r\nEigen::Vector3d getAngularVelocityVectorOfFrameInOriginalFrame( const std::string& originalFrame,\r\n                                                                const std::string& newFrame,\r\n                                                                const double ephemerisTime )\r\n{\r\n    double stateTransition[ 6 ][ 6 ];\r\n\r\n    // Calculate state transition matrix.\r\n    sxform_c( originalFrame.c_str( ), newFrame.c_str( ), ephemerisTime, stateTransition );\r\n\r\n    double rotation[ 3 ][ 3 ];\r\n    double angularVelocity[ 3 ];\r\n\r\n    // Calculate angular velocity vector.\r\n    xf2rav_c( stateTransition, rotation, angularVelocity );\r\n\r\n    return ( Eigen::Vector3d( )<<angularVelocity[ 0 ], angularVelocity[ 1 ], angularVelocity[ 2 ] ).\r\n            finished( );\r\n}\r\n\r\nstd::pair< Eigen::Quaterniond, Eigen::Matrix3d > computeRotationQuaternionAndRotationMatrixDerivativeBetweenFrames(\r\n        const std::string& originalFrame, const std::string& newFrame, const double ephemerisTime )\r\n{\r\n    double stateTransition[ 6 ][ 6 ];\r\n\r\n    sxform_c( originalFrame.c_str( ), newFrame.c_str( ), ephemerisTime, stateTransition );\r\n\r\n    Eigen::Matrix3d matrixDerivative;\r\n    Eigen::Matrix3d rotationMatrix;\r\n\r\n    for( unsigned int i = 0; i < 3; i++ )\r\n    {\r\n        for( unsigned int j = 0; j < 3; j++ )\r\n        {\r\n            rotationMatrix( i, j ) = stateTransition[ i ][ j ];\r\n            matrixDerivative( i, j ) = stateTransition[ i + 3 ][ j ];\r\n        }\r\n    }\r\n    return std::make_pair( Eigen::Quaterniond( rotationMatrix ), matrixDerivative );\r\n}\r\n\r\n//! Get property of a body from Spice.\r\nstd::vector< double > getBodyProperties( const std::string& body, const std::string& property,\r\n                                         const int maximumNumberOfValues )\r\n{\r\n    // Delcare variable in which raw result is to be put by Spice function.\r\n    double propertyArray[ maximumNumberOfValues ];\r\n\r\n    // Call Spice function to retrieve property.\r\n    SpiceInt numberOfReturnedParameters;\r\n    bodvrd_c( body.c_str( ), property.c_str( ), maximumNumberOfValues, &numberOfReturnedParameters,\r\n              propertyArray );\r\n\r\n    // Put result in STL vector.\r\n    std::vector< double > bodyProperties;\r\n    bodyProperties.resize( numberOfReturnedParameters );\r\n    for ( int i = 0; i < numberOfReturnedParameters; i++ )\r\n    {\r\n        bodyProperties.at( i ) = propertyArray[ i ];\r\n    }\r\n    return bodyProperties;\r\n}\r\n\r\n//! Get gravitational parameter of a body.\r\ndouble getBodyGravitationalParameter( const std::string& body )\r\n{\r\n    // Delcare variable in which raw result is to be put by Spice function.\r\n    double gravitationalParameter[ 1 ];\r\n\r\n    // Call Spice function to retrieve gravitational parameter.\r\n    SpiceInt numberOfReturnedParameters;\r\n    bodvrd_c( body.c_str( ), \"GM\", 1, &numberOfReturnedParameters, gravitationalParameter );\r\n\r\n    // Convert from km^3/s^2 to m^3/s^2\r\n    return unit_conversions::convertKilometersToMeters< double >(\r\n                unit_conversions::convertKilometersToMeters< double >(\r\n                    unit_conversions::convertKilometersToMeters< double >(\r\n                        gravitationalParameter[ 0 ] ) ) );\r\n}\r\n\r\n//! Get the (arithmetic) mean of the three principal axes of the tri-axial ellipsoid shape.\r\ndouble getAverageRadius( const std::string& body )\r\n{\r\n    // Delcare variable in which raw result is to be put by Spice function.\r\n    double radii[ 3 ];\r\n\r\n    // Call Spice function to retrieve gravitational parameter.\r\n    SpiceInt numberOfReturnedParameters;\r\n    bodvrd_c( body.c_str( ), \"RADII\", 3, &numberOfReturnedParameters, radii );\r\n\r\n    // Compute average and convert from km to m.\r\n    return unit_conversions::convertKilometersToMeters< double >(\r\n                radii[ 0 ] + radii[ 1 ] + radii[ 2 ] ) / 3.0;\r\n}\r\n\r\n//! Convert a body name to its NAIF identification number.\r\nint convertBodyNameToNaifId( const std::string& bodyName )\r\n{\r\n    // Convert body name to NAIF ID number.\r\n    SpiceInt bodyNaifId;\r\n    SpiceBoolean isIdFound;\r\n    bods2c_c( bodyName.c_str( ), &bodyNaifId, &isIdFound );\r\n\r\n    // Convert SpiceInt (typedef for long) to int and return.\r\n    return static_cast< int >( bodyNaifId );\r\n}\r\n\r\n//! Check if a certain property of a body is in the kernel pool.\r\nbool checkBodyPropertyInKernelPool( const std::string& bodyName, const std::string& bodyProperty )\r\n{\r\n    // Convert body name to NAIF ID.\r\n    const int naifId = convertBodyNameToNaifId( bodyName );\r\n\r\n    // Determine if property is in pool.\r\n    SpiceBoolean isPropertyInPool = bodfnd_c( naifId, bodyProperty.c_str( ) );\r\n    return static_cast< bool >( isPropertyInPool );\r\n}\r\n\r\n//! Load a Spice kernel.\r\nvoid loadSpiceKernelInTudat( const std::string& fileName )\r\n{\r\n    furnsh_c(  fileName.c_str( ) );\r\n}\r\n\r\n//! Get the amount of loaded Spice kernels.\r\nint getTotalCountOfKernelsLoaded( )\r\n{\r\n    SpiceInt count;\r\n    ktotal_c( \"ALL\", &count );\r\n    return count;\r\n}\r\n\r\n//! Clear all Spice kernels.\r\nvoid clearSpiceKernels( ) { kclear_c( ); }\r\n\r\n} // namespace spice_interface\r\n} // namespace tudat\r\n", "meta": {"hexsha": "dba4f7a88636a23efe8ac352f0b74a07af0849c4", "size": 12223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/External/SpiceInterface/spiceInterface.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/External/SpiceInterface/spiceInterface.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/External/SpiceInterface/spiceInterface.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.3022508039, "max_line_length": 116, "alphanum_fraction": 0.6405955985, "num_tokens": 2810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.10818895887524602, "lm_q1q2_score": 0.04861932124894634}}
{"text": "\n// Copyright (c) 2021-2022, University of Colorado Denver. All rights reserved.\n//\n// This file is part of <T>LAPACK.\n// <T>LAPACK is free software: you can redistribute it and/or modify it under\n// the terms of the BSD 3-Clause license. See the accompanying LICENSE file.\n\n#ifndef __TLAPACK_EIGEN_HH__\n#define __TLAPACK_EIGEN_HH__\n\n#include <Eigen/Core>\n#include <type_traits>\n#include \"blas/arrayTraits.hpp\"\n\nnamespace blas{\n\n    // // -----------------------------------------------------------------------------\n    // // is_EigenBlock\n    \n    // template< class >\n    // struct is_EigenBlock : public std::false_type {};\n\n    // template< typename T, int R, int C, bool P >\n    // struct is_EigenBlock< Eigen::Block<T,R,C,P> > : public std::true_type {};\n\n    // -----------------------------------------------------------------------------\n    // Data traits for Eigen\n\n    // Data type\n    template<typename Scalar_, int Rows_, int Cols_, int Options_, int MaxRows_, int MaxCols_>\n    struct type_trait< Eigen::Matrix<Scalar_, Rows_, Cols_, Options_, MaxRows_, MaxCols_> > {\n        using type = Scalar_;\n    };\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    struct type_trait< Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel> > {\n        using type = typename XprType::Scalar;\n    };\n    template<class T>\n    struct type_trait< Eigen::VectorBlock<T> > {\n        using type = typename T::Scalar;\n    };\n    template<class T, int idx>\n    struct type_trait< Eigen::Diagonal<T,idx> > {\n        using type = typename T::Scalar;\n    };\n\n    // Size type\n    template<typename Scalar_, int Rows_, int Cols_, int Options_, int MaxRows_, int MaxCols_>\n    struct sizet_trait< Eigen::Matrix<Scalar_, Rows_, Cols_, Options_, MaxRows_, MaxCols_> > {\n        using type = Eigen::Index;\n    };\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    struct sizet_trait< Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel> > {\n        using type = Eigen::Index;\n    };\n    template<class T>\n    struct sizet_trait< Eigen::VectorBlock<T> > {\n        using type = Eigen::Index;\n    };\n    template<class T, int idx>\n    struct sizet_trait< Eigen::Diagonal<T,idx> > {\n        using type = Eigen::Index;\n    };\n\n    // -----------------------------------------------------------------------------\n    // blas functions to access Eigen properties\n\n    // Size\n    template<class T>\n    inline constexpr auto\n    size( const Eigen::EigenBase<T>& x ) {\n        return x.size();\n    }\n    // Number of rows\n    template<class T>\n    inline constexpr auto\n    nrows( const Eigen::EigenBase<T>& x ) {\n        return x.rows();\n    }\n    // Number of columns\n    template<class T>\n    inline constexpr auto\n    ncols( const Eigen::EigenBase<T>& x ) {\n        return x.cols();\n    }\n    // Read policy\n    template<class T>\n    inline constexpr auto\n    read_policy( const Eigen::DenseBase<T>& x ) {\n        return lapack::dense;\n    }\n    // Write policy\n    template<class T>\n    inline constexpr auto\n    write_policy( const Eigen::DenseBase<T>& x ) {\n        return lapack::dense;\n    }\n\n    // -----------------------------------------------------------------------------\n    // blas functions to access Eigen block operations\n\n    #define isSlice(SliceSpec) !std::is_convertible< SliceSpec, Eigen::Index >::value\n\n    // Slice\n    template<class T, typename SliceSpecRow, typename SliceSpecCol,\n        typename std::enable_if< isSlice(SliceSpecRow) && isSlice(SliceSpecCol), int >::type = 0\n    >\n    inline constexpr auto slice(\n        const Eigen::DenseBase<T>& A, SliceSpecRow&& rows, SliceSpecCol&& cols ) noexcept\n    {\n        return A.block( rows.first, cols.first,\n                        rows.second-rows.first, cols.second-cols.first );\n    }\n    template<class T, typename SliceSpecRow, typename SliceSpecCol,\n        typename std::enable_if< isSlice(SliceSpecRow) && isSlice(SliceSpecCol), int >::type = 0\n    >\n    inline constexpr auto slice(\n        Eigen::DenseBase<T>& A, SliceSpecRow&& rows, SliceSpecCol&& cols ) noexcept\n    {\n        return A.block( rows.first, cols.first,\n                        rows.second-rows.first, cols.second-cols.first );\n    }\n    template< typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n              typename SliceSpecRow, typename SliceSpecCol,\n        typename std::enable_if< isSlice(SliceSpecRow) && isSlice(SliceSpecCol), int >::type = 0\n    >\n    inline constexpr auto slice(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A,\n        SliceSpecRow&& rows, SliceSpecCol&& cols ) noexcept\n    {\n        return A.block( rows.first, cols.first,\n                        rows.second-rows.first, cols.second-cols.first );\n    }\n\n    #undef isSlice\n\n    // Slice\n    template<class T, typename SliceSpecCol>\n    inline constexpr auto slice(\n        const Eigen::DenseBase<T>& A, Eigen::Index rowIdx, SliceSpecCol&& cols ) noexcept\n    {\n        return A.row( rowIdx ).segment( cols.first, cols.second-cols.first );\n    }\n    template<class T, typename SliceSpecCol>\n    inline constexpr auto slice(\n        Eigen::DenseBase<T>& A, Eigen::Index rowIdx, SliceSpecCol&& cols ) noexcept\n    {\n        return A.row( rowIdx ).segment( cols.first, cols.second-cols.first );\n    }\n    template< typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n              typename SliceSpecCol >\n    inline constexpr auto slice(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A,\n        Eigen::Index rowIdx, SliceSpecCol&& cols ) noexcept\n    {\n        return A.row( rowIdx ).segment( cols.first, cols.second-cols.first );\n    }\n\n    // Slice\n    template<class T, typename SliceSpecRow>\n    inline constexpr auto slice(\n        const Eigen::DenseBase<T>& A, SliceSpecRow&& rows, Eigen::Index colIdx = 0 ) noexcept\n    {\n        return A.col( colIdx ).segment( rows.first, rows.second-rows.first );\n    }\n    template<class T, typename SliceSpecRow>\n    inline constexpr auto slice(\n        Eigen::DenseBase<T>& A, SliceSpecRow&& rows, Eigen::Index colIdx = 0 ) noexcept\n    {\n        return A.col( colIdx ).segment( rows.first, rows.second-rows.first );\n    }\n    template< typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n              typename SliceSpecRow >\n    inline constexpr auto slice(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A,\n        SliceSpecRow&& rows, Eigen::Index colIdx = 0 ) noexcept\n    {\n        return A.col( colIdx ).segment( rows.first, rows.second-rows.first );\n    }\n\n    // Rows\n    template<class T, typename SliceSpec>\n    inline constexpr auto rows(\n        const Eigen::DenseBase<T>& A, SliceSpec&& rows ) noexcept\n    {\n        return A.middleRows( rows.first, rows.second-rows.first );\n    }\n    template<class T, typename SliceSpec>\n    inline constexpr auto rows(\n        Eigen::DenseBase<T>& A, SliceSpec&& rows ) noexcept\n    {\n        return A.middleRows( rows.first, rows.second-rows.first );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n             typename SliceSpec>\n    inline constexpr auto rows(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, SliceSpec&& rows ) noexcept\n    {\n        return A.middleRows( rows.first, rows.second-rows.first );\n    }\n\n    // Row\n    template<class T>\n    inline constexpr auto row( const Eigen::DenseBase<T>& A, Eigen::Index rowIdx ) noexcept\n    {\n        return A.row( rowIdx );\n    }\n    template<class T>\n    inline constexpr auto row( Eigen::DenseBase<T>& A, Eigen::Index rowIdx ) noexcept\n    {\n        return A.row( rowIdx );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    inline constexpr auto row(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, Eigen::Index rowIdx ) noexcept\n    {\n        return A.row( rowIdx );\n    }\n\n    // Cols\n    template<class T, typename SliceSpec>\n    inline constexpr auto cols(\n        const Eigen::DenseBase<T>& A, SliceSpec&& cols ) noexcept\n    {\n        return A.middleCols( cols.first, cols.second-cols.first );\n    }\n    template<class T, typename SliceSpec>\n    inline constexpr auto cols(\n        Eigen::DenseBase<T>& A, SliceSpec&& cols ) noexcept\n    {\n        return A.middleCols( cols.first, cols.second-cols.first );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n             typename SliceSpec>\n    inline constexpr auto cols(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, SliceSpec&& cols ) noexcept\n    {\n        return A.middleCols( cols.first, cols.second-cols.first );\n    }\n\n    // Column\n    template<class T>\n    inline constexpr auto col( const Eigen::DenseBase<T>& A, Eigen::Index colIdx ) noexcept\n    {\n        return A.col( colIdx );\n    }\n    template<class T>\n    inline constexpr auto col( Eigen::DenseBase<T>& A, Eigen::Index colIdx ) noexcept\n    {\n        return A.col( colIdx );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    inline constexpr auto col( Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, Eigen::Index colIdx ) noexcept\n    {\n        return A.col( colIdx );\n    }\n\n    // Diagonal\n    template<class T, class int_t>\n    inline constexpr auto diag( const Eigen::MatrixBase<T>& A, int_t diagIdx = 0 ) noexcept\n    {\n        return A.diagonal( diagIdx );\n    }\n    template<class T, class int_t>\n    inline constexpr auto diag( Eigen::MatrixBase<T>& A, int_t diagIdx = 0 ) noexcept\n    {\n        return A.diagonal( diagIdx );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel, typename SliceSpec, class int_t>\n    inline constexpr auto diag( Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, int_t diagIdx = 0 ) noexcept\n    {\n        return A.diagonal( diagIdx );\n    }\n\n} // namespace blas\n\nnamespace lapack {\n\n    using blas::size;\n    using blas::nrows;\n    using blas::ncols;\n    using blas::read_policy;\n    using blas::write_policy;\n\n    using blas::slice;\n    using blas::rows;\n    using blas::row;\n    using blas::cols;\n    using blas::col;\n    using blas::diag;\n\n} // namespace lapack\n\n#endif // __TLAPACK_EIGEN_HH__\n", "meta": {"hexsha": "87930b13b871a65adae1420ecfbb7f0f4dadc475", "size": 10272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/plugins/tlapack_eigen.hpp", "max_stars_repo_name": "thijssteel/tlapack", "max_stars_repo_head_hexsha": "0749324fdecfc80c089d58d8d43500b66a20df70", "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/plugins/tlapack_eigen.hpp", "max_issues_repo_name": "thijssteel/tlapack", "max_issues_repo_head_hexsha": "0749324fdecfc80c089d58d8d43500b66a20df70", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/plugins/tlapack_eigen.hpp", "max_forks_repo_name": "thijssteel/tlapack", "max_forks_repo_head_hexsha": "0749324fdecfc80c089d58d8d43500b66a20df70", "max_forks_repo_licenses": ["BSD-3-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.8203389831, "max_line_length": 122, "alphanum_fraction": 0.6236370717, "num_tokens": 2517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.09670580045532219, "lm_q1q2_score": 0.0468423637746222}}
{"text": "/* $Id: step-49.cc 28599 2013-02-27 04:25:41Z bangerth $\n *\n * Copyright (C) 2013 by the deal.II authors\n *\n * This file is subject to QPL and may not be  distributed\n * without copyright and license information. Please refer\n * to the file deal.II/doc/license.html for the  text  and\n * further information on this license.\n */\n\n\n// This tutorial program is odd in the sense that, unlike for most other\n// steps, the introduction already provides most of the information on how to\n// use the various strategies to generate meshes. Consequently, there is\n// little that remains to be commented on here, and we intersperse the code\n// with relatively little text. In essence, the code here simply provides a\n// reference implementation of what has already been described in the\n// introduction.\n\n// @sect3{Include files}\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_in.h>\n\n#include <fstream>\n\n#include <map>\n\nusing namespace dealii;\n\n// @sect3{Generating output for a given mesh}\n\n// The following function generates some output for any of the meshes we will\n// be generating in the remainder of this program. In particular, it generates\n// the following information:\n//\n// - Some general information about the number of space dimensions in which\n//   this mesh lives and its number of cells.\n// - The number of boundary faces that use each boundary indicator, so that\n//   it can be compared with what we expect.\n//\n// Finally, the function outputs the mesh in encapsulated postscript (EPS)\n// format that can easily be visualized in the same way as was done in step-1.\ntemplate<int dim>\nvoid mesh_info(const Triangulation<dim> &tria,\n\t       const std::string        &filename)\n{\n  std::cout << \"Mesh info:\" << std::endl\n            << \" dimension: \" << dim << std::endl\n            << \" no. of cells: \" << tria.n_active_cells() << std::endl;\n\n  // Next loop over all faces of all cells and find how often each boundary\n  // indicator is used:\n  {\n    std::map<unsigned int, unsigned int> boundary_count;\n    typename Triangulation<dim>::active_cell_iterator\n    cell = tria.begin_active(),\n    endc = tria.end();\n    for (; cell!=endc; ++cell)\n      {\n        for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)\n          {\n            if (cell->face(face)->at_boundary())\n              boundary_count[cell->face(face)->boundary_indicator()]++;\n          }\n      }\n\n    std::cout << \" boundary indicators: \";\n    for (std::map<unsigned int, unsigned int>::iterator it=boundary_count.begin();\n         it!=boundary_count.end();\n         ++it)\n      {\n        std::cout << it->first << \"(\" << it->second << \" times) \";\n      }\n    std::cout << std::endl;\n  }\n\n  // Finally, produce a graphical representation of the mesh to an output\n  // file:\n  std::ofstream out (filename.c_str());\n  GridOut grid_out;\n  grid_out.write_eps (tria, out);\n  std::cout << \" written to \" << filename\n\t    << std::endl\n\t    << std::endl;\n}\n\n// @sect3{Main routines}\n\n// @sect4{grid_1: Loading a mesh generated by gmsh}\n\n// In this first example, we show how to load the mesh for which we have\n// discussed in the introduction how to generate it. This follows the same\n// pattern as used in step-5 to load a mesh, although there it was written in\n// a different file format (UCD instead of MSH).\nvoid grid_1 ()\n{\n  Triangulation<2> triangulation;\n\n  GridIn<2> gridin;\n  gridin.attach_triangulation(triangulation);\n  std::ifstream f(\"untitled.msh\");\n  gridin.read_msh(f);\n\n  mesh_info(triangulation, \"grid-1.eps\");\n\n}\n\n\n// @sect4{grid_2: Merging triangulations}\n\n// Here, we first create two triangulations and then merge them into one.  As\n// discussed in the introduction, it is important to ensure that the vertices\n// at the common interface are located at the same coordinates.\nvoid grid_2 ()\n{\n  Triangulation<2> tria1;\n  GridGenerator::hyper_cube_with_cylindrical_hole (tria1, 0.25, 1.0);\n\n  Triangulation<2> tria2;\n  std::vector< unsigned int > repetitions(2);\n  repetitions[0]=3;\n  repetitions[1]=2;\n  GridGenerator::subdivided_hyper_rectangle (tria2, repetitions,\n                                             Point<2>(1.0,-1.0),\n\t\t\t\t\t     Point<2>(4.0,1.0));\n\n  Triangulation<2> triangulation;\n  GridGenerator::merge_triangulations (tria1, tria2, triangulation);\n\n  mesh_info(triangulation, \"grid-2.eps\");\n}\n\n\n// @sect4{grid_3: Moving vertices}\n\n// In this function, we move vertices of a mesh. This is simpler than one\n// usually expects: if you ask a cell using <code>cell-@>vertex(i)</code> for\n// the coordinates of its <code>i</code>th vertex, it doesn't just provide the\n// location of this vertex but in fact a reference to the location where these\n// coordinates are stored. We can then modify the value stored there.\n//\n// So this is what we do in the first part of this function: We create a\n// square of geometry $[-1,1]^2$ with a circular hole with radius 0.25 located\n// at the origin. We then loop over all cells and all vertices and if a vertex\n// has a $y$ coordinate equal to one, we move it upward by 0.5.\n//\n// Note that this sort of procedure does not usually work this way because one\n// will typically encounter the same vertices multiple times and may move them\n// more than once. It works here because we select the vertices we want to use\n// based on their geometric location, and a vertex moved once will fail this\n// test in the future. A more general approach to this problem would have been\n// to keep a std::set of of those vertex indices that we have already moved\n// (which we can obtain using <code>cell-@>vertex_index(i)</code> and only\n// move those vertices whose index isn't in the set yet.\nvoid grid_3 ()\n{\n  Triangulation<2> triangulation;\n  GridGenerator::hyper_cube_with_cylindrical_hole (triangulation, 0.25, 1.0);\n\n  Triangulation<2>::active_cell_iterator\n  cell = triangulation.begin_active(),\n  endc = triangulation.end();\n  for (; cell!=endc; ++cell)\n    {\n      for (unsigned int i=0; i<GeometryInfo<2>::vertices_per_cell; ++i)\n        {\n          Point<2> &v = cell->vertex(i);\n          if (std::abs(v(1)-1.0)<1e-5)\n            v(1) += 0.5;\n        }\n    }\n\n  // In the second step we will refine the mesh twice. To do this correctly,\n  // we have to associate a geometry object with the boundary of the hole;\n  // since the boundary of the hole has boundary indicator 1 (see the\n  // documentation of the function that generates the mesh), we need to create\n  // an object that describes a circle (i.e., a hyper ball) with appropriate\n  // center and radius and assign it to the triangulation. We can then refine\n  // twice:\n  const HyperBallBoundary<2> boundary_description(Point<2>(0,0), 0.25);\n  triangulation.set_boundary (1, boundary_description);\n  triangulation.refine_global(2);\n\n  // The mesh so generated is then passed to the function that generates\n  // output. In a final step we remove the boundary object again so that it is\n  // no longer in use by the triangulation when it is destroyed (the boundary\n  // object is destroyed first in this function since it was declared after\n  // the triangulation).\n  mesh_info (triangulation, \"grid-3.eps\");\n  triangulation.set_boundary (1);\n}\n\n// There is one snag to doing things as shown above: If one moves the nodes on\n// the boundary as shown here, one often ends up with cells in the interior\n// that are badly distorted since the interior nodes were not moved around. This\n// is not that much of a problem in the current case since the mesh did not\n// contain any internal nodes when the nodes were moved -- it was the coarse\n// mesh and it so happened that all vertices are at the boundary. It's also\n// the case that the movement we had here was, compared to the average cell\n// size not overly dramatic. Nevertheless, sometimes one does want to move\n// vertices by a significant distance, and in that case one needs to move\n// internal nodes as well. One way to do that automatically is to call the\n// function GridTools::laplace_transform that takes a set of transformed\n// vertex coordinates and moves all of the other vertices in such a way that the\n// resulting mesh has, in some sense, a small distortion.\n\n\n\n// @sect4{grid_4: Demonstrating extrude_triangulation}\n\n// This example takes the initial grid from the previous function and simply extrudes it into the third space dimension:\nvoid grid_4()\n{\n  Triangulation<2> triangulation;\n  Triangulation<3> out;\n  GridGenerator::hyper_cube_with_cylindrical_hole (triangulation, 0.25, 1.0);\n\n  GridGenerator::extrude_triangulation (triangulation, 3, 2.0, out);\n  mesh_info(out, \"grid-4.eps\");\n\n}\n\n\n// @sect4{grid_5: Demonstrating GridTools::transform, part 1}\n\n// This and the next example first create a mesh and then transform it by\n// moving every node of the mesh according to a function that takes a point\n// and returns a mapped point. In this case, we transform $(x,y) \\mapsto\n// (x,y+\\sin(\\pi x/5))$.\n//\n// GridTools::transform takes a triangulation and any kind of object that can\n// be called like a function as arguments. This function-like argument can be\n// simply the address of a function as in the current case, or an object that\n// has an <code>operator()</code> as in the next example, or for example a\n// <code>std::function@<Point@<2@>(const Point@<2@>)@></code> object one can get\n// via <code>std::bind</code> in more complex cases.\nPoint<2> grid_5_transform (const Point<2> &in)\n{\n  return Point<2>(in(0),\n\t\t  in(1) + std::sin(in(0)/5.0*3.14159));\n}\n\n\nvoid grid_5()\n{\n  Triangulation<2> tria;\n  std::vector<unsigned int> repetitions(2);\n  repetitions[0] = 14;\n  repetitions[1] = 2;\n  GridGenerator::subdivided_hyper_rectangle (tria, repetitions,\n                                             Point<2>(0.0,0.0),\n\t\t\t\t\t     Point<2>(10.0,1.0));\n\n  GridTools::transform(&grid_5_transform, tria);\n  mesh_info(tria, \"grid-5.eps\");\n}\n\n\n\n// @sect4{grid_6: Demonstrating GridTools::transform, part 2}\n\n// In this second example of transforming points from an original to a new\n// mesh, we will use the mapping $(x,y) \\mapsto (x,\\tanh(2y)/\\tanh(2))$. To\n// make things more interesting, rather than doing so in a single function as\n// in the previous example, we here create an object with an\n// <code>operator()</code> that will be called by GridTools::transform. Of\n// course, this object may in reality be much more complex: the object may\n// have member variables that play a role in computing the new locations of\n// vertices.\nstruct Grid6Func\n{\n    double trans(const double y) const\n      {\n\treturn std::tanh(2*y)/tanh(2);\n      }\n\n    Point<2> operator() (const Point<2> & in) const\n      {\n\treturn Point<2> (in(0),\n\t\t\t trans(in(1)));\n      }\n};\n\n\nvoid grid_6()\n{\n  Triangulation<2> tria;\n  std::vector< unsigned int > repetitions(2);\n  repetitions[0] = repetitions[1] = 40;\n  GridGenerator::subdivided_hyper_rectangle (tria, repetitions,\n                                             Point<2>(0.0,0.0),\n\t\t\t\t\t     Point<2>(1.0,1.0));\n\n  GridTools::transform(Grid6Func(), tria);\n  mesh_info(tria, \"grid-6.eps\");\n}\n\n\n// @sect4{grid_7: Demonstrating distort_random}\n\n// In this last example, we create a mesh and then distort its (interior)\n// vertices by a random perturbation. This is not something you want to do for\n// production computations, but it is a useful tool for testing\n// discretizations and codes to make sure they don't work just by accident\n// because the mesh happens to be uniformly structured and supporting\n// super-convergence properties.\nvoid grid_7()\n{\n  Triangulation<2> tria;\n  std::vector<unsigned int> repetitions(2);\n  repetitions[0] = repetitions[1] = 16;\n  GridGenerator::subdivided_hyper_rectangle (tria, repetitions,\n                                             Point<2>(0.0,0.0),\n\t\t\t\t\t     Point<2>(1.0,1.0));\n\n  GridTools::distort_random (0.3, tria, true);\n  mesh_info(tria, \"grid-7.eps\");\n}\n\n\n// @sect3{The main function}\n\n// Finally, the main function. There isn't much to do here, only to call the\n// subfunctions.\nint main ()\n{\n  grid_1 ();\n  grid_2 ();\n  grid_3 ();\n  grid_4 ();\n  grid_5 ();\n  grid_6 ();\n  grid_7 ();\n}\n", "meta": {"hexsha": "c683340fc48e4c0211fa4111d0fb8450efa7faf2", "size": 12306, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-49/step-49.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-49/step-49.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-49/step-49.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": 35.9824561404, "max_line_length": 120, "alphanum_fraction": 0.694457988, "num_tokens": 3222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.310694383214554, "lm_q2_score": 0.1500288262426238, "lm_q1q2_score": 0.046613113633855494}}
{"text": "#ifndef FVMSCALAR1D_RECONSTRUCTION_HPP\n#define FVMSCALAR1D_RECONSTRUCTION_HPP\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <memory>\n\n#include <ancse/grid.hpp>\n#include <ancse/model.hpp>\n#include <ancse/rate_of_change.hpp>\n#include <ancse/simulation_time.hpp>\n\ninline double sign(double a) { return copysign(1.0, a); }\n\n\nclass PWConstantReconstruction {\n  public:\n    /// Compute the left and right trace at the interface i + 1/2.\n    /** Note: This API is agnostic to the number of cell-averages required\n     *        by the method. Therefore, reconstructions with different stencil\n     *        sizes can implement this API; and this call can be used in parts\n     *        of the code that do not need to know about the details of the\n     *        reconstruction.\n     */\n    inline std::pair<double, double> operator()(const Eigen::VectorXd &u,\n                                                int i) const {\n        return (*this)(u[i], u[i + 1]);\n    }\n\n    /// Compute the left and right trace at the interface.\n    /** Piecewise constant reconstruction of the left and right trace only\n     *  requires the cell-average to the left and right of the interface.\n     *\n     *  Note: Compared to the other overload this reduces the assumption on\n     *        how the cell-averages are stored. This is useful when testing and\n     *        generally makes the function useful in more situations.\n     */\n    inline std::pair<double, double> operator()(double ua, double ub) const {\n        return {ua, ub};\n    }\n};\n\n\n#endif // FVMSCALAR1D_RATE_OF_CHANGE_HPP\n", "meta": {"hexsha": "dc17bdb013da44f364b71aa642df4435965e97ff", "size": 1570, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series1_handout/fvm_scalar_1d/include/ancse/reconstruction.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series1_handout/fvm_scalar_1d/include/ancse/reconstruction.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series1_handout/fvm_scalar_1d/include/ancse/reconstruction.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 34.8888888889, "max_line_length": 79, "alphanum_fraction": 0.6592356688, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.09534945718704857, "lm_q1q2_score": 0.045441611035314515}}
{"text": "#ifndef CCSR_HPP\n#define CCSR_HPP\n\n/*\nThe MIT License\n\nCopyright (c) 2013 Denis Demidov <ddemidov@ksu.ru>\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   ccsr.hpp\n * \\author Denis Demidov <ddemidov@ksu.ru>\n * \\brief  Lossy compression for CSR sparse matrix format.\n *\n * Each row is stored as a pointer to a table of unique matrix rows, where\n * uniqueness is determined approximately.  This may result in significant\n * storage space savings in case matrix has regular structure (e.g. it\n * represents a Poisson problem in a domain with piecewise-constant or slowly\n * changing properties).  The precision loss is possible, but may not be\n * important (e.g.  coefficients come from an experiment with incorporated\n * observation error).\n */\n\n\n#include <vector>\n#include <deque>\n#include <type_traits>\n#include <memory>\n#include <functional>\n#include <numeric>\n#include <cassert>\n\n#include <boost/unordered_set.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n\nnamespace ccsr {\n\nnamespace detail {\n\ntemplate <typename T>\nstruct hash_impl {\n    static inline size_t get(T v) {\n        return std::hash<T>()(v);\n    }\n};\n\ntemplate <>\nstruct hash_impl<double> {\n    static inline size_t get(double v) {\n        static const uint64_t mask = 0xffffffffff000000;\n                                    // eeefffffffffffff;\n        // Zero-out least significant bits and hash as uint64_t:\n        return std::hash<uint64_t>()(*reinterpret_cast<const uint64_t*>(&v) & mask);\n    }\n};\n\ntemplate <>\nstruct hash_impl<float> {\n    static inline size_t get(float v) {\n        static const uint32_t mask = 0xfffffc00;\n                                    // eeffffff;\n        // Zero-out least significant bits and hash as uint64_t:\n        return std::hash<uint32_t>()(*reinterpret_cast<const uint32_t*>(&v) & mask);\n    }\n};\n\n}\n\ntemplate <class T>\ninline size_t hash(const T &v) {\n    return detail::hash_impl<T>::get(v);\n}\n\n/// Lossy compression for CSR sparse matrix format.\n/**\n * Each row is stored as a pointer to a table of unique matrix rows, where\n * uniqueness is determined approximately.  This may result in significant\n * storage space savings in case matrix has regular structure (e.g. it\n * represents a Poisson problem in a domain with piecewise-constant or slowly\n * changing properties).  The precision loss is possible, but may not be\n * important (e.g.  coefficients come from an experiment with incorporated\n * observation error).\n*/\ntemplate <\n    typename val_t = double,\n    typename row_t = size_t,\n    typename col_t = ptrdiff_t,\n    typename idx_t = row_t\n    >\nclass matrix {\n    static_assert(std::is_signed<col_t>::value, \"Column type should be signed!\");\n\n    private:\n        size_t nrows, ncols, nnz;\n        val_t  eps;\n\n        std::vector< idx_t > idx;\n        std::vector< row_t > row;\n        std::vector< col_t > col;\n        std::vector< val_t > val;\n\n        // Returns operand incremented by a given value.\n        struct shift {\n            typedef col_t result_type;\n\n            col_t s;\n\n            shift(col_t s) : s(s) {}\n\n            col_t operator()(col_t v) const {\n                return v + s;\n            }\n        };\n\n        // Extracts and stores unique rows.\n        struct builder_t {\n            std::deque< idx_t > idx;\n            std::deque< row_t > row;\n            std::deque< col_t > col;\n            std::deque< val_t > val;\n\n            // Hashes and compares matrix rows.\n            struct row_hasher {\n                val_t eps;\n\n                row_hasher(val_t eps) : eps(eps) {}\n\n                template <class Range>\n                size_t operator()(const Range &r) const {\n                    using boost::get;\n\n                    auto begin = get<0>(r);\n                    auto end   = get<1>(r);\n\n                    size_t h = hash(end - begin);\n\n                    for(auto i = begin; i != end; ++i)\n                        h ^= hash(get<0>(*i)) ^ hash(get<1>(*i));\n\n                    return h;\n                }\n\n                template <class Range1, class Range2>\n                bool operator()(const Range1 &r1, const Range2 &r2) const {\n                    using boost::get;\n\n                    auto i1 = get<0>(r1);\n                    auto e1 = get<1>(r1);\n                    auto i2 = get<0>(r2);\n                    auto e2 = get<1>(r2);\n\n                    if (e1 - i1 != e2 - i2) return false;\n\n                    for(; i1 != e1; ++i1, ++i2) {\n                        if (get<0>(*i1) != get<0>(*i2))\n                            return false;\n\n                        if (fabs(get<1>(*i1) - get<1>(*i2)) > eps)\n                            return false;\n                    }\n\n                    return true;\n                }\n            } hasher;\n\n            typedef boost::zip_iterator<\n                        boost::tuple<\n                            typename std::deque< col_t >::const_iterator,\n                            typename std::deque< val_t >::const_iterator\n                        >\n                    > row_iterator;\n\n            typedef boost::tuple< row_iterator, row_iterator, size_t > row_range;\n\n            boost::unordered_set<row_range, row_hasher, row_hasher> index;\n\n            builder_t(size_t nrows, val_t eps)\n                : idx(nrows, 0), hasher(eps), index(1979, hasher, hasher)\n            {\n                // Artificial empty row:\n                row.push_back(0);\n                row.push_back(0);\n\n                index.insert(\n                        boost::make_tuple(\n                            boost::make_zip_iterator(\n                                boost::make_tuple(col.begin(), val.begin())\n                                ),\n                            boost::make_zip_iterator(\n                                boost::make_tuple(col.end(), val.end())\n                                ),\n                            index.size()\n                            )\n                        );\n            }\n\n            void insert(col_t row_begin, col_t row_end,\n                    const row_t *r, const col_t *c, const val_t *v)\n            {\n                for(col_t i = row_begin, j = 0; i < row_end; ++i, ++j) {\n                    shift s(-i);\n\n                    auto range = boost::make_tuple(\n                            boost::make_zip_iterator(\n                                boost::make_tuple(\n                                    boost::make_transform_iterator(c + r[j], s),\n                                    v + r[j])\n                                ),\n                            boost::make_zip_iterator(\n                                boost::make_tuple(\n                                    boost::make_transform_iterator(c + r[j+1], s),\n                                    v + r[j+1])\n                                )\n                            );\n\n                    auto pos = index.find(range, hasher, hasher);\n\n                    if (pos == index.end()) {\n                        idx[i] = index.size();\n\n                        size_t start = val.size();\n\n                        for(size_t k = r[j]; k < r[j+1]; ++k) {\n                            col.push_back( c[k] - i );\n                            val.push_back( v[k] );\n                        }\n\n                        index.insert(\n                                boost::make_tuple(\n                                    boost::make_zip_iterator(\n                                        boost::make_tuple(\n                                            col.begin() + start,\n                                            val.begin() + start)\n                                        ),\n                                    boost::make_zip_iterator(\n                                        boost::make_tuple(\n                                            col.end(),\n                                            val.end()\n                                            )\n                                        ),\n                                    index.size()\n                                    )\n                                );\n\n                        row.push_back(val.size());\n                    } else {\n                        idx[i] = boost::get<2>(*pos);\n                    }\n                }\n            }\n        };\n\n        std::unique_ptr<builder_t> builder;\n\n    public:\n        typedef boost::zip_iterator<\n                    boost::tuple<\n                        boost::transform_iterator<\n                            shift, typename std::vector<col_t>::const_iterator\n                        >,\n                        typename std::vector<val_t>::const_iterator\n                    >\n                > const_row_iterator;\n\n        /// Constructor.\n        matrix(size_t nrows, size_t ncols, val_t eps = 1e-5)\n            : nrows(nrows), ncols(ncols), nnz(0), eps(eps),\n              builder(new builder_t(nrows, eps))\n        {\n        }\n\n        /// Store matrix slice.\n        /**\n         * May accept whole matrix, or just a slice of matrix rows.\n         */\n        void insert(col_t row_begin, col_t row_end,\n                const row_t *r, const col_t *c, const val_t *v)\n        {\n            assert(builder);\n\n            builder->insert(row_begin, row_end, r, c, v);\n        }\n\n        /// All rows have been processed; finalize the construction phase.\n        void finish() {\n            assert(builder);\n\n            idx.assign(builder->idx.begin(), builder->idx.end());\n            row.assign(builder->row.begin(), builder->row.end());\n            col.assign(builder->col.begin(), builder->col.end());\n            val.assign(builder->val.begin(), builder->val.end());\n\n            builder.reset();\n\n            nnz = std::accumulate(idx.begin(), idx.end(), static_cast<size_t>(0),\n                    [&](size_t tot, size_t p) {\n                        return tot + row[p + 1] - row[p];\n                    });\n        }\n\n        /// Number of unique rows in the matrix.\n        size_t unique_rows() const {\n            return row.size() - 1;\n        }\n\n        /// Returns boost::zip_iterator to start of columns/values range for a given row.\n        const_row_iterator begin(size_t i) const {\n            assert(!builder && i < nrows);\n\n            return boost::make_zip_iterator(\n                    boost::make_tuple(\n                        boost::make_transform_iterator(\n                            col.begin() + row[idx[i]],\n                            shift(i)\n                            ),\n                        val.begin() + row[idx[i]]\n                        )\n                    );\n        }\n\n        /// Returns boost::zip_iterator to end of columns/values range for a given row.\n        const_row_iterator end(size_t i) const {\n            assert(!builder && i < nrows);\n\n            return boost::make_zip_iterator(\n                    boost::make_tuple(\n                        boost::make_transform_iterator(\n                            col.begin() + row[idx[i] + 1],\n                            shift(i)\n                            ),\n                        val.begin() + row[idx[i] + 1]\n                        )\n                    );\n        }\n\n        /// Number of rows.\n        size_t rows() const {\n            return nrows;\n        }\n\n        /// Number of cols.\n        size_t cols() const {\n            return ncols;\n        }\n\n        /// Number of nonzeros in the matrix.\n        size_t non_zeros() const {\n            assert(!builder);\n\n            return nnz;\n        }\n\n        /// Compression ratio.\n        double compression() const {\n            assert(!builder);\n            return 1.0 *\n                (\n                 sizeof(idx[0]) * idx.size() +\n                 sizeof(row[0]) * row.size() +\n                 sizeof(col[0]) * col.size() +\n                 sizeof(val[0]) * val.size()\n                ) /\n                (\n                    sizeof(row[0]) * (nrows + 1) +\n                    sizeof(col[0]) * nnz        +\n                    sizeof(val[0]) * nnz\n                );\n        }\n\n\n        /// Matrix transpose.\n        friend matrix transp(const matrix &A) {\n            const col_t chunk_size = 4096;\n\n            col_t lw = 0, rw = 0;\n            for(size_t i = 0, n = A.unique_rows(); i < n; ++i) {\n                for(row_t j = A.row[i]; j < A.row[i + 1]; ++j) {\n                    lw = std::max(lw, -A.col[j]);\n                    rw = std::max(rw,  A.col[j]);\n                }\n            }\n\n            matrix T(A.ncols, A.nrows, A.eps);\n\n            std::vector<row_t> row;\n            std::vector<col_t> col;\n            std::vector<val_t> val;\n\n            for(col_t chunk = 0; chunk < A.nrows; chunk += chunk_size) {\n                col_t row_start = std::max(chunk - rw,              static_cast<col_t>(0));\n                col_t row_end   = std::min(chunk + chunk_size + lw, static_cast<col_t>(A.nrows));\n                col_t chunk_end = std::min(chunk + chunk_size,      static_cast<col_t>(A.nrows));\n\n                row.clear();\n                col.clear();\n                val.clear();\n\n                row.resize(chunk_size + 1, 0);\n\n                for(col_t i = row_start; i < row_end; ++i)\n                    for(auto j = A.begin(i), e = A.end(i); j != e; ++j) {\n                        col_t c = boost::get<0>(*j);\n                        if (c >= chunk && c < chunk_end)\n                            ++( row[c - chunk + 1] );\n                    }\n\n                std::partial_sum(row.begin(), row.end(), row.begin());\n\n                col.resize(row.back());\n                val.resize(row.back());\n\n                for(size_t i = row_start; i < row_end; ++i) {\n                    for(auto j = A.begin(i), e = A.end(i); j != e; ++j) {\n                        col_t c = boost::get<0>(*j);\n                        val_t v = boost::get<1>(*j);\n\n                        if (c >= chunk && c < chunk_end) {\n                            row_t head = row[c - chunk]++;\n\n                            col[head] = i;\n                            val[head] = v;\n                        }\n                    }\n                }\n\n                std::rotate(row.begin(), row.end() - 1, row.end());\n                row[0] = 0;\n\n                T.insert(chunk, chunk_end, row.data(), col.data(), val.data());\n            }\n\n            T.finish();\n\n            return T;\n        }\n\n        /// Matrix-matrix product.\n        friend matrix prod(const matrix &A, const matrix &B) {\n            matrix C(A.nrows, B.ncols, std::max(A.eps, B.eps));\n\n            std::vector<col_t> marker(B.ncols, -1);\n\n            row_t row[2] = {0, 0};\n            std::vector<col_t> col;\n            std::vector<val_t> val;\n\n            for(size_t ia = 0; ia < A.nrows; ++ia) {\n                col.clear();\n                val.clear();\n\n                for(auto ja = A.begin(ia), ea = A.end(ia); ja != ea; ++ja) {\n                    col_t ca = boost::get<0>(*ja);\n                    val_t va = boost::get<1>(*ja);\n\n                    for(auto jb = B.begin(ca), eb = B.end(ca); jb != eb; ++jb) {\n                        col_t cb = boost::get<0>(*jb);\n                        val_t vb = boost::get<1>(*jb);\n\n                        if (marker[cb] < 0) {\n                            marker[cb] = col.size();\n                            col.push_back(cb);\n                            val.push_back(va * vb);\n                        } else {\n                            val[marker[cb]] += va * vb;\n                        }\n                    }\n                }\n\n                for(auto c = col.begin(); c != col.end(); ++c)\n                    marker[*c] = -1;\n\n                row[1] = col.size();\n\n                C.insert(ia, ia + 1, row, col.data(), val.data());\n            }\n\n            C.finish();\n            return C;\n        }\n\n};\n\n} // namespace ccsr\n\n#endif\n", "meta": {"hexsha": "e1c56e3bf0e031f1575ce112bd633b01ce06a1c9", "size": 16824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ccsr.hpp", "max_stars_repo_name": "ddemidov/ccsr", "max_stars_repo_head_hexsha": "319a706d78d7f8d9d33eaaded1220298e670f270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-28T18:43:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:43:24.000Z", "max_issues_repo_path": "ccsr.hpp", "max_issues_repo_name": "ddemidov/ccsr", "max_issues_repo_head_hexsha": "319a706d78d7f8d9d33eaaded1220298e670f270", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ccsr.hpp", "max_forks_repo_name": "ddemidov/ccsr", "max_forks_repo_head_hexsha": "319a706d78d7f8d9d33eaaded1220298e670f270", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-05-08T14:07:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T05:28:08.000Z", "avg_line_length": 33.3148514851, "max_line_length": 97, "alphanum_fraction": 0.4478126486, "num_tokens": 3475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.10669060104662922, "lm_q1q2_score": 0.04507727343331233}}
{"text": "#pragma once\n\n#include <stdexcept>\n#include <algorithm>\n#include <iostream>\n#include <complex>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <assert.h>\n#include <memory>\n#include <fstream>\n#include <iomanip>\n#include <numeric>\n#include <complex>\n#include <hdf5.h>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\n//debug\n//#include <chrono>\n//\n//#ifdef IRBASIS_USE_EIGEN3\n//#include <Eigen/Core>\n//#endif\n\nnamespace irbasis {\nnamespace mp = boost::multiprecision;\ntypedef mp::number<mp::cpp_dec_float<30> > mpf;\n\nnamespace internal {\n\n// Simple implementation without meta programming...\ntemplate<typename T, int DIM>\nclass multi_array {\n\n  template<typename T2, int DIM2>\n  friend class multi_array;\n\npublic:\n  multi_array() : owner_(true), p_data_(NULL), num_elements_(0) {\n    for (int i = 0; i < DIM; ++i) {\n      extents_[i] = 0;\n    }\n  }\n\n  multi_array(int N1) : owner_(true), p_data_(new T[N1]), num_elements_(N1) {\n    assert(DIM == 1);\n    extents_[0] = N1;\n  }\n\n  multi_array(int N1, int N2) : owner_(true), p_data_(new T[N1 * N2]), num_elements_(N1 * N2) {\n    assert(DIM == 2);\n    extents_[0] = N1;\n    extents_[1] = N2;\n  }\n\n  multi_array(int N1, int N2, int N3) : owner_(true), p_data_(new T[N1 * N2 * N3]), num_elements_(N1 * N2 * N3) {\n    assert(DIM == 3);\n    extents_[0] = N1;\n    extents_[1] = N2;\n    extents_[2] = N3;\n  }\n\n  multi_array(std::size_t *dims) {\n    resize(dims);\n  }\n\n  multi_array(const multi_array<T, DIM> &other) : p_data_(NULL) {\n    owner_ = true;\n    resize(&other.extents_[0]);\n    std::copy(other.origin(), other.origin() + other.num_elements(), origin());\n  }\n\n  ~multi_array() {\n    if (this->owner_) {\n      delete[] p_data_;\n    }\n  }\n\n  multi_array<T, DIM> &operator=(const multi_array<T, DIM> &other) {\n    if (!this->owner_) {\n      throw std::logic_error(\"Error: assignment to a view is not supported.\");\n    }\n\n    this->owner_ = other.owner_;\n    for (int i = 0; i < DIM; ++i) {\n      this->extents_[i] = other.extents_[i];\n    }\n    this->num_elements_ = other.num_elements_;\n\n    // allocate memoery and copy data\n    if (this->p_data_ != NULL) {\n      delete[] this->p_data_;\n      this->p_data_ = NULL;\n    }\n    this->p_data_ = new T[this->num_elements_];\n\n    for (int i = 0; i < this->num_elements_; ++i) {\n      *(this->p_data_ + i) = *(other.p_data_ + i);\n    }\n\n    return *this;\n  }\n\n  std::size_t extent(int i) const {\n    assert(i >= 0);\n    assert(i < DIM);\n    return extents_[i];\n  }\n\n  const std::size_t* extents() const {\n      return &(extents_[0]);\n  }\n\n  void resize(const std::size_t *const dims) {\n    if (!owner_) {\n      throw std::runtime_error(\"resize is not permitted for a view\");\n    }\n\n    std::size_t tot_size = std::accumulate(dims, dims + DIM, 1, std::multiplies<std::size_t>());\n    delete[] p_data_;\n    p_data_ = new T[tot_size];\n    num_elements_ = tot_size;\n    for (int i = 0; i < DIM; ++i) {\n      extents_[i] = dims[i];\n    }\n  }\n\n  void fill(T value) {\n    if (!owner_) {\n      throw std::runtime_error(\"resize is not permitted for a view\");\n    }\n    for (int i = 0; i < this->num_elements_; ++i) {\n      *(this->p_data_ + i) = value;\n    }\n  }\n\n  multi_array<T, DIM - 1> make_view(std::size_t most_left_index) const {\n    multi_array<T, DIM - 1> view;\n    view.owner_ = false;\n    std::size_t new_size = 1;\n    for (int i = 0; i < DIM - 1; ++i) {\n      view.extents_[i] = this->extents_[i + 1];\n      new_size *= view.extents_[i];\n    }\n    view.num_elements_ = new_size;\n    view.p_data_ = p_data_ + most_left_index * new_size;\n\n    return view;\n  }\n\n  multi_array<T, 2> make_matrix_view(std::size_t size1, std::size_t size2) const {\n    multi_array<T, 2> view;\n    view.owner_ = false;\n    view.extents_[0] = size1;\n    view.extents_[1] = size2;\n    view.num_elements_ = num_elements_;\n    view.p_data_ = p_data_;\n\n    return view;\n  }\n\n  std::size_t num_elements() const {\n    return num_elements_;\n  }\n\n  bool is_view() const {\n    return !owner_;\n  }\n\n  T *origin() const {\n    return p_data_;\n  }\n\n  inline T &operator()(int i) {\n    assert(DIM == 1);\n    int idx = i;\n    assert(idx >= 0 && idx < num_elements());\n    return *(p_data_ + idx);\n  }\n\n  inline const T &operator()(int i) const {\n    assert(DIM == 1);\n    int idx = i;\n    assert(idx >= 0 && idx < num_elements());\n    return *(p_data_ + idx);\n  }\n\n  inline T &operator()(int i, int j) {\n    assert(DIM == 2);\n    int idx = extents_[1] * i + j;\n    assert(idx >= 0 && idx < num_elements());\n    return *(p_data_ + idx);\n  }\n\n  inline const T &operator()(int i, int j) const {\n    assert(DIM == 2);\n    int idx = extents_[1] * i + j;\n    assert(idx >= 0 && idx < num_elements());\n    return *(p_data_ + idx);\n  }\n\n  inline T &operator()(int i, int j, int k) {\n    assert(DIM == 3);\n    int idx = (i * extents_[1] + j) * extents_[2] + k;\n    assert(idx >= 0 && idx < num_elements());\n    return *(p_data_ + idx);\n  }\n\n  inline const T &operator()(int i, int j, int k) const {\n    assert(DIM == 3);\n    int idx = (i * extents_[1] + j) * extents_[2] + k;\n    assert(idx >= 0 && idx < num_elements());\n    return *(p_data_ + idx);\n  }\n\nprivate:\n  bool owner_;\n  T *p_data_;\n  std::size_t num_elements_;\n  std::size_t extents_[DIM];\n};\n\ntemplate<typename T1, typename T2, typename T3>\nvoid multiply(const multi_array<T1, 2> &A, const multi_array<T2, 2> &B, multi_array<T3, 2> &AB) {\n  std::size_t N1 = A.extent(0);\n  std::size_t N2 = A.extent(1);\n  std::size_t N3 = B.extent(1);\n\n  assert(B.extent(0) == N2);\n\n  if (AB.extent(0) != N1 || AB.extent(1) != N3) {\n    std::size_t dims[2];\n    dims[0] = N1;\n    dims[1] = N3;\n    AB.resize(dims);\n  }\n\n  AB.fill(0);\n  for (int i = 0; i < N1; ++i) {\n    for (int k = 0; k < N2; ++k) {\n      for (int j = 0; j < N3; ++j) {\n        AB(i, j) += A(i, k) * B(k, j);\n      }\n    }\n  }\n\n}\n\n// https://www.physics.ohio-state.edu/~wilkins/computing/HDF/hdf5tutorial/examples/C/h5_rdwt.c\n// https://support.hdfgroup.org/ftp/HDF5/current/src/unpacked/examples/h5_read.c\ntemplate<typename T> hid_t get_native_type();\n\ntemplate<>\ninline\nhid_t\nget_native_type<double>() {\n  return H5T_NATIVE_DOUBLE;\n}\n\ntemplate<>\ninline\nhid_t\nget_native_type<int>() {\n  return H5T_NATIVE_INT;\n}\n\ntypedef struct {\n  double re;   /*real part*/\n  double im;   /*imaginary part*/\n} complex_t;\n\ntemplate<>\ninline\nhid_t\nget_native_type<std::complex<double> >() {\n  hid_t complex_id = H5Tcreate(H5T_COMPOUND, sizeof(complex_t));\n  H5Tinsert(complex_id, \"r\", HOFFSET(complex_t, re), H5T_NATIVE_DOUBLE);\n  H5Tinsert(complex_id, \"i\", HOFFSET(complex_t, im), H5T_NATIVE_DOUBLE);\n  return complex_id;\n}\n\n// read a scalar\ntemplate<typename T>\nT hdf5_read_scalar(hid_t &file, const std::string &name) {\n  hid_t dataset = H5Dopen2(file, name.c_str(), H5P_DEFAULT);\n  if (dataset < 0) {\n    throw std::runtime_error(\"Failed to load dataset\" + name);\n  }\n  T data;\n  H5Dread(dataset, get_native_type<T>(), H5S_ALL, H5S_ALL, H5P_DEFAULT, &data);\n  H5Dclose(dataset);\n  return data;\n}\n\n// read array of double\ntemplate<int DIM>\nvoid hdf5_read_double_array(hid_t &file, const std::string &name, std::vector<std::size_t> &extents,\n                            std::vector<double> &data) {\n  hid_t dataset = H5Dopen2(file, name.c_str(), H5P_DEFAULT);\n  if (dataset < 0) {\n    throw std::runtime_error(\"Failed to load dataset\" + name);\n  }\n  hid_t space = H5Dget_space(dataset);\n  std::vector<hsize_t> dims(DIM);\n  int n_dims = H5Sget_simple_extent_dims(space, &dims[0], NULL);\n  assert(n_dims == DIM);\n  std::size_t tot_size = std::accumulate(dims.begin(), dims.end(), 1, std::multiplies<std::size_t>());\n  data.resize(tot_size);\n  extents.resize(DIM);\n  for (int i = 0; i < DIM; ++i) {\n    extents[i] = static_cast<std::size_t>(dims[i]);\n  }\n  H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &data[0]);\n  H5Dclose(dataset);\n}\n\ntemplate<int DIM>\nvoid hdf5_read_mpf_array(hid_t &file, const std::string &name, std::vector<std::size_t> &extents,\n                            std::vector<mpf> &data) {\n  std::vector<double> data_tmp;\n  hdf5_read_double_array<DIM>(file, name, extents, data_tmp);\n  data.resize(data_tmp.size());\n  for (int i = 0; i< data.size(); ++i) {\n    data[i] = data_tmp[i];\n  }\n\n  hdf5_read_double_array<DIM>(file, name+\"_corr\", extents, data_tmp);\n  for (int i = 0; i< data.size(); ++i) {\n    data[i] += data_tmp[i];\n  }\n\n}\n\n// read a multi_array\ntemplate<typename T, int DIM>\nmulti_array<T, DIM> load_multi_array(hid_t &file, const std::string &name) {\n  hid_t dataset = H5Dopen2(file, name.c_str(), H5P_DEFAULT);\n  if (dataset < 0) {\n    throw std::runtime_error(\"Faild to open a dataset.\");\n  }\n  hid_t space = H5Dget_space(dataset);\n  std::vector<hsize_t> dims(DIM);\n  int n_dims = H5Sget_simple_extent_dims(space, &dims[0], NULL);\n  assert(n_dims == DIM);\n  std::size_t\n      tot_size = static_cast<std::size_t>(std::accumulate(dims.begin(), dims.end(), 1, std::multiplies<std::size_t>()));\n  std::vector<std::size_t> extents(DIM);\n  for (int i = 0; i < DIM; ++i) {\n    extents[i] = static_cast<std::size_t>(dims[i]);\n  }\n  multi_array<T, DIM> a;\n  a.resize(&extents[0]);\n  H5Dread(dataset, get_native_type<T>(), H5S_ALL, H5S_ALL, H5P_DEFAULT, a.origin());\n  std::vector<T> data(tot_size);\n  H5Dread(dataset, get_native_type<T>(), H5S_ALL, H5S_ALL, H5P_DEFAULT, &data[0]);\n  H5Dclose(dataset);\n  return a;\n}\n\ntemplate<int DIM>\nmulti_array<mpf,DIM> load_mpf_multi_array(hid_t &file, const std::string &name) {\n  multi_array<double,DIM> data = load_multi_array<double,DIM>(file, name);\n  multi_array<double,DIM> data_corr = load_multi_array<double,DIM>(file, name + \"_corr\");\n\n  multi_array<mpf,DIM> result;\n  result.resize(data.extents());\n\n  for (int i=0; i<result.num_elements(); ++i) {\n      *(result.origin()+i) = *(data.origin()+i);\n      *(result.origin()+i) += *(data_corr.origin()+i);\n  }\n  return result;\n}\n\ninline\nstd::size_t find_section(const multi_array<mpf, 1> &section_edges, double x) {\n  std::size_t idx = std::upper_bound(\n      section_edges.origin(),\n      section_edges.origin() + section_edges.num_elements(),\n      x) - section_edges.origin() - 1;\n\n  return std::min(idx, section_edges.num_elements() - 2);\n}\n\ninline\nvoid compute_legendre(double x, std::vector<double> &val) {\n  for (int l = 0; l < val.size(); l++) {\n    if (l == 0) {\n      val[l] = 1;\n    } else if (l == 1) {\n      val[l] = x;\n    } else {\n      val[l] = ((2 * l - 1) * x * val[l - 1] - (l - 1) * val[l - 2]) / l;\n    }\n  }\n}\n\n\ninline\nint even_odd_sign(const int l) {\n  return (l % 2 == 0 ? 1 : -1);\n}\n\ninline\nmulti_array<std::complex<double>, 2>\ncompute_unl_tail(std::vector<double> &w_vec,\n                 const std::string &statistics,\n                 const multi_array<double, 2> &derive_x1,\n                 const int n) {\n  // n : target number to calculate\n  int sign = statistics == \"B\" ? 1 : -1;\n  std::size_t n_iw = w_vec.size();\n  std::size_t Nl = derive_x1.extent(0);\n  std::size_t num_deriv = derive_x1.extent(1);\n  multi_array<std::complex<double>, 2> result(n_iw, Nl);\n  result.fill(std::complex<double>(0.0, 0.0));\n  if (n > 0)\n    num_deriv -= n;\n  multi_array<std::complex<double>, 2> coeffs_nm(n_iw, num_deriv);\n  coeffs_nm.fill(std::complex<double>(0.0, 0.0));\n\n  //coeffs_nm\n  for (int i_iw = 0; i_iw < n_iw; i_iw++) {\n    if (statistics == \"B\" && w_vec[i_iw] == 0) {\n      continue;\n    }\n    std::complex<double> fact = std::complex<double>(0.0, 1.0 / w_vec[i_iw]);\n    coeffs_nm(i_iw, 0) = fact;\n    for (int m = 1; m < num_deriv; m++) {\n      coeffs_nm(i_iw, m) = fact * coeffs_nm(i_iw, m - 1);\n    }\n  }\n\n  //coeffs_lm ()\n  multi_array<std::complex<double>, 2> coeffs_lm(Nl, num_deriv);\n  coeffs_lm.fill(std::complex<double>(0.0, 0.0));\n  for (int l = 0; l < Nl; l++) {\n    for (int m = 0; m < num_deriv; m++) {\n      coeffs_lm(l, m) = (1.0 - sign * even_odd_sign(l + m)) * derive_x1(l, m);\n    }\n  }\n\n  for (int i = 0; i < n_iw; i++) {\n    for (int k = 0; k < Nl; k++) {\n      for (int j = 0; j < num_deriv; j++) {\n        result(i, k) += coeffs_nm(i, j) * coeffs_lm(k, j);\n      }\n      result(i, k) *= -sign / sqrt(2.0);\n    }\n  }\n  return result;\n}\n\nstruct func {\n  void load_from_h5(hid_t file, const std::string &prefix) {\n    data = internal::load_multi_array<double, 3>(file, prefix + std::string(\"/data\"));\n    np = internal::hdf5_read_scalar<int>(file, prefix + std::string(\"/np\"));\n    ns = internal::hdf5_read_scalar<int>(file, prefix + std::string(\"/ns\"));\n    nl = data.extent(0);\n    section_edges = internal::load_mpf_multi_array<1>(file, prefix + std::string(\"/section_edges\"));\n\n    std::size_t extents[3];\n    extents[0] = ns;\n    extents[1] = np;\n    extents[2] = nl;\n    data_for_vec.resize(&extents[0]);\n    for (int l = 0; l < nl; ++l) {\n      for (int s = 0; s < ns; ++s) {\n        for (int p = 0; p < np; ++p) {\n          data_for_vec(s, p, l) = data(l, s, p);\n        }\n      }\n    }\n  }\n  multi_array<mpf, 1> section_edges;\n  multi_array<double, 3> data; //(nl, ns, np)\n  multi_array<double, 3> data_for_vec; //(ns, np, nl). Just a copy of data.\n  int np;\n  int ns;\n  int nl;\n};\n\nstruct ref {\n  multi_array<double, 2> data;\n  multi_array<double, 1> max;\n};\n\n}\n\nclass basis {\npublic:\n  basis() {}\n\n  basis(\n      const std::string &file_name,\n      const std::string &prefix = \"\"\n  ) throw(std::runtime_error) {\n    hid_t file = H5Fopen(file_name.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n\n    if (file < 0) {\n      throw std::runtime_error(\"Failed to open \" + file_name + \"!\");\n    }\n\n    //read info\n    Lambda_ = internal::hdf5_read_scalar<double>(file, prefix + std::string(\"/info/Lambda\"));\n    dim_ = internal::hdf5_read_scalar<int>(file, prefix + std::string(\"/info/dim\"));\n    statistics_ = internal::hdf5_read_scalar<int>(file, prefix + std::string(\"/info/statistics\")) == 0 ? \"B\" : \"F\";\n\n    //read sl\n    sl_ = internal::load_multi_array<double, 1>(file, prefix + std::string(\"/sl\"));\n\n    //read ulx\n    ulx_.load_from_h5(file, prefix + \"/ulx\");\n\n    //read ref_ulx\n    ref_ulx_.data = internal::load_multi_array<double, 2>(file, prefix + std::string(\"/ulx/ref/data\"));\n    ref_ulx_.max = internal::load_multi_array<double, 1>(file, prefix + std::string(\"/ulx/ref/max\"));\n\n    //read vly\n    vly_.load_from_h5(file, prefix + \"/vly\");\n\n    //read ref_vly\n    ref_vly_.data = internal::load_multi_array<double, 2>(file, prefix + std::string(\"/vly/ref/data\"));\n    ref_vly_.max = internal::load_multi_array<double, 1>(file, prefix + std::string(\"/vly/ref/max\"));\n\n    H5Fclose(file);\n\n    std::size_t np = ulx_.np;\n    {\n      std::vector<double> coeffs(np);\n      for (int p=0; p<np; ++p) {\n        //Conversion between \\tilde{P}_l and P_l\n        coeffs[p] = std::sqrt(p + 0.5);\n      }\n\n      std::size_t dims[2] = {np, np};\n      deriv_mat_.resize(dims);\n      deriv_mat_.fill(0.0);\n      for (int l=0; l<np; ++l) {\n        for (int m=l-1; m>=0; m-=2) {\n          deriv_mat_(m, l) = (1/coeffs[m]) * (2*m + 1) * coeffs[l];\n        }\n      }\n    }\n\n    norm_coeff_.resize(np);\n    for (int p=0; p<np; ++p) {\n      norm_coeff_[p] = std::sqrt(p + 0.5);\n    }\n\n  }\n\n  /**\n    * Return number of basis functions\n    * @return  number of basis functions\n    */\n  int dim() const { return dim_; }\n\n  /**\n    * Return Lambda\n    * @return  Lambda\n    */\n  double Lambda() const { return Lambda_; }\n\n  /**\n    * Return statistics\n    * @return  string representing statistics \"F\" or \"B\"\n    */\n  std::string statistics() const { return statistics_; }\n\n\n  double sl(int l) const throw(std::runtime_error) {\n    assert(l >= 0 && l < dim());\n    return sl_(l);\n  }\n\n  double ulx(int l, double x) const throw(std::runtime_error) {\n    using namespace internal;\n\n    if (std::abs(x) > 1) {\n        throw std::runtime_error(\"x must be in [-1,1]!\");\n    }\n\n    if (x >= 0) {\n      return eval(x, ulx_.data.make_view(l), ulx_.section_edges);\n    } else {\n      return eval(-x, ulx_.data.make_view(l), ulx_.section_edges) * even_odd_sign(l);\n    }\n  }\n\n  std::vector<std::vector<double> > check_ulx() const {\n    double ulx_max = ref_ulx_.max(2);\n    std::vector<std::vector<double> > ref_data(ref_ulx_.data.extent(0));\n    int count = 0;\n    for (int i = 0; i < ref_ulx_.data.extent(0); i++) {\n      if (ref_ulx_.data(i, 2) == 0) {\n        ref_data[i].push_back(ref_ulx_.data(i, 0));\n        ref_data[i].push_back(ref_ulx_.data(i, 1));\n        ref_data[i].push_back(\n            fabs(ulx(ref_ulx_.data(i, 0) - 1, ref_ulx_.data(i, 1)) - ref_ulx_.data(i, 3)) / ulx_max);\n        count++;\n      }\n    }\n    ref_data.resize(count);\n    return ref_data;\n  }\n\n  std::vector<std::vector<double> > check_vly() const {\n    double vly_max = ref_vly_.max(2);\n    std::vector<std::vector<double> > ref_data(ref_vly_.data.extent(0));\n    int count = 0;\n    for (int i = 0; i < ref_vly_.data.extent(0); i++) {\n      if (ref_vly_.data(i, 2) == 0) {\n        ref_data[i].push_back(ref_vly_.data(i, 0));\n        ref_data[i].push_back(ref_vly_.data(i, 1));\n        ref_data[i].push_back(\n            fabs(vly(ref_vly_.data(i, 0) - 1, ref_vly_.data(i, 1)) - ref_vly_.data(i, 3)) / vly_max);\n        count++;\n      }\n    }\n    ref_data.resize(count);\n    return ref_data;\n  }\n\n  double d_ulx(int l, double x, std::size_t order) const throw(std::runtime_error) {\n    using namespace internal;\n\n    if (std::abs(x) > 1) {\n        throw std::runtime_error(\"x must be in [-1,1]!\");\n    }\n\n    if (x >= 0) {\n      return eval_derivative(x, order, ulx_.data.make_view(l), ulx_.section_edges);\n    } else {\n      return eval_derivative(-x, order, ulx_.data.make_view(l), ulx_.section_edges) * even_odd_sign(l + order);\n    }\n  }\n\n  double vly(int l, double y) const throw(std::runtime_error) {\n    using namespace internal;\n\n    if (std::abs(y) > 1) {\n        throw std::runtime_error(\"y must be in [-1,1]!\");\n    }\n    if (y >= 0) {\n      return eval(y, vly_.data.make_view(l), vly_.section_edges);\n    } else {\n      return eval(-y, vly_.data.make_view(l), vly_.section_edges) * even_odd_sign(l);\n    }\n  }\n\n  double d_vly(int l, double y, std::size_t order) const throw(std::runtime_error) {\n    using namespace internal;\n\n    if (std::abs(y) > 1) {\n        throw std::runtime_error(\"y must be in [-1,1]!\");\n    }\n    if (y >= 0) {\n      return eval_derivative(y, order, vly_.data.make_view(l), vly_.section_edges);\n    } else {\n      return eval_derivative(-y, order, vly_.data.make_view(l), vly_.section_edges) * even_odd_sign(l + order);\n    }\n  }\n\n  double get_ref_ulx(std::size_t order) const {\n    double ref_data;\n    for (int i = 0; i < ref_ulx_.data.extent(0); i++) {\n      if (ref_ulx_.data(i, 2) == order) {\n        ref_data = ref_ulx_.data(i, 3);\n      }\n    }\n    return ref_data;\n  }\n\n  int num_sections_x() const {\n    return ulx_.data.extent(1);\n  }\n\n  double section_edge_x(std::size_t index) const {\n    assert(index >= 0 && index <= num_sections_x());\n    return ulx_.section_edges(index).convert_to<double>();\n  }\n\n  int num_sections_y() const {\n    return vly_.data.extent(1);\n  }\n\n  std::vector<std::vector<std::complex<double> > > compute_unl(long long n) const {\n      std::vector<long long> n_vec;\n      n_vec.push_back(n);\n      return compute_unl(n_vec);\n  }\n\n  std::vector<std::vector<std::complex<double> > > compute_unl(const std::vector<long long> &n) const {\n    using namespace internal;\n\n    typedef std::complex<double> dcomplex;\n    typedef std::complex<mpf> mcomplex; // may be illegal to instantiate std::complex with mpf?\n\n    mpf mpi = boost::math::constants::pi<mpf>();\n\n    int num_n = n.size();\n\n    std::vector<mpf> o_vec(n.size());\n    if (this->statistics_ == \"F\") {\n      for (int i = 0; i < num_n; i++) {\n        o_vec[i] = (mpf(2) * n[i] + 1);\n      }\n    } else {\n      for (int i = 0; i < num_n; i++) {\n        o_vec[i] = (mpf(2) * n[i]);\n      }\n    }\n\n    //w_vec = 0.5 * pi * o_vec\n    std::vector<mpf> w_vec(o_vec);\n    std::transform(w_vec.begin(), w_vec.end(), w_vec.begin(), std::bind1st(std::multiplies<mpf>(), mpi/2));\n    std::vector<double> w_vec_f(num_n);\n    for (int i=0; i<num_n; ++i) {\n      w_vec_f[i] = w_vec[i].convert_to<double>();\n    }\n\n    std::size_t num_deriv = this->ulx_.data.extent(2);\n\n    //Compute tail\n    std::vector<std::vector<int> > replaced_with_tail(num_n, std::vector<int>(this->dim_, 0));\n    multi_array<double, 2> deriv_x1(this->dim_, num_deriv);\n    deriv_x1.fill(0.0);\n    std::vector<double> d_ulx_result;\n    for (int l = 0; l < dim_; ++l) {\n      for (int p = 0; p < num_deriv; ++p) {\n        deriv_x1(l, p) = d_ulx(l, 1.0, p);\n      }\n    }\n\n    multi_array<std::complex<double>, 2> unl_tail = compute_unl_tail(w_vec_f, statistics_, deriv_x1, -1);\n    multi_array<std::complex<double>, 2> unl_tail_without_last_two = compute_unl_tail(w_vec_f, statistics_, deriv_x1, 2);\n\n    for (int i = 0; i < num_n; i++) {\n      if (statistics_ == \"B\" && n[i] == 0)\n        continue;\n      for (int l = 0; l < dim_; ++l) {\n        if (std::abs((unl_tail(i, l) - unl_tail_without_last_two(i, l)) / unl_tail(i, l)) < 1e-10) {\n          replaced_with_tail[i][l] = 1;\n        }\n      }\n    }\n\n    multi_array<std::complex<mpf>,2> tilde_unl = compute_tilde_unl_fast(w_vec);\n\n    std::vector<std::vector<std::complex<double> > > result_vec(num_n, std::vector<std::complex<double> >(dim_, 0));\n    int sign_shift = statistics_ == \"F\" ? 1 : 0;\n    for (int l = 0; l < dim_; ++l) {\n      if ((l + sign_shift)%2 == 1) {\n        for (int i=0; i<num_n; ++i) {\n          result_vec[i][l] = std::complex<double>(\n              0, 2*tilde_unl(i, l).imag().convert_to<double>()\n              );\n        }\n      } else {\n        for (int i=0; i<num_n; ++i) {\n          result_vec[i][l] = 2 * tilde_unl(i, l).real().convert_to<double>();\n        }\n      }\n    }\n\n    //Overwrite by tail\n    for (int i = 0; i < num_n; i++) {\n      for (int l = 0; l < dim_; l++) {\n        if (replaced_with_tail[i][l] == 1) {\n          result_vec[i][l] = unl_tail(i, l);\n        }\n      }\n    }\n\n    return result_vec;\n  }\n\n  double section_edge_y(std::size_t index) const {\n    assert(index >= 0 && index <= num_sections_y());\n    return vly_.section_edges(index).convert_to<double>();\n  }\n\n\nprotected:\n  double Lambda_;\n  int dim_;\n  std::string statistics_;\n  internal::multi_array<double, 1> sl_;\n  internal::func ulx_;\n  internal::func vly_;\n  internal::ref ref_ulx_;\n  internal::ref ref_vly_;\n  internal::multi_array<double, 2> deriv_mat_;\n  std::vector<double> norm_coeff_;\n\nprivate:\n  // Evaluate the value of function at given x\n  double eval(double x, const internal::multi_array<double, 2> &data, const internal::multi_array<mpf, 1> &section_edges) const {\n    std::size_t section_idx = find_section(section_edges, x);\n    return eval_impl(x, section_edges(section_idx), section_edges(section_idx+1), data.make_view(section_idx));\n  };\n\n  double eval_impl(double x, mpf x_s, mpf x_sp, const internal::multi_array<double, 1> &coeffs) const {\n    mpf dx = x_sp - x_s;\n    mpf tilde_x = (2*x - x_sp - x_s)/dx;\n\n    std::vector<double> leg_vals(coeffs.extent(0));\n    internal::compute_legendre(tilde_x.convert_to<double>(), leg_vals);\n    double eval_result = 0.0;\n    for (int p=0; p<leg_vals.size(); ++p) {\n      eval_result += leg_vals[p] * norm_coeff_[p] * coeffs(p);\n    }\n    return eval_result * std::sqrt(2/dx.convert_to<double>());\n  }\n\n  inline\n  internal::multi_array<double,1>\n  differentiate_coeff(const internal::multi_array<double, 1> &coeffs, std::size_t order) const {\n    const std::size_t np = coeffs.num_elements();\n\n    internal::multi_array<double,2> tmp2(np, 1);\n    internal::multi_array<double,2> tmp(np, 1);\n    for (int i=0; i<np; ++i) {\n      tmp2(i, 0) = coeffs(i);\n    }\n    for (int i=0; i<order; ++i) {\n      internal::multiply(deriv_mat_, tmp2, tmp);\n      std::swap(tmp2, tmp);\n    }\n    internal::multi_array<double,1> coeffs_deriv(np);\n    for (int p=0; p<np; ++p) {\n      coeffs_deriv(p) = tmp2(p, 0);\n    }\n    return coeffs_deriv;\n  }\n\n  double eval_derivative(double x,\n                                std::size_t order,\n                                const internal::multi_array<double, 2> &data,\n                                const internal::multi_array<mpf, 1> &section_edges,\n                                int section = -1) const {\n    using namespace internal;\n    std::size_t section_idx = section >= 0 ? section : find_section(section_edges, x);\n\n    multi_array<double, 1> coeffs_deriv = differentiate_coeff(data.make_view(section_idx), order);\n    double dx = static_cast<mpf>(section_edges(section_idx+1) - section_edges(section_idx)).convert_to<double>();\n    return eval_impl(x, section_edges(section_idx), section_edges(section_idx+1), coeffs_deriv) * std::pow(2/dx, order);\n  }\n\n  internal::multi_array<std::complex<mpf>,2> compute_tilde_unl_fast(const std::vector<mpf>& w_vec) const {\n    const int num_n = w_vec.size();\n    const int np = ulx_.np;\n\n    typedef std::complex<mpf> mcomplex;\n    typedef std::complex<double> dcomplex;\n\n    internal::multi_array<mcomplex,2> tilde_unl(num_n, dim_);\n    tilde_unl.fill(mcomplex(0,0));\n\n    internal::multi_array<double,2> tmp_lp(dim_, np);\n    internal::multi_array<dcomplex,2> tmp_np(num_n, np);\n    std::vector<dcomplex> exp_n(num_n);\n\n    for (int s=0; s<num_sections_x(); ++s) {\n      const mpf xs = ulx_.section_edges(s);\n      const mpf xsp = ulx_.section_edges(s+1);\n      const mpf dx = xsp - xs;\n      const mpf xmid = (xsp + xs)/2;\n\n      // tmp_lp: lp\n      {\n        // Normalization factor\n        double coeff_tmp = std::sqrt(dx.convert_to<double>())/2;\n        for (int l=0; l<dim_; ++l) {\n          for (int p=0; p<np; ++p) {\n            tmp_lp(l, p) = ulx_.data(l, s, p) * coeff_tmp * norm_coeff_[p];\n          }\n        }\n      }\n\n      // tmp_np: np\n      for (int n=0; n<num_n; ++n) {\n        mpf phase = w_vec[n] * (xmid+1);\n        mpf c = boost::multiprecision::cos(phase);\n        mpf s = boost::multiprecision::sin(phase);\n        exp_n[n] = std::complex<double>(c.convert_to<double>(), s.convert_to<double>());\n      }\n      for (int n=0; n<num_n; ++n) {\n        double w_tmp = static_cast<mpf>(dx * w_vec[n]/2).convert_to<double>();\n        dcomplex phase_p(1, 0);\n        for (int p = 0; p < np; ++p) {\n          if (w_tmp >= 0) {\n              tmp_np(n, p) = 2.0 * phase_p * boost::math::sph_bessel(p, w_tmp) * exp_n[n];\n          } else {\n              tmp_np(n, p) = std::conj(2.0 * phase_p * boost::math::sph_bessel(p, -w_tmp)) * exp_n[n];\n          }\n          phase_p *= dcomplex(0, 1);\n        }\n      }\n\n      for (int n=0; n<num_n; ++n) {\n        for (int l=0; l<dim_; ++l) {\n          dcomplex tmp_nl(0.0);\n          for (int p=0; p<np; ++p) {\n             tmp_nl += tmp_np(n, p) * tmp_lp(l, p);\n          }\n          tilde_unl(n, l) += tmp_nl;\n        }\n      }\n\n    }\n    return tilde_unl;\n  }\n};\n\ninline\nbasis load(const std::string &statistics, double Lambda, const std::string &file_name = \"./irbasis.h5\") {\n  std::stringstream ss;\n  ss << std::fixed;\n  ss << std::setprecision(1);\n  ss << Lambda;\n  std::string prefix;\n  if (statistics == \"F\") {\n    prefix = \"basis_f-mp-Lambda\" + ss.str() + \"_np8\";\n  } else if (statistics == \"B\") {\n    prefix = \"basis_b-mp-Lambda\" + ss.str() + \"_np8\";\n  } else {\n    throw std::runtime_error(\"Unsupported statistics \" + statistics);\n  }\n\n  return basis(file_name, prefix);\n}\n};\n\n\n", "meta": {"hexsha": "ada18cd1c1d6e2d5524918647437b673ae64acc5", "size": 27347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/irbasis.hpp", "max_stars_repo_name": "SpM-lab/irbasis", "max_stars_repo_head_hexsha": "5beb5cbe3c0ba0fb42c32e262f04d1f3359d6045", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T15:07:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:46:55.000Z", "max_issues_repo_path": "c++/irbasis.hpp", "max_issues_repo_name": "SpM-lab/irbasis", "max_issues_repo_head_hexsha": "5beb5cbe3c0ba0fb42c32e262f04d1f3359d6045", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-09-19T07:12:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-14T11:54:03.000Z", "max_forks_repo_path": "c++/irbasis.hpp", "max_forks_repo_name": "SpM-lab/irbasis", "max_forks_repo_head_hexsha": "5beb5cbe3c0ba0fb42c32e262f04d1f3359d6045", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-01-28T19:51:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T12:57:14.000Z", "avg_line_length": 29.0616365569, "max_line_length": 129, "alphanum_fraction": 0.5965553808, "num_tokens": 8607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.0913821067789649, "lm_q1q2_score": 0.04462036536731949}}
{"text": "#include \"naiveexpectedvaluecalculator.hpp\"\r\n\r\n#undef NDEBUG\r\n#include <algorithm>\r\n#include <assert.h>\r\n#include <fstream>\r\n#include <numeric>\r\n\r\n#include <boost/algorithm/string/classification.hpp>\r\n#include <boost/algorithm/string/split.hpp>\r\n#include <boost/dll.hpp>\r\n\r\n#include \"mahjong/requiredtileselector.hpp\"\r\n#include \"mahjong/syanten.hpp\"\r\n#include \"mahjong/unnecessarytileselector.hpp\"\r\n#include \"mahjong/utils.hpp\"\r\n\r\nnamespace mahjong\r\n{\r\n\r\nNaiveExpectedValueCalculator::NaiveExpectedValueCalculator()\r\n    : calc_syanten_down_(false)\r\n    , calc_tegawari_(false)\r\n    , calc_double_reach_(false)\r\n    , calc_ippatu_(false)\r\n    , calc_haitei_(false)\r\n    , calc_uradora_(false)\r\n    , calc_akatile_tumo_(false)\r\n    , maximize_win_prob_(false)\r\n    , discard_cache_(5) // 0(聴牌) ~ 4(4向聴)\r\n    , draw_cache_(5)    // 0(聴牌) ~ 4(4向聴)\r\n{\r\n    make_uradora_table();\r\n}\r\n\r\n/**\r\n * @brief 期待値を計算する。\r\n *\r\n * @param hand 手牌\r\n * @param score_calculator 点数計算機\r\n * @param dora_indicators ドラ表示牌の一覧\r\n * @param syanten_type 向聴数の種類\r\n * @param flag フラグ\r\n * @return 各打牌の情報\r\n */\r\nstd::tuple<bool, std::vector<Candidate>>\r\nNaiveExpectedValueCalculator::calc(const Hand &hand, const ScoreCalculator &score_calculator,\r\n                                   const std::vector<int> &dora_indicators, int syanten_type,\r\n                                   int turn, int flag)\r\n{\r\n    std::vector<Candidate> candidates;\r\n\r\n    score_calculator_ = score_calculator;\r\n    syanten_type_ = syanten_type;\r\n    dora_indicators_ = dora_indicators;\r\n\r\n    calc_syanten_down_ = flag & CalcSyantenDown;\r\n    calc_tegawari_ = flag & CalcTegawari;\r\n    calc_double_reach_ = flag & CalcDoubleReach;\r\n    calc_ippatu_ = flag & CalcIppatu;\r\n    calc_haitei_ = flag & CalcHaiteitumo;\r\n    calc_uradora_ = flag & CalcUradora;\r\n    calc_akatile_tumo_ = flag & CalcAkaTileTumo;\r\n    maximize_win_prob_ = flag & MaximaizeWinProb;\r\n\r\n    // 手牌の枚数を数える。\r\n    int n_tiles = hand.num_tiles() + int(hand.melds.size()) * 3;\r\n    if (n_tiles != 14)\r\n        return {false, {}}; // 手牌が14枚ではない場合\r\n\r\n    // 現在の向聴数を計算する。\r\n    auto [_, syanten] = SyantenCalculator::calc(hand, syanten_type_);\r\n    if (syanten == -1)\r\n        return {false, {}}; // 手牌が和了形の場合\r\n\r\n    // 各牌の残り枚数を数える。\r\n    std::vector<int> counts = count_left_tiles(hand, dora_indicators_);\r\n    sum_left_tiles_ = std::accumulate(counts.begin(), counts.begin() + 34, 0);\r\n\r\n    // 自摸確率のテーブルを作成する。\r\n    create_prob_table(sum_left_tiles_);\r\n\r\n    if (syanten > 3) // 3向聴以下は聴牌確率、和了確率、期待値を計算する。\r\n        candidates = analyze(syanten, hand);\r\n    else // 4向聴以上は受入枚数のみ計算する。\r\n        candidates = analyze(0, syanten, hand, turn);\r\n\r\n    // キャッシュをクリアする。\r\n    clear_cache();\r\n\r\n    return {true, candidates};\r\n}\r\n\r\n/**\r\n * @brief 有効牌の一覧を取得する。\r\n *\r\n * @param[in] hand 手牌\r\n * @param[in] syanten_type 向聴数の種類\r\n * @param[in] counts 各牌の残り枚数\r\n * @return 有効牌の一覧\r\n */\r\nstd::vector<std::tuple<int, int>>\r\nNaiveExpectedValueCalculator::get_required_tiles(const Hand &hand, int syanten_type,\r\n                                                 const std::vector<int> &counts)\r\n{\r\n    std::vector<std::tuple<int, int>> required_tiles;\r\n\r\n    // 有効牌の一覧を取得する。\r\n    std::vector<int> tiles = RequiredTileSelector::select(hand, syanten_type);\r\n\r\n    for (auto tile : tiles)\r\n        required_tiles.emplace_back(tile, counts[tile]);\r\n\r\n    return required_tiles;\r\n}\r\n\r\n/**\r\n * @brief 各牌の残り枚数を数える。\r\n *\r\n * @param[in] hand 手牌\r\n * @param[in] dora_indicators ドラ表示牌の一覧\r\n * @return 各牌の残り枚数\r\n */\r\nstd::vector<int>\r\nNaiveExpectedValueCalculator::count_left_tiles(const Hand &hand,\r\n                                               const std::vector<int> &dora_indicators)\r\n{\r\n    std::vector<int> counts(37, 4);\r\n    counts[Tile::AkaManzu5] = counts[Tile::AkaPinzu5] = counts[Tile::AkaSozu5] = 1;\r\n\r\n    // 手牌を除く。\r\n    for (int i = 0; i < 34; ++i)\r\n        counts[i] -= hand.num_tiles(i);\r\n    counts[Tile::AkaManzu5] -= hand.aka_manzu5;\r\n    counts[Tile::AkaPinzu5] -= hand.aka_pinzu5;\r\n    counts[Tile::AkaSozu5] -= hand.aka_sozu5;\r\n\r\n    // 副露ブロックを除く。\r\n    for (const auto &block : hand.melds) {\r\n        for (auto tile : block.tiles) {\r\n            counts[aka2normal(tile)]--;\r\n            counts[Tile::AkaManzu5] -= tile == Tile::AkaManzu5;\r\n            counts[Tile::AkaPinzu5] -= tile == Tile::AkaPinzu5;\r\n            counts[Tile::AkaSozu5] -= tile == Tile::AkaSozu5;\r\n        }\r\n    }\r\n\r\n    // ドラ表示牌を除く。\r\n    for (auto tile : dora_indicators) {\r\n        counts[aka2normal(tile)]--;\r\n        counts[Tile::AkaManzu5] -= tile == Tile::AkaManzu5;\r\n        counts[Tile::AkaPinzu5] -= tile == Tile::AkaPinzu5;\r\n        counts[Tile::AkaSozu5] -= tile == Tile::AkaSozu5;\r\n    }\r\n\r\n    return counts;\r\n}\r\n\r\n/**\r\n * @brief 裏ドラ確率のテーブルを初期化する。\r\n *\r\n * @return 初期化に成功した場合は true、そうでない場合は false を返す。\r\n */\r\nbool NaiveExpectedValueCalculator::make_uradora_table()\r\n{\r\n    if (!uradora_prob_table_.empty())\r\n        return true;\r\n\r\n    uradora_prob_table_.resize(6);\r\n\r\n    boost::filesystem::path path = boost::dll::this_line_location().parent_path() / \"uradora.txt\";\r\n    std::ifstream ifs(path.string());\r\n\r\n    std::string line;\r\n    int i = 0;\r\n    while (std::getline(ifs, line)) {\r\n        std::vector<std::string> tokens;\r\n        boost::split(tokens, line, boost::is_any_of(\" \"));\r\n\r\n        for (auto token : tokens)\r\n            uradora_prob_table_[i].push_back(std::stod(token));\r\n        i++;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n/**\r\n * @brief 自摸確率のテーブルを初期化する。\r\n *\r\n * @param[in] n_left_tiles 1巡目時点の残り枚数の合計\r\n */\r\nvoid NaiveExpectedValueCalculator::create_prob_table(int n_left_tiles)\r\n{\r\n    // 有効牌の枚数ごとに、この巡目で有効牌を引ける確率のテーブルを作成する\r\n    // tumo_prob_table_[i][j] = 有効牌の枚数が i 枚の場合に j 巡目に有効牌が引ける確率\r\n    tumo_prob_table_.resize(5, std::vector<double>(17));\r\n    for (int i = 0; i < 5; ++i) {\r\n        for (int j = 0; j < 17; ++j)\r\n            tumo_prob_table_[i][j] = double(i) / double(n_left_tiles - j);\r\n    }\r\n\r\n    // 有効牌の合計枚数ごとに、これまでの巡目で有効牌が引けなかった確率のテーブルを作成する\r\n    // not_tumo_prob_table_[i][j] = 有効牌の合計枚数が i 枚の場合に j - 1 巡目までに有効牌が引けなかった確率\r\n    not_tumo_prob_table_.resize(n_left_tiles, std::vector<double>(17));\r\n    for (int i = 0; i < n_left_tiles; ++i) {\r\n        not_tumo_prob_table_[i][0] = 1;\r\n        // n_left_tiles - i - j > 0 は残りはすべて有効牌の場合を考慮\r\n        for (int j = 0; j < 16 && n_left_tiles - i - j > 0; ++j) {\r\n            not_tumo_prob_table_[i][j + 1] = not_tumo_prob_table_[i][j] *\r\n                                             double(n_left_tiles - i - j) /\r\n                                             double(n_left_tiles - j);\r\n        }\r\n    }\r\n}\r\n\r\n/**\r\n * @brief キャッシュをクリアする。\r\n */\r\nvoid NaiveExpectedValueCalculator::clear_cache()\r\n{\r\n    // デバッグ用\r\n    // for (size_t i = 0; i < 5; ++i)\r\n    //     spdlog::info(\"向聴数{} 打牌: {}, 自摸: {}\", i, discard_cache_[i].size(),\r\n    //                  draw_cache_[i].size());\r\n    std::for_each(discard_cache_.begin(), discard_cache_.end(), [](auto &x) { x.clear(); });\r\n    std::for_each(draw_cache_.begin(), draw_cache_.end(), [](auto &x) { x.clear(); });\r\n}\r\n\r\n/**\r\n * @brief 自摸牌一覧を取得する。\r\n *\r\n * @param[in] hand 手牌\r\n * @param[in] syanten 手牌の向聴数\r\n * @param[in] counts 各牌の残り枚数\r\n * @return 自摸牌候補の一覧。各要素は (牌, 残り枚数, 向聴数の変化) を表す。\r\n */\r\nstd::vector<std::tuple<int, int, int>>\r\nNaiveExpectedValueCalculator::get_draw_tiles(Hand &hand, int syanten,\r\n                                             const std::vector<int> &counts)\r\n{\r\n    std::vector<std::tuple<int, int, int>> flags;\r\n    flags.reserve(34);\r\n\r\n    for (int tile = 0; tile < 34; ++tile) {\r\n        if (counts[tile] == 0)\r\n            continue;\r\n\r\n        add_tile(hand, tile);\r\n        auto [_, syanten_after] = SyantenCalculator::calc(hand, syanten_type_);\r\n        remove_tile(hand, tile);\r\n        int syanten_diff = syanten_after - syanten; // 向聴数の変化\r\n\r\n        if (calc_akatile_tumo_ && tile == Tile::Manzu5 && counts[Tile::AkaManzu5] == 1) {\r\n            // 赤五萬が残っている場合\r\n            if (counts[Tile::Manzu5] >= 2) {\r\n                // 普通の牌と赤牌の両方が残っている\r\n                flags.emplace_back(tile, counts[tile] - 1, syanten_diff);\r\n                flags.emplace_back(Tile::AkaManzu5, 1, syanten_diff);\r\n            }\r\n            else if (counts[Tile::Manzu5] == 1) {\r\n                // 赤牌のみ残っている\r\n                flags.emplace_back(Tile::AkaManzu5, 1, syanten_diff);\r\n            }\r\n        }\r\n        else if (calc_akatile_tumo_ && tile == Tile::Pinzu5 && counts[Tile::AkaPinzu5] == 1) {\r\n            // 赤五筒が残っている場合\r\n            if (counts[Tile::Pinzu5] >= 2) {\r\n                // 普通の牌と赤牌の両方が残っている\r\n                flags.emplace_back(tile, counts[tile] - 1, syanten_diff);\r\n                flags.emplace_back(Tile::AkaPinzu5, 1, syanten_diff);\r\n            }\r\n            else if (counts[Tile::Pinzu5] == 1) {\r\n                // 赤牌のみ残っている\r\n                flags.emplace_back(Tile::AkaPinzu5, 1, syanten_diff);\r\n            }\r\n        }\r\n        else if (calc_akatile_tumo_ && tile == Tile::Sozu5 && counts[Tile::AkaSozu5] == 1) {\r\n            // 赤五索が残っている場合\r\n            if (counts[Tile::Sozu5] >= 2) {\r\n                // 普通の牌と赤牌の両方が残っている\r\n                flags.emplace_back(tile, counts[tile] - 1, syanten_diff);\r\n                flags.emplace_back(Tile::AkaSozu5, 1, syanten_diff);\r\n            }\r\n            else if (counts[Tile::Sozu5] == 1) {\r\n                // 赤牌のみ残っている\r\n                flags.emplace_back(Tile::AkaSozu5, 1, syanten_diff);\r\n            }\r\n        }\r\n        else {\r\n            flags.emplace_back(tile, counts[tile], syanten_diff);\r\n        }\r\n    }\r\n\r\n    return flags;\r\n}\r\n\r\n/**\r\n * @brief 打牌一覧を取得する。\r\n *\r\n * @param[in] hand 手牌\r\n * @param[in] syanten 手牌の向聴数\r\n * @return 打牌一覧 (向聴戻し: 1、向聴数変化なし: 0、手牌に存在しない: inf)\r\n */\r\nstd::vector<int> NaiveExpectedValueCalculator::get_discard_tiles(Hand &hand, int syanten)\r\n{\r\n    std::vector<int> flags(34, std::numeric_limits<int>::max());\r\n\r\n    for (int tile = 0; tile < 34; ++tile) {\r\n        if (hand.contains(tile)) {\r\n            remove_tile(hand, tile);\r\n            auto [_, syanten_after] = SyantenCalculator::calc(hand, syanten_type_);\r\n            add_tile(hand, tile);\r\n            flags[tile] = syanten_after - syanten;\r\n        }\r\n    }\r\n\r\n    return flags;\r\n}\r\n\r\n/**\r\n * @brief 手牌の点数を取得する。\r\n *\r\n * @param[in] hand 手牌\r\n * @param[in] win_tile 自摸牌\r\n * @param[in] counts 各牌の残り枚数\r\n * @return 点数\r\n */\r\nstd::vector<double> NaiveExpectedValueCalculator::get_score(const Hand &hand, int win_tile,\r\n                                                            const std::vector<int> &counts)\r\n{\r\n    // 非門前の場合は自摸のみ\r\n    int hand_flag = hand.is_menzen() ? (HandFlag::Tumo | HandFlag::Reach) : HandFlag::Tumo;\r\n\r\n    // 点数計算を行う。\r\n    Result result = score_calculator_.calc(hand, win_tile, hand_flag);\r\n\r\n    // 表ドラの数\r\n    int n_dora = int(dora_indicators_.size());\r\n\r\n    // ダブル立直、一発、海底撈月で最大3翻まで増加するので、\r\n    // ベースとなる点数、+1翻の点数、+2翻の点数、+3翻の点数も計算しておく。\r\n    std::vector<double> scores(4, 0);\r\n    if (result.success) {\r\n        // 役ありの場合\r\n        std::vector<int> up_scores = score_calculator_.get_scores_for_exp(result);\r\n\r\n        if (calc_uradora_ && n_dora == 1) {\r\n            // 裏ドラ考慮ありかつ表ドラが1枚以上の場合は、厳密に計算する。\r\n            std::vector<double> n_indicators(5, 0);\r\n            int sum_indicators = 0;\r\n            for (int tile = 0; tile < 34; ++tile) {\r\n                int n = hand.num_tiles(tile);\r\n                if (n > 0) {\r\n                    // ドラ表示牌の枚数を数える。\r\n                    n_indicators[n] += counts[Dora2Indicator.at(tile)];\r\n                    sum_indicators += counts[Dora2Indicator.at(tile)];\r\n                }\r\n            }\r\n\r\n            // 裏ドラの乗る確率を枚数ごとに計算する。\r\n            std::vector<double> uradora_probs(5, 0);\r\n\r\n            // 厳密に計算するなら残り枚数は数えるべきだが、あまり影響がないので121枚で固定\r\n            int n_left_tiles = 121;\r\n            uradora_probs[0] = double(n_left_tiles - sum_indicators) / n_left_tiles;\r\n            for (int i = 1; i < 5; ++i)\r\n                uradora_probs[i] = double(n_indicators[i]) / n_left_tiles;\r\n\r\n            for (int base = 0; base < 4; ++base) {\r\n                for (int i = 0; i < 5; ++i) { // 裏ドラ1枚の場合、最大4翻まで乗る可能性がある\r\n                    int han_idx = std::min(base + i, int(up_scores.size() - 1));\r\n                    scores[base] += up_scores[han_idx] * uradora_probs[i];\r\n                }\r\n            }\r\n        }\r\n        else if (calc_uradora_ && n_dora > 1) {\r\n            // 裏ドラ考慮ありかつ表ドラが2枚以上の場合、統計データを利用する。\r\n            for (int base = 0; base < 4; ++base) {\r\n                for (int i = 0; i < 13; ++i) {\r\n                    int han_idx = std::min(base + i, int(up_scores.size() - 1));\r\n                    scores[base] += up_scores[han_idx] * uradora_prob_table_[n_dora][i];\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            // 裏ドラ考慮なしまたは表ドラが0枚の場合\r\n            for (int base = 0; base < 4; ++base) {\r\n                int han_idx = std::min(base, int(up_scores.size() - 1));\r\n                scores[base] += up_scores[han_idx];\r\n            }\r\n        }\r\n    }\r\n\r\n    return scores;\r\n}\r\n\r\n/**\r\n * @brief 自摸する。(手変わりを考慮しない)\r\n *\r\n * @param[in] n_extra_tumo\r\n * @param[in] syanten 向聴数\r\n * @param[in] hand 手牌\r\n * @param[in] counts 各牌の残り枚数\r\n * @return (各巡目の聴牌確率, 各巡目の和了確率, 各巡目の期待値)\r\n */\r\nstd::tuple<double, double, double>\r\nNaiveExpectedValueCalculator::draw_without_tegawari(int n_extra_tumo, int syanten, Hand &hand,\r\n                                                    std::vector<int> &counts, int turn)\r\n{\r\n    assert(syanten > -1);\r\n    // 自摸候補を取得する。\r\n    std::vector<std::tuple<int, int, int>> flags = get_draw_tiles(hand, syanten, counts);\r\n\r\n    // 有効牌の合計枚数を計算する。\r\n    int sum_required_tiles = 0;\r\n    for (auto &[tile, count, diff] : flags) {\r\n        if (diff == -1) // 有効牌の場合\r\n            sum_required_tiles += count;\r\n    }\r\n\r\n    double tenpai_prob = 0, win_prob = 0, exp_value = 0;\r\n    for (auto &[tile, count, diff] : flags) {\r\n        if (diff != -1) // 有効牌以外の場合\r\n            continue;\r\n\r\n        const std::vector<double> &tumo_probs = tumo_prob_table_[count];\r\n        const std::vector<double> &not_tumo_probs = not_tumo_prob_table_[sum_required_tiles];\r\n\r\n        // 手牌に加える\r\n        add_tile(hand, tile, counts);\r\n\r\n        std::vector<double> scores;\r\n        if (syanten == 0) {\r\n            scores = get_score(hand, tile, counts);\r\n        }\r\n\r\n        for (int t = turn - 1; t <= 16; ++t) {\r\n            // 現在の巡目が turn の場合に t 巡目に有効牌を引く確率\r\n            double not_prob = not_tumo_probs[t] / not_tumo_probs[turn - 1];\r\n            double prob = tumo_probs[t] * not_prob;\r\n\r\n            double tumo_prob2 = double(count) / (sum_left_tiles_ - t);\r\n            double not_prob2 = 1;\r\n            for (int j = turn - 1; j < t; j++)\r\n                not_prob2 *=\r\n                    double(sum_left_tiles_ - j - sum_required_tiles) / (sum_left_tiles_ - j);\r\n\r\n            assert(std::abs(tumo_probs[t] - tumo_prob2) < 10e-10);\r\n            assert(std::abs(not_prob - not_prob2) < 10e-10);\r\n            //std::cout << fmt::format(\"tumo_prob t={}, {} vs {}\\n\", t, tumo_probs[t], prob2);\r\n            // std::cout << fmt::format(\"not_tumo_prob turn={}, t={}, {} vs {}\\n\", turn, t, not_prob,\r\n            //                          not_prob2);\r\n\r\n            double next_tenpai_prob = 0, next_win_prob = 0, next_exp_value = 0;\r\n            if (t < 16 && syanten > 0) {\r\n                // 次の巡目がある場合\r\n                std::tie(next_tenpai_prob, next_win_prob, next_exp_value) =\r\n                    discard(n_extra_tumo, syanten - 1, hand, counts, t + 2);\r\n            }\r\n\r\n            if (syanten == 1) // 1向聴の場合は次で聴牌\r\n                tenpai_prob += prob;\r\n            else if (t < 16 && syanten > 1) // 2向聴以上で16巡目以下の場合\r\n            {\r\n                tenpai_prob += prob * next_tenpai_prob;\r\n                // if (syanten - (16 - t) > 1) {\r\n                //     // 聴牌までたどり着くことが不可能\r\n                //     assert(next_tenpai_prob == 0);\r\n                // }\r\n                // else {\r\n                //     assert(next_tenpai_prob > 0);\r\n                // }\r\n            }\r\n\r\n            // scores[0] == 0 の場合は役なしなので、和了確率、期待値は0\r\n            if (syanten == 0 && scores[0] != 0) { // 聴牌の場合は次で和了\r\n                // 1巡目で聴牌の場合はダブル立直成立\r\n                bool win_double_reach = turn == 1 && calc_double_reach_;\r\n                // 1巡目で聴牌し、次の巡目で和了の場合は一発成立\r\n                bool win_ippatu = t == turn - 1 && calc_ippatu_;\r\n                // 最後の巡目で和了の場合は海底撈月成立\r\n                bool win_haitei = t == 16 && calc_haitei_;\r\n\r\n                win_prob += prob;\r\n                exp_value += prob * scores[win_double_reach + win_ippatu + win_haitei];\r\n            }\r\n            else if (t < 16 && syanten > 0) { // 聴牌以上で16巡目以下の場合\r\n                win_prob += prob * next_win_prob;\r\n                exp_value += prob * next_exp_value;\r\n            }\r\n        }\r\n\r\n        // 手牌から除く\r\n        remove_tile(hand, tile, counts);\r\n    }\r\n\r\n    return {tenpai_prob, win_prob, exp_value};\r\n}\r\n\r\n/**\r\n * @brief 自摸する。(手変わりを考慮する)\r\n *\r\n * @param[in] n_extra_tumo\r\n * @param[in] syanten 向聴数\r\n * @param[in] hand 手牌\r\n * @param[in] counts 各牌の残り枚数\r\n * @return (各巡目の聴牌確率, 各巡目の和了確率, 各巡目の期待値)\r\n *\r\n * この関数が呼ばれた時点で向聴戻しは行われていない\r\n */\r\nstd::tuple<double, double, double>\r\nNaiveExpectedValueCalculator::draw_with_tegawari(int n_extra_tumo, int syanten, Hand &hand,\r\n                                                 std::vector<int> &counts, int turn)\r\n{\r\n    assert(syanten > -1);\r\n    // 自摸候補を取得する。\r\n    std::vector<std::tuple<int, int, int>> flags = get_draw_tiles(hand, syanten, counts);\r\n\r\n    // 有効牌の合計枚数を計算する。\r\n    double s = 0;\r\n    int s2 = 0;\r\n    int s3 = 0;\r\n    // 残り牌を集計\r\n    for (int i = 0; i < 34; ++i) {\r\n        s2 += counts[i];\r\n    }\r\n\r\n    for (auto &[tile, count, syanten_diff] : flags) {\r\n        s += double(count) / s2;\r\n        s3 += count;\r\n    }\r\n\r\n    // if (s2 != 121 - turn - 1) {\r\n    //     std::cout << fmt::format(\"121 - turn - 1={}, s={}, diff={}\", 121 - turn - 1, s3,\r\n    //                              (121 - turn - 1) - s3)\r\n    //               << std::endl;\r\n    // }\r\n\r\n    // if (std::abs(s - 1) > 10e-10) {\r\n    //     std::cout << fmt::format(\"t={}, sum={}\", turn - 1, s2) << std::endl;\r\n    //     std::cout << s << \" \" << std::endl;\r\n    //     for (auto &[tile, count, syanten_diff] : flags) {\r\n    //         std::cout << fmt::format(\"count={}, prob={:.8f}\", count,\r\n    //                                  tumo_prob_table_[count][turn - 1])\r\n    //                   << std::endl;\r\n    //     }\r\n    //     assert(std::abs(s - 1) < 10e-10);\r\n    // }\r\n\r\n    assert(std::abs(s - 1) < 10e-10);\r\n\r\n    double tenpai_prob = 0, win_prob = 0, exp_value = 0;\r\n    for (auto &[tile, count, syanten_diff] : flags) {\r\n        assert(syanten_diff == -1 || syanten_diff == 0);\r\n        if (syanten_diff != -1)\r\n            continue; // 有効牌以外の場合\r\n\r\n        const std::vector<double> &tumo_probs = tumo_prob_table_[count];\r\n\r\n        // 手牌に加える\r\n        add_tile(hand, tile, counts);\r\n\r\n        std::vector<double> scores;\r\n        if (syanten == 0) {\r\n            scores = get_score(hand, tile, counts);\r\n        }\r\n\r\n        int t = turn - 1;\r\n        double next_tenpai_prob = 0, next_win_prob = 0, next_exp_value = 0;\r\n        if (t < 16 && syanten > 0) {\r\n            std::tie(next_tenpai_prob, next_win_prob, next_exp_value) =\r\n                discard(n_extra_tumo, syanten - 1, hand, counts, turn + 1);\r\n        }\r\n\r\n#ifdef FIX_TEGAWARI_PROB\r\n        double tumo_prob = double(count) / s3; // 確率が1を超えないようにするため\r\n#else\r\n        double tumo_prob = tumo_probs[t];\r\n#endif\r\n\r\n        if (syanten == 1) // 1向聴の場合は次で聴牌\r\n            tenpai_prob += tumo_prob;\r\n        else if (t < 16 && syanten > 1)\r\n            tenpai_prob += tumo_prob * next_tenpai_prob;\r\n\r\n        if (syanten == 0) { // 聴牌の場合は次で和了\r\n            // 1巡目で聴牌の場合はダブル立直成立\r\n            bool win_double_reach = turn == 1 && calc_double_reach_;\r\n            // 1巡目で聴牌し、次の巡目で和了の場合は一発成立\r\n            bool win_ippatu = t == turn - 1 && calc_ippatu_;\r\n            // 最後の巡目で和了の場合は海底撈月成立\r\n            bool win_haitei = t == 16 && calc_haitei_;\r\n\r\n            win_prob += tumo_prob;\r\n            exp_value += tumo_prob * scores[win_double_reach + win_ippatu + win_haitei];\r\n        }\r\n        else if (t < 16 && syanten > 0) {\r\n            win_prob += tumo_prob * next_win_prob;\r\n            exp_value += tumo_prob * next_exp_value;\r\n        }\r\n\r\n        // 手牌から除く\r\n        remove_tile(hand, tile, counts);\r\n    }\r\n\r\n    for (auto &[tile, count, syanten_diff] : flags) {\r\n        if (syanten_diff != 0)\r\n            continue; // 有効牌の場合\r\n\r\n        const std::vector<double> &tumo_probs = tumo_prob_table_[count];\r\n        int t = turn - 1;\r\n#ifdef FIX_TEGAWARI_PROB\r\n        double tumo_prob = double(count) / s3; // 確率が1を超えないようにするため\r\n#else\r\n        double tumo_prob = tumo_probs[t];\r\n#endif\r\n\r\n        // 手牌に加える\r\n        add_tile(hand, tile, counts);\r\n\r\n        double next_tenpai_prob = 0, next_win_prob = 0, next_exp_value = 0;\r\n        if (t < 16) {\r\n            auto [next_tenpai_prob, next_win_prob, next_exp_value] =\r\n                discard(n_extra_tumo + 1, syanten, hand, counts, turn + 1);\r\n            tenpai_prob += tumo_prob * next_tenpai_prob;\r\n            win_prob += tumo_prob * next_win_prob;\r\n            exp_value += tumo_prob * next_exp_value;\r\n        }\r\n\r\n        // 手牌から除く\r\n        remove_tile(hand, tile, counts);\r\n    }\r\n\r\n    return {tenpai_prob, win_prob, exp_value};\r\n}\r\n\r\n/**\r\n * @brief 自摸する。\r\n *\r\n * @param[in] n_extra_tumo\r\n * @param[in] syanten 向聴数\r\n * @param[in] hand 手牌\r\n * @param[in] counts 各牌の残り枚数\r\n * @return (各巡目の聴牌確率, 各巡目の和了確率, 各巡目の期待値)\r\n */\r\nstd::tuple<double, double, double> NaiveExpectedValueCalculator::draw(int n_extra_tumo, int syanten,\r\n                                                                      Hand &hand,\r\n                                                                      std::vector<int> &counts,\r\n                                                                      int turn)\r\n{\r\n    if (calc_tegawari_ && n_extra_tumo == 0)\r\n        return draw_with_tegawari(n_extra_tumo, syanten, hand, counts, turn);\r\n    else\r\n        return draw_without_tegawari(n_extra_tumo, syanten, hand, counts, turn);\r\n}\r\n\r\n/**\r\n * @brief 打牌する。\r\n *\r\n * @param[in] n_extra_tumo\r\n * @param[in] syanten 向聴数\r\n * @param[in] hand 手牌\r\n * @param[in] counts 各牌の残り枚数\r\n * @return (各巡目の聴牌確率, 各巡目の和了確率, 各巡目の期待値)\r\n */\r\nstd::tuple<double, double, double> NaiveExpectedValueCalculator::discard(int n_extra_tumo,\r\n                                                                         int syanten, Hand &hand,\r\n                                                                         std::vector<int> &counts,\r\n                                                                         int turn)\r\n{\r\n    assert(syanten > -1);\r\n\r\n    // 打牌候補を取得する。\r\n    const std::vector<int> flags = get_discard_tiles(hand, syanten);\r\n\r\n    // 期待値が最大となる打牌を選択する。\r\n    double max_tenpai_prob, max_win_prob, max_exp_value;\r\n    double tenpai_prob, win_prob, exp_value;\r\n    int max_tile = -1;\r\n    double max_value = -1;\r\n    for (int tile = 0; tile < 34; ++tile) {\r\n        int discard_tile = tile;\r\n        // 赤牌以外が残っている場合はそちらを先に捨てる。\r\n        if (tile == Tile::Manzu5 && hand.aka_manzu5 && hand.num_tiles(Tile::Manzu5) == 1)\r\n            discard_tile = Tile::AkaManzu5;\r\n        else if (tile == Tile::Pinzu5 && hand.aka_pinzu5 && hand.num_tiles(Tile::Pinzu5) == 1)\r\n            discard_tile = Tile::AkaPinzu5;\r\n        else if (tile == Tile::Sozu5 && hand.aka_sozu5 && hand.num_tiles(Tile::Sozu5) == 1)\r\n            discard_tile = Tile::AkaSozu5;\r\n\r\n        if (flags[tile] == 0) {\r\n            // 向聴数が変化しない打牌\r\n            remove_tile(hand, discard_tile);\r\n            std::tie(tenpai_prob, win_prob, exp_value) =\r\n                draw(n_extra_tumo, syanten, hand, counts, turn);\r\n            add_tile(hand, discard_tile);\r\n        }\r\n        else if (calc_syanten_down_ && n_extra_tumo == 0 && flags[tile] == 1) {\r\n            // 向聴戻ししたら最短でも聴牌できなくなる場合\r\n            // if (turn + syanten > 18)\r\n            //     continue; //\r\n\r\n            // 向聴戻しになる打牌\r\n            remove_tile(hand, discard_tile);\r\n            std::tie(tenpai_prob, win_prob, exp_value) =\r\n                draw(n_extra_tumo + 1, syanten + 1, hand, counts, turn);\r\n            add_tile(hand, discard_tile);\r\n        }\r\n        else {\r\n            // 手牌に存在しない牌、または向聴落としが無効な場合に向聴落としとなる牌\r\n            continue;\r\n        }\r\n\r\n        // 向聴戻し、手変わりは巡目がずれるので、1つ手前にずらす。(このやり方で正しいのか要検証)\r\n\r\n        // 和了確率は下2桁まで一致していれば同じ、期待値は下0桁まで一致していれば同じとみなす。\r\n        double value = maximize_win_prob_ ? int(win_prob * 10000) : int(exp_value);\r\n        if ((value == max_value && DiscardPriorities[max_tile] < DiscardPriorities[tile]) ||\r\n            value > max_value) {\r\n            // 値が同等なら、DiscardPriorities が高い牌を優先して選択する。\r\n            max_tenpai_prob = tenpai_prob;\r\n            max_win_prob = win_prob;\r\n            max_exp_value = exp_value;\r\n\r\n            max_value = value;\r\n            max_tile = tile;\r\n        }\r\n    }\r\n\r\n    return {max_tenpai_prob, max_win_prob, max_exp_value};\r\n}\r\n\r\n/**\r\n * @brief 手牌の推移パターンを和了まですべて解析する。\r\n *\r\n * @param [in]n_extra_tumo\r\n * @param [in]syanten 向聴数\r\n * @param [in]_hand 手牌\r\n * @return std::vector<Candidate> 打牌候補の一覧\r\n */\r\nstd::vector<Candidate> NaiveExpectedValueCalculator::analyze(int n_extra_tumo, int syanten,\r\n                                                             const Hand &_hand, int turn)\r\n{\r\n    assert(syanten >= -1);\r\n\r\n    std::vector<Candidate> candidates;\r\n    Hand hand = _hand;\r\n\r\n    // 各牌の残り枚数を数える。\r\n    std::vector<int> counts = count_left_tiles(hand, dora_indicators_);\r\n\r\n    // 打牌候補を取得する。\r\n    const std::vector<int> flags = get_discard_tiles(hand, syanten);\r\n\r\n    for (int tile = 0; tile < 34; ++tile) {\r\n        int discard_tile = tile;\r\n        // 赤牌以外が残っている場合はそちらを先に捨てる。\r\n        if (tile == Tile::Manzu5 && hand.aka_manzu5 && hand.num_tiles(Tile::Manzu5) == 1)\r\n            discard_tile = Tile::AkaManzu5;\r\n        else if (tile == Tile::Pinzu5 && hand.aka_pinzu5 && hand.num_tiles(Tile::Pinzu5) == 1)\r\n            discard_tile = Tile::AkaPinzu5;\r\n        else if (tile == Tile::Sozu5 && hand.aka_sozu5 && hand.num_tiles(Tile::Sozu5) == 1)\r\n            discard_tile = Tile::AkaSozu5;\r\n\r\n        if (flags[tile] == 0) {\r\n            remove_tile(hand, discard_tile);\r\n\r\n            auto required_tiles = get_required_tiles(hand, syanten_type_, counts);\r\n\r\n            auto [tenpai_prob, win_prob, exp_value] =\r\n                draw(n_extra_tumo, syanten, hand, counts, turn);\r\n\r\n            if (syanten == 0)\r\n                tenpai_prob = 1;\r\n\r\n            add_tile(hand, discard_tile);\r\n\r\n            std::vector<double> tenpai_probs(17), win_probs(17), exp_values(17);\r\n            tenpai_probs[turn - 1] = tenpai_prob;\r\n            win_probs[turn - 1] = win_prob;\r\n            exp_values[turn - 1] = exp_value;\r\n            candidates.emplace_back(discard_tile, required_tiles, tenpai_probs, win_probs,\r\n                                    exp_values, false);\r\n        }\r\n        else if (calc_syanten_down_ && flags[tile] == 1 && n_extra_tumo == 0 && syanten < 3) {\r\n            remove_tile(hand, discard_tile);\r\n\r\n            auto required_tiles = get_required_tiles(hand, syanten_type_, counts);\r\n\r\n            auto [tenpai_prob, win_prob, exp_value] =\r\n                draw(n_extra_tumo + 1, syanten + 1, hand, counts, turn);\r\n\r\n            add_tile(hand, discard_tile);\r\n\r\n            std::vector<double> tenpai_probs(17), win_probs(17), exp_values(17);\r\n            tenpai_probs[turn - 1] = tenpai_prob;\r\n            win_probs[turn - 1] = win_prob;\r\n            exp_values[turn - 1] = exp_value;\r\n\r\n            candidates.emplace_back(discard_tile, required_tiles, tenpai_probs, win_probs,\r\n                                    exp_values, true);\r\n        }\r\n    }\r\n\r\n    return candidates;\r\n}\r\n\r\n/**\r\n * @brief 手牌の推移パターンを1手先まで解析する。\r\n *\r\n * @param [in]syanten 向聴数\r\n * @param [in]_hand 手牌\r\n * @return std::vector<Candidate> 打牌候補の一覧\r\n */\r\nstd::vector<Candidate> NaiveExpectedValueCalculator::analyze(int syanten, const Hand &_hand)\r\n{\r\n    std::vector<Candidate> candidates;\r\n    Hand hand = _hand;\r\n\r\n    // 各牌の残り枚数を数える。\r\n    std::vector<int> counts = count_left_tiles(hand, dora_indicators_);\r\n\r\n    std::vector<int> tiles = UnnecessaryTileSelector::select(hand, syanten_type_);\r\n\r\n    for (auto tile : tiles) {\r\n        remove_tile(hand, tile);\r\n        auto required_tiles = get_required_tiles(hand, syanten_type_, counts);\r\n        auto [_, syanten_after] = SyantenCalculator::calc(hand, syanten_type_);\r\n        bool syanten_down = syanten_after == 1;\r\n        add_tile(hand, tile);\r\n        candidates.emplace_back(tile, required_tiles, syanten_down);\r\n    }\r\n\r\n    return candidates;\r\n}\r\n\r\nstd::vector<std::vector<double>> NaiveExpectedValueCalculator::uradora_prob_table_;\r\n\r\n} // namespace mahjong\r\n", "meta": {"hexsha": "bf1ab3352de50661fea1023f5ec38c55d85d5680", "size": 28780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/naiveexpectedvaluecalculator.cpp", "max_stars_repo_name": "happapa/mahjong-cpp", "max_stars_repo_head_hexsha": "a392a9a48cd790dbcf4ee31463c3a431c9a614c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/naiveexpectedvaluecalculator.cpp", "max_issues_repo_name": "happapa/mahjong-cpp", "max_issues_repo_head_hexsha": "a392a9a48cd790dbcf4ee31463c3a431c9a614c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/naiveexpectedvaluecalculator.cpp", "max_forks_repo_name": "happapa/mahjong-cpp", "max_forks_repo_head_hexsha": "a392a9a48cd790dbcf4ee31463c3a431c9a614c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2211652794, "max_line_length": 102, "alphanum_fraction": 0.5435371786, "num_tokens": 9532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.09009300190197035, "lm_q1q2_score": 0.04363925585404291}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2021\n * Alberto Francisco Kummer Neto (afkneto@inf.ufrgs.br),\n * Luciana Salete Buriol (buriol@inf.ufrgs.br),\n * Olinto César Bassi de Araújo (olinto@ctism.ufsm.br) and\n * Mauricio G.C. Resende (resendem@amazon.com)\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#include \"Instance.h\"\n#include \"SortingDecoder.h\"\n#include \"Timer.h\"\n\n#include \"brkga_mp_ipr.hpp\"\n\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <sstream>\n\n#include <boost/program_options.hpp>\n\nusing namespace std;\n\n/// Parses the command line arguments using boost::program_options library.\nboost::program_options::variables_map parseCommandline(int argc, char **argv);\n\n/// Converts the parameters to the format that BRKGA library uses.\nBRKGA::BrkgaParams extractFrom(boost::program_options::variables_map &vm);\n\n/// Prints some metrics regarding the number of qualified caregivers, \n/// and the number of service requests, per service type.\nvoid printSupplyDemandIndicators(const Instance &inst);\n\n/// Computes the average and standard deviation of elite set of the GA.\ntuple<double, double> computeEliteDiversity(const BRKGA::BRKGA_MP_IPR<SortingDecoder> &solver);\n\nint main(int argc, char* argv[]) {\n   // Parses command line arguments.\n   auto args = parseCommandline(argc, argv);\n   auto brkga_params = extractFrom(args);\n\n   // Print some information about the run.\n   const unsigned seed = args[\"seed\"].as<int>();\n   cout << \"--- BRKGA-MP-IPR for HHCRSP ---\\n\";\n   cout << \"Instance: \" << args[\"instance\"].as<string>() << endl;\n   cout << \"Seed: \" << seed << endl;\n   cout << \"\\n\";\n\n   // Reads the problem instance.\n   const string instFile = args[\"instance\"].as<string>();\n   cout << \"Parsing instance file...\\n\";\n   auto instance = Instance(instFile.c_str());\n   cout << \"Problem contains \" << (instance.numNodes() - 2) << \n      \" patients and \" << instance.numVehicles() << \" caregivers.\\n\";\n   printSupplyDemandIndicators(instance);\n   cout << endl;\n\n   double overallBest = 1e75;\n   try {\n      // Caches a copy some of the control parameters.\n      const unsigned num_generations = args[\"gens\"].as<int>();\n      const int immigrants = args[\"immigrants\"].as<int>();\n      const auto iprType = args[\"ptype\"].as<string>();\n\n      // Logic for selecting the distance function according to \n      // implicit PR selection.\n      shared_ptr <BRKGA::DistanceFunctionBase> distFuncPtr;\n      {\n         const auto &str = args[\"dfunc\"].as<string>();\n         if (str.empty()) {\n            cout << \"Inferred distance function by PR type: \";\n            if (str == \"direct\") {\n               cout << \"hamming\";\n               distFuncPtr.reset(new BRKGA::HammingDistance(args[\"hdist\"].as<int>()));\n            } else {\n               cout << \"kendall-tau\";\n               distFuncPtr.reset(new BRKGA::KendallTauDistance());\n            }\n            cout << \"\\n\";\n         } else {\n            if (str == \"hamming\") {\n               cout << \"Using hamming distance forcibly.\\n\";\n               distFuncPtr.reset(new BRKGA::HammingDistance(args[\"hdist\"].as<int>()));\n            } else if (str == \"kendall\") {\n               cout << \"Using kendall-tau distance forcibly.\\n\";\n               distFuncPtr.reset(new BRKGA::KendallTauDistance());\n            } else {\n               cout << \"Unknown distance function: \" << str << \"\\n\";\n               abort();\n            }\n         }\n      }\n\n      cout << \"Initializing genetic algorithm...\\n\";\n      SortingDecoder decoder(instance);\n      BRKGA::BRKGA_MP_IPR<SortingDecoder> algorithm(\n         decoder, BRKGA::Sense::MINIMIZE, seed,\n         decoder.chromosomeLength(), brkga_params, omp_get_max_threads()\n      );\n      algorithm.initialize();\n\n      // Some other control parameters used within the algorithm.\n      const auto prPeriod = args[\"pperiod\"].as<int>();\n      const auto resetPeriod = args[\"reset\"].as<long>();\n      const auto exchangePeriod = args[\"xelite\"].as<int>();\n      const auto printPeriod = args.count(\"printall\") ? 1 : 50;\n\n      // Some indicators collected during the run.\n      int iprHomogeneous = 0, iprNoImprovement = 0, \n         iprEliteImprovement = 0, iprBestImprovement = 0;\n      int linesPrinted = 0;\n      int opIpr = 0, opXe = 0, opRst = 0;\n\n      Timer tm;\n      unsigned generation = 0;\n      int noImprove = 0;\n\n      double localBest = numeric_limits<double>::infinity();\n      double dist = localBest, tard = localBest, tmax = localBest;      \n\n      // Prints the header of algorithm output.\n      auto printHeader = [] () {\n         cout << \"\\n\";\n         cout << \n            setw(1) << \"\" << \" \" <<\n            setw(4) << \"Gens\" << \" \" <<\n            setw(4) << \"Rem\" << \" \" <<\n            \n            setw(8) << \"Local\" << \" \" << \n            setw(7) << \"ElDiv\" << \" \" <<\n            setw(3) << \"NoImpr\" << \" \" <<\n\n            setw(33) << \"Best solution        \" << \" \" << \n            \n            setw(7) << \"Time\" << \" \" <<\n            setw(3) << \"Op\" << \n         \"\\n\";\n\n         cout << \n            setw(34) << \"\" << \" \" <<\n            setw(8) << \"Cost\" << \" \" <<\n            setw(8) << \"Dist\" << \" \" <<\n            setw(7) << \"Tard\" << \" \" <<\n            setw(7) << \"TMax\" << \" \" <<\n         \"\\n\";\n\n      };\n\n      // Prints the algorithm progress.\n      char hdr = ' ';\n      string evt = \"\";\n      auto printProgress = [&] () {\n         if (linesPrinted >= 15) {\n            printHeader();\n            linesPrinted = 0;\n         } else {\n            ++linesPrinted;\n         }\n\n         auto [eliteMean, eliteStdev] = computeEliteDiversity(algorithm);\n         tm.finish();\n         cout << \n            fixed << \n            setw(1) << hdr << \" \" <<\n            setw(4) << generation << \" \" <<\n            setw(4) << num_generations - generation << \" \" <<\n            \n            setw(8) << setprecision(2) << localBest << \" \" << \n            setw(7) << setprecision(2) << eliteStdev << \" \" <<\n            setw(6) << noImprove << \" \" <<\n            \n            setw(8) << setprecision(2) << overallBest << \" \" <<\n            setw(8) << setprecision(2) << dist << \" \" <<\n            setw(7) << setprecision(1) << tard << \" \" <<\n            setw(7) << setprecision(1) << tmax << \" \" <<\n\n            setw(7) << setprecision(1) << tm.elapsed() << \" \" <<\n            setw(3) << evt << \n         \"\\n\";\n         hdr = ' ';\n         evt = \"\";\n      };\n      \n      cout << \"Stopping criteria: \" << instance.numNodes()/2 << \" staled generations, maximum of \"<< num_generations << \" generations.\\n\";\n\n      printHeader();\n      tm.start();\n      do {\n         bool hasImproved = false;\n         algorithm.evolve();         \n         \n         if (localBest >= numeric_limits<double>::infinity()) {\n            localBest = algorithm.getBestFitness(); \n            hasImproved = true;\n         }\n         \n         if (localBest < overallBest) {\n            overallBest = localBest;\n            const auto sol = decoder.decodeSolution(algorithm.getBestChromosome());\n            dist = sol.dist;\n            tard = sol.tard;\n            tmax = sol.tmax;\n            hdr = '*';\n         }\n\n         if (generation % printPeriod == 0 || hasImproved || hdr == '*') {\n            printProgress();\n         }\n\n         if (prPeriod > 0 && generation > 0 && generation % prPeriod == 0) {\n            using BRKGA::PathRelinking::PathRelinkingResult;\n            evt += 'P';\n            opIpr++;\n            PathRelinkingResult result = algorithm.pathRelink(distFuncPtr);\n            cout << \"Path relinking result: \";\n            switch(result) {\n               case PathRelinkingResult::TOO_HOMOGENEOUS:\n                  cout << \"too homogeneous.\";\n                  iprHomogeneous++;\n                  break;\n               case PathRelinkingResult::NO_IMPROVEMENT:\n                  cout << \"no improvement.\";\n                  iprNoImprovement++;\n                  break;\n               case PathRelinkingResult::ELITE_IMPROVEMENT:\n                  cout << \"elite improvement.\";\n                  iprEliteImprovement++;\n                  break;\n               case PathRelinkingResult::BEST_IMPROVEMENT:\n                  cout << \"best improvement.\";\n                  iprBestImprovement++;\n                  break;\n            }\n            cout << \"\\n\";\n         }\n\n         if (exchangePeriod > 0 && generation > 0 && brkga_params.num_independent_populations > 1 && generation % exchangePeriod == 0) {\n            evt += 'X';\n            opXe++;\n            algorithm.exchangeElite(immigrants);\n         }\n         \n         if (localBest - algorithm.getBestFitness() < 0.05) {\n            ++noImprove;\n         } else {\n            localBest = algorithm.getBestFitness();\n            noImprove = 0;\n         }\n\n         if (noImprove >= resetPeriod) {\n            evt += 'R';\n            opRst++;\n            localBest = numeric_limits<double>::infinity();\n            algorithm.reset();\n            noImprove = 0;\n         }\n\n         if (!evt.empty()) {\n            printProgress();\n         }\n\n         ++generation;\n\n         // New stopping criteria: by iterations without improvement.\n         if (noImprove >= instance.numNodes()/2) {\n            cout << \"Stopping a stale search.\\n\";\n            break;\n         }\n      } while (generation < num_generations);\n\n      printProgress(); \n      cout << \"\\nEvolutionary process finished.\\n\";\n\n      // Post-optimization processing of the fittest individual.\n      {\n         char buf[256] = \"solution-XXXXXX.txt\";\n         int fid = mkstemps(buf, 4);\n         if (fid == -1) {\n            cout << \"Error creating solution file: \" << strerror(errno) << endl;\n            return EXIT_FAILURE;\n         }\n         close(fid);\n         auto sol = decoder.decodeSolution(algorithm.getBestChromosome());\n         sol.writeFile(buf, seed);\n         cout << \"Solution written to '\" << buf << \"'.\\n\";\n\n         cout << \"Unused vehicle list: \";\n         int idle = 0;\n         for (int v = 0; v < instance.numVehicles(); ++v) {\n            if (sol.routes[v].size() <= 2) {\n               ++idle;\n               cout << v << ' ';\n            }\n         }\n         cout << \"(total = \" << idle << \" out of \" << instance.numVehicles() << \")\" << \"\\n\";\n      }\n\n\n      cout << \"\\n---\\nSearch finished.\\n\";\n      cout << \"Total of \" << generation << \" generations in \" << tm.elapsed() << \" seconds.\\n\";\n      cout << \"Exchange elite runs: \" << opXe << \"\\n\";\n      cout << \"Implicit path relinking runs: \" << opIpr << \"\\n\";\n      cout << \"Reset attempts: \" << opRst << \"\\n\";\n      cout << \"\\n\";\n\n      cout << \"Best solution found:\\n\";\n      cout << \"   Cost: \" << overallBest << \"\\n\";\n      cout << \"   Total travel time: \" << dist << \"\\n\";\n      cout << \"   Total tardiness time: \" << tard << \"\\n\";\n      cout << \"   Largest tardiness: \" << tmax << \"\\n\";\n   }\n   catch(exception& e) {\n      cerr << \"\\n***********************************************************\"\n           << \"\\n****  Exception Occured: \" << e.what()\n           << \"\\n***********************************************************\"\n           << endl;\n      return 70; // BSD software internal error code\n   }\n\n   cout << \"\\n\\n\" << overallBest << endl;\n\n   return 0;\n}\n\nboost::program_options::variables_map parseCommandline(int argc, char **argv) {\n   namespace po = boost::program_options;\n   po::options_description desc(\"Accepted command options are\");\n   desc.add_options()\n      (\"help,h\", \"shows this text\")\n\n      (\"instance,i\", po::value<string>(), \"path to the instance file\")\n\n      (\"seed,s\", po::value<int>()->default_value(1), \"seed for the PRNG\")\n\n      (\"printall\", \"log the search progress in each generation, otherwise from \"\n         \"50 to 50 generations, or when a improved solution is found\")\n\n      (\"popsize,p\", po::value<int>()->default_value(300), \"number of individuals \"\n       \"in each population\")\n\n      (\"gens,g\", po::value<int>()->default_value(99999), \n       \"max. generations for the BRKGA phase\")\n\n      (\"pe\", po::value<double>()->default_value(0.15), \"percentage of elite population\")\n\n      (\"pm\", po::value<double>()->default_value(0.15), \"percentagem of mutant population\")\n\n      (\"mp\", po::value<int>()->default_value(2), \"number of parents involved in the mating\")\n\n      (\"ep\", po::value<int>()->default_value(1), \"number of elite parents involved in the mating\")\n\n      (\"bp\", po::value<string>()->default_value(\"loginverse\"), \"set the bias\"\n       \" function to be used while selecting parents for mating. Accepted \"\n       \"values: constant, cubic, exponential, linear, loginverse, quadratic\")\n\n      (\"npop\", po::value<int>()->default_value(1), \"number of independent populations to evolve\")\n\n      (\"npairs\", po::value<int>()->default_value(100), \"number of pairs of chromosomes to test during PR\")\n\n      (\"mindist\", po::value<double>()->default_value(0.15), \"minimal distance between chromosomes to allow \"\n       \"performing PR\")\n\n      (\"psel\", po::value<string>()->default_value(\"best\"), \"specifies which individuals used durint the PR. \"\n       \"Valid options: best, random\")\n\n      (\"alpha\", po::value<double>()->default_value(1.0), \"defines the block size during PR\")\n\n      (\"hdist\", po::value<double>()->default_value(0.5), \"defines the thresold value, used in the hamming distance \"\n         \"to interpret a random key as false or true\")\n\n      (\"pperc\", po::value<double>()->default_value(1.0), \"defines the percentage of PR path to explore\")\n\n      (\"ptype\", po::value<string>()->default_value(\"permutation\"), \"type of PR. Valid values: direct, permutation\")\n\n      (\"dfunc\", po::value<string>()->default_value(\"\"), \"type of distance function to be used. Accepted values are hamming and kendall. If the parameter is suppressed, it is set automatically according to value of ptype: permutation => kendall, direct => hamming\")\n\n      (\"pperiod\", po::value<int>()->default_value(50), \"number of generations between PR attempts\")\n\n      (\"reset\", po::value<long>()->default_value(1e6), \"number of non-improving generations prior resetting the populations\")\n\n      (\"xelite\", po::value<int>()->default_value(100), \"number of generations between exchanging elite from populations\")\n\n      (\"immigrants\", po::value<int>()->default_value(8), \"number of immigrants while exchanging elites\")\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(\"instance\")) {\n      cout << desc << \"\\n\";\n      exit(EXIT_FAILURE);\n   }\n\n   return vm;\n}\n\nBRKGA::BrkgaParams extractFrom(boost::program_options::variables_map &vm) {\n   auto params {BRKGA::BrkgaParams()};\n\n   params.population_size = vm[\"popsize\"].as<int>();\n   params.elite_percentage = vm[\"pe\"].as<double>();\n   params.mutants_percentage = vm[\"pm\"].as<double>();\n   params.total_parents = vm[\"mp\"].as<int>();\n   params.num_elite_parents = vm[\"ep\"].as<int>();\n\n   {\n      auto bp = vm[\"bp\"].as<string>();\n      if (bp == \"constant\") {\n         params.bias_type = BRKGA::BiasFunctionType::CONSTANT;\n      } else if (bp == \"cubic\") {\n         params.bias_type = BRKGA::BiasFunctionType::CUBIC;\n      } else if (bp == \"exponential\") {\n         params.bias_type = BRKGA::BiasFunctionType::EXPONENTIAL;\n      } else if (bp == \"linear\") {\n         params.bias_type = BRKGA::BiasFunctionType::LINEAR;\n      } else if (bp == \"loginverse\") {\n         params.bias_type = BRKGA::BiasFunctionType::LOGINVERSE;\n      } else if (bp == \"quadratic\") {\n         params.bias_type = BRKGA::BiasFunctionType::QUADRATIC;\n      } else {\n         cout << \"Invalid bias for parent selection: \" << bp << \"\\n\";\n         exit(EXIT_FAILURE);\n      }\n   }\n\n   params.num_independent_populations = vm[\"npop\"].as<int>();\n   params.pr_number_pairs = vm[\"npairs\"].as<int>();\n   params.pr_minimum_distance = vm[\"mindist\"].as<double>();\n\n   {\n      const auto ty = vm[\"ptype\"].as<string>();\n      if (ty == \"direct\") {\n         params.pr_type = BRKGA::PathRelinking::Type::DIRECT;\n      } else if (ty == \"permutation\") {\n         params.pr_type = BRKGA::PathRelinking::Type::PERMUTATION;\n      } else {\n         cout << \"Unknown path relinking type: \" << ty << \"\\n\";\n         exit(EXIT_FAILURE);\n      }\n   }\n   \n   {\n      auto sel = vm[\"psel\"].as<string>();\n      if (sel == \"best\") {\n         params.pr_selection = BRKGA::PathRelinking::Selection::BESTSOLUTION;\n      } else if (sel == \"random\") {\n         params.pr_selection = BRKGA::PathRelinking::Selection::RANDOMELITE;\n      } else {\n         cout << \"Invalid individual selection for PR: \" << sel << \"\\n\";\n         exit(EXIT_FAILURE);\n      }\n   }\n\n   params.alpha_block_size = vm[\"alpha\"].as<double>();\n   params.pr_percentage = vm[\"pperc\"].as<double>();\n\n   return params;\n}\n   \nvoid printSupplyDemandIndicators(const Instance &inst) {\n   cout << \"Summary of supply/demand per service type:\\n\";\n   for (int s = 0; s < inst.numSkills(); ++s) {\n      int supply = 0, demand = 0;\n      for (int i = 1; i < inst.numNodes()-1; ++i) {\n         demand += inst.nodeReqSkill(i, s) ? 1 : 0;\n      }\n      for (int v = 0; v < inst.numVehicles(); ++v) {\n         supply += inst.vehicleHasSkill(v, s) ? 1 : 0;\n      }\n      cout << \"   Service type: \" << s << \" Qualified carers: \" << setw(3) << supply << \n         \" Service requests: \" << setw(4) << demand << \" Ratio = \" <<  double(supply)/demand<< \"\\n\";\n   }\n}\n\ntuple<double, double> computeEliteDiversity(const BRKGA::BRKGA_MP_IPR<SortingDecoder> &solver) {\n   int cnt = 0;\n   double mean = 0.0;\n   const auto npop = solver.getBrkgaParams().num_independent_populations;\n   const auto numElites = solver.getBrkgaParams().population_size * solver.getBrkgaParams().elite_percentage;\n   for (unsigned k = 0; k < npop; ++k) {\n      for (int i = 0; i < numElites; ++i) {\n         mean += solver.getFitness(k, i);\n         ++cnt;\n      }\n   }\n   mean /= cnt;\n   double stdev = 0.0;\n   for (unsigned k = 0; k < npop; ++k) {\n      for (int i = 0; i < numElites; ++i) {\n         stdev += pow(solver.getFitness(k, i) - mean, 2.0);\n      }\n   }\n   stdev /= cnt;\n   stdev = sqrt(stdev);\n   return make_tuple(mean, stdev);\n}\n", "meta": {"hexsha": "33723b7df9a08e531fc9cd334fda25b4ee7a8e48", "size": 19198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mainBrkgaMpIpr.cpp", "max_stars_repo_name": "afkummer/brkga-mp-ipr-hhcrsp-2021", "max_stars_repo_head_hexsha": "2770f1463df34c994dbb633c5b68e03f7b03fa5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mainBrkgaMpIpr.cpp", "max_issues_repo_name": "afkummer/brkga-mp-ipr-hhcrsp-2021", "max_issues_repo_head_hexsha": "2770f1463df34c994dbb633c5b68e03f7b03fa5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mainBrkgaMpIpr.cpp", "max_forks_repo_name": "afkummer/brkga-mp-ipr-hhcrsp-2021", "max_forks_repo_head_hexsha": "2770f1463df34c994dbb633c5b68e03f7b03fa5d", "max_forks_repo_licenses": ["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.9192307692, "max_line_length": 264, "alphanum_fraction": 0.5606313158, "num_tokens": 4752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.09009299579426375, "lm_q1q2_score": 0.04293648849891144}}
{"text": "/*=============================================================================\r\n    Spirit v1.6.0\r\n    Copyright (c) 2001-2003 Andy Elvey\r\n    Copyright (c) 2001-2003 Dan Nuffer\r\n    http://spirit.sourceforge.net/\r\n\r\n    Permission to copy, use, modify, sell and distribute this software is\r\n    granted provided this copyright notice appears in all copies. This\r\n    software is provided \"as is\" without express or implied warranty, and\r\n    with no claim as to its suitability for any purpose.\r\n=============================================================================*/\r\n//\r\n//  A very simple parser grammar .\r\n//  This parser parses a simple polynomial expression ( of the form\r\n//  aX^2 + bX^3 + ...  ) .\r\n//\r\n// Uses:  The Spirit parser framework, which was written by\r\n//  Joel de Guzman isis-tech.n3.net\r\n//\r\n\r\n//#define BOOST_SPIRIT_DEBUG  ///$$$ DEFINE THIS WHEN DEBUGGING $$$///\r\n\r\n#include <boost/spirit/core.hpp>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <vector>\r\n#include <string>\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nusing namespace boost::spirit;\r\nusing namespace std;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//----------------------------------------------------------------------------\r\n//  Start grammar definition\r\n//----------------------------------------------------------------------------\r\n\r\nstruct polynomial_grammar :\r\n    public grammar<polynomial_grammar>\r\n{\r\n    template <typename ScannerT>\r\n    struct definition\r\n    {\r\n        typedef rule<ScannerT> rule_t;\r\n\r\n        rule_t program, stmts, term, constant, sign, var, caret;\r\n        rule_t IDENT, STRING_LITERAL, VAR;\r\n\r\n        definition(polynomial_grammar const&)\r\n        {\r\n            //-----------------------------------------------------------------\r\n            // OPERATORS\r\n            //-----------------------------------------------------------------\r\n            chlit<>     PLUS('+');\r\n            chlit<>     MINUS('-');\r\n            chlit<>     CARET('^');\r\n\r\n            //-----------------------------------------------------------------\r\n            // TOKENS\r\n            //-----------------------------------------------------------------\r\n\r\n\r\n            IDENT =\r\n                as_lower_d\r\n                [\r\n                    lexeme_d\r\n                    [\r\n                        (alpha_p >> *(alnum_p | '_'))\r\n                    ]\r\n                ]\r\n            ;\r\n\r\n            STRING_LITERAL =\r\n                lexeme_d\r\n                [\r\n                    ch_p('\\'')\r\n                    >>  +(\r\n                            str_p(\"\\'\\'\")\r\n                            | anychar_p - ch_p('\\'')\r\n                         )\r\n                    >> ch_p('\\'')\r\n                ]\r\n            ;\r\n\r\n            VAR = as_lower_d[ lexeme_d[ alpha_p ] ] ;\r\n\r\n\r\n            //-----------------------------------------------------------------\r\n            // RULES\r\n            //-----------------------------------------------------------------\r\n\r\n            //  Now - the actual BNF grammar for the parser\r\n\r\n            program =\r\n                +(stmts)\r\n            ;\r\n\r\n            stmts =\r\n                ( term | constant )\r\n            ;\r\n\r\n            term =\r\n                +(\r\n                    !(sign)\r\n                    >> !(uint_p)\r\n                    >> VAR\r\n                    >> !(CARET)\r\n                    >> !(uint_p)\r\n                 )\r\n            ;   //  e.g. 3x^2\r\n\r\n            constant =\r\n                !(sign) >> +(uint_p)\r\n            ;\r\n\r\n            sign =\r\n                ( PLUS | MINUS )\r\n            ;\r\n\r\n            var =\r\n                VAR\r\n            ;\r\n\r\n            caret =\r\n                CARET\r\n            ;\r\n\r\n        }\r\n\r\n        rule_t const& start() const\r\n        {\r\n            return program;\r\n        }\r\n    };\r\n};\r\n\r\n\r\nint\r\nmain(int /*argc*/, char* /*argv[]*/)\r\n{\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\t A polynomial parser...\\n\\n\";\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"Type a polynomial (e.g. 3a^4 + 7a^5 - 8a^3 - 4a - 5) or\\n\"\r\n        << \"[q or Q] to quit\\n\\n\";\r\n\r\n\r\n    polynomial_grammar g;\r\n\r\n    string str;\r\n    while (getline(cin, str))\r\n    {\r\n        if (str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        if (parse(str.c_str(), g, space_p).full)\r\n        {\r\n            cout << \"parsing succeeded\\n\";\r\n        }\r\n        else\r\n        {\r\n            cout << \"parsing failed\\n\";\r\n        }\r\n    }\r\n\r\n    cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "3fa2bcfa48a134364bf7e9f9cd43ef2a5d3298db", "size": 4679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/polynomial.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/polynomial.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/spirit/example/fundamental/polynomial.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5235294118, "max_line_length": 80, "alphanum_fraction": 0.3120324856, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.10970576805636037, "lm_q1q2_score": 0.04222708244483068}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n// This C++ file compiles to binary code that can be linked to by your C program,\r\n// thanks to the extern \"C\" syntax used in the declarations in binary_library.h.\r\n\r\n#include \"binary_library.h\"\r\n\r\n#include <Eigen/Core>\r\n\r\nusing namespace Eigen;\r\n\r\n/************************* pointer conversion methods **********************************************/\r\n\r\n////// class MatrixXd //////\r\n\r\ninline MatrixXd& c_to_eigen(C_MatrixXd* ptr)\r\n{\r\n  return *reinterpret_cast<MatrixXd*>(ptr);\r\n}\r\n\r\ninline const MatrixXd& c_to_eigen(const C_MatrixXd* ptr)\r\n{\r\n  return *reinterpret_cast<const MatrixXd*>(ptr);\r\n}\r\n\r\ninline C_MatrixXd* eigen_to_c(MatrixXd& ref)\r\n{\r\n  return reinterpret_cast<C_MatrixXd*>(&ref);\r\n}\r\n\r\ninline const C_MatrixXd* eigen_to_c(const MatrixXd& ref)\r\n{\r\n  return reinterpret_cast<const C_MatrixXd*>(&ref);\r\n}\r\n\r\n////// class Map<MatrixXd> //////\r\n\r\ninline Map<MatrixXd>& c_to_eigen(C_Map_MatrixXd* ptr)\r\n{\r\n  return *reinterpret_cast<Map<MatrixXd>*>(ptr);\r\n}\r\n\r\ninline const Map<MatrixXd>& c_to_eigen(const C_Map_MatrixXd* ptr)\r\n{\r\n  return *reinterpret_cast<const Map<MatrixXd>*>(ptr);\r\n}\r\n\r\ninline C_Map_MatrixXd* eigen_to_c(Map<MatrixXd>& ref)\r\n{\r\n  return reinterpret_cast<C_Map_MatrixXd*>(&ref);\r\n}\r\n\r\ninline const C_Map_MatrixXd* eigen_to_c(const Map<MatrixXd>& ref)\r\n{\r\n  return reinterpret_cast<const C_Map_MatrixXd*>(&ref);\r\n}\r\n\r\n\r\n/************************* implementation of classes **********************************************/\r\n\r\n\r\n////// class MatrixXd //////\r\n\r\n\r\nC_MatrixXd* MatrixXd_new(int rows, int cols)\r\n{\r\n  return eigen_to_c(*new MatrixXd(rows,cols));\r\n}\r\n\r\nvoid MatrixXd_delete(C_MatrixXd *m)\r\n{\r\n  delete &c_to_eigen(m);\r\n}\r\n\r\ndouble* MatrixXd_data(C_MatrixXd *m)\r\n{\r\n  return c_to_eigen(m).data();\r\n}\r\n\r\nvoid MatrixXd_set_zero(C_MatrixXd *m)\r\n{\r\n  c_to_eigen(m).setZero();\r\n}\r\n\r\nvoid MatrixXd_resize(C_MatrixXd *m, int rows, int cols)\r\n{\r\n  c_to_eigen(m).resize(rows,cols);\r\n}\r\n\r\nvoid MatrixXd_copy(C_MatrixXd *dst, const C_MatrixXd *src)\r\n{\r\n  c_to_eigen(dst) = c_to_eigen(src);\r\n}\r\n\r\nvoid MatrixXd_copy_map(C_MatrixXd *dst, const C_Map_MatrixXd *src)\r\n{\r\n  c_to_eigen(dst) = c_to_eigen(src);\r\n}\r\n\r\nvoid MatrixXd_set_coeff(C_MatrixXd *m, int i, int j, double coeff)\r\n{\r\n  c_to_eigen(m)(i,j) = coeff;\r\n}\r\n\r\ndouble MatrixXd_get_coeff(const C_MatrixXd *m, int i, int j)\r\n{\r\n  return c_to_eigen(m)(i,j);\r\n}\r\n\r\nvoid MatrixXd_print(const C_MatrixXd *m)\r\n{\r\n  std::cout << c_to_eigen(m) << std::endl;\r\n}\r\n\r\nvoid MatrixXd_multiply(const C_MatrixXd *m1, const C_MatrixXd *m2, C_MatrixXd *result)\r\n{\r\n  c_to_eigen(result) = c_to_eigen(m1) * c_to_eigen(m2);\r\n}\r\n\r\nvoid MatrixXd_add(const C_MatrixXd *m1, const C_MatrixXd *m2, C_MatrixXd *result)\r\n{\r\n  c_to_eigen(result) = c_to_eigen(m1) + c_to_eigen(m2);\r\n}\r\n\r\n\r\n\r\n////// class Map_MatrixXd //////\r\n\r\n\r\nC_Map_MatrixXd* Map_MatrixXd_new(double *array, int rows, int cols)\r\n{\r\n  return eigen_to_c(*new Map<MatrixXd>(array,rows,cols));\r\n}\r\n\r\nvoid Map_MatrixXd_delete(C_Map_MatrixXd *m)\r\n{\r\n  delete &c_to_eigen(m);\r\n}\r\n\r\nvoid Map_MatrixXd_set_zero(C_Map_MatrixXd *m)\r\n{\r\n  c_to_eigen(m).setZero();\r\n}\r\n\r\nvoid Map_MatrixXd_copy(C_Map_MatrixXd *dst, const C_Map_MatrixXd *src)\r\n{\r\n  c_to_eigen(dst) = c_to_eigen(src);\r\n}\r\n\r\nvoid Map_MatrixXd_copy_matrix(C_Map_MatrixXd *dst, const C_MatrixXd *src)\r\n{\r\n  c_to_eigen(dst) = c_to_eigen(src);\r\n}\r\n\r\nvoid Map_MatrixXd_set_coeff(C_Map_MatrixXd *m, int i, int j, double coeff)\r\n{\r\n  c_to_eigen(m)(i,j) = coeff;\r\n}\r\n\r\ndouble Map_MatrixXd_get_coeff(const C_Map_MatrixXd *m, int i, int j)\r\n{\r\n  return c_to_eigen(m)(i,j);\r\n}\r\n\r\nvoid Map_MatrixXd_print(const C_Map_MatrixXd *m)\r\n{\r\n  std::cout << c_to_eigen(m) << std::endl;\r\n}\r\n\r\nvoid Map_MatrixXd_multiply(const C_Map_MatrixXd *m1, const C_Map_MatrixXd *m2, C_Map_MatrixXd *result)\r\n{\r\n  c_to_eigen(result) = c_to_eigen(m1) * c_to_eigen(m2);\r\n}\r\n\r\nvoid Map_MatrixXd_add(const C_Map_MatrixXd *m1, const C_Map_MatrixXd *m2, C_Map_MatrixXd *result)\r\n{\r\n  c_to_eigen(result) = c_to_eigen(m1) + c_to_eigen(m2);\r\n}\r\n", "meta": {"hexsha": "f21051a1d6974662e83785e84a1a1e7be7c0d8d2", "size": 4343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/demos/mix_eigen_and_c/binary_library.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/demos/mix_eigen_and_c/binary_library.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/demos/mix_eigen_and_c/binary_library.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 23.3494623656, "max_line_length": 103, "alphanum_fraction": 0.6728068156, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.0888202936060873, "lm_q1q2_score": 0.04198388517617295}}
{"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 \"aig_word.hpp\"\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/format.hpp>\n\nnamespace cirkit\n{\n\nusing namespace boost::assign;\n\naig_word to_aig_word( const aig_function& f )\n{\n  return aig_word(1u, f);\n}\n\nconst aig_function &to_aig_function( const aig_word& w )\n{\n  assert( w.size() == 1 );\n  return w[0];\n}\n\naig_word aig_create_wi( aig_graph& aig, const unsigned width, const std::string& name )\n{\n  assert( width > 0 && \"Width must not be < 0\" );\n  aig_word w;\n  for ( unsigned u = 0u; u < width; ++u )\n  {\n    const std::string n = (boost::format(\"%s[%d]\") % name % u).str();\n    w += ( aig_create_pi( aig, n ) );\n  }\n  return w;\n}\n\nvoid aig_create_wo( aig_graph& aig, const aig_word& w, const std::string& name )\n{\n  unsigned index = 0u;\n  for ( auto& e : w )\n  {\n    const std::string n = (boost::format(\"%s[%d]\") % name % index++).str();\n    aig_create_po( aig, e, n);\n  }\n}\n\naig_word aig_create_bvbin( aig_graph& aig, const std::string& value )\n{\n  assert( value.size() > 0u );\n  aig_word w( value.size() );\n  for ( std::size_t s = 0u; s < value.size(); ++s )\n  {\n    assert( value[s] == '0' || value[s] == '1' );\n    w[ value.size() - 1u - s] = aig_get_constant( aig, value[s] == '1' );\n  }\n  return w;\n}\n\naig_function aig_create_equal( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  aig_function result = aig_get_constant( aig, false );\n  for ( unsigned u = 0u; u < left.size(); ++u )\n  {\n    const aig_function current = aig_create_xor( aig, left[u], right[u] );\n    result = aig_create_or( aig, current, result );\n  }\n  return !result;\n}\n\naig_function aig_create_bvsgt( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0u );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n\n  aig_function not_l = !*li;\n  aig_function not_r = !*ri;\n  aig_function result = aig_create_and( aig, not_l, *ri );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n\n  for ( ++li, ++ri; li != end; ++li, ++ri )\n  {\n    not_r = !*ri;\n\n    const auto now_great = aig_create_and( aig, *li, not_r );\n    const auto now = aig_create_and( aig, equal, now_great );\n\n    const auto now_equal = !aig_create_xor( aig, *li, *ri );\n    equal = aig_create_and( aig, now_equal, equal );\n\n    result = aig_create_or( aig, result, now );\n  }\n\n  return result;\n}\n\naig_function aig_create_bvslt( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0u );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n\n  aig_function not_l = !*li;\n  aig_function result = aig_create_and( aig, *li, not_l );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n\n  for ( ++li, ++ri; li != end; ++li, ++ri )\n  {\n    not_l = !*li;\n\n    const auto now_less = aig_create_and( aig, not_l, *ri );\n    const auto now = aig_create_and( aig, equal, now_less );\n\n    const auto now_equal = !aig_create_xor( aig, *li, *ri );\n    equal = aig_create_and( aig, now_equal, equal );\n\n    result = aig_create_or( aig, result, now );\n  }\n\n  return result;\n}\n\naig_function aig_create_bvsge( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0u );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n\n  aig_function not_l = !*li;\n  aig_function not_r = !*ri;\n  aig_function great = aig_create_and( aig, not_l, *ri );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n  aig_function result = great;\n\n  for ( ++li, ++ri; li != end; ++li, ++ri )\n  {\n    not_r = !*ri;\n    const auto now_great = aig_create_and( aig, *li, not_r );\n    const auto now = aig_create_and( aig, equal, now_great );\n\n    const auto now_equal = !aig_create_xor( aig, *li, *ri );\n    equal = aig_create_and( aig, now_equal, equal );\n\n    result = aig_create_or( aig, result, now );\n  }\n  return aig_create_or( aig, result, equal );\n}\n\naig_function aig_create_bvsle( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0u );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n\n  aig_function not_r = !*ri;\n  aig_function less = aig_create_and( aig, *li, not_r );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n  aig_function result = less;\n\n  for ( ++li, ++ri; li != end; ++li, ++ri )\n  {\n    const aig_function not_l = !*li;\n    const aig_function now_less = aig_create_and( aig, not_l, *ri );\n    const aig_function now = aig_create_and( aig, equal, now_less );\n\n    const aig_function now_equal = !aig_create_xor( aig, *li, *ri );\n    equal = aig_create_and( aig, now_equal, equal );\n\n    result = aig_create_or( aig, result, now );\n  }\n  return aig_create_or( aig, result, equal );\n}\n\naig_function aig_create_bvule( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0 );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n  aig_function not_l = !*li;\n  aig_function less = aig_create_and( aig, not_l, *ri );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n  aig_function ret = less;\n\n  for (++li, ++ri; li != end; ++li, ++ri) {\n    not_l = !*li;\n    aig_function now_less = aig_create_and(aig, not_l, *ri);\n    aig_function now = aig_create_and(aig, equal, now_less);\n    aig_function now_equal = !aig_create_xor(aig, *li, *ri);\n    equal = aig_create_and(aig, now_equal, equal);\n    ret = aig_create_or(aig, ret, now);\n  }\n  ret = aig_create_or(aig, ret, equal);\n  return ret;\n}\n\naig_function aig_create_bvult( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0 );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n  aig_function not_l = !*li;\n  aig_function ret = aig_create_and(aig, not_l, *ri );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n\n  for (++li, ++ri; li != end; ++li, ++ri) {\n    not_l = !*li;\n    aig_function now_less = aig_create_and(aig, not_l, *ri);\n    aig_function now = aig_create_and(aig, equal, now_less);\n    aig_function now_equal = !aig_create_xor(aig, *li, *ri);\n    equal = aig_create_and(aig, now_equal, equal);\n    ret = aig_create_or(aig, ret, now);\n  }\n  return ret;\n}\n\naig_function aig_create_bvugt( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0 );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n  aig_function not_r = !*ri;\n  aig_function ret = aig_create_and(aig, *li, not_r );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n\n  for (++li, ++ri; li != end; ++li, ++ri) {\n    not_r = !*ri;\n    aig_function now_great = aig_create_and(aig, *li, not_r);\n    aig_function now = aig_create_and(aig, equal, now_great);\n    aig_function now_equal = !aig_create_xor(aig, *li, *ri);\n    equal = aig_create_and(aig, now_equal, equal);\n    ret = aig_create_or(aig, ret, now);\n  }\n  return ret;\n}\n\naig_function aig_create_bvuge( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  assert( left.size() > 0 );\n\n  auto li = left.rbegin(), ri = right.rbegin(), end = left.rend();\n  aig_function not_r = !*ri;\n  aig_function great = aig_create_and(aig, *li, not_r );\n  aig_function equal = !aig_create_xor( aig, *li, *ri );\n  aig_function ret = great;\n\n  for (++li, ++ri; li != end; ++li, ++ri) {\n    not_r = !*ri;\n    aig_function now_great = aig_create_and(aig, *li, not_r);\n    aig_function now = aig_create_and(aig, equal, now_great);\n    aig_function now_equal = !aig_create_xor(aig, *li, *ri);\n    equal = aig_create_and(aig, now_equal, equal);\n    ret = aig_create_or(aig, ret, now);\n  }\n  ret = aig_create_or(aig, ret, equal);\n  return ret;\n}\n\naig_word aig_create_bvand( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  aig_word result( left.size() );\n  for ( unsigned u = 0; u < left.size(); ++u ) {\n    result[u] = aig_create_and( aig, left[u], right[u] );\n  }\n  return result;\n}\n\naig_word aig_create_bvor( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  aig_word result( left.size() );\n  for ( unsigned u = 0; u < left.size(); ++u ) {\n    result[u] = aig_create_or( aig, left[u], right[u] );\n  }\n  return result;\n}\n\naig_word aig_create_bvxor( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n  aig_word result( left.size() );\n  for ( unsigned u = 0; u < left.size(); ++u ) {\n    result[u] = aig_create_xor( aig, left[u], right[u] );\n  }\n  return result;\n}\n\naig_word aig_create_bvadd( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n\n  aig_word result( left.size() );\n  aig_function carry = aig_get_constant( aig, false );\n\n  aig_function xor1, or1, and1, and2;\n  for ( unsigned u = 0u; u < left.size(); ++u )\n  {\n    xor1 = aig_create_xor( aig, left[u], right[u] );\n    result[u] = aig_create_xor( aig, xor1, carry );\n\n    // left & right | carry & ( left | right )\n    and1 = aig_create_and( aig, left[u], right[u] );\n    or1 = aig_create_or( aig, left[u], right[u] );\n    and2 = aig_create_and( aig, carry, or1 );\n    carry = aig_create_or( aig, and1, and2 );\n  }\n\n  return result;\n}\n\naig_word shift_left( aig_graph& aig, const aig_word& w, unsigned value )\n{\n  aig_word result( w.size() );\n  if ( value == 0u )\n  {\n    return w;\n  }\n  for ( unsigned i = 0u; i < w.size(); ++i )\n  {\n    if ( i < value )\n    {\n      result[ i ] = aig_get_constant( aig, false );\n    }\n    else\n    {\n      result[ i ] = w[ i - value ];\n    }\n  }\n  return result;\n}\n\naig_word aig_create_bvmul( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  assert( left.size() == right.size() );\n\n  aig_word result( left.size(), aig_get_constant( aig, false ) );\n\n  aig_word tmp;\n  for ( unsigned i = 0; i < result.size(); ++i )\n  {\n    tmp = aig_create_sext( aig, left.size() - 1u, to_aig_word( left[i] ) );\n    tmp = aig_create_bvand( aig, right, tmp );\n    tmp = shift_left( aig, tmp, i );\n\n    result = aig_create_bvadd( aig, result, tmp );\n  }\n  return result;\n}\n\naig_word aig_create_bvnot( aig_graph& aig, const aig_word& w )\n{\n  aig_word result( w.size() );\n  for ( unsigned u = 0u; u < w.size(); ++u )\n  {\n    result[ u ] = !w[ u ];\n  }\n  return result;\n}\n\naig_word aig_create_bvneg( aig_graph& aig, const aig_word& w )\n{\n  aig_word result( w.size(), aig_get_constant( aig, false ) );\n  result.front() = aig_get_constant( aig, true );\n  const aig_word tmp = aig_create_bvnot( aig, w );\n  return aig_create_bvadd( aig, tmp, result );\n}\n\naig_word aig_create_bvsub( aig_graph& aig, const aig_word& left, const aig_word& right )\n{\n  aig_word result( aig_create_bvneg( aig, right ) );\n  return aig_create_bvadd( aig, left, result );\n}\n\naig_word aig_create_sext( aig_graph& aig, const unsigned width, const aig_word& w )\n{\n  assert( w.size() > 0u );\n  aig_word result( w.size() + width, w.back() );\n  std::copy( w.begin(), w.end(), result.begin() );\n  return result;\n}\n\naig_word aig_create_zext( aig_graph& aig, const unsigned width, const aig_word& w )\n{\n  assert( w.size() > 0u );\n  aig_word result( w.size() + width, aig_get_constant( aig, false ) );\n  std::copy( w.begin(), w.end(), result.begin() );\n  return result;\n}\n\naig_word aig_create_ite( aig_graph& aig, const aig_function& cond, const aig_word& t, const aig_word& e )\n{\n  assert( t.size() == e.size() );\n  const std::size_t size = t.size();\n  aig_word result( size,  aig_get_constant( aig, false ) );\n  for ( unsigned u = 0u; u < size; ++u )\n  {\n    result[ u ] = aig_create_ite( aig, cond, t[ u ], e[ u ] );\n  }\n  return result;\n}\n\nstd::ostream& operator<<( std::ostream& os, const aig_word &w )\n{\n  os << \"[ \";\n  for ( const auto& it : w )\n  {\n    os << it << \" \";\n  }\n  os << \"]\";\n  return os;\n}\n\n}\n\n// Local Variables:\n// c-basic-offset: 2\n// eval: (c-set-offset 'substatement-open 0)\n// eval: (c-set-offset 'innamespace 0)\n// End:\n", "meta": {"hexsha": "ba215eca4a17de1e1171ac580d2256f4e80ad9db", "size": 13428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/aig_word.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/aig_word.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/aig_word.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": 29.7079646018, "max_line_length": 105, "alphanum_fraction": 0.6419422103, "num_tokens": 4374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.09401017771282379, "lm_q1q2_score": 0.04188431214961721}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\r\n#define BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\r\n\r\n#include <boost/units/pow.hpp>\r\n#include <boost/units/static_constant.hpp>\r\n\r\n#include <boost/units/systems/detail/constants.hpp>\r\n#include <boost/units/systems/si/amount.hpp>\r\n#include <boost/units/systems/si/area.hpp>\r\n#include <boost/units/systems/si/electric_charge.hpp>\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/frequency.hpp>\r\n#include <boost/units/systems/si/mass.hpp>\r\n#include <boost/units/systems/si/power.hpp>\r\n#include <boost/units/systems/si/solid_angle.hpp>\r\n#include <boost/units/systems/si/temperature.hpp>\r\n\r\n#include <boost/units/systems/si/codata/typedefs.hpp>\r\n\r\n/// \\file\r\n/// CODATA recommended values of fundamental physico-chemical constants\r\n/// CODATA 2006 values as of 2007/03/30\r\n\r\nnamespace boost {\r\n\r\nnamespace units { \r\n\r\nnamespace si {\r\n                            \r\nnamespace constants {\r\n\r\nnamespace codata {\r\n\r\n// PHYSICO-CHEMICAL\r\n/// Avogadro constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(N_A,quantity<inverse_amount>,6.02214179e23/mole,3.0e16/mole);\r\n/// atomic mass constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_u,quantity<mass>,1.660538782e-27*kilograms,8.3e-35*kilograms);\r\n/// Faraday constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(F,quantity<electric_charge_over_amount>,96485.3399*coulombs/mole,2.4e-3*coulombs/mole);\r\n/// molar gas constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(R,quantity<energy_over_temperature_amount>,8.314472*joules/kelvin/mole,1.5e-5*joules/kelvin/mole);\r\n/// Boltzmann constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(k_B,quantity<energy_over_temperature>,1.3806504e-23*joules/kelvin,2.4e-29*joules/kelvin);\r\n/// Stefan-Boltzmann constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(sigma_SB,quantity<power_over_area_temperature_4>,5.670400e-8*watts/square_meter/pow<4>(kelvin),4.0e-13*watts/square_meter/pow<4>(kelvin));\r\n/// first radiation constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1,quantity<power_area>,3.74177118e-16*watt*square_meters,1.9e-23*watt*square_meters);\r\n/// first radiation constant for spectral radiance\r\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1L,quantity<power_area_over_solid_angle>,1.191042759e-16*watt*square_meters/steradian,5.9e-24*watt*square_meters/steradian);\r\n/// second radiation constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(c_2,quantity<length_temperature>,1.4387752e-2*meter*kelvin,2.5e-8*meter*kelvin);\r\n/// Wien displacement law constant : lambda_max T\r\nBOOST_UNITS_PHYSICAL_CONSTANT(b,quantity<length_temperature>,2.8977685e-3*meter*kelvin,5.1e-9*meter*kelvin);\r\n/// Wien displacement law constant : nu_max/T\r\nBOOST_UNITS_PHYSICAL_CONSTANT(b_prime,quantity<frequency_over_temperature>,5.878933e10*hertz/kelvin,1.0e15*hertz/kelvin);\r\n\r\n} // namespace codata\r\n\r\n} // namespace constants    \r\n\r\n} // namespace si\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\r\n", "meta": {"hexsha": "2434e79e0f3550a35abb1b1d8d269b6b8c6d7bdc", "size": 3311, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/units/systems/si/codata/physico-chemical_constants.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/units/systems/si/codata/physico-chemical_constants.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 41.9113924051, "max_line_length": 169, "alphanum_fraction": 0.7801268499, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.09138210863486171, "lm_q1q2_score": 0.04177411711811414}}
{"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#ifndef BOOST_GRAPH_CUTHILL_MCKEE_HPP\n#define BOOST_GRAPH_CUTHILL_MCKEE_HPP\n\n#include <boost/config.hpp>\n#include <vector>\n#include <queue>\n#include <boost/pending/queue.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/property_map.hpp>\n\n/*\n  (Reverse) Cuthill-McKee Algorithm for matrix reordering\n */\n\nnamespace boost {\n\n  namespace detail {\n\n    // rcm_queue\n    //\n    // This is a custom queue type used in the\n    // reverse_cuthill_mckee_ordering algorithm.\n    // In addition to the normal queue operations, the\n    // rcm_queue provides:\n    // \n    //   int eccentricity() const;\n    //   value_type spouse() const;\n    // \n    template < class Vertex, class DegreeMap,\n               class Container = std::deque<Vertex> >\n    class rcm_queue : public std::queue<Vertex, Container> {\n      typedef std::queue<Vertex> base;\n    public:\n      typedef typename base::value_type value_type;\n      typedef typename base::size_type size_type;\n\n      /* SGI queue has not had a contructor queue(const Container&) */\n      inline rcm_queue(DegreeMap deg)\n        : _size(0), Qsize(1), eccen(-1), degree(deg) { }\n\n      inline void pop() {\n        if ( !_size ) \n          Qsize = base::size();\n\n        base::pop();\n        if ( _size == Qsize-1 ) {\n          _size = 0;\n          ++eccen;\n        } else \n          ++_size;\n\n      }\n\n      inline value_type& front() {\n        value_type& u =  base::front();\n        if ( _size == 0 ) \n          w = u;\n        else if (get(degree,u) < get(degree,w) )\n          w = u;\n        return u;\n      }\n      inline const value_type& front() const {\n        const value_type& u =  base::front();\n        if ( _size == 0 ) \n          w = u;\n        else if (get(degree,u) < get(degree,w) )\n          w = u;\n        return u;\n      }\n\n      inline value_type& top() { return front(); }\n      inline const value_type& top() const { return front(); }\n\n      inline size_type size() const { return base::size(); }\n\n      inline size_type eccentricity() const { return eccen; }\n      inline value_type spouse() const { return w; }\n\n    protected:\n      size_type _size;\n      size_type Qsize;\n      int eccen;\n      mutable value_type w;\n      DegreeMap degree;\n    };\n\n  } // namespace detail  \n\n  // Compute Pseudo peripheral\n  //\n  // To compute an approximated peripheral for a given vertex. \n  // Used in <tt>reverse_cuthill_mckee_ordering</tt> algorithm.\n  //\n  template <class Graph, class Vertex, class ColorMap, class DegreeMap>\n  Vertex \n  pseudo_peripheral_pair(Graph& G, const Vertex& u, int& ecc,\n                         ColorMap color, DegreeMap degree)\n  {\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n\n    detail::rcm_queue<Vertex, DegreeMap> Q(degree);\n\n    typename boost::graph_traits<Graph>::vertex_iterator ui, ui_end;\n    for (tie(ui, ui_end) = vertices(G); ui != ui_end; ++ui)\n      put(color, *ui, Color::white());\n    breadth_first_search(G, u, buffer(Q).color_map(color));\n\n    ecc = Q.eccentricity(); \n    return Q.spouse();\n  }\n\n  // Find a good starting node\n  //\n  // This is to find a good starting node for the\n  // reverse_cuthill_mckee_ordering algorithm. \"good\" is in the sense\n  // of the ordering generated by RCM.\n  //\n  template <class Graph, class Vertex, class Color, class Degree> \n  Vertex find_starting_node(Graph& G, Vertex r, Color color, Degree degree)\n  {\n    Vertex x, y;\n    int eccen_r, eccen_x;\n\n    x = pseudo_peripheral_pair(G, r, eccen_r, color, degree);\n    y = pseudo_peripheral_pair(G, x, eccen_x, color, degree);\n\n    while (eccen_x > eccen_r) {\n      r = x;\n      eccen_r = eccen_x;\n      x = y;\n      y = pseudo_peripheral_pair(G, x, eccen_x, color, degree);\n    }\n    return x;\n  }\n\n\n  // Reverse Cuthill-McKee algorithm with a given starting Vertex.\n  //\n  // This algorithm requires user to provide a starting vertex to\n  // compute RCM ordering.\n\n  template <class Graph, class OutputIterator,\n            class ColorMap, class DegreeMap>\n  OutputIterator\n  cuthill_mckee_ordering(Graph& g,\n                         typename graph_traits<Graph>::vertex_descriptor s,\n                         OutputIterator inverse_permutation, \n                         ColorMap color, DegreeMap degree)\n  {\n    typedef typename property_traits<DegreeMap>::value_type DS;\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\n    typename graph_traits<Graph>::vertex_iterator ui, ui_end;\n    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)\n      put(color, *ui, Color::white());\n\n    typedef indirect_cmp<DegreeMap, std::greater<DS> > Compare;\n    Compare comp(degree);\n\n    boost::queue<Vertex> bfs_queue;\n    std::priority_queue<Vertex, std::vector<Vertex>, Compare> \n      degree_queue(comp);\n    Vertex u, v;\n\n    // Like BFS, except the adjacent vertices are visited\n    // in increasing order of degree.\n    \n    put(color, s, Color::gray());\n    bfs_queue.push(s);\n    while (! bfs_queue.empty()) {\n      u = bfs_queue.top(); bfs_queue.pop();\n      *inverse_permutation++ = u;\n      typename graph_traits<Graph>::out_edge_iterator ei, ei_end;\n      for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {\n        v = target(*ei, g);\n        if (get(color, v) == Color::white()) {\n          put(color, v, Color::gray());\n          degree_queue.push(v);\n        }\n      }\n      while (!degree_queue.empty()) {\n        v = degree_queue.top(); degree_queue.pop();\n        bfs_queue.push(v);\n      }\n      put(color, u, Color::black());\n    } // while\n    return inverse_permutation;\n  }  \n  \n  template < class Graph, class OutputIterator, \n             class Color, class Degree >\n  inline OutputIterator \n  cuthill_mckee_ordering(Graph& G, OutputIterator inverse_permutation, \n                         Color color, Degree degree)\n  {\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename boost::graph_traits<Graph>::vertex_iterator   VerIter;\n    VerIter ri = vertices(G).first;\n    Vertex r = *ri;\n\n    //if G has several forests, how to let is cover all. ??\n\n    Vertex s = find_starting_node(G, r, color, degree);\n    return cuthill_mckee_ordering(G, s, inverse_permutation, color, degree);\n  }\n\n} // namespace boost\n\n\n#endif // BOOST_GRAPH_CUTHILL_MCKEE_HPP\n", "meta": {"hexsha": "285f06040302cc543266a752d67efd27a5514bc9", "size": 7818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/graph/cuthill_mckee_ordering.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/cuthill_mckee_ordering.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/graph/cuthill_mckee_ordering.hpp", "max_forks_repo_name": "Imperator-Knoedel/Sunset", "max_forks_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 32.1728395062, "max_line_length": 76, "alphanum_fraction": 0.6369915579, "num_tokens": 1912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.0888202966210113, "lm_q1q2_score": 0.040603018784973334}}
{"text": "/*\n * stepper_details.cpp\n *\n * This example demonstrates some details about the steppers in odeint.\n *\n *\n * Copyright 2011-2012 Karsten Ahnert\n * Copyright 2012 Mario Mulansky\n * Copyright 2013 Pascal Germroth\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <iostream>\n#include <boost/array.hpp>\n#include <boost/bind.hpp>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\nconst size_t N = 3;\n\ntypedef boost::array< double , N > state_type;\n\n//[ system_function_structure\nvoid sys( const state_type & /*x*/ , state_type & /*dxdt*/ , const double /*t*/ )\n{\n    // ...\n}\n//]\n\nvoid sys1( const state_type &/*x*/ , state_type &/*dxdt*/ , const double /*t*/ )\n{\n}\n\nvoid sys2( const state_type &/*x*/ , state_type &/*dxdt*/ , const double /*t*/ )\n{\n}\n\n\n//[ symplectic_stepper_detail_system_function\ntypedef boost::array< double , 1 > vector_type;\n\n\nstruct harm_osc_f1\n{\n    void operator()( const vector_type &p , vector_type &dqdt )\n    {\n        dqdt[0] = p[0];\n    }\n};\n\nstruct harm_osc_f2\n{\n    void operator()( const vector_type &q , vector_type &dpdt )\n    {\n        dpdt[0] = -q[0];\n    }\n};\n//]\n\n//[ symplectic_stepper_detail_system_class\nstruct harm_osc\n{\n    void f1( const vector_type &p , vector_type &dqdt ) const\n    {\n        dqdt[0] = p[0];\n    }\n\n    void f2( const vector_type &q , vector_type &dpdt ) const\n    {\n        dpdt[0] = -q[0];\n    }\n};\n//]\n\nint main( int argc , char **argv )\n{\n    using namespace std;\n\n    // Explicit stepper example\n    {\n        double t( 0.0 ) , dt( 0.1 );\n        state_type in , out , dxdtin , inout;\n        //[ explicit_stepper_detail_example\n        runge_kutta4< state_type > rk;\n        rk.do_step( sys1 , inout , t , dt );               // In-place transformation of inout\n        rk.do_step( sys2 , inout , t , dt );               // call with different system: Ok\n        rk.do_step( sys1 , in , t , out , dt );            // Out-of-place transformation\n        rk.do_step( sys1 , inout , dxdtin , t , dt );      // In-place tranformation of inout\n        rk.do_step( sys1 , in , dxdtin , t , out , dt );   // Out-of-place transformation\n        //]\n    }\n\n\n\n    // FSAL stepper example\n    {\n        double t( 0.0 ) , dt( 0.1 );\n        state_type in , in2 , in3 , out , dxdtin , dxdtout , inout , dxdtinout;\n        //[ fsal_stepper_detail_example\n        runge_kutta_dopri5< state_type > rk;\n        rk.do_step( sys1 , in , t , out , dt );\n        rk.do_step( sys2 , in , t , out , dt );         // DONT do this, sys1 is assumed\n\n        rk.do_step( sys2 , in2 , t , out , dt );\n        rk.do_step( sys2 , in3 , t , out , dt );        // DONT do this, in2 is assumed\n\n        rk.do_step( sys1 , inout , dxdtinout , t , dt );\n        rk.do_step( sys2 , inout , dxdtinout , t , dt );           // Ok, internal derivative is not used, dxdtinout is updated\n\n        rk.do_step( sys1 , in , dxdtin , t , out , dxdtout , dt );\n        rk.do_step( sys2 , in , dxdtin , t , out , dxdtout , dt ); // Ok, internal derivative is not used\n        //]\n    }\n\n\n    // Symplectic harmonic oscillator example\n    {\n        double t( 0.0 ) , dt( 0.1 );\n        //[ symplectic_stepper_detail_example\n        pair< vector_type , vector_type > x;\n        x.first[0] = 1.0; x.second[0] = 0.0;\n        symplectic_rkn_sb3a_mclachlan< vector_type > rkn;\n        rkn.do_step( make_pair( harm_osc_f1() , harm_osc_f2() ) , x , t , dt );\n        //]\n\n        //[ symplectic_stepper_detail_system_class_example\n        harm_osc h;\n        rkn.do_step( make_pair( boost::bind( &harm_osc::f1 , h , _1 , _2 ) , boost::bind( &harm_osc::f2 , h , _1 , _2 ) ) ,\n                x , t , dt );\n        //]\n    }\n\n    // Simplified harmonic oscillator example\n    {\n        double t = 0.0, dt = 0.1;\n        //[ simplified_symplectic_stepper_example\n        pair< vector_type , vector_type > x;\n        x.first[0] = 1.0; x.second[0] = 0.0;\n        symplectic_rkn_sb3a_mclachlan< vector_type > rkn;\n        rkn.do_step( harm_osc_f1() , x , t , dt );\n        //]\n\n        vector_type q = {{ 1.0 }} , p = {{ 0.0 }};\n        //[ symplectic_stepper_detail_ref_usage\n        rkn.do_step( harm_osc_f1() , make_pair( boost::ref( q ) , boost::ref( p ) ) , t , dt );\n        rkn.do_step( harm_osc_f1() , q , p , t , dt );\n        rkn.do_step( make_pair( harm_osc_f1() , harm_osc_f2() ) , q , p , t , dt );\n        //]\n    }\n    \n    // adams_bashforth_moulton stepper example\n    {\n        double t = 0.0 , dt = 0.1;\n        state_type inout;\n        //[ multistep_detail_example\n        adams_bashforth_moulton< 5 , state_type > abm;\n        abm.initialize( sys , inout , t , dt );\n        abm.do_step( sys , inout , t , dt );\n        //]\n        \n        //[ multistep_detail_own_stepper_initialization\n        abm.initialize( runge_kutta_fehlberg78< state_type >() , sys , inout , t , dt );\n        //]\n    }\n\n\n\n    // dense output stepper examples\n    {\n        double t = 0.0 , dt = 0.1;\n        state_type in;\n        //[ dense_output_detail_example\n        dense_output_runge_kutta< controlled_runge_kutta< runge_kutta_dopri5< state_type > > > dense;\n        dense.initialize( in , t , dt );\n        pair< double , double > times = dense.do_step( sys );\n        (void)times;\n        //]\n\n        state_type inout;\n        double t_start = 0.0 , t_end = 1.0;\n        //[ dense_output_detail_generation1\n        typedef boost::numeric::odeint::result_of::make_dense_output<\n            runge_kutta_dopri5< state_type > >::type dense_stepper_type;\n        dense_stepper_type dense2 = make_dense_output( 1.0e-6 , 1.0e-6 , runge_kutta_dopri5< state_type >() );\n        (void)dense2;\n        //]\n\n        //[ dense_output_detail_generation2\n        integrate_const( make_dense_output( 1.0e-6 , 1.0e-6 , runge_kutta_dopri5< state_type >() ) , sys , inout , t_start , t_end , dt );\n        //]\n    }\n\n\n    return 0;\n}\n", "meta": {"hexsha": "d4ae8bd1eef262e2720f2fa12783fc40a71a6aac", "size": 6002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/stepper_details.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/examples/stepper_details.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/examples/stepper_details.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 29.8606965174, "max_line_length": 138, "alphanum_fraction": 0.5756414528, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.08756383059393905, "lm_q1q2_score": 0.04036839516466702}}
{"text": "﻿/***\r\n八：变量模板与成员变量模板\r\n变量模板:Variable Templates。C++14新标准中引入的(一般放在.h头文件中）\r\n从感觉上，变量模板与函数模板有些类似，看起来象一个没有参数，但是有返回值的函数模板。\r\n三种零初始化方式（T表示一个类型）\r\na)T();       //比如int temp1 = int();\r\nb)T t = {};  //比如 int temp2 = {};\r\nc)T {};      //比如int temp3 = int{};\r\n\r\n（8.1）变量模板的特化\r\na)变量模板的全特化\r\n变量模板特化的时候，并不需要正在特化的类型（double）与这个变量模板的类型（char）保持一致。\r\nb)变量模板的偏特化\r\n（8.2）默认模板参数\r\n（8.3）非类型模板参数\r\n（8.4）变量模板的另一种形式\r\n（8.5）成员变量模板\r\n\r\n九：别名模板与成员别名模板\r\n别名模板 = \"Alias Templates\"，C++11新标准中引入的，引入的目的不但能简化书写，而且可以达到一些通过其他手段难以达到的效果。\r\n***/\r\n\r\n\r\n#include <iostream>\r\n#include <map>\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\nnamespace _nmsp1\r\n{\r\n\t//g_myvar的泛化版本\r\n\ttemplate<typename T>\r\n\tT g_myvar{};    //写成T g_myvar =0;也不会出现语法错误，但该写法一般只适合数值类型\r\n\t                //{}是一种对变量的初始化方式，叫做零初始化。int = 0，指针=nullptr,bool = false\r\n\t//全特化\r\n\ttemplate<>\r\n\tchar g_myvar<double>{};\r\n\r\n\t//偏特化\r\n\ttemplate<typename T>\r\n\tT g_myvar<T*>{120}; //要求T*必须依赖于T\r\n\t//T g_myvar<double*>{120};\r\n\r\n}\r\n\r\nnamespace _nmsp2\r\n{\r\n\t//g_myvar的泛化版本\r\n\ttemplate<typename T = int>\r\n\tT g_myvar;\r\n}\r\n\r\nnamespace _nmsp3\r\n{\r\n\ttemplate<typename T,int value>\r\n\tT g_myvar[value];\r\n}\r\n\r\nnamespace _nmsp4\r\n{\r\n\ttemplate <typename T>\r\n\tstruct B\r\n\t{\r\n\t\tconst static T value = { 160 }; //const也可以写成constexpr,{}也可以不加\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tint g_myvar4 = B<T>::value; //注意g_myvar4是个变量模板\r\n\r\n}\r\n\r\nnamespace _nmsp5\r\n{\r\n\ttemplate <typename T>\r\n\tclass D\r\n\t{\r\n\tpublic:\r\n\t\ttemplate <typename W>\r\n\t\tstatic W m_tpi; //静态成员变量模板声明\r\n\t};\r\n\ttemplate <typename T>\r\n\ttemplate <typename W>\r\n\tW D<T>::m_tpi = 5; //定义\r\n}\r\n\r\nnamespace _nmsp6\r\n{\r\n\t//别名模板\r\n\ttemplate<typename T>\r\n\tusing str_map_t = std::map<std::string, T>;\r\n\r\n\ttemplate<typename T>\r\n\tclass E\r\n\t{\r\n\t\t//成员别名模板\r\n\t\ttemplate<typename T>\r\n\t\tusing str_map_t = std::map<std::string, T>;\r\n\r\n\tpublic:\r\n\t\tstr_map_t<int> map1;\r\n\r\n\t};\r\n}\r\n\r\nint main()\r\n{\r\n\r\n\t//char* p{}; //nullptr,NULL\r\n\t//int q{}; //0\r\n\t/*char* p;\r\n\tint q;*/\r\n\t/*char* p = {};\r\n\tint q={};\r\n\r\n\tint temp1 = int();\r\n\tint temp2 = {};\r\n\tint temp3 = int{};\r\n\t*/\r\n\r\n\t//测试_nmsp1\r\n\t_nmsp1::g_myvar<float> = 15.6f;\r\n\t_nmsp1::g_myvar<int> = 13;\r\n\tcout << _nmsp1::g_myvar<float> << endl;\r\n\tcout << _nmsp1::g_myvar<int> << endl;\r\n\r\n\t\r\n\t_nmsp1::g_myvar<double> = '2';           //这个使用的就是刚刚特化版本的g_myvar变量模板\r\n\r\n\tcout << _nmsp1::g_myvar<double> << endl;\r\n\tprintf(\"%d\\n\", _nmsp1::g_myvar<double>);\r\n\r\n\tcout << _nmsp1::g_myvar<int*> << endl;\r\n\tcout << _nmsp1::g_myvar<int> << endl;\r\n\r\n\t//测试_nmsp2\r\n\t_nmsp2::g_myvar<int> = 13;\r\n\t_nmsp2::g_myvar<> = 26;                 //尖括号不能省略,_nmsp2::g_myvar<>等价于_nmsp2::g_myvar<int>\r\n\tcout << _nmsp2::g_myvar<int> << endl;\r\n\tcout << _nmsp2::g_myvar<> << endl;\r\n\r\n\t//测试_nmsp3\r\n\tfor (int i = 0; i < 15; ++i) //i = 0~14\r\n\t{\r\n\t\t_nmsp3::g_myvar<int,15>[i] = i;    //注意[]中的下标数字<=14，否则下标会越界。\r\n\t\t\t\t\t\t\t\t\t       //g_myvar<int,15>写法一出现就表示定义了g_myvar<int,15>[15]这个大小为15个元素的int类型数组。\r\n\t}\r\n\tfor (int i = 0; i < 15; ++i)\r\n\t{\r\n\t\tcout << _nmsp3::g_myvar<int, 15>[i] << endl;\r\n\t}\r\n\r\n\t//测试_nmsp4\r\n\tcout << _nmsp4::g_myvar4<int> << endl; //160,g_myvar4<int>相当于B<int>::value\r\n\t_nmsp4::g_myvar4<int> = 152;\r\n\tcout << _nmsp4::g_myvar4<int> << endl; //152\r\n\tcout << _nmsp4::B<int>::value << endl; //160\r\n\t\r\n\r\n\t//测试_nmsp5\r\n\tcout << _nmsp5::D<float>::m_tpi<int> << endl;\r\n\t_nmsp5::D<float>::m_tpi<int> = 150;\r\n\tcout << _nmsp5::D<float>::m_tpi<int> << endl;\r\n\r\n\t//测试_nmsp6\r\n\t_nmsp6::str_map_t<int> map1;\r\n\tmap1.insert({\"first\",1});\r\n\tmap1.insert({\"second\",2 });\r\n\r\n\t_nmsp6::E<float> obja;\r\n\tobja.map1.insert({ \"first\",1 });\r\n\tobja.map1.insert({ \"second\",8 });\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "2fdebdae361c0bef02f529b8e59032c81c7198f8", "size": 3522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/209.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/209.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/209.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 19.8983050847, "max_line_length": 92, "alphanum_fraction": 0.5999432141, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.14414885303274058, "lm_q1q2_score": 0.040110397660769175}}
{"text": "/*\n==============================================================================\nKratosStructuralApplication \nA library based on:\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, Janosch Stascheit, Felix Nagel \npooyan@cimne.upc.edu \nrrossi@cimne.upc.edu\njanosch.stascheit@rub.de\nnagel@sd.rub.de\n- CIMNE (International Center for Numerical Methods in Engineering),\nGran Capita' s/n, 08034 Barcelona, Spain\n- Ruhr-University Bochum, Institute for Structural Mechanics, Germany\n\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 OWNERS.\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*   Last Modified by:    $Author: janosch $\n*   Date:                $Date: 2009-01-14 09:23:49 $\n*   Revision:            $Revision: 1.5 $\n*\n* ***********************************************************/\n\n// System includes \n\n\n// External includes \n\n// Project includes \n// #include \"includes/define.h\"\n#include \"custom_elements/kinematic_linear.h\"\n#include \"utilities/math_utils.h\"\n#include \"custom_utilities/sd_math_utils.h\"\n\n#include <boost/timer.hpp>\n\nnamespace Kratos\n{\n    namespace KinematicLinearAuxiliaries\n    {\n        Matrix msB(0,0);\n#ifdef _OPENMP\n#pragma omp threadprivate(msB)\n#endif\n        Matrix msTanC(0,0);\n#ifdef _OPENMP\n#pragma omp threadprivate(msTanC)\n#endif\n        Vector msStrainVector(0);\n#ifdef _OPENMP\n#pragma omp threadprivate(msStrainVector)\n#endif\n        Vector msStressVector(0);\n#ifdef _OPENMP\n#pragma omp threadprivate(msStressVector)\n#endif\n        Matrix msDN_DX(0,0);   \n#ifdef _OPENMP\n#pragma omp threadprivate(msDN_DX)\n#endif\n        Matrix msCurrentDisp(0,0);\n#ifdef _OPENMP\n#pragma omp threadprivate(msCurrentDisp)\n#endif\n    }\n\n    using namespace KinematicLinearAuxiliaries;\n\n\n    KinematicLinear::KinematicLinear(IndexType NewId, \n            GeometryType::Pointer pGeometry)\n    : Element(NewId, pGeometry)\n    {\n        //DO NOT ADD DOFS HERE!!!\n        //THIS IS THE DEFAULT CONSTRUCTOR\n    }\n    \n    /**\n    * A simple kinematic linear 3D element for the solution\n    * of the momentum balance in structural mechanics.\n    * This element is used for students training at the Ruhr University Bochum.\n    * Therefore it may includes comments that are obvious for the \n    * experienced user.\n    */\n    KinematicLinear::KinematicLinear(IndexType NewId, \n            GeometryType::Pointer pGeometry,  PropertiesType::Pointer pProperties)\n    : Element(NewId, pGeometry, pProperties)\n    {\n        //DEFINE HERE THE INTEGRATION METHOD (the number of integration points to be used)\n        //see /kratos/source/integration_rules.cpp for further details\n        mThisIntegrationMethod= GeometryData::GI_GAUSS_1;//default method\n        //m... declares that this is a member variable initialized in the header file\n        //select Integration Method for 8 node hexahedron\n        if(GetGeometry().size()== 8 )\n            mThisIntegrationMethod= GeometryData::GI_GAUSS_3;//methods for hexahedra elements\n        \n        //select Integration Method for 27 and 20 nodes\n        if(GetGeometry().size()== 27 || GetGeometry().size()== 20)\n            mThisIntegrationMethod= GeometryData::GI_GAUSS_3;//methods for hexahedra elements\n        \n        //select Integration Method for 10 and 4 node tetrahedron\n        if(GetGeometry().size()== 4 || GetGeometry().size()== 10)\n            mThisIntegrationMethod= GeometryData::GI_GAUSS_5;//methods for tetrahedra elements\n    }\n\n    Element::Pointer KinematicLinear::Create(IndexType NewId, \n            NodesArrayType const& ThisNodes,  PropertiesType::Pointer pProperties) const\n    {\n        return Element::Pointer(new KinematicLinear(NewId, GetGeometry().Create(ThisNodes), \n                                pProperties));\n    }\n\n\t//************************************************************************************\n\t//************************************************************************************\n\t//THIS IS THE DESTRUCTOR, as we use UBLAS classes, we don't have to care about garbage collecting\n\t//************************************************************************************\n\t//************************************************************************************\n    KinematicLinear::~KinematicLinear()\n    {\n    }\n    \n    void KinematicLinear::ResizeAndInitializeAuxiliaries()\n    {\n        unsigned int dimension = GetGeometry().WorkingSpaceDimension();\n        unsigned int dim2 = GetGeometry().size()*dimension;\n        unsigned int StrainSize;\n        if (dimension==3) \n            StrainSize = 6;\n        else \n            KRATOS_ERROR(std::logic_error, \"KinematicLinear cannot be used for other than 3D problems\" , \"\");\n        if(msB.size2() != dim2)\n        {\n            msB.resize(StrainSize,dim2,false);\n            msTanC.resize(StrainSize,StrainSize,false);\n            msStrainVector.resize(StrainSize,false);\n            msStressVector.resize(StrainSize,false);\n            msDN_DX.resize(GetGeometry().size(),dimension,false);\n            msCurrentDisp.resize(GetGeometry().size(),dimension,false);\n        }\n    }\n\n\t/**\n    * Initialization of the element, called at the begin of each simulation.\n    * Membervariables and the Material law are initialized here\n    */\n    void KinematicLinear::Initialize()\n    {\n        KRATOS_TRY//EXCEPTION HANDLING (see corresponing KRATOS_CATCH(\"\") )\n                \n        //dimension of the problem\n\t\tunsigned int dim = GetGeometry().WorkingSpaceDimension();\n        //number of integration points used, mThisIntegrationMethod refers to the\n        //integration method defined in the constructor\n       \tconst GeometryType::IntegrationPointsArrayType& integration_points =\n                GetGeometry().IntegrationPoints(mThisIntegrationMethod);\n        \n        //initializing the Jacobian, the inverse Jacobian and Jacobians determinant in the reference \n        // configuration\n        GeometryType::JacobiansType J0(integration_points.size());\n        mInvJ0.resize(integration_points.size());\n        \n        for(unsigned int i=0; i< integration_points.size(); i++)\n        {\n            mInvJ0[i].resize(dim,dim,false);\n            noalias(mInvJ0[i])= ZeroMatrix(dim,dim);\n        }\n        \n        mDetJ0.resize(integration_points.size(),false);\n        noalias(mDetJ0)= ZeroVector(integration_points.size());\n        \n        //calculating the Jacobian\n        J0 = GetGeometry().Jacobian(J0, mThisIntegrationMethod);\n        \n        //calculating the inverse Jacobian\n        for(unsigned int PointNumber = 0; PointNumber<integration_points.size(); PointNumber++)\n        {\n            //calculating and storing inverse of the jacobian and the parameters needed\n            MathUtils<double>::InvertMatrix(J0[PointNumber],mInvJ0[PointNumber],mDetJ0[PointNumber]);\n        }\n        \n        //SetUpInitialisplacement for StressFreeActivation of Elements\n        mInitialDisp.resize(GetGeometry().size(),dim,false);\n        for(unsigned int node = 0; node< GetGeometry().size(); node++)  \n                for(unsigned int i = 0; i< 3; i++)  \n                        mInitialDisp(node, i)= GetGeometry()[node].GetSolutionStepValue(DISPLACEMENT)[i];\n        //Initialization of the constitutive law vector and \n        // declaration, definition and initialization of the material \n        // lwas at each integration point\n        if(mConstitutiveLawVector.size() != integration_points.size())\n        {\n            mConstitutiveLawVector.resize(integration_points.size());\n            InitializeMaterial();\n        }\n\n//just for testing the unsaturated soil element\nfor(unsigned int i=0; i< GetGeometry().size(); i++)\n{\n        GetGeometry()[i].GetSolutionStepValue(TEMPERATURE)= 0.0;\n}\n\n        KRATOS_CATCH(\"\")\n    }\n\n\t/**\n    * Calculate double Variables at each integration point, used for postprocessing etc.\n    * @param rVariable Global name of the variable to be calculated\n    * @param output Vector to store the values on the qudrature points, output of the method \n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::CalculateOnIntegrationPoints(const Variable<double>& rVariable, Vector& Output, \n            const ProcessInfo& rCurrentProcessInfo)\n    {\n        if(Output.size() != GetGeometry().IntegrationPoints(mThisIntegrationMethod).size())\n            Output.resize(GetGeometry().IntegrationPoints(mThisIntegrationMethod).size(),false);\n        for(unsigned int ii = 0; ii<mConstitutiveLawVector.size(); ii++)\n            Output[ii] = mConstitutiveLawVector[ii]->GetValue( rVariable );\n    }\n    \n    /**\n    * Calculate Vector Variables at each integration point, used for postprocessing etc.\n    * @param rVariable Global name of the variable to be calculated\n    * @param output Vector to store the values on the qudrature points, output of the method \n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::CalculateOnIntegrationPoints(const Variable<Vector>& rVariable, \n            std::vector<Vector>& Output, const ProcessInfo& rCurrentProcessInfo)\n    {\n        if(Output.size() != GetGeometry().IntegrationPoints(mThisIntegrationMethod).size())\n            Output.resize(GetGeometry().IntegrationPoints(mThisIntegrationMethod).size());\n        for(unsigned int ii = 0; ii<mConstitutiveLawVector.size(); ii++)\n            Output[ii] = mConstitutiveLawVector[ii]->GetValue( rVariable );\n    }\n    \n    /**\n    * Calculate Matrix Variables at each integration point, used for postprocessing etc.\n    * @param rVariable Global name of the variable to be calculated\n    * @param output Vector to store the values on the qudrature points, output of the method \n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::CalculateOnIntegrationPoints(const Variable<Matrix>& rVariable, \n            std::vector<Matrix>& Output, const ProcessInfo& rCurrentProcessInfo)\n    {\n        KRATOS_TRY\n                \n//         unsigned int number_of_nodes = GetGeometry().size();\n//         unsigned int dim= 3;\n        \n        ResizeAndInitializeAuxiliaries();\n        \n//         std::cout << \"Calculating Values on integration points in element: \" << Id() <<std::endl;\n        \n        //reading integration points and local gradients\n        const GeometryType::IntegrationPointsArrayType& integration_points =\n                GetGeometry().IntegrationPoints(mThisIntegrationMethod);\n        const Matrix& Ncontainer = GetGeometry().ShapeFunctionsValues(mThisIntegrationMethod);\n        \n        if(Output.size() != integration_points.size())\n            Output.resize(integration_points.size());\n        \n        const GeometryType::ShapeFunctionsGradientsType& DN_De =   \n                GetGeometry().ShapeFunctionsLocalGradients(mThisIntegrationMethod);\n        \n        //Current displacements\n        for( unsigned int node=0; node < GetGeometry().size(); node++ )\n        {\n            msCurrentDisp(node,0) = GetGeometry()[node].GetSolutionStepValue( DISPLACEMENT_X );\n            msCurrentDisp(node,1) = GetGeometry()[node].GetSolutionStepValue( DISPLACEMENT_Y );\n            msCurrentDisp(node,2) = GetGeometry()[node].GetSolutionStepValue( DISPLACEMENT_Z );\n        }\n        \n        //Declaration of the integration weight\n        double Weight;\n        \n        //loop over all integration points\n        for(unsigned int PointNumber = 0; PointNumber<integration_points.size(); PointNumber++)\n        {\n//             noalias(msDN_DX)= ZeroMatrix(number_of_nodes, dim);\n            noalias(msDN_DX)= prod(DN_De[PointNumber],mInvJ0[PointNumber]);\n            //Initializing B_Operator at the current integration point\n            CalculateBoperator(msB, msDN_DX);\n            \n            //calculate strain\n            CalculateStrain(msB, msCurrentDisp, msStrainVector);\n            //assign the integration weight at the current integration point\n            Weight= integration_points[PointNumber].Weight();\n            \n            //calculate stress\n            mConstitutiveLawVector[PointNumber]->UpdateMaterial( msStrainVector,\n                    GetProperties(), GetGeometry(), row(Ncontainer,PointNumber), rCurrentProcessInfo );\n            mConstitutiveLawVector[PointNumber]->CalculateStress(msStrainVector, msStressVector);\n            \n            if(Output[PointNumber].size2() != msStrainVector.size())\n                Output[PointNumber].resize(1,msStrainVector.size(),false);\n            \n            if(rVariable==GREEN_LAGRANGE_STRAIN_TENSOR)\n            {\n                for(unsigned int ii = 0; ii<msStrainVector.size(); ii++)\n                    Output[PointNumber](0,ii) = msStrainVector[ii];\n            }\n            else if(rVariable==PK2_STRESS_TENSOR)\n            {\n                for(unsigned int ii = 0; ii<msStrainVector.size(); ii++)\n                    Output[PointNumber](0,ii) = msStressVector[ii];\n            }\n            else if(rVariable==INSITU_STRESS)\n            {\n                row(Output[PointNumber],0) = mConstitutiveLawVector[PointNumber]->GetValue(INSITU_STRESS);\n            }\n//             std::cout << msStressVector[2] << \"\\t\";\n        }\n//         std::cout << std::endl;\n        KRATOS_CATCH(\"\")\n    }\n\t/**\n    * Initialization of the Material law at each integration point\n    */\n    void KinematicLinear::InitializeMaterial()\n    {\n        KRATOS_TRY\n        for( unsigned int i=0; i<mConstitutiveLawVector.size(); i++ )\n        {\n            mConstitutiveLawVector[i] = GetProperties()[CONSTITUTIVE_LAW]->Clone();\n            mConstitutiveLawVector[i]->InitializeMaterial(GetProperties(), GetGeometry(), row(GetGeometry().ShapeFunctionsValues(mThisIntegrationMethod), i) );\n        }\n\t\tKRATOS_CATCH(\"\")\n    } \n\t/**\n    * THIS is the main method here the integration in space (loop over the integration points) is done,\n    * the algorithmic tangent and the (inner and outer) load vector is computed\n    * @param rLeftHandSideMatrix algorithmic tangent, size (number_of_nodes*dim)*(number_of_nodes*dim)\n    * @param rRightHandSideVector (inner and outer) load vector, size (number_of_nodes*dim)\n    * @param rCurrentProcessInfo\n    * @param CalculateStiffnessMatrixFlag true: algorithmic tangent has to be computed\n    * @param CalculateResidualVectorFlag true: load vector has to be computed\n    */\n    void KinematicLinear::CalculateAll(MatrixType& rLeftHandSideMatrix, \n            VectorType& rRightHandSideVector,ProcessInfo& rCurrentProcessInfo,\n            bool CalculateStiffnessMatrixFlag,bool CalculateResidualVectorFlag)\n    {\n         KRATOS_TRY\n                 \n//          boost::timer element_time;\n         \n//          int counter = 0;\n         \n//          for( int i=0; i<1000; i++ )\n//          {\n             \n\n\n         unsigned int number_of_nodes = GetGeometry().size();\n         unsigned int dim = GetGeometry().WorkingSpaceDimension();\n         \n         ResizeAndInitializeAuxiliaries();\n\n         //this is the size of the elements stiffness matrix/force vector\n         unsigned int MatSize=(number_of_nodes*dim);      \n\n         if (CalculateStiffnessMatrixFlag == true) //calculation of the matrix is required\n         {\n             //resize the LHS=StiffnessMatrix if its size is not correct\n             if(rLeftHandSideMatrix.size1() != MatSize)\n                 rLeftHandSideMatrix.resize(MatSize,MatSize,false);\n             noalias(rLeftHandSideMatrix) = ZeroMatrix(MatSize,MatSize); //resetting LHS\n         }\n         \n         //resizing as needed the RHS\n         if (CalculateResidualVectorFlag == true) //calculation of the matrix is required\n         {\n             //resize the RHS=force vector if its size is not correct\n             if(rRightHandSideVector.size() != MatSize)\n                 rRightHandSideVector.resize(MatSize,false);\n             noalias(rRightHandSideVector) = ZeroVector(MatSize); //resetting RHS    \n         }\n         \n         //reading integration points and local gradients\n         const GeometryType::IntegrationPointsArrayType& integration_points = GetGeometry().IntegrationPoints(mThisIntegrationMethod);\n         const GeometryType::ShapeFunctionsGradientsType& DN_De = GetGeometry().ShapeFunctionsLocalGradients(mThisIntegrationMethod);\n         const Matrix& Ncontainer = GetGeometry().ShapeFunctionsValues(mThisIntegrationMethod);\n         \n         //Current displacements\n         for( unsigned int node=0; node < GetGeometry().size(); node++ )\n         {\n             msCurrentDisp(node,0) = GetGeometry()[node].GetSolutionStepValue( DISPLACEMENT_X );\n             msCurrentDisp(node,1) = GetGeometry()[node].GetSolutionStepValue( DISPLACEMENT_Y );\n             msCurrentDisp(node,2) = GetGeometry()[node].GetSolutionStepValue( DISPLACEMENT_Z );\n         }\n//         Vector N_DISP(number_of_nodes);\n        \n        //Declaration of the integration weight\n        double Weight;\n        \n        //Body force\n//         Vector BodyForce;\n\n        //Declaration of the Strain Tensor at current integration point (3 times 3)\n//         Vector StrainVector;\n\n        //Declaration of the Stress Tensor at current integration point (3 times 3)\n//         Vector StressVector;\n\n        //Initialization of Jacobian at current integration point\n//         double DetJ=0.0;\n\n        /////////////////////////////////////////////////////////////////////////\n        //// Integration in space over quadrature points\n        /////////////////////////////////////////////////////////////////////////\n        for(unsigned int PointNumber = 0; PointNumber<integration_points.size(); PointNumber++)\n        {  \n\n\t\t\tnoalias(msDN_DX)= prod(DN_De[PointNumber],mInvJ0[PointNumber]);\n            //Initializing B_Operator at the current integration point\n            CalculateBoperator(msB, msDN_DX);\n            \n            //calculate strain\n            CalculateStrain(msB, msCurrentDisp, msStrainVector);\n\t\t\t//assign the integration weight at the current integration point\n            Weight= integration_points[PointNumber].Weight();\n            \n            //calculate stress\n            mConstitutiveLawVector[PointNumber]->UpdateMaterial( msStrainVector,\n                    GetProperties(), GetGeometry(), row(Ncontainer,PointNumber), rCurrentProcessInfo );\n            mConstitutiveLawVector[PointNumber]->CalculateStress(msStrainVector, msStressVector);\n            \n            if (CalculateStiffnessMatrixFlag == true) //calculation of the matrix is required\n            {\n                //calculate material tangent\n                mConstitutiveLawVector[PointNumber]->CalculateConstitutiveMatrix(msStrainVector, msTanC);\n                //calculate stiffness matrix\n                noalias(rLeftHandSideMatrix) +=\n                        prod(trans(msB),(Weight*mDetJ0[PointNumber])*Matrix(prod(msTanC,msB)) );\n                //CalculateStiffnesMatrix(rLeftHandSideMatrix, msTanC, msB, Weight, mDetJ0[PointNumber]);\n            }\n            if (CalculateResidualVectorFlag == true) \n            {\n//                 //contribution to external forces \n//                 BodyForce = GetProperties()[BODY_FORCE];\n                //Calculation of Loadvector\n                AddBodyForcesToRHS(rRightHandSideVector, row(Ncontainer,PointNumber), Weight, mDetJ0[PointNumber] );\n                AddInternalForcesToRHS(rRightHandSideVector, msB, msStressVector, Weight, mDetJ0[PointNumber]);\n            }\n\n\t\t\t///////////////////////////////////////////////////////////////////////\n\t\t\t// END Integration in space sum_(beta=0)^(number of quadrature points)\n\t\t\t///////////////////////////////////////////////////////////////////////\n        }\n// KRATOS_WATCH(rRightHandSideVector);\n// KRATOS_WATCH(rLeftHandSideMatrix);\n\n//         counter++;\n        \n//        }//end of repetition\n//         std::cout << \"Element Time x \" <<counter << \": \" << element_time.elapsed() << std::endl;\n//         std::cout << \"number of integration points: \" << GetGeometry().IntegrationPoints(mThisIntegrationMethod).size() << std::endl;\n\n\n        KRATOS_CATCH(\"\")\n    }\n\t/**\n    * THIS method is called from the scheme during the iteration loop, it calls the CalculateAll()\n    * method with CalculateStiffnessMatrixFlag = false and CalculateResidualVectorFlag = true\n    * @param rRightHandSideVector (inner and outer) load vector, size (number_of_nodes*dim)\n    * @param rCurrentProcessInfo\n    */\n     void KinematicLinear::CalculateRightHandSide(VectorType& rRightHandSideVector, \n             ProcessInfo& rCurrentProcessInfo)\n      {\n\t   //calculation flags\n           bool CalculateStiffnessMatrixFlag = false;\n           bool CalculateResidualVectorFlag = true;\n           MatrixType temp = Matrix();\n\t\t\n           CalculateAll(temp, rRightHandSideVector, rCurrentProcessInfo, CalculateStiffnessMatrixFlag,  CalculateResidualVectorFlag);\n       }\t\n\t/**\n    * THIS method is called from the scheme during the iteration loop, it calls the CalculateAll()\n    * method with CalculateStiffnessMatrixFlag = true and CalculateResidualVectorFlag = true\n    * @param rLeftHandSideMatrix algorithmic tangent, size (number_of_nodes*dim)*(number_of_nodes*dim)\n    * @param rRightHandSideVector (inner and outer) load vector, size (number_of_nodes*dim)\n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, \n                VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo)\n    {\n\t   //calculation flags\n            bool CalculateStiffnessMatrixFlag = true;\n            bool CalculateResidualVectorFlag = true;\n            CalculateAll(rLeftHandSideMatrix, rRightHandSideVector, rCurrentProcessInfo, \n                     CalculateStiffnessMatrixFlag,CalculateResidualVectorFlag);\n    }\n\t/**\n    * THIS method is called from the scheme after each solution step, here the time step\n    * start and end point variables can be transferred n --> n+1\n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::FinalizeSolutionStep(ProcessInfo& CurrentProcessInfo)\n    {\n         //reading integration points and local gradients\n         const GeometryType::IntegrationPointsArrayType& integration_points = GetGeometry().IntegrationPoints(mThisIntegrationMethod);\n\n         for(unsigned int Point=0; Point< integration_points.size(); Point++)\n         {\n            mConstitutiveLawVector[Point]->FinalizeSolutionStep(GetProperties(), GetGeometry(), row( GetGeometry().ShapeFunctionsValues(mThisIntegrationMethod),Point), CurrentProcessInfo);\n         }\n//                 Matrix Dummy_Matrix(3,3);\n//                 noalias(Dummy_Matrix)= mConstitutiveLawVector[0]->GetValue(PK2_STRESS_TENSOR);\n                Vector Dummy_Vector(5);\n                noalias(Dummy_Vector)= mConstitutiveLawVector[0]->GetValue(INTERNAL_VARIABLES);\n                for(unsigned int i=0; i< GetGeometry().size(); i++)\n                {\n                        GetGeometry()[i].GetSolutionStepValue(MOMENTUM_X)= Dummy_Vector(0);\n                        GetGeometry()[i].GetSolutionStepValue(MOMENTUM_Y)= Dummy_Vector(1);\n                        GetGeometry()[i].GetSolutionStepValue(MOMENTUM_Z)= Dummy_Vector(2);\n                        GetGeometry()[i].GetSolutionStepValue(PRESSURE)= Dummy_Vector(3);\n                        GetGeometry()[i].GetSolutionStepValue(ERROR_RATIO)= Dummy_Vector(4);\n                }\n\n     }\n\n        /**\n    * THIS method is called from the scheme at the start of each solution step\n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::InitializeSolutionStep(ProcessInfo& CurrentProcessInfo)\n    {\n         //reading integration points and local gradients\n         const GeometryType::IntegrationPointsArrayType& integration_points = GetGeometry().IntegrationPoints(mThisIntegrationMethod);\n\n         for(unsigned int Point=0; Point< integration_points.size(); Point++)\n         {\n            mConstitutiveLawVector[Point]->InitializeSolutionStep(GetProperties(), GetGeometry(), row( GetGeometry().ShapeFunctionsValues(mThisIntegrationMethod),Point), CurrentProcessInfo);\n\n//            mConstitutiveLawVector[Point]->SetValue(SUCTION, GetGeometry()[0].GetSolutionStepValue(TEMPERATURE),CurrentProcessInfo );\n         }\n    }\n\t/**\n    * returns the used integration method \n    */\n\tKinematicLinear::IntegrationMethod KinematicLinear::GetIntegrationMethod()\n\t{\n\t\t\treturn mThisIntegrationMethod;\n\t}\n\t/**\n    * not used\n    */\n    void KinematicLinear::CalculateAndAddExtForceContribution(const Vector& N, \n                const ProcessInfo& CurrentProcessInfo, Vector& BodyForce, VectorType& rRightHandSideVector, \n                double weight)\n    {\n            KRATOS_TRY\n\n            KRATOS_CATCH(\"\")\n    }\n\t/**\n    * Informations for the builder and solver to assemble the global vectors and matrices.\n    * Here a Vector containing the EquationIds of the differnt Dofs is created\n    * @param rResult Vector of the EquationIds\n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::EquationIdVector(EquationIdVectorType& rResult, \n                ProcessInfo& CurrentProcessInfo)\n    {\n        unsigned int dim = (GetGeometry().WorkingSpaceDimension());//3 displacement dofs \n        unsigned int MatSize = GetGeometry().size()*dim;\n        if(rResult.size() != MatSize)\n            rResult.resize(MatSize,false);\n\n        for (unsigned int i=0 ;i<GetGeometry().size() ;i++)\n        {\n                    int index = i*dim;\n                    rResult[index] = GetGeometry()[i].GetDof(DISPLACEMENT_X).EquationId();\n                    rResult[index+1] = GetGeometry()[i].GetDof(DISPLACEMENT_Y).EquationId();\n                    rResult[index+2] = GetGeometry()[i].GetDof(DISPLACEMENT_Z).EquationId();\n         }\n     }\n\t/**\n    * Informations for the builder and solver to assemble the global vectors and matrices.\n    * Here a Container containing the pointers rto the DOFs of this element is created\n    * @param ElementalDofList Container with of the DOFs associated with the nodes\n    *                           of this element\n    * @param rCurrentProcessInfo\n    */\n    void KinematicLinear::GetDofList(DofsVectorType& ElementalDofList,ProcessInfo& \n                CurrentProcessInfo)\n    {\n        ElementalDofList.resize(0);\n\n        for (unsigned int i=0 ;i<GetGeometry().size() ;i++)\n        {      \n            ElementalDofList.push_back(GetGeometry()[i].pGetDof(DISPLACEMENT_X));\n            ElementalDofList.push_back(GetGeometry()[i].pGetDof(DISPLACEMENT_Y));\n            ElementalDofList.push_back(GetGeometry()[i].pGetDof(DISPLACEMENT_Z));\n        }\n     }\n\t/**\n    * A Vector containing the current values of the DOFs is created\n    * @param values Vector with the current values of the DOFs\n    * @param Step number of the time step\n    */\n    void KinematicLinear::GetValuesVector(Vector& values, int Step)\n    {\n        unsigned int dim = (GetGeometry().WorkingSpaceDimension());//3 displacement dofs \n        unsigned int MatSize = GetGeometry().size()*dim;\n\n        if(values.size() != MatSize)\n            values.resize(MatSize);\n\n        for (unsigned int i=0 ;i<GetGeometry().size();i++)\n        {\n            int index = i*dim;\n\n            values(index) = \n                GetGeometry()[i].GetSolutionStepValue(DISPLACEMENT_X,Step);\n            values(index+1) = \n                GetGeometry()[i].GetSolutionStepValue(DISPLACEMENT_Y,Step); \n            values(index+2) = \n                GetGeometry()[i].GetSolutionStepValue(DISPLACEMENT_Z,Step); \n        }\n    }\n\t/**\n    * Adds the Body Forces to the load vector\n    * @param R RHS Vector\n    * @param N_DISP shape function values at the current integration points\n    * @param Weight current integration weight\n    * @param detJ current Determinant of the Jacobian\n    */\n    void KinematicLinear::AddBodyForcesToRHS(Vector& R, const Vector& N_DISP, double Weight, double detJ )\n    {\n        KRATOS_TRY\n            \n        unsigned int dim= GetGeometry().WorkingSpaceDimension();\n\n        Vector gravity(dim);\n            \n        noalias(gravity)=GetProperties()[GRAVITY];\n\n        double density= GetProperties()[DENSITY];\n\n        for(unsigned int prim=0; prim< GetGeometry().size(); prim++)\n        {\n            for(unsigned int i=0; i< dim; i++)\n            {\n                R(prim*dim+i) += N_DISP(prim)*density*gravity(i)*detJ*Weight;\n            }\n        }\n\n        KRATOS_CATCH(\"\")\n    }\n\t/**\n    * Adds the Internal Forces to the load vector\n    * @param R RHS Vector\n    * @param B_Operator B-Operator at the current integration point\n    * @param StressVector current stress vector\n    * @param Weight current integration weight\n    * @param detJ current Determinant of the Jacobian\n    */\n    void KinematicLinear::AddInternalForcesToRHS(Vector& R, const Matrix& B_Operator, Vector& StressVector, double Weight, double detJ)\n    {     \n        KRATOS_TRY\n             \n        unsigned int dim= GetGeometry().WorkingSpaceDimension();\n            \n        for(unsigned int prim=0; prim< GetGeometry().size(); prim++)\n        {\n            for(unsigned int i=0; i< dim; i++)\n            {\n                for(unsigned int gamma=0; gamma<6; gamma++)\n                {\n                    R(prim*dim+i) +=(-1)*(B_Operator(gamma,prim*3+i)*StressVector(gamma)*\n                                        detJ*Weight);     \n                }\n            }\n        }\n\n//         noalias(R) -= detJ*Weight* prod(trans(B_Operator),StressVector);\n\n        KRATOS_CATCH(\"\")\n    }\n\t/**\n    * Adds the Contribution of the current quadrature point to the load vector\n    * @param K LHS Matrix\n    * @param tan_C 6*6 algorithmic tangent of the materia law (derivation of stresses \n    *               regarding strains\n    * @param B_Operator B-Operator at the current integration point\n    * @param Weight current integration weight\n    * @param detJ current Determinant of the Jacobian\n    */\n    void KinematicLinear::CalculateStiffnesMatrix(Matrix& K,const \n                Matrix& tan_C,const Matrix& B_Operator, double Weight, double detJ)\n    {\n        KRATOS_TRY\n\n        unsigned int dim= GetGeometry().WorkingSpaceDimension();\n\n        for(unsigned int prim=0; prim< GetGeometry().size(); prim++)\n        {\n            for(unsigned int i=0; i< dim; i++)\n            {\n                for(unsigned int sec=0; sec< GetGeometry().size(); sec++)\n                {\n                    for(unsigned int j=0; j< dim; j++)\n                    {\n                        for(unsigned int alpha=0; alpha<6; alpha++)\n                            for(unsigned int beta=0; beta<6; beta++) \n                                K(prim*dim+i,sec*dim+j) += B_Operator(alpha,3*prim+i)\n                                    *tan_C(alpha,beta)*B_Operator(beta,3*sec+j)*detJ*Weight;\n                    }\n                }\n            }\n        }\n\n//         noalias(K)-= prod(trans(B_Operator),(Weight*detJ)*Matrix(prod(C,B_Operator)) );\n\n        KRATOS_CATCH(\"\")\n    }\n\t/**\n    * Computes the stress vector and the algorithmic tangent at the current quadrature points   \n    * regarding the current strain vector\n    * @param StressVector output of the method, Cauchy stress vector\n    * @param tanC_U algorithmic tangen (derivative Cauchy stress vector/StrainVector) [6*6]\n    * @param StrainVector output: current strain vector\n    * @param B_Operator current B-operator \n    * @param PointNumber number of the current integration point\n    * @param CurrentProcessInfo\n    */\n    void KinematicLinear::CalculateStressAndTangentialStiffness(Vector& StressVector, Matrix& tanC_U,\n            Vector& StrainVector, const Matrix& B_Operator, int PointNumber,\n            const ProcessInfo& CurrentProcessInfo)\n    {\n        KRATOS_TRY\n                \n        //Calculate the current strain vector using the B-Operator\n        //CalculateStrainVector(B_Operator, StrainVector, PointNumber);\n        //Call the material law to get the current Stress Vector\n        //mConstitutiveLawVector[PointNumber]->CalculateStress(StrainVector, StressVector);\n        //Call the material law to get the current algorithmic tangent\n        //mConstitutiveLawVector[PointNumber]->CalculateConstitutiveMatrix(StrainVector, tanC_U);\n\n        KRATOS_CATCH(\"\")\n    }\n    \n    /**\n     * Computes the strain vector\n     */\n    void KinematicLinear::CalculateStrain( const Matrix& B, const Matrix& Displacements, Vector& StrainVector )\n    {\n        KRATOS_TRY\n        noalias(StrainVector)=ZeroVector(6);\n        for(unsigned int node=0; node<GetGeometry().size(); node++)\n        {\n            for( unsigned int item = 0; item < 6; item++ )\n                for( unsigned int dim=0; dim<3; dim++ )\n                    StrainVector[item]+=B(item,3*node+dim)*(Displacements(node,dim)-mInitialDisp(node,dim));\n        }\n        KRATOS_CATCH(\"\")\n    }\n    \n\t/**\n    * Computes the B-Operator at the current quadrature point\n    * @param B_Operator current B-operator \n    * @param DN_DX shape function values at the current integration point\n    */\n    void KinematicLinear::CalculateBoperator\n                   (Matrix& B_Operator, const Matrix& DN_DX)\n    {\n        KRATOS_TRY\n\n        const unsigned int number_of_nodes = GetGeometry().PointsNumber();\n\n//         if(B_Operator.size() != number_of_nodes)\n//             B_Operator.resize(number_of_nodes);\n        noalias(B_Operator)=ZeroMatrix(6,number_of_nodes*3);\n\n        for (unsigned int i=0;i<number_of_nodes;i++)\n\t\t{\n//             if(B_Operator[i].size1() != 6 || B_Operator[i].size2() != 3)\n//                 B_Operator[i].resize(6,3);\n\n//             noalias(B_Operator[i])= ZeroMatrix(6,3);\n                \n            B_Operator(0,i*3)= DN_DX(i,0);\n            B_Operator(1,i*3+1)= DN_DX(i,1);\n            B_Operator(2,i*3+2)= DN_DX(i,2);\n            B_Operator(3,i*3)= DN_DX(i,1);\n            B_Operator(3,i*3+1)= DN_DX(i,0);\n            B_Operator(4,i*3+1)= DN_DX(i,2);\n            B_Operator(4,i*3+2)= DN_DX(i,1);\n            B_Operator(5,i*3)= DN_DX(i,2);\n            B_Operator(5,i*3+2)= DN_DX(i,0);\n        }\n\n        return;\n\n        KRATOS_CATCH(\"\")\n\t}\n\t/**\n    * Calculate Matrix Variables at each integration point, used for postprocessing etc.\n    * @param rVariable Global name of the variable to be calculated\n    * @param rValues Vector to store the values on the qudrature points, output of the method \n    * @param rCurrentProcessInfo\n    */\n \tvoid KinematicLinear::GetValueOnIntegrationPoints(const Variable<Matrix>& rVariable, std::vector<Matrix>& rValues, const ProcessInfo& rCurrentProcessInfo)\n\t{\n\t\tif(rVariable== PK2_STRESS_TENSOR || rVariable == GREEN_LAGRANGE_STRAIN_TENSOR)\n        {\n            CalculateOnIntegrationPoints(rVariable, rValues, rCurrentProcessInfo);\n        }\n\t\treturn;\n\t}\n\t/**\n    * Calculate Vector Variables at each integration point, used for postprocessing etc.\n    * @param rVariable Global name of the variable to be calculated\n    * @param rValues Vector to store the values on the qudrature points, output of the method \n    * @param rCurrentProcessInfo\n    */\n\t void KinematicLinear::GetValueOnIntegrationPoints(const Variable<Vector>& rVariable, std::vector<Vector>& rValues, const ProcessInfo& rCurrentProcessInfo)\n\t{\n// std::cout<<\"GetValueOnIntegrationPoints\"<<std::endl;\n            if(rVariable==INSITU_STRESS)\n            {\n                for( unsigned int PointNumber = 0; \n                     PointNumber < GetGeometry().IntegrationPoints(mThisIntegrationMethod).size(); \n                     PointNumber++ )\n                {\n                    rValues[PointNumber] = \n                            mConstitutiveLawVector[PointNumber]->GetValue(INSITU_STRESS);\n                }\n            }\n            if(rVariable==MATERIAL_PARAMETERS)\n            {\n                for( unsigned int PointNumber = 0; \n                     PointNumber < GetGeometry().IntegrationPoints(mThisIntegrationMethod).size(); PointNumber++ )\n                {\n                    rValues[PointNumber] =\n                            mConstitutiveLawVector[PointNumber]->GetValue(MATERIAL_PARAMETERS);\n                }\n            }\n            if (rVariable==INTERNAL_VARIABLES)\n            {\n                for( unsigned int PointNumber = 0;\n                     PointNumber<GetGeometry().IntegrationPoints(mThisIntegrationMethod).size();\n                     PointNumber++ )\n                {\n                    rValues[PointNumber] = \n                            mConstitutiveLawVector[PointNumber]->GetValue(INTERNAL_VARIABLES);\n                }\n            }\n// std::cout<<\"END::GetValueOnIntegrationPoints\"<<std::endl;\n\t}\n\t/**\n    * Calculate double Variables at each integration point, used for postprocessing etc.\n    * @param rVariable Global name of the variable to be calculated\n    * @param rValues Vector to store the values on the qudrature points, output of the method \n    * @param rCurrentProcessInfo\n    */\n\t void KinematicLinear::GetValueOnIntegrationPoints(const Variable<double>& rVariable, std::vector<double>& rValues, const ProcessInfo& rCurrentProcessInfo)\n\t{\n\t\tif(!(rVariable== DP_EPSILON))\n\t\t\treturn;\n\t\tif(rValues.size() != GetGeometry().IntegrationPoints().size())\n\t\t  \t   rValues.resize(GetGeometry().IntegrationPoints().size());\n        //reading integration points and local gradients\n        for(unsigned int Point=0; Point< mConstitutiveLawVector.size(); Point++)\n        {\n\t\t\trValues[Point]= mConstitutiveLawVector[Point]->GetValue( rVariable); \n        }\n\t}\n\t/**\n    * Set a Matrix Variable from outside \n    * @param rVariable Global name of the variable to be calculated\n    * @param rValues Vector of the values on the quadrature points\n    * @param rCurrentProcessInfo\n    */\n\tvoid KinematicLinear::SetValueOnIntegrationPoints(const Variable<Matrix>& rVariable, std::vector<Matrix>& rValues, const ProcessInfo& rCurrentProcessInfo)\n\t{\n\t\tif(rValues.size() != mConstitutiveLawVector.size())\n\t\t{\n\t\t\tstd::cout<<\"In KinematicLinear:SetValueOnIntegrationPoints(...) Line 798, wrong size of the input vector, is = \"<< rValues.size()<<\" ; should be = \"<<mConstitutiveLawVector.size()<<std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tif(rVariable==ELASTIC_LEFT_CAUCHY_GREEN_OLD)\n        {\n\n\t\t\tfor( unsigned int i=0; i<mConstitutiveLawVector.size(); i++ )\n            {\n\t\t\t\t\t\tmConstitutiveLawVector[i]->SetValue(ELASTIC_LEFT_CAUCHY_GREEN_OLD, rValues[i], rCurrentProcessInfo);\n\t\t\t}\t\t\n\t\t}\n\n\t}\n\t/**\n    * Set a Vector Variable from outside \n    * @param rVariable Global name of the variable to be calculated\n    * @param rValues Vector of the values on the quadrature points\n    * @param rCurrentProcessInfo\n    */\n        void KinematicLinear::SetValueOnIntegrationPoints(const Variable<Vector>& rVariable, std::vector<Vector>& rValues, const ProcessInfo& rCurrentProcessInfo)\n        {\n//              std::cout << mConstitutiveLawVector[0] << std::endl;\n                if (rVariable==INSITU_STRESS)\n                {\n                    for( unsigned int PointNumber = 0; PointNumber<GetGeometry().IntegrationPoints(mThisIntegrationMethod).size(); PointNumber++ )\n                        {\n                                mConstitutiveLawVector[PointNumber]->SetValue(INSITU_STRESS, rValues[PointNumber],\n                                                rCurrentProcessInfo );\n                        }\n                }\n                if (rVariable==MATERIAL_PARAMETERS)\n                {\n                    for( unsigned int PointNumber = 0; PointNumber<GetGeometry().IntegrationPoints(mThisIntegrationMethod).size(); PointNumber++ )\n                    {\n                        mConstitutiveLawVector[PointNumber]->SetValue( MATERIAL_PARAMETERS,\n                                rValues[PointNumber], rCurrentProcessInfo );\n                    }\n                }\n        }\n        /**\n    * Set a Double Variable from outside \n    * @param rVariable Global name of the variable to be calculated\n    * @param rValue value on the quadrature points\n    * @param rCurrentProcessInfo\n    */\n        void KinematicLinear::SetValueOnIntegrationPoints( const Variable<double>& rVariable,\n                    std::vector<double>& rValues,const ProcessInfo& rCurrentProcessInfo)\n        {\n//              std::cout << mConstitutiveLawVector[0] << std::endl;\n                if (rVariable==SUCTION)\n                {\n                    for( unsigned int PointNumber = 0; PointNumber<GetGeometry().IntegrationPoints(mThisIntegrationMethod).size(); PointNumber++ )\n                        {\n                                mConstitutiveLawVector[PointNumber]->SetValue(SUCTION, rValues[PointNumber],\n                                                rCurrentProcessInfo );\n                        }\n                }\n        }\n\n        \n} // Namespace Kratos\n", "meta": {"hexsha": "addcdb45037204ee30242872c0e1e1630a3720b2", "size": 41968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/structural_application/custom_elements/kinematic_linear.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": "applications/structural_application/custom_elements/kinematic_linear.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": "applications/structural_application/custom_elements/kinematic_linear.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": 43.3553719008, "max_line_length": 194, "alphanum_fraction": 0.6253097598, "num_tokens": 9359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.09401017200157859, "lm_q1q2_score": 0.03900471185661067}}
{"text": "// g2o - General Graph Optimization\r\n// Copyright (C) 2011 H. Strasdat\r\n// All rights reserved.\r\n//\r\n// Redistribution and use in source and binary forms, with or without\r\n// modification, are permitted provided that the following conditions are\r\n// met:\r\n//\r\n// * Redistributions of source code must retain the above copyright notice,\r\n//   this list of conditions and the following disclaimer.\r\n// * Redistributions in binary form must reproduce the above copyright\r\n//   notice, this list of conditions and the following disclaimer in the\r\n//   documentation and/or other materials provided with the distribution.\r\n//\r\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\r\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#include <Eigen/StdVector>\r\n\r\n#include <unordered_set>\r\n\r\n#include <iostream>\r\n#include <stdint.h>\r\n\r\n#include \"g2o/config.h\"\r\n#include \"g2o/core/sparse_optimizer.h\"\r\n#include \"g2o/core/block_solver.h\"\r\n#include \"g2o/core/solver.h\"\r\n#include \"g2o/core/robust_kernel_impl.h\"\r\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\r\n#include \"g2o/solvers/dense/linear_solver_dense.h\"\r\n#include \"g2o/types/icp/types_icp.h\"\r\n#include \"g2o/solvers/structure_only/structure_only_solver.h\"\r\n\r\n#if defined G2O_HAVE_CHOLMOD\r\n#include \"g2o/solvers/cholmod/linear_solver_cholmod.h\"\r\n#elif defined G2O_HAVE_CSPARSE\r\n#include \"g2o/solvers/csparse/linear_solver_csparse.h\"\r\n#endif\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n\r\nclass Sample\r\n{\r\npublic:\r\n  static int uniform(int from, int to);\r\n  static double uniform();\r\n  static double gaussian(double sigma);\r\n};\r\n\r\nstatic double uniform_rand(double lowerBndr, double upperBndr)\r\n{\r\n  return lowerBndr + ((double) std::rand() / (RAND_MAX + 1.0)) * (upperBndr - lowerBndr);\r\n}\r\n\r\nstatic double gauss_rand(double mean, double sigma)\r\n{\r\n  double x, y, r2;\r\n  do {\r\n    x = -1.0 + 2.0 * uniform_rand(0.0, 1.0);\r\n    y = -1.0 + 2.0 * uniform_rand(0.0, 1.0);\r\n    r2 = x * x + y * y;\r\n  } while (r2 > 1.0 || r2 == 0.0);\r\n  return mean + sigma * y * std::sqrt(-2.0 * log(r2) / r2);\r\n}\r\n\r\nint Sample::uniform(int from, int to)\r\n{\r\n  return static_cast<int>(uniform_rand(from, to));\r\n}\r\n\r\ndouble Sample::uniform()\r\n{\r\n  return uniform_rand(0., 1.);\r\n}\r\n\r\ndouble Sample::gaussian(double sigma)\r\n{\r\n  return gauss_rand(0., sigma);\r\n}\r\n\r\nint main(int argc, const char* argv[])\r\n{\r\n  if (argc<2)\r\n  {\r\n    cout << endl;\r\n    cout << \"Please type: \" << endl;\r\n    cout << \"ba_demo [PIXEL_NOISE] [OUTLIER RATIO] [ROBUST_KERNEL] [STRUCTURE_ONLY] [DENSE]\" << endl;\r\n    cout << endl;\r\n    cout << \"PIXEL_NOISE: noise in image space (E.g.: 1)\" << endl;\r\n    cout << \"OUTLIER_RATIO: probability of spuroius observation  (default: 0.0)\" << endl;\r\n    cout << \"ROBUST_KERNEL: use robust kernel (0 or 1; default: 0==false)\" << endl;\r\n    cout << \"STRUCTURE_ONLY: performe structure-only BA to get better point initializations (0 or 1; default: 0==false)\" << endl;\r\n    cout << \"DENSE: Use dense solver (0 or 1; default: 0==false)\" << endl;\r\n    cout << endl;\r\n    cout << \"Note, if OUTLIER_RATIO is above 0, ROBUST_KERNEL should be set to 1==true.\" << endl;\r\n    cout << endl;\r\n    exit(0);\r\n  }\r\n\r\n  double PIXEL_NOISE = atof(argv[1]);\r\n\r\n  double OUTLIER_RATIO = 0.0;\r\n\r\n  if (argc>2)\r\n  {\r\n    OUTLIER_RATIO = atof(argv[2]);\r\n  }\r\n\r\n  bool ROBUST_KERNEL = false;\r\n  if (argc>3)\r\n  {\r\n    ROBUST_KERNEL = atoi(argv[3]) != 0;\r\n  }\r\n  bool STRUCTURE_ONLY = false;\r\n  if (argc>4)\r\n  {\r\n    STRUCTURE_ONLY = atoi(argv[4]) != 0;\r\n  }\r\n\r\n  bool DENSE = false;\r\n  if (argc>5)\r\n  {\r\n    DENSE = atoi(argv[5]) != 0;\r\n  }\r\n\r\n  cout << \"PIXEL_NOISE: \" <<  PIXEL_NOISE << endl;\r\n  cout << \"OUTLIER_RATIO: \" << OUTLIER_RATIO<<  endl;\r\n  cout << \"ROBUST_KERNEL: \" << ROBUST_KERNEL << endl;\r\n  cout << \"STRUCTURE_ONLY: \" << STRUCTURE_ONLY<< endl;\r\n  cout << \"DENSE: \"<<  DENSE << endl;\r\n\r\n\r\n\r\n  g2o::SparseOptimizer optimizer;\r\n  optimizer.setVerbose(false);\r\n  std::unique_ptr<g2o::BlockSolver_6_3::LinearSolverType> linearSolver;\r\n  if (DENSE)\r\n  {\r\n    linearSolver = g2o::make_unique<g2o::LinearSolverDense<g2o::BlockSolver_6_3::PoseMatrixType>>();\r\n    cerr << \"Using DENSE\" << endl;\r\n  }\r\n  else\r\n  {\r\n#ifdef G2O_HAVE_CHOLMOD\r\n\tcerr << \"Using CHOLMOD\" << endl;\r\n    linearSolver = g2o::make_unique<g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType>>();\r\n#elif defined G2O_HAVE_CSPARSE\r\n    linearSolver = g2o::make_unique<g2o::LinearSolverCSparse<g2o::BlockSolver_6_3::PoseMatrixType>>();\r\n\tcerr << \"Using CSPARSE\" << endl;\r\n#else\r\n#error neither CSparse nor Cholmod are available\r\n#endif\r\n  }\r\n\r\n  g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(\r\n    g2o::make_unique<g2o::BlockSolver_6_3>(std::move(linearSolver)));\r\n\r\n  optimizer.setAlgorithm(solver);\r\n\r\n  // set up 500 points\r\n  vector<Vector3d> true_points;\r\n  for (size_t i=0;i<500; ++i)\r\n  {\r\n    true_points.push_back(Vector3d((Sample::uniform()-0.5)*3,\r\n                                   Sample::uniform()-0.5,\r\n                                   Sample::uniform()+10));\r\n  }\r\n\r\n\r\n  Vector2d focal_length(500,500); // pixels\r\n  Vector2d principal_point(320,240); // 640x480 image\r\n  double baseline = 0.075;      // 7.5 cm baseline\r\n\r\n\r\n  vector<Eigen::Isometry3d,\r\n      aligned_allocator<Eigen::Isometry3d> > true_poses;\r\n\r\n  // set up camera params\r\n  g2o::VertexSCam::setKcam(focal_length[0],focal_length[1],\r\n                           principal_point[0],principal_point[1],\r\n                           baseline);\r\n  \r\n  // set up 5 vertices, first 2 fixed\r\n  int vertex_id = 0;\r\n  for (size_t i=0; i<5; ++i)\r\n  {\r\n\r\n\r\n    Vector3d trans(i*0.04-1.,0,0);\r\n\r\n    Eigen:: Quaterniond q;\r\n    q.setIdentity();\r\n    Eigen::Isometry3d pose;\r\n    pose = q;\r\n    pose.translation() = trans;\r\n\r\n\r\n    g2o::VertexSCam * v_se3\r\n        = new g2o::VertexSCam();\r\n\r\n    v_se3->setId(vertex_id);\r\n    v_se3->setEstimate(pose);\r\n    v_se3->setAll();            // set aux transforms\r\n\r\n    if (i<2)\r\n      v_se3->setFixed(true);\r\n    \r\n    optimizer.addVertex(v_se3);\r\n    true_poses.push_back(pose);\r\n    vertex_id++;\r\n  }\r\n\r\n  int point_id=vertex_id;\r\n  int point_num = 0;\r\n  double sum_diff2 = 0;\r\n\r\n  cout << endl;\r\n  unordered_map<int,int> pointid_2_trueid;\r\n  unordered_set<int> inliers;\r\n\r\n  // add point projections to this vertex\r\n  for (size_t i=0; i<true_points.size(); ++i)\r\n  {\r\n    g2o::VertexSBAPointXYZ * v_p\r\n        = new g2o::VertexSBAPointXYZ();\r\n\r\n\r\n    v_p->setId(point_id);\r\n    v_p->setMarginalized(true);\r\n    v_p->setEstimate(true_points.at(i)\r\n        + Vector3d(Sample::gaussian(1),\r\n                   Sample::gaussian(1),\r\n                   Sample::gaussian(1)));\r\n\r\n    int num_obs = 0;\r\n\r\n    for (size_t j=0; j<true_poses.size(); ++j)\r\n    {\r\n      Vector3d z;\r\n      dynamic_cast<g2o::VertexSCam*>\r\n        (optimizer.vertices().find(j)->second)\r\n        ->mapPoint(z,true_points.at(i));\r\n\r\n      if (z[0]>=0 && z[1]>=0 && z[0]<640 && z[1]<480)\r\n      {\r\n        ++num_obs;\r\n      }\r\n    }\r\n\r\n    if (num_obs>=2)\r\n    {\r\n      optimizer.addVertex(v_p);\r\n\r\n      bool inlier = true;\r\n      for (size_t j=0; j<true_poses.size(); ++j)\r\n      {\r\n        Vector3d z;\r\n        dynamic_cast<g2o::VertexSCam*>\r\n          (optimizer.vertices().find(j)->second)\r\n          ->mapPoint(z,true_points.at(i));\r\n\r\n        if (z[0]>=0 && z[1]>=0 && z[0]<640 && z[1]<480)\r\n        {\r\n          double sam = Sample::uniform();\r\n          if (sam<OUTLIER_RATIO)\r\n          {\r\n            z = Vector3d(Sample::uniform(64,640),\r\n                         Sample::uniform(0,480),\r\n                         Sample::uniform(0,64)); // disparity\r\n            z(2) = z(0) - z(2); // px' now\r\n\r\n            inlier= false;\r\n          }\r\n\r\n          z += Vector3d(Sample::gaussian(PIXEL_NOISE),\r\n                        Sample::gaussian(PIXEL_NOISE),\r\n                        Sample::gaussian(PIXEL_NOISE/16.0));\r\n\r\n          g2o::Edge_XYZ_VSC * e\r\n              = new g2o::Edge_XYZ_VSC();\r\n\r\n\r\n          e->vertices()[0]\r\n              = dynamic_cast<g2o::OptimizableGraph::Vertex*>(v_p);\r\n\r\n          e->vertices()[1]\r\n              = dynamic_cast<g2o::OptimizableGraph::Vertex*>\r\n              (optimizer.vertices().find(j)->second);\r\n\r\n          e->setMeasurement(z);\r\n          //e->inverseMeasurement() = -z;\r\n          e->information() = Matrix3d::Identity();\r\n\r\n          if (ROBUST_KERNEL) {\r\n            g2o::RobustKernelHuber* rk = new g2o::RobustKernelHuber;\r\n            e->setRobustKernel(rk);\r\n          }\r\n\r\n          optimizer.addEdge(e);\r\n\r\n\r\n        }\r\n\r\n      }\r\n\r\n      if (inlier)\r\n      {\r\n        inliers.insert(point_id);\r\n        Vector3d diff = v_p->estimate() - true_points[i];\r\n\r\n        sum_diff2 += diff.dot(diff);\r\n      }\r\n     // else\r\n     //   cout << \"Point: \" << point_id <<  \"has at least one spurious observation\" <<endl;\r\n\r\n      pointid_2_trueid.insert(make_pair(point_id,i));\r\n\r\n      ++point_id;\r\n      ++point_num;\r\n    }\r\n\r\n  }\r\n\r\n  cout << endl;\r\n  optimizer.initializeOptimization();\r\n\r\n  optimizer.setVerbose(true);\r\n\r\n  if (STRUCTURE_ONLY)\r\n  {\r\n    cout << \"Performing structure-only BA:\"   << endl;\r\n    g2o::StructureOnlySolver<3> structure_only_ba;\r\n    g2o::OptimizableGraph::VertexContainer points;\r\n    for (g2o::OptimizableGraph::VertexIDMap::const_iterator it = optimizer.vertices().begin(); it != optimizer.vertices().end(); ++it) {\r\n      g2o::OptimizableGraph::Vertex* v = static_cast<g2o::OptimizableGraph::Vertex*>(it->second);\r\n      if (v->dimension() == 3)\r\n        points.push_back(v);\r\n    }\r\n\r\n    structure_only_ba.calc(points, 10);\r\n  }\r\n\r\n    cout << endl;\r\n  cout << \"Performing full BA:\" << endl;\r\n  optimizer.optimize(10);\r\n\r\n  cout << endl;\r\n  cout << \"Point error before optimisation (inliers only): \" << sqrt(sum_diff2/inliers.size()) << endl;\r\n\r\n\r\n  point_num = 0;\r\n  sum_diff2 = 0;\r\n\r\n\r\n  for (unordered_map<int,int>::iterator it=pointid_2_trueid.begin();\r\n       it!=pointid_2_trueid.end(); ++it)\r\n  {\r\n\r\n    g2o::HyperGraph::VertexIDMap::iterator v_it\r\n        = optimizer.vertices().find(it->first);\r\n\r\n    if (v_it==optimizer.vertices().end())\r\n    {\r\n      cerr << \"Vertex \" << it->first << \" not in graph!\" << endl;\r\n      exit(-1);\r\n    }\r\n\r\n    g2o::VertexSBAPointXYZ * v_p\r\n        = dynamic_cast< g2o::VertexSBAPointXYZ * > (v_it->second);\r\n\r\n    if (v_p==0)\r\n    {\r\n      cerr << \"Vertex \" << it->first << \"is not a PointXYZ!\" << endl;\r\n      exit(-1);\r\n    }\r\n\r\n    Vector3d diff = v_p->estimate()-true_points[it->second];\r\n\r\n    if (inliers.find(it->first)==inliers.end())\r\n      continue;\r\n\r\n    sum_diff2 += diff.dot(diff);\r\n\r\n    ++point_num;\r\n  }\r\n\r\n  cout << \"Point error after optimisation (inliers only): \" << sqrt(sum_diff2/inliers.size()) << endl;\r\n  cout << endl;\r\n\r\n}\r\n", "meta": {"hexsha": "a7bef859ce0f74852db409d51fe409202b58c653", "size": 11423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slambook2/3rdparty/g2o/g2o/examples/sba/sba_demo.cpp", "max_stars_repo_name": "zhh2005757/slambook2_in_Docker", "max_stars_repo_head_hexsha": "f0e71327d196cdad3b3c10d96eacdf95240d528b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-14T07:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T09:20:33.000Z", "max_issues_repo_path": "slambook2/3rdparty/g2o/g2o/examples/sba/sba_demo.cpp", "max_issues_repo_name": "zhh2005757/slambook2_in_Docker", "max_issues_repo_head_hexsha": "f0e71327d196cdad3b3c10d96eacdf95240d528b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slambook2/3rdparty/g2o/g2o/examples/sba/sba_demo.cpp", "max_forks_repo_name": "zhh2005757/slambook2_in_Docker", "max_forks_repo_head_hexsha": "f0e71327d196cdad3b3c10d96eacdf95240d528b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-10-21T06:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T15:52:28.000Z", "avg_line_length": 28.3449131514, "max_line_length": 137, "alphanum_fraction": 0.6018559048, "num_tokens": 3188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.0769608335789328, "lm_q1q2_score": 0.0381797946494469}}
{"text": "/**\n * @file isam.cpp\n * @brief Main isam program.\n * @author Michael Kaess\n * @version $Id: isam.cpp 6377 2012-03-30 20:06:44Z kaess $\n *\n * Copyright (C) 2009-2013 Massachusetts Institute of Technology.\n * Michael Kaess, Hordur Johannsson, David Rosen,\n * Nicholas Carlevaris-Bianco and John. J. Leonard\n *\n * This file is part of iSAM.\n *\n * iSAM is free software; you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the\n * Free Software Foundation; either version 2.1 of the License, or (at\n * your option) any later version.\n *\n * iSAM is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with iSAM.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <iostream>\n\nconst std::string usage = \"\\n\"\n    \"Usage:\\n\"\n    \"  iSAM [OPTION...] FILE\\n\"\n    \"\\n\"\n    \"Options:\\n\"\n    \"  -h  -?       show help options\\n\"\n    \"  -v           verbose - additional output\\n\"\n    \"  -q           quiet - no output\\n\"\n    \"  -n <number>  max. number of lines to read, 0=all\\n\"\n    \"  -G           GUI: show in 3D viewer\\n\"\n    \"  -L           LCM: send data to external process\\n\"\n    \"  -S [fname]   save statistics\\n\"\n    \"  -W [fname]   write out final result\\n\"\n    \"  -F           force use of numerical derivatives\\n\"\n    \"  -C           calculate marginal covariances\\n\"\n    \"  -B           batch processing\\n\"\n    \"  -M           use Levenberg-Marquardt for batch\\n\"\n    \"  -P           use Powell's Dog-Leg algorithm for optimization\\n\"\n    \"  -N           no optimization\\n\"\n    \"  -R           use robust (pseudo-Huber) cost function\\n\"\n    \"  -d <number>  #steps between drawing/sending data\\n\"\n    \"  -u <number>  #steps between any updates (batch or incremental)\\n\"\n    \"  -b <number>  #steps between batch steps, 0=never\\n\"\n    \"  -s <number>  #steps between solution (backsubstitution)\\n\"\n    \"\\n\";\n\nconst std::string intro = \"\\n\"\n    \"Incremental Smoothing and Mapping (iSAM) version 1.6\\n\"\n    \"(C) 2009-2012 Massachusetts Institute of Technology\\n\"\n    \"Michael Kaess, Hordur Johannsson, David M. Rosen, and John J. Leonard\\n\"\n    \"\\n\";\n\n#include <stdio.h>\n#include <cstring>\n#include <map>\n#include <Eigen/Dense>\n\n#include <isam/isam.h>\n#include <isam/robust.h>\n\n#include \"Loader.h\"\n#ifdef USE_LCM\n#include \"Lcm.h\"\n#endif\n#ifdef USE_GUI\n// needed in file with main() function to work on Mac...\n#include \"SDL.h\"\n#include \"Viewer.h\"\n#endif\n\n// for getopt / command line options processing\n#include <unistd.h>\nextern int optind;\nextern char *optarg;\n\nusing namespace std;\nusing namespace isam;\nusing namespace Eigen;\n\nconst int FNAME_MAX = 500;\nchar fname[FNAME_MAX];\nchar fname_stats[FNAME_MAX] = \"isam_stats.txt\";\nchar fname_result[FNAME_MAX] = \"isam_result.txt\";\n\nbool use_gui = false;\nbool use_lcm = false;\nbool save_stats = false;\nbool write_result = false;\nbool calculate_covariances = false;\nbool batch_processing = false;\nbool no_optimization = false;\nint parse_num_lines = 0;\n\n// draw state every mod_draw steps\nint mod_draw = 1;\n\nSlam slam;\nProperties prop;\n#ifdef USE_LCM\nLcm lcm;\nbool lcm_first = true;\n#endif\n#ifdef USE_GUI\nViewer viewer;\n#endif\nLoader* loader;\n\n// for recording of statistics for each time step (for visualization)\nclass Stats {\npublic:\n  double time;\n  double chi2;\n  unsigned int nnz;\n  double local_chi2;\n  unsigned int nnodes;\n  unsigned int nconstraints;\n};\nvector<class Stats> stats;\n\n// hard coded for now, affecting all constraints\ndouble robust_cost_function(double d) {\n  return cost_pseudo_huber(d, .5);\n}\n\n/**\n * Command line argument processing.\n */\nvoid process_arguments(int argc, char* argv[]) {\n  int c;\n  while ((c = getopt(argc, argv, \":h?vqn:GLS:W:FCBMPNRd:u:b:s:\")) != -1) {\n    // Each option character has to be in the string in getopt();\n    // the first colon changes the error character from '?' to ':';\n    // a colon after an option means that there is an extra\n    // parameter to this option; 'W' is a reserved character\n    switch (c) {\n    case 'h':\n    case '?':\n      cout << intro;\n      cout << usage;\n      exit(0);\n      break;\n    case 'v':\n      prop.quiet = false;\n      prop.verbose = true;\n      break;\n    case 'q':\n      prop.quiet = true;\n      prop.verbose = false;\n      break;\n    case 'n':\n      parse_num_lines = atoi(optarg);\n      require(parse_num_lines>0, \"Number of lines (-n) must be positive (>0).\");\n      break;\n    case 'G':\n#ifndef USE_GUI\n      require(false, \"GUI support (-G) was disabled at compile time\");\n#endif\n      use_gui = true;\n      break;\n    case 'L':\n#ifndef USE_LCM\n      require(false, \"LCM support (-L) was disabled at compile time\");\n#endif\n      use_lcm = true;\n      break;\n    case 'S':\n      save_stats = true;\n      if (optarg != NULL) {\n        strncpy(fname_stats, optarg, FNAME_MAX);\n      }\n      break;\n    case 'W':\n      write_result = true;\n      if (optarg != NULL) {\n        strncpy(fname_result, optarg, FNAME_MAX);\n      }\n      break;\n    case 'F':\n      prop.force_numerical_jacobian = true;\n      break;\n    case 'C':\n      calculate_covariances = true;\n      break;\n    case 'B':\n      batch_processing = true;\n      break;\n    case 'M':\n      prop.method = LEVENBERG_MARQUARDT;\n      break;\n    case 'P':\n      prop.method = DOG_LEG;\n      break;\n    case 'N':\n      no_optimization = true;\n      break;\n    case 'R':\n      slam.set_cost_function(&robust_cost_function);\n      break;\n    case 'd':\n      mod_draw = atoi(optarg);\n      require(mod_draw>0,\n          \"Number of steps between drawing (-d) must be positive (>0).\");\n      break;\n    case 'u':\n      prop.mod_update = atoi(optarg);\n      require(prop.mod_update>0,\n          \"Number of steps between updates (-u) must be positive (>0).\");\n      break;\n    case 'b':\n      prop.mod_batch = atoi(optarg);\n      require(\n          prop.mod_batch>=0,\n          \"Number of steps between batch steps (-b) must be positive or zero (>=0).\");\n      break;\n    case 's':\n      prop.mod_solve = atoi(optarg);\n      require(prop.mod_solve>0,\n          \"Number of steps between solving (-s) must be positive (>0).\");\n      break;\n    case ':': // unknown option, from getopt\n      cout << intro;\n      cout << usage;\n      exit(1);\n      break;\n    }\n  }\n\n  if ((prop.method == LEVENBERG_MARQUARDT) && (!batch_processing)) {\n    cout << \"Error:  Levenberg-Marquardt optimization has no incremental mode.\"\n        << endl;\n    exit(1);\n  }\n\n  if (argc > optind + 1) {\n    cout << intro;\n    cout << endl;\n    cout << \"Error: Too many arguments.\" << endl;\n    cout << usage;\n    exit(1);\n  } else if (argc == optind + 1) {\n    strncpy(fname, argv[optind], FNAME_MAX);\n  }\n\n}\n\n/**\n * Save statistics for each time step for external visualization.\n */\nvoid save_statistics(const string& fname) {\n  ofstream out(fname.c_str(), ios::out | ios::binary);\n  require(out, \"Cannot open statistics file.\");\n  for (unsigned int i = 0; i < stats.size(); i++) {\n    out << i << \" \" << stats[i].time << \" \" << stats[i].chi2 << \" \"\n        << stats[i].nnz;\n    out << \" \" << stats[i].local_chi2;\n    out << \" \" << stats[i].nconstraints << \" \" << stats[i].nnodes;\n    out << endl;\n  }\n  out.close();\n}\n\n/**\n * Calculate covariances for both points and poses up to the given time step.\n */\nvoid covariances(unsigned int step, list<MatrixXd>& point_marginals,\n    list<MatrixXd>& pose_marginals) {\n  // make sure return arguments are empty\n  point_marginals.clear();\n  pose_marginals.clear();\n\n  // combining everything into one call is faster,\n  // as it avoids recalculating commonly needed entries\n  Covariances::node_lists_t node_lists;\n  for (unsigned int i = 0; i < step; i++) {\n    list<Node*> entry;\n    entry.push_back(loader->pose_nodes()[i]);\n    node_lists.push_back(entry);\n  }\n  for (unsigned int i = 0; i < loader->num_points(step); i++) {\n    list<Node*> entry;\n    entry.push_back(loader->point_nodes()[i]);\n    node_lists.push_back(entry);\n  }\n  pose_marginals = slam.covariances().marginal(node_lists);\n\n  // split into points and poses\n  if (pose_marginals.size() > 0) {\n    list<MatrixXd>::iterator center = pose_marginals.begin();\n    for (unsigned int i = 0; i < step; i++, center++)\n      ;\n    point_marginals.splice(point_marginals.begin(), pose_marginals, center,\n        pose_marginals.end());\n  }\n}\n\n/**\n * Visualize data during optimization in internal viewer\n * or send data via LCM (to an external viewer).\n */\nvoid visualize(unsigned int step) {\n  list<MatrixXd> point_marginals;\n  list<MatrixXd> pose_marginals;\n  if (calculate_covariances && (use_gui || use_lcm) && (step % mod_draw == 0)) {\n    covariances(step, point_marginals, pose_marginals);\n  }\n\n#ifdef USE_LCM\n  {\n    // ids also determine color in viewer\n    const int id_trajectory = 0;\n    const int id_landmarks = 1;\n    const int id_constraints = 2;\n    const int id_measurements = 3;\n    const int id_pose_covs = 4;\n    const int id_point_covs = 5;\n\n    // send to LCM viewer\n    if (use_lcm && lcm_first) {\n      lcm.send_reset();\n      lcm_first = false;\n    }\n    if (use_lcm && step%mod_draw==0) {\n      lcm.send_nodes(loader->poses(step), id_trajectory, (char*)\"Trajectory\", 1);\n      lcm.send_nodes(loader->points(step), id_landmarks, (char*)\"Landmarks\", loader->is_3d() ? 3 : 2);\n      lcm.send_links(loader->constraints(step), id_constraints,\n          (char*)\"Odometry\", id_trajectory, id_trajectory);\n      lcm.send_links(loader->measurements(step), id_measurements,\n          (char*)\"Measurements\", id_trajectory, id_landmarks);\n      if (calculate_covariances) {\n        lcm.send_covariances(pose_marginals, id_pose_covs,\n            (char*)\"Pose Covs\", id_trajectory, loader->is_3d());\n        lcm.send_covariances(point_marginals, id_point_covs,\n            (char*)\"Point Covs\", id_landmarks, loader->is_3d());\n      }\n    }\n  }\n#endif\n\n#ifdef USE_GUI\n  {\n    // display in internal 3D viewer\n    const int id_trajectory = 0;\n    const int id_landmarks = 1;\n    const int id_constraints = 2;\n    const int id_measurements = 3;\n    const int id_pose_covs = 4;\n    const int id_point_covs = 5;\n    if (use_gui && step%mod_draw==0) {\n      viewer.set_nodes(loader->poses(step), id_trajectory,\n          (char*)\"Trajectory\", VIEWER_OBJ_POSE3D);\n      viewer.set_nodes(loader->points(step), id_landmarks,\n          (char*)\"Landmarks\", loader->is_3d() ? VIEWER_OBJ_POINT3D : VIEWER_OBJ_TREE);\n      viewer.set_links(loader->constraints(step), id_constraints,\n          \"Odometry\", id_trajectory, id_trajectory);\n      viewer.set_links(loader->measurements(step), id_measurements,\n          \"Measurements\", id_trajectory, id_landmarks);\n      if (calculate_covariances) {\n        viewer.set_covariances(pose_marginals, id_pose_covs,\n            (char*)\"Pose Covs\", id_trajectory, loader->is_3d());\n        viewer.set_covariances(point_marginals, id_point_covs,\n            (char*)\"Point Covs\", id_landmarks, loader->is_3d());\n      }\n    }\n  }\n#endif\n}\n\n/**\n * Quit if viewer was closed.\n */\nvoid check_quit() {\n#ifdef USE_GUI\n  if (viewer.exit_requested()) {\n    cout << endl << \"Aborted by user...\" << endl;\n    exit(0);\n  }\n#endif\n}\n\n/**\n * Incrementally process factors.\n */\nvoid incremental_slam() {\n\n\n// AJOUT CODE\nchar fname_result_incr[FNAME_MAX];\nstrcpy(fname_result_incr,fname_result);\nstrcat(fname_result_incr,\"_incremental.txt\");\nofstream out(fname_result_incr, ios::out | ios::binary );\nrequire(out, \"Slam.save: Cannot open output file.\");\nout << \"\\0\";\nout.close();\n\n// AJOUT CODE\nchar fname_result_cov[FNAME_MAX];\nstrcpy(fname_result_cov,fname_result);\nstrcat(fname_result_cov,\"_cov.txt\");\nofstream out_cov(fname_result_cov, ios::out | ios::binary );\nrequire(out_cov, \"Slam.save: Cannot open output file.\");\nout_cov << \"\\0\";\nout_cov.close();\n\n  unsigned int step = 0;\n\n\n  unsigned int next_step = step;\n  // step by step after reading log file\n  for (; loader->more_data(&next_step); step = next_step) {\n    check_quit();\n\n// cout << \" AJOUT CODE : Une ligne de plus !\" <<endl;\n\n    double t0 = tic();\n\n    tic(\"setup\");\n\n    // add new variables and constraints for current step\n    for (unsigned int s = step; s < next_step; s++) {\n      for (list<Node*>::const_iterator it = loader->nodes(s).begin();\n          it != loader->nodes(s).end(); it++) {\n        if (prop.verbose)\n          cout << **it << endl;\n        slam.add_node(*it);\n\n      }\n \n      for (list<Factor*>::const_iterator it = loader->factors(s).begin();\n          it != loader->factors(s).end(); it++) {\n        if (prop.verbose)\n          cout << **it << endl;\n        slam.add_factor(*it);\n      }\n    }\n\n// cout << endl << slam.get_nodes().back()->name() << ' ' << slam.get_nodes().back()->unique_id() << endl;\n\n/*\ncout << endl << (*loader->nodes(step).begin())->name() << ' ' << (*loader->nodes(step).begin())->unique_id() << endl;\ncout<<step<<' ';\n(*loader->nodes(step).begin())->write(cout);\ncout<<endl;\nsleep(1);\n*/\n\n// cout << (*it)->name() << (*it)->unique_id() << endl;\n// system(\"PAUSE\");\n// AJOUT CODE cout << it->name() << \"_Node \" << it->_id << endl;\n\n\n\n// slam.get_nodes().back()->write( cout);\n// cout << endl;\n\n\n    toc(\"setup\");\n    tic(\"incremental\");\n\n    if (!(batch_processing || no_optimization)) {\n      slam.update();\n    }\n\n\n// AJOUT CODE\n/*\ncout << endl << (*loader->nodes(step).begin())->name() << ' ' << (*loader->nodes(step).begin())->unique_id() << endl;\ncout<<step<<' ';\n(*loader->nodes(step).begin())->write(cout);\ncout<<endl;\nsleep(1);\n*/\n\n// AJOUT CODE\nchar fname_result_incr[FNAME_MAX];\nstrcpy(fname_result_incr,fname_result);\nstrcat(fname_result_incr,\"_incremental.txt\");\nofstream out(fname_result_incr, ios::out | ios::binary | ios::app);\nrequire(out, \"Slam.save: Cannot open output file.\");\n//out << \"test \" << endl;\n(*loader->nodes(step).begin())->write(out);\nout << endl;\n// slam.get_nodes().back()->write(out);\nout.close();\n\n// AJOUT CODE : Covariances\n\n\nNode* last_node(0); // dernier noeud\nlast_node = *loader->nodes(step).begin();\nstd::list<Node*> last_node_as_list;\nlast_node_as_list.push_back(last_node);\n\nMatrixXd cov_full = slam.covariances().marginal(last_node_as_list);\nofstream out_cov(fname_result_cov, ios::out | ios::binary | ios::app);\nrequire(out_cov, \"Slam.save: Cannot open output file.\");\nout_cov << cov_full << endl;\nout_cov.close();\n\n\n\n/*\nstd::list<std::pair<Node*, Node*> > node_pair_list_t; // Liste des noeuds calcules\nMatrixXd cov_last = slam.covariances().marginal(loader());\ncout << cov_last << endl << endl;\nsleep(1);\n*/\n\n  if (write_result) {\n\n// AJOUT CODE\n//char fname_result_incr[FNAME_MAX];\n//strcpy(fname_result_incr,fname_result);\n//strcat(fname_result_incr,\"_incremental\");\n//ofstream out(fname_result_incr, ios::out | ios::binary | ios::app);\n//require(out, \"Slam.save: Cannot open output file.\");\n//out << \"test \" << endl;\n//slam.get_nodes().back()->write(out);\n//out.close();\n\n    // cout << \"Saving last node to \" << fname_result << endl;\n    // slam.get_nodes().back()->write(fname_result);\n    // slam.save(fname_result);\n    // cout << endl;\n  }\n\n    toc(\"incremental\");\n\n    if (save_stats) {\n      stats.resize(step + 1);\n      stats[step].time = toc(t0);\n      stats[step].chi2 = slam.normalized_chi2();\n      stats[step].nnz = slam.get_R().nnz();\n      stats[step].local_chi2 = slam.local_chi2(100); // last 100 constraints\n      stats[step].nnodes = slam.get_nodes().size();\n      stats[step].nconstraints = slam.get_factors().size();\n    }\n\n    // visualization is not counted in timing\n    if (!(batch_processing || no_optimization)) {\n      visualize(step);\n    }\n  }\n\n\n  visualize(step - 1);\n\n  if (!no_optimization) {\n    if (batch_processing) {\n      tic(\"batch\");\n      slam.batch_optimization();\n      toc(\"batch\");\n    } else {\n      // end with a batch step/relinearization\n      prop.mod_batch = 1;\n      slam.set_properties(prop);\n      tic(\"final\");\n      slam.update();\n      toc(\"final\");\n    }\n  }\n\n  visualize(step - 1);\n}\n\n/**\n * The actual processing of data, in separate thread if GUI enabled.\n */\nint process(void* unused) {\n\n  // incrementally process data\n  slam.set_properties(prop);\n  incremental_slam();\n\n  toc(\"all\");\n\n// AJOUT CODE\n  // recovering the block-diagonals only of the full covariance matrix\n/*\n  cout << \"Block-diagonals only:\" << endl;\n  Covariances::node_lists_t node_lists;\n  list<Node*> nodes;\n  nodes.push_back(pose_node_1);\n  node_lists.push_back(nodes);\n  nodes.clear();\n  nodes.push_back(pose_node_2);\n  node_lists.push_back(nodes);\n  list<MatrixXd> cov_blocks = covariances.marginal(node_lists);\n  int i = 1;\n  for (list<MatrixXd>::iterator it = cov_blocks.begin(); it!=cov_blocks.end(); it++, i++) {\n    cout << \"block \" << i << endl;\n    cout << *it << endl;\n  }\n*/\n\n\n\n\n\n\n\n\n\n// AJOUT CODE\nchar fname_result_features[FNAME_MAX];\nstrcpy(fname_result_features,fname_result);\nstrcat(fname_result_features,\"_features.txt\");\nofstream out_features(fname_result_features, ios::out | ios::binary);\nrequire(out_features, \"Slam.save: Cannot open output file.\");\nout_features << \"\\0\";\n\n\n// AJOUT CODE COV AMERS\n\n\n\nchar fname_result_cov_final[FNAME_MAX];\nstrcpy(fname_result_cov_final,fname_result);\nstrcat(fname_result_cov_final,\"_cov_final.txt\");\nofstream out_cov_final(fname_result_cov_final, ios::out | ios::binary );\nrequire(out_cov_final, \"Slam.save: Cannot open output file.\");\nout_cov_final << \"\\0\";\n\n// Node* node_i(0); // noeud\n// last_node = *loader->nodes(step).begin();\nstd::list<Node*> node_i_as_list;\n// last_node_as_list.push_back(last_node);\n\n// int res;\n\n  const Covariances& covariances = slam.covariances().clone();\n  // recovering the full covariance matrix\n  cout << \"Full covariance matrix:\" << endl;\n  MatrixXd cov_full ;\n      for (list<Node*>::const_iterator it = slam.get_nodes().begin();\n          it != slam.get_nodes().end(); it++) {\nif ( strcmp ( (*it)->name(), \"Point2d\" )==0 ){\nnode_i_as_list.push_back(*it);\n(*it)->write(out_features);\nout_features << endl;\n\n// cov_full = covariances.marginal(node_i_as_list);\n// cout << cov_full << endl << endl;\n\n}\n// res = strcmp ( (*it)->name(), \"Point2d\" );\n// cout << res << endl;\n// node_i_as_list.push_back(*it);\n// cout << (*it)->name() << endl;\n\n//  MatrixXd cov_full = covariances.marginal(slam.get_nodes());\n}\n  cov_full = covariances.marginal(node_i_as_list);\n  out_cov_final << cov_full << endl << endl;\n\nout_cov_final.close();\nout_features.close();\n\n\n\n\n\n\n\n\n\n\n  if (!prop.quiet) {\n    if (!batch_processing) {\n      cout << endl;\n    }\n    double accumulated = tictoc(\"setup\") + tictoc(\"incremental\")\n        + tictoc(\"batch\");\n    cout << \"Accumulated computation time: \" << accumulated << \"s\" << endl;\n    cout << \"(Overall execution time: \" << tictoc(\"all\") << \"s)\" << endl;\n    slam.print_stats();\n    cout << endl;\n  }\n\n  if (save_stats) {\n    cout << \"Saving statistics to \" << fname_stats << endl;\n    save_statistics(fname_stats);\n    cout << endl;\n  }\n  if (write_result) {\n    cout << \"Saving result to \" << fname_result << endl;\n    slam.save(fname_result);\n    cout << endl;\n  }\n\n#ifdef USE_GUI\n  if (use_gui) {\n    while (true) {\n      if (viewer.exit_requested()) {\n        exit(0);\n      }\n      SDL_Delay(100);\n    }\n  }\n#endif\n\n  exit(0);\n}\n\n/**\n * Everything starts here.\n */\nint main(int argc, char* argv[]) {\n\n  tic(\"all\");\n\n  process_arguments(argc, argv);\n\n  cout << intro;\n\n  if (!prop.quiet) {\n    cout << \"Reading \" << fname;\n    if (parse_num_lines > 0) {\n      cout << \" (only \" << parse_num_lines << \" lines)\";\n    }\n    cout << endl;\n  }\n  // parse all data and get into suitable format for incremental processing\n  Loader loader_(fname, parse_num_lines, prop.verbose);\n  loader = &loader_;\n  if (!prop.quiet) {\n    loader_.print_stats();\n    cout << endl;\n  }\n\n  if (!prop.quiet) {\n    if (batch_processing) {\n      cout << \"Performing SAM (batch processing)\\n\";\n    } else {\n      cout << \"Performing iSAM with parameters:\\n\";\n      cout << \"  Draw/send every \" << mod_draw << \" steps\\n\";\n      cout << \"  Update every \" << prop.mod_update << \" steps\\n\";\n      cout << \"  Solve every \" << prop.mod_solve << \" steps\\n\";\n      cout << \"  Batch every \" << prop.mod_batch << \" steps\\n\";\n    }\n    cout << endl;\n  }\n\n#ifdef USE_GUI\n  if (use_gui) {\n    cout << \"3D viewer:\\n\";\n    cout << \"  Exit: Esc or \\\"q\\\"\\n\";\n    cout << \"  Reset view: \\\"r\\\"\\n\";\n    cout << \"  Toggle background color \\\"c\\\"\\n\";\n    cout << \"  Rotate: left mouse button\\n\";\n    cout << \"  Translate: middle mouse button or CTRL+left mouse button\\n\";\n    cout << \"  Scale: right mouse button or SHIFT+left mouse button or mouse wheel\\n\";\n    cout << endl;\n    // process will be run in separate thread\n    viewer.init(process);\n  } else {\n    process(NULL);\n  }\n#else\n  // no threads needed, simply run process\n  process(NULL);\n#endif\n\n  return 0;\n}\n", "meta": {"hexsha": "cc82ff7cfa9a4dfd58e319f415f3a4485233cc78", "size": 20961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulations/isam/isam/isam.cpp", "max_stars_repo_name": "CAOR-MINES-ParisTech/esde", "max_stars_repo_head_hexsha": "f7b27039b6d4e913bf9a10bd6c81838e17f87d4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T13:26:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T20:18:50.000Z", "max_issues_repo_path": "simulations/isam/isam/isam.cpp", "max_issues_repo_name": "CAOR-MINES-ParisTech/esde", "max_issues_repo_head_hexsha": "f7b27039b6d4e913bf9a10bd6c81838e17f87d4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/isam/isam/isam.cpp", "max_forks_repo_name": "CAOR-MINES-ParisTech/esde", "max_forks_repo_head_hexsha": "f7b27039b6d4e913bf9a10bd6c81838e17f87d4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-22T11:24:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T15:19:59.000Z", "avg_line_length": 27.0813953488, "max_line_length": 117, "alphanum_fraction": 0.6299317781, "num_tokens": 5599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.11279540180929934, "lm_q1q2_score": 0.0381335465655409}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Class:       NPSOLOptimizer\n//- Description: Implementation code for the NPSOLOptimizer class\n//- Owner:       Mike Eldred\n//- Checked by:\n\n#include \"dakota_system_defs.hpp\"\n#include \"DakotaModel.hpp\"\n#include \"DakotaResponse.hpp\"\n#include \"NPSOLOptimizer.hpp\"\n#include \"ProblemDescDB.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <algorithm>\n#include <sstream>\n\nstatic const char rcsId[]=\"@(#) $Id: NPSOLOptimizer.cpp 7029 2010-10-22 00:17:02Z mseldre $\";\n\n#define NPSOL_F77   F77_FUNC(npsol,NPSOL)\n// BMA (20160315): Changed to use Fortran 2003 ISO C bindings.\n// The Fortran symbol will be lowercase with same name as if in C\n//#define NPOPTN2_F77 F77_FUNC(npoptn2,NPOPTN2)\n#define NPOPTN2_F77 npoptn2\n\nextern \"C\" {\n\nvoid NPSOL_F77( int& n, int& nclin, int& ncnln, int& nrowa, int& nrowj,\n\t\tint& nrowr, double* a, double* bl, double* bu,\n\t\tvoid (*funcon)(int& mode, int& ncnln, int& n, int& nrowj,\n\t\t\t       int* needc, double* x, double* c, double* cjac, \n\t\t\t       int& nstate),\n\t\tvoid (*funobj)(int& mode, int& n, double* x, double& f,\n\t\t\t       double* gradf, int& nstate),\n\t\tint& inform, int& iter, int* istate, double* c, double* cjac,\n\t\tdouble* clambda, double& objf, double* grad, double* r,\n\t\tdouble* x, int* iw, int& leniw, double* w, int& lenw );\n\n// NOTE: replacing void* function pointers with void(NPSOLOptimizer::*) member\n// function pointers in the declaration above (in order to try to remove static\n// requirement) will compile and link, but this pointer format is not \n// acceptible to the Fortran and the call to NPSOL core dumps with an \"Illegal\n// Instruction\" message.  Also, trying to cast from a member function pointer \n// to a function pointer is not allowed by the compiler.\n\nvoid NPOPTN2_F77( const char* option_string );\n\n//void mcenvn( int& idmy1, int& idmy2, double& eps, int& idmy3, double& rdmy);\n\n}\n\n\nnamespace Dakota {\n\nNPSOLOptimizer* NPSOLOptimizer::npsolInstance(NULL);\n\n\n/** This is the primary constructor.  It accepts a Model reference. */\nNPSOLOptimizer::NPSOLOptimizer(ProblemDescDB& problem_db, Model& model):\n  Optimizer(problem_db, model, std::shared_ptr<TraitsBase>(new NPSOLTraits())),\n  SOLBase(model), setUpType(\"model\")\n{\n  // invoke SOLBase set function (shared with NLSSOLLeastSq)\n  set_options(speculativeFlag, vendorNumericalGradFlag, outputLevel,\n              probDescDB.get_int(\"method.npsol.verify_level\"),\n              probDescDB.get_real(\"method.function_precision\"),\n              probDescDB.get_real(\"method.npsol.linesearch_tolerance\"),\n              maxIterations, constraintTol, convergenceTol,\n\t      iteratedModel.gradient_type(),\n\t      iteratedModel.fd_gradient_step_size());\n}\n\n\n/** This is an alternate constructor which accepts a Model but does\n    not have a supporting method specification from the ProblemDescDB. */\nNPSOLOptimizer::NPSOLOptimizer(Model& model):\n  Optimizer(NPSOL_SQP, model, std::shared_ptr<TraitsBase>(new NPSOLTraits())),\n  SOLBase(model), setUpType(\"model\")\n{\n  // invoke SOLBase set function (shared with NLSSOLLeastSq)\n  set_options(speculativeFlag, vendorNumericalGradFlag, outputLevel, -1,\n\t      1.e-10, 0.9, maxIterations, constraintTol, convergenceTol,\n\t      iteratedModel.gradient_type(),\n\t      iteratedModel.fd_gradient_step_size());\n}\n\n\n/** This is an alternate constructor for instantiations on the fly\n    using a Model but no ProblemDescDB. */\nNPSOLOptimizer::\nNPSOLOptimizer(Model& model, const int& derivative_level, const Real& conv_tol):\n  Optimizer(NPSOL_SQP, model, std::shared_ptr<TraitsBase>(new NPSOLTraits())),\n  SOLBase(model), setUpType(\"model\")\n{\n  // Set NPSOL options (mostly use defaults)\n  std::string vlevel_s(\"Verify Level                = -1\");\n  vlevel_s.resize(72, ' ');\n  NPOPTN2_F77( vlevel_s.data() ); // NO Null terminator with std::string::data()\n\n  std::string plevel_s(\"Major Print Level           = 0\");\n  plevel_s.resize(72, ' ');\n  NPOPTN2_F77( plevel_s.data() );\n\n  // assign the derivative_level passed in\n  std::string dlevel_s(\"Derivative Level            = \");\n  dlevel_s += boost::lexical_cast<std::string>(derivative_level);\n  dlevel_s.resize(72, ' ');\n  NPOPTN2_F77( dlevel_s.data() );\n\n  // assign the conv_tol passed in\n  if (conv_tol > 0.) { // conv_tol < 0 can be passed to use the NPSOL default\n    std::ostringstream ctol_stream;\n    ctol_stream << \"Optimality Tolerance        = \"\n                << std::setiosflags(std::ios::left) << std::setw(26)<< conv_tol;\n    std::string ctol_s( ctol_stream.str() );\n    ctol_s.resize(72, ' ');\n    NPOPTN2_F77( ctol_s.data() );\n  }\n}\n\n\n/** This is an alternate constructor for performing an optimization using\n    the passed in objective function and constraint function pointers. */\nNPSOLOptimizer::NPSOLOptimizer(const RealVector& initial_point, \n  const RealVector& var_lower_bnds, const RealVector& var_upper_bnds,\n  const RealMatrix& lin_ineq_coeffs,\n  const RealVector& lin_ineq_lower_bnds,\n  const RealVector& lin_ineq_upper_bnds,\n  const RealMatrix& lin_eq_coeffs,\n  const RealVector& lin_eq_targets,\n  const RealVector& nonlin_ineq_lower_bnds,\n  const RealVector& nonlin_ineq_upper_bnds,\n  const RealVector& nonlin_eq_targets,\n  void (*user_obj_eval) (int&, int&, double*, double&, double*, int&),\n  void (*user_con_eval) (int&, int&, int&, int&, int*, double*, double*,\n\t\t\t double*, int&),\n  const int& derivative_level, const Real& conv_tol): // SOLBase default ctor\n  Optimizer(NPSOL_SQP, initial_point.length(), 0, 0, 0,\n\t    lin_ineq_coeffs.numRows(), lin_eq_coeffs.numRows(),\n\t    nonlin_ineq_lower_bnds.length(), nonlin_eq_targets.length(),\n            std::shared_ptr<TraitsBase>(new NPSOLTraits())),\n  setUpType(\"user_functions\"), initialPoint(initial_point), \n  lowerBounds(var_lower_bnds), upperBounds(var_upper_bnds), \n  userObjectiveEval(user_obj_eval), userConstraintEval(user_con_eval)\n{\n  // invoke SOLBase allocate/set functions (shared with NLSSOLLeastSq)\n  allocate_arrays(numContinuousVars, numNonlinearConstraints, lin_ineq_coeffs,\n\t\t  lin_eq_coeffs);\n  allocate_workspace(numContinuousVars, numNonlinearConstraints,\n\t\t     numLinearConstraints, 0);\n  augment_bounds(lowerBounds, upperBounds, lin_ineq_lower_bnds,\n                 lin_ineq_upper_bnds, lin_eq_targets, nonlin_ineq_lower_bnds,\n                 nonlin_ineq_upper_bnds, nonlin_eq_targets);\n\n  // Set NPSOL options (mostly use defaults)\n  std::string vlevel_s(\"Verify Level                = -1\");\n  vlevel_s.resize(72, ' ');\n  NPOPTN2_F77( vlevel_s.data() );\n\n  std::string plevel_s(\"Major Print Level           = 0\");\n  plevel_s.resize(72, ' ');\n  NPOPTN2_F77( plevel_s.data() );\n\n  // Set Derivative Level = 3 for user-supplied gradients, 0 for NPSOL\n  // vendor-numerical, ...\n  std::string dlevel_s(\"Derivative Level            = \");\n  dlevel_s += boost::lexical_cast<std::string>(derivative_level);\n  dlevel_s.resize(72, ' ');\n  NPOPTN2_F77( dlevel_s.data() );\n\n  // assign the conv_tol passed in.\n  if (conv_tol > 0.) { // conv_tol < 0 can be passed to use the NPSOL default\n    std::ostringstream ctol_stream;\n    ctol_stream << \"Optimality Tolerance        = \"\n                << std::setiosflags(std::ios::left) << std::setw(26)<< conv_tol;\n    std::string ctol_s( ctol_stream.str() );\n    ctol_s.resize(72, ' ');\n    NPOPTN2_F77( ctol_s.data() );\n  }\n}\n\n\nNPSOLOptimizer::~NPSOLOptimizer()\n{\n  // Virtual destructor handles referenceCount at Iterator level.\n\n  // invoke SOLBase deallocate function (shared with NLSSOLLeastSq)\n  if (setUpType == \"user_functions\")\n    deallocate_arrays();\n}\n\n\n#ifdef HAVE_DYNLIB_FACTORIES\nNPSOLOptimizer* new_NPSOLOptimizer(ProblemDescDB& problem_db)\n{\n#ifdef DAKOTA_DYNLIB\n  not_available(\"NPSOL\");\n  return 0;\n#else\n  return new NPSOLOptimizer(problem_db);\n#endif\n}\n\nNPSOLOptimizer* new_NPSOLOptimizer1(Model& model)\n{\n#ifdef DAKOTA_DYNLIB\n  not_available(\"NPSOL\");\n  return 0;\n#else\n  return new NPSOLOptimizer(model);\n#endif\n}\n\nNPSOLOptimizer* new_NPSOLOptimizer2(Model& model, const int& derivative_level,\n                                    const Real& conv_tol)\n{\n#ifdef DAKOTA_DYNLIB\n  not_available(\"NPSOL\");\n  return 0;\n#else\n  return new NPSOLOptimizer(model, derivative_level, conv_tol);\n#endif\n}\n\nNPSOLOptimizer* new_NPSOLOptimizer3(const RealVector& initial_point,\n  const RealVector& var_lower_bnds,\n  const RealVector& var_upper_bnds,\n  const RealMatrix& lin_ineq_coeffs,\n  const RealVector& lin_ineq_lower_bnds,\n  const RealVector& lin_ineq_upper_bnds,\n  const RealMatrix& lin_eq_coeffs,\n  const RealVector& lin_eq_targets,\n  const RealVector& nonlin_ineq_lower_bnds,\n  const RealVector& nonlin_ineq_upper_bnds,\n  const RealVector& nonlin_eq_targets,\n  void (*user_obj_eval) (int&, int&, double*, double&, double*, int&),\n  void (*user_con_eval) (int&, int&, int&, int&, int*, double*, double*,\n                         double*, int&),\n  const int& derivative_level, const Real& conv_tol)\n{\n#ifdef DAKOTA_DYNLIB\n  not_available(\"NPSOL\");\n  return 0;\n#else\n  return new NPSOLOptimizer(initial_point, var_lower_bnds, var_upper_bnds,\n\t       lin_ineq_coeffs, lin_ineq_lower_bnds, lin_ineq_upper_bnds,\n\t       lin_eq_coeffs, lin_eq_targets, nonlin_ineq_lower_bnds,\n\t       nonlin_ineq_upper_bnds, nonlin_eq_targets, user_obj_eval,\n\t       user_con_eval, derivative_level, conv_tol);\n#endif // DAKOTA_DYNLIB\n}\n#endif // HAVE_DYNLIB_FACTORIES\n\n\nvoid NPSOLOptimizer::\nobjective_eval(int& mode, int& n, double* x, double& f, double* gradf,\n\t       int& nstate)\n{\n  // NPSOL computes constraints first, then the objective function.  However, \n  // Dakota assumes that the objective and constraint function values are all \n  // computed in a single fn. evaluation. A numNonlinearConstraints check is\n  // therefore needed to ensure that 1 and only 1 mapping occurs.\n\n  // Handle special cases with asv_request (see SOLBase::constraint_eval)\n  short asv_request = mode + 1; // default definition of asv_request\n\n  //if ( !(solInstance->derivLevel & 1) && (asv_request & 2) ) { // more general\n  if (npsolInstance->vendorNumericalGradFlag && (asv_request & 2) ) {\n    asv_request -= 2; // downgrade request\n    if (npsolInstance->numNonlinearConstraints == 0) { // else already printed\n      Cout << \"NPSOL has requested objective gradient for case of vendor \"\n\t   << \"numerical gradients.\\n\";\n      if (asv_request)\n\tCout << \"Request will be downgraded to objective value alone.\\n\"\n             << std::endl;\n      else\n\tCout << \"Request will be ignored and no evaluation performed.\\n\"\n             << std::endl;\n    }\n  }\n\n  if (asv_request && npsolInstance->numNonlinearConstraints == 0) {\n    // constraint_eval has not been called.  Therefore, set vars/asv\n    // and perform an evaluate() prior to data recovery.\n    RealVector local_des_vars(n, false);\n    copy_data(x, n, local_des_vars);\n    npsolInstance->iteratedModel.continuous_variables(local_des_vars);\n    npsolInstance->activeSet.request_values(asv_request);\n    npsolInstance->\n      iteratedModel.evaluate(npsolInstance->activeSet);\n    if (++npsolInstance->fnEvalCntr == npsolInstance->maxFunctionEvals) {\n      mode = -1; // terminate NPSOL (see mode discussion in \"User-Supplied\n\t         // Subroutines\" section of NPSOL manual)\n      Cout << \"Iteration terminated: max_function_evaluations limit has been \"\n\t   << \"met.\" << std::endl;\n    }\n  }\n  \n  const Response& local_response\n    = npsolInstance->iteratedModel.current_response();\n  // Any MOO/NLS recasting is responsible for setting the scalar min/max\n  // sense within the recast.\n  const BoolDeque& max_sense\n    = npsolInstance->iteratedModel.primary_response_fn_sense();\n  bool max_flag = (!max_sense.empty() && max_sense[0]);\n  if (asv_request & 1)\n    f = (max_flag) ? -local_response.function_value(0) :\n                      local_response.function_value(0);\n  if (asv_request & 2) {\n    const Real* local_grad = local_response.function_gradient(0);\n    if (max_flag)\n      for (size_t i=0; i<n; ++i)\n\tgradf[i] = -local_grad[i];\n    else\n      std::copy(local_grad, local_grad + n, gradf);\n  }\n}\n\n\nvoid NPSOLOptimizer::core_run()\n{\n  if (setUpType == \"model\")\n    find_optimum_on_model();\n  else if (setUpType == \"user_functions\")\n    find_optimum_on_user_functions();\n  else {\n    Cerr << \"Error: bad setUpType in NPSOLOptimizer::core_run().\"\n         << std::endl;\n    abort_handler(-1);\n  }\n}\n\n\nvoid NPSOLOptimizer::find_optimum_on_model()\n{\n  //------------------------------------------------------------------\n  //     Solve the problem.\n  //------------------------------------------------------------------\n\n  // set the object instance pointers for use within the static member fns\n  NPSOLOptimizer* prev_nps_instance = npsolInstance;\n  SOLBase*        prev_sol_instance = solInstance;\n  npsolInstance = this; solInstance = this; optLSqInstance = this;\n\n  // Augmentation of bounds appears here rather than in the constructor because\n  // set the constraint offset used in SOLBase::constraint_eval()\n  constrOffset = numObjectiveFns;\n\n  fnEvalCntr = 0; // prevent current iterator from continuing previous counting\n\n  // casts for Fortran interface\n  int num_cv = numContinuousVars;\n  int num_linear_constraints = numLinearConstraints;\n  int num_nonlinear_constraints = numNonlinearConstraints;\n\n  double     local_f_val = 0.;\n  RealVector local_f_grad(numContinuousVars, true);\n\n  allocate_arrays(numContinuousVars, numNonlinearConstraints,\n\t\t  iteratedModel.linear_ineq_constraint_coeffs(),\n\t\t  iteratedModel.linear_eq_constraint_coeffs());\n  allocate_workspace(numContinuousVars, numNonlinearConstraints,\n                     numLinearConstraints, 0);\n\n  // NPSOL requires a non-zero array size.  Therefore, size the local \n  // constraint arrays and matrices to a size of 1 if there are no nonlinear\n  // constraints and to the proper size otherwise.\n  RealVector local_c_vals(nlnConstraintArraySize);\n\n  // initialize local_des_vars with DB initial point.  Variables are updated \n  // in constraint_eval/objective_eval\n  RealVector local_des_vars;\n  copy_data(iteratedModel.continuous_variables(), local_des_vars);\n\n  // these bounds must be updated from model bounds each time an iterator is\n  // run within the B&B minimizer.\n  RealVector augmented_l_bnds, augmented_u_bnds;\n  copy_data(iteratedModel.continuous_lower_bounds(), augmented_l_bnds);\n  copy_data(iteratedModel.continuous_upper_bounds(), augmented_u_bnds);\n  augment_bounds(augmented_l_bnds, augmented_u_bnds, iteratedModel);\n\n  NPSOL_F77( num_cv, num_linear_constraints, num_nonlinear_constraints, \n\t     linConstraintArraySize, nlnConstraintArraySize, num_cv, \n\t     linConstraintMatrixF77, augmented_l_bnds.values(),\n\t     augmented_u_bnds.values(), constraint_eval, objective_eval,\n\t     informResult, numberIterations, &constraintState[0],\n\t     local_c_vals.values(), constraintJacMatrixF77, &cLambda[0],\n\t     local_f_val, local_f_grad.values(), upperFactorHessianF77,\n\t     local_des_vars.values(), &intWorkSpace[0], intWorkSpaceSize,\n\t     &realWorkSpace[0], realWorkSpaceSize );\n\n  // NPSOL completed. Do post-processing/output of final NPSOL info and data:\n  Cout << \"\\nNPSOL exits with INFORM code = \" << informResult\n       << \" (see \\\"Interpretation of output\\\" section in NPSOL manual)\\n\";\n\n  // invoke SOLBase deallocate function (shared with NLSSOLLeastSq)\n  deallocate_arrays();\n\n  // Set best variables and response for use at higher levels.\n  // local_des_vars, local_f_val, & local_c_vals contain the optimal design \n  // (not the final fn. eval) since NPSOL performs this assignment internally \n  // prior to exiting (see \"Subroutine npsol\" section of NPSOL manual).\n  bestVariablesArray.front().continuous_variables(local_des_vars);\n  if (!localObjectiveRecast) { // else local_objective_recast_retrieve()\n                               // is used in Optimizer::post_run()\n    RealVector best_fns(numFunctions, false);\n    const BoolDeque& max_sense = iteratedModel.primary_response_fn_sense();\n    best_fns[0] = (!max_sense.empty() && max_sense[0]) ?\n      -local_f_val : local_f_val;\n    if (numNonlinearConstraints)\n      //copy_data_partial(local_c_vals, best_fns, 1);\n      std::copy(local_c_vals.values(),\n                local_c_vals.values() + nlnConstraintArraySize,\n                best_fns.values() + 1);\n    bestResponseArray.front().function_values(best_fns);\n  }\n\n  /*\n  // For better post-processing, could append fort.9 to dakota.out line\n  // by line, but: THERE IS A PROBLEM WITH GETTING ALL OF THE FILE!\n  // (FORTRAN output is lacking a final buffer flush?)\n  Cout << \"\\nEcho NPSOL's iteration output from fort.9 file:\\n\" << std::endl;\n  ifstream npsol_fort_9( \"fort.9\" );\n  char fort_9_line[255];\n  while (npsol_fort_9) {\n    npsol_fort_9.getline( fort_9_line, 255 );\n    Cout << fort_9_line << '\\n';\n  }\n  Cout << std::endl;\n  */\n  Cout << \"\\nNOTE: see Fortran device 9 file (fort.9 or ftn09)\"\n       << \"\\n      for complete NPSOL iteration history.\" << std::endl;\n\n  // restore in case of recursion\n  npsolInstance  = prev_nps_instance;\n  solInstance    = prev_sol_instance;\n  optLSqInstance = prevMinInstance;\n}\n\n\nvoid NPSOLOptimizer::find_optimum_on_user_functions()\n{\n  //------------------------------------------------------------------\n  //     Solve the problem.\n  //------------------------------------------------------------------\n\n  int i;\n\n  // casts for Fortran interface\n  int num_cv = numContinuousVars;\n  int num_linear_constraints = numLinearConstraints;\n  int num_nonlinear_constraints = numNonlinearConstraints;\n\n  double     local_f_val = 0.;\n  RealVector local_f_grad(numContinuousVars, true);\n  RealVector local_c_vals(nlnConstraintArraySize);\n  \n  NPSOL_F77( num_cv, num_linear_constraints, num_nonlinear_constraints, \n\t     linConstraintArraySize, nlnConstraintArraySize, num_cv, \n\t     linConstraintMatrixF77, lowerBounds.values(), upperBounds.values(),\n\t     userConstraintEval, userObjectiveEval, informResult,\n\t     numberIterations, &constraintState[0], local_c_vals.values(),\n\t     constraintJacMatrixF77, &cLambda[0], local_f_val,\n\t     local_f_grad.values(), upperFactorHessianF77,\n\t     initialPoint.values(), &intWorkSpace[0], intWorkSpaceSize,\n\t     &realWorkSpace[0], realWorkSpaceSize );\n\n  bestVariablesArray.front().continuous_variables(initialPoint);\n  // user-functions mode is restricted to single-objective optimization\n  RealVector best_fns(numFunctions, false);\n  best_fns[0] = local_f_val;\n  if (numNonlinearConstraints)\n    //copy_data_partial(local_c_vals, best_fns, 1);\n    std::copy(local_c_vals.values(),\n              local_c_vals.values() + nlnConstraintArraySize,\n              best_fns.values() + 1);\n  bestResponseArray.front().function_values(best_fns);\n}\n\n} // namespace Dakota\n", "meta": {"hexsha": "aec30aa4ed07ef9fadd0ef1219e4e5b5b4bb2508", "size": 19075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NPSOLOptimizer.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NPSOLOptimizer.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NPSOLOptimizer.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2489711934, "max_line_length": 93, "alphanum_fraction": 0.7091480996, "num_tokens": 5070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.09009298724347511, "lm_q1q2_score": 0.03806470598486444}}
{"text": "﻿/***\r\n第四节 可变参模板\r\n（4）可变参类模板：允许模板定义中包含0到多个（任意个）模板参数。\r\n参数包展开方式有多种。介绍典型的展开方式。\r\n（4.1）通过递归继承方式展开类型、非类型、模板模板参数包\r\n1：类型模板参数包的展开一例\r\n有时只写类模板声明而不写类模板定义的手法非常重要,靠这种手段能够帮助排错。\r\n目前讲解的范例取材于C++标准库中的tuple(元组)\r\n2：非类型模板参数包展开一例\r\n3：模板模板参数包的展开一例\r\n//ParentMM<int>\r\n//ParentMM<int,deque>\r\n//ParentMM<int,list,deque>\r\n//ParentMM<int,vector,list,deque>\r\n//myclasst3<int, vector, list, deque>\r\n***/\r\n\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <list>\r\n#include <deque>\r\n\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\n//非类型模板参数包展开一例\r\nnamespace _nmsp1\r\n{\r\n\t//主模板定义（泛化版本的类模板）\r\n\ttemplate <typename ...Args>\r\n\tclass myclasst\r\n\t{\r\n\tpublic:\r\n\t\tmyclasst()\r\n\t\t{\r\n\t\t\tprintf(\"myclasst::myclasst()泛化版本执行了,this = %p\\n\", this);\r\n\t\t}\r\n\t};\r\n\t//template <typename ...Args>class myclasst; //主模板声明(前向声明/前置声明)\r\n\r\n\ttemplate <typename First, typename ... Others>\r\n\tclass myclasst<First, Others...> :private myclasst<Others...>  //偏特化\r\n\t{\r\n\tpublic:\r\n\t\tmyclasst() :m_i(0)\r\n\t\t{\r\n\t\t\tprintf(\"myclasst::myclasst()偏特化版本执行了，this = %p,sizeof...(Others)=%d\\n\", this, sizeof...(Others));\r\n\t\t}\r\n\r\n\t\tmyclasst(First parf, Others... paro) :m_i(parf), myclasst<Others...>(paro...)\r\n\t\t{\r\n\t\t\tprintf(\"myclasst::myclasst(parf,...paro)执行了,this = %p\\n\", this);\r\n\t\t\tcout << \"m_i = \" << m_i << endl;\r\n\t\t}\r\n\t\t\r\n\t\tFirst m_i;\r\n\t};\r\n\r\n\ttemplate<>\r\n\tclass myclasst<>    //一个特殊的特化版本,看起来象全特化,不是全特化,可变参模板不存在全特化\r\n\t{\r\n\tpublic:\r\n\t\tmyclasst()\r\n\t\t{\r\n\t\t\tprintf(\"myclasst::myclasst()特殊的特化版本执行了,this = %p\\n\", this);\r\n\t\t}\r\n\t};\r\n\r\n\t/*\r\n\ttemplate <typename ...Args1, typename ... Args2>\r\n\tclass myclasst2 {};\r\n\t\r\n\ttemplate <typename ...Args, typename U>\r\n\tclass myclasst3 {};\r\n\t*/\r\n}\r\n\r\n//类型模板参数包的展开一例\r\nnamespace _nmsp2\r\n{\r\n\t//主模板定义(泛化版本的类模板)\r\n\ttemplate <int ...FTArgs>            //int 替换为auto也可以\r\n\tclass myclasst2\r\n\t{\r\n\tpublic:\r\n\t\tmyclasst2()\r\n\t\t{\r\n\t\t\tprintf(\"myclasst2::myclasst2()泛化版本执行了,this = %p\\n\", this);\r\n\t\t}\r\n\t};\r\n\t\r\n\ttemplate <int First,int ...Others> //int替换成auto也没问题\r\n\tclass myclasst2<First, Others...> :private myclasst2<Others...> //偏特化\r\n\t{\r\n\tpublic:\r\n\t\tmyclasst2()\r\n\t\t{\r\n\t\t\tprintf(\"myclasst2::myclasst2()偏特化版本执行了，this = %p,sizeof...(Others)=%d,First=%d\\n\", this, sizeof...(Others),First);\r\n\t\t}\r\n\t};\r\n\r\n}\r\n\r\n//模板模板参数包的展开一例\r\nnamespace _nmsp3\r\n{\r\n\t//泛化版本\r\n\ttemplate<typename T,\r\n\t\t\t template<typename> typename... Container>\r\n\tclass ParentMM\r\n\t{\r\n\tpublic:\r\n\t\tParentMM()\r\n\t\t{\r\n\t\t\tprintf(\"ParentMM::ParentMM()泛化版本执行了,this = %p\\n\", this);\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate<typename T,\r\n\t\t     template<typename> typename FirstContainer,\r\n\t\t     template<typename> typename... OtherContainers>\r\n\tclass ParentMM<T, FirstContainer, OtherContainers...> :private ParentMM<T, OtherContainers...> //偏特化\r\n\t{\r\n\tpublic:\r\n\t\tParentMM()\r\n\t\t{\r\n\t\t\tprintf(\"ParentMM::ParentMM()偏特化版本执行了，this = %p,sizeof...(OtherContainers)=%d\\n\", this, sizeof...(OtherContainers));\r\n\t\t\tm_container.push_back(12);\r\n\t\t}\r\n\r\n\t\tFirstContainer<T>  m_container;\r\n\t};\r\n\r\n\ttemplate<typename T,\r\n\t\t     template<typename> typename... Container>\r\n\tclass myclasst3 :private ParentMM<T, Container...>\r\n\t{\r\n\tpublic:\r\n\t\tmyclasst3()\r\n\t\t{\r\n\t\t\tprintf(\"myclasst3::myclasst3()执行了，this = %p,T的类型是:%s，Container参数个数是%d个\\n\",\r\n\t\t\t\t   this, typeid(T).name(), sizeof...(Container));   //以后会用boost库中的type_id_with_cvr<.......>().pretty_name()。\r\n\t\t}\r\n\t};\r\n\r\n}\r\n\r\nint main()\r\n{\r\n\t_nmsp1::myclasst<int, float, double> myc;\r\n\t//_nmsp1::myclasst<int, float, double> myc(12,13.5,23);\r\n\r\n\t_nmsp2::myclasst2<12, 18, 23> myc2;\r\n\t//_nmsp3::myclasst3<int, vector, list, deque> myc3;\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "f7b2bd4c8a5b16c17bb5361620d6d1300579f256", "size": 3493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/215.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/215.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/215.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 21.6956521739, "max_line_length": 119, "alphanum_fraction": 0.6312625251, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.16885695841556156, "lm_q1q2_score": 0.038063162368910816}}
{"text": "//  Copyright John Maddock 2006.\r\n//  Copyright Paul A. Bristow 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// TODO deal with infinity as special better - or remove.\r\n//\r\n\r\n#ifndef BOOST_STATS_UNIFORM_HPP\r\n#define BOOST_STATS_UNIFORM_HPP\r\n\r\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3668.htm\r\n// http://mathworld.wolfram.com/UniformDistribution.html\r\n// http://documents.wolfram.com/calculationcenter/v2/Functions/ListsMatrices/Statistics/UniformDistribution.html\r\n// http://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29\r\n\r\n#include <boost/math/distributions/fwd.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\n  namespace detail\r\n  {\r\n    template <class RealType, class Policy>\r\n    inline bool check_uniform_lower(\r\n      const char* function,\r\n      RealType lower,\r\n      RealType* result, const Policy& pol)\r\n    {\r\n      if((boost::math::isfinite)(lower))\r\n      { // any finite value is OK.\r\n        return true;\r\n      }\r\n      else\r\n      { // Not finite.\r\n        *result = policies::raise_domain_error<RealType>(\r\n          function,\r\n          \"Lower parameter is %1%, but must be finite!\", lower, pol);\r\n        return false;\r\n      }\r\n    } // bool check_uniform_lower(\r\n\r\n    template <class RealType, class Policy>\r\n    inline bool check_uniform_upper(\r\n      const char* function,\r\n      RealType upper,\r\n      RealType* result, const Policy& pol)\r\n    {\r\n      if((boost::math::isfinite)(upper))\r\n      { // Any finite value is OK.\r\n        return true;\r\n      }\r\n      else\r\n      { // Not finite.\r\n        *result = policies::raise_domain_error<RealType>(\r\n          function,\r\n          \"Upper parameter is %1%, but must be finite!\", upper, pol);\r\n        return false;\r\n      }\r\n    } // bool check_uniform_upper(\r\n\r\n    template <class RealType, class Policy>\r\n    inline bool check_uniform_x(\r\n      const char* function,\r\n      RealType const& x,\r\n      RealType* result, const Policy& pol)\r\n    {\r\n      if((boost::math::isfinite)(x))\r\n      { // Any finite value is OK\r\n        return true;\r\n      }\r\n      else\r\n      { // Not finite..\r\n        *result = policies::raise_domain_error<RealType>(\r\n          function,\r\n          \"x parameter is %1%, but must be finite!\", x, pol);\r\n        return false;\r\n      }\r\n    } // bool check_uniform_x\r\n\r\n    template <class RealType, class Policy>\r\n    inline bool check_uniform(\r\n      const char* function,\r\n      RealType lower,\r\n      RealType upper,\r\n      RealType* result, const Policy& pol)\r\n    {\r\n      if((check_uniform_lower(function, lower, result, pol) == false)\r\n        || (check_uniform_upper(function, upper, result, pol) == false))\r\n      {\r\n        return false;\r\n      }\r\n      else if (lower >= upper) // If lower == upper then 1 / (upper-lower) = 1/0 = +infinity!\r\n      { // upper and lower have been checked before, so must be lower >= upper.\r\n        *result = policies::raise_domain_error<RealType>(\r\n          function,\r\n          \"lower parameter is %1%, but must be less than upper!\", lower, pol);\r\n        return false;\r\n      }\r\n      else\r\n      { // All OK,\r\n        return true;\r\n      }\r\n    } // bool check_uniform(\r\n\r\n  } // namespace detail\r\n\r\n  template <class RealType = double, class Policy = policies::policy<> >\r\n  class uniform_distribution\r\n  {\r\n  public:\r\n    typedef RealType value_type;\r\n    typedef Policy policy_type;\r\n\r\n    uniform_distribution(RealType l_lower = 0, RealType l_upper = 1) // Constructor.\r\n      : m_lower(l_lower), m_upper(l_upper) // Default is standard uniform distribution.\r\n    {\r\n      RealType result;\r\n      detail::check_uniform(\"boost::math::uniform_distribution<%1%>::uniform_distribution\", l_lower, l_upper, &result, Policy());\r\n    }\r\n    // Accessor functions.\r\n    RealType lower()const\r\n    {\r\n      return m_lower;\r\n    }\r\n\r\n    RealType upper()const\r\n    {\r\n      return m_upper;\r\n    }\r\n  private:\r\n    // Data members:\r\n    RealType m_lower;  // distribution lower aka a.\r\n    RealType m_upper;  // distribution upper aka b.\r\n  }; // class uniform_distribution\r\n\r\n  typedef uniform_distribution<double> uniform;\r\n\r\n  template <class RealType, class Policy>\r\n  inline const std::pair<RealType, RealType> range(const uniform_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>(-max_value<RealType>(), max_value<RealType>()); // - to + 'infinity'.\r\n     // Note RealType infinity is NOT permitted, only max_value.\r\n  }\r\n\r\n  template <class RealType, class Policy>\r\n  inline const std::pair<RealType, RealType> support(const uniform_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     return std::pair<RealType, RealType>(dist.lower(),  dist.upper());\r\n  }\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType pdf(const uniform_distribution<RealType, Policy>& dist, const RealType& x)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::pdf(const uniform_distribution<%1%>&, %1%)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if(false == detail::check_uniform_x(\"boost::math::pdf(const uniform_distribution<%1%>&, %1%)\", x, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n\r\n    if((x < lower) || (x > upper) )\r\n    {\r\n      return 0;\r\n    }\r\n    else\r\n    {\r\n      return 1 / (upper - lower);\r\n    }\r\n  } // RealType pdf(const uniform_distribution<RealType, Policy>& dist, const RealType& x)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType cdf(const uniform_distribution<RealType, Policy>& dist, const RealType& x)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::cdf(const uniform_distribution<%1%>&, %1%)\",lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if(false == detail::check_uniform_x(\"boost::math::cdf(const uniform_distribution<%1%>&, %1%)\", x, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if (x < lower)\r\n    {\r\n      return 0;\r\n    }\r\n    if (x > upper)\r\n    {\r\n      return 1;\r\n    }\r\n    return (x - lower) / (upper - lower); // lower <= x <= upper\r\n  } // RealType cdf(const uniform_distribution<RealType, Policy>& dist, const RealType& x)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType quantile(const uniform_distribution<RealType, Policy>& dist, const RealType& p)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0; // of checks\r\n    if(false == detail::check_uniform(\"boost::math::quantile(const uniform_distribution<%1%>&, %1%)\",lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if(false == detail::check_probability(\"boost::math::quantile(const uniform_distribution<%1%>&, %1%)\", p, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if(p == 0)\r\n    {\r\n      return lower;\r\n    }\r\n    if(p == 1)\r\n    {\r\n      return upper;\r\n    }\r\n    return p * (upper - lower) + lower;\r\n  } // RealType quantile(const uniform_distribution<RealType, Policy>& dist, const RealType& p)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType cdf(const complemented2_type<uniform_distribution<RealType, Policy>, RealType>& c)\r\n  {\r\n    RealType lower = c.dist.lower();\r\n    RealType upper = c.dist.upper();\r\n    RealType x = c.param;\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::cdf(const uniform_distribution<%1%>&, %1%)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if(false == detail::check_uniform_x(\"boost::math::cdf(const uniform_distribution<%1%>&, %1%)\", x, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if (x < lower)\r\n    {\r\n      return 1;\r\n    }\r\n    if (x > upper)\r\n    {\r\n      return 0;\r\n    }\r\n    return (upper - x) / (upper - lower);\r\n  } // RealType cdf(const complemented2_type<uniform_distribution<RealType, Policy>, RealType>& c)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType quantile(const complemented2_type<uniform_distribution<RealType, Policy>, RealType>& c)\r\n  {\r\n    RealType lower = c.dist.lower();\r\n    RealType upper = c.dist.upper();\r\n    RealType q = c.param;\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::quantile(const uniform_distribution<%1%>&, %1%)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    if(false == detail::check_probability(\"boost::math::quantile(const uniform_distribution<%1%>&, %1%)\", q, &result, Policy()))\r\n    {\r\n       return result;\r\n    }\r\n    if(q == 0)\r\n    {\r\n       return upper;\r\n    }\r\n    if(q == 1)\r\n    {\r\n       return lower;\r\n    }\r\n    return -q * (upper - lower) + upper;\r\n  } // RealType quantile(const complemented2_type<uniform_distribution<RealType, Policy>, RealType>& c)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType mean(const uniform_distribution<RealType, Policy>& dist)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0;  // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::mean(const uniform_distribution<%1%>&)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    return (lower + upper ) / 2;\r\n  } // RealType mean(const uniform_distribution<RealType, Policy>& dist)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType variance(const uniform_distribution<RealType, Policy>& dist)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::variance(const uniform_distribution<%1%>&)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    return (upper - lower) * ( upper - lower) / 12;\r\n    // for standard uniform = 0.833333333333333333333333333333333333333333;\r\n  } // RealType variance(const uniform_distribution<RealType, Policy>& dist)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType mode(const uniform_distribution<RealType, Policy>& dist)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::mode(const uniform_distribution<%1%>&)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    result = lower; // Any value [lower, upper] but arbitrarily choose lower.\r\n    return result;\r\n  }\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType median(const uniform_distribution<RealType, Policy>& dist)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::median(const uniform_distribution<%1%>&)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    return (lower + upper) / 2; //\r\n  }\r\n  template <class RealType, class Policy>\r\n  inline RealType skewness(const uniform_distribution<RealType, Policy>& dist)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0; // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::skewness(const uniform_distribution<%1%>&)\",lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    return 0;\r\n  } // RealType skewness(const uniform_distribution<RealType, Policy>& dist)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType kurtosis_excess(const uniform_distribution<RealType, Policy>& dist)\r\n  {\r\n    RealType lower = dist.lower();\r\n    RealType upper = dist.upper();\r\n    RealType result = 0;  // of checks.\r\n    if(false == detail::check_uniform(\"boost::math::kurtosis_execess(const uniform_distribution<%1%>&)\", lower, upper, &result, Policy()))\r\n    {\r\n      return result;\r\n    }\r\n    return static_cast<RealType>(-6)/5; //  -6/5 = -1.2;\r\n  } // RealType kurtosis_excess(const uniform_distribution<RealType, Policy>& dist)\r\n\r\n  template <class RealType, class Policy>\r\n  inline RealType kurtosis(const uniform_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_UNIFORM_HPP\r\n\r\n\r\n\r\n", "meta": {"hexsha": "b4307a6e3025aff9b9f4892d461e3e443df4cd5c", "size": 13151, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/distributions/uniform.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/math/distributions/uniform.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/math/distributions/uniform.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 34.3368146214, "max_line_length": 139, "alphanum_fraction": 0.6297619953, "num_tokens": 3223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356686808225123, "lm_q2_score": 0.09401018152032078, "lm_q1q2_score": 0.03793939452399979}}
{"text": "/* Hector -- A Simple Climate Model\n   Copyright (C) 2014-2015  Battelle Memorial Institute\n\n   Please see the accompanying file LICENSE.md for additional licensing\n   information.\n*/\n/*\n *  oceanbox.cpp\n *  hector\n *\n *  Created by Corinne Hartin on 1/31/13\n *\n */\n\n#include <boost/math/tools/minima.hpp>\n#include <iomanip>\n\n#include \"oceanbox.hpp\"\n\nnamespace Hector {\n  \nusing namespace std;\n\n//------------------------------------------------------------------------------\n/*! \\brief a new oceanbox logger\n *\n * The oceanbox logger may or may not be defined and therefore we check before logging\n */\n#define OB_LOG(log, level)  \\\nif( log != NULL ) H_LOG( (*log), level )\n\n//------------------------------------------------------------------------------\n/*! \\brief Constructor\n */\noceanbox::oceanbox() {\n    logger = NULL;\n    deltaT.set( 0.0, U_DEGC );\n    initbox( unitval( 0.0, U_PGC ), \"?\" );\n    surfacebox = false;\n    preindustrial_flux.set( 0.0, U_PGC_YR );\n    warmingfactor = 1.0;      // by default warms exactly as global\n    Tbox = unitval( -999, U_DEGC );\n    atmosphere_flux.set( 0.0, U_PGC );\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief sets the amount of carbon in this box\n */\nvoid oceanbox::set_carbon( const unitval C) {\n\tcarbon = C;\n\tOB_LOG( logger, Logger::WARNING ) << Name << \" box C has been set to \" << carbon << endl;\n\tcarbonHistory.insert( carbonHistory.begin(), C.value( U_PGC ) );\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief initialize basic information in an oceanbox\n */\nvoid oceanbox::initbox( unitval C, string N ) {\n    // Reset the box to its pristine state\n    connection_list.clear();\n    connection_k.clear();\n    carbonHistory.clear(); \n    carbonLossHistory.clear();\n    connection_window.clear();\n    annual_box_fluxes.clear();\n    \n    set_carbon( C );\n    if( N != \"\" ) Name = N;\n    CarbonToAdd.set( 0.0, U_PGC );  // each box is separate from each other, and we keep track of carbon in each box.\n    active_chemistry = false;\n    \n    OB_LOG( logger, Logger::NOTICE) << \"hello \" << N << endl;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief          Add carbon to an oceanbox\n *  \\param[in] C    amount of carbon to add to this box\n *\n *  Carbon flows between boxes arrive via this method. Any carbon (it must be\n *  a positive value) is scheduled for addition; the actual increment happens\n *  in update_state().\n */\nvoid oceanbox::add_carbon( unitval C ) {\n\tH_ASSERT( C.value( U_PGC ) >= 0.0, \"add_carbon called with negative value\" );\n\tCarbonToAdd = CarbonToAdd + C;\n\tOB_LOG( logger, Logger::DEBUG) << Name << \" receiving \" << C << \" (\" << CarbonToAdd << \")\" << endl;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief          Compute absolute temperature of box in C\n *  \\param[in] Tgav Mean global temperature change from preindustrial, C\n *  \\returns        Absolute temperature of box, C\n */\nunitval oceanbox::compute_tabsC( const unitval Tgav ) const {\n    return Tgav * warmingfactor + unitval( MEAN_GLOBAL_TEMP, U_DEGC ) + deltaT;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief          Is box C oscillating?\n *  \\param[in] lookback     Window size to look back into the past\n *  \\param[in] maxamp       Max amplitude (% of box size) allowed\n *  \\param[in] maxflips     Max flips (direction reversals) allowed\n *  \\returns                bool indicating whether box C is oscillating recently\n *  \\details                How do we identify is the box is oscillating? Count how many\n *  sign flips there are in the deltas (C(t)-C(t-1)) of a certain magnitude.\n */\nbool oceanbox::oscillating( const unsigned lookback, const double maxamp, const int maxflips ) const {\n    \n#define sgn( x ) ( x > 0 ) - ( x < 0 )\n    \n    if( carbonHistory.size() < lookback ) return false;\n    \n    const double currentC = carbon.value( U_PGC );\n    double minC = currentC, maxC = currentC;\n    double lastdelta = currentC - carbonHistory[ 0 ];\n    int flipcount = 0;\n    for ( unsigned i=0; i<lookback-1; i++ )  {\n        double delta = carbonHistory[ i ]-carbonHistory[ i+1 ];\n        flipcount += ( sgn( lastdelta ) != sgn( delta ) );\n        lastdelta = delta;\n        minC = min( minC, carbonHistory[ i ] );\n        maxC = max( maxC, carbonHistory[ i ] );\n    }\n    return flipcount>maxflips && ( maxC-minC )/currentC*100 > maxamp;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief                  Calculate mean past box carbon\n *  \\param[in] lookback     Window size to look back into the past (including current value)\n *  \\returns                bool indicating whether box C is oscillating recently\n *  \\exception              lookback must be non-negative\n */\ndouble oceanbox::vectorHistoryMean( std::vector<double> v, int lookback ) const {\n    H_ASSERT( lookback > 0, \"lookback must be >0\" );\n    H_ASSERT( v.size() > 0, \"vector size must be >0\" );\n\n    lookback = min<int>( int( v.size() ), lookback );\n\n    double sum = 0.0;\n    for ( int j=0; j<lookback; j++ )  {\n        sum += v[ j ]; // sum up the past states\n    }\n    return sum / lookback;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief          Add (or replace) a box-to-box connection\n *  \\param[in] ob   pointer to another oceanbox\n *  \\param[in] k    weight of the connection\n *  \\param[in] ws   connection window size: 0=current state only, 1=mean of current and 1 year back, etc.\n *  \\exception      if ob is same as current box\n *\n *  Establishes a one-way connection from the current box to another, with a weight of\n *  k. If a connection already exists, it will be overwritten (i.e. only two connections\n *  between any two boxes are allowed, one in each direction).  Window establishes how many previous\n *  time step connections to use.\n */\nvoid oceanbox::make_connection( oceanbox* ob, const double k, const int ws ) { //, window=1 or whatever we are averaging over.  use curent state of 1 or will use what we tell it to use.\n    \n\tH_ASSERT( ob != this, \"can't make connection to same box\" );\n\tOB_LOG( logger, Logger::NOTICE) << \"Adding connection \" << Name << \" to \" << ob->Name << \", k=\" << k << endl;\n    \n\t// If a connection to this box already exists, replace it\n\tfor( unsigned i=0; i<connection_list.size(); i++ ) {\n\t\tif( connection_list[ i ]==ob ) {\n\t\t\tconnection_k[ i ] = k;\n\t\t\tconnection_window[ i ] = ws;\n\t\t\tOB_LOG( logger, Logger::WARNING) << \"** overwriting connection in \" << Name << \" ** \" << endl;\n\t\t\tOB_LOG( logger, Logger::WARNING) << \"** Are you sure about this? ** \" << endl;\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\t// Otherwise, make a new connection\n\tconnection_list.push_back( ob ); // add new element to vector\n\tconnection_k.push_back( k );\n\tH_ASSERT( ws >= 0, \"window negative number\" );\n\tconnection_window.push_back( ws );\n}\n\n//------------------------------------------------------------------------------\ndouble round( const double d ) { return floor( d + 0.5 ); }\n\n//------------------------------------------------------------------------------\n/*! \\brief Log the current box state\n *\n *  Writes a variety of information (carbon, temperature, DIC, etc.),\n *  as well as connection summaries, to the active log.\n */\nvoid oceanbox::log_state() {\n\tOB_LOG( logger, Logger::DEBUG) << \"----- State of \" << Name << \" box -----\" << endl;\n    unitval futurec = carbon + CarbonToAdd + atmosphere_flux;\n\tOB_LOG( logger, Logger::DEBUG) << \"   carbon = \" << carbon << \" -> \" << futurec << endl;\n\tOB_LOG( logger, Logger::DEBUG) << \"   T=\" << Tbox << \", surfacebox=\" << surfacebox << \", active_chemistry=\" << active_chemistry << endl;\n\tOB_LOG( logger, Logger::DEBUG) << \"   CarbonToAdd = \" << CarbonToAdd << \" (\"\n        << ( CarbonToAdd/carbon*100 ) << \"%)\" << endl;\n    if( surfacebox ) {\n        OB_LOG( logger, Logger::DEBUG) << \"   FPgC = \" << atmosphere_flux << \" (\"\n            << ( atmosphere_flux/carbon*100 ) << \"%)\" << endl;\n    }\n\n    unitval K0 = mychemistry.get_K0();\n    unitval Tr = mychemistry.get_Tr();\n\tOB_LOG( logger, Logger::DEBUG) << \"   K0 = \" << K0 << \" \" << \"Tr = \" << Tr << endl;\n    \n\tif( active_chemistry ) {\n        unitval dic = mychemistry.convertToDIC( carbon );\n\t\tOB_LOG( logger, Logger::DEBUG) << \"   Surface DIC = \" << dic << endl;\n    }\n\tfor( unsigned i=0; i<connection_list.size(); i++ ) {\n\t\tOB_LOG( logger, Logger::DEBUG) << \"   Connection #\" << i << \" to \" << connection_list[ i ]->Name << \", k=\" << connection_k[ i ] << \", window=\" << connection_window[ i ] << endl;\n\t}\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Compute one flux from this to another box\n * \\param[in] i     connection number\n * \\param[in] yf    year fraction (0-1)\n * \\returns         flux in Pg C, accounting for yf, connection strength\n */\nunitval oceanbox::compute_connection_flux( int i, double yf ) const {\n    // Compute the mean_carbon over connection-specific history window\n    double mean_carbon = carbon.value( U_PGC );\n    if( connection_window[ i ] )\n        mean_carbon = vectorHistoryMean( carbonHistory, connection_window[ i ] );\n    \n    unitval closs( mean_carbon * connection_k[ i ] * yf, U_PGC );\n    return closs;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Compute all fluxes between boxes\n * \\param[in] Ca                atmospheric CO2\n * \\param[in] yf                year fraction (0-1)\n * \\param[in] do_circ           flag: do circulation, or not?\n */\nvoid oceanbox::compute_fluxes( const unitval current_Ca, const double yf, const bool do_circ ) {\n    \n    Ca = current_Ca;\n    \n\t// Step 1 : run chemistry mode, if applicable\n\tif( active_chemistry ) {\n\t\tOB_LOG( logger, Logger::DEBUG) << Name << \" running ocean_csys\" << endl;\n        H_ASSERT( Tbox.value( U_DEGC ) > -999, \"bad tbox value\" );        // TODO: this isn't a good temperature check\n\t\tmychemistry.ocean_csys_run( Tbox, carbon );\n        \n        atmosphere_flux = unitval( mychemistry.calc_annual_surface_flux( Ca ).value( U_PGC_YR ), U_PGC );\n        \n\t} else  {\n\t\t// No active chemistry, so atmosphere-box flux is simply a function of the\n\t\t// difference between box carbon and atmospheric carbon s.t. it is preindustrial_flux\n\t\tif( surfacebox )\n            atmosphere_flux = unitval( preindustrial_flux.value( U_PGC_YR ), U_PGC );\n        else\n            atmosphere_flux = unitval( 0.0, U_PGC );\n\t}\n\n    // Step 2 : account for partial year\n    atmosphere_flux = atmosphere_flux * yf;\n\n    // Step 3: check if this box is oscillating\n    /*\n    const bool osc = oscillating( 10, // over the last 10 states,\n                                   1,   // has box C varied by >1%\n                                   3 ); // while changing direction 3+ times?\n    */\n    \n\t// Step 4 : calculate the carbon transports between the boxes\n    if( do_circ ) {\n        double unstable_box_flux_adjust = 1.0;\n        \n        // 'Preflight' the outbound fluxes, i.e. get estimate of their total\n        unitval closs_total( 0.0, U_PGC );\n        for( unsigned i=0; i < connection_window.size(); i++ ){\n            closs_total = closs_total + compute_connection_flux( i, yf );\n        } // for i\n\n        if( 0 /* osc */ ) {\n            const double mean_past_loss = vectorHistoryMean( carbonLossHistory, 10 );\n            unstable_box_flux_adjust = mean_past_loss / closs_total.value( U_PGC );\n            \n            OB_LOG( logger, Logger::DEBUG) << Name << \"is oscillating.\" << std::endl;\n            std::cout << \"Preflighted connection fluxes = \" << closs_total << std::endl;\n            std::cout << \"Recent mean loss = \" << mean_past_loss << std::endl;\n            std::cout << \"unstable_box_flux_adjust = \" << unstable_box_flux_adjust << std::endl;\n            // The box's C is oscillating\n        }\n                \n        closs_total.set( 0.0, U_PGC );\n        for( unsigned i=0; i < connection_window.size(); i++ ){\n\n            unitval closs = compute_connection_flux( i, yf ) * unstable_box_flux_adjust;\n\n            OB_LOG( logger, Logger::DEBUG) << Name << \" conn \" << i << \" flux= \" << closs << endl;\n                 \n            connection_list[ i ]->add_carbon( closs );\n            CarbonToAdd = CarbonToAdd - closs;  // PgC\n            closs_total = closs_total + closs;\n           annual_box_fluxes[ connection_list[ i ] ] = annual_box_fluxes[ connection_list[ i ] ] +\n                unitval( closs.value( U_PGC ), U_PGC_YR );\n        } // for i\n        \n        carbonLossHistory.insert( carbonLossHistory.begin (), closs_total.value( U_PGC ) );\n        \n    } // if do_circulation\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief    Function to calculate Revelle Factor\n*/\n\n// 2 ways of solving for the Revelle factor\n// keep track of last year pCO2 in the ocean and DIC\nunitval oceanbox::calc_revelle() {\n    H_ASSERT( active_chemistry, \"Active Chemistry required\");\n        \n//    unitval deltapco2 = Ca - pco2_lastyear;\n    unitval deltadic = mychemistry.convertToDIC(carbon) - dic_lastyear;\n    \n    H_ASSERT( deltadic.value( U_UMOL_KG) != 0, \"DeltaDIC can not be zero\");\n    \n    // Revelle Factor can be calculated multiple ways.  \n    // Based on changing atmospheric conditions as well approximated via DIC and CO3\n     return unitval ( mychemistry.convertToDIC( carbon ) / mychemistry.CO3, U_UNITLESS ); \n    // under high CO2, the HL box numbers are potentially unrealistic. \n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Update to a new carbon state\n */\nvoid oceanbox::update_state() {\n    \n\tcarbonHistory.insert( carbonHistory.begin (), carbon.value( U_PGC ) );\n\t\n\tcarbon = carbon + CarbonToAdd + atmosphere_flux;\n    \n\tH_ASSERT( carbon.value( U_PGC ) >= 0.0, \"box carbon is negative\" );\n\tCarbonToAdd.set( 0.0, U_PGC );\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief          A new year is starting. Zero flux variables.\n *  \\param[in] t    Mean global temperature this year\n */\nvoid oceanbox::new_year( const unitval Tgav ) {\n    \n    for( unsigned i=0; i < connection_window.size(); i++ ){\n        annual_box_fluxes[ connection_list[ i ] ] = unitval( 0.0, U_PGC_YR );\n    }\n    atmosphere_flux.set( 0.0, U_PGC );\n    Tbox = compute_tabsC( Tgav );\n\n    // save for Revelle Calc\n    pco2_lastyear = Ca;\n    dic_lastyear = mychemistry.convertToDIC( carbon );\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief              Function that chem_equilibrate tries to minimize\n *  \\param[in] alk      alkalinity value to try\n *  \\param[in] *params  pointer to other parameters (just f_target currently)\n *  \\returns            double, difference between flux and target flux\n *\n *  The gsl minimization algorithm calls this function, which slots alk\n *  into the csys chemistry input, runs csys, and reports back the difference\n *  between csys's computed ocean-atmosphere flux and the target flux.\n */\ndouble oceanbox::fmin( double alk, void *params ) {\n    \n\t// Call the chemistry model with new value for alk\n\tmychemistry.set_alk( alk );\n\tmychemistry.ocean_csys_run( Tbox, carbon );\n    \n\tdouble f_target = *( double * )params;\n\tdouble diff = fabs( mychemistry.calc_annual_surface_flux( Ca ).value( U_PGC_YR ) - f_target );\n\t//    OB_LOG( logger, Logger::DEBUG) << \"fmin at \" << alk << \", f_target=\" << f_target << \", returning \" << diff << endl;\n    \n\treturn diff;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Functor wrapper for minimization function\n */\nstruct FMinWrapper {\n    FMinWrapper(oceanbox* instance, const double f_targetIn):\n        object_which_will_handle_signal(instance),\n        f_target(f_targetIn)\n    {\n    }\n    double operator()(const double alk) {\n        return object_which_will_handle_signal->fmin(alk, &f_target);\n    }\n\n    private:\n    oceanbox* object_which_will_handle_signal;\n    double f_target;\n};\n\n//------------------------------------------------------------------------------\n/*! \\brief                  Equilibrate the chemistry model to a given flux\n *  \\param[in] Ca           Atmospheric CO2 (ppmv)\n *\n *  \\details The global carbon cycle can be spun up with ocean chemistry either\n *  on or off. In the former case, the ocean continually equilibrates with the\n *  atmosphere during spinup, and the entire system should come to steady state.\n *  In the latter case, the ocean is sealed off from the atmosphere during\n *  spinup, with no surface chemistry; this presumes we know exactly how much\n *  carbon should be in the preindustrial ocean. Before chemistry is re-enabled\n *  for the main run, however, we need to adjust ocean conditions (alkalinity)\n *  such that the chemistry model will produce the specified spinup-condition\n *  fluxes. That's what this method does. Note that we pass in current CO2 because\n *  in case the model was NOT spun up, need to set the box's internal tracking var.\n */\nvoid oceanbox::chem_equilibrate( const unitval current_Ca ) {\n    \n\tusing namespace std;\n    \n    Ca = current_Ca;\n    \n\tH_ASSERT( active_chemistry, \"chemistry not turned on\" );\n\tOB_LOG( logger, Logger::DEBUG) << \"Equilibrating chemistry for box \" << Name << endl;\n    \n\t// Initialize the box chemistry values: temperature, atmospheric CO2, DIC\n//\tmychemistry.ocean_csys_run( Tbox, carbon );\n    \n    unitval dic = mychemistry.convertToDIC( carbon );\n\tOB_LOG( logger, Logger::DEBUG) << \"Ca=\" << Ca << \", DIC=\" << dic <<  endl;\n    \n\t// Tune the chemistry model's alkalinity parameter to produce a particular flux.\n\t// This happens after the box model has been spun up with chemistry turned off, before the chemistry\n\t// model is turned on (because we don't want it to suddenly produce a larger ocean-atmosphere flux).\n    \n\t// Here we use the Brent algorithm\n\t//      http://www.gnu.org/software/gsl/manual/html_node/Minimization-Algorithms.html\n\t// to minimize abs(f-f0), where f is computed by the csys chemistry code and f0 passed in\n    \n\tdouble alk_min = 2100e-6, alk_max = 2750e-6;\n\tdouble f_target = preindustrial_flux.value( U_PGC_YR );\n    \n\t// Find a best-guess point; the GSL algorithm seems to need it\n\tOB_LOG( logger, Logger::DEBUG) << \"Looking for best-guess alkalinity\" << endl;\n\tconst int w = 12;\n\tOB_LOG( logger, Logger::DEBUG) << setw( w ) << \"Alk\" << setw( w ) << \"FPgC\"\n        << setw( w ) << \"f_target\" << setw( w ) << \"diff\" << endl;\n\tdouble min_diff = 1e6;\n\tdouble min_point = ( alk_min + alk_max ) / 2.0;\n\tfor( double alk1=alk_min; alk1 <= alk_max; alk1 += (alk_max-alk_min)/20 ) {\n\t\tdouble diff = fmin( alk1, &f_target );\n\t\tif( diff < min_diff ) {\n\t\t\tmin_diff = diff;\n\t\t\tmin_point = alk1;\n\t\t}\n\t\tOB_LOG( logger, Logger::DEBUG) << setw( w ) << alk1 << setw( w ) << atmosphere_flux\n        << setw( w ) << f_target << setw( w ) << diff << endl;\n\t}\n\tdouble alk = min_point;        // this is our best guess\n\tOB_LOG( logger, Logger::DEBUG) << \"Best guess minimum is at \" << alk << endl;\n    \n    FMinWrapper fFunctor(this, f_target);\n    // arbitrarily solve unil 60% of the digits are correct.\n    const int digits = numeric_limits<double>::digits;\n    int get_digits = static_cast<int>(digits * 0.6);\n    std::pair<double, double> r = boost::math::tools::brent_find_minima(fFunctor, alk_min, alk_max, get_digits);\n\tOB_LOG( logger, Logger::DEBUG) << setw( w ) << \"Alk\" << setw( w ) << \"FPgC\"\n        << setw( w ) << \"f_target\" << setw( w ) << \"diff\" << endl;\n    OB_LOG( logger, Logger::DEBUG) << setw( w ) << r.first << setw( w ) << atmosphere_flux\n        << setw( w ) << f_target << setw( w ) << r.second << endl;\n}\n\n}\n", "meta": {"hexsha": "23665cfba0ebb6950fb632ddaa83ef70c194bcbe", "size": 19810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/oceanbox.cpp", "max_stars_repo_name": "bvegawe/hector", "max_stars_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/oceanbox.cpp", "max_issues_repo_name": "bvegawe/hector", "max_issues_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/oceanbox.cpp", "max_forks_repo_name": "bvegawe/hector", "max_forks_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_forks_repo_licenses": ["ECL-2.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.059447983, "max_line_length": 185, "alphanum_fraction": 0.5884906613, "num_tokens": 4963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.08632347717391049, "lm_q1q2_score": 0.037794446831986434}}
{"text": "//    Copyright 2020 Jij Inc.\n\n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n\n//        http://www.apache.org/licenses/LICENSE-2.0\n\n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n\n/**\n * @mainpage cimod\n * \n * @section s_overview Overview\n * cimod is a C++ library for a binary quadratic model.\n * This library provides a binary quadratic model class which contains an Ising model or a quadratic unconstrained binary optimization (QUBO) model.\n * It also provides utilities for constructing a model and transforming to some other interfaces.\n * This library is created based on dimod (https://github.com/dwavesystems/dimod).\n * \n * @section s_bqm Binary quadratic model\n * A binary quadratic model class can contain an Ising model or a QUBO model.\n * \n * @subsection ss_ising Ising model\n * An energy of an Ising model \\f$E_{\\mathrm{Ising}}\\f$ is represented by\n * \\f[\n * E_{\\mathrm{Ising}} = \\sum_{i} h_i s_i + \\sum_{i \\neq j} J_{ij} s_i s_j + \\delta_{\\mathrm{Ising}},\n * \\f]\n * where \\f$s_i \\in \\{+1, -1\\}\\f$ denotes a spin at the site \\f$i\\f$, \\f$h_i\\f$ denotes an external magnetic field parameter, \\f$J_{ij}\\f$ denotes an interaction parameter and \\f$\\delta_{\\mathrm{Ising}}\\f$ denotes an offset.\n * Note that this library assumes that the interaction is not symmetric, i.e., \\f$J_{ij} \\neq J_{ji}\\f$.\n * \n * @subsection ss_qubo QUBO model\n * An evaluation function of a QUBO model \\f$E_{\\mathrm{QUBO}}\\f$ is represented by\n * \\f[\n * E_{\\mathrm{QUBO}} = \\sum_{i, j} Q_{ij} x_i x_j + \\delta_{\\mathrm{QUBO}},\n * \\f]\n * where \\f$x_i \\in \\{0, 1\\}\\f$ denotes a decision variable, \\f$Q_{ij}\\f$ denotes a quadratic bias and \\f$\\delta_{\\mathrm{QUBO}}\\f$ denotes an offset.\n * Note that this library assumes that the quadratic bias is not symmetric, i.e., \\f$Q_{ij} \\neq Q_{ji}\\f$ if \\f$i \\neq j\\f$.\n * \n * @section s_example Example\n * @code\n * #include \"src/binary_quadratic_model.hpp\"\n * \n * using namespace cimod;\n * int main()\n * {\n * // Set linear biases and quadratic biases\n * Linear<uint32_t, double> linear{ {1, 1.0}, {2, 2.0}, {3, 3.0}, {4, 4.0} };\n * Quadratic<uint32_t, double> quadratic\n * {\n *      {std::make_pair(1, 2), 12.0}, {std::make_pair(1, 3), 13.0}, {std::make_pair(1, 4), 14.0},\n *      {std::make_pair(2, 3), 23.0}, {std::make_pair(2, 4), 24.0},\n *      {std::make_pair(3, 4), 34.0}\n *  };\n * \n * // Set offset\n * double offset = 0.0;\n * \n * // Set variable type\n * Vartype vartype = Vartype::BINARY;\n * // Create a BinaryQuadraticModel instance\n * BinaryQuadraticModel<uint32_t, double> bqm(linear, quadratic, offset, vartype);\n * \n * // Print informations of bqm\n * bqm.print();\n * \n * return 0;\n * }\n * @endcode\n */\n\n/**\n * @file binary_quadratic_model.hpp\n * @author Fumiya Watanabe\n * @brief BinaryQuadraticModel class\n * @version 1.0.0\n * @date 2020-03-24\n * \n * @copyright Copyright (c) Jij Inc. 2020\n * \n */\n\n#ifndef BINARY_QUADRATIC_MODEL_HPP__\n#define BINARY_QUADRATIC_MODEL_HPP__\n\n#include \"vartypes.hpp\"\n#include \"hash.hpp\"\n#include \"utilities.hpp\"\n#include \"json.hpp\"\n\n#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <typeinfo>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n#include <functional>\n#include <Eigen/Dense>\n\nnamespace cimod\n{\n/**\n * @brief Type alias for linear bias\n * \n * @tparam IndexType \n */\ntemplate <typename IndexType, typename FloatType>\nusing Linear = std::unordered_map<IndexType, FloatType>;\n\n/**\n * @brief Type alias for quadratic bias\n * \n * @tparam IndexType \n */\ntemplate <typename IndexType, typename FloatType>\nusing Quadratic = std::unordered_map<std::pair<IndexType, IndexType>, FloatType, pair_hash>;\n\n/**\n * @brief Type alias for adjacency list\n * \n * @tparam IndexType \n */\ntemplate <typename IndexType, typename FloatType>\nusing Adjacency = std::unordered_map<IndexType, std::unordered_map<IndexType, FloatType>>;\n\n/**\n * @brief Type alias for sample\n * \n * @tparam IndexType \n */\ntemplate <typename IndexType>\nusing Sample = std::unordered_map<IndexType, int32_t>;\n\n\n/**\n * @brief Class for binary quadratic model.\n */\n\ntemplate <typename IndexType, typename FloatType>\nclass BinaryQuadraticModel\n{\npublic:\n/**\n * @brief Eigen Matrix\n */\nusing Matrix = Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\nprotected:\n    /**\n     * @brief Linear biases as a dictionary.\n     * \n     */\n    Linear<IndexType, FloatType> m_linear;\n\n    /**\n     * @brief Quadratic biases as a dictionary.\n     * \n     */\n    Quadratic<IndexType, FloatType> m_quadratic;\n\n    /**\n     * @brief The energy offset associated with the model.\n     * \n     */\n    FloatType m_offset;\n\n    /**\n     * @brief The model's type.\n     * \n     */\n    Vartype m_vartype = Vartype::NONE;\n\n    /**\n     * @brief A place to store miscellaneous data about the binary quadratic model as a whole.\n     * \n     */\n    std::string m_info;\n\n    /**\n     * @brief The model's interactions as nested dictionaries.\n     * \n     */\n    Adjacency<IndexType, FloatType> m_adj;\n\n    /**\n     * @brief Add the adjacency to the adjacency list\n     * \n     */\n    void update_adjacency\n    (\n        const IndexType &u,\n        const IndexType &v\n    )\n    {\n        std::pair<IndexType, IndexType> p = std::make_pair(u, v);\n        if(m_quadratic.count(p)!=0)\n        {\n            insert_or_assign(m_adj[u], v, m_quadratic[p]);\n        }\n    }\n\n    /**\n     * @brief Remove adjacency from the adjacency list\n     * \n     * @param u \n     * @param v \n     */\n    void remove_adjacency\n    (\n        const IndexType &u,\n        const IndexType &v\n    )\n    {\n        auto k = m_adj[u].erase(v);\n    };\n\npublic:\n    /**\n     * @brief BinaryQuadraticModel constructor.\n     * \n     * @param linear\n     * @param quadratic\n     * @param offset\n     * @param vartype\n     * @param info\n     */\n    BinaryQuadraticModel\n    (\n        const Linear<IndexType, FloatType> &linear,\n        const Quadratic<IndexType, FloatType> &quadratic,\n        const FloatType &offset,\n        const Vartype vartype,\n        const std::string info = \"\"\n    ):\n        m_offset(offset),\n        m_vartype(vartype),\n        m_info(info)\n    {\n        add_variables_from(linear);\n        add_interactions_from(quadratic);\n    };\n\n    /**\n     * @brief Copy constructor of BinaryQuadraticModel\n     * \n     * @param bqm \n     */\n    //BinaryQuadraticModel\n    //(\n    //    const BinaryQuadraticModel &bqm\n    //)\n    //{\n    //    m_offset = bqm.get_offset();\n    //    m_vartype = bqm.get_vartype();\n    //    m_info = bqm.get_info();\n    //    add_variables_from(bqm.get_linear());\n    //    add_interactions_from(bqm.get_quadratic());\n    //};\n\n    BinaryQuadraticModel(const BinaryQuadraticModel&) = default;\n    BinaryQuadraticModel(BinaryQuadraticModel&&) = default;\n\n    /**\n     * @brief generate indices\n     *\n     * @return generated indices\n     */\n    std::vector<IndexType> _generate_indices() const{\n        std::unordered_set<IndexType> index_set;\n        for(auto elem : m_linear){\n            index_set.insert(elem.first);\n        }\n\n        for(auto elem : m_quadratic){\n            index_set.insert(elem.first.first);\n            index_set.insert(elem.first.second);\n        }\n\n        auto ret = std::vector<IndexType>(index_set.begin(), index_set.end());\n        std::sort(ret.begin(), ret.end());\n        return ret;\n    }\n\n    /**\n     * @brief Return the number of variables.\n     * \n     * @return The number of variables.\n     */\n    size_t length() const\n    {\n        return m_linear.size();\n    };\n\n    /**\n     * @brief Return true if the variable contains v.\n     * \n     * @return Return true if the variable contains v.\n     * @param v\n     */\n    bool contains\n    (\n        const IndexType &v\n    )\n    {\n        if(m_linear.count(v)!=0)\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n        \n    };\n    \n    /**\n     * @brief Get the linear object\n     * \n     * @return A linear bias.\n     */\n    const Linear<IndexType, FloatType>& get_linear() const\n    {\n        return this->m_linear;\n    };\n\n    /**\n     * @brief Get the quadratic object\n     * \n     * @return A quadratic bias.\n     */\n    const Quadratic<IndexType, FloatType>& get_quadratic() const\n    {\n        return this->m_quadratic;\n    };\n\n    /**\n     * @brief Get the adjacency object\n     * \n     * @return A adjacency list.\n     */\n    const Adjacency<IndexType, FloatType>& get_adjacency() const\n    {\n        return this->m_adj;\n    };\n\n    /**\n     * @brief Get the offset\n     * \n     * @return An offset.\n     */\n    const FloatType& get_offset() const\n    {\n        return this->m_offset;\n    }\n\n    /**\n     * @brief Get the vartype object\n     * \n     * @return Type of the model.\n     */\n    const Vartype& get_vartype() const\n    {\n        return this->m_vartype;\n    }\n\n    /**\n     * @brief Get the info object\n     * \n     * @return Information.\n     */\n    const std::string& get_info() const\n    {\n        return this->m_info;\n    }\n\n    /**\n     * @brief Print informations of BinaryQuadraticModel\n     * \n     */\n    //void print()\n    //{\n    //    std::cout << \"[BinaryQuadraticModel]\" << std::endl;\n\n    //    // Print linear\n    //    std::cout << \"linear = \" << std::endl;\n    //    for(auto &it : m_linear)\n    //    {\n    //        std::cout << \"\" << it.first << \": \" << it.second << std::endl;\n    //    }\n\n    //    // Print quadratic\n    //    std::cout << \"quadratic = \" << std::endl;\n    //    for(auto &it : m_quadratic)\n    //    {\n    //        std::cout << \"(\" << it.first.first << \", \" << it.first.second << \"): \" << it.second << \", \";\n    //    }\n    //    std::cout << std::endl;\n\n    //    // Print adjacency\n    //    std::cout << \"adjacency = \" << std::endl;\n    //    for(auto &it_src : m_linear)\n    //    {\n    //        std::cout << it_src.first << \": {\";\n    //        for(auto &it_dst : m_adj[it_src.first])\n    //        {\n    //            std::cout << \"(\" << it_src.first << \", \" << it_dst.first << \"): \" << it_dst.second << \", \";\n    //        }\n    //        std::cout << \"}\" << std::endl;\n    //    }\n\n    //    // Print vartype\n    //    std::cout << \"vartype = \";\n    //    if(m_vartype == Vartype::SPIN)\n    //    {\n    //        std::cout << \"Spin\" << std::endl;\n    //    }\n    //    else if(m_vartype == Vartype::BINARY)\n    //    {\n    //        std::cout << \"Binary\" << std::endl;\n    //    }\n\n    //    // Print info\n    //    std::cout << \"info = \";\n    //    std::cout << \"\\\"\" << m_info << \"\\\"\" << std::endl;\n    //}\n\n    /**\n     * @brief Create an empty BinaryQuadraticModel\n     * \n     */\n    void empty()\n    {\n        m_linear = {};\n        m_quadratic = {};\n        m_offset = 0.0;\n        m_vartype = Vartype::NONE;\n        m_info = \"\";\n    }\n\n    /* Update methods */\n\n    /**\n     * @brief Add variable v and/or its bias to a binary quadratic model.\n     * \n     * @param v\n     * @param bias\n     * @param vartype\n     */\n    void add_variable\n    (\n        const IndexType &v,\n        const FloatType &bias,\n        const Vartype vartype = Vartype::NONE\n    )\n    {\n        FloatType b = bias;\n\n        // handle the case that a different vartype is provided\n        if((vartype!=Vartype::NONE)&&(vartype!=m_vartype))\n        {\n            if((m_vartype == Vartype::SPIN)&&(vartype == Vartype::BINARY))\n            {\n                b /= 2;\n                m_offset += b;\n            }\n            else if((m_vartype == Vartype::BINARY)&&(vartype == Vartype::SPIN))\n            {\n                m_offset -= b;\n                b *= 2;\n            }\n            else\n            {\n                std::cerr << \"Unknown vartype\" << std::endl;\n            }\n        }\n\n        // Insert or assign the bias\n        FloatType value = 0;\n        if(m_linear.count(v) != 0)\n        {\n            value = m_linear[v];\n        }\n        insert_or_assign(m_linear, v, value + b);\n    };\n\n    /**\n     * @brief Add variables and/or linear biases to a binary quadratic model.\n     * \n     * @param linear\n     * @param vartype\n     */\n    void add_variables_from\n    (\n        const Linear<IndexType, FloatType> &linear,\n        const Vartype vartype = Vartype::NONE\n    )\n    {\n        for(auto &it : linear)\n        {\n            add_variable(it.first, it.second, vartype);\n        }\n    };\n\n    /**\n     * @brief Add an interaction and/or quadratic bias to a binary quadratic model.\n     * \n     * @param u\n     * @param v\n     * @param bias\n     * @param vartype\n     */\n    void add_interaction\n    (\n        const IndexType &u,\n        const IndexType &v,\n        const FloatType &bias,\n        const Vartype vartype = Vartype::NONE\n    )\n    {\n        if(u == v)\n        {\n            std::cerr << \"No self-loops allowed\" << std::endl;\n        }\n        else\n        {\n            FloatType b = bias;\n            if((vartype!=Vartype::NONE)&&(vartype!=m_vartype))\n            {\n                if((m_vartype == Vartype::SPIN)&&(vartype == Vartype::BINARY))\n                {\n                    //convert from binary to spin\n                    b /= 4;\n                    add_offset(b);\n                    add_variable(u, b);\n                    add_variable(v, b);\n                }\n                else if((m_vartype == Vartype::BINARY)&&(vartype == Vartype::SPIN))\n                {\n                    //convert from spin to binary\n                    add_offset(b);\n                    add_variable(u, -2 * b);\n                    add_variable(v, -2 * b);\n                    b *= 4;\n                }\n                else\n                {\n                    std::cerr << \"Unknown vartype\" << std::endl;\n                }\n            }\n            else\n            {\n                if(m_linear.count(u) == 0)\n                {\n                    add_variable(u, 0);\n                }\n                if(m_linear.count(v) == 0)\n                {\n                    add_variable(v, 0);\n                }\n            }\n            \n            FloatType value = 0;\n            std::pair<IndexType, IndexType> p1 = std::make_pair(u, v);\n            if(m_quadratic.count(p1) != 0)\n            {\n                value = m_quadratic[p1];\n            }\n            insert_or_assign(m_quadratic, p1, value + b);\n            update_adjacency(u, v);\n        }\n    };\n\n    /**\n     * @brief Add interactions and/or quadratic biases to a binary quadratic model.\n     * \n     * @param quadratic\n     * @param vartype\n     */\n    void add_interactions_from\n    (\n        const Quadratic<IndexType, FloatType> &quadratic,\n        const Vartype vartype = Vartype::NONE\n    )\n    {\n        for(auto &it : quadratic)\n        {\n            add_interaction(it.first.first, it.first.second, it.second, vartype);\n        }\n    }\n\n    \n\n    /**\n     * @brief Remove variable v and all its interactions from a binary quadratic model.\n     * \n     * @param v\n     */\n    void remove_variable\n    (\n        const IndexType &v\n    )\n    {\n        std::vector<std::pair<IndexType, IndexType>> interactions;\n        for(auto &it : m_quadratic)\n        {\n            if(it.first.first == v || it.first.second == v)\n            {\n                interactions.push_back(it.first);\n            }         \n        }\n        remove_interactions_from(interactions);\n        m_linear.erase(v);\n        m_adj.erase(v);\n    }\n\n    /**\n     * @brief Remove specified variables and all of their interactions from a binary quadratic model.\n     * \n     * @param variables\n     */\n    void remove_variables_from\n    (\n        const std::vector<IndexType> &variables\n    )\n    {\n        for(auto &it : variables)\n        {\n            remove_variable(it);\n        }\n    };\n\n    /**\n     * @brief Remove interaction of variables u, v from a binary quadratic model.\n     * \n     * @param u\n     * @param v\n     */\n    void remove_interaction\n    (\n        const IndexType &u,\n        const IndexType &v      \n    )\n    {\n        auto p = std::make_pair(u, v);\n        if(m_quadratic.count(p)!=0)\n        {\n            auto k = m_quadratic.erase(p);\n            remove_adjacency(u, v);\n        }\n    };\n\n    /**\n     * @brief Remove all specified interactions from the binary quadratic model.\n     * \n     * @param interactions\n     */\n    void remove_interactions_from\n    (\n        const std::vector<std::pair<IndexType, IndexType>> &interactions\n    )\n    {\n        for(auto &it : interactions)\n        {\n            remove_interaction(it.first, it.second);\n        }\n    };\n\n    /**\n     * @brief Add specified value to the offset of a binary quadratic model.\n     * \n     * @param offset\n     */\n    void add_offset\n    (\n        const FloatType &offset\n    )\n    {\n        m_offset += offset;\n    };\n\n    /**\n     * @brief Set the binary quadratic model's offset to zero.\n     */\n    void remove_offset()\n    {\n        add_offset(-m_offset);\n    };\n\n    /**\n     * @brief Multiply by the specified scalar all the biases and offset of a binary quadratic model.\n     * \n     * @param scalar\n     * @param ignored_variables\n     * @param ignored_interactions\n     * @param ignored_offset\n     */\n    void scale\n    (\n        const FloatType &scalar,\n        const std::vector<IndexType> &ignored_variables = {},\n        const std::vector<std::pair<IndexType, IndexType>> &ignored_interactions = {},\n        const bool ignored_offset = false\n    )\n    {\n        // scaling linear\n        for(auto &it : m_linear)\n        {\n            if(std::find(ignored_variables.begin(), ignored_variables.end(), it.first) != ignored_variables.end() || ignored_variables.empty())\n            {\n                it.second *= scalar;\n            }\n        }\n\n        // scaling quadratic\n        for(auto &it : m_quadratic)\n        {\n            if(std::find(ignored_interactions.begin(), ignored_interactions.end(), it.first) != ignored_interactions.end() || ignored_variables.empty())\n            {\n                it.second *= scalar;\n            }\n        }\n\n        // scaling offset\n        if(!ignored_offset)\n        {\n            m_offset *= scalar;\n        }\n    };\n\n    /**\n     * @brief Normalizes the biases of the binary quadratic model such that they fall in the provided range(s), and adjusts the offset appropriately.\n     * \n     * @param bias_range\n     * @param use_quadratic_range\n     * @param quadratic_range\n     * @param ignored_variables\n     * @param ignored_interactions\n     * @param ignored_offset\n     * \n     */\n    void normalize\n    (\n        const std::pair<FloatType, FloatType> &bias_range = {1.0, 1.0},\n        const bool use_quadratic_range = false,\n        const std::pair<FloatType, FloatType> &quadratic_range = {1.0, 1.0},\n        const std::vector<IndexType> &ignored_variables = {},\n        const std::vector<std::pair<IndexType, IndexType>> &ignored_interactions = {},\n        const bool ignored_offset = false\n    )\n    {\n        // parse range\n        std::pair<FloatType, FloatType> l_range = bias_range;\n        std::pair<FloatType, FloatType> q_range;\n        if(!use_quadratic_range)\n        {\n            q_range = bias_range;\n        }\n        else\n        {\n            q_range = quadratic_range;\n        }\n\n        // calculate scaling value\n        auto comp = [](const auto &a, const auto &b) { return a.second < b.second; };\n        auto it_lin_min = std::min_element(m_linear.begin(), m_linear.end(), comp);\n        auto it_lin_max = std::max_element(m_linear.begin(), m_linear.end(), comp);\n        auto it_quad_min = std::min_element(m_quadratic.begin(), m_quadratic.end(), comp);\n        auto it_quad_max = std::max_element(m_quadratic.begin(), m_quadratic.end(), comp);\n\n        std::vector<FloatType> v_scale =\n        {\n            it_lin_min->second / l_range.first,\n            it_lin_max->second / l_range.second,\n            it_quad_min->second / q_range.first,\n            it_quad_max->second / q_range.second\n        };\n        FloatType inv_scale = *std::max_element(v_scale.begin(), v_scale.end());\n\n        // scaling\n        if(inv_scale != 0.0)\n        {\n            scale(1.0 / inv_scale, ignored_variables, ignored_interactions, ignored_offset);\n        }\n    };\n\n    /**\n     * @brief Fix the value of a variable and remove it from a binary quadratic model.\n     * \n     * @param v\n     * @param value\n     */\n    void fix_variable\n    (\n        const IndexType &v,\n        const int32_t &value\n    )\n    {\n        std::vector<std::pair<IndexType, IndexType>> interactions;\n        for(auto &it : m_quadratic)\n        {\n            if(it.first.first == v)\n            {\n                add_variable(it.first.second, value*it.second);\n                interactions.push_back(it.first);\n            }\n            else if(it.first.second == v)\n            {\n                add_variable(it.first.first, value*it.second);\n                interactions.push_back(it.first);\n            }\n        }\n        remove_interactions_from(interactions);\n        add_offset(m_linear[v]*value);\n        remove_variable(v);\n    };\n\n    /**\n     * @brief Fix the value of the variables and remove it from a binary quadratic model.\n     * \n     * @param fixed\n     */\n    void fix_variables\n    (\n        const std::vector<std::pair<IndexType, int32_t>> &fixed\n    )\n    {\n        for(auto &it : fixed)\n        {\n            fix_variable(it.first, it.second);\n        }\n    };\n\n    /**\n     * @brief Flip variable v in a binary quadratic model.\n     * \n     * @param v\n     */\n    void flip_variable\n    (\n        const IndexType &v\n    )\n    {\n        // check variable\n        if(m_linear.count(v)==0)\n        {\n           std::cerr << \"not a variable in the binary quadratic model.\" << std::endl;\n           return;\n        }\n\n        if(m_vartype == Vartype::SPIN)\n        {\n            m_linear[v] *= -1.0;\n            for(auto &it : m_quadratic)\n            {\n                if(it.first.first == v || it.first.second == v)\n                {\n                    it.second *= -1.0;\n                    update_adjacency(it.first.first, it.first.second);\n                }\n            }\n        }\n        else if(m_vartype == Vartype::BINARY)\n        {\n            add_offset(m_linear[v]);\n            m_linear[v] *= -1.0;\n\n            for(auto &it : m_quadratic)\n            {\n                if(it.first.first == v)\n                {\n                    m_linear[it.first.second] += it.second;\n                    it.second *= -1.0;\n                    update_adjacency(it.first.first, it.first.second);\n                }\n                else if(it.first.second == v)\n                {\n                    m_linear[it.first.first] += it.second;\n                    it.second *= -1.0;\n                    update_adjacency(it.first.first, it.first.second);\n                }\n            }\n        }\n    };\n\n    void update\n    (\n        const BinaryQuadraticModel &bqm,\n        const bool ignore_info = true\n    )\n    {\n        add_variables_from(bqm.get_linear(), bqm.get_vartype());\n        add_interactions_from(bqm.get_quadratic(), bqm.get_vartype());\n        add_offset(bqm.get_offset());\n        if(!ignore_info)\n        {\n            m_info = bqm.get_info();\n        }\n    };\n\n    /**\n     * @brief Enforce u, v being the same variable in a binary quadratic model.\n     * \n     * @param u\n     * @param v\n     */\n    void contract_variables\n    (\n        const IndexType &u,\n        const IndexType &v\n    )\n    {\n        // check variable\n        if(m_linear.count(v)==0)\n        {\n            std::cerr << \"not a variable in the binary quadratic model.\" << std::endl;\n            return;\n        }\n        if(m_linear.count(u)==0)\n        {\n            std::cerr << \"not a variable in the binary quadratic model.\" << std::endl;\n            return;\n        }\n\n        auto p1 = std::make_pair(u, v);\n        auto p2 = std::make_pair(v, u);\n        if(m_quadratic.count(p1) != 0)\n        {\n            if(m_vartype == Vartype::BINARY)\n            {\n                add_variable(u, m_quadratic[p1]);\n            }\n            else if(m_vartype == Vartype::SPIN)\n            {\n                add_offset(m_quadratic[p1]);\n            }\n            remove_interaction(u, v);\n        }\n        if(m_quadratic.count(p2) != 0)\n        {\n            if(m_vartype == Vartype::BINARY)\n            {\n                add_variable(u, m_quadratic[p2]);\n            }\n            else if(m_vartype == Vartype::SPIN)\n            {\n                add_offset(m_quadratic[p2]);\n            }\n            remove_interaction(v, u);\n        }\n\n        std::vector<std::pair<IndexType, IndexType>> interactions;\n        for(auto &it : m_quadratic)\n        {\n            if(it.first.first == v)\n            {\n                add_interaction(u, it.first.second, it.second);\n                update_adjacency(u, it.first.second);\n                interactions.push_back(it.first);\n            }\n            else if(it.first.second == v)\n            {\n                add_interaction(it.first.first, u, it.second);\n                update_adjacency(it.first.first, u);\n                interactions.push_back(it.first);\n            }\n        }\n        remove_interactions_from(interactions);\n\n        add_variable(u, m_linear[v]);\n        remove_variable(v);\n    };\n\n    /* Transformations */\n\n    /**\n     * @brief Create a binary quadratic model with the specified vartype.\n     * \n     * @param vartype\n     * @param inplace\n     * @return A new instance of the BinaryQuadraticModel class.\n     */\n    BinaryQuadraticModel change_vartype\n    (\n        const Vartype &vartype,\n        bool inplace=true\n    )\n    {\n        Linear<IndexType, FloatType> linear;\n        Quadratic<IndexType, FloatType> quadratic;\n        FloatType offset = 0.0;\n\n        if(m_vartype == Vartype::BINARY && vartype == Vartype::SPIN) // binary -> spin\n        {\n            std::tie(linear, quadratic, offset) = binary_to_spin(m_linear, m_quadratic, m_offset);                \n        }\n        else if(m_vartype == Vartype::SPIN && vartype == Vartype::BINARY) // spin -> binary\n        {\n            std::tie(linear, quadratic, offset) = spin_to_binary(m_linear, m_quadratic, m_offset);\n        }\n        else\n        {\n            std::tie(linear, quadratic, offset) = std::tie(m_linear, m_quadratic, m_offset);\n        }\n\n        BinaryQuadraticModel bqm(linear, quadratic, offset, vartype, m_info);\n        \n        if(inplace == true)\n        {\n            //inplace\n            m_linear = bqm.get_linear();\n            m_quadratic = bqm.get_quadratic();\n            m_offset = bqm.get_offset();\n            m_adj = bqm.get_adjacency();\n            m_info = bqm.get_info();\n            m_vartype = bqm.get_vartype();\n        }\n\n        return bqm;\n    };\n    \n    /* Static methods */\n    /**\n     * @brief Convert linear, quadratic, and offset from spin to binary. Does no checking of vartype. Copies all of the values into new objects.\n     * \n     * @param linear\n     * @param quadratic\n     * @param offset\n     * \n     * @return A tuple including a linear bias, a quadratic bias and an offset.\n     */\n    static std::tuple<Linear<IndexType, FloatType>, Quadratic<IndexType, FloatType>, FloatType> spin_to_binary\n    (\n        const Linear<IndexType, FloatType> &linear,\n        const Quadratic<IndexType, FloatType> &quadratic,\n        const FloatType &offset\n    )\n    {\n        Linear<IndexType, FloatType> new_linear;\n        Quadratic<IndexType, FloatType> new_quadratic;\n        FloatType new_offset = offset;\n        FloatType linear_offset = 0.0;\n        FloatType quadratic_offset = 0.0;\n\n        for(auto &it : linear)\n        {\n            insert_or_assign(new_linear, it.first, static_cast<FloatType>(2.0 * it.second));\n            linear_offset += it.second;\n        }\n\n        for(auto &it : quadratic)\n        {\n            insert_or_assign(new_quadratic, it.first, static_cast<FloatType>(4.0 * it.second));\n            new_linear[it.first.first] -= 2.0 * it.second;\n            new_linear[it.first.second] -= 2.0 * it.second;\n            quadratic_offset += it.second; \n        }\n\n        new_offset += quadratic_offset - linear_offset;\n\n        return std::make_tuple(new_linear, new_quadratic, new_offset);\n    };\n\n    /**\n     * @brief Convert linear, quadratic and offset from binary to spin. Does no checking of vartype. Copies all of the values into new objects.\n     * \n     * @param linear\n     * @param quadratic\n     * @param offset\n     * \n     * @return A tuple including a linear bias, a quadratic bias and an offset.\n     */\n    static std::tuple<Linear<IndexType, FloatType>, Quadratic<IndexType, FloatType>, FloatType> binary_to_spin\n    (\n        const Linear<IndexType, FloatType> &linear,\n        const Quadratic<IndexType, FloatType> &quadratic,\n        const FloatType &offset\n    )\n    {\n        Linear<IndexType, FloatType> h;\n        Quadratic<IndexType, FloatType> J;\n        FloatType new_offset = offset;\n        FloatType linear_offset = 0.0;\n        FloatType quadratic_offset = 0.0;\n\n        for(auto &it : linear)\n        {\n            insert_or_assign(h, it.first, static_cast<FloatType>(0.5 * it.second));\n            linear_offset += it.second;\n        }\n\n        for(auto &it : quadratic)\n        {\n            insert_or_assign(J, it.first, static_cast<FloatType>(0.25 * it.second));\n            h[it.first.first] += 0.25 * it.second;\n            h[it.first.second] += 0.25 * it.second;\n            quadratic_offset += it.second;\n        }\n\n        new_offset += 0.5 * linear_offset + 0.25 * quadratic_offset;\n\n        return std::make_tuple(h, J, new_offset);\n    };\n\n    /* Methods */\n\n    /**\n     * @brief Determine the energy of the specified sample of a binary quadratic model.\n     * \n     * @param sample\n     * @return An energy with respect to the sample.\n     */\n    FloatType energy\n    (\n        const Sample<IndexType> &sample\n    )\n    {\n        FloatType en = m_offset;\n        for(auto &&it : m_linear)\n        {\n            if(check_vartype(sample.at(it.first), m_vartype))\n            {\n                en += static_cast<FloatType>(sample.at(it.first)) * it.second;\n            }\n        }\n        for(auto &it : m_quadratic)\n        {\n            if(check_vartype(sample.at(it.first.first), m_vartype)&&check_vartype(sample.at(it.first.second), m_vartype))\n            {\n                en += static_cast<FloatType>(sample.at(it.first.first)) * static_cast<FloatType>(sample.at(it.first.second)) * it.second;\n            }\n        }\n        return en;\n    };\n    \n    /**\n     * @brief Determine the energies of the given samples.\n     * \n     * @param samples_like\n     * @return A vector including energies with respect to the samples.\n     */\n    std::vector<FloatType> energies\n    (\n        const std::vector<Sample<IndexType>> &samples_like\n    )\n    {\n        std::vector<FloatType> en_vec;\n        for(auto &it : samples_like)\n        {\n            en_vec.push_back(energy(it));\n        }\n        return en_vec;\n    };\n    \n    /* Conversions */\n    /**\n     * @brief Convert a binary quadratic model to QUBO format.\n     * \n     * @return A tuple including a quadratic bias and an offset.\n     */\n    std::tuple<Quadratic<IndexType, FloatType>, FloatType> to_qubo()\n    {\n        // change vartype to binary\n        BinaryQuadraticModel bqm = change_vartype(Vartype::BINARY, false);\n\n        Linear<IndexType, FloatType> linear = bqm.get_linear();\n        Quadratic<IndexType, FloatType> Q = bqm.get_quadratic();\n        FloatType offset = bqm.get_offset();\n        for(auto &it : linear)\n        {\n            insert_or_assign(Q, std::make_pair(it.first, it.first), it.second);\n        }\n        return std::make_tuple(Q, offset);\n    };\n\n    /**\n     * @brief Create a binary quadratic model from a QUBO model.\n     *\n     * @param Q\n     * @param offset\n     *\n     * @return Binary quadratic model with vartype set to `.Vartype.BINARY`.\n     */\n    static BinaryQuadraticModel from_qubo(const Quadratic<IndexType, FloatType>& Q, FloatType offset=0.0)\n    {\n        Linear<IndexType, FloatType> linear;\n        Quadratic<IndexType, FloatType> quadratic;\n\n        for(auto&& elem : Q){\n            const auto& key = elem.first;\n            const auto& value = elem.second;\n            if(key.first == key.second){\n                linear[key.first] = value;\n            }\n            else{\n                quadratic[std::make_pair(key.first, key.second)] = value;\n            }\n        }\n\n        return BinaryQuadraticModel<IndexType, FloatType>(linear, quadratic, offset, Vartype::BINARY);\n    }\n\n    /**\n     * @brief Convert a binary quadratic model to Ising format.\n     * \n     * @return A tuple including a linear bias, a quadratic bias and an offset.\n     */\n    std::tuple<Linear<IndexType, FloatType>, Quadratic<IndexType, FloatType>, FloatType> to_ising()\n    {\n        // change vartype to spin\n        BinaryQuadraticModel bqm = change_vartype(Vartype::SPIN, false);\n\n        Linear<IndexType, FloatType> linear = bqm.get_linear();\n        Quadratic<IndexType, FloatType> quadratic = bqm.get_quadratic();\n        FloatType offset = bqm.get_offset();\n        return std::make_tuple(linear, quadratic, offset);\n    };\n\n    /**\n     * @brief Create a binary quadratic model from an Ising problem.\n     *\n     * @param linear\n     * @param quadratic\n     * @param offset\n     *\n     * @return Binary quadratic model with vartype set to `.Vartype.SPIN`.\n     */\n    static BinaryQuadraticModel from_ising(const Linear<IndexType, FloatType>& linear, const Quadratic<IndexType, FloatType>& quadratic, FloatType offset=0.0)\n    {\n        return BinaryQuadraticModel<IndexType, FloatType>(linear, quadratic, offset, Vartype::SPIN);\n    }\n\n\n    /**\n     * @brief generate interaction matrix with given list of indices\n     * The generated matrix will be the following symmetric matrix:\n     * \\f[\n     * \\begin{pmatrix}\n     * \\tilde{J}_{0,0} & \\tilde{J}_{0,1} & \\tilde{J}_{0,2} & \\cdots \\\\\n     * \\tilde{J}_{1,0} & \\tilde{J}_{1,1} & \\tilde{J}_{1,2} & \\cdots \\\\\n     * \\tilde{J}_{2,0} & \\tilde{J}_{2,1} & \\tilde{J}_{2,2} & \\cdots \\\\\n     * \\vdots & \\vdots & \\vdots & \\ddots \\\\\n     * \\end{pmatrix}\n     * \\f]\n     *\n     * where in the Ising case,\n     * \\f[\n     * \\tilde{J}_{f(i),f(j)} = J_{ij} + J_{ji}, \\\\\n     * \\tilde{J}_{f(i),f(i)} = h_{i},\n     * \\f]\n     * and the QUBO case,\n     * \\f[\n     * \\tilde{J}_{f(i),f(j)} = Q_{ij} + Q_{ji}, \\\\\n     * \\tilde{J}_{f(i),f(i)} = Q_{ii},\n     * \\f]\n     * and the function \\f$f\\f$ denotes a mapping from index to the corresponding number specified by the argument `indices`.\n     * For instance, if `indices` is ['a', 'b', 'c'], The following equations, \\f$f(a) = 0, f(b)=1, \\mathrm{and} f(c)=2\\f$ hold.\n     *\n     * The original Hamiltonian can be rewritten with \\f$\\tilde{J_{ij}}\\f$ as\n     * \\f[\n     * E_{\\mathrm{Ising}} = \\sum_{i} \\tilde{J}_{f(i),f(i)} s_i + \\sum_{i < j} \\tilde{J}_{f(i), f(j)} s_i s_j + \\delta_{\\mathrm{Ising}},\n     * \\f]\n     * and\n     * \\f[\n     * E_{\\mathrm{QUBO}} = \\sum_{i} \\tilde{J}_{f(i), f(i)}x_i + \\sum_{i < j} \\tilde{J}_{f(i), f(j)} x_i x_j + \\delta_{\\mathrm{QUBO}}.\n     * \\f]\n     *\n     * @param indices\n     *\n     * @return corresponding interaction matrix (Eigen)\n     */\n    Matrix interaction_matrix(const std::vector<IndexType>& indices){\n        // generate matrix\n        size_t system_size = indices.size();\n        Matrix _interaction_matrix = Matrix::Zero(system_size, system_size);\n        const Linear<IndexType, FloatType>& linear = m_linear; \n        const Quadratic<IndexType, FloatType>& quadratic = m_quadratic; \n\n        for(size_t i=0; i<indices.size(); i++){\n            const IndexType& i_index = indices[i];\n            _interaction_matrix(i, i) = (linear.find(i_index) != linear.end()) ? linear.at(i_index): 0;\n            for(size_t j=i+1; j<indices.size(); j++){\n                const IndexType& j_index = indices[j];\n                FloatType jval = 0.0;\n\n                if(quadratic.find(std::make_pair(i_index, j_index)) != quadratic.end()){\n                    jval += quadratic.at(std::make_pair(i_index, j_index));\n                }\n                if(quadratic.find(std::make_pair(j_index, i_index)) != quadratic.end()){\n                    jval += quadratic.at(std::make_pair(j_index, i_index));\n                }\n\n                _interaction_matrix(i, j) = jval;\n                _interaction_matrix(j, i) = jval;\n            }\n        }\n\n        return _interaction_matrix;\n    }\n\n\n    using json = nlohmann::json;\n\n    /**\n     * @brief Convert the binary quadratic model to a serializable object\n     * user_bytes is assume to be set to False\n     *\n     * @return An object that can be serialized (nlohmann::json)\n     */\n    json to_serializable() const\n    {\n        std::string schema_version = \"3.0.0\";\n        //all variables are contained in the keys of m_linear.\n        //All we need is to traverse the keys of m_linear.\n        /*\n         * output sample\n         * >>> bqm = dimod.BinaryQuadraticModel({'c': -1, 'd': 1}, {('a', 'd'): 2, ('b', 'e'): 5, ('a', 'c'): 3}, 0.0, dimod.BINARY)\n         *\n         * >>> bqm.to_serializable()\n         * {'type': 'BinaryQuadraticModel', 'version': {'bqm_schema': '3.0.0'}, 'use_bytes': False, 'index_type': 'uint16', 'bias_type': 'float32', 'num_variables': 5, 'num_interactions': 3, 'variable_labels': ['a', 'b', 'c', 'd', 'e'], 'variable_type': 'BINARY', 'offset': 0.0, 'info': {}, 'linear_biases': [0.0, 0.0, -1.0, 1.0, 0.0], 'quadratic_biases': [3.0, 2.0, 5.0], 'quadratic_head': [0, 0, 1], 'quadratic_tail': [2, 3, 4]}\n         */\n\n        //set variables (sorted)\n        std::vector<IndexType> variables;\n        variables.reserve(m_linear.size());\n        for(auto&& elem : m_linear)\n        {\n            variables.push_back(elem.first);\n        }\n\n        std::sort(variables.begin(), variables.end());\n\n        size_t num_variables = variables.size();\n        \n        //set sorted linear biases\n        std::vector<FloatType> l_bias;\n        for(auto&& key : variables)\n        {\n            l_bias.push_back(m_linear.at(key));\n        }\n\n        //set quadratic head, tail and biases\n        std::vector<size_t> q_head, q_tail;\n        std::vector<FloatType> q_bias;\n        for(auto&& elem : m_quadratic)\n        {\n            auto it_head = std::find(variables.begin(), variables.end(), elem.first.first);\n            auto it_tail = std::find(variables.begin(), variables.end(), elem.first.second);\n            size_t idx_head = std::distance(variables.begin(), it_head);\n            size_t idx_tail = std::distance(variables.begin(), it_tail);\n            q_head.push_back(idx_head);\n            q_tail.push_back(idx_tail);\n            q_bias.push_back(elem.second);\n        }\n\n        size_t num_interactions =  m_quadratic.size();\n\n        //set index_dtype\n        std::string index_dtype = num_variables <= 65536UL ? \"uint16\" : \"uint32\";\n\n        //set bias_type\n        std::string bias_type;\n        if(typeid(m_offset) == typeid(float))\n        {\n            bias_type = \"float32\";\n        }\n        else if(typeid(m_offset) == typeid(double))\n        {\n            bias_type = \"float64\";\n        }\n        else\n        {\n            std::cerr << \"FloatType must be float or double.\" << std::endl;\n        }\n\n        //set variable type\n        std::string variable_type;\n        if(m_vartype == Vartype::SPIN)\n        {\n            variable_type = \"SPIN\";\n        }\n        else if(m_vartype == Vartype::BINARY)\n        {\n            variable_type = \"BINARY\";\n        }\n        else\n        {\n            std::cerr << \"Variable type must be SPIN or BINARY.\" << std::endl;\n        }\n\n        json output;\n        output[\"type\"] = \"BinaryQuadraticModel\";\n        output[\"version\"] = {{\"bqm_schema\", \"3.0.0\"}};\n        output[\"variable_labels\"] = variables;\n        output[\"use_bytes\"] = false;\n        output[\"index_type\"] = index_dtype;\n        output[\"bias_type\"] = bias_type;\n        output[\"num_variables\"] = num_variables;\n        output[\"num_interactions\"] = num_interactions;\n        output[\"variable_labels\"] = variables;\n        output[\"variable_type\"] = variable_type;\n        output[\"offset\"] = m_offset;\n        output[\"info\"] = m_info;\n        output[\"linear_biases\"] = l_bias;\n        output[\"quadratic_biases\"] = q_bias;\n        output[\"quadratic_head\"] = q_head;\n        output[\"quadratic_tail\"] = q_tail;\n\n        return output;\n    };\n\n    /**\n     * @brief Create a BinaryQuadraticModel instance from a serializable object.\n     * \n     * @tparam IndexType_serial\n     * @tparam FloatType_serial\n     * @param input\n     * @return BinaryQuadraticModel<IndexType_serial, FloatType_serial> \n     */\n    template <typename IndexType_serial = IndexType, typename FloatType_serial = FloatType>\n    static BinaryQuadraticModel<IndexType_serial, FloatType_serial> from_serializable(const json &input)\n    {\n        //extract type and version\n        std::string type = input[\"type\"];\n        if(type != \"BinaryQuadraticModel\")\n        {\n            throw std::runtime_error(\"Type must be \\\"BinaryQuadraticModel\\\".\\n\");\n        }\n        std::string version = input[\"version\"][\"bqm_schema\"];\n        if(version != \"3.0.0\")\n        {\n            throw std::runtime_error(\"bqm_schema must be 3.0.0.\\n\");\n        }\n\n        //extract variable_type\n        Vartype vartype;\n        std::string variable_type = input[\"variable_type\"];\n        if(variable_type == \"SPIN\")\n        {\n            vartype = Vartype::SPIN;\n        }\n        else if(variable_type == \"BINARY\")\n        {\n            vartype = Vartype::BINARY;\n        }\n        else\n        {\n            throw std::runtime_error(\"variable_type must be SPIN or BINARY.\");\n        }\n\n        //extract linear biases\n        Linear<IndexType_serial, FloatType_serial> linear;\n        std::vector<IndexType_serial> variables = input[\"variable_labels\"];\n        std::vector<FloatType_serial> l_bias = input[\"linear_biases\"];\n        for(size_t i = 0; i < variables.size(); ++i)\n        {\n            insert_or_assign(linear, variables[i], l_bias[i]);\n        }\n\n        //extract quadratic biases\n        Quadratic<IndexType_serial, FloatType_serial> quadratic;\n        std::vector<size_t> q_head = input[\"quadratic_head\"];\n        std::vector<size_t> q_tail = input[\"quadratic_tail\"];\n        std::vector<FloatType_serial> q_bias = input[\"quadratic_biases\"];\n        for(size_t i = 0; i < q_head.size(); ++i)\n        {\n            insert_or_assign(quadratic, std::make_pair(variables[q_head[i]], variables[q_tail[i]]), q_bias[i]);\n        }\n\n        //extract offset and info\n        FloatType_serial offset = input[\"offset\"];\n        std::string info = (input[\"info\"].empty())?\"\":input[\"info\"];\n\n        //construct a BinaryQuadraticModel instance\n        BinaryQuadraticModel<IndexType_serial, FloatType_serial> bqm(linear, quadratic, offset, vartype, info);\n        return bqm;\n    };\n\n};\n}\n#endif\n", "meta": {"hexsha": "73b0264d6c79b938797cf9c04aa11b9d55802a73", "size": 43328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/binary_quadratic_model.hpp", "max_stars_repo_name": "kotarotanahashi/cimod", "max_stars_repo_head_hexsha": "062209f3767092cc1993fc46e7a2d6f63d8a4c72", "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/binary_quadratic_model.hpp", "max_issues_repo_name": "kotarotanahashi/cimod", "max_issues_repo_head_hexsha": "062209f3767092cc1993fc46e7a2d6f63d8a4c72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/binary_quadratic_model.hpp", "max_forks_repo_name": "kotarotanahashi/cimod", "max_forks_repo_head_hexsha": "062209f3767092cc1993fc46e7a2d6f63d8a4c72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T06:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T06:52:09.000Z", "avg_line_length": 29.1182795699, "max_line_length": 430, "alphanum_fraction": 0.5470596381, "num_tokens": 11010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.07921032302219254, "lm_q1q2_score": 0.03775002810655758}}
{"text": "/* Author: Wolfgang Bangerth, Texas A&M University, 2009, 2010 */\n/*         Timo Heister, University of Goettingen, 2009, 2010 */\n\n/*    $Id: step-40.cc 28561 2013-02-25 23:16:09Z heister $       */\n/*                                                                */\n/*    Copyright (C) 2009-2012 by Timo Heister 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// Most of the include files we need for this program have already been\n// discussed in previous programs. In particular, all of the following should\n// already be familiar friends:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/compressed_simple_sparsity_pattern.h>\n\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n\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/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n\n// The following, however, will be new or be used in new roles. Let's walk\n// through them. The first of these will provide the tools of the\n// Utilities::System namespace that we will use to query things like the\n// number of processors associated with the current MPI universe, or the\n// number within this universe the processor this job runs on is:\n#include <deal.II/base/utilities.h>\n// The next one provides a class, ConditionOStream that allows us to write\n// code that would output things to a stream (such as <code>std::cout</code>\n// on every processor but throws the text away on all but one of them. We\n// could achieve the same by simply putting an <code>if</code> statement in\n// front of each place where we may generate output, but this doesn't make the\n// code any prettier. In addition, the condition whether this processor should\n// or should not produce output to the screen is the same every time -- and\n// consequently it should be simple enough to put it into the statements that\n// generate output itself.\n#include <deal.II/base/conditional_ostream.h>\n// After these preliminaries, here is where it becomes more interesting. As\n// mentioned in the @ref distributed module, one of the fundamental truths of\n// solving problems on large numbers of processors is that there is no way for\n// any processor to store everything (e.g. information about all cells in the\n// mesh, all degrees of freedom, or the values of all elements of the solution\n// vector). Rather, every processor will <i>own</i> a few of each of these\n// and, if necessary, may <i>know</i> about a few more, for example the ones\n// that are located on cells adjacent to the ones this processor owns\n// itself. We typically call the latter <i>ghost cells</i>, <i>ghost nodes</i>\n// or <i>ghost elements of a vector</i>. The point of this discussion here is\n// that we need to have a way to indicate which elements a particular\n// processor owns or need to know of. This is the realm of the IndexSet class:\n// if there are a total of $N$ cells, degrees of freedom, or vector elements,\n// associated with (non-negative) integral indices $[0,N)$, then both the set\n// of elements the current processor owns as well as the (possibly larger) set\n// of indices it needs to know about are subsets of the set $[0,N)$. IndexSet\n// is a class that stores subsets of this set in an efficient format:\n#include <deal.II/base/index_set.h>\n// The next header file is necessary for a single function,\n// SparsityTools::distribute_sparsity_pattern. The role of this function will\n// be explained below.\n#include <deal.II/lac/sparsity_tools.h>\n// The final two, new header files provide the class\n// parallel::distributed::Triangulation that provides meshes distributed\n// across a potentially very large number of processors, while the second\n// provides the namespace parallel::distributed::GridRefinement that offers\n// functions that can adaptively refine such distributed meshes:\n#include <deal.II/distributed/tria.h>\n#include <deal.II/distributed/grid_refinement.h>\n\n#include <fstream>\n#include <iostream>\n\nnamespace Step40\n{\n  using namespace dealii;\n\n  // @sect3{The <code>LaplaceProblem</code> class template}\n\n  // Next let's declare the main class of this program. Its structure is\n  // almost exactly that of the step-6 tutorial program. The only significant\n  // differences are:\n  // - The <code>mpi_communicator</code> variable that\n  //   describes the set of processors we want this code to run on. In practice,\n  //   this will be MPI_COMM_WORLD, i.e. all processors the batch scheduling\n  //   system has assigned to this particular job.\n  // - The presence of the <code>pcout</code> variable of type ConditionOStream.\n  // - The obvious use of parallel::distributed::Triangulation instead of Triangulation.\n  // - The presence of two IndexSet objects that denote which sets of degrees of\n  //   freedom (and associated elements of solution and right hand side vectors)\n  //   we own on the current processor and which we need (as ghost elements) for\n  //   the algorithms in this program to work.\n  // - The fact that all matrices and vectors are now distributed. We use\n  //   their PETScWrapper versions for this since deal.II's own classes do not\n  //   provide %parallel functionality. Note that as part of this class, we\n  //   store a solution vector that does not only contain the degrees of freedom\n  //   the current processor owns, but also (as ghost elements) all those vector\n  //   elements that correspond to \"locally relevant\" degrees of freedom\n  //   (i.e. all those that live on locally owned cells or the layer of ghost\n  //   cells that surround it).\n  template <int dim>\n  class LaplaceProblem\n  {\n  public:\n    LaplaceProblem ();\n    ~LaplaceProblem ();\n\n    void run ();\n\n  private:\n    void setup_system ();\n    void assemble_system ();\n    void solve ();\n    void refine_grid ();\n    void output_results (const unsigned int cycle) const;\n\n    MPI_Comm mpi_communicator;\n\n    parallel::distributed::Triangulation<dim>   triangulation;\n\n    DoFHandler<dim>      dof_handler;\n    FE_Q<dim>            fe;\n\n    IndexSet             locally_owned_dofs;\n    IndexSet             locally_relevant_dofs;\n\n    ConstraintMatrix     constraints;\n\n    PETScWrappers::MPI::SparseMatrix system_matrix;\n    PETScWrappers::MPI::Vector locally_relevant_solution;\n    PETScWrappers::MPI::Vector system_rhs;\n\n    ConditionalOStream                pcout;\n  };\n\n\n  // @sect3{The <code>LaplaceProblem</code> class implementation}\n\n  // @sect4{Constructors and destructors}\n\n  // Constructors and destructors are rather trivial. In addition to what we\n  // do in step-6, we set the set of processors we want to work on to all\n  // machines available (MPI_COMM_WORLD); ask the triangulation to ensure that\n  // the mesh remains smooth and free to refined islands, for example; and\n  // initialize the <code>pcout</code> variable to only allow processor zero\n  // to output anything:\n  template <int dim>\n  LaplaceProblem<dim>::LaplaceProblem ()\n    :\n    mpi_communicator (MPI_COMM_WORLD),\n    triangulation (mpi_communicator,\n                   typename Triangulation<dim>::MeshSmoothing\n                   (Triangulation<dim>::smoothing_on_refinement |\n                    Triangulation<dim>::smoothing_on_coarsening)),\n    dof_handler (triangulation),\n    fe (2),\n    pcout (std::cout,\n           (Utilities::MPI::this_mpi_process(mpi_communicator)\n            == 0))\n  {}\n\n\n\n  template <int dim>\n  LaplaceProblem<dim>::~LaplaceProblem ()\n  {\n    dof_handler.clear ();\n  }\n\n\n  // @sect4{LaplaceProblem::setup_system}\n\n  // The following function is, arguably, the most interesting one in the\n  // entire program since it goes to the heart of what distinguishes %parallel\n  // step-40 from sequential step-6.\n  //\n  // At the top we do what we always do: tell the DoFHandler object to\n  // distribute degrees of freedom. Since the triangulation we use here is\n  // distributed, the DoFHandler object is smart enough to recognize that on\n  // each processor it can only distribute degrees of freedom on cells it\n  // owns; this is followed by an exchange step in which processors tell each\n  // other about degrees of freedom on ghost cell. The result is a DoFHandler\n  // that knows about the degrees of freedom on locally owned cells and ghost\n  // cells (i.e. cells adjacent to locally owned cells) but nothing about\n  // cells that are further away, consistent with the basic philosophy of\n  // distributed computing that no processor can know everything.\n  template <int dim>\n  void LaplaceProblem<dim>::setup_system ()\n  {\n    dof_handler.distribute_dofs (fe);\n\n    // The next two lines extract some informatino we will need later on,\n    // namely two index sets that provide information about which degrees of\n    // freedom are owned by the current processor (this information will be\n    // used to initialize solution and right hand side vectors, and the system\n    // matrix, indicating which elements to store on the current processor and\n    // which to expect to be stored somewhere else); and an index set that\n    // indicates which degrees of freedom are locally relevant (i.e. live on\n    // cells that the current processor owns or on the layer of ghost cells\n    // around the locally owned cells; we need all of these degrees of\n    // freedom, for example, to estimate the error on the local cells).\n    locally_owned_dofs = dof_handler.locally_owned_dofs ();\n    DoFTools::extract_locally_relevant_dofs (dof_handler,\n                                             locally_relevant_dofs);\n\n    // Next, let us initialize the solution and right hand side vectors. As\n    // mentioned above, the solution vector we seek does not only store\n    // elements we own, but also ghost entries; on the other hand, the right\n    // hand side vector only needs to have the entries the current processor\n    // owns since all we will ever do is write into it, never read from it on\n    // locally owned cells (of course the linear solvers will read from it,\n    // but they do not care about the geometric location of degrees of\n    // freedom).\n    locally_relevant_solution.reinit (mpi_communicator,\n                                      locally_owned_dofs,\n                                      locally_relevant_dofs);\n    system_rhs.reinit (mpi_communicator,\n                       dof_handler.n_dofs(),\n                       dof_handler.n_locally_owned_dofs());\n    system_rhs = 0;\n\n    // The next step is to compute hanging node and boundary value\n    // constraints, which we combine into a single object storing all\n    // constraints.\n    //\n    // As with all other things in %parallel, the mantra must be that no\n    // processor can store all information about the entire universe. As a\n    // consequence, we need to tell the constraints object for which degrees\n    // of freedom it can store constraints and for which it may not expect any\n    // information to store. In our case, as explained in the @ref distributed\n    // module, the degrees of freedom we need to care about on each processor\n    // are the locally relevant ones, so we pass this to the\n    // ConstraintMatrix::reinit function. As a side note, if you forget to\n    // pass this argument, the ConstraintMatrix class will allocate an array\n    // with length equal to the largest DoF index it has seen so far. For\n    // processors with high MPI process number, this may be very large --\n    // maybe on the order of billions. The program would then allocate more\n    // memory than for likely all other operations combined for this single\n    // array.\n    constraints.clear ();\n    constraints.reinit (locally_relevant_dofs);\n    DoFTools::make_hanging_node_constraints (dof_handler, constraints);\n    VectorTools::interpolate_boundary_values (dof_handler,\n                                              0,\n                                              ZeroFunction<dim>(),\n                                              constraints);\n    constraints.close ();\n\n    // The last part of this function deals with initializing the matrix with\n    // accompanying sparsity pattern. As in previous tutorial programs, we use\n    // the CompressedSimpleSparsityPattern as an intermediate with which we\n    // then initialize the PETSc matrix. To do so we have to tell the sparsity\n    // pattern its size but as above there is no way the resulting object will\n    // be able to store even a single pointer for each global degree of\n    // freedom; the best we can hope for is that it stores information about\n    // each locally relevant degree of freedom, i.e. all those that we may\n    // ever touch in the process of assembling the matrix (the @ref\n    // distributed_paper \"distributed computing paper\" has a long discussion\n    // why one really needs the locally relevant, and not the small set of\n    // locally active degrees of freedom in this context).\n    //\n    // So we tell the sparsity pattern its size and what DoFs to store\n    // anything for and then ask DoFTools::make_sparsity_pattern to fill it\n    // (this function ignores all cells that are not locally owned, mimicking\n    // what we will do below in the assembly process). After this, we call a\n    // function that exchanges entries in these sparsity pattern between\n    // processors so that in the end each processor really knows about all the\n    // entries that will exist in that part of the finite element matrix that\n    // it will own. The final step is to initialize the matrix with the\n    // sparsity pattern.\n    CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(),\n                                         dof_handler.n_dofs(),\n                                         locally_relevant_dofs);\n    DoFTools::make_sparsity_pattern (dof_handler,\n                                     csp,\n                                     constraints, false);\n    SparsityTools::distribute_sparsity_pattern (csp,\n                                                dof_handler.n_locally_owned_dofs_per_processor(),\n                                                mpi_communicator,\n                                                locally_relevant_dofs);\n    system_matrix.reinit (mpi_communicator,\n                          csp,\n                          dof_handler.n_locally_owned_dofs_per_processor(),\n                          dof_handler.n_locally_owned_dofs_per_processor(),\n                          Utilities::MPI::this_mpi_process(mpi_communicator));\n  }\n\n\n\n  // @sect4{LaplaceProblem::assemble_system}\n\n  // The function that then assembles the linear system is comparatively\n  // boring, being almost exactly what we've seen before. The points to watch\n  // out for are:\n  // - Assembly must only loop over locally owned cells. There\n  //   are multiple ways to test that; for example, we could compare a cell's\n  //   subdomain_id against information from the triangulation as in\n  //   <code>cell->subdomain_id() ==\n  //   triangulation.locally_owned_subdomain()</code>, or skip all cells for\n  //   which the condition <code>cell->is_ghost() ||\n  //   cell->is_artificial()</code> is true. The simplest way, however, is to\n  //   simply ask the cell whether it is owned by the local processor.\n  // - Copying local contributions into the global matrix must include\n  //   distributing constraints and boundary values. In other words, we can now\n  //   (as we did in step-6) first copy every local contribution into the global\n  //   matrix and only in a later step take care of hanging node constraints and\n  //   boundary values. The reason is, as discussed in step-17, that PETSc does\n  //   not provide access to arbitrary elements of the matrix once they have\n  //   been assembled into it -- in parts because they may simple no longer\n  //   reside on the current processor but have instead been shipped to a\n  //   different machine.\n  // - The way we compute the right hand side (given the\n  //   formula stated in the introduction) may not be the most elegant but will\n  //   do for a program whose focus lies somewhere entirely different.\n  template <int dim>\n  void LaplaceProblem<dim>::assemble_system ()\n  {\n    const QGauss<dim>  quadrature_formula(3);\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values    |  update_gradients |\n                             update_quadrature_points |\n                             update_JxW_values);\n\n    const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int   n_q_points    = quadrature_formula.size();\n\n    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       cell_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      if (cell->is_locally_owned())\n        {\n          cell_matrix = 0;\n          cell_rhs = 0;\n\n          fe_values.reinit (cell);\n\n          for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n            {\n              const double\n              rhs_value\n                = (fe_values.quadrature_point(q_point)[1]\n                   >\n                   0.5+0.25*std::sin(4.0 * numbers::PI *\n                                     fe_values.quadrature_point(q_point)[0])\n                   ? 1 : -1);\n\n              for (unsigned int i=0; i<dofs_per_cell; ++i)\n                {\n                  for (unsigned int j=0; j<dofs_per_cell; ++j)\n                    cell_matrix(i,j) += (fe_values.shape_grad(i,q_point) *\n                                         fe_values.shape_grad(j,q_point) *\n                                         fe_values.JxW(q_point));\n\n                  cell_rhs(i) += (rhs_value *\n                                  fe_values.shape_value(i,q_point) *\n                                  fe_values.JxW(q_point));\n                }\n            }\n\n          cell->get_dof_indices (local_dof_indices);\n          constraints.distribute_local_to_global (cell_matrix,\n                                                  cell_rhs,\n                                                  local_dof_indices,\n                                                  system_matrix,\n                                                  system_rhs);\n        }\n\n    system_matrix.compress (VectorOperation::add);\n    system_rhs.compress (VectorOperation::add);\n  }\n\n\n\n  // @sect4{LaplaceProblem::solve}\n\n  // Even though solving linear systems on potentially tens of thousands of\n  // processors is by far not a trivial job, the function that does this is --\n  // at least at the outside -- relatively simple. Most of the parts you've\n  // seen before. There are really only two things worth mentioning:\n  // - Solvers and preconditioners are built on the deal.II wrappers of PETSc\n  //   functionality. It is relatively well known that the primary bottleneck of\n  //   massively %parallel linear solvers is not actually the communication\n  //   between processors, but the fact that it is difficult to produce\n  //   preconditioners that scale well to large numbers of processors. Over the\n  //   second half of the first decade of the 21st century, it has become clear\n  //   that algebraic multigrid (AMG) methods turn out to be extremely efficient\n  //   in this context, and we will use one of them -- the BoomerAMG\n  //   implementation of the Hypre package that can be interfaced to through\n  //   PETSc -- for the current program. The rest of the solver itself is\n  //   boilerplate and has been shown before. Since the linear system is\n  //   symmetric and positive definite, we can use the CG method as the outer\n  //   solver.\n  // - Ultimately, we want a vector that stores not only the elements\n  //   of the solution for degrees of freedom the current processor owns, but\n  //   also all other locally relevant degrees of freedom. On the other hand,\n  //   the solver itself needs a vector that is uniquely split between\n  //   processors, without any overlap. We therefore create a vector at the\n  //   beginning of this function that has these properties, use it to solve the\n  //   linear system, and only assign it to the vector we want at the very\n  //   end. This last step ensures that all ghost elements are also copied as\n  //   necessary.\n  template <int dim>\n  void LaplaceProblem<dim>::solve ()\n  {\n    PETScWrappers::MPI::Vector\n    completely_distributed_solution (mpi_communicator,\n                                     dof_handler.n_dofs(),\n                                     dof_handler.n_locally_owned_dofs());\n\n    SolverControl solver_control (dof_handler.n_dofs(), 1e-12);\n\n    PETScWrappers::SolverCG solver(solver_control, mpi_communicator);\n\n    // Ask for a symmetric preconditioner by setting the first parameter in\n    // AdditionalData to true.\n    PETScWrappers::PreconditionBoomerAMG\n    preconditioner(system_matrix,\n                   PETScWrappers::PreconditionBoomerAMG::AdditionalData(true));\n\n    solver.solve (system_matrix, completely_distributed_solution, system_rhs,\n                  preconditioner);\n\n    pcout << \"   Solved in \" << solver_control.last_step()\n          << \" iterations.\" << std::endl;\n\n    constraints.distribute (completely_distributed_solution);\n\n    locally_relevant_solution = completely_distributed_solution;\n  }\n\n\n\n  // @sect4{LaplaceProblem::refine_grid}\n\n  // The function that estimates the error and refines the grid is again\n  // almost exactly like the one in step-6. The only difference is that the\n  // function that flags cells to be refined is now in namespace\n  // parallel::distributed::GridRefinement -- a namespace that has functions\n  // that can communicate between all involved processors and determine global\n  // thresholds to use in deciding which cells to refine and which to coarsen.\n  //\n  // Note that we didn't have to do anything special about the\n  // KellyErrorEstimator class: we just give it a vector with as many elements\n  // as the local triangulation has cells (locally owned cells, ghost cells,\n  // and artificial ones), but it only fills those entries that correspond to\n  // cells that are locally owned.\n  template <int dim>\n  void LaplaceProblem<dim>::refine_grid ()\n  {\n    Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n    KellyErrorEstimator<dim>::estimate (dof_handler,\n                                        QGauss<dim-1>(3),\n                                        typename FunctionMap<dim>::type(),\n                                        locally_relevant_solution,\n                                        estimated_error_per_cell);\n    parallel::distributed::GridRefinement::\n    refine_and_coarsen_fixed_number (triangulation,\n                                     estimated_error_per_cell,\n                                     0.3, 0.03);\n    triangulation.execute_coarsening_and_refinement ();\n  }\n\n\n\n  // @sect4{LaplaceProblem::output_results}\n\n  // Compared to the corresponding function in step-6, the one here is a tad\n  // more complicated. There are two reasons: the first one is that we do not\n  // just want to output the solution but also for each cell which processor\n  // owns it (i.e. which \"subdomain\" it is in). Secondly, as discussed at\n  // length in step-17 and step-18, generating graphical data can be a\n  // bottleneck in parallelizing. In step-18, we have moved this step out of\n  // the actual computation but shifted it into a separate program that later\n  // combined the output from various processors into a single file. But this\n  // doesn't scale: if the number of processors is large, this may mean that\n  // the step of combining data on a single processor later becomes the\n  // longest running part of the program, or it may produce a file that's so\n  // large that it can't be visualized any more. We here follow a more\n  // sensible approach, namely creating individual files for each MPI process\n  // and leaving it to the visualization program to make sense of that.\n  //\n  // To start, the top of the function looks like always. In addition to\n  // attaching the solution vector (the one that has entries for all locally\n  // relevant, not only the locally owned, elements), we attach a data vector\n  // that stores, for each cell, the subdomain the cell belongs to. This is\n  // slightly tricky, because of course not every processor knows about every\n  // cell. The vector we attach therefore has an entry for every cell that the\n  // current processor has in its mesh (locally owned onces, ghost cells, and\n  // artificial cells), but the DataOut class will ignore all entries that\n  // correspond to cells that are not owned by the current processor. As a\n  // consequence, it doesn't actually matter what values we write into these\n  // vector entries: we simply fill the entire vector with the number of the\n  // current MPI process (i.e. the subdomain_id of the current process); this\n  // correctly sets the values we care for, i.e. the entries that correspond\n  // to locally owned cells, while providing the wrong value for all other\n  // elements -- but these are then ignored anyway.\n  template <int dim>\n  void LaplaceProblem<dim>::output_results (const unsigned int cycle) const\n  {\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (locally_relevant_solution, \"u\");\n\n    Vector<float> subdomain (triangulation.n_active_cells());\n    for (unsigned int i=0; i<subdomain.size(); ++i)\n      subdomain(i) = triangulation.locally_owned_subdomain();\n    data_out.add_data_vector (subdomain, \"subdomain\");\n\n    data_out.build_patches ();\n\n    // The next step is to write this data to disk. We choose file names of\n    // the form <code>solution-XX-PPPP.vtu</code> where <code>XX</code>\n    // indicates the refinement cycle, <code>PPPP</code> refers to the\n    // processor number (enough for up to 10,000 processors, though we hope\n    // that nobody ever tries to generate this much data -- you would likely\n    // overflow all file system quotas), and <code>.vtu</code> indicates the\n    // XML-based Visualization Toolkit (VTK) file format.\n    const std::string filename = (\"solution-\" +\n                                  Utilities::int_to_string (cycle, 2) +\n                                  \".\" +\n                                  Utilities::int_to_string\n                                  (triangulation.locally_owned_subdomain(), 4));\n    std::ofstream output ((filename + \".vtu\").c_str());\n    data_out.write_vtu (output);\n\n    // The last step is to write a \"master record\" that lists for the\n    // visualization program the names of the various files that combined\n    // represents the graphical data for the entire domain. The\n    // DataOutBase::write_pvtu_record does this, and it needs a list of\n    // filenames that we create first. Note that only one processor needs to\n    // generate this file; we arbitrarily choose processor zero to take over\n    // this job.\n    if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)\n      {\n        std::vector<std::string> filenames;\n        for (unsigned int i=0;\n             i<Utilities::MPI::n_mpi_processes(mpi_communicator);\n             ++i)\n          filenames.push_back (\"solution-\" +\n                               Utilities::int_to_string (cycle, 2) +\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\n  // @sect4{LaplaceProblem::run}\n\n  // The function that controls the overall behavior of the program is again\n  // like the one in step-6. The minor difference are the use of\n  // <code>pcout</code> instead of <code>std::cout</code> for output to the\n  // console (see also step-17) and that we only generate graphical output if\n  // at most 32 processors are involved. Without this limit, it would be just\n  // too easy for people carelessly running this program without reading it\n  // first to bring down the cluster interconnect and fill any file system\n  // available :-)\n  //\n  // A functional difference to step-6 is the use of a square domain and that\n  // we start with a slightly finer mesh (5 global refinement cycles) -- there\n  // just isn't much of a point showing a massively %parallel program starting\n  // on 4 cells (although admittedly the point is only slightly stronger\n  // starting on 1024).\n  template <int dim>\n  void LaplaceProblem<dim>::run ()\n  {\n    const unsigned int n_cycles = 8;\n    for (unsigned int cycle=0; cycle<n_cycles; ++cycle)\n      {\n        pcout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n          {\n            GridGenerator::hyper_cube (triangulation);\n            triangulation.refine_global (5);\n          }\n        else\n          refine_grid ();\n\n        setup_system ();\n\n        pcout << \"   Number of active cells:       \"\n              << triangulation.n_global_active_cells()\n              << std::endl\n              << \"   Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << std::endl;\n\n        assemble_system ();\n        solve ();\n\n        if (Utilities::MPI::n_mpi_processes(mpi_communicator) <= 32)\n          output_results (cycle);\n\n        pcout << std::endl;\n      }\n  }\n}\n\n\n\n// @sect4{main()}\n\n// The final function, <code>main()</code>, again has the same structure as in\n// all other programs, in particular step-6. Like in the other programs that\n// use PETSc, we have to inialize and finalize PETSc, which is done using the\n// helper object MPI_InitFinalize.\n//\n// Note how we enclose the use the use of the LaplaceProblem class in a pair\n// of braces. This makes sure that all member variables of the object are\n// destroyed by the time we destroy the mpi_intialization object. Not doing\n// this will lead to strange and hard to debug errors when\n// <code>PetscFinalize</code> first deletes all PETSc vectors that are still\n// around, and the destructor of the LaplaceProblem class then tries to delete\n// them again.\nint main(int argc, char *argv[])\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step40;\n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv);\n      deallog.depth_console (0);\n\n      {\n        LaplaceProblem<2> laplace_problem_2d;\n        laplace_problem_2d.run ();\n      }\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": "64c516adeb4d864314ac8f3ede584e920c50debb", "size": 32223, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-40/step-40.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-40/step-40.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-40/step-40.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": 46.835755814, "max_line_length": 97, "alphanum_fraction": 0.659870279, "num_tokens": 7247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.1294027332703691, "lm_q1q2_score": 0.037653719417588535}}
{"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 truth_table_from_bitset.hpp\n *\n * @brief Generates a truth table from a bitset\n *\n * @author Mathias Soeken\n * @since  2.3\n */\n\n#ifndef TRUTH_TABLE_FROM_BITSET_HPP\n#define TRUTH_TABLE_FROM_BITSET_HPP\n\n#include <boost/dynamic_bitset.hpp>\n\n#include <reversible/truth_table.hpp>\n\nnamespace cirkit\n{\n\n/* e.g.: maps 0001 into\n *\n *  00 0\n *  01 0\n *  10 0\n *  11 1\n */\nbinary_truth_table truth_table_from_bitset_direct( const boost::dynamic_bitset<>& bs );\n\n\n/* e.g.: maps 0001 into\n *\n *  000 0--\n *  001 0--\n *  010 0--\n *  011 1--\n *  100 ---\n *  101 ---\n *  110 ---\n *  111 ---\n *\n * requires one fewer line if bs is balanced\n */\nbinary_truth_table truth_table_from_bitset( const boost::dynamic_bitset<>& bs );\n\n/* e.g.: maps 0001 into\n *\n *   00 0  00 0\n *   00 1  00 1\n *   01 0  01 0\n *   01 1  01 1\n *   10 0  10 0\n *   10 1  10 1\n *   11 0  11 1\n *   11 1  11 0\n */\nbinary_truth_table truth_table_from_bitset_bennett( const boost::dynamic_bitset<>& bs );\n\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": "d90aed77ac3db652c126e1b313872f9318e56395", "size": 2317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/functions/truth_table_from_bitset.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/functions/truth_table_from_bitset.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/functions/truth_table_from_bitset.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": 24.9139784946, "max_line_length": 88, "alphanum_fraction": 0.6948640483, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.07696083516675281, "lm_q1q2_score": 0.03757869790002513}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <cassert>\n#include <cstdlib>\n#include <vector>\n\nnamespace rek {\n\nnamespace sample {\n\nclass AliasSampler {\n\n  unsigned int N;\n  std::vector<unsigned int> A, B;\n  std::vector<double> Y;\n\npublic:\n  AliasSampler(const AliasSampler &) = delete;\n\n  AliasSampler(const AliasSampler &&) = delete;\n\n  ~AliasSampler() = default;\n\n  explicit AliasSampler(const std::vector<double> &probs)\n      : A(probs.size() + 2), B(probs.size() + 2), Y(probs.size() + 2) {\n    double sum = 0;\n\n    this->N = (unsigned int)probs.size();\n    for (size_t j = 0; j < N; j++) {\n      sum += probs[j];\n    }\n\n    sum = 1 / sum;\n\n    // Normalize it now\n    for (size_t j = 0; j < N; j++)\n      Y[j + 1] = probs[j] * sum;\n  };\n\n  explicit AliasSampler(const Eigen::RowVectorXd &probs)\n      : A(probs.size() + 2), B(probs.size() + 2), Y(probs.size() + 2) {\n\n    double sum = 0;\n\n    this->N = (unsigned int)probs.size();\n\n    for (size_t j = 0; j < N; j++) {\n      sum += probs(j);\n    }\n\n    sum = 1 / sum;\n\n    // Normalize it now\n    for (size_t j = 0; j < N; j++) {\n      Y[j + 1] = probs(j) * sum;\n    }\n  };\n\n  std::vector<unsigned int> sample(unsigned int numSamples) {\n    std::vector<unsigned int> samples(numSamples);\n\n    // Sample from Alias Sampler\n    for (unsigned int k = 0; k < numSamples; k++) {\n      samples[k] = walkerSample();\n    }\n\n    return samples;\n  };\n\n  void initSampler() {\n    unsigned int i, j, k;\n    assert(1 <= N);\n    for (i = 1; i <= N; i++) {\n      A[i] = i;\n      B[i] = i; /* initial destins=stay there */\n      assert(Y[i] >= 0.0);\n      Y[i] = Y[i] * N; /* scale probvec */\n    }\n    B[0] = 0;\n    Y[0] = 0.0;\n    B[N + 1] = N + 1;\n    Y[N + 1] = 2.0; /* sentinels */\n    i = 0;\n    j = N + 1;\n    for (;;) {\n      do {\n        i++;\n      } while (Y[B[i]] < 1.0); /* find i so X[B[i]] needs more */\n      do {\n        j--;\n      } while (Y[B[j]] >= 1.0); /* find j so X[B[j]] wants less */\n      if (i >= j)\n        break;\n      k = B[i];\n      B[i] = B[j];\n      B[j] = k; /* swap B[i], B[j] */\n    }\n\n    i = j;\n    j++;\n    while (i > 0) {\n      while (Y[B[j]] <= 1.0)\n        j++;\n      /* find j so X[B[j]] needs more */\n      assert(Y[B[i]] < 1.0); /* meanwhile X[B[i]] wants less */\n      if (j > N)\n        break;\n      assert(j <= N);\n      assert(Y[B[j]] > 1.0);\n      Y[B[j]] -= 1.0 - Y[B[i]]; /* B[i] will donate to B[j] to fix up */\n      A[B[i]] = B[j];\n      if (Y[B[j]] < 1.0) { /* X[B[j]] now wants less so readjust ordering */\n        assert(i < j);\n        k = B[i];\n        B[i] = B[j];\n        B[j] = k; /* swap B[j], B[i] */\n        j++;\n      } else\n        i--;\n    }\n  };\n\n  unsigned int walkerSample() {\n    unsigned int i;\n    double r;\n    /* Let i = random uniform integer from {1,2,...N};  */\n    i = 1 + (unsigned int)((N - 1) * drand48());\n    r = drand48();\n    if (r > Y[i])\n      i = A[i];\n\n    return i - 1;\n  }\n};\n} // namespace sample\n} // namespace rek", "meta": {"hexsha": "2783f4a7b1c7cd5e156da2c6b5d1c609374e1ab4", "size": 2950, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sampler.hpp", "max_stars_repo_name": "zouzias/REK-CPP", "max_stars_repo_head_hexsha": "01eaaf4f5d05e7665595a8d3dc919632ba2940fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T06:50:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T08:48:25.000Z", "max_issues_repo_path": "src/sampler.hpp", "max_issues_repo_name": "zouzias/REK-CPP", "max_issues_repo_head_hexsha": "01eaaf4f5d05e7665595a8d3dc919632ba2940fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sampler.hpp", "max_forks_repo_name": "zouzias/REK-CPP", "max_forks_repo_head_hexsha": "01eaaf4f5d05e7665595a8d3dc919632ba2940fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5328467153, "max_line_length": 76, "alphanum_fraction": 0.4647457627, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.07369626411128531, "lm_q1q2_score": 0.036848132055642656}}
{"text": "/**\r\n * @author Tomas Polasek\r\n * @date 3.23.2020\r\n * @version 1.0\r\n * @brief Acceleration structures and query helpers.\r\n */\r\n\r\n#include \"TreeIOAcceleration.h\"\r\n\r\n#include <Eigen/Eigen>\r\n#include <unsupported/Eigen/BVH>\r\n\r\nnamespace treeacc\r\n{\r\n\r\nvoid PointCloudAcceleration::fromCloud(const PointCloud &cloud, std::size_t maxLeafSize)\r\n{ PointCloud cloudCopy{ cloud }; fromCloud(std::move(cloudCopy), maxLeafSize); }\r\n\r\nvoid PointCloudAcceleration::fromCloud(PointCloud &&cloud, std::size_t maxLeafSize)\r\n{\r\n    mData = std::make_shared<PointCloud>(std::move(cloud));\r\n\r\n    mIndex = std::make_shared<KdTree>(PointCloud::DATA_DIMENSIONALITY, *mData,\r\n        nanoflann::KDTreeSingleIndexAdaptorParams(maxLeafSize));\r\n    mIndex->buildIndex();\r\n}\r\n\r\nvoid PointCloudAcceleration::fromVertices(const std::vector<Vertex3D> &vertices, std::size_t maxLeafSize)\r\n{ std::vector<Vertex3D> vertexCopy{ vertices }; fromVertices(std::move(vertexCopy), maxLeafSize); }\r\n\r\nvoid PointCloudAcceleration::fromVertices(std::vector<Vertex3D> &&vertices, std::size_t maxLeafSize)\r\n{\r\n    if (!mData)\r\n    { mData = std::make_shared<PointCloud>( ); }\r\n\r\n    mData->points() = std::move(vertices);\r\n\r\n    mIndex = std::make_shared<KdTree>(PointCloud::DATA_DIMENSIONALITY, *mData,\r\n        nanoflann::KDTreeSingleIndexAdaptorParams(maxLeafSize));\r\n    mIndex->buildIndex();\r\n}\r\n\r\nvoid PointCloudAcceleration::fromVertices(const Vertex3D *vertices, std::size_t vertexCount,\r\n    std::size_t maxLeafSize)\r\n{\r\n    std::vector<Vertex3D> vertexCopy{ vertices, vertices + vertexCount };\r\n    fromVertices(std::move(vertexCopy), maxLeafSize);\r\n}\r\n\r\nPointCloudAcceleration::QueryResult PointCloudAcceleration::queryRange(const Vector3D &p,\r\n    float range, std::size_t maxNeighbors, bool sort) const\r\n{\r\n    QueryResult result{ };\r\n    nanoflann::SearchParams searchParams{ };\r\n    searchParams.sorted = sort;\r\n    const auto found{ mIndex->radiusSearch(&p[0], range * range, result.points, searchParams) };\r\n\r\n    if (maxNeighbors && found > maxNeighbors)\r\n    { result.points.resize(maxNeighbors); }\r\n\r\n    result.sorted = sort;\r\n    return result;\r\n}\r\n\r\nPointCloudAcceleration::QueryResult PointCloudAcceleration::queryKNN(const Vector3D &p,\r\n    std::size_t maxNeighbors) const\r\n{\r\n    QueryResult result{ };\r\n\r\n    std::vector<QueryResult::IndexT> indices{ };\r\n    indices.resize(maxNeighbors);\r\n    std::vector<QueryResult::DistanceT> distances{ };\r\n    distances.resize(maxNeighbors);\r\n    const auto found{ mIndex->knnSearch(&p[0], maxNeighbors, indices.data(), distances.data()) };\r\n\r\n    result.points.resize(found);\r\n    for (std::size_t iii = 0u; iii < found; ++iii)\r\n    { result.points[iii] = std::make_pair(indices[iii], distances[iii]); }\r\n\r\n    // TODO - Check it is actually sorted.\r\n    result.sorted = true;\r\n    return result;\r\n}\r\n\r\nPointCloudAcceleration::QueryResult PointCloudAcceleration::queryPosition(const Vector3D &p) const\r\n{ return queryKNN(p, 1u); }\r\n\r\nPointCloudAcceleration::LegacyKdTreePtr PointCloudAcceleration::toLegacyKdTree() const\r\n{\r\n    std::vector<kd::Vector3D> positions{ };\r\n    const auto vertexCount{ mData->points().size() };\r\n    positions.resize(vertexCount);\r\n    for (std::size_t iii = 0u; iii < vertexCount; ++iii)\r\n    { const auto &v{ mData->points()[iii] }; positions[iii] = { v.p.x, v.p.y, v.p.z }; }\r\n\r\n    return std::make_shared<LegacyKdTree>(positions.data(), positions.size(), mIndex->index_params.leaf_max_size);\r\n}\r\n\r\nnamespace impl\r\n{\r\n\r\nstruct TriangleIntersectorImpl\r\n{\r\n    /// @brief Scalar used for distances and inner operations.\r\n    using ScalarT = TriangleIntersector::ScalarT;\r\n    /// @brief Dimensionality of the accelerated space.\r\n    static constexpr auto Dimensionality{ 3u };\r\n\r\n    /// @brier Wrapper around acceleration object which includes index of the original primitive.\r\n    class AccelerationObject : public Eigen::AlignedBox<ScalarT, Dimensionality>\r\n    {\r\n    public:\r\n        /// Epsilon used when constructing loose bounding box.\r\n        static constexpr auto EPS{ std::numeric_limits<float>::epsilon() };\r\n\r\n        /// @brief Empty acceleration object.\r\n        inline AccelerationObject();\r\n\r\n        /// @brief Create the acceleration object with index to original primitive.\r\n        inline AccelerationObject(std::size_t primitiveIdx, const Vector3D &min, const Vector3D &max);\r\n\r\n        /// @brief Get reference to the original primitive.\r\n        inline TriangleIntersector::PrimitiveIdxT primitiveIdx() const;\r\n    private:\r\n        /// Index to the original primitive.\r\n        std::size_t mPrimitiveIdx{ };\r\n    protected:\r\n    }; // class AccelerationObject\r\n\r\n    /// @brief Object used in the acceleration structure nodes.\r\n    using AccelerationObjectT = AccelerationObject;\r\n\r\n    /// @brief Acceleration structure used for the operations.\r\n    using SpatialAcceleratorT = Eigen::KdBVH<ScalarT, Dimensionality, TriangleIntersector::PrimitiveT>;\r\n\r\n    /// @brief Type used for storing the list of currently accelerated primitives.\r\n    using PrimitiveStoreT = std::vector<TriangleIntersector::PrimitiveT>;\r\n    /// @brief Type used for storing the list of acceleration objects.\r\n    using AccelerationStoreT = std::vector<AccelerationObjectT>;\r\n\r\n    /// @brief Helper used for detecting volume intersections.\r\n    template <typename TargetT, typename VolumeT, typename AccelerationT>\r\n    struct VolumeIntersector;\r\n\r\n    /// @brief Helper used for detecting object intersections.\r\n    template <typename TargetT>\r\n    struct ObjectIntersector;\r\n\r\n    /// @brief Aggregator used for hit queries.\r\n    template <typename TargetT>\r\n    struct HitQueryAggregator;\r\n\r\n    /// @brief Aggregator used for nearest hit queries.\r\n    template <typename TargetT>\r\n    struct NearestQueryAggregator;\r\n\r\n    /// @brief Functor used for intersection queries.\r\n    template <typename TargetT, typename AggregatorT>\r\n    class IntersectQuery\r\n    {\r\n    public:\r\n        /// @brief Shortcut for the volume intersector type.\r\n        using VolumeIntersectorT = VolumeIntersector<TargetT,\r\n            SpatialAcceleratorT::Volume, TriangleIntersectorImpl::AccelerationObjectT>;\r\n        /// @brief Shortcut for the object intersector type.\r\n        using ObjectIntersectorT = ObjectIntersector<TargetT>;\r\n\r\n        /// @brief Initialize intersection query for given target. Set limit to non-zero to end after finding set amount of hits.\r\n        template <typename... AggCArgTs>\r\n        IntersectQuery(const TargetT &target, AggCArgTs... aggregatorArguments);\r\n\r\n        /// @brief Returns true if the volume intersects current query.\r\n        bool intersectVolume(const SpatialAcceleratorT::Volume &volume);\r\n        /// @brief Returns true if the search should end immediately.\r\n        bool intersectObject(const SpatialAcceleratorT::Object &object);\r\n\r\n        /// @brief Get result aggregator of the intersection query.\r\n        const AggregatorT &aggregator() const;\r\n        /// @brief Get queried target.\r\n        const TriangleIntersector::PrimitiveT &target() const;\r\n    private:\r\n        /// Target being queried.\r\n        TargetT mTarget{ };\r\n        /// Acceleration object of the target.\r\n        TriangleIntersectorImpl::AccelerationObjectT mAcceleration{ };\r\n        /// Aggregator of results.\r\n        AggregatorT mAggregator{ };\r\n    protected:\r\n    }; // class IntersectQuery\r\n\r\n    /// @brief Create acceleration object for given primitive, which is at provided index in the primitive array.\r\n    static AccelerationObjectT createAccelerationObject(const TriangleIntersector::PrimitiveT &primitive,\r\n        std::size_t idx = 0u);\r\n\r\n    /// @brief Create acceleration object for given point.\r\n    static AccelerationObjectT createAccelerationObject(const Vector3D &point);\r\n\r\n    /// @brief Create acceleration object for given ray.\r\n    static AccelerationObjectT createAccelerationObject(const Ray &ray);\r\n\r\n    /// @brief Build the acceleration structure for given list of primitives.\r\n    void buildAccelerator(const TriangleIntersector::PrimitiveSetT &primitives);\r\n\r\n    /// @brief Perform intersection query with given primitive against the built acceleration structure.\r\n    TriangleIntersector::IntersectResultT queryIntersect(const TriangleIntersector::PrimitiveT &primitive,\r\n        std::size_t limit = 0u) const;\r\n\r\n    /// @brief Perform intersection query for primitives which contain given point.\r\n    TriangleIntersector::IntersectResultT queryPoint(const Vector3D &point, std::size_t limit = 0u) const;\r\n\r\n    /// @brief Perform intersection query for primitives having intersection with given ray.\r\n    TriangleIntersector::IntersectResultT queryRay(const Ray &ray, std::size_t limit = 0u) const;\r\n\r\n    /// @brief Find nearest primitive intersection with given ray and return its index and distance.\r\n    TriangleIntersector::NearestIntersectResultT queryRayNearest(const Ray &ray) const;\r\n\r\n    /// Currently used acceleration structure.\r\n    std::unique_ptr<SpatialAcceleratorT> accelerator{ };\r\n\r\n    /// Primitives stored in the acceleration structure.\r\n    PrimitiveStoreT primitives{ };\r\n    /// Acceleration objects to the corresponding primitives.\r\n    AccelerationStoreT accelerations{ };\r\n}; // struct TriangleIntersectorImpl\r\n\r\ninline TriangleIntersectorImpl::AccelerationObject::AccelerationObject()\r\n{ /* Automatic */ }\r\n\r\ninline TriangleIntersectorImpl::AccelerationObject::AccelerationObject(\r\n    std::size_t primitiveIdx, const Vector3D &min, const Vector3D &max) :\r\n    AlignedBox(\r\n        VectorType{ min.x - EPS, min.y - EPS, min.z - EPS },\r\n        VectorType{ max.x + EPS, max.y + EPS, max.z + EPS }),\r\n    mPrimitiveIdx{ primitiveIdx }\r\n{ }\r\n\r\ninline TriangleIntersector::PrimitiveIdxT TriangleIntersectorImpl::AccelerationObject::primitiveIdx() const\r\n{ return mPrimitiveIdx; }\r\n\r\ntemplate <typename TargetT, typename VolumeT, typename AccelerationT>\r\nstruct TriangleIntersectorImpl::VolumeIntersector\r\n{\r\n    /// @brief Check intersection of given target and its acceleration agains the volume.\r\n    static bool intersectVolume(const TargetT &target, const VolumeT &volume, const AccelerationT &acceleration);\r\n}; // struct VolumeIntersector\r\n\r\ntemplate <typename TargetT, typename VolumeT, typename AccelerationT>\r\nbool TriangleIntersectorImpl::VolumeIntersector<TargetT, VolumeT, AccelerationT>::intersectVolume(\r\n    const TargetT &target, const VolumeT &volume, const AccelerationT &acceleration)\r\n{ return volume.intersects(acceleration); }\r\n\r\ntemplate <typename VolumeT, typename AccelerationT>\r\nstruct TriangleIntersectorImpl::VolumeIntersector<Ray, VolumeT, AccelerationT>\r\n{\r\n    /// @brief Check intersection of given target and its acceleration agains the volume.\r\n    static bool intersectVolume(const Ray &target, const VolumeT &volume, const AccelerationT &acceleration);\r\n}; // struct VolumeIntersector\r\n\r\ntemplate <typename VolumeT, typename AccelerationT>\r\nbool TriangleIntersectorImpl::VolumeIntersector<Ray, VolumeT, AccelerationT>::intersectVolume(\r\n    const Ray &target, const VolumeT &volume, const AccelerationT &acceleration)\r\n{\r\n    // Perform ray-aabb intersection test.\r\n    const auto min{ volume.corner(SpatialAcceleratorT::Volume::BottomLeftFloor) };\r\n    const auto max{ volume.corner(SpatialAcceleratorT::Volume::TopRightCeil) };\r\n    BoundingBox3D bb({ min.x(), min.y(), min.z() }, { max.x(), max.y(), max.z() });\r\n\r\n    return bb.intersects(target);\r\n}\r\n\r\ntemplate <typename TargetT>\r\nstruct TriangleIntersectorImpl::ObjectIntersector\r\n{\r\n    /// @brief Perform intersection test and fill members.\r\n    ObjectIntersector(const TargetT &target, const SpatialAcceleratorT::Object &object);\r\n\r\n    /// Distance of the intersection point.\r\n    ScalarT distance{ TriangleIntersector::InvalidScalar };\r\n    /// Does the object intersect target?\r\n    bool intersects{ false };\r\n    /// Index of the object.\r\n    TriangleIntersector::PrimitiveIdxT objectIdx{ TriangleIntersector::InvalidPrimitiveIdx };\r\n}; // struct ObjectIntersector\r\n\r\ntemplate <>\r\nTriangleIntersectorImpl::ObjectIntersector<TriangleIntersector::PrimitiveT>::ObjectIntersector(\r\n    const TriangleIntersector::PrimitiveT &target, const SpatialAcceleratorT::Object &object)\r\n{ distance = 0.0f; intersects = target.intersects(object); objectIdx = object.tIdx; }\r\n\r\ntemplate <>\r\nTriangleIntersectorImpl::ObjectIntersector<Vector3D>::ObjectIntersector(\r\n    const Vector3D &target, const SpatialAcceleratorT::Object &object)\r\n{ distance = 0.0f; intersects = object.contains(target); objectIdx = object.tIdx; }\r\n\r\ntemplate <>\r\nTriangleIntersectorImpl::ObjectIntersector<Ray>::ObjectIntersector(\r\n    const Ray &target, const SpatialAcceleratorT::Object &object)\r\n{ distance = object.intersection(target); intersects = distance < TriangleIntersector::InvalidScalar; objectIdx = object.tIdx; }\r\n\r\ntemplate <typename TargetT>\r\nstruct TriangleIntersectorImpl::HitQueryAggregator\r\n{\r\n    /// @brief Aggregate results up to given limit. Set to zero for unlimited results.\r\n    HitQueryAggregator(std::size_t resultLimit = 0u) :\r\n        limit{ resultLimit }\r\n    { }\r\n\r\n    /// @brief Check intersection with given object and return whether to quit.\r\n    bool checkAddFull(const ObjectIntersector<TargetT> &intersector);\r\n\r\n    /// @brief Limiti of the number of results.\r\n    std::size_t limit{ 0u };\r\n    /// @brief List of results.\r\n    std::vector<TriangleIntersector::PrimitiveIdxT> results{ };\r\n}; // struct HitQueryAggregator\r\n\r\ntemplate <typename TargetT>\r\nbool TriangleIntersectorImpl::HitQueryAggregator<TargetT>::checkAddFull(\r\n    const ObjectIntersector<TargetT> &intersector)\r\n{\r\n    if (intersector.intersects)\r\n    { // Found intersecting triangle -> Add it to the list.\r\n        results.push_back(intersector.objectIdx);\r\n    }\r\n\r\n    // Returns true only when we have found requested number of hits.\r\n    return (limit > 0u) ? (results.size() >= limit) : false;\r\n}\r\n\r\n/// @brief Aggregator used for nearest hit queries.\r\ntemplate <typename TargetT>\r\nstruct TriangleIntersectorImpl::NearestQueryAggregator\r\n{\r\n    /// @brief Aggregate results up to given limit. Set to zero for unlimited results.\r\n    NearestQueryAggregator()\r\n    { }\r\n\r\n    /// @brief Check intersection with given object and return whether to quit.\r\n    bool checkAddFull(const ObjectIntersector<TargetT> &intersector);\r\n\r\n    /// @brief Distance of the currently nearest result.\r\n    ScalarT distance{ TriangleIntersector::InvalidScalar };\r\n    /// @brief Index of the currently nearest result.\r\n    TriangleIntersector::PrimitiveIdxT nearestIdx{ TriangleIntersector::InvalidPrimitiveIdx };\r\n}; // struct NearestQueryAggregator\r\n\r\ntemplate <typename TargetT>\r\nbool TriangleIntersectorImpl::NearestQueryAggregator<TargetT>::checkAddFull(\r\n    const ObjectIntersector<TargetT> &intersector)\r\n{\r\n    const auto intersectionDistance{ intersector.distance };\r\n    if (intersectionDistance < distance && intersectionDistance > ScalarT(0) && intersector.intersects)\r\n    { // Found new nearest -> remember its index and distance.\r\n        nearestIdx = intersector.objectIdx;\r\n        distance = intersectionDistance;\r\n    }\r\n\r\n    // Never full, we need to check all possibilities.\r\n    return false;\r\n}\r\n\r\ntemplate <typename TargetT, typename AggregatorT>\r\ntemplate <typename... AggCArgTs>\r\nTriangleIntersectorImpl::IntersectQuery<TargetT, AggregatorT>::IntersectQuery(\r\n    const TargetT &target, AggCArgTs... aggregatorArguments) :\r\n    mTarget{ target }, mAcceleration{ createAccelerationObject(target) },\r\n    mAggregator(std::forward<AggCArgTs>(aggregatorArguments)...)\r\n{ }\r\n\r\ntemplate <typename TargetT, typename AggregatorT>\r\nbool TriangleIntersectorImpl::IntersectQuery<TargetT, AggregatorT>::intersectVolume(\r\n    const SpatialAcceleratorT::Volume &volume)\r\n{\r\n    // Go down to the leafs and find all potential intersections.\r\n    return VolumeIntersectorT::intersectVolume(mTarget, volume, mAcceleration);\r\n}\r\n\r\ntemplate <typename TargetT, typename AggregatorT>\r\nbool TriangleIntersectorImpl::IntersectQuery<TargetT, AggregatorT>::intersectObject(\r\n    const SpatialAcceleratorT::Object &object)\r\n{ return mAggregator.checkAddFull(ObjectIntersector(mTarget, object)); }\r\n\r\ntemplate <typename TargetT, typename AggregatorT>\r\nconst AggregatorT &TriangleIntersectorImpl::IntersectQuery<TargetT, AggregatorT>::aggregator() const\r\n{ return mAggregator; }\r\ntemplate <typename TargetT, typename AggregatorT>\r\nconst TriangleIntersector::PrimitiveT &TriangleIntersectorImpl::IntersectQuery<TargetT, AggregatorT>::target() const\r\n{ return mTarget; }\r\n\r\nTriangleIntersectorImpl::AccelerationObjectT TriangleIntersectorImpl::createAccelerationObject(\r\n    const TriangleIntersector::PrimitiveT &primitive, std::size_t idx)\r\n{\r\n    const auto aabb{ primitive.aabb() };\r\n    return AccelerationObjectT(idx, aabb.min, aabb.max);\r\n}\r\n\r\nTriangleIntersectorImpl::AccelerationObjectT TriangleIntersectorImpl::createAccelerationObject(const Vector3D &point)\r\n{ return AccelerationObjectT(0u, point, point); }\r\n\r\nTriangleIntersectorImpl::AccelerationObjectT TriangleIntersectorImpl::createAccelerationObject(const Ray &ray)\r\n{\r\n    // Create binding box extending to infinity.\r\n    const auto firstCorner{ ray.origin };\r\n    const auto secondCorner{ ray.direction.sgn() * Vector3D::maxVector() };\r\n    return AccelerationObjectT(0u,\r\n        Vector3D::elementMin(firstCorner, secondCorner),\r\n        Vector3D::elementMax(firstCorner, secondCorner));\r\n}\r\n\r\nvoid TriangleIntersectorImpl::buildAccelerator(const TriangleIntersector::PrimitiveSetT &p)\r\n{\r\n    const auto primitiveCount{ p.size() };\r\n\r\n    // Switch to new primitives.\r\n    primitives = p;\r\n    accelerations.resize(primitiveCount);\r\n\r\n    // Re-calculate acceleration objects.\r\n    for (std::size_t iii = 0u; iii < accelerations.size(); ++iii)\r\n    { accelerations[iii] = createAccelerationObject(primitives[iii], iii); }\r\n\r\n    // Create the accelerator.\r\n    accelerator = std::make_unique<SpatialAcceleratorT>(\r\n        primitives.begin(), primitives.end(), accelerations.begin(), accelerations.end());\r\n}\r\n\r\nTriangleIntersector::IntersectResultT TriangleIntersectorImpl::queryIntersect(\r\n    const TriangleIntersector::PrimitiveT &primitive, std::size_t limit) const\r\n{\r\n    if (!accelerator)\r\n    { return { }; }\r\n\r\n    using TargetT = TriangleIntersector::PrimitiveT;\r\n    IntersectQuery<TargetT, HitQueryAggregator<TargetT>> query(primitive, limit);\r\n    Eigen::BVIntersect(*accelerator, query);\r\n\r\n    return query.aggregator().results;\r\n}\r\n\r\nTriangleIntersector::IntersectResultT TriangleIntersectorImpl::queryPoint(\r\n    const Vector3D &point, std::size_t limit) const\r\n{\r\n    if (!accelerator)\r\n    { return { }; }\r\n\r\n    using TargetT = Vector3D;\r\n    IntersectQuery<TargetT, HitQueryAggregator<TargetT>> query(point, limit);\r\n    Eigen::BVIntersect(*accelerator, query);\r\n\r\n    return query.aggregator().results;\r\n}\r\n\r\nTriangleIntersector::IntersectResultT TriangleIntersectorImpl::queryRay(\r\n    const Ray &ray, std::size_t limit) const\r\n{\r\n    if (!accelerator)\r\n    { return { }; }\r\n\r\n    using TargetT = Ray;\r\n    IntersectQuery<TargetT, HitQueryAggregator<TargetT>> query(ray, limit);\r\n    Eigen::BVIntersect(*accelerator, query);\r\n\r\n    return query.aggregator().results;\r\n}\r\n\r\nTriangleIntersector::NearestIntersectResultT TriangleIntersectorImpl::queryRayNearest( const Ray &ray) const\r\n{\r\n    if (!accelerator)\r\n    { return { }; }\r\n\r\n    using TargetT = Ray;\r\n    IntersectQuery<TargetT, NearestQueryAggregator<TargetT>> query(ray);\r\n    Eigen::BVIntersect(*accelerator, query);\r\n\r\n    return { query.aggregator().nearestIdx, query.aggregator().distance };\r\n}\r\n\r\n} // namespace impl\r\n\r\nTriangleIntersector::TriangleIntersector() :\r\n    TriangleIntersector(PrimitiveSetT{ })\r\n{ }\r\n\r\nTriangleIntersector::~TriangleIntersector()\r\n{ /* Automatic */ }\r\n\r\nTriangleIntersector::TriangleIntersector(const PrimitiveSetT &primitives)\r\n{ create(primitives); }\r\n\r\nvoid TriangleIntersector::create(const PrimitiveSetT &primitives)\r\n{\r\n    mImpl = std::make_unique<impl::TriangleIntersectorImpl>();\r\n    mImpl->buildAccelerator(primitives);\r\n}\r\n\r\nconst TriangleIntersector::PrimitiveSetT &TriangleIntersector::primitives() const\r\n{ return mImpl->primitives; }\r\n\r\nTriangleIntersector::IntersectResultT TriangleIntersector::queryIntersect(\r\n    const PrimitiveT &primitive, std::size_t limit) const\r\n{ return mImpl ? mImpl->queryIntersect(primitive, limit) : IntersectResultT{ }; }\r\n\r\nTriangleIntersector::IntersectResultT TriangleIntersector::queryPoint(\r\n    const Vector3D &point, std::size_t limit) const\r\n{ return mImpl ? mImpl->queryPoint(point, limit) : IntersectResultT{ }; }\r\n\r\nTriangleIntersector::IntersectResultT TriangleIntersector::queryRay(\r\n    const Vector3D &origin, const Vector3D &direction, std::size_t limit) const\r\n{ return mImpl ? mImpl->queryRay(Ray{ origin, direction }, limit) : IntersectResultT{ }; }\r\n\r\nTriangleIntersector::NearestIntersectResultT TriangleIntersector::queryRayNearest(\r\n    const Vector3D &origin, const Vector3D &direction) const\r\n{ return mImpl ? mImpl->queryRayNearest(Ray{ origin, direction }) : InvalidIdxDistance; }\r\n\r\nTriangleIntersector::NearestIntersectResultT TriangleIntersector::checkOcclusion(\r\n    const Vector3D &first, const Vector3D &second) const\r\n{\r\n    const auto rayOrigin{ first };\r\n    const auto rayDirection{ second - first };\r\n    const auto rayDirectionNorm{ rayDirection.normalized() };\r\n    const auto distance{ rayDirection.length() };\r\n    const auto nearestQuery{ queryRayNearest(rayOrigin, rayDirectionNorm) };\r\n\r\n    return (nearestQuery.second <= (distance + std::numeric_limits<ScalarT>::epsilon())) ? nearestQuery : InvalidIdxDistance;\r\n}\r\n\r\n} // namespace treeacc\r\n\r\n", "meta": {"hexsha": "5a7a80e18aafdfafe3d5c9dafbf7ac15fda84c3d", "size": 21717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TreeIOAcceleration/src/TreeIO/impl/TreeIOAcceleration.cpp", "max_stars_repo_name": "PolasekT/ICTree", "max_stars_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T22:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T13:40:44.000Z", "max_issues_repo_path": "TreeIOAcceleration/src/TreeIO/impl/TreeIOAcceleration.cpp", "max_issues_repo_name": "PolasekT/ICTree", "max_issues_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TreeIOAcceleration/src/TreeIO/impl/TreeIOAcceleration.cpp", "max_forks_repo_name": "PolasekT/ICTree", "max_forks_repo_head_hexsha": "d13ad603101805bcc288411504ecffd6f2e1f365", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-09T22:37:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:38:39.000Z", "avg_line_length": 41.0529300567, "max_line_length": 130, "alphanum_fraction": 0.7268038864, "num_tokens": 4892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.0769608351667528, "lm_q1q2_score": 0.03667796796934013}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006 Joseph Wang\n Copyright (C) 2010 Liquidnet Holdings, Inc.\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 timeseries.hpp\n    \\brief Container for historical data\n*/\n\n#ifndef quantlib_timeseries_hpp\n#define quantlib_timeseries_hpp\n\n#include <ql/time/date.hpp>\n#include <ql/utilities/null.hpp>\n#include <ql/errors.hpp>\n#include <ql/functional.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/reverse_iterator.hpp>\n#include <boost/utility.hpp>\n#include <map>\n#include <vector>\n\nnamespace QuantLib {\n\n    //! Container for historical data\n    /*! This class acts as a generic repository for a set of\n        historical data.  Any single datum can be accessed through its\n        date, while sets of consecutive data can be accessed through\n        iterators.\n\n        \\pre The <c>Container</c> type must satisfy the requirements\n             set by the C++ standard for associative containers.\n    */\n    template <class T, class Container = std::map<Date, T> >\n    class TimeSeries {\n      public:\n        typedef Date key_type;\n        typedef T value_type;\n      private:\n        mutable Container values_;\n      public:\n        /*! Default constructor */\n        TimeSeries() {}\n        /*! This constructor initializes the history with a set of\n            values passed as two sequences, the first containing dates\n            and the second containing corresponding values.\n        */\n        template <class DateIterator, class ValueIterator>\n        TimeSeries(DateIterator dBegin, DateIterator dEnd,\n                   ValueIterator vBegin) {\n            while (dBegin != dEnd)\n                values_[*(dBegin++)] = *(vBegin++);\n        }\n        /*! This constructor initializes the history with a set of\n            values. Such values are assigned to a corresponding number\n            of consecutive dates starting from <b><i>firstDate</i></b>\n            included.\n        */\n        template <class ValueIterator>\n        TimeSeries(const Date& firstDate,\n                   ValueIterator begin, ValueIterator end) {\n            Date d = firstDate;\n            while (begin != end)\n                values_[d++] = *(begin++);\n        }\n        //! \\name Inspectors\n        //@{\n        //! returns the first date for which a historical datum exists\n        Date firstDate() const;\n        //! returns the last date for which a historical datum exists\n        Date lastDate() const;\n        //! returns the number of historical data including null ones\n        Size size() const;\n        //! returns whether the series contains any data\n        bool empty() const;\n        //@}\n        //! \\name Historical data access\n        //@{\n        //! returns the (possibly null) datum corresponding to the given date\n        T operator[](const Date& d) const {\n            if (values_.find(d) != values_.end())\n                return values_[d];\n            else\n                return Null<T>();\n        }\n        T& operator[](const Date& d) {\n            if (values_.find(d) == values_.end())\n                values_[d] = Null<T>();\n            return values_[d];\n        }\n        //@}\n\n        //! \\name Iterators\n        //@{\n        typedef typename Container::const_iterator const_iterator;\n        typedef typename const_iterator::iterator_category iterator_category;\n\n        // Reverse iterators\n        // The following class makes compilation fail for the code\n        // that calls rbegin or rend with a container that does not\n        // support reverse iterators.  All the rest TimeSeries class\n        // features should compile and work for this type of\n        // containers.\n        template <class container, class iterator_category>\n        struct reverse {\n            typedef boost::reverse_iterator<typename container::const_iterator>\n                                                       const_reverse_iterator;\n            reverse(const container& c) : c_(c) {}\n            const_reverse_iterator rbegin() const {\n                return const_reverse_iterator(c_.end());\n            }\n            const_reverse_iterator rend() const {\n                return const_reverse_iterator(c_.begin());\n            }\n            const container& c_;\n        };\n\n        // This class defines reverse iterator features via\n        // container's native calls.\n        template <class container>\n        struct reverse<container, std::bidirectional_iterator_tag> {\n            typedef typename container::const_reverse_iterator\n                                                       const_reverse_iterator;\n            reverse(const container& c) : c_(c) {}\n            const_reverse_iterator rbegin() const { return c_.rbegin(); }\n            const_reverse_iterator rend() const { return c_.rend(); }\n            const container& c_;\n        };\n\n        // The following typedef enables reverse iterators for\n        // bidirectional_iterator_tag category.\n        typedef typename boost::mpl::if_ <\n            boost::mpl::or_ <\n                boost::is_same<iterator_category,\n                               std::bidirectional_iterator_tag>,\n                boost::is_base_of<std::bidirectional_iterator_tag,\n                                  iterator_category> >,\n            std::bidirectional_iterator_tag, \n            std::input_iterator_tag>::type enable_reverse;\n\n        typedef typename\n        reverse<Container, enable_reverse>::const_reverse_iterator\n                                                       const_reverse_iterator;\n\n        const_iterator cbegin() const;\n        const_iterator cend() const;\n        const_iterator begin() const { return cbegin(); }\n        const_iterator end() const { return cend(); }\n        const_reverse_iterator crbegin() const {\n            return reverse<Container, enable_reverse>(values_).rbegin();\n        }\n        const_reverse_iterator crend() const {\n            return reverse<Container, enable_reverse>(values_).rend();\n        }\n        const_reverse_iterator rbegin() const { return crbegin(); }\n        const_reverse_iterator rend() const { return crend(); }\n        //@}\n\n      private:\n        typedef typename Container::value_type container_value_type;\n        typedef ext::function<Date(const container_value_type&)>\n                                                              projection_time;\n        typedef ext::function<T(const container_value_type&)>\n                                                             projection_value;\n\n      public:\n        //! \\name Projection iterators\n        //@{\n\n        typedef boost::transform_iterator<projection_time, const_iterator>\n                                                          const_time_iterator;\n        typedef boost::transform_iterator<projection_value, const_iterator>\n                                                         const_value_iterator;\n        typedef boost::transform_iterator<projection_time,\n                                          const_reverse_iterator>\n                                                  const_reverse_time_iterator;\n        typedef boost::transform_iterator<projection_value,\n                                          const_reverse_iterator>\n                                                 const_reverse_value_iterator;\n\n        const_value_iterator cbegin_values() const {\n            return const_value_iterator(cbegin(), get_value);\n        }\n        const_value_iterator cend_values() const {\n            return const_value_iterator(cend(), get_value);\n        }\n        const_reverse_value_iterator crbegin_values() const {\n            return const_reverse_value_iterator(crbegin(), get_value);\n        }\n        const_reverse_value_iterator crend_values() const {\n            return const_reverse_value_iterator(crend(), get_value);\n        }\n\n        const_time_iterator cbegin_time() const {\n            return const_time_iterator(cbegin(), get_time);\n        }\n        const_time_iterator cend_time() const {\n            return const_time_iterator(cend(), get_time);\n        }\n        const_reverse_time_iterator crbegin_time() const {\n            return const_reverse_time_iterator(crbegin(), get_time);\n        }\n        const_reverse_time_iterator crend_time() const {\n            return const_reverse_time_iterator(crend(), get_time);\n        }\n\n        //! \\name Utilities\n        //@{\n        const_iterator find(const Date&);\n        //! returns the dates for which historical data exist\n        std::vector<Date> dates() const;\n        //! returns the historical data\n        std::vector<T> values() const;\n        //@}\n\n      private:\n        static const Date& get_time (const container_value_type& v) {\n            return v.first;\n        }\n        static const T& get_value (const container_value_type& v) {\n            return v.second;\n        }\n    };\n\n\n    // inline definitions\n\n    template <class T, class C>\n    inline Date TimeSeries<T,C>::firstDate() const {\n        QL_REQUIRE(!values_.empty(), \"empty timeseries\");\n        return values_.begin()->first;\n    }\n\n    template <class T, class C>\n    inline Date TimeSeries<T,C>::lastDate() const {\n        QL_REQUIRE(!values_.empty(), \"empty timeseries\");\n        return rbegin()->first;\n    }\n\n    template <class T, class C>\n    inline Size TimeSeries<T,C>::size() const {\n        return values_.size();\n    }\n\n    template <class T, class C>\n    inline bool TimeSeries<T,C>::empty() const {\n        return values_.empty();\n    }\n\n    template <class T, class C>\n    inline typename TimeSeries<T,C>::const_iterator\n    TimeSeries<T,C>::cbegin() const {\n        return values_.begin();\n    }\n\n    template <class T, class C>\n    inline typename TimeSeries<T,C>::const_iterator\n    TimeSeries<T,C>::cend() const {\n        return values_.end();\n    }\n\n    template <class T, class C>\n    inline typename TimeSeries<T,C>::const_iterator\n    TimeSeries<T,C>::find(const Date& d) {\n        const_iterator i = values_.find(d);\n        if (i == values_.end()) {\n            values_[d] = Null<T>();\n            i = values_.find(d);\n        }\n        return i;\n    }\n\n    template <class T, class C>\n    std::vector<Date> TimeSeries<T,C>::dates() const {\n        std::vector<Date> v;\n        v.reserve(size());\n        std::transform(cbegin(), cend(), std::back_inserter(v),\n                       TimeSeries<T,C>::get_time);\n        return v;\n    }\n\n    template <class T, class C>\n    std::vector<T> TimeSeries<T,C>::values() const {\n        std::vector<T> v;\n        v.reserve(size());\n        std::transform(cbegin(), cend(), std::back_inserter(v),\n                       TimeSeries<T,C>::get_value);\n        return v;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "f3137404764933f224928c973db152499278bf49", "size": 11385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/timeseries.hpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T01:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T17:44:12.000Z", "max_issues_repo_path": "ql/timeseries.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/timeseries.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 36.8446601942, "max_line_length": 79, "alphanum_fraction": 0.5891084761, "num_tokens": 2224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167302036300954, "lm_q2_score": 0.08269733702314093, "lm_q1q2_score": 0.036525182618988385}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2007 Joel de Guzman\n\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n///////////////////////////////////////////////////////////////////////////////\n//\n//  A Roman Numerals Parser (demonstrating the symbol table). This is\n//  discussed in the \"Symbols\" chapter in the Spirit User's Guide.\n//\n//  [ JDG August 22, 2002 ] spirit1\n//  [ JDG March 13, 2007 ]  spirit2\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n\n#include <iostream>\n#include <string>\n\nusing namespace boost::spirit;\nusing namespace boost::spirit::qi;\nusing namespace boost::spirit::ascii;\nusing namespace boost::spirit::arg_names;\nusing boost::phoenix::ref;\n\n///////////////////////////////////////////////////////////////////////////////\n//  Parse roman hundreds (100..900) numerals using the symbol table.\n//  Notice that the data associated with each slot is the parser's attribute\n//  (which is passed to attached semantic actions).\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_hundreds\nstruct hundreds_ : symbols<char, unsigned>\n{\n    hundreds_()\n    {\n        add\n            (\"C\"    , 100)\n            (\"CC\"   , 200)\n            (\"CCC\"  , 300)\n            (\"CD\"   , 400)\n            (\"D\"    , 500)\n            (\"DC\"   , 600)\n            (\"DCC\"  , 700)\n            (\"DCCC\" , 800)\n            (\"CM\"   , 900)\n        ;\n    }\n\n} hundreds;\n//]\n\n///////////////////////////////////////////////////////////////////////////////\n//  Parse roman tens (10..90) numerals using the symbol table.\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_tens\nstruct tens_ : symbols<char, unsigned>\n{\n    tens_()\n    {\n        add\n            (\"X\"    , 10)\n            (\"XX\"   , 20)\n            (\"XXX\"  , 30)\n            (\"XL\"   , 40)\n            (\"L\"    , 50)\n            (\"LX\"   , 60)\n            (\"LXX\"  , 70)\n            (\"LXXX\" , 80)\n            (\"XC\"   , 90)\n        ;\n    }\n\n} tens;\n//]\n\n///////////////////////////////////////////////////////////////////////////////\n//  Parse roman ones (1..9) numerals using the symbol table.\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_ones\nstruct ones_ : symbols<char, unsigned>\n{\n    ones_()\n    {\n        add\n            (\"I\"    , 1)\n            (\"II\"   , 2)\n            (\"III\"  , 3)\n            (\"IV\"   , 4)\n            (\"V\"    , 5)\n            (\"VI\"   , 6)\n            (\"VII\"  , 7)\n            (\"VIII\" , 8)\n            (\"IX\"   , 9)\n        ;\n    }\n\n} ones;\n//]\n\n///////////////////////////////////////////////////////////////////////////////\n//  roman (numerals) grammar\n//\n//      Note the use of the || operator. The expression\n//      a || b reads match a or b and in sequence. Try\n//      defining the roman numerals grammar in YACC or\n//      PCCTS. Spirit rules! :-)\n///////////////////////////////////////////////////////////////////////////////\n//[tutorial_roman_grammar\ntemplate <typename Iterator>\nstruct roman : grammar<Iterator, unsigned()>\n{\n    roman() : roman::base_type(start)\n    {\n        start = eps             [_val = 0] >>\n            (\n                +char_('M')     [_val += 1000]\n                ||  hundreds    [_val += _1]\n                ||  tens        [_val += _1]\n                ||  ones        [_val += _1]\n            )\n        ;\n    }\n\n    rule<Iterator, unsigned()> start;\n};\n//]\n\n///////////////////////////////////////////////////////////////////////////////\n//  Main program\n///////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"\\t\\tRoman Numerals Parser\\n\\n\";\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"Type a Roman Numeral ...or [q or Q] to quit\\n\\n\";\n\n    typedef std::string::const_iterator iterator_type;\n    typedef roman<iterator_type> roman;\n\n    roman roman_parser; // Our grammar\n\n    std::string str;\n    unsigned result;\n    while (std::getline(std::cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        std::string::const_iterator iter = str.begin();\n        std::string::const_iterator end = str.end();\n        //[tutorial_roman_grammar_parse\n        bool r = parse(iter, end, roman_parser, result);\n\n        if (r && iter == end)\n        {\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing succeeded\\n\";\n            std::cout << \"result = \" << result << std::endl;\n            std::cout << \"-------------------------\\n\";\n        }\n        else\n        {\n            std::string rest(iter, end);\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing failed\\n\";\n            std::cout << \"stopped at: \\\": \" << rest << \"\\\"\\n\";\n            std::cout << \"-------------------------\\n\";\n        }\n        //]\n    }\n\n    std::cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "33e3fb9af1250465a134098d39aa2cdafdc9e46c", "size": 5457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/spirit/example/qi/roman.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T17:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T17:17:41.000Z", "max_issues_repo_path": "libs/spirit/example/qi/roman.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/spirit/example/qi/roman.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 29.8196721311, "max_line_length": 81, "alphanum_fraction": 0.3730987722, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.08269735002250668, "lm_q1q2_score": 0.036206844367556675}}
{"text": "/* Boost interval/utility.hpp template implementation file\r\n *\r\n * Copyright 2000 Jens Maurer\r\n * Copyright 2002-2003 Herv� Br�nnimann, Guillaume Melquiond, Sylvain Pion\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_INTERVAL_UTILITY_HPP\r\n#define BOOST_NUMERIC_INTERVAL_UTILITY_HPP\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/numeric/interval/detail/interval_prototype.hpp>\r\n#include <boost/numeric/interval/detail/test_input.hpp>\r\n#include <boost/numeric/interval/detail/bugs.hpp>\r\n#include <algorithm>\r\n#include <utility>\r\n\r\n/*\r\n * Implementation of simple functions\r\n */\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\n\r\n/*\r\n * Utility Functions\r\n */\r\n\r\ntemplate<class T, class Policies> inline\r\nconst T& lower(const interval<T, Policies>& x)\r\n{\r\n  return x.lower();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nconst T& upper(const interval<T, Policies>& x)\r\n{\r\n  return x.upper();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nT checked_lower(const interval<T, Policies>& x)\r\n{\r\n  if (empty(x)) {\r\n    typedef typename Policies::checking checking;\r\n    return checking::nan();\r\n  }\r\n  return x.lower();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nT checked_upper(const interval<T, Policies>& x)\r\n{\r\n  if (empty(x)) {\r\n    typedef typename Policies::checking checking;\r\n    return checking::nan();\r\n  }\r\n  return x.upper();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nT width(const interval<T, Policies>& x)\r\n{\r\n  if (interval_lib::detail::test_input(x)) return static_cast<T>(0);\r\n  typename Policies::rounding rnd;\r\n  return rnd.sub_up(x.upper(), x.lower());\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nT median(const interval<T, Policies>& x)\r\n{\r\n  if (interval_lib::detail::test_input(x)) {\r\n    typedef typename Policies::checking checking;\r\n    return checking::nan();\r\n  }\r\n  typename Policies::rounding rnd;\r\n  return rnd.median(x.lower(), x.upper());\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> widen(const interval<T, Policies>& x, const T& v)\r\n{\r\n  if (interval_lib::detail::test_input(x))\r\n    return interval<T, Policies>::empty();\r\n  typename Policies::rounding rnd;\r\n  return interval<T, Policies>(rnd.sub_down(x.lower(), v),\r\n                               rnd.add_up  (x.upper(), v), true);\r\n}\r\n\r\n/*\r\n * Set-like operations\r\n */\r\n\r\ntemplate<class T, class Policies> inline\r\nbool empty(const interval<T, Policies>& x)\r\n{\r\n  return interval_lib::detail::test_input(x);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nbool zero_in(const interval<T, Policies>& x)\r\n{\r\n  if (interval_lib::detail::test_input(x)) return false;\r\n  return (!interval_lib::user::is_pos(x.lower())) &&\r\n         (!interval_lib::user::is_neg(x.upper()));\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nbool in_zero(const interval<T, Policies>& x) // DEPRECATED\r\n{\r\n  return zero_in<T, Policies>(x);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nbool in(const T& x, const interval<T, Policies>& y)\r\n{\r\n  if (interval_lib::detail::test_input(x, y)) return false;\r\n  return y.lower() <= x && x <= y.upper();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nbool subset(const interval<T, Policies>& x,\r\n            const interval<T, Policies>& y)\r\n{\r\n  if (empty(x)) return true;\r\n  return !empty(y) && y.lower() <= x.lower() && x.upper() <= y.upper();\r\n}\r\n\r\ntemplate<class T, class Policies1, class Policies2> inline\r\nbool proper_subset(const interval<T, Policies1>& x,\r\n                   const interval<T, Policies2>& y)\r\n{\r\n  if (empty(y)) return false;\r\n  if (empty(x)) return true;\r\n  return y.lower() <= x.lower() && x.upper() <= y.upper() &&\r\n         (y.lower() != x.lower() || x.upper() != y.upper());\r\n}\r\n\r\ntemplate<class T, class Policies1, class Policies2> inline\r\nbool overlap(const interval<T, Policies1>& x,\r\n             const interval<T, Policies2>& y)\r\n{\r\n  if (interval_lib::detail::test_input(x, y)) return false;\r\n  return (x.lower() <= y.lower() && y.lower() <= x.upper()) ||\r\n         (y.lower() <= x.lower() && x.lower() <= y.upper());\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nbool singleton(const interval<T, Policies>& x)\r\n{\r\n return !empty(x) && x.lower() == x.upper();\r\n}\r\n\r\ntemplate<class T, class Policies1, class Policies2> inline\r\nbool equal(const interval<T, Policies1>& x, const interval<T, Policies2>& y)\r\n{\r\n  if (empty(x)) return empty(y);\r\n  return !empty(y) && x.lower() == y.lower() && x.upper() == y.upper();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> intersect(const interval<T, Policies>& x,\r\n                                const interval<T, Policies>& y)\r\n{\r\n  BOOST_USING_STD_MIN();\r\n  BOOST_USING_STD_MAX();\r\n  if (interval_lib::detail::test_input(x, y))\r\n    return interval<T, Policies>::empty();\r\n  const T& l = max BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower());\r\n  const T& u = min BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper());\r\n  if (l <= u) return interval<T, Policies>(l, u, true);\r\n  else        return interval<T, Policies>::empty();\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> hull(const interval<T, Policies>& x,\r\n                           const interval<T, Policies>& y)\r\n{\r\n  BOOST_USING_STD_MIN();\r\n  BOOST_USING_STD_MAX();\r\n  bool bad_x = interval_lib::detail::test_input(x);\r\n  bool bad_y = interval_lib::detail::test_input(y);\r\n  if (bad_x)\r\n    if (bad_y) return interval<T, Policies>::empty();\r\n    else       return y;\r\n  else\r\n    if (bad_y) return x;\r\n  return interval<T, Policies>(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower()),\r\n                               max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper()), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> hull(const interval<T, Policies>& x, const T& y)\r\n{\r\n  BOOST_USING_STD_MIN();\r\n  BOOST_USING_STD_MAX();\r\n  bool bad_x = interval_lib::detail::test_input(x);\r\n  bool bad_y = interval_lib::detail::test_input<T, Policies>(y);\r\n  if (bad_y)\r\n    if (bad_x) return interval<T, Policies>::empty();\r\n    else       return x;\r\n  else\r\n    if (bad_x) return interval<T, Policies>(y, y, true);\r\n  return interval<T, Policies>(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y),\r\n                               max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> hull(const T& x, const interval<T, Policies>& y)\r\n{\r\n  BOOST_USING_STD_MIN();\r\n  BOOST_USING_STD_MAX();\r\n  bool bad_x = interval_lib::detail::test_input<T, Policies>(x);\r\n  bool bad_y = interval_lib::detail::test_input(y);\r\n  if (bad_x)\r\n    if (bad_y) return interval<T, Policies>::empty();\r\n    else       return y;\r\n  else\r\n    if (bad_y) return interval<T, Policies>(x, x, true);\r\n  return interval<T, Policies>(min BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.lower()),\r\n                               max BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.upper()), true);\r\n}\r\n\r\ntemplate<class T> inline\r\ninterval<T> hull(const T& x, const T& y)\r\n{\r\n  return interval<T>::hull(x, y);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\nstd::pair<interval<T, Policies>, interval<T, Policies> >\r\nbisect(const interval<T, Policies>& x)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x))\r\n    return std::pair<I,I>(I::empty(), I::empty());\r\n  const T m = median(x);\r\n  return std::pair<I,I>(I(x.lower(), m, true), I(m, x.upper(), true));\r\n}\r\n\r\n/*\r\n * Elementary functions\r\n */\r\n\r\ntemplate<class T, class Policies> inline\r\nT norm(const interval<T, Policies>& x)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x)) {\r\n    typedef typename Policies::checking checking;\r\n    return checking::nan();\r\n  }\r\n  BOOST_USING_STD_MAX();\r\n  return max BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<T>(-x.lower()), x.upper());\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> abs(const interval<T, Policies>& x)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x))\r\n    return I::empty();\r\n  if (!interval_lib::user::is_neg(x.lower())) return x;\r\n  if (!interval_lib::user::is_pos(x.upper())) return -x;\r\n  BOOST_USING_STD_MAX();\r\n  return I(static_cast<T>(0), max BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<T>(-x.lower()), x.upper()), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> max BOOST_PREVENT_MACRO_SUBSTITUTION (const interval<T, Policies>& x,\r\n                                                            const interval<T, Policies>& y)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x, y))\r\n    return I::empty();\r\n  BOOST_USING_STD_MAX();\r\n  return I(max BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower()), max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper()), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> max BOOST_PREVENT_MACRO_SUBSTITUTION (const interval<T, Policies>& x, const T& y)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x, y))\r\n    return I::empty();\r\n  BOOST_USING_STD_MAX();\r\n  return I(max BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y), max BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> max BOOST_PREVENT_MACRO_SUBSTITUTION (const T& x, const interval<T, Policies>& y)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x, y))\r\n    return I::empty();\r\n  BOOST_USING_STD_MAX();\r\n  return I(max BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.lower()), max BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.upper()), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> min BOOST_PREVENT_MACRO_SUBSTITUTION (const interval<T, Policies>& x,\r\n                                                            const interval<T, Policies>& y)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x, y))\r\n    return I::empty();\r\n  BOOST_USING_STD_MIN();\r\n  return I(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y.lower()), min BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y.upper()), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> min BOOST_PREVENT_MACRO_SUBSTITUTION (const interval<T, Policies>& x, const T& y)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x, y))\r\n    return I::empty();\r\n  BOOST_USING_STD_MIN();\r\n  return I(min BOOST_PREVENT_MACRO_SUBSTITUTION(x.lower(), y), min BOOST_PREVENT_MACRO_SUBSTITUTION(x.upper(), y), true);\r\n}\r\n\r\ntemplate<class T, class Policies> inline\r\ninterval<T, Policies> min BOOST_PREVENT_MACRO_SUBSTITUTION (const T& x, const interval<T, Policies>& y)\r\n{\r\n  typedef interval<T, Policies> I;\r\n  if (interval_lib::detail::test_input(x, y))\r\n    return I::empty();\r\n  BOOST_USING_STD_MIN();\r\n  return I(min BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.lower()), min BOOST_PREVENT_MACRO_SUBSTITUTION(x, y.upper()), true);\r\n}\r\n\r\n} // namespace numeric\r\n} // namespace boost\r\n\r\n#endif // BOOST_NUMERIC_INTERVAL_UTILITY_HPP\r\n", "meta": {"hexsha": "cbd12bae3d28e67badaad058c508537fc1c3c963", "size": 11153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/interval/utility.hpp", "max_stars_repo_name": "lucasaugustscode/veroo-delivery-app", "max_stars_repo_head_hexsha": "a1653525b77ac66c8dfc971163c75a731998a652", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T16:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:17:40.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/interval/utility.hpp", "max_issues_repo_name": "lucasaugustscode/veroo-delivery-app", "max_issues_repo_head_hexsha": "a1653525b77ac66c8dfc971163c75a731998a652", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/interval/utility.hpp", "max_forks_repo_name": "lucasaugustscode/veroo-delivery-app", "max_forks_repo_head_hexsha": "a1653525b77ac66c8dfc971163c75a731998a652", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-09T02:53:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T03:32:31.000Z", "avg_line_length": 32.9970414201, "max_line_length": 138, "alphanum_fraction": 0.6626019905, "num_tokens": 2715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.0815197598797173, "lm_q1q2_score": 0.03600507736713329}}
{"text": "\n// Copyright (c) 2021, University of Colorado Denver. All rights reserved.\n//\n// This file is part of <T>LAPACK.\n// <T>LAPACK is free software: you can redistribute it and/or modify it under\n// the terms of the BSD 3-Clause license. See the accompanying LICENSE file.\n\n#ifndef __TLAPACK_EIGEN_HH__\n#define __TLAPACK_EIGEN_HH__\n\n#include <Eigen/Core>\n#include <type_traits>\n\nnamespace blas{\n\n    // // -----------------------------------------------------------------------------\n    // // is_EigenBlock\n    \n    // template< class >\n    // struct is_EigenBlock : public std::false_type {};\n\n    // template< typename T, int R, int C, bool P >\n    // struct is_EigenBlock< Eigen::Block<T,R,C,P> > : public std::true_type {};\n\n    // -----------------------------------------------------------------------------\n    // Data traits for Eigen\n\n    #ifndef TBLAS_ARRAY_TRAITS\n        #define TBLAS_ARRAY_TRAITS\n\n        // Data type\n        template< class T > struct type_trait {};\n        template< class T >\n        using type_t = typename type_trait< T >::type;\n\n        // Size type\n        template< class T > struct sizet_trait {};\n        template< class T >\n        using size_type = typename sizet_trait< T >::type;\n\n    #endif // TBLAS_ARRAY_TRAITS\n\n    // Data type\n    template<typename Scalar_, int Rows_, int Cols_, int Options_, int MaxRows_, int MaxCols_>\n    struct type_trait< Eigen::Matrix<Scalar_, Rows_, Cols_, Options_, MaxRows_, MaxCols_> > {\n        using type = Scalar_;\n    };\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    struct type_trait< Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel> > {\n        using type = typename XprType::Scalar;\n    };\n    template<class T>\n    struct type_trait< Eigen::VectorBlock<T> > {\n        using type = typename T::Scalar;\n    };\n    template<class T, int idx>\n    struct type_trait< Eigen::Diagonal<T,idx> > {\n        using type = typename T::Scalar;\n    };\n\n    // Size type\n    template<typename Scalar_, int Rows_, int Cols_, int Options_, int MaxRows_, int MaxCols_>\n    struct sizet_trait< Eigen::Matrix<Scalar_, Rows_, Cols_, Options_, MaxRows_, MaxCols_> > {\n        using type = Eigen::Index;\n    };\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    struct sizet_trait< Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel> > {\n        using type = Eigen::Index;\n    };\n    template<class T>\n    struct sizet_trait< Eigen::VectorBlock<T> > {\n        using type = Eigen::Index;\n    };\n    template<class T, int idx>\n    struct sizet_trait< Eigen::Diagonal<T,idx> > {\n        using type = Eigen::Index;\n    };\n\n    // -----------------------------------------------------------------------------\n    // blas functions to access Eigen properties\n\n    // Size\n    template<class T>\n    inline constexpr auto\n    size( const Eigen::EigenBase<T>& x ) {\n        return x.size();\n    }\n    // Number of rows\n    template<class T>\n    inline constexpr auto\n    nrows( const Eigen::EigenBase<T>& x ) {\n        return x.rows();\n    }\n    // Number of columns\n    template<class T>\n    inline constexpr auto\n    ncols( const Eigen::EigenBase<T>& x ) {\n        return x.cols();\n    }\n\n    // -----------------------------------------------------------------------------\n    // blas functions to access Eigen block operations\n\n    // Submatrix\n    template<class T, typename SliceSpecRow, typename SliceSpecCol>\n    inline constexpr auto submatrix(\n        const Eigen::DenseBase<T>& A, SliceSpecRow&& rows, SliceSpecCol&& cols ) noexcept\n    {\n        return A.block( rows.first, cols.first,\n                        rows.second-rows.first, cols.second-cols.first );\n    }\n    template<class T, typename SliceSpecRow, typename SliceSpecCol>\n    inline constexpr auto submatrix(\n        Eigen::DenseBase<T>& A, SliceSpecRow&& rows, SliceSpecCol&& cols ) noexcept\n    {\n        return A.block( rows.first, cols.first,\n                        rows.second-rows.first, cols.second-cols.first );\n    }\n    template< typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n              typename SliceSpecRow, typename SliceSpecCol >\n    inline constexpr auto submatrix(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A,\n        SliceSpecRow&& rows, SliceSpecCol&& cols ) noexcept\n    {\n        return A.block( rows.first, cols.first,\n                        rows.second-rows.first, cols.second-cols.first );\n    }\n\n    // Rows\n    template<class T, typename SliceSpec>\n    inline constexpr auto rows(\n        const Eigen::DenseBase<T>& A, SliceSpec&& rows ) noexcept\n    {\n        return A.middleRows( rows.first, rows.second-rows.first );\n    }\n    template<class T, typename SliceSpec>\n    inline constexpr auto rows(\n        Eigen::DenseBase<T>& A, SliceSpec&& rows ) noexcept\n    {\n        return A.middleRows( rows.first, rows.second-rows.first );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n             typename SliceSpec>\n    inline constexpr auto rows(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, SliceSpec&& rows ) noexcept\n    {\n        return A.middleRows( rows.first, rows.second-rows.first );\n    }\n\n    // Row\n    template<class T>\n    inline constexpr auto row( const Eigen::DenseBase<T>& A, Eigen::Index rowIdx ) noexcept\n    {\n        return A.row( rowIdx );\n    }\n    template<class T>\n    inline constexpr auto row( Eigen::DenseBase<T>& A, Eigen::Index rowIdx ) noexcept\n    {\n        return A.row( rowIdx );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    inline constexpr auto row(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, Eigen::Index rowIdx ) noexcept\n    {\n        return A.row( rowIdx );\n    }\n\n    // Cols\n    template<class T, typename SliceSpec>\n    inline constexpr auto cols(\n        const Eigen::DenseBase<T>& A, SliceSpec&& cols ) noexcept\n    {\n        return A.middleCols( cols.first, cols.second-cols.first );\n    }\n    template<class T, typename SliceSpec>\n    inline constexpr auto cols(\n        Eigen::DenseBase<T>& A, SliceSpec&& cols ) noexcept\n    {\n        return A.middleCols( cols.first, cols.second-cols.first );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel,\n             typename SliceSpec>\n    inline constexpr auto cols(\n        Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, SliceSpec&& cols ) noexcept\n    {\n        return A.middleCols( cols.first, cols.second-cols.first );\n    }\n\n    // Column\n    template<class T>\n    inline constexpr auto col( const Eigen::DenseBase<T>& A, Eigen::Index colIdx ) noexcept\n    {\n        return A.col( colIdx );\n    }\n    template<class T>\n    inline constexpr auto col( Eigen::DenseBase<T>& A, Eigen::Index colIdx ) noexcept\n    {\n        return A.col( colIdx );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>\n    inline constexpr auto col( Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, Eigen::Index colIdx ) noexcept\n    {\n        return A.col( colIdx );\n    }\n\n    // Subvector\n    template<class T, typename SliceSpec>\n    inline constexpr auto subvector( const Eigen::DenseBase<T>& v, SliceSpec&& rows ) noexcept\n    {\n        return v.segment( rows.first, rows.second-rows.first );\n    }\n    template<class T, typename SliceSpec>\n    inline constexpr auto subvector( Eigen::DenseBase<T>& v, SliceSpec&& rows ) noexcept\n    {\n        return v.segment( rows.first, rows.second-rows.first );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel, typename SliceSpec>\n    inline constexpr auto subvector( Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& v, SliceSpec&& rows ) noexcept\n    {\n        return v.segment( rows.first, rows.second-rows.first );\n    }\n\n    // Diagonal\n    template<class T>\n    inline constexpr auto diag( const Eigen::MatrixBase<T>& A, int diagIdx = 0 ) noexcept\n    {\n        return A.diagonal( diagIdx );\n    }\n    template<class T>\n    inline constexpr auto diag( Eigen::MatrixBase<T>& A, int diagIdx = 0 ) noexcept\n    {\n        return A.diagonal( diagIdx );\n    }\n    template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel, typename SliceSpec>\n    inline constexpr auto diag( Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>&& A, int diagIdx = 0 ) noexcept\n    {\n        return A.diagonal( diagIdx );\n    }\n\n} // namespace blas\n\nnamespace lapack {\n    \n    using blas::type_trait;\n    using blas::sizet_trait;\n\n    using blas::size;\n    using blas::nrows;\n    using blas::ncols;\n\n    using blas::submatrix;\n    using blas::rows;\n    using blas::row;\n    using blas::cols;\n    using blas::col;\n    using blas::subvector;\n    using blas::diag;\n\n} // namespace lapack\n\n#endif // __TLAPACK_EIGEN_HH__", "meta": {"hexsha": "e870e2b37da08de0274c73fa7768818803e5f8c5", "size": 8872, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/plugins/tlapack_eigen.hpp", "max_stars_repo_name": "rileyjmurray/tlapack", "max_stars_repo_head_hexsha": "640dc35a2eb0748b3c094efda8187a9e0b6a5762", "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/plugins/tlapack_eigen.hpp", "max_issues_repo_name": "rileyjmurray/tlapack", "max_issues_repo_head_hexsha": "640dc35a2eb0748b3c094efda8187a9e0b6a5762", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/plugins/tlapack_eigen.hpp", "max_forks_repo_name": "rileyjmurray/tlapack", "max_forks_repo_head_hexsha": "640dc35a2eb0748b3c094efda8187a9e0b6a5762", "max_forks_repo_licenses": ["BSD-3-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.9923371648, "max_line_length": 125, "alphanum_fraction": 0.6203787196, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.08632347834919092, "lm_q1q2_score": 0.0358155102831848}}
{"text": "// This file is part of the dune-xt project:\n//   https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt\n// Copyright 2009-2021 dune-xt 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 (2014 - 2017, 2020)\n//   René Fritze     (2014 - 2020)\n//   Tim Keil        (2018)\n//   Tobias Leibner  (2014, 2016 - 2020)\n\n#ifndef DUNE_XT_COMMON_FVECTOR_26_HH\n#define DUNE_XT_COMMON_FVECTOR_26_HH\n\n#include <functional>\n#include <initializer_list>\n#include <numeric>\n#include <type_traits>\n#include <vector>\n\n#include <boost/functional/hash.hpp>\n\n#include <dune/common/fvector.hh>\n#include <dune/common/fmatrix.hh>\n#include <dune/common/promotiontraits.hh>\n\n#include <dune/xt/common/debug.hh>\n#include <dune/xt/common/densevector.hh>\n#include <dune/xt/common/exceptions.hh>\n#include <dune/xt/common/float_cmp.hh>\n#include <dune/xt/common/numeric.hh>\n#include <dune/xt/common/type_traits.hh>\n#include <dune/xt/common/vector.hh>\n\nnamespace Dune {\nnamespace XT::Common {\n\n\n/**\n * \\todo We need to implement all operators from the base which return the base, to rather return ourselfes!\n */\ntemplate <class K, int SIZE>\nclass FieldVector : public Dune::FieldVector<K, SIZE>\n{\n  static_assert(SIZE >= 0, \"Really?\");\n\n  using BaseType = Dune::FieldVector<K, SIZE>;\n  using ThisType = FieldVector<K, SIZE>;\n\npublic:\n  FieldVector(const K& kk = suitable_default<K>::value())\n    : BaseType(kk)\n  {}\n\n  FieldVector(const ThisType& other) = default;\n\n  FieldVector(const BaseType& other)\n    : BaseType(other)\n  {}\n\n  /* FieldMatrix< K, 1, 1 > is convertible to K, which in turn is convertible to FieldVector< K, 1 >. Without the\n   * following constructor, this leads to an \"ambiguous constructor\" error (candidates are copy constructor and\n   * constructor taking a K) */\n  template <class Type = K>\n  FieldVector(const typename std::enable_if<SIZE == 1 && std::is_same<K, Type>::value,\n                                            typename Dune::FieldMatrix<K, 1, 1>>::type& mat)\n    : BaseType(mat[0][0])\n  {}\n\n  FieldVector(const std::vector<K>& vec)\n    : BaseType()\n  {\n#ifndef NDEBUG\n    if (vec.size() != SIZE)\n      DUNE_THROW(Exceptions::wrong_input_given,\n                 \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \"\n                                                                    << \"static size) from a vector of size \"\n                                                                    << vec.size() << \"!\");\n#endif // NDEBUG\n    for (size_t ii = 0; ii < SIZE; ++ii)\n      this->operator[](ii) = vec[ii];\n  } // FieldVector(...)\n\n  FieldVector(std::initializer_list<K> list)\n    : BaseType()\n  {\n#ifndef NDEBUG\n    if (list.size() != SIZE)\n      DUNE_THROW(Exceptions::wrong_input_given,\n                 \"You are trying to construct a FieldVector< ..., \" << SIZE << \" > (of \"\n                                                                    << \"static size) from a list of size \"\n                                                                    << list.size() << \"!\");\n#endif // NDEBUG\n    size_t ii = 0;\n    for (auto element : list)\n      this->operator[](ii++) = element;\n  } // FieldVector(...)\n\n  template <class C>\n  FieldVector(\n      const DenseVector<C>& x,\n      typename std::enable_if<IsFieldVectorSizeCorrect<C, SIZE>::value\n                              && std::is_convertible<typename DenseVector<C>::value_type, K>::value>::type* /*dummy*/\n      = nullptr)\n    : BaseType(x)\n  {}\n\n  operator std::vector<K>() const\n  {\n    std::vector<K> ret(SIZE);\n    for (size_t ii = 0; ii < SIZE; ++ii)\n      ret[ii] = this->operator[](ii);\n    return ret;\n  }\n\n  operator Dune::FieldMatrix<K, 1, SIZE>() const\n  {\n    Dune::FieldMatrix<K, 1, SIZE> ret;\n    ret[0] = *this;\n    return ret;\n  }\n\n  template <int S = SIZE>\n  operator typename std::enable_if<(S == SIZE) && (SIZE != 1), Dune::FieldMatrix<K, S, 1>>::type() const\n  {\n    Dune::FieldMatrix<K, SIZE, 1> ret;\n    for (size_t ii = 0; ii < SIZE; ++ii)\n      ret[ii][0] = this->operator[](ii);\n    return ret;\n  }\n\n  operator std::array<K, SIZE>() const\n  {\n    std::array<K, SIZE> ret;\n    for (size_t ii = 0; ii < SIZE; ++ii)\n      ret[ii] = this->operator[](ii);\n    return ret;\n  }\n\n  template <class K_Other>\n  typename multiplication_promotion<K, K_Other>::type operator*(const Dune::FieldVector<K_Other, SIZE>& other) const\n  {\n    typename multiplication_promotion<K, K_Other>::type result(0.);\n    for (size_t ii = 0; ii < SIZE; ++ii)\n      result += (*this)[ii] * other[ii];\n    return result;\n  }\n\n  template <int R>\n  typename std::enable_if<SIZE != 1 && R == SIZE, K>::type operator*(const Dune::FieldMatrix<K, R, 1>& mat) const\n  {\n    K ret = 0;\n    for (size_t ii = 0; ii < SIZE; ++ii)\n      ret += (*this)[ii] * mat[ii][0];\n    return ret;\n  }\n\n  //! This op is not redundant\n  ThisType operator*(const K& scalar) const\n  {\n    ThisType ret(*this);\n    ret *= scalar;\n    return ret;\n  }\n\n  ThisType operator/(const K& scalar) const\n  {\n    ThisType ret(*this);\n    ret /= scalar;\n    return ret;\n  }\n}; // class FieldVector\n\n\ntemplate <class K, size_t block_num, size_t size_block>\nclass BlockedFieldVector\n{\n  using ThisType = BlockedFieldVector;\n\npublic:\n  static constexpr size_t num_blocks = block_num;\n  static constexpr size_t block_size = size_block;\n  static constexpr size_t static_size = num_blocks * block_size;\n  using VectorType = Dune::FieldVector<K, static_size>;\n  using XtVectorType = FieldVector<K, static_size>;\n  using BlockType = FieldVector<K, block_size>;\n\n  BlockedFieldVector(const K& val = K(0.))\n    : backend_(BlockType(val))\n  {}\n\n  template <class OtherVectorType>\n  BlockedFieldVector(const OtherVectorType& other,\n                     std::enable_if_t<is_vector<OtherVectorType>::value, int> /*dummy*/ = 0)\n  {\n    *this = other;\n  }\n\n  BlockedFieldVector(const BlockType& block)\n    : backend_(block)\n  {}\n\n  BlockedFieldVector(const std::initializer_list<K>& init_list)\n  {\n    assert(init_list.size() == static_size || init_list.size() == num_blocks);\n    if (init_list.size() == static_size) {\n      *this = VectorType(init_list);\n    } else {\n      size_t jj = 0;\n      for (const auto& block_init : init_list)\n        block(jj++) = block_init;\n    }\n  }\n\n  template <class OtherVectorType>\n  std::enable_if_t<is_vector<OtherVectorType>::value, ThisType>& operator=(const OtherVectorType& other)\n  {\n    assert(other.size() == static_size);\n    for (size_t jj = 0; jj < num_blocks; ++jj)\n      for (size_t ii = 0; ii < block_size; ++ii)\n        backend_[jj][ii] = other[jj * block_size + ii];\n    return *this;\n  }\n\n  size_t size() const\n  {\n    return static_size;\n  }\n\n  K& operator[](const size_t ii)\n  {\n    assert(ii < static_size);\n    return backend_[ii / block_size][ii % block_size];\n  }\n\n  const K& operator[](const size_t ii) const\n  {\n    assert(ii < static_size);\n    return backend_[ii / block_size][ii % block_size];\n  }\n\n  K& get_entry(const size_t jj, const size_t ii)\n  {\n    assert(jj < num_blocks);\n    assert(ii < block_size);\n    return backend_[jj][ii];\n  }\n\n  const K& get_entry(const size_t jj, const size_t ii) const\n  {\n    assert(jj < num_blocks);\n    assert(ii < block_size);\n    return backend_[jj][ii];\n  }\n\n  BlockType& block(const size_t jj)\n  {\n    assert(jj < num_blocks);\n    return backend_[jj];\n  }\n\n  const BlockType& block(const size_t jj) const\n  {\n    assert(jj < num_blocks);\n    return backend_[jj];\n  }\n\n  K one_norm() const\n  {\n    K ret(0);\n    for (const auto& block_vec : backend_)\n      for (const auto& entry : block_vec)\n        ret += std::abs(entry);\n    return ret;\n  }\n\n  K two_norm() const\n  {\n    return std::sqrt(two_norm2());\n  }\n\n  K two_norm2() const\n  {\n    K ret(0);\n    for (const auto& block_vec : backend_)\n      for (const auto& entry : block_vec)\n        ret += std::pow(entry, 2);\n    return ret;\n  }\n\n  operator XtVectorType() const\n  {\n    XtVectorType ret(0.);\n    for (size_t jj = 0; jj < num_blocks; ++jj)\n      for (size_t ii = 0; ii < block_size; ++ii)\n        ret[jj * block_size + ii] = backend_[jj][ii];\n    return ret;\n  }\n\n  K* data()\n  {\n    return &(backend_[0][0]);\n  }\n\n  const K* data() const\n  {\n    return &(backend_[0][0]);\n  }\n\n  K* begin()\n  {\n    return data();\n  }\n\n  const K* begin() const\n  {\n    return data();\n  }\n\n  K* end()\n  {\n    return &(backend_[num_blocks - 1][block_size]);\n  }\n\n  const K* end() const\n  {\n    return &(backend_[num_blocks - 1][block_size]);\n  }\n\n  ThisType& operator*=(const K& val)\n  {\n    for (size_t jj = 0; jj < num_blocks; ++jj)\n      backend_[jj] *= val;\n    return *this;\n  }\n\n  ThisType operator*(const K& val) const\n  {\n    auto ret = *this;\n    ret *= val;\n    return ret;\n  }\n\n  K operator*(const ThisType& other) const\n  {\n    return Common::transform_reduce(begin(), end(), other.begin(), 0.);\n  }\n\n  ThisType& operator+=(const ThisType& other)\n  {\n    backend_ += other.backend_;\n    return *this;\n  }\n\n  ThisType operator+(const ThisType& other) const\n  {\n    auto ret = *this;\n    ret += other;\n    return ret;\n  }\n\n  ThisType& operator-=(const ThisType& other)\n  {\n    backend_ -= other.backend_;\n    return *this;\n  }\n\n  ThisType operator-(const ThisType& other) const\n  {\n    auto ret = *this;\n    ret -= other;\n    return ret;\n  }\n\nprivate:\n  FieldVector<BlockType, num_blocks> backend_;\n};\n\n\n//! this allows to set the init value of the FieldVector at compile time\ntemplate <class K, int SIZE, K value>\nclass ValueInitFieldVector : public Dune::XT::Common::FieldVector<K, SIZE>\n{\n  using BaseType = Dune::XT::Common::FieldVector<K, SIZE>;\n\npublic:\n  ValueInitFieldVector()\n    : BaseType(value)\n  {}\n}; // class ValueInitFieldVector\n\n\n//! struct to be used as comparison function e.g. in a std::map<FieldVector<...>, ..., FieldVectorLess>\nstruct FieldVectorLess\n{\n  template <class FieldType, int dimDomain>\n  bool operator()(const Dune::FieldVector<FieldType, dimDomain>& a,\n                  const Dune::FieldVector<FieldType, dimDomain>& b) const\n  {\n    for (size_t dd = 0; dd < dimDomain; ++dd) {\n      if (a[dd] < b[dd])\n        return true;\n      if (a[dd] > b[dd])\n        return false;\n    }\n    return false;\n  }\n};\n\nstruct FieldVectorFloatLess\n{\n  template <class FieldType, int dimDomain>\n  bool operator()(const Dune::FieldVector<FieldType, dimDomain>& a,\n                  const Dune::FieldVector<FieldType, dimDomain>& b) const\n  {\n    for (size_t dd = 0; dd < dimDomain; ++dd) {\n      if (XT::Common::FloatCmp::lt(a[dd], b[dd]))\n        return true;\n      if (XT::Common::FloatCmp::gt(a[dd], b[dd]))\n        return false;\n    }\n    return false;\n  }\n};\n\n\n//! Specialization of VectorAbstraction for Dune::XT::Common::FieldVector\ntemplate <class K, int SIZE>\nstruct VectorAbstraction<Dune::XT::Common::FieldVector<K, SIZE>>\n  : public internal::VectorAbstractionBase<Dune::XT::Common::FieldVector<K, SIZE>, K>\n  , public internal::HasSubscriptOperatorForVectorAbstraction<Dune::XT::Common::FieldVector<K, SIZE>,\n                                                              typename Dune::FieldTraits<K>::field_type>\n{\n  static constexpr bool has_static_size = true;\n  static constexpr size_t static_size = SIZE;\n  static constexpr bool is_contiguous = true;\n\n  template <size_t SZ = SIZE, class Field = K>\n  using VectorTypeTemplate = Dune::XT::Common::FieldVector<Field, SZ>;\n\n  template <size_t SZ = SIZE>\n  static inline VectorTypeTemplate<SZ> create(const size_t sz, const K& val = suitable_default<K>::value())\n  {\n    if (sz != SZ)\n      DUNE_THROW(Exceptions::wrong_input_given,\n                 \"You are trying to construct a FieldVector< ..., \" << SZ << \" > (of \"\n                                                                    << \"static size) with \" << sz << \" elements!\");\n    return VectorTypeTemplate<SZ>(val);\n  }\n};\n\n\n//! Specialization of VectorAbstraction for Dune::XT::Common::BlockedFieldVector\ntemplate <class K, size_t num_blocks, size_t block_size>\nstruct VectorAbstraction<Dune::XT::Common::BlockedFieldVector<K, num_blocks, block_size>>\n  : public internal::VectorAbstractionBase<Dune::XT::Common::BlockedFieldVector<K, num_blocks, block_size>, K>\n  , public internal::HasSubscriptOperatorForVectorAbstraction<\n        Dune::XT::Common::BlockedFieldVector<K, num_blocks, block_size>,\n        typename Dune::FieldTraits<K>::field_type>\n{\n  using VectorType = Dune::XT::Common::BlockedFieldVector<K, num_blocks, block_size>;\n  static constexpr bool has_static_size = true;\n  static constexpr size_t static_size = VectorType::static_size;\n  static constexpr bool is_contiguous = true;\n\n  template <size_t SZ = static_size>\n  static inline VectorType create(const size_t sz, const K& val = suitable_default<K>::value())\n  {\n    static_assert(SZ == static_size, \"Creation of Vector with different size not implemented!\");\n    if (sz != SZ)\n      DUNE_THROW(Exceptions::wrong_input_given,\n                 \"You are trying to construct a FieldVector< ..., \" << SZ << \" > (of \"\n                                                                    << \"static size) with \" << sz << \" elements!\");\n    return VectorType(val);\n  }\n};\n\n\ntemplate <class V>\ntypename std::enable_if<\n    is_vector<V>::value && VectorAbstraction<V>::has_static_size,\n    std::unique_ptr<FieldVector<typename VectorAbstraction<V>::S, VectorAbstraction<V>::static_size>>>::type\nmake_field_container_ptr(const V& vec)\n{\n  auto ret = std::make_unique<FieldVector<typename VectorAbstraction<V>::S, VectorAbstraction<V>::static_size>>;\n  for (size_t ii = 0; ii < ret->size(); ++ii)\n    (*ret)[ii] = vec[ii];\n  return std::move(ret);\n}\n\n\ntemplate <class V>\ntypename std::enable_if<is_vector<V>::value && VectorAbstraction<V>::has_static_size,\n                        FieldVector<typename VectorAbstraction<V>::S, VectorAbstraction<V>::static_size>>::type\nmake_field_container(const V& vec)\n{\n  FieldVector<typename VectorAbstraction<V>::S, VectorAbstraction<V>::static_size> ret;\n  for (size_t ii = 0; ii < ret.size(); ++ii)\n    ret[ii] = vec[ii];\n  return ret;\n}\n\n\ntemplate <class K, int SIZE>\nFieldVector<K, SIZE> make_field_container(Dune::FieldVector<K, SIZE>&& vec)\n{\n  return std::move(vec);\n}\n\n\ntemplate <class K, int SIZE>\nFieldVector<K, SIZE> make_field_container(FieldVector<K, SIZE>&& vec)\n{\n  return std::move(vec);\n}\n\ntemplate <class K>\nFieldVector<K, 3> cross_product(const FieldVector<K, 3>& u, const FieldVector<K, 3>& v)\n{\n  FieldVector<K, 3> ret;\n  ret[0] = u[1] * v[2] - u[2] * v[1];\n  ret[1] = u[2] * v[0] - u[0] * v[2];\n  ret[2] = u[0] * v[1] - u[1] * v[0];\n  return ret;\n}\n\n\nnamespace internal {\n\n\n/**\n * Most likely, you do not want to use this class directly, but \\sa hstack instead.\n */\ntemplate <class K>\nstruct hstack_decay\n{\n  static_assert(is_arithmetic<K>::value);\n  using type = K;\n};\n\ntemplate <class K, int SIZE>\nstruct hstack_decay<Dune::FieldVector<K, SIZE>>\n{\n  using type = Dune::XT::Common::FieldVector<K, SIZE>;\n};\n\ntemplate <class K, int SIZE>\nstruct hstack_decay<const Dune::FieldVector<K, SIZE>&> : public hstack_decay<Dune::FieldVector<K, SIZE>>\n{};\n\ntemplate <class K, int SIZE>\nstruct hstack_decay<Dune::XT::Common::FieldVector<K, SIZE>> : public hstack_decay<Dune::FieldVector<K, SIZE>>\n{};\n\ntemplate <class K, int SIZE>\nstruct hstack_decay<const Dune::XT::Common::FieldVector<K, SIZE>&> : public hstack_decay<Dune::FieldVector<K, SIZE>>\n{};\n\n\n/**\n * Most likely, you do not want to use this, but \\sa hstack instead.\n */\ntemplate <class T>\nusing hstack_decay_t = typename hstack_decay<T>::type;\n\n\n/**\n * Most likely, you do not want to use this class directly, but \\sa hstack instead.\n */\ntemplate <class... Vectors>\nstruct hstack_helper;\n\ntemplate <class L, class R, class... Vectors>\nstruct hstack_helper<L, R, Vectors...>\n{\n  using type =\n      typename hstack_helper<typename hstack_helper<hstack_decay_t<L>, hstack_decay_t<R>>::type, Vectors...>::type;\n};\n\ntemplate <class K, int SIZE>\nstruct hstack_helper<Dune::FieldVector<K, SIZE>>\n{\n  using type = hstack_decay_t<Dune::FieldVector<K, SIZE>>;\n};\n\ntemplate <class K, int SIZE>\nstruct hstack_helper<Dune::XT::Common::FieldVector<K, SIZE>> : public hstack_helper<Dune::FieldVector<K, SIZE>>\n{};\n\ntemplate <class KL, class KR, int r>\nstruct hstack_helper<KL, Dune::FieldVector<KR, r>>\n{\n  using type = hstack_decay_t<Dune::FieldVector<typename PromotionTraits<KL, KR>::PromotedType, 1 + r>>;\n};\n\ntemplate <class KL, class KR, int r>\nstruct hstack_helper<KL, Dune::XT::Common::FieldVector<KR, r>> : public hstack_helper<KL, Dune::FieldVector<KR, r>>\n{};\n\ntemplate <class KL, int l, class KR>\nstruct hstack_helper<Dune::FieldVector<KL, l>, KR>\n{\n  using type = hstack_decay_t<Dune::FieldVector<typename PromotionTraits<KL, KR>::PromotedType, l + 1>>;\n};\n\ntemplate <class KL, int l, class KR>\nstruct hstack_helper<Dune::XT::Common::FieldVector<KL, l>, KR> : public hstack_helper<Dune::FieldVector<KL, l>, KR>\n{};\n\ntemplate <class KL, int l, class KR, int r>\nstruct hstack_helper<Dune::FieldVector<KL, l>, Dune::FieldVector<KR, r>>\n{\n  using type = hstack_decay_t<Dune::FieldVector<typename PromotionTraits<KL, KR>::PromotedType, l + r>>;\n};\n\ntemplate <class KL, int l, class KR, int r>\nstruct hstack_helper<Dune::XT::Common::FieldVector<KL, l>, Dune::FieldVector<KR, r>>\n  : public hstack_helper<Dune::FieldVector<KL, l>, Dune::FieldVector<KR, r>>\n{};\n\ntemplate <class KL, int l, class KR, int r>\nstruct hstack_helper<Dune::FieldVector<KL, l>, Dune::XT::Common::FieldVector<KR, r>>\n  : public hstack_helper<Dune::FieldVector<KL, l>, Dune::FieldVector<KR, r>>\n{};\n\ntemplate <class KL, int l, class KR, int r>\nstruct hstack_helper<Dune::XT::Common::FieldVector<KL, l>, Dune::XT::Common::FieldVector<KR, r>>\n  : public hstack_helper<Dune::FieldVector<KL, l>, Dune::FieldVector<KR, r>>\n{};\n\n// not sure why this is required, would've hoped the decay above would take care of it\ntemplate <class KL, int l, class KR, int r>\nstruct hstack_helper<Dune::FieldVector<KL, l>, const Dune::FieldVector<KR, r>&>\n  : public hstack_helper<Dune::FieldVector<KL, l>, Dune::FieldVector<KR, r>>\n{};\n\n// not sure why this is required, would've hoped the decay above would take care of it\ntemplate <class KL, int l, class KR, int r>\nstruct hstack_helper<Dune::FieldVector<KL, l>, const Dune::XT::Common::FieldVector<KR, r>&>\n  : public hstack_helper<Dune::FieldVector<KL, l>, Dune::FieldVector<KR, r>>\n{};\n\n\n} // namespace internal\n\n\n/// \\brief Specialization of \\sa hstack to stop the recursion.\ntemplate <class K, int SIZE>\nDune::XT::Common::FieldVector<K, SIZE> hstack(Dune::FieldVector<K, SIZE>&& vec)\n{\n  return std::move(vec);\n}\n\n/// \\brief Specialization of \\sa hstack to stop the recursion.\ntemplate <class K, int SIZE>\nDune::XT::Common::FieldVector<K, SIZE> hstack(Dune::XT::Common::FieldVector<K, SIZE>&& vec)\n{\n  return std::move(vec);\n}\n\n/// \\brief Specialization of \\sa hstack to stop the recursion.\ntemplate <class K, int SIZE>\nDune::XT::Common::FieldVector<K, SIZE> hstack(const Dune::FieldVector<K, SIZE>& vec)\n{\n  return vec;\n}\n\n/// \\brief Specialization of \\sa hstack to stop the recursion.\ntemplate <class K, int SIZE>\nDune::XT::Common::FieldVector<K, SIZE> hstack(const Dune::XT::Common::FieldVector<K, SIZE>& vec)\n{\n  return vec;\n}\n\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, class KR, int r>\ntypename std::enable_if<\n    is_arithmetic<KL>::value && !is_field_vector<KL>::value,\n    typename internal::hstack_helper<internal::hstack_decay_t<KL>,\n                                     internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type>::type\nhstack(const KL& left, const Dune::FieldVector<KR, r>& right)\n{\n  typename internal::hstack_helper<internal::hstack_decay_t<KL>,\n                                   internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type ret;\n  ret[0] = left;\n  for (size_t ii = 0; ii < r; ++ii)\n    ret[ii + 1] = right[ii];\n  return ret;\n} // ... hstack<1, r>(...)\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, class KR, int r>\ntypename std::enable_if<\n    is_arithmetic<KL>::value && !is_field_vector<KL>::value,\n    typename internal::hstack_helper<internal::hstack_decay_t<KL>,\n                                     internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type>::type\nhstack(const KL& left, const Dune::XT::Common::FieldVector<KR, r>& right)\n{\n  return hstack(left, static_cast<const Dune::FieldVector<KR, r>&>(right));\n}\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, int l, class KR>\ntypename std::enable_if<is_arithmetic<KR>::value && !is_field_vector<KR>::value,\n                        typename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                                         internal::hstack_decay_t<KR>>::type>::type\nhstack(const Dune::FieldVector<KL, l>& left, const KR& right)\n{\n  typename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                   internal::hstack_decay_t<KR>>::type ret;\n  for (size_t ii = 0; ii < l; ++ii)\n    ret[ii] = left[ii];\n  ret[l] = right;\n  return ret;\n} // ... hstack<l, 1>(...)\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, int l, class KR>\ntypename std::enable_if<is_arithmetic<KR>::value && !is_field_vector<KR>::value,\n                        typename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                                         internal::hstack_decay_t<KR>>::type>::type\nhstack(const Dune::XT::Common::FieldVector<KL, l>& left, const KR& right)\n{\n  return hstack(static_cast<const Dune::FieldVector<KL, l>&>(left), right);\n}\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, int l, class KR, int r>\ntypename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                 internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type\nhstack(const Dune::FieldVector<KL, l>& left, const Dune::FieldVector<KR, r>& right)\n{\n  typename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                   internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type ret;\n  size_t ii = 0;\n  for (size_t jj = 0; jj < l; ++jj, ++ii)\n    ret[ii] = left[jj];\n  for (size_t jj = 0; jj < r; ++jj, ++ii)\n    ret[ii] = right[jj];\n  return ret;\n} // ... hstack<l, r>(...)\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, int l, class KR, int r>\ntypename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                 internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type\nhstack(const Dune::XT::Common::FieldVector<KL, l>& left, const Dune::FieldVector<KR, r>& right)\n{\n  return hstack(static_cast<const Dune::FieldVector<KL, l>&>(left), right);\n}\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, int l, class KR, int r>\ntypename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                 internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type\nhstack(const Dune::FieldVector<KL, l>& left, const Dune::XT::Common::FieldVector<KR, r>& right)\n{\n  return hstack(left, static_cast<const Dune::FieldVector<KR, r>&>(right));\n}\n\n/// \\brief Specialization of \\sa hstack for two arguments.\ntemplate <class KL, int l, class KR, int r>\ntypename internal::hstack_helper<internal::hstack_decay_t<Dune::FieldVector<KL, l>>,\n                                 internal::hstack_decay_t<Dune::FieldVector<KR, r>>>::type\nhstack(const Dune::XT::Common::FieldVector<KL, l>& left, const Dune::XT::Common::FieldVector<KR, r>& right)\n{\n  return hstack(static_cast<const Dune::FieldVector<KL, l>&>(left),\n                static_cast<const Dune::FieldVector<KR, r>&>(right));\n}\n\n\n/**\n * \\brief Stacks an arbitrary number of numbers and FieldVectors horizontally into one appropriate FieldVector.\n * \\note  At least one argument must be a FieldVector!\n */\ntemplate <class L, class R, class... Vectors>\ntypename std::enable_if<\n    is_field_vector<L>::value || is_field_vector<R>::value,\n    typename internal::hstack_helper<internal::hstack_decay_t<L>, internal::hstack_decay_t<R>, Vectors...>::type>::type\nhstack(const L& left, const R& right, Vectors&&... vectors)\n{\n  return hstack(hstack(left, right), std::forward<Vectors>(vectors)...);\n}\n\n\n} // namespace XT::Common\n\n\ntemplate <class K, int SIZE>\ntypename std::enable_if<SIZE != 1, K>::type operator*(const Dune::FieldVector<K, SIZE>& vec,\n                                                      const Dune::FieldMatrix<K, SIZE, 1>& mat)\n{\n  K ret = 0;\n  for (size_t ii = 0; ii < SIZE; ++ii)\n    ret += vec[ii] * mat[ii][0];\n  return ret;\n}\n\ntemplate <class K, int SIZE>\nstruct FieldTraits<XT::Common::FieldVector<K, SIZE>>\n{\n  using field_type = typename FieldTraits<K>::field_type;\n  using real_type = typename FieldTraits<K>::real_type;\n};\n\n\n} // namespace Dune\nnamespace std {\n\n\n/**\n * \\sa http://en.cppreference.com/w/cpp/utility/hash\n * \\sa http://www.boost.org/doc/libs/1_55_0/doc/html/hash/combine.html\n */\ntemplate <class K, int SIZE>\nstruct hash<Dune::FieldVector<K, SIZE>>\n{\n  using argument_type = Dune::FieldVector<K, SIZE>;\n  using result_type = std::size_t;\n\n  result_type operator()(argument_type const& s) const noexcept\n  {\n    std::size_t seed = 0;\n    for (size_t ii = 0; ii < s.size(); ++ii)\n      boost::hash_combine(seed, s[ii]);\n    return seed;\n  }\n}; // struct hash<Dune::FieldVector<...>>\n\n\n/**\n * \\sa http://en.cppreference.com/w/cpp/utility/hash\n * \\sa http://www.boost.org/doc/libs/1_55_0/doc/html/hash/combine.html\n */\ntemplate <class K, int SIZE>\nstruct hash<Dune::XT::Common::FieldVector<K, SIZE>>\n{\n  using argument_type = Dune::XT::Common::FieldVector<K, SIZE>;\n  using result_type = std::size_t;\n\n  result_type operator()(argument_type const& s) const noexcept\n  {\n    std::size_t seed = 0;\n    for (size_t ii = 0; ii < s.size(); ++ii)\n      boost::hash_combine(seed, s[ii]);\n    return seed;\n  }\n}; // struct hash<Dune::XT::Common::FieldVector<...>>\n\n\n} // namespace std\n\n#endif // DUNE_XT_COMMON_FVECTOR_26_HH\n", "meta": {"hexsha": "abce38b54e8f6cfb501349841113a39d05473e8c", "size": 26403, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/xt/common/fvector-2.6.hh", "max_stars_repo_name": "dune-community/dune-xt", "max_stars_repo_head_hexsha": "da921524c6fff8d60c715cb4849a0bdd5f020d2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T04:08:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-01T18:54:14.000Z", "max_issues_repo_path": "dune/xt/common/fvector-2.6.hh", "max_issues_repo_name": "dune-community/dune-xt", "max_issues_repo_head_hexsha": "da921524c6fff8d60c715cb4849a0bdd5f020d2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-19T12:06:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T08:20:39.000Z", "max_forks_repo_path": "dune/xt/common/fvector-2.6.hh", "max_forks_repo_name": "dune-community/dune-xt", "max_forks_repo_head_hexsha": "da921524c6fff8d60c715cb4849a0bdd5f020d2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T04:09:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:09:34.000Z", "avg_line_length": 30.8446261682, "max_line_length": 119, "alphanum_fraction": 0.6437904784, "num_tokens": 7294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.08389039270915707, "lm_q1q2_score": 0.035764284596281885}}
{"text": "/* This file is part of libtrevisan, a modular implementation of\n   Trevisan's randomness extraction construction.\n\n   Copyright (C) 2011-2012, Wolfgang Mauerer <wm@linux-kernel.net>\n\n   This program is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License\n   as published by the Free Software Foundation; either version 2\n   of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with libtrevisan. If not, see <http://www.gnu.org/licenses/>. */\n\n// Generate a list of precomputed irreducible polynomials\n\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#include <NTL/tools.h>\n#include <cstring>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <inttypes.h>\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"CumffaTypes.h\"\n\nNTL_CLIENT\n\nunsigned int field_sizes[] = {8192, 16382};\n\nvoid convertCharArrayToIntArray( unsigned char* s_value, ufixn* t_value, int num_chars ) {\n  \n  int offset = 0;\n  \n  if(num_chars == 0)\n    return;\n    \n  int highest_block_idx = (num_chars-1)/8;\n  double j=highest_block_idx+1-0.125;\n  \n  for(int i=num_chars-1; i>=0; --i) {\n    t_value[(int)j] += ((ufixn)s_value[i] << offset);\n    \n    offset = (offset + 8) % 64;\n    j-=0.125;\n  }\n}\n\nvoid clearArray( ufixn* array, int size ) {\n  for(int i=0; i<size; ++i) {\n    array[i] = 0;\n  }\n}\n\nvoid printbincharpad(unsigned char* ca, unsigned int n)\n{\n  for(int j=0; j<n; j++) {\n    char c = ca[j];\n      for (int i = 7; i >= 0; --i)\n      {\n          putchar( (c & (1 << i)) ? '1' : '0' );\n      }\n      putchar(' ');\n  }\n  putchar('\\n');\n}\n\nvoid printbincharpad(int* ca, unsigned int n)\n{\n  for(int j=0; j<n; j++) {\n    int c = ca[j];\n      for (int i = 31; i >= 0; --i)\n      {\n          putchar( (c & (1 << i)) ? '1' : '0' );\n      }\n      putchar(' ');\n  }\n  putchar('\\n');\n}\n\nvoid gen_irreps_ntl() {\n  stringstream ss;\n  cout << \"// This file is auto-generated by gen_irreps.cc, don't modify\" << endl;\n  cout << \"#include <NTL/GF2X.h>\" << endl;\n  cout << \"#include <sstream>\" << endl;\n  cout << \"#include <iostream>\" << endl;\n    cout << \"#include <cstdlib>\" << endl;\n  cout << \"NTL_CLIENT\" << endl;\n  cout << \"void set_irrep(GF2X &P, unsigned n) {\" << endl;\n  cout << \"stringstream ss;\" << endl;\n  cout << \"switch (n) {\" << endl;\n\n  for( unsigned n = 0; n < sizeof(field_sizes)/sizeof(unsigned int); n++ ) \n  {\n    GF2X P;\n    BuildSparseIrred(P, field_sizes[n]);\n\n    // This way of storage is extremely inefficient. But since\n    // we're only talking about a few bytes on a big iron machine,\n    // who cares...\n    cout << \"case \" << field_sizes[n] << \":\" << endl;\n    cout << \"ss << \\\"\" << P  << \"\\\";\" << endl;\n    cout << \"ss >> P;\" << endl;\n    cout << \"break;\" << endl;\n  }\n\n  cout << \"default:\" << endl;\n  cout << \" cerr << \\\"Internal error: n out of bounds!\\\";\" << endl;\n  cout << \" exit(-1);\" << endl;\n  cout << \"}\" << endl;\n  cout << \"}\" << endl;\n}\n\nvoid gen_irreps_openssl() {\n  stringstream ss;\n  cout << \"// This file is auto-generated by gen_irreps.cc, don't modify\" << endl;\n  cout << \"#include <openssl/bn.h>\" << endl;\n  cout << \"#include <iostream>\" << endl;\n    cout << \"#include <cstdlib>\" << endl;\n    cout << \"#include <vector>\" << endl;\n  cout << \"using namespace std;\" << endl;\n  cout << \"void set_irrep(vector<int> &p, unsigned n) {\" << endl;\n  cout << \"switch (n) {\" << endl;\n\n  for( unsigned n = 0; n < sizeof(field_sizes)/sizeof(unsigned int); n++ ) \n  {\n    GF2X P;\n    BuildSparseIrred(P, field_sizes[n]);\n\n    // Sure, there are much more efficient ways to detect the number\n    // of set bits\n    cout << \"case \" << field_sizes[n] << \": {\" << endl;\n    \n    for (long i = deg(P); i >= 0; i--) {\n      if (coeff(P, i) == 1)\n        cout << \"p.push_back(\"  << i << \");\" << endl;\n    }\n    cout << \"} break;\" << endl;\n  }\n\n  cout << \"default:\" << endl;\n  cout << \" cerr << \\\"Internal error: n out of bounds!\\\";\" << endl;\n  cout << \" exit(-1);\" << endl;\n  cout << \"}\" << endl;\n  cout << \"}\" << endl;\n}\n\nvoid gen_irreps_cuda() {\n  stringstream ss;\n  cout << \"// This file is auto-generated by gen_irreps.cc, don't modify\" << endl;\n  cout << \"#include \\\"CumffaTypes.h\\\"\" << endl;\n  cout << \"#include <iostream>\" << endl;\n    cout << \"#include <cstdlib>\" << endl;\n    cout << \"#include <vector>\" << endl;\n  cout << \"using namespace std;\" << endl;\n\n  cout << \"void set_irrep_cuda(vector<ufixn> &p, ufixn n) {\" << endl;\n  cout << \"switch (n) {\" << endl;\n\n  for( unsigned n = 0; n < sizeof(field_sizes)/sizeof(unsigned int); n++ ) \n  {\n    GF2X P;\n    BuildSparseIrred(P, field_sizes[n]);\n\n    // Sure, there are much more efficient ways to detect the number\n    // of set bits\n    cout << \"case \" << field_sizes[n] << \": {\" << endl;\n\n    long num_bytes = NumBytes(P);\n    unsigned char bytes[num_bytes];\n    int num_chunks = (num_bytes-1)/sizeof(ufixn)+1;\n    ufixn bytes_as_ufixn[num_chunks];\n    clearArray(bytes_as_ufixn, num_chunks);\n\n    BytesFromGF2X(bytes, P, num_bytes);\n\n    reverse(bytes, bytes+num_bytes);\n    \n    long offset = 0;\n    long i = 0;\n    \n    convertCharArrayToIntArray(bytes, bytes_as_ufixn, num_bytes);\n\n    for(int i=0; i<num_chunks; i++) {\n      cout << \"p.push_back(\"  << bytes_as_ufixn[i] << \"ULL);\" << endl;\n    }\n\n    cout << \"} break;\" << endl;\n  }\n\n  cout << \"default:\" << endl;\n  cout << \" cerr << \\\"Internal error: n out of bounds!\\\";\" << endl;\n  cout << \" exit(-1);\" << endl;\n  cout << \"}\" << endl;\n  cout << \"}\" << endl;\n}\n\nvoid gen_irreps_cuda_for_py() {\n  stringstream ss;\n  cout << \"# This file is auto-generated by gen_irreps.cc, don't modify\" << endl;\n  cout << endl;\n\n  cout << \"def set_irrep( n ):\" << endl;\n\n  cout << endl;\n  cout << \"\\tres = 0\" << endl;\n  cout << endl;\n\n  for( unsigned n = 0; n < sizeof(field_sizes)/sizeof(unsigned int); n++ ) \n  {\n    GF2X P;\n    BuildSparseIrred(P, field_sizes[n]);\n\n    // Sure, there are much more efficient ways to detect the number\n    // of set bits\n    if( field_sizes[n] == 1 )\n      cout << \"\\tif n == \" << field_sizes[n] << \":\" << endl;\n    else\n      cout << \"\\telif n == \" << field_sizes[n] << \":\" << endl;\n\n    long num_bytes = NumBytes(P);\n    unsigned char bytes[num_bytes];\n\n    BytesFromGF2X(bytes, P, num_bytes);\n\n    reverse(bytes, bytes+num_bytes);\n    \n    long shift = 0;\n\n    for( int i=num_bytes-1; i>=0; --i ) {\n      cout << \"\\t\\tres = res + (\" << +bytes[i] << \" << \" << shift << \")\" << endl;\n      shift = shift + 8;\n    }\n  }\n\n  cout << endl;\n  cout << \"\\treturn res\" << endl;\n}\n\nint main(int argc, char **argv) {\n  if(strcmp(argv[1], \"NTL\") == 0) {\n    gen_irreps_ntl();\n  } else if(strcmp(argv[1], \"CUDA\") == 0) {\n    gen_irreps_cuda();\n  } else if(strcmp(argv[1], \"PYTHON\") == 0) {\n    gen_irreps_cuda_for_py();\n  } else {\n    gen_irreps_openssl();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "67ff9e83e4cd242995b6bdf14b456283c0557162", "size": 7112, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lib/tools/gen_irreps/gen_irreps_array.cc", "max_stars_repo_name": "dom8509/libcumffa", "max_stars_repo_head_hexsha": "a21380266973a21e7e5472c3881b5d1871230472", "max_stars_repo_licenses": ["MIT"], "max_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/tools/gen_irreps/gen_irreps_array.cc", "max_issues_repo_name": "dom8509/libcumffa", "max_issues_repo_head_hexsha": "a21380266973a21e7e5472c3881b5d1871230472", "max_issues_repo_licenses": ["MIT"], "max_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/tools/gen_irreps/gen_irreps_array.cc", "max_forks_repo_name": "dom8509/libcumffa", "max_forks_repo_head_hexsha": "a21380266973a21e7e5472c3881b5d1871230472", "max_forks_repo_licenses": ["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.1450381679, "max_line_length": 90, "alphanum_fraction": 0.5787401575, "num_tokens": 2147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.07263671288517126, "lm_q1q2_score": 0.03575092829983913}}
{"text": "/* ----------------------------------------------------------------------------\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 dataset.cpp\n * @date Jan 22, 2010\n * @author Kai Ni, Luca Carlone, Frank Dellaert\n * @brief utility functions for loading datasets\n */\n\n#include <gtsam/sam/BearingRangeFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/slam/dataset.h>\n#include <gtsam/geometry/Point3.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/geometry/Rot3.h>\n#include <gtsam/inference/FactorGraph.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/nonlinear/NonlinearFactor.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/Values-inl.h>\n#include <gtsam/linear/Sampler.h>\n#include <gtsam/base/GenericValue.h>\n#include <gtsam/base/Lie.h>\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/types.h>\n#include <gtsam/base/Value.h>\n#include <gtsam/base/Vector.h>\n\n#include <boost/assign/list_inserter.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/path.hpp>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n\nusing namespace std;\nnamespace fs = boost::filesystem;\nusing namespace gtsam::symbol_shorthand;\n\n#define LINESIZE 81920\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nstring findExampleDataFile(const string& name) {\n  // Search source tree and installed location\n  vector<string> rootsToSearch;\n\n  // Constants below are defined by CMake, see gtsam/gtsam/CMakeLists.txt\n  rootsToSearch.push_back(GTSAM_SOURCE_TREE_DATASET_DIR);\n  rootsToSearch.push_back(GTSAM_INSTALLED_DATASET_DIR);\n\n  // Search for filename as given, and with .graph and .txt extensions\n  vector<string> namesToSearch;\n  namesToSearch.push_back(name);\n  namesToSearch.push_back(name + \".graph\");\n  namesToSearch.push_back(name + \".txt\");\n  namesToSearch.push_back(name + \".out\");\n  namesToSearch.push_back(name + \".xml\");\n\n  // Find first name that exists\n  for(const fs::path& root: rootsToSearch) {\n    for(const fs::path& name: namesToSearch) {\n      if (fs::is_regular_file(root / name))\n        return (root / name).string();\n    }\n  }\n\n  // If we did not return already, then we did not find the file\n  throw invalid_argument(\n      \"gtsam::findExampleDataFile could not find a matching file in\\n\"\n      GTSAM_SOURCE_TREE_DATASET_DIR \" or\\n\"\n      GTSAM_INSTALLED_DATASET_DIR \" named\\n\" + name + \", \" + name\n          + \".graph, or \" + name + \".txt\");\n}\n\n/* ************************************************************************* */\nstring createRewrittenFileName(const string& name) {\n  // Search source tree and installed location\n  if (!exists(fs::path(name))) {\n    throw invalid_argument(\n        \"gtsam::createRewrittenFileName could not find a matching file in\\n\"\n            + name);\n  }\n\n  fs::path p(name);\n  fs::path newpath = fs::path(p.parent_path().string())\n      / fs::path(p.stem().string() + \"-rewritten.txt\");\n\n  return newpath.string();\n}\n\n/* ************************************************************************* */\nGraphAndValues load2D(pair<string, SharedNoiseModel> dataset, int maxID,\n    bool addNoise, bool smart, NoiseFormat noiseFormat,\n    KernelFunctionType kernelFunctionType) {\n  return load2D(dataset.first, dataset.second, maxID, addNoise, smart,\n      noiseFormat, kernelFunctionType);\n}\n\n/* ************************************************************************* */\n// Read noise parameters and interpret them according to flags\nstatic SharedNoiseModel readNoiseModel(ifstream& is, bool smart,\n    NoiseFormat noiseFormat, KernelFunctionType kernelFunctionType) {\n  double v1, v2, v3, v4, v5, v6;\n  is >> v1 >> v2 >> v3 >> v4 >> v5 >> v6;\n\n  if (noiseFormat == NoiseFormatAUTO) {\n    // Try to guess covariance matrix layout\n    if (v1 != 0.0 && v2 == 0.0 && v3 != 0.0 && v4 != 0.0 && v5 == 0.0\n        && v6 == 0.0) {\n      // NoiseFormatGRAPH\n      noiseFormat = NoiseFormatGRAPH;\n    } else if (v1 != 0.0 && v2 == 0.0 && v3 == 0.0 && v4 != 0.0 && v5 == 0.0\n        && v6 != 0.0) {\n      // NoiseFormatCOV\n      noiseFormat = NoiseFormatCOV;\n    } else {\n      throw std::invalid_argument(\n          \"load2D: unrecognized covariance matrix format in dataset file. Please specify the noise format.\");\n    }\n  }\n\n  // Read matrix and check that diagonal entries are non-zero\n  Matrix M(3, 3);\n  switch (noiseFormat) {\n  case NoiseFormatG2O:\n  case NoiseFormatCOV:\n    // i.e., [ v1 v2 v3; v2' v4 v5; v3' v5' v6 ]\n    if (v1 == 0.0 || v4 == 0.0 || v6 == 0.0)\n      throw runtime_error(\n          \"load2D::readNoiseModel looks like this is not G2O matrix order\");\n    M << v1, v2, v3, v2, v4, v5, v3, v5, v6;\n    break;\n  case NoiseFormatTORO:\n  case NoiseFormatGRAPH:\n    // http://www.openslam.org/toro.html\n    // inf_ff inf_fs inf_ss inf_rr inf_fr inf_sr\n    // i.e., [ v1 v2 v5; v2' v3 v6; v5' v6' v4 ]\n    if (v1 == 0.0 || v3 == 0.0 || v4 == 0.0)\n      throw invalid_argument(\n          \"load2D::readNoiseModel looks like this is not TORO matrix order\");\n    M << v1, v2, v5, v2, v3, v6, v5, v6, v4;\n    break;\n  default:\n    throw runtime_error(\"load2D: invalid noise format\");\n  }\n\n  // Now, create a Gaussian noise model\n  // The smart flag will try to detect a simpler model, e.g., unit\n  SharedNoiseModel model;\n  switch (noiseFormat) {\n  case NoiseFormatG2O:\n  case NoiseFormatTORO:\n    // In both cases, what is stored in file is the information matrix\n    model = noiseModel::Gaussian::Information(M, smart);\n    break;\n  case NoiseFormatGRAPH:\n  case NoiseFormatCOV:\n    // These cases expect covariance matrix\n    model = noiseModel::Gaussian::Covariance(M, smart);\n    break;\n  default:\n    throw invalid_argument(\"load2D: invalid noise format\");\n  }\n\n  switch (kernelFunctionType) {\n  case KernelFunctionTypeNONE:\n    return model;\n    break;\n  case KernelFunctionTypeHUBER:\n    return noiseModel::Robust::Create(\n        noiseModel::mEstimator::Huber::Create(1.345), model);\n    break;\n  case KernelFunctionTypeTUKEY:\n    return noiseModel::Robust::Create(\n        noiseModel::mEstimator::Tukey::Create(4.6851), model);\n    break;\n  default:\n    throw invalid_argument(\"load2D: invalid kernel function type\");\n  }\n}\n\n/* ************************************************************************* */\nboost::optional<IndexedPose> parseVertex(istream& is, const string& tag) {\n  if ((tag == \"VERTEX2\") || (tag == \"VERTEX_SE2\") || (tag == \"VERTEX\")) {\n    Key id;\n    double x, y, yaw;\n    is >> id >> x >> y >> yaw;\n    return IndexedPose(id, Pose2(x, y, yaw));\n  } else {\n    return boost::none;\n  }\n}\n\n/* ************************************************************************* */\nboost::optional<IndexedEdge> parseEdge(istream& is, const string& tag) {\n  if ((tag == \"EDGE2\") || (tag == \"EDGE\") || (tag == \"EDGE_SE2\")\n      || (tag == \"ODOMETRY\")) {\n\n    Key id1, id2;\n    double x, y, yaw;\n    is >> id1 >> id2 >> x >> y >> yaw;\n    return IndexedEdge(pair<Key, Key>(id1, id2), Pose2(x, y, yaw));\n  } else {\n    return boost::none;\n  }\n}\n\n/* ************************************************************************* */\nGraphAndValues load2D(const string& filename, SharedNoiseModel model, Key maxID,\n    bool addNoise, bool smart, NoiseFormat noiseFormat,\n    KernelFunctionType kernelFunctionType) {\n\n  ifstream is(filename.c_str());\n  if (!is)\n    throw invalid_argument(\"load2D: can not find file \" + filename);\n\n  Values::shared_ptr initial(new Values);\n  NonlinearFactorGraph::shared_ptr graph(new NonlinearFactorGraph);\n\n  string tag;\n\n  // load the poses\n  while (!is.eof()) {\n    if (!(is >> tag))\n      break;\n\n    const auto indexed_pose = parseVertex(is, tag);\n    if (indexed_pose) {\n      Key id = indexed_pose->first;\n\n      // optional filter\n      if (maxID && id >= maxID)\n        continue;\n\n      initial->insert(id, indexed_pose->second);\n    }\n    is.ignore(LINESIZE, '\\n');\n  }\n  is.clear(); /* clears the end-of-file and error flags */\n  is.seekg(0, ios::beg);\n\n  // If asked, create a sampler with random number generator\n  Sampler sampler;\n  if (addNoise) {\n    noiseModel::Diagonal::shared_ptr noise;\n    if (model)\n      noise = std::dynamic_pointer_cast<noiseModel::Diagonal>(model);\n    if (!noise)\n      throw invalid_argument(\n          \"gtsam::load2D: invalid noise model for adding noise\"\n              \"(current version assumes diagonal noise model)!\");\n    sampler = Sampler(noise);\n  }\n\n  // Parse the pose constraints\n  Key id1, id2;\n  bool haveLandmark = false;\n  const bool useModelInFile = !model;\n  while (!is.eof()) {\n    if (!(is >> tag))\n      break;\n\n    auto between_pose = parseEdge(is, tag);\n    if (between_pose) {\n      std::tie(id1, id2) = between_pose->first;\n      Pose2& l1Xl2 = between_pose->second;\n\n      // read noise model\n      SharedNoiseModel modelInFile = readNoiseModel(is, smart, noiseFormat,\n          kernelFunctionType);\n\n      // optional filter\n      if (maxID && (id1 >= maxID || id2 >= maxID))\n        continue;\n\n      if (useModelInFile)\n        model = modelInFile;\n\n      if (addNoise)\n        l1Xl2 = l1Xl2.retract(sampler.sample());\n\n      // Insert vertices if pure odometry file\n      if (!initial->exists(id1))\n        initial->insert(id1, Pose2());\n      if (!initial->exists(id2))\n        initial->insert(id2, initial->at<Pose2>(id1) * l1Xl2);\n\n      NonlinearFactor::shared_ptr factor(\n          new BetweenFactor<Pose2>(id1, id2, l1Xl2, model));\n      graph->push_back(factor);\n    }\n    // Parse measurements\n    double bearing, range, bearing_std, range_std;\n\n    // A bearing-range measurement\n    if (tag == \"BR\") {\n      is >> id1 >> id2 >> bearing >> range >> bearing_std >> range_std;\n    }\n\n    // A landmark measurement, TODO Frank says: don't know why is converted to bearing-range\n    if (tag == \"LANDMARK\") {\n      double lmx, lmy;\n      double v1, v2, v3;\n\n      is >> id1 >> id2 >> lmx >> lmy >> v1 >> v2 >> v3;\n\n      // Convert x,y to bearing,range\n      bearing = atan2(lmy, lmx);\n      range = sqrt(lmx * lmx + lmy * lmy);\n\n      // In our experience, the x-y covariance on landmark sightings is not very good, so assume\n      // it describes the uncertainty at a range of 10m, and convert that to bearing/range uncertainty.\n      if (std::abs(v1 - v3) < 1e-4) {\n        bearing_std = sqrt(v1 / 10.0);\n        range_std = sqrt(v1);\n      } else {\n        bearing_std = 1;\n        range_std = 1;\n        if (!haveLandmark) {\n          cout\n              << \"Warning: load2D is a very simple dataset loader and is ignoring the\\n\"\n                  \"non-uniform covariance on LANDMARK measurements in this file.\"\n              << endl;\n          haveLandmark = true;\n        }\n      }\n    }\n\n    // Do some common stuff for bearing-range measurements\n    if (tag == \"LANDMARK\" || tag == \"BR\") {\n\n      // optional filter\n      if (maxID && id1 >= maxID)\n        continue;\n\n      // Create noise model\n      noiseModel::Diagonal::shared_ptr measurementNoise =\n          noiseModel::Diagonal::Sigmas((Vector(2) << bearing_std, range_std).finished());\n\n      // Add to graph\n      *graph += BearingRangeFactor<Pose2, Point2>(id1, L(id2), bearing, range,\n          measurementNoise);\n\n      // Insert poses or points if they do not exist yet\n      if (!initial->exists(id1))\n        initial->insert(id1, Pose2());\n      if (!initial->exists(L(id2))) {\n        Pose2 pose = initial->at<Pose2>(id1);\n        Point2 local(cos(bearing) * range, sin(bearing) * range);\n        Point2 global = pose.transformFrom(local);\n        initial->insert(L(id2), global);\n      }\n    }\n    is.ignore(LINESIZE, '\\n');\n  }\n\n  return make_pair(graph, initial);\n}\n\n/* ************************************************************************* */\nGraphAndValues load2D_robust(const string& filename,\n    const noiseModel::Base::shared_ptr& model, int maxID) {\n  return load2D(filename, model, maxID);\n}\n\n/* ************************************************************************* */\nvoid save2D(const NonlinearFactorGraph& graph, const Values& config,\n    const noiseModel::Diagonal::shared_ptr model, const string& filename) {\n\n  fstream stream(filename.c_str(), fstream::out);\n\n  // save poses\n\n  for(const Values::ConstKeyValuePair& key_value: config) {\n    const Pose2& pose = key_value.value.cast<Pose2>();\n    stream << \"VERTEX2 \" << key_value.key << \" \" << pose.x() << \" \" << pose.y()\n        << \" \" << pose.theta() << endl;\n  }\n\n  // save edges\n  Matrix R = model->R();\n  Matrix RR = trans(R) * R; //prod(trans(R),R);\n  for(std::shared_ptr<NonlinearFactor> factor_: graph) {\n    std::shared_ptr<BetweenFactor<Pose2> > factor =\n        std::dynamic_pointer_cast<BetweenFactor<Pose2> >(factor_);\n    if (!factor)\n      continue;\n\n    Pose2 pose = factor->measured().inverse();\n    stream << \"EDGE2 \" << factor->key2() << \" \" << factor->key1() << \" \"\n        << pose.x() << \" \" << pose.y() << \" \" << pose.theta() << \" \" << RR(0, 0)\n        << \" \" << RR(0, 1) << \" \" << RR(1, 1) << \" \" << RR(2, 2) << \" \"\n        << RR(0, 2) << \" \" << RR(1, 2) << endl;\n  }\n\n  stream.close();\n}\n\n/* ************************************************************************* */\nGraphAndValues readG2o(const string& g2oFile, const bool is3D,\n                       KernelFunctionType kernelFunctionType) {\n  if (is3D) {\n    return load3D(g2oFile);\n  } else {\n    // just call load2D\n    int maxID = 0;\n    bool addNoise = false;\n    bool smart = true;\n    return load2D(g2oFile, SharedNoiseModel(), maxID, addNoise, smart,\n                  NoiseFormatG2O, kernelFunctionType);\n  }\n}\n\n/* ************************************************************************* */\nvoid writeG2o(const NonlinearFactorGraph& graph, const Values& estimate,\n    const string& filename) {\n  fstream stream(filename.c_str(), fstream::out);\n\n  // save 2D & 3D poses\n  for (const auto& key_value : estimate) {\n    auto p = dynamic_cast<const GenericValue<Pose2>*>(&key_value.value);\n    if (!p) continue;\n    const Pose2& pose = p->value();\n    stream << \"VERTEX_SE2 \" << key_value.key << \" \" << pose.x() << \" \"\n        << pose.y() << \" \" << pose.theta() << endl;\n  }\n\n  for(const auto& key_value: estimate) {\n      auto p = dynamic_cast<const GenericValue<Pose3>*>(&key_value.value);\n      if (!p) continue;\n      const Pose3& pose = p->value();\n      Point3 t = pose.translation();\n      Rot3 R = pose.rotation();\n      stream << \"VERTEX_SE3:QUAT \" << key_value.key << \" \" << t.x() << \" \"  << t.y() << \" \" << t.z()\n        << \" \" << R.toQuaternion().x() << \" \" << R.toQuaternion().y() << \" \" << R.toQuaternion().z()\n        << \" \" << R.toQuaternion().w() << endl;\n  }\n\n  // save edges (2D or 3D)\n  for(const auto& factor_: graph) {\n    std::shared_ptr<BetweenFactor<Pose2> > factor =\n        std::dynamic_pointer_cast<BetweenFactor<Pose2> >(factor_);\n    if (factor){\n      SharedNoiseModel model = factor->noiseModel();\n      std::shared_ptr<noiseModel::Gaussian> gaussianModel =\n          std::dynamic_pointer_cast<noiseModel::Gaussian>(model);\n      if (!gaussianModel){\n        model->print(\"model\\n\");\n        throw invalid_argument(\"writeG2o: invalid noise model!\");\n      }\n      Matrix Info = gaussianModel->R().transpose() * gaussianModel->R();\n      Pose2 pose = factor->measured(); //.inverse();\n      stream << \"EDGE_SE2 \" << factor->key1() << \" \" << factor->key2() << \" \"\n          << pose.x() << \" \" << pose.y() << \" \" << pose.theta();\n      for (int i = 0; i < 3; i++){\n        for (int j = i; j < 3; j++){\n          stream << \" \" << Info(i, j);\n        }\n      }\n      stream << endl;\n    }\n\n    std::shared_ptr< BetweenFactor<Pose3> > factor3D =\n        std::dynamic_pointer_cast< BetweenFactor<Pose3> >(factor_);\n\n    if (factor3D){\n      SharedNoiseModel model = factor3D->noiseModel();\n\n      std::shared_ptr<noiseModel::Gaussian> gaussianModel =\n          std::dynamic_pointer_cast<noiseModel::Gaussian>(model);\n      if (!gaussianModel){\n        model->print(\"model\\n\");\n        throw invalid_argument(\"writeG2o: invalid noise model!\");\n      }\n      Matrix Info = gaussianModel->R().transpose() * gaussianModel->R();\n      Pose3 pose3D = factor3D->measured();\n      Point3 p = pose3D.translation();\n      Rot3 R = pose3D.rotation();\n\n      stream << \"EDGE_SE3:QUAT \" << factor3D->key1() << \" \" << factor3D->key2() << \" \"\n          << p.x() << \" \"  << p.y() << \" \" << p.z()  << \" \" << R.toQuaternion().x()\n          << \" \" << R.toQuaternion().y() << \" \" << R.toQuaternion().z()  << \" \" << R.toQuaternion().w();\n\n      Matrix InfoG2o = I_6x6;\n      InfoG2o.block(0,0,3,3) = Info.block(3,3,3,3); // cov translation\n      InfoG2o.block(3,3,3,3) = Info.block(0,0,3,3); // cov rotation\n      InfoG2o.block(0,3,3,3) = Info.block(0,3,3,3); // off diagonal\n      InfoG2o.block(3,0,3,3) = Info.block(3,0,3,3); // off diagonal\n\n      for (int i = 0; i < 6; i++){\n        for (int j = i; j < 6; j++){\n          stream << \" \" << InfoG2o(i, j);\n        }\n      }\n      stream << endl;\n    }\n  }\n  stream.close();\n}\n\n/* ************************************************************************* */\nstd::map<Key, Pose3> parse3DPoses(const string& filename) {\n  ifstream is(filename.c_str());\n  if (!is)\n    throw invalid_argument(\"parse3DPoses: can not find file \" + filename);\n\n  std::map<Key, Pose3> poses;\n  while (!is.eof()) {\n    char buf[LINESIZE];\n    is.getline(buf, LINESIZE);\n    istringstream ls(buf);\n    string tag;\n    ls >> tag;\n\n    if (tag == \"VERTEX3\") {\n      Key id;\n      double x, y, z, roll, pitch, yaw;\n      ls >> id >> x >> y >> z >> roll >> pitch >> yaw;\n      poses.emplace(id, Pose3(Rot3::Ypr(yaw, pitch, roll), {x, y, z}));\n    }\n    if (tag == \"VERTEX_SE3:QUAT\") {\n      Key id;\n      double x, y, z, qx, qy, qz, qw;\n      ls >> id >> x >> y >> z >> qx >> qy >> qz >> qw;\n      poses.emplace(id, Pose3(Rot3::Quaternion(qw, qx, qy, qz), {x, y, z}));\n    }\n  }\n  return poses;\n}\n\n/* ************************************************************************* */\nBetweenFactorPose3s parse3DFactors(const string& filename) {\n  ifstream is(filename.c_str());\n  if (!is) throw invalid_argument(\"parse3DFactors: can not find file \" + filename);\n\n  std::vector<BetweenFactor<Pose3>::shared_ptr> factors;\n  while (!is.eof()) {\n    char buf[LINESIZE];\n    is.getline(buf, LINESIZE);\n    istringstream ls(buf);\n    string tag;\n    ls >> tag;\n\n    if (tag == \"EDGE3\") {\n      Key id1, id2;\n      double x, y, z, roll, pitch, yaw;\n      ls >> id1 >> id2 >> x >> y >> z >> roll >> pitch >> yaw;\n      Matrix m(6, 6);\n      for (size_t i = 0; i < 6; i++)\n        for (size_t j = i; j < 6; j++) ls >> m(i, j);\n      SharedNoiseModel model = noiseModel::Gaussian::Information(m);\n      factors.emplace_back(new BetweenFactor<Pose3>(\n          id1, id2, Pose3(Rot3::Ypr(yaw, pitch, roll), {x, y, z}), model));\n    }\n    if (tag == \"EDGE_SE3:QUAT\") {\n      Key id1, id2;\n      double x, y, z, qx, qy, qz, qw;\n      ls >> id1 >> id2 >> x >> y >> z >> qx >> qy >> qz >> qw;\n      Matrix m(6, 6);\n      for (size_t i = 0; i < 6; i++) {\n        for (size_t j = i; j < 6; j++) {\n          double mij;\n          ls >> mij;\n          m(i, j) = mij;\n          m(j, i) = mij;\n        }\n      }\n      Matrix mgtsam(6, 6);\n\n      mgtsam.block<3, 3>(0, 0) = m.block<3, 3>(3, 3);  // cov rotation\n      mgtsam.block<3, 3>(3, 3) = m.block<3, 3>(0, 0);  // cov translation\n      mgtsam.block<3, 3>(0, 3) = m.block<3, 3>(0, 3);  // off diagonal\n      mgtsam.block<3, 3>(3, 0) = m.block<3, 3>(3, 0);  // off diagonal\n\n      SharedNoiseModel model = noiseModel::Gaussian::Information(mgtsam);\n      factors.emplace_back(new BetweenFactor<Pose3>(\n          id1, id2, Pose3(Rot3::Quaternion(qw, qx, qy, qz), {x, y, z}), model));\n    }\n  }\n  return factors;\n}\n\n/* ************************************************************************* */\nGraphAndValues load3D(const string& filename) {\n  const auto factors = parse3DFactors(filename);\n  NonlinearFactorGraph::shared_ptr graph(new NonlinearFactorGraph);\n  for (const auto& factor : factors) {\n    graph->push_back(factor);\n  }\n\n  const auto poses = parse3DPoses(filename);\n  Values::shared_ptr initial(new Values);\n  for (const auto& key_pose : poses) {\n    initial->insert(key_pose.first, key_pose.second);\n  }\n\n  return make_pair(graph, initial);\n}\n\n/* ************************************************************************* */\nRot3 openGLFixedRotation() { // this is due to different convention for cameras in gtsam and openGL\n  /* R = [ 1   0   0\n   *       0  -1   0\n   *       0   0  -1]\n   */\n  Matrix3 R_mat = Matrix3::Zero(3, 3);\n  R_mat(0, 0) = 1.0;\n  R_mat(1, 1) = -1.0;\n  R_mat(2, 2) = -1.0;\n  return Rot3(R_mat);\n}\n\n/* ************************************************************************* */\nPose3 openGL2gtsam(const Rot3& R, double tx, double ty, double tz) {\n  Rot3 R90 = openGLFixedRotation();\n  Rot3 wRc = (R.inverse()).compose(R90);\n\n  // Our camera-to-world translation wTc = -R'*t\n  return Pose3(wRc, R.unrotate(Point3(-tx, -ty, -tz)));\n}\n\n/* ************************************************************************* */\nPose3 gtsam2openGL(const Rot3& R, double tx, double ty, double tz) {\n  Rot3 R90 = openGLFixedRotation();\n  Rot3 cRw_openGL = R90.compose(R.inverse());\n  Point3 t_openGL = cRw_openGL.rotate(Point3(-tx, -ty, -tz));\n  return Pose3(cRw_openGL, t_openGL);\n}\n\n/* ************************************************************************* */\nPose3 gtsam2openGL(const Pose3& PoseGTSAM) {\n  return gtsam2openGL(PoseGTSAM.rotation(), PoseGTSAM.x(), PoseGTSAM.y(),\n      PoseGTSAM.z());\n}\n\n/* ************************************************************************* */\nbool readBundler(const string& filename, SfM_data &data) {\n  // Load the data file\n  ifstream is(filename.c_str(), ifstream::in);\n  if (!is) {\n    cout << \"Error in readBundler: can not find the file!!\" << endl;\n    return false;\n  }\n\n  // Ignore the first line\n  char aux[500];\n  is.getline(aux, 500);\n\n  // Get the number of camera poses and 3D points\n  size_t nrPoses, nrPoints;\n  is >> nrPoses >> nrPoints;\n\n  // Get the information for the camera poses\n  for (size_t i = 0; i < nrPoses; i++) {\n    // Get the focal length and the radial distortion parameters\n    float f, k1, k2;\n    is >> f >> k1 >> k2;\n    Cal3Bundler K(f, k1, k2);\n\n    // Get the rotation matrix\n    float r11, r12, r13;\n    float r21, r22, r23;\n    float r31, r32, r33;\n    is >> r11 >> r12 >> r13 >> r21 >> r22 >> r23 >> r31 >> r32 >> r33;\n\n    // Bundler-OpenGL rotation matrix\n    Rot3 R(r11, r12, r13, r21, r22, r23, r31, r32, r33);\n\n    // Check for all-zero R, in which case quit\n    if (r11 == 0 && r12 == 0 && r13 == 0) {\n      cout << \"Error in readBundler: zero rotation matrix for pose \" << i\n          << endl;\n      return false;\n    }\n\n    // Get the translation vector\n    float tx, ty, tz;\n    is >> tx >> ty >> tz;\n\n    Pose3 pose = openGL2gtsam(R, tx, ty, tz);\n\n    data.cameras.emplace_back(pose, K);\n  }\n\n  // Get the information for the 3D points\n  data.tracks.reserve(nrPoints);\n  for (size_t j = 0; j < nrPoints; j++) {\n    SfM_Track track;\n\n    // Get the 3D position\n    float x, y, z;\n    is >> x >> y >> z;\n    track.p = Point3(x, y, z);\n\n    // Get the color information\n    float r, g, b;\n    is >> r >> g >> b;\n    track.r = r / 255.f;\n    track.g = g / 255.f;\n    track.b = b / 255.f;\n\n    // Now get the visibility information\n    size_t nvisible = 0;\n    is >> nvisible;\n\n    track.measurements.reserve(nvisible);\n    track.siftIndices.reserve(nvisible);\n    for (size_t k = 0; k < nvisible; k++) {\n      size_t cam_idx = 0, point_idx = 0;\n      float u, v;\n      is >> cam_idx >> point_idx >> u >> v;\n      track.measurements.emplace_back(cam_idx, Point2(u, -v));\n      track.siftIndices.emplace_back(cam_idx, point_idx);\n    }\n\n    data.tracks.push_back(track);\n  }\n\n  is.close();\n  return true;\n}\n\n/* ************************************************************************* */\nbool readBAL(const string& filename, SfM_data &data) {\n  // Load the data file\n  ifstream is(filename.c_str(), ifstream::in);\n  if (!is) {\n    cout << \"Error in readBAL: can not find the file!!\" << endl;\n    return false;\n  }\n\n  // Get the number of camera poses and 3D points\n  size_t nrPoses, nrPoints, nrObservations;\n  is >> nrPoses >> nrPoints >> nrObservations;\n\n  data.tracks.resize(nrPoints);\n\n  // Get the information for the observations\n  for (size_t k = 0; k < nrObservations; k++) {\n    size_t i = 0, j = 0;\n    float u, v;\n    is >> i >> j >> u >> v;\n    data.tracks[j].measurements.emplace_back(i, Point2(u, -v));\n  }\n\n  // Get the information for the camera poses\n  for (size_t i = 0; i < nrPoses; i++) {\n    // Get the Rodrigues vector\n    float wx, wy, wz;\n    is >> wx >> wy >> wz;\n    Rot3 R = Rot3::Rodrigues(wx, wy, wz); // BAL-OpenGL rotation matrix\n\n    // Get the translation vector\n    float tx, ty, tz;\n    is >> tx >> ty >> tz;\n\n    Pose3 pose = openGL2gtsam(R, tx, ty, tz);\n\n    // Get the focal length and the radial distortion parameters\n    float f, k1, k2;\n    is >> f >> k1 >> k2;\n    Cal3Bundler K(f, k1, k2);\n\n    data.cameras.emplace_back(pose, K);\n  }\n\n  // Get the information for the 3D points\n  for (size_t j = 0; j < nrPoints; j++) {\n    // Get the 3D position\n    float x, y, z;\n    is >> x >> y >> z;\n    SfM_Track& track = data.tracks[j];\n    track.p = Point3(x, y, z);\n    track.r = 0.4f;\n    track.g = 0.4f;\n    track.b = 0.4f;\n  }\n\n  is.close();\n  return true;\n}\n\n/* ************************************************************************* */\nbool writeBAL(const string& filename, SfM_data &data) {\n  // Open the output file\n  ofstream os;\n  os.open(filename.c_str());\n  os.precision(20);\n  if (!os.is_open()) {\n    cout << \"Error in writeBAL: can not open the file!!\" << endl;\n    return false;\n  }\n\n  // Write the number of camera poses and 3D points\n  size_t nrObservations = 0;\n  for (size_t j = 0; j < data.number_tracks(); j++) {\n    nrObservations += data.tracks[j].number_measurements();\n  }\n\n  // Write observations\n  os << data.number_cameras() << \" \" << data.number_tracks() << \" \"\n      << nrObservations << endl;\n  os << endl;\n\n  for (size_t j = 0; j < data.number_tracks(); j++) { // for each 3D point j\n    const SfM_Track& track = data.tracks[j];\n\n    for (size_t k = 0; k < track.number_measurements(); k++) { // for each observation of the 3D point j\n      size_t i = track.measurements[k].first; // camera id\n      double u0 = data.cameras[i].calibration().u0();\n      double v0 = data.cameras[i].calibration().v0();\n\n      if (u0 != 0 || v0 != 0) {\n        cout\n            << \"writeBAL has not been tested for calibration with nonzero (u0,v0)\"\n            << endl;\n      }\n\n      double pixelBALx = track.measurements[k].second.x() - u0; // center of image is the origin\n      double pixelBALy = -(track.measurements[k].second.y() - v0); // center of image is the origin\n      Point2 pixelMeasurement(pixelBALx, pixelBALy);\n      os << i /*camera id*/<< \" \" << j /*point id*/<< \" \"\n          << pixelMeasurement.x() /*u of the pixel*/<< \" \"\n          << pixelMeasurement.y() /*v of the pixel*/<< endl;\n    }\n  }\n  os << endl;\n\n  // Write cameras\n  for (size_t i = 0; i < data.number_cameras(); i++) { // for each camera\n    Pose3 poseGTSAM = data.cameras[i].pose();\n    Cal3Bundler cameraCalibration = data.cameras[i].calibration();\n    Pose3 poseOpenGL = gtsam2openGL(poseGTSAM);\n    os << Rot3::Logmap(poseOpenGL.rotation()) << endl;\n    os << poseOpenGL.translation().x() << endl;\n    os << poseOpenGL.translation().y() << endl;\n    os << poseOpenGL.translation().z() << endl;\n    os << cameraCalibration.fx() << endl;\n    os << cameraCalibration.k1() << endl;\n    os << cameraCalibration.k2() << endl;\n    os << endl;\n  }\n\n  // Write the points\n  for (size_t j = 0; j < data.number_tracks(); j++) { // for each 3D point j\n    Point3 point = data.tracks[j].p;\n    os << point.x() << endl;\n    os << point.y() << endl;\n    os << point.z() << endl;\n    os << endl;\n  }\n\n  os.close();\n  return true;\n}\n\nbool writeBALfromValues(const string& filename, const SfM_data &data,\n    Values& values) {\n  using Camera = PinholeCamera<Cal3Bundler>;\n  SfM_data dataValues = data;\n\n  // Store poses or cameras in SfM_data\n  size_t nrPoses = values.count<Pose3>();\n  if (nrPoses == dataValues.number_cameras()) { // we only estimated camera poses\n    for (size_t i = 0; i < dataValues.number_cameras(); i++) { // for each camera\n      Key poseKey = symbol('x', i);\n      Pose3 pose = values.at<Pose3>(poseKey);\n      Cal3Bundler K = dataValues.cameras[i].calibration();\n      Camera camera(pose, K);\n      dataValues.cameras[i] = camera;\n    }\n  } else {\n    size_t nrCameras = values.count<Camera>();\n    if (nrCameras == dataValues.number_cameras()) { // we only estimated camera poses and calibration\n      for (size_t i = 0; i < nrCameras; i++) { // for each camera\n        Key cameraKey = i; // symbol('c',i);\n        Camera camera = values.at<Camera>(cameraKey);\n        dataValues.cameras[i] = camera;\n      }\n    } else {\n      cout\n          << \"writeBALfromValues: different number of cameras in SfM_dataValues (#cameras \"\n          << dataValues.number_cameras() << \") and values (#cameras \"\n          << nrPoses << \", #poses \" << nrCameras << \")!!\"\n          << endl;\n      return false;\n    }\n  }\n\n  // Store 3D points in SfM_data\n  size_t nrPoints = values.count<Point3>(), nrTracks = dataValues.number_tracks();\n  if (nrPoints != nrTracks) {\n    cout\n        << \"writeBALfromValues: different number of points in SfM_dataValues (#points= \"\n        << nrTracks << \") and values (#points \"\n        << nrPoints << \")!!\" << endl;\n  }\n\n  for (size_t j = 0; j < nrTracks; j++) { // for each point\n    Key pointKey = P(j);\n    if (values.exists(pointKey)) {\n      Point3 point = values.at<Point3>(pointKey);\n      dataValues.tracks[j].p = point;\n    } else {\n      dataValues.tracks[j].r = 1.0;\n      dataValues.tracks[j].g = 0.0;\n      dataValues.tracks[j].b = 0.0;\n      dataValues.tracks[j].p = Point3(0,0,0);\n    }\n  }\n\n  // Write SfM_data to file\n  return writeBAL(filename, dataValues);\n}\n\nValues initialCamerasEstimate(const SfM_data& db) {\n  Values initial;\n  size_t i = 0; // NO POINTS:  j = 0;\n  for(const SfM_Camera& camera: db.cameras)\n    initial.insert(i++, camera);\n  return initial;\n}\n\nValues initialCamerasAndPointsEstimate(const SfM_data& db) {\n  Values initial;\n  size_t i = 0, j = 0;\n  for(const SfM_Camera& camera: db.cameras)\n    initial.insert((i++), camera);\n  for(const SfM_Track& track: db.tracks)\n    initial.insert(P(j++), track.p);\n  return initial;\n}\n\n} // \\namespace gtsam\n", "meta": {"hexsha": "299615a36350c8f29aa98d50608ac3486f764c3e", "size": 30814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/slam/dataset.cpp", "max_stars_repo_name": "ProfFan/gtsam", "max_stars_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "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": "gtsam/slam/dataset.cpp", "max_issues_repo_name": "ProfFan/gtsam", "max_issues_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam/slam/dataset.cpp", "max_forks_repo_name": "ProfFan/gtsam", "max_forks_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "max_forks_repo_licenses": ["BSD-3-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.5385427666, "max_line_length": 109, "alphanum_fraction": 0.5687349906, "num_tokens": 8792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.08756383535613607, "lm_q1q2_score": 0.03566767477667694}}
{"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_TMERC_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_TMERC_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/function_overloads.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct tmerc {}; // Transverse Mercator\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 tmerc\r\n    {\r\n\r\n            static const double epsilon10 = 1.e-10;\r\n\r\n            template <typename T>\r\n            inline T FC1() { return 1.; }\r\n            template <typename T>\r\n            inline T FC2() { return .5; }\r\n            template <typename T>\r\n            inline T FC3() { return .16666666666666666666666666666666666666; }\r\n            template <typename T>\r\n            inline T FC4() { return .08333333333333333333333333333333333333; }\r\n            template <typename T>\r\n            inline T FC5() { return .05; }\r\n            template <typename T>\r\n            inline T FC6() { return .03333333333333333333333333333333333333; }\r\n            template <typename T>\r\n            inline T FC7() { return .02380952380952380952380952380952380952; }\r\n            template <typename T>\r\n            inline T FC8() { return .01785714285714285714285714285714285714; }\r\n\r\n            template <typename T>\r\n            struct par_tmerc\r\n            {\r\n                T    esp;\r\n                T    ml0;\r\n                detail::en<T> en;\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_tmerc_ellipsoid\r\n                : public base_t_fi<base_tmerc_ellipsoid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_tmerc<T> m_proj_parm;\r\n\r\n                inline base_tmerc_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_tmerc_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(e_forward)  ellipse\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                    static const T half_pi = detail::half_pi<T>();\r\n                    static const T FC1 = tmerc::FC1<T>();\r\n                    static const T FC2 = tmerc::FC2<T>();\r\n                    static const T FC3 = tmerc::FC3<T>();\r\n                    static const T FC4 = tmerc::FC4<T>();\r\n                    static const T FC5 = tmerc::FC5<T>();\r\n                    static const T FC6 = tmerc::FC6<T>();\r\n                    static const T FC7 = tmerc::FC7<T>();\r\n                    static const T FC8 = tmerc::FC8<T>();\r\n\r\n                    T al, als, n, cosphi, sinphi, t;\r\n\r\n                    /*\r\n                     * Fail if our longitude is more than 90 degrees from the\r\n                     * central meridian since the results are essentially garbage.\r\n                     * Is error -20 really an appropriate return value?\r\n                     *\r\n                     *  http://trac.osgeo.org/proj/ticket/5\r\n                     */\r\n                    if( lp_lon < -half_pi || lp_lon > half_pi )\r\n                    {\r\n                        xy_x = HUGE_VAL;\r\n                        xy_y = HUGE_VAL;\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_or_lon_exceed_limit) );\r\n                        return;\r\n                    }\r\n\r\n                    sinphi = sin(lp_lat);\r\n                    cosphi = cos(lp_lat);\r\n                    t = fabs(cosphi) > 1e-10 ? sinphi/cosphi : 0.;\r\n                    t *= t;\r\n                    al = cosphi * lp_lon;\r\n                    als = al * al;\r\n                    al /= sqrt(1. - this->m_par.es * sinphi * sinphi);\r\n                    n = this->m_proj_parm.esp * cosphi * cosphi;\r\n                    xy_x = this->m_par.k0 * al * (FC1 +\r\n                        FC3 * als * (1. - t + n +\r\n                        FC5 * als * (5. + t * (t - 18.) + n * (14. - 58. * t)\r\n                        + FC7 * als * (61. + t * ( t * (179. - t) - 479. ) )\r\n                        )));\r\n                    xy_y = this->m_par.k0 * (pj_mlfn(lp_lat, sinphi, cosphi, this->m_proj_parm.en) - this->m_proj_parm.ml0 +\r\n                        sinphi * al * lp_lon * FC2 * ( 1. +\r\n                        FC4 * als * (5. - t + n * (9. + 4. * n) +\r\n                        FC6 * als * (61. + t * (t - 58.) + n * (270. - 330 * t)\r\n                        + FC8 * als * (1385. + t * ( t * (543. - t) - 3111.) )\r\n                        ))));\r\n                }\r\n\r\n                // INVERSE(e_inverse)  ellipsoid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    static const T half_pi = detail::half_pi<T>();\r\n                    static const T FC1 = tmerc::FC1<T>();\r\n                    static const T FC2 = tmerc::FC2<T>();\r\n                    static const T FC3 = tmerc::FC3<T>();\r\n                    static const T FC4 = tmerc::FC4<T>();\r\n                    static const T FC5 = tmerc::FC5<T>();\r\n                    static const T FC6 = tmerc::FC6<T>();\r\n                    static const T FC7 = tmerc::FC7<T>();\r\n                    static const T FC8 = tmerc::FC8<T>();\r\n\r\n                    T n, con, cosphi, d, ds, sinphi, t;\r\n\r\n                    lp_lat = pj_inv_mlfn(this->m_proj_parm.ml0 + xy_y / this->m_par.k0, this->m_par.es, this->m_proj_parm.en);\r\n                    if (fabs(lp_lat) >= half_pi) {\r\n                        lp_lat = xy_y < 0. ? -half_pi : half_pi;\r\n                        lp_lon = 0.;\r\n                    } else {\r\n                        sinphi = sin(lp_lat);\r\n                        cosphi = cos(lp_lat);\r\n                        t = fabs(cosphi) > 1e-10 ? sinphi/cosphi : 0.;\r\n                        n = this->m_proj_parm.esp * cosphi * cosphi;\r\n                        d = xy_x * sqrt(con = 1. - this->m_par.es * sinphi * sinphi) / this->m_par.k0;\r\n                        con *= t;\r\n                        t *= t;\r\n                        ds = d * d;\r\n                        lp_lat -= (con * ds / (1.-this->m_par.es)) * FC2 * (1. -\r\n                            ds * FC4 * (5. + t * (3. - 9. *  n) + n * (1. - 4 * n) -\r\n                            ds * FC6 * (61. + t * (90. - 252. * n +\r\n                                45. * t) + 46. * n\r\n                           - ds * FC8 * (1385. + t * (3633. + t * (4095. + 1574. * t)) )\r\n                            )));\r\n                        lp_lon = d*(FC1 -\r\n                            ds*FC3*( 1. + 2.*t + n -\r\n                            ds*FC5*(5. + t*(28. + 24.*t + 8.*n) + 6.*n\r\n                           - ds * FC7 * (61. + t * (662. + t * (1320. + 720. * t)) )\r\n                        ))) / cosphi;\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"tmerc_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_tmerc_spheroid\r\n                : public base_t_fi<base_tmerc_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_tmerc<T> m_proj_parm;\r\n\r\n                inline base_tmerc_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_tmerc_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& lp_lon, T& 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 b, cosphi;\r\n\r\n                    /*\r\n                     * Fail if our longitude is more than 90 degrees from the\r\n                     * central meridian since the results are essentially garbage.\r\n                     * Is error -20 really an appropriate return value?\r\n                     *\r\n                     *  http://trac.osgeo.org/proj/ticket/5\r\n                     */\r\n                    if( lp_lon < -half_pi || lp_lon > half_pi )\r\n                    {\r\n                        xy_x = HUGE_VAL;\r\n                        xy_y = HUGE_VAL;\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_or_lon_exceed_limit) );\r\n                        return;\r\n                    }\r\n\r\n                    cosphi = cos(lp_lat);\r\n                    b = cosphi * sin(lp_lon);\r\n                    if (fabs(fabs(b) - 1.) <= epsilon10)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n\r\n                    xy_x = this->m_proj_parm.ml0 * log((1. + b) / (1. - b));\r\n                    xy_y = cosphi * cos(lp_lon) / sqrt(1. - b * b);\r\n\r\n                    b = fabs( xy_y );\r\n                    if (b >= 1.) {\r\n                        if ((b - 1.) > epsilon10)\r\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                        else xy_y = 0.;\r\n                    } else\r\n                        xy_y = acos(xy_y);\r\n\r\n                    if (lp_lat < 0.)\r\n                        xy_y = -xy_y;\r\n                    xy_y = this->m_proj_parm.esp * (xy_y - this->m_par.phi0);\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& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    T h, g;\r\n\r\n                    h = exp(xy_x / this->m_proj_parm.esp);\r\n                    g = .5 * (h - 1. / h);\r\n                    h = cos(this->m_par.phi0 + xy_y / this->m_proj_parm.esp);\r\n                    lp_lat = asin(sqrt((1. - h * h) / (1. + g * g)));\r\n\r\n                    /* Make sure that phi is on the correct hemisphere when false northing is used */\r\n                    if (xy_y < 0. && -lp_lat+this->m_par.phi0 < 0.0) lp_lat = -lp_lat;\r\n\r\n                    lp_lon = (g != 0.0 || h != 0.0) ? atan2(g, h) : 0.;\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"tmerc_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            template <typename Parameters, typename T>\r\n            inline void setup(Parameters& par, par_tmerc<T>& proj_parm)\r\n            {\r\n                if (par.es != 0.0) {\r\n                    proj_parm.en = pj_enfn<T>(par.es);\r\n                    proj_parm.ml0 = pj_mlfn(par.phi0, sin(par.phi0), cos(par.phi0), proj_parm.en);\r\n                    proj_parm.esp = par.es / (1. - par.es);\r\n                } else {\r\n                    proj_parm.esp = par.k0;\r\n                    proj_parm.ml0 = .5 * proj_parm.esp;\r\n                }\r\n            }\r\n\r\n    }} // namespace detail::tmerc\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Transverse 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 Example\r\n        \\image html ex_tmerc.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct tmerc_ellipsoid : public detail::tmerc::base_tmerc_ellipsoid<T, Parameters>\r\n    {\r\n        inline tmerc_ellipsoid(const Parameters& par) : detail::tmerc::base_tmerc_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::tmerc::setup(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Transverse 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 Example\r\n        \\image html ex_tmerc.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct tmerc_spheroid : public detail::tmerc::base_tmerc_spheroid<T, Parameters>\r\n    {\r\n        inline tmerc_spheroid(const Parameters& par) : detail::tmerc::base_tmerc_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::tmerc::setup(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::tmerc, tmerc_spheroid, tmerc_ellipsoid)\r\n        \r\n        // Factory entry(s) - dynamic projection\r\n        template <typename T, typename Parameters>\r\n        class tmerc_entry : public detail::factory_entry<T, Parameters>\r\n        {\r\n            public :\r\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\r\n                {\r\n                    if (par.es)\r\n                        return new base_v_fi<tmerc_ellipsoid<T, Parameters>, T, Parameters>(par);\r\n                    else\r\n                        return new base_v_fi<tmerc_spheroid<T, Parameters>, T, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename T, typename Parameters>\r\n        inline void tmerc_init(detail::base_factory<T, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"tmerc\", new tmerc_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_TMERC_HPP\r\n\r\n", "meta": {"hexsha": "e0d82b4737743e0e285a62744f418d16f31bfe33", "size": 16217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/srs/projections/proj/tmerc.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/tmerc.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/tmerc.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.3420365535, "max_line_length": 127, "alphanum_fraction": 0.4957143738, "num_tokens": 3740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.07477003723826108, "lm_q1q2_score": 0.03563387825702852}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\r\n#define BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\r\n\r\n#include <boost/units/pow.hpp>\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/static_constant.hpp>\r\n\r\n#include <boost/units/systems/detail/constants.hpp>\r\n#include <boost/units/systems/si/amount.hpp>\r\n#include <boost/units/systems/si/area.hpp>\r\n#include <boost/units/systems/si/electric_charge.hpp>\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/frequency.hpp>\r\n#include <boost/units/systems/si/mass.hpp>\r\n#include <boost/units/systems/si/power.hpp>\r\n#include <boost/units/systems/si/solid_angle.hpp>\r\n#include <boost/units/systems/si/temperature.hpp>\r\n\r\n#include <boost/units/systems/si/codata/typedefs.hpp>\r\n\r\n/// \\file\r\n/// CODATA recommended values of fundamental physico-chemical constants\r\n/// CODATA 2014 values as of 2016/04/26\r\n\r\nnamespace boost {\r\n\r\nnamespace units { \r\n\r\nnamespace si {\r\n                            \r\nnamespace constants {\r\n\r\nnamespace codata {\r\n\r\n// PHYSICO-CHEMICAL\r\n/// Avogadro constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(N_A,quantity<inverse_amount>,6.022140857e23/mole,7.4e15/mole);\r\n/// atomic mass constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_u,quantity<mass>,1.660539040e-27*kilograms,2.0e-35*kilograms);\r\n/// Faraday constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(F,quantity<electric_charge_over_amount>,96485.33289*coulombs/mole,5.9e-4*coulombs/mole);\r\n/// molar gas constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(R,quantity<energy_over_temperature_amount>,8.3144598*joules/kelvin/mole,4.8e-06*joules/kelvin/mole);\r\n/// Boltzmann constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(k_B,quantity<energy_over_temperature>,1.38064852e-23*joules/kelvin,7.9e-30*joules/kelvin);\r\n/// Stefan-Boltzmann constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(sigma_SB,quantity<power_over_area_temperature_4>,5.670367e-8*watts/square_meter/pow<4>(kelvin),1.3e-13*watts/square_meter/pow<4>(kelvin));\r\n/// first radiation constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1,quantity<power_area>,3.741771790e-16*watt*square_meters,4.6e-24*watt*square_meters);\r\n/// first radiation constant for spectral radiance\r\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1L,quantity<power_area_over_solid_angle>,1.191042953e-16*watt*square_meters/steradian,1.5e-24*watt*square_meters/steradian);\r\n/// second radiation constant\r\nBOOST_UNITS_PHYSICAL_CONSTANT(c_2,quantity<length_temperature>,1.43877736e-2*meter*kelvin,8.3e-9*meter*kelvin);\r\n/// Wien displacement law constant : lambda_max T\r\nBOOST_UNITS_PHYSICAL_CONSTANT(b,quantity<length_temperature>,2.8977729e-3*meter*kelvin,1.7e-9*meter*kelvin);\r\n/// Wien displacement law constant : nu_max/T\r\nBOOST_UNITS_PHYSICAL_CONSTANT(b_prime,quantity<frequency_over_temperature>,5.8789238e10*hertz/kelvin,3.4e4*hertz/kelvin);\r\n\r\n} // namespace codata\r\n\r\n} // namespace constants    \r\n\r\n} // namespace si\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\r\n", "meta": {"hexsha": "cc7ffc0d2cba13ef4ec98b37389371052e3fb9e1", "size": 3355, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 41.9375, "max_line_length": 169, "alphanum_fraction": 0.7803278689, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906414693485, "lm_q2_score": 0.0758581784543034, "lm_q1q2_score": 0.0355616041382892}}
{"text": "#include \"grid_tools.hpp\"\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/lac/sparsity_pattern.h>\n\n#include <boost/lexical_cast.hpp>\n\nextern \"C\" {\n#include <metis.h>\n}\n\n#include <map>\n#include <vector>\n\nusing namespace dealii;\n\n//   Code taken from deal.II and adapted such that METIS takes\n//   the dense boundary blocks into account when partitioning the\n//   grid.\n\nnamespace boltzmann {\n\nnamespace {\n\n/**\n * Exception\n */\nDeclException1(ExcInvalidNumberOfPartitions,\n               int,\n               << \"The number of partitions you gave is \" << arg1\n               << \", but must be greater than zero.\");\n/**\n * Exception\n */\nDeclException1(ExcNonExistentSubdomain,\n               int,\n               << \"The subdomain id \" << arg1 << \" has no cells associated with it.\");\n/**\n * Exception\n */\nDeclException0(ExcTriangulationHasBeenRefined);\n\n/**\n * Exception\n */\nDeclException1(\n    ExcScalingFactorNotPositive, double, << \"The scaling factor must be positive, but is \" << arg1);\n/**\n * Exception\n */\ntemplate <int N>\nDeclException1(ExcPointNotFoundInCoarseGrid,\n               Point<N>,\n               << \"The point <\" << arg1 << \"> could not be found inside any of the \"\n               << \"coarse grid cells.\");\n/**\n * Exception\n */\ntemplate <int N>\nDeclException1(ExcPointNotFound,\n               Point<N>,\n               << \"The point <\" << arg1 << \"> could not be found inside any of the \"\n               << \"subcells of a coarse grid cell.\");\n\n/**\n * Exception\n */\nDeclException1(ExcVertexNotUsed,\n               unsigned int,\n               << \"The given vertex \" << arg1 << \" is not used in the given triangulation\");\n\nDeclException2(ExcInvalidArraySize,\n               int,\n               int,\n               << \"The array has size \" << arg1 << \" but should have size \" << arg2);\n\nstruct face_connectivity_of_cells\n{\n  typedef std::map<std::pair<unsigned int, unsigned int>, unsigned int> indexmap_t;\n\n  static void get(const dealii::Triangulation<2, 2>& triangulation,\n                  SparsityPattern& cell_connectivity,\n                  indexmap_t& indexmap)\n  {\n    // as built in this function, we only consider face neighbors, which leads\n    // to a fixed number of entries per row (don't forget that each cell couples\n    // with itself, and that neighbors can be refined)\n    cell_connectivity.reinit(\n        triangulation.n_active_cells(),\n        triangulation.n_active_cells(),\n        GeometryInfo<2>::faces_per_cell * GeometryInfo<2>::max_children_per_face + 1);\n\n    // create a map pair<lvl,idx> -> SparsityPattern index\n    // TODO: we are no longer using user_indices for this because we can get\n    // pointer/index clashes when saving/restoring them. The following approach\n    // works, but this map can get quite big. Not sure about more efficient solutions.\n    // std::map< std::pair<unsigned int,unsigned int>, unsigned int >\n    //   indexmap;\n    unsigned int index = 0;\n    for (typename dealii::internal::ActiveCellIterator<2, 2, Triangulation<2, 2> >::type\n             cell = triangulation.begin_active();\n         cell != triangulation.end();\n         ++cell, ++index)\n      indexmap[std::pair<unsigned int, unsigned int>(cell->level(), cell->index())] = index;\n\n    // next loop over all cells and their neighbors to build the sparsity\n    // pattern. note that it's a bit hard to enter all the connections when a\n    // neighbor has children since we would need to find out which of its\n    // children is adjacent to the current cell. this problem can be omitted if\n    // we only do something if the neighbor has no children -- in that case it\n    // is either on the same or a coarser level than we are. in return, we have\n    // to add entries in both directions for both cells\n    index = 0;\n    for (typename dealii::internal::ActiveCellIterator<2, 2, Triangulation<2, 2> >::type\n             cell = triangulation.begin_active();\n         cell != triangulation.end();\n         ++cell, ++index) {\n      cell_connectivity.add(index, index);\n      for (unsigned int f = 0; f < GeometryInfo<2>::faces_per_cell; ++f)\n        if ((cell->at_boundary(f) == false) && (cell->neighbor(f)->has_children() == false)) {\n          unsigned int other_index =\n              indexmap\n                  .find(std::pair<unsigned int, unsigned int>(cell->neighbor(f)->level(),\n                                                              cell->neighbor(f)->index()))\n                  ->second;\n          cell_connectivity.add(index, other_index);\n          cell_connectivity.add(other_index, index);\n        }\n    }\n\n    // now compress the so-built connectivity pattern\n    cell_connectivity.compress();\n  }\n};\n\n// ----------------------------------------------------------------------\nvoid partition(const SparsityPattern& sparsity_pattern,\n               const unsigned int n_partitions,\n               std::vector<unsigned int>& partition_indices,\n               std::vector<idx_t> cell_weights = {})\n{\n  Assert(sparsity_pattern.n_rows() == sparsity_pattern.n_cols(), ExcNotQuadratic());\n  Assert(sparsity_pattern.is_compressed(), SparsityPattern::ExcNotCompressed());\n\n  Assert(n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));\n  Assert(partition_indices.size() == sparsity_pattern.n_rows(),\n         ExcInvalidArraySize(partition_indices.size(), sparsity_pattern.n_rows()));\n\n  // check for an easy return\n  if (n_partitions == 1) {\n    std::fill_n(partition_indices.begin(), partition_indices.size(), 0U);\n    return;\n  }\n\n// Make sure that METIS is actually\n// installed and detected\n#ifndef DEAL_II_WITH_METIS\n  AssertThrow(false, ExcMETISNotInstalled());\n#else\n\n  // generate the data structures for\n  // METIS. Note that this is particularly\n  // simple, since METIS wants exactly our\n  // compressed row storage format. we only\n  // have to set up a few auxiliary arrays\n  idx_t n = static_cast<signed int>(sparsity_pattern.n_rows()),\n        ncon = 1,                               // number of balancing constraints (should be >0)\n      nparts = static_cast<int>(n_partitions),  // number of subdomains to create\n      dummy;                                    // the numbers of edges cut by the\n  // resulting partition\n\n  // use default options for METIS\n  idx_t options[METIS_NOPTIONS];\n  METIS_SetDefaultOptions(options);\n\n  // one more nuisance: we have to copy our\n  // own data to arrays that store signed\n  // integers :-(\n  std::vector<idx_t> int_rowstart(1);\n  int_rowstart.reserve(sparsity_pattern.n_rows() + 1);\n  std::vector<idx_t> int_colnums;\n  int_colnums.reserve(sparsity_pattern.n_nonzero_elements());\n  for (SparsityPattern::size_type row = 0; row < sparsity_pattern.n_rows(); ++row) {\n    for (SparsityPattern::iterator col = sparsity_pattern.begin(row);\n         col < sparsity_pattern.end(row);\n         ++col)\n      int_colnums.push_back(col->column());\n    int_rowstart.push_back(int_colnums.size());\n  }\n\n  std::vector<idx_t> int_partition_indices(sparsity_pattern.n_rows());\n\n  // Make use of METIS' error code.\n  int ierr;\n\n  // Select which type of partitioning to\n  // create\n\n  // Use recursive if the number of\n  // partitions is less than or equal to 8\n  // if (n_partitions <= 8)\n  //   ierr = METIS_PartGraphRecursive(&n, &ncon, &int_rowstart[0], &int_colnums[0],\n  //                                   cell_weights.data(), NULL, NULL,\n  //                                   &nparts,NULL,NULL,&options[0],\n  //                                   &dummy,&int_partition_indices[0]);\n\n  // // Otherwise use kway\n  // else\n  ierr = METIS_PartGraphKway(&n,\n                             &ncon,\n                             &int_rowstart[0],\n                             &int_colnums[0],\n                             cell_weights.data(),\n                             NULL,\n                             NULL,\n                             &nparts,\n                             NULL,\n                             NULL,\n                             &options[0],\n                             &dummy,\n                             &int_partition_indices[0]);\n  // ierr = METIS_PartGraphRecursive(&n, &ncon, &int_rowstart[0], &int_colnums[0],\n  //                                 cell_weights.data(), NULL, NULL,\n  //                                 &nparts,NULL,NULL,&options[0],\n  //                                 &dummy,&int_partition_indices[0]);\n\n  // If metis returns normally, an\n  // error code METIS_OK=1 is\n  // returned from the above\n  // functions (see metish.h)\n  if (ierr != 1) {\n    throw std::runtime_error(\"METIS-Error: \" + boost::lexical_cast<std::string>(ierr));\n  }\n  //  AssertThrow (ierr == 1, ExcMETISError (ierr));\n\n  // now copy back generated indices into the\n  // output array\n  std::copy(int_partition_indices.begin(), int_partition_indices.end(), partition_indices.begin());\n#endif\n}\n\n}  // end namespace\n\nvoid partition_triangulation(const unsigned int n_partitions,\n                             dealii::Triangulation<2, 2>& triangulation,\n                             const unsigned int cell_weight,\n                             const unsigned int cell_weight_bc)\n{\n  Assert(n_partitions > 0, ExcInvalidNumberOfPartitions(n_partitions));\n\n  // check for an easy return\n  if (n_partitions == 1) {\n    for (typename dealii::internal::ActiveCellIterator<2, 2, Triangulation<2, 2> >::type cell =\n             triangulation.begin_active();\n         cell != triangulation.end();\n         ++cell)\n      cell->set_subdomain_id(0);\n    return;\n  }\n\n  // we decompose the domain by first generating the connection graph of all\n  // cells with their neighbors, and then passing this graph off to METIS.\n  // finally defer to the other function for partitioning and assigning\n  // subdomain idsdealii::\n  dealii::SparsityPattern cell_connectivity;\n  typename face_connectivity_of_cells::indexmap_t cell_enumeration;\n  face_connectivity_of_cells::get(triangulation, cell_connectivity, cell_enumeration);\n\n  // check for an easy return\n  if (n_partitions == 1) {\n    for (typename dealii::internal::ActiveCellIterator<2, 2, Triangulation<2, 2> >::type cell =\n             triangulation.begin_active();\n         cell != triangulation.end();\n         ++cell)\n      cell->set_subdomain_id(0);\n    return;\n  }\n\n  std::vector<idx_t> cell_weights(triangulation.n_active_cells());\n  for (auto cell : triangulation.active_cell_iterators()) {\n    int nfaces = dealii::GeometryInfo<2>::faces_per_cell;\n    int count = 0;\n    for (int i = 0; i < nfaces; ++i)\n      if (cell->face(i)->at_boundary()) count++;\n\n    unsigned int index =\n        cell_enumeration.find(std::make_pair(cell->level(), cell->index()))->second;\n    if (count == 0) cell_weights[index] = cell_weight;\n    if (count > 0) cell_weights[index] = cell_weight_bc;\n  }\n\n  // partition this connection graph and get back a vector of indices, one per\n  // degree of freedom (which is associated with a cell)\n  std::vector<unsigned int> partition_indices(triangulation.n_active_cells());\n  partition(cell_connectivity, n_partitions, partition_indices, cell_weights);\n\n  // finally loop over all cells and set the subdomain ids\n  unsigned int index = 0;\n  for (typename dealii::internal::ActiveCellIterator<2, 2, Triangulation<2, 2> >::type\n           cell = triangulation.begin_active();\n       cell != triangulation.end();\n       ++cell, ++index)\n    cell->set_subdomain_id(partition_indices[index]);\n\n  // (end)\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "e154a1c61838e65c9d115f9ec19c4590372de915", "size": 11522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/grid/grid_tools.cpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/grid/grid_tools.cpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/grid/grid_tools.cpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9294871795, "max_line_length": 100, "alphanum_fraction": 0.6219406353, "num_tokens": 2685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101679412289653, "lm_q2_score": 0.07696083357893281, "lm_q1q2_score": 0.03548023676958537}}
{"text": "/* Copyright 2017-2018 PaGMO development team\n\nThis file is part of the PaGMO library.\n\nThe PaGMO library is free software; you can redistribute it and/or modify\nit under the terms of either:\n\n  * the GNU Lesser General Public License as published by the Free\n    Software Foundation; either version 3 of the License, or (at your\n    option) any later version.\n\nor\n\n  * the GNU General Public License as published by the Free Software\n    Foundation; either version 3 of the License, or (at your option) any\n    later version.\n\nor both in parallel, as here.\n\nThe PaGMO library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\nfor more details.\n\nYou should have received copies of the GNU General Public License and the\nGNU Lesser General Public License along with the PaGMO library.  If not,\nsee https://www.gnu.org/licenses/. */\n\n#ifndef PAGMO_UTILS_GENERIC_HPP\n#define PAGMO_UTILS_GENERIC_HPP\n\n#include <cassert>\n#include <cmath>\n#include <limits>\n#include <numeric>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <pagmo/detail/custom_comparisons.hpp>\n#include <pagmo/exceptions.hpp>\n#include <pagmo/problem.hpp>\n#include <pagmo/types.hpp>\n\nnamespace pagmo\n{\n\nnamespace detail\n{\n\n// Checks that all elements of the problem bounds are not equal\ninline bool some_bound_is_equal(const problem &prob)\n{\n    // Some variable renaming\n    const auto &lb = prob.get_lb();\n    const auto &ub = prob.get_ub();\n    // Since the bounds are extracted from problem we can be sure they have equal length\n    for (decltype(lb.size()) i = 0u; i < lb.size(); ++i) {\n        if (lb[i] == ub[i]) {\n            return true;\n        }\n    }\n    return false;\n}\n\n// Check that the lower/upper bounds lb/ub are suitable for the\n// generation of a real number. The boolean flags specify at\n// compile time which checks to run.\ntemplate <bool FiniteCheck, bool LbUbCheck, bool RangeCheck>\ninline void uniform_real_from_range_checks(double lb, double ub)\n{\n    // NOTE: see here for the requirements for floating-point RNGS:\n    // http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution/uniform_real_distribution\n\n    // 0 - Forbid random generation when bounds are not finite.\n    if (FiniteCheck) {\n        if (!std::isfinite(lb) || !std::isfinite(ub)) {\n            pagmo_throw(std::invalid_argument, \"Cannot generate a random real if the bounds are not finite\");\n        }\n    } else {\n        assert(std::isfinite(lb) && std::isfinite(ub));\n    }\n\n    // 1 - Check that lb is <= ub\n    if (LbUbCheck) {\n        if (lb > ub) {\n            pagmo_throw(std::invalid_argument,\n                        \"Cannot generate a random real if the lower bound is larger than the upper bound\");\n        }\n    } else {\n        assert(lb <= ub);\n    }\n\n    // 2 - Bounds cannot be too large\n    if (RangeCheck) {\n        const auto delta = ub - lb;\n        if (!std::isfinite(delta) || delta > std::numeric_limits<double>::max()) {\n            pagmo_throw(std::invalid_argument, \"Cannot generate a random real within bounds that are too large\");\n        }\n    } else {\n        assert(std::isfinite(ub - lb) && (ub - lb) <= std::numeric_limits<double>::max());\n    }\n}\n\n// Implementation of the uniform_real_from_range() function.\ntemplate <bool FiniteCheck, bool LbUbCheck, bool RangeCheck, typename Rng>\ninline double uniform_real_from_range_impl(double lb, double ub, Rng &r_engine)\n{\n    // Run the checks on the bounds.\n    uniform_real_from_range_checks<FiniteCheck, LbUbCheck, RangeCheck>(lb, ub);\n    // If the bounds are equal we don't call the RNG, as that would be undefined behaviour.\n    return (lb == ub) ? lb : std::uniform_real_distribution<double>(lb, ub)(r_engine);\n}\n\n// Check that the lower/upper bounds lb/ub are suitable for the\n// generation of an integral number. The boolean flags specify at\n// compile time which checks to run.\ntemplate <bool FiniteCheck, bool LbUbCheck, bool IntCheck>\ninline void uniform_integral_from_range_checks(double lb, double ub)\n{\n    // 0 - Check for finite bounds.\n    if (FiniteCheck) {\n        if (!std::isfinite(lb) || !std::isfinite(ub)) {\n            pagmo_throw(std::invalid_argument, \"Cannot generate a random integer if the bounds are not finite\");\n        }\n    } else {\n        assert(std::isfinite(lb) && std::isfinite(ub));\n    }\n\n    // 1 - Check that lb is <= ub\n    if (LbUbCheck) {\n        if (lb > ub) {\n            pagmo_throw(std::invalid_argument,\n                        \"Cannot generate a random integer if the lower bound is larger than the upper bound\");\n        }\n    } else {\n        assert(lb <= ub);\n    }\n\n    // 2 - Check that lb/ub are integral values.\n    if (IntCheck) {\n        if (std::trunc(lb) != lb || std::trunc(ub) != ub) {\n            pagmo_throw(std::invalid_argument,\n                        \"Cannot generate a random integer if the lower/upper bounds are not integral values\");\n        }\n    } else {\n        assert(std::trunc(lb) == lb && std::trunc(ub) == ub);\n    }\n}\n\n// Implementation of the uniform_integral_from_range() function.\ntemplate <bool FiniteCheck, bool LbUbCheck, bool IntCheck, typename Rng>\ninline double uniform_integral_from_range_impl(double lb, double ub, Rng &r_engine)\n{\n    // Run the checks on the bounds.\n    uniform_integral_from_range_checks<FiniteCheck, LbUbCheck, IntCheck>(lb, ub);\n    // We will convert ub/lb to the widest signed integral type possible (long long),\n    // do the generation using uniform_int_distribution, and finally convert back the\n    // result to double precision.\n    // NOTE: the use of numeric_cast ensures that the conversion to long long is checked\n    // (in case of overflow, an exception will be thrown).\n    long long l, u;\n    try {\n        l = boost::numeric_cast<long long>(lb);\n        u = boost::numeric_cast<long long>(ub);\n    } catch (...) {\n        pagmo_throw(std::invalid_argument, \"Cannot generate a random integer if the lower/upper bounds are not within \"\n                                           \"the bounds of the long long type\");\n    }\n    // NOTE: it should be safe here to do a raw cast, as the result\n    // will be within the original bounds and thus representable by double.\n    return static_cast<double>(std::uniform_int_distribution<long long>(l, u)(r_engine));\n}\n\n} // namespace detail\n\n/// Generate a random integral number within some lower and upper bounds\n/**\n * This function will create a random integral number within a closed range. If\n * both the lower and upper bounds are finite numbers, then the generated value\n * \\f$ x \\f$ will be such that \\f$lb \\le x \\le ub\\f$.\n *\n * Example:\n *\n * @code{.unparsed}\n * std::mt19937 r_engine(32u);\n * auto x = uniform_integral_from_range(3,5,r_engine); // one of [3, 4, 5].\n * auto x = uniform_integral_from_range(2,2,r_engine); // the value 2.\n * @endcode\n *\n * \\verbatim embed:rst:leading-asterisk\n * .. note::\n *\n *    The return value is created internally via an integral random number\n *    generator based on the ``long long`` type, and then cast back to ``double``.\n *    Thus, if the absolute values of the lower/upper bounds are large enough, any of\n *    the following may happen:\n *\n *    * the conversion of the lower/upper bounds to ``long long`` may produce an overflow error,\n *    * the conversion of the randomly-generated ``long long`` integer back to ``double`` may yield an\n *      inexact result.\n *\n *    In pratice, on modern mainstream computer architectures, this function will produce uniformly-distributed\n *    integral values as long as the absolute values of the bounds do not exceed :math:`2^{53}`.\n *\n * \\endverbatim\n *\n * @param lb lower bound\n * @param ub upper bound\n * @param r_engine a C++ random engine\n *\n * @throws std::invalid_argument if:\n * - the bounds are not finite,\n * - \\f$ lb > ub \\f$,\n * - \\f$ lb \\f$ and/or \\f$ ub \\f$ are not integral values,\n * - \\f$ lb \\f$ and/or \\f$ ub \\f$ are not within the bounds of the ``long long`` type.\n *\n * @returns a random integral value\n */\ntemplate <typename Rng>\ninline double uniform_integral_from_range(double lb, double ub, Rng &r_engine)\n{\n    // Activate all checks on lb/ub.\n    return detail::uniform_integral_from_range_impl<true, true, true>(lb, ub, r_engine);\n}\n\ntemplate <typename Rng>\ninline int uniform_integral_from_range_cm(int lb, int ub, Rng& r_engine)\n{\n\tlong long l, u;\n\ttry {\n\t\tl = boost::numeric_cast<long long>(lb);\n\t\tu = boost::numeric_cast<long long>(ub);\n\t}\n\tcatch (...) {\n\t\tpagmo_throw(std::invalid_argument, \"Cannot generate a random integer if the lower/upper bounds are not within \"\n\t\t\t\"the bounds of the long long type\");\n\t}\n\treturn static_cast<int>(std::uniform_int_distribution<long long>(l, u)(r_engine));\n}\n\n/// Generate a random real number within some lower and upper bounds\n/**\n * This function will create a random real number within a half-open range. If\n * both the lower and upper bounds are finite numbers, then the generated value\n * \\f$ x \\f$ will be such that \\f$lb \\le x < ub\\f$. If \\f$lb = ub\\f$, then \\f$lb\\f$ is\n * returned.\n *\n * Example:\n *\n * @code{.unparsed}\n * std::mt19937 r_engine(32u);\n * auto x = uniform_real_from_range(3,5,r_engine); // a random real in the [3, 5) range.\n * auto x = uniform_real_from_range(2,2,r_engine); // the value 2.\n * @endcode\n *\n * @param lb lower bound\n * @param ub upper bound\n * @param r_engine a C++ random engine\n *\n * @throws std::invalid_argument if:\n * - the bounds are not finite,\n * - \\f$ lb > ub \\f$,\n * - \\f$ ub - lb \\f$ is larger than an implementation-defined value.\n *\n * @returns a random floating-point value\n */\ntemplate <typename Rng>\ninline double uniform_real_from_range(double lb, double ub, Rng &r_engine)\n{\n    // Activate all checks on lb/ub.\n    return detail::uniform_real_from_range_impl<true, true, true>(lb, ub, r_engine);\n}\n\n/// Generate a random decision vector compatible with a problem\n/**\n * This function will generate a decision vector whose values\n * are randomly chosen with uniform probability within\n * the input problem's bounds.\n *\n * For the continuous part of the decision vector, the values will be\n * generated via pagmo::uniform_real_from_range().\n *\n * For the discrete part of the decision vector, the values will be generated\n * via pagmo::uniform_integral_from_range().\n *\n * @param prob the input pagmo::problem\n * @param r_engine a C++ random engine\n *\n * @throws unspecified any exception thrown by pagmo::uniform_real_from_range() or pagmo::uniform_integral_from_range().\n *\n * @returns a pagmo::vector_double containing a random decision vector\n */\ntemplate <typename Rng>\ninline vector_double random_decision_vector(const problem &prob, Rng &r_engine)\n{\n    // Prepare the return value.\n    vector_double out(prob.get_nx());\n\n    // Fetch a few quantities from prob.\n    const auto nx = prob.get_nx();\n    const auto ncx = nx - prob.get_nix();\n    const auto &lb = prob.get_lb();\n    const auto &ub = prob.get_ub();\n\n    // Continuous part.\n    for (vector_double::size_type i = 0u; i < ncx; ++i) {\n        // NOTE: the lb<=ub check is not needed, as it is ensured by the problem class.\n        // Still need to check for finiteness and range.\n        out[i] = detail::uniform_real_from_range_impl<true, false, true>(lb[i], ub[i], r_engine);\n    }\n\n    // Integer part.\n    for (auto i = ncx; i < nx; ++i) {\n        // NOTE: the lb<=ub check and the check that lb/ub are integral values are not needed,\n        // as they are ensured by the problem class.\n        // Still need to check for finiteness.\n        out[i] = detail::uniform_integral_from_range_impl<true, false, false>(lb[i], ub[i], r_engine);\n    }\n\n    return out;\n}\n\n/// Generate a batch of random decision vectors compatible with a problem\n/**\n * This function will generate \\p n decision vectors whose values\n * are randomly chosen with uniform probability within\n * the input problem's bounds. The decision vectors are laid\n * out contiguously in the return value: for a problem with dimension \\f$ d \\f$,\n * the first decision vector in the return value occupies\n * the index range \\f$ \\left[0, d\\right) \\f$, the second decision vector occupies the range\n * \\f$ \\left[d, 2d\\right) \\f$, and so on.\n *\n * For the continuous parts of the decision vectors, the values will be\n * generated via pagmo::uniform_real_from_range().\n *\n * For the discrete parts of the decision vectors, the values will be generated\n * via pagmo::uniform_integral_from_range().\n *\n * @param prob the input pagmo::problem\n * @param n how many decision vectors will be generated\n * @param r_engine a C++ random engine\n *\n * @throws std::overflow_error in case of (unlikely) overflow errors.\n * @throws unspecified any exception thrown by pagmo::uniform_real_from_range() or pagmo::uniform_integral_from_range().\n *\n * @returns a pagmo::vector_double containing \\p n random decision vectors\n */\ntemplate <typename Rng>\ninline vector_double batch_random_decision_vector(const problem &prob, vector_double::size_type n, Rng &r_engine)\n{\n    // NOTE: it is possible in principle to do this in a parallel fashion, e.g., see code\n    // at the commit 13d4182a41e4e71034c6e1085699c5138805d21c. The price to pay however is\n    // the loss of determinism. We can reconsider in the future whether it's worth it\n    // to add an option to this constructor, e.g., par_random, defaulting to false.\n\n    // Fetch a few quantities from prob.\n    const auto nx = prob.get_nx();\n    const auto ncx = nx - prob.get_nix();\n    const auto &lb = prob.get_lb();\n    const auto &ub = prob.get_ub();\n\n    // LCOV_EXCL_START\n    if (n > std::numeric_limits<vector_double::size_type>::max() / nx) {\n        pagmo_throw(std::overflow_error,\n                    \"Cannot generate \" + std::to_string(n)\n                        + \" random decision vectors in batch mode, as that would result in an overflow error\");\n    }\n    // LCOV_EXCL_STOP\n\n    // Check the problem bounds.\n    for (vector_double::size_type i = 0u; i < ncx; ++i) {\n        // NOTE: the lb<=ub check is not needed, as it is ensured by the problem class.\n        // Still need to check for finiteness and range.\n        detail::uniform_real_from_range_checks<true, false, true>(lb[i], ub[i]);\n    }\n    for (auto i = ncx; i < nx; ++i) {\n        // NOTE: the lb<=ub check and the check that lb/ub are integral values are not needed,\n        // as they are ensured by the problem class.\n        // Still need to check for finiteness.\n        detail::uniform_integral_from_range_checks<true, false, false>(lb[i], ub[i]);\n        try {\n            // Check that the bounds can be converted safely to long long.\n            boost::numeric_cast<long long>(lb[i]);\n            boost::numeric_cast<long long>(ub[i]);\n        } catch (...) {\n            pagmo_throw(std::invalid_argument,\n                        \"Cannot generate a random integer if the lower/upper bounds are not within \"\n                        \"the bounds of the long long type\");\n        }\n    }\n\n    // Prepare the return value.\n    vector_double out(nx * n);\n\n    // Proceed to the random number generation.\n    std::uniform_real_distribution<double> rdist;\n    std::uniform_int_distribution<long long> idist;\n    for (vector_double::size_type i = 0; i < out.size(); i += nx) {\n        for (vector_double::size_type j = 0; j < ncx; ++j) {\n            out[i + j] = (lb[j] == ub[j])\n                             ? lb[j]\n                             : rdist(r_engine, std::uniform_real_distribution<double>::param_type(lb[j], ub[j]));\n        }\n        for (vector_double::size_type j = ncx; j < nx; ++j) {\n            out[i + j] = static_cast<double>(\n                idist(r_engine, std::uniform_int_distribution<long long>::param_type(static_cast<long long>(lb[j]),\n                                                                                     static_cast<long long>(ub[j]))));\n        }\n    }\n\n    return out;\n}\n\n/// Binomial coefficient\n/**\n * An implementation of the binomial coefficient using gamma functions\n * @param  n first parameter \\f$n\\f$\n * @param  k second paramater \\f$k\\f$\n * @return the binomial coefficient \\f$ n \\choose k \\f$\n */\ninline double binomial_coefficient(vector_double::size_type n, vector_double::size_type k)\n{\n    if (k <= n) {\n        return std::round(std::exp(std::lgamma(static_cast<double>(n) + 1.) - std::lgamma(static_cast<double>(k) + 1.)\n                                   - std::lgamma(static_cast<double>(n) - static_cast<double>(k) + 1.)));\n    } else {\n        pagmo_throw(std::invalid_argument, \"The binomial coefficient is only defined for k<=n, you requested n=\"\n                                               + std::to_string(n) + \" and k=\" + std::to_string(k));\n    }\n}\n\n/// K-Nearest Neighbours\n/**\n * Computes the indexes of the k nearest neighbours (euclidean distance) to each of the input points.\n * The algorithm complexity (naive implementation) is \\f$ O(MN^2)\\f$ where \\f$N\\f$ is the number of\n * points and \\f$M\\f$ their dimensionality\n *\n * Example:\n * @code{.unparsed}\n * auto res = kNN({{1, 1}, {2, 2}, {3.1, 3.1}, {5, 5}}, 2u);\n * @endcode\n *\n * @param points the \\f$N\\f$ points having dimension \\f$M\\f$\n * @param k number of neighbours to detect\n * @return An <tt>std::vector<std::vector<population::size_type> > </tt> containing the indexes of the k nearest\n * neighbours sorted by distance\n * @throws std::invalid_argument If the points do not all have the same dimension.\n */\ninline std::vector<std::vector<vector_double::size_type>> kNN(const std::vector<vector_double> &points,\n                                                              std::vector<vector_double>::size_type k)\n{\n    std::vector<std::vector<vector_double::size_type>> neigh_idxs;\n    auto N = points.size();\n    if (N == 0u) {\n        return {};\n    }\n    auto M = points[0].size();\n    if (!std::all_of(points.begin(), points.end(), [M](const vector_double &p) { return p.size() == M; })) {\n        pagmo_throw(std::invalid_argument, \"All points must have the same dimensionality for k-NN to be invoked\");\n    }\n    // loop through the points\n    for (decltype(N) i = 0u; i < N; ++i) {\n        // We compute all the distances to all other points including the self\n        vector_double distances;\n        for (decltype(N) j = 0u; j < N; ++j) {\n            double dist = 0.;\n            for (decltype(M) l = 0u; l < M; ++l) {\n                dist += (points[i][l] - points[j][l]) * (points[i][l] - points[j][l]);\n            }\n            distances.push_back(std::sqrt(dist));\n        }\n        // We sort the indexes with respect to the distance\n        std::vector<vector_double::size_type> idxs(N);\n        std::iota(idxs.begin(), idxs.end(), vector_double::size_type(0u));\n        std::sort(idxs.begin(), idxs.end(), [&distances](vector_double::size_type idx1, vector_double::size_type idx2) {\n            return detail::less_than_f(distances[idx1], distances[idx2]);\n        });\n        // We remove the first element containg the self-distance (0)\n        idxs.erase(std::remove(idxs.begin(), idxs.end(), i), idxs.end());\n        neigh_idxs.push_back(idxs);\n    }\n    // We trim to k the lists if needed\n    if (k < N - 1u) {\n        for (decltype(neigh_idxs.size()) i = 0u; i < neigh_idxs.size(); ++i) {\n            neigh_idxs[i].erase(neigh_idxs[i].begin() + static_cast<int>(k),\n                                neigh_idxs[i].end()); // TODO: remove the static_cast\n        }\n    }\n    return neigh_idxs;\n}\n\nnamespace detail\n{\n// modifies a chromosome so that it will be in the bounds. elements that are off are resampled at random in the bounds\ntemplate <typename Rng>\ninline void force_bounds_random(vector_double &x, const vector_double &lb, const vector_double &ub, Rng &r_engine)\n{\n    assert(x.size() == lb.size());\n    assert(x.size() == ub.size());\n    for (decltype(x.size()) j = 0u; j < x.size(); ++j) {\n        if ((x[j] < lb[j]) || (x[j] > ub[j])) {\n            x[j] = pagmo::uniform_real_from_range(lb[j], ub[j], r_engine);\n        }\n    }\n}\n// modifies a chromosome so that it will be in the bounds. Elements that are off are reflected in the bounds\ninline void force_bounds_reflection(vector_double &x, const vector_double &lb, const vector_double &ub)\n{\n    assert(x.size() == lb.size());\n    assert(x.size() == ub.size());\n    for (decltype(x.size()) j = 0u; j < x.size(); ++j) {\n        while (x[j] < lb[j] || x[j] > ub[j]) {\n            if (x[j] < lb[j]) {\n                x[j] = 2 * lb[j] - x[j];\n            }\n            if (x[j] > ub[j]) {\n                x[j] = 2 * ub[j] - x[j];\n            }\n        }\n    }\n}\n// modifies a chromosome so that it will be in the bounds. Elements that are off are set on the bounds\ninline void force_bounds_stick(vector_double &x, const vector_double &lb, const vector_double &ub)\n{\n    assert(x.size() == lb.size());\n    assert(x.size() == ub.size());\n    for (decltype(x.size()) j = 0u; j < x.size(); ++j) {\n        if (x[j] < lb[j]) {\n            x[j] = lb[j];\n        }\n        if (x[j] > ub[j]) {\n            x[j] = ub[j];\n        }\n    }\n}\n} // namespace detail\n\n} // namespace pagmo\n\n#endif\n", "meta": {"hexsha": "071ff82de35b5966419a391e22804c8b9f000e50", "size": 21263, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Gui/pagmo/utils/generic.hpp", "max_stars_repo_name": "haisenzhao/CarpentryCompiler", "max_stars_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-06T09:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T12:58:09.000Z", "max_issues_repo_path": "Gui/pagmo/utils/generic.hpp", "max_issues_repo_name": "haisenzhao/CarpentryCompiler", "max_issues_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gui/pagmo/utils/generic.hpp", "max_forks_repo_name": "haisenzhao/CarpentryCompiler", "max_forks_repo_head_hexsha": "c9714310b7ce7523a25becd397265bfaa3ab7ea3", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-18T00:09:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T04:40:47.000Z", "avg_line_length": 38.9432234432, "max_line_length": 120, "alphanum_fraction": 0.6454404364, "num_tokens": 5376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.087563838927784, "lm_q1q2_score": 0.0353378629770769}}
{"text": "//\r\n//=======================================================================\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// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, University of Notre Dame, Notre\r\n// Dame, IN 46556.\r\n//\r\n// Permission to modify the code and to distribute modified code is\r\n// granted, provided the text of this NOTICE is retained, a notice that\r\n// the code was modified is included with the above COPYRIGHT NOTICE and\r\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\r\n// file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n//\r\n//\r\n// Revision History:\r\n//   04 April 2001: Added named parameter variant. (Jeremy Siek)\r\n//   01 April 2001: Modified to use new <boost/limits.hpp> header. (JMaddock)\r\n//\r\n#ifndef BOOST_GRAPH_DIJKSTRA_HPP\r\n#define BOOST_GRAPH_DIJKSTRA_HPP\r\n\r\n#include <functional>\r\n#include <boost/limits.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include <boost/pending/mutable_queue.hpp>\r\n#include <boost/graph/relax.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/graph/exception.hpp>\r\n\r\nnamespace boost {\r\n\r\n  template <class Visitor, class Graph>\r\n  struct DijkstraVisitorConcept {\r\n    void constraints() {\r\n      function_requires< CopyConstructibleConcept<Visitor> >();\r\n      vis.discover_vertex(u, g);\r\n      vis.examine_vertex(u, g);\r\n      vis.examine_edge(e, g);\r\n      vis.edge_relaxed(e, g);\r\n      vis.edge_not_relaxed(e, g);\r\n      vis.finish_vertex(u, g);\r\n    }\r\n    Visitor vis;\r\n    Graph g;\r\n    typename graph_traits<Graph>::vertex_descriptor u;\r\n    typename graph_traits<Graph>::edge_descriptor e;\r\n  };\r\n\r\n  template <class Visitors = null_visitor>\r\n  class dijkstra_visitor : public bfs_visitor<Visitors> {\r\n  public:\r\n    dijkstra_visitor() { }\r\n    dijkstra_visitor(Visitors vis)\r\n      : bfs_visitor<Visitors>(vis) { }\r\n\r\n    template <class Edge, class Graph>\r\n    void edge_relaxed(Edge e, Graph& g) {\r\n      invoke_visitors(this->m_vis, e, g, on_edge_relaxed());      \r\n    }\r\n    template <class Edge, class Graph>\r\n    void edge_not_relaxed(Edge e, Graph& g) {\r\n      invoke_visitors(this->m_vis, e, g, on_edge_not_relaxed());      \r\n    }\r\n  private:\r\n    template <class Edge, class Graph>\r\n    void tree_edge(Edge u, Graph& g) { }\r\n  };\r\n  template <class Visitors>\r\n  dijkstra_visitor<Visitors>\r\n  make_dijkstra_visitor(Visitors vis) {\r\n    return dijkstra_visitor<Visitors>(vis);\r\n  }\r\n  typedef dijkstra_visitor<> default_dijkstra_visitor;\r\n\r\n  namespace detail {\r\n\r\n    template <class UniformCostVisitor, class UpdatableQueue,\r\n      class WeightMap, class PredecessorMap, class DistanceMap,\r\n      class BinaryFunction, class BinaryPredicate>\r\n    struct dijkstra_bfs_visitor\r\n    {\r\n      typedef typename property_traits<DistanceMap>::value_type D;\r\n\r\n      dijkstra_bfs_visitor(UniformCostVisitor vis, UpdatableQueue& Q,\r\n                           WeightMap w, PredecessorMap p, DistanceMap d, \r\n                           BinaryFunction combine, BinaryPredicate compare,\r\n                           D zero)\r\n        : m_vis(vis), m_Q(Q), m_weight(w), m_predecessor(p), m_distance(d), \r\n          m_combine(combine), m_compare(compare), m_zero(zero)  { }\r\n\r\n      template <class Edge, class Graph>\r\n      void tree_edge(Edge e, Graph& g) {\r\n        m_decreased = relax(e, g, m_weight, m_predecessor, m_distance, \r\n                            m_combine, m_compare);\r\n        if (m_decreased)\r\n          m_vis.edge_relaxed(e, g);\r\n        else\r\n          m_vis.edge_not_relaxed(e, g);\r\n      }\r\n      template <class Edge, class Graph>\r\n      void gray_target(Edge e, Graph& g) {\r\n        m_decreased = relax(e, g, m_weight, m_predecessor, m_distance, \r\n                            m_combine, m_compare);\r\n        if (m_decreased) {\r\n          m_Q.update(target(e, g));\r\n          m_vis.edge_relaxed(e, g);\r\n        } else\r\n          m_vis.edge_not_relaxed(e, g);\r\n      }\r\n\r\n      template <class Vertex, class Graph>\r\n      void initialize_vertex(Vertex u, Graph& g)\r\n        { m_vis.initialize_vertex(u, g); }\r\n      template <class Edge, class Graph>\r\n      void non_tree_edge(Edge, Graph&) { }\r\n      template <class Vertex, class Graph>\r\n      void discover_vertex(Vertex u, Graph& g) { m_vis.discover_vertex(u, g); }\r\n      template <class Vertex, class Graph>\r\n      void examine_vertex(Vertex u, Graph& g) { m_vis.examine_vertex(u, g); }\r\n      template <class Edge, class Graph>\r\n      void examine_edge(Edge e, Graph& g) { \r\n        if (m_compare(get(m_weight, e), m_zero))\r\n          throw negative_edge();\r\n        m_vis.examine_edge(e, g);\r\n      }\r\n      template <class Edge, class Graph>\r\n      void black_target(Edge, Graph&) { }\r\n      template <class Vertex, class Graph>\r\n      void finish_vertex(Vertex u, Graph& g) { m_vis.finish_vertex(u, g); }\r\n\r\n      UniformCostVisitor m_vis;\r\n      UpdatableQueue& m_Q;\r\n      WeightMap m_weight;\r\n      PredecessorMap m_predecessor;\r\n      DistanceMap m_distance;\r\n      BinaryFunction m_combine;\r\n      BinaryPredicate m_compare;\r\n      bool m_decreased;\r\n      D m_zero;\r\n    };\r\n\r\n  } // namespace detail\r\n\r\n  // Initalize distances and call breadth first search\r\n  template <class VertexListGraph, class DijkstraVisitor, \r\n            class PredecessorMap, class DistanceMap,\r\n            class WeightMap, class IndexMap, class Compare, class Combine, \r\n            class DistZero>\r\n  inline void\r\n  dijkstra_shortest_paths_no_init\r\n    (const VertexListGraph& g,\r\n     typename graph_traits<VertexListGraph>::vertex_descriptor s, \r\n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight, \r\n     IndexMap index_map,\r\n     Compare compare, Combine combine, DistZero zero,\r\n     DijkstraVisitor vis)\r\n  {\r\n    typedef indirect_cmp<DistanceMap, Compare> IndirectCmp;\r\n    IndirectCmp icmp(distance, compare);\r\n\r\n    typedef typename graph_traits<VertexListGraph>::vertex_descriptor Vertex;\r\n    typedef mutable_queue<Vertex, std::vector<Vertex>, IndirectCmp, IndexMap>\r\n      MutableQueue;\r\n\r\n    MutableQueue Q(num_vertices(g), icmp, index_map);\r\n\r\n    detail::dijkstra_bfs_visitor<DijkstraVisitor, MutableQueue, WeightMap,\r\n      PredecessorMap, DistanceMap, Combine, Compare>\r\n        bfs_vis(vis, Q, weight, predecessor, distance, combine, compare, zero);\r\n\r\n    std::vector<default_color_type> color(num_vertices(g));\r\n    default_color_type c = white_color;\r\n    breadth_first_visit(g, s, Q, bfs_vis,\r\n      make_iterator_property_map(&color[0], index_map, c));\r\n  }\r\n\r\n\r\n  // Initalize distances and call breadth first search\r\n  template <class VertexListGraph, class DijkstraVisitor, \r\n            class PredecessorMap, class DistanceMap,\r\n            class WeightMap, class IndexMap, class Compare, class Combine, \r\n            class DistInf, class DistZero>\r\n  inline void\r\n  dijkstra_shortest_paths\r\n    (const VertexListGraph& g,\r\n     typename graph_traits<VertexListGraph>::vertex_descriptor s, \r\n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight, \r\n     IndexMap index_map,\r\n     Compare compare, Combine combine, DistInf inf, DistZero zero,\r\n     DijkstraVisitor vis)\r\n  {\r\n    typename graph_traits<VertexListGraph>::vertex_iterator ui, ui_end;\r\n    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\r\n      put(distance, *ui, inf);\r\n      put(predecessor, *ui, *ui);\r\n    }\r\n    put(distance, s, zero);\r\n\r\n    dijkstra_shortest_paths_no_init(g, s, predecessor, distance, weight,\r\n                            index_map, compare, combine, zero, vis);\r\n  }\r\n\r\n  namespace detail {\r\n\r\n    // Handle defaults for PredecessorMap and \r\n    // Distance Compare, Combine, Inf and Zero\r\n    template <class VertexListGraph, class DistanceMap, class WeightMap,\r\n              class IndexMap, class Params>\r\n    inline void\r\n    dijkstra_dispatch2\r\n      (const VertexListGraph& g,\r\n       typename graph_traits<VertexListGraph>::vertex_descriptor s, \r\n       DistanceMap distance, WeightMap weight, IndexMap index_map,\r\n       const Params& params)\r\n    {\r\n      // Default for predecessor map\r\n      dummy_property_map p_map;\r\n\r\n      typedef typename property_traits<DistanceMap>::value_type D;\r\n      dijkstra_shortest_paths\r\n        (g, s, \r\n         choose_param(get_param(params, vertex_predecessor), p_map),\r\n         distance, weight, index_map, \r\n         choose_param(get_param(params, distance_compare_t()), \r\n                      std::less<D>()),\r\n         choose_param(get_param(params, distance_combine_t()), \r\n                      closed_plus<D>()),\r\n         choose_param(get_param(params, distance_inf_t()), \r\n                      (std::numeric_limits<D>::max)()),\r\n         choose_param(get_param(params, distance_zero_t()), \r\n                      D()),\r\n         choose_param(get_param(params, graph_visitor),\r\n                      make_dijkstra_visitor(null_visitor())));\r\n    }\r\n\r\n    template <class VertexListGraph, class DistanceMap, class WeightMap, \r\n              class IndexMap, class Params>\r\n    inline void\r\n    dijkstra_dispatch1\r\n      (const VertexListGraph& g,\r\n       typename graph_traits<VertexListGraph>::vertex_descriptor s, \r\n       DistanceMap distance, WeightMap weight, IndexMap index_map,\r\n       const Params& params)\r\n    {\r\n      // Default for distance map\r\n      typedef typename property_traits<WeightMap>::value_type D;\r\n      typename std::vector<D>::size_type \r\n        n = is_default_param(distance) ? num_vertices(g) : 1;\r\n      std::vector<D> distance_map(n);\r\n\r\n      detail::dijkstra_dispatch2\r\n        (g, s, choose_param(distance, make_iterator_property_map\r\n                            (distance_map.begin(), index_map, \r\n                             distance_map[0])),\r\n         weight, index_map, params);\r\n    }\r\n  } // namespace detail\r\n\r\n  // Named Parameter Variant\r\n  template <class VertexListGraph, class Param, class Tag, class Rest>\r\n  inline void\r\n  dijkstra_shortest_paths\r\n    (const VertexListGraph& g,\r\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\r\n     const bgl_named_params<Param,Tag,Rest>& params)\r\n  {\r\n    // Default for edge weight and vertex index map is to ask for them\r\n    // from the graph.  Default for the visitor is null_visitor.\r\n    detail::dijkstra_dispatch1\r\n      (g, s, \r\n       get_param(params, vertex_distance),\r\n       choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\r\n       choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n       params);\r\n  }\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_DIJKSTRA_HPP\r\n", "meta": {"hexsha": "c01fa7b7314bddc304ab8ce3f32bb62458043c61", "size": 11298, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/dijkstra_shortest_paths.hpp", "max_stars_repo_name": "macaurther/DOCUSA", "max_stars_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/dijkstra_shortest_paths.hpp", "max_issues_repo_name": "macaurther/DOCUSA", "max_issues_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/dijkstra_shortest_paths.hpp", "max_forks_repo_name": "dguenms/Dawn-of-Civilization", "max_forks_repo_head_hexsha": "1c4f510af97a869637cddb4c0859759158cea5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 38.4285714286, "max_line_length": 80, "alphanum_fraction": 0.6501150646, "num_tokens": 2579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.07921032791293581, "lm_q1q2_score": 0.035290540565382375}}
{"text": "// This file is part of the dune-gdt project:\n//   https://github.com/dune-community/dune-gdt\n// Copyright 2010-2017 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 (2014 - 2017)\n//   Rene Milk       (2016 - 2017)\n//   Tobias Leibner  (2014)\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/xt/common/exceptions.hh>\n#include <dune/xt/common/fvector.hh>\n#include <dune/xt/common/fmatrix.hh>\n#include <dune/xt/common/type_traits.hh>\n#include <dune/xt/grid/type_traits.hh>\n#include <dune/xt/functions/interfaces.hh>\n#include <dune/xt/la/container.hh>\n#include <dune/xt/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 {\n\n\n// forward, to be used in the traits\ntemplate <class GridLayerImp, class FunctionImp>\nclass DarcyOperator;\n\n\nnamespace internal {\n\n\ntemplate <class GridLayerImp, class FunctionImp>\nclass DarcyOperatorTraits\n{\n  static_assert(XT::Functions::is_localizable_function<FunctionImp>::value,\n                \"FunctionImp has to be derived from XT::Functions::is_localizable_function!\");\n  static_assert(std::is_same<typename GridLayerImp::ctype, typename FunctionImp::DomainFieldType>::value,\n                \"Types do not match!\");\n  static_assert(GridLayerImp::dimension == FunctionImp::dimDomain, \"Dimensions do not match!\");\n  static_assert(FunctionImp::dimRange == FunctionImp::dimRangeCols, \"Dimensions do not match!\");\n\npublic:\n  typedef DarcyOperator<GridLayerImp, FunctionImp> derived_type;\n  typedef GridLayerImp GridLayerType;\n  typedef typename FunctionImp::RangeFieldType FieldType;\n  typedef NoJacobian JacobianType;\n}; // class DarcyOperatorTraits\n\n\n} // namespace internal\n\n\n/**\n  * \\note Only works for scalar valued function atm.\n  * \\todo add make_darcy_operator\n  **/\ntemplate <class GridLayerImp, class FunctionImp>\nclass DarcyOperator : public OperatorInterface<internal::DarcyOperatorTraits<GridLayerImp, FunctionImp>>\n{\n  typedef OperatorInterface<internal::DarcyOperatorTraits<GridLayerImp, FunctionImp>> BaseType;\n\npublic:\n  typedef internal::DarcyOperatorTraits<GridLayerImp, FunctionImp> Traits;\n  typedef typename Traits::GridLayerType GridLayerType;\n  typedef typename Traits::FieldType FieldType;\n  typedef typename Traits::JacobianType JacobianType;\n  using EntityType = XT::Grid::extract_entity_t<GridLayerType>;\n  typedef typename GridLayerType::ctype DomainFieldType;\n  static const size_t dimDomain = GridLayerType::dimension;\n\n  DarcyOperator(const GridLayerType& grd_vw, const FunctionImp& function)\n    : grid_layer_(grd_vw)\n    , function_(function)\n  {\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\n  apply(const XT::Functions::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, r, rC>&\n            source,\n        DiscreteFunction<S, V>& range,\n        const Dune::XT::Common::Parameter& param = {}) const\n  {\n    redirect_apply(range.space(), source, range, param);\n  }\n\n  template <class SourceType>\n  JacobianType jacobian(const SourceType& /*source*/, const Dune::XT::Common::Parameter& /*param*/ = {}) const\n  {\n    DUNE_THROW(NotImplemented, \"This operator does not provide a jacobian (yet)!\");\n    return JacobianType();\n  }\n\n  template <class SourceType>\n  void\n  jacobian(const SourceType& /*source*/, JacobianType& /*jac*/, const Dune::XT::Common::Parameter& /*param*/ = {}) const\n  {\n    DUNE_THROW(NotImplemented, \"This operator does not provide a jacobian (yet)!\");\n  }\n\nprivate:\n  template <class R, size_t r, size_t rC>\n  struct Helper\n  {\n    static_assert(AlwaysFalse<R>::value, \"This should not happen (see check in Traits)!\");\n  };\n\n  template <class R, size_t r>\n  struct Helper<R, r, r>\n  {\n    typedef XT::Common::FieldMatrix<R, r, r> type;\n  };\n\n  template <class R>\n  struct Helper<R, 1, 1>\n  {\n    typedef XT::Common::FieldVector<R, 1> type;\n  };\n\n  typedef typename Helper<typename FunctionImp::RangeFieldType, FunctionImp::dimRange, FunctionImp::dimRangeCols>::type\n      ValueType;\n\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(\n      const CgSpaceInterface<T, dimDomain, dimDomain, 1>& /*space*/,\n      const XT::Functions::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1, 1>&\n          source,\n      DiscreteFunction<S, V>& range,\n      const XT::Common::Parameter param) const\n  {\n    typedef typename XT::LA::Container<FieldType, V::sparse_matrix_type>::MatrixType MatrixType;\n    MatrixType lhs(\n        range.space().mapper().size(), range.space().mapper().size(), range.space().compute_volume_pattern());\n    V rhs(range.space().mapper().size());\n\n    // walk the grid\n    const auto entity_it_end = grid_layer_.template end<0>();\n    for (auto entity_it = grid_layer_.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 =\n          std::max(local_function->order() + ssize_t(local_source->order()) - 1, basis.order()) + basis.order();\n      const auto& quadrature =\n          QuadratureRules<DomainFieldType, dimDomain>::rule(entity.type(), 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 ValueType function_value = local_function->evaluate(xx, param);\n        const auto source_gradient = local_source->jacobian(xx, param);\n        const auto basis_value = basis.evaluate(xx, param);\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 * -1.0\n                               * ((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(\n                global_ii, global_jj, 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      XT::LA::Solver<MatrixType>(lhs).apply(rhs, range.vector());\n    } catch (XT::LA::Exceptions::linear_solver_failed& ee) {\n      DUNE_THROW(operator_error,\n                 \"Application of the Darcy operator failed because a matrix could not be inverted!\\n\\n\"\n                     << \"This was the original error: \"\n                     << ee.what());\n    }\n  } // ... redirect_apply(...)\n\n  template <class T, class S, class V>\n  void redirect_apply(\n      const RtSpaceInterface<T, dimDomain, dimDomain, 1>& /*space*/,\n      const XT::Functions::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1>& source,\n      DiscreteFunction<S, V>& range,\n      const XT::Common::Parameter param) const\n  {\n    static_assert(RtSpaceInterface<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_layer_.template end<0>();\n    for (auto entity_it = grid_layer_.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_layer_.iend(entity);\n      for (auto intersection_it = grid_layer_.ibegin(entity); intersection_it != intersection_it_end;\n           ++intersection_it) {\n        const auto& intersection = *intersection_it;\n        if (intersection.neighbor() && !intersection.boundary()) {\n          const auto neighbor = intersection.outside();\n          if (grid_layer_.indexSet().index(entity) < grid_layer_.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(\n                intersection.type(), 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 weight = 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              ValueType function_value = local_function->evaluate(xx_entity, param);\n              function_value *= 0.5;\n              ValueType function_value_neighbor = local_function_neighbor->evaluate(xx_neighbor, param);\n              function_value_neighbor *= 0.5;\n              function_value += function_value_neighbor;\n              auto source_gradient = local_source->jacobian(xx_entity, param)[0];\n              source_gradient *= 0.5;\n              auto source_gradient_neighbor = local_source_neighbor->jacobian(xx_neighbor, param)[0];\n              source_gradient_neighbor *= 0.5;\n              source_gradient += source_gradient_neighbor;\n              const auto basis_values = local_basis.evaluate(xx_entity, param);\n              const auto basis_value = basis_values[local_DoF_index];\n              // compute integrals\n              lhs += integration_factor * weight * (basis_value * normal);\n              rhs += integration_factor * weight * -1.0 * compute_value(function_value, source_gradient, 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(\n              intersection.type(), 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 weight = quadrature_it->weight();\n            const auto xx_entity = intersection.geometryInInside().global(xx_intersection);\n            // evalaute\n            const ValueType function_value = local_function->evaluate(xx_entity, param);\n            const auto source_gradient = local_source->jacobian(xx_entity, param)[0];\n            const auto basis_values = local_basis.evaluate(xx_entity, param);\n            const auto basis_value = basis_values[local_DoF_index];\n            // compute integrals\n            lhs += integration_factor * weight * (basis_value * normal);\n            rhs += integration_factor * weight * -1.0 * compute_value(function_value, source_gradient, 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(XT::Common::Exceptions::internal_error, \"Unknown intersection type!\");\n      } // walk the intersections\n    } // walk the grid\n  } // ... redirect_apply(...)\n\n  template <class R, int d>\n  R compute_value(const FieldVector<R, 1>& function_value,\n                  const FieldVector<R, d>& source_gradient,\n                  const FieldVector<R, d>& normal) const\n  {\n    return function_value * (source_gradient * normal);\n  }\n\n  template <class R, int d>\n  typename std::enable_if<(d > 1), R>::type compute_value(const XT::Common::FieldMatrix<R, d, d>& function_value,\n                                                          const FieldVector<R, d>& source_gradient,\n                                                          const FieldVector<R, d>& normal) const\n  {\n    return (function_value * source_gradient) * normal;\n  }\n\n  const GridLayerType& grid_layer_;\n  const FunctionImp& function_;\n}; // class DarcyOperator\n\n\ntemplate <class G, class F>\nstd::unique_ptr<DarcyOperator<G, F>> make_darcy(const G& grid_layer, const F& function)\n{\n  return std::unique_ptr<DarcyOperator<G, F>>(new DarcyOperator<G, F>(grid_layer, function));\n}\n\n\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_OPERATORS_DARCY_HH\n", "meta": {"hexsha": "cc40b34a90096d376091f0eb6ff64a32fd9f48dd", "size": 15609, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/operators/darcy.hh", "max_stars_repo_name": "tobiasleibner/dune-gdt", "max_stars_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "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/darcy.hh", "max_issues_repo_name": "tobiasleibner/dune-gdt", "max_issues_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "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": "tobiasleibner/dune-gdt", "max_forks_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "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": 45.375, "max_line_length": 120, "alphanum_fraction": 0.6776218848, "num_tokens": 3547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.0705595976531412, "lm_q1q2_score": 0.0352797988265706}}
{"text": "/* __HEAD__\r\n * Copyright (c) 2011-2016, Matthieu FAESSEL and ARMINES\r\n * Copyright (c) 2017-2020, Centre de Morphologie Mathematique\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of Matthieu FAESSEL, or ARMINES nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\r\n * THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n * Description :\r\n *   Porting GeoCuts module from Morph-M - This is the Watershed submodule\r\n *\r\n * History :\r\n *   - 20/03/2019 - by Jose-Marcio Martins da Cruz\r\n *     Just created it...\r\n *   - XX/XX/XXXX -\r\n *\r\n *\r\n * __HEAD__ - Stop here !\r\n */\r\n\r\n#ifndef _D_GEOCUTS_WATERSHED_HPP_\r\n#define _D_GEOCUTS_WATERSHED_HPP_\r\n\r\n/*\r\n *\r\n *\r\n *\r\n */\r\n#ifndef __BOOST_INCLUDED__\r\n#define __BOOST_INCLUDED__\r\n\r\n#include <boost/config.hpp>\r\n// for boost::tie\r\n#include <boost/utility.hpp>\r\n// for boost::graph_traits\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n// JOE #include <boost/graph/graphviz.hpp>\r\n// JOE #include <boost/graph/prim_minimum_spanning_tree.hpp>\r\n// JOE #include <boost/graph/dijkstra_shortest_paths.hpp>\r\n// JOE #include <boost/graph/johnson_all_pairs_shortest.hpp>\r\n\r\n#include <boost/version.hpp>\r\n\r\n#if 0\r\n// FROM STAWIASKI JAN 2012\r\n#include \"../boost_ext/kolmogorov_max_flow_min_cost.hpp\"\r\n//#include \"../boost_ext/maximum_spanning_tree.hpp\"\r\n//STAWIASKI JAN2012 commented, why?\r\n//#include \"../boost_ext/boost_compare.hpp\"\r\n#include <boost/graph/connected_components.hpp>\r\n#endif\r\n\r\n#endif //  __BOOST_INCLUDED__\r\n\r\n#include <vector>\r\n\r\nusing namespace geocuts;\r\n\r\nnamespace smil\r\n{\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   */\r\n  template <class T1, class T2>\r\n  RES_T geoCutsWatershed_MinCut(const Image<T1> &imIn,\r\n                                const Image<T2> &imMarker, const double Power,\r\n                                const StrElt &nl, Image<T2> &imOut)\r\n  {\r\n    std::cout << \"Enter function Geo-Cuts Watershed\" << std::endl;\r\n\r\n    ASSERT_ALLOCATED(&imIn, &imMarker, &imOut);\r\n    ASSERT_SAME_SIZE(&imIn, &imMarker, &imOut);\r\n\r\n    typename Image<T1>::lineType bufIn     = imIn.getPixels();\r\n    typename Image<T2>::lineType bufMarker = imMarker.getPixels();\r\n    typename Image<T2>::lineType bufOut    = imOut.getPixels();\r\n\r\n    double exposant = Power;\r\n\r\n    // needed for max flow: capacit map, rev_capacity map, etc.\r\n    typedef boost::adjacency_list_traits<boost::vecS, boost::vecS,\r\n                                         boost::directedS>\r\n        Traits_d;\r\n\r\n    typedef boost::adjacency_list<\r\n        boost::vecS, boost::vecS, boost::directedS,\r\n        boost::property<boost::vertex_name_t, std::string>,\r\n        boost::property<\r\n            boost::edge_capacity_t, double,\r\n            boost::property<boost::edge_residual_capacity_t, double,\r\n                            boost::property<boost::edge_reverse_t,\r\n                                            Traits_d::edge_descriptor>>>>\r\n        Graph_d;\r\n\r\n    Graph_d g;\r\n\r\n    boost::property_map<Graph_d, boost::edge_capacity_t>::type capacity =\r\n        boost::get(boost::edge_capacity, g);\r\n\r\n    boost::property_map<Graph_d, boost::edge_reverse_t>::type rev =\r\n        get(boost::edge_reverse, g);\r\n\r\n    boost::property_map<Graph_d, boost::edge_residual_capacity_t>::type\r\n        residual_capacity = get(boost::edge_residual_capacity, g);\r\n\r\n    Graph_d::edge_descriptor e1, e2, e3, e4;\r\n    Graph_d::vertex_descriptor vSource, vSink;\r\n    T1 numVertex = maxVal(imIn);\r\n    // T2 numLabels = maxVal(imMarker);\r\n\r\n    std::cout << \"build graph vertices\" << std::endl;\r\n    std::cout << \"number of vertices : \" << numVertex << std::endl;\r\n\r\n    size_t pixelCount = imIn.getPixelCount();\r\n    for (off_t i = 0; i < (off_t) pixelCount; i++) {\r\n      boost::add_vertex(g);\r\n      bufOut[i] = (T2) 1;\r\n    }\r\n\r\n    vSource = boost::add_vertex(g);\r\n    vSink   = boost::add_vertex(g);\r\n\r\n    int width  = imIn.getWidth();\r\n    int height = imIn.getHeight();\r\n    int depth  = imIn.getDepth();\r\n\r\n    off_t strideY = width;\r\n    off_t strideZ = width * height;\r\n    for (int z = 0; z < depth; z++) {\r\n      off_t p0Z = z * strideZ;\r\n      for (int y = 0; y < height; y++) {\r\n        off_t p0Y = y * strideY;\r\n        for (int x = 0; x < width; x++) {\r\n          off_t o1 = p0Z + p0Y + x;\r\n\r\n          // iterators on the Structuring Element\r\n          vector<IntPoint> pts = filterStrElt(nl);\r\n          vector<IntPoint>::iterator itBegin, itEnd, it;\r\n          itBegin = pts.begin();\r\n          itEnd   = pts.end();\r\n\r\n          T1 val1   = bufIn[o1];\r\n          T2 marker = bufMarker[o1];\r\n\r\n          bool hasEdge = false;\r\n          if (marker == 2) {\r\n            boost::tie(e4, hasEdge) = boost::add_edge(vSource, o1, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(o1, vSource, g);\r\n            capacity[e4]            = (std::numeric_limits<double>::max)();\r\n            capacity[e3]            = (std::numeric_limits<double>::max)();\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          } else if (marker == 3) {\r\n            boost::tie(e4, hasEdge) = boost::add_edge(o1, vSink, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(vSink, o1, g);\r\n            capacity[e4]            = (std::numeric_limits<double>::max)();\r\n            capacity[e3]            = (std::numeric_limits<double>::max)();\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          }\r\n\r\n          for (it = itBegin; it != itEnd; it++) {\r\n            if (x + it->x > width - 1 || x + it->x < 0)\r\n              continue;\r\n            if (y + it->y > height - 1 || y + it->y < 0)\r\n              continue;\r\n            if (z + it->z > depth - 1 || z + it->z < 0)\r\n              continue;\r\n\r\n            off_t o2 = o1 + it->z * strideZ + it->y * strideY + it->x;\r\n            if (o2 <= o1)\r\n              continue;\r\n\r\n            T2 val2       = bufIn[o2];\r\n            double valeur = (255.0 / (std::abs((double) (val1 - val2)) + 1));\r\n            double cost   = std::pow(valeur, exposant);\r\n\r\n            bool hasEdge            = false;\r\n            boost::tie(e4, hasEdge) = boost::add_edge(o1, o2, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(o2, o1, g);\r\n            capacity[e4]            = cost;\r\n            capacity[e3]            = cost;\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    std::cout << \"Compute Max flow\" << std::endl;\r\n    boost::property_map<Graph_d, boost::vertex_index_t>::type indexmap =\r\n        boost::get(boost::vertex_index, g);\r\n    std::vector<boost::default_color_type> color(boost::num_vertices(g));\r\n#if BOOST_VERSION >= 104700\r\n    double flow =\r\n        boykov_kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                   &color[0], indexmap, vSource, vSink);\r\n#else\r\n    double flow = kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                      &color[0], indexmap, vSource, vSink);\r\n#endif\r\n    std::cout << \"c  The total flow:\" << std::endl;\r\n    std::cout << \"s \" << flow << std::endl << std::endl;\r\n\r\n    // for all pixels in imIn create a vertex and an edge\r\n    for (off_t o1 = 0; o1 < (off_t) pixelCount; o1++) {\r\n      if (color[o1] == color[vSource])\r\n        bufOut[o1] = (T2) 2;\r\n      else if (color[o1] == color[vSink])\r\n        bufOut[o1] = (T2) 3;\r\n      else if (color[o1] == 1)\r\n        bufOut[o1] = (T2) 4;\r\n    }\r\n\r\n    return RES_OK;\r\n  }\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   */\r\n  template <class T1, class T2>\r\n  RES_T geoCutsMultiway_Watershed(const Image<T1> &imIn,\r\n                                  const Image<T2> &imMarker, const double Power,\r\n                                  const StrElt &nl, Image<T2> &imOut)\r\n  {\r\n    std::cout << \"Enter function Multi way watershed\" << std::endl;\r\n    ASSERT_ALLOCATED(&imIn, &imMarker, &imOut);\r\n    ASSERT_SAME_SIZE(&imIn, &imMarker, &imOut);\r\n\r\n    typename Image<T1>::lineType bufIn     = imIn.getPixels();\r\n    typename Image<T2>::lineType bufMarker = imMarker.getPixels();\r\n    typename Image<T2>::lineType bufOut    = imOut.getPixels();\r\n\r\n    double exposant = Power;\r\n\r\n    // needed for max flow: capacit map, rev_capacity map, etc.\r\n    typedef boost::adjacency_list_traits<boost::vecS, boost::vecS,\r\n                                         boost::directedS>\r\n        Traits_d;\r\n\r\n    typedef boost::adjacency_list<\r\n        boost::vecS, boost::vecS, boost::directedS,\r\n        boost::property<boost::vertex_name_t, std::string>,\r\n        boost::property<\r\n            boost::edge_capacity_t, double,\r\n            boost::property<boost::edge_residual_capacity_t, double,\r\n                            boost::property<boost::edge_reverse_t,\r\n                                            Traits_d::edge_descriptor>>>>\r\n        Graph_d;\r\n\r\n    Graph_d g;\r\n\r\n    boost::property_map<Graph_d, boost::edge_capacity_t>::type capacity =\r\n        boost::get(boost::edge_capacity, g);\r\n\r\n    boost::property_map<Graph_d, boost::edge_reverse_t>::type rev =\r\n        get(boost::edge_reverse, g);\r\n\r\n    boost::property_map<Graph_d, boost::edge_residual_capacity_t>::type\r\n        residual_capacity = get(boost::edge_residual_capacity, g);\r\n\r\n    Graph_d::edge_descriptor e1, e2, e3, e4;\r\n    Graph_d::vertex_descriptor vSource, vSink;\r\n    T1 numVertex = maxVal(imIn);\r\n    T2 numLabels = maxVal(imMarker);\r\n\r\n    std::cout << \"build graph vertices\" << std::endl;\r\n\r\n    size_t pixelCount = imIn.getPixelCount();\r\n    for (off_t i = 0; i < (off_t) pixelCount; i++) {\r\n      boost::add_vertex(g);\r\n      bufOut[i] = (T2) 1;\r\n    }\r\n\r\n    std::cout << \"number of Labels: \" << numLabels << std::endl;\r\n    std::cout << \"number of vertices: \" << numVertex << std::endl;\r\n\r\n    vSource = boost::add_vertex(g);\r\n    vSink   = boost::add_vertex(g);\r\n\r\n    std::cout << \"build graph edges\" << std::endl;\r\n\r\n    int width  = imIn.getWidth();\r\n    int height = imIn.getHeight();\r\n    int depth  = imIn.getDepth();\r\n\r\n    off_t strideY = width;\r\n    off_t strideZ = width * height;\r\n    for (int z = 0; z < depth; z++) {\r\n      off_t p0Z = z * strideZ;\r\n      for (int y = 0; y < height; y++) {\r\n        off_t p0Y = y * strideY;\r\n        for (int x = 0; x < width; x++) {\r\n          off_t o1 = p0Z + p0Y + x;\r\n\r\n          // iterators on the Structuring Element\r\n          vector<IntPoint> pts = filterStrElt(nl);\r\n          vector<IntPoint>::iterator itBegin, itEnd, it;\r\n          itBegin = pts.begin();\r\n          itEnd   = pts.end();\r\n\r\n          T1 val1 = bufIn[o1];\r\n\r\n          for (it = itBegin; it != itEnd; it++) {\r\n            if (x + it->x > width - 1 || x + it->x < 0)\r\n              continue;\r\n            if (y + it->y > height - 1 || y + it->y < 0)\r\n              continue;\r\n            if (z + it->z > depth - 1 || z + it->z < 0)\r\n              continue;\r\n\r\n            off_t o2 = o1 + it->z * strideZ + it->y * strideY + it->x;\r\n            if (o2 <= o1)\r\n              continue;\r\n\r\n            T2 val2       = bufIn[o2];\r\n            double valeur = (255.0 / (std::abs((double) (val1 - val2)) + 1));\r\n            double cost   = std::pow(valeur, exposant);\r\n\r\n            bool hasEdge            = false;\r\n            boost::tie(e4, hasEdge) = boost::add_edge(o1, o2, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(o2, o1, g);\r\n            capacity[e4]            = cost;\r\n            capacity[e3]            = cost;\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    for (T2 nbk = 2; nbk <= numLabels; nbk++) {\r\n      // for all pixels in imIn create a vertex\r\n      for (off_t o0 = 0; o0 < (off_t) pixelCount; o0++) {\r\n        T2 val1 = bufMarker[o0];\r\n        T1 val2 = bufIn[o0];\r\n\r\n        double cost = std::numeric_limits<double>::max();\r\n        bool hasEdge;\r\n        if (val1 == nbk) {\r\n          boost::tie(e4, hasEdge) = boost::edge(vSource, o0, g);\r\n          if (!hasEdge) {\r\n            boost::tie(e4, hasEdge) = boost::add_edge(vSource, o0, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(o0, vSource, g);\r\n            capacity[e4]            = cost;\r\n            capacity[e3]            = cost;\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          }\r\n        } else if (val1 > 1 && val1 != nbk) {\r\n          boost::tie(e4, hasEdge) = boost::edge(val2, vSink, g);\r\n          if (!hasEdge) {\r\n            boost::tie(e4, hasEdge) = boost::add_edge(o0, vSink, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(vSink, o0, g);\r\n            capacity[e4]            = cost;\r\n            capacity[e3]            = cost;\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          }\r\n        }\r\n      }\r\n\r\n      std::cout << \"Compute Max flow\" << std::endl;\r\n      boost::property_map<Graph_d, boost::vertex_index_t>::type indexmap =\r\n          boost::get(boost::vertex_index, g);\r\n      std::vector<boost::default_color_type> color(boost::num_vertices(g));\r\n#if BOOST_VERSION >= 104700\r\n      double flow =\r\n          boykov_kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                     &color[0], indexmap, vSource, vSink);\r\n#else\r\n      double flow = kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                        &color[0], indexmap, vSource, vSink);\r\n#endif\r\n      std::cout << \"c  The total flow:\" << std::endl;\r\n      std::cout << \"s \" << flow << std::endl << std::endl;\r\n\r\n      // for all pixels in imIn create a vertex and an edge\r\n      for (off_t o1 = 0; o1 < (off_t) pixelCount; o1++) {\r\n        T1 val1 = (int) bufIn[o1];\r\n        T2 val2 = (int) bufOut[o1];\r\n        T2 val3 = (int) bufMarker[o1];\r\n\r\n        if (val2 == 1) {\r\n          if (color[val1] == color[vSource])\r\n            bufOut[o1] = (T2) nbk;\r\n        }\r\n\r\n        bool hasEdge;\r\n        if (val3 == nbk) {\r\n          boost::tie(e4, hasEdge) = boost::edge(vSource, o1, g);\r\n          if (hasEdge) {\r\n            boost::remove_edge(vSource, o1, g);\r\n            boost::remove_edge(o1, vSource, g);\r\n          }\r\n        } else if (val3 > 1) {\r\n          boost::tie(e4, hasEdge) = boost::edge(o1, vSink, g);\r\n          if (hasEdge) {\r\n            boost::remove_edge(o1, vSink, g);\r\n            boost::remove_edge(vSink, o1, g);\r\n          }\r\n        }\r\n      }\r\n    }\r\n    return RES_OK;\r\n  }\r\n\r\n} // namespace smil\r\n\r\n#endif // _D_GEOCUTS_WATERSHED_HPP_\r\n", "meta": {"hexsha": "9026cac92268c505113d60b8d9de372eb87c922f", "size": 15929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Addons/GraphCuts/include/private/GeoCuts/Watershed.hpp", "max_stars_repo_name": "basileMarchand/smil", "max_stars_repo_head_hexsha": "84e4825e813b6cdd757290ff769e7bcc43d2ac08", "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": "Addons/GraphCuts/include/private/GeoCuts/Watershed.hpp", "max_issues_repo_name": "basileMarchand/smil", "max_issues_repo_head_hexsha": "84e4825e813b6cdd757290ff769e7bcc43d2ac08", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/GraphCuts/include/private/GeoCuts/Watershed.hpp", "max_forks_repo_name": "basileMarchand/smil", "max_forks_repo_head_hexsha": "84e4825e813b6cdd757290ff769e7bcc43d2ac08", "max_forks_repo_licenses": ["BSD-3-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.4508009153, "max_line_length": 81, "alphanum_fraction": 0.5417163664, "num_tokens": 4221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.07159120142539066, "lm_q1q2_score": 0.03523633996357499}}
{"text": "/*\r\n [auto_generated]\r\n  boost/numeric/odeint/iterator/detail/times_iterator_impl.hpp\r\n\r\n  [begin_description]\r\n  tba.\r\n  [end_description]\r\n\r\n  Copyright 2009-2013 Karsten Ahnert\r\n  Copyright 2009-2013 Mario Mulansky\r\n\r\n  Distributed under the Boost Software License, Version 1.0.\r\n  (See accompanying file LICENSE_1_0.txt or\r\n  copy at http://www.boost.org/LICENSE_1_0.txt)\r\n*/\r\n\r\n\r\n#ifndef BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_TIMES_ITERATOR_IMPL_HPP_DEFINED\r\n#define BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_TIMES_ITERATOR_IMPL_HPP_DEFINED\r\n\r\n#include <boost/utility/enable_if.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/throw_exception.hpp>\r\n\r\n#include <boost/numeric/odeint/util/unit_helper.hpp>\r\n#include <boost/numeric/odeint/util/copy.hpp>\r\n#include <boost/numeric/odeint/stepper/controlled_step_result.hpp>\r\n#include <boost/numeric/odeint/iterator/detail/ode_iterator_base.hpp>\r\n\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\n\r\n\r\n    template< class Iterator , class Stepper , class System , class State , class TimeIterator ,\r\n              typename Tag , typename StepperTag >\r\n    class times_iterator_impl;\r\n\r\n    /*\r\n     * Specilization for basic steppers\r\n     */\r\n    /**\r\n     * \\brief ODE Iterator with constant step size.\r\n     *\r\n     * Implements an ODE iterator with observer calls at predefined times.\r\n     * Uses controlled steppers. times_iterator is a model of single-pass iterator.\r\n     *\r\n     * The value type of this iterator is the state type of the stepper. Hence one can only access the state and not the current time.\r\n     *\r\n     * \\tparam Stepper The stepper type which should be used during the iteration.\r\n     * \\tparam System The type of the system function (ODE) which should be solved.\r\n     */\r\n    template< class Iterator , class Stepper , class System , class State , class TimeIterator , typename Tag >\r\n    class times_iterator_impl< Iterator , Stepper , System , State , TimeIterator , Tag , stepper_tag >\r\n        : public detail::ode_iterator_base< Iterator , Stepper , System , State , Tag >\r\n    {\r\n    private:\r\n\r\n\r\n        typedef Stepper stepper_type;\r\n        typedef System system_type;\r\n        typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type unwrapped_stepper_type;\r\n        typedef State state_type;\r\n        typedef TimeIterator time_iterator_type;\r\n        typedef typename traits::time_type< stepper_type >::type time_type;\r\n        typedef typename traits::value_type< stepper_type >::type ode_value_type;\r\n        #ifndef DOXYGEN_SKIP\r\n        typedef detail::ode_iterator_base< Iterator , Stepper , System , State , Tag > base_type;\r\n        #endif\r\n\r\n    public:\r\n\r\n        /**\r\n         * \\brief Constructs a times_iterator. This constructor should be used to construct the begin iterator.\r\n         *\r\n         * \\param stepper The stepper to use during the iteration.\r\n         * \\param sys The system function (ODE) to solve.\r\n         * \\param s The initial state. adaptive_iterator stores a reference of s and changes its value during the iteration.\r\n         * \\param t_start Iterator to the begin of a sequence of time values.\r\n         * \\param t_end Iterator to the begin of a sequence of time values.\r\n         * \\param dt The (initial) time step.\r\n         */\r\n        times_iterator_impl( stepper_type stepper , system_type sys , state_type &s ,\r\n                             time_iterator_type t_start , time_iterator_type t_end , time_type dt )\r\n            : base_type( stepper , sys , *t_start , dt ) ,\r\n              m_t_start( t_start ) , m_t_end( t_end ) , m_state( &s )\r\n        {\r\n            if( t_start == t_end )\r\n                this->m_at_end = true;\r\n        }\r\n\r\n        /**\r\n         * \\brief Constructs an adaptive_iterator. This constructor should be used to construct the end iterator.\r\n         *\r\n         * \\param stepper The stepper to use during the iteration.\r\n         * \\param sys The system function (ODE) to solve.\r\n         * \\param s The initial state. adaptive_iterator store a reference of s and changes its value during the iteration.\r\n         */\r\n        times_iterator_impl( stepper_type stepper , system_type sys , state_type &s )\r\n            : base_type( stepper , sys ) , m_state( &s ) { }\r\n\r\n    protected:\r\n\r\n        friend class boost::iterator_core_access;\r\n\r\n        void increment()\r\n        {\r\n            unwrapped_stepper_type &stepper = this->m_stepper;\r\n            if( ++m_t_start != m_t_end )\r\n            {\r\n                while( detail::less_with_sign( this->m_t , static_cast<time_type>(*m_t_start) , this->m_dt ) )\r\n                {\r\n                    const time_type current_dt = detail::min_abs( this->m_dt , static_cast<time_type>(*m_t_start) - this->m_t );\r\n                    stepper.do_step( this->m_system , *( this->m_state ) , this->m_t , current_dt );\r\n                    this->m_t += current_dt;\r\n                }\r\n\r\n            } else {\r\n                this->m_at_end = true;\r\n            }\r\n         }\r\n\r\n    public:\r\n        const state_type& get_state() const\r\n        {\r\n            return *m_state;\r\n        }\r\n\r\n    private:\r\n        time_iterator_type m_t_start;\r\n        time_iterator_type m_t_end;\r\n        state_type* m_state;\r\n    };\r\n\r\n\r\n\r\n    /*\r\n     * Specilization for controlled steppers\r\n     */\r\n    /**\r\n     * \\brief ODE Iterator with adaptive step size control. The value type of this iterator is the state type of the stepper.\r\n     *\r\n     * Implements an ODE iterator with observer calls at predefined times.\r\n     * Uses controlled steppers. times_iterator is a model of single-pass iterator.\r\n     *\r\n     * The value type of this iterator is the state type of the stepper. Hence one can only access the state and not the current time.\r\n     *\r\n     * \\tparam Stepper The stepper type which should be used during the iteration.\r\n     * \\tparam System The type of the system function (ODE) which should be solved.\r\n     */\r\n    template< class Iterator , class Stepper , class System , class State , class TimeIterator , typename Tag >\r\n    class times_iterator_impl< Iterator , Stepper , System , State , TimeIterator , Tag , controlled_stepper_tag >\r\n        : public detail::ode_iterator_base< Iterator , Stepper , System , State , Tag >\r\n    {\r\n    private:\r\n\r\n\r\n        typedef Stepper stepper_type;\r\n        typedef System system_type;\r\n        typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type unwrapped_stepper_type;\r\n        typedef State state_type;\r\n        typedef TimeIterator time_iterator_type;\r\n        typedef typename traits::time_type< stepper_type >::type time_type;\r\n        typedef typename traits::value_type< stepper_type >::type ode_value_type;\r\n        #ifndef DOXYGEN_SKIP\r\n        typedef detail::ode_iterator_base< Iterator , Stepper , System , State , Tag > base_type;\r\n        #endif\r\n\r\n    public:\r\n\r\n        /**\r\n         * \\brief Constructs a times_iterator. This constructor should be used to construct the begin iterator.\r\n         *\r\n         * \\param stepper The stepper to use during the iteration.\r\n         * \\param sys The system function (ODE) to solve.\r\n         * \\param s The initial state. adaptive_iterator stores a reference of s and changes its value during the iteration.\r\n         * \\param t_start Iterator to the begin of a sequence of time values.\r\n         * \\param t_end Iterator to the begin of a sequence of time values.\r\n         * \\param dt The (initial) time step.\r\n         */\r\n        times_iterator_impl( stepper_type stepper , system_type sys , state_type &s ,\r\n                             time_iterator_type t_start , time_iterator_type t_end , time_type dt )\r\n            : base_type( stepper , sys , *t_start , dt ) ,\r\n              m_t_start( t_start ) , m_t_end( t_end ) , m_state( &s )\r\n        {\r\n            if( t_start == t_end )\r\n                this->m_at_end = true;\r\n        }\r\n\r\n        /**\r\n         * \\brief Constructs an adaptive_iterator. This constructor should be used to construct the end iterator.\r\n         *\r\n         * \\param stepper The stepper to use during the iteration.\r\n         * \\param sys The system function (ODE) to solve.\r\n         * \\param s The initial state. adaptive_iterator store a reference of s and changes its value during the iteration.\r\n         */\r\n        times_iterator_impl( stepper_type stepper , system_type sys , state_type &s )\r\n            : base_type( stepper , sys ) , m_state( &s ) { }\r\n\r\n    protected:\r\n\r\n        friend class boost::iterator_core_access;\r\n\r\n        void increment()\r\n        {\r\n            if( ++m_t_start != m_t_end )\r\n            {\r\n                while( detail::less_with_sign( this->m_t , static_cast<time_type>(*m_t_start) , this->m_dt ) )\r\n                {\r\n                    if( detail::less_with_sign( static_cast<time_type>(*m_t_start) - this->m_t , this->m_dt , this->m_dt ) )\r\n                    {\r\n                        // we want to end exactly at the time point\r\n                        time_type current_dt = static_cast<time_type>(*m_t_start) - this->m_t;\r\n                        step_loop( current_dt );\r\n                    } else {\r\n                        step_loop( this->m_dt );\r\n                    }\r\n                }\r\n\r\n            } else {\r\n                this->m_at_end = true;\r\n            }\r\n        }\r\n\r\n    private:\r\n        void step_loop( time_type &dt )\r\n        {\r\n            unwrapped_stepper_type &stepper = this->m_stepper;\r\n            const size_t max_attempts = 1000;\r\n            size_t trials = 0;\r\n            controlled_step_result res = success;\r\n            do\r\n            {\r\n                res = stepper.try_step( this->m_system , *( this->m_state ) , this->m_t , dt );\r\n                ++trials;\r\n            }\r\n            while( ( res == fail ) && ( trials < max_attempts ) );\r\n            if( trials == max_attempts )\r\n            {\r\n                BOOST_THROW_EXCEPTION( std::overflow_error( \"Adaptive iterator : Maximal number of iterations reached. A step size could not be found.\" ) );\r\n            }\r\n        }\r\n\r\n    public:\r\n        const state_type& get_state() const\r\n        {\r\n            return *m_state;\r\n        }\r\n\r\n\r\n    private:\r\n        time_iterator_type m_t_start;\r\n        time_iterator_type m_t_end;\r\n        state_type* m_state;\r\n    };\r\n\r\n\r\n    /*\r\n     * Specilization for dense outputer steppers\r\n     */\r\n    /**\r\n     * \\brief ODE Iterator with step size control and dense output.\r\n     * Implements an ODE iterator with adaptive step size control. Uses dense-output steppers.\r\n     * times_iterator is a model of single-pass iterator.\r\n     *\r\n     * \\tparam Stepper The stepper type which should be used during the iteration.\r\n     * \\tparam System The type of the system function (ODE) which should be solved.\r\n     */\r\n    template< class Iterator , class Stepper , class System , class State , class TimeIterator , typename Tag >\r\n    class times_iterator_impl< Iterator , Stepper , System , State , TimeIterator , Tag , dense_output_stepper_tag >\r\n        : public detail::ode_iterator_base< Iterator , Stepper , System , State , Tag >\r\n    {\r\n    private:\r\n\r\n\r\n        typedef Stepper stepper_type;\r\n        typedef System system_type;\r\n        typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type unwrapped_stepper_type;\r\n        typedef State state_type;\r\n        typedef TimeIterator time_iterator_type;\r\n        typedef typename traits::time_type< stepper_type >::type time_type;\r\n        typedef typename traits::value_type< stepper_type >::type ode_value_type;\r\n        #ifndef DOXYGEN_SKIP\r\n        typedef detail::ode_iterator_base< Iterator , Stepper , System , State , Tag > base_type;\r\n        #endif\r\n\r\n\r\n   public:\r\n\r\n\r\n        /**\r\n         * \\brief Constructs a times_iterator. This constructor should be used to construct the begin iterator.\r\n         *\r\n         * \\param stepper The stepper to use during the iteration.\r\n         * \\param sys The system function (ODE) to solve.\r\n         * \\param s The initial state.\r\n         * \\param t_start Iterator to the begin of a sequence of time values.\r\n         * \\param t_end Iterator to the begin of a sequence of time values.\r\n         * \\param dt The (initial) time step.\r\n         */\r\n        times_iterator_impl( stepper_type stepper , system_type sys , state_type &s ,\r\n                             time_iterator_type t_start , time_iterator_type t_end , time_type dt )\r\n            : base_type( stepper , sys , *t_start , dt ) ,\r\n              m_t_start( t_start ) , m_t_end( t_end ) , m_final_time( *(t_end-1) ) ,\r\n              m_state( &s )\r\n        {\r\n            if( t_start != t_end )\r\n            {\r\n                unwrapped_stepper_type &st = this->m_stepper;\r\n                st.initialize( *( this->m_state ) , this->m_t , this->m_dt );\r\n            } else {\r\n                this->m_at_end = true;\r\n            }\r\n        }\r\n\r\n        /**\r\n         * \\brief Constructs a times_iterator. This constructor should be used to construct the end iterator.\r\n         *\r\n         * \\param stepper The stepper to use during the iteration.\r\n         * \\param sys The system function (ODE) to solve.\r\n         * \\param s The initial state.\r\n         */\r\n        times_iterator_impl( stepper_type stepper , system_type sys , state_type &s )\r\n            : base_type( stepper , sys ) , m_state( &s ) { }\r\n\r\n    protected:\r\n\r\n        friend class boost::iterator_core_access;\r\n\r\n        void increment()\r\n        {\r\n            unwrapped_stepper_type &st = this->m_stepper;\r\n            if( ++m_t_start != m_t_end )\r\n            {\r\n                this->m_t = static_cast<time_type>(*m_t_start);\r\n                while( detail::less_with_sign( st.current_time() , this->m_t , this->m_dt ) )\r\n                {\r\n                    // make sure we don't go beyond the last point\r\n                    if( detail::less_with_sign( m_final_time-st.current_time() , st.current_time_step() , st.current_time_step() ) )\r\n                    {\r\n                        st.initialize( st.current_state() , st.current_time() , m_final_time-st.current_time() );\r\n                    }\r\n                    st.do_step( this->m_system );\r\n                }\r\n                st.calc_state( this->m_t , *( this->m_state ) );\r\n            } else {\r\n                this->m_at_end = true;\r\n            }\r\n        }\r\n\r\n    public:\r\n        const state_type& get_state() const\r\n        {\r\n            return *m_state;\r\n        }\r\n\r\n\r\n    private:\r\n        time_iterator_type m_t_start;\r\n        time_iterator_type m_t_end;\r\n        time_type m_final_time;\r\n        state_type* m_state;\r\n    };\r\n\r\n} // namespace odeint\r\n} // namespace numeric\r\n} // namespace boost\r\n\r\n\r\n#endif // BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_TIMES_ITERATOR_IMPL_HPP_DEFINED\r\n", "meta": {"hexsha": "ca1a20c67abc14972b257128a73172533c7e19a2", "size": 14859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/odeint/iterator/impl/times_iterator_impl.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/odeint/iterator/impl/times_iterator_impl.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/odeint/iterator/impl/times_iterator_impl.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 39.9435483871, "max_line_length": 157, "alphanum_fraction": 0.5970792113, "num_tokens": 3154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.07477003878454293, "lm_q1q2_score": 0.03476070852258321}}
{"text": "﻿/***\r\n第三节 类模板中的友元\r\n\r\n(2)友元函数：函数模板可以被声明为友元函数\r\n(2.1)让函数模板的某个实例成为友元函数\r\n代码行_nmsp1::func(2, 3);，会实例化出 void func<int,int>(int,int){......}\r\n\r\n(2.2)友元模板\r\n将func函数模板（泛化版本）声明为Men类模板的友元模板之后，那么func函数模板的特化版本也会被看成是Men类模板的友元。\r\n编译器会把全特化的func函数模板看待成一个实例化过的函数模板。\r\n看待成了void func<int,double>(int val1, double val2)\r\n\r\n(2.3)在类模板中定义友元函数\r\n这种友元函数是能够被调用的，而且也只有在代码中调用了函数的时候，编译器才会实例化出这个函数。\r\n之所以这样定义友元函数，一般都是因为在该友元函数中会 用到这个类模板。\r\n 这种友元函数的调用与调用普通函数函数，大家就把他当成普通函数来看待即可。\r\nfunc2在Men类模板被实例化时并不会被一并实例化出来，只有调用了func2的时候，才会被实例化出来。\r\n因为func2在类模板Men中，所以调用func2时，如果func2中的代码特别简单，则func2会被当成内联函数来处理。\r\n如果func2中的代码比较复杂，比如出现了for循环，那么func2很可能就不会被当做内联函数来处理。\r\nfunc2(mymen2); 可以被实例化出  void func2(class Men<double>&);\r\nfunc2(mymen3); 可以被实例化出  void func2(class Men<int>&);\r\nfunc2其实是个全局函数。\r\n***/\r\n\r\n#include <iostream>\r\n\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996) \r\n\r\nnamespace _nmsp1\r\n{\r\n\t//函数模板func的声明\r\n\t//template <typename U, typename V> void func(U val1, V val2);\r\n\r\n\t//Men类模板\r\n\ttemplate <typename Z>\r\n\tclass Men\r\n\t{\r\n\t\tfriend void func2(Men<Z>& tmpmen)\r\n\t\t{\r\n\t\t\t//for(int i= 0; i<1 ; ++i)\r\n\t\t\t\ttmpmen.funcmen();\r\n\t\t}\r\n\r\n\t\t//friend void func<int, int>(int, int);  //<int,int>是两个模板实参\r\n\t\t////friend void func<>(int, int);\r\n\t\t////friend void func<int>(int, int);\r\n\r\n\t\t////friend void func<float,int>(float, int);\r\n\t\t//friend void func<>(float, int);\r\n\r\n\t\t////friend void func<int, float>(int, float);\r\n\t\t//friend void func<>(int, float);\r\n\r\n\r\n\t\t//让函数模板func成为类模板Men的友元函数模板\r\n\t\ttemplate <typename U, typename V> friend void func(U val1, V val2);\r\n\r\n\tprivate:\r\n\t\tvoid funcmen() const\r\n\t\t{\r\n\t\t\tcout << \"Men::funcmen被调用了\" << endl;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename U,typename V>\r\n\tvoid func(U val1, V val2)\r\n\t{\r\n\t\t/*cout << \"val1 = \" << val1 << endl;\r\n\t\tcout << \"val2 = \" << val2 << endl;*/\r\n\t\t//Men mymen;\r\n\t\tMen<int> mymen;\r\n\t\tmymen.funcmen(); \r\n\t}\r\n\r\n\t//func全特化版本\r\n\ttemplate <>\r\n\tvoid func(int val1, double val2)\r\n\t{\r\n\t\tMen<int> mymen;\r\n\t\tmymen.funcmen();\r\n\t}\r\n\r\n}\r\n\r\nint main()\r\n{\r\n\t//调用func的方法很多\r\n\t//_nmsp1::func(2, 3);\r\n\t//_nmsp1::func<float>(4.6f, 5); //第一个模板参数指定，第二个模板参数编译器自己推断\r\n\t//_nmsp1::func<int, float>(4, 5.8f); //完全手工指定模板参数\r\n\r\n\t_nmsp1::Men<double> mymen2;\r\n\tfunc2(mymen2); //直接调用Men类模板中定义的友元函数func2\r\n\r\n\t_nmsp1::Men<int> mymen3;\r\n\tfunc2(mymen3);\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "733149dd274485d66b62ef50ce3a3c5e551eda47", "size": 2268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/212.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/212.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/212.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 22.2352941176, "max_line_length": 70, "alphanum_fraction": 0.6578483245, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786954, "lm_q2_score": 0.15405755686555633, "lm_q1q2_score": 0.034727131509144686}}
{"text": "/**\r\n * -*- c++ -*-\r\n *\r\n * \\file iterator_type.hpp\r\n *\r\n * \\brief Iterator to a given container type.\r\n *\r\n * Copyright (c) 2009, Marco Guazzone\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 * \\author Marco Guazzone, marco.guazzone@gmail.com\r\n */\r\n\r\n\r\n#ifndef BOOST_NUMERIC_UBLAS_TRAITS_ITERATOR_TYPE_HPP\r\n#define BOOST_NUMERIC_UBLAS_TRAITS_ITERATOR_TYPE_HPP\r\n\r\n\r\n#include <boost/numeric/ublas/fwd.hpp>\r\n#include <boost/numeric/ublas/traits.hpp>\r\n#include <boost/numeric/ublas/tags.hpp>\r\n\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    namespace detail {\r\n\r\n        /**\r\n         * \\brief Auxiliary class for retrieving the iterator to the given\r\n         *  matrix expression according its orientation and to the given dimension tag.\r\n         * \\tparam MatrixT A model of MatrixExpression.\r\n         * \\tparam TagT A dimension tag type (e.g., tag::major).\r\n         * \\tparam OrientationT An orientation category type (e.g., row_major_tag).\r\n         */\r\n        template <typename MatrixT, typename TagT, typename OrientationT>\r\n        struct iterator_type_impl;\r\n\r\n\r\n        /// \\brief Specialization of \\c iterator_type_impl for row-major oriented\r\n        ///  matrices and over the major dimension.\r\n        template <typename MatrixT>\r\n        struct iterator_type_impl<MatrixT,tag::major,row_major_tag>\r\n        {\r\n            typedef typename matrix_traits<MatrixT>::iterator1 type;\r\n        };\r\n\r\n\r\n        /// \\brief Specialization of \\c iterator_type_impl for column-major oriented\r\n        ///  matrices and over the major dimension.\r\n        template <typename MatrixT>\r\n        struct iterator_type_impl<MatrixT,tag::major,column_major_tag>\r\n        {\r\n            typedef typename matrix_traits<MatrixT>::iterator2 type;\r\n        };\r\n\r\n\r\n        /// \\brief Specialization of \\c iterator_type_impl for row-major oriented\r\n        ///  matrices and over the minor dimension.\r\n        template <typename MatrixT>\r\n        struct iterator_type_impl<MatrixT,tag::minor,row_major_tag>\r\n        {\r\n            typedef typename matrix_traits<MatrixT>::iterator2 type;\r\n        };\r\n\r\n\r\n        /// \\brief Specialization of \\c iterator_type_impl for column-major oriented\r\n        ///  matrices and over the minor dimension.\r\n        template <typename MatrixT>\r\n        struct iterator_type_impl<MatrixT,tag::minor,column_major_tag>\r\n        {\r\n            typedef typename matrix_traits<MatrixT>::iterator1 type;\r\n        };\r\n\r\n    } // Namespace detail\r\n\r\n\r\n    /**\r\n     * \\brief A iterator for the given container type over the given dimension.\r\n     * \\tparam ContainerT A container expression type.\r\n     * \\tparam TagT A dimension tag type (e.g., tag::major).\r\n     */\r\n    template <typename ContainerT, typename TagT=void>\r\n    struct iterator_type;\r\n\r\n\r\n    /**\r\n     * \\brief Specialization of \\c iterator_type for vector expressions.\r\n     * \\tparam VectorT A model of VectorExpression type.\r\n     */\r\n    template <typename VectorT>\r\n    struct iterator_type<VectorT, void>\r\n    {\r\n        typedef typename vector_traits<VectorT>::iterator type;\r\n    };\r\n\r\n\r\n    /**\r\n     * \\brief Specialization of \\c iterator_type for matrix expressions and\r\n     *  over the major dimension.\r\n     * \\tparam MatrixT A model of MatrixExpression type.\r\n     */\r\n    template <typename MatrixT>\r\n    struct iterator_type<MatrixT,tag::major>\r\n    {\r\n        typedef typename detail::iterator_type_impl<MatrixT,tag::major,typename matrix_traits<MatrixT>::orientation_category>::type type;\r\n    };\r\n\r\n\r\n    /**\r\n     * \\brief Specialization of \\c iterator_type for matrix expressions and\r\n     *  over the minor dimension.\r\n     * \\tparam MatrixT A model of MatrixExpression type.\r\n     */\r\n    template <typename MatrixT>\r\n    struct iterator_type<MatrixT,tag::minor>\r\n    {\r\n        typedef typename detail::iterator_type_impl<MatrixT,tag::minor,typename matrix_traits<MatrixT>::orientation_category>::type type;\r\n    };\r\n\r\n}}} // Namespace boost::numeric::ublas\r\n\r\n\r\n#endif // BOOST_NUMERIC_UBLAS_TRAITS_ITERATOR_TYPE_HPP\r\n", "meta": {"hexsha": "913eea67ba9322537a554952908f181b7b750037", "size": 4172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/ublas/traits/iterator_type.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/ublas/traits/iterator_type.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/numeric/ublas/traits/iterator_type.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 32.8503937008, "max_line_length": 138, "alphanum_fraction": 0.6581975072, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.07263670736453837, "lm_q1q2_score": 0.034617176650206034}}
{"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-2011 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\n/**\n *\n * Use this file for lossy compression with adaptive grids. No temporal prediction/differential\n * encoding is performed.\n *\n * TODO: Implement temporal compression for adaptive grids.\n *\n */\n\n#ifndef LOSSYSTORAGE_HH\n#define LOSSYSTORAGE_HH\n\n#include <limits>\n\n#include \"io/vtk.hh\"\n#include \"io/rangecoder.hh\"\n#include \"fem/mgtools.hh\"\n\n#include <boost/unordered_map.hpp>\n\nbool abscompare( double a, double b ) { return fabs( a ) < fabs( b ) ; }\ntemplate< class T > bool greaterZero( T t ) { return t > 0 ; }\n\ntypedef unsigned long ULong ;\n\n// Use policies for determining the quantization intervals\ntemplate <class VariableSetSens, class Grid, int D=2>\nstruct UniformQuantizationPolicy \n{\n   typedef Dune::FieldVector<double,D> Coor ;\n\n   void update( typename VariableSetSens::VariableSet const&, GridManager<Grid> &  ){} \n   \n   void resetCount() {}\n   \n   long int getIntervals(double range, double aTol, Coor const& coor = Coor(0), \n\t\t\t bool uniform = true, unsigned int vidx=0  ) \n   { \n//      return (long int) ceil( range / aTol / 2.0 ) ; \n    \n//       symmetric mid-tread quantization : need odd number of intervals\n      long int nIntervals = (long int) ceil( range / aTol / 2.0 ) ; \n      if( nIntervals % 2 == 0 ) return nIntervals + 1 ;\n      return nIntervals ;\n   }\n} ;\n\n\ntemplate <class Grid, class VariableSet, class Space, class QuantizationPolicy=UniformQuantizationPolicy<VariableSet,Grid> >\nclass LossyStorage \n{    \n  public:\n    static const int dim = Grid::dimension ;\n    \n\n    // some typedefs used throughout the class\n    typedef Dune::FieldVector<double,1> StorageValueType;\n    typedef boost::fusion::vector<Space const*> Spaces ;\n    typedef boost::fusion::vector<VariableDescription<0,1,0> > VariableDescriptions;\n    typedef VariableSetDescription<Spaces,VariableDescriptions> PredVariableSet;\n    typedef typename Grid::template Codim<dim>::LevelIterator VertexLevelIterator ;\n    typedef typename Grid::template Codim<dim>::LeafIterator  VertexLeafIterator ;\n    typedef typename Grid::template Codim<dim>::LeafIndexSet IndexSet ;\n    typedef typename Grid::LevelGridView LevelView ;\n\n\n  public:\n\n    LossyStorage( GridManager<Grid>& gridManager_, VariableSet const& varSet_, int coarseLevel_, double aTol_ , bool uniform_ = false, \n\t\t  QuantizationPolicy& quantizationPolicy_ = QuantizationPolicy()  ) \n      : gridManager(gridManager_), varSet(varSet_), coarseLevel(coarseLevel_), aTol(aTol_), \n        count(0), firstCall(true), uniform(uniform_), order(1), quantizationPolicy(quantizationPolicy_)\n    {\n      mlTransfer = NULL ;\n      ioOptions.outputType = IoOptions::ascii ;\n    }\n\n    ~LossyStorage()\n    {\n      if( mlTransfer != NULL ) delete mlTransfer ;\n    }\n\n    /**\n     *  Encode a given state.\n     *  Quantized values are written to a file specified by the member variables \n     *  filePrefix and count, keeping track of the already encoded timesteps.\n     */\n    typename VariableSet::VariableSet encode( typename VariableSet::VariableSet const& sol, std::string fn )\n    {      \n      fn += \".dat\" ;\n      \n      // for adaptivity in space, mlTransfer has to be recomputed\n      if( mlTransfer != NULL ) delete mlTransfer ;\n      mlTransfer = new MultilevelTransfer<Space,Grid>( gridManager, order, coarseLevel ) ;\n      \n      // build map: vertex id - level the vertex is created\n      unsigned long int ID ;\n      levelInfo.clear();\n      for( int level = 0 ; level <= gridManager.grid().maxLevel() ; level++ )\n      {\n\tfor ( VertexLevelIterator it = gridManager.grid().template lbegin <dim>( level ); \n\t      it != gridManager.grid().template lend <dim>( level ); ++ it)\n\t{\n\t  ID = gridManager.grid().globalIdSet().id( *it ) ;\n\t  if( levelInfo.find(ID) != levelInfo.end() ) continue ;\n\t  levelInfo[ID] = level ;\n\t}\n      }\n      \n      IndexSet const& indexSet = varSet.indexSet ;\n      int maxLevel = gridManager.grid().maxLevel() ;\n\n      // for some debug output\n      std::ostringstream debugfn ;\n      typename VariableSet::VariableSet predictionError(varSet) ;\n      predictionError *= 0 ;\n\n      // create variable set over hierarchic function space for multilevel-prediction\n      LevelView gv = gridManager.grid().levelView( coarseLevel ) ;\n      Space space( gridManager, gv, order ) ;\n      Spaces spaces( &space ) ;\n      std::string varNames[1] = { \"pred\" };\n      PredVariableSet predVarSet( spaces, varNames ) ;\n      \n      typename PredVariableSet::VariableSet x( predVarSet ) ;\n      x *= 0 ;\n\n      // calculate quantization (for coarseLevel)\n      std::vector<std::vector<ULong> > allIndices ;\n      std::vector<ULong> indices ;\n      std::vector<double> nodalValues ;\n      for ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>( coarseLevel ) ;\n\t  it != gridManager.grid().template lend<dim>( coarseLevel ); ++it )\n      {\n\tnodalValues.push_back( -(*boost::fusion::at_c<0>(sol.data))[indexSet.index(*it)] ) ;\n      }    \n\n      double ub = *std::max_element( nodalValues.begin(), nodalValues.end() ) ;\n      double lb = *std::min_element( nodalValues.begin(), nodalValues.end() ) ;\n      \n      // symmetric quantization\n      ub = *std::max_element( nodalValues.begin(), nodalValues.end(), abscompare ) ;\n      if( ub < 0 ) { lb = ub ; ub = -lb  ; }\n      else         { lb = -ub ; }\n      // --\n      \n      double range = ub - lb ;\n     \n      // only needed if no pre-computed frequencies are used for range coding\n      double maxBits ;\n      if( range > 0 ) maxBits = (-ld(aTol) ) ;\n      else            maxBits = 0 ;\n      if( maxBits < 0 ) maxBits = 0 ; \n      maxIntervals = (long int)ceil(pow( 2, maxBits )); \n\n      std::ofstream out( fn.c_str(), std::ios::binary ) ;  \n      \n      // write interval bounds for coarse level\n      out.write(reinterpret_cast<char*>( &lb ), sizeof(double) ) ; \n      out.write(reinterpret_cast<char*>( &ub ), sizeof(double) ) ; \n      \n      // for iterating over grid level, used throughout this method\n      VertexLevelIterator itEnd = gridManager.grid().template lend<dim>( coarseLevel );\n      \n      unsigned long vertexCount = 0 ;\n      if( uniform )\n      {\n\tquantize( nodalValues, indices, coarseLevel, lb, ub ) ;    \n\t\n\t// collect indices on each level in a common vector, and after finishing the\n\t// multilevel prediction, calculate occuring frequencies of interval numbers, and encode\n\t// using range coder\n\tallIndices.push_back( indices ) ;\n\t\n\treconstruct( nodalValues, indices, coarseLevel, lb, ub ) ;\n      }\n      else\n      {\n\t// perform quantization adaptively, possibly different for each node\n\tindices.clear() ; \n\tindices.resize(nodalValues.size(), 0) ;\n\tfor ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>( coarseLevel ) ;\n\t      it != itEnd; ++it )\n\t{ \n\t  unsigned int vidx = gridManager.grid().leafIndexSet().index(*it) ;\n\t  \n\t  indices[vertexCount] = quantize( nodalValues[vertexCount], lb, ub, it->geometry().corner(0),vidx );\n\t  \n\t  nodalValues[vertexCount] = reconstruct( indices[vertexCount], lb, ub, it->geometry().corner(0),vidx);\n\t  \n\t  vertexCount++ ;\n\t}    \n\tallIndices.push_back( indices ) ;\n      }\n                 \n      // assign reconstructed coarse grid values of solution to hierarchic variable\n      vertexCount = 0 ;\n      for ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>( coarseLevel ); \n\t      it != itEnd ; ++it)\n      {\n\t(*boost::fusion::at_c<0>(x.data))[gv.indexSet().index(*it)] -= nodalValues[vertexCount] ;\n\tvertexCount++ ;\n      }\n\n\n      typename VariableSet::VariableSet pred(varSet) ;\n      for ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>(coarseLevel); \n\t      it != itEnd; ++it)\n\t{\n\t  (*boost::fusion::at_c<0>(pred.data))[ indexSet.index(*it) ] = (*boost::fusion::at_c<0>(x.data))[ gv.indexSet().index(*it) ] ;\n\t}\n\n      // now iterate over all grid levels\n      for( int l = coarseLevel ; l < maxLevel ; l++ )\n      {\n\tgv = gridManager.grid().levelView(l+1) ;\n\tspace.setGridView(gv);\n\t  \n\t*boost::fusion::at_c<0>(x.data) = *(mlTransfer->apply(l, *boost::fusion::at_c<0>(x.data))) ;\n  \n\tnodalValues.clear() ;\n\titEnd = gridManager.grid().template lend<dim>( l+1 );\n\tfor ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>( l+1 ); \n\t\tit != itEnd;  ++it)\n\t{\n\t  double val = (*boost::fusion::at_c<0>(x.data))[gv.indexSet().index(*it)] \n\t\t      -(*boost::fusion::at_c<0>(sol.data))[indexSet.index(*it)] ;\n\n\t  nodalValues.push_back(val);\n\t}\n\n\tub = *std::max_element( nodalValues.begin(), nodalValues.end() ) ;\n\tlb = *std::min_element( nodalValues.begin(), nodalValues.end() ) ;\n\t\n\t// symmetric mid tread quant\n\tub = *std::max_element( nodalValues.begin(), nodalValues.end(), abscompare ) ;\n\tif( ub < 0 ) { lb = ub ; ub = -lb  ; }\n\telse         { lb = -ub ; }\n\t// --\n\t\n\tout.write(reinterpret_cast<char*>( &lb ), sizeof(double) ) ; \n\tout.write(reinterpret_cast<char*>( &ub ), sizeof(double) ) ; \n\t\n\tif( uniform ) \n\t{\n\t  quantize( nodalValues, indices, l+1, lb, ub) ;\n\t  allIndices.push_back( indices ) ;\n\t  reconstruct( nodalValues, indices, l+1, lb, ub ) ;\n\t}\n\telse\n\t{\n\t  vertexCount = 0 ;\n\t  indices.clear() ; indices.resize(nodalValues.size(), 0);\n\t  \t    \n\t  for ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>( l+1 ) ;\n\t    it != itEnd; ++it )\n\t  {    \n\t    unsigned int vidx = gridManager.grid().leafIndexSet().index(*it) ;\n\t    \t    \n\t    indices[vertexCount] = quantize( nodalValues[vertexCount], lb, ub, it->geometry().corner(0), vidx );\n\t    nodalValues[vertexCount] = reconstruct( indices[vertexCount], lb, ub, it->geometry().corner(0), vidx );\n\t    vertexCount++ ;\n\t  }    \n\t  allIndices.push_back( indices ) ;\n\t}\n\t\n\t// prepare prediction on next level -- use reconstructed values\n\tvertexCount = 0 ;\n\tunsigned long skipped = 0 ;\n\tfor ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>( l+1 ); \n\t\tit != itEnd; ++it)\n\t{\n\t  // correction only for the nodes on level l+1\n\t  unsigned long ID = gridManager.grid().globalIdSet().id( *it ) ;\n\t  unsigned char vertexLevel = levelInfo[ID] ;\n\t  if( vertexLevel < l+1 ) { vertexCount++ ; skipped++ ; continue ; }\n\t  \n\t  (*boost::fusion::at_c<0>(x.data))[gv.indexSet().index(*it)] -= nodalValues[vertexCount] ;\n\t  vertexCount++ ;\n\t}\n// \tstd::cout << \"vertices on level \" << l+1 << \": \" << vertexCount - skipped << std::endl ;\n\n\t// now prediction to level l+1 is finished -- store in prediction variable set\n\tfor ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>(l+1); \n\t      it != itEnd; ++it)\n\t{\n\t  (*boost::fusion::at_c<0>(pred.data))[ indexSet.index(*it) ] = (*boost::fusion::at_c<0>(x.data))[ gv.indexSet().index(*it) ] ;\n\t}\n      }\n      \n      // evaluation of quantization error\n      pred -= sol ;\n//       std::vector<double> foo( gridManager.grid().size(dim) ) ;\n//       pred.write( foo.begin() ) ;\n//       double absQuantErr = fabs(*std::max_element(foo.begin(),foo.end(),abscompare)) ;\n//       sol.write( foo.begin() ) ;\n//       double relQuantErr = absQuantErr / fabs(*std::max_element(foo.begin(),foo.end(),abscompare)) ;\n//       std::cout << \"Linf quant err: abs = \" << absQuantErr << \"\\trel = \" << relQuantErr << \"\\n\" ;\n//       \n//       L2Norm l2 ; \n//       double l2q2 = l2.square( boost::fusion::at_c<0>(pred.vars) ) ;\n//       double l2y2 = l2.square( boost::fusion::at_c<0>(sol.vars) ) ;\n//       relQuantErr = sqrt(l2q2) / sqrt(l2y2) ;\n//       absQuantErr = sqrt(l2q2) ;\n//       std::cout << \"  L2 quant err: abs = \" << absQuantErr << \"\\trel = \" << relQuantErr << \"\\n\" ;\n\n      // debug output\n//       debugfn.str(\"\") ; debugfn << \"predErr\" << count ; debugfn.flush() ;\n//       writeVTKFile( gridManager.grid().leafView(), varSet, pred, debugfn.str(), ioOptions ) ;\n      \n      \n      // Now allIndices contains the collected interval numbers of all levels.\n      // In order to maximize efficiency of the range coder, precalculate the\n      // frequency of each interval, befor encoding.\n      typename VariableSet::VariableSet intervals(varSet) ; intervals *= 0 ;\n      for( int l = maxLevel ; l >= coarseLevel ; l-- )\n      {\n\tvertexCount = 0 ;\n\titEnd = gridManager.grid().template lend<dim>( l );\n\tfor ( VertexLevelIterator it = gridManager.grid().template lbegin<dim>( l ); \n\t\tit != itEnd;  ++it)\n\t{\n\t  (*boost::fusion::at_c<0>(intervals.data))[indexSet.index(*it)] = allIndices[l-coarseLevel][vertexCount] ;\n\t  vertexCount++ ;\n\t}\n      }\n\n     count++ ;\n\n      // and output the indices\n      std::vector<long int> intervalIndicesTmp( gridManager.grid().size(dim) ) ;\n      intervals.write( intervalIndicesTmp.begin() ) ;\n\n      // shift indices, only positive indices for range encoding\n      // TODO: could be skipped when not using differential encoding in time, indices are always >=0.\n      long int minIndex = *std::min_element( intervalIndicesTmp.begin(), intervalIndicesTmp.end() ) ;\n      std::vector<ULong> intervalIndices( gridManager.grid().size(dim) ) ;\n      \n      for( int i = 0 ; i < intervalIndicesTmp.size() ; i++ ) \n\tintervalIndices[i] = intervalIndicesTmp[i] - minIndex ;\n      \n      out.write(reinterpret_cast<char*>( &minIndex ), sizeof(long int) ) ;\n\n      long int maxIndex = *std::max_element( intervalIndices.begin(), intervalIndices.end() ) + 1 ;\n      \n      std::vector<ULong> frequencies( maxIndex, 0 ) ;\n      for( int i = 0 ; i < intervalIndices.size() ; i++ ) frequencies[ intervalIndices[i] ]++ ;\n\n      // only need to store symbols with nonzero frequency\n      unsigned int nnz = (unsigned int) std::count_if( frequencies.begin(), frequencies.end(), greaterZero<ULong> ) ;\n      \n      std::vector<int> dictionary( frequencies.size(), -1 ) ;\n      int cur_no = 0 ;\n      for( int i = 0 ; i < frequencies.size() ; i++ )\n      {\n\tif( frequencies[i] > 0 ) \n\t{ \n\t  dictionary[i] = cur_no ; cur_no++ ; \n\t}\n      }\n      out.write(reinterpret_cast<char*>( &nnz ), sizeof(unsigned int) ) ;\n      for( int i = 0 ; i < dictionary.size() ; i++ )\n      {\n\tif( dictionary[i] >= 0 ) out.write(reinterpret_cast<char*>( &i ), sizeof(int) ) ;\n      }\n      \n      frequencies.erase( std::remove(frequencies.begin(), frequencies.end(), 0), frequencies.end() ) ;\n      for( int i = 0 ; i < frequencies.size() ; i++ ) \n\tout.write(reinterpret_cast<char*>( &frequencies[i] ), sizeof(ULong) ) ; \n    \n      Alphabet<ULong> alphabet( frequencies.begin(), frequencies.end() ) ;\n      RangeEncoder<ULong> encoder( out ) ;\n      \n      for( int i = 0 ; i < intervalIndices.size(); i++ ) \n      {\n\tencodeSymbol( encoder, alphabet, dictionary[intervalIndices[i]] );\n      }\n      \n      // encoding without using precomputed frequencies\n//       int symbolCounter = 0 ;                 \n//       std::vector<ULong> count(maxIntervals, 1) ; \n//       Alphabet<ULong> alphabet( count.begin(), count.end() ) ; \n//       for( int i = 0 ; i < intervalIndices.size(); i++ ) \n//       {\n// \tencodeSymbol( encoder, alphabet, intervalIndices[i] );\n// \t++count[intervalIndices[i]];\n// \t++symbolCounter ;\n// \tif (symbolCounter>2*alphabet.size())\n// \t{\n// \t  alphabet.update(count.begin(),count.end());\n// \t  symbolCounter=0;\n// \t}\n//       }\n\n      return pred ; // return quantization error\n    }\n\n    /** In the end, write remaining indices to disc. */\n    void flush()  { } // not needed for version without temporal correlations\n    \n    void finish() { firstCall = true ; quantizationPolicy.resetCount() ; } ;\n\n    \n    /**\n     *  Decode quantized values and store in a VariableSet::VariableSet.\n     *  The file to be read is specified by the member variables \n     *  filePrefix and count, keeping track of the already decoded timesteps.\n     */\n    void decode( GridManager<Grid>& gridManagerState, typename VariableSet::VariableSet& sol, std::string fn ) \n    {  \n      fn += \".dat\" ;\n      \n      // for adaptivity in space, mlTransfer has to be recomputed\n      if( mlTransfer != NULL ) delete mlTransfer ;\n      mlTransfer = new MultilevelTransfer<Space,Grid>( gridManagerState, order, coarseLevel ) ;\n      \n      // build map: vertex id - level the vertex is created\n      unsigned long int ID ;\n      levelInfo.clear() ;\n      for( int level = 0 ; level <= gridManagerState.grid().maxLevel() ; level++ )\n      {\n\tfor ( VertexLevelIterator it = gridManagerState.grid().template lbegin <dim>( level ); \n\t      it != gridManagerState.grid().template lend <dim>( level ); ++ it)\n\t{\n\t  ID = gridManagerState.grid().globalIdSet().id( *it ) ;\n\t  if( levelInfo.find(ID) != levelInfo.end() ) continue ;\n\t  levelInfo[ID] = level ;\n\t}\n      }\n\n      // build hierarchic variable set -- could probably be moved to constructor\n      LevelView gv = gridManagerState.grid().levelView( coarseLevel ) ;\n      Space space( gridManagerState, gv, order ) ;\n      Spaces spaces( &space ) ;\n      std::string varNames[1] = { \"pred\" };\n      PredVariableSet predVarSet( spaces, varNames ) ;\n      typename PredVariableSet::VariableSet x( predVarSet ) ;\n      x *= 0 ;\n      \n      // prepare prediction\n      int maxLevel = gridManagerState.grid().maxLevel() ;\n      IndexSet const& indexSet = gridManagerState.grid().leafIndexSet();\n\n      std::vector<double> values ;\n      \n      std::vector<double> lb(maxLevel-coarseLevel+1), ub(maxLevel-coarseLevel+1) ;\n      \n      // read lb, ub from file\n      std::ifstream in( fn.c_str(), std::ios::binary ) ;  \n      for( int i = 0 ; i <= maxLevel-coarseLevel ; i++ )\n      {\n\tin.read( reinterpret_cast<char*>( &lb[i] ), sizeof(double) ) ; \n\tin.read( reinterpret_cast<char*>( &ub[i] ), sizeof(double) ) ; \n      }\n\n      // read in indices from file     \n      std::vector<long int> intervalIndices( gridManagerState.grid().size(dim) ) ;\n\n      long int minIndex ;\n      in.read(reinterpret_cast<char*>( &minIndex ), sizeof(long int) ) ;   \n\n      // # non-empty intervals\n      unsigned int nnz ;\n      in.read(reinterpret_cast<char*>( &nnz ), sizeof(unsigned int) ) ;\n      \n      // existing intervals (dictionary)\n      std::vector<int> dictionary( nnz ) ;\n      for( int i = 0 ; i < nnz ; i++ )\n      {\n\tin.read(reinterpret_cast<char*>( &dictionary[i] ), sizeof(int) ) ; \n      }\n      std::vector<ULong> frequencies( nnz, 0 ) ;\n      for( int i = 0 ; i < nnz ; i++ )\n\tin.read(reinterpret_cast<char*>( &frequencies[i] ), sizeof(ULong) ) ; // frequencies\n\n      Alphabet<ULong> alphabet( frequencies.begin(), frequencies.end() ) ; \n      try\n      {\n\tRangeDecoder<ULong> decoder( in ) ;\n\tfor( int i = 0 ; i < intervalIndices.size() ; i++ ) \n\t{\n\t  ULong s = decodeSymbol(decoder,alphabet) ;\n\t  intervalIndices[i] = dictionary[s] + minIndex ;\n\t}\n      }\n      catch( std::ios_base::failure& e ) { std::cout << e.what() << \" Decoding error\\n\" ; } \n\n      // version without using precomputed frequencies\n//       int symbolCounter = 0 ;                 // 2010-02-19\n//       std::vector<ULong> symcount(maxIntervals, 1) ; // 2010-02-19\n//       Alphabet<ULong> alphabet( symcount.begin(), symcount.end() ) ;//2010-02-19\n//       try\n//       {\n// \tRangeDecoder<ULong> decoder( in ) ;\n// \tfor( int i = 0 ; i < intervalIndices.size() ; i++ ) \n// \t{\n// \t  ULong s = decodeSymbol(decoder,alphabet) ;  \n// \t  intervalIndices[i] = s + minIndex ;\n// \t  ++symcount[s];\n// \t  ++symbolCounter ;\n// \t  if (symbolCounter>2*alphabet.size())\n// \t  {\n// \t    alphabet.update(symcount.begin(),symcount.end());\n// \t    symbolCounter=0;\n// \t  }\n// \t}\n//       }\n//       catch( std::ios_base::failure& e ) { std::cout << e.what() << \" Decoding error\\n\" ; } \n\n\n      // assign corrections to variableSet\n      typename VariableSet::VariableSet corr(sol) ; corr *= 0 ;\n      corr.read( intervalIndices.begin() ) ;\n     \n      // assign the overall vector to the single levels\n      std::vector<std::vector<ULong> > allIndices( maxLevel+1-coarseLevel ) ;\n      for( int l = coarseLevel ; l <= maxLevel ; l++ )\n      {\n\tfor ( VertexLevelIterator it = gridManagerState.grid().template lbegin<dim>( l ); \n\t      it != gridManagerState.grid().template lend<dim>( l ); ++it)\n\t{\n\t  allIndices[l-coarseLevel].push_back( (*boost::fusion::at_c<0>(corr.data))[indexSet.index(*it)] ) ;\n\t}\n      }\n\n      // start reconstruction\n      VertexLevelIterator itEnd = gridManagerState.grid().template lend<dim>( coarseLevel );\n      \n      int vertexCount = 0;\n      if( uniform )\n      {\n\treconstruct( values, allIndices[0], coarseLevel, lb[0], ub[0] );\n      }\n      else\n      {\n\tvalues.clear()  ; values.resize( allIndices[0].size() ) ;\n\tfor ( VertexLevelIterator it = gridManagerState.grid().template lbegin<dim>( coarseLevel ) ;\n\t  it != itEnd; ++it )\n\t{\n\t  unsigned int vidx = gridManagerState.grid().leafIndexSet().index(*it) ;\n\t  \n\t  values[vertexCount] = reconstruct( allIndices[0][vertexCount], lb[0], ub[0], it->geometry().corner(0),vidx );\n\t  vertexCount++ ;\n\t}    \n      }\n      \n      vertexCount = 0 ;\n      for ( VertexLevelIterator it = gridManagerState.grid().template lbegin<dim>( coarseLevel ); \n\t      it != itEnd; ++it)\n      {\n\t(*boost::fusion::at_c<0>(x.data))[gv.indexSet().index(*it)] = -values[vertexCount] ; \n\tvertexCount++ ;\n      }\n      \n      // store predicted values for the coarse grid in solution vector\n      for ( VertexLevelIterator it = gridManagerState.grid().template lbegin<dim>( coarseLevel ); \n\t      it != itEnd; ++it)\n      {\n\t(*boost::fusion::at_c<0>(sol.data))[ indexSet.index(*it) ] = (*boost::fusion::at_c<0>(x.data))[ gv.indexSet().index(*it) ] ;\n\tvertexCount++ ;\n      }\n      \n      // perform prediction and correction\n      for( int l = coarseLevel ; l < maxLevel ; l++ )\n      {\n\titEnd = gridManagerState.grid().template lend<dim>( l+1 );\n\t\n\tgv = gridManagerState.grid().levelView(l+1) ;\n\tspace.setGridView(gv);\n\t \n\t*boost::fusion::at_c<0>(x.data) = *(mlTransfer->apply(l, *boost::fusion::at_c<0>(x.data))) ;\n\n\tif( uniform )\n\t{\n\t  reconstruct( values, allIndices[l-coarseLevel+1], l+1, lb[l+1-coarseLevel], ub[l+1-coarseLevel] );\n\t}\n\telse\n\t{\n\t  vertexCount = 0;\n\t  values.clear();\n\t  values.resize( allIndices[l-coarseLevel+1].size() ) ;\n\t  \n\t  for ( VertexLevelIterator it = gridManagerState.grid().template lbegin<dim>( l+1 ) ;\n\t    it != itEnd; ++it )\n\t  {\t    \n\t    unsigned int vidx = gridManagerState.grid().leafIndexSet().index(*it) ;\n\t    \t    \n\t    values[vertexCount] = reconstruct( allIndices[l-coarseLevel+1][vertexCount], lb[l-coarseLevel+1], \n\t    ub[l-coarseLevel+1], it->geometry().corner(0), vidx );\n\t    vertexCount++ ;\n\t  }    \n\t}\n\t\n\tvertexCount = 0 ;\n\tfor ( VertexLevelIterator it = gridManagerState.grid().template lbegin<dim>( l+1 ); \n\t\tit != itEnd; ++it)\n\t{\n\t  //correct only vertices new on level l+1\n\t  if( levelInfo[gridManagerState.grid().globalIdSet().id(*it)] == l+1 ) \n\t  {\n\t    (*boost::fusion::at_c<0>(x.data))[gv.indexSet().index(*it)] -= values[vertexCount] ;\n\t  }\n\t  vertexCount++ ;\n\t}\n\t\n\t// store predicted values for the coarse grid in solution vector\n\tfor ( VertexLevelIterator it = gridManagerState.grid().template lbegin<dim>( l+1 ); \n\t      it != itEnd; ++it)\n\t{\n\t  (*boost::fusion::at_c<0>(sol.data))[ indexSet.index(*it) ] = (*boost::fusion::at_c<0>(x.data))[ gv.indexSet().index(*it) ] ;\n\t  vertexCount++ ;\n\t}\n      }\n      \n      count-- ;\n      \n      // debug output\n//       std::ostringstream debugfn ;\n//       debugfn << \"reconstruction\" << count ; debugfn.flush() ;\n//       writeVTKFile( varSet, sol, debugfn.str(), ioOptions ) ;\n\n      in.close() ;\n    }\n\n\n  private:\n    LossyStorage( LossyStorage const& );\n    LossyStorage& operator=( LossyStorage const& ) ;\n\n    /** Helper method to perform the actual quantization for a whole level. */\n    void quantize( std::vector<double> const& values, std::vector<ULong>& indices, int level, double lb, double ub )\n    {\n      double range = ub - lb ;\n     \n      long int nIntervals = quantizationPolicy.getIntervals( range, aTol );\n      \n      // needed for range encoding without precomputed frequencies\n      if( nIntervals > maxIntervals ) maxIntervals = nIntervals ; \n\n      // debug output\n//       std::cout << nIntervals << \"=\" \n// \t\t<< ( (nIntervals > 0) ? (int(ld(nIntervals)*100))/100.0 : 0 ) << \" / \" ;\n\n//      std::cout << \"  Level:  \" << level << \"  Intervals: \" << nIntervals \n//                 << \"   Bits:  \"  << ( (nIntervals > 0) ? (int(ld(nIntervals)*100))/100.0 : 0 )\n// \t\t<< \"\\n\" ;\n\n      indices.clear() ;\n      indices.resize( values.size(), 0 ) ;\n      if( range > 0 ) // if range is empty, indices[i]=0 for all values\n      {\n\tULong idx ;\n\tfor( int i = 0 ; i < values.size() ; i++ )\n\t{\n\t  idx = (ULong)( (values[i] - lb) * nIntervals / range ) + 1 ; \n\t  indices[i] = idx ;\n\t}\n      }\n    }\n    \n    /** Helper method to perform the actual quantization for a single node. */\n    ULong quantize( double value, double lb, double ub, Dune::FieldVector<double,dim> const& coor,\n\t\t    bool uniform = false, unsigned int vidx = 0 )\n    {\n      double range = ub - lb ;\n      \n      if( range == 0 ) return 0 ;\n      \n      long int nIntervals = quantizationPolicy.getIntervals( range, aTol, coor, uniform, vidx ) ;\n      \n      // needed for range encoding without precomputed frequencies\n      if( nIntervals > maxIntervals ) maxIntervals = nIntervals ;\n      \n      return (ULong)( (value - lb) * nIntervals / range ) + 1 ; \n    }\n    \n\n    /** Helper method to perform the actual reconstruction of quantized values. */\n    void reconstruct( std::vector<double>& values, std::vector<ULong> const& indices, int level, double lb, double ub )\n    {\n      double range = ub - lb ; \n\n      long int nIntervals = quantizationPolicy.getIntervals( range, aTol );\n\n      double delta ;\n      if( nIntervals <= 0 ) delta = 0 ;\n      else                  delta = range / nIntervals ;\n\n      values.clear() ;\n      values.resize( indices.size() ) ;\n      for( int i = 0 ; i < indices.size() ; i++ )\n      {\n\tif( indices[i] == 0 ) values[i] = lb ; \n\telse\t              values[i] = lb + (2*indices[i]-1) * delta/2 ;\n      }\n    }\n\n    /** Helper method to perform the actual reconstruction for a single node. */\n    double reconstruct( ULong index, double lb, double ub, Dune::FieldVector<double,dim> const& coor, \n\t\t\tbool uniform = false, unsigned int vidx = 0 )\n    {\n      double range = ub - lb ;\n      long int nIntervals = quantizationPolicy.getIntervals( range, aTol, coor, uniform, vidx ) ;\n      double delta ;\n      if( nIntervals <= 0 ) delta = 0 ;\n      else                  delta = range / nIntervals ;\n      if( index == 0 ) return lb ;\n      else             return lb + (2*index-1) * delta/2 ;\n    }\n\n\n    /** Helper method returning the base 2-logarithm. */\n    double ld( double val ) { return log(val)/log(2.0) ; }\n    \n    void setTolerance( double tol ) { aTol = tol ; }\n  \n  \n  private:\n    GridManager<Grid>& gridManager ;\n    VariableSet varSet ;\n    MultilevelTransfer<Space,Grid>* mlTransfer ;\n\n    int coarseLevel ;\n    double aTol ;\n    std::string filePrefix ;\n\n    int count ; // count timesteps\n    IoOptions ioOptions;\n\n    bool firstCall ;\n    long int maxIntervals ;\n\n    bool uniform ;\n    boost::unordered_map<unsigned long int, unsigned char> levelInfo ;\n    \n    int order; // degree of interpolation polynomials; currently only linear interpolation is supported\n  \n  public:\n    QuantizationPolicy quantizationPolicy ;\n  \n} ;\n\n#endif\n", "meta": {"hexsha": "741c3807d0ad9545f902abe0a6fdc2af1d1c49bf", "size": 28044, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/io/lossystorageWithoutTemporalPred.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/io/lossystorageWithoutTemporalPred.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/io/lossystorageWithoutTemporalPred.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.0462351387, "max_line_length": 135, "alphanum_fraction": 0.6033019541, "num_tokens": 7506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.08632347012222819, "lm_q1q2_score": 0.03451312822392072}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\r\n#define BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <utility>\r\n#include <boost/config/no_tr1/cmath.hpp>\r\n#include <stdexcept>\r\n\r\n#include <boost/math/tools/config.hpp>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/assert.hpp>\r\n#include <boost/throw_exception.hpp>\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning(push)\r\n#pragma warning(disable: 4512)\r\n#endif\r\n#include <boost/math/tools/tuple.hpp>\r\n#ifdef BOOST_MSVC\r\n#pragma warning(pop)\r\n#endif\r\n\r\n#include <boost/math/special_functions/sign.hpp>\r\n#include <boost/math/tools/toms748_solve.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace tools{\r\n\r\nnamespace detail{\r\n\r\ntemplate <class Tuple, class T>\r\ninline void unpack_0(const Tuple& t, T& val)\r\n{ val = boost::math::get<0>(t); }\r\n\r\ntemplate <class F, class T>\r\nvoid handle_zero_derivative(F f,\r\n                            T& last_f0,\r\n                            const T& f0,\r\n                            T& delta,\r\n                            T& result,\r\n                            T& guess,\r\n                            const T& min,\r\n                            const T& max)\r\n{\r\n   if(last_f0 == 0)\r\n   {\r\n      // this must be the first iteration, pretend that we had a\r\n      // previous one at either min or max:\r\n      if(result == min)\r\n      {\r\n         guess = max;\r\n      }\r\n      else\r\n      {\r\n         guess = min;\r\n      }\r\n      unpack_0(f(guess), last_f0);\r\n      delta = guess - result;\r\n   }\r\n   if(sign(last_f0) * sign(f0) < 0)\r\n   {\r\n      // we've crossed over so move in opposite direction to last step:\r\n      if(delta < 0)\r\n      {\r\n         delta = (result - min) / 2;\r\n      }\r\n      else\r\n      {\r\n         delta = (result - max) / 2;\r\n      }\r\n   }\r\n   else\r\n   {\r\n      // move in same direction as last step:\r\n      if(delta < 0)\r\n      {\r\n         delta = (result - max) / 2;\r\n      }\r\n      else\r\n      {\r\n         delta = (result - min) / 2;\r\n      }\r\n   }\r\n}\r\n\r\n} // namespace\r\n\r\ntemplate <class F, class T, class Tol, class Policy>\r\nstd::pair<T, T> bisect(F f, T min, T max, Tol tol, boost::uintmax_t& max_iter, const Policy& pol)\r\n{\r\n   T fmin = f(min);\r\n   T fmax = f(max);\r\n   if(fmin == 0)\r\n      return std::make_pair(min, min);\r\n   if(fmax == 0)\r\n      return std::make_pair(max, max);\r\n\r\n   //\r\n   // Error checking:\r\n   //\r\n   static const char* function = \"boost::math::tools::bisect<%1%>\";\r\n   if(min >= max)\r\n   {\r\n      return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,\r\n         \"Arguments in wrong order in boost::math::tools::bisect (first arg=%1%)\", min, pol));\r\n   }\r\n   if(fmin * fmax >= 0)\r\n   {\r\n      return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,\r\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));\r\n   }\r\n\r\n   //\r\n   // Three function invocations so far:\r\n   //\r\n   boost::uintmax_t count = max_iter;\r\n   if(count < 3)\r\n      count = 0;\r\n   else\r\n      count -= 3;\r\n\r\n   while(count && (0 == tol(min, max)))\r\n   {\r\n      T mid = (min + max) / 2;\r\n      T fmid = f(mid);\r\n      if((mid == max) || (mid == min))\r\n         break;\r\n      if(fmid == 0)\r\n      {\r\n         min = max = mid;\r\n         break;\r\n      }\r\n      else if(sign(fmid) * sign(fmin) < 0)\r\n      {\r\n         max = mid;\r\n         fmax = fmid;\r\n      }\r\n      else\r\n      {\r\n         min = mid;\r\n         fmin = fmid;\r\n      }\r\n      --count;\r\n   }\r\n\r\n   max_iter -= count;\r\n\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n   std::cout << \"Bisection iteration, final count = \" << max_iter << std::endl;\r\n\r\n   static boost::uintmax_t max_count = 0;\r\n   if(max_iter > max_count)\r\n   {\r\n      max_count = max_iter;\r\n      std::cout << \"Maximum iterations: \" << max_iter << std::endl;\r\n   }\r\n#endif\r\n\r\n   return std::make_pair(min, max);\r\n}\r\n\r\ntemplate <class F, class T, class Tol>\r\ninline std::pair<T, T> bisect(F f, T min, T max, Tol tol, boost::uintmax_t& max_iter)\r\n{\r\n   return bisect(f, min, max, tol, max_iter, policies::policy<>());\r\n}\r\n\r\ntemplate <class F, class T, class Tol>\r\ninline std::pair<T, T> bisect(F f, T min, T max, Tol tol)\r\n{\r\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\r\n   return bisect(f, min, max, tol, m, policies::policy<>());\r\n}\r\n\r\ntemplate <class F, class T>\r\nT newton_raphson_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   T f0(0), f1, last_f0(0);\r\n   T result = guess;\r\n\r\n   T factor = static_cast<T>(ldexp(1.0, 1 - digits));\r\n   T delta = 1;\r\n   T delta1 = tools::max_value<T>();\r\n   T delta2 = tools::max_value<T>();\r\n\r\n   boost::uintmax_t count(max_iter);\r\n\r\n   do{\r\n      last_f0 = f0;\r\n      delta2 = delta1;\r\n      delta1 = delta;\r\n      boost::math::tie(f0, f1) = f(result);\r\n      if(0 == f0)\r\n         break;\r\n      if(f1 == 0)\r\n      {\r\n         // Oops zero derivative!!!\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n         std::cout << \"Newton iteration, zero derivative found\" << std::endl;\r\n#endif\r\n         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);\r\n      }\r\n      else\r\n      {\r\n         delta = f0 / f1;\r\n      }\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n      std::cout << \"Newton iteration, delta = \" << delta << std::endl;\r\n#endif\r\n      if(fabs(delta * 2) > fabs(delta2))\r\n      {\r\n         // last two steps haven't converged, try bisection:\r\n         delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;\r\n      }\r\n      guess = result;\r\n      result -= delta;\r\n      if(result <= min)\r\n      {\r\n         delta = 0.5F * (guess - min);\r\n         result = guess - delta;\r\n         if((result == min) || (result == max))\r\n            break;\r\n      }\r\n      else if(result >= max)\r\n      {\r\n         delta = 0.5F * (guess - max);\r\n         result = guess - delta;\r\n         if((result == min) || (result == max))\r\n            break;\r\n      }\r\n      // update brackets:\r\n      if(delta > 0)\r\n         max = guess;\r\n      else\r\n         min = guess;\r\n   }while(--count && (fabs(result * factor) < fabs(delta)));\r\n\r\n   max_iter -= count;\r\n\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n   std::cout << \"Newton Raphson iteration, final count = \" << max_iter << std::endl;\r\n\r\n   static boost::uintmax_t max_count = 0;\r\n   if(max_iter > max_count)\r\n   {\r\n      max_count = max_iter;\r\n      std::cout << \"Maximum iterations: \" << max_iter << std::endl;\r\n   }\r\n#endif\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class F, class T>\r\ninline T newton_raphson_iterate(F f, T guess, T min, T max, int digits)\r\n{\r\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\r\n   return newton_raphson_iterate(f, guess, min, max, digits, m);\r\n}\r\n\r\ntemplate <class F, class T>\r\nT halley_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   T f0(0), f1, f2;\r\n   T result = guess;\r\n\r\n   T factor = static_cast<T>(ldexp(1.0, 1 - digits));\r\n   T delta = (std::max)(T(10000000 * guess), T(10000000));  // arbitarily large delta\r\n   T last_f0 = 0;\r\n   T delta1 = delta;\r\n   T delta2 = delta;\r\n\r\n   bool out_of_bounds_sentry = false;\r\n\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n   std::cout << \"Halley iteration, limit = \" << factor << std::endl;\r\n#endif\r\n\r\n   boost::uintmax_t count(max_iter);\r\n\r\n   do{\r\n      last_f0 = f0;\r\n      delta2 = delta1;\r\n      delta1 = delta;\r\n      boost::math::tie(f0, f1, f2) = f(result);\r\n\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(f0);\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(f1);\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(f2);\r\n      \r\n      if(0 == f0)\r\n         break;\r\n      if(f1 == 0)\r\n      {\r\n         // Oops zero derivative!!!\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n         std::cout << \"Halley iteration, zero derivative found\" << std::endl;\r\n#endif\r\n         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);\r\n      }\r\n      else\r\n      {\r\n         if(f2 != 0)\r\n         {\r\n            T denom = 2 * f0;\r\n            T num = 2 * f1 - f0 * (f2 / f1);\r\n\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(denom);\r\n            BOOST_MATH_INSTRUMENT_VARIABLE(num);\r\n\r\n            if((fabs(num) < 1) && (fabs(denom) >= fabs(num) * tools::max_value<T>()))\r\n            {\r\n               // possible overflow, use Newton step:\r\n               delta = f0 / f1;\r\n            }\r\n            else\r\n               delta = denom / num;\r\n            if(delta * f1 / f0 < 0)\r\n            {\r\n               // Oh dear, we have a problem as Newton and Halley steps\r\n               // disagree about which way we should move.  Probably\r\n               // there is cancelation error in the calculation of the\r\n               // Halley step, or else the derivatives are so small\r\n               // that their values are basically trash.  We will move\r\n               // in the direction indicated by a Newton step, but\r\n               // by no more than twice the current guess value, otherwise\r\n               // we can jump way out of bounds if we're not careful.\r\n               // See https://svn.boost.org/trac/boost/ticket/8314.\r\n               delta = f0 / f1;\r\n               if(fabs(delta) > 2 * fabs(guess))\r\n                  delta = (delta < 0 ? -1 : 1) * 2 * fabs(guess);\r\n            }\r\n         }\r\n         else\r\n            delta = f0 / f1;\r\n      }\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n      std::cout << \"Halley iteration, delta = \" << delta << std::endl;\r\n#endif\r\n      T convergence = fabs(delta / delta2);\r\n      if((convergence > 0.8) && (convergence < 2))\r\n      {\r\n         // last two steps haven't converged, try bisection:\r\n         delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;\r\n         if(fabs(delta) > result)\r\n            delta = sign(delta) * result; // protect against huge jumps!\r\n         // reset delta2 so that this branch will *not* be taken on the\r\n         // next iteration:\r\n         delta2 = delta * 3;\r\n         BOOST_MATH_INSTRUMENT_VARIABLE(delta);\r\n      }\r\n      guess = result;\r\n      result -= delta;\r\n      BOOST_MATH_INSTRUMENT_VARIABLE(result);\r\n\r\n      // check for out of bounds step:\r\n      if(result < min)\r\n      {\r\n         T diff = ((fabs(min) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(min))) ? T(1000)  : T(result / min);\r\n         if(fabs(diff) < 1)\r\n            diff = 1 / diff;\r\n         if(!out_of_bounds_sentry && (diff > 0) && (diff < 3))\r\n         {\r\n            // Only a small out of bounds step, lets assume that the result\r\n            // is probably approximately at min:\r\n            delta = 0.99f * (guess  - min);\r\n            result = guess - delta;\r\n            out_of_bounds_sentry = true; // only take this branch once!\r\n         }\r\n         else\r\n         {\r\n            delta = (guess - min) / 2;\r\n            result = guess - delta;\r\n            if((result == min) || (result == max))\r\n               break;\r\n         }\r\n      }\r\n      else if(result > max)\r\n      {\r\n         T diff = ((fabs(max) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(max))) ? T(1000) : T(result / max);\r\n         if(fabs(diff) < 1)\r\n            diff = 1 / diff;\r\n         if(!out_of_bounds_sentry && (diff > 0) && (diff < 3))\r\n         {\r\n            // Only a small out of bounds step, lets assume that the result\r\n            // is probably approximately at min:\r\n            delta = 0.99f * (guess  - max);\r\n            result = guess - delta;\r\n            out_of_bounds_sentry = true; // only take this branch once!\r\n         }\r\n         else\r\n         {\r\n            delta = (guess - max) / 2;\r\n            result = guess - delta;\r\n            if((result == min) || (result == max))\r\n               break;\r\n         }\r\n      }\r\n      // update brackets:\r\n      if(delta > 0)\r\n         max = guess;\r\n      else\r\n         min = guess;\r\n   }while(--count && (fabs(result * factor) < fabs(delta)));\r\n\r\n   max_iter -= count;\r\n\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n   std::cout << \"Halley iteration, final count = \" << max_iter << std::endl;\r\n#endif\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class F, class T>\r\ninline T halley_iterate(F f, T guess, T min, T max, int digits)\r\n{\r\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\r\n   return halley_iterate(f, guess, min, max, digits, m);\r\n}\r\n\r\ntemplate <class F, class T>\r\nT schroeder_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter)\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   T f0(0), f1, f2, last_f0(0);\r\n   T result = guess;\r\n\r\n   T factor = static_cast<T>(ldexp(1.0, 1 - digits));\r\n   T delta = 0;\r\n   T delta1 = tools::max_value<T>();\r\n   T delta2 = tools::max_value<T>();\r\n\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n   std::cout << \"Schroeder iteration, limit = \" << factor << std::endl;\r\n#endif\r\n\r\n   boost::uintmax_t count(max_iter);\r\n\r\n   do{\r\n      last_f0 = f0;\r\n      delta2 = delta1;\r\n      delta1 = delta;\r\n      boost::math::tie(f0, f1, f2) = f(result);\r\n      if(0 == f0)\r\n         break;\r\n      if((f1 == 0) && (f2 == 0))\r\n      {\r\n         // Oops zero derivative!!!\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n         std::cout << \"Halley iteration, zero derivative found\" << std::endl;\r\n#endif\r\n         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);\r\n      }\r\n      else\r\n      {\r\n         T ratio = f0 / f1;\r\n         if(ratio / result < 0.1)\r\n         {\r\n            delta = ratio + (f2 / (2 * f1)) * ratio * ratio;\r\n            // check second derivative doesn't over compensate:\r\n            if(delta * ratio < 0)\r\n               delta = ratio;\r\n         }\r\n         else\r\n            delta = ratio;  // fall back to Newton iteration.\r\n      }\r\n      if(fabs(delta * 2) > fabs(delta2))\r\n      {\r\n         // last two steps haven't converged, try bisection:\r\n         delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;\r\n      }\r\n      guess = result;\r\n      result -= delta;\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n      std::cout << \"Halley iteration, delta = \" << delta << std::endl;\r\n#endif\r\n      if(result <= min)\r\n      {\r\n         delta = 0.5F * (guess - min);\r\n         result = guess - delta;\r\n         if((result == min) || (result == max))\r\n            break;\r\n      }\r\n      else if(result >= max)\r\n      {\r\n         delta = 0.5F * (guess - max);\r\n         result = guess - delta;\r\n         if((result == min) || (result == max))\r\n            break;\r\n      }\r\n      // update brackets:\r\n      if(delta > 0)\r\n         max = guess;\r\n      else\r\n         min = guess;\r\n   }while(--count && (fabs(result * factor) < fabs(delta)));\r\n\r\n   max_iter -= count;\r\n\r\n#ifdef BOOST_MATH_INSTRUMENT\r\n   std::cout << \"Schroeder iteration, final count = \" << max_iter << std::endl;\r\n\r\n   static boost::uintmax_t max_count = 0;\r\n   if(max_iter > max_count)\r\n   {\r\n      max_count = max_iter;\r\n      std::cout << \"Maximum iterations: \" << max_iter << std::endl;\r\n   }\r\n#endif\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class F, class T>\r\ninline T schroeder_iterate(F f, T guess, T min, T max, int digits)\r\n{\r\n   boost::uintmax_t m = (std::numeric_limits<boost::uintmax_t>::max)();\r\n   return schroeder_iterate(f, guess, min, max, digits, m);\r\n}\r\n\r\n} // namespace tools\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP\r\n\r\n\r\n\r\n", "meta": {"hexsha": "4b1621e2a5cd158ad7800da9f5c300349ac35dcc", "size": 15583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/tools/roots.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/tools/roots.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/tools/roots.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 28.6979742173, "max_line_length": 167, "alphanum_fraction": 0.5273695694, "num_tokens": 4155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.07159119795892385, "lm_q1q2_score": 0.034398044155169755}}
{"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 *      130218    D. Dirkx          File created from personal application.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\n\nnamespace tudat\n{\nnamespace basic_astrodynamics\n{\n\n//! Compute number of seconds since a reference Julian day.\ndouble convertJulianDayToSecondsSinceEpoch( const double julianDay,\n                                            const double epochSinceJulianDayZero )\n{\n    return ( julianDay - epochSinceJulianDayZero ) * physical_constants::JULIAN_DAY;\n}\n\n//! Compute Julian day from seconds since reference Julian day epoch.\ndouble convertSecondsSinceEpochToJulianDay( const double secondsSinceEpoch,\n                                            const double epochSinceJulianDayZero )\n{\n    return ( secondsSinceEpoch / physical_constants::JULIAN_DAY + epochSinceJulianDayZero );\n}\n\n//! Compute the Julian day from the calendar date and time.\ndouble convertCalendarDateToJulianDay( const int calendarYear,\n                                       const int calendarMonth,\n                                       const int calendarDay,\n                                       const int calendarHour,\n                                       const int calendarMinutes,\n                                       const double calendarSeconds )\n{\n    // Calculate julian day of calendar date.\n    double julianDay = boost::gregorian::date( calendarYear, calendarMonth, calendarDay ).julian_day( );\n\n    //Compute day fraction\n    const double dayFraction = static_cast< double >( calendarHour ) / 24.0 +\n                               static_cast< double >( calendarMinutes ) / ( 24.0 * 60.0 ) +\n                               calendarSeconds / ( 24.0 * 3600.0 );\n\n    // Compute Julian day by adding day fraction and subtracting 0.5 to reference to midnight\n    // instead of noon..\n    return julianDay + dayFraction - 0.5;\n}\n\n} // namespace basic_astrodynamics\n} // namespace tudat\n", "meta": {"hexsha": "3a7d483c517e6e47585317244f1b0aeb76dfe665", "size": 3811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.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/BasicAstrodynamics/timeConversions.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/BasicAstrodynamics/timeConversions.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": 45.9156626506, "max_line_length": 104, "alphanum_fraction": 0.6775124639, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.07263670736453837, "lm_q1q2_score": 0.034334171367330996}}
{"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/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/playground/spaces/finitevolume/default.hh>\n#include <dune/gdt/playground/spaces/raviartthomas/pdelab.hh>\n#include <dune/gdt/products/boundaryl2.hh>\n#include <dune/gdt/products/elliptic.hh>\n#include <dune/gdt/products/h1.hh>\n#include <dune/gdt/products/l2.hh>\n#include <dune/gdt/spaces/discontinuouslagrange.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::DiscontinuousLagrangeProvider< GridType, layer, space_backend,\n                                                      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::ConstProviderInterface< 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    return DiscretizationInterface< Traits >::static_id() + \".swipdg\";\n  }\n\n  SWIPDG(const 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    : BaseType(std::make_shared< TestSpaceType >(SpaceProvider::create(grid_provider, level_or_subdomain)),\n               std::make_shared< AnsatzSpaceType >(SpaceProvider::create(grid_provider, level_or_subdomain)),\n               bound_inf_cfg,\n               prob)\n    , beta_(GDT::LocalEvaluation::SWIPDG::internal::default_beta(dimDomain))\n    , pattern_(EllipticOperatorType::pattern(*(BaseType::test_space()), *(BaseType::ansatz_space())))\n    , only_these_products_(only_these_products)\n  {\n    // in case of parametric diffusion tensor this discretization is not affinely decomposable any more\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  } // SWIPDG(...)\n\n#if HAVE_DUNE_GRID_MULTISCALE\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    : BaseType(std::make_shared< TestSpaceType >(SpaceProvider::create(grid_provider, level_or_subdomain)),\n               std::make_shared< AnsatzSpaceType >(SpaceProvider::create(grid_provider, level_or_subdomain)),\n               bound_inf_cfg,\n               prob)\n    , beta_(GDT::LocalEvaluation::SWIPDG::internal::default_beta(dimDomain))\n    , pattern_(EllipticOperatorType::pattern(*(BaseType::test_space()), *(BaseType::ansatz_space())))\n    , only_these_products_(only_these_products)\n  {\n    // in case of parametric diffusion tensor this discretization is not affinely decomposable any more\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  } // SWIPDG(...)\n#endif // HAVE_DUNE_GRID_MULTISCALE\n\n  const PatternType& pattern() const\n  {\n    return pattern_;\n  }\n\n  void init(std::ostream& out = Stuff::Common::Logger().devnull(), const std::string prefix = \"\")\n  {\n    if (!this->container_based_initialized_) {\n      using namespace GDT;\n\n      auto& matrix = *(this->matrix_);\n      auto& rhs = *(this->rhs_);\n      const auto& space = *(this->test_space_);\n      const auto& boundary_info = *(this->boundary_info_);\n\n      out << prefix << \"assembling... \" << std::flush;\n      Dune::Timer timer;\n      SystemAssembler< TestSpaceType > system_assembler(space);\n      Stuff::Grid::Functor::DirichletDetector< GridViewType > dirichlet_detector(this->boundary_info());\n      system_assembler.add(dirichlet_detector);\n\n      // lhs operator\n      const auto& diffusion_factor = *(this->problem_.diffusion_factor());\n      const auto& diffusion_tensor = *(this->problem_.diffusion_tensor());\n      assert(!diffusion_tensor.parametric());\n      assert(diffusion_tensor.has_affine_part());\n      std::vector< std::unique_ptr< EllipticOperatorType > > elliptic_operators;\n      for (size_t qq = 0; qq < boost::numeric_cast< size_t >(diffusion_factor.num_components()); ++qq) {\n        const size_t id = matrix.register_component(diffusion_factor.coefficient(qq),\n                                                    space.mapper().size(), space.mapper().size(), pattern_);\n        elliptic_operators.emplace_back(new EllipticOperatorType(\n            *(diffusion_factor.component(qq)),\n            *(diffusion_tensor.affine_part()),\n            boundary_info,\n            *(matrix.component(id)),\n            space));\n      }\n      if (diffusion_factor.has_affine_part()) {\n        if (!matrix.has_affine_part())\n          matrix.register_affine_part(space.mapper().size(), space.mapper().size(), pattern_);\n        elliptic_operators.emplace_back(new EllipticOperatorType(\n            *(diffusion_factor.affine_part()),\n            *(diffusion_tensor.affine_part()),\n            boundary_info,\n            *(matrix.affine_part()),\n            space));\n      }\n      for (auto& elliptic_operator : elliptic_operators)\n        system_assembler.add(*elliptic_operator);\n\n      // rhs functional\n      // * volume\n      typedef typename ProblemType::FunctionType::NonparametricType FunctionType;\n      const auto& force = *(this->problem_.force());\n      typedef Functionals::L2Volume< FunctionType, VectorType, TestSpaceType > L2VolumeFunctionalType;\n      std::vector< std::unique_ptr< L2VolumeFunctionalType > > force_functionals;\n      for (size_t qq = 0; qq < boost::numeric_cast< size_t >(force.num_components()); ++qq) {\n        const size_t id = rhs.register_component(force.coefficient(qq), space.mapper().size());\n        force_functionals.emplace_back(new L2VolumeFunctionalType(*(force.component(qq)),\n                                                                  *(rhs.component(id)),\n                                                                  space));\n      }\n      if (force.has_affine_part()) {\n        if (!rhs.has_affine_part())\n          rhs.register_affine_part(space.mapper().size());\n        force_functionals.emplace_back(new L2VolumeFunctionalType(*(force.affine_part()),\n                                                                  *(rhs.affine_part()),\n                                                                  space));\n      }\n      for (auto& force_functional : force_functionals)\n        system_assembler.add(*force_functional);\n      // * dirichlet boundary\n      const auto& dirichlet = *(this->problem_.dirichlet());\n      typedef Functionals::DirichletBoundarySWIPDG< DiffusionFactorType, FunctionType, VectorType, TestSpaceType,\n                                                    GridViewType, DiffusionTensorType > DirichletBoundaryFunctionalType;\n      std::vector< std::unique_ptr< DirichletBoundaryFunctionalType > > dirichlet_boundary_functionals;\n      if (diffusion_factor.has_affine_part() && dirichlet.has_affine_part()) {\n        if (!rhs.has_affine_part())\n          rhs.register_affine_part(space.mapper().size());\n        dirichlet_boundary_functionals.emplace_back(new DirichletBoundaryFunctionalType(\n            *(diffusion_factor.affine_part()),\n            *(diffusion_tensor.affine_part()),\n            *(dirichlet.affine_part()),\n            boundary_info,\n            *(rhs.affine_part()),\n            space));\n      }\n      if (diffusion_factor.has_affine_part()) {\n        for (size_t qq = 0; qq < boost::numeric_cast< size_t >(dirichlet.num_components()); ++qq) {\n          const size_t id = rhs.register_component(dirichlet.coefficient(qq), space.mapper().size());\n          dirichlet_boundary_functionals.emplace_back(new DirichletBoundaryFunctionalType(\n              *(diffusion_factor.affine_part()),\n              *(diffusion_tensor.affine_part()),\n              *(dirichlet.component(qq)),\n              boundary_info,\n              *(rhs.component(id)),\n              space));\n        }\n      }\n      if (dirichlet.has_affine_part()) {\n        for (size_t qq = 0; qq < boost::numeric_cast< size_t >(diffusion_factor.num_components()); ++qq) {\n          const size_t id = rhs.register_component(diffusion_factor.coefficient(qq), space.mapper().size());\n          dirichlet_boundary_functionals.emplace_back(new DirichletBoundaryFunctionalType(\n              *(diffusion_factor.component(qq)),\n              *(diffusion_tensor.affine_part()),\n              *(dirichlet.affine_part()),\n              boundary_info,\n              *(rhs.component(id)),\n              space));\n        }\n      }\n      Pymor::ParameterType param;\n      for (const auto& key : diffusion_factor.parameter_type().keys())\n        param.set(key, diffusion_factor.parameter_type().get(key));\n      for (const auto& key : dirichlet.parameter_type().keys())\n        param.set(key, dirichlet.parameter_type().get(key));\n      for (size_t pp = 0; pp < boost::numeric_cast< size_t >(diffusion_factor.num_components()); ++ pp) {\n        for (size_t qq = 0; qq < boost::numeric_cast< size_t >(dirichlet.num_components()); ++qq) {\n          const std::string expression = \"(\" + diffusion_factor.coefficient(pp)->expression()\n                                             + \")*(\" + dirichlet.coefficient(qq)->expression() + \")\";\n          const size_t id = rhs.register_component(param, expression, space.mapper().size());\n          dirichlet_boundary_functionals.emplace_back(new DirichletBoundaryFunctionalType(\n              *(diffusion_factor.component(pp)),\n              *(diffusion_tensor.affine_part()),\n              *(dirichlet.component(qq)),\n              boundary_info,\n              *(rhs.component(id)),\n              space));\n        }\n      }\n      for (auto& dirichlet_boundary_functional : dirichlet_boundary_functionals)\n        system_assembler.add(*dirichlet_boundary_functional);\n\n      // * neumann boundary\n      const auto& neumann = *(this->problem_.neumann());\n      typedef Functionals::L2Face< FunctionType, VectorType, TestSpaceType > L2FaceFunctionalType;\n      std::vector< std::unique_ptr< L2FaceFunctionalType > > neumann_boundary_functionals;\n      for (size_t qq = 0; qq < boost::numeric_cast< size_t >(neumann.num_components()); ++qq) {\n        const size_t id = rhs.register_component(neumann.coefficient(qq), space.mapper().size());\n        neumann_boundary_functionals.emplace_back(new L2FaceFunctionalType(\n            *(neumann.component(qq)),\n            *(rhs.component(id)),\n            space,\n            new Stuff::Grid::ApplyOn::NeumannIntersections< GridViewType >(boundary_info)));\n      }\n      if (neumann.has_affine_part()) {\n        if (!rhs.has_affine_part())\n          rhs.register_affine_part(space.mapper().size());\n        neumann_boundary_functionals.emplace_back(new L2FaceFunctionalType(\n            *(neumann.affine_part()),\n            *(rhs.affine_part()),\n            space,\n            new Stuff::Grid::ApplyOn::NeumannIntersections< GridViewType >(boundary_info)));\n      }\n      for (auto& neumann_boundary_functional : neumann_boundary_functionals)\n        system_assembler.add(*neumann_boundary_functional);\n\n      // products\n      const size_t over_integrate = 2;\n      // * L2\n      typedef Products::L2Assemblable< MatrixType, TestSpaceType, GridViewType, AnsatzSpaceType > 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                                                       this->grid_view(),\n                                                       *this->ansatz_space(),\n                                                       over_integrate);\n        system_assembler.add(*l2_product);\n      }\n      // * H1 semi\n      typedef Products::H1SemiAssemblable< MatrixType, TestSpaceType, GridViewType, 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                                                       this->grid_view(),\n                                                       *this->ansatz_space(),\n                                                       over_integrate);\n        system_assembler.add(*h1_product);\n      }\n      // * elliptic\n      assert(!diffusion_tensor.parametric());\n      typedef Products::EllipticAssemblable< MatrixType, DiffusionFactorType, TestSpaceType, GridViewType,\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                                                                 this->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                                                                 this->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 Products::BoundaryL2Assemblable< MatrixType, TestSpaceType, GridViewType, 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                                                                        this->grid_view(),\n                                                                        *this->ansatz_space(),\n                                                                        over_integrate);\n        system_assembler.add(*boundary_l2_product);\n      }\n      // * penalty term\n      typedef 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                                                               this->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                                                               this->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      // do the actual assembling\n      system_assembler.walk();\n      out << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n\n      if (!dirichlet_detector.found())\n        this->purely_neumann_ = true;\n\n      // build parameter type\n      this->inherit_parameter_type(matrix.parameter_type(), \"lhs\");\n      this->inherit_parameter_type(rhs.parameter_type(),    \"rhs\");\n\n      // finalize\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\n      this->container_based_initialized_ = true;\n    } // if (!this->container_based_initialized_)\n  } // ... init(...)\n\nprivate:\n  friend class BlockSWIPDG< GridImp, RangeFieldImp, rangeDim, polynomialOrder, la_backend >;\n\n  const RangeFieldType beta_;\n  PatternType pattern_;\n  const std::vector< std::string > only_these_products_;\n}; // class SWIPDG\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": "64a4f31f94ae37e38dd755212632f757aad30fc4", "size": 28859, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/discretizations/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/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/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": 54.5538752363, "max_line_length": 125, "alphanum_fraction": 0.5988426487, "num_tokens": 5910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06853749778844886, "lm_q1q2_score": 0.03426874889422443}}
{"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 StatPro Italia srl\n Copyright (C) 2004, 2005, 2006 Ferdinando Ametrano\n Copyright (C) 2006 Katiuscia Manzoni\n Copyright (C) 2006 Toyin Akin\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 date.hpp\n    \\brief date- and time-related classes, typedefs and enumerations\n*/\n\n#ifndef quantlib_date_hpp\n#define quantlib_date_hpp\n\n#include <ql/time/period.hpp>\n#include <ql/time/weekday.hpp>\n#include <ql/utilities/null.hpp>\n#include <boost/cstdint.hpp>\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n#include <boost/date_time/posix_time/ptime.hpp>\n#include <boost/date_time/posix_time/posix_time_duration.hpp>\n#endif\n\n#include <utility>\n#include <functional>\n\n\nnamespace QuantLib {\n\n    //! Day number\n    /*! \\ingroup datetime */\n    typedef Integer Day;\n\n    //! Month names\n    /*! \\ingroup datetime */\n    enum Month { January   = 1,\n                 February  = 2,\n                 March     = 3,\n                 April     = 4,\n                 May       = 5,\n                 June      = 6,\n                 July      = 7,\n                 August    = 8,\n                 September = 9,\n                 October   = 10,\n                 November  = 11,\n                 December  = 12,\n                 Jan = 1,\n                 Feb = 2,\n                 Mar = 3,\n                 Apr = 4,\n                 Jun = 6,\n                 Jul = 7,\n                 Aug = 8,\n                 Sep = 9,\n                 Oct = 10,\n                 Nov = 11,\n                 Dec = 12\n    };\n\n    /*! \\relates Month */\n    std::ostream& operator<<(std::ostream&, Month);\n\n    //! Year number\n    /*! \\ingroup datetime */\n    typedef Integer Year;\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n    //! Hour number\n    /*! \\ingroup datetime */\n    typedef boost::posix_time::hours::hour_type Hour;\n\n    //! Minute number\n    /*! \\ingroup datetime */\n    typedef boost::posix_time::minutes::min_type Minute;\n\n    //! Second number\n    /*! \\ingroup datetime */\n    typedef boost::posix_time::minutes::sec_type Second;\n\n    //! Millisecond number\n    /*! \\ingroup datetime */\n    typedef boost::posix_time::time_duration::fractional_seconds_type\n        Millisecond;\n\n    //! Millisecond number\n    /*! \\ingroup datetime */\n    typedef boost::posix_time::time_duration::fractional_seconds_type\n        Microsecond;\n#endif\n\n    //! Concrete date class\n    /*! This class provides methods to inspect dates as well as methods and\n        operators which implement a limited date algebra (increasing and\n        decreasing dates, and calculating their difference).\n\n        \\ingroup datetime\n\n        \\test self-consistency of dates, serial numbers, days of\n              month, months, and weekdays is checked over the whole\n              date range.\n    */\n\n    class Date {\n      public:\n        //! serial number type\n        typedef boost::int_fast32_t serial_type;\n        //! \\name constructors\n        //@{\n        //! Default constructor returning a null date.\n        Date();\n        //! Constructor taking a serial number as given by Applix or Excel.\n        explicit Date(Date::serial_type serialNumber);\n        //! More traditional constructor.\n        Date(Day d, Month m, Year y);\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n        //! Constructor taking boost posix date time object\n        explicit Date(const boost::posix_time::ptime& localTime);\n        //! More traditional constructor.\n        Date(Day d, Month m, Year y,\n             Hour hours, Minute minutes, Second seconds,\n             Millisecond millisec = 0, Microsecond microsec = 0);\n#endif\n        //@}\n\n        //! \\name inspectors\n        //@{\n        Weekday weekday() const;\n        Day dayOfMonth() const;\n        //! One-based (Jan 1st = 1)\n        Day dayOfYear() const;\n        Month month() const;\n        Year year() const;\n        Date::serial_type serialNumber() const;\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n        Hour hours() const;\n        Minute minutes() const;\n        Second seconds() const;\n        Millisecond milliseconds() const;\n        Microsecond microseconds() const;\n\n        Time fractionOfDay() const;\n        Time fractionOfSecond() const;\n\n        const boost::posix_time::ptime& dateTime() const;\n#endif\n        //@}\n\n        //! \\name date algebra\n        //@{\n        //! increments date by the given number of days\n        Date& operator+=(Date::serial_type days);\n        //! increments date by the given period\n        Date& operator+=(const Period&);\n        //! decrement date by the given number of days\n        Date& operator-=(Date::serial_type days);\n        //! decrements date by the given period\n        Date& operator-=(const Period&);\n        //! 1-day pre-increment\n        Date& operator++();\n        //! 1-day post-increment\n        Date operator++(int );\n        //! 1-day pre-decrement\n        Date& operator--();\n        //! 1-day post-decrement\n        Date operator--(int );\n        //! returns a new date incremented by the given number of days\n        Date operator+(Date::serial_type days) const;\n        //! returns a new date incremented by the given period\n        Date operator+(const Period&) const;\n        //! returns a new date decremented by the given number of days\n        Date operator-(Date::serial_type days) const;\n        //! returns a new date decremented by the given period\n        Date operator-(const Period&) const;\n        //@}\n\n        //! \\name static methods\n        //@{\n        //! today's date.\n        static Date todaysDate();\n        //! earliest allowed date\n        static Date minDate();\n        //! latest allowed date\n        static Date maxDate();\n        //! whether the given year is a leap one\n        static bool isLeap(Year y);\n        //! last day of the month to which the given date belongs\n        static Date endOfMonth(const Date& d);\n        //! whether a date is the last day of its month\n        static bool isEndOfMonth(const Date& d);\n        //! next given weekday following or equal to the given date\n        /*! E.g., the Friday following Tuesday, January 15th, 2002\n            was January 18th, 2002.\n\n            see http://www.cpearson.com/excel/DateTimeWS.htm\n        */\n        static Date nextWeekday(const Date& d,\n                                Weekday w);\n        //! n-th given weekday in the given month and year\n        /*! E.g., the 4th Thursday of March, 1998 was March 26th,\n            1998.\n\n            see http://www.cpearson.com/excel/DateTimeWS.htm\n        */\n        static Date nthWeekday(Size n,\n                               Weekday w,\n                               Month m,\n                               Year y);\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n        //! local date time, based on the time zone settings of the computer\n        static Date localDateTime();\n        //! UTC date time\n        static Date universalDateTime();\n\n        //! underlying resolution of the  posix date time object\n        static Size ticksPerSecond();\n#endif\n\n        //@}\n\n      private:\n        static Date::serial_type minimumSerialNumber();\n        static Date::serial_type maximumSerialNumber();\n        static void checkSerialNumber(Date::serial_type serialNumber);\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n        boost::posix_time::ptime dateTime_;\n#else\n        Date::serial_type serialNumber_;\n        static Date advance(const Date& d, Integer units, TimeUnit);\n        static Integer monthLength(Month m, bool leapYear);\n        static Integer monthOffset(Month m, bool leapYear);\n        static Date::serial_type yearOffset(Year y);\n#endif\n    };\n\n    /*! \\relates Date\n        \\brief Difference in days between dates\n    */\n    Date::serial_type operator-(const Date&, const Date&);\n    /*! \\relates Date\n        \\brief Difference in days (including fraction of days) between dates\n    */\n    Time daysBetween(const Date&, const Date&);\n\n    /*! \\relates Date */\n    bool operator==(const Date&, const Date&);\n    /*! \\relates Date */\n    bool operator!=(const Date&, const Date&);\n    /*! \\relates Date */\n    bool operator<(const Date&, const Date&);\n    /*! \\relates Date */\n    bool operator<=(const Date&, const Date&);\n    /*! \\relates Date */\n    bool operator>(const Date&, const Date&);\n    /*! \\relates Date */\n    bool operator>=(const Date&, const Date&);\n\n    /*! \\relates Date */\n    std::ostream& operator<<(std::ostream&, const Date&);\n\n    namespace detail {\n\n        struct short_date_holder {\n            short_date_holder(const Date d) : d(d) {}\n            Date d;\n        };\n        std::ostream& operator<<(std::ostream&, const short_date_holder&);\n\n        struct long_date_holder {\n            long_date_holder(const Date& d) : d(d) {}\n            Date d;\n        };\n        std::ostream& operator<<(std::ostream&, const long_date_holder&);\n\n        struct iso_date_holder {\n            iso_date_holder(const Date& d) : d(d) {}\n            Date d;\n        };\n        std::ostream& operator<<(std::ostream&, const iso_date_holder&);\n\n        struct formatted_date_holder {\n            formatted_date_holder(const Date& d, const std::string& f)\n            : d(d), f(f) {}\n            Date d;\n            std::string f;\n        };\n        std::ostream& operator<<(std::ostream&,\n                                 const formatted_date_holder&);\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n        struct iso_datetime_holder {\n            iso_datetime_holder(const Date& d) : d(d) {}\n            Date d;\n        };\n        std::ostream& operator<<(std::ostream&, const iso_datetime_holder&);\n#endif\n    }\n\n    namespace io {\n\n        //! output dates in short format (mm/dd/yyyy)\n        /*! \\ingroup manips */\n        detail::short_date_holder short_date(const Date&);\n\n        //! output dates in long format (Month ddth, yyyy)\n        /*! \\ingroup manips */\n        detail::long_date_holder long_date(const Date&);\n\n        //! output dates in ISO format (yyyy-mm-dd)\n        /*! \\ingroup manips */\n        detail::iso_date_holder iso_date(const Date&);\n\n        //! output dates in user defined format using boost date functionality\n        /*! \\ingroup manips */\n        detail::formatted_date_holder formatted_date(const Date&,\n                                                     const std::string& fmt);\n\n#ifdef QL_HIGH_RESOLUTION_DATE\n        //! output datetimes in ISO format (YYYY-MM-DDThh:mm:ss,SSSSSS)\n        /*! \\ingroup manips */\n        detail::iso_datetime_holder iso_datetime(const Date&);\n#endif\n\n    }\n\n    //! specialization of Null template for the Date class\n    template <>\n    class Null<Date> {\n      public:\n        Null() {}\n        operator Date() const { return Date(); }\n    };\n\n\n#ifndef QL_HIGH_RESOLUTION_DATE\n    // inline definitions\n\n    inline Weekday Date::weekday() const {\n        Integer w = serialNumber_ % 7;\n        return Weekday(w == 0 ? 7 : w);\n    }\n\n    inline Day Date::dayOfMonth() const {\n        return dayOfYear() - monthOffset(month(),isLeap(year()));\n    }\n\n    inline Day Date::dayOfYear() const {\n        return serialNumber_ - yearOffset(year());\n    }\n\n    inline Date::serial_type Date::serialNumber() const {\n        return serialNumber_;\n    }\n\n    inline Date Date::operator+(Date::serial_type days) const {\n        return Date(serialNumber_+days);\n    }\n\n    inline Date Date::operator-(Date::serial_type days) const {\n        return Date(serialNumber_-days);\n    }\n\n    inline Date Date::operator+(const Period& p) const {\n        return advance(*this,p.length(),p.units());\n    }\n\n    inline Date Date::operator-(const Period& p) const {\n        return advance(*this,-p.length(),p.units());\n    }\n\n    inline Date Date::endOfMonth(const Date& d) {\n        Month m = d.month();\n        Year y = d.year();\n        return Date(monthLength(m, isLeap(y)), m, y);\n    }\n\n    inline bool Date::isEndOfMonth(const Date& d) {\n       return (d.dayOfMonth() == monthLength(d.month(), isLeap(d.year())));\n    }\n\n    inline Date::serial_type operator-(const Date& d1, const Date& d2) {\n        return d1.serialNumber()-d2.serialNumber();\n    }\n\n    inline Time daysBetween(const Date& d1, const Date& d2) {\n        return Time(d2-d1);\n    }\n\n    inline bool operator==(const Date& d1, const Date& d2) {\n        return (d1.serialNumber() == d2.serialNumber());\n    }\n\n    inline bool operator!=(const Date& d1, const Date& d2) {\n        return (d1.serialNumber() != d2.serialNumber());\n    }\n\n    inline bool operator<(const Date& d1, const Date& d2) {\n        return (d1.serialNumber() < d2.serialNumber());\n    }\n\n    inline bool operator<=(const Date& d1, const Date& d2) {\n        return (d1.serialNumber() <= d2.serialNumber());\n    }\n\n    inline bool operator>(const Date& d1, const Date& d2) {\n        return (d1.serialNumber() > d2.serialNumber());\n    }\n\n    inline bool operator>=(const Date& d1, const Date& d2) {\n        return (d1.serialNumber() >= d2.serialNumber());\n    }\n#endif\n}\n\n#endif\n", "meta": {"hexsha": "c891f4020360092449980abf1739639fd539c3bd", "size": 13671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/time/date.hpp", "max_stars_repo_name": "yuiwashita/quantlib", "max_stars_repo_head_hexsha": "209b36cd94e70e8b5a297e640a9bc58888c36f22", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-13T22:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-18T12:51:41.000Z", "max_issues_repo_path": "ql/time/date.hpp", "max_issues_repo_name": "yuiwashita/quantlib", "max_issues_repo_head_hexsha": "209b36cd94e70e8b5a297e640a9bc58888c36f22", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/time/date.hpp", "max_forks_repo_name": "yuiwashita/quantlib", "max_forks_repo_head_hexsha": "209b36cd94e70e8b5a297e640a9bc58888c36f22", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-27T19:25:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-27T19:25:30.000Z", "avg_line_length": 31.2123287671, "max_line_length": 79, "alphanum_fraction": 0.5913247019, "num_tokens": 3079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.09807932412953667, "lm_q1q2_score": 0.03419487923460424}}
{"text": "\r\n#ifndef __CPP_META_REPLACE_TYPE_HPP__\r\n#define __CPP_META_REPLACE_TYPE_HPP__\r\n\r\n#include <boost/type_traits.hpp>\r\n\r\n/**\r\n * Write a ternary meta-function replace_type<c,x,y> that takes an arbitrary\r\n * compound type c as its first parameter, and replaces all occurrences of a\r\n * type x within c with y:\r\n *\r\n * typedef replace_type<void*, void, int>::type t1; // int*\r\n * typedef replace_type<\r\n *   int const*[10]\r\n *   , int const\r\n *   , long\r\n *   >::type t2; // long* [10]\r\n * typedef replace_type<\r\n *   char& (*)(char&)\r\n *   , char&\r\n *   , long&\r\n *   >::type t3; // long& (*)(long&)\r\n */\r\n\r\nnamespace detail {\r\n\r\ntemplate <\r\n    typename T,\r\n    size_t N,\r\n    typename = typename boost::enable_if_c<\r\n        !boost::is_abstract<T>::value &&\r\n        !boost::is_reference<T>::value &&\r\n        !boost::is_function<T>::value &&\r\n        !boost::is_void<T>::value &&\r\n        (N > 0)\r\n    >::type\r\n>\r\nstruct add_extent\r\n{\r\n    using type = T[N];\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type_impl;\r\n\r\ntemplate <typename C, typename Y>\r\nstruct replace_type_impl<C, C, Y>\r\n{\r\n    using type = Y;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<C[N], C, Y>\r\n{\r\n    using type = typename add_extent<Y, N>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const C[N], C, Y>\r\n{\r\n    using type = typename add_extent<typename boost::add_const<Y>::type, N>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<volatile C[N], C, Y>\r\n{\r\n    using type = typename add_extent<typename boost::add_volatile<Y>::type, N>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const volatile C[N], C, Y>\r\n{\r\n    using type = typename add_extent<typename boost::add_cv<Y>::type, N>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const volatile C[N], const C, Y>\r\n{\r\n    using type = typename add_extent<typename boost::add_volatile<Y>::type, N>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const volatile C[N], volatile C, Y>\r\n{\r\n    using type = typename add_extent<typename boost::add_const<Y>::type, N>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<C*[N], C, Y>\r\n{\r\n    using type = typename add_extent<typename boost::add_pointer<Y>::type, N>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const C*[N], C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_pointer<\r\n            typename boost::add_const<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<volatile C*[N], C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_pointer<\r\n            typename boost::add_volatile<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const volatile C*[N], C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_pointer<\r\n            typename boost::add_cv<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const volatile C*[N], const C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_pointer<\r\n            typename boost::add_volatile<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<const volatile C*[N], volatile C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_pointer<\r\n            typename boost::add_const<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<C* const[N], C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_const<\r\n            typename boost::add_pointer<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<C* volatile[N], C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_volatile<\r\n            typename boost::add_pointer<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y, size_t N>\r\nstruct replace_type_impl<C* const volatile[N], C, Y>\r\n{\r\n    using type = typename add_extent<\r\n        typename boost::add_cv<\r\n            typename boost::add_pointer<Y>::type\r\n        >::type,\r\n        N\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename Y>\r\nstruct replace_type_impl<const C, C, Y>\r\n{\r\n    using type = typename boost::add_const<Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y>\r\nstruct replace_type_impl<volatile C, C, Y>\r\n{\r\n    using type = typename boost::add_volatile<Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y>\r\nstruct replace_type_impl<const volatile C, C, Y>\r\n{\r\n    using type = typename boost::add_cv<Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y>\r\nstruct replace_type_impl<const volatile C, const C, Y>\r\n{\r\n    using type = typename boost::add_volatile<Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename Y>\r\nstruct replace_type_impl<const volatile C, volatile C, Y>\r\n{\r\n    using type = typename boost::add_const<Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type\r\n{\r\n    using type = typename replace_type_impl<C, X, Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C*, X, Y>\r\n{\r\n    using type = typename boost::add_pointer<\r\n        typename replace_type_impl<C, X, Y>::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C* const, X, Y>\r\n{\r\n    using type = typename boost::add_const<\r\n        typename boost::add_pointer<\r\n            typename replace_type_impl<C, X, Y>::type\r\n        >::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C* volatile, X, Y>\r\n{\r\n    using type = typename boost::add_volatile<\r\n        typename boost::add_pointer<\r\n            typename replace_type_impl<C, X, Y>::type\r\n        >::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C* const volatile, X, Y>\r\n{\r\n    using type = typename boost::add_cv<\r\n        typename boost::add_pointer<\r\n            typename replace_type_impl<C, X, Y>::type\r\n        >::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C*, X*, Y>\r\n{\r\n    using type = typename replace_type_impl<C, X, Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C* const, X*, Y>\r\n{\r\n    using type = typename boost::add_const<\r\n        typename replace_type_impl<C, X, Y>::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C* volatile, X*, Y>\r\n{\r\n    using type = typename boost::add_volatile<\r\n        typename replace_type_impl<C, X, Y>::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C* const volatile, X*, Y>\r\n{\r\n    using type = typename boost::add_cv<\r\n        typename replace_type_impl<C, X, Y>::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C&, X, Y>\r\n{\r\n    using type = typename boost::add_reference<\r\n        typename replace_type_impl<C, X, Y>::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C&, X&, Y>\r\n{\r\n    using type = typename replace_type_impl<C, X, Y>::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C*&, X, Y>\r\n{\r\n    using type = typename boost::add_reference<\r\n        typename boost::add_pointer<\r\n            typename replace_type_impl<C, X, Y>::type\r\n        >::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C*&, X*, Y>\r\n{\r\n    using type = typename boost::add_reference<\r\n        typename replace_type_impl<C, X, Y>::type\r\n    >::type;\r\n};\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type<C*&, X*&, Y>\r\n{\r\n    using type = typename replace_type_impl<C, X, Y>::type;\r\n};\r\n\r\ntemplate <typename R, typename X, typename Y>\r\nstruct replace_type<R(*)(), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)();\r\n};\r\n\r\ntemplate <typename R, typename A0, typename X, typename Y>\r\nstruct replace_type<R(*)(A0), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(typename replace_type<A0, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename A3, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2, A3), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type,\r\n        typename replace_type<A3, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2, A3, A4), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type,\r\n        typename replace_type<A3, X, Y>::type,\r\n        typename replace_type<A4, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename A3, typename A4,\r\n          typename A5, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2, A3, A4, A5), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type,\r\n        typename replace_type<A3, X, Y>::type,\r\n        typename replace_type<A4, X, Y>::type,\r\n        typename replace_type<A5, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename A3, typename A4,\r\n          typename A5, typename A6, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2, A3, A4, A5, A6), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type,\r\n        typename replace_type<A3, X, Y>::type,\r\n        typename replace_type<A4, X, Y>::type,\r\n        typename replace_type<A5, X, Y>::type,\r\n        typename replace_type<A6, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename A3, typename A4,\r\n          typename A5, typename A6, typename A7, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2, A3, A4, A5, A6, A7), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type,\r\n        typename replace_type<A3, X, Y>::type,\r\n        typename replace_type<A4, X, Y>::type,\r\n        typename replace_type<A5, X, Y>::type,\r\n        typename replace_type<A6, X, Y>::type,\r\n        typename replace_type<A7, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename A3, typename A4,\r\n          typename A5, typename A6, typename A7, typename A8, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2, A3, A4, A5, A6, A7, A8), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type,\r\n        typename replace_type<A3, X, Y>::type,\r\n        typename replace_type<A4, X, Y>::type,\r\n        typename replace_type<A5, X, Y>::type,\r\n        typename replace_type<A6, X, Y>::type,\r\n        typename replace_type<A7, X, Y>::type,\r\n        typename replace_type<A8, X, Y>::type);\r\n};\r\n\r\ntemplate <typename R, typename A0, typename A1, typename A2, typename A3, typename A4,\r\n          typename A5, typename A6, typename A7, typename A8, typename A9, typename X, typename Y>\r\nstruct replace_type<R(*)(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9), X, Y>\r\n{\r\n    using type = typename replace_type<R, X, Y>::type (*)(\r\n        typename replace_type<A0, X, Y>::type,\r\n        typename replace_type<A1, X, Y>::type,\r\n        typename replace_type<A2, X, Y>::type,\r\n        typename replace_type<A3, X, Y>::type,\r\n        typename replace_type<A4, X, Y>::type,\r\n        typename replace_type<A5, X, Y>::type,\r\n        typename replace_type<A6, X, Y>::type,\r\n        typename replace_type<A7, X, Y>::type,\r\n        typename replace_type<A8, X, Y>::type,\r\n        typename replace_type<A9, X, Y>::type);\r\n};\r\n\r\n} // namespace\r\n\r\ntemplate <typename C, typename X, typename Y>\r\nstruct replace_type : public detail::replace_type<C, X, Y> {};\r\n\r\n#endif  // __CPP_META_REPLACE_TYPE_HPP__\r\n", "meta": {"hexsha": "523f328915da61f7ecc12975d961edbcbbd3dd5f", "size": 13679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/chapter_2/replace_type.hpp", "max_stars_repo_name": "matrixjoeq/Cpp-Template-Metaprogramming-Exercises", "max_stars_repo_head_hexsha": "9512c40f6ad9c380b954d18b884dd3effd0c2947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapter_2/replace_type.hpp", "max_issues_repo_name": "matrixjoeq/Cpp-Template-Metaprogramming-Exercises", "max_issues_repo_head_hexsha": "9512c40f6ad9c380b954d18b884dd3effd0c2947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter_2/replace_type.hpp", "max_forks_repo_name": "matrixjoeq/Cpp-Template-Metaprogramming-Exercises", "max_forks_repo_head_hexsha": "9512c40f6ad9c380b954d18b884dd3effd0c2947", "max_forks_repo_licenses": ["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.0637362637, "max_line_length": 111, "alphanum_fraction": 0.6189048907, "num_tokens": 3626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.10230470926115265, "lm_q1q2_score": 0.033522010249559045}}
{"text": "#include \"../include/common.hpp\"\n#include <boost/mpi.hpp>\n#include <cstddef>\n#include <algorithm>\n#include <cmath>\n\nnamespace mpi_pi::common {\n\nDivision::Division(const boost::mpi::communicator &comm, std::size_t total) noexcept {\n  const auto rank = static_cast<std::size_t>(comm.rank());\n  const auto size = static_cast<std::size_t>(comm.size());\n\n  const auto basic_local_count = static_cast<std::size_t>(std::ceil(static_cast<double>(total) / size));\n  this->first = basic_local_count * rank;\n  this->last = std::min(total, basic_local_count * (rank + 1));\n}\n\nstd::size_t Division::count() const noexcept { return this->last - this->first; }\n\n} // namespace mpi_pi::common\n", "meta": {"hexsha": "42e72b3989e468a69c05b6804217336a43f6a0aa", "size": 677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common.cpp", "max_stars_repo_name": "linyinfeng/mpi-pi", "max_stars_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common.cpp", "max_issues_repo_name": "linyinfeng/mpi-pi", "max_issues_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.cpp", "max_forks_repo_name": "linyinfeng/mpi-pi", "max_forks_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2380952381, "max_line_length": 104, "alphanum_fraction": 0.7119645495, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.0736962661457446, "lm_q1q2_score": 0.03340370578505393}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\r\n//\r\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla Public License\r\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\r\n// obtain one at http://mozilla.org/MPL/2.0/.\r\n#include \"boundary_facets.h\"\r\n#include \"face_occurrences.h\"\r\n#include \"list_to_matrix.h\"\r\n#include \"matrix_to_list.h\"\r\n#include \"sort.h\"\r\n#include \"unique_rows.h\"\r\n#include \"accumarray.h\"\r\n#include \"slice_mask.h\"\r\n\r\n#include <Eigen/Core>\r\n\r\n#include <map>\r\n#include <iostream>\r\n\r\ntemplate <\r\n  typename DerivedT, \r\n  typename DerivedF,\r\n  typename DerivedJ,\r\n  typename DerivedK>\r\nIGL_INLINE void igl::boundary_facets(\r\n  const Eigen::MatrixBase<DerivedT>& T,\r\n  Eigen::PlainObjectBase<DerivedF>& F,\r\n  Eigen::PlainObjectBase<DerivedJ>& J,\r\n  Eigen::PlainObjectBase<DerivedK>& K)\r\n{\r\n  const int simplex_size = T.cols();\r\n  // Handle boring base case\r\n  if(T.rows() == 0)\r\n  {\r\n    F.resize(0,simplex_size-1);\r\n    J.resize(0,1);\r\n    K.resize(0,1);\r\n    return;\r\n  }\r\n  // Get a list of all facets\r\n  DerivedF allF(T.rows()*simplex_size,simplex_size-1);\r\n  // Gather faces (e.g., loop over tets)\r\n  for(int i = 0; i< (int)T.rows();i++)\r\n  {\r\n    switch(simplex_size)\r\n    {\r\n      case 4:\r\n        // get face in correct order\r\n        allF(i*simplex_size+0,0) = T(i,1);\r\n        allF(i*simplex_size+0,1) = T(i,3);\r\n        allF(i*simplex_size+0,2) = T(i,2);\r\n        // get face in correct order\r\n        allF(i*simplex_size+1,0) = T(i,0);\r\n        allF(i*simplex_size+1,1) = T(i,2);\r\n        allF(i*simplex_size+1,2) = T(i,3);\r\n        // get face in correct order\r\n        allF(i*simplex_size+2,0) = T(i,0);\r\n        allF(i*simplex_size+2,1) = T(i,3);\r\n        allF(i*simplex_size+2,2) = T(i,1);\r\n        // get face in correct order\r\n        allF(i*simplex_size+3,0) = T(i,0);\r\n        allF(i*simplex_size+3,1) = T(i,1);\r\n        allF(i*simplex_size+3,2) = T(i,2);\r\n        break;\r\n      case 3:\r\n        allF(i*simplex_size+0,0) = T(i,1);\r\n        allF(i*simplex_size+0,1) = T(i,2);\r\n        allF(i*simplex_size+1,0) = T(i,2);\r\n        allF(i*simplex_size+1,1) = T(i,0);\r\n        allF(i*simplex_size+2,0) = T(i,0);\r\n        allF(i*simplex_size+2,1) = T(i,1);\r\n        break;\r\n    }\r\n  }\r\n  DerivedF sortedF;\r\n  igl::sort(allF,2,true,sortedF);\r\n  Eigen::VectorXi m,n;\r\n  {\r\n    DerivedF _1;\r\n    igl::unique_rows(sortedF,_1,m,n);\r\n  }\r\n  Eigen::VectorXi C;\r\n  igl::accumarray(n,1,C);\r\n  const int ones = (C.array()==1).count();\r\n  // Resize output to fit number of non-twos\r\n  F.resize(ones, allF.cols());\r\n  J.resize(F.rows(),1);\r\n  K.resize(F.rows(),1);\r\n  int k = 0;\r\n  for(int c = 0;c< (int)C.size();c++)\r\n  {\r\n    if(C(c) == 1)\r\n    {\r\n      const int i = m(c);\r\n      assert(k<(int)F.rows());\r\n      F.row(k) = allF.row(i);\r\n      J(k) = i/simplex_size;\r\n      K(k) = i%simplex_size;\r\n      k++;\r\n    }\r\n  }\r\n  assert(k==(int)F.rows());\r\n}\r\n\r\ntemplate <typename DerivedT, typename DerivedF>\r\nIGL_INLINE void igl::boundary_facets(\r\n  const Eigen::MatrixBase<DerivedT>& T,\r\n  Eigen::PlainObjectBase<DerivedF>& F)\r\n{\r\n  Eigen::VectorXi J,K;\r\n  return boundary_facets(T,F,J,K);\r\n}\r\n\r\ntemplate <typename DerivedT, typename Ret>\r\nRet igl::boundary_facets(\r\n  const Eigen::MatrixBase<DerivedT>& T)\r\n{\r\n  Ret F;\r\n  igl::boundary_facets(T,F);\r\n  return F;\r\n}\r\n\r\ntemplate <typename IntegerT, typename IntegerF>\r\nIGL_INLINE void igl::boundary_facets(\r\n  const std::vector<std::vector<IntegerT> > & T,\r\n  std::vector<std::vector<IntegerF> > & F)\r\n{\r\n  // Kept for legacy reasons. Could probably just delete.\r\n  using namespace std;\r\n\r\n  if(T.size() == 0)\r\n  {\r\n    F.clear();\r\n    return;\r\n  }\r\n\r\n  int simplex_size = T[0].size();\r\n  // Get a list of all faces\r\n  vector<vector<IntegerF> > allF(\r\n    T.size()*simplex_size,\r\n    vector<IntegerF>(simplex_size-1));\r\n\r\n  // Gather faces, loop over tets\r\n  for(int i = 0; i< (int)T.size();i++)\r\n  {\r\n    assert((int)T[i].size() == simplex_size);\r\n    switch(simplex_size)\r\n    {\r\n      case 4:\r\n        // get face in correct order\r\n        allF[i*simplex_size+0][0] = T[i][1];\r\n        allF[i*simplex_size+0][1] = T[i][3];\r\n        allF[i*simplex_size+0][2] = T[i][2];\r\n        // get face in correct order\r\n        allF[i*simplex_size+1][0] = T[i][0];\r\n        allF[i*simplex_size+1][1] = T[i][2];\r\n        allF[i*simplex_size+1][2] = T[i][3];\r\n        // get face in correct order\r\n        allF[i*simplex_size+2][0] = T[i][0];\r\n        allF[i*simplex_size+2][1] = T[i][3];\r\n        allF[i*simplex_size+2][2] = T[i][1];\r\n        // get face in correct order\r\n        allF[i*simplex_size+3][0] = T[i][0];\r\n        allF[i*simplex_size+3][1] = T[i][1];\r\n        allF[i*simplex_size+3][2] = T[i][2];\r\n        break;\r\n      case 3:\r\n        allF[i*simplex_size+0][0] = T[i][1];\r\n        allF[i*simplex_size+0][1] = T[i][2];\r\n        allF[i*simplex_size+1][0] = T[i][2];\r\n        allF[i*simplex_size+1][1] = T[i][0];\r\n        allF[i*simplex_size+2][0] = T[i][0];\r\n        allF[i*simplex_size+2][1] = T[i][1];\r\n        break;\r\n    }\r\n  }\r\n\r\n  // Counts\r\n  vector<int> C;\r\n  face_occurrences(allF,C);\r\n\r\n  // Q: Why not just count the number of ones?\r\n  // A: because we are including non-manifold edges as boundary edges\r\n  int twos = (int) count(C.begin(),C.end(),2);\r\n  //int ones = (int) count(C.begin(),C.end(),1);\r\n  // Resize output to fit number of ones\r\n  F.resize(allF.size() - twos);\r\n  //F.resize(ones);\r\n  int k = 0;\r\n  for(int i = 0;i< (int)allF.size();i++)\r\n  {\r\n    if(C[i] != 2)\r\n    {\r\n      assert(k<(int)F.size());\r\n      F[k] = allF[i];\r\n      k++;\r\n    }\r\n  }\r\n  assert(k==(int)F.size());\r\n  //if(k != F.size())\r\n  //{\r\n  //  printf(\"%d =? %d\\n\",k,F.size());\r\n  //}\r\n\r\n}\r\n\r\n\r\n#ifdef IGL_STATIC_LIBRARY\r\n// Explicit template instantiation\r\n// generated by autoexplicit.sh\r\ntemplate void igl::boundary_facets<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);\r\n// generated by autoexplicit.sh\r\ntemplate void igl::boundary_facets<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3> >&);\r\n// generated by autoexplicit.sh\r\ntemplate void igl::boundary_facets<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&);\r\ntemplate void igl::boundary_facets<int, int>(std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > const&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&);\r\n//template Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > igl::boundary_facets(Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&);\r\ntemplate Eigen::Matrix<int, -1, -1, 0, -1, -1> igl::boundary_facets<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&);\r\ntemplate void igl::boundary_facets<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 3, 1, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> >&);\r\n#endif\r\n", "meta": {"hexsha": "288ce45bcfabe33560eb00cf3cd42f3c17f0f61d", "size": 7606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/boundary_facets.cpp", "max_stars_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_stars_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "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/boundary_facets.cpp", "max_issues_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_issues_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "max_issues_repo_licenses": ["Apache-2.0"], "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/boundary_facets.cpp", "max_forks_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_forks_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "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.1076233184, "max_line_length": 276, "alphanum_fraction": 0.5758611622, "num_tokens": 2598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.0900929902973281, "lm_q1q2_score": 0.033354712702938674}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <NTL/BasicThreadPool.h>\n\n#include \"recryption.h\"\n#include \"EncryptedArray.h\"\n#include \"EvalMap.h\"\n#include \"powerful.h\"\n#include \"CtPtrs.h\"\n#include \"intraSlot.h\"\n\n\n/************* Some local functions *************/\nstatic void x2iInSlots(ZZX& poly, long i,\n\t\t       vector<ZZX>& xVec, const EncryptedArray& ea);\n\n// Make every entry of vec divisible by p^e by adding/subtracting multiples\n// of p^r and q, while keeping the added multiples small. \ntemplate<class VecInt>\nlong makeDivisible(VecInt& vec, long p2e, long p2r, long q, double alpha);\nstatic inline double pow(long a, long b) {return pow(double(a), double(b));}\n\nRecryptData::~RecryptData()\n{\n  if (alMod!=NULL)     delete alMod;\n  if (ea!=NULL)        delete ea;\n  if (firstMap!=NULL)  delete firstMap;\n  if (secondMap!=NULL) delete secondMap;\n  if (p2dConv!=NULL)   delete p2dConv;\n}\n\n\n/** Computing the recryption parameters\n *\n * To get the smallest possible value of e-e', the params need to satisfy:\n *  (p^e +1)/4 =>\n *       max { (t+1)( 1+ (alpha/2)*(p^e/p^{ceil(log_p(t+2))}) ) + noise      }\n *           { (t+1)( 1+ ((1-alpha)/2)*(p^e/p^{ceil(log_p(t+2))}) +p^r/2) +1 },\n *\n * where noise is taken to be twice the mod-switching additive term, namely\n * noise = p^r *sqrt((t+1)*phi(m)/3). Denoting rho=(t+1)/p^{ceil(log_p(t+2))}\n * (and ignoring fome +1 terms), this is equivalent to:\n *\n *   p^e > max { 4(t+noise)/(1-2*alpha*rho), 2(t+1)p^r/(1-2(1-alpha)rho) }.\n *\n * We first compute the optimal value for alpha (which must be in [0,1]),\n * that makes the two terms in the max{...} as close as possible, and\n * then compute the smallest value of e satisfying this constraint.\n *\n * If this value is too big then we try again with e-e' one larger,\n * which means that rho is a factor of p smaller.\n */\n\n// Some convenience functions\nstatic double lowerBound1(long p, long r, long ePrime, long t,\n\t\t\t  double alpha, double noise)\n{\n  return (t+1)*(1+ alpha*pow(p,r+ePrime-1)/2)+noise;\n}\nstatic double lowerBound2(long p, long r, long ePrime, long t, double alpha)\n{\n  return (t+1)*(1+ (1-alpha)*pow(p,r+ePrime-1)/2 + pow(p,r)/2)+1;\n}\n\nstatic void setAlphaE(double& alpha, long& e, double rho, double gamma,\n\t\t      double noise, double logp, long p2r, long t)\n{\n  alpha = (1 +gamma*(2*rho-1))/(2*rho*(1+gamma));\n  if (alpha<0) alpha=0;\n  else if (alpha>1) alpha=1;\n\n  if (alpha<1) {\n    double ratio = 4*(t+noise)/(1-2*alpha*rho);\n    e = floor(1+ log(ratio)/logp);\n  }\n  else\n    e = floor(1+ log(2*(t+1)*p2r)/logp);\n}\n\nbool RecryptData::operator==(const RecryptData& other) const\n{\n  if (mvec != other.mvec) return false;\n  if (hwt != other.hwt) return false;\n  if (conservative != other.conservative) return false;\n\n  return true;\n}\n\n\n\n// The main method\nvoid RecryptData::init(const FHEcontext& context, const Vec<long>& mvec_,\n\t\t       long t, bool consFlag, bool build_cache_, bool minimal)\n{\n  if (alMod != NULL) { // were we called for a second time?\n    cerr << \"@Warning: multiple calls to RecryptData::init\\n\";\n    return;\n  }\n  assert(computeProd(mvec_) == (long)context.zMStar.getM()); // sanity check\n\n  // Record the arguments to this function\n  mvec = mvec_;\n  conservative = consFlag;\n  build_cache = build_cache_;\n\n  if (t <= 0) t = defSkHwt+1; // recryption key Hwt\n  hwt = t;\n  long p = context.zMStar.getP();\n  long phim = context.zMStar.getPhiM();\n  long r = context.alMod.getR();\n  long p2r = context.alMod.getPPowR();\n  double logp = log((double)p);\n\n  double noise = p2r * sqrt((t+1)*phim/3.0);\n  double gamma = 2*(t+noise)/((t+1)*p2r); // ratio between numerators\n\n  long logT = ceil(log((double)(t+2))/logp); // ceil(log_p(t+2))\n  double rho = (t+1)/pow(p,logT);\n\n  if (!conservative) {   // try alpha, e with this \"aggresive\" setting\n    setAlphaE(alpha, e, rho, gamma, noise, logp, p2r, t);\n    ePrime = e -r +1 -logT;\n\n    // If e is too large, try again with rho/p instead of rho\n    long bound = (1L << (context.bitsPerLevel-1)); // halfSizePrime/2\n    if (pow(p,e) > bound) { // try the conservative setting instead\n      cerr << \"* p^e=\"<<pow(p,e)<<\" is too big (bound=\"<<bound<<\")\\n\";\n      conservative = true;\n    }\n  }\n  if (conservative) { // set alpha, e with a \"conservative\" rho/p\n    setAlphaE(alpha, e, rho/p, gamma, noise, logp, p2r, t);\n    ePrime = e -r -logT;\n  }\n\n  // Compute highest key-Hamming-weight that still works (not more than 256)\n  double qOver4 = (pow(p,e)+1)/4;\n  for (t-=10; qOver4>=lowerBound2(p,r,ePrime,t,alpha)\n\t &&  qOver4>=lowerBound1(p,r,ePrime,t,alpha,noise) && t<257; t++);\n  skHwt = t-1;\n\n  // First part of Bootstrapping works wrt plaintext space p^{r'}\n  alMod = new PAlgebraMod(context.zMStar, e-ePrime+r);\n  ea = new EncryptedArray(context, *alMod);\n         // Polynomial defaults to F0, PAlgebraMod explicitly given\n\n\n  p2dConv = new PowerfulDCRT(context, mvec);\n\n  // Initialize the linear polynomial for unpacking the slots\n  zz_pBak bak; bak.save(); ea->getAlMod().restoreContext();\n  long nslots = ea->size();\n  long d = ea->getDegree();\n\n  const Mat<zz_p>& CBi=ea->getDerived(PA_zz_p()).getNormalBasisMatrixInverse();\n\n  vector<ZZX> LM;\n  LM.resize(d);\n  for (long i = 0; i < d; i++) // prepare the linear polynomial\n    LM[i] = rep(CBi[i][0]);\n\n  vector<ZZX> C; \n  ea->buildLinPolyCoeffs(C, LM); // \"build\" the linear polynomial\n\n  unpackSlotEncoding.resize(d);  // encode the coefficients\n\n  for (long j = 0; j < d; j++) {\n    vector<ZZX> v(nslots);\n    for (long k = 0; k < nslots; k++) v[k] = C[j];\n    ea->encode(unpackSlotEncoding[j], v);\n  }\n  firstMap = new EvalMap(*ea, minimal, mvec, true, build_cache);\n  secondMap = new EvalMap(*context.ea, minimal, mvec, false, build_cache);\n}\n\n/********************************************************************/\n/********************************************************************/\n\n#ifdef DEBUG_PRINTOUT\n#include \"debugging.h\"\nlong printFlag = FLAG_PRINT_VEC;\n#endif\n\n// Extract digits from fully packed slots\nvoid extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime,\n\t\t\t const vector<ZZX>& unpackSlotEncoding);\n \n// bootstrap a ciphertext to reduce noise\nvoid FHEPubKey::reCrypt(Ctxt &ctxt)\n{\n  FHE_TIMER_START;\n\n  // Some sanity checks for dummy ciphertext\n  long ptxtSpace = ctxt.getPtxtSpace();\n  if (ctxt.isEmpty()) return;\n  if (ctxt.parts.size()==1 && ctxt.parts[0].skHandle.isOne()) {\n    // Dummy encryption, just ensure that it is reduced mod p\n    ZZX poly = to_ZZX(ctxt.parts[0]);\n    for (long i=0; i<poly.rep.length(); i++)\n      poly[i] = to_ZZ( rem(poly[i],ptxtSpace) );\n    poly.normalize();\n    ctxt.DummyEncrypt(poly);\n    return;\n  }\n\n  assert(recryptKeyID>=0); // check that we have bootstrapping data\n\n  long p = getContext().zMStar.getP();\n  long r = getContext().alMod.getR();\n  long p2r = getContext().alMod.getPPowR();\n\n  // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}.\n  long e = getContext().rcData.e;\n  long ePrime = getContext().rcData.ePrime;\n  long p2ePrime = power_long(p,ePrime);\n  long q = power_long(p,e)+1;\n  assert(e>=r);\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"reCrypt: p=\"<<p<<\", r=\"<<r<<\", e=\"<<e<<\" ePrime=\"<<ePrime\n       << \", q=\"<<q<<endl;\n#endif\n\n  // can only bootstrap ciphertext with plaintext-space dividing p^r\n  assert(p2r % ptxtSpace == 0);\n\n  FHE_NTIMER_START(preProcess);\n\n  // Make sure that this ciphertxt is in canonical form\n  if (!ctxt.inCanonicalForm()) ctxt.reLinearize();\n\n  // Mod-switch down if needed\n  IndexSet s = ctxt.getPrimeSet() / getContext().specialPrimes; // set minus\n  if (s.card()>2) { // leave only bottom two primes\n    long frst = s.first();\n    long scnd = s.next(frst);\n    IndexSet s2(frst,scnd);\n    s.retain(s2); // retain only first two primes\n  }\n  ctxt.modDownToSet(s);\n\n  // key-switch to the bootstrapping key\n  ctxt.reLinearize(recryptKeyID);\n\n  // \"raw mod-switch\" to the bootstrapping mosulus q=p^e+1.\n  vector<ZZX> zzParts; // the mod-switched parts, in ZZX format\n  double noise = ctxt.rawModSwitch(zzParts, q);\n  noise = sqrt(noise);\n\n  // Add multiples of p2r and q to make the zzParts divisible by p^{e'}\n  long maxU=0;\n  for (long i=0; i<(long)zzParts.size(); i++) {\n    // make divisible by p^{e'}\n    long newMax = makeDivisible(zzParts[i].rep, p2ePrime, p2r, q,\n\t\t\t\tgetContext().rcData.alpha);\n    zzParts[i].normalize();   // normalize after working directly on the rep\n    if (maxU < newMax)  maxU = newMax;\n  }\n\n  // Check that the estimated noise is still low\n  if (noise + maxU*p2r*(skHwts[recryptKeyID]+1) > q/2) \n    cerr << \" * noise/q after makeDivisible = \"\n\t << ((noise + maxU*p2r*(skHwts[recryptKeyID]+1))/q) << endl;\n\n  for (long i=0; i<(long)zzParts.size(); i++)\n    zzParts[i] /= p2ePrime;   // divide by p^{e'}\n\n  // Multiply the post-processed cipehrtext by the encrypted sKey\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ Before recryption \";\n  decryptAndPrint(cerr, recryptEkey, *dbgKey, *dbgEa, printFlag);\n#endif\n\n  double p0size = to_double(coeffsL2Norm(zzParts[0]));\n  double p1size = to_double(coeffsL2Norm(zzParts[1]));\n  ctxt = recryptEkey;\n  ctxt.multByConstant(zzParts[1], p1size*p1size);\n  ctxt.addConstant(zzParts[0], p0size*p0size);\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ Before linearTrans1 \";\n  decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag);\n#endif\n  FHE_NTIMER_STOP(preProcess);\n\n  // Move the powerful-basis coefficients to the plaintext slots\n  FHE_NTIMER_START(LinearTransform1);\n  ctxt.getContext().rcData.firstMap->apply(ctxt);\n  FHE_NTIMER_STOP(LinearTransform1);\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ After linearTrans1 \";\n  decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag);\n#endif\n\n  // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots)\n  extractDigitsPacked(ctxt, e-ePrime, r, ePrime,\n\t\t      context.rcData.unpackSlotEncoding);\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ Before linearTrans2 \";\n  decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag);\n#endif\n\n  // Move the slots back to powerful-basis coefficients\n  FHE_NTIMER_START(LinearTransform2);\n  ctxt.getContext().rcData.secondMap->apply(ctxt);\n  FHE_NTIMER_STOP(LinearTransform2);\n}\n\n/*********************************************************************/\n/*********************************************************************/\n\n// Return in poly a polynomial with X^i encoded in all the slots\nstatic void x2iInSlots(ZZX& poly, long i,\n\t\t       vector<ZZX>& xVec, const EncryptedArray& ea)\n{\n  xVec.resize(ea.size());\n  ZZX x2i = ZZX(i,1);\n  for (long j=0; j<(long)xVec.size(); j++) xVec[j] = x2i;\n  ea.encode(poly, xVec);\n}\n\n// Make every entry of vec divisible by p^e by adding/subtracting multiples\n// of p^r and q, while keeping the added multiples small. Specifically, for\n// e>=2, an integer z can be made divisible by p^e via\n//   z' = z + u * p^r + v*p^r * q,\n// with\n//   |u|<=ceil(alpha p^{r(e-1)}/2) and |v|<=0.5+floor(beta p^{r(e-1)}/2),\n// for any alpha+beta=1. We assume that r<e and that q-1 is divisible by p^e.\n// Returns the largest absolute values of the u's and the new entries.\n//\n// This code is more general than we need, for bootstrapping we will always\n// have e>r.\ntemplate<class VecInt>\nlong makeDivisible(VecInt& vec, long p2e, long p2r, long q, double alpha)\n{\n  assert(((p2e % p2r == 0) && (q % p2e == 1)) ||\n\t ((p2r % p2e == 0) && (q % p2r == 1)));\n\n  long maxU =0;\n  ZZ maxZ;\n  for (long i=0; i<vec.length(); i++) {\n    ZZ z, z2; conv(z, vec[i]);\n    long u=0, v=0;\n\n    long zMod1=0, zMod2=0;\n    if (p2r < p2e && alpha>0) {\n      zMod1 = rem(z,p2r);\n      if (zMod1 > p2r/2) zMod1 -= p2r; // map to the symmetric interval\n\n      // make z divisible by p^r by adding a multiple of q\n      z2 = z - to_ZZ(zMod1)*q;\n      zMod2 = rem(z2,p2e); // z mod p^e, still divisible by p^r\n      if (zMod2 > p2e/2) zMod2 -= p2e; // map to the symmetric interval\n      zMod2 /= -p2r; // now z+ p^r*zMod2=0 (mod p^e) and |zMod2|<=p^{r(e-1)}/2\n\n      u = ceil(alpha * zMod2);\n      v = zMod2 - u; // = floor((1-alpha) * zMod2)\n      z = z2 + u*p2r + to_ZZ(q)*v*p2r;\n    }\n    else { // r >= e or alpha==0, use only mulitples of q\n      zMod1 = rem(z,p2e);\n      if (zMod1 > p2e/2) zMod1 -= p2e; // map to the symmetric interval\n      z -= to_ZZ(zMod1) * q;\n    }\n    if (abs(u) > maxU) maxU = abs(u);\n    if (abs(z) > maxZ) maxZ = abs(z);\n\n    if (rem(z,p2e) != 0) { // sanity check\n      cerr << \"**error: original z[\"<<i<<\"]=\" << vec[i]\n\t   << std::dec << \", p^r=\"<<p2r << \", p^e=\"<<p2e << endl;\n      cerr << \"z' = z - \"<<zMod1<<\"*q = \"<< z2<<endl;\n      cerr << \"z''=z' +\" <<u<<\"*p^r +\"<<v<<\"*p^r*q = \"<<z<<endl;\n      exit(1);\n    }\n    conv(vec[i], z); // convert back to native format\n  }\n  return maxU;\n}\n// explicit instantiation for vec_ZZ and vec_long\ntemplate long makeDivisible<vec_ZZ>(vec_ZZ& v, long p2e,\n\t\t\t\t    long p2r, long q, double alpha);\n// template long makeDivisible<vec_long>(vec_long& v, long p2e,\n// \t\t\t\t      long p2r, long q, double alpha);\n\n#ifdef FHE_BOOT_THREADS\n\n// Extract digits from fully packed slots, multithreaded version\nvoid extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime,\n\t\t\t const vector<ZZX>& unpackSlotEncoding)\n{\n  FHE_TIMER_START;\n\n  // Step 1: unpack the slots of ctxt\n  FHE_NTIMER_START(unpack);\n  ctxt.cleanUp();\n\n  // Apply the d automorphisms and store them in scratch area\n  long d = ctxt.getContext().zMStar.getOrdP();\n\n  vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt));\n  { // explicit scope to force all temporaries to be released\n    vector< shared_ptr<DoubleCRT> > coeff_vector;\n    coeff_vector.resize(d);\n\n    FHE_NTIMER_START(unpack1);\n    for (long i = 0; i < d; i++)\n      coeff_vector[i] = shared_ptr<DoubleCRT>(new \n        DoubleCRT(unpackSlotEncoding[i], ctxt.getContext(), ctxt.getPrimeSet()) );\n    FHE_NTIMER_STOP(unpack1);\n\n    FHE_NTIMER_START(unpack2);\n    vector<Ctxt> frob(d, Ctxt(ZeroCtxtLike, ctxt));\n\n    NTL_EXEC_RANGE(d, first, last)\n    // FIXME: implement using hoisting!\n        for (long j = first; j < last; j++) { // process jth Frobenius \n          frob[j] = ctxt;\n          frob[j].frobeniusAutomorph(j);\n          frob[j].cleanUp();\n          // FIXME: not clear if we should call cleanUp here\n        }\n    NTL_EXEC_RANGE_END\n\n    FHE_NTIMER_STOP(unpack2);\n\n    FHE_NTIMER_START(unpack3);\n    Ctxt tmp1(ZeroCtxtLike, ctxt);\n    for (long i = 0; i < d; i++) {\n      for (long j = 0; j < d; j++) {\n        tmp1 = frob[j];\n        tmp1.multByConstant(*coeff_vector[mcMod(i+j, d)]);\n        unpacked[i] += tmp1;\n      }\n    }\n    FHE_NTIMER_STOP(unpack3);\n  }\n  FHE_NTIMER_STOP(unpack);\n\n  // Step 2: extract the digits top-1,...,0 from the slots of unpacked[i]\n  long p = ctxt.getContext().zMStar.getP();\n  long p2r = power_long(p,r);\n  long topHigh = botHigh + r-1;\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ After unpack \";\n  decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag);\n  cerr << \"    extracting \"<<(topHigh+1)<<\" digits\\n\";\n#endif\n\n  if (p==2 && r>2)\n    topHigh--; // For p==2 we sometime get a bit for free\n\n  FHE_NTIMER_START(extractDigits);\n\n  NTL_EXEC_RANGE(d, first, last)\n      for (long i = first; i < last; i++) {\n        vector<Ctxt> scratch;\n    \n        if (topHigh<=0) { // extracting LSB = no-op\n          scratch.assign(1,unpacked[i]);\n        } else {          // extract digits topHigh...0, store them in scratch\n          extractDigits(scratch, unpacked[i], topHigh+1);\n        }\n\n        // set upacked[i] = -\\sum_{j=botHigh}^{topHigh} scratch[j] * p^{j-botHigh}\n        if (topHigh >= (long)scratch.size()) {\n          topHigh = scratch.size() -1;\n          cerr << \" @ suspect: not enough digits in extractDigitsPacked\\n\";\n        }\n    \n        unpacked[i] = scratch[topHigh];\n        for (long j=topHigh-1; j>=botHigh; --j) {\n          unpacked[i].multByP();\n          unpacked[i] += scratch[j];\n        }\n        if (p==2 && botHigh>0) {   // For p==2, subtract also the previous bit\n          //cerr << scratch.size() << \" \" <<  botHigh-1 << \"\\n\";\n          unpacked.at(i) += scratch.at(botHigh-1);\n        }\n        unpacked[i].negate();\n    \n        if (r>ePrime) {          // Add in digits from the bottom part, if any\n          long topLow = r-1 - ePrime;\n          Ctxt tmp = scratch[topLow];\n          for (long j=topLow-1; j>=0; --j) {\n    \ttmp.multByP();\n    \ttmp += scratch[j];\n          }\n          if (ePrime>0)\n    \ttmp.multByP(ePrime); // multiply by p^e'\n          unpacked[i] += tmp;\n        }\n        unpacked[i].reducePtxtSpace(p2r); // Our plaintext space is now mod p^r\n      }\n  NTL_EXEC_RANGE_END\n\n  FHE_NTIMER_STOP(extractDigits);\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ Before repack \";\n  decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag);\n#endif\n\n  // Step 3: re-pack the slots\n  FHE_NTIMER_START(repack);\n  const EncryptedArray& ea2 = *ctxt.getContext().ea;\n  ZZX xInSlots;\n  vector<ZZX> xVec(ea2.size());\n  ctxt = unpacked[0];\n  for (long i=1; i<d; i++) {\n    x2iInSlots(xInSlots, i, xVec, ea2);\n    unpacked[i].multByConstant(xInSlots);\n    ctxt += unpacked[i];\n  }\n  FHE_NTIMER_STOP(repack);\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ After repack \";\n  decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag);\n#endif\n}\n\n\n#else\n\n// Extract digits from fully packed slots\nvoid extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime,\n\t\t\t const vector<ZZX>& unpackSlotEncoding)\n{\n  FHE_TIMER_START;\n\n  // Step 1: unpack the slots of ctxt\n  FHE_NTIMER_START(unpack);\n  ctxt.cleanUp();\n\n  // Apply the d automorphisms and store them in scratch area\n  long d = ctxt.getContext().zMStar.getOrdP();\n\n  vector<Ctxt> scratch; // used below \n  vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt));\n  { // explicit scope to force all temporaries to be released\n    vector< shared_ptr<DoubleCRT> > coeff_vector;\n    coeff_vector.resize(d);\n    for (long i = 0; i < d; i++)\n      coeff_vector[i] = shared_ptr<DoubleCRT>(new \n        DoubleCRT(unpackSlotEncoding[i], ctxt.getContext(), ctxt.getPrimeSet()) );\n    Ctxt tmp1(ZeroCtxtLike, ctxt);\n    Ctxt tmp2(ZeroCtxtLike, ctxt);\n\n    // FIXME: implement using hoisting!\n    for (long j = 0; j < d; j++) { // process jth Frobenius \n      tmp1 = ctxt;\n      tmp1.frobeniusAutomorph(j);\n      tmp1.cleanUp();\n      // FIXME: not clear if we should call cleanUp here\n\n      for (long i = 0; i < d; i++) {\n        tmp2 = tmp1;\n        tmp2.multByConstant(*coeff_vector[mcMod(i+j, d)]);\n        unpacked[i] += tmp2;\n      }\n    }\n  }\n  FHE_NTIMER_STOP(unpack);\n\n  // Step 2: extract the digits top-1,...,0 from the slots of unpacked[i]\n  long p = ctxt.getContext().zMStar.getP();\n  long p2r = power_long(p,r);\n  long topHigh = botHigh + r-1;\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ After unpack \";\n  decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag);\n  cerr << \"    extracting \"<<(topHigh+1)<<\" digits\\n\";\n#endif\n\n  if (p==2 && r>2)\n    topHigh--; // For p==2 we sometime get a bit for free\n\n  FHE_NTIMER_START(extractDigits);\n  for (long i=0; i<(long)unpacked.size(); i++) {\n    if (topHigh<=0) { // extracting LSB = no-op\n      scratch.assign(1,unpacked[i]);\n    } else {          // extract digits topHigh...0, store them in scratch\n      extractDigits(scratch, unpacked[i], topHigh+1);\n    }\n\n    // set upacked[i] = -\\sum_{j=botHigh}^{topHigh} scratch[j] * p^{j-botHigh}\n    if (topHigh >= (long)scratch.size()) {\n      topHigh = scratch.size() -1;\n      cerr << \" @ suspect: not enough digits in extractDigitsPacked\\n\";\n    }\n\n    unpacked[i] = scratch[topHigh];\n    for (long j=topHigh-1; j>=botHigh; --j) {\n      unpacked[i].multByP();\n      unpacked[i] += scratch[j];\n    }\n    if (p==2 && botHigh>0)   // For p==2, subtract also the previous bit\n      unpacked[i] += scratch[botHigh-1];\n    unpacked[i].negate();\n\n    if (r>ePrime) {          // Add in digits from the bottom part, if any\n      long topLow = r-1 - ePrime;\n      Ctxt tmp = scratch[topLow];\n      for (long j=topLow-1; j>=0; --j) {\n\ttmp.multByP();\n\ttmp += scratch[j];\n      }\n      if (ePrime>0)\n\ttmp.multByP(ePrime); // multiply by p^e'\n      unpacked[i] += tmp;\n    }\n    unpacked[i].reducePtxtSpace(p2r); // Our plaintext space is now mod p^r\n  }\n  FHE_NTIMER_STOP(extractDigits);\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"+ Before repack \";\n  decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag);\n#endif\n\n  // Step 3: re-pack the slots\n  FHE_NTIMER_START(repack);\n  const EncryptedArray& ea2 = *ctxt.getContext().ea;\n  ZZX xInSlots;\n  vector<ZZX> xVec(ea2.size());\n  ctxt = unpacked[0];\n  for (long i=1; i<d; i++) {\n    x2iInSlots(xInSlots, i, xVec, ea2);\n    unpacked[i].multByConstant(xInSlots);\n    ctxt += unpacked[i];\n  }\n  FHE_NTIMER_STOP(repack);\n}\n\n#endif\n\n\n// Use packed bootstrapping, so we can bootstrap all in just one go.\nvoid packedRecrypt(const CtPtrs& cPtrs,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea)\n{\n  FHEPubKey& pKey = (FHEPubKey&)cPtrs[0]->getPubKey();\n\n  // Allocate temporary ciphertexts for the recryption\n  int nPacked = divc(cPtrs.size(), ea.getDegree()); // ceil(totoalNum/d)\n  std::vector<Ctxt> cts(nPacked, Ctxt(pKey));\n\n  repack(CtPtrs_vectorCt(cts), cPtrs, ea);  // pack ciphertexts\n  //  cout << \"@\"<< lsize(cts)<<std::flush;\n  for (Ctxt& c: cts) {     // then recrypt them\n    c.reducePtxtSpace(2);  // we only have recryption data for binary ctxt\n#ifdef DEBUG_PRINTOUT\n    ZZX ptxt;\n    decryptAndPrint((cout<<\"  before recryption \"), c, *dbgKey, *dbgEa);\n    dbgKey->Decrypt(ptxt, c);\n    c.DummyEncrypt(ptxt);\n    decryptAndPrint((cout<<\"  after recryption \"), c, *dbgKey, *dbgEa);\n#else\n    pKey.reCrypt(c);\n#endif\n  }\n  unpack(cPtrs, CtPtrs_vectorCt(cts), ea, unpackConsts);\n}\n\n// recrypt all ctxt at level < belowLvl\nvoid packedRecrypt(const CtPtrs& array,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea, long belowLvl)\n{\n  std::vector<Ctxt*> v;\n  for (long i=0; i<array.size(); i++)\n    if ( array.isSet(i) && !array[i]->isEmpty()\n         && array[i]->findBaseLevel()<belowLvl )\n      v.push_back(array[i]);\n  packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea);\n}\nvoid packedRecrypt(const CtPtrMat& m,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea, long belowLvl)\n{\n  std::vector<Ctxt*> v;\n  for (long i=0; i<m.size(); i++)\n    for (long j=0; j<m[i].size(); j++)\n      if ( m[i].isSet(j) && !m[i][j]->isEmpty()\n           && m[i][j]->findBaseLevel()<belowLvl )\n        v.push_back(m[i][j]);\n  packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea);\n}\n", "meta": {"hexsha": "075a964186442363deb88181a38a3ef0eb028097", "size": 23095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/recryption.cpp", "max_stars_repo_name": "msatyan/HElib", "max_stars_repo_head_hexsha": "0553a60f809c13859f64935ec24c14447e8c9159", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-22T00:27:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T21:22:58.000Z", "max_issues_repo_path": "src/recryption.cpp", "max_issues_repo_name": "msatyan/HElib", "max_issues_repo_head_hexsha": "0553a60f809c13859f64935ec24c14447e8c9159", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T21:41:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-18T21:37:26.000Z", "max_forks_repo_path": "src/recryption.cpp", "max_forks_repo_name": "msatyan/HElib", "max_forks_repo_head_hexsha": "0553a60f809c13859f64935ec24c14447e8c9159", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-03T15:41:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-03T15:41:14.000Z", "avg_line_length": 32.8988603989, "max_line_length": 82, "alphanum_fraction": 0.6233816843, "num_tokens": 7186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.06754669630158147, "lm_q1q2_score": 0.033245682526774144}}
{"text": "/**\n * \\file boost/numeric/ublasx/matrix_diagonal.hpp\n *\n * \\brief Diagonal view of a matrix.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2009, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_PROXY_MATRIX_DIAGONAL_HPP\n#define BOOST_NUMERIC_UBLASX_PROXY_MATRIX_DIAGONAL_HPP\n\n#include <algorithm>\n#include <boost/mpl/if.hpp>\n#include <boost/numeric/ublas/detail/config.hpp>\n#include <boost/numeric/ublas/detail/temporary.hpp>\n#include <boost/numeric/ublas/detail/vector_assign.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n//#include <boost/numeric/ublasx/traits/array_type.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_const.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n/**\n * \\brief Matrix based diagonal vector class\n * \\tparam MatrixT A model of MatrixExpression.\n *\n * This class provides a view of a specific diagonal of a matrix of type\n * \\a MatrixT.\n * The diagonal of the matrix is chosen during construction through the\n * parameter \\c k passed to the constructor.\n * The parameter \\c k has the following meaning:\n * - \\c k = 0, the main diagonal is extracted;\n * - \\c k > 0, the \\c k-th diagonal above the main diagonal is extracted;\n * - \\c k < 0, the \\c k-th diagonal under the main diagonal is extracted;\n * .\n * Model of VectorExpression.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixT>\nclass matrix_diagonal: public vector_expression< matrix_diagonal<MatrixT> >\n{\n\tpublic: class const_iterator;\n\tpublic: class iterator;\n\n\n\tprivate: typedef matrix_diagonal<MatrixT> self_type;\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n\tpublic: using vector_expression<self_type>::operator();\n#endif // BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n\tpublic: typedef MatrixT matrix_type;\n\tpublic: typedef typename matrix_traits<MatrixT>::size_type size_type;\n\tpublic: typedef typename matrix_traits<MatrixT>::difference_type difference_type;\n\tpublic: typedef typename matrix_traits<MatrixT>::value_type value_type;\n//\tpublic: typedef typename array_type<MatrixT>::type array_type; // FIXME: not in matrix_traits\n\tpublic: typedef typename matrix_traits<MatrixT>::const_reference const_reference;\n\tpublic: typedef typename ::boost::mpl::if_<\n\t\t\t\t\t\t\t\t\t::boost::is_const<MatrixT>,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::const_reference,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::reference\n\t\t\t\t\t\t\t>::type reference;\n\tpublic: typedef typename ::boost::mpl::if_<\n\t\t\t\t\t\t\t\t\t::boost::is_const<MatrixT>,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::const_closure_type,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::closure_type\n\t\t\t\t\t\t\t>::type matrix_closure_type;\n\tpublic: typedef const self_type const_closure_type;\n\tpublic: typedef self_type closure_type;\n\tpublic: typedef typename storage_restrict_traits<\n\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::storage_category,\n\t\t\t\t\t\t\t\tdense_proxy_tag\n\t\t\t\t\t\t\t>::storage_category storage_category;\n\t// Iterator types\n\tprivate: typedef typename matrix_traits<MatrixT>::const_iterator1 const_subiterator1_type;\n\tprivate: typedef typename matrix_traits<MatrixT>::const_iterator2 const_subiterator2_type;\n\tprivate: typedef typename ::boost::mpl::if_<\n\t\t\t\t\t\t\t\t\t::boost::is_const<MatrixT>,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::const_iterator1,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::iterator1\n\t\t\t\t\t\t\t>::type subiterator1_type;\n\tprivate: typedef typename ::boost::mpl::if_<\n\t\t\t\t\t\t\t\t\t::boost::is_const<MatrixT>,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::const_iterator2,\n\t\t\t\t\t\t\t\t\ttypename matrix_traits<MatrixT>::iterator2\n\t\t\t\t\t\t\t>::type subiterator2_type;\n\t// Reverse iterator\n\tpublic: typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n\tpublic: typedef reverse_iterator_base<iterator> reverse_iterator;\n\n\n\t//@{ Construction and destruction\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tmatrix_diagonal(matrix_type& data, difference_type k)\n\t\t\t: data_(data),\n\t\t\t  k_(k),\n\t\t\t  r_(k < 0 ? -k : 0),\n\t\t\t  c_(k > 0 ?  k : 0)\n\t{\n\t\t// Early checking of preconditions here.\n\t\t// BOOST_UBLAS_CHECK(r_ < data_.size1() && c_ < data_.size2(), bad_index());\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tmatrix_diagonal(matrix_closure_type const& data, difference_type k, int)\n\t\t\t: data_(data),\n\t\t\t  k_(k),\n\t\t\t  r_(k < 0 ? -k : 0),\n\t\t\t  c_(k > 0 ?  k : 0)\n\t{\n\t\t// Early checking of preconditions here.\n\t\t// BOOST_UBLAS_CHECK(r_ < data_.size1() && c_ < data_.size2(), bad_index());\n\t}\n\n\n//\tpublic: template <typename ExprT>\n//\t\tBOOST_UBLAS_INLINE\n//\t\tmatrix_diagonal(matrix_expression<ExprT>& me, difference_type k)\n//\t\t\t: data_(me()),\n//\t\t\t  k_(k),\n//\t\t\t  r_(k < 0 ? -k : 0),\n//\t\t\t  c_(k > 0 ?  k : 0)\n//\t{\n//\t\t// Early checking of preconditions here.\n//\t\t// BOOST_UBLAS_CHECK(r_ < data_.size1() && c_ < data_.size2(), bad_index());\n//\t}\n\n\t//@} Construction and destruction\n\n\t//@{ Accessors\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tsize_type size() const\n\t{\n\t\tif (k_ > 0)\n\t\t{\n\t\t\treturn ::std::min(data_.size1(), data_.size2() - c_);\n\t\t}\n\t\treturn ::std::min(data_.size1() - r_, data_.size2());\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tdifference_type offset() const\n\t{\n\t\treturn k_;\n\t}\n\n\t//@} Accessors\n\n\t//@{ Storage accessors\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tmatrix_closure_type const& data() const\n\t{\n\t\treturn data_;\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tmatrix_closure_type& data()\n\t{\n\t\treturn data_;\n\t}\n\n\t//@} Storage accessors\n\n\t//@{ Element access\n\n#ifndef BOOST_UBLASX_PROXY_CONST_MEMBER\n\tpublic: BOOST_UBLAS_INLINE\n\t\tconst_reference operator()(size_type j) const\n\t{\n\t\treturn data_(j+r_, j+c_);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\treference operator()(size_type j)\n\t{\n\t\treturn data_(j+r_, j+c_);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tconst_reference operator[](size_type j) const\n\t{\n\t\treturn (*this)(j);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\treference operator[](size_type j)\n\t{\n\t\treturn (*this)(j);\n\t}\n#else\n\tpublic: BOOST_UBLAS_INLINE\n\t\treference operator()(size_type j) const\n\t{\n\t\treturn data_(j+r_, j+c_);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\treference operator[](size_type j) const\n\t{\n\t\treturn (*this)(j);\n\t}\n#endif // BOOST_UBLASX_PROXY_CONST_MEMBER\n\n\t//@} Element access\n\n\t//@{ Assignment\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tmatrix_diagonal& operator=(matrix_diagonal const& md)\n\t{\n\t\t// ISSUE need a temporary, proxy can be overlaping alias\n\t\tvector_assign<scalar_assign>(\n\t\t\t*this,\n\t\t\ttypename vector_temporary_traits<matrix_type>::type(md)\n\t\t);\n\t\treturn *this;\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tmatrix_diagonal& assign_temporary(matrix_diagonal& md)\n\t{\n\t\t// assign elements, proxied container remains the same\n\t\tvector_assign<scalar_assign>(*this, md);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AE>\n\t\tBOOST_UBLAS_INLINE\n\t\tmatrix_diagonal& operator=(vector_expression<AE> const& ae)\n\t{\n\t\tvector_assign<scalar_assign>(\n\t\t\t*this,\n\t\t\ttypename vector_temporary_traits<matrix_type>::type(ae)\n\t\t);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AE>\n\tBOOST_UBLAS_INLINE\n\tmatrix_diagonal& assign(vector_expression<AE> const& ae)\n\t{\n\t\tvector_assign<scalar_assign>(*this, ae);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AE>\n\t\tBOOST_UBLAS_INLINE\n\t\tmatrix_diagonal& operator+=(vector_expression<AE> const& ae)\n\t{\n\t\tvector_assign<scalar_assign>(\n\t\t\t*this,\n\t\t\ttypename vector_temporary_traits<matrix_type>::type(*this + ae)\n\t\t);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AE>\n\t\tBOOST_UBLAS_INLINE\n\t\tmatrix_diagonal& plus_assign(vector_expression<AE> const& ae)\n\t{\n\t\tvector_assign<scalar_plus_assign>(*this, ae);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AE>\n\t\tBOOST_UBLAS_INLINE\n\t\tmatrix_diagonal& operator-=(vector_expression<AE> const& ae)\n\t{\n\t\tvector_assign<scalar_assign>(\n\t\t\t*this,\n\t\t\ttypename vector_temporary_traits<matrix_type>::type(*this - ae)\n\t\t);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AE>\n\t\tBOOST_UBLAS_INLINE\n\t\tmatrix_diagonal &minus_assign(vector_expression<AE> const& ae)\n\t{\n\t\tvector_assign<scalar_minus_assign>(*this, ae);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AT>\n\t\tBOOST_UBLAS_INLINE\n\t\tmatrix_diagonal &operator*=(AT const& at)\n\t{\n\t\tvector_assign_scalar<scalar_multiplies_assign>(*this, at);\n\t\treturn *this;\n\t}\n\n\n\tpublic: template<class AT>\n\t\tBOOST_UBLAS_INLINE\n\t\tmatrix_diagonal &operator/=(AT const& at)\n\t{\n\t\tvector_assign_scalar<scalar_divides_assign>(*this, at);\n\t\treturn *this;\n\t}\n\n\t//@} Assignment\n\n\t//@{ Closure comparison\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tbool same_closure(matrix_diagonal const& mr) const\n\t{\n\t\treturn this->data_.same_closure(mr.data_);\n\t}\n\n\t//@} Closure comparison\n\n\t//@{ Comparison\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tbool operator==(matrix_diagonal const& mr) const\n\t{\n\t\treturn this->data_ == mr.data_ && offset() == mr.offset();\n\t}\n\n\t//@} Comparison\n\n\t//@{ Swapping\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tvoid swap(matrix_diagonal mr) //FIXME: why not pass-by-reference?\n\t{\n\t\tif (this != &mr)\n\t\t{\n\t\t\tBOOST_UBLAS_CHECK(size() == mr.size(), bad_size());\n\t\t\t// Sparse ranges may be nonconformant now.\n\t\t\t// std::swap_ranges (begin(), end(), mr.begin());\n\t\t\tvector_swap<scalar_swap>(*this, mr);\n\t\t}\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tfriend\n\t\tvoid swap(matrix_diagonal mr1, matrix_diagonal mr2) //FIXME: why not pass-by-reference?\n\t{\n\t\tmr1.swap(mr2);\n\t}\n\n\t//@} Swapping\n\n\t//@{ Iterators\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tconst_iterator find(size_type j) const\n\t{\n\t\tconst_subiterator1_type it1(data_.find1(2, j+r_, c_));\n\t\tconst_subiterator2_type it2(data_.find2(1, r_, j+c_));\n\n\t\treturn const_iterator(*this, it1, it2);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\titerator find(size_type j)\n\t{\n\t\tsubiterator1_type it1(data_.find1(2, j+r_, c_));\n\t\tsubiterator2_type it2(data_.find2(1, r_, j+c_));\n\n\t\treturn iterator(*this, it1, it2);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tconst_iterator begin() const\n\t{\n\t\treturn find(0);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tconst_iterator end() const\n\t{\n\t\treturn find(size());\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\titerator begin()\n\t{\n\t\treturn find(0);\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\titerator end()\n\t{\n\t\treturn find(size());\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tconst_reverse_iterator rbegin() const\n\t{\n\t\treturn const_reverse_iterator(end());\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\tconst_reverse_iterator rend() const\n\t{\n\t\treturn const_reverse_iterator(begin());\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\treverse_iterator rbegin()\n\t{\n\t\treturn reverse_iterator(end());\n\t}\n\n\n\tpublic: BOOST_UBLAS_INLINE\n\t\treverse_iterator rend()\n\t{\n\t\treturn reverse_iterator(begin());\n\t}\n\n\n\tpublic: class const_iterator: \tpublic container_const_reference<matrix_diagonal>,\n\t\t\t\t\t\t\t\t\tpublic iterator_base_traits<typename const_subiterator1_type::iterator_category>::template iterator_base<const_iterator, value_type>::type\n\t{\n\t\tpublic: typedef typename const_subiterator1_type::value_type value_type;\n\t\tpublic: typedef typename const_subiterator1_type::difference_type difference_type;\n\t\tpublic: typedef typename const_subiterator1_type::reference reference;\n\t\tpublic: typedef typename const_subiterator1_type::pointer pointer;\n\n\n\t\t// Iterators cannot be different\n\t\tBOOST_STATIC_ASSERT((\n\t\t\t::boost::is_same<\n\t\t\t\t\ttypename MatrixT::const_iterator1::iterator_category,\n\t\t\t\t\ttypename MatrixT::const_iterator2::iterator_category\n\t\t\t>::value\n\t\t));\n\n\n\t\t// Construction and destruction\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator()\n\t\t\t: container_const_reference<self_type>(),\n\t\t\t  it1_(),\n\t\t\t  it2_()\n\t\t{\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator(self_type const& mr, const_subiterator1_type const& it1, const_subiterator2_type const& it2)\n\t\t\t: container_const_reference<self_type>(mr),\n\t\t\t  it1_(it1),\n\t\t\t  it2_(it2)\n\t\t{\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator(typename self_type::iterator const& it)  // ISSUE self_type:: stops VC8 using std::iterator here\n\t\t\t: container_const_reference<self_type>(it()),\n\t\t\t  it1_(it.it1_),\n\t\t\t  it2_(it.it2_)\n\t\t{\n\t\t}\n\n\n\t\t// Arithmetic\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator& operator++()\n\t\t{\n\t\t\t++it1_;\n\t\t\t++it2_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator& operator--()\n\t\t{\n\t\t\t--it1_;\n\t\t\t--it2_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator& operator+=(difference_type n)\n\t\t{\n\t\t\tit1_ += n;\n\t\t\tit1_ += n;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator& operator-=(difference_type n)\n\t\t{\n\t\t\tit1_ -= n;\n\t\t\tit2_ -= n;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tdifference_type operator-(const_iterator const& it) const\n\t\t{\n\t\t\tBOOST_UBLAS_CHECK((*this)().same_closure (it()), external_logic());\n\t\t\treturn BOOST_UBLAS_SAME(it1_ - it.it1_, it2_ - it.it2_);\n\t\t}\n\n\n\t\t// Dereference\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_reference operator*() const\n\t\t{\n\t\t\treturn (*this)().data_(it1_.index1(), it2_.index2());\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_reference operator[](difference_type n) const\n\t\t{\n\t\t\treturn *(*this + n);\n\t\t}\n\n\n\t\t// Index\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tsize_type index() const\n\t\t{\n\t\t\tif (it1_.index1() > it2_.index2())\n\t\t\t{\n\t\t\t\treturn it2_.index2();\n\t\t\t}\n\n\t\t\treturn it1_.index1();\n\t\t}\n\n\n\t\t// Assignment\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tconst_iterator& operator=(const_iterator const& it)\n\t\t{\n\t\t\tcontainer_const_reference<self_type>::assign(&it());\n\t\t\tit1_ = it.it1_;\n\t\t\tit2_ = it.it2_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\t// Comparison\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tbool operator==(const_iterator const& it) const\n\t\t{\n\t\t\tBOOST_UBLAS_CHECK((*this)().same_closure(it()), external_logic());\n\t\t\treturn it1_ == it.it1_ && it2_ == it.it2_;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tbool operator<(const_iterator const& it) const\n\t\t{\n\t\t\tBOOST_UBLAS_CHECK((*this)().same_closure(it()), external_logic());\n\t\t\treturn it1_ < it.it1_ && it2_ < it.it2_;\n\t\t}\n\n\n\t\tprivate: const_subiterator1_type it1_;\n\t\tprivate: const_subiterator2_type it2_;\n\t};\n\n\n\tpublic: class iterator: \tpublic container_reference<matrix_diagonal>,\n\t\t\t\t\t\t\t\tpublic iterator_base_traits<typename subiterator1_type::iterator_category>::template iterator_base<iterator, value_type>::type\n\t{\n\t\tpublic: typedef typename subiterator1_type::value_type value_type;\n\t\tpublic: typedef typename subiterator1_type::difference_type difference_type;\n\t\tpublic: typedef typename subiterator1_type::reference reference;\n\t\tpublic: typedef typename subiterator1_type::pointer pointer;\n\n\n\t\t// Iterators cannot be different\n\t\tBOOST_STATIC_ASSERT((\n\t\t\t::boost::is_same<\n\t\t\t\t\ttypename MatrixT::iterator1::iterator_category,\n\t\t\t\t\ttypename MatrixT::iterator2::iterator_category\n\t\t\t>::value\n\t\t));\n\n\n\t\t// Construction and destruction\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\titerator ()\n\t\t\t: container_reference<self_type>(),\n\t\t\t  it1_(),\n\t\t\t  it2_()\n\t\t{\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\titerator(self_type& mr, subiterator1_type const& it1, subiterator2_type const& it2)\n\t\t\t: container_reference<self_type>(mr),\n\t\t\t  it1_(it1),\n\t\t\t  it2_(it2)\n\t\t{\n\t\t}\n\n\n\t\t// Arithmetic\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\titerator &operator++()\n\t\t{\n\t\t\t++it1_;\n\t\t\t++it2_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\titerator& operator--()\n\t\t{\n\t\t\t--it1_;\n\t\t\t--it2_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\titerator& operator+=(difference_type n)\n\t\t{\n\t\t\tit1_ += n;\n\t\t\tit2_ += n;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\titerator& operator-=(difference_type n)\n\t\t{\n\t\t\tit1_ -= n;\n\t\t\tit2_ -= n;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tdifference_type operator-(iterator const& it) const\n\t\t{\n\t\t\tBOOST_UBLAS_CHECK((*this)().same_closure(it()), external_logic());\n\t\t\treturn BOOST_UBLAS_SAME(it1_ - it.it1_, it2_ - it.it2_);\n\t\t}\n\n\n\t\t// Dereference\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\treference operator*() const\n\t\t{\n\t\t\treturn (*this)().data_(it1_.index1(), it2_.index2());\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\treference operator[](difference_type n) const\n\t\t{\n\t\t\treturn *(*this + n);\n\t\t}\n\n\n\t\t// Index\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tsize_type index() const\n\t\t{\n\t\t\treturn BOOST_UBLAS_SAME(it1_.index1(),  it2_.index2());\n\t\t}\n\n\n\t\t// Assignment\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\titerator& operator=(iterator const& it)\n\t\t{\n\t\t\tcontainer_reference<self_type>::assign(&it());\n\t\t\tit1_ = it.it1_;\n\t\t\tit2_ = it.it2_;\n\t\t\treturn *this;\n\t\t}\n\n\n\t\t// Comparison\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tbool operator==(iterator const& it) const\n\t\t{\n\t\t\tBOOST_UBLAS_CHECK((*this)().same_closure(it()), external_logic());\n\t\t\treturn it1_ == it.it1_ && it2_ == it.it2_;\n\t\t}\n\n\n\t\tpublic: BOOST_UBLAS_INLINE\n\t\t\tbool operator<(iterator const& it) const\n\t\t{\n\t\t\tBOOST_UBLAS_CHECK((*this)().same_closure(it()), external_logic());\n\t\t\treturn it1_ < it.it1_ && it2_ < it.it2_;\n\t\t}\n\n\n\t\tprivate: subiterator1_type it1_;\n\t\tprivate: subiterator2_type it2_;\n\t\tprivate: friend class const_iterator; // See the const_interator(iterator const&) constructor\n\t};\n\n\t//@} Iterators\n\n\t//@{ Data members\n\n\tprivate: matrix_closure_type data_; ///< The underlying matrix.\n\tprivate: difference_type k_; ///< Offset from the main diagonal.\n\tprivate: size_type r_; ///< Offset from the row of the main diagonal.\n\tprivate: size_type c_; ///< Offset from the column of the main diagonal.\n\n\t//@} Data members\n};\n\n} // Namespace ublasx\n\nnamespace ublas {\n\n// Specialize temporary traits\n\ntemplate <typename MatrixT>\nstruct vector_temporary_traits< ::boost::numeric::ublasx::matrix_diagonal<MatrixT> >: public vector_temporary_traits<MatrixT> {};\n\ntemplate <typename  MatrixT>\nstruct vector_temporary_traits< const ::boost::numeric::ublasx::matrix_diagonal<MatrixT> >: public vector_temporary_traits<MatrixT> {};\n\n} // Namespace ublas\n\n}} // Namespace boost::numeric\n\n\n#endif // BOOST_NUMERIC_UBLASX_PROXY_MATRIX_DIAGONAL_HPP\n", "meta": {"hexsha": "999888da9050db5c33ae2ce8c1c27fcbe381ec9f", "size": 17722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/proxy/matrix_diagonal.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/proxy/matrix_diagonal.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/proxy/matrix_diagonal.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 22.8082368082, "max_line_length": 147, "alphanum_fraction": 0.7091186096, "num_tokens": 4943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.07263670334953287, "lm_q1q2_score": 0.03292344746686832}}
{"text": "/*=============================================================================\r\n    Copyright (c) 2001-2014 Joel de Guzman\r\n\r\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n=============================================================================*/\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Yet another calculator example! This time, we will compile to a simple\r\n//  virtual machine. This is actually one of the very first Spirit example\r\n//  circa 2000. Now, it's ported to Spirit2 (and X3).\r\n//\r\n//  [ JDG Sometime 2000 ]       pre-boost\r\n//  [ JDG September 18, 2002 ]  spirit1\r\n//  [ JDG April 8, 2007 ]       spirit2\r\n//  [ JDG February 18, 2011 ]   Pure attributes. No semantic actions.\r\n//  [ JDG April 9, 2014 ]       Spirit X3 (from qi calc6)\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// Uncomment this if you want to enable debugging\r\n//#define BOOST_SPIRIT_X3_DEBUG\r\n\r\n#if defined(_MSC_VER)\r\n# pragma warning(disable: 4345)\r\n#endif\r\n\r\n#include <boost/config/warning_disable.hpp>\r\n#include <boost/spirit/home/x3.hpp>\r\n#include <boost/spirit/home/x3/support/ast/variant.hpp>\r\n#include <boost/fusion/include/adapt_struct.hpp>\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <list>\r\n#include <numeric>\r\n\r\nnamespace x3 = boost::spirit::x3;\r\n\r\nnamespace client { namespace ast\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    //  The AST\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    struct nil {};\r\n    struct signed_;\r\n    struct expression;\r\n\r\n    struct operand : x3::variant<\r\n            nil\r\n          , unsigned int\r\n          , x3::forward_ast<signed_>\r\n          , x3::forward_ast<expression>\r\n        >\r\n    {\r\n        using base_type::base_type;\r\n        using base_type::operator=;\r\n    };\r\n\r\n    struct signed_\r\n    {\r\n        char sign;\r\n        operand operand_;\r\n    };\r\n\r\n    struct operation\r\n    {\r\n        char operator_;\r\n        operand operand_;\r\n    };\r\n\r\n    struct expression\r\n    {\r\n        operand first;\r\n        std::list<operation> rest;\r\n    };\r\n\r\n    // print function for debugging\r\n    inline std::ostream& operator<<(std::ostream& out, nil) { out << \"nil\"; return out; }\r\n}}\r\n\r\nBOOST_FUSION_ADAPT_STRUCT(\r\n    client::ast::signed_,\r\n    (char, sign)\r\n    (client::ast::operand, operand_)\r\n)\r\n\r\nBOOST_FUSION_ADAPT_STRUCT(\r\n    client::ast::operation,\r\n    (char, operator_)\r\n    (client::ast::operand, operand_)\r\n)\r\n\r\nBOOST_FUSION_ADAPT_STRUCT(\r\n    client::ast::expression,\r\n    (client::ast::operand, first)\r\n    (std::list<client::ast::operation>, rest)\r\n)\r\n\r\nnamespace client\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    //  The Virtual Machine\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    enum byte_code\r\n    {\r\n        op_neg,     //  negate the top stack entry\r\n        op_add,     //  add top two stack entries\r\n        op_sub,     //  subtract top two stack entries\r\n        op_mul,     //  multiply top two stack entries\r\n        op_div,     //  divide top two stack entries\r\n        op_int,     //  push constant integer into the stack\r\n    };\r\n\r\n    class vmachine\r\n    {\r\n    public:\r\n\r\n        vmachine(unsigned stackSize = 4096)\r\n          : stack(stackSize)\r\n          , stack_ptr(stack.begin())\r\n        {\r\n        }\r\n\r\n        int top() const { return stack_ptr[-1]; };\r\n        void execute(std::vector<int> const& code);\r\n\r\n    private:\r\n\r\n        std::vector<int> stack;\r\n        std::vector<int>::iterator stack_ptr;\r\n    };\r\n\r\n    void vmachine::execute(std::vector<int> const& code)\r\n    {\r\n        std::vector<int>::const_iterator pc = code.begin();\r\n        stack_ptr = stack.begin();\r\n\r\n        while (pc != code.end())\r\n        {\r\n            switch (*pc++)\r\n            {\r\n                case op_neg:\r\n                    stack_ptr[-1] = -stack_ptr[-1];\r\n                    break;\r\n\r\n                case op_add:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] += stack_ptr[0];\r\n                    break;\r\n\r\n                case op_sub:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] -= stack_ptr[0];\r\n                    break;\r\n\r\n                case op_mul:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] *= stack_ptr[0];\r\n                    break;\r\n\r\n                case op_div:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] /= stack_ptr[0];\r\n                    break;\r\n\r\n                case op_int:\r\n                    *stack_ptr++ = *pc++;\r\n                    break;\r\n            }\r\n        }\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    //  The Compiler\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    struct compiler\r\n    {\r\n        typedef void result_type;\r\n\r\n        std::vector<int>& code;\r\n        compiler(std::vector<int>& code)\r\n          : code(code) {}\r\n\r\n        void operator()(ast::nil) const { BOOST_ASSERT(0); }\r\n        void operator()(unsigned int n) const\r\n        {\r\n            code.push_back(op_int);\r\n            code.push_back(n);\r\n        }\r\n\r\n        void operator()(ast::operation const& x) const\r\n        {\r\n            boost::apply_visitor(*this, x.operand_);\r\n            switch (x.operator_)\r\n            {\r\n                case '+': code.push_back(op_add); break;\r\n                case '-': code.push_back(op_sub); break;\r\n                case '*': code.push_back(op_mul); break;\r\n                case '/': code.push_back(op_div); break;\r\n                default: BOOST_ASSERT(0); break;\r\n            }\r\n        }\r\n\r\n        void operator()(ast::signed_ const& x) const\r\n        {\r\n            boost::apply_visitor(*this, x.operand_);\r\n            switch (x.sign)\r\n            {\r\n                case '-': code.push_back(op_neg); break;\r\n                case '+': break;\r\n                default: BOOST_ASSERT(0); break;\r\n            }\r\n        }\r\n\r\n        void operator()(ast::expression const& x) const\r\n        {\r\n            boost::apply_visitor(*this, x.first);\r\n            for (ast::operation const& oper : x.rest)\r\n            {\r\n                (*this)(oper);\r\n            }\r\n        }\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    //  The calculator grammar\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    namespace calculator_grammar\r\n    {\r\n        using x3::uint_;\r\n        using x3::char_;\r\n\r\n        struct expression_class;\r\n        struct term_class;\r\n        struct factor_class;\r\n\r\n        x3::rule<expression_class, ast::expression> const expression(\"expression\");\r\n        x3::rule<term_class, ast::expression> const term(\"term\");\r\n        x3::rule<factor_class, ast::operand> const factor(\"factor\");\r\n\r\n        auto const expression_def =\r\n            term\r\n            >> *(   (char_('+') > term)\r\n                |   (char_('-') > term)\r\n                )\r\n            ;\r\n\r\n        auto const term_def =\r\n            factor\r\n            >> *(   (char_('*') > factor)\r\n                |   (char_('/') > factor)\r\n                )\r\n            ;\r\n\r\n        auto const factor_def =\r\n                uint_\r\n            |   '(' > expression > ')'\r\n            |   (char_('-') > factor)\r\n            |   (char_('+') > factor)\r\n            ;\r\n\r\n        BOOST_SPIRIT_DEFINE(\r\n            expression = expression_def\r\n          , term = term_def\r\n          , factor = factor_def\r\n        );\r\n\r\n        struct expression_class\r\n        {\r\n            //  Our error handler\r\n            template <typename Iterator, typename Exception, typename Context>\r\n            x3::error_handler_result\r\n            on_error(Iterator&, Iterator const& last, Exception const& x, Context const& context)\r\n            {\r\n                std::cout\r\n                    << \"Error! Expecting: \"\r\n                    << x.which()\r\n                    << \" here: \\\"\"\r\n                    << std::string(x.where(), last)\r\n                    << \"\\\"\"\r\n                    << std::endl\r\n                    ;\r\n                return x3::error_handler_result::fail;\r\n            }\r\n        };\r\n\r\n        auto calculator = expression;\r\n    }\r\n\r\n    using calculator_grammar::calculator;\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Main program\r\n///////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    std::cout << \"Expression parser...\\n\\n\";\r\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    std::cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\r\n\r\n    typedef std::string::const_iterator iterator_type;\r\n    typedef client::ast::expression ast_expression;\r\n    typedef client::compiler compiler;\r\n\r\n    std::string str;\r\n    while (std::getline(std::cin, str))\r\n    {\r\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        client::vmachine mach;              // Our virtual machine\r\n        std::vector<int> code;              // Our VM code\r\n        auto& calc = client::calculator;    // Our grammar\r\n        ast_expression expression;          // Our program (AST)\r\n        compiler compile(code);             // Compiles the program\r\n\r\n        std::string::const_iterator iter = str.begin();\r\n        std::string::const_iterator end = str.end();\r\n        boost::spirit::x3::ascii::space_type space;\r\n        bool r = phrase_parse(iter, end, calc, space, expression);\r\n\r\n        if (r && iter == end)\r\n        {\r\n            std::cout << \"-------------------------\\n\";\r\n            std::cout << \"Parsing succeeded\\n\";\r\n            compile(expression);\r\n            mach.execute(code);\r\n            std::cout << \"\\nResult: \" << mach.top() << std::endl;\r\n            std::cout << \"-------------------------\\n\";\r\n        }\r\n        else\r\n        {\r\n            std::string rest(iter, end);\r\n            std::cout << \"-------------------------\\n\";\r\n            std::cout << \"Parsing failed\\n\";\r\n            std::cout << \"-------------------------\\n\";\r\n        }\r\n    }\r\n\r\n    std::cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "17799c7bc5a2165217b53d8904404910a77fff2a", "size": 10622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/spirit/example/x3/calc6.cpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/spirit/example/x3/calc6.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/spirit/example/x3/calc6.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 30.5229885057, "max_line_length": 98, "alphanum_fraction": 0.4190359631, "num_tokens": 2105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.08269734041427963, "lm_q1q2_score": 0.03275378397362394}}
{"text": "/********************************************************************************\n * Copyright 2015 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RWLIBS_MATHEMATICA_RAWARRAY_HPP_\n#define RWLIBS_MATHEMATICA_RAWARRAY_HPP_\n\n/**\n * @file RawArray.hpp\n *\n * \\copydoc rwlibs::mathematica::RawArray\n */\n\n#include \"List.hpp\"\n#include \"Mathematica.hpp\"\n\n#include <rw/core/Ptr.hpp>\n#include <rw/core/macros.hpp>\n\n#include <boost/multi_array.hpp>\n\nnamespace rwlibs { namespace mathematica {\n    //! @addtogroup mathematica\n\n    //! @{\n    //! @brief Utility for the RawArray type.\n    class RawArrayUtil\n    {\n      public:\n        /**\n         * @brief Detect the dimensions of an array given as an expression.\n         * @param exp [in] the expression.\n         * @return the dimensions.\n         */\n        static std::size_t detectDimensions (const Mathematica::FunctionBase& exp);\n\n        /**\n         * @brief Get the type of array.\n         * @return a symbol with the data type.\n         */\n        template< typename T > static Mathematica::Symbol::Ptr getType ()\n        {\n            RW_THROW (\"Could not determine type for RawArray.\");\n        }\n\n      private:\n        RawArrayUtil (){};\n        virtual ~RawArrayUtil (){};\n    };\n\n    /**\n     * @brief Construct Byte symbol from unsigned char.\n     * @return Byte symbol.\n     */\n    template<> inline Mathematica::Symbol::Ptr RawArrayUtil::getType< unsigned char > ()\n    {\n        return rw::core::ownedPtr (new Mathematica::Symbol (\"Byte\"));\n    }\n\n    //! @brief Representation of a N-dimensional %Mathematica array with fixed depth.\n    template< typename T, std::size_t Dim > class RawArray : public Mathematica::Array< T >\n    {\n      public:\n        //! @brief Smart pointer type.\n        typedef rw::core::Ptr< RawArray< T, Dim > > Ptr;\n\n        //! @brief The underlying array type.\n        typedef boost::multi_array< T, Dim > ArrayType;\n\n        /**\n         * @brief Construct new array.\n         * @param array [in] the array.\n         */\n        RawArray (const ArrayType& array) : _array (array), _size (new int[Dim])\n        {\n            for (std::size_t i = 0; i < Dim; i++) {\n                _size[i] = _array.shape ()[i];\n            }\n            _type = RawArrayUtil::getType< T > ();\n        }\n\n        /**\n         * @brief Construct new array with specific shape.\n         * @param shape [in] the shape.\n         */\n        RawArray (boost::array< typename ArrayType::index, Dim > shape) :\n            _array (shape), _size (new int[Dim])\n        {\n            for (std::size_t i = 0; i < Dim; i++) {\n                _size[i] = shape[i];\n            }\n            _type = RawArrayUtil::getType< T > ();\n        }\n\n        /**\n         * @brief Construct new array with specific shape.\n         * @param shape [in] the shape.\n         */\n        RawArray (const std::vector< std::size_t > shape) : _size (new int[Dim])\n        {\n            for (std::size_t i = 0; i < Dim; i++) {\n                _size[i] = shape[i];\n            }\n            boost::array< typename ArrayType::index, Dim > bshape;\n            typename boost::array< typename ArrayType::index, Dim >::size_type i;\n            for (i = 0; i < Dim; i++) {\n                bshape[i] = shape[i];\n            }\n            _array.resize (bshape);\n\n            _type = RawArrayUtil::getType< T > ();\n            // boost::array<typename ArrayType::index,Dim> cur;\n            //_list = createList(_array,0,cur,size());\n        }\n\n        /**\n         * @brief Construct RawArray from native Mathematica array.\n         * @param data [in] the data.\n         * @param shape [in] the shape.\n         */\n        RawArray (const T* const data, const int* const shape) : _size (new int[Dim])\n        {\n            for (std::size_t i = 0; i < Dim; i++) {\n                _size[i] = shape[i];\n            }\n            boost::array< typename ArrayType::index, Dim > bshape;\n            typename boost::array< typename ArrayType::index, Dim >::size_type i;\n            int elements = 0;\n            for (i = 0; i < Dim; i++) {\n                bshape[i] = shape[i];\n                if (i == 0)\n                    elements = shape[0];\n                else\n                    elements *= shape[i];\n            }\n            _array.resize (bshape);\n            std::copy (data, data + elements, _array.data ());\n\n            _type = RawArrayUtil::getType< T > ();\n        }\n\n        //! @brief Destructor.\n        virtual ~RawArray () { delete[] _size; }\n\n        /**\n         * @brief Get the underlying array.\n         * @return a reference to the array.\n         */\n        const ArrayType& getArray () const { return _array; }\n\n        /**\n         * @brief Set a value.\n         * @param indexes [in] the indices.\n         * @param value [in] the value to set.\n         */\n        void set (std::vector< std::size_t > indexes, T value)\n        {\n            RW_ASSERT (indexes.size () == Dim);\n            boost::array< typename ArrayType::index, Dim > cur;\n            for (std::size_t i = 0; i < Dim; i++)\n                cur[i] = indexes[i];\n            _array (cur) = value;\n        }\n\n        /**\n         * @brief Construct a new array from an expression.\n         * @param exp [in] the expression to parse.\n         * @return a new array.\n         */\n        static RawArray< T, Dim >::Ptr fromExpression (const Mathematica::FunctionBase& exp)\n        {\n            if (exp.getName () != \"RawArray\")\n                RW_THROW (\"Expected function with name RawArray, not \" << exp.getName () << \".\");\n            const std::list< rw::core::Ptr< const Mathematica::Expression > > args =\n                exp.getArguments ();\n            if (args.size () != 2)\n                RW_THROW (\"Expected two arguments for RawArray, not \" << args.size () << \".\");\n\n            // Find the shape\n            boost::array< typename ArrayType::index, Dim > shape;\n            rw::core::Ptr< const Mathematica::Expression > arrayArg = args.back ();\n            rw::core::Ptr< const Mathematica::FunctionBase > fct;\n            bool cont                                                              = true;\n            typename boost::array< typename ArrayType::index, Dim >::size_type dim = 0;\n            while (cont) {\n                cont = false;\n                fct  = arrayArg.cast< const Mathematica::FunctionBase > ();\n                if (!fct.isNull ()) {\n                    const std::size_t args = fct->getArguments ().size ();\n                    if (args > 0) {\n                        shape[dim] = args;\n                        dim++;\n                        arrayArg = fct->getArguments ().front ();\n                        cont     = true;\n                    }\n                }\n            }\n            if (dim != Dim) {\n                RW_THROW (\"Dim appear to be wrong.\");\n            }\n\n            arrayArg = args.back ();\n            fct      = arrayArg.cast< const Mathematica::FunctionBase > ();\n            const rw::core::Ptr< const List > list = List::fromExpression (*fct);\n\n            RawArray< T, Dim >::Ptr array = rw::core::ownedPtr (new RawArray< T, Dim > (shape));\n            const std::vector< std::size_t > size = array->getSize ();\n            boost::array< typename ArrayType::index, Dim > cur;\n            setValues (array->_array, list, 0, cur, size);\n            return array;\n        }\n\n        /**\n         * @brief Set the values of an array recursively.\n         * @param array [in/out] the array.\n         * @param list  [in] the list at the current level.\n         * @param level [in] the current level.\n         * @param cur [in] the current indices.\n         * @param size [in] the shape of the array.\n         */\n        static void setValues (ArrayType& array, rw::core::Ptr< const List > list,\n                               std::size_t level,\n                               boost::array< typename ArrayType::index, Dim > cur,\n                               const std::vector< std::size_t >& size)\n        {\n            const std::list< rw::core::Ptr< const Mathematica::Expression > >& args =\n                list->getArguments ();\n            std::list< rw::core::Ptr< const Mathematica::Expression > >::const_iterator it =\n                args.begin ();\n            if (level == Dim - 1) {\n                for (std::size_t i = 0; i < size[level]; i++) {\n                    cur[level]                                               = i;\n                    const rw::core::Ptr< const Mathematica::Expression > exp = *it;\n                    const rw::core::Ptr< const Mathematica::Integer > integer =\n                        exp.cast< const Mathematica::Integer > ();\n                    if (integer.isNull ())\n                        RW_THROW (\"Expected integer at this level of the array.\");\n                    array (cur) = (T) integer->value ();\n                    it++;\n                }\n            }\n            else {\n                for (std::size_t i = 0; i < size[level]; i++) {\n                    cur[level]                                               = i;\n                    const rw::core::Ptr< const Mathematica::Expression > exp = *it;\n                    const rw::core::Ptr< const Mathematica::FunctionBase > fct =\n                        exp.cast< const Mathematica::FunctionBase > ();\n                    if (fct.isNull ())\n                        RW_THROW (\"Expected function at this level of the array.\");\n                    if (fct->getName () != \"List\")\n                        RW_THROW (\"Expected function with name \\\"List\\\", instead got \\\"\"\n                                  << fct->getName () << \"\\\".\");\n                    const rw::core::Ptr< const List > listChild = fct.cast< const List > ();\n                    RW_ASSERT (!listChild.isNull ());\n                    setValues (array, listChild, level + 1, cur, size);\n                    it++;\n                }\n            }\n        }\n\n        /**\n         * @brief Create a List expression from an array.\n         * @param array [in] the array.\n         * @param level [in] the current level.\n         * @param cur [in] the current indices.\n         * @param size [in] the shape of the array.\n         * @return a list.\n         */\n        static List::Ptr createList (const ArrayType& array, std::size_t level,\n                                     boost::array< typename ArrayType::index, Dim > cur,\n                                     const std::vector< std::size_t >& size)\n        {\n            const List::Ptr list = rw::core::ownedPtr (new List ());\n            if (level == Dim - 1) {\n                for (std::size_t i = 0; i < size[level]; i++) {\n                    cur[level] = i;\n                    list->add (rw::core::ownedPtr (new Mathematica::Integer (array (cur))));\n                }\n            }\n            else {\n                for (std::size_t i = 0; i < size[level]; i++) {\n                    cur[level] = i;\n                    list->add (createList (array, level + 1, cur, size));\n                }\n            }\n            return list;\n        }\n\n        /**\n         * @brief Get the shape.\n         * @return a list of sizes for each dimension.\n         */\n        std::vector< std::size_t > getSize () const\n        {\n            std::vector< std::size_t > shape;\n            for (std::size_t i = 0; i < Dim; i++)\n                shape.push_back (_array.shape ()[i]);\n            return shape;\n        }\n\n        //! @copydoc Mathematica::Expression::out\n        virtual void out (std::ostream& stream) const\n        {\n            stream << \"RawArray[\" << _type->getName () << \", << \";\n            for (std::size_t i = 0; i < Dim; i++) {\n                stream << _array.shape ()[i];\n                if (i != Dim - 1)\n                    stream << \"x\";\n            }\n            stream << \" array >>]\";\n        }\n\n        //! @copydoc Mathematica::Expression::clone\n        virtual Mathematica::Expression::Ptr clone () const\n        {\n            return rw::core::ownedPtr (new RawArray< T, Dim > (_array));\n        }\n\n        //! @copydoc Mathematica::Array::size\n        virtual const int* size () const { return _size; }\n\n        //! @copydoc Mathematica::Array::data\n        virtual const T* data () const { return _array.data (); }\n\n        //! @copydoc Mathematica::Array::dimensions\n        virtual int dimensions () const { return Dim; }\n\n      private:\n        ArrayType _array;\n        int* _size;\n        Mathematica::Symbol::Ptr _type;\n    };\n\n    //! @brief Value for the size of a RawArray when size is not known at compile time.\n    const int Dynamic = -1;\n\n    //! @brief Representation of a N-dimensional %Mathematica array with dynamic depth.\n    template< typename T > class RawArray< T, Dynamic > : public Mathematica::Array< T >\n    {\n      public:\n        //! @brief Smart pointer type.\n        typedef rw::core::Ptr< RawArray< T, Dynamic > > Ptr;\n\n        /**\n         * @brief Construct new array with a dynamic dimensionality.\n         * @param data [in] the data.\n         * @param dims [in] the size of each dimension.\n         * @param depth [in] the number of dimensions.\n         */\n        RawArray (const T* const data, const int* const dims, const int depth) :\n            _data (NULL), _dims (new int[depth]), _depth (depth)\n        {\n            int size = 0;\n            if (depth > 0) {\n                size = dims[0];\n                for (int i = 1; i < depth; i++) {\n                    size *= dims[i];\n                }\n            }\n            _data = new unsigned char[size];\n            std::copy (data, data + size, _data);\n            std::copy (dims, dims + depth, _dims);\n            _type = RawArrayUtil::getType< T > ();\n        }\n\n        //! @brief Destructor.\n        virtual ~RawArray ()\n        {\n            delete[] _data;\n            delete[] _dims;\n        }\n\n        //! @copydoc Mathematica::Expression::out\n        void out (std::ostream& stream) const\n        {\n            stream << \"RawArray[\" << _type->getName () << \", << \";\n            for (int i = 0; i < _depth; i++) {\n                stream << _dims[i];\n                if (i != _depth - 1)\n                    stream << \"x\";\n            }\n            stream << \" array >>]\";\n        }\n\n        //! @copydoc Mathematica::Expression::clone\n        Mathematica::Expression::Ptr clone () const\n        {\n            return rw::core::ownedPtr (new RawArray< T, Dynamic > (_data, _dims, _depth));\n        }\n\n        //! @copydoc Mathematica::Array::size\n        const int* size () const { return _dims; }\n\n        //! @copydoc Mathematica::Array::data\n        const T* data () const { return _data; }\n\n        //! @copydoc Mathematica::Array::dimensions\n        int dimensions () const { return _depth; }\n\n      private:\n        T* _data;\n        int* _dims;\n        const int _depth;\n        Mathematica::Symbol::Ptr _type;\n    };\n\n    //! @}\n}}     // namespace rwlibs::mathematica\n#endif /* RWLIBS_MATHEMATICA_RAWARRAY_HPP_ */\n", "meta": {"hexsha": "efeb2f7df5b69f1ce0709c668e4ac52e1e8215d2", "size": 15678, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/mathematica/RawArray.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rwlibs/mathematica/RawArray.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rwlibs/mathematica/RawArray.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0638297872, "max_line_length": 97, "alphanum_fraction": 0.4856486797, "num_tokens": 3564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.07477003775368835, "lm_q1q2_score": 0.03273607955822081}}
{"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/// Miscellaneous convenience resources.\n\n#include <tuple>\n#include <vector>\n#include <string>\n#include <memory>\n#include <limits>\n#include <algorithm>\n#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <random>\n#include <boost/integer/common_factor.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/mpi.hpp>\n#include <constants.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n\nnamespace alma {\n\n\n/// Randomly choose an element from a sequence using the provided rng.\ntemplate <typename I, typename R> I choose(I start, I end, R& g) {\n    std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);\n    std::advance(start, dis(g));\n    return start;\n}\n\n/// Stable Sum using Neumaier\n/// algorithm. See DOI: 10.1002/zamm.19740540106\n///(in German)\n\n/// Stable sum using pointer and size\n///@param  A pointer to data\n///@param  size size of data\n///@return stable summation result\ntemplate <class T> T NeumaierSum(T* A, std::size_t size) {\n    T sum = 0;\n    T c = 0;\n\n    for (std::size_t i = 0; i < size; i++) {\n        T t = sum + A[i];\n        if (std::abs(sum) >= std::abs(A[i]))\n            c += (sum - t) + A[i];\n        else\n            c += (A[i] - t) + sum;\n        sum = t;\n    }\n    return sum + c;\n}\n\n/// Neumaier Sum in which the summation\n/// cannot be done all together\n/// so that we keep the correction\n/// and the summation\n///@param result Neumaier sum until now\n///@param b      the number to add\ntemplate <class T>\nstd::complex<T> NeumaierSum(std::complex<T>& result, const T& b) {\n    T TemporalSum = std::real(result) + b;\n    if (std::abs(std::real(result)) >= std::abs(b)) {\n        result += std::complex<T>(0, (std::real(result) - TemporalSum) + b);\n    }\n    else {\n        result += std::complex<T>(0, (b - TemporalSum) + std::real(result));\n    }\n    result = std::complex<T>(TemporalSum, std::imag(result));\n    return result;\n}\n\n/// This is to eval the Neumaier sum\n/// it add correction to the summation\n/// and return the value\n///@param N summation and correction\n///@return the Neumaier summation\ntemplate <class T> T evalNeumaierSum(std::complex<T>& N) {\n    return std::real(N) + std::imag(N);\n}\n\n/// Thought for MPI collapse\n/// after gather\n///@param Ns vector containing Neumaier sumation info\n///          from different procs\n///@return the Neumaier summation\ntemplate <class T> T combineNeumaierSums(std::vector<std::complex<T>>& Ns) {\n    /// Get sums and errors and apply\n    /// stable sum to them\n    std::vector<T> sums, cs;\n    for (auto& N : Ns) {\n        sums.push_back(std::real(N));\n        cs.push_back(std::imag(N));\n    }\n\n    auto NeuSum = NeumaierSum(sums.data(), sums.size());\n\n    auto NeuCs = NeumaierSum(cs.data(), cs.size());\n\n    return NeuSum + NeuCs;\n}\n\n/// Comparator function object template for a container of\n/// comparable objects.\ntemplate <typename T> class Container_comparator {\npublic:\n    inline bool operator()(const T& op1, const T& op2) const {\n        return std::lexicographical_compare(\n            std::begin(op1), std::end(op1), std::begin(op2), std::end(op2));\n    }\n};\n\n/// Put the keys and values of a map (or similar) into separate\n/// vectors.\ntemplate <typename T>\nstd::tuple<std::vector<typename T::key_type>,\n           std::vector<typename T::mapped_type>>\nsplit_keys_and_values(const T& input) {\n    auto size = input.size();\n\n    std::vector<typename T::key_type> keys;\n    keys.reserve(size);\n    std::vector<typename T::mapped_type> values;\n    values.reserve(size);\n\n    for (auto& i : input) {\n        keys.emplace_back(i.first);\n        values.emplace_back(i.second);\n    }\n    return std::make_tuple(keys, values);\n}\n\n\n/// Read from f until '\\n' is found.\n///\n/// This function is meant to be called after reading data from f\n/// using >> and before using std::getline() on it.\n///\n/// @param[in] f - istream from which to read\ninline void flush_istream(std::istream& f) {\n    if (f.peek() == '\\n') {\n        f.ignore(1, '\\n');\n    }\n}\n\n\n/// Try to tokenize a line into homogeneous tokens.\n///\n/// This function tries to split a line into fields that can all be\n/// cast into the same type and return a vector of tokens.\n/// boost::bad_lexical_cast will be thrown in case of failure.\n///\n/// @param[in] line - line of text to tokenize\n/// @param[in] sep - field separators\n/// @return a vector of tokens\ntemplate <typename T>\ninline std::vector<T> tokenize_homogeneous_line(std::string& line,\n                                                const std::string sep = \" \\t\") {\n    std::vector<T> nruter;\n    boost::char_separator<char> separator(sep.c_str());\n    boost::tokenizer<boost::char_separator<char>> tokenizer(line, separator);\n\n    for (auto i : tokenizer)\n        nruter.emplace_back(boost::lexical_cast<T>(i));\n    return nruter;\n}\n\n\n/// Check whether a line starts with a character from a given set.\n///\n/// @param[in] line - string containing the line\n/// @param[in] chars - string containing the set of characters\n/// @return true if line starts with a character from chars\ninline bool starts_with_character(const std::string& line,\n                                  const std::string& chars) {\n    if (line.length() == 0)\n        return false;\n\n    for (auto c : chars) {\n        if (line[0] == c)\n            return true;\n    }\n    return false;\n}\n\n\n/// Approximate comparation between doubles.\n///\n/// @param[in] a - first value\n/// @param[in] b - second value\n/// @param[in] abstol - Maximum absolute tolerance\n/// @param[in] reltol - Maximum relative tolerance\n/// @return - true if the two values are almost equal\ninline bool almost_equal(const double a,\n                         const double b,\n                         const double abstol = 1e-8,\n                         const double reltol = 1e-5) {\n    // Method and default values inspired by\n    // numpy.allclose().\n    const auto tol = std::fabs(abstol) + std::fabs(reltol * b);\n\n    return std::fabs(a - b) < tol;\n}\n\n\n/// Convenience class for updating a minimum value and keeping track\n/// of all the objects associated to it.\ntemplate <typename T> class Min_keeper {\npublic:\n    /// Basic constructor.\n    Min_keeper(const double _abstol = 1e-8, const double _reltol = 1e-5)\n        : abstol(_abstol), reltol(_reltol) {\n    }\n\n\n    /// @return the current minimum value.\n    double get_value() const {\n        return this->minimum;\n    }\n\n\n    /// @return the vector of objects associated to the\n    /// current minimum.\n    std::vector<T> get_vector() const {\n        return this->objects;\n    }\n\n\n    /// Update the minimum value with a new one if the latter\n    /// is lower.\n    ///\n    /// If the new value is almost equal to the current minimum,\n    /// append obj to the vector of objects.\n    /// If the new value is lower than the current minimum, empty the\n    /// vector of objects, append obj and update the minimum value.\n    /// If the new value is higher than the current minimum, do\n    /// nothing.\n    /// @param[in] obj - new object\n    /// @param[in] value - associated value\n    void update(const T& obj, double value) {\n        if (almost_equal(value, this->minimum, this->abstol, this->reltol)) {\n            this->objects.emplace_back(obj);\n        }\n        else if (value < this->minimum) {\n            this->minimum = value;\n            this->objects.clear();\n            this->objects.emplace_back(obj);\n        }\n    }\n\n\nprivate:\n    /// Current minimum value.\n    double minimum = std::numeric_limits<double>::infinity();\n    /// Vector of objects associated to the current minimum value.\n    std::vector<T> objects;\n    /// Maximum absolute tolerance for equality between doubles.\n    const double abstol;\n    /// Maximum relative tolerance for equality between doubles.\n    const double reltol;\n};\n\n/// \"Signed square root\" of real numbers, that converts purely\n/// imaginary numbers to negative values.\n///\n/// @param[in] x - argument of the square root\n/// @return a real number with the absolute value of sqrt(|x|) and\n/// the sign of x\ninline double ssqrt(double x) {\n    return std::copysign(std::sqrt(std::fabs(x)), x);\n}\n\n\n/// Compute the sign of an argument.\n///\n/// @param[in] arg - anything that can be constructed passing 0\n/// as the only argument and that supports operator -\n/// @return -1, 0 or 1 depending on the sign of arg\ntemplate <typename T> inline int signum(const T& arg) {\n    T zero(0);\n\n    return (zero < arg) - (arg < zero);\n}\n\n\n/// Build a timestamp in our preferred format.\n///\n/// @return a string containing the current time.\ninline std::string get_timestamp() {\n    // A much more elegant solution using put_time() exists.\n    // We chose the traditional implementation because put time\n    // is not implemented in GCC < 5.\n    auto t = std::time(nullptr);\n    auto localtime = std::localtime(&t);\n    std::size_t size = 0;\n\n    std::vector<char> buffer;\n\n    do {\n        size += 64;\n        buffer.reserve(size);\n        // 64 bytesshould be enough for everybody, but we\n        // check the return code of std::strftime anyway to see\n        // if we need to allocate more space.\n    } while (std::strftime(\n                 buffer.data(), size, \"%Y-%m-%dT%H:%M:%S\", localtime) == 0u);\n    return std::string(buffer.data());\n}\n\n\n/// Compute the minimum and maximum indices of the jobs that must\n/// be executed in the current process.\n///\n/// Split njobs jobs among nproc processes and return the\n/// minimum and maximum indices of the jobs that must be assigned\n/// to the current process, bundled in an array. More\n/// specifically, return jmin and jmax so that we can write a\n/// for loop like\n/// for (auto j = jmin; j < jmax; ++j)\n/// @param[in] njobs - number of jobs\n/// @param[in] nprocs - number of process\n/// @param[in] my_id - id of the current process\ninline std::array<std::size_t, 2> my_jobs(std::size_t njobs,\n                                          std::size_t nprocs,\n                                          std::size_t my_id) {\n    // If nprocs divides njobs, each process gets exactly its\n    // fair share of jobs. If there is a remainder R , an extra\n    // job is assigned to the first R processes. If njobs > nprocs,\n    // some processes do not get any job.\n    auto quot = njobs / nprocs;\n    auto rem = njobs % nprocs;\n\n    std::array<std::size_t, 2> nruter;\n    nruter[0] = quot * my_id + std::min(rem, my_id);\n    nruter[1] = quot * (my_id + 1) + std::min(rem, my_id + 1);\n    return nruter;\n}\n\n\n/// Alternative modulus operation with a behavior similar to the %\n/// operator in Python.\n///\n/// @param[in] n - numerator\n/// @param[in] d - denominator\n/// @return the remainder of the integer division n / d with\n/// the same sign as d.\ntemplate <typename T, typename U> inline U python_mod(const T& n, const U& d) {\n    if (d < 0)\n        return python_mod(-n, -d);\n    else {\n        auto nruter = n % d;\n\n        if (nruter < 0)\n            nruter += d;\n        return nruter;\n    }\n}\n\n\n/// Bose-Einstein distribution.\n///\n/// @param[in] omega - angular frequency in rad/ps\n/// @param[in] T - temperature in K\n/// @return the average occupation number at equilibrium\ninline double bose_einstein(double omega, double T) {\n    constexpr double prefactor = 1e12 * constants::hbar / constants::kB;\n\n    return 1. / (std::exp(prefactor * omega / T) - 1.);\n}\n\n\n/// Integration kernel for the specific heat, thermal conductivity\n/// and other integrals.\n///\n/// This function implements the calculation of\n/// (x / sinh(x))^2,\n/// where x = hbar * omega / (2 * kB *T).\n/// @param[in] omega - angular frequency in rad/ps\n/// @param[in] T - temperature in K\n/// @return the value of the aforementioned function\ninline double bose_einstein_kernel(double omega, double T) {\n    constexpr double prefactor = 0.5 * 1e12 * constants::hbar / constants::kB;\n    auto x = prefactor * omega / T;\n\n    if (x < 1e-320) {\n        return 1.;\n    }\n    else if (x > 300.) {\n        return 0.;\n    }\n    else {\n        auto s = x / std::sinh(x);\n        return s * s;\n    }\n}\n\n\n/// Divide a vector of integers by the GCD of their coefficients.\n///\n/// @param[in] vector - the original vector\n/// @return the reduced vector\ninline Eigen::VectorXi reduce_integers(\n    const Eigen::Ref<const Eigen::VectorXi>& vector) {\n    std::size_t d = vector.size();\n    Eigen::VectorXi::Scalar gcd;\n\n    if (d == 0)\n        gcd = 1;\n    else {\n        gcd = std::abs(vector(0));\n\n        for (std::size_t i = 1; i < d; ++i)\n            gcd = boost::integer::gcd(gcd, vector(i));\n    }\n    return Eigen::VectorXi(vector / gcd);\n}\n\n\n/// Convert a numerical value to a string that uses engineering prefix\ninline std::string engineer_format(double x, bool insert_space = false) {\n    std::vector<char> prefix(\n        {'f', 'p', 'n', 'u', 'm', ' ', 'k', 'M', 'G', 'T'});\n    std::vector<double> scaling(\n        {1e-15, 1e-12, 1e-9, 1e-6, 1e-3, 1.0, 1e3, 1e6, 1e9, 1e12, 1e15});\n\n    int idx =\n        static_cast<int>(std::floor((std::log10(x) + 15.0) / (3.0 - 1e-12)));\n\n    if (idx < 0) {\n        idx = 0;\n    }\n\n    if (idx > 9) {\n        idx = 9;\n    }\n    std::stringstream result_builder;\n    result_builder << x / scaling.at(idx);\n\n    if (idx != 5) { // avoid introducing blank space\n        if (insert_space) {\n            result_builder << \" \";\n        }\n        result_builder << prefix.at(idx);\n    }\n    return result_builder.str();\n}\n\n\n/// Construct a vector with N logarithmically spaced values from min to\n/// max.\ninline Eigen::VectorXd logSpace(double min, double max, int N) {\n    Eigen::VectorXd logresult(N);\n\n    logresult.setLinSpaced(N, std::log10(min), std::log10(max));\n    return Eigen::pow(10.0, logresult.array());\n}\n\n\n} // namespace alma\n\nnamespace boost {\nnamespace serialization {\n/// Allow boost to serialize an Eigen::Triplet.\ntemplate <class Archive, typename S>\nvoid save(Archive& ar, const Eigen::Triplet<S>& t, const unsigned int version) {\n    ar& t.row();\n    ar& t.col();\n    ar& t.value();\n}\n\n\n/// Allow boost to unserialize an Eigen::Triplet.\ntemplate <class Archive, typename S>\nvoid load(Archive& ar, Eigen::Triplet<S>& t, const unsigned int version) {\n    int row;\n    ar& row;\n    int col;\n    ar& col;\n    S value;\n    ar& value;\n\n    t = Eigen::Triplet<S>(row, col, value);\n}\n\n\n/// Dummy function allowing us to implement\n/// save() and load() separately.\ntemplate <class Archive, typename S>\nvoid serialize(Archive& ar, Eigen::Triplet<S>& t, const unsigned int version) {\n    split_free(ar, t, version);\n}\n} // namespace serialization\n} // namespace boost\n", "meta": {"hexsha": "7a7680480c7a4142a50437b97d00e7d377cd8a70", "size": 15206, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utilities.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/utilities.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/utilities.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": 29.5836575875, "max_line_length": 80, "alphanum_fraction": 0.6288964882, "num_tokens": 3945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.07055959863037338, "lm_q1q2_score": 0.032529157865115815}}
{"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-2011 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#ifndef CHECK_DERIVATIVE_HH\n#define CHECK_DERIVATIVE_HH\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <fstream>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n#include <boost/mpl/size.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"algorithm/dune_bridge.hh\"\n#include \"tools/linalg/scalarproducts.hh\"\n\n/// Some helper's for a correct indentation of XML-code\nnamespace XMLHelper{\n\n  static int xml_level;\n\n  struct XMLBlock{\n    XMLBlock(std::ofstream &f, const char* s, const char* d=\"\") : file(f), str(s), data(d), offset(\"\")\n    {\n      xml_level += 2;\n      getOffset();\n      writeBegin();\n    }\n    XMLBlock(std::ofstream &f, std::string &s, std::string d=\"\") : file(f), str(s), data(d), offset(\"\")\n    { \n      xml_level += 2;\n      getOffset();\n      writeBegin();\n    }\n    ~XMLBlock()\n    {\n      file << offset.c_str() << \"</\" << str.c_str() << \">\" << std::endl;\n      xml_level -= 2;\n    }\n    \n  private:\n    void getOffset(){\n      for(int i=0; i<xml_level; ++i) offset.append(\" \");\n    }\n\n    void writeBegin(){\n      file << offset.c_str() << \"<\" << str.c_str() << data.c_str() << \">\" << std::endl;\n    }\n\n    std::ofstream& file;\n    std::string const str, data;\n    std::string offset;\n  };\n  \n}\n\n/// Class that checks the derivatives of a functional at a linearization point.\n/**\n * The analytic derivatives are compared with a finite difference approximation. Note that this\n * just gives you a hint (but a good one if you don't use stupid parameters for the tolerance and\n * the increment) about the correctness of your analytically calculated derivatives.\n * Keep in mind that it is a heuristic.\n */\ntemplate <class Functional, class EvaluationPoint, class SparseInt=int>\n                                                                   class DerivativeChecker\n                                                                   {\n                                                                   public:\n  typedef Bridge::KaskadeLinearization<Functional, EvaluationPoint> Linearization;\n  typedef typename Functional::Scalar Scalar;\n  enum{ idOfFirstBlock = 0,\n        idOfLastBlock  = boost::mpl::size<typename Functional::AnsatzVars::Variables>::type::value };\n\n  /// Constructor\n  /**\n   * \\param functional instance of the Functional\n   * \\param x_ linearization point\n   * \\param t error tolerance (point-wise, default=1.0e-6)\n   * \\param incr increment for finite differences (default=1.0e-9)\n   */\n  DerivativeChecker(Functional &functional, EvaluationPoint &x_, Scalar const t = 1.0e-6, Scalar const incr = 1.0e-9) :\n      x(x_), tolerance(t), increment(incr), linearization(functional, x)\n  {\n    checkFirstDerivative();\n    checkSecondDerivative();\n  }\n\n\n  /// Check first derivative.\n  /**\n   * This function is called by the constructor. You only need to call this function if you have\n   * changed the tolerance.\n   */\n  void checkFirstDerivative(){\n\n    std::cout << \"checking first derivative\" << std::endl;\n    int const numRows = linearization.rows(idOfFirstBlock, idOfLastBlock);\n    std::cout << \"number of rows: \" << numRows << std::endl;\n    std::cout << \"assembling...\";;\n\n    // analytic solution\n    std::vector<Scalar> analytic_solution;\n    // storage for the evaluation of the derivative at x and the at x+increment*e_i\n    Scalar distorted_value;\n\n    linearization.flush();\n    // get reference solution\n    linearization.getRHSBlocks(analytic_solution, idOfFirstBlock, idOfLastBlock);\n    // get undistorted rhs\n    Scalar const reference_value = linearization.getValue();\n\n    EvaluationPoint copyOf_x = linearization.getX();\n    std::vector<Scalar> xAsVector(numRows);\n    copyOf_x.write(xAsVector.begin());\n\n    // reserve storage for finite difference solution\n    firstDerivativeError.resize(xAsVector.size(),0);\n\n    // get finite difference gradient\n    for(size_t i=0; i<xAsVector.size(); ++i)\n    {\n      xAsVector[i] += increment;\n      copyOf_x.read(xAsVector.begin());\n      linearization.setX(copyOf_x);\n      linearization.flush();\n      distorted_value = linearization.getValue();\n      xAsVector[i] -= increment;\n\n      // store finite difference\n      firstDerivativeError[i] = (distorted_value - reference_value)/increment;\n      std::cout << \".\";\n    }\n    std::cout << \"done.\" << std::endl;\n    for(size_t i=0; i<firstDerivativeError.size(); ++i)\n      firstDerivativeError[i] -= analytic_solution[i];\n\n    Scalar infinityError = InfinityNorm(firstDerivativeError);\n    firstDerivativeOk = infinityError < tolerance;\n    if(firstDerivativeOk)\n      std::cout << \"\\n first derivative seems to be trustworthy!\\n\" << std::endl;\n    else\n      std::cout << \"\\n first derivative does not seem to be trustworthy!\\n\" << std::endl;\n  }\n\n\n  /// Check second derivative.\n  /**\n   * This function is called by the constructor. You only need to call this function if you have\n   * changed the tolerance.\n   */\n  void checkSecondDerivative(){\n\n    std::cout << \"checking second derivative:\" << std::endl;\n    // Define linearization at x\n    int const numRows = linearization.rows(idOfFirstBlock, idOfLastBlock);\n    std::cout << \"number of rows: \" << numRows << std::endl;\n    std::cout << \"assembling...\";\n\n\n    // sparse storage for the analytic solution\n    MatrixAsTriplet<Scalar,SparseInt> analytic_solution;\n    // storage for the evaluation of the derivative at x and the at x+increment*e_i\n    std::vector<Scalar> reference_value, distorted_value;\n    linearization.flush();\n    // get reference solution\n    linearization.getMatrixBlocks(analytic_solution, idOfFirstBlock, idOfLastBlock, idOfFirstBlock, idOfLastBlock);\n    // get undistorted rhs\n    linearization.getRHSBlocks(reference_value, idOfFirstBlock, idOfLastBlock);\n\n    // get evaluation point\n    EvaluationPoint copyOf_x = linearization.getX();\n    std::vector<Scalar> xAsVector(numRows);\n    copyOf_x.write(xAsVector.begin());\n\n    // get finite difference gradient matrix\n    for(size_t i=0; i<xAsVector.size(); ++i)\n    {\n      xAsVector[i] += increment;\n      copyOf_x.read(xAsVector.begin());\n      linearization.setX(copyOf_x);\n      linearization.flush();\n      linearization.getRHSBlocks(distorted_value, idOfFirstBlock, idOfLastBlock);\n      xAsVector[i] -= increment;\n\n      // store finite difference\n      for(size_t k=0; k<numRows; ++k)\n      {\n        secondDerivativeError.addEntry(k, i, (distorted_value[k] - reference_value[k])/increment);\n      }\n      std::cout << \".\";\n    }\n    std::cout << \"done.\" << std::endl;\n    analytic_solution *= -1;\n    secondDerivativeError += analytic_solution;\n\n\n    Scalar infinityError = InfinityNorm(secondDerivativeError);\n    secondDerivativeOk = tolerance > infinityError;\n    if(secondDerivativeOk)\n      std::cout << \"\\n second derivative seems to be trustworthy!\\n\" << std::endl;\n    else\n      std::cout << \"\\n second derivative does not seem to be trustworthy!\\n\" << std::endl;\n  }\n\n  /// get block\n  MatrixAsTriplet<Scalar> getBlocksD2Error(int firstBlockId, int lastBlockId) const\n  {\n    assert(firstBlockId < lastBlockId);\n    int offset = 0;\n    if(firstBlockId > 0) offset = linearization.rows(0,firstBlockId);\n    int const lastBlockIndex = offset + linearization.rows(firstBlockId, lastBlockId);\n\n    MatrixAsTriplet<Scalar> blocks;\n    for(int i=0; i<secondDerivativeError.size(); ++i)\n    {\n      if(secondDerivativeError.ridx[i] >= offset && secondDerivativeError.ridx[i] < lastBlockIndex &&\n         secondDerivativeError.cidx[i] >= offset && secondDerivativeError.cidx[i] < lastBlockIndex)\n        blocks.addEntry(secondDerivativeError.ridx[i], secondDerivativeError.cidx[i], secondDerivativeError.data[i]);\n    }\n    return blocks;\n  }\n\n  /// Only errors below tolerance will be displayed.\n  void setTolerance(Scalar const tol){ tolerance = tol; }\n\n  /// Set increment for finite differences\n  void setIncrement(Scalar const incr){ increment = incr; }\n\n  /// print error in first derivative (only values below tolerance)\n  void printD1Error() const {\n    std::cout << \"components in D1 over tolerance:\\n\";\n    for(size_t i=0; i<firstDerivativeError.size(); ++i)\n      if(fabs(firstDerivativeError[i]) > tolerance)\n        std::cout << i << \": \" << firstDerivativeError[i] << std::endl;\n  }\n\n  /// print error in first derivative\n  void printFullD1Error() const {\n    std::cout << \"components in D1:\\n\" << firstDerivativeError << std::endl;\n  }\n\n  /// print error in second derivative (only values below tolerance)\n  void printD2Error() const {\n    std::cout << \"components in D2 over tolerance:\\n\";\n    secondDerivativeError.print(std::cout,tolerance);\n  }\n\n  /// print error in second derivative\n  void printFullD2Error() const {\n    std::cout << \"components in D2:\\n\";\n    secondDerivativeError.print(std::cout);\n  }\n\n  /// write error in first derivative to .vtu file\n  void d1ErrorToVTK()  {\n\n    using std::endl;\n    using std::string;\n\n    size_t const numberOfCells = firstDerivativeError.size(),\n                 numberOfPoints = (1+numberOfCells)*2;\n    size_t const cell_type = 8,\n    offset = 4;\n\n    XMLHelper::xml_level = 0;\n    typedef typename XMLHelper::XMLBlock XMLBlock;\n\n    std::ofstream file(\"d1error.vtu\");\n    file << \"<?xml version=\\\"1.0\\\"?>\" << endl;\n    { XMLBlock xvtk(file, \"VTKFile\", \" type=\\\"UnstructuredGrid\\\" version=\\\"0.1\\\" byte_order=\\\"LittleEndian\\\"\");\n      { XMLBlock xgrid(file, \"UnstructuredGrid\");\n        { string str = string(\" NumberOfPoints=\\\"\") + boost::lexical_cast<string>(numberOfPoints) + \" \\\" NumberOfCells=\\\"\" +\n                                                      boost::lexical_cast<string>(numberOfCells) + \"\\\"\";\n          XMLBlock xpiece(file, \"Piece\", str.c_str());\n          { XMLBlock xcd(file, \"CellData\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"d2error\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << fabs(firstDerivativeError[cell]) << \" \";\n                if(cell%12==11 || cell==(numberOfCells-1) ) file << endl;\n              }\n            }\n          }\n          { XMLBlock xpoints(file, \"Points\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"Coordinates\\\" NumberOfComponents=\\\"3\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells+1; ++cell){\n                if(cell%2==0) file << \"    \";\n                file << cell << \" 0 0 \" << cell << \" 1 0 \";\n                if(cell%2==1 || cell==numberOfCells) file << endl;\n              }\n            }\n          }\n          { XMLBlock xcells(file, \"Cells\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"connectivity\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%3==0) file << \"    \";\n                file << 2*cell << \" \" << 2*cell+1 << \" \" << 2*cell+2 << \" \" << 2*cell+3 << \" \" << endl;\n                if(cell%3==11 || cell==(numberOfCells-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"offsets\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell*offset << \" \";\n                if(cell%12==1 || cell==(numberOfCells-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"UInt8\\\" Name=\\\"types\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell_type << \" \";\n                if(cell%12==11 || cell==(numberOfCells-1) ) file << endl;\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  /// write error in second derivative to .vtu file\n  void d2ErrorToVTK()  {\n\n    using std::endl;\n    using std::string;\n\n    /// store index pairs\n    std::vector<std::pair<SparseInt,SparseInt> > indices(secondDerivativeError.data.size());\n    for(size_t i=0; i<indices.size(); ++i)\n      indices[i] = std::make_pair(secondDerivativeError.ridx[i], secondDerivativeError.cidx[i]);\n\n    SparseInt const numberOfRows = secondDerivativeError.nrows()+1,\n    numberOfColumns = secondDerivativeError.ncols()+1,\n    numberOfPoints = numberOfRows*numberOfColumns,\n    numberOfCells = (numberOfRows-1)*(numberOfColumns-1);\n    size_t const cell_type = 8, // = vtk_pixel\n    offset = 4;\n\n    XMLHelper::xml_level = 0;\n    typedef typename XMLHelper::XMLBlock XMLBlock;\n\n    std::ofstream file(\"d2error.vtu\");\n    file << \"<?xml version=\\\"1.0\\\"?>\" << endl;\n    { XMLBlock xvtk(file, \"VTKFile\", \" type=\\\"UnstructuredGrid\\\" version=\\\"0.1\\\" byte_order=\\\"LittleEndian\\\"\");\n      { XMLBlock xgrid(file, \"UnstructuredGrid\");\n        { string str = string(\" NumberOfPoints=\\\"\") + boost::lexical_cast<string>(numberOfPoints) + \" \\\" NumberOfCells=\\\"\" +\n                                             boost::lexical_cast<string>(numberOfCells) + \"\\\"\";\n          XMLBlock xpiece(file, \"Piece\", str.c_str());\n          { XMLBlock xcd(file, \"CellData\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"d2error\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << fabs(firstDerivativeError[cell]) << \" \";\n                if(cell%12==11 || cell==(numberOfCells-1) ) file << endl;\n              }\n            }\n          }\n          { XMLBlock xp(file, \"Points\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"Coordinates\\\" NumberOfComponents=\\\"3\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells+1; ++cell){\n                if(cell%2==0) file << \"    \";\n                file << cell << \" 0 0 \" << cell << \" 1 0 \";\n                if(cell%2==1 || cell==numberOfCells) file << endl;\n              }\n            }\n          }\n          { XMLBlock xcell(file, \"Cells\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"connectivity\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%3==0) file << \"    \";\n                file << 2*cell << \" \" << 2*cell+1 << \" \" << 2*cell+2 << \" \" << 2*cell+3 << \" \" << endl;\n                if(cell%3==11 || cell==(numberOfCells-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"offsets\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell*offset << \" \";\n                if(cell%12==1 || cell==(numberOfCells-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"UInt8\\\" Name=\\\"types\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell_type << \" \";\n                if(cell%12==11 || cell==(numberOfCells-1) ) file << endl;\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\nprivate:\n  EvaluationPoint & x;\n  Scalar tolerance, increment;\n  Linearization linearization;\n  std::vector<Scalar> firstDerivativeError;\n  MatrixAsTriplet<Scalar,SparseInt> secondDerivativeError;\n  bool firstDerivativeOk, secondDerivativeOk;\n};\n#endif /* CHECK_DERIVATIVE_HH */\n", "meta": {"hexsha": "b65f809e53d2ac6105b6df412cd26c9309ac1d76", "size": 16528, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/tools/check_derivative.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/tools/check_derivative.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/tools/check_derivative.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": 39.922705314, "max_line_length": 130, "alphanum_fraction": 0.577928364, "num_tokens": 4057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.07477004857766206, "lm_q1q2_score": 0.03244881520519243}}
{"text": "/*******************************************************************************\n *\n * An implementation of discrete domains based on Patricia trees.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n *\n * Notices:\n *\n * Copyright (c) 2011 United States Government as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All Rights Reserved.\n *\n * Disclaimers:\n *\n * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED \"AS IS\" WITHOUT ANY WARRANTY OF\n * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED\n * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,\n * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,\n * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE\n * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO\n * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN\n * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,\n * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS\n * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY\n * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,\n * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT \"AS IS.\"\n *\n * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST\n * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL\n * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS\n * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH\n * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,\n * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD\n * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,\n * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.\n * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,\n * UNILATERAL TERMINATION OF THIS AGREEMENT.\n *\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/domains/patricia_trees.hpp>\n#include <crab/support/debug.hpp>\n\n#include <boost/range.hpp>\n\nnamespace ikos {\n\ntemplate <typename Element> class discrete_domain {\n\nprivate:\n  using ptset_t = patricia_tree_set<Element>;\n\npublic:\n  using discrete_domain_t = discrete_domain<Element>;\n  using iterator = typename ptset_t::iterator;\n\nprivate:\n  bool m_is_top;\n  ptset_t m_set;\n\nprivate:\n  discrete_domain(bool is_top) : m_is_top(is_top) {}\n  discrete_domain(ptset_t set) : m_is_top(false), m_set(set) {}\n\npublic:\n  // Return an empty set\n  static discrete_domain_t bottom() { return discrete_domain_t(false); }\n  // Return a set with all variables\n  static discrete_domain_t top() { return discrete_domain_t(true); }\n\npublic:\n  // Default constructor creates an empty set rather than top\n  discrete_domain() : m_is_top(false) {}\n\n  discrete_domain(const discrete_domain_t &other) = default;\n  discrete_domain(discrete_domain_t &&other) = default;\n  discrete_domain_t &operator=(const discrete_domain_t &other) = default;\n  discrete_domain_t &operator=(discrete_domain_t &&other) = default;  \n\n  discrete_domain(Element s) : m_is_top(false), m_set(s) {}\n\n  template <typename Iterator>\n  discrete_domain(Iterator eIt, Iterator eEt) : m_is_top(false) {\n    for (auto e : boost::make_iterator_range(eIt, eEt)) {\n      m_set += e;\n    }\n  }\n\n  bool is_top() const { return m_is_top; }\n\n  bool is_bottom() const { return (!m_is_top && m_set.empty()); }\n\n  bool operator<=(const discrete_domain_t &other) const {\n    return other.m_is_top || (!m_is_top && m_set <= other.m_set);\n  }\n\n  bool operator==(const discrete_domain_t &other) const {\n    return (m_is_top && other.m_is_top) || (m_set == other.m_set);\n  }\n\n  void operator|=(const discrete_domain_t &other) { *this = *this | other; }\n\n  discrete_domain_t operator|(const discrete_domain_t &other) const {\n    if (m_is_top || other.m_is_top) {\n      return discrete_domain_t(true);\n    } else {\n      return discrete_domain_t(m_set | other.m_set);\n    }\n  }\n\n  discrete_domain_t operator&(const discrete_domain_t &other) const {\n    if (is_bottom() || other.is_bottom()) {\n      return discrete_domain_t::bottom();\n    } else if (is_top()) {\n      return other;\n    } else if (other.is_top()) {\n      return *this;\n    } else {\n      return discrete_domain_t(m_set & other.m_set);\n    }\n  }\n\n  discrete_domain_t operator||(const discrete_domain_t &other) const {\n    return operator|(other);\n  }\n\n  discrete_domain_t operator&&(const discrete_domain_t &other) const {\n    return operator&(other);\n  }\n\n  discrete_domain_t &operator+=(Element s) {\n    if (!m_is_top) {\n      m_set += s;\n    }\n    return *this;\n  }\n\n  template <typename Range> discrete_domain_t &operator+=(Range es) {\n    if (!m_is_top) {\n      for (auto e : es) {\n        m_set += e;\n      }\n    }\n    return *this;\n  }\n\n  discrete_domain_t operator+(Element s) {\n    discrete_domain_t r(*this);\n    r.operator+=(s);\n    return r;\n  }\n\n  template <typename Range> discrete_domain_t operator+(Range es) {\n    discrete_domain_t r(*this);\n    r.operator+=(es);\n    return r;\n  }\n\n  discrete_domain_t &operator-=(Element s) {\n    if (!m_is_top) {\n      m_set -= s;\n    }\n    return *this;\n  }\n\n  template <typename Range> discrete_domain_t &operator-=(Range es) {\n    if (!m_is_top) {\n      for (auto e : es) {\n        m_set -= e;\n      }\n    }\n    return *this;\n  }\n\n  discrete_domain_t operator-(Element s) {\n    discrete_domain_t r(*this);\n    r.operator-=(s);\n    return r;\n  }\n\n  template <typename Range> discrete_domain_t operator-(Range es) {\n    discrete_domain_t r(*this);\n    r.operator-=(es);\n    return r;\n  }\n\n  bool contain(Element e) {\n    if (is_bottom()) {\n      return false;\n    } else if (is_top()) {\n      return true;\n    } else {\n      return m_set[e];\n    }\n  }\n  \n  void rename(const std::vector<Element> &from, const std::vector<Element> &to) {\n    if (is_top() || is_bottom()) {\n      return;\n    }\n    if (from.size() != to.size()) {\n      CRAB_ERROR(\"discrete_domain::rename with input vectors of different sizes\");\n    }\n\n    for(unsigned i=0, sz=from.size(); i<sz; ++i) {\n      if (from[i] == to[i]) {\n\tcontinue;\n      }\n      if (contain(from[i])) {\n\tthis->operator-=(from[i]);\n\tthis->operator+=(to[i]);\n      }\n    }\n  }\n  \n  std::size_t size() const {\n    if (m_is_top) {\n      assert(false);\n      CRAB_ERROR(\"Size for discrete domain TOP is undefined\");\n    } else {\n      return m_set.size();\n    }\n  }\n\n  iterator begin() const {\n    if (m_is_top) {\n      assert(false);      \n      CRAB_ERROR(\"Iterator for discrete domain TOP is undefined\");\n    } else {\n      return m_set.begin();\n    }\n  }\n\n  iterator end() const {\n    if (m_is_top) {\n      assert(false);      \n      CRAB_ERROR(\"Iterator for discrete domain TOP is undefined\");\n    } else {\n      return m_set.end();\n    }\n  }\n\n  void write(crab::crab_os &o) const {\n    if (m_is_top) {\n      o << \"{...}\";\n    } else if (m_set.empty()) {\n      o << \"{}\";\n    } else {\n      o << m_set;\n    }\n  }\n\n}; // class discrete_domain\n\ntemplate <typename Elem>\ninline crab::crab_os &operator<<(crab::crab_os &o,\n                                 const discrete_domain<Elem> &d) {\n  d.write(o);\n  return o;\n}\n\n} // namespace ikos\n\n\nnamespace crab {\nnamespace domains {\n  \n//===================================================================//  \n//        The NOSA license does not apply to this code  \n//===================================================================//  \n\n\n/**\n * This domain is semantically equivalent to discrete_domain but it\n * uses std::set instead of patricia tries as underlying\n * datastructure. Because of this, this domain is slower than\n * discrete_domain so the only reason to use it is when Element is not\n * a subclass of indexable.\n**/\n\ntemplate <class Element, class Compare>\nclass set_domain {\nprivate:\n  using set_t = std::set<Element, Compare>;\n\npublic:\n  using set_domain_t = set_domain<Element, Compare>;\n  using iterator = typename set_t::const_iterator;\n\nprivate:\n  bool m_is_top;\n  set_t m_set;\n\nprivate:\n  set_domain(bool is_top) : m_is_top(is_top) {}\n  set_domain(set_t set) : m_is_top(false), m_set(set) {}\n\npublic:\n  // Default constructor creates an empty set rather than top\n  set_domain() : m_is_top(false) {}\n  set_domain(Element s) : m_is_top(false) {\n    m_set.insert(s);\n  }  \n  set_domain(const set_domain_t &other) = default;\n  set_domain(set_domain_t &&other) = default;\n  set_domain_t &operator=(const set_domain_t &other) = default;\n  set_domain_t &operator=(set_domain_t &&other) = default;  \n\n  // Return an empty set\n  static set_domain_t bottom() { return set_domain_t(false); }\n  // Return a set with all variables\n  static set_domain_t top() { return set_domain_t(true); }\n  \n  bool is_top() const { return m_is_top; }\n  bool is_bottom() const { return (!m_is_top && m_set.empty()); }\n\n  bool operator<=(const set_domain_t &other) const {\n    return other.m_is_top ||\n      (!m_is_top && std::includes(other.m_set.begin(), other.m_set.end(),\n\t\t\t\t  m_set.begin(), m_set.end(),\n\t\t\t\t  [](const Element &e1, const Element &e2) {\n\t\t\t\t    Compare cmp;\n\t\t\t\t    return cmp(e1,e2);\n\t\t\t\t  }));\n  }\n\n  bool operator==(const set_domain_t &other) const {\n    return (m_is_top && other.m_is_top) || (m_set == other.m_set);\n  }\n\n  void operator|=(const set_domain_t &other) {\n    if (is_top()) {\n      return;\n    } else if (other.is_top()) {\n      *this = other;\n    } else {\n      m_set.insert(other.begin(), other.end());\n    }\n  }\n\n  set_domain_t operator|(const set_domain_t &other) const {\n    if (is_top() || other.is_top()) {\n      return set_domain_t::top();\n    } else {\n      set_domain_t res(*this);\n      res.m_set.insert(other.begin(), other.end());\n      return res;\n    }\n  }\n\n  set_domain_t operator&(const set_domain_t &other) const {\n    if (is_bottom() || other.is_bottom()) {\n      return set_domain_t::bottom();\n    } else if (is_top()) {\n      return other;\n    } else if (other.is_top()) {\n      return *this;\n    } else {\n      set_t s;\n      std::set_intersection(m_set.begin(), m_set.end(),\n\t\t\t    other.m_set.begin(), other.m_set.end(),\n\t\t\t    std::inserter(s, s.end()),\n\t\t\t    [](const Element &e1, const Element &e2) {\n\t\t\t      Compare cmp;\n\t\t\t      return cmp(e1,e2);\n\t\t\t    });\n      return set_domain_t(s);\n    }\n  }\n\n  set_domain_t operator||(const set_domain_t &other) const {\n    return operator|(other);\n  }\n\n  set_domain_t operator&&(const set_domain_t &other) const {\n    return operator&(other);\n  }\n\n  set_domain_t &operator+=(Element s) {\n    if (!is_top()) {\n      m_set.insert(s);\n    }\n    return *this;\n  }\n\n  set_domain_t operator+(Element s) {\n    set_domain_t r(*this);\n    r.operator+=(s);\n    return r;\n  }\n\n  set_domain_t &operator-=(Element s) {\n    if (!is_top()) {\n      m_set.erase(s);\n    }\n    return *this;\n  }\n\n  set_domain_t operator-(Element s) {\n    set_domain_t r(*this);\n    r.operator-=(s);\n    return r;\n  }\n\n  bool contain(Element e) {\n    if (is_bottom()) {\n      return false;\n    } else if (is_top()) {\n      return true;\n    } else {\n      return m_set.count(e) > 0;\n    }\n  }\n  \n  void rename(const std::vector<Element> &from, const std::vector<Element> &to) {\n    if (is_top() || is_bottom()) {\n      return;\n    }\n    if (from.size() != to.size()) {\n      CRAB_ERROR(\"set domain::rename with input vectors of different sizes\");\n    }\n\n    for(unsigned i=0, sz=from.size(); i<sz; ++i) {\n      if (from[i] == to[i]) {\n\tcontinue;\n      }\n      if (contain(from[i])) {\n\tthis->operator-=(from[i]);\n\tthis->operator+=(to[i]);\n      }\n    }\n  }\n  \n  std::size_t size() const {\n    if (is_top()) {\n      assert(false);\n      CRAB_ERROR(\"Size for set domain TOP is undefined\");\n    } else {\n      return m_set.size();\n    }\n  }\n\n  iterator begin() const {\n    if (is_top()) {\n      assert(false);      \n      CRAB_ERROR(\"Iterator for set domain TOP is undefined\");\n    } else {\n      return m_set.begin();\n    }\n  }\n\n  iterator end() const {\n    if (is_top()) {\n      assert(false);      \n      CRAB_ERROR(\"Iterator for set domain TOP is undefined\");\n    } else {\n      return m_set.end();\n    }\n  }\n\n  void write(crab::crab_os &o) const {\n    if (is_top()) {\n      o << \"{...}\";\n    } else if (is_bottom()) {\n      o << \"{}\";\n    } else {\n      o << \"{\";\n      for (auto it = m_set.begin(), et = m_set.end(); it!=et; ) {\n\to << *it;\n\t++it;\n\tif (it != et) {\n\t  o << \",\";\n\t}\n      }\n      o << \"}\";\n    }\n  }\n\n}; // class set_domain\n\ntemplate<class Element, class Compare>\ninline crab::crab_os &operator<<(crab::crab_os &o,\n                                 const set_domain<Element,Compare> &d) {\n  d.write(o);\n  return o;\n}\n\n// Dual of set_domain: the larger is the set, the more precise is the\n// domain.\ntemplate<class Element, class Compare>\nclass dual_set_domain {\n  using dual_set_domain_t = dual_set_domain<Element, Compare>;\n  using set_domain_t = set_domain<Element, Compare>;\n  \n  \n  set_domain_t m_set;\n    \npublic:\n  using iterator = typename set_domain_t::iterator;\n\n  dual_set_domain(set_domain_t s)\n    : m_set(s) {}\n  dual_set_domain()\n    : m_set(set_domain_t::bottom()) /*top by default*/ {}\n  dual_set_domain(const dual_set_domain_t &other)\n    : m_set(other.m_set) {}\n\n  static dual_set_domain_t bottom() { return set_domain_t::top(); }\n  static dual_set_domain_t top() { return set_domain_t::bottom(); }\n  bool is_top() const { return m_set.is_bottom(); }\n  bool is_bottom() const { return m_set.is_top(); }\n\n  bool operator<=(const dual_set_domain_t &other) const {\n    if (other.is_top() || is_bottom()) {\n      return true;\n    } else {\n      return other.m_set <= m_set;\n    }\n  }\n\n  bool operator==(const dual_set_domain_t &other) const {\n    return (*this <= other && other <= *this);\n  }\n\n  void operator|=(const dual_set_domain_t &other) {\n    m_set = m_set & other.m_set;\n  }\n\n  dual_set_domain_t operator|(const dual_set_domain_t &other) const {\n    return dual_set_domain_t(m_set & other.m_set);\n  }\n\n  dual_set_domain_t operator&(const dual_set_domain_t &other) const {\n    return dual_set_domain_t(m_set | other.m_set);\n  }\n\n  dual_set_domain_t operator||(const dual_set_domain_t &other) const {\n    return this->operator|(other);\n  }\n\n  dual_set_domain_t operator&&(const dual_set_domain_t &other) const {\n    return this->operator&(other);\n  }\n\n  dual_set_domain_t &operator+=(const Element &c) {\n    m_set += c;\n    return *this;\n  }\n  dual_set_domain_t &operator-=(const Element &c) {\n    m_set -= c;\n    return *this;\n  }\n\n  std::size_t size() { return m_set.size(); }\n\n  iterator begin() const  { return m_set.begin(); }\n  iterator end() const { return m_set.end(); }\n  \n  void write(crab::crab_os &o) {\n    if (is_bottom()) {\n      o << \"_|_\";\n    } else if (is_top()) {\n      o << \"top\";\n    } else {\n      m_set.write(o);\n    }\n  }\n\n  friend crab::crab_os &operator<<(crab::crab_os &o,\n\t\t\t\t   dual_set_domain_t &dom) {\n    dom.write(o);\n    return o;\n  }\n}; // end dual_set_domain\n\n\n/*\n * Represent sets of pairs (Key,Value).\n * \n * The pair must consist of a Key (must inherit from indexable class)\n * and a Value that can be a generic abstract domain. \n * \n * Bottom means empty set rather than failure.\n */ \ntemplate <typename Key, typename Value> class discrete_pair_domain {\n\nprivate:\n  using patricia_tree_t = ikos::patricia_tree<Key, Value>;\n  using unary_op_t = typename patricia_tree_t::unary_op_t;\n  using binary_op_t = typename patricia_tree_t::binary_op_t;\n  using partial_order_t = typename patricia_tree_t::partial_order_t;\n\npublic:\n  using discrete_pair_domain_t = discrete_pair_domain<Key, Value>;\n  using iterator = typename patricia_tree_t::iterator;\n  using key_type = Key;\n  using value_type = Value;\n\nprivate:\n  bool m_is_top;\n  patricia_tree_t m_tree;\n\n  static patricia_tree_t apply_operation(binary_op_t &o,\n                                         const patricia_tree_t &t1,\n                                         const patricia_tree_t &t2,\n                                         bool &is_bottom) {\n    patricia_tree_t res(t1);\n    is_bottom = res.merge_with(t2, o);\n    return res;\n  }\n\n  discrete_pair_domain(patricia_tree_t t) : m_is_top(false), m_tree(t) {}\n\n  discrete_pair_domain(bool b) : m_is_top(b) {}\n\n  class join_op : public binary_op_t {\n    std::pair<bool, boost::optional<Value>> apply(Value x, Value y) {\n      Value z = x.operator|(y);\n      if (z.is_top()) {\n        return {false, boost::optional<Value>()};\n      } else {\n        return {false, boost::optional<Value>(z)};\n      }\n    }\n    bool default_is_absorbing() { return false; }\n  }; // class join_op\n\n  class meet_op : public binary_op_t {\n    std::pair<bool, boost::optional<Value>> apply(Value x, Value y) {\n      Value z = x.operator&(y);\n      if (z.is_bottom()) {\n        return {true, boost::optional<Value>()};\n      } else {\n        return {false, boost::optional<Value>(z)};\n      }\n    };\n    bool default_is_absorbing() { return true; }\n  }; // class meet_op\n\n  class domain_po : public partial_order_t {\n    bool leq(Value x, Value y) { return x.operator<=(y); }\n    bool default_is_top() { return false; }\n  }; // class domain_po\n\npublic:\n  static discrete_pair_domain_t top() {\n    return discrete_pair_domain_t(true);\n  }\n\n  static discrete_pair_domain_t bottom() {\n    return discrete_pair_domain_t(false);\n  }\n  \n  discrete_pair_domain() : m_is_top(false), m_tree(patricia_tree_t()) {}\n\n\n  discrete_pair_domain(const discrete_pair_domain_t &o) = default;\n  discrete_pair_domain(discrete_pair_domain_t &&o) = default;\n  discrete_pair_domain_t &operator=(const discrete_pair_domain_t &o)  = default;\n  discrete_pair_domain_t &operator=(discrete_pair_domain_t &&o)  = default;\n  \n  iterator begin() const {\n    if (is_top()) {\n      CRAB_ERROR(\"discrete_pair_domain: trying to invoke iterator on top\");\n    } else {\n      return m_tree.begin();\n    }\n  }\n\n  iterator end() const {\n    if (is_top()) {\n      CRAB_ERROR(\"discrete_pair_domain: trying to invoke iterator on top\");\n    } else {\n      return m_tree.end();\n    }\n  }\n\n  bool is_top() const { return m_is_top; }\n\n  bool is_bottom() const { return (!is_top() && m_tree.empty()); }\n\n  bool operator<=(const discrete_pair_domain_t &o) const {\n    domain_po po;\n    return (o.is_top() || (!is_top() && (m_tree.leq(o.m_tree, po))));\n  }\n\n  discrete_pair_domain_t\n  operator|(const discrete_pair_domain_t &o) const {\n    if (is_top() || o.is_top()) {\n      return discrete_pair_domain_t::top();\n    } else {\n      join_op op;\n      bool is_bottom;\n      patricia_tree_t res = apply_operation(op, m_tree, o.m_tree, is_bottom);\n      return discrete_pair_domain_t(std::move(res));\n    }\n  }\n\n  discrete_pair_domain_t\n  operator&(const discrete_pair_domain_t &o) const {\n    if (is_top()) {\n      return o;\n    } else if (o.is_top()) {\n      return *this;\n    } else {\n      meet_op op;\n      bool is_bottom;\n      patricia_tree_t res = apply_operation(op, m_tree, o.m_tree, is_bottom);\n      if (is_bottom) {\n        return discrete_pair_domain_t::bottom();\n      } else {\n        return discrete_pair_domain_t(std::move(res));\n      }\n    }\n  }\n\n  void set(Key k, Value v) {\n    if (!is_top()) {\n      m_tree.insert(k, v);\n    }\n  }\n\n  discrete_pair_domain_t &operator-=(Key k) {\n    if (!is_top()) {\n      m_tree.remove(k);\n    }\n    return *this;\n  }\n\n  Value operator[](Key k) {\n    if (is_top())\n      return Value::top();\n    else {\n      boost::optional<Value> v = m_tree.lookup(k);\n      if (v) {\n        return *v;\n      } else {\n        return Value::bottom();\n      }\n    }\n  }\n  \n  void write(crab::crab_os &o) const {\n    if (is_top()) {\n      o << \"{...}\";\n    } else if (is_bottom()) {\n      o << \"{}\";\n    } else {\n      o << \"{\";\n      for (typename patricia_tree_t::iterator it = m_tree.begin();\n           it != m_tree.end();) {\n        Key k = it->first;\n        k.write(o);\n        o << \" -> \";\n        Value v = it->second;\n        v.write(o);\n        ++it;\n        if (it != m_tree.end()) {\n          o << \"; \";\n        }\n      }\n      o << \"}\";\n    }\n  }\n}; // class discrete_pair_domain\n\ntemplate <typename Key, typename Value>\ninline crab_os &operator<<(crab_os &o, const discrete_pair_domain<Key, Value> &d) {\n  d.write(o);\n  return o;\n}\n\n} //end namespace domains\n} //end namespace crab\n", "meta": {"hexsha": "dae2a6893b22c421d8a28df290a247c6ed980629", "size": 20422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/discrete_domains.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/discrete_domains.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/discrete_domains.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 26.2831402831, "max_line_length": 83, "alphanum_fraction": 0.6192341592, "num_tokens": 5288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.0685375006423242, "lm_q1q2_score": 0.03239654408248895}}
{"text": "#ifndef WINDOW_MIN_HPP\r\n#define WINDOW_MIN_HPP\r\n\r\n#include <Python.h>\r\n\r\n#include <utility>\r\n#include <iosfwd>\r\n#include <boost/circular_buffer.hpp>\r\n\r\n#include \"dbg.hpp\"\r\n\r\n/**\r\n* Implementation of Richard Harter's algorithm \r\n*\t(http://home.tiac.net/~cri/2001/slidingmin.html). */\r\ntemplate<\r\n\ttypename Value_Type = double, \r\n\tclass Cmp = std::less<Value_Type> >\r\nclass sliding_window_min_tracker\r\n{\r\npublic:\r\n\ttypedef Value_Type value_type;\r\n\ttypedef Cmp cmp;\r\n\r\npublic:\r\n\texplicit sliding_window_min_tracker(unsigned int capacity);\r\n\tvirtual ~sliding_window_min_tracker();\r\n\r\n\tvoid push(value_type v);\r\n\r\n\tinline value_type min() const;\r\n\r\n\tinline bool empty() const;\r\n\r\n\tinline unsigned int capacity() const;\r\n\r\n\tvoid trace(std::ostream &r_os) const;\r\n\r\nprivate:\r\n\ttypedef std::pair<value_type, unsigned int> entry_t;\r\n\ttypedef boost::circular_buffer<entry_t> buf_t;\r\n\r\n\r\nprivate:\r\n#ifdef DBG_MODE\r\n\tvoid assert_valid() const;\r\n#endif // #ifdef DBG_MODE\r\n\r\nprivate:\r\n\tcmp m_cmp;\r\n\r\n\tbuf_t m_a_buf;\r\n\r\n\tunsigned int m_ind;\r\n};\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\n\tCmp sliding_window_min_tracker<Value_Type, Cmp>::s_cmp;\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\nsliding_window_min_tracker<Value_Type, Cmp>::\r\n\t\tsliding_window_min_tracker(unsigned int capacity) :\r\n\tm_a_buf(capacity)\r\n{\r\n\tDBG_ONLY(assert_valid();)\r\n}\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\nsliding_window_min_tracker<Value_Type, Cmp>::~sliding_window_min_tracker()\r\n{\r\n\tDBG_ONLY(assert_valid();)\r\n}\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\nvoid sliding_window_min_tracker<Value_Type, Cmp>::\r\n\tpush(value_type v)\r\n{\r\n\tDBG_ONLY(assert_valid();)\r\n\r\n\tif (m_a_buf.size() > 0 && m_a_buf[0].second == m_ind)\r\n\t\tm_a_buf.pop_front();\r\n\r\n\twhile (m_a_buf.size() > 0 && !s_cmp(m_a_buf.back().first, v))\r\n\t\tm_a_buf.pop_back();\r\n\r\n\tm_a_buf.push_back(std::make_pair(\r\n\t\tv, \r\n\t\tstatic_cast<unsigned int>((m_ind++) + m_a_buf.capacity())));\r\n\r\n\tDBG_ONLY(assert_valid();)\r\n}\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\ninline typename sliding_window_min_tracker<Value_Type, Cmp>::value_type \r\n\tsliding_window_min_tracker<Value_Type, Cmp>::min() const\r\n{\r\n\tDBG_ONLY(assert_valid();)\r\n\r\n\treturn m_a_buf[0].first;\t\r\n}\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\ninline bool sliding_window_min_tracker<Value_Type, Cmp>::empty() const\r\n{\r\n\treturn m_a_buf.size() == 0;\r\n}\r\n\r\n#ifdef DBG_MODE\r\ntemplate<typename Value_Type, class Cmp>\r\nvoid sliding_window_min_tracker<Value_Type, Cmp>::assert_valid() const\r\n{\r\n\tif(m_a_buf.size() < 2)\r\n\t\treturn;\r\n\r\n\tfor(size_t i = 10; i < m_a_buf.size() - 1; ++i)\r\n\t\tDBG_ASSERT(!s_cmp(m_a_buf[i + 1].first, m_a_buf[i].first));\r\n}\r\n#endif // #ifdef DBG_MODE\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\nvoid sliding_window_min_tracker<Value_Type, Cmp>::trace(\r\n\tstd::ostream &r_os) const\r\n{\r\n\tfor (size_t i = 0; i < m_a_buf.size(); ++i)\r\n\t\tr_os << '(' << m_a_buf[i].first << \", \" <<\r\n\t\t\tm_a_buf[i].second << \") \";\r\n}\r\n\r\ntemplate<typename Value_Type, class Cmp>\r\ninline unsigned int \r\n\tsliding_window_min_tracker<Value_Type, Cmp>::\r\n\t\tcapacity() const\r\n{\r\n\treturn static_cast<unsigned int>(m_a_buf.capacity());\r\n}\r\n\r\n#endif // #ifndef WINDOW_MIN_HPP\r\n\r\n", "meta": {"hexsha": "b28ae429494773eda3d0b9475e944fbccb1cbc8a", "size": 3152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pypedream/window_min.hpp", "max_stars_repo_name": "garywu/pipedream", "max_stars_repo_head_hexsha": "d89a4031d5ee78c05c6845341607a59528f0bd75", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-02-21T04:13:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T20:05:47.000Z", "max_issues_repo_path": "pypedream/window_min.hpp", "max_issues_repo_name": "garywu/pipedream", "max_issues_repo_head_hexsha": "d89a4031d5ee78c05c6845341607a59528f0bd75", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-13T13:14:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-13T13:14:32.000Z", "max_forks_repo_path": "pypedream/window_min.hpp", "max_forks_repo_name": "garywu/pypedream", "max_forks_repo_head_hexsha": "d89a4031d5ee78c05c6845341607a59528f0bd75", "max_forks_repo_licenses": ["BSD-3-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.8405797101, "max_line_length": 75, "alphanum_fraction": 0.7071700508, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.07263671238329551, "lm_q1q2_score": 0.03236180069493282}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/**\n * @file keySwitching.cpp\n * @brief A few strategies for generating key-switching matrices\n *\n * Copyright IBM Corporation 2012 All rights reserved.\n */\n#include <unordered_set>\n#include <NTL/ZZ.h>\n#include <helib/permutations.h>\n\n#include <helib/binio.h>\n#include <helib/keySwitching.h>\n#include <helib/keys.h>\n#include <helib/apiAttributes.h>\n\nnamespace helib {\n\n/******************** KeySwitch implementation **********************/\n/********************************************************************/\n\nKeySwitch::KeySwitch(long sPow, long xPow, long fromID, long toID, long p) :\n    fromKey(sPow, xPow, fromID), toKeyID(toID), ptxtSpace(p)\n{}\n\nKeySwitch::KeySwitch(const SKHandle& _fromKey,\n                     UNUSED long fromID,\n                     long toID,\n                     long p) :\n    fromKey(_fromKey), toKeyID(toID), ptxtSpace(p)\n{}\n\nbool KeySwitch::operator==(const KeySwitch& other) const\n{\n  if (this == &other)\n    return true;\n\n  if (fromKey != other.fromKey)\n    return false;\n  if (toKeyID != other.toKeyID)\n    return false;\n  if (ptxtSpace != other.ptxtSpace)\n    return false;\n\n  if (prgSeed != other.prgSeed)\n    return false;\n\n  if (b.size() != other.b.size())\n    return false;\n  for (size_t i = 0; i < b.size(); i++)\n    if (b[i] != other.b[i])\n      return false;\n\n  return true;\n}\nbool KeySwitch::operator!=(const KeySwitch& other) const\n{\n  return !(*this == other);\n}\n\nunsigned long KeySwitch::NumCols() const { return b.size(); }\n\nbool KeySwitch::isDummy() const { return (toKeyID == -1); }\n\nvoid KeySwitch::verify(SecKey& sk)\n{\n  long fromSPower = fromKey.getPowerOfS();\n  long fromXPower = fromKey.getPowerOfX();\n  long fromIdx = fromKey.getSecretKeyID();\n  long toIdx = toKeyID;\n  long p = ptxtSpace;\n  long n = b.size();\n\n  std::cout << \"KeySwitch::verify\\n\";\n  std::cout << \"fromS = \" << fromSPower << \" fromX = \" << fromXPower\n            << \" fromIdx = \" << fromIdx << \" toIdx = \" << toIdx << \" p = \" << p\n            << \" n = \" << n << \"\\n\";\n\n  if (fromSPower != 1 || fromXPower != 1 || (fromIdx == toIdx) || n == 0) {\n    std::cout << \"KeySwitch::verify: these parameters not checkable\\n\";\n    return;\n  }\n\n  const Context& context = b[0].getContext();\n\n  // we don't store the context in the ks matrix, so let's\n  // check that they are consistent\n\n  for (long i = 0; i < n; i++) {\n    if (&context != &(b[i].getContext()))\n      std::cout << \"KeySwitch::verify: bad context \" << i << \"\\n\";\n  }\n\n  std::cout << \"context.ctxtPrimes = \" << context.ctxtPrimes << \"\\n\";\n  std::cout << \"context.specialPrimes = \" << context.specialPrimes << \"\\n\";\n  IndexSet fullPrimes = context.fullPrimes(); // ctxtPrimes | specialPrimes;\n\n  std::cout << \"digits: \";\n  for (long i = 0; i < n; i++)\n    std::cout << context.digits[i] << \" \";\n  std::cout << \"\\n\";\n\n  std::cout << \"IndexSets of b: \";\n  for (long i = 0; i < n; i++)\n    std::cout << b[i].getMap().getIndexSet() << \" \";\n  std::cout << \"\\n\";\n\n  // VJS: suspicious shadowing of fromKey, toKey\n  const DoubleCRT& _fromKey = sk.sKeys.at(fromIdx);\n  const DoubleCRT& _toKey = sk.sKeys.at(toIdx);\n\n  std::cout << \"IndexSet of fromKey: \" << _fromKey.getMap().getIndexSet()\n            << \"\\n\";\n  std::cout << \"IndexSet of toKey: \" << _toKey.getMap().getIndexSet() << \"\\n\";\n\n  std::vector<DoubleCRT> a;\n  a.resize(n, DoubleCRT(context, fullPrimes)); // defined modulo all primes\n\n  {\n    RandomState state;\n\n    SetSeed(prgSeed);\n    for (long i = 0; i < n; i++)\n      a[i].randomize();\n\n  } // the RandomState destructor \"restores the state\" (see NumbTh.h)\n\n  std::vector<NTL::ZZX> A, B;\n\n  A.resize(n);\n  B.resize(n);\n\n  for (long i = 0; i < n; i++) {\n    a[i].toPoly(A[i]);\n    b[i].toPoly(B[i]);\n  }\n\n  NTL::ZZX FromKey, ToKey;\n  _fromKey.toPoly(FromKey, fullPrimes);\n  _toKey.toPoly(ToKey, fullPrimes);\n\n  NTL::ZZ Q = context.productOfPrimes(fullPrimes);\n  NTL::ZZ prod = context.productOfPrimes(context.specialPrimes);\n  NTL::ZZX C, D;\n  NTL::ZZX PhimX = context.zMStar.getPhimX();\n\n  long nb = 0;\n  for (long i = 0; i < n; i++) {\n    C = (B[i] - FromKey * prod + ToKey * A[i]) % PhimX;\n    PolyRed(C, Q);\n    if (!divide(D, C, p)) {\n      std::cout << \"*** not divisible by p at \" << i << \"\\n\";\n    } else {\n      for (long j = 0; j <= deg(D); j++)\n        if (NumBits(coeff(D, j)) > nb)\n          nb = NumBits(coeff(D, j));\n    }\n    prod *= context.productOfPrimes(context.digits[i]);\n  }\n\n  std::cout << \"error ratio: \" << ((double)nb) / ((double)NumBits(Q)) << \"\\n\";\n}\n\nconst KeySwitch& KeySwitch::dummy()\n{\n  static const KeySwitch dummy(-1, -1, -1, -1);\n  return dummy;\n}\n\nstd::ostream& operator<<(std::ostream& str, const KeySwitch& matrix)\n{\n  str << \"[\" << matrix.fromKey << \" \" << matrix.toKeyID << \" \"\n      << matrix.ptxtSpace << \" \" << matrix.b.size() << std::endl;\n  for (long i = 0; i < (long)matrix.b.size(); i++)\n    str << matrix.b[i] << std::endl;\n  str << matrix.prgSeed << \" \" << matrix.noiseBound << \"]\";\n  return str;\n}\n\n// Used in lieu of std::istream& operator>>(std::istream& str, KeySwitch&\n// matrix)\nvoid KeySwitch::readMatrix(std::istream& str, const Context& context)\n{\n  seekPastChar(str, '['); // defined in NumbTh.cpp\n  str >> fromKey;\n  str >> toKeyID;\n  str >> ptxtSpace;\n\n  long nDigits;\n  str >> nDigits;\n  b.resize(nDigits, DoubleCRT(context, IndexSet::emptySet()));\n  for (long i = 0; i < nDigits; i++)\n    str >> b[i];\n  str >> prgSeed;\n  str >> noiseBound;\n  seekPastChar(str, ']');\n}\n\nvoid KeySwitch::write(std::ostream& str) const\n{\n  writeEyeCatcher(str, BINIO_EYE_SKM_BEGIN);\n  /*\n      Write out raw\n      1. SKHandle fromKey;\n      2. long     toKeyID;\n      3. long     ptxtSpace;\n      4. vector<DoubleCRT> b;\n      5. ZZ prgSeed;\n      6. xdouble noiseBound;\n  */\n\n  fromKey.write(str);\n  write_raw_int(str, toKeyID);\n  write_raw_int(str, ptxtSpace);\n\n  write_raw_vector(str, b);\n\n  write_raw_ZZ(str, prgSeed);\n  write_raw_xdouble(str, noiseBound);\n\n  writeEyeCatcher(str, BINIO_EYE_SKM_END);\n}\n\nvoid KeySwitch::read(std::istream& str, const Context& context)\n{\n  int eyeCatcherFound = readEyeCatcher(str, BINIO_EYE_SKM_BEGIN);\n  assertEq(eyeCatcherFound, 0, \"Could not find pre-secret key eyecatcher\");\n\n  fromKey.read(str);\n  toKeyID = read_raw_int(str);\n  ptxtSpace = read_raw_int(str);\n  DoubleCRT blankDCRT(context, IndexSet::emptySet());\n  read_raw_vector(str, b, blankDCRT);\n  read_raw_ZZ(str, prgSeed);\n  noiseBound = read_raw_xdouble(str);\n\n  eyeCatcherFound = readEyeCatcher(str, BINIO_EYE_SKM_END);\n  assertEq(eyeCatcherFound, 0, \"Could not find post-secret key eyecatcher\");\n}\n\nlong KSGiantStepSize(long D)\n{\n  assertTrue<InvalidArgument>(D > 0l, \"Step size must be positive\");\n  long g = NTL::SqrRoot(D);\n  if (g * g < D)\n    g++; // g = ceiling(sqrt(D))\n  return g;\n}\n\n// A maximalistic approach: generate matrices s(X^e)->s(X) for all e \\in Zm*\nvoid addAllMatrices(SecKey& sKey, long keyID)\n{\n  const Context& context = sKey.getContext();\n  long m = context.zMStar.getM();\n\n  // key-switching matrices for the automorphisms\n  for (long i = 0; i < m; i++) {\n    if (!context.zMStar.inZmStar(i))\n      continue;\n    sKey.GenKeySWmatrix(1, i, keyID, keyID);\n  }\n  sKey.setKeySwitchMap(); // re-compute the key-switching map\n}\n\n// TODO: generate matrices s.t. you can reLinearize each s(X^e) in at most two\n// steps void addFewMatrices(SecKey& sKey, long keyID)\n// {\n//   throw LogicError(\"addFewMatrices not implemented yet\");\n// }\n\n// This code block appears at least twice below\n#define computeParams(context, m, i)                                           \\\n  bool native;                                                                 \\\n  long ord, gi, g2md;                                                          \\\n  NTL::mulmod_precon_t g2mdminv;                                               \\\n  if (i == context.zMStar.numOfGens()) { /* Frobenius matrices */              \\\n    ord = context.zMStar.getOrdP();                                            \\\n    gi = context.zMStar.getP();                                                \\\n    native = true;                                                             \\\n  } else { /* one of the \"regular\" dimensions */                               \\\n    ord = context.zMStar.OrderOf(i);                                           \\\n    gi = context.zMStar.ZmStarGen(i);                                          \\\n    native = context.zMStar.SameOrd(i);                                        \\\n    if (!native) {                                                             \\\n      g2md = PowerMod(gi, -ord, m); /* g^{-ord} mod m */                       \\\n      g2mdminv = PrepMulModPrecon(g2md, m);                                    \\\n    }                                                                          \\\n  }                                                                            \\\n  NTL::mulmod_precon_t giminv = PrepMulModPrecon(gi, m);\n\n#if 0\nstatic void add1Dmats4dim(SecKey& sKey, long i, long keyID)\n{\n  const Context &context = sKey.getContext();\n  long m = context.zMStar.getM();\n  computeParams(context,m,i); // defines vars: native, ord, gi, g2md, giminv, g2mdminv\n\n  /* MAUTO std::vector<long> vals; */\n  for (long j=1,val=gi; j < ord; j++) {\n    // From s(X^val) to s(X)\n    sKey.GenKeySWmatrix(1, val, keyID, keyID);\n    if (!native) { // also from s(X^{g^{i-ord}}) to s(X)\n      long val2 = MulModPrecon(val,g2md,m,g2mdminv);\n      sKey.GenKeySWmatrix(1, val2, keyID, keyID);\n      /* MAUTO vals.push_back(val2); */\n    }\n    /* MAUTO vals.push_back(val); */\n    val = MulModPrecon(val, gi, m, giminv); // val *= g mod m (= g^{j+1})\n  }\n\n  if (!native) {\n    sKey.GenKeySWmatrix(1, context.zMStar.genToPow(i, -ord), keyID, keyID);\n  }\n\n\n/* MAUTO\n  sKey.resetTree(i,keyID); // remove existing tree, if any\n  sKey.add2tree(i, 1, vals, keyID);\n*/\n}\n#else\n// adds all matrices for dim i.\n// i == -1 => Frobenius (NOTE: in matmul1D, i ==#gens means something else,\n//   so it is best to avoid that).\nstatic void add1Dmats4dim(SecKey& sKey, long i, long keyID)\n{\n  const PAlgebra& zMStar = sKey.getContext().zMStar;\n  long ord;\n  bool native;\n\n  if (i != -1) {\n    ord = zMStar.OrderOf(i);\n    native = zMStar.SameOrd(i);\n  } else {\n    // Frobenius\n    ord = zMStar.getOrdP();\n    native = true;\n  }\n\n  for (long j = 1; j < ord; j++)\n    sKey.GenKeySWmatrix(1, zMStar.genToPow(i, j), keyID, keyID);\n\n  if (!native)\n    sKey.GenKeySWmatrix(1, zMStar.genToPow(i, -ord), keyID, keyID);\n\n  sKey.setKSStrategy(i, HELIB_KSS_FULL);\n}\n\n#endif\n\n#if 0\nstatic std::pair<long,long> computeSteps(long ord, long bound, bool native)\n{\n  long baby,giant;\n  if (native) { // using giant+baby matrices\n    if (bound*bound >= 4*ord)\n      giant = ceil((bound - sqrt((double)bound*bound -4*ord))/2.0);\n    else\n      giant = sqrt((double)ord);\n  }\n  else { // using giant+2*baby matrices\n    if (bound*bound >= 8*ord)\n      giant = ceil((bound - sqrt((double)bound*bound -8*ord))/2.0);\n    else\n      giant = sqrt((double)ord);\n  }\n  baby = ord/giant;\n  if (baby*giant<ord) baby++;\n\n  //std::cerr << \"*** giant steps = \" << giant << \"\\n\";\n  return std::pair<long,long>(baby,giant);\n}\n\nstatic void addSome1Dmats4dim(SecKey& sKey, long i, long bound, long keyID)\n{\n  const Context &context = sKey.getContext();\n  long m = context.zMStar.getM();\n  computeParams(context,m,i); // defines vars: native, ord, gi, g2md, giminv, g2mdminv\n\n  long baby, giant;\n  std::tie(baby,giant) = computeSteps(ord, bound, native);\n\n  for (long j=1,val=gi; j<=baby; j++) { // Add matrices for baby steps\n    sKey.GenKeySWmatrix(1, val, keyID, keyID);\n    if (!native) {\n      long val2 = MulModPrecon(val,g2md,m,g2mdminv);\n      sKey.GenKeySWmatrix(1, val2, keyID, keyID);\n    }\n    val = MulModPrecon(val, gi, m, giminv); // val *= g mod m (= g^{j+1})\n   }\n\n  long gb = PowerMod(gi,baby,m); // g^baby\n  NTL::mulmod_precon_t gbminv = PrepMulModPrecon(gb, m);\n  for (long j=2,val=gb; j < giant; j++) { // Add matrices for giant steps\n    val = MulModPrecon(val, gb, m, gbminv); // val = g^{(j+1)*baby}\n    sKey.GenKeySWmatrix(1, val, keyID, keyID);\n  }\n\n  if (!native) {\n    sKey.GenKeySWmatrix(1, context.zMStar.genToPow(i, -ord), keyID, keyID);\n  }\n\n  // VJS: experimantal feature...because the replication code\n  // uses rotations by -1, -2, -4, -8, we add a few\n  // of these as well...only the small ones are important,\n  // and we only need them if SameOrd(i)...\n  // Note: we do indeed get a nontrivial speed-up\n\n  if (native && i<context.zMStar.numOfGens()) {\n    for (long k = 1; k < giant; k = 2*k) {\n      long j = ord - k;\n      long val = PowerMod(gi, j, m); // val = g^j\n      sKey.GenKeySWmatrix(1, val, keyID, keyID);\n    }\n  }\n\n#if 0\nMAUTO\n\n  // build the tree for this dimension, the internal nodes are 1 and\n  // (subset of) gi^{giant}, gi^{2*giant}, ..., gi^{baby*giant}. We\n\n  MAUTO sKey.resetTree(i,keyID); // remove existing tree, if any\n\n  // keep a list of all the elements that are covered by the tree so far,\n  // initialized to only the root (=1).\n  std::unordered_set<long> covered({1});\n\n  // Make a list of the automorphisms for this dimension\n  std::vector<long> autos;\n  for (long j=1,val=gi; j<ord; j++) {\n    // Do we have matrices for val and/or val/gi^{di}?\n    if (!native) {\n      long val2 = MulModPrecon(val, g2md, m, g2mdminv);\n      if (sKey.haveKeySWmatrix(1,val2,keyID,keyID)) {\n        autos.push_back(val2);\n      }\n    }\n    if (sKey.haveKeySWmatrix(1,val,keyID,keyID)) {\n      autos.push_back(val);\n    }\n    val = MulModPrecon(val, gi, m, giminv); // g^{j+1}\n  }\n\n  // Insert internal nodes and their children to tree\n  for (long j=0,fromVal=1; j<giant; j++) {\n    NTL::mulmod_precon_t fromminv = PrepMulModPrecon(fromVal, m);\n    std::vector<long> children;\n    for (long k: autos) {\n      long toVal = MulModPrecon(k, fromVal, m, fromminv);\n      if (covered.count(toVal)==0) { // toVal not covered yet\n        covered.insert(toVal);\n        children.push_back(toVal);\n      }\n    }\n    if (!children.empty()) { // insert fromVal with its children\n      sKey.add2tree(i, fromVal, children, keyID);\n    }\n    fromVal = MulModPrecon(fromVal, gb, m, gbminv); // g^{(j+1)*baby}\n  }\n\n  // Sanity-check, did we cover everything?\n  long toCover = native? ord: (2*ord-1);\n  if (covered.size()<toCover)\n    std::cerr << \"**Warning: order-\"<<ord<<\" dimension, covered \"<<covered.size()\n         << \" of \"<<toCover<<std::endl;\n#endif\n}\n\n#else\n// same as above, but uses BS/GS strategy\nstatic void addSome1Dmats4dim(SecKey& sKey,\n                              long i,\n                              UNUSED long bound,\n                              long keyID)\n{\n  const PAlgebra& zMStar = sKey.getContext().zMStar;\n  long ord;\n  bool native;\n\n  if (i != -1) {\n    ord = zMStar.OrderOf(i);\n    native = zMStar.SameOrd(i);\n  } else {\n    // Frobenius\n    ord = zMStar.getOrdP();\n    native = true;\n  }\n\n  long g = KSGiantStepSize(ord);\n\n  // baby steps\n  for (long j = 1; j < g; j++)\n    sKey.GenKeySWmatrix(1, zMStar.genToPow(i, j), keyID, keyID);\n\n  // giant steps\n  for (long j = g; j < ord; j += g)\n    sKey.GenKeySWmatrix(1, zMStar.genToPow(i, j), keyID, keyID);\n\n  if (!native)\n    sKey.GenKeySWmatrix(1, zMStar.genToPow(i, -ord), keyID, keyID);\n\n  sKey.setKSStrategy(i, HELIB_KSS_BSGS);\n\n  // NOTE: the old code also added matrices for ord-2^k for small k,\n  // in the case of (native && i<context.zMStar.numOfGens()).\n  // This supposedly speeds up the replication code, but for now\n  // we are leaving this out, for simplicity.   Also, it is a waste\n  // of space for applications that don't use replication.\n}\n\n#endif\n\n// generate only matrices of the form s(X^{g^i})->s(X), but not all of them.\n// For a generator g whose order is larger than bound, generate only enough\n// matrices for the giant-step/baby-step procedures (2*sqrt(ord(g))of them).\nvoid addSome1DMatrices(SecKey& sKey, long bound, long keyID)\n{\n  const Context& context = sKey.getContext();\n\n  // key-switching matrices for the automorphisms\n  for (long i : range(context.zMStar.numOfGens())) {\n    // For generators of small order, add all the powers\n    if (bound >= context.zMStar.OrderOf(i))\n      add1Dmats4dim(sKey, i, keyID);\n    else // For generators of large order, add only some of the powers\n      addSome1Dmats4dim(sKey, i, bound, keyID);\n  }\n  sKey.setKeySwitchMap(); // re-compute the key-switching map\n}\n\nvoid add1DMatrices(SecKey& sKey, long keyID)\n{\n  addSome1DMatrices(sKey, LONG_MAX, keyID);\n}\n\nvoid addBSGS1DMatrices(SecKey& sKey, long keyID)\n{\n  addSome1DMatrices(sKey, 0, keyID);\n}\n\n// Generate all Frobenius matrices of the form s(X^{p^i})->s(X)\nvoid addSomeFrbMatrices(SecKey& sKey, long bound, long keyID)\n{\n  const Context& context = sKey.getContext();\n  if (bound >= LONG(context.zMStar.getOrdP()))\n    add1Dmats4dim(sKey, -1, keyID);\n  else // For generators of large order, add only some of the powers\n    addSome1Dmats4dim(sKey, -1, bound, keyID);\n\n  sKey.setKeySwitchMap(); // re-compute the key-switching map\n}\n\nvoid addFrbMatrices(SecKey& sKey, long keyID)\n{\n  addSomeFrbMatrices(sKey, LONG_MAX, keyID);\n}\n\nvoid addBSGSFrbMatrices(SecKey& sKey, long keyID)\n{\n  addSomeFrbMatrices(sKey, 0, keyID);\n}\n\nstatic void addMinimal1Dmats4dim(SecKey& sKey, long i, long keyID)\n{\n  const PAlgebra& zMStar = sKey.getContext().zMStar;\n  long ord;\n  bool native;\n\n  if (i != -1) {\n    ord = zMStar.OrderOf(i);\n    native = zMStar.SameOrd(i);\n  } else {\n    // Frobenius\n    ord = zMStar.getOrdP();\n    native = true;\n  }\n\n  sKey.GenKeySWmatrix(1, zMStar.genToPow(i, 1), keyID, keyID);\n\n  if (!native)\n    sKey.GenKeySWmatrix(1, zMStar.genToPow(i, -ord), keyID, keyID);\n\n  if (ord > HELIB_KEYSWITCH_MIN_THRESH) {\n    long g = KSGiantStepSize(ord);\n    sKey.GenKeySWmatrix(1, zMStar.genToPow(i, g), keyID, keyID);\n  }\n\n  sKey.setKSStrategy(i, HELIB_KSS_MIN);\n}\n\nvoid addMinimal1DMatrices(SecKey& sKey, long keyID)\n{\n  const Context& context = sKey.getContext();\n\n  // key-switching matrices for the automorphisms\n  for (long i : range(context.zMStar.numOfGens())) {\n    addMinimal1Dmats4dim(sKey, i, keyID);\n  }\n  sKey.setKeySwitchMap(); // re-compute the key-switching map\n}\n\n// Generate all Frobenius matrices of the form s(X^{p^i})->s(X)\nvoid addMinimalFrbMatrices(SecKey& sKey, long keyID)\n{\n  addMinimal1Dmats4dim(sKey, -1, keyID);\n  sKey.setKeySwitchMap(); // re-compute the key-switching map\n}\n\n// Generate all key-switching matrices for a given permutation network\nvoid addMatrices4Network(SecKey& sKey, const PermNetwork& net, long keyID)\n{\n  const Context& context = sKey.getContext();\n  long m = context.zMStar.getM();\n\n  for (long i = 0; i < net.depth(); i++) {\n    long e = net.getLayer(i).getE();\n    long gIdx = net.getLayer(i).getGenIdx();\n    long g = context.zMStar.ZmStarGen(gIdx);\n    long g2e = NTL::PowerMod(g, e, m); // g^e mod m\n    const NTL::Vec<long>& shamts = net.getLayer(i).getShifts();\n    for (long j = 0; j < shamts.length(); j++) {\n      if (shamts[j] == 0)\n        continue;\n      long val = NTL::PowerMod(g2e, shamts[j], m);\n      sKey.GenKeySWmatrix(1, val, keyID, keyID);\n    }\n  }\n  sKey.setKeySwitchMap(); // re-compute the key-switching map\n}\n\nvoid addTheseMatrices(SecKey& sKey, const std::set<long>& automVals, long keyID)\n{\n  std::set<long>::iterator it;\n  for (it = automVals.begin(); it != automVals.end(); ++it) {\n    long k = *it;\n    sKey.GenKeySWmatrix(1, k, keyID, keyID);\n  }\n  sKey.setKeySwitchMap(); // re-compute the key-switching map\n}\n\n} // namespace helib\n", "meta": {"hexsha": "9c4491f879c405d44154fc84e1d462359d949dd2", "size": 20082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/keySwitching.cpp", "max_stars_repo_name": "TomMD/HElib", "max_stars_repo_head_hexsha": "78e3bae2df5776a0261e357ab52d27ad281f0ced", "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/keySwitching.cpp", "max_issues_repo_name": "TomMD/HElib", "max_issues_repo_head_hexsha": "78e3bae2df5776a0261e357ab52d27ad281f0ced", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/keySwitching.cpp", "max_forks_repo_name": "TomMD/HElib", "max_forks_repo_head_hexsha": "78e3bae2df5776a0261e357ab52d27ad281f0ced", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-26T12:06:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-26T12:06:42.000Z", "avg_line_length": 30.7534456355, "max_line_length": 86, "alphanum_fraction": 0.6047206454, "num_tokens": 6152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.06656919452604805, "lm_q1q2_score": 0.03224479205477812}}
{"text": "//[ MapAssign\n//  Copyright 2008 Eric Niebler. 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// This is a port of map_list_of() from the Boost.Assign library.\n// It has the advantage of being more efficient at runtime by not\n// building any temporary container that requires dynamic allocation.\n\n#include <map>\n#include <string>\n#include <iostream>\n#include <boost/proto/core.hpp>\n#include <boost/proto/transform.hpp>\n#include <boost/type_traits/add_reference.hpp>\nnamespace proto = boost::proto;\nusing proto::_;\n\nstruct map_list_of_tag\n{};\n\n// A simple callable function object that inserts a\n// (key,value) pair into a map.\nstruct insert\n  : proto::callable\n{\n    template<typename Sig>\n    struct result;\n\n    template<typename This, typename Map, typename Key, typename Value>\n    struct result<This(Map, Key, Value)>\n      : boost::add_reference<Map>\n    {};\n\n    template<typename Map, typename Key, typename Value>\n    Map &operator()(Map &map, Key const &key, Value const &value) const\n    {\n        map.insert(typename Map::value_type(key, value));\n        return map;\n    }\n};\n\n// The grammar for valid map-list expressions, and a\n// transform that populates the map.\nstruct MapListOf\n  : proto::or_<\n        proto::when<\n            proto::function<\n                proto::terminal<map_list_of_tag>\n              , proto::terminal<_>\n              , proto::terminal<_>\n            >\n          , insert(\n                proto::_data\n              , proto::_value(proto::_child1)\n              , proto::_value(proto::_child2)\n            )\n        >\n      , proto::when<\n            proto::function<\n                MapListOf\n              , proto::terminal<_>\n              , proto::terminal<_>\n            >\n          , insert(\n                MapListOf(proto::_child0)\n              , proto::_value(proto::_child1)\n              , proto::_value(proto::_child2)\n            )\n        >\n    >\n{};\n\ntemplate<typename Expr>\nstruct map_list_of_expr;\n\nstruct map_list_of_dom\n  : proto::domain<proto::pod_generator<map_list_of_expr>, MapListOf>\n{};\n\n// An expression wrapper that provides a conversion to a\n// map that uses the MapListOf\ntemplate<typename Expr>\nstruct map_list_of_expr\n{\n    BOOST_PROTO_BASIC_EXTENDS(Expr, map_list_of_expr, map_list_of_dom)\n    BOOST_PROTO_EXTENDS_FUNCTION()\n\n    template<typename Key, typename Value, typename Cmp, typename Al>\n    operator std::map<Key, Value, Cmp, Al> () const\n    {\n        BOOST_MPL_ASSERT((proto::matches<Expr, MapListOf>));\n        std::map<Key, Value, Cmp, Al> map;\n        return MapListOf()(*this, 0, map);\n    }\n};\n\nmap_list_of_expr<proto::terminal<map_list_of_tag>::type> const map_list_of = {{{}}};\n\nint main()\n{\n    // Initialize a map:\n    std::map<std::string, int> op =\n        map_list_of\n            (\"<\", 1)\n            (\"<=\",2)\n            (\">\", 3)\n            (\">=\",4)\n            (\"=\", 5)\n            (\"<>\",6)\n        ;\n\n    std::cout << \"\\\"<\\\"  --> \" << op[\"<\"] << std::endl;\n    std::cout << \"\\\"<=\\\" --> \" << op[\"<=\"] << std::endl;\n    std::cout << \"\\\">\\\"  --> \" << op[\">\"] << std::endl;\n    std::cout << \"\\\">=\\\" --> \" << op[\">=\"] << std::endl;\n    std::cout << \"\\\"=\\\"  --> \" << op[\"=\"] << std::endl;\n    std::cout << \"\\\"<>\\\" --> \" << op[\"<>\"] << std::endl;\n\n    return 0;\n}\n//]\n\n", "meta": {"hexsha": "f5a2f71a813a8a53691fac6d63026665c092453a", "size": 3375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/proto/example/map_assign.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T10:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-08T10:44:28.000Z", "max_issues_repo_path": "libs/proto/example/map_assign.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/proto/example/map_assign.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 27.2177419355, "max_line_length": 84, "alphanum_fraction": 0.570962963, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101676450173534, "lm_q2_score": 0.06954173727440403, "lm_q1q2_score": 0.032059906716075476}}
{"text": "//  (C) Copyright John Maddock 2005-2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_TOOLS_SERIES_INCLUDED\r\n#define BOOST_MATH_TOOLS_SERIES_INCLUDED\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/config/no_tr1/cmath.hpp>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/math/tools/config.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace tools{\r\n\r\n//\r\n// Simple series summation come first:\r\n//\r\ntemplate <class Functor, class U, class V>\r\ninline typename Functor::result_type sum_series(Functor& func, const U& factor, boost::uintmax_t& max_terms, const V& init_value) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   typedef typename Functor::result_type result_type;\r\n\r\n   boost::uintmax_t counter = max_terms;\r\n\r\n   result_type result = init_value;\r\n   result_type next_term;\r\n   do{\r\n      next_term = func();\r\n      result += next_term;\r\n   }\r\n   while((fabs(factor * result) < fabs(next_term)) && --counter);\r\n\r\n   // set max_terms to the actual number of terms of the series evaluated:\r\n   max_terms = max_terms - counter;\r\n\r\n   return result;\r\n}\r\n\r\ntemplate <class Functor, class U>\r\ninline typename Functor::result_type sum_series(Functor& func, const U& factor, boost::uintmax_t& max_terms) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   typename Functor::result_type init_value = 0;\r\n   return sum_series(func, factor, max_terms, init_value);\r\n}\r\n\r\ntemplate <class Functor, class U>\r\ninline typename Functor::result_type sum_series(Functor& func, int bits, boost::uintmax_t& max_terms, const U& init_value) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   BOOST_MATH_STD_USING\r\n   typedef typename Functor::result_type result_type;\r\n   result_type factor = ldexp(result_type(1), 1 - bits);\r\n   return sum_series(func, factor, max_terms, init_value);\r\n}\r\n\r\ntemplate <class Functor>\r\ninline typename Functor::result_type sum_series(Functor& func, int bits) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   BOOST_MATH_STD_USING\r\n   typedef typename Functor::result_type result_type;\r\n   boost::uintmax_t iters = (std::numeric_limits<boost::uintmax_t>::max)();\r\n   result_type init_val = 0;\r\n   return sum_series(func, bits, iters, init_val);\r\n}\r\n\r\ntemplate <class Functor>\r\ninline typename Functor::result_type sum_series(Functor& func, int bits, boost::uintmax_t& max_terms) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   BOOST_MATH_STD_USING\r\n   typedef typename Functor::result_type result_type;\r\n   result_type init_val = 0;\r\n   return sum_series(func, bits, max_terms, init_val);\r\n}\r\n\r\ntemplate <class Functor, class U>\r\ninline typename Functor::result_type sum_series(Functor& func, int bits, const U& init_value) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   BOOST_MATH_STD_USING\r\n   boost::uintmax_t iters = (std::numeric_limits<boost::uintmax_t>::max)();\r\n   return sum_series(func, bits, iters, init_value);\r\n}\r\n\r\n//\r\n// Algorithm kahan_sum_series invokes Functor func until the N'th\r\n// term is too small to have any effect on the total, the terms\r\n// are added using the Kahan summation method.\r\n//\r\n// CAUTION: Optimizing compilers combined with extended-precision\r\n// machine registers conspire to render this algorithm partly broken:\r\n// double rounding of intermediate terms (first to a long double machine\r\n// register, and then to a double result) cause the rounding error computed\r\n// by the algorithm to be off by up to 1ulp.  However this occurs rarely, and\r\n// in any case the result is still much better than a naive summation.\r\n//\r\ntemplate <class Functor>\r\ninline typename Functor::result_type kahan_sum_series(Functor& func, int bits) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   typedef typename Functor::result_type result_type;\r\n\r\n   result_type factor = pow(result_type(2), bits);\r\n   result_type result = func();\r\n   result_type next_term, y, t;\r\n   result_type carry = 0;\r\n   do{\r\n      next_term = func();\r\n      y = next_term - carry;\r\n      t = result + y;\r\n      carry = t - result;\r\n      carry -= y;\r\n      result = t;\r\n   }\r\n   while(fabs(result) < fabs(factor * next_term));\r\n   return result;\r\n}\r\n\r\ntemplate <class Functor>\r\ninline typename Functor::result_type kahan_sum_series(Functor& func, int bits, boost::uintmax_t& max_terms) BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(typename Functor::result_type) && noexcept(std::declval<Functor>()()))\r\n{\r\n   BOOST_MATH_STD_USING\r\n\r\n   typedef typename Functor::result_type result_type;\r\n\r\n   boost::uintmax_t counter = max_terms;\r\n\r\n   result_type factor = ldexp(result_type(1), bits);\r\n   result_type result = func();\r\n   result_type next_term, y, t;\r\n   result_type carry = 0;\r\n   do{\r\n      next_term = func();\r\n      y = next_term - carry;\r\n      t = result + y;\r\n      carry = t - result;\r\n      carry -= y;\r\n      result = t;\r\n   }\r\n   while((fabs(result) < fabs(factor * next_term)) && --counter);\r\n\r\n   // set max_terms to the actual number of terms of the series evaluated:\r\n   max_terms = max_terms - counter;\r\n\r\n   return result;\r\n}\r\n\r\n} // namespace tools\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_TOOLS_SERIES_INCLUDED\r\n\r\n", "meta": {"hexsha": "4b17993b5552ba6ec37b72e109ddd5314a09a722", "size": 5799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/tools/series.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/math/tools/series.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/math/tools/series.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 36.4716981132, "max_line_length": 239, "alphanum_fraction": 0.7178823935, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.06754669020109236, "lm_q1q2_score": 0.03192820435845566}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2013 - 2016.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n/*!\r\n  \\file\r\n\r\n \\brief This file is a partial reference implementation for the proposed\r\n \"C++ binary fixed-point arithmetic\" as specified in N3352.\\n\r\n\r\n \\sa http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3352.html \\n\r\n\r\n In this file, we include subsidiary files that implement the\r\n proposed specified fixed-point types,\r\n and explain macros that may be optionally defined.\r\n\r\n \\details\r\n   There is optional support for certain variations of fixed_point\r\n   using preprocessor definitions. Not all of these are supported\r\n   at the moment. The potential options include:\r\n\r\n   Is supported now  : \\#define BOOST_FIXED_POINT_DISABLE_IOSTREAM\\n\r\n   Is supported now  : \\#define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\\n\r\n   Not yet supported : \\#define BOOST_FIXED_POINT_DISABLE_WIDE_INTEGER_MATH\\n\r\n   Not yet supported : \\#define BOOST_FIXED_POINT_DISABLE_CPP11\\n\r\n   Is now supported  : \\#define BOOST_FIXED_POINT_ENABLE_GMP_BACKENDS\\n\r\n*/\r\n\r\n#ifndef FIXED_POINT_2015_03_06_HPP_\r\n  #define FIXED_POINT_2015_03_06_HPP_\r\n\r\n  #ifdef BOOST_DOXYGEN_GENERATION\r\n    // These items below document the function of optional macros,\r\n    // but are processed only if the doxyfile or jamfile contains\r\n    // <doxygen:param>PREDEFINED=BOOST_DOXYGEN_GENERATION\r\n\r\n    /*! \\def BOOST_FIXED_POINT_DISABLE_IOSTREAM\r\n    \\brief All I/O streaming is disabled, as is the inclusion of associated standard\r\n    library headers. This option eliminates all I/O stream overhead,\r\n    in particular for bare-metal microcontroller projects.\r\n    Disabling I/O streaming requires simultaneous disabling of multiprecision,\r\n    as shown below.\r\n    */\r\n    #define BOOST_FIXED_POINT_DISABLE_IOSTREAM\r\n\r\n    /*! \\def BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\r\n    \\brief This option is defined to disable the use of\r\n    Boost.Multiprecision for back-ends of the fixed-point classes.\r\n    Multiprecision fixed-point numbers are not available if this\r\n    option is set.\r\n    (Implemented).\r\n    */\r\n    #define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\r\n\r\n    /*! \\def BOOST_FIXED_POINT_DISABLE_WIDE_INTEGER_MATH\r\n    \\brief This option is defined to avoid using the unsigned_large_type in the\r\n    implementations of multiplication and division operations.\r\n    This option is intended for systems with limited integer widths\r\n    such as bare-metal microcontrollers.\r\n    When used in combination with BOOST_FIXED_POINT_DISABLE_MULTIPRECISION,\r\n    this option is intended to provide fixed-point representations\r\n    with up to 64-bits (if 64-bit integer types are available)\r\n    without requiring any multiprecision.\r\n    (Not yet implemented).\r\n    */\r\n    #define BOOST_FIXED_POINT_DISABLE_WIDE_INTEGER_MATH\r\n\r\n    /*! \\def BOOST_FIXED_POINT_DISABLE_CPP11\r\n    \\brief This option enables support for a back-port to C++03.\r\n    This option eliminates the use of all native C++11 language elements. This might send the\r\n    wrong message about language technology, but could\r\n    increase the range of potential target compilers, especially for embedded systems.\r\n    (Implemented but not yet fully tested).\r\n    */\r\n    #define BOOST_FIXED_POINT_DISABLE_CPP11\r\n\r\n    /*! \\def BOOST_FIXED_POINT_ENABLE_GMP_BACKENDS\r\n    \\brief When this option is defined, fixed-point uses multiple-precision backends\r\n    (when required) based on GMP instead of Boost.Multiprecision's self-written\r\n    binary floating-point backend.\r\n    GMP backends use highly optimized assembler and advanced\r\n    multiplication algorithms that are significantly faster for high digit counts\r\n    in excess of a few hundred binary digits.\r\n    \\sa https://gmplib.org\r\n    (Implemented but not yet fully tested).\r\n    */\r\n    #define BOOST_FIXED_POINT_ENABLE_GMP_BACKENDS\r\n\r\n  #endif // BOOST_DOXYGEN_GENERATION\r\n\r\n  #include <boost/fixed_point/fixed_point_negatable.hpp>\r\n\r\n#endif // FIXED_POINT_2015_03_06_HPP_\r\n", "meta": {"hexsha": "4a6fecf4d85e7ce93ad9214bff64ffd04f553413", "size": 4240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/fixed_point/fixed_point.hpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/fixed_point/fixed_point.hpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/fixed_point/fixed_point.hpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2653061224, "max_line_length": 94, "alphanum_fraction": 0.7400943396, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.07477003826911564, "lm_q1q2_score": 0.031876081789726174}}
{"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 \"geoids.h\"\n#include <boost/algorithm/string.hpp>\n#include <sstream>\n\nnamespace snark { namespace geodesy {\n    \nnamespace impl {\n\nwgs84::geoid wgs84;\nagd84::geoid agd84;\nsnark::spherical::ellipsoid sphere( earth_average_radius, earth_average_radius );\nsnark::spherical::ellipsoid unit( 1, unit_minor_semiaxis );\ngrs67::geoid grs67;\n\nstatic std::string sphere_info()\n{\n    std::stringstream os;\n    os  << \"shere,sphere with equal major and minor semiaxis,\" << earth_average_radius << \",\" << earth_average_radius << \",1\" << std::endl;\n    return os.str();\n}\n\nstatic std::string unit_info()\n{\n    std::stringstream os;\n    os << \"unit,scaled down WGS84,1,\" << unit_minor_semiaxis << \",\" << wgs84::eccentricity << std::endl;\n    return os.str();\n}\n\n} // namespace impl\n\nconst snark::spherical::ellipsoid& geoids::select( std::string name )\n{\n    if ( name.empty())\n        return impl::wgs84;\n    boost::algorithm::to_lower(name);\n    if ( name == wgs84::name ) { return impl::wgs84; }\n    else if ( name == agd84::name ) { return impl::agd84; }\n    else if ( name == grs67::name ) { return impl::grs67; }\n    else if ( name == \"sphere\" ) { return impl::sphere; }\n    else if ( name == \"unit\" ) { return impl::unit; }\n    else { COMMA_THROW( comma::exception, \"geoid not supported: \"<<name); }\n}\n\nstd::string geoids::info( std::string name )\n{\n    if ( name.empty())\n        return wgs84::info();\n    boost::algorithm::to_lower( name );\n    if ( name == wgs84::name ) { return wgs84::info(); }\n    else if ( name == agd84::name ) { return agd84::info(); }\n    else if ( name == grs67::name ) { return grs67::info(); }\n    else if ( name == \"sphere\" ) { return impl::sphere_info(); }\n    else if ( name == \"unit\" ) { return impl::unit_info(); }\n    else { COMMA_THROW( comma::exception, \"can't get info on geoid: \"<<name); }\n}\n\nstd::string geoids::help()\n{\n    std::stringstream os;\n    os << \"        sphere: sphere with earth average radius for comparision/testing ; \" << earth_average_radius << \";\" << earth_average_radius << \"); 1\" << std::endl;\n    os << \"        unit: WGS84 scaled down to unit, useful for getting distance in equivalent radian for instance (1; \" << unit_minor_semiaxis << \");\" << wgs84::eccentricity << std::endl;\n    return os.str();\n}\n\n} } // snark geodesy\n", "meta": {"hexsha": "83be8891604e97ace4e0de6ed4031ec4575e4edc", "size": 4053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geodesy/geoids.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": "geodesy/geoids.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": "geodesy/geoids.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": 42.6631578947, "max_line_length": 187, "alphanum_fraction": 0.6915864792, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.06853749208069855, "lm_q1q2_score": 0.03186318675005221}}
{"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_TRAITS_ROOT_INCLUDE\n#define MTL_TRAITS_ROOT_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n\nnamespace mtl { namespace traits {\n\n\n/// Type trait to reduce types to their essentials by removing const, reference, ... and gearing derived types to their bases\ntemplate <typename T>\nstruct root\n{\n    typedef T        type;\n};\n\n// ==========================\n// Remove language attributes\n// ==========================\n\ntemplate <typename T>\nstruct root<T&>\n  : public root<T> {};\n\ntemplate <typename T>\nstruct root<const T>\n  : public root<T> {};\n\n// Redundant specialization to make xlc++ happy\ntemplate <typename T, int R, int C>\nstruct root<const T[R][C]>\n  : public root<T[R][C]> {};\n\n\n// ============\n// Base classes\n// ============\n\n// Implicit dense matrices\n\ntemplate <typename Value>\nstruct root<mtl::mat::ones_matrix<Value> >\n{\n    typedef mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > type;\n};\n\ntemplate <typename Value>\nstruct root<mtl::mat::hilbert_matrix<Value> >\n{\n    typedef mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > type;\n};\n\ntemplate <typename Vector1, typename Vector2>\nstruct root<mtl::mat::outer_product_matrix<Vector1, Vector2> >\n{\n    typedef mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > type;\n};\n\n// Matrix map views\n\ntemplate <typename Scaling, typename Matrix>\nstruct root< mtl::mat::scaled_view<Scaling, Matrix> >\n{\n    typedef mtl::mat::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::mat::conj_view<Matrix> >\n{\n    typedef mtl::mat::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::mat::negate_view<Matrix> >\n{\n    typedef mtl::mat::map_view<sfunctor::negate<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::mat::imag_view<Matrix> >\n{\n    typedef mtl::mat::map_view<sfunctor::imag<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::mat::real_view<Matrix> >\n{\n    typedef mtl::mat::map_view<sfunctor::real<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::mat::exp_view<Matrix> >\n{\n    typedef mtl::mat::map_view<sfunctor::exp<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::mat::hermitian_view<Matrix> >\n{\n    typedef mtl::mat::map_view<sfunctor::conj<typename Matrix::value_type>, mtl::mat::transposed_view<Matrix> > type;\n};\n\ntemplate <typename Matrix, typename RScaling>\nstruct root< mtl::mat::rscaled_view<Matrix, RScaling> >\n{\n    typedef mtl::mat::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, Matrix> type;\n};\n\ntemplate <typename Matrix, typename Divisor>\nstruct root< mtl::mat::divide_by_view<Matrix, Divisor> >\n{\n    typedef mtl::mat::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, Matrix> type;\n};\n\n// Matrix operations\ntemplate <typename M1, typename M2> \nstruct root< mtl::mat::mat_mat_plus_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::plus<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::mat::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::mat::mv_mv_plus_expr<M1, M2> >\n{\n    typedef typename root< mtl::mat::mat_mat_plus_expr<M1, M2> >::type type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::mat::mat_mat_minus_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::minus<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::mat::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::mat::mv_mv_minus_expr<M1, M2> >\n{\n    typedef typename root< mtl::mat::mat_mat_minus_expr<M1, M2> >::type type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::mat::mat_mat_times_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::times<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::mat::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::mat::mat_mat_ele_times_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::times<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::mat::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\n\n// Vector assignment expressions\n\ntemplate <typename E1, typename E2>\nstruct root< vec::vec_vec_asgn_expr<E1, E2> >\n{\n    typedef vec::vec_vec_aop_expr< E1, E2, mtl::sfunctor::assign<typename E1::value_type, typename E2::value_type> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vec::vec_vec_plus_asgn_expr<E1, E2> >\n{\n    typedef vec::vec_vec_aop_expr< E1, E2, mtl::sfunctor::plus_assign<typename E1::value_type, typename E2::value_type> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vec::vec_vec_minus_asgn_expr<E1, E2> >\n{\n    typedef vec::vec_vec_aop_expr< E1, E2, mtl::sfunctor::minus_assign<typename E1::value_type, typename E2::value_type> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vec::vec_scal_asgn_expr<E1, E2> >\n{\n    typedef vec::vec_scal_aop_expr< E1, E2, mtl::sfunctor::assign<typename E1::value_type, E2> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vec::vec_scal_times_asgn_expr<E1, E2> >\n{\n    typedef vec::vec_scal_aop_expr< E1, E2, mtl::sfunctor::times_assign<typename E1::value_type, E2> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vec::vec_scal_div_asgn_expr<E1, E2> >\n{\n    typedef vec::vec_scal_aop_expr< E1, E2, mtl::sfunctor::divide_assign<typename E1::value_type, E2> > type;\n};\n\ntemplate <typename Scaling, typename Vector>\nstruct root< vec::scaled_view<Scaling, Vector> >\n{\n    typedef vec::map_view<tfunctor::scale<Scaling, typename Vector::value_type>, Vector> type;\n};\n\ntemplate <typename Vector, typename RScaling>\nstruct root< vec::rscaled_view<Vector, RScaling> >\n{\n    typedef vec::map_view<tfunctor::rscale<typename Vector::value_type, RScaling>, Vector> type;\n};\n\ntemplate <typename Vector, typename Divisor>\nstruct root< vec::divide_by_view<Vector, Divisor> >\n{\n    typedef vec::map_view<tfunctor::divide_by<typename Vector::value_type, Divisor>, Vector> type;\n};\n\ntemplate <typename Vector>\nstruct root< vec::conj_view<Vector> >\n{\n    typedef vec::map_view<mtl::sfunctor::conj<typename Vector::value_type>, Vector> type;\n};\n\ntemplate <typename Vector>\nstruct root< vec::negate_view<Vector> >\n{\n    typedef vec::map_view<mtl::sfunctor::negate<typename Vector::value_type>, Vector> type;\n};\n\ntemplate <unsigned BSize, typename Vector>\nstruct root< vec::unrolled1<BSize, Vector> >\n{\n    typedef Vector type;\n};\n\n\n\n#if 0 // template\nstruct root\n{\n    typedef  type;\n};\n#endif\n\n\n}} // namespace mtl::traits\n\n#endif // MTL_TRAITS_ROOT_INCLUDE\n", "meta": {"hexsha": "771ff217db9f0ee69cc5bd6acba7b96941f9cc68", "size": 7371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/utility/root.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/utility/root.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/utility/root.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": 28.79296875, "max_line_length": 128, "alphanum_fraction": 0.7175417175, "num_tokens": 2081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.06656918480384218, "lm_q1q2_score": 0.03172551886540846}}
{"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_PROPERTY_MAP_INCLUDE\n#define MTL_PROPERTY_MAP_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/utility/property_map_impl.hpp>\n\nnamespace mtl { namespace traits {    \n\ntemplate <class Matrix> struct row {};\ntemplate <class Matrix> struct col {};\ntemplate <class Matrix> struct const_value {};\ntemplate <class Matrix> struct value {};\ntemplate <class Matrix> struct offset {};\n\n// For vectors\ntemplate <class Vector> struct index {};\n\n// ===========\n// For dense2D\n// ===========\n\ntemplate <typename Value, class Parameters>\nstruct row<mtl::mat::dense2D<Value, Parameters> >\n{\n    typedef mtl::detail::indexer_row_ref<mtl::mat::dense2D<Value, Parameters> > type;\n};\n\ntemplate <typename Value, class Parameters>\nstruct col<mtl::mat::dense2D<Value, Parameters> >\n{\n    typedef mtl::detail::indexer_col_ref<mtl::mat::dense2D<Value, Parameters> > type;\n};\n\ntemplate <typename Value, class Parameters>\nstruct const_value<mtl::mat::dense2D<Value, Parameters> >\n{\n    typedef mtl::detail::direct_const_value<mtl::mat::dense2D<Value, Parameters> > type;\n};\n\ntemplate <typename Value, class Parameters>\nstruct value<mtl::mat::dense2D<Value, Parameters> >\n{\n    typedef mtl::detail::direct_value<mtl::mat::dense2D<Value, Parameters> > type;\n};\n\n\n// ================\n// For morton_dense\n// ================\n\n\ntemplate <class Elt, std::size_t BitMask, class Parameters>\nstruct row<mtl::mat::morton_dense<Elt, BitMask, Parameters> >\n{\n    typedef mtl::detail::row_in_key<mtl::mat::morton_dense<Elt, BitMask, Parameters> > type;\n};\n\ntemplate <class Elt, std::size_t BitMask, class Parameters>\nstruct col<mtl::mat::morton_dense<Elt, BitMask, Parameters> >\n{\n    typedef mtl::detail::col_in_key<mtl::mat::morton_dense<Elt, BitMask, Parameters> > type;\n};\n\ntemplate <class Elt, std::size_t BitMask, class Parameters>\nstruct const_value<mtl::mat::morton_dense<Elt, BitMask, Parameters> >\n{\n    typedef mtl::detail::matrix_const_value_ref<mtl::mat::morton_dense<Elt, BitMask, Parameters> > type;\n};\n\ntemplate <class Elt, std::size_t BitMask, class Parameters>\nstruct value<mtl::mat::morton_dense<Elt, BitMask, Parameters> >\n{\n    typedef mtl::detail::matrix_value_ref<mtl::mat::morton_dense<Elt, BitMask, Parameters> > type;\n};\n\n\n// ================\n// For compressed2D\n// ================\n\ntemplate <class Elt, class Parameters>\nstruct row<mtl::mat::compressed2D<Elt, Parameters> >\n{\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename Parameters::orientation, row_major>\n      , mtl::detail::major_in_key<mtl::mat::compressed2D<Elt, Parameters> >\n      , mtl::detail::indexer_minor_ref<mtl::mat::compressed2D<Elt, Parameters> >\n    >::type type;  \n};\n\ntemplate <class Elt, class Parameters>\nstruct col<mtl::mat::compressed2D<Elt, Parameters> >\n{\n    typedef typename boost::mpl::if_<\n\tboost::is_same<typename Parameters::orientation, row_major>\n      , mtl::detail::indexer_minor_ref<mtl::mat::compressed2D<Elt, Parameters> >\n      , mtl::detail::major_in_key<mtl::mat::compressed2D<Elt, Parameters> >\n    >::type type;  \n};\n\ntemplate <class Elt, class Parameters>\nstruct const_value<mtl::mat::compressed2D<Elt, Parameters> >\n{\n    typedef mtl::detail::matrix_offset_const_value<mtl::mat::compressed2D<Elt, Parameters> > type;\n};\n\ntemplate <class Elt, class Parameters>\nstruct value<mtl::mat::compressed2D<Elt, Parameters> >\n{\n    typedef mtl::detail::matrix_offset_value<mtl::mat::compressed2D<Elt, Parameters> > type;\n};\n \n// Offset that corresponds to cursor, e.g. to set values in a matrix with same pattern \n// needed in ILU_0, so far only for compressed2D, could be useful for algos on sparse and dense\ntemplate <class Elt, class Parameters>\nstruct offset<mtl::mat::compressed2D<Elt, Parameters> >\n{\n    typedef mtl::detail::offset_from_key<mtl::mat::compressed2D<Elt, Parameters> > type;\n};\n  \n  \n// ================\n// For coordinate2D\n// ================\n\ntemplate <class Value, class Parameters>\nstruct row<mtl::mat::coordinate2D<Value, Parameters> >\n{\n    typedef mtl::detail::coordinate2D_row<Value, Parameters>   type; \n};\n\ntemplate <class Value, class Parameters>\nstruct col<mtl::mat::coordinate2D<Value, Parameters> >\n{\n    typedef mtl::detail::coordinate2D_col<Value, Parameters>   type; \n};\n\ntemplate <class Value, class Parameters>\nstruct const_value<mtl::mat::coordinate2D<Value, Parameters> >\n{\n    typedef mtl::detail::coordinate2D_const_value<Value, Parameters>   type; \n};\n\n// =================\n// For sparse_banded\n// =================\n\ntemplate <class Value, class Parameters>\nstruct row<mtl::mat::sparse_banded<Value, Parameters> >\n{\n    typedef mtl::detail::sparse_banded_row<Value, Parameters>   type; \n};\n\ntemplate <class Value, class Parameters>\nstruct col<mtl::mat::sparse_banded<Value, Parameters> >\n{\n    typedef mtl::detail::sparse_banded_col<Value, Parameters>   type; \n};\n\ntemplate <class Value, class Parameters>\nstruct const_value<mtl::mat::sparse_banded<Value, Parameters> >\n{\n    typedef mtl::detail::sparse_banded_const_value<Value, Parameters>   type; \n};\n\n// ==================\n// For implicit_dense\n// ==================\n\ntemplate <typename Functor>\nstruct row<mtl::mat::implicit_dense<Functor> >\n{\n    typedef mtl::detail::row_in_element_key<mtl::mat::implicit_dense<Functor> > type;\n};\n\ntemplate <typename Functor>\nstruct col<mtl::mat::implicit_dense<Functor> >\n{\n    typedef mtl::detail::col_in_element_key<mtl::mat::implicit_dense<Functor> > type;\n};\n\ntemplate <typename Functor>\nstruct const_value<mtl::mat::implicit_dense<Functor> >\n{\n    typedef mtl::detail::const_value_in_element_key<mtl::mat::implicit_dense<Functor> > type;\n};\n\n\n// ===============\n// For ones_matrix\n// ===============\n\ntemplate <typename Value>\nstruct row<mtl::mat::ones_matrix<Value> >\n  : public row<mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > > \n{};\n\ntemplate <typename Value>\nstruct col<mtl::mat::ones_matrix<Value> >\n  : public col<mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > > \n{};\n\ntemplate <typename Value>\nstruct const_value<mtl::mat::ones_matrix<Value> >\n  : public const_value<mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > > \n{};\n\n\n// ===============\n// For hilbert_matrix\n// ===============\n\ntemplate <typename Value>\nstruct row<mtl::mat::hilbert_matrix<Value> >\n  : public row<mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > > \n{};\n\ntemplate <typename Value>\nstruct col<mtl::mat::hilbert_matrix<Value> >\n  : public col<mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > > \n{};\n\ntemplate <typename Value>\nstruct const_value<mtl::mat::hilbert_matrix<Value> >\n  : public const_value<mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > > \n{};\n\n\n// ========================\n// For outer_product_matrix\n// ========================\n\ntemplate <typename Vector1, typename Vector2>\nstruct row<mtl::mat::outer_product_matrix<Vector1, Vector2> >\n  : public row<mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > > \n{};\n\ntemplate <typename Vector1, typename Vector2>\nstruct col<mtl::mat::outer_product_matrix<Vector1, Vector2> >\n  : public col<mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > > \n{};\n\ntemplate <typename Vector1, typename Vector2>\nstruct const_value<mtl::mat::outer_product_matrix<Vector1, Vector2> >\n  : public const_value<mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > > \n{};\n\n\n// ====================\n// For mat::indirect\n// ====================\n\ntemplate <typename Matrix>\nstruct row<mtl::mat::indirect<Matrix> >\n{\n    typedef mtl::detail::row_in_element_key<mtl::mat::indirect<Matrix> > type;\n};\n\ntemplate <typename Matrix>\nstruct col<mtl::mat::indirect<Matrix> >\n{\n    typedef mtl::detail::col_in_element_key<mtl::mat::indirect<Matrix> > type;\n};\n\ntemplate <typename Matrix>\nstruct const_value<mtl::mat::indirect<Matrix> >\n{\n    typedef mtl::detail::const_value_in_element_key<mtl::mat::indirect<Matrix> > type;\n};\n\n\n// ================\n// For dense_vector\n// ================\n\ntemplate <class Elt, class Parameters>\nstruct index<mtl::vec::dense_vector<Elt, Parameters> >\n{\n    typedef mtl::detail::index_from_offset< mtl::vec::dense_vector<Elt, Parameters> > type;\n};\n\ntemplate <typename Value, class Parameters>\nstruct const_value<mtl::vec::dense_vector<Value, Parameters> >\n{\n    typedef mtl::detail::direct_const_value<mtl::vec::dense_vector<Value, Parameters> > type;\n};\n\ntemplate <typename Value, class Parameters>\nstruct value<mtl::vec::dense_vector<Value, Parameters> >\n{\n    typedef mtl::detail::direct_value<mtl::vec::dense_vector<Value, Parameters> > type;\n};\n// ================\n// For strided_vector_ref\n// ================\n\ntemplate <class Elt, class Parameters>\nstruct index<mtl::vec::strided_vector_ref<Elt, Parameters> >\n{\n    typedef mtl::detail::index_from_offset< vec::strided_vector_ref<Elt, Parameters> > type;\n};\n\ntemplate <typename Value, class Parameters>\nstruct const_value<mtl::vec::strided_vector_ref<Value, Parameters> >\n{\n    typedef mtl::detail::direct_const_value<vec::strided_vector_ref<Value, Parameters> > type;\n};\n\ntemplate <typename Value, class Parameters>\nstruct value<mtl::vec::strided_vector_ref<Value, Parameters> >\n{\n    typedef mtl::detail::direct_value<vec::strided_vector_ref<Value, Parameters> > type;\n};\n\n\n\n\n}} // namespace mtl::traits\n\nnamespace mtl { namespace mat {\n\n// Helpers\n\n/// Row map of matrix A\ntemplate <typename Matrix>\ntypename mtl::traits::row<Matrix>::type\ninline row_map(const Matrix& A)\n{\n    return typename mtl::traits::row<Matrix>::type(A);\n}\n\n/// Column map of matrix A\ntemplate <typename Matrix>\ntypename mtl::traits::col<Matrix>::type\ninline col_map(const Matrix& A)\n{\n    return typename mtl::traits::col<Matrix>::type(A);\n}\n\n/// Constant value map of matrix A\ntemplate <typename Matrix>\ntypename mtl::traits::const_value<Matrix>::type\ninline const_value_map(const Matrix& A)\n{\n    return typename mtl::traits::const_value<Matrix>::type(A);\n}\n\n/// Value map of matrix A\ntemplate <typename Matrix>\ntypename mtl::traits::value<Matrix>::type\ninline value_map(Matrix& A)\n{\n    return typename mtl::traits::value<Matrix>::type(A);\n}\n\n/// Offset map of matrix A\ntemplate <typename Matrix>\ntypename mtl::traits::offset<Matrix>::type\ninline offset_map(const Matrix& A)\n{\n    return typename mtl::traits::offset<Matrix>::type(A);\n}\n\n}} // namespace typename mtl::matrix\n\nnamespace mtl { namespace vec {\n\n/// Index map of vector A\ntemplate <typename Vector>\ntypename mtl::traits::index<Vector>::type\ninline index_map(const Vector& A)\n{\n    return typename mtl::traits::index<Vector>::type(A);\n}\n\n/// Constant value map of vector A\ntemplate <typename Vector>\ntypename mtl::traits::const_value<Vector>::type\ninline const_value_map(const Vector& A)\n{\n    return typename mtl::traits::const_value<Vector>::type(A);\n}\n\n/// Value map of vector A\ntemplate <typename Vector>\ntypename mtl::traits::value<Vector>::type\ninline value_map(Vector& A)\n{\n    return typename mtl::traits::value<Vector>::type(A);\n}\n\n}} // namespace typename mtl::vector\n\n\n\n#endif // MTL_PROPERTY_MAP_INCLUDE\n\n\n", "meta": {"hexsha": "d7f8cb2e612c498c217337de066b70017f5f2176", "size": 11511, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/utility/property_map.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/utility/property_map.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/utility/property_map.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": 28.0072992701, "max_line_length": 104, "alphanum_fraction": 0.7021978977, "num_tokens": 3063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.06853748922682354, "lm_q1q2_score": 0.03159693254550274}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <utility>\n#include <numeric>\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#include <amgcl/backend/builtin.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/preconditioner/runtime.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/mpi/make_solver.hpp>\n#include <amgcl/mpi/block_preconditioner.hpp>\n#include <amgcl/profiler.hpp>\n\n#include \"domain_partition.hpp\"\n\nnamespace amgcl { profiler<> prof; }\nusing amgcl::prof;\nusing amgcl::precondition;\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\n//---------------------------------------------------------------------------\ntemplate <template <class> class Precond, class Matrix>\nstd::tuple<size_t, double> solve(\n        const amgcl::mpi::communicator &comm,\n        const boost::property_tree::ptree &prm,\n        const Matrix &A\n        )\n{\n    typedef amgcl::backend::builtin<double> Backend;\n\n    typedef amgcl::mpi::make_solver<\n        amgcl::mpi::block_preconditioner< Precond<Backend> >,\n        amgcl::runtime::solver::wrapper\n        > Solver;\n\n    const size_t n = amgcl::backend::rows(A);\n\n    std::vector<double> rhs(n, 1), x(n, 0);\n\n    prof.tic(\"setup\");\n    Solver solve(comm, A, prm);\n    prof.toc(\"setup\");\n\n    {\n        auto t2 = prof.scoped_tic(\"solve\");\n        return solve(rhs, x);\n    }\n}\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    namespace po = boost::program_options;\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        (\n         \"size,n\",\n         po::value<int>()->default_value(1024),\n         \"The size of the Poisson problem to solve. \"\n         \"Specified as number of grid nodes along each dimension of a unit square. \"\n         \"The resulting system will have n*n unknowns. \"\n        )\n        (\n         \"single-level,1\",\n         po::bool_switch()->default_value(false),\n         \"When specified, the AMG hierarchy is not constructed. \"\n         \"Instead, the problem is solved using a single-level smoother as preconditioner. \"\n        )\n        (\n         \"initial,x\",\n         po::value<double>()->default_value(0),\n         \"Value to use as initial approximation. \"\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(\"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    MPI_Init(&argc, &argv);\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    const ptrdiff_t n   = vm[\"size\"].as<int>();\n    const double    h2i = (n - 1) * (n - 1);\n\n    boost::array<ptrdiff_t, 2> lo = { {0, 0} };\n    boost::array<ptrdiff_t, 2> hi = { {n - 1, n - 1} };\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(\"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\n    ptr.push_back(0);\n\n    for(ptrdiff_t j = lo[1]; j <= hi[1]; ++j) {\n        for(ptrdiff_t i = lo[0]; i <= hi[0]; ++i) {\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            ptr.push_back( col.size() );\n        }\n    }\n    prof.toc(\"assemble\");\n\n    size_t iters;\n    double error;\n\n    bool single_level = vm[\"single-level\"].as<bool>();\n\n    if (single_level)\n        prm.put(\"precond.class\", \"relaxation\");\n\n    std::tie(iters, error) = solve<amgcl::runtime::preconditioner>(\n            world, prm, std::tie(chunk, ptr, col, val));\n\n    if (world.rank == 0) {\n        std::cout\n            << \"Iterations: \" << iters << std::endl\n            << \"Error:      \" << error << std::endl\n            << std::endl\n            << prof << std::endl;\n    }\n}\n", "meta": {"hexsha": "76fd6b26d1e9430c819cbbced3dd671bd1f07090", "size": 6388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/runtime_bp.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_bp.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_bp.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": 27.6536796537, "max_line_length": 91, "alphanum_fraction": 0.5360050094, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.06465349105959628, "lm_q1q2_score": 0.031569226132308566}}
{"text": "// Copyright (C) 2005-2008 The Trustees of Indiana University.\r\n\r\n// Use, modification and distribution is subject to the Boost Software\r\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Douglas Gregor\r\n//           Andrew Lumsdaine\r\n#ifndef BOOST_GRAPH_DISTRIBUTED_BOMAN_ET_AL_GRAPH_COLORING_HPP\r\n#define BOOST_GRAPH_DISTRIBUTED_BOMAN_ET_AL_GRAPH_COLORING_HPP\r\n\r\n#ifndef BOOST_GRAPH_USE_MPI\r\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\r\n#endif\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/parallel/algorithm.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/parallel/process_group.hpp>\r\n#include <functional>\r\n#include <vector>\r\n#include <utility>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/optional.hpp>\r\n#include <boost/assert.hpp>\r\n#include <boost/graph/parallel/container_traits.hpp>\r\n#include <boost/graph/properties.hpp>\r\n\r\n#ifdef PBGL_ACCOUNTING\r\n#  include <boost/graph/accounting.hpp>\r\n#endif // PBGL_ACCOUNTING\r\n\r\nnamespace boost { namespace graph { namespace distributed {\r\n\r\n/**************************************************************************\r\n * This source file implements the distributed graph coloring algorithm   *\r\n * by Boman et al in:                                                     *\r\n *                                                                        *\r\n *   Erik G. Boman, Doruk Bozdag, Umit Catalyurek, Assefaw H. Gebremedhin,*\r\n *   and Fredrik Manne. A Scalable Parallel Graph Coloring Algorithm for  *\r\n *   Distributed Memory Computers. [unpublished preprint?]                *\r\n *                                                                        *\r\n **************************************************************************/\r\n\r\n#ifdef PBGL_ACCOUNTING\r\nstruct boman_et_al_graph_coloring_stats_t\r\n{\r\n  /* The size of the blocks to step through (i.e., the parameter s). */\r\n  std::size_t block_size;\r\n  \r\n  /* Total wall-clock time used by the algorithm.*/\r\n  accounting::time_type execution_time;\r\n\r\n  /* The number of conflicts that occurred during execution. */\r\n  std::size_t conflicts;\r\n\r\n  /* The number of supersteps. */\r\n  std::size_t supersteps;\r\n\r\n  /* The number of colors used. */\r\n  std::size_t num_colors;\r\n\r\n  template<typename OutputStream>\r\n  void print(OutputStream& out)\r\n  {\r\n    out << \"Problem = \\\"Coloring\\\"\\n\"\r\n        << \"Algorithm = \\\"Boman et al\\\"\\n\"\r\n        << \"Function = boman_et_al_graph_coloring\\n\"\r\n        << \"(P) Block size = \" << block_size << \"\\n\"\r\n        << \"Wall clock time = \" << accounting::print_time(execution_time) \r\n        << \"\\nConflicts = \" << conflicts << \"\\n\"\r\n        << \"Supersteps = \" << supersteps << \"\\n\"\r\n        << \"(R) Colors = \" << num_colors << \"\\n\";\r\n  }\r\n};\r\n\r\nstatic boman_et_al_graph_coloring_stats_t boman_et_al_graph_coloring_stats;\r\n#endif\r\n\r\nnamespace detail {\r\n  template<typename T>\r\n  struct graph_coloring_reduce\r\n  {\r\n    BOOST_STATIC_CONSTANT(bool, non_default_resolver = true);\r\n\r\n    template<typename Key>\r\n    T operator()(const Key&) const { return (std::numeric_limits<T>::max)(); }\r\n\r\n    template<typename Key> T operator()(const Key&, T, T y) const { return y; }\r\n  };\r\n}\r\n\r\ntemplate<typename Color>\r\nstruct first_fit_color\r\n{\r\n  template<typename T>\r\n  Color operator()(const std::vector<T>& marked, T marked_true)\r\n  {\r\n    Color k = 0;\r\n    while (k < (Color)marked.size() && marked[k] == marked_true)\r\n      ++k;\r\n    return k;\r\n  }\r\n};\r\n\r\ntemplate<typename DistributedGraph, typename ColorMap, typename ChooseColor,\r\n         typename VertexOrdering, typename VertexIndexMap>\r\ntypename property_traits<ColorMap>::value_type\r\nboman_et_al_graph_coloring\r\n  (const DistributedGraph& g,\r\n   ColorMap color,\r\n   typename graph_traits<DistributedGraph>::vertices_size_type s,\r\n   ChooseColor choose_color,\r\n   VertexOrdering ordering, VertexIndexMap vertex_index)\r\n{\r\n  using namespace boost::graph::parallel;\r\n  using boost::parallel::all_reduce;\r\n\r\n  typename property_map<DistributedGraph, vertex_owner_t>::const_type\r\n    owner = get(vertex_owner, g);\r\n\r\n  typedef typename process_group_type<DistributedGraph>::type \r\n    process_group_type;\r\n  typedef typename process_group_type::process_id_type process_id_type;\r\n  typedef typename graph_traits<DistributedGraph>::vertex_descriptor Vertex;\r\n  typedef typename graph_traits<DistributedGraph>::vertices_size_type \r\n    vertices_size_type;\r\n  typedef typename property_traits<ColorMap>::value_type color_type;\r\n  typedef unsigned long long iterations_type;\r\n  typedef typename std::vector<Vertex>::iterator vertex_set_iterator;\r\n  typedef std::pair<Vertex, color_type> message_type;\r\n\r\n#ifdef PBGL_ACCOUNTING\r\n  boman_et_al_graph_coloring_stats.block_size = s;\r\n  boman_et_al_graph_coloring_stats.execution_time = accounting::get_time();\r\n  boman_et_al_graph_coloring_stats.conflicts = 0;\r\n  boman_et_al_graph_coloring_stats.supersteps = 0;\r\n#endif\r\n\r\n  // Initialize color map\r\n  color_type no_color = (std::numeric_limits<color_type>::max)();\r\n  BGL_FORALL_VERTICES_T(v, g, DistributedGraph)\r\n    put(color, v, no_color);\r\n  color.set_reduce(detail::graph_coloring_reduce<color_type>());\r\n  \r\n  // Determine if we'll be using synchronous or asynchronous communication.\r\n  typedef typename process_group_type::communication_category\r\n    communication_category;\r\n  static const bool asynchronous = \r\n    is_convertible<communication_category, boost::parallel::immediate_process_group_tag>::value;\r\n  process_group_type pg = process_group(g);\r\n\r\n  // U_i <- V_i\r\n  std::vector<Vertex> vertices_to_color(vertices(g).first, vertices(g).second);\r\n\r\n  iterations_type iter_num = 1, outer_iter_num = 1;\r\n  std::vector<iterations_type> marked;\r\n  std::vector<iterations_type> marked_conflicting(num_vertices(g), 0);\r\n  std::vector<bool> sent_to_processors;\r\n\r\n  std::size_t rounds = vertices_to_color.size() / s \r\n    + (vertices_to_color.size() % s == 0? 0 : 1);\r\n  rounds = all_reduce(pg, rounds, boost::parallel::maximum<std::size_t>());\r\n\r\n#ifdef PBGL_GRAPH_COLORING_DEBUG\r\n  std::cerr << \"Number of rounds = \" << rounds << std::endl;\r\n#endif\r\n\r\n  while (rounds > 0) {\r\n    if (!vertices_to_color.empty()) {\r\n      // Set of conflicting vertices\r\n      std::vector<Vertex> conflicting_vertices;\r\n\r\n      vertex_set_iterator first = vertices_to_color.begin();\r\n      while (first != vertices_to_color.end()) {\r\n        // For each subset of size s (or smaller for the last subset)\r\n        vertex_set_iterator start = first;\r\n        for (vertices_size_type counter = s; \r\n             first != vertices_to_color.end() && counter > 0;\r\n             ++first, --counter) {\r\n          // This vertex hasn't been sent to anyone yet\r\n          sent_to_processors.assign(num_processes(pg), false);\r\n          sent_to_processors[process_id(pg)] = true;\r\n\r\n          // Mark all of the colors that we see\r\n          BGL_FORALL_OUTEDGES_T(*first, e, g, DistributedGraph) {\r\n            color_type k = get(color, target(e, g));\r\n            if (k != no_color) {\r\n              if (k >= (color_type)marked.size()) marked.resize(k + 1, 0);\r\n              marked[k] = iter_num;\r\n            }\r\n          }\r\n\r\n          // Find a color for this vertex\r\n          put(color, *first, choose_color(marked, iter_num));\r\n\r\n#ifdef PBGL_GRAPH_COLORING_DEBUG\r\n          std::cerr << \"Chose color \" << get(color, *first) << \" for vertex \"\r\n                    << *first << std::endl;\r\n#endif\r\n\r\n          // Send this vertex's color to the owner of the edge target.\r\n          BGL_FORALL_OUTEDGES_T(*first, e, g, DistributedGraph) {\r\n            if (!sent_to_processors[get(owner, target(e, g))]) {\r\n              send(pg, get(owner, target(e, g)), 17, \r\n                   message_type(source(e, g), get(color, source(e, g))));\r\n              sent_to_processors[get(owner, target(e, g))] = true;\r\n            }\r\n          }\r\n\r\n          ++iter_num;\r\n        }\r\n\r\n        // Synchronize for non-immediate process groups.\r\n        if (!asynchronous) { \r\n          --rounds;\r\n          synchronize(pg);\r\n        }\r\n\r\n        // Receive boundary colors from other processors\r\n        while (optional<std::pair<process_id_type, int> > stp = probe(pg)) {\r\n          BOOST_ASSERT(stp->second == 17);\r\n          message_type msg;\r\n          receive(pg, stp->first, stp->second, msg);\r\n          cache(color, msg.first, msg.second);\r\n#ifdef PBGL_GRAPH_COLORING_DEBUG\r\n          std::cerr << \"Cached color \" << msg.second << \" for vertex \" \r\n                    << msg.first << std::endl;\r\n#endif\r\n        }\r\n\r\n        // Compute the set of conflicting vertices\r\n        // [start, first) contains all vertices in this subset\r\n        for (vertex_set_iterator vi = start; vi != first; ++vi) {\r\n          Vertex v = *vi;\r\n          BGL_FORALL_OUTEDGES_T(v, e, g, DistributedGraph) {\r\n            Vertex w = target(e, g);\r\n            if (get(owner, w) != process_id(pg) // boundary vertex\r\n                && marked_conflicting[get(vertex_index, v)] != outer_iter_num\r\n                && get(color, v) == get(color, w)\r\n                && ordering(v, w)) {\r\n              conflicting_vertices.push_back(v);\r\n              marked_conflicting[get(vertex_index, v)] = outer_iter_num;\r\n              put(color, v, no_color);\r\n#ifdef PBGL_GRAPH_COLORING_DEBUG\r\n              std::cerr << \"Vertex \" << v << \" has a conflict with vertex \"\r\n                        << w << std::endl;\r\n#endif\r\n              break;\r\n            }\r\n          }\r\n        }\r\n\r\n#ifdef PBGL_ACCOUNTING\r\n        boman_et_al_graph_coloring_stats.conflicts += \r\n          conflicting_vertices.size();\r\n#endif\r\n      }\r\n\r\n      if (asynchronous) synchronize(pg);\r\n      else {\r\n        while (rounds > 0) {\r\n          synchronize(pg);\r\n          --rounds;\r\n        }\r\n      }\r\n      conflicting_vertices.swap(vertices_to_color);\r\n      ++outer_iter_num;\r\n    } else {\r\n      if (asynchronous) synchronize(pg);\r\n      else {\r\n        while (rounds > 0) {\r\n          synchronize(pg);\r\n          --rounds;\r\n        }\r\n      }\r\n    }\r\n\r\n    // Receive boundary colors from other processors\r\n    while (optional<std::pair<process_id_type, int> > stp = probe(pg)) {\r\n      BOOST_ASSERT(stp->second == 17);\r\n      message_type msg;\r\n      receive(pg, stp->first, stp->second, msg);\r\n      cache(color, msg.first, msg.second);\r\n    }\r\n\r\n    rounds = vertices_to_color.size() / s \r\n      + (vertices_to_color.size() % s == 0? 0 : 1);\r\n    rounds = all_reduce(pg, rounds, boost::parallel::maximum<std::size_t>());\r\n\r\n#ifdef PBGL_ACCOUNTING\r\n    ++boman_et_al_graph_coloring_stats.supersteps;\r\n#endif\r\n  }\r\n\r\n  // Determine the number of colors used.\r\n  color_type num_colors = 0;\r\n  BGL_FORALL_VERTICES_T(v, g, DistributedGraph) {\r\n    color_type k = get(color, v);\r\n    BOOST_ASSERT(k != no_color);\r\n    if (k != no_color) {\r\n      if (k >= (color_type)marked.size()) marked.resize(k + 1, 0); // TBD: perf?\r\n      if (marked[k] != iter_num) {\r\n        marked[k] = iter_num;\r\n        ++num_colors;\r\n      }\r\n    }\r\n  }\r\n\r\n  num_colors = \r\n    all_reduce(pg, num_colors, boost::parallel::maximum<color_type>());\r\n\r\n\r\n#ifdef PBGL_ACCOUNTING\r\n  boman_et_al_graph_coloring_stats.execution_time = \r\n    accounting::get_time() - boman_et_al_graph_coloring_stats.execution_time;\r\n  \r\n  boman_et_al_graph_coloring_stats.conflicts = \r\n    all_reduce(pg, boman_et_al_graph_coloring_stats.conflicts,\r\n               std::plus<color_type>());\r\n  boman_et_al_graph_coloring_stats.num_colors = num_colors;\r\n#endif\r\n\r\n  return num_colors;\r\n}\r\n\r\n\r\ntemplate<typename DistributedGraph, typename ColorMap, typename ChooseColor, \r\n         typename VertexOrdering>\r\ninline typename property_traits<ColorMap>::value_type\r\nboman_et_al_graph_coloring\r\n  (const DistributedGraph& g, ColorMap color,\r\n   typename graph_traits<DistributedGraph>::vertices_size_type s,\r\n   ChooseColor choose_color, VertexOrdering ordering)\r\n{\r\n  return boman_et_al_graph_coloring(g, color, s, choose_color, ordering, \r\n                                    get(vertex_index, g));\r\n}\r\n\r\ntemplate<typename DistributedGraph, typename ColorMap, typename ChooseColor>\r\ninline typename property_traits<ColorMap>::value_type\r\nboman_et_al_graph_coloring\r\n  (const DistributedGraph& g,\r\n   ColorMap color,\r\n   typename graph_traits<DistributedGraph>::vertices_size_type s,\r\n   ChooseColor choose_color)\r\n{\r\n  typedef typename graph_traits<DistributedGraph>::vertex_descriptor\r\n    vertex_descriptor;\r\n  return boman_et_al_graph_coloring(g, color, s, choose_color,\r\n                                    std::less<vertex_descriptor>());\r\n}\r\n\r\ntemplate<typename DistributedGraph, typename ColorMap>\r\ninline typename property_traits<ColorMap>::value_type\r\nboman_et_al_graph_coloring\r\n  (const DistributedGraph& g,\r\n   ColorMap color,\r\n   typename graph_traits<DistributedGraph>::vertices_size_type s = 100)\r\n{\r\n  typedef typename property_traits<ColorMap>::value_type Color;\r\n  return boman_et_al_graph_coloring(g, color, s, first_fit_color<Color>());\r\n}\r\n\r\n} } } // end namespace boost::graph::distributed\r\n\r\nnamespace boost { namespace graph {\r\nusing distributed::boman_et_al_graph_coloring;\r\n} } // end namespace boost::graph\r\n\r\n#endif // BOOST_GRAPH_DISTRIBUTED_BOMAN_ET_AL_GRAPH_COLORING_HPP\r\n", "meta": {"hexsha": "3de087fe26f81168da3e074f4a54cc4730818298", "size": 13358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/boman_et_al_graph_coloring.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/boman_et_al_graph_coloring.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/boman_et_al_graph_coloring.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 35.9086021505, "max_line_length": 102, "alphanum_fraction": 0.6390926785, "num_tokens": 3017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.07696084257657987, "lm_q1q2_score": 0.031348721677117865}}
{"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_VECTOR_H\r\n#define BOOST_UBLAS_VECTOR_H\r\n\r\n#include <vector>\r\n\r\n#include <boost/numeric/ublas/config.hpp>\r\n#include <boost/numeric/ublas/storage.hpp>\r\n#include <boost/numeric/ublas/vector_expression.hpp>\r\n#include <boost/numeric/ublas/vector_assign.hpp>\r\n#include <boost/numeric/ublas/vector_proxy.hpp>\r\n\r\n// Iterators based on ideas of Jeremy Siek\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    // Array based vector class\r\n    template<class T, class A>\r\n    class vector:\r\n        public vector_expression<vector<T, A> > {\r\n    public:\r\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\r\n        BOOST_UBLAS_USING vector_expression<vector<T, A> >::operator ();\r\n#endif\r\n        typedef typename A::size_type size_type;\r\n        typedef typename A::difference_type difference_type;\r\n        typedef T value_type;\r\n        typedef typename type_traits<T>::const_reference const_reference;\r\n        typedef T &reference;\r\n        typedef A array_type;\r\n    private:\r\n        typedef T *pointer;\r\n        typedef vector<T, A> self_type;\r\n    public:\r\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\r\n        typedef const vector_const_reference<const self_type> const_closure_type;\r\n#else\r\n        typedef const vector_reference<const self_type> const_closure_type;\r\n#endif\r\n        typedef vector_reference<self_type> closure_type;\r\n        typedef self_type vector_temporary_type;\r\n        typedef dense_tag storage_category;\r\n        typedef concrete_tag simd_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        vector ():\r\n            vector_expression<self_type> (),\r\n            data_ () {}\r\n        explicit BOOST_UBLAS_INLINE\r\n        vector (size_type size):\r\n            vector_expression<self_type> (),\r\n            data_ (size) {\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector (size_type size, const array_type &data):\r\n            vector_expression<self_type> (),\r\n            data_ (data) {}\r\n        BOOST_UBLAS_INLINE\r\n        vector (const vector &v):\r\n            vector_expression<self_type> (),\r\n            data_ (v.data_) {}\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector (const vector_expression<AE> &ae):\r\n            vector_expression<self_type> (),\r\n            data_ (ae ().size ()) {\r\n            vector_assign (scalar_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n        }\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return data_.size ();\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const array_type &data () const {\r\n            return data_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        array_type &data () {\r\n            return data_;\r\n        }\r\n\r\n        // Resizing\r\n        BOOST_UBLAS_INLINE\r\n        void resize (size_type size, bool preserve = true) {\r\n            if (preserve)\r\n                data ().resize (size, BOOST_UBLAS_TYPENAME A::value_type (0));\r\n            else\r\n                data ().resize (size);\r\n        }\r\n\r\n        // Element access\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type i) const {\r\n            return data () [i];\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) {\r\n            return data () [i];\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) {\r\n            return (*this) (i);\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        vector &operator = (const vector &v) {\r\n            data () = v.data ();\r\n            return *this;\r\n        }\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\n        template<class A2>          // Generic vector assignment without temporary\r\n        BOOST_UBLAS_INLINE\r\n        vector &operator = (const vector<T, A2> &v) {\r\n            resize (v.size ());\r\n            assign (v);\r\n            return *this;\r\n        }\r\n#endif\r\n        BOOST_UBLAS_INLINE\r\n        vector &assign_temporary (vector &v) {\r\n            swap (v);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector &operator = (const vector_expression<AE> &ae) {\r\n            // return assign (self_type (ae));\r\n            self_type temporary (ae);\r\n            return assign_temporary (temporary);\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector &assign (const vector_expression<AE> &ae) {\r\n            vector_assign (scalar_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector &operator += (const vector_expression<AE> &ae) {\r\n            // return assign (self_type (*this + ae));\r\n            self_type temporary (*this + ae);\r\n            return assign_temporary (temporary);\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector &plus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign (scalar_plus_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector &operator -= (const vector_expression<AE> &ae) {\r\n            // return assign (self_type (*this - ae));\r\n            self_type temporary (*this - ae);\r\n            return assign_temporary (temporary);\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector &minus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign (scalar_minus_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector &operator *= (const AT &at) {\r\n            vector_assign_scalar (scalar_multiplies_assign<reference, AT> (), *this, at);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector &operator /= (const AT &at) {\r\n            vector_assign_scalar (scalar_divides_assign<reference, AT> (), *this, at);\r\n            return *this;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (vector &v) {\r\n            if (this != &v) {\r\n                data ().swap (v.data ());\r\n            }\r\n        }\r\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (vector &v1, vector &v2) {\r\n            v1.swap (v2);\r\n        }\r\n#endif\r\n\r\n        // Element insertion and erasure\r\n        // These functions should work with std::vector.\r\n        // Thanks to Kresimir Fresl for spotting this.\r\n        BOOST_UBLAS_INLINE\r\n        void insert (size_type i, const_reference t) {\r\n            // FIXME: only works for EqualityComparable value types.\r\n            // BOOST_UBLAS_CHECK (data () [i] == value_type (0), bad_index ());\r\n            // Previously: data ().insert (data ().begin () + i, t);\r\n            data () [i] = t;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        void erase (size_type i) {\r\n            // Previously: data ().erase (data ().begin () + i);\r\n            data () [i] = value_type (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        void clear () {\r\n            // Previously: data ().clear ();\r\n            std::fill (data ().begin (), data ().end (), value_type (0));\r\n        }\r\n\r\n        // Iterator types\r\n    private:\r\n        // Use the storage array iterator\r\n        typedef typename A::const_iterator const_iterator_type;\r\n        typedef typename A::iterator iterator_type;\r\n\r\n    public:\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        typedef indexed_iterator<self_type, dense_random_access_iterator_tag> iterator;\r\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\r\n#else\r\n        class const_iterator;\r\n        class iterator;\r\n#endif\r\n\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return const_iterator (*this, data ().begin () + i);\r\n#else\r\n            return const_iterator (*this, i);\r\n#endif\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator find (size_type i) {\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return iterator (*this, data ().begin () + i);\r\n#else\r\n            return iterator (*this, i);\r\n#endif\r\n        }\r\n\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class const_iterator:\r\n            public container_const_reference<vector>,\r\n            public random_access_iterator_base<dense_random_access_iterator_tag,\r\n                                               const_iterator, value_type, difference_type> {\r\n        public:\r\n            typedef dense_random_access_iterator_tag iterator_category;\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n            typedef const_reference reference;\r\n#else\r\n            typedef typename vector::difference_type difference_type;\r\n            typedef typename vector::value_type value_type;\r\n            typedef typename vector::const_reference reference;\r\n            typedef const typename vector::pointer pointer;\r\n#endif\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const self_type &v, const const_iterator_type &it):\r\n                container_const_reference<self_type> (v), it_ (it) {}\r\n            BOOST_UBLAS_INLINE\r\n#ifndef BOOST_UBLAS_QUALIFIED_TYPENAME\r\n            const_iterator (const iterator &it):\r\n#else\r\n            const_iterator (const typename self_type::iterator &it):\r\n#endif\r\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\r\n                return *it_;\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\r\n                return it_ - (*this) ().begin ().it_;\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            const_iterator_type it_;\r\n\r\n            friend class iterator;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (data_.size ());\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class iterator:\r\n            public container_reference<vector>,\r\n            public random_access_iterator_base<dense_random_access_iterator_tag,\r\n                                               iterator, value_type, difference_type> {\r\n        public:\r\n            typedef dense_random_access_iterator_tag iterator_category;\r\n#ifndef BOOST_MSVC_STD_ITERATOR\r\n            typedef typename vector::difference_type difference_type;\r\n            typedef typename vector::value_type value_type;\r\n            typedef typename vector::reference reference;\r\n            typedef typename vector::pointer pointer;\r\n#endif\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            iterator ():\r\n                container_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            iterator (self_type &v, const iterator_type &it):\r\n                container_reference<self_type> (v), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            reference operator * () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_ , bad_index ());\r\n                return *it_;\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_ , bad_index ());\r\n                return it_ - (*this) ().begin ().it_;\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator = (const iterator &it) {\r\n                container_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            iterator_type it_;\r\n\r\n            friend class const_iterator;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        iterator begin () {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator end () {\r\n            return find (data_.size ());\r\n        }\r\n\r\n        // Reverse iterator\r\n\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\r\n#else\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n        typedef reverse_iterator_base<iterator, value_type, reference> reverse_iterator;\r\n#else\r\n        typedef reverse_iterator_base<iterator> reverse_iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rbegin () {\r\n            return reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rend () {\r\n            return reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        array_type data_;\r\n    };\r\n\r\n    // Bounded vector class\r\n    template<class T, std::size_t N>\r\n    class bounded_vector:\r\n        public vector<T, bounded_array<T, N> > {\r\n\r\n        typedef vector<T, bounded_array<T, N> > vector_type;\r\n    public:\r\n        typedef typename vector_type::size_type size_type;\r\n        BOOST_STATIC_CONSTANT (size_type,  max_size = N);\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector ():\r\n            vector_type (N) {}\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector (size_type size):\r\n            vector_type (size) {}\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector (const bounded_vector &v):\r\n            vector_type (v) {}\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\n        template<class A2>              // Allow vector<T,bounded_array<N> construction\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector (const vector<T, A2> &v):\r\n            vector_type (v) {}\r\n#endif\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector (const vector_expression<AE> &ae):\r\n            vector_type (ae) {}\r\n        BOOST_UBLAS_INLINE\r\n        ~bounded_vector () {}\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector &operator = (const bounded_vector &v) {\r\n            vector_type::operator = (v);\r\n            return *this;\r\n        }\r\n        template<class A2>              // Generic vector assignment\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector &operator = (const vector<T, A2> &v) {\r\n            vector_type::operator = (v);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        bounded_vector &operator = (const vector_expression<AE> &ae) {\r\n            vector_type::operator = (ae);\r\n            return *this;\r\n        }\r\n    };\r\n\r\n    // Unit vector class\r\n    template<class T>\r\n    class unit_vector:\r\n        public vector_expression<unit_vector<T> > {\r\n    public:\r\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\r\n        BOOST_UBLAS_USING vector_expression<unit_vector<T> >::operator ();\r\n#endif\r\n        typedef std::size_t size_type;\r\n        typedef std::ptrdiff_t difference_type;\r\n        typedef T value_type;\r\n        typedef const T &const_reference;\r\n        typedef T &reference;\r\n    private:\r\n        typedef const T *const_pointer;\r\n        typedef unit_vector<T> self_type;\r\n    public:\r\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\r\n        typedef const vector_const_reference<const self_type> const_closure_type;\r\n#else\r\n        typedef const vector_reference<const self_type> const_closure_type;\r\n#endif\r\n        typedef vector_reference<self_type> closure_type;\r\n        typedef packed_tag storage_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        unit_vector ():\r\n            vector_expression<self_type> (),\r\n            size_ (0), index_ (0) {}\r\n        BOOST_UBLAS_INLINE\r\n        explicit unit_vector (size_type size, size_type index = 0):\r\n            vector_expression<self_type> (),\r\n            size_ (size), index_ (index) {}\r\n        BOOST_UBLAS_INLINE\r\n        unit_vector (const unit_vector &v):\r\n            vector_expression<self_type> (),\r\n            size_ (v.size_), index_ (v.index_) {}\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return size_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        size_type index () const {\r\n            return index_;\r\n        }\r\n\r\n        // Resizing\r\n        BOOST_UBLAS_INLINE\r\n        void resize (size_type size, bool preserve = true) {\r\n            size_ = size;\r\n        }\r\n\r\n        // Element access\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type i) const {\r\n            if (i == index_)\r\n                return one_;\r\n            else\r\n                return zero_;\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        unit_vector &operator = (const unit_vector &v) {\r\n            size_ = v.size_;\r\n            index_ = v.index_;\r\n            return *this;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        unit_vector &assign_temporary (unit_vector &v) {\r\n            swap (v);\r\n            return *this;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (unit_vector &v) {\r\n            if (this != &v) {\r\n                std::swap (size_, v.size_);\r\n                std::swap (index_, v.index_);\r\n            }\r\n        }\r\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (unit_vector &v1, unit_vector &v2) {\r\n            v1.swap (v2);\r\n        }\r\n#endif\r\n\r\n        // Iterator types\r\n    private:\r\n        // Use an index\r\n        typedef size_type const_iterator_type;\r\n    public:\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        typedef indexed_const_iterator<self_type, packed_random_access_iterator_tag> iterator;\r\n        typedef indexed_const_iterator<self_type, packed_random_access_iterator_tag> const_iterator;\r\n#else\r\n        class const_iterator;\r\n#endif\r\n\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n            i = (std::max) (i, index_);\r\n            i = (std::min) (i, index_ + 1);\r\n            return const_iterator (*this, i);\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class const_iterator:\r\n            public container_const_reference<unit_vector>,\r\n            public random_access_iterator_base<packed_random_access_iterator_tag,\r\n                                               const_iterator, value_type> {\r\n        public:\r\n            typedef packed_random_access_iterator_tag iterator_category;\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n            typedef const_reference reference;\r\n#else\r\n            typedef typename unit_vector::difference_type difference_type;\r\n            typedef typename unit_vector::value_type value_type;\r\n            typedef typename unit_vector::const_reference reference;\r\n            typedef typename unit_vector::const_pointer pointer;\r\n#endif\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<unit_vector> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const unit_vector &v, const const_iterator_type &it):\r\n                container_const_reference<unit_vector> (v), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\r\n                return (*this) () (index ());\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\r\n                return it_;\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<unit_vector>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            const_iterator_type it_;\r\n        };\r\n\r\n        typedef const_iterator iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (size_);\r\n        }\r\n\r\n        // Reverse iterator\r\n\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\r\n#else\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        size_type size_;\r\n        size_type index_;\r\n        typedef const value_type const_value_type;\r\n        static const_value_type zero_;\r\n        static const_value_type one_;\r\n    };\r\n\r\n    template<class T>\r\n    typename unit_vector<T>::const_value_type unit_vector<T>::zero_ \r\n#ifdef BOOST_UBLAS_STATIC_OLD_INIT\r\n        = BOOST_UBLAS_TYPENAME unit_vector<T>::const_value_type\r\n#endif\r\n        (0);\r\n    template<class T>\r\n    typename unit_vector<T>::const_value_type unit_vector<T>::one_\r\n#ifdef BOOST_UBLAS_STATIC_OLD_INIT\r\n        = BOOST_UBLAS_TYPENAME unit_vector<T>::const_value_type\r\n#endif\r\n        (1);\r\n\r\n    // Zero vector class\r\n    template<class T>\r\n    class zero_vector:\r\n        public vector_expression<zero_vector<T> > {\r\n    public:\r\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\r\n        BOOST_UBLAS_USING vector_expression<zero_vector<T> >::operator ();\r\n#endif\r\n        typedef std::size_t size_type;\r\n        typedef std::ptrdiff_t difference_type;\r\n        typedef T value_type;\r\n        typedef const T &const_reference;\r\n        typedef T &reference;\r\n    private:\r\n        typedef const T *const_pointer;\r\n        typedef zero_vector<T> self_type;\r\n    public:\r\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\r\n        typedef const vector_const_reference<const self_type> const_closure_type;\r\n#else\r\n        typedef const vector_reference<const self_type> const_closure_type;\r\n#endif\r\n        typedef vector_reference<self_type> closure_type;\r\n        typedef sparse_tag storage_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        zero_vector ():\r\n            vector_expression<self_type> (),\r\n            size_ (0) {}\r\n        explicit BOOST_UBLAS_INLINE\r\n        zero_vector (size_type size):\r\n            vector_expression<self_type> (),\r\n            size_ (size) {}\r\n        BOOST_UBLAS_INLINE\r\n        zero_vector (const zero_vector &v):\r\n            vector_expression<self_type> (),\r\n            size_ (v.size_) {}\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return size_;\r\n        }\r\n\r\n        // Resizing\r\n        BOOST_UBLAS_INLINE\r\n        void resize (size_type size, bool preserve = true) {\r\n            size_ = size;\r\n        }\r\n\r\n        // Element access\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type /* i */) const {\r\n            return zero_;\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        zero_vector &operator = (const zero_vector &v) {\r\n            size_ = v.size_;\r\n            return *this;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        zero_vector &assign_temporary (zero_vector &v) {\r\n            swap (v);\r\n            return *this;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (zero_vector &v) {\r\n            if (this != &v) {\r\n                std::swap (size_, v.size_);\r\n            }\r\n        }\r\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (zero_vector &v1, zero_vector &v2) {\r\n            v1.swap (v2);\r\n        }\r\n#endif\r\n\r\n        // Iterator types\r\n    private:\r\n        // Use an index\r\n        typedef size_type const_iterator_type;\r\n    public:\r\n        class const_iterator;\r\n\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n            return const_iterator (*this, i);\r\n        }\r\n\r\n\r\n        class const_iterator:\r\n            public container_const_reference<zero_vector>,\r\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\r\n                                               const_iterator, value_type> {\r\n        public:\r\n            typedef sparse_bidirectional_iterator_tag iterator_category;\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n            typedef const_reference reference;\r\n#else\r\n            typedef typename zero_vector::difference_type difference_type;\r\n            typedef typename zero_vector::value_type value_type;\r\n            typedef typename zero_vector::const_reference reference;\r\n            typedef typename zero_vector::const_pointer pointer;\r\n#endif\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const self_type &v, const const_iterator_type &it):\r\n                container_const_reference<self_type> (v), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\r\n                return (*this) () (index ());\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\r\n                return it_;\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n\r\n        private:\r\n            const_iterator_type it_;\r\n        };\r\n\r\n        typedef const_iterator iterator;\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (size_);\r\n        }\r\n\r\n        // Reverse iterator\r\n\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\r\n#else\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        size_type size_;\r\n        typedef const value_type const_value_type;\r\n        static const_value_type zero_;\r\n    };\r\n\r\n    template<class T>\r\n    typename zero_vector<T>::const_value_type zero_vector<T>::zero_\r\n#ifdef BOOST_UBLAS_STATIC_OLD_INIT\r\n        = BOOST_UBLAS_TYPENAME zero_vector<T>::const_value_type\r\n#endif\r\n        (0);\r\n\r\n    // Scalar vector class\r\n    template<class T>\r\n    class scalar_vector:\r\n        public vector_expression<scalar_vector<T> > {\r\n    public:\r\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\r\n        BOOST_UBLAS_USING vector_expression<scalar_vector<T> >::operator ();\r\n#endif\r\n        typedef std::size_t size_type;\r\n        typedef std::ptrdiff_t difference_type;\r\n        typedef T value_type;\r\n        typedef const T &const_reference;\r\n        typedef T &reference;\r\n    private:\r\n        typedef const T *const_pointer;\r\n        typedef scalar_vector<T> self_type;\r\n    public:\r\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\r\n        typedef const vector_const_reference<const self_type> const_closure_type;\r\n#else\r\n        typedef const vector_reference<const self_type> const_closure_type;\r\n#endif\r\n        typedef dense_tag storage_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        scalar_vector ():\r\n            vector_expression<self_type> (),\r\n            size_ (0), value_ () {}\r\n        BOOST_UBLAS_INLINE\r\n        explicit scalar_vector (size_type size, const value_type &value = value_type(1)):\r\n            vector_expression<self_type> (),\r\n            size_ (size), value_ (value) {}\r\n        BOOST_UBLAS_INLINE\r\n        scalar_vector (const scalar_vector &v):\r\n            vector_expression<self_type> (),\r\n            size_ (v.size_), value_ (v.value_) {}\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return size_;\r\n        }\r\n\r\n        // Resizing\r\n        BOOST_UBLAS_INLINE\r\n        void resize (size_type size, bool preserve = true) {\r\n            size_ = size;\r\n        }\r\n\r\n        // Element access\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type i) const {\r\n            return value_;\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return value_;\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        scalar_vector &operator = (const scalar_vector &v) {\r\n            size_ = v.size_;\r\n            value_ = v.value_;\r\n            return *this;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        scalar_vector &assign_temporary (scalar_vector &v) {\r\n            swap (v);\r\n            return *this;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (scalar_vector &v) {\r\n            if (this != &v) {\r\n                std::swap (size_, v.size_);\r\n                std::swap (value_, v.value_);\r\n            }\r\n        }\r\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (scalar_vector &v1, scalar_vector &v2) {\r\n            v1.swap (v2);\r\n        }\r\n#endif\r\n\r\n        // Iterator types\r\n    private:\r\n        // Use an index\r\n        typedef size_type const_iterator_type;\r\n\r\n    public:\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> iterator;\r\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\r\n#else\r\n        class const_iterator;\r\n#endif\r\n\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n            return const_iterator (*this, i);\r\n        }\r\n\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class const_iterator:\r\n            public container_const_reference<scalar_vector>,\r\n            public random_access_iterator_base<dense_random_access_iterator_tag,\r\n                                               const_iterator, value_type> {\r\n        public:\r\n            typedef dense_random_access_iterator_tag iterator_category;\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n            typedef const_reference reference;\r\n#else\r\n            typedef typename scalar_vector::difference_type difference_type;\r\n            typedef typename scalar_vector::value_type value_type;\r\n            typedef typename scalar_vector::const_reference reference;\r\n            typedef typename scalar_vector::const_pointer pointer;\r\n#endif\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<scalar_vector> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const scalar_vector &v, const const_iterator_type &it):\r\n                container_const_reference<scalar_vector> (v), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\r\n                return (*this) () (index ());\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\r\n                return it_;\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<scalar_vector>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            const_iterator_type it_;\r\n        };\r\n\r\n        typedef const_iterator iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (size_);\r\n        }\r\n\r\n        // Reverse iterator\r\n\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\r\n#else\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        size_type size_;\r\n        value_type value_;\r\n    };\r\n\r\n    // Array based vector class\r\n    template<class T, std::size_t N>\r\n    class c_vector:\r\n        public vector_expression<c_vector<T, N> > {\r\n    public:\r\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\r\n        BOOST_UBLAS_USING vector_expression<c_vector<T, N> >::operator ();\r\n#endif\r\n        typedef std::size_t size_type;\r\n        typedef std::ptrdiff_t difference_type;\r\n        typedef T value_type;\r\n        typedef const T &const_reference;\r\n        typedef T &reference;\r\n        typedef value_type array_type[N];\r\n        typedef T *pointer;\r\n        typedef const T *const_pointer;\r\n    private:\r\n        typedef c_vector<T, N> self_type;\r\n    public:\r\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\r\n        typedef const vector_const_reference<const self_type> const_closure_type;\r\n#else\r\n        typedef const vector_reference<const self_type> const_closure_type;\r\n#endif\r\n        typedef vector_reference<self_type> closure_type;\r\n        typedef self_type vector_temporary_type;\r\n        typedef dense_tag storage_category;\r\n        typedef concrete_tag simd_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        c_vector ():\r\n            size_ (N) /* , data_ () */ {}\r\n        explicit BOOST_UBLAS_INLINE\r\n        c_vector (size_type size):\r\n            size_ (size) /* , data_ () */ {\r\n            if (size_ > N)\r\n                bad_size ().raise ();\r\n            std::fill (data_, data_ + size_, value_type (0));\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        c_vector (const c_vector &v):\r\n            size_ (v.size_) /* , data_ () */ {\r\n            if (size_ > N)\r\n                bad_size ().raise ();\r\n            *this = v;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector (const vector_expression<AE> &ae):\r\n            size_ (ae ().size ()) /* , data_ () */ {\r\n            if (size_ > N)\r\n                bad_size ().raise ();\r\n            vector_assign (scalar_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n        }\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return size_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_pointer data () const {\r\n            return data_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        pointer data () {\r\n            return data_;\r\n        }\r\n\r\n        // Resizing\r\n        BOOST_UBLAS_INLINE\r\n        void resize (size_type size, bool preserve = true) {\r\n            if (size > N)\r\n                bad_size ().raise ();\r\n            std::fill (data_ + (std::min) (size, size_), data_ + size, value_type (0));\r\n            size_ = size;\r\n        }\r\n\r\n        // Element access\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type i) const {\r\n            BOOST_UBLAS_CHECK (i < size_,  bad_index ());\r\n            return data_ [i];\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) {\r\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\r\n            return data_ [i];\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) {\r\n            return (*this) (i);\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &operator = (const c_vector &v) {\r\n            size_ = v.size_;\r\n            std::copy (v.data_, v.data_ + v.size_, data_);\r\n            return *this;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &assign_temporary (c_vector &v) {\r\n            swap (v);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &operator = (const vector_expression<AE> &ae) {\r\n            // return assign (self_type (ae));\r\n            self_type temporary (ae);\r\n            return assign_temporary (temporary);\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &assign (const vector_expression<AE> &ae) {\r\n            vector_assign (scalar_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &operator += (const vector_expression<AE> &ae) {\r\n            // return assign (self_type (*this + ae));\r\n            self_type temporary (*this + ae);\r\n            return assign_temporary (temporary);\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &plus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign (scalar_plus_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &operator -= (const vector_expression<AE> &ae) {\r\n            // return assign (self_type (*this - ae));\r\n            self_type temporary (*this - ae);\r\n            return assign_temporary (temporary);\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &minus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign (scalar_minus_assign<reference, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &operator *= (const AT &at) {\r\n            vector_assign_scalar (scalar_multiplies_assign<reference, AT> (), *this, at);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        c_vector &operator /= (const AT &at) {\r\n            vector_assign_scalar (scalar_divides_assign<reference, AT> (), *this, at);\r\n            return *this;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (c_vector &v) {\r\n            if (this != &v) {\r\n                BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\r\n                std::swap (size_, v.size_);\r\n                std::swap_ranges (data_, data_ + size_, v.data_);\r\n            }\r\n        }\r\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (c_vector &v1, c_vector &v2) {\r\n            v1.swap (v2);\r\n        }\r\n#endif\r\n\r\n        // Element insertion and erasure\r\n        BOOST_UBLAS_INLINE\r\n        void insert (size_type i, const_reference t) {\r\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\r\n            BOOST_UBLAS_CHECK (data_ [i] == value_type (0), bad_index ());\r\n            data_ [i] = t;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        void erase (size_type i) {\r\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\r\n            data_ [i] = value_type (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        void clear () {\r\n            std::fill (data_, data_ + size_, value_type (0));\r\n        }\r\n\r\n        // Iterator types\r\n    private:\r\n        // Use pointers for iterator\r\n        typedef const_pointer const_iterator_type;\r\n        typedef pointer iterator_type;\r\n\r\n    public:\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        typedef indexed_iterator<self_type, dense_random_access_iterator_tag> iterator;\r\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\r\n#else\r\n        class const_iterator;\r\n        class iterator;\r\n#endif\r\n\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return const_iterator (*this, &data_ [i]);\r\n#else\r\n            return const_iterator (*this, i);\r\n#endif\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator find (size_type i) {\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return iterator (*this, &data_ [i]);\r\n#else\r\n            return iterator (*this, i);\r\n#endif\r\n        }\r\n\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class const_iterator:\r\n            public container_const_reference<c_vector>,\r\n            public random_access_iterator_base<dense_random_access_iterator_tag,\r\n                                               const_iterator, value_type> {\r\n        public:\r\n            typedef dense_random_access_iterator_tag iterator_category;\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n            typedef const_reference reference;\r\n#else\r\n            typedef typename c_vector::difference_type difference_type;\r\n            typedef typename c_vector::value_type value_type;\r\n            typedef typename c_vector::const_reference reference;\r\n            typedef typename c_vector::const_pointer pointer;\r\n#endif\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const self_type &v, const const_iterator_type &it):\r\n                container_const_reference<self_type> (v), it_ (it) {}\r\n            BOOST_UBLAS_INLINE\r\n#ifndef BOOST_UBLAS_QUALIFIED_TYPENAME\r\n            const_iterator (const iterator &it):\r\n#else\r\n            const_iterator (const typename self_type::iterator &it):\r\n#endif\r\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\r\n                return *it_;\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\r\n                const self_type &v = (*this) ();\r\n                return it_ - v.begin ().it_;\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            const_iterator_type it_;\r\n\r\n            friend class iterator;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (size_);\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class iterator:\r\n            public container_reference<c_vector>,\r\n            public random_access_iterator_base<dense_random_access_iterator_tag,\r\n                                               iterator, value_type> {\r\n        public:\r\n            typedef dense_random_access_iterator_tag iterator_category;\r\n#ifndef BOOST_MSVC_STD_ITERATOR\r\n            typedef typename c_vector::difference_type difference_type;\r\n            typedef typename c_vector::value_type value_type;\r\n            typedef typename c_vector::reference reference;\r\n            typedef typename c_vector::pointer pointer;\r\n#endif\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            iterator ():\r\n                container_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            iterator (self_type &v, const iterator_type &it):\r\n                container_reference<self_type> (v), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            reference operator * () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\r\n                return *it_;\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\r\n                // EDG won't allow const self_type it doesn't allow friend access to it_\r\n                self_type &v = (*this) ();\r\n                return it_ - v.begin ().it_;\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator = (const iterator &it) {\r\n                container_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            iterator_type it_;\r\n\r\n            friend class const_iterator;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        iterator begin () {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator end () {\r\n            return find (size_);\r\n        }\r\n\r\n        // Reverse iterator\r\n\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\r\n#else\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n\r\n#ifdef BOOST_MSVC_STD_ITERATOR\r\n        typedef reverse_iterator_base<iterator, value_type, reference> reverse_iterator;\r\n#else\r\n        typedef reverse_iterator_base<iterator> reverse_iterator;\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rbegin () {\r\n            return reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rend () {\r\n            return reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        size_type size_;\r\n        array_type data_;\r\n    };\r\n\r\n}}}\r\n\r\n#endif\r\n", "meta": {"hexsha": "47777c3b1efef21fcb9375fdfa850b5efceefe37", "size": 58789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/vector.hpp", "max_stars_repo_name": "macaurther/DOCUSA", "max_stars_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/vector.hpp", "max_issues_repo_name": "macaurther/DOCUSA", "max_issues_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/vector.hpp", "max_forks_repo_name": "dguenms/Dawn-of-Civilization", "max_forks_repo_head_hexsha": "1c4f510af97a869637cddb4c0859759158cea5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 33.6899713467, "max_line_length": 114, "alphanum_fraction": 0.5479086224, "num_tokens": 11996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.0769608335789328, "lm_q1q2_score": 0.03134871801207569}}
{"text": "/*! file one-solver-anneal.cpp\n *\n * @copyright Licensed under MIT license by hyperQ – Ewa Hendzel\n *\n */\n\n#include <boost/program_options.hpp>\n#include <fstream>\n#include <iostream>\n#include <ctime>\n#include <random>\n\n#include <mpi.h>\n#include \"CL/sycl.hpp\"\n#include \"helpers/devices.hpp\"\n#include \"helpers/qubo_helpers.hpp\"\n#include \"model/qubo.hpp\"\n#include \"model/solution.hpp\"\n#include \"simulated_annealing/annealing.hpp\"\n\n#define SEED 1234\n\nnamespace po = boost::program_options;\nnamespace sycl = cl::sycl;\n\nusing queue_ptr = std::unique_ptr<sycl::queue>;\n\n/*!\n * @brief Constructs a linear beta schedule.\n *\n * @param a reference to a vector for storing the schedule\n * @param minimum value of beta in the annealing schedule.\n * @param maximum value of beta in the annealing schedule.\n * @param number of iterations of the algorithm.\n *\n * @returns returns schedule.\n */\nvoid construct_linear_beta_schedule(std::vector<double> &schedule,\n                                    double beta_min, double beta_max,\n                                    uint num_iter) {\n  for (auto i = 0; i < num_iter; i++) {\n    schedule[i] = beta_min + beta_max * i / static_cast<double>(num_iter - 1);\n  }\n}\n\n/*!\n * @brief Constructs a geometric beta schedule.\n *\n * @param a reference to a vector for storing the schedule\n * @param minimum value of beta in the annealing schedule.\n * @param maximum value of beta in the annealing schedule.\n * @param number of iterations of the algorithm.\n *\n */\nvoid construct_geometric_beta_schedule(std::vector<double> &schedule,\n                                       double beta_min, double beta_max,\n                                       uint num_iter) {\n  schedule[0] = beta_min;\n  auto alpha = pow(beta_max / beta_min, 1.0 / (num_iter - 1));\n  for (auto i = 1; i < num_iter; i++) {\n    schedule[i] = (schedule[i - 1]) * alpha;\n  }\n}\n\n/*!\n * @brief Compute QUBO solution in a give solution space on a given device.\n *\n * @param Instance of the proble to solve.\n * @param Accelerator device type.\n * @param beta schedule type linear or geometric.\n * @param seed for random number generator.\n * @param minimum value of beta in the annealing schedule.\n * @param maximum value of beta in the annealing schedule.\n * @param number of iterations of the algorithm.\n * @param number of trajectories to try.\n *\n * @returns solution to the given QUBO problem and acclerator device name.\n */\nstd::tuple<qubo::Solution, std::string> sycl_native_anneal(qubo::QUBOModel<int, double> instance, std::string device_type, std::string schedule_type, std::uint64_t seed, double beta_min, double beta_max, uint num_iter, uint num_tries)\n{\n  queue_ptr q_ptr;\n  std::string accl_device_name;\n\n  try {\n    q_ptr = queue_ptr(\n        new sycl::queue(*devices::construct_device_selector(device_type)));\n  } catch (std::runtime_error) {\n    std::cerr << \"No devices of given type could be initialized.\"\n              << std::endl;\n  }\n  \n  accl_device_name = q_ptr->get_device().get_info<sycl::info::device::name>();\n  // std::cout << \"Node ID [\" << machine_name << \"], \" << \"Rank [\" << rank << \"], \" << \"Using device: \"\n  //           << q_ptr->get_device().get_info<sycl::info::device::name>()\n  //           << std::endl;\n\n  std::vector<double> beta_schedule(num_iter);\n\n  if (schedule_type == \"linear\") {\n    construct_linear_beta_schedule(beta_schedule, beta_min, beta_max,\n                                   num_iter);\n  } else {\n    construct_geometric_beta_schedule(beta_schedule, beta_min, beta_max,\n                                      num_iter);\n  }\n\n  auto solution =\n      sa::anneal(instance, *q_ptr, beta_schedule, seed, num_iter, num_tries);\n\n  return {solution, accl_device_name};\n}\n\n/*!\n * @brief Parse command line.\n * @param argument count.\n * @param arguments array.\n *\n * @returns returns input file name, output file name, device type, beta_min, beta_max, \n *                  number of iteration and number of tries.\n */\nstd::tuple<std::string, std::string, std::string, std::string, double, double, uint, uint> parse_cmd_line_anneal(int argc, char *argv[])\n{\n  std::string input_file;\n  std::string output_file;\n  std::string schedule_type;\n  std::string device_type;\n\n  uint num_iter;\n  uint num_tries;\n\n  double beta_min, beta_max;\n\n  po::options_description options(\"Allowed options\");\n  options.add_options()(\"help\", \"produce help message\")(\n     \"input\", po::value<std::string>(&input_file), \"input file\")(\n     \"output\", po::value<std::string>(&output_file), \"output file\")(\n     \"num-iter\", po::value<uint>(&num_iter)->default_value(100),\n     \"number of iterations of the algorithm\")(\n     \"num-tries\", po::value<uint>(&num_tries)->default_value(100),\n     \"number of trajectories to try\")(\n     \"schedule-type\",\n     po::value<std::string>(&schedule_type)->default_value(\"geometric\"),\n     \"type of beta schedule to use, either linear or geometric\")(\n     \"beta-min\", po::value<double>(&beta_min)->default_value(0.1),\n     \"minimum value of beta in the annealing schedule (default 0.1)\")(\n     \"beta-max\", po::value<double>(&beta_max)->default_value(1.0),\n     \"maximum value of beta in the annealing schedule (default 1.0)\")(\n     \"device-type\",\n     po::value<std::string>(&device_type)->default_value(\"host\"),\n     \"device type to use (cpu, gpu or host)\");\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << std::endl;\n    MPI_Abort(MPI_COMM_WORLD, MPI_SUCCESS);\n  }\n\n  if (!vm.count(\"input\")) {\n    throw std::runtime_error(\"No input file provided.\");\n  }\n\n  if (!vm.count(\"output\")) {\n    throw std::runtime_error(\"No output file provided.\");\n  }\n\n  if (device_type != \"cpu\" && device_type != \"gpu\" && device_type != \"host\") {\n    throw std::runtime_error(\"Unknown device type: \" + device_type);\n  }\n\n  if (schedule_type != \"linear\" && schedule_type != \"geometric\") {\n    throw std::runtime_error(\"Unknown beta schedule: \" + schedule_type);\n  }\n\n  if (beta_max < 0 || beta_min < 0) {\n    throw std::runtime_error(\"Invalid schedule, both ends of beta range need to be positive.\");\n  }\n\n  if (beta_min >= beta_max) {\n    throw std::runtime_error(\"Invalid schedule, initial beta is not lesser than final beta.\");\n  }\n  \n  return {input_file, output_file, device_type, schedule_type, beta_min, beta_max, num_iter, num_tries};\n}\n\nint main(int argc, char *argv[]) {\n  const clock_t begin_time = clock();\n\n  char machine_name[MPI_MAX_PROCESSOR_NAME];\n  int name_len = 0;\n  int rank = 0;\n  const int root_rank = 0; // Rank zero process.\n  int min_energy_process_rank = 0; // Rank of process with minimum energy.\n  int num_procs = 0;\n  int size = 0;\n  \n  long long int msg_size = 0;\n\n  std::string input_file;\n  std::string output_file;\n  std::string schedule_type;\n  std::string device_type;\n  std::vector<char> msg_buff;\n  std::uint64_t *seed_buff = NULL;\n  std::uint64_t seed;\n  \n  uint num_iter;\n  uint num_tries;\n  uint param_buff[2];\n\n  double beta_min, beta_max;\n  double beta_buff[2];\n\n  qubo::QUBOModel<int, double> instance;\n\n  try {\n    // Start MPI.\n    if (MPI_Init(&argc, &argv) != MPI_SUCCESS) {\n      throw std::runtime_error(\"Failed to initialize MPI\\n\");\n    }\n\n    // Create the communicator, and retrieve the number of MPI ranks.\n    MPI_Comm_size(MPI_COMM_WORLD, &num_procs);\n\n    // Determine the rank number.\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    \n    // Get the machine name.\n    MPI_Get_processor_name(machine_name, &name_len);\n\n    if (rank == root_rank) {\n      // Parse command line to get the parameters.\n      std::tie(input_file, output_file, device_type, schedule_type, beta_min, beta_max, num_iter, num_tries) = parse_cmd_line_anneal(argc, argv);\n\n      std::cout << \"Reading input from: \" << input_file << std::endl;\n\n      std::cout << \"Output will be saved to: \" << output_file << std::endl;\n\n      std::cout << \"Schedule type: \" << schedule_type << std::endl;\n\n      std::cout << \"Beta range: [\" << beta_min << \", \" << beta_max << \"]\"\n                << std::endl;\n\n      std::cout << \"Number of iterations: \" << num_iter << std::endl;\n      std::cout << \"Number of tries: \" << num_tries << std::endl;\n\n      std::ifstream qubo_file(input_file);\n\n      if (!qubo_file) {\n        std::cerr << \"can not open input file: \" << input_file << std::endl;\n        return -1;\n      }\n\n      qubo_file.unsetf(std::ios::skipws);\n      instance = qubo::QUBOModel<int, double>::load(qubo_file);\n\n      std::ostringstream oss;\n      // save data to archive\n      {\n         boost::archive::text_oarchive ar(oss);\n         // write class instance to archive\n         ar << instance;\n         // archive and stream closed when destructors are called.\n      }\n#ifdef DEBUG\n      std::cout << \"sSize: \" << oss.str().size() << std::endl;\n      std::cout << \"sData: \" << oss.str().c_str() << std::endl;\n#endif\n      msg_buff.assign(oss.str().c_str(), oss.str().c_str() + oss.str().size() +1);\n      msg_size = oss.str().size();\n    }\n\n    // Send QUBOModel instance to all the proecesses.\n    if (MPI_Bcast(&msg_size, 1, MPI_LONG_LONG_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    } \n  \n    if (rank != root_rank) {\n      msg_buff.resize(msg_size);\n    }\n\n    if (MPI_Bcast(msg_buff.data(), msg_size, MPI_CHAR, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n    \n    if (rank != root_rank) {\n      if (msg_buff.size() > 0) {\n        std::istringstream iss(std::string(msg_buff.data(), msg_buff.size()));\n#ifdef DEBUG\n        std::cout << \"rSize: \" << iss.str().size() << std::endl;\n        std::cout << \"rData: \" << iss.str().c_str() << std::endl;\n#endif\n        {\n          boost::archive::text_iarchive ar(iss);   \n          ar >> instance;\n        }\n      }\n    }\n\n    // Send device_type to all the processes.\n    if (rank == root_rank) {\n      msg_size = device_type.size();\n      msg_buff.assign(device_type.c_str(),device_type.c_str() + device_type.size() +1);\n    }\n  \n    if (MPI_Bcast(&msg_size, 1, MPI_LONG_LONG_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n\n    if (rank != root_rank) {\n      msg_buff.resize(msg_size);\n    }\n  \n    if (MPI_Bcast(msg_buff.data(), msg_size, MPI_CHAR, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n\n    if (rank != root_rank) {\n      device_type = std::string(&msg_buff[0], msg_size);\n#ifdef DEBUG\n      std::cout << \"device_type: \" << device_type << std::endl;\n#endif\n    }\n\n    // Send schedule_type to all the processes.\n    if (rank == root_rank) {\n      msg_size = schedule_type.size();\n      msg_buff.assign(schedule_type.c_str(),schedule_type.c_str() + schedule_type.size() +1);\n    }\n  \n    if (MPI_Bcast(&msg_size, 1, MPI_LONG_LONG_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n\n    if (rank != root_rank) {\n      msg_buff.resize(msg_size);\n    }\n  \n    if (MPI_Bcast(msg_buff.data(), msg_size, MPI_CHAR, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n\n    if (rank != root_rank) {\n      schedule_type = std::string(&msg_buff[0], msg_size);\n#ifdef DEBUG\n      std::cout << \"schedule_type: \" << schedule_type << std::endl;\n#endif\n    }\n\n    // Send beta_min and beta_max to all the processes.\n    if(rank == root_rank){\n      beta_buff[0] = beta_min;\n      beta_buff[1] = beta_max;\n    }\n\n    if (MPI_Bcast(&beta_buff, 2, MPI::DOUBLE, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n\n    if (rank != root_rank) {\n      beta_min = beta_buff[0];\n      beta_max = beta_buff[1];\n#ifdef DEBUG\n      std::cout << \"Beta range: [\" << beta_min << \", \" << beta_max << \"]\"\n                << std::endl;\n#endif\n    }\n\n    // Send num_iter and num_tries to all the processes.\n    if (rank == root_rank) {\n      param_buff[0] = num_iter;\n      param_buff[1] = num_tries;\n    }\n\n    if (MPI_Bcast(&param_buff, 2, MPI_UNSIGNED, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n\n    if (rank != root_rank) {\n      num_iter = param_buff[0];\n      num_tries = param_buff[1];\n#ifdef DEBUG\n      std::cout << \"Number of iterations: \" << num_iter << std::endl;\n      std::cout << \"Number of tries: \" << num_tries << std::endl;\n#endif\n    }\n\n    // Send the seed for random number generator to all the processes.\n    if (rank == root_rank) {\n      seed_buff = new std::uint64_t[num_procs];\n      // Seed generation using mt19937_64 i.e 64 bit Mersenne Twister by Matsumoto, 2000.\n      //std::random_device rd; // for non-deterministic generator uncomment this line and\n      std::mt19937_64 gen(SEED); // replace SEED with rd() in mersenne twister.\n                                 \n      for (auto i=0; i < num_procs; ++i) {\n        seed_buff[i] = gen();\n#ifdef DEBUG\n        std::cout << \"seed: \" << seed_buff[i] << std::endl;\n#endif\n      }    \n    }\n    \n    if (MPI_Scatter(seed_buff, 1, MPI_INT64_T, &seed, 1, MPI_INT64_T, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI scatter failed\\n\");\n    }\n    \n    if (rank == root_rank) {\n      delete [] seed_buff;\n    }\n\n#ifdef DEBUG   \n    std::cout << \"seed: \" << seed << std::endl;\n#endif\n\n    auto [solution, accl_device_name] = sycl_native_anneal(instance, device_type, schedule_type, seed, beta_min, beta_max, num_iter, num_tries);\n\n    if(rank == root_rank){\n      //std::unique_ptr<char> log_buff_ptr(new char[100]);\n      MPI_Status status;\n      int msg_length;\n      \n      //char log_buff_ptr[100];\n      std::cout << \"Node ID [\" << machine_name << \"], \" << \"Rank [\" << rank << \"], \" << \"Using device: \" << accl_device_name << std::endl;\n      for(auto rank_indx = 1; rank_indx < num_procs; ++rank_indx){\n        MPI_Probe(rank_indx, 1, MPI_COMM_WORLD, &status);\n        MPI_Get_count(&status, MPI_CHAR, &msg_length);\n\n        std::unique_ptr<char> log_buff_ptr(new char[msg_length]{});\n\n        MPI_Recv(log_buff_ptr.get(), msg_length, MPI_CHAR, rank_indx, 1 , MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n        std::string log_msg(log_buff_ptr.get());\n        //std::cout << log_buff_ptr.get() << std::endl;\n        std::cout << log_msg;\n      }\n    }else{\n      std::ostringstream log_stream;\n      log_stream << \"Node ID [\" << machine_name << \"], \" << \"Rank [\" << rank << \"], \" << \"Using device: \" << accl_device_name << std::endl;\n      MPI_Send(log_stream.str().c_str(), log_stream.str().size(), MPI_CHAR, root_rank, 1, MPI_COMM_WORLD);\n    }\n\n    std::unique_ptr<double> energy_buff_ptr(new double[num_procs]);\n\n    if (MPI_Gather(&solution.energy, 1, MPI_DOUBLE, energy_buff_ptr.get(), 1, MPI_DOUBLE, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI gather failed\\n\");\n    }\n\n    if (rank == root_rank) {\n       std::vector<double> energies(&energy_buff_ptr.get()[0], &energy_buff_ptr.get()[num_procs]);\n       auto min_energy = std::min_element(energies.begin(), energies.end());\n       auto min_idx_energy = std::distance(energies.begin(), min_energy);\n#ifdef DEBUG\n       std::cout << \"min_energy: \" << energies[min_idx_energy] << std::endl;\n#endif\n       solution.energy = energies[min_idx_energy];\n\n       min_energy_process_rank = min_idx_energy;\n    }\n\n    if (MPI_Bcast(&min_energy_process_rank, 1, MPI_INT, root_rank, MPI_COMM_WORLD) != MPI_SUCCESS) {\n      throw std::runtime_error(\"MPI broadcast failed\\n\");\n    }\n\n    if ((min_energy_process_rank != root_rank) && (rank == min_energy_process_rank)) {\n       auto state = solution.state; \n       if (MPI_Send(state.data(), state.size(), MPI_CHAR, root_rank, 0, MPI_COMM_WORLD) != MPI_SUCCESS) {\n         throw std::runtime_error(\"MPI send failed\\n\");\n        }\n    }\n\n    if (rank == root_rank) {\n      if (min_energy_process_rank != 0) {\n        MPI_Status status;\n        int msg_length;\n        \n        // Probe msg size\n        MPI_Probe(min_energy_process_rank, 0, MPI_COMM_WORLD, &status);\n        MPI_Get_count(&status, MPI_CHAR, &msg_length);\n        \n        std::unique_ptr<char> buff_ptr(new char[msg_length]{});\n\n        if (MPI_Recv(buff_ptr.get(), msg_length, MPI_CHAR, min_energy_process_rank, root_rank, MPI_COMM_WORLD, MPI_STATUS_IGNORE) != MPI_SUCCESS) {\n         throw std::runtime_error(\"MPI receive failed\\n\");\n        }\n        //std::cout << buff_ptr.get();\n#ifdef DEBUG\n        std::cout << \"Min Energy State: \";\n        for (auto i = 0; i < solution.state.size(); ++i) {\n        std::cout << (int)buff_ptr.get()[i] << \" \";\n        }\n        std::cout << std::endl;\n#endif\n        for (auto i=0; i < solution.state.size(); ++i ) {\n          solution.state[i] = buff_ptr.get()[i];\n        } \n      }\n\n#ifdef DEBUG\n      std::cout << \"Min Energy State: \"\n      for (auto i = 0; i < solution.state.size(); ++i) {\n        std::cout << (int)solution.state[i] << \" \";\n      }\n      std::cout << std::endl;\n#endif\n      std::ofstream results_file(output_file);\n      solution.save(results_file);\n      results_file.close();\n    }\n\n  } catch (std::exception &e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);\n  } catch (...) {\n    std::cerr << \"Exception of unknown type!\\n\";\n  }\n\n  if (rank == root_rank) {\n    std::cout << \"Calculation time [s]: \"<< float( clock () - begin_time ) /  CLOCKS_PER_SEC << \"\\n\";\n  }\n\n  MPI_Finalize();\n  return 0;\n}", "meta": {"hexsha": "29794e11e6507a7646c22490ab584e5c459cb811", "size": 17604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/one-solver-anneal.cpp", "max_stars_repo_name": "quantumz-io/oneSolver", "max_stars_repo_head_hexsha": "a5c3b3a2ce1eef3e237f121a836bb8a5f8aeac51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T13:27:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T13:27:38.000Z", "max_issues_repo_path": "src/one-solver-anneal.cpp", "max_issues_repo_name": "quantumz-io/oneSolver", "max_issues_repo_head_hexsha": "a5c3b3a2ce1eef3e237f121a836bb8a5f8aeac51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/one-solver-anneal.cpp", "max_forks_repo_name": "quantumz-io/oneSolver", "max_forks_repo_head_hexsha": "a5c3b3a2ce1eef3e237f121a836bb8a5f8aeac51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T12:36:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T08:35:16.000Z", "avg_line_length": 33.5954198473, "max_line_length": 234, "alphanum_fraction": 0.6269597819, "num_tokens": 4601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.06560484385324576, "lm_q1q2_score": 0.03126593359166681}}
{"text": "#include <list>\n#include <algorithm>\n#include <math.h>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n\n#include \"FixVec.hpp\"\n#include \"Boundary.hpp\"\n#include \"DOFAdmin.hpp\"\n#include \"ElInfo.hpp\"\n// #include \"Expressions.hpp\"\n#include \"FiniteElemSpace.hpp\"\n#include \"Global.hpp\"\n#include \"Mesh.hpp\"\n#include \"Quadrature.hpp\"\n#include \"BoundaryManager.hpp\"\n#include \"Assembler.hpp\"\n#include \"Operator.hpp\"\n#include \"Initfile.hpp\"\n#include \"Traverse.hpp\"\n// #include \"DualTraverse.hpp\"\n#include \"MatrixVectorOperations.hpp\"\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n#include \"parallel/MpiHelper.hpp\"\n#include \"parallel/MeshDistributor.hpp\"\n#endif\n\n#include <expressions/Expressions.hpp>\n\n// Defining the interface for MTL4\nnamespace mtl\n{\n  // Let MTL4 know that DOFVector it is a column vector\n  namespace traits\n  {\n    template <class T>\n    struct category<AMDiS::DOFVector<T>>\n    {\n      typedef tag::dense_col_vector type;\n    };\n  } // end namepsace traits\n\n\n  namespace ashape\n  {\n    template <class T>\n    struct ashape<AMDiS::DOFVector<T>>\n    {\n      typedef cvec<typename ashape<T>::type> type;\n    };\n  } // end namespace ashape\n\n  // Modelling Collection and MutableCollection\n  template <class T>\n  struct Collection<AMDiS::DOFVector<T>>\n  {\n    typedef T               value_type;\n    typedef const T&        const_reference;\n    typedef std::size_t     size_type;\n  };\n\n  template <typename T>\n  struct MutableCollection<AMDiS::DOFVector<T>>\n        : public Collection<AMDiS::DOFVector<T>>\n  {\n    typedef T&              reference;\n  };\n\n} // namespace mtl\n\n\n\nnamespace AMDiS\n{\n  template <class T>\n  DOFVector<T>::DOFVector(const FiniteElemSpace* f, std::string n, bool addToSynch)\n    : DOFVectorBase<T>(f, n)\n  {\n    vec.resize(0);\n    init(f, n, addToSynch);\n  }\n\n\n  template <class T>\n  void DOFVector<T>::init(const FiniteElemSpace* f, std::string n, bool /*addToSynch*/) // NOTE: parameter addToSynch only for PARALLEL_DOMAIN\n  {\n    this->name = n;\n    this->feSpace = f;\n    if (this->feSpace && this->feSpace->getAdmin())\n      (this->feSpace->getAdmin())->addDOFIndexed(this);\n    this->boundaryManager = new BoundaryManager(f);\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    if (addToSynch && Parallel::MeshDistributor::globalMeshDistributor != NULL)\n      Parallel::MeshDistributor::globalMeshDistributor->addInterchangeVector(this);\n#endif\n  }\n\n\n  template <class T>\n  DOFVector<T>::~DOFVector()\n  {\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    if ( Parallel::MeshDistributor::globalMeshDistributor != NULL)\n      Parallel::MeshDistributor::globalMeshDistributor->removeInterchangeVector(this);\n#endif\n    if (this->feSpace && this->feSpace->getAdmin())\n      (this->feSpace->getAdmin())->removeDOFIndexed(this);\n\n    if (this->boundaryManager)\n      delete this->boundaryManager;\n\n    vec.clear();\n  }\n\n\n  template <class T>\n  double DOFVector<T>::squareNrm2() const\n  {\n    checkFeSpace(this->feSpace, vec);\n\n    double nrm = 0.0;\n    Iterator vecIterator(dynamic_cast<DOFIndexed<T>*>(const_cast<DOFVector<T>*>(this)),\n                         USED_DOFS);\n    for (vecIterator.reset(); !vecIterator.end(); ++vecIterator)\n      nrm += (*vecIterator) * (*vecIterator);\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(nrm);\n#endif\n\n    return nrm;\n  }\n\n  template <class T>\n  double DOFVector<T>::nrm2() const\n  {\n    return std::sqrt(squareNrm2());\n  }\n\n\n  template <class T>\n  T DOFVector<T>::asum() const\n  {\n    checkFeSpace(this->feSpace, vec);\n\n    double nrm = 0.0;\n    Iterator vecIterator(dynamic_cast<DOFIndexed<T>*>(const_cast<DOFVector<T>*>(this)),\n                         USED_DOFS);\n    for (vecIterator.reset(); !vecIterator.end(); ++vecIterator)\n      nrm += std::abs(*vecIterator);\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(nrm);\n#endif\n\n    return nrm;\n  }\n\n\n  template <class T>\n  T DOFVector<T>::sum() const\n  {\n    checkFeSpace(this->feSpace, vec);\n\n    double nrm = 0.0;\n    Iterator vecIterator(dynamic_cast<DOFIndexed<T>*>(const_cast<DOFVector<T>*>(this)),\n                         USED_DOFS);\n    for (vecIterator.reset(); !vecIterator.end(); ++vecIterator)\n      nrm += *vecIterator;\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(nrm);\n#endif\n\n    return nrm;\n  }\n\n\n  template <class T>\n  void DOFVector<T>::set(T alpha)\n  {\n    checkFeSpace(this->feSpace, vec);\n\n    Iterator vecIterator(dynamic_cast<DOFIndexed<T>*>(this), USED_DOFS);\n    for (vecIterator.reset(); !vecIterator.end(); ++vecIterator)\n      *vecIterator = alpha ;\n  }\n\n\n  template <class T>\n  void DOFVector<T>::copy(DOFVector<T> const& x)\n  {\n    FUNCNAME_DBG(\"DOFVector<T>::copy()\");\n\n    checkFeSpace(this->feSpace, vec);\n\n    TEST_EXIT_DBG(static_cast<int>(x.vec.size()) >=\n                  this->feSpace->getAdmin()->getUsedSize())\n    (\"x.size = %d too small: admin->sizeUsed = %d\\n\", x.vec.size(),\n     this->feSpace->getAdmin()->getUsedSize());\n\n    Iterator vecIterator(dynamic_cast<DOFIndexed<T>*>(this), USED_DOFS);\n    Iterator xIterator(dynamic_cast<DOFVector<T>*>(const_cast<DOFVector<T>*>(&x)),\n                       USED_DOFS);\n    for (vecIterator.reset(), xIterator.reset(); !vecIterator.end();\n         ++vecIterator, ++xIterator)\n      *vecIterator = *xIterator;\n  }\n\n\n  template <class T>\n  T DOFVector<T>::min() const\n  {\n    checkFeSpace(this->feSpace, vec);\n\n    T m;\n    Iterator vecIterator(const_cast<DOFIndexed<T>*>(dynamic_cast<const DOFIndexed<T>*>(this)), USED_DOFS);\n    for (vecIterator.reset(), m = *vecIterator; !vecIterator.end(); ++vecIterator)\n      m = std::min(m, *vecIterator);\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalMin(m);\n#endif\n\n    return m;\n  }\n\n\n  template <class T>\n  T DOFVector<T>::max() const\n  {\n    checkFeSpace(this->feSpace, vec);\n\n    T m;\n    Iterator vecIterator(const_cast<DOFIndexed<T>*>(dynamic_cast<const DOFIndexed<T>*>(this)), USED_DOFS);\n    for (vecIterator.reset(), m = *vecIterator; !vecIterator.end(); ++vecIterator)\n      m = std::max(m, *vecIterator);\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalMax(m);\n#endif\n\n    return m;\n  }\n\n\n  template <class T>\n  T DOFVector<T>::absMax() const\n  {\n    return std::max(std::abs(max()), std::abs(min()));\n  }\n\n\n  template <class T>\n  T DOFVector<T>::average() const\n  {\n    checkFeSpace(this->feSpace, vec);\n\n    int count = 0;\n    T m = 0;\n    Iterator vecIterator(const_cast<DOFIndexed<T>*>(dynamic_cast<const DOFIndexed<T>*>(this)), USED_DOFS);\n    for (vecIterator.reset(); !vecIterator.end(); ++vecIterator)\n    {\n      m += *vecIterator;\n      count++;\n    }\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(m);\n    Parallel::mpi::globalAdd(count);\n#endif\n\n    return m / count;\n  }\n\n\n  template <class T>\n  size_t DOFVector<T>::calcMemoryUsage() const\n  {\n    size_t result = 0;\n    result += sizeof(DOFVector<T>);\n    result += vec.size() * sizeof(T);\n\n    return result;\n  }\n\n\n  template <class T>\n  T DOFVector<T>::Int(int meshLevel, Quadrature* q) const\n  {\n    Mesh* mesh = this->feSpace->getMesh();\n\n    if (!q)\n    {\n      int deg = 2 * this->feSpace->getBasisFcts()->getDegree();\n      q = Quadrature::provideQuadrature(this->dim, deg);\n    }\n\n    FastQuadrature* quadFast =\n      FastQuadrature::provideFastQuadrature(this->feSpace->getBasisFcts(), *q, INIT_PHI);\n\n    Flag flag = Mesh::FILL_COORDS | Mesh::FILL_DET;\n    if (meshLevel == -1)\n      flag |= Mesh::CALL_LEAF_EL;\n    else\n      flag |= Mesh::CALL_EL_LEVEL;\n\n    T result;\n    nullify(result);\n    int nPoints = quadFast->getNumPoints();\n    DenseVector<T> uh_vec(nPoints);\n    TraverseStack stack;\n    ElInfo* elInfo =  stack.traverseFirst(mesh, meshLevel, flag);\n    while (elInfo)\n    {\n      double det = elInfo->getDet();\n      T normT;\n      nullify(normT);\n      this->getVecAtQPs(elInfo, NULL, quadFast, uh_vec);\n      for (int iq = 0; iq < nPoints; iq++)\n        normT += quadFast->getWeight(iq) * (uh_vec[iq]);\n      result += det * normT;\n\n      elInfo = stack.traverseNext(elInfo);\n    }\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(result);\n#endif\n\n    return result;\n  }\n\n\n  template <class T>\n  double DOFVector<T>::L1Norm(Quadrature* q) const\n  {\n    Mesh* mesh = this->feSpace->getMesh();\n\n    if (!q)\n    {\n      int deg = 2 * this->feSpace->getBasisFcts()->getDegree();\n      q = Quadrature::provideQuadrature(this->dim, deg);\n    }\n\n    FastQuadrature* quadFast =\n      FastQuadrature::provideFastQuadrature(this->feSpace->getBasisFcts(), *q, INIT_PHI);\n\n    double result = 0.0;\n    int nPoints = quadFast->getNumPoints();\n    DenseVector<T> uh_vec(nPoints);\n    TraverseStack stack;\n    ElInfo* elInfo =\n      stack.traverseFirst(mesh, -1,\n                          Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS | Mesh::FILL_DET);\n    while (elInfo)\n    {\n      double det = elInfo->getDet();\n      double normT = 0.0;\n      this->getVecAtQPs(elInfo, NULL, quadFast, uh_vec);\n      for (int iq = 0; iq < nPoints; iq++)\n        normT += quadFast->getWeight(iq) * std::abs(uh_vec[iq]);\n      result += det * normT;\n\n      elInfo = stack.traverseNext(elInfo);\n    }\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(result);\n#endif\n\n    return result;\n  }\n\n\n  template <class T>\n  double DOFVector<T>::L2NormSquare(Quadrature* q) const\n  {\n    using math::sqr;\n    Mesh* mesh = this->feSpace->getMesh();\n\n    if (!q)\n    {\n      int deg = 2 * this->feSpace->getBasisFcts()->getDegree();\n      q = Quadrature::provideQuadrature(this->dim, deg);\n    }\n\n    FastQuadrature* quadFast =\n      FastQuadrature::provideFastQuadrature(this->feSpace->getBasisFcts(), *q, INIT_PHI);\n\n    double result = 0.0;\n    int nPoints = quadFast->getNumPoints();\n    DenseVector<T> uh_vec(nPoints);\n    TraverseStack stack;\n    ElInfo* elInfo =\n      stack.traverseFirst(mesh, -1,\n                          Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS | Mesh::FILL_DET);\n    while (elInfo)\n    {\n      double det = elInfo->getDet();\n      double normT = 0.0;\n      this->getVecAtQPs(elInfo, NULL, quadFast, uh_vec);\n      for (int iq = 0; iq < nPoints; iq++)\n        normT += quadFast->getWeight(iq) * sqr(uh_vec[iq]);\n      result += det * normT;\n\n      elInfo = stack.traverseNext(elInfo);\n    }\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(result);\n#endif\n\n    return result;\n  }\n\n\n  template <class T>\n  double DOFVector<T>::H1NormSquare(Quadrature* q) const\n  {\n    using math::sqr;\n    Mesh* mesh = this->feSpace->getMesh();\n\n    if (!q)\n    {\n      int deg = 2 * this->feSpace->getBasisFcts()->getDegree() - 2;\n      q = Quadrature::provideQuadrature(this->dim, deg);\n    }\n\n    FastQuadrature* quadFast =\n      FastQuadrature::provideFastQuadrature(this->feSpace->getBasisFcts(), *q, INIT_GRD_PHI);\n\n    double result = 0.0;\n    int nPoints = quadFast->getNumPoints();\n    int dimOfWorld = Global::getGeo(WORLD);\n    DenseVector<WorldVector<T>> grduh_vec(nPoints);\n    TraverseStack stack;\n    ElInfo* elInfo =\n      stack.traverseFirst(mesh, -1,\n                          Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS |\n                          Mesh::FILL_DET | Mesh::FILL_GRD_LAMBDA);\n    while (elInfo)\n    {\n      double det = elInfo->getDet();\n      double normT = 0.0;\n      this->getGrdAtQPs(elInfo, NULL, quadFast, grduh_vec);\n\n      for (int iq = 0; iq < nPoints; iq++)\n      {\n        double norm2 = 0.0;\n        for (int j = 0; j < dimOfWorld; j++)\n          norm2 += sqr(grduh_vec[iq][j]);\n        normT += quadFast->getWeight(iq) * norm2;\n      }\n\n      result += det * normT;\n\n      elInfo = stack.traverseNext(elInfo);\n    }\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(result);\n#endif\n\n    return result;\n  }\n\n\n\n  template <class T>\n  bool DOFVector<T>::getDofIdxAtPoint(WorldVector<double>& p,\n                                      DegreeOfFreedom& idx,\n                                      ElInfo* oldElInfo,\n                                      bool useOldElInfo) const\n  {\n    Mesh* mesh = this->feSpace->getMesh();\n    const BasisFunction* basFcts = this->feSpace->getBasisFcts();\n\n    int dim = mesh->getDim();\n    int numBasFcts = basFcts->getNumber();\n\n    std::vector<DegreeOfFreedom> localIndices(numBasFcts);\n    DimVec<double> lambda(dim);\n\n    ElInfo* elInfo = mesh->createNewElInfo();\n    idx = 0;\n    int inside = 0;\n\n    if (oldElInfo && useOldElInfo && oldElInfo->getMacroElement())\n    {\n      inside = mesh->findElInfoAtPoint(p, elInfo, lambda, oldElInfo->getMacroElement(), NULL, NULL);\n      delete oldElInfo;\n    }\n    else\n    {\n      inside = mesh->findElInfoAtPoint(p, elInfo, lambda, NULL, NULL, NULL);\n    }\n\n    if (oldElInfo)\n      oldElInfo = elInfo;\n\n    if (inside == 0)\n    {\n      delete elInfo;\n      return false;\n    }\n\n    basFcts->getLocalIndices(elInfo->getElement(), this->feSpace->getAdmin(), localIndices);\n\n    WorldVector<double> coord;\n    int minIdx = -1;\n    double minDist = 1.e15;\n\n    for (int i = 0; i < numBasFcts; i++)\n    {\n      elInfo->coordToWorld(*(basFcts->getCoords(i)), coord);\n      double newDist = norm(coord - p);\n      if (newDist < minDist)\n      {\n        minIdx = i;\n        minDist = newDist;\n        if (minDist < 1.e-10)\n          break;\n      }\n    }\n\n    if (minIdx >= 0)\n      idx = localIndices[minIdx];\n\n    if(!oldElInfo) delete elInfo;\n    return inside != 0;\n  }\n\n\n  template <class T>\n  void DOFVector<T>::compressDOFIndexed(int first, int last,\n                                        std::vector<DegreeOfFreedom>& newDOF)\n  {\n    for (int i = first; i <= last; i++)\n      if (newDOF[i] >= 0)\n        vec[newDOF[i]] = vec[i];\n  }\n\n\n  template <class T>\n  DOFVector<T>& DOFVector<T>::operator=(const DOFVector<T>& rhs)\n  {\n    this->feSpace = rhs.feSpace;\n    this->dim = rhs.dim;\n    this->nBasFcts = rhs.nBasFcts;\n    vec = rhs.vec;\n    this->elementVector.change_dim(this->nBasFcts);\n    this->operators = rhs.operators;\n    this->operatorFactor = rhs.operatorFactor;\n\n    if (rhs.boundaryManager)\n    {\n      if (this->boundaryManager)\n        delete this->boundaryManager;\n\n      this->boundaryManager = new BoundaryManager(*rhs.boundaryManager);\n    }\n    else\n    {\n      this->boundaryManager = NULL;\n    }\n\n    return *this;\n  }\n\n\n  template <class T>\n  double DOFVector<T>::DoubleWell(Quadrature* q) const\n  {\n    using math::sqr;\n    Mesh* mesh = this->feSpace->getMesh();\n\n    if (!q)\n    {\n      int deg = 2 * this->feSpace->getBasisFcts()->getDegree();\n      q = Quadrature::provideQuadrature(this->dim, deg);\n    }\n\n    FastQuadrature* quadFast =\n      FastQuadrature::provideFastQuadrature(this->feSpace->getBasisFcts(), *q, INIT_PHI);\n\n    double result = 0.0;\n    int nPoints = quadFast->getNumPoints();\n    DenseVector<T> uh_vec(nPoints);\n    TraverseStack stack;\n    ElInfo* elInfo =\n      stack.traverseFirst(mesh, -1,\n                          Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS | Mesh::FILL_DET);\n    while (elInfo)\n    {\n      double det = elInfo->getDet();\n      double normT = 0.0;\n      this->getVecAtQPs(elInfo, NULL, quadFast, uh_vec);\n      for (int iq = 0; iq < nPoints; iq++)\n        normT += quadFast->getWeight(iq) * sqr(uh_vec[iq]) * sqr(1.0 - uh_vec[iq]);\n      result += det * normT;\n\n      elInfo = stack.traverseNext(elInfo);\n    }\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(result);\n#endif\n\n    return result;\n  }\n\n\n  template <class T>\n  DOFVector<Gradient_t<T>>*\n                        DOFVector<T>::getGradient(DOFVector<Gradient_t<T>>* grad) const\n  {\n    FUNCNAME_DBG(\"DOFVector<T>::getGradient()\");\n    const FiniteElemSpace* feSpace = DOFVector<T>::feSpace;\n\n    // define result vector\n    static DOFVector<Gradient_t<T>>* result = NULL; // TODO: REMOVE STATIC\n\n    if (grad)\n    {\n      result = grad;\n    }\n    else\n    {\n      if(result && result->getFeSpace() != feSpace)\n      {\n        delete result;\n        result = new DOFVector<Gradient_t<T>>(feSpace, \"gradient\");\n      }\n    }\n\n    Mesh* mesh = feSpace->getMesh();\n    int dim = mesh->getDim();\n    const BasisFunction* basFcts = feSpace->getBasisFcts();\n    DOFAdmin* admin = feSpace->getAdmin();\n\n    // count number of nodes and dofs per node\n    std::vector<int> nNodeDOFs;\n    std::vector<int> nNodePreDofs;\n    std::vector<DimVec<double>*> bary;\n\n    int nNodes = 0;\n    int nDofs = 0;\n\n    for (int i = 0; i < dim + 1; i++)\n    {\n      GeoIndex geoIndex = INDEX_OF_DIM(i, dim);\n      int nPositions = mesh->getGeo(geoIndex);\n      int numPreDofs = admin->getNumberOfPreDofs(i);\n      for (int j = 0; j < nPositions; j++)\n      {\n        int dofs = basFcts->getNumberOfDofs(geoIndex);\n        nNodeDOFs.push_back(dofs);\n        nDofs += dofs;\n        nNodePreDofs.push_back(numPreDofs);\n      }\n      nNodes += nPositions;\n    }\n\n    TEST_EXIT_DBG(nDofs == basFcts->getNumber())\n    (\"number of dofs != number of basis functions\\n\");\n\n    for (int i = 0; i < nDofs; i++)\n      bary.push_back(basFcts->getCoords(i));\n\n    DenseVector<T> localUh(basFcts->getNumber());\n\n    // traverse mesh\n    std::vector<bool> visited(getUsedSize(), false);\n    TraverseStack stack;\n    Flag fillFlag = Mesh::CALL_LEAF_EL | Mesh::FILL_GRD_LAMBDA | Mesh::FILL_COORDS;\n    ElInfo* elInfo = stack.traverseFirst(mesh, -1, fillFlag);\n\n    while (elInfo)\n    {\n      const DegreeOfFreedom** dof = elInfo->getElement()->getDof();\n      auto& grdLambda = elInfo->getGrdLambda();\n      this->getLocalVector(elInfo->getElement(), localUh);\n\n      int localDOFNr = 0;\n      for (int i = 0; i < nNodes; i++)   // for all nodes\n      {\n        for (int j = 0; j < nNodeDOFs[i]; j++)   // for all dofs at this node\n        {\n          DegreeOfFreedom dofIndex = dof[i][nNodePreDofs[i] + j];\n          if (!visited[dofIndex])\n          {\n            basFcts->evalGrdUh(*(bary[localDOFNr]), grdLambda,\n                               localUh, ((*result)[dofIndex]));\n\n            visited[dofIndex] = true;\n          }\n          localDOFNr++;\n        }\n      }\n\n      elInfo = stack.traverseNext(elInfo);\n    }\n\n    return result;\n  }\n\n\n  template <class T>\n  DOFVector<Gradient_t<T>>*\n                        DOFVector<T>::getRecoveryGradient(DOFVector<Gradient_t<T>>* grad) const\n  {\n    const FiniteElemSpace* feSpace = DOFVector<T>::feSpace;\n    int dim = DOFVector<T>::dim;\n\n    // define result vector\n    static DOFVector<Gradient_t<T>>* vec = NULL; // TODO: REMOVE STATIC\n\n    DOFVector<Gradient_t<T>>* result = grad;\n\n    if (!result)\n    {\n      if (vec && vec->getFeSpace() != feSpace)\n      {\n        delete vec;\n        vec = NULL;\n      }\n      if (!vec)\n        vec = new DOFVector<Gradient_t<T>>(feSpace, \"gradient\");\n\n      result = vec;\n    }\n\n    Gradient_t<T> grd;\n    nullify(grd);\n\n    result->set(grd);\n\n    DOFVector<double> volume(feSpace, \"volume\");\n    volume.set(0.0);\n\n    const BasisFunction* basFcts = feSpace->getBasisFcts();\n    int nBasisFcts = basFcts->getNumber();\n    DimVec<double> bary(dim, (1.0 / (dim + 1.0)));\n\n    // traverse mesh\n    Mesh* mesh = feSpace->getMesh();\n    TraverseStack stack;\n    ElInfo* elInfo = stack.traverseFirst(mesh, -1,\n                                         Mesh::CALL_LEAF_EL | Mesh::FILL_DET |\n                                         Mesh::FILL_GRD_LAMBDA | Mesh::FILL_COORDS);\n\n    DenseVector<T> localUh(nBasisFcts);\n    std::vector<DegreeOfFreedom> localIndices(nBasisFcts);\n\n    while (elInfo)\n    {\n      double det = elInfo->getDet();\n      auto& grdLambda = elInfo->getGrdLambda();\n      this->getLocalVector(elInfo->getElement(), localUh);\n      basFcts->evalGrdUh(bary, grdLambda, localUh, grd);\n      basFcts->getLocalIndices(elInfo->getElement(), feSpace->getAdmin(), localIndices);\n\n      for (int i = 0; i < nBasisFcts; i++)\n      {\n        (*result)[localIndices[i]] += grd * det;\n        volume[localIndices[i]] += det;\n      }\n\n      elInfo = stack.traverseNext(elInfo);\n\n    }\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::MeshDistributor::globalMeshDistributor->checkMeshChange(false);\n    Parallel::MeshDistributor::globalMeshDistributor->synchAddVector(*result);\n    Parallel::MeshDistributor::globalMeshDistributor->synchAddVector(volume);\n#endif\n\n    DOFVector<double>::Iterator volIt(&volume, USED_DOFS);\n    typename DOFVector<Gradient_t<T>>::Iterator grdIt(result, USED_DOFS);\n\n    for (volIt.reset(), grdIt.reset(); !volIt.end(); ++volIt, ++grdIt)\n      if (*volIt != 0.0)\n        *grdIt *= 1.0 / (*volIt);\n\n    return result;\n  }\n  \n  \n  \n  template <class T>\n  void DOFVector<T>::coarseRestrictImpl(Id<double>, RCNeighbourList& list, int n)\n  {\n    FUNCNAME(\"DOFVector<double>::coarseRestrict()\");\n\n    switch (this->coarsenOperation)\n    {\n    case NO_OPERATION:\n      return;\n      break;\n    case COARSE_RESTRICT:\n      (const_cast<BasisFunction*>(this->feSpace->getBasisFcts()))->coarseRestr(this, &list, n);\n      break;\n    case COARSE_INTERPOL:\n      TEST_EXIT_DBG(this->feSpace)(\"Should not happen!\\n\");\n      TEST_EXIT_DBG(this->feSpace->getBasisFcts())(\"Shoud not happen!\\n\");\n\n      (const_cast<BasisFunction*>(this->feSpace->getBasisFcts()))->coarseInter(this, &list, n);\n      break;\n    default:\n      WARNING(\"Invalid coarsen operation \\\"%d\\\" in vector \\\"%s\\\"\\n\",\n              this->coarsenOperation, this->name.c_str());\n    }\n  }\n\n\n  template <class T>\n  void DOFVector<T>::refineInterpolImpl(Id<double>, RCNeighbourList& list, int n)\n  {\n    switch (this->refineOperation)\n    {\n    case NO_OPERATION:\n      return;\n      break;\n    case REFINE_INTERPOL:\n    default:\n      (const_cast<BasisFunction*>(this->feSpace->getBasisFcts()))->refineInter(this, &list, n);\n      break;\n    }\n  }\n\n\n  template <class T>\n  void DOFVector<T>::refineInterpolImpl(Id<WorldVector<double>>, RCNeighbourList& list, int n)\n  {\n    if (this->refineOperation == NO_OPERATION)\n      return;\n\n    if (n < 1)\n      return;\n\n    Element* el = list.getElement(0);\n    int n0 = this->feSpace->getAdmin()->getNumberOfPreDofs(VERTEX);\n    DegreeOfFreedom dof0 = el->getDof(0, n0);\n    DegreeOfFreedom dof1 = el->getDof(1, n0);\n    DegreeOfFreedom dof_new = el->getChild(0)->getDof(this->feSpace->getMesh()->getDim(), n0);\n    vec[dof_new] = vec[dof0];\n    vec[dof_new] += vec[dof1];\n    vec[dof_new] *= 0.5;\n  }\n\n\n  template <class T>\n  double DOFVector<T>::evalAtPointImpl(Id<double>,\n      WorldVector<double> const& p,\n      ElInfo* oldElInfo) const\n  {\n    Mesh* mesh = this->feSpace->getMesh();\n    const BasisFunction* basFcts = this->feSpace->getBasisFcts();\n\n    int dim = mesh->getDim();\n    int nBasFcts = basFcts->getNumber();\n\n    std::vector<DegreeOfFreedom> localIndices(nBasFcts);\n    DimVec<double> lambda(dim);\n\n    ElInfo* elInfo = mesh->createNewElInfo();\n    double value = 0.0;\n    int inside = 0;\n\n    if (oldElInfo && oldElInfo->getMacroElement())\n    {\n      inside = mesh->findElInfoAtPoint(p, elInfo, lambda, oldElInfo->getMacroElement(), NULL, NULL);\n      delete oldElInfo;\n    }\n    else\n      inside = mesh->findElInfoAtPoint(p, elInfo, lambda, NULL, NULL, NULL);\n\n    if (oldElInfo)\n      oldElInfo = elInfo;\n\n    if (inside > 0)\n    {\n      basFcts->getLocalIndices(elInfo->getElement(), this->feSpace->getAdmin(), localIndices);\n      DenseVector<double> uh(nBasFcts);\n      for (int i = 0; i < nBasFcts; i++)\n        uh[i] = operator[](localIndices[i]);\n      value = basFcts->evalUh(lambda, uh);\n    }\n    else\n    {\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n      value = 0.0;\n#else\n      ERROR_EXIT(\"Can not eval DOFVector at point p, because point is outside geometry.\");\n#endif\n    }\n\n\n    if (oldElInfo == NULL)\n      delete elInfo;\n\n#ifdef HAVE_PARALLEL_DOMAIN_AMDIS\n    Parallel::mpi::globalAdd(value);\n#endif\n    return value;\n  }\n\n\n  template <class T>\n  WorldVector<double> DOFVector<T>::evalAtPointImpl(Id<WorldVector<double>>,\n        WorldVector<double> const& p,\n        ElInfo* oldElInfo) const\n  {\n    Mesh* mesh = this->feSpace->getMesh();\n    const BasisFunction* basFcts = this->feSpace->getBasisFcts();\n\n    int dim = mesh->getDim();\n    int nBasFcts = basFcts->getNumber();\n\n    std::vector<DegreeOfFreedom> localIndices(nBasFcts);\n    DimVec<double> lambda(dim);\n    ElInfo* elInfo = mesh->createNewElInfo();\n    WorldVector<double> value(DEFAULT_SIZE, 0.0);\n    int inside = 0;\n\n    if (oldElInfo && oldElInfo->getMacroElement())\n    {\n      inside = mesh->findElInfoAtPoint(p, elInfo, lambda, oldElInfo->getMacroElement(), NULL, NULL);\n      delete oldElInfo;\n    }\n    else\n      inside = mesh->findElInfoAtPoint(p, elInfo, lambda, NULL, NULL, NULL);\n\n    if (oldElInfo)\n      oldElInfo = elInfo;\n\n    if (inside > 0)\n    {\n      basFcts->getLocalIndices(elInfo->getElement(), this->feSpace->getAdmin(), localIndices);\n      DenseVector<WorldVector<double>> uh(nBasFcts);\n      for (int i = 0; i < nBasFcts; i++)\n        uh[i] = operator[](localIndices[i]);\n      value = basFcts->evalUh(lambda, uh);\n    }\n    else\n    {\n      ERROR_EXIT(\"Can not eval DOFVector at point p, because point is outside geometry.\");\n    }\n\n    if (oldElInfo == NULL)\n      delete elInfo;\n\n    return value;\n  }\n\n\n  template <class T>\n  std::vector<DOFVector<double>*>* transform(DOFVector<Gradient_t<T>>* vec,\n      std::vector<DOFVector<double>*>* res)\n  {\n    FUNCNAME_DBG(\"DOFVector<T>::transform()\");\n\n    TEST_EXIT_DBG(vec)(\"no vector\\n\");\n\n    static std::vector<DOFVector<double>*>* result = NULL; // TODO: REMOVE STATIC\n\n    int len = num_rows(GradientType<T>::getValues((*vec)[0]));\n\n    if (!res && !result)\n    {\n      result = new std::vector<DOFVector<double>*>(len);\n      for (int i = 0; i < len; i++)\n        (*result)[i] = new DOFVector<double>(vec->getFeSpace(), \"transform\");\n    }\n    else if (res->size() == 0 || (*res)[0] == NULL)\n    {\n      res->resize(len, NULL);\n      for (int i = 0; i < len; i++)\n        (*res)[i] = new DOFVector<double>(vec->getFeSpace(), \"transform\");\n    }\n\n    std::vector<DOFVector<double>*>* r = res ? res : result;\n\n    int vecSize = vec->getSize();\n    for (int i = 0; i < vecSize; i++)\n      for (int j = 0; j < len; j++)\n        (*((*r)[j]))[i] = (GradientType<T>::getValues((*vec)[i]))[j];\n\n    return r;\n  }\n\n\n  template<typename T>\n  DOFVector<T>& DOFVector<T>::operator*=(T scal)\n  {\n    FUNCNAME_DBG(\"DOFVector<T>::operator*=(T scal)\");\n\n    TEST_EXIT_DBG(this->getFeSpace() && this->getFeSpace()->getAdmin())\n    (\"pointer is NULL: %8X, %8X\\n\", this->getFeSpace(), this->getFeSpace()->getAdmin());\n\n    DOFIterator<T> xIterator(this, USED_DOFS);\n    for (xIterator.reset(); !xIterator.end(); ++xIterator)\n      (*xIterator) *= scal;\n\n    return *this;\n  }\n\n\n  template<typename T>\n  DOFVector<T>& DOFVector<T>::operator+=(DOFVector<T> const& y)\n  {\n    FUNCNAME_DBG(\"DOFVector<T>::operator+=(const DOFVector<T>& y)\");\n\n    TEST_EXIT_DBG(this->getFeSpace() && y.getFeSpace())\n    (\"feSpace is NULL: %8X, %8X\\n\", this->getFeSpace(), y.getFeSpace());\n    TEST_EXIT_DBG(this->getFeSpace()->getAdmin() &&\n                  (this->getFeSpace()->getAdmin() == y.getFeSpace()->getAdmin()))\n    (\"no admin or different admins: %8X, %8X\\n\",\n     this->getFeSpace()->getAdmin(), y.getFeSpace()->getAdmin());\n    TEST_EXIT_DBG(this->getSize() == y.getSize())(\"different sizes\\n\");\n\n    DOFIterator<T> xIterator(this, USED_DOFS);\n    DOFConstIterator<T> yIterator(&y, USED_DOFS);\n    for (xIterator.reset(), yIterator.reset(); !xIterator.end(); ++xIterator, ++yIterator)\n      *xIterator += *yIterator;\n\n    return *this;\n  }\n\n\n  template<typename T>\n  DOFVector<T>& DOFVector<T>::operator-=(DOFVector<T> const& y)\n  {\n    FUNCNAME_DBG(\"DOFVector<T>::operator-=(const DOFVector<T>& y)\");\n\n    TEST_EXIT_DBG(this->getFeSpace() && y.getFeSpace())\n    (\"feSpace is NULL: %8X, %8X\\n\", this->getFeSpace(), y.getFeSpace());\n    TEST_EXIT_DBG(this->getFeSpace()->getAdmin() &&\n                  (this->getFeSpace()->getAdmin() == y.getFeSpace()->getAdmin()))\n    (\"no admin or different admins: %8X, %8X\\n\",\n     this->getFeSpace()->getAdmin(), y.getFeSpace()->getAdmin());\n    TEST_EXIT_DBG(this->getSize() == y.getSize())(\"different sizes\\n\");\n\n    DOFIterator<T> xIterator(this, USED_DOFS);\n    DOFConstIterator<T> yIterator(&y, USED_DOFS);\n    for (xIterator.reset(), yIterator.reset(); !xIterator.end(); ++xIterator, ++yIterator)\n      *xIterator -= *yIterator;\n\n    return *this;\n  }\n\n\n  template<typename T>\n  DOFVector<T>& DOFVector<T>::operator*=(DOFVector<T> const& y)\n  {\n    FUNCNAME_DBG(\"DOFVector<T>::operator*=(const DOFVector<T>& y)\");\n\n    TEST_EXIT_DBG(this->getFeSpace() && y.getFeSpace())\n    (\"feSpace is NULL: %8X, %8X\\n\", this->getFeSpace(), y.getFeSpace());\n    TEST_EXIT_DBG(this->getFeSpace()->getAdmin() &&\n                  (this->getFeSpace()->getAdmin() == y.getFeSpace()->getAdmin()))\n    (\"no admin or different admins: %8X, %8X\\n\",\n     this->getFeSpace()->getAdmin(), y.getFeSpace()->getAdmin());\n    TEST_EXIT_DBG(this->getSize() == y.getSize())(\"different sizes\\n\");\n\n    DOFIterator<T> xIterator(this, USED_DOFS);\n    DOFConstIterator<T> yIterator(&y, USED_DOFS);\n    for (xIterator.reset(), yIterator.reset(); !xIterator.end(); ++xIterator, ++yIterator)\n      *xIterator *= *yIterator;\n\n    return *this;\n  }\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "8f7ade1a6b0d50afd3b6c241ee5b5f7dc1894d4a", "size": 29249, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/DOFVector.hh", "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/DOFVector.hh", "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/DOFVector.hh", "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": 27.0573543016, "max_line_length": 142, "alphanum_fraction": 0.6184143048, "num_tokens": 8413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.06278921385835866, "lm_q1q2_score": 0.030904106112319894}}
{"text": "/*\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef cl_utilities_adjoint_hpp\n#define cl_utilities_adjoint_hpp\n#pragma once\n\n#include <ql/math/matrix.hpp>\n#include <boost/timer.hpp>\n#include <boost/date_time.hpp>\n\nnamespace QuantLib\n{\n    struct PerformanceTime\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Number of independent variables\", \"Tape recording time\", \"Adjoint calculations time\", \"No Adjoint calculations time\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, PerformanceTime& v)\n        {\n                stm << v.indepVarNumber_\n                    << \";\" << v.timeTapeRecording_\n                    << \";\" << v.timeAdjoint_\n                    << \";\" << v.timeAnalytical_ << std::endl;\n\n                return stm;\n            }\n\n        double timeTapeRecording_;\n        double timeAdjoint_;\n        double timeAnalytical_;\n        Size indepVarNumber_;\n    };\n\n    struct AdjointTime\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Number of independent variables\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, AdjointTime& v)\n        {\n                stm << v.indepVarNumber_\n                    << \";\" << v.timeAdjoint_\n                    << std::endl;\n                return stm;\n            }\n\n        double timeAdjoint_;\n        Size indepVarNumber_;\n    };\n\n    struct TapeSize\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Number of independent variables\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, TapeSize& v)\n        {\n                stm << v.indepVarNumber_\n                    << \";\" << v.memory_ / 1048576.0\n                    << std::endl;\n                return stm;\n            }\n\n        Size indepVarNumber_;\n        Size memory_;\n    };\n\n    inline std::string currentTime()\n    {\n        boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();\n        std::stringstream ss;\n        ss << now.time_of_day().hours() << \"h  \" << now.time_of_day().minutes() << \"m  \"\n            << now.time_of_day().seconds() << \"s  \" << now.time_of_day().fractional_seconds() << \"mcs\";\n        return ss.str();\n    }\n\n    // checking consistency of elements of three vectors\n    inline bool checkConsistencyWithBC(\n        const std::vector<double>& forwardMode,\n        const std::vector<double>& reverseMode,\n        const std::vector<Real>& theoretical,\n        double relativeTol, double absTol = 1e-10)\n    {\n        bool result = true;\n        int n = theoretical.size();\n        if (theoretical.size() != forwardMode.size())\n        {\n            std::cout << \"Forward mode and Theoretical results vectors size mismatch.\\n\";\n            return false;\n        }\n        if (theoretical.size() != reverseMode.size())\n        {\n            std::cout << \"Reverse mode and Theoretical results vectors size mismatch.\\n\";\n            return false;\n        }\n        std::vector<double>::const_iterator fwd = forwardMode.begin();\n        std::vector<double>::const_iterator rev = reverseMode.begin();\n        std::vector<Real  >::const_iterator thr = theoretical.begin();\n        for (int i = 0; i < n; ++i, ++thr, ++fwd, ++rev)\n        {\n            Real maxabs = std::max(std::abs(*thr), std::max(std::abs(*fwd), std::abs(*rev)));\n            Real tol = relativeTol * maxabs + absTol;\n            if (std::abs(*fwd - *thr) > tol)\n            {\n                result = false;\n                std::cout << \"Forward mode derivative[\" << i << \"] and Theoretical results mismatch.\"\n                    << \"\\n    forward mode:      \" << *fwd\n                    << \"\\n    theoretical:       \" << *thr\n                    << \"\\n    tolerance:  \" << tol << std::endl;\n            }\n            if (std::abs(*rev - *thr) > tol)\n            {\n                result = false;\n                std::cout << \"Reverse mode derivative[\" << i << \"] and Theoretical results mismatch.\"\n                    << \"\\n    reverse mode:      \" << *rev\n                    << \"\\n    theoretical:       \" << *thr\n                    << \"\\n    tolerance:  \" << tol << std::endl;\n            }\n        }\n        return result;\n    }\n\n\n    // checking consistency of elements of three vectors\n    inline bool checkConsistencyWithFD(\n        const std::vector<double>& forwardMode,\n        const std::vector<double>& reverseMode,\n        const std::vector<Real>& finiteDiff,\n        double relativeTol, double absTol = 1e-10)\n    {\n        bool result = true;\n        int n = finiteDiff.size();\n        if (finiteDiff.size() != forwardMode.size())\n        {\n            std::cout << \"Forward mode and Finite difference vectors size mismatch.\\n\";\n            return false;\n        }\n        if (finiteDiff.size() != reverseMode.size())\n        {\n            std::cout << \"Reverse mode and Finite difference vectors size mismatch.\\n\";\n            return false;\n        }\n        std::vector<double>::const_iterator fwd = forwardMode.begin();\n        std::vector<double>::const_iterator rev = reverseMode.begin();\n        std::vector<Real  >::const_iterator fin = finiteDiff.begin();\n        for (int i = 0; i < n; ++i, ++fin, ++fwd, ++rev)\n        {\n            Real maxabs = std::max(std::abs(*fin), std::max(std::abs(*fwd), std::abs(*rev)));\n            Real tol = relativeTol * maxabs + absTol;\n            if (std::abs(*fwd - *fin) > tol)\n            {\n                result = false;\n                std::cout << \"Forward mode and Finite difference derivative[\" << i << \"] mismatch.\"\n                    << \"\\n    forward mode:      \" << *fwd\n                    << \"\\n    finite difference: \" << *fin\n                    << \"\\n    tolerance:  \" << tol << std::endl;\n            }\n            if (std::abs(*rev - *fin) > tol)\n            {\n                result = false;\n                std::cout << \"Reverse mode and Finite difference derivative[\" << i << \"] mismatch.\"\n                    << \"\\n    reverse mode:      \" << *rev\n                    << \"\\n    finite difference: \" << *fin\n                    << \"\\n    tolerance:  \" << tol << std::endl;\n            }\n            if (std::abs(*rev - *fwd) > tol)\n            {\n                result = false;\n                std::cout << \"Forward mode and Reverse mode derivative[\" << i << \"] mismatch.\"\n                    << \"\\n    forward mode:      \" << *fwd\n                    << \"\\n    reverse mode:      \" << *rev\n                    << \"\\n    tolerance:  \" << tol << std::endl;\n            }\n        }\n        return result;\n    }\n\n\n    // computes gradient in Forward AD mode and outputs results\n    inline double gradForward(cl::tape_function<double>& f,\n        std::vector<double>& grad,\n        bool timeOutput,\n        bool gradOutput)\n    {\n        using namespace std;\n        size_t n = f.Domain();\n        size_t m = f.Range();\n        grad.resize(m*n);\n        vector<double> dx(n), dy(m);\n\n\n        const size_t iterNum = 10;\n        boost::timer timer;\n        timer.restart();\n        for (size_t k = 0; k < iterNum; k++)\n        {\n            for (size_t i = 0; i < n; i++)\n            {\n                dx[i] = 1;\n                dy = f.Forward(1, dx);\n                dx[i] = 0;\n                for (size_t j = 0; j < m; j++)\n                    grad[j*n + i] = dy[j];\n            }\n        }\n        double timeForward = timer.elapsed() / iterNum;\n        if (timeOutput)\n            cout << \"Time for Forward AD mode : \" << timeForward << endl;\n\n\n        if (gradOutput)\n        {\n            cout << \"Forward AD mode : \" << endl;\n            for (size_t i = 0; i < grad.size(); i++)\n                cout << \"dy\" << i / n << \"/dx\" << i % n << \"= \" << grad[i] << endl;\n        }\n        return timeForward;\n    }\n\n\n    // computes gradient in Reverse AD mode and outputs results\n    inline double gradReverse(cl::tape_function<double>& f,\n        std::vector<double>& grad,\n        bool timeOutput,\n        bool gradOutput)\n    {\n        using namespace std;\n        size_t n = f.Domain();\n        size_t m = f.Range();\n        grad.resize(m*n);\n        vector<double> dw(m), dy(n);\n\n\n        const size_t iterNum = 10;\n        boost::timer timer;\n        timer.restart();\n        for (size_t k = 0; k < iterNum; k++)\n        for (size_t i = 0; i < m; i++)\n        {\n            dw[i] = 1;\n            dy = f.Reverse(1, dw);\n            dw[i] = 0;\n            for (size_t j = 0; j < n; j++)\n                grad[i*n + j] = dy[j];\n        }\n        double timeReverse = timer.elapsed() / iterNum;\n        if (timeOutput)\n            cout << \"Time for Reverse AD mode : \" << timer.elapsed() / iterNum << endl;\n\n        if (gradOutput)\n        {\n            cout << \"Reverse AD mode : \" << endl;\n            for (size_t i = 0; i < grad.size(); i++)\n                cout << \"dy\" << i / n << \"/dx\" << i % n << \"= \" << grad[i] << endl;\n        }\n        return timeReverse;\n    }\n\n    // computes gradient in Forward AD mode and outputs results\n    inline double gradForward(cl::tape_function<double>& f,\n        std::vector<double>& grad,\n        cl::tape_empty_test_output& out,\n        bool timeOutput,\n        bool gradOutput,\n        size_t iterNum = 10)\n    {\n#ifndef CL_GRAPH_GEN\n        iterNum = 1;\n#endif\n        using namespace std;\n        out.log() << \"Start of differentiation in Forward mode:  \" << currentTime() << endl;\n        size_t n = f.Domain();\n        size_t m = f.Range();\n        grad.resize(m*n);\n        vector<double> dx(n), dy(m);\n\n        try{\n            boost::timer timer;\n            timer.restart();\n            for (size_t k = 0; k < iterNum; k++)\n            {\n                for (size_t i = 0; i < n; i++)\n                {\n                    dx[i] = 1;\n                    dy = f.Forward(1, dx);\n                    dx[i] = 0;\n                    for (size_t j = 0; j < m; j++)\n                        grad[j*n + i] = dy[j];\n                }\n            }\n            double timeForward = timer.elapsed() / iterNum;\n            if (timeOutput)\n                cout << \"Time for Forward AD mode : \" << timeForward << endl;\n\n\n            if (gradOutput)\n            {\n                cout << \"Forward AD mode : \" << endl;\n                for (size_t i = 0; i < grad.size(); i++)\n                    cout << \"dy\" << i / n << \"/dx\" << i % n << \"= \" << grad[i] << endl;\n            }\n            out.log() << \"Forward Mode Derivatives calculated successfully\" << std::endl;\n            out.log() << \"Time in Forward mode:   \" << timeForward << \"s\" << endl;\n\n            return timeForward;\n        }\n        catch (std::exception& ex)\n        {\n            out.log() << ex.what() << std::endl;\n            return 0;\n        }\n    }\n\n\n    // computes gradient in Reverse AD mode and outputs results\n    inline double gradReverse(cl::tape_function<double>& f,\n        std::vector<double>& grad,\n        cl::tape_empty_test_output& out,\n        bool timeOutput,\n        bool gradOutput,\n        size_t iterNum = 10)\n    {\n#ifndef CL_GRAPH_GEN\n        iterNum = 1;\n#endif\n        using namespace std;\n        out.log() << \"Start of differentiation in Reverse mode:   \" << currentTime() << endl;\n        size_t n = f.Domain();\n        size_t m = f.Range();\n        grad.resize(m*n);\n        vector<double> dw(m), dy(n);\n\n        try{\n            boost::timer timer;\n            timer.restart();\n            for (size_t k = 0; k < iterNum; k++)\n            for (size_t i = 0; i < m; i++)\n            {\n                dw[i] = 1;\n                dy = f.Reverse(1, dw);\n                dw[i] = 0;\n                for (size_t j = 0; j < n; j++)\n                    grad[i*n + j] = dy[j];\n            }\n            double timeReverse = timer.elapsed() / iterNum;\n            if (timeOutput)\n                cout << \"Time for Reverse AD mode : \" << timer.elapsed() / iterNum << endl;\n\n            if (gradOutput)\n            {\n                cout << \"Reverse AD mode : \" << endl;\n                for (size_t i = 0; i < grad.size(); i++)\n                    cout << \"dy\" << i / n << \"/dx\" << i % n << \"= \" << grad[i] << endl;\n            }\n\n            out.log() << \"Reverse Mode Derivatives calculated successfully\" << std::endl;\n            out.log() << \"Time in Reverse mode:   \" << timeReverse << \" s\" << endl;\n\n            return timeReverse;\n        }\n        catch (std::exception& ex)\n        {\n            out.log() << ex.what() << std::endl;\n            return 0;\n        }\n    }\n\n    // vector-matrix converters\n\n    template<class C>\n    inline Matrix vector2matrix(const C& vec, int rows, int columns)\n    {\n        Matrix A(rows, columns);\n        copy(vec.begin(), vec.end(), A.begin());\n        return A;\n    }\n\n    inline std::vector<cl::tape_double>  matrix2vector(const Matrix& A)\n    {\n        return std::vector<cl::tape_double>(A.begin(), A.end());\n    }\n\n\n    inline PerformanceTime& operator+=(PerformanceTime& left, PerformanceTime const& right)\n    {\n        left.timeAdjoint_ += right.timeAdjoint_;\n        left.timeAnalytical_ += right.timeAnalytical_;\n        left.timeTapeRecording_ += right.timeTapeRecording_;\n        return left;\n    }\n    inline PerformanceTime& operator-=(PerformanceTime& left, PerformanceTime const& right)\n    {\n        left.timeAdjoint_ -= right.timeAdjoint_;\n        left.timeAnalytical_ -= right.timeAnalytical_;\n        left.timeTapeRecording_ -= right.timeTapeRecording_;\n        return left;\n    }\n    inline PerformanceTime& operator*=(PerformanceTime& left, double right)\n    {\n        left.timeAdjoint_ *= right;\n        left.timeAnalytical_ *= right;\n        left.timeTapeRecording_ *= right;\n        return left;\n    }\n    inline PerformanceTime operator+(PerformanceTime const& left, PerformanceTime const& right)\n    {\n        PerformanceTime temp = left;\n        return temp += right;\n    }\n    inline PerformanceTime operator-(PerformanceTime const& left, PerformanceTime const& right)\n    {\n        PerformanceTime temp = left;\n        return temp -= right;\n    }\n    inline PerformanceTime operator*(double left, PerformanceTime const& right)\n    {\n        PerformanceTime temp = right;\n        return temp *= left;\n    }\n    // what = max(what, where);\n    inline void upTo(PerformanceTime & what, PerformanceTime const& where)\n    {\n        what.timeAdjoint_ = std::max(what.timeAdjoint_, where.timeAdjoint_);\n        what.timeAnalytical_ = std::max(what.timeAnalytical_, where.timeAnalytical_);\n        what.timeTapeRecording_ = std::max(what.timeTapeRecording_, where.timeTapeRecording_);\n    }\n    // what = max(what, where);\n    inline void upTo(PerformanceTime & what, double where)\n    {\n        upTo(what, PerformanceTime{ where, where, where, 0 });\n    }\n\n    inline void upTo(double & what, double const& where)\n    {\n        what = std::max(what, where);\n    }\n\n    // Dummy realization of heat equation.\n    template <class RanIt>\n    void heatbackward(RanIt first, RanIt last, double a, size_t n = 1)\n    {\n        if (last - first < 3)\n            return;\n\n        for (size_t i = 0; i < n; i++)\n        {\n            std::reverse_iterator<RanIt> prev(last);\n            auto curr = prev + 1;\n            auto next = curr + 1;\n            for (; next != std::reverse_iterator<RanIt>(first); ++curr, ++next, ++prev)\n            {\n                typename RanIt::value_type deriv = *next + *prev - 2 * (*curr);\n                *curr += 0.5 * a * deriv;\n                *prev -= 0.25 * a * deriv;\n                *next -= 0.25 * a * deriv;\n                upTo(*next, 0);\n            }\n            upTo(*curr, 0.5 * (*prev));\n        }\n    }\n\n    template <class RanIt>\n    void heat2(RanIt first, RanIt last, double a, size_t n = 1)\n    {\n        size_t size = last - first;\n        if (size < 3)\n            return;\n\n        typedef typename RanIt::value_type value_type;\n        value_type left = *first;\n        value_type right = *(last - 1);\n        value_type sum = std::accumulate(first + 1, last, *first);\n        for (size_t i = 0; i < n; i++)\n        {\n            std::vector<value_type> derivatives(size);\n            RanIt prev = first;\n            RanIt curr = prev + 1;\n            RanIt next = curr + 1;\n            derivatives[0] = *curr + left - 2 * (*first);\n            for (auto deriv = derivatives.begin() + 1; deriv != derivatives.end() - 1; ++deriv, ++curr, ++next, ++prev)\n            {\n                *deriv = *next + *prev - 2 * (*curr);\n            }\n            derivatives.back() = right + *prev - 2 * (*curr);\n            auto deriv = derivatives.begin();\n            std::for_each(first, last, [&deriv, a](value_type& v)\n            {\n                v += 0.5 * a * (*deriv++);\n            });\n        }\n    }\n\n    template <class RanIt>\n    inline void makeSmooth(RanIt first, RanIt last, double sigma = 10.0)\n    {\n        if (sigma <= 0)\n            return;\n\n        size_t n = size_t(sigma*sigma * 10 + sigma * 50) + 1;\n        double a = sigma*sigma / n;\n        heatbackward(first, last, a, n);\n        //heat2(first, last, a, n);\n    }\n\n    // Makes data in c smooth.\n    template <class Cont>\n    inline void makeSmooth(Cont& c, double sigma = 10.0)\n    {\n        makeSmooth(c.begin(), c.end(), sigma);\n    }\n\n    template <template<typename T, typename A = std::allocator<T> > class Cont>\n    inline void makeSmooth(Cont<std::string>& c, const std::string& sigma)\n    {\n        std::vector<double> v(c.size());\n        std::transform(c.begin(), c.end(), v.begin(),\n            [](std::string const& s)\n        {\n            return std::stod(s);\n        });\n\n        if (sigma == \"default\")\n        {\n            makeSmooth(v, c.size() * 0.05 + 5);\n        }\n        else\n        {\n            makeSmooth(v, std::stod(sigma));\n        }\n\n        std::transform(v.begin(), v.end(), c.begin(), [](double v)\n        {\n            std::ostringstream strs;\n            strs << v;\n            return strs.str();\n        });\n    }\n\n    template <class Key, class Cont, class Pr>\n    inline void makeSmooth(std::map<Key, Cont>& graphics, const std::string& sigma, Pr pred)\n    {\n        std::for_each(graphics.begin(), graphics.end(),\n            [&pred, &sigma](std::pair<const Key, Cont>& v)\n        {\n            if (pred(v.first))\n                makeSmooth(v.second, sigma);\n        });\n    }\n\n    template <class Key, class Cont>\n    inline void makeSmooth(std::map<Key, Cont>& graphics, const std::string& sigma)\n    {\n        makeSmooth(graphics, sigma, [](const std::string&){ return true; });\n    }\n}\n\n#endif", "meta": {"hexsha": "3fc88d00d393d119cdf7db2117b2cbece5a16474", "size": 19731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointutils.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointutils.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointutils.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 32.9398998331, "max_line_length": 133, "alphanum_fraction": 0.5013430642, "num_tokens": 4710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.07055960107345387, "lm_q1q2_score": 0.030892651438081772}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006, 2007, 2011 Ferdinando Ametrano\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2003, 2004, 2005, 2006, 2009 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/*! \\file schedule.hpp\n    \\brief date schedule\n*/\n\n#ifndef quantlib_schedule_hpp\n#define quantlib_schedule_hpp\n\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/utilities/null.hpp>\n#include <ql/time/period.hpp>\n#include <ql/time/dategenerationrule.hpp>\n#include <ql/errors.hpp>\n#include <boost/optional.hpp>\n\nnamespace QuantLib {\n\n    //! Payment schedule\n    /*! \\ingroup datetime */\n    class Schedule {\n      public:\n        /*! constructor that takes any list of dates, and optionally\n            meta information that can be used by client classes. Note\n            that neither the list of dates nor the meta information is\n            checked for plausibility in any sense. */\n        Schedule(const std::vector<Date>&,\n                 const Calendar& calendar = NullCalendar(),\n                 const BusinessDayConvention\n                                    convention = Unadjusted,\n                 boost::optional<BusinessDayConvention>\n                     terminationDateConvention = boost::none,\n                 const boost::optional<Period> tenor = boost::none,\n                 boost::optional<DateGeneration::Rule> rule = boost::none,\n                 boost::optional<bool> endOfMonth = boost::none,\n                 const std::vector<bool>& isRegular = std::vector<bool>(0));\n        /*! rule based constructor */\n        Schedule(Date effectiveDate,\n                 const Date& terminationDate,\n                 const Period& tenor,\n                 const Calendar& calendar,\n                 BusinessDayConvention convention,\n                 BusinessDayConvention terminationDateConvention,\n                 DateGeneration::Rule rule,\n                 bool endOfMonth,\n                 const Date& firstDate = Date(),\n                 const Date& nextToLastDate = Date());\n        Schedule() {}\n        //! \\name Date access\n        //@{\n        Size size() const { return dates_.size(); }\n        const Date& operator[](Size i) const;\n        const Date& at(Size i) const;\n        const Date& date(Size i) const;\n        Date previousDate(const Date& refDate) const;\n        Date nextDate(const Date& refDate) const;\n        const std::vector<Date>& dates() const { return dates_; }\n        bool hasIsRegular() const;\n        bool isRegular(Size i) const;\n        const std::vector<bool>& isRegular() const;\n        //@}\n        //! \\name Other inspectors\n        //@{\n        bool empty() const { return dates_.empty(); }\n        const Calendar& calendar() const;\n        const Date& startDate() const;\n        const Date& endDate() const;\n        bool hasTenor() const;\n        const Period& tenor() const;\n        BusinessDayConvention businessDayConvention() const;\n        bool hasTerminationDateBusinessDayConvention() const;\n        BusinessDayConvention terminationDateBusinessDayConvention() const;\n        bool hasRule() const;\n        DateGeneration::Rule rule() const;\n        bool hasEndOfMonth() const;\n        bool endOfMonth() const;\n        //@}\n        //! \\name Iterators\n        //@{\n        typedef std::vector<Date>::const_iterator const_iterator;\n        const_iterator begin() const { return dates_.begin(); }\n        const_iterator end() const { return dates_.end(); }\n        const_iterator lower_bound(const Date& d = Date()) const;\n        //@}\n        //! \\name Utilities\n        //@{\n        //! truncated schedule\n        Schedule until(const Date& truncationDate) const;\n        //@}\n      private:\n        boost::optional<Period> tenor_;\n        Calendar calendar_;\n        BusinessDayConvention convention_;\n        boost::optional<BusinessDayConvention> terminationDateConvention_;\n        boost::optional<DateGeneration::Rule> rule_;\n        boost::optional<bool> endOfMonth_;\n        Date firstDate_, nextToLastDate_;\n        std::vector<Date> dates_;\n        std::vector<bool> isRegular_;\n    };\n\n\n    //! helper class\n    /*! This class provides a more comfortable interface to the\n        argument list of Schedule's constructor.\n    */\n    class MakeSchedule {\n      public:\n        MakeSchedule();\n        MakeSchedule& from(const Date& effectiveDate);\n        MakeSchedule& to(const Date& terminationDate);\n        MakeSchedule& withTenor(const Period&);\n        MakeSchedule& withFrequency(Frequency);\n        MakeSchedule& withCalendar(const Calendar&);\n        MakeSchedule& withConvention(BusinessDayConvention);\n        MakeSchedule& withTerminationDateConvention(BusinessDayConvention);\n        MakeSchedule& withRule(DateGeneration::Rule);\n        MakeSchedule& forwards();\n        MakeSchedule& backwards();\n        MakeSchedule& endOfMonth(bool flag=true);\n        MakeSchedule& withFirstDate(const Date& d);\n        MakeSchedule& withNextToLastDate(const Date& d);\n        operator Schedule() const;\n      private:\n        Calendar calendar_;\n        Date effectiveDate_, terminationDate_;\n        boost::optional<Period> tenor_;\n        boost::optional<BusinessDayConvention> convention_;\n        boost::optional<BusinessDayConvention> terminationDateConvention_;\n        DateGeneration::Rule rule_;\n        bool endOfMonth_;\n        Date firstDate_, nextToLastDate_;\n    };\n\n\n\n    // inline definitions\n\n    inline const Date& Schedule::date(Size i) const {\n        return dates_.at(i);\n    }\n\n    inline const Date& Schedule::operator[](Size i) const {\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        return dates_.at(i);\n        #else\n        return dates_[i];\n        #endif\n    }\n\n    inline const Date& Schedule::at(Size i) const {\n        return dates_.at(i);\n    }\n\n    inline const Calendar& Schedule::calendar() const {\n        return calendar_;\n    }\n\n    inline const Date& Schedule::startDate() const {\n        return dates_.front();\n    }\n\n    inline const Date &Schedule::endDate() const { return dates_.back(); }\n\n    inline bool Schedule::hasTenor() const {\n        return tenor_ != boost::none;\n    }\n\n    inline const Period& Schedule::tenor() const {\n        QL_REQUIRE(hasTenor(),\n                   \"full interface (tenor) not available\");\n        return *tenor_;\n    }\n\n    inline BusinessDayConvention Schedule::businessDayConvention() const {\n        return convention_;\n    }\n\n    inline bool\n    Schedule::hasTerminationDateBusinessDayConvention() const {\n        return terminationDateConvention_ != boost::none;\n    }\n\n    inline BusinessDayConvention\n    Schedule::terminationDateBusinessDayConvention() const {\n        QL_REQUIRE(hasTerminationDateBusinessDayConvention(),\n                   \"full interface (termination date bdc) not available\");\n        return *terminationDateConvention_;\n    }\n\n    inline bool Schedule::hasRule() const {\n        return rule_ != boost::none;\n    }\n\n    inline DateGeneration::Rule Schedule::rule() const {\n        QL_REQUIRE(hasRule(), \"full interface (rule) not available\");\n        return *rule_;\n    }\n\n    inline bool Schedule::hasEndOfMonth() const {\n        return endOfMonth_ != boost::none;\n    }\n\n    inline bool Schedule::endOfMonth() const {\n        QL_REQUIRE(hasEndOfMonth(),\n                   \"full interface (end of month) not available\");\n        return *endOfMonth_;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "4b37cbdcc054bdcbda65aec03be916afe378fdf0", "size": 8096, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/time/schedule.hpp", "max_stars_repo_name": "japari/QuantLib", "max_stars_repo_head_hexsha": "c2670bd433289eaf98410e911d87156595ca6d67", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T01:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T17:44:12.000Z", "max_issues_repo_path": "ql/time/schedule.hpp", "max_issues_repo_name": "japari/QuantLib", "max_issues_repo_head_hexsha": "c2670bd433289eaf98410e911d87156595ca6d67", "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/time/schedule.hpp", "max_forks_repo_name": "TheOnlyDyson/QuantLib", "max_forks_repo_head_hexsha": "78a144bbc5030c9e417e810e44ee48cffe40cf70", "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": 34.8965517241, "max_line_length": 79, "alphanum_fraction": 0.6346343874, "num_tokens": 1701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.06656918897050167, "lm_q1q2_score": 0.03068951310061362}}
{"text": "﻿//******************************************************************************\r\n//  Project:\t\tWeather-based simulation framework (WBSF)\r\n//\tProgrammer:     Rémi Saint-Amant\r\n// \r\n//  It under the terms of the GNU General Public License as published by\r\n//     the Free Software Foundation\r\n//  It is provided \"as is\" without express or implied warranty.\r\n//******************************************************************************\r\n// 22-01-2019\t1.0.3\tRémi Saint-Amant\tsieve uniformly for moths reduction (optimization)\r\n// 17-04-2018\t1.0.2\tRémi Saint-Amant\tTransfer liftoff here instead of in the model\r\n// 01-01-2016\t1.0.1\tRémi Saint-Amant\tCreation\r\n//******************************************************************************\r\n#include \"stdafx.h\"\r\n#include <boost\\algorithm\\string.hpp>\r\n#include <Boost\\multi_array.hpp>\r\n#include <algorithm>\r\n#pragma warning(disable: 4275 4251)\r\n#include \"gdal_priv.h\"\r\n\r\n\r\n#include \"Basic/Statistic.h\"\r\n#include \"Basic/HourlyDatabase.h\"\r\n#include \"Basic/ModelStat.h\"\r\n#include \"FileManager/FileManager.h\"\r\n#include \"Geomatic/IWD.h\"\r\n#include \"Simulation/Dispersal.h\"\r\n#include \"Simulation/ExecutableFactory.h\"\r\n#include \"Simulation/ATM.h\"\r\n\r\n\r\n#include \"WeatherBasedSimulationString.h\"\r\n\r\n\r\nusing namespace boost;\r\nusing namespace std;\r\nusing namespace WBSF::HOURLY_DATA;\r\nusing namespace WBSF::WEATHER;\r\nusing namespace WBSF::DIMENSION;\r\n\r\n\r\nnamespace WBSF\r\n{\r\n\tenum TSBWInput { I_YEAR, I_MONTH, I_DAY, I_SEX, I_A, I_M, I_G, I_Fᵒ, I_Fᴰ, NB_SBW_INPUTS };\r\n\tstatic const char* SBW_VARIABLE_NAME[NB_SBW_INPUTS] = { \"Year\", \"Month\",\"Day\",\"sex\",\"A\", \"M\", \"G\", \"F°\", \"F\" };\r\n\r\n\t//*******************************************************************************\r\n\r\n\tstatic const double IWD_POWER = 1.0;\r\n\tstatic const double WIND_SEED_BIAS_FACTOR = 67.3 / 58.7;\r\n\r\n\tstd::string CWindStability::GetWindStabilityName(int stabType)\r\n\t{\r\n\t\tASSERT(stabType >= 0 && stabType < NB_STABILITY);\r\n\r\n\t\tstatic const StringVector WIND_STABILITY_NAME(IDS_WG_WIND_STABILITY, \"|;\");\r\n\r\n\t\treturn WIND_STABILITY_NAME[stabType];\r\n\t}\r\n\r\n\t//*******************************************************************************\r\n\r\n\tconst char* CDispersalParamters::MEMBERS_NAME[CDispersalParamters::NB_MEMBERS] = { \"World\", \"Moths\" };\r\n\r\n\r\n\t//*******************************************************************************\r\n\tconst char* CDispersal::XML_FLAG = \"Dispersal\";\r\n\tconst char* CDispersal::MEMBERS_NAME[CDispersal::NB_MEMBERS_EX] = { \"Parameters\" };\r\n\tconst int CDispersal::CLASS_NUMBER = CExecutableFactory::RegisterClass(CDispersal::GetXMLFlag(), &CDispersal::CreateObject);\r\n\r\n\tCDispersal::CDispersal()\r\n\t{\r\n\t\tClassReset();\r\n\t}\r\n\r\n\tCDispersal::CDispersal(const CDispersal& in)\r\n\t{\r\n\t\toperator=(in);\r\n\t}\r\n\r\n\tCDispersal::~CDispersal()\r\n\t{}\r\n\r\n\tvoid CDispersal::Reset()\r\n\t{\r\n\t\tCExecutable::Reset();\r\n\t\tClassReset();\r\n\t}\r\n\r\n\tvoid CDispersal::ClassReset()\r\n\t{\r\n\t\tm_name = \"Dispersal\";\r\n\t\tm_parameters.clear();\r\n\t}\r\n\r\n\tCDispersal& CDispersal::operator =(const CDispersal& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tCExecutable::operator =(in);\r\n\t\t\tm_parameters = in.m_parameters;\r\n\t\t}\r\n\r\n\t\tASSERT(*this == in);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tbool CDispersal::operator == (const CDispersal& in)const\r\n\t{\r\n\t\tbool bEqual = true;\r\n\r\n\t\tif (CExecutable::operator !=(in))bEqual = false;\r\n\t\tif (m_parameters != in.m_parameters)bEqual = false;\r\n\r\n\t\treturn bEqual;\r\n\t}\r\n\r\n\tERMsg CDispersal::GetParentInfo(const CFileManager& fileManager, CParentInfo& info, CParentInfoFilter filter)const\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tif (filter[REPLICATION])\r\n\t\t\tfilter.set(TIME_REF);\r\n\r\n\t\tmsg = m_pParent->GetParentInfo(fileManager, info, filter);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tif (filter[LOCATION])\r\n\t\t\t{\r\n\t\t\t\t//same as parent\r\n\t\t\t}\r\n\r\n\t\t\tif (filter[PARAMETER])\r\n\t\t\t{\r\n\t\t\t\t//same as parent\r\n\t\t\t}\r\n\r\n\t\t\tif (filter[REPLICATION])\r\n\t\t\t{\r\n\t\t\t\tASSERT(info.m_period.GetTType() == CTM::ATEMPORAL);\r\n\t\t\t\tinfo.m_nbReplications *= info.m_period.size();\r\n\t\t\t}\r\n\r\n\t\t\tif (filter[TIME_REF])\r\n\t\t\t{\r\n\t\t\t\tinfo.m_period.Transform(CTM(CTM::HOURLY));\r\n\t\t\t}\r\n\r\n\t\t\tif (filter[VARIABLE])\r\n\t\t\t{\r\n\t\t\t\tGetOutputDefinition(info.m_variables);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tsize_t Find(const CModelOutputVariableDefVector& vars, string name)\r\n\t{\r\n\t\tsize_t v = NOT_INIT;\r\n\r\n\t\tfor (size_t vv = 0; vv < vars.size() && v == NOT_INIT; vv++)\r\n\t\t\tif (WBSF::IsEqual(vars[vv].m_name, name))\r\n\t\t\t\tv = vv;\r\n\r\n\r\n\t\treturn v;\r\n\t}\r\n\r\n\r\n\tvoid CDispersal::GetInputDBInfo(CResultPtr& pResult, CDBMetadata& info)\r\n\t{\r\n\t\tconst CModelOutputVariableDefVector& vars = pResult->GetMetadata().GetOutputDefinition();\r\n\r\n\t\tif (!vars.empty())\r\n\t\t{\r\n\t\t\tCModelOutputVariableDefVector outputVar;\r\n\t\t\tGetOutputDefinition(outputVar);\r\n\r\n\t\t\tCTPeriod period = m_parameters.m_world.m_simulationPeriod;\r\n\t\t\tperiod.Transform(CTM::HOURLY);\r\n\r\n\t\t\tinfo.SetLocations(pResult->GetMetadata().GetLocations());\r\n\t\t\tinfo.SetParameterSet(pResult->GetMetadata().GetParameterSet());\r\n\t\t\tinfo.SetOutputDefinition(outputVar);\r\n\t\t\tinfo.SetTPeriod(period);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tERMsg CDispersal::GetOutputDefinition(const CFileManager& fileManager, CModelOutputVariableDefVector& outputVar)const\r\n\t{\r\n\t\tGetOutputDefinition(outputVar);\r\n\r\n\t\treturn ERMsg();\r\n\t}\r\n\r\n\tvoid CDispersal::GetOutputDefinition(CModelOutputVariableDefVector& outputVar)const\r\n\t{\r\n\t\toutputVar.clear();\r\n\t\tASSERT(NB_ATM_OUTPUT == 35);\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"FlightNo\", \"FlightNo\", \"\", \"Flight numero for this moth\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Age\", \"Age\", \"[0..1]\", \"Phisiological age\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Sex\", \"Sex\", \"m=0|f=1\", \"Sex of moth\", CTM(CTM::ATEMPORAL), 0));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"A\", \"A\", \"cm²\", \"Forewing surface area\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"M\", \"M\", \"g\", \"Dry weight\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Broods\", \"Broods\", \"\", \"Broods\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"G\", \"G\", \"\", \"Gravidity\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"F\", \"F\", \"\", \"F\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"State\", \"State\", \"\", \"State of moth\", CTM(CTM::ATEMPORAL), 0));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Flag\", \"Flag\", \"\", \"State flag\", CTM(CTM::ATEMPORAL), 0));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"X\", \"X\", \"m\", \"Current X coordinate\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Y\", \"Y\", \"m\", \"Current Y coordinate\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Latitude\", \"Latitude\", \"°\", \"Current latitude\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Longitude\", \"Longitude\", \"°\", \"Current longitude\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Tair\", \"Tair\", \"°C\", \"Air temperature\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Prcp\", \"Prcp\", \"mm\", \"Precipitation\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"U\", \"U\", \"km/h\", \"mean U wind speed\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"V\", \"V\", \"km/h\", \"mean V wind speed\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"W\", \"W\", \"km/h\", \"mean W wind speed\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Galt\", \"GroundAltitude\", \"m\", \"Ground altitude.\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"MH\", \"MeanHeight\", \"m\", \"Mean flight height.\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"CH\", \"CurrentHeight\", \"m\", \"Current flight height. Begin at 5 meters and end at 0.\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"MDH\", \"MeanDeltaHeight\", \"m\", \"Mean change in height\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"MothSpeed\", \"MothSpeed\", \"\", \"Moth speed without wind speed\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Wh\", \"Whorizontal\", \"km/h\", \"Mean horizontal velocity\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Wv\", \"Wvertical\", \"km/h\", \"Mean vertical velocity\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"D\", \"Direction\", \"°\", \"Direction\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Distance\", \"Distance\", \"m\", \"Distance\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"DistanceOrigine\", \"DistanceOrigine\", \"m\", \"DistanceOrigine\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"FlightTime\", \"FlightTime\", \"h\", \"FlightTime\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"LiftoffTime\", \"LiftoffTime\", \"Decimal hour\", \"\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"LandingTime\", \"LandingTime\", \"Decimal hour\", \"\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"LiftoffT\", \"LiftoffT\", \"°C\", \"Liftoff Temperature\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"LandingT\", \"LandingT\", \"°C\", \"Landing Temperature\", CTM(CTM::ATEMPORAL), 5));\r\n\t\toutputVar.push_back(CModelOutputVariableDef(\"Defoliation\", \"Defoliation\", \"\", \"Defoliation\", CTM(CTM::ATEMPORAL), 5));\r\n\r\n\t}\r\n\r\n\r\n\tvoid CDispersal::writeStruc(zen::XmlElement& output)const\r\n\t{\r\n\t\tstring test = GetMemberName(ATM_PARAMETERS);\r\n\r\n\t\tCExecutable::writeStruc(output);\r\n\t\tzen::XmlOut out(output);\r\n\t\tout[GetMemberName(ATM_PARAMETERS)](m_parameters);\r\n\t}\r\n\r\n\tbool CDispersal::readStruc(const zen::XmlElement& input)\r\n\t{\r\n\t\tCExecutable::readStruc(input);\r\n\t\tzen::XmlIn in(input);\r\n\t\tin[GetMemberName(ATM_PARAMETERS)](m_parameters);\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t//*******************************************************************************\r\n\tCGeoPoint CDispersal::GetNewPosition(const CGeoPoint& pt, double U, double V)\r\n\t{\r\n\t\t//formaula from site:http://williams.best.vwh.net/avform.htm#LL\r\n\t\t//A point{ lat, lon } is a distance d out on the tc radial from point 1 if:\r\n\t\t//This algorithm is limited to distances such that dlon <pi / 2, i.e those that extend around less than one quarter of the circumference of the earth in longitude.A completely general, but more complicated algorithm is necessary if greater distances are allowed :\r\n\r\n\t\tdouble tc = fmod(3 * PI / 2 - atan2(V, U), 2 * PI);\r\n\t\tdouble distance = sqrt(U*U + V * V);//distance in km\r\n\t\tdouble d = distance / 6371; //distance in radian 6366.71\r\n\r\n\t\tdouble lat1 = Deg2Rad(pt.m_lat);\r\n\t\tdouble lon1 = Deg2Rad(pt.m_lon);\r\n\r\n\t\tdouble lat2 = asin(sin(lat1)*cos(d) + cos(lat1)*sin(d)*cos(tc));\r\n\t\tdouble dlon = atan2(sin(tc)*sin(d)*cos(lat1), cos(d) - sin(lat1)*sin(lat2));\r\n\t\tdouble lon2 = fmod(lon1 + dlon + PI, 2 * PI) - PI;\r\n\r\n\t\tCGeoPoint pt2(Rad2Deg(lon2), Rad2Deg(lat2), PRJ_WGS_84);\r\n\t\tASSERT(fabs(pt.GetDistance(pt2) / 1000 - distance) < 0.1);\r\n\r\n\t\treturn pt2;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t//http://www.ndbc.noaa.gov/view_text_file.php?filename=44011h2013.txt.gz&dir=data/historical/stdmet/\r\n\r\n\t//http ://www.meds-sdmm.dfo-mpo.gc.ca/isdm-gdsi/azmp-pmza/met/plot-graph-eng.asp?a=12\r\n\t//http ://www.meds-sdmm.dfo-mpo.gc.ca/isdm-gdsi/azmp-pmza/met/plot-graph-eng.asp?a=12\r\n\t//www.meds - sdmm.dfo - mpo.gc.ca / alphapro / zmp / met / data / Natashquan_A_HLY01.zip\r\n\t//http://www.meds-sdmm.dfo-mpo.gc.ca/isdm-gdsi/azmp-pmza/met/index-eng.asp\r\n\t//http ://isdm.gc.ca/isdm-gdsi/waves-vagues/search-recherche/map-carte/index-eng.asp?MedsID=All&ID=&StnName=&Active=ON&Lat1=&Lat2=&Long1=&Long2=&sDate=&eDate=&typedisplay=map&Search=Get+Results\r\n\t//http://isdm.gc.ca/isdm-gdsi/waves-vagues/search-recherche/list-liste/data-donnees-eng.asp?medsid=C44255\r\n\r\n\r\n\tstruct location_compare\r\n\t{\r\n\t\tbool operator() (const CLocation& l1, const CLocation& l2) const\r\n\t\t{\r\n\t\t\treturn l1.m_lat < l2.m_lat || l1.m_lon < l2.m_lon;\r\n\t\t}\r\n\t};\r\n\r\n\r\n\tdouble SumBroods(const CNewSectionData& section, size_t vBroods)\r\n\t{\r\n\t\tdouble sumBroods = 0;\r\n\t\tfor (size_t t = 0; t < section.GetRows(); t++)\r\n\t\t\tsumBroods += section[t][vBroods][MEAN];\r\n\r\n\t\treturn sumBroods;\r\n\t}\r\n\r\n\t/*ERMsg CreateGribsFromNetCDF(CCallback& callback)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tenum VAR { V_GHT, V_T, V_U, V_V, V_W, V_PRESS, V_PRCP, V_NBV };\r\n\r\n\t\tstatic const char* VN[V_NBV] = { \"geopotential_height\",\"temperature\",\"u_unstaggered\",\"v_unstaggered\",\"w_unstaggered\",\"pressure\",\"precipitation\" };\r\n\r\n\t\tWBSF::ofStream convert;\r\n\t\tmsg = convert.open(\"D:\\\\Travaux\\\\WRF2013Test\\\\Convert.bat\");\r\n\r\n\t\tWBSF::ofStream build;\r\n\t\tmsg += build.open(\"D:\\\\Travaux\\\\WRF2013Test\\\\Build.bat\");\r\n\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tStringVector list = GetFilesList(\"D:\\\\Travaux\\\\WRF2013Test\\\\NetCDF\\\\*.nc\");\r\n\t\t\tfor (size_t i = 0; i < list.size(); i++)\r\n\t\t\t{\r\n\t\t\t\tstring file_title = GetFileTitle(list[i]);\r\n\t\t\t\tstring file_path = \"D:\\\\Travaux\\\\WRF2013Test\\\\tmp\\\\\" + file_title + \".file_list.txt\";\r\n\r\n\t\t\t\tWBSF::ofStream file_list;\r\n\r\n\t\t\t\tmsg += file_list.open(file_path);\r\n\t\t\t\tif (msg)\r\n\t\t\t\t{\r\n\r\n\t\t\t\t\tfor (size_t v = 0; v < V_NBV; v++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (size_t l = 0; l < (v!= V_PRCP ?13:1); l++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tconvert << \"gdal_translate -b \" << l+1 << \" -ot Float32 -a_ullr  145750 189000 420750 -80000 -a_srs \\\"+proj=lcc +lat_1=30 +lat_2=60 +lat_0=48.13746 +lon_0=-71.4 +x_0=0 +y_0=0 +datum=WGS84\\\" NETCDF:\\\"D:/Travaux/WRF2013Test/NetCDF/\" << file_title << \".nc\\\":\" << VN[v] << \" ./tmp/\" << file_title << \".\" << VN[v] << \".\" << l << \".tif\" << endl;\r\n\t\t\t\t\t\t\tfile_list << \"D:\\\\Travaux\\\\WRF2013Test\\\\tmp\\\\\" << file_title << \".\" << VN[v] << \".\" << l << \".tif\" << endl;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfile_list.close();\r\n\t\t\t\t\tbuild << \"gdalBuildVRT -overwrite -separate -input_file_list \" << file_path << \" D:\\\\Travaux\\\\WRF2013Test\\\\tmp\\\\\" << file_title << \".vrt\" << endl;\r\n\t\t\t\t\tbuild << \"gdal_translate -co compress=LZW -ot Float32 -co TILED=YES -co BLOCKXSIZE=128 -co BLOCKYSIZE=128 .\\\\tmp\\\\\" << file_title << \".vrt .\\\\geoTIFF\\\\\" << file_title << \".tif\" << endl << endl;\r\n\r\n\t\t\t\t\tWBSF::CopyOneFile(\"D:\\\\Travaux\\\\WRF2013Test\\\\template.inv\", \"D:\\\\Travaux\\\\WRF2013Test\\\\GeoTIFF\\\\\"+ file_title +\".inv\", false);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}*/\r\n\r\n\tERMsg CDispersal::Execute(const CFileManager& fileManager, CCallback& callback)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t//return CreateGribsFromNetCDF(callback);\r\n\r\n\t\tcallback.AddMessage(string(\"Execute dispersal with ATM-SBW version: \") + WBSF_ATM_VERSION);\r\n\r\n\r\n\t\tGIntBig test = GDALGetCacheMax64();\r\n\t\tGDALSetCacheMax64(128 * 1024 * 1024);\r\n\r\n\r\n\t\tCATMWorld world;\r\n\t\tworld.m_world_param = m_parameters.m_world;\r\n\t\tworld.m_moths_param = m_parameters.m_moths;\r\n\t\tworld.m_nb_max_threads = CTRL.m_nbMaxThreads;\r\n\r\n\t\tofStream output_file;\r\n\t\tofStream sub_hourly_file;\r\n\r\n\t\tstring DEM_filepath, gribs_filepath, hourly_DB_filepath, defoliation_filepath, host_filepath, distraction_filepath, water_filepath;\r\n\t\tstring outputPath = GetPath(fileManager);\t\t//Generate output path\r\n\t\tstring DBFilePath = GetDBFilePath(outputPath);\t\t//Generate DB file path\r\n\t\tstring outputFilePath = !m_parameters.m_world.m_outputFileTitle.empty() && m_parameters.m_world.m_bOutputSubHourly ? fileManager.GetOutputPath() + GetFileTitle(m_parameters.m_world.m_outputFileTitle) + \".csv\" : \"\";\r\n\r\n\t\t//if (!m_parameters.m_world.m_simulationPeriod.IsInside(m_parameters.m_world.m_flightPeriod))\r\n\t\t\t//msg.ajoute(\"Flight period (\" + m_parameters.m_world.m_flightPeriod.GetFormatedString() + \") must be inside simulation period (\" + m_parameters.m_world.m_simulationPeriod.GetFormatedString() + \")\");\r\n\r\n\t\tif (!m_parameters.m_world.m_DEM_name.empty())\r\n\t\t\tmsg += fileManager.MapInput().GetFilePath(m_parameters.m_world.m_DEM_name, DEM_filepath);\r\n\t\telse\r\n\t\t\tmsg.ajoute(\"A DEM must be supply\");\r\n\r\n\t\tif (!m_parameters.m_world.m_defoliation_name.empty())\r\n\t\t\tmsg += fileManager.MapInput().GetFilePath(m_parameters.m_world.m_defoliation_name, defoliation_filepath);\r\n\t\tif (!m_parameters.m_world.m_water_name.empty())\r\n\t\t\tmsg += fileManager.MapInput().GetFilePath(m_parameters.m_world.m_water_name, water_filepath);\r\n\t\tif (m_parameters.m_world.UseGribs())\r\n\t\t{\r\n\t\t\tif (!m_parameters.m_world.m_gribs_name.empty())\r\n\t\t\t\tmsg += fileManager.Gribs().GetFilePath(m_parameters.m_world.m_gribs_name, gribs_filepath);\r\n\t\t\telse\r\n\t\t\t\tmsg.ajoute(\"Gribs file is not defined\");\r\n\t\t}\r\n\r\n\t\tif ((m_parameters.m_world.UseHourlyDB() || m_parameters.m_world.m_PSource == CATMWorldParamters::PRCP_WEATHER_STATION))\r\n\t\t{\r\n\t\t\tif (!m_parameters.m_world.m_hourly_DB_name.empty())\r\n\t\t\t\tmsg += fileManager.Hourly().GetFilePath(m_parameters.m_world.m_hourly_DB_name, hourly_DB_filepath);\r\n\t\t\telse\r\n\t\t\t\tmsg.ajoute(\"Hourly database is not defined\");\r\n\t\t}\r\n\r\n\t\toutput_file.open(DBFilePath + \".tmp\", std::fstream::binary | std::fstream::out | std::fstream::trunc);\r\n\r\n\r\n\r\n\r\n\t\tif (!outputFilePath.empty())\r\n\t\t\tmsg += sub_hourly_file.open(outputFilePath);\r\n\r\n\r\n\r\n\r\n\t\tCResultPtr pResult = m_pParent->GetResult(fileManager);\r\n\t\tmsg += pResult->Open();\r\n\r\n\t\t//open outputDB\r\n\t\tCResult result;\r\n\t\tmsg += result.Open(DBFilePath, std::fstream::binary | std::fstream::out | std::fstream::trunc);\r\n\r\n\t\tif (!msg)\r\n\t\t\treturn msg;\r\n\r\n\r\n\t\t//init output info\r\n\t\tCDBMetadata& metadata = result.GetMetadata();\r\n\t\tGetInputDBInfo(pResult, metadata);\r\n\r\n\t\tconst CModelOutputVariableDefVector& vars = pResult->GetMetadata().GetOutputDefinition();\r\n\r\n\t\tbool bMissing = false;\r\n\t\tstd::array<size_t, NB_SBW_INPUTS> varsPos;\r\n\t\tfor (size_t i = 0; i < NB_SBW_INPUTS; i++)\r\n\t\t{\r\n\t\t\tvarsPos[i] = Find(vars, SBW_VARIABLE_NAME[i]);\r\n\t\t\tbMissing = bMissing || varsPos[i] == NOT_INIT;\r\n\t\t}\r\n\r\n\r\n\t\tif (bMissing)\r\n\t\t{\r\n\t\t\tmsg.ajoute(\"Invalid dispersal variables input. Variable \\\"Year\\\", \\\"Month\\\", \\\"Day\\\",\\\"Sex\\\", \\\"A\\\", \\\"M\\\", \\\"G\\\", \\\"F°\\\", \\\"F\\\", must be defined\");\r\n\t\t\treturn msg;\r\n\t\t}\r\n\r\n\r\n\t\tcallback.PushTask(\"Open Dispersal's Input\", 4);\r\n\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tmsg += world.m_DEM_DS.OpenInputImage(DEM_filepath);\r\n\t\t\tcallback.StepIt();\r\n\t\t}\r\n\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tmsg += world.m_weather.Load(gribs_filepath, hourly_DB_filepath, callback);\r\n\t\t\tcallback.StepIt();\r\n\t\t}\r\n\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tif (!defoliation_filepath.empty())\r\n\t\t\t{\r\n\t\t\t\tmsg += world.m_defoliation_DS.OpenInputImage(defoliation_filepath);\r\n\t\t\t}\r\n\t\t\telse if (world.m_moths_param.m_maxFlights > 1)\r\n\t\t\t{\r\n\t\t\t\tmsg.ajoute(\"maximum flights is more than 1 but there is no defoliation map. Reset maximum flights to 1 or provide defoliation map.\");\r\n\t\t\t}\r\n\r\n\t\t\tcallback.StepIt();\r\n\t\t}\r\n\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tif (!water_filepath.empty())\r\n\t\t\t{\r\n\t\t\t\tmsg += world.m_water_DS.OpenInputImage(water_filepath);\r\n\t\t\t}\r\n\t\t\telse if (world.m_moths_param.m_maxFlights > 1)\r\n\t\t\t{\r\n\t\t\t\tmsg.ajoute(\"maximum flights is more than 1 but there is no water map. Reset maximum flights to 1 or provide water map.\");\r\n\t\t\t}\r\n\r\n\t\t\tcallback.StepIt();\r\n\t\t}\r\n\r\n\t\tcallback.PopTask();\r\n\r\n\r\n\t\tCTPeriod outputPeriod2 = world.m_world_param.m_simulationPeriod;\r\n\t\toutputPeriod2.End()++;//add one day at the end\r\n\t\toutputPeriod2.Transform(CTM::HOURLY);\r\n\t\toutputPeriod2.Begin().m_hour = 16;\r\n\t\toutputPeriod2.End().m_hour = 15;\r\n\r\n\r\n\t\tCTPeriod weatherPeriod = world.m_weather.GetEntireTPeriod();\r\n\t\t//weatherPeriod.Transform(CTM::DAILY);\r\n\r\n\t\tCTPeriod savedPeriod = outputPeriod2.Intersect(weatherPeriod);\r\n\r\n\r\n\r\n\t\tASSERT(outputPeriod2.GetTM() == weatherPeriod.GetTM());\r\n\t\tif (!outputPeriod2.IsIntersect(weatherPeriod))\r\n\t\t{\r\n\t\t\tmsg.ajoute(\"Weather period doesn't intersect simulation period\");\r\n\t\t}\r\n\r\n\t\tif (!msg)\r\n\t\t\treturn msg;\r\n\r\n\t\t//if (period.End() > weatherPeriod.End())//stop simulation at the end of weather \r\n\t\t\t//period.End() = weatherPeriod.End();\r\n\r\n\r\n\t\tconst CLocationVector& locations = metadata.GetLocations();\r\n\t\tcallback.PushTask(\"Initialize dispersal moths\", metadata.GetNbReplications() *locations.size()*metadata.GetParameterSet().size());\r\n\r\n\t\tCGeoExtents extents = world.m_DEM_DS.GetExtents();\r\n\t\textents.Reproject(GetReProjection(world.m_DEM_DS.GetPrjID(), PRJ_WGS_84));\r\n\r\n\t\tdouble max_moth_prop = 1;//all moths by default\r\n\t\tsize_t nbMoths = 0;\r\n\t\tif (world.m_world_param.m_maxFlyers > 0)//replace maxFlyers par maxMoths\r\n\t\t{\r\n\t\t\t//for optimization, clean extra moths\r\n\t\t\tnbMoths = GetNbMoths(pResult);\r\n\t\t\tif (nbMoths > world.m_world_param.m_maxFlyers)\r\n\t\t\t{\r\n\t\t\t\tmax_moth_prop = ((double)world.m_world_param.m_maxFlyers/ nbMoths);\r\n\r\n\t\t\t\tcallback.AddMessage(\"Number of moths before optimization: \" + ToString(nbMoths) + \" moths\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstd::vector<std::array<size_t, 3>> IDmap;\r\n\r\n\r\n\t\tsize_t no = 0;\r\n\t\tsize_t nbReplications = 0;\r\n\t\tsize_t moths_before = 0;\r\n\t\tsize_t moths_after = 0;\r\n\t\tsize_t sum_individual = 0;\r\n\t\tfor (size_t l = 0; l < locations.size() && msg; l++)\r\n\t\t{\r\n\t\t\tfor (size_t p = 0; p < pResult->GetMetadata().GetParameterSet().size() && msg; p++)\r\n\t\t\t{\r\n\t\t\t\tsize_t rr = 0;\r\n\t\t\t\tfor (size_t r = 0; r < pResult->GetMetadata().GetNbReplications() && msg; r++)\r\n\t\t\t\t{\r\n\t\t\t\t\tCNewSectionData section;\r\n\t\t\t\t\tpResult->GetSection(l, p, r, section);\r\n\t\t\t\t\tassert(section.GetCols() == pResult->GetNbCols(false));\r\n\r\n\t\t\t\t\tfor (size_t t = 0; t < section.GetRows() && msg; t++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstd::array<double, NB_SBW_INPUTS> v;\r\n\t\t\t\t\t\tfor (size_t i = 0; i < varsPos.size(); i++)\r\n\t\t\t\t\t\t\tv[i] = section[t][varsPos[i]][MEAN];\r\n\r\n\t\t\t\t\t\tif (v[I_YEAR] > -999 && v[I_MONTH] > -999 && v[I_DAY] > -999)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tCTRef emergingDate = CTRef(int(v[I_YEAR]), size_t(v[I_MONTH]) - 1, size_t(v[I_DAY]) - 1);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif (world.random().Randu() <= max_moth_prop)//remove moth by optimization\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tif (world.m_world_param.m_simulationPeriod.IsInside(emergingDate))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tCSBWMoth moth(world);\r\n\r\n\t\t\t\t\t\t\t\t\tmoth.m_ID = no;\r\n\t\t\t\t\t\t\t\t\tIDmap.push_back({ { l,p,rr } });\r\n\r\n\t\t\t\t\t\t\t\t\tmoth.m_emergingDate = emergingDate;//daily reference of ready moths\r\n\t\t\t\t\t\t\t\t\tmoth.m_sex = v[I_SEX];//sex (MALE=0, FEMALE=1)\r\n\t\t\t\t\t\t\t\t\tmoth.m_A = v[I_A];\r\n\t\t\t\t\t\t\t\t\tmoth.m_M = v[I_M];\r\n\t\t\t\t\t\t\t\t\tmoth.m_G = v[I_G];\r\n\t\t\t\t\t\t\t\t\tmoth.m_Fᵒ = v[I_Fᵒ];\r\n\t\t\t\t\t\t\t\t\tmoth.m_Fᴰ = v[I_Fᴰ];\r\n\t\t\t\t\t\t\t\t\tmoth.m_F = moth.m_Fᴰ;\r\n\t\t\t\t\t\t\t\t\tmoth.m_location = locations[l];\r\n\t\t\t\t\t\t\t\t\tmoth.m_pt = locations[l];\r\n\r\n\t\t\t\t\t\t\t\t\tif (extents.IsInside(moth.m_pt))\r\n\t\t\t\t\t\t\t\t\t\tworld.m_moths.push_back(moth);\r\n\t\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t\t\tcallback.AddMessage(\"WARNING: Simulation point outside elevation map\");\r\n\r\n\t\t\t\t\t\t\t\t\trr++;\r\n\t\t\t\t\t\t\t\t\tnbReplications = max(nbReplications, rr);\r\n\t\t\t\t\t\t\t\t\tno++;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse//is inside simulation period\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tif (emergingDate < world.m_world_param.m_simulationPeriod.Begin())\r\n\t\t\t\t\t\t\t\t\t\tmoths_before++;\r\n\t\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t\t\tmoths_after++;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tworld.m_seasonalIndividuals++;\r\n\t\t\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\t\tsum_individual++;\r\n\t\t\t\t\t\t}//is valid insect\r\n\t\t\t\t\t}//for all rows\r\n\r\n\t\t\t\t\tmsg += callback.StepIt();\r\n\t\t\t\t}//for all replications\r\n\t\t\t}//for all parameter set\r\n\t\t}//for all locations\r\n\r\n\r\n\t\tcallback.PopTask();\r\n\r\n\t\tcallback.AddMessage(\"Kept ratio: \" + ToString(100.0*world.m_seasonalIndividuals/ sum_individual, 1) + \" %\");\r\n\t\tcallback.AddMessage(\"Number of moths for the entire season: \" + ToString(world.m_seasonalIndividuals) + \" moths\");\r\n\t\tcallback.AddMessage(\"Number of moths before the period: \" + to_string(moths_before) + \" moths (\" + ToString(100.0*moths_before / world.m_seasonalIndividuals, 2) + \" %)\");\r\n\t\tcallback.AddMessage(\"Number of moths for the period: \" + to_string(world.m_moths.size()) + \" moths (\" + ToString(100.0*world.m_moths.size() / world.m_seasonalIndividuals, 2) + \" %)\");\r\n\t\tcallback.AddMessage(\"Number of moths after the period: \" + to_string(moths_after) + \" moths (\" + ToString(100.0*moths_after / world.m_seasonalIndividuals, 2) + \" %)\");\r\n\t\tcallback.AddMessage(\"Execute dispersal with: \" + to_string(world.m_moths.size()) + \" moths (\" + ToString(100.0*world.m_moths.size() / world.m_seasonalIndividuals, 2) + \" %)\");\r\n\t\tcallback.AddMessage(\"Weather period:         \" + world.m_weather.GetEntireTPeriod().GetFormatedString());\r\n\t\tcallback.AddMessage(\"Output period:          \" + outputPeriod2.GetFormatedString());\r\n\t\tcallback.AddMessage(\"Output replications (max moths/location):\" + ToString(nbReplications));\r\n\r\n\t\tmetadata.SetNbReplications(nbReplications);\r\n\t\tmetadata.SetTPeriod(outputPeriod2);\r\n\r\n\t\tif (!world.m_moths.empty())\r\n\t\t{\r\n\r\n\t\t\t/*CATMOutputMatrix output(world.m_moths.size());\r\n\t\t\tfor (size_t no = 0; no < output.size(); no++)\r\n\t\t\t\toutput[no].Init(outputPeriod, VMISS);\r\n\r\n\t\t\tmsg = world.Execute(output, sub_hourly_file, callback);\r\n\t\t\tif (msg)\r\n\t\t\t{\r\n\t\t\t\tcallback.PushTask(\"Save data\" , output.size() );\r\n\r\n\t\t\t\tATMOutput missing_output;\r\n\t\t\t\tmissing_output.Init(outputPeriod, VMISS);\r\n\r\n\t\t\t\tfor (size_t l = 0; l < locations.size(); l++)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t p = 0; p < metadata.GetParameterSet().size(); p++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (size_t r = 0; r < nbReplications; r++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tsize_t section = result.GetSectionNo(l, p, r);\r\n\r\n\t\t\t\t\t\t\tstd::array<size_t, 3> lpr = { {l,p,r} };\r\n\t\t\t\t\t\t\tauto it = find(IDmap2.begin(), IDmap2.end(), lpr);\r\n\t\t\t\t\t\t\tif (it != IDmap2.end())\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tsize_t no = distance(IDmap2.begin(), it);\r\n\t\t\t\t\t\t\t\tmsg += result.SetSection(section, output[no]);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tmsg += result.SetSection(section, missing_output);\r\n\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tmsg += callback.StepIt();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t\tcallback.PopTask();\r\n\r\n\t\t\t\tif (msg&& m_parameters.m_world.m_bCreateEggMaps)\r\n\t\t\t\t{\r\n\t\t\t\t\tstring outputFilePath = fileManager.GetOutputMapPath() + m_parameters.m_world.m_eggMapsTitle + \".tif\";\r\n\t\t\t\t\tmsg = world.CreateEggDepositionMap(outputFilePath, output, callback);\r\n\t\t\t\t}\r\n\t\t\t}*/\r\n\r\n\r\n\r\n\t\t\tCStatistic::SetVMiss(-999);\r\n\r\n\t\t\tworld.Init(callback);\r\n\r\n\r\n\t\t\t//world.write_sub_hourly_header(output_file);\r\n\r\n\t\t\tif (sub_hourly_file.is_open())\r\n\t\t\t\tworld.write_sub_hourly_header(sub_hourly_file);\r\n\r\n\r\n\t\t\t//get period of simulation\r\n\t\t\tCTPeriod period = world.m_world_param.m_simulationPeriod;\r\n\t\t\tcallback.PushTask(\"Execute dispersal for year = \" + ToString(period.Begin().GetYear()) + \" (\" + ToString(period.GetNbDay()) + \" days)\", period.GetNbDay() * 2);\r\n\t\t\tcallback.AddMessage(\"Date            NotEmerged       Emerging         WaitingToFly     Flying           FinishingEggs    Finished        \");\r\n\r\n\t\t\t//for all days\r\n\t\t\tfor (CTRef TRef = period.Begin(); TRef <= period.End() && msg; TRef++)\r\n\t\t\t{\r\n\t\t\t\tCATMOutputMatrix output;\r\n\t\t\t\tworld.init_output(TRef, output);\r\n\r\n\t\t\t\tCATMOutputMatrix sub_output;\r\n\t\t\t\tif (sub_hourly_file.is_open())\r\n\t\t\t\t\tworld.init_sub_hourly(TRef, sub_output);\t//initmemory\r\n\r\n\t\t\t\tmsg += world.ExecuteOneNight(TRef, output, sub_output, callback);\r\n\r\n\t\t\t\tif (msg)\r\n\t\t\t\t\tmsg += world.save_output(savedPeriod, output_file, output, callback);\r\n\r\n\t\t\t\tif (msg && sub_hourly_file.is_open())\r\n\t\t\t\t{\r\n\t\t\t\t\tmsg += world.save_sub_output(TRef, sub_hourly_file, sub_output, callback);\r\n\t\t\t\t}//if sub hourly output\r\n\r\n\t\t\t}//for all valid days\r\n\r\n\r\n\t\t\toutput_file.close();\r\n\t\t\tif (sub_hourly_file.is_open())\r\n\t\t\t\tsub_hourly_file.close();\r\n\r\n\t\t\tcallback.PopTask();\r\n\r\n\t\t\tif (msg)\r\n\t\t\t\tmsg += copy_result(DBFilePath + \".tmp\", IDmap, savedPeriod, result, callback);\r\n\r\n\t\t\tif (msg&& m_parameters.m_world.m_bCreateEggMaps)\r\n\t\t\t{\r\n\t\t\t\tstring inputFilePath = DBFilePath + \".tmp\";\r\n\t\t\t\tstring outputFilePath = fileManager.GetOutputMapPath() + m_parameters.m_world.m_eggMapsTitle + \".tif\";\r\n\t\t\t\tmsg = world.CreateEggDepositionMap(inputFilePath, outputFilePath, savedPeriod, callback);\r\n\t\t\t}\r\n\r\n\t\t\tWBSF::RemoveFile(DBFilePath + \".tmp\");\r\n\t\t}\r\n\r\n\t\tresult.Close();\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tERMsg CDispersal::copy_result(const string& file_path, const std::vector<std::array<size_t, 3>>& IDmap, CTPeriod savedPeriod, CResult& result, CCallback& callback)\r\n\t{\r\n\t\tERMsg msg;\r\n\t\t\r\n\t\tifStream input_file;\r\n\t\tmsg = input_file.open(file_path, ios_base::in | ios_base::binary);\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tconst size_t size_struct = sizeof(size_t) + savedPeriod.size()*(sizeof(__int32) + sizeof(float)*NB_ATM_OUTPUT);\r\n\t\t\tsize_t length = input_file.length();\r\n\t\t\tASSERT(length == IDmap.size()*size_struct);\r\n\r\n\t\t\tcallback.PushTask(\"Save result\", result.GetNbSection());\r\n\r\n\t\t\tfor (size_t l = 0; l < result.GetDimension()[LOCATION] && msg; l++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t p = 0; p < result.GetDimension()[PARAMETER] && msg; p++)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t r = 0; r < result.GetDimension()[REPLICATION] && msg; r++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tATMOutput output;\r\n\t\t\t\t\t\toutput.Init(savedPeriod, VMISS);\r\n\r\n\t\t\t\t\t\tstd::array<size_t, 3> lpr = { { l,p,r } };\r\n\t\t\t\t\t\tauto it = find(IDmap.begin(), IDmap.end(), lpr);\r\n\t\t\t\t\t\tif (it != IDmap.end())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tCTRef trefTest = savedPeriod.Begin();\r\n\t\t\t\t\t\t\tsize_t no = input_file.read_value<size_t>();\r\n\t\t\t\t\t\t\tASSERT(no < result.GetNbSection());\r\n\r\n\t\t\t\t\t\t\tfor (size_t t = 0; t < savedPeriod.size() && msg; t++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t__int32 tmp = input_file.read_value<__int32 >();\r\n\t\t\t\t\t\t\t\tASSERT(!input_file.eof());\r\n\r\n\t\t\t\t\t\t\t\tCTRef TRef;\r\n\t\t\t\t\t\t\t\tTRef.Set__int32(tmp);\r\n\t\t\t\t\t\t\t\tASSERT(output.IsInside(TRef));\r\n\t\t\t\t\t\t\t\tASSERT(TRef == trefTest);\r\n\t\t\t\t\t\t\t\ttrefTest++;\r\n\r\n\r\n\t\t\t\t\t\t\t\tfor (size_t v = 0; v < NB_ATM_OUTPUT; v++)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tfloat value = input_file.read_value<float>();\r\n\t\t\t\t\t\t\t\t\tASSERT(!input_file.eof());\r\n\r\n\t\t\t\t\t\t\t\t\tif (value > -999)\r\n\t\t\t\t\t\t\t\t\t\toutput[TRef][v] = value;\r\n\r\n\t\t\t\t\t\t\t\t\tASSERT(output[TRef][ATM_DEFOLIATION] != 0);\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}\r\n\r\n\r\n\t\t\t\t\t\tsize_t section = result.GetSectionNo(l, p, r);\r\n\t\t\t\t\t\tmsg += result.SetSection(section, output);\r\n\r\n\t\t\t\t\t\tmsg += callback.StepIt();\r\n\t\t\t\t\t}//r\r\n\t\t\t\t}//p\r\n\t\t\t}//l\r\n\r\n\t\t\tinput_file.close();\r\n\t\t\tcallback.PopTask();\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\tsize_t CDispersal::GetNbMoths(CResultPtr pResult)\r\n\t{\r\n\t\tsize_t nbMoths = 0;\r\n\t\tconst CModelOutputVariableDefVector& vars = pResult->GetMetadata().GetOutputDefinition();\r\n\t\tstd::array<size_t, NB_SBW_INPUTS> varsPos;\r\n\t\tfor (size_t i = 0; i < NB_SBW_INPUTS; i++)\r\n\t\t\tvarsPos[i] = Find(vars, SBW_VARIABLE_NAME[i]);\r\n\r\n\t\tconst CLocationVector& locations = pResult->GetMetadata().GetLocations();\r\n\t\tfor (size_t l = 0; l < pResult->GetMetadata().GetLocations().size(); l++)\r\n\t\t{\r\n\t\t\tfor (size_t p = 0; p < pResult->GetMetadata().GetParameterSet().size(); p++)\r\n\t\t\t{\r\n\t\t\t\tsize_t rr = 0;\r\n\t\t\t\tfor (size_t r = 0; r < pResult->GetMetadata().GetNbReplications(); r++)\r\n\t\t\t\t{\r\n\t\t\t\t\tCNewSectionData section;\r\n\t\t\t\t\tpResult->GetSection(l, p, r, section);\r\n\t\t\t\t\tassert(section.GetCols() == pResult->GetNbCols(false));\r\n\r\n\t\t\t\t\tfor (size_t t = 0; t < section.GetRows(); t++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstd::array<double, NB_SBW_INPUTS> v;\r\n\t\t\t\t\t\tfor (size_t i = 0; i < varsPos.size(); i++)\r\n\t\t\t\t\t\t\tv[i] = section[t][varsPos[i]][MEAN];\r\n\r\n\t\t\t\t\t\tif (v[I_YEAR] > -999 && v[I_MONTH] > -999 && v[I_DAY] > -999)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnbMoths++;\r\n\t\t\t\t\t\t\tCTRef emergingDate = CTRef(int(v[I_YEAR]), size_t(v[I_MONTH]) - 1, size_t(v[I_DAY]) - 1);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}//for all rows\r\n\t\t\t\t}//for all replications\r\n\t\t\t}//for all paramterset\r\n\t\t}//for all locations\r\n\r\n\t\treturn nbMoths;\r\n\t}\r\n}", "meta": {"hexsha": "782289cca070519dd460e97cf4cf749e63881452", "size": 30860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbs/src/Simulation/Dispersal.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": "wbs/src/Simulation/Dispersal.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": "wbs/src/Simulation/Dispersal.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": 35.1881413911, "max_line_length": 347, "alphanum_fraction": 0.6415100454, "num_tokens": 8986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.06465348925734801, "lm_q1q2_score": 0.030560636077805063}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2018 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 <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"SiconosVector.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n\nusing namespace Siconos;\n\n//=============================\n// Elements access (get or set)\n//=============================\n\ndouble SimpleMatrix::getValue(unsigned int row, unsigned int col) const\n{\n  if (row >= size(0) || col >= size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix:getValue(index): Index out of range\");\n\n  if (_num == 1)\n    return (*mat.Dense)(row, col);\n  else if (_num == 2)\n    return (*mat.Triang)(row, col);\n  else if (_num == 3)\n    return (*mat.Sym)(row, col);\n  else if (_num == 4)\n  {\n    double * d = (*mat.Sparse).find_element(row, col);\n    if (d)\n      return *d;\n    else\n      return 0.0;\n  }\n  else if (_num == 5)\n    return (*mat.Banded)(row, col);\n  else if (_num == 6)\n    return 0;\n  else //if (_num==7)\n    return(row == col);\n}\n\nvoid SimpleMatrix::setValue(unsigned int row, unsigned int col, double value)\n{\n  if (row >= size(0) || col >= size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix:setValue: Index out of range\");\n\n  if (_num == 1)\n    (*mat.Dense)(row, col) = value;\n  else if (_num == 2)\n    (*mat.Triang)(row, col) = value;\n  else if (_num == 3)\n    (*mat.Sym)(row, col) = value ;\n  else if (_num == 4)\n  {\n    double * d = (*mat.Sparse).find_element(row, col);\n    if (d)\n    {\n      *d = value;\n    }\n    else\n    {\n      (*mat.Sparse).insert_element(row, col, value);\n    }\n  }\n  else if (_num == 5)\n    (*mat.Banded)(row, col) = value;\n  else if (_num == 6 || _num == 7)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix:setValue: forbidden for Identity or Zero type matrices.\");\n  resetLU();\n\n}\n\n//============================================\n// Access (get or set) to blocks of elements\n//============================================\n\nvoid SimpleMatrix::setBlock(unsigned int row_min, unsigned int col_min, const SiconosMatrix& m)\n{\n  // Set current matrix elements, starting from row row_min and column col_min, with the values of the matrix m.\n  // m may be a BlockMatrix.\n\n  // Exceptions ...\n  if (&m == this)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::setBlock(pos,..., m): m = this.\");\n\n  if (row_min >= size(0))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::setBlock(row,col): row is out of range\");\n\n  if (col_min >= size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::setBlock(row,col): col is out of range\");\n\n  unsigned int row_max, col_max;\n  row_max = m.size(0) + row_min;\n  col_max = m.size(1) + col_min;\n\n  if (row_max > size(0))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::setBlock(row,col,m): m.row + row is out of range.\");\n\n  if (col_max > size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::setBlock(row,col,m): m.col + col is out of range.\");\n\n  unsigned int numM = m.num();\n\n  if (numM == 0) // if m is a block matrix ...\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    BlocksMat::const_iterator1 it;\n    BlocksMat::const_iterator2 it2;\n    unsigned int posRow = row_min;\n    unsigned int posCol = col_min;\n\n    for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for (it2 = it.begin(); it2 != it.end(); ++it2)\n      {\n        setBlock(posRow, posCol, **it2);\n        posCol += (*it2)->size(1);\n      }\n      posRow += (*it)->size(0);\n      posCol = col_min;\n    }\n  }\n  else // if m is a SimpleMatrix\n  {\n    if (numM != _num)\n      SiconosMatrixException::selfThrow(\"SimpleMatrix::setBlock(i,j,m), inconsistent types.\");\n\n    if (_num == 1)\n      noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) = *(m.dense());\n    else if (_num == 2)\n      noalias(ublas::subrange(*mat.Triang, row_min, row_max, col_min, col_max)) = *(m.triang());\n    else if (_num == 3)\n      noalias(ublas::subrange(*mat.Sym, row_min, row_max, col_min, col_max)) = *(m.sym());\n    else if (_num == 4)\n      noalias(ublas::subrange(*mat.Sparse, row_min, row_max, col_min, col_max)) = *(m.sparse());\n    else if (_num == 5)\n      noalias(ublas::subrange(*mat.Banded, row_min, row_max, col_min, col_max)) = *(m.banded());\n    else // if(_num==6) or _num == 7 nothing to do\n    {}\n    resetLU();\n  }\n}\n\nvoid setBlock(SPC::SiconosMatrix  MIn, SP::SiconosMatrix MOut, const Index& dim, const Index& start)\n{\n  // To copy a subBlock of MIn into a subBlock of MOut.\n  // dim[0], dim[1]: number of rows and columns of the sub-block\n  // start[0], start[1]: position (row, column) of the first element of the subBlock in MIn\n  // start[2], start[3]: position (row, column) of the first element of the subBlock in MOut\n\n  if (MIn == MOut) // useless op => nothing to be done.\n  {}// SiconosVectorException::selfThrow(\"\");\n  else\n  {\n    unsigned int numIn = MIn->num();\n    unsigned int numOut = MOut->num();\n\n    if (numOut == 6 || numOut == 7) // if MOut = 0 or Identity => read-only\n      SiconosMatrixException::selfThrow(\"matrices, setBlock(MIn, MOut...): MOut is read-only (zero or identity matrix?).\");\n\n    // Check dimension\n    Index MDim(4); // dim. of matrices MIn and MOut.\n    MDim[0] = MIn->size(0);\n    MDim[1] = MIn->size(1);\n    MDim[2] = MOut->size(0);\n    MDim[3] = MOut->size(1);\n\n    for (unsigned int i = 0; i < 4 ; ++i)\n      if (start[i] >= MDim[i])\n        SiconosMatrixException::selfThrow(\"matrices, setBlock(MIn, ...): sub-block indices are out of range.\");\n\n    // index position of the last element in subBlock ...\n    Index end(4);\n    end[0] = dim[0] + start[0];\n    end[1] = dim[1] + start[1];\n    end[2] = dim[0] + start[2];\n    end[3] = dim[1] + start[3];\n\n    for (unsigned int i = 0; i < 4 ; ++i)\n      if (end[i] > MDim[i])\n        SiconosMatrixException::selfThrow(\"matrices, setBlock(MIn, ...): sub-block indices are out of range.\");\n\n    // Elements from row/col start[i] to row/col (end[i]-1) will be copied.\n\n    // If both matrices MIn and MOut are block, exception.\n    if (numIn == 0 && numOut == 0)\n      SiconosMatrixException::selfThrow(\"matrices, setBlock(MIn, MOut ...): not yet implemented for MIn and MOut both BlockMatrix. Try to use setBlock on the sub-matrices?\");\n\n    else if (numOut == 0) // if MOut is a BlockMatrix.\n    {\n\n      // Steps:\n      // A - Find the blocks of MOut that \"own\" indices start[2] and end[2] ie\n      //     the first and last sub-block to be set in a block-column\n      //         --> numbers blockStart0 and blockEnd0\n      // B - Find the  Block of MOut that \"owns\" index start[3] and end[3] ie\n      //     the first sub-block to be set in a block-row\n      //         --> numbers blockStart1 and blockEnd1\n      //\n      //        => The blocks concerned in MOut, are those between (block) rows blockStart0 and blockEnd0\n      //           and (block) columns blockStart1 and blockEnd1.\n      //\n      // C - Loop through the concerned blocks (name = currentBlock) of MOut and call setBlock(MIn, currentBlock, subSize, currentPos).\n      //     subSize: dim. of the considered sub-block of currentBlock to be set\n      //     currentPos: same as \"start\" vector but for currentBlock\n      //\n\n      // A - Block-Row position: we look for the block of MOut that include index start[2] and end[2].\n      //\n      unsigned int blockStart0 = 0;\n      SPC::Index tab = MOut->tabRow();\n      while (start[2] >= (*tab)[blockStart0] && blockStart0 < tab->size())\n        blockStart0 ++;\n      // Relative position in the block blockStart0 of the first element to be set.\n      unsigned int posOut0 = start[2];\n      if (blockStart0 != 0)\n        posOut0 -= (*tab)[blockStart0 - 1];\n\n      unsigned int blockEnd0 = blockStart0;\n      while (end[2] > (*tab)[blockEnd0] && blockEnd0 < tab->size())\n        blockEnd0 ++;\n\n      // Size of the last sub-block in the column of block\n      unsigned int lastBlockSize0 = end[2];\n      if (blockEnd0 != 0)\n        lastBlockSize0 -= (*tab)[blockEnd0 - 1];\n\n      // B - Block-Col position: we look for the block of MOut that include index start[3] and end[3].\n      unsigned int blockStart1 = 0;\n      tab = MOut->tabCol();\n      while (start[3] >= (*tab)[blockStart1] && blockStart1 < tab->size())\n        blockStart1 ++;\n      // Relative position in the block blockStart1 of the first element to be set.\n      unsigned int posOut1 = start[3];\n      if (blockStart1 != 0)\n        posOut1 -= (*tab)[blockStart1 - 1];\n\n      unsigned int blockEnd1 = blockStart1;\n      while (end[3] > (*tab)[blockEnd1] && blockEnd1 < tab->size())\n        blockEnd1 ++;\n\n      // Size of the last sub-block in the row of block\n      unsigned int lastBlockSize1 = end[3];\n      if (blockEnd1 != 0)\n        lastBlockSize1 -= (*tab)[blockEnd1 - 1];\n\n      //C - Next, 3 steps for each row:\n      // - set first sub-block in the row (number blockStart1)\n      // - set all other blocks in the row except the last one\n      // - set last block (number blockEnd1)\n      // Same process for other rows ...\n\n      // The current considered block\n      SP::SiconosMatrix   currentBlock = MOut->block(blockStart0, blockStart1);\n\n      // dim of the subBlock of currentBlock to be set.\n      Index subSize(2);\n      // indices of the first element of MIn (resp. currentBlock) to be read (resp. set)  (same as start for MIn and MOut).\n      Index currentPos(4);\n\n      // currentBlock position in MOut.\n      unsigned int numRow = blockStart0;\n      unsigned int numCol = blockStart1;\n\n      // Init currentPos\n      // row and col position for first element to be read in MIn,\n      currentPos[0] = start[0];\n      currentPos[1] = start[1];\n      // row and col position for first element in sub-block of Mout (namely currentBlock).\n      currentPos[2] = posOut0;\n      currentPos[3] = posOut1;\n\n      while (numRow != blockEnd0 + 1)\n      {\n\n        while (numCol != blockEnd1 + 1)\n        {\n          // Get the block of MOut from which a sub-block will be set ...\n          currentBlock = MOut->block(numRow, numCol);\n\n          // Set subSize[0], dim (rows) and subSize[1], dim (columns) of the sub-block.\n          // subSize[0] is only required for the first block in the row, after it remains constant.\n          subSize[1] = currentBlock->size(1);\n\n          // Warning: test \"a\" must be done before test \"b\"\n          if (numCol == blockEnd1) // if last column of blocks -> test \"a\"\n            subSize[1] = lastBlockSize1;\n\n          if (numCol == blockStart1) // -> test \"b\"\n          {\n            subSize[1] -= posOut1;\n            subSize[0] = currentBlock->size(0);\n            if (numRow == blockEnd0) // if last row of blocks\n              subSize[0] = lastBlockSize0;\n            if (numRow == blockStart0) // if first row of blocks\n              subSize[0] -= posOut0;\n          }\n\n          // Set sub-block\n          setBlock(MIn, currentBlock, subSize, currentPos);\n\n          // Update currentPos:\n          // col position for first element to be read in MIn,\n          currentPos[1] += subSize[1] ;\n          // col position for first element to be set in sub-block.\n          currentPos[3] = 0;\n          numCol++;\n        }\n\n        numCol = blockStart1;\n        numRow++;\n\n        // Update currentPos:\n        // row position for first element to be read in MIn,\n        currentPos[0] += subSize[0] ;\n        // col position for first element to be read in MIn,\n        currentPos[1] = start[1] ;\n        // row position for first element to be set in sub-block.\n        currentPos[2] = 0;\n        // col position for first element to be set in sub-block.\n        currentPos[3] = posOut1;\n\n      }\n\n    }\n    else if (numIn == 0) // If MIn is a BlockMatrix.\n    {\n\n      // Same process as for numOut == 0\n\n      unsigned int blockStart0 = 0;\n      SPC::Index tab = MIn->tabRow();\n      while (start[0] >= (*tab)[blockStart0] && blockStart0 < tab->size())\n        blockStart0 ++;\n      // Relative position in the block blockStart0 of the first element to be set.\n      unsigned int posOut0 = start[0];\n      if (blockStart0 != 0)\n        posOut0 -= (*tab)[blockStart0 - 1];\n\n      unsigned int blockEnd0 = blockStart0;\n      while (end[0] > (*tab)[blockEnd0] && blockEnd0 < tab->size())\n        blockEnd0 ++;\n\n      // Size of the last sub-block in the column of block\n      unsigned int lastBlockSize0 = end[0];\n      if (blockEnd0 != 0)\n        lastBlockSize0 -= (*tab)[blockEnd0 - 1];\n\n      // B - Block-Col position: we look for the block of MOut that include index start[3] and end[3].\n      unsigned int blockStart1 = 0;\n      tab = MIn->tabCol();\n      while (start[1] >= (*tab)[blockStart1] && blockStart1 < tab->size())\n        blockStart1 ++;\n      // Relative position in the block blockStart1 of the first element to be set.\n      unsigned int posOut1 = start[1];\n      if (blockStart1 != 0)\n        posOut1 -= (*tab)[blockStart1 - 1];\n\n      unsigned int blockEnd1 = blockStart1;\n      while (end[1] > (*tab)[blockEnd1] && blockEnd1 < tab->size())\n        blockEnd1 ++;\n\n      // Size of the last sub-block in the row of block\n      unsigned int lastBlockSize1 = end[1];\n      if (blockEnd1 != 0)\n        lastBlockSize1 -= (*tab)[blockEnd1 - 1];\n\n      //C - Next, 3 steps for each row:\n      // - set first sub-block in the row (number blockStart1)\n      // - set all other blocks in the row except the last one\n      // - set last block (number blockEnd1)\n      // Same process for other rows ...\n\n      // The current considered block\n      SPC::SiconosMatrix  currentBlock = MIn->block(blockStart0, blockStart1);\n\n      // dim of the subBlock of currentBlock to be set.\n      Index subSize(2);\n      // indices of the first element of MIn (resp. currentBlock) to be read (resp. set)  (same as start for MIn and MOut).\n      Index currentPos(4);\n\n      // currentBlock position in MOut.\n      unsigned int numRow = blockStart0;\n      unsigned int numCol = blockStart1;\n\n      // Init currentPos\n      // row and col position for first element to be read in MIn,\n      currentPos[0] = posOut0;\n      currentPos[1] = posOut1;\n      // row and col position for first element in sub-block of Mout (namely currentBlock).\n      currentPos[2] = start[2];\n      currentPos[3] = start[3];\n\n      while (numRow != blockEnd0 + 1)\n      {\n\n        while (numCol != blockEnd1 + 1)\n        {\n          // Get the block of MOut from which a sub-block will be set ...\n          currentBlock = MIn->block(numRow, numCol);\n\n          // Set subSize[0], dim (rows) and subSize[1], dim (columns) of the sub-block.\n          // subSize[0] is only required for the first block in the row, after it remains constant.\n          subSize[1] = currentBlock->size(1);\n          // Warning: test \"a\" must be done before test \"b\"\n          if (numCol == blockEnd1) // if last column of blocks -> test \"a\"\n            subSize[1] = lastBlockSize1;\n\n          if (numCol == blockStart1) // -> test \"b\"\n          {\n            subSize[1] -= posOut1;\n            subSize[0] = currentBlock->size(0);\n            if (numRow == blockEnd0) // if last row of blocks\n              subSize[0] = lastBlockSize0;\n            if (numRow == blockStart0) // if first row of blocks\n              subSize[0] -= posOut0;\n          }\n\n          // Set sub-block\n          setBlock(currentBlock, MOut, subSize, currentPos);\n\n          // Update currentPos:\n          // col position for first element to be read in MIn,\n          currentPos[1] = 0 ;\n          // col position for first element to be set in sub-block.\n          currentPos[3] += subSize[1];\n          numCol++;\n        }\n\n        numCol = blockStart1;\n        numRow++;\n\n        // Update currentPos:\n        // row position for first element to be read in MIn,\n        currentPos[0] = 0;\n        // col position for first element to be read in MIn,\n        currentPos[1] = posOut1;\n        // row position for first element to be set in sub-block.\n        currentPos[2] += subSize[0] ;\n        // col position for first element to be set in sub-block.\n        currentPos[3] = start[3];\n\n      }\n      MOut->resetLU();\n\n    }\n    else // neither MIn nor MOut is a BlockMatrix.\n    {\n      switch (numIn)\n      {\n      case 1:\n        if (numOut != 1)\n          SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        noalias(ublas::subrange(*MOut->dense(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->dense(), start[0], end[0], start[1], end[1]);\n        break;\n\n      case 2:\n        if (numOut != 1)\n          SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        noalias(ublas::subrange(*MOut->dense(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->triang(), start[0], end[0], start[1], end[1]);\n        break;\n\n      case 3:\n        if (numOut != 1)\n          SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        noalias(ublas::subrange(*MOut->dense(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->sym(), start[0], end[0], start[1], end[1]);\n        break;\n\n      case 4:\n        if (numOut == 1)\n          noalias(ublas::subrange(*MOut->dense(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->sparse(), start[0], end[0], start[1], end[1]);\n        else if (numOut == 4)\n          noalias(ublas::subrange(*MOut->sparse(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->sparse(), start[0], end[0], start[1], end[1]);\n        else\n          SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        break;\n\n      case 5:\n        if (numOut != 1)\n          SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        noalias(ublas::subrange(*MOut->dense(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->banded(), start[0], end[0], start[1], end[1]);\n        break;\n\n      case 6:\n        if (numOut == 1)\n          ublas::subrange(*MOut->dense(), start[2], end[2], start[3], end[3]) *= 0.0;\n        else if (numOut == 2)\n          ublas::subrange(*MOut->triang(), start[2], end[2], start[3], end[3]) *= 0.0;\n        else if (numOut == 4)\n          ublas::subrange(*MOut->sparse(), start[2], end[2], start[3], end[3]) *= 0.0;\n        else if (numOut == 5)\n          ublas::subrange(*MOut->banded(), start[2], end[2], start[3], end[3]) *= 0.0;\n        else\n          SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        break;\n\n      case 7:\n        if (numOut == 1)\n          noalias(ublas::subrange(*MOut->dense(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->identity(), start[0], end[0], start[1], end[1]);\n        else if (numOut == 4)\n          noalias(ublas::subrange(*MOut->sparse(), start[2], end[2], start[3], end[3])) = ublas::subrange(*MIn->identity(), start[0], end[0], start[1], end[1]);\n        else\n          SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        break;\n\n      default:\n        SiconosMatrixException::selfThrow(\"matrix, setBlock(MIn, MOut, ...), unconsistent types between MIn and MOut.\");\n        break;\n      }\n      MOut->resetLU();\n    }\n  }\n}\n\n\nvoid SimpleMatrix::getRow(unsigned int r, SiconosVector &vOut) const\n{\n  // Get row number r of current matrix and copy it into vOut.\n  if (r >= size(0))\n    SiconosMatrixException::selfThrow(\"getRow(row): row is out of range\");\n\n  if (vOut.size() != size(1))\n    SiconosMatrixException::selfThrow(\"getRow(row,v): inconsistent sizes between this and v.\");\n\n  if (_num == 7) // identity matrix\n  {\n    vOut.zero();\n    vOut(r) = 1.0;\n  }\n  else if (_num == 6) // Zero matrix\n    vOut.zero();\n  else\n  {\n    unsigned int numV = vOut.num();\n    if (numV == 1)\n    {\n      if (_num == 1)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Dense, r);\n      }\n      else if (_num == 2)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Triang, r);\n      }\n      else if (_num == 3)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Sym, r);\n      }\n      else if (_num == 4)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Sparse, r);\n      }\n      else //if(_num==5){\n        noalias(*(vOut.dense())) = ublas::row(*mat.Banded, r);\n    }\n    else // if numV == 4\n    {\n      if (_num == 4)\n      {\n        noalias(*(vOut.sparse())) = ublas::row(*mat.Sparse, r);\n      }\n      else\n        SiconosMatrixException::selfThrow(\"getRow(row,v): inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n}\n\nvoid SimpleMatrix::setRow(unsigned int r, const SiconosVector& vIn)\n{\n  // Set row number r of current matrix with vIn.\n  unsigned int numV = vIn.num();\n  if (r >= size(0))\n    SiconosMatrixException::selfThrow(\"setRow(row): row is out of range\");\n\n  if (vIn.size() != size(1))\n    SiconosMatrixException::selfThrow(\"setRow(row,v): inconsistent sizes between this and v.\");\n\n  if (_num == 6 || _num == 7)\n    SiconosMatrixException::selfThrow(\"setRow(row,v): current matrix is read-only (zero or identity).\");\n\n  {\n    if (_num == 1)\n    {\n      if (numV == 1)\n      {\n        noalias(ublas::row(*mat.Dense, r)) = *vIn.dense();\n      }\n      else if (numV == 4)\n      {\n        noalias(ublas::row(*mat.Dense, r)) = *vIn.sparse();\n      }\n    }\n    else if (_num == 4 && numV == 4)\n      noalias(ublas::row(*mat.Sparse, r)) = *vIn.sparse();\n    else\n      SiconosMatrixException::selfThrow(\"setRow(row,v): inconsistent types between current matrix and v.\");\n  }\n\n  resetLU();\n}\n\nvoid SimpleMatrix::getCol(unsigned int r, SiconosVector &vOut)const\n{\n  // Get column number r of current matrix and copy it into vOut.\n  if (r >= size(1))\n    SiconosMatrixException::selfThrow(\"getCol(col): col is out of range\");\n\n  if (vOut.size() != size(0))\n    SiconosMatrixException::selfThrow(\"getCol(col,v): inconsistent sizes between this and v.\");\n\n  if (_num == 7) // identity matrix\n  {\n    vOut.zero();\n    vOut(r) = 1.0;\n  }\n  else if (_num == 6) // Zero matrix\n    vOut.zero();\n  else\n  {\n    unsigned int numV = vOut.num();\n\n    if (numV == 1)\n    {\n\n      if (_num == 1)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Dense, r);\n      }\n      else if (_num == 2)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Triang, r);\n      }\n      else if (_num == 3)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Sym, r);\n      }\n      else if (_num == 4)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Sparse, r);\n      }\n      else //if(_num==5){\n        noalias(*(vOut.dense())) = ublas::column(*mat.Banded, r);\n    }\n    else // if _numV == 4\n    {\n      if (_num == 4)\n      {\n        noalias(*(vOut.sparse())) = ublas::column(*mat.Sparse, r);\n      }\n      else\n        SiconosMatrixException::selfThrow(\"getCol(col,v): inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n}\n\nvoid SimpleMatrix::setCol(unsigned int r, const SiconosVector &vIn)\n{\n  // Set column number r of current matrix with vIn.\n  unsigned int numV = vIn.num();\n  if (r >= size(1))\n    SiconosMatrixException::selfThrow(\"setCol(col): col is out of range\");\n\n  if (vIn.size() != size(0))\n    SiconosMatrixException::selfThrow(\"setCol(col,v): inconsistent sizes between this and v.\");\n\n  if (_num == 6 || _num == 7)\n    SiconosMatrixException::selfThrow(\"setCol(col,v): current matrix is read-only (zero or identity).\");\n\n  {\n    if (_num == 1)\n    {\n      if (numV == 1)\n      {\n        noalias(ublas::column(*mat.Dense, r)) = *vIn.dense();\n      }\n      else if (numV == 4)\n      {\n        noalias(ublas::column(*mat.Dense, r)) = *vIn.sparse();\n      }\n    }\n    else if (_num == 4 && numV == 4)\n      noalias(ublas::column(*mat.Sparse, r)) = *vIn.sparse();\n    else\n      SiconosMatrixException::selfThrow(\"setCol(col,v): inconsistent types between current matrix and v.\");\n  }\n\n  resetLU();\n}\n\nvoid SimpleMatrix::getSubRow(unsigned int r, unsigned int pos, SP::SiconosVector vOut) const\n{\n  // Get row number r of current matrix, starting from element at position pos, and copy it into vOut.\n  if (r >= size(0))\n    SiconosMatrixException::selfThrow(\"getSubRow(row,pos,v): row is out of range\");\n\n  if (vOut->size() > size(1) - pos)\n    SiconosMatrixException::selfThrow(\"getSubRow(row,pos,v): inconsistent sizes between this and v.\");\n\n  if (_num == 7) // identity matrix\n  {\n    vOut->zero();\n    if (r >= pos)\n      (*vOut)(r - pos) = 1.0;\n  }\n  else if (_num == 6) // Zero matrix\n    vOut->zero();\n  else\n  {\n    unsigned int numV = vOut->num();\n    unsigned int nbEl = vOut->size();\n\n    if (numV == 1)\n    {\n      if (_num == 1)\n      {\n        //      noalias(*(vOut->dense())) = ublas::row(ublas::subrange(*mat.Dense, r, r+1,pos, endPos),0);\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n      }\n      else if (_num == 2)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<TriangMat >(*mat.Triang, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n      }\n      else if (_num == 3)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SymMat >(*mat.Sym, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n      }\n      else if (_num == 4)\n      {\n        // #ifdef BOOST_LIMITATION\n        //         SiconosMatrixException(\"SimpleMatrix::getSubRow warning - ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n        // #else\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n        // #endif\n      }\n      else //if(_num==5){\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<BandedMat >(*mat.Banded, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n    }\n    else // if numV == 4\n    {\n      if (_num == 4)\n      {\n#ifdef BOOST_LIMITATION\n        SiconosMatrixException(\"SimpleMatrix::getSubRow warning - ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n        noalias(*(vOut->sparse())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n#endif\n      }\n      else\n        SiconosMatrixException::selfThrow(\"getSubRow(row,v): inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n\n}\n\nvoid SimpleMatrix::setSubRow(unsigned int r, unsigned int pos, SP::SiconosVector vIn)\n{\n  // Set row number r, starting from element at position pos, of current matrix with vIn.\n  unsigned int numV = vIn->num();\n  if (r >= size(0))\n    SiconosMatrixException::selfThrow(\"setSubRow(row): row is out of range\");\n\n  if (vIn->size() > size(1) - pos)\n    SiconosMatrixException::selfThrow(\"setSubRow(row,v): inconsistent sizes between this and v.\");\n\n  if (_num == 6 || _num == 7)\n    SiconosMatrixException::selfThrow(\"setSubRow(row,v): current matrix is read-only (zero or identity).\");\n\n  {\n    unsigned int nbEl = vIn->size();\n    if (_num == 1)\n    {\n      if (numV == 1)\n      {\n        noalias(ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl))) = *vIn->dense();\n      }\n      else if (numV == 4)\n      {\n        ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl)) = *vIn->sparse();\n      }\n    }\n    else if (_num == 4 && numV == 4)\n#ifdef BOOST_LIMITATION\n      SiconosMatrixException(\"SimpleMatrix::setSubRow warning - ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n      ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl)) = *vIn->sparse();\n#endif\n    else\n      SiconosMatrixException::selfThrow(\"setSubRow(row,v): inconsistent types between current matrix and v.\");\n    resetLU();\n  }\n\n}\n\nvoid SimpleMatrix::getSubCol(unsigned int r, unsigned int pos, SP::SiconosVector vOut) const\n{\n  // Get col _number r of current matrix, starting from element at position pos, and copy it into vOut.\n  if (r >= size(1))\n    SiconosMatrixException::selfThrow(\"getSubCol(col,pos,v): col is out of range\");\n\n  if (vOut->size() > size(0) - pos)\n    SiconosMatrixException::selfThrow(\"getSubCol(col,pos,v): inconsistent sizes between this and v.\");\n\n  if (_num == 7) // identity matrix\n  {\n    vOut->zero();\n    if (r >= pos)\n      (*vOut)(r - pos) = 1.0;\n  }\n  else if (_num == 6) // Zero matrix\n    vOut->zero();\n  else\n  {\n    unsigned int numV = vOut->num();\n    unsigned int nbEl = vOut->size();\n\n    if (numV == 1)\n    {\n      if (_num == 1)\n      {\n        //      noalias(*(vOut->dense())) = ublas::row(ublas::subrange(*mat.Dense, r, r+1,pos, endPos),0);\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n      }\n      else if (_num == 2)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<TriangMat >(*mat.Triang, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n      }\n      else if (_num == 3)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SymMat >(*mat.Sym, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n      }\n      else if (_num == 4)\n      {\n#ifdef BOOST_LIMITATION\n        SiconosMatrixException(\"SimpleMatrix::getSubCol warning - ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n#endif\n      }\n      else //if(_num==5){\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<BandedMat >(*mat.Banded, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n    }\n    else // if numV == 4\n    {\n      if (_num == 4)\n      {\n#ifdef BOOST_LIMITATION\n        SiconosMatrixException(\"SimpleMatrix::getSubCol warning - ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n        noalias(*(vOut->sparse())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n#endif\n      }\n      else\n        SiconosMatrixException::selfThrow(\"getSubCol(col,v): inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n\n}\n\nvoid SimpleMatrix::setSubCol(unsigned int r, unsigned int pos, SP::SiconosVector vIn)\n{\n  // Set column number r, starting from element at position pos, of current matrix with vIn.\n  unsigned int numV = vIn->num();\n  if (r >= size(1))\n    SiconosMatrixException::selfThrow(\"setSubCol(col): col is out of range\");\n\n  if (vIn->size() > size(0) - pos)\n    SiconosMatrixException::selfThrow(\"setSubCol(col,v): inconsistent sizes between this and v.\");\n\n  if (_num == 6 || _num == 7)\n    SiconosMatrixException::selfThrow(\"setSubCol(col,v): current matrix is read-only (zero or identity).\");\n\n  {\n    unsigned int nbEl = vIn->size();\n    if (_num == 1)\n    {\n      if (numV == 1)\n      {\n        noalias(ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl))) = *vIn->dense();\n      }\n      else if (numV == 4)\n      {\n        ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl)) = *vIn->sparse();\n      }\n    }\n    else if (_num == 4 && numV == 4)\n#ifdef BOOST_LIMITATION\n      SiconosMatrixException(\"SimpleMatrix::setSubCol warning - ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n      ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl)) = *vIn->sparse();\n#endif\n    else\n      SiconosMatrixException::selfThrow(\"setSubCol(row,v): inconsistent types between current matrix and v.\");\n    resetLU();\n  }\n}\n\n\n", "meta": {"hexsha": "2d0c19e228a1b56d1af710f50b684b43690bc5b9", "size": 32910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixSetGet.cpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "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/SimpleMatrixSetGet.cpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "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/SimpleMatrixSetGet.cpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "avg_line_length": 35.8496732026, "max_line_length": 183, "alphanum_fraction": 0.596931024, "num_tokens": 9711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.06754669630158144, "lm_q1q2_score": 0.03035498780035872}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP\r\n\r\n\r\n\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/core/point_order.hpp>\r\n#include <boost/geometry/core/exterior_ring.hpp>\r\n\r\n#include <boost/geometry/geometries/concepts/check.hpp>\r\n\r\n#include <boost/geometry/strategies/convex_hull.hpp>\r\n#include <boost/geometry/strategies/concepts/convex_hull_concept.hpp>\r\n\r\n#include <boost/geometry/views/detail/range_type.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/as_range.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace convex_hull\r\n{\r\n\r\ntemplate\r\n<\r\n    typename Geometry,\r\n    order_selector Order,\r\n    typename Strategy\r\n>\r\nstruct hull_insert\r\n{\r\n\r\n    // Member template function (to avoid inconvenient declaration\r\n    // of output-iterator-type, from hull_to_geometry)\r\n    template <typename OutputIterator>\r\n    static inline OutputIterator apply(Geometry const& geometry,\r\n            OutputIterator out, Strategy const& strategy)\r\n    {\r\n        typename Strategy::state_type state;\r\n\r\n        strategy.apply(geometry, state);\r\n        strategy.result(state, out, Order == clockwise);\r\n        return out;\r\n    }\r\n};\r\n\r\ntemplate\r\n<\r\n    typename Geometry,\r\n    typename OutputGeometry,\r\n    typename Strategy\r\n>\r\nstruct hull_to_geometry\r\n{\r\n    static inline void apply(Geometry const& geometry, OutputGeometry& out,\r\n            Strategy const& strategy)\r\n    {\r\n        hull_insert\r\n            <\r\n                Geometry,\r\n                geometry::point_order<OutputGeometry>::value,\r\n                Strategy\r\n            >::apply(geometry,\r\n                std::back_inserter(\r\n                    // Handle linestring, ring and polygon the same:\r\n                    detail::as_range\r\n                        <\r\n                            typename range_type<OutputGeometry>::type\r\n                        >(out)), strategy);\r\n    }\r\n};\r\n\r\n\r\n}} // namespace detail::convex_hull\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\r\n<\r\n    typename Tag1,\r\n    typename Geometry,\r\n    typename Output,\r\n    typename Strategy\r\n>\r\nstruct convex_hull\r\n    : detail::convex_hull::hull_to_geometry<Geometry, Output, Strategy>\r\n{};\r\n\r\n\r\ntemplate\r\n<\r\n    typename GeometryTag,\r\n    order_selector Order,\r\n    typename GeometryIn, typename Strategy\r\n >\r\nstruct convex_hull_insert\r\n    : detail::convex_hull::hull_insert<GeometryIn, Order, Strategy>\r\n{};\r\n\r\n\r\n} // namespace dispatch\r\n#endif // DOXYGEN_NO_DISPATCH\r\n\r\n\r\ntemplate<typename Geometry1, typename Geometry2, typename Strategy>\r\ninline void convex_hull(Geometry1 const& geometry,\r\n            Geometry2& out, Strategy const& strategy)\r\n{\r\n    concept::check_concepts_and_equal_dimensions\r\n        <\r\n            const Geometry1,\r\n            Geometry2\r\n        >();\r\n\r\n    BOOST_CONCEPT_ASSERT( (geometry::concept::ConvexHullStrategy<Strategy>) );\r\n\r\n\r\n    dispatch::convex_hull\r\n        <\r\n            typename tag<Geometry1>::type,\r\n            Geometry1,\r\n            Geometry2,\r\n            Strategy\r\n        >::apply(geometry, out, strategy);\r\n}\r\n\r\n\r\n/*!\r\n\\brief \\brief_calc{convex hull}\r\n\\ingroup convex_hull\r\n\\details \\details_calc{convex_hull,convex hull}.\r\n\\tparam Geometry1 \\tparam_geometry\r\n\\tparam Geometry2 \\tparam_geometry\r\n\\param geometry \\param_geometry,  input geometry\r\n\\param hull \\param_geometry \\param_set{convex hull}\r\n\r\n\\qbk{[include reference/algorithms/convex_hull.qbk]}\r\n */\r\ntemplate<typename Geometry1, typename Geometry2>\r\ninline void convex_hull(Geometry1 const& geometry,\r\n            Geometry2& hull)\r\n{\r\n    concept::check_concepts_and_equal_dimensions\r\n        <\r\n            const Geometry1,\r\n            Geometry2\r\n        >();\r\n\r\n    typedef typename point_type<Geometry2>::type point_type;\r\n\r\n    typedef typename strategy_convex_hull\r\n        <\r\n            typename cs_tag<point_type>::type,\r\n            Geometry1,\r\n            point_type\r\n        >::type strategy_type;\r\n\r\n    convex_hull(geometry, hull, strategy_type());\r\n}\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace convex_hull\r\n{\r\n\r\n\r\ntemplate<typename Geometry, typename OutputIterator, typename Strategy>\r\ninline OutputIterator convex_hull_insert(Geometry const& geometry,\r\n            OutputIterator out, Strategy const& strategy)\r\n{\r\n    // Concept: output point type = point type of input geometry\r\n    concept::check<Geometry const>();\r\n    concept::check<typename point_type<Geometry>::type>();\r\n\r\n    BOOST_CONCEPT_ASSERT( (geometry::concept::ConvexHullStrategy<Strategy>) );\r\n\r\n    return dispatch::convex_hull_insert\r\n        <\r\n            typename tag<Geometry>::type,\r\n            geometry::point_order<Geometry>::value,\r\n            Geometry, Strategy\r\n        >::apply(geometry, out, strategy);\r\n}\r\n\r\n\r\n/*!\r\n\\brief Calculate the convex hull of a geometry, output-iterator version\r\n\\ingroup convex_hull\r\n\\tparam Geometry the input geometry type\r\n\\tparam OutputIterator: an output-iterator\r\n\\param geometry the geometry to calculate convex hull from\r\n\\param out an output iterator outputing points of the convex hull\r\n\\note This overloaded version outputs to an output iterator.\r\nIn this case, nothing is known about its point-type or\r\n    about its clockwise order. Therefore, the input point-type\r\n    and order are copied\r\n\r\n */\r\ntemplate<typename Geometry, typename OutputIterator>\r\ninline OutputIterator convex_hull_insert(Geometry const& geometry,\r\n            OutputIterator out)\r\n{\r\n    // Concept: output point type = point type of input geometry\r\n    concept::check<Geometry const>();\r\n    concept::check<typename point_type<Geometry>::type>();\r\n\r\n    typedef typename point_type<Geometry>::type point_type;\r\n\r\n    typedef typename strategy_convex_hull\r\n        <\r\n            typename cs_tag<point_type>::type,\r\n            Geometry,\r\n            point_type\r\n        >::type strategy_type;\r\n\r\n    return convex_hull_insert(geometry, out, strategy_type());\r\n}\r\n\r\n\r\n}} // namespace detail::convex_hull\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_HPP\r\n", "meta": {"hexsha": "6e0a67f32227cf702b0f484b17aab5e099352b21", "size": 6799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependencies/boost_geometry/boost/geometry/algorithms/convex_hull.hpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-30T18:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T18:41:39.000Z", "max_issues_repo_path": "dependencies/boost_geometry/boost/geometry/algorithms/convex_hull.hpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dependencies/boost_geometry/boost/geometry/algorithms/convex_hull.hpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4153225806, "max_line_length": 80, "alphanum_fraction": 0.6725989116, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.06187598615612916, "lm_q1q2_score": 0.030213016607592808}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n#define CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n\n#include <stdexcept>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"crocoddyl/core/fwd.hpp\"\n#include \"crocoddyl/core/state-base.hpp\"\n#include \"crocoddyl/core/utils/to-string.hpp\"\n#include \"crocoddyl/core/utils/math.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Abstract class for differential action model\n *\n * A differential action model describes a time-continuous action model with a first-order ODE, i.e.\n * \\f[\n * \\dot{\\mathbf{v}} = \\mathbf{f}(\\mathbf{q}, \\mathbf{v}, \\mathbf{u})\n * \\f]\n * where the configuration \\f$\\mathbf{q}\\in\\mathcal{Q}\\f$ lies in the configuration manifold described with a\n * `nq`-tuple, the velocity \\f$\\mathbf{v}\\in T_{\\mathbf{q}}\\mathcal{Q}\\f$ its a tangent vector to this manifold with\n * `nv` dimension, and \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$ is the input commands. Both, configuration and velocity,\n * describes the system space \\f$\\mathbf{x}\\in\\mathbf{X}\\f$ which lies in the state manifold. Note that the\n * acceleration \\f$\\dot{\\mathbf{v}}\\in T_{\\mathbf{q}}\\mathcal{Q}\\f$ lies also in the tangent space of the configuration\n * manifold.\n *\n * `calc` computes the acceleration and cost and `calcDiff` computes the derivatives of the dynamics and cost function.\n * Concretely speaking, `calcDiff` builds a linear-quadratic approximation of the differential action, where the\n * dynamics and cost functions have linear and quadratic forms, respectively. \\f$\\mathbf{f_x}\\in\\mathbb{R}^{nv\\times\n * ndx}\\f$, \\f$\\mathbf{f_u}\\in\\mathbb{R}^{nv\\times nu}\\f$ are the Jacobians of the dynamics;\n * \\f$\\mathbf{l_x}\\in\\mathbb{R}^{ndx}\\f$, \\f$\\mathbf{l_u}\\in\\mathbb{R}^{nu}\\f$,\n * \\f$\\mathbf{l_{xx}}\\in\\mathbb{R}^{ndx\\times ndx}\\f$, \\f$\\mathbf{l_{xu}}\\in\\mathbb{R}^{ndx\\times nu}\\f$,\n * \\f$\\mathbf{l_{uu}}\\in\\mathbb{R}^{nu\\times nu}\\f$ are the Jacobians and Hessians of the cost function, respectely.\n *\n * \\sa `calc()`, `calcDiff()`, `createData()`\n */\ntemplate <typename _Scalar>\nclass DifferentialActionModelAbstractTpl {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef DifferentialActionDataAbstractTpl<Scalar> DifferentialActionDataAbstract;\n  typedef StateAbstractTpl<Scalar> StateAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  /**\n   * @brief Initialize the differential action model\n   *\n   * @param[in] state  State Dimension of state configuration tuple\n   * @param[in] nu     Dimension of control vector\n   * @param[in] nr     Dimension of cost-residual vector\n   */\n  DifferentialActionModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t& nu,\n                                     const std::size_t& nr = 0);\n  virtual ~DifferentialActionModelAbstractTpl();\n\n  /**\n   * @brief Compute the system acceleration and cost value\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   * @param[in] u     Control input\n   */\n  virtual void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                    const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Compute the derivatives of the dynamics and cost functions\n   *\n   * It computes the partial derivatives of the dynamical system and the cost function. It assumes that calc has been\n   * run first. This function builds a quadratic approximation of the time-continuous action model (i.e. dynamical\n   * system and cost function).\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   * @param[in] u     Control input\n   */\n  virtual void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data,\n                        const Eigen::Ref<const VectorXs>& x, const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Create the differential action data\n   *\n   * @return the differential action data\n   */\n  virtual boost::shared_ptr<DifferentialActionDataAbstract> createData();\n\n  /**\n   * @brief Checks that a specific data belongs to this model\n   */\n  virtual bool checkData(const boost::shared_ptr<DifferentialActionDataAbstract>& data);\n\n  /**\n   * @copybrief calc()\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   */\n  void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @copybrief calcDiff()\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   */\n  void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief Computes the quasic static commands\n   *\n   * The quasic static commands are the ones produced for a the reference posture as an equilibrium point, i.e.\n   * for \\f$\\mathbf{f(q,v=0,u)=0}\\f$\n   *\n   * @param[in] data    Differential action data\n   * @param[out] u      Quasic static commands\n   * @param[in] x       State point (velocity has to be zero)\n   * @param[in] maxiter Maximum allowed number of iterations\n   * @param[in] tol     Tolerance\n   */\n  virtual void quasiStatic(const boost::shared_ptr<DifferentialActionDataAbstract>& data, Eigen::Ref<VectorXs> u,\n                           const Eigen::Ref<const VectorXs>& x, const std::size_t& maxiter = 100,\n                           const Scalar& tol = Scalar(1e-9));\n\n  /**\n   * @copybrief quasicStatic()\n   *\n   * @copydetails quasicStatic()\n   *\n   * @param[in] data    Differential action data\n   * @param[in] x       State point (velocity has to be zero)\n   * @param[in] maxiter Maximum allowed number of iterations\n   * @param[in] tol     Tolerance\n   * @return Quasic static commands\n   */\n  VectorXs quasiStatic_x(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const VectorXs& x,\n                         const std::size_t& maxiter = 100, const Scalar& tol = Scalar(1e-9));\n\n  /**\n   * @brief Return the dimension of the control input\n   */\n  const std::size_t& get_nu() const;\n\n  /**\n   * @brief Return the dimension of the cost-residual vector\n   */\n  const std::size_t& get_nr() const;\n\n  /**\n   * @brief Return the state\n   */\n  const boost::shared_ptr<StateAbstract>& get_state() const;\n\n  /**\n   * @brief Return the control lower bound\n   */\n  const VectorXs& get_u_lb() const;\n\n  /**\n   * @brief Return the control upper bound\n   */\n  const VectorXs& get_u_ub() const;\n\n  /**\n   * @brief Indicates if there are defined control limits\n   */\n  bool const& get_has_control_limits() const;\n\n  /**\n   * @brief Modify the control lower bounds\n   */\n  void set_u_lb(const VectorXs& u_lb);\n\n  /**\n   * @brief Modify the control upper bounds\n   */\n  void set_u_ub(const VectorXs& u_ub);\n\n protected:\n  std::size_t nu_;                          //!< Control dimension\n  std::size_t nr_;                          //!< Dimension of the cost residual\n  boost::shared_ptr<StateAbstract> state_;  //!< Model of the state\n  VectorXs unone_;                          //!< Neutral state\n  VectorXs u_lb_;                           //!< Lower control limits\n  VectorXs u_ub_;                           //!< Upper control limits\n  bool has_control_limits_;                 //!< Indicates whether any of the control limits is finite\n\n  void update_has_control_limits();\n};\n\ntemplate <typename _Scalar>\nstruct DifferentialActionDataAbstractTpl {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  template <template <typename Scalar> class Model>\n  explicit DifferentialActionDataAbstractTpl(Model<Scalar>* const model)\n      : cost(0.),\n        xout(model->get_state()->get_nv()),\n        Fx(model->get_state()->get_nv(), model->get_state()->get_ndx()),\n        Fu(model->get_state()->get_nv(), model->get_nu()),\n        r(model->get_nr()),\n        Lx(model->get_state()->get_ndx()),\n        Lu(model->get_nu()),\n        Lxx(model->get_state()->get_ndx(), model->get_state()->get_ndx()),\n        Lxu(model->get_state()->get_ndx(), model->get_nu()),\n        Luu(model->get_nu(), model->get_nu()) {\n    xout.setZero();\n    r.setZero();\n    Fx.setZero();\n    Fu.setZero();\n    Lx.setZero();\n    Lu.setZero();\n    Lxx.setZero();\n    Lxu.setZero();\n    Luu.setZero();\n  }\n  virtual ~DifferentialActionDataAbstractTpl() {}\n\n  Scalar cost;\n  VectorXs xout;\n  MatrixXs Fx;\n  MatrixXs Fu;\n  VectorXs r;\n  VectorXs Lx;\n  VectorXs Lu;\n  MatrixXs Lxx;\n  MatrixXs Lxu;\n  MatrixXs Luu;\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/diff-action-base.hxx\"\n\n#endif  // CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n", "meta": {"hexsha": "e5507af0724163f84920d31075e45f6c5923a402", "size": 9357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/diff-action-base.hpp", "max_stars_repo_name": "nyu-locomotion/crocoddyl", "max_stars_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "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/diff-action-base.hpp", "max_issues_repo_name": "nyu-locomotion/crocoddyl", "max_issues_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/diff-action-base.hpp", "max_forks_repo_name": "nyu-locomotion/crocoddyl", "max_forks_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "max_forks_repo_licenses": ["BSD-3-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.4085603113, "max_line_length": 119, "alphanum_fraction": 0.6459335257, "num_tokens": 2414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.06371499291856339, "lm_q1q2_score": 0.030117024365592802}}
{"text": "#include \"blocks.h\"\n\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <boost/pending/disjoint_sets.hpp>\n\nnamespace py = pybind11;\n\nnamespace {\n\nconst char* blockwise_means_doc = R\"(blockwise_means(blocks, input)\n\nAverage the elements of the given vector within each block.\n\nSpecifically, the coordinate ``i`` of the returned vector will contain the mean\nof all entries ``j`` in ``input`` that have ``blocks[j]=b``.\n\nArguments\n---------\nblocks : numpy.ndarray\n    A vector of ints that denote the block memberships of each position.\n\n    The set of numbers in this vector should start at zero and be consecutive.\n\ninput : numpy.ndarray\n    A vector of same size as ``block`` containing the data to be averaged.\n\nReturns\n--------\nnumpy.ndarray\n    A vector of same size as the inputs that contains the block-wise averages.\n)\";\n\n}  // namespace\n\npy::array_t<float> blockwise_means(const py::array_t<int>& blocks_,\n                                   const py::array_t<float>& input_) {\n    if (blocks_.ndim() != 1 || input_.ndim() != 1) {\n        throw std::runtime_error(\"the given arrays must be one dimensional\");\n    }\n    if (blocks_.shape(0) != input_.shape(0)) {\n        throw std::runtime_error(\"the number of elements in the must match\");\n    }\n\n    auto blocks = blocks_.unchecked<1>();\n    auto input = input_.unchecked<1>();\n\n    int n_blocks = 0;\n    for (int i = 0; i < blocks.shape(0); i++) {\n        if (blocks[i] < 0) {\n            throw std::runtime_error(\"the block ids must be non-negative\");\n        }\n        n_blocks = std::max(n_blocks, 1 + blocks(i));\n    }\n\n    std::vector<float> blocks_sums(n_blocks);\n    std::vector<int> blocks_total(n_blocks);\n\n    for (int i = 0; i < blocks.shape(0); i++) {\n        blocks_sums[blocks(i)] += input[i];\n        ++blocks_total[blocks[i]];\n    }\n    for (int i = 0; i < n_blocks; i++) {\n        blocks_sums[i] /= static_cast<float>(blocks_total[i]);\n    }\n\n    py::array_t<float> output_ = py::array_t<float>(blocks.shape(0));\n    auto output = output_.mutable_unchecked<1>();\n    for (int i = 0; i < output_.shape(0); i++) {\n        output(i) = blocks_sums[blocks[i]];\n    }\n    return output_;\n}\n\n\nnamespace {\n\nconst char* blocks_2d_doc = R\"(blocks_2d(matrix)\n\nReturn the connected components of the matrix.\n\nTwo positions are connected iff they hold the same value, and they differ in\none coordinate by one (i.e., it is a 4-connected grid).\n\nArguments\n---------\nmatrix : numpy.ndarray\n    The two-dimensional matrix.\n\nReturns\n--------\nnumpy.ndarray\n    A matrix of ints, same size as the input.\n\n    The positions corresponding to the same connected component have the\n    same label. The labels are consecutive integers starting at zero.\n)\";\n\n}  // namespace\n\n\npy::array_t<int> blocks_2d(const py::array_t<double>& matrix_) {\n    if (matrix_.ndim() != 2) {\n        throw std::runtime_error(\"the given matrix must be two dimensional\");\n    }\n    auto matrix = matrix_.unchecked<2>();\n\n    std::vector<int> ranks(matrix.size());\n    std::vector<int> parents(matrix.size());\n    boost::disjoint_sets<int*, int*> union_find(&ranks[0], &parents[0]);\n\n    #define IDX(i, j) ((i) * static_cast<int>(matrix.shape(1)) + (j))\n\n    for (int i = 0; i < matrix_.shape(0); i++) {\n        for (int j = 0; j < matrix_.shape(1); j++) {\n            int idx = IDX(i, j);\n            union_find.make_set(idx);\n            if (i > 0 && matrix(i, j) == matrix(i - 1, j)) {\n                union_find.union_set(idx, IDX(i - 1, j));\n            }\n            if (j > 0 && matrix(i, j) == matrix(i, j - 1)) {\n                union_find.union_set(idx, IDX(i, j - 1));\n            }\n        }\n    }\n\n    std::unordered_map<int, int> root_to_idx;\n    py::array_t<int> output_ = py::array_t<int>({matrix_.shape(0),\n                                                 matrix_.shape(1)});\n    auto output = output_.mutable_unchecked<2>();\n    int next_id = 0;\n    for (int i = 0; i < matrix.shape(0); i++) {\n        for (int j = 0; j < matrix.shape(1); j++) {\n            int idx = IDX(i, j);\n            int root = union_find.find_set(idx);\n            auto iter = root_to_idx.find(root);\n            if (iter == root_to_idx.end()) {\n                output(i, j) = next_id;\n                root_to_idx[root] = next_id++;\n            } else {\n                output(i, j) = iter->second;\n            }\n        }\n    }\n\n    return output_;\n}\n\n\nPYBIND11_MODULE(blocks, m) {\n    py::options options;\n    options.disable_function_signatures();\n    m.def(\"blockwise_means\", blockwise_means, blockwise_means_doc);\n    m.def(\"blocks_2d\", blocks_2d, blocks_2d_doc);\n}\n", "meta": {"hexsha": "734c697338c2a1b52ba2c4ddbcca95f0feef17df", "size": 4606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/blocks.cpp", "max_stars_repo_name": "marcocannici/torch-submod", "max_stars_repo_head_hexsha": "91d9f7fce775847fe4a7ab6a55d239485c068265", "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/blocks.cpp", "max_issues_repo_name": "marcocannici/torch-submod", "max_issues_repo_head_hexsha": "91d9f7fce775847fe4a7ab6a55d239485c068265", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/blocks.cpp", "max_forks_repo_name": "marcocannici/torch-submod", "max_forks_repo_head_hexsha": "91d9f7fce775847fe4a7ab6a55d239485c068265", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-10T07:25:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T07:25:06.000Z", "avg_line_length": 29.3375796178, "max_line_length": 79, "alphanum_fraction": 0.5946591403, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388504, "lm_q2_score": 0.06754668550840877, "lm_q1q2_score": 0.030094044382604098}}
{"text": "// Filename: CirculationModel_with_lv.cpp\n// Created on 20 Aug 2007 by Boyce Griffith\n\n// Modified 2019, Alexander D. Kaiser\n\n#include \"CirculationModel_with_lv.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_with_lv::CirculationModel_with_lv(const fourier_series_data *fourier_aorta, \n                                                   const fourier_series_data *fourier_atrium, \n                                                   const fourier_series_data *fourier_ventricle, \n                                                   string aorta_vertices_file_name,\n                                                   string atrium_vertices_file_name,\n                                                   const double  cycle_duration,\n                                                   const double  t_offset_bcs_unscaled, \n                                                   const double  initial_time)\n    : \n      d_object_name(\"circ_model_with_lv\"),  // constant name here  \n      d_registered_for_restart(true),      // always true\n      d_fourier_aorta (fourier_aorta), \n      d_fourier_atrium(fourier_atrium),       \n      d_fourier_ventricle(fourier_ventricle), \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_aorta      (0.0), \n      d_Q_left_atrium(0.0),\n      d_Q_mitral     (0.0),\n      d_time(initial_time), \n      d_area_aorta(0.0),\n      d_area_atrium(0.0),\n      d_area_initialized(false)\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    // read aorta and atrium vertices from file \n    ifstream aorta_file(aorta_vertices_file_name.c_str(), ios::in);\n\n    if(!aorta_file){\n        TBOX_ERROR(\"Aorta file not found\\n\"); \n    }\n\n    aorta_file >> d_n_pts_aorta; \n    \n    d_aorta_points_x = new double[d_n_pts_aorta]; \n    d_aorta_points_y = new double[d_n_pts_aorta]; \n\n    double z,z_prev; \n    double tol = 1.0e-2; \n\n    for (int i=0; i<d_n_pts_aorta; i++){\n        aorta_file >> d_aorta_points_x[i]; \n        aorta_file >> d_aorta_points_y[i];\n        aorta_file >> z; \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 aorta file close\\n\"; \n    aorta_file.close(); \n\n    ifstream atrium_file(atrium_vertices_file_name.c_str(), ios::in);\n    if(!atrium_file){\n        TBOX_ERROR(\"Atrium file not found\\n\"); \n    }\n    atrium_file >> d_n_pts_atrium; \n    \n    d_atrium_points_x = new double[d_n_pts_atrium]; \n    d_atrium_points_y = new double[d_n_pts_atrium]; \n\n    for (int i=0; i<d_n_pts_atrium; i++){\n        atrium_file >> d_atrium_points_x[i]; \n        atrium_file >> d_atrium_points_y[i];\n        atrium_file >> z; \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    atrium_file.close();\n\n    pout << \"passed contstructor\\n\"; \n\n    return;\n} // CirculationModel\n\nCirculationModel_with_lv::~CirculationModel_with_lv()\n{\n    return;\n} // ~CirculationModel_with_lv\n\n\nvoid CirculationModel_with_lv::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_aorta_local = 0.0; \n    double Q_left_atrium_local = 0.0; \n\n    double area_aorta_local = 0.0; \n    double area_atrium_local = 0.0; \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                // always looking for z flux here \n                // side is always 1, top of box \n                static const int axis = 2;\n                int side = 1; \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                        const int in_aorta  = this->point_in_aorta (X[0],X[1]); \n                        const int in_atrium = this->point_in_atrium(X[0],X[1]); \n\n                        if (in_aorta && in_atrium){\n                            TBOX_ERROR(\"Position is within both aorta and atrium, should be impossible\\n\"); \n                        }\n\n                        if (in_aorta)\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 = n[axis] * dV / dx[axis];\n                                Q_aorta_local += (*U_data)(i_s)*dA;\n\n                                if (!d_area_initialized){\n                                    area_aorta_local += dA;\n                                }\n\n                            }\n                        }\n\n                        if (in_atrium)\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 = n[axis] * dV / dx[axis];\n                                Q_left_atrium_local += (*U_data)(i_s)*dA;\n\n                                if (!d_area_initialized){\n                                    area_atrium_local += dA;\n                                }\n                            }\n                        }\n                    }\n                }\n                \n            }\n        }\n    }\n\n    d_Q_aorta       = SAMRAI_MPI::sumReduction(Q_aorta_local);\n    d_Q_left_atrium = SAMRAI_MPI::sumReduction(Q_left_atrium_local);\n\n    if (!d_area_initialized){\n        d_area_aorta  = SAMRAI_MPI::sumReduction(area_aorta_local);\n        d_area_atrium = SAMRAI_MPI::sumReduction(area_atrium_local);  \n        d_area_initialized = true;       \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_aorta->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_aorta->dt));\n    \n    // // take periodic reduction\n    d_current_idx_series = k % (d_fourier_aorta->N_times);\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_with_lv::set_Q_mitral(double Q_mitral){\n    d_Q_mitral = Q_mitral; \n}\n\n\nvoid\nCirculationModel_with_lv::putToDatabase(Pointer<Database> db)\n{\n\n    db->putInteger(\"d_current_idx_series\", d_current_idx_series); \n    db->putDouble(\"d_Q_aorta\", d_Q_aorta); \n    db->putDouble(\"d_Q_left_atrium\", d_Q_left_atrium);\n    db->putDouble(\"d_Q_mitral\", d_Q_mitral);\n    db->putDouble(\"d_time\", d_time); \n    return; \n} // putToDatabase\n\nvoid CirculationModel_with_lv::print_summary(){\n\n    double P_aorta     = d_fourier_aorta->values[d_current_idx_series]; \n    double P_atrium    = d_fourier_atrium->values[d_current_idx_series];\n    double P_ventricle = d_fourier_ventricle->values[d_current_idx_series];\n\n    pout << \"% time \\t P_aorta (mmHg)\\t P_atrium (mmHg)\\t P_ventricle (mmHg)\\t Q_Aorta (ml/s)\\t d_Q_left_atrium (ml/s)\\tQ_mitral (ml/s) \\t idx\\n\" ; \n    pout << d_time << \" \" << P_aorta <<  \" \" << P_atrium << \" \" << P_ventricle << \" \" << d_Q_aorta << \" \" << d_Q_left_atrium << \" \" << d_Q_mitral << \" \" << d_current_idx_series << \"\\n\";    \n\n}\n\nint CirculationModel_with_lv::point_in_aorta(double testx, double testy){\n    // checks whether given point is in aorta \n    return pnpoly(d_n_pts_aorta, d_aorta_points_x, d_aorta_points_y, testx, testy); \n}\n\nint CirculationModel_with_lv::point_in_atrium(double testx, double testy){\n    // checks whether given point is in atrium\n    return pnpoly(d_n_pts_atrium, d_atrium_points_x, d_atrium_points_y, testx, testy); \n}\n\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\nCirculationModel_with_lv::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_aorta (mmHg)\\t P_atrium (mmHg)\\t P_ventricle (mmHg)\\t Q_Aorta (ml/s)\\t d_Q_left_atrium (ml/s)\\tQ_mitral (ml/s)\"\n                 << \"\\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_aorta     = d_fourier_aorta->values[d_current_idx_series]; \n        double P_atrium    = d_fourier_atrium->values[d_current_idx_series];\n        double P_ventricle = d_fourier_ventricle->values[d_current_idx_series];\n        fout << \" \" << P_aorta <<  \" \" << P_atrium << \" \" << P_ventricle << \" \" << d_Q_aorta << \" \" << d_Q_left_atrium << \" \" << d_Q_mitral << \"; \\n\";\n\n    }\n\n    return;\n} // writeDataFile\n\nvoid\nCirculationModel_with_lv::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_aorta            = db->getDouble(\"d_Q_aorta\"); \n    d_Q_left_atrium      = db->getDouble(\"d_Q_left_atrium\");\n    d_Q_mitral           = db->getDouble(\"d_Q_mitral\");\n    d_time               = db->getDouble(\"d_time\");\n\n    return;\n} // getFromRestart\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////\n\n//////////////////////////////////////////////////////////////////////////////", "meta": {"hexsha": "319fc4ba71e06d3ab927f07f9df25009270b6f27", "size": 14625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CirculationModel_with_lv.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_with_lv.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_with_lv.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": 35.8455882353, "max_line_length": 189, "alphanum_fraction": 0.5243760684, "num_tokens": 3561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.07055960156206999, "lm_q1q2_score": 0.030081081707458067}}
{"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_TRAITS_ROOT_INCLUDE\n#define MTL_TRAITS_ROOT_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n\nnamespace mtl { namespace traits {\n\n\n/// Type trait to reduce types to their essentials by removing const, reference, ... and gearing derived types to their bases\ntemplate <typename T>\nstruct root\n{\n    typedef T        type;\n};\n\n// ==========================\n// Remove language attributes\n// ==========================\n\ntemplate <typename T>\nstruct root<T&>\n  : public root<T> {};\n\ntemplate <typename T>\nstruct root<const T>\n  : public root<T> {};\n\n// Redundant specialization to make xlc++ happy\ntemplate <typename T, int R, int C>\nstruct root<const T[R][C]>\n  : public root<T[R][C]> {};\n\n\n// ============\n// Base classes\n// ============\n\n// Implicit dense matrices\n\ntemplate <typename Value>\nstruct root<mtl::matrix::ones_matrix<Value> >\n{\n    typedef mtl::matrix::implicit_dense<mtl::matrix::ones_functor<Value> > type;\n};\n\ntemplate <typename Value>\nstruct root<mtl::matrix::hilbert_matrix<Value> >\n{\n    typedef mtl::matrix::implicit_dense<mtl::matrix::hilbert_functor<Value> > type;\n};\n\ntemplate <typename Vector1, typename Vector2>\nstruct root<mtl::matrix::outer_product_matrix<Vector1, Vector2> >\n{\n    typedef mtl::matrix::implicit_dense<mtl::matrix::outer_product_functor<Vector1, Vector2> > type;\n};\n\n// Matrix map views\n\ntemplate <typename Scaling, typename Matrix>\nstruct root< mtl::matrix::scaled_view<Scaling, Matrix> >\n{\n    typedef mtl::matrix::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::matrix::conj_view<Matrix> >\n{\n    typedef mtl::matrix::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::matrix::negate_view<Matrix> >\n{\n    typedef mtl::matrix::map_view<sfunctor::negate<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::matrix::imag_view<Matrix> >\n{\n    typedef mtl::matrix::map_view<sfunctor::imag<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::matrix::real_view<Matrix> >\n{\n    typedef mtl::matrix::map_view<sfunctor::real<typename Matrix::value_type>, Matrix> type;\n};\n\ntemplate <typename Matrix>\nstruct root< mtl::matrix::hermitian_view<Matrix> >\n{\n    typedef mtl::matrix::map_view<sfunctor::conj<typename Matrix::value_type>, mtl::matrix::transposed_view<Matrix> > type;\n};\n\ntemplate <typename Matrix, typename RScaling>\nstruct root< mtl::matrix::rscaled_view<Matrix, RScaling> >\n{\n    typedef mtl::matrix::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, Matrix> type;\n};\n\ntemplate <typename Matrix, typename Divisor>\nstruct root< mtl::matrix::divide_by_view<Matrix, Divisor> >\n{\n    typedef mtl::matrix::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, Matrix> type;\n};\n\n// Matrix operations\ntemplate <typename M1, typename M2> \nstruct root< mtl::matrix::mat_mat_plus_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::plus<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::matrix::mv_mv_plus_expr<M1, M2> >\n{\n    typedef typename root< mtl::matrix::mat_mat_plus_expr<M1, M2> >::type type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::matrix::mat_mat_minus_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::minus<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::matrix::mv_mv_minus_expr<M1, M2> >\n{\n    typedef typename root< mtl::matrix::mat_mat_minus_expr<M1, M2> >::type type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::matrix::mat_mat_times_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::times<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\ntemplate <typename M1, typename M2> \nstruct root< mtl::matrix::mat_mat_ele_times_expr<M1, M2> >\n{\n    typedef mtl::sfunctor::times<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;\n    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;\n};\n\n\n// Vector assignment expressions\n\ntemplate <typename E1, typename E2>\nstruct root< vector::vec_vec_asgn_expr<E1, E2> >\n{\n    typedef vector::vec_vec_aop_expr< E1, E2, mtl::sfunctor::assign<typename E1::value_type, typename E2::value_type> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vector::vec_vec_plus_asgn_expr<E1, E2> >\n{\n    typedef vector::vec_vec_aop_expr< E1, E2, mtl::sfunctor::plus_assign<typename E1::value_type, typename E2::value_type> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vector::vec_vec_minus_asgn_expr<E1, E2> >\n{\n    typedef vector::vec_vec_aop_expr< E1, E2, mtl::sfunctor::minus_assign<typename E1::value_type, typename E2::value_type> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vector::vec_scal_asgn_expr<E1, E2> >\n{\n    typedef vector::vec_scal_aop_expr< E1, E2, mtl::sfunctor::assign<typename E1::value_type, E2> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vector::vec_scal_times_asgn_expr<E1, E2> >\n{\n    typedef vector::vec_scal_aop_expr< E1, E2, mtl::sfunctor::times_assign<typename E1::value_type, E2> > type;\n};\n\ntemplate <typename E1, typename E2>\nstruct root< vector::vec_scal_div_asgn_expr<E1, E2> >\n{\n    typedef vector::vec_scal_aop_expr< E1, E2, mtl::sfunctor::divide_assign<typename E1::value_type, E2> > type;\n};\n\ntemplate <typename Scaling, typename Vector>\nstruct root< vector::scaled_view<Scaling, Vector> >\n{\n    typedef vector::map_view<tfunctor::scale<Scaling, typename Vector::value_type>, Vector> type;\n};\n\ntemplate <typename Vector, typename RScaling>\nstruct root< vector::rscaled_view<Vector, RScaling> >\n{\n    typedef vector::map_view<tfunctor::rscale<typename Vector::value_type, RScaling>, Vector> type;\n};\n\ntemplate <typename Vector, typename Divisor>\nstruct root< vector::divide_by_view<Vector, Divisor> >\n{\n    typedef vector::map_view<tfunctor::divide_by<typename Vector::value_type, Divisor>, Vector> type;\n};\n\ntemplate <typename Vector>\nstruct root< vector::conj_view<Vector> >\n{\n    typedef vector::map_view<mtl::sfunctor::conj<typename Vector::value_type>, Vector> type;\n};\n\ntemplate <typename Vector>\nstruct root< vector::negate_view<Vector> >\n{\n    typedef vector::map_view<mtl::sfunctor::negate<typename Vector::value_type>, Vector> type;\n};\n\ntemplate <unsigned BSize, typename Vector>\nstruct root< vector::unrolled1<BSize, Vector> >\n{\n    typedef Vector type;\n};\n\n\n\n#if 0 // template\nstruct root\n{\n    typedef  type;\n};\n#endif\n\n\n}} // namespace mtl::traits\n\n#endif // MTL_TRAITS_ROOT_INCLUDE\n", "meta": {"hexsha": "19058dbb8a40368d4003e8f7b2b329972fcc7911", "size": 7390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/utility/root.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/utility/root.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/utility/root.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": 29.56, "max_line_length": 131, "alphanum_fraction": 0.7244925575, "num_tokens": 2036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906414693485, "lm_q2_score": 0.06371499869663867, "lm_q1q2_score": 0.029868995110215946}}
{"text": "#pragma once\n\n// Include GLM\n#include <glm/glm.hpp>\n\n// Include STL\n#include <vector>\n#include <random>\n#include <utility>\n#include <iostream>\n\n// Eigen CORE\n#include <Eigen/Core>\n\n// Local include\n#include \"SH.hpp\"\n\n/* _Is `a` close to `b` ?_\n *\n * This template function check if a-b is smaller than a fraction of the max\n * between a and b. By default, it checks if it is smaller than 1 percent of\n * the maximum value.\n */\ntemplate<typename T>\ninline bool closeTo(const T& a, const T&b, const T& Percentage = T(0.01)) {\n   if(a == T(0.0) || b == T(0.0)) {\n      return std::abs<T>(a-b) < Percentage;\n   } else {\n      const T c = std::max<T>(std::max<T>(a, b), Percentage);\n      return (std::abs<T>(a-b) < Percentage * c);\n   }\n}\n\n/* _Is `a` inside the confidence interval `[m-s, m+s]?\n *\n * `b` is supposed to be a confidence interval in the form of µ±ε where µ is\n * `b.first` and ε is `b.second`.\n */\ntemplate<typename T>\ninline bool closeTo(const T& a, const std::pair<T,T>& b) {\n   assert(b.second >= T(0));\n   return (a < b.first + b.second) && (a > b.first - b.second);\n}\n\nstruct Vector : public glm::vec3 {\n\n   Vector() : glm::vec3() {}\n   Vector(float x, float y, float z) : glm::vec3(x, y, z) {}\n   Vector(const glm::vec3& w) : glm::vec3(w) {}\n\n   static inline float Dot(const glm::vec3& a, const glm::vec3& b) {\n      return glm::dot<float>(a, b);\n   }\n\n   static inline glm::vec3 Cross(const glm::vec3& a, const glm::vec3& b) {\n      return glm::cross(a, b);\n   }\n\n   static inline glm::vec3 Normalize(const glm::vec3& a) {\n      return glm::normalize(a);\n   }\n\n   static inline float Length(const glm::vec3& a) {\n      return glm::length(a);\n   }\n};\n\nstd::ostream& operator<< (std::ostream& out, const glm::vec3& a) {\n   out << \"[\" << a.x << \", \" << a.y << \", \" << a.z << \"]\";\n   return out;\n}\n\n\nstruct Edge {\n   Edge(const Vector& a, const Vector& b) : A(a), B(b) {}\n   Vector A, B;\n};\n\n/* 'The Triangle' structure represent a spherical triangle of three coordinates\n * A, B and C by storing its Edges in a vcetor.\n *\n * TODO: Extend to the polygon structure\n */\nstruct Triangle : public std::vector<Edge> {\n   Triangle() {\n   }\n   Triangle(const Vector& A, const Vector& B, const Vector& C) {\n     this->push_back(Edge(A, B));\n     this->push_back(Edge(B, C));\n     this->push_back(Edge(C, A));\n   }\n};\n\nstruct Quad: public std::vector<Edge> {\n   Quad() {\n   }\n   Quad(const Vector& A, const Vector& B,\n        const Vector& C, const Vector& D) {\n     this->push_back(Edge(A, B));\n     this->push_back(Edge(B, C));\n     this->push_back(Edge(C, D));\n     this->push_back(Edge(D, A));\n   }\n};\n\nstruct Polygon : public std::vector<Edge> {\n\n   // Constructor\n   Polygon() {\n   }\n   Polygon(const Vector& A, const Vector& B, const Vector& C) {\n      this->push_back(Edge(A, B));\n      this->push_back(Edge(B, C));\n      this->push_back(Edge(C, A));\n   }\n};\n\nstd::ostream& operator<<(std::ostream& out, const Polygon& polygon) {\n   for(auto& edge : polygon) {\n      out << \" + \" << edge.A << std::endl;\n   }\n   return out;\n}\n\nstruct PolygonConstructor : public std::vector<Vector> {\n\n   // Constructor\n   PolygonConstructor() {\n   }\n   PolygonConstructor(const Vector& A, const Vector& B, const Vector& C) {\n      this->push_back(A);\n      this->push_back(B);\n      this->push_back(C);\n   }\n\n   Polygon ProjectToHemisphere(const Vector& p) const {\n      Polygon P;\n#ifdef REMOVE\n      std::cout << \"A = \" << P[0].A << std::endl;\n      std::cout << \"B = \" << P[1].A << std::endl;\n      std::cout << \"C = \" << P[2].A << std::endl;\n#endif\n      for(unsigned int k=0; k<this->size(); ++k) {\n         const Vector& A = this->at(k);\n         const Vector& B = (k == this->size()-1) ? this->at(0) : this->at(k+1);\n\n         P.push_back(Edge(Vector::Normalize(A-p), Vector::Normalize(B-p)));\n      }\n      return P;\n   }\n\n   /* Clamp the Polygon with respect to the Shading normal.\n    */\n   Polygon ProjectToHemisphere(const Vector& p, const Vector& n) const {\n      Polygon P;\n#ifdef REMOVE\n      std::cout << \"A = \" << P[0].A << std::endl;\n      std::cout << \"B = \" << P[1].A << std::endl;\n      std::cout << \"C = \" << P[2].A << std::endl;\n#endif\n      // Constant\n      const unsigned int size = this->size();\n\n      // Starting vector of the Edge. This vector can be clamped if necessary\n      // to account for the shading horizon.\n      unsigned int start = 0;\n      Vector A, M;\n      float dotAn;\n      bool condition = true;\n      do {\n         // Get the current element\n         A = Vector::Normalize(this->at(start) - p);\n\n         // Initial condition: the vertex needs to be above the horizon\n         dotAn = Vector::Dot(A, n);\n         condition = dotAn < 0.0;\n         ++start;\n\n      } while(condition && start<size);\n      --start;\n\n      // Return the empty polygon in case every vertex is below the horizon\n      if(start == size) { return P; }\n\n      for(unsigned int k=1; k<=size; ++k) {\n         const unsigned int next = (start + k) % size;\n         const Vector B = Vector::Normalize(this->at(next) - p);\n\n         const float dotBn = Vector::Dot(B, n);\n\n         // First case: the beginning of the Edge was below the hemisphere.\n         // Then we must create the intermediate point N and create an egde\n         // using M and N and another with N and B..\n         if(dotAn < 0 && dotBn >= 0) {\n            const float alpha = dotAn / (dotAn - dotBn);\n            const Vector N  = Vector::Normalize(A + alpha*(B-A));\n\n            if(Vector::Dot(M, N) < 1.0f) {\n               P.push_back(Edge(M, N));\n            }\n            if(alpha > 0 && Vector::Dot(N, B) < 1.0f) {\n               P.push_back(Edge(N, B));\n            }\n\n         } else if(dotAn >= 0 && dotBn < 0) {\n            const float alpha = dotAn / (dotAn - dotBn);\n            M = Vector::Normalize(A + alpha*(B-A));\n            if(alpha > 0) {\n               P.push_back(Edge(A, M));\n            }\n\n         // The next point is a valid one (above the horizon). Add the Edge\n         // (A,B)\n         } else if(dotAn >= 0 && dotBn >= 0) {\n            if(Vector::Dot(A, B) < 1.0f) {\n               P.push_back(Edge(A, B));\n            }\n         }\n\n         // Update the loop variables.\n         A = B;\n         dotAn = dotBn;\n      }\n      return P;\n   }\n};\n\nstd::mt19937 _test_gen(0);\nstd::uniform_real_distribution<float> _test_dist(0.0,1.0);\n\n/* 'Sample' generate a random direction on the unit sphere with uniform\n * distribution using _test_gen and _test_dist random number generators..\n */\nglm::vec3 Sample() {\n\n   glm::vec3 out;\n\n   // Sample the cosine of the elevation\n   const double z = _test_dist(_test_gen);\n   out.z = 2.0*z - 1.0;\n   const double z2 = out.z*out.z;\n\n   // Sample the azimuth\n   const double phi = 2.0*M_PI*_test_dist(_test_gen);\n   out.x = sqrt(1.0-z2) * cos(phi);\n   out.y = sqrt(1.0-z2) * sin(phi);\n   return out;\n}\n\n// Sample a spherical triangle using Arvo's stratified method.\n// Note: This code is not reliable right now. An error in the computation of the\n// solid angle bias the distribution of points. Use the uniform sampling method\n// instead.\nglm::vec3 SampleSphericalTriangle(const Triangle& triangle, float& pdf) {\n   const glm::vec3& A = triangle[0].A;\n   const glm::vec3& B = triangle[1].A;\n   const glm::vec3& C = triangle[2].A;\n\n   const glm::vec3 ab = glm::normalize(glm::cross(A, B));\n   const glm::vec3 ac = glm::normalize(glm::cross(A, C));\n   const glm::vec3 ba = glm::normalize(glm::cross(B, A));\n   const glm::vec3 bc = glm::normalize(glm::cross(B, C));\n   const glm::vec3 cb = glm::normalize(glm::cross(C, B));\n\n   const float alpha = acos(glm::dot(ba, ac));\n   const float beta  = acos(glm::dot(cb, ab));\n   const float gamma = acos(glm::dot(ac, bc));\n\n   const float area  = alpha + beta + gamma - M_PI;\n   pdf = 1.0f / area;\n\n   const float phi = _test_dist(_test_gen)*area - alpha;\n   const float t   = cos(phi);\n   const float s   = sin(phi);\n   const float u   = t - cos(alpha);\n   const float v   = s + sin(alpha)*glm::dot(A, B);\n\n   const float q = (v*t - u*s)*cos(alpha) - v / ((v*s + u*t)*sin(alpha));\n\n   glm::vec3 hC = q*A + float(sqrt(1.0f-q*q))*glm::normalize(C-glm::dot(C, A)*A);\n\n   // Select the cos(theta)\n   const float z = 1.0f - _test_dist(_test_gen)*(1.0f - glm::dot(hC, B));\n\n   return z*B + float(sqrt(1.0f-z*z))*glm::normalize(hC - glm::dot(hC, B)*B);\n}\n\nbool HitTriangle(const Triangle& triangle, const Vector& w) {\n\n   const float Epsilon = 1.0E-6;\n\n   auto& p1 = triangle[0].A;\n   auto& p2 = triangle[0].B;\n   auto& p3 = triangle[1].B;\n\n   //Find vectors for two edges sharing vertex/point p1\n   auto e1 = p2 - p1;\n   auto e2 = p3 - p1;\n\n   // calculating determinant\n   auto p   = Vector::Cross(w, e2);\n   auto det = Vector::Dot(e1, p);\n\n   //if determinant is near zero, ray lies in plane of triangle otherwise not\n   if (det > -Epsilon && det < Epsilon) { return false; }\n   auto invDet = 1.0f / det;\n\n   //calculate distance from p1 to ray origin\n   auto t = - p1;\n\n   //Calculate u parameter\n   auto u = Vector::Dot(t, p) * invDet;\n\n   //Check for ray hit\n   if (u < 0 || u > 1) { return false; }\n\n   //Prepare to test v parameter\n   auto q = glm::cross(t, e1);\n\n   //Calculate v parameter\n   auto v = Vector::Dot(w, q) * invDet;\n\n   //Check for ray hit\n   if (v < 0 || u + v > 1) { return false; }\n\n   if ((Vector::Dot(e2, q) * invDet) > Epsilon) {\n       //ray does intersect\n       return true;\n   }\n\n   // No hit at all\n   return false;\n}\n\n/* Spherical Harmonics wrapper for the code in 'SphericalHarmonics.hpp'\n */\nstruct SH {\n\n   // Inline for FastBasis\n   static inline Eigen::VectorXf FastBasis(const Vector& w, int lmax) {\n      const auto size = Terms(lmax);\n      Eigen::VectorXf res(size);\n      SHEvalFast<Vector>(w, lmax, res);\n      return res;\n   }\n   static inline void FastBasis(const Vector& w, int lmax, Eigen::VectorXf& clm) {\n      assert(clm.size() == Terms(lmax));\n      SHEvalFast<Vector>(w, lmax, clm);\n   }\n\n   // Inline for Terms\n   static inline int Terms(int band) {\n      return SHTerms(band);\n   }\n\n   // Inline for Index\n   static inline int Index(int l, int m) {\n      return SHIndex(l, m);\n   }\n};\n", "meta": {"hexsha": "d83e9e150c8baacac9c31132722251a7380630f5", "size": 10128, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/Tests.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "tests/Tests.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 28.055401662, "max_line_length": 82, "alphanum_fraction": 0.5782977883, "num_tokens": 2991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.06008665480259673, "lm_q1q2_score": 0.02980861868111743}}
{"text": "/**\n * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor <omarthoro@gmail.com>, 2017\n */\n\n#ifndef SP_ALGO_NN_OPTIMIZER_GRAD_DESC_HPP\n#define SP_ALGO_NN_OPTIMIZER_GRAD_DESC_HPP\n\n#include \"optimizer.hpp\"\n\n#include <boost/assert.hpp>\n\nSP_ALGO_NN_NAMESPACE_BEGIN\n\n/**\n * \\brief Implementation of gradient descent optimizer\n */\n\n/**\n * \\brief Gradient Descent Optimizer\n */\ntemplate<typename LearningRate = default_learning_rate>\nstruct gradient_descent_optimizer : optimizer<gradient_descent_optimizer<LearningRate>> {\n\n    constexpr static float_t alpha = static_cast<float_t>(LearningRate::num) / static_cast<float_t>(LearningRate::den);\n\n    static_assert(alpha > 0 && alpha < 1.0, \"Alpha is in the range of (0, 1]\");\n\n    constexpr static float_t epsilon = 1.0e-8f;\n\n    template<typename Tensor>\n    void update_impl(Tensor& dw, Tensor& w) {\n        BOOST_ASSERT(dw.size() == w.size());\n        BOOST_ASSERT(dw.dimensions() == w.dimensions());\n        w -= (alpha * dw);\n    }\n\n};\n\nSP_ALGO_NN_NAMESPACE_END\n\n#endif\t/* SP_ALGO_NN_OPTIMIZER_GRAD_DESC_HPP */\n\n", "meta": {"hexsha": "dc0a40879e800069e623027933d21d8a3e79e195", "size": 1211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/algo/nn/optimizer/grad_desc.hpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sp/algo/nn/optimizer/grad_desc.hpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sp/algo/nn/optimizer/grad_desc.hpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7659574468, "max_line_length": 119, "alphanum_fraction": 0.7266721718, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.07585818681131791, "lm_q1q2_score": 0.029761959477812083}}
{"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_MATRIX_IMPLICIT_DENSE_INCLUDE\n#define MTL_MATRIX_IMPLICIT_DENSE_INCLUDE\n\n#include <vector>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/matrix/crtp_base_matrix.hpp>\n#include <boost/numeric/mtl/matrix/mat_expr.hpp>\n#include <boost/numeric/mtl/concept/std_concept.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n\n#ifdef MTL_HAS_MPI\n#   include <boost/numeric/mtl/matrix/distributed.hpp>\n#   include <boost/numeric/mtl/matrix/inserter.hpp>\n#   include <boost/mpi/collectives.hpp>\n#endif\n\nnamespace mtl { namespace mat {\n\ntemplate <typename Functor>\nclass implicit_dense\n  : public const_crtp_base_matrix< implicit_dense<Functor>,\n\t\t\t\t   typename Functor::result_type, typename Functor::size_type >,\n    public mat_expr< implicit_dense<Functor> >\n{\n    typedef implicit_dense                             self;\n  public:\n    typedef mtl::tag::row_major                        orientation; // for completeness\n    typedef typename Functor::result_type              value_type;\n    typedef typename Functor::result_type              const_reference;\n    typedef typename Functor::size_type                size_type;\n\n    // Should not be needed, to be removed after transposed_view is cleaned up\n    typedef index::c_index                             index_type;\n    typedef mtl::traits::detail::matrix_element_key<self> key_type;\n    typedef mtl::non_fixed::dimensions                 dim_type;\n\n    explicit implicit_dense (const Functor& functor) : my_functor(functor) {}\n\n    value_type operator() (size_type r, size_type c) const { return my_functor(r, c); }\n\n    size_type nnz() const { return dim1() * dim2(); }\n    size_type dim1() const { return num_rows(my_functor); }\n    size_type dim2() const { return num_cols(my_functor); }\n\n    friend size_type inline num_rows(const self& A) { return num_rows(A.my_functor); }\n    friend size_type inline num_cols(const self& A) { return num_cols(A.my_functor); }\n\n    Functor& functor() { return my_functor; }\n    Functor const& functor() const { return my_functor; }\n\n  private:\n    Functor           my_functor;    \n};\n\ntemplate <typename Functor>\ntypename Functor::size_type inline size(const implicit_dense<Functor>& A) \n{ \n    return num_rows(A) * num_cols(A);\n}\n\n// ==========\n// Sub matrix\n// ==========\n\n// To do later\n\n}} // namespace mtl::matrix\n\n\nnamespace mtl { namespace traits {\n\n    // ================\n    // Range generators\n    // For cursors\n    // ================\n\n    template <typename Functor>\n    struct range_generator<glas::tag::row, mtl::mat::implicit_dense<Functor> >\n      : detail::all_rows_range_generator<mtl::mat::implicit_dense<Functor>, complexity_classes::linear>\n    {};\n\n    template <typename Functor>\n    struct range_generator<glas::tag::major, mtl::mat::implicit_dense<Functor> >\n      : range_generator<glas::tag::row, mtl::mat::implicit_dense<Functor> >\n    {};\n\n    template <typename Functor>\n    struct range_generator<glas::tag::nz,\n\t\t\t   detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::row, 2> > \n      : detail::all_cols_in_row_range_generator<detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::row, 2> >\n    {};\n\n    template <typename Functor>\n    struct range_generator<glas::tag::col, mtl::mat::implicit_dense<Functor> >\n      : detail::all_cols_range_generator<mtl::mat::implicit_dense<Functor>, complexity_classes::linear>\n    {};\n\n    template <typename Functor>\n    struct range_generator<glas::tag::nz,\n\t\t\t   detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::col, 2> > \n      : detail::all_rows_in_col_range_generator<detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::col, 2> >\n    {};\n\n\n    template <typename Tag, typename Value>\n    struct range_generator<Tag, mtl::mat::ones_matrix<Value> >\n      : public range_generator<Tag, mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > > \n    {};\n\n    template <typename Value>\n    struct range_generator<glas::tag::major, mtl::mat::ones_matrix<Value> >\n      : public range_generator<glas::tag::major, mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > > \n    {};\n\n    template <typename Tag, typename Value>\n    struct range_generator<Tag, mtl::mat::hilbert_matrix<Value> >\n      : public range_generator<Tag, mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > > \n    {};\n\n    template <typename Value>\n    struct range_generator<glas::tag::major, mtl::mat::hilbert_matrix<Value> >\n      : public range_generator<glas::tag::major, mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > > \n    {};\n\n    template <typename Tag, typename Vector1, typename Vector2>\n    struct range_generator<Tag, mtl::mat::outer_product_matrix<Vector1, Vector2> >\n      : public range_generator<Tag, mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > > \n    {};\n\n    template <typename Vector1, typename Vector2>\n    struct range_generator<glas::tag::major, mtl::mat::outer_product_matrix<Vector1, Vector2> >\n      : public range_generator<glas::tag::major, mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > > \n    {};\n\n}} // mtl::traits\n\n// =============\n// Some functors\n// =============\n\n\nnamespace mtl { namespace mat {\n\ntemplate <typename Value= int>\nclass ones_functor\n{\n    typedef ones_functor    self;\n  public:\n    typedef std::size_t    size_type;\n    typedef Value          result_type;\n\n    ones_functor(size_type nr, size_type nc) : nr(nr), nc(nc) {}\n\n    friend size_type inline num_rows(const self& A) { return A.nr; }\n    friend size_type inline num_cols(const self& A) { return A.nc; }\n\n    result_type operator()(size_type, size_type) const { return Value(1); }\n\n  private:\n    size_type nr, nc;\n};\n\n    \ntemplate <typename Value= double>\nclass hilbert_functor\n{\n    typedef hilbert_functor    self;\n  public:\n    typedef std::size_t    size_type;\n    typedef Value          result_type;\n\n    hilbert_functor(size_type nr, size_type nc) : nr(nr), nc(nc) {}\n\n    friend size_type inline num_rows(const self& A) { return A.nr; }\n    friend size_type inline num_cols(const self& A) { return A.nc; }\n\n    result_type operator()(size_type r, size_type c) const \n    { \n\tusing math::reciprocal;  \n\treturn reciprocal(Value(r + c + 1)); \n    }\n  private:\n    size_type nr, nc;\n};\n\n    \ntemplate <typename Vector1, typename Vector2>\nclass outer_product_functor\n{\n    typedef outer_product_functor    self;\n  public:\n    typedef std::size_t              size_type;\n    typedef typename Multiplicable<typename Collection<Vector1>::value_type,\n\t\t\t\t   typename Collection<Vector2>::value_type>::result_type   result_type;\n\n    outer_product_functor(const Vector1& v1, const Vector2& v2) : my_v1(v1), my_v2(v2) {}\n    outer_product_functor(size_type r, size_type c) : my_v1(r), my_v2(c) {}\n\n    friend size_type inline num_rows(const self& A) { return mtl::size(A.my_v1); }\n    friend size_type inline num_cols(const self& A) { return mtl::size(A.my_v2); }\n\n    result_type operator()(size_type r, size_type c) const { return my_v1[r] * my_v2[c]; }\n\n    Vector1&       v1()       { return my_v1; }\n    Vector1 const& v1() const { return my_v1; }\n    Vector2&       v2()       { return my_v2; }\n    Vector2 const& v2() const { return my_v2; }\n\n  private:\n    Vector1  my_v1; // keeps copy\n    Vector2  my_v2;\n};\n\n// ======================\n// Some implicit matrices\n// ======================\n\n\ntemplate <typename Value= int>\nclass ones_matrix\n  : public implicit_dense<ones_functor<Value> >\n{\n  public:\n    typedef ones_functor<Value>                functor_type;\n    typedef typename functor_type::size_type  size_type;\n    typedef implicit_dense<functor_type>      base;\n\n    ones_matrix(size_type r, size_type c) : base(functor_type(r, c)) {}\n};\n\n\ntemplate <typename Value= double>\nclass hilbert_matrix\n  : public implicit_dense<hilbert_functor<Value> >\n{\n  public:\n    typedef hilbert_functor<Value>            functor_type;\n    typedef typename functor_type::size_type  size_type;\n    typedef implicit_dense<functor_type>      base;\n\n    hilbert_matrix(size_type r, size_type c) : base(functor_type(r, c)) {}\n};\n\n\ntemplate <typename Vector1, typename Vector2>\nclass outer_product_matrix\n  : public implicit_dense<outer_product_functor<Vector1, Vector2> >\n{\n    typedef outer_product_matrix self;\n  public:\n    typedef outer_product_functor<Vector1, Vector2>  functor_type;\n    typedef typename functor_type::size_type  size_type;\n    typedef implicit_dense<functor_type>      base;\n\n    outer_product_matrix(const Vector1& v1, const Vector2& v2) : base(functor_type(v1, v2)) {}\n    outer_product_matrix(size_type r, size_type c) : base(functor_type(r, c)) {}\n\n    Vector1&       v1()       { return this->functor().v1(); }\n    Vector1 const& v1() const { return this->functor().v1(); }\n    Vector2&       v2()       { return this->functor().v2(); }\n    Vector2 const& v2() const { return this->functor().v2(); }\n};\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_IMPLICIT_DENSE_INCLUDE\n", "meta": {"hexsha": "132dabf97fb344f54051283a91ac7c957ab85532", "size": 9541, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/matrix/implicit_dense.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/implicit_dense.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/implicit_dense.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": 34.075, "max_line_length": 129, "alphanum_fraction": 0.6793837124, "num_tokens": 2450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.07159120439664804, "lm_q1q2_score": 0.029703107037481476}}
{"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_PROBLEMS_THERMALBLOCK_HH\n#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH\n\n#include <memory>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/static_assert.hh>\n#include <dune/common/timer.hh>\n\n#include <dune/grid/multiscale/provider/cube.hh>\n\n#include <dune/stuff/common/memory.hh>\n#include <dune/stuff/functions/constant.hh>\n#include <dune/stuff/functions/expression.hh>\n#include <dune/stuff/playground/functions/indicator.hh>\n#include <dune/stuff/grid/provider/cube.hh>\n#include <dune/stuff/grid/boundaryinfo.hh>\n\n#include <dune/pymor/functions/default.hh>\n#include <dune/pymor/functions/checkerboard.hh>\n\n#include \"default.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Problems {\n\n\ntemplate< class E, class D, int d, class R, int r = 1 >\nclass Thermalblock\n  : public ProblemInterface< E, D, d, R, r >\n{\n  Thermalblock() { static_assert(AlwaysFalse< E >::value, \"Not available for these dimensions!\"); }\n};\n\n\ntemplate< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n  : public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\n  typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n  typedef Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n\npublic:\n  typedef Pymor::Functions::Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n      CheckerboardFunctionType;\n  using typename BaseType::DiffusionTensorType;\n  using typename BaseType::FunctionType;\n\n  static const bool available = true;\n\n  static std::string static_id()\n  {\n    return BaseType::BaseType::static_id() + \".thermalblock\";\n  }\n\n  static Stuff::Common::Configuration default_config(const std::string sub_name = \"\")\n  {\n    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n        ConstantFunctionType;\n    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >\n        ConstantMatrixFunctionType;\n    Stuff::Common::Configuration config;\n    Stuff::Common::Configuration checkerboard_config = CheckerboardFunctionType::default_config();\n    checkerboard_config[\"name\"] = \"diffusion_factor\";\n    checkerboard_config[\"type\"] = CheckerboardFunctionType::static_id();\n    checkerboard_config[\"num_elements\"] = \"[4 4 4]\";\n    checkerboard_config[\"parameter_name\"] = \"diffusion_factor\";\n    config.add(checkerboard_config, \"diffusion_factor\");\n    Stuff::Common::Configuration diffusion_tensor_config = ConstantMatrixFunctionType::default_config();\n    diffusion_tensor_config[\"name\"] = \"diffusion_tensor\";\n    diffusion_tensor_config[\"type\"] = ConstantMatrixFunctionType::static_id();\n    config.add(diffusion_tensor_config, \"diffusion_tensor\");\n    Stuff::Common::Configuration constant_config = ConstantFunctionType::default_config();\n    constant_config[\"type\"] = ConstantFunctionType::static_id();\n    constant_config[\"name\"] = \"force\";\n    constant_config[\"value\"] = \"1\";\n    config.add(constant_config, \"force\");\n    constant_config[\"name\"] = \"dirichlet\";\n    constant_config[\"value\"] = \"0\";\n    config.add(constant_config, \"dirichlet\");\n    constant_config[\"name\"] = \"neumann\";\n    config.add(constant_config, \"neumann\");\n    if (sub_name.empty())\n      return config;\n    else {\n      Stuff::Common::Configuration tmp;\n      tmp.add(config, sub_name);\n      return tmp;\n    }\n  } // ... default_config(...)\n\n  static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),\n                                            const std::string sub_name = static_id())\n  {\n    const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n    std::shared_ptr< CheckerboardFunctionType >\n        checkerboard_function(CheckerboardFunctionType::create(cfg.sub(\"diffusion_factor\")));\n    return Stuff::Common::make_unique< ThisType >(checkerboard_function,\n                                                  BaseType::create_matrix_function(\"diffusion_tensor\", cfg),\n                                                  BaseType::create_vector_function(\"force\", cfg),\n                                                  BaseType::create_vector_function(\"dirichlet\", cfg),\n                                                  BaseType::create_vector_function(\"neumann\", cfg));\n  } // ... create(...)\n\n  Thermalblock(const std::shared_ptr< const CheckerboardFunctionType >& checkerboard_function,\n               const std::shared_ptr< const DiffusionTensorType >& diffusion_tensor,\n               const std::shared_ptr< const FunctionType >& force,\n               const std::shared_ptr< const FunctionType >& dirichlet,\n               const std::shared_ptr< const FunctionType >& neumann)\n    : BaseType(checkerboard_function, diffusion_tensor, force, dirichlet, neumann)\n  {}\n\n  virtual std::string type() const override\n  {\n    return BaseType::BaseType::static_id() + \".thermalblock\";\n  }\n}; // class Thermalblock< ..., 1 >\n\n\ntemplate< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim = 1 >\nclass LocalThermalblock\n{\n  static_assert(AlwaysFalse< EntityImp >::value, \"Not available for dimRange > 1!\");\n};\n\n\ntemplate< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass LocalThermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n  : public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\n  typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n  typedef LocalThermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n\n  typedef Pymor::Functions::AffinelyDecomposableDefault< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n      AffinelyDecomposableDefaultFunctionType;\n  typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >\n      ConstantMatrixFunctionType;\npublic:\n  using typename BaseType::FunctionType;\n\n  static std::string static_id()\n  {\n    return BaseType::BaseType::static_id() + \".localthermalblock\";\n  }\n\n  static Stuff::Common::Configuration default_config(const std::string sub_name = \"\")\n  {\n    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n        ConstantFunctionType;\n    Stuff::Common::Configuration config;\n    Stuff::Common::Configuration constant_config = ConstantFunctionType::default_config();\n    constant_config[\"type\"] = ConstantFunctionType::static_id();\n    constant_config[\"name\"] = \"force\";\n    constant_config[\"value\"] = \"1\";\n    config.add(constant_config, \"force\");\n    constant_config[\"name\"] = \"dirichlet\";\n    constant_config[\"value\"] = \"0\";\n    config.add(constant_config, \"dirichlet\");\n    constant_config[\"name\"] = \"neumann\";\n    config.add(constant_config, \"neumann\");\n    if (sub_name.empty())\n      return config;\n    else {\n      Stuff::Common::Configuration tmp;\n      tmp.add(config, sub_name);\n      return tmp;\n    }\n  } // ... default_config(...)\n\n  static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),\n                                            const std::string sub_name = static_id())\n  {\n    const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n    return Stuff::Common::make_unique< ThisType >(BaseType::create_vector_function(\"force\", cfg),\n                                                  BaseType::create_vector_function(\"dirichlet\", cfg),\n                                                  BaseType::create_vector_function(\"neumann\", cfg));\n  } // ... create(...)\n\n  LocalThermalblock(const std::shared_ptr< const FunctionType >& force,\n                    const std::shared_ptr< const FunctionType >& dirichlet,\n                    const std::shared_ptr< const FunctionType >& neumann)\n    : BaseType(create_diffusion_factor(),\n               create_diffusion_tensor(),\n               force,\n               dirichlet,\n               neumann)\n  {}\n\n  virtual std::string type() const override\n  {\n    return BaseType::BaseType::static_id() + \".localthermalblock\";\n  }\n\nprivate:\n  static std::shared_ptr< AffinelyDecomposableDefaultFunctionType > create_diffusion_factor()\n  {\n    typedef Stuff::Functions::Indicator< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > IndicatorFunctionType;\n    const Pymor::ParameterType mu(\"diffusion_factor\", 3);\n\n    auto ret = std::make_shared< AffinelyDecomposableDefaultFunctionType >(\"diffusion_factor\");\n    ret->register_component(new IndicatorFunctionType({{{{0.0, 0.0}, {0.5, 0.16}}, 1.0},\n                                                       {{{0.0, 0.16}, {0.16, 0.33}}, 1.0},\n                                                       {{{0.33, 0.16}, {0.5, 0.33}}, 1.0},\n                                                       {{{0.0, 0.33}, {0.5, 1.0}}, 1.0}},\n                                                      \"left_block\"),\n                            new Pymor::ParameterFunctional(mu, \"diffusion_factor[0]\"));\n    ret->register_component(new IndicatorFunctionType({{{{0.5, 0.0}, {1.0, 1.0}}, 1.0}},\n                                                      \"right_block\"),\n                            new Pymor::ParameterFunctional(mu, \"diffusion_factor[1]\"));\n    ret->register_component(new IndicatorFunctionType({{{{0.16, 0.16}, {0.33, 0.33}}, 1.0}},\n                                                      \"small_block\"),\n                            new Pymor::ParameterFunctional(mu, \"diffusion_factor[2]\"));\n    return ret;\n  } // ... create_diffusion_factor()\n\n  typedef Pymor::Functions::NonparametricDefault\n      < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim > NonparametricFunctionType;\n\n  static std::shared_ptr< NonparametricFunctionType > create_diffusion_tensor()\n  {\n    Stuff::Common::Configuration diffusion_tensor_config = ConstantMatrixFunctionType::default_config();\n    diffusion_tensor_config[\"name\"] = \"diffusion_tensor\";\n    return std::make_shared< NonparametricFunctionType >(ConstantMatrixFunctionType::create(diffusion_tensor_config));\n  } // ... create_diffusion_tensor()\n}; // class LocalThermalblock< ..., 1 >\n\n\n} // namespace Problems\nnamespace DiscreteProblems {\n\n\ntemplate< class GridImp >\nclass Thermalblock\n{\npublic:\n  typedef GridImp GridType;\n  typedef Stuff::Grid::Providers::Cube< GridType > GridProviderType;\nprivate:\n  typedef Stuff::Grid::BoundaryInfos::AllDirichlet< typename GridType::LeafIntersection > BoundaryInfoType;\n  typedef typename GridType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridType::ctype DomainFieldType;\n  static const unsigned int dimDomain = GridType::dimension;\npublic:\n  typedef double RangeFieldType;\n  static const unsigned int dimRange = 1;\n  typedef Problems::Thermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;\n\n  static void write_config(const std::string filename, const std::string id)\n  {\n    std::ofstream file;\n    file.open(filename);\n    file << \"[\" << id << \"]\" << std::endl;\n    file << \"filename = \" << id << std::endl;\n    file << \"[logging]\" << std::endl;\n    file << \"info  = true\" << std::endl;\n    file << \"debug = true\" << std::endl;\n    file << \"file  = false\" << std::endl;\n    file << \"[parameter]\" << std::endl;\n    file << \"0.diffusion_factor = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]\" << std::endl;\n    file << GridProviderType::default_config(GridProviderType::static_id());\n    file << ProblemType::default_config(ProblemType::static_id());\n    file << \"[pymor]\" << std::endl;\n    file << \"training_set = random\" << std::endl;\n    file << \"num_training_samples = 100\" << std::endl;\n    file << \"reductor = generic\" << std::endl;\n    file << \"extension_algorithm = gram_schmidt\" << std::endl;\n    file << \"extension_algorithm_product = h1_semi\" << std::endl;\n    file << \"greedy_error_norm = h1_semi\" << std::endl;\n    file << \"use_estimator = False\" << std::endl;\n    file << \"max_rb_size = 100\" << std::endl;\n    file << \"target_error = 0.01\" << std::endl;\n    file << \"final_compression = False\" << std::endl;\n    file << \"compression_product = None\" << std::endl;\n    file << \"test_set = training\" << std::endl;\n    file << \"num_test_samples = 100\" << std::endl;\n    file << \"test_error_norm = h1_semi\" << std::endl;\n    file.close();\n  } // ... write_config(...)\n\n  Thermalblock(const std::string id, const std::vector< std::string >& arguments, const bool visualize = true)\n  {\n    // mpi\n    int argc = boost::numeric_cast< int >(arguments.size());\n    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);\n#if HAVE_DUNE_FEM\n    Fem::MPIManager::initialize(argc, argv);\n#else\n    MPIHelper::instance(argc, argv);\n#endif\n\n    // configuration\n    config_ = Stuff::Common::Configuration(argc, argv, id + \".cfg\");\n    if (!config_.has_sub(id))\n      DUNE_THROW(Stuff::Exceptions::configuration_error,\n                 \"Missing sub '\" << id << \"' in the following Configuration:\\n\\n\" << config_);\n    filename_ = config_.get(id + \".filename\", id);\n\n    // logger\n    const Stuff::Common::Configuration& logger_config = config_.sub(\"logging\");\n    int log_flags = Stuff::Common::LOG_CONSOLE;\n    debug_logging_ = logger_config.get< bool >(\"debug\", false);\n    if (logger_config.get< bool >(\"info\"))\n      log_flags = log_flags | Stuff::Common::LOG_INFO;\n    if (debug_logging_)\n      log_flags = log_flags | Stuff::Common::LOG_DEBUG;\n    if (logger_config.get< bool >(\"file\", false))\n      log_flags = log_flags | Stuff::Common::LOG_FILE;\n    Stuff::Common::Logger().create(log_flags, id, \"\", \"\");\n    auto& info  = Stuff::Common::Logger().info();\n\n    Timer timer;\n    info << \"creating grid with '\" << GridProviderType::static_id() << \"'... \" << std::flush;\n    grid_provider_ = GridProviderType::create(config_);\n    const auto grid_view = grid_provider_->leaf_view();\n    info << \" done (took \" << timer.elapsed()\n         << \"s, has \" << grid_view->indexSet().size(0) << \" element\";\n    if (grid_view->indexSet().size(0) > 1)\n      info << \"s\";\n    info << \")\" << std::endl;\n\n    boundary_info_ = Stuff::Common::Configuration(\"type\", BoundaryInfoType::static_id());\n\n    info << \"setting up \";\n    info << \"'\" << ProblemType::static_id() << \"'... \" << std::flush;\n    timer.reset();\n    problem_ = ProblemType::create(config_);\n    info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n\n    if (visualize) {\n      info << \"visualizing grid and problem... \" << std::flush;\n      timer.reset();\n      grid_provider_->visualize(boundary_info_, filename_ + \".grid\");\n      problem_->visualize(*grid_view, filename_ + \".problem\");\n      info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n    } // if (visualize)\n  } // Thermalblock\n\n  std::string filename() const\n  {\n    return filename_;\n  }\n\n  const Stuff::Common::Configuration& config() const\n  {\n    return config_;\n  }\n\n  bool debug_logging() const\n  {\n    return debug_logging_;\n  }\n\n  GridProviderType& grid_provider()\n  {\n    return *grid_provider_;\n  }\n\n  const GridProviderType& grid_provider() const\n  {\n    return *grid_provider_;\n  }\n\n  const Stuff::Common::Configuration& boundary_info() const\n  {\n    return boundary_info_;\n  }\n\n  const ProblemType& problem() const\n  {\n    return *problem_;\n  }\n\nprivate:\n  std::string filename_;\n  Stuff::Common::Configuration config_;\n  bool debug_logging_;\n  std::unique_ptr< GridProviderType > grid_provider_;\n  Stuff::Common::Configuration boundary_info_;\n  std::unique_ptr< const ProblemType > problem_;\n}; // class Thermalblock\n\n\ntemplate< class GridImp >\nclass ThermalblockMultiScale\n{\npublic:\n  typedef GridImp GridType;\n  typedef grid::Multiscale::Providers::Cube< GridType > GridProviderType;\nprivate:\n  typedef typename GridType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridType::ctype DomainFieldType;\n  static const unsigned int dimDomain = GridType::dimension;\npublic:\n  typedef double RangeFieldType;\n  static const unsigned int dimRange = 1;\n  typedef Problems::Thermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;\n\n  static void write_config(const std::string filename, const std::string id)\n  {\n    std::ofstream file;\n    file.open(filename);\n    file << \"[\" << id << \"]\" << std::endl;\n    file << \"filename = \" << id << std::endl;\n    file << \"[logging]\" << std::endl;\n    file << \"info  = true\" << std::endl;\n    file << \"debug = false\" << std::endl;\n    file << \"file  = false\" << std::endl;\n    file << \"visualize = false\" << std::endl;\n    file << \"[parameter]\" << std::endl;\n    file << \"0.diffusion_factor = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]\" << std::endl;\n    file << GridProviderType::default_config(GridProviderType::static_id());\n    file << ProblemType::default_config(ProblemType::static_id());\n    file << \"[pymor]\" << std::endl;\n    file << \"training_set = random\" << std::endl;\n    file << \"num_training_samples = 100\" << std::endl;\n    file << \"reductor = generic\" << std::endl;\n    file << \"extension_algorithm = pod\" << std::endl;\n    file << \"extension_algorithm_product = h1_semi\" << std::endl;\n    file << \"greedy_error_norm = h1_semi\" << std::endl;\n    file << \"use_estimator = False\" << std::endl;\n    file << \"max_rb_size = 100\" << std::endl;\n    file << \"target_error = 0.01\" << std::endl;\n    file << \"final_compression = False\" << std::endl;\n    file << \"compression_product = None\" << std::endl;\n    file << \"test_set = training\" << std::endl;\n    file << \"num_test_samples = 100\" << std::endl;\n    file << \"test_error_norm = h1_semi\" << std::endl;\n    file.close();\n  } // ... write_config(...)\n\n  ThermalblockMultiScale(const std::string id, const std::vector< std::string >& arguments, const bool visualize = true)\n  {\n    // mpi\n    int argc = boost::numeric_cast< int >(arguments.size());\n    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);\n#if HAVE_DUNE_FEM\n    Fem::MPIManager::initialize(argc, argv);\n#else\n    MPIHelper::instance(argc, argv);\n#endif\n\n    // configuration\n    config_ = Stuff::Common::Configuration(argc, argv, id + \".cfg\");\n    if (!config_.has_sub(id))\n      DUNE_THROW(Stuff::Exceptions::configuration_error,\n                 \"Missing sub '\" << id << \"' in the following Configuration:\\n\\n\" << config_);\n    filename_ = config_.get(id + \".filename\", id);\n\n    // logger\n    const Stuff::Common::Configuration& logger_config = config_.sub(\"logging\");\n    int log_flags = Stuff::Common::LOG_CONSOLE;\n    debug_logging_ = logger_config.get< bool >(\"debug\", false);\n    if (logger_config.get< bool >(\"info\"))\n      log_flags = log_flags | Stuff::Common::LOG_INFO;\n    if (debug_logging_)\n      log_flags = log_flags | Stuff::Common::LOG_DEBUG;\n    if (logger_config.get< bool >(\"file\", false))\n      log_flags = log_flags | Stuff::Common::LOG_FILE;\n    Stuff::Common::Logger().create(log_flags, id, \"\", \"\");\n    auto& info  = Stuff::Common::Logger().info();\n\n    Timer timer;\n    info << \"creating grid with '\" << GridProviderType::static_id() << \"'... \" << std::flush;\n    grid_provider_ = GridProviderType::create(config_);\n    const auto grid_view = grid_provider_->leaf_view();\n    info << \" done (took \" << timer.elapsed()\n         << \"s, has \" << grid_view.indexSet().size(0) << \" element\";\n    if (grid_view.indexSet().size(0) > 1)\n      info << \"s\";\n    info << \")\" << std::endl;\n\n    boundary_info_ = Stuff::Grid::BoundaryInfoConfigs::NormalBased::default_config();\n    boundary_info_[\"dirichlet.0\"] = \"[0.0 -1.0]\";\n    boundary_info_[\"dirichlet.1\"] = \"[0.0 1.0]\";\n    boundary_info_[\"neumann.0\"] = \"[1.0 0.0]\";\n    boundary_info_[\"neumann.1\"] = \"[-1.0 0.0]\";\n\n    info << \"setting up \";\n    info << \"'\" << ProblemType::static_id() << \"'... \" << std::flush;\n    timer.reset();\n    problem_ = ProblemType::create(config_);\n    info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n\n    if (visualize && logger_config.get(\"visualize\", false)) {\n      info << \"visualizing grid and problem... \" << std::flush;\n      timer.reset();\n      grid_provider_->visualize(boundary_info_, filename_ + \".grid\");\n      grid_provider_->visualize(filename_ + \".msgrid\");\n      problem_->visualize(grid_view, filename_ + \".problem\");\n      info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n    } // if (visualize)\n  } // Thermalblock\n\n  std::string filename() const\n  {\n    return filename_;\n  }\n\n  const Stuff::Common::Configuration& config() const\n  {\n    return config_;\n  }\n\n  bool debug_logging() const\n  {\n    return debug_logging_;\n  }\n\n  GridProviderType& grid_provider()\n  {\n    return *grid_provider_;\n  }\n\n  const GridProviderType& grid_provider() const\n  {\n    return *grid_provider_;\n  }\n\n  const Stuff::Common::Configuration& boundary_info() const\n  {\n    return boundary_info_;\n  }\n\n  const ProblemType& problem() const\n  {\n    return *problem_;\n  }\n\nprivate:\n  std::string filename_;\n  Stuff::Common::Configuration config_;\n  bool debug_logging_;\n  std::unique_ptr< GridProviderType > grid_provider_;\n  Stuff::Common::Configuration boundary_info_;\n  std::unique_ptr< const ProblemType > problem_;\n}; // class ThermalblockMultiScale\n\n\ntemplate< class GridImp >\nclass LocalThermalblockMultiScale\n{\npublic:\n  typedef GridImp GridType;\n  typedef grid::Multiscale::Providers::Cube< GridType > GridProviderType;\nprivate:\n  typedef typename GridType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridType::ctype DomainFieldType;\n  static const unsigned int dimDomain = GridType::dimension;\npublic:\n  typedef double RangeFieldType;\n  static const unsigned int dimRange = 1;\n  typedef Problems::LocalThermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;\n\n  static void write_config(const std::string filename, const std::string id)\n  {\n    std::ofstream file;\n    file.open(filename);\n    file << \"[\" << id << \"]\" << std::endl;\n    file << \"filename = \" << id << std::endl;\n    file << \"[logging]\" << std::endl;\n    file << \"info  = true\" << std::endl;\n    file << \"debug = false\" << std::endl;\n    file << \"file  = false\" << std::endl;\n    file << \"visualize = false\" << std::endl;\n    file << \"[parameter]\" << std::endl;\n    file << \"0.diffusion_factor = [1 2 3]\" << std::endl;\n    file << GridProviderType::default_config(GridProviderType::static_id());\n    file << ProblemType::default_config(ProblemType::static_id());\n    file << \"[pymor]\" << std::endl;\n    file << \"training_set = random\" << std::endl;\n    file << \"num_training_samples = 100\" << std::endl;\n    file << \"reductor = generic\" << std::endl;\n    file << \"extension_algorithm = pod\" << std::endl;\n    file << \"extension_algorithm_product = h1_semi\" << std::endl;\n    file << \"greedy_error_norm = h1_semi\" << std::endl;\n    file << \"use_estimator = False\" << std::endl;\n    file << \"max_rb_size = 100\" << std::endl;\n    file << \"target_error = 5e-3\" << std::endl;\n    file << \"final_compression = False\" << std::endl;\n    file << \"compression_product = None\" << std::endl;\n    file << \"test_set = training\" << std::endl;\n    file << \"num_test_samples = 100\" << std::endl;\n    file << \"test_error_norm = h1_semi\" << std::endl;\n    file.close();\n  } // ... write_config(...)\n\n  LocalThermalblockMultiScale(const std::string id,\n                              const std::vector< std::string >& arguments,\n                              const bool visualize = true)\n  {\n    // mpi\n    int argc = boost::numeric_cast< int >(arguments.size());\n    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);\n#if HAVE_DUNE_FEM\n    Fem::MPIManager::initialize(argc, argv);\n#else\n    MPIHelper::instance(argc, argv);\n#endif\n\n    // configuration\n    config_ = Stuff::Common::Configuration(argc, argv, id + \".cfg\");\n    if (!config_.has_sub(id))\n      DUNE_THROW(Stuff::Exceptions::configuration_error,\n                 \"Missing sub '\" << id << \"' in the following Configuration:\\n\\n\" << config_);\n    filename_ = config_.get(id + \".filename\", id);\n\n    // logger\n    const Stuff::Common::Configuration& logger_config = config_.sub(\"logging\");\n    int log_flags = Stuff::Common::LOG_CONSOLE;\n    debug_logging_ = logger_config.get< bool >(\"debug\", false);\n    if (logger_config.get< bool >(\"info\"))\n      log_flags = log_flags | Stuff::Common::LOG_INFO;\n    if (debug_logging_)\n      log_flags = log_flags | Stuff::Common::LOG_DEBUG;\n    if (logger_config.get< bool >(\"file\", false))\n      log_flags = log_flags | Stuff::Common::LOG_FILE;\n    Stuff::Common::Logger().create(log_flags, id, \"\", \"\");\n    auto& info  = Stuff::Common::Logger().info();\n\n    Timer timer;\n    info << \"creating grid with '\" << GridProviderType::static_id() << \"'... \" << std::flush;\n    grid_provider_ = GridProviderType::create(config_);\n    const auto grid_view = grid_provider_->leaf_view();\n    info << \" done (took \" << timer.elapsed()\n         << \"s, has \" << grid_view->indexSet().size(0) << \" element\";\n    if (grid_view->indexSet().size(0) > 1)\n      info << \"s\";\n    info << \")\" << std::endl;\n\n    boundary_info_ = Stuff::Grid::BoundaryInfoConfigs::NormalBased::default_config();\n    boundary_info_[\"dirichlet.0\"] = \"[0.0 -1.0]\";\n    boundary_info_[\"dirichlet.1\"] = \"[0.0 1.0]\";\n    boundary_info_[\"neumann.0\"] = \"[1.0 0.0]\";\n    boundary_info_[\"neumann.1\"] = \"[-1.0 0.0]\";\n\n    info << \"setting up \";\n    info << \"'\" << ProblemType::static_id() << \"'... \" << std::flush;\n    timer.reset();\n    problem_ = ProblemType::create(config_);\n    info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n\n    if (visualize && logger_config.get(\"visualize\", false)) {\n      info << \"visualizing grid and problem... \" << std::flush;\n      timer.reset();\n      grid_provider_->visualize(boundary_info_, filename_ + \".grid\");\n      grid_provider_->visualize(filename_ + \".msgrid\");\n      problem_->visualize(*grid_view, filename_ + \".problem\");\n      info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n    } // if (visualize)\n  } // Thermalblock\n\n  std::string filename() const\n  {\n    return filename_;\n  }\n\n  const Stuff::Common::Configuration& config() const\n  {\n    return config_;\n  }\n\n  bool debug_logging() const\n  {\n    return debug_logging_;\n  }\n\n  GridProviderType& grid_provider()\n  {\n    return *grid_provider_;\n  }\n\n  const GridProviderType& grid_provider() const\n  {\n    return *grid_provider_;\n  }\n\n  const Stuff::Common::Configuration& boundary_info() const\n  {\n    return boundary_info_;\n  }\n\n  const ProblemType& problem() const\n  {\n    return *problem_;\n  }\n\nprivate:\n  std::string filename_;\n  Stuff::Common::Configuration config_;\n  bool debug_logging_;\n  std::unique_ptr< GridProviderType > grid_provider_;\n  Stuff::Common::Configuration boundary_info_;\n  std::unique_ptr< const ProblemType > problem_;\n}; // class LocalThermalblockMultiScale\n\n\n} // namespace DiscreteProblems\n} // namespace LinearElliptic\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH\n", "meta": {"hexsha": "647257024b9cd7c2e2687b52821d5fccb7d68b27", "size": 27356, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/problems/thermalblock.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/problems/thermalblock.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/problems/thermalblock.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": 38.4753867792, "max_line_length": 120, "alphanum_fraction": 0.6510820295, "num_tokens": 6888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367316191467, "lm_q2_score": 0.0646534861034137, "lm_q1q2_score": 0.029555483325098462}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\r\n//\r\n// Copyright (C) 2016 Michael Rabinovich\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla Public License\r\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\r\n// obtain one at http://mozilla.org/MPL/2.0/.\r\n#include \"slim.h\"\r\n\r\n#include \"boundary_loop.h\"\r\n#include \"cotmatrix.h\"\r\n#include \"edge_lengths.h\"\r\n#include \"grad.h\"\r\n#include \"local_basis.h\"\r\n#include \"repdiag.h\"\r\n#include \"vector_area_matrix.h\"\r\n#include \"arap.h\"\r\n#include \"cat.h\"\r\n#include \"doublearea.h\"\r\n#include \"grad.h\"\r\n#include \"local_basis.h\"\r\n#include \"per_face_normals.h\"\r\n#include \"slice_into.h\"\r\n#include \"volume.h\"\r\n#include \"polar_svd.h\"\r\n#include \"flip_avoiding_line_search.h\"\r\n#include \"mapping_energy_with_jacobians.h\"\r\n\r\n#include <iostream>\r\n#include <map>\r\n#include <set>\r\n#include <vector>\r\n\r\n#include <Eigen/IterativeLinearSolvers>\r\n#include <Eigen/SparseCholesky>\r\n#include <Eigen/IterativeLinearSolvers>\r\n\r\n#include \"Timer.h\"\r\n#include \"sparse_cached.h\"\r\n#include \"AtA_cached.h\"\r\n\r\n#ifdef CHOLMOD\r\n#include <Eigen/CholmodSupport>\r\n#endif\r\n\r\nnamespace igl\r\n{\r\n  namespace slim\r\n  {\r\n    // Definitions of internal functions\r\n    IGL_INLINE void buildRhs(igl::SLIMData& s, const Eigen::SparseMatrix<double> &A);\r\n    IGL_INLINE void add_soft_constraints(igl::SLIMData& s, Eigen::SparseMatrix<double> &L);\r\n    IGL_INLINE double compute_energy(igl::SLIMData& s, Eigen::MatrixXd &V_new);\r\n    IGL_INLINE double compute_soft_const_energy(igl::SLIMData& s,\r\n                                                const Eigen::MatrixXd &V,\r\n                                                const Eigen::MatrixXi &F,\r\n                                                Eigen::MatrixXd &V_o);\r\n\r\n    IGL_INLINE void solve_weighted_arap(igl::SLIMData& s,\r\n                                        const Eigen::MatrixXd &V,\r\n                                        const Eigen::MatrixXi &F,\r\n                                        Eigen::MatrixXd &uv,\r\n                                        Eigen::VectorXi &soft_b_p,\r\n                                        Eigen::MatrixXd &soft_bc_p);\r\n    IGL_INLINE void update_weights_and_closest_rotations( igl::SLIMData& s,\r\n                                                          Eigen::MatrixXd &uv);\r\n    IGL_INLINE void compute_jacobians(igl::SLIMData& s, const Eigen::MatrixXd &uv);\r\n    IGL_INLINE void build_linear_system(igl::SLIMData& s, Eigen::SparseMatrix<double> &L);\r\n    IGL_INLINE void pre_calc(igl::SLIMData& s);\r\n\r\n    // Implementation\r\n\r\n    IGL_INLINE void compute_jacobians(igl::SLIMData& s, const Eigen::MatrixXd &uv)\r\n    {\r\n      if (s.F.cols() == 3)\r\n      {\r\n        // Ji=[D1*u,D2*u,D1*v,D2*v];\r\n        s.Ji.col(0) = s.Dx * uv.col(0);\r\n        s.Ji.col(1) = s.Dy * uv.col(0);\r\n        s.Ji.col(2) = s.Dx * uv.col(1);\r\n        s.Ji.col(3) = s.Dy * uv.col(1);\r\n      }\r\n      else /*tet mesh*/{\r\n        // Ji=[D1*u,D2*u,D3*u, D1*v,D2*v, D3*v, D1*w,D2*w,D3*w];\r\n        s.Ji.col(0) = s.Dx * uv.col(0);\r\n        s.Ji.col(1) = s.Dy * uv.col(0);\r\n        s.Ji.col(2) = s.Dz * uv.col(0);\r\n        s.Ji.col(3) = s.Dx * uv.col(1);\r\n        s.Ji.col(4) = s.Dy * uv.col(1);\r\n        s.Ji.col(5) = s.Dz * uv.col(1);\r\n        s.Ji.col(6) = s.Dx * uv.col(2);\r\n        s.Ji.col(7) = s.Dy * uv.col(2);\r\n        s.Ji.col(8) = s.Dz * uv.col(2);\r\n      }\r\n    }\r\n\r\n    IGL_INLINE void update_weights_and_closest_rotations(igl::SLIMData& s, Eigen::MatrixXd &uv)\r\n    {\r\n      compute_jacobians(s, uv);\r\n      slim_update_weights_and_closest_rotations_with_jacobians(s.Ji, s.slim_energy, s.exp_factor, s.W, s.Ri);\r\n    }\r\n    \r\n\r\n\r\n\r\n    IGL_INLINE void solve_weighted_arap(igl::SLIMData& s,\r\n                                        const Eigen::MatrixXd &V,\r\n                                        const Eigen::MatrixXi &F,\r\n                                        Eigen::MatrixXd &uv,\r\n                                        Eigen::VectorXi &soft_b_p,\r\n                                        Eigen::MatrixXd &soft_bc_p)\r\n    {\r\n      using namespace Eigen;\r\n\r\n      Eigen::SparseMatrix<double> L;\r\n      build_linear_system(s,L);\r\n\r\n      igl::Timer t;\r\n      \r\n      //t.start();\r\n      // solve\r\n      Eigen::VectorXd Uc;\r\n#ifndef CHOLMOD\r\n      if (s.dim == 2)\r\n      {\r\n        SimplicialLDLT<Eigen::SparseMatrix<double> > solver;\r\n        Uc = solver.compute(L).solve(s.rhs);\r\n      }\r\n      else\r\n      { // seems like CG performs much worse for 2D and way better for 3D\r\n        Eigen::VectorXd guess(uv.rows() * s.dim);\r\n        for (int i = 0; i < s.v_num; i++) for (int j = 0; j < s.dim; j++) guess(uv.rows() * j + i) = uv(i, j); // flatten vector\r\n        ConjugateGradient<Eigen::SparseMatrix<double>, Lower | Upper> cg;\r\n        cg.setTolerance(1e-8);\r\n        cg.compute(L);\r\n        Uc = cg.solveWithGuess(s.rhs, guess);\r\n      }\r\n#else\r\n        CholmodSimplicialLDLT<Eigen::SparseMatrix<double> > solver;\r\n        Uc = solver.compute(L).solve(s.rhs);\r\n#endif\r\n      for (int i = 0; i < s.dim; i++)\r\n        uv.col(i) = Uc.block(i * s.v_n, 0, s.v_n, 1);\r\n\r\n      // t.stop();\r\n      // std::cerr << \"solve: \" << t.getElapsedTime() << std::endl;\r\n\r\n    }\r\n\r\n\r\n    IGL_INLINE void pre_calc(igl::SLIMData& s)\r\n    {\r\n      if (!s.has_pre_calc)\r\n      {\r\n        s.v_n = s.v_num;\r\n        s.f_n = s.f_num;\r\n\r\n        if (s.F.cols() == 3)\r\n        {\r\n          s.dim = 2;\r\n          Eigen::MatrixXd F1, F2, F3;\r\n          igl::local_basis(s.V, s.F, F1, F2, F3);\r\n          Eigen::SparseMatrix<double> G;\r\n          igl::grad(s.V, s.F, G);\r\n          Eigen::SparseMatrix<double> Face_Proj;\r\n\r\n          auto face_proj = [](Eigen::MatrixXd& F){\r\n            std::vector<Eigen::Triplet<double> >IJV;\r\n            int f_num = F.rows();\r\n            for(int i=0; i<F.rows(); i++) {\r\n              IJV.push_back(Eigen::Triplet<double>(i, i, F(i,0)));\r\n              IJV.push_back(Eigen::Triplet<double>(i, i+f_num, F(i,1)));\r\n              IJV.push_back(Eigen::Triplet<double>(i, i+2*f_num, F(i,2)));\r\n            }\r\n            Eigen::SparseMatrix<double> P(f_num, 3*f_num);\r\n            P.setFromTriplets(IJV.begin(), IJV.end());\r\n            return P;\r\n          };\r\n          \r\n          s.Dx = face_proj(F1) * G;\r\n          s.Dy = face_proj(F2) * G;\r\n        }\r\n        else\r\n        {\r\n          s.dim = 3;\r\n          Eigen::SparseMatrix<double> G;\r\n          igl::grad(s.V, s.F, G,\r\n                    s.mesh_improvement_3d /*use normal gradient, or one from a \"regular\" tet*/);\r\n          s.Dx = G.block(0, 0, s.F.rows(), s.V.rows());\r\n          s.Dy = G.block(s.F.rows(), 0, s.F.rows(), s.V.rows());\r\n          s.Dz = G.block(2 * s.F.rows(), 0, s.F.rows(), s.V.rows());\r\n        }\r\n\r\n        s.W.resize(s.f_n, s.dim * s.dim);\r\n        s.Dx.makeCompressed();\r\n        s.Dy.makeCompressed();\r\n        s.Dz.makeCompressed();\r\n        s.Ri.resize(s.f_n, s.dim * s.dim);\r\n        s.Ji.resize(s.f_n, s.dim * s.dim);\r\n        s.rhs.resize(s.dim * s.v_num);\r\n\r\n        // flattened weight matrix\r\n        s.WGL_M.resize(s.dim * s.dim * s.f_n);\r\n        for (int i = 0; i < s.dim * s.dim; i++)\r\n          for (int j = 0; j < s.f_n; j++)\r\n            s.WGL_M(i * s.f_n + j) = s.M(j);\r\n\r\n        s.first_solve = true;\r\n        s.has_pre_calc = true;\r\n      }\r\n    }\r\n\r\n    IGL_INLINE void build_linear_system(igl::SLIMData& s, Eigen::SparseMatrix<double> &L)\r\n    {\r\n      // formula (35) in paper\r\n      std::vector<Eigen::Triplet<double> > IJV;\r\n      \r\n      #ifdef SLIM_CACHED\r\n      slim_buildA(s.Dx, s.Dy, s.Dz, s.W, IJV);\r\n      if (s.A.rows() == 0)\r\n      {\r\n        s.A = Eigen::SparseMatrix<double>(s.dim * s.dim * s.f_n, s.dim * s.v_n);\r\n        igl::sparse_cached_precompute(IJV,s.A_data,s.A);\r\n      }\r\n      else\r\n        igl::sparse_cached(IJV,s.A_data,s.A);\r\n      #else\r\n      Eigen::SparseMatrix<double> A(s.dim * s.dim * s.f_n, s.dim * s.v_n);\r\n      slim_buildA(s.Dx, s.Dy, s.Dz, s.W, IJV);\r\n      A.setFromTriplets(IJV.begin(),IJV.end());\r\n      A.makeCompressed();\r\n      #endif\r\n\r\n      #ifdef SLIM_CACHED\r\n      #else\r\n      Eigen::SparseMatrix<double> At = A.transpose();\r\n      At.makeCompressed();\r\n      #endif\r\n\r\n      #ifdef SLIM_CACHED\r\n      Eigen::SparseMatrix<double> id_m(s.A.cols(), s.A.cols());\r\n      #else\r\n      Eigen::SparseMatrix<double> id_m(A.cols(), A.cols());\r\n      #endif\r\n\r\n      id_m.setIdentity();\r\n\r\n      // add proximal penalty\r\n      #ifdef SLIM_CACHED\r\n      s.AtA_data.W = s.WGL_M;\r\n      if (s.AtA.rows() == 0)\r\n        igl::AtA_cached_precompute(s.A,s.AtA_data,s.AtA);\r\n      else\r\n        igl::AtA_cached(s.A,s.AtA_data,s.AtA);\r\n\r\n      L = s.AtA + s.proximal_p * id_m; //add also a proximal \r\n      L.makeCompressed();\r\n\r\n      #else\r\n      L = At * s.WGL_M.asDiagonal() * A + s.proximal_p * id_m; //add also a proximal term\r\n      L.makeCompressed();\r\n      #endif\r\n\r\n      #ifdef SLIM_CACHED\r\n      buildRhs(s, s.A);\r\n      #else\r\n      buildRhs(s, A);\r\n      #endif\r\n\r\n      Eigen::SparseMatrix<double> OldL = L;\r\n      add_soft_constraints(s,L);\r\n      L.makeCompressed();\r\n    }\r\n\r\n    IGL_INLINE void add_soft_constraints(igl::SLIMData& s, Eigen::SparseMatrix<double> &L)\r\n    {\r\n      int v_n = s.v_num;\r\n      for (int d = 0; d < s.dim; d++)\r\n      {\r\n        for (int i = 0; i < s.b.rows(); i++)\r\n        {\r\n          int v_idx = s.b(i);\r\n          s.rhs(d * v_n + v_idx) += s.soft_const_p * s.bc(i, d); // rhs\r\n          L.coeffRef(d * v_n + v_idx, d * v_n + v_idx) += s.soft_const_p; // diagonal of matrix\r\n        }\r\n      }\r\n    }\r\n\r\n    IGL_INLINE double compute_energy(igl::SLIMData& s, Eigen::MatrixXd &V_new)\r\n    {\r\n      compute_jacobians(s,V_new);\r\n      return mapping_energy_with_jacobians(s.Ji, s.M, s.slim_energy, s.exp_factor) +\r\n             compute_soft_const_energy(s, s.V, s.F, V_new);\r\n    }\r\n\r\n    IGL_INLINE double compute_soft_const_energy(igl::SLIMData& s,\r\n                                                const Eigen::MatrixXd &V,\r\n                                                const Eigen::MatrixXi &F,\r\n                                                Eigen::MatrixXd &V_o)\r\n    {\r\n      double e = 0;\r\n      for (int i = 0; i < s.b.rows(); i++)\r\n      {\r\n        e += s.soft_const_p * (s.bc.row(i) - V_o.row(s.b(i))).squaredNorm();\r\n      }\r\n      return e;\r\n    }\r\n\r\n\r\n\r\n    IGL_INLINE void buildRhs(igl::SLIMData& s, const Eigen::SparseMatrix<double> &A)\r\n    {\r\n      Eigen::VectorXd f_rhs(s.dim * s.dim * s.f_n);\r\n      f_rhs.setZero();\r\n      if (s.dim == 2)\r\n      {\r\n        /*b = [W11*R11 + W12*R21; (formula (36))\r\n             W11*R12 + W12*R22;\r\n             W21*R11 + W22*R21;\r\n             W21*R12 + W22*R22];*/\r\n        for (int i = 0; i < s.f_n; i++)\r\n        {\r\n          f_rhs(i + 0 * s.f_n) = s.W(i, 0) * s.Ri(i, 0) + s.W(i, 1) * s.Ri(i, 1);\r\n          f_rhs(i + 1 * s.f_n) = s.W(i, 0) * s.Ri(i, 2) + s.W(i, 1) * s.Ri(i, 3);\r\n          f_rhs(i + 2 * s.f_n) = s.W(i, 2) * s.Ri(i, 0) + s.W(i, 3) * s.Ri(i, 1);\r\n          f_rhs(i + 3 * s.f_n) = s.W(i, 2) * s.Ri(i, 2) + s.W(i, 3) * s.Ri(i, 3);\r\n        }\r\n      }\r\n      else\r\n      {\r\n        /*b = [W11*R11 + W12*R21 + W13*R31;\r\n             W11*R12 + W12*R22 + W13*R32;\r\n             W11*R13 + W12*R23 + W13*R33;\r\n             W21*R11 + W22*R21 + W23*R31;\r\n             W21*R12 + W22*R22 + W23*R32;\r\n             W21*R13 + W22*R23 + W23*R33;\r\n             W31*R11 + W32*R21 + W33*R31;\r\n             W31*R12 + W32*R22 + W33*R32;\r\n             W31*R13 + W32*R23 + W33*R33;];*/\r\n        for (int i = 0; i < s.f_n; i++)\r\n        {\r\n          f_rhs(i + 0 * s.f_n) = s.W(i, 0) * s.Ri(i, 0) + s.W(i, 1) * s.Ri(i, 1) + s.W(i, 2) * s.Ri(i, 2);\r\n          f_rhs(i + 1 * s.f_n) = s.W(i, 0) * s.Ri(i, 3) + s.W(i, 1) * s.Ri(i, 4) + s.W(i, 2) * s.Ri(i, 5);\r\n          f_rhs(i + 2 * s.f_n) = s.W(i, 0) * s.Ri(i, 6) + s.W(i, 1) * s.Ri(i, 7) + s.W(i, 2) * s.Ri(i, 8);\r\n          f_rhs(i + 3 * s.f_n) = s.W(i, 3) * s.Ri(i, 0) + s.W(i, 4) * s.Ri(i, 1) + s.W(i, 5) * s.Ri(i, 2);\r\n          f_rhs(i + 4 * s.f_n) = s.W(i, 3) * s.Ri(i, 3) + s.W(i, 4) * s.Ri(i, 4) + s.W(i, 5) * s.Ri(i, 5);\r\n          f_rhs(i + 5 * s.f_n) = s.W(i, 3) * s.Ri(i, 6) + s.W(i, 4) * s.Ri(i, 7) + s.W(i, 5) * s.Ri(i, 8);\r\n          f_rhs(i + 6 * s.f_n) = s.W(i, 6) * s.Ri(i, 0) + s.W(i, 7) * s.Ri(i, 1) + s.W(i, 8) * s.Ri(i, 2);\r\n          f_rhs(i + 7 * s.f_n) = s.W(i, 6) * s.Ri(i, 3) + s.W(i, 7) * s.Ri(i, 4) + s.W(i, 8) * s.Ri(i, 5);\r\n          f_rhs(i + 8 * s.f_n) = s.W(i, 6) * s.Ri(i, 6) + s.W(i, 7) * s.Ri(i, 7) + s.W(i, 8) * s.Ri(i, 8);\r\n        }\r\n      }\r\n      Eigen::VectorXd uv_flat(s.dim *s.v_n);\r\n      for (int i = 0; i < s.dim; i++)\r\n        for (int j = 0; j < s.v_n; j++)\r\n          uv_flat(s.v_n * i + j) = s.V_o(j, i);\r\n\r\n      s.rhs = (f_rhs.transpose() * s.WGL_M.asDiagonal() * A).transpose() + s.proximal_p * uv_flat;\r\n    }\r\n\r\n  }\r\n}\r\n\r\nIGL_INLINE void igl::slim_update_weights_and_closest_rotations_with_jacobians(const Eigen::MatrixXd &Ji,\r\n                                          igl::MappingEnergyType slim_energy,\r\n                                          double exp_factor,\r\n                                          Eigen::MatrixXd &W,\r\n                                          Eigen::MatrixXd &Ri)\r\n{\r\n  const double eps = 1e-8;\r\n  double exp_f = exp_factor;\r\n  const int dim = (Ji.cols()==4? 2:3);\r\n\r\n  if (dim == 2)\r\n  {\r\n    for (int i = 0; i < Ji.rows(); ++i)\r\n    {\r\n      typedef Eigen::Matrix2d Mat2;\r\n      typedef Eigen::Matrix<double, 2, 2, Eigen::RowMajor> RMat2;\r\n      typedef Eigen::Vector2d Vec2;\r\n      Mat2 ji, ri, ti, ui, vi;\r\n      Vec2 sing;\r\n      Vec2 closest_sing_vec;\r\n      RMat2 mat_W;\r\n      Vec2 m_sing_new;\r\n      double s1, s2;\r\n\r\n      ji(0, 0) = Ji(i, 0);\r\n      ji(0, 1) = Ji(i, 1);\r\n      ji(1, 0) = Ji(i, 2);\r\n      ji(1, 1) = Ji(i, 3);\r\n\r\n      igl::polar_svd(ji, ri, ti, ui, sing, vi);\r\n\r\n      s1 = sing(0);\r\n      s2 = sing(1);\r\n\r\n      // Update Weights according to energy\r\n      switch (slim_energy)\r\n      {\r\n        case igl::MappingEnergyType::ARAP:\r\n        {\r\n          m_sing_new << 1, 1;\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::SYMMETRIC_DIRICHLET:\r\n        {\r\n          double s1_g = 2 * (s1 - pow(s1, -3));\r\n          double s2_g = 2 * (s2 - pow(s2, -3));\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::LOG_ARAP:\r\n        {\r\n          double s1_g = 2 * (log(s1) / s1);\r\n          double s2_g = 2 * (log(s2) / s2);\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::CONFORMAL:\r\n        {\r\n          double s1_g = 1 / (2 * s2) - s2 / (2 * pow(s1, 2));\r\n          double s2_g = 1 / (2 * s1) - s1 / (2 * pow(s2, 2));\r\n\r\n          double geo_avg = sqrt(s1 * s2);\r\n          double s1_min = geo_avg;\r\n          double s2_min = geo_avg;\r\n\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - s1_min))), sqrt(s2_g / (2 * (s2 - s2_min)));\r\n\r\n          // change local step\r\n          closest_sing_vec << s1_min, s2_min;\r\n          ri = ui * closest_sing_vec.asDiagonal() * vi.transpose();\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::EXP_CONFORMAL:\r\n        {\r\n          double s1_g = 2 * (s1 - pow(s1, -3));\r\n          double s2_g = 2 * (s2 - pow(s2, -3));\r\n\r\n          double geo_avg = sqrt(s1 * s2);\r\n          double s1_min = geo_avg;\r\n          double s2_min = geo_avg;\r\n\r\n          double in_exp = exp_f * ((pow(s1, 2) + pow(s2, 2)) / (2 * s1 * s2));\r\n          double exp_thing = exp(in_exp);\r\n\r\n          s1_g *= exp_thing * exp_f;\r\n          s2_g *= exp_thing * exp_f;\r\n\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET:\r\n        {\r\n          double s1_g = 2 * (s1 - pow(s1, -3));\r\n          double s2_g = 2 * (s2 - pow(s2, -3));\r\n\r\n          double in_exp = exp_f * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2));\r\n          double exp_thing = exp(in_exp);\r\n\r\n          s1_g *= exp_thing * exp_f;\r\n          s2_g *= exp_thing * exp_f;\r\n\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));\r\n          break;\r\n        }\r\n      }\r\n\r\n      if (std::abs(s1 - 1) < eps) m_sing_new(0) = 1;\r\n      if (std::abs(s2 - 1) < eps) m_sing_new(1) = 1;\r\n      mat_W = ui * m_sing_new.asDiagonal() * ui.transpose();\r\n\r\n      W.row(i) = Eigen::Map<Eigen::Matrix<double, 1, 4, Eigen::RowMajor>>(mat_W.data());\r\n      // 2) Update local step (doesn't have to be a rotation, for instance in case of conformal energy)\r\n      Ri.row(i) = Eigen::Map<Eigen::Matrix<double, 1,4,Eigen::RowMajor>>(ri.data());\r\n    }\r\n  }\r\n  else\r\n  {\r\n    typedef Eigen::Matrix<double, 3, 1> Vec3;\r\n    typedef Eigen::Matrix<double, 3, 3, Eigen::ColMajor> Mat3;\r\n    typedef Eigen::Matrix<double, 3, 3, Eigen::RowMajor> RMat3;\r\n    Mat3 ji;\r\n    Vec3 m_sing_new;\r\n    Vec3 closest_sing_vec;\r\n    const double sqrt_2 = sqrt(2);\r\n    for (int i = 0; i < Ji.rows(); ++i)\r\n    {\r\n      ji << Ji(i,0), Ji(i,1), Ji(i,2), \r\n      Ji(i,3), Ji(i,4), Ji(i,5), \r\n      Ji(i,6), Ji(i,7), Ji(i,8);\r\n\r\n      Mat3 ri, ti, ui, vi;\r\n      Vec3 sing;\r\n      igl::polar_svd(ji, ri, ti, ui, sing, vi);\r\n\r\n      double s1 = sing(0);\r\n      double s2 = sing(1);\r\n      double s3 = sing(2);\r\n\r\n      // 1) Update Weights\r\n      switch (slim_energy)\r\n      {\r\n        case igl::MappingEnergyType::ARAP:\r\n        {\r\n          m_sing_new << 1, 1, 1;\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::LOG_ARAP:\r\n        {\r\n          double s1_g = 2 * (log(s1) / s1);\r\n          double s2_g = 2 * (log(s2) / s2);\r\n          double s3_g = 2 * (log(s3) / s3);\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::SYMMETRIC_DIRICHLET:\r\n        {\r\n          double s1_g = 2 * (s1 - pow(s1, -3));\r\n          double s2_g = 2 * (s2 - pow(s2, -3));\r\n          double s3_g = 2 * (s3 - pow(s3, -3));\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET:\r\n        {\r\n          double s1_g = 2 * (s1 - pow(s1, -3));\r\n          double s2_g = 2 * (s2 - pow(s2, -3));\r\n          double s3_g = 2 * (s3 - pow(s3, -3));\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));\r\n\r\n          double in_exp = exp_f * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2) + pow(s3, 2) + pow(s3, -2));\r\n          double exp_thing = exp(in_exp);\r\n\r\n          s1_g *= exp_thing * exp_f;\r\n          s2_g *= exp_thing * exp_f;\r\n          s3_g *= exp_thing * exp_f;\r\n\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));\r\n\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::CONFORMAL:\r\n        {\r\n          double common_div = 9 * (pow(s1 * s2 * s3, 5. / 3.));\r\n\r\n          double s1_g = (-2 * s2 * s3 * (pow(s2, 2) + pow(s3, 2) - 2 * pow(s1, 2))) / common_div;\r\n          double s2_g = (-2 * s1 * s3 * (pow(s1, 2) + pow(s3, 2) - 2 * pow(s2, 2))) / common_div;\r\n          double s3_g = (-2 * s1 * s2 * (pow(s1, 2) + pow(s2, 2) - 2 * pow(s3, 2))) / common_div;\r\n\r\n          double closest_s = sqrt(pow(s1, 2) + pow(s3, 2)) / sqrt_2;\r\n          double s1_min = closest_s;\r\n          double s2_min = closest_s;\r\n          double s3_min = closest_s;\r\n\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - s1_min))), sqrt(s2_g / (2 * (s2 - s2_min))), sqrt(\r\n              s3_g / (2 * (s3 - s3_min)));\r\n\r\n          // change local step\r\n          closest_sing_vec << s1_min, s2_min, s3_min;\r\n          ri = ui * closest_sing_vec.asDiagonal() * vi.transpose();\r\n          break;\r\n        }\r\n        case igl::MappingEnergyType::EXP_CONFORMAL:\r\n        {\r\n          // E_conf = (s1^2 + s2^2 + s3^2)/(3*(s1*s2*s3)^(2/3) )\r\n          // dE_conf/ds1 = (-2*(s2*s3)*(s2^2+s3^2 -2*s1^2) ) / (9*(s1*s2*s3)^(5/3))\r\n          // Argmin E_conf(s1): s1 = sqrt(s1^2+s2^2)/sqrt(2)\r\n          double common_div = 9 * (pow(s1 * s2 * s3, 5. / 3.));\r\n\r\n          double s1_g = (-2 * s2 * s3 * (pow(s2, 2) + pow(s3, 2) - 2 * pow(s1, 2))) / common_div;\r\n          double s2_g = (-2 * s1 * s3 * (pow(s1, 2) + pow(s3, 2) - 2 * pow(s2, 2))) / common_div;\r\n          double s3_g = (-2 * s1 * s2 * (pow(s1, 2) + pow(s2, 2) - 2 * pow(s3, 2))) / common_div;\r\n\r\n          double in_exp = exp_f * ((pow(s1, 2) + pow(s2, 2) + pow(s3, 2)) / (3 * pow((s1 * s2 * s3), 2. / 3)));;\r\n          double exp_thing = exp(in_exp);\r\n\r\n          double closest_s = sqrt(pow(s1, 2) + pow(s3, 2)) / sqrt_2;\r\n          double s1_min = closest_s;\r\n          double s2_min = closest_s;\r\n          double s3_min = closest_s;\r\n\r\n          s1_g *= exp_thing * exp_f;\r\n          s2_g *= exp_thing * exp_f;\r\n          s3_g *= exp_thing * exp_f;\r\n\r\n          m_sing_new << sqrt(s1_g / (2 * (s1 - s1_min))), sqrt(s2_g / (2 * (s2 - s2_min))), sqrt(\r\n              s3_g / (2 * (s3 - s3_min)));\r\n\r\n          // change local step\r\n          closest_sing_vec << s1_min, s2_min, s3_min;\r\n          ri = ui * closest_sing_vec.asDiagonal() * vi.transpose();\r\n        }\r\n      }\r\n      if (std::abs(s1 - 1) < eps) m_sing_new(0) = 1;\r\n      if (std::abs(s2 - 1) < eps) m_sing_new(1) = 1;\r\n      if (std::abs(s3 - 1) < eps) m_sing_new(2) = 1;\r\n      RMat3 mat_W;\r\n      mat_W = ui * m_sing_new.asDiagonal() * ui.transpose();\r\n\r\n      W.row(i) = Eigen::Map<Eigen::Matrix<double, 1,9,Eigen::RowMajor>>(mat_W.data());\r\n      // 2) Update closest rotations (not rotations in case of conformal energy)\r\n      Ri.row(i) = Eigen::Map<Eigen::Matrix<double, 1,9,Eigen::RowMajor>>(ri.data());\r\n    } // for loop end\r\n\r\n  } // if dim end\r\n\r\n}\r\n\r\nIGL_INLINE void igl::slim_buildA(const Eigen::SparseMatrix<double> &Dx,\r\n          const Eigen::SparseMatrix<double> &Dy,\r\n          const Eigen::SparseMatrix<double> &Dz,\r\n          const Eigen::MatrixXd &W,\r\nstd::vector<Eigen::Triplet<double> > & IJV)\r\n{\r\n  const int dim = (W.cols() == 4) ? 2 : 3;\r\n  const int f_n = W.rows();\r\n  const int v_n = Dx.cols();\r\n\r\n  // formula (35) in paper\r\n  if (dim == 2)\r\n  {\r\n    IJV.reserve(4 * (Dx.outerSize() + Dy.outerSize()));\r\n\r\n    /*A = [W11*Dx, W12*Dx;\r\n          W11*Dy, W12*Dy;\r\n          W21*Dx, W22*Dx;\r\n          W21*Dy, W22*Dy];*/\r\n    for (int k = 0; k < Dx.outerSize(); ++k)\r\n    {\r\n      for (Eigen::SparseMatrix<double>::InnerIterator it(Dx, k); it; ++it)\r\n      {\r\n        int dx_r = it.row();\r\n        int dx_c = it.col();\r\n        double val = it.value();\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(dx_r, dx_c, val * W(dx_r, 0)));\r\n        IJV.push_back(Eigen::Triplet<double>(dx_r, v_n + dx_c, val * W(dx_r, 1)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dx_r, dx_c, val * W(dx_r, 2)));\r\n        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dx_r, v_n + dx_c, val * W(dx_r, 3)));\r\n      }\r\n    }\r\n\r\n    for (int k = 0; k < Dy.outerSize(); ++k)\r\n    {\r\n      for (Eigen::SparseMatrix<double>::InnerIterator it(Dy, k); it; ++it)\r\n      {\r\n        int dy_r = it.row();\r\n        int dy_c = it.col();\r\n        double val = it.value();\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, dy_c, val * W(dy_r, 0)));\r\n        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, v_n + dy_c, val * W(dy_r, 1)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dy_r, dy_c, val * W(dy_r, 2)));\r\n        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dy_r, v_n + dy_c, val * W(dy_r, 3)));\r\n      }\r\n    }\r\n  }\r\n  else\r\n  {\r\n\r\n    /*A = [W11*Dx, W12*Dx, W13*Dx;\r\n            W11*Dy, W12*Dy, W13*Dy;\r\n            W11*Dz, W12*Dz, W13*Dz;\r\n            W21*Dx, W22*Dx, W23*Dx;\r\n            W21*Dy, W22*Dy, W23*Dy;\r\n            W21*Dz, W22*Dz, W23*Dz;\r\n            W31*Dx, W32*Dx, W33*Dx;\r\n            W31*Dy, W32*Dy, W33*Dy;\r\n            W31*Dz, W32*Dz, W33*Dz;];*/\r\n    IJV.reserve(9 * (Dx.outerSize() + Dy.outerSize() + Dz.outerSize()));\r\n    for (int k = 0; k < Dx.outerSize(); k++)\r\n    {\r\n      for (Eigen::SparseMatrix<double>::InnerIterator it(Dx, k); it; ++it)\r\n      {\r\n        int dx_r = it.row();\r\n        int dx_c = it.col();\r\n        double val = it.value();\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(dx_r, dx_c, val * W(dx_r, 0)));\r\n        IJV.push_back(Eigen::Triplet<double>(dx_r, v_n + dx_c, val * W(dx_r, 1)));\r\n        IJV.push_back(Eigen::Triplet<double>(dx_r, 2 * v_n + dx_c, val * W(dx_r, 2)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dx_r, dx_c, val * W(dx_r, 3)));\r\n        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dx_r, v_n + dx_c, val * W(dx_r, 4)));\r\n        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dx_r, 2 * v_n + dx_c, val * W(dx_r, 5)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(6 * f_n + dx_r, dx_c, val * W(dx_r, 6)));\r\n        IJV.push_back(Eigen::Triplet<double>(6 * f_n + dx_r, v_n + dx_c, val * W(dx_r, 7)));\r\n        IJV.push_back(Eigen::Triplet<double>(6 * f_n + dx_r, 2 * v_n + dx_c, val * W(dx_r, 8)));\r\n      }\r\n    }\r\n\r\n    for (int k = 0; k < Dy.outerSize(); k++)\r\n    {\r\n      for (Eigen::SparseMatrix<double>::InnerIterator it(Dy, k); it; ++it)\r\n      {\r\n        int dy_r = it.row();\r\n        int dy_c = it.col();\r\n        double val = it.value();\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, dy_c, val * W(dy_r, 0)));\r\n        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, v_n + dy_c, val * W(dy_r, 1)));\r\n        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, 2 * v_n + dy_c, val * W(dy_r, 2)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(4 * f_n + dy_r, dy_c, val * W(dy_r, 3)));\r\n        IJV.push_back(Eigen::Triplet<double>(4 * f_n + dy_r, v_n + dy_c, val * W(dy_r, 4)));\r\n        IJV.push_back(Eigen::Triplet<double>(4 * f_n + dy_r, 2 * v_n + dy_c, val * W(dy_r, 5)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(7 * f_n + dy_r, dy_c, val * W(dy_r, 6)));\r\n        IJV.push_back(Eigen::Triplet<double>(7 * f_n + dy_r, v_n + dy_c, val * W(dy_r, 7)));\r\n        IJV.push_back(Eigen::Triplet<double>(7 * f_n + dy_r, 2 * v_n + dy_c, val * W(dy_r, 8)));\r\n      }\r\n    }\r\n\r\n    for (int k = 0; k < Dz.outerSize(); k++)\r\n    {\r\n      for (Eigen::SparseMatrix<double>::InnerIterator it(Dz, k); it; ++it)\r\n      {\r\n        int dz_r = it.row();\r\n        int dz_c = it.col();\r\n        double val = it.value();\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dz_r, dz_c, val * W(dz_r, 0)));\r\n        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dz_r, v_n + dz_c, val * W(dz_r, 1)));\r\n        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dz_r, 2 * v_n + dz_c, val * W(dz_r, 2)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(5 * f_n + dz_r, dz_c, val * W(dz_r, 3)));\r\n        IJV.push_back(Eigen::Triplet<double>(5 * f_n + dz_r, v_n + dz_c, val * W(dz_r, 4)));\r\n        IJV.push_back(Eigen::Triplet<double>(5 * f_n + dz_r, 2 * v_n + dz_c, val * W(dz_r, 5)));\r\n\r\n        IJV.push_back(Eigen::Triplet<double>(8 * f_n + dz_r, dz_c, val * W(dz_r, 6)));\r\n        IJV.push_back(Eigen::Triplet<double>(8 * f_n + dz_r, v_n + dz_c, val * W(dz_r, 7)));\r\n        IJV.push_back(Eigen::Triplet<double>(8 * f_n + dz_r, 2 * v_n + dz_c, val * W(dz_r, 8)));\r\n      }\r\n    }\r\n  }\r\n}\r\n/// Slim Implementation\r\n\r\nIGL_INLINE void igl::slim_precompute(\r\n  const Eigen::MatrixXd &V, \r\n  const Eigen::MatrixXi &F, \r\n  const Eigen::MatrixXd &V_init, \r\n  igl::SLIMData &data,\r\n  igl::MappingEnergyType slim_energy, \r\n  Eigen::VectorXi &b, \r\n  Eigen::MatrixXd &bc,\r\n  double soft_p)\r\n{\r\n\r\n  data.V = V;\r\n  data.F = F;\r\n  data.V_o = V_init;\r\n\r\n  data.v_num = V.rows();\r\n  data.f_num = F.rows();\r\n\r\n  data.slim_energy = slim_energy;\r\n\r\n  data.b = b;\r\n  data.bc = bc;\r\n  data.soft_const_p = soft_p;\r\n\r\n  data.proximal_p = 0.0001;\r\n\r\n  igl::doublearea(V, F, data.M);\r\n  data.M /= 2.;\r\n  data.mesh_area = data.M.sum();\r\n  data.mesh_improvement_3d = false; // whether to use a jacobian derived from a real mesh or an abstract regular mesh (used for mesh improvement)\r\n  data.exp_factor = 1.0; // param used only for exponential energies (e.g exponential symmetric dirichlet)\r\n\r\n  assert (F.cols() == 3 || F.cols() == 4);\r\n\r\n  igl::slim::pre_calc(data);\r\n  data.energy = igl::slim::compute_energy(data,data.V_o) / data.mesh_area;\r\n}\r\n\r\nIGL_INLINE Eigen::MatrixXd igl::slim_solve(igl::SLIMData &data, int iter_num)\r\n{\r\n  for (int i = 0; i < iter_num; i++)\r\n  {\r\n    Eigen::MatrixXd dest_res;\r\n    dest_res = data.V_o;\r\n\r\n    // Solve Weighted Proxy\r\n    igl::slim::update_weights_and_closest_rotations(data, dest_res);\r\n    igl::slim::solve_weighted_arap(data,data.V, data.F, dest_res, data.b, data.bc);\r\n\r\n    double old_energy = data.energy;\r\n\r\n    std::function<double(Eigen::MatrixXd &)> compute_energy = [&](\r\n        Eigen::MatrixXd &aaa) { return igl::slim::compute_energy(data,aaa); };\r\n\r\n    data.energy = igl::flip_avoiding_line_search(data.F, data.V_o, dest_res, compute_energy,\r\n                                                 data.energy * data.mesh_area) / data.mesh_area;\r\n  }\r\n  return data.V_o;\r\n}\r\n\r\n\r\n#ifdef IGL_STATIC_LIBRARY\r\n// Explicit template instantiation\r\n#endif\r\n", "meta": {"hexsha": "9cde7d8a68acf86f3e281e7af9b2b04054bc5b5c", "size": 29308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/slim.cpp", "max_stars_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_stars_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "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/slim.cpp", "max_issues_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_issues_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "max_issues_repo_licenses": ["Apache-2.0"], "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/slim.cpp", "max_forks_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_forks_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "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.2722772277, "max_line_length": 146, "alphanum_fraction": 0.4996246759, "num_tokens": 9707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.06187599221093972, "lm_q1q2_score": 0.02948883877710838}}
{"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_DENSE2D_INCLUDE\n#define MTL_DENSE2D_INCLUDE\n\n\n#include <algorithm>\n#include <boost/mpl/bool.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/utility/enable_if.hpp>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/matrix/crtp_base_matrix.hpp>\n#include <boost/numeric/mtl/matrix/base_sub_matrix.hpp>\n#include <boost/numeric/mtl/matrix/all_mat_expr.hpp>\n#include <boost/numeric/mtl/matrix/operators.hpp>\n#include <boost/numeric/mtl/detail/contiguous_memory_block.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/operation/compute_factors.hpp>\n#include <boost/numeric/mtl/operation/clone.hpp>\n#include <boost/numeric/mtl/operation/is_negative.hpp>\n#include <boost/numeric/mtl/utility/common_include.hpp>\n#include <boost/numeric/mtl/utility/assert.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/is_static.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/utility/dense_el_cursor.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/utility/strided_dense_el_cursor.hpp>\n#include <boost/numeric/mtl/utility/strided_dense_el_iterator.hpp>\n#include <boost/numeric/mtl/utility/transposed_orientation.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n\n#ifdef MTL_WITH_INITLIST\n# include <initializer_list>\n#endif\n#include <algorithm>\n\n// Forward declaration (for friend declaration)\nnamespace mtl { namespace traits { namespace detail {\n    template <typename, typename, bool> struct dense2D_iterator_range_generator;\n}}}\n\nnamespace mtl { namespace mat {\n\n\nusing std::size_t;\n\n// Forward declarations\ntemplate <typename Value, typename Parameters> class dense2D;\nclass dense2D_indexer;\n\n// Helper type\nstruct dense2D_sub_ctor {};\n\n// Indexing for dense matrices\nclass dense2D_indexer \n{\n    // helpers for public functions\n    size_t offset(size_t ldim, size_t r, size_t c, row_major) const \n    {\n\treturn r * ldim + c; \n    }\n    size_t offset(size_t ldim, size_t r, size_t c, col_major) const \n    {\n\treturn c * ldim + r; \n    }\n    \n    size_t row(size_t offset, size_t ldim, row_major) const \n    {\n\treturn offset / ldim; \n    }\n    size_t row(size_t offset, size_t ldim, col_major) const \n    {\n\treturn offset % ldim;\n    }\n    \n    size_t col(size_t offset, size_t ldim, row_major) const \n    {\n\treturn offset % ldim;\n    }\n    size_t col(size_t offset, size_t ldim, col_major) const \n    {\n\treturn offset / ldim; \n    }\n\n public:\n    template <typename Value, class Parameters>\n    size_t operator() (const dense2D<Value, Parameters>& ma, size_t r, size_t c) const\n    {\n\ttypedef dense2D<Value, Parameters> matrix_type;\n\t// convert into c indices\n\ttypename matrix_type::index_type my_index;\n\tsize_t my_r= index::change_from(my_index, r);\n\tsize_t my_c= index::change_from(my_index, c);\n\treturn offset(ma.ldim, my_r, my_c, typename matrix_type::orientation());\n    }\n\n    template <typename Value, class Parameters>\n    size_t row(const dense2D<Value, Parameters>& ma, \n\t       typename dense2D<Value, Parameters>::key_type key) const\n    {\n\ttypedef dense2D<Value, Parameters> matrix_type;\n\t// row with c-index for my orientation\n\tsize_t r= row(ma.offset(key), ma.ldim, typename matrix_type::orientation());\n\treturn index::change_to(typename matrix_type::index_type(), r);\n    }\n\n    template <typename Value, class Parameters>\n    size_t col(const dense2D<Value, Parameters>& ma, \n\t       typename dense2D<Value, Parameters>::key_type key) const \n    {\n\ttypedef dense2D<Value, Parameters> matrix_type;\n\t// column with c-index for my orientation\n\tsize_t c= col(ma.offset(key), ma.ldim, typename matrix_type::orientation());\n\treturn index::change_to(typename matrix_type::index_type(), c);\n    }\n    template <typename, typename> friend class dense2D;\n}; // dense2D_indexer\n\n\nnamespace detail \n{\n    \n    // Compute required memory\n    // Enabling mechanism to make sure that computation is valid\n    template <typename Parameters, bool Enable>\n    struct dense2D_array_size {\n\tstatic std::size_t const value= 0;\n    };\n\n    template <typename Parameters>\n    struct dense2D_array_size<Parameters, true>\n    {\n\ttypedef typename Parameters::dimensions   dimensions;\n\tMTL_STATIC_ASSERT((dimensions::is_static), \"Size must be known at compile time.\");\n\tstatic std::size_t const value= dimensions::Num_Rows * dimensions::Num_Cols;\n    };\n\n    // return const-ref if matrix on stack and type itself if on heap \n    template <typename Matrix, bool on_stack>\n    struct ref_on_stack\n    {\n\ttypedef Matrix type;\n    };\n\n    template <typename Matrix>\n    struct ref_on_stack<Matrix, true>\n    {\n\ttypedef const Matrix& type;\n    };\n\n} // namespace detail\n\n  \n/// Dense matrix type\ntemplate <typename Value, typename Parameters = parameters<> >\nclass dense2D\n    : public base_sub_matrix<Value, Parameters>,\n    public mtl::detail::contiguous_memory_block< Value, Parameters::on_stack,\n    detail::dense2D_array_size<Parameters, Parameters::on_stack>::value >,\n    public crtp_base_matrix< dense2D<Value, Parameters>, Value, std::size_t >,\n    public mat_expr< dense2D<Value, Parameters> >\n{\n    typedef dense2D                                           self;\n    typedef base_sub_matrix<Value, Parameters>                super;\n    typedef mtl::detail::contiguous_memory_block<Value, Parameters::on_stack,\n\tdetail::dense2D_array_size<Parameters, Parameters::on_stack>::value>     memory_base;\n    typedef mat_expr< dense2D<Value, Parameters> >            expr_base;\n    typedef crtp_base_matrix< self, Value, std::size_t >      crtp_base;\n    typedef crtp_matrix_assign< self, Value, std::size_t >    assign_base;\npublic:\n    typedef Parameters                        parameters;\n    typedef typename Parameters::orientation  orientation;\n    typedef typename Parameters::index        index_type;\n    typedef typename Parameters::dimensions   dim_type;\n    typedef Value                             value_type;\n    typedef const value_type&                 const_reference;\n    typedef value_type&                       reference;\n\n    typedef const value_type*                 const_pointer_type;\n    typedef const_pointer_type                key_type;\n    typedef std::size_t                       size_type;\n    typedef dense_el_cursor<Value>            el_cursor_type;\n    typedef dense2D_indexer                   indexer_type;\n\n    // Self-similar type unless dimension is fixed\n    // Not supported for the moment\n    typedef self                              sub_matrix_type;\n\nprotected:\n    // Obviously, the next 3 functions must be called after setting dimensions\n    void set_nnz() { this->my_nnz = this->num_rows() * this->num_cols(); }\n    void set_ldim(row_major) { ldim = this->num_cols(); }\n    void set_ldim(col_major) { ldim = this->num_rows(); }\n    void set_ldim() { set_ldim(orientation()); }\n\n    void init()\n    {\n\tset_nnz(); set_ldim(); // set_to_zero(*this);\n    }\n\npublic:\n    /// Default constructor, if compile time matrix size allocate memory\n    dense2D() : memory_base(dim_type().num_rows() * dim_type().num_cols())\n    {\n\tinit();\n    }\n\n    /// Constructor that only sets dimensions, only for run-time dimensions\n    explicit dense2D(mtl::non_fixed::dimensions d)\n\t: super(d), memory_base(d.num_rows() * d.num_cols())\n    {\n\tinit();\n    }\n\n    /// Most common constructor from number of rows and columns\n    explicit dense2D(size_type num_rows, size_type num_cols)\n\t: super(dim_type(num_rows, num_cols)),\n\tmemory_base(num_rows * num_cols)\n    {\n\tinit();\n    }\n\n    /// Constructor that sets dimensions and pointer to external data\n    explicit dense2D(mtl::non_fixed::dimensions d, value_type* a)\n\t: super(d), memory_base(a, d.num_rows() * d.num_cols())\n    {\n\tinit();\n    }\n\n    /// Constructor that sets dimensions and pointer to external data\n    explicit dense2D(size_type num_rows, size_type num_cols, value_type* a)\n\t: super(mtl::non_fixed::dimensions(num_rows, num_cols)), memory_base(a, num_rows * num_cols)\n    {\n\tinit();\n    }\n\n    /// Constructor for compile time matrix size\n    /** sets dimensions and pointer to external data **/\n    explicit dense2D(value_type* a)\n\t: super(), memory_base(a, dim_type().num_rows() * dim_type().num_cols())\n    {\n\tMTL_STATIC_ASSERT((dim_type::is_static), \"Size must be known at compile time.\");\n\tinit();\n    }\n\n    /// Default copy constructor\n    dense2D(const self& m)\n\t: super(dim_type(m.num_rows(), m.num_cols())),\n\tmemory_base(m)\n    {\n\t// In case of sub-matrices we need m's ldim -> init doesn't work\n\tthis->my_nnz = m.my_nnz; ldim = m.ldim;\n    }\n\n    /// Clone constructor, copies every source including sub-matrices and other matrices with references\n    explicit dense2D(const self& m, clone_ctor)\n\t: super(mtl::non_fixed::dimensions(m.num_rows(), m.num_cols())),\n\tmemory_base(m, clone_ctor())\n    {\n\tinit();\n\t*this = m;\n    }\n\n    /// General copy constructor, uses functionality from CRTP base\n    template <typename MatrixSrc>\n    explicit dense2D(const MatrixSrc& src)\n\t: super(), memory_base(dim_type().num_rows() * dim_type().num_cols())\n    {\n\tinit();\n\t*this = src;\n    }\n\n#ifdef MTL_WITH_MOVE\n    /// Move constructor\n    dense2D(self&& src)\n\t: super(std::move(src)), memory_base(std::move(src)), ldim(src.ldim)\n    {}\n#endif\t\n\n    /// Constructor for creating sub-matrices\n    template <typename MatrixSrc>\n    dense2D(MatrixSrc& matrix, dense2D_sub_ctor, \n\t    size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n      : super(mtl::non_fixed::dimensions(matrix.num_rows(), matrix.num_cols())),\n        memory_base(matrix.data, (end_r - begin_r) * (end_c - begin_c), true)\n    {\n\tsub_matrix_constructor(matrix, begin_r, end_r, begin_c, end_c, boost::mpl::bool_<memory_base::on_stack>());\n    }\n\n#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n    /// Constructor for initializer list \\p values \n    template <typename Value2>\n    dense2D(std::initializer_list<std::initializer_list<Value2> > values)\n      : super(mtl::non_fixed::dimensions(values.size(), values.size()? values.begin()->size() : 0)),\n    \tmemory_base(this->num_rows() * this->num_cols()) \n    {\n    \tinit();\n\t*this= values;\n    }\n#endif\n\n  private:\n    template <typename MatrixSrc>\n    void sub_matrix_constructor(MatrixSrc& matrix, size_type begin_r, size_type end_r, \n\t\t\t\tsize_type begin_c, size_type end_c, boost::mpl::false_)\n    {\n\tmatrix.check_ranges(begin_r, end_r, begin_c, end_c);\n\t\n\tif(end_r <= begin_r || end_c <= begin_c)\n\t    set_ranges(0, 0);\n\telse {\n\t    // Leading dimension doesn't change\n\t    this->data += matrix.indexer(matrix, begin_r, begin_c);  // Takes care of indexing\n\t    set_ranges(end_r - begin_r, end_c - begin_c);\n\t}\n\tthis->my_nnz= matrix.nnz(); ldim= matrix.get_ldim();\n    }\n\n    template <typename MatrixSrc>\n    void sub_matrix_constructor(MatrixSrc&, size_type, size_type, \n\t\t\t\tsize_type, size_type, boost::mpl::true_)\n    {\n\tMTL_THROW(logic_error(\"Matrices cannot be used as sub-matrices!\"));\n    }\n\n  public:\n\n#ifdef MTL_WITH_MOVE\n    /// Move assignment for data on heap\n    self& operator=(self&& src)\n    {\treturn self_assign(src, boost::mpl::bool_<memory_base::on_stack>());    }\n\n    /// (Copy) Assignment\n    self& operator=(const self& src)\n    {\treturn self_assign(src, boost::mpl::true_());    }\n    \n#else   \n    /// (Copy) Assignment\n    self& operator=(typename detail::ref_on_stack<self, memory_base::on_stack>::type src)\n    {\n\treturn self_assign(src, boost::mpl::bool_<memory_base::on_stack>());\n    }\n#endif\n\n  private:\n    // Already copied for lvalues -> data can be stolen (need non-const ref)  \n    self& self_assign(self& src, boost::mpl::false_)\n    {\n\t// Self-copy would be an indication of an error\n\tassert(this != &src);\n\t// std::cout << \"In move assignment: this* = \\n\" << *this << \"src = \\n\" << src;\n\n\tthis->checked_change_dim(src.num_rows(), src.num_cols());\n\tif (this->category == memory_base::view || src.category == memory_base::view)\n\t    matrix_copy(src, *this);\n\telse {\n\t    if (this->num_rows() != src.num_rows() || this->num_cols() != src.num_cols()) {\n\t\tsuper::change_dim(src.num_rows(), src.num_cols());\n\t\tinit();\n\t    }\n\t    memory_base::move_assignment(src);\n\t}\n\t// std::cout << \"End of move assignment: this* = \\n\" << *this;\n\treturn *this;\n    }\n\n    // For matrices with data on stack (or lvalues in C++11)\n    self& self_assign(const self& src, boost::mpl::true_)\n    {\n\tif (this != &src) {\n\t    this->checked_change_dim(src.num_rows(), src.num_cols());\n\t    matrix_copy(src, *this);\n\t}\n\treturn *this;\n    }\n  public:\n\n    // import operators from CRTP base class\n#if 0 // def __PGI\n    using crtp_base::operator=;\n#else\n    using assign_base::operator=;\n#endif\n\n    /// Change dimension, can keep old data\n    void change_dim(size_type r, size_type c, bool keep_data = false)\n    {\n\tchange_dim(r, c, keep_data, mtl::traits::is_static<self>());\n    }\n\n  private:\n    void change_dim(size_type r, size_type c, bool keep_data, boost::mpl::false_)\n    {\n\tif (r == this->num_rows() && c == this->num_cols())\n\t    return;\n\n\tself temp;\n\tif (keep_data) {\n\t    temp.super::change_dim(this->num_rows(), this->num_cols());\n\t    temp.init();\n\t    temp.memory_base::move_assignment(*this);\n\t}\n\tmemory_base::realloc(r*c);\n\tsuper::change_dim(r, c);\n\tinit();\n\tif (keep_data) {\n\t    if (r > temp.num_rows() || c > temp.num_cols()){\n\t\tset_to_zero(*this);\n#if 0\n\t\tirange rr(0, std::min(r,temp.num_rows())), cr(0, std::min(c,temp.num_cols()));\n\t\t*this[rr][cr]= temp[rr][cr];\n#endif\n\t\tsub_matrix(*this,0,std::min(r,temp.num_rows()),0,std::min(c,temp.num_cols()))\n\t\t    = sub_matrix(temp,0,std::min(r,temp.num_rows()),0,std::min(c,temp.num_cols()));\n\t    } else \n\t\t*this = temp[irange(0, r)][irange(0, c)];\n\t}\n    }\n\n    void change_dim(size_type MTL_DEBUG_ARG(r), size_type MTL_DEBUG_ARG(c), bool, boost::mpl::true_)\n    {\tassert(r == this->num_rows() && c == this->num_cols());    }\n\n public:\n    /// Check whether indices r and c are in range\n    bool check_indices(size_t r, size_t c) const\n    {\treturn r >= this->begin_row() && r < this->end_row() && c >= this->begin_col() && c < this->end_col();    }\n\n    /// Constant access to element\n    const_reference operator() (size_t r, size_t c) const \n    {\n\tMTL_CRASH_IF(is_negative(r) || r >= this->num_rows() || is_negative(c) || c >= this->num_cols(), \n\t\t     \"Index out of range!\");\n        return this->data[indexer(*this, r, c)];\n    }\n\n    /// Mutable access to element\n    value_type& operator() (size_t r, size_t c)\n    {\n\tMTL_CRASH_IF(is_negative(r) || r >= this->num_rows() || is_negative(c) || c >= this->num_cols(), \n\t\t     \"Index out of range!\");\n\treturn this->data[indexer(*this, r, c)]; \n    }    \n\n    // offset regarding c-style indices\n    size_t c_offset(size_t r, size_t c) const\n    {\treturn indexer.offset(ldim, r, c, orientation());    }\n\n    /// Get lower dimension [advanced]\n    size_type get_ldim() const\n    {\treturn ldim;    }\n\n    /// Swap two matrices\n    friend void swap(self& matrix1, self& matrix2)\n    {\n\tswap(static_cast<memory_base&>(matrix1), static_cast<memory_base&>(matrix2));\n\tswap(static_cast<super&>(matrix1), static_cast<super&>(matrix2));\n\tstd::swap(matrix1.ldim, matrix2.ldim);\n    }\n\n    void crop() {} ///< Delete structural zeros; only dummy here\n\n    /// Address of first data entry (mutable); to be used with care. [advanced]\n    value_type* address_data() { return this->data; }\n    /// Address of first data entry (constant); to be used with care. [advanced]\n    const value_type* address_data() const { return this->data; }\n\n    /// Whether data is stored in strides\n    bool has_strided_data() const { return this->category != this->own; }\n    \n  protected:\n    \n    // Set ranges from begin_r to end_r and begin_c to end_c\n    void set_ranges(size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n    {\n\tsuper::set_ranges(begin_r, end_r, begin_c, end_c);\n\tset_nnz();\n    }\n\t\n    // Set ranges to a num_row x num_col matrix, keeps indexing\n    void set_ranges(size_type num_rows, size_type num_cols)\n    {\n\tset_ranges(this->begin_row(), this->begin_row() + num_rows, \n\t\t   this->begin_col(), this->begin_col() + num_cols);\n    }\n    \n  public:\n\n    indexer_type  indexer;\n\n    friend class dense2D_indexer;\n\n#if !defined(_MSC_VER) || _MSC_VER != 1400 // Bug in MSVC 2005\n    template <typename> friend struct sub_matrix_t;\n    template <typename, typename> friend struct mtl::traits::range_generator;\n    template <typename, typename, bool> friend struct mtl::traits::detail::dense2D_iterator_range_generator;\n\n  protected:\n#endif\n\n    // Leading dimension is minor dimension in original matrix \n    // Opposed to other dims doesn't change in sub-matrices\n    size_type     ldim; \n\n}; // dense2D\n\n\n// ================\n// Free functions\n// ================\n\n\n/// Number of rows\ntemplate <typename Value, typename Parameters>\ntypename dense2D<Value, Parameters>::size_type\ninline num_rows(const dense2D<Value, Parameters>& matrix)\n{\n    return matrix.num_rows();\n}\n\n/// Number of columns\ntemplate <typename Value, typename Parameters>\ntypename dense2D<Value, Parameters>::size_type\ninline num_cols(const dense2D<Value, Parameters>& matrix)\n{\n    return matrix.num_cols();\n}\n\n/// Size of the matrix, i.e. the number of row times columns\ntemplate <typename Value, typename Parameters>\ntypename dense2D<Value, Parameters>::size_type\ninline size(const dense2D<Value, Parameters>& matrix)\n{\n    return matrix.num_cols() * matrix.num_rows();\n}\n\n\n}\n\nusing mat::dense2D;\n\n} // namespace mtl::matrix\n\n\nnamespace mtl { namespace traits {\n\n\n    // VC 8.0 finds ambiguity with mtl::tag::dense2D (I wonder why, especially here)\n    using mtl::mat::dense2D;\n\n    // ================\n    // Range generators\n    // For cursors\n    // ================\n\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::all, dense2D<Value, Parameters> >\n      : detail::dense_element_range_generator<dense2D<Value, Parameters>,\n\t\t\t\t\t      dense_el_cursor<Value>, complexity_classes::linear_cached>\n    {};\n\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::nz, dense2D<Value, Parameters> >\n      : detail::dense_element_range_generator<dense2D<Value, Parameters>,\n\t\t\t\t\t      dense_el_cursor<Value>, complexity_classes::linear_cached>\n    {};\n\n    namespace detail \n    {\n\t// complexity of dense row cursor depends on storage scheme\n\t// if orientation is row_major then complexity is cached_linear, otherwise linear\n\ttemplate <typename Orientation> struct dense2D_rc {};\n\ttemplate<> struct dense2D_rc<row_major>\n\t{\n\t    typedef complexity_classes::linear_cached type;\n\t};\n\ttemplate<> struct dense2D_rc<col_major>\n\t{\n\t    typedef complexity_classes::linear type;\n\t};\n\n\t// Complexity of column cursor is of course opposite\n\ttemplate <typename Orientation> struct dense2D_cc\n\t    : dense2D_rc<typename mtl::traits::transposed_orientation<Orientation>::type>\n\t{};\n    }\n\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::row, dense2D<Value, Parameters> >\n\t: detail::all_rows_range_generator<dense2D<Value, Parameters>, \n\t\t\t\t\t   typename detail::dense2D_rc<typename Parameters::orientation>::type>\n    {};\n \n    // For a cursor pointing to some row give the range of elements in this row \n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::nz, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, glas::tag::row, 2> >\n    {\n\ttypedef dense2D<Value, Parameters>                                            matrix;\n\ttypedef typename matrix::size_type                                            size_type;\n\ttypedef detail::sub_matrix_cursor<matrix, glas::tag::row, 2>               cursor;\n\n\t// linear for col_major and linear_cached for row_major\n\ttypedef typename detail::dense2D_rc<typename Parameters::orientation>::type   complexity;\n\tstatic int const                                                              level = 1;\n\n\ttypedef typename boost::mpl::if_<\n\t    boost::is_same<typename Parameters::orientation, row_major>\n\t  , dense_el_cursor<Value>\n\t  , strided_dense_el_cursor<Value>\n\t>::type type;  \n\n      private:\n\n\ttype dispatch(cursor const& c, size_type col, row_major) const\n\t{\n\t    return type(c.ref, c.key, col);\n\t}\n\ttype dispatch(cursor const& c, size_type col, col_major) const\n\t{\n\t    return type(c.ref, c.key, col, c.ref.ldim);\n\t}\n\n      public:\n\n\ttype begin(cursor const& c) const\n\t{\n\t    return dispatch(c, c.ref.begin_col(), typename matrix::orientation());\n\t}\n\ttype end(cursor const& c) const\n\t{\n\t    return dispatch(c, c.ref.end_col(), typename matrix::orientation());\n\t}\t\n\ttype lower_bound(cursor const& c, size_type position) const\n\t{\n\t    return dispatch(c, std::min(c.ref.end_col(), position), typename matrix::orientation());\n\t}\n    };\n\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::all, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, glas::tag::row, 2> >\n        : range_generator<glas::tag::nz, \n\t\t\t  detail::sub_matrix_cursor<dense2D<Value, Parameters>, glas::tag::row, 2> >\n    {};\n\n\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::col, dense2D<Value, Parameters> >\n\t: detail::all_cols_range_generator<dense2D<Value, Parameters>, \n\t\t\t\t\t   typename detail::dense2D_cc<typename Parameters::orientation>::type>\n    {};\n \n    // For a cursor pointing to some row give the range of elements in this row \n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::nz, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, glas::tag::col, 2> >\n    {\n\ttypedef dense2D<Value, Parameters>                                            matrix;\n\ttypedef typename matrix::size_type                                            size_type;\n\ttypedef detail::sub_matrix_cursor<matrix, glas::tag::col, 2>               cursor;\t\n\ttypedef typename detail::dense2D_cc<typename Parameters::orientation>::type   complexity;\n\tstatic int const                                                              level = 1;\n\n\ttypedef typename boost::mpl::if_<\n\t    boost::is_same<typename Parameters::orientation, col_major>\n\t  , dense_el_cursor<Value>\n\t  , strided_dense_el_cursor<Value>\n\t>::type type;  \n\n      private:\n\ttype dispatch(cursor const& c, size_type row, col_major) const\n\t{\n\t    return type(c.ref, row, c.key);\n\t}\n\ttype dispatch(cursor const& c, size_type row, row_major) const\n\t{\n\t    return type(c.ref, row, c.key, c.ref.ldim);\n\t}\n\n      public:\n\ttype begin(cursor const& c) const\n\t{\n\t    return dispatch(c, c.ref.begin_row(), typename matrix::orientation());\n\t}\n\ttype end(cursor const& c) const\n\t{\n\t    return dispatch(c, c.ref.end_row(), typename matrix::orientation());\n\t}\n\ttype lower_bound(cursor const& c, size_type position) const\n\t{\n\t    return dispatch(c, std::min(c.ref.end_row(), position), typename matrix::orientation());\n\t}\t\n    };\n\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::all, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, glas::tag::col, 2> >\n      : public range_generator<glas::tag::nz, \n\t\t\t       detail::sub_matrix_cursor<dense2D<Value, Parameters>, glas::tag::col, 2> >\n    {};\n\n// =============\n// For iterators\n// =============\n\n\n    namespace detail {\n\n        // Traversal along major dimension first and then along minor\n        template <typename OuterTag, typename Orientation>\n        struct major_traversal\n        {\n\t    static const bool value= false;\n        };\n          \n        template <> struct major_traversal<glas::tag::row, row_major>\n        {\n\t    static const bool value= true;\n        };\n        \n        template <> struct major_traversal<glas::tag::col, col_major>\n        {\n\t    static const bool value= true;\n        };\n\n\n        template <typename OuterTag, typename Matrix, bool is_const>\n        struct dense2D_iterator_range_generator\n        {\n\t    typedef Matrix                                                                matrix_type;\n\t    typedef typename matrix_type::size_type                                       size_type;\n\t    typedef typename matrix_type::value_type                                      value_type;\n\t    typedef typename matrix_type::parameters                                      parameters;\n\t    typedef detail::sub_matrix_cursor<matrix_type, OuterTag, 2>                   cursor;\n\n\t    // if traverse first along major dimension then memory access is contiguous (otherwise strided)\n\t    typedef typename boost::mpl::if_<\n\t\tmajor_traversal<OuterTag, typename parameters::orientation> \n\t      , complexity_classes::linear_cached\n\t      , complexity_classes::linear\n\t    >::type                                                                       complexity;\n\t    static int const                                                              level = 1;\n\n\t    // if traverse first along major dimension use pointer otherwise strided iterator\n\t    typedef typename boost::mpl::if_<\n\t\tmajor_traversal<OuterTag, typename parameters::orientation> \n\t      , typename boost::mpl::if_c<\n    \t            is_const \n\t\t  , const value_type*\n    \t          , value_type*\n\t\t>::type\n\t      , typename boost::mpl::if_c<\n    \t            is_const \n\t\t  , strided_dense_el_const_iterator<value_type>\n    \t          , strided_dense_el_iterator<value_type>\n    \t        >::type\n\t    >::type type;  \n\n        private:\n\t    // if traverse first along major dim. then return address as pointer\n\t    type dispatch(cursor const& c, size_type row, size_type col, complexity_classes::linear_cached) const\n\t    {\n\t\tmatrix_type& ma= const_cast<matrix_type&>(c.ref);\n\t\treturn ma.elements() + ma.indexer(ma, row, col); // &ref[row][col];\n\t    }\n\n\t    // otherwise strided \n\t    type dispatch(cursor const& c, size_type row, size_type col, complexity_classes::linear) const\n\t    {\n\t\t// cast const away (is dirty and should be improved later (cursors must distinct constness))\n\t\tmatrix_type& ref= const_cast<matrix_type&>(c.ref);\n\t\treturn type(ref, row, col, ref.ldim);\n\t    }\n\n\t    type begin_dispatch(cursor const& c, glas::tag::row) const\n\t    {\n\t\treturn dispatch(c, c.key, c.ref.begin_col(), complexity());\n\t    }\n\t    \n\t    type end_dispatch(cursor const& c, glas::tag::row) const\n\t    {\n\t\treturn dispatch(c, c.key, c.ref.end_col(), complexity());\n\t    }\n\n\n\t    type begin_dispatch(cursor const& c, glas::tag::col) const\n\t    {\n\t\treturn dispatch(c, c.ref.begin_row(), c.key, complexity());\n\t    }\n\n\t    type end_dispatch(cursor const& c, glas::tag::col) const\n\t    {\n\t\treturn dispatch(c, c.ref.end_row(), c.key, complexity());\n\t    }\n\n        public:\n\n\t    type begin(cursor const& c) const\n\t    {\n\t\treturn begin_dispatch(c, OuterTag());\n\t    }\n\n\t    type end(cursor const& c) const\n\t    {\n\t\treturn end_dispatch(c, OuterTag());\n\t    }\t\n        };\n\n    } // namespace detail\n\n        \n    template <typename Value, typename Parameters, typename OuterTag>\n    struct range_generator<tag::iter::nz, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, OuterTag, 2> >\n      : public detail::dense2D_iterator_range_generator<OuterTag, dense2D<Value, Parameters>, false>\n    {};\n\n    template <typename Value, typename Parameters, typename OuterTag>\n    struct range_generator<tag::iter::all, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, OuterTag, 2> >\n      : public detail::dense2D_iterator_range_generator<OuterTag, dense2D<Value, Parameters>, false>\n    {};\n\n    template <typename Value, typename Parameters, typename OuterTag>\n    struct range_generator<tag::const_iter::nz, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, OuterTag, 2> >\n      : public detail::dense2D_iterator_range_generator<OuterTag, dense2D<Value, Parameters>, true>\n    {};\n\n    template <typename Value, typename Parameters, typename OuterTag>\n    struct range_generator<tag::const_iter::all, \n\t\t\t   detail::sub_matrix_cursor<dense2D<Value, Parameters>, OuterTag, 2> >\n      : public detail::dense2D_iterator_range_generator<OuterTag, dense2D<Value, Parameters>, true>\n    {};\n\n\n}} // namespace mtl::traits\n\nnamespace mtl { namespace mat {\n\n    // ==========\n    // Sub matrix\n    // ==========\n\n    template <typename Value, typename Parameters>\n    struct sub_matrix_t<dense2D<Value, Parameters> >\n    {\n        typedef dense2D<Value, Parameters>      matrix_type;\n\t// copy orientation, ignore index, set dimension to non-fixed and on_stack to false\n\ttypedef parameters<typename Parameters::orientation> para_type; \n\n        typedef dense2D<Value, para_type>       sub_matrix_type;\n        typedef sub_matrix_type const           const_sub_matrix_type;\n        typedef typename matrix_type::size_type size_type;\n        \n        sub_matrix_type operator()(matrix_type& matrix, size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n        {\n\t    return sub_matrix_type(matrix, dense2D_sub_ctor(), begin_r, end_r, begin_c, end_c);\n        }\n\n        const_sub_matrix_type\n        operator()(matrix_type const& matrix, size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n        {\n\t    // To minimize code duplication, we use the non-const version\n\t    sub_matrix_type tmp((*this)(const_cast<matrix_type&>(matrix), begin_r, end_r, begin_c, end_c));\n\t    return tmp;\n        }\t\n    };\n        \n}} // mtl::matrix\n\nnamespace mtl {\n\n    // Enable cloning of dense matrices\n    template <typename Value, typename Parameters>\n    struct is_clonable< mtl::mat::dense2D<Value, Parameters> > : boost::mpl::true_ {};\n        \n} // namespace mtl\n\n\n\nnamespace math {\n\n    // Multiplicative identities of matrices\n    template <typename Value, typename Parameters>\n    struct identity_t< mult<mtl::mat::dense2D<Value, Parameters> >, mtl::mat::dense2D<Value, Parameters> >\n        : public std::binary_function< mult<mtl::mat::dense2D<Value, Parameters> >, \n\t\t\t\t       mtl::mat::dense2D<Value, Parameters>, \n\t\t\t\t       mtl::mat::dense2D<Value, Parameters> >\n    {\n        typedef mtl::mat::dense2D<Value, Parameters>  matrix_type;\n\n        matrix_type operator() (const mult<matrix_type>&, const matrix_type& ref) const\n        {\n\t    matrix_type tmp(ref);\n\t    tmp= one(typename matrix_type::value_type());\n\t    return tmp;\n        }\n    };\n        \n} // namespace math\n\n\n#endif // MTL_DENSE2D_INCLUDE\n\n\n/*\nLimitations:\n- with compile-time constant dimension, submatrices are not supported (would violate self-similarity)\n- Element cursor doesn't work for sub-matrices (not contiguous)\n*/\n", "meta": {"hexsha": "574201f997f1505d94da41c9fb03bf3c9abdce8d", "size": 31091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/matrix/dense2D.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/mtl/matrix/dense2D.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/mtl/matrix/dense2D.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6118918919, "max_line_length": 127, "alphanum_fraction": 0.6643723264, "num_tokens": 7567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.06954174595211299, "lm_q1q2_score": 0.02938171098919833}}
{"text": "/**\n * @file\n * @brief Reads meshes containing second order elements and performs refinement\n * @author Anian Ruoss\n * @date   24.02.2019 18:24:17\n * @copyright MIT License\n */\n\n#include <lf/base/base.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/refinement/mesh_hierarchy.h>\n#include <boost/filesystem.hpp>\n#include <iostream>\n\nusing lf::io::TikzOutputCtrl;\n\nint main() {\n  boost::filesystem::path file_path = __FILE__;\n\n  for (const std::string& mesh_name :\n       {\"square_quads.msh\", \"square_trias.msh\"}) {\n    auto mesh_path = file_path.parent_path() / \"meshes\" / mesh_name;\n\n    // read mesh from file\n    auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n    const lf::io::GmshReader reader(std::move(mesh_factory),\n                                    mesh_path.string());\n\n    // create mesh hierarchy from mesh for refinement\n    lf::refinement::MeshHierarchy multi_mesh(\n        std::const_pointer_cast<lf::mesh::Mesh>(reader.mesh()),\n        std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2));\n\n    int refinement_steps = 2;\n\n    for (int step = 0; step < refinement_steps; ++step) {\n      // refine mesh and store to TikZ\n      multi_mesh.RefineRegular();\n      auto mesh = multi_mesh.getMesh(multi_mesh.NumLevels() - 1);\n      lf::io::writeTikZ(\n          *mesh,\n          mesh_name.substr(0, mesh_name.find_last_of('.')) + \"_\" +\n              std::to_string(step) + \".tex\",\n          TikzOutputCtrl::RenderCells | TikzOutputCtrl::CellNumbering |\n              TikzOutputCtrl::VerticeNumbering | TikzOutputCtrl::NodeNumbering |\n              TikzOutputCtrl::EdgeNumbering);\n    }\n  }\n\n  return 0;\n}", "meta": {"hexsha": "dc410b948d2678c0b2e4fcc11c106148a10c8e0d", "size": 1695, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/refinement/second_order_demo.cc", "max_stars_repo_name": "Pascal-So/lehrfempp", "max_stars_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/refinement/second_order_demo.cc", "max_issues_repo_name": "Pascal-So/lehrfempp", "max_issues_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/refinement/second_order_demo.cc", "max_forks_repo_name": "Pascal-So/lehrfempp", "max_forks_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_forks_repo_licenses": ["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.9811320755, "max_line_length": 80, "alphanum_fraction": 0.6477876106, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.05921025323146657, "lm_q1q2_score": 0.029373841269541137}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2018 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n#include \"SiconosConfig.h\"\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n\n#include \"ioMatrix.hpp\"\n#include \"BlockVector.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n#include \"SiconosVector.hpp\"\n#include \"SimpleMatrix.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n// Useful function (print ...) from boost bindings examples.\n#include \"bindings_utils.hpp\"\n\n#include \"Tools.hpp\"\n\nusing namespace Siconos;\n\n#include <boost/numeric/bindings/blas.hpp>\nnamespace siconosBindings = boost::numeric::bindings::blas;\n\n\n// =================================================\n//                CONSTRUCTORS\n// =================================================\n\nusing std::cout;\nusing std::endl;\n\n\n// Default (protected, used only for derived classes)\nSimpleMatrix::SimpleMatrix(int i): SiconosMatrix(1), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Dense = new DenseMat(ublas::zero_matrix<double>());\n}\n\nSimpleMatrix::SimpleMatrix(): SiconosMatrix(1), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Dense = new DenseMat(ublas::zero_matrix<double>());\n}\n\n// parameters: dimensions and type.\nSimpleMatrix::SimpleMatrix(unsigned int row, unsigned int col, UBLAS_TYPE typ, unsigned int upper, unsigned int lower):\n  SiconosMatrix(1), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  if (typ == DENSE)\n  {\n    mat.Dense = new DenseMat(ublas::zero_matrix<double>(row, col));\n    // _num = 1; default value\n  }\n  else if (typ == TRIANGULAR)\n  {\n    mat.Triang = new TriangMat(ublas::zero_matrix<double>(row, col));\n    _num = 2;\n  }\n  else if (typ == SYMMETRIC)\n  {\n    mat.Sym = new SymMat(ublas::zero_matrix<double>(row, col));\n    _num = 3;\n  }\n  else if (typ == SPARSE)\n  {\n    mat.Sparse = new SparseMat(row, col, upper);\n    _num = 4;\n    zero();\n  }\n  else if (typ == BANDED)\n  {\n    mat.Banded = new BandedMat(row, col, upper, lower);\n    _num = 5;\n    zero();\n  }\n  else if (typ == ZERO)\n  {\n    mat.Zero = new ZeroMat(row, col);\n    _num = 6;\n  }\n  else if (typ == IDENTITY)\n  {\n    mat.Identity = new IdentityMat(row, col);\n    _num = 7;\n  }\n  else\n    SiconosMatrixException::selfThrow(\"SiconosMatrix::constructor(UBLAS_TYPE type, unsigned int row, unsigned int col): invalid type.\");\n}\n\n// parameters: dimensions, input value and type\nSimpleMatrix::SimpleMatrix(unsigned int row, unsigned int col, double inputValue, UBLAS_TYPE typ, unsigned int upper, unsigned int lower):\n  SiconosMatrix(1), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  // This constructor has sense only for dense matrices ...\n  if (typ == DENSE)\n  {\n    mat.Dense = new DenseMat(ublas::scalar_matrix<double>(row, col, inputValue));\n    // _num = 1; default value\n  }\n  else\n    SiconosMatrixException::selfThrow(\"SiconosMatrix::constructor(UBLAS_TYPE type, unsigned int row, unsigned int col, double fillInValue): invalid type.\");\n}\n\n// // parameters: a vector (stl) of double and the type.\n// SimpleMatrix::SimpleMatrix(const std::vector<double>& v, unsigned int row, unsigned int col, UBLAS_TYPE typ, unsigned int lower, unsigned int upper):\n//   SiconosMatrix(1, row, col), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n// {\n//   if( (  (v.size() != row*col) && (typ != SYMMETRIC && typ != BANDED) )\n//       || (v.size() != row*row && typ == SYMMETRIC)\n//       || (typ == BANDED && ( (v.size()) != (unsigned int)(std::max)(row, col)*(lower+1+upper) ) ))\n//     SiconosMatrixException::selfThrow(\"constructor(UBLAS_TYPE, const std::vector<double>, int, int) : invalid vector size\");\n\n//   if(typ == DENSE)\n//     {\n//       mat.Dense = new DenseMat(row,col);\n//       // _num = 1; default value\n//     }\n//   else if(typ == TRIANGULAR)\n//     {\n//       mat.Triang = new TriangMat(row,col);\n//       _num = 2;\n//     }\n//   else if(typ == SYMMETRIC)\n//     {\n//       mat.Sym = new SymMat(row);\n//       _num = 3;\n//     }\n//   else if(typ == SPARSE)\n//     {\n//       SiconosMatrixException::selfThrow(\"SimpleMatrix::constructor(UBLAS_TYPE, const std::vector<double>, int row, int col, int lower, int upper) : warning -- use constructor(const SparseMat &m) or constructor(UBLAS_TYPE, int row, int col) with UBLAS_TYPE = SPARSE\");\n\n//     }\n//   else if(typ == BANDED)\n//     {\n//       mat.Banded = new BandedMat(row, col, lower, upper);\n//       _num = 5;\n//     }\n//   else\n//     SiconosMatrixException::selfThrow(\"constructor(UBLAS_TYPE, const std::vector<double>, int, int) : invalid type of matrix given\");\n\n//   std::copy(v.begin(), v.end(), (vect.Dense)->begin());\n\n\n// }\n\n// Copy constructors\nSimpleMatrix::SimpleMatrix(const SimpleMatrix &smat): SiconosMatrix(smat.num()), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  if (_num == 1)\n  {\n    mat.Dense = new DenseMat(smat.size(0), smat.size(1));\n    noalias(*mat.Dense) = (*smat.dense());\n  }\n  //   mat.Dense = new DenseMat(*smat.dense());\n\n  else if (_num == 2)\n    mat.Triang = new TriangMat(*smat.triang());\n\n  else if (_num == 3)\n\n    mat.Sym = new SymMat(*smat.sym());\n\n  else if (_num == 4)\n    mat.Sparse = new SparseMat(*smat.sparse());\n\n  else if (_num == 5)\n    mat.Banded = new BandedMat(*smat.banded());\n\n  else if (_num == 6)\n    mat.Zero = new ZeroMat(smat.size(0), smat.size(1));\n\n  else// if(_num == 7)\n    mat.Identity = new IdentityMat(smat.size(0), smat.size(1));\n}\n\n/** copy constructor of a block given by the coord = [r0A r1A c0A c1A]\n *  \\param A the matrix for extracting the block\n */\nSimpleMatrix::SimpleMatrix(const SimpleMatrix& A , const Index& coord ):  SiconosMatrix(A.num()), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  if (coord[0]>=coord[1])\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SimpleMatrix(const SimpleMatrix& A , const Index& coord ). Empty row range coord[0]>= coord[1]\");\n  if (coord[2]>=coord[3])\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SimpleMatrix(const SimpleMatrix& A , const Index& coord ). Empty column range coord[2]>= coord[3]\");\n  if (coord[1] > A.size(0) )\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SimpleMatrix(const SimpleMatrix& A , const Index& coord ). row index too large.\");\n  if (coord[3] > A.size(1) )\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::SimpleMatrix(const SimpleMatrix& A , const Index& coord ). column index too large.\");\n\n  if (_num== 1)\n  {\n    ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Dense=new DenseMat(subA);\n  }\n  else if (_num == 2)\n  {\n    ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Triang=new TriangMat(subA);\n  }\n  else if (_num == 3)\n  {\n    ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Sym=new SymMat(subA);\n  }\n  else if (_num == 4)\n  {\n    ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Sparse=new SparseMat(subA);\n  }\n  else if (_num == 5)\n  {\n    ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n    mat.Banded=new BandedMat(subA);\n  }\n  else if (_num == 6)\n  {\n    mat.Zero = new ZeroMat(coord[1]-coord[0], coord[3]-coord[2]);\n  }\n  else// if(_num == 7)\n    mat.Identity = new IdentityMat(coord[1]-coord[0], coord[3]-coord[2] );\n}\n\n\n\n\nSimpleMatrix::SimpleMatrix(const SiconosMatrix &m): SiconosMatrix(m.num()), _isPLUFactorized(), _isQRFactorized(false), _isPLUInversed(false)\n{\n  // _num is set in SiconosMatrix constructor with m.num() ... must be changed if m is Block\n  unsigned int numM = m.num();\n\n\n  _isPLUFactorized= m.isPLUFactorized();\n  _isPLUInversed= m.isPLUInversed();\n\n  if (m.ipiv())\n    _ipiv.reset(new VInt(*(m.ipiv())));\n\n  if (numM == 0) // ie if m is Block, this matrix is set to a dense.\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    _num = 1;\n    // get number of blocks in a row/col of m.\n    mat.Dense = new DenseMat(m.size(0), m.size(1));\n    ConstBlocksIterator1 it;\n    ConstBlocksIterator2 it2;\n    unsigned int posRow = 0;\n    unsigned int posCol = 0;\n\n    for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for (it2 = it.begin(); it2 != it.end(); ++it2)\n      {\n        setBlock(posRow, posCol, **it2);\n        posCol += (*it2)->size(1);\n      }\n      posRow += (*it)->size(0);\n      posCol = 0;\n    }\n  }\n  else if (_num == 1)\n  {\n    mat.Dense = new DenseMat(m.size(0), m.size(1));\n    noalias(*mat.Dense) = (*m.dense());\n  }\n\n  else if (_num == 2)\n    mat.Triang = new TriangMat(*m.triang());\n\n  else if (_num == 3)\n    mat.Sym = new SymMat(*m.sym());\n\n  else if (_num == 4)\n    mat.Sparse = new SparseMat(*m.sparse());\n\n  else if (_num == 5)\n    mat.Banded = new BandedMat(*m.banded());\n\n  else if (_num == 6)\n    mat.Zero = new ZeroMat(m.size(0), m.size(1));\n\n  else // if(_num == 7)\n    mat.Identity = new IdentityMat(m.size(0), m.size(1));\n}\n\nSimpleMatrix::SimpleMatrix(const DenseMat& m): SiconosMatrix(1), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Dense = new DenseMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const TriangMat& m): SiconosMatrix(2), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Triang = new TriangMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const SymMat& m): SiconosMatrix(3), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Sym = new SymMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const SparseMat& m): SiconosMatrix(4), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Sparse = new SparseMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const BandedMat& m): SiconosMatrix(5), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Banded = new BandedMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const ZeroMat& m): SiconosMatrix(6), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Zero = new ZeroMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const IdentityMat& m): SiconosMatrix(7), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Identity = new IdentityMat(m);\n}\n\nSimpleMatrix::SimpleMatrix(const std::string &file, bool ascii): SiconosMatrix(1), _isPLUFactorized(false), _isQRFactorized(false), _isPLUInversed(false)\n{\n  mat.Dense = new DenseMat();\n  if (ascii)\n  {\n    ioMatrix::read(file, \"ascii\", *this);\n  }\n  else\n  {\n    ioMatrix::read(file, \"binary\", *this);\n  }\n}\n\nSimpleMatrix::~SimpleMatrix()\n{\n  if (_num == 1)\n    delete(mat.Dense);\n  else if (_num == 2)\n    delete(mat.Triang);\n  else if (_num == 3)\n    delete(mat.Sym);\n  else if (_num == 4)\n    delete(mat.Sparse);\n  else if (_num == 5)\n    delete(mat.Banded);\n  else if (_num == 6)\n    delete(mat.Zero);\n  else if (_num == 7)\n    delete(mat.Identity);\n}\n\nbool SimpleMatrix::isSymmetric(double tol) const\n{\n  SP::SimpleMatrix  m_trans (new SimpleMatrix(*this));\n  m_trans->trans();\n  double err = (*this-*m_trans).normInf();\n  if ((*m_trans).normInf() > 0.0 )\n  {\n    err /= (*m_trans).normInf();\n  }\n  // std::cout << \"err_rel  =\"<< err <<std::endl;\n  return (err < tol);\n}\n//======================================\n// get Ublas component (dense, sym ...)\n//======================================\n\nconst DenseMat SimpleMatrix::getDense(unsigned int, unsigned int) const\n{\n  if (_num != 1)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::getDense(): the current matrix is not a Dense matrix\");\n\n  return *mat.Dense;\n}\n\nconst TriangMat SimpleMatrix::getTriang(unsigned int, unsigned int) const\n{\n  if (_num != 2)\n    SiconosMatrixException::selfThrow(\"TriangMat SimpleMatrix::getTriang(): the current matrix is not a Triangular matrix\");\n\n  return *mat.Triang;\n}\n\nconst SymMat SimpleMatrix::getSym(unsigned int, unsigned int) const\n{\n  if (_num != 3)\n    SiconosMatrixException::selfThrow(\"SymMat SimpleMatrix::getSym(): the current matrix is not a Symmetric matrix\");\n\n  return *mat.Sym;\n}\n\nconst SparseMat SimpleMatrix::getSparse(unsigned int, unsigned int) const\n{\n  if (_num != 4)\n    SiconosMatrixException::selfThrow(\"SparseMat SimpleMatrix::getSparse(): the current matrix is not a Sparse matrix\");\n\n  return *mat.Sparse;\n}\n\nconst BandedMat SimpleMatrix::getBanded(unsigned int, unsigned int) const\n{\n  if (_num != 5)\n    SiconosMatrixException::selfThrow(\"BandedMat SimpleMatrix::getBanded(): the current matrix is not a Banded matrix\");\n\n  return *mat.Banded;\n}\n\nconst ZeroMat SimpleMatrix::getZero(unsigned int, unsigned int) const\n{\n  if (_num != 6)\n    SiconosMatrixException::selfThrow(\"ZeroMat SimpleMatrix::getZero(): the current matrix is not a Zero matrix\");\n\n  return *mat.Zero;\n}\n\nconst IdentityMat SimpleMatrix::getIdentity(unsigned int, unsigned int) const\n{\n  if (_num != 7)\n    SiconosMatrixException::selfThrow(\"IdentityMat SimpleMatrix::getIdentity(): the current matrix is not a Identity matrix\");\n\n  return *mat.Identity;\n}\n\nDenseMat* SimpleMatrix::dense(unsigned int, unsigned int) const\n{\n  if (_num != 1)\n    SiconosMatrixException::selfThrow(\"DenseMat* SimpleMatrix::dense(): the current matrix is not a Dense matrix\");\n\n  return mat.Dense;\n}\n\nTriangMat* SimpleMatrix::triang(unsigned int, unsigned int) const\n{\n  if (_num != 2)\n    SiconosMatrixException::selfThrow(\"TriangMat* SimpleMatrix::triang(): the current matrix is not a Triangular matrix\");\n\n  return mat.Triang;\n}\n\nSymMat* SimpleMatrix::sym(unsigned int, unsigned int) const\n{\n  if (_num != 3)\n    SiconosMatrixException::selfThrow(\"SymMat* SimpleMatrix::sym(): the current matrix is not a Symmetric matrix\");\n\n  return mat.Sym;\n}\n\nSparseMat* SimpleMatrix::sparse(unsigned int, unsigned int) const\n{\n  if (_num != 4)\n    SiconosMatrixException::selfThrow(\"SparseMat* SimpleMatrix::sparse(): the current matrix is not a Sparse matrix\");\n\n  return mat.Sparse;\n}\n\nBandedMat* SimpleMatrix::banded(unsigned int, unsigned int) const\n{\n  if (_num != 5)\n    SiconosMatrixException::selfThrow(\"BandedMat* SimpleMatrix::banded(): the current matrix is not a Banded matrix\");\n\n  return mat.Banded;\n}\n\nZeroMat* SimpleMatrix::zero_mat(unsigned int, unsigned int) const\n{\n  if (_num != 6)\n    SiconosMatrixException::selfThrow(\"ZeroMat* SimpleMatrix::zero_mat(): the current matrix is not a Zero matrix\");\n\n  return mat.Zero;\n}\n\nIdentityMat* SimpleMatrix::identity(unsigned int, unsigned int) const\n{\n  if (_num != 7)\n    SiconosMatrixException::selfThrow(\"IdentityMat* SimpleMatrix::identity(): the current matrix is not a Identity matrix\");\n\n  return mat.Identity;\n}\n\ndouble* SimpleMatrix::getArray(unsigned int, unsigned int) const\n{\n  if (_num == 4)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::getArray(): not yet implemented for sparse matrix.\");\n\n  if (_num == 1)\n    return (((*mat.Dense).data()).data());\n  else if (_num == 2)\n    return &(((*mat.Triang).data())[0]);\n  else if (_num == 3)\n    return &(((*mat.Sym).data())[0]);\n  else if (_num == 6)\n  {\n    ZeroMat::iterator1 it = (*mat.Zero).begin1();\n    return const_cast<double*>(&(*it));\n  }\n  else if (_num == 7)\n  {\n    IdentityMat::iterator1 it = (*mat.Identity).begin1();\n    return const_cast<double*>(&(*it));\n  }\n  else\n    return &(((*mat.Banded).data())[0]);\n}\n\n// ===========================\n//       fill matrix\n// ===========================\n\nvoid SimpleMatrix::zero()\n{\n  unsigned int size1 = size(0);\n  unsigned int size2 = size(1);\n  if (_num == 1)\n    *mat.Dense = ublas::zero_matrix<double>(size1, size2);\n  else if (_num == 2)\n    *mat.Triang = ublas::zero_matrix<double>(size1, size2);\n\n  else if (_num == 3)\n    *mat.Sym = ublas::zero_matrix<double>(size1, size2);\n\n  else if (_num == 4)\n    *mat.Sparse = ublas::zero_matrix<double>(size1, size2);\n\n  else if (_num == 5)\n    *mat.Banded = ublas::zero_matrix<double>(size1, size2);\n\n  else if (_num == 7)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::zero(): you can not set to zero a matrix of type Identity!.\");\n  resetLU();\n  // if _num == 6: nothing\n}\n\nvoid SimpleMatrix::randomize()\n{\n  if (_num == 1)\n    Siconos::algebra::fill(*mat.Dense);\n  else\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::randomize(): only implemented for dense matrices.\");\n  resetLU();\n}\n\nvoid SimpleMatrix::randomize_sym()\n{\n  if (_num == 1)\n    Siconos::algebra::fill_sym(*mat.Dense);\n  else\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::randomize_sym(): only implemented for dense matrices.\");\n  resetLU();\n}\n\nvoid SimpleMatrix::eye()\n{\n  unsigned int size1 = size(0);\n  unsigned int size2 = size(1);\n  if (_num == 1)\n    *mat.Dense = ublas::identity_matrix<double>(size1, size2);\n\n  else if (_num == 2)\n    *mat.Triang = ublas::identity_matrix<double>(size1, size2);\n\n  else if (_num == 3)\n    *mat.Sym = ublas::identity_matrix<double>(size1, size2);\n\n  else if (_num == 4)\n    *mat.Sparse = ublas::identity_matrix<double>(size1, size2);\n\n  else if (_num == 5)\n    *mat.Banded = ublas::identity_matrix<double>(size1, size2);\n\n  else if (_num == 6)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::eye(): you can not set to identity a matrix of type Zero!.\");\n  resetLU();\n}\n\n\n\nunsigned int SimpleMatrix::size(unsigned int index) const\n{\n  if (_num == 1)\n  {\n    if (index == 0) return (*mat.Dense).size1();\n    else  return (*mat.Dense).size2();\n  }\n  else if (_num == 2)\n  {\n   if (index == 0) return (*mat.Triang).size1();\n   else return (*mat.Triang).size2();\n  }\n  else if (_num == 3)\n  {\n   if (index == 0) return (*mat.Sym).size1();\n   else  return (*mat.Sym).size2();\n  }\n  else if (_num == 4)\n  {\n   if (index == 0) return (*mat.Sparse).size1();\n   else return (*mat.Sparse).size2();\n  }\n  else if (_num == 5)\n  {\n  if (index == 0) return  (*mat.Banded).size1();\n  else  return  (*mat.Banded).size2();\n  }\n  else if (_num == 6)\n  {\n  if (index == 0) return (*mat.Zero).size1();\n  else  return (*mat.Zero).size2();\n  }\n  else if (_num == 7)\n  {\n   if (index == 0) return (*mat.Identity).size1();\n   else  return (*mat.Identity).size2();\n  }\n  else return 0;\n\n\n};\n\n\n//=======================\n// set matrix dimension\n//=======================\n\nvoid SimpleMatrix::resize(unsigned int row, unsigned int col, unsigned int lower, unsigned int upper, bool preserve)\n{\n\n  if (_num == 1)\n  {\n    (*mat.Dense).resize(row, col, preserve);\n  }\n  else if (_num == 2)\n  {\n    (*mat.Triang).resize(row, col, preserve);\n  }\n  else if (_num == 3)\n  {\n    (*mat.Sym).resize(row, col, preserve);\n  }\n  else if (_num == 4)\n  {\n    (*mat.Sparse).resize(row, col, preserve);\n  }\n  else if (_num == 5)\n  {\n    (*mat.Banded).resize(row, col, lower, upper, preserve);\n  }\n  else if (_num == 6)\n  {\n    (*mat.Zero).resize(row, col, preserve);\n  }\n  else if (_num == 7)\n  {\n    (*mat.Identity).resize(row, col, preserve);\n  }\n  resetLU();\n }\n\n\n//=====================\n// screen display\n//=====================\n\nvoid SimpleMatrix::display() const\n{\n  std::cout.setf(std::ios::scientific);\n  std::cout.precision(6);\n  \n  if (size(0) == 0 || size(1) ==0)\n  {\n    std::cout << \"SimpleMatrix::display(): empty matrix\" << std::endl;\n  }\n  std::cout << \"SimpleMatrix storage type - num = \" << _num << \"\\n\";\n  if (_num == 1)\n  {\n    Siconos::algebra::print_m(*mat.Dense);\n    //std::cout << *mat.Dense << std::endl;\n  }\n  else if (_num == 2)\n    std::cout << *mat.Triang << std::endl;\n  else if (_num == 3)\n    std::cout << *mat.Sym << std::endl;\n  else if (_num == 4)\n    std::cout << *mat.Sparse << std::endl;\n  else if (_num == 5)\n    std::cout << *mat.Banded << std::endl;\n  else if (_num == 6)\n    std::cout << *mat.Zero << std::endl;\n  else if (_num == 7)\n    std::cout << *mat.Identity << std::endl;\n}\n\n//=====================\n// convert to a string\n//=====================\n\nstd::string SimpleMatrix::toString() const\n{\n  return ::toString(*this);\n}\n\n//=====================\n// convert to an ostream\n//=====================\n\nstd::ostream& operator<<(std::ostream& os, const SimpleMatrix& sm)\n{\n  if (sm._num == 1)\n    os << *sm.mat.Dense;\n  else if (sm._num == 2)\n    os << *sm.mat.Triang;\n  else if (sm._num == 3)\n    os << *sm.mat.Sym;\n  else if (sm._num == 4)\n    os << *sm.mat.Sparse;\n  else if (sm._num == 5)\n    os << *sm.mat.Banded;\n  else if (sm._num == 6)\n    os << *sm.mat.Zero;\n  else if (sm._num == 7)\n    os << *sm.mat.Identity;\n  return os;\n}\n\nvoid prod(const SiconosMatrix& A, const BlockVector& x, SiconosVector& y, bool init)\n{\n\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n\n  if (init)\n    y.zero();\n  unsigned int startRow = 0;\n  unsigned int startCol = 0;\n  // In private_addprod, the sum of all blocks of x, x[i], is computed: y = Sum_i (subA x[i]), with subA a submatrix of A,\n  // starting from position startRow in rows and startCol in columns.\n  // private_prod takes also into account the fact that each block of x can also be a block.\n  VectorOfVectors::const_iterator it;\n  for (it = x.begin(); it != x.end(); ++it)\n  {\n    private_addprod(A, startRow, startCol, **it, y);\n    startCol += (*it)->size();\n  }\n}\n\nvoid prod(const SiconosMatrix& A, const SiconosVector& x, BlockVector& y, bool init)\n{\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  unsigned int startRow = 0;\n  VectorOfVectors::const_iterator it;\n  // For Each subvector of y, y[i], private_prod computes y[i] = subA x, subA being a submatrix of A corresponding to y[i] position.\n  //       // private_prod takes into account the fact that x and y[i] may be block vectors.\n  for (it = y.begin(); it != y.end(); ++it)\n  {\n    private_prod(A, startRow, x, **it, init);\n    startRow += (*it)->size();\n  }\n\n}\n\nvoid subprod(const SiconosMatrix& A, const BlockVector& x, SiconosVector& y, const Index& coord, bool init)\n{\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  // Number of the subvector of x that handles element at position coord[4]\n  std::size_t firstBlockNum = x.getNumVectorAtPos(coord[4]);\n  // Number of the subvector of x that handles element at position coord[5]\n  unsigned int lastBlockNum = x.getNumVectorAtPos(coord[5]);\n  Index subCoord = coord;\n  SPC::SiconosVector  tmp = x[firstBlockNum];\n  std::size_t subSize =  tmp->size(); // Size of the sub-vector\n  const SP::Index xTab = x.tabIndex();\n  if (firstBlockNum != 0)\n  {\n    subCoord[4] -= (*xTab)[firstBlockNum - 1];\n    subCoord[5] =  std::min(coord[5] - (*xTab)[firstBlockNum - 1], subSize);\n  }\n  else\n    subCoord[5] =  std::min(coord[5], subSize);\n\n  if (firstBlockNum == lastBlockNum)\n  {\n    subprod(A, *tmp, y, subCoord, init);\n  }\n  else\n  {\n    unsigned int xPos = 0 ; // Position in x of the current sub-vector of x\n    bool firstLoop = true;\n    subCoord[3] = coord[2] + subCoord[5] - subCoord[4];\n    for (VectorOfVectors::const_iterator it = x.begin(); it != x.end(); ++it)\n    {\n      if ((*it)->num() == 0)\n        SiconosMatrixException::selfThrow(\"subprod(A,x,y) error: not yet implemented for x block of blocks ...\");\n      if (xPos >= firstBlockNum && xPos <= lastBlockNum)\n      {\n        tmp = x[xPos];\n        if (firstLoop)\n        {\n          subprod(A, *tmp, y, subCoord, init);\n          firstLoop = false;\n        }\n        else\n        {\n          subCoord[2] += subCoord[5] - subCoord[4]; // !! old values for 4 and 5\n          subSize = tmp->size();\n          subCoord[4] = 0;\n          subCoord[5] = std::min(coord[5] - (*xTab)[xPos - 1], subSize);\n          subCoord[3] = subCoord[2] + subCoord[5] - subCoord[4];\n          subprod(A, *tmp, y, subCoord, false);\n        }\n      }\n      xPos++;\n    }\n  }\n}\n\nvoid prod(const SiconosVector& x, const SiconosMatrix& A, BlockVector& y, bool init)\n{\n\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  unsigned int startRow = 0;\n  VectorOfVectors::const_iterator it;\n  // For Each subvector of y, y[i], private_prod computes y[i] = subA x, subA being a submatrix of A corresponding to y[i] position.\n  // private_prod takes into account the fact that x and y[i] may be block vectors.\n  for (it = y.begin(); it != y.end(); ++it)\n  {\n    private_prod(createSPtrConstSiconosVector(x), createSPtrConstSiconosMatrix(A), startRow, *it, init);\n    startRow += (*it)->size();\n  }\n}\n\nvoid private_addprod(const SiconosMatrix& A, unsigned startRow, unsigned int startCol, const SiconosVector& x, SiconosVector& y)\n{\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n  assert(!A.isBlock() && \"private_addprod(A,start,x,y) error: not yet implemented for block matrix.\");\n\n\n  // we take a submatrix subA of A, starting from row startRow to row (startRow+sizeY) and between columns startCol and (startCol+sizeX).\n  // Then computation of y = subA*x + y.\n  unsigned int numA = A.num();\n  unsigned int numY = y.num();\n  unsigned int numX = x.num();\n  unsigned int sizeX = x.size();\n  unsigned int sizeY = y.size();\n\n  assert(numX == numY && \"private_addprod(A,start,x,y) error: not yet implemented for x and y of different types.\");\n\n  if (numY == 1 && numX == 1)\n  {\n\n    assert(y.dense() != x.dense());\n\n    if (numA == 1)\n      noalias(*y.dense()) += prod(ublas::subrange(*A.dense(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else if (numA == 2)\n      noalias(*y.dense()) += prod(ublas::subrange(*A.triang(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else if (numA == 3)\n      noalias(*y.dense()) += prod(ublas::subrange(*A.sym(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else if (numA == 4)\n      noalias(*y.dense()) += prod(ublas::subrange(*A.sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else //if(numA==5)\n      noalias(*y.dense()) += prod(ublas::subrange(*A.banded(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n  }\n  else // x and y sparse\n  {\n    if (numA == 4)\n      *y.sparse() += prod(ublas::subrange(*A.sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.sparse());\n    else\n      SiconosMatrixException::selfThrow(\"private_addprod(A,start,x,y) error: not yet implemented for x, y  sparse and A not sparse.\");\n  }\n}\n\nvoid private_addprod(const SiconosMatrix& A, unsigned int startRow, unsigned int startCol, const BlockVector& x, SiconosVector& y)\n{\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  assert(!A.isBlock() && \"private_addprod(A,start,x,y) error: not yet implemented for block matrix.\");\n\n  VectorOfVectors::const_iterator it;\n  unsigned int startColBis = startCol;\n  for (it = x.begin(); it != x.end(); ++it)\n  {\n    private_addprod(A, startRow, startColBis, **it, y);\n    startColBis += (*it)->size();\n  }\n\n}\n\n// x block, y siconos\nvoid private_prod(const SiconosMatrix& A, unsigned int startRow, const BlockVector& x, SiconosVector& y, bool init)\n{\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  // Computes y = subA *x (or += if init = false), subA being a sub-matrix of A, between el. of index (row) startRow and startRow + sizeY\n\n  if (init) // y = subA * x , else y += subA * x\n    y.zero();\n  private_addprod(A, startRow, 0, x, y);\n}\n\n// x and y blocks\nvoid private_prod(SPC::SiconosMatrix A, const unsigned int startRow, SPC::BlockVector x, SP::BlockVector y, bool init)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  unsigned int row = startRow;\n  VectorOfVectors::const_iterator it;\n  for (it = y->begin(); it != y->end(); ++it)\n  {\n    private_prod(*A, row, *x, **it, init);\n    row += (*it)->size();\n  }\n}\n\n// x block, y siconos\nvoid private_prod(const SiconosMatrix& A, unsigned int startRow, const SiconosVector& x, SiconosVector& y, bool init)\n{\n  assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  // Computes y = subA *x (or += if init = false), subA being a sub-matrix of A, between el. of index (row) startRow and startRow + sizeY\n\n  if (init) // y = subA * x , else y += subA * x\n    y.zero();\n  private_addprod(A, startRow, 0, x, y);\n}\n\n// x and y blocks\nvoid private_prod(SPC::SiconosMatrix A, const unsigned int startRow, SPC::SiconosVector x, SP::BlockVector y, bool init)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  unsigned int row = startRow;\n  VectorOfVectors::const_iterator it;\n  for (it = y->begin(); it != y->end(); ++it)\n  {\n    private_prod(*A, row, *x, **it, init);\n    row += (*it)->size();\n  }\n}\n// With trans(A) ...\nvoid private_addprod(SPC::SiconosVector x, SPC::SiconosMatrix A, unsigned int startRow, unsigned int startCol, SP::SiconosVector y)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  if (A->isBlock())\n    SiconosMatrixException::selfThrow(\"private_addprod(x,A,start,y) error: not yet implemented for block matrix.\");\n\n  // we take a submatrix subA of A, starting from row startRow to row (startRow+sizeY) and between columns startCol and (startCol+sizeX).\n  // Then computation of y = subA*x + y.\n  unsigned int numA = A->num();\n  unsigned int numY = y->num();\n  unsigned int numX = x->num();\n  unsigned int sizeX = x->size();\n  unsigned int sizeY = y->size();\n\n  if (numX != numY)\n    SiconosMatrixException::selfThrow(\"private_addprod(x,A,start,y) error: not yet implemented for x and y of different types.\");\n\n  if (numY == 1 && numX == 1)\n  {\n\n    assert(y->dense() != x->dense());\n\n    if (numA == 1)\n      noalias(*y->dense()) += prod(ublas::subrange(trans(*A->dense()), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else if (numA == 2)\n      noalias(*y->dense()) += prod(ublas::subrange(trans(*A->triang()), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else if (numA == 3)\n      noalias(*y->dense()) += prod(ublas::subrange(trans(*A->sym()), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else if (numA == 4)\n      noalias(*y->dense()) += prod(ublas::subrange(trans(*A->sparse()), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else //if(numA==5)\n      noalias(*y->dense()) += prod(ublas::subrange(trans(*A->banded()), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n  }\n  else // x and y sparse\n  {\n    if (numA == 4)\n      *y->sparse() += prod(ublas::subrange(trans(*A->sparse()), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->sparse());\n    else\n      SiconosMatrixException::selfThrow(\"private_addprod(x,A,start,y) error: not yet implemented for x, y  sparse and A not sparse.\");\n  }\n}\n\nvoid private_addprod(SPC::BlockVector x, SPC::SiconosMatrix A, unsigned int startRow, unsigned int startCol, SP::SiconosVector y)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  VectorOfVectors::const_iterator it;\n  unsigned int startColBis = startCol;\n  for (it = x->begin(); it != x->end(); ++it)\n  {\n    private_addprod((*it), A, startRow, startColBis, y);\n    startColBis += (*it)->size();\n  }\n\n}\n\nvoid private_prod(SPC::SiconosVector x, SPC::SiconosMatrix A, unsigned int startCol, SP::SiconosVector  y, bool init)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  // Computes y = subA *x (or += if init = false), subA being a sub-matrix of trans(A), between el. of A of index (col) startCol and startCol + sizeY\n  if (init) // y = subA * x , else y += subA * x\n    y->zero();\n  private_addprod(x, A, startCol, 0 , y);\n\n}\n\nvoid private_prod(SPC::SiconosVector x, SPC::SiconosMatrix A, unsigned int startCol, SP::BlockVector  y, bool init)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  unsigned int col = startCol;\n  VectorOfVectors::const_iterator it;\n  for (it = y->begin(); it != y->end(); ++it)\n  {\n    private_prod(x, A, col, *it, init);\n    col += (*it)->size();\n  }\n}\n\nvoid private_prod(SPC::BlockVector x, SPC::SiconosMatrix A, unsigned int startCol, SP::SiconosVector  y, bool init)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  // Computes y = subA *x (or += if init = false), subA being a sub-matrix of trans(A), between el. of A of index (col) startCol and startCol + sizeY\n  if (init) // y = subA * x , else y += subA * x\n    y->zero();\n  private_addprod(x, A, startCol, 0 , y);\n\n}\n\nvoid private_prod(SPC::BlockVector x, SPC::SiconosMatrix A, unsigned int startCol, SP::BlockVector  y, bool init)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  unsigned int col = startCol;\n  VectorOfVectors::const_iterator it;\n  for (it = y->begin(); it != y->end(); ++it)\n  {\n    private_prod(x, A, col, *it, init);\n    col += (*it)->size();\n  }\n}\n\nvoid private_addprod(double a, SPC::SiconosMatrix A, unsigned int startRow, unsigned int startCol, SPC::SiconosVector x, SP::SiconosVector y)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  if (A->isBlock())\n    SiconosMatrixException::selfThrow(\"private_addprod(A,start,x,y) error: not yet implemented for block matrix.\");\n\n  // we take a submatrix subA of A, starting from row startRow to row (startRow+sizeY) and between columns startCol and (startCol+sizeX).\n  // Then computation of y = subA*x + y.\n  unsigned int numA = A->num();\n  unsigned int numY = y->num();\n  unsigned int numX = x->num();\n  unsigned int sizeX = x->size();\n  unsigned int sizeY = y->size();\n\n  if (numX != numY)\n    SiconosMatrixException::selfThrow(\"private_addprod(A,start,x,y) error: not yet implemented for x and y of different types.\");\n\n  if (numY == 1 && numX == 1)\n  {\n\n    assert(y->dense() != x->dense());\n\n    if (numA == 1)\n      noalias(*y->dense()) += a * prod(ublas::subrange(*A->dense(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else if (numA == 2)\n      noalias(*y->dense()) += a * prod(ublas::subrange(*A->triang(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else if (numA == 3)\n      noalias(*y->dense()) += a * prod(ublas::subrange(*A->sym(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else if (numA == 4)\n      noalias(*y->dense()) += a * prod(ublas::subrange(*A->sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n    else //if(numA==5)\n      noalias(*y->dense()) += a * prod(ublas::subrange(*A->banded(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->dense());\n  }\n  else // x and y sparse\n  {\n    if (numA == 4)\n      *y->sparse() += a * prod(ublas::subrange(*A->sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x->sparse());\n    else\n      SiconosMatrixException::selfThrow(\"private_addprod(A,start,x,y) error: not yet implemented for x, y  sparse and A not sparse.\");\n  }\n\n}\n\nvoid private_prod(double a, SPC::SiconosMatrix A, unsigned int startRow, SPC::SiconosVector x, SP::SiconosVector  y, bool init)\n{\n  assert(!(A->isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n  // Computes y = subA *x (or += if init = false), subA being a sub-matrix of A, between el. of index (row) startRow and startRow + sizeY\n\n  if (init) // y = subA * x , else y += subA * x\n    y->zero();\n  private_addprod(a, A, startRow, 0, x, y);\n\n}\n\nunsigned SimpleMatrix::copyData(double* data) const\n{\n  assert((_num == 1) && \"SiconosMatrix::copyData : forbidden: the current matrix is not dense.\");\n\n  unsigned size = mat.Dense->size1() * mat.Dense->size2();\n  siconosBindings::detail::copy(size, getArray(), 1, data, 1);\n  return size;\n}\n", "meta": {"hexsha": "05b6c492fc14207fb4b6def43f27653d72807fec", "size": 36467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrix.cpp", "max_stars_repo_name": "fperignon/siconos", "max_stars_repo_head_hexsha": "dd9070b5934c5c13accce38eb79cdb4a1d18f6e6", "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/SimpleMatrix.cpp", "max_issues_repo_name": "fperignon/siconos", "max_issues_repo_head_hexsha": "dd9070b5934c5c13accce38eb79cdb4a1d18f6e6", "max_issues_repo_licenses": ["Apache-2.0"], "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/SimpleMatrix.cpp", "max_forks_repo_name": "fperignon/siconos", "max_forks_repo_head_hexsha": "dd9070b5934c5c13accce38eb79cdb4a1d18f6e6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "avg_line_length": 32.2431476569, "max_line_length": 270, "alphanum_fraction": 0.6401129789, "num_tokens": 11048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.05921024991122573, "lm_q1q2_score": 0.02937383962239015}}
{"text": "#pragma once\n#include <memory>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n\n#include \"operators.hpp\"\n\nnamespace yavque\n{\nclass Variable;\n\nclass Circuit\n{\nprivate:\n\tuint32_t dim_;\n\n\t// Operators\n\tstd::vector<std::unique_ptr<Operator>> ops_;\n\n\t// States evaluated from the left\n\tmutable std::vector<std::shared_ptr<const Eigen::VectorXcd>> states_from_left_ = {};\n\tmutable uint32_t states_updated_to_ = 0;\n\n\tvoid add_op_right(std::unique_ptr<Operator> op) { ops_.emplace_back(std::move(op)); }\n\n\tvoid add_op_left(std::unique_ptr<Operator> op)\n\t{\n\t\tstates_updated_to_ = 0;\n\t\tops_.emplace(ops_.begin(), std::move(op));\n\t}\n\nprotected:\n\ttemplate<typename ConstIterator>\n\tCircuit(uint32_t dim, const ConstIterator& begin, const ConstIterator& end)\n\t\t: dim_{dim}\n\t{\n\t\t// check all ops has the same dim\n\t\tfor(auto iter = begin; iter != end; ++iter)\n\t\t{\n\t\t\tops_.push_back((*iter)->clone());\n\t\t}\n\t}\n\npublic:\n\texplicit Circuit(uint32_t dim) : dim_{dim} { }\n\n\tCircuit(const Circuit& rhs); // Defined in cpp\n\tCircuit(Circuit&& rhs) = default;\n\n\tCircuit& operator=(const Circuit& rhs); // Defined in cpp\n\tCircuit& operator=(Circuit&& rhs) = default;\n\n\t~Circuit() = default;\n\n\tuint32_t get_dim() const { return dim_; }\n\n\tbool is_evaluated() const { return (states_updated_to_ == ops_.size() + 1); }\n\n\t// evaluate\n\tvoid evaluate() const\n\t{\n\t\t// Initial state hasn't been set\n\t\tif(states_updated_to_ == 0)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t// All states are evaluated\n\t\tif(states_updated_to_ == ops_.size() + 1)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tfor(auto d = states_from_left_.size() - 1; d < ops_.size(); ++d)\n\t\t{\n\t\t\tstates_from_left_.emplace_back(std::make_shared<Eigen::VectorXcd>(\n\t\t\t\tops_[d]->apply_right(*states_from_left_[d])));\n\t\t}\n\t\tstates_updated_to_ = ops_.size() + 1;\n\t}\n\n\tvoid clear_evaluated()\n\t{\n\t\tstates_updated_to_ = 1;\n\t\tstates_from_left_.resize(1);\n\t}\n\n\tstd::size_t num_operators() const { return ops_.size(); }\n\n\tconst std::unique_ptr<Operator>& operator_at(std::size_t idx) const\n\t{\n\t\treturn ops_[idx];\n\t}\n\n\ttemplate<typename T, typename... Args> void add_op_right(Args&&... args)\n\t{\n\t\tstatic_assert(std::is_convertible_v<T*, Operator*>,\n\t\t              \"T must be a subclass of yavque::Operator.\");\n\t\tops_.emplace_back(std::make_unique<T>(std::forward<Args>(args)...));\n\t}\n\n\ttemplate<typename T, typename... Args> void add_op_left(Args&&... args)\n\t{\n\t\tstatic_assert(std::is_convertible_v<T*, Operator*>,\n\t\t              \"T must be a subclass of yavque::Operator.\");\n\t\tstates_updated_to_ = 0;\n\t\tops_.emplace(ops_.begin(), std::make_unique<T>(std::forward<Args>(args)...));\n\t}\n\n\t/**\n\t * evaluate |st> - C\n\t * When C = U_N \\cdots U_1, it computes U_N \\cdots U_1 | st \\rangle\n\t * */\n\tvoid set_input(const Eigen::VectorXcd& st)\n\t{\n\t\tstates_updated_to_ = 1;\n\t\tstates_from_left_.clear();\n\t\tstates_from_left_.push_back(std::make_shared<Eigen::VectorXcd>(st));\n\t}\n\n\t/**\n\t * subcircuit from 0 to d [0,d)\n\t */\n\tCircuit to(uint32_t d) const\n\t{\n\t\tCircuit circ(dim_, ops_.begin(), ops_.begin() + d);\n\t\tif(states_updated_to_ != 0)\n\t\t{\n\t\t\tcirc.states_from_left_ = std::vector<std::shared_ptr<const Eigen::VectorXcd>>(\n\t\t\t\tstates_from_left_.begin(),\n\t\t\t\tstates_from_left_.begin() + std::min(d + 1, states_updated_to_));\n\t\t\tcirc.states_updated_to_ = std::min(d + 1, states_updated_to_);\n\t\t}\n\t\treturn circ;\n\t}\n\n\t/**\n\t * subcircuit from d to end [d,end)\n\t */\n\tCircuit from(uint32_t d) const\n\t{\n\t\tCircuit circ(dim_, ops_.begin() + d, ops_.end());\n\t\tif(states_updated_to_ > d)\n\t\t{\n\t\t\tcirc.states_from_left_ = std::vector<std::shared_ptr<const Eigen::VectorXcd>>(\n\t\t\t\tstates_from_left_.begin() + d,\n\t\t\t\tstates_from_left_.begin() + states_updated_to_);\n\t\t\tcirc.states_updated_to_ = states_updated_to_ - d;\n\t\t}\n\n\t\treturn circ;\n\t}\n\n\tCircuit& operator|=(const Circuit& b)\n\t{\n\t\tusing std::begin;\n\t\tusing std::end;\n\t\tassert(dim_ == b.dim_);\n\t\tfor(const auto& op : b.ops_)\n\t\t{\n\t\t\tops_.push_back(op->clone());\n\t\t}\n\t\treturn *this;\n\t}\n\n\tCircuit& operator|=(Circuit&& b)\n\t{\n\t\tusing std::begin;\n\t\tusing std::end;\n\t\tassert(dim_ == b.dim_);\n\t\tfor(auto&& op : b.ops_)\n\t\t{\n\t\t\tops_.emplace_back(std::move(op));\n\t\t}\n\t\tb.states_updated_to_ = 0;\n\t\tb.states_from_left_.resize(0);\n\t\tb.ops_.resize(0);\n\t\treturn *this;\n\t}\n\n\tCircuit dagger() const\n\t{\n\t\tCircuit res(dim_, ops_.crbegin(), ops_.crend());\n\t\tfor(std::size_t idx = 0; idx < ops_.size(); ++idx)\n\t\t{\n\t\t\tres.ops_[idx]->dagger_in_place();\n\t\t}\n\t\treturn res;\n\t}\n\n\tstd::vector<Variable> variables() const;\n\n\tvoid derivs() const;\n\n\tstd::shared_ptr<const Eigen::VectorXcd> state_at(uint32_t idx) const\n\t{\n\t\t// May throw exception instead\n\t\tif(idx > ops_.size())\n\t\t{\n\t\t\treturn nullptr;\n\t\t}\n\n\t\t// If not all stastes are evaluated\n\t\tif(idx > states_updated_to_)\n\t\t{\n\t\t\tevaluate();\n\t\t}\n\n\t\treturn states_from_left_[idx];\n\t}\n\n\tstd::shared_ptr<const Eigen::VectorXcd> output() const\n\t{\n\t\tif(!is_evaluated())\n\t\t{\n\t\t\tevaluate();\n\t\t}\n\t\treturn states_from_left_.back();\n\t}\n\n\t[[nodiscard]] std::string desc() const\n\t{\n\t\t// change to format in C++20\n\t\tstd::ostringstream ss;\n\t\tfor(uint32_t d = 0; d < ops_.size(); ++d)\n\t\t{\n\t\t\tss << \"layer\" << d << \": [\" << ops_[d]->desc() << \"]\" << std::endl;\n\t\t}\n\t\treturn ss.str();\n\t}\n};\n\nCircuit operator|(Circuit a, const Circuit& b);\nCircuit operator|(Circuit a, Circuit&& b);\n\n} // namespace yavque\n", "meta": {"hexsha": "950d8b6f2def0b5fa3c8aa373e90073acbd47214", "size": 5260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Circuit.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/yavque/Circuit.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/yavque/Circuit.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9166666667, "max_line_length": 86, "alphanum_fraction": 0.6570342205, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05834584552384339, "lm_q1q2_score": 0.029172922761921696}}
{"text": "// Filename: CirculationModel_aorta.cpp\n// Created on 20 Aug 2007 by Boyce Griffith\n\n// Modified 2019, Alexander D. Kaiser\n\n#include \"CirculationModel_aorta.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_aorta::CirculationModel_aorta(Pointer<Database> input_db, \n                                               const fourier_series_data *fourier_ventricle, \n                                               string ventricle_vertices_file_name,\n                                               string aorta_vertices_file_name,\n                                               const double  cycle_duration,\n                                               const double  t_offset_bcs_unscaled, \n                                               const double  initial_time, \n                                               double P_initial_aorta,\n                                               bool rcr_bcs_on,\n                                               bool P_initial_aorta_equal_to_ventricle,\n                                               double rcr_on_time)\n    : \n      d_object_name(\"circ_model_aorta\"),  // constant name here  \n      d_registered_for_restart(true),      // always true\n      d_fourier_ventricle(fourier_ventricle), \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_ventricle(0.0), \n      d_Q_aorta(0.0),\n      d_time(initial_time), \n      d_aorta_P_Wk(P_initial_aorta),\n      d_p_extender_mean(0.0),\n      d_p_extender_point(0.0),\n      d_area_ventricle(0.0),\n      d_area_aorta(0.0),\n      d_area_initialized(false), \n      d_rcr_bcs_on(rcr_bcs_on), \n      d_P_initial_aorta_equal_to_ventricle(P_initial_aorta_equal_to_ventricle), \n      d_rcr_on_time(rcr_on_time)\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_aorta_R_proximal = input_db->getDouble(\"R_proximal\");\n            d_aorta_R_distal   = input_db->getDouble(\"R_distal\");\n            d_aorta_C          = input_db->getDouble(\"C\");\n\n            std::cout << \"input db got values:\\n\";\n            std::cout << \"input db got values R_proximal = \" << d_aorta_R_proximal << \"\\tR_distal = \" << d_aorta_R_distal << \"\\tC = \" << d_aorta_C << \"\\n\";   \n        }\n        else {\n            TBOX_ERROR(\"Must provide valid input_db\");\n        }\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 ventricle_file(ventricle_vertices_file_name.c_str(), ios::in);\n\n    if(!ventricle_file){\n        TBOX_ERROR(\"Aorta file not found\\n\"); \n    }\n\n    ventricle_file >> d_n_pts_ventricle; \n    \n    d_ventricle_points_idx1 = new double[d_n_pts_ventricle]; \n    d_ventricle_points_idx2 = new double[d_n_pts_ventricle]; \n\n    for (int i=0; i<d_n_pts_ventricle; i++){\n        ventricle_file >> x; \n        ventricle_file >> d_ventricle_points_idx1[i]; \n        ventricle_file >> d_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 ventricle file close\\n\"; \n    ventricle_file.close(); \n    // hardcode to top \n    d_ventricle_axis = 0; \n    d_ventricle_side = 1; \n\n    // read vertices from file \n    ifstream aorta_file(aorta_vertices_file_name.c_str(), ios::in);\n\n    if(!aorta_file){\n        TBOX_ERROR(\"Aorta file not found\\n\"); \n    }\n\n    aorta_file >> d_n_pts_aorta; \n    \n    d_aorta_points_idx1 = new double[d_n_pts_aorta]; \n    d_aorta_points_idx2 = new double[d_n_pts_aorta]; \n\n    for (int i=0; i<d_n_pts_aorta; i++){\n        aorta_file >> d_aorta_points_idx1[i]; \n        aorta_file >> d_aorta_points_idx2[i]; \n        aorta_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 aorta file close\\n\"; \n    aorta_file.close(); \n    d_aorta_axis = 2; \n    d_aorta_side = 1; \n\n    if (!from_restart){\n        if (d_P_initial_aorta_equal_to_ventricle){\n            d_aorta_P = MMHG_TO_CGS * this->d_fourier_ventricle->values[0];\n        }\n        else{\n            d_aorta_P = P_initial_aorta; \n        }\n    }\n\n    pout << \"passed contstructor\\n\"; \n\n    pout << \"initial aorta pressure = \" << P_initial_aorta << \", P_wk = \" << d_aorta_P << \"\\n\"; \n\n    return;\n} // CirculationModel\n\nCirculationModel_aorta::~CirculationModel_aorta()\n{\n    return;\n} // ~CirculationModel_aorta\n\n\nvoid CirculationModel_aorta::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_ventricle_local = 0.0; \n    double Q_aorta_local = 0.0; \n\n    double area_ventricle_local = 0.0; \n    double area_aorta_local = 0.0; \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_ventricle  = this->point_in_ventricle(X_in_plane_1, X_in_plane_2, axis, side);\n                                const int in_aorta      = this->point_in_aorta    (X_in_plane_1, X_in_plane_2, axis, side);\n\n                                if (in_ventricle && in_aorta){\n                                    TBOX_ERROR(\"Position is within two inlets and outlets, should be impossible\\n\"); \n                                }\n\n                                if (in_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_ventricle_local += (*U_data)(i_s)* n[axis] * dA;\n\n                                        if (!d_area_initialized){\n                                            area_ventricle_local += dA;\n                                        }\n\n                                    }\n                                }\n\n                                if (in_aorta)\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_aorta_local += (*U_data)(i_s) * n[axis] * dA;\n\n                                        if (!d_area_initialized){\n                                            area_aorta_local += dA;\n                                        }\n\n                                    }\n                                }\n\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    d_Q_ventricle = SAMRAI_MPI::sumReduction(Q_ventricle_local);\n    d_Q_aorta        = SAMRAI_MPI::sumReduction(Q_aorta_local);\n\n    if (!d_area_initialized){\n        d_area_ventricle = SAMRAI_MPI::sumReduction(area_ventricle_local);\n        d_area_aorta        = SAMRAI_MPI::sumReduction(area_aorta_local);  \n        d_area_initialized = true;       \n    }\n\n    if (d_rcr_bcs_on){\n        // The downstream pressure is determined by a three-element Windkessel model.\n\n        if ((d_P_initial_aorta_equal_to_ventricle) && (d_time < d_rcr_on_time)){\n            // linear interpolation \n            d_aorta_P = (1 - d_time/d_rcr_on_time) * MMHG_TO_CGS * this->d_fourier_ventricle->values[0] + \n                        (    d_time/d_rcr_on_time) * d_aorta_P_Wk; // wk pressure is the end pressure for the interpolation\n        }\n        else{\n            d_aorta_P_Wk = ((d_aorta_C / dt) * d_aorta_P_Wk + d_Q_aorta) / (d_aorta_C / dt + 1.0 / d_aorta_R_distal);        \n            d_aorta_P = d_aorta_P_Wk + d_aorta_R_proximal * d_Q_aorta;\n        }\n    }\n\n    // print_summary();\n\n    // bool debug_out_areas = false; \n    // if (debug_out_areas){\n    //     pout << \"d_area_ventricle = \" << d_area_ventricle << \"\\n\"; \n    //     pout << \"d_area_aorta = \" << d_area_aorta << \"\\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_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_ventricle->dt));\n    \n    // // take periodic reduction\n    d_current_idx_series = k % (d_fourier_ventricle->N_times);\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_aorta::set_Q_valve(double Q_valve){\n    d_Q_valve = Q_valve; \n}\n\nvoid CirculationModel_aorta::set_extender_pressures(double p_extender_mean, double p_extender_point){\n    d_p_extender_mean  = p_extender_mean; \n    d_p_extender_point = p_extender_point;\n}\n\n\n\nvoid\nCirculationModel_aorta::putToDatabase(Pointer<Database> db)\n{\n\n    db->putInteger(\"d_current_idx_series\", d_current_idx_series); \n    db->putDouble(\"d_Q_ventricle\", d_Q_ventricle); \n    db->putDouble(\"d_Q_aorta\", d_Q_aorta);\n    db->putDouble(\"d_Q_valve\", d_Q_valve);\n    db->putDouble(\"d_aorta_P\", d_aorta_P);\n    db->putDouble(\"d_aorta_P_Wk\", d_aorta_P_Wk);\n    db->putDouble(\"d_p_extender_mean\", d_p_extender_mean);\n    db->putDouble(\"d_p_extender_point\", d_p_extender_point);\n    db->putDouble(\"d_time\", d_time); \n    db->putBool(\"d_rcr_bcs_on\", d_rcr_bcs_on); \n    return; \n} // putToDatabase\n\nvoid CirculationModel_aorta::print_summary(){\n\n    double P_ventricle = d_fourier_ventricle->values[d_current_idx_series]; \n    double P_aorta = d_aorta_P / MMHG_TO_CGS;\n\n    if (!d_rcr_bcs_on){\n        TBOX_ERROR(\"Not implemented\\n\"); \n        // P_aorta        = d_fourier_aorta->values[d_current_idx_series];\n    }\n\n    pout << \"rcr_bcs_on = \" << d_rcr_bcs_on << \"\\n\"; \n    pout << \"% time \\t       P_ventricle (mmHg)\\t   P_aorta (mmHg)\\t  Q_ventricle (ml/s)\\t    d_Q_aorta (ml/s)\\t  d_Q_valve (ml/s)\\t  Q_current_idx_series \\t idx\" ;\n    pout << \"\\t aorta_P_Wk \\t p_extender_mean \\t p_extender_point \"; \n    pout << \"\\n\";\n    pout << d_time << \" \" << P_ventricle <<  \" \" << P_aorta << \" \" << d_Q_ventricle << \" \" << d_Q_aorta << \" \" << d_Q_valve << \" \" << d_current_idx_series; \n    pout  << \" \" << d_aorta_P_Wk << \" \" << d_p_extender_mean/MMHG_TO_CGS << \" \" << d_p_extender_point/MMHG_TO_CGS; \n    pout << \"\\n\";\n\n}\n\nint CirculationModel_aorta::point_in_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_ventricle_axis) || (side != d_ventricle_side))\n        return 0; \n\n    return pnpoly(d_n_pts_ventricle, d_ventricle_points_idx1, d_ventricle_points_idx2, testx, testy); \n}\n\nint CirculationModel_aorta::point_in_aorta(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_aorta_axis) || (side != d_aorta_side))\n        return 0; \n\n    return pnpoly(d_n_pts_aorta, d_aorta_points_idx1, d_aorta_points_idx2, testx, testy); \n}\n\n\n    void CirculationModel_aorta::write_plot_code()\n{\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        fout << \"];\\n\";  \n        fout << \"fig = figure;\\n\";  \n        fout << \"times            =  bc_vals(:,1);\\n\"; \n        fout << \"p_lv             =  bc_vals(:,2);\\n\"; \n        fout << \"p_aorta          =  bc_vals(:,3); \\n\"; \n        fout << \"q_ventricle      = -bc_vals(:,4);\\n\"; \n        fout << \"q_aorta          =  bc_vals(:,5);\\n\"; \n        fout << \"q_valve          =  bc_vals(:,6);\\n\"; \n        fout << \"p_wk             =  bc_vals(:,7);\\n\"; \n        fout << \"p_extender_mean  =  bc_vals(:,8);\\n\"; \n        fout << \"p_extender_point =  bc_vals(:,9);\\n\"; \n        fout << \"subplot(2,1,1)\\n\"; \n        fout << \"plot(times, p_aorta, 'k')\\n\"; \n        fout << \"hold on\\n\"; \n        fout << \"plot(times, p_wk, ':k')\\n\"; \n        fout << \"plot(times, p_lv, '--k')\\n\"; \n        fout << \"%plot(times, p_extender_mean)\\n\"; \n        fout << \"plot(times, p_extender_point)\\n\";                         \n        fout << \"%legend('P_{Ao}', 'P_{Wk}', 'P_{LV}', 'P extender mean', 'P extender point', 'Location','NorthEastOutside');\\n\"; \n        fout << \"%legend('P_{Ao}', 'P_{Wk}', 'P_{LV}', 'P extender point', '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_aorta, 'k')\\n\"; \n        fout << \"hold on\\n\"; \n        fout << \"dt = times(2,1) - times(1);\\n\"; \n        fout << \"net_flux = dt*cumsum(q_aorta);\\n\"; \n        fout << \"plot(times, net_flux, '--k')\\n\"; \n        fout << \"plot(times, q_ventricle)\\n\"; \n        fout << \"% plot(times, q_valve)\\n\"; \n        fout << \"plot(bc_vals(:,1), 0*net_flux, ':k')\\n\"; \n        fout << \"%legend('Q', 'net Q', 'Q ventricle', 'Q valve', 'Location','NorthEastOutside')\\n\"; \n        fout << \"legend('Q', 'net Q', 'Q ventricle', 'Location','NorthEastOutside')\\n\"; \n        fout << \"xlabel('t (s)')\\n\"; \n        fout << \"ylabel('Flow (ml/s), Net Flow (ml)')\\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')\\n\"; \n        fout << \"diary notes.txt\\n\"; \n        fout << \"min_p_aorta_after_first_beat = min(p_aorta(floor(end/3):end))\\n\"; \n        fout << \"max_p_aorta_after_first_beat = max(p_aorta(floor(end/3):end))\\n\"; \n        fout << \"mean_p_aorta = mean(p_aorta)\\n\"; \n        fout << \"mean_p_wk    = mean(p_wk)\\n\"; \n        fout << \"max_p_exender_mean = max(p_extender_mean)\\n\"; \n        fout << \"max_p_exender_point = max(p_extender_point)\\n\"; \n        fout << \"mean_p_lv    = mean(p_lv)\\n\"; \n        fout << \"end_flux    = net_flux(end)\\n\"; \n        fout << \"max_flux    = max(net_flux)\\n\"; \n        fout << \"diary off\\n\"; \n\n    }\n    return;\n\n}\n\n\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\n    CirculationModel_aorta::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_ventricle (mmHg)\\t P_aorta (mmHg)\\t d_Q_ventricle (ml/s)\\t d_Q_aorta (ml/s)\\t d_Q_valve (ml/s)\\t\" \n                 << \"d_aorta_P_Wk (mmHg) \\t d_p_extender_mean (mmHg) \\t d_p_extender_point (mmHg)\" \n                 << \"\\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_ventricle = d_fourier_ventricle->values[d_current_idx_series]; \n\n        double P_aorta = 0.0; \n\n        if (d_rcr_bcs_on){\n            P_aorta        = d_aorta_P/MMHG_TO_CGS;\n        }\n        else{\n            TBOX_ERROR(\"not implemented\\n\"); \n            // P_aorta        = d_fourier_aorta->values[d_current_idx_series];\n        }\n\n        fout << \" \" << P_ventricle <<  \" \" << P_aorta;\n        fout << \" \" << d_Q_ventricle << \" \" << d_Q_aorta << \" \" << d_Q_valve;         \n        fout << \" \" << d_aorta_P_Wk/MMHG_TO_CGS;\n        fout << \" \" << d_p_extender_mean/MMHG_TO_CGS;\n        fout << \" \" << d_p_extender_point/MMHG_TO_CGS;                        \n        fout << \"; \\n\";\n\n    }\n\n    return;\n} // writeDataFile\n\nvoid\nCirculationModel_aorta::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_ventricle        = db->getDouble(\"d_Q_ventricle\"); \n    d_Q_aorta            = db->getDouble(\"d_Q_aorta\");\n    d_Q_valve            = db->getDouble(\"d_Q_valve\");\n    d_aorta_P            = db->getDouble(\"d_aorta_P\");\n    d_aorta_P_Wk         = db->getDouble(\"d_aorta_P_Wk\");\n    d_p_extender_mean    = db->getDouble(\"d_p_extender_mean\");\n    d_p_extender_point   = db->getDouble(\"d_p_extender_point\");\n    d_time               = db->getDouble(\"d_time\");\n    d_rcr_bcs_on         = db->getBool(\"d_rcr_bcs_on\"); \n    return;\n} // getFromRestart\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////\n\n//////////////////////////////////////////////////////////////////////////////", "meta": {"hexsha": "8dd69044d55e2e6bbc79f998842c12e7e5cbf2b2", "size": 23413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CirculationModel_aorta.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_aorta.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_aorta.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": 38.2565359477, "max_line_length": 164, "alphanum_fraction": 0.5047196002, "num_tokens": 6018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05834584388645591, "lm_q1q2_score": 0.029172921943227955}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_UNITS_CODATA_MUON_CONSTANTS_HPP\r\n#define BOOST_UNITS_CODATA_MUON_CONSTANTS_HPP\r\n\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/static_constant.hpp>\r\n\r\n#include <boost/units/systems/detail/constants.hpp>\r\n#include <boost/units/systems/si/amount.hpp>\r\n#include <boost/units/systems/si/area.hpp>\r\n#include <boost/units/systems/si/electric_charge.hpp>\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/frequency.hpp>\r\n#include <boost/units/systems/si/length.hpp>\r\n#include <boost/units/systems/si/mass.hpp>\r\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\r\n#include <boost/units/systems/si/time.hpp>\r\n#include <boost/units/systems/si/wavenumber.hpp>\r\n\r\n#include <boost/units/systems/si/codata/typedefs.hpp>\r\n\r\n/// \\file\r\n/// CODATA recommended values of fundamental atomic and nuclear constants\r\n/// CODATA 2006 values as of 2007/03/30\r\n\r\nnamespace boost {\r\n\r\nnamespace units { \r\n\r\nnamespace si {\r\n                            \r\nnamespace constants {\r\n\r\nnamespace codata {\r\n\r\n/// CODATA recommended values of the fundamental physical constants: NIST SP 961\r\n\r\n/// muon mass\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_mu,quantity<mass>,1.88353130e-28*kilograms,1.1e-35*kilograms);\r\n/// muon-electron mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_mu_over_m_e,quantity<dimensionless>,206.7682823*dimensionless(),5.2e-6*dimensionless());\r\n/// muon-tau mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_mu_over_m_tau,quantity<dimensionless>,5.94592e-2*dimensionless(),9.7e-6*dimensionless());\r\n/// muon-proton mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_mu_over_m_p,quantity<dimensionless>,0.1126095261*dimensionless(),2.9e-9*dimensionless());\r\n/// muon-neutron mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_mu_over_m_n,quantity<dimensionless>,0.1124545167*dimensionless(),2.9e-9*dimensionless());\r\n/// muon molar mass\r\nBOOST_UNITS_PHYSICAL_CONSTANT(M_mu,quantity<mass_over_amount>,0.1134289256e-3*kilograms/mole,2.9e-12*kilograms/mole);\r\n/// muon Compton wavelength\r\nBOOST_UNITS_PHYSICAL_CONSTANT(lambda_C_mu,quantity<length>,11.73444104e-15*meters,3.0e-22*meters);\r\n/// muon magnetic moment\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_mu,quantity<energy_over_magnetic_flux_density>,-4.49044786e-26*joules/tesla,1.6e-33*joules/tesla);\r\n/// muon-Bohr magneton ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_mu_over_mu_B,quantity<dimensionless>,-4.84197049e-3*dimensionless(),1.2e-10*dimensionless());\r\n/// muon-nuclear magneton ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_mu_over_mu_N,quantity<dimensionless>,-8.89059705*dimensionless(),2.3e-7*dimensionless());\r\n/// muon magnetic moment anomaly\r\nBOOST_UNITS_PHYSICAL_CONSTANT(a_mu,quantity<dimensionless>,1.16592069e-3*dimensionless(),6.0e-10*dimensionless());\r\n/// muon g-factor\r\nBOOST_UNITS_PHYSICAL_CONSTANT(g_mu,quantity<dimensionless>,-2.0023318414*dimensionless(),1.2e-9*dimensionless());\r\n/// muon-proton magnetic moment ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_mu_over_mu_p,quantity<dimensionless>,-3.183345137*dimensionless(),8.5e-8*dimensionless());\r\n\r\n} // namespace codata\r\n\r\n} // namespace constants    \r\n\r\n} // namespace si\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_UNITS_CODATA_MUON_CONSTANTS_HPP\r\n", "meta": {"hexsha": "162b34d742040b51cf1efb247648f660e144859f", "size": 3592, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/muon_constants.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/muon_constants.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/muon_constants.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 42.2588235294, "max_line_length": 132, "alphanum_fraction": 0.7739420935, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.06656918758161515, "lm_q1q2_score": 0.029145554640172423}}
{"text": "/*    Copyright (c) 2010-2016, 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#include <boost/make_shared.hpp>\r\n#include <boost/bind.hpp>\r\n\r\n#include \"Tudat/Astrodynamics/Aerodynamics/aerodynamicCoefficientInterface.h\"\r\n#include \"Tudat/Astrodynamics/Aerodynamics/customAerodynamicCoefficientInterface.h\"\r\n#include \"Tudat/SimulationSetup/createFlightConditions.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace simulation_setup\r\n{\r\n\r\n//! Function to create an aerodynamic coefficient interface containing constant coefficients.\r\nboost::shared_ptr< aerodynamics::AerodynamicCoefficientInterface >\r\ncreateConstantCoefficientAerodynamicCoefficientInterface(\r\n        const Eigen::Vector3d constantForceCoefficient,\r\n        const Eigen::Vector3d constantMomentCoefficient,\r\n        const double referenceLength,\r\n        const double referenceArea,\r\n        const double lateralReferenceLength,\r\n        const Eigen::Vector3d& momentReferencePoint,\r\n        const bool areCoefficientsInAerodynamicFrame,\r\n        const bool areCoefficientsInNegativeAxisDirection  )\r\n{\r\n    // Create coefficient interface\r\n    boost::shared_ptr< aerodynamics::AerodynamicCoefficientInterface > coefficientInterface =\r\n            boost::make_shared< aerodynamics::CustomAerodynamicCoefficientInterface >(\r\n                boost::lambda::constant( constantForceCoefficient ),\r\n                boost::lambda::constant( constantMomentCoefficient ),\r\n                referenceLength, referenceArea, lateralReferenceLength, momentReferencePoint,\r\n                std::vector< aerodynamics::AerodynamicCoefficientsIndependentVariables >( ),\r\n                areCoefficientsInAerodynamicFrame, areCoefficientsInNegativeAxisDirection );\r\n    coefficientInterface->updateCurrentCoefficients( std::vector< double >( ) );\r\n\r\n    return coefficientInterface;\r\n}\r\n\r\n//! Function to create and aerodynamic coefficient interface.\r\nboost::shared_ptr< aerodynamics::AerodynamicCoefficientInterface >\r\ncreateAerodynamicCoefficientInterface(\r\n        const boost::shared_ptr< AerodynamicCoefficientSettings > coefficientSettings,\r\n        const std::string& body )\r\n{\r\n    using namespace tudat::aerodynamics;\r\n\r\n    boost::shared_ptr< AerodynamicCoefficientInterface > coefficientInterface;\r\n\r\n    // Check type of interface that is to be created.\r\n    switch( coefficientSettings->getAerodynamicCoefficientType( ) )\r\n    {\r\n    case constant_aerodynamic_coefficients:\r\n    {\r\n        // Check consistency of type.\r\n        boost::shared_ptr< ConstantAerodynamicCoefficientSettings > constantCoefficientSettings =\r\n                boost::dynamic_pointer_cast< ConstantAerodynamicCoefficientSettings >(\r\n                    coefficientSettings );\r\n        if( constantCoefficientSettings == NULL )\r\n        {\r\n            throw std::runtime_error(\r\n                        \"Error, expected constant aerodynamic coefficients for body \" + body );\r\n        }\r\n        else\r\n        {\r\n            // create constant interface.\r\n            coefficientInterface = createConstantCoefficientAerodynamicCoefficientInterface(\r\n                        constantCoefficientSettings->getConstantForceCoefficient( ),\r\n                        constantCoefficientSettings->getConstantMomentCoefficient( ),\r\n                        constantCoefficientSettings->getReferenceLength( ),\r\n                        constantCoefficientSettings->getReferenceArea( ),\r\n                        constantCoefficientSettings->getReferenceLength( ),\r\n                        constantCoefficientSettings->getMomentReferencePoint( ),\r\n                        constantCoefficientSettings->getAreCoefficientsInAerodynamicFrame( ),\r\n                        constantCoefficientSettings->getAreCoefficientsInNegativeAxisDirection( ) );\r\n        }\r\n        break;\r\n    }\r\n    case tabulated_coefficients:\r\n    {\r\n        // Check number of dimensions of tabulated coefficients.\r\n        int numberOfDimensions = coefficientSettings->getIndependentVariableNames( ).size( );\r\n        switch( numberOfDimensions )\r\n        {\r\n        case 1:\r\n        {\r\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 1 >(\r\n                        coefficientSettings, body );\r\n            break;\r\n        }\r\n        case 2:\r\n        {\r\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 2 >(\r\n                        coefficientSettings, body );\r\n            break;\r\n        }\r\n        case 3:\r\n        {\r\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 3 >(\r\n                        coefficientSettings, body );\r\n            break;\r\n        }\r\n        case 4:\r\n        {\r\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 4 >(\r\n                        coefficientSettings, body );\r\n            break;\r\n        }\r\n        case 5:\r\n        {\r\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 5 >(\r\n                        coefficientSettings, body );\r\n            break;\r\n        }\r\n        case 6:\r\n        {\r\n            coefficientInterface = createTabulatedCoefficientAerodynamicCoefficientInterface< 6 >(\r\n                        coefficientSettings, body );\r\n            break;\r\n        }\r\n        default:\r\n            throw std::runtime_error( \"Error when making tabulated aerodynamic coefficient interface, \" +\r\n                       boost::lexical_cast< std::string >( numberOfDimensions ) + \" dimensions not yet implemented\" );\r\n        }\r\n\r\n    }\r\n    default:\r\n        throw std::runtime_error( \"Error, do not recognize aerodynamic coefficient settings for \" + body );\r\n    }\r\n    return coefficientInterface;\r\n}\r\n\r\n//! Function to create a flight conditions object\r\nboost::shared_ptr< aerodynamics::FlightConditions > createFlightConditions(\r\n        const boost::shared_ptr< Body > bodyWithFlightConditions,\r\n        const boost::shared_ptr< Body > centralBody,\r\n        const std::string& nameOfBodyUndergoingAcceleration,\r\n        const std::string& nameOfBodyExertingAcceleration,\r\n        const boost::function< double( ) > angleOfAttackFunction,\r\n        const boost::function< double( ) > angleOfSideslipFunction,\r\n        const boost::function< double( ) > bankAngleFunction )\r\n{\r\n    // Check whether all required environment models are set.\r\n    if( centralBody->getAtmosphereModel( ) == NULL )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no atmosphere model.\" );\r\n    }\r\n\r\n    if( centralBody->getShapeModel( ) == NULL )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no shape model.\" );\r\n    }\r\n\r\n    if( centralBody->getRotationalEphemeris( ) == NULL )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no rotation model.\" );\r\n    }\r\n\r\n    if( bodyWithFlightConditions->getAerodynamicCoefficientInterface( ) == NULL )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \"+ nameOfBodyUndergoingAcceleration +\r\n                    \" has no aerodynamic coefficients.\" );\r\n    }\r\n\r\n    // Create function to calculate the altitude from current body-fixed state\r\n    boost::function< double( const Eigen::Vector3d ) > altitudeFunction =\r\n            boost::bind( &basic_astrodynamics::BodyShapeModel::getAltitude,\r\n                         centralBody->getShapeModel( ), _1 );\r\n\r\n    // Create function to rotate state from intertial to body-fixed frame.\r\n    boost::function< Eigen::Quaterniond( ) > rotationToFrameFunction =\r\n            boost::bind( &Body::getCurrentRotationToLocalFrame, centralBody );\r\n    boost::function< Eigen::Matrix3d( ) > rotationMatrixToFrameDerivativeFunction =\r\n            boost::bind( &Body::getCurrentRotationMatrixDerivativeToLocalFrame, centralBody );\r\n    boost::function< basic_mathematics::Vector6d( const basic_mathematics::Vector6d& ) >\r\n            transformationToCentralBodyFrame =\r\n            boost::bind(\r\n                static_cast< basic_mathematics::Vector6d(&)(\r\n                    const basic_mathematics::Vector6d&,\r\n                    const boost::function< Eigen::Quaterniond( ) >,\r\n                    const boost::function< Eigen::Matrix3d( ) > ) >(\r\n                    &ephemerides::transformStateToFrame ),\r\n                _1, rotationToFrameFunction,\r\n                rotationMatrixToFrameDerivativeFunction );\r\n\r\n    // Create flight conditions.\r\n    boost::shared_ptr< aerodynamics::FlightConditions > flightConditions =\r\n            boost::make_shared< aerodynamics::FlightConditions >(\r\n                centralBody->getAtmosphereModel( ), altitudeFunction,\r\n                boost::bind( &Body::getState, bodyWithFlightConditions ),\r\n                boost::bind( &Body::getState, centralBody ),\r\n                transformationToCentralBodyFrame,\r\n                bodyWithFlightConditions->getAerodynamicCoefficientInterface( ) );\r\n\r\n    // Create aerodynamic angles calculator and set in flight conditions.\r\n    boost::shared_ptr< reference_frames::AerodynamicAngleCalculator > aerodynamicAngleCalculator =\r\n            boost::make_shared< reference_frames::AerodynamicAngleCalculator >(\r\n                boost::bind( &aerodynamics::FlightConditions::getCurrentBodyCenteredBodyFixedState,\r\n                             flightConditions ),\r\n                angleOfAttackFunction, angleOfSideslipFunction, bankAngleFunction, 1 );\r\n    flightConditions->setAerodynamicAngleCalculator( aerodynamicAngleCalculator );\r\n\r\n    return flightConditions;\r\n\r\n\r\n}\r\n\r\n} // namespace simulation_setup\r\n\r\n} // namespace tudat\r\n", "meta": {"hexsha": "75d07ff7189650723892d073b1e27fcc835238f7", "size": 10304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/createFlightConditions.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/SimulationSetup/createFlightConditions.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/SimulationSetup/createFlightConditions.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": 45.3920704846, "max_line_length": 119, "alphanum_fraction": 0.649359472, "num_tokens": 1950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.05921025157134612, "lm_q1q2_score": 0.029142583336460155}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Alexander Sokolov <asokolov@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_REVERSER_HPP\n#define CRYPTO3_DETAIL_REVERSER_HPP\n\n#include <boost/integer.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/endian/conversion.hpp>\n\n#include <nil/crypto3/detail/unbounded_shift.hpp>\n#include <nil/crypto3/detail/stream_endian.hpp>\n#include <nil/crypto3/detail/predef.hpp>\n\n#include <climits>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n\n            /*!\n             * @defgroup reverser Reverser functions\n             */\n\n            typedef typename boost::uint_t<CHAR_BIT>::exact byte_type;\n\n            /*!\n             * @brief This function reverses bit order in the byte b depending on the machine word size.\n             * The underlying algorithms used in this function are described in\n             * http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits and in\n             * http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64BitsDiv .\n             *\n             * @ingroup reverser\n             *\n             * @param b\n             *\n             * @return\n             */\n            inline void reverse_byte(byte_type &b) {\n\n#if (BOOST_ARCH_CURRENT_WORD_BITS == 32)\n                b = unbounded_shr<16>(((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU);\n#elif (BOOST_ARCH_CURRENT_WORD_BITS == 64)\n                b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;\n#else\n#error \"BOOST_ARCH_CURRENT_WORD_BITS not set\"\n#endif\n            }\n\n            /*!\n             * @brief bit_in_unit_byte_reverser transforms the sequence of bits in each byte of\n             * the input unit into reversed sequence of bits in each byte of the output unit.\n             * The function reverse is recursively invoked and the parameter k is used to track\n             * the number of already processed input bytes. The recursion ends, when all input\n             * bytes have been processed, i.e. when k == UnitBits.\n             *\n             * @ingroup reverser\n             *\n             * @tparam UnitBits\n             * @tparam k\n             */\n            template<int UnitBits, int k = 0>\n            struct bit_in_unit_byte_reverser {\n\n                BOOST_STATIC_ASSERT(!(UnitBits % CHAR_BIT));\n\n                typedef bit_in_unit_byte_reverser<UnitBits, k + CHAR_BIT> next_type;\n                typedef typename boost::uint_t<UnitBits>::exact UnitType;\n\n                inline static void reverse(UnitType &in, UnitType &out) {\n                    int const shift = UnitBits - (CHAR_BIT + k);\n                    byte_type byte = byte_type(low_bits<CHAR_BIT>(unbounded_shr(in, shift)));\n                    reverse_byte(byte);\n                    out |= unbounded_shl(low_bits<CHAR_BIT>(UnitType(byte)), shift);\n\n                    next_type::reverse(in, out);\n                }\n            };\n\n            template<int UnitBits>\n            struct bit_in_unit_byte_reverser<UnitBits, UnitBits> {\n                inline static void reverse(typename boost::uint_t<UnitBits>::exact &,\n                                           typename boost::uint_t<UnitBits>::exact &) {\n                }\n            };\n\n            /*!\n             * @brief The functions listed below deal with bit reversal in a unit.\n             */\n\n            /*!\n             * @brief This function deals with the case of UnitBits > CHAR_BIT. To reverse\n             * the order of bits, first, it reverses the byte order of unit, and then, it\n             * invokes bit_in_unit_byte_reverser to reverse bits in each byte of unit.\n             *\n             * @ingroup reverser\n             *\n             * @tparam UnitType\n             * @tparam UnitBits\n             *\n             * @param unit\n             *\n             * @return\n             */\n            template<typename UnitType,\n                     int UnitBits = sizeof(UnitType) * CHAR_BIT,\n                     typename std::enable_if<(UnitBits > CHAR_BIT), int>::type = 0>\n            inline void reverse_bits(UnitType &unit) {\n                boost::endian::endian_reverse_inplace(unit);\n                UnitType out = UnitType();\n                bit_in_unit_byte_reverser<UnitBits>::reverse(unit, out);\n                unit = out;\n            }\n            /*!\n             * @brief This function deals with the special case of UnitBits == CHAR_BIT,\n             * it just reverses the bit order in the byte.\n             * @ingroup reverser\n             *\n             * @tparam UnitType\n             * @tparam UnitBits\n             *\n             * @param unit\n             *\n             * @return\n             */\n            template<typename UnitType,\n                     int UnitBits = sizeof(UnitType) * CHAR_BIT,\n                     typename std::enable_if<(UnitBits == CHAR_BIT), int>::type = 0>\n            inline void reverse_bits(UnitType &unit) {\n                reverse_byte(unit);\n            }\n\n            /*!\n             * @brief bit_in_unit_reverser transforms the sequence of bits in each unit of\n             * the input value into reversed sequence of bytes in each unit of the output value.\n             * The function reverse is recursively invoked and the parameter k is used to track\n             * the number of already processed input units. The recursion ends, when all input\n             * units have been processed, i.e. when k == InputBits.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputBits\n             * @tparam UnitBits\n             * @tparam k\n             */\n            template<int InputBits, int UnitBits, int k = 0>\n            struct bit_in_unit_reverser {\n\n                BOOST_STATIC_ASSERT(!(InputBits % UnitBits) && !(UnitBits % CHAR_BIT));\n\n                typedef bit_in_unit_reverser<InputBits, UnitBits, k + UnitBits> next_type;\n                typedef typename boost::uint_t<UnitBits>::exact UnitType;\n\n                template<typename ValueType>\n                inline static void reverse(ValueType &in, ValueType &out) {\n                    int const shift = InputBits - (UnitBits + k);\n                    UnitType unit = UnitType(low_bits<UnitBits>(unbounded_shr(in, shift)));\n                    reverse_bits(unit);\n                    out |= unbounded_shl(low_bits<UnitBits>(ValueType(unit)), shift);\n\n                    next_type::reverse(in, out);\n                }\n            };\n\n            template<int InputBits, int UnitBits>\n            struct bit_in_unit_reverser<InputBits, UnitBits, InputBits> {\n                template<typename ValueType>\n                inline static void reverse(ValueType &, ValueType &) {\n                }\n            };\n\n            /*!\n             * @brief The group of traits below is used to determine the order of bits defined\n             * by the endianness.\n             */\n\n            /*!\n             * @brief Trait to determine whether the order of bits defined by Endianness endianness\n             * is big.\n             *\n             * @ingroup reverser\n             *\n             * @tparam Endianness\n             * @tparam UnitBits\n             */\n            template<typename Endianness, int UnitBits>\n            struct is_big_bit {\n                constexpr static const bool value =\n                    std::is_same<Endianness, stream_endian::big_unit_big_bit<UnitBits>>::value ||\n                    std::is_same<Endianness, stream_endian::little_unit_big_bit<UnitBits>>::value;\n            };\n\n            /*!\n             * @brief Trait to determine whether the order of bits defined by Endianness endianness\n             * is little.\n             *\n             * @ingroup reverser\n             *\n             * @tparam Endianness\n             * @tparam UnitBits\n             */\n            template<typename Endianness, int UnitBits>\n            struct is_little_bit {\n                constexpr static const bool value =\n                    std::is_same<Endianness, stream_endian::big_unit_little_bit<UnitBits>>::value ||\n                    std::is_same<Endianness, stream_endian::little_unit_little_bit<UnitBits>>::value;\n            };\n\n            /*!\n             * @brief Trait to determine whether the orders of bits defined by Endianness1 endianness\n             * and Endianness2 endianness are the same.\n             *\n             * @ingroup reverser\n             *\n             * @tparam Endianness1\n             * @tparam Endianness2\n             * @tparam UnitBits\n             */\n            template<typename Endianness1, typename Endianness2, int UnitBits>\n            struct is_same_bit {\n                constexpr static const bool value =\n                    (is_big_bit<Endianness1, UnitBits>::value && is_big_bit<Endianness2, UnitBits>::value) ||\n                    (is_little_bit<Endianness1, UnitBits>::value && is_little_bit<Endianness2, UnitBits>::value);\n            };\n\n            /*!\n             * @brief bit_reverser reverses the sequence of bits in each unit of the given value,\n             * if InputEndianness and OutputEndianness endiannesses have different bit orders, and\n             * does nothing, otherwise.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             * @tparam IsSameBit\n             */\n            template<typename InputEndianness,\n                     typename OutputEndianness,\n                     int UnitBits,\n                     bool IsSameBit = is_same_bit<InputEndianness, OutputEndianness, UnitBits>::value>\n            struct bit_reverser;\n\n            /*!\n             * @brief This bit_reverser is a dummy and deals with the case of the endiannesses with\n             * the same order of bits.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             */\n            template<typename InputEndianness, typename OutputEndianness, int UnitBits>\n            struct bit_reverser<InputEndianness, OutputEndianness, UnitBits, true> {\n                template<typename ValueType>\n                inline static void reverse(ValueType &) {\n                }\n\n                template<typename ValueType>\n                inline static ValueType reverse(ValueType const &val) {\n                    return val;\n                }\n            };\n\n            /*!\n             * @brief This bit_reverser deals with the case of the endiannesses with different order of\n             * bits and invokes bit_in_unit_reverser which reverses bits in each unit of the input value.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             */\n            template<typename InputEndianness, typename OutputEndianness, int UnitBits>\n            struct bit_reverser<InputEndianness, OutputEndianness, UnitBits, false> {\n                template<typename ValueType, int ValueBits = sizeof(ValueType) * CHAR_BIT>\n                inline static void reverse(ValueType &val) {\n                    ValueType out = ValueType();\n                    bit_in_unit_reverser<ValueBits, UnitBits>::reverse(val, out);\n                    val = out;\n                }\n\n                template<typename ValueType, int ValueBits = sizeof(ValueType) * CHAR_BIT>\n                inline static ValueType reverse(ValueType const &val) {\n                    ValueType tmp = val;\n                    ValueType out = ValueType();\n                    bit_in_unit_reverser<ValueBits, UnitBits>::reverse(tmp, out);\n                    return out;\n                }\n            };\n\n            /*!\n             * @brief byte_in_unit_reverser transforms the sequence of bytes in each unit of\n             * the input value into reversed sequence of bytes in each unit of the output value.\n             * The function reverse is recursively invoked and the parameter k is used to track\n             * the number of already processed input units. The recursion ends, when all input\n             * units have been processed, i.e. when k == InputBits.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputBits\n             * @tparam UnitBits\n             * @tparam k\n             */\n            template<int InputBits, int UnitBits, int k = 0>\n            struct byte_in_unit_reverser {\n\n                BOOST_STATIC_ASSERT(!(InputBits % UnitBits) && !(UnitBits % CHAR_BIT));\n\n                typedef byte_in_unit_reverser<InputBits, UnitBits, k + UnitBits> next_type;\n                typedef typename boost::uint_t<UnitBits>::exact UnitType;\n\n                template<typename ValueType>\n                inline static void reverse(ValueType &in, ValueType &out) {\n                    int const shift = InputBits - (UnitBits + k);\n                    UnitType unit = UnitType(low_bits<UnitBits>(unbounded_shr(in, shift)));\n                    boost::endian::endian_reverse_inplace(unit);\n                    out |= unbounded_shl(low_bits<UnitBits>(ValueType(unit)), shift);\n\n                    next_type::reverse(in, out);\n                }\n            };\n\n            template<int InputBits, int UnitBits>\n            struct byte_in_unit_reverser<InputBits, UnitBits, InputBits> {\n                template<typename ValueType>\n                inline static void reverse(ValueType &, ValueType &) {\n                }\n            };\n\n            /*!\n             * @brief The group of traits below is used to determine the order of units defined\n             * by the endianness.\n             */\n\n            /*!\n             * @brief Trait to determine whether the order of units defined by Endianness endianness\n             * is big.\n             *\n             * @ingroup reverser\n             *\n             * @tparam Endianness\n             * @tparam UnitBits\n             */\n            template<typename Endianness, int UnitBits>\n            struct is_big_unit {\n                constexpr static const bool value =\n                    std::is_same<Endianness, stream_endian::big_unit_big_bit<UnitBits>>::value ||\n                    std::is_same<Endianness, stream_endian::big_unit_little_bit<UnitBits>>::value;\n            };\n\n            /*!\n             * @brief Trait to determine whether the order of units defined by Endianness endianness\n             * is little.\n             *\n             * @ingroup reverser\n             *\n             * @tparam Endianness\n             * @tparam UnitBits\n             */\n            template<typename Endianness, int UnitBits>\n            struct is_little_unit {\n                constexpr static const bool value =\n                    std::is_same<Endianness, stream_endian::little_unit_big_bit<UnitBits>>::value ||\n                    std::is_same<Endianness, stream_endian::little_unit_little_bit<UnitBits>>::value;\n            };\n\n            /*!\n             * @brief Trait to determine whether the orders of units defined by Endianness1 endianness\n             * and Endianness2 endianness are the same.\n             *\n             * @ingroup reverser\n             *\n             * @tparam Endianness1\n             * @tparam Endianness2\n             * @tparam UnitBits\n             */\n            template<typename Endianness1, typename Endianness2, int UnitBits>\n            struct is_same_unit {\n                constexpr static const bool value =\n                    (is_big_unit<Endianness1, UnitBits>::value && is_big_unit<Endianness2, UnitBits>::value) ||\n                    (is_little_unit<Endianness1, UnitBits>::value && is_little_unit<Endianness2, UnitBits>::value);\n            };\n\n            /*!\n             * @brief unit_reverser reverses the sequence of units in the given value, if InputEndianness\n             * and OutputEndianness endiannesses have different unit orders, and does nothing, otherwise.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             * @tparam Enable\n             */\n            template<typename InputEndianness, typename OutputEndianness, int UnitBits, typename Enable = void>\n            struct unit_reverser;\n\n            /*!\n             * @brief This unit_reverser is a dummy and deals with the case of the endiannesses with\n             * the same order of units.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             */\n            template<typename InputEndianness, typename OutputEndianness, int UnitBits>\n            struct unit_reverser<\n                InputEndianness,\n                OutputEndianness,\n                UnitBits,\n                typename std::enable_if<is_same_unit<InputEndianness, OutputEndianness, UnitBits>::value>::type> {\n                template<typename ValueType>\n                inline static void reverse(ValueType &) {\n                }\n\n                template<typename ValueType>\n                inline static ValueType reverse(ValueType const &val) {\n                    return val;\n                }\n            };\n\n            /*!\n             * @brief This unit_reverser deals with the case of UnitBits == CHAR_BIT. This case is\n             * special since it is sufficient to reverse the order of bytes in an input value.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             */\n            template<typename InputEndianness, typename OutputEndianness, int UnitBits>\n            struct unit_reverser<\n                InputEndianness,\n                OutputEndianness,\n                UnitBits,\n                typename std::enable_if<!is_same_unit<InputEndianness, OutputEndianness, UnitBits>::value &&\n                                        UnitBits == CHAR_BIT>::type> {\n                template<typename ValueType>\n                inline static void reverse(ValueType &val) {\n                    boost::endian::endian_reverse_inplace(val);\n                }\n\n                template<typename ValueType>\n                inline static ValueType reverse(ValueType const &val) {\n                    return boost::endian::endian_reverse(val);\n                }\n            };\n\n            /*!\n             * @brief This unit_reverser deals with the case of UnitBits > CHAR_BIT. To reverse the\n             * order of units, first, it reverses the byte order in an input value, and then, it\n             * invokes byte_in_unit_reverser to reverse the byte order in each unit of the input value.\n             *\n             * @ingroup reverser\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam UnitBits\n             */\n            template<typename InputEndianness, typename OutputEndianness, int UnitBits>\n            struct unit_reverser<\n                InputEndianness,\n                OutputEndianness,\n                UnitBits,\n                typename std::enable_if<!is_same_unit<InputEndianness, OutputEndianness, UnitBits>::value &&\n                                        (UnitBits > CHAR_BIT)>::type> {\n                template<typename ValueType, int ValueBits = sizeof(ValueType) * CHAR_BIT>\n                inline static void reverse(ValueType &val) {\n                    boost::endian::endian_reverse_inplace(val);\n                    ValueType out = ValueType();\n                    byte_in_unit_reverser<ValueBits, UnitBits>::reverse(val, out);\n                    val = out;\n                }\n\n                template<typename ValueType, int ValueBits = sizeof(ValueType) * CHAR_BIT>\n                inline static ValueType reverse(ValueType const &val) {\n                    ValueType tmp = boost::endian::endian_reverse(val);\n                    ValueType out = ValueType();\n                    byte_in_unit_reverser<ValueBits, UnitBits>::reverse(tmp, out);\n                    return out;\n                }\n            };\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_DETAIL_REVERSER_HPP\n", "meta": {"hexsha": "937eeee6885bddbe999e419d8b0804fdeee75b27", "size": 21847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/reverser.hpp", "max_stars_repo_name": "NoamDev/crypto3-hash", "max_stars_repo_head_hexsha": "0bf16b912780fd2f82b9a94899fd2151c09209bb", "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/reverser.hpp", "max_issues_repo_name": "NoamDev/crypto3-hash", "max_issues_repo_head_hexsha": "0bf16b912780fd2f82b9a94899fd2151c09209bb", "max_issues_repo_licenses": ["MIT"], "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/detail/reverser.hpp", "max_forks_repo_name": "NoamDev/crypto3-hash", "max_forks_repo_head_hexsha": "0bf16b912780fd2f82b9a94899fd2151c09209bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 42.2572533849, "max_line_length": 115, "alphanum_fraction": 0.5477639951, "num_tokens": 4393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438009916360314, "lm_q2_score": 0.060086654381815895, "lm_q1q2_score": 0.02910477960787313}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n/// \\file algorithm.hpp\r\n///   Contains range-based versions of the std algorithms\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Copyright 2009 Neil Groves.\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// Copyright 2006 Thorsten Ottosen.\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// Copyright 2004 Eric Niebler.\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#if defined(_MSC_VER) && _MSC_VER >= 1000\r\n    #pragma once\r\n#endif\r\n\r\n#ifndef BOOST_RANGE_NUMERIC_HPP\r\n#define BOOST_RANGE_NUMERIC_HPP\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/assert.hpp>\r\n#include <boost/range/begin.hpp>\r\n#include <boost/range/end.hpp>\r\n#include <boost/range/concepts.hpp>\r\n#include <boost/range/distance.hpp>\r\n#include <numeric>\r\n\r\n\r\nnamespace boost\r\n{\r\n    template< class SinglePassRange, class Value >\r\n    inline Value accumulate( const SinglePassRange& rng, Value init )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));\r\n        return std::accumulate( boost::begin(rng), boost::end(rng), init );\r\n    }\r\n\r\n    template< class SinglePassRange, class Value, class BinaryOperation >\r\n    inline Value accumulate( const SinglePassRange& rng, Value init, BinaryOperation op )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));\r\n        return std::accumulate( boost::begin(rng), boost::end(rng), init, op );\r\n    }\r\n\r\n\r\n    template< class SinglePassRange1, class SinglePassRange2, class Value >\r\n    inline Value inner_product( const SinglePassRange1& rng1, const SinglePassRange2& rng2, Value init )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange1> ));\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange2> ));\r\n        BOOST_ASSERT( boost::distance(rng2) >= boost::distance(rng1) );\r\n        return std::inner_product( boost::begin(rng1), boost::end(rng1),\r\n            boost::begin(rng2), init );\r\n    }\r\n\r\n    template< class SinglePassRange1,\r\n              class SinglePassRange2,\r\n              class Value,\r\n              class BinaryOperation1, class BinaryOperation2 >\r\n    inline Value inner_product( const SinglePassRange1& rng1, const SinglePassRange2& rng2,\r\n                                Value init,\r\n                                BinaryOperation1 op1, BinaryOperation2 op2 )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange1> ));\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange2> ));\r\n        BOOST_ASSERT( boost::distance(rng2) >= boost::distance(rng1) );\r\n\r\n        return std::inner_product( boost::begin(rng1), boost::end(rng1),\r\n                                   boost::begin(rng2), init, op1, op2 );\r\n    }\r\n\r\n    template< class SinglePassRange, class OutputIterator >\r\n    inline OutputIterator partial_sum ( const SinglePassRange& rng,\r\n                                        OutputIterator result )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));\r\n        return std::partial_sum( boost::begin(rng), boost::end(rng), result );\r\n    }\r\n\r\n    template< class SinglePassRange, class OutputIterator, class BinaryOperation >\r\n    inline OutputIterator partial_sum ( const SinglePassRange& rng, OutputIterator result,\r\n                                        BinaryOperation op )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));\r\n        return std::partial_sum( boost::begin(rng), boost::end(rng), result, op );\r\n    }\r\n\r\n    template< class SinglePassRange, class OutputIterator >\r\n    inline OutputIterator adjacent_difference ( const SinglePassRange& rng,\r\n                                                OutputIterator result )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));\r\n        return std::adjacent_difference( boost::begin(rng), boost::end(rng),\r\n                                         result );\r\n    }\r\n\r\n    template< class SinglePassRange, class OutputIterator, class BinaryOperation >\r\n    inline OutputIterator adjacent_difference ( const SinglePassRange& rng,\r\n                                                OutputIterator result,\r\n                                                BinaryOperation op )\r\n    {\r\n        BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<SinglePassRange> ));\r\n        return std::adjacent_difference( boost::begin(rng), boost::end(rng),\r\n                                         result, op );\r\n    }\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "294147374f48503c8c20288e2745317c7dafff42", "size": 5043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/range/numeric.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "master/core/third/boost/range/numeric.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/range/numeric.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": 42.3781512605, "max_line_length": 105, "alphanum_fraction": 0.6254213762, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.06008664975322682, "lm_q1q2_score": 0.029104776471389645}}
{"text": "#ifndef FDJAC_HPP_\n#define FDJAC_HPP_\n\n/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n\n/*!\n * \\file fdjac.hpp\n * \\ingroup Solution\n * \\brief Finite-difference Jacobian helper functions for multidimensional root finders\n * \\remark Because this function is actually a template, the entire definition goes in the header file.\n * \\remark We already have a procedure for finding the Jacobian, but it is a little confusing\n *         to use.  This version will use the functors we have defined to abstract much of that\n *         complexity.  A consequence of this is that if there is any lazy evaluation or other\n *         optimization to be done in the function evaluation, it will be up to the functor to\n *         arrange it.\n */\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include \"functor.hpp\"\n#include <iostream>\n#include \"solution/util/include/ublas-helpers.hpp\"\n\n#define UBLAS boost::numeric::ublas\n\n#include \"util/base/include/timer.h\"\n\n/*!\n * Compute a single column in a Jacobian matrix.  We have broken this\n * out from the fdjac subroutine so that we can easily test a single\n * column for nonsingularity without duplicating any code.\n */\ntemplate<class FTYPE,class MTRAIT>\ninline void jacol(VecFVec<FTYPE,FTYPE> &F, const UBLAS::vector<FTYPE> &x,\n                  const UBLAS::vector<FTYPE> &fx, int j, \n                  UBLAS::matrix<FTYPE,MTRAIT> &J,\n                  bool usepartial=true, std::ostream *diagnostic=NULL) {\n  const FTYPE heps = 1.0e-6;\n  const FTYPE TINY = 1.0e-6;\n  UBLAS::vector<FTYPE> xx(x); // temporary, so we can respect the const on x\n  UBLAS::vector<FTYPE> fxx(fx.size());        // hold the values of F(xx)\n  FTYPE t = xx[j];            // store the old value\n  FTYPE h = heps * (fabs(t)+TINY);\n  \n  xx[j] = t+h;\n  h     = xx[j]-t; // reduce roundoff error, since (t+h)-t is not\n                   // necessarily identical to the original h\n  if(diagnostic) {\n      (*diagnostic) << \"j= \" << j << \"\\th= \" << h << \"\\nxx:\\n\" << xx << \"\\n\";\n  } \n  if(usepartial) {F.partial(j);}    // hint to the function that this is a partial derivative calculation\n  F(xx,fxx);       // eval the function\n  xx[j] = t;       // restore the old value\n  \n  if(diagnostic) {\n    (*diagnostic) << \"fxx:\\n\" << fxx << \"\\n\";\n  }\n  \n  // compute the finite difference derivatives\n  FTYPE hinv = 1.0/h;\n  for(size_t i=0; i<fxx.size(); ++i) {\n    J(i,j) = (fxx[i] - fx[i]) * hinv;\n  } \n}\n\n\n/*!\n * Compute the Jacobian of a vector function F at point x.\n * \\param[in] F: The function to have its Jacobian calculated\n * \\param[in] x: The point at which to calculate the Jacobian\n * \\param[out] J: The Jacobian of F\n * \\remark This function evaluates F(x) and then calls fdjac(F,x,Fx,J).  If you have already\n *         evaluated F(x), you should call the latter version directly.\n * \\warning The Jacobian calculated here is defined as J(i,j) = \\partial F_i / \\partial x_j.\n *          The version in use in GCAM looks as though it might reverse the roles of i and j;\n *          therefore, any function making use of either of these functions should take care\n *          that the right convention is being used.\n */\ntemplate <class FTYPE, class MTRAIT>\nvoid fdjac(VecFVec<FTYPE,FTYPE> &F, const UBLAS::vector<FTYPE> &x,\n           UBLAS::matrix<FTYPE,MTRAIT> &J, bool usepartial=true)\n{\n  UBLAS::vector<FTYPE> fx(F.nrtn());\n\n  F(x,fx);                      // fx = F(x)\n  fdjac(F,x,fx,J,usepartial);\n}\n\n/*!\n * Compute the Jacobian of a vector function F at point x.\n * \\tparam FTYPE: The floating point type of the input and output vectors\n * \\param[in] F: The function to have its Jacobian calculated\n * \\param[in] x: The point at which to calculate the Jacobian\n * \\param[in] fx: F(x)\n * \\param[out] J: The Jacobian of F\n * \\param[in] usepartial: (optional) use partial model evaluation for partial derivatives\n * \\param[in] diagnostic: (optional) ostream pointer to which to send additional diagnostics\n *\n */\ntemplate<class FTYPE, class MTRAIT>\nvoid fdjac(VecFVec<FTYPE,FTYPE> &F, const UBLAS::vector<FTYPE> &x,\n           const UBLAS::vector<FTYPE> &fx, UBLAS::matrix<FTYPE,MTRAIT> &J, bool usepartial=true,\n           std::ostream *diagnostic=NULL)\n{\n  if(diagnostic) {\n    (*diagnostic) << \"fdjac: usepartial = \" << usepartial << \"\\nInitial x:\\n\" << x\n        << \"\\nInitial fx:\\n\" << fx << \"\\n\";\n  }\n\n  Timer& jacTimer = TimerRegistry::getInstance().getTimer( TimerRegistry::JACOBIAN );\n  jacTimer.start();\n  \n  for(size_t j=0; j<x.size(); ++j) {\n    jacol(F, x, fx, j, J, usepartial, diagnostic);\n  }\n\n  jacTimer.stop();\n}\n\n\n#undef UBLAS\n\n#endif\n", "meta": {"hexsha": "fa6e125cdd75ef7b252f7c6bbdd5f7c0d6c16366", "size": 6181, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/solution/util/include/fdjac.hpp", "max_stars_repo_name": "zcranmer/OWEProject", "max_stars_repo_head_hexsha": "67d2367d6bdb5dd2a0aa0285be7e33ce64348677", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cvs/objects/solution/util/include/fdjac.hpp", "max_issues_repo_name": "zcranmer/OWEProject", "max_issues_repo_head_hexsha": "67d2367d6bdb5dd2a0aa0285be7e33ce64348677", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvs/objects/solution/util/include/fdjac.hpp", "max_forks_repo_name": "zcranmer/OWEProject", "max_forks_repo_head_hexsha": "67d2367d6bdb5dd2a0aa0285be7e33ce64348677", "max_forks_repo_licenses": ["ECL-2.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.8774193548, "max_line_length": 105, "alphanum_fraction": 0.685325999, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879061178313897, "lm_q2_score": 0.06187598572364271, "lm_q1q2_score": 0.02900688120207124}}
{"text": "// This file is part of the dune-gdt project:\n//   https://github.com/dune-community/dune-gdt\n// Copyright 2010-2017 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 (2013 - 2017)\n//   Kirsten Weber   (2013)\n//   Rene Milk       (2014, 2016 - 2017)\n//   Tobias Leibner  (2014, 2016)\n\n#ifndef DUNE_GDT_LOCAL_INTEGRANDS_ELLIPTIC_HH\n#define DUNE_GDT_LOCAL_INTEGRANDS_ELLIPTIC_HH\n\n#include <tuple>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/dynmatrix.hh>\n#include <dune/common/typetraits.hh>\n\n#include <dune/xt/common/fmatrix.hh>\n#include <dune/xt/common/memory.hh>\n#include <dune/xt/functions/constant.hh>\n#include <dune/xt/functions/interfaces.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\n\n\n// forward\ntemplate <class DiffusionFactorImp, class DiffusionTensorImp = void>\nclass LocalEllipticIntegrand;\n\n\nnamespace internal {\n\n\n/**\n * \\brief Traits for the Elliptic evaluation (variant for given diffusion factor and tensor).\n */\ntemplate <class DiffusionFactorImp, class DiffusionTensorImp>\nclass LocalEllipticIntegrandTraits\n{\n  static_assert(XT::Functions::is_localizable_function<DiffusionFactorImp>::value,\n                \"DiffusionFactorType has to be a localizable function!\");\n\npublic:\n  typedef typename DiffusionFactorImp::EntityType EntityType;\n  typedef typename DiffusionFactorImp::DomainFieldType DomainFieldType;\n  static const size_t dimDomain = DiffusionFactorImp::dimDomain;\n\n  // we need to distinguish three cases here (since DiffusionTensorImp may be void):\n  // given two functions, a factor and a tensor\n  // given a single factor (then set the tensor to default)\n  // given a single tensor (then set the factor to default)\nprivate:\n  typedef EntityType E;\n  typedef DomainFieldType D;\n  static const size_t d = dimDomain;\n\n  template <bool factor, bool tensor, bool anything = true>\n  struct Helper\n  {\n    static_assert(AlwaysFalse<DiffusionTensorImp>::value, \"Unsupported combination of functions given!\");\n  };\n\n  // given both\n  template <bool anything>\n  struct Helper<false, false, anything>\n  {\n    static_assert(XT::Functions::is_localizable_function<DiffusionTensorImp>::value,\n                  \"DiffusionTensorType has to be a localizable function!\");\n    static_assert(std::is_same<typename DiffusionFactorImp::EntityType, typename DiffusionTensorImp::EntityType>::value,\n                  \"EntityTypes have to agree!\");\n    static_assert(\n        std::is_same<typename DiffusionFactorImp::DomainFieldType, typename DiffusionTensorImp::DomainFieldType>::value,\n        \"DomainFieldTypes have to agree!\");\n    static_assert(DiffusionFactorImp::dimDomain == DiffusionTensorImp::dimDomain, \"Dimensions have to agree!\");\n    static_assert(DiffusionFactorImp::dimRange == 1, \"DiffusionFactorType has to be scalar!\");\n    static_assert(DiffusionFactorImp::dimRangeCols == 1, \"DiffusionFactorType has to be scalar!\");\n    static_assert(DiffusionTensorImp::dimRange == DiffusionTensorImp::dimDomain,\n                  \"DiffusionTensorType has to be matrix valued!\");\n    static_assert(DiffusionTensorImp::dimRangeCols == DiffusionTensorImp::dimDomain,\n                  \"DiffusionTensorType has to be matrix valued!\");\n    typedef DiffusionFactorImp FactorType;\n    typedef DiffusionTensorImp TensorType;\n  };\n\n  // given only one, and this is scalar\n  template <bool anything>\n  struct Helper<true, false, anything>\n  {\n    typedef DiffusionFactorImp FactorType;\n    typedef XT::Functions::ConstantFunction<E, D, d, D, d, d> TensorType;\n  };\n\n  // given only one, and this is a tensor\n  template <bool anything>\n  struct Helper<false, true, anything>\n  {\n    typedef XT::Functions::ConstantFunction<E, D, d, D, 1, 1> FactorType;\n    typedef DiffusionFactorImp TensorType;\n  };\n\n  static const bool single_factor_given = DiffusionFactorImp::dimRange == 1\n                                          && DiffusionFactorImp::dimRangeCols == DiffusionFactorImp::dimRange\n                                          && std::is_same<DiffusionTensorImp, void>::value;\n  static const bool single_tensor_given = DiffusionFactorImp::dimRange != 1\n                                          && DiffusionFactorImp::dimRange == DiffusionFactorImp::dimRangeCols\n                                          && std::is_same<DiffusionTensorImp, void>::value;\n\npublic:\n  typedef typename Helper<single_factor_given, single_tensor_given>::FactorType DiffusionFactorType;\n  typedef typename Helper<single_factor_given, single_tensor_given>::TensorType DiffusionTensorType;\n  typedef LocalEllipticIntegrand<DiffusionFactorType, DiffusionTensorType> derived_type;\n  typedef std::tuple<std::shared_ptr<typename DiffusionFactorType::LocalfunctionType>,\n                     std::shared_ptr<typename DiffusionTensorType::LocalfunctionType>>\n      LocalfunctionTupleType;\n}; // class LocalEllipticIntegrandTraits\n\n\n} // namespace internal\n\n\n/**\n * \\brief Computes an elliptic evaluation.\n */\ntemplate <class DiffusionFactorImp, class DiffusionTensorImp>\nclass LocalEllipticIntegrand\n    : public LocalVolumeIntegrandInterface<internal::LocalEllipticIntegrandTraits<DiffusionFactorImp,\n                                                                                  DiffusionTensorImp>,\n                                           2>\n{\n  typedef LocalVolumeIntegrandInterface<internal::LocalEllipticIntegrandTraits<DiffusionFactorImp, DiffusionTensorImp>,\n                                        2>\n      BaseType;\n  typedef LocalEllipticIntegrand<DiffusionFactorImp, DiffusionTensorImp> ThisType;\n\npublic:\n  typedef internal::LocalEllipticIntegrandTraits<DiffusionFactorImp, DiffusionTensorImp> Traits;\n  typedef typename Traits::DiffusionFactorType DiffusionFactorType;\n  typedef typename Traits::DiffusionTensorType DiffusionTensorType;\n  typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;\n  typedef typename Traits::EntityType EntityType;\n  typedef typename Traits::DomainFieldType DomainFieldType;\n  static const size_t dimDomain = Traits::dimDomain;\n\nprivate:\n  typedef XT::Common::ConstStorageProvider<DiffusionFactorType> DiffusionFactorProvider;\n  typedef XT::Common::ConstStorageProvider<DiffusionTensorType> DiffusionTensorProvider;\n  using typename BaseType::E;\n  using typename BaseType::D;\n  using BaseType::d;\n\npublic:\n  LocalEllipticIntegrand(const DiffusionFactorType& diff_factor,\n                         const DiffusionTensorType& diff_tensor,\n                         const XT::Common::Parameter& param = {})\n    : diffusion_factor_(diff_factor)\n    , diffusion_tensor_(diff_tensor)\n    , param_(param)\n  {\n  }\n\n  LocalEllipticIntegrand(const DiffusionFactorType& diff_factor, const XT::Common::Parameter& param = {})\n    : diffusion_factor_(diff_factor)\n    , diffusion_tensor_(new DiffusionTensorType(\n          XT::Functions::internal::UnitMatrix<typename DiffusionTensorType::RangeFieldType, dimDomain>::value()))\n    , param_(param)\n  {\n  }\n\n\n  template < // This disables the ctor if dimDomain == 1, since factor and tensor are then identical and the\n      typename DiffusionType, //                                                            ctors ambiguous.\n      typename = typename std::enable_if<(std::is_same<DiffusionType, DiffusionTensorType>::value) && (dimDomain > 1)\n                                         && sizeof(DiffusionType)>::type>\n  LocalEllipticIntegrand(const DiffusionType& diffusion, const XT::Common::Parameter& param = {})\n    : diffusion_factor_(new DiffusionFactorType(1.))\n    , diffusion_tensor_(diffusion)\n    , param_(param)\n  {\n  }\n\n  /**\n   * \\attention Due to the nature of XT::Common::ConstStorageProvider, this copy may leave you with a dead reference,\n   *            if other is destructed.\n   */\n  LocalEllipticIntegrand(const ThisType& other)\n    : diffusion_factor_(other.diffusion_factor())\n    , diffusion_tensor_(other.diffusion_tensor())\n    , param_(other.param_)\n  {\n  }\n\n  LocalEllipticIntegrand(ThisType&& source) = default;\n\n  /// \\name Required by LocalVolumeIntegrandInterface< ..., 2 >\n  /// \\{\n\n  LocalfunctionTupleType localFunctions(const EntityType& entity) const\n  {\n    return std::make_tuple(diffusion_factor_.access().local_function(entity),\n                           diffusion_tensor_.access().local_function(entity));\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct order() method\n   */\n  template <class R, size_t rT, size_t rCT, size_t rA, size_t rCA>\n  size_t order(const LocalfunctionTupleType& local_functions_tuple,\n               const XT::Functions::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,\n               const XT::Functions::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base) const\n  {\n    const auto local_diffusion_factor = std::get<0>(local_functions_tuple);\n    const auto local_diffusion_tensor = std::get<1>(local_functions_tuple);\n    return order(*local_diffusion_factor, *local_diffusion_tensor, test_base, ansatz_base);\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct evaluate() method\n   */\n  template <class R, size_t rT, size_t rCT, size_t rA, size_t rCA>\n  void evaluate(const LocalfunctionTupleType& local_functions_tuple,\n                const XT::Functions::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,\n                const XT::Functions::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base,\n                const Dune::FieldVector<D, d>& localPoint,\n                Dune::DynamicMatrix<R>& ret) const\n  {\n    const auto local_diffusion_factor = std::get<0>(local_functions_tuple);\n    const auto local_diffusion_tensor = std::get<1>(local_functions_tuple);\n    evaluate(*local_diffusion_factor, *local_diffusion_tensor, test_base, ansatz_base, localPoint, ret);\n  }\n\n  /// \\}\n  /// \\name Actual implementations of order\n  /// \\{\n\n  template <class R, size_t rDF, size_t rCDF, size_t rDT, size_t rCDT, size_t rT, size_t rCT, size_t rA, size_t rCA>\n  size_t order(const XT::Functions::LocalfunctionInterface<E, D, d, R, rDF, rCDF>& local_diffusion_factor,\n               const XT::Functions::LocalfunctionInterface<E, D, d, R, rDT, rCDT>& local_diffusion_tensor,\n               const XT::Functions::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,\n               const XT::Functions::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base) const\n  {\n    return local_diffusion_factor.order() + local_diffusion_tensor.order()\n           + std::max(ssize_t(test_base.order()) - 1, ssize_t(0))\n           + std::max(ssize_t(ansatz_base.order()) - 1, ssize_t(0));\n  }\n\n  /// \\}\n  /// \\name Actual implementations of evaluate\n  /// \\{\n\n  template <class R, size_t r>\n  void evaluate(const XT::Functions::LocalfunctionInterface<E, D, d, R, 1, 1>& local_diffusion_factor,\n                const XT::Functions::LocalfunctionInterface<E, D, d, R, d, d>& local_diffusion_tensor,\n                const XT::Functions::LocalfunctionSetInterface<E, D, d, R, r, 1>& test_base,\n                const XT::Functions::LocalfunctionSetInterface<E, D, d, R, r, 1>& ansatz_base,\n                const Dune::FieldVector<D, d>& localPoint,\n                Dune::DynamicMatrix<R>& ret) const\n  {\n    typedef XT::Common::FieldMatrix<R, d, d> TensorType;\n    ret *= 0.0;\n    // evaluate local functions\n    const auto diffusion_factor_value = local_diffusion_factor.evaluate(localPoint, param_);\n    const TensorType diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint, param_);\n    const auto diffusion_value = diffusion_tensor_value * diffusion_factor_value;\n    // evaluate bases\n    const auto testGradients = test_base.jacobian(localPoint, param_);\n    const auto ansatzGradients = ansatz_base.jacobian(localPoint, param_);\n    // compute elliptic evaluation\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    for (size_t ii = 0; ii < rows; ++ii) {\n      auto& retRow = ret[ii];\n      for (size_t jj = 0; jj < cols; ++jj) {\n        for (size_t rr = 0; rr < r; ++rr) {\n          retRow[jj] += (diffusion_value * ansatzGradients[jj][rr]) * testGradients[ii][rr];\n        }\n      }\n    }\n  } // ... evaluate(...)\n\n  /// \\}\n  /// \\name Access to data functions (allows the evaluation to be used as traits handling multiple szenarios).\n  /// \\{\n\n  const DiffusionFactorType& diffusion_factor() const\n  {\n    return diffusion_factor_.access();\n  }\n\n  const DiffusionTensorType& diffusion_tensor() const\n  {\n    return diffusion_tensor_.access();\n  }\n\n  /// \\}\n\nprivate:\n  const DiffusionFactorProvider diffusion_factor_;\n  const DiffusionTensorProvider diffusion_tensor_;\n  const XT::Common::Parameter param_;\n}; // class LocalEllipticIntegrand\n\n\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_LOCAL_INTEGRANDS_ELLIPTIC_HH\n", "meta": {"hexsha": "a900d840c769cedfc34a928526fd9d55fd9ed66e", "size": 13105, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/local/integrands/elliptic.hh", "max_stars_repo_name": "tobiasleibner/dune-gdt", "max_stars_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "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/integrands/elliptic.hh", "max_issues_repo_name": "tobiasleibner/dune-gdt", "max_issues_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "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/integrands/elliptic.hh", "max_forks_repo_name": "tobiasleibner/dune-gdt", "max_forks_repo_head_hexsha": "5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3406940063, "max_line_length": 120, "alphanum_fraction": 0.6992750858, "num_tokens": 3172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.06853749921538652, "lm_q1q2_score": 0.028957412073829406}}
{"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__UTILS_HPP_\n#define SMOOTH__UTILS_HPP_\n\n#include <array>\n#include <cstddef>\n#include <functional>\n#include <numeric>\n#include <utility>\n\n#include <Eigen/Core>\n\nnamespace smooth::utils {\n\n/////////////////////\n// STATIC FOR LOOP //\n/////////////////////\n\n/**\n * @brief Compile-time for loop implementation\n */\ntemplate<typename _F, std::size_t... _Idx>\ninline static constexpr auto static_for_impl(_F && f, std::index_sequence<_Idx...>)\n{\n  return (std::invoke(f, std::integral_constant<std::size_t, _Idx>()), ...);\n}\n\n/**\n * @brief Compile-time for loop over 0, ..., _I-1\n */\ntemplate<std::size_t _I, typename _F>\ninline static constexpr auto static_for(_F && f)\n{\n  return static_for_impl(std::forward<_F>(f), std::make_index_sequence<_I>{});\n}\n\n/////////////////\n// ARRAY UTILS //\n/////////////////\n\n/**\n * @brief Prefix-sum an array starting at zero\n */\ntemplate<typename T, std::size_t L>\nconstexpr std::array<T, L + 1> array_psum(const std::array<T, L> & x)\n{\n  std::array<T, L + 1> ret;\n  ret[0] = T(0);\n  std::partial_sum(x.begin(), x.end(), ret.begin() + 1);\n  return ret;\n}\n\n///////////////////////\n// TUPLE STATE UTILS //\n///////////////////////\n\ntemplate<typename T>\nstruct tuple_dof\n{};\n\n/**\n * @brief Compile-time size of a tuple of variables.\n *\n * If at least one variable is dynamically sized (size -1), this returns -1.\n */\ntemplate<typename... Wrt>\nstruct tuple_dof<std::tuple<Wrt...>>\n{\n  static constexpr int value = std::min<int>({std::decay_t<Wrt>::SizeAtCompileTime...}) == -1\n                               ? std::min<int>({std::decay_t<Wrt>::SizeAtCompileTime...})\n                               : (std::decay_t<Wrt>::SizeAtCompileTime + ...);\n};\n\n/**\n * @brief Cast a tuple of variables to a new scalar type.\n */\ntemplate<typename Scalar, typename... _Wrt>\nauto tuple_cast(const std::tuple<_Wrt...> & wrt)\n{\n  std::tuple<\n    typename std::decay_t<decltype(std::decay_t<_Wrt>{}.template cast<Scalar>())>::PlainObject...>\n    ret;\n  static_for<sizeof...(_Wrt)>(\n    [&](auto i) { std::get<i>(ret) = std::get<i>(wrt).template cast<Scalar>(); });\n  return ret;\n}\n\n/**\n * @brief Add a tangent vector to a tuple of variables.\n */\ntemplate<typename Derived, typename... _Wrt>\nauto tuple_plus(const std::tuple<_Wrt...> & wrt, const Eigen::MatrixBase<Derived> & a)\n{\n  std::tuple<typename std::decay_t<_Wrt>::PlainObject...> ret;\n  std::size_t i_beg = 0;\n  static_for<sizeof...(_Wrt)>([&](auto i) {\n    constexpr auto i_size =\n      std::tuple_element_t<i, std::tuple<std::decay_t<_Wrt>...>>::SizeAtCompileTime;\n    std::size_t i_len = std::get<i>(wrt).size();\n    std::get<i>(ret)  = std::get<i>(wrt) + a.template segment<i_size>(i_beg, i_len);\n    i_beg += i_len;\n  });\n  return ret;\n}\n\n/**\n * @brief Trait for removing const-ness from reference types.\n */\ntemplate<typename T>\nstruct remove_const_ref\n{\n  using type = T;\n};\n\ntemplate<typename T>\nstruct remove_const_ref<const T &>\n{\n  using type = T;\n};\n\n/**\n * @brief Copy a tuple to make all elements modifiable.\n *\n * Copies are created form const & members, rest is forwarded.\n */\ntemplate<typename... T>\nstd::tuple<typename remove_const_ref<T>::type...> tuple_copy_if_const(std::tuple<T...> && in)\n{\n  return std::make_from_tuple<std::tuple<typename remove_const_ref<T>::type...>>(std::move(in));\n}\n\n/**\n * @brief Copy a tuple to make all elements modifiable.\n *\n * Copies are created form const & members, rest is forwarded.\n */\ntemplate<typename... T>\nauto tuple_copy_if_const(const std::tuple<T...> & in)\n{\n  return std::make_from_tuple<std::tuple<typename remove_const_ref<T>::type...>>(in);\n}\n\n/////////////////////////////////\n// COMPILE-TIME MATRIX ALGEBRA //\n/////////////////////////////////\n\n/**\n * @brief Elementary structure for compile-time matrix algebra\n */\ntemplate<typename _Scalar, std::size_t _Rows, std::size_t _Cols>\nstruct StaticMatrix : public std::array<std::array<_Scalar, _Cols>, _Rows>\n{\n  std::size_t Rows = _Rows;\n  std::size_t Cols = _Cols;\n\n  using std::array<std::array<_Scalar, _Cols>, _Rows>::operator[];\n\n  /**\n   * @brief Construct a matrix filled with zeros\n   */\n  constexpr StaticMatrix() : std::array<std::array<_Scalar, _Cols>, _Rows>{}\n  {\n    for (auto i = 0u; i != _Rows; ++i) { operator[](i).fill(_Scalar(0)); }\n  }\n\n  /**\n   * @brief Add two matrices\n   */\n  constexpr StaticMatrix<_Scalar, _Rows, _Cols> operator+(\n    StaticMatrix<_Scalar, _Rows, _Cols> o) const\n  {\n    StaticMatrix<_Scalar, _Rows, _Cols> ret;\n    for (auto i = 0u; i < _Rows; ++i) {\n      for (auto j = 0u; j < _Cols; ++j) { ret[i][j] = operator[](i)[j] + o[i][j]; }\n    }\n    return ret;\n  }\n\n  /**\n   * @brief Return transpose of a matrix\n   */\n  constexpr StaticMatrix<_Scalar, _Rows, _Cols> transpose() const\n  {\n    StaticMatrix<_Scalar, _Rows, _Cols> ret;\n    for (auto i = 0u; i < _Rows; ++i) {\n      for (auto j = 0u; j < _Cols; ++j) { ret[j][i] = operator[](i)[j]; }\n    }\n    return ret;\n  }\n\n  /**\n   * @brief Multiply two matrices\n   */\n  template<std::size_t _ColsNew>\n  constexpr StaticMatrix<_Scalar, _Rows, _ColsNew> operator*(\n    StaticMatrix<_Scalar, _Cols, _ColsNew> o) const\n  {\n    StaticMatrix<_Scalar, _Rows, _ColsNew> ret;\n    for (auto i = 0u; i < _Rows; ++i) {\n      for (auto j = 0u; j < _ColsNew; ++j) {\n        for (auto k = 0u; k < _Cols; ++k) { ret[i][j] += operator[](i)[k] * o[k][j]; }\n      }\n    }\n    return ret;\n  }\n};\n\n}  // namespace smooth::utils\n\n#endif  // SMOOTH__UTILS_HPP_\n", "meta": {"hexsha": "bf38838cc88b3ac6cdb301a236aaee01f0be7965", "size": 6689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/utils.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/internal/utils.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/internal/utils.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": 28.4638297872, "max_line_length": 98, "alphanum_fraction": 0.6394079833, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141883, "lm_q2_score": 0.06853748875117771, "lm_q1q2_score": 0.02895740665589788}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2014 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 <comma/base/exception.h>\n#include \"polytope.h\"\n\nnamespace snark{ namespace geometry {\n\nconst Eigen::MatrixXd& convex_polytope::normals() const { return normals_; }\n    \nconst Eigen::VectorXd& convex_polytope::offsets() const { return offsets_; }\n\nconvex_polytope::convex_polytope( const std::vector< Eigen::VectorXd >& normals, const std::vector< double >& offsets )\n{\n    if(!normals.size() || normals[0].size()) { COMMA_THROW( comma::exception, \"normals size cannot be zero\" ); }\n    if(normals.size()!=offsets.size()) { COMMA_THROW( comma::exception, \"normals and offsets should be of same size, got \"<< normals.size()<<\" and \"<<offsets.size() ); }\n    normals_.resize(normals.size(),normals[0].size());\n    offsets_.resize(offsets.size());\n    for(unsigned int i=0; i<normals.size(); ++i )\n    {\n        normals_.row(i)=normals[i].transpose();\n        offsets_(i)=offsets[i];\n    }\n}\n\nconvex_polytope::convex_polytope( const Eigen::MatrixXd& normals, const Eigen::VectorXd& offsets )\n    : normals_( normals )\n    , offsets_( offsets )\n{\n    if(!normals.size()) { COMMA_THROW( comma::exception, \"normals size cannot be zero\" ); }\n    if(normals.rows()!=offsets.rows()) { COMMA_THROW( comma::exception, \"normals and offsets should be of same size, got \"<< normals.rows()<<\" and \"<<offsets.rows() ); }\n}\n\nconvex_polytope::convex_polytope( const Eigen::MatrixXd& planes )\n{\n    if(!planes.rows() || planes.cols() < 2) { COMMA_THROW( comma::exception, \"planes rows cannot be zero and cols must be at least two, got \"<<planes.rows()<<\" and \"<<planes.cols() ); }\n    normals_=planes.leftCols( static_cast< unsigned int >( planes.cols() - 1 ) );\n    offsets_=planes.rightCols(1);\n}\n\n//static Eigen::VectorXd symmat2vec(const Eigen::MatrixXd& A)\n//{\n//    unsigned int n = A.rows();\n//    Eigen::VectorXd v( n * ( n + 1 ) / 2 );\n//    unsigned int m = 0;\n//    for( unsigned int i=0; i<n; ++i )\n//    {\n//        for( unsigned int j = 0; j <= i; v(m) = A(i,j), ++j, ++m );\n//    }\n//    return v;\n//}\n\n//static Eigen::VectorXd symmat2vec(const Eigen::MatrixXd& A)\n//{\n//    int n=A.rows();\n//    Eigen::VectorXd v(n*(n+1)/2);\n\n//    for(int i=0; i<n; i++)\n//    {\n//        for(int j=0; j<=i; j++)\n//        {\n//            v(i*(i+1)/2+j)=A(i,j);\n//        }\n//    }\n//    return v;\n//}\n// This function uses the SDP solver provided by the DSDP library\n// It reformulates the problem of finding whether a point is inside a convex polygon as an SDP (Semi-Definite Program)\n// Problem:\n// min ||y-x||^2 s.t. Ay<=b\n// SDP Formulation:\n// [I y-x; (y-xy)' t] is psd\n// diag(b)-y1*A1-...-yn*An is psd\n\n/// This function checks whether a point is inside a convex polytope: Ay<=b\nbool convex_polytope::has(const Eigen::VectorXd &x)\n{\n    int dimx=x.size();\n    if(dimx!=normals_.cols())\n    {\n        COMMA_THROW( comma::exception, \"point should be of same dimension as polytope, polytope dimension: \"<<normals_.cols()<<\" point dimension: \"<<dimx );\n    }\n\n    const Eigen::MatrixXd& A=normals_;\n    const Eigen::VectorXd& b=offsets_;\n\n    Eigen::VectorXd d=A*x-b;\n\n    return((d.array()>=0).all());\n\n//    int nofaces=A.rows();\n\n//    tolerance=tolerance*tolerance; //square tolerance\n\n//    DSDP solver;\n//    DSDPCreate(dimx+1,&solver);\n\n\n//    for(int cntr=1; cntr<=dimx; cntr++)\n//    {\n//        DSDPSetDualObjective(solver,cntr,0);\n//    }\n//    DSDPSetDualObjective(solver,dimx+1,-1); // objective is inverted\n\n//    SDPCone cone;\n//    DSDPCreateSDPCone(solver,2,&cone);\n\n//    Eigen::MatrixXd A0(nofaces,nofaces);\n//    Eigen::MatrixXd A1(dimx+1,dimx+1);\n\n//    std::vector< Eigen::VectorXd > a0(dimx+2);\n//    std::vector< Eigen::VectorXd > a1(dimx+2);\n\n//    //constant terms\n//    A0.setZero();\n//    A1.setZero();\n//    A0=b.asDiagonal();A0=-A0;\n//    A1.block(0,0,dimx,dimx)=Eigen::MatrixXd::Identity(dimx,dimx);\n//    A1.block(0,dimx,dimx,1)=-x;\n//    A1.block(dimx,0,1,dimx)=-x.transpose();\n//    a0[0] = Eigen::VectorXd(symmat2vec(A0));\n//    a1[0] = Eigen::VectorXd(symmat2vec(A1));\n//    SDPConeSetADenseVecMat(cone,0,0,nofaces,1.0,a0[0].data(),a0[0].size());\n//    SDPConeSetADenseVecMat(cone,1,0,dimx+1,1.0,a1[0].data(),a1[0].size());\n\n\n//    //yi's, A's are negated\n//    for(int cntr=0; cntr<dimx; cntr++)\n//    {\n//        A0.setZero();\n//        A1.setZero();\n//        A0=A.col(cntr).asDiagonal();\n//        A1(dimx,cntr)=1;\n//        A1(cntr,dimx)=1;\n//        a0[cntr+1] = Eigen::VectorXd(symmat2vec(-A0));\n//        a1[cntr+1] = Eigen::VectorXd(symmat2vec(-A1));\n//        SDPConeSetADenseVecMat(cone,0,cntr+1,nofaces,1.0,a0[cntr+1].data(),a0[cntr+1].size());\n//        SDPConeSetADenseVecMat(cone,1,cntr+1,dimx+1,1.0,a1[cntr+1].data(),a1[cntr+1].size());\n//    }\n\n//    //t\n//    A0.setZero();\n//    A1.setZero();\n//    A1(dimx,dimx)=1;\n//    a0[dimx+1] = Eigen::VectorXd(symmat2vec(-A0));\n//    a1[dimx+1] = Eigen::VectorXd(symmat2vec(-A1));\n//    SDPConeSetADenseVecMat(cone,0,dimx+1,nofaces,1.0,a0[dimx+1].data(),a0[dimx+1].size());\n//    SDPConeSetADenseVecMat(cone,1,dimx+1,dimx+1,1.0,a1[dimx+1].data(),a1[dimx+1].size());\n\n// //    DSDPSetY0(solver,1,1);\n// //    DSDPSetY0(solver,2,1);\n// //    DSDPSetY0(solver,3,1);\n// //    DSDPSetY0(solver,4,10);\n// //    SDPConeViewDataMatrix(cone,1,1);\n// //    std::cout<<std::endl;\n// //    SDPConeViewDataMatrix(cone,1,2);\n// //    std::cout<<std::endl;\n// //    SDPConeViewDataMatrix(cone,1,3);\n// //    std::cout<<std::endl;\n// //    SDPConeViewDataMatrix(cone,1,4);\n// //    std::cout<<std::endl;\n\n//    DSDPSetup(solver);\n//    DSDPSetGapTolerance(solver,1e-10);\n// //    DSDPSetStandardMonitor(solver,1);\n//    DSDPSolve(solver);\n\n// //    DSDPTerminationReason reason;\n// //    DSDPStopReason(solver,&reason);\n// //    std::cout<<\"reason: \"<<reason<<std::endl;\n\n//    Eigen::VectorXd y(dimx+1);\n\n//    DSDPGetY(solver,y.data(),y.size());\n\n// //    Eigen::VectorXd smat((dimx+1)*(dimx+2)/2);\n// //    SDPConeComputeS(cone,1,1, y.data(), y.size(), 0, dimx+1, smat.data(), smat.size());\n// //    Eigen::MatrixXd S=vec2symmat(smat);\n// //    std::cout<<S<<std::endl;\n// //    std::cout<<y<<std::endl;\n\n//    double t=y(dimx);\n//    return(t<tolerance);\n}\n\n}} // namespace snark{ { namespace geometry {\n", "meta": {"hexsha": "116fe5a85e89e339714b114f2ad454650ccf3da7", "size": 7988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/geometry/polytope.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/geometry/polytope.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/geometry/polytope.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": 36.9814814815, "max_line_length": 185, "alphanum_fraction": 0.639334001, "num_tokens": 2456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015862011227, "lm_q2_score": 0.06187599134596675, "lm_q1q2_score": 0.02876624652450688}}
{"text": "#ifndef N_BODY_SPACE_HPP\n#define N_BODY_SPACE_HPP\n\n#include \"communication.hpp\"\n#include \"data.hpp\"\n#include \"logging.hpp\"\n#include <algorithm>\n#include <boost/mpi.hpp>\n#include <cstddef>\n#include <limits>\n\nnamespace n_body::space {\n\ntemplate <typename T, std::size_t Dimension>\ndata::Space<T, Dimension> root_space(const boost::mpi::communicator &comm,\n                                     const data::Bodies<T, Dimension> &bodies) {\n  communication::Division division(comm, bodies.size());\n\n  T min = std::numeric_limits<T>::max();\n  T max = std::numeric_limits<T>::min();\n\n  for (auto i = division.begin; i < division.end; ++i) {\n    for (std::size_t d = 0; d < Dimension; ++d) {\n      if (bodies[i].position[d] < min)\n        min = bodies[i].position[d];\n      if (bodies[i].position[d] > max)\n        max = bodies[i].position[d];\n    }\n  }\n\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    boost::mpi::all_reduce(comm, boost::mpi::inplace(min),\n                           boost::mpi::minimum<T>());\n    boost::mpi::all_reduce(comm, boost::mpi::inplace(max),\n                           boost::mpi::maximum<T>());\n  }\n  data::Space<T, Dimension> space{};\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    space.min[d] = min;\n    space.max[d] = max;\n    space.center[d] = (max + min) / 2;\n  }\n  return space;\n}\n\n// TODO infer T and Dimension\ntemplate <typename T, std::size_t Dimension, typename Iter>\ndata::Space<T, Dimension> root_space(Iter first, Iter last) {\n\n  T min = std::numeric_limits<T>::max();\n  T max = std::numeric_limits<T>::min();\n\n  for (; first != last; ++first) {\n    for (std::size_t d = 0; d < Dimension; ++d) {\n      if (first->position[d] < min)\n        min = first->position[d];\n      if (first->position[d] > max)\n        max = first->position[d];\n    }\n  }\n\n  data::Space<T, Dimension> space{};\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    space.min[d] = min;\n    space.max[d] = max;\n    space.center[d] = (max + min) / 2;\n  }\n  return space;\n}\n\ntemplate <typename T, std::size_t Dimension>\ndata::Space<T, Dimension> subspace(const data::Space<T, Dimension> &space,\n                                   std::size_t part) {\n  data::Space<T, Dimension> result{};\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    auto is_negative = part & 0b1u;\n    part >>= 1u;\n\n    if (is_negative == 0) {\n      result.max[d] = space.max[d];\n      result.min[d] = space.center[d];\n    } else {\n      result.max[d] = space.center[d];\n      result.min[d] = space.min[d];\n    }\n    result.center[d] = (result.max[d] + result.min[d]) / 2;\n  }\n\n  return result;\n}\n\ntemplate <typename T, std::size_t Dimension>\nbool contains(const data::Space<T, Dimension> &space,\n              data::Vector<T, Dimension> position) {\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    if (position[d] < space.min[d] || position[d] > space.max[d]) {\n      return false;\n    }\n  }\n  return true;\n}\n\n// determine which part of the space does the position belong to\n// use binary to encode the part\ntemplate <typename T, std::size_t Dimension>\nstd::size_t part_of_space(const data::Space<T, Dimension> &space,\n                          data::Vector<T, Dimension> position) {\n  static_assert(\n      std::numeric_limits<std::size_t>::radix == 2,\n      \"the radix of std::size_t must be 2 to make the algorithm working\");\n  static_assert(Dimension <= std::numeric_limits<std::size_t>::digits,\n                \"the dimension is too big for std::size_t to represent parts \"\n                \"of the space\");\n\n  std::size_t result = 0;\n  for (std::size_t i = Dimension; i > 0; --i) {\n    result <<= 1u;\n    auto d = i - 1;\n    if (position[d] < space.center[d]) {\n      result |= 0b1u;\n    }\n  }\n  return result;\n}\n\ntemplate <typename T, std::size_t Dimension>\nstd::size_t size_of_space(const data::Space<T, Dimension> &space) {\n  return space.max[0] - space.min[0];\n}\n\ntemplate <typename T, std::size_t Dimension>\nvoid extend_to_contain(data::Space<T, Dimension> &space,\n                       const data::Space<T, Dimension> &other) {\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    bool changed = false;\n    if (other.max[d] > space.max[d]) {\n      space.max[d] = other.max[d];\n      changed = true;\n    }\n    if (other.min[d] < space.min[d]) {\n      space.min[d] = other.min[d];\n      changed = true;\n    }\n    if (changed) {\n      space.center[d] = (space.max[d] + space.min[d]) / 2;\n    }\n  }\n}\n\n}; // namespace n_body::space\n\n#endif\n", "meta": {"hexsha": "e87b6906a5568355f460e7375cf1e02ba686f3c0", "size": 4435, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/space.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/space.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/space.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": 28.9869281046, "max_line_length": 80, "alphanum_fraction": 0.5851183766, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.06187598745358852, "lm_q1q2_score": 0.028766244714934074}}
{"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_COLLECTION_INCLUDE\n#define MTL_COLLECTION_INCLUDE\n\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <vector>\n\n#ifdef __GXX_CONCEPTS__\n#  include <concepts>\n#else \n#  include <boost/numeric/linear_algebra/pseudo_concept.hpp>\n#  include <boost/numeric/mtl/concept/std_concept.hpp>\n#endif\n\n#include <boost/numeric/mtl/utility/transposed_orientation.hpp>\n\nnamespace mtl {\n\n/** @addtogroup Concepts\n *  @{\n */\n\n#ifdef __GXX_CONCEPTS__\n    auto concept Collection<typename T>\n    {\n\ttypename value_type;\n\ttypename const_reference;\n\ttypename size_type;\n    };\n#else\n    /// Concept Collection\n    template <typename T>\n    struct Collection\n    {\n\t/// Associated type: elements in the collection\n\ttypedef associated_type value_type;\n\n\t/// Associated type: return type of const element access (however implemented)\n\ttypedef associated_type const_reference;\n\n\t/// Associated type: size type used for indexing in collection\n\ttypedef associated_type size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept MutableCollection<typename T>\n      : Collection<T>\n    {\n\ttypename reference;\n    }\n#else\n    /// Concept MutableCollection\n    template <typename T>\n    struct MutableCollection\n\t: public Collection<T>\n    {\n\t/// Associated type: return type of non-const element access (however implemented)\n\ttypedef associated_type reference;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    concept ConstantSizeCollection<typename T>\n      : Collection<T>\n    {};\n#else\n    /// Concept ConstantSizeCollection: size parameters of collection are completely given at compile time\n    /* Which parameters determine collection size depends on type of collection, e.g. different for vector and matrix\n       \\par Refinement of:\n       - Collection < T >\n    */\n    template <typename T>\n    struct ConstantSizeCollection\n\t: Collection<T>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept AlgebraicCollection<typename T>\n      : Collection<T>\n    {\n\tsize_type num_rows(T);\n\tsize_type num_cols(T);\n\tsize_type size(T);\n    };\n#else\n    /// Concept AlgebraicCollection: common requirements of matrices, vectors, and scalars in computations\n    /** For more design clarity we consider them all as matrices (as Matlab does) and we regard \n\tScalar and Vector as special cases (see there).  However, the implementation of vectors\n\tis supposed to differ from the ones of matrices in order to provide efficient computations and storage.\n        \\par Refinement of:\n\t- Collection < T >\n\t\\par Notation:\n\t- X is a type that models AlgebraicCollection\n\t- x is an object of type X\n\t\\par Valid expressions:\n\t- Number of rows: \\n num_rows(x) \\n Return Type: size_type\n\t- Number of columns: \\n num_cols(x) \\n Return Type: size_type\n\t- Number of elements: \\n size(x) \\n Return Type: size_type\n\t  \\n Sematics: num_rows(x) * num_cols(x) (but possibly faster implemented)\n    */\n    template <typename T>\n    struct AlgebraicCollection\n\t: public Collection<T>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept ConstantSizeAlgebraicCollection<typename T>\n      : AlgebraicCollection<T>,\n        ConstantSizeCollection<T>\n    {\n#if 0\n\t// Is there a way to require static members????\n\tstatic Collection<T>::size_type T::static_num_rows;\n\tstatic Collection<T>::size_type T::static_num_cols;\n\tstatic Collection<T>::size_type T::static_size;\n#endif \n    };\n#else\n    /// Concept ConstantSizeAlgebraicCollection: extension of AlgebraicCollection with meta-functions\n    /** This concept is used for algebraic collections with sizes known at compile time. \n\tThe motivation is that if the size of the collection is\n\tis small, arithmetic operations can be unrolled at compile time.\n\n        \\par Refinement of:\n\t- Collection < T >\n\t\\par Notation:\n\t- X is a type that models ConstantSizeAlgebraicCollection\n\t- x is an object of type X\n\t\\par Valid expressions:\n\t- Number of rows: \\n static_num_rows<X>::value\n\t- Number of columns: \\n static_num_cols<X>::value\n\t- Number of elements: \\n static_size<X>::value\n\t  \\n Sematics: static_num_rows<X>::value * static_size<X>::value\n\t\\note\n\t-# For more design clarity we consider them all as matrices (as Matlab does) and we regard \n\t   Scalar and Vector as special cases (see there).  However, the implementation of vectors\n\t   is supposed to differ from the ones of matrices in order to provide efficient computations and storage.\n\n    */\n    template <typename T>\n    struct ConstantSizeAlgebraicCollection\n      : public AlgebraicCollection<T>,\n        public ConstantSizeCollection<T>\n    {\n\t/// Associated type: meta-function for number of rows\n\ttypedef associated_type static_num_rows;\n\t/// Associated type: meta-function for number of columns\n\ttypedef associated_type static_num_cols;\n\t/// Associated type: meta-function for number of elements\n\ttypedef associated_type static_size;\n    };\n#endif\n\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept TraversableCollection<typename Tag, typename C>\n      : Collection<C>\n    {\n#if 0\n\t// This might be impossible to declare with concepts\n\ttypename cursor_type;\n\n\tcursor_type begin<Tag>(const C& c);\n\tcursor_type   end<Tag>(const C& c);\n#endif\n\n\t// Maybe we switch to this syntax for the sake of concepts\n\ttypename cursor_type;\n\n\tcursor_type begin(const C& c, Tag);\n\tcursor_type   end(const C& c, Tag);\n    }\n#else\n    /// Concept TraversableCollection: collections that can be traversed by cursor or iterator\n    template <typename Tag, typename C>\n    struct TraversableCollection\n\t: public Collection<C>\n    {\n\t/// Associated type: return type of tagged begin and end function\n\ttypedef associated_type cursor_type;\n\n\t/// Tagged free function that returns a cursor or iterator at the begin of an interval \n\t/** The interval is specified by the Tag, i.e. the function is called begin<Tag>(c); */\n\tcursor_type begin(const C& c);\n\n\t/// Tagged free function that returns a cursor or iterator at the end of an interval \n\t/** The interval is specified by the Tag, i.e. the function is called end<Tag>(c);  */\n\tcursor_type end(const C& c);\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept TraversableMutableCollection<typename Tag, typename C>\n      : MutableCollection<C>\n    {\n#if 0\n\ttypename cursor_type;\n\n\tcursor_type begin<Tag>(C& c);\n\tcursor_type   end<Tag>(C& c);\n#endif\n\n\t// Maybe we switch to this syntax for the sake of concepts\n\ttypename cursor_type;\n\n\tcursor_type begin(C& c, Tag);\n\tcursor_type   end(C& c, Tag);\n    }\n#else\n    /// Concept TraversableMutableCollection: collections that can be traversed by (mutable) iterator\n    template <typename Tag, typename C>\n    struct TraversableMutableCollection\n\t: public MutableCollection<C>\n    {\n\t/// Associated type: return type of tagged begin function\n\ttypedef associated_type cursor_type;\n\n\t/// Tagged free function that returns a cursor or iterator at the begin of an interval \n\t/** The interval is specified by the Tag, i.e. the function is called begin<Tag>(c); */\n\tcursor_type begin(const C& c);\n\n\t/// Tagged free function that returns a cursor or iterator at the end of an interval \n\t/** The interval is specified by the Tag, i.e. the function is called end<Tag>(c);  */\n\tcursor_type end(const C& c);\n    };\n#endif\n\n\n\n\n#ifdef __GXX_CONCEPTS__\n#if 0\n    concept CategorizedType<typename T>\n    {\n\ttypedef associated_type type;\n    };\n#endif\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    concept OrientedCollection<typename T>\n      : Collection<T>\n    {\n\ttypename orientation;\n\n    };\n#else\n    /// Concept OrientedCollection: collections with concept-awareness in terms of associated type\n    /** Concept-awareness is given for matrices as well as for vectors consistent to the unification in\n\tAlgebraicCollection. The orientation of vectors determines whether it is a row or a column vector.\n\tThe orientation of matrices only characterizes the internal representation and has no semantic consequences.\n        \\par Refinement of:\n\t- Collection < T >\n\t\\par Associated type:\n\t- orientation\n    */\n    template <typename T>\n    struct OrientedCollection\n      : public Collection<T>\n    {\n\t/// Associated type for orientation; by default identical with member type\n\ttypedef typename T::orientation orientation;\n    };\n#endif\n\n\n\n\n\n\n\n// ============================================\n// Concept maps (and emulations as type traits)\n// ============================================\n\n#ifdef __GXX_CONCEPTS__\n    // Needs redefinition in refinements (at least in conceptg++)\n    // -> as a consequence we define it directly there\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mtl::mat::dense2D<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n        // Alleged ambiguity with mtl::tag::dense2D on MSVC\n        typedef typename mtl::mat::dense2D<Value, Parameters>::size_type size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename Value, std::size_t Mask, typename Parameters>\n    struct Collection<mtl::mat::morton_dense<Value, Mask, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename Parameters::size_type size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value, typename Parameters>\n    concept_map Collection<mtl::mat::compressed2D<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef Value            const_reference;\n\ttypedef typename mtl::mat::compressed2D<Value, Parameters>::size_type size_type;\n    };\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mtl::mat::compressed2D<Value, Parameters> >\n    {\n\ttypedef Value            \t       value_type;\n\ttypedef Value            \t       const_reference;\n\ttypedef typename Parameters::size_type size_type;\n    };\n\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mtl::mat::coordinate2D<Value, Parameters> >\n    {\n\ttypedef Value            \t       value_type;\n\ttypedef Value            \t       const_reference;\n\ttypedef typename Parameters::size_type size_type;\n    };\n\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mtl::mat::sparse_banded<Value, Parameters> >\n    {\n\ttypedef Value            \t       value_type;\n\ttypedef Value            \t       const_reference;\n\ttypedef typename Parameters::size_type size_type;\n    };\n\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Vector>\n    concept_map Collection<mtl::mat::multi_vector<Vector> >\n    {\n\ttypedef typename mtl::mat::multi_vector<Vector>::value_type       value_type;\n\ttypedef typename mtl::mat::multi_vector<Vector>::const_reference  const_reference;\n\ttypedef typename mtl::mat::multi_vector<Vector>::size_type        size_type;\n    };\n#else\n    template <typename Vector>\n    struct Collection<mtl::mat::multi_vector<Vector> >\n    {\n\ttypedef typename mtl::mat::multi_vector<Vector>::value_type       value_type;\n\ttypedef typename mtl::mat::multi_vector<Vector>::const_reference  const_reference;\n\ttypedef typename mtl::mat::multi_vector<Vector>::size_type        size_type;\n    };\n\n#endif\n\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Vector>\n    concept_map Collection<mtl::mat::multi_vector_range<Vector> >\n    {\n\ttypedef typename mtl::mat::multi_vector_range<Vector>::value_type       value_type;\n\ttypedef typename mtl::mat::multi_vector_range<Vector>::const_reference  const_reference;\n\ttypedef typename mtl::mat::multi_vector_range<Vector>::size_type        size_type;\n    };\n#else\n    template <typename Vector>\n    struct Collection<mtl::mat::multi_vector_range<Vector> >\n    {\n\ttypedef typename mtl::mat::multi_vector_range<Vector>::value_type       value_type;\n\ttypedef typename mtl::mat::multi_vector_range<Vector>::const_reference  const_reference;\n\ttypedef typename mtl::mat::multi_vector_range<Vector>::size_type        size_type;\n    };\n\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Value>\n    struct Collection<mat::element_structure<Value> >\n    {\n\ttypedef Value            value_type;\n      // typedef Value            const_reference;\n      // typedef typename mtl::mat::compressed2D<Value, Parameters>::size_type size_type;\n    };\n\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mat::ell_matrix<Value, Parameters> >\n    {\n\ttypedef Value            \t       value_type;\n\ttypedef Value            \t       const_reference;\n\ttypedef typename Parameters::size_type size_type;\n    };\n\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Scaling, typename Coll>\n    concept_map Collection<mat::scaled_view<Scaling, Coll> >\n    {\n\ttypedef typename mat::scaled_view<Scaling, Coll>::value_type        value_type;\n\ttypedef typename mat::scaled_view<Scaling, Coll>::const_reference   const_reference;\n\ttypedef typename mat::scaled_view<Scaling, Coll>::size_type         size_type;\n    };\n#else\n    template <typename Scaling, typename Coll>\n    struct Collection<mat::scaled_view<Scaling, Coll> >\n    {\n\ttypedef typename mat::scaled_view<Scaling, Coll>::value_type        value_type;\n\ttypedef typename mat::scaled_view<Scaling, Coll>::const_reference   const_reference;\n\ttypedef typename mat::scaled_view<Scaling, Coll>::size_type         size_type;\n    };\n#endif\n\n// added by Hui Li\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll, typename RScaling>\n    concept_map Collection<mat::rscaled_view<Coll,RScaling> >\n    {\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::value_type        value_type;\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::const_reference   const_reference;\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::size_type         size_type;\n    };\n#else\n    template <typename Coll, typename RScaling>\n    struct Collection<mat::rscaled_view<Coll,RScaling> >\n    {\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::value_type        value_type;\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::const_reference   const_reference;\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::size_type         size_type;\n    };\n#endif\n\t\n\n\n#ifdef __GXX_CONCEPTS__\n    // template <typename Functor, typename Coll>\n    // concept_map Collection< vec::map_view<Functor, Coll> >\n    // {\n    // \ttypedef typename vec::map_view<Functor, Coll>::value_type        value_type;\n    // \ttypedef typename vec::map_view<Functor, Coll>::const_reference   const_reference;\n    // \ttypedef typename vec::map_view<Functor, Coll>::size_type         size_type;\n    // };\n#else\n    template <typename Functor, typename Coll>\n    struct Collection< vec::map_view<Functor, Coll> >\n    {\n\t// typedef typename Functor::result_type              value_type;\n\t// typedef typename Functor::result_type              const_reference;\n\t// typedef typename Collection<Coll>::size_type     size_type;\n\t\n\ttypedef typename vec::map_view<Functor, Coll>::value_type        value_type;\n\ttypedef typename vec::map_view<Functor, Coll>::const_reference   const_reference;\n\ttypedef typename vec::map_view<Functor, Coll>::size_type         size_type;\n    };\n#endif\n\n\t\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename Scaling, typename Coll>\n    struct Collection<vec::scaled_view<Scaling, Coll> >\n      : Collection< vec::map_view<tfunctor::rscale<typename Collection<Coll>::value_type, Scaling>, Coll> >\n    {\n\t// typedef typename vec::scaled_view<Scaling, Coll>::value_type        value_type;\n\t// typedef typename vec::scaled_view<Scaling, Coll>::const_reference   const_reference;\n\t// typedef typename vec::scaled_view<Scaling, Coll>::size_type         size_type;\n    };\n#endif\n\n\n\n// added by Hui Li\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll, typename RScaling>\n    concept_map Collection<vec::rscaled_view<Coll,RScaling> >\n    {\n\ttypedef typename vec::rscaled_view<Coll,RScaling>::value_type        value_type;\n\ttypedef typename vec::rscaled_view<Coll,RScaling>::const_reference   const_reference;\n\ttypedef typename vec::rscaled_view<Coll,RScaling>::size_type         size_type;\n    };\n#else\n    template <typename Coll, typename RScaling>\n    struct Collection<vec::rscaled_view<Coll,RScaling> >\n      : Collection< vec::map_view<tfunctor::rscale<typename Collection<Coll>::value_type, RScaling>, Coll> >\n    {\n\t// typedef typename vec::rscaled_view<Coll,RScaling>::value_type        value_type;\n\t// typedef typename vec::rscaled_view<Coll,RScaling>::const_reference   const_reference;\n\t// typedef typename vec::rscaled_view<Coll,RScaling>::size_type         size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map Collection<vec::conj_view<Coll> >\n    {\n\ttypedef typename vec::conj_view<Coll>::value_type        value_type;\n\ttypedef typename vec::conj_view<Coll>::const_reference   const_reference;\n\ttypedef typename vec::conj_view<Coll>::size_type         size_type;\n    };\n#else\n    template <typename Coll>\n    struct Collection<vec::conj_view<Coll> >\n    {\n\ttypedef typename vec::conj_view<Coll>::value_type        value_type;\n\ttypedef typename vec::conj_view<Coll>::const_reference   const_reference;\n\ttypedef typename vec::conj_view<Coll>::size_type         size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Coll>\n    struct Collection<vec::real_view<Coll> >\n    {\n\ttypedef typename vec::real_view<Coll>::value_type        value_type;\n\ttypedef typename vec::real_view<Coll>::const_reference   const_reference;\n\ttypedef typename vec::real_view<Coll>::size_type         size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Coll>\n    struct Collection<vec::imag_view<Coll> >\n    {\n\ttypedef typename vec::imag_view<Coll>::value_type        value_type;\n\ttypedef typename vec::imag_view<Coll>::const_reference   const_reference;\n\ttypedef typename vec::imag_view<Coll>::size_type         size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map Collection<vec::negate_view<Coll> >\n    {\n\ttypedef typename vec::negate_view<Coll>::value_type        value_type;\n\ttypedef typename vec::negate_view<Coll>::const_reference   const_reference;\n\ttypedef typename vec::negate_view<Coll>::size_type         size_type;\n    };\n#else\n    template <typename Coll>\n    struct Collection<vec::negate_view<Coll> >\n    {\n\ttypedef typename vec::negate_view<Coll>::value_type        value_type;\n\ttypedef typename vec::negate_view<Coll>::const_reference   const_reference;\n\ttypedef typename vec::negate_view<Coll>::size_type         size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <class E1, class E2, typename SFunctor>\n    struct Collection< vec::vec_scal_aop_expr<E1, E2, SFunctor> >\n    {\n\ttypedef typename Collection<E1>::value_type                   value_type;\n\ttypedef value_type                                            const_reference;\n\ttypedef typename Collection<E1>::size_type                    size_type; \n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <class E1, class E2>\n    struct Collection<vec::vec_scal_asgn_expr<E1, E2> >\n      : Collection< vec::vec_scal_aop_expr<E1, E2, mtl::sfunctor::assign<typename Collection<E1>::value_type, E2> > >\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <unsigned BSize, typename Vector>\n    struct Collection<vec::unrolled1<BSize, Vector> >\n    {\n\ttypedef typename Collection<Vector>::value_type value_type;\n\ttypedef value_type                              const_reference;\n\ttypedef typename Collection<Vector>::size_type  size_type;\n    };\n#endif\n\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map Collection<mat::conj_view<Coll> >\n    {\n\ttypedef typename mat::conj_view<Coll>::value_type        value_type;\n\ttypedef typename mat::conj_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::conj_view<Coll>::size_type         size_type;\n    };\n#else\n    template <typename Coll>\n    struct Collection<mat::conj_view<Coll> >\n    {\n\ttypedef typename mat::conj_view<Coll>::value_type        value_type;\n\ttypedef typename mat::conj_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::conj_view<Coll>::size_type         size_type;\n    };\n#endif\n\n\n// Refrain from concept definition for newly added types\n// Forward to mat::map_view\ntemplate <typename Matrix>\nstruct Collection<mat::exp_view<Matrix> >\n//  : Collection<mat::map_view<mtl::sfunctor::exp<typename Collection<Matrix>::value_type>, Matrix> > // doesn't work for unknown reasons\n{\n    typedef typename mat::exp_view<Matrix>::value_type        value_type;\n    typedef typename mat::exp_view<Matrix>::const_reference   const_reference;\n    typedef typename mat::exp_view<Matrix>::size_type         size_type;\n};\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map Collection<mat::imag_view<Coll> >\n    {\n\ttypedef typename mat::imag_view<Coll>::value_type        value_type;\n\ttypedef typename mat::imag_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::imag_view<Coll>::size_type         size_type;\n    };\n#else\n    template <typename Coll>\n    struct Collection<mat::imag_view<Coll> >\n    {\n\ttypedef typename mat::imag_view<Coll>::value_type        value_type;\n\ttypedef typename mat::imag_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::imag_view<Coll>::size_type         size_type;\n    };\n#endif\n\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map Collection<mat::negate_view<Coll> >\n    {\n\ttypedef typename mat::negate_view<Coll>::value_type        value_type;\n\ttypedef typename mat::negate_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::negate_view<Coll>::size_type         size_type;\n    };\n#else\n    template <typename Coll>\n    struct Collection<mat::negate_view<Coll> >\n    {\n\ttypedef typename mat::negate_view<Coll>::value_type        value_type;\n\ttypedef typename mat::negate_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::negate_view<Coll>::size_type         size_type;\n    };\n#endif\n\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map Collection<mat::real_view<Coll> >\n    {\n\ttypedef typename mat::real_view<Coll>::value_type        value_type;\n\ttypedef typename mat::real_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::real_view<Coll>::size_type         size_type;\n    };\n#else\n    template <typename Coll>\n    struct Collection<mat::real_view<Coll> >\n    {\n\ttypedef typename mat::real_view<Coll>::value_type        value_type;\n\ttypedef typename mat::real_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::real_view<Coll>::size_type         size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Functor>\n    concept_map Collection<mat::implicit_dense<Functor> >\n    {\n\ttypedef typename mat::implicit_dense<Functor>::value_type        value_type;\n\ttypedef typename mat::implicit_dense<Functor>::const_reference   const_reference;\n\ttypedef typename mat::implicit_dense<Functor>::size_type         size_type;\n    };\n#else\n    template <typename Functor>\n    struct Collection<mat::implicit_dense<Functor> >\n    {\n\ttypedef typename mat::implicit_dense<Functor>::value_type        value_type;\n\ttypedef typename mat::implicit_dense<Functor>::const_reference   const_reference;\n\ttypedef typename mat::implicit_dense<Functor>::size_type         size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value>\n    concept_map Collection<mat::ones_matrix<Value> >\n    {\n\ttypedef typename mat::ones_matrix<Value>::value_type        value_type;\n\ttypedef typename mat::ones_matrix<Value>::const_reference   const_reference;\n\ttypedef typename mat::ones_matrix<Value>::size_type         size_type;\n    };\n#else\n    template <typename Value>\n    struct Collection<mat::ones_matrix<Value> >\n    {\n\ttypedef typename mat::ones_matrix<Value>::value_type        value_type;\n\ttypedef typename mat::ones_matrix<Value>::const_reference   const_reference;\n\ttypedef typename mat::ones_matrix<Value>::size_type         size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value>\n    concept_map Collection<mat::hilbert_matrix<Value> >\n    {\n\ttypedef typename mat::hilbert_matrix<Value>::value_type        value_type;\n\ttypedef typename mat::hilbert_matrix<Value>::const_reference   const_reference;\n\ttypedef typename mat::hilbert_matrix<Value>::size_type         size_type;\n    };\n#else\n    template <typename Value>\n    struct Collection<mat::hilbert_matrix<Value> >\n    {\n\ttypedef typename mat::hilbert_matrix<Value>::value_type        value_type;\n\ttypedef typename mat::hilbert_matrix<Value>::const_reference   const_reference;\n\ttypedef typename mat::hilbert_matrix<Value>::size_type         size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Vector1, typename Vector2>\n    concept_map Collection<mat::outer_product_matrix<Vector1, Vector2> >\n    {\n\ttypedef typename mat::outer_product_matrix<Vector1, Vector2>::value_type        value_type;\n\ttypedef typename mat::outer_product_matrix<Vector1, Vector2>::const_reference   const_reference;\n\ttypedef typename mat::outer_product_matrix<Vector1, Vector2>::size_type         size_type;\n    };\n#else\n    template <typename Vector1, typename Vector2>\n    struct Collection<mat::outer_product_matrix<Vector1, Vector2> >\n    {\n\ttypedef typename mat::outer_product_matrix<Vector1, Vector2>::value_type        value_type;\n\ttypedef typename mat::outer_product_matrix<Vector1, Vector2>::const_reference   const_reference;\n\ttypedef typename mat::outer_product_matrix<Vector1, Vector2>::size_type         size_type;\n    };\n#endif\n\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Matrix>\n    concept_map Collection<mtl::mat::transposed_view<Matrix> >\n    {\n\ttypedef typename mtl::mat::transposed_view<Matrix>::value_type        value_type;\n\ttypedef typename mtl::mat::transposed_view<Matrix>::const_reference   const_reference;\n\ttypedef typename mtl::mat::transposed_view<Matrix>::size_type         size_type;\n    };\n#else\n    template <typename Matrix>\n    struct Collection<mtl::mat::transposed_view<Matrix> >\n    {\n\ttypedef typename mtl::mat::transposed_view<Matrix>::value_type        value_type;\n\ttypedef typename mtl::mat::transposed_view<Matrix>::const_reference   const_reference;\n\ttypedef typename mtl::mat::transposed_view<Matrix>::size_type         size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Matrix>\n    concept_map Collection<mat::hermitian_view<Matrix> >\n    {\n\ttypedef typename Collection<Matrix>::value_type        value_type;\n\ttypedef typename Collection<Matrix>::const_reference   const_reference;\n\ttypedef typename Collection<Matrix>::size_type         size_type;\n    };\n#else\n    template <typename Matrix>\n    struct Collection<mat::hermitian_view<Matrix> >\n    {\n\ttypedef typename Collection<Matrix>::value_type        value_type;\n\ttypedef typename Collection<Matrix>::const_reference   const_reference;\n\ttypedef typename Collection<Matrix>::size_type         size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map Collection< mat::banded_view<Coll> >\n    {\n\ttypedef typename mat::banded_view<Coll>::value_type        value_type;\n\ttypedef typename mat::banded_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::banded_view<Coll>::size_type         size_type;\n    };\n#else\n    template <typename Coll>\n    struct Collection< mat::banded_view<Coll> >\n    {\n\ttypedef typename mat::banded_view<Coll>::value_type        value_type;\n\ttypedef typename mat::banded_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::banded_view<Coll>::size_type         size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Matrix>\n    struct Collection< mat::indirect<Matrix> >\n    {\n\ttypedef typename Collection<Matrix>::value_type               value_type;\n\ttypedef value_type                                            const_reference; // maybe change later\n\ttypedef typename Collection<Matrix>::size_type                size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename Matrix, typename Tag, int level>\n    struct Collection<traits::detail::sub_matrix_cursor<Matrix, Tag, level> >\n    {\n\ttypedef typename Collection<Matrix>::value_type               value_type;\n\ttypedef typename Collection<Matrix>::const_reference          const_reference;\n\ttypedef typename Collection<Matrix>::size_type                size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename E1, typename E2>\n    struct Collection<mat::mat_mat_times_expr<E1, E2> >\n    {\n\ttypedef typename Collection<E1>::value_type                   ft;\n\ttypedef typename Collection<E2>::value_type                   st;\n\n\ttypedef typename Multiplicable<ft, st>::result_type           value_type;\n\ttypedef const value_type&                                     const_reference;\n\ttypedef typename Collection<E1>::size_type                    size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename E1, typename E2>\n    struct Collection<mat::mat_mat_plus_expr<E1, E2> >\n    {\n\ttypedef typename Collection<E1>::value_type                   ft;\n\ttypedef typename Collection<E2>::value_type                   st;\n\n\ttypedef typename Addable<ft, st>::result_type                 value_type;\n\ttypedef const value_type&                                     const_reference;\n\ttypedef typename Collection<E1>::size_type                    size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename E1, typename E2>\n    struct Collection<mat::mv_mv_plus_expr<E1, E2> >\n      : Collection<mat::mat_mat_plus_expr<E1, E2> >\n    {};\n#endif\n\n#ifdef __GXX_CONCECPTS__\n\n#else\n    template< typename Matrix, typename Vector>\n    struct Collection<mtl::mat_cvec_times_expr<Matrix, Vector> > \n    {\n\ttypedef typename Collection< Matrix >::value_type value_type;\n\ttypedef const value_type& const_reference;\n\ttypedef typename Collection< Matrix >::size_type size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mtl::vec::dense_vector<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename Parameters::size_type size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mtl::vec::strided_vector_ref<Value, Parameters> >\n    {\n\ttypedef typename boost::remove_const<Value>::type            value_type;\n\ttypedef const Value&                                         const_reference;\n\ttypedef typename mtl::vec::strided_vector_ref<Value, Parameters>::size_type size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Value, typename Parameters>\n    struct Collection<mtl::vec::sparse_vector<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef value_type       const_reference;\n\ttypedef typename Parameters::size_type size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <class E1, class E2, typename SFunctor> \n    struct Collection<mtl::vec::vec_vec_ele_prod_expr<E1, E2, SFunctor> >\n    {\n\ttypedef typename Multiplicable<typename Collection<E1>::value_type,\n\t\t\t\t       typename Collection<E2>::value_type>::result_type value_type;\n\ttypedef const value_type&     const_reference;\n\ttypedef typename Collection<E1>::size_type  size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <class E1, class E2, typename SFunctor> \n    struct Collection<mtl::vec::vec_vec_pmop_expr<E1, E2, SFunctor> >\n    {\n\ttypedef typename Addable<typename Collection<E1>::value_type,\n\t\t\t\t typename Collection<E2>::value_type>::result_type value_type;\n\ttypedef const value_type&     const_reference;\n\ttypedef typename Collection<E1>::size_type  size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <class E1, class E2, typename SFunctor> \n    struct Collection<mtl::vec::vec_vec_op_expr<E1, E2, SFunctor> >\n    {\n\ttypedef typename SFunctor::result_type value_type;\n\ttypedef const value_type&     const_reference;\n\ttypedef typename Collection<E1>::size_type  size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <class E1, class E2, typename SFunctor> \n    struct Collection<mtl::vec::vec_vec_aop_expr<E1, E2, SFunctor> >\n    {\n\ttypedef typename Collection<E1>::value_type value_type;\n\ttypedef const value_type&                   const_reference;\n\ttypedef typename Collection<E1>::size_type  size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Matrix, typename VectorIn>\n    struct Collection<mtl::vec::mat_cvec_multiplier<Matrix, VectorIn> >\n    {\n\ttypedef typename Multiplicable<typename Collection<Matrix>::value_type,\n\t\t\t\t       typename Collection<VectorIn>::value_type>::result_type value_type;\n\ttypedef const value_type&                   const_reference;\n\ttypedef typename Collection<Matrix>::size_type  size_type;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    // Dunno if this is really a good idea\n    template <typename T>\n    struct Collection<T const>\n      : Collection<T>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n\n#else\n    template <typename Value>\n    struct Collection<std::vector<Value> >\n    {\n\ttypedef typename std::vector<Value>::value_type      value_type;\n\ttypedef typename std::vector<Value>::const_reference const_reference;\n\ttypedef typename std::vector<Value>::size_type       size_type;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Vector, typename Functor>\n    struct Collection<mtl::vec::lazy_reduction<Vector, Functor> >\n    {\n\ttypedef std::size_t size_type;\n    };\n#endif\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value, typename Parameters>\n    concept_map MutableCollection<mtl::mat::dense2D<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::mat::dense2D<Value, Parameters>::size_type size_type;\n\n\ttypedef Value&           reference;\n    };\n#else\n    template <typename Value, typename Parameters>\n    struct MutableCollection<mtl::mat::dense2D<Value, Parameters> >\n\t: public Collection<mtl::mat::dense2D<Value, Parameters> >\n    {\n\ttypedef Value&           reference;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n\n    template <typename Value, unsigned long Mask, typename Parameters>\n    concept_map MutableCollection<mtl::mat::morton_dense<Value, Mask, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::mat::morton_dense<Value, Mask, Parameters>::size_type size_type;\n\n\ttypedef Value&           reference;\n    };\n\n#else\n\n    template <typename Value, unsigned long Mask, typename Parameters>\n    struct MutableCollection<mtl::mat::morton_dense<Value, Mask, Parameters> >\n\t: public Collection<mtl::mat::morton_dense<Value, Mask, Parameters> >\n    {\n\ttypedef Value&           reference;\n    };\n\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value, typename Parameters>\n    concept_map MutableCollection<mtl::vec::strided_vector_ref<Value, Parameters> >\n    {\n\ttypedef typename boost::remove_const<Value>::type            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::vec::strided_vector_ref<Value, Parameters>::size_type size_type;\n\n\ttypedef Value&           reference;\n    };\n#else\n    template <typename Value, typename Parameters>\n    struct MutableCollection<mtl::vec::strided_vector_ref<Value, Parameters> >\n\t: public Collection<mtl::vec::strided_vector_ref<Value, Parameters> >\n    {\n\ttypedef Value&           reference;\n    };\n#endif\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value>\n    concept_map MutableCollection<<std::vector<Value> >\n    {\n\ttypedef typename std::vector<Value>::value_type      value_type;\n\ttypedef typename std::vector<Value>::const_reference const_reference;\n\ttypedef typename std::vector<Value>::size_type       size_type;\n\n\ttypedef typename std::vector<Value>::reference       reference;\n    };\n#else\n    template <typename Value>\n    struct MutableCollection<std::vector<Value> >\n\t: public Collection<std::vector<Value> >\n    {\n\ttypedef typename std::vector<Value>::reference       reference;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename T>\n    struct OrientedCollection<const T>\n      : OrientedCollection<T>\n    {};\n#endif\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value, typename Parameters>\n    concept_map OrientedCollection<mtl::mat::dense2D<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::mat::dense2D<Value, Parameters>::size_type size_type;\n\n\ttypedef typename mtl::mat::dense2D<Value, Parameters>::orientation   orientation;\n    };\n#else\n    template <typename Value, typename Parameters>\n    struct OrientedCollection<mtl::mat::dense2D<Value, Parameters> >\n\t: public Collection<mtl::mat::dense2D<Value, Parameters> >\n    {\n\ttypedef typename mtl::mat::dense2D<Value, Parameters>::orientation   orientation;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n\n    template <typename Value, unsigned long Mask, typename Parameters>\n    concept_map OrientedCollection<mtl::mat::morton_dense<Value, Mask, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::mat::morton_dense<Value, Mask, Parameters>::size_type size_type;\n\n\ttypedef typename mtl::mat::morton_dense<Value, Mask, Parameters>::orientation   orientation;\n    };\n\n#else\n\n    template <typename Value, unsigned long Mask, typename Parameters>\n    struct OrientedCollection<mtl::mat::morton_dense<Value, Mask, Parameters> >\n\t: public Collection<mtl::mat::morton_dense<Value, Mask, Parameters> >\n    {\n\ttypedef typename mtl::mat::morton_dense<Value, Mask, Parameters>::orientation   orientation;\n    };\n\n#endif\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value, typename Parameters>\n    concept_map OrientedCollection<mtl::mat::compressed2D<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::mat::compressed2D<Value, Parameters>::size_type size_type;\n\n\ttypedef typename mtl::mat::compressed2D<Value, Parameters>::orientation   orientation;\n    };\n#else\n    template <typename Value, typename Parameters>\n    struct OrientedCollection<mtl::mat::compressed2D<Value, Parameters> >\n\t: public Collection<mtl::mat::compressed2D<Value, Parameters> >\n    {\n\ttypedef typename mtl::mat::compressed2D<Value, Parameters>::orientation   orientation;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n#else\n    template <typename Matrix>\n    struct OrientedCollection<mtl::mat::indirect<Matrix> >\n\t: public Collection<mtl::mat::indirect<Matrix> >\n    {\n\ttypedef row_major   orientation;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value, typename Parameters>\n    concept_map OrientedCollection<mtl::vec::dense_vector<Value, Parameters> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::vec::dense_vector<Value, Parameters>::size_type size_type;\n\n\ttypedef typename mtl::vec::dense_vector<Value, Parameters>::orientation   orientation;\n    };\n#else\n    template <typename Value, typename Parameters>\n    struct OrientedCollection<mtl::vec::dense_vector<Value, Parameters> >\n\t: public Collection<mtl::vec::dense_vector<Value, Parameters> >\n    {\n\ttypedef typename mtl::vec::dense_vector<Value, Parameters>::orientation   orientation;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value, typename Parameters>\n    concept_map OrientedCollection<mtl::vec::strided_vector_ref<Value, Parameters> >\n    {\n\ttypedef typename boost::remove_const<Value>::type            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename mtl::vec::strided_vector_ref<Value, Parameters>::size_type size_type;\n\n\ttypedef typename mtl::vec::strided_vector_ref<Value, Parameters>::orientation   orientation;\n    };\n#else\n    template <typename Value, typename Parameters>\n    struct OrientedCollection<mtl::vec::strided_vector_ref<Value, Parameters> >\n\t: public Collection<mtl::vec::strided_vector_ref<Value, Parameters> >\n    {\n\ttypedef typename mtl::vec::strided_vector_ref<Value, Parameters>::orientation   orientation;\n    };\n#endif\n\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Value>\n    concept_map OrientedCollection<std::vector<Value> >\n    {\n\ttypedef Value            value_type;\n\ttypedef const Value&     const_reference;\n\ttypedef typename std::vector<Value>::size_type size_type;\n\n\ttypedef mtl::tag::col_major   orientation;\n    };\n#else\n    template <typename Value>\n    struct OrientedCollection<std::vector<Value> >\n\t: public Collection<std::vector<Value> >\n    {\n\ttypedef mtl::tag::col_major   orientation;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Scaling, typename Coll>\n    concept_map OrientedCollection< mat::scaled_view<Scaling, Coll> >\n    {\n\ttypedef typename mat::scaled_view<Scaling, Coll>::value_type        value_type;\n\ttypedef typename mat::scaled_view<Scaling, Coll>::const_reference   const_reference;\n\ttypedef typename mat::scaled_view<Scaling, Coll>::size_type         size_type;\n\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#else\n    template <typename Scaling, typename Coll>\n    struct OrientedCollection< mat::scaled_view<Scaling, Coll> >\n\t: public Collection< mat::scaled_view<Scaling, Coll> >\n    {\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#endif\n\n// added by Hui Li\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll, typename RScaling>\n    concept_map OrientedCollection< mat::rscaled_view<Coll,RScaling> >\n    {\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::value_type        value_type;\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::const_reference   const_reference;\n\ttypedef typename mat::rscaled_view<Coll,RScaling>::size_type         size_type;\n\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#else\n    template <typename Coll, typename RScaling>\n    struct OrientedCollection< mat::rscaled_view<Coll,RScaling> >\n\t: public Collection< mat::rscaled_view<Coll,RScaling> >\n    {\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#endif\n\n\t\n#ifdef __GXX_CONCEPTS__\n    template <typename Scaling, typename Coll>\n    concept_map OrientedCollection< mtl::vec::scaled_view<Scaling, Coll> >\n    {\n\ttypedef typename mtl::vec::scaled_view<Scaling, Coll>::value_type        value_type;\n\ttypedef typename mtl::vec::scaled_view<Scaling, Coll>::const_reference   const_reference;\n\ttypedef typename mtl::vec::scaled_view<Scaling, Coll>::size_type         size_type;\n\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#else\n    template <typename Scaling, typename Coll>\n    struct OrientedCollection< mtl::vec::scaled_view<Scaling, Coll> >\n\t: public Collection< mtl::vec::scaled_view<Scaling, Coll> >\n    {\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#endif\n\n//added by Hui Li\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll, typename RScaling>\n    concept_map OrientedCollection< mtl::vec::rscaled_view<Coll,RScaling> >\n    {\n\ttypedef typename mtl::vec::rscaled_view<Coll,RScaling>::value_type        value_type;\n\ttypedef typename mtl::vec::rscaled_view<Coll,RScaling>::const_reference   const_reference;\n\ttypedef typename mtl::vec::rscaled_view<Coll,RScaling>::size_type         size_type;\n\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#else\n    template <typename Coll, typename RScaling>\n    struct OrientedCollection< mtl::vec::rscaled_view<Coll,RScaling> >\n\t: public Collection< mtl::vec::rscaled_view<Coll,RScaling> >\n    {\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#endif\n\n\t\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map OrientedCollection<mat::conj_view<Coll> >\n    {\n\ttypedef typename mat::conj_view<Coll>::value_type         value_type;\n\ttypedef typename mat::conj_view<Coll>::const_reference    const_reference;\n\ttypedef typename mat::conj_view<Coll>::size_type          size_type;\n\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#else\n    template <typename Coll>\n    struct OrientedCollection<mat::conj_view<Coll> >\n\t: public Collection<mat::conj_view<Coll> >\n    {\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#endif\n\n\n// Refrain from concept definition for newly added types\ntemplate <typename Matrix>\nstruct OrientedCollection<mat::exp_view<Matrix> >\n  : Collection<mat::exp_view<Matrix> >\n{\n    typedef typename OrientedCollection<Matrix>::orientation       orientation;\n};\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map OrientedCollection<mtl::vec::conj_view<Coll> >\n    {\n\ttypedef typename mtl::vec::conj_view<Coll>::value_type        value_type;\n\ttypedef typename mtl::vec::conj_view<Coll>::const_reference   const_reference;\n\ttypedef typename mtl::vec::conj_view<Coll>::size_type         size_type;\n\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#else\n    template <typename Coll>\n    struct OrientedCollection<mtl::vec::conj_view<Coll> >\n\t: public Collection<mtl::vec::conj_view<Coll> >\n    {\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Functor, typename Coll>\n    concept_map OrientedCollection< mtl::vec::map_view<Functor, Coll> >\n    {\n\ttypedef typename mtl::vec::map_view<Functor, Coll>::value_type        value_type;\n\ttypedef typename mtl::vec::map_view<Functor, Coll>::const_reference   const_reference;\n\ttypedef typename mtl::vec::map_view<Functor, Coll>::size_type         size_type;\n\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#else\n    template <typename Functor, typename Coll>\n    struct OrientedCollection< mtl::vec::map_view<Functor, Coll> >\n\t: public Collection< mtl::vec::map_view<Functor, Coll> >\n    {\n\ttypedef typename OrientedCollection<Coll>::orientation       orientation;\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map OrientedCollection<mtl::mat::transposed_view<Coll> >\n    {\n\ttypedef typename mtl::mat::transposed_view<Coll>::value_type        value_type;\n\ttypedef typename mtl::mat::transposed_view<Coll>::const_reference   const_reference;\n\ttypedef typename mtl::mat::transposed_view<Coll>::size_type         size_type;\n\n\ttypedef typename mtl::traits::transposed_orientation<typename OrientedCollection<Coll>::orientation>::type   orientation;\n    };\n#else\n    template <typename Coll>\n    struct OrientedCollection<mtl::mat::transposed_view<Coll> >\n\t: public Collection<mtl::mat::transposed_view<Coll> >\n    {\n\ttypedef typename mtl::traits::transposed_orientation<typename OrientedCollection<Coll>::orientation>::type   orientation;\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n    template <typename Coll>\n    concept_map OrientedCollection<mat::hermitian_view<Coll> >\n    {\n\ttypedef typename mat::hermitian_view<Coll>::value_type        value_type;\n\ttypedef typename mat::hermitian_view<Coll>::const_reference   const_reference;\n\ttypedef typename mat::hermitian_view<Coll>::size_type         size_type;\n\n\ttypedef typename mtl::traits::transposed_orientation<typename OrientedCollection<Coll>::orientation>::type   orientation;\n    };\n#else\n    template <typename Coll>\n    struct OrientedCollection<mat::hermitian_view<Coll> >\n      : public Collection<mat::hermitian_view<Coll> >\n    {\n\ttypedef typename mtl::traits::transposed_orientation<typename OrientedCollection<Coll>::orientation>::type   orientation;\n    };\n#endif\n\n\n\n/*@}*/ // end of group Concepts\n\n} // namespace mtl\n\n#endif // MTL_COLLECTION_INCLUDE\n", "meta": {"hexsha": "3ef81abbec38dce775d479792e48158186d115fa", "size": 48462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/concept/collection.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/concept/collection.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/concept/collection.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": 32.8111035884, "max_line_length": 137, "alphanum_fraction": 0.7169534893, "num_tokens": 10966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.06560484248306504, "lm_q1q2_score": 0.028723341694771583}}
{"text": "/*!\r\n@file\r\nForward declares `boost::hana::Ring`.\r\n\r\n@copyright Louis Dionne 2013-2017\r\nDistributed under the Boost Software License, Version 1.0.\r\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#ifndef BOOST_HANA_FWD_CONCEPT_RING_HPP\r\n#define BOOST_HANA_FWD_CONCEPT_RING_HPP\r\n\r\n#include <boost/hana/config.hpp>\r\n\r\n\r\nBOOST_HANA_NAMESPACE_BEGIN\r\n    //! @ingroup group-concepts\r\n    //! @defgroup group-Ring Ring\r\n    //! The `Ring` concept represents `Group`s that also form a `Monoid`\r\n    //! under a second binary operation that distributes over the first.\r\n    //!\r\n    //! A [Ring][1] is an algebraic structure built on top of a `Group`\r\n    //! which requires a monoidal structure with respect to a second binary\r\n    //! operation. This second binary operation must distribute over the\r\n    //! first one. Specifically, a `Ring` is a triple `(S, +, *)` such that\r\n    //! `(S, +)` is a `Group`, `(S, *)` is a `Monoid` and `*` distributes\r\n    //! over `+`, i.e.\r\n    //! @code\r\n    //!     x * (y + z) == (x * y) + (x * z)\r\n    //! @endcode\r\n    //!\r\n    //! The second binary operation is often written `*` with its identity\r\n    //! written `1`, in reference to the `Ring` of integers under\r\n    //! multiplication. The method names used here refer to this exact ring.\r\n    //!\r\n    //!\r\n    //! Minimal complete definintion\r\n    //! ----------------------------\r\n    //! `one` and `mult` satisfying the laws\r\n    //!\r\n    //!\r\n    //! Laws\r\n    //! ----\r\n    //! For all objects `x`, `y`, `z` of a `Ring` `R`, the following laws must\r\n    //! be satisfied:\r\n    //! @code\r\n    //!     mult(x, mult(y, z)) == mult(mult(x, y), z)          // associativity\r\n    //!     mult(x, one<R>()) == x                              // right identity\r\n    //!     mult(one<R>(), x) == x                              // left identity\r\n    //!     mult(x, plus(y, z)) == plus(mult(x, y), mult(x, z)) // distributivity\r\n    //! @endcode\r\n    //!\r\n    //!\r\n    //! Refined concepts\r\n    //! ----------------\r\n    //! `Monoid`, `Group`\r\n    //!\r\n    //!\r\n    //! Concrete models\r\n    //! ---------------\r\n    //! `hana::integral_constant`\r\n    //!\r\n    //!\r\n    //! Free model for non-boolean arithmetic data types\r\n    //! ------------------------------------------------\r\n    //! A data type `T` is arithmetic if `std::is_arithmetic<T>::%value` is\r\n    //! true. For a non-boolean arithmetic data type `T`, a model of `Ring` is\r\n    //! automatically defined by using the provided `Group` model and setting\r\n    //! @code\r\n    //!     mult(x, y) = (x * y)\r\n    //!     one<T>() = static_cast<T>(1)\r\n    //! @endcode\r\n    //!\r\n    //! @note\r\n    //! The rationale for not providing a Ring model for `bool` is the same\r\n    //! as for not providing Monoid and Group models.\r\n    //!\r\n    //!\r\n    //! Structure-preserving functions\r\n    //! ------------------------------\r\n    //! Let `A` and `B` be two `Ring`s. A function `f : A -> B` is said to\r\n    //! be a [Ring morphism][2] if it preserves the ring structure between\r\n    //! `A` and `B`. Rigorously, for all objects `x, y` of data type `A`,\r\n    //! @code\r\n    //!     f(plus(x, y)) == plus(f(x), f(y))\r\n    //!     f(mult(x, y)) == mult(f(x), f(y))\r\n    //!     f(one<A>()) == one<B>()\r\n    //! @endcode\r\n    //! Because of the `Ring` structure, it is easy to prove that the\r\n    //! following will then also be satisfied:\r\n    //! @code\r\n    //!     f(zero<A>()) == zero<B>()\r\n    //!     f(negate(x)) == negate(f(x))\r\n    //! @endcode\r\n    //! which is to say that `f` will then also be a `Group` morphism.\r\n    //! Functions with these properties interact nicely with `Ring`s,\r\n    //! which is why they are given such a special treatment.\r\n    //!\r\n    //!\r\n    //! [1]: http://en.wikipedia.org/wiki/Ring_(mathematics)\r\n    //! [2]: http://en.wikipedia.org/wiki/Ring_homomorphism\r\n    template <typename R>\r\n    struct Ring;\r\nBOOST_HANA_NAMESPACE_END\r\n\r\n#endif // !BOOST_HANA_FWD_CONCEPT_RING_HPP\r\n", "meta": {"hexsha": "fd82deb5436d62b57e4f7c8534548e75763b5d9f", "size": 3992, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/hana/fwd/concept/ring.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": 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": "deps/boost/include/boost/hana/fwd/concept/ring.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": 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": "deps/boost/include/boost/hana/fwd/concept/ring.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": 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": 37.308411215, "max_line_length": 82, "alphanum_fraction": 0.5293086172, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.06560483015143977, "lm_q1q2_score": 0.028723337258167305}}
{"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    LevenbergMarquardtOptimizer.cpp\n * @brief   \n * @author  Richard Roberts\n * @date\tFeb 26, 2012\n */\n\n#include <cmath>\n\n#include <gtsam/linear/linearExceptions.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/SuccessiveLinearizationOptimizer.h>\n\n#include <boost/algorithm/string.hpp>\n#include <string>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nLevenbergMarquardtParams::VerbosityLM LevenbergMarquardtParams::verbosityLMTranslator(const std::string &src) const {\n  std::string s = src;  boost::algorithm::to_upper(s);\n  if (s == \"SILENT\") return LevenbergMarquardtParams::SILENT;\n  if (s == \"LAMBDA\") return LevenbergMarquardtParams::LAMBDA;\n  if (s == \"TRYLAMBDA\") return LevenbergMarquardtParams::TRYLAMBDA;\n  if (s == \"TRYCONFIG\") return LevenbergMarquardtParams::TRYCONFIG;\n  if (s == \"TRYDELTA\") return LevenbergMarquardtParams::TRYDELTA;\n  if (s == \"DAMPED\") return LevenbergMarquardtParams::DAMPED;\n\n  /* default is silent */\n  return LevenbergMarquardtParams::SILENT;\n}\n\n/* ************************************************************************* */\nstd::string LevenbergMarquardtParams::verbosityLMTranslator(VerbosityLM value) const {\n  std::string s;\n  switch (value) {\n  case LevenbergMarquardtParams::SILENT:    s = \"SILENT\" ;     break;\n  case LevenbergMarquardtParams::LAMBDA:    s = \"LAMBDA\" ;     break;\n  case LevenbergMarquardtParams::TRYLAMBDA: s = \"TRYLAMBDA\" ;  break;\n  case LevenbergMarquardtParams::TRYCONFIG: s = \"TRYCONFIG\" ;  break;\n  case LevenbergMarquardtParams::TRYDELTA:  s = \"TRYDELTA\" ;   break;\n  case LevenbergMarquardtParams::DAMPED:    s = \"DAMPED\" ;     break;\n  default:                                  s = \"UNDEFINED\" ;  break;\n  }\n  return s;\n}\n\n/* ************************************************************************* */\nvoid LevenbergMarquardtParams::print(const std::string& str) const {\n  SuccessiveLinearizationParams::print(str);\n  std::cout << \"              lambdaInitial: \" << lambdaInitial << \"\\n\";\n  std::cout << \"               lambdaFactor: \" << lambdaFactor << \"\\n\";\n  std::cout << \"           lambdaUpperBound: \" << lambdaUpperBound << \"\\n\";\n  std::cout << \"                verbosityLM: \" << verbosityLMTranslator(verbosityLM) << \"\\n\";\n  std::cout.flush();\n}\n\n/* ************************************************************************* */\nvoid LevenbergMarquardtOptimizer::iterate() {\n\n  // Linearize graph\n  GaussianFactorGraph::shared_ptr linear = graph_.linearize(state_.values, *params_.ordering);\n\n  // Pull out parameters we'll use\n  const NonlinearOptimizerParams::Verbosity nloVerbosity = params_.verbosity;\n  const LevenbergMarquardtParams::VerbosityLM lmVerbosity = params_.verbosityLM;\n\n  // Keep increasing lambda until we make make progress\n  while(true) {\n    if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n      cout << \"trying lambda = \" << state_.lambda << endl;\n\n    // Add prior-factors\n    // TODO: replace this dampening with a backsubstitution approach\n    GaussianFactorGraph dampedSystem(*linear);\n    {\n      double sigma = 1.0 / std::sqrt(state_.lambda);\n      dampedSystem.reserve(dampedSystem.size() + dimensions_.size());\n      // for each of the variables, add a prior\n      for(Index j=0; j<dimensions_.size(); ++j) {\n        size_t dim = (dimensions_)[j];\n        Matrix A = eye(dim);\n        Vector b = zero(dim);\n        SharedDiagonal model = noiseModel::Isotropic::Sigma(dim,sigma);\n        GaussianFactor::shared_ptr prior(new JacobianFactor(j, A, b, model));\n        dampedSystem.push_back(prior);\n      }\n    }\n    if (lmVerbosity >= LevenbergMarquardtParams::DAMPED) dampedSystem.print(\"damped\");\n\n    // Try solving\n    try {\n      // Solve Damped Gaussian Factor Graph\n      const VectorValues delta = solveGaussianFactorGraph(dampedSystem, params_);\n\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA) cout << \"linear delta norm = \" << delta.vector().norm() << endl;\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYDELTA) delta.print(\"delta\");\n\n      // update values\n      Values newValues = state_.values.retract(delta, *params_.ordering);\n\n      // create new optimization state with more adventurous lambda\n      double error = graph_.error(newValues);\n\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA) cout << \"next error = \" << error << endl;\n\n      if(error <= state_.error) {\n        state_.values.swap(newValues);\n        state_.error = error;\n        state_.lambda /= params_.lambdaFactor;\n        break;\n      } else {\n        // Either we're not cautious, or the same lambda was worse than the current error.\n        // The more adventurous lambda was worse too, so make lambda more conservative\n        // and keep the same values.\n        if(state_.lambda >= params_.lambdaUpperBound) {\n          if(nloVerbosity >= NonlinearOptimizerParams::ERROR)\n            cout << \"Warning:  Levenberg-Marquardt giving up because cannot decrease error with maximum lambda\" << endl;\n          break;\n        } else {\n          state_.lambda *= params_.lambdaFactor;\n        }\n      }\n    } catch(const IndeterminantLinearSystemException& e) {\n      if(lmVerbosity >= LevenbergMarquardtParams::LAMBDA)\n        cout << \"Negative matrix, increasing lambda\" << endl;\n      // Either we're not cautious, or the same lambda was worse than the current error.\n      // The more adventurous lambda was worse too, so make lambda more conservative\n      // and keep the same values.\n      if(state_.lambda >= params_.lambdaUpperBound) {\n        if(nloVerbosity >= NonlinearOptimizerParams::ERROR)\n          cout << \"Warning:  Levenberg-Marquardt giving up because cannot decrease error with maximum lambda\" << endl;\n        break;\n      } else {\n        state_.lambda *= params_.lambdaFactor;\n      }\n    } catch(...) {\n      throw;\n    }\n  } // end while\n\n  // Increment the iteration counter\n  ++state_.iterations;\n}\n\n} /* namespace gtsam */\n", "meta": {"hexsha": "a77cac35aee31c4a6e10a1e315b01ce61b0c2ce4", "size": 6406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/nonlinear/LevenbergMarquardtOptimizer.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "gtsam/nonlinear/LevenbergMarquardtOptimizer.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/nonlinear/LevenbergMarquardtOptimizer.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 40.0375, "max_line_length": 126, "alphanum_fraction": 0.6244146113, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.06853749065376102, "lm_q1q2_score": 0.028696435511724003}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/transform.hpp\n *\n * The \\c transform operation.\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_TRANSFORM_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_TRANSFORM_HPP\n\n\n#include <boost/numeric/ublas/expression_types.hpp>\n//#include <boost/numeric/ublas/fwd.hpp>\n//#include <boost/numeric/ublas/functional.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n//#include <boost/shared_ptr.hpp>//FIXME\n//#include <boost/function.hpp>//FIXME\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n//namespace detail {\n//\n//template <typename T, typename F>\n//struct scalar_unary_generic: public scalar_unary_functor<T>\n//{\n//\ttypedef typename scalar_unary_functor<T>::value_type value_type;\n//\ttypedef typename scalar_unary_functor<T>::argument_type argument_type;\n//\ttypedef typename scalar_unary_functor<T>::result_type result_type;\n//\t//typedef typename F::result_type result_type;\n//\n//\texplicit scalar_unary_generic(F const& f)\n//\t: f_(f)\n//\t{\n//\t}\n//\n//\n//\tBOOST_UBLAS_INLINE\n//\tresult_type operator()(argument_type t)\n//\t{\n//std::cerr << \"In scalar_unary_generic: \" << t << std::endl;\n//\t\treturn f_(t);\n//\t}\n//\n//\tboost::function<result_type (argument_type)> f_;\n//};\n//\n//} // Namespace detail\n\n\n/**\n * \\brief Apply a function to each element of a given vector expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n * \\tparam UnaryFunctorT The type of the unary functor.\n *\n * \\param ve The input vector expression.\n * \\param f The unary functor to be applied to each vector element.\n * \\return A vector expression representing the application of \\a f to each\n *  element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT, typename UnaryFunctorT>\nBOOST_UBLAS_INLINE\ntypename vector_unary_functor_traits<\n\tVectorExprT,\n\ttypename UnaryFunctorT::result_type (typename UnaryFunctorT::argument_type)\n>::result_type transform(vector_expression<VectorExprT> const& ve, UnaryFunctorT const& f)\n{\n\ttypedef typename vector_unary_functor_traits<\n\t\t\t\tVectorExprT,\n\t\t\t\ttypename UnaryFunctorT::result_type (typename UnaryFunctorT::argument_type)\n\t\t\t>::expression_type expression_type;\n\n\treturn expression_type(ve(), f);\n}\n\n\n/**\n * \\brief Apply a function to each element of a given matrix expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n * \\tparam UnaryFunctorT The type of the unary functor.\n *\n * \\param me The input matrix expression.\n * \\param f The unary functor to be applied to each matrix element.\n * \\return A matrix expression representing the application of \\a f to each\n *  element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT, typename UnaryFunctorT>\nBOOST_UBLAS_INLINE\ntypename matrix_unary_functor_traits<\n\tMatrixExprT,\n//\tUnaryFunctorT\n\ttypename UnaryFunctorT::result_type (typename UnaryFunctorT::argument_type)\n//\tdetail::scalar_unary_generic<\n//\t\ttypename matrix_traits<MatrixExprT>::value_type,\n//\t\tUnaryFunctorT\n//\t>\n>::result_type transform(matrix_expression<MatrixExprT> const& me, UnaryFunctorT const& f)\n{\n//\ttypedef detail::scalar_unary_generic<\n//\t\t\ttypename matrix_traits<MatrixExprT>::value_type,\n//\t\t\tUnaryFunctorT\n//\t\t> wrapper_functor_type;\n\n\ttypedef typename matrix_unary_functor_traits<\n\t\t\tMatrixExprT,\n//\t\t\twrapper_functor_type\n\t\t\ttypename UnaryFunctorT::result_type (typename UnaryFunctorT::argument_type)\n\t\t>::expression_type expression_type;\n\n\t//return expression_type(me(), wrapper_functor_type(f));\n\treturn expression_type(me(), f);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_TRANSFORM_HPP\n", "meta": {"hexsha": "cbe992947e6e52f80d8478f6ac6f5df90fd35530", "size": 4093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/transform.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/transform.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/transform.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0955882353, "max_line_length": 90, "alphanum_fraction": 0.7612997801, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.06954174691630292, "lm_q1q2_score": 0.028589368022684733}}
{"text": "#include <utility/Configurations.hpp>\r\n#include <data/Spin_System.hpp>\r\n#include <engine/Vectormath.hpp>\r\n#include <utility/Constants.hpp>\r\n#include <utility/Logging.hpp>\r\n#include <utility/Exception.hpp>\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <fmt/format.h>\r\n\r\n#include <random>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing Utility::Constants::Pi;\r\n\r\nnamespace Utility\r\n{\r\n\tnamespace Configurations\r\n\t{\r\n\t\tvoid filter_to_mask(const vectorfield & spins, const vectorfield & positions, filterfunction filter, intfield & mask)\r\n\t\t{\r\n\t\t\tint nos = spins.size();\r\n\t\t\tmask = intfield(nos, 0);\r\n\r\n\t\t\tfor (unsigned int iatom = 0; iatom < mask.size(); ++iatom)\r\n\t\t\t{\r\n\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t{\r\n\t\t\t\t\tmask[iatom] = 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid Move(vectorfield& configuration, const Data::Geometry & geometry, int da, int db, int dc)\r\n\t\t{\r\n\t\t\tint delta = geometry.n_cell_atoms*da + geometry.n_cell_atoms*geometry.n_cells[0] * db + geometry.n_cell_atoms*geometry.n_cells[0] * geometry.n_cells[1] * dc;\r\n\t\t\tif (delta < 0)\r\n\t\t\t\tdelta += geometry.nos;\r\n\t\t\tstd::rotate(configuration.begin(), configuration.begin() + delta, configuration.end());\r\n\t\t}\r\n\r\n\t\tvoid Insert(Data::Spin_System &s, const vectorfield& configuration, int shift, filterfunction filter)\r\n\t\t{\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\t\t\tint nos = s.nos;\r\n\t\t\tif (shift < 0) shift += nos;\r\n\r\n\t\t\tif (nos != configuration.size())\r\n\t\t\t{\r\n\t\t\t\tLog(Log_Level::Warning, Log_Sender::All, \"Tried to insert spin configuration with NOS != NOS_system\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tfor (int iatom = 0; iatom < nos; ++iatom)\r\n\t\t\t{\r\n\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t{\r\n\t\t\t\t\tspins[iatom] = configuration[(iatom + shift) % nos];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid Domain(Data::Spin_System & s, Vector3 v, filterfunction filter)\r\n\t\t{\r\n\t\t\tif (v.norm() < 1e-8)\r\n\t\t\t{\r\n\t\t\t\tLog( Log_Level::Warning, Log_Sender::All, fmt::format(\"Homogeneous vector was ({}, {}, {}) and got set to (0, 0, 1)\", v[0], v[1], v[2]) );\r\n\t\t\t\tv[0] = 0.0; v[1] = 0.0; v[2] = 1.0;\t\t// if vector is zero -> set vector to 0,0,1 (posZdir)\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tv.normalize();\r\n\t\t\t}\r\n\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\t\t\t\r\n\t\t\tfor (int iatom = 0; iatom < s.nos; ++iatom)\r\n\t\t\t{\r\n\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t{\r\n\t\t\t\t\tspins[iatom] = v;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid Random(Data::Spin_System & s, filterfunction filter, bool external)\r\n\t\t{\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\r\n\t\t\tauto distribution = std::uniform_real_distribution<scalar>(-1, 1);\r\n\t\t\tif (!external) {\r\n\t\t\t\tfor (int iatom = 0; iatom < s.nos; ++iatom)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tEngine::Vectormath::get_random_vector_unitsphere(distribution, s.llg_parameters->prng, spins[iatom]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tstd::mt19937 prng = std::mt19937(123456789);\r\n\t\t\t\tfor (int iatom = 0; iatom < s.nos; ++iatom)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tEngine::Vectormath::get_random_vector_unitsphere(distribution, s.llg_parameters->prng, spins[iatom]);\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\r\n\t\tvoid Add_Noise_Temperature(Data::Spin_System & s, scalar temperature, int delta_seed, filterfunction filter)\r\n\t\t{\r\n\t\t\tif (temperature == 0.0) return;\r\n\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\t\t\tvectorfield xi(spins.size());\r\n\t\t\tintfield mask;\r\n\r\n\t\t\tfilter_to_mask(spins, positions, filter, mask);\r\n\r\n\t\t\tscalar epsilon = std::sqrt(temperature*Constants::k_B);\r\n\t\t\t\r\n\t\t\tstd::mt19937 * prng;\r\n\t\t\tif (delta_seed!=0) prng = new std::mt19937(123456789+delta_seed);\r\n\t\t\telse prng = &s.llg_parameters->prng;\r\n\r\n\t\t\tauto distribution = std::uniform_real_distribution<scalar>(-1, 1);\r\n\r\n\t\t\tEngine::Vectormath::get_random_vectorfield_unitsphere(*prng, xi);\r\n\t\t\tEngine::Vectormath::scale(xi, epsilon);\r\n\t\t\tEngine::Vectormath::add_c_a(1, xi, *s.spins, mask);\r\n\t\t\tEngine::Vectormath::normalize_vectors(*s.spins);\r\n\t\t}\r\n\r\n\t\tvoid Hopfion(Data::Spin_System & s, Vector3 pos, scalar r, int order, filterfunction filter)\r\n\t\t{\r\n\t\t\tusing std::pow;\r\n\t\t\tusing std::sqrt;\r\n\t\t\tusing std::acos;\r\n\t\t\tusing std::sin;\r\n\t\t\tusing std::cos;\r\n\t\t\tusing std::atan;\r\n\t\t\tusing std::atan2;\r\n\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\r\n\t\t\tif (r != 0.0)\r\n\t\t\t{\r\n\t\t\t\tscalar tmp;\r\n\t\t\t\tscalar d, T, t, F, f;\r\n\t\t\t\tfor (int n = 0; n<s.nos; n++)\r\n\t\t\t\t{\r\n\t\t\t\t\t// Distance of spin from center\r\n\t\t\t\t\tif (filter(spins[n], positions[n]))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\td = (positions[n] - pos).norm();\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t// Theta\r\n\t\t\t\t\t\tif (d == 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tT = 0;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tT = (positions[n][2] - pos[2]) / d; // angle with respect to the main axis of toroid [0,0,1]\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tT = acos(T);\r\n\t\t\t\t\t\t// ...\r\n\t\t\t\t\t\tt = d / r;\t// r is a big radius of the torus\r\n\t\t\t\t\t\tt = 1.0 + 4.22 / (t*t);\r\n\t\t\t\t\t\ttmp = Pi*(1.0 - 1.0 / sqrt(t));\r\n\t\t\t\t\t\tt = sin(tmp)*sin(T);\r\n\t\t\t\t\t\tt = acos(1.0 - 2.0*t*t);\r\n\t\t\t\t\t\t// ...\r\n\t\t\t\t\t\tF = atan2(positions[n][1] - pos[1], positions[n][0] - pos[0]);\r\n\t\t\t\t\t\tif (T > Pi / 2.0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tf = F + atan(1.0 / (tan(tmp)*cos(T)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tf = F + atan(1.0 / (tan(tmp)*cos(T))) + Pi;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t// Spin orientation\r\n\t\t\t\t\t\tspins[n][0] = sin(t)*cos(order * f);\r\n\t\t\t\t\t\tspins[n][1] = sin(t)*sin(order * f);\r\n\t\t\t\t\t\tspins[n][2] = cos(t);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid Skyrmion(Data::Spin_System & s, Vector3 pos, scalar r, scalar order, scalar phase, bool upDown, bool achiral, bool rl, bool experimental, filterfunction filter)\r\n\t\t{\r\n\t\t\t//bool experimental uses Method similar to PHYSICAL REVIEW B 67, 020401(R) (2003)\r\n\t\t\t\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\r\n\t\t\t// skaled to fit with \r\n\t\t\tscalar r_new = r;\r\n\t\t\tif (experimental) { r_new = r*1.2; }\r\n\t\t\tint iatom, ksi = ((int)rl) * 2 - 1, dir = ((int)upDown) * 2 - 1;\r\n\t\t\tscalar distance, phi_i, theta_i;\r\n\t\t\tfor (iatom = 0; iatom < s.nos; ++iatom)\r\n\t\t\t{\r\n\t\t\t\tdistance = std::sqrt(std::pow(s.geometry->positions[iatom][0] - pos[0], 2) + std::pow(s.geometry->positions[iatom][1] - pos[1], 2));\r\n\t\t\t\tdistance = distance / r_new;\r\n\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble x = (s.geometry->positions[iatom][0] - pos[0]) / distance / r_new;\r\n\t\t\t\t\tphi_i = std::acos(std::max(-1.0, std::min(1.0, x)));\r\n\t\t\t\t\tif (distance == 0) { phi_i = 0; }\r\n\t\t\t\t\tif (s.geometry->positions[iatom][1] - pos[1] < 0.0) { phi_i = - phi_i ; }\r\n\t\t\t\t\tphi_i += phase / 180 * Pi;\r\n\t\t\t\t\tif (experimental) { theta_i = Pi - 4 * std::asin(std::tanh(distance)); }\r\n\t\t\t\t\telse { theta_i = Pi - Pi *distance; }\r\n\r\n\t\t\t\t\tspins[iatom][0] = ksi * std::sin(theta_i) * std::cos(order * phi_i);\r\n\t\t\t\t\tspins[iatom][1] = ksi * std::sin(theta_i) * std::sin(order * (phi_i + achiral * Pi));\r\n\t\t\t\t\tspins[iatom][2] = std::cos(theta_i) * -dir;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (auto& v : spins) v.normalize();\t\r\n\t\t}\r\n\t\t// end Skyrmion\r\n\r\n\t\tvoid SpinSpiral(Data::Spin_System & s, std::string direction_type, Vector3 q, Vector3 axis, scalar theta, filterfunction filter)\r\n\t\t{\r\n\t\t\tscalar phase;\r\n\t\t\tVector3 vx{ 1,0,0 }, vy{ 0,1,0 }, vz{ 0,0,1 };\r\n\t\t\tVector3 e1, e2;\r\n\t\t\t\r\n\t\t\tVector3 a1 = s.geometry->bravais_vectors[0];\r\n\t\t\tVector3 a2 = s.geometry->bravais_vectors[1];\r\n\t\t\tVector3 a3 = s.geometry->bravais_vectors[2];\r\n\t\t\t\r\n\t\t\t// -------------------- Preparation --------------------\r\n\t\t\taxis.normalize();\r\n\t\t\t\r\n\t\t\t/*\r\n\t\t\tif axis_z=0 its in the xy-plane\r\n\t\t\t\taxis, vz, (axis x vz)\r\n\t\t\telse its either above or below the xy-plane.\r\n\t\t\tif its above the xy-plane, it points in z-direction\r\n\t\t\t\taxis, vx, -vy\r\n\t\t\tif its below the xy-plane, it points in -z-direction\r\n\t\t\t\taxis, vx, vy\r\n\t\t\t*/\r\n\t\t\t\r\n\t\t\t// Choose orthogonalisation basis for Grahm-Schmidt\r\n\t\t\t//\t\tWe will need two vectors with which the axis always forms the\r\n\t\t\t//\t\tsame orientation (händigkeit des vektor-dreibeins)\r\n\t\t\t// If axis_z=0 its in the xy-plane\r\n\t\t\t//\t\tthe vectors should be: axis, vz, (axis x vz)\r\n\t\t\tif (axis[2] == 0)\r\n\t\t\t{\r\n\t\t\t\te2 = axis.cross(vz);\r\n\t\t\t\te1 = vz;\r\n\t\t\t}\r\n\t\t\t// Else its either above or below the xy-plane.\r\n\t\t\t//\t\tif its above the xy-plane, it points in z-direction\r\n\t\t\t//\t\tthe vectors should be: axis, vx, -vy\r\n\t\t\telse if (axis[2] > 0)\r\n\t\t\t{\r\n\t\t\t\te1 = vx;\r\n\t\t\t\te2 = -vy;\r\n\t\t\t}\r\n\t\t\t//\t\tif its below the xy-plane, it points in -z-direction\r\n\t\t\t//\t\tthe vectors should be: axis, vx, vy\r\n\t\t\telse if (axis[2] < 0)\r\n\t\t\t{\r\n\t\t\t\te1 = vx;\r\n\t\t\t\te2 = vy;\r\n\t\t\t}\r\n\r\n\t\t\t// Some normalisations\r\n\t\t\ttheta = theta / 180.0 * Pi;\r\n\t\t\tscalar qnorm = q.norm();\r\n\t\t\tscalar axnorm = axis.norm();\r\n\t\t\taxis.normalize();\r\n\r\n\t\t\t// Grahm-Schmidt orthogonalization: two vectors orthogonal to an axis\r\n\t\t\tVector3 v1, v2;\r\n\t\t\t//u1 = axis\r\n\t\t\t//u2 = v1 = vx - vx*axis/|axis|^2 * axis\r\n\t\t\t//u3 = v2 = vy - vy*axis/|axis|^2 * axis - vy*v1/|v1|^2 * v1\r\n\t\t\tscalar proj1 = 0, proj2 = 0, proj3 = 0, proj1a=0, proj2a=0, proj3a=0, proj1b=0, proj2b=0, proj3b=0;\r\n\t\t\t// Projections\r\n\t\t\tproj1a = e1.dot(axis);\r\n\t\t\tproj2a = e2.dot(axis);\r\n\t\t\tproj1b = axis.dot(axis);\r\n\t\t\tproj2b = axis.dot(axis);\r\n\t\t\tproj1 += proj1a / proj1b;\r\n\t\t\tproj2 += proj2a / proj2b;\r\n\r\n\t\t\t// First vector\r\n\t\t\tv1 = e1 - proj1 * axis;\r\n\r\n\t\t\t// One more projection\r\n\t\t\tproj3a = e2.dot(v1);\r\n\t\t\tproj3b = v1.dot(v1);\r\n\t\t\tproj3 = proj3a / proj3b;\r\n\r\n\t\t\t// Second vector\r\n\t\t\tv2 = e2 - proj2 * axis - proj3*v1;\r\n\r\n\t\t\t// -------------------- Spin Spiral creation --------------------\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\t\t\tif (direction_type == \"Reciprocal Lattice\")\r\n\t\t\t{\r\n\t\t\t\t// bi = 2*pi*(aj x ak) / (ai * (aj x ak))\r\n\t\t\t\tVector3 b1, b2, b3;\r\n\t\t\t\tb1 = 2.0 * Pi * a2.cross(a3) / (a1.dot(a2.cross(a3)));\r\n\t\t\t\tb2 = 2.0 * Pi * a3.cross(a1) / (a2.dot(a3.cross(a1)));\r\n\t\t\t\tb3 = 2.0 * Pi * a1.cross(a2) / (a3.dot(a1.cross(a2)));\r\n\t\t\t\t// The q-vector is specified in units of the reciprocal lattice\r\n\t\t\t\tVector3 projBQ = q[0]*b1 + q[1]*b2 + q[2]*b3;\r\n\t\t\t\tq = projBQ;\r\n\t\t\t}\r\n\t\t\telse if (direction_type == \"Real Lattice\")\r\n\t\t\t{\r\n\t\t\t\t// The q-vector is specified in units of the real lattice\r\n\t\t\t\tVector3 projBQ = { q.dot(a1), q.dot(a2), q.dot(a3) };\r\n\t\t\t\tq = projBQ;\r\n\t\t\t}\r\n\t\t\telse if (direction_type == \"Real Space\")\r\n\t\t\t{\r\n\t\t\t\t// The q-vector is specified in units of (x, y, z)\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tLog(Log_Level::Warning, Log_Sender::All, \"Got passed invalid type for SS: \" + direction_type);\r\n\t\t\t}\r\n\t\t\tfor (int iatom = 0; iatom < s.nos; ++iatom)\r\n\t\t\t{\r\n\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t{\r\n\t\t\t\t\t// Phase is scalar product of spin position and q\r\n\t\t\t\t\tphase = s.geometry->positions[iatom].dot(q);\r\n\t\t\t\t\t//phase = phase / 180.0 * Pi;// / period;\r\n\t\t\t\t\t// The opening angle determines how far from the axis the spins rotate around it.\r\n\t\t\t\t\t//\t\tThe rotation is done by alternating between v1 and v2 periodically\r\n\t\t\t\t\tscalar norms = 0.0;\r\n\t\t\t\t\tspins[iatom] = axis * std::cos(theta)\r\n\t\t\t\t\t\t+ v1 * std::cos(phase) * std::sin(theta)\r\n\t\t\t\t\t\t+ v2 * std::sin(phase) * std::sin(theta);\r\n\t\t\t\t\tspins[iatom].normalize();\r\n\t\t\t\t}\r\n\t\t\t}// endfor iatom\r\n\t\t}\r\n\r\n\t\tvoid SpinSpiral(Data::Spin_System & s, std::string direction_type, Vector3 q1, Vector3 q2, Vector3 axis, scalar theta, filterfunction filter)\r\n\t\t{\r\n\t\t\tVector3 vx{ 1,0,0 }, vy{ 0,1,0 }, vz{ 0,0,1 };\r\n\t\t\tVector3 e1, e2;\r\n\t\t\tVector3 qm, qk;\r\n\t\t\t\r\n\t\t\tVector3 a1 = s.geometry->bravais_vectors[0];\r\n\t\t\tVector3 a2 = s.geometry->bravais_vectors[1];\r\n\t\t\tVector3 a3 = s.geometry->bravais_vectors[2];\r\n\t\t\t\r\n\t\t\t// -------------------- Preparation --------------------\r\n\t\t\taxis.normalize();\r\n\t\t\t\r\n\t\t\t/*\r\n\t\t\tif axis_z=0 its in the xy-plane\r\n\t\t\t\taxis, vz, (axis x vz)\r\n\t\t\telse its either above or below the xy-plane.\r\n\t\t\tif its above the xy-plane, it points in z-direction\r\n\t\t\t\taxis, vx, -vy\r\n\t\t\tif its below the xy-plane, it points in -z-direction\r\n\t\t\t\taxis, vx, vy\r\n\t\t\t*/\r\n\t\t\t\r\n\t\t\t// Choose orthogonalisation basis for Grahm-Schmidt\r\n\t\t\t//\t\tWe will need two vectors with which the axis always forms the\r\n\t\t\t//\t\tsame orientation (händigkeit des vektor-dreibeins)\r\n\t\t\t// If axis_z=0 its in the xy-plane\r\n\t\t\t//\t\tthe vectors should be: axis, vz, (axis x vz)\r\n\t\t\tif (axis[2] == 0)\r\n\t\t\t{\r\n\t\t\t\te2 = axis.cross(vz);\r\n\t\t\t\te1 = vz;\r\n\t\t\t}\r\n\t\t\t// Else its either above or below the xy-plane.\r\n\t\t\t//\t\tif its above the xy-plane, it points in z-direction\r\n\t\t\t//\t\tthe vectors should be: axis, vx, -vy\r\n\t\t\telse if (axis[2] > 0)\r\n\t\t\t{\r\n\t\t\t\te1 = vx;\r\n\t\t\t\te2 = -vy;\r\n\t\t\t}\r\n\t\t\t//\t\tif its below the xy-plane, it points in -z-direction\r\n\t\t\t//\t\tthe vectors should be: axis, vx, vy\r\n\t\t\telse if (axis[2] < 0)\r\n\t\t\t{\r\n\t\t\t\te1 = vx;\r\n\t\t\t\te2 = vy;\r\n\t\t\t}\r\n\r\n\t\t\t// Some normalisations\r\n\t\t\ttheta = theta / 180.0 * Pi;\r\n\t\t\tscalar q1norm = q1.norm();\r\n\t\t\tscalar q2norm = q2.norm();\r\n\t\t\tscalar axnorm = axis.norm();\r\n\t\t\taxis.normalize();\r\n\r\n\t\t\t// Grahm-Schmidt orthogonalization: two vectors orthogonal to an axis\r\n\t\t\tVector3 v1, v2;\r\n\t\t\t//u1 = axis\r\n\t\t\t//u2 = v1 = vx - vx*axis/|axis|^2 * axis\r\n\t\t\t//u3 = v2 = vy - vy*axis/|axis|^2 * axis - vy*v1/|v1|^2 * v1\r\n\t\t\tscalar proj1 = 0, proj2 = 0, proj3 = 0, proj1a=0, proj2a=0, proj3a=0, proj1b=0, proj2b=0, proj3b=0;\r\n\t\t\t// Projections\r\n\t\t\tproj1a = e1.dot(axis);\r\n\t\t\tproj2a = e2.dot(axis);\r\n\t\t\tproj1b = axis.dot(axis);\r\n\t\t\tproj2b = axis.dot(axis);\r\n\t\t\tproj1 += proj1a / proj1b;\r\n\t\t\tproj2 += proj2a / proj2b;\r\n\r\n\t\t\t// First vector\r\n\t\t\tv1 = e1 - proj1 * axis;\r\n\r\n\t\t\t// One more projection\r\n\t\t\tproj3a = e2.dot(v1);\r\n\t\t\tproj3b = v1.dot(v1);\r\n\t\t\tproj3 = proj3a / proj3b;\r\n\r\n\t\t\t// Second vector\r\n\t\t\tv2 = e2 - proj2 * axis - proj3*v1;\r\n\r\n\t\t\t// -------------------- Spin Spiral creation --------------------\r\n\t\t\tauto& spins = *s.spins;\r\n\t\t\tauto& positions = s.geometry->positions;\r\n\t\t\tif (direction_type == \"Reciprocal Lattice\")\r\n\t\t\t{\r\n\t\t\t\t// bi = 2*pi*(aj x ak) / (ai * (aj x ak))\r\n\t\t\t\tVector3 b1, b2, b3;\r\n\t\t\t\tb1 = 2.0 * Pi * a2.cross(a3) / (a1.dot(a2.cross(a3)));\r\n\t\t\t\tb2 = 2.0 * Pi * a3.cross(a1) / (a2.dot(a3.cross(a1)));\r\n\t\t\t\tb3 = 2.0 * Pi * a1.cross(a2) / (a3.dot(a1.cross(a2)));\r\n\r\n\t\t\t\t// The q-vectors are specified in units of the reciprocal lattice\r\n\t\t\t\tVector3 projBQ = q1[0]*b1 + q1[1]*b2 + q1[2]*b3;\r\n\t\t\t\tq1 = projBQ;\r\n\t\t\t\tprojBQ = q2[0]*b1 + q2[1]*b2 + q2[2]*b3;\r\n\t\t\t\tq2 = projBQ;\r\n\t\t\t\tqm = (q1+q2)*0.5;\r\n\t\t\t\tqk = (q1-q2)*0.5;\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\telse if (direction_type == \"Real Lattice\")\r\n\t\t\t{\r\n\t\t\t\t// The q-vector is specified in units of the real lattice\r\n\t\t\t\tVector3 projBQ = { q1.dot(a1), q1.dot(a2), q1.dot(a3) };\r\n\t\t\t\tq1 = projBQ;\r\n\t\t\t\tprojBQ = { q2.dot(a1), q2.dot(a2), q2.dot(a3) };\r\n\t\t\t\tq2 = projBQ;\r\n\t\t\t}\r\n\t\t\telse if (direction_type == \"Real Space\")\r\n\t\t\t{\r\n\t\t\t\t// The q-vector is specified in units of (x, y, z)\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tLog(Log_Level::Warning, Log_Sender::All, \"Got passed invalid type for SS: \" + direction_type);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tfor (int iatom = 0; iatom < s.nos; ++iatom)\r\n\t\t\t{\r\n\t\t\t\tif (filter(spins[iatom], positions[iatom]))\r\n\t\t\t\t{\r\n\t\t\t\t\t// Phase is scalar product of spin position and q\r\n\t\t\t\t\tauto& r = s.geometry->positions[iatom];\r\n\t\t\t\t\t//phase = phase / 180.0 * Pi;// / period;\r\n\t\t\t\t\t// The opening angle determines how far from the axis the spins rotate around it.\r\n\t\t\t\t\t//\t\tThe rotation is done by alternating between v1 and v2 periodically\r\n\t\t\t\t\tscalar norms = 0.0;\r\n\t\t\t\t\tspins[iatom] =\taxis * std::sin(r.dot(qm))\r\n\t\t\t\t\t\t+ v1 * std::cos(r.dot(qm)) * std::sin(r.dot(qk))\r\n\t\t\t\t\t\t+ v2 * std::cos(r.dot(qm)) * std::cos(r.dot(qk));\r\n\t\t\t\t\tspins[iatom].normalize();\r\n\t\t\t\t}\r\n\t\t\t}// endfor iatom\r\n\t\t}\r\n\r\n\t}//end namespace Spin_Setters\r\n}//end namespace Utility", "meta": {"hexsha": "86dc102ddc15b180d136321f293dfed87f2c2260", "size": 15493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/utility/Configurations.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/Configurations.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/Configurations.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": 30.8625498008, "max_line_length": 168, "alphanum_fraction": 0.5677402698, "num_tokens": 5159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.06187599004850731, "lm_q1q2_score": 0.02852586964892375}}
{"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 *      15XXXX    D. Dirkx          File created.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#include <iostream>\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/Astrodynamics/Gravitation/gravityFieldModel.h\"\n\nnamespace tudat\n{\nnamespace gravitation\n{\n\n//! Set predefined central gravity field settings.\nboost::shared_ptr< GravityFieldModel > getPredefinedCentralGravityField(\n    BodiesWithPredefinedCentralGravityFields bodyWithPredefinedCentralGravityField )\n{\n    double gravitationalParameter = 0.0;\n\n    // Select body with prefined central gravity field.\n    switch( bodyWithPredefinedCentralGravityField )\n    {\n    case sun:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 1.32712440018e20;\n\n        break;\n\n    case mercury:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 2.203289218e13;\n\n        break;\n\n    case venus:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 3.2485504415e14;\n\n        break;\n\n    case earth:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 3.9859383624e14;\n\n        break;\n\n    case moon:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 4.903686391e12;\n\n        break;\n\n    case mars:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 4.2828018915e13;\n\n        break;\n\n    case jupiter:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 1.2668579374e17;\n\n        break;\n\n    case saturn:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 3.793100511400001e16;\n\n        break;\n\n    case uranus:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 5.793943348799999e15;\n\n        break;\n\n    case neptune:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 6.834733937e15;\n\n        break;\n\n    default:\n\n        // Print cerr statement.\n        std::cerr << \"Desired predefined central gravity field does not exist.\" << std::endl;\n    }\n    return boost::make_shared< GravityFieldModel >( gravitationalParameter );\n}\n\n} // namespace gravitation\n} // namespace tudat\n", "meta": {"hexsha": "6fed5d9ae32d49828f37b57f7ab97a673315a6be", "size": 5863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/gravityFieldModel.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/Gravitation/gravityFieldModel.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/Gravitation/gravityFieldModel.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": 36.1913580247, "max_line_length": 99, "alphanum_fraction": 0.6368753198, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.06187598010131917, "lm_q1q2_score": 0.02852586506310311}}
{"text": "/**\n * @file graph_utils.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_GRAPH_UTILS_H\n#define BOOST_GRAPH_UTILS_H\n\n#include <algorithm>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <optional>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <string_view>\n#include <unordered_set>\n#include <vector>\n\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <arlib/graph_types.hpp>\n#include <arlib/path.hpp>\n#include <arlib/type_traits.hpp>\n\n#include <arlib/multi_predecessor_map.hpp>\n#include <boost/graph/compressed_sparse_row_graph.hpp>\n\n/**\n * An Alternative-Routing library for Boost.Graph\n */\nnamespace arlib {\nusing CSRGraph = boost::compressed_sparse_row_graph<\n    boost::bidirectionalS, boost::no_property,\n    boost::property<boost::edge_weight_t, double>>;\n\nCSRGraph read_csr_graph_from_string(const std::string &graph);\nstd::optional<CSRGraph> read_csr_graph_from_file(const std::string_view path);\n\n/**\n * Constructs a PropertyGraph from vertices, edges and weights contained in a\n * .gr-format string. An example of .gr-format string is the following:\n * ```\n * d\n * # nb_vertices nb_edges\n * 3 2\n * # v1 v2 weight\n * 0 1 4\n * 1 2 3\n * ```\n *\n * @tparam PropertyGraph The Graph type\n * @param graph A .gr-format string defining the graph.\n * @return the constructed graph.\n */\ntemplate <typename PropertyGraph>\nPropertyGraph read_graph_from_string(const std::string &graph) {\n  auto ss = std::stringstream{graph};\n  std::string line{};\n\n  // Drop graph type info\n  std::getline(ss, line);\n\n  // Get number of nodes and edges\n  std::getline(ss, line);\n  auto line_s = std::stringstream{line};\n  int nb_nodes, nb_edges;\n  line_s >> nb_nodes >> nb_edges;\n\n  // Get edges and weights\n  // Get edges and weights\n  using Length = typename arlib::length_of_t<CSRGraph>;\n  auto edges = std::vector<std::pair<long unsigned, long unsigned>>{};\n  auto weights = std::vector<Length>{};\n\n  long unsigned s, t;\n  Length w;\n  while (std::getline(ss, line)) {\n    line_s.str(line);\n    line_s.seekg(std::ios_base::beg);\n    line_s >> s >> t >> w;\n\n    edges.emplace_back(s, t);\n    weights.push_back(w);\n  }\n\n  // Return a PropertyGraph from data\n  auto G = PropertyGraph(std::begin(edges), std::end(edges),\n                         std::begin(weights), nb_nodes);\n\n  return G;\n}\n\ntemplate <typename PropertyGraph>\nstd::optional<PropertyGraph> read_graph_from_file(const std::string_view path) {\n  namespace fs = std::filesystem;\n  auto fs_path = fs::path(path);\n\n  if (!fs::is_regular_file(fs_path)) {\n    std::cerr << fs_path << \" is not a regular file.\\n\";\n    return {};\n  }\n\n  if (fs::is_empty(fs_path)) {\n    std::cerr << fs_path << \" is empty.\\n\";\n    return {};\n  }\n\n  auto buffer = std::stringstream{};\n  auto input = std::ifstream{fs_path.string()};\n  buffer << input.rdbuf();\n\n  return {read_graph_from_string<PropertyGraph>(buffer.str())};\n}\n\n/**\n * Create a string representation of a graph edges and their weight.\n *\n * @tparam Graph A model of EdgeListGraph\n * @param G The graph\n * @return The edges and weights dump\n */\ntemplate <typename Graph> std::string dump_edges_weight(const Graph &G) {\n  using namespace boost;\n  auto ss = std::stringstream{};\n  auto weight = get(edge_weight, G);\n\n  for (auto ei = edges(G).first; ei != edges(G).second; ++ei) {\n    auto w = weight[*ei];\n\n    ss << \"(\" << source(*ei, G) << \", \" << target(*ei, G) << \"; \" << w << \") \";\n  }\n\n  return ss.str();\n}\n\n/**\n * Construct a new Graph from a vector of edges, taking their weights from\n * another graph.\n *\n * @pre Edges in `edge_list` exist in `G`. If not, the behavior is undefined.\n *\n * @tparam Graph The type of the output graph.\n * @param edge_list Vector of `(vertex_id, vertex_id)` edges.\n * @param G The source graph from where to take `edge_list` edges' weights.\n * @return The constructed graph.\n */\ntemplate <typename Graph>\nGraph build_graph_from_edges(const std::vector<VPair> &edge_list,\n                             const Graph &G) {\n  using namespace boost;\n  using Length = typename boost::property_traits<typename boost::property_map<\n      Graph, boost::edge_weight_t>::type>::value_type;\n  auto weight = get(edge_weight, G);\n  auto weights = std::vector<Length>{};\n\n  for (auto &e : edge_list) {\n    auto u = e.first;\n    auto v = e.second;\n    auto edge_in_G = edge(u, v, G).first;\n    weights.push_back(weight[edge_in_G]);\n  }\n\n  return Graph{std::begin(edge_list), std::end(edge_list), std::begin(weights),\n               num_vertices(G)};\n}\n\n/**\n * Construct an [Alternative Graph] from a sequence of\n * paths, taking their weights from another source graph.\n *\n * [Alternative Graph]: http://drops.dagstuhl.de/opus/volltexte/2013/4248/\n *\n * @pre Edges in `paths` exist in `g`. If not, the behavior is undefined.\n *\n * @tparam Graph The type of the output graph.\n * @param paths A vector of simple paths.\n * @param g The source graph from where to take `edge_list` edges' weights.\n * @return The constructed graph.\n */\ntemplate <typename Graph>\nGraph build_AG(const std::vector<Path<Graph>> &paths, const Graph &g) {\n  using namespace boost;\n  using Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\n  using Length = typename boost::property_traits<typename boost::property_map<\n      Graph, boost::edge_weight_t>::type>::value_type;\n\n  auto weight = get(edge_weight, g);\n  auto es = std::vector<VPair>{};\n  auto weights = std::vector<Length>{};\n  auto nodes = std::unordered_set<Vertex>{};\n\n  for (auto &path : paths) {\n    for (auto it = edges(path).first; it != edges(path).second; ++it) {\n      auto u = source(*it, g);\n      auto v = target(*it, g);\n\n      auto e = edge(u, v, g).first; // Assume it exists\n      auto w = weight[e];\n\n      es.emplace_back(u, v);\n      weights.push_back(w);\n\n      if (nodes.find(u) == std::end(nodes)) {\n        nodes.insert(u);\n      }\n\n      if (nodes.find(v) == std::end(nodes)) {\n        nodes.insert(v);\n      }\n    }\n  }\n\n  return Graph{std::begin(es), std::end(es), std::begin(weights),\n               num_vertices(g)};\n}\n\n/**\n * Implementations details of kSPwLO algorithms\n */\nnamespace details {\n/**\n * Construct a Path from a sequence of vertices of a graph `G`.\n *\n * @pre `vertex_descriptor`s of `path` must be vertices of `G`.\n *\n * @tparam Graph A model of a graph for which `edge(u, v, G)` is a valid\n *         expression.\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 * @param path A sequence of vertices of `G` representing a simple-path.\n * @param G The graph.\n * @param W The Weight Property Map of `G`.\n * @return The constructed Path.\n */\ntemplate <typename Graph, typename WeightMap,\n          typename Vertex = vertex_of_t<Graph>>\nPath<Graph> build_path_from(std::vector<Vertex> const &path, Graph const &G,\n                            WeightMap const &W) {\n  using namespace boost;\n  using Length = typename property_traits<\n      typename property_map<Graph, edge_weight_t>::type>::value_type;\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n\n  auto u = *path.begin();\n  auto len = Length{};\n\n  auto path_es = std::unordered_set<Edge, boost::hash<Edge>>{};\n  for (auto it = std::next(std::begin(path)); it != std::end(path); ++it) {\n    auto v = *it;\n    auto [e, is_ok] = edge(u, v, G);\n    assert(is_ok && \"[arlib::details::build_path_from] Edge not found.\");\n    auto weight = W[e];\n    len += weight;\n    path_es.insert(e);\n    u = v;\n  }\n\n  auto path_vs = std::unordered_set<Vertex, boost::hash<Vertex>>{path.cbegin(),\n                                                                 path.cend()};\n  auto edge_pred = alternative_path_edges{std::move(path_es)};\n  auto vertex_pred = alternative_path_vertices{std::move(path_vs)};\n  using FilteredGraph = filtered_graph<Graph, alternative_path_edges<Edge>,\n                                       alternative_path_vertices<Vertex>>;\n  auto fg = std::make_shared<FilteredGraph>(G, edge_pred, vertex_pred);\n  return Path{fg, len};\n}\n\n/**\n * Construct a Path from a sequence of vertices of a graph `G`.\n *\n * @pre `vertex_descriptor`s of `path` must be vertices of `G`.\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n * @param path A sequence of vertices of `G` representing a simple-path.\n * @param G The graph.\n * @return The constructed Path.\n */\ntemplate <typename Graph, typename Vertex = vertex_of_t<Graph>>\nPath<Graph> build_path_from(std::vector<Vertex> const &path, Graph const &G) {\n  using namespace boost;\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n  BOOST_CONCEPT_ASSERT((PropertyGraphConcept<Graph, Edge, edge_weight_t>));\n\n  auto W = get(edge_weight, G);\n  return build_path_from(path, G, W);\n}\n\n} // namespace details\n\n/**\n * Construct a sequence of Path from a graph `G` a pair of source-target\n * vertices a multi_predecessor_map holding alternative paths from `s` to `t`.\n *\n * multi_predecessor_map is often filled by *alternative routing* algorithms\n * like onepass_plus(), esx() or penalty().\n *\n * @tparam Graph A model of a graph for which `edge(u, v, G)` is a valid\n *         expression.\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 * @param G The graph.\n * @param pmap The multi predecessor map of `G`.\n * @param weight The Weight Property Map of `G`.\n * @param s The source vertex.\n * @param t The target vertex.\n * @return A sequence of constructed Path.\n */\ntemplate <typename Graph, typename WeightMap,\n          typename Vertex = vertex_of_t<Graph>>\nstd::vector<Path<Graph>> to_paths(Graph const &G,\n                                  multi_predecessor_map<Vertex> &pmap,\n                                  WeightMap const &weight, Vertex s, Vertex t) {\n  auto res = std::vector<Path<Graph>>{};\n  auto Q = std::stack<std::pair<int, std::vector<Vertex>>>{};\n  for (auto const &[k_th, v] : get(pmap, t)) {\n    Q.push({k_th, {t}});\n  }\n\n  while (!Q.empty()) {\n    auto [k_th, path] = std::move(Q.top());\n    Q.pop();\n    if (path.front() != s) {\n      auto const &preds = get(pmap, path.front());\n      // Stack a pair only for predecessor of same k_th\n      for (auto const &[k_prime, pred] : preds) {\n        if (k_prime == k_th) {\n          auto path_prime = path;\n          path_prime.insert(path_prime.begin(), pred);\n          Q.push({k_prime, std::move(path_prime)});\n        }\n      }\n    } else {\n      res.push_back(details::build_path_from(path, G, weight));\n    }\n  }\n\n  std::sort(res.begin(), res.end(), [](auto const &a, auto const &b) {\n    return a.length() < b.length();\n  });\n  return res;\n}\n\n/**\n * Construct a sequence of Path from a graph `G` a pair of source-target\n * vertices a multi_predecessor_map holding alternative paths from `s` to `t`.\n *\n * multi_predecessor_map is often filled by *alternative routing* algorithms\n * like onepass_plus(), esx() or penalty().\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n * @param G The graph.\n * @param pmap The multi predecessor map of `G`.\n * @param s The source vertex.\n * @param t The target vertex.\n * @return A sequence of constructed Path.\n */\ntemplate <typename Graph, typename Vertex = vertex_of_t<Graph>>\nstd::vector<Path<Graph>> to_paths(Graph const &G,\n                                  multi_predecessor_map<Vertex> &pmap, Vertex s,\n                                  Vertex t) {\n  using namespace boost;\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n  BOOST_CONCEPT_ASSERT((PropertyGraphConcept<Graph, Edge, edge_weight_t>));\n\n  auto weight = get(edge_weight, G);\n  return to_paths(G, pmap, weight, s, t);\n}\n} // namespace arlib\n\n#endif", "meta": {"hexsha": "f1264b46578ad24655aa7be79fc01c1713bdff24", "size": 13873, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/graph_utils.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/graph_utils.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/graph_utils.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": 33.6723300971, "max_line_length": 80, "alphanum_fraction": 0.6675556837, "num_tokens": 3425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.05749327839665524, "lm_q1q2_score": 0.028522060648634384}}
{"text": "//\n// Created by asem on 14/08/18.\n//\n\n#ifndef MARKOVIAN_FEATURES_DLIB_UTILITIES_HPP\n#define MARKOVIAN_FEATURES_DLIB_UTILITIES_HPP\n\n#include <dlib/matrix.h>\n\nnamespace dlib_utilities {\n\ntemplate<typename T>\nstruct column_matrix_like\n{\n    /*!\n        This object defines a matrix expression that holds a reference to a std::vector<T>\n        and makes it look like a column vector.  Thus it enables you to use a std::vector\n        as if it was a dlib::matrix.\n    !*/\n    explicit column_matrix_like( std::vector<T> vect_ ) : _vect( std::move( vect_ ))\n    {}\n\n    template<typename MatrixExpression>\n    explicit column_matrix_like( MatrixExpression exp )\n    {\n        _vect.reserve( exp.size());\n        _vect.insert( _vect.end(), exp.begin(), exp.end());\n    }\n\n    template<typename MatrixExpression>\n    column_matrix_like &operator=( MatrixExpression exp )\n    {\n        _vect.clear();\n        _vect.reserve( exp.nr());\n        _vect.insert( _vect.end(), exp.cbegin(), exp.cend());\n        return *this;\n    }\n\n    // This expression wraps direct memory accesses so we use the lowest possible cost.\n    const static long cost = 1;\n\n    const static long NR = 0; // We don't know the length of the vector until runtime.  So we put 0 here.\n    const static long NC = 1; // We do know that it only has one column (since it's a vector)\n    typedef T type;\n    // Since the std::vector doesn't use a dlib memory manager we list the default one here.\n    typedef dlib::default_memory_manager mem_manager_type;\n    // The layout type also doesn't really matter in this case.  So we list row_major_layout\n    // since it is a good default.\n    typedef dlib::row_major_layout layout_type;\n\n    // Note that we define const_ret_type to be a reference type.  This way we can\n    // return the contents of the std::vector by reference.\n    typedef const T &const_ret_type;\n\n    const_ret_type apply(\n            long r,\n            long\n    ) const\n    { return _vect[r]; }\n\n    long nr() const\n    { return _vect.size(); }\n\n    long nc() const\n    { return 1; }\n\n    std::vector<T> steal_vector()\n    {\n        return std::move( _vect );\n    }\n\n    // This expression never aliases anything since it doesn't contain any matrix expression (it\n    // contains only a std::vector which doesn't count since you can't assign a matrix expression\n    // to a std::vector object).\n    template<typename U>\n    bool aliases( const dlib::matrix_exp<U> & ) const\n    { return false; }\n\n    template<typename U>\n    bool destructively_aliases( const dlib::matrix_exp<U> & ) const\n    { return false; }\n\nprivate:\n    std::vector<T> _vect;\n};\n\ntemplate<typename T>\nstruct row_matrix_like\n{\n    /*!\n        This object defines a matrix expression that holds a reference to a std::vector<T>\n        and makes it look like a column vector.  Thus it enables you to use a std::vector\n        as if it was a dlib::matrix.\n    !*/\n    explicit row_matrix_like( std::vector<T> vect_ ) : _vect( std::move( vect_ ))\n    {}\n\n    template<typename MatrixExpression>\n    explicit row_matrix_like( MatrixExpression exp )\n    {\n        _vect.reserve( exp.size());\n        _vect.insert( _vect.end(), exp.begin(), exp.end());\n    }\n\n    template<typename MatrixExpression>\n    row_matrix_like &operator=( MatrixExpression exp )\n    {\n        _vect.clear();\n        _vect.reserve( exp.size());\n        _vect.insert( _vect.end(), exp.cbegin(), exp.cend());\n        return *this;\n    }\n\n    // This expression wraps direct memory accesses so we use the lowest possible cost.\n    const static long cost = 1;\n\n    const static long NR = 1; // We don't know the length of the vector until runtime.  So we put 0 here.\n    const static long NC = 0; // We do know that it only has one column (since it's a vector)\n    typedef T type;\n    // Since the std::vector doesn't use a dlib memory manager we list the default one here.\n    typedef dlib::default_memory_manager mem_manager_type;\n    // The layout type also doesn't really matter in this case.  So we list row_major_layout\n    // since it is a good default.\n    typedef dlib::row_major_layout layout_type;\n\n    // Note that we define const_ret_type to be a reference type.  This way we can\n    // return the contents of the std::vector by reference.\n    typedef const T &const_ret_type;\n\n    const_ret_type apply(\n            long ,\n            long c\n    ) const\n    { return _vect[c]; }\n\n    long nr() const\n    { return 1; }\n\n    long nc() const\n    { return _vect.size(); }\n\n    std::vector<T> steal_vector()\n    {\n        return std::move( _vect );\n    }\n\n    // This expression never aliases anything since it doesn't contain any matrix expression (it\n    // contains only a std::vector which doesn't count since you can't assign a matrix expression\n    // to a std::vector object).\n    template<typename U>\n    bool aliases( const dlib::matrix_exp<U> & ) const\n    { return false; }\n\n    template<typename U>\n    bool destructively_aliases( const dlib::matrix_exp<U> & ) const\n    { return false; }\n\nprivate:\n    std::vector<T> _vect;\n};\n\ntemplate<typename InputContainer>\nauto vector_to_column_matrix_like( InputContainer &&container )\n{\n    using T = typename std::remove_reference_t<InputContainer>::value_type;\n    using MatrixLike = column_matrix_like<T>;\n\n    std::vector<T> delegate = std::forward<InputContainer>( container );\n    return dlib::matrix_op<MatrixLike>( MatrixLike( std::move( delegate )));\n}\n\ntemplate<typename InputContainer>\nauto vector_to_row_matrix_like( InputContainer &&container )\n{\n    using T = typename std::remove_reference_t<InputContainer>::value_type;\n    using MatrixLike = row_matrix_like<T>;\n\n    std::vector<T> delegate = std::forward<InputContainer>( container );\n    return dlib::matrix_op<MatrixLike>( MatrixLike( std::move( delegate )));\n}\n\n}\n#endif //MARKOVIAN_FEATURES_DLIB_UTILITIES_HPP\n", "meta": {"hexsha": "4739769619ccc1a2ada066523981bc16eec48c04", "size": 5854, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/data/dlib_utilities.hpp", "max_stars_repo_name": "aametwally/MC_MicroSimilarities", "max_stars_repo_head_hexsha": "b625fcbe7eb1fcd8f04fedec1a111b4d3a1bde3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-22T03:08:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-17T02:30:58.000Z", "max_issues_repo_path": "src/data/dlib_utilities.hpp", "max_issues_repo_name": "aametwally/MC_MicroSimilarities", "max_issues_repo_head_hexsha": "b625fcbe7eb1fcd8f04fedec1a111b4d3a1bde3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-02-24T13:13:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T10:10:58.000Z", "max_forks_repo_path": "src/data/dlib_utilities.hpp", "max_forks_repo_name": "aametwally/MC_MicroSimilarities", "max_forks_repo_head_hexsha": "b625fcbe7eb1fcd8f04fedec1a111b4d3a1bde3a", "max_forks_repo_licenses": ["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.8152173913, "max_line_length": 105, "alphanum_fraction": 0.6699692518, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.05834584593319027, "lm_q1q2_score": 0.02848930775366581}}
{"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 <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"SiconosVector.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n#include \"SiconosException.hpp\"\n\nusing namespace Siconos;\n\n//=============================\n// Elements access (get or set)\n//=============================\n\ndouble SimpleMatrix::getValue(unsigned int row, unsigned int col) const\n{\n  if(row >= size(0) || col >= size(1))\n    THROW_EXCEPTION(\"Index out of range\");\n\n  if(_num == Siconos::DENSE)\n    return (*mat.Dense)(row, col);\n  else if(_num == Siconos::TRIANGULAR)\n    return (*mat.Triang)(row, col);\n  else if(_num == Siconos::SYMMETRIC)\n    return (*mat.Sym)(row, col);\n  else if(_num == Siconos::SPARSE)\n  {\n    double * d = (*mat.Sparse).find_element(row, col);\n    if(d)\n      return *d;\n    else\n      return 0.0;\n  }\n  else if(_num == Siconos::SPARSE_COORDINATE)\n  {\n    double * d = (*mat.SparseCoordinate).find_element(row, col);\n    if(d)\n      return *d;\n    else\n      return 0.0;\n  }\n  else if(_num == Siconos::BANDED)\n    return (*mat.Banded)(row, col);\n  else if(_num == Siconos::ZERO)\n    return 0;\n  else //if (_num == Siconos::IDENTITY)\n    return(row == col);\n}\n\nvoid SimpleMatrix::setValue(unsigned int row, unsigned int col, double value)\n{\n  if(row >= size(0) || col >= size(1))\n    THROW_EXCEPTION(\"Index out of range\");\n\n  if(_num == Siconos::DENSE)\n    (*mat.Dense)(row, col) = value;\n  else if(_num == Siconos::TRIANGULAR)\n    (*mat.Triang)(row, col) = value;\n  else if(_num == Siconos::SYMMETRIC)\n    (*mat.Sym)(row, col) = value ;\n  else if(_num == Siconos::SPARSE)\n  {\n    double * d = (*mat.Sparse).find_element(row, col);\n    if(d)\n    {\n      *d = value;\n    }\n    else\n    {\n      (*mat.Sparse).insert_element(row, col, value);\n    }\n  }\n  else if(_num == Siconos::SPARSE_COORDINATE)\n  {\n    // double * d = (*mat.Sparse).find_element(row, col);\n    // if (d)\n    // {\n    //   *d = value;\n    // }\n    // else\n    // {\n    (*mat.SparseCoordinate).insert_element(row, col, value);\n    // }\n  }\n\n  else if(_num == Siconos::BANDED)\n    (*mat.Banded)(row, col) = value;\n  else if(_num == Siconos::ZERO || _num == Siconos::IDENTITY)\n    THROW_EXCEPTION(\"orbidden for Identity or Zero type matrices.\");\n  resetFactorizationFlags();\n\n}\n\n//============================================\n// Access (get or set) to blocks of elements\n//============================================\n\nvoid SimpleMatrix::setBlock(unsigned int row_min, unsigned int col_min, const SiconosMatrix& m)\n{\n  // Set current matrix elements, starting from row row_min and column col_min, with the values of the matrix m.\n  // m may be a BlockMatrix.\n\n  if(&m == this)\n    THROW_EXCEPTION(\"m = this.\");\n\n  if(row_min >= size(0))\n    THROW_EXCEPTION(\"row is out of range\");\n\n  if(col_min >= size(1))\n    THROW_EXCEPTION(\"col is out of range\");\n\n  unsigned int row_max, col_max;\n  row_max = m.size(0) + row_min;\n  col_max = m.size(1) + col_min;\n\n  if(row_max > size(0))\n    THROW_EXCEPTION(\"row is out of range.\");\n\n  if(col_max > size(1))\n    THROW_EXCEPTION(\"m.col + col is out of range.\");\n\n  Siconos::UBLAS_TYPE numM = m.num();\n\n  if(numM == Siconos::BLOCK)  // if m is a block matrix ...\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    BlocksMat::const_iterator1 it;\n    BlocksMat::const_iterator2 it2;\n    unsigned int posRow = row_min;\n    unsigned int posCol = col_min;\n\n    for(it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for(it2 = it.begin(); it2 != it.end(); ++it2)\n      {\n        setBlock(posRow, posCol, **it2);\n        posCol += (*it2)->size(1);\n      }\n      posRow += (*it)->size(0);\n      posCol = col_min;\n    }\n  }\n  else // if m is a SimpleMatrix\n  {\n    if(numM != _num)\n      THROW_EXCEPTION(\"Inconsistent matrix types.\");\n\n    if(_num == Siconos::DENSE)\n      noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) = *(m.dense());\n    else if(_num == Siconos::TRIANGULAR)\n      noalias(ublas::subrange(*mat.Triang, row_min, row_max, col_min, col_max)) = *(m.triang());\n    else if(_num == Siconos::SYMMETRIC)\n      noalias(ublas::subrange(*mat.Sym, row_min, row_max, col_min, col_max)) = *(m.sym());\n    else if(_num == Siconos::SPARSE)\n      noalias(ublas::subrange(*mat.Sparse, row_min, row_max, col_min, col_max)) = *(m.sparse());\n    else if(_num == Siconos::BANDED)\n      noalias(ublas::subrange(*mat.Banded, row_min, row_max, col_min, col_max)) = *(m.banded());\n    else // if(_num == Siconos::ZERO) or _num == Siconos::IDENTITY nothing to do\n    {}\n    resetFactorizationFlags();\n  }\n}\n\nvoid SimpleMatrix::getRow(unsigned int r, SiconosVector &vOut) const\n{\n  // Get row number r of current matrix and copy it into vOut.\n  if(r >= size(0))\n    THROW_EXCEPTION(\"row is out of range\");\n\n  if(vOut.size() != size(1))\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::IDENTITY)  // identity matrix\n  {\n    vOut.zero();\n    vOut(r) = 1.0;\n  }\n  else if(_num == Siconos::ZERO)  // Zero matrix\n    vOut.zero();\n  else\n  {\n    Siconos::UBLAS_TYPE numV = vOut.num();\n    if(numV == Siconos::DENSE)\n    {\n      if(_num == Siconos::DENSE)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Dense, r);\n      }\n      else if(_num == Siconos::TRIANGULAR)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Triang, r);\n      }\n      else if(_num == Siconos::SYMMETRIC)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Sym, r);\n      }\n      else if(_num == Siconos::SPARSE)\n      {\n        noalias(*(vOut.dense())) = ublas::row(*mat.Sparse, r);\n      }\n      else //if(_num == Siconos::BANDED){\n        noalias(*(vOut.dense())) = ublas::row(*mat.Banded, r);\n    }\n    else // if numV == Siconos::SPARSE\n    {\n      if(_num == Siconos::SPARSE)\n      {\n        noalias(*(vOut.sparse())) = ublas::row(*mat.Sparse, r);\n      }\n      else\n        THROW_EXCEPTION(\"inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n}\n\nvoid SimpleMatrix::setRow(unsigned int r, const SiconosVector& vIn)\n{\n  // Set row number r of current matrix with vIn.\n  Siconos::UBLAS_TYPE numV = vIn.num();\n  if(r >= size(0))\n    THROW_EXCEPTION(\"row is out of range\");\n\n  if(vIn.size() != size(1))\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::ZERO || _num == Siconos::IDENTITY)\n    THROW_EXCEPTION(\"current matrix is read-only (zero or identity).\");\n\n  {\n    if(_num == Siconos::DENSE)\n    {\n      if(numV == Siconos::DENSE)\n      {\n        noalias(ublas::row(*mat.Dense, r)) = *vIn.dense();\n      }\n      else if(numV == Siconos::SPARSE)\n      {\n        noalias(ublas::row(*mat.Dense, r)) = *vIn.sparse();\n      }\n    }\n    else if(_num == Siconos::SPARSE && numV == Siconos::SPARSE)\n      noalias(ublas::row(*mat.Sparse, r)) = *vIn.sparse();\n    else\n      THROW_EXCEPTION(\"inconsistent types between current matrix and v.\");\n  }\n\n  resetFactorizationFlags();\n}\n\nvoid SimpleMatrix::getCol(unsigned int r, SiconosVector &vOut)const\n{\n  // Get column number r of current matrix and copy it into vOut.\n  if(r >= size(1))\n    THROW_EXCEPTION(\"col is out of range\");\n\n  if(vOut.size() != size(0))\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::IDENTITY)  // identity matrix\n  {\n    vOut.zero();\n    vOut(r) = 1.0;\n  }\n  else if(_num == Siconos::ZERO)  // Zero matrix\n    vOut.zero();\n  else\n  {\n    Siconos::UBLAS_TYPE numV = vOut.num();\n\n    if(numV == Siconos::DENSE)\n    {\n\n      if(_num == Siconos::DENSE)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Dense, r);\n      }\n      else if(_num == Siconos::TRIANGULAR)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Triang, r);\n      }\n      else if(_num == Siconos::SYMMETRIC)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Sym, r);\n      }\n      else if(_num == Siconos::SPARSE)\n      {\n        noalias(*(vOut.dense())) = ublas::column(*mat.Sparse, r);\n      }\n      else //if(_num == Siconos:BANDED){\n        noalias(*(vOut.dense())) = ublas::column(*mat.Banded, r);\n    }\n    else // if _numV == Siconos::SPARSE\n    {\n      if(_num == Siconos::SPARSE)\n      {\n        noalias(*(vOut.sparse())) = ublas::column(*mat.Sparse, r);\n      }\n      else\n        THROW_EXCEPTION(\"inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n}\n\nvoid SimpleMatrix::setCol(unsigned int r, const SiconosVector &vIn)\n{\n  // Set column number r of current matrix with vIn.\n  Siconos::UBLAS_TYPE numV = vIn.num();\n  if(r >= size(1))\n    THROW_EXCEPTION(\"col is out of range\");\n\n  if(vIn.size() != size(0))\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::ZERO || _num == Siconos::IDENTITY)\n    THROW_EXCEPTION(\"current matrix is read-only (zero or identity).\");\n\n  {\n    if(_num == Siconos::DENSE)\n    {\n      if(numV == Siconos::DENSE)\n      {\n        noalias(ublas::column(*mat.Dense, r)) = *vIn.dense();\n      }\n      else if(numV == Siconos::SPARSE)\n      {\n        noalias(ublas::column(*mat.Dense, r)) = *vIn.sparse();\n      }\n    }\n    else if(_num == Siconos::SPARSE && numV == Siconos::SPARSE)\n      noalias(ublas::column(*mat.Sparse, r)) = *vIn.sparse();\n    else\n      THROW_EXCEPTION(\"nconsistent types between current matrix and v.\");\n  }\n\n  resetFactorizationFlags();\n}\n\nvoid SimpleMatrix::getSubRow(unsigned int r, unsigned int pos, SP::SiconosVector vOut) const\n{\n  // Get row number r of current matrix, starting from element at position pos, and copy it into vOut.\n  if(r >= size(0))\n    THROW_EXCEPTION(\"row is out of range\");\n\n  if(vOut->size() > size(1) - pos)\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::IDENTITY)  // identity matrix\n  {\n    vOut->zero();\n    if(r >= pos)\n      (*vOut)(r - pos) = 1.0;\n  }\n  else if(_num == Siconos::ZERO)  // Zero matrix\n    vOut->zero();\n  else\n  {\n    Siconos::UBLAS_TYPE numV = vOut->num();\n    unsigned int nbEl = vOut->size();\n\n    if(numV == Siconos::DENSE)\n    {\n      if(_num == Siconos::DENSE)\n      {\n        //      noalias(*(vOut->dense())) = ublas::row(ublas::subrange(*mat.Dense, r, r+1,pos, endPos),0);\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n      }\n      else if(_num == Siconos::TRIANGULAR)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<TriangMat >(*mat.Triang, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n      }\n      else if(_num == Siconos::SYMMETRIC)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SymMat >(*mat.Sym, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n      }\n      else if(_num == Siconos::SPARSE)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n      }\n      else //if(_num == Siconos::BANDED){\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<BandedMat >(*mat.Banded, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n    }\n    else // if numV == Siconos::SPARSE\n    {\n      if(_num == Siconos::SPARSE)\n      {\n#ifdef BOOST_LIMITATION\n        THROW_EXCEPTION(\"ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n        noalias(*(vOut->sparse())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl));\n#endif\n      }\n      else\n        THROW_EXCEPTION(\"inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n\n}\n\nvoid SimpleMatrix::setSubRow(unsigned int r, unsigned int pos, SP::SiconosVector vIn)\n{\n  // Set row number r, starting from element at position pos, of current matrix with vIn.\n  Siconos::UBLAS_TYPE numV = vIn->num();\n  if(r >= size(0))\n    THROW_EXCEPTION(\"row is out of range\");\n\n  if(vIn->size() > size(1) - pos)\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::ZERO || _num == Siconos::IDENTITY)\n    THROW_EXCEPTION(\"current matrix is read-only (zero or identity).\");\n\n  {\n    unsigned int nbEl = vIn->size();\n    if(_num == Siconos::DENSE)\n    {\n      if(numV == Siconos::DENSE)\n      {\n        noalias(ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl))) = *vIn->dense();\n      }\n      else if(numV == Siconos::SPARSE)\n      {\n        ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl)) = *vIn->sparse();\n      }\n    }\n    else if(_num == Siconos::SPARSE && numV == Siconos::SPARSE)\n#ifdef BOOST_LIMITATION\n      THROW_EXCEPTION(\"ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n      ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(r, 0, nbEl), ublas::slice(pos, 1, nbEl)) = *vIn->sparse();\n#endif\n    else\n      THROW_EXCEPTION(\"inconsistent types between current matrix and v.\");\n    resetFactorizationFlags();\n  }\n\n}\n\nvoid SimpleMatrix::getSubCol(unsigned int r, unsigned int pos, SP::SiconosVector vOut) const\n{\n  // Get col _number r of current matrix, starting from element at position pos, and copy it into vOut.\n  if(r >= size(1))\n    THROW_EXCEPTION(\"col is out of range\");\n\n  if(vOut->size() > size(0) - pos)\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::IDENTITY)  // identity matrix\n  {\n    vOut->zero();\n    if(r >= pos)\n      (*vOut)(r - pos) = 1.0;\n  }\n  else if(_num == Siconos::ZERO)  // Zero matrix\n    vOut->zero();\n  else\n  {\n    Siconos::UBLAS_TYPE numV = vOut->num();\n    unsigned int nbEl = vOut->size();\n\n    if(numV == Siconos::DENSE)\n    {\n      if(_num == Siconos::DENSE)\n      {\n        //      noalias(*(vOut->dense())) = ublas::row(ublas::subrange(*mat.Dense, r, r+1,pos, endPos),0);\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n      }\n      else if(_num == Siconos::TRIANGULAR)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<TriangMat >(*mat.Triang, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n      }\n      else if(_num == Siconos::SYMMETRIC)\n      {\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SymMat >(*mat.Sym, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n      }\n      else if(_num == Siconos::SPARSE)\n      {\n#ifdef BOOST_LIMITATION\n        THROW_EXCEPTION(\"ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n#endif\n      }\n      else //if(_num == Siconos::BANDED){\n        noalias(*(vOut->dense())) = ublas::matrix_vector_slice<BandedMat >(*mat.Banded, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n    }\n    else // if numV == Siconos::SPARSE\n    {\n      if(_num == Siconos::SPARSE)\n      {\n#ifdef BOOST_LIMITATION\n        THROW_EXCEPTION(\"ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n        noalias(*(vOut->sparse())) = ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl));\n#endif\n      }\n      else\n        THROW_EXCEPTION(\"inconsistent types between this (not sparse) and v (sparse).\");\n    }\n  }\n\n}\n\nvoid SimpleMatrix::setSubCol(unsigned int r, unsigned int pos, SP::SiconosVector vIn)\n{\n  // Set column number r, starting from element at position pos, of current matrix with vIn.\n  Siconos::UBLAS_TYPE numV = vIn->num();\n  if(r >= size(1))\n    THROW_EXCEPTION(\"col is out of range\");\n\n  if(vIn->size() > size(0) - pos)\n    THROW_EXCEPTION(\"inconsistent sizes between this and v.\");\n\n  if(_num == Siconos::ZERO || _num == Siconos::IDENTITY)\n    THROW_EXCEPTION(\"current matrix is read-only (zero or identity).\");\n\n  {\n    unsigned int nbEl = vIn->size();\n    if(_num == Siconos::DENSE)\n    {\n      if(numV == Siconos::DENSE)\n      {\n        noalias(ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl))) = *vIn->dense();\n      }\n      else if(numV == Siconos::SPARSE)\n      {\n        ublas::matrix_vector_slice<DenseMat >(*mat.Dense, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl)) = *vIn->sparse();\n      }\n    }\n    else if(_num == Siconos::SPARSE && numV == Siconos::SPARSE)\n#ifdef BOOST_LIMITATION\n      THROW_EXCEPTION(\"ublas::matrix_vector_slice<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n      ublas::matrix_vector_slice<SparseMat >(*mat.Sparse, ublas::slice(pos, 1, nbEl), ublas::slice(r, 0, nbEl)) = *vIn->sparse();\n#endif\n    else\n      THROW_EXCEPTION(\"inconsistent types between current matrix and v.\");\n    resetFactorizationFlags();\n  }\n}\n\n\n", "meta": {"hexsha": "1204069eacf4e0e9549da000087869e629ec5aef", "size": 17755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixSetGet.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/SimpleMatrixSetGet.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/SimpleMatrixSetGet.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": 31.5364120782, "max_line_length": 143, "alphanum_fraction": 0.611433399, "num_tokens": 5347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.058345843067762165, "lm_q1q2_score": 0.028489306354524846}}
{"text": "#include <armadillo>\n#include <fstream>\n#include \"mcpdft.h\"\n#include \"HDF5_Read_Contiguous.h\"\n#include \"hdf5.h\"\n#include <assert.h>\n\n#define OPDM_H5FILE  \"opdm.h5\"\n#define TPDM_H5FILE  \"tpdm.h5\"\n#define D1A_DATASET  \"/D1a/D1a_DataSet\"\n#define D1B_DATASET  \"/D1b/D1b_DataSet\"\n#define D2AB_DATASET \"/D2ab/D2ab_DataSet\"\n#define RANK 2\n\nnamespace mcpdft {\n\n   void HDF5ReadContiguous::read_rdms(arma::mat &D1a,\n                          arma::mat &D1b,\n\t\t\t  arma::mat &D2ab) {\n      read_opdm(D1a, D1b);\n      read_tpdm(D2ab);\n   }\n\n   void HDF5ReadContiguous::read_opdm(arma::mat &D1a,\n\t\t          arma::mat &D1b) {\n      std::ifstream file(OPDM_H5FILE);\n      if( !file.good() )\n\tthrow \"\\n  Warning: No accessible HDF5 file by the name \\\"opdm.h5\\\" exists!\\n\";\n        file.close();\n\n      assert( D1a.n_cols == D1a.n_rows );\n      assert( D1b.n_cols == D1b.n_rows );\n      size_t dim = D1a.n_cols;\n\n      /* file indentifiers and handles */\n      hid_t file_id;\n      hid_t dcpl_D1a, dcpl_D1b;\n      hid_t D1a_dst_id, D1b_dst_id;\n      herr_t status;\n\n      /* Open the existing HDF5 file in the read-only mode */\n      file_id = H5Fopen(OPDM_H5FILE, H5F_ACC_RDONLY, H5P_DEFAULT);\n\n      /* Open the existing HDF5 dataset in the read-only mode */\n      D1a_dst_id = H5Dopen2(file_id, D1A_DATASET, H5P_DEFAULT);\n\n      /* Open the existing HDF5 dataset in the read-only mode */\n      D1b_dst_id = H5Dopen2(file_id, D1B_DATASET, H5P_DEFAULT);\n\n      /*\n       * Retrieve the dataset creation property list for opdms\n       * and print their storage layout.\n       */\n      dcpl_D1a = H5Dget_create_plist (D1a_dst_id);\n      dcpl_D1b = H5Dget_create_plist (D1b_dst_id);\n      H5D_layout_t layout[] = { H5Pget_layout (dcpl_D1a), H5Pget_layout (dcpl_D1b) };\n      std::string  dataset_names[] = { D1A_DATASET, D1B_DATASET };\n\n      printf (\"-------------------------------------------------------------\\n\");\n      printf (\"          HDF5 OPDM & TPDM FILES LAYOUT SUMMARY              \\n\");\n      printf (\"-------------------------------------------------------------\\n\");\n      for (int i = 0; i < 2; i++) {\n         printf (\"  Storage layout for %s is   : \", dataset_names[i].c_str());\n         switch (layout[i]) {\n             case H5D_COMPACT:\n                 printf (\"H5D_COMPACT\\n\");\n                 break;\n             case H5D_CONTIGUOUS:\n                 printf (\"H5D_CONTIGUOUS\\n\");\n                 break;\n             case H5D_CHUNKED:\n                 printf (\"H5D_CHUNKED\\n\");\n                 break;\n             case H5D_VIRTUAL:\n                 printf (\"H5D_VIRTUAL\\n\");\n                 break;\n             case H5D_LAYOUT_ERROR:\n             case H5D_NLAYOUTS:\n                 printf (\"H5D_LAYOUT_ERROR\\n\");\n         }\n      }\n\n      /* Read the D1a_DataSet */\n      status = H5Dread(D1a_dst_id, H5T_NATIVE_DOUBLE,\n                       H5S_ALL, H5S_ALL, H5P_DEFAULT, D1a.memptr());\n\n      /* Read the D1a_DataSet */\n      status = H5Dread(D1b_dst_id, H5T_NATIVE_DOUBLE,\n                       H5S_ALL, H5S_ALL, H5P_DEFAULT, D1b.memptr());\n\n      /* Close property lists */\n      status = H5Pclose(dcpl_D1a);\n      status = H5Pclose(dcpl_D1b);\n\n      /* Close datasets */\n      status = H5Dclose(D1a_dst_id);\n      status = H5Dclose(D1b_dst_id);\n\n      /* Close the file */\n      status = H5Fclose(file_id); \n   }\n\n   void HDF5ReadContiguous::read_tpdm(arma::mat &D2ab) {\n      std::ifstream file(TPDM_H5FILE);\n      if( !file.good() )\n\tthrow \"\\n  Warning: No accessible HDF5 file by the name \\\"tpdm.h5\\\" exists!\\n\";\n        file.close();\n\n      assert( D2ab.n_cols == D2ab.n_rows );\n      size_t dim = D2ab.n_cols;\n\n      /* file indentifiers and handles */\n      hid_t file_id;\n      hid_t dcpl_D2ab;\n      hid_t D2ab_dst_id;\n      herr_t status;\n\n      /* Open the existing HDF5 file in the read-only mode */\n      file_id = H5Fopen(TPDM_H5FILE, H5F_ACC_RDONLY, H5P_DEFAULT);\n\n      /* Open the existing HDF5 dataset in the read-only mode */\n      D2ab_dst_id = H5Dopen2(file_id, D2AB_DATASET, H5P_DEFAULT);\n\n      /*\n       * Retrieve the dataset creation property list for opdms\n       * and print their storage layout\n       */\n      dcpl_D2ab = H5Dget_create_plist (D2ab_dst_id);\n      H5D_layout_t layout = H5Pget_layout (dcpl_D2ab);\n\n      printf (\"  Storage layout for %s is : \", D2AB_DATASET);\n      switch (layout) {\n          case H5D_COMPACT:\n              printf (\"H5D_COMPACT\\n\");\n              break;\n          case H5D_CONTIGUOUS:\n              printf (\"H5D_CONTIGUOUS\\n\");\n              break;\n          case H5D_CHUNKED:\n              printf (\"H5D_CHUNKED\\n\");\n              break;\n          case H5D_VIRTUAL:\n              printf (\"H5D_VIRTUAL\\n\");\n              break;\n          case H5D_LAYOUT_ERROR:\n          case H5D_NLAYOUTS:\n              printf (\"H5D_LAYOUT_ERROR\\n\");\n      }\n      printf (\"-------------------------------------------------------------\\n\\n\" );\n\n      /* Read the D2ab_DataSet */\n      status = H5Dread(D2ab_dst_id, H5T_NATIVE_DOUBLE,\n                       H5S_ALL, H5S_ALL, H5P_DEFAULT, D2ab.memptr());\n\n      /* Close property list */\n      status = H5Pclose(dcpl_D2ab);\n      \n      /* Close dataset */\n      status = H5Dclose(D2ab_dst_id);\n\n      /* Close the file */\n      status = H5Fclose(file_id); \n   }\n}\n", "meta": {"hexsha": "e1aafff4d198389cc7d2d0f4ff2425875cf042e7", "size": 5278, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libio/HDF5_Read_Contiguous.cc", "max_stars_repo_name": "SinaMostafanejad/libRDMInoles", "max_stars_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T14:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:41:55.000Z", "max_issues_repo_path": "src/libio/HDF5_Read_Contiguous.cc", "max_issues_repo_name": "SinaMostafanejad/libRDMInoles", "max_issues_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libio/HDF5_Read_Contiguous.cc", "max_forks_repo_name": "SinaMostafanejad/libRDMInoles", "max_forks_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-13T05:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-29T02:39:04.000Z", "avg_line_length": 31.9878787879, "max_line_length": 85, "alphanum_fraction": 0.5577870405, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.06097517574577167, "lm_q1q2_score": 0.028347455018977778}}
{"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__MANIFOLD_HPP_\n#define SMOOTH__MANIFOLD_HPP_\n\n#include <Eigen/Core>\n\n#include <concepts>\n\n/**\n * @file manifold.hpp Manifold interface and free Manifold functions.\n */\n\nnamespace smooth {\n\nnamespace traits {\n\n/**\n * @brief Trait class for making a class a Manifold instance via specialization.\n */\ntemplate<typename T>\nstruct man;\n\n}  // namespace traits\n\n// clang-format off\n\n/**\n * @brief Class-external Manifold interface defined through the traits::man trait class.\n */\ntemplate<typename M>\nconcept Manifold =\nrequires  (Eigen::Index dof) {\n  // Underlying scalar type\n  typename traits::man<M>::Scalar;\n  // Default representation\n  typename traits::man<M>::PlainObject;\n  // Compile-time degrees of freedom (tangent space dimension). Can be dynamic (equal to -1)\n  {traits::man<M>::Dof}->std::convertible_to<Eigen::Index>;\n  // A default-initialized Manifold object (if Dof > 0 then dof = Dof can be assumed)\n  {traits::man<M>::Default(dof)}->std::convertible_to<typename traits::man<M>::PlainObject>;\n} &&\nrequires(const M & m1, const M & m2, const Eigen::Vector<typename traits::man<M>::Scalar, traits::man<M>::Dof> & a) {\n  // Run-time degrees of freedom (tangent space dimension)\n  {traits::man<M>::dof(m1)}->std::convertible_to<Eigen::Index>;\n  // Right-plus: add a tangent vector to a Manifold element to obtain a new Manifold element\n  {traits::man<M>::rplus(m1, a)}->std::convertible_to<typename traits::man<M>::PlainObject>;\n  // Right-minus: subtract a Manifold element from another to obtain the difference tangent vector\n  {traits::man<M>::rminus(m1, m2)}->std::convertible_to<Eigen::Vector<typename traits::man<M>::Scalar, traits::man<M>::Dof>>;\n} && (\n  !std::is_convertible_v<typename traits::man<M>::Scalar, double> ||\n  requires (const M & m) {\n    {traits::man<M>::template cast<double>(m)}->std::convertible_to<typename traits::man<M>::template CastT<double>>;\n  }\n) && (\n  !std::is_convertible_v<typename traits::man<M>::Scalar, float> ||\n  requires (const M & m) {\n    {traits::man<M>::template cast<float>(m)}->std::convertible_to<typename traits::man<M>::template CastT<float>>;\n  }\n) &&\n// PlainObject must be default-constructible\nstd::is_default_constructible_v<typename traits::man<M>::PlainObject> &&\nstd::is_copy_constructible_v<typename traits::man<M>::PlainObject> &&\n// PlainObject must be assignable from M\nstd::is_assignable_v<typename traits::man<M>::PlainObject &, M>;\n\n// clang-format on\n\nnamespace traits {\n\n/**\n * @brief Concept to identify Eigen column vectors\n */\ntemplate<typename G>\nconcept RnType = std::is_base_of_v<Eigen::MatrixBase<G>, G> && G::ColsAtCompileTime == 1;\n\n/**\n * @brief Manifold interface for RnType\n */\ntemplate<RnType M>\nstruct man<M>\n{\n  // \\cond\n  static constexpr int Dof = M::SizeAtCompileTime;\n\n  using Scalar      = typename M::Scalar;\n  using PlainObject = Eigen::Vector<Scalar, Dof>;\n  template<typename NewScalar>\n  using CastT = Eigen::Vector<NewScalar, M::SizeAtCompileTime>;\n\n  static inline PlainObject Default(Eigen::Index dof) { return M::Zero(dof); }\n\n  static inline Eigen::Index dof(const M & m) { return m.size(); }\n\n  template<typename NewScalar>\n  static inline CastT<NewScalar> cast(const M & m)\n  {\n    return m.template cast<NewScalar>();\n  }\n\n  template<typename Derived>\n  static inline PlainObject rplus(const M & g, const Eigen::MatrixBase<Derived> & a)\n  {\n    return g + a;\n  }\n\n  template<typename Derived>\n  static inline Eigen::Vector<Scalar, M::SizeAtCompileTime>\n  rminus(const M & m1, const Eigen::MatrixBase<Derived> & m2)\n  {\n    return m1 - m2;\n  }\n  // \\endcond\n};\n\n/**\n * @brief Trait class to mark external types as scalars.\n */\ntemplate<typename T>\nstruct scalar_trait\n{\n  /// @brief true if type T is a scalar\n  static constexpr bool value = false;\n};\n\n/**\n * @brief Concept to identify built-in scalars\n */\ntemplate<typename T>\nconcept ScalarType = std::is_floating_point_v<T> || traits::scalar_trait<T>::value;\n\n/**\n * @brief Manifold interface for ScalarType\n */\n\ntemplate<ScalarType M>\nstruct man<M>\n{\n  // \\cond\n  static constexpr int Dof = 1;\n\n  using Scalar      = M;\n  using PlainObject = M;\n  template<typename NewScalar>\n  using CastT = NewScalar;\n\n  static inline PlainObject Default(Eigen::Index) { return M(0); }\n\n  static inline Eigen::Index dof(const M &) { return 1; }\n\n  template<typename NewScalar>\n  static inline CastT<NewScalar> cast(const M & m)\n  {\n    return static_cast<NewScalar>(m);\n  }\n\n  template<typename Derived>\n  static inline PlainObject rplus(const M & g, const Eigen::MatrixBase<Derived> & a)\n  {\n    return g + a.x();\n  }\n\n  static inline Eigen::Vector<Scalar, Dof> rminus(const M & m1, const M & m2)\n  {\n    return Eigen::Vector<Scalar, Dof>(m1 - m2);\n  }\n  // \\endcond\n};\n\n}  // namespace traits\n\n////////////////////////////////////////////////\n//// Free functions that dispatch to traits::man<M> ////\n////////////////////////////////////////////////\n\n// Static constants\n\n/**\n * @brief Manifold degrees of freedom (tangent space dimension)\n *\n * @note Equal to -1 for a dynamically sized Manifold\n */\ntemplate<Manifold M>\nstatic inline constexpr Eigen::Index Dof = traits::man<M>::Dof;\n\n// Types\n\n/**\n * @brief Manifold scalar type\n */\ntemplate<Manifold M>\nusing Scalar = typename traits::man<M>::Scalar;\n\n/**\n * @brief Manifold default type\n */\ntemplate<Manifold M>\nusing PlainObject = typename traits::man<M>::PlainObject;\n\n/**\n * @brief Cast'ed type\n */\ntemplate<typename NewScalar, Manifold M>\nusing CastT = typename traits::man<M>::template CastT<NewScalar>;\n\n/**\n * @brief Tangent as a Dof-length vector\n */\ntemplate<Manifold M>\nusing Tangent = Eigen::Vector<Scalar<M>, Dof<M>>;\n\n/**\n * @brief Matrix of size Dof x Dof\n */\ntemplate<Manifold M>\nusing TangentMap = Eigen::Matrix<Scalar<M>, Dof<M>, Dof<M>>;\n\n// Functions\n\n/**\n * @brief Default-initialized Manifold\n */\ntemplate<Manifold M>\ninline PlainObject<M> Default(Eigen::Index dof)\n{\n  return traits::man<M>::Default(dof);\n}\n\n/**\n * @brief Default-initialized Manifold with static dof\n */\ntemplate<Manifold M>\ninline PlainObject<M> Default() requires(Dof<M> > 0)\n{\n  return traits::man<M>::Default(Dof<M>);\n}\n\n/**\n * @brief Manifold degrees of freedom (tangent space dimension)\n */\ntemplate<Manifold M>\ninline Eigen::Index dof(const M & m)\n{\n  return traits::man<M>::dof(m);\n}\n\n/**\n * @brief Cast to different scalar type\n */\ntemplate<typename NewScalar, Manifold M>\ninline CastT<NewScalar, M> cast(const M & m)\n{\n  return traits::man<M>::template cast<NewScalar>(m);\n}\n\n/**\n * @brief Manifold right-plus\n */\ntemplate<Manifold M, typename Derived>\ninline PlainObject<M> rplus(const M & m, const Eigen::MatrixBase<Derived> & a)\n{\n  return traits::man<M>::rplus(m, a);\n}\n\n/**\n * @brief Manifold right-minus\n */\ntemplate<Manifold M, Manifold Mo>\ninline Tangent<M> rminus(const M & g1, const Mo & g2)\n{\n  return traits::man<M>::rminus(g1, g2);\n}\n\n}  // namespace smooth\n\n#endif\n", "meta": {"hexsha": "0638d4d221e5c7edeaa13ad356c8306d76aed167", "size": 8165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/manifold.hpp", "max_stars_repo_name": "pettni/smooth", "max_stars_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/manifold.hpp", "max_issues_repo_name": "pettni/lie", "max_issues_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/manifold.hpp", "max_forks_repo_name": "pettni/lie", "max_forks_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 27.2166666667, "max_line_length": 125, "alphanum_fraction": 0.6940600122, "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05665242570615468, "lm_q1q2_score": 0.02832621285307734}}
{"text": "#ifndef KA_FUNCTIONAL_HPP\n#define KA_FUNCTIONAL_HPP\n#pragma once\n#include <boost/config.hpp>\n#include <boost/optional.hpp>\n#include \"integersequence.hpp\"\n#include \"macro.hpp\"\n#include \"macroregular.hpp\"\n#include \"memory.hpp\"\n#include \"src.hpp\"\n#include \"typetraits.hpp\"\n#include \"utility.hpp\"\n\n/// @file\n/// Contains functional tools: function composition, constant function, identity\n/// function, lock-and-call wrapper, etc.\n\nnamespace ka {\n\n  /// Polymorphic function that maps any input to the same output.\n  ///\n  /// Copiable Ret\n  template<typename Ret>\n  struct constant_function_t {\n    Ret ret;\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_1(constant_function_t, ret)\n  // PolymorphicFunction<Ret (Args...)>:\n    template<typename... Args>\n    Ret operator()(Args const&...) const {\n      return ret;\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION_TEMPLATE(constant_function)\n\n  /// `void` specialization\n  template<>\n  struct constant_function_t<void> {\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_0(constant_function_t)\n  // PolymorphicFunction<void (Args...)>:\n    template<typename... Args>\n    void operator()(Args const&...) const {\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION_TEMPLATE_VOID(constant_function)\n\n  /// A polymorphic transformation that takes a value and returns it as-is.\n  ///\n  /// A transformation is a unary function from a type to itself.\n  struct id_transfo_t {\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_0(id_transfo_t)\n  // PolymorphicTransformation:\n    template<typename T>\n    inline T operator()(T const& t) const {\n      return t;\n    }\n  // Isomorphism:\n    friend id_transfo_t retract(id_transfo_t x) {\n      return x;\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION(id_transfo)\n\n  /// A polymorphic action that does not modify its argument.\n  ///\n  /// See concept `Action`.\n  struct id_action_t {\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_0(id_action_t)\n  // PolymorphicAction:\n    template<typename T>\n    inline void operator()(T&) const {\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION(id_action)\n\n// Mainly useful because of the redundancy of trailing return types.\n//\n// TODO: Remove this when get rid of C++11.\n#define KA_FWD_ARGS fwd<Args>(args)...\n\n  namespace detail {\n    template<typename Ret>\n    struct composition_t {\n      /// TODO: Remove the trailing return type when get rid of C++11.\n      template<typename G, typename F, typename... Args>\n      auto operator()(G& g, F& f, Args&&... args) const -> decltype(g(f(KA_FWD_ARGS))) {\n        return g(f(KA_FWD_ARGS));\n      }\n    };\n\n    template<>\n    struct composition_t<void> {\n      /// TODO: Remove the trailing return type when get rid of C++11.\n      template<typename G, typename F, typename... Args>\n      auto operator()(G& g, F& f, Args&&... args) const -> decltype(g()) {\n        return f(KA_FWD_ARGS), g();\n      }\n    };\n  } // namespace detail\n\n  /// Composes two procedures, handling the void case.\n  ///\n  /// In C++, `g(f(x))` is not possible if `f` returns `void` and `g` takes `void`\n  /// (no argument). This case is handled as `f(x), g()`.\n  ///\n  /// Procedure<C (B)> G, Procedure<B (A...)> F\n  template<typename G, typename F>\n  struct composition_t {\n    G g;\n    F f;\n  // Regular (if G and F are):\n    KA_GENERATE_FRIEND_REGULAR_OPS_2(composition_t, g, f)\n  // Procedure<C (A...)>:\n    /// TODO: Remove the trailing return type when get rid of C++11.\n    template<typename... Args>\n    auto operator()(Args&&... args)\n        -> decltype(detail::composition_t<decltype(f(KA_FWD_ARGS))>{}(g, f, KA_FWD_ARGS)) {\n      return detail::composition_t<decltype(f(KA_FWD_ARGS))>{}(g, f, KA_FWD_ARGS);\n    }\n\n    template<typename... Args>\n    auto operator()(Args&&... args) const\n        -> decltype(detail::composition_t<decltype(f(KA_FWD_ARGS))>{}(g, f, KA_FWD_ARGS)) {\n      return detail::composition_t<decltype(f(KA_FWD_ARGS))>{}(g, f, KA_FWD_ARGS);\n    }\n  // RetractableFunction (if `F` and `G` are):\n    // TODO: Add it when switching to C++14.\n    // implementation is: x -> compose(retract(x.f), retract(x.g))\n  };\n\n#undef KA_FWD_ARGS\n\n  namespace detail {\n    template<typename G, typename F>\n    using IsCompositionIdentity = Conjunction<\n      std::is_empty<G>,\n      ka::IsRetract<G, F>>;\n  } // namespace detail\n\n  /// Performs a mathematical function composition.\n  ///\n  /// The composition is smart enough so that if you compose a function and its\n  /// retraction, it will return the identity function.\n  ///\n  /// Example: Composing with a non-void function\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// // `motor` takes a `string` and returns the properties of a motor.\n  /// // `heat` takes the properties of a motor and returns an `int`.\n  /// // `motor_names` is a container of string.\n  /// auto heat_of_motor = compose(heat, motor);\n  /// auto max_heat = std::max_element(motor_names.begin(), motor_names.end(), heat_of_motor);\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Example: Composing with a void function\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// // `log_name` and `log_heat` take no input (void) and returns no ouput (void).\n  /// auto log_name_then_heat = compose(log_heat, log_name);\n  /// auto fut = strand.async(log_name_then_heat);\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Remark: In the future, add a SFINAE guard if there is a name clash.\n  ///   Alternatively, rename this function in `fun_compose`.\n  ///\n  /// Remark: Operator `*` is proposed as an opt-in alternative to `compose` in\n  ///   the `functional_ops` namespace.\n  ///\n  /// Procedure<C (B)> G,\n  /// Procedure<B (Args...)> F\n\n// TODO: Remove this when get rid of VS2013.\n#if KA_COMPILER_VS2013_OR_BELOW\n  // Poor-man version that does not perform  simplifications.\n  template<typename G, typename F>\n  composition_t<Decay<G>, Decay<F>> compose(G&& g, F&& f) {\n    return {fwd<G>(g), fwd<F>(f)};\n  }\n#else\n  template<typename G, typename F, typename =\n    EnableIf<!detail::IsCompositionIdentity<Decay<G>, Decay<F>>::value>>\n  composition_t<Decay<G>, Decay<F>> compose(G&& g, F&& f) {\n    return {fwd<G>(g), fwd<F>(f)};\n  }\n\n  template<typename F, typename = EnableIf<std::is_empty<F>::value>>\n  id_transfo_t compose(Retract<Decay<F>> const&, F const&) {\n    return {};\n  }\n#endif\n\n  template<typename F>\n  F&& compose(id_transfo_t, F&& f) {\n    return fwd<F>(f);\n  }\n\n  template<typename F>\n  F&& compose(F&& f, id_transfo_t) {\n    return fwd<F>(f);\n  }\n\n  // This one could be theoretically handled by the simplifying overload\n  // (because `id_transfo_t` is its own retraction/inverse). But removing this\n  // overload causes overload resolution to fail because of ambiguities.\n  inline id_transfo_t compose(id_transfo_t, id_transfo_t) {\n    return {};\n  }\n\n  /// Composes two accumulations.\n  ///\n  /// An `Accumulation` has the signature `void (T&, Args...)`, meaning it modifies\n  /// its argument in-place. There is always a semantically identical `Function`\n  /// of the form `T (T)`.\n  ///\n  /// Composing two accumulations `g` and `f` is equivalent to perform\n  /// ```\n  /// f(args...);\n  /// g(args...);\n  /// ```\n  /// This implies that both accumulations must have the same signature to be\n  /// composable.\n  ///\n  /// Example: Arithmetic actions\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// using M = matrix_t<int, 10000, 10000>;\n  ///\n  /// // We use actions to avoid the expensive copies that would happen with the\n  /// // equivalent transformations (at least without compiler optimizations).\n  /// incr_t<M> incr;   // signature: void (M&)\n  /// twice_t<M> twice; // signature: void (M&)\n  ///\n  /// // Using `compose` wouldn't work here because we don't pass the output of\n  /// // `incr` to the input of `twice`.\n  ///\n  /// auto twice_of_incr = compose_accu(twice, incr); // signature: void (M&)\n  ///\n  /// M m = compute_matrix();\n  /// twice_of_incr(m); // Apply `incr`, then `twice`.\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Remark: Operator `*=` is proposed as an opt-in alternative to\n  ///   `compose_accu` in the `functional_ops` namespace.\n  ///\n  /// Accumulation<T, Args...> G, Accumulation<T, Args...> F\n  template<typename G, typename F>\n  struct composition_accu_t {\n    G g;\n    F f;\n  // Regular (if G and F are):\n    KA_GENERATE_FRIEND_REGULAR_OPS_2(composition_accu_t, g, f)\n  // Accumulation<T, Args...>:\n    template<typename T, typename... Args>\n    void operator()(T& t, Args const&... args) {\n      f(t, args...);\n      g(t, args...);\n    }\n\n    template<typename T, typename... Args>\n    void operator()(T& t, Args const&... args) const {\n      f(t, args...);\n      g(t, args...);\n    }\n  // IsomorphismAccu (if `F` and `G` are):\n    // TODO: Add it when switching to C++14.\n    // implementation is: x -> compose_accu(retract(x.f), retract(x.g))\n  };\n\n  /// Helper-function to deduce types for `composition_accu_t`.\n  ///\n  /// This function will detect retractions and optimise the composition. This\n  /// means that if you compose an action with its retraction (i.e. an action\n  /// that undoes it), the identity action will be returned.\n  ///\n  /// Accumulation<T...> G, Accumulation<T...> F\n  template<typename G, typename F, typename = EnableIf<\n    !detail::IsCompositionIdentity<Decay<G>, Decay<F>>::value>>\n  composition_accu_t<Decay<G>, Decay<F>> compose_accu(G&& g, F&& f) {\n    return {fwd<G>(g), fwd<F>(f)};\n  }\n\n  template<typename F, typename = EnableIf<std::is_empty<F>::value>>\n  id_action_t compose_accu(Retract<F> const&, F const&) {\n    return {};\n  }\n\n  template<typename F>\n  F&& compose_accu(id_action_t, F&& f) {\n    return fwd<F>(f);\n  }\n\n  template<typename F>\n  F&& compose_accu(F&& f, id_action_t) {\n    return fwd<F>(f);\n  }\n\n  // This one could be theoretically handled by the simplifying overload\n  // (because `id_action_t` is its own inverse). But removing this overload causes\n  // overload resolution to fail because of ambiguities.\n  inline id_action_t compose_accu(id_action_t, id_action_t) {\n    return {};\n  }\n\n  namespace functional_ops {\n    /// Performs a mathematical function composition.\n    ///\n    /// See `compose()`.\n    ///\n    /// `*` is used because in mathematics multiplication denotes an\n    /// associative operation (not required to be commutative).\n    /// Function composition being associative, the composition of `g` with `f`\n    /// is often abbreviated as `gf`, reusing the product notation.\n    ///\n    /// Furthermore `id_transfo_t` being polymorphic, it denotes the identity\n    /// functions for all types, so the function composition together with\n    /// `id_transfo_t` forms a category.\n    ///\n    /// Therefore, the following invariants hold:\n    ///\n    /// ```\n    /// // `f` is an arbitrary function.\n    /// id_transfo_t _1;\n    ///\n    /// assert(f * _1 == f);\n    /// assert(_1 * f == f);\n    /// assert(_1 * _1 == _1);\n    /// ```\n    template<typename G, typename F>\n    auto operator*(G&& g, F&& f) -> decltype(compose(fwd<G>(g), fwd<F>(f))) {\n      return compose(fwd<G>(g), fwd<F>(f));\n    }\n\n    /// Performs a composition of accumulation procedures.\n    ///\n    /// See `compose_accu()`.\n    ///\n    /// `*=` is used as a variant of `*` (the function composition operator).\n    /// The `=` sign is used to emphasize the notion of accumulation.\n    ///\n    /// This naming follows the fact that in the language, binary operations\n    /// typically have a semantically equivalent accumulation counterpart.\n    /// For example for a type `T`, `+: T x T -> T` is a binary operation and\n    /// has for counterpart the semantically equivalent accumulation\n    /// `+=: T& x T -> void`.\n    ///\n    /// So composing functions (i.e. regular procedures with signature\n    /// `A0 x A1 x ... -> B`) is done with `*` and composing accumulations (i.e.\n    /// procedures with signature `A0& x A1 x ... -> void)` is done with `*=`.\n    ///\n    /// Note: Symmetrically to `compose` with `id_transfo_t`, `compose_accu` with\n    ///   `id_action_t` forms a category. Therefore, the same kind of invariants\n    ///   hold:\n    ///\n    /// ```\n    /// // `a` is an arbitrary accumulation.\n    /// id_action_t _1;\n    ///\n    /// assert((a *= _1) == a);\n    /// assert((_1 *= a) == a);\n    /// assert((_1 *= _1) == _1);\n    /// ```\n    template<typename G, typename F>\n    auto operator*=(G&& g, F&& f) -> decltype(compose_accu(fwd<G>(g), fwd<F>(f))) {\n      return compose_accu(fwd<G>(g), fwd<F>(f));\n    }\n  }\n\n  /// Function that transforms the codomain (return type) of the given procedure\n  /// into an \"enriched\" type.\n  ///\n  /// This is related to monad theory (see below).\n  ///\n  /// Example: Transforming a procedure of type (A -> B) in a procedure of type (A -> Future<B>):\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// // `proc` takes an `int` and returns a `bool`\n  /// auto f = semilift(proc, UnitFuture{});\n  /// Future<bool> fut = f(i);\n  /// // ...\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// # Background on monads\n  ///\n  /// A monad can be viewed as an \"enriched\" type together with functions to go\n  /// from and to the corresponding \"base\" type.\n  /// In the above example, `int` is the base type and `Future<int>` is the\n  /// enriched, monadic, type.\n  ///\n  /// To lift is to map a function on base types to a function on the\n  /// corresponding enriched types:\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// enriched \"level\":  X<int> ---> X<bool>\n  ///                            ^\n  ///                            | lift\n  ///                            |\n  /// base \"level\":      int    ---> bool\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// In the above case `X` is `Future`.\n  ///\n  /// Other examples for X are: std::optional, std::vector, etc.\n  ///\n  /// Generally speaking, the enriched type (e.g. X<int>) gives access to a value\n  /// of an underlying type (e.g. int). Thus, it can be viewed as a \"container\".\n  ///\n  /// In our case, we have:\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// enriched \"level\":       X<bool>\n  ///                         ^    ^\n  ///   semilift(proc, unit) /     | unit\n  ///                       /      |\n  /// base \"level\":      int ---> bool\n  ///                        proc\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// This diagram commutes: all paths are equivalent.\n  ///\n  /// That is, we have for all x:\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// semilift(proc, unit)(x) == compose(unit, proc)(x)\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// where `compose` denotes the function composition.\n  ///\n  /// `unit` is a function that sends a \"base\" value to an \"enriched\", monadic value.\n  /// Its name comes from the fact that it is a \"unit\" or \"neutral element\" for\n  /// monadic composition.\n  ///\n  /// This function is named `semilift` because it partially \"lifts\" the procedure:\n  /// only the codomain is enriched.\n  ///\n  /// Procedure Proc\n  template<typename Proc, typename F>\n  auto semilift(Proc&& p, F&& unit) -> decltype(compose(fwd<F>(unit), fwd<Proc>(p))) {\n    return compose(fwd<F>(unit), fwd<Proc>(p));\n  }\n\n  /// Bind a data to a procedure without changing its semantics.\n  /// One use is to bind a shared pointer to extend the lifetime of some data\n  /// related to the procedure.\n  ///\n  /// This type is a useful equivalent to a variadic generic lambda in C++14:\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// T data;\n  /// auto data_bound_proc = [data](auto&&... args) {\n  ///   // ...\n  /// };\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Warning: This type is not strictly equivalent to a lambda (C++14 or even C++17),\n  ///   as it is Regular and lambdas are not.\n  ///\n  /// Procedure Proc\n  template<typename Proc, typename T>\n  struct data_bound_proc_t {\n    Proc proc;\n    T data;\n  // Regular (if T is regular):\n    KA_GENERATE_FRIEND_REGULAR_OPS_2(data_bound_proc_t, proc, data)\n  // Procedure:\n    template<typename... Args>\n    auto operator()(Args&&... args) -> decltype(proc(fwd<Args>(args)...)) {\n      return proc(fwd<Args>(args)...);\n    }\n\n    template<typename... Args>\n    auto operator()(Args&&... args) const -> decltype(proc(fwd<Args>(args)...)) {\n      return proc(fwd<Args>(args)...);\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION_TEMPLATE(data_bound_proc)\n\n  /// A polymorphic transformation that takes a procedure and returns\n  /// an equivalent one that is bound to an arbitrary data.\n  /// The bound data can be a shared pointer to extend the lifetime of an object\n  /// the procedure is dependent on.\n  ///\n  /// Example: extending instance lifetime by binding a shared pointer\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// // Network N\n  /// template<typename N>\n  /// struct X : std::enable_shared_from_this<X> {\n  ///   SendMessageEnqueue<N, SocketPtr<N>> sendMsg;\n  ///\n  ///   void doStuff() {\n  ///     // ...\n  ///     auto onSent = [](...) {\n  ///        // use X's members here\n  ///     };\n  ///     // sendMsg will wrap any asynchronous task by binding it with a\n  ///     // shared pointer on this instance.\n  ///     sendMsg(msg, ssl, onSent,\n  ///       data_bound_transfo(shared_from_this()) // lifetimeTransfo\n  ///     );\n  ///   }\n  /// };\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Regular T\n  template<typename T>\n  struct data_bound_transfo_t {\n    T data;\n  // Regular (if T is regular):\n    KA_GENERATE_FRIEND_REGULAR_OPS_1(data_bound_transfo_t, data)\n  // PolymorphicTransformation:\n    template<typename Proc>\n    data_bound_proc_t<Decay<Proc>, T> operator()(Proc&& p) {\n      return {fwd<Proc>(p), data};\n    }\n\n    template<typename Proc>\n    data_bound_proc_t<Decay<Proc>, T> operator()(Proc&& p) const {\n      return {fwd<Proc>(p), data};\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION_TEMPLATE(data_bound_transfo)\n\n  /// Action that move-assigns a stored value on call.\n  ///\n  /// Warning: Can be called only once because the value assigned from is moved.\n  ///\n  /// With Src s, Dest d, the following is valid:\n  ///   d = std::move(s);\n  template<typename Dest, typename Src>\n  struct move_assign_t {\n    Src s;\n  // Action<T>:\n    /// Precondition: it is the first time this operator is called on this instance\n    void operator()(Dest& d) {\n      d = std::move(s);\n    }\n\n    // TODO: Remove this when get rid of VS2013.\n    move_assign_t(Src&& s)\n      : s(std::move(s)) {\n    }\n\n    // TODO: Remove this when get rid of VS2013.\n    move_assign_t(Src const& s)\n      : s(s) {\n    }\n\n    // TODO: Remove this when get rid of VS2013.\n    move_assign_t(move_assign_t const& other) = default;\n\n    // TODO: Remove this when get rid of VS2013.\n    move_assign_t(move_assign_t&& x)\n      : s(std::move(x.s)) {\n    }\n  };\n\n  /// Helper function that performs type deduction for `MoveAssign`.\n  template<typename Dest, typename Src>\n  move_assign_t<Dest, Decay<Src>> move_assign(Src&& s) {\n    return std::move(move_assign_t<Dest, Decay<Src>>(fwd<Src>(s)));\n  }\n\n  template<typename T>\n  struct incr_mono_t;\n\n  /// Isomorphic action that decrements its parameter.\n  ///\n  /// See `incr_mono_t` for a use example.\n  ///\n  /// The inverse action is `incr_mono_t<T>`\n  ///\n  /// (Arithmetic || BidirectionalIterator) T\n  template<typename T>\n  struct decr_mono_t {\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_0(decr_mono_t)\n  // Action<Arithmetic || BidirectionalIterator>:\n    // TODO: Remove this when get rid of VS2013.\n    using retract_type = incr_mono_t<T>;\n\n    void operator()(T& x) const {\n      --x;\n    }\n  // IsomorphicAction<Integral || BidirectionalIterator>:\n    template<typename U>\n    friend incr_mono_t<U> retract(decr_mono_t<U>);\n  };\n\n  /// Isomorphic action that increments its parameter.\n  ///\n  /// Example: Using in conjunction with scoped tools\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// void pretty_print(doc_t const& doc, std::ostream& o) {\n  ///   // `depth` is an `int` with a wider scope.\n  ///   auto _ = scoped_apply_and_retract(depth, incr_mono_t<int>{});\n  ///   // here, the depth has been incremented\n  ///   ...\n  /// }\n  /// // here, the depth has been decremented\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// The inverse action is `decr_mono_t<T>`.\n  ///\n  /// (Arithmetic || InputIterator) T\n  template<typename T>\n  struct incr_mono_t {\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_0(incr_mono_t)\n  // Action<Arithmetic || InputIterator>:\n    void operator()(T& x) const {\n      ++x;\n    }\n  // IsomorphicAction<Integral || BidirectionalIterator>:\n    // TODO: Remove this when get rid of VS2013.\n    using retract_type = decr_mono_t<T>;\n\n    friend decr_mono_t<T> retract(incr_mono_t) {\n      return {};\n    }\n  };\n\n  template<typename T>\n  incr_mono_t<T> retract(decr_mono_t<T>) {\n    return {};\n  }\n\n  struct incr_t;\n\n  struct decr_t {\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_0(decr_t)\n  // Action<Arithmetic || BidirectionalIterator>:\n    // TODO: Remove this when get rid of VS2013.\n    using retract_type = incr_t;\n\n    template<typename T>\n    inline void operator()(T& x) const {\n      --x;\n    }\n  // IsomorphicAction<Integral || BidirectionalIterator>:\n    inline friend incr_t retract(decr_t);\n  };\n\n  KA_DERIVE_CTOR_FUNCTION(decr)\n\n  struct incr_t {\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_0(incr_t)\n  // Action<Arithmetic || InputIterator>:\n    template<typename T>\n    inline void operator()(T& x) const {\n      ++x;\n    }\n  // IsomorphicAction<Integral || BidirectionalIterator>:\n    // TODO: Remove this when get rid of VS2013.\n    using retract_type = decr_t;\n\n    inline friend decr_t retract(incr_t) {\n      return {};\n    }\n  };\n\n  inline incr_t retract(decr_t) {\n    return {};\n  }\n\n  KA_DERIVE_CTOR_FUNCTION(incr)\n\n  namespace detail {\n    template<typename Proc, typename Args, std::size_t... I>\n    BOOST_CONSTEXPR auto apply_impl(Proc&& proc, Args&& args, index_sequence<I...>)\n      // TODO: Guess what, remove this when c++14 is available.\n        -> decltype(proc(std::get<I>(fwd<Args>(args))...)) {\n      return proc(std::get<I>(fwd<Args>(args))...);\n    }\n  }\n\n  /// Applies the procedure after unpacking the arguments.\n  ///\n  /// Besides std::tuple, arguments can be stored as std::pair, std::array, or\n  /// any type modeling the `Tuple` concept (see concept.hpp).\n  ///\n  /// Note: This is roughly equivalent to C++17's `std::apply`. The main difference\n  /// is that this version use function call syntax instead of C++17's `std::invoke`.\n  ///\n  /// TODO: Replace this by `std::apply` when C++17 is available.\n  ///\n  /// Example: using a `std::tuple` as a container for arguments\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// int f(int i, char c, float f) {\n  ///   ...\n  /// }\n  ///\n  /// // ...\n  /// auto args = std::make_tuple(5, 'a', 3.14f);\n  /// int res = apply(f, args);\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Example: using a `std::pair` as a container for arguments\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// int f(int i, char c) {\n  ///   ...\n  /// }\n  ///\n  /// // ...\n  /// auto args = std::make_pair(5, 'a');\n  /// int res = apply(f, args);\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Example: using a `std::array` as a container for arguments\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// int f(int i, int j, int k, int l) {\n  ///   ...\n  /// }\n  ///\n  /// // ...\n  /// std::array<int, 4> args = {13, 2, 9874, 42};\n  /// int res = apply(f, args);\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Example: using a custom type as a container for arguments\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// namespace test {\n  ///   template<std::size_t N>\n  ///   using index = std::integral_constant<std::size_t, N>;\n  ///\n  ///   template<typename A, typename B, typename C>\n  ///   struct X {\n  ///     A a;\n  ///     B b;\n  ///     C c;\n  ///\n  ///     bool operator==(X const& y) const {\n  ///       return a == y.a && b == y.b && c == y.c;\n  ///     }\n  ///\n  ///     A& get(index<0>) {return a;}\n  ///     B& get(index<1>) {return b;}\n  ///     C& get(index<2>) {return c;}\n  ///     A const& get(index<0>) const {return a;}\n  ///     B const& get(index<1>) const {return b;}\n  ///     C const& get(index<2>) const {return c;}\n  ///   };\n  /// } // namespace test\n  ///\n  /// namespace std {\n  ///   template<typename A, typename B, typename C>\n  ///   struct tuple_size<test::X<A, B, C>> : integral_constant<size_t, 3> {\n  ///   };\n  ///\n  ///   template<size_t I, typename A, typename B, typename C>\n  ///   BOOST_CONSTEXPR auto get(test::X<A, B, C>& x)\n  ///     // TODO: replace the trailing return by a `decltype(auto)` when c++14 is available\n  ///       -> decltype(x.get(integral_constant<size_t, I>{})) {\n  ///     return x.get(integral_constant<size_t, I>{});\n  ///   }\n  ///\n  ///   template<size_t I, typename A, typename B, typename C>\n  ///   BOOST_CONSTEXPR auto get(test::X<A, B, C> const& x)\n  ///     // TODO: replace the trailing return by a `decltype(auto)` when c++14 is available\n  ///       -> decltype(x.get(integral_constant<size_t, I>{})) {\n  ///     return x.get(integral_constant<size_t, I>{});\n  ///   }\n  /// } // namespace std\n  ///\n  /// int f(int i, char c, float f) {\n  ///   ...\n  /// }\n  /// // ...\n  ///\n  /// X const args{5, 'a', 3.14f};\n  /// int res = apply(f, args);\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// See `apply_t` to transform a function into an equivalent tuple-accepting function.\n  ///\n  /// Procedure Proc, Tuple Args\n  template<typename Proc, typename Args>\n  BOOST_CONSTEXPR auto apply(Proc&& proc, Args&& args)\n    // TODO: replace the trailing return by a `decltype(auto)` when c++14 is available\n      -> decltype(detail::apply_impl(fwd<Proc>(proc), fwd<Args>(args),\n        make_index_sequence<std::tuple_size<Decay<Args>>::value>{})) {\n    return detail::apply_impl(fwd<Proc>(proc), fwd<Args>(args),\n      make_index_sequence<std::tuple_size<Decay<Args>>::value>{});\n  }\n\n  /// Procedure accepting a tuple of arguments and unpacking them for the underlying\n  /// procedure.\n  ///\n  /// Example: transforming a \"n-argument function\" into a \"tuple function\"\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// int f(int i, int j) {\n  ///   ...\n  /// };\n  ///\n  /// // ...\n  /// auto f2 = apply(f); // helper function that returns a `apply_t<Decay<decltype(f)>>`\n  /// int res0 = f2(std::make_tuple(4454, 7));\n  /// int res1 = f2(std::make_pair(5, 12));\n  /// int res2 = f2(std::array<int, 2>{98, 99});\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Note: See `apply` for an example on how to use a custom type.\n  ///\n  /// See `apply` for more examples.\n  ///\n  /// Procedure Proc\n  template<typename Proc>\n  struct apply_t {\n    Proc proc;\n  // Regular:\n    KA_GENERATE_FRIEND_REGULAR_OPS_1(apply_t, proc)\n  // Procedure:\n    template<typename Args>\n    auto operator()(Args&& args) KA_NOEXCEPT_EXPR(apply(proc, fwd<Args>(args)))\n        // TODO: replace the trailing return by a `decltype(auto)` when c++14 is available\n        -> decltype(apply(proc, fwd<Args>(args))) {\n      return apply(proc, fwd<Args>(args));\n    }\n\n    template<typename Args>\n    auto operator()(Args&& args) const KA_NOEXCEPT_EXPR(apply(proc, fwd<Args>(args)))\n        // TODO: replace the trailing return by a `decltype(auto)` when c++14 is available\n        -> decltype(apply(proc, fwd<Args>(args))) {\n      return apply(proc, fwd<Args>(args));\n    }\n  };\n\n  /// Helper function to enable type deduction for `apply_t`.\n  ///\n  /// Note: An overload taking the procedure _and_ the arguments also exists.\n  /// This allows for currying.\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// int f(int i, int j) {\n  ///   ...\n  /// };\n  ///\n  /// // ...\n  /// auto args = std::make_pair(34, 45);\n  ///\n  /// // immediate call version\n  /// auto res0 = apply(f, args);\n  ///\n  /// // currified version (this version)\n  /// auto f2 = apply(f);\n  /// auto res1 = f2(args);\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Procedure Proc\n  template<typename Proc>\n  apply_t<Decay<Proc>> apply(Proc&& proc) {\n    return {fwd<Proc>(proc)};\n  }\n\n  namespace detail {\n    template<typename Ret>\n    struct scope_lock_proc_t {\n      template<typename Proc, typename L, typename... Args>\n      boost::optional<Ret> operator()(Proc& proc, L& lockable, Args&&... args) const {\n        if (auto lock = scopelock(lockable)) {\n          return proc(fwd<Args>(args)...);\n        }\n        return {};\n      }\n    };\n\n    template<>\n    struct scope_lock_proc_t<void> {\n      template<typename Proc, typename L, typename... Args>\n      void operator()(Proc& proc, L& lockable, Args&&... args) const {\n        if (auto lock = scopelock(lockable)) {\n          proc(fwd<Args>(args)...);\n        }\n      }\n    };\n  } // namespace detail\n\n  /// Procedure wrapper that calls its underlying procedure only if the associated\n  /// lockable could be locked.\n  ///\n  /// Example: weak_ptr as a lockable to perform lifetime protection\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// // std::shared_ptr<T> p;\n  /// async(scope_lock_proc(\n  ///   [](int i) mutable { // procedure to be called\n  ///     return p->do_stuff(i);\n  ///   },\n  ///   mutable_store(std::weak_ptr<T>{p}) // lockable: will create a non-null shared_ptr on success\n  ///   )\n  /// );\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Procedure<T (...)> Proc,\n  /// Mutable<ScopeLockable> M\n  template<typename Proc, typename M>\n  struct scope_lock_proc_t {\n    Proc proc;\n    M mut_lockable;\n  // Regular (if members are):\n    KA_GENERATE_FRIEND_REGULAR_OPS_2(scope_lock_proc_t, proc, mut_lockable)\n  // Procedure:\n    template<typename... Args>\n    auto operator()(Args&&... args)\n      -> decltype(detail::scope_lock_proc_t<Decay<decltype(proc(fwd<Args>(args)...))>>{}\n                    (proc, src(mut_lockable), fwd<Args>(args)...)) { // TODO: Remove this when we can use C++14\n      return detail::scope_lock_proc_t<Decay<decltype(proc(fwd<Args>(args)...))>>{}\n        (proc, src(mut_lockable), fwd<Args>(args)...);\n    }\n\n    template<typename... Args>\n    auto operator()(Args&&... args) const\n      -> decltype(detail::scope_lock_proc_t<Decay<decltype(proc(fwd<Args>(args)...))>>{}\n                    (proc, src(mut_lockable), fwd<Args>(args)...)) { // TODO: Remove this when we can use C++14\n      return detail::scope_lock_proc_t<Decay<decltype(proc(fwd<Args>(args)...))>>{}\n        (proc, src(mut_lockable), fwd<Args>(args)...);\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION_TEMPLATE(scope_lock_proc)\n\n  /// A polymorphic transformation constructed from an instance `l` of a\n  /// ScopeLockable type that takes a procedure and returns an equivalent one\n  /// that calls that procedure only if l was successfully locked and keeps the\n  /// lock alive until the procedure returns.\n  ///\n  /// Example: mutex as a lockable to protect a asynchronous function call\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  /// int global_count = 0;\n  /// void increment_global_count() {\n  ///   ++global_count;\n  /// }\n  ///\n  /// template<typename P>\n  /// void async_increment_ten_times(P sync_transfo) {\n  ///   for (int i = 0; i < 10; ++i)\n  ///     my::async(sync_transfo(increment_global_count));\n  /// }\n  ///\n  /// void do_stuff() {\n  ///   static std::mutex m;\n  ///   async_increment_ten_times(scope_lock_transfo(&m));\n  /// }\n  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n  ///\n  /// Mutable<ScopeLockable> M\n  template<typename M>\n  struct scope_lock_transfo_t {\n    M mut_lockable;\n  // Regular (if members are regular):\n    KA_GENERATE_FRIEND_REGULAR_OPS_1(scope_lock_transfo_t, mut_lockable)\n  // PolymorphicTransformation:\n    /// Procedure<T (...)> Proc0\n    template<typename Proc>\n    scope_lock_proc_t<Decay<Proc>, M> operator()(Proc&& p) {\n      return { fwd<Proc>(p), mut_lockable };\n    }\n\n    /// Procedure<T (...)> Proc0\n    template<typename Proc>\n    scope_lock_proc_t<Decay<Proc>, M> operator()(Proc&& p) const {\n      return { fwd<Proc>(p), mut_lockable };\n    }\n  };\n\n  KA_DERIVE_CTOR_FUNCTION_TEMPLATE(scope_lock_transfo)\n} // namespace ka\n\n#endif // KA_FUNCTIONAL_HPP\n", "meta": {"hexsha": "48a455524081eb5c1b31341dd53f3ad655cf0aa9", "size": 33330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ka/functional.hpp", "max_stars_repo_name": "yumilceh/libqi", "max_stars_repo_head_hexsha": "f094bcad506bcfd5a8dcfa7688cbcce864b0765b", "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": "ka/functional.hpp", "max_issues_repo_name": "yumilceh/libqi", "max_issues_repo_head_hexsha": "f094bcad506bcfd5a8dcfa7688cbcce864b0765b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ka/functional.hpp", "max_forks_repo_name": "yumilceh/libqi", "max_forks_repo_head_hexsha": "f094bcad506bcfd5a8dcfa7688cbcce864b0765b", "max_forks_repo_licenses": ["BSD-3-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.5031055901, "max_line_length": 111, "alphanum_fraction": 0.5633363336, "num_tokens": 8437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.06465349196072043, "lm_q1q2_score": 0.02830681902870876}}
{"text": "/*\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#include \"dataset.hpp\"\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nnamespace bayesopt\n{\n\n  Dataset::Dataset(): mMinIndex(0), mMaxIndex(0) {};\n\n  Dataset::Dataset(const matrixd& x, const vectord& y):\n    mMinIndex(0), mMaxIndex(0)\n  {\n    setSamples(x,y);\n  };\n\n  Dataset::~Dataset(){};\n\n  void Dataset::setSamples(const matrixd &x, const vectord &y)\n  {\n    // WARNING: It assumes mX is empty\n    mY = y;\n    for (size_t i=0; i<x.size1(); ++i)\n      {\n\tmX.push_back(row(x,i));\n\tupdateMinMax(i);\n      } \n  };\n\n  void Dataset::setSamples(const vectord &y)\n  {\n    mY = y;\n    for (size_t i=0; i<y.size(); ++i)\n      {\n\tupdateMinMax(i);\n      } \n  };\n\n\n  void Dataset::setSamples(const matrixd &x)\n  {\n    for (size_t i=0; i<x.size1(); ++i)\n      {\n\tmX.push_back(row(x,i));\n      } \n  };\n\n  void Dataset::plotData(TLogLevel level)\n  {\n    // For logging purpose\n    FILE_LOG(level) << \"Initial points:\" ;\n    for(size_t i = 0; i < mY.size(); i++)\n      {\n\tFILE_LOG(level) << \"X:\" << mX[i]\n\t\t\t<< \"|Y:\" << mY(i);\n      }\n    const double yPoint = getValueAtMinimum();\n    const vectord xPoint = getPointAtMinimum();\n    FILE_LOG(level) << \"Best point so far:\" ;\n    FILE_LOG(level) << \"X:\" << xPoint\n\t\t    << \"|Y:\" << yPoint;\n    \n  } // plotData\n\n\n} //namespace bayesopt\n", "meta": {"hexsha": "806ac400600aa711a69e38ac334c8f6397600e3a", "size": 2244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/src/dataset.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/dataset.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/dataset.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": 25.5, "max_line_length": 75, "alphanum_fraction": 0.5931372549, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.057493280415308184, "lm_q1q2_score": 0.02829751050408346}}
{"text": "#ifndef PARSER_REGULAR_GRAMMAR_HPP\n#define PARSER_REGULAR_GRAMMAR_HPP\n\n#include <iostream>\n#include <boost/spirit/home/x3.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/io.hpp>\n\n#include <boost/spirit/include/support_istream_iterator.hpp>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#include <formal_languages/devices/Grammar.hpp>\n\nnamespace formal_device\n{\nnamespace grammar\n{\n\nusing string_type = Regular::symbol_type::string_type;\n\nnamespace ast\n{\nstruct Production\n{\n    string_type m_production;\n};\n\nstruct Line\n{\n    string_type m_symbol;\n    std::vector<Production> m_productions;\n};\n\nstruct Document\n{\n    std::vector<Line> m_lines;\n};\n}   // namespace ast\n}   // namespace grammar\n}   // namespace formal_device\n\nBOOST_FUSION_ADAPT_STRUCT(formal_device::grammar::ast::Production, m_production)\nBOOST_FUSION_ADAPT_STRUCT(formal_device::grammar::ast::Line, m_symbol, m_productions)\nBOOST_FUSION_ADAPT_STRUCT(formal_device::grammar::ast::Document, m_lines)\n\nnamespace formal_device\n{\nnamespace grammar\n{\nnamespace parser\n{\n    Regular make_regular_grammar(const string_type & file);\n\n    namespace x3    = boost::spirit::x3;\n    namespace ascii = x3::ascii;\n\n    x3::rule<class production_, ast::Production> production{\"production\"};\n    x3::rule<class line_, ast::Line>             line{\"line\"};\n    x3::rule<class document_, ast::Document>     document{\"document\"};\n\n    const auto identifier     = x3::lexeme[+x3::char_(\"a-zA-Z\")];\n    const auto production_def = identifier;\n    const auto line_def       = identifier >> x3::lit(\"->\") >> production % \"|\";\n    const auto document_def   = line % x3::eol;\n\n    BOOST_SPIRIT_DEFINE(production, line, document);\n}   // namespace ast\n}   // namespace grammar\n}   // namespace formal_devices\n\n#endif\n", "meta": {"hexsha": "b554bb91b12d0d66a0464d5813e26110f5f41613", "size": 1807, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "formal_languages/parsers/GrammarParser.hpp", "max_stars_repo_name": "Bonotto/INE5421", "max_stars_repo_head_hexsha": "d47da55eec17d1c1cab52e4cdf3d50c1e23cad3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "formal_languages/parsers/GrammarParser.hpp", "max_issues_repo_name": "Bonotto/INE5421", "max_issues_repo_head_hexsha": "d47da55eec17d1c1cab52e4cdf3d50c1e23cad3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "formal_languages/parsers/GrammarParser.hpp", "max_forks_repo_name": "Bonotto/INE5421", "max_forks_repo_head_hexsha": "d47da55eec17d1c1cab52e4cdf3d50c1e23cad3e", "max_forks_repo_licenses": ["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.4189189189, "max_line_length": 85, "alphanum_fraction": 0.7271721085, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.06853748922682355, "lm_q1q2_score": 0.028176506771029782}}
{"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_LOWER_TRISOLVE_INCLUDE\n#define MTL_LOWER_TRISOLVE_INCLUDE\n\n#include <boost/mpl/int.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/exception.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/category.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace mat {\n\n\nnamespace detail {\n\n    /// Class that implements lower trisolver\n    /** DiaTag can be tag::regular_diagonal, tag::unit_diagonal, or tag::inverse_diagonal.\n\tCompactStorage means that matrix contains only lower entries (strict lower when DiaTag == unit_diagonal). \\sa \\ref trisolve_object **/\n    template <typename Matrix, typename DiaTag, bool CompactStorage= false>\n    struct lower_trisolve_t\n    {\n\tMTL_STATIC_ASSERT((boost::is_same<DiaTag, tag::regular_diagonal>::value\n\t\t\t   || boost::is_same<DiaTag, tag::unit_diagonal>::value\n\t\t\t   || boost::is_same<DiaTag, tag::inverse_diagonal>::value),\n\t\t\t  \"DiaTag must be either tag::regular_diagonal, tag::unit_diagonal, or tag::inverse_diagonal.\");\n\n\ttypedef typename Collection<Matrix>::value_type         \t       \t    value_type;\n\ttypedef typename Collection<Matrix>::size_type          \t       \t    size_type;\n\ttypedef typename OrientedCollection<Matrix>::orientation\t       \t    my_orientation;\n\ttypedef typename mtl::traits::category<Matrix>::type    \t       \t    my_category;\n\ttypedef typename mtl::traits::range_generator<tag::major, Matrix>::type     a_cur_type; // row or col depending on Matrix    \n\ttypedef typename mtl::traits::range_generator<tag::nz, a_cur_type>::type    a_icur_type;   \n\n\t/// Construction from matrix \\p A\n\tlower_trisolve_t(const Matrix& A) : A(A), value_a(A), col_a(A), row_a(A)\n\t{    MTL_THROW_IF(num_rows(A) != num_cols(A), matrix_not_square());\t}\n\t\n\ttemplate <typename M, typename D, bool C>\n\tstruct generic_version\n\t  : boost::mpl::int_<(mtl::traits::is_row_major<M>::value ? 0 : 2)\n\t                     + (boost::is_same<D, tag::unit_diagonal>::value ? 1 : 2)\n                            > {};\n\n\ttemplate <typename M, typename D, bool C>\n\tstruct version\n\t  : generic_version<M, D, C> {};\n\n\n\ttemplate <typename Value, typename Para, typename D>\n\tstruct version<compressed2D<Value, Para>, D, true>\n\t  : boost::mpl::if_<mtl::traits::is_row_major<Para>,\n\t\t\t    typename boost::mpl::if_<boost::is_same<D, tag::unit_diagonal>,\n\t\t\t\t\t\t     boost::mpl::int_<5>,\n\t\t\t\t\t\t     boost::mpl::int_<6> >::type,\n\t\t\t    generic_version<compressed2D<Value, Para>, D, true>\n\t                   >::type {};\n\n\t/// Solve \\p w = A * \\p v\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid operator()(const VectorIn& v, VectorOut& w) const\n\t{   vampir_trace<5022> tracer; apply(v, w, version<Matrix, DiaTag, CompactStorage>()); }\n\t\n\n      private:\n\ttemplate <typename Value>\n\tValue inline lower_trisolve_diavalue(const Value& v, tag::regular_diagonal) const\n\t{   using math::reciprocal; return reciprocal(v); }\n\n\ttemplate <typename Value>\n\tValue lower_trisolve_diavalue(const Value& v, tag::inverse_diagonal) const\n\t{  return v;\t}    \n\n\ttemplate <typename Tag> int dia_inc(Tag) { return 0; }\n\tint dia_inc(tag::unit_diagonal) { return 1; }\n\n\t// Generic row-major unit_diagonal\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<1>) const\n\t{\n\t    using namespace tag; \n\t    a_cur_type ac= begin<row>(A), aend= end<row>(A); \n\t    for (size_type r= 0; ac != aend; ++r, ++ac) {\n\t\ta_icur_type aic= begin<nz>(ac), aiend= CompactStorage ? end<nz>(ac) : lower_bound<nz>(ac, r);\n\t\ttypename Collection<VectorOut>::value_type rr= v[r];\n\t\tfor (; aic != aiend; ++aic) {\n\t\t    MTL_DEBUG_THROW_IF(col_a(*aic) >= r, logic_error(\"Matrix entries must be sorted for this.\"));\n\t\t    rr-= value_a(*aic) * w[col_a(*aic)];\n\t\t}\n\t\tw[r]= rr;\n\t    }\n\t}\n\n\t// Generic row-major not unit_diagonal\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<2>) const\n\t{\n\t    using namespace tag; \n\t    a_cur_type ac= begin<row>(A), aend= end<row>(A); \n\t    for (size_type r= 0; ac != aend; ++r, ++ac) {\n\t\ta_icur_type aic= begin<nz>(ac), aiend= CompactStorage ? end<nz>(ac) : lower_bound<nz>(ac, r+1);\n\t\tMTL_THROW_IF(aic == aiend, missing_diagonal());\n\t\t--aiend;\n\t\tMTL_THROW_IF(col_a(*aiend) != r, missing_diagonal());\n\n\t\tvalue_type dia= value_a(*aiend);\n\t\ttypename Collection<VectorOut>::value_type rr= v[r];\n\n\t\tfor (; aic != aiend; ++aic) {\n\t\t    MTL_DEBUG_THROW_IF(col_a(*aic) >= r, logic_error(\"Matrix entries must be sorted for this.\"));\n\t\t    rr-= value_a(*aic) * w[col_a(*aic)];\n\t\t}\n\t\tw[r]= rr * lower_trisolve_diavalue(dia, DiaTag());\n\t    }\n\t}\t\n\n\t// Generic column-major unit_diagonal\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<3>) const\n\t{\n\t    using namespace tag; \n\t    w= v;\n\t    a_cur_type ac= begin<col>(A), aend= end<col>(A); \n\t    for (size_type r= 0; ac != aend; ++r, ++ac) {\n\t\ta_icur_type aic= CompactStorage ? begin<nz>(ac) : lower_bound<nz>(ac, r+1), aiend= end<nz>(ac);\n\t\ttypename Collection<VectorOut>::value_type rr= w[r];\n\n\t\tfor (; aic != aiend; ++aic) {\n\t\t    MTL_DEBUG_THROW_IF(row_a(*aic) <= r, logic_error(\"Matrix entries must be sorted for this.\"));\n\t\t    w[row_a(*aic)]-= value_a(*aic) * rr;\n\t\t}\n\t    }\n\t}\n\n\t// Generic column-major not unit_diagonal\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<4>) const\n\t{\n\t    using namespace tag;\n\t    w= v;\n\t    a_cur_type ac= begin<col>(A), aend= end<col>(A); \n\t    for (size_type r= 0; ac != aend; ++r, ++ac) {\n\t\ta_icur_type aic= CompactStorage ? begin<nz>(ac) : lower_bound<nz>(ac, r), aiend= end<nz>(ac);\n\t\tMTL_DEBUG_THROW_IF(aic == aiend || row_a(*aic) != r, missing_diagonal());\n\t\ttypename Collection<VectorOut>::value_type rr= w[r]*= lower_trisolve_diavalue(value_a(*aic), DiaTag());\n\n\t\tfor (++aic; aic != aiend; ++aic) {\n\t\t    MTL_DEBUG_THROW_IF(row_a(*aic) <= r, logic_error(\"Matrix entries must be sorted for this.\"));\n\t\t    w[row_a(*aic)]-= value_a(*aic) * rr;\n\t\t}\n\t    }\n\t}\n\n\t// Tuning for IC_0 and similar using compressed2D row-major compact with implicit unit diagonal\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<5>) const\n\t{\n\t    vampir_trace<5048> tracer;\n\t    if (num_rows(A) == 0) return;\n\t    size_type j1= A.ref_major()[1];\n\t    for (size_type r= 0, rend= num_rows(A); r != rend; ++r) {\n\t\tsize_type j0= j1; \n\t\tj1= A.ref_major()[r+1];\n\t\ttypename Collection<VectorOut>::value_type rr= v[r];\n\t\tfor (; j0 != j1; ++j0) {\n\t\t    MTL_DEBUG_THROW_IF(A.ref_minor()[j0] > r, logic_error(\"Matrix entries from U in lower triangular.\"));\n\t\t    rr-= A.data[j0] * w[A.ref_minor()[j0]];\n\t\t}\n\t\tw[r]= rr;\n\t    }\n\t}\t\n\n\t// Tuning for IC_0 and similar using compressed2D row-major compact with explicitly stored diagonal (possibly already inverted)\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<6>) const\n\t{\n\t    vampir_trace<5047> tracer;\n\t    for (size_type r= 0, rend= num_rows(A); r != rend; ++r) {\n\t\tsize_type j0= A.ref_major()[r], j1= A.ref_major()[r+1];\n\t\tMTL_THROW_IF(j0 == j1, missing_diagonal());\n\t\t--j1;\n\t\tMTL_THROW_IF(A.ref_minor()[j1] != r, missing_diagonal());\n\t\tvalue_type dia= A.data[j1];\n\t\ttypename Collection<VectorOut>::value_type rr= v[r];\n\t\tfor (; j0 != j1; ++j0) {\n\t\t    MTL_DEBUG_THROW_IF(A.ref_minor()[j0] > r, logic_error(\"Matrix entries from U in lower triangular.\"));\n\t\t    rr-= A.data[j0] * w[A.ref_minor()[j0]];\n\t\t}\n\t\tw[r]= rr * lower_trisolve_diavalue(dia, DiaTag());\n\t    }\n\t}\t\n\n\tconst Matrix&                                    A;\n\ttypename mtl::traits::const_value<Matrix>::type  value_a; \n\ttypename mtl::traits::col<Matrix>::type          col_a; \n\ttypename mtl::traits::row<Matrix>::type          row_a;\n    };\n\n}  // detail\n\n\n/// Solves the lower triangular matrix A  with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename Vector>\nVector inline lower_trisolve(const Matrix& A, const Vector& v)\n{\n    Vector w(resource(v));\n    detail::lower_trisolve_t<Matrix, tag::regular_diagonal> solver(A); \n    solver(v, w);\n    return w;\n}\n\n/// Solves the lower triangular matrix A  with the rhs v \ntemplate <typename Matrix, typename VectorIn, typename VectorOut>\ninline void lower_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w)\n{\n    detail::lower_trisolve_t<Matrix, tag::regular_diagonal> solver(A); \n    solver(v, w);\n}\n\n/// Solves the lower triangular matrix A (only one's in the diagonal) with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename Vector>\nVector inline unit_lower_trisolve(const Matrix& A, const Vector& v)\n{\n    Vector w(resource(v));\n    detail::lower_trisolve_t<Matrix, tag::unit_diagonal> solver(A); \n    solver(v, w);\n    return w;\n}\n\n/// Solves the lower triangular matrix A (only one's in the diagonal) with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename VectorIn, typename VectorOut>\ninline void unit_lower_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w)\n{\n    detail::lower_trisolve_t<Matrix, tag::unit_diagonal> solver(A); \n    solver(v, w);\n}\n\n/// Solves the lower triangular matrix A (inverse the diagonal) with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename Vector>\nVector inline inverse_lower_trisolve(const Matrix& A, const Vector& v)\n{\n    Vector w(resource(v));\n    detail::lower_trisolve_t<Matrix, tag::inverse_diagonal> solver(A); \n    solver(v, w);\n    return w;\n}\n\n/// Solves the lower triangular matrix A (inverse the diagonal) with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename VectorIn, typename VectorOut>\ninline void inverse_lower_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w)\n{\n    detail::lower_trisolve_t<Matrix, tag::inverse_diagonal> solver(A); \n    solver(v, w);\n}\n\ntemplate <typename Matrix, typename Vector, typename DiaTag>\nVector inline lower_trisolve(const Matrix& A, const Vector& v, DiaTag)\n{\n    Vector w(resource(v));\n    detail::lower_trisolve_t<Matrix, DiaTag> solver(A); \n    solver(v, w);\n    return w;\n}\n\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename DiaTag>\ninline void lower_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w, DiaTag)\n{\n    detail::lower_trisolve_t<Matrix, DiaTag> solver(A); \n    solver(v, w);\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_LOWER_TRISOLVE_INCLUDE\n", "meta": {"hexsha": "a738784bbab33cd0a963d068d31325168f5fcc2d", "size": 11317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/lower_trisolve.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/operation/lower_trisolve.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/operation/lower_trisolve.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": 38.6245733788, "max_line_length": 135, "alphanum_fraction": 0.6826013961, "num_tokens": 3192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.06008665564415842, "lm_q1q2_score": 0.02816806095130035}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_DIFFERENTIATION_AUTODIFF_HPP\n#define BOOST_MATH_DIFFERENTIATION_AUTODIFF_HPP\n\n#include <boost/cstdfloat.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <boost/math/special_functions/acosh.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n#include <boost/math/special_functions/atanh.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/polygamma.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/special_functions/lambert_w.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/tools/promotion.hpp>\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <functional>\n#include <limits>\n#include <numeric>\n#include <ostream>\n#include <tuple>\n#include <type_traits>\n\nnamespace boost {\nnamespace math {\nnamespace differentiation {\n// Automatic Differentiation v1\ninline namespace autodiff_v1 {\nnamespace detail {\n\ntemplate <typename RealType, typename... RealTypes>\nstruct promote_args_n {\n  using type = typename tools::promote_args_2<RealType, typename promote_args_n<RealTypes...>::type>::type;\n};\n\ntemplate <typename RealType>\nstruct promote_args_n<RealType> {\n  using type = typename tools::promote_arg<RealType>::type;\n};\n\n}  // namespace detail\n\ntemplate <typename RealType, typename... RealTypes>\nusing promote = typename detail::promote_args_n<RealType, RealTypes...>::type;\n\nnamespace detail {\n\ntemplate <typename RealType, size_t Order>\nclass fvar;\n\ntemplate <typename T>\nstruct is_fvar_impl : std::false_type {};\n\ntemplate <typename RealType, size_t Order>\nstruct is_fvar_impl<fvar<RealType, Order>> : std::true_type {};\n\ntemplate <typename T>\nusing is_fvar = is_fvar_impl<typename std::decay<T>::type>;\n\ntemplate <typename RealType, size_t Order, size_t... Orders>\nstruct nest_fvar {\n  using type = fvar<typename nest_fvar<RealType, Orders...>::type, Order>;\n};\n\ntemplate <typename RealType, size_t Order>\nstruct nest_fvar<RealType, Order> {\n  using type = fvar<RealType, Order>;\n};\n\ntemplate <typename>\nstruct get_depth_impl : std::integral_constant<size_t, 0> {};\n\ntemplate <typename RealType, size_t Order>\nstruct get_depth_impl<fvar<RealType, Order>>\n    : std::integral_constant<size_t, get_depth_impl<RealType>::value + 1> {};\n\ntemplate <typename T>\nusing get_depth = get_depth_impl<typename std::decay<T>::type>;\n\ntemplate <typename>\nstruct get_order_sum_t : std::integral_constant<size_t, 0> {};\n\ntemplate <typename RealType, size_t Order>\nstruct get_order_sum_t<fvar<RealType, Order>>\n    : std::integral_constant<size_t, get_order_sum_t<RealType>::value + Order> {};\n\ntemplate <typename T>\nusing get_order_sum = get_order_sum_t<typename std::decay<T>::type>;\n\ntemplate <typename RealType>\nstruct get_root_type {\n  using type = RealType;\n};\n\ntemplate <typename RealType, size_t Order>\nstruct get_root_type<fvar<RealType, Order>> {\n  using type = typename get_root_type<RealType>::type;\n};\n\ntemplate <typename RealType, size_t Depth>\nstruct type_at {\n  using type = RealType;\n};\n\ntemplate <typename RealType, size_t Order, size_t Depth>\nstruct type_at<fvar<RealType, Order>, Depth> {\n  using type = typename conditional<Depth == 0,\n                                    fvar<RealType, Order>,\n                                    typename type_at<RealType, Depth - 1>::type>::type;\n};\n\ntemplate <typename RealType, size_t Depth>\nusing get_type_at = typename type_at<RealType, Depth>::type;\n\n// Satisfies Boost's Conceptual Requirements for Real Number Types.\n// https://www.boost.org/libs/math/doc/html/math_toolkit/real_concepts.html\ntemplate <typename RealType, size_t Order>\nclass fvar {\n protected:\n  std::array<RealType, Order + 1> v;\n\n public:\n  using root_type = typename get_root_type<RealType>::type;  // RealType in the root fvar<RealType,Order>.\n\n  fvar() = default;\n\n  // Initialize a variable or constant.\n  fvar(root_type const&, bool const is_variable);\n\n  // RealType(cr) | RealType | RealType is copy constructible.\n  fvar(fvar const&) = default;\n\n  // Be aware of implicit casting from one fvar<> type to another by this copy constructor.\n  template <typename RealType2, size_t Order2>\n  fvar(fvar<RealType2, Order2> const&);\n\n  // RealType(ca) | RealType | RealType is copy constructible from the arithmetic types.\n  explicit fvar(root_type const&);  // Initialize a constant. (No epsilon terms.)\n\n  template <typename RealType2>\n  fvar(RealType2 const& ca);  // Supports any RealType2 for which static_cast<root_type>(ca) compiles.\n\n  // r = cr | RealType& | Assignment operator.\n  fvar& operator=(fvar const&) = default;\n\n  // r = ca | RealType& | Assignment operator from the arithmetic types.\n  // Handled by constructor that takes a single parameter of generic type.\n  // fvar& operator=(root_type const&); // Set a constant.\n\n  // r += cr | RealType& | Adds cr to r.\n  template <typename RealType2, size_t Order2>\n  fvar& operator+=(fvar<RealType2, Order2> const&);\n\n  // r += ca | RealType& | Adds ar to r.\n  fvar& operator+=(root_type const&);\n\n  // r -= cr | RealType& | Subtracts cr from r.\n  template <typename RealType2, size_t Order2>\n  fvar& operator-=(fvar<RealType2, Order2> const&);\n\n  // r -= ca | RealType& | Subtracts ca from r.\n  fvar& operator-=(root_type const&);\n\n  // r *= cr | RealType& | Multiplies r by cr.\n  template <typename RealType2, size_t Order2>\n  fvar& operator*=(fvar<RealType2, Order2> const&);\n\n  // r *= ca | RealType& | Multiplies r by ca.\n  fvar& operator*=(root_type const&);\n\n  // r /= cr | RealType& | Divides r by cr.\n  template <typename RealType2, size_t Order2>\n  fvar& operator/=(fvar<RealType2, Order2> const&);\n\n  // r /= ca | RealType& | Divides r by ca.\n  fvar& operator/=(root_type const&);\n\n  // -r | RealType | Unary Negation.\n  fvar operator-() const;\n\n  // +r | RealType& | Identity Operation.\n  fvar const& operator+() const;\n\n  // cr + cr2 | RealType | Binary Addition\n  template <typename RealType2, size_t Order2>\n  promote<fvar, fvar<RealType2, Order2>> operator+(fvar<RealType2, Order2> const&) const;\n\n  // cr + ca | RealType | Binary Addition\n  fvar operator+(root_type const&) const;\n\n  // ca + cr | RealType | Binary Addition\n  template <typename RealType2, size_t Order2>\n  friend fvar<RealType2, Order2> operator+(typename fvar<RealType2, Order2>::root_type const&,\n                                           fvar<RealType2, Order2> const&);\n\n  // cr - cr2 | RealType | Binary Subtraction\n  template <typename RealType2, size_t Order2>\n  promote<fvar, fvar<RealType2, Order2>> operator-(fvar<RealType2, Order2> const&) const;\n\n  // cr - ca | RealType | Binary Subtraction\n  fvar operator-(root_type const&) const;\n\n  // ca - cr | RealType | Binary Subtraction\n  template <typename RealType2, size_t Order2>\n  friend fvar<RealType2, Order2> operator-(typename fvar<RealType2, Order2>::root_type const&,\n                                           fvar<RealType2, Order2> const&);\n\n  // cr * cr2 | RealType | Binary Multiplication\n  template <typename RealType2, size_t Order2>\n  promote<fvar, fvar<RealType2, Order2>> operator*(fvar<RealType2, Order2> const&)const;\n\n  // cr * ca | RealType | Binary Multiplication\n  fvar operator*(root_type const&)const;\n\n  // ca * cr | RealType | Binary Multiplication\n  template <typename RealType2, size_t Order2>\n  friend fvar<RealType2, Order2> operator*(typename fvar<RealType2, Order2>::root_type const&,\n                                           fvar<RealType2, Order2> const&);\n\n  // cr / cr2 | RealType | Binary Subtraction\n  template <typename RealType2, size_t Order2>\n  promote<fvar, fvar<RealType2, Order2>> operator/(fvar<RealType2, Order2> const&) const;\n\n  // cr / ca | RealType | Binary Subtraction\n  fvar operator/(root_type const&) const;\n\n  // ca / cr | RealType | Binary Subtraction\n  template <typename RealType2, size_t Order2>\n  friend fvar<RealType2, Order2> operator/(typename fvar<RealType2, Order2>::root_type const&,\n                                           fvar<RealType2, Order2> const&);\n\n  // For all comparison overloads, only the root term is compared.\n\n  // cr == cr2 | bool | Equality Comparison\n  template <typename RealType2, size_t Order2>\n  bool operator==(fvar<RealType2, Order2> const&) const;\n\n  // cr == ca | bool | Equality Comparison\n  bool operator==(root_type const&) const;\n\n  // ca == cr | bool | Equality Comparison\n  template <typename RealType2, size_t Order2>\n  friend bool operator==(typename fvar<RealType2, Order2>::root_type const&, fvar<RealType2, Order2> const&);\n\n  // cr != cr2 | bool | Inequality Comparison\n  template <typename RealType2, size_t Order2>\n  bool operator!=(fvar<RealType2, Order2> const&) const;\n\n  // cr != ca | bool | Inequality Comparison\n  bool operator!=(root_type const&) const;\n\n  // ca != cr | bool | Inequality Comparison\n  template <typename RealType2, size_t Order2>\n  friend bool operator!=(typename fvar<RealType2, Order2>::root_type const&, fvar<RealType2, Order2> const&);\n\n  // cr <= cr2 | bool | Less than equal to.\n  template <typename RealType2, size_t Order2>\n  bool operator<=(fvar<RealType2, Order2> const&) const;\n\n  // cr <= ca | bool | Less than equal to.\n  bool operator<=(root_type const&) const;\n\n  // ca <= cr | bool | Less than equal to.\n  template <typename RealType2, size_t Order2>\n  friend bool operator<=(typename fvar<RealType2, Order2>::root_type const&, fvar<RealType2, Order2> const&);\n\n  // cr >= cr2 | bool | Greater than equal to.\n  template <typename RealType2, size_t Order2>\n  bool operator>=(fvar<RealType2, Order2> const&) const;\n\n  // cr >= ca | bool | Greater than equal to.\n  bool operator>=(root_type const&) const;\n\n  // ca >= cr | bool | Greater than equal to.\n  template <typename RealType2, size_t Order2>\n  friend bool operator>=(typename fvar<RealType2, Order2>::root_type const&, fvar<RealType2, Order2> const&);\n\n  // cr < cr2 | bool | Less than comparison.\n  template <typename RealType2, size_t Order2>\n  bool operator<(fvar<RealType2, Order2> const&) const;\n\n  // cr < ca | bool | Less than comparison.\n  bool operator<(root_type const&) const;\n\n  // ca < cr | bool | Less than comparison.\n  template <typename RealType2, size_t Order2>\n  friend bool operator<(typename fvar<RealType2, Order2>::root_type const&, fvar<RealType2, Order2> const&);\n\n  // cr > cr2 | bool | Greater than comparison.\n  template <typename RealType2, size_t Order2>\n  bool operator>(fvar<RealType2, Order2> const&) const;\n\n  // cr > ca | bool | Greater than comparison.\n  bool operator>(root_type const&) const;\n\n  // ca > cr | bool | Greater than comparison.\n  template <typename RealType2, size_t Order2>\n  friend bool operator>(typename fvar<RealType2, Order2>::root_type const&, fvar<RealType2, Order2> const&);\n\n  // Will throw std::out_of_range if Order < order.\n  template <typename... Orders>\n  get_type_at<RealType, sizeof...(Orders)> at(size_t order, Orders... orders) const;\n\n  template <typename... Orders>\n  get_type_at<fvar, sizeof...(Orders)> derivative(Orders... orders) const;\n\n  const RealType& operator[](size_t) const;\n\n  fvar inverse() const;  // Multiplicative inverse.\n\n  fvar& negate();  // Negate and return reference to *this.\n\n  static constexpr size_t depth = get_depth<fvar>::value;  // Number of nested std::array<RealType,Order>.\n\n  static constexpr size_t order_sum = get_order_sum<fvar>::value;\n\n  explicit operator root_type() const;  // Must be explicit, otherwise overloaded operators are ambiguous.\n\n  template <typename T, typename = typename std::enable_if<std::is_arithmetic<typename std::decay<T>::type>::value>>\n  explicit operator T() const;  // Must be explicit; multiprecision has trouble without the std::enable_if\n\n  fvar& set_root(root_type const&);\n\n  // Apply coefficients using horner method.\n  template <typename Func, typename Fvar, typename... Fvars>\n  promote<fvar<RealType, Order>, Fvar, Fvars...> apply_coefficients(size_t const order,\n                                                                    Func const& f,\n                                                                    Fvar const& cr,\n                                                                    Fvars&&... fvars) const;\n\n  template <typename Func>\n  fvar apply_coefficients(size_t const order, Func const& f) const;\n\n  // Use when function returns derivative(i)/factorial(i) and may have some infinite derivatives.\n  template <typename Func, typename Fvar, typename... Fvars>\n  promote<fvar<RealType, Order>, Fvar, Fvars...> apply_coefficients_nonhorner(size_t const order,\n                                                                              Func const& f,\n                                                                              Fvar const& cr,\n                                                                              Fvars&&... fvars) const;\n\n  template <typename Func>\n  fvar apply_coefficients_nonhorner(size_t const order, Func const& f) const;\n\n  // Apply derivatives using horner method.\n  template <typename Func, typename Fvar, typename... Fvars>\n  promote<fvar<RealType, Order>, Fvar, Fvars...> apply_derivatives(size_t const order,\n                                                                   Func const& f,\n                                                                   Fvar const& cr,\n                                                                   Fvars&&... fvars) const;\n\n  template <typename Func>\n  fvar apply_derivatives(size_t const order, Func const& f) const;\n\n  // Use when function returns derivative(i) and may have some infinite derivatives.\n  template <typename Func, typename Fvar, typename... Fvars>\n  promote<fvar<RealType, Order>, Fvar, Fvars...> apply_derivatives_nonhorner(size_t const order,\n                                                                             Func const& f,\n                                                                             Fvar const& cr,\n                                                                             Fvars&&... fvars) const;\n\n  template <typename Func>\n  fvar apply_derivatives_nonhorner(size_t const order, Func const& f) const;\n\n private:\n  RealType epsilon_inner_product(size_t z0,\n                                 size_t isum0,\n                                 size_t m0,\n                                 fvar const& cr,\n                                 size_t z1,\n                                 size_t isum1,\n                                 size_t m1,\n                                 size_t j) const;\n\n  fvar epsilon_multiply(size_t z0, size_t isum0, fvar const& cr, size_t z1, size_t isum1) const;\n\n  fvar epsilon_multiply(size_t z0, size_t isum0, root_type const& ca) const;\n\n  fvar inverse_apply() const;\n\n  fvar& multiply_assign_by_root_type(bool is_root, root_type const&);\n\n  template <typename RealType2, size_t Orders2>\n  friend class fvar;\n\n  template <typename RealType2, size_t Order2>\n  friend std::ostream& operator<<(std::ostream&, fvar<RealType2, Order2> const&);\n\n  // C++11 Compatibility\n#ifdef BOOST_NO_CXX17_IF_CONSTEXPR\n  template <typename RootType>\n  void fvar_cpp11(std::true_type, RootType const& ca, bool const is_variable);\n\n  template <typename RootType>\n  void fvar_cpp11(std::false_type, RootType const& ca, bool const is_variable);\n\n  template <typename... Orders>\n  get_type_at<RealType, sizeof...(Orders)> at_cpp11(std::true_type, size_t order, Orders... orders) const;\n\n  template <typename... Orders>\n  get_type_at<RealType, sizeof...(Orders)> at_cpp11(std::false_type, size_t order, Orders... orders) const;\n\n  template <typename SizeType>\n  fvar epsilon_multiply_cpp11(std::true_type,\n                              SizeType z0,\n                              size_t isum0,\n                              fvar const& cr,\n                              size_t z1,\n                              size_t isum1) const;\n\n  template <typename SizeType>\n  fvar epsilon_multiply_cpp11(std::false_type,\n                              SizeType z0,\n                              size_t isum0,\n                              fvar const& cr,\n                              size_t z1,\n                              size_t isum1) const;\n\n  template <typename SizeType>\n  fvar epsilon_multiply_cpp11(std::true_type, SizeType z0, size_t isum0, root_type const& ca) const;\n\n  template <typename SizeType>\n  fvar epsilon_multiply_cpp11(std::false_type, SizeType z0, size_t isum0, root_type const& ca) const;\n\n  template <typename RootType>\n  fvar& multiply_assign_by_root_type_cpp11(std::true_type, bool is_root, RootType const& ca);\n\n  template <typename RootType>\n  fvar& multiply_assign_by_root_type_cpp11(std::false_type, bool is_root, RootType const& ca);\n\n  template <typename RootType>\n  fvar& negate_cpp11(std::true_type, RootType const&);\n\n  template <typename RootType>\n  fvar& negate_cpp11(std::false_type, RootType const&);\n\n  template <typename RootType>\n  fvar& set_root_cpp11(std::true_type, RootType const& root);\n\n  template <typename RootType>\n  fvar& set_root_cpp11(std::false_type, RootType const& root);\n#endif\n};\n\n// Standard Library Support Requirements\n\n// fabs(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fabs(fvar<RealType, Order> const&);\n\n// abs(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> abs(fvar<RealType, Order> const&);\n\n// ceil(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> ceil(fvar<RealType, Order> const&);\n\n// floor(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> floor(fvar<RealType, Order> const&);\n\n// exp(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> exp(fvar<RealType, Order> const&);\n\n// pow(cr, ca) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> pow(fvar<RealType, Order> const&, typename fvar<RealType, Order>::root_type const&);\n\n// pow(ca, cr) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> pow(typename fvar<RealType, Order>::root_type const&, fvar<RealType, Order> const&);\n\n// pow(cr1, cr2) | RealType\ntemplate <typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1, Order1>, fvar<RealType2, Order2>> pow(fvar<RealType1, Order1> const&,\n                                                              fvar<RealType2, Order2> const&);\n\n// sqrt(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sqrt(fvar<RealType, Order> const&);\n\n// log(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> log(fvar<RealType, Order> const&);\n\n// frexp(cr1, &i) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> frexp(fvar<RealType, Order> const&, int*);\n\n// ldexp(cr1, i) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> ldexp(fvar<RealType, Order> const&, int);\n\n// cos(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> cos(fvar<RealType, Order> const&);\n\n// sin(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sin(fvar<RealType, Order> const&);\n\n// asin(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> asin(fvar<RealType, Order> const&);\n\n// tan(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> tan(fvar<RealType, Order> const&);\n\n// atan(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atan(fvar<RealType, Order> const&);\n\n// atan2(cr, ca) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atan2(fvar<RealType, Order> const&, typename fvar<RealType, Order>::root_type const&);\n\n// atan2(ca, cr) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atan2(typename fvar<RealType, Order>::root_type const&, fvar<RealType, Order> const&);\n\n// atan2(cr1, cr2) | RealType\ntemplate <typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1, Order1>, fvar<RealType2, Order2>> atan2(fvar<RealType1, Order1> const&,\n                                                                fvar<RealType2, Order2> const&);\n\n// fmod(cr1,cr2) | RealType\ntemplate <typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1, Order1>, fvar<RealType2, Order2>> fmod(fvar<RealType1, Order1> const&,\n                                                               fvar<RealType2, Order2> const&);\n\n// round(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> round(fvar<RealType, Order> const&);\n\n// iround(cr1) | int\ntemplate <typename RealType, size_t Order>\nint iround(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nlong lround(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nlong long llround(fvar<RealType, Order> const&);\n\n// trunc(cr1) | RealType\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> trunc(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nlong double truncl(fvar<RealType, Order> const&);\n\n// itrunc(cr1) | int\ntemplate <typename RealType, size_t Order>\nint itrunc(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nlong long lltrunc(fvar<RealType, Order> const&);\n\n// Additional functions\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> acos(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> acosh(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> asinh(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atanh(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> cosh(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> digamma(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> erf(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> erfc(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> lambert_w0(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> lgamma(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sinc(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sinh(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> tanh(fvar<RealType, Order> const&);\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> tgamma(fvar<RealType, Order> const&);\n\ntemplate <size_t>\nstruct zero : std::integral_constant<size_t, 0> {};\n\n}  // namespace detail\n\ntemplate <typename RealType, size_t Order, size_t... Orders>\nusing autodiff_fvar = typename detail::nest_fvar<RealType, Order, Orders...>::type;\n\ntemplate <typename RealType, size_t Order, size_t... Orders>\nautodiff_fvar<RealType, Order, Orders...> make_fvar(RealType const& ca) {\n  return autodiff_fvar<RealType, Order, Orders...>(ca, true);\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\nnamespace detail {\n\ntemplate <typename RealType, size_t Order, size_t... Is>\nauto make_fvar_for_tuple(std::index_sequence<Is...>, RealType const& ca) {\n  return make_fvar<RealType, zero<Is>::value..., Order>(ca);\n}\n\ntemplate <typename RealType, size_t... Orders, size_t... Is, typename... RealTypes>\nauto make_ftuple_impl(std::index_sequence<Is...>, RealTypes const&... ca) {\n  return std::make_tuple(make_fvar_for_tuple<RealType, Orders>(std::make_index_sequence<Is>{}, ca)...);\n}\n\n}  // namespace detail\n\ntemplate <typename RealType, size_t... Orders, typename... RealTypes>\nauto make_ftuple(RealTypes const&... ca) {\n  static_assert(sizeof...(Orders) == sizeof...(RealTypes),\n                \"Number of Orders must match number of function parameters.\");\n  return detail::make_ftuple_impl<RealType, Orders...>(std::index_sequence_for<RealTypes...>{}, ca...);\n}\n#endif\n\nnamespace detail {\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>::fvar(root_type const& ca, bool const is_variable) {\n  if constexpr (is_fvar<RealType>::value) {\n    v.front() = RealType(ca, is_variable);\n    if constexpr (0 < Order)\n      std::fill(v.begin() + 1, v.end(), static_cast<RealType>(0));\n  } else {\n    v.front() = ca;\n    if constexpr (0 < Order)\n      v[1] = static_cast<root_type>(static_cast<int>(is_variable));\n    if constexpr (1 < Order)\n      std::fill(v.begin() + 2, v.end(), static_cast<RealType>(0));\n  }\n}\n#endif\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nfvar<RealType, Order>::fvar(fvar<RealType2, Order2> const& cr) {\n  for (size_t i = 0; i <= (std::min)(Order, Order2); ++i)\n    v[i] = static_cast<RealType>(cr.v[i]);\n  BOOST_IF_CONSTEXPR (Order2 < Order)\n    std::fill(v.begin() + (Order2 + 1), v.end(), static_cast<RealType>(0));\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>::fvar(root_type const& ca) : v{{static_cast<RealType>(ca)}} {}\n\n// Can cause compiler error if RealType2 cannot be cast to root_type.\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2>\nfvar<RealType, Order>::fvar(RealType2 const& ca) : v{{static_cast<RealType>(ca)}} {}\n\n/*\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::operator=(root_type const& ca)\n{\n    v.front() = static_cast<RealType>(ca);\n    if constexpr (0 < Order)\n        std::fill(v.begin()+1, v.end(), static_cast<RealType>(0));\n    return *this;\n}\n*/\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nfvar<RealType, Order>& fvar<RealType, Order>::operator+=(fvar<RealType2, Order2> const& cr) {\n  for (size_t i = 0; i <= (std::min)(Order, Order2); ++i)\n    v[i] += cr.v[i];\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::operator+=(root_type const& ca) {\n  v.front() += ca;\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nfvar<RealType, Order>& fvar<RealType, Order>::operator-=(fvar<RealType2, Order2> const& cr) {\n  for (size_t i = 0; i <= Order; ++i)\n    v[i] -= cr.v[i];\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::operator-=(root_type const& ca) {\n  v.front() -= ca;\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nfvar<RealType, Order>& fvar<RealType, Order>::operator*=(fvar<RealType2, Order2> const& cr) {\n  using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n  promote<RealType, RealType2> const zero(0);\n  BOOST_IF_CONSTEXPR (Order <= Order2)\n    for (size_t i = 0, j = Order; i <= Order; ++i, --j)\n      v[j] = std::inner_product(v.cbegin(), v.cend() - diff_t(i), cr.v.crbegin() + diff_t(i), zero);\n  else {\n    for (size_t i = 0, j = Order; i <= Order - Order2; ++i, --j)\n      v[j] = std::inner_product(cr.v.cbegin(), cr.v.cend(), v.crbegin() + diff_t(i), zero);\n    for (size_t i = Order - Order2 + 1, j = Order2 - 1; i <= Order; ++i, --j)\n      v[j] = std::inner_product(cr.v.cbegin(), cr.v.cbegin() + diff_t(j + 1), v.crbegin() + diff_t(i), zero);\n  }\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::operator*=(root_type const& ca) {\n  return multiply_assign_by_root_type(true, ca);\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nfvar<RealType, Order>& fvar<RealType, Order>::operator/=(fvar<RealType2, Order2> const& cr) {\n  using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n  RealType const zero(0);\n  v.front() /= cr.v.front();\n  BOOST_IF_CONSTEXPR (Order < Order2)\n    for (size_t i = 1, j = Order2 - 1, k = Order; i <= Order; ++i, --j, --k)\n      (v[i] -= std::inner_product(\n           cr.v.cbegin() + 1, cr.v.cend() - diff_t(j), v.crbegin() + diff_t(k), zero)) /= cr.v.front();\n  else BOOST_IF_CONSTEXPR (0 < Order2)\n    for (size_t i = 1, j = Order2 - 1, k = Order; i <= Order; ++i, j && --j, --k)\n      (v[i] -= std::inner_product(\n           cr.v.cbegin() + 1, cr.v.cend() - diff_t(j), v.crbegin() + diff_t(k), zero)) /= cr.v.front();\n  else\n    for (size_t i = 1; i <= Order; ++i)\n      v[i] /= cr.v.front();\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::operator/=(root_type const& ca) {\n  std::for_each(v.begin(), v.end(), [&ca](RealType& x) { x /= ca; });\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::operator-() const {\n  fvar<RealType, Order> retval(*this);\n  retval.negate();\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> const& fvar<RealType, Order>::operator+() const {\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\npromote<fvar<RealType, Order>, fvar<RealType2, Order2>> fvar<RealType, Order>::operator+(\n    fvar<RealType2, Order2> const& cr) const {\n  promote<fvar<RealType, Order>, fvar<RealType2, Order2>> retval;\n  for (size_t i = 0; i <= (std::min)(Order, Order2); ++i)\n    retval.v[i] = v[i] + cr.v[i];\n  BOOST_IF_CONSTEXPR (Order < Order2)\n    for (size_t i = Order + 1; i <= Order2; ++i)\n      retval.v[i] = cr.v[i];\n  else BOOST_IF_CONSTEXPR (Order2 < Order)\n    for (size_t i = Order2 + 1; i <= Order; ++i)\n      retval.v[i] = v[i];\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::operator+(root_type const& ca) const {\n  fvar<RealType, Order> retval(*this);\n  retval.v.front() += ca;\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> operator+(typename fvar<RealType, Order>::root_type const& ca,\n                                fvar<RealType, Order> const& cr) {\n  return cr + ca;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\npromote<fvar<RealType, Order>, fvar<RealType2, Order2>> fvar<RealType, Order>::operator-(\n    fvar<RealType2, Order2> const& cr) const {\n  promote<fvar<RealType, Order>, fvar<RealType2, Order2>> retval;\n  for (size_t i = 0; i <= (std::min)(Order, Order2); ++i)\n    retval.v[i] = v[i] - cr.v[i];\n  BOOST_IF_CONSTEXPR (Order < Order2)\n    for (auto i = Order + 1; i <= Order2; ++i)\n      retval.v[i] = -cr.v[i];\n  else BOOST_IF_CONSTEXPR (Order2 < Order)\n    for (auto i = Order2 + 1; i <= Order; ++i)\n      retval.v[i] = v[i];\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::operator-(root_type const& ca) const {\n  fvar<RealType, Order> retval(*this);\n  retval.v.front() -= ca;\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> operator-(typename fvar<RealType, Order>::root_type const& ca,\n                                fvar<RealType, Order> const& cr) {\n  fvar<RealType, Order> mcr = -cr;  // Has same address as retval in operator-() due to NRVO.\n  mcr += ca;\n  return mcr;  // <-- This allows for NRVO. The following does not. --> return mcr += ca;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\npromote<fvar<RealType, Order>, fvar<RealType2, Order2>> fvar<RealType, Order>::operator*(\n    fvar<RealType2, Order2> const& cr) const {\n  using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n  promote<RealType, RealType2> const zero(0);\n  promote<fvar<RealType, Order>, fvar<RealType2, Order2>> retval;\n  BOOST_IF_CONSTEXPR (Order < Order2)\n    for (size_t i = 0, j = Order, k = Order2; i <= Order2; ++i, j && --j, --k)\n      retval.v[i] = std::inner_product(v.cbegin(), v.cend() - diff_t(j), cr.v.crbegin() + diff_t(k), zero);\n  else\n    for (size_t i = 0, j = Order2, k = Order; i <= Order; ++i, j && --j, --k)\n      retval.v[i] = std::inner_product(cr.v.cbegin(), cr.v.cend() - diff_t(j), v.crbegin() + diff_t(k), zero);\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::operator*(root_type const& ca) const {\n  fvar<RealType, Order> retval(*this);\n  retval *= ca;\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> operator*(typename fvar<RealType, Order>::root_type const& ca,\n                                fvar<RealType, Order> const& cr) {\n  return cr * ca;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\npromote<fvar<RealType, Order>, fvar<RealType2, Order2>> fvar<RealType, Order>::operator/(\n    fvar<RealType2, Order2> const& cr) const {\n  using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n  promote<RealType, RealType2> const zero(0);\n  promote<fvar<RealType, Order>, fvar<RealType2, Order2>> retval;\n  retval.v.front() = v.front() / cr.v.front();\n  BOOST_IF_CONSTEXPR (Order < Order2) {\n    for (size_t i = 1, j = Order2 - 1; i <= Order; ++i, --j)\n      retval.v[i] =\n          (v[i] - std::inner_product(\n                      cr.v.cbegin() + 1, cr.v.cend() - diff_t(j), retval.v.crbegin() + diff_t(j + 1), zero)) /\n          cr.v.front();\n    for (size_t i = Order + 1, j = Order2 - Order - 1; i <= Order2; ++i, --j)\n      retval.v[i] =\n          -std::inner_product(\n              cr.v.cbegin() + 1, cr.v.cend() - diff_t(j), retval.v.crbegin() + diff_t(j + 1), zero) /\n          cr.v.front();\n  } else BOOST_IF_CONSTEXPR (0 < Order2)\n    for (size_t i = 1, j = Order2 - 1, k = Order; i <= Order; ++i, j && --j, --k)\n      retval.v[i] =\n          (v[i] - std::inner_product(\n                      cr.v.cbegin() + 1, cr.v.cend() - diff_t(j), retval.v.crbegin() + diff_t(k), zero)) /\n          cr.v.front();\n  else\n    for (size_t i = 1; i <= Order; ++i)\n      retval.v[i] = v[i] / cr.v.front();\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::operator/(root_type const& ca) const {\n  fvar<RealType, Order> retval(*this);\n  retval /= ca;\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> operator/(typename fvar<RealType, Order>::root_type const& ca,\n                                fvar<RealType, Order> const& cr) {\n  using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n  fvar<RealType, Order> retval;\n  retval.v.front() = ca / cr.v.front();\n  BOOST_IF_CONSTEXPR (0 < Order) {\n    RealType const zero(0);\n    for (size_t i = 1, j = Order - 1; i <= Order; ++i, --j)\n      retval.v[i] =\n          -std::inner_product(\n              cr.v.cbegin() + 1, cr.v.cend() - diff_t(j), retval.v.crbegin() + diff_t(j + 1), zero) /\n          cr.v.front();\n  }\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nbool fvar<RealType, Order>::operator==(fvar<RealType2, Order2> const& cr) const {\n  return v.front() == cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\nbool fvar<RealType, Order>::operator==(root_type const& ca) const {\n  return v.front() == ca;\n}\n\ntemplate <typename RealType, size_t Order>\nbool operator==(typename fvar<RealType, Order>::root_type const& ca, fvar<RealType, Order> const& cr) {\n  return ca == cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nbool fvar<RealType, Order>::operator!=(fvar<RealType2, Order2> const& cr) const {\n  return v.front() != cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\nbool fvar<RealType, Order>::operator!=(root_type const& ca) const {\n  return v.front() != ca;\n}\n\ntemplate <typename RealType, size_t Order>\nbool operator!=(typename fvar<RealType, Order>::root_type const& ca, fvar<RealType, Order> const& cr) {\n  return ca != cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nbool fvar<RealType, Order>::operator<=(fvar<RealType2, Order2> const& cr) const {\n  return v.front() <= cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\nbool fvar<RealType, Order>::operator<=(root_type const& ca) const {\n  return v.front() <= ca;\n}\n\ntemplate <typename RealType, size_t Order>\nbool operator<=(typename fvar<RealType, Order>::root_type const& ca, fvar<RealType, Order> const& cr) {\n  return ca <= cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nbool fvar<RealType, Order>::operator>=(fvar<RealType2, Order2> const& cr) const {\n  return v.front() >= cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\nbool fvar<RealType, Order>::operator>=(root_type const& ca) const {\n  return v.front() >= ca;\n}\n\ntemplate <typename RealType, size_t Order>\nbool operator>=(typename fvar<RealType, Order>::root_type const& ca, fvar<RealType, Order> const& cr) {\n  return ca >= cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nbool fvar<RealType, Order>::operator<(fvar<RealType2, Order2> const& cr) const {\n  return v.front() < cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\nbool fvar<RealType, Order>::operator<(root_type const& ca) const {\n  return v.front() < ca;\n}\n\ntemplate <typename RealType, size_t Order>\nbool operator<(typename fvar<RealType, Order>::root_type const& ca, fvar<RealType, Order> const& cr) {\n  return ca < cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RealType2, size_t Order2>\nbool fvar<RealType, Order>::operator>(fvar<RealType2, Order2> const& cr) const {\n  return v.front() > cr.v.front();\n}\n\ntemplate <typename RealType, size_t Order>\nbool fvar<RealType, Order>::operator>(root_type const& ca) const {\n  return v.front() > ca;\n}\n\ntemplate <typename RealType, size_t Order>\nbool operator>(typename fvar<RealType, Order>::root_type const& ca, fvar<RealType, Order> const& cr) {\n  return ca > cr.v.front();\n}\n\n  /*** Other methods and functions ***/\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// f : order -> derivative(order)/factorial(order)\n// Use this when you have the polynomial coefficients, rather than just the derivatives. E.g. See atan2().\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_coefficients(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  size_t i = (std::min)(order, order_sum);\n  promote<fvar<RealType, Order>, Fvar, Fvars...> accumulator = cr.apply_coefficients(\n      order - i, [&f, i](auto... indices) { return f(i, indices...); }, std::forward<Fvars>(fvars)...);\n  while (i--)\n    (accumulator *= epsilon) += cr.apply_coefficients(\n        order - i, [&f, i](auto... indices) { return f(i, indices...); }, std::forward<Fvars>(fvars)...);\n  return accumulator;\n}\n#endif\n\n// f : order -> derivative(order)/factorial(order)\n// Use this when you have the polynomial coefficients, rather than just the derivatives. E.g. See atan().\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func>\nfvar<RealType, Order> fvar<RealType, Order>::apply_coefficients(size_t const order, Func const& f) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n  size_t i = (std::min)(order, order_sum);\n#else  // ODR-use of static constexpr\n  size_t i = order < order_sum ? order : order_sum;\n#endif\n  fvar<RealType, Order> accumulator = f(i);\n  while (i--)\n    (accumulator *= epsilon) += f(i);\n  return accumulator;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// f : order -> derivative(order)\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_coefficients_nonhorner(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  fvar<RealType, Order> epsilon_i = fvar<RealType, Order>(1);  // epsilon to the power of i\n  promote<fvar<RealType, Order>, Fvar, Fvars...> accumulator = cr.apply_coefficients_nonhorner(\n      order,\n      [&f](auto... indices) { return f(0, static_cast<std::size_t>(indices)...); },\n      std::forward<Fvars>(fvars)...);\n  size_t const i_max = (std::min)(order, order_sum);\n  for (size_t i = 1; i <= i_max; ++i) {\n    epsilon_i = epsilon_i.epsilon_multiply(i - 1, 0, epsilon, 1, 0);\n    accumulator += epsilon_i.epsilon_multiply(\n        i,\n        0,\n        cr.apply_coefficients_nonhorner(\n            order - i,\n            [&f, i](auto... indices) { return f(i, static_cast<std::size_t>(indices)...); },\n            std::forward<Fvars>(fvars)...),\n        0,\n        0);\n  }\n  return accumulator;\n}\n#endif\n\n// f : order -> coefficient(order)\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func>\nfvar<RealType, Order> fvar<RealType, Order>::apply_coefficients_nonhorner(size_t const order,\n                                                                          Func const& f) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  fvar<RealType, Order> epsilon_i = fvar<RealType, Order>(1);  // epsilon to the power of i\n  fvar<RealType, Order> accumulator = fvar<RealType, Order>(f(0u));\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n  size_t const i_max = (std::min)(order, order_sum);\n#else  // ODR-use of static constexpr\n  size_t const i_max = order < order_sum ? order : order_sum;\n#endif\n  for (size_t i = 1; i <= i_max; ++i) {\n    epsilon_i = epsilon_i.epsilon_multiply(i - 1, 0, epsilon, 1, 0);\n    accumulator += epsilon_i.epsilon_multiply(i, 0, f(i));\n  }\n  return accumulator;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// f : order -> derivative(order)\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_derivatives(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  size_t i = (std::min)(order, order_sum);\n  promote<fvar<RealType, Order>, Fvar, Fvars...> accumulator =\n      cr.apply_derivatives(\n          order - i, [&f, i](auto... indices) { return f(i, indices...); }, std::forward<Fvars>(fvars)...) /\n      factorial<root_type>(static_cast<unsigned>(i));\n  while (i--)\n    (accumulator *= epsilon) +=\n        cr.apply_derivatives(\n            order - i, [&f, i](auto... indices) { return f(i, indices...); }, std::forward<Fvars>(fvars)...) /\n        factorial<root_type>(static_cast<unsigned>(i));\n  return accumulator;\n}\n#endif\n\n// f : order -> derivative(order)\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func>\nfvar<RealType, Order> fvar<RealType, Order>::apply_derivatives(size_t const order, Func const& f) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n  size_t i = (std::min)(order, order_sum);\n#else  // ODR-use of static constexpr\n  size_t i = order < order_sum ? order : order_sum;\n#endif\n  fvar<RealType, Order> accumulator = f(i) / factorial<root_type>(static_cast<unsigned>(i));\n  while (i--)\n    (accumulator *= epsilon) += f(i) / factorial<root_type>(static_cast<unsigned>(i));\n  return accumulator;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// f : order -> derivative(order)\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_derivatives_nonhorner(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  fvar<RealType, Order> epsilon_i = fvar<RealType, Order>(1);  // epsilon to the power of i\n  promote<fvar<RealType, Order>, Fvar, Fvars...> accumulator = cr.apply_derivatives_nonhorner(\n      order,\n      [&f](auto... indices) { return f(0, static_cast<std::size_t>(indices)...); },\n      std::forward<Fvars>(fvars)...);\n  size_t const i_max = (std::min)(order, order_sum);\n  for (size_t i = 1; i <= i_max; ++i) {\n    epsilon_i = epsilon_i.epsilon_multiply(i - 1, 0, epsilon, 1, 0);\n    accumulator += epsilon_i.epsilon_multiply(\n        i,\n        0,\n        cr.apply_derivatives_nonhorner(\n            order - i,\n            [&f, i](auto... indices) { return f(i, static_cast<std::size_t>(indices)...); },\n            std::forward<Fvars>(fvars)...) /\n            factorial<root_type>(static_cast<unsigned>(i)),\n        0,\n        0);\n  }\n  return accumulator;\n}\n#endif\n\n// f : order -> derivative(order)\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func>\nfvar<RealType, Order> fvar<RealType, Order>::apply_derivatives_nonhorner(size_t const order,\n                                                                         Func const& f) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  fvar<RealType, Order> epsilon_i = fvar<RealType, Order>(1);  // epsilon to the power of i\n  fvar<RealType, Order> accumulator = fvar<RealType, Order>(f(0u));\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n  size_t const i_max = (std::min)(order, order_sum);\n#else  // ODR-use of static constexpr\n  size_t const i_max = order < order_sum ? order : order_sum;\n#endif\n  for (size_t i = 1; i <= i_max; ++i) {\n    epsilon_i = epsilon_i.epsilon_multiply(i - 1, 0, epsilon, 1, 0);\n    accumulator += epsilon_i.epsilon_multiply(i, 0, f(i) / factorial<root_type>(static_cast<unsigned>(i)));\n  }\n  return accumulator;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// Can throw \"std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)\"\ntemplate <typename RealType, size_t Order>\ntemplate <typename... Orders>\nget_type_at<RealType, sizeof...(Orders)> fvar<RealType, Order>::at(size_t order, Orders... orders) const {\n  if constexpr (0 < sizeof...(Orders))\n    return v.at(order).at(static_cast<std::size_t>(orders)...);\n  else\n    return v.at(order);\n}\n#endif\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// Can throw \"std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)\"\ntemplate <typename RealType, size_t Order>\ntemplate <typename... Orders>\nget_type_at<fvar<RealType, Order>, sizeof...(Orders)> fvar<RealType, Order>::derivative(\n    Orders... orders) const {\n  static_assert(sizeof...(Orders) <= depth,\n                \"Number of parameters to derivative(...) cannot exceed fvar::depth.\");\n  return at(static_cast<std::size_t>(orders)...) *\n         (... * factorial<root_type>(static_cast<unsigned>(orders)));\n}\n#endif\n\ntemplate <typename RealType, size_t Order>\nconst RealType& fvar<RealType, Order>::operator[](size_t i) const {\n  return v[i];\n}\n\ntemplate <typename RealType, size_t Order>\nRealType fvar<RealType, Order>::epsilon_inner_product(size_t z0,\n                                                      size_t const isum0,\n                                                      size_t const m0,\n                                                      fvar<RealType, Order> const& cr,\n                                                      size_t z1,\n                                                      size_t const isum1,\n                                                      size_t const m1,\n                                                      size_t const j) const {\n  static_assert(is_fvar<RealType>::value, \"epsilon_inner_product() must have 1 < depth.\");\n  RealType accumulator = RealType();\n  auto const i0_max = m1 < j ? j - m1 : 0;\n  for (auto i0 = m0, i1 = j - m0; i0 <= i0_max; ++i0, --i1)\n    accumulator += v[i0].epsilon_multiply(z0, isum0 + i0, cr.v[i1], z1, isum1 + i1);\n  return accumulator;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply(size_t z0,\n                                                              size_t isum0,\n                                                              fvar<RealType, Order> const& cr,\n                                                              size_t z1,\n                                                              size_t isum1) const {\n  using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n  RealType const zero(0);\n  size_t const m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n  size_t const m1 = order_sum + isum1 < Order + z1 ? Order + z1 - (order_sum + isum1) : 0;\n  size_t const i_max = m0 + m1 < Order ? Order - (m0 + m1) : 0;\n  fvar<RealType, Order> retval = fvar<RealType, Order>();\n  if constexpr (is_fvar<RealType>::value)\n    for (size_t i = 0, j = Order; i <= i_max; ++i, --j)\n      retval.v[j] = epsilon_inner_product(z0, isum0, m0, cr, z1, isum1, m1, j);\n  else\n    for (size_t i = 0, j = Order; i <= i_max; ++i, --j)\n      retval.v[j] = std::inner_product(\n          v.cbegin() + diff_t(m0), v.cend() - diff_t(i + m1), cr.v.crbegin() + diff_t(i + m0), zero);\n  return retval;\n}\n#endif\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// When called from outside this method, z0 should be non-zero. Otherwise if z0=0 then it will give an\n// incorrect result of 0 when the root value is 0 and ca=inf, when instead the correct product is nan.\n// If z0=0 then use the regular multiply operator*() instead.\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply(size_t z0,\n                                                              size_t isum0,\n                                                              root_type const& ca) const {\n  fvar<RealType, Order> retval(*this);\n  size_t const m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n  if constexpr (is_fvar<RealType>::value)\n    for (size_t i = m0; i <= Order; ++i)\n      retval.v[i] = retval.v[i].epsilon_multiply(z0, isum0 + i, ca);\n  else\n    for (size_t i = m0; i <= Order; ++i)\n      if (retval.v[i] != static_cast<RealType>(0))\n        retval.v[i] *= ca;\n  return retval;\n}\n#endif\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::inverse() const {\n  return static_cast<root_type>(*this) == 0 ? inverse_apply() : 1 / *this;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::negate() {\n  if constexpr (is_fvar<RealType>::value)\n    std::for_each(v.begin(), v.end(), [](RealType& r) { r.negate(); });\n  else\n    std::for_each(v.begin(), v.end(), [](RealType& a) { a = -a; });\n  return *this;\n}\n#endif\n\n// This gives log(0.0) = depth(1)(-inf,inf,-inf,inf,-inf,inf)\n// 1 / *this: log(0.0) = depth(1)(-inf,inf,-inf,-nan,-nan,-nan)\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::inverse_apply() const {\n  root_type derivatives[order_sum + 1];  // LCOV_EXCL_LINE This causes a false negative on lcov coverage test.\n  root_type const x0 = static_cast<root_type>(*this);\n  *derivatives = 1 / x0;\n  for (size_t i = 1; i <= order_sum; ++i)\n    derivatives[i] = -derivatives[i - 1] * i / x0;\n  return apply_derivatives_nonhorner(order_sum, [&derivatives](size_t j) { return derivatives[j]; });\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::multiply_assign_by_root_type(bool is_root,\n                                                                           root_type const& ca) {\n  auto itr = v.begin();\n  if constexpr (is_fvar<RealType>::value) {\n    itr->multiply_assign_by_root_type(is_root, ca);\n    for (++itr; itr != v.end(); ++itr)\n      itr->multiply_assign_by_root_type(false, ca);\n  } else {\n    if (is_root || *itr != 0)\n      *itr *= ca;  // Skip multiplication of 0 by ca=inf to avoid nan, except when is_root.\n    for (++itr; itr != v.end(); ++itr)\n      if (*itr != 0)\n        *itr *= ca;\n  }\n  return *this;\n}\n#endif\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>::operator root_type() const {\n  return static_cast<root_type>(v.front());\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename T, typename>\nfvar<RealType, Order>::operator T() const {\n  return static_cast<T>(static_cast<root_type>(v.front()));\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::set_root(root_type const& root) {\n  if constexpr (is_fvar<RealType>::value)\n    v.front().set_root(root);\n  else\n    v.front() = root;\n  return *this;\n}\n#endif\n\n// Standard Library Support Requirements\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fabs(fvar<RealType, Order> const& cr) {\n  typename fvar<RealType, Order>::root_type const zero(0);\n  return cr < zero ? -cr\n                   : cr == zero ? fvar<RealType, Order>()  // Canonical fabs'(0) = 0.\n                                : cr;                      // Propagate NaN.\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> abs(fvar<RealType, Order> const& cr) {\n  return fabs(cr);\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> ceil(fvar<RealType, Order> const& cr) {\n  using std::ceil;\n  return fvar<RealType, Order>(ceil(static_cast<typename fvar<RealType, Order>::root_type>(cr)));\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> floor(fvar<RealType, Order> const& cr) {\n  using std::floor;\n  return fvar<RealType, Order>(floor(static_cast<typename fvar<RealType, Order>::root_type>(cr)));\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> exp(fvar<RealType, Order> const& cr) {\n  using std::exp;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  root_type const d0 = exp(static_cast<root_type>(cr));\n  return cr.apply_derivatives(order, [&d0](size_t) { return d0; });\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> pow(fvar<RealType, Order> const& x,\n                          typename fvar<RealType, Order>::root_type const& y) {\n  BOOST_MATH_STD_USING\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const x0 = static_cast<root_type>(x);\n  root_type derivatives[order + 1]{pow(x0, y)};\n  if (fabs(x0) < std::numeric_limits<root_type>::epsilon()) {\n    root_type coef = 1;\n    for (size_t i = 0; i < order && y - i != 0; ++i) {\n      coef *= y - i;\n      derivatives[i + 1] = coef * pow(x0, y - (i + 1));\n    }\n    return x.apply_derivatives_nonhorner(order, [&derivatives](size_t i) { return derivatives[i]; });\n  } else {\n    for (size_t i = 0; i < order && y - i != 0; ++i)\n      derivatives[i + 1] = (y - i) * derivatives[i] / x0;\n    return x.apply_derivatives(order, [&derivatives](size_t i) { return derivatives[i]; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> pow(typename fvar<RealType, Order>::root_type const& x,\n                          fvar<RealType, Order> const& y) {\n  BOOST_MATH_STD_USING\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const y0 = static_cast<root_type>(y);\n  root_type derivatives[order + 1];\n  *derivatives = pow(x, y0);\n  root_type const logx = log(x);\n  for (size_t i = 0; i < order; ++i)\n    derivatives[i + 1] = derivatives[i] * logx;\n  return y.apply_derivatives(order, [&derivatives](size_t i) { return derivatives[i]; });\n}\n\ntemplate <typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1, Order1>, fvar<RealType2, Order2>> pow(fvar<RealType1, Order1> const& x,\n                                                              fvar<RealType2, Order2> const& y) {\n  BOOST_MATH_STD_USING\n  using return_type = promote<fvar<RealType1, Order1>, fvar<RealType2, Order2>>;\n  using root_type = typename return_type::root_type;\n  constexpr size_t order = return_type::order_sum;\n  root_type const x0 = static_cast<root_type>(x);\n  root_type const y0 = static_cast<root_type>(y);\n  root_type dxydx[order + 1]{pow(x0, y0)};\n  BOOST_IF_CONSTEXPR (order == 0)\n    return return_type(*dxydx);\n  else {\n    for (size_t i = 0; i < order && y0 - i != 0; ++i)\n      dxydx[i + 1] = (y0 - i) * dxydx[i] / x0;\n    std::array<fvar<root_type, order>, order + 1> lognx;\n    lognx.front() = fvar<root_type, order>(1);\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n    lognx[1] = log(make_fvar<root_type, order>(x0));\n#else  // for compilers that compile this branch when order == 0.\n    lognx[(std::min)(size_t(1), order)] = log(make_fvar<root_type, order>(x0));\n#endif\n    for (size_t i = 1; i < order; ++i)\n      lognx[i + 1] = lognx[i] * lognx[1];\n    auto const f = [&dxydx, &lognx](size_t i, size_t j) {\n      size_t binomial = 1;\n      root_type sum = dxydx[i] * static_cast<root_type>(lognx[j]);\n      for (size_t k = 1; k <= i; ++k) {\n        (binomial *= (i - k + 1)) /= k;  // binomial_coefficient(i,k)\n        sum += binomial * dxydx[i - k] * lognx[j].derivative(k);\n      }\n      return sum;\n    };\n    if (fabs(x0) < std::numeric_limits<root_type>::epsilon())\n      return x.apply_derivatives_nonhorner(order, f, y);\n    return x.apply_derivatives(order, f, y);\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sqrt(fvar<RealType, Order> const& cr) {\n  using std::sqrt;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type derivatives[order + 1];\n  root_type const x = static_cast<root_type>(cr);\n  *derivatives = sqrt(x);\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(*derivatives);\n  else {\n    root_type numerator = 0.5;\n    root_type powers = 1;\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n    derivatives[1] = numerator / *derivatives;\n#else  // for compilers that compile this branch when order == 0.\n    derivatives[(std::min)(size_t(1), order)] = numerator / *derivatives;\n#endif\n    using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n    for (size_t i = 2; i <= order; ++i) {\n      numerator *= static_cast<root_type>(-0.5) * ((static_cast<diff_t>(i) << 1) - 3);\n      powers *= x;\n      derivatives[i] = numerator / (powers * *derivatives);\n    }\n    auto const f = [&derivatives](size_t i) { return derivatives[i]; };\n    if (cr < std::numeric_limits<root_type>::epsilon())\n      return cr.apply_derivatives_nonhorner(order, f);\n    return cr.apply_derivatives(order, f);\n  }\n}\n\n// Natural logarithm. If cr==0 then derivative(i) may have nans due to nans from inverse().\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> log(fvar<RealType, Order> const& cr) {\n  using std::log;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = log(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto const d1 = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr)).inverse();  // log'(x) = 1 / x\n    return cr.apply_coefficients_nonhorner(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> frexp(fvar<RealType, Order> const& cr, int* exp) {\n  using std::exp2;\n  using std::frexp;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  frexp(static_cast<root_type>(cr), exp);\n  return cr * static_cast<root_type>(exp2(-*exp));\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> ldexp(fvar<RealType, Order> const& cr, int exp) {\n  // argument to std::exp2 must be casted to root_type, otherwise std::exp2 returns double (always)\n  using std::exp2;\n  return cr * exp2(static_cast<typename fvar<RealType, Order>::root_type>(exp));\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> cos(fvar<RealType, Order> const& cr) {\n  BOOST_MATH_STD_USING\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = cos(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    root_type const d1 = -sin(static_cast<root_type>(cr));\n    root_type const derivatives[4]{d0, d1, -d0, -d1};\n    return cr.apply_derivatives(order, [&derivatives](size_t i) { return derivatives[i & 3]; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sin(fvar<RealType, Order> const& cr) {\n  BOOST_MATH_STD_USING\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = sin(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    root_type const d1 = cos(static_cast<root_type>(cr));\n    root_type const derivatives[4]{d0, d1, -d0, -d1};\n    return cr.apply_derivatives(order, [&derivatives](size_t i) { return derivatives[i & 3]; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> asin(fvar<RealType, Order> const& cr) {\n  using std::asin;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = asin(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = sqrt((x *= x).negate() += 1).inverse();  // asin'(x) = 1 / sqrt(1-x*x).\n    return cr.apply_coefficients_nonhorner(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> tan(fvar<RealType, Order> const& cr) {\n  using std::tan;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = tan(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto c = cos(make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr)));\n    auto const d1 = (c *= c).inverse();  // tan'(x) = 1 / cos(x)^2\n    return cr.apply_coefficients_nonhorner(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atan(fvar<RealType, Order> const& cr) {\n  using std::atan;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = atan(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = ((x *= x) += 1).inverse();  // atan'(x) = 1 / (x*x+1).\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atan2(fvar<RealType, Order> const& cr,\n                            typename fvar<RealType, Order>::root_type const& ca) {\n  using std::atan2;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = atan2(static_cast<root_type>(cr), ca);\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto y = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = ca / ((y *= y) += (ca * ca));  // (d/dy)atan2(y,x) = x / (y*y+x*x)\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atan2(typename fvar<RealType, Order>::root_type const& ca,\n                            fvar<RealType, Order> const& cr) {\n  using std::atan2;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = atan2(ca, static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = -ca / ((x *= x) += (ca * ca));  // (d/dx)atan2(y,x) = -y / (x*x+y*y)\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1, Order1>, fvar<RealType2, Order2>> atan2(fvar<RealType1, Order1> const& cr1,\n                                                                fvar<RealType2, Order2> const& cr2) {\n  using std::atan2;\n  using return_type = promote<fvar<RealType1, Order1>, fvar<RealType2, Order2>>;\n  using root_type = typename return_type::root_type;\n  constexpr size_t order = return_type::order_sum;\n  root_type const y = static_cast<root_type>(cr1);\n  root_type const x = static_cast<root_type>(cr2);\n  root_type const d00 = atan2(y, x);\n  BOOST_IF_CONSTEXPR (order == 0)\n    return return_type(d00);\n  else {\n    constexpr size_t order1 = fvar<RealType1, Order1>::order_sum;\n    constexpr size_t order2 = fvar<RealType2, Order2>::order_sum;\n    auto x01 = make_fvar<typename fvar<RealType2, Order2>::root_type, order2 - 1>(x);\n    auto const d01 = -y / ((x01 *= x01) += (y * y));\n    auto y10 = make_fvar<typename fvar<RealType1, Order1>::root_type, order1 - 1>(y);\n    auto x10 = make_fvar<typename fvar<RealType2, Order2>::root_type, 0, order2>(x);\n    auto const d10 = x10 / ((x10 * x10) + (y10 *= y10));\n    auto const f = [&d00, &d01, &d10](size_t i, size_t j) {\n      return i ? d10[i - 1][j] / i : j ? d01[j - 1] / j : d00;\n    };\n    return cr1.apply_coefficients(order, f, cr2);\n  }\n}\n\ntemplate <typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1, Order1>, fvar<RealType2, Order2>> fmod(fvar<RealType1, Order1> const& cr1,\n                                                               fvar<RealType2, Order2> const& cr2) {\n  using boost::math::trunc;\n  auto const numer = static_cast<typename fvar<RealType1, Order1>::root_type>(cr1);\n  auto const denom = static_cast<typename fvar<RealType2, Order2>::root_type>(cr2);\n  return cr1 - cr2 * trunc(numer / denom);\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> round(fvar<RealType, Order> const& cr) {\n  using boost::math::round;\n  return fvar<RealType, Order>(round(static_cast<typename fvar<RealType, Order>::root_type>(cr)));\n}\n\ntemplate <typename RealType, size_t Order>\nint iround(fvar<RealType, Order> const& cr) {\n  using boost::math::iround;\n  return iround(static_cast<typename fvar<RealType, Order>::root_type>(cr));\n}\n\ntemplate <typename RealType, size_t Order>\nlong lround(fvar<RealType, Order> const& cr) {\n  using boost::math::lround;\n  return lround(static_cast<typename fvar<RealType, Order>::root_type>(cr));\n}\n\ntemplate <typename RealType, size_t Order>\nlong long llround(fvar<RealType, Order> const& cr) {\n  using boost::math::llround;\n  return llround(static_cast<typename fvar<RealType, Order>::root_type>(cr));\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> trunc(fvar<RealType, Order> const& cr) {\n  using boost::math::trunc;\n  return fvar<RealType, Order>(trunc(static_cast<typename fvar<RealType, Order>::root_type>(cr)));\n}\n\ntemplate <typename RealType, size_t Order>\nlong double truncl(fvar<RealType, Order> const& cr) {\n  using std::truncl;\n  return truncl(static_cast<typename fvar<RealType, Order>::root_type>(cr));\n}\n\ntemplate <typename RealType, size_t Order>\nint itrunc(fvar<RealType, Order> const& cr) {\n  using boost::math::itrunc;\n  return itrunc(static_cast<typename fvar<RealType, Order>::root_type>(cr));\n}\n\ntemplate <typename RealType, size_t Order>\nlong long lltrunc(fvar<RealType, Order> const& cr) {\n  using boost::math::lltrunc;\n  return lltrunc(static_cast<typename fvar<RealType, Order>::root_type>(cr));\n}\n\ntemplate <typename RealType, size_t Order>\nstd::ostream& operator<<(std::ostream& out, fvar<RealType, Order> const& cr) {\n  out << \"depth(\" << cr.depth << \")(\" << cr.v.front();\n  for (size_t i = 1; i <= Order; ++i)\n    out << ',' << cr.v[i];\n  return out << ')';\n}\n\n// Additional functions\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> acos(fvar<RealType, Order> const& cr) {\n  using std::acos;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = acos(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = sqrt((x *= x).negate() += 1).inverse().negate();  // acos'(x) = -1 / sqrt(1-x*x).\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> acosh(fvar<RealType, Order> const& cr) {\n  using boost::math::acosh;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = acosh(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = sqrt((x *= x) -= 1).inverse();  // acosh'(x) = 1 / sqrt(x*x-1).\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> asinh(fvar<RealType, Order> const& cr) {\n  using boost::math::asinh;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = asinh(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = sqrt((x *= x) += 1).inverse();  // asinh'(x) = 1 / sqrt(x*x+1).\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> atanh(fvar<RealType, Order> const& cr) {\n  using boost::math::atanh;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = atanh(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));\n    auto const d1 = ((x *= x).negate() += 1).inverse();  // atanh'(x) = 1 / (1-x*x)\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> cosh(fvar<RealType, Order> const& cr) {\n  BOOST_MATH_STD_USING\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = cosh(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    root_type const derivatives[2]{d0, sinh(static_cast<root_type>(cr))};\n    return cr.apply_derivatives(order, [&derivatives](size_t i) { return derivatives[i & 1]; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> digamma(fvar<RealType, Order> const& cr) {\n  using boost::math::digamma;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const x = static_cast<root_type>(cr);\n  root_type const d0 = digamma(x);\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    static_assert(order <= static_cast<size_t>((std::numeric_limits<int>::max)()),\n                  \"order exceeds maximum derivative for boost::math::polygamma().\");\n    return cr.apply_derivatives(\n        order, [&x, &d0](size_t i) { return i ? boost::math::polygamma(static_cast<int>(i), x) : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> erf(fvar<RealType, Order> const& cr) {\n  using boost::math::erf;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = erf(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));  // d1 = 2/sqrt(pi)*exp(-x*x)\n    auto const d1 = 2 * constants::one_div_root_pi<root_type>() * exp((x *= x).negate());\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> erfc(fvar<RealType, Order> const& cr) {\n  using boost::math::erfc;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = erfc(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    auto x = make_fvar<root_type, bool(order) ? order - 1 : 0>(static_cast<root_type>(cr));  // erfc'(x) = -erf'(x)\n    auto const d1 = -2 * constants::one_div_root_pi<root_type>() * exp((x *= x).negate());\n    return cr.apply_coefficients(order, [&d0, &d1](size_t i) { return i ? d1[i - 1] / i : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> lambert_w0(fvar<RealType, Order> const& cr) {\n  using std::exp;\n  using boost::math::lambert_w0;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type derivatives[order + 1];\n  *derivatives = lambert_w0(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(*derivatives);\n  else {\n    root_type const expw = exp(*derivatives);\n    derivatives[1] = 1 / (static_cast<root_type>(cr) + expw);\n    BOOST_IF_CONSTEXPR (order == 1)\n      return cr.apply_derivatives_nonhorner(order, [&derivatives](size_t i) { return derivatives[i]; });\n    else {\n      using diff_t = typename std::array<RealType, Order + 1>::difference_type;\n      root_type d1powers = derivatives[1] * derivatives[1];\n      root_type const x = derivatives[1] * expw;\n      derivatives[2] = d1powers * (-1 - x);\n      std::array<root_type, order> coef{{-1, -1}};  // as in derivatives[2].\n      for (size_t n = 3; n <= order; ++n) {\n        coef[n - 1] = coef[n - 2] * -static_cast<root_type>(2 * n - 3);\n        for (size_t j = n - 2; j != 0; --j)\n          (coef[j] *= -static_cast<root_type>(n - 1)) -= (n + j - 2) * coef[j - 1];\n        coef[0] *= -static_cast<root_type>(n - 1);\n        d1powers *= derivatives[1];\n        derivatives[n] =\n            d1powers * std::accumulate(coef.crend() - diff_t(n - 1),\n                                       coef.crend(),\n                                       coef[n - 1],\n                                       [&x](root_type const& a, root_type const& b) { return a * x + b; });\n      }\n      return cr.apply_derivatives_nonhorner(order, [&derivatives](size_t i) { return derivatives[i]; });\n    }\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> lgamma(fvar<RealType, Order> const& cr) {\n  using std::lgamma;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const x = static_cast<root_type>(cr);\n  root_type const d0 = lgamma(x);\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    static_assert(order <= static_cast<size_t>((std::numeric_limits<int>::max)()) + 1,\n                  \"order exceeds maximum derivative for boost::math::polygamma().\");\n    return cr.apply_derivatives(\n        order, [&x, &d0](size_t i) { return i ? boost::math::polygamma(static_cast<int>(i - 1), x) : d0; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sinc(fvar<RealType, Order> const& cr) {\n  if (cr != 0)\n    return sin(cr) / cr;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type taylor[order + 1]{1};  // sinc(0) = 1\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(*taylor);\n  else {\n    for (size_t n = 2; n <= order; n += 2)\n      taylor[n] = (1 - static_cast<int>(n & 2)) / factorial<root_type>(static_cast<unsigned>(n + 1));\n    return cr.apply_coefficients_nonhorner(order, [&taylor](size_t i) { return taylor[i]; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> sinh(fvar<RealType, Order> const& cr) {\n  BOOST_MATH_STD_USING\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  root_type const d0 = sinh(static_cast<root_type>(cr));\n  BOOST_IF_CONSTEXPR (fvar<RealType, Order>::order_sum == 0)\n    return fvar<RealType, Order>(d0);\n  else {\n    root_type const derivatives[2]{d0, cosh(static_cast<root_type>(cr))};\n    return cr.apply_derivatives(order, [&derivatives](size_t i) { return derivatives[i & 1]; });\n  }\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> tanh(fvar<RealType, Order> const& cr) {\n  fvar<RealType, Order> retval = exp(cr * 2);\n  fvar<RealType, Order> const denom = retval + 1;\n  (retval -= 1) /= denom;\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> tgamma(fvar<RealType, Order> const& cr) {\n  using std::tgamma;\n  using root_type = typename fvar<RealType, Order>::root_type;\n  constexpr size_t order = fvar<RealType, Order>::order_sum;\n  BOOST_IF_CONSTEXPR (order == 0)\n    return fvar<RealType, Order>(tgamma(static_cast<root_type>(cr)));\n  else {\n    if (cr < 0)\n      return constants::pi<root_type>() / (sin(constants::pi<root_type>() * cr) * tgamma(1 - cr));\n    return exp(lgamma(cr)).set_root(tgamma(static_cast<root_type>(cr)));\n  }\n}\n\n}  // namespace detail\n}  // namespace autodiff_v1\n}  // namespace differentiation\n}  // namespace math\n}  // namespace boost\n\nnamespace std {\n\n// boost::math::tools::digits<RealType>() is handled by this std::numeric_limits<> specialization,\n// and similarly for max_value, min_value, log_max_value, log_min_value, and epsilon.\ntemplate <typename RealType, size_t Order>\nclass numeric_limits<boost::math::differentiation::detail::fvar<RealType, Order>>\n    : public numeric_limits<typename boost::math::differentiation::detail::fvar<RealType, Order>::root_type> {\n};\n\n}  // namespace std\n\nnamespace boost {\nnamespace math {\nnamespace tools {\nnamespace detail {\n\ntemplate <typename RealType, std::size_t Order>\nusing autodiff_fvar_type = differentiation::detail::fvar<RealType, Order>;\n\ntemplate <typename RealType, std::size_t Order>\nusing autodiff_root_type = typename autodiff_fvar_type<RealType, Order>::root_type;\n}  // namespace detail\n\n// See boost/math/tools/promotion.hpp\ntemplate <typename RealType0, size_t Order0, typename RealType1, size_t Order1>\nstruct promote_args_2<detail::autodiff_fvar_type<RealType0, Order0>,\n                      detail::autodiff_fvar_type<RealType1, Order1>> {\n  using type = detail::autodiff_fvar_type<typename promote_args_2<RealType0, RealType1>::type,\n#ifndef BOOST_NO_CXX14_CONSTEXPR\n                                          (std::max)(Order0, Order1)>;\n#else\n        Order0<Order1 ? Order1 : Order0>;\n#endif\n};\n\ntemplate <typename RealType, size_t Order>\nstruct promote_args<detail::autodiff_fvar_type<RealType, Order>> {\n  using type = detail::autodiff_fvar_type<typename promote_args<RealType>::type, Order>;\n};\n\ntemplate <typename RealType0, size_t Order0, typename RealType1>\nstruct promote_args_2<detail::autodiff_fvar_type<RealType0, Order0>, RealType1> {\n  using type = detail::autodiff_fvar_type<typename promote_args_2<RealType0, RealType1>::type, Order0>;\n};\n\ntemplate <typename RealType0, typename RealType1, size_t Order1>\nstruct promote_args_2<RealType0, detail::autodiff_fvar_type<RealType1, Order1>> {\n  using type = detail::autodiff_fvar_type<typename promote_args_2<RealType0, RealType1>::type, Order1>;\n};\n\ntemplate <typename destination_t, typename RealType, std::size_t Order>\ninline BOOST_MATH_CONSTEXPR destination_t real_cast(detail::autodiff_fvar_type<RealType, Order> const& from_v)\n    BOOST_NOEXCEPT_IF(BOOST_MATH_IS_FLOAT(destination_t) && BOOST_MATH_IS_FLOAT(RealType)) {\n  return real_cast<destination_t>(static_cast<detail::autodiff_root_type<RealType, Order>>(from_v));\n}\n\n}  // namespace tools\n\nnamespace policies {\n\ntemplate <class Policy, std::size_t Order>\nusing fvar_t = differentiation::detail::fvar<Policy, Order>;\ntemplate <class Policy, std::size_t Order>\nstruct evaluation<fvar_t<float, Order>, Policy> {\n  using type = fvar_t<typename conditional<Policy::promote_float_type::value, double, float>::type, Order>;\n};\n\ntemplate <class Policy, std::size_t Order>\nstruct evaluation<fvar_t<double, Order>, Policy> {\n  using type =\n      fvar_t<typename conditional<Policy::promote_double_type::value, long double, double>::type, Order>;\n};\n\n}  // namespace policies\n}  // namespace math\n}  // namespace boost\n\n#ifdef BOOST_NO_CXX17_IF_CONSTEXPR\n#include \"autodiff_cpp11.hpp\"\n#endif\n\n#endif  // BOOST_MATH_DIFFERENTIATION_AUTODIFF_HPP\n", "meta": {"hexsha": "a36959309965760864e7563a0e645677d4da804c", "size": 82576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/differentiation/autodiff.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/differentiation/autodiff.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/differentiation/autodiff.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": 40.046556741, "max_line_length": 128, "alphanum_fraction": 0.6652538268, "num_tokens": 23176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.06097517617237109, "lm_q1q2_score": 0.028110579336987587}}
{"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_EXAMPLES_LINEARELLIPTIC_OS2015_SISC_6_2_HH\n#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2015_SISC_6_2_HH\n\n#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#if HAVE_DUNE_FEM\n# include <dune/fem/misc/mpimanager.hh>\n#endif\n\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/logging.hh>\n#include <dune/stuff/common/memory.hh>\n#include <dune/stuff/common/ranges.hh>\n#include <dune/stuff/functions/expression.hh>\n\n#include <dune/pymor/parameters/base.hh>\n\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/operators/projections.hh>\n#include <dune/gdt/operators/prolongations.hh>\n#include <dune/gdt/playground/products/elliptic-swipdg.hh>\n#include <dune/gdt/playground/spaces/finitevolume/default.hh>\n\n#include <dune/hdd/linearelliptic/testcases/OS2015.hh>\n#include <dune/hdd/linearelliptic/discretizations/block-swipdg.hh>\n#include <dune/hdd/linearelliptic/estimators/block-swipdg.hh>\n\nnamespace internal {\n\n\nclass Initializer\n{\npublic:\n  Initializer(const DUNE_STUFF_SSIZE_T info_log_levels,\n              const DUNE_STUFF_SSIZE_T debug_log_levels,\n              const bool enable_warnings,\n              const bool enable_colors,\n              const std::string info_color,\n              const std::string debug_color,\n              const std::string warn_color)\n  {\n    try {\n      int argc = 0;\n      char** argv = new char* [0];\n      Dune::Fem::MPIManager::initialize(argc, argv);\n    } catch (...) {}\n    DSC::TimedLogger().create(info_log_levels,\n                              debug_log_levels,\n                              enable_warnings,\n                              enable_colors,\n                              info_color,\n                              debug_color,\n                              warn_color);\n    DSC::TimedLogger().get(\"OS2015.initializer\").info() << \"creating grid and problem... \" << std::endl;\n  }\n}; // class Initializer\n\n\ntemplate< class TestCaseType >\nclass Example\n  : Initializer\n{\npublic:\n  typedef typename TestCaseType::GridType GridType;\n  typedef double RangeFieldType;\n  typedef Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG< GridType, RangeFieldType, 1 > DiscretizationType;\n  typedef typename DiscretizationType::VectorType VectorType;\n  typedef typename TestCaseType::ParametersMapType ParametersMapType;\n\nprivate:\n  typedef Dune::HDD::LinearElliptic::Estimators::BlockSWIPDG< typename DiscretizationType::AnsatzSpaceType,\n                                                              VectorType,\n                                                              typename DiscretizationType::ProblemType,\n                                                              GridType > Estimator;\n\npublic:\n  Example(const ParametersMapType& parameter_range,\n          const std::string partitioning = \"[1 1 1]\",\n          const DUNE_STUFF_SSIZE_T num_refinements = 0,\n          const DUNE_STUFF_SSIZE_T oversampling_layers = 0,\n          const std::vector< std::string > products = {},\n          const bool with_reference = true,\n          const DUNE_STUFF_SSIZE_T info_log_levels  = 0,\n          const DUNE_STUFF_SSIZE_T debug_log_levels = -1,\n          const bool enable_warnings = true,\n          const bool enable_colors   = true,\n          const std::string info_color  = DSC::TimedLogging::default_info_color(),\n          const std::string debug_color = DSC::TimedLogging::default_debug_color(),\n          const std::string warn_color  = DSC::TimedLogging::default_warning_color())\n    : Initializer(info_log_levels,\n                  debug_log_levels,\n                  enable_warnings,\n                  enable_colors,\n                  info_color,\n                  debug_color,\n                  warn_color)\n    , with_reference_(with_reference),\n      parameter_range_(parameter_range)\n    , test_case_(merge_parameters({{\"mu\",     Dune::Pymor::Parameter(\"mu\", 1)},  // <- it does not matter which parameters we give to the\n                                   {\"mu_hat\", Dune::Pymor::Parameter(\"mu\", 1)},  //    test case here, since we use test_case_.problem()\n                                   {\"mu_bar\", Dune::Pymor::Parameter(\"mu\", 1)}}, //    (which is the parametric problem) anyway\n                                  parameter_range_),\n                 partitioning,\n                 boost::numeric_cast< size_t >(num_refinements),\n                 boost::numeric_cast< size_t >(oversampling_layers))\n    , reference_test_case_(with_reference_\n                           ? new TestCaseType(merge_parameters({{\"mu\",     Dune::Pymor::Parameter(\"mu\", 1)},\n                                                                {\"mu_hat\", Dune::Pymor::Parameter(\"mu\", 1)},\n                                                                {\"mu_bar\", Dune::Pymor::Parameter(\"mu\", 1)}},\n                                                               parameter_range_),\n                                              partitioning,\n                                              boost::numeric_cast< size_t >(num_refinements + 1))\n                           : nullptr)\n    , discretization_(*test_case_.reference_provider(),\n                      test_case_.boundary_info(),\n                      test_case_.problem(),\n                      products)\n    , reference_discretization_(with_reference_\n                                ? new DiscretizationType(*reference_test_case_->reference_provider(),\n                                                         reference_test_case_->boundary_info(),\n                                                         reference_test_case_->problem(),\n                                                         products)\n                                : nullptr)\n  {\n    auto logger = DSC::TimedLogger().get(\"OS2015.example\");\n    logger.info() << \"initializing discretization... \" << std::flush;\n    discretization_.init();\n    if (with_reference_)\n      reference_discretization_->init();\n    logger.info() << \"done (grid has \" << discretization_.grid_view().indexSet().size(0)\n                  << \" elements, discretization has \" << discretization_.ansatz_space().mapper().size() << \" DoFs)\"\n                  << std::endl;\n  } // ... Example(...)\n\n  const TestCaseType& test_case() const\n  {\n    return test_case_;\n  }\n\n  DiscretizationType& discretization()\n  {\n    return discretization_;\n  }\n\n  DiscretizationType* discretization_and_return_ptr() const\n  {\n    return new DiscretizationType(discretization_);\n  }\n\n  void visualize(const std::string& filename_prefix) const\n  {\n    test_case_.reference_provider()->visualize(filename_prefix + \".grid\", /*coupling=*/ false);\n    test_case_.problem().visualize(test_case_.reference_provider()->leaf_view(),\n                                   filename_prefix + \".problem\",\n                                   /*subsampling=*/ false);\n  } // ... visualize(...)\n\n  VectorType project(const std::string expression) const\n  {\n    using namespace Dune;\n    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n    typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;\n    DiscreteFunctionType discrete_function(discretization_.ansatz_space());\n\n    typedef Stuff::Functions::Expression< typename DiscreteFunctionType::EntityType,\n                                          typename DiscreteFunctionType::DomainFieldType,\n                                          DiscreteFunctionType::dimDomain,\n                                          typename DiscreteFunctionType::RangeFieldType,\n                                          DiscreteFunctionType::dimRange > ExpressionFunctionType;\n    ExpressionFunctionType func(\"x\", expression);\n\n    GDT::Operators::Projection< typename DiscretizationType::GridViewType > projection(discretization_.grid_view());\n    projection.apply(func, discrete_function);\n\n    return discrete_function.vector();\n  } // ... project(...)\n\n  RangeFieldType compute_error(const VectorType& solution,\n                               const std::string product_type = \"\",\n                               const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter(),\n                               const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())\n  {\n    if (!with_reference_)\n      DUNE_THROW(Dune::Stuff::Exceptions::you_are_using_this_wrong,\n                 \"Do not call compute error() if with_reference is false!\");\n    const std::string type = (product_type.empty() && reference_discretization_->available_products().size() == 1)\n                             ? reference_discretization_->available_products()[0]\n                             : product_type;\n    // wrap solution into a discrete function\n    using namespace Dune;\n    typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;\n    typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;\n    ConstDiscreteFunctionType coarse_solution(discretization_.ansatz_space(), solution);\n    // prolong to reference grid view\n    typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;\n    DiscreteFunctionType fine_solution(reference_discretization_->ansatz_space());\n    GDT::Operators::Prolongation< typename DiscretizationType::GridViewType >\n        prolongation_operator(reference_discretization_->grid_view());\n    prolongation_operator.apply(coarse_solution, fine_solution);\n    // compute reference solution\n    DiscreteFunctionType reference_solution(reference_discretization_->ansatz_space());\n    reference_discretization_->solve(reference_solution.vector(), mu);\n    // compute error\n    const auto difference = reference_solution.vector() - fine_solution.vector();\n    const auto product = reference_discretization_->get_product(type);\n    return std::sqrt(product.apply2(difference, difference, mu_product));\n  } // ... compute_error(...)\n\n  VectorType* pb_project_global_to_oversampled(const VectorType& global_vector, const DUNE_STUFF_SSIZE_T subdomain) const\n  {\n    using namespace Dune;\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::wrong_input_given,\n                 \"There was an error in boost converting \" << subdomain << \" to \"\n                 << Stuff::Common::Typename< size_t >::value() << \": \\n\\n\" << ee.what());\n    }\n    const GDT::ConstDiscreteFunction< typename DiscretizationType::AnsatzSpaceType, VectorType >\n        global_function(discretization_.ansatz_space(), global_vector);\n    const auto oversampled_discretization = discretization_.get_oversampled_discretization(subdomain, \"dirichlet\");\n    GDT::DiscreteFunction< typename DiscretizationType::OversampledDiscretizationType::AnsatzSpaceType, VectorType >\n        oversampled_function(oversampled_discretization.ansatz_space());\n    const GDT::Operators::Projection< typename DiscretizationType::OversampledDiscretizationType::GridViewType >\n        projection_operator(oversampled_discretization.grid_view());\n    projection_operator.apply(global_function, oversampled_function);\n    return new VectorType(oversampled_function.vector());\n  } // ... pb_project_global_to_oversampled(...)\n\n  VectorType* pb_project_global_to_local(const VectorType& global_vector, const DUNE_STUFF_SSIZE_T subdomain) const\n  {\n    using namespace Dune;\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::wrong_input_given,\n                 \"There was an error in boost converting \" << subdomain << \" to \"\n                 << Stuff::Common::Typename< size_t >::value() << \": \\n\\n\" << ee.what());\n    }\n    const GDT::ConstDiscreteFunction< typename DiscretizationType::AnsatzSpaceType, VectorType >\n        global_function(discretization_.ansatz_space(), global_vector);\n    const auto local_discretization = discretization_.get_local_discretization(subdomain);\n    GDT::DiscreteFunction< typename DiscretizationType::LocalDiscretizationType::AnsatzSpaceType, VectorType >\n        local_function(local_discretization.ansatz_space());\n    const GDT::Operators::Projection< typename DiscretizationType::LocalDiscretizationType::GridViewType >\n        projection_operator(local_discretization.grid_view());\n    projection_operator.apply(global_function, local_function);\n    return new VectorType(local_function.vector());\n  } // ... pb_project_global_to_local(...)\n\n  VectorType* pb_project_oversampled_to_local(const VectorType& oversampled_vector, const DUNE_STUFF_SSIZE_T subdomain) const\n  {\n    using namespace Dune;\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::wrong_input_given,\n                 \"There was an error in boost converting \" << subdomain << \" to \"\n                 << Stuff::Common::Typename< size_t >::value() << \": \\n\\n\" << ee.what());\n    }\n    const auto oversampled_discretization = discretization_.get_oversampled_discretization(subdomain, \"dirichlet\");\n    const GDT::ConstDiscreteFunction\n        < typename DiscretizationType::OversampledDiscretizationType::AnsatzSpaceType, VectorType >\n        oversampled_function(oversampled_discretization.ansatz_space(), oversampled_vector);\n    const auto local_discretization = discretization_.get_local_discretization(subdomain);\n    const auto& local_space = local_discretization.ansatz_space();\n    GDT::DiscreteFunction< typename DiscretizationType::LocalDiscretizationType::AnsatzSpaceType, VectorType >\n        local_function(local_space);\n    const GDT::Operators::Projection< typename DiscretizationType::LocalDiscretizationType::GridViewType >\n        projection_operator(local_space.grid_view());\n    projection_operator.apply(oversampled_function, local_function);\n    return new VectorType(local_function.vector());\n  } // ... pb_project_oversampled_to_local(...)\n\n  std::vector< std::string > available_estimators() const\n  {\n    return Estimator::available();\n  }\n\n  RangeFieldType estimate(const VectorType& vector,\n                          const std::string type,\n                          const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),\n                          const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),\n                          const Dune::Pymor::Parameter mu     = Dune::Pymor::Parameter())\n  {\n    return Estimator::estimate(discretization_.ansatz_space(),\n                               vector,\n                               discretization_.problem(),\n                               type,\n                               merge_parameters({{\"mu_hat\", mu_hat},\n                                                 {\"mu_bar\", mu_bar},\n                                                 {\"mu\",     mu}},\n                                                parameter_range_));\n  } // ... estimate(...)\n\n  std::vector< std::string > available_local_estimators() const\n  {\n    return Estimator::available_local();\n  }\n\n  std::vector< RangeFieldType > estimate_local(const VectorType& vector,\n                                               const std::string type,\n                                               const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),\n                                               const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),\n                                               const Dune::Pymor::Parameter mu     = Dune::Pymor::Parameter())\n  {\n    return Estimator::estimate_local(discretization_.ansatz_space(),\n                                     vector,\n                                     discretization_.problem(),\n                                     type,\n                                     merge_parameters({{\"mu_hat\", mu_hat},\n                                                       {\"mu_bar\", mu_bar},\n                                                       {\"mu\",     mu}},\n                                                      parameter_range_));\n  } // ... estimate_local(...)\n\n  VectorType solve_for_local_correction(const std::vector< VectorType >& local_vectors,\n                                        const DUNE_STUFF_SSIZE_T subdomain,\n                                        const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter()) const\n  {\n    const size_t ss = boost::numeric_cast< size_t >(subdomain);\n    return discretization_.solve_for_local_correction(local_vectors, ss, mu);\n  }\n\n  VectorType solve_oversampled(const DUNE_STUFF_SSIZE_T subdomain,\n                               const std::string& boundary_value_type,\n                               const VectorType& boundary_values,\n                               const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter()) const\n  {\n    using namespace Dune;\n    DSC::Configuration boundary_cfg;\n    if (boundary_value_type == \"dirichlet\")\n      boundary_cfg = Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config();\n    else if (boundary_value_type == \"neumann\")\n      boundary_cfg = Stuff::Grid::BoundaryInfoConfigs::AllNeumann::default_config();\n    else\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Unknown boundary_value_type given: \" << boundary_value_type);\n    // we need this one temporarily for the space\n    const auto tmp_oversampled_discretization = discretization_.get_oversampled_discretization(boost::numeric_cast< size_t >(subdomain),\n                                                                                               boundary_value_type);\n    const auto oversampled_space = tmp_oversampled_discretization.ansatz_space();\n    typedef typename DiscretizationType::OversampledDiscretizationType OversampledDiscretizationType;\n    typedef typename HDD::LinearElliptic::Problems::ConvertToDefault< typename TestCaseType::ProblemType >::Type\n                                                                       OversampledProblemType;\n    typedef typename OversampledDiscretizationType::AnsatzSpaceType    OversampledAnsatzSpaceType;\n    auto bv_function = std::make_shared< GDT::ConstDiscreteFunction< OversampledAnsatzSpaceType, VectorType > >(\n          oversampled_space, boundary_values, \"boundary_values\");\n    auto nonparametric_problem = test_case_.problem().with_mu(mu);\n    const OversampledProblemType oversampled_problem(nonparametric_problem->diffusion_factor()->affine_part(),\n                                                     nonparametric_problem->diffusion_tensor()->affine_part(),\n                                                     nonparametric_problem->force()->affine_part(),\n                                                     bv_function,\n                                                     bv_function);\n    OversampledDiscretizationType discretization(*test_case_.reference_provider(),\n                                                 boundary_cfg,\n                                                 oversampled_problem,\n                                                 boost::numeric_cast< int >(subdomain));\n    discretization.init();\n    VectorType solution = discretization.create_vector();\n    discretization.solve(solution);\n    return solution;\n  } // ... solve_oversampled(...)\n\n  void visualize_on_coarse_grid(const std::vector< double >& vector,\n                                const std::string& filename,\n                                const std::string& name)\n  {\n    using namespace Dune;\n    const auto ms_grid = discretization_.ansatz_space().ms_grid();\n    const auto& grid_view = discretization_.grid_view();\n    if (vector.size() != ms_grid->size())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n                 \"Given vector has wrong lenght!\\n\"\n                 << \"  expected: \" << ms_grid->size() << \"\\n\"\n                 << \"  actual:   \" << vector.size() << \"\\n\");\n    if (filename.empty())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Given filename must not be empty!\");\n    if (name.empty())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Given name must not be empty!\");\n    GDT::Spaces::FiniteVolume::Default< typename std::remove_reference< decltype(grid_view) >::type, RangeFieldType, 1 >\n        fv_space(grid_view);\n    auto visualization = GDT::make_discrete_function< VectorType >(fv_space, name);\n    for (const auto& entity : Stuff::Common::entityRange(grid_view))\n      visualization.vector().set_entry(grid_view.indexSet().index(entity), vector[ms_grid->subdomainOf(entity)]);\n    visualization.visualize(filename);\n  } // ... visualize_on_coarse_grid(...)\n\n  RangeFieldType alpha(const Dune::Pymor::Parameter& mu_1, const Dune::Pymor::Parameter& mu_2)\n  {\n    return test_case_.problem().diffusion_factor()->alpha(mu_1, mu_2);\n  }\n\n  RangeFieldType gamma(const Dune::Pymor::Parameter& mu_1, const Dune::Pymor::Parameter& mu_2)\n  {\n    return test_case_.problem().diffusion_factor()->gamma(mu_1, mu_2);\n  }\n\nprivate:\n  static ParametersMapType merge_parameters(const ParametersMapType& first,\n                                            const ParametersMapType& second)\n  {\n    ParametersMapType ret = first;\n    for (const auto& element : second)\n      ret.insert(element);\n    return ret;\n  }\n\n  const bool with_reference_;\n  const ParametersMapType parameter_range_;\n  TestCaseType test_case_;\n  std::unique_ptr< TestCaseType > reference_test_case_;\n  DiscretizationType discretization_;\n  std::unique_ptr< DiscretizationType > reference_discretization_;\n}; // class Example\n\n\n} // namespace internal\n\n\ntemplate< class GridImp >\nclass OS2015MultiscaleExample\n  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2015::Multiscale< GridImp > >\n{\n  static_assert(GridImp::dimension == 2, \"Only available in 2d!\");\n  typedef internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2015::Multiscale< GridImp > > BaseType;\n\npublic:\n  template< class... Args >\n  OS2015MultiscaleExample(Args&& ...args)\n    : BaseType({{\"parameter_range_min\", Dune::Pymor::Parameter(\"mu\", 0.1)},\n                {\"parameter_range_max\", Dune::Pymor::Parameter(\"mu\", 1.0)}},\n               std::forward< Args >(args)...)\n  {}\n}; // class OS2015MultiscaleExample\n\n\ntemplate< class GridImp >\nclass OS2015AcademicExample\n  : public internal::Example< Dune::HDD::LinearElliptic::TestCases::OS2015::Academic< GridImp > >\n{\n  static_assert(GridImp::dimension == 2, \"Only available in 2d!\");\n  typedef internal::Example\n      < Dune::HDD::LinearElliptic::TestCases::OS2015::Academic< GridImp > > BaseType;\n\npublic:\n  template< class... Args >\n  OS2015AcademicExample(Args&& ...args)\n    : BaseType({{\"parameter_range_min\", Dune::Pymor::Parameter(\"mu\", 0.1)},\n                {\"parameter_range_max\", Dune::Pymor::Parameter(\"mu\", 1.0)}},\n               std::forward< Args >(args)...)\n  {}\n}; // class OS2015AcademicExample\n\n\n#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2015_SISC_6_2_HH\n", "meta": {"hexsha": "64a0e4a62dc9eecb582fbe6a4404df0606c84f0a", "size": 23269, "ext": "hh", "lang": "C++", "max_stars_repo_path": "examples/linearelliptic/OS2015_SISC__6_2.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": "examples/linearelliptic/OS2015_SISC__6_2.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": "examples/linearelliptic/OS2015_SISC__6_2.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": 49.9334763948, "max_line_length": 137, "alphanum_fraction": 0.6284756543, "num_tokens": 4987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.05749327435934956, "lm_q1q2_score": 0.028073011210858156}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2019 - 2022 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 \"ibamr/IBInterpolantMethod.h\"\n\n#include \"ibtk/HierarchyIntegrator.h\"\n#include \"ibtk/IBTK_CHKERRQ.h\"\n#include \"ibtk/IBTK_MPI.h\"\n#include \"ibtk/LData.h\"\n#include \"ibtk/LDataManager.h\"\n#include \"ibtk/LEInteractor.h\"\n#include \"ibtk/LInitStrategy.h\"\n#include \"ibtk/LMesh.h\"\n#include \"ibtk/LNode.h\"\n#include \"ibtk/LSiloDataWriter.h\"\n#include \"ibtk/ibtk_utilities.h\"\n\n#include \"BasePatchHierarchy.h\"\n#include \"BasePatchLevel.h\"\n#include \"CartesianGridGeometry.h\"\n#include \"CellVariable.h\"\n#include \"CoarsenSchedule.h\"\n#include \"GriddingAlgorithm.h\"\n#include \"HierarchyCellDataOpsReal.h\"\n#include \"HierarchySideDataOpsReal.h\"\n#include \"IntVector.h\"\n#include \"MultiblockDataTranslator.h\"\n#include \"PatchHierarchy.h\"\n#include \"PatchLevel.h\"\n#include \"RefineAlgorithm.h\"\n#include \"RefineOperator.h\"\n#include \"SideVariable.h\"\n#include \"Variable.h\"\n#include \"VariableContext.h\"\n#include \"VariableDatabase.h\"\n#include \"tbox/Array.h\"\n#include \"tbox/Database.h\"\n#include \"tbox/MathUtilities.h\"\n#include \"tbox/PIO.h\"\n#include \"tbox/Pointer.h\"\n#include \"tbox/RestartManager.h\"\n#include \"tbox/Utilities.h\"\n\n#include \"petscvec.h\"\n#include <petscsys.h>\n\n#include \"ibamr/namespaces.h\" // IWYU pragma: keep\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <boost/multi_array.hpp>\nIBTK_ENABLE_EXTRA_WARNINGS\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <Eigen/Core>\n#include <Eigen/Geometry>\nIBTK_ENABLE_EXTRA_WARNINGS\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <limits>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace SAMRAI\n{\nnamespace xfer\n{\ntemplate <int DIM>\nclass RefineSchedule;\n} // namespace xfer\n} // namespace SAMRAI\n\nnamespace IBTK\n{\nclass RobinPhysBdryPatchStrategy;\n} // namespace IBTK\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\nnamespace IBAMR\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\nnamespace\n{\n// Version of IBInterpolantMethod restart file data.\nstatic const int IB_INTERPOLANT_METHOD_VERSION = 1;\n\ninline void\nset_rotation_matrix(const EigenAlignedVector<Eigen::Vector3d>& rot_vel,\n                    const EigenAlignedVector<Eigen::Quaterniond>& q_old,\n                    EigenAlignedVector<Eigen::Quaterniond>& q_new,\n                    EigenAlignedVector<Eigen::Matrix3d>& rot_mat,\n                    const double dt)\n{\n    unsigned n_structs = (unsigned)rot_mat.size();\n    for (unsigned struct_no = 0; struct_no < n_structs; ++struct_no)\n    {\n        const double norm = rot_vel[struct_no].norm();\n        if (!IBTK::abs_equal_eps(norm, 0.0))\n        {\n            Eigen::Vector3d rot_axis = rot_vel[struct_no] / norm;\n            Eigen::Quaterniond q(Eigen::AngleAxisd(norm * dt, rot_axis));\n            q_new[struct_no] = (q.normalized() * q_old[struct_no]).normalized();\n        }\n        else\n        {\n            q_new[struct_no] = q_old[struct_no];\n        }\n\n        rot_mat[struct_no] = q_new[struct_no].toRotationMatrix();\n    }\n    return;\n} // set_rotation_matrix\n\n} // namespace\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nIBInterpolantMethod::IBInterpolantMethod(std::string object_name,\n                                         Pointer<Database> input_db,\n                                         int no_structures,\n                                         bool register_for_restart)\n    : d_num_rigid_parts(no_structures),\n      d_object_name(std::move(object_name)),\n      d_registered_for_restart(register_for_restart)\n{\n    // Register object with the restart manager.\n    if (d_registered_for_restart)\n    {\n        RestartManager::getManager()->registerRestartItem(d_object_name, this);\n    }\n\n    // Set some default values.\n    d_struct_lag_idx_range.resize(d_num_rigid_parts);\n    d_quaternion_current.resize(d_num_rigid_parts, Eigen::Quaterniond::Identity());\n    d_quaternion_new.resize(d_num_rigid_parts, Eigen::Quaterniond::Identity());\n    d_center_of_mass_initial.resize(d_num_rigid_parts, Eigen::Vector3d::Zero());\n    d_center_of_mass_current.resize(d_num_rigid_parts, Eigen::Vector3d::Zero());\n    d_center_of_mass_new.resize(d_num_rigid_parts, Eigen::Vector3d::Zero());\n\n    // Set some default values.\n    d_ghosts = std::max(LEInteractor::getMinimumGhostWidth(d_interp_kernel_fcn),\n                        LEInteractor::getMinimumGhostWidth(d_spread_kernel_fcn));\n\n    // Initialize object with data read from the input and restart databases.\n    bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (from_restart) getFromRestart();\n    if (input_db) getFromInput(input_db, from_restart);\n\n    // Check the choices for the kernel function.\n    if (d_interp_kernel_fcn != d_spread_kernel_fcn)\n    {\n        pout << \"WARNING: different kernel functions are being used for  \"\n                \"interpolation and \"\n                \"spreading.\\n\";\n    }\n\n    // Get the Lagrangian Data Manager.\n    d_l_data_manager = LDataManager::getManager(d_object_name + \"::LDataManager\",\n                                                d_interp_kernel_fcn,\n                                                d_spread_kernel_fcn,\n                                                d_error_if_points_leave_domain,\n                                                d_ghosts,\n                                                d_registered_for_restart);\n    d_ghosts = d_l_data_manager->getGhostCellWidth();\n\n    return;\n} // IBInterpolantMethod\n\nIBInterpolantMethod::~IBInterpolantMethod()\n{\n    if (d_registered_for_restart)\n    {\n        RestartManager::getManager()->unregisterRestartItem(d_object_name);\n        d_registered_for_restart = false;\n    }\n    return;\n} // ~IBInterpolantMethod\n\nvoid\nIBInterpolantMethod::registerEulerianVariables()\n{\n    const IntVector<NDIM> ib_ghosts = getMinimumGhostCellWidth();\n    for (auto& q_pair : d_q_interp_idx)\n    {\n        const std::string& var_name = q_pair.first;\n        q_pair.second = -1;\n        registerVariable(q_pair.second, d_q_var[var_name], ib_ghosts, NULL /*d_ib_solver->getScratchContext()*/);\n    }\n\n    return;\n} // registerEulerianVariables\n\nvoid\nIBInterpolantMethod::registerEulerianCommunicationAlgorithms()\n{\n    Pointer<RefineAlgorithm<NDIM> > ghost_fill_alg = new RefineAlgorithm<NDIM>();\n    Pointer<RefineOperator<NDIM> > refine_op = NULL;\n\n    for (const auto& q_pair : d_q_interp_idx)\n    {\n        const int q_interp_idx = q_pair.second;\n        ghost_fill_alg->registerRefine(q_interp_idx, q_interp_idx, q_interp_idx, refine_op);\n    }\n    registerGhostfillRefineAlgorithm(d_object_name + \"::ghost_fill_alg\", ghost_fill_alg);\n\n    return;\n} // registerEulerianCommunicationAlgorithms\n\nvoid\nIBInterpolantMethod::registerVariableAndHierarchyIntegrator(const std::string& var_name,\n                                                            const int var_depth,\n                                                            Pointer<Variable<NDIM> > var,\n                                                            Pointer<HierarchyIntegrator> hier_integrator)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(d_q_var.find(var_name) == d_q_var.end());\n    TBOX_ASSERT(d_q_depth.find(var_name) == d_q_depth.end());\n    TBOX_ASSERT(d_q_hier_integrator.find(var_name) == d_q_hier_integrator.end());\n#endif\n    d_q_var[var_name] = var;\n    d_q_depth[var_name] = var_depth;\n    d_q_hier_integrator[var_name] = hier_integrator;\n    d_q_interp_idx[var_name] = -1;\n    d_Q_current_data[var_name] = {};\n    d_Q_new_data[var_name] = {};\n\n    return;\n} // registerVariableAndHierarchyIntegrator\n\nvoid\nIBInterpolantMethod::registerLInitStrategy(Pointer<LInitStrategy> l_initializer)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(l_initializer);\n#endif\n    d_l_initializer = l_initializer;\n    d_l_data_manager->registerLInitStrategy(d_l_initializer);\n    return;\n} // registerLInitStrategy\n\nvoid\nIBInterpolantMethod::freeLInitStrategy()\n{\n    d_l_initializer.setNull();\n    d_l_data_manager->freeLInitStrategy();\n    return;\n} // freeLInitStrategy\n\nLDataManager*\nIBInterpolantMethod::getLDataManager() const\n{\n    return d_l_data_manager;\n} // getLDataManager\n\nint\nIBInterpolantMethod::getStructuresLevelNumber() const\n{\n    return d_hierarchy->getFinestLevelNumber();\n\n} // getStructuresLevelNumber\n\nint\nIBInterpolantMethod::getStructureHandle(const int lag_idx) const\n{\n    for (unsigned struct_no = 0; struct_no < d_num_rigid_parts; ++struct_no)\n    {\n        const std::pair<int, int>& lag_idx_range = d_struct_lag_idx_range[struct_no];\n        if (lag_idx_range.first <= lag_idx && lag_idx < lag_idx_range.second) return struct_no;\n    }\n\n    return -1;\n} // getStructureHandle\n\nvoid\nIBInterpolantMethod::registerLSiloDataWriter(Pointer<LSiloDataWriter> silo_writer)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(silo_writer);\n#endif\n    d_silo_writer = silo_writer;\n    d_l_data_manager->registerLSiloDataWriter(d_silo_writer);\n    return;\n} // registerLSiloDataWriter\n\nconst IntVector<NDIM>&\nIBInterpolantMethod::getMinimumGhostCellWidth() const\n{\n    return d_ghosts;\n} // getMinimumGhostCellWidth\n\nvoid\nIBInterpolantMethod::setupTagBuffer(Array<int>& tag_buffer, Pointer<GriddingAlgorithm<NDIM> > gridding_alg) const\n{\n    const int finest_hier_ln = gridding_alg->getMaxLevels() - 1;\n    const int tsize = tag_buffer.size();\n    tag_buffer.resizeArray(finest_hier_ln);\n    for (int i = tsize; i < finest_hier_ln; ++i) tag_buffer[i] = 0;\n    const int gcw = d_ghosts.max();\n    for (int tag_ln = 0; tag_ln < finest_hier_ln; ++tag_ln)\n    {\n        const int data_ln = tag_ln + 1;\n        const int can_be_refined = data_ln < finest_hier_ln;\n        if (!d_l_initializer->getLevelHasLagrangianData(data_ln, can_be_refined)) continue;\n        tag_buffer[tag_ln] = std::max(tag_buffer[tag_ln], gcw);\n    }\n    for (int ln = finest_hier_ln - 2; ln >= 0; --ln)\n    {\n        tag_buffer[ln] =\n            std::max(tag_buffer[ln], tag_buffer[ln + 1] / gridding_alg->getRatioToCoarserLevel(ln + 1).max() + 1);\n    }\n    return;\n} // setupTagBuffer\n\nvoid\nIBInterpolantMethod::preprocessIntegrateData(double current_time, double new_time, int /*num_cycles*/)\n{\n    d_current_time = current_time;\n    d_new_time = new_time;\n    d_half_time = current_time + 0.5 * (new_time - current_time);\n\n    int ierr;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Look-up or allocate Lagangian data.\n    d_X_current_data.resize(finest_ln + 1);\n    d_X_new_data.resize(finest_ln + 1);\n    for (auto& Q_pair : d_Q_current_data)\n    {\n        const std::string& name = Q_pair.first;\n        Q_pair.second.resize(finest_ln + 1);\n        d_Q_new_data[name].resize(finest_ln + 1);\n    }\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        d_X_current_data[ln] = d_l_data_manager->getLData(LDataManager::POSN_DATA_NAME, ln);\n        d_X_new_data[ln] = d_l_data_manager->createLData(\"X_new\", ln, NDIM);\n\n        for (auto& Q_pair : d_Q_current_data)\n        {\n            const std::string& name = Q_pair.first;\n            Q_pair.second[ln] = d_l_data_manager->getLData(name, ln);\n            d_Q_new_data[name][ln] = d_l_data_manager->createLData(name + \"_new\", ln, d_q_depth[name]);\n        }\n\n        // Initialize X^{n+1} to equal X^{n}, and initialize Q^{n+1} to equal Q^{n}.\n        ierr = VecCopy(d_X_current_data[ln]->getVec(), d_X_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n        for (auto& Q_pair : d_Q_current_data)\n        {\n            const std::string& name = Q_pair.first;\n            ierr = VecCopy(Q_pair.second[ln]->getVec(), d_Q_new_data[name][ln]->getVec());\n            IBTK_CHKERRQ(ierr);\n        }\n    }\n\n    return;\n} // preprocessIntegrateData\n\nvoid\nIBInterpolantMethod::postprocessIntegrateData(double /*current_time*/, double /*new_time*/, int /*num_cycles*/)\n{\n    int ierr;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Reset time-dependent Lagrangian data.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        ierr = VecSwap(d_X_current_data[ln]->getVec(), d_X_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n        for (auto& Q_pair : d_Q_current_data)\n        {\n            const std::string& name = Q_pair.first;\n            ierr = VecSwap(Q_pair.second[ln]->getVec(), d_Q_new_data[name][ln]->getVec());\n            IBTK_CHKERRQ(ierr);\n        }\n    }\n\n    // Deallocate Lagrangian scratch data.\n    d_X_current_data.clear();\n    d_X_new_data.clear();\n    for (auto& Q_pair : d_Q_current_data)\n    {\n        const std::string& name = Q_pair.first;\n        Q_pair.second.clear();\n        d_Q_new_data[name].clear();\n    }\n\n    // New state becomes current state for the next timestep.\n    d_center_of_mass_current = d_center_of_mass_new;\n    d_quaternion_current = d_quaternion_new;\n\n    // Reset the current time step interval.\n    d_current_time = std::numeric_limits<double>::quiet_NaN();\n    d_new_time = std::numeric_limits<double>::quiet_NaN();\n    d_half_time = std::numeric_limits<double>::quiet_NaN();\n    return;\n} // postprocessIntegrateData\n\nvoid\nIBInterpolantMethod::interpolateVelocity(const int /*u_data_idx*/,\n                                         const std::vector<Pointer<CoarsenSchedule<NDIM> > >& /*u_synch_scheds*/,\n                                         const std::vector<Pointer<RefineSchedule<NDIM> > >& /*u_ghost_fill_scheds*/,\n                                         const double /*data_time*/)\n{\n    TBOX_ERROR(\"IBInterpolantMethod::interpolateVelocity(). This method is not implemented.\" << std::endl);\n    return;\n} // interpolateVelocity\n\nvoid\nIBInterpolantMethod::interpolateQ(const double data_time)\n{\n    int finest_ln = d_hierarchy->getFinestLevelNumber();\n    std::vector<Pointer<LData> >* X_data;\n    getPositionData(&X_data, data_time);\n    std::vector<Pointer<LData> >* Q_data;\n\n    for (auto& Q_pair : d_Q_current_data)\n    {\n        const std::string& name = Q_pair.first;\n        int q_data_idx = d_q_interp_idx[name];\n        copyEulerianDataFromIntegrator(name, q_data_idx, data_time);\n        getQData(name, &Q_data, data_time);\n        d_l_data_manager->interp(q_data_idx,\n                                 *Q_data,\n                                 *X_data,\n                                 std::vector<Pointer<CoarsenSchedule<NDIM> > >(finest_ln + 1, NULL),\n                                 getGhostfillRefineSchedules(d_object_name + \"::ghost_fill_alg\"),\n                                 data_time);\n    }\n\n    return;\n} // interpolateQ\n\nvoid\nIBInterpolantMethod::interpolateQ()\n{\n    interpolateQ(d_current_time);\n    interpolateQ(d_new_time);\n\n    return;\n} // interpolateQ\n\nvoid\nIBInterpolantMethod::forwardEulerStep(const double /*current_time*/, const double /*new_time*/)\n{\n    TBOX_ERROR(\"IBInterpolantMethod::forwardEulerStep(). This method is not implemented.\" << std::endl);\n    return;\n} // forwardEulerStep\n\nvoid\nIBInterpolantMethod::backwardEulerStep(const double /*current_time*/, const double /*new_time*/)\n{\n    TBOX_ERROR(\"IBInterpolantMethod::backwardEulerStep(). This method is not implemented.\" << std::endl);\n    return;\n} // backwardEulerStep\n\nvoid\nIBInterpolantMethod::midpointStep(const double /*current_time*/, const double /*new_time*/)\n{\n    TBOX_ERROR(\"IBInterpolantMethod::midpointStep(). This method is not implemented.\" << std::endl);\n    return;\n} // midpointStep\n\nvoid\nIBInterpolantMethod::trapezoidalStep(const double /*current_time*/, const double /*new_time*/)\n{\n    TBOX_ERROR(\"IBInterpolantMethod::trapezoidalStep(). This method is not implemented.\" << std::endl);\n    return;\n} // trapezoidalStep\n\nvoid\nIBInterpolantMethod::updateMeshPosition(double current_time,\n                                        double new_time,\n                                        const EigenAlignedVector<Eigen::Vector3d>& U,\n                                        const EigenAlignedVector<Eigen::Vector3d>& W)\n{\n    const double dt = new_time - current_time;\n\n    // Fill the rotation matrix of structures with rotation angle (W^n+1)*dt.\n    EigenAlignedVector<Eigen::Matrix3d> rotation_mat(d_num_rigid_parts, Eigen::Matrix3d::Identity(3, 3));\n    set_rotation_matrix(W, d_quaternion_current, d_quaternion_new, rotation_mat, dt);\n\n    // Rotate the body with new rotational velocity about origin\n    // and translate the body to newer position.\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        boost::multi_array_ref<double, 2>& X_new_array = *d_X_new_data[ln]->getLocalFormVecArray();\n        const boost::multi_array_ref<double, 2>& X0_array =\n            *(d_l_data_manager->getLData(\"X0\", ln)->getLocalFormVecArray());\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const unsigned structs_on_this_ln = (unsigned)structIDs.size();\n#if !defined(NDEBUG)\n        TBOX_ASSERT(structs_on_this_ln == d_num_rigid_parts);\n#endif\n\n        for (const auto& node_idx : local_nodes)\n        {\n            const int lag_idx = node_idx->getLagrangianIndex();\n            const int local_idx = node_idx->getLocalPETScIndex();\n            double* const X_new = &X_new_array[local_idx][0];\n            const double* const X0 = &X0_array[local_idx][0];\n            Eigen::Vector3d dr = Eigen::Vector3d::Zero();\n\n            int struct_handle = 0;\n            if (structs_on_this_ln > 1) struct_handle = getStructureHandle(lag_idx);\n\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                dr[d] = X0[d] - d_center_of_mass_initial[struct_handle][d];\n            }\n\n            // Rotate dr vector using the rotation matrix.\n            const Eigen::Vector3d R_dr = rotation_mat[struct_handle] * dr;\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                X_new[d] = d_center_of_mass_current[struct_handle][d] + R_dr[d] + dt * U[struct_handle][d];\n            }\n        }\n        d_X_new_data[ln]->restoreArrays();\n        d_l_data_manager->getLData(\"X0\", ln)->restoreArrays();\n    }\n\n    // Compute the new center of mass.\n    for (unsigned struct_no = 0; struct_no < d_num_rigid_parts; ++struct_no)\n    {\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            d_center_of_mass_new[struct_no][d] = d_center_of_mass_current[struct_no][d] + dt * U[struct_no][d];\n        }\n    }\n\n    return;\n} // updateMeshPosition\n\nvoid\nIBInterpolantMethod::computeLagrangianForce(double /*data_time*/)\n{\n    TBOX_ERROR(\"IBInterpolantMethod::computeLagrangianForce(). This method is not implemented.\" << std::endl);\n    return;\n} // computeLagrangianForce\n\nvoid\nIBInterpolantMethod::spreadForce(const int /*f_data_idx*/,\n                                 RobinPhysBdryPatchStrategy* /*f_phys_bdry_op*/,\n                                 const std::vector<Pointer<RefineSchedule<NDIM> > >& /*f_prolongation_scheds*/,\n                                 const double /*data_time*/)\n{\n    TBOX_ERROR(\"IBInterpolantMethod::spreadForce(). This method is not implemented.\" << std::endl);\n    return;\n} // spreadForce\n\nvoid\nIBInterpolantMethod::spreadQ(double data_time)\n{\n    int finest_ln = d_hierarchy->getFinestLevelNumber();\n    Pointer<PatchLevel<NDIM> > finest_level = d_hierarchy->getPatchLevel(finest_ln);\n    const IntVector<NDIM>& ratio = finest_level->getRatio();\n    Pointer<CartesianGridGeometry<NDIM> > grid_geom = d_hierarchy->getGridGeometry();\n    const double* dx0 = grid_geom->getDx();\n    std::array<double, NDIM> dx;\n    PetscScalar vol = 1.0;\n    for (unsigned i = 0; i < NDIM; ++i)\n    {\n        dx[i] = dx0[i] / ratio(i);\n        vol *= dx[i];\n    }\n\n    std::vector<Pointer<LData> >* X_data;\n    getPositionData(&X_data, data_time);\n    std::vector<Pointer<LData> >* Q_data;\n\n    for (auto& Q_pair : d_Q_current_data)\n    {\n        const std::string& name = Q_pair.first;\n        int q_data_idx = d_q_interp_idx[name];\n        zeroOutEulerianData(name, q_data_idx);\n\n        getQData(name, &Q_data, data_time);\n        Vec l_data_vec = (*Q_data)[finest_ln]->getVec();\n        VecScale(l_data_vec, vol);\n        d_l_data_manager->spread(q_data_idx, *Q_data, *X_data, (RobinPhysBdryPatchStrategy*)NULL);\n        VecScale(l_data_vec, 1.0 / vol);\n    }\n\n    return;\n} // spreadQ\n\nvoid\nIBInterpolantMethod::copyEulerianDataToIntegrator(double data_time)\n{\n    for (auto& Q_pair : d_Q_current_data)\n    {\n        const std::string& name = Q_pair.first;\n        int q_data_idx = d_q_interp_idx[name];\n        copyEulerianDataToIntegrator(name, q_data_idx, data_time);\n    }\n    return;\n} // copyEulerianDataToIntegrator\n\nvoid\nIBInterpolantMethod::initializePatchHierarchy(\n    Pointer<PatchHierarchy<NDIM> > hierarchy,\n    Pointer<GriddingAlgorithm<NDIM> > gridding_alg,\n    int /*u_data_idx*/,\n    const std::vector<Pointer<CoarsenSchedule<NDIM> > >& /*u_synch_scheds*/,\n    const std::vector<Pointer<RefineSchedule<NDIM> > >& /*u_ghost_fill_scheds*/,\n    int /*integrator_step*/,\n    double /*init_data_time*/,\n    bool initial_time)\n{\n    // Cache pointers to the patch hierarchy and gridding algorithm.\n    d_hierarchy = hierarchy;\n    d_gridding_alg = gridding_alg;\n\n    // Set structure index info.\n    const int struct_ln = getStructuresLevelNumber();\n    std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(struct_ln);\n    std::sort(structIDs.begin(), structIDs.end());\n    const auto structs_on_this_ln = static_cast<unsigned>(structIDs.size());\n\n    for (unsigned struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n    {\n        d_struct_lag_idx_range[struct_no] =\n            d_l_data_manager->getLagrangianStructureIndexRange(structIDs[struct_no], struct_ln);\n    }\n\n    // Initialize initial center of mass of structures.\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    std::vector<Pointer<LData> > X0_data_vec(finest_ln + 1, Pointer<LData>(NULL));\n    X0_data_vec[finest_ln] = d_l_data_manager->getLData(\"X0\", finest_ln);\n    computeCenterOfMass(d_center_of_mass_initial, X0_data_vec);\n\n    if (initial_time)\n    {\n        d_center_of_mass_current = d_center_of_mass_initial;\n    }\n\n    return;\n} // initializePatchHierarchy\n\nvoid\nIBInterpolantMethod::addWorkloadEstimate(Pointer<PatchHierarchy<NDIM> > hierarchy, const int workload_data_idx)\n{\n    d_l_data_manager->addWorkloadEstimate(hierarchy, workload_data_idx);\n    return;\n} // addWorkloadEstimate\n\nvoid IBInterpolantMethod::beginDataRedistribution(Pointer<PatchHierarchy<NDIM> > /*hierarchy*/,\n                                                  Pointer<GriddingAlgorithm<NDIM> > /*gridding_alg*/)\n{\n    d_l_data_manager->beginDataRedistribution();\n    return;\n} // beginDataRedistribution\n\nvoid IBInterpolantMethod::endDataRedistribution(Pointer<PatchHierarchy<NDIM> > /*hierarchy*/,\n                                                Pointer<GriddingAlgorithm<NDIM> > /*gridding_alg*/)\n{\n    d_l_data_manager->endDataRedistribution();\n    return;\n} // endDataRedistribution\n\nvoid\nIBInterpolantMethod::initializeLevelData(Pointer<BasePatchHierarchy<NDIM> > hierarchy,\n                                         int level_number,\n                                         double init_data_time,\n                                         bool can_be_refined,\n                                         bool initial_time,\n                                         Pointer<BasePatchLevel<NDIM> > old_level,\n                                         bool allocate_data)\n{\n    const int finest_hier_level = hierarchy->getFinestLevelNumber();\n    d_l_data_manager->setPatchHierarchy(hierarchy);\n    d_l_data_manager->setPatchLevels(0, finest_hier_level);\n    d_l_data_manager->initializeLevelData(\n        hierarchy, level_number, init_data_time, can_be_refined, initial_time, old_level, allocate_data);\n    if (initial_time && d_l_data_manager->levelContainsLagrangianData(level_number))\n    {\n        for (const auto& Q_pair : d_Q_current_data)\n        {\n            const std::string& Q_name = Q_pair.first;\n            const int Q_depth = d_q_depth[Q_name];\n            Pointer<LData> Q_data = d_l_data_manager->createLData(Q_name, level_number, Q_depth, /*manage_data*/ true);\n        }\n    }\n\n    return;\n} // initializeLevelData\n\nvoid\nIBInterpolantMethod::resetHierarchyConfiguration(Pointer<BasePatchHierarchy<NDIM> > hierarchy,\n                                                 int coarsest_level,\n                                                 int finest_level)\n{\n    const int finest_hier_level = hierarchy->getFinestLevelNumber();\n    d_l_data_manager->setPatchHierarchy(hierarchy);\n    d_l_data_manager->setPatchLevels(0, finest_hier_level);\n    d_l_data_manager->resetHierarchyConfiguration(hierarchy, coarsest_level, finest_level);\n\n    return;\n} // resetHierarchyConfiguration\n\nvoid\nIBInterpolantMethod::applyGradientDetector(Pointer<BasePatchHierarchy<NDIM> > base_hierarchy,\n                                           int level_number,\n                                           double error_data_time,\n                                           int tag_index,\n                                           bool initial_time,\n                                           bool uses_richardson_extrapolation_too)\n{\n    Pointer<PatchHierarchy<NDIM> > hierarchy = base_hierarchy;\n#if !defined(NDEBUG)\n    TBOX_ASSERT(hierarchy);\n    TBOX_ASSERT((level_number >= 0) && (level_number <= hierarchy->getFinestLevelNumber()));\n    TBOX_ASSERT(hierarchy->getPatchLevel(level_number));\n#endif\n\n    // Tag cells that contain Lagrangian nodes.\n    d_l_data_manager->applyGradientDetector(\n        hierarchy, level_number, error_data_time, tag_index, initial_time, uses_richardson_extrapolation_too);\n    return;\n} // applyGradientDetector\n\nvoid\nIBInterpolantMethod::putToDatabase(Pointer<Database> db)\n{\n    db->putInteger(\"IB_INTERPOLANT_METHOD_VERSION\", IB_INTERPOLANT_METHOD_VERSION);\n    db->putString(\"d_interp_kernel_fcn\", d_interp_kernel_fcn);\n    db->putString(\"d_spread_kernel_fcn\", d_spread_kernel_fcn);\n    db->putIntegerArray(\"d_ghosts\", d_ghosts, NDIM);\n\n    const int finest_hier_level = d_hierarchy->getFinestLevelNumber();\n    db->putInteger(\"finest_hier_level\", finest_hier_level);\n\n    for (unsigned int struct_no = 0; struct_no < d_num_rigid_parts; ++struct_no)\n    {\n        std::ostringstream C, Q;\n        C << \"C_\" << struct_no;\n        Q << \"Q_\" << struct_no;\n\n        double Q_coeffs[4] = { d_quaternion_current[struct_no].w(),\n                               d_quaternion_current[struct_no].x(),\n                               d_quaternion_current[struct_no].y(),\n                               d_quaternion_current[struct_no].z() };\n\n        db->putDoubleArray(C.str(), &d_center_of_mass_current[struct_no][0], 3);\n        db->putDoubleArray(Q.str(), &Q_coeffs[0], 4);\n    }\n\n    return;\n} // putToDatabase\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\nvoid\nIBInterpolantMethod::getPositionData(std::vector<Pointer<LData> >** X_data, double data_time)\n{\n    if (IBTK::rel_equal_eps(data_time, d_current_time))\n    {\n        *X_data = &d_X_current_data;\n    }\n    else if (IBTK::rel_equal_eps(data_time, d_new_time))\n    {\n        *X_data = &d_X_new_data;\n    }\n    else\n    {\n        TBOX_ERROR(\n            \"IBInterpolantMethod::getPositionData() Structure position inquired at times other than current and new. \"\n            \"\\n\");\n    }\n    return;\n} // getPositionData\n\nvoid\nIBInterpolantMethod::copyEulerianDataFromIntegrator(const std::string& var_name, int q_data_idx, double data_time)\n{\n    int q_hier_idx = -1;\n\n    Pointer<HierarchyIntegrator> hier_integrator = d_q_hier_integrator[var_name];\n    Pointer<Variable<NDIM> > var = d_q_var[var_name];\n\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    if (IBTK::rel_equal_eps(data_time, d_current_time))\n    {\n        q_hier_idx = var_db->mapVariableAndContextToIndex(var, hier_integrator->getCurrentContext());\n    }\n    else if (IBTK::rel_equal_eps(data_time, d_new_time))\n    {\n        q_hier_idx = var_db->mapVariableAndContextToIndex(var, hier_integrator->getNewContext());\n    }\n    else\n    {\n        TBOX_ERROR(\n            \"IBInterpolantMethod::getEulerianDataForInterpolation() Interpolation not supported at times other than \"\n            \"current and new.\\n\");\n    }\n\n    // Copy integrator data into q_data_idx\n    Pointer<CellVariable<NDIM, double> > cc_var = var;\n    Pointer<SideVariable<NDIM, double> > sc_var = var;\n    if (cc_var)\n    {\n        HierarchyCellDataOpsReal<NDIM, double> hier_data_ops(d_hierarchy);\n        hier_data_ops.copyData(q_data_idx, q_hier_idx);\n    }\n\n    if (sc_var)\n    {\n        HierarchySideDataOpsReal<NDIM, double> hier_data_ops(d_hierarchy);\n        hier_data_ops.copyData(q_data_idx, q_hier_idx);\n    }\n\n    return;\n} // copyEulerianDataFromIntegrator\n\nvoid\nIBInterpolantMethod::zeroOutEulerianData(const std::string& var_name, int q_data_idx)\n{\n    Pointer<Variable<NDIM> > var = d_q_var[var_name];\n\n    Pointer<CellVariable<NDIM, double> > cc_var = var;\n    Pointer<SideVariable<NDIM, double> > sc_var = var;\n    if (cc_var)\n    {\n        HierarchyCellDataOpsReal<NDIM, double> hier_data_ops(d_hierarchy);\n        hier_data_ops.setToScalar(q_data_idx, 0.0);\n    }\n\n    if (sc_var)\n    {\n        HierarchySideDataOpsReal<NDIM, double> hier_data_ops(d_hierarchy);\n        hier_data_ops.setToScalar(q_data_idx, 0.0);\n    }\n\n    return;\n} // zeroOutEulerianData\n\nvoid\nIBInterpolantMethod::copyEulerianDataToIntegrator(const std::string& var_name, int q_data_idx, double data_time)\n{\n    int q_hier_idx = -1;\n\n    Pointer<HierarchyIntegrator> hier_integrator = d_q_hier_integrator[var_name];\n    Pointer<Variable<NDIM> > var = d_q_var[var_name];\n\n    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n    if (IBTK::rel_equal_eps(data_time, d_current_time))\n    {\n        q_hier_idx = var_db->mapVariableAndContextToIndex(var, hier_integrator->getCurrentContext());\n    }\n    else if (IBTK::rel_equal_eps(data_time, d_new_time))\n    {\n        q_hier_idx = var_db->mapVariableAndContextToIndex(var, hier_integrator->getNewContext());\n    }\n    else\n    {\n        TBOX_ERROR(\n            \"IBInterpolantMethod::getEulerianDataForInterpolation() Interpolation not supported at times other than \"\n            \"current and new.\\n\");\n    }\n\n    // Copy integrator data into q_data_idx\n    Pointer<CellVariable<NDIM, double> > cc_var = var;\n    Pointer<SideVariable<NDIM, double> > sc_var = var;\n    if (cc_var)\n    {\n        HierarchyCellDataOpsReal<NDIM, double> hier_data_ops(d_hierarchy);\n        hier_data_ops.copyData(q_hier_idx, q_data_idx);\n    }\n\n    if (sc_var)\n    {\n        HierarchySideDataOpsReal<NDIM, double> hier_data_ops(d_hierarchy);\n        hier_data_ops.copyData(q_hier_idx, q_data_idx);\n    }\n\n    return;\n} // copyEulerianDataToIntegrator\n\nvoid\nIBInterpolantMethod::getQData(const std::string& var_name, std::vector<Pointer<LData> >** Q_data, double data_time)\n{\n    if (IBTK::rel_equal_eps(data_time, d_current_time))\n    {\n        *Q_data = &d_Q_current_data[var_name];\n    }\n    else if (IBTK::rel_equal_eps(data_time, d_new_time))\n    {\n        *Q_data = &d_Q_new_data[var_name];\n    }\n    else\n    {\n        TBOX_ERROR(\"IBInterpolantMethod::getQData() Q data inquired at times other than current and new.\\n\");\n    }\n    return;\n} // getQData\n\nvoid\nIBInterpolantMethod::computeCenterOfMass(EigenAlignedVector<Eigen::Vector3d>& center_of_mass,\n                                         std::vector<SAMRAI::tbox::Pointer<IBTK::LData> >& X_data)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Zero out the COM vector.\n    for (unsigned int struct_no = 0; struct_no < d_num_rigid_parts; ++struct_no)\n    {\n        center_of_mass[struct_no].setZero();\n    }\n\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n        const boost::multi_array_ref<double, 2>& X_data_array = *X_data[ln]->getLocalFormVecArray();\n        const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln);\n        const std::vector<LNode*>& local_nodes = mesh->getLocalNodes();\n\n        // Get structures on this level.\n        const std::vector<int> structIDs = d_l_data_manager->getLagrangianStructureIDs(ln);\n        const unsigned structs_on_this_ln = static_cast<unsigned>(structIDs.size());\n#if !defined(NDEBUG)\n        TBOX_ASSERT(structs_on_this_ln == d_num_rigid_parts);\n#endif\n\n        for (const auto& node_idx : local_nodes)\n        {\n            const int lag_idx = node_idx->getLagrangianIndex();\n            const int local_idx = node_idx->getLocalPETScIndex();\n            const double* const X = &X_data_array[local_idx][0];\n\n            int struct_handle = 0;\n            if (structs_on_this_ln > 1) struct_handle = getStructureHandle(lag_idx);\n\n            for (unsigned int d = 0; d < NDIM; ++d) center_of_mass[struct_handle][d] += X[d];\n        }\n\n        for (unsigned struct_no = 0; struct_no < structs_on_this_ln; ++struct_no)\n        {\n            IBTK_MPI::sumReduction(&center_of_mass[struct_no][0], NDIM);\n            const int total_nodes = getNumberOfNodes(struct_no);\n            center_of_mass[struct_no] /= total_nodes;\n        }\n\n        X_data[ln]->restoreArrays();\n    }\n    return;\n} // computeCenterOfMass\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\nIBInterpolantMethod::getFromInput(Pointer<Database> db, bool is_from_restart)\n{\n    if (!is_from_restart)\n    {\n        if (db->isString(\"interp_kernel_fcn\") && db->isString(\"spread_kernel_fcn\"))\n        {\n            d_interp_kernel_fcn = db->getString(\"interp_kernel_fcn\");\n            d_spread_kernel_fcn = db->getString(\"spread_kernel_fcn\");\n        }\n        if (db->isString(\"interp_delta_fcn\") && db->isString(\"spread_delta_fcn\"))\n        {\n            d_interp_kernel_fcn = db->getString(\"interp_delta_fcn\");\n            d_spread_kernel_fcn = db->getString(\"spread_delta_fcn\");\n        }\n        else if (db->keyExists(\"delta_fcn\"))\n        {\n            d_interp_kernel_fcn = db->getString(\"delta_fcn\");\n            d_spread_kernel_fcn = db->getString(\"delta_fcn\");\n        }\n        else if (db->keyExists(\"kernel_fcn\"))\n        {\n            d_interp_kernel_fcn = db->getString(\"kernel_fcn\");\n            d_spread_kernel_fcn = db->getString(\"kernel_fcn\");\n        }\n        else if (db->keyExists(\"IB_delta_fcn\"))\n        {\n            d_interp_kernel_fcn = db->getString(\"IB_delta_fcn\");\n            d_spread_kernel_fcn = db->getString(\"IB_delta_fcn\");\n        }\n        else if (db->keyExists(\"IB_kernel_fcn\"))\n        {\n            d_interp_kernel_fcn = db->getString(\"IB_kernel_fcn\");\n            d_spread_kernel_fcn = db->getString(\"IB_kernel_fcn\");\n        }\n\n        if (db->isInteger(\"min_ghost_cell_width\"))\n        {\n            d_ghosts = db->getInteger(\"min_ghost_cell_width\");\n        }\n        else if (db->isDouble(\"min_ghost_cell_width\"))\n        {\n            d_ghosts = static_cast<int>(std::ceil(db->getDouble(\"min_ghost_cell_width\")));\n        }\n    }\n    TBOX_ASSERT(LEInteractor::isKnownKernel(d_interp_kernel_fcn));\n    TBOX_ASSERT(LEInteractor::isKnownKernel(d_spread_kernel_fcn));\n    if (db->keyExists(\"error_if_points_leave_domain\"))\n        d_error_if_points_leave_domain = db->getBool(\"error_if_points_leave_domain\");\n    if (db->keyExists(\"do_log\"))\n        d_do_log = db->getBool(\"do_log\");\n    else if (db->keyExists(\"enable_logging\"))\n        d_do_log = db->getBool(\"enable_logging\");\n    return;\n} // getFromInput\n\nvoid\nIBInterpolantMethod::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(d_object_name << \":  Restart database corresponding to \" << d_object_name\n                                 << \" not found in restart file.\" << std::endl);\n    }\n    int ver = db->getInteger(\"IB_INTERPOLANT_METHOD_VERSION\");\n    if (ver != IB_INTERPOLANT_METHOD_VERSION)\n    {\n        TBOX_ERROR(d_object_name << \":  Restart file version different than class version.\" << std::endl);\n    }\n    if (db->keyExists(\"d_interp_kernel_fcn\"))\n        d_interp_kernel_fcn = db->getString(\"d_interp_kernel_fcn\");\n    else if (db->keyExists(\"d_interp_delta_fcn\"))\n        d_interp_kernel_fcn = db->getString(\"d_interp_delta_fcn\");\n    if (db->keyExists(\"d_spread_kernel_fcn\"))\n        d_spread_kernel_fcn = db->getString(\"d_spread_kernel_fcn\");\n    else if (db->keyExists(\"d_spread_delta_fcn\"))\n        d_spread_kernel_fcn = db->getString(\"d_spread_delta_fcn\");\n    TBOX_ASSERT(LEInteractor::isKnownKernel(d_interp_kernel_fcn));\n    TBOX_ASSERT(LEInteractor::isKnownKernel(d_spread_kernel_fcn));\n    db->getIntegerArray(\"d_ghosts\", d_ghosts, NDIM);\n\n    for (unsigned int struct_no = 0; struct_no < d_num_rigid_parts; ++struct_no)\n    {\n        std::ostringstream C, Q;\n        C << \"C_\" << struct_no;\n        Q << \"Q_\" << struct_no;\n\n        double Q_coeffs[4];\n        db->getDoubleArray(C.str(), &d_center_of_mass_current[struct_no][0], 3);\n        db->getDoubleArray(Q.str(), &Q_coeffs[0], 4);\n\n        d_quaternion_current[struct_no].w() = Q_coeffs[0];\n        d_quaternion_current[struct_no].x() = Q_coeffs[1];\n        d_quaternion_current[struct_no].y() = Q_coeffs[2];\n        d_quaternion_current[struct_no].z() = Q_coeffs[3];\n        d_quaternion_current[struct_no].normalized();\n    }\n\n    return;\n} // getFromRestart\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n} // namespace IBAMR\n\n//////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "5908de1bd8c96a1cb6442f44e8342d0d1eab2f10", "size": 38759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IB/IBInterpolantMethod.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "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/IB/IBInterpolantMethod.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T17:54:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-30T17:54:49.000Z", "max_forks_repo_path": "src/IB/IBInterpolantMethod.cpp", "max_forks_repo_name": "akashdhruv/IBAMR", "max_forks_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T03:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T03:40:20.000Z", "avg_line_length": 35.428702011, "max_line_length": 119, "alphanum_fraction": 0.6480043345, "num_tokens": 9650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.06278920684328233, "lm_q1q2_score": 0.027974446130391135}}
{"text": "/*=============================================================================\n    Copyright (c) 2001-2007 Joel de Guzman\n    Copyright (c) 2001-2009 Hartmut Kaiser\n\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n///////////////////////////////////////////////////////////////////////////////\n//\n//  A calculator example demonstrating the grammar and semantic actions\n//  using phoenix to do the actual expression evaluation. The parser is\n//  essentially an \"interpreter\" that evaluates expressions on the fly.\n//\n//  Additionally this examples shows how to build and use a lexer based on \n//  Ben Hansons Lexertl (http://www.benhanson.net/lexertl.html). This way the\n//  parser matches the grammar against the tokens generated by the lexer \n//  component and not against the input character stream.\n//\n//  Even if the benefits of using a lexer for this small calculator grammar may \n//  not outweight the corresponding overhead, we provide this example because \n//  it allows to concentrate on the essentials without having to understand\n//  the semantics first.\n//\n//  [ JDG June 29, 2002 ]   spirit1\n//  [ JDG March 5, 2007 ]   spirit2\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/lex_lexer_lexertl.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n\n#include <iostream>\n#include <string>\n\nusing namespace boost::spirit;\nusing namespace boost::spirit::qi;\nusing namespace boost::spirit::lex;\nusing namespace boost::spirit::ascii;\nusing namespace boost::spirit::arg_names;\n\n///////////////////////////////////////////////////////////////////////////////\n//  Our token definition\n//  This class is used to define all the tokens to be recognized by the lexer. \n///////////////////////////////////////////////////////////////////////////////\ntemplate <typename Lexer>\nstruct calculator_tokens : lexer_def<Lexer>\n{\n    template <typename Self>\n    void def (Self& self)\n    {\n        // unsigned integer token definition\n        ui = \"[1-9][0-9]*\";\n        \n        // whitespace token definitions\n        ws = \"[ \\\\t\\\\f\\\\v]+\";\n        c_comment = \"\\\\/\\\\*[^*]*\\\\*+([^/*][^*]*\\\\*+)*\\\\/\";\n        \n        // build token set\n        skipper = ws | c_comment;                   // += is allowed as well\n        \n        // associate the tokens and the token set with the lexer\n        // default lexer state\n        self = token_def<>('+') | '-' | '*' | '/' | '(' | ')'; \n        self += ui;                                 // still default state\n        \n        // The token_set 'skipper' get's assigned to a separate lexer state\n        // which allows to use it separately from the main tokenization\n        // (it is used as the skipper parser below)\n        self(\"SKIPPER\") = skipper;                  // lexer state \"SKIPPER\"\n    }\n\n    // This are the tokens to be recognized by the lexer.\n    token_def<unsigned int> ui;   // matched tokens will have a unsigned int \n    token_def<> ws, c_comment;    // attribute will not be used\n\n    // This is the only token set explicitly defined by this lexer because it\n    // needs to be accessible from the outside (used as skip parser below).\n    typename Lexer::token_set skipper;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n//  Our calculator grammar\n//\n//  The difference to the original example (calc3.cpp) is that we are \n//  specifying a second template parameter referring to the lexer. Further, we \n//  use a defined tokenset from above as the skip parser.\n///////////////////////////////////////////////////////////////////////////////\ntemplate <typename Iterator, typename Lexer>\nstruct calculator : grammar<Iterator, int(), typename Lexer::token_set>\n{\n    template <typename TokenDef>\n    calculator(TokenDef const& tok) \n      : calculator::base_type(expression)\n    {\n        // grammar\n        expression =\n            term                            [_val = _1]\n            >> *(   ('+' >> term            [_val += _1])\n                |   ('-' >> term            [_val -= _1])\n                )\n            ;\n\n        term =\n            factor                          [_val = _1]\n            >> *(   ('*' >> factor          [_val *= _1])\n                |   ('/' >> factor          [_val /= _1])\n                )\n            ;\n\n        factor =\n            tok.ui                          [_val = _1]\n            |   '(' >> expression           [_val = _1] >> ')'\n            |   ('-' >> factor              [_val = -_1])\n            |   ('+' >> factor              [_val = _1])\n            ;\n    }\n\n    rule<Iterator, int(), typename Lexer::token_set> expression, term, factor;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n//  Main program\n///////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"Expression parser...\\n\\n\";\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\n\n    // iterator type used to expose the underlying input stream\n    typedef std::string::const_iterator base_iterator_type;\n    \n    // This is the lexer token type to use. The second template parameter lists \n    // all attribute types used for token_def's during token definition (see \n    // calculator_tokens<> above). Here we use the predefined lexertl token \n    // type, but any compatible token type may be used.\n    typedef lexertl_token<\n        base_iterator_type, boost::mpl::vector<unsigned int> \n    > token_type;\n    \n    // This is the lexer type to use to tokenize the input.\n    // Here we use the lexertl based lexer engine.\n    typedef lexertl_lexer<token_type> lexer_type;\n    \n    // This is the token definition type (derived from the given lexer type).\n    typedef calculator_tokens<lexer_type> calculator_tokens;\n    \n    // this is the iterator type exposed by the lexer \n    typedef lexer<calculator_tokens>::iterator_type iterator_type;\n\n    // this is the type of the grammar to parse\n    typedef calculator<iterator_type, lexer_type> calculator;\n\n    // now we use the types defined above to create the lexer and grammar\n    // object instances needed to invoke the parsing process\n    calculator_tokens tokens;                       // Our token definition\n    calculator calc(tokens);                        // Our grammar definition\n\n    lexer<calculator_tokens> lex(tokens);           // Our lexer\n\n    // get input line by line and feed the parser to evaluate the expressions\n    // read in from the input\n    std::string str;\n    int result;\n    while (std::getline(std::cin, str))\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        // At this point we generate the iterator pair used to expose the\n        // tokenized input stream.\n        iterator_type iter = lex.begin(str.begin(), str.end());\n        iterator_type end = lex.end();\n        \n        // Parsing is done based on the the token stream, not the character \n        // stream read from the input.\n        // Note, how we use the token_set defined above as the skip parser.\n        bool r = phrase_parse(iter, end, calc, result, tokens.skipper);\n\n        if (r && iter == end)\n        {\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing succeeded\\n\";\n            std::cout << \"result = \" << result << std::endl;\n            std::cout << \"-------------------------\\n\";\n        }\n        else\n        {\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing failed\\n\";\n            std::cout << \"-------------------------\\n\";\n        }\n    }\n\n    std::cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "2f9548375a274861048177276a9fcf72fe3a0ff7", "size": 8115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/spirit/example/qi/calc3_lexer.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T17:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T17:17:41.000Z", "max_issues_repo_path": "libs/spirit/example/qi/calc3_lexer.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/spirit/example/qi/calc3_lexer.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-07T05:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-07T05:20:43.000Z", "avg_line_length": 39.7794117647, "max_line_length": 81, "alphanum_fraction": 0.5182994455, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.06853748637294865, "lm_q1q2_score": 0.027917606368686267}}
{"text": "#include \"domain/mesh/mesh_cartesian.hpp\"\n\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\n#include <deal.II/base/point.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/base/tensor.h>\n#include <deal.II/base/utilities.h>\n\n#include \"domain/mesh/factory.hpp\"\n#include \"problem/parameter_types.hpp\"\n\nnamespace bart::domain::mesh {\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max, const std::vector<int> n_cells,\n                                  const std::string material_mapping)\n    : MeshCartesian(spatial_max, n_cells) {\n  ParseMaterialMap(material_mapping);\n}\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max, const std::vector<int> n_cells) {\n  const std::string error_string{\"MeshCartesian constructor error: \"};\n  // Check lengths of spatial max and n_cells\n  AssertThrow(spatial_max.size() == dim, dealii::ExcMessage(error_string + \"incorrect spatial vector size\"))\n  AssertThrow(n_cells.size() == dim, dealii::ExcMessage(error_string + \"incorrect number of cells vector size\"))\n  AssertThrow(std::all_of(spatial_max.cbegin(), spatial_max.cend(), [](const double val){ return val != 0; }),\n              dealii::ExcMessage(error_string + \"spatial max has 0 entry.\"))\n  AssertThrow(std::all_of(n_cells.cbegin(), n_cells.cend(), [](const int val){ return val > 0; }),\n              dealii::ExcMessage(error_string + \"n_cells values must be >= 0\"))\n  \n  std::copy(n_cells.begin(), n_cells.end(), n_cells_.begin());\n  std::copy(spatial_max.begin(), spatial_max.end(), spatial_max_.begin());\n  std::string description = \"deal.II Cartesian Mesh, \"+ std::to_string(dim) + \"D, Size: {\";\n\n  auto int_comma_fold = [](std::string a, int b) { return std::move(a) + \", \" + std::to_string(b); };\n  auto double_comma_fold = [](std::string a, double b) { return std::move(a) + \", \" + std::to_string(b); };\n\n  std::string size_string = std::accumulate(std::next(spatial_max.begin()), spatial_max.end(),\n                                            std::to_string(spatial_max.at(0)), double_comma_fold);\n  std::string n_cells_string = std::accumulate(std::next(n_cells.begin()), n_cells.end(),\n                                               std::to_string(n_cells.at(0)), int_comma_fold);\n  description += size_string + \"}, N_cells: {\" + n_cells_string + \"}\";\n  this->set_description(description, utility::DefaultImplementation(true));\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillTriangulation(dealii::Triangulation<dim> &to_fill) {\n  dealii::Point<dim> diagonal;\n  dealii::Point<dim> origin;\n\n  for (int i = 0; i < dim; ++i)\n    diagonal[i] = spatial_max_[i];\n\n  std::vector<unsigned int> number_of_cells{n_cells_.begin(), n_cells_.end()};\n  dealii::GridGenerator::subdivided_hyper_rectangle(to_fill, number_of_cells, origin, diagonal);\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::ParseMaterialMap(std::string material_mapping) {\n  using dealii::Utilities::split_string_list;\n  using dealii::Utilities::string_to_int;\n  using StringVector = std::vector<std::string>;\n\n  StringVector z_blocks = split_string_list(material_mapping, \"\\n\\n\");\n\n  std::reverse(z_blocks.begin(), z_blocks.end());\n\n  for (unsigned k = 0; k < z_blocks.size(); ++k) {\n    StringVector y_line = split_string_list(z_blocks.at(k), \"\\n\");\n    std::reverse(y_line.begin(), y_line.end());\n    for (unsigned j = 0; j < y_line.size(); ++j) {\n      StringVector x_positions = split_string_list(y_line.at(j), \" \");\n      for (unsigned i = 0; i < x_positions.size(); ++i) {\n        std::array<unsigned, 3> index{i, j, k};\n        std::array<int, dim> location;\n        for (int dir = 0; dir < dim; ++dir)\n          location.at(dir) = index.at(dir);\n        material_mapping_[location] = string_to_int(x_positions.at(i));\n      }\n      n_material_cells_.at(0) = x_positions.size();\n    }\n    if (dim > 1)\n      n_material_cells_.at(1) = y_line.size();\n  }\n\n  if (dim > 2)\n    n_material_cells_.at(2) = z_blocks.size();\n}\n\ntemplate <int dim>  \nvoid MeshCartesian<dim>::FillMaterialID(dealii::Triangulation<dim> &to_fill) {\n  for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n    if (cell->is_locally_owned()) {\n      int material_id = GetMaterialID(cell->center());\n      cell->set_material_id(material_id);\n    }\n  }\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillBoundaryID(dealii::Triangulation<dim> &to_fill) {\n  using Boundary = bart::problem::Boundary;\n  int faces_per_cell = dealii::GeometryInfo<dim>::faces_per_cell;\n  double zero_tol = 1.0e-14;\n  \n  for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n    if (cell->is_locally_owned() && cell->at_boundary()) {\n      for (int face_id = 0; face_id < faces_per_cell; ++face_id) {\n        auto face = cell->face(face_id);\n        if (face->at_boundary()) {\n          dealii::Point<dim> face_center = face->center();\n          switch (dim) {\n            case 3: {\n              if (std::fabs(face_center[2]) < zero_tol) {\n                face->set_boundary_id(static_cast<int>(Boundary::kZMin));\n                break;\n              } else if (std::fabs(face_center[2] - spatial_max_.at(2)) < zero_tol) {\n                face->set_boundary_id(static_cast<int>(Boundary::kZMax));\n                break;\n              }\n              [[fallthrough]];\n            }\n            case 2: {\n              if (std::fabs(face_center[1]) < zero_tol) {\n                face->set_boundary_id(static_cast<int>(Boundary::kYMin));\n                break;\n              } else if (std::fabs(face_center[1] - spatial_max_[1]) < zero_tol) {\n                face->set_boundary_id(static_cast<int>(Boundary::kYMax));\n                break;\n              }\n              [[fallthrough]];\n            }\n              // Fall through to check x-direction\n            case 1: {\n              if (std::fabs(face_center[0]) < zero_tol) {\n                face->set_boundary_id(static_cast<int>(Boundary::kXMin));\n                break;\n              } else if (std::fabs(face_center[0] - spatial_max_[0]) < zero_tol) {\n                face->set_boundary_id(static_cast<int>(Boundary::kXMax));\n                break;\n              }\n              [[fallthrough]];\n            }\n            default: {\n              AssertThrow(false,\n                          dealii::ExcMessage(\"The location of a boundary could \"\n                                             \"not be determined.\"))\n            }\n          }\n        }\n      }\n    }\n  }\n}\n  \n\ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(dealii::Point<dim> location) {\n  std::array<double, dim> array_location;\n  for (int i = 0; i < dim; ++i)\n    array_location[i] = location[i];\n  return GetMaterialID(array_location);\n}\n  \ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(std::array<double, dim> location) {\n  std::array<int, dim> relative_location;\n\n  for (int i = 0; i < dim; ++i) {\n    double cell_size = spatial_max_.at(i)/n_material_cells_.at(i);\n    double cell_location = location.at(i) / cell_size;\n    int cell_index = std::floor(cell_location);\n\n    if (static_cast<double>(cell_index) == cell_location && cell_index != 0) {\n      relative_location.at(i) = cell_index - 1;\n    } else {\n      relative_location.at(i) = cell_index;\n    }\n  }\n  \n  return material_mapping_[relative_location];\n}\n\ntemplate <int dim>\nbool MeshCartesian<dim>::is_registered_ =\n    MeshIFactory<dim, const std::vector<double>, const std::vector<int>, const std::string>::get()\n    .RegisterConstructor(\n        MeshName::kCartesian,\n        [] (const std::vector<double> spatial_max,\n            const std::vector<int> n_cells,\n            const std::string material_mapping) {\n          std::unique_ptr<MeshI<dim>> return_ptr =\n              std::make_unique<MeshCartesian<dim>>(spatial_max, n_cells, material_mapping);\n          return return_ptr; }\n    );\n\ntemplate class MeshCartesian<1>;\ntemplate class MeshCartesian<2>;\ntemplate class MeshCartesian<3>;\n\n} // } // namespace bart::domain::mesh\n\n", "meta": {"hexsha": "d3277c8c88228b6eb660e6e952aa880974cb1e8c", "size": 8003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/domain/mesh/mesh_cartesian.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/domain/mesh/mesh_cartesian.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/domain/mesh/mesh_cartesian.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 38.6618357488, "max_line_length": 112, "alphanum_fraction": 0.6223916031, "num_tokens": 2003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05582313956382588, "lm_q1q2_score": 0.02791156978191294}}
{"text": "// -*- C++ -*-\n\n// The MIT License (MIT)\n//\n// Copyright (c) 2021 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#include <boost/program_options.hpp>\n#include \"PoissonProblem.hpp\"\n\nstruct program_options\n{\n    bool verbose                    = {false};\n    size_t M                        = {32};    // grid size along `x` direction\n    size_t N                        = {32};    // grid size along `y` direction\n    double x_min                    = {-1.0};  // minimum `x` value\n    double x_max                    = { 1.0};  // maximum `x` value\n    double y_min                    = {-1.0};  // minimum `y` value\n    double y_max                    = { 1.0};  // maximum `y` value\n    std::string asy_name            = {\"\"};    // dump streamlines to vector `.asy` file if name is given\n};\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            (\"M\",                      po::value<size_t>(),      \"`M`     -- grid size along `x` direction\")\n            (\"N\",                      po::value<size_t>(),      \"`N`     -- grid size along `y` direction\")\n            (\"x_min\",                  po::value<double>(),      \"`x_min` -- minimum `x` value\")\n            (\"x_max\",                  po::value<double>(),      \"`x_max` -- maximum `x` value\")\n            (\"y_min\",                  po::value<double>(),      \"`y_min` -- minimum `y` value\")\n            (\"y_max\",                  po::value<double>(),      \"`y_max` -- maximum `y` value\")\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\n        if (vm.count(\"help\")) {\n            std::cout << desc << std::endl;\n            std::exit(0);\n        }\n\n        popt.verbose = vm.count(\"verbose\");\n\n        if (vm.count(\"M\")) {\n            popt.M = vm[\"M\"].as<size_t>();\n        }\n\n        if (vm.count(\"N\")) {\n            popt.N = vm[\"N\"].as<size_t>();\n        }\n\n        if (vm.count(\"x_min\")) {\n            popt.x_min = vm[\"x_min\"].as<double>();\n        }\n\n        if (vm.count(\"x_max\")) {\n            popt.x_max = vm[\"x_max\"].as<double>();\n        }\n\n        if (vm.count(\"y_min\")) {\n            popt.y_min = vm[\"y_min\"].as<double>();\n        }\n\n        if (vm.count(\"y_max\")) {\n            popt.y_max = vm[\"y_max\"].as<double>();\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\nint main(int argc, char **argv)\n{\n    program_options po = parse_command_line(argc, argv);\n\n    if (po.verbose) {\n        std::cout << \"problem parameters: M: \" << po.M << \" N: \" << po.N\n                  << \" x_min: \" << po.x_min << \" x_max: \" << po.x_max\n                  << \" y_min: \" << po.y_min << \" y_max: \" << po.y_max\n                  << std::endl;\n    }\n\n    PoissonProblem problem(po.M, po.N, po.x_min, po.x_max, po.y_min, po.y_max, po.verbose);\n\n    problem.solve();\n\n    problem.compute_residual();\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "81d8dacf9bd3b20b1f202d279b544c82d8c2d5ce", "size": 4461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chebyshev_pseudospectral/src/main.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": "chebyshev_pseudospectral/src/main.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": "chebyshev_pseudospectral/src/main.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": 36.5655737705, "max_line_length": 124, "alphanum_fraction": 0.5303743555, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.0618759813987784, "lm_q1q2_score": 0.02780661029088949}}
{"text": "/***\n第三节 完美转发\n（1）完美转发的概念和步骤演绎\na)直接调用：  funcLast();\nb)转发： 通过funcMiddle()间接调用funcLast。funcMiddle相当于一个跳板函数。如果有参数，那么参数也需要通过funcMiddle中转传递给funcLast()\nc)完美转发：const,左值，右值。实参的属性完全不丢失，原原本本的通过funcMiddle转发给funcLast，这种转发就是完美转发。\n万能引用：实参的所有信息都会传递到万能引用当中去从而让编译器推导出来函数模板最终的形参类型 (引用折叠)。\n完美转发：就是让程序员可以书写接受任意实参的函数模板（funcMiddle_Temp），并将其转发到目标函数（funcLast2)，目标函数会接收到与\n转发函数（funcMiddle_Temp）所接收的完全相同（当然包括类型相同比如保持参数的左值、右值特性）的参数。\n要实现完美转发，就要用到std::forward了。\n\n（2）std::forward ：C++11中专门为转发而存在的函数。这个函数要么返回一个左值，要么返回一个右值。\n万能引用类型才是forward能够发挥作用的重要条件。\n理解：\n(a)实参原来是个左值j，到了形参中还是左值t2。forward能够转化回原来该实参的左值或者右值性。所以，forward之后还是个左值。\n(b)实参原来是个右值20，到了形参中变成了左值t1。forward能够转化回原来该实参的左值或者右值性。所以，forward之后还是个右值。\nforward这个函数有强制把左值转换成右值的能力。所以：forward这个函数只对原来是个右值这种情况有用。\nforward的能力：保持原始实参的左值性或者右值性\n总结：完美转发：比较好的解决了参数转发的问题。\n\n（3）普通参数的完美转发:auto &&\n***/\n\n#include <iostream>\n\n//#include <boost/type_index.hpp>\nusing namespace std;\n//#pragma warning(disable : 4996) \n\n\n//函数模板\n//template <typename T>\n//void myfunc(T  tmprv)\n//{\n//\tcout << \"--------------------------------begin----------------\" << endl;\n//\tusing boost::typeindex::type_id_with_cvr;\n//\tcout << \"T=\" << type_id_with_cvr<T>().pretty_name() << endl; //显示T的类型\n//\tcout << \"tmprv=\" << type_id_with_cvr<decltype(tmprv)>().pretty_name() << endl; //显示tmprv的类型\n//\tcout << \"--------------------------------end------------------\" << endl;\n//}\n\nnamespace _nmsp1\n{\n\t//void funcLast(int v1, int v2)\n\tvoid funcLast(int v1, int& v2)\n\t{\n\t\t++v2; //改变v2的值，让其自增1\n\t\tcout << v1 + v2 << endl;\n\t}\n\n\tvoid funcLast2(int&& v1, int& v2)\n\t{\n\t\tcout << v1 << endl;\n\t\tcout << v2 << endl;\n\t}\n\n\t//函数模板（跳板函数）：把收到的参数以及这些参数相对应的类型不变的转发给其他函数（完美转发）\n\ttemplate<typename F, typename T1,typename T2>\n\t//void funcMiddle_Temp(F f, T1 t1, T2 t2) //f:函数指针类型void(*)(int,int)，而funcLast是函数类型void(int,int)\n\tvoid funcMiddle_Temp(F f, T1&& t1, T2&& t2)\n\t{\n\t\t//f(t1, t2);\n\t\tf(\n\t\t\tstd::forward<T1>(t1), //T1 = int\n\t\t\tstd::forward<T2>(t2)  //T2 = int &\n\t\t);\n\t}\n\n}\nnamespace _nmsp2\n{\n\tvoid printInfo(int& t)\n\t{\n\t\tcout << \"printInfo()参数类型为左值引用\" << endl;\n\t}\n\n\tvoid printInfo(int&& t)\n\t{\n\t\tcout << \"printInfo()参数类型为右值引用\" << endl;\n\t}\n\n\tvoid printInfo(const int& t)\n\t{\n\t\tcout << \"printInfo()参数类型为const 左值引用\" << endl;\n\t}\n\n\ttemplate <typename T>\n\tvoid TestF(T&& t)\n\t{\n\t\tprintInfo(std::forward<T>(t));\n\t}\n\n}\nnamespace _nmsp3\n{\n\tint getData()\n\t{\n\t\treturn 3;\n\t}\n\tvoid funcLast3(int v1)\n\t{\n\t\tcout << \"v1=\" << v1 << endl;\n\t}\n\n\tvoid funcMiddle_Temp2()\n\t{\n\t\tauto&& result = getData(); //getData返回的是右值，所以auto = int ,result = int &&（右值引用） \n\t\t//....对result做各种运算。\n\t\tfuncLast3(\n\t\t\tstd::forward<decltype(result)>(result)\n\t\t);\n\t}\n\n}\n\nint main()\n{ \n\n\n\n\t/*int i = 50;\n\t_nmsp1::funcLast(41, i); //92*/\n\n\t/*\n\tint j = 70;\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast, 20, j); //91\n\t*/\n\n\t/*\n\tint i = 50;\n\t_nmsp1::funcLast(41, i); //直接调用，92,执行完i=51         \n\t*/\n\n\t/*\n\tint j = 70;\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast, 20, j); //91,执行完本函数，j = 71？70呢？ = 70\n\t                                                   //当前情况下j被funcMiddle_Temp推断成了int而不是int&\n\t                                                    //void funcMiddle_Temp(void(*f)(int,int &),int t1,int t2){...}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n\n\t/*\n\tint j = 70;\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast, 20, j);  //91,T1=int, t1 = int &&，      T2 = int & , t2 = int &\n\t\t                                                  //j = 71;\n\n\t\n\t/*\n\tint j = 70;\n\t//_nmsp1::funcLast2(20, j); //20,70\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast2, 20, j);\n\t                                                 //20->t1(int &&)，但是t1本身是左值。\n\t\t\t\t\t\t\t\t\t\t\t\t\t */\n\t/*int&& abc = 1;\n\tabc = 15;*/\n\n\t/*\n\t_nmsp2::TestF(1); //printInfo()参数类型为右值引用\n\tint i = 5;\n\t_nmsp2::TestF(i);  //printInfo()参数类型为左值引用\n\t_nmsp2::TestF(std::move(i)); //printInfo()参数类型为右值引用     ----std::move能够将左值转换成右值。\n\tconst int j = 8;\n\t_nmsp2::TestF(j); //printInfo()参数类型为const 左值引用   ------j是个const左值\n\t_nmsp2::TestF(int(12)); //printInfo()参数类型为右值引用 ----int(12)是个临时对象，是个右值。\n\tint&& tempvalue = 16;\n\t_nmsp2::TestF(tempvalue);//printInfo()参数类型为左值引用\n\t*/\n\n\t//_nmsp3::funcLast3(_nmsp3::getData());\n\n\t_nmsp3::funcMiddle_Temp2();\n\n\n\n\n\n\n\n\n\t\n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "cc936654aa756cf5d2a8faeb3ef6ca7f60a2ed4b", "size": 4039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/3/305.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/3/305.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/3/305.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 21.9510869565, "max_line_length": 115, "alphanum_fraction": 0.6041099282, "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934189686402, "lm_q2_score": 0.11596072283669215, "lm_q1q2_score": 0.027755122696846917}}
{"text": "/***************************************************************************\n * Copyright (C) 2012, Naomasa Matsubayashi\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 * 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 ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT 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 OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n ***************************************************************************/\n\n#ifndef HERMIT_MPINT_HPP\n#define HERMIT_MPINT_HPP\n\n#include <boost/cstdint.hpp>\n#include <stdexcept>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/mpl/less_equal.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <tommath.h>\n\n\n#define MPINT_SAFE_CALL( expr ) \\\n{ \\\n  int mp_op_result = expr; \\\n  if( mp_op_result != MP_OKAY ) \\\n  throw std::runtime_error( mp_error_to_string( mp_op_result ) ); \\\n}\n\nnamespace hermit {\n  boost::optional< std::string > is_hex( const std::string &temp );\n  boost::optional< std::string > is_dec( const std::string temp );\n  boost::optional< std::string > is_oct( const std::string temp );\n\n  class mpint {\n    public:\n      mpint() {\n        MPINT_SAFE_CALL( mp_init( &value ) );\n        mp_zero( &value );\n      }\n      mpint( const mpint &src_ ) {\n        MPINT_SAFE_CALL( mp_init_copy( &value, const_cast< mp_int* >( &src_.value ) ) );\n      }\n      mpint &operator=( const mpint &src_ ) {\n        MPINT_SAFE_CALL( mp_init_copy( &value, const_cast< mp_int* >( &src_.value ) ) );\n        return *this;\n      }\n      template< typename T >\n        mpint( T value_,\n            typename boost::enable_if<\n            typename boost::is_integral<\n            typename boost::remove_cv< T >::type\n            >::type\n            >::type* = NULL\n            ) {\n          MPINT_SAFE_CALL( mp_init( &value ) );\n          mp_zero( &value );\n          from_string( boost::lexical_cast< std::string >( value_ ), 10 );\n        }\n      mpint( const std::string &value_ );\n      ~mpint() {\n        mp_clear( &value );\n      }\n      void swap( mpint &target ) {\n        mp_exch( &value, &target.value );\n      }\n      void shrink_to_fit() {\n        MPINT_SAFE_CALL( mp_shrink( &value ) );\n      }\n      void reserve( int size_ ) {\n        MPINT_SAFE_CALL( mp_grow( &value, size_ ) );\n      }\n      void clear() {\n        mp_zero( &value );\n      }\n      int size() const {\n        return mp_count_bits( const_cast< mp_int* >( &value ) );\n      }\n      operator uint64_t() const {\n        static const mpint mask( \"0xFFFFFFFFFFFFFFFF\" );\n        return boost::lexical_cast< uint64_t >( *this & mask );\n      }\n      operator int64_t() const {\n        static const mpint mask( \"0x7FFFFFFFFFFFFFFF\" );\n        return boost::lexical_cast< int64_t >( *this & mask );\n      }\n      operator uint32_t() const {\n        static const mpint mask( \"0xFFFFFFFF\" );\n        return boost::lexical_cast< uint32_t >( *this & mask );\n      }\n      operator int32_t() const {\n        static const mpint mask( \"0x7FFFFFFF\" );\n        return boost::lexical_cast< int32_t >( *this & mask );\n      }\n      operator uint16_t() const {\n        static const mpint mask( \"0xFFFF\" );\n        return boost::lexical_cast< uint16_t >( *this & mask );\n      }\n      operator int16_t() const {\n        static const mpint mask( \"0x7FFF\" );\n        return boost::lexical_cast< int16_t >( *this & mask );\n      }\n      operator uint8_t() const {\n        static const mpint mask( \"0xFF\" );\n        return boost::lexical_cast< uint8_t >( *this & mask );\n      }\n      operator int8_t() const {\n        static const mpint mask( \"0x7F\" );\n        return boost::lexical_cast< int8_t >( *this & mask );\n      }\n      mpint &operator>>=( int right ) {\n        *this = *this >> right;\n        return *this;\n      }\n      mpint &operator<<=( int right ) {\n        *this = *this << right;\n        return *this;\n      }\n      mpint operator>>( int right ) const {\n        mpint result;\n        mpint remainder;\n        MPINT_SAFE_CALL( mp_div_2d( const_cast< mp_int* >( &value ), right, &result.value, &remainder.value ) ) \n          return result;\n      }\n      mpint operator<<( int right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_mul_2d( const_cast< mp_int* >( &value ), right, &result.value ) ) \n          return result;\n      }\n      mpint operator^( const mpint &right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_xor( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value ) );\n        return result;\n      }\n      mpint &operator^=( const mpint &right ) {\n        *this = *this ^ right;\n        return *this;\n      }\n      mpint operator|( const mpint &right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_or( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value ) );\n        return result;\n      }\n      mpint &operator|=( const mpint &right ) {\n        *this = *this | right;\n        return *this;\n      }\n      mpint operator&( const mpint &right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_and( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value ) );\n        return result;\n      }\n      mpint &operator&=( const mpint &right ) {\n        *this = *this + right;\n        return *this;\n      }\n      mpint operator-() {\n        mpint result;\n        MPINT_SAFE_CALL( mp_neg( &result.value, &value ) );\n        return result;\n      }\n      mpint operator+( const mpint &right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_add( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value ) );\n        return result;\n      }\n      mpint &operator+=( const mpint &right ) {\n        *this = *this + right;\n        return *this;\n      }\n      mpint operator++() {\n        mpint temp = *this;\n        *this += static_cast<mpint>( 1ul );\n        return temp;\n      }\n      mpint &operator++( int ) {\n        *this += static_cast<mpint>( 1ul );\n        return *this;\n      }\n      mpint operator-( const mpint &right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_sub( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value ) );\n        return result;\n      }\n      mpint &operator-=( const mpint &right ) {\n        *this = *this - right;\n        return *this;\n      }\n      mpint operator--() {\n        mpint temp = *this;\n        *this -= static_cast<mpint>( 1ul );\n        return temp;\n      }\n      mpint &operator--( int ) {\n        *this -= static_cast<mpint>( 1ul );\n        return *this;\n      }\n      mpint operator*( const mpint &right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_mul( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value ) );\n        return result;\n      }\n      mpint &operator*=( const mpint &right ) {\n        *this = *this * right;\n        return *this;\n      }\n      mpint operator/( const mpint &right ) const {\n        mpint result;\n        mpint remainder;\n        MPINT_SAFE_CALL( mp_div( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value, &remainder.value ) );\n        return result;\n      }\n      mpint &operator/=( const mpint &right ) {\n        *this = *this / right;\n        return *this;\n      }\n      mpint operator%( const mpint &right ) const {\n        mpint result;\n        MPINT_SAFE_CALL( mp_mod( const_cast< mp_int* >( &value ), const_cast< mp_int* >( &right.value ), &result.value ) );\n        return result;\n      }\n      mpint &operator%=( const mpint &right ) {\n        *this = *this % right;\n        return *this;\n      }\n      std::string to_string( int radix ) const;\n      void from_string( const std::string &str, int radix ) {\n        MPINT_SAFE_CALL( mp_read_radix( const_cast< mp_int* >( &value ), str.c_str(), radix ) );\n      }\n\n      const mp_int &get_raw() const {\n        return value;\n      }\n    private:\n      mp_int value;\n  };\n\n  std::ostream &operator<<( std::ostream &stream, const mpint &mp_value );\n  std::istream &operator>>( std::istream &stream, mpint &mp_value );\n  mpint sqrt( const mpint &value );\n  void swap( mpint &left, mpint &right );\n\n}\n\n\n\n#endif\n\n", "meta": {"hexsha": "bfc2080f32f46c261aab718b3420194d7d710364", "size": 9307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hermit/mpint.hpp", "max_stars_repo_name": "Fadis/hermit", "max_stars_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T05:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-09T05:54:01.000Z", "max_issues_repo_path": "include/hermit/mpint.hpp", "max_issues_repo_name": "Fadis/hermit", "max_issues_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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/hermit/mpint.hpp", "max_forks_repo_name": "Fadis/hermit", "max_forks_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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.8576779026, "max_line_length": 141, "alphanum_fraction": 0.5802084453, "num_tokens": 2342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.05665242291888883, "lm_q1q2_score": 0.027662437414570598}}
{"text": "#pragma once\n//! c/c++ headers\n#include <list>\n#include <set>\n#include <unordered_map>\n#include <utility>\n//! dependency headers\n#include <armadillo>\n//! project headers\n\nnamespace correspondences {\nnamespace graph {\n//! useful type definitions\nusing vertex_t = size_t;  // vertices will be indexed by an unsigned integer\nusing vertices_t = std::set< vertex_t >;\nusing edge_t = std::pair< vertex_t, vertex_t >;\nusing edges_t = std::set< edge_t >;\nusing adjacency_t = std::set< size_t >;\nusing coloring_t = std::unordered_map< vertex_t, size_t >;\n\n//! exit code when constructed graph is invalid\nconstexpr inline int INVALID_GRAPH = 1;\n\n/**\n * @class UndirectedGraph\n *\n * @see https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)#Undirected_graph\n */\nclass UndirectedGraph {\n public:\n   /** UndirectedGraph::UndirectedGraph()\n    * @brief default undirected graph constructor\n    *\n    * @param[in]\n    * @return\n    *\n    * @note creates an empty graph\n    */\n   UndirectedGraph();\n\n   /**\n    * UndirectedGraph::UndirectedGraph(vertices_t const&, edges_t const&)\n    *\n    * @brief constructor that builds undirected graph from input\n    * vertices and edges\n    *\n    * @param[in] vertices_t const&, graph vertices\n    * @param[in] edges_t const&, graph edges\n    *\n    * @note the application will exit with error if graph is invalid\n    * @see UndirectedGraph::validate_graph() method\n    */\n   UndirectedGraph(vertices_t const & vertices, edges_t const & edges);\n\n   /**\n    * UndirectedGraph::UndirectedGraph(arma::mat const&, arma::mat const&,\n    *      double const&, double const &)\n    *\n    * @brief constructor that builds graph from source and target point clouds,\n    * as well as consistency thresholds\n    *\n    * @param[in] arma::mat const&, source point cloud\n    * @param[in] arma::mat const&, target point cloud\n    * @param[in] double const&, distance between correspondences threshold\n    * @param[in] double const&, pairwise distance threshold - reject pairwise\n    * consideration when points in a set are too close\n    *\n    * @note the application will exit with error if graph is invalid\n    * @see UndirectedGraph::validate_graph() method\n    */\n   UndirectedGraph(arma::mat const & source_pts, arma::mat const & target_pts,\n       double const & eps, double const & pw_thresh);\n\n   /** UndirectedGraph::~UndirectedGraph()\n    * @brief destructor for constrained objective function\n    *\n    * @param[in]\n    * @return\n    *\n    * @note nothing to do; resources are automatically deleted\n    */\n   ~UndirectedGraph();\n\n   /**\n    * UndirectedGraph::add_edge(edge_t)\n    *\n    * @brief add edge to graph\n    *\n    * @param[in] vertex_t, vertex to add\n    *\n    * @note adds vertex to graph if it doesn't already exist\n    */\n   void add_edge(edge_t e) noexcept;\n\n   /**\n    * UndirectedGraph::get_adjacency(vertex_t const&)\n    *\n    * @brief get adjacency set for a vertex in the graph\n    * @note the size of the adjacency set is the \"degree\" of the vertex\n    *\n    * @param[in] vertex_t, desired vertex to get adjacency of\n    * @return adjacency set of input vertex (or {}, if vertex is not in graph)\n    */\n   adjacency_t get_adjacency(vertex_t const & v) const noexcept {\n     if (adjacency_.find(v) != adjacency_.end()) {\n       return adjacency_.at(v);\n     }\n     // LCOV_EXCL_START\n     adjacency_t out = {};\n     return out;\n     // LCOV_EXCL_STOP\n   }\n\n   /**\n    * UndirectedGraph::get_vertex_degree(vertex_t const&)\n    *\n    * @brief get degree of vertex in the graph\n    *\n    * @param[in] vertex_t, desired vertex to get degree of\n    * @return degree of input vertex (or 0, if vertex is not in the graph)\n    */\n   size_t get_vertex_degree(vertex_t const & v) const noexcept {\n     return (vertices_.find(v) != vertices_.end()) ? get_adjacency(v).size() : 0;\n   }\n\n   /**\n    * UndirectedGraph::get_vertices()\n    *\n    * @return vertices of the graph\n    */\n   vertices_t get_vertices() const noexcept { return vertices_; }\n\n   /**\n    * UndirectedGraph::get_edges()\n    *\n    * @return edges of the graph\n    */\n   edges_t get_edges() const noexcept { return edges_; }\n\n private:\n   /**\n    * UndirectedGraph::validate_graph()\n    *\n    * @brief validate graph based on vertices and edges declared\n    *\n    * @note a graph is valid if, for every edge, the following are true\n    *  (1) the first vertex is in the set of vertices\n    *  (2) the second vertex is in the set of vertices\n    *  (3) the first and second vertex indices are unique\n    * @return true, if all 3 conditions are met, false otherwise\n    */\n   bool validate_graph() const noexcept;\n\n   /**\n    * UndirectedGraph::add_vertex(vertex_t)\n    *\n    * @brief add vertex to graph\n    *\n    * @param[in] vertex_t, vertex to add\n    */\n   void add_vertex(vertex_t v) noexcept;\n\n   /**\n    * UndirectedGraph::add_adjacency(edge_t)\n    *\n    * @brief add to adjacency sets for vertices in an edge\n    *\n    * @param[in] edge_t, edge to incorporate in adjacency sets\n    */\n   void add_adjacency(edge_t e) noexcept;\n\n   std::unordered_map<vertex_t, adjacency_t> adjacency_;  // NOLINT [linelength] key-value store for vertex and its adjacency set\n   vertices_t vertices_;  // set of graph vertices\n   edges_t edges_;  // set of graph edges\n};\n\n/**\n * next_available_color(std::list<size_t> const&)\n *\n * @brief return next available color based on adjacency coloring\n * @see Section 3.2 of https://arxiv.org/pdf/1902.01534.pdf\n *\n * @param[in] std::list<size_t>, list of accounted for colors\n * @return size_t, smallest unsigned integer not in input list\n */\nsize_t next_available_color(std::list<size_t> const & colors) noexcept;\n\n/**\n * greedy_vertices_coloring(vertices_t const&, UndirectedGraph const&)\n *\n * @brief create greedy coloring of vertices, based on degree of vertex\n * @see Section 3.2 of https://arxiv.org/pdf/1902.01534.pdf\n *\n * @param vertices_t, set of vertices to color\n * @param UndirectedGraph, graph containing vertices to color\n * @return size_t, smallest unsigned integer not in input list\n */\ncoloring_t greedy_vertices_coloring(vertices_t const & vertices,\n    UndirectedGraph const & graph) noexcept;\n\n/**\n * @enum class max_clique_algo_e\n *\n * @brief available algorithms for finding maximum clique\n */\nenum class max_clique_algo_e {\n  bnb_basic = 0,\n  bnb_color = 1\n};\n\n/**\n * max_cliq_bnb_basic(UndirectedGraph const&, vertices_t const&,\n *     vertices_t&, vertices_t&)\n *\n * @brief find maximum clique using a recursive basic branch-and-bound (bnb)\n * algorithm\n * @see Section 3.1 of https://arxiv.org/pdf/1902.01534.pdf\n *\n * @param[in] UndirectedGraph, graph to find maximum clique within\n * @param[in] vertices_t, set of candidate vertices to check\n * @param[in][out] vertices_t&, current clique to check for optimality\n * @param[in][out] vertices_t&, biggest clique found so far\n */\nvoid max_cliq_bnb_basic(UndirectedGraph const & graph, vertices_t S,\n    vertices_t & R, vertices_t & R_best) noexcept;\n\n/**\n * max_cliq_bnb_color(UndirectedGraph const&, vertices_t const&,\n *     coloring_t const&, vertices_t&, vertices_t&)\n *\n * @brief find maximum clique using a recursive basic branch-and-bound (bnb)\n * algorithm\n * @see Section 3.1 of https://arxiv.org/pdf/1902.01534.pdf\n *\n * @param[in] UndirectedGraph, graph to find maximum clique within\n * @param[in] vertices_t, set of candidate vertices to check\n * @param[in] coloring_t, vertex coloring (@see greedy_vertices_coloring)\n * @param[in][out] vertices_t&, current clique to check for optimality\n * @param[in][out] vertices_t&, biggest clique found so far\n */\nvoid max_cliq_bnb_color(UndirectedGraph const & graph, vertices_t const & S,\n    coloring_t const & f, vertices_t & R, vertices_t & R_best) noexcept;\n\n/**\n * find_max_clique(UndirectedGraph const&, max_clique_algo_e const&,\n *     vertices_t&)\n *\n * @brief find maximum clique using a recursive basic branch-and-bound (bnb)\n * algorithm\n * @see Section 3.1 of https://arxiv.org/pdf/1902.01534.pdf\n *\n * @param[in] UndirectedGraph, graph to find maximum clique within\n * @param[in] max_clique_algo_e, algorithm to use\n * @param[in][out] vertices_t&, maximum clique of graph\n */\nvoid find_max_clique(UndirectedGraph const & graph, max_clique_algo_e const & algo,\n    vertices_t & R_best) noexcept;\n}  // namespace graph\n}  // namespace correspondences\n", "meta": {"hexsha": "0af0c454e18742b22051779bc8f73d6e49af0aa9", "size": 8326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "correspondences/graph/include/correspondences/graph/graph.hpp", "max_stars_repo_name": "jwdinius/nmsac", "max_stars_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "correspondences/graph/include/correspondences/graph/graph.hpp", "max_issues_repo_name": "jwdinius/nmsac", "max_issues_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-07-19T23:38:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T22:36:30.000Z", "max_forks_repo_path": "correspondences/graph/include/correspondences/graph/graph.hpp", "max_forks_repo_name": "jwdinius/nmsac", "max_forks_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T06:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-06T06:59:04.000Z", "avg_line_length": 32.0230769231, "max_line_length": 129, "alphanum_fraction": 0.690127312, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.05921024742104522, "lm_q1q2_score": 0.027526937067451043}}
{"text": "﻿/***\r\n第四章\t标准库的典型内容\r\n第一节 std::declval\r\n\r\n（2.2）返回左值引用还是返回右值引用\r\ndecltype(DeclValRight<A>)())的返回类型 = class _nmsp1::A &\r\ndecltype(DeclValRight<A&>)())的返回类型 = class _nmsp1::A &\r\ndecltype(DeclValRight<A&&>)())的返回类型 = class _nmsp1::A &\r\n\r\ndecltype(DeclValRight<A>)())的返回类型 = class _nmsp1::A &&\r\ndecltype(DeclValRight<A&>)())的返回类型 = class _nmsp1::A &\r\ndecltype(DeclValRight<A&&>)())的返回类型 = class _nmsp1::A &&\r\n\r\n（2.3）调用引用限定符修饰的成员函数范例\r\n\r\n（3）推导函数返回值范例\r\nT_F：是int (*)(int,int)类型，也就是函数指针类型\r\ndecltype(std::DeclValLeft<T_F>()   (std::DeclValLeft<U_Args>()...))：是int类型，也就是myfunc函数的返回类型\r\na)decltype(std::DeclValLeft<T_F>() )：是 int (* && )(int,int),函数指针的右值引用类型，其实就简单理解成函数指针类型\r\nb)decltype(std::DeclValLeft<U_Args>()...)这种写法：推导出来的是两个int &&\r\n***/\r\n\r\n#include <iostream>\r\n#include <boost/type_index.hpp>\r\nusing namespace std;\r\n\r\nnamespace _nmsp1\r\n{\t\r\n\tclass A\r\n\t{\r\n\tpublic:\r\n\t\tA(int i)        //构造函数\r\n\t\t{\r\n\t\t\tprintf(\"A::A(),this=%p\\n\", this);\r\n\t\t}\r\n\t\r\n\t\tdouble myfunc() //普通成员函数\r\n\t\t{\r\n\t\t\tprintf(\"A::myfunc(),this=%p\\n\", this);\r\n\t\t\treturn 12.1;\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\t~A() {}\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tT&& DeclValRight() noexcept;\r\n\r\n\ttemplate <typename T>\r\n\tT& DeclValLeft() noexcept;\r\n\r\n\r\n\tclass ALR\r\n\t{\r\n\tpublic:\r\n\t\tvoid onAnyValue()\r\n\t\t{\r\n\t\t\tcout << \"ALR::onAnyValue()\" << endl;\r\n\t\t}\r\n\r\n\t\tvoid onLvalue()&  //只能被类ALR的左值对象调用\r\n\t\t{\r\n\t\t\tcout << \"ALR::onLvalue()\" << endl;\r\n\t\t}\r\n\r\n\t\tvoid onRvalue()&& //只能被类ALR的右值对象调用\r\n\t\t{\r\n\t\t\tcout << \"ALR::onRvalue()\" << endl;\r\n\t\t}\r\n\t};\r\n\r\n}\r\n\r\n\r\nint main()\r\n{ \r\n\t\r\n\t\r\n\tusing boost::typeindex::type_id_with_cvr;\r\n\t\r\n\tcout << \"decltype(DeclValRight<A>)())的返回类型  =\" << type_id_with_cvr<decltype(_nmsp1::DeclValRight<_nmsp1::A>())>().pretty_name()   << endl;\r\n\tcout << \"decltype(DeclValRight<A&>)())的返回类型 =\" << type_id_with_cvr<decltype(_nmsp1::DeclValRight<_nmsp1::A&>())>().pretty_name()  << endl;\r\n\tcout << \"decltype(DeclValRight<A&&>)())的返回类型=\" << type_id_with_cvr<decltype(_nmsp1::DeclValRight<_nmsp1::A&&>())>().pretty_name() << endl;\r\n\t\r\n\t_nmsp1::ALR alr;             //左值对象alr\r\n\talr.onLvalue();\r\n\t//alr.onRvalue();            //编译错误，因为onRvalue只能被类A的右值对象调用\r\n\t_nmsp1::ALR().onRvalue();    //临时对象是右值对象\r\n\t//_nmsp1::ALR().onLvalue();  //编译错误，因为onLvalue只能被类A的左值对象调用\r\n\t\r\n#if 0\r\n\t//MSVC OK, GCC error\r\n\tdecltype(_nmsp1::DeclValRight<_nmsp1::ALR>().onAnyValue());\r\n\tdecltype(_nmsp1::DeclValRight<_nmsp1::ALR&>().onLvalue());    //返回的类型是class ALR &， 代表返回的是左值对象，左值对象调用onLvalue没问题\r\n\tdecltype(_nmsp1::DeclValRight<_nmsp1::ALR&&>().onRvalue());   //返回的类型是class ALR &&，代表返回的是右值对象，右值对象调用onRvalue没问题\r\n\t//decltype(_nmsp1::DeclValRight<_nmsp1::ALR&>().onRvalue());  //返回的类型是class ALR &， 代表返回的是左值对象，左值对象调用onRvalue是错误的\r\n\t//decltype(_nmsp1::DeclValRight<_nmsp1::ALR&&>().onLvalue()); //返回的类型是class ALR &&，代表返回的是右值对象，右值对象调用onLvalue是错误的\r\n\t\r\n\r\n\tdecltype(_nmsp1::DeclValLeft<_nmsp1::ALR>().onAnyValue()); \r\n\tdecltype(_nmsp1::DeclValLeft<_nmsp1::ALR&>().onLvalue());    //返回的类型是class ALR &，代表返回的是左值对象，左值对象调用onLvalue没问题\r\n\t//decltype(_nmsp1::DeclValLeft<_nmsp1::ALR&&>().onRvalue()); //返回的类型是class ALR &，代表返回的是左值对象，左值对象调用onRvalue是错误的\r\n\t//decltype(_nmsp1::DeclValLeft<_nmsp1::ALR&>().onRvalue());  //返回的类型是class ALR &，代表返回的是左值对象，左值对象调用onRvalue是错误的\r\n\tdecltype(_nmsp1::DeclValLeft<_nmsp1::ALR&&>().onLvalue());   //返回的类型是class ALR &，代表返回的是左值对象，左值对象调用onLvalue没问#题\r\n#endif\t\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "fc0c0844187f925111e652d9c43da467f526238f", "size": 3279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/4/402a.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/4/402a.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/4/402a.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 29.8090909091, "max_line_length": 140, "alphanum_fraction": 0.648063434, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1778108607641985, "lm_q2_score": 0.1540575704593912, "lm_q1q2_score": 0.02739310921062551}}
{"text": "#include <string>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <cmath>\n#include <stdexcept>\n#include <array>\n#include <random>\n\n#include <spdlog/spdlog.h>\n#include <spdlog/sinks/basic_file_sink.h>\n#include <spdlog/cfg/env.h>\n\n#include <boost/algorithm/string.hpp>\n\n// Python Binding\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/numpy.h>\nnamespace py = pybind11;\n\n#include \"cosmolike/basics.h\"\n#include \"cosmolike/bias.h\"\n#include \"cosmolike/baryons.h\"\n#include \"cosmolike/cosmo2D.h\"\n#include \"cosmolike/cosmo3D.h\"\n#include \"cosmolike/halo.h\"\n#include \"cosmolike/radial_weights.h\"\n#include \"cosmolike/recompute.h\"\n#include \"cosmolike/pt_cfastpt.h\"\n#include \"cosmolike/redshift_spline.h\"\n#include \"cosmolike/structs.h\"\n\n#include \"interface.hpp\"\n\nnamespace ima = interface_mpp_aux;\n\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// init functions\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n\nvoid cpp_initial_setup()\n{\n  spdlog::cfg::load_env_levels();\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"initial_setup\");\n\n  // restart variables to 0 so error check can flag bad initialization\n  tomo.shear_Nbin = 0;\n  tomo.clustering_Nbin = 0;\n\n  like.shear_shear = 0;\n  like.shear_pos = 0;\n  like.pos_pos = 0;\n\n  // bias\n  gbias.b1_function = &b1_per_bin;\n\n  // no priors\n  like.clusterN = 0;\n  like.clusterWL = 0;\n  like.clusterCG = 0;\n  like.clusterCC = 0;\n\n  // reset bias\n  for (int i = 0; i < MAX_SIZE_ARRAYS; i++)\n  {\n    gbias.b[i] = 0.0;\n    gbias.b2[i] = 0.0;\n    gbias.b_mag[i] = 0.0;\n  }\n\n  // reset IA\n  for (int i = 0; i < MAX_SIZE_ARRAYS; i++)\n  {\n    nuisance.A_z[i] = 0.0;\n    nuisance.A2_z[i] = 0.0;\n    nuisance.b_ta_z[i] = 0.0;\n  }\n\n  like.high_def_integration = 1;\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"initial_setup\");\n}\n\nvoid cpp_init_probes(std::string possible_probes)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_probes\");\n\n  if (possible_probes.compare(\"xi\") == 0)\n  { // cosmolike c interface\n    like.shear_shear = 1;\n\n    spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\", \"init_probes\",\n      \"possible_probes\", \"xi\");\n  }\n  else if (possible_probes.compare(\"wtheta\") == 0)\n  {\n    like.pos_pos = 1;\n\n    spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\", \"init_probes\",\n      \"possible_probes\", \"wtheta\");\n  }\n  else if (possible_probes.compare(\"gammat\") == 0)\n  {\n    like.shear_pos = 1;\n\n    spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\", \"init_probes\",\n      \"possible_probes\", \"gammat\");\n  }\n  else if (possible_probes.compare(\"2x2pt\") == 0)\n  {\n    like.shear_pos = 1;\n    like.pos_pos = 1;\n\n    spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\", \"init_probes\",\n      \"possible_probes\", \"2x2pt\");\n  }\n  else if (possible_probes.compare(\"3x2pt\") == 0)\n  {\n    like.shear_shear = 1;\n    like.shear_pos = 1;\n    like.pos_pos = 1;\n\n    spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\", \"init_probes\",\n      \"possible_probes\", \"3x2pt\");\n  }\n  else if (possible_probes.compare(\"xi_ggl\") == 0)\n  {\n    like.shear_shear = 1;\n    like.shear_pos = 1;\n\n    spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\", \"init_probes\",\n      \"possible_probes\", \"xi + ggl (2x2pt)\");\n  }\n  else\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = {} probe not supported\",\n      \"init_probes\", \"possible_probes\", possible_probes);\n    exit(1);\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_probes\");\n}\n\nvoid cpp_init_survey(std::string surveyname, double area, double sigma_e)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_survey\");\n\n  if (surveyname.size() > CHAR_MAX_SIZE - 1)\n  {\n    exit(1);\n  }\n  if (!(surveyname.size()>0))\n  {\n    spdlog::critical(\"{}: incompatible input\", \"init_survey\");\n    exit(1);\n  }\n\n  memcpy(survey.name, surveyname.c_str(), surveyname.size() + 1);\n  survey.area = area;\n  survey.sigma_e = sigma_e;\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_survey\");\n}\n\nvoid cpp_init_cosmo_runmode(const bool is_linear)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_cosmo_runmode\");\n\n  std::string mode = is_linear ? \"linear\" : \"Halofit\";\n  const size_t size = mode.size();\n  memcpy(pdeltaparams.runmode, mode.c_str(), size + 1);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\",\n    \"init_cosmo_runmode\", \"runmode\", mode);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_cosmo_runmode\");\n}\n\nvoid cpp_init_IA(int N)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_IA\");\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\", \"init_IA\", \"IA\", N);\n\n  if (N == 3 || N == 4 || N == 5 || N == 6)\n  {\n    like.IA = N;\n  }\n  else\n  {\n    spdlog::critical(\"{}: {} = {} not supported\", \"init_IA\", \"like.IA\", N);\n    exit(1);\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_IA\");\n}\n\nvoid cpp_init_baryons_contamination(\nconst bool use_baryonic_simulations_contamination,\nconst std::string which_baryonic_simulations_contamination)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_baryons_contamination\");\n\n  spdlog::info(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\",\n    \"init_baryons_contamination\", \"use_baryonic_simulations\",\n    use_baryonic_simulations_contamination);\n\n  if (use_baryonic_simulations_contamination)\n  {\n    init_baryons(which_baryonic_simulations_contamination.c_str());\n\n    spdlog::info(\"\\x1b[90m{}\\x1b[0m: {} = {} selected\",\n      \"init_baryons_contamination\", \"which_baryonic_simulations_contamination\",\n      which_baryonic_simulations_contamination);\n  }\n  else\n  {\n    reset_bary_struct();\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_baryons_contamination\");\n}\n\nvoid cpp_init_binning(const int Ntheta, const double theta_min_arcmin,\nconst double theta_max_arcmin)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_binning\");\n\n  if (!(Ntheta > 0))\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = {} not supported\", \"init_binning\",\n      \"like.Ntheta\", Ntheta);\n    exit(1);\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\",\n    \"init_binning\", \"Ntheta\", Ntheta);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\",\n    \"init_binning\", \"theta_min_arcmin\", theta_min_arcmin);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\",\n    \"init_binning\", \"theta_max_arcmin\", theta_max_arcmin);\n\n  like.Ntheta = Ntheta;\n  like.vtmin = theta_min_arcmin * 2.90888208665721580e-4;\n  like.vtmax = theta_max_arcmin * 2.90888208665721580e-4;\n  const double logdt = (std::log(like.vtmax)-std::log(like.vtmin))/like.Ntheta;\n  like.theta = (double*) calloc(like.Ntheta, sizeof(double));\n\n  constexpr double x = 2./ 3.;\n\n  for (int i = 0; i < like.Ntheta; i++)\n  {\n    const double thetamin = std::exp(log(like.vtmin) + (i + 0.0) * logdt);\n    const double thetamax = std::exp(log(like.vtmin) + (i + 1.0) * logdt);\n    like.theta[i] = x * (std::pow(thetamax, 3) - std::pow(thetamin, 3)) /\n      (thetamax*thetamax - thetamin*thetamin);\n\n    spdlog::debug(\n      \"\\x1b[90m{}\\x1b[0m: Bin {:d} - {} = {:.4e}, {} = {:.4e} and {} = {:.4e}\",\n      \"init_binning\", i, \"theta_min [rad]\", thetamin, \"theta [rad]\",\n      like.theta[i], \"theta_max [rad]\", thetamax);\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_binning\");\n}\n\nvoid cpp_init_lens_sample(std::string multihisto_file, const int Ntomo, const double ggl_cut)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_lens_sample\");\n\n  if (tomo.shear_Nbin == 0)\n  {\n    spdlog::critical(\"{}: {} not set prior to this function call\",\n      \"init_lens_sample\", \"tomo.shear_Nbin\");\n    exit(1);\n  }\n  if (multihisto_file.size()>CHAR_MAX_SIZE-1)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: insufficient pre-allocated char memory (max = {}) for\"\n      \"the string: {}\", \"init_lens_sample\", CHAR_MAX_SIZE-1, multihisto_file);\n    exit(1);\n  }\n  if (!(multihisto_file.size() > 0))\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: empty {} string not supported\",\n      \"init_lens_sample\", \"multihisto_file\");\n    exit(1);\n  }\n  if (!(Ntomo > 0) || Ntomo > MAX_SIZE_ARRAYS)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = {} not supported (max = {})\",\n      \"init_lens_sample\", \"Ntomo\", Ntomo, MAX_SIZE_ARRAYS);\n    exit(1);\n  }\n\n  memcpy(redshift.clustering_REDSHIFT_FILE, multihisto_file.c_str(), multihisto_file.size()+1);\n\n  redshift.clustering_photoz = 4;\n  tomo.clustering_Nbin = Ntomo;\n  tomo.clustering_Npowerspectra = tomo.clustering_Nbin;\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\", \"init_lens_sample\",\n    \"clustering_REDSHIFT_FILE\", multihisto_file);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\", \"init_lens_sample\",\n    \"clustering_Nbin\", Ntomo);\n\n  if (ggl_cut > 0)\n  {\n    survey.ggl_overlap_cut = ggl_cut;\n  }\n  else\n  {\n    survey.ggl_overlap_cut = 0.0;\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\", \"init_lens_sample\",\n    \"survey.ggl_overlap_cut\", survey.ggl_overlap_cut);\n\n  pf_photoz(0.1, 0);\n  {\n    int n = 0;\n    for (int i = 0; i < tomo.clustering_Nbin; i++)\n    {\n      for (int j = 0; j < tomo.shear_Nbin; j++)\n      {\n        n += test_zoverlap(i, j);\n      }\n    }\n    tomo.ggl_Npowerspectra = n;\n\n    spdlog::debug(\"\\x1b[90m{}\\x1b[0m: tomo.ggl_Npowerspectra = {}\",\n      \"init_lens_sample\", tomo.ggl_Npowerspectra);\n  }\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_lens_sample\");\n}\n\nvoid cpp_init_source_sample(std::string multihisto_file, const int Ntomo)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_source_sample\");\n\n  if (multihisto_file.size() > CHAR_MAX_SIZE - 1)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: insufficient pre-allocated char memory (max = {}) for\"\n      \"the string: {}\", \"init_source_sample\", CHAR_MAX_SIZE-1, multihisto_file);\n    exit(1);\n  }\n  if (!(multihisto_file.size() > 0))\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: empty {} string not supported\",\n      \"init_source_sample\", \"multihisto_file\");\n    exit(1);\n  }\n  if (!(Ntomo > 0) || Ntomo > MAX_SIZE_ARRAYS)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = {} not supported (max = {})\",\n      \"init_source_sample\", \"Ntomo\", Ntomo, MAX_SIZE_ARRAYS);\n    exit(1);\n  }\n\n  // convert std::string to char*\n  memcpy(redshift.shear_REDSHIFT_FILE, multihisto_file.c_str(), multihisto_file.size() + 1);\n\n  redshift.shear_photoz = 4;\n  tomo.shear_Nbin = Ntomo;\n  tomo.shear_Npowerspectra = tomo.shear_Nbin * (tomo.shear_Nbin + 1) / 2;\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: tomo.shear_Npowerspectra = {}\", \n    \"init_source_sample\", tomo.shear_Npowerspectra);\n\n  for (int i=0; i<tomo.shear_Nbin; i++)\n  {\n    nuisance.bias_zphot_shear[i] = 0.0;\n\n    spdlog::info(\"\\x1b[90m{}\\x1b[0m: bin {} - {} = {}.\",\n      \"init_source_sample\", i, \"<z_s>\", zmean_source(i));\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\", \"init_source_sample\",\n    \"shear_REDSHIFT_FILE\", multihisto_file);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\", \"init_source_sample\",\n    \"shear_Nbin\", Ntomo);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_source_sample\");\n}\n\nvoid cpp_init_size_data_vector()\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_size_data_vector\");\n\n  if (tomo.shear_Nbin == 0)\n  {\n    spdlog::critical(\"{}: {} not set prior to this function call\",\n      \"init_size_data_vector\", \"tomo.shear_Nbin\");\n    exit(1);\n  }\n  if (tomo.clustering_Nbin == 0)\n  {\n    spdlog::critical(\"{}: {} not set prior to this function call\",\n      \"init_size_data_vector\", \"tomo.clustering_Nbin\");\n    exit(1);\n  }\n  if (like.Ntheta == 0)\n  {\n    spdlog::critical(\"{}: {} not set prior to this function call\",\n      \"init_size_data_vector\", \"like.Ntheta\");\n    exit(1);\n  }\n\n  like.Ndata = like.Ntheta*(2*tomo.shear_Npowerspectra +\n                        tomo.ggl_Npowerspectra + tomo.clustering_Npowerspectra);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: {} = {} selected.\",\n    \"init_size_data_vector\", \"Ndata\", like.Ndata);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_size_data_vector\");\n}\n\nvoid cpp_init_linear_power_spectrum(std::vector<double> io_log10k,\nstd::vector<double> io_z, std::vector<double> io_lnP)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_linear_power_spectrum\");\n\n  {\n    bool debug_fail = false;\n    if (io_z.size()*io_log10k.size() != io_lnP.size())\n    {\n      debug_fail = true;\n    }\n    else\n    {\n      if (io_z.size() == 0 || io_log10k.size() == 0)\n      {\n        debug_fail = true;\n      }\n    }\n    if (debug_fail)\n    {\n      spdlog::critical(\n        \"\\x1b[90m{}\\x1b[0m: incompatible input w/ k.size = {}, z.size = {}, \"\n        \"and lnP.size = {}\", \"init_linear_power_spectrum\", io_log10k.size(),\n        io_z.size(), io_lnP.size());\n      exit(1);\n    }\n\n    if(io_z.size() < 5 || io_log10k.size() < 5)\n    {\n      spdlog::critical(\n        \"\\x1b[90m{}\\x1b[0m: bad input w/ k.size = {}, z.size = {}, \"\n        \"and lnP.size = {}\", \"init_linear_power_spectrum\", io_log10k.size(),\n        io_z.size(), io_lnP.size());\n      exit(1);\n    }\n  }\n\n  int nlog10k = static_cast<int>(io_log10k.size());\n  int nz = static_cast<int>(io_z.size());\n  double* log10k = io_log10k.data();\n  double* z = io_z.data();\n  double* lnP = io_lnP.data();\n  setup_p_lin(&nlog10k, &nz, &log10k, &z, &lnP, 1);\n\n  // force initialization - imp to avoid seg fault when openmp is on\n  const double io_a = 1.0;\n  const double io_k = 0.1*cosmology.coverH0;\n  p_lin(io_k, io_a);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_linear_power_spectrum\");\n\n  return;\n}\n\nvoid cpp_init_non_linear_power_spectrum(std::vector<double> io_log10k,\nstd::vector<double> io_z, std::vector<double> io_lnP)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_non_linear_power_spectrum\");\n\n  {\n    bool debug_fail = false;\n    if (io_z.size()*io_log10k.size() != io_lnP.size())\n    {\n      debug_fail = true;\n    }\n    else\n    {\n      if (io_z.size() == 0)\n      {\n        debug_fail = true;\n      }\n    }\n    if (debug_fail)\n    {\n      spdlog::critical(\n        \"\\x1b[90m{}\\x1b[0m: incompatible input w/ k.size = {}, z.size = {}, \"\n        \"and lnP.size = {}\", \"init_non_linear_power_spectrum\", io_log10k.size(),\n        io_z.size(), io_lnP.size());\n      exit(1);\n    }\n\n    if(io_z.size() < 5 || io_log10k.size() < 5)\n    {\n      spdlog::critical(\n        \"\\x1b[90m{}\\x1b[0m: bad input w/ k.size = {}, z.size = {}, \"\n        \"and lnP.size = {}\", \"init_non_linear_power_spectrum\", io_log10k.size(),\n        io_z.size(), io_lnP.size());\n      exit(1);\n    }\n  }\n\n  int nlog10k = static_cast<int>(io_log10k.size());\n  int nz = static_cast<int>(io_z.size());\n  double* log10k = io_log10k.data();\n  double* z = io_z.data();\n  double* lnP = io_lnP.data();\n  setup_p_nonlin(&nlog10k, &nz, &log10k, &z, &lnP, 1);\n\n  // force initialization - imp to avoid seg fault when openmp is on\n  const double io_a = 1.0;\n  const double io_k = 0.1*cosmology.coverH0;\n  p_nonlin(io_k, io_a);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_non_linear_power_spectrum\");\n\n  return;\n}\n\n// Growth: D = G * a\nvoid cpp_init_growth(std::vector<double> io_z, std::vector<double> io_G)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_growth\");\n\n  {\n    bool debug_fail = false;\n    if (io_z.size() != io_G.size())\n    {\n      debug_fail = true;\n    }\n    else\n    {\n      if (io_z.size() == 0)\n      {\n        debug_fail = true;\n      }\n    }\n    if (debug_fail)\n    {\n      spdlog::critical(\"\\x1b[90m{}\\x1b[0m: incompatible input w/ z.size = {} and G.size = {}\",\n        \"init_growth\", io_z.size(), io_G.size());\n      exit(1);\n    }\n  }\n\n  int nz = static_cast<int>(io_z.size());\n  double* z = io_z.data();\n  double* G = io_G.data();\n  setup_growth(&nz, &z, &G, 1);\n\n  // force initialization - imp to avoid seg fault when openmp is on\n  const double io_a = 1.0;\n  const double zz = 0.0;\n  f_growth(zz);\n  growfac_all(io_a);\n  growfac(io_a);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_growth\");\n\n  return;\n}\n\nvoid cpp_init_distances(std::vector<double> io_z, std::vector<double> io_chi)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_distances\");\n\n  {\n    bool debug_fail = false;\n    if (io_z.size() != io_chi.size())\n    {\n      debug_fail = true;\n    }\n    else\n    {\n      if (io_z.size() == 0)\n      {\n        debug_fail = true;\n      }\n    }\n    if (debug_fail)\n    {\n      spdlog::critical(\n        \"\\x1b[90m{}\\x1b[0m: incompatible input w/ z.size = {} and G.size = {}\",\n        \"init_distances\",\n        io_z.size(),\n        io_chi.size()\n      );\n      exit(1);\n    }\n  }\n\n  int nz = static_cast<int>(io_z.size());\n  double* vz = io_z.data();\n  double* vchi = io_chi.data();\n  setup_chi(&nz, &vz, &vchi, 1);\n\n  // force initialization - imp to avoid seg fault when openmp is on\n  const double io_a = 1.0;\n  chi(io_a);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_distances\");\n\n  return;\n}\n\nvoid cpp_init_data_real(std::string COV, std::string MASK, std::string DATA)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_data_real\");\n\n  ima::RealData& instance = ima::RealData::get_instance();\n\n  instance.set_mask(MASK); // set_mask must be called first\n  instance.set_data(DATA);\n  instance.set_inv_cov(COV);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_data_real\");\n\n  return;\n}\n\nvoid cpp_init_baryon_pca_scenarios(std::string scenarios)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"init_baryon_pca_scenarios\");\n\n  ima::BaryonScenario& instance = ima::BaryonScenario::get_instance();\n\n  instance.set_scenarios(scenarios);\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"init_baryon_pca_scenarios\");\n\n  return;\n}\n\nvoid cpp_init_accuracy_boost(const double accuracy_boost, const double sampling_boost,\nconst int integration_accuracy)\n{\n  const double from_desy3_to_lsst_acc = 2;\n\n  Ntable.N_a = static_cast<int>(ceil(Ntable.N_a*accuracy_boost));\n  Ntable.N_ell_TATT = static_cast<int>(ceil(Ntable.N_ell_TATT*accuracy_boost));\n  Ntable.N_ell_TATT = static_cast<int>(ceil(Ntable.N_ell_TATT*from_desy3_to_lsst_acc));\n\n  Ntable.N_k_lin = static_cast<int>(ceil(Ntable.N_k_lin*sampling_boost));\n  Ntable.N_k_nlin = static_cast<int>(ceil(Ntable.N_k_nlin*sampling_boost));\n  Ntable.N_ell = static_cast<int>(ceil(Ntable.N_ell*sampling_boost));\n  \n  Ntable.N_theta  = static_cast<int>(ceil(Ntable.N_theta*sampling_boost));\n\n  Ntable.N_S2 = static_cast<int>(ceil(Ntable.N_S2*sampling_boost));\n  Ntable.N_DS = static_cast<int>(ceil(Ntable.N_DS*sampling_boost));\n\n  precision.low /= accuracy_boost;\n  precision.medium /= accuracy_boost;\n  precision.high /= accuracy_boost;\n  precision.insane /= accuracy_boost; \n  \n  like.high_def_integration = integration_accuracy;\n}\n\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// SET PARAM FUNCTIONS\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n\nvoid cpp_set_cosmological_parameters(const double omega_matter,\nconst double hubble, const bool is_cached_cosmology)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_cosmological_parameters\");\n\n  if(!is_cached_cosmology)\n  {\n    // Cosmolike should not need parameters from inflation or dark energy.\n    // because Cobaya provides P(k,z), H(z), D(z), Chi(z)...\n    // It may require H0 to set scales and \\Omega_M to set the halo model\n\n    // cosmolike c interface\n    cosmology.Omega_m = omega_matter;\n    cosmology.Omega_v = 1.0-omega_matter;\n    // Cosmolike only needs to know that there are massive neutrinos (>0)\n    cosmology.Omega_nu = 0.1;\n    cosmology.h0 = hubble/100.0; // assuming H0 in km/s/Mpc\n    cosmology.MGSigma = 0.0;\n    cosmology.MGmu = 0.0;\n\n    // Technical Problem: we want Cosmolike to calculate the data vector when\n    // Cobaya request (no cache). To avoid cache in Cosmolike, we use a\n    // random number generators to set cosmology.random\n    cosmology.random = ima::RandomNumber::get_instance().get();\n    cosmology.is_cached = 0;\n  }\n  else\n  {\n    cosmology.is_cached = 1;\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_cosmological_parameters\");\n}\n\nvoid cpp_set_nuisance_shear_calib(std::vector<double> M)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_nuisance_shear_calib\");\n\n  if (tomo.shear_Nbin == 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\", \"set_nuisance_shear_calib\",\n      \"shear_Nbin\");\n    exit(1);\n  }\n  if (tomo.shear_Nbin != static_cast<int>(M.size()))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: incompatible input w/ size = {} (!= {})\",\n      \"set_nuisance_shear_calib\", M.size(), tomo.shear_Nbin);\n    exit(1);\n  }\n\n  for (int i=0; i<tomo.shear_Nbin; i++)\n  {\n    nuisance.shear_calibration_m[i] = M[i];\n  }\n\n   spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_nuisance_shear_calib\");\n}\n\nvoid cpp_set_nuisance_shear_photoz(std::vector<double> SP)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_nuisance_shear_photoz\");\n\n  if (tomo.shear_Nbin == 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"set_nuisance_shear_photoz\",\n      \"shear_Nbin\"\n    );\n    exit(1);\n  }\n  if (tomo.shear_Nbin != static_cast<int>(SP.size()))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: incompatible input w/ size = {} (!= {})\",\n      \"set_nuisance_shear_photoz\",\n      SP.size(),\n      tomo.shear_Nbin\n    );\n    exit(1);\n  }\n\n  for (int i=0; i<tomo.shear_Nbin; i++)\n  {\n    nuisance.bias_zphot_shear[i] = SP[i];\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_nuisance_shear_photoz\");\n}\n\nvoid cpp_set_nuisance_clustering_photoz(std::vector<double> CP)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_nuisance_clustering_photoz\");\n\n  if (tomo.clustering_Nbin == 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"set_nuisance_clustering_photoz\",\n      \"clustering_Nbin\"\n    );\n    exit(1);\n  }\n  if (tomo.clustering_Nbin != static_cast<int>(CP.size()))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: incompatible input w/ size = {} (!= {})\",\n      \"set_nuisance_clustering_photoz\",\n      CP.size(),\n      tomo.clustering_Nbin\n    );\n    exit(1);\n  }\n\n  for (int i=0; i<tomo.clustering_Nbin; i++)\n  {\n    nuisance.bias_zphot_clustering[i] = CP[i];\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_nuisance_clustering_photoz\");\n}\n\nvoid cpp_set_nuisance_linear_bias(std::vector<double> B1)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_nuisance_linear_bias\");\n\n  if (tomo.clustering_Nbin == 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"set_nuisance_linear_bias\", \"clustering_Nbin\");\n    exit(1);\n  }\n  if (tomo.clustering_Nbin != static_cast<int>(B1.size()))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: incompatible input w/ size = {} (!= {})\",\n      \"set_nuisance_linear_bias\", B1.size(), tomo.clustering_Nbin);\n    exit(1);\n  }\n\n  for (int i=0; i<tomo.clustering_Nbin; i++)\n  {\n    gbias.b[i] = B1[i];\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_nuisance_linear_bias\");\n}\n\nvoid cpp_set_nuisance_nonlinear_bias(std::vector<double> B1,\nstd::vector<double> B2)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_nuisance_nonlinear_bias\");\n\n  if (tomo.clustering_Nbin == 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"set_nuisance_nonlinear_bias\", \"clustering_Nbin\"\n    );\n    exit(1);\n  }\n  if (tomo.clustering_Nbin != static_cast<int>(B1.size()) ||\n      tomo.clustering_Nbin != static_cast<int>(B2.size()))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: incompatible input w/ sizes = {} and {} (!= {})\",\n      \"set_nuisance_nonlinear_bias\", B1.size(), B2.size(), tomo.clustering_Nbin\n    );\n    exit(1);\n  }\n\n  constexpr double tmp = -4./7.;\n  for (int i=0; i<tomo.clustering_Nbin; i++)\n  {\n    gbias.b2[i] = B2[i];\n    gbias.bs2[i] = ima::almost_equal(B2[i], 0.) ? 0 : tmp*(B1[i]-1.0);\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_nuisance_nonlinear_bias\");\n}\n\nvoid cpp_set_nuisance_magnification_bias(std::vector<double> B_MAG)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_nuisance_magnification_bias\");\n\n  if (tomo.clustering_Nbin == 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"set_nuisance_magnification_bias\",\n      \"clustering_Nbin\");\n    exit(1);\n  }\n  if (tomo.clustering_Nbin != static_cast<int>(B_MAG.size()))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: incompatible input w/ size = {} (!= {})\",\n      \"set_nuisance_magnification_bias\", B_MAG.size(), tomo.clustering_Nbin);\n    exit(1);\n  }\n\n  for (int i=0; i<tomo.clustering_Nbin; i++)\n  {\n    gbias.b_mag[i] = B_MAG[i];\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_nuisance_magnification_bias\");\n}\n\nvoid cpp_set_nuisance_bias(std::vector<double> B1, std::vector<double> B2,\nstd::vector<double> B_MAG)\n{\n  cpp_set_nuisance_linear_bias(B1);\n  cpp_set_nuisance_nonlinear_bias(B1, B2);\n  cpp_set_nuisance_magnification_bias(B_MAG);\n}\n\nvoid cpp_set_nuisance_ia(std::vector<double> A1, std::vector<double> A2,\nstd::vector<double> B_TA)\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"set_nuisance_ia\");\n\n  if (tomo.shear_Nbin == 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"set_nuisance_ia\", \"shear_Nbin\");\n    exit(1);\n  }\n  if (tomo.shear_Nbin != static_cast<int>(A1.size()) ||\n      tomo.shear_Nbin != static_cast<int>(A2.size()) ||\n  \t\ttomo.shear_Nbin != static_cast<int>(B_TA.size()))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: incompatible input w/ sizes = {}, {} and {} (!= {})\",\n      \"set_nuisance_ia\", A1.size(), A2.size(), B_TA.size(), tomo.shear_Nbin\n    );\n    exit(1);\n  }\n\n  nuisance.c1rhocrit_ia = 0.01389;\n  if (like.IA == 3 || like.IA == 5)\n  {\n    for (int i=0; i<tomo.shear_Nbin; i++)\n    {\n      nuisance.A_z[i] = A1[i];\n      nuisance.A2_z[i] = A2[i];\n      nuisance.b_ta_z[i] = B_TA[i];\n    }\n  }\n  else if (like.IA == 4 || like.IA == 6)\n  {\n    nuisance.A_ia = A1[0];\n    nuisance.eta_ia = A1[1];\n    nuisance.oneplusz0_ia = 1.62;\n\n    nuisance.A2_ia = A2[0];\n    nuisance.eta_ia_tt = A2[1];\n    nuisance.b_ta_z[0] = B_TA[0];\n\n    for (int i=2; i<tomo.shear_Nbin; i++)\n    {\n      if ( !(ima::almost_equal(A1[i], 0.)) || !(ima::almost_equal(A2[i], 0.)) ||\n           !(ima::almost_equal(B_TA[i], 0.)))\n      {\n        spdlog::critical(\n        \t\"set_nuisance_ia: one of nuisance.A_z[{}]={}, nuisance.A2_z[{}]=\"\n          \"{}, nuisance.b_ta[{}]={} was specified w/ power-law evolution\\n\",\n          i, nuisance.A_z[i], i, nuisance.A2_z[i], i, nuisance.b_ta_z[i]);\n        exit(1);\n      }\n    }\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"set_nuisance_ia\");\n}\n\nvoid cpp_set_pm(std::vector<double> pm)\n{\n  ima::PointMass& instance = ima::PointMass::get_instance();\n  instance.set_pm_vector(pm);\n  return;\n}\n\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// GET FUNCTIONS\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n\narma::Mat<double> cpp_get_covariance_masked()\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n  return instance.get_covariance_masked();\n}\n\narma::Mat<double> cpp_get_covariance_masked_reduced_dim()\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n  return instance.get_covariance_masked_reduced_dim();\n}\n\nint cpp_get_mask(const int i)\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n  return instance.get_mask(i);\n}\n\nint cpp_get_ndim()\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n  return instance.get_ndim();\n}\n\nint cpp_get_nreduced_dim()\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n  return instance.get_nreduced_dim();\n}\n\nint cpp_get_index_reduced_dim(const int i)\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n  return instance.get_index_reduced_dim(i);\n}\n\n// The conversion between STL vector and python np array is cleaner\n// arma:Col is cast to 2D np array with 1 column (not as nice!)\nstd::vector<double> cpp_get_expand_dim_from_masked_reduced_dim(\nstd::vector<double> reduced_dim_vector)\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n\n  arma::Col<double> tmp = instance.get_expand_dim_from_masked_reduced_dim(\n    arma::Col<double>(reduced_dim_vector));\n\n  std::vector<double> result(tmp.n_elem, 0.0);\n  for(int i=0; i<static_cast<int>(tmp.n_elem); i++)\n  {\n    result[i] = tmp(i);\n  }\n\n  return result;\n}\n\nint cpp_get_baryon_pca_nscenarios()\n{\n  ima::BaryonScenario& instance = ima::BaryonScenario::get_instance();\n  return instance.nscenarios();\n}\n\nstd::string cpp_get_baryon_pca_scenario_name(const int i)\n{\n  ima::BaryonScenario& instance = ima::BaryonScenario::get_instance();\n  return instance.get_scenario(i);\n}\n\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// COMPUTE FUNCTIONS\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n\ndouble cpp_compute_chi2(std::vector<double> datavector)\n{\n  ima::RealData& instance = ima::RealData::get_instance();\n  return instance.get_chi2(datavector);\n}\n\ndouble cpp_compute_pm(const int zl, const int zs,\nconst double theta)\n{\n  ima::PointMass& instance = ima::PointMass::get_instance();\n  return instance.get_pm(zl,zs,theta);\n}\n\nstd::vector<double> cpp_compute_data_vector_masked()\n{\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Begins\", \"compute_data_vector_masked\");\n\n  if (tomo.shear_Nbin == 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"compute_data_vector_masked\", \"shear_Nbin\");\n    exit(1);\n  }\n  if (tomo.clustering_Nbin == 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"compute_data_vector_masked\", \"clustering_Nbin\");\n    exit(1);\n  }\n  if (like.Ntheta == 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} = 0 is invalid\",\n      \"compute_data_vector_masked\", \"Ntheta\");\n    exit(1);\n  }\n  if (!ima::RealData::get_instance().is_mask_set())\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"compute_data_vector_masked\", \"mask\");\n    exit(1);\n  }\n  if (!ima::RealData::get_instance().is_data_set())\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"compute_data_vector_masked\", \"data_vector\");\n    exit(1);\n  }\n  if (!ima::RealData::get_instance().is_inv_cov_set())\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"compute_data_vector_masked\", \"inv_cov\");\n    exit(1);\n  }\n\n  std::vector<double> data_vector(like.Ndata, 0.0);\n\n  int start = 0;\n  if (like.shear_shear == 1)\n  {\n    for (int nz=0; nz<tomo.shear_Npowerspectra; nz++)\n    {\n      const int z1 = Z1(nz);\n      const int z2 = Z2(nz);\n      for (int i = 0; i<like.Ntheta; i++)\n      {\n        if (cpp_get_mask(like.Ntheta*nz+i))\n        {\n          data_vector[like.Ntheta*nz+i] =\n            xi_pm_tomo(1, i, z1, z2, 1 /* limber option = 1 -> limber */)*\n            (1.0 + nuisance.shear_calibration_m[z1])*\n            (1.0 + nuisance.shear_calibration_m[z2]);\n        }\n        if (cpp_get_mask(like.Ntheta*(tomo.shear_Npowerspectra+nz)+i))\n        {\n          data_vector[like.Ntheta*(tomo.shear_Npowerspectra+nz)+i] =\n            xi_pm_tomo(-1, i, z1, z2, 1 /*limber*/)*\n            (1. + nuisance.shear_calibration_m[z1])*\n            (1. + nuisance.shear_calibration_m[z2]);\n        }\n      }\n    }\n  }\n\n  start = start + 2*like.Ntheta*tomo.shear_Npowerspectra;\n  if (like.shear_pos == 1)\n  {\n    for (int nz=0; nz<tomo.ggl_Npowerspectra; nz++)\n    {\n      const int zl = ZL(nz);\n      const int zs = ZS(nz);\n      for (int i=0; i<like.Ntheta; i++)\n      {\n        if (cpp_get_mask(start+(like.Ntheta*nz)+i))\n        {\n          const double theta = like.theta[i];\n          data_vector[start+(like.Ntheta*nz)+i] = (\n            w_gammat_tomo(i, zl, zs, 1 /* limber option=1 -> limber */) +\n            cpp_compute_pm(zl, zs, theta))*(1.0+nuisance.shear_calibration_m[zs]);\n        }\n      }\n    }\n  }\n\n  start = start + like.Ntheta*tomo.ggl_Npowerspectra;\n  if (like.pos_pos == 1)\n  {\n    for (int nz=0; nz<tomo.clustering_Npowerspectra; nz++)\n    {\n      for (int i=0; i<like.Ntheta; i++)\n      {\n        if (cpp_get_mask(start+(like.Ntheta*nz)+i))\n        {\n          data_vector[start+(like.Ntheta*nz)+i] =\n            w_gg_tomo(i, nz, nz, 0 /* limber option = 0 -> nonlimber */);\n        }\n      }\n    }\n  }\n\n  spdlog::debug(\"\\x1b[90m{}\\x1b[0m: Ends\", \"compute_data_vector_masked\");\n\n  return data_vector;\n}\n\nstd::vector<double> cpp_compute_data_vector_masked_reduced_dim()\n{\n  std::vector<double> data_vector_masked = cpp_compute_data_vector_masked();\n\n  const int ndim = data_vector_masked.size();\n  const int ndim_reduced = cpp_get_nreduced_dim();\n\n  std::vector<double> data_vector_masked_reduced_dim(ndim_reduced, 0.0);\n\n  for(int i=0; i<ndim; i++)\n  {\n    if(cpp_get_mask(i)>0.99)\n    {\n      if(cpp_get_index_reduced_dim(i) < 0)\n      {\n        spdlog::critical(\"\\x1b[90m{}\\x1b[0m: logical error, internal\"\n          \" inconsistent mask operation\",\n          \"cpp_compute_data_vector_masked_reduced_dim\");\n        exit(1);\n      }\n\n      data_vector_masked_reduced_dim[cpp_get_index_reduced_dim(i)] =\n        data_vector_masked[i];\n    }\n  }\n\n  return data_vector_masked_reduced_dim;\n}\n\ndouble cpp_compute_baryon_ratio(double log10k, double a)\n{\n  const double KNL = pow(10.0,log10k)*cosmology.coverH0;\n  return PkRatio_baryons(KNL, a);\n}\n\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// RESET FUNCTIONS\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n\nvoid cpp_reset_baryionic_struct()\n{\n  reset_bary_struct();\n  return;\n}\n\n// ----------------------------------------------------------------------------\n// ------------------------ INTERNAL C++ FUNCTIONS ----------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ------------------------ INTERNAL C++ FUNCTIONS ----------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ------------------------ INTERNAL C++ FUNCTIONS ----------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ------------------------ INTERNAL C++ FUNCTIONS ----------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ------------------------ INTERNAL C++ FUNCTIONS ----------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ------------------------ INTERNAL C++ FUNCTIONS ----------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// CLASS RealData MEMBER FUNCTIONS (& RELATED) - READ MASK, COV..\n// THERE ARE \"C\" WRAPS FOR MOST OF THESE FUNCTIONS\n// ----------------------------------------------------------------------------\n\narma::Mat<double> ima::read_table(const std::string file_name)\n{\n  std::ifstream input_file(file_name);\n\n  if (!input_file.is_open())\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: file {} cannot be opened\",\n      \"read_table\",\n      file_name\n    );\n    exit(1);\n  }\n\n  // Read the entire file into memory\n  std::string tmp;\n  input_file.seekg(0,std::ios::end);\n  tmp.resize(static_cast<size_t>(input_file.tellg()));\n  input_file.seekg(0,std::ios::beg);\n  input_file.read(&tmp[0],tmp.size());\n  input_file.close();\n  if(tmp.empty())\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: file {} is empty\",\n      \"read_table\",\n      file_name\n    );\n    exit(1);\n  }\n  std::vector<std::string> lines;\n  lines.reserve(50000);\n  // Second: Split file into lines\n  boost::trim_if(tmp,boost::is_any_of(\"\\t \"));\n  boost::trim_if(tmp,boost::is_any_of(\"\\n\"));\n  boost::split(lines, tmp,boost::is_any_of(\"\\n\"), boost::token_compress_on);\n  // Erase comment/blank lines\n  auto check = [](std::string mystr) -> bool\n  {\n    return boost::starts_with(mystr, \"#\");\n  };\n  lines.erase(std::remove_if(lines.begin(), lines.end(), check), lines.end());\n  // Third: Split line into words\n  arma::Mat<double> result;\n  size_t ncols = 0;\n  { // first line\n    std::vector<std::string> words;\n    words.reserve(100);\n    boost::split(words,lines[0], boost::is_any_of(\" \\t\"),\n      boost::token_compress_on);\n    ncols = words.size();\n    result.set_size(lines.size(), ncols);\n    for (size_t j=0; j<ncols; j++)\n    {\n      result(0,j) = std::stod(words[j]);\n    }\n  }\n  #pragma omp parallel for\n  for (size_t i=1; i<lines.size(); i++)\n  {\n    std::vector<std::string> words;\n    boost::split(words, lines[i], boost::is_any_of(\" \\t\"),\n      boost::token_compress_on);\n    if (words.size() != ncols)\n    {\n      spdlog::critical(\"\\x1b[90m{}\\x1b[0m: file {} is not well formatted\"\n      \" (regular table required)\", \"read_table\", file_name);\n      exit(1);\n    }\n    for (size_t j=0; j<ncols; j++)\n    {\n      result(i,j) = std::stod(words[j]);\n    }\n  };\n  return result;\n}\n\nstd::vector<double> ima::convert_arma_col_to_stl_vector(arma::Col<double> in)\n{\n  std::vector<double> out(in.n_elem, 0.0);\n\n  for(int i=0; i<static_cast<int>(in.n_elem); i++)\n  {\n    out[i] = in(i);\n  }\n\n  return out;\n}\n\nvoid ima::RealData::set_mask(std::string MASK)\n{\n  if (!(like.Ndata>0))\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"set_mask\", \"like.Ndata\");\n    exit(1);\n  }\n\n  this->ndata_ = like.Ndata;\n  this->mask_.set_size(this->ndata_);\n\n  arma::Mat<double> table = ima::read_table(MASK);\n  for (int i=0; i<this->ndata_; i++)\n  {\n    this->mask_(i) = static_cast<int>(table(i,1)+1e-13);\n    if(!(this->mask_(i) == 0 || this->mask_(i) == 1))\n    {\n      spdlog::critical(\"\\x1b[90m{}\\x1b[0m: inconsistent mask\", \"set_mask\");\n      exit(1);\n    }\n  }\n\n  // overwriting mask if some part of the observable is not wanted\n  if (like.shear_shear == 0)\n  {\n    const int M = like.Ntheta*2*tomo.shear_Npowerspectra;\n    for (int i=0; i<M; i++)\n    {\n      this->mask_(i) = 0;\n    }\n  }\n  if (like.shear_pos == 0)\n  {\n    const int N = 2*like.Ntheta*tomo.shear_Npowerspectra;\n    const int M = N + like.Ntheta*tomo.ggl_Npowerspectra;\n    for (int i=N; i<M; i++)\n    {\n      this->mask_(i) = 0;\n    }\n  }\n  if (like.pos_pos == 0)\n  {\n    const int N = like.Ntheta*(2*tomo.shear_Npowerspectra + tomo.ggl_Npowerspectra);\n    const int M = N + like.Ntheta*tomo.clustering_Npowerspectra;\n    for (int i=N; i<M; i++)\n    {\n      this->mask_(i) = 0;\n    }\n  }\n\n  this->mask_filename_ = MASK;\n  this->ndata_masked_ = arma::accu(this->mask_);\n\n  if(!(this->ndata_masked_>0))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: mask file {} left no data points after masking\",\n      \"set_mask\", MASK);\n    exit(1);\n  }\n  spdlog::info(\n    \"\\x1b[90m{}\\x1b[0m: mask file {} left {} non-masked elements after masking\",\n    \"set_mask\", MASK, this->ndata_masked_);\n\n  this->index_reduced_dim_.set_size(this->ndata_);\n  {\n    double j=0;\n    for(int i=0; i<this->ndata_; i++)\n    {\n      if(this->get_mask(i) > 0)\n      {\n        this->index_reduced_dim_(i) = j;\n        j++;\n      }\n      else\n      {\n        this->index_reduced_dim_(i) = -1;\n      }\n    }\n    if(j != this->ndata_masked_)\n    {\n      spdlog::critical(\n       \"\\x1b[90m{}\\x1b[0m: logical error, internal inconsistent mask operation\",\n       \"set_mask\");\n      exit(1);\n    }\n  }\n\n  this->is_mask_set_ = true;\n}\n\nvoid ima::RealData::set_data(std::string DATA)\n{\n  if (!(this->is_mask_set_))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\", \"set_data\",\n      \"mask\");\n    exit(1);\n  }\n\n  this->data_masked_.set_size(this->ndata_);\n  this->data_filename_ = DATA;\n  this->data_masked_reduced_dim_.set_size(this->ndata_masked_);\n\n  arma::Mat<double> table = ima::read_table(DATA);\n\n  for(int i=0; i<like.Ndata; i++)\n  {\n    this->data_masked_(i) = table(i,1);\n    this->data_masked_(i) *= this->get_mask(i);\n\n    if(this->get_mask(i) == 1)\n    {\n      if(this->get_index_reduced_dim(i) < 0)\n      {\n        spdlog::critical(\"\\x1b[90m{}\\x1b[0m: logical error, internal\"\n          \" inconsistent mask operation\", \"set_data\");\n        exit(1);\n      }\n\n      this->data_masked_reduced_dim_(this->get_index_reduced_dim(i)) =\n        this->data_masked_(i);\n    }\n  }\n\n  this->is_data_set_ = true;\n}\n\nvoid ima::RealData::set_inv_cov(std::string COV)\n{\n  if (!(this->is_mask_set_))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"set_inv_cov\",\n      \"mask\"\n    );\n    exit(1);\n  }\n\n  arma::Mat<double> table = ima::read_table(COV); // this reads cov!\n\n  this->cov_masked_.set_size(this->ndata_, this->ndata_);\n  this->cov_masked_.zeros();\n\n  this->inv_cov_masked_.set_size(this->ndata_, this->ndata_);\n  this->inv_cov_masked_.zeros();\n\n  switch (table.n_cols)\n  {\n    case 3:\n    {\n      for (int i=0; i<static_cast<int>(table.n_rows); i++)\n      {\n        const int j = static_cast<int>(table(i,0));\n        const int k = static_cast<int>(table(i,1));\n\n        this->cov_masked_(j,k) = table(i,2);\n        this->inv_cov_masked_(j,k) = table(i,2);\n\n        if (j!=k)\n        {\n          // apply mask to off-diagonal covariance elements\n          this->cov_masked_(j,k) *= this->get_mask(j);\n          this->cov_masked_(j,k) *= this->get_mask(k);\n\n          this->inv_cov_masked_(j,k) *= this->get_mask(j);\n          this->inv_cov_masked_(j,k) *= this->get_mask(k);\n\n          // m(i,j) = m(j,i)\n          this->cov_masked_(k,j) = this->cov_masked_(j,k);\n          this->inv_cov_masked_(k,j) = this->inv_cov_masked_(j,k);\n        }\n      };\n      break;\n    }\n    case 4:\n    {\n      for (int i=0; i<static_cast<int>(table.n_rows); i++)\n      {\n        const int j = static_cast<int>(table(i,0));\n        const int k = static_cast<int>(table(i,1));\n\n        this->cov_masked_(j,k) = table(i,2) + table(i,3);\n        this->inv_cov_masked_(j,k) = table(i,2) + table(i,3);\n\n        if (j!=k)\n        {\n          // apply mask to off-diagonal covariance elements\n          this->cov_masked_(j,k) *= this->get_mask(j);\n          this->cov_masked_(j,k) *= this->get_mask(k);\n\n          this->inv_cov_masked_(j,k) *= this->get_mask(j);\n          this->inv_cov_masked_(j,k) *= this->get_mask(k);\n\n          // m(i,j) = m(j,i)\n          this->cov_masked_(k,j) = this->cov_masked_(j,k);\n          this->inv_cov_masked_(k,j) = this->inv_cov_masked_(j,k);\n        }\n      };\n      break;\n    }\n    case 10:\n    {\n      for (int i=0; i<static_cast<int>(table.n_rows); i++)\n      {\n        const int j = static_cast<int>(table(i,0));\n        const int k = static_cast<int>(table(i,1));\n\n        this->cov_masked_(j,k) = table(i,8) + table(i,9);\n        this->inv_cov_masked_(j,k) = table(i,8) + table(i,9);\n\n        if (j!=k)\n        {\n          // apply mask to off-diagonal covariance elements\n          this->cov_masked_(j,k) *= this->get_mask(j);\n          this->cov_masked_(j,k) *= this->get_mask(k);\n\n          this->inv_cov_masked_(j,k) *= this->get_mask(j);\n          this->inv_cov_masked_(j,k) *= this->get_mask(k);\n\n          // m(i,j) = m(j,i)\n          this->cov_masked_(k,j) = this->cov_masked_(j,k);\n          this->inv_cov_masked_(k,j) = this->inv_cov_masked_(j,k);\n        }\n      }\n      break;\n    }\n    default:\n      spdlog::critical(\"{}: data format for covariance file = {} is invalid\",\n        \"set_inv_cov\", COV);\n      exit(1);\n  }\n\n  this->inv_cov_masked_ = arma::inv(this->inv_cov_masked_);\n\n  // apply mask again, to make sure numerical errors in matrix\n  // inversion don't cause problems...\n  // also, set diagonal elements corresponding to datavector elements\n  // outside mask to zero, so that these elements don't contribute to chi2\n  for (int i=0; i<this->ndata_; i++)\n  {\n    this->inv_cov_masked_(i,i) *= this->get_mask(i)*this->get_mask(i);\n    for (int j=0; j<i; j++)\n    {\n      this->inv_cov_masked_(i,j) *= this->get_mask(i)*this->get_mask(j);\n      this->inv_cov_masked_(j,i) = this->inv_cov_masked_(i,j);\n    }\n  };\n  this->cov_filename_ = COV;\n  this->is_inv_cov_set_ = true;\n\n  this->cov_masked_reduced_dim_.set_size(this->ndata_masked_,\n    this->ndata_masked_);\n\n  this->inv_cov_masked_reduced_dim_.set_size(this->ndata_masked_,\n    this->ndata_masked_);\n\n  for(int i=0; i<this->ndata_; i++)\n  {\n    for(int j=0; j<this->ndata_; j++)\n    {\n      if((this->mask_(i)>0.99) && (this->mask_(j)>0.99))\n      {\n        if(this->get_index_reduced_dim(i) < 0)\n        {\n          spdlog::critical(\"\\x1b[90m{}\\x1b[0m: logical error, internal\"\n            \" inconsistent mask operation\", \"set_inv_cov\");\n          exit(1);\n        }\n        if(this->get_index_reduced_dim(j) < 0)\n        {\n          spdlog::critical(\"\\x1b[90m{}\\x1b[0m: logical error, internal\"\n            \" inconsistent mask operation\", \"set_inv_cov\");\n          exit(1);\n        }\n\n        this->cov_masked_reduced_dim_(this->get_index_reduced_dim(i),\n          this->get_index_reduced_dim(j)) = this->cov_masked_(i,j);\n\n        this->inv_cov_masked_reduced_dim_(this->get_index_reduced_dim(i),\n          this->get_index_reduced_dim(j)) = this->inv_cov_masked_(i,j);\n      }\n    }\n  }\n}\n\narma::Col<int> ima::RealData::get_mask() const\n{\n  return this->mask_;\n}\n\nint ima::RealData::get_mask(const int ci) const\n{\n  if (ci > like.Ndata || ci < 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: index i = {} is not valid (min = {}, max = {})\",\n      \"get_mask\", ci, 0.0, like.Ndata);\n    exit(1);\n  }\n\n  return this->mask_(ci);\n}\n\nint ima::RealData::get_ndim() const\n{\n  return this->ndata_;\n}\n\nint ima::RealData::get_nreduced_dim() const\n{\n  return this->ndata_masked_;\n}\n\nint ima::RealData::get_index_reduced_dim(const int ci) const\n{\n  if (ci > like.Ndata || ci < 0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: index i = {} is not valid\"\n      \" (min = {}, max = {})\", \"get_index_reduced_dim\", ci, 0.0, like.Ndata);\n    exit(1);\n  }\n\n  return this->index_reduced_dim_(ci);\n}\n\narma::Col<double> ima::RealData::get_data_masked() const\n{\n  return this->data_masked_;\n}\n\ndouble ima::RealData::get_data_masked(const int ci) const\n{\n  if (ci > like.Ndata || ci < 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: index i = {} is not valid (min = {}, max = {})\",\n      \"get_data_masked\", ci, 0, like.Ndata);\n    exit(1);\n  }\n\n  return this->data_masked_(ci);\n}\n\narma::Col<double> ima::RealData::get_data_masked_reduced_dim() const\n{\n  return this->data_masked_reduced_dim_;\n}\n\ndouble ima::RealData::get_data_masked_reduced_dim(const int ci) const\n{\n  if (ci > like.Ndata || ci < 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: index i = {} is not valid (min = {}, max = {})\",\n      \"get_data_masked_reduced_dim\", ci, 0, like.Ndata);\n    exit(1);\n  }\n\n  return this->data_masked_reduced_dim_(ci);\n}\n\narma::Mat<double> ima::RealData::get_inverse_covariance_masked() const\n{\n  return this->inv_cov_masked_;\n}\n\ndouble ima::RealData::get_inverse_covariance_masked(const int ci,\nconst int cj) const\n{\n  if (ci > like.Ndata || ci < 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: index i = {} is not valid (min = {}, max = {})\",\n      \"get_inverse_covariance_masked\", ci, 0.0, like.Ndata);\n    exit(1);\n  }\n  if (cj > like.Ndata || cj < 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: index j = {} is not valid (min = {}, max = {})\",\n      \"get_inverse_covariance_masked\", cj, 0.0, like.Ndata);\n    exit(1);\n  }\n\n  return this->inv_cov_masked_(ci, cj);\n}\n\narma::Mat<double> ima::RealData::get_inverse_covariance_masked_reduced_dim() const\n{\n  return this->inv_cov_masked_reduced_dim_;\n}\n\ndouble ima::RealData::get_inverse_covariance_masked_reduced_dim(const int ci,\nconst int cj) const\n{\n  if (ci > like.Ndata || ci < 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: index i = {} is not valid (min = {}, max = {})\",\n      \"get_inverse_covariance_masked_reduced_dim\", ci, 0.0, like.Ndata);\n    exit(1);\n  }\n  if (cj > like.Ndata || cj < 0)\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: index j = {} is not valid (min = {}, max = {})\",\n      \"get_inverse_covariance_masked_reduced_dim\", cj, 0.0, like.Ndata);\n    exit(1);\n  }\n\n  return this->inv_cov_masked_reduced_dim_(ci, cj);\n}\n\narma::Mat<double> ima::RealData::get_covariance_masked() const\n{\n  return this->cov_masked_;\n}\n\narma::Mat<double> ima::RealData::get_covariance_masked_reduced_dim() const\n{\n  return this->cov_masked_reduced_dim_;\n}\n\ndouble ima::RealData::get_chi2(std::vector<double> datavector) const\n{\n  if (!(this->is_data_set_))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"get_chi2\",\n      \"data_vector\"\n    );\n    exit(1);\n  }\n  if (!(this->is_mask_set_))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"get_chi2\",\n      \"mask\"\n    );\n    exit(1);\n  }\n  if (!(this->is_inv_cov_set_))\n  {\n    spdlog::critical(\n      \"\\x1b[90m{}\\x1b[0m: {} not set prior to this function call\",\n      \"get_chi2\",\n      \"inv_cov\"\n    );\n    exit(1);\n  }\n\n  double chi2 = 0.0;\n  for (int i=0; i<like.Ndata; i++)\n  {\n    if (this->get_mask(i))\n    {\n      const double x = datavector[i] - this->get_data_masked(i);\n      for (int j=0; j<like.Ndata; j++)\n      {\n        if (this->get_mask(j))\n        {\n          const double y = datavector[j] - this->get_data_masked(j);\n          chi2 += x*this->get_inverse_covariance_masked(i,j)*y;\n        }\n      }\n    }\n  }\n  if (chi2 < 0.0)\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: chi2 = {} (invalid)\", \"get_chi2\", chi2);\n    exit(1);\n  }\n  return chi2;\n}\n\nbool ima::RealData::is_mask_set() const\n{\n  return this->is_mask_set_;\n}\n\nbool ima::RealData::is_data_set() const\n{\n  return this->is_data_set_;\n}\n\nbool ima::RealData::is_inv_cov_set() const\n{\n  return this->is_inv_cov_set_;\n}\n\narma::Col<double> ima::RealData::get_expand_dim_from_masked_reduced_dim(\narma::Col<double> reduced_dim_vector) const\n{\n  if (this->ndata_masked_ != static_cast<int>(reduced_dim_vector.n_elem))\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: {} invalid input vector\",\n      \"get_expand_dim_from_masked_reduced_dim\"\n    );\n    exit(1);\n  }\n\n  arma::Col<double> vector;\n  vector.set_size(this->ndata_);\n  vector.zeros();\n\n  for(int i=0; i<this->ndata_; i++)\n  {\n    if(this->mask_(i) > 0.99)\n    {\n      if(this->get_index_reduced_dim(i) < 0)\n      {\n        spdlog::critical(\"\\x1b[90m{}\\x1b[0m: logical error, internal \"\n        \"inconsistent mask operation\",\n        \"get_expand_dim_from_masked_reduced_dim\");\n        exit(1);\n      }\n\n      vector(i) = reduced_dim_vector(this->get_index_reduced_dim(i));\n    }\n  }\n\n  return vector;\n}\n\n// ----------------------------------------------------------------------------\n// CLASS PointMass MEMBER FUNCTIONS\n// THERE ARE \"C\" WRAPS FOR MOST OF THESE FUNCTIONS\n// ----------------------------------------------------------------------------\n\nvoid ima::PointMass::set_pm_vector(std::vector<double> pm)\n{\n  this->pm_ = pm;\n  return;\n}\n\nstd::vector<double> ima::PointMass::get_pm_vector() const\n{\n  return this->pm_;\n}\n\ndouble ima::PointMass::get_pm(const int zl, const int zs,\nconst double theta) const\n{\n  constexpr double G_over_c2 = 1.6e-23;\n  const double a_lens = 1.0/(1.0 + zmean(zl));\n  const double chi_lens = chi(a_lens);\n\n  return 4*G_over_c2*this->pm_[zl]*1.e+13*g_tomo(a_lens, zs)/(theta*theta)/\n    (chi_lens*a_lens);\n}\n\n// ----------------------------------------------------------------------------\n// CLASS BaryonScenario MEMBER FUNCTIONS\n// THERE ARE \"C\" WRAPS FOR MOST OF THESE FUNCTIONS\n// ----------------------------------------------------------------------------\n\nint ima::BaryonScenario::nscenarios() const\n{\n  return this->nscenarios_;\n}\n\nvoid ima::BaryonScenario::set_scenarios(std::string scenarios)\n{\n  std::vector<std::string> lines;\n  lines.reserve(50);\n\n  // Second: Split file into lines\n  boost::trim_if(scenarios, boost::is_any_of(\"\\t \"));\n  boost::trim_if(scenarios, boost::is_any_of(\"\\n\"));\n\n  if (scenarios.empty())\n  {\n    spdlog::critical(\"\\x1b[90m{}\\x1b[0m: invalid string input (empty)\",\n      \"init_baryon_pca_scenarios\");\n    exit(1);\n  }\n\n  boost::split(lines, scenarios, boost::is_any_of(\"/\"),\n    boost::token_compress_on);\n\n  this->nscenarios_ = lines.size();\n\n  for(int i=0; i<this->nscenarios_; i++)\n  {\n    this->scenarios_[i] = lines[i];\n  }\n\n  return;\n}\n\nstd::string ima::BaryonScenario::get_scenario(const int i) const\n{\n  return this->scenarios_.at(i);\n}\n\n// ----------------------------------------------------------------------------\n// ---------------------------- PYTHON WRAPPER --------------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ---------------------------- PYTHON WRAPPER --------------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ---------------------------- PYTHON WRAPPER --------------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ---------------------------- PYTHON WRAPPER --------------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ---------------------------- PYTHON WRAPPER --------------------------------\n// ----------------------------------------------------------------------------\n\n// ----------------------------------------------------------------------------\n// ---------------------------- PYTHON WRAPPER --------------------------------\n// ----------------------------------------------------------------------------\n\n\nPYBIND11_MODULE(cosmolike_lsst_y1_interface, m)\n{\n  m.doc() = \"CosmoLike Interface for LSST-Y1 3x2 Module\";\n\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n  // INIT FUNCTIONS\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n\n  m.def(\"initial_setup\",\n    &cpp_initial_setup,\n    \"Initialize Many Cosmolike Variables to their Default Values\"\n  );\n\n  m.def(\"init_probes\",\n    &cpp_init_probes,\n    \"Init Probes (cosmic shear or 2x2pt or 3x2pt...)\",\n    py::arg(\"possible_probes\")\n  );\n\n  m.def(\"init_survey_parameters\",\n    &cpp_init_survey,\n    \"Init Survey Parameters\",\n    py::arg(\"surveyname\"),\n    py::arg(\"area\"),\n    py::arg(\"sigma_e\")\n  );\n\n  m.def(\"init_cosmo_runmode\",\n    &cpp_init_cosmo_runmode,\n    \"Init Run Mode\",\n    py::arg(\"is_linear\")\n  );\n\n  m.def(\"init_baryons_contamination\",\n    &cpp_init_baryons_contamination,\n    \"Add baryonic simulations to power spectrum as contamination\",\n    py::arg(\"use_baryonic_simulations_contamination\"),\n    py::arg(\"which_baryonic_simulations_contamination\")\n  );\n\n  m.def(\"init_IA\",\n    &cpp_init_IA,\n    \"Init IA related options\",\n    py::arg(\"ia_model\")\n  );\n\n  m.def(\"init_binning\",\n    &cpp_init_binning,\n    \"Init Bining related variables\",\n    py::arg(\"Ntheta\"),\n    py::arg(\"theta_min_arcmin\"),\n    py::arg(\"theta_max_arcmin\")\n  );\n\n  m.def(\"init_data_real\",\n    &cpp_init_data_real,\n    \"Init covariance, mask and data vector by providing the file names that\"\n    \"hold their values\",\n    py::arg(\"COV\"),\n    py::arg(\"MASK\"),\n    py::arg(\"DATA\")\n  );\n\n  m.def(\"init_lens_sample\",\n    &cpp_init_lens_sample,\n    \"Init Lens Sample\",\n    py::arg(\"multihisto_file\"),\n    py::arg(\"Ntomo\"),\n    py::arg(\"ggl_cut\")\n  );\n\n  m.def(\"init_source_sample\",\n    &cpp_init_source_sample,\n    \"Init Source Sample\",\n    py::arg(\"multihisto_file\"),\n    py::arg(\"Ntomo\")\n  );\n\n  m.def(\"init_size_data_vector\",\n    &cpp_init_size_data_vector,\n    \"Init Size Data Vector\"\n  );\n\n  m.def(\"init_linear_power_spectrum\",\n    &cpp_init_linear_power_spectrum,\n    \"Load Linear Matter Power Spectrum from Cobaya to Cosmolike\",\n    py::arg(\"log10k\"),\n    py::arg(\"z\"),\n    py::arg(\"lnP\")\n  );\n\n  m.def(\"init_non_linear_power_spectrum\",\n    &cpp_init_non_linear_power_spectrum,\n    \"Load Matter Power Spectrum from Cobaya to Cosmolike\",\n    py::arg(\"log10k\"),\n    py::arg(\"z\"),\n    py::arg(\"lnP\")\n  );\n\n  m.def(\"init_growth\",\n    &cpp_init_growth,\n    \"Load Growth Factor from Cobaya to Cosmolike\",\n    py::arg(\"z\"),\n    py::arg(\"G\")\n  );\n\n  m.def(\"init_distances\",\n    &cpp_init_distances,\n    \"Load chi(z) from Cobaya to Cosmolike\",\n    py::arg(\"z\"),\n    py::arg(\"chi\")\n  );\n\n  m.def(\"init_baryon_pca_scenarios\",\n    &cpp_init_baryon_pca_scenarios,\n    \"Init scenario selection to generate baryonic PCA\",\n    py::arg(\"scenarios\")\n  );\n\n  m.def(\"init_accuracy_boost\",\n    &cpp_init_accuracy_boost,\n    \"Init Accuracy and Sampling Boost (can slow down Cosmolike a lot)\",\n    py::arg(\"accuracy_boost\"),\n    py::arg(\"sampling_boost\"),\n    py::arg(\"integration_accuracy\")\n  );\n\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n  // SET FUNCTIONS\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n\n  m.def(\"set_nuisance_ia\",\n    &cpp_set_nuisance_ia,\n    \"Set Nuisance IA Parameters\",\n    py::arg(\"A1\"),\n    py::arg(\"A2\"),\n    py::arg(\"B_TA\")\n  );\n\n  m.def(\"set_nuisance_bias\",\n    &cpp_set_nuisance_bias,\n    \"Set Nuisance Bias Parameters\",\n    py::arg(\"B1\"),\n    py::arg(\"B2\"),\n    py::arg(\"B_MAG\")\n  );\n\n  m.def(\"set_nuisance_shear_calib\",\n    &cpp_set_nuisance_shear_calib,\n    \"Set Shear Calibration Parameters\",\n    py::arg(\"M\")\n  );\n\n  m.def(\"set_nuisance_clustering_photoz\",\n    &cpp_set_nuisance_clustering_photoz,\n    \"Set Clustering Shear Photo-Z Parameters\",\n    py::arg(\"bias\")\n  );\n\n  m.def(\"set_nuisance_shear_photoz\",\n    &cpp_set_nuisance_shear_photoz,\n    \"Set Shear Photo-z Parameters\",\n    py::arg(\"bias\")\n  );\n\n  m.def(\"set_cosmological_parameters\",\n    &cpp_set_cosmological_parameters,\n    \"Set Cosmological Parameters\",\n    py::arg(\"omega_matter\"),\n    py::arg(\"hubble\"),\n    py::arg(\"is_cached\")\n  );\n\n  m.def(\"set_point_mass\",\n    &cpp_set_pm,\n    py::arg(\"PMV\")\n  );\n\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n  // GET FUNCTIONS\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n\n  m.def(\"get_covariance_masked\",\n    &cpp_get_covariance_masked,\n    \"Get Masked Covariance Matrix - masked dimensions are filled w/ zeros\"\n  );\n\n  m.def(\"get_covariance_masked_reduced_dim\",\n    &cpp_get_covariance_masked_reduced_dim,\n    \"Get Masked Covariance Matrix - it does not to contain masked dimensions\"\n  );\n\n  m.def(\"get_ndim\", &cpp_get_ndim, \"Get number of data points\");\n\n  m.def(\"get_nreduced_dim\", &cpp_get_nreduced_dim,\n    \"Get number of non-masked points\"\n  );\n\n  m.def(\"get_baryon_pca_scenario_name\", &cpp_get_baryon_pca_scenario_name,\n    \"Get jth scenario name selected to generate baryonic PCA\", py::arg(\"i\"));\n\n  m.def(\"get_baryon_pca_nscenarios\",\n    &cpp_get_baryon_pca_nscenarios,\n    \"Get number of scenarios selected to generate baryonic PCA\"\n  );\n\n  m.def(\"get_expand_dim_from_masked_reduced_dim\",\n    &cpp_get_expand_dim_from_masked_reduced_dim,\n    \"Get expanded vector (w/ zeros on masked dim) from masked reduced dim vector\"\n  );\n\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n  // COMPUTE FUNCTIONS\n  // --------------------------------------------------------------------\n  // --------------------------------------------------------------------\n\n  m.def(\"compute_data_vector_masked\",\n    &cpp_compute_data_vector_masked,\n    \"Get theoretical data vector - masked dimensions are filled w/ zeros\"\n  );\n\n  m.def(\"compute_data_vector_masked_reduced_dim\",\n    &cpp_compute_data_vector_masked_reduced_dim,\n    \"Get theoretical data vector - it does not to contain masked dimensions\"\n  );\n\n  m.def(\"compute_chi2\",\n    &cpp_compute_chi2,\n    \"Get chi^2\",\n    py::arg(\"datavector\")\n  );\n\n  m.def(\"compute_baryon_ratio\",\n    &cpp_compute_baryon_ratio,\n    \"Get Baryon Ratio\"\n  );\n\n  m.def(\"reset_baryionic_struct\",\n    &cpp_reset_baryionic_struct,\n    \"reset baryionic struct to original values\"\n  );\n}\n\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n\nint main()\n{\n  cpp_initial_setup();\n  std::cout << \"GOODBYE\" << std::endl;\n  exit(1);\n}\n", "meta": {"hexsha": "cdf5f3688b6dc9116819b7acf06dfe603925d0f7", "size": 62771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "interface/interface.cpp", "max_stars_repo_name": "SBU-UNESP-2022-COCOA/cocoa_lsst_y1", "max_stars_repo_head_hexsha": "ffc4449d893ab2d2db35bf9fab0f8aac43f9e92b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interface/interface.cpp", "max_issues_repo_name": "SBU-UNESP-2022-COCOA/cocoa_lsst_y1", "max_issues_repo_head_hexsha": "ffc4449d893ab2d2db35bf9fab0f8aac43f9e92b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interface/interface.cpp", "max_forks_repo_name": "SBU-UNESP-2022-COCOA/cocoa_lsst_y1", "max_forks_repo_head_hexsha": "ffc4449d893ab2d2db35bf9fab0f8aac43f9e92b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-23T07:14:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T02:25:06.000Z", "avg_line_length": 28.085458613, "max_line_length": 95, "alphanum_fraction": 0.5570725335, "num_tokens": 18370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.058345836108865935, "lm_q1q2_score": 0.027351980204474026}}
{"text": "/**\n * @author Tiago de Freitas Pereira <tiago.pereira@idiap.ch>\n * @date Wed 04 Feb 14:15:00 2015\n *\n * @brief Python API for bob::learn::em\n *\n * Copyright (C) 2011-2014 Idiap Research Institute, Martigny, Switzerland\n */\n\n#include \"main.h\"\n#include <boost/make_shared.hpp>\n#include <boost/assign.hpp>\n\n//Defining maps for each initializatio method\nstatic const std::map<std::string, bob::learn::em::PLDATrainer::InitFMethod> FMethod = boost::assign::map_list_of\n  (\"RANDOM_F\",  bob::learn::em::PLDATrainer::RANDOM_F)\n  (\"BETWEEN_SCATTER\", bob::learn::em::PLDATrainer::BETWEEN_SCATTER)\n  ;\n\nstatic const std::map<std::string, bob::learn::em::PLDATrainer::InitGMethod> GMethod = boost::assign::map_list_of\n  (\"RANDOM_G\",  bob::learn::em::PLDATrainer::RANDOM_G)\n  (\"WITHIN_SCATTER\", bob::learn::em::PLDATrainer::WITHIN_SCATTER)\n  ;\n\nstatic const std::map<std::string, bob::learn::em::PLDATrainer::InitSigmaMethod> SigmaMethod = boost::assign::map_list_of\n  (\"RANDOM_SIGMA\",  bob::learn::em::PLDATrainer::RANDOM_SIGMA)\n  (\"VARIANCE_G\", bob::learn::em::PLDATrainer::VARIANCE_G)\n  (\"CONSTANT\", bob::learn::em::PLDATrainer::CONSTANT)\n  (\"VARIANCE_DATA\", bob::learn::em::PLDATrainer::VARIANCE_DATA)\n  ;\n\n//String to type\nstatic inline bob::learn::em::PLDATrainer::InitFMethod string2FMethod(const std::string& o){\n  auto it = FMethod.find(o);\n  if (it == FMethod.end()) throw std::runtime_error(\"The given FMethod '\" + o + \"' is not known; choose one of ('RANDOM_F','BETWEEN_SCATTER')\");\n  else return it->second;\n}\n\nstatic inline bob::learn::em::PLDATrainer::InitGMethod string2GMethod(const std::string& o){\n  auto it = GMethod.find(o);\n  if (it == GMethod.end()) throw std::runtime_error(\"The given GMethod '\" + o + \"' is not known; choose one of ('RANDOM_G','WITHIN_SCATTER')\");\n  else return it->second;\n}\n\nstatic inline bob::learn::em::PLDATrainer::InitSigmaMethod string2SigmaMethod(const std::string& o){\n  auto it = SigmaMethod.find(o);\n  if (it == SigmaMethod.end()) throw std::runtime_error(\"The given SigmaMethod '\" + o + \"' is not known; choose one of ('RANDOM_SIGMA','VARIANCE_G', 'CONSTANT', 'VARIANCE_DATA')\");\n  else return it->second;\n}\n\n//Type to string\nstatic inline const std::string& FMethod2string(bob::learn::em::PLDATrainer::InitFMethod o){\n  for (auto it = FMethod.begin(); it != FMethod.end(); ++it) if (it->second == o) return it->first;\n  throw std::runtime_error(\"The given FMethod type is not known\");\n}\n\nstatic inline const std::string& GMethod2string(bob::learn::em::PLDATrainer::InitGMethod o){\n  for (auto it = GMethod.begin(); it != GMethod.end(); ++it) if (it->second == o) return it->first;\n  throw std::runtime_error(\"The given GMethod type is not known\");\n}\n\nstatic inline const std::string& SigmaMethod2string(bob::learn::em::PLDATrainer::InitSigmaMethod o){\n  for (auto it = SigmaMethod.begin(); it != SigmaMethod.end(); ++it) if (it->second == o) return it->first;\n  throw std::runtime_error(\"The given SigmaMethod type is not known\");\n}\n\n\nstatic inline bool f(PyObject* o){return o != 0 && PyObject_IsTrue(o) > 0;}  /* converts PyObject to bool and returns false if object is NULL */\n\ntemplate <int N>\nint list_as_vector(PyObject* list, std::vector<blitz::Array<double,N> >& vec)\n{\n  for (int i=0; i<PyList_GET_SIZE(list); i++)\n  {\n    PyBlitzArrayObject* blitz_object;\n    if (!PyArg_Parse(PyList_GetItem(list, i), \"O&\", &PyBlitzArray_Converter, &blitz_object)){\n      PyErr_Format(PyExc_RuntimeError, \"Expected numpy array object\");\n      return -1;\n    }\n    auto blitz_object_ = make_safe(blitz_object);\n    vec.push_back(*PyBlitzArrayCxx_AsBlitz<double,N>(blitz_object));\n  }\n  return 0;\n}\n\n\ntemplate <int N>\nstatic PyObject* vector_as_list(const std::vector<blitz::Array<double,N> >& vec)\n{\n  PyObject* list = PyList_New(vec.size());\n  for(size_t i=0; i<vec.size(); i++){\n    blitz::Array<double,N> numpy_array = vec[i];\n    PyObject* numpy_py_object = PyBlitzArrayCxx_AsNumpy(numpy_array);\n    PyList_SET_ITEM(list, i, numpy_py_object);\n  }\n  return list;\n}\n\n\n/******************************************************************/\n/************ Constructor Section *********************************/\n/******************************************************************/\n\n\nstatic auto PLDATrainer_doc = bob::extension::ClassDoc(\n  BOB_EXT_MODULE_PREFIX \".PLDATrainer\",\n  \"This class can be used to train the :math:`F`, :math:`G` and \"\n  \" :math:`\\\\Sigma` matrices and the mean vector :math:`\\\\mu` of a PLDA model.\"\n  \"References: [ElShafey2014]_ [PrinceElder2007]_ [LiFu2012]_ \",\n  \"\"\n).add_constructor(\n  bob::extension::FunctionDoc(\n    \"__init__\",\n    \"Default constructor.\\n Initializes a new PLDA trainer. The \"\n    \"training stage will place the resulting components in the \"\n    \"PLDABase.\",\n    \"\",\n    true\n  )\n  .add_prototype(\"use_sum_second_order\",\"\")\n  .add_prototype(\"other\",\"\")\n  .add_prototype(\"\",\"\")\n\n  .add_parameter(\"other\", \":py:class:`bob.learn.em.PLDATrainer`\", \"A PLDATrainer object to be copied.\")\n  .add_parameter(\"use_sum_second_order\", \"bool\", \"\")\n);\n\nstatic int PyBobLearnEMPLDATrainer_init_copy(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n\n  char** kwlist = PLDATrainer_doc.kwlist(1);\n  PyBobLearnEMPLDATrainerObject* o;\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O!\", kwlist, &PyBobLearnEMPLDATrainer_Type, &o)){\n    PLDATrainer_doc.print_usage();\n    return -1;\n  }\n\n  self->cxx.reset(new bob::learn::em::PLDATrainer(*o->cxx));\n  return 0;\n}\n\n\nstatic int PyBobLearnEMPLDATrainer_init_bool(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n\n  char** kwlist = PLDATrainer_doc.kwlist(0);\n  PyObject* use_sum_second_order = Py_False;\n\n  //Parsing the input argments\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"|O!\", kwlist, &PyBool_Type, &use_sum_second_order))\n    return -1;\n\n  self->cxx.reset(new bob::learn::em::PLDATrainer(f(use_sum_second_order)));\n  return 0;\n}\n\n\nstatic int PyBobLearnEMPLDATrainer_init(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n  BOB_TRY\n\n  // get the number of command line arguments\n  int nargs = (args?PyTuple_Size(args):0) + (kwargs?PyDict_Size(kwargs):0);\n\n  if(nargs==0)\n    return PyBobLearnEMPLDATrainer_init_bool(self, args, kwargs);\n  else if(nargs==1){\n    //Reading the input argument\n    PyObject* arg = 0;\n    if (PyTuple_Size(args))\n      arg = PyTuple_GET_ITEM(args, 0);\n    else {\n      PyObject* tmp = PyDict_Values(kwargs);\n      auto tmp_ = make_safe(tmp);\n      arg = PyList_GET_ITEM(tmp, 0);\n    }\n\n    if(PyBobLearnEMPLDATrainer_Check(arg))\n      // If the constructor input is PLDATrainer object\n      return PyBobLearnEMPLDATrainer_init_copy(self, args, kwargs);\n    else\n      return PyBobLearnEMPLDATrainer_init_bool(self, args, kwargs);\n  }\n  else{\n    PyErr_Format(PyExc_RuntimeError, \"number of arguments mismatch - %s requires only 0 or 1 argument, but you provided %d (see help)\", Py_TYPE(self)->tp_name, nargs);\n    PLDATrainer_doc.print_usage();\n    return -1;\n  }\n\n  BOB_CATCH_MEMBER(\"cannot create PLDATrainer\", -1)\n  return 0;\n}\n\n\nstatic void PyBobLearnEMPLDATrainer_delete(PyBobLearnEMPLDATrainerObject* self) {\n  self->cxx.reset();\n  Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\n\nint PyBobLearnEMPLDATrainer_Check(PyObject* o) {\n  return PyObject_IsInstance(o, reinterpret_cast<PyObject*>(&PyBobLearnEMPLDATrainer_Type));\n}\n\n\nstatic PyObject* PyBobLearnEMPLDATrainer_RichCompare(PyBobLearnEMPLDATrainerObject* self, PyObject* other, int op) {\n  BOB_TRY\n\n  if (!PyBobLearnEMPLDATrainer_Check(other)) {\n    PyErr_Format(PyExc_TypeError, \"cannot compare `%s' with `%s'\", Py_TYPE(self)->tp_name, Py_TYPE(other)->tp_name);\n    return 0;\n  }\n  auto other_ = reinterpret_cast<PyBobLearnEMPLDATrainerObject*>(other);\n  switch (op) {\n    case Py_EQ:\n      if (*self->cxx==*other_->cxx) Py_RETURN_TRUE; else Py_RETURN_FALSE;\n    case Py_NE:\n      if (*self->cxx==*other_->cxx) Py_RETURN_FALSE; else Py_RETURN_TRUE;\n    default:\n      Py_INCREF(Py_NotImplemented);\n      return Py_NotImplemented;\n  }\n  BOB_CATCH_MEMBER(\"cannot compare PLDATrainer objects\", 0)\n}\n\n\n/******************************************************************/\n/************ Variables Section ***********************************/\n/******************************************************************/\n\nstatic auto z_second_order = bob::extension::VariableDoc(\n  \"z_second_order\",\n  \"array_like <float, 3D>\",\n  \"\",\n  \"\"\n);\nPyObject* PyBobLearnEMPLDATrainer_get_z_second_order(PyBobLearnEMPLDATrainerObject* self, void*){\n  BOB_TRY\n  //return PyBlitzArrayCxx_AsConstNumpy(self->cxx->getZSecondOrder());\n  return vector_as_list(self->cxx->getZSecondOrder());\n  BOB_CATCH_MEMBER(\"z_second_order could not be read\", 0)\n}\n\n\nstatic auto z_second_order_sum = bob::extension::VariableDoc(\n  \"z_second_order_sum\",\n  \"array_like <float, 2D>\",\n  \"\",\n  \"\"\n);\nPyObject* PyBobLearnEMPLDATrainer_get_z_second_order_sum(PyBobLearnEMPLDATrainerObject* self, void*){\n  BOB_TRY\n  return PyBlitzArrayCxx_AsConstNumpy(self->cxx->getZSecondOrderSum());\n  BOB_CATCH_MEMBER(\"z_second_order_sum could not be read\", 0)\n}\n\n\nstatic auto z_first_order = bob::extension::VariableDoc(\n  \"z_first_order\",\n  \"array_like <float, 2D>\",\n  \"\",\n  \"\"\n);\nPyObject* PyBobLearnEMPLDATrainer_get_z_first_order(PyBobLearnEMPLDATrainerObject* self, void*){\n  BOB_TRY\n  //return PyBlitzArrayCxx_AsConstNumpy(self->cxx->getZFirstOrder());\n  return vector_as_list(self->cxx->getZFirstOrder());\n  BOB_CATCH_MEMBER(\"z_first_order could not be read\", 0)\n}\n\n\n/***** init_f_method *****/\nstatic auto init_f_method = bob::extension::VariableDoc(\n  \"init_f_method\",\n  \"str\",\n  \"The method used for the initialization of :math:`$F$`.\",\n  \"Possible values are: ('RANDOM_F', 'BETWEEN_SCATTER')\"\n);\nPyObject* PyBobLearnEMPLDATrainer_getFMethod(PyBobLearnEMPLDATrainerObject* self, void*) {\n  BOB_TRY\n  return Py_BuildValue(\"s\", FMethod2string(self->cxx->getInitFMethod()).c_str());\n  BOB_CATCH_MEMBER(\"init_f_method method could not be read\", 0)\n}\nint PyBobLearnEMPLDATrainer_setFMethod(PyBobLearnEMPLDATrainerObject* self, PyObject* value, void*) {\n  BOB_TRY\n\n  if (!PyString_Check(value)){\n    PyErr_Format(PyExc_RuntimeError, \"%s %s expects an str\", Py_TYPE(self)->tp_name, init_f_method.name());\n    return -1;\n  }\n  self->cxx->setInitFMethod(string2FMethod(PyString_AS_STRING(value)));\n\n  return 0;\n  BOB_CATCH_MEMBER(\"init_f_method method could not be set\", -1)\n}\n\n\n/***** init_g_method *****/\nstatic auto init_g_method = bob::extension::VariableDoc(\n  \"init_g_method\",\n  \"str\",\n  \"The method used for the initialization of :math:`$G$`.\",\n  \"Possible values are: ('RANDOM_G', 'WITHIN_SCATTER')\"\n);\nPyObject* PyBobLearnEMPLDATrainer_getGMethod(PyBobLearnEMPLDATrainerObject* self, void*) {\n  BOB_TRY\n  return Py_BuildValue(\"s\", GMethod2string(self->cxx->getInitGMethod()).c_str());\n  BOB_CATCH_MEMBER(\"init_g_method method could not be read\", 0)\n}\nint PyBobLearnEMPLDATrainer_setGMethod(PyBobLearnEMPLDATrainerObject* self, PyObject* value, void*) {\n  BOB_TRY\n\n  if (!PyString_Check(value)){\n    PyErr_Format(PyExc_RuntimeError, \"%s %s expects an str\", Py_TYPE(self)->tp_name, init_g_method.name());\n    return -1;\n  }\n  self->cxx->setInitGMethod(string2GMethod(PyString_AS_STRING(value)));\n\n  return 0;\n  BOB_CATCH_MEMBER(\"init_g_method method could not be set\", -1)\n}\n\n/***** init_sigma_method *****/\nstatic auto init_sigma_method = bob::extension::VariableDoc(\n  \"init_sigma_method\",\n  \"str\",\n  \"The method used for the initialization of :math:`$\\\\Sigma$`.\",\n  \"Possible values are: ('RANDOM_SIGMA', 'VARIANCE_G', 'CONSTANT', 'VARIANCE_DATA')\"\n);\nPyObject* PyBobLearnEMPLDATrainer_getSigmaMethod(PyBobLearnEMPLDATrainerObject* self, void*) {\n  BOB_TRY\n  return Py_BuildValue(\"s\", SigmaMethod2string(self->cxx->getInitSigmaMethod()).c_str());\n  BOB_CATCH_MEMBER(\"init_sigma_method method could not be read\", 0)\n}\nint PyBobLearnEMPLDATrainer_setSigmaMethod(PyBobLearnEMPLDATrainerObject* self, PyObject* value, void*) {\n  BOB_TRY\n\n  if (!PyString_Check(value)){\n    PyErr_Format(PyExc_RuntimeError, \"%s %s expects an str\", Py_TYPE(self)->tp_name, init_sigma_method.name());\n    return -1;\n  }\n  self->cxx->setInitSigmaMethod(string2SigmaMethod(PyString_AS_STRING(value)));\n\n  return 0;\n  BOB_CATCH_MEMBER(\"init_sigma_method method could not be set\", -1)\n}\n\n\nstatic auto use_sum_second_order = bob::extension::VariableDoc(\n  \"use_sum_second_order\",\n  \"bool\",\n  \"Tells whether the second order statistics are stored during the training procedure, or only their sum.\",\n  \"\"\n);\nPyObject* PyBobLearnEMPLDATrainer_getUseSumSecondOrder(PyBobLearnEMPLDATrainerObject* self, void*){\n  BOB_TRY\n  return Py_BuildValue(\"O\",self->cxx->getUseSumSecondOrder()?Py_True:Py_False);\n  BOB_CATCH_MEMBER(\"use_sum_second_order could not be read\", 0)\n}\nint PyBobLearnEMPLDATrainer_setUseSumSecondOrder(PyBobLearnEMPLDATrainerObject* self, PyObject* value, void*) {\n  BOB_TRY\n\n  if (!PyBool_Check(value)){\n    PyErr_Format(PyExc_RuntimeError, \"%s %s expects an str\", Py_TYPE(self)->tp_name, use_sum_second_order.name());\n    return -1;\n  }\n  self->cxx->setUseSumSecondOrder(f(value));\n\n  return 0;\n  BOB_CATCH_MEMBER(\"use_sum_second_order method could not be set\", -1)\n}\n\n\n\nstatic PyGetSetDef PyBobLearnEMPLDATrainer_getseters[] = {\n  {\n   z_first_order.name(),\n   (getter)PyBobLearnEMPLDATrainer_get_z_first_order,\n   0,\n   z_first_order.doc(),\n   0\n  },\n  {\n   z_second_order_sum.name(),\n   (getter)PyBobLearnEMPLDATrainer_get_z_second_order_sum,\n   0,\n   z_second_order_sum.doc(),\n   0\n  },\n  {\n   z_second_order.name(),\n   (getter)PyBobLearnEMPLDATrainer_get_z_second_order,\n   0,\n   z_second_order.doc(),\n   0\n  },\n  {\n   init_f_method.name(),\n   (getter)PyBobLearnEMPLDATrainer_getFMethod,\n   (setter)PyBobLearnEMPLDATrainer_setFMethod,\n   init_f_method.doc(),\n   0\n  },\n  {\n   init_g_method.name(),\n   (getter)PyBobLearnEMPLDATrainer_getGMethod,\n   (setter)PyBobLearnEMPLDATrainer_setGMethod,\n   init_g_method.doc(),\n   0\n  },\n  {\n   init_sigma_method.name(),\n   (getter)PyBobLearnEMPLDATrainer_getSigmaMethod,\n   (setter)PyBobLearnEMPLDATrainer_setSigmaMethod,\n   init_sigma_method.doc(),\n   0\n  },\n  {\n   use_sum_second_order.name(),\n   (getter)PyBobLearnEMPLDATrainer_getUseSumSecondOrder,\n   (setter)PyBobLearnEMPLDATrainer_setUseSumSecondOrder,\n   use_sum_second_order.doc(),\n   0\n  },\n  {0}  // Sentinel\n};\n\n\n/******************************************************************/\n/************ Functions Section ***********************************/\n/******************************************************************/\n\n/*** initialize ***/\nstatic auto initialize = bob::extension::FunctionDoc(\n  \"initialize\",\n  \"Initialization before the EM steps\",\n  \"\",\n  true\n)\n.add_prototype(\"plda_base, data, [rng]\")\n.add_parameter(\"plda_base\", \":py:class:`bob.learn.em.PLDABase`\", \"PLDAMachine Object\")\n.add_parameter(\"data\", \"list\", \"\")\n.add_parameter(\"rng\", \":py:class:`bob.core.random.mt19937`\", \"The Mersenne Twister mt19937 random generator used for the initialization of subspaces/arrays before the EM loop.\");\nstatic PyObject* PyBobLearnEMPLDATrainer_initialize(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n  BOB_TRY\n\n  /* Parses input arguments in a single shot */\n  char** kwlist = initialize.kwlist(0);\n\n  PyBobLearnEMPLDABaseObject* plda_base = 0;\n  PyObject* data = 0;\n  PyBoostMt19937Object* rng = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O!O!|O!\", kwlist, &PyBobLearnEMPLDABase_Type, &plda_base,\n                                                                 &PyList_Type, &data,\n                                                                 &PyBoostMt19937_Type, &rng)) return 0;\n\n  std::vector<blitz::Array<double,2> > data_vector;\n  if(list_as_vector(data ,data_vector)==0){\n    if(rng){\n      self->cxx->setRng(rng->rng);\n    }\n\n    self->cxx->initialize(*plda_base->cxx, data_vector);\n  }\n  else\n    return 0;\n\n  BOB_CATCH_MEMBER(\"cannot perform the initialize method\", 0)\n\n  Py_RETURN_NONE;\n}\n\n\n/*** e_step ***/\nstatic auto e_step = bob::extension::FunctionDoc(\n  \"e_step\",\n  \"Expectation step before the EM steps\",\n  \"\",\n  true\n)\n.add_prototype(\"plda_base,data\")\n.add_parameter(\"plda_base\", \":py:class:`bob.learn.em.PLDABase`\", \"PLDAMachine Object\")\n.add_parameter(\"data\", \"list\", \"\");\nstatic PyObject* PyBobLearnEMPLDATrainer_e_step(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n  BOB_TRY\n\n  /* Parses input arguments in a single shot */\n  char** kwlist = e_step.kwlist(0);\n\n  PyBobLearnEMPLDABaseObject* plda_base = 0;\n  PyObject* data = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O!O!\", kwlist, &PyBobLearnEMPLDABase_Type, &plda_base,\n                                                                 &PyList_Type, &data)) return 0;\n\n  std::vector<blitz::Array<double,2> > data_vector;\n  if(list_as_vector(data ,data_vector)==0)\n    self->cxx->eStep(*plda_base->cxx, data_vector);\n  else\n    return 0;\n\n  BOB_CATCH_MEMBER(\"cannot perform the e_step method\", 0)\n\n  Py_RETURN_NONE;\n}\n\n\n/*** m_step ***/\nstatic auto m_step = bob::extension::FunctionDoc(\n  \"m_step\",\n  \"Maximization step \",\n  \"\",\n  true\n)\n.add_prototype(\"plda_base,data\")\n.add_parameter(\"plda_base\", \":py:class:`bob.learn.em.PLDABase`\", \"PLDAMachine Object\")\n.add_parameter(\"data\", \"list\", \"\");\nstatic PyObject* PyBobLearnEMPLDATrainer_m_step(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n  BOB_TRY\n\n  /* Parses input arguments in a single shot */\n  char** kwlist = m_step.kwlist(0);\n\n  PyBobLearnEMPLDABaseObject* plda_base = 0;\n  PyObject* data = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O!O!\", kwlist, &PyBobLearnEMPLDABase_Type, &plda_base,\n                                                                 &PyList_Type, &data)) return 0;\n\n  std::vector<blitz::Array<double,2> > data_vector;\n  if(list_as_vector(data ,data_vector)==0)\n    self->cxx->mStep(*plda_base->cxx, data_vector);\n  else\n    return 0;\n\n  BOB_CATCH_MEMBER(\"cannot perform the m_step method\", 0)\n\n  Py_RETURN_NONE;\n}\n\n\n/*** finalize ***/\nstatic auto finalize = bob::extension::FunctionDoc(\n  \"finalize\",\n  \"finalize before the EM steps\",\n  \"\",\n  true\n)\n.add_prototype(\"plda_base,data\")\n.add_parameter(\"plda_base\", \":py:class:`bob.learn.em.PLDABase`\", \"PLDAMachine Object\")\n.add_parameter(\"data\", \"list\", \"\");\nstatic PyObject* PyBobLearnEMPLDATrainer_finalize(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n  BOB_TRY\n\n  /* Parses input arguments in a single shot */\n  char** kwlist = finalize.kwlist(0);\n\n  PyBobLearnEMPLDABaseObject* plda_base = 0;\n  PyObject* data = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O!O!\", kwlist, &PyBobLearnEMPLDABase_Type, &plda_base,\n                                                                 &PyList_Type, &data)) return 0;\n\n  std::vector<blitz::Array<double,2> > data_vector;\n  if(list_as_vector(data ,data_vector)==0)\n    self->cxx->finalize(*plda_base->cxx, data_vector);\n  else\n    return 0;\n\n  BOB_CATCH_MEMBER(\"cannot perform the finalize method\", 0)\n\n  Py_RETURN_NONE;\n}\n\n\n\n/*** enroll ***/\nstatic auto enroll = bob::extension::FunctionDoc(\n  \"enroll\",\n  \"Main procedure for enrolling a PLDAMachine\",\n  \"\",\n  true\n)\n.add_prototype(\"plda_machine,data\")\n.add_parameter(\"plda_machine\", \":py:class:`bob.learn.em.PLDAMachine`\", \"PLDAMachine Object\")\n.add_parameter(\"data\", \"list\", \"\");\nstatic PyObject* PyBobLearnEMPLDATrainer_enroll(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwargs) {\n  BOB_TRY\n\n  /* Parses input arguments in a single shot */\n  char** kwlist = enroll.kwlist(0);\n\n  PyBobLearnEMPLDAMachineObject* plda_machine = 0;\n  PyBlitzArrayObject* data = 0;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"O!O&\", kwlist, &PyBobLearnEMPLDAMachine_Type, &plda_machine,\n                                                                 &PyBlitzArray_Converter, &data)) return 0;\n\n  auto data_ = make_safe(data);\n  self->cxx->enroll(*plda_machine->cxx, *PyBlitzArrayCxx_AsBlitz<double,2>(data));\n\n  BOB_CATCH_MEMBER(\"cannot perform the enroll method\", 0)\n\n  Py_RETURN_NONE;\n}\n\n\n/*** is_similar_to ***/\nstatic auto is_similar_to = bob::extension::FunctionDoc(\n  \"is_similar_to\",\n\n  \"Compares this PLDATrainer with the ``other`` one to be approximately the same.\",\n  \"The optional values ``r_epsilon`` and ``a_epsilon`` refer to the \"\n  \"relative and absolute precision for the ``weights``, ``biases`` \"\n  \"and any other values internal to this machine.\"\n)\n.add_prototype(\"other, [r_epsilon], [a_epsilon]\",\"output\")\n.add_parameter(\"other\", \":py:class:`bob.learn.em.PLDAMachine`\", \"A PLDAMachine object to be compared.\")\n.add_parameter(\"r_epsilon\", \"float\", \"Relative precision.\")\n.add_parameter(\"a_epsilon\", \"float\", \"Absolute precision.\")\n.add_return(\"output\",\"bool\",\"True if it is similar, otherwise false.\");\nstatic PyObject* PyBobLearnEMPLDATrainer_IsSimilarTo(PyBobLearnEMPLDATrainerObject* self, PyObject* args, PyObject* kwds) {\n\n  /* Parses input arguments in a single shot */\n  char** kwlist = is_similar_to.kwlist(0);\n\n  //PyObject* other = 0;\n  PyBobLearnEMPLDATrainerObject* other = 0;\n  double r_epsilon = 1.e-5;\n  double a_epsilon = 1.e-8;\n\n  if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O!|dd\", kwlist,\n        &PyBobLearnEMPLDATrainer_Type, &other,\n        &r_epsilon, &a_epsilon)){\n\n        is_similar_to.print_usage();\n        return 0;\n  }\n\n  if (self->cxx->is_similar_to(*other->cxx, r_epsilon, a_epsilon))\n    Py_RETURN_TRUE;\n  else\n    Py_RETURN_FALSE;\n}\n\n\n\nstatic PyMethodDef PyBobLearnEMPLDATrainer_methods[] = {\n  {\n    initialize.name(),\n    (PyCFunction)PyBobLearnEMPLDATrainer_initialize,\n    METH_VARARGS|METH_KEYWORDS,\n    initialize.doc()\n  },\n  {\n    e_step.name(),\n    (PyCFunction)PyBobLearnEMPLDATrainer_e_step,\n    METH_VARARGS|METH_KEYWORDS,\n    e_step.doc()\n  },\n  {\n    m_step.name(),\n    (PyCFunction)PyBobLearnEMPLDATrainer_m_step,\n    METH_VARARGS|METH_KEYWORDS,\n    m_step.doc()\n  },\n  {\n    finalize.name(),\n    (PyCFunction)PyBobLearnEMPLDATrainer_finalize,\n    METH_VARARGS|METH_KEYWORDS,\n    finalize.doc()\n  },\n  {\n    enroll.name(),\n    (PyCFunction)PyBobLearnEMPLDATrainer_enroll,\n    METH_VARARGS|METH_KEYWORDS,\n    enroll.doc()\n  },\n  {\n    is_similar_to.name(),\n    (PyCFunction)PyBobLearnEMPLDATrainer_IsSimilarTo,\n    METH_VARARGS|METH_KEYWORDS,\n    is_similar_to.doc()\n  },\n  {0} /* Sentinel */\n};\n\n\n/******************************************************************/\n/************ Module Section **************************************/\n/******************************************************************/\n\n// Define the Gaussian type struct; will be initialized later\nPyTypeObject PyBobLearnEMPLDATrainer_Type = {\n  PyVarObject_HEAD_INIT(0,0)\n  0\n};\n\nbool init_BobLearnEMPLDATrainer(PyObject* module)\n{\n  // initialize the type struct\n  PyBobLearnEMPLDATrainer_Type.tp_name      = PLDATrainer_doc.name();\n  PyBobLearnEMPLDATrainer_Type.tp_basicsize = sizeof(PyBobLearnEMPLDATrainerObject);\n  PyBobLearnEMPLDATrainer_Type.tp_flags     = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;//Enable the class inheritance;\n  PyBobLearnEMPLDATrainer_Type.tp_doc       = PLDATrainer_doc.doc();\n\n  // set the functions\n  PyBobLearnEMPLDATrainer_Type.tp_new          = PyType_GenericNew;\n  PyBobLearnEMPLDATrainer_Type.tp_init         = reinterpret_cast<initproc>(PyBobLearnEMPLDATrainer_init);\n  PyBobLearnEMPLDATrainer_Type.tp_dealloc      = reinterpret_cast<destructor>(PyBobLearnEMPLDATrainer_delete);\n  PyBobLearnEMPLDATrainer_Type.tp_richcompare = reinterpret_cast<richcmpfunc>(PyBobLearnEMPLDATrainer_RichCompare);\n  PyBobLearnEMPLDATrainer_Type.tp_methods      = PyBobLearnEMPLDATrainer_methods;\n  PyBobLearnEMPLDATrainer_Type.tp_getset       = PyBobLearnEMPLDATrainer_getseters;\n  //PyBobLearnEMPLDATrainer_Type.tp_call         = reinterpret_cast<ternaryfunc>(PyBobLearnEMPLDATrainer_compute_likelihood);\n\n\n  // check that everything is fine\n  if (PyType_Ready(&PyBobLearnEMPLDATrainer_Type) < 0) return false;\n\n  // add the type to the module\n  Py_INCREF(&PyBobLearnEMPLDATrainer_Type);\n  return PyModule_AddObject(module, \"PLDATrainer\", (PyObject*)&PyBobLearnEMPLDATrainer_Type) >= 0;\n}\n", "meta": {"hexsha": "49842a3b086f4c3e865812a69a71eaedf553924d", "size": 24136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/em/plda_trainer.cpp", "max_stars_repo_name": "bioidiap/bob.learn.em", "max_stars_repo_head_hexsha": "e4676f6b15ad6d1a13abf6212bfbc62b2bdb142d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-02-05T03:55:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T11:52:15.000Z", "max_issues_repo_path": "bob/learn/em/plda_trainer.cpp", "max_issues_repo_name": "bioidiap/bob.learn.em", "max_issues_repo_head_hexsha": "e4676f6b15ad6d1a13abf6212bfbc62b2bdb142d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2015-03-25T17:47:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-22T14:19:59.000Z", "max_forks_repo_path": "bob/learn/em/plda_trainer.cpp", "max_forks_repo_name": "bioidiap/bob.learn.em", "max_forks_repo_head_hexsha": "e4676f6b15ad6d1a13abf6212bfbc62b2bdb142d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:00:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T13:53:51.000Z", "avg_line_length": 33.4293628809, "max_line_length": 180, "alphanum_fraction": 0.6922439509, "num_tokens": 6697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.05749328243396118, "lm_q1q2_score": 0.02717612462320523}}
{"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    LevenbergMarquardtOptimizer.cpp\n * @brief   \n * @author  Richard Roberts\n * @author  Luca Carlone\n * @date  Feb 26, 2012\n */\n\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/linear/linearExceptions.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/VectorValues.h>\n#include <gtsam/linear/Errors.h>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/range/adaptor/map.hpp>\n#include <string>\n#include <cmath>\n#include <fstream>\n\nusing namespace std;\n\nnamespace gtsam {\n\nusing boost::adaptors::map_values;\n\n/* ************************************************************************* */\nLevenbergMarquardtParams::VerbosityLM LevenbergMarquardtParams::verbosityLMTranslator(\n    const std::string &src) const {\n  std::string s = src;\n  boost::algorithm::to_upper(s);\n  if (s == \"SILENT\")\n    return LevenbergMarquardtParams::SILENT;\n  if (s == \"LAMBDA\")\n    return LevenbergMarquardtParams::LAMBDA;\n  if (s == \"TRYLAMBDA\")\n    return LevenbergMarquardtParams::TRYLAMBDA;\n  if (s == \"TRYCONFIG\")\n    return LevenbergMarquardtParams::TRYCONFIG;\n  if (s == \"TRYDELTA\")\n    return LevenbergMarquardtParams::TRYDELTA;\n  if (s == \"DAMPED\")\n    return LevenbergMarquardtParams::DAMPED;\n\n  /* default is silent */\n  return LevenbergMarquardtParams::SILENT;\n}\n\n/* ************************************************************************* */\nstd::string LevenbergMarquardtParams::verbosityLMTranslator(\n    VerbosityLM value) const {\n  std::string s;\n  switch (value) {\n  case LevenbergMarquardtParams::SILENT:\n    s = \"SILENT\";\n    break;\n  case LevenbergMarquardtParams::TERMINATION:\n    s = \"TERMINATION\";\n    break;\n  case LevenbergMarquardtParams::LAMBDA:\n    s = \"LAMBDA\";\n    break;\n  case LevenbergMarquardtParams::TRYLAMBDA:\n    s = \"TRYLAMBDA\";\n    break;\n  case LevenbergMarquardtParams::TRYCONFIG:\n    s = \"TRYCONFIG\";\n    break;\n  case LevenbergMarquardtParams::TRYDELTA:\n    s = \"TRYDELTA\";\n    break;\n  case LevenbergMarquardtParams::DAMPED:\n    s = \"DAMPED\";\n    break;\n  default:\n    s = \"UNDEFINED\";\n    break;\n  }\n  return s;\n}\n\n/* ************************************************************************* */\nvoid LevenbergMarquardtParams::print(const std::string& str) const {\n  NonlinearOptimizerParams::print(str);\n  std::cout << \"              lambdaInitial: \" << lambdaInitial << \"\\n\";\n  std::cout << \"               lambdaFactor: \" << lambdaFactor << \"\\n\";\n  std::cout << \"           lambdaUpperBound: \" << lambdaUpperBound << \"\\n\";\n  std::cout << \"           lambdaLowerBound: \" << lambdaLowerBound << \"\\n\";\n  std::cout << \"           minModelFidelity: \" << minModelFidelity << \"\\n\";\n  std::cout << \"            diagonalDamping: \" << diagonalDamping << \"\\n\";\n  std::cout << \"               min_diagonal: \" << min_diagonal_ << \"\\n\";\n  std::cout << \"               max_diagonal: \" << max_diagonal_ << \"\\n\";\n  std::cout << \"                verbosityLM: \"\n      << verbosityLMTranslator(verbosityLM) << \"\\n\";\n  std::cout.flush();\n}\n\n/* ************************************************************************* */\nGaussianFactorGraph::shared_ptr LevenbergMarquardtOptimizer::linearize() const {\n  return graph_.linearize(state_.values);\n}\n\n/* ************************************************************************* */\nvoid LevenbergMarquardtOptimizer::increaseLambda() {\n  if (params_.useFixedLambdaFactor_) {\n    state_.lambda *= params_.lambdaFactor;\n  } else {\n    state_.lambda *= params_.lambdaFactor;\n    params_.lambdaFactor *= 2.0;\n  }\n  params_.reuse_diagonal_ = true;\n}\n\n/* ************************************************************************* */\nvoid LevenbergMarquardtOptimizer::decreaseLambda(double stepQuality) {\n\n  if (params_.useFixedLambdaFactor_) {\n    state_.lambda /= params_.lambdaFactor;\n  } else {\n    // CHECK_GT(step_quality, 0.0);\n    state_.lambda *= std::max(1.0 / 3.0, 1.0 - pow(2.0 * stepQuality - 1.0, 3));\n    params_.lambdaFactor = 2.0;\n  }\n  state_.lambda = std::max(params_.lambdaLowerBound, state_.lambda);\n  params_.reuse_diagonal_ = false;\n\n}\n\n/* ************************************************************************* */\nGaussianFactorGraph::shared_ptr LevenbergMarquardtOptimizer::buildDampedSystem(\n    const GaussianFactorGraph& linear) {\n\n  gttic(damp);\n  if (params_.verbosityLM >= LevenbergMarquardtParams::DAMPED)\n    cout << \"building damped system with lambda \" << state_.lambda << endl;\n\n  // Only retrieve diagonal vector when reuse_diagonal = false\n  if (params_.diagonalDamping && params_.reuse_diagonal_ == false) {\n    state_.hessianDiagonal = linear.hessianDiagonal();\n    BOOST_FOREACH(Vector& v, state_.hessianDiagonal | map_values) {\n      for (int aa = 0; aa < v.size(); aa++) {\n        v(aa) = std::min(std::max(v(aa), params_.min_diagonal_),\n            params_.max_diagonal_);\n        v(aa) = sqrt(v(aa));\n      }\n    }\n  } // reuse diagonal\n\n  // for each of the variables, add a prior\n  double sigma = 1.0 / std::sqrt(state_.lambda);\n  GaussianFactorGraph::shared_ptr dampedPtr = linear.cloneToPtr();\n  GaussianFactorGraph &damped = (*dampedPtr);\n  damped.reserve(damped.size() + state_.values.size());\n  if (params_.diagonalDamping) {\n    BOOST_FOREACH(const VectorValues::KeyValuePair& key_vector, state_.hessianDiagonal) {\n      // Fill in the diagonal of A with diag(hessian)\n      try {\n        Matrix A = Eigen::DiagonalMatrix<double, Eigen::Dynamic>(\n            state_.hessianDiagonal.at(key_vector.first));\n        size_t dim = key_vector.second.size();\n        Vector b = Vector::Zero(dim);\n        SharedDiagonal model = noiseModel::Isotropic::Sigma(dim, sigma);\n        damped += boost::make_shared<JacobianFactor>(key_vector.first, A, b,\n            model);\n      } catch (std::exception e) {\n        // Don't attempt any damping if no key found in diagonal\n        continue;\n      }\n    }\n  } else {\n    // Straightforward damping:\n    BOOST_FOREACH(const Values::KeyValuePair& key_value, state_.values) {\n      size_t dim = key_value.value.dim();\n      Matrix A = Matrix::Identity(dim, dim);\n      Vector b = Vector::Zero(dim);\n      SharedDiagonal model = noiseModel::Isotropic::Sigma(dim, sigma);\n      damped += boost::make_shared<JacobianFactor>(key_value.key, A, b, model);\n    }\n  }\n  gttoc(damp);\n  return dampedPtr;\n}\n\n/* ************************************************************************* */\n// Log current error/lambda to file\ninline void LevenbergMarquardtOptimizer::writeLogFile(double currentError){\n  if (!params_.logFile.empty()) {\n    ofstream os(params_.logFile.c_str(), ios::app);\n    boost::posix_time::ptime currentTime = boost::posix_time::microsec_clock::universal_time();\n    os << /*inner iterations*/ state_.totalNumberInnerIterations << \",\"\n        << 1e-6 * (currentTime - state_.startTime).total_microseconds() << \",\"\n        << /*current error*/ currentError << \",\" << state_.lambda << \",\"\n        << /*outer iterations*/ state_.iterations << endl;\n  }\n}\n\n/* ************************************************************************* */\nvoid LevenbergMarquardtOptimizer::iterate() {\n\n  gttic(LM_iterate);\n\n  // Pull out parameters we'll use\n  const NonlinearOptimizerParams::Verbosity nloVerbosity = params_.verbosity;\n  const LevenbergMarquardtParams::VerbosityLM lmVerbosity = params_.verbosityLM;\n\n  // Linearize graph\n  if (lmVerbosity >= LevenbergMarquardtParams::DAMPED)\n    cout << \"linearizing = \" << endl;\n  GaussianFactorGraph::shared_ptr linear = linearize();\n\n  if(state_.totalNumberInnerIterations==0) // write initial error\n    writeLogFile(state_.error);\n\n  // Keep increasing lambda until we make make progress\n  while (true) {\n\n    if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n      cout << \"trying lambda = \" << state_.lambda << endl;\n\n    // Build damped system for this lambda (adds prior factors that make it like gradient descent)\n    GaussianFactorGraph::shared_ptr dampedSystemPtr = buildDampedSystem(*linear);\n    GaussianFactorGraph &dampedSystem = (*dampedSystemPtr);\n\n    // Try solving\n    double modelFidelity = 0.0;\n    bool step_is_successful = false;\n    bool stopSearchingLambda = false;\n    double newError;\n    Values newValues;\n    VectorValues delta;\n\n    bool systemSolvedSuccessfully;\n    try {\n      delta = solve(dampedSystem, state_.values, params_);\n      systemSolvedSuccessfully = true;\n    } catch (IndeterminantLinearSystemException) {\n      systemSolvedSuccessfully = false;\n    }\n\n    if (systemSolvedSuccessfully) {\n      params_.reuse_diagonal_ = true;\n\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n        cout << \"linear delta norm = \" << delta.norm() << endl;\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYDELTA)\n        delta.print(\"delta\");\n\n      // cost change in the linearized system (old - new)\n      double newlinearizedError = linear->error(delta);\n\n      double linearizedCostChange = state_.error - newlinearizedError;\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n              cout << \"newlinearizedError = \" << newlinearizedError <<\n              \"  linearizedCostChange = \" << linearizedCostChange << endl;\n\n      if (linearizedCostChange >= 0) { // step is valid\n        // update values\n        gttic(retract);\n        newValues = state_.values.retract(delta);\n        gttoc(retract);\n\n        // compute new error\n        gttic(compute_error);\n        if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n          cout << \"calculating error:\" << endl;\n        newError = graph_.error(newValues);\n        gttoc(compute_error);\n\n        if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n          cout << \"old error (\" << state_.error\n              << \") new (tentative) error (\" << newError << \")\" << endl;\n\n        // cost change in the original, nonlinear system (old - new)\n        double costChange = state_.error - newError;\n\n        if (linearizedCostChange > 1e-20) { // the (linear) error has to decrease to satisfy this condition\n          // fidelity of linearized model VS original system between\n          modelFidelity = costChange / linearizedCostChange;\n          // if we decrease the error in the nonlinear system and modelFidelity is above threshold\n          step_is_successful = modelFidelity > params_.minModelFidelity;\n          if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n            cout << \"modelFidelity: \" << modelFidelity << endl;\n        } // else we consider the step non successful and we either increase lambda or stop if error change is small\n\n        double minAbsoluteTolerance = params_.relativeErrorTol * state_.error;\n        // if the change is small we terminate\n        if (fabs(costChange) < minAbsoluteTolerance){\n          if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n                        cout << \"fabs(costChange)=\"<<fabs(costChange) << \"  minAbsoluteTolerance=\"<< minAbsoluteTolerance\n                        << \" (relativeErrorTol=\" << params_.relativeErrorTol << \")\" << endl;\n          stopSearchingLambda = true;\n        }\n      }\n    }\n\n    ++state_.totalNumberInnerIterations;\n\n    if (step_is_successful) { // we have successfully decreased the cost and we have good modelFidelity\n      state_.values.swap(newValues);\n      state_.error = newError;\n      decreaseLambda(modelFidelity);\n      writeLogFile(state_.error);\n      break;\n    } else if (!stopSearchingLambda) { // we failed to solved the system or we had no decrease in cost\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n        cout << \"increasing lambda\" << endl;\n      increaseLambda();\n      writeLogFile(state_.error);\n\n      // check if lambda is too big\n      if (state_.lambda >= params_.lambdaUpperBound) {\n        if (nloVerbosity >= NonlinearOptimizerParams::TERMINATION)\n          cout << \"Warning:  Levenberg-Marquardt giving up because \"\n              \"cannot decrease error with maximum lambda\" << endl;\n        break;\n      }\n    } else { // the change in the cost is very small and it is not worth trying bigger lambdas\n      writeLogFile(state_.error);\n      if (lmVerbosity >= LevenbergMarquardtParams::TRYLAMBDA)\n              cout << \"Levenberg-Marquardt: stopping as relative cost reduction is small\" << endl;\n      break;\n    }\n  } // end while\n\n  // Increment the iteration counter\n  ++state_.iterations;\n}\n\n/* ************************************************************************* */\nLevenbergMarquardtParams LevenbergMarquardtOptimizer::ensureHasOrdering(\n    LevenbergMarquardtParams params, const NonlinearFactorGraph& graph) const {\n  if (!params.ordering)\n    params.ordering = Ordering::COLAMD(graph);\n  return params;\n}\n\n} /* namespace gtsam */\n\n", "meta": {"hexsha": "08961db860a9d771ef25dbff11d476f321a2905d", "size": 13060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/nonlinear/LevenbergMarquardtOptimizer.cpp", "max_stars_repo_name": "Ellon/gtsam-3.1.0", "max_stars_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T21:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T12:14:04.000Z", "max_issues_repo_path": "gtsam/nonlinear/LevenbergMarquardtOptimizer.cpp", "max_issues_repo_name": "Ellon/gtsam-3.1.0", "max_issues_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/nonlinear/LevenbergMarquardtOptimizer.cpp", "max_forks_repo_name": "Ellon/gtsam-3.1.0", "max_forks_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3142857143, "max_line_length": 121, "alphanum_fraction": 0.6209800919, "num_tokens": 3252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.057493273551888456, "lm_q1q2_score": 0.027176120424796217}}
{"text": "//\r\n//  Copyright (c) 2018-2019, Cem Bassoy, cem.bassoy@gmail.com\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//  The authors gratefully acknowledge the support of\r\n//  Fraunhofer IOSB, Ettlingen, Germany\r\n//\r\n\r\n#ifndef BOOST_UBLAS_TENSOR_OPERATORS_COMPARISON_HPP\r\n#define BOOST_UBLAS_TENSOR_OPERATORS_COMPARISON_HPP\r\n\r\n#include <boost/numeric/ublas/tensor/expression.hpp>\r\n#include <boost/numeric/ublas/tensor/expression_evaluation.hpp>\r\n#include <type_traits>\r\n#include <functional>\r\n\r\nnamespace boost::numeric::ublas {\r\ntemplate<class element_type, class storage_format, class storage_type>\r\nclass tensor;\r\n}\r\n\r\nnamespace boost::numeric::ublas::detail {\r\n\r\ntemplate<class T, class F, class A, class BinaryPred>\r\nbool compare(tensor<T,F,A> const& lhs, tensor<T,F,A> const& rhs, BinaryPred pred)\r\n{\r\n\r\n\tif(lhs.extents() != rhs.extents()){\r\n\t\tif constexpr(!std::is_same<BinaryPred,std::equal_to<>>::value && !std::is_same<BinaryPred,std::not_equal_to<>>::value)\r\n\t\t\tthrow std::runtime_error(\"Error in boost::numeric::ublas::detail::compare: cannot compare tensors with different shapes.\");\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\r\n\tif constexpr(std::is_same<BinaryPred,std::greater<>>::value || std::is_same<BinaryPred,std::less<>>::value)\r\n\t\tif(lhs.empty())\r\n\t\t\treturn false;\r\n\r\n\tfor(auto i = 0u; i < lhs.size(); ++i)\r\n\t\tif(!pred(lhs(i), rhs(i)))\r\n\t\t\treturn false;\r\n\treturn true;\r\n}\r\n\r\ntemplate<class T, class F, class A, class UnaryPred>\r\nbool compare(tensor<T,F,A> const& rhs, UnaryPred pred)\r\n{\r\n\tfor(auto i = 0u; i < rhs.size(); ++i)\r\n\t\tif(!pred(rhs(i)))\r\n\t\t\treturn false;\r\n\treturn true;\r\n}\r\n\r\n\r\ntemplate<class T, class L, class R, class BinaryPred>\r\nbool compare(tensor_expression<T,L> const& lhs, tensor_expression<T,R> const& rhs, BinaryPred pred)\r\n{\r\n\tconstexpr bool lhs_is_tensor = std::is_same<T,L>::value;\r\n\tconstexpr bool rhs_is_tensor = std::is_same<T,R>::value;\r\n\r\n\tif constexpr (lhs_is_tensor && rhs_is_tensor)\r\n\t\treturn compare(static_cast<T const&>( lhs ), static_cast<T const&>( rhs ), pred);\r\n\telse if constexpr (lhs_is_tensor && !rhs_is_tensor)\r\n\t\treturn compare(static_cast<T const&>( lhs ), T( rhs ), pred);\r\n\telse if constexpr (!lhs_is_tensor && rhs_is_tensor)\r\n\t\treturn compare(T( lhs ), static_cast<T const&>( rhs ), pred);\r\n\telse\r\n\t\treturn compare(T( lhs ), T( rhs ), pred);\r\n\r\n}\r\n\r\ntemplate<class T, class D, class UnaryPred>\r\nbool compare(tensor_expression<T,D> const& expr, UnaryPred pred)\r\n{\r\n\tif constexpr (std::is_same<T,D>::value)\r\n\t\treturn compare(static_cast<T const&>( expr ), pred);\r\n\telse\r\n\t\treturn compare(T( expr ), pred);\r\n}\r\n\r\n}\r\n\r\n\r\ntemplate<class T, class L, class R>\r\nbool operator==( boost::numeric::ublas::detail::tensor_expression<T,L> const& lhs,\r\n\t\t\t\t\t\t\t\t boost::numeric::ublas::detail::tensor_expression<T,R> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, rhs, std::equal_to<>{} );\r\n}\r\ntemplate<class T, class L, class R>\r\nauto operator!=(boost::numeric::ublas::detail::tensor_expression<T,L> const& lhs,\r\n\t\t\t\t\t\t\t\tboost::numeric::ublas::detail::tensor_expression<T,R> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, rhs, std::not_equal_to<>{}  );\r\n}\r\ntemplate<class T, class L, class R>\r\nauto operator< ( boost::numeric::ublas::detail::tensor_expression<T,L> const& lhs,\r\n\t\t\t\t\t\t\t\t boost::numeric::ublas::detail::tensor_expression<T,R> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, rhs, std::less<>{} );\r\n}\r\ntemplate<class T, class L, class R>\r\nauto operator<=( boost::numeric::ublas::detail::tensor_expression<T,L> const& lhs,\r\n\t\t\t\t\t\t\t\t boost::numeric::ublas::detail::tensor_expression<T,R> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, rhs, std::less_equal<>{} );\r\n}\r\ntemplate<class T, class L, class R>\r\nauto operator> ( boost::numeric::ublas::detail::tensor_expression<T,L> const& lhs,\r\n\t\t\t\t\t\t\t\t boost::numeric::ublas::detail::tensor_expression<T,R> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, rhs, std::greater<>{} );\r\n}\r\ntemplate<class T, class L, class R>\r\nauto operator>=( boost::numeric::ublas::detail::tensor_expression<T,L> const& lhs,\r\n\t\t\t\t\t\t\t\t boost::numeric::ublas::detail::tensor_expression<T,R> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, rhs, std::greater_equal<>{} );\r\n}\r\n\r\n\r\n\r\n\r\n\r\ntemplate<class T, class D>\r\nbool operator==( typename T::const_reference lhs, boost::numeric::ublas::detail::tensor_expression<T,D> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( rhs, [lhs](auto const& r){ return lhs == r; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator!=( typename T::const_reference lhs, boost::numeric::ublas::detail::tensor_expression<T,D> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( rhs, [lhs](auto const& r){ return lhs != r; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator< ( typename T::const_reference lhs, boost::numeric::ublas::detail::tensor_expression<T,D> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( rhs, [lhs](auto const& r){ return lhs <  r; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator<=( typename T::const_reference lhs, boost::numeric::ublas::detail::tensor_expression<T,D> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( rhs, [lhs](auto const& r){ return lhs <= r; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator> ( typename T::const_reference lhs, boost::numeric::ublas::detail::tensor_expression<T,D> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( rhs, [lhs](auto const& r){ return lhs >  r; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator>=( typename T::const_reference lhs, boost::numeric::ublas::detail::tensor_expression<T,D> const& rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( rhs, [lhs](auto const& r){ return lhs >= r; } );\r\n}\r\n\r\n\r\n\r\ntemplate<class T, class D>\r\nbool operator==( boost::numeric::ublas::detail::tensor_expression<T,D> const& lhs, typename T::const_reference rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, [rhs](auto const& l){ return l == rhs; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator!=( boost::numeric::ublas::detail::tensor_expression<T,D> const& lhs, typename T::const_reference rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, [rhs](auto const& l){ return l != rhs; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator< ( boost::numeric::ublas::detail::tensor_expression<T,D> const& lhs, typename T::const_reference rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, [rhs](auto const& l){ return l <  rhs; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator<=( boost::numeric::ublas::detail::tensor_expression<T,D> const& lhs, typename T::const_reference rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, [rhs](auto const& l){ return l <= rhs; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator> ( boost::numeric::ublas::detail::tensor_expression<T,D> const& lhs, typename T::const_reference rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, [rhs](auto const& l){ return l >  rhs; } );\r\n}\r\ntemplate<class T, class D>\r\nauto operator>=( boost::numeric::ublas::detail::tensor_expression<T,D> const& lhs, typename T::const_reference rhs) {\r\n\treturn boost::numeric::ublas::detail::compare( lhs, [rhs](auto const& l){ return l >= rhs; } );\r\n}\r\n\r\n\r\n#endif\r\n", "meta": {"hexsha": "d1047911d23826e992e1e50a5cd659464610c109", "size": 7397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/numeric/ublas/tensor/operators_comparison.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": 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": "deps/boost/include/boost/numeric/ublas/tensor/operators_comparison.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": 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": "deps/boost/include/boost/numeric/ublas/tensor/operators_comparison.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": 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.0284090909, "max_line_length": 127, "alphanum_fraction": 0.6867649047, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.06097518513095939, "lm_q1q2_score": 0.02716624588034821}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n// Contributors:\n//  * Kedar R. Bhat - C++11 compatibility.\n\n// Notes:\n//  * Any changes to this file should always be downstream from autodiff.cpp.\n//    C++17 is a higher-level language and is easier to maintain. For example, a number of functions which are\n//    lucidly read in autodiff.cpp are forced to be split into multiple structs/functions in this file for\n//    C++11.\n//  * Use of typename RootType and SizeType is a hack to prevent Visual Studio 2015 from compiling functions\n//    that are never called, that would otherwise produce compiler errors. Also forces functions to be inline.\n\n#ifndef BOOST_MATH_DIFFERENTIATION_AUTODIFF_HPP\n#error \\\n    \"Do not #include this file directly. This should only be #included by autodiff.hpp for C++11 compatibility.\"\n#endif\n\n#include <type_traits>\n#include <boost/math/tools/mp.hpp>\n\nnamespace boost {\nnamespace math {\n\nnamespace mp = tools::meta_programming;\n\nnamespace differentiation {\ninline namespace autodiff_v1 {\nnamespace detail {\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>::fvar(root_type const& ca, bool const is_variable) {\n  fvar_cpp11(is_fvar<RealType>{}, ca, is_variable);\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nvoid fvar<RealType, Order>::fvar_cpp11(std::true_type, RootType const& ca, bool const is_variable) {\n  v.front() = RealType(ca, is_variable);\n  if (0 < Order)\n    std::fill(v.begin() + 1, v.end(), static_cast<RealType>(0));\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nvoid fvar<RealType, Order>::fvar_cpp11(std::false_type, RootType const& ca, bool const is_variable) {\n  v.front() = ca;\n  if (0 < Order) {\n    v[1] = static_cast<root_type>(static_cast<int>(is_variable));\n    if (1 < Order)\n      std::fill(v.begin() + 2, v.end(), static_cast<RealType>(0));\n  }\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename... Orders>\nget_type_at<RealType, sizeof...(Orders)> fvar<RealType, Order>::at_cpp11(std::true_type,\n                                                                         size_t order,\n                                                                         Orders...) const {\n  return v.at(order);\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename... Orders>\nget_type_at<RealType, sizeof...(Orders)> fvar<RealType, Order>::at_cpp11(std::false_type,\n                                                                         size_t order,\n                                                                         Orders... orders) const {\n  return v.at(order).at(orders...);\n}\n\n// Can throw \"std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)\"\ntemplate <typename RealType, size_t Order>\ntemplate <typename... Orders>\nget_type_at<RealType, sizeof...(Orders)> fvar<RealType, Order>::at(size_t order, Orders... orders) const {\n  return at_cpp11(std::integral_constant<bool, sizeof...(orders) == 0>{}, order, orders...);\n}\n\ntemplate <typename T, typename... Ts>\nconstexpr T product(Ts...) {\n  return static_cast<T>(1);\n}\n\ntemplate <typename T, typename... Ts>\nconstexpr T product(T factor, Ts... factors) {\n  return factor * product<T>(factors...);\n}\n\n// Can throw \"std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)\"\ntemplate <typename RealType, size_t Order>\ntemplate <typename... Orders>\nget_type_at<fvar<RealType, Order>, sizeof...(Orders)> fvar<RealType, Order>::derivative(\n    Orders... orders) const {\n  static_assert(sizeof...(Orders) <= depth,\n                \"Number of parameters to derivative(...) cannot exceed fvar::depth.\");\n  return at(static_cast<size_t>(orders)...) *\n         product(boost::math::factorial<root_type>(static_cast<unsigned>(orders))...);\n}\n\ntemplate <typename RootType, typename Func>\nclass Curry {\n  Func const& f_;\n  size_t const i_;\n\n public:\n  template <typename SizeType>  // typename SizeType to force inline constructor.\n  Curry(Func const& f, SizeType i) : f_(f), i_(static_cast<std::size_t>(i)) {}\n  template <typename... Indices>\n  RootType operator()(Indices... indices) const {\n    using unsigned_t = typename std::make_unsigned<typename std::common_type<Indices>::type...>::type;\n    return f_(i_, static_cast<unsigned_t>(indices)...);\n  }\n};\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_coefficients(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  size_t i = order < order_sum ? order : order_sum;\n  using return_type = promote<fvar<RealType, Order>, Fvar, Fvars...>;\n  return_type accumulator = cr.apply_coefficients(\n      order - i, Curry<typename return_type::root_type, Func>(f, i), std::forward<Fvars>(fvars)...);\n  while (i--)\n    (accumulator *= epsilon) += cr.apply_coefficients(\n        order - i, Curry<typename return_type::root_type, Func>(f, i), std::forward<Fvars>(fvars)...);\n  return accumulator;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_coefficients_nonhorner(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  fvar<RealType, Order> epsilon_i = fvar<RealType, Order>(1);  // epsilon to the power of i\n  using return_type = promote<fvar<RealType, Order>, Fvar, Fvars...>;\n  return_type accumulator = cr.apply_coefficients_nonhorner(\n      order, Curry<typename return_type::root_type, Func>(f, 0), std::forward<Fvars>(fvars)...);\n  size_t const i_max = order < order_sum ? order : order_sum;\n  for (size_t i = 1; i <= i_max; ++i) {\n    epsilon_i = epsilon_i.epsilon_multiply(i - 1, 0, epsilon, 1, 0);\n    accumulator += epsilon_i.epsilon_multiply(\n        i,\n        0,\n        cr.apply_coefficients_nonhorner(\n            order - i, Curry<typename return_type::root_type, Func>(f, i), std::forward<Fvars>(fvars)...),\n        0,\n        0);\n  }\n  return accumulator;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_derivatives(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  size_t i = order < order_sum ? order : order_sum;\n  using return_type = promote<fvar<RealType, Order>, Fvar, Fvars...>;\n  return_type accumulator =\n      cr.apply_derivatives(\n          order - i, Curry<typename return_type::root_type, Func>(f, i), std::forward<Fvars>(fvars)...) /\n      factorial<root_type>(static_cast<unsigned>(i));\n  while (i--)\n    (accumulator *= epsilon) +=\n        cr.apply_derivatives(\n            order - i, Curry<typename return_type::root_type, Func>(f, i), std::forward<Fvars>(fvars)...) /\n        factorial<root_type>(static_cast<unsigned>(i));\n  return accumulator;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename Func, typename Fvar, typename... Fvars>\npromote<fvar<RealType, Order>, Fvar, Fvars...> fvar<RealType, Order>::apply_derivatives_nonhorner(\n    size_t const order,\n    Func const& f,\n    Fvar const& cr,\n    Fvars&&... fvars) const {\n  fvar<RealType, Order> const epsilon = fvar<RealType, Order>(*this).set_root(0);\n  fvar<RealType, Order> epsilon_i = fvar<RealType, Order>(1);  // epsilon to the power of i\n  using return_type = promote<fvar<RealType, Order>, Fvar, Fvars...>;\n  return_type accumulator = cr.apply_derivatives_nonhorner(\n      order, Curry<typename return_type::root_type, Func>(f, 0), std::forward<Fvars>(fvars)...);\n  size_t const i_max = order < order_sum ? order : order_sum;\n  for (size_t i = 1; i <= i_max; ++i) {\n    epsilon_i = epsilon_i.epsilon_multiply(i - 1, 0, epsilon, 1, 0);\n    accumulator += epsilon_i.epsilon_multiply(\n        i,\n        0,\n        cr.apply_derivatives_nonhorner(\n            order - i, Curry<typename return_type::root_type, Func>(f, i), std::forward<Fvars>(fvars)...) /\n            factorial<root_type>(static_cast<unsigned>(i)),\n        0,\n        0);\n  }\n  return accumulator;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename SizeType>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply_cpp11(std::true_type,\n                                                                    SizeType z0,\n                                                                    size_t isum0,\n                                                                    fvar<RealType, Order> const& cr,\n                                                                    size_t z1,\n                                                                    size_t isum1) const {\n  size_t const m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n  size_t const m1 = order_sum + isum1 < Order + z1 ? Order + z1 - (order_sum + isum1) : 0;\n  size_t const i_max = m0 + m1 < Order ? Order - (m0 + m1) : 0;\n  fvar<RealType, Order> retval = fvar<RealType, Order>();\n  for (size_t i = 0, j = Order; i <= i_max; ++i, --j)\n    retval.v[j] = epsilon_inner_product(z0, isum0, m0, cr, z1, isum1, m1, j);\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename SizeType>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply_cpp11(std::false_type,\n                                                                    SizeType z0,\n                                                                    size_t isum0,\n                                                                    fvar<RealType, Order> const& cr,\n                                                                    size_t z1,\n                                                                    size_t isum1) const {\n  using ssize_t = typename std::make_signed<std::size_t>::type;\n  RealType const zero(0);\n  size_t const m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n  size_t const m1 = order_sum + isum1 < Order + z1 ? Order + z1 - (order_sum + isum1) : 0;\n  size_t const i_max = m0 + m1 < Order ? Order - (m0 + m1) : 0;\n  fvar<RealType, Order> retval = fvar<RealType, Order>();\n  for (size_t i = 0, j = Order; i <= i_max; ++i, --j)\n    retval.v[j] = std::inner_product(\n        v.cbegin() + ssize_t(m0), v.cend() - ssize_t(i + m1), cr.v.crbegin() + ssize_t(i + m0), zero);\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply(size_t z0,\n                                                              size_t isum0,\n                                                              fvar<RealType, Order> const& cr,\n                                                              size_t z1,\n                                                              size_t isum1) const {\n  return epsilon_multiply_cpp11(is_fvar<RealType>{}, z0, isum0, cr, z1, isum1);\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename SizeType>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply_cpp11(std::true_type,\n                                                                    SizeType z0,\n                                                                    size_t isum0,\n                                                                    root_type const& ca) const {\n  fvar<RealType, Order> retval(*this);\n  size_t const m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n  for (size_t i = m0; i <= Order; ++i)\n    retval.v[i] = retval.v[i].epsilon_multiply(z0, isum0 + i, ca);\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename SizeType>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply_cpp11(std::false_type,\n                                                                    SizeType z0,\n                                                                    size_t isum0,\n                                                                    root_type const& ca) const {\n  fvar<RealType, Order> retval(*this);\n  size_t const m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n  for (size_t i = m0; i <= Order; ++i)\n    if (retval.v[i] != static_cast<RealType>(0))\n      retval.v[i] *= ca;\n  return retval;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order> fvar<RealType, Order>::epsilon_multiply(size_t z0,\n                                                              size_t isum0,\n                                                              root_type const& ca) const {\n  return epsilon_multiply_cpp11(is_fvar<RealType>{}, z0, isum0, ca);\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nfvar<RealType, Order>& fvar<RealType, Order>::multiply_assign_by_root_type_cpp11(std::true_type,\n                                                                                 bool is_root,\n                                                                                 RootType const& ca) {\n  auto itr = v.begin();\n  itr->multiply_assign_by_root_type(is_root, ca);\n  for (++itr; itr != v.end(); ++itr)\n    itr->multiply_assign_by_root_type(false, ca);\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nfvar<RealType, Order>& fvar<RealType, Order>::multiply_assign_by_root_type_cpp11(std::false_type,\n                                                                                 bool is_root,\n                                                                                 RootType const& ca) {\n  auto itr = v.begin();\n  if (is_root || *itr != 0)\n    *itr *= ca;  // Skip multiplication of 0 by ca=inf to avoid nan, except when is_root.\n  for (++itr; itr != v.end(); ++itr)\n    if (*itr != 0)\n      *itr *= ca;\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::multiply_assign_by_root_type(bool is_root,\n                                                                           root_type const& ca) {\n  return multiply_assign_by_root_type_cpp11(is_fvar<RealType>{}, is_root, ca);\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nfvar<RealType, Order>& fvar<RealType, Order>::negate_cpp11(std::true_type, RootType const&) {\n  std::for_each(v.begin(), v.end(), [](RealType& r) { r.negate(); });\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nfvar<RealType, Order>& fvar<RealType, Order>::negate_cpp11(std::false_type, RootType const&) {\n  std::for_each(v.begin(), v.end(), [](RealType& a) { a = -a; });\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::negate() {\n  return negate_cpp11(is_fvar<RealType>{}, static_cast<root_type>(*this));\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nfvar<RealType, Order>& fvar<RealType, Order>::set_root_cpp11(std::true_type, RootType const& root) {\n  v.front().set_root(root);\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\ntemplate <typename RootType>\nfvar<RealType, Order>& fvar<RealType, Order>::set_root_cpp11(std::false_type, RootType const& root) {\n  v.front() = root;\n  return *this;\n}\n\ntemplate <typename RealType, size_t Order>\nfvar<RealType, Order>& fvar<RealType, Order>::set_root(root_type const& root) {\n  return set_root_cpp11(is_fvar<RealType>{}, root);\n}\n\ntemplate <typename RealType, size_t Order, size_t... Is>\nauto make_fvar_for_tuple(mp::index_sequence<Is...>, RealType const& ca)\n    -> decltype(make_fvar<RealType, zero<Is>::value..., Order>(ca)) {\n  return make_fvar<RealType, zero<Is>::value..., Order>(ca);\n}\n\ntemplate <typename RealType, size_t... Orders, size_t... Is, typename... RealTypes>\nauto make_ftuple_impl(mp::index_sequence<Is...>, RealTypes const&... ca)\n    -> decltype(std::make_tuple(make_fvar_for_tuple<RealType, Orders>(mp::make_index_sequence<Is>{},\n                                                                      ca)...)) {\n  return std::make_tuple(make_fvar_for_tuple<RealType, Orders>(mp::make_index_sequence<Is>{}, ca)...);\n}\n\n}  // namespace detail\n\ntemplate <typename RealType, size_t... Orders, typename... RealTypes>\nauto make_ftuple(RealTypes const&... ca)\n    -> decltype(detail::make_ftuple_impl<RealType, Orders...>(mp::index_sequence_for<RealTypes...>{},\n                                                              ca...)) {\n  static_assert(sizeof...(Orders) == sizeof...(RealTypes),\n                \"Number of Orders must match number of function parameters.\");\n  return detail::make_ftuple_impl<RealType, Orders...>(mp::index_sequence_for<RealTypes...>{}, ca...);\n}\n\n}  // namespace autodiff_v1\n}  // namespace differentiation\n}  // namespace math\n}  // namespace boost\n", "meta": {"hexsha": "1624c494eeb04d1a2c55ae8f761baa65d1549386", "size": 17196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/differentiation/autodiff_cpp11.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/differentiation/autodiff_cpp11.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/differentiation/autodiff_cpp11.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": 44.3195876289, "max_line_length": 112, "alphanum_fraction": 0.6021167713, "num_tokens": 4248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.060975174465973454, "lm_q1q2_score": 0.02716624112878198}}
{"text": "#pragma once\n/**\n * @file pauli_operator.hpp\n * @brief Definition and basic functions for MultiPauliTerm\n */\n\n#pragma once\n\n#include <boost/dynamic_bitset.hpp>\n#include <cassert>\n#include <iostream>\n#include <vector>\n\n#include \"exception.hpp\"\n#include \"type.hpp\"\n\nclass QuantumStateBase;\n\n/**\n * \\~japanese-en\n * @struct SiglePauliOperator\n * 単一qubitに作用するパウリ演算子の情報を保持するクラス。\n * 作用するqubitの添字と自身のパウリ演算子の情報をもつ。\n */\nclass DllExport SinglePauliOperator {\nprotected:\n    UINT _index;\n    UINT _pauli_id;\n\npublic:\n    /**\n     * \\~japanese-en\n     * コンストラクタ\n     *\n     * 添字とパウリ演算子からインスタンスを生成する。\n     *\n     * @param[in] index_ 作用するqubitの添字\n     * @param[in] pauli_id_\n     * パウリ演算子を表す整数。(I,X,Y,Z)が(0,1,2,3)に対応する。\n     * @return 新しいインスタンス\n     */\n    SinglePauliOperator(UINT index_, UINT pauli_id_)\n        : _index(index_), _pauli_id(pauli_id_) {\n        if (pauli_id_ > 3) {\n            throw InvalidPauliIdentifierException(\n                \"Error: SinglePauliOperator(UINT, UINT): index must be \"\n                \"either of 0,1,2,3\");\n        }\n    };\n\n    /**\n     * \\~japanese-en\n     * 自身が作用する添字を返す\n     *\n     * @return 自身が作用する添字\n     */\n    UINT index() const { return _index; }\n\n    /**\n     * \\~japanese-en\n     * 自身を表すパウリ演算子を返す\n     *\n     * @return\n     * 自身のもつパウリ演算子を表す整数。(I,X,Y,Z)が(0,1,2,3)に対応する。\n     */\n    UINT pauli_id() const { return _pauli_id; }\n};\n\n/**\n * \\~japanese-en\n * @struct PauliOperator\n * 複数qubitに作用するパウリ演算子の情報を保持するクラス。\n * SinglePauliOperatorをリストとして持ち, 種々の操作を行う。\n */\nclass DllExport PauliOperator {\nprivate:\n    std::vector<SinglePauliOperator> _pauli_list;\n    CPPCTYPE _coef;\n    boost::dynamic_bitset<> _z;\n    boost::dynamic_bitset<> _x;\n\npublic:\n    /**\n     * \\~japanese-en\n     * 自身の保持するパウリ演算子が作用する添字のリストを返す\n     *\n     * それぞれの添字に作用する演算子は\n     * PauliOperator::get_pauli_id_listで得られる添字のリストの対応する場所から得られる。\n     *\n     * @return 自身の保持するパウリ演算子が作用する添字のリスト。\n     */\n    std::vector<UINT> get_index_list() const {\n        std::vector<UINT> index_list;\n        std::transform(_pauli_list.cbegin(), _pauli_list.cend(),\n            std::back_inserter(index_list),\n            [](auto val) { return val.index(); });\n        return index_list;\n    }\n\n    /**\n     * \\~japanese-en\n     * 自身の保持するパウリ演算子が添え字のうち、最大の添え字を返す\n     *\n     * @return 自身の保持するパウリ演算子が作用する添字のうち最大の整数\n     */\n    UINT get_qubit_count() const {\n        std::vector<UINT> index_list = get_index_list();\n        if (index_list.size() == 0) return 0;\n        return *std::max_element(index_list.begin(), index_list.end()) + 1;\n    }\n\n    /**\n     * \\~japanese-en\n     * 自身が保持するパウリ演算子を返す。\n     *\n     * それぞれが作用するqubitは\n     * PauliOperator::get_index_listで得られる添字のリストの対応する場所から得られる。\n     *\n     * @return\n     * 自身の保持するパウリ演算子のリスト。(I,X,Y,Z)が(0,1,2,3)に対応する。\n     */\n    std::vector<UINT> get_pauli_id_list() const {\n        std::vector<UINT> pauli_id_list;\n        std::transform(_pauli_list.cbegin(), _pauli_list.cend(),\n            std::back_inserter(pauli_id_list),\n            [](auto val) { return val.pauli_id(); });\n        return pauli_id_list;\n    }\n\n    /**\n     * \\~japanese-en\n     * コンストラクタ\n     *\n     * 係数をとって空のインスタンスを返す。\n     *\n     * @param[in] coef 係数。デフォルトは1.0\n     * @return 係数がcoefの空のインスタンス\n     */\n    explicit PauliOperator(CPPCTYPE coef = 1.) : _coef(coef){};\n\n    /**\n     * \\~japanese-en\n     * コンストラクタ\n     *\n     * パウリ演算子とその添字からなる文字列と、その係数から複数qubitに掛かるパウリ演算子を作成する\n     *\n     * @param[in] strings Pauli演算子とその掛かるindex. \"X 1 Y 2 Z\n     * 5\"のようにスペース区切りの文字列\n     * @param[in] coef 演算子の係数\n     * @return 入力のパウリ演算子と係数をもつPauliOpetatorのインスタンス\n     */\n    explicit PauliOperator(std::string strings, CPPCTYPE coef = 1.);\n\n    /**\n     * \\~japanese-en\n     * コンストラクタ\n     *\n     * パウリ演算子の文字列と添字のリスト、係数からPauliOperatorのインスタンスを生成する。\n     * このとき入力として与える演算子と添字のリストは、i番目の演算子にi番目の添字が対応する。\n     *\n     * @param[in] target_qubit_index_list\n     * Pauli_operator_type_listで与えるパウリ演算子が掛かるqubitを指定する添字のリスト。\n     * @param[in] Pauli_operator_type_list パウリ演算子の文字列。(example:\n     * \"XXYZ\")\n     * @param[in] coef 係数\n     * @return\n     * 入力として与えたパウリ演算子のリストと添字のリスト、係数から生成されるPauliOperatorのインスタンス\n     */\n    PauliOperator(const std::vector<UINT>& target_qubit_index_list,\n        std::string Pauli_operator_type_list, CPPCTYPE coef = 1.);\n\n    /**\n     * \\~japanese-en\n     * コンストラクタ\n     *\n     * 配列の添字に作用するパウリ演算子と係数からインスタンスを生成する。\n     * @param[in] pauli_list\n     * 配列の添字に対応するqubitに作用するパウリ演算子のリスト\n     * @param[in] coef 係数\n     * @return\n     * pauli_listの添字に対応するqubitに作用するパウリ演算子と係数をもつインスタンス\n     */\n    explicit PauliOperator(\n        const std::vector<UINT>& pauli_list, CPPCTYPE coef = 1.);\n\n    /**\n     * \\~japanese-en\n     * コンストラクタ\n     *\n     * パウリ演算子のリストと添字のリスト、係数からPauliOperatorのインスタンスを生成する。\n     * このとき入力として与える演算子と添字のリストは、リストの同じ添字の場所にあるものが対応する。\n     *\n     * @param[in] target_qubit_index_list\n     * Pauli_operator_type_listで与えるパウリ演算子が掛かるqubitを指定する添字のリスト\n     * @param[in] target_qubit_pauli_list\n     * パウリ演算子の符号なし整数リスト。(I,X,Y,Z)が(0,1,2,3)に対応する。\n     * @param[in] coef 係数\n     * @return\n     * 入力として与えたパウリ演算子のリストと添字のリスト、係数から生成されるPauliOperatorのインスタンス\n     */\n    PauliOperator(const std::vector<UINT>& target_qubit_index_list,\n        const std::vector<UINT>& target_qubit_pauli_list, CPPCTYPE coef = 1.);\n\n    PauliOperator(const boost::dynamic_bitset<>& x,\n        const boost::dynamic_bitset<>& z, CPPCTYPE coef = 1.);\n\n    /**\n     * \\~japanese-en\n     * 自身の係数を返す\n     *\n     * @return 自身の係数\n     */\n    virtual CPPCTYPE get_coef() const { return _coef; }\n\n    /**\n     * \\~japanese-en\n     * 自身のxビットを返す\n     *\n     * @return 自身のxビット\n     */\n    virtual boost::dynamic_bitset<> get_x_bits() const { return _x; }\n\n    /**\n     * \\~japanese-en\n     * 自身のzビットを返す\n     *\n     * @return 自身のzビット\n     */\n    virtual boost::dynamic_bitset<> get_z_bits() const { return _z; }\n\n    virtual ~PauliOperator(){};\n\n    /**\n     * \\~japanese-en\n     * 指定した添字のqubitに作用するSinglePauliOperatorを自身が保持するリストの末尾に追加する。\n     *\n     * @param[in] qubit_index 作用するqubitの添字\n     * @param[in] pauli_type パウリ演算子。(I,X,Y,Z)が(0,1,2,3)に対応する。\n     */\n    virtual void add_single_Pauli(UINT qubit_index, UINT pauli_type);\n\n    /**\n     * \\~japanese-en\n     * 量子状態に対応するパウリ演算子の期待値を計算する\n     *\n     * @param[in] state 期待値をとるときの量子状態\n     * @return stateに対応する期待値\n     */\n    virtual CPPCTYPE get_expectation_value(const QuantumStateBase* state) const;\n\n    /**\n     * \\~japanese-en\n     * added by myself\n     * 量子状態に対応するパウリ演算子の期待値を計算する\n     * get_expectation_value の 1 スレッドバージョン\n     *\n     * @param[in] state 期待値をとるときの量子状態\n     * @return stateに対応する期待値\n     */\n    virtual CPPCTYPE get_expectation_value_single_thread(\n        const QuantumStateBase* state) const;\n\n    /**\n     * \\~japanese-en\n     * 量子状態に対応するパウリ演算子の遷移振幅を計算する\n     *\n     * @param[in] state_bra 遷移先の量子状態\n     * @param[in] state_ket 遷移元の量子状態\n     * @return state_bra, state_ketに対応する遷移振幅\n     */\n    virtual CPPCTYPE get_transition_amplitude(const QuantumStateBase* state_bra,\n        const QuantumStateBase* state_ket) const;\n\n    /**\n     * \\~japanese-en\n     * 自身のディープコピーを生成する\n     *\n     * @return 自身のディープコピー\n     */\n    virtual PauliOperator* copy() const;\n\n    virtual void change_coef(CPPCTYPE new_coef);\n\n    /**\n     * \\~japanese-en\n     * パウリ演算子に対応する文字列を返す\n     */\n    virtual std::string get_pauli_string() const;\n    /**\n     * \\~japanese-en\n     * このオブザーバブルに入っているものを、ゲートとしてstateに作用させる\n     * @param [in] state 入力\n     */\n    virtual void update_quantum_state(QuantumStateBase* instate);\n\n    PauliOperator operator*(const PauliOperator& target) const;\n\n    PauliOperator operator*(CPPCTYPE target) const;\n\n    PauliOperator& operator*=(const PauliOperator& target);\n\n    PauliOperator& operator*=(CPPCTYPE target);\n};\n", "meta": {"hexsha": "78a7db40d60f1d8c06249572de1e7e70b4aefb16", "size": 7652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppsim/pauli_operator.hpp", "max_stars_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_stars_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-26T06:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:07:24.000Z", "max_issues_repo_path": "src/cppsim/pauli_operator.hpp", "max_issues_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_issues_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-11-12T04:15:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:12:20.000Z", "max_forks_repo_path": "src/cppsim/pauli_operator.hpp", "max_forks_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_forks_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T11:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T04:20:17.000Z", "avg_line_length": 25.1710526316, "max_line_length": 80, "alphanum_fraction": 0.6301620491, "num_tokens": 3256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.055823145454283137, "lm_q1q2_score": 0.027039619899752024}}
{"text": "/*\n  Copyright (C) 2016 Ahmed Riza\n\n  This file is part of MathFin.\n\n  This program is free software: you  can redistribute it and/or modify it\n  under the  terms of the GNU  General Public License as  published by the\n  Free Software Foundation,  either version 3 of the License,  or (at your\n  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 GNU General\n  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, see <http://www.gnu.org/licenses/>.\n*/\n\n/*\n  Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n  Copyright (C) 2003, 2004, 2005, 2006 StatPro Italia srl\n  Copyright (C) 2004, 2005, 2006 Ferdinando Ametrano\n  Copyright (C) 2006 Katiuscia Manzoni\n  Copyright (C) 2006 Toyin Akin\n  Copyright (C) 2015 Klaus Spanderen\n\n  QuantLib is free software: you can redistribute it and/or modify it\n  under the terms of the QuantLib license.  You should have received a\n  copy of the license along with this program; if not, please email\n  <quantlib-dev@lists.sf.net>. The license is also available online at\n  <http://quantlib.org/license.shtml>.\n\n  This program is distributed in the hope that it will be useful, but WITHOUT\n  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n  FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef MATHFIN_DATE_HPP\n#define MATHFIN_DATE_HPP\n\n#include <time/period.hpp>\n#include <time/month.hpp>\n#include <time/weekday.hpp>\n#include <boost/date_time/posix_time/ptime.hpp>\n#include <boost/date_time/posix_time/posix_time_duration.hpp>\n\nnamespace MathFin {\n\n  /**\n   * Day number\n   * @ingroup datetime\n   */\n  typedef Integer Day;\n\n  /**\n   * Year number\n   * @ingroup datetime\n   */\n  typedef Integer Year;\n\n  /**\n   * Hour number\n   * @ingroup datetime\n   */\n  typedef boost::posix_time::hours::hour_type Hour;\n\n  /**\n   * Minute number\n   * @ingroup datetime\n   */\n  typedef boost::posix_time::minutes::min_type Minute;\n\n  /**\n   * Second number\n   * @ingroup datetime\n   */\n  typedef boost::posix_time::minutes::sec_type Second;\n\n  /**\n   * Millisecond number\n   * @ingroup datetime\n   */\n  typedef boost::posix_time::time_duration::fractional_seconds_type Millisecond;\n\n  /**\n   * Microsecond number\n   * @ingroup datetime\n   */\n  typedef boost::posix_time::time_duration::fractional_seconds_type Microsecond;\n\n  /**\n   * Date class.\n   *\n   * This class provides methods to inspect dates as well as methods and\n   * operators which implement a limited date algebra (increasing and\n   * decreasing dates, and calculating their difference).\n   *\n   * The maximal resolution of the methods is either micro or nano seconds\n   * depending on the underlying boost installation.\n   *\n   * @ingroup datetime\n   */\n  class Date {\n  public:\n    typedef boost::int_fast32_t serial_type;\n\n    /**\n     * @name constructors\n     * @{\n     */\n\n    /**\n     * Default constructor returning a null date.\n     */\n    Date();\n\n    /**\n     * Constructor taking a serial number as given by Excel.\n     */\n    explicit Date(Date::serial_type serialNumber);\n\n    /**\n     * Constructor taking day, month and year.\n     */\n    explicit Date(Day d, Month m, Year y);\n\n    /**\n     * Constructor taking boost posix date time object\n     */\n    explicit Date(const boost::posix_time::ptime& localTime);\n\n    /**\n     * Constructor taking the full range of parameters.\n     */\n    explicit Date(Day d,\n         Month m,\n         Year y,\n         Hour hours,\n         Minute minutes,\n         Second seconds,\n         Millisecond millisec = 0,\n         Microsecond microsec = 0);\n\n    /** @} */ // end of constructors.\n\n    // -------------------------------------------------------------------------\n\n    /**\n     * @name inspectors\n     * @{\n     */\n\n    /**\n     * Get week day.\n     */\n    Weekday weekday() const;\n\n    /**\n     * Get day of month.\n     */\n    Day dayOfMonth() const;\n\n    /**\n     * Get day of the year; one-based (Jan 1st = 1)\n     */\n    Day dayOfYear() const;\n\n    /**\n     *  Get month\n     */\n    Month month() const;\n\n    /**\n     * Get year.\n     */\n    Year year() const;\n\n    /**\n     * Get serial number.\n     */\n    Date::serial_type serialNumber() const;\n\n    /**\n     * Get hours.\n     */\n    Hour hours() const;\n\n    /**\n     * Get minutes.\n     */\n    Minute minutes() const;\n\n    /**\n     * Get seconds.\n     */\n    Second seconds() const;\n\n    /**\n     * Get  millseconds.\n     */\n    Millisecond milliseconds() const;\n\n    /**\n     *  Get microseconds.\n     */\n    Microsecond microseconds() const;\n\n    /**\n     * Get fraction of day represent by this Date instance.\n     * The maximal resolution of the methods is either micro or nano seconds\n     * depending on the underlying boost installation.\n     */\n    Time fractionOfDay() const;\n\n    /**\n     * Get fraction of second represented by this Date instance.\n     * The maximal resolution of the methods is either micro or nano seconds\n     * depending on the underlying boost installation.\n     */\n    Time fractionOfSecond() const;\n\n    const boost::posix_time::ptime& dateTime() const { return dateTime_; }\n\n    /**\n     * Get the number of days in the year.\n     * If the year is a leap year, return 366 otherwise return 365.\n     */\n    Real lengthOfYear() const;\n\n    /** @} */ // end of inspectors.\n\n    // -------------------------------------------------------------------------\n\n    /**\n     * @name date algebra\n     * @{\n     */\n\n    /**\n     * returns a new date incremented by the given number of days\n     */\n    Date operator+(Date::serial_type days) const;\n\n    /**\n     * returns a new date incremented by the given period\n     */\n    Date operator+(const Period&) const;\n\n    /**\n     * returns a new date decremented by the given number of days\n     */\n    Date operator-(Date::serial_type days) const;\n\n    /**\n     * returns a new date decremented by the given period\n     */\n    Date operator-(const Period&) const;\n\n    /** @} */ // end of date algebra methods.\n\n    // -------------------------------------------------------------------------\n\n    /**\n     * today's date.\n     */\n    static Date todaysDate();\n\n    /**\n     * earliest allowed date\n     */\n    static Date minDate();\n\n    /**\n     * latest allowed date\n     */\n    static Date maxDate();\n\n    /**\n     * whether the given year is a leap one\n     */\n    static bool isLeap(Year y);\n\n    /**\n     * last day of the month to which the given date belongs\n     */\n    static Date endOfMonth(const Date& d);\n\n    /**\n     * whether a date is the last day of its month\n     */\n    static bool isEndOfMonth(const Date& d);\n\n    /**\n     * next given weekday following or equal to the given date\n     * E.g., the Friday following Tuesday, January 15th, 2002\n     * was January 18th, 2002.\n     * @see http://www.cpearson.com/excel/DateTimeWS.htm\n     */\n    static Date nextWeekday(const Date& d, Weekday w);\n\n    /**\n     * n-th given weekday in the given month and year\n     * E.g., the 4th Thursday of March, 1998 was March 26th,\n     * 1998.\n     * @see http://www.cpearson.com/excel/DateTimeWS.htm\n     */\n    static Date nthWeekday(Size n, Weekday w, Month m, Year y);\n\n    /**\n     * local date time, based on the time zone settings of the computer\n     */\n    static Date localDateTime();\n\n    /**\n     * UTC date time\n     */\n    static Date universalDateTime();\n\n    /**\n     *  underlying resolution of the  posix date time object\n     */\n    static const Size ticksPerSecond();\n\n  private:\n    Date& operator=(const Date&) = delete;\n\n    static Date::serial_type minimumSerialNumber();\n    static Date::serial_type maximumSerialNumber();\n    static void checkSerialNumber(Date::serial_type serialNumber);\n\n    const boost::posix_time::ptime dateTime_;\n  };\n\n  /**\n   * Difference in days between dates.\n   * @relates Date\n   */\n  Date::serial_type operator-(const Date&, const Date&);\n\n  /**\n   * Difference in days (including fraction of days) between dates\n   * @relates Date\n   */\n  Time daysBetween(const Date& d1, const Date& d2);\n\n  // -------------------------------------------------------------------------\n\n  /**\n   * Equivalence operator.\n   * @relates Date\n   */\n  bool operator==(const Date&, const Date&);\n\n  /**\n   * Not equals operator.\n   * @relates Date\n   */\n  bool operator!=(const Date&, const Date&);\n\n  /**\n   * Less than operator.\n   * @relates Date\n   */\n  bool operator<(const Date&, const Date&);\n\n  /**\n   * Less than or equals operator.\n   * @relates Date\n   */\n  bool operator<=(const Date&, const Date&);\n\n  /**\n   * Greater than operator.\n   * @relates Date\n   */\n  bool operator>(const Date&, const Date&);\n\n  /**\n   * Greater than or equals operator.\n   * @relates Date\n   */\n  bool operator>=(const Date&, const Date&);\n\n  /**\n   * Output operator.\n   * @relates Date\n   */\n  std::ostream& operator<<(std::ostream&, const Date&);\n\n}\n\n#endif /* MATHFIN_DATE_HPP */\n", "meta": {"hexsha": "ae382928c4a40f62beeec0af5e91e1d628012e32", "size": 9123, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "time/date.hpp", "max_stars_repo_name": "onedigit/finmath", "max_stars_repo_head_hexsha": "8b7dd9f3e41ba810622070060af2b3a246c079c1", "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": "time/date.hpp", "max_issues_repo_name": "onedigit/finmath", "max_issues_repo_head_hexsha": "8b7dd9f3e41ba810622070060af2b3a246c079c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "time/date.hpp", "max_forks_repo_name": "onedigit/finmath", "max_forks_repo_head_hexsha": "8b7dd9f3e41ba810622070060af2b3a246c079c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.154822335, "max_line_length": 80, "alphanum_fraction": 0.6026526362, "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.07921033008659957, "lm_q1q2_score": 0.026779200598650268}}
{"text": "/* $Id: formula.hpp 48740 2011-03-05 10:01:34Z mordante $ */\r\n/*\r\n   Copyright (C) 2008 - 2011 by Mark de Wever <koraq@xs4all.nl>\r\n   Part of the Battle for Wesnoth Project http://www.wesnoth.org/\r\n\r\n   This program is free software; you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation; either version 2 of the License, or\r\n   (at your option) any later version.\r\n   This program is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY.\r\n\r\n   See the COPYING file for more details.\r\n*/\r\n\r\n#ifndef GUI_WIDGETS_FORMULA_HPP_INCLUDED\r\n#define GUI_WIDGETS_FORMULA_HPP_INCLUDED\r\n\r\n#include \"formula_callable.hpp\"\r\n#include \"../../formula.hpp\"\r\n#include \"gui/auxiliary/log.hpp\"\r\n#include \"gui/widgets/helper.hpp\"\r\n#include \"serialization/string_utils.hpp\"\r\n#include \"util.hpp\"\r\n#include \"tstring.hpp\"\r\n\r\n#include <boost/static_assert.hpp>\r\n\r\n#include <cassert>\r\n\r\nnamespace gui2{\r\n\r\n/**\r\n * Template class can hold a value or a formula to calculate the value.\r\n *\r\n * A string is a formula when it starts with a right paren, no other validation\r\n * is done by this function, leading whitespace is significant.\r\n *\r\n * Upon getting the value of the formula a variable map is send. The variables\r\n * in the map can be used in the formula. The 'owners' of the class need to\r\n * document the variables available.\r\n *\r\n * @tparam T                      The type of the formula. This type needs to\r\n *                                be constructable form a string, either by a\r\n *                                lexical_cast or a template specialization in\r\n *                                this header.\r\n */\r\ntemplate <class T>\r\nclass tformula\r\n{\r\npublic:\r\n\t/**\r\n\t * Constructor.\r\n\t *\r\n\t * @param str                 The string used to initialize the class, this\r\n\t *                            can either be a formula or a string which can\r\n\t *                            be converted to the type T.\r\n\t * @param value               The default value for the object.\r\n\t */\r\n\ttformula<T>(const std::string& str, const T value = T());\r\n\r\n\t/**\r\n\t * Returns the value, can only be used if the data is no formula.\r\n\t *\r\n\t * Another option would be to cache the output of the formula in value_\r\n\t * and always allow this function. But for now decided that the caller\r\n\t * needs to do the caching. It might be changed later.\r\n\t */\r\n\tT operator()() const\r\n\t{\r\n\t\tassert(!has_formula());\r\n\t\treturn value_;\r\n\t}\r\n\r\n\t/** Returns the value, can always be used. */\r\n\tT operator() (const game_logic::map_formula_callable& variables) const;\r\n\r\n\t/** Determine whether the class contains a formula. */\r\n\tbool has_formula() const { return !formula_.empty(); }\r\n\r\nprivate:\r\n\r\n\t/**\r\n\t * Converts the string to the template type.\r\n\t *\r\n\t * This function is used by the constructor to convert the string to the\r\n\t * wanted value, if not a formula.\r\n\t *\r\n\t * @param str                 The str send to the constructor.\r\n\t */\r\n\tvoid convert(const std::string& str);\r\n\r\n\t/**\r\n\t * Executes the formula.\r\n\t *\r\n\t * This function does the calculation and can only be called if the object\r\n\t * contains a formula.\r\n\t *\r\n\t * @param variables           The state variables which might be used in\r\n\t *                            the formula. For example a screen_width can\r\n\t *                            be set so the formula can return the half\r\n\t *                            width of the screen.\r\n\t *\r\n\t * @returns                   The calculated value.\r\n\t */\r\n\tT execute(const game_logic::map_formula_callable& variables) const;\r\n\r\n\t/**\r\n\t * Contains the formuale for the variable.\r\n\t *\r\n\t * If the string is empty, there's no formula.\r\n\t */\r\n\tstd::string formula_;\r\n\r\n\t/** If there's no formula it contains the value. */\r\n\tT value_;\r\n};\r\n\r\ntemplate<class T>\r\ntformula<T>::tformula(const std::string& str, const T value) :\r\n\tformula_(),\r\n\tvalue_(value)\r\n{\r\n\tif(str.empty()) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tif(str[0] == '(') {\r\n\t\tformula_ = str;\r\n\t} else {\r\n\t\tconvert(str);\r\n\t}\r\n}\r\n\r\ntemplate<class T>\r\ninline T tformula<T>::operator()(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\tif(has_formula()) {\r\n\t\tconst T& result = execute(variables);\r\n\t\tLOG_GUI_D << \"Formula: execute '\" << formula_\r\n\t\t\t<< \"' result '\" << result\r\n\t\t\t<< \"'.\\n\";\r\n\t\treturn result;\r\n\t} else {\r\n\t\treturn value_;\r\n\t}\r\n}\r\n\r\ntemplate<>\r\ninline bool tformula<bool>::execute(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\treturn game_logic::formula(formula_).evaluate(variables).as_bool();\r\n}\r\n\r\ntemplate<>\r\ninline int tformula<int>::execute(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\treturn game_logic::formula(formula_).evaluate(variables).as_int();\r\n}\r\n\r\ntemplate<>\r\ninline unsigned tformula<unsigned>::execute(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\treturn game_logic::formula(formula_).evaluate(variables).as_int();\r\n}\r\n\r\ntemplate<>\r\ninline std::string tformula<std::string>::execute(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\treturn game_logic::formula(formula_).evaluate(variables).as_string();\r\n}\r\n\r\ntemplate<>\r\ninline t_string tformula<t_string>::execute(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\treturn game_logic::formula(formula_).evaluate(variables).as_string();\r\n}\r\n\r\ntemplate<>\r\ninline PangoAlignment tformula<PangoAlignment>::execute(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\treturn decode_text_alignment(\r\n\t\t\tgame_logic::formula(formula_).evaluate(variables).as_string());\r\n}\r\n\r\ntemplate<class T>\r\ninline T tformula<T>::execute(\r\n\t\tconst game_logic::map_formula_callable& variables) const\r\n{\r\n\t// Every type needs its own execute function avoid instantiation of the\r\n\t// default execute.\r\n\tBOOST_STATIC_ASSERT(sizeof(T) == 0);\r\n\treturn T();\r\n}\r\n\r\ntemplate<>\r\ninline void tformula<bool>::convert(const std::string& str)\r\n{\r\n\tvalue_ = utils::string_bool(str);\r\n}\r\n\r\ntemplate<>\r\ninline void tformula<std::string>::convert(const std::string& str)\r\n{\r\n\tvalue_ = str;\r\n}\r\n\r\ntemplate<>\r\ninline void tformula<t_string>::convert(const std::string& str)\r\n{\r\n\tvalue_ = str;\r\n}\r\n\r\ntemplate<>\r\ninline void tformula<PangoAlignment>::convert(const std::string& str)\r\n{\r\n\tvalue_ = decode_text_alignment(str);\r\n}\r\n\r\ntemplate<class T>\r\ninline void tformula<T>::convert(const std::string& str)\r\n{\r\n\tvalue_ = lexical_cast_default<T>(str);\r\n}\r\n\r\n} // namespace gui2\r\n\r\n#endif\r\n", "meta": {"hexsha": "b67ba61d3918429cb1cbad66292ecabae2b0d343", "size": 6463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gui/auxiliary/formula.hpp", "max_stars_repo_name": "blackberry/Wesnoth", "max_stars_repo_head_hexsha": "8b307689158db568ecc6cc3b537e8d382ccea449", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-03-04T15:07:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-13T16:31:06.000Z", "max_issues_repo_path": "src/gui/auxiliary/formula.hpp", "max_issues_repo_name": "blackberry/Wesnoth", "max_issues_repo_head_hexsha": "8b307689158db568ecc6cc3b537e8d382ccea449", "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/gui/auxiliary/formula.hpp", "max_forks_repo_name": "blackberry/Wesnoth", "max_forks_repo_head_hexsha": "8b307689158db568ecc6cc3b537e8d382ccea449", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-04-22T08:16:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T03:35:16.000Z", "avg_line_length": 27.3855932203, "max_line_length": 80, "alphanum_fraction": 0.6571251741, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.08509903920620716, "lm_q1q2_score": 0.02672539964098855}}
{"text": "﻿\r\n/******\r\n\r\n六：成员函数模板\r\n6.1 基本概念、构造函数模板\r\n一些说法：\r\na)类模板中的成员函数，只有源程序代码中出现调用这些成员函数的代码时，\r\n  这些成员函数才会出现在一个实例化了的类模板中。\r\n\r\nb)类模板中的成员函数模板，只有源程序代码中出现调用这些成员函数模板的代码时，\r\n  这些成员函数模板的具体实例才会出现在一个实例化了的类模板中。\r\n\r\nc)目前编译器并不支持虚成员函数模板，因为虚函数表vtbl的大小是固定的。\r\n\r\nC++之父的说法：如果允许虚函数模板，则每次有人用新的参数类型调用该虚函数模板时，就必须给对应的虚函数表再增加一项，\r\n这意味着只有链接程序才能去构造虚函数表并在表中设置有关函数，因此，成员函数模板绝不能是虚的。\r\n类模板中可以有普通的虚成员函数（虚函数），这并没有什么问题。大家都知道，普通成员函数如果不被调用的情况下不会被实例化出来。\r\n但是，对于虚函数，不管是否调用，编译器都会把他实例化出来，因为编译器要创建虚函数表vtbl，该表中的每个具体表项都对应一个\r\n虚函数地址，所以编译器必然得把所有虚函数都实例化出来。\r\n\r\n\r\n6.2 拷贝构造函数模板与拷贝赋值运算符模板\r\n请大家注意区分：拷贝构造函数模板不是拷贝构造函数，拷贝赋值运算符模板不是拷贝赋值运算符\r\n（构造函数模板也不是构造函数）；\r\n因为拷贝构造函数或者拷贝赋值运算符要求拷贝的对象类型完全相同，而拷贝构造函数模板和拷贝\r\n赋值运算符模板就没有这种要求。\r\n\r\n发现两个问题：\r\na)_nmsp1::A<float> a4(a3);代码行没输出任何结果，这表示拷贝构造函数模板中的代码没有执行。\r\n\r\nb)a4.m_ic值的确变成了16.2了。这说明确实是通过a3拷贝构造生成的a4。\r\na3,a4类型相同（A<float>），本该执行拷贝构造函数，但是因为类模板A中没有拷贝构造函数，所以编译器内部实际是\r\n执行了按值拷贝的一个动作，使a4.m_ic值变成了16.2了。\r\n【拷贝构造函数模板永远不可能成为拷贝构造函数。编译器不会用调用拷贝构造函数模板来代替调用拷贝构造函数。】\r\n拷贝构造函数模板什么时候被调用？类型不同（都是用类模板A实例化出来的，比如A<double>与A<float>）的两个对象，\r\n用一个拷贝构造另一个时。\r\n\r\n拷贝赋值运算符模板永远不可能成为拷贝赋值运算符\r\n\r\n****/\r\n\r\n#include <iostream>\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\n//6.1\r\nnamespace _nmsp1\r\n{\r\n\r\n\ttemplate <typename T1>\r\n\tclass A\r\n\t{\r\n\tpublic:\r\n\t\ttemplate <typename T2>\r\n\t\tA(T2 v1, T2 v2); //构造函数模板，引入了自己的模板参数T2，与类A的模板参数T1没有关系\r\n\r\n\tpublic:\r\n\t\tA(double v1, double v2)\r\n\t\t{\r\n\t\t\tcout << \"A::A(double,double)执行了!\" << endl;\r\n\t\t}\r\n\t\tA(T1 v1, T1 v2)\r\n\t\t{\r\n\t\t\tcout << \"A::A(T1,T1)执行了!\" << endl;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t//拷贝构造函数模板\r\n\t\ttemplate <typename U>\r\n\t\tA(const A<U>& other)\r\n\t\t//A(A<U>& other)\r\n\t\t{\r\n\t\t\tcout << \"A::A(const A<U>& other)拷贝构造函数模板执行了!\" << endl;\r\n\t\t}\r\n\r\n\t\t//拷贝赋值运算符模板\r\n\t\ttemplate <typename U>\r\n\t\tA<T1>& operator=(const A<U>& other)\r\n\t\t//A<T1>& operator=(A<U>& other)\r\n\t\t{\r\n\t\t\t//.....\r\n\t\t\tcout << \"operator=(const A<U>& other)拷贝赋值运算符模板执行了!\" << endl;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\t////拷贝赋值运算符\r\n\t\t//A<T1>& operator=(const A<T1>& other)\r\n\t\t//{\r\n\t\t//\tcout << \"operator=(const A<T1>& other)拷贝赋值运算符执行了!\" << endl;\r\n\t\t//\treturn *this;\r\n\t\t//}\r\n\r\n\r\n\t\t//---------------------------------\r\n\t\t/*template <typename T4>\r\n\t\tvirtual void myvirfunc() {}*/\r\n\t\tvirtual void myvirfunc2() {}\r\n\r\n\t\t//----------------------------------\r\n\t\ttemplate <typename T3>\r\n\t\tvoid myft(T3 tmpt) //普通成员函数模板\r\n\t\t{\r\n\t\t\tcout << tmpt << endl;\r\n\t\t}\r\n\r\n\t\tT1 m_ic;\r\n\t\tstatic constexpr int m_stcvalue = 200;\r\n\t};\r\n\r\n\t//在类外实现类模板的构造函数模板\r\n\ttemplate <typename T1>\r\n\ttemplate <typename T2>\r\n\tA<T1>::A(T2 v1, T2 v2)\r\n\t{\r\n\t\tcout << \"A::A(T2,T2)执行了!\" << endl;\r\n\t}\r\n\r\n}\r\n\r\n//void f(int tm) {}\r\n//void f2(int tm) {}\r\n\r\n\r\nint main()\r\n{\r\n\t_nmsp1::A<float> a(1, 2);           //实例化了A<float>这样一个类型，并用int类型来实例化构造函数\r\n\ta.myft(3);                          //3\r\n\t_nmsp1::A<float> a2(1.1, 2.2);      //A<float>类型已经被上面的代码实例化过了，并用doule类型来实例化构造函数,因为1.1和2.2都是double类型\r\n\t_nmsp1::A<float> a3(11.1f, 12.2f);  //用float类型来实例化构造函数,因为11.1f和12.2f都是float类型\r\n\r\n\t//----------------\r\n\ta3.m_ic = 16.2f;\r\n\t_nmsp1::A<float> a4(a3);   //会执行拷贝构造函数模板中的代码吗(不会)\r\n\r\n\t//----------------\r\n\t_nmsp1::A<int> a5(a3);     //a3是A<float>类型，a5是A<int>类型，两者类型不同\r\n\r\n\t//----------------\r\n\ta3 = a4;\r\n\ta3 = a5;\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "5ba6329a90839cab85ee6a1fe7f7d9ce4a314a13", "size": 3100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/207.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/207.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/207.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 21.3793103448, "max_line_length": 101, "alphanum_fraction": 0.6193548387, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106118745263715, "lm_q2_score": 0.1561048915563923, "lm_q1q2_score": 0.026703488116801614}}
{"text": "/*\r\nCopyright (c) by respective owners including Yahoo!, Microsoft, and\r\nindividual contributors. All rights reserved.  Released under a BSD (revised)\r\nlicense as described in the file LICENSE.\r\n */\r\n#include <fstream>\r\n#include <vector>\r\n#include <float.h>\r\n#ifdef _WIN32\r\n#include <winsock2.h>\r\n#else\r\n#include <netdb.h>\r\n#endif\r\n#include <string.h>\r\n#include <stdio.h>\r\n#include <assert.h>\r\n#include \"constant.h\"\r\n#include \"sparse_dense.h\"\r\n#include \"gd.h\"\r\n#include \"simple_label.h\"\r\n#include \"rand48.h\"\r\n#include \"reductions.h\"\r\n\r\nusing namespace LEARNER;\r\nusing namespace std;\r\n\r\nnamespace LDA {\r\n\r\nclass index_feature {\r\npublic:\r\n  uint32_t document;\r\n  feature f;\r\n  bool operator<(const index_feature b) const { return f.weight_index < b.f.weight_index; }\r\n};\r\n\r\n  struct lda {\r\n    v_array<float> Elogtheta;\r\n    v_array<float> decay_levels;\r\n    v_array<float> total_new;\r\n    v_array<example* > examples;\r\n    v_array<float> total_lambda;\r\n    v_array<int> doc_lengths;\r\n    v_array<float> digammas;\r\n    v_array<float> v;\r\n    vector<index_feature> sorted_features;\r\n\r\n    bool total_lambda_init;\r\n    \r\n    double example_t;\r\n    vw* all;\r\n  };\r\n  \r\n#ifdef _WIN32\r\ninline float fmax(float f1, float f2) { return (f1 < f2 ? f2 : f1); }\r\ninline float fmin(float f1, float f2) { return (f1 > f2 ? f2 : f1); }\r\n#endif\r\n\r\n#define MINEIRO_SPECIAL\r\n#ifdef MINEIRO_SPECIAL\r\n\r\nnamespace {\r\n\r\ninline float \r\nfastlog2 (float x)\r\n{\r\n  union { float f; uint32_t i; } vx = { x };\r\n  union { uint32_t i; float f; } mx = { (vx.i & 0x007FFFFF) | (0x7e << 23) };\r\n  float y = (float)vx.i;\r\n  y *= 1.0f / (float)(1 << 23);\r\n\r\n  return \r\n    y - 124.22544637f - 1.498030302f * mx.f - 1.72587999f / (0.3520887068f + mx.f);\r\n}\r\n\r\ninline float\r\nfastlog (float x)\r\n{\r\n  return 0.69314718f * fastlog2 (x);\r\n}\r\n\r\ninline float\r\nfastpow2 (float p)\r\n{\r\n  float offset = (p < 0) ? 1.0f : 0.0f;\r\n  float clipp = (p < -126) ? -126.0f : p;\r\n  int w = (int)clipp;\r\n  float z = clipp - w + offset;\r\n  union { uint32_t i; float f; } v = { (uint32_t)((1 << 23) * (clipp + 121.2740838f + 27.7280233f / (4.84252568f - z) - 1.49012907f * z)) };\r\n\r\n  return v.f;\r\n}\r\n \r\ninline float\r\nfastexp (float p)\r\n{\r\n  return fastpow2 (1.442695040f * p);\r\n}\r\n\r\ninline float\r\nfastpow (float x,\r\n         float p)\r\n{\r\n  return fastpow2 (p * fastlog2 (x));\r\n}\r\n\r\ninline float\r\nfastlgamma (float x)\r\n{\r\n  float logterm = fastlog (x * (1.0f + x) * (2.0f + x));\r\n  float xp3 = 3.0f + x;\r\n\r\n  return \r\n    -2.081061466f - x + 0.0833333f / xp3 - logterm + (2.5f + x) * fastlog (xp3);\r\n}\r\n\r\ninline float\r\nfastdigamma (float x)\r\n{\r\n  float twopx = 2.0f + x;\r\n  float logterm = fastlog (twopx);\r\n\r\n  return - (1.0f + 2.0f * x) / (x * (1.0f + x)) \r\n         - (13.0f + 6.0f * x) / (12.0f * twopx * twopx) \r\n         + logterm;\r\n}\r\n\r\n#define log fastlog\r\n#define exp fastexp\r\n#define powf fastpow\r\n#define mydigamma fastdigamma\r\n#define mylgamma fastlgamma\r\n\r\n#if defined(__SSE2__) && !defined(VW_LDA_NO_SSE)\r\n\r\n#include <emmintrin.h>\r\n\r\ntypedef __m128 v4sf;\r\ntypedef __m128i v4si;\r\n\r\n#define v4si_to_v4sf _mm_cvtepi32_ps\r\n#define v4sf_to_v4si _mm_cvttps_epi32\r\n\r\nstatic inline float\r\nv4sf_index (const v4sf x,\r\n            unsigned int i)\r\n{\r\n  union { v4sf f; float array[4]; } tmp = { x };\r\n\r\n  return tmp.array[i];\r\n}\r\n\r\nstatic inline const v4sf\r\nv4sfl (float x)\r\n{\r\n  union { float array[4]; v4sf f; } tmp = { { x, x, x, x } };\r\n\r\n  return tmp.f;\r\n}\r\n\r\nstatic inline const v4si\r\nv4sil (uint32_t x)\r\n{\r\n  uint64_t wide = (((uint64_t) x) << 32) | x;\r\n  union { uint64_t array[2]; v4si f; } tmp = { { wide, wide } };\r\n\r\n  return tmp.f;\r\n}\r\n\r\nstatic inline v4sf\r\nvfastpow2 (const v4sf p)\r\n{\r\n  v4sf ltzero = _mm_cmplt_ps (p, v4sfl (0.0f));\r\n  v4sf offset = _mm_and_ps (ltzero, v4sfl (1.0f));\r\n  v4sf lt126 = _mm_cmplt_ps (p, v4sfl (-126.0f));\r\n  v4sf clipp = _mm_andnot_ps (lt126, p) + _mm_and_ps (lt126, v4sfl (-126.0f));\r\n  v4si w = v4sf_to_v4si (clipp);\r\n  v4sf z = clipp - v4si_to_v4sf (w) + offset;\r\n\r\n  const v4sf c_121_2740838 = v4sfl (121.2740838f);\r\n  const v4sf c_27_7280233 = v4sfl (27.7280233f);\r\n  const v4sf c_4_84252568 = v4sfl (4.84252568f);\r\n  const v4sf c_1_49012907 = v4sfl (1.49012907f);\r\n  union { v4si i; v4sf f; } v = {\r\n    v4sf_to_v4si (\r\n      v4sfl (1 << 23) * \r\n      (clipp + c_121_2740838 + c_27_7280233 / (c_4_84252568 - z) - c_1_49012907 * z)\r\n    )\r\n  };\r\n\r\n  return v.f;\r\n}\r\n\r\ninline v4sf\r\nvfastexp (const v4sf p)\r\n{\r\n  const v4sf c_invlog_2 = v4sfl (1.442695040f);\r\n\r\n  return vfastpow2 (c_invlog_2 * p);\r\n}\r\n\r\ninline v4sf\r\nvfastlog2 (v4sf x)\r\n{\r\n  union { v4sf f; v4si i; } vx = { x };\r\n  union { v4si i; v4sf f; } mx = { (vx.i & v4sil (0x007FFFFF)) | v4sil (0x3f000000) };\r\n  v4sf y = v4si_to_v4sf (vx.i);\r\n  y *= v4sfl (1.1920928955078125e-7f);\r\n\r\n  const v4sf c_124_22551499 = v4sfl (124.22551499f);\r\n  const v4sf c_1_498030302 = v4sfl (1.498030302f);\r\n  const v4sf c_1_725877999 = v4sfl (1.72587999f);\r\n  const v4sf c_0_3520087068 = v4sfl (0.3520887068f);\r\n\r\n  return y - c_124_22551499\r\n           - c_1_498030302 * mx.f \r\n           - c_1_725877999 / (c_0_3520087068 + mx.f);\r\n}\r\n\r\ninline v4sf\r\nvfastlog (v4sf x)\r\n{\r\n  const v4sf c_0_69314718 = v4sfl (0.69314718f);\r\n\r\n  return c_0_69314718 * vfastlog2 (x);\r\n}\r\n\r\ninline v4sf\r\nvfastdigamma (v4sf x)\r\n{\r\n  v4sf twopx = v4sfl (2.0f) + x;\r\n  v4sf logterm = vfastlog (twopx);\r\n\r\n  return (v4sfl (-48.0f) + x * (v4sfl (-157.0f) + x * (v4sfl (-127.0f) - v4sfl (30.0f) * x))) /\r\n         (v4sfl (12.0f) * x * (v4sfl (1.0f) + x) * twopx * twopx)\r\n         + logterm;\r\n}\r\n\r\nvoid\r\nvexpdigammify (vw& all, float* gamma)\r\n{\r\n  unsigned int n = all.lda;\r\n  float extra_sum = 0.0f;\r\n  v4sf sum = v4sfl (0.0f);\r\n  size_t i;\r\n\r\n  for (i = 0; i < n && ((uintptr_t) (gamma + i)) % 16 > 0; ++i)\r\n    { \r\n      extra_sum += gamma[i];\r\n      gamma[i] = fastdigamma (gamma[i]);\r\n    }\r\n\r\n  for (; i + 4 < n; i += 4)\r\n    { \r\n      v4sf arg = _mm_load_ps (gamma + i);\r\n      sum += arg;\r\n      arg = vfastdigamma (arg);\r\n      _mm_store_ps (gamma + i, arg);\r\n    }\r\n\r\n  for (; i < n; ++i)\r\n    { \r\n      extra_sum += gamma[i];\r\n      gamma[i] = fastdigamma (gamma[i]);\r\n    } \r\n\r\n  extra_sum += v4sf_index (sum, 0) + v4sf_index (sum, 1) +\r\n               v4sf_index (sum, 2) + v4sf_index (sum, 3);\r\n  extra_sum = fastdigamma (extra_sum);\r\n  sum = v4sfl (extra_sum);\r\n\r\n  for (i = 0; i < n && ((uintptr_t) (gamma + i)) % 16 > 0; ++i)\r\n    { \r\n      gamma[i] = fmaxf (1e-10f, fastexp (gamma[i] - v4sf_index (sum, 0)));\r\n    }\r\n\r\n  for (; i + 4 < n; i += 4)\r\n    { \r\n      v4sf arg = _mm_load_ps (gamma + i);\r\n      arg -= sum;\r\n      arg = vfastexp (arg);\r\n      arg = _mm_max_ps (v4sfl (1e-10f), arg);\r\n      _mm_store_ps (gamma + i, arg);\r\n    }\r\n\r\n  for (; i < n; ++i)\r\n    {\r\n      gamma[i] = fmaxf (1e-10f, fastexp (gamma[i] - v4sf_index (sum, 0)));\r\n    } \r\n}\r\n\r\nvoid vexpdigammify_2(vw& all, float* gamma, const float* norm)\r\n{\r\n  size_t n = all.lda;\r\n  size_t i;\r\n\r\n  for (i = 0; i < n && ((uintptr_t) (gamma + i)) % 16 > 0; ++i)\r\n    { \r\n      gamma[i] = fmaxf (1e-10f, fastexp (fastdigamma (gamma[i]) - norm[i]));\r\n    }\r\n\r\n  for (; i + 4 < n; i += 4)\r\n    {\r\n      v4sf arg = _mm_load_ps (gamma + i);\r\n      arg = vfastdigamma (arg);\r\n      v4sf vnorm = _mm_loadu_ps (norm + i);\r\n      arg -= vnorm;\r\n      arg = vfastexp (arg);\r\n      arg = _mm_max_ps (v4sfl (1e-10f), arg);\r\n      _mm_store_ps (gamma + i, arg);\r\n    }\r\n\r\n  for (; i < n; ++i)\r\n    {\r\n      gamma[i] = fmaxf (1e-10f, fastexp (fastdigamma (gamma[i]) - norm[i]));\r\n    }\r\n}\r\n\r\n#define myexpdigammify vexpdigammify\r\n#define myexpdigammify_2 vexpdigammify_2\r\n\r\n#else\r\n#ifndef _WIN32\r\n#warning \"lda IS NOT using sse instructions\"\r\n#endif\r\n#define myexpdigammify expdigammify\r\n#define myexpdigammify_2 expdigammify_2\r\n\r\n#endif // __SSE2__\r\n\r\n} // end anonymous namespace\r\n\r\n#else \r\n\r\n#include <boost/math/special_functions/digamma.hpp>\r\n#include <boost/math/special_functions/gamma.hpp>\r\n\r\nusing namespace boost::math::policies;\r\n\r\n#define mydigamma boost::math::digamma\r\n#define mylgamma boost::math::lgamma\r\n#define myexpdigammify expdigammify\r\n#define myexpdigammify_2 expdigammify_2\r\n\r\n#endif // MINEIRO_SPECIAL\r\n\r\nfloat decayfunc(float t, float old_t, float power_t) {\r\n  float result = 1;\r\n  for (float i = old_t+1; i <= t; i += 1)\r\n    result *= (1-powf(i, -power_t));\r\n  return result;\r\n}\r\n\r\nfloat decayfunc2(float t, float old_t, float power_t) \r\n{\r\n  float power_t_plus_one = 1.f - power_t;\r\n  float arg =  - ( powf(t, power_t_plus_one) -\r\n                   powf(old_t, power_t_plus_one));\r\n  return exp ( arg\r\n               / power_t_plus_one);\r\n}\r\n\r\nfloat decayfunc3(double t, double old_t, double power_t) \r\n{\r\n  double power_t_plus_one = 1. - power_t;\r\n  double logt = log((float)t);\r\n  double logoldt = log((float)old_t);\r\n  return (float)((old_t / t) * exp((float)(0.5*power_t_plus_one*(-logt*logt + logoldt*logoldt))));\r\n}\r\n\r\nfloat decayfunc4(double t, double old_t, double power_t)\r\n{\r\n  if (power_t > 0.99)\r\n    return decayfunc3(t, old_t, power_t);\r\n  else\r\n    return (float)decayfunc2((float)t, (float)old_t, (float)power_t);\r\n}\r\n\r\nvoid expdigammify(vw& all, float* gamma)\r\n{\r\n  float sum=0;\r\n  for (size_t i = 0; i<all.lda; i++)\r\n    {\r\n      sum += gamma[i];\r\n      gamma[i] = mydigamma(gamma[i]);\r\n    }\r\n  sum = mydigamma(sum);\r\n  for (size_t i = 0; i<all.lda; i++)\r\n    gamma[i] = fmax(1e-6f, exp(gamma[i] - sum));\r\n}\r\n\r\nvoid expdigammify_2(vw& all, float* gamma, float* norm)\r\n{\r\n  for (size_t i = 0; i<all.lda; i++)\r\n    {\r\n      gamma[i] = fmax(1e-6f, exp(mydigamma(gamma[i]) - norm[i]));\r\n    }\r\n}\r\n\r\nfloat average_diff(vw& all, float* oldgamma, float* newgamma)\r\n{\r\n  float sum = 0.;\r\n  float normalizer = 0.;\r\n  for (size_t i = 0; i<all.lda; i++) {\r\n    sum += fabsf(oldgamma[i] - newgamma[i]);\r\n    normalizer += newgamma[i];\r\n  }\r\n  return sum / normalizer;\r\n}\r\n\r\n// Returns E_q[log p(\\theta)] - E_q[log q(\\theta)].\r\n  float theta_kl(vw& all, v_array<float>& Elogtheta, float* gamma)\r\n{\r\n  float gammasum = 0;\r\n  Elogtheta.erase();\r\n  for (size_t k = 0; k < all.lda; k++) {\r\n    Elogtheta.push_back(mydigamma(gamma[k]));\r\n    gammasum += gamma[k];\r\n  }\r\n  float digammasum = mydigamma(gammasum);\r\n  gammasum = mylgamma(gammasum);\r\n  float kl = -(all.lda*mylgamma(all.lda_alpha));\r\n  kl += mylgamma(all.lda_alpha*all.lda) - gammasum;\r\n  for (size_t k = 0; k < all.lda; k++) {\r\n    Elogtheta[k] -= digammasum;\r\n    kl += (all.lda_alpha - gamma[k]) * Elogtheta[k];\r\n    kl += mylgamma(gamma[k]);\r\n  }\r\n\r\n  return kl;\r\n}\r\n\r\nfloat find_cw(vw& all, float* u_for_w, float* v)\r\n{\r\n  float c_w = 0;\r\n  for (size_t k =0; k<all.lda; k++)\r\n    c_w += u_for_w[k]*v[k];\r\n\r\n  return 1.f / c_w;\r\n}\r\n\r\nv_array<float> new_gamma;\r\nv_array<float> old_gamma;\r\n// Returns an estimate of the part of the variational bound that\r\n// doesn't have to do with beta for the entire corpus for the current\r\n// setting of lambda based on the document passed in. The value is\r\n// divided by the total number of words in the document This can be\r\n// used as a (possibly very noisy) estimate of held-out likelihood.\r\n  float lda_loop(vw& all, v_array<float>& Elogtheta, float* v,weight* weights,example* ec, float power_t)\r\n{\r\n  new_gamma.erase();\r\n  old_gamma.erase();\r\n  \r\n  for (size_t i = 0; i < all.lda; i++)\r\n    {\r\n      new_gamma.push_back(1.f);\r\n      old_gamma.push_back(0.f);\r\n    }\r\n  size_t num_words =0;\r\n  for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)\r\n    num_words += ec->atomics[*i].end - ec->atomics[*i].begin;\r\n\r\n  float xc_w = 0;\r\n  float score = 0;\r\n  float doc_length = 0;\r\n  do\r\n    {\r\n      memcpy(v,new_gamma.begin,sizeof(float)*all.lda);\r\n      myexpdigammify(all, v);\r\n\r\n      memcpy(old_gamma.begin,new_gamma.begin,sizeof(float)*all.lda);\r\n      memset(new_gamma.begin,0,sizeof(float)*all.lda);\r\n\r\n      score = 0;\r\n      size_t word_count = 0;\r\n      doc_length = 0;\r\n      for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)\r\n\t{\r\n\t  feature *f = ec->atomics[*i].begin;\r\n\t  for (; f != ec->atomics[*i].end; f++)\r\n\t    {\r\n\t      float* u_for_w = &weights[(f->weight_index&all.reg.weight_mask)+all.lda+1];\r\n\t      float c_w = find_cw(all, u_for_w,v);\r\n\t      xc_w = c_w * f->x;\r\n              score += -f->x*log(c_w);\r\n\t      size_t max_k = all.lda;\r\n\t      for (size_t k =0; k<max_k; k++) {\r\n\t\tnew_gamma[k] += xc_w*u_for_w[k];\r\n\t      }\r\n\t      word_count++;\r\n              doc_length += f->x;\r\n\t    }\r\n\t}\r\n      for (size_t k =0; k<all.lda; k++)\r\n\tnew_gamma[k] = new_gamma[k]*v[k]+all.lda_alpha;\r\n    }\r\n  while (average_diff(all, old_gamma.begin, new_gamma.begin) > all.lda_epsilon);\r\n\r\n  ec->topic_predictions.erase();\r\n  ec->topic_predictions.resize(all.lda);\r\n  memcpy(ec->topic_predictions.begin,new_gamma.begin,all.lda*sizeof(float));\r\n\r\n  score += theta_kl(all, Elogtheta, new_gamma.begin);\r\n\r\n  return score / doc_length;\r\n}\r\n\r\nsize_t next_pow2(size_t x) {\r\n  int i = 0;\r\n  x = x > 0 ? x - 1 : 0;\r\n  while (x > 0) {\r\n    x >>= 1;\r\n    i++;\r\n  }\r\n  return ((size_t)1) << i;\r\n}\r\n\r\nvoid save_load(lda& l, io_buf& model_file, bool read, bool text)\r\n{\r\n  vw* all = l.all;\r\n  uint32_t length = 1 << all->num_bits;\r\n  uint32_t stride = 1 << all->reg.stride_shift;\r\n  \r\n  if (read)\r\n    {\r\n      initialize_regressor(*all);\r\n      for (size_t j = 0; j < stride*length; j+=stride)\r\n\t{\r\n\t  for (size_t k = 0; k < all->lda; k++) {\r\n\t    if (all->random_weights) {\r\n\t      all->reg.weight_vector[j+k] = (float)(-log(frand48()) + 1.0f);\r\n\t      all->reg.weight_vector[j+k] *= (float)(all->lda_D / all->lda / all->length() * 200);\r\n\t    }\r\n\t  }\r\n\t  all->reg.weight_vector[j+all->lda] = all->initial_t;\r\n\t}\r\n    }\r\n    \r\n  if (model_file.files.size() > 0)\r\n    {\r\n      uint32_t i = 0;\r\n      uint32_t text_len;\r\n      char buff[512];\r\n      size_t brw = 1;\r\n      do \r\n\t{\r\n\t  brw = 0;\r\n\t  size_t K = all->lda;\r\n\t  \r\n\t  text_len = sprintf(buff, \"%d \", i);\r\n\t  brw += bin_text_read_write_fixed(model_file,(char *)&i, sizeof (i),\r\n\t\t\t\t\t   \"\", read,\r\n\t\t\t\t\t   buff, text_len, text);\r\n\t  if (brw != 0)\r\n\t    for (uint32_t k = 0; k < K; k++)\r\n\t      {\r\n\t\tuint32_t ndx = stride*i+k;\r\n\t\t\r\n\t\tweight* v = &(all->reg.weight_vector[ndx]);\r\n\t\ttext_len = sprintf(buff, \"%f \", *v + all->lda_rho);\r\n\t\t\r\n\t\tbrw += bin_text_read_write_fixed(model_file,(char *)v, sizeof (*v),\r\n\t\t\t\t\t\t \"\", read,\r\n\t\t\t\t\t\t buff, text_len, text);\r\n\t\t\r\n\t      }\r\n\t  if (text)\r\n\t    brw += bin_text_read_write_fixed(model_file,buff,0,\r\n\t\t\t\t\t     \"\", read,\r\n\t\t\t\t\t     \"\\n\",1,text);\r\n\t  \r\n\t  if (!read)\r\n\t    i++;\r\n\t}  \r\n      while ((!read && i < length) || (read && brw >0));\r\n    }\r\n}\r\n\r\n  void learn_batch(lda& l)\r\n  {\r\n    if (l.sorted_features.empty()) {\r\n      // This can happen when the socket connection is dropped by the client.\r\n      // If l.sorted_features is empty, then l.sorted_features[0] does not\r\n      // exist, so we should not try to take its address in the beginning of\r\n      // the for loops down there. Since it seems that there's not much to\r\n      // do in this case, we just return.\r\n      for (size_t d = 0; d < l.examples.size(); d++)\r\n\treturn_simple_example(*l.all, NULL, *l.examples[d]);\r\n      l.examples.erase();\r\n      return;\r\n    }\r\n\r\n    float eta = -1;\r\n    float minuseta = -1;\r\n\r\n    if (l.total_lambda.size() == 0)\r\n      {\r\n\tfor (size_t k = 0; k < l.all->lda; k++)\r\n\t  l.total_lambda.push_back(0.f);\r\n\t\r\n\tsize_t stride = 1 << l.all->reg.stride_shift;\r\n\tfor (size_t i =0; i <= l.all->reg.weight_mask;i+=stride)\r\n\t  for (size_t k = 0; k < l.all->lda; k++)\r\n\t    l.total_lambda[k] += l.all->reg.weight_vector[i+k];\r\n      }\r\n\r\n    l.example_t++;\r\n    l.total_new.erase();\r\n    for (size_t k = 0; k < l.all->lda; k++)\r\n      l.total_new.push_back(0.f);\r\n    \r\n    size_t batch_size = l.examples.size();\r\n   \r\n    sort(l.sorted_features.begin(), l.sorted_features.end());\r\n    \r\n    eta = l.all->eta * powf((float)l.example_t, - l.all->power_t);\r\n    minuseta = 1.0f - eta;\r\n    eta *= l.all->lda_D / batch_size;\r\n    l.decay_levels.push_back(l.decay_levels.last() + log(minuseta));\r\n    \r\n    l.digammas.erase();\r\n    float additional = (float)(l.all->length()) * l.all->lda_rho;\r\n    for (size_t i = 0; i<l.all->lda; i++) {\r\n      l.digammas.push_back(mydigamma(l.total_lambda[i] + additional));\r\n    }\r\n    \r\n    \r\n    weight* weights = l.all->reg.weight_vector;\r\n    \r\n    size_t last_weight_index = -1;\r\n    for (index_feature* s = &l.sorted_features[0]; s <= &l.sorted_features.back(); s++)\r\n      {\r\n\tif (last_weight_index == s->f.weight_index)\r\n\t  continue;\r\n\tlast_weight_index = s->f.weight_index;\r\n\tfloat* weights_for_w = &(weights[s->f.weight_index & l.all->reg.weight_mask]);\r\n\tfloat decay = fmin(1.0, exp(l.decay_levels.end[-2] - l.decay_levels.end[(int)(-1 - l.example_t+weights_for_w[l.all->lda])]));\r\n\tfloat* u_for_w = weights_for_w + l.all->lda+1;\r\n\t\r\n\tweights_for_w[l.all->lda] = (float)l.example_t;\r\n\tfor (size_t k = 0; k < l.all->lda; k++)\r\n\t  {\r\n\t    weights_for_w[k] *= decay;\r\n\t    u_for_w[k] = weights_for_w[k] + l.all->lda_rho;\r\n\t  }\r\n\tmyexpdigammify_2(*l.all, u_for_w, l.digammas.begin);\r\n      }\r\n    \r\n    for (size_t d = 0; d < batch_size; d++)\r\n      {\r\n\tfloat score = lda_loop(*l.all, l.Elogtheta, &(l.v[d*l.all->lda]), weights, l.examples[d],l.all->power_t);\r\n\tif (l.all->audit)\r\n\t  GD::print_audit_features(*l.all, *l.examples[d]);\r\n\t// If the doc is empty, give it loss of 0.\r\n\tif (l.doc_lengths[d] > 0) {\r\n\t  l.all->sd->sum_loss -= score;\r\n\t  l.all->sd->sum_loss_since_last_dump -= score;\r\n\t}\r\n\treturn_simple_example(*l.all, NULL, *l.examples[d]);\r\n      }\r\n    \r\n    for (index_feature* s = &l.sorted_features[0]; s <= &l.sorted_features.back();)\r\n      {\r\n\tindex_feature* next = s+1;\r\n\twhile(next <= &l.sorted_features.back() && next->f.weight_index == s->f.weight_index)\r\n\t  next++;\r\n\t\r\n\tfloat* word_weights = &(weights[s->f.weight_index & l.all->reg.weight_mask]);\r\n\tfor (size_t k = 0; k < l.all->lda; k++) {\r\n\t  float new_value = minuseta*word_weights[k];\r\n\t  word_weights[k] = new_value;\r\n\t}\r\n\t\r\n\tfor (; s != next; s++) {\r\n\t  float* v_s = &(l.v[s->document*l.all->lda]);\r\n\t  float* u_for_w = &weights[(s->f.weight_index & l.all->reg.weight_mask) + l.all->lda + 1];\r\n\t  float c_w = eta*find_cw(*l.all, u_for_w, v_s)*s->f.x;\r\n\t  for (size_t k = 0; k < l.all->lda; k++) {\r\n\t    float new_value = u_for_w[k]*v_s[k]*c_w;\r\n\t    l.total_new[k] += new_value;\r\n\t    word_weights[k] += new_value;\r\n\t  }\r\n\t}\r\n      }\r\n    for (size_t k = 0; k < l.all->lda; k++) {\r\n      l.total_lambda[k] *= minuseta;\r\n      l.total_lambda[k] += l.total_new[k];\r\n    }\r\n\r\n    l.sorted_features.resize(0);\r\n    \r\n    l.examples.erase();\r\n    l.doc_lengths.erase();\r\n  }\r\n  \r\n  void learn(lda& l, learner& base, example& ec) \r\n  {\r\n    size_t num_ex = l.examples.size();\r\n    l.examples.push_back(&ec);\r\n    l.doc_lengths.push_back(0);\r\n    for (unsigned char* i = ec.indices.begin; i != ec.indices.end; i++) {\r\n      feature* f = ec.atomics[*i].begin;\r\n      for (; f != ec.atomics[*i].end; f++) {\r\n\tindex_feature temp = {(uint32_t)num_ex, *f};\r\n\tl.sorted_features.push_back(temp);\r\n\tl.doc_lengths[num_ex] += (int)f->x;\r\n      }\r\n    }\r\n    if (++num_ex == l.all->minibatch)\r\n      learn_batch(l);\r\n  }\r\n\r\n  // placeholder\r\n  void predict(lda& l, learner& base, example& ec)\r\n  {\r\n    bool test_only = ec.test_only;\r\n    ec.test_only = true;\r\n    learn(l, base, ec);\r\n    ec.test_only = test_only;\r\n  }\r\n\r\n  void end_pass(lda& l)\r\n  {\r\n    if (l.examples.size())\r\n      learn_batch(l);\r\n  }\r\n\r\nvoid end_examples(lda& l)\r\n{\r\n  for (size_t i = 0; i < l.all->length(); i++) {\r\n    weight* weights_for_w = & (l.all->reg.weight_vector[i << l.all->reg.stride_shift]);\r\n    float decay = fmin(1.0, exp(l.decay_levels.last() - l.decay_levels.end[(int)(-1- l.example_t +weights_for_w[l.all->lda])]));\r\n    for (size_t k = 0; k < l.all->lda; k++) \r\n      weights_for_w[k] *= decay;\r\n  }\r\n}\r\n\r\n  void finish_example(vw& all, lda&, example& ec)\r\n{}\r\n\r\n  void finish(lda& ld)\r\n  {\r\n    ld.sorted_features.~vector<index_feature>();\r\n    ld.Elogtheta.delete_v();\r\n    ld.decay_levels.delete_v();\r\n    ld.total_new.delete_v();\r\n    ld.examples.delete_v();\r\n    ld.total_lambda.delete_v();\r\n    ld.doc_lengths.delete_v();\r\n    ld.digammas.delete_v();\r\n    ld.v.delete_v();\r\n  }\r\n\r\nlearner* setup(vw&all, vector<string>&opts, po::variables_map& vm)\r\n{\r\n  lda* ld = (lda*)calloc_or_die(1,sizeof(lda));\r\n  ld->sorted_features = vector<index_feature>();\r\n  ld->total_lambda_init = 0;\r\n  ld->all = &all;\r\n  ld->example_t = all.initial_t;\r\n\r\n  po::options_description desc(\"LDA options\");\r\n  desc.add_options()\r\n    (\"lda_alpha\", po::value<float>(&all.lda_alpha), \"Prior on sparsity of per-document topic weights\")\r\n    (\"lda_rho\", po::value<float>(&all.lda_rho), \"Prior on sparsity of topic distributions\")\r\n    (\"lda_D\", po::value<float>(&all.lda_D), \"Number of documents\")\r\n    (\"lda_epsilon\", po::value<float>(&all.lda_epsilon), \"Loop convergence threshold\")\r\n    (\"minibatch\", po::value<size_t>(&all.minibatch), \"Minibatch size, for LDA\");\r\n\r\n  po::parsed_options parsed = po::command_line_parser(opts).\r\n    style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing).\r\n    options(desc).allow_unregistered().run();\r\n  opts = po::collect_unrecognized(parsed.options, po::include_positional);\r\n  po::store(parsed, vm);\r\n  po::notify(vm);\r\n\r\n  all.p->sort_features = true;\r\n  float temp = ceilf(logf((float)(all.lda*2+1)) / logf (2.f));\r\n  all.reg.stride_shift = (size_t)temp;\r\n  all.random_weights = true;\r\n  all.add_constant = false;\r\n\r\n  if (vm.count(\"lda\") && all.eta > 1.)\r\n    {\r\n      cerr << \"your learning rate is too high, setting it to 1\" << endl;\r\n      all.eta = min(all.eta,1.f);\r\n    }\r\n\r\n  if (vm.count(\"minibatch\")) {\r\n    size_t minibatch2 = next_pow2(all.minibatch);\r\n    all.p->ring_size = all.p->ring_size > minibatch2 ? all.p->ring_size : minibatch2;\r\n  }\r\n  \r\n  ld->v.resize(all.lda*all.minibatch);\r\n  \r\n  ld->decay_levels.push_back(0.f);\r\n\r\n  all.l->finish();\r\n  learner* l = new learner(ld, 1 << all.reg.stride_shift);\r\n  l->set_learn<lda,learn>();\r\n  l->set_predict<lda,predict>();\r\n  l->set_save_load<lda,save_load>();\r\n  l->set_finish_example<lda,finish_example>();\r\n  l->set_end_examples<lda,end_examples>();  \r\n  l->set_end_pass<lda,end_pass>();  \r\n  l->set_finish<lda,finish>();\r\n  \r\n  return l;\r\n}\r\n}\r\n", "meta": {"hexsha": "788956069e4d40297575ded49afd6df705f0f4eb", "size": 22206, "ext": "cc", "lang": "C++", "max_stars_repo_path": "vowpalwabbit/lda_core.cc", "max_stars_repo_name": "singular-value/YelpGroupRecommendations", "max_stars_repo_head_hexsha": "08cdea2e5047a622ad37a45306ffc6667314a2f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-19T17:00:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T17:00:11.000Z", "max_issues_repo_path": "vowpalwabbit/lda_core.cc", "max_issues_repo_name": "singular-value/YelpGroupRecommendations", "max_issues_repo_head_hexsha": "08cdea2e5047a622ad37a45306ffc6667314a2f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vowpalwabbit/lda_core.cc", "max_forks_repo_name": "singular-value/YelpGroupRecommendations", "max_forks_repo_head_hexsha": "08cdea2e5047a622ad37a45306ffc6667314a2f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-19T17:00:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T17:00:19.000Z", "avg_line_length": 27.4148148148, "max_line_length": 141, "alphanum_fraction": 0.5898856165, "num_tokens": 7294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.058345843477109034, "lm_q1q2_score": 0.026672028190687938}}
{"text": "/**\n * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor <omarthoro@gmail.com>, 2017\n */\n#ifndef SP_ALGO_NN_LOSS_GRADIENT_HPP\n#define SP_ALGO_NN_LOSS_GRADIENT_HPP\n\n#include <boost/assert.hpp>\n#include \"../config.hpp\"\n#include \"../matrix.hpp\"\n#include \"../types.hpp\"\n#include \"sp/util/hints.hpp\"\n\n\nSP_ALGO_NN_NAMESPACE_BEGIN\n\n/**\n * \\file Gradient helper funciton\n */\n\n/**\n * \\brief Calculate the the gradient of the expected vs actual output of\n *        a mini-batch\n */\ntemplate<typename LossFunction>\nvoid gradient(LossFunction& loss, tensor_4& predicted, tensor_4& expected, tensor_4& result) {\n    BOOST_ASSERT_MSG(\n        predicted.dimensions() == expected.dimensions(),\n        \"Dimensions of Expected and Actual must match\"\n    );\n    const size_t sample_count = predicted.dimension(0);\n    for(size_t si = 0; si < sample_count; ++si) {\n        loss.derivative(si, predicted, expected, result);\n    }\n}\n\nSP_ALGO_NN_NAMESPACE_END\n\n#endif\t/* SP_ALGO_NN_LOSS_GRADIENT_HPP */\n\n", "meta": {"hexsha": "43d066293a6b9717c58e007365f84264d63e2498", "size": 1135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/algo/nn/loss/gradient.hpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sp/algo/nn/loss/gradient.hpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sp/algo/nn/loss/gradient.hpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7954545455, "max_line_length": 94, "alphanum_fraction": 0.7162995595, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.06187598053380557, "lm_q1q2_score": 0.026615788967765692}}
{"text": "/* Copyright (c) 2016 - 2019, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#ifndef ELECTRON_BEAM_TEMPLATES_HH\n#define ELECTRON_BEAM_TEMPLATES_HH\n\n#include <ElectronBeam.hh>\n#include <instantiation.hh>\n#include <utils.hh>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n\n#include <cstdlib>\n\nusing std::pow;\n\nnamespace adamantine\n{\nnamespace internal\n{\nclass PointSource : public dealii::Function<1>\n{\npublic:\n  PointSource(std::vector<double> const &position);\n\n  double value(dealii::Point<1> const &time,\n               unsigned int const component = 0) const override;\n\n  void rewind_time();\n\n  void save_time();\n\nprivate:\n  mutable unsigned int _current_pos;\n  unsigned int _saved_pos;\n  mutable dealii::Point<1> _current_time;\n  dealii::Point<1> _saved_time;\n  std::vector<double> _position;\n};\n\nPointSource::PointSource(std::vector<double> const &position)\n    : _current_pos(-1), _saved_pos(-1), _position(position)\n{\n  _current_time[0] = -1.;\n}\n\ndouble PointSource::value(dealii::Point<1> const &time,\n                          unsigned int const) const\n{\n  // If the time is greater than the current one, we use the next entry in the\n  // vector.\n  if (time[0] > _current_time[0])\n  {\n    ++_current_pos;\n    _current_time[0] = time[0];\n  }\n\n  return _position[_current_pos];\n}\n\nvoid PointSource::rewind_time()\n{\n  _current_pos = _saved_pos;\n  _current_time = _saved_time;\n}\n\nvoid PointSource::save_time()\n{\n  _saved_pos = _current_pos;\n  _saved_time = _current_time;\n}\n} // namespace internal\n\ntemplate <int dim>\nElectronBeam<dim>::ElectronBeam(boost::property_tree::ptree const &database)\n    : dealii::Function<dim>(), _is_point_source(false), _max_height(0.)\n{\n  // Set the properties of the electron beam.\n  _beam.depth = database.get<double>(\"depth\");\n  _beam.energy_conversion_eff =\n      database.get<double>(\"energy_conversion_efficiency\");\n  _beam.control_eff = database.get<double>(\"control_efficiency\");\n  _beam.diameter_squared = pow(database.get(\"diameter\", 2e-3), 2);\n  boost::optional<double> max_power =\n      database.get_optional<double>(\"max_power\");\n  if (max_power)\n    _beam.max_power = max_power.get();\n  else\n  {\n    double const current = database.get<double>(\"current\");\n    double const voltage = database.get<double>(\"voltage\");\n    _beam.max_power = current * voltage;\n  }\n\n  // The only variable that can be used to define the position is the time t.\n  std::string variable = \"t\";\n  // Predefined constants\n  std::map<std::string, double> constants;\n  constants[\"pi\"] = dealii::numbers::PI;\n\n  boost::optional<std::string> input_file =\n      database.get_optional<std::string>(\"input_file\");\n  if (input_file)\n  {\n    std::array<std::vector<double>, dim - 1> points;\n    std::string delimiter = database.get<std::string>(\"delimiter\");\n    ASSERT_THROW(boost::filesystem::exists(input_file.get()) == true,\n                 \"The file \" + input_file.get() + \" does not exist.\");\n    std::ifstream file(input_file.get());\n    std::string line;\n    // Read the file line by line, split the strings, and convert the strings\n    // into double.\n    if (file)\n    {\n      while (std::getline(file, line))\n      {\n        std::vector<std::string> split_strings;\n        boost::algorithm::split(split_strings, line,\n                                boost::is_any_of(delimiter),\n                                boost::algorithm::token_compress_on);\n        ASSERT_THROW(split_strings.size() == dim - 1,\n                     \"Problem parsing the source input file.\");\n        for (unsigned int i = 0; i < dim - 1; ++i)\n          points[i].push_back(std::atof(split_strings[i].c_str()));\n      }\n      file.close();\n    }\n\n    // Create the point source.\n    for (unsigned int i = 0; i < dim - 1; ++i)\n      _position[i].reset(new internal::PointSource(points[i]));\n    _is_point_source = true;\n  }\n  else\n  {\n    std::array<std::string, 2> position_expression = {{\"abscissa\", \"ordinate\"}};\n    for (unsigned int i = 0; i < dim - 1; ++i)\n    {\n      std::string expression =\n          database.get<std::string>(position_expression[i]);\n      _position[i].reset(new dealii::FunctionParser<1>());\n      static_cast<dealii::FunctionParser<1> *>(_position[i].get())\n          ->initialize(variable, expression, constants);\n    }\n  }\n}\n\ntemplate <int dim>\nvoid ElectronBeam<dim>::rewind_time()\n{\n  if (_is_point_source)\n    for (unsigned int i = 0; i < dim - 1; ++i)\n      static_cast<internal::PointSource *>(_position[i].get())->rewind_time();\n}\n\ntemplate <int dim>\nvoid ElectronBeam<dim>::save_time()\n{\n  if (_is_point_source)\n    for (unsigned int i = 0; i < dim - 1; ++i)\n      static_cast<internal::PointSource *>(_position[i].get())->save_time();\n}\n\ntemplate <int dim>\ndouble ElectronBeam<dim>::value(dealii::Point<dim> const &point,\n                                unsigned int const /*component*/) const\n{\n  double const z = point[1] - _max_height;\n  if ((z + _beam.depth) < 0.)\n    return 0.;\n  else\n  {\n    double const distribution_z =\n        -3. * pow(z / _beam.depth, 2) - 2. * (z / _beam.depth) + 1.;\n\n    dealii::Point<1> time;\n    time[0] = this->get_time();\n    double const beam_center_x = _position[0]->value(time);\n    double xpy_squared = pow(point[0] - beam_center_x, 2);\n    if (dim == 3)\n    {\n      double const beam_center_y = _position[1]->value(time);\n      xpy_squared += pow(point[2] - beam_center_y, 2);\n    }\n\n    double constexpr four_ln_pone = 4. * std::log(0.1);\n    double heat_source = 0.;\n    heat_source =\n        -_beam.energy_conversion_eff * _beam.control_eff * _beam.max_power *\n        four_ln_pone /\n        (dealii::numbers::PI * _beam.diameter_squared * _beam.depth) *\n        std::exp(four_ln_pone * xpy_squared / _beam.diameter_squared) *\n        distribution_z;\n\n    return heat_source;\n  }\n}\n} // namespace adamantine\n\nINSTANTIATE_DIM(ElectronBeam)\n\n#endif\n", "meta": {"hexsha": "aa0c31e5117f6a1b7ec37c1227b44107669c159f", "size": 6055, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/ElectronBeam.cc", "max_stars_repo_name": "masterleinad/adamantine", "max_stars_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/ElectronBeam.cc", "max_issues_repo_name": "masterleinad/adamantine", "max_issues_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/ElectronBeam.cc", "max_forks_repo_name": "masterleinad/adamantine", "max_forks_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1105769231, "max_line_length": 80, "alphanum_fraction": 0.6523534269, "num_tokens": 1577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.05749327678173294, "lm_q1q2_score": 0.02650536529402607}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <numeric>\n#include <sstream>\n#include <stdint.h>\n#include <string>\n#include <vector>\n#include <boost/regex.hpp> \n#include <boost/algorithm/string.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <tr1/unordered_map>\n#include <boost/function.hpp>\n\nusing namespace std;\nusing namespace boost; \nusing namespace boost::lambda; \nusing namespace std::tr1;\n\ntypedef unordered_map<char, string> ProductionMap;\nclass DOL\n{\n  public:\n    static regex matchProduction;\n\n    DOL(const std::string& source)\n    {\n      std::vector<std::string> strs;\n      boost::split(strs, source, boost::is_any_of(\"\\n\"));\n      _axiom = strs[0];\n      for_each(strs.begin()+1, strs.end(), bind(&DOL::parseLine, this, cref(_1)));\n    }\n\n    const ProductionMap& productions()const { return _productions; }\n    const string& axiom()const { return _axiom; }\n\n    std::string& step(std::string& str)const\n    {\n      string result;\n      for (std::string::const_iterator i = str.begin(); \n          i != str.end(); ++i)\n      {\n        ProductionMap::const_iterator p = _productions.find(*i);\n        if (p != _productions.end())\n        {\n          result += p->second;\n        }\n        else\n        {\n          result += *i;\n        }\n      }\n      str = result;\n      return str;\n    }\n\n    private:\n    void parseLine(const std::string& line)\n    {\n      cmatch what;\n      if(regex_match(line.c_str(), what, matchProduction)) \n      {\n        string succ(what[2]);\n        char c = *(what[1].first);\n        _productions[c] = succ;\n      }\n    }\n    std::string _axiom;\n    ProductionMap _productions;\n};\n\nregex DOL::matchProduction(\"(\\\\w)\\\\s*->\\\\s*(.+)\\\\s*$\");\n\nstd::ostream& operator<<(std::ostream& os, const DOL& rhs)\n{\n  os << \"axiom: \" << rhs.axiom() << '\\n';\n  os << \"productions:\\n\";\n  for_each(rhs.productions().begin(), rhs.productions().end(),\n      os << bind(&ProductionMap::value_type::first, _1) << \": \" \n      << bind(&ProductionMap::value_type::second, _1) << '\\n');\n  return os;\n}\n\n\nclass Turtle;\ntypedef boost::function<void(Turtle*)> Action;\ntypedef std::tr1::unordered_map<char, Action> ActionMap;\nclass Turtle\n{\n  public:\n    Turtle()\n    {\n      _actions['F'] = &Turtle::draw;\n      _actions['f'] = &Turtle::forward;\n      _actions['+'] = &Turtle::left;\n      _actions['-'] = &Turtle::right;\n    }\n\n    void render(const std::string& program)\n    {\n      for_each(program.begin(), program.end(),\n        bind(&Turtle::doAction, this, _1));\n    }\n  private:\n    void doAction(const char a) { _actions[a](this); }\n    void draw() { cout << \"draw \"; }\n    void forward() { cout << \"forward \"; }\n    void left() { cout << \"left \"; }\n    void right() { cout << \"right \"; }\n\n    ActionMap _actions; \n};\n\nint main(int argc, char **argv)\n{\n  string ts = \"F-F-F-F\\n\"\n    \"F -> F-F+F+FF-F-F+F\\n\";\n\n  DOL dol(ts);\n  cout << \"dol: \" << dol << endl;\n\n  string q(dol.axiom());\n  Turtle turtle;\n  for (int i = 0; i < 1; ++i)\n  {\n    cout << dol.step(q) << endl;\n    turtle.render(q);\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "ff7c4a2d41ef56bba056cd1e312f41a5dc29bfbc", "size": 3163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toy-problems/lsystems/dol/dol.cpp", "max_stars_repo_name": "danielgrigg/sandbox", "max_stars_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-23T03:57:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-23T03:57:39.000Z", "max_issues_repo_path": "toy-problems/lsystems/dol/dol.cpp", "max_issues_repo_name": "danielgrigg/sandbox", "max_issues_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toy-problems/lsystems/dol/dol.cpp", "max_forks_repo_name": "danielgrigg/sandbox", "max_forks_repo_head_hexsha": "95128ef44ddc2df2a819b14b9930f95d9c9fd423", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0875912409, "max_line_length": 82, "alphanum_fraction": 0.5836231426, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.05340333318956081, "lm_q1q2_score": 0.026493064068520675}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Time/TimeSteppers/AdamsBashforthN.hpp\"\n\n#include <algorithm>\n#include <boost/iterator/transform_iterator.hpp>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <ostream>\n#include <pup.h>\n#include <tuple>\n\n#include \"NumericalAlgorithms/Interpolation/LagrangePolynomial.hpp\"\n#include \"Time/BoundaryHistory.hpp\"\n#include \"Time/EvolutionOrdering.hpp\"\n#include \"Time/History.hpp\"\n#include \"Time/SelfStart.hpp\"\n#include \"Time/Time.hpp\"\n#include \"Time/TimeStepId.hpp\"\n#include \"Utilities/CachedFunction.hpp\"\n#include \"Utilities/EqualWithinRoundoff.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/ErrorHandling/Error.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/Math.hpp\"\n#include \"Utilities/Overloader.hpp\"\n\nnamespace TimeSteppers {\n\nnamespace {\n// TimeDelta-like interface to a double used for dense output\nstruct ApproximateTimeDelta {\n  double delta = std::numeric_limits<double>::signaling_NaN();\n  double value() const { return delta; }\n  bool is_positive() const { 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) {\n    return a.value() < b.value();\n  }\n};\n\n// Time-like interface to a double used for dense output\nstruct ApproximateTime {\n  double time = std::numeric_limits<double>::signaling_NaN();\n  double value() const { return time; }\n\n  // Only the operators that are actually used are defined.\n  friend ApproximateTimeDelta operator-(const ApproximateTime& a,\n                                        const Time& b) {\n    return {a.value() - b.value()};\n  }\n\n  friend bool operator<(const Time& a, const ApproximateTime& b) {\n    return a.value() < b.value();\n  }\n\n  friend bool operator<(const ApproximateTime& a, const Time& b) {\n    return a.value() < b.value();\n  }\n\n  friend std::ostream& operator<<(std::ostream& s, const ApproximateTime& t) {\n    return s << t.value();\n  }\n};\n}  // namespace\n\nAdamsBashforthN::AdamsBashforthN(const size_t order) : order_(order) {\n  if (order_ < 1 or order_ > maximum_order) {\n    ERROR(\"The order for Adams-Bashforth Nth order must be 1 <= order <= \"\n          << maximum_order);\n  }\n}\n\nsize_t AdamsBashforthN::order() const { return order_; }\n\nsize_t AdamsBashforthN::error_estimate_order() const { return order_ - 1; }\n\nsize_t AdamsBashforthN::number_of_past_steps() const { return order_ - 1; }\n\ndouble AdamsBashforthN::stable_step() const {\n  if (order_ == 1) {\n    return 1.;\n  }\n\n  // This is the condition that the characteristic polynomial of the\n  // recurrence relation defined by the method has the correct sign at\n  // -1.  It is not clear whether this is actually sufficient.\n  const auto& coefficients = constant_coefficients(order_);\n  double invstep = 0.;\n  double sign = 1.;\n  for (const auto coef : coefficients) {\n    invstep += sign * coef;\n    sign = -sign;\n  }\n  return 1. / invstep;\n}\n\nTimeStepId AdamsBashforthN::next_time_id(const TimeStepId& current_id,\n                                         const TimeDelta& time_step) const {\n  ASSERT(current_id.substep() == 0, \"Adams-Bashforth should not have substeps\");\n  return {current_id.time_runs_forward(), current_id.slab_number(),\n          current_id.step_time() + time_step};\n}\n\nstd::vector<double> AdamsBashforthN::get_coefficients_impl(\n    const std::vector<double>& steps) {\n  const size_t order = steps.size();\n  ASSERT(order >= 1 and order <= maximum_order, \"Bad order\" << order);\n  if (std::all_of(steps.begin(), steps.end(), [&steps](const double s) {\n        return equal_within_roundoff(\n            s, steps[0], 10.0 * std::numeric_limits<double>::epsilon(), 0.0);\n      })) {\n    return constant_coefficients(order);\n  }\n\n  return variable_coefficients(steps);\n}\n\nstd::vector<double> AdamsBashforthN::variable_coefficients(\n    const std::vector<double>& steps) {\n  const size_t order = steps.size();  // \"k\" in below equations\n  std::vector<double> result;\n  result.reserve(order);\n\n  // The `steps` vector contains the step sizes:\n  //   steps = {dt_{n-k+1}, ..., dt_n}\n  // Our goal is to calculate, for each j, the coefficient given by\n  //   \\int_0^1 dt ell_j(t dt_n; dt_n, dt_n + dt_{n-1}, ...,\n  //                             dt_n + ... + dt_{n-k+1})\n  // (Where the ell_j are the Lagrange interpolating polynomials.)\n\n  std::vector<double> poly(order);\n  double step_sum_j = 0.0;\n  for (size_t j = 0; j < order; ++j) {\n    // Calculate coefficients of the Lagrange interpolating polynomials,\n    // in the standard a_0 + a_1 t + a_2 t^2 + ... form.\n    std::fill(poly.begin(), poly.end(), 0.0);\n\n    step_sum_j += steps[order - j - 1];\n    poly[0] = 1.0;\n\n    double step_sum_m = 0.0;\n    for (size_t m = 0; m < order; ++m) {\n      step_sum_m += steps[order - m - 1];\n      if (m == j) {\n        continue;\n      }\n      const double denom = 1.0 / (step_sum_j - step_sum_m);\n      for (size_t i = m < j ? m + 1 : m; i > 0; --i) {\n        poly[i] = (poly[i - 1] - poly[i] * step_sum_m) * denom;\n      }\n      poly[0] *= -step_sum_m * denom;\n    }\n\n    // Integrate p(t dt_n), term by term.\n    for (size_t m = 0; m < order; ++m) {\n      poly[m] /= m + 1.0;\n    }\n    result.push_back(evaluate_polynomial(poly, steps.back()));\n  }\n  return result;\n}\n\nstd::vector<double> AdamsBashforthN::constant_coefficients(const size_t order) {\n  switch (order) {\n    case 1: return {1.};\n    case 2: return {1.5, -0.5};\n    case 3: return {23.0 / 12.0, -4.0 / 3.0, 5.0 / 12.0};\n    case 4: return {55.0 / 24.0, -59.0 / 24.0, 37.0 / 24.0, -3.0 / 8.0};\n    case 5: return {1901.0 / 720.0, -1387.0 / 360.0, 109.0 / 30.0,\n          -637.0 / 360.0, 251.0 / 720.0};\n    case 6: return {4277.0 / 1440.0, -2641.0 / 480.0, 4991.0 / 720.0,\n          -3649.0 / 720.0, 959.0 / 480.0, -95.0 / 288.0};\n    case 7: return {198721.0 / 60480.0, -18637.0 / 2520.0, 235183.0 / 20160.0,\n          -10754.0 / 945.0, 135713.0 / 20160.0, -5603.0 / 2520.0,\n          19087.0 / 60480.0};\n    case 8: return {16083.0 / 4480.0, -1152169.0 / 120960.0, 242653.0 / 13440.0,\n          -296053.0 / 13440.0, 2102243.0 / 120960.0, -115747.0 / 13440.0,\n          32863.0 / 13440.0, -5257.0 / 17280.0};\n    default:\n      ERROR(\"Bad order: \" << order);\n  }\n}\n\nvoid AdamsBashforthN::pup(PUP::er& p) {\n  LtsTimeStepper::pup(p);\n  p | order_;\n}\n\ntemplate <typename T>\nvoid AdamsBashforthN::update_u_impl(\n    const gsl::not_null<T*> u, const gsl::not_null<UntypedHistory<T>*> history,\n    const TimeDelta& time_step) const {\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_common(u, *history, time_step, history->integration_order());\n}\n\ntemplate <typename T>\nbool AdamsBashforthN::update_u_impl(\n    const gsl::not_null<T*> u, const gsl::not_null<T*> u_error,\n    const gsl::not_null<UntypedHistory<T>*> history,\n    const TimeDelta& time_step) const {\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_common(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_common(u_error, *history, time_step,\n                  history->integration_order() - 1);\n  *u_error = *u - *u_error;\n  return true;\n}\n\ntemplate <typename T>\nbool AdamsBashforthN::dense_update_u_impl(const gsl::not_null<T*> u,\n                                          const UntypedHistory<T>& history,\n                                          const double time) const {\n  const ApproximateTimeDelta time_step{time - history.back().value()};\n  update_u_common(make_not_null(&*make_math_wrapper(u)), history, time_step,\n                  history.integration_order());\n  return true;\n}\n\ntemplate <typename T, typename Delta>\nvoid AdamsBashforthN::update_u_common(const gsl::not_null<T*> u,\n                                      const UntypedHistory<T>& history,\n                                      const Delta& time_step,\n                                      const size_t order) const {\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 UntypedHistory<T>::difference_type>(order);\n  const auto coefficients =\n      get_coefficients(history_start, history.end(), time_step);\n\n  *u = *history.untyped_most_recent_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 T>\nbool AdamsBashforthN::can_change_step_size_impl(\n    const TimeStepId& time_id, const UntypedHistory<T>& history) const {\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 not ::SelfStart::is_self_starting(time_id) and\n         (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 T>\nvoid AdamsBashforthN::add_boundary_delta_impl(\n    const gsl::not_null<T*> result,\n    const TimeSteppers::BoundaryHistoryEvaluator<T>& coupling,\n    const TimeSteppers::BoundaryHistoryCleaner& cleaner,\n    const TimeDelta& time_step) const {\n  const auto signed_order =\n      static_cast<typename decltype(cleaner.local_end())::difference_type>(\n          cleaner.integration_order());\n\n  ASSERT(cleaner.local_size() >= cleaner.integration_order(),\n         \"Insufficient data to take an order-\" << cleaner.integration_order()\n         << \" step.  Have \" << cleaner.local_size() << \" times, need \"\n         << cleaner.integration_order());\n  cleaner.local_mark_unneeded(cleaner.local_end() - signed_order);\n\n  if (std::equal(cleaner.local_begin(), cleaner.local_end(),\n                 cleaner.remote_end() - signed_order)) {\n    // GTS\n    ASSERT(cleaner.remote_size() >= cleaner.integration_order(),\n           \"Insufficient data to take an order-\" << cleaner.integration_order()\n           << \" step.  Have \" << cleaner.remote_size() << \" times, need \"\n           << cleaner.integration_order());\n    cleaner.remote_mark_unneeded(cleaner.remote_end() - signed_order);\n  } else {\n    const auto remote_step_for_step_start =\n        std::upper_bound(cleaner.remote_begin(), cleaner.remote_end(),\n                         *(cleaner.local_end() - 1),\n                         evolution_less<Time>{time_step.is_positive()});\n    ASSERT(remote_step_for_step_start - cleaner.remote_begin() >= signed_order,\n           \"Insufficient data to take an order-\" << cleaner.integration_order()\n           << \" step.  Have \"\n           << remote_step_for_step_start - cleaner.remote_begin()\n           << \" times before the step, need \" << cleaner.integration_order());\n    cleaner.remote_mark_unneeded(remote_step_for_step_start - signed_order);\n  }\n\n  boundary_impl(result, coupling, *(cleaner.local_end() - 1) + time_step);\n}\n\ntemplate <typename T>\nvoid AdamsBashforthN::boundary_dense_output_impl(\n    const gsl::not_null<T*> result,\n    const TimeSteppers::BoundaryHistoryEvaluator<T>& coupling,\n    const double time) const {\n  return boundary_impl(result, coupling, ApproximateTime{time});\n}\n\ntemplate <typename T, typename TimeType>\nvoid AdamsBashforthN::boundary_impl(const gsl::not_null<T*> result,\n                                    const BoundaryHistoryEvaluator<T>& coupling,\n                                    const TimeType& end_time) const {\n  // Might be different from order_ during self-start.\n  const auto current_order = coupling.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(coupling.remote_size() >= current_order,\n         \"Remote history is too short (\" << coupling.remote_size()\n         << \" should be at least \" << current_order << \")\");\n\n  // Avoid billions of casts\n  const auto order_s = static_cast<\n      typename BoundaryHistoryEvaluator<T>::iterator::difference_type>(\n      current_order);\n\n  // Start and end of the step we are trying to take\n  const Time start_time = *(coupling.local_end() - 1);\n  const auto time_step = end_time - start_time;\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 = coupling.local_end() - order_s;\n\n  if (std::equal(local_begin, coupling.local_end(),\n                 coupling.remote_end() - order_s)) {\n    // No local time-stepping going on.\n    const auto coefficients =\n        get_coefficients(local_begin, coupling.local_end(), time_step);\n\n    auto local_it = local_begin;\n    auto remote_it = coupling.remote_end() - order_s;\n    for (auto coefficients_it = coefficients.rbegin();\n         coefficients_it != coefficients.rend();\n         ++coefficients_it, ++local_it, ++remote_it) {\n      *result +=\n          time_step.value() * *coefficients_it * *coupling(local_it, remote_it);\n    }\n    return;\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(coupling.remote_begin(), coupling.remote_end(),\n                       start_time, less) -\n      order_s;\n\n  ASSERT(std::is_sorted(local_begin, coupling.local_end(), less),\n         \"Local history not in order\");\n  ASSERT(std::is_sorted(remote_begin, coupling.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(*(coupling.remote_end() - 1), end_time),\n         \"Please supply only older data: \" << *(coupling.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 = [&coupling, &local_begin, &remote_begin, &less]() {\n    std::vector<Time> ret;\n    ret.reserve(coupling.local_size() + coupling.remote_size());\n    std::set_union(local_begin, coupling.local_end(), remote_begin,\n                   coupling.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) {\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 = [order_s,\n                                    &union_times](const UnionIter& it) {\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>, std::map>(\n          [order_s](const std::tuple<UnionIter, TimeDelta>& args) {\n            return get_coefficients(\n                std::get<0>(args) -\n                    static_cast<typename UnionIter::difference_type>(order_s -\n                                                                     1),\n                std::get<0>(args) + 1, std::get<1>(args));\n          }),\n      make_cached_function<std::tuple<UnionIter, ApproximateTimeDelta>,\n                           std::map>(\n          [order_s](const std::tuple<UnionIter, ApproximateTimeDelta>& args) {\n            return get_coefficients(\n                std::get<0>(args) -\n                    static_cast<typename UnionIter::difference_type>(order_s -\n                                                                     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,\n                                const UnionIter& evaluation_step) {\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 != coupling.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 != coupling.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) {\n          return boost::make_transform_iterator(\n              it, [](const Time& t) { 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, coupling.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(coupling.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, coupling.remote_end(),\n                                   *local_evaluation_step, less)) {\n          auto union_step_upper_bound =\n              advance_within_step(union_local_evaluation_step);\n          if (coupling.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        *result += deriv_coef *\n                   *coupling(local_evaluation_step, remote_evaluation_step);\n      }\n    }  // for remote_evaluation_step\n  }  // for local_evaluation_step\n}\n\ntemplate <typename Iterator, typename Delta>\nstd::vector<double> AdamsBashforthN::get_coefficients(\n    const Iterator& times_begin, const Iterator& times_end, const Delta& step) {\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\nbool operator==(const AdamsBashforthN& lhs, const AdamsBashforthN& rhs) {\n  return lhs.order_ == rhs.order_;\n}\n\nbool operator!=(const AdamsBashforthN& lhs, const AdamsBashforthN& rhs) {\n  return not(lhs == rhs);\n}\n\nTIME_STEPPER_DEFINE_OVERLOADS(AdamsBashforthN)\nLTS_TIME_STEPPER_DEFINE_OVERLOADS(AdamsBashforthN)\n}  // namespace TimeSteppers\n\nPUP::able::PUP_ID TimeSteppers::AdamsBashforthN::my_PUP_ID =  // NOLINT\n    0;\n", "meta": {"hexsha": "46366e859dfa881726a1f2757c6e6d49cfc0a4b9", "size": 24287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Time/TimeSteppers/AdamsBashforthN.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:17:33.000Z", "max_issues_repo_path": "src/Time/TimeSteppers/AdamsBashforthN.cpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["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.4783333333, "max_line_length": 80, "alphanum_fraction": 0.6375838926, "num_tokens": 5788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.05500528364610641, "lm_q1q2_score": 0.026428865971931375}}
{"text": "//=======================================================================\n// Copyright (c) 2014 Piotr Smulewicz\n//               2013 Piotr Wygocki\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file steiner_tree_greedy.hpp\n * @brief\n * @author Piotr Wygocki, Piotr Smulewicz\n * @version 1.0\n * @date 2013-11-27\n */\n#ifndef PAAL_STEINER_TREE_GREEDY_HPP\n#define PAAL_STEINER_TREE_GREEDY_HPP\n\n#include \"paal/utils/accumulate_functors.hpp\"\n#include \"paal/utils/functors.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/two_bit_color_map.hpp>\n\n#include <boost/property_map/property_map.hpp>\n\n#include <boost/range/algorithm/copy.hpp>\n#include <boost/range/algorithm/fill.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/range/algorithm/unique.hpp>\n#include <boost/range/as_array.hpp>\n#include <boost/range/numeric.hpp>\n\n#include <algorithm>\n#include <utility>\n\n/// enum for edge base property\nenum edge_base_t { edge_base };\n\nnamespace boost {\n/// macro create edge base property\nBOOST_INSTALL_PROPERTY(edge, base);\n}\n\nnamespace paal {\n\n/**\n * @brief enum indicates if given color represents terminal or NONTERMINAL.\n */\nenum Terminals { NONTERMINAL, TERMINAL };\n\nnamespace detail {\ntemplate <typename NearestMap, typename LastEdgeMap, typename Tag>\nclass nearest_recorder\n    : boost::base_visitor<nearest_recorder<NearestMap, LastEdgeMap, Tag>> {\n  public:\n    using event_filter = Tag;\n    nearest_recorder(NearestMap &nearest_map, LastEdgeMap &vpred)\n        : m_nearest_map(nearest_map), m_vpred(vpred) {};\n    template <typename Edge, typename Graph>\n    void operator()(Edge const e, Graph const &g) {\n        m_nearest_map[target(e, g)] = m_nearest_map[source(e, g)];\n        m_vpred[target(e, g)] = e;\n    }\n\n  private:\n    NearestMap &m_nearest_map;\n    LastEdgeMap &m_vpred;\n};\n\ntemplate <typename NearestMap, typename LastEdgeMap, typename Tag>\nnearest_recorder<NearestMap, LastEdgeMap, Tag>\nmake_nearest_recorder(NearestMap &nearest_map, LastEdgeMap &vpred, Tag) {\n    return nearest_recorder<NearestMap, LastEdgeMap, Tag>{ nearest_map, vpred };\n}\n}\n/**\n * @brief non-named version of  steiner_tree_greedy\n *\n * @tparam Graph\n * @tparam OutputIterator\n * @tparam EdgeWeightMap\n * @tparam ColorMap\n * @param g - given graph\n * @param out - edge output iterator\n * @param edge_weight\n * @param color_map\n */\ntemplate <typename Graph, typename OutputIterator, typename EdgeWeightMap,\n          typename ColorMap>\nauto steiner_tree_greedy(const Graph &g, OutputIterator out,\n                         EdgeWeightMap edge_weight, ColorMap color_map)\n    -> typename std::pair<\n          typename boost::property_traits<EdgeWeightMap>::value_type,\n          typename boost::property_traits<EdgeWeightMap>::value_type> {\n    using Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\n    using Edge = typename boost::graph_traits<Graph>::edge_descriptor;\n    using Base = typename boost::property<edge_base_t, Edge>;\n    using Weight = typename boost::property_traits<EdgeWeightMap>::value_type;\n    using WeightProperty =\n        typename boost::property<boost::edge_weight_t, Weight, Base>;\n    using TerminalGraph =\n        boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n                              boost::no_property, WeightProperty>;\n    using EdgeTerminal =\n        typename boost::graph_traits<TerminalGraph>::edge_descriptor;\n\n    auto N = num_vertices(g);\n\n    // distance array used in the dijkstra runs\n    std::vector<Weight> distance(N);\n\n    // computing terminals\n    std::vector<int> terminals;\n    auto terminals_nr = accumulate_functor(\n        vertices(g), 0, [=](Vertex v) { return get(color_map, v); });\n    terminals.reserve(terminals_nr);\n    for (auto v : boost::as_array(vertices(g))) {\n        if (get(color_map, v) == Terminals::TERMINAL) {\n            terminals.push_back(v);\n        }\n    }\n    if (terminals.empty()) {\n        return std::make_pair(Weight{}, Weight{});\n    }\n    std::vector<Vertex> nearest_terminal(num_vertices(g));\n    auto index = get(boost::vertex_index, g);\n    auto nearest_terminal_map = boost::make_iterator_property_map(\n        nearest_terminal.begin(), get(boost::vertex_index, g));\n    for (auto terminal : terminals) {\n        nearest_terminal_map[terminal] = terminal;\n    }\n\n    // compute voronoi diagram each vertex get nearest terminal and last edge on\n    // path to nearest terminal\n    auto distance_map = make_iterator_property_map(distance.begin(), index);\n    std::vector<Edge> vpred(N);\n    auto last_edge = boost::make_iterator_property_map(\n        vpred.begin(), get(boost::vertex_index, g));\n    boost::dijkstra_shortest_paths(\n        g, terminals.begin(), terminals.end(), boost::dummy_property_map(),\n        distance_map, edge_weight, index, utils::less(),\n        boost::closed_plus<Weight>(), std::numeric_limits<Weight>::max(), 0,\n        boost::make_dijkstra_visitor(detail::make_nearest_recorder(\n            nearest_terminal_map, last_edge, boost::on_edge_relaxed{})));\n\n    // computing distances between terminals\n    // creating terminal_graph\n    TerminalGraph terminal_graph(N);\n    for (auto w : boost::as_array(edges(g))) {\n        auto const &nearest_to_source = nearest_terminal_map[source(w, g)];\n        auto const &nearest_to_target = nearest_terminal_map[target(w, g)];\n        if (nearest_to_source != nearest_to_target) {\n            add_edge(nearest_to_source, nearest_to_target,\n                     WeightProperty(distance[source(w, g)] +\n                                        distance[target(w, g)] + edge_weight[w],\n                                    Base(w)),\n                     terminal_graph);\n        }\n    }\n    // computing spanning tree on terminal_graph\n    std::vector<Edge> terminal_edge;\n    boost::kruskal_minimum_spanning_tree(terminal_graph,\n                                         std::back_inserter(terminal_edge));\n\n    // computing result\n    std::vector<Edge> tree_edges;\n    tree_edges.reserve(terminals_nr);\n    for (auto edge : terminal_edge) {\n        auto base = get(edge_base, terminal_graph, edge);\n        tree_edges.push_back(base);\n        for (auto pom : { source(base, g), target(base, g) }) {\n            while (nearest_terminal_map[pom] != pom) {\n                tree_edges.push_back(vpred[pom]);\n                pom = source(vpred[pom], g);\n            }\n        }\n    }\n\n    // because in each voronoi region we have unique patch to all vertex from\n    // terminal, result graph contain no cycle\n    // and all leaf are terminal\n\n    boost::sort(tree_edges);\n    auto get_weight=[&](Edge edge){return edge_weight[edge];};\n    auto lower_bound=accumulate_functor(tree_edges, Weight{}, get_weight);\n    auto unique_edges = boost::unique(tree_edges);\n    auto cost_solution=accumulate_functor(unique_edges, Weight{}, get_weight);\n    boost::copy(unique_edges, out);\n    return std::make_pair(cost_solution, lower_bound / 2.);\n}\n\n/**\n * @brief named version of  steiner_tree_greedy\n *\n * @tparam Graph\n * @tparam OutputIterator\n * @tparam P\n * @tparam T\n * @tparam R\n * @param g - given graph\n * @param out - edge output iterator\n * @param params\n */\ntemplate <typename Graph, typename OutputIterator, typename P, typename T,\n          typename R>\nauto steiner_tree_greedy(const Graph &g, OutputIterator out,\n                         const boost::bgl_named_params<P, T, R> &params) {\n    return steiner_tree_greedy(\n        g, out, choose_const_pmap(get_param(params, boost::edge_weight), g,\n                                  boost::edge_weight),\n        choose_const_pmap(get_param(params, boost::vertex_color), g,\n                          boost::vertex_color));\n}\n\n/**\n * @brief version of  steiner_tree_greedy with all default parameters\n *\n * @tparam Graph\n * @tparam OutputIterator\n * @param g - given graph\n * @param out - edge output iterator\n */\ntemplate <typename Graph, typename OutputIterator>\nauto steiner_tree_greedy(const Graph &g, OutputIterator out) {\n    return steiner_tree_greedy(g, out, boost::no_named_parameters());\n}\n\n} // paal\n\n#endif // PAAL_STEINER_TREE_GREEDY_HPP\n", "meta": {"hexsha": "5ae6b093fa46ecffd2ff281b00b1c59536f8b4be", "size": 8573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/greedy/steiner_tree_greedy.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/greedy/steiner_tree_greedy.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/greedy/steiner_tree_greedy.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.0210084034, "max_line_length": 80, "alphanum_fraction": 0.671643532, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215779698935, "lm_q2_score": 0.061875980966291995, "lm_q1q2_score": 0.026379065843984698}}
{"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, 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 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_INIT_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_INIT_HPP\r\n\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/range.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/condition.hpp>\r\n\r\n#include <boost/geometry/srs/projections/impl/dms_parser.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_datum_set.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_datums.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_ell_set.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_units.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/proj4.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry { namespace projections\r\n{\r\n\r\n\r\nnamespace detail\r\n{\r\n\r\ntemplate <typename BGParams, typename T>\r\ninline void pj_push_defaults(BGParams const& /*bg_params*/, parameters<T>& pin)\r\n{\r\n    pin.params.push_back(pj_mkparam<T>(\"ellps\", \"WGS84\"));\r\n\r\n    if (pin.name == \"aea\")\r\n    {\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_1\", \"29.5\"));\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_2\", \"45.5 \"));\r\n    }\r\n    else if (pin.name == \"lcc\")\r\n    {\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_1\", \"33\"));\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_2\", \"45\"));\r\n    }\r\n    else if (pin.name == \"lagrng\")\r\n    {\r\n        pin.params.push_back(pj_mkparam<T>(\"W\", \"2\"));\r\n    }\r\n}\r\n\r\ntemplate <BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX, typename T>\r\ninline void pj_push_defaults(srs::static_proj4<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& /*bg_params*/,\r\n                             parameters<T>& pin)\r\n{\r\n    typedef srs::static_proj4<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> static_parameters_type;\r\n    typedef typename srs::par4::detail::pick_proj_tag\r\n        <\r\n            static_parameters_type\r\n        >::type proj_tag;\r\n\r\n    // statically defaulting to WGS84\r\n    //pin.params.push_back(pj_mkparam(\"ellps\", \"WGS84\"));\r\n\r\n    if (BOOST_GEOMETRY_CONDITION((boost::is_same<proj_tag, srs::par4::aea>::value)))\r\n    {\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_1\", \"29.5\"));\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_2\", \"45.5 \"));\r\n    }\r\n    else if (BOOST_GEOMETRY_CONDITION((boost::is_same<proj_tag, srs::par4::lcc>::value)))\r\n    {\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_1\", \"33\"));\r\n        pin.params.push_back(pj_mkparam<T>(\"lat_2\", \"45\"));\r\n    }\r\n    else if (BOOST_GEOMETRY_CONDITION((boost::is_same<proj_tag, srs::par4::lagrng>::value)))\r\n    {\r\n        pin.params.push_back(pj_mkparam<T>(\"W\", \"2\"));\r\n    }\r\n}\r\n\r\ntemplate <typename T>\r\ninline void pj_init_units(std::vector<pvalue<T> > const& params,\r\n                          std::string const& sunits,\r\n                          std::string const& sto_meter,\r\n                          T & to_meter,\r\n                          T & fr_meter,\r\n                          T const& default_to_meter,\r\n                          T const& default_fr_meter)\r\n{\r\n    std::string s;\r\n    std::string units = pj_get_param_s(params, sunits);\r\n    if (! units.empty())\r\n    {\r\n        const int n = sizeof(pj_units) / sizeof(pj_units[0]);\r\n        int index = -1;\r\n        for (int i = 0; i < n && index == -1; i++)\r\n        {\r\n            if(pj_units[i].id == units)\r\n            {\r\n                index = i;\r\n            }\r\n        }\r\n\r\n        if (index == -1) {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unknow_unit_id) );\r\n        }\r\n        s = pj_units[index].to_meter;\r\n    }\r\n\r\n    if (s.empty())\r\n    {\r\n        s = pj_get_param_s(params, sto_meter);\r\n    }\r\n\r\n    if (! s.empty())\r\n    {\r\n        std::size_t const pos = s.find('/');\r\n        if (pos == std::string::npos)\r\n        {\r\n            to_meter = geometry::str_cast<T>(s);\r\n        }\r\n        else\r\n        {\r\n            T const numerator = geometry::str_cast<T>(s.substr(0, pos));\r\n            T const denominator = geometry::str_cast<T>(s.substr(pos + 1));\r\n            if (numerator == 0.0 || denominator == 0.0)\r\n            {\r\n                BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );\r\n            }\r\n            to_meter = numerator / denominator;\r\n        }\r\n        if (to_meter == 0.0)\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );\r\n        }\r\n        fr_meter = 1. / to_meter;\r\n    }\r\n    else\r\n    {\r\n        to_meter = default_to_meter;\r\n        fr_meter = default_fr_meter;\r\n    }\r\n}\r\n\r\n/************************************************************************/\r\n/*                              pj_init()                               */\r\n/*                                                                      */\r\n/*      Main entry point for initialing a PJ projections                */\r\n/*      definition.  Note that the projection specific function is      */\r\n/*      called to do the initial allocation so it can be created        */\r\n/*      large enough to hold projection specific parameters.            */\r\n/************************************************************************/\r\ntemplate <typename T, typename BGParams, typename R>\r\ninline parameters<T> pj_init(BGParams const& bg_params, R const& arguments, bool use_defaults = true)\r\n{\r\n    parameters<T> pin;\r\n    for (std::vector<std::string>::const_iterator it = boost::begin(arguments);\r\n        it != boost::end(arguments); it++)\r\n    {\r\n        pin.params.push_back(pj_mkparam<T>(*it));\r\n    }\r\n\r\n    // maybe TODO: handle \"init\" parameter\r\n    /* check if +init present */\r\n    //std::string sinit;\r\n    //if (pj_param_s(pin.params, \"init\", sinit))\r\n    //{\r\n    //    //if (!(curr = get_init(&arguments, curr, sinit)))\r\n    //}\r\n\r\n    // find projection -> implemented in projection factory\r\n    pin.name = pj_get_param_s(pin.params, \"proj\");\r\n    // exception thrown in projection<>\r\n    // TODO: consider throwing here both projection_unknown_id_exception and\r\n    // projection_not_named_exception in order to throw before other exceptions\r\n    //if (pin.name.empty())\r\n    //{ BOOST_THROW_EXCEPTION( projection_not_named_exception() ); }\r\n\r\n    // set defaults, unless inhibited\r\n    // GL-Addition, if use_defaults is false then defaults are ignored\r\n    if (use_defaults && ! pj_get_param_b(pin.params, \"no_defs\"))\r\n    {\r\n        // proj4 gets defaults from \"proj_def.dat\", file of 94/02/23 with a few defaults.\r\n        // Here manually\r\n        pj_push_defaults(bg_params, pin);\r\n        //curr = get_defaults(&arguments, curr, name);\r\n    }\r\n\r\n    /* allocate projection structure */\r\n    // done by BGParams constructor:\r\n    // pin.is_latlong = 0;\r\n    // pin.is_geocent = 0;\r\n    // pin.long_wrap_center = 0.0;\r\n    // pin.long_wrap_center = 0.0;\r\n    pin.is_long_wrap_set = false;\r\n\r\n    /* set datum parameters */\r\n    pj_datum_set(bg_params, pin.params, pin);\r\n\r\n    /* set ellipsoid/sphere parameters */\r\n    pj_ell_set(bg_params, pin.params, pin.a, pin.es);\r\n\r\n    pin.a_orig = pin.a;\r\n    pin.es_orig = pin.es;\r\n\r\n    pin.e = sqrt(pin.es);\r\n    pin.ra = 1. / pin.a;\r\n    pin.one_es = 1. - pin.es;\r\n    if (pin.one_es == 0.) {\r\n        BOOST_THROW_EXCEPTION( projection_exception(error_eccentricity_is_one) );\r\n    }\r\n    pin.rone_es = 1./pin.one_es;\r\n\r\n    /* Now that we have ellipse information check for WGS84 datum */\r\n    if( pin.datum_type == datum_3param\r\n        && pin.datum_params[0] == 0.0\r\n        && pin.datum_params[1] == 0.0\r\n        && pin.datum_params[2] == 0.0\r\n        && pin.a == 6378137.0\r\n        && geometry::math::abs(pin.es - 0.006694379990) < 0.000000000050 )/*WGS84/GRS80*/\r\n    {\r\n        pin.datum_type = datum_wgs84;\r\n    }\r\n\r\n    /* set pin.geoc coordinate system */\r\n    pin.geoc = (pin.es && pj_get_param_b(pin.params, \"geoc\"));\r\n\r\n    /* over-ranging flag */\r\n    pin.over = pj_get_param_b(pin.params, \"over\");\r\n\r\n    /* longitude center for wrapping */\r\n    pin.is_long_wrap_set = pj_param_r(pin.params, \"lon_wrap\", pin.long_wrap_center);\r\n\r\n    /* central meridian */\r\n    pin.lam0 = pj_get_param_r(pin.params, \"lon_0\");\r\n\r\n    /* central latitude */\r\n    pin.phi0 = pj_get_param_r(pin.params, \"lat_0\");\r\n\r\n    /* false easting and northing */\r\n    pin.x0 = pj_get_param_f(pin.params, \"x_0\");\r\n    pin.y0 = pj_get_param_f(pin.params, \"y_0\");\r\n\r\n    /* general scaling factor */\r\n    if (pj_param_f(pin.params, \"k_0\", pin.k0)) {\r\n        /* empty */\r\n    } else if (pj_param_f(pin.params, \"k\", pin.k0)) {\r\n        /* empty */\r\n    } else\r\n        pin.k0 = 1.;\r\n    if (pin.k0 <= 0.) {\r\n        BOOST_THROW_EXCEPTION( projection_exception(error_k_less_than_zero) );\r\n    }\r\n\r\n    /* set units */\r\n    pj_init_units(pin.params, \"units\", \"to_meter\",\r\n                  pin.to_meter, pin.fr_meter, 1., 1.);\r\n    pj_init_units(pin.params, \"vunits\", \"vto_meter\",\r\n                  pin.vto_meter, pin.vfr_meter, pin.to_meter, pin.fr_meter);\r\n\r\n    /* prime meridian */\r\n    std::string pm = pj_get_param_s(pin.params, \"pm\");\r\n    if (! pm.empty())\r\n    {\r\n        std::string value;\r\n\r\n        int n = sizeof(pj_prime_meridians) / sizeof(pj_prime_meridians[0]);\r\n        for (int i = 0; i < n ; i++)\r\n        {\r\n            if(pj_prime_meridians[i].id == pm)\r\n            {\r\n                value = pj_prime_meridians[i].defn;\r\n                break;\r\n            }\r\n        }\r\n\r\n        dms_parser<T, true> parser;\r\n\r\n        // TODO: Is this try-catch needed?\r\n        // In other cases the bad_str_cast exception is simply thrown\r\n        BOOST_TRY\r\n        {\r\n            if (value.empty()) {\r\n                pin.from_greenwich = parser.apply(pm).angle();\r\n            } else {\r\n                pin.from_greenwich = parser.apply(value).angle();\r\n            }\r\n        }\r\n        BOOST_CATCH(geometry::bad_str_cast const&)\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unknown_prime_meridian) );\r\n        }\r\n        BOOST_CATCH_END\r\n    }\r\n    else\r\n    {\r\n        pin.from_greenwich = 0.0;\r\n    }\r\n\r\n    return pin;\r\n}\r\n\r\n/************************************************************************/\r\n/*                            pj_init_plus()                            */\r\n/*                                                                      */\r\n/*      Same as pj_init() except it takes one argument string with      */\r\n/*      individual arguments preceeded by '+', such as \"+proj=utm       */\r\n/*      +zone=11 +ellps=WGS84\".                                         */\r\n/************************************************************************/\r\ntemplate <typename T, typename BGParams>\r\ninline parameters<T> pj_init_plus(BGParams const& bg_params, std::string const& definition, bool use_defaults = true)\r\n{\r\n    const char* sep = \" +\";\r\n\r\n    /* split into arguments based on '+' and trim white space */\r\n\r\n    // boost::split splits on one character, here it should be on \" +\", so implementation below\r\n    // todo: put in different routine or sort out\r\n    std::vector<std::string> arguments;\r\n    std::string def = boost::trim_copy(definition);\r\n    boost::trim_left_if(def, boost::is_any_of(sep));\r\n\r\n    std::string::size_type loc = def.find(sep);\r\n    while (loc != std::string::npos)\r\n    {\r\n        std::string par = def.substr(0, loc);\r\n        boost::trim(par);\r\n        if (! par.empty())\r\n        {\r\n            arguments.push_back(par);\r\n        }\r\n\r\n        def.erase(0, loc);\r\n        boost::trim_left_if(def, boost::is_any_of(sep));\r\n        loc = def.find(sep);\r\n    }\r\n\r\n    if (! def.empty())\r\n    {\r\n        arguments.push_back(def);\r\n    }\r\n\r\n    /*boost::split(arguments, definition, boost::is_any_of(\"+\"));\r\n    for (std::vector<std::string>::iterator it = arguments.begin(); it != arguments.end(); it++)\r\n    {\r\n        boost::trim(*it);\r\n    }*/\r\n    return pj_init<T>(bg_params, arguments, use_defaults);\r\n}\r\n\r\n} // namespace detail\r\n}}} // namespace boost::geometry::projections\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_INIT_HPP\r\n", "meta": {"hexsha": "04e63fcfcd3ad6df09181469047c852b092e10e7", "size": 14076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/srs/projections/impl/pj_init.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/impl/pj_init.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/impl/pj_init.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": 35.7258883249, "max_line_length": 118, "alphanum_fraction": 0.5824097755, "num_tokens": 3332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606815201671963, "lm_q2_score": 0.06656918248903143, "lm_q1q2_score": 0.02636593308969445}}
{"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_ORDERABLE_DETAIL_ORDERABLE_FWD_HPP\n#define BOOST_HANA_ORDERABLE_DETAIL_ORDERABLE_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 orderable_detail { namespace operators { struct enable { }; }}\n\n    //! @ingroup group-typeclasses\n    //! The `Orderable` type class is used for data types defining a\n    //! [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_ordering).\n    //!\n    //! @anchor strict_weak_ordering\n    //! ### Laws\n    //! `less` must define a strict weak ordering. Formally, let\n    //!\n    //! @code\n    //!     x ~ y if and only if !(x < y) && !(y < x)\n    //! @endcode\n    //!\n    //! be the incomparability relation. Then, for all `a`, `b`, `c` of an\n    //! orderable data type,\n    //!\n    //! @code\n    //!     !(a < a)                     // Irreflexivity\n    //!     if a < b then !(b < a)       // Asymmetry\n    //!     if a < b && b < c then a < c // Transitivity\n    //!     if a ~ b && b ~ c then a ~ c // Transitivity of incomparability\n    //! @endcode\n    struct Orderable {\n        BOOST_HANA_BINARY_TYPECLASS(Orderable);\n        struct less_mcd;\n        struct laws;\n        using operators = orderable_detail::operators::enable;\n    };\n\n    //! Returns a `Logical` representing whether `x` is less than `y`.\n    //! @relates Orderable\n    //!\n    //! ### Example\n    //! @snippet example/orderable/less.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto less = [](auto x, auto y) {\n        return Orderable::instance<\n            datatype_t<decltype(x)>, datatype_t<decltype(y)>\n        >::less_impl(x, y);\n    };\n\n    //! Returns a `Logical` representing whether `x` is less than or\n    //! equal to `y`.\n    //! @relates Orderable\n    //!\n    //! ### Example\n    //! @snippet example/orderable/less_equal.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto less_equal = [](auto x, auto y) {\n        return Orderable::instance<\n            datatype_t<decltype(x)>, datatype_t<decltype(y)>\n        >::less_equal_impl(x, y);\n    };\n\n    //! Returns a `Logical` representing whether `x` is greater than `y`.\n    //! @relates Orderable\n    //!\n    //! ### Example\n    //! @snippet example/orderable/greater.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto greater = [](auto x, auto y) {\n        return Orderable::instance<\n            datatype_t<decltype(x)>, datatype_t<decltype(y)>\n        >::greater_impl(x, y);\n    };\n\n    //! Returns a `Logical` representing whether `x` is greater than or\n    //! equal to `y`.\n    //! @relates Orderable\n    //!\n    //! ### Example\n    //! @snippet example/orderable/greater_equal.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto greater_equal = [](auto x, auto y) {\n        return Orderable::instance<\n            datatype_t<decltype(x)>, datatype_t<decltype(y)>\n        >::greater_equal_impl(x, y);\n    };\n\n    //! Returns the smallest of its arguments according to the `less` ordering.\n    //! @relates Orderable\n    //!\n    //! ### Example\n    //! @snippet example/orderable/min.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto min = [](auto x, auto y) {\n        return Orderable::instance<\n            datatype_t<decltype(x)>, datatype_t<decltype(y)>\n        >::min_impl(x, y);\n    };\n\n    //! Returns the greatest of its arguments according to the `less` ordering.\n    //! @relates Orderable\n    //!\n    //! ### Example\n    //! @snippet example/orderable/max.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto max = [](auto x, auto y) {\n        return Orderable::instance<\n            datatype_t<decltype(x)>, datatype_t<decltype(y)>\n        >::max_impl(x, y);\n    };\n\n    //! Returns a function performing `less` after applying a transformation\n    //! to both arguments.\n    //! @relates Orderable\n    //!\n    //! This is not a method of the `Orderable` type class, but just a\n    //! convenience function provided with it. Also note that\n    //! @code\n    //!     ordering(f) == less ^on^ f\n    //! @endcode\n    //!\n    //! ### Example\n    //! @snippet example/orderable/ordering.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto ordering = [](auto f) {\n        return [=](auto x, auto y) {\n            return less(f(x), f(y));\n        };\n    };\n\n    namespace orderable_detail { namespace operators {\n        //! Equivalent to `less`.\n        //! @relates boost::hana::Orderable\n        template <typename T, typename U>\n        constexpr auto operator<(T t, U u)\n        { return less(t, u); }\n\n        //! Equivalent to `less_equal`.\n        //! @relates boost::hana::Orderable\n        template <typename T, typename U>\n        constexpr auto operator<=(T t, U u)\n        { return less_equal(t, u); }\n\n        //! Equivalent to `greater`.\n        //! @relates boost::hana::Orderable\n        template <typename T, typename U>\n        constexpr auto operator>(T t, U u)\n        { return greater(t, u); }\n\n        //! Equivalent to `greater_equal`.\n        //! @relates boost::hana::Orderable\n        template <typename T, typename U>\n        constexpr auto operator>=(T t, U u)\n        { return greater_equal(t, u); }\n    }}\n}} // end namespace boost::hana\n\n#endif // !BOOST_HANA_ORDERABLE_DETAIL_ORDERABLE_FWD_HPP\n", "meta": {"hexsha": "7e21403d56e2206182d0497d2e3eba4e8d8c5955", "size": 5424, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/hana/orderable/detail/orderable_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/orderable/detail/orderable_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/orderable/detail/orderable_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.4814814815, "max_line_length": 82, "alphanum_fraction": 0.6012168142, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.07263671037579263, "lm_q1q2_score": 0.026364889056659957}}
{"text": "#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#include <amgcl/io/binary.hpp>\n#include <amgcl/io/mm.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/mpi/make_solver.hpp>\n#include <amgcl/mpi/cpr.hpp>\n#include <amgcl/mpi/amg.hpp>\n#include <amgcl/mpi/coarsening/runtime.hpp>\n#include <amgcl/mpi/relaxation/runtime.hpp>\n#include <amgcl/mpi/relaxation/as_preconditioner.hpp>\n#include <amgcl/mpi/direct_solver/runtime.hpp>\n#include <amgcl/mpi/partition/runtime.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nusing amgcl::prof;\nusing amgcl::precondition;\n\n//---------------------------------------------------------------------------\nptrdiff_t read_matrix_market(\n        amgcl::mpi::communicator comm,\n        const std::string &A_file, const std::string &rhs_file, int block_size,\n        std::vector<ptrdiff_t> &ptr,\n        std::vector<ptrdiff_t> &col,\n        std::vector<double>    &val,\n        std::vector<double>    &rhs)\n{\n    amgcl::io::mm_reader A_mm(A_file);\n    ptrdiff_t n = A_mm.rows();\n\n    ptrdiff_t chunk = (n + comm.size - 1) / comm.size;\n    if (chunk % block_size != 0) {\n        chunk += block_size - chunk % block_size;\n    }\n\n    ptrdiff_t row_beg = std::min(n, chunk * comm.rank);\n    ptrdiff_t row_end = std::min(n, row_beg + chunk);\n\n    chunk = row_end - row_beg;\n\n    A_mm(ptr, col, val, row_beg, row_end);\n\n    if (rhs_file.empty()) {\n        rhs.resize(chunk);\n        std::fill(rhs.begin(), rhs.end(), 1.0);\n    } else {\n        amgcl::io::mm_reader rhs_mm(rhs_file);\n        rhs_mm(rhs, row_beg, row_end);\n    }\n\n    return chunk;\n}\n\n//---------------------------------------------------------------------------\nptrdiff_t read_binary(\n        amgcl::mpi::communicator comm,\n        const std::string &A_file, const std::string &rhs_file, int block_size,\n        std::vector<ptrdiff_t> &ptr,\n        std::vector<ptrdiff_t> &col,\n        std::vector<double>    &val,\n        std::vector<double>    &rhs)\n{\n    ptrdiff_t n = amgcl::io::crs_size<ptrdiff_t>(A_file);\n\n    ptrdiff_t chunk = (n + comm.size - 1) / comm.size;\n    if (chunk % block_size != 0) {\n        chunk += block_size - chunk % block_size;\n    }\n\n    ptrdiff_t row_beg = std::min(n, chunk * comm.rank);\n    ptrdiff_t row_end = std::min(n, row_beg + chunk);\n\n    chunk = row_end - row_beg;\n\n    amgcl::io::read_crs(A_file, n, ptr, col, val, row_beg, row_end);\n\n    if (rhs_file.empty()) {\n        rhs.resize(chunk);\n        std::fill(rhs.begin(), rhs.end(), 1.0);\n    } else {\n        ptrdiff_t rows, cols;\n        amgcl::io::read_dense(rhs_file, rows, cols, rhs, row_beg, row_end);\n    }\n\n    return chunk;\n}\n\n//---------------------------------------------------------------------------\ntemplate <class Backend, class Matrix>\nstd::shared_ptr< amgcl::mpi::distributed_matrix<Backend> >\npartition(amgcl::mpi::communicator comm, const Matrix &Astrip,\n        std::vector<double> &rhs, const typename Backend::params &bprm,\n        amgcl::runtime::mpi::partition::type ptype, int block_size = 1)\n{\n    typedef amgcl::mpi::distributed_matrix<Backend> DMatrix;\n\n    using amgcl::prof;\n\n    auto A = std::make_shared<DMatrix>(comm, Astrip);\n\n    if (comm.size == 1 || ptype == amgcl::runtime::mpi::partition::merge)\n        return A;\n\n    prof.tic(\"partition\");\n    boost::property_tree::ptree prm;\n    prm.put(\"type\", ptype);\n    prm.put(\"shrink_ratio\", 1);\n    amgcl::runtime::mpi::partition::wrapper<Backend> part(prm);\n\n    auto I = part(*A, block_size);\n    auto J = transpose(*I);\n    A = product(*J, *product(*A, *I));\n\n    std::vector<double> new_rhs(J->loc_rows());\n\n    J->move_to_backend(bprm);\n\n    amgcl::backend::spmv(1, *J, rhs, 0, new_rhs);\n    rhs.swap(new_rhs);\n    prof.toc(\"partition\");\n\n    return A;\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 comm(MPI_COMM_WORLD);\n\n    if (comm.rank == 0)\n        std::cout << \"World size: \" << comm.size << std::endl;\n\n    using amgcl::prof;\n\n    // Read configuration from command line\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\"matrix,A\",\n         po::value<std::string>(),\n         \"System matrix in the MatrixMarket format. \"\n         \"When not specified, a Poisson problem in 3D unit cube is assembled. \"\n        )\n        (\n         \"rhs,f\",\n         po::value<std::string>()->default_value(\"\"),\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         \"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         \"block-size,b\",\n         po::value<int>()->default_value(1),\n         \"The block size of the system matrix. \"\n        )\n        (\n         \"partitioner,r\",\n         po::value<amgcl::runtime::mpi::partition::type>()->default_value(\n#if defined(AMGCL_HAVE_SCOTCH)\n             amgcl::runtime::mpi::partition::ptscotch\n#elif defined(AMGCL_HAVE_PASTIX)\n             amgcl::runtime::mpi::partition::parmetis\n#else\n             amgcl::runtime::mpi::partition::merge\n#endif\n             ),\n         \"Repartition the system matrix\"\n        )\n        (\"prm-file,P\",\n         po::value<std::string>(),\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\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        if (comm.rank == 0) std::cout << desc << std::endl;\n        return 0;\n    }\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"prm-file\")) {\n        read_json(vm[\"prm-file\"].as<std::string>(), prm);\n    }\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    ptrdiff_t n;\n    std::vector<ptrdiff_t> ptr;\n    std::vector<ptrdiff_t> col;\n    std::vector<double>    val;\n    std::vector<double>    rhs;\n\n    int block_size = vm[\"block-size\"].as<int>();\n    prm.put(\"precond.block_size\", block_size);\n\n    prof.tic(\"read\");\n    if (vm[\"binary\"].as<bool>()) {\n        n = read_binary(comm,\n                vm[\"matrix\"].as<std::string>(),\n                vm[\"rhs\"].as<std::string>(),\n                block_size, ptr, col, val, rhs);\n    } else {\n        n = read_matrix_market(comm,\n                vm[\"matrix\"].as<std::string>(),\n                vm[\"rhs\"].as<std::string>(),\n                block_size, ptr, col, val, rhs);\n    }\n    prof.toc(\"read\");\n\n    typedef amgcl::backend::builtin<double> Backend;\n\n    auto A = partition<Backend>(comm,\n            std::tie(n, ptr, col, val), rhs, Backend::params(),\n            vm[\"partitioner\"].as<amgcl::runtime::mpi::partition::type>(),\n            block_size);\n\n    prof.tic(\"setup\");\n    typedef\n        amgcl::mpi::make_solver<\n            amgcl::mpi::cpr<\n                amgcl::mpi::amg<\n                    Backend,\n                    amgcl::runtime::mpi::coarsening::wrapper<Backend>,\n                    amgcl::runtime::mpi::relaxation::wrapper<Backend>,\n                    amgcl::runtime::mpi::direct::solver<double>,\n                    amgcl::runtime::mpi::partition::wrapper<Backend>\n                    >,\n                amgcl::mpi::relaxation::as_preconditioner<\n                    amgcl::runtime::mpi::relaxation::wrapper<Backend>\n                    >\n                >,\n            amgcl::runtime::solver::wrapper\n            >\n        Solver;\n\n    Solver solve(comm, A, prm);\n    prof.toc(\"setup\");\n\n    if (comm.rank == 0)\n        std::cout << solve << std::endl;\n\n    std::vector<double> x(rhs.size(), 0.0);\n\n    prof.tic(\"solve\");\n    size_t iters;\n    double error;\n    std::tie(iters, error) = solve(rhs, x);\n    prof.toc(\"solve\");\n\n    if (comm.rank == 0) {\n        std::cout\n            << \"Iterations: \" << iters << std::endl\n            << \"Error:      \" << error << std::endl\n            << prof << std::endl;\n    }\n}\n", "meta": {"hexsha": "ebfae67a060aeba8c9726a42f51aa18d9e63cc21", "size": 8958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/cpr_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/cpr_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/cpr_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.2635135135, "max_line_length": 88, "alphanum_fraction": 0.5561509265, "num_tokens": 2350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015862011227, "lm_q2_score": 0.056652430484325014, "lm_q1q2_score": 0.026337804794311536}}
{"text": "// Modified from boost/math/tools/rational.hpp (as of Boost 1.61)\n//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef NAM_EVALUATE_HPP\n#define NAM_EVALUATE_HPP\n\n#include <boost/mpl/int.hpp>\nnamespace mpl = boost::mpl;\n#include \"polynomial_horner2_20.hpp\"\n\n//\n// Forward declaration to keep two phase lookup happy:\n//\ntemplate <class T, class U>\nconstexpr U evaluate_polynomial(const T* poly, U const& z, std::size_t count);\n\nnamespace detail {\n    // Fallback if none of the unrolled ones (up to size 20) suffice\n    template <class T, class V, class Tag>\n    constexpr V evaluate_polynomial_c_imp(const T* a, const V& val, const Tag*) {\n       return evaluate_polynomial(a, val, Tag::value);\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>\nconstexpr U evaluate_polynomial(const T* poly, U const& z, std::size_t count) {\n   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      sum *= z;\n      sum += static_cast<U>(poly[i]);\n   }\n   return sum;\n}\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>\nconstexpr V evaluate_polynomial(const T(&a)[N], const V& val) {\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\n#endif // NAM_EVALUATE_HPP\n\n\n\n\n", "meta": {"hexsha": "6858657ff382d83003ef3f37b456530f3d70f273", "size": 1746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "evaluate.hpp", "max_stars_repo_name": "kundor/static-poly", "max_stars_repo_head_hexsha": "e1fd8ec7a55d67c665a1ec8057c6ccb744c45f5c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T19:26:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T19:26:32.000Z", "max_issues_repo_path": "evaluate.hpp", "max_issues_repo_name": "kundor/static-poly", "max_issues_repo_head_hexsha": "e1fd8ec7a55d67c665a1ec8057c6ccb744c45f5c", "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": "evaluate.hpp", "max_forks_repo_name": "kundor/static-poly", "max_forks_repo_head_hexsha": "e1fd8ec7a55d67c665a1ec8057c6ccb744c45f5c", "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.593220339, "max_line_length": 108, "alphanum_fraction": 0.7016036655, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05261894851934593, "lm_q1q2_score": 0.026309474259672967}}
{"text": "/* \n *  Jan Totz <jantotz@itp.tu-berlin.de>\n */\n\n// C++11 & Boost libraries, OpenMP\n#include <boost/program_options.hpp>\t\t\t// command line parsing\n#include <boost/property_tree/ptree.hpp>\t\t// support structure for ini file writing\n#include <boost/property_tree/ini_parser.hpp>\t// read/write ini file\n#include <iostream>\t\t\t\t\t\t\t\t// cout, cerr\n#include <fstream>\t\t\t\t\t\t\t\t// ofstream, ifstream\n#include <chrono>\t\t\t\t\t\t\t\t// chrono::high_resolution_clock::now()\n#include <random>\t\t\t\t\t\t\t\t// default_random_engine, normal_distribution<double>, uniform_real_distribution\n#include <stdlib.h>\t\t\t\t\t\t\t\t// system(), NULL, EXIT_FAILURE\n#include <cstdlib>\t\t\t\t\t\t\t\t// getenv()\n#include <unistd.h>\t\t\t\t\t\t\t\t// readlink()\n#include <omp.h>\t\t\t\t\t\t\t\t// omp_get_max_threads(), omp_set_num_threads()\n\n#include \"SWC_CPU_solver.hpp\"\t\t\t\t\t// struct params\n#include \"safe.hpp\"\t\t\t\t\t\t\t\t// saving\n#include \"safe_coupling.hpp\"\t\t\t\t\t// save phi coupling\n#include \"models.hpp\"\t\t\t\t\t\t\t// reaction models\n#include \"coupling.hpp\"\t\t\t\t\t\t\t// coupling schemes\n\n// namespaces\nnamespace po = boost::program_options;\nnamespace pt = boost::property_tree;\nusing namespace std;\n\ninline double posi_fmod(double i, double n){ return fmod((fmod(i,n)+n),n); }\ninline int posi_imod(int i, int n){ return (i % n + n) % n; }\n\n// custom parser for arrays in inifile, works for arrays of any kind: string, int, float, double...\ntemplate<typename T>\nstd::vector<T> to_array(const std::string& s){\n\tstd::vector<T> result;\n\tstd::stringstream ss(s);\n\tstd::string item;\n\twhile(std::getline(ss, item, ',')) result.push_back(boost::lexical_cast<T>(item));\n\treturn result;\n}\n\nstd::string get_executable_path(){\n\t\n\tchar buff[1024];\n\tssize_t len = ::readlink(\"/proc/self/exe\", buff, sizeof(buff)-1);\n\tstring pthexe;\n\t\n\t// get pthfnexe\n\tif(len != -1){\t\t\t\t// success\n\t\tbuff[len] = '\\0';\n\t\tpthexe = std::string(buff);\n\t}else{\t\t\t\t\t\t\t// error\n\t\tprintf(\"Error! Could not find path to executable!\"); exit(EXIT_FAILURE);\n\t}\n\t\n\t// remove filename from pathexe\n\tconst size_t last_slash_idx = pthexe.rfind('/');\n\tif (std::string::npos != last_slash_idx){\n\t\tpthexe = pthexe.substr(0, last_slash_idx+1);\n\t}\n\t\n\treturn pthexe;\n}\n\nstd::string replaceEnvironmentVariables(std::string input){\n\t\n\tsize_t pos1 = input.find(\"$\", 0);\n\tif(pos1 != std::string::npos){\t\t\t\t\t\t\t\t\t\t// \"$\" was found in string\n\t\tsize_t pos2 = input.find(\"/\", pos1);\n\t\tstring envVarString = input.substr(pos1+1,pos1+pos2-1).c_str();\n\t\tstring envVarValue;\n\t\tif( getenv(envVarString.c_str()) != NULL){\n\t\t\tenvVarValue = getenv(envVarString.c_str());\n\t\t}\n\t\treturn input.replace(pos1,pos1+pos2,envVarValue);\n\t}else{\n\t\treturn input;\n\t}\n}\n\n\n\nstd::string RealArrayToString(Real *array, int n){\n\t\n\tstd::string result=\"\";\n\tstd::ostringstream strs;\n\t\n\tfor(int i=0; i<n-1; i++) strs << array[i] << \",\";\n\tstrs << array[n-1];\n\t\n\treturn strs.str();\n\t\n}\n\n\nstd::string RealVectorToString(vector<Real> vec){\n\t\n\tstd::string result=\"\";\n\tstd::ostringstream strs;\n\t\n\tfor(int i=0; i<(int)vec.size()-1; i++) strs << vec[i] << \",\";\n\tstrs << vec[vec.size()-1];\n\t\n\treturn strs.str();\n}\n\n\n// read command line parameters with boost\nvoid main_cmdln_params(int &ac, char *av[], string &pthexe, string &pthini, string &ini, params &p){\n\t\n\tint errorflag=0;\t\t\t// no error: 0, error: 1\n\tstring spatial_settings1_string;\n\t\n\ttry{\n\t\tpo::options_description desc(\"Allowed options\");\n\t\tdesc.add_options()\n\t\t\t(\"help\", \"produce help message\")\n\t\t\t(\"pthini\", po::value<string>(&pthini)->default_value(pthexe+\"../ini\"), \"path for ini\")\n\t\t\t(\"pthout\", po::value<string>(&p.pthout)->default_value(\"-1\"), \"path for output\")\n\t\t\t(\"ini\", po::value<string>(&ini)->default_value(\"chimera_spiral_zbke2k.ini\"), \"name of inifile\")\n\t\t\t(\"spatial_settings1\", po::value<string>(&spatial_settings1_string)->default_value(\"-1\"), \"excitable array, no whitespace!\")\n\t\t\t(\"coupling_coeffs\", po::value<string>(&p.coupling_coeffs_string)->default_value(\"-1\"), \"coupling/diffusion coefficents, no whitespace!\")\n\t\t\t(\"uSeed\", po::value<int>(&p.uSeed)->default_value(-1), \"uSeed\")\n\t\t\t(\"pSeed\", po::value<int>(&p.pSeed)->default_value(-1), \"seed for parameter heterogeneity\")\n\t\t\t(\"nx\", po::value<int>(&p.nx)->default_value(-1), \"nx\")\n\t\t\t(\"ny\", po::value<int>(&p.ny)->default_value(-1), \"ny\")\n\t\t\t(\"diffusionChoice\", po::value<int>(&p.diffusionChoice)->default_value(-1), \"diffusionChoice\")\n\t\t\t(\"hehoflag\", po::value<int>(&p.hehoflag)->default_value(-1), \"hehoflag\")\n\t\t\t(\"reactionModel\", po::value<int>(&p.reactionModel)->default_value(-1), \"reactionModel\")\n\t\t\t(\"ChimeraCutOffRange\", po::value<int>(&p.ChimeraCutOffRange)->default_value(-1), \"ChimeraCutOffRange\")\n\t\t\t(\"stepsEnd\", po::value<size_t>(&p.stepsEnd)->default_value(0), \"stepsEnd\")\n\t\t\t(\"stepsSaveState\", po::value<size_t>(&p.stepsSaveState)->default_value(0), \"stepsSaveState\")\n\t\t\t(\"stepsSaveStateOffset\", po::value<size_t>(&p.stepsSaveStateOffset)->default_value(0), \"stepsSaveStateOffset\")\n\t\t\t(\"delayTimeMax\", po::value<float>(&p.delayTimeMax)->default_value(-1.0f), \"delayTimeMax\")\n\t\t\t(\"ChimeraK\", po::value<Real>(&p.ChimeraK)->default_value(-1.0), \"ChimeraK\")\n\t\t\t(\"ChimeraKappa\", po::value<Real>(&p.ChimeraKappa)->default_value(-1.0), \"ChimeraKappa\")\n\t\t\t(\"dt\", po::value<Real>(&p.dt)->default_value(-1.0), \"dt\")\n\t\t\t(\"dx\", po::value<Real>(&p.dx)->default_value(-1.0), \"dx\")\n\t\t\t(\"dy\", po::value<Real>(&p.dy)->default_value(-1.0), \"dy\")\n\t\t\t;\n\t\t\n\t\tpo::variables_map vm;\n\t\tpo::store(po::parse_command_line(ac, av, desc), vm);\n\t\tpo::notify(vm);\n\t\t\n\t\tif(vm.count(\"help\")){ cout << desc << \"\\n\"; exit(EXIT_SUCCESS); }\n\t}\n\tcatch(exception& e){\n\t\tcerr << \"error: \" << e.what() << \"\\n\";\n\t\terrorflag=1;\n\t}\n\tcatch(...){\n\t\tcerr << \"Exception of unknown type!\\n\";\n\t\terrorflag=1;\n\t}\n\t\n\tif(errorflag){\n\t\tcout<<\"--- program shutdown due to error at cmdln_params ---\"<<endl; \n\t\texit(EXIT_FAILURE);\n\t}\n\t\n\t// convert string to vector\n\tp.spatial_settings1 = to_array<Real>(spatial_settings1_string);\n\t\n}\n\n// resize phase inside function\nvoid get_limitCycleData(vector<Real>& phases, int nc, string pthfn_lc){ \n\t\n\tifstream fs;\n\tfs.open(pthfn_lc);\n\tstring temp_line;\n\tint ni=0;\n\twhile(getline(fs,temp_line)){\n\t\tif(!temp_line.empty()) ni++;\n\t}\n\tfs.clear();\n\tfs.seekg(fs.beg);\n\t//~ cout << \"ni: \" << ni << endl;\t\t// DEBUG\n\tphases.resize(ni*nc);\n\tfor(int i=0; i<ni; i++){\n\tfor(int c=0; c<nc; c++){\n\t\tfs>>phases[c+i*nc];\n\t}}\n\tfs.close();\n}\n\n\n\n// preliminary for all components, needs extra functions\nvoid initialCondition(Real *cfield, params &p, modelparams &m){\n\t\n\tint nc = p.ncomponents;\n\t\n\tif(p.ic==\"uniform_noise\"){\n\t\tprintf(\"ic: %s\\n\",p.ic.c_str());\n\t\t\n\t\t// random numbers from uniform distribution\n\t\tdefault_random_engine generator(p.uSeed);\n\t\tuniform_real_distribution<Real> udistribution(p.uMin,p.uMax);\n\t\t\n\t\tfor(int c=0; c<p.ncomponents; c++){\n\t\tfor(int i=0; i<p.n; i++){\n\t\t\tcfield[i+c*p.n]=udistribution(generator);\n\t\t}}\n\t\t\n\t\n\t}else if(p.ic==\"homo\"){\t\t\t\t\t\t\t\t\t\t// homogeneous background concentration\n\t\tprintf(\"ic: %s\\n\",p.ic.c_str());\n\t\t\n\t\tfor(int c=0; c<p.ncomponents; c++){\n\t\tfor(int i=0; i<p.n; i++){\n\t\t\tcfield[i+c*p.n]=m.model_phases[2*nc+c];\n\t\t}}\n\t\n\t\t\n\t\t\n\t\t\n\t}else if(p.ic==\"phase_proto_spiral\"){\n\t\tswitch(p.spaceDim){\n\t\t\tcase 2:  printf(\"ic: phase proto spiral wave\\n\"); break;\n\t\t\tdefault: printf(\"Error: spaceDim=%d is insufficient for phase proto spiral ic, use 2 instead!\\n\",p.spaceDim); exit(EXIT_FAILURE); break;\n\t\t}\n\t\t\n\t\t// spatial_settings1 overloaded for options: spatial_settings1 = {phasex0,phasey0,nArms,phi0,chirality}\n\t\tauto result1 = std::minmax_element(p.spatial_settings1.begin(), p.spatial_settings1.end());\n\t\tfloat minmaxdiff=*result1.second - *result1.first;\n\t\tif(minmaxdiff<1e-5){ // default settings, otherwise: ini settings\n\t\t\tp.spatial_settings1={0.5,0.5,M_PI,1};\n\t\t}\n\t\t\n\t\t// pattern parameters\n\t\tfloat phasex0 = p.spatial_settings1[0]; \t\t\t// x-coords of phase singularity = spiral center\n\t\tfloat phasey0 = p.spatial_settings1[1];\t\t\t\t// y-coords of phase singularity = spiral center\n\t\tfloat phi0 = p.spatial_settings1[2];\t\t\t\t// initial phase offset\n\t\tint chi = p.spatial_settings1[3];\t\t\t\t\t// chirality\n\t\t\n\t\tvector<Real> phases;\t\t\t\t// initialize empty vector\n\t\tget_limitCycleData(phases,nc,p.pthfn_lc);\n\t\tint ni=phases.size()/nc;\n\t\t\n\t\tfor(int y = 0; y < p.ny; ++y){\n\t\tfor(int x = 0; x < p.nx; ++x){\n\t\t\tint index = posi_fmod( atan2(y-phasey0*p.ny,chi*(x-phasex0*p.nx)) - phi0, 2.0*M_PI )/(2.0*M_PI)*(ni-1);\n\t\t\tfor(int c=0; c<nc; c++) cfield[x+y*p.nx+c*p.n]=phases[c+index*nc];\n\t\t}}\n\t\t\n\t\t\n\t\t\n\t\t\n\t}else{\n\t\tcout<<\"Error: ic \\\"\"<<p.ic<<\"\\\" does not exist!\" <<endl; exit(EXIT_FAILURE);\n\t}\n\n}\n\n// save params as binary float\nvoid saveParamDistro(Real *k, params &p){\n\t\n\tchar spbuff[100];\n\tsprintf(spbuff,\"/paramDistro.bin\");\n\tofstream dataout;\n\tdataout.open(p.pthout+spbuff,ios::binary);\n\t\n\tint size=sizeof(Real);\n\t\n\t// save header (2 ints): nx,ny,nz\n\tdataout.write((char*) &p.nx, sizeof(int));\n\tdataout.write((char*) &p.ny, sizeof(int));\n\t\n\t// save data\n\tfor(int n=0; n<p.n; n++) dataout.write((char*) &k[n], size);\n\t\n\tdataout.close();\n}\n\n\nvoid main_parameterDistribution(Real *hetArray, params &p, modelparams &m){\n\n\t// random numbers from gaussian distribution\n\tdefault_random_engine generator(p.pSeed);\n\tnormal_distribution<double> p_normal_distribution(p.het1,p.pSigma);\n\tuniform_real_distribution<double> p_uniform_distribution(p.het1-p.pSigma,p.het1+p.pSigma);\n\t\n\tswitch(p.hehoflag){\n\t\tcase 0:\t\t\t// homogeneous distribution\n\t\t\tcout << \"main_parameterDistribution (\" << p.hehoflag << \"): homogeneous\" << endl;\n\t\t\tfor(int i=0; i<p.n; i++) hetArray[i]=p.het1;\n\t\t\tbreak;\n\t\t\n\t\tcase 1:\t\t\t// heterogeneous, normal distribution\n\t\t\tcout << \"main_parameterDistribution (\" << p.hehoflag << \"): bounded normal distribution\" << endl;\n\t\t\tfor(int i=0; i<p.n; i++){\n\t\t\t\tfloat prnd=0.;\n\t\t\t\twhile(prnd<p.het1-p.pSigma or prnd>p.het1+p.pSigma) prnd = p_normal_distribution(generator);\t\t\t// limits for parameter p\n\t\t\t\thetArray[i]=prnd;\n\t\t\t}\n\t\t\tbreak;\n\t\t\n\t\tcase 7:\t\t\t\t// heterogeneous, uniform distribution\n\t\t\tcout << \"main_parameterDistribution (\" << p.hehoflag << \"): uniform distribution\" << endl;\n\t\t\tfor(int i=0; i<p.n; i++) hetArray[i]=p_uniform_distribution(generator);\n\t\t\tbreak;\n\t\t\n\t\tdefault:\n\t\t\tcout << \"chosen value (\" << p.hehoflag << \") for hehoflag is not implemented!\" << endl; exit(1);\n\t\t\tbreak;\n\t}\n}\n\n\n// only linux!, OS-independent option: boost\nvoid main_housekeeper(string pthout, string pthexe){\n\t\n\t#ifdef _WIN32\n\t\n\t#elif __linux__\n\t// remove potential old files in directories\n\tstring cmd0 = \"rm -r \"+pthout+\"/* 2> /dev/null\";\n\tint systemRet = system(const_cast<char*>(cmd0.c_str()));\n\tif(systemRet == -1){cout<<\"rm system command failed\"<<endl;}\n\t\n\t// create directory for output\n\tcmd0 = \"mkdir -p \"+pthout+\" \"+pthout+\"/states\";\n\tsystemRet = system(const_cast<char*>(cmd0.c_str()));\n\tif(systemRet == -1){cout<<\"mkdir system command failed\"<<endl;}\n\t\n\t// copy current source code into output directory\n\tcmd0 = \"mkdir -p \"+pthout+\" \"+pthout+\"/source_code\";\n\tcout << cmd0 << endl;\n\tsystemRet = system(const_cast<char*>(cmd0.c_str()));\n\tif(systemRet == -1){cout<<\"mkdir system command failed\"<<endl;}\n\t// cp .{hpp,cpp} is not supported in sh\n\tcmd0 = \"cd \"+pthexe+\" && cp *.cpp *.hpp \"+pthout+\"/source_code/\";\n\tsystemRet = system(const_cast<char*>(cmd0.c_str()));\n\tif(systemRet == -1){cout<<\"cp system command failed\"<<endl;}\n\t#endif\n\t\n}\n\n\n\n// strip string of unwanted chars\nstring stripString(string &str){\n\n\t// escaped quotation mark\n\tchar badchars[] = \"\\\"\";\n\n\tfor (unsigned int i = 0; i < strlen(badchars); ++i){\n\t\tstr.erase (std::remove(str.begin(), str.end(), badchars[i]), str.end());\n\t}\n\n\treturn str;\n}\n\nvoid setReactionCouplingParams(params &ip, pt::ptree pt, modelparams &m, params &pExtra){\n\t\n\tswitch(ip.reactionModel){\n\t\tcase 24:\t\t\t\t\t\t\t\t\t\t\t\t// zbke2k\n\t\tcase 2401:\t\t\t\t\t\t\t\t\t\t\t\t// zbke2k qhet\n\t\t\tm.ncomponents=2;\n\t\t\tm.nparams=9;\n\t\t\tm.model_params = new Real[9] {1.0/0.11,1.7e-5,1.6e-3,0.1,1.7e-5,1.2,2.4e-4,0.7,5.25e-4};\t\t// ooeps1, eps2, eps3, alpha, beta, gamma, mu, q, phi0\n\t\t\tm.model_phases = new Real[6] {0.1,0.01,0.0001,0.3,0.0,0.0};\n\t\t\tm.coupling_coeffs = new Real[2] {1.0/0.11,2.0};\n\t\t\tbreak;\n\t\t\t\n\t\tcase 25:\t\t\t\t\t\t\t\t\t\t\t\t// fhn\n\t\t\tm.ncomponents=2;\n\t\t\tm.nparams=2;\n\t\t\tm.model_params = new Real[2] {1.0/0.05,1.1};\t\t\t\t\t\t\t// ooeps, a\n\t\t\tm.model_phases = new Real[6] {1.5,0.0,0.0,1.5,-1.1,-0.656333};\t\t\t// bg = stable fixed point\n\t\t\tm.coupling_coeffs = new Real[2] {1.0,0.0};\n\t\t\tbreak;\n\t\t\t\n\t\tdefault:\t\t\t\t\t\t\t\t\t\t\t\t// default case\n\t\t\tprintf(\"Error: reactionModel not implemented. (readInifile @ line: %d)\\n\",__LINE__); exit(EXIT_FAILURE);\n\t\t\tbreak;\n\t}\n\t\n\t\n\t// a1) read model data from inifile\n\tstd::vector<Real> modelParameters0 = to_array<Real>(pt.get<std::string>(\"model_parameters.modelParams\",\"0\"));\n\tstd::vector<Real> coupling_coeffs0 = to_array<Real>(pt.get<std::string>(\"model_parameters.coupling_coeffs\",\"0\"));\n\tstd::vector<Real> phases0 = to_array<Real>(pt.get<std::string>(\"model_parameters.phases\",\"0\"));\n\t\n\t// a2) read model.coupling_coeffs from commandline\n\tif(pExtra.coupling_coeffs_string!=\"-1\") coupling_coeffs0 = to_array<Real>(pExtra.coupling_coeffs_string);\n\t\n\t// b) apply it; if not set, then write default values into resulting ini file\n\tif(modelParameters0.size()!=1 or modelParameters0[0]!=0){\n\t\tm.model_params = (Real *) malloc(modelParameters0.size()*sizeof(Real));\n\t\tfor(size_t i=0; i<modelParameters0.size(); i++) m.model_params[i]=modelParameters0[i];\n\t}else{\n\t\tstd::string s=RealArrayToString(m.model_params,m.nparams);\n\t\tpt.put<std::string>(\"model_parameters.modelParams\",s);\n\t}\n\t\n\tif(coupling_coeffs0.size()!=1 or coupling_coeffs0[0]!=0){\n\t\tm.coupling_coeffs = (Real *) malloc(coupling_coeffs0.size()*sizeof(Real));\n\t\tfor(size_t i=0; i<coupling_coeffs0.size(); i++) m.coupling_coeffs[i]=coupling_coeffs0[i];\n\t}else{\n\t\tstd::string s=RealArrayToString(m.coupling_coeffs,m.ncomponents);\n\t\tpt.put<std::string>(\"model_parameters.coupling_coeffs\",s);\n\t}\n\t\n\tif(phases0.size()!=1 or phases0[0]!=0){\n\t\tm.model_phases = (Real *) malloc(phases0.size()*sizeof(Real));\n\t\tfor(size_t i=0; i<phases0.size(); i++) m.model_phases[i]=phases0[i];\n\t}else{\n\t\tstd::string s=RealArrayToString(m.model_phases,m.ncomponents*3);\n\t\tpt.put<std::string>(\"model_parameters.phases\",s);\n\t}\n}\n\n\n\n\n// read parameters from text file\nvoid main_readInifile(string pthini, string pthexe, string &ini, params &ip, pt::ptree pt, modelparams &m, params &pExtra){\n\t\n\t// initialize variables\n\tstring pthfnini=pthini+\"/\"+ini;\n\t\n\t// read ini\n\tpt::ini_parser::read_ini(pthfnini, pt);\n\tcout<<\"\\n############# reading ini file ###################\"<<endl;\n\tcout<<pthfnini<<endl;\n\tip.nx = max(pt.get<int>(\"numerics_space.nx\",100),1);\t\t// max: in case user input is 0 instead of 1\n\tip.ny = max(pt.get<int>(\"numerics_space.ny\",100),1);\n\tip.dx = pt.get<Real>(\"numerics_space.dx\",1.0);\n\tip.dy = pt.get<Real>(\"numerics_space.dy\",1.0);\n\tip.bc = pt.get<string>(\"numerics_space.boundary_condition\",\"periodic\");\t\t\t// periodic or neumann\n\tip.diffusionChoice = pt.get<int>(\"numerics_space.diffusionChoice\",0);\n\tip.dt = pt.get<Real>(\"numerics_time.dt\",0.01);\n\tip.stepsSaveState = pt.get<size_t>(\"numerics_time.stepsSaveState\",10000);\n\tip.stepsSaveStateOffset = pt.get<size_t>(\"numerics_time.stepsSaveStateOffset\",0);\n\tip.stepsEnd = pt.get<size_t>(\"numerics_time.stepsEnd\",100000);\n\tip.couplingStartTime = pt.get<float>(\"numerics_time.couplingStartTime\",0);\n\tip.delayTimeMax = pt.get<float>(\"numerics_time.delayTimeMax\",0);\n\tip.delayStartTime = pt.get<float>(\"numerics_time.delayStartTime\",1);\n\tip.nCpuThresh = pt.get<int>(\"device.cpu_nCoreThresh\",100);\n\tip.ic = pt.get<string>(\"initial_condition.ic\",\"uniform_noise\");\n\tip.pthfn_lc = pt.get<string>(\"initial_condition.pthfn_lc\",pthexe+\"/../lc_zbke2k_phi0_1.6e-4.dat\");\n\tip.uSeed = pt.get<unsigned int>(\"initial_condition.uSeed\",1);\n\tip.uMin = pt.get<Real>(\"initial_condition.uMin\",0.);\n\tip.uMax = pt.get<Real>(\"initial_condition.uMax\",1.);\n\tip.reactionModel = pt.get<int>(\"model_parameters.reactionModel\",10);\n\tip.hehoflag = pt.get<int>(\"model_parameters.hehoflag\",0);\n\tip.pSeed = pt.get<unsigned int>(\"model_parameters.pSeed\",1);\n\tip.pSigma = pt.get<float>(\"model_parameters.pSigma\",0.01);\n\tip.het1 = pt.get<Real>(\"model_parameters.het1\",0.01);\t\t\t\t\t\t\t\t\t// heterogeneity parameter\n\tip.ChimeraK = pt.get<Real>(\"chimera.ChimeraK\",0.0001);\n\tip.ChimeraKappa = pt.get<Real>(\"chimera.ChimeraKappa\",3.0);\n\tip.ChimeraCutOffRange = pt.get<int>(\"chimera.ChimeraCutoffRange\",3);\n\tip.pthout = pt.get<string>(\"dir_management.pthout\",pthexe+\"/../../Simulations/test\");\n\tip.saveSingleFlag = pt.get<int>(\"dir_management.saveSingleFlag\",0);\n\tip.spatial_settings1 = to_array<Real>(pt.get<std::string>(\"initial_condition.spatial_settings1\",\"0\")); \n\t\n\t// assign additional cmd line values to params\n\tif(pExtra.uSeed>=0){ ip.uSeed = pExtra.uSeed; pt.put<int>(\"initial_condition.uSeed\",ip.uSeed); }\n\tif(pExtra.pSeed>=0){ ip.pSeed = pExtra.pSeed; pt.put<int>(\"model_parameters.pSeed\",ip.pSeed); }\n\tif(pExtra.diffusionChoice>=0){ ip.diffusionChoice = pExtra.diffusionChoice; pt.put<int>(\"numerics_space.diffusionChoice\",ip.diffusionChoice); }\n\tif(pExtra.nx>=0){ ip.nx = pExtra.nx; pt.put<int>(\"numerics_space.nx\",ip.nx); }\n\tif(pExtra.ny>=0){ ip.ny = pExtra.ny; pt.put<int>(\"numerics_space.ny\",ip.ny); }\n\tif(pExtra.dx>=0){ ip.dx = pExtra.dx; pt.put<Real>(\"numerics_space.dx\",ip.dx); }\n\tif(pExtra.dy>=0){ ip.dy = pExtra.dy; pt.put<Real>(\"numerics_space.dy\",ip.dy); }\n\tif(pExtra.dt>=0){ ip.dt = pExtra.dt; pt.put<Real>(\"numerics_time.dt\",ip.dt); }\n\tif(pExtra.ChimeraCutOffRange>=0){ ip.ChimeraCutOffRange = pExtra.ChimeraCutOffRange; pt.put<int>(\"chimera.ChimeraCutOffRange\",ip.ChimeraCutOffRange); }\n\tif(pExtra.ChimeraKappa>=0){ ip.ChimeraKappa = pExtra.ChimeraKappa; pt.put<Real>(\"chimera.ChimeraKappa\",ip.ChimeraKappa); }\n\tif(pExtra.ChimeraK>=0){ ip.ChimeraK = pExtra.ChimeraK; pt.put<Real>(\"chimera.ChimeraK\",ip.ChimeraK); }\n\tif(pExtra.hehoflag>=0){ ip.hehoflag = pExtra.hehoflag; pt.put<int>(\"model_parameters.hehoflag\",ip.hehoflag); }\n\tif(pExtra.reactionModel>=0){ ip.reactionModel = pExtra.reactionModel; pt.put<int>(\"model_parameters.reactionModel\",ip.reactionModel); }\n\tif(pExtra.stepsEnd>0){ ip.stepsEnd = pExtra.stepsEnd; pt.put<size_t>(\"numerics_time.stepsEnd\",ip.stepsEnd); }\n\tif(pExtra.stepsSaveState>0){ ip.stepsSaveState = pExtra.stepsSaveState; pt.put<size_t>(\"numerics_time.stepsSaveState\",ip.stepsSaveState); }\n\tif(pExtra.stepsSaveStateOffset>0){ ip.stepsSaveStateOffset = pExtra.stepsSaveStateOffset; pt.put<size_t>(\"numerics_time.stepsSaveStateOffset\",ip.stepsSaveStateOffset); }\n\tif(pExtra.delayTimeMax>=0){ ip.delayTimeMax = pExtra.delayTimeMax; pt.put<float>(\"numerics_time.delayTime\",ip.delayTimeMax); }\n\tif(pExtra.spatial_settings1[0]>=0){ ip.spatial_settings1 = pExtra.spatial_settings1; pt.put<std::string>(\"initial_condition.spatial_settings1\",RealVectorToString(ip.spatial_settings1)); }\n\tif(pExtra.pthout!=\"-1\"){ ip.pthout = pExtra.pthout; pt.put<std::string>(\"dir_management.pthout\",ip.pthout); }\n\t\n\t// interpret environment variables in pthout string\n\tip.pthout = replaceEnvironmentVariables(ip.pthout);\n\tip.pthfn_lc = replaceEnvironmentVariables(ip.pthfn_lc);\n\t\n\t// recalculate total simulation time, so that no superfluous, unsaved simulation steps are performed\n\tip.stepsEnd = (ip.stepsEnd/ip.stepsSaveState)*ip.stepsSaveState;\n\tpt.put<size_t>(\"numerics_time.stepsEnd\",ip.stepsEnd);\n\t\n\t// check correctness of delay settings, if inappropriate switch to easiest case\n\tif(ip.diffusionChoice==6){ ip.delayFlag=1; }\n\telse{ ip.delayFlag=0; }\n\t\n\tif(ip.delayFlag==1 and ip.delayTimeMax==0.0){\n\t\tprintf(\"\\nWarning: delayTimeMax of 0.0 is not supported for diffusionChoice=6! Switching to diffusionChoice=5 (readInifile @ line: %d)\\n\",__LINE__);\n\t\tip.diffusionChoice=5;\n\t\tip.delayFlag=0;\n\t}\n\tpt.put<int>(\"numerics_space.diffusionChoice\",ip.diffusionChoice);\n\t\n\t// input checks\n\tif(ip.delayFlag){\n\t\tif(ip.delayStartTime<ip.delayTimeMax and ip.couplingStartTime<ip.delayTimeMax){\n\t\t\tcout << \"\\nWarning: delayTimeMax must be <= delayStartTime or couplingStartTime! Setting delayStartTime = delayTimeMin! Correcting...\\n\" << endl;\n\t\t\tip.delayStartTime = ip.delayTimeMax;\n\t\t}\n\t}\n\t\n\t\n\t// find the space dimension automatically\n\tip.spaceDim=2;\n\tif(ip.nx==1) ip.spaceDim--;\n\tif(ip.ny==1) ip.spaceDim--;\n\t\n\t\n\t#ifdef DOUBLE\n\t\tcout << \"dataytpe mode: DOUBLE\" << endl;\n\t#else\n\t\tcout << \"dataytpe mode: FLOAT\" << endl;\n\t#endif\n\t\n\tsetReactionCouplingParams(ip,pt,m,pExtra);\n\tip.ncomponents=m.ncomponents;\n\t\n\tip.delayStepsMax=ip.delayTimeMax/ip.dt*!!ip.delayFlag;\n\tip.delayStartSteps=ip.delayStartTime/ip.dt*!!ip.delayFlag;\n\tip.stepsCouplingStart=ip.couplingStartTime/ip.dt;\n\tip.pthout=stripString(ip.pthout)+\"_cpu\";\n\tpt.put<std::string>(\"dir_management.pthout\",ip.pthout);\n\tmain_housekeeper(ip.pthout,pthexe);\n\tip.bc=stripString(ip.bc);\n\tip.ic=stripString(ip.ic);\n\tip.pthfn_lc=stripString(ip.pthfn_lc);\n\tip.n=ip.nx*ip.ny;\t\t\t\t\t// total number of cells\n\tpt.put<int>(\"numerics_space.n\",ip.n);\n\t\n\tstring iniOutString=ip.pthout+\"/used0.ini\";\n\tcout<<\"output inifile: \"<<iniOutString<<endl;\n\tpt::ini_parser::write_ini(iniOutString,pt);\n\t\n\t// terminal output\n\tcout<<\"spaceDim: \"<<ip.spaceDim<<endl;\n\tcout<<\"boundary condition: \"<<ip.bc<<endl;\n\tprintf(\"nx: %d, ny: %d = lx: %.2f, ly: %.2f\\n\",ip.nx,ip.ny,ip.nx*ip.dx,ip.ny*ip.dy);\n\tprintf(\"dx: %.2f, dy: %.2f\\n\",ip.dx,ip.dy);\n\tcout<<\"dt: \"<<ip.dt<<endl;\n\tcout<<\"reaction model: \"<<ip.reactionModel<<endl;\n\tcout<<\"stepsSaveState: \"<<ip.stepsSaveState<<\" steps = \"<<ip.stepsSaveState*ip.dt<<\" time units\"<<endl;\n\tcout<<\"stepsEnd: \"<<ip.stepsEnd<<\" steps = \"<<ip.stepsEnd*ip.dt<<\" time units\"<<endl;\n\tcout<<\"pthout: \"<<ip.pthout<<endl;\n\tcout<<\"##############################################\\n\"<<endl;\n\t\n}\n\n// Courant-Friedrichs-Levy (CFL) criterion\nvoid calcCFL(params &p, Real *k, modelparams &m){\n\t\n\tif(p.diffusionChoice==0 || p.diffusionChoice==1 || p.diffusionChoice==2){\n\t\tReal kmax = *max_element(k,k+p.n);\n\t\tReal diffmax = *max_element(m.coupling_coeffs,m.coupling_coeffs+m.ncomponents);\n\t\tif(p.hehoflag) diffmax=kmax;\n\t\tReal cfl=2.0*p.spaceDim*p.dt*diffmax/(p.dx*p.dx);\n\t\t\n\t\tcout<<\"CFL: \"<< cfl << endl;\n\t\tif(cfl>0.9) { cout<<\"CFL violated! \"<<cfl<<\">0.9 (conservative).\"<<endl; exit(1); }\n\t}\n}\n\n\n\nReal kernelfunction(int i, int j, int i0, int j0, params &p){\n\t\n\tReal value=0.0;\n\t\n\t// exponential decay\n\tswitch(p.spaceDim){\n\t\tcase 2:\n\t\t\tvalue=p.dx*p.dy*exp(-sqrt((i-i0)*(i-i0)*p.dx*p.dx+(j-j0)*(j-j0)*p.dy*p.dy)/p.ChimeraKappa);\n\t\t\tbreak;\n\t}\n\t\n\treturn value;\n}\n\n\n\nvoid create_kernel_and_rescale(params &p, Real* &kernel, modelparams &m){\n\t\n\t\n\tswitch(p.diffusionChoice){\n\t\t// nonlocal chimera coupling: Exp(-d/kappa), d = euclidean distance\n\t\tcase 5:\n\t\tcase 6:\n\t\t\t{\n\t\t\t\tint i=0, j=0, i0=0, j0=0;\n\t\t\t\tp.kdia=2*p.ChimeraCutOffRange+1;\n\t\t\t\tp.kradius = p.ChimeraCutOffRange;\n\t\t\t\tp.ksum=0.0;\n\t\t\t\tswitch(p.spaceDim){\n\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tp.klen=pow(p.kdia,2);\n\t\t\t\t\t\ti0=p.ChimeraCutOffRange; j0=i0;\n\t\t\t\t\t\tkernel = new Real[p.klen];\n\t\t\t\t\t\tfor(i=0; i<p.kdia; i++){\n\t\t\t\t\t\tfor(j=0; j<p.kdia; j++){\n\t\t\t\t\t\t\tkernel[i+j*p.kdia] = kernelfunction(i,j,i0,j0,p);\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tfor(i=0; i<p.klen; i++) kernel[i] *= p.ChimeraK*p.dt;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\t\t\t\t// save kernel in binary data format for later\n\t\t\t\tstd::ofstream dataout;\n\t\t\t\tdataout.open(p.pthout+\"/coupling_kernel.bin\",std::ios::binary);\n\t\t\t\tfor(int i=0; i<p.klen; i++) dataout.write((char*) &(kernel[i]), sizeof(Real));\n\t\t\t\tdataout.close();\n\t\t\t\tfor(int i=0; i<p.klen; i++) p.ksum += kernel[i];\n\t\t\t\t\n\t\t\t}\n\t\t\tbreak;\n\t\t\n\t\t// rescaling is accounted for in coupling\n\t\tcase 7:\t\t\t// no coupling\n\t\t\tbreak;\n\t\tdefault: printf(\"Unknown value for diffusionChoice (create_kernel_and_rescale()).\\n\"); exit(EXIT_FAILURE); break;\n\t}\n\t\n}\n\n\n\n\n// c,cnew pointers are passed by reference, because they are changed in the function!\nvoid dynamics(Real *&c, Real *&cnew, Real *c0, Real *kernel, Real *k, params &p, modelparams &m, size_t step, Real* feedback){\n\t\n\tswitch(p.delayFlag){\n\t\tcase 0:\t\t\t\t\t\t\t\t\t\t\t// no delay\n\t\t\treaction(c,cnew,k,p);\t\t\t\t\t\t\t\t\t\t\t\t// reaction part, see models.cpp\n\t\t\tcoupling(c,cnew,c0,k,p,m,kernel,step,feedback);\t\t\t\t\t\t// spatial coupling, see coupling.cpp\n\t\t\tswap(c,cnew);\t\t\t\t\t\t\t\t\t\t\t\t\t\t// update position values = pointer swap\n\t\t\tbreak;\n\t\t\n\t\tcase 1:\t\t\t\t\t\t\t\t\t\t\t// with delay\n\t\t\treaction(c,cnew,k,p);\t\t\t\t\t\t\t\t\t\t\t\t// reaction part, see models.cpp\n\t\t\tcoupling(c,cnew,c0,k,p,m,kernel,step,feedback);\t\t\t\t\t\t// spatial coupling, see coupling.cpp\n\t\t\t\n\t\t\t// pointer position iteration as update\n\t\t\tc = c0 + ((step+1) % (p.delayStepsMax+1))*p.n*p.ncomponents;\n\t\t\tcnew = c0 + ((step+2) % (p.delayStepsMax+1))*p.n*p.ncomponents;\n\t\t\tbreak;\n\t\t\n\t\tdefault: printf(\"Unknown value for delayFlag (rd_dynamics).\\n\"); exit(EXIT_FAILURE); break;\n\t}\n}\n\n\n\nvoid solverCPU_2d(Real *c, Real *cnew, Real *k, params &p, modelparams &m, Real* kernel, Real* c0, Real* feedback){\n\t\n\tif(p.delayFlag){\n\t\tfor(int i=0; i<p.n*p.ncomponents; i++) c0[i] = c[i];\t\t\t\t\t// set initial conditions\n\t\t// init array pointers for first step\n\t\tc = c0;\n\t\tcnew = c0+p.n*p.ncomponents;\n\t}\n\t\n\t\n\t// init containers for analysis; can not be done conditionally ;(\n\tint nSaveStates=100;\n\tSafe safe(p,nSaveStates);\n\tint useSafeCouplingQ = 0;\n\tif(p.reactionModel==24 or p.reactionModel==2401 or p.reactionModel==25) useSafeCouplingQ = 1;\n\tSafe_coupling safe_coupling(p,nSaveStates,useSafeCouplingQ);\n\t\n\t// save initial condition\n\tsafe.save(c,0);\n\t\n\t\n\t// time loop\n\tfor(size_t step=0; step<p.stepsEnd; step++){\n\t\t\n\t\t// dynamics\n\t\tdynamics(c,cnew,c0,kernel,k,p,m,step,feedback);\n\t\t\n\t\tif(c[0]!=c[0]){ printf(\"step: %zu, u[0]=%f. Abort!\\n\",step,c[0]);  exit(EXIT_FAILURE); }\n\t\t\n\t\t// step counter output\n\t\tif(step>0){\n\t\t\t\n\t\t\t// output: save state\n\t\t\tif(!(step%p.stepsSaveState)){ \n\t\t\t\tsafe.save(c,step);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// save concentrations\n\t\t\t\tif(p.reactionModel==24 or p.reactionModel==2401 or p.reactionModel==25) safe_coupling.save(feedback,step);\t\t// save feedback\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n// adapt number of processors based on system size\nvoid set_OpenMP_Cores(params &p){\n\t\n\tint maxCPUs = omp_get_max_threads();\n\tint nOMPs = min(p.n/p.nCpuThresh+1,maxCPUs);\n\tomp_set_num_threads(nOMPs);\n\tprintf(\"# of used processors: %d/%d\\n\",nOMPs,maxCPUs);\n\t\n\t\n}\n\n\nint main(int ac, char* av[]){\n\n// message at program start\ncout << \"############ Solver is starting ############ \" << endl;\n\n// 0. parameter declaration\nstruct params inifile_params, inifile_params_cmdline;\nstruct modelparams model_params;\nauto t1=chrono::high_resolution_clock::now(), t2=chrono::high_resolution_clock::now();\nstring pthini, ini;\nstring pthexe = get_executable_path();\n\n// 1. read pth of inifile from commandline (default path)\nmain_cmdln_params(ac,av,pthexe,pthini,ini,inifile_params_cmdline);\n\n// 2a. read data from inifile\npt::ptree iniPropTree;\nmain_readInifile(pthini,pthexe,ini,inifile_params,iniPropTree,model_params,inifile_params_cmdline);\n\n// 3. prepare system\nset_OpenMP_Cores(inifile_params);\nint array_size=inifile_params.n*inifile_params.ncomponents;\nint history_array_size=1;\n\nif(inifile_params.delayFlag){ \n\thistory_array_size = array_size*(inifile_params.delayStepsMax+1);\n\tprintf(\"c0 size: %.3f MB = states: %zu\\n\",history_array_size*sizeof(Real)/(1024.*1024.), inifile_params.delayStepsMax+1);\n}\t\t\t\t\t\t\t\t\t\t\t// set number of used cpu cores\nReal *c0 = new Real[history_array_size]();\t\t// holds all concentration values for time delay (history array)\nReal *cfield = new Real[array_size];\t\t\t// dynamic variables = concentrations\nReal *cnew = new Real[array_size]();\t\t\t// all dynamic variables {u,v,w,} (more are not implemented), init to zero\nReal *feedback = new Real[inifile_params.n]();\t// save scalar feedback in case of ZBKE model\nReal *kfield = new Real[inifile_params.n];\t\t\t\t\t\t\t\t\t// parameter k for every cell\t\t\t\t\t\t\t\t\t// parameter k for every cell\nReal *kernel = NULL;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// kernel for convolution operations\ninitialCondition(cfield,inifile_params,model_params);\t\t\t\t\t\t// set initial condition\nmain_parameterDistribution(kfield,inifile_params,model_params);\t\t\t\t// set spatially heterogeneous parameter distribution\nsaveParamDistro(kfield,inifile_params);\ncreate_kernel_and_rescale(inifile_params,kernel,model_params);\t\t\t\t// create kernel and rescale coupling coefficents\n\n// 3b. CFL check\ncalcCFL(inifile_params,kfield,model_params);\n\n\n// 4. simulation\nt1 = std::chrono::high_resolution_clock::now();\t\t\t\t\t\t\t\t\t\t\t// timer start\nsolverCPU_2d(cfield,cnew,kfield,inifile_params,model_params,kernel,c0,feedback);\t\t// simulation\nt2 = std::chrono::high_resolution_clock::now();\t\t\t\t\t\t\t\t\t\t\t// timer end\nint runtime = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n\n// write report\nofstream dataout;\nchar spbuff[100];\nsprintf(spbuff,\"execution time: %d ms = %d h, %d min, %d s.\",runtime,runtime/1000/3600,runtime/1000/60%60,int(floor(runtime/1000.+0.5))%60);\ndataout.open(inifile_params.pthout+\"/report.txt\", ios::out);\ndataout<<spbuff<<endl;\ndataout.close();\ncout<<\"\\n\"<<spbuff<<endl;\n\n// deallocate memory\ndelete[] cfield;\ndelete[] kfield;\ndelete[] kernel;\ndelete[] model_params.coupling_coeffs;\ndelete[] model_params.model_params;\ndelete[] model_params.model_phases;\ndelete[] cnew;\ndelete[] c0;\ndelete[] feedback;\n\n\nreturn 0;\n}\n\n", "meta": {"hexsha": "272b23f94d309917970a1af659133410b06242a2", "size": 28953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SWC_CPU_solver/SWC_CPU_solver.cpp", "max_stars_repo_name": "bzjan/Spiral_Wave_Chimera_Solver", "max_stars_repo_head_hexsha": "2c1a254f9882d628c99a0f83298458e61396f80a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-30T18:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-18T17:44:19.000Z", "max_issues_repo_path": "SWC_CPU_solver/SWC_CPU_solver.cpp", "max_issues_repo_name": "bzjan/Spiral_Wave_Chimera_Solver", "max_issues_repo_head_hexsha": "2c1a254f9882d628c99a0f83298458e61396f80a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SWC_CPU_solver/SWC_CPU_solver.cpp", "max_forks_repo_name": "bzjan/Spiral_Wave_Chimera_Solver", "max_forks_repo_head_hexsha": "2c1a254f9882d628c99a0f83298458e61396f80a", "max_forks_repo_licenses": ["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.8358778626, "max_line_length": 188, "alphanum_fraction": 0.6815183228, "num_tokens": 8724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.06008665227791172, "lm_q1q2_score": 0.026307347468858315}}
{"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 DSFVector.cpp\n * @date Jun 25, 2010\n * @author Kai Ni\n * @brief a faster implementation for DSF, which uses vector rather than btree.\n */\n\n#include <gtsam/base/DSFVector.h>\n#include <boost/make_shared.hpp>\n#include <algorithm>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nDSFBase::DSFBase(const size_t numNodes) {\n  v_ = std::make_shared < V > (numNodes);\n  int index = 0;\n  for (V::iterator it = v_->begin(); it != v_->end(); it++, index++)\n    *it = index;\n}\n\n/* ************************************************************************* */\nDSFBase::DSFBase(const std::shared_ptr<V>& v_in) {\n  v_ = v_in;\n  int index = 0;\n  for (V::iterator it = v_->begin(); it != v_->end(); it++, index++)\n    *it = index;\n}\n\n/* ************************************************************************* */\nsize_t DSFBase::find(size_t key) const {\n  // follow parent pointers until we reach set representative\n  size_t parent = (*v_)[key];\n  if (parent != key)\n    parent = find(parent); // recursive call\n  (*v_)[key] = parent; // path compression\n  return parent;\n}\n\n/* ************************************************************************* */\nvoid DSFBase::merge(const size_t& i1, const size_t& i2) {\n  (*v_)[find(i2)] = find(i1);\n}\n\n/* ************************************************************************* */\nDSFVector::DSFVector(const size_t numNodes) :\n    DSFBase(numNodes) {\n  keys_.reserve(numNodes);\n  for (size_t index = 0; index < numNodes; index++)\n    keys_.push_back(index);\n}\n\n/* ************************************************************************* */\nDSFVector::DSFVector(const std::vector<size_t>& keys) :\n    DSFBase(1 + *std::max_element(keys.begin(), keys.end())), keys_(keys) {\n}\n\n/* ************************************************************************* */\nDSFVector::DSFVector(const std::shared_ptr<V>& v_in,\n    const std::vector<size_t>& keys) :\n    DSFBase(v_in), keys_(keys) {\n  assert(*(std::max_element(keys.begin(), keys.end()))<v_in->size());\n}\n\n/* ************************************************************************* */\nbool DSFVector::isSingleton(const size_t& label) const {\n  bool result = false;\n  for(size_t key: keys_) {\n    if (find(key) == label) {\n      if (!result) // find the first occurrence\n        result = true;\n      else\n        return false;\n    }\n  }\n  return result;\n}\n\n/* ************************************************************************* */\nstd::set<size_t> DSFVector::set(const size_t& label) const {\n  std::set < size_t > set;\n  for(size_t key: keys_)\n    if (find(key) == label)\n      set.insert(key);\n  return set;\n}\n\n/* ************************************************************************* */\nstd::map<size_t, std::set<size_t> > DSFVector::sets() const {\n  std::map<size_t, std::set<size_t> > sets;\n  for(size_t key: keys_)\n    sets[find(key)].insert(key);\n  return sets;\n}\n\n/* ************************************************************************* */\nstd::map<size_t, std::vector<size_t> > DSFVector::arrays() const {\n  std::map<size_t, std::vector<size_t> > arrays;\n  for(size_t key: keys_)\n    arrays[find(key)].push_back(key);\n  return arrays;\n}\n\n} // namespace  gtsam\n\n", "meta": {"hexsha": "ebc0ed603a4d66aa36aa6d81d62c7cb9e4a3871a", "size": 3639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/base/DSFVector.cpp", "max_stars_repo_name": "ProfFan/gtsam", "max_stars_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "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": "gtsam/base/DSFVector.cpp", "max_issues_repo_name": "ProfFan/gtsam", "max_issues_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam/base/DSFVector.cpp", "max_forks_repo_name": "ProfFan/gtsam", "max_forks_repo_head_hexsha": "67ce22c039cc0d04b0085203651dd859bbc44934", "max_forks_repo_licenses": ["BSD-3-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.5798319328, "max_line_length": 80, "alphanum_fraction": 0.463588898, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186968948485238, "lm_q2_score": 0.06278921385835867, "lm_q1q2_score": 0.026289648872474675}}
{"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#include \"Point.h\"\n#include \"Cavity.h\"\n#include \"QuadTree.h\"\n#include \"Verifier.h\"\n\n#include \"galois/Galois.h\"\n#include \"galois/Bag.h\"\n#include \"galois/Timer.h\"\n\n#include \"Lonestar/BoilerPlate.h\"\n#include \"llvm/Support/CommandLine.h\"\n\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\n#include <algorithm>\n#include <deque>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <string.h>\n#include <unistd.h>\n\nnamespace cll = llvm::cl;\n\nstatic const char* name = \"Delaunay Triangulation\";\nstatic const char* desc =\n    \"Produces a Delaunay triangulation for a set of points\";\nstatic const char* url = \"delaunay_triangulation\";\n\nstatic cll::opt<std::string>\n    doWriteMesh(\"writemesh\",\n                cll::desc(\"Write the mesh out to files with basename\"),\n                cll::value_desc(\"basename\"));\nstatic cll::opt<std::string>\n    doWritePoints(\"writepoints\",\n                  cll::desc(\"Write the (reordered) points to filename\"),\n                  cll::value_desc(\"filename\"));\nstatic cll::opt<bool>\n    noReorderPoints(\"noreorder\",\n                    cll::desc(\"Don't reorder points to improve locality\"),\n                    cll::init(false));\nstatic cll::opt<std::string>\n    inputFile(cll::Positional, cll::desc(\"<input file>\"), cll::Required);\n\nenum DetAlgo { nondet, detBase, detPrefix, detDisjoint };\n\nstatic cll::opt<DetAlgo>\n    detAlgo(cll::desc(\"Deterministic algorithm:\"),\n            cll::values(clEnumVal(nondet, \"Non-deterministic\"),\n                        clEnumVal(detBase, \"Base execution\"),\n                        clEnumVal(detPrefix, \"Prefix execution\"),\n                        clEnumVal(detDisjoint, \"Disjoint execution\")),\n            cll::init(nondet));\n\n//! Flag that forces user to be aware that they should be passing in a\n//! mesh graph.\nstatic cll::opt<bool>\n    meshGraph(\"meshGraph\", cll::desc(\"Specify that the input graph is a mesh\"),\n              cll::init(false));\n\nstruct GetPointer : public std::unary_function<Point&, Point*> {\n  Point* operator()(Point& p) const { return &p; }\n};\n\ntypedef std::vector<Point> PointList;\n\nclass ReadPoints {\n  void addBoundaryPoints() {\n    double minX, maxX, minY, maxY;\n\n    minX = minY = std::numeric_limits<double>::max();\n    maxX = maxY = std::numeric_limits<double>::min();\n\n    for (auto& p : points) {\n      double x = p.t().x();\n      double y = p.t().y();\n      if (x < minX)\n        minX = x;\n      else if (x > maxX)\n        maxX = x;\n      if (y < minY)\n        minY = y;\n      else if (y > maxY)\n        maxY = y;\n    }\n\n    size_t size      = points.size();\n    double width     = maxX - minX;\n    double height    = maxY - minY;\n    double maxLength = std::max(width, height);\n    double centerX   = minX + width / 2.0;\n    double centerY   = minY + height / 2.0;\n    double radius =\n        maxLength * 3.0; // radius of circle that should cover all points\n\n    for (int i = 0; i < 3; ++i) {\n      double dX = radius * cos(2 * M_PI * (i / 3.0));\n      double dY = radius * sin(2 * M_PI * (i / 3.0));\n      points.push_back(Point(centerX + dX, centerY + dY, size + i));\n    }\n  }\n\n  void nextLine(std::ifstream& scanner) {\n    scanner.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n  }\n\n  void fromTriangle(std::ifstream& scanner) {\n    double x, y;\n    long numPoints;\n\n    scanner >> numPoints;\n\n    int dim;\n    scanner >> dim;\n    assert(dim == 2);\n    int k;\n    scanner >> k; // number of attributes\n    assert(k == 0);\n    scanner >> k; // has boundary markers?\n\n    for (long id = 0; id < numPoints; ++id) {\n      scanner >> k; // point id\n      scanner >> x >> y;\n      nextLine(scanner);\n      points.push_back(Point(x, y, id));\n    }\n  }\n\n  void fromPointList(std::ifstream& scanner) {\n    double x, y;\n\n    // comment line\n    nextLine(scanner);\n    size_t id = 0;\n    while (!scanner.eof()) {\n      scanner >> x >> y;\n      if (x == 0 && y == 0)\n        break;\n      points.push_back(Point(x, y, id++));\n      x = y = 0;\n      nextLine(scanner);\n    }\n  }\n\n  PointList& points;\n\npublic:\n  ReadPoints(PointList& p) : points(p) {}\n\n  void from(const std::string& name) {\n    std::ifstream scanner(name.c_str());\n    if (!scanner.good()) {\n      GALOIS_DIE(\"could not open file: \", name);\n    }\n    if (name.find(\".node\") == name.size() - 5) {\n      fromTriangle(scanner);\n    } else {\n      fromPointList(scanner);\n    }\n    scanner.close();\n\n    if (points.size())\n      addBoundaryPoints();\n    else {\n      GALOIS_DIE(\"no points found in file: \", name);\n    }\n  }\n};\n\nstatic void writePoints(const std::string& filename, const PointList& points) {\n  std::ofstream out(filename.c_str());\n  // <num vertices> <dimension> <num attributes> <has boundary markers>\n  out << points.size() << \" 2 0 0\\n\";\n  // out.setf(std::ios::fixed, std::ios::floatfield);\n  out.setf(std::ios::scientific, std::ios::floatfield);\n  out.precision(10);\n  long id = 0;\n  for (const auto& p : points) {\n    const Tuple& t = p.t();\n    out << id++ << \" \" << t.x() << \" \" << t.y() << \" 0\\n\";\n  }\n\n  out.close();\n}\n\nusing BasePoints = galois::InsertBag<Point>;\nusing PtrPoints  = galois::InsertBag<Point*>;\nusing Rounds     = std::vector<PtrPoints*>;\n\nsize_t maxRounds;\nconst int roundShift = 4; //! round sizes are portional to (1 << roundsShift)\n\nstatic void copyPointsFromRounds(PointList& points, Rounds& rounds) {\n  for (int i = maxRounds - 1; i >= 0; --i) {\n    //! [Access elements of InsertBag]\n    // PtrPoints expands to galois::InsertBag<Point*>\n    // points is of type std::vector<Point>\n    PtrPoints& pptrs = *rounds[i];\n    for (auto ii : pptrs) {\n      points.push_back(*ii);\n    }\n    //! [Access elements of InsertBag]\n  }\n}\n\nstruct ReadInput {\n  Graph& graph;\n  BasePoints& basePoints;\n  Rounds& rounds;\n  std::random_device rng;\n  std::mt19937 urng;\n\n  ReadInput(Graph& g, BasePoints& b, Rounds& r)\n      : graph(g), basePoints(b), rounds(r), urng(rng()) {}\n\n  void addBoundaryNodes(Point* p1, Point* p2, Point* p3) {\n    Element large_triangle(p1, p2, p3);\n    GNode large_node = graph.createNode(large_triangle);\n    graph.addNode(large_node);\n\n    p1->addElement(large_node);\n    p2->addElement(large_node);\n    p3->addElement(large_node);\n\n    Element border_ele1(p1, p2);\n    Element border_ele2(p2, p3);\n    Element border_ele3(p3, p1);\n\n    GNode border_node1 = graph.createNode(border_ele1);\n    GNode border_node2 = graph.createNode(border_ele2);\n    GNode border_node3 = graph.createNode(border_ele3);\n\n    graph.addNode(border_node1);\n    graph.addNode(border_node2);\n    graph.addNode(border_node3);\n\n    graph.getEdgeData(graph.addEdge(large_node, border_node1)) = 0;\n    graph.getEdgeData(graph.addEdge(large_node, border_node2)) = 1;\n    graph.getEdgeData(graph.addEdge(large_node, border_node3)) = 2;\n\n    graph.getEdgeData(graph.addEdge(border_node1, large_node)) = 0;\n    graph.getEdgeData(graph.addEdge(border_node2, large_node)) = 0;\n    graph.getEdgeData(graph.addEdge(border_node3, large_node)) = 0;\n  }\n\n  template <typename L>\n  void generateRoundsImpl(const L& loop, size_t size, PointList& points,\n                          size_t log2) {\n    loop(\n        galois::iterate(size_t{0}, size),\n        [&, this](size_t index) {\n          const Point& p = points[index];\n\n          Point* ptr = &(basePoints.push(p));\n          int r      = 0;\n          for (size_t i = 0; i < log2; ++i) {\n            size_t mask = (1UL << (i + 1)) - 1;\n            if ((index & mask) == (1UL << i)) {\n              r = i;\n              break;\n            }\n          }\n\n          rounds[r / roundShift]->push(ptr);\n        },\n        galois::loopname(\"generateRoundsImpl\"));\n  }\n\n  //! Blocked point distribution (exponentially increasing block size) with\n  //! points randomized within a round\n  void generateRoundsOld(PointList& points, bool randomize) {\n    size_t counter = 0;\n    size_t round   = 0;\n    size_t next    = 1 << roundShift;\n    std::vector<Point*> buf;\n\n    PointList::iterator ii = points.begin(), ei = points.end();\n    while (ii != ei) {\n      Point* ptr = &(basePoints.push(*ii));\n      buf.push_back(ptr);\n      ++ii;\n      if (ii == ei || counter > next) {\n        next *= next;\n        int r = maxRounds - 1 - round;\n        if (randomize)\n          std::shuffle(buf.begin(), buf.end(), urng);\n        std::copy(buf.begin(), buf.end(), std::back_inserter(*rounds[r]));\n        buf.clear();\n        ++round;\n      }\n      ++counter;\n    }\n  }\n\n  void generateRounds(PointList& points, bool addBoundary) {\n    size_t size = points.size() - 3;\n\n    size_t log2 = std::max((size_t)floor(log(size) / log(2)), (size_t)1);\n    maxRounds   = log2 / roundShift;\n    for (size_t i = 0; i <= maxRounds;\n         i++) { // rounds[maxRounds+1] for boundary points\n      rounds.push_back(new galois::InsertBag<Point*>);\n    }\n\n    PointList ordered;\n    // ordered.reserve(size);\n\n    if (noReorderPoints) {\n      std::copy(points.begin(), points.begin() + size,\n                std::back_inserter(ordered));\n      generateRoundsOld(ordered, false);\n    } else {\n      // Reorganize spatially\n      QuadTree q(\n          boost::make_transform_iterator(points.begin(), GetPointer()),\n          boost::make_transform_iterator(points.begin() + size, GetPointer()));\n\n      q.output(std::back_inserter(ordered));\n\n      if (true) {\n        if (detAlgo == nondet) {\n          generateRoundsImpl(galois::DoAll(), size, ordered, log2);\n\n        } else {\n          generateRoundsImpl(galois::StdForEach(), size, ordered, log2);\n        }\n      } else {\n        generateRoundsOld(ordered, true);\n      }\n    }\n\n    if (!addBoundary)\n      return;\n\n    // Now, handle boundary points\n    size_t last = points.size();\n    //! [Insert elements into InsertBag]\n    // basePoints is of type galois::InsertBag<Point>\n    // points is of type std::vector<Point>\n    Point* p1 = &(basePoints.push(points[last - 1]));\n    Point* p2 = &(basePoints.push(points[last - 2]));\n    Point* p3 = &(basePoints.push(points[last - 3]));\n    //! [Insert elements into InsertBag]\n\n    rounds[maxRounds]->push(p1);\n    rounds[maxRounds]->push(p2);\n    rounds[maxRounds]->push(p3);\n\n    addBoundaryNodes(p1, p2, p3);\n  }\n\n  void operator()(const std::string& filename, bool addBoundary) {\n    PointList points;\n    ReadPoints(points).from(filename);\n\n    std::cout << \"configuration: \" << points.size() << \" points\\n\";\n\n#if 1\n    galois::preAlloc(\n        32 * points.size() * sizeof(Element) *\n        1.5 // mesh is about 2x number of points (for random points)\n        / (galois::runtime::pagePoolSize()) // in pages\n    );\n#else\n    galois::preAlloc(1 * numThreads // some per-thread state\n                     + 2 * points.size() *\n                           sizeof(Element) // mesh is about 2x number of points\n                                           // (for random points)\n                           * 32            // include graph node size\n                           / (galois::runtime::hugePageSize) // in pages\n    );\n#endif\n    galois::reportPageAlloc(\"MeminfoPre\");\n\n    galois::StatTimer T(\"generateRounds\");\n    T.start();\n    generateRounds(points, addBoundary);\n    T.stop();\n  }\n};\n\nstatic void writeMesh(const std::string& filename, Graph& graph) {\n  long numTriangles = 0;\n  long numSegments  = 0;\n  for (auto n : graph) {\n    Element& e = graph.getData(n);\n    if (e.boundary()) {\n      numSegments++;\n    } else {\n      numTriangles++;\n    }\n  }\n\n  long tid = 0;\n  long sid = 0;\n  std::string elementName(filename);\n  std::string polyName(filename);\n\n  elementName.append(\".ele\");\n  polyName.append(\".poly\");\n\n  std::ofstream eout(elementName.c_str());\n  std::ofstream pout(polyName.c_str());\n  // <num triangles> <nodes per triangle> <num attributes>\n  eout << numTriangles << \" 3 0\\n\";\n  // <num vertices> <dimension> <num attributes> <has boundary markers>\n  // ...\n  // <num segments> <has boundary markers>\n  pout << \"0 2 0 0\\n\";\n  pout << numSegments << \" 1\\n\";\n  for (auto n : graph) {\n    const Element& e = graph.getData(n);\n    if (e.boundary()) {\n      // <segment id> <vertex> <vertex> <is boundary>\n      pout << sid++ << \" \" << e.getPoint(0)->id() << \" \" << e.getPoint(1)->id()\n           << \" 1\\n\";\n    } else {\n      // <triangle id> <vertex> <vertex> <vertex> [in ccw order]\n      eout << tid++ << \" \" << e.getPoint(0)->id() << \" \";\n      if (e.clockwise()) {\n        eout << e.getPoint(2)->id() << \" \" << e.getPoint(1)->id() << \"\\n\";\n      } else {\n        eout << e.getPoint(1)->id() << \" \" << e.getPoint(2)->id() << \"\\n\";\n      }\n    }\n  }\n\n  eout.close();\n  // <num holes>\n  pout << \"0\\n\";\n  pout.close();\n}\n\nstruct DelaunayTriangulation {\n\n  QuadTree* tree;\n  Graph& graph;\n\n  struct ContainsTuple {\n    const Graph& graph;\n    Tuple tuple;\n    ContainsTuple(const Graph& g, const Tuple& t) : graph(g), tuple(t) {}\n    bool operator()(const GNode& n) const {\n      assert(!graph.getData(n, galois::MethodFlag::UNPROTECTED).boundary());\n      return graph.getData(n, galois::MethodFlag::UNPROTECTED)\n          .inTriangle(tuple);\n    }\n  };\n\n  void computeCenter(const Element& e, Tuple& t) const {\n    for (int i = 0; i < 3; ++i) {\n      const Tuple& o = e.getPoint(i)->t();\n      for (int j = 0; j < 2; ++j) {\n        t[j] += o[j];\n      }\n    }\n    for (int j = 0; j < 2; ++j) {\n      t[j] *= 1 / 3.0;\n    }\n  }\n\n  void findBestNormal(const Element& element, const Point* p,\n                      const Point*& bestP1, const Point*& bestP2) {\n    Tuple center(0);\n    computeCenter(element, center);\n    int scale = element.clockwise() ? 1 : -1;\n\n    Tuple origin = p->t() - center;\n    //        double length2 = origin.x() * origin.x() + origin.y() *\n    //        origin.y();\n    bestP1 = bestP2 = NULL;\n    double bestVal  = 0.0;\n    for (int i = 0; i < 3; ++i) {\n      int next = i + 1;\n      if (next > 2)\n        next -= 3;\n\n      const Point* p1 = element.getPoint(i);\n      const Point* p2 = element.getPoint(next);\n      double dx       = p2->t().x() - p1->t().x();\n      double dy       = p2->t().y() - p1->t().y();\n      Tuple normal(scale * -dy, scale * dx);\n      double val = normal.dot(origin); // / length2;\n      if (bestP1 == NULL || val > bestVal) {\n        bestVal = val;\n        bestP1  = p1;\n        bestP2  = p2;\n      }\n    }\n    assert(bestP1 != NULL && bestP2 != NULL && bestVal > 0);\n  }\n\n  GNode findCorrespondingNode(GNode start, const Point* p1, const Point* p2) {\n    for (auto ii : graph.edges(start)) {\n      GNode dst  = graph.getEdgeDst(ii);\n      Element& e = graph.getData(dst, galois::MethodFlag::UNPROTECTED);\n      int count  = 0;\n      for (int i = 0; i < e.dim(); ++i) {\n        if (e.getPoint(i) == p1 || e.getPoint(i) == p2) {\n          if (++count == 2)\n            return dst;\n        }\n      }\n    }\n    GALOIS_DIE(\"unreachable\");\n    return start;\n  }\n\n  bool planarSearch(const Point* p, GNode start, GNode& node) {\n    // Try simple hill climbing instead\n    ContainsTuple contains(graph, p->t());\n    while (!contains(start)) {\n      Element& element = graph.getData(start, galois::MethodFlag::WRITE);\n      if (element.boundary()) {\n        // Should only happen when quad tree returns a boundary point which is\n        // rare There's only one way to go from here\n        assert(std::distance(graph.edge_begin(start), graph.edge_end(start)) ==\n               1);\n        start = graph.getEdgeDst(\n            graph.edge_begin(start, galois::MethodFlag::WRITE));\n      } else {\n        // Find which neighbor will get us to point fastest by computing normal\n        // vectors\n        const Point *p1, *p2;\n        findBestNormal(element, p, p1, p2);\n        start = findCorrespondingNode(start, p1, p2);\n      }\n    }\n\n    node = start;\n    return true;\n  }\n\n  bool findContainingElement(const Point* p, GNode& node) {\n    Point* result;\n    if (!tree->find(p, result)) {\n      return false;\n    }\n\n    result->get(galois::MethodFlag::WRITE);\n\n    GNode someNode = result->someElement();\n\n    // Not in mesh yet\n    if (!someNode) {\n      return false;\n    }\n\n    return planarSearch(p, someNode, node);\n  }\n\n  using Alloc = galois::PerIterAllocTy;\n\n  struct LocalState {\n    Cavity<Alloc> cav;\n    LocalState(Graph& graph, Alloc& alloc) : cav(graph, alloc) {}\n  };\n\n  template <int Version, typename C>\n  void processPoint(Point* p, C& ctx) {\n    Cavity<Alloc>* cavp = NULL;\n\n    if (Version == detDisjoint) {\n\n      if (ctx.isFirstPass()) {\n        LocalState* localState = ctx.template createLocalState<LocalState>(\n            graph, ctx.getPerIterAlloc());\n        cavp = &localState->cav;\n\n      } else {\n\n        LocalState* localState = ctx.template getLocalState<LocalState>();\n        localState->cav.update();\n        return;\n      }\n    }\n\n    p->get(galois::MethodFlag::WRITE);\n    assert(!p->inMesh());\n\n    GNode node;\n    if (!findContainingElement(p, node)) {\n      // Someone updated an element while we were searching, producing\n      // a semi-consistent state\n      // ctx.push(p);\n      // Current version is safe with locking so this shouldn't happen\n      GALOIS_DIE(\"unreachable\");\n      return;\n    }\n\n    assert(graph.getData(node).inTriangle(p->t()));\n    assert(graph.containsNode(node));\n\n    if (Version == detDisjoint && ctx.isFirstPass()) {\n      cavp->init(node, p);\n      cavp->build();\n    } else {\n      Cavity<Alloc> cav(graph, ctx.getPerIterAlloc());\n      cav.init(node, p);\n      cav.build();\n      if (Version == detPrefix)\n        return;\n      ctx.cautiousPoint();\n      cav.update();\n    }\n  }\n\n  template <int Version, typename WL, typename B, typename... Args>\n  void generateMesh(B& pptrs, Args&&... args) {\n\n    galois::for_each(\n        galois::iterate(pptrs),\n        [&, this](Point* p, auto& ctx) { this->processPoint<Version>(p, ctx); },\n        galois::wl<WL>(), galois::loopname(\"generateMesh\"),\n        galois::local_state<LocalState>(), galois::per_iter_alloc(),\n        galois::no_pushes(), std::forward<Args>(args)...);\n  }\n};\n\n/*\ntemplate<int Version=detBase>\nstruct Process {\n\n\n\n  //! Serial operator\n  void operator()(Point* p) {\n    p->get(galois::MethodFlag::WRITE);\n    assert(!p->inMesh());\n\n    GNode node;\n    if (!findContainingElement(p, node)) {\n      GALOIS_DIE(\"Could not find triangle containing point\");\n      return;\n    }\n\n    assert(graph.getData(node).inTriangle(p->t()));\n    assert(graph.containsNode(node));\n\n    Cavity<> cav(graph);\n    cav.init(node, p);\n    cav.build();\n    cav.update();\n  }\n};\n*/\n\nstatic void run(Rounds& rounds, Graph& graph) {\n  typedef galois::worklists::PerThreadChunkLIFO<32> Chunk;\n  typedef galois::worklists::Deterministic<> DWL;\n\n  for (int i = maxRounds - 1; i >= 0; --i) {\n\n    galois::StatTimer BT(\"buildtree\");\n    BT.start();\n    assert(rounds[i + 1]);\n    PtrPoints& tptrs = *(rounds[i + 1]);\n    QuadTree tree(tptrs.begin(), tptrs.end());\n    BT.stop();\n\n    galois::StatTimer PT(\"ParallelTime\");\n    PT.start();\n\n    assert(rounds[i]);\n    galois::InsertBag<Point*>& pptrs = *(rounds[i]);\n\n    DelaunayTriangulation dt{&tree, graph};\n    switch (detAlgo) {\n    case nondet:\n      dt.generateMesh<detBase, Chunk>(pptrs);\n      break;\n    case detBase:\n      dt.generateMesh<detBase, DWL>(pptrs);\n      break;\n    case detPrefix: {\n      auto nv = [&dt](Point* p, auto& ctx) {\n        dt.processPoint<detPrefix>(p, ctx);\n      };\n      dt.generateMesh<detBase, DWL>(\n          pptrs, galois::neighborhood_visitor<decltype(nv)>(nv));\n      break;\n    }\n    case detDisjoint:\n      dt.generateMesh<detDisjoint, DWL>(pptrs);\n      break;\n    default:\n      GALOIS_DIE(\"unknown algorithm: \", detAlgo);\n    }\n\n    PT.stop();\n  }\n}\n\nvoid deleteRounds(Rounds& rounds) {\n  for (auto r : rounds)\n    delete r;\n}\n\nint main(int argc, char** argv) {\n  galois::SharedMemSys G;\n  LonestarStart(argc, argv, name, desc, url, &inputFile);\n\n  galois::StatTimer totalTime(\"TimerTotal\");\n  totalTime.start();\n\n  if (!meshGraph) {\n    GALOIS_DIE(\"This application requires a mesh graph input;\"\n               \" please use the -meshGraph flag \"\n               \" to indicate the input is a mesh graph.\");\n  }\n\n  Graph graph;\n\n  //! All Point* refer to elements in this bag\n  //! [Define InsertBag]\n  // BasePoints expands to galois::InsertBag<Point>\n  BasePoints basePoints;\n  //! [Define InsertBag]\n\n  Rounds rounds;\n\n  bool writepoints = doWritePoints.size() > 0;\n  ReadInput(graph, basePoints, rounds)(inputFile, !writepoints);\n  if (writepoints) {\n    std::cout << \"Writing \" << doWritePoints << \"\\n\";\n    PointList points;\n    copyPointsFromRounds(points, rounds);\n    writePoints(doWritePoints, points);\n    deleteRounds(rounds);\n    return 0;\n  }\n\n  const char* name = 0;\n  switch (detAlgo) {\n  case nondet:\n    name = \"nondet\";\n    break;\n  case detBase:\n    name = \"detBase\";\n    break;\n  case detPrefix:\n    name = \"detPrefix\";\n    break;\n  case detDisjoint:\n    name = \"detDisjoint\";\n    break;\n  default:\n    name = \"unknown\";\n    break;\n  }\n  galois::gInfo(\"Algorithm \", name);\n\n  galois::StatTimer execTime(\"Timer_0\");\n  execTime.start();\n  run(rounds, graph);\n  execTime.stop();\n  std::cout << \"mesh size: \" << graph.size() << \"\\n\";\n\n  galois::reportPageAlloc(\"MeminfoPost\");\n\n  if (!skipVerify) {\n    Verifier verifier;\n    if (!verifier.verify(&graph)) {\n      GALOIS_DIE(\"triangulation failed\");\n    }\n    std::cout << \"Triangulation OK\\n\";\n  }\n\n  if (doWriteMesh.size()) {\n    std::string base = doWriteMesh;\n    std::cout << \"Writing \" << base << \"\\n\";\n    writeMesh(base.c_str(), graph);\n\n    PointList points;\n    // Reordering messes up connection between id and place in pointlist\n    ReadPoints(points).from(inputFile);\n    writePoints(base.append(\".node\"), points);\n  }\n\n  deleteRounds(rounds);\n\n  totalTime.stop();\n\n  return 0;\n}\n", "meta": {"hexsha": "445ddd7b3dbdc1b1734e17aba455e8dfe8f80957", "size": 22875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/scientific/cpu/delaunaytriangulation/DelaunayTriangulationDet.cpp", "max_stars_repo_name": "vishweshjatala/Galois", "max_stars_repo_head_hexsha": "3b62118a0bebee56a13841170a9328f199332330", "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/scientific/cpu/delaunaytriangulation/DelaunayTriangulationDet.cpp", "max_issues_repo_name": "vishweshjatala/Galois", "max_issues_repo_head_hexsha": "3b62118a0bebee56a13841170a9328f199332330", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/scientific/cpu/delaunaytriangulation/DelaunayTriangulationDet.cpp", "max_forks_repo_name": "vishweshjatala/Galois", "max_forks_repo_head_hexsha": "3b62118a0bebee56a13841170a9328f199332330", "max_forks_repo_licenses": ["BSD-3-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.3106435644, "max_line_length": 80, "alphanum_fraction": 0.5960655738, "num_tokens": 6290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.06278921341991638, "lm_q1q2_score": 0.026051171267882273}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_ElectronVoltUnit.hpp\n//! \\author Alex Robison\n//! \\brief  The electron volt unit declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_ELECTRON_VOLT_UNIT_HPP\n#define UTILITY_ELECTRON_VOLT_UNIT_HPP\n\n// Boost Includes\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/physical_dimensions/energy.hpp>\n#include <boost/units/base_unit.hpp>\n#include <boost/units/conversion.hpp>\n#include <boost/units/make_scaled_unit.hpp>\n\nnamespace Utility{\n\nnamespace Units{\n\n//! The electron volt base unit\nstruct ElectronVoltBaseUnit : public boost::units::base_unit<ElectronVoltBaseUnit,boost::units::energy_dimension,1>\n{\n  static const char* name() { return \"electron volt\"; }\n  static const char* symbol() { return \"eV\"; }\n};\n\n//! The electron volt unit\ntypedef ElectronVoltBaseUnit::unit_type ElectronVolt;\n\n//! The kilo-electron volt unit\ntypedef boost::units::make_scaled_unit<ElectronVolt, boost::units::scale<10,boost::units::static_rational<3> > >::type KiloElectronVolt;\n\n//! The mega-electron volt unit\ntypedef boost::units::make_scaled_unit<ElectronVolt, boost::units::scale<10,boost::units::static_rational<6> > >::type MegaElectronVolt;\n\nBOOST_UNITS_STATIC_CONSTANT( eV, ElectronVolt );\nBOOST_UNITS_STATIC_CONSTANT( keV, KiloElectronVolt );\nBOOST_UNITS_STATIC_CONSTANT( MeV, MegaElectronVolt );\n\n} // end Units namespace\n\n} // end Utility namespace\n\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR( Utility::Units::ElectronVoltBaseUnit, boost::units::si::energy, double, 1.602176565e-19 );\nBOOST_UNITS_DEFINE_CONVERSION_FACTOR( boost::units::si::energy, Utility::Units::ElectronVoltBaseUnit, double, 1.0/1.602176565e-19 );\n\nBOOST_UNITS_DEFAULT_CONVERSION( Utility::Units::ElectronVoltBaseUnit, boost::units::si::energy );\n\n#endif // end UTILITY_ELECTRON_VOLT_UNIT_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_ElectronVoltUnit.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "f3571a7963f36d2c6f3e5f460f22fa1e75c0c6bb", "size": 2131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/units/src/Utility_ElectronVoltUnit.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/units/src/Utility_ElectronVoltUnit.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/units/src/Utility_ElectronVoltUnit.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.3859649123, "max_line_length": 136, "alphanum_fraction": 0.665415298, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.06278920508951336, "lm_q1q2_score": 0.026051168720135694}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n\n/****************************************************************************/\n\n/* Paso: SparseMatrix */\n\n/****************************************************************************/\n\n/* Author: Lutz Gross, l.gross@uq.edu.au */\n\n/****************************************************************************/\n\n#include \"SparseMatrix.h\"\n#include \"BlockOps.h\"\n#include \"MKL.h\"\n#include \"Options.h\"\n#include \"PasoUtil.h\"\n#include \"Preconditioner.h\"\n#include \"UMFPACK.h\"\n#include \"mmio.h\"\n\n#include <boost/scoped_array.hpp>\n#include <fstream>\n\n/****************************************************************************/\n\nnamespace paso {\n\nusing escript::IndexList;\n\n/* debug: print the entries */\n/*\nvoid print_entries(index_t *r, index_t *c, double *v, int nz)\n{\n    for(int i=0; i<nz; i++)\n        printf(\"(%ld, %ld) == %e\\n\", (long)r[i], (long)c[i], v[i]);\n}\n*/\n\n/* swap function */\nvoid swap(index_t *r, index_t *c, double *v, int left, int right)\n{\n    double v_temp;\n    index_t temp;\n\n    temp = r[left];\n    r[left] = r[right];\n    r[right] = temp;\n\n    temp = c[left];\n    c[left] = c[right];\n    c[right] = temp;\n\n    v_temp = v[left];\n    v[left] = v[right];\n    v[right] = v_temp;\n}\n\nvoid q_sort(index_t *row, index_t *col, double *val, int begin, int end, int N)\n{\n    int l, r;\n    index_t pivot, lval;\n\n    if (end > begin) {\n        pivot = N * row[begin] + col[begin];\n        l = begin + 1;\n        r = end;\n\n        while (l < r) {\n            lval = N * row[l] + col[l];\n            if (lval < pivot)\n                l++;\n            else {\n                r--;\n                swap( row, col, val, l, r );\n            }\n        }\n        l--;\n        swap(row, col, val, begin, l);\n        q_sort(row, col, val, begin, l, N);\n        q_sort(row, col, val, r, end, N);\n    }\n}\n\n\n/* Allocates a SparseMatrix of given type using the given matrix pattern.\n   Values are initialized with zero.\n   If patternIsUnrolled and type & MATRIX_FORMAT_BLK1, it is assumed that the\n   pattern is already unrolled to match the requested block size\n   and offsets. Otherwise unrolling and offset adjustment will be performed.\n*/\nSparseMatrix::SparseMatrix(SparseMatrixType ntype, Pattern_ptr npattern,\n                           dim_t rowBlockSize, dim_t colBlockSize,\n                           bool patternIsUnrolled) :\n    type(ntype),\n    val(NULL),\n    solver_package(PASO_PASO),\n    solver_p(NULL)\n{\n    if (patternIsUnrolled) {\n        if ((ntype & MATRIX_FORMAT_OFFSET1) != (npattern->type & MATRIX_FORMAT_OFFSET1)) {\n            throw PasoException(\"SparseMatrix: requested offset and pattern offset do not match.\");\n        }\n    }\n    // do we need to apply unrolling?\n    bool unroll\n          // we don't like non-square blocks\n        = (rowBlockSize != colBlockSize)\n#ifndef ESYS_HAVE_LAPACK\n          // or any block size bigger than 3\n          || (colBlockSize > 3)\n#endif\n          // or if block size one requested and the block size is not 1\n          || ((ntype & MATRIX_FORMAT_BLK1) && (colBlockSize > 1))\n          // or if offsets don't match\n          || ((ntype & MATRIX_FORMAT_OFFSET1) != (npattern->type & MATRIX_FORMAT_OFFSET1));\n\n    SparseMatrixType pattern_format_out = (ntype & MATRIX_FORMAT_OFFSET1)\n                             ? MATRIX_FORMAT_OFFSET1 : MATRIX_FORMAT_DEFAULT;\n\n    // === compressed sparse columns ===\n    if (ntype & MATRIX_FORMAT_CSC) {\n        if (unroll) {\n            if (patternIsUnrolled) {\n                pattern = npattern;\n            } else {\n                pattern = npattern->unrollBlocks(pattern_format_out,\n                                                 colBlockSize, rowBlockSize);\n            }\n            row_block_size = 1;\n            col_block_size = 1;\n        } else {\n            pattern = npattern->unrollBlocks(pattern_format_out, 1, 1);\n            row_block_size = rowBlockSize;\n            col_block_size = colBlockSize;\n        }\n        numRows = pattern->numInput;\n        numCols = pattern->numOutput;\n    } else {\n    // === compressed sparse row ===\n        if (unroll) {\n            if (patternIsUnrolled) {\n                pattern = npattern;\n            } else {\n                pattern = npattern->unrollBlocks(pattern_format_out,\n                                                 rowBlockSize, colBlockSize);\n            }\n            row_block_size = 1;\n            col_block_size = 1;\n        } else {\n            pattern = npattern->unrollBlocks(pattern_format_out, 1, 1);\n            row_block_size = rowBlockSize;\n            col_block_size = colBlockSize;\n        }\n        numRows = pattern->numOutput;\n        numCols = pattern->numInput;\n    }\n    if (ntype & MATRIX_FORMAT_DIAGONAL_BLOCK) {\n        block_size = std::min(row_block_size, col_block_size);\n    } else {\n        block_size = row_block_size*col_block_size;\n    }\n    len = (size_t)(pattern->len)*(size_t)(block_size);\n\n    val=new double[len];\n    setValues(0.);\n}\n\nSparseMatrix::~SparseMatrix()\n{\n    switch (solver_package) {\n        case PASO_SMOOTHER:\n            Preconditioner_LocalSmoother_free((Preconditioner_LocalSmoother*) solver_p);\n            break;\n\n        case PASO_MKL:\n            MKL_free(this);\n            break;\n\n        case PASO_UMFPACK:\n            UMFPACK_free(this);\n            break;\n    }\n    delete[] val;\n}\n\nSparseMatrix_ptr SparseMatrix::loadMM_toCSR(const char* filename)\n{\n    SparseMatrix_ptr out;\n    int i;\n    MM_typecode matrixCode;\n\n    // open the file\n    std::ifstream f(filename);\n    if (f.fail()) {\n        throw PasoException(\"SparseMatrix::loadMM_toCSR: Cannot open file for reading.\");\n    }\n\n    // process banner\n    if (mm_read_banner(f, &matrixCode) != 0) {\n        f.close();\n        throw PasoException(\"SparseMatrix::loadMM_toCSR: Error processing MM banner.\");\n    }\n    if (!(mm_is_real(matrixCode) && mm_is_sparse(matrixCode) && mm_is_general(matrixCode))) {\n        f.close();\n        throw PasoException(\"SparseMatrix::loadMM_toCSR: found Matrix Market type is not supported.\");\n    }\n\n    // get matrix size\n    int M, N, nz;\n\n    if (mm_read_mtx_crd_size(f, &M, &N, &nz) != 0) {\n        f.close();\n        throw PasoException(\"SparseMatrix::loadMM_toCSR: Could not parse matrix size.\");\n    }\n\n    // prepare storage\n    index_t* col_ind = new index_t[nz];\n    index_t* row_ind = new index_t[nz];\n    index_t* row_ptr = new index_t[M+1];\n    double* val = new double[nz];\n\n    // perform actual read of elements\n    for (i=0; i<nz; i++) {\n        f >> row_ind[i] >> col_ind[i] >> val[i];\n        //scan_ret = fscanf(fileHandle_p, \"%d %d %le\\n\", &row_ind[i], &col_ind[i], &val[i]);\n        if (!f.good()) {\n            delete[] val;\n            delete[] row_ind;\n            delete[] col_ind;\n            delete[] row_ptr;\n            f.close();\n            return out;\n        }\n        row_ind[i]--;\n        col_ind[i]--;\n    }\n    f.close();\n\n    // sort the entries\n    q_sort(row_ind, col_ind, val, 0, nz, N);\n\n    // setup row_ptr\n    int curr_row = 0;\n    for(i=0; (i<nz && curr_row<M); curr_row++) {\n        while(row_ind[i] != curr_row)\n            i++;\n        row_ptr[curr_row] = i;\n    }\n    row_ptr[M] = nz;\n\n    Pattern_ptr mainPattern(new Pattern(MATRIX_FORMAT_DEFAULT, M, N,\n                                        row_ptr, col_ind));\n    out.reset(new SparseMatrix(MATRIX_FORMAT_DEFAULT, mainPattern, 1, 1, true));\n\n    // copy values\n    for (i=0; i<nz; i++)\n        out->val[i] = val[i];\n\n    delete[] val;\n    delete[] row_ind;\n    return out;\n}\n\nvoid SparseMatrix::saveMM(const char* filename) const\n{\n    if (col_block_size != row_block_size) {\n        throw PasoException(\"SparseMatrix::saveMM: currently only square blocks are supported.\");\n    }\n\n    // open the file\n    std::ofstream f(filename);\n    if (f.fail()) {\n        throw PasoException(\"SparseMatrix::saveMM: File could not be opened for writing\");\n    }\n    if (type & MATRIX_FORMAT_CSC) {\n        throw PasoException(\"SparseMatrix::saveMM does not support CSC.\");\n    } else {\n        MM_typecode matcode;\n        mm_initialize_typecode(&matcode);\n        mm_set_matrix(&matcode);\n        mm_set_coordinate(&matcode);\n        mm_set_real(&matcode);\n\n        const dim_t N = getNumRows();\n        const dim_t M = getNumCols();\n        mm_write_banner(f, matcode);\n        mm_write_mtx_crd_size(f, N*row_block_size,\n                              M*col_block_size, pattern->ptr[N]*block_size);\n\n        const index_t offset=(type & MATRIX_FORMAT_OFFSET1 ? 1:0);\n\n        f.precision(15);\n\n        if (type & MATRIX_FORMAT_DIAGONAL_BLOCK) {\n            for (dim_t i=0; i<N; i++) {\n                for (dim_t iptr = pattern->ptr[i]-offset; iptr<pattern->ptr[i+1]-offset; ++iptr) {\n                    const dim_t j=pattern->index[iptr]-offset;\n                    for (dim_t ib=0; ib<block_size; ib++) {\n                        const dim_t irow=ib+row_block_size*i;\n                        const dim_t icol=ib+col_block_size*j;\n                        f << irow+1 << \" \" << icol+1 << \" \"\n                          << val[iptr*block_size+ib] << std::endl;\n                    }\n                }\n            }\n        } else {\n            for (dim_t i=0; i<N; i++) {\n                for (dim_t iptr = pattern->ptr[i]-offset; iptr<pattern->ptr[i+1]-offset; ++iptr) {\n                    const dim_t j=pattern->index[iptr]-offset;\n                    for (dim_t irb=0; irb<row_block_size; irb++) {\n                        const dim_t irow=irb+row_block_size*i;\n                        for (dim_t icb=0; icb<col_block_size; icb++) {\n                            const dim_t icol=icb+col_block_size*j;\n                            f << irow+1 << \" \" << icol+1 << \" \"\n                                << val[iptr*block_size+irb+row_block_size*icb]\n                                << std::endl;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    // close the file\n    f.close();\n}\n\nvoid SparseMatrix::addAbsRow_CSR_OFFSET0(double* array) const\n{\n    const dim_t nOut = pattern->numOutput;\n#pragma omp parallel for\n    for (dim_t ir=0; ir < nOut; ir++) {\n        for (dim_t irb=0; irb < row_block_size; irb++) {\n            const dim_t irow = irb+row_block_size*ir;\n            double fac=0.;\n            for (index_t iptr=pattern->ptr[ir]; iptr < pattern->ptr[ir+1]; iptr++) {\n                for (dim_t icb=0; icb < col_block_size; icb++) {\n                    const index_t idx = iptr*block_size+irb+row_block_size*icb;\n                    fac += std::abs(val[idx]);\n                }\n            }\n            array[irow]+=fac;\n        }\n    }\n}\n\nvoid SparseMatrix::maxAbsRow_CSR_OFFSET0(double* array) const\n{\n    const dim_t nOut = pattern->numOutput;\n#pragma omp parallel for\n    for (dim_t ir=0; ir < nOut; ir++) {\n        for (dim_t irb=0; irb < row_block_size; irb++) {\n            const dim_t irow = irb+row_block_size*ir;\n            double fac=0.;\n            for (index_t iptr=pattern->ptr[ir]; iptr < pattern->ptr[ir+1]; iptr++) {\n                for (dim_t icb=0; icb < col_block_size; icb++) {\n                    const index_t idx = iptr*block_size+irb+row_block_size*icb;\n                    fac=std::max(fac, std::abs(val[idx]));\n                }\n            }\n            array[irow]=std::max(array[irow], fac);\n        }\n    }\n}\n\nvoid SparseMatrix::addRow_CSR_OFFSET0(double* array) const\n{\n    const dim_t nOut = pattern->numOutput;\n#pragma omp parallel for\n    for (dim_t ir=0; ir < nOut; ir++) {\n        for (dim_t irb=0; irb < row_block_size; irb++) {\n            dim_t irow=irb+row_block_size*ir;\n            double fac=0.;\n            for (index_t iptr=pattern->ptr[ir]; iptr<pattern->ptr[ir+1]; iptr++) {\n                for (dim_t icb=0; icb < col_block_size; icb++)\n                    fac += val[iptr*block_size+irb+row_block_size*icb];\n\n            }\n            array[irow]+=fac;\n        }\n    }\n}\n\nvoid SparseMatrix::copyBlockToMainDiagonal(const double* in)\n{\n    const dim_t n = pattern->numOutput;\n    const dim_t nblk = block_size;\n    const size_t nblk_size = sizeof(double)*nblk;\n    const index_t* main_ptr = borrowMainDiagonalPointer();\n#pragma omp parallel for\n    for (index_t ir=0; ir < n;ir++) {\n        memcpy((void*)&val[main_ptr[ir]*nblk], (void*)&in[nblk*ir], nblk_size);\n    }\n}\n\nvoid SparseMatrix::copyBlockFromMainDiagonal(double* out) const\n{\n    const dim_t n = pattern->numOutput;\n    const dim_t nblk = block_size;\n    const size_t nblk_size = sizeof(double)*nblk;\n    const index_t* main_ptr = borrowMainDiagonalPointer();\n#pragma omp parallel for\n    for (index_t ir=0; ir < n; ir++) {\n        memcpy((void*)&out[nblk*ir], (void*)&val[main_ptr[ir]*nblk], nblk_size);\n    }\n}\n\nvoid SparseMatrix::copyFromMainDiagonal(double* out) const\n{\n    const dim_t n = pattern->numOutput;\n    const dim_t nblk = block_size;\n    const dim_t blk = std::min(row_block_size, col_block_size);\n    const index_t* main_ptr = borrowMainDiagonalPointer();\n#pragma omp parallel for\n    for (index_t ir=0; ir < n; ir++) {\n        for (index_t ib=0; ib < blk; ib++) {\n            out[ir*blk+ib] = val[main_ptr[ir]*nblk+ib+row_block_size*ib];\n        }\n    }\n}\n\nvoid SparseMatrix::copyToMainDiagonal(const double* in)\n{\n    const dim_t n = pattern->numOutput;\n    const dim_t nblk = block_size;\n    const dim_t blk = std::min(row_block_size, col_block_size);\n    const index_t* main_ptr = borrowMainDiagonalPointer();\n#pragma omp parallel for\n    for (index_t ir=0; ir < n; ir++) {\n        for (index_t ib=0; ib < blk; ib++) {\n            val[main_ptr[ir]*nblk+ib+row_block_size*ib] = in[ir*blk+ib];\n        }\n    }\n}\n\nvoid SparseMatrix::applyDiagonal_CSR_OFFSET0(const double* left,\n                                             const double* right)\n{\n    const dim_t row_block = row_block_size;\n    const dim_t col_block = col_block_size;\n    const dim_t n_block = row_block*col_block;\n    const dim_t nOut = pattern->numOutput;\n\n#pragma omp parallel for\n    for (index_t ir=0; ir < nOut; ir++) {\n        for (index_t irb=0; irb < row_block; irb++) {\n            const index_t irow = irb+row_block*ir;\n            const double rtmp = left[irow];\n            for (index_t iptr=pattern->ptr[ir]; iptr < pattern->ptr[ir+1]; iptr++) {\n                #pragma ivdep\n                for (index_t icb=0; icb < col_block_size; icb++) {\n                    const index_t icol = icb+col_block*pattern->index[iptr];\n                    const index_t l = iptr*n_block + irb+row_block*icb;\n                    val[l] *= rtmp*right[icol];\n                }\n            }\n        }\n    }\n}\n\nvoid SparseMatrix::setValues(double value)\n{\n    const index_t index_offset=(type & MATRIX_FORMAT_OFFSET1 ? 1:0);\n    if (!pattern->isEmpty()) {\n        const dim_t nOut = pattern->numOutput;\n#pragma omp parallel for\n        for (dim_t i=0; i < nOut; ++i) {\n            for (index_t iptr=pattern->ptr[i]-index_offset; iptr < pattern->ptr[i+1]-index_offset; ++iptr) {\n                for (dim_t j=0; j<block_size; ++j)\n                    val[iptr*block_size+j] = value;\n            }\n        }\n    }\n}\n\nvoid SparseMatrix::invMain(double* inv_diag, index_t* pivot) const\n{\n    int failed = 0;\n    double A11;\n    const dim_t n=numRows;\n    const dim_t n_block=row_block_size;\n    const dim_t m_block=col_block_size;\n    dim_t i;\n    index_t iPtr;\n    index_t* main_ptr=pattern->borrowMainDiagonalPointer();\n    // check matrix is square\n    if (m_block != n_block) {\n        throw PasoException(\"SparseMatrix::invMain: square block size expected.\");\n    }\n    if (n_block == 1) {\n#pragma omp parallel for private(i, iPtr, A11) schedule(static)\n        for (i = 0; i < n; i++) {\n            iPtr = main_ptr[i];\n            A11 = val[iPtr];\n            if (std::abs(A11) > 0.) {\n                inv_diag[i]=1./A11;\n            } else {\n                failed=1;\n            }\n        }\n    } else if (n_block==2) {\n#pragma omp parallel for private(i, iPtr) schedule(static)\n        for (i = 0; i < n; i++) {\n            iPtr = main_ptr[i];\n            BlockOps_invM_2(&inv_diag[i*4], &val[iPtr*4], &failed);\n        }\n    } else if (n_block==3) {\n#pragma omp parallel for private(i, iPtr) schedule(static)\n        for (i = 0; i < n; i++) {\n            iPtr = main_ptr[i];\n            BlockOps_invM_3(&inv_diag[i*9], &val[iPtr*9], &failed);\n        }\n    } else {\n#pragma omp parallel for private(i, iPtr) schedule(static)\n        for (i = 0; i < n; i++) {\n            iPtr = main_ptr[i];\n            BlockOps_Cpy_N(block_size, &inv_diag[i*block_size], &val[iPtr*block_size]);\n            BlockOps_invM_N(n_block, &inv_diag[i*block_size], &pivot[i*n_block], &failed);\n        }\n    }\n    if (failed > 0) {\n        throw PasoException(\"SparseMatrix::invMain: non-regular main diagonal block.\");\n    }\n}\n\nvoid SparseMatrix::applyBlockMatrix(double* block_diag, index_t* pivot,\n                                    double* x, const double *b) const\n{\n    const dim_t n = numRows;\n    const dim_t n_block = row_block_size;\n    util::copy(n_block*n, x, b);\n    BlockOps_solveAll(n_block, n, block_diag, pivot, x);\n}\n\nSparseMatrix_ptr SparseMatrix::getTranspose() const\n{\n    const dim_t m = numCols;\n    const dim_t n = numRows;\n    boost::scoped_array<IndexList> index_list(new IndexList[m]);\n\n    for (dim_t i=0; i<n; ++i) {\n        for (index_t iptr2=pattern->ptr[i]; iptr2<pattern->ptr[i+1]; ++iptr2) {\n            const index_t j = pattern->index[iptr2];\n            index_list[j].insertIndex(i);\n        }\n    }\n\n    Pattern_ptr ATpattern(Pattern::fromIndexListArray(0,m,index_list.get(),0,n,0));\n    SparseMatrix_ptr AT(new SparseMatrix(type, ATpattern, col_block_size, row_block_size, false));\n\n    if ( ((type & MATRIX_FORMAT_DIAGONAL_BLOCK) && (block_size == 1)) ||\n         (row_block_size == 1 && col_block_size == 1)) {\n#pragma omp parallel for\n        for (dim_t i=0; i<m; ++i) {\n            for (index_t iptr_AT=AT->pattern->ptr[i]; iptr_AT<AT->pattern->ptr[i+1]; ++iptr_AT) {\n                const index_t j = AT->pattern->index[iptr_AT];\n                index_t jptr_A = pattern->ptr[j];\n                const index_t* start_p = &pattern->index[jptr_A];\n                const index_t* where_p=(index_t*)bsearch(&i, start_p,\n                                          pattern->ptr[j+1]-jptr_A,\n                                          sizeof(index_t), util::comparIndex);\n                if (where_p != NULL) { // this should always be the case\n                    jptr_A += (index_t)(where_p-start_p);\n                    AT->val[iptr_AT] = val[jptr_A];\n                }\n            }\n        }\n    } else {\n        if (type & MATRIX_FORMAT_DIAGONAL_BLOCK) {\n#pragma omp parallel for\n            for (dim_t i=0; i<m; ++i) {\n                for (index_t iptr_AT=AT->pattern->ptr[i]; iptr_AT<AT->pattern->ptr[i+1]; ++iptr_AT) {\n                    const index_t j = AT->pattern->index[iptr_AT];\n                    index_t jptr_A = pattern->ptr[j];\n                    const index_t* start_p = &pattern->index[jptr_A];\n                    const index_t* where_p = (index_t*)bsearch(&i, start_p,\n                                         pattern->ptr[j+1]-jptr_A,\n                                         sizeof(index_t), util::comparIndex);\n                    if (where_p != NULL) { // this should always be the case\n                        jptr_A += (index_t)(where_p-start_p);\n                        for (dim_t ib=0; ib < block_size; ++ib)\n                            AT->val[iptr_AT*block_size+ib] = val[jptr_A*block_size+ib];\n                    }\n                }\n            }\n        } else {\n#pragma omp parallel for\n            for (dim_t i=0; i<m; ++i) {\n                for (index_t iptr_AT=AT->pattern->ptr[i]; iptr_AT<AT->pattern->ptr[i+1]; ++iptr_AT) {\n                    const index_t j = AT->pattern->index[iptr_AT];\n                    index_t jptr_A = pattern->ptr[j];\n                    const index_t* start_p = &pattern->index[jptr_A];\n                    const index_t* where_p=(index_t*)bsearch(&i, start_p,\n                                       pattern->ptr[j + 1]-jptr_A,\n                                       sizeof(index_t), util::comparIndex);\n                    if (where_p != NULL) { // this should always be the case\n                        jptr_A += (index_t)(where_p-start_p);\n                        for (index_t irb=0; irb < row_block_size; ++irb) {\n                            for (index_t icb=0 ; icb < col_block_size; ++icb) {\n                                AT->val[iptr_AT*block_size+icb+col_block_size*irb] = val[jptr_A*block_size+irb+row_block_size*icb];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return AT;\n}\n\nSparseMatrix_ptr SparseMatrix::unroll(SparseMatrixType newType) const\n{\n    const index_t out_type = (newType & MATRIX_FORMAT_BLK1) ? newType : newType + MATRIX_FORMAT_BLK1;\n    SparseMatrix_ptr out(new SparseMatrix(out_type, pattern, row_block_size, col_block_size, false));\n\n    const dim_t n = numRows;\n    const index_t A_offset = (type & MATRIX_FORMAT_OFFSET1 ? 1 : 0);\n    const index_t out_offset = (out_type & MATRIX_FORMAT_OFFSET1 ? 1 : 0);\n\n    if (out->type & MATRIX_FORMAT_CSC) {\n#pragma omp parallel for\n        for (dim_t i=0; i<n; ++i) {\n            for (index_t iptr=pattern->ptr[i]-A_offset; iptr<pattern->ptr[i+1]-A_offset; ++iptr) {\n                const index_t j = pattern->index[iptr]-A_offset;\n                for (dim_t icb=0; icb<col_block_size; ++icb) {\n                    const index_t icol=j*col_block_size+icb;\n                    const index_t* start_p=&out->pattern->index[out->pattern->ptr[icol]-out_offset];\n                    const index_t l_col=out->pattern->ptr[icol+1]-out->pattern->ptr[icol];\n                    for (dim_t irb=0; irb<row_block_size; ++irb) {\n                        const index_t irow=row_block_size*i+irb+out_offset;\n                        const index_t* where_p = (index_t*)bsearch(&irow,\n                                    start_p, l_col, sizeof(index_t),\n                                    util::comparIndex);\n                        if (where_p != NULL)\n                            out->val[out->pattern->ptr[icol]-out_offset+(index_t)(where_p-start_p)] =\n                                val[block_size*iptr+irb+row_block_size*icb];\n                    }\n                }\n            }\n        }\n    } else {\n#pragma omp parallel for\n        for (dim_t i=0; i<n; ++i) {\n            for (index_t iptr=pattern->ptr[i]-A_offset; iptr<pattern->ptr[i+1]-A_offset; ++iptr) {\n                const index_t j = pattern->index[iptr]-A_offset;\n                for (dim_t irb=0; irb<row_block_size; ++irb) {\n                    const index_t irow=row_block_size*i+irb;\n                    const index_t* start_p = &out->pattern->index[out->pattern->ptr[irow]-out_offset];\n                    const index_t l_row=out->pattern->ptr[irow+1]-out->pattern->ptr[irow];\n                    for (dim_t icb=0; icb<col_block_size; ++icb) {\n                        const index_t icol=j*col_block_size+icb+out_offset;\n                        const index_t* where_p = (index_t*)bsearch(&icol,\n                                    start_p, l_row, sizeof(index_t),\n                                    util::comparIndex);\n                        if (where_p != NULL)\n                            out->val[out->pattern->ptr[irow]-out_offset+(index_t)(where_p-start_p)] =\n                                val[block_size*iptr+irb+row_block_size*icb];\n                    }\n                }\n            }\n        }\n    }\n    return out;\n}\n\n} // namespace paso\n\n", "meta": {"hexsha": "442821863a836421f4de346a00d32bef3dc7dae8", "size": 24205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "paso/src/SparseMatrix.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paso/src/SparseMatrix.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "paso/src/SparseMatrix.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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.439238653, "max_line_length": 131, "alphanum_fraction": 0.5354265648, "num_tokens": 6231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.05834584675188404, "lm_q1q2_score": 0.02599479797485706}}
{"text": "/**\n * @file GlobalLearning.hpp\n * @brief Implementation of the classes for global learning algorithms.\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_GLOBALLEARNING_HPP_\n#define DETAIL_GLOBALLEARNING_HPP_\n\n#include \"common/SetUtils.hpp\"\n#include \"utils/Logging.hpp\"\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/tuple/tuple.hpp>\n\n\ntemplate <typename Data, typename Var, typename Set>\n/**\n * @brief Constructs the object with the given data.\n */\nGlobalLearning<Data, Var, Set>::GlobalLearning(\n  const mxx::comm& comm,\n  const Data& data,\n  const double alpha,\n  const Var maxConditioning\n) : ConstraintBasedLearning<Data, Var, Set>(comm, data, alpha, maxConditioning),\n    m_cachedNeighbors(),\n    m_removedEdges()\n{\n  TIMER_RESET(m_tSync);\n  TIMER_RESET(m_tDist);\n}\n\ntemplate <typename Data, typename Var, typename Set>\n/**\n * @brief Default destructor that prints out timing information.\n */\nGlobalLearning<Data, Var, Set>::~GlobalLearning(\n)\n{\n  if (this->m_comm.is_first()) {\n    TIMER_ELAPSED_NONZERO(\"Time taken in redistributing: \", m_tDist);\n    TIMER_ELAPSED_NONZERO(\"Time taken in synchronizing neighbors: \", m_tSync);\n  }\n}\n\ntemplate <typename Data, typename Var, typename Set>\nconst Set&\nGlobalLearning<Data, Var, Set>::getPC(\n  const Var target\n) const\n{\n  return m_cachedNeighbors.at(target);\n}\n\ntemplate <typename Data, typename Var, typename Set>\nconst Set&\nGlobalLearning<Data, Var, Set>::getMB(\n  const Var target\n) const\n{\n  return m_cachedNeighbors.at(target);\n}\n\ntemplate <typename Data, typename Var, typename Set>\n/**\n * @brief Function for initializing the data structures used for\n *        learning the skeleton.\n *\n * @param myEdges The array to be initialized with the edges\n *                to be handled by this processor.\n * @param allNeighbors The map containing the neighborhood set\n *                     for all the variables in the network.\n * @param allNeighbors The map used for tracking the removals for\n *                     for all the variables in the network.\n */\nvoid\nGlobalLearning<Data, Var, Set>::initializeLearning(\n  std::vector<std::tuple<Var, Var, double>>& myEdges,\n  std::unordered_map<Var, Set>& allNeighbors,\n  std::unordered_map<Var, Set>& removedNeighbors\n) const\n{\n  // First, block decompose all the edges on all the processors\n  auto n = this->m_allVars.size();\n  mxx::blk_dist dist((n * (n - 1)) / 2, this->m_comm);\n  auto myOffset = dist.eprefix_size();\n  auto mySize = dist.local_size();\n\n  auto vars = std::vector<Var>(this->m_allVars.begin(), this->m_allVars.end());\n  auto k = 0u;\n  auto currOffset = 0u;\n  while (currOffset + (n - (k + 1)) <= static_cast<uint32_t>(myOffset)) {\n    currOffset += (n - (k + 1));\n    ++k;\n  }\n  auto primary = vars.begin() + k;\n  auto secondary = primary + 1 + (myOffset - currOffset);\n\n  myEdges.resize(mySize);\n  for (auto i = 0u; i < mySize; ++i, ++secondary) {\n    if (secondary == vars.end()) {\n      // Start a new primary variable if the secondary variable is exhausted\n      ++primary;\n      secondary = primary + 1;\n    }\n    // Initialize the p-values\n    myEdges[i] = std::make_tuple(*primary, *secondary, 0.0);\n  }\n  // Then, initialize all the neighbor sets\n  for (const auto v : vars) {\n    allNeighbors.insert(std::make_pair(v, set_init(this->getCandidates(v), this->m_data.numVars())));\n    removedNeighbors.insert(std::make_pair(v, set_init(Set(), this->m_data.numVars())));\n  }\n}\n\ntemplate <typename Data, typename Var, typename Set>\nbool\nGlobalLearning<Data, Var, Set>::fixWeightedImbalance(\n  std::vector<std::tuple<Var, Var, double>>& myEdges,\n  const std::vector<double>& myWeights,\n  const double imbalanceThreshold\n) const\n{\n  bool fixed = false;\n  double myTotalWeight = std::accumulate(myWeights.cbegin(), myWeights.cend(), 0.0);\n  TIMER_START(this->m_tMxx);\n  double totalWeight = mxx::allreduce(myTotalWeight, this->m_comm);\n  TIMER_PAUSE(this->m_tMxx);\n  auto imbalance = 0.0;\n  if (totalWeight > 0) {\n    TIMER_START(this->m_tMxx);\n    auto maxWeight = mxx::allreduce(myTotalWeight, mxx::max<double>(), this->m_comm);\n    TIMER_PAUSE(this->m_tMxx);\n    auto avgWeight = totalWeight / this->m_comm.size();\n    imbalance = (maxWeight / avgWeight) - 1.0;\n    //if (this->m_comm.is_first()) {\n      //std::cout << \"Imbalance: \" << imbalance << std::endl;\n    //}\n  }\n  if (std::isgreater(imbalance, imbalanceThreshold)) {\n    TIMER_START(this->m_tMxx);\n    // Get the weight on previous processors\n    auto globalPrefix = mxx::exscan(myTotalWeight, this->m_comm);\n    TIMER_PAUSE(this->m_tMxx);\n    std::vector<uint64_t> sendCounts(this->m_comm.size(), 0);\n    if (std::isgreater(myTotalWeight, 0)) {\n      double div = totalWeight / this->m_comm.size();\n      auto proc = static_cast<uint32_t>(std::floor(globalPrefix / div));\n      auto procFirst = 0u;\n      double localPrefix = 0;\n      double leftWeight = myTotalWeight;\n      std::vector<double> myWeightsPrefix(myWeights.size());\n      std::partial_sum(myWeights.cbegin(), myWeights.cend(), myWeightsPrefix.begin());\n      for (; std::isgreater(leftWeight, 0) && (proc < this->m_comm.size()); ++proc) {\n        double sendWeight = std::min<double>((div * (proc + 1)) - globalPrefix, leftWeight);\n        auto procLast = std::distance(myWeightsPrefix.cbegin(),\n                                      std::lower_bound(myWeightsPrefix.cbegin(),\n                                                       myWeightsPrefix.cend(),\n                                                       localPrefix + sendWeight));\n\n        if (std::isless(myWeightsPrefix[procLast], localPrefix + sendWeight)) {\n          ++procLast;\n        }\n        sendCounts[proc] = (procLast - procFirst) + 1;\n        leftWeight -= (myWeightsPrefix[procLast] - localPrefix);\n        globalPrefix += (myWeightsPrefix[procLast] - localPrefix);\n        localPrefix = myWeightsPrefix[procLast];\n        procFirst = procLast + 1;\n      }\n    }\n    TIMER_START(this->m_tMxx);\n    auto recvCounts = mxx::all2all(sendCounts, this->m_comm);\n    TIMER_PAUSE(this->m_tMxx);\n    auto myRecv = std::accumulate(recvCounts.begin(), recvCounts.end(), 0u);\n    std::vector<std::tuple<Var, Var, double>> newEdges(myRecv);\n    const std::tuple<Var, Var, double>* sendBuf = (myEdges.size() > 0) ? &myEdges[0] : nullptr;\n    std::tuple<Var, Var, double>* recvBuf = (newEdges.size() > 0) ? &newEdges[0] : nullptr;\n    TIMER_START(this->m_tMxx);\n    mxx::all2allv(sendBuf, sendCounts, recvBuf, recvCounts, this->m_comm);\n    TIMER_PAUSE(this->m_tMxx);\n    myEdges = std::move(newEdges);\n    fixed = true;\n  }\n  return fixed;\n}\n\ntemplate <typename Data, typename Var, typename Set>\n/**\n * @brief Function for storing removed edges if they might be relevant\n *        for directing edges later.\n *\n * @param myRemoved A vector of all the removed edges.\n * @param myDSepSets Vector containing d-separating sets for all the removed edges.\n * @param allNeighbors Neighbor sets for all the variables.\n */\nvoid\nGlobalLearning<Data, Var, Set>::storeRemovedEdges(\n  std::vector<std::tuple<Var, Var, double>>&& myRemoved,\n  std::vector<Set>&& myDSepSets,\n  const std::unordered_map<Var, Set>& allNeighbors,\n  const bool duplicateEdges\n) const\n{\n  LOG_MESSAGE_IF(myRemoved.size() != myDSepSets.size(),\n                 error, \"Mismatch between number of edges and d-separating sets.\");\n  // Only retain information which can be used for directing edges later\n  auto newEnd = std::remove_if(boost::make_zip_iterator(boost::make_tuple(myRemoved.begin(), myDSepSets.begin())),\n                               boost::make_zip_iterator(boost::make_tuple(myRemoved.end(), myDSepSets.end())),\n                               [&allNeighbors] (const boost::tuple<std::tuple<Var, Var, double>, Set>& e)\n                                               { return set_intersection(allNeighbors.at(std::get<0>(boost::get<0>(e))),\n                                                                         allNeighbors.at(std::get<1>(boost::get<0>(e)))).empty(); });\n  myRemoved.erase(boost::get<0>(newEnd.get_iterator_tuple()), myRemoved.end());\n  myDSepSets.erase(boost::get<1>(newEnd.get_iterator_tuple()), myDSepSets.end());\n  TIMER_START(this->m_tMxx);\n  // Get the prefix size of all the d-separating sets\n  auto removedSizes = mxx::allgather(myRemoved.size(), this->m_comm);\n  TIMER_PAUSE(this->m_tMxx);\n  auto removedPrefix = std::accumulate(removedSizes.begin(), removedSizes.begin() + this->m_comm.rank(), 0u);\n  std::vector<std::tuple<Var, Var, double, uint32_t>> myRemovedEdges(myRemoved.size());\n  std::transform(std::make_move_iterator(myRemoved.begin()), std::make_move_iterator(myRemoved.end()),\n                 boost::counting_iterator<uint32_t>(removedPrefix), myRemovedEdges.begin(),\n                 [] (const std::tuple<Var, Var, double>&& e, const uint32_t idx)\n                    { return std::make_tuple(std::get<0>(e), std::get<1>(e), std::get<2>(e), idx); });\n  TIMER_START(this->m_tMxx);\n  // Block redistribute all the removed edges\n  mxx::stable_distribute_inplace(myRemovedEdges, this->m_comm);\n  // Sort the removed edges in parallel\n  mxx::comm nonzero_comm(static_cast<MPI_Comm>(this->m_comm));\n  if (mxx::any_of(myRemovedEdges.size() == 0, this->m_comm)) {\n    nonzero_comm = this->m_comm.split(myRemovedEdges.size() > 0);\n  }\n  if (myRemovedEdges.size() > 0) {\n    auto sortEdges = [] (const std::tuple<Var, Var, double, uint32_t>& a, const std::tuple<Var, Var, double, uint32_t>& b)\n                        { return std::make_pair(std::get<0>(a), std::get<1>(a)) < std::make_pair(std::get<0>(b), std::get<1>(b)); };\n    if (!duplicateEdges) {\n      mxx::sort(myRemovedEdges.begin(), myRemovedEdges.end(), sortEdges, nonzero_comm);\n    }\n    else {\n      mxx::stable_sort(myRemovedEdges.begin(), myRemovedEdges.end(), sortEdges, nonzero_comm);\n      auto newEnd = mxx::unique(myRemovedEdges.begin(), myRemovedEdges.end(),\n                                [] (const std::tuple<Var, Var, double, uint32_t>& a, const std::tuple<Var, Var, double, uint32_t>& b)\n                                   { return std::make_pair(std::get<0>(a), std::get<1>(a)) == std::make_pair(std::get<0>(b), std::get<1>(b)); },\n                                nonzero_comm);\n      myRemovedEdges.erase(newEnd, myRemovedEdges.end());\n    }\n  }\n  // Gather all the removed edges on all the processors\n  auto allRemovedEdges = mxx::allgatherv(std::move(myRemovedEdges), this->m_comm);\n  // Also gather all the d-separating sets on all the processors\n  // XXX: We can not use Set as part of a std::tuple during communication\n  //      Therefore, we gather all the sets separately\n  auto allDSepSets = set_allgatherv(std::move(myDSepSets), removedSizes, this->m_data.numVars(), this->m_comm);\n  TIMER_PAUSE(this->m_tMxx);\n  // Finally, store the removed edges with the corresponding d-separating sets\n  m_removedEdges.resize(allRemovedEdges.size());\n  std::transform(std::make_move_iterator(allRemovedEdges.begin()), std::make_move_iterator(allRemovedEdges.end()),\n                 m_removedEdges.begin(),\n                 [&allDSepSets] (const std::tuple<Var, Var, double, uint32_t>&& e)\n                                { return std::make_tuple(std::get<0>(e), std::get<1>(e), std::get<2>(e), allDSepSets.at(std::get<3>(e))); });\n}\n\ntemplate <typename Data, typename Var, typename Set>\n/**\n * @brief Function for constructing skeleton from the neighbor sets.\n *\n * @param allNeighbors Neighborhood sets for all the variables.\n */\nBayesianNetwork<Var>\nGlobalLearning<Data, Var, Set>::constructSkeleton(\n  const std::unordered_map<Var, Set>&& allNeighbors\n) const\n{\n  BayesianNetwork<Var> bn(this->m_data.varNames(this->m_allVars));\n  for (const auto& neighbors : allNeighbors) {\n    const auto x = neighbors.first;\n    for (const auto y : neighbors.second) {\n      if (x < y) {\n        LOG_MESSAGE(info, \"+ Adding the edge %s <-> %s\",\n                          this->m_data.varName(x), this->m_data.varName(y));\n        bn.addEdge(x, y, true);\n      }\n    }\n  }\n  m_cachedNeighbors = std::move(allNeighbors);\n  return bn;\n}\n\ntemplate <typename Data, typename Var, typename Set>\n/**\n * @brief Checks if the given v-structure (y-x-z) is a collider.\n *        Also returns the p-value for the collider.\n *\n * This function checks if x is part of the set that rendered\n * y and z independent. If not, y-x-z is a collider.\n */\nstd::pair<bool, double>\nGlobalLearning<Data, Var, Set>::checkCollider(\n  const Var y,\n  const Var x,\n  const Var z\n) const\n{\n  static auto findPair = [] (const std::tuple<Var, Var, double, Set>& t, const std::pair<Var, Var>& e)\n                            { return std::make_pair(std::get<0>(t), std::get<1>(t)) < e; };\n  // Always try to find the forward edge\n  auto edge = (y < z) ? std::make_pair(y, z) : std::make_pair(z, y);\n  auto eIt = std::lower_bound(m_removedEdges.begin(), m_removedEdges.end(), edge, findPair);\n  if ((eIt == m_removedEdges.end()) ||\n      (std::make_pair(std::get<0>(*eIt), std::get<1>(*eIt)) != edge)) {\n    auto pv = this->m_data.pValue(y, z);\n    LOG_MESSAGE(debug, \"Computed p-value for edge %s - %s is %g\",\n                       this->m_data.varName(y), this->m_data.varName(z), pv);\n    return std::make_pair(true, pv);\n  }\n  else {\n    auto collider = !(std::get<3>(*eIt).contains(x));\n    auto pv = std::get<2>(*eIt);\n    LOG_MESSAGE(debug, \"Stored p-value for edge %s - %s is %g\",\n                       this->m_data.varName(y), this->m_data.varName(z), std::get<2>(*eIt));\n    return std::make_pair(collider, pv);\n  }\n}\n\ntemplate <typename Data, typename Var, typename Set>\nPCStableCommon<Data, Var, Set>::PCStableCommon(\n  const mxx::comm& comm,\n  const Data& data,\n  const double alpha,\n  const Var maxConditioning\n) : GlobalLearning<Data, Var, Set>(comm, data, alpha, maxConditioning)\n{\n}\n\ntemplate <typename Data, typename Var, typename Set>\nstd::pair<double, Set>\nPCStableCommon<Data, Var, Set>::checkEdge(\n  const std::tuple<Var, Var, double>& edge,\n  const std::unordered_map<Var, Set>& allNeighbors,\n  std::unordered_map<Var, Set>& removedNeighbors,\n  const uint32_t setSize,\n  const bool checkBackward\n) const\n{\n  auto pv = 0.0;\n  auto dsep = set_init(Set(), this->m_data.numVars());\n  const auto x = std::get<0>(edge);\n  const auto y = std::get<1>(edge);\n  auto xNeighbors = allNeighbors.at(x);\n  auto yNeighbors = allNeighbors.at(y);\n  LOG_MESSAGE(debug, \"Checking the edge %s <-> %s, d-separating set of size %u\",\n                     this->m_data.varName(x), this->m_data.varName(y), setSize);\n  auto remove = false;\n  // First, check the edge using neighbors of x\n  if (xNeighbors.size() > setSize) {\n    xNeighbors.erase(y);\n    std::tie(pv, dsep) = this->m_data.maxPValueSubset(this->m_alpha, x, y, xNeighbors, setSize, setSize);\n    remove = this->m_data.isIndependent(this->m_alpha, pv);\n  }\n  // Then, check the edge using neighbors of y if all of the following hold:\n  // 1. The conditioning set used for checking is not empty\n  // 2. The neighbors of x did not remove it already\n  // 3. The size of the neighborhood of y is greater than the conditioning set size\n  if (checkBackward && !remove && (yNeighbors.size() > setSize)) {\n    yNeighbors.erase(x);\n    // Further, only check if neighborhood of y has some elements which are\n    // not present in the neighborhood of x\n    if (!set_difference(yNeighbors, xNeighbors).empty()) {\n      std::tie(pv, dsep) = this->m_data.maxPValueSubset(this->m_alpha, x, y, yNeighbors, setSize, setSize);\n      remove = this->m_data.isIndependent(this->m_alpha, pv);\n    }\n  }\n  LOG_MESSAGE(debug, \"%s and %s are \" + std::string(this->m_data.isIndependent(this->m_alpha, pv) ? \"independent\" : \"dependent\") +\n                     \" (p-value = %g)\",\n                     this->m_data.varName(x), this->m_data.varName(y), pv);\n  LOG_MESSAGE_IF(remove, debug, \"- Removing the edge %s <-> %s\",\n                                this->m_data.varName(x), this->m_data.varName(y));\n  if (remove) {\n    // Mark y for removal from neighborhood of x\n    removedNeighbors.at(x).insert(y);\n    // Mark x for removal from neighborhood of y\n    removedNeighbors.at(y).insert(x);\n  }\n  return std::make_pair(pv, dsep);\n}\n\ntemplate <typename Data, typename Var, typename Set>\nBayesianNetwork<Var>\nPCStableCommon<Data, Var, Set>::getSkeleton_sequential(\n  const bool directEdges\n) const\n{\n  std::vector<std::tuple<Var, Var, double>> allEdges;\n  std::unordered_map<Var, Set> allNeighbors;\n  std::unordered_map<Var, Set> removedNeighbors;\n  this->initializeLearning(allEdges, allNeighbors, removedNeighbors);\n  auto maxSize = std::min(this->m_maxConditioning, static_cast<Var>(this->m_allVars.size() - 2));\n  for (auto s = 0u; (s <= maxSize) && !allEdges.empty(); ++s) {\n    LOG_MESSAGE(debug, \"Testing %u edges using sets of size %u\", allEdges.size(), s);\n    TIMER_DECLARE(tIter);\n    for (auto& e : allEdges) {\n      auto result = this->checkEdge(e, allNeighbors, removedNeighbors, s, (s > 0));\n      std::get<2>(e) = result.first;\n      // We need to store the removed edges since the d-separating\n      // set may be required for directing edges later\n      if (directEdges && (s > 0) &&\n          this->m_data.isIndependent(this->m_alpha, result.first)) {\n        TIMER_START(this->m_tDirect);\n        Var x, y;\n        std::tie(x, y, std::ignore) = e;\n        // We only use this information for directing colliders of type x-z-y\n        // However, there is no need to store it if there are no candidates for z\n        // i.e., no common neighbors between x and y\n        if (!set_intersection(allNeighbors.at(x), allNeighbors.at(y)).empty()) {\n          this->m_removedEdges.push_back(std::make_tuple(x, y, result.first, result.second));\n        }\n        TIMER_PAUSE(this->m_tDirect);\n      }\n    }\n    for (auto& rn : removedNeighbors) {\n      if (!rn.second.empty()) {\n        allNeighbors[rn.first] = set_difference(allNeighbors.at(rn.first), rn.second);\n        rn.second.clear();\n      }\n    }\n    auto newEnd = std::remove_if(allEdges.begin(), allEdges.end(),\n                                 [this, &allNeighbors, &s] (const std::tuple<Var, Var, double>& e)\n                                                           { return this->m_data.isIndependent(this->m_alpha, std::get<2>(e)) ||\n                                                                    (allNeighbors.at(std::get<0>(e)).size() <= (s + 1) &&\n                                                                     allNeighbors.at(std::get<1>(e)).size() <= (s + 1)); });\n    allEdges.erase(newEnd, allEdges.end());\n    if (this->m_comm.is_first()) {\n      TIMER_ELAPSED(\"Time taken in testing all sets of size \" + std::to_string(s) + \": \", tIter);\n    }\n    if (directEdges) {\n      TIMER_START(this->m_tDirect);\n      auto newEnd = std::remove_if(this->m_removedEdges.begin(), this->m_removedEdges.end(),\n                                   [&allNeighbors] (const std::tuple<Var, Var, double, Set>& t)\n                                                   { return set_intersection(allNeighbors.at(std::get<0>(t)),\n                                                                             allNeighbors.at(std::get<1>(t))).empty(); });\n      this->m_removedEdges.erase(newEnd, this->m_removedEdges.end());\n      TIMER_PAUSE(this->m_tDirect);\n    }\n  }\n  if (directEdges) {\n    TIMER_START(this->m_tDirect);\n    std::sort(this->m_removedEdges.begin(), this->m_removedEdges.end(),\n              [] (const std::tuple<Var, Var, double, Set>& a, const std::tuple<Var, Var, double, Set>& b)\n                 { return std::make_pair(std::get<0>(a), std::get<1>(a)) < std::make_pair(std::get<0>(b), std::get<1>(b)); });\n    TIMER_PAUSE(this->m_tDirect);\n  }\n  return this->constructSkeleton(std::move(allNeighbors));\n}\n\ntemplate <typename Data, typename Var, typename Set>\nPCStable<Data, Var, Set>::PCStable(\n  const mxx::comm& comm,\n  const Data& data,\n  const double alpha,\n  const Var maxConditioning\n) : PCStableCommon<Data, Var, Set>(comm, data, alpha, maxConditioning)\n{\n}\n\ntemplate <typename Data, typename Var, typename Set>\n/**\n * @brief Function that synchronizes the candidate sets by taking an\n *        intersection of the sets across all the processors.\n *\n * @param mySets A map with the neighbors of the variables\n *               remaining on this processor.\n */\nvoid\nPCStable<Data, Var, Set>::syncSets(\n  std::unordered_map<Var, Set>& mySets\n) const\n{\n  TIMER_START(this->m_tMxx);\n  set_allintersect_indexed(mySets, this->m_allVars, this->m_data.numVars(), this->m_comm);\n  TIMER_PAUSE(this->m_tMxx);\n}\n\ntemplate <typename Data, typename Var, typename Set>\nBayesianNetwork<Var>\nPCStable<Data, Var, Set>::getSkeleton_parallel(\n  const bool directEdges,\n  const double imbalanceThreshold\n) const\n{\n  // Initialize the learning in a similar fashion as done sequentially\n  // Create nC2 edges - one for each unordered variable pair\n  std::vector<std::tuple<Var, Var, double>> myEdges;\n  std::unordered_map<Var, Set> allNeighbors;\n  std::unordered_map<Var, Set> removedNeighbors;\n  this->initializeLearning(myEdges, allNeighbors, removedNeighbors);\n  // The following two data structures are used for getting\n  // d-separating set and p-value for all the removed edges\n  std::vector<std::tuple<Var, Var, double>> myRemoved;\n  std::vector<Set> myDSepSets;\n  auto maxSize = std::min(this->m_maxConditioning, static_cast<Var>(this->m_allVars.size() - 2));\n  for (auto s = 0u; (s <= maxSize) && mxx::any_of(myEdges.size() > 0, this->m_comm); ++s) {\n    LOG_MESSAGE(debug, \"Testing %u edges using sets of size %u\", myEdges.size(), s);\n    TIMER_DECLARE(tIter);\n    for (auto& e : myEdges) {\n      auto result = this->checkEdge(e, allNeighbors, removedNeighbors, s, (s > 0));\n      std::get<2>(e) = result.first;\n      // We need to store the removed edges since the d-separating\n      // set may be required for directing edges later\n      if (directEdges && (s > 0) &&\n          this->m_data.isIndependent(this->m_alpha, result.first)) {\n        TIMER_START(this->m_tDirect);\n        Var x, y;\n        std::tie(x, y, std::ignore) = e;\n        // We only use this information for directing colliders of type x-z-y\n        // However, there is no need to store it if there are no candidates for z\n        // i.e., no common neighbors between x and y\n        if (!set_intersection(allNeighbors.at(x), allNeighbors.at(y)).empty()) {\n          myRemoved.push_back(e);\n          myDSepSets.push_back(result.second);\n        }\n        TIMER_PAUSE(this->m_tDirect);\n      }\n    }\n    auto newEnd = std::remove_if(myEdges.begin(), myEdges.end(),\n                                 [this] (const std::tuple<Var, Var, double>& e)\n                                        { return this->m_data.isIndependent(this->m_alpha, std::get<2>(e)); });\n    myEdges.erase(newEnd, myEdges.end());\n    for (auto& rn : removedNeighbors) {\n      if (!rn.second.empty()) {\n        allNeighbors[rn.first] = set_difference(allNeighbors.at(rn.first), rn.second);\n        rn.second.clear();\n      }\n    }\n    this->m_comm.barrier();\n    TIMER_START(this->m_tSync);\n    this->syncSets(allNeighbors);\n    TIMER_PAUSE(this->m_tSync);\n    newEnd = std::remove_if(myEdges.begin(), myEdges.end(),\n                            [&allNeighbors, &s] (const std::tuple<Var, Var, double>& e)\n                                                { return allNeighbors.at(std::get<0>(e)).size() <= (s + 1) &&\n                                                         allNeighbors.at(std::get<1>(e)).size() <= (s + 1); });\n    myEdges.erase(newEnd, myEdges.end());\n    if (this->m_comm.is_first()) {\n      TIMER_ELAPSED(\"Time taken in testing all sets of size \" + std::to_string(s) + \": \", tIter);\n    }\n    if (std::isgreaterequal(imbalanceThreshold, 0.0)) {\n      std::vector<double> myWeights(myEdges.size(), 0.0);\n      for (auto e = 0u; e < myEdges.size(); ++e) {\n        auto n1 = allNeighbors.at(std::get<0>(myEdges[e])).size();\n        auto n2 = allNeighbors.at(std::get<1>(myEdges[e])).size();\n        if (n1 > s + 1) {\n          myWeights[e] = boost::math::binomial_coefficient<double>(n1 - 1, s + 1);\n        }\n        if (n2 > s + 1) {\n          myWeights[e] += boost::math::binomial_coefficient<double>(n2 - 1, s + 1);\n        }\n      }\n      TIMER_START(this->m_tDist);\n      this->fixWeightedImbalance(myEdges, myWeights, imbalanceThreshold);\n      TIMER_PAUSE(this->m_tDist);\n    }\n  }\n  if (directEdges) {\n    TIMER_START(this->m_tDirect);\n    this->storeRemovedEdges(std::move(myRemoved), std::move(myDSepSets), allNeighbors);\n    TIMER_PAUSE(this->m_tDirect);\n  }\n  return this->constructSkeleton(std::move(allNeighbors));\n}\n\ntemplate <typename Data, typename Var, typename Set>\nPCStable2<Data, Var, Set>::PCStable2(\n  const mxx::comm& comm,\n  const Data& data,\n  const double alpha,\n  const Var maxConditioning\n) : PCStableCommon<Data, Var, Set>(comm, data, alpha, maxConditioning)\n{\n}\n\ntemplate <typename Data, typename Var, typename Set>\nBayesianNetwork<Var>\nPCStable2<Data, Var, Set>::getSkeleton_parallel(\n  const bool directEdges,\n  const double imbalanceThreshold\n) const\n{\n  // Initialize the learning in a similar fashion as done sequentially\n  // Create nC2 edges - one for each unordered variable pair\n  std::vector<std::tuple<Var, Var, double>> myEdges;\n  std::unordered_map<Var, Set> allNeighbors;\n  std::unordered_map<Var, Set> removedNeighbors;\n  this->initializeLearning(myEdges, allNeighbors, removedNeighbors);\n  // The following two data structures are used for getting\n  // d-separating set and p-value for all the removed edges\n  std::vector<std::tuple<Var, Var, double>> myRemoved;\n  std::vector<Set> myDSepSets;\n  std::set<std::tuple<Var, Var, double>> myBackwardRemoved;\n  auto maxSize = std::min(this->m_maxConditioning, static_cast<Var>(this->m_allVars.size() - 2));\n  for (auto s = 0u; (s <= maxSize) && mxx::any_of(myEdges.size() > 0, this->m_comm); ++s) {\n    LOG_MESSAGE(debug, \"Testing %u edges using sets of size %u\", myEdges.size(), s);\n    TIMER_DECLARE(tIter);\n    for (auto& e : myEdges) {\n      auto result = this->checkEdge(e, allNeighbors, removedNeighbors, s, false);\n      std::get<2>(e) = result.first;\n      // We need to store the removed edges since the d-separating\n      // set may be required for directing edges later\n      if (directEdges && (s > 0) &&\n          this->m_data.isIndependent(this->m_alpha, result.first)) {\n        TIMER_START(this->m_tDirect);\n        Var x, y;\n        double pv;\n        std::tie(x, y, pv) = e;\n        // We only use this information for directing colliders of type x-z-y\n        // However, there is no need to store it if there are no candidates for z\n        // i.e., no common neighbors between x and y\n        if (!set_intersection(allNeighbors.at(x), allNeighbors.at(y)).empty()) {\n          myRemoved.push_back((x < y) ? e : std::make_tuple(y, x, pv));\n          myDSepSets.push_back(result.second);\n        }\n        TIMER_PAUSE(this->m_tDirect);\n      }\n    }\n    this->m_comm.barrier();\n    if (this->m_comm.is_first()) {\n      TIMER_ELAPSED(\"Time taken in testing all sets of size \" + std::to_string(s) + \": \", tIter);\n    }\n    TIMER_START(this->m_tSync);\n    this->syncSets(removedNeighbors);\n    TIMER_PAUSE(this->m_tSync);\n    // Remove all the edges found to be independent on this processor\n    // Also remove all the edges found to be independent on any other processor\n    auto newEnd = std::remove_if(myEdges.begin(), myEdges.end(),\n                                 [this, &removedNeighbors] (const std::tuple<Var, Var, double>& e)\n                                                           { return this->m_data.isIndependent(this->m_alpha, std::get<2>(e)) ||\n                                                                    removedNeighbors.at(std::get<0>(e)).contains(std::get<1>(e)); });\n    myEdges.erase(newEnd, myEdges.end());\n    for (auto& rn : removedNeighbors) {\n      if (!rn.second.empty()) {\n        allNeighbors[rn.first] = set_difference(allNeighbors.at(rn.first), rn.second);\n        rn.second.clear();\n      }\n    }\n    if (s == 0) {\n      // Both direction of edges can be tested simultaneously when s > 0\n      // Create a reverse edge for all the remaining edges\n      auto origSize = myEdges.size();\n      myEdges.resize(origSize * 2);\n      Var x, y;\n      for (auto f = 0u, b = origSize; f < origSize; ++f, ++b) {\n        std::tie(x, y, std::ignore) = myEdges[f];\n        myEdges[b] = std::make_tuple(y, x, 0.0);\n      }\n    }\n    // Remove the edges that can no longer be tested using the first variable's neighborhood\n    newEnd = std::remove_if(myEdges.begin(), myEdges.end(),\n                            [&allNeighbors, &s] (const std::tuple<Var, Var, double>& e)\n                                                { return allNeighbors.at(std::get<0>(e)).size() <= (s + 1); });\n    myEdges.erase(newEnd, myEdges.end());\n    std::set<std::tuple<Var, Var, double>> remove;\n    // Now, copy all the backward edges, i.e., (x, y) such that x > y\n    // and the neighborhood of x is the same as that of y\n    std::copy_if(myEdges.begin(), myEdges.end(), std::inserter(remove, remove.begin()),\n                 [&allNeighbors] (const std::tuple<Var, Var, double>& e)\n                                 { return (std::get<0>(e) > std::get<1>(e)) &&\n                                          (set_difference(allNeighbors.at(std::get<0>(e)),\n                                                          allNeighbors.at(std::get<1>(e))) == Set({std::get<1>(e)})); });\n    newEnd = std::remove_if(myEdges.begin(), myEdges.end(), [&remove] (const std::tuple<Var, Var, double>& e)\n                                                                      { return remove.find(e) != remove.end(); });\n    myEdges.erase(newEnd, myEdges.end());\n    // Check if any of the backward edges removed in previous iterations\n    // can be added back to the list of edges\n    std::set<std::tuple<Var, Var, double>> addBackwardRemoved;\n    Var x, y;\n    for (const auto& e : myBackwardRemoved) {\n      std::tie(x, y, std::ignore) = e;\n      if ((allNeighbors.at(x).size() > (s + 1)) &&\n          (set_difference(allNeighbors.at(x), allNeighbors.at(y)) != Set({y}))) {\n        addBackwardRemoved.insert(e);\n      }\n    }\n    // Remove the edges to be added back from the set of removed edges\n    std::set<std::tuple<Var, Var, double>> remaining;\n    std::set_difference(std::make_move_iterator(myBackwardRemoved.begin()),\n                        std::make_move_iterator(myBackwardRemoved.end()),\n                        addBackwardRemoved.begin(), addBackwardRemoved.end(),\n                        std::inserter(remaining, remaining.begin()));\n    myBackwardRemoved.clear();\n    // Also add the edges removed in this iteration\n    std::set_union(std::make_move_iterator(remaining.begin()),\n                   std::make_move_iterator(remaining.end()),\n                   remove.begin(), remove.end(),\n                   std::inserter(myBackwardRemoved, myBackwardRemoved.begin()));\n    // Re-add the backward edges which now need to be tested\n    myEdges.insert(myEdges.end(), addBackwardRemoved.begin(), addBackwardRemoved.end());\n    if (std::isgreaterequal(imbalanceThreshold, 0.0)) {\n      std::vector<double> myWeights(myEdges.size());\n      for (auto e = 0u; e < myEdges.size(); ++e) {\n        auto n = allNeighbors.at(std::get<0>(myEdges[e])).size();\n        myWeights[e] = boost::math::binomial_coefficient<double>(n - 1, s + 1);\n      }\n      TIMER_START(this->m_tDist);\n      this->fixWeightedImbalance(myEdges, myWeights, imbalanceThreshold);\n      TIMER_PAUSE(this->m_tDist);\n    }\n  }\n  if (directEdges) {\n    TIMER_START(this->m_tDirect);\n    this->storeRemovedEdges(std::move(myRemoved), std::move(myDSepSets), allNeighbors, true);\n    TIMER_PAUSE(this->m_tDirect);\n  }\n  return this->constructSkeleton(std::move(allNeighbors));\n}\n\n#endif // DETAIL_GLOBALLEARNING_HPP_\n", "meta": {"hexsha": "8755e38876a8722f66430477c18d647ed7c521e3", "size": 32565, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/GlobalLearning.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/GlobalLearning.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/GlobalLearning.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": 44.5485636115, "max_line_length": 144, "alphanum_fraction": 0.6304928604, "num_tokens": 8461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.055823137600340265, "lm_q1q2_score": 0.025952265217121726}}
{"text": "#ifndef __POTENTIALS_HPP__\n#define __POTENTIALS_HPP__\n\n#include <initializer_list>\n#include <stdexcept>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <functional>\n#include <armadillo>\n#include <stdexcept>\n#include <boost/range/combine.hpp>\n#include \"pauth_types.hpp\"\n#include \"molecular.hpp\"\n\nnamespace pauth {\n\n/*! \\brief Abstract base class for potentials\n *\n * Defines a public interface for all potentials (e.g. spring, LJ, bond-angle,\n * etc.)\n */\nclass abstract_potential {\npublic:\n  virtual ~abstract_potential() = 0;\n\n  /*! \\brief Calculates total potential energy of the current configuration\n   *\n   * Calculates the total potential energy of the current configuration given\n   * each molecule position. Complexity is N^2.\n   * \n   * \\param    sim             Metropolis simulation object\n   * \\return                   Potential energy of the current configuration\n   */\n  inline double U(const metropolis &sim) const {\n    return _U(sim);\n  }\n\n  /*! \\brief Calculates the change in potential energy from a molecule moving\n   *\n   * Calculates the change in potential energy due to the motion of a single\n   * molecule given by the index i. Note the complexity of this is N, which\n   * is much more efficient than calculating the difference using `U`.\n   * Requires: 0 <= i < N\n   * \n   * \\param    sim             Metropolis simulation object\n   * \\param    j               Index of the molecule that moved\n   * \\param    rn_j            New position\n   * \\return                   Change in potential energy\n   */\n  inline double delta_U(const metropolis &sim, const size_t j, \n                        arma::vec& rn_j) const {\n    return _delta_U(sim, j, rn_j);\n  }\n\n  /*! \\brief Calculates the force between molecules i and j\n   *\n   * \\param    sim             Metropolis simulation object\n   * \\param    i               Index of the first molecule\n   * \\param    j               Index of the second molecule\n   * \\return                   Force of molecule j on molecule i\n   */\n  inline arma::vec forceij(const metropolis &sim, const size_t i, \n                           const size_t j) const {\n    return _forceij(sim, i, j);\n  }\n\nprivate:\n  virtual double _U(const metropolis &sim) const = 0;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &rn_j) const = 0;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t i, \n                             const size_t j) const = 0;\n};\n\n/*! Public interface for a 6-12 Lennard-Jones pairwise potential\n */\nclass abstract_LJ_potential : public abstract_potential {\npublic:\n  virtual ~abstract_LJ_potential() = 0;\n\n  /*! \\brief Get the well depth of the potential (epsilon)\n   *\n   * \\param    id1   Molecular id of the first molecule\n   * \\param    id2   Molecular id of the second molecule\n   * \\return         Depth of the potential well\n   */\n  inline double get_well_depth(const molecular_id id1,\n                               const molecular_id id2) const {\n    return _get_well_depth(id1, id2);\n  }\n\n  /*! \\brief Get the distance at which the potential is zero (sigma)\n   *\n   * \\param    id1   Molecular id of the first molecule\n   * \\param    id2   Molecular id of the second molecule\n   * \\return         Zero of the potential\n   */\n  inline double get_rzero(const molecular_id id1,\n                          const molecular_id id2) const {\n    return _get_rzero(id1, id2);\n  }\n\nprivate:\n  virtual double _U(const metropolis &sim) const = 0;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &dx) const = 0;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t i, \n                             const size_t j) const = 0;\n  virtual double _get_well_depth(const molecular_id,\n                                 const molecular_id) const = 0;\n  virtual double _get_rzero(const molecular_id, const molecular_id) const = 0;\n};\n\n/*! Public interface for a 6-12 Lennard-Jones pairwise potential without cutoff\n */\nclass abstract_LJ_full_potential : virtual public abstract_LJ_potential {\npublic:\n  virtual ~abstract_LJ_full_potential() = 0;\n\nprivate:\n  virtual double _U(const metropolis &sim) const;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &dx) const;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t i, \n                             const size_t j) const;\n};\n\n/*! \\brief 6-12 Lennard-Jones pairwise potential\n *\n * Public interface for a Lennard-Jones potential to be used in a simulation \n * where the potential parameters between every pair of molecules is loaded \n * from a YAML file and looked up at runtime.\n */\nclass abstract_LJ_lookup_potential : virtual public abstract_LJ_potential {\npublic:\n  virtual ~abstract_LJ_lookup_potential() = 0;\n\n  /*! \\brief Constructor for LJ potential where well parameters are looked up\n   *\n   * \\param       fname     Filename to well parameter data\n   * \\return                LJ potential with well parameter lookup\n   */\n  abstract_LJ_lookup_potential(const char *fname);\n\nprivate:\n  virtual double _get_well_depth(const molecular_id, const molecular_id) const;\n  virtual double _get_rzero(const molecular_id, const molecular_id) const;\n\n  molecular_pair_interaction_map _well_depth_map; \n  molecular_pair_interaction_map _rzero_map; \n};\n\n/*! \\brief 6-12 Lennard-Jones pairwise potential\n *\n * Lennard-Jones potential to be used in a simulation where the potential\n * parameters between every pair of molecules is loaded from a YAML file\n * and looked up at runtime.\n */\nclass LJ_potential : public abstract_LJ_full_potential, \n                     public abstract_LJ_lookup_potential {\npublic:\n  /*! \\brief Constructor for LJ potential where well parameters are looked up\n   *\n   * \\param       fname     Filename to well parameter data\n   * \\return                LJ potential with well parameter lookup\n   */\n  LJ_potential(const char *fname) \n    : abstract_LJ_lookup_potential(fname) {}\n};\n\n/*! \\brief 6-12 Lennard-Jones pairwise potential\n *\n * Lennard-Jones potential to be used in a simulation where the potential\n * function between every pair of molecules is the same (i.e. to be used in\n * a simulation where all of the molecules are of the same type).\n */\nclass const_well_params_LJ_potential : public abstract_LJ_full_potential {\npublic:\n  /*! \\brief Constructor for a LJ potential with constant well parameters\n   *\n   * \\param    well_depth    Depth of the potential well\n   * \\param    rzero         Finite distance at which potential is zero\n   * \\return                 LJ potential\n   */\n  const_well_params_LJ_potential(const double well_depth, const double rzero)\n      : _well_depth(well_depth), _rzero(rzero) {}\n\n  ~const_well_params_LJ_potential() {}\n\nprivate:\n  virtual double _get_well_depth(molecular_id, molecular_id) const {\n    return _well_depth;\n  }\n\n  virtual double _get_rzero(molecular_id, molecular_id) const { return _rzero; }\n\n  double _well_depth;\n  double _rzero;\n};\n\n/*! \\brief Public interface for a 6-12 Lennard-Jones potential with a cutoff\n *\n * Public interface for a 6-12 Lennard-Jones potential with a cutoff radius\n * and periodic boundary conditions.\n */\nclass abstract_LJ_cutoff_potential : virtual public abstract_LJ_potential {\npublic:\n  /*! \\brief Constructor for a LJ potential with a cutoff radius\n   *\n   * \\param   cutoff         Cutoff radius, default value is 2.5\n   * \\return                 LJ potential\n   */\n  abstract_LJ_cutoff_potential(const double cutoff = 2.5)\n      : _cutoff(cutoff), _rc2(_cutoff * _cutoff),\n        _rc6(_rc2 * _rc2 * _rc2), _rc7(_rc6 * _cutoff), _rc12(_rc6 * _rc6),\n        _rc13(_rc6 * _rc7) {}\n\n  virtual ~abstract_LJ_cutoff_potential() = 0;\n\n  /*! \\brief Get cutoff radius\n   *\n   * \\return            Cutoff radius\n   */\n  inline double cutoff() const { return _cutoff; }\n\nprivate:\n  virtual double _U(const metropolis &sim) const;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &rn_j) const;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t i, \n                             const size_t j) const;\n\n  double _cutoff;\n\n  double _rc2;\n  double _rc6;\n  double _rc7;\n  double _rc12;\n  double _rc13;\n};\n\n/*! \\brief 6-12 Lennard-Jones pairwise potential\n *\n * Lennard-Jones potential with cutoff to be used in a simulation where the \n * parameters between every pair of molecules is loaded from a YAML file\n * and looked up at runtime.\n */\nclass LJ_cutoff_potential : public abstract_LJ_lookup_potential, \n                            public abstract_LJ_cutoff_potential {\npublic:\n  /*! \\brief Constructor for LJ potential where well parameters are looked up\n   *\n   * \\param       fname     Filename to well parameter data\n   * \\param       cutoff    Cutoff radius\n   * \\return                LJ potential with well parameter lookup\n   */\n  LJ_cutoff_potential(const char *fname, const double cutoff = 2.5) \n    : abstract_LJ_lookup_potential(fname), abstract_LJ_cutoff_potential(cutoff) \n      {}\n};\n\n/*! \\brief 6-12 Lennard-Jones pairwise potential with a cutoff radius\n *\n * Lennard-Jones potential to be used in a simulation where the potential\n * function between every pair of molecules is the same (i.e. to be used in\n * a simulation where all of the molecules are of the same type).\n */\nclass const_well_params_LJ_cutoff_potential\n    : public abstract_LJ_cutoff_potential {\npublic:\n  /*! \\brief Constructor for a LJ potential with constant well parameters\n   *\n   * \\param    well_depth    Depth of the potential well\n   * \\param    rzero         Finite distance at which potential is zero\n   * \\return                 LJ potential\n   */\n  const_well_params_LJ_cutoff_potential(const double well_depth,\n                                        const double rzero,\n                                        const double cutoff = 2.5)\n      : abstract_LJ_cutoff_potential(cutoff),\n        _well_depth(well_depth), _rzero(rzero) {}\n\n  ~const_well_params_LJ_cutoff_potential() {}\n\nprivate:\n  virtual double _get_well_depth(molecular_id, molecular_id) const {\n    return _well_depth;\n  }\n\n  virtual double _get_rzero(molecular_id, molecular_id) const { return _rzero; }\n\n  double _well_depth;\n  double _rzero;\n};\n\n/*! \\brief Public interface for a spring potential\n */\nclass abstract_spring_potential : public abstract_potential {\npublic:\n  virtual ~abstract_spring_potential() = 0;\n\n  /*! \\brief Get the spring constant\n   *\n   * \\param    id    Molecular id of the molecule\n   * \\return         Spring constant\n   */\n  inline double get_k(molecular_id id) const { return _get_k(id); }\n\nprivate:\n  virtual double _U(const metropolis &sim) const;\n  virtual double  _delta_U(const metropolis &sim, const size_t j, \n                           arma::vec &rn_j) const;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t, \n                             const size_t) const;\n\n  virtual double _get_k(molecular_id) const = 0;\n};\n\n/*! \\brief Potential due to a spring with constant k\n *\n * Potential due to a spring in which the spring constant, k, is the same\n * for all molecules, regardless of molecular id.\n * k should always be greater than 0.\n */\nclass const_k_spring_potential : public abstract_spring_potential {\npublic:\n  /*! \\brief Constructor for potential with same spring constant for all\n   * molecules\n   *\n   * Constructor for potential with same spring constant for all molecules.\n   * Requires: k > 0\n   *\n   * \\param    k     Spring constant\n   * \\return         Spring potential\n   */\n  const_k_spring_potential(const double k) : _k(k) {}\n\n  virtual ~const_k_spring_potential() {}\n\nprivate:\n  virtual double _get_k(molecular_id) const { return _k; }\n\n  double _k;\n};\n\n/*! \\brief Potential due to a quadratic spring with constant parameters\n *\n * Potential due to a spring in which the spring parameters are the same\n * for all molecules, regardless of molecular id.\n */\nclass const_quad_spring_potential : public abstract_potential {\npublic:\n  /*! \\brief Constructor for potential with same spring parameters for all\n   * molecules\n   *\n   * Constructor for potential with same spring constant for all molecules.\n   *\n   * \\param    k     Spring constant\n   * \\return         Spring potential\n   */\n  const_quad_spring_potential(const double a, const double b, const double c)\n      : a(a), b(b), c(c) {}\n\n  virtual ~const_quad_spring_potential() {}\n\nprivate:\n  virtual double _U(const metropolis &sim) const;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &rn_j) const;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t, \n                             const size_t) const;\n\n  double a;\n  double b;\n  double c;\n};\n\n/*! \\brief Potential due to a spring with a polynomial potential\n *\n * Potential due to a spring in which the potential, a x^n + b x^-1 + ...,\n * is the same for all molecules, regardless of molecular id.\n */\nclass const_poly_spring_potential : public abstract_potential {\npublic:\n  /*! \\brief Constructor for potential with same spring potential for all\n   * molecules\n   *\n   * Constructor for potential with same spring constant for all molecules.\n   *\n   * \\param    coeffs   Polynomial coefficients\n   * \\return            Spring potential\n   */\n  const_poly_spring_potential(const std::initializer_list<double> &coeffs);\n\n  virtual ~const_poly_spring_potential() {}\n\nprivate:\n  virtual double _U(const metropolis &sim) const;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &rn_j) const;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t, \n                             const size_t) const;\n\n  std::vector<double> pcoeffs;\n  std::vector<double> fcoeffs;\n};\n\n/*! \\brief Two state potential with interactions between molecules\n */\nclass twostate_int_potential : public abstract_potential {\npublic:\n  /*! Constructor for two state potential with interactions\n   *\n   * \\param     gamma     Potential energy of state 1\n   * \\param     mu        Potential energy of state 2\n   * \\return              Two state potential with interactions\n   */\n  twostate_int_potential(const double gamma, const double mu) {\n    _Us[0] = gamma;\n    _Us[1] = mu;\n  }\n\nprivate:\n  std::array<double, 2> _Us;\n\n  double _U(const metropolis &sim) const;\n  double _delta_U(const metropolis &sim, const size_t j, \n                  arma::vec &rn_j) const;\n  inline double _Ui(const arma::vec &x) const {\n    return _Us[static_cast<unsigned>(x(0))];\n  }\n  inline bool _check_x(const arma::vec &x) const {\n    return (static_cast<unsigned>(x(0)) == 0 ||\n            static_cast<unsigned>(x(0)) == 1);\n  }\n  arma::vec _forceij(const metropolis &sim, const size_t, const size_t) const;\n};\n\n/*! \\brief Potential of a dipole in an electric field\n */\nclass dipole_electric_potential : public abstract_potential {\npublic:\n  /*! \\brief Potential of a dipole in a (constant) electric field\n   *\n   * \\param   E0        Magnitude of electric field\n   * \\param   dof_idx   Index of the degree of freedom of the E field\n   * \\return            Potential of a dipole in a (constant) electric field\n   */\n  dipole_electric_potential(const double E0, const unsigned dof_idx = 2) {\n    _efield[dof_idx] = [E0](const arma::vec&) { return E0; };\n  }\n\n  /*! \\brief Potential of a dipole in a (constant) electric field\n   *\n   * \\param   E0        Magnitude of electric field\n   * \\param   dof_idx   Index of the degree of freedom of the E field\n   * \\return            Potential of a dipole in a (constant) electric field\n   */\n  dipole_electric_potential(const std::initializer_list<double> Es, \n                            const std::initializer_list<unsigned> dof_idxs) {\n    if (Es.size() != dof_idxs.size()) \n      throw std::invalid_argument(\"E field function list and dof list should \"\n                                  \"be of the same length\");\n\n    for(auto tup : boost::combine(dof_idxs, Es)) {\n      unsigned idx;\n      double E;\n      boost::tie(idx, E) = tup;\n      _efield[idx] = [E](const arma::vec&) { return E; };\n    }\n  }\n\n  /*! \\brief Potential of a dipole in an electric field\n   *\n   * \\param   Es        Components of electric field\n   * \\param   dox_idxs  Indexes of the degree of freedom of the E field\n   * \\return            Potential of a dipole in an electric field\n   */\n  dipole_electric_potential(std::initializer_list<\n      std::function<double(const arma::vec&)> > Es, \n      std::initializer_list<unsigned> dof_idxs) {\n\n    if (Es.size() != dof_idxs.size()) \n      throw std::invalid_argument(\"E field function list and dof list should \"\n                                  \"be of the same length\");\n\n    for(auto tup : boost::combine(dof_idxs, Es)) \n      _efield[boost::get<0>(tup)] = boost::get<1>(tup); \n\n  }\n\nprivate:\n  virtual double _U(const metropolis &sim) const;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &dx) const;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t i, \n                             const size_t j) const;\n\n  std::map<unsigned, std::function<double(const arma::vec&)>> _efield;\n};\n\n/*! \\brief Potential of a dipole in an electric field\n */\nclass abstract_dipole_strain_potential : public abstract_potential {\npublic:\n  virtual ~abstract_dipole_strain_potential() = 0;\n\n  /*! \\brief Inverse of the susceptibility tensor\n   *\n   * \\param   xs    Degrees of freedom of dipole\n   * \\param   id    Molecular id of the particle\n   * \\return        Inverse susceptibility\n   */\n  inline arma::mat inv_chi(const arma::vec& xs, const molecular_id id) const {\n    return _inv_chi(xs, id);\n  }\n\n  /*! \\brief Polarization vector\n   *\n   * \\param   xs    Degrees of freedom of dipole\n   * \\return        Polarization vector\n   */\n  inline arma::vec p(const arma::vec& xs) const {\n    return _p(xs);\n  }\n\nprivate:\n  virtual double _U(const metropolis &sim) const;\n  virtual double _delta_U(const metropolis &sim, const size_t j, \n                          arma::vec &dx) const;\n  virtual arma::vec _forceij(const metropolis &sim, const size_t, \n                             const size_t) const;\n  virtual arma::mat _inv_chi(const arma::vec& xs, \n                             const molecular_id id) const = 0;\n  virtual arma::vec _p(const arma::vec& xs) const = 0;\n};\n\n/*! \\brief Dipole in 2D space\n */\nclass abstract_dipole_strain_2d_potential : \n  virtual public abstract_dipole_strain_potential {\npublic:\n  virtual ~abstract_dipole_strain_2d_potential()=0;\nprivate:\n  arma::vec _p(const arma::vec& xs) const {\n    return arma::vec(xs.memptr(), 2);\n  }\n};\n\n/*! \\brief Dipole in 3D space\n */\nclass abstract_dipole_strain_3d_potential :\n  virtual public abstract_dipole_strain_potential {\npublic:\n  virtual ~abstract_dipole_strain_3d_potential()=0;\nprivate:\n  arma::vec _p(const arma::vec& xs) const {\n    return arma::vec(xs.memptr(), 3);\n  }\n};\n\n/*! \\brief Dipole whose susceptibility does not depend on space, direction, etc.\n */\nclass abstract_dipole_strain_linear_potential :\n  virtual public abstract_dipole_strain_potential {\npublic:\n  virtual ~abstract_dipole_strain_linear_potential()=0;\n\n  abstract_dipole_strain_linear_potential(const arma::mat& inv_chi) \n    : _const_inv_chi(inv_chi) {}\n\nprivate:\n  arma::mat _inv_chi(const arma::vec&, const molecular_id) const {\n    return _const_inv_chi;\n  }\n\n  arma::mat _const_inv_chi;\n};\n\n/*! \\brief Dipole, in 2D space, whose susceptibility tensor is linear\n */\nclass dipole_strain_linear_2d_potential :\n  public abstract_dipole_strain_2d_potential,\n  public abstract_dipole_strain_linear_potential {\npublic:\n  virtual ~dipole_strain_linear_2d_potential() {}\n\n  dipole_strain_linear_2d_potential(const arma::mat& inv_chi)\n    : abstract_dipole_strain_linear_potential(inv_chi) {}\n};\n\n/*! \\brief Dipole, in 3D space, whose susceptibility tensor is linear\n */\nclass dipole_strain_linear_3d_potential :\n  public abstract_dipole_strain_3d_potential,\n  public abstract_dipole_strain_linear_potential {\npublic:\n  virtual ~dipole_strain_linear_3d_potential() {}\n\n  dipole_strain_linear_3d_potential(const arma::mat& inv_chi)\n    : abstract_dipole_strain_linear_potential(inv_chi) {}\n};\n\n/*! \\brief Dipole, in 2D space, whose susceptibility tensor is nonlinear\n */\nclass dipole_strain_nonlinear_2d_potential : \n  public abstract_dipole_strain_2d_potential {\npublic:\n  virtual ~dipole_strain_nonlinear_2d_potential() {}\n\n  dipole_strain_nonlinear_2d_potential(std::function<arma::mat(const arma::vec&,\n    const molecular_id)> inv_chi_f) : _inv_chi_f(inv_chi_f) {}\nprivate:\n  arma::mat _inv_chi(const arma::vec& xs, const molecular_id id) const {\n    const double theta = xs(2);\n    arma::vec n({std::cos(theta), std::sin(theta)});\n    return _inv_chi_f(n, id);\n  }\n\n  std::function<arma::mat(const arma::vec&, const molecular_id)> _inv_chi_f;\n};\n\n/*! \\brief Dipole, in 3D space, whose susceptibility tensor is nonlinear\n */\nclass dipole_strain_nonlinear_3d_potential : \n  public abstract_dipole_strain_3d_potential {\npublic:\n  virtual ~dipole_strain_nonlinear_3d_potential() {}\n\n  dipole_strain_nonlinear_3d_potential(std::function<arma::mat(const arma::vec&,\n    const molecular_id)> inv_chi_f) : _inv_chi_f(inv_chi_f) {}\nprivate:\n  arma::mat _inv_chi(const arma::vec& xs, const molecular_id id) const {\n    const double phi = xs(3);\n    const double theta = xs(4);\n    const double cp = std::cos(phi);\n    const double sp = std::sin(phi);\n    const double ct = std::cos(theta);\n    const double st = std::sin(theta);\n    arma::vec n({cp * st, sp * st, ct});\n    return _inv_chi_f(n, id);\n  }\n\n  std::function<arma::mat(const arma::vec&, const molecular_id)> _inv_chi_f;\n};\n\n} // namespace pauth\n\n#endif\n", "meta": {"hexsha": "5791623c0558505ad99bd0ade720be9b22f287ec", "size": 21799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/potentials.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/potentials.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/potentials.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": 33.4854070661, "max_line_length": 80, "alphanum_fraction": 0.676636543, "num_tokens": 5472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05184546262100774, "lm_q1q2_score": 0.02592273131050387}}
{"text": "#pragma once\n#include \"spn_math.hpp\"\n#include <type_traits>\n#include <boost/serialization/access.hpp>\n#include <boost/serialization/nvp.hpp>\n#include \"serialization/traits.hpp\"\n#include \"../random/rotation.hpp\"\n\nnamespace spn {\n\t// Degree角度を示すタグ構造体\n\tstruct Degree_t {};\n\t// Radian角度を示すタグ構造体\n\tstruct Radian_t {};\n\n\t//! 角度変換ヘルパークラス\n\ttemplate <class From, class To>\n\tstruct ConvertAngle;\n\t// 同じ単位なので変換の必要なし\n\ttemplate <class TAG>\n\tstruct ConvertAngle<TAG, TAG> {\n\t\ttemplate <class T>\n\t\tT operator()(T ang) const {\n\t\t\treturn ang;\n\t\t}\n\t};\n\ttemplate <>\n\tstruct ConvertAngle<Degree_t, Radian_t> {\n\t\ttemplate <class T>\n\t\tT operator()(T deg) const {\n\t\t\treturn deg / 180 * Pi<T>;\n\t\t}\n\t};\n\ttemplate <>\n\tstruct ConvertAngle<Radian_t, Degree_t> {\n\t\ttemplate <class T>\n\t\tT operator()(T rad) const {\n\t\t\treturn rad / Pi<T> * 180;\n\t\t}\n\t};\n\n\ttemplate <class TAG>\n\tstruct AngleInfo;\n\ttemplate <>\n\tstruct AngleInfo<Degree_t> {\n\t\ttemplate <class T>\n\t\tconstexpr static T onerotation = T(360);\n\t\tconst static char *name,\n\t\t\t\t\t\t\t*name_short;\n\t};\n\ttemplate <>\n\tstruct AngleInfo<Radian_t> {\n\t\ttemplate <class T>\n\t\tconstexpr static T onerotation = T(2*Pi<T>);\n\t\tconst static char *name,\n\t\t\t\t\t\t\t*name_short;\n\t};\n\n\t//! 角度クラス\n\t/*! 混同を避けるために数値への変換は明示的\n\t\t他形式との変換は暗黙的 */\n\ttemplate <class TAG, class V>\n\tclass Angle {\n\t\tprivate:\n\t\t\tusing tag_type = TAG;\n\t\t\tusing value_type = V;\n\t\t\tvalue_type\t_angle;\n\n\t\t\tfriend class boost::serialization::access;\n\t\t\ttemplate <class Ar>\n\t\t\tvoid serialize(Ar& ar, const unsigned int /*ver*/) {\n\t\t\t\tar & BOOST_SERIALIZATION_NVP(_angle);\n\t\t\t}\n\t\tpublic:\n\t\t\tconstexpr static value_type OneRotationAng = AngleInfo<tag_type>::template onerotation<value_type>;\n\t\t\tAngle() = default;\n\t\t\t//! Degreeで角度指定\n\t\t\ttemplate <class TAG2, class V2>\n\t\t\tAngle(const Angle<TAG2,V2>& ang) {\n\t\t\t\t_angle = ConvertAngle<TAG2, TAG>()(ang.get());\n\t\t\t}\n\t\t\t//! floatで直接角度指定\n\t\t\texplicit constexpr Angle(value_type ang):\n\t\t\t\t_angle(ang)\n\t\t\t{}\n\t\t\tconstexpr static Angle Rotation(value_type r=value_type(1)) {\n\t\t\t\treturn Angle(OneRotationAng * r);\n\t\t\t}\n\t\t\tAngle& operator = (const Angle& ang) = default;\n\t\t\ttemplate <class TAG2, class V2>\n\t\t\tAngle& operator = (const Angle<TAG2,V2>& ang) {\n\t\t\t\t_angle = Angle(ang).get();\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\t// 浮動少数点数型なら明示的に角度を出力\n\t\t\ttemplate <class T2, class=std::enable_if_t<std::is_floating_point<T2>::value>>\n\t\t\texplicit operator T2() const {\n\t\t\t\treturn _angle;\n\t\t\t}\n\t\t\ttemplate <class TAG2, class V2=value_type>\n\t\t\tAngle<TAG2,V2> convert() const {\n\t\t\t\treturn Angle<TAG2,V2>(*this);\n\t\t\t}\n\t\t\tvoid set(value_type ang) {\n\t\t\t\t_angle = ang;\n\t\t\t}\n\t\t\tvalue_type get() const {\n\t\t\t\treturn _angle;\n\t\t\t}\n\t\t\t//! 角度をループ(0から2Piの間に収める)\n\t\t\tvoid single() {\n\t\t\t\tauto ang = std::fmod(_angle, OneRotationAng);\n\t\t\t\tif(ang < 0)\n\t\t\t\t\tang += OneRotationAng;\n\t\t\t\t_angle = ang;\n\t\t\t}\n\t\t\tvoid rangeValue(V low, V high) {\n\t\t\t\tif(_angle < low)\n\t\t\t\t\t_angle = low;\n\t\t\t\telse if(_angle > high)\n\t\t\t\t\t_angle = high;\n\t\t\t}\n\t\t\t//! 角度に制限をつける\n\t\t\tvoid range(const Angle& low, const Angle& high) {\n\t\t\t\tif(_angle < low.get())\n\t\t\t\t\t_angle = low.get();\n\t\t\t\telse if(_angle > high.get())\n\t\t\t\t\t_angle = high.get();\n\t\t\t}\n\n\t\t\ttemplate <class TAG2, class V2>\n\t\t\tAngle operator + (const Angle<TAG2,V2>& ang) const {\n\t\t\t\treturn Angle(_angle + Angle(ang).get());\n\t\t\t}\n\t\t\ttemplate <class TAG2, class V2>\n\t\t\tAngle& operator += (const Angle<TAG2,V2>& ang) {\n\t\t\t\t_angle += Angle(ang).get();\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class TAG2, class V2>\n\t\t\tAngle operator - (const Angle<TAG2,V2>& ang) const {\n\t\t\t\treturn Angle(_angle - Angle(ang).get());\n\t\t\t}\n\t\t\ttemplate <class TAG2, class V2>\n\t\t\tAngle& operator -= (const Angle<TAG2,V2>& ang) {\n\t\t\t\t_angle -= Angle(ang).get();\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tAngle operator * (value_type r) const {\n\t\t\t\treturn Angle(_angle * r);\n\t\t\t}\n\t\t\tAngle& operator *= (value_type r) {\n\t\t\t\t_angle *= r;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tAngle operator / (value_type r) const {\n\t\t\t\treturn Angle(_angle / r);\n\t\t\t}\n\t\t\tAngle& operator /= (value_type r) {\n\t\t\t\t_angle /= r;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tAngle operator -() const {\n\t\t\t\treturn Angle(-_angle);\n\t\t\t}\n\t\t\ttemplate <class... Ts>\n\t\t\tstatic Angle Random(Ts&&... ts) {\n\t\t\t\treturn random::GenRAngle<Angle>(std::forward<Ts>(ts)...);\n\t\t\t}\n\n\t\t\t// ---- 比較演算子の定義 ----\n\t\t\t#define DEF_ANGLE_OPERATOR(op) \\\n\t\t\t\ttemplate <class TAG2, class V2> \\\n\t\t\t\tbool operator op (const Angle<TAG2,V2>& ang) const { \\\n\t\t\t\t\treturn _angle op Angle(ang).get(); \\\n\t\t\t\t}\n\t\t\tDEF_ANGLE_OPERATOR(==)\n\t\t\tDEF_ANGLE_OPERATOR(!=)\n\t\t\tDEF_ANGLE_OPERATOR(<)\n\t\t\tDEF_ANGLE_OPERATOR(<=)\n\t\t\tDEF_ANGLE_OPERATOR(>)\n\t\t\tDEF_ANGLE_OPERATOR(>=)\n\t\t\t#undef DEF_ANGLE_OPERATOR\n\n\t\t\t// -------- Luaへのエクスポート用 --------\n\t\t\tusing Deg_t = Angle<Degree_t, value_type>;\n\t\t\tusing Rad_t = Angle<Radian_t, value_type>;\n\t\t\tAngle luaAddD(const Deg_t& a) const {\n\t\t\t\treturn *this + a;\n\t\t\t}\n\t\t\tAngle luaAddR(const Rad_t& a) const {\n\t\t\t\treturn *this + a;\n\t\t\t}\n\t\t\tAngle luaSubD(const Deg_t& a) const {\n\t\t\t\treturn *this - a;\n\t\t\t}\n\t\t\tAngle luaSubR(const Rad_t& a) const {\n\t\t\t\treturn *this - a;\n\t\t\t}\n\t\t\tDeg_t luaToDegree() const {\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tRad_t luaToRadian() const {\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tAngle luaMulF(float s) const {\n\t\t\t\treturn *this * s;\n\t\t\t}\n\t\t\tAngle luaDivF(float s) const {\n\t\t\t\treturn *this / s;\n\t\t\t}\n\t\t\tAngle luaInvert() const {\n\t\t\t\treturn -*this;\n\t\t\t}\n\t\t\tbool luaLessthan(const Angle& a) const {\n\t\t\t\treturn *this < a;\n\t\t\t}\n\t\t\tbool luaLessequal(const Angle& a) const {\n\t\t\t\treturn *this <= a;\n\t\t\t}\n\t\t\tbool luaEqual(const Angle& a) const {\n\t\t\t\treturn *this == a;\n\t\t\t}\n\t\t\tstd::string luaToString() const {\n\t\t\t\treturn ToString(*this);\n\t\t\t}\n\t};\n\n\ttemplate <class T>\n\tusing Degree = Angle<Degree_t, T>;\n\tusing DegF = Degree<float>;\n\tusing DegD = Degree<double>;\n\ttemplate <class T>\n\tusing Radian = Angle<Radian_t, T>;\n\tusing RadF = Radian<float>;\n\tusing RadD = Radian<double>;\n\n\ttemplate <class TAG, class V>\n\tstd::ostream& operator << (std::ostream& os, const Angle<TAG,V>& ang) {\n\t\treturn os << ang.get() << \"(\" << AngleInfo<TAG>::name_short << \")\";\n\t}\n}\nBOOST_CLASS_IMPLEMENTATION_TEMPLATE((class)(class), spn::Angle, object_serializable)\nBOOST_CLASS_TRACKING_TEMPLATE((class)(class), spn::Angle, track_never)\n\n// ------------- Angle系関数 -------------\nnamespace spn {\n\ttemplate <int N, bool A>\n\tstruct VecT;\n\tusing Vec2 = VecT<2,false>;\n\n\t//! dirAを基準に反時計回りに増加する値を返す\n\t/*! \\param[in] dir 値を算出したい単位ベクトル\n\t\t\\param[in] dirA 基準の単位ベクトル\n\t\t\\return 角度に応じた0〜4の値(一様ではない) */\n\tfloat AngleValueNL(const Vec2& dir, const Vec2& dirA);\n\t//! 上方向を基準としたdirの角度を返す(半時計周り)\n\t/*! \\return 0〜2*PI未満の角度値 */\n\tRadF AngleValue(const Vec2& dir);\n\t//! ang0,ang1における-oneloop以上oneloop未満の差分角度値を計算\n\tfloat AngleLerpValueDiff(float ang0, float ang1, const float oneloop);\n\ttemplate <class Proc>\n\tfloat AngleLerpValue(float ang0, float ang1, const Proc& proc, const float oneloop) {\n\t\tauto diff = AngleLerpValueDiff(ang0, ang1, oneloop);\n\t\treturn ang0 + proc(diff);\n\t}\n\t//! 上方向を0度とし、反時計回り方向に指定角度回転したベクトルを返す\n\tVec2 VectorFromAngle(const RadF& ang);\n\t//! 2つの角度値をang0 -> ang1の線形補間\n\ttemplate <class T>\n\tT AngleLerp(const T& ang0, const T& ang1, float r) {\n\t\tauto fn = [r](auto&& v){ return v*r; };\n\t\treturn T(AngleLerpValue(ang0.get(), ang1.get(), fn, T::OneRotationAng));\n\t}\n\t//! ang0からang1へ向けてmaxDiff以下の分だけ近づける\n\ttemplate <class T>\n\tT AngleMove(const T& ang0, const T& ang1, const T& maxDiff) {\n\t\tauto fn = [mdiff = maxDiff.get()](auto&& v) {\n\t\t\tif(std::abs(v) > mdiff)\n\t\t\t\treturn (v > 0) ? mdiff : -mdiff;\n\t\t\treturn decltype(mdiff)(v);\n\t\t};\n\t\treturn T(AngleLerpValue(ang0.get(), ang1.get(), fn, T::OneRotationAng));\n\t}\n}\n", "meta": {"hexsha": "425c2edae7a9ebedfd68bf8d16a817d2a6721458", "size": 7445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "structure/angle.hpp", "max_stars_repo_name": "degarashi/spinner", "max_stars_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "structure/angle.hpp", "max_issues_repo_name": "degarashi/spinner", "max_issues_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "structure/angle.hpp", "max_forks_repo_name": "degarashi/spinner", "max_forks_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_forks_repo_licenses": ["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.0314685315, "max_line_length": 102, "alphanum_fraction": 0.6394895903, "num_tokens": 2536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.053403333942835626, "lm_q1q2_score": 0.02586751139590266}}
{"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_PROBLEMS_THERMALBLOCK_HH\n#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH\n\n#include <memory>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/static_assert.hh>\n#include <dune/common/timer.hh>\n#include <dune/common/typetraits.hh>\n\n#if HAVE_DUNE_GRID_MULTISCALE\n# include <dune/grid/multiscale/provider/cube.hh>\n#endif\n\n#include <dune/stuff/common/memory.hh>\n#include <dune/stuff/common/string.hh>\n#include <dune/stuff/functions/constant.hh>\n#include <dune/stuff/functions/expression.hh>\n#include <dune/stuff/playground/functions/indicator.hh>\n#include <dune/stuff/grid/provider/cube.hh>\n#include <dune/stuff/grid/boundaryinfo.hh>\n\n#include <dune/pymor/functions/default.hh>\n#include <dune/pymor/functions/checkerboard.hh>\n\n#include \"default.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Problems {\n\n\ntemplate< class E, class D, int d, class R, int r = 1 >\nclass Thermalblock\n  : public ProblemInterface< E, D, d, R, r >\n{\n  Thermalblock() { static_assert(AlwaysFalse< E >::value, \"Not available for these dimensions!\"); }\n};\n\n\ntemplate< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n  : public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\n  typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n  typedef Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n\npublic:\n  typedef Pymor::Functions::Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n      CheckerboardFunctionType;\n  using typename BaseType::DiffusionTensorType;\n  using typename BaseType::FunctionType;\n\n  static const bool available = true;\n\n  static std::string static_id()\n  {\n    return BaseType::BaseType::static_id() + \".thermalblock\";\n  }\n\n  static Stuff::Common::Configuration default_config(const std::string sub_name = \"\")\n  {\n    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n        ConstantFunctionType;\n    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >\n        ConstantMatrixFunctionType;\n    Stuff::Common::Configuration config;\n    config[\"type\"] = static_id();\n    Stuff::Common::Configuration checkerboard_config = CheckerboardFunctionType::default_config();\n    checkerboard_config[\"name\"] = \"diffusion_factor\";\n    checkerboard_config[\"type\"] = CheckerboardFunctionType::static_id();\n    checkerboard_config[\"num_elements\"] = \"[4 4 4]\";\n    checkerboard_config[\"parameter_name\"] = \"diffusion\";\n    config.add(checkerboard_config, \"diffusion_factor\");\n    Stuff::Common::Configuration diffusion_tensor_config = ConstantMatrixFunctionType::default_config();\n    diffusion_tensor_config[\"name\"] = \"diffusion_tensor\";\n    diffusion_tensor_config[\"type\"] = ConstantMatrixFunctionType::static_id();\n    config.add(diffusion_tensor_config, \"diffusion_tensor\");\n    Stuff::Common::Configuration constant_config = ConstantFunctionType::default_config();\n    constant_config[\"type\"] = ConstantFunctionType::static_id();\n    constant_config[\"name\"] = \"force\";\n    constant_config[\"value\"] = \"1\";\n    config.add(constant_config, \"force\");\n    constant_config[\"name\"] = \"dirichlet\";\n    constant_config[\"value\"] = \"0\";\n    config.add(constant_config, \"dirichlet\");\n    constant_config[\"name\"] = \"neumann\";\n    config.add(constant_config, \"neumann\");\n    if (sub_name.empty())\n      return config;\n    else {\n      Stuff::Common::Configuration tmp;\n      tmp.add(config, sub_name);\n      return tmp;\n    }\n  } // ... default_config(...)\n\n  static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),\n                                            const std::string sub_name = static_id())\n  {\n    const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n    std::shared_ptr< CheckerboardFunctionType >\n        checkerboard_function(CheckerboardFunctionType::create(cfg.sub(\"diffusion_factor\")));\n    return Stuff::Common::make_unique< ThisType >(checkerboard_function,\n                                                  BaseType::create_matrix_function(\"diffusion_tensor\", cfg),\n                                                  BaseType::create_vector_function(\"force\", cfg),\n                                                  BaseType::create_vector_function(\"dirichlet\", cfg),\n                                                  BaseType::create_vector_function(\"neumann\", cfg));\n  } // ... create(...)\n\n  Thermalblock(const std::shared_ptr< const CheckerboardFunctionType >& checkerboard_function,\n               const std::shared_ptr< const DiffusionTensorType >& diffusion_tensor,\n               const std::shared_ptr< const FunctionType >& force,\n               const std::shared_ptr< const FunctionType >& dirichlet,\n               const std::shared_ptr< const FunctionType >& neumann)\n    : BaseType(checkerboard_function, diffusion_tensor, force, dirichlet, neumann)\n  {}\n\n  virtual std::string type() const override\n  {\n    return BaseType::BaseType::static_id() + \".thermalblock\";\n  }\n}; // class Thermalblock< ..., 1 >\n\n\ntemplate< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim = 1 >\nclass LocalThermalblock\n{\n  static_assert(AlwaysFalse< EntityImp >::value, \"Not available for dimRange > 1!\");\n};\n\n\ntemplate< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass LocalThermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n  : public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\n  typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n  typedef LocalThermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n\n  typedef Pymor::Functions::AffinelyDecomposableDefault< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n      AffinelyDecomposableDefaultFunctionType;\n  typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >\n      ConstantMatrixFunctionType;\npublic:\n  using typename BaseType::FunctionType;\n\n  static std::string static_id()\n  {\n    return BaseType::BaseType::static_id() + \".localthermalblock\";\n  }\n\n  static Stuff::Common::Configuration default_config(const std::string sub_name = \"\")\n  {\n    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >\n        ConstantFunctionType;\n    Stuff::Common::Configuration config;\n    Stuff::Common::Configuration constant_config = ConstantFunctionType::default_config();\n    constant_config[\"type\"] = ConstantFunctionType::static_id();\n    constant_config[\"name\"] = \"force\";\n    constant_config[\"value\"] = \"1\";\n    config.add(constant_config, \"force\");\n    constant_config[\"name\"] = \"dirichlet\";\n    constant_config[\"value\"] = \"0\";\n    config.add(constant_config, \"dirichlet\");\n    constant_config[\"name\"] = \"neumann\";\n    config.add(constant_config, \"neumann\");\n    if (sub_name.empty())\n      return config;\n    else {\n      Stuff::Common::Configuration tmp;\n      tmp.add(config, sub_name);\n      return tmp;\n    }\n  } // ... default_config(...)\n\n  static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),\n                                            const std::string sub_name = static_id())\n  {\n    const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n    return Stuff::Common::make_unique< ThisType >(BaseType::create_vector_function(\"force\", cfg),\n                                                  BaseType::create_vector_function(\"dirichlet\", cfg),\n                                                  BaseType::create_vector_function(\"neumann\", cfg));\n  } // ... create(...)\n\n  LocalThermalblock(const std::shared_ptr< const FunctionType >& force,\n                    const std::shared_ptr< const FunctionType >& dirichlet,\n                    const std::shared_ptr< const FunctionType >& neumann)\n    : BaseType(create_diffusion_factor(),\n               create_diffusion_tensor(),\n               force,\n               dirichlet,\n               neumann)\n  {}\n\n  virtual std::string type() const override\n  {\n    return BaseType::BaseType::static_id() + \".localthermalblock\";\n  }\n\nprivate:\n  static std::shared_ptr< AffinelyDecomposableDefaultFunctionType > create_diffusion_factor()\n  {\n    typedef Stuff::Functions::DomainIndicator< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > IndicatorFunctionType;\n    const Pymor::ParameterType mu(\"diffusion\", 3);\n\n    auto ret = std::make_shared< AffinelyDecomposableDefaultFunctionType >(\"diffusion_factor\");\n    ret->register_component(new IndicatorFunctionType({{{{0.0, 0.0}, {0.5, 0.16}}, 1.0},\n                                                       {{{0.0, 0.16}, {0.16, 0.33}}, 1.0},\n                                                       {{{0.33, 0.16}, {0.5, 0.33}}, 1.0},\n                                                       {{{0.0, 0.33}, {0.5, 1.0}}, 1.0}},\n                                                      \"left_block\"),\n                            new Pymor::ParameterFunctional(mu, \"diffusion_factor[0]\"));\n    ret->register_component(new IndicatorFunctionType({{{{0.5, 0.0}, {1.0, 1.0}}, 1.0}},\n                                                      \"right_block\"),\n                            new Pymor::ParameterFunctional(mu, \"diffusion_factor[1]\"));\n    ret->register_component(new IndicatorFunctionType({{{{0.16, 0.16}, {0.33, 0.33}}, 1.0}},\n                                                      \"small_block\"),\n                            new Pymor::ParameterFunctional(mu, \"diffusion_factor[2]\"));\n    return ret;\n  } // ... create_diffusion_factor()\n\n  typedef Pymor::Functions::NonparametricDefault\n      < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim > NonparametricFunctionType;\n\n  static std::shared_ptr< NonparametricFunctionType > create_diffusion_tensor()\n  {\n    Stuff::Common::Configuration diffusion_tensor_config = ConstantMatrixFunctionType::default_config();\n    diffusion_tensor_config[\"name\"] = \"diffusion_tensor\";\n    return std::make_shared< NonparametricFunctionType >(ConstantMatrixFunctionType::create(diffusion_tensor_config));\n  } // ... create_diffusion_tensor()\n}; // class LocalThermalblock< ..., 1 >\n\n\n} // namespace Problems\n} // namespace LinearElliptic\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH\n", "meta": {"hexsha": "ffa67de7e414e982bbd7392d7eb0ef4f0f39e822", "size": 10894, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/problems/thermalblock.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/problems/thermalblock.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/problems/thermalblock.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.1052631579, "max_line_length": 126, "alphanum_fraction": 0.6736735818, "num_tokens": 2533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.06465349376296874, "lm_q1q2_score": 0.025849219420932636}}
{"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_REDUCTION_INCLUDE\n#define MTL_REDUCTION_INCLUDE\n\n#include <boost/mpl/bool.hpp>\n#include <boost/numeric/meta_math/loop1.hpp>\n#include <boost/numeric/mtl/utility/omp_size_type.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n\nnamespace mtl { namespace vec {\n\n\n    namespace impl {\n\t\n\ttemplate <unsigned long Index0, unsigned long Max0, typename Functor>\n\tstruct reduction\n\t{\n\t    typedef reduction<Index0+1, Max0, Functor>     next;\n\n\t    template <typename Value>\n\t    static inline void init(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, \n\t\t\t\t    Value& tmp05, Value& tmp06, Value& tmp07)\n\t    {\n\t\tFunctor::init(tmp00);\n\t\tnext::init(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00);\n\t    }\n\n\t    template <typename Value, typename Vector, typename Size>\n\t    static inline void update(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, \n\t\t\t\t      Value& tmp05, Value& tmp06, Value& tmp07, const Vector& v, Size i)\n\t    {\n\t\tFunctor::update(tmp00, v[ i + Index0-1 ]);\n\t\tnext::update(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00, v, i);\n\t    }\n\n\t    template <typename Value>\n\t    static inline void finish(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, \n\t\t\t\t    Value& tmp05, Value& tmp06, Value& tmp07)\n\t    {\n\t\tnext::finish(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00);\n\t\tFunctor::finish(tmp00, tmp01);\n\t    }\n\t};\n\n\ttemplate <unsigned long Max0, typename Functor>\n\tstruct reduction<Max0, Max0, Functor>\n\t{\n\t    template <typename Value>\n\t    static inline void init(Value& tmp00, Value&, Value&, Value&, Value&, Value&, Value&, Value&)\n\t    {\n\t\tFunctor::init(tmp00);\n\t    }\n\n\t    template <typename Value, typename Vector, typename Size>\n\t    static inline void update(Value& tmp00, Value&, Value&, Value&, Value&, Value&, Value&, Value&, \n\t\t\t\t      const Vector& v, Size i)\n\t    {\n\t\tFunctor::update(tmp00, v[ i + Max0-1 ]);\n\t    }\n\n\t    template <typename Value>\n\t    static inline void finish(Value&, Value&, Value&, Value&, Value&, Value&, Value&, Value&) {}\n\t};\n\n    } // namespace impl\n\n\n// Will need distinction between dense and sparse in the future\ntemplate <unsigned long Unroll, typename Functor, typename Result>\nstruct reduction\n{\n    template <typename Vector>\n    Result static inline apply(const Vector& v)\n    {\n\tvampir_trace<2009> tracer;\n\treturn apply(v, typename mtl::traits::is_sparse<Vector>());\n    }\n\n  private:\n    template <typename Vector>\n    Result static inline apply(const Vector& v, boost::mpl::true_)\n    {\n\tResult tmp00;\n\tFunctor::init(tmp00);\n\n\tfor (std::size_t i= 0, n= v.nnz(); i < n; i++) \n\t    Functor::update(tmp00, v.value(i));\n\t// std::cout << \"i == \" << i << \"\n\n#if 0\n\ttypename mtl::traits::const_value<Vector>::type                        value(v); \n\ttypedef typename mtl::traits::range_generator<tag::nz, Vector>::type   cursor_type;\n\n\tfor (cursor_type cursor = begin<tag::nz>(v), cend = end<tag::nz>(v); cursor != cend; ++cursor)\n\t    Functor::update(tmp00, value(*cursor));\n#endif\n\treturn tmp00;\n    }\n\n# ifdef MTL_WITH_OPENMP   \n\n    template <typename Vector>\n    Result static inline apply(const Vector& v, boost::mpl::false_)\n    {\n\tMTL_STATIC_ASSERT((Unroll >= 1), \"Unroll size must be at least 1.\");\n\tMTL_STATIC_ASSERT((Unroll <= 8), \"Maximal unrolling is 8.\"); // Might be relaxed in future versions\n\n\tResult result;\n\tFunctor::init(result);\n\n\ttypedef typename mtl::traits::omp_size_type<typename Collection<Vector>::size_type>::type size_type;\n\tconst size_type  i_max= mtl::size(v), i_block= Unroll * (i_max / Unroll);\n\n\t#pragma omp parallel\n\t{\n\t    vampir_trace<8002> tracer;\n\t    Result tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07;\n\t    impl::reduction<1, Unroll, Functor>::init(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07);\n\n\t    #pragma omp for\n\t    for (size_type i= 0; i < i_block; i+= Unroll)\n\t\timpl::reduction<1, Unroll, Functor>::update(tmp00, tmp01, tmp02, tmp03, \n\t\t\t\t\t\t\t    tmp04, tmp05, tmp06, tmp07, v, i);\n\n\t    impl::reduction<1, Unroll, Functor>::finish(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07);\n\n\t    #pragma omp critical\n\t    Functor::finish(result, tmp00);\n\t}\n\n\tfor (size_type i= i_block; i < i_max; i++) \n\t    Functor::update(result, v[i]);\n\n\treturn result;\n    } \n\n# else\n\n    template <typename Vector>\n    Result static inline apply(const Vector& v, boost::mpl::false_)\n    {\n\tMTL_STATIC_ASSERT((Unroll >= 1), \"Unroll size must be at least 1.\");\n\tMTL_STATIC_ASSERT((Unroll <= 8), \"Maximal unrolling is 8.\"); // Might be relaxed in future versions\n\n\tResult tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07;\n\timpl::reduction<1, Unroll, Functor>::init(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07);\n\n\ttypedef typename Collection<Vector>::size_type              size_type;\n\tconst size_type  i_max= mtl::vec::size(v), i_block= Unroll * (i_max / Unroll);\n\tfor (size_type i = 0; i < i_block; i += Unroll)\n\t\timpl::reduction<1, Unroll, Functor>::update(tmp00, tmp01, tmp02, tmp03,\n\t\t\ttmp04, tmp05, tmp06, tmp07, v, i);\n\tfor (size_type i= i_block; i < i_max; i++) \n\t    Functor::update(tmp00, v[i]);\n\n\timpl::reduction<1, Unroll, Functor>::finish(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07);\n\treturn tmp00;\n    } \n\n# endif\n\n\n};\n\n}} // namespace mtl\n\n#endif // MTL_REDUCTION_INCLUDE\n", "meta": {"hexsha": "c03af3b288671a34296b57b9675a902795575914", "size": 5973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/vector/reduction.hpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/vector/reduction.hpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/vector/reduction.hpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 32.6393442623, "max_line_length": 105, "alphanum_fraction": 0.670517328, "num_tokens": 1721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981162643692786, "lm_q2_score": 0.06465348790566186, "lm_q1q2_score": 0.025849216154382914}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2020 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\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/level3.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#include <boost/numeric/ublas/io.hpp>\n#include \"SiconosAlgebraProd.hpp\" // for axpy_prod and prod\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\n\n// needed for blas3\n#include <assert.h>\n\nnamespace siconosBindings = boost::numeric::bindings;\n\n// for ublas::axpy_prod, ...\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n// require for matrix stuff like value_type\n//#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n#include \"SiconosAlgebraProd.hpp\" // for prod\n\nusing namespace Siconos;\n\n\n\n//======================\n// Product of matrices\n//======================\n// Note FP: this function is never used. We keep it for the record. Remove it later ?\n\n\n// const SimpleMatrix prod(const SiconosMatrix &A, const SiconosMatrix& B)\n// {\n//   // To compute C = A * B\n//   assert(!(B.isPLUFactorized()) && \"B is PLUFactorized in prod !!\");\n//   assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n\n//   if((A.size(1) != B.size(0)))\n//     THROW_EXCEPTION(\"Matrix function C=prod(A,B): inconsistent sizes\");\n\n//   Siconos::UBLAS_TYPE numA = A.num();\n//   Siconos::UBLAS_TYPE numB = B.num();\n\n//   // == TODO: implement block product ==\n//   if(numA == 0 || numB == 0)\n//     THROW_EXCEPTION(\"Matrix product ( C=prod(A,B) ): not yet implemented for BlockMatrix objects.\");\n\n//   if(numA == Siconos::IDENTITY || numB == Siconos::ZERO)  // A = identity or B = 0\n//     return SimpleMatrix(B);\n\n//   else if(numB == Siconos::IDENTITY || numA == Siconos::ZERO)  // B = identity or A = 0\n//     return SimpleMatrix(A);\n\n//   else // neither A or B is equal to identity or zero.\n//   {\n//     if(numB == Siconos::DENSE)\n//     {\n//       if(numA == Siconos::DENSE)\n//       {\n//         DenseMat p(A.size(0), B.size(1));\n//         siconosBindings::blas::gemm(1.0, *A.dense(), *B.dense(), 1.0, p);\n//         //      return (DenseMat)(prod(*A.dense(),*B.dense()));\n//         return p;\n//       }\n//       else if(numA == Siconos::TRIANGULAR)\n//         return (DenseMat)(prod(*A.triang(), *B.dense()));\n//       else if(numA == Siconos::SYMMETRIC)\n//         return (DenseMat)(prod(*A.sym(), *B.dense()));\n//       else if(numA == Siconos::SPARSE)\n//         return (DenseMat)(prod(*A.sparse(), *B.dense()));\n//       else if(numA == Siconos::SPARSE_COORDINATE)\n//         return (DenseMat)(prod(*A.sparseCoordinate(), *B.dense()));\n//       else// if(numA==Siconos::BANDED)\n//         return (DenseMat)(prod(*A.banded(), *B.dense()));\n//     }\n//     else if(numB == Siconos::TRIANGULAR)\n//     {\n//       if(numA == Siconos::DENSE)\n//         return (DenseMat)(prod(*A.dense(), *B.triang()));\n//       else if(numA == Siconos::TRIANGULAR)\n//         return (TriangMat)(prod(*A.triang(), *B.triang()));\n//       else if(numA == Siconos::SYMMETRIC)\n//         return (DenseMat)(prod(*A.sym(), *B.triang()));\n//       else if(numA == Siconos::SPARSE)\n//         return (DenseMat)(prod(*A.sparse(), *B.triang()));\n//       else if(numA == Siconos::SPARSE_COORDINATE)\n//         return (DenseMat)(prod(*A.sparseCoordinate(), *B.triang()));\n//       else //if(numA==Siconos::BANDED)\n//         return (DenseMat)(prod(*A.banded(), *B.triang()));\n//     }\n//     else if(numB == Siconos::SYMMETRIC)\n//     {\n//       if(numA == Siconos::DENSE)\n//         return (DenseMat)(prod(*A.dense(), *B.sym()));\n//       else if(numA == Siconos::TRIANGULAR)\n//         return (DenseMat)(prod(*A.triang(), *B.sym()));\n//       else if(numA == Siconos::SYMMETRIC)\n//         return (SymMat)(prod(*A.sym(), *B.sym()));\n//       else if(numA == Siconos::SPARSE)\n//         return (DenseMat)(prod(*A.sparse(), *B.sym()));\n//       else if(numA == Siconos::SPARSE_COORDINATE)\n//         return (DenseMat)(prod(*A.sparseCoordinate(), *B.sym()));\n//       else // if (numA == Siconos::BANDED)\n//         return (DenseMat)(prod(*A.banded(), *B.sym()));\n//     }\n//     else if(numB == Siconos::SPARSE)\n//     {\n//       if(numA == Siconos::DENSE)\n//         return (DenseMat)(prod(*A.dense(), *B.sparse()));\n//       else if(numA == Siconos::TRIANGULAR)\n//         return (DenseMat)(prod(*A.triang(), *B.sparse()));\n//       else if(numA == Siconos::SYMMETRIC)\n//         return (DenseMat)(prod(*A.sym(), *B.sparse()));\n//       else if(numA == Siconos::SPARSE)\n//         return (SparseMat)(prod(*A.sparse(), *B.sparse()));\n//       else if(numA == Siconos::SPARSE_COORDINATE)\n//         return (SparseMat)(prod(*A.sparseCoordinate(), *B.sparse()));\n//       else //if(numA==Siconos::BANDED){\n//         return (DenseMat)(prod(*A.banded(), *B.sparse()));\n//     }\n//     else if(numB == Siconos::SPARSE_COORDINATE)\n//     {\n//       if(numA == Siconos::DENSE)\n//         return (DenseMat)(prod(*A.dense(), *B.sparseCoordinate()));\n//       else if(numA == Siconos::TRIANGULAR)\n//         return (DenseMat)(prod(*A.triang(), *B.sparseCoordinate()));\n//       else if(numA == Siconos::SYMMETRIC)\n//         return (DenseMat)(prod(*A.sym(), *B.sparseCoordinate()));\n//       else if(numA == Siconos::SPARSE)\n//         return (SparseMat)(prod(*A.sparse(), *B.sparseCoordinate()));\n//       else if(numA == Siconos::SPARSE_COORDINATE)\n//         return (SparseMat)(prod(*A.sparseCoordinate(), *B.sparseCoordinate()));\n//       else //if(numA==Siconos::BANDED){\n//         return (DenseMat)(prod(*A.banded(), *B.sparseCoordinate()));\n//     }\n//     else //if(numB==Siconos::BANDED)\n//     {\n//       if(numA == Siconos::DENSE)\n//         return (DenseMat)(prod(*A.dense(), *B.banded()));\n//       else if(numA == Siconos::TRIANGULAR)\n//         return (DenseMat)(prod(*A.triang(), *B.banded()));\n//       else if(numA == Siconos::SYMMETRIC)\n//         return (DenseMat)(prod(*A.sym(), *B.banded()));\n//       else if(numA == Siconos::SPARSE)\n//         return (DenseMat)(prod(*A.sparse(), *B.banded()));\n//       else if(numA == Siconos::SPARSE_COORDINATE)\n//         return (DenseMat)(prod(*A.sparseCoordinate(), *B.banded()));\n//       else //if(numA==Siconos::BANDED)\n//         return (DenseMat)(prod(*A.banded(), *B.banded()));\n//     }\n//   }\n// }\n/**\n\nindexStart : indexStart[0] is the first raw, indexStart[1] is the first col\ndim : dim[0] number of raw, dim[1] number of col\n*/\n// void zeroBlock(const SiconosMatrix& A, index indexStart, index dim){\n//   ;\n// }\n// void prod(const SiconosMatrix& A, const SiconosMatrix& B, SiconosMatrix& C, int indexACol, bool init){\n//   // To compute C[indexAcol::] = A * B\n\n//   Siconos::UBLAS_TYPE numA = A.num();\n//   Siconos::UBLAS_TYPE numB = B.num();\n//   Siconos::UBLAS_TYPE numC = C.num();\n//   if (numA == 0 || numB == 0 || numC == 0)\n//     THROW_EXCEPTION(\"Matrix function prod(A,B,C,index): inconsistent sizes\");\n//   // === if C is zero or identity => read-only ===\n//   if (numC == Siconos::Zero || numC == Siconos::IDENTITY)\n//     THROW_EXCEPTION(\"Matrix product ( prod(A,B,C,index) ): wrong type for resulting matrix C (read-only: zero or identity).\");\n\n\n//   if (numA == Siconos::IDENTITY || numC == Siconos::Zero) // A = identity or 0\n//     THROW_EXCEPTION(\"Matrix function prod(A,B,C,index): numA == Siconos::IDENTITY || numC == Siconos::Zero not yet implemented\");\n\n//   int rawB = B.size(0);\n//   int colB = B.size(1);\n\n// }\n\n\nvoid axpy_prod(const SiconosMatrix& A, const SiconosMatrix& B, SiconosMatrix& C, bool init)\n{\n\n  // To compute C = A * B (init = true) or C += A * B (init = false) using ublas axpy_prod.\n  // High speedup for sparse matrices.\n  // Warning FP: ublas::axpy_prod(A, B, C, init) with init = True is equivalent\n  // to C = A*B with C.clear BEFORE product. So C==A or B must be forbidden.\n  // See http://www.boost.org/doc/libs/1_63_0/libs/numeric/ublas/doc/products.html\n  //\n\n  if((A.size(1) != B.size(0)))\n    THROW_EXCEPTION(\"Matrix function axpy_prod(A,B,C): inconsistent sizes\");\n\n  if(A.size(0) != C.size(0) || B.size(1) != C.size(1))\n    THROW_EXCEPTION(\"Matrix function axpy_prod(A,B,C): inconsistent sizes\");\n\n  if(&A == &C || &B == &C)\n    THROW_EXCEPTION(\"Matrix function axpy_prod(A,B,C): C must be different from A and B.\");\n\n  assert(!(A.isPLUFactorizedInPlace()) && \"A is PLUFactorized in place in prod !!\");\n  assert(!(B.isPLUFactorizedInPlace()) && \"B is PLUFactorized in place in prod !!\");\n  if(!C.isBlock())\n    C.resetFactorizationFlags();\n  Siconos::UBLAS_TYPE numA = A.num();\n  Siconos::UBLAS_TYPE numB = B.num();\n  Siconos::UBLAS_TYPE numC = C.num();\n  // == TODO: implement block product ==\n  if(numA == Siconos::BLOCK || numB == Siconos::BLOCK)\n    THROW_EXCEPTION(\"Matrix product ( prod(A,B,C) ): not yet implemented for BlockMatrix objects.\");\n\n  // === if C is zero or identity => read-only ===\n  if(numC == Siconos::ZERO || numC == Siconos::IDENTITY)\n    THROW_EXCEPTION(\"Matrix product ( prod(A,B,C) ): wrong type for resulting matrix C (read-only: zero or identity).\");\n\n\n  if(numA == Siconos::IDENTITY)  // A = identity ...\n  {\n    if(!init)\n      C += B;\n    else\n      C = B; // if C and B are two different objects.\n  }\n\n  else if(numB == Siconos::IDENTITY)  // B = identity\n  {\n    if(!init)\n      C += A;\n    else\n      C = A; // if C and A are two different objects.\n  }\n\n\n  else if(numA == Siconos::ZERO || numB == Siconos::ZERO)  // if A or B = 0\n  {\n    if(init) C.zero();  // else nothing\n  }\n  else if(numC == Siconos::BLOCK)  // if C is Block - Temp. solution\n  {\n    SimpleMatrix tmp(C);\n    axpy_prod(A, B, tmp, init);\n    C = tmp;\n  }\n  else // neither A or B is equal to identity or zero.\n  {\n    switch(numC)\n    {\n    case Siconos::DENSE:\n      if(numB == Siconos::DENSE)\n      {\n        if(numA == Siconos::DENSE)\n          ublas::axpy_prod(*A.dense(), *B.dense(), *C.dense(), init);\n        else if(numA == Siconos::TRIANGULAR)\n          ublas::axpy_prod(*A.triang(), *B.dense(), *C.dense(), init);\n        else if(numA == Siconos::SYMMETRIC)\n          ublas::axpy_prod(*A.sym(), *B.dense(), *C.dense(), init);\n        else if(numA == Siconos::SPARSE)\n          ublas::axpy_prod(*A.sparse(), *B.dense(), *C.dense(), init);\n        else// if(numA==Siconos::BANDED)\n          ublas::axpy_prod(*A.banded(), *B.dense(), *C.dense(), init);\n      }\n      else if(numB == Siconos::TRIANGULAR)\n      {\n        if(numA == Siconos::DENSE)\n          ublas::axpy_prod(*A.dense(), *B.triang(), *C.dense(), init);\n        else if(numA == Siconos::TRIANGULAR)\n          ublas::axpy_prod(*A.triang(), *B.triang(), *C.dense(), init);\n        else if(numA == Siconos::SYMMETRIC)\n          ublas::axpy_prod(*A.sym(), *B.triang(), *C.dense(), init);\n        else if(numA == Siconos::SPARSE)\n          ublas::axpy_prod(*A.sparse(), *B.triang(), *C.dense(), init);\n        else //if(numA==Siconos::BANDED)\n          ublas::axpy_prod(*A.banded(), *B.triang(), *C.dense(), init);\n      }\n      else if(numB == Siconos::SYMMETRIC)\n      {\n        if(numA == Siconos::DENSE)\n          ublas::axpy_prod(*A.dense(), *B.sym(), *C.dense(), init);\n        else if(numA == Siconos::TRIANGULAR)\n          ublas::axpy_prod(*A.triang(), *B.sym(), *C.dense(), init);\n        else if(numA == Siconos::SYMMETRIC)\n          ublas::axpy_prod(*A.sym(), *B.sym(), *C.dense(), init);\n        else if(numA == Siconos::SPARSE)\n          ublas::axpy_prod(*A.sparse(), *B.sym(), *C.dense(), init);\n        else // if (numA == Siconos::BANDED)\n          ublas::axpy_prod(*A.banded(), *B.sym(), *C.dense(), init);\n      }\n      else if(numB == Siconos::SPARSE)\n      {\n        if(numA == Siconos::DENSE)\n          ublas::axpy_prod(*A.dense(), *B.sparse(), *C.dense(), init);\n        else if(numA == Siconos::TRIANGULAR)\n          ublas::axpy_prod(*A.triang(), *B.sparse(), *C.dense(), init);\n        else if(numA == Siconos::SYMMETRIC)\n          ublas::axpy_prod(*A.sym(), *B.sparse(), *C.dense(), init);\n        else if(numA == Siconos::SPARSE)\n          ublas::axpy_prod(*A.sparse(), *B.sparse(), *C.dense(), init);\n        else //if(numA==Siconos::BANDED){\n          ublas::axpy_prod(*A.banded(), *B.sparse(), *C.dense(), init);\n      }\n      else //if(numB==Siconos::BANDED)\n      {\n        if(numA == Siconos::DENSE)\n          ublas::axpy_prod(*A.dense(), *B.banded(), *C.dense(), init);\n        else if(numA == Siconos::TRIANGULAR)\n          ublas::axpy_prod(*A.triang(), *B.banded(), *C.dense(), init);\n        else if(numA == Siconos::SYMMETRIC)\n          ublas::axpy_prod(*A.sym(), *B.banded(), *C.dense(), init);\n        else if(numA == Siconos::SPARSE)\n          ublas::axpy_prod(*A.sparse(), *B.banded(), *C.dense(), init);\n        else //if(numA==Siconos::BANDED)\n          ublas::axpy_prod(*A.banded(), *B.banded(), *C.dense(), init);\n      }\n      break;\n    case Siconos::TRIANGULAR:\n      // if(numA!= Siconos::TRIANGULAR || numB != Siconos::TRIANGULAR)\n      THROW_EXCEPTION(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n      //ublas::axpy_prod(*A.triang(), *B.triang(),*C.triang(), init);\n      break;\n    case Siconos::SYMMETRIC:\n      //        if(numA!= Siconos::SYMMETRIC || numB != Siconos::SYMMETRIC)\n      THROW_EXCEPTION(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n      //ublas::axpy_prod(*A.sym(), *B.sym(),*C.sym(),init);\n      break;\n    case Siconos::SPARSE:\n      if(numA != Siconos::SPARSE || numB != Siconos::SPARSE)\n        THROW_EXCEPTION(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n      ublas::sparse_prod(*A.sparse(), *B.sparse(), *C.sparse(), init);\n      break;\n    default:\n      THROW_EXCEPTION(\"Matrix function axpy_prod(A,B,C): wrong type for C (according to A and B types).\");\n    }\n    if(!C.isBlock())\n      C.resetFactorizationFlags();\n  }\n}\n\n\n// Note FP: this function is never used. We keep it for the record. Remove it later ?\n// void gemmtranspose(double a, const SiconosMatrix& A, const SiconosMatrix& B, double b, SiconosMatrix& C)\n// {\n//   if(A.isBlock() || B.isBlock() || C.isBlock())\n//     THROW_EXCEPTION(\"gemm(...) not yet implemented for block matrices.\");\n//   Siconos::UBLAS_TYPE numA = A.num();\n//   Siconos::UBLAS_TYPE numB = B.num();\n//   Siconos::UBLAS_TYPE numC = C.num();\n//   if(numA != Siconos::DENSE || numB != Siconos::DENSE || numC != Siconos::DENSE)\n//     THROW_EXCEPTION(\"gemm(...) failed: reserved to dense matrices.\");\n\n\n//   assert(!(B.isPLUFactorized()) && \"B is PLUFactorized in prod !!\");\n//   assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n\n\n//   siconosBindings::blas::gemm(a, siconosBindings::trans(*A.dense()), siconosBindings::trans(*B.dense()), b, *C.dense());\n\n\n//   C.resetFactorizationFlags();\n// }\n\n// Note FP: this function is never used. We keep it for the record. Remove it later ?\n// void gemm(double a, const SiconosMatrix& A, const SiconosMatrix& B, double b, SiconosMatrix& C)\n// {\n//   Siconos::UBLAS_TYPE numA = A.num();\n//   Siconos::UBLAS_TYPE numB = B.num();\n//   Siconos::UBLAS_TYPE numC = C.num();\n//   assert(!(B.isPLUFactorized()) && \"B is PLUFactorized in prod !!\");\n//   assert(!(A.isPLUFactorized()) && \"A is PLUFactorized in prod !!\");\n//   C.resetFactorizationFlags();\n\n//   // At the time, only dense output allowed\n//   DenseMat * tmpC = nullptr;\n//   if(numA == 0 || numB == 0 || numC == 0)\n//     THROW_EXCEPTION(\"gemm(...) not yet implemented for block matrices.\");\n\n//   if(numA == Siconos::DENSE && numB == Siconos::DENSE && numC == Siconos::DENSE)\n//     siconosBindings::blas::gemm(a, *A.dense(), *B.dense(), b, *C.dense());\n//   else if(numA == Siconos::DENSE && numB == Siconos::DENSE && numC != Siconos::DENSE)\n//   {\n//     // Copy C into tmpC ...\n//     tmpC = new DenseMat(*C.dense());\n//     siconosBindings::blas::gemm(a, *A.dense(), *B.dense(), b, *tmpC);\n//     std::cout << *tmpC << std::endl;\n//     noalias(*C.dense()) = *tmpC;\n//     delete tmpC;\n//   }\n//   else\n//     THROW_EXCEPTION(\"gemm(...) not yet implemented for these kinds of matrices.\");\n//   C.resetFactorizationFlags();\n// }\n\n", "meta": {"hexsha": "31d182c09a19d4811ab009e94750bb9f5109609d", "size": 17199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixBLAS3.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixBLAS3.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixBLAS3.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2786885246, "max_line_length": 132, "alphanum_fraction": 0.5927088784, "num_tokens": 5225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.054198731732815156, "lm_q1q2_score": 0.025830012657318827}}
{"text": "#ifdef RICH_MPI\n#include <mpi.h>\n#endif\n#include <boost/foreach.hpp>\n#include \"source/newtonian/two_dimensional/diagnostics.hpp\"\n#include \"source/newtonian/test_2d/main_loop_2d.hpp\"\n#include \"source/tessellation/shape_2d.hpp\"\n#include \"source/newtonian/test_2d/piecewise.hpp\"\n#include \"source/newtonian/two_dimensional/physical_geometry.hpp\"\n#include \"source/newtonian/two_dimensional/geometric_outer_boundaries/SquareBox.hpp\"\n#include \"source/tessellation/VoronoiMesh.hpp\"\n#include \"source/newtonian/common/ideal_gas.hpp\"\n#include \"source/newtonian/two_dimensional/point_motions/eulerian.hpp\"\n#include \"source/newtonian/common/hllc.hpp\"\n#include \"source/newtonian/two_dimensional/source_terms/zero_force.hpp\"\n#include \"source/misc/mesh_generator.hpp\"\n#include \"source/newtonian/two_dimensional/spatial_distributions/uniform2d.hpp\"\n#include \"source/newtonian/two_dimensional/source_terms/cylindrical_complementary.hpp\"\n#include \"source/newtonian/two_dimensional/simple_flux_calculator.hpp\"\n#include \"source/newtonian/two_dimensional/simple_cell_updater.hpp\"\n#include \"source/newtonian/two_dimensional/hdf5_diagnostics.hpp\"\n#include \"source/newtonian/two_dimensional/simple_extensive_updater.hpp\"\n#include \"source/newtonian/two_dimensional/stationary_box.hpp\"\n\nusing namespace std;\nusing namespace simulation2d;\n\nnamespace {\n\n  bool same_side(const Vector2D& p1,\n\t\t const Vector2D& p2,\n\t\t const Vector2D& a,\n\t\t const Vector2D& b)\n  {\n    const double cp1 = CrossProduct(b-a,p1-a);\n    const double cp2 = CrossProduct(b-a,p2-a);\n    return cp1*cp2>=0;\n  }\n\n  class Triangle: public Shape2D\n  {\n  public:\n\n    const Vector2D p1;\n    const Vector2D p2;\n    const Vector2D p3;\n\n    Triangle(const Vector2D& p1_i,\n\t     const Vector2D& p2_i,\n\t     const Vector2D& p3_i):\n      p1(p1_i), p2(p2_i), p3(p3_i) {}\n\n    bool operator()(const Vector2D& p) const\n    {\n      return same_side(p,p1,p2,p3)&&\n\tsame_side(p,p2,p1,p3)&&\n\tsame_side(p,p3,p1,p2);\n    }\n  };\n\n  vector<ComputationalCell> calc_init_cond\n  (const Tessellation& tess)\n  {\n    vector<ComputationalCell> res(static_cast<size_t>(tess.GetPointNo()));\n    for(size_t i=0;i<res.size();++i){\n      const Triangle triangle(Vector2D(0.5,0.6),\n\t\t\t      Vector2D(0.7,0.5),\n\t\t\t      Vector2D(0.4,0.4));\n      const Vector2D r = tess.GetMeshPoint(static_cast<int>(i));\n      res[i].density = 1;\n      res[i].pressure = triangle(r) ? 2 : 1;\n      res[i].velocity = triangle(r) ? Vector2D(1,-1) : Vector2D(0,0);\n      //      res[i].tracers.push_back(triangle(r) ? 1 : 0);\n      res[i].tracers[0] = triangle(r) ? 1 : 0;\n    }\n    return res;\n  }\n\n  class SimData\n  {\n  public:\n\n    SimData(void):\n      pg_(),\n      outer_(Vector2D(0,0), Vector2D(1,1)),\n#ifdef RICH_MPI\n      proc_tess_(process_positions(outer_),outer_),\n      init_points_\n      (distribute_grid(proc_tess_,CartesianGridGenerator\n\t\t       (30,30, outer_.getBoundary().first,\n\t\t\touter_.getBoundary().second))),\n#else\n      init_points_(cartesian_mesh(30,30,\n\t\t\t\t  outer_.getBoundary().first,\n\t\t\t\t  outer_.getBoundary().second)),\n#endif\n      tess_(init_points_,outer_),\n      eos_(5./3.),\n      pm_(),\n      evc_(),\n      rs_(),\n      force_(),\n      tsf_(0.3),\n      fc_(rs_),\n      eu_(),\n      cu_(),\n      sim_(tess_,\n\t   outer_,\n\t   pg_,\n\t   calc_init_cond(tess_),\n\t   eos_,\n\t   pm_,\n\t   evc_,\n\t   force_,\n\t   tsf_,\n\t   fc_,\n\t   eu_,\n\t   cu_,\n\t   TracerStickerNames(vector<string>(1,\"tracer\"),vector<string>())) {}\n\n    hdsim& getSim(void)\n    {\n      return sim_;\n    }\n\n  private:\n    SlabSymmetry pg_;\n    SquareBox outer_;\n#ifdef RICH_MPI\n    VoronoiMesh proc_tess_;\n#endif\n    const vector<Vector2D> init_points_;\n    VoronoiMesh tess_;\n    IdealGas eos_;\n    Eulerian pm_;\n    const StationaryBox evc_;\n    Hllc rs_;\n    ZeroForce force_;\n    SimpleCFL tsf_;\n    SimpleFluxCalculator fc_;\n    const SimpleExtensiveUpdater eu_;\n    SimpleCellUpdater cu_;\n    hdsim sim_;\n  };\n\n  class WriteConserved: public DiagnosticFunction\n  {\n  public:\n\n    WriteConserved(string const& fname):\n      cons_(), fname_(fname) {}\n\n    void operator()(hdsim const& sim)\n    {\n      cons_.push_back(total_conserved(sim));\n    }\n\n    ~WriteConserved(void)\n    {\n#ifdef RICH_MPI\n      if(get_mpi_rank()==0){\n#endif\n\tofstream f(fname_.c_str());\n\tfor(size_t i=0;i<cons_.size();++i)\n\t  f << cons_[i].mass << \" \"\n\t    << cons_[i].momentum.x << \" \"\n\t    << cons_[i].momentum.y << \" \"\n\t    << cons_[i].energy << \" \"\n\t    << cons_[i].tracers[0] << \"\\n\";\n\tf.close();\n#ifdef RICH_MPI\n      }\n#endif\n    }\n\n  private:\n    mutable vector<Extensive> cons_;\n    const string fname_;\n  };\n}\n\nnamespace {\n  void my_main_loop(hdsim& sim)\n  {\n    SafeTimeTermination term_cond(0.05,1e6);\n    WriteConserved diag(\"res.txt\");\n    write_snapshot_to_hdf5(sim,\"initial.h5\");\n    main_loop(sim, \n\t      term_cond, \n\t      &hdsim::TimeAdvance,\n\t      &diag);\n    write_snapshot_to_hdf5(sim,\"final.h5\");\n  }\n}\n\nint main(void)\n{\n#ifdef RICH_MPI\n  MPI_Init(NULL, NULL);\n#endif\n  SimData sim_data;\n  hdsim& sim = sim_data.getSim();\n\n  my_main_loop(sim);\n\n#ifdef RICH_MPI\n  MPI_Finalize();\n#endif\n\n  return 0;\n}\n\n", "meta": {"hexsha": "f62b51dc3d78147fb689dd9673998213e43aa4c4", "size": 5084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/tests/newtonian/two_dimensional/conservation_eulerian/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/conservation_eulerian/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/conservation_eulerian/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.8685446009, "max_line_length": 86, "alphanum_fraction": 0.667191188, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.055005284420664345, "lm_q1q2_score": 0.025785961751318004}}
{"text": "/// @file\n/// @copyright The code is licensed under the BSD License\n///            <http://opensource.org/licenses/BSD-2-Clause>,\n///            Copyright (c) 2012-2015 Alexandre Hamez.\n/// @author Alexandre Hamez\n\n#pragma once\n\n#include <algorithm>  // all_of, copy, equal\n#include <iosfwd>\n#include <stdexcept>  // invalid_argument\n\n#include <boost/container/flat_set.hpp>\n\n#include \"sdd/internal_manager_fwd.hh\"\n#include \"sdd/dd/definition.hh\"\n#include \"sdd/hom/consolidate.hh\"\n#include \"sdd/hom/context_fwd.hh\"\n#include \"sdd/hom/definition_fwd.hh\"\n#include \"sdd/hom/identity.hh\"\n#include \"sdd/hom/local.hh\"\n#include \"sdd/order/order.hh\"\n#include \"sdd/util/packed.hh\"\n\nnamespace sdd { namespace hom {\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief Saturation Fixpoint homomorphism.\ntemplate <typename C>\nstruct LIBSDD_ATTRIBUTE_PACKED _saturation_fixpoint\n{\n  /// @brief The type of a const iterator on this saturation_fixpoint's G operands.\n  using const_iterator = const homomorphism<C>*;\n\n  /// @brief The variable type.\n  using variable_type = typename C::variable_type;\n\n  /// @brief The type deduced from configuration of the number of operands.\n  using operands_size_type = typename C::operands_size_type;\n\n  /// @brief The variable on which this sum works.\n  const variable_type variable;\n\n  /// @brief The homomorphism's F part.\n  const homomorphism<C> F;\n\n  /// @brief The homomorphism's G part size.\n  const operands_size_type G_size;\n\n  /// @brief The homomorphism's L part.\n  const homomorphism<C> L;\n\npublic:\n\n  /// @brief Constructor.\n  _saturation_fixpoint( variable_type var, homomorphism<C> f\n                      , boost::container::flat_set<homomorphism<C>>& g\n                      , homomorphism<C> l)\n    : variable{var}\n    , F{std::move(f)}\n    , G_size{static_cast<operands_size_type>(g.size())}\n    , L{std::move(l)}\n  {\n    // Put all homomorphisms operands right after this sum instance.\n    hom::consolidate(G_operands_addr(), g.begin(), g.end());\n  }\n\n  /// @brief Destructor.\n  ~_saturation_fixpoint()\n  {\n    for (auto& elem : *this)\n    {\n      elem.~homomorphism<C>();\n    }\n  }\n\n  /// @brief Evaluation.\n  SDD<C>\n  operator()(context<C>& cxt, const order<C>& o, const SDD<C>& s)\n  const\n  {\n    auto& sdd_context = cxt.sdd_context();\n\n    SDD<C> s1 = s;\n    SDD<C> s2 = s;\n\n    do\n    {\n      s1 = s2;\n\n      s2 = F(cxt, o, s2); // apply (F + Id)*\n      s2 = L(cxt, o, s2); // apply (L + Id)*\n\n      for (const auto& g : *this)\n      {\n        // chain applications of G\n        s2 = dd::sum(sdd_context, dd::sum_builder<C, SDD<C>>(sdd_context, {s2, g(cxt, o, s2)}));\n      }\n    } while (s1 != s2);\n\n    return s1;\n  }\n\n  /// @brief Skip predicate.\n  bool\n  skip(const order<C>& o)\n  const noexcept\n  {\n    return variable != o.variable();\n  }\n\n  /// @brief Selector predicate.\n  bool\n  selector()\n  const noexcept\n  {\n    return F.selector() and L.selector()\n       and std::all_of(begin(), end(), [](const auto& h){return h.selector();});\n  }\n\n  /// @brief Get an iterator to the first operand of G.\n  ///\n  /// O(1).\n  const_iterator\n  begin()\n  const noexcept\n  {\n    return reinterpret_cast<const homomorphism<C>*>(G_operands_addr());\n  }\n\n  /// @brief Get an iterator to the end of operands of G.\n  ///\n  /// O(1).\n  const_iterator\n  end()\n  const noexcept\n  {\n    return reinterpret_cast<const homomorphism<C>*>(G_operands_addr()) + G_size;\n  }\n\n  friend\n  bool\n  operator==(const _saturation_fixpoint& lhs, const _saturation_fixpoint& rhs)\n  noexcept\n  {\n    return lhs.variable == rhs.variable and lhs.F == rhs.F\n       and lhs.L == rhs.L and lhs.G_size == rhs.G_size\n       and std::equal(lhs.begin(), lhs.end(), rhs.begin());\n  }\n\n  friend\n  std::ostream&\n  operator<<(std::ostream& os, const _saturation_fixpoint& s)\n  {\n    os << \"Sat(@\" << s.variable << \",  \" << s.F << \" + \" << s.L;\n    if (s.G_size != 0)\n    {\n      os << \" + \";\n      std::copy( s.begin(), std::prev(s.end())\n               , std::ostream_iterator<homomorphism<C>>(os, \" + \"));\n      os << *std::prev(s.end()) << \")*\";\n    }\n    return os;\n  }\n\nprivate:\n\n  /// @brief Return the address of the beginning of the operands of G.\n  char*\n  G_operands_addr()\n  const noexcept\n  {\n    return reinterpret_cast<char*>(const_cast<_saturation_fixpoint*>(this))\n         + sizeof(_saturation_fixpoint);\n  }\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief Create the Saturation Fixpoint homomorphism.\n/// @related sdd::homomorphism\n///\n/// We suppose that a saturation fixpoint is created in the rewriting process. Thus, we assume\n/// that operands of the G part are already optimized (e.g. local merged and sums flatten).\ntemplate <typename C, typename InputIterator>\nhomomorphism<C>\nsaturation_fixpoint( typename C::variable_type var\n                  , const homomorphism<C>& f\n                  , InputIterator gbegin, InputIterator gend\n                  , const homomorphism<C>& l)\n{\n  const std::size_t gsize = std::distance(gbegin, gend);\n\n  if (gsize == 0)\n  {\n    if (f != id<C>() and l == id<C>()) return f;\n    if (f == id<C>() and l != id<C>()) return l;\n  }\n\n  // A global flat_set to avoid reallocating a new set of operands each time.\n  auto& g = global<C>().saturation_fixpoint_data;\n  g.clear();\n  g.insert(gbegin, gend);\n  const std::size_t extra_bytes = g.size() * sizeof(homomorphism<C>);\n  return hom::make_variable_size<C, _saturation_fixpoint<C>>(extra_bytes, var, f, g, l);\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\n}} // namespace sdd::hom\n\nnamespace std {\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief Hash specialization for sdd::hom::_saturation_fixpoint.\ntemplate <typename C>\nstruct hash<sdd::hom::_saturation_fixpoint<C>>\n{\n  std::size_t\n  operator()(const sdd::hom::_saturation_fixpoint<C>& s)\n  const\n  {\n    using namespace sdd::hash;\n    return seed(s.variable) (val(s.F)) (val(s.L)) (range(s));\n  }\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n} // namespace std\n", "meta": {"hexsha": "5438a63537c00eeac007862edc14217d24a992c2", "size": 6283, "ext": "hh", "lang": "C++", "max_stars_repo_path": "sdd/hom/saturation_fixpoint.hh", "max_stars_repo_name": "tic-toc/libsdd", "max_stars_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T01:20:28.000Z", "max_issues_repo_path": "sdd/hom/saturation_fixpoint.hh", "max_issues_repo_name": "tic-toc/libsdd", "max_issues_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-05T23:39:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-05T23:40:04.000Z", "max_forks_repo_path": "libsdd/sdd/hom/saturation_fixpoint.hh", "max_forks_repo_name": "kyouko-taiga/SwiftSDD", "max_forks_repo_head_hexsha": "9312160e0fac5fef6e605c9e74c543ded9708e54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-05-13T14:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T20:13:39.000Z", "avg_line_length": 26.6228813559, "max_line_length": 100, "alphanum_fraction": 0.5807735158, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.05500528325882745, "lm_q1q2_score": 0.025785961206659755}}
{"text": "// This file is part of the dune-mlmc project:\n//   http://users.dune-project.org/projects/dune-mlmc\n// Copyright Holders: Jan Mohring\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#ifndef MLMC_H\n#define MLMC_H\n\n#include <mpi.h>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <boost/noncopyable.hpp>\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/xt/common/configuration.hh>\n\n/// \\file Environment for computing expected values by the Multi Level\n/// Monte Carlo approach. For each level you have to provide extensions\n/// of the base class Difference which implement the two methods\n/// init and eval.\n/// \\author jan.mohring@itwm.fraunhofer.de\n/// \\date 2015\n\nnamespace MultiLevelMonteCarlo {\n\n/// Terminates program if condition is not satisfied.\n/// \\param condition   condition to check\n/// \\param message     message to show when condition is false\n/// TODO embed into exception handling\nstatic void check(bool condition, const char* message) {\n  if (!condition) {\n    std::cerr << message << \"\\n\";\n    DUNE_THROW(Dune::InvalidStateException, message);\n  }\n}\n\n/// Checks for power of 2\n/// \\param x  number to check\nstatic bool isPowerOf2(int x) { return (x != 0) && ((x & (x - 1)) == 0); }\n\n/// Base class of difference of solutions on subsequent levels.\n/// On the coarsest level the solution itself has to be returned.\nclass Difference : boost::noncopyable {\npublic:\n  /// Initialize level.\n  /// \\param global  global communicator\n  /// \\param local   communicator of processors involved in this solution\n  virtual void init(MPI_Comm global, MPI_Comm local) = 0;\n\n  /// Evaluate difference of solutions on subsequent levels.\n  virtual double eval() = 0;\n\n  virtual ~Difference() {}\n};\n\n/// Class for doing statistics on a given level.\nclass Level {\npublic:\n  /// Constructs empty level.\n  Level()\n    : _n(0)\n    , _N(0)\n    , _p(0)\n    , _g(0)\n    , _sumX(0)\n    , _sumX2(0)\n    , _T(0)\n    , _diff(nullptr)\n    , _masters(MPI_COMM_NULL) {}\n\n  /// Constructs level from Difference object.\n  /// \\param diff     Difference object\n  /// \\param minProc  minimal number of processors needed to compute solution\n  Level(const std::shared_ptr<Difference> diff, int minProc = 1)\n    : _n(0)\n    , _N(0)\n    , _p(minProc)\n    , _g(0)\n    , _sumX(0)\n    , _sumX2(0)\n    , _T(0)\n    , _diff(diff)\n    , _masters(MPI_COMM_NULL) {\n    check(minProc > 0, \"minProc must be positive.\");\n  }\n\n  /// Assigns communicator and group\n  /// \\param world   global communicator\n  void assignProcessors(MPI_Comm world = MPI_COMM_WORLD) {\n    check(_diff != NULL, \"No Difference object set.\");\n    int size, rank;\n    int range[1][3];\n    MPI_Group all, group, masters;\n    MPI_Comm_size(world, &size);\n    MPI_Comm_rank(world, &rank);\n    MPI_Comm_group(world, &all);\n    range[0][0] = rank - rank % _p;\n    range[0][1] = range[0][0] + _p - 1;\n    range[0][2] = 1;\n    MPI_Group_range_incl(all, 1, range, &group);\n    MPI_Comm_create(world, group, &_group);\n    _g = size / _p;\n    _diff->init(world, _group);\n    range[0][0] = 0;\n    range[0][1] = size - 1;\n    range[0][2] = _p;\n    MPI_Group_range_incl(all, 1, range, &masters);\n    MPI_Comm_create(world, masters, &_masters);\n    int grank;\n    MPI_Comm_rank(_group, &grank);\n    _isMaster = grank == 0;\n  }\n\n  /// Sets number of repetitions.\n  /// \\param N   number of repetitions\n  void setRepetitions(int N) { _N = N; }\n\n  /// Gets number of repetitions.\n  int getRepetitions() const { return _N; }\n\n  /// Returns number of repetitions till next break.\n  /// \\param iBreak  index of next break\n  /// \\param nBreak  total number of breaks\n  int nextRepetitions(int iBreak, int nBreak) const { return _N * iBreak / nBreak - _n; }\n\n  /// Returns communicator of masters\n  MPI_Comm getMasters() const { return _masters; }\n\n  /// Indicates master\n  bool isMaster() const { return _isMaster; }\n\n  /// Returns communicator of masters\n  MPI_Comm getGroup() const { return _group; }\n\n  /// Clears statistics.\n  void clear() {\n    _n = 0;\n    _sumX = 0;\n    _sumX2 = 0;\n    _T = 0;\n  }\n\n  /// Updates statistics.\n  void update(int n, double sumX, double sumX2, double T) {\n    _n += n;\n    _sumX += sumX;\n    _sumX2 += sumX2;\n    _T += T;\n  }\n\n  /// Returns mean value of realizations on present level.\n  double mean() const { return _sumX / (_n * _g); }\n\n  /// Returns empirical variance of realizations on present level.\n  double var() const { return _sumX2 / (_n * _g) - mean() * mean(); }\n\n  /// Returns average time of repetition on present level.\n  double time() const { return _T / (_n *  _g); }\n\n  /// Returns number of groups on present level.\n  int groups() const { return _g; }\n\n  /// Return number of processors per group.\n  int procs() const { return _p; }\n\n  int totalRepetitions() const { return _N * _g; }\n  int doneRepetitions() const { return _n * _g; }\n\n  /// Evaluate difference.\n  double eval() { return _diff->eval(); }\n\nprivate:\n  int _n;                  ///< number of performed repetitions\n  int _N;                  ///< number of required repetitions\n  int _p;                  ///< number of processors per realization\n  int _g;                  ///< number of groups acting in parallel per repetition\n  double _sumX;            ///< sum of results so far\n  double _sumX2;           ///< sum of squared results so far\n  double _T;               ///< total time of repetitions so far\n  const std::shared_ptr<Difference> _diff; ///< pointer to Difference object\n  MPI_Comm _group;         ///< communicator of group\n  MPI_Comm _masters;       ///< communicator of masters\n  bool _isMaster;          ///< flag indicating master\n};\n\n/// Environment for computing expected values by the\n/// Multi Level Monte Carlo Method.\nclass MLMC {\n\npublic:\n  /// Adds difference object.\n  /// \\param diff     Difference object\n  /// \\param minProc  minimal number of processors needed to compute solution\n  void addDifference(const std::shared_ptr<Difference> diff, int minProc) {\n    check(isPowerOf2(minProc), \"minProc must be power of 2.\");\n    _level.emplace_back(diff, minProc);\n  }\n\n  /// Computes optimal number of repetitions per level .\n  /// \\param tol  absolute tolerance of expected value\n  void setRepetitions(double tol) {\n    double alpha = 0;\n    int n = _level.size();\n    for (int i = 0; i < n; ++i)\n      alpha += sqrt(_level[i].time() * _level[i].var());\n    alpha /= tol * tol;\n    for (int i = 0; i < n; ++i)\n      _level[i].setRepetitions(ceil(alpha * sqrt(_level[i].var() / _level[i].time()) / _level[i].groups()));\n  }\n\n  /// Computes the expected value of a scalar random variable up to a given\n  /// tolerance by the Multi Level Monte Carlo approach.\n  /// \\param tol    absolute tolerance of expected value\n  /// \\param nBreak number of breaks for recomputing required realizations\n  double expectation(double tol, int nBreak, MPI_Comm world = MPI_COMM_WORLD) {\n    int nLevel = _level.size();\n    int rank, size;\n    MPI_Comm_rank(world, &rank);\n    MPI_Comm_size(world, &size);\n    check(isPowerOf2(size), \"Number of processors must be power of 2.\");\n\n    // XXX\n    double duration;\n    std::stringstream ss;\n    std::fstream fs;\n    if (rank == 0) {\n      duration = MPI_Wtime();\n      ss << DXTC_CONFIG_GET(\"global.datadir\", \"data/\") << \"/mlmc\" << size << \".txt\";\n      fs.open(ss.str(), std::fstream::out);\n    }\n    // XXX\n\n    // Check input.\n    check(nLevel > 0, \"No levels set.\");\n    check(tol > 0, \"tol must be positive.\");\n    check(nBreak > 1, \"nBreak must be greater than 1.\");\n\n    // Create groups and communicators for different levels.\n    int startRepititions = DXTC_CONFIG_GET(\"mlmc.start_repititions\", 16);\n    for (int i = 0; i < nLevel; ++i) {\n      _level[i].assignProcessors(world);\n      _level[i].setRepetitions(std::max(nBreak, nBreak * startRepititions / _level[i].groups()));\n    }\n\n    // Loop over breaks and levels\n    for (int iBreak = 1; iBreak <= nBreak; ++iBreak) {\n      for (int iLevel = 0; iLevel < nLevel; ++iLevel) {\n        // Moments of groups.\n        Level& l = _level[iLevel];\n        MPI_Comm masters = l.getMasters();\n        MPI_Comm group = l.getGroup();\n\n        int n = l.nextRepetitions(iBreak, nBreak);\n        if (n <= 0)\n          continue;\n\n        double gdata[3] = {0};\n        gdata[2] = MPI_Wtime();\n        for (int i = 0; i < n; ++i) {\n          double x = l.eval();\n          gdata[0] += x;\n          gdata[1] += x * x;\n        }\n        gdata[2] = MPI_Wtime() - gdata[2];\n\n        double data[3];\n        // Accumulate over group masters\n        if (l.isMaster()) {\n          MPI_Allreduce(gdata, data, 3, MPI_DOUBLE, MPI_SUM, masters);\n        }\n        // Distribute master results over groups\n        MPI_Bcast(data, 3, MPI_DOUBLE, 0, group);\n        // Update moments.\n        l.update(n, data[0], data[1], data[2]);\n      }\n\n      // Compute optimal number of repetitions per algorithm.\n      setRepetitions(tol);\n\n      // XXX fs -> std::cout\n      if (rank == 0) {\n        fs << \"Break: \" << iBreak << \"\\n\";\n        for (int i = 0; i < nLevel; ++i)\n          fs << \"\\tL: \" << i \n             << \"\\tn: \" << _level[i].doneRepetitions()\n             << \"\\tN: \" << _level[i].totalRepetitions()\n             << \"\\tg: \" << _level[i].groups()\n             << \"\\tQ: \" << _level[i].mean()\n             << \"\\tV: \" << _level[i].var()\n             << \"\\tt: \" << _level[i].time()\n             << \"\\n\";\n        fs << \"\\n\";\n        fs.flush();\n        // XXX\n      }\n    }\n\n    // Compute expected value from mean values of differences.\n    double e = 0;\n    for (int i = 0; i < nLevel; ++i)\n      e += _level[i].mean();\n\n    // XXX\n    if (rank == 0) {\n      duration = MPI_Wtime() - duration;\n      fs << \"Expected value: \" << e << \" Duration: \" << duration << \" s\\n\";\n      fs.close();\n    }\n    // XXX\n\n    return e;\n  }\n\nprivate:\n  std::vector<Level> _level; ///< vector of levels\n};\n} // namespace MultiLevelMonteCarlo {\n\n#endif\n", "meta": {"hexsha": "92248dc0f7af1d60dd61c243a059c2d9d6a04b81", "size": 9971, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/mlmc/mlmc.hh", "max_stars_repo_name": "wwu-numerik/DUNE-mlmc", "max_stars_repo_head_hexsha": "5ea4b663ec0a30d2bfcccdf736a9db9bdcea16fb", "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/mlmc/mlmc.hh", "max_issues_repo_name": "wwu-numerik/DUNE-mlmc", "max_issues_repo_head_hexsha": "5ea4b663ec0a30d2bfcccdf736a9db9bdcea16fb", "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/mlmc/mlmc.hh", "max_forks_repo_name": "wwu-numerik/DUNE-mlmc", "max_forks_repo_head_hexsha": "5ea4b663ec0a30d2bfcccdf736a9db9bdcea16fb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8699690402, "max_line_length": 108, "alphanum_fraction": 0.6090662922, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.06754668410060374, "lm_q1q2_score": 0.02575011761487334}}
{"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#include \"BlockCSRMatrix.hpp\"\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include \"NonSmoothLaw.hpp\"\n#include \"Interaction.hpp\"\n\n#include \"NewtonEulerDS.hpp\"\n#include \"NewtonEulerR.hpp\"\n#include \"SimulationGraphs.hpp\"\n#include \"SparseBlockMatrix.h\" // From numerics, for SparseBlockStructuredMatrix\n#include \"Tools.hpp\"\n\n//#define DEBUG_STDOUT\n//#define DEBUG_MESSAGES 1\n#include \"siconos_debug.h\"\n\n// Default constructor: empty matrix\nBlockCSRMatrix::BlockCSRMatrix():\n  _nr(0),\n  _blockCSR(new CompressedRowMat()),\n  _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n  _diagsize0(new IndexInt()),\n  _diagsize1(new IndexInt()),\n  rowPos(new IndexInt()),\n  colPos(new IndexInt())\n{}\n\n// Constructor with dimensions\nBlockCSRMatrix::BlockCSRMatrix(unsigned int nRow):\n  _nr(nRow),\n  // Only square-blocks matrices for the moment (ie nRow = nr = nrol)\n\n  // Allocate memory and fill in the matrix rowPos, rowCol ... are\n  // initialized with nr to reserve at first step the maximum possible\n  // (according to given nr) space in memory.  Thus a future resize\n  // will not require memory allocation or copy.\n  _blockCSR(new CompressedRowMat(_nr, _nr)),\n  _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n  _diagsize0(new IndexInt(_nr)),\n  _diagsize1(new IndexInt(_nr)),\n  rowPos(new IndexInt(_nr)),\n  colPos(new IndexInt(_nr))\n{}\n\n// Basic constructor\nBlockCSRMatrix::BlockCSRMatrix(InteractionsGraph& indexSet):\n  _nr(indexSet.size()),\n  _blockCSR(new CompressedRowMat(_nr, _nr)),\n  _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n  _diagsize0(new IndexInt(_nr)),\n  _diagsize1(new IndexInt(_nr)),\n  rowPos(new IndexInt(_nr)),\n  colPos(new IndexInt(_nr))\n{\n  DEBUG_BEGIN(\"BlockCSRMatrix::BlockCSRMatrix(SP::InteractionsGraph indexSet)\\n\");\n  fill(indexSet);\n  DEBUG_END(\"BlockCSRMatrix::BlockCSRMatrix(SP::InteractionsGraph indexSet)\\n\");\n}\n\nBlockCSRMatrix::~BlockCSRMatrix()\n{}\n\n// Fill the SparseMat\nvoid BlockCSRMatrix::fill(InteractionsGraph& indexSet)\n{\n  // ======> Aim: find inter1 and inter2 both in indexSets[level] and which\n  // have common DynamicalSystems.  Then get the corresponding matrix\n  // from map blocks.\n\n  // Number of blocks in a row = number of active constraints.\n  _nr = indexSet.size();\n\n  // (re)allocate memory for ublas matrix\n  _blockCSR->resize(_nr, _nr, false);\n\n  _diagsize0->resize(_nr);\n  _diagsize1->resize(_nr);\n\n  // === Loop through \"active\" Interactions (ie present in\n  // indexSets[level]) ===\n\n\n  int sizeV = 0;\n\n  InteractionsGraph::VIterator vi, viend;\n  for(std::tie(vi, viend) = indexSet.vertices();\n      vi != viend; ++vi)\n  {\n    SP::Interaction inter = indexSet.bundle(*vi);\n\n    assert(inter->nonSmoothLaw()->size() > 0);\n\n    sizeV  += inter->nonSmoothLaw()->size();\n    (*_diagsize0)[indexSet.index(*vi)] = sizeV;\n    (*_diagsize1)[indexSet.index(*vi)] = sizeV;\n    assert((*_diagsize0)[indexSet.index(*vi)] > 0);\n    assert((*_diagsize1)[indexSet.index(*vi)] > 0);\n\n    (*_blockCSR)(indexSet.index(*vi), indexSet.index(*vi)) =\n      indexSet.properties(*vi).block->getArray();\n  }\n\n  InteractionsGraph::EIterator ei, eiend;\n  for(std::tie(ei, eiend) = indexSet.edges();\n      ei != eiend; ++ei)\n  {\n    InteractionsGraph::VDescriptor vd1 = indexSet.source(*ei);\n    InteractionsGraph::VDescriptor vd2 = indexSet.target(*ei);\n    SP::Interaction inter1 = indexSet.bundle(vd1);\n    SP::Interaction inter2 = indexSet.bundle(vd2);\n\n    assert(indexSet.index(vd1) < _nr);\n    assert(indexSet.index(vd2) < _nr);\n\n    assert(indexSet.is_vertex(inter2));\n\n    assert(vd2 == indexSet.descriptor(inter2));\n    assert(indexSet.index(vd2) == indexSet.index(indexSet.descriptor(inter2)));\n\n\n    unsigned int pos = indexSet.index(vd1);\n    unsigned int col = indexSet.index(vd2);\n\n    assert(pos != col);\n\n    (*_blockCSR)(std::min(pos, col), std::max(pos, col)) =\n      indexSet.properties(*ei).upper_block->getArray();\n\n    (*_blockCSR)(std::max(pos, col), std::min(pos, col)) =\n      indexSet.properties(*ei).lower_block->getArray();\n  }\n  DEBUG_EXPR(display(););\n}\n\nvoid BlockCSRMatrix::fillW(InteractionsGraph& indexSet)\n{\n  /* on adjoint graph a dynamical system may be on several edges */\n  std::map<SP::DynamicalSystem, bool> involvedDS;\n  InteractionsGraph::EIterator ei, eiend;\n  for(std::tie(ei, eiend) = indexSet.edges();\n      ei != eiend; ++ei)\n  {\n    if(Type::value(*indexSet.bundle(*ei)) != Type::NewtonEulerDS)\n    {\n      THROW_EXCEPTION(\"BlockCSRMatrix::fillW only for Newton EulerDS\");\n    }\n\n    _nr = 0;\n\n    if(involvedDS.find(indexSet.bundle(*ei)) == involvedDS.end())\n    {\n      _nr++;\n      involvedDS[indexSet.bundle(*ei)] = true;\n      _blockCSR->resize(_nr, _nr, false);\n\n      (*_blockCSR)(_nr-1, _nr-1) = std::static_pointer_cast<NewtonEulerDS>\n                                   (indexSet.bundle(*ei))->mass()->getArray();\n    }\n  }\n\n  _diagsize0->resize(involvedDS.size());\n  _diagsize1->resize(involvedDS.size());\n\n  /* here we suppose NewtonEuler with 6 dofs */\n  /* it cannot be another case at this point */\n  unsigned int index, ac;\n  for(index = 0, ac = 6;\n      index < involvedDS.size();\n      ++index, ac+=6)\n  {\n    (*_diagsize0)[index] = ac;\n    (*_diagsize1)[index] = ac;\n  }\n\n}\n\nvoid BlockCSRMatrix::fillH(InteractionsGraph& indexSet)\n{\n  /* on adjoint graph a dynamical system may be on several edges */\n  std::map<SP::DynamicalSystem, unsigned int> involvedDS;\n  InteractionsGraph::EIterator ei, eiend;\n  {\n    unsigned int index;\n    for(std::tie(ei, eiend) = indexSet.edges(), index=0;\n        ei != eiend; ++ei, ++index)\n    {\n      if(involvedDS.find(indexSet.bundle(*ei)) == involvedDS.end())\n      {\n        if(Type::value(*indexSet.bundle(*ei)) != Type::NewtonEulerDS)\n        {\n          THROW_EXCEPTION(\"BlockCSRMatrix::fillH only for Newton EulerDS\");\n        }\n        involvedDS[indexSet.bundle(*ei)] = index;\n      }\n    }\n  }\n\n  _nr = involvedDS.size();\n\n  _blockCSR->resize(_nr, _nr, false);\n\n  InteractionsGraph::VIterator vi, viend;\n  for(std::tie(vi, viend) = indexSet.vertices();\n      vi != viend; ++vi)\n  {\n\n    SP::DynamicalSystem first = SP::DynamicalSystem();\n    unsigned int pos=0, col=0;\n    InteractionsGraph::EDescriptor ed1, ed2;\n    InteractionsGraph::OEIterator oei, oeiend;\n    for(std::tie(oei, oeiend) = indexSet.out_edges(*vi);\n        oei != oeiend; ++oei)\n    {\n      if(!first)\n      {\n        first = indexSet.bundle(*oei);\n        col = involvedDS[first];\n        pos = involvedDS[first];\n      }\n      else\n      {\n        if(indexSet.bundle(*oei) != first)\n        {\n          pos = involvedDS[indexSet.bundle(*oei)];\n        }\n      }\n    }\n\n    (*_blockCSR)(std::min(pos, col), std::max(pos, col)) =\n      std::static_pointer_cast<NewtonEulerR>(indexSet.bundle(*vi)->relation())->jachqT()->getArray();\n\n    (*_blockCSR)(std::max(pos, col), std::min(pos, col)) =\n      std::static_pointer_cast<NewtonEulerR>(indexSet.bundle(*vi)->relation())->jachqT()->getArray();\n\n  }\n\n  _diagsize0->resize(involvedDS.size());\n  _diagsize1->resize(involvedDS.size());\n\n  /* only NewtonEuler3DR */\n  unsigned int index, ac0, ac1;\n  for(index= 0, ac0 = 6, ac1 = 3;\n      index < involvedDS.size();\n      ++index, ac0 +=6, ac1 +=3)\n  {\n    (*_diagsize0)[index] = ac0;\n    (*_diagsize1)[index] = ac1;\n  }\n\n}\n\n\n// convert _blockCSR to numerics structure\nvoid BlockCSRMatrix::convert()\n{\n  DEBUG_BEGIN(\"void BlockCSRMatrix::convert()\\n\");\n  _sparseBlockStructuredMatrix->blocknumber0 = _nr;\n  _sparseBlockStructuredMatrix->blocknumber1 = _nr;  // nc not always set\n  _sparseBlockStructuredMatrix->nbblocks = (*_blockCSR).nnz();\n  // Next copies: pointer links!!\n  _sparseBlockStructuredMatrix->blocksize0 =  _diagsize0->data();\n  _sparseBlockStructuredMatrix->blocksize1 =  _diagsize1->data(); // nr = nc\n\n  // boost\n  _sparseBlockStructuredMatrix->filled1 = (*_blockCSR).filled1();\n  _sparseBlockStructuredMatrix->filled2 = (*_blockCSR).filled2();\n  _sparseBlockStructuredMatrix->index1_data = _blockCSR->index1_data().begin();\n  if(_nr > 0)\n  {\n    _sparseBlockStructuredMatrix->index2_data = _blockCSR->index2_data().begin();\n    _sparseBlockStructuredMatrix->block =  _blockCSR->value_data().begin();\n  };\n  if(_sparseBlockStructuredMatrix->diagonal_blocks)\n  {\n    free(_sparseBlockStructuredMatrix->diagonal_blocks);\n    _sparseBlockStructuredMatrix->diagonal_blocks = nullptr;\n  }\n  //   // Loop through the non-null blocks\n  //   for (SpMatIt1 i1 = _blockCSR->begin1(); i1 != _blockCSR->end1(); ++i1)\n  //     {\n  //       for (SpMatIt2 i2 = i1.begin(); i2 != i1.end(); ++i2)\n  //  {\n  //    block[i] = *i2;\n  //  }\n  //     }\n  DEBUG_END(\"void BlockCSRMatrix::convert()\\n\");\n}\n\n// Display data\nvoid BlockCSRMatrix::display() const\n{\n  std::cout << \"----- Sparse Block Matrix with \"\n            << _nr << \" blocks in a row/col and \"\n            << _blockCSR->nnz()\n            << \" non-null blocks\" <<std::endl;\n  std::cout << \"filled1 (index of the last non empty line + 1):\" << _blockCSR->filled1() <<std::endl;\n  std::cout << \"filled2 (number of non null blocks):\" << _blockCSR->filled2() <<std::endl;\n  std::cout << \"_blockCSR->index1_data().size()\" << _blockCSR->index1_data().size() << std::endl;\n  print(_blockCSR->index1_data().begin(), _blockCSR->index1_data().end(),\"index1_data\", \"\\t\");\n\n  assert(_blockCSR->index2_data().size() >= _blockCSR->filled2());\n\n  std::cout << \"_blockCSR->index2_data().size()\" << _blockCSR->index2_data().size() << std::endl;\n  print(_blockCSR->index2_data().begin(), _blockCSR->index2_data().end(), \"index2_data (column number for each block)\", \"\\t\");\n\n  std::cout << \"last column number  \"<<   _blockCSR->index2_data()[_blockCSR->filled2()-1] <<  \" for block   \" << _blockCSR->filled2() << std::endl;\n  print(_diagsize0->begin(), _diagsize0->end(),\"_diagsize0 , sum of row sizes of the diagonal blocks\", \"\\t\");\n  print(_diagsize1->begin(), _diagsize1->end(),\"_diagsize1 , sum of col sizes of the diagonal blocks\", \"\\t\");\n}\n\nunsigned int BlockCSRMatrix::getNbNonNullBlocks() const\n{\n  return _blockCSR->nnz();\n};\n", "meta": {"hexsha": "050974b16dcd2f135fec37e95d978c90214f0dae", "size": 10749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/simulationTools/BlockCSRMatrix.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/simulationTools/BlockCSRMatrix.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/simulationTools/BlockCSRMatrix.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": 32.1826347305, "max_line_length": 148, "alphanum_fraction": 0.6671318262, "num_tokens": 3068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.05582313524415761, "lm_q1q2_score": 0.025735402021377373}}
{"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 rkf_integrator.hpp\n * @brief Integration of ODEs using the Runge-Kutta-Fehlberg method\n */\n\n#ifndef RKF_INTEGRATOR_H\n#define RKF_INTEGRATOR_H\n\n#include \"error.hpp\"\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nnamespace runge_kutta {\n\n/**\n * @class RKF_integrator\n * @brief Class for integrating ODEs using a Runge-Kutta-Fehlberg method\n *\n * This class makes use of the 8th order Runge-Kutta-Fehlberg algorithm\n * provided by the odeint library in Boost.\n */\nclass RKF_integrator {\npublic:\n   using Derivs = std::function<Eigen::ArrayXd(double, const Eigen::ArrayXd&)>;\n\n   /// Integrates the system over an interval\n   void operator()(double start, double end, Eigen::ArrayXd& pars,\n                   const Derivs& derivs, double tol) const;\nprivate:\n   class DisabledOdeintError : Error {\n   public:\n      explicit DisabledOdeintError(const std::string& msg_) : msg(msg_) {}\n      virtual ~DisabledOdeintError() = default;\n      virtual std::string what() const override { return msg; }\n   private:\n      std::string msg;\n   };\n\n   struct RKF_observer {\n      void operator()(const Eigen::ArrayXd&, double) const;\n   };\n};\n\n} // namespace runge_kutta\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "eb3d40cd0c3d184c48edfcf2af58432438de12fc", "size": 2062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/rkf_integrator.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/rkf_integrator.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/rkf_integrator.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.4571428571, "max_line_length": 79, "alphanum_fraction": 0.666343356, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.05184546481851975, "lm_q1q2_score": 0.025720215182519296}}
{"text": "/*\n * Copyright (c) 2019 Opticks Team. All Rights Reserved.\n *\n * This file is part of Opticks\n * (see https://bitbucket.org/simoncblyth/opticks).\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 <boost/math/constants/constants.hpp>\n\n#include \"NGLMExt.hpp\"\n#include \"GLMPrint.hpp\"\n#include \"NPY.hpp\"\n\n#include \"NQuad.hpp\"\n#include \"NBBox.hpp\"\n#include \"NTrianglesNPY.hpp\"\n#include \"NTesselate.hpp\"\n#include \"NTriangle.hpp\"\n\n#include \"NTris.hpp\"\n\n#include \"PLOG.hh\"\n\n#ifdef _MSC_VER\n// instanciations of 'NTrianglesNPY' raise warning:\n//    object allocated on the heap may not be aligned 16\n// https://github.com/g-truc/glm/issues/235\n// apparently fixed by 0.9.7.1 Release : currently on 0.9.6.3\n\n#pragma warning( disable : 4316 )\n#endif\n\n\nconst char* NTrianglesNPY::PLACEHOLDER = \"PLACEHOLDER\" ; \n\n\n\nNPY<float>* NTrianglesNPY::getTris() const \n{\n    return m_tris ; \n}\nNPY<float>* NTrianglesNPY::getNormals() const \n{\n    return m_normals ; \n}\n\nfloat NTrianglesNPY::maxdiff( const NTrianglesNPY* other, bool dump )\n{\n    return m_tris->maxdiff( other->getTris(), dump ); \n}\n\n\n\nvoid NTrianglesNPY::dump(const char* msg) const \n{\n    LOG(info) << \"NTrianglesNPY::dump\"\n              << \" tris \" << m_tris->getShapeString()\n              ;\n\n    m_tris->dump(msg);\n}\n\n\nvoid NTrianglesNPY::setPoly(const std::string& poly)\n{\n   m_poly = poly ; \n}\nconst std::string& NTrianglesNPY::getPoly()\n{\n   return m_poly ; \n}\n\n\n\nvoid NTrianglesNPY::setMessage(const std::string& msg)\n{\n   m_message = msg ; \n}\nconst std::string& NTrianglesNPY::getMessage()\n{\n   return m_message ; \n}\n\nbool NTrianglesNPY::hasMessage(const std::string& msg)\n{\n    return m_message.compare(msg) == 0 ; \n}\nbool NTrianglesNPY::isPlaceholder()\n{\n    return m_message.compare(PLACEHOLDER) == 0 ; \n}\n\n\n\n\n\n\n\nvoid NTrianglesNPY::setTransform(const glm::mat4& transform_)\n{\n    m_transform = transform_ ; \n}\nglm::mat4 NTrianglesNPY::getTransform()\n{\n    return m_transform ; \n}\n\n\n\nNTrianglesNPY::NTrianglesNPY(const NTriSource* tris)\n   :\n   m_tris(NPY<float>::make(0,3,3)),\n   m_normals(NPY<float>::make(0,3,3)),\n   m_transform(1.0f) \n{\n    glm::uvec3 t ; \n    glm::vec3 a ; \n    glm::vec3 b ; \n    glm::vec3 c ; \n    \n    unsigned ntri = tris->get_num_tri();\n    for(unsigned i=0 ; i < ntri ; i++)\n    {   \n        tris->get_tri(i,t,a,b,c );\n        add(a,b,c); \n    }\n}\n\n\nNTrianglesNPY::NTrianglesNPY() \n   :\n   m_tris(NPY<float>::make(0,3,3)),\n   m_normals(NPY<float>::make(0,3,3)),\n   m_transform(1.0f) \n{\n}\n\nNTrianglesNPY::NTrianglesNPY(NPY<float>* tris, NPY<float>* normals)\n   :\n   m_tris(tris),\n   m_normals(normals),\n   m_transform(1.0f) \n{\n}\n\nNTrianglesNPY* NTrianglesNPY::transform(glm::mat4& m)\n{\n    NPY<float>* tbuf = m_tris->transform(m);\n\n    NTrianglesNPY* t = new NTrianglesNPY(tbuf);\n\n    return t ; \n}\n\nNTrianglesNPY* NTrianglesNPY::subdivide(unsigned int nsubdiv)\n{\n    NTesselate* tess = new NTesselate(m_tris);\n\n    tess->subdivide(nsubdiv);\n\n    NPY<float>* tbuf = tess->getBuffer();\n\n    NTrianglesNPY* t = new NTrianglesNPY(tbuf);\n\n    t->setTransform( getTransform() );\n\n    return t ;\n}\n\n\n\nunsigned int NTrianglesNPY::getNumTriangles()\n{\n    return m_tris->getNumItems();\n}\n\n\nvoid NTrianglesNPY::add(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c, const glm::vec3& d)\n{\n   /*\n         a------d\n         |    . | \n         |  .   |\n         |.     |\n         b------c\n\n   */\n    add(a,b,d);\n    add(d,b,c);\n}\n\nvoid NTrianglesNPY::add(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c)\n{\n    ntriangle t(a,b,c);\n    add(t);\n}\n\n\nvoid NTrianglesNPY::addNormal(const glm::vec3& nrm )  // in triplicate\n{\n    int n = 3*3 ; \n    float* vals = new float[n] ;\n    for(int i=0 ; i < 3 ; i++)  \n    {\n       vals[i*3+0] = nrm.x ;\n       vals[i*3+1] = nrm.y ;\n       vals[i*3+2] = nrm.z ;\n    }\n    m_normals->add(vals, n);\n    delete [] vals ; \n}\n\n\nvoid NTrianglesNPY::addNormal(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c ) \n{\n    float vals[9] ;\n\n    vals[0*3 + 0 ] = a.x ; \n    vals[0*3 + 1 ] = a.y ; \n    vals[0*3 + 2 ] = a.z ;\n\n    vals[1*3 + 0 ] = b.x ; \n    vals[1*3 + 1 ] = b.y ; \n    vals[1*3 + 2 ] = b.z ;\n  \n    vals[2*3 + 0 ] = c.x ; \n    vals[2*3 + 1 ] = c.y ; \n    vals[2*3 + 2 ] = c.z ;\n \n    m_normals->add(vals, 9);\n}\n\n\n\n\nvoid NTrianglesNPY::add(const ntriangle& t )\n{\n    unsigned int n = 3*3 ; \n    float* vals = new float[n] ;\n    t.copyTo(vals); \n    m_tris->add(vals, n);\n    delete [] vals ; \n}\n\n\nvoid NTrianglesNPY::add(NTrianglesNPY* other )\n{\n    m_tris->add(other->getTris());\n}\n\nnbbox* NTrianglesNPY::findBBox()\n{\n    NPY<float>* buf = getTris();\n    assert(buf && buf->hasItemShape(3,3));\n    unsigned nitem = buf->getShape(0);\n    nbbox* bb = NULL ; \n    if(nitem > 0)\n    {\n        ntrange3<float> r = buf->minmax3(); \n        bb = new nbbox ;  \n        bb->min.x = r.min.x ; \n        bb->min.y = r.min.y ; \n        bb->min.z = r.min.z ;\n     \n        bb->max.x = r.max.x ; \n        bb->max.y = r.max.y ; \n        bb->max.z = r.max.z ;\n    }\n    return bb ; \n}\n\n\n/* for icosahedron \n\n* 20 faces (triangular)\n* 12 verts\n* 30 edges\n\n*/\n#define CZ (0.89442719099991)   /*  2/sqrt(5) */\n#define SZ (0.44721359549995)   /*  1/sqrt(5) */\n#define C1 (0.951056516)        /* cos(18),  */\n#define S1 (0.309016994)        /* sin(18) */\n#define C2 (0.587785252)        /* cos(54),  */\n#define S2 (0.809016994)        /* sin(54) */\n#define X1 (C1*CZ)\n#define Y1 (S1*CZ)\n#define X2 (C2*CZ)\n#define Y2 (S2*CZ)\n\nconst glm::vec3 NTrianglesNPY::Ip0 = glm::vec3(0,0,1.) ;\nconst glm::vec3 NTrianglesNPY::Ip1 = glm::vec3(-X2,-Y2,SZ) ;\nconst glm::vec3 NTrianglesNPY::Ip2 = glm::vec3( X2,-Y2,SZ) ;\nconst glm::vec3 NTrianglesNPY::Ip3 = glm::vec3( X1, Y1,SZ) ;\nconst glm::vec3 NTrianglesNPY::Ip4 = glm::vec3(  0, CZ,SZ) ;\nconst glm::vec3 NTrianglesNPY::Ip5 = glm::vec3(-X1, Y1,SZ) ;\n\nconst glm::vec3 NTrianglesNPY::Im0 = glm::vec3(-X1, -Y1,-SZ) ;\nconst glm::vec3 NTrianglesNPY::Im1 = glm::vec3(  0, -CZ,-SZ) ;\nconst glm::vec3 NTrianglesNPY::Im2 = glm::vec3( X1, -Y1,-SZ) ;\nconst glm::vec3 NTrianglesNPY::Im3 = glm::vec3( X2,  Y2,-SZ) ;\nconst glm::vec3 NTrianglesNPY::Im4 = glm::vec3(-X2,  Y2,-SZ) ;\nconst glm::vec3 NTrianglesNPY::Im5 = glm::vec3(0,0,-1.) ;\n\n\nNTrianglesNPY* NTrianglesNPY::icosahedron()\n{\n    NTrianglesNPY* tris = new NTrianglesNPY();\n\n    /* front pole */\n    tris->add(Ip0, Ip1, Ip2);\n    tris->add(Ip0, Ip5, Ip1);\n    tris->add(Ip0, Ip4, Ip5);\n    tris->add(Ip0, Ip3, Ip4);\n    tris->add(Ip0, Ip2, Ip3);\n\n    /* mid */\n    tris->add(Ip1, Im0, Im1);\n    tris->add(Im0, Ip1, Ip5);\n    tris->add(Ip5, Im4, Im0);\n    tris->add(Im4, Ip5, Ip4);\n    tris->add(Ip4, Im3, Im4);\n    tris->add(Im3, Ip4, Ip3);\n    tris->add(Ip3, Im2, Im3);\n    tris->add(Im2, Ip3, Ip2);\n    tris->add(Ip2, Im1, Im2);\n    tris->add(Im1, Ip2, Ip1);\n\n    /* back pole */\n    tris->add(Im3, Im2, Im5);\n    tris->add(Im4, Im3, Im5);\n    tris->add(Im0, Im4, Im5);\n    tris->add(Im1, Im0, Im5);\n    tris->add(Im2, Im1, Im5);\n\n    return tris ;\n}\n\n\n\n\nNTrianglesNPY* NTrianglesNPY::from_indexed( NPY<float>* vtx, NPY<unsigned>* idx )\n{\n    assert( vtx->hasShape( -1, 3) && idx->hasShape(-1,3) );\n    // each idx entry of 3 unsigned ints points to three vertices of the triangle\n     \n    unsigned nvtx = vtx->getShape(0) ; \n    unsigned ntri = idx->getShape(0) ; \n\n    LOG(info) << \" idx \" << idx->getShapeString() ; \n    LOG(info) << \" vtx \" << vtx->getShapeString() ; \n\n    NTrianglesNPY* tris = new NTrianglesNPY();\n\n    for(unsigned i=0 ; i < ntri ; i++)\n    {\n        unsigned v0 = idx->getValue( i, 0, 0,  0 );\n        unsigned v1 = idx->getValue( i, 0, 0,  1 );\n        unsigned v2 = idx->getValue( i, 0, 0,  2 );\n \n        assert( v0 < nvtx );\n        assert( v1 < nvtx );\n        assert( v2 < nvtx );\n\n        glm::vec3 vtx0 ; \n        vtx0.x = vtx->getValue( v0, 0, 0,  0 );\n        vtx0.y = vtx->getValue( v0, 0, 0,  1 );\n        vtx0.z = vtx->getValue( v0, 0, 0,  2 );\n\n        glm::vec3 vtx1 ; \n        vtx1.x = vtx->getValue( v1, 0, 0,  0 );\n        vtx1.y = vtx->getValue( v1, 0, 0,  1 );\n        vtx1.z = vtx->getValue( v1, 0, 0,  2 );\n\n        glm::vec3 vtx2 ; \n        vtx2.x = vtx->getValue( v2, 0, 0,  0 );\n        vtx2.y = vtx->getValue( v2, 0, 0,  1 );\n        vtx2.z = vtx->getValue( v2, 0, 0,  2 );\n\n        tris->add( vtx0, vtx1, vtx2 );\n    }\n    return tris ;\n}\n\nvoid NTrianglesNPY::to_vtxidx(NVtxIdx& vtxidx) \n{\n    assert( m_tris->hasShape(-1,3,3) );  // items with 3*3 float for each tri\n    unsigned ntri = m_tris->getShape(0) ; \n\n    NPY<float>* vtx = NPY<float>::copy( m_tris ) ;\n    vtx->reshape( ntri*3 , 3 );\n\n    NPY<unsigned>* idx = NPY<unsigned>::make( ntri, 3 ) ;\n    idx->zero();\n\n    vtxidx.vtx = vtx ;   // duplicate vertices for each use in a face     \n    vtxidx.idx = idx ; \n\n\n    for(unsigned i=0 ; i < ntri ; i++)\n    {\n        idx->setValue( i, 0, 0,  0,  i*3+0  );\n        idx->setValue( i, 0, 0,  1,  i*3+1  );\n        idx->setValue( i, 0, 0,  2,  i*3+2  );\n    }\n}\n\n\n\nconst glm::vec3 NTrianglesNPY::PX = glm::vec3(1,0,0) ;\nconst glm::vec3 NTrianglesNPY::PY = glm::vec3(0,1,0) ;\nconst glm::vec3 NTrianglesNPY::PZ = glm::vec3(0,0,1) ;\nconst glm::vec3 NTrianglesNPY::MX = glm::vec3(-1,0,0) ;\nconst glm::vec3 NTrianglesNPY::MY = glm::vec3(0,-1,0) ;\nconst glm::vec3 NTrianglesNPY::MZ = glm::vec3(0,0,-1) ;\n\nNTrianglesNPY* NTrianglesNPY::octahedron()\n{\n    NTrianglesNPY* tris = new NTrianglesNPY();\n\n    // PZ pyramid\n    tris->add(PX,PZ,MY);\n    tris->add(MY,PZ,MX);\n    tris->add(MX,PZ,PY);\n    tris->add(PY,PZ,PX);\n\n    // MZ pyramid\n    tris->add(PX,MY,MZ);\n    tris->add(MY,MX,MZ);\n    tris->add(MX,PY,MZ);\n    tris->add(PY,PX,MZ);\n\n    return tris ;\n}\n\nNTrianglesNPY* NTrianglesNPY::hemi_octahedron()\n{\n    NTrianglesNPY* tris = new NTrianglesNPY();\n\n    // PZ pyramid\n    tris->add(PX,PZ,MY);\n    tris->add(MY,PZ,MX);\n    tris->add(MX,PZ,PY);\n    tris->add(PY,PZ,PX);\n\n    return tris ;\n}\n\n\n\n\n\nNTrianglesNPY* NTrianglesNPY::sphere(unsigned int n_polar, unsigned int n_azimuthal) \n{\n    glm::vec4 param(-1.f, 1.f, 0.f, 1.f);\n    return sphere(param, n_polar, n_azimuthal);\n}\n\n\nvoid NTrianglesNPY::setTransform(const glm::vec3& scale, const glm::vec3& translate)\n{\n    glm::mat4 m_scale = glm::scale(glm::mat4(1.0f), scale);\n    glm::mat4 m_translate = glm::translate(glm::mat4(1.0f), translate);\n    glm::mat4 mat = m_translate * m_scale ; \n\n    //print(mat, \"NTrianglesNPY::setTransform\");\n\n    setTransform(mat);\n}\n\n\n\nNTrianglesNPY* NTrianglesNPY::sphere(glm::vec4& param, unsigned int n_polar, unsigned int n_azimuthal) \n{\n    float ctmin = param.x ; \n    float ctmax = param.y ; \n    float zpos  = param.z ; \n    float radius = param.w ; \n\n    // unit sphere at origin \n    NTris* ts = NTris::make_sphere( n_polar, n_azimuthal, ctmin, ctmax );\n\n    NTrianglesNPY* tris = new NTrianglesNPY(ts); \n\n    glm::vec3 scale(radius);\n    glm::vec3 translate(0,0,zpos);\n    tris->setTransform(scale, translate);   \n\n    // dont apply the transform yet, as whilst sphere at origin\n    // can easily get normals from the positions\n\n    return tris ;\n}\n\n\n\n/*\n         p0     p1\n\n     t0  x00----x10\n          |   .  |\n          | .    |\n     t1  x01----x11\n\n\n      t = 0  => t0 = 0 \n               x00 x10 degenerate (0,0,1)  \n \n      t = n_polar - 1 => t1 = pi   \n               x01 x11 degenerate (0,0,-1)  \n\n*/\n\n\n\n\n\nNTrianglesNPY* NTrianglesNPY::disk(glm::vec4& param, unsigned int n_azimuthal) \n{\n    float ct = param.x ; \n    double ct0, st0 ;\n    sincos_<double>(acos(ct), st0, ct0 ); \n    float pi = boost::math::constants::pi<float>() ;\n\n    NTrianglesNPY* tris = new NTrianglesNPY();\n    for(unsigned int p=0 ; p < n_azimuthal ; p++)\n    {\n        float p0 = 2.0f*pi*float(p)/n_azimuthal ;\n        float p1 = 2.0f*pi*float(p+1)/n_azimuthal ;\n\n        double sp0,sp1,cp0,cp1 ;\n        sincos_<double>(p0, sp0, cp0 ); \n        sincos_<double>(p1, sp1, cp1 ); \n\n        glm::vec3 x0(   st0*cp0,  st0*sp0,   ct0 );\n        glm::vec3 x1(   st0*cp1,  st0*sp1,   ct0 );\n        glm::vec3 xc(         0,        0,   ct0 );\n\n        tris->add(x0,x1,xc); // winding order directs normal along -z \n    }\n    return tris ; \n}\n\n\n\n\n\n\n\nconst glm::vec3 NTrianglesNPY::PXPYPZ = glm::vec3(1,1,1) ;\nconst glm::vec3 NTrianglesNPY::PXPYMZ = glm::vec3(1,1,-1) ;\nconst glm::vec3 NTrianglesNPY::PXMYPZ = glm::vec3(1,-1,1) ;\nconst glm::vec3 NTrianglesNPY::PXMYMZ = glm::vec3(1,-1,-1) ;\n\nconst glm::vec3 NTrianglesNPY::MXPYPZ = glm::vec3(-1,1,1) ;\nconst glm::vec3 NTrianglesNPY::MXPYMZ = glm::vec3(-1,1,-1) ;\nconst glm::vec3 NTrianglesNPY::MXMYPZ = glm::vec3(-1,-1,1) ;\nconst glm::vec3 NTrianglesNPY::MXMYMZ = glm::vec3(-1,-1,-1) ;\n\n\nNTrianglesNPY* NTrianglesNPY::cube()\n{\n    NTrianglesNPY* tris = new NTrianglesNPY();\n\n    tris->add(PXPYPZ, MXPYPZ, MXMYPZ, PXMYPZ);    // PZ face\n    tris->add(PXPYPZ, PXMYPZ, PXMYMZ, PXPYMZ);    // PX face\n    tris->add(PXPYPZ, PXPYMZ, MXPYMZ, MXPYPZ);    // PY face   \n\n    tris->add(MXMYMZ, PXMYMZ, PXPYMZ, MXPYMZ);    // MZ face  \n    tris->add(MXMYMZ, MXPYMZ, MXPYPZ, MXMYPZ);    // MX face\n    tris->add(MXMYMZ, MXMYPZ, PXMYPZ, PXMYMZ);    // MY face\n\n    return tris ; \n}\n\n\n\n\nNTrianglesNPY* NTrianglesNPY::box(const nbbox& bb)\n{\n    NTrianglesNPY* tris = new NTrianglesNPY();\n   \n    glm::vec3 P(bb.max.x, bb.max.y, bb.max.z );\n    glm::vec3 M(bb.min.x, bb.min.y, bb.min.z );\n\n    glm::vec3 _PXPYPZ( P.x, P.y, P.z ); \n    glm::vec3 _PXPYMZ( P.x, P.y, M.z ); \n    glm::vec3 _PXMYPZ( P.x, M.y, P.z );\n    glm::vec3 _PXMYMZ( P.x, M.y, M.z );\n\n    glm::vec3 _MXPYPZ( M.x, P.y, P.z );\n    glm::vec3 _MXPYMZ( M.x, P.y, M.z );\n    glm::vec3 _MXMYPZ( M.x, M.y, P.z );\n    glm::vec3 _MXMYMZ( M.x, M.y, M.z ) ;\n\n    tris->add(_PXPYPZ, _MXPYPZ, _MXMYPZ, _PXMYPZ);    // PZ face\n    tris->add(_PXPYPZ, _PXMYPZ, _PXMYMZ, _PXPYMZ);    // PX face\n    tris->add(_PXPYPZ, _PXPYMZ, _MXPYMZ, _MXPYPZ);    // PY face   \n\n    tris->add(_MXMYMZ, _PXMYMZ, _PXPYMZ, _MXPYMZ);    // MZ face  \n    tris->add(_MXMYMZ, _MXPYMZ, _MXPYPZ, _MXMYPZ);    // MX face\n    tris->add(_MXMYMZ, _MXMYPZ, _PXMYPZ, _PXMYMZ);    // MY face\n\n    return tris ; \n}\n\n\n\n\n\n\n\nNTrianglesNPY* NTrianglesNPY::prism(const glm::vec4& param)\n{\n/*\n::\n\n   .                \n               \n               A'\n                    A  (0,height)\n                   /|\\\n                  / | \\\n                 /  |  \\\n                /   h   \\\n               /    |    \\ (x,y)   \n         L'   M     |     N   \n             /      |      \\\n            L-------O-------R   \n                               \n     (-hwidth,0)  (0,0)    (hwidth, 0)     \n\n*/\n\n    // hmm how to avoid duplication between here and hemi-pmt.cu/make_prism\n    float angle = param.x > 0.f ? param.x : 60.f ; \n    float height = param.y > 0.f ? param.y : param.w  ;\n    float depth = param.z > 0.f ? param.z : param.w ;\n\n    float pi = boost::math::constants::pi<float>() ;\n    float hwidth = height*tan((pi/180.f)*angle/2.0f) ;      \n\n    float ymax =  height/2.0f ; \n    float ymin = -height/2.0f ; \n\n    glm::vec3 apex_near(0.f,     ymax, depth/2.f );\n    glm::vec3 apex_far( 0.f,     ymax, -depth/2.f );\n\n    glm::vec3 left_near(-hwidth,  ymin, depth/2.f);    \n    glm::vec3 left_far(-hwidth,   ymin, -depth/2.f);    \n\n    glm::vec3 right_near( hwidth, ymin, depth/2.f);    \n    glm::vec3 right_far( hwidth,  ymin, -depth/2.f);    \n\n    NTrianglesNPY* tris = new NTrianglesNPY();\n\n    tris->add( apex_near, apex_far, left_far, left_near );\n    tris->add( apex_near, right_near,  right_far,  apex_far );\n    tris->add( left_near, left_far, right_far, right_near );\n    tris->add( apex_near, left_near, right_near );\n    tris->add( apex_far,  right_far, left_far );\n\n    return tris ; \n}\n\n\n\n", "meta": {"hexsha": "94fe083cf3502c6086b864cd0e6dd7dcf9d621dc", "size": 16107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "npy/NTrianglesNPY.cpp", "max_stars_repo_name": "hanswenzel/opticks", "max_stars_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-07-05T02:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:52:44.000Z", "max_issues_repo_path": "npy/NTrianglesNPY.cpp", "max_issues_repo_name": "hanswenzel/opticks", "max_issues_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npy/NTrianglesNPY.cpp", "max_forks_repo_name": "hanswenzel/opticks", "max_forks_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T20:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T07:42:21.000Z", "avg_line_length": 23.6519823789, "max_line_length": 103, "alphanum_fraction": 0.5750294903, "num_tokens": 5957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.054198724094297254, "lm_q1q2_score": 0.02561884133328405}}
{"text": "#ifndef JHMI_PT3_HPP_NRC_20141031\n#define JHMI_PT3_HPP_NRC_20141031\n\n#include <boost/functional/hash.hpp>\n#include <boost/units/units_fwd.hpp>\n#include <cmath>\n#include <iostream>\n#include <type_traits>\n\nnamespace jhmi {\n  namespace jhmi_detail {\n    template <typename Src, typename Dst>\n    struct is_lossy_convertible\n    {\n      static const bool value =  (std::is_integral<Dst>::value && !std::is_integral<Src>::value)\n        || (std::is_integral<Src>::value && !std::is_integral<Dst>::value\n            && sizeof(Src) == sizeof(Dst))\n        || sizeof(Src) > sizeof(Dst);\n    };\n\n    template <typename Src, typename Dst>\n    struct is_non_narrowing_conversion\n    {\n      static const bool value = std::is_convertible<Src,Dst>::value\n        && !((std::is_arithmetic<Src>::value && std::is_arithmetic<Dst>::value)\n             || is_lossy_convertible<Src,Dst>::value);\n    };\n\n  }//end jhmi_detail\n\n  template <typename T> struct pt3\n  {\n    using type = T;\n    constexpr pt3() : x(), y(), z() {}\n    constexpr pt3(T x, T y, T z) : x(x),y(y),z(z) {}\n\n    template <typename U>\n    constexpr pt3(pt3<U> const& u, typename std::enable_if<\n        jhmi_detail::is_non_narrowing_conversion<U,T>::value>::type* = nullptr)\n      : x(u.x),\n        y(u.y),\n        z(u.z)\n    {}\n    template <typename U>\n    constexpr explicit pt3(pt3<U> const& u, typename std::enable_if<\n        !jhmi_detail::is_non_narrowing_conversion<U,T>::value>::type* = nullptr)\n      : x(static_cast<T>(u.x)),\n        y(static_cast<T>(u.y)),\n        z(static_cast<T>(u.z))\n    {}\n\n    constexpr pt3<T>& operator+=(pt3<T> const& rhs)\n    { x += rhs.x; y += rhs.y; z += rhs.z; return *this; }\n    constexpr pt3<T>& operator-=(pt3<T> const& rhs)\n    { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; }\n\n    T x, y, z;\n  };\n  template <typename T> constexpr auto operator+(pt3<T> const& pt)\n  { return pt; }\n  template <typename T> constexpr auto operator-(pt3<T> const& pt)\n  { return pt3<T>{-pt.x, -pt.y, -pt.z}; }\n  template <typename T, typename U> constexpr auto operator+(pt3<T> const& lhs, pt3<U> const& rhs)\n  { return pt3<decltype(lhs.x+rhs.x)>{lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z}; }\n  template <typename T, typename U> constexpr auto operator-(pt3<T> const& lhs, pt3<U> const& rhs)\n  { return pt3<decltype(lhs.x-rhs.x)>{lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z}; }\n  template <typename T, typename U> constexpr auto operator*(pt3<T> const& lhs, U rhs)\n  { return pt3<decltype(lhs.x*rhs)>{lhs.x * rhs, lhs.y * rhs, lhs.z * rhs}; }\n  template <typename T, typename U> constexpr auto operator*(U lhs, pt3<T> const& rhs)\n  { return pt3<decltype(lhs*rhs.x)>{lhs * rhs.x, lhs * rhs.y, lhs * rhs.z}; }\n  template <typename T, typename D, typename S> constexpr auto operator*(pt3<T> const& lhs, boost::units::unit<D,S> rhs)\n  { return pt3<decltype(lhs.x*rhs)>{lhs.x * rhs, lhs.y * rhs, lhs.z * rhs}; }\n  template <typename T, typename D, typename S> constexpr auto operator*(boost::units::unit<D,S> lhs, pt3<T> const& rhs)\n  { return pt3<decltype(lhs*rhs.x)>{lhs * rhs.x, lhs * rhs.y, lhs * rhs.z}; }\n  template <typename T, typename U> constexpr auto operator/(pt3<T> const& lhs, U rhs)\n  { return pt3<decltype(lhs.x/rhs)>{lhs.x / rhs, lhs.y / rhs, lhs.z / rhs}; }\n  template <typename T, typename D, typename S> constexpr auto operator/(pt3<T> const& lhs, boost::units::unit<D,S> rhs)\n  { return pt3<decltype(lhs.x/rhs)>{lhs.x / rhs, lhs.y / rhs, lhs.z / rhs}; }\n  template <typename T> constexpr auto operator==(pt3<T> const& lhs, pt3<T> const& rhs)\n  { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; }\n  template <typename T> constexpr auto operator!=(pt3<T> const& lhs, pt3<T> const& rhs)\n  { return !(lhs == rhs); }\n  template <typename T> constexpr bool operator<(pt3<T> const& lhs, pt3<T> const& rhs)\n  { return lhs.x < rhs.x || (lhs.x == rhs.x && (lhs.y < rhs.y || (lhs.y == rhs.y && lhs.z < rhs.z))); }\n  template <typename T> std::ostream& operator<<(std::ostream& out, pt3<T> const& pt)\n  { out << '[' << pt.x << ',' << pt.y << ',' << pt.z << ']'; return out; }\n  template <typename T> std::size_t hash_value(pt3<T> const& pt) {\n    std::size_t seed = 0;\n    boost::hash_combine(seed, pt.x);\n    boost::hash_combine(seed, pt.y);\n    boost::hash_combine(seed, pt.z);\n    return seed;\n  }\n\n  template <typename T> constexpr auto abs(pt3<T> const& v)\n  { using std::abs; return pt3<T>{abs(v.x), abs(v.y), abs(v.z)}; }\n  template <typename T> constexpr auto ceil(pt3<T> const& v)\n  { using std::ceil; return pt3<T>{ceil(v.x), ceil(v.y), ceil(v.z)}; }\n  template <typename T> constexpr auto cross(pt3<T> const& lhs, pt3<T> const& rhs) {\n    return pt3<T>{lhs.y * rhs.z - lhs.z * rhs.y,\n                  lhs.z * rhs.x - lhs.x * rhs.z,\n                  lhs.x * rhs.y - lhs.y * rhs.x};\n  }\n  //Overloaded since we're losing precision with normalizing code.\n  template <typename T, typename U> constexpr auto cross(pt3<boost::units::quantity<T,U>> const& lhs, pt3<boost::units::quantity<T,U>> const& rhs) {\n    return pt3<boost::units::quantity<T,U>>{\n      boost::units::quantity<T,U>::from_value(lhs.y.value() * rhs.z.value() - lhs.z.value() * rhs.y.value()),\n      boost::units::quantity<T,U>::from_value(lhs.z.value() * rhs.x.value() - lhs.x.value() * rhs.z.value()),\n      boost::units::quantity<T,U>::from_value(lhs.x.value() * rhs.y.value() - lhs.y.value() * rhs.x.value())};\n  }\n  template <typename T> auto distance(pt3<T> const& pt)\n  { using std::sqrt; return sqrt(distance_squared(pt)); }\n  template <typename T> constexpr auto distance_squared(pt3<T> const& pt)\n  { return pt.x * pt.x + pt.y * pt.y + pt.z * pt.z; }\n  template <typename T> constexpr auto distance_squared(pt3<T> const& lhs, pt3<T> const& rhs)\n  { return distance_squared(lhs - rhs); }\n  template <typename T, typename U> constexpr auto dot(pt3<T> const& lhs, pt3<U> const& rhs)\n  { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; }\n  template <typename T, typename U> constexpr auto element_multiply(pt3<T> const& lhs, pt3<U> const& rhs) {\n    return pt3<decltype(lhs.x * rhs.x)>{lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z};\n  }\n  template <typename T, typename U> constexpr auto element_divide(pt3<T> const& lhs, pt3<U> const& rhs) {\n    return pt3<decltype(lhs.x / rhs.x)>{lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z};\n  }\n  template <typename T, typename U> constexpr auto element_modulus(pt3<T> const& lhs, pt3<U> const& rhs) {\n    return pt3<decltype(lhs.x % rhs.x)>{lhs.x % rhs.x, lhs.y % rhs.y, lhs.z % rhs.z};\n  }\n  template <typename T> auto element_max(pt3<T> const& lhs, pt3<T> const& rhs) {\n    return pt3<T>{std::max(lhs.x, rhs.x), std::max(lhs.y, rhs.y), std::max(lhs.z, rhs.z)};\n  }\n  template <typename T> auto element_min(pt3<T> const& lhs, pt3<T> const& rhs) {\n    return pt3<T>{std::min(lhs.x, rhs.x), std::min(lhs.y, rhs.y), std::min(lhs.z, rhs.z)};\n  }\n  template <typename T> pt3<T> floor(pt3<T> const& pt)\n  { using std::floor; return {floor(pt.x), floor(pt.y), floor(pt.z)}; }\n  template <typename T> auto normalize(pt3<T> const& pt)\n  { return pt / distance(pt); }\n  template <typename T> auto round(pt3<T> const& pt)\n  { using std::round; return pt3<T>{round(pt.x), round(pt.y), round(pt.z)}; }\n  template <typename U, typename T> auto round_to(pt3<T> const& pt)\n  { using std::lround; return pt3<U>(lround(pt.x), lround(pt.y), lround(pt.z)); }\n\n  typedef pt3<int> int3;\n  typedef pt3<float> flt3;\n  typedef pt3<double> dbl3;\n  typedef pt3<long double> ldb3;\n}//jhmi\n#endif\n", "meta": {"hexsha": "9d0ad0161fd1c2392a686ed934d3c1fb61475594", "size": 7493, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/pt3.hpp", "max_stars_repo_name": "ncrookston/liver_source", "max_stars_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utility/pt3.hpp", "max_issues_repo_name": "ncrookston/liver_source", "max_issues_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utility/pt3.hpp", "max_forks_repo_name": "ncrookston/liver_source", "max_forks_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.288590604, "max_line_length": 148, "alphanum_fraction": 0.6273855599, "num_tokens": 2311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05108273587359001, "lm_q1q2_score": 0.025541367936795005}}
{"text": "// Copyright (C) 2019 Maciej Drwal\n// \n// Permission is granted to copy and distribute verbatim copies and modified\n// versions of this file, provided that the copyright notice and this permission\n// notice are preserved on all copies and modified versions of this file.\n// \n\n#include <iostream>\n\n#include <boost/spirit/home/x3.hpp>\n\n#include \"parser.h\"\n#include \"simplex.h\"\n#include \"utils.h\"\n\nstruct ParserState \n{\n    ParserState(LinearProgram& _lp) : lp(_lp), var_coeff_cache(0.0), sign_cache(1.0), label_cache(\"\") {}\n\n    LinearProgram& lp;\n    double var_coeff_cache;\n    double sign_cache;\n    std::string label_cache;\n};\n\nnamespace x3 = boost::spirit::x3;\nnamespace ascii = boost::spirit::x3::ascii;\n\nnamespace parser \n{\n    using x3::double_;\n    using x3::eoi;\n    using x3::lexeme;\n    using x3::lit;\n    using x3::no_case;\n    using x3::skip;\n\n    using ascii::alnum;\n    using ascii::alpha;\n    using ascii::char_;\n    using ascii::space;\n\n    // Semantic actions definitions\n    auto set_minimize       = [](auto& ctx) { _val(ctx).lp.set_sense('m'); };\n    auto set_maximize       = [](auto& ctx) { _val(ctx).lp.set_sense('M'); };\n    auto set_obj_label      = [](auto& ctx) { _val(ctx).lp.set_objective_label(_attr(ctx)); };\n    auto add_obj_fun_coeff  = [](auto& ctx) { _val(ctx).var_coeff_cache = _attr(ctx); };\n    auto add_obj_fun_var    = [](auto& ctx) \n    {\n        // create new variable and store associated obj.fun. coefficient\n        auto var_name = _attr(ctx);\n        if (_val(ctx).lp.has_variable(var_name)) {\n            throw \"Parser: variable already defined in objective function.\";\n        }\n        _val(ctx).lp.add_variable(var_name); \n        _val(ctx).lp.objective_name_coeff[var_name] = \n            _val(ctx).sign_cache * _val(ctx).var_coeff_cache;\n    };\n    auto neg_var_coeff      = [](auto& ctx) { _val(ctx).sign_cache = -1; };\n    auto term_parsed        = [](auto& ctx) \n    { \n        _val(ctx).sign_cache = 1;\n        _val(ctx).var_coeff_cache = 1; \n    };\n    auto add_obj_fun_const  = [](auto& ctx) { _val(ctx).lp.set_obj_value_shift(_attr(ctx)); };\n\n    auto set_constr_label   = [](auto& ctx) \n    {\n        // create labeled constraint\n        const auto& constraint = Constraint();\n        _val(ctx).label_cache = _attr(ctx); \n        _val(ctx).lp.constraints.emplace(_attr(ctx), constraint);\n    };\n    auto add_constr_coeff   = [](auto& ctx) { _val(ctx).var_coeff_cache = _attr(ctx); };\n    auto add_constr_var     = [](auto& ctx) \n    {\n        auto& constr_label = _val(ctx).label_cache;\n        if (constr_label == \"\") {\n            // no label was defined by user; create new constraint with default label\n            const auto& constraint = Constraint();\n            constr_label = std::string(\"CONSTR\") + tostr<size_t>(_val(ctx).lp.constraints.size());\n            _val(ctx).label_cache = constr_label;\n            _val(ctx).lp.constraints.emplace(constr_label, constraint);\n        }\n\n        auto var_name = _attr(ctx);\n\n        if (_val(ctx).lp.constraints[constr_label].name_coeff.count(var_name) != 0) {\n            throw (std::string(\"Parser: variable already defined in constraint\") + constr_label).c_str();\n        }\n\n        if (!_val(ctx).lp.has_variable(var_name)) {\n            // adding new variable via constraint\n            _val(ctx).lp.add_variable(var_name);\n        }\n\n        auto coeff = _val(ctx).var_coeff_cache;\n        auto sign  = _val(ctx).sign_cache;\n        _val(ctx).lp.constraints[constr_label].name_coeff[var_name] = sign * coeff;\n    };\n\n    auto add_constr_type = [](auto& ctx) \n    { \n        _val(ctx).lp.constraints[_val(ctx).label_cache].type = _attr(ctx);\n    };\n    auto add_constr_rhs  = [](auto& ctx) \n    {\n        double _rhs = _attr(ctx);\n        _val(ctx).lp.constraints[_val(ctx).label_cache].rhs = _rhs;\n        auto op = _val(ctx).lp.constraints[_val(ctx).label_cache].type;\n        if ((op == '<' && _rhs < 0.0) ||\n            (op == '>' && _rhs > 0.0) ||\n            (op == '=')) _val(ctx).lp.set_all_inequalities(false);\n        _val(ctx).label_cache = \"\";\n    };\n\n    auto add_lb_constr   = [](auto& ctx) \n    { \n        auto lb = _val(ctx).var_coeff_cache;  // now it contains LB\n        auto var_name = _attr(ctx);\n        _val(ctx).label_cache = var_name;  // store var_name, in case we need to add UB\n        if (_isfloatzero(lb)) return;\n        _val(ctx).lp.var_lbnd[var_name] = lb;\n    };\n    auto add_ub_constr     = [](auto& ctx)\n    {\n        auto var_name = _val(ctx).label_cache;    // now it contains var_name\n        auto ub = _attr(ctx);\n        _val(ctx).lp.var_ubnd[var_name] = ub;\n    };\n    auto store_ub_var_name = [](auto& ctx) { _val(ctx).label_cache = _attr(ctx); };\n    auto add_inf_lb        = [](auto& ctx) \n    {\n        auto lb = std::numeric_limits<double>::min();\n        _val(ctx).var_coeff_cache = lb; \n    };\n    auto add_inf_ub        = [](auto& ctx)\n    {\n        auto var_name = _val(ctx).label_cache;    // now it contains var_name\n        auto ub = std::numeric_limits<double>::max();\n        _val(ctx).lp.var_ubnd[var_name] = ub;\n    };\n\n    auto print_attr = [](auto& ctx) { std::cout << _attr(ctx) << std::endl; };\n\n    // Grammar rules definitions\n    // TODO: handle properly the constant objective function, e.g., obj: 0\n\n    struct keywords_t : x3::symbols<x3::unused_type> \n    {\n        keywords_t() {\n            add(\"Subject\")\n               (\"Bounds\")\n               (\"End\")\n               (\"Inf\")\n               (\"Infinity\");\n        }\n    } const keywords;\n\n    const auto distinct_keywords = lexeme[no_case[keywords] >> !(alnum | '_')];\n\n    x3::rule<struct identifier_tag, std::string> const identifier (\"identifier\");\n    const auto identifier_def = lexeme[+(alpha | '_') >> *(alnum | '_')] - distinct_keywords;\n\n    BOOST_SPIRIT_DEFINE(identifier);\n\n    const auto obj_fun_term =\n           -(double_ [add_obj_fun_coeff])\n        >> identifier [add_obj_fun_var]\n    ;\n\n    const auto obj_fun_expr =\n           -(identifier >> ':') [set_obj_label]\n        >> -(char_('+') | char_('-')[neg_var_coeff]) >> obj_fun_term [term_parsed]\n        >> *((char_('+') | char_('-')[neg_var_coeff]) > obj_fun_term [term_parsed])\n    ;\n\n    const auto constr_term =\n           -(double_ [add_constr_coeff])\n        >> identifier [add_constr_var]\n    ;\n\n    const auto constraint_expr = \n        -(identifier >> ':') [set_constr_label]\n        >> \n        (\n               -(char_('+') | char_('-')[neg_var_coeff]) >> constr_term [term_parsed]\n            >> *((char_('+') | char_('-')[neg_var_coeff]) > constr_term [term_parsed])\n            >> (char_(\"<>=\")) [add_constr_type] >> -char_('=')\n            >> double_ [add_constr_rhs]\n        )\n    ;\n\n    const auto bound_expr =\n        ((double_ [add_constr_coeff] | ('-' >> (no_case[\"Inf\"] | no_case[\"Infinity\"]) [add_inf_lb]))\n            >> lit(\"<=\") >> identifier [add_lb_constr] \n            >> -(lit(\"<=\") >> double_ [add_ub_constr]))\n        |\n        (identifier [store_ub_var_name] \n            >> lit(\"<=\") \n            >> (double_[add_ub_constr] | (-char_('+') >> (no_case[\"Inf\"] | no_case[\"Infinity\"]) [add_inf_ub])))\n    ;\n\n    x3::rule<class lp_rules, ParserState> const lp_rules (\"lp_rules\");\n    const auto lp_rules_def =\n        skip(space)[\n               (no_case[\"Minimize\"] [set_minimize] | no_case[\"Maximize\"] [set_maximize])\n            >> -char_(':')\n            >> obj_fun_expr\n            >> no_case[\"Subject To\"] >> -char_(':')\n            >> +constraint_expr\n            >> -(no_case[\"Bounds\"] >> -char_(':') >> +bound_expr)\n            >> no_case[\"End\"] >> -char_('.')\n            >> eoi\n        ]\n    ;\n\n    BOOST_SPIRIT_DEFINE(lp_rules);\n}\n\nstd::string remove_comments(const std::string& input)\n{\n    std::string result(\"\");\n    size_t pos_start = 0, pos_cur = 0;\n\n    while (true) \n    {\n        pos_cur = input.find_first_of(\"/\\\\#\", pos_start);\n        if (pos_cur == std::string::npos) {\n            pos_cur = input.length();\n            break;\n        }\n        result += input.substr(pos_start, pos_cur - pos_start);\n        pos_start = input.find_first_of('\\n', pos_cur) + 1;\n    }\n    result += input.substr(pos_start, pos_cur - pos_start);\n\n    return result;\n}\n\nbool run_parser_lp(const std::string& input, LinearProgram& lp)\n{\n    std::string stripped_input = remove_comments(input);\n    auto iter = stripped_input.begin();\n    const auto end = stripped_input.end();\n\n    ParserState parser_state{ lp };\n    \n    bool r = parse(iter, end, parser::lp_rules, parser_state);\n\n    if (r && iter == end) {\n        std::cout << \"Parser success.\" << std::endl;\n        return true;\n    }\n    else {\n        std::cout << \"Parser fail.\" << std::endl;\n        return false;\n    }\n}\n\n", "meta": {"hexsha": "7258df0e6ef30f27e974f401d8b0cd3453fc8fcd", "size": 8721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parser.cpp", "max_stars_repo_name": "maciejdrwal/simplex", "max_stars_repo_head_hexsha": "da6130aea2405b9b211f7bacbd82af9001716e66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-20T22:27:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-16T22:26:25.000Z", "max_issues_repo_path": "parser.cpp", "max_issues_repo_name": "maciejdrwal/simplex", "max_issues_repo_head_hexsha": "da6130aea2405b9b211f7bacbd82af9001716e66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parser.cpp", "max_forks_repo_name": "maciejdrwal/simplex", "max_forks_repo_head_hexsha": "da6130aea2405b9b211f7bacbd82af9001716e66", "max_forks_repo_licenses": ["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.4137931034, "max_line_length": 111, "alphanum_fraction": 0.5745900699, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367020358429, "lm_q2_score": 0.055823136029551815, "lm_q1q2_score": 0.025518804301847553}}
{"text": "#pragma once\n\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/detail/iterator.hpp>\n\n#include \"permutations.hpp\"\n\nnamespace tu\n{\n\n  /**\n   * A matrix proxy with permuted rows and columns.\n   */\n\n  template <typename M>\n  class matrix_permuted: public boost::numeric::ublas::matrix_expression <matrix_permuted <M> >\n  {\n  public:\n    typedef matrix_permuted <M> self_type;\n    typedef M matrix_type;\n    typedef typename M::size_type size_type;\n    typedef typename M::difference_type difference_type;\n    typedef typename M::value_type value_type;\n    typedef typename M::const_reference const_reference;\n    typedef typename boost::mpl::if_ <boost::is_const <M>, typename M::const_reference, typename M::reference>::type reference;\n    typedef typename boost::mpl::if_ <boost::is_const <M>, typename M::const_closure_type, typename M::closure_type>::type matrix_closure_type;\n    typedef const self_type const_closure_type;\n    typedef self_type closure_type;\n    typedef permutation permutation_type;\n    typedef typename M::orientation_category orientation_category;\n    typedef typename M::storage_category storage_category;\n\n  private:\n    matrix_type& _data;\n    permutation_type _perm1;\n    permutation_type _perm2;\n\n  public:\n\n    /**\n     * Constructs the matrix proxy.\n     *\n     * @param matrix The original matrix\n     */\n\n    matrix_permuted(matrix_type& matrix) :\n      _data(matrix), _perm1(matrix.size1()), _perm2(matrix.size2())\n    {\n\n    }\n\n    /**\n     * @return Height of the matrix\n     */\n\n    inline size_type size1() const\n    {\n      return _perm1.size();\n    }\n\n    /**\n     * @return Width of the matrix\n     */\n\n    inline size_type size2() const\n    {\n      return _perm2.size();\n    }\n\n    /**\n     * @return Reference to the row permutation\n     */\n\n    inline const permutation_type& perm1() const\n    {\n      return _perm1;\n    }\n\n    /**\n     * @return Reference to the row permutation\n     */\n\n    inline permutation_type& perm1()\n    {\n      return _perm1;\n    }\n\n    /**\n     * @return Reference to the column permutation\n     */\n\n    inline const permutation_type& perm2() const\n    {\n      return _perm2;\n    }\n\n    /**\n     * @return Reference to the column permutation\n     */\n\n    inline permutation_type& perm2()\n    {\n      return _perm2;\n    }\n\n    /**\n     * Read-only access operator\n     *\n     * @param i Row index\n     * @param j Column index\n     * @return original(row-permutation(row), column-permutation(column))\n     */\n\n    inline const_reference operator ()(size_type i, size_type j) const\n    {\n      return _data(_perm1(i), _perm2(j));\n    }\n\n    /**\n     * Access operator\n     *\n     * @param i Row index\n     * @param j Column index\n     * @return original(row-permutation(row), column-permutation(column))\n     */\n\n    inline reference operator ()(size_type i, size_type j)\n    {\n      return _data(_perm1(i), _perm2(j));\n    }\n\n    /**\n     * @return Reference to original matrix\n     */\n\n    inline matrix_type& data()\n    {\n      return _data;\n    }\n\n    /**\n     * @return Read-only reference to original matrix\n     */\n\n    inline const matrix_type& data() const\n    {\n      return _data;\n    }\n\n    typedef boost::numeric::ublas::detail::indexed_iterator1 <self_type, typename matrix_type::iterator1::iterator_category> iterator1;\n    typedef boost::numeric::ublas::detail::indexed_iterator2 <self_type, typename matrix_type::iterator2::iterator_category> iterator2;\n    typedef boost::numeric::ublas::detail::indexed_const_iterator1 <self_type, typename matrix_type::const_iterator1::iterator_category>\n        const_iterator1;\n    typedef boost::numeric::ublas::detail::indexed_const_iterator2 <self_type, typename matrix_type::const_iterator2::iterator_category>\n        const_iterator2;\n  };\n\n  /**\n   * Free function to set a matrix value of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param row Row index\n   * @param column Column index\n   * @param value New value\n   */\n\n  template <typename MatrixType>\n  inline void matrix_set_value(matrix_permuted <MatrixType>& matrix, size_t row, size_t column, typename MatrixType::value_type value)\n  {\n    matrix(row, column) = value;\n  }\n\n  /**\n   * Dummy function for the version with writable orignal matrix.\n   */\n\n  template <typename MatrixType>\n  inline void matrix_set_value(matrix_permuted <const MatrixType>& matrix, size_t row, size_t column, typename MatrixType::value_type value)\n  {\n    assert (false);\n  }\n\n  /**\n   * Free function to permute two rows of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param index1 First index\n   * @param index2 Second index\n   */\n\n  template <typename MatrixType>\n  inline void matrix_permute1(matrix_permuted <MatrixType>& matrix, size_t index1, size_t index2)\n  {\n    matrix.perm1().swap(index1, index2);\n  }\n\n  /**\n   * Free function to permute two columns of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param index1 First index\n   * @param index2 Second index\n   */\n\n  template <typename MatrixType>\n  inline void matrix_permute2(matrix_permuted <MatrixType>& matrix, size_t index1, size_t index2)\n  {\n    matrix.perm2().swap(index1, index2);\n  }\n\n  /**\n   * Free function to perform a pivot on a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param i Row index\n   * @param j Column index\n   */\n\n  template <typename MatrixType>\n  inline void matrix_binary_pivot(matrix_permuted <MatrixType>& matrix, size_t i, size_t j)\n  {\n    matrix_binary_pivot(matrix.data(), matrix.perm1()(i), matrix.perm2()(j));\n  }\n\n  template <typename MatrixType>\n  inline permutation matrix_get_perm1(matrix_permuted <MatrixType>& matrix)\n  {\n    return matrix.perm1();\n  }\n\n  template <typename MatrixType>\n  inline permutation matrix_get_perm2(matrix_permuted <MatrixType>& matrix)\n  {\n    return matrix.perm2();\n  }\n\n  template <typename MatrixType>\n  inline permutation matrix_get_perm1(matrix_transposed <MatrixType>& matrix)\n  {\n    return matrix_get_perm2(matrix.data());\n  }\n\n  template <typename MatrixType>\n  inline permutation matrix_get_perm2(matrix_transposed <MatrixType>& matrix)\n  {\n    return matrix_get_perm1(matrix.data());\n  }\n\n  template <typename MatrixType>\n  inline void matrix_set_perm1(matrix_permuted <MatrixType>& matrix, const permutation& permutation)\n  {\n    matrix.perm1() = permutation;\n  }\n\n  template <typename MatrixType>\n  inline void matrix_set_perm2(matrix_permuted <MatrixType>& matrix, const permutation& permutation)\n  {\n    matrix.perm2() = permutation;\n  }\n\n  template <typename MatrixType>\n  inline void matrix_set_perm1(matrix_transposed <MatrixType>& matrix, const permutation& permutation)\n  {\n    matrix_set_perm2(matrix.data(), permutation);\n  }\n\n  template <typename MatrixType>\n  inline void matrix_set_perm2(matrix_transposed <MatrixType>& matrix, const permutation& permutation)\n  {\n    matrix_set_perm1(matrix.data(), permutation);\n  }\n} /* namespace tu */\n", "meta": {"hexsha": "8808cdc7f1161c171ec465a01f962b0758da99b4", "size": 6989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cmr/matrix_permuted.hpp", "max_stars_repo_name": "discopt/cmr", "max_stars_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-13T12:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:56:31.000Z", "max_issues_repo_path": "src/cmr/matrix_permuted.hpp", "max_issues_repo_name": "xammy/unimodularity-test", "max_issues_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T09:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T23:18:47.000Z", "max_forks_repo_path": "src/cmr/matrix_permuted.hpp", "max_forks_repo_name": "discopt/cmr", "max_forks_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_forks_repo_licenses": ["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.6007326007, "max_line_length": 143, "alphanum_fraction": 0.6856488768, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.05184546481851975, "lm_q1q2_score": 0.025517722674605333}}
{"text": "#pragma once\n\n/* =========================================================================\n      Copyright (c) 2015-2017, COE of Peking University, Shaoqiang Tang.\n\n                         -----------------\n            cuarma - COE of Peking University, Shaoqiang Tang.\n                         -----------------\n\n                  Author Email    yangxianpku@pku.edu.cn\n\n         Code Repo   https://github.com/yangxianpku/cuarma\n\n                      License:    MIT (X11) License\n============================================================================= */\n\n/** @file cuarma/compressed_matrix.hpp\n *  @encoding:UTF-8 文档编码\n *  @brief Implementation of the compressed_matrix class\n*/\n\n#include <vector>\n#include <list>\n#include <map>\n#include \"cuarma/forwards.h\"\n#include \"cuarma/vector.hpp\"\n#include \"cuarma/blas/sparse_matrix_operations.hpp\"\n#include \"cuarma/tools/tools.hpp\"\n#include \"cuarma/tools/entry_proxy.hpp\"\n\n#ifdef CUARMA_WITH_UBLAS\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#endif\n\nnamespace cuarma\n{\nnamespace detail\n{\n\n  /** @brief Implementation of the copy of a host-based sparse matrix to the device.\n    *\n    * See convenience copy() routines for type requirements of CPUMatrixT\n    */\n  template<typename CPUMatrixT, typename NumericT, unsigned int AlignmentV>\n  void copy_impl(const CPUMatrixT & cpu_matrix,\n                 compressed_matrix<NumericT, AlignmentV> & gpu_matrix,\n                 arma_size_t nonzeros)\n  {\n    assert( (gpu_matrix.size1() == 0 || cuarma::traits::size1(cpu_matrix) == gpu_matrix.size1()) && bool(\"Size mismatch\") );\n    assert( (gpu_matrix.size2() == 0 || cuarma::traits::size2(cpu_matrix) == gpu_matrix.size2()) && bool(\"Size mismatch\") );\n\n    cuarma::backend::typesafe_host_array<unsigned int> row_buffer(gpu_matrix.handle1(), cpu_matrix.size1() + 1);\n    cuarma::backend::typesafe_host_array<unsigned int> col_buffer(gpu_matrix.handle2(), nonzeros);\n    std::vector<NumericT> elements(nonzeros);\n\n    arma_size_t row_index  = 0;\n    arma_size_t data_index = 0;\n\n    for (typename CPUMatrixT::const_iterator1 row_it = cpu_matrix.begin1();\n         row_it != cpu_matrix.end1();\n         ++row_it)\n    {\n      row_buffer.set(row_index, data_index);\n      ++row_index;\n\n      for (typename CPUMatrixT::const_iterator2 col_it = row_it.begin();\n           col_it != row_it.end();\n           ++col_it)\n      {\n        col_buffer.set(data_index, col_it.index2());\n        elements[data_index] = *col_it;\n        ++data_index;\n      }\n      data_index = cuarma::tools::align_to_multiple<arma_size_t>(data_index, AlignmentV); //take care of alignment\n    }\n    row_buffer.set(row_index, data_index);\n\n    gpu_matrix.set(row_buffer.get(),\n                   col_buffer.get(),\n                   &elements[0],\n        cpu_matrix.size1(),\n        cpu_matrix.size2(),\n        nonzeros);\n  }\n}\n\n//\n// host to device:\n//\n\n//provide copy-operation:\n/** @brief Copies a sparse matrix from the host to the  device (either GPU or multi-core CPU)\n  *\n  * There are some type requirements on the CPUMatrixT type (fulfilled by e.g. boost::numeric::ublas):\n  * - .size1() returns the number of rows\n  * - .size2() returns the number of columns\n  * - const_iterator1    is a type definition for an iterator along increasing row indices\n  * - const_iterator2    is a type definition for an iterator along increasing columns indices\n  * - The const_iterator1 type provides an iterator of type const_iterator2 via members .begin() and .end() that iterates along column indices in the current row.\n  * - The types const_iterator1 and const_iterator2 provide members functions .index1() and .index2() that return the current row and column indices respectively.\n  * - Dereferenciation of an object of type const_iterator2 returns the entry.\n  *\n  * @param cpu_matrix   A sparse matrix on the host.\n  * @param gpu_matrix   A compressed_matrix from cuarma\n  */\ntemplate<typename CPUMatrixT, typename NumericT, unsigned int AlignmentV>\nvoid copy(const CPUMatrixT & cpu_matrix,\n          compressed_matrix<NumericT, AlignmentV> & gpu_matrix )\n{\n  if ( cpu_matrix.size1() > 0 && cpu_matrix.size2() > 0 )\n  {\n    //determine nonzeros:\n    arma_size_t num_entries = 0;\n    for (typename CPUMatrixT::const_iterator1 row_it = cpu_matrix.begin1();\n         row_it != cpu_matrix.end1();\n         ++row_it)\n    {\n      arma_size_t entries_per_row = 0;\n      for (typename CPUMatrixT::const_iterator2 col_it = row_it.begin();\n           col_it != row_it.end();\n           ++col_it)\n      {\n        ++entries_per_row;\n      }\n      num_entries += cuarma::tools::align_to_multiple<arma_size_t>(entries_per_row, AlignmentV);\n    }\n\n    if (num_entries == 0) //we copy an empty matrix\n      num_entries = 1;\n\n    //set up matrix entries:\n    cuarma::detail::copy_impl(cpu_matrix, gpu_matrix, num_entries);\n  }\n}\n\n\n//adapted for std::vector< std::map < > > argument:\n/** @brief Copies a sparse square matrix in the std::vector< std::map < > > format to an device. Use cuarma::tools::sparse_matrix_adapter for non-square matrices.\n  *\n  * @param cpu_matrix   A sparse square matrix on the host using STL types\n  * @param gpu_matrix   A compressed_matrix from cuarma\n  */\ntemplate<typename SizeT, typename NumericT, unsigned int AlignmentV>\nvoid copy(const std::vector< std::map<SizeT, NumericT> > & cpu_matrix, compressed_matrix<NumericT, AlignmentV> & gpu_matrix )\n{\n  arma_size_t nonzeros = 0;\n  arma_size_t max_col = 0;\n  for (arma_size_t i=0; i<cpu_matrix.size(); ++i)\n  {\n    if (cpu_matrix[i].size() > 0)\n      nonzeros += ((cpu_matrix[i].size() - 1) / AlignmentV + 1) * AlignmentV;\n    if (cpu_matrix[i].size() > 0)\n      max_col = std::max<arma_size_t>(max_col, (cpu_matrix[i].rbegin())->first);\n  }\n\n  cuarma::detail::copy_impl(tools::const_sparse_matrix_adapter<NumericT, SizeT>(cpu_matrix, cpu_matrix.size(), max_col + 1),\n                              gpu_matrix,\n                              nonzeros);\n}\n\n#ifdef CUARMA_WITH_UBLAS\n/** @brief Convenience routine for copying a sparse uBLAS matrix to a cuarma matrix.\n  *\n  * Optimization which copies the data directly from the internal uBLAS buffers.\n  */\ntemplate<typename ScalarType, typename F, arma_size_t IB, typename IA, typename TA>\nvoid copy(const boost::numeric::ublas::compressed_matrix<ScalarType, F, IB, IA, TA> & ublas_matrix,\n          cuarma::compressed_matrix<ScalarType, 1> & gpu_matrix)\n{\n  assert( (gpu_matrix.size1() == 0 || cuarma::traits::size1(ublas_matrix) == gpu_matrix.size1()) && bool(\"Size mismatch\") );\n  assert( (gpu_matrix.size2() == 0 || cuarma::traits::size2(ublas_matrix) == gpu_matrix.size2()) && bool(\"Size mismatch\") );\n\n  //we just need to copy the CSR arrays:\n  cuarma::backend::typesafe_host_array<unsigned int> row_buffer(gpu_matrix.handle1(), ublas_matrix.size1() + 1);\n  for (arma_size_t i=0; i<=ublas_matrix.size1(); ++i)\n    row_buffer.set(i, ublas_matrix.index1_data()[i]);\n\n  cuarma::backend::typesafe_host_array<unsigned int> col_buffer(gpu_matrix.handle2(), ublas_matrix.nnz());\n  for (arma_size_t i=0; i<ublas_matrix.nnz(); ++i)\n    col_buffer.set(i, ublas_matrix.index2_data()[i]);\n\n  gpu_matrix.set(row_buffer.get(),\n                 col_buffer.get(),\n                 &(ublas_matrix.value_data()[0]),\n      ublas_matrix.size1(),\n      ublas_matrix.size2(),\n      ublas_matrix.nnz());\n\n}\n#endif\n\n\n//\n// device to host:\n//\n/** @brief Copies a sparse matrix from the  device (either GPU or multi-core CPU) to the host.\n  *\n  * There are two type requirements on the CPUMatrixT type (fulfilled by e.g. boost::numeric::ublas):\n  * - resize(rows, cols)  A resize function to bring the matrix into the correct size\n  * - operator(i,j)       Write new entries via the parenthesis operator\n  *\n  * @param gpu_matrix   A compressed_matrix from cuarma\n  * @param cpu_matrix   A sparse matrix on the host.\n  */\ntemplate<typename CPUMatrixT, typename NumericT, unsigned int AlignmentV>\nvoid copy(const compressed_matrix<NumericT, AlignmentV> & gpu_matrix,\n          CPUMatrixT & cpu_matrix )\n{\n  assert( (cuarma::traits::size1(cpu_matrix) == gpu_matrix.size1()) && bool(\"Size mismatch\") );\n  assert( (cuarma::traits::size2(cpu_matrix) == gpu_matrix.size2()) && bool(\"Size mismatch\") );\n\n  if ( gpu_matrix.size1() > 0 && gpu_matrix.size2() > 0 )\n  {\n    //get raw data from memory:\n    cuarma::backend::typesafe_host_array<unsigned int> row_buffer(gpu_matrix.handle1(), cpu_matrix.size1() + 1);\n    cuarma::backend::typesafe_host_array<unsigned int> col_buffer(gpu_matrix.handle2(), gpu_matrix.nnz());\n    std::vector<NumericT> elements(gpu_matrix.nnz());\n\n    //std::cout << \"GPU->CPU, nonzeros: \" << gpu_matrix.nnz() << std::endl;\n\n    cuarma::backend::memory_read(gpu_matrix.handle1(), 0, row_buffer.raw_size(), row_buffer.get());\n    cuarma::backend::memory_read(gpu_matrix.handle2(), 0, col_buffer.raw_size(), col_buffer.get());\n    cuarma::backend::memory_read(gpu_matrix.handle(),  0, sizeof(NumericT)* gpu_matrix.nnz(), &(elements[0]));\n\n    //fill the cpu_matrix:\n    arma_size_t data_index = 0;\n    for (arma_size_t row = 1; row <= gpu_matrix.size1(); ++row)\n    {\n      while (data_index < row_buffer[row])\n      {\n        if (col_buffer[data_index] >= gpu_matrix.size2())\n        {\n          std::cerr << \"cuarma encountered invalid data at colbuffer[\" << data_index << \"]: \" << col_buffer[data_index] << std::endl;\n          return;\n        }\n\n        if (std::fabs(elements[data_index]) > static_cast<NumericT>(0))\n          cpu_matrix(row-1, static_cast<arma_size_t>(col_buffer[data_index])) = elements[data_index];\n        ++data_index;\n      }\n    }\n  }\n}\n\n\n/** @brief Copies a sparse matrix from an  device to the host. The host type is the std::vector< std::map < > > format .\n  *\n  * @param gpu_matrix   A compressed_matrix from cuarma\n  * @param cpu_matrix   A sparse matrix on the host.\n  */\ntemplate<typename NumericT, unsigned int AlignmentV>\nvoid copy(const compressed_matrix<NumericT, AlignmentV> & gpu_matrix,\n          std::vector< std::map<unsigned int, NumericT> > & cpu_matrix)\n{\n  assert( (cpu_matrix.size() == gpu_matrix.size1()) && bool(\"Size mismatch\") );\n\n  tools::sparse_matrix_adapter<NumericT> temp(cpu_matrix, gpu_matrix.size1(), gpu_matrix.size2());\n  copy(gpu_matrix, temp);\n}\n\n#ifdef CUARMA_WITH_UBLAS\n/** @brief Convenience routine for copying a cuarma sparse matrix back to a sparse uBLAS matrix\n  *\n  * Directly populates the internal buffer of the uBLAS matrix, thus avoiding a temporary STL matrix.\n  */\ntemplate<typename ScalarType, unsigned int AlignmentV, typename F, arma_size_t IB, typename IA, typename TA>\nvoid copy(cuarma::compressed_matrix<ScalarType, AlignmentV> const & gpu_matrix,\n          boost::numeric::ublas::compressed_matrix<ScalarType> & ublas_matrix)\n{\n  assert( (cuarma::traits::size1(ublas_matrix) == gpu_matrix.size1()) && bool(\"Size mismatch\") );\n  assert( (cuarma::traits::size2(ublas_matrix) == gpu_matrix.size2()) && bool(\"Size mismatch\") );\n\n  cuarma::backend::typesafe_host_array<unsigned int> row_buffer(gpu_matrix.handle1(), gpu_matrix.size1() + 1);\n  cuarma::backend::typesafe_host_array<unsigned int> col_buffer(gpu_matrix.handle2(), gpu_matrix.nnz());\n\n  cuarma::backend::memory_read(gpu_matrix.handle1(), 0, row_buffer.raw_size(), row_buffer.get());\n  cuarma::backend::memory_read(gpu_matrix.handle2(), 0, col_buffer.raw_size(), col_buffer.get());\n\n  ublas_matrix.clear();\n  ublas_matrix.reserve(gpu_matrix.nnz());\n\n  ublas_matrix.set_filled(gpu_matrix.size1() + 1, gpu_matrix.nnz());\n\n  for (arma_size_t i=0; i<ublas_matrix.size1() + 1; ++i)\n    ublas_matrix.index1_data()[i] = row_buffer[i];\n\n  for (arma_size_t i=0; i<ublas_matrix.nnz(); ++i)\n    ublas_matrix.index2_data()[i] = col_buffer[i];\n\n  cuarma::backend::memory_read(gpu_matrix.handle(),  0, sizeof(ScalarType) * gpu_matrix.nnz(), &(ublas_matrix.value_data()[0]));\n\n}\n#endif\n\n//////////////////////// compressed_matrix //////////////////////////\n/** @brief A sparse square matrix in compressed sparse rows format.\n  *\n  * @tparam NumericT    The floating point type (either float or double, checked at compile time)\n  * @tparam AlignmentV     The internal memory size for the entries in each row is given by (size()/AlignmentV + 1) * AlignmentV. AlignmentV must be a power of two. Best values or usually 4, 8 or 16, higher values are usually a waste of memory.\n  */\ntemplate<class NumericT, unsigned int AlignmentV /* see VCLForwards.h */>\nclass compressed_matrix\n{\npublic:\n  typedef cuarma::backend::mem_handle                                                              handle_type;\n  typedef scalar<typename cuarma::tools::CHECK_SCALAR_TEMPLATE_ARGUMENT<NumericT>::ResultType>   value_type;\n  typedef arma_size_t                                                                                 size_type;\n\n  /** @brief Default construction of a compressed matrix. No memory is allocated */\n  compressed_matrix() : rows_(0), cols_(0), nonzeros_(0), row_block_num_(0) {}\n\n  /** @brief Construction of a compressed matrix with the supplied number of rows and columns. If the number of nonzeros is positive, memory is allocated\n      *\n      * @param rows     Number of rows\n      * @param cols     Number of columns\n      * @param nonzeros Optional number of nonzeros for memory preallocation\n      * @param ctx      Optional context in which the matrix is created (one out of multiple  contexts, CUDA, host)\n      */\n  explicit compressed_matrix(arma_size_t rows, arma_size_t cols, arma_size_t nonzeros = 0, cuarma::context ctx = cuarma::context())\n    : rows_(rows), cols_(cols), nonzeros_(nonzeros), row_block_num_(0)\n  {\n    row_buffer_.switch_active_handle_id(ctx.memory_type());\n    col_buffer_.switch_active_handle_id(ctx.memory_type());\n    elements_.switch_active_handle_id(ctx.memory_type());\n    row_blocks_.switch_active_handle_id(ctx.memory_type());\n\n\n    if (rows > 0)\n    {\n      cuarma::backend::memory_create(row_buffer_, cuarma::backend::typesafe_host_array<unsigned int>().element_size() * (rows + 1), ctx);\n      cuarma::vector_base<unsigned int> init_temporary(row_buffer_, size_type(rows+1), 0, 1);\n      init_temporary = cuarma::zero_vector<unsigned int>(size_type(rows+1), ctx);\n    }\n    if (nonzeros > 0)\n    {\n      cuarma::backend::memory_create(col_buffer_, cuarma::backend::typesafe_host_array<unsigned int>().element_size() * nonzeros, ctx);\n      cuarma::backend::memory_create(elements_, sizeof(NumericT) * nonzeros, ctx);\n    }\n  }\n\n  /** @brief Construction of a compressed matrix with the supplied number of rows and columns. If the number of nonzeros is positive, memory is allocated\n      *\n      * @param rows     Number of rows\n      * @param cols     Number of columns\n      * @param ctx      Context in which to create the matrix\n      */\n  explicit compressed_matrix(arma_size_t rows, arma_size_t cols, cuarma::context ctx)\n    : rows_(rows), cols_(cols), nonzeros_(0), row_block_num_(0)\n  {\n    row_buffer_.switch_active_handle_id(ctx.memory_type());\n    col_buffer_.switch_active_handle_id(ctx.memory_type());\n    elements_.switch_active_handle_id(ctx.memory_type());\n    row_blocks_.switch_active_handle_id(ctx.memory_type());\n\n\n    if (rows > 0)\n    {\n      cuarma::backend::memory_create(row_buffer_, cuarma::backend::typesafe_host_array<unsigned int>().element_size() * (rows + 1), ctx);\n      cuarma::vector_base<unsigned int> init_temporary(row_buffer_, size_type(rows+1), 0, 1);\n      init_temporary = cuarma::zero_vector<unsigned int>(size_type(rows+1), ctx);\n    }\n  }\n\n  /** @brief Creates an empty compressed_matrix, but sets the respective context information.\n    *\n    * This is useful if you want to want to populate e.g. a cuarma::compressed_matrix<> on the host with copy(), but the default backend is .\n    */\n  explicit compressed_matrix(cuarma::context ctx) : rows_(0), cols_(0), nonzeros_(0), row_block_num_(0)\n  {\n    row_buffer_.switch_active_handle_id(ctx.memory_type());\n    col_buffer_.switch_active_handle_id(ctx.memory_type());\n    elements_.switch_active_handle_id(ctx.memory_type());\n    row_blocks_.switch_active_handle_id(ctx.memory_type());\n  }\n\n\n  /** @brief Assignment a compressed matrix from the product of two compressed_matrix objects (C = A * B). */\n  compressed_matrix(matrix_expression<const compressed_matrix, const compressed_matrix, op_prod> const & proxy)\n    : rows_(0), cols_(0), nonzeros_(0), row_block_num_(0)\n  {\n    cuarma::context ctx = cuarma::traits::context(proxy.lhs());\n\n    row_buffer_.switch_active_handle_id(ctx.memory_type());\n    col_buffer_.switch_active_handle_id(ctx.memory_type());\n    elements_.switch_active_handle_id(ctx.memory_type());\n    row_blocks_.switch_active_handle_id(ctx.memory_type());\n\n    cuarma::blas::prod_impl(proxy.lhs(), proxy.rhs(), *this);\n    generate_row_block_information();\n  }\n\n  /** @brief Assignment a compressed matrix from possibly another memory domain. */\n  compressed_matrix & operator=(compressed_matrix const & other)\n  {\n    assert( (rows_ == 0 || rows_ == other.size1()) && bool(\"Size mismatch\") );\n    assert( (cols_ == 0 || cols_ == other.size2()) && bool(\"Size mismatch\") );\n\n    rows_ = other.size1();\n    cols_ = other.size2();\n    nonzeros_ = other.nnz();\n    row_block_num_ = other.row_block_num_;\n\n    cuarma::backend::typesafe_memory_copy<unsigned int>(other.row_buffer_, row_buffer_);\n    cuarma::backend::typesafe_memory_copy<unsigned int>(other.col_buffer_, col_buffer_);\n    cuarma::backend::typesafe_memory_copy<unsigned int>(other.row_blocks_, row_blocks_);\n    cuarma::backend::typesafe_memory_copy<NumericT>(other.elements_, elements_);\n\n    return *this;\n  }\n\n  /** @brief Assignment a compressed matrix from the product of two compressed_matrix objects (C = A * B). */\n  compressed_matrix & operator=(matrix_expression<const compressed_matrix, const compressed_matrix, op_prod> const & proxy)\n  {\n    assert( (rows_ == 0 || rows_ == proxy.lhs().size1()) && bool(\"Size mismatch\") );\n    assert( (cols_ == 0 || cols_ == proxy.rhs().size2()) && bool(\"Size mismatch\") );\n\n    cuarma::blas::prod_impl(proxy.lhs(), proxy.rhs(), *this);\n    generate_row_block_information();\n\n    return *this;\n  }\n\n\n  /** @brief Sets the row, column and value arrays of the compressed matrix\n    *\n    * Type of row_jumper and col_buffer is 'unsigned int' for CUDA and OpenMP (host) backend, but *must* be cl_uint for .\n    * The reason is that 'unsigned int' might have a different bit representation on the host than 'unsigned int' on the  device.\n    * cl_uint is guaranteed to have the correct bit representation for  devices.\n    *\n    * @param row_jumper     Pointer to an array holding the indices of the first element of each row (starting with zero). E.g. row_jumper[10] returns the index of the first entry of the 11th row. The array length is 'cols + 1'\n    * @param col_buffer     Pointer to an array holding the column index of each entry. The array length is 'nonzeros'\n    * @param elements       Pointer to an array holding the entries of the sparse matrix. The array length is 'elements'\n    * @param rows           Number of rows of the sparse matrix\n    * @param cols           Number of columns of the sparse matrix\n    * @param nonzeros       Number of nonzeros\n    */\n  void set(const void * row_jumper,\n           const void * col_buffer,\n           const NumericT * elements,\n           arma_size_t rows,\n           arma_size_t cols,\n           arma_size_t nonzeros)\n  {\n    assert( (rows > 0)     && bool(\"Error in compressed_matrix::set(): Number of rows must be larger than zero!\"));\n    assert( (cols > 0)     && bool(\"Error in compressed_matrix::set(): Number of columns must be larger than zero!\"));\n    assert( (nonzeros > 0) && bool(\"Error in compressed_matrix::set(): Number of nonzeros must be larger than zero!\"));\n    //std::cout << \"Setting memory: \" << cols + 1 << \", \" << nonzeros << std::endl;\n\n    //row_buffer_.switch_active_handle_id(cuarma::backend::_MEMORY);\n    cuarma::backend::memory_create(row_buffer_, cuarma::backend::typesafe_host_array<unsigned int>(row_buffer_).element_size() * (rows + 1), cuarma::traits::context(row_buffer_), row_jumper);\n\n    //col_buffer_.switch_active_handle_id(cuarma::backend::_MEMORY);\n    cuarma::backend::memory_create(col_buffer_, cuarma::backend::typesafe_host_array<unsigned int>(col_buffer_).element_size() * nonzeros, cuarma::traits::context(col_buffer_), col_buffer);\n\n    //elements_.switch_active_handle_id(cuarma::backend::_MEMORY);\n    cuarma::backend::memory_create(elements_, sizeof(NumericT) * nonzeros, cuarma::traits::context(elements_), elements);\n\n    nonzeros_ = nonzeros;\n    rows_ = rows;\n    cols_ = cols;\n\n    //generate block information for CSR-adaptive:\n    generate_row_block_information();\n  }\n\n  /** @brief Allocate memory for the supplied number of nonzeros in the matrix. Old values are preserved. */\n  void reserve(arma_size_t new_nonzeros, bool preserve = true)\n  {\n    if (new_nonzeros > nonzeros_)\n    {\n      if (preserve)\n      {\n        handle_type col_buffer_old;\n        handle_type elements_old;\n        cuarma::backend::memory_shallow_copy(col_buffer_, col_buffer_old);\n        cuarma::backend::memory_shallow_copy(elements_,   elements_old);\n\n        cuarma::backend::typesafe_host_array<unsigned int> size_deducer(col_buffer_);\n        cuarma::backend::memory_create(col_buffer_, size_deducer.element_size() * new_nonzeros, cuarma::traits::context(col_buffer_));\n        cuarma::backend::memory_create(elements_,   sizeof(NumericT) * new_nonzeros,          cuarma::traits::context(elements_));\n\n        cuarma::backend::memory_copy(col_buffer_old, col_buffer_, 0, 0, size_deducer.element_size() * nonzeros_);\n        cuarma::backend::memory_copy(elements_old,   elements_,   0, 0, sizeof(NumericT)* nonzeros_);\n      }\n      else\n      {\n        cuarma::backend::typesafe_host_array<unsigned int> size_deducer(col_buffer_);\n        cuarma::backend::memory_create(col_buffer_, size_deducer.element_size() * new_nonzeros, cuarma::traits::context(col_buffer_));\n        cuarma::backend::memory_create(elements_,   sizeof(NumericT)            * new_nonzeros, cuarma::traits::context(elements_));\n      }\n\n      nonzeros_ = new_nonzeros;\n    }\n  }\n\n  /** @brief Resize the matrix.\n      *\n      * @param new_size1    New number of rows\n      * @param new_size2    New number of columns\n      * @param preserve     If true, the old values are preserved. At present, old values are always discarded.\n      */\n  void resize(arma_size_t new_size1, arma_size_t new_size2, bool preserve = true)\n  {\n    assert(new_size1 > 0 && new_size2 > 0 && bool(\"Cannot resize to zero size!\"));\n\n    if (new_size1 != rows_ || new_size2 != cols_)\n    {\n      if (!preserve)\n      {\n        cuarma::backend::typesafe_host_array<unsigned int> host_row_buffer(row_buffer_, new_size1 + 1);\n        cuarma::backend::memory_create(row_buffer_, cuarma::backend::typesafe_host_array<unsigned int>().element_size() * (new_size1 + 1), cuarma::traits::context(row_buffer_), host_row_buffer.get());\n        // faster version without initializing memory:\n        //cuarma::backend::memory_create(row_buffer_, cuarma::backend::typesafe_host_array<unsigned int>().element_size() * (new_size1 + 1), cuarma::traits::context(row_buffer_));\n        nonzeros_ = 0;\n      }\n      else\n      {\n        std::vector<std::map<unsigned int, NumericT> > stl_sparse_matrix;\n        if (rows_ > 0)\n        {\n          stl_sparse_matrix.resize(rows_);\n          cuarma::copy(*this, stl_sparse_matrix);\n        } else {\n          stl_sparse_matrix.resize(new_size1);\n          stl_sparse_matrix[0][0] = 0;      //enforces nonzero array sizes if matrix was initially empty\n        }\n\n        stl_sparse_matrix.resize(new_size1);\n\n        //discard entries with column index larger than new_size2\n        if (new_size2 < cols_ && rows_ > 0)\n        {\n          for (arma_size_t i=0; i<stl_sparse_matrix.size(); ++i)\n          {\n            std::list<unsigned int> to_delete;\n            for (typename std::map<unsigned int, NumericT>::iterator it = stl_sparse_matrix[i].begin();\n                 it != stl_sparse_matrix[i].end();\n                 ++it)\n            {\n              if (it->first >= new_size2)\n                to_delete.push_back(it->first);\n            }\n\n            for (std::list<unsigned int>::iterator it = to_delete.begin(); it != to_delete.end(); ++it)\n              stl_sparse_matrix[i].erase(*it);\n          }\n        }\n\n        cuarma::tools::sparse_matrix_adapter<NumericT> adapted_matrix(stl_sparse_matrix, new_size1, new_size2);\n        rows_ = new_size1;\n        cols_ = new_size2;\n        cuarma::copy(adapted_matrix, *this);\n      }\n\n      rows_ = new_size1;\n      cols_ = new_size2;\n    }\n  }\n\n  /** @brief Resets all entries in the matrix back to zero without changing the matrix size. Resets the sparsity pattern. */\n  void clear()\n  {\n    cuarma::backend::typesafe_host_array<unsigned int> host_row_buffer(row_buffer_, rows_ + 1);\n    cuarma::backend::typesafe_host_array<unsigned int> host_col_buffer(col_buffer_, 1);\n    std::vector<NumericT> host_elements(1);\n\n    cuarma::backend::memory_create(row_buffer_, host_row_buffer.element_size() * (rows_ + 1), cuarma::traits::context(row_buffer_), host_row_buffer.get());\n    cuarma::backend::memory_create(col_buffer_, host_col_buffer.element_size() * 1,           cuarma::traits::context(col_buffer_), host_col_buffer.get());\n    cuarma::backend::memory_create(elements_,   sizeof(NumericT) * 1,                         cuarma::traits::context(elements_), &(host_elements[0]));\n\n    nonzeros_ = 0;\n  }\n\n  /** @brief Returns a reference to the (i,j)-th entry of the sparse matrix. If (i,j) does not exist (zero), it is inserted (slow!) */\n  entry_proxy<NumericT> operator()(arma_size_t i, arma_size_t j)\n  {\n    assert( (i < rows_) && (j < cols_) && bool(\"compressed_matrix access out of bounds!\"));\n\n    arma_size_t index = element_index(i, j);\n\n    // check for element in sparsity pattern\n    if (index < nonzeros_)\n      return entry_proxy<NumericT>(index, elements_);\n\n    // Element not found. Copying required. Very slow, but direct entry manipulation is painful anyway...\n    std::vector< std::map<unsigned int, NumericT> > cpu_backup(rows_);\n    tools::sparse_matrix_adapter<NumericT> adapted_cpu_backup(cpu_backup, rows_, cols_);\n    cuarma::copy(*this, adapted_cpu_backup);\n    cpu_backup[i][static_cast<unsigned int>(j)] = 0.0;\n    cuarma::copy(adapted_cpu_backup, *this);\n\n    index = element_index(i, j);\n\n    assert(index < nonzeros_);\n\n    return entry_proxy<NumericT>(index, elements_);\n  }\n\n  /** @brief  Returns the number of rows */\n  const arma_size_t & size1() const { return rows_; }\n  /** @brief  Returns the number of columns */\n  const arma_size_t & size2() const { return cols_; }\n  /** @brief  Returns the number of nonzero entries */\n  const arma_size_t & nnz() const { return nonzeros_; }\n  /** @brief  Returns the internal number of row blocks for an adaptive SpMV */\n  const arma_size_t & blocks1() const { return row_block_num_; }\n\n  /** @brief  Returns the  handle to the row index array */\n  const handle_type & handle1() const { return row_buffer_; }\n  /** @brief  Returns the  handle to the column index array */\n  const handle_type & handle2() const { return col_buffer_; }\n  /** @brief  Returns the  handle to the row block array */\n  const handle_type & handle3() const { return row_blocks_; }\n  /** @brief  Returns the  handle to the matrix entry array */\n  const handle_type & handle() const { return elements_; }\n\n  /** @brief  Returns the  handle to the row index array */\n  handle_type & handle1() { return row_buffer_; }\n  /** @brief  Returns the  handle to the column index array */\n  handle_type & handle2() { return col_buffer_; }\n  /** @brief  Returns the  handle to the row block array */\n  handle_type & handle3() { return row_blocks_; }\n  /** @brief  Returns the  handle to the matrix entry array */\n  handle_type & handle() { return elements_; }\n\n  /** @brief Switches the memory context of the matrix.\n    *\n    * Allows for e.g. an migration of the full matrix from  memory to host memory for e.g. computing a preconditioner.\n    */\n  void switch_memory_context(cuarma::context new_ctx)\n  {\n    cuarma::backend::switch_memory_context<unsigned int>(row_buffer_, new_ctx);\n    cuarma::backend::switch_memory_context<unsigned int>(col_buffer_, new_ctx);\n    cuarma::backend::switch_memory_context<unsigned int>(row_blocks_, new_ctx);\n    cuarma::backend::switch_memory_context<NumericT>(elements_, new_ctx);\n  }\n\n  /** @brief Returns the current memory context to determine whether the matrix is set up for OpenMP, , or CUDA. */\n  cuarma::memory_types memory_context() const\n  {\n    return row_buffer_.get_active_handle_id();\n  }\n\nprivate:\n\n  /** @brief Helper function for accessing the element (i,j) of the matrix. */\n  arma_size_t element_index(arma_size_t i, arma_size_t j)\n  {\n    //read row indices\n    cuarma::backend::typesafe_host_array<unsigned int> row_indices(row_buffer_, 2);\n    cuarma::backend::memory_read(row_buffer_, row_indices.element_size()*i, row_indices.element_size()*2, row_indices.get());\n\n    //get column indices for row i:\n    cuarma::backend::typesafe_host_array<unsigned int> col_indices(col_buffer_, row_indices[1] - row_indices[0]);\n    cuarma::backend::memory_read(col_buffer_, col_indices.element_size()*row_indices[0], row_indices.element_size()*col_indices.size(), col_indices.get());\n\n    for (arma_size_t k=0; k<col_indices.size(); ++k)\n    {\n      if (col_indices[k] == j)\n        return row_indices[0] + k;\n    }\n\n    // if not found, return index past the end of the matrix (cf. matrix.end() in the spirit of the STL)\n    return nonzeros_;\n  }\n\npublic:\n  /** @brief Builds the row block information needed for fast sparse matrix-vector multiplications.\n   *\n   *  Required when manually populating the memory buffers with values. Not necessary when using cuarma::copy() or .set()\n   */\n  void generate_row_block_information()\n  {\n    cuarma::backend::typesafe_host_array<unsigned int> row_buffer(row_buffer_, rows_ + 1);\n    cuarma::backend::memory_read(row_buffer_, 0, row_buffer.raw_size(), row_buffer.get());\n\n    cuarma::backend::typesafe_host_array<unsigned int> row_blocks(row_buffer_, rows_ + 1);\n\n    arma_size_t num_entries_in_current_batch = 0;\n\n    const arma_size_t shared_mem_size = 1024; // number of column indices loaded to shared memory, number of floating point values loaded to shared memory\n\n    row_block_num_ = 0;\n    row_blocks.set(0, 0);\n    for (arma_size_t i=0; i<rows_; ++i)\n    {\n      arma_size_t entries_in_row = arma_size_t(row_buffer[i+1]) - arma_size_t(row_buffer[i]);\n      num_entries_in_current_batch += entries_in_row;\n\n      if (num_entries_in_current_batch > shared_mem_size)\n      {\n        arma_size_t rows_in_batch = i - row_blocks[row_block_num_];\n        if (rows_in_batch > 0) // at least one full row is in the batch. Use current row in next batch.\n          row_blocks.set(++row_block_num_, i--);\n        else // row is larger than buffer in shared memory\n          row_blocks.set(++row_block_num_, i+1);\n        num_entries_in_current_batch = 0;\n      }\n    }\n    if (num_entries_in_current_batch > 0)\n      row_blocks.set(++row_block_num_, rows_);\n\n    if (row_block_num_ > 0) //matrix might be empty...\n      cuarma::backend::memory_create(row_blocks_,\n                                       row_blocks.element_size() * (row_block_num_ + 1),\n                                       cuarma::traits::context(row_buffer_), row_blocks.get());\n\n  }\n\nprivate:\n  // /** @brief Copy constructor is by now not available. */\n  //compressed_matrix(compressed_matrix const &);\n\nprivate:\n\n  arma_size_t rows_;\n  arma_size_t cols_;\n  arma_size_t nonzeros_;\n  arma_size_t row_block_num_;\n  handle_type row_buffer_;\n  handle_type row_blocks_;\n  handle_type col_buffer_;\n  handle_type elements_;\n};\n\n/** @brief Output stream support for compressed_matrix. Output format is same as MATLAB, Octave, or SciPy\n  *\n  * @param os   STL output stream\n  * @param A    The compressed matrix to be printed.\n*/\ntemplate<typename NumericT, unsigned int AlignmentV>\nstd::ostream & operator<<(std::ostream & os, compressed_matrix<NumericT, AlignmentV> const & A)\n{\n  std::vector<std::map<unsigned int, NumericT> > tmp(A.size1());\n  cuarma::copy(A, tmp);\n  os << \"compressed_matrix of size (\" << A.size1() << \", \" << A.size2() << \") with \" << A.nnz() << \" nonzeros:\" << std::endl;\n\n  for (arma_size_t i=0; i<A.size1(); ++i)\n  {\n    for (typename std::map<unsigned int, NumericT>::const_iterator it = tmp[i].begin(); it != tmp[i].end(); ++it)\n      os << \"  (\" << i << \", \" << it->first << \")\\t\" << it->second << std::endl;\n  }\n  return os;\n}\n\n//\n// Specify available operations:\n//\n\n/** \\cond */\n\nnamespace blas\n{\nnamespace detail\n{\n  // x = A * y\n  template<typename T, unsigned int A>\n  struct op_executor<vector_base<T>, op_assign, vector_expression<const compressed_matrix<T, A>, const vector_base<T>, op_prod> >\n  {\n    static void apply(vector_base<T> & lhs, vector_expression<const compressed_matrix<T, A>, const vector_base<T>, op_prod> const & rhs)\n    {\n      // check for the special case x = A * x\n      if (cuarma::traits::handle(lhs) == cuarma::traits::handle(rhs.rhs()))\n      {\n        cuarma::vector<T> temp(lhs);\n        cuarma::blas::prod_impl(rhs.lhs(), rhs.rhs(), T(1), temp, T(0));\n        lhs = temp;\n      }\n      else\n        cuarma::blas::prod_impl(rhs.lhs(), rhs.rhs(), T(1), lhs, T(0));\n    }\n  };\n\n  template<typename T, unsigned int A>\n  struct op_executor<vector_base<T>, op_inplace_add, vector_expression<const compressed_matrix<T, A>, const vector_base<T>, op_prod> >\n  {\n    static void apply(vector_base<T> & lhs, vector_expression<const compressed_matrix<T, A>, const vector_base<T>, op_prod> const & rhs)\n    {\n      // check for the special case x += A * x\n      if (cuarma::traits::handle(lhs) == cuarma::traits::handle(rhs.rhs()))\n      {\n        cuarma::vector<T> temp(lhs);\n        cuarma::blas::prod_impl(rhs.lhs(), rhs.rhs(), T(1), temp, T(0));\n        lhs += temp;\n      }\n      else\n        cuarma::blas::prod_impl(rhs.lhs(), rhs.rhs(), T(1), lhs, T(1));\n    }\n  };\n\n  template<typename T, unsigned int A>\n  struct op_executor<vector_base<T>, op_inplace_sub, vector_expression<const compressed_matrix<T, A>, const vector_base<T>, op_prod> >\n  {\n    static void apply(vector_base<T> & lhs, vector_expression<const compressed_matrix<T, A>, const vector_base<T>, op_prod> const & rhs)\n    {\n      // check for the special case x -= A * x\n      if (cuarma::traits::handle(lhs) == cuarma::traits::handle(rhs.rhs()))\n      {\n        cuarma::vector<T> temp(lhs);\n        cuarma::blas::prod_impl(rhs.lhs(), rhs.rhs(), T(1), temp, T(0));\n        lhs -= temp;\n      }\n      else\n        cuarma::blas::prod_impl(rhs.lhs(), rhs.rhs(), T(-1), lhs, T(1));\n    }\n  };\n\n\n  // x = A * vec_op\n  template<typename T, unsigned int A, typename LHS, typename RHS, typename OP>\n  struct op_executor<vector_base<T>, op_assign, vector_expression<const compressed_matrix<T, A>, const vector_expression<const LHS, const RHS, OP>, op_prod> >\n  {\n    static void apply(vector_base<T> & lhs, vector_expression<const compressed_matrix<T, A>, const vector_expression<const LHS, const RHS, OP>, op_prod> const & rhs)\n    {\n      cuarma::vector<T> temp(rhs.rhs(), cuarma::traits::context(rhs));\n      cuarma::blas::prod_impl(rhs.lhs(), temp, lhs);\n    }\n  };\n\n  // x = A * vec_op\n  template<typename T, unsigned int A, typename LHS, typename RHS, typename OP>\n  struct op_executor<vector_base<T>, op_inplace_add, vector_expression<const compressed_matrix<T, A>, vector_expression<const LHS, const RHS, OP>, op_prod> >\n  {\n    static void apply(vector_base<T> & lhs, vector_expression<const compressed_matrix<T, A>, vector_expression<const LHS, const RHS, OP>, op_prod> const & rhs)\n    {\n      cuarma::vector<T> temp(rhs.rhs(), cuarma::traits::context(rhs));\n      cuarma::vector<T> temp_result(lhs);\n      cuarma::blas::prod_impl(rhs.lhs(), temp, temp_result);\n      lhs += temp_result;\n    }\n  };\n\n  // x = A * vec_op\n  template<typename T, unsigned int A, typename LHS, typename RHS, typename OP>\n  struct op_executor<vector_base<T>, op_inplace_sub, vector_expression<const compressed_matrix<T, A>, const vector_expression<const LHS, const RHS, OP>, op_prod> >\n  {\n    static void apply(vector_base<T> & lhs, vector_expression<const compressed_matrix<T, A>, const vector_expression<const LHS, const RHS, OP>, op_prod> const & rhs)\n    {\n      cuarma::vector<T> temp(rhs.rhs(), cuarma::traits::context(rhs));\n      cuarma::vector<T> temp_result(lhs);\n      cuarma::blas::prod_impl(rhs.lhs(), temp, temp_result);\n      lhs -= temp_result;\n    }\n  };\n\n} // namespace detail\n} // namespace blas\n  /** \\endcond */\n}\n", "meta": {"hexsha": "f662cfe2fc53c97a9347b76d49f33cec22c532ef", "size": 36807, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cuarma/compressed_matrix.hpp", "max_stars_repo_name": "yangxianpku/cuarma", "max_stars_repo_head_hexsha": "404f20b5b3fa74e5e27338e89343450f8853024c", "max_stars_repo_licenses": ["X11", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cuarma/compressed_matrix.hpp", "max_issues_repo_name": "yangxianpku/cuarma", "max_issues_repo_head_hexsha": "404f20b5b3fa74e5e27338e89343450f8853024c", "max_issues_repo_licenses": ["X11", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cuarma/compressed_matrix.hpp", "max_forks_repo_name": "yangxianpku/cuarma", "max_forks_repo_head_hexsha": "404f20b5b3fa74e5e27338e89343450f8853024c", "max_forks_repo_licenses": ["X11", "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.3023529412, "max_line_length": 244, "alphanum_fraction": 0.6732958405, "num_tokens": 9253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.06754668503914044, "lm_q1q2_score": 0.02550161969862723}}
{"text": "#include \"domain.hpp\"\n\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/lac/sparsity_tools.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/dofs/dof_renumbering.h>\n\nnamespace bart::domain {\n\nnamespace  {\ntemplate <int dim>\nauto MeshSmoothing = typename dealii::Triangulation<dim>::MeshSmoothing(\n    dealii::Triangulation<dim>::smoothing_on_refinement | dealii::Triangulation<dim>::smoothing_on_coarsening);\n} // namespace\n\ntemplate <int dim>\nDomain<dim>::Domain(std::unique_ptr<domain::mesh::MeshI<dim>> mesh,\n                    std::shared_ptr<domain::finite_element::FiniteElementI<dim>> finite_element,\n                    problem::DiscretizationType discretization)\n    : mesh_(std::move(mesh)),                     \n      finite_element_(finite_element),\n      triangulation_(MPI_COMM_WORLD, MeshSmoothing<dim>),\n      dof_handler_(triangulation_),\n      discretization_type_(discretization) {\n  AssertPointerNotNull(mesh_.get(), \"mesh\", \"domain constructor\");\n  AssertPointerNotNull(finite_element_.get(), \"finite_element\", \"domain constructor\");\n\n  std::string description{\"Domain, \" + std::to_string(dim) + \"D\"};\n  if (discretization == problem::DiscretizationType::kContinuousFEM) {\n    description += \", Continuous\";\n  } else if (discretization == problem::DiscretizationType::kDiscontinuousFEM ){\n    description += \", Discontinuous\";\n  }\n  this->set_description(description, utility::DefaultImplementation(true));\n}\n\ntemplate <>\nDomain<1>::Domain(\n    std::unique_ptr<domain::mesh::MeshI<1>> mesh,\n    std::shared_ptr<domain::finite_element::FiniteElementI<1>> finite_element,\n    problem::DiscretizationType discretization)\n    : mesh_(std::move(mesh)),\n      finite_element_(finite_element),\n      triangulation_(MeshSmoothing<1>),\n      dof_handler_(triangulation_),\n      discretization_type_(discretization) {\n  AssertPointerNotNull(mesh_.get(), \"mesh\", \"domain constructor\");\n  AssertPointerNotNull(finite_element_.get(), \"finite_element\", \"domain constructor\");\n  std::string description{\"Domain, 1D\"};\n  if (discretization == problem::DiscretizationType::kContinuousFEM) {\n    description += \", Continuous\";\n  } else if (discretization == problem::DiscretizationType::kDiscontinuousFEM ){\n    description += \", Discontinuous\";\n  }\n  this->set_description(description, utility::DefaultImplementation(true));\n}\n\ntemplate <int dim>\nDomain<dim>& Domain<dim>::SetUpDOF() {\n  // Setup dof Handler\n  dof_handler_.distribute_dofs(*(finite_element_->finite_element()));\n  // Populate dof IndexSets\n  locally_owned_dofs_ = dof_handler_.locally_owned_dofs();\n  dealii::DoFTools::extract_locally_relevant_dofs(dof_handler_, locally_relevant_dofs_);\n  // Create constraint matrix\n  constraint_matrix_.clear();\n  constraint_matrix_.reinit(locally_relevant_dofs_);\n  dealii::DoFTools::make_hanging_node_constraints(dof_handler_, constraint_matrix_);\n  constraint_matrix_.close();\n\n  for (auto cell = dof_handler_.begin_active(); cell != dof_handler_.end(); ++cell) {\n    if (cell->is_locally_owned())\n      local_cells_.push_back(cell);\n  }\n\n  // Set up dynamic sparsity pattern\n  dynamic_sparsity_pattern_.reinit(locally_relevant_dofs_.size(), locally_relevant_dofs_.size(),\n                                   locally_relevant_dofs_);\n\n  if (discretization_type_ ==  problem::DiscretizationType::kDiscontinuousFEM) {\n    dealii::DoFTools::make_flux_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_, constraint_matrix_, false);\n  } else {\n    dealii::DoFTools::make_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_, constraint_matrix_, false);\n  }\n\n  dealii::SparsityTools::distribute_sparsity_pattern(dynamic_sparsity_pattern_, locally_owned_dofs_,\n                                                     MPI_COMM_WORLD, locally_relevant_dofs_);\n\n  constraint_matrix_.condense(dynamic_sparsity_pattern_);\n\n  return *this;\n}\n\ntemplate <>\nDomain<1>& Domain<1>::SetUpDOF() {\n  const auto n_mpi_processes{ dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD) };\n  const auto this_process{ dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) };\n\n  dealii::GridTools::partition_triangulation(n_mpi_processes, triangulation_);\n  dof_handler_.distribute_dofs(*(finite_element_)->finite_element());\n  dealii::DoFRenumbering::subdomain_wise(dof_handler_);\n\n  for (auto cell = dof_handler_.begin_active(); cell != dof_handler_.end(); ++cell) {\n    if (cell->is_locally_owned())\n      local_cells_.push_back(cell);\n  }\n\n  auto locally_owned_dofs_vector = dealii::DoFTools::locally_owned_dofs_per_subdomain(dof_handler_);\n  locally_owned_dofs_ = locally_owned_dofs_vector.at(this_process);\n\n  constraint_matrix_.clear();\n  dealii::DoFTools::make_hanging_node_constraints(dof_handler_, constraint_matrix_);\n  constraint_matrix_.close();\n\n  dynamic_sparsity_pattern_.reinit(dof_handler_.n_dofs(), dof_handler_.n_dofs());\n\n  if (discretization_type_ ==  problem::DiscretizationType::kDiscontinuousFEM) {\n    dealii::DoFTools::make_flux_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_, constraint_matrix_, false);\n  } else {\n    dealii::DoFTools::make_sparsity_pattern(dof_handler_, dynamic_sparsity_pattern_, constraint_matrix_, false);\n  }\n\n  return *this;\n}\n\ntemplate <int dim>\nDomain<dim>& Domain<dim>::SetUpMesh() {return SetUpMesh(0); }\n\ntemplate<int dim>\nDomain<dim>& Domain<dim>::SetUpMesh(const int global_refinements) {\n  AssertThrow(mesh_->has_material_mapping(), dealii::ExcMessage(\"Mesh object must have initialized material mapping\"));\n  mesh_->FillTriangulation(triangulation_);\n  mesh_->FillBoundaryID(triangulation_);\n  mesh_->FillMaterialID(triangulation_);\n  triangulation_.refine_global(global_refinements);\n  return *this;\n}\n\ntemplate<int dim>\nauto Domain<dim>::GetCellMatrix() const -> dealii::FullMatrix<double> {\n  const int cell_dofs{ finite_element_->dofs_per_cell() };\n  return dealii::FullMatrix<double>(cell_dofs, cell_dofs);\n//  dealii::FullMatrix<double> full_matrix(cell_dofs, cell_dofs);\n//  return full_matrix;\n}\ntemplate<int dim>\nauto Domain<dim>::GetCellVector() const -> dealii::Vector<double> {\n  return dealii::Vector<double>(finite_element_->dofs_per_cell());\n//  int cell_dofs = finite_element_->dofs_per_cell();\n//  dealii::Vector<double> vector(cell_dofs);\n//  return vector;\n}\n\ntemplate<int dim>\nstd::shared_ptr<system::MPISparseMatrix> Domain<dim>::MakeSystemMatrix() const {\n  auto system_matrix_ptr = std::make_shared<system::MPISparseMatrix>();\n  system_matrix_ptr->reinit(locally_owned_dofs_, locally_owned_dofs_, dynamic_sparsity_pattern_, MPI_COMM_WORLD);\n  return system_matrix_ptr;\n}\n\ntemplate<int dim>\nstd::shared_ptr<system::MPIVector> Domain<dim>::MakeSystemVector() const {\n  auto system_vector_ptr = std::make_shared<system::MPIVector>();\n  system_vector_ptr->reinit(locally_owned_dofs_, MPI_COMM_WORLD);\n  return system_vector_ptr;\n}\n\ntemplate <int dim>\nint Domain<dim>::total_degrees_of_freedom() const {\n  if (total_degrees_of_freedom_ == 0)\n    total_degrees_of_freedom_ = dof_handler_.n_dofs();\n  return total_degrees_of_freedom_;\n}\n\ntemplate class Domain<1>;\ntemplate class Domain<2>;\ntemplate class Domain<3>;\n\n} // namespace bart::domain\n", "meta": {"hexsha": "aa61523ce46d1006dd25a832b0e4754d7277aac3", "size": 7139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/domain/domain.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/domain/domain.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/domain/domain.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 39.6611111111, "max_line_length": 119, "alphanum_fraction": 0.7522061913, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.05261894851934593, "lm_q1q2_score": 0.025487570718367086}}
{"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/SurfaceParameterization.h>\n#include <pmp/algorithms/DifferentialGeometry.h>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n//=============================================================================\n\nnamespace pmp {\n\n//=============================================================================\n\nSurfaceParameterization::SurfaceParameterization(SurfaceMesh& mesh)\n    : m_mesh(mesh)\n{\n}\n\n//-----------------------------------------------------------------------------\n\nbool SurfaceParameterization::setupBoundaryConstraints()\n{\n    // get properties\n    auto points = m_mesh.vertexProperty<Point>(\"v:point\");\n    auto tex = m_mesh.vertexProperty<TextureCoordinate>(\"v:tex\");\n\n    SurfaceMesh::VertexIterator vit, vend = m_mesh.verticesEnd();\n    SurfaceMesh::Vertex vh;\n    SurfaceMesh::Halfedge hh;\n    std::vector<SurfaceMesh::Vertex> loop;\n\n    // Initialize all texture coordinates to the origin.\n    for (auto v : m_mesh.vertices())\n        tex[v] = TextureCoordinate(0.5, 0.5);\n\n    // find 1st boundary vertex\n    for (vit = m_mesh.verticesBegin(); vit != vend; ++vit)\n        if (m_mesh.isSurfaceBoundary(*vit))\n            break;\n\n    // no boundary found ?\n    if (vit == vend)\n    {\n        std::cerr << \"Mesh has no boundary.\" << std::endl;\n        return false;\n    }\n\n    // collect boundary loop\n    vh = *vit;\n    hh = m_mesh.halfedge(vh);\n    do\n    {\n        loop.push_back(m_mesh.toVertex(hh));\n        hh = m_mesh.nextHalfedge(hh);\n    } while (hh != m_mesh.halfedge(vh));\n\n    // map boundary loop to unit circle in texture domain\n    unsigned int i, n = loop.size();\n    Scalar angle, l, length;\n    TextureCoordinate t;\n\n    // compute length of boundary loop\n    for (i = 0, length = 0.0; i < n; ++i)\n        length += distance(points[loop[i]], points[loop[(i + 1) % n]]);\n\n    // map length intervalls to unit circle intervals\n    for (i = 0, l = 0.0; i < n;)\n    {\n        // go from 2pi to 0 to preserve orientation\n        angle = 2.0 * M_PI * (1.0 - l / length);\n\n        t[0] = 0.5 + 0.5 * cosf(angle);\n        t[1] = 0.5 + 0.5 * sinf(angle);\n\n        tex[loop[i]] = t;\n\n        ++i;\n        if (i < n)\n        {\n            l += distance(points[loop[i]], points[loop[(i + 1) % n]]);\n        }\n    }\n\n    return true;\n}\n\n//-----------------------------------------------------------------------------\n\nvoid SurfaceParameterization::harmonic(bool useUniformWeights)\n{\n    // map boundary to circle\n    if (!setupBoundaryConstraints())\n    {\n        std::cerr << \"Could not perform setup of boundary constraints.\\n\";\n        return;\n    }\n\n    // get properties\n    auto tex = m_mesh.vertexProperty<TextureCoordinate>(\"v:tex\");\n    auto eweight = m_mesh.addEdgeProperty<Scalar>(\"e:param\");\n    auto idx = m_mesh.addVertexProperty<int>(\"v:idx\", -1);\n\n    // compute Laplace weight per edge: cotan or uniform\n    for (auto e : m_mesh.edges())\n    {\n        eweight[e] =\n            useUniformWeights ? 1.0 : std::max(0.0, cotanWeight(m_mesh, e));\n    }\n\n    // collect free (non-boundary) vertices in array free_vertices[]\n    // assign indices such that idx[ free_vertices[i] ] == i\n    unsigned i = 0;\n    std::vector<SurfaceMesh::Vertex> free_vertices;\n    free_vertices.reserve(m_mesh.nVertices());\n    for (auto v : m_mesh.vertices())\n    {\n        if (!m_mesh.isSurfaceBoundary(v))\n        {\n            idx[v] = i++;\n            free_vertices.push_back(v);\n        }\n    }\n\n    // setup matrix A and rhs B\n    const unsigned int n = free_vertices.size();\n    Eigen::SparseMatrix<double> A(n, n);\n    Eigen::MatrixXd B(n, 2);\n    std::vector<Eigen::Triplet<double>> triplets;\n    double w, ww;\n    SurfaceMesh::Vertex v, vv;\n    SurfaceMesh::Edge e;\n    for (i = 0; i < n; ++i)\n    {\n        v = free_vertices[i];\n\n        // rhs row\n        B(i, 0) = 0.0;\n        B(i, 1) = 0.0;\n\n        // lhs row\n        ww = 0.0;\n        for (auto h : m_mesh.halfedges(v))\n        {\n            vv = m_mesh.toVertex(h);\n            e = m_mesh.edge(h);\n            w = eweight[e];\n            ww += w;\n\n            if (m_mesh.isSurfaceBoundary(vv))\n            {\n                B(i, 0) -= -w * tex[vv][0];\n                B(i, 1) -= -w * tex[vv][1];\n            }\n            else\n            {\n                triplets.emplace_back(i, idx[vv], -w);\n            }\n        }\n        triplets.emplace_back(i, i, ww);\n    }\n\n    // build sparse matrix from triplets\n    A.setFromTriplets(triplets.begin(), triplets.end());\n\n    // solve A*X = B\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);\n    Eigen::MatrixXd X = solver.solve(B);\n    if (solver.info() != Eigen::Success)\n    {\n        std::cerr << \"SurfaceParameterization: Could not solve linear system\\n\";\n    }\n    else\n    {\n        // copy solution\n        for (i = 0; i < n; ++i)\n        {\n            v = free_vertices[i];\n            tex[v][0] = X(i, 0);\n            tex[v][1] = X(i, 1);\n        }\n    }\n\n    // clean-up\n    m_mesh.removeVertexProperty(idx);\n    m_mesh.removeEdgeProperty(eweight);\n}\n\n//-----------------------------------------------------------------------------\n\nbool SurfaceParameterization::setupLSCMBoundary()\n{\n    // constrain the two boundary vertices farthest from each other to fix\n    // the translation and rotation of the resulting parameterization\n\n    // vertex properties\n    auto pos = m_mesh.vertexProperty<Point>(\"v:point\");\n    auto tex = m_mesh.vertexProperty<TexCoord>(\"v:tex\");\n    auto locked = m_mesh.addVertexProperty<bool>(\"v:locked\", false);\n\n    // find boundary vertices and store handles in vector\n    std::vector<SurfaceMesh::Vertex> boundary;\n    for (auto v : m_mesh.vertices())\n        if (m_mesh.isSurfaceBoundary(v))\n            boundary.push_back(v);\n\n    // no boundary?\n    if (boundary.empty())\n    {\n        return false;\n    }\n\n    // find boundary vertices with largest distance\n    Scalar diam(0.0), d;\n    SurfaceMesh::Vertex v1, v2;\n    for (auto vv1 : boundary)\n    {\n        for (auto vv2 : boundary)\n        {\n            d = distance(pos[vv1], pos[vv2]);\n            if (d > diam)\n            {\n                diam = d;\n                v1 = vv1;\n                v2 = vv2;\n            }\n        }\n    }\n\n    // pin these two boundary vertices\n    for (auto v : m_mesh.vertices())\n    {\n        tex[v] = TexCoord(0.5, 0.5);\n        locked[v] = false;\n    }\n    tex[v1] = TexCoord(0.0, 0.0);\n    tex[v2] = TexCoord(1.0, 1.0);\n    locked[v1] = true;\n    locked[v2] = true;\n\n    return true;\n}\n\n//-----------------------------------------------------------------------------\n\nvoid SurfaceParameterization::lscm()\n{\n    // boundary constraints\n    if (!setupLSCMBoundary())\n        return;\n\n    // properties\n    auto pos = m_mesh.vertexProperty<Point>(\"v:point\");\n    auto tex = m_mesh.vertexProperty<TexCoord>(\"v:tex\");\n    auto idx = m_mesh.addVertexProperty<int>(\"v:idx\", -1);\n    auto weight = m_mesh.addHalfedgeProperty<dvec2>(\"h:lscm\");\n    auto locked = m_mesh.getVertexProperty<bool>(\"v:locked\");\n    assert(locked);\n\n    // compute weights/gradients per face/halfedge\n    for (auto f : m_mesh.faces())\n    {\n        // collect face halfedge\n        auto fh_it = m_mesh.halfedges(f);\n        auto ha = *fh_it;\n        ++fh_it;\n        auto hb = *fh_it;\n        ++fh_it;\n        auto hc = *fh_it;\n\n        // collect face vertices\n        dvec3 a = (dvec3)pos[m_mesh.toVertex(ha)];\n        dvec3 b = (dvec3)pos[m_mesh.toVertex(hb)];\n        dvec3 c = (dvec3)pos[m_mesh.toVertex(hc)];\n\n        // calculate local coordinate system\n        dvec3 z = cross(c - b, a - b);\n        dvec3 x = normalize(b - a);\n        dvec3 y = normalize(cross(z, x));\n\n        // calculate local vertex coordinates\n        dvec2 a2D(0.0, 0.0);\n        dvec2 b2D(norm(b - a), 0.0);\n        dvec2 c2D(dot(c - a, x), dot(c - a, y));\n\n        // calculate double triangle area\n        double area = norm(z);\n        if (area)\n            area = 1.0 / area;\n\n        // calculate W_j,Ti (index by corner a,b,c and real/imaginary)\n        double War = c2D[0] - b2D[0];\n        double Wbr = a2D[0] - c2D[0];\n        double Wcr = b2D[0] - a2D[0];\n        double Wai = c2D[1] - b2D[1];\n        double Wbi = a2D[1] - c2D[1];\n        double Wci = b2D[1] - a2D[1];\n\n        // store matrix information per halfedge\n        weight[ha] = dvec2(War * area, Wai * area);\n        weight[hb] = dvec2(Wbr * area, Wbi * area);\n        weight[hc] = dvec2(Wcr * area, Wci * area);\n    }\n\n    // collect free (non-boundary) vertices in array free_vertices[]\n    // assign indices such that idx[ free_vertices[i] ] == i\n    unsigned i = 0;\n    std::vector<SurfaceMesh::Vertex> free_vertices;\n    free_vertices.reserve(m_mesh.nVertices());\n    for (auto v : m_mesh.vertices())\n    {\n        if (!locked[v])\n        {\n            idx[v] = i++;\n            free_vertices.push_back(v);\n        }\n    }\n\n    // build matrix and rhs\n    const unsigned int nV2 = 2 * m_mesh.nVertices();\n    const unsigned int nV = m_mesh.nVertices();\n    const unsigned int N = free_vertices.size();\n    SurfaceMesh::Vertex vi, vj;\n    SurfaceMesh::Halfedge hh;\n    double si, sj0, sj1, sign;\n    int row(0), c0, c1;\n\n    Eigen::SparseMatrix<double> A(2 * N, 2 * N);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(2 * N);\n    std::vector<Eigen::Triplet<double>> triplets;\n\n    for (unsigned int i = 0; i < nV2; ++i)\n    {\n        vi = SurfaceMesh::Vertex(i % nV);\n\n        if (i < nV)\n        {\n            sign = 1.0;\n            c0 = 0;\n            c1 = 1;\n        }\n        else\n        {\n            sign = -1.0;\n            c0 = 1;\n            c1 = 0;\n        }\n\n        if (!locked[vi])\n        {\n            si = 0;\n\n            for (auto h : m_mesh.halfedges(vi))\n            {\n                vj = m_mesh.toVertex(h);\n                sj0 = sj1 = 0;\n\n                if (!m_mesh.isSurfaceBoundary(h))\n                {\n                    const dvec2& wj = weight[h];\n                    const dvec2& wi = weight[m_mesh.prevHalfedge(h)];\n\n                    sj0 += sign * wi[c0] * wj[0] + wi[c1] * wj[1];\n                    sj1 += -sign * wi[c0] * wj[1] + wi[c1] * wj[0];\n                    si += wi[0] * wi[0] + wi[1] * wi[1];\n                }\n\n                h = m_mesh.oppositeHalfedge(h);\n                if (!m_mesh.isSurfaceBoundary(h))\n                {\n                    const dvec2& wi = weight[h];\n                    const dvec2& wj = weight[m_mesh.prevHalfedge(h)];\n\n                    sj0 += sign * wi[c0] * wj[0] + wi[c1] * wj[1];\n                    sj1 += -sign * wi[c0] * wj[1] + wi[c1] * wj[0];\n                    si += wi[0] * wi[0] + wi[1] * wi[1];\n                }\n\n                if (!locked[vj])\n                {\n                    triplets.emplace_back(row, idx[vj], sj0);\n                    triplets.emplace_back(row, idx[vj] + N, sj1);\n                }\n                else\n                {\n                    b[row] -= sj0 * tex[vj][0];\n                    b[row] -= sj1 * tex[vj][1];\n                }\n            }\n\n            triplets.emplace_back(row, idx[vi] + (i < nV ? 0 : N), 0.5 * si);\n\n            ++row;\n        }\n    }\n\n    // build sparse matrix from triplets\n    A.setFromTriplets(triplets.begin(), triplets.end());\n\n    // solve A*X = B\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);\n    Eigen::VectorXd x = solver.solve(b);\n    if (solver.info() != Eigen::Success)\n    {\n        std::cerr << \"SurfaceParameterization: Could not solve linear system\\n\";\n    }\n    else\n    {\n        // copy solution\n        for (i = 0; i < N; ++i)\n        {\n            tex[free_vertices[i]] = TexCoord(x[i], x[i + N]);\n        }\n    }\n\n    // scale tex coordiantes to unit square\n    TexCoord bbmin(1, 1), bbmax(0, 0);\n    for (auto v : m_mesh.vertices())\n    {\n        bbmin = min(bbmin, tex[v]);\n        bbmax = max(bbmax, tex[v]);\n    }\n    bbmax -= bbmin;\n    Scalar s = std::max(bbmax[0], bbmax[1]);\n    for (auto v : m_mesh.vertices())\n    {\n        tex[v] -= bbmin;\n        tex[v] /= s;\n    }\n\n    // clean-up\n    m_mesh.removeVertexProperty(idx);\n    m_mesh.removeVertexProperty(locked);\n    m_mesh.removeHalfedgeProperty(weight);\n}\n\n//=============================================================================\n} // namespace pmp\n//=============================================================================\n", "meta": {"hexsha": "91b7c9ad808462bba058ef7fdca6fbf1eccad237", "size": 14059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pmp/algorithms/SurfaceParameterization.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/SurfaceParameterization.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/SurfaceParameterization.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": 30.169527897, "max_line_length": 80, "alphanum_fraction": 0.520876307, "num_tokens": 3621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.056652426502516375, "lm_q1q2_score": 0.025459183194787002}}
{"text": "/*\n[begin_description]\nModification of the implicit Euler method, works with the MTL4 matrix library only. \n[end_description]\n\nCopyright 2009-2011 Karsten Ahnert\nCopyright 2009-2011 Mario Mulansky\nCopyright 2012 Andreas Angelopoulos\n\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE_1_0.txt or\ncopy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n\n\n#ifndef BOOST_NUMERIC_ODEINT_EXTERNAL_MTL4_RESIZE_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_EXTERNAL_MTL4_RESIZE_HPP_INCLUDED\n\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resize.hpp>\n#include <boost/numeric/odeint/util/same_size.hpp>\n\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\ntemplate< class Value , class Parameters >\nstruct is_resizeable< mtl::dense_vector< Value , Parameters > >\n{ \n    typedef boost::true_type type;\n    const static bool value = type::value;\n};\n\ntemplate< class Value , class Parameters >\nstruct is_resizeable< mtl::dense2D< Value , Parameters > >\n{\n    typedef boost::true_type type;\n    const static bool value = type::value;\n};\n\ntemplate< class Value , class Parameters >\nstruct is_resizeable< mtl::compressed2D< Value , Parameters > >\n{\n    typedef boost::true_type type;\n    const static bool value = type::value;\n};\n\n\n\n\ntemplate< class Value , class Parameters >\nstruct same_size_impl< mtl::dense_vector< Value , Parameters > , mtl::dense_vector< Value , Parameters > >\n{\n    static bool same_size( const mtl::dense_vector< Value , Parameters > &v1 ,\n                           const mtl::dense_vector< Value , Parameters > &v2 )\n    {\n        return mtl::size( v1 ) == mtl::size( v2 );\n    }\n};\n\ntemplate< class Value , class Parameters >\nstruct resize_impl< mtl::dense_vector< Value , Parameters > , mtl::dense_vector< Value , Parameters > >\n{\n    static void resize( mtl::dense_vector< Value , Parameters > &v1 ,\n                        const mtl::dense_vector< Value , Parameters > &v2 )\n    {\n        v1.change_dim( mtl::size( v2 ) );\n    }\n};\n\n\n\ntemplate< class Value , class MatrixParameters , class VectorParameters >\nstruct same_size_impl< mtl::dense2D< Value , MatrixParameters > , mtl::dense_vector< Value , VectorParameters > >\n{\n    static bool same_size( const mtl::dense2D< Value , MatrixParameters > &m , \n                           const mtl::dense_vector< Value , VectorParameters > &v )\n    {\n        return ( ( mtl::size( v ) == m.num_cols() ) && ( mtl::size( v ) == m.num_rows() ) );\n    }\n};\n\ntemplate< class Value , class MatrixParameters , class VectorParameters >\nstruct resize_impl< mtl::dense2D< Value , MatrixParameters > , mtl::dense_vector< Value , VectorParameters > >\n{\n    static void resize( mtl::dense2D< Value , MatrixParameters > &m , \n                        const mtl::dense_vector< Value , VectorParameters > &v )\n    {\n        m.change_dim( mtl::size( v ) , mtl::size( v ) , false );\n    }\n};\n\n\n\n\ntemplate< class Value , class MatrixParameters , class VectorParameters >\nstruct same_size_impl< mtl::compressed2D< Value , MatrixParameters > , mtl::dense_vector< Value , VectorParameters > >\n{\n    static bool same_size( const mtl::compressed2D< Value , MatrixParameters > &m , \n                           const mtl::dense_vector< Value , VectorParameters > &v )\n    {\n        return ( ( mtl::size( v ) == m.num_cols() ) && ( mtl::size( v ) == m.num_rows() ) );\n    }\n};\n\ntemplate< class Value , class MatrixParameters , class VectorParameters >\nstruct resize_impl< mtl::compressed2D< Value , MatrixParameters > , mtl::dense_vector< Value , VectorParameters > >\n{\n    static void resize( mtl::compressed2D< Value , MatrixParameters > &m , \n                        const mtl::dense_vector< Value , VectorParameters > &v )\n    {\n        m.change_dim( mtl::size( v ) , mtl::size( v ) );\n    }\n};\n\n\n\n\n\n\n\n\n} // namespace odeint\n} // namesapce numeric\n} // namespace boost\n\n#endif // BOOST_NUMERIC_ODEINT_EXTERNAL_MTL4_RESIZE_HPP_INCLUDED\n", "meta": {"hexsha": "935697474a2f7c4e08121c88653190edf1f20236", "size": 4107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/odeint/external/mtl4/mtl4_resize.hpp", "max_stars_repo_name": "datacratic/boost-svn", "max_stars_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T18:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T18:18:10.000Z", "max_issues_repo_path": "boost/numeric/odeint/external/mtl4/mtl4_resize.hpp", "max_issues_repo_name": "datacratic/boost-svn", "max_issues_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/odeint/external/mtl4/mtl4_resize.hpp", "max_forks_repo_name": "datacratic/boost-svn", "max_forks_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6492537313, "max_line_length": 118, "alphanum_fraction": 0.6803019235, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.06465349286184457, "lm_q1q2_score": 0.02536594644864787}}
{"text": "/*!\n@file\nForward declares `boost::hana::Logical`.\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_LOGICAL_HPP\n#define BOOST_HANA_FWD_LOGICAL_HPP\n\n#include <boost/hana/config.hpp>\n#include <boost/hana/detail/std/forward.hpp>\n#include <boost/hana/fwd/core/datatype.hpp>\n#include <boost/hana/fwd/core/models.hpp>\n#include <boost/hana/fwd/core/operators.hpp>\n\n\nnamespace boost { namespace hana {\n    //! @ingroup group-concepts\n    //! The `Logical` concept represents types with a truth value.\n    //!\n    //! Intuitively, a `Logical` is just a `bool`, or something that can act\n    //! like one. However, in the context of programming with heterogeneous\n    //! objects, it becomes extremely important to distinguish between those\n    //! objects whose truth value is known at compile-time, and those whose\n    //! truth value is only known at runtime. The reason why this is so\n    //! important is because it is possible to branch at compile-time on\n    //! a condition whose truth value is known at compile-time, and hence\n    //! the return type of the enclosing function can depend on that truth\n    //! value. However, if the truth value is only known at runtime, then\n    //! the compiler has to compile both branches (because any or both of\n    //! them may end up being used), which creates the additional requirement\n    //! that both branches must evaluate to the same type.\n    //!\n    //! Specifically, `Logical` (almost) represents a [boolean algebra][1],\n    //! which is a mathematical structure encoding the usual properties that\n    //! allow us to reason with `bool`. The exact properties that must be\n    //! satisfied by any model of `Logical` are rigorously stated in the laws\n    //! below.\n    //!\n    //!\n    //! Truth, falsity and logical equivalence\n    //! --------------------------------------\n    //! A `Logical` `x` is said to be _true-valued_, or sometimes also just\n    //! _true_ as an abuse of notation, if\n    //! @code\n    //!     if_(x, true, false) == true\n    //! @endcode\n    //!\n    //! Similarly, `x` is _false-valued_, or sometimes just _false_, if\n    //! @code\n    //!     if_(x, true, false) == false\n    //! @endcode\n    //!\n    //! This provides a standard way of converting any `Logical` to a straight\n    //! `bool`. The notion of truth value suggests another definition, which\n    //! is that of logical equivalence. We will say that two `Logical`s `x`\n    //! and `y` are _logically equivalent_ if they have the same truth value.\n    //! To denote that some expressions `p` and `q` of a Logical data type are\n    //! logically equivalent, we will sometimes also write\n    //! @code\n    //!     p   if and only if   q\n    //! @endcode\n    //! which is very common in mathematics. The intuition behind this notation\n    //! is that whenever `p` is true-valued, then `q` should be; but when `p`\n    //! is false-valued, then `q` should be too. Hence, `p` should be\n    //! true-valued when (and only when) `q` is true-valued.\n    //!\n    //!\n    //! Laws\n    //! ----\n    //! As outlined above, the `Logical` concept almost represents a boolean\n    //! algebra. The rationale for this laxity is to allow things like integers\n    //! to act like `Logical`s, which is aligned with C++, even though they do\n    //! not form a boolean algebra. Even though we depart from the usual\n    //! axiomatization of boolean algebras, we have found through experience\n    //! that the definition of a Logical given here is largely compatible with\n    //! intuition.\n    //!\n    //! The following laws must be satisfied for any data type `L` modeling\n    //! the `Logical` concept. Let `a`, `b` and `c` be objects of a `Logical`\n    //! data type, and let `t` and `f` be arbitrary _true-valued_ and\n    //! _false-valued_ `Logical`s of that data type, respectively. Then,\n    //! @code\n    //!     // associativity\n    //!     or_(a, or_(b, c))   == or_(or_(a, b), c)\n    //!     and_(a, and_(b, c)) == and_(and_(a, b), c)\n    //!\n    //!     // equivalence through commutativity\n    //!     or_(a, b)   if and only if   or_(b, a)\n    //!     and_(a, b)  if and only if   and_(b, a)\n    //!\n    //!     // absorption\n    //!     or_(a, and_(a, b)) == a\n    //!     and_(a, or_(a, b)) == a\n    //!\n    //!     // left identity\n    //!     or_(a, f)  == a\n    //!     and_(a, t) == a\n    //!\n    //!     // distributivity\n    //!     or_(a, and_(b, c)) == and_(or_(a, b), or_(a, c))\n    //!     and_(a, or_(b, c)) == or_(and_(a, b), and_(a, c))\n    //!\n    //!     // complements\n    //!     or_(a, not_(a))  is true-valued\n    //!     and_(a, not_(a)) is false-valued\n    //! @endcode\n    //!\n    //! > #### Why is the above not a boolean algebra?\n    //! > If you look closely, you will find that we depart from the usual\n    //! > boolean algebras because:\n    //! > 1. we do not require the elements representing truth and falsity to\n    //! >    be unique\n    //! > 2. we do not enforce commutativity of the `and_` and `or_` operations\n    //! > 3. because we do not enforce commutativity, the identity laws become\n    //! >    left-identity laws\n    //!\n    //!\n    //! Minimal complete definition\n    //! ---------------------------\n    //! 1. `eval_if`, `not_` and `while_`\\n\n    //! @todo\n    //!\n    //!\n    //! Provided models\n    //! ---------------\n    //! 1. For arithmetic data types\\n\n    //! A data type `T` is arithmetic if `std::is_arithmetic<T>::value` is\n    //! true. For an arithmetic data type `T`, a model of `Logical` is\n    //! provided automatically by using the result of the builtin implicit\n    //! conversion to `bool` as a truth value. Specifically, the minimal\n    //! complete definition for those data types is\n    //! @code\n    //!     eval_if(cond, then, else_) = cond ? then(id) : else(id)\n    //!     not_(cond) = static_cast<T>(cond ? false : true)\n    //!     while_(pred, state, f) = equivalent to a normal while loop\n    //! @endcode\n    //!\n    //! > #### Rationale for not providing a model for all contextually convertible to bool data types\n    //! > The `not_` method can not be implemented in a meaningful way for all\n    //! > of those types. For example, one can not cast a pointer type `T*`\n    //! > to bool and then back again to `T*` in a meaningful way. With an\n    //! > arithmetic type `T`, however, it is possible to cast from `T` to\n    //! > bool and then to `T` again; the result will be `0` or `1` depending\n    //! > on the truth value. If you want to use a pointer type or something\n    //! > similar in a conditional, it is suggested to explicitly convert it\n    //! > to bool by using `to<bool>`.\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    //!     &&  ->  and_\n    //!     ||  ->  or_\n    //! @endcode\n    //!\n    //!\n    //! @bug\n    //! We can't use perfect forwarding in that MCD because of\n    //! [this bug](http://llvm.org/bugs/show_bug.cgi?id=20619).\n    //!\n    //! @todo\n    //! The methods don't short-circuit right now, which is a real bummer.\n    //!\n    //!\n    //! [1]: http://en.wikipedia.org/wiki/Boolean_algebra_(structure)\n    struct Logical { };\n\n    //! Conditionally return one of two values based on a condition.\n    //! @relates Logical\n    //!\n    //! Specifically, `then` is returned iff `cond` is true-valued, and\n    //! `else_` is returned otherwise. Note that some `Logical` models may\n    //! allow `then` and `else_` to have different types, while others may\n    //! require both values to have the same type.\n    //!\n    //!\n    //! @param cond\n    //! The condition determining which of the two values is returned.\n    //!\n    //! @param then\n    //! The value returned when `cond` is true-valued.\n    //!\n    //! @param else_\n    //! The value returned when `cond` is false-valued.\n    //!\n    //!\n    //! Example\n    //! -------\n    //! @snippet example/logical.cpp if_\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto if_ = [](auto&& cond, auto&& then, auto&& else_) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename L, typename = void>\n    struct if_impl;\n\n    struct _if {\n        template <typename Cond, typename Then, typename Else>\n        constexpr decltype(auto) operator()(Cond&& cond, Then&& then, Else&& else_) const {\n#ifdef BOOST_HANA_CONFIG_CHECK_DATA_TYPES\n            static_assert(_models<Logical, typename datatype<Cond>::type>{},\n            \"hana::if_(cond, then, else) requires cond to be a Logical\");\n#endif\n            return if_impl<typename datatype<Cond>::type>::apply(\n                detail::std::forward<Cond>(cond),\n                detail::std::forward<Then>(then),\n                detail::std::forward<Else>(else_)\n            );\n        }\n    };\n\n    constexpr _if if_{};\n#endif\n\n    //! Conditionally execute one of two branches based on a condition.\n    //! @relates Logical\n    //!\n    //! Given a condition and two branches in the form of lambdas, `eval_if`\n    //! will evaluate the branch selected by the condition and return the\n    //! result. But that's not all; the lambdas must accept a parameter\n    //! (usually called `_`), which can be used to defer the compile-time\n    //! evaluation of expressions as required. Here's an example:\n    //! @code\n    //!     template <typename N>\n    //!     auto fact(N n) {\n    //!         return hana::eval_if(n == hana::int_<0>,\n    //!             [](auto _) { return hana::int_<1>; },\n    //!             [=](auto _) { return n * fact(_(n) - hana::int_<1>); }\n    //!         );\n    //!     }\n    //! @endcode\n    //!\n    //! What happens here is that `eval_if` will pass an identity function to\n    //! the selected branch. Hence, `_(x)` is always the same as `x`, but the\n    //! compiler can't tell until the lambda has been called! Hence, the\n    //! compiler has to wait before it instantiates the body of the lambda\n    //! and no infinite recursion happens. However, this trick to delay the\n    //! instantiation of the lambda's body can only be used when the condition\n    //! is known at compile-time, because otherwise both branches have to be\n    //! instantiated inside the `eval_if` anyway. Also note that `always` can\n    //! be used to make `eval_if` easier to work with:\n    //! @code\n    //!     template <typename N>\n    //!     auto fact(N n) {\n    //!         return hana::eval_if(n == hana::int_<0>,\n    //!             always(hana::int_<1>),\n    //!             [=](auto _) { return n * fact(_(n) - hana::int_<1>); }\n    //!         );\n    //!     }\n    //! @endcode\n    //!\n    //! There are several caveats to note with our approach to lazy branching.\n    //! First, because we're using lambdas, it means that the function's\n    //! result can't be used in a constant expression. This is a limitation\n    //! of the current version of C++.\n    //!\n    //! The second caveat is that compilers currently have several bugs\n    //! regarding deeply nested lambdas with captures. So you always risk\n    //! crashing the compiler, but this is a question of time before it is\n    //! not a problem anymore.\n    //!\n    //! Finally, it means that conditionals can't be written directly inside\n    //! unevaluated contexts. The reason is that a lambda can't appear in an\n    //! unevaluated context, for example in `decltype`. One way to workaround\n    //! this is to completely lift your type computations into variable\n    //! templates instead. So instead of writing e.g. (stupid example, just\n    //! to show):\n    //! @code\n    //!     template <typename T>\n    //!     struct f : decltype(eval_if(true_,\n    //!             [](auto _) { return type<T>; },\n    //!             [](auto _) { return type<T>; }\n    //!         ))\n    //!     { };\n    //! @endcode\n    //!\n    //! you could instead write\n    //!\n    //! @code\n    //!     template <typename T>\n    //!     auto f_impl(_type<T> t) {\n    //!         return eval_if(true_,\n    //!             [](auto) { return type<T>; },\n    //!             [](auto) { return type<T>; }\n    //!         );\n    //!     }\n    //!\n    //!     template <typename T>\n    //!     using f = decltype(f_impl(type<T>));\n    //! @endcode\n    //!\n    //! Now, this hoop-jumping only has to be done in one place, because\n    //! you should use normal function notation everywhere else in your\n    //! metaprogram to perform type computations. So the syntactic\n    //! cost is amortized over the whole program.\n    //!\n    //!\n    //! @param cond\n    //! The condition determining which of the two branches is selected.\n    //!\n    //! @param then\n    //! A function called as `then([](auto x) { return x; })` if `cond` is\n    //! true-valued.\n    //!\n    //! @param else_\n    //! A function called as `else_([](auto x) { return x; })` if `cond` is\n    //! false-valued.\n    //!\n    //!\n    //! Example (purely compile-time condition)\n    //! ---------------------------------------\n    //! @snippet example/logical.cpp heterogeneous_eval_if\n    //!\n    //! Example (runtime or `constexpr` condition)\n    //! ------------------------------------------\n    //! @snippet example/logical.cpp homogeneous_eval_if\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto eval_if = [](auto&& cond, auto&& then, auto&& else_) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename L, typename = void>\n    struct eval_if_impl;\n\n    struct _eval_if {\n        template <typename Cond, typename Then, typename Else>\n        constexpr decltype(auto) operator()(Cond&& cond, Then&& then, Else&& else_) const {\n#ifdef BOOST_HANA_CONFIG_CHECK_DATA_TYPES\n            static_assert(_models<Logical, typename datatype<Cond>::type>{},\n            \"hana::eval_if(cond, then, else) requires cond to be a Logical\");\n#endif\n            return eval_if_impl<typename datatype<Cond>::type>::apply(\n                detail::std::forward<Cond>(cond),\n                detail::std::forward<Then>(then),\n                detail::std::forward<Else>(else_)\n            );\n        }\n    };\n\n    constexpr _eval_if eval_if{};\n#endif\n\n    //! Apply a function to an initial state while some predicate is satisfied.\n    //! @relates Logical\n    //!\n    //! This method is a natural extension of the `while` language construct\n    //! to manipulate a state whose type may change from one iteration to\n    //! another. However, note that having a state whose type changes from\n    //! one iteration to the other is only possible as long as the predicate\n    //! returns a `Logical` whose truth value is known at compile-time.\n    //!\n    //! Specifically, `while_(pred, state, f)` is equivalent to\n    //! @code\n    //!     f(...f(f(state)))\n    //! @endcode\n    //! where `f` is iterated as long as `pred(f(...))` is a true-valued\n    //! `Logical`.\n    //!\n    //!\n    //! @param pred\n    //! A predicate called on the state or on the result of applying `f` a\n    //! certain number of times to the state, and returning whether `f`\n    //! should be applied one more time.\n    //!\n    //! @param state\n    //! The initial state on which `f` is applied.\n    //!\n    //! @param f\n    //! A function that is iterated on the initial state. Note that the\n    //! return type of `f` may change from one iteration to the other,\n    //! but only while `pred` returns a compile-time `Logical`. In other\n    //! words, `decltype(f(stateN))` may differ from `decltype(f(stateN+1))`,\n    //! but only if `pred(f(stateN))` returns a compile-time `Logical`.\n    //!\n    //!\n    //! Example (purely compile-time condition)\n    //! ---------------------------------------\n    //! @snippet example/logical.cpp heterogeneous_while\n    //!\n    //! Example (runtime or `constexpr` condition)\n    //! ------------------------------------------\n    //! @snippet example/logical.cpp homogeneous_while\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto while_ = [](auto&& pred, auto&& state, auto&& f) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename L, typename = void>\n    struct while_impl;\n\n    struct _while {\n        template <typename Pred, typename State, typename F>\n        constexpr decltype(auto) operator()(Pred&& pred, State&& state, F&& f) const {\n            using Cond = decltype(pred(state));\n\n#ifdef BOOST_HANA_CONFIG_CHECK_DATA_TYPES\n            static_assert(_models<Logical, typename datatype<Cond>::type>{},\n            \"hana::while_(pred, state, f) requires pred(state) to be a Logical\");\n#endif\n            return while_impl<typename datatype<Cond>::type>::apply(\n                detail::std::forward<Pred>(pred),\n                detail::std::forward<State>(state),\n                detail::std::forward<F>(f)\n            );\n        }\n    };\n\n    constexpr _while while_{};\n#endif\n\n    //! Apply a function to an initial state until some predicate is satisfied.\n    //! @relates Logical\n    //!\n    //! Specifically, `until(pred, state, f)` is equivalent to\n    //! @code\n    //!     f(...f(f(state)))\n    //! @endcode\n    //! where `f` is iterated until `pred(f(...))` is a true-valued `Logical`.\n    //!\n    //!\n    //! @param pred\n    //! A predicate called on the state or on the result of applying `f` a\n    //! certain number of times to the state, and returning whether `f`\n    //! should stop being applied.\n    //!\n    //! @param state\n    //! The initial state on which `f` is applied.\n    //!\n    //! @param f\n    //! A function that is iterated on the initial state. Note that the\n    //! return type of `f` may change from one iteration to the other,\n    //! but only while `pred` returns a compile-time `Logical`. In other\n    //! words, `decltype(f(stateN))` may differ from `decltype(f(stateN+1))`,\n    //! but only if `pred(f(stateN))` returns a compile-time `Logical`.\n    //!\n    //!\n    //! Example (purely compile-time condition)\n    //! ---------------------------------------\n    //! @snippet example/logical.cpp heterogeneous_until\n    //!\n    //! Example (runtime or `constexpr` condition)\n    //! ------------------------------------------\n    //! @snippet example/logical.cpp homogeneous_until\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto until = [](auto&& pred, auto&& state, auto&& f) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename L, typename = void>\n    struct until_impl;\n\n    struct _until {\n        template <typename Pred, typename State, typename F>\n        constexpr decltype(auto) operator()(Pred&& pred, State&& state, F&& f) const {\n            using Cond = decltype(pred(state));\n\n#ifdef BOOST_HANA_CONFIG_CHECK_DATA_TYPES\n            static_assert(_models<Logical, typename datatype<Cond>::type>{},\n            \"hana::until(pred, state, f) requires pred(state) to be a Logical\");\n#endif\n            return until_impl<typename datatype<Cond>::type>::apply(\n                detail::std::forward<Pred>(pred),\n                detail::std::forward<State>(state),\n                detail::std::forward<F>(f)\n            );\n        }\n    };\n\n    constexpr _until until{};\n#endif\n\n    //! Negates a `Logical`.\n    //! @relates Logical\n    //!\n    //! This method returns a `Logical` of the same data type, but whose\n    //! truth-value is negated. Specifically, `not_(x)` returns a false-valued\n    //! `Logical` if `x` is a true-valued `Logical`, and a true-valued one\n    //! otherwise.\n    //!\n    //!\n    //! Example\n    //! -------\n    //! @snippet example/logical.cpp not_\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto not_ = [](auto&& x) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename L, typename = void>\n    struct not_impl;\n\n    struct _not {\n        template <typename X>\n        constexpr decltype(auto) operator()(X&& x) const {\n            return not_impl<typename datatype<X>::type>::apply(\n                detail::std::forward<X>(x)\n            );\n        }\n    };\n\n    constexpr _not not_{};\n#endif\n\n    //! Return whether all the arguments are true-valued.\n    //! @relates Logical\n    //!\n    //! `and_` can be called with one argument or more. When called with\n    //! two arguments, `and_` uses tag-dispatching to find the right\n    //! implementation. Otherwise,\n    //! @code\n    //!     and_(x) == x\n    //!     and_(x, y, ...z) == and_(and_(x, y), z...)\n    //! @endcode\n    //!\n    //!\n    //! Example\n    //! -------\n    //! @snippet example/logical.cpp and_\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto and_ = [](auto&& x, auto&& ...y) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename L, typename = void>\n    struct and_impl;\n\n    struct _and {\n        template <typename X, typename Y>\n        constexpr decltype(auto) operator()(X&& x, Y&& y) const;\n\n        template <typename X, typename ...Y>\n        constexpr decltype(auto) operator()(X&& x, Y&& ...y) const;\n    };\n\n    constexpr _and and_{};\n#endif\n\n    //! Return whether any of the arguments is true-valued.\n    //! @relates Logical\n    //!\n    //! `or_` can be called with one argument or more. When called with\n    //! two arguments, `or_` uses tag-dispatching to find the right\n    //! implementation. Otherwise,\n    //! @code\n    //!     or_(x) == x\n    //!     or_(x, y, ...z) == or_(or_(x, y), z...)\n    //! @endcode\n    //!\n    //!\n    //! Example\n    //! -------\n    //! @snippet example/logical.cpp or_\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto or_ = [](auto&& x, auto&& ...y) -> decltype(auto) {\n        return tag-dispatched;\n    };\n#else\n    template <typename L, typename = void>\n    struct or_impl;\n\n    struct _or {\n        template <typename X, typename Y>\n        constexpr decltype(auto) operator()(X&& x, Y&& y) const;\n\n        template <typename X, typename ...Y>\n        constexpr decltype(auto) operator()(X&& x, Y&& ...y) const;\n    };\n\n    constexpr _or or_{};\n#endif\n\n    template <>\n    struct operators::of<Logical>\n        : decltype(and_), decltype(or_), decltype(not_)\n    { };\n}} // end namespace boost::hana\n\n#endif // !BOOST_HANA_FWD_LOGICAL_HPP\n", "meta": {"hexsha": "18e9779b2aefba35a551dd0a172584ef96cf9466", "size": 22201, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/hana/fwd/logical.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/logical.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/logical.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": 37.885665529, "max_line_length": 102, "alphanum_fraction": 0.5869104995, "num_tokens": 5502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.060975184277760455, "lm_q1q2_score": 0.025298533579088095}}
{"text": "/**------------------------------------------------------------------------------\r\n\r\n* references:\r\n*     [1] S.Schear, W.Gurtner and J.Feltens, IONEX: The IONosphere Map EXchange\r\n*         Format Version 1, February 25, 1998\r\n*     [2] S.Schaer, R.Markus, B.Gerhard and A.S.Timon, Daily Global Ionosphere\r\n*         Maps based on GPS Carrier Phase Data Routinely producted by CODE\r\n*         Analysis Center, Proceeding of the IGS Analysis Center Workshop, 1996\r\n*-----------------------------------------------------------------------------*/\r\n#include <boost/log/trivial.hpp>\r\n\r\n\r\n#include \"corrections.hpp\"\r\n#include \"navigation.hpp\"\r\n#include \"acsConfig.hpp\"\r\n#include \"constants.hpp\"\r\n#include \"biasSINEX.hpp\"\r\n#include \"common.hpp\"\r\n\r\n\r\n#define VAR_NOTEC   SQR(30.0)   /* variance of no tec */\r\n#define MIN_EL      0.0         /* min elevation angle (rad) */\r\n#define MIN_HGT     -1000.0     /* min user height (m) */\r\n\r\n/* get index -----------------------------------------------------------------*/\r\nint getindex(\r\n\tdouble value, \r\n\tconst double* range)\r\n{\r\n\tif (range[2] == 0)\t\t\t\t\t\t\t\t\t\t\t\treturn 0;\r\n\tif (range[1] > 0 && (value < range[0] || range[1] < value))\t\treturn -1;\r\n\tif (range[1] < 0 && (value < range[1] || range[0] < value))\t\treturn -1;\r\n\r\n\treturn (int) floor((value - range[0]) / range[2] + 0.5);\r\n}\r\n\r\n/* get number of items -------------------------------------------------------*/\r\nint nitem(\r\n\tconst double* range)\r\n{\r\n\treturn getindex(range[1], range) + 1;\r\n}\r\n\r\n/* data index (i:lat,j:lon,k:hgt) --------------------------------------------*/\r\nint dataindex(\r\n\tint i,\r\n\tint j,\r\n\tint k,\r\n\tconst int* ndata)\r\n{\r\n\tif\t(  i < 0 || ndata[0] <= i\r\n\t\t|| j < 0 || ndata[1] <= j\r\n\t\t|| k < 0 || ndata[2] <= k)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\r\n\treturn i + ndata[0] * (j + ndata[1] * k);\r\n}\r\n\r\n/* read ionex dcb aux data ----------------------------------------------------*/\r\nvoid readionexdcb(\r\n\tstd::ifstream& in,\r\n\tnav_t* navi)\r\n{\r\n\tchar buff[1024];\r\n\tSinexBias entry;\r\n\tbool refObs = false;\r\n\r\n\tentry.tini.sec\t= 2;\r\n\tentry.measType\t= CODE;\r\n\tentry.source\t= \"ionex\";\r\n\r\n\tBOOST_LOG_TRIVIAL(debug)\r\n\t<< \"readionexdcb:\";\r\n\r\n\tstring line;\r\n\twhile (std::getline(in, line))\r\n\t{\r\n\t\tchar* buff = &line[0];\r\n\r\n\t\tif (strlen(buff) < 60)\r\n\t\t\tcontinue;\r\n\r\n\t\tchar* label = buff + 60;\r\n\r\n\t\tSatSys Sat;\r\n\r\n\t\tstring id;\r\n\t\tif\t( strstr(label,\t\"COMMENT\") == label\r\n\t\t\t&&strstr(buff,\t\"Reference observables\"))\r\n\t\t{\r\n\t\t\tchar* ptr = strchr(buff, ':');\r\n\t\t\tif (ptr != NULL)\r\n\t\t\t{\r\n\t\t\t\tstring cod1str(ptr + 2, 3);\r\n\t\t\t\tstring cod2str(ptr + 6, 3);\r\n\r\n\t\t\t\tE_MeasType dummy1;\r\n\t\t\t\tdouble dummy2 = 0;\r\n\t\t\t\tentry.cod1 = str2code(cod1str, dummy1, dummy2);\r\n\t\t\t\tentry.cod2 = str2code(cod2str, dummy1, dummy2);\r\n\r\n\t\t\t\trefObs = true;\r\n\t\t\t}\r\n\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\telse if (strstr(label, \"PRN / BIAS / RMS\") == label)\r\n\t\t{\r\n\t\t\tstring sat(buff + 3,  3);\r\n\t\t\tSat = SatSys(sat.c_str());\r\n\t\t\tentry.Sat  = Sat;\r\n\t\t\tentry.name = \"\";\r\n\t\t\tid = sat;\r\n\r\n\t\t\tif (!refObs)\r\n\t\t\t{\r\n\t\t\t\tif (Sat.sys == +E_Sys::GPS)\r\n\t\t\t\t{\r\n\t\t\t\t\tentry.cod1 = E_ObsCode::L1W;\r\n\t\t\t\t\tentry.cod2 = E_ObsCode::L2W;\r\n\t\t\t\t}\r\n\t\t\t\telse if (Sat.sys == +E_Sys::GLO)\r\n\t\t\t\t{\r\n\t\t\t\t\tentry.cod1 = E_ObsCode::L1P;\r\n\t\t\t\t\tentry.cod2 = E_ObsCode::L2P;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t\t\t<< \"ionex invalid satellite: \" << id;\r\n\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (Sat)\r\n\t\t\t{\r\n\t\t\t\tentry.bias =     str2num(buff,  6, 10) * CLIGHT * 1E-9;\r\n\t\t\t\tentry.var  = SQR(str2num(buff, 16, 10) * CLIGHT * 1E-9);\r\n\r\n\t\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t\t<< id << entry.bias;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t\t<< \"ionex invalid satellite: \" << id;\r\n\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//fallthrough to after the ifs\r\n\t\t}\r\n\t\telse if (strstr(label, \"STATION / BIAS / RMS\") == label)\r\n\t\t{\r\n\t\t\tstring sys (buff + 3, 1);\r\n\t\t\tstring name(buff + 6, 4);\r\n\t\t\tSat = SatSys(sys.c_str());\r\n\t\t\tentry.Sat  = Sat;\r\n\t\t\tentry.name = name;\r\n\t\t\tid = name;\r\n\r\n\t\t\tif (!refObs)\r\n\t\t\t{\r\n\t\t\t\tif (Sat.sys == +E_Sys::GPS)\r\n\t\t\t\t{\r\n\t\t\t\t\tentry.cod1 = E_ObsCode::L1W;\r\n\t\t\t\t\tentry.cod2 = E_ObsCode::L2W;\r\n\t\t\t\t}\r\n\t\t\t\telse if (Sat.sys == +E_Sys::GLO)\r\n\t\t\t\t{\r\n\t\t\t\t\tentry.cod1 = E_ObsCode::L1P;\r\n\t\t\t\t\tentry.cod2 = E_ObsCode::L2P;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t\t\t<< \"ionex invalid satellite system: \" << sys;\r\n\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (Sat)\r\n\t\t\t{\r\n\t\t\t\tentry.bias =     str2num(buff, 26, 10) * CLIGHT * 1E-9;\r\n\t\t\t\tentry.var  = SQR(str2num(buff, 36, 10) * CLIGHT * 1E-9);\r\n\r\n\t\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t\t<< id << entry.bias;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t\t<< \"ionex invalid station: \" << id;\r\n\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//fallthrough to after the ifs\r\n\t\t}\r\n\t\telse if (strstr(label, \"END OF AUX DATA\") == label)\r\n\t\t\tbreak;\r\n\t\telse\r\n\t\t\tcontinue;\r\n\r\n\t\tentry.name = id;\r\n\t\t\r\n\t\tif\t( Sat.sys == +E_Sys::GLO\r\n\t\t\t&&Sat.prn == 0)\r\n\t\t{\r\n\t\t\t// this seems to be a receiver\r\n\t\t\t// for ambiguous GLO receiver bias id (i.e. PRN not specified), duplicate bias entry for each satellite\r\n\t\t\tfor (int prn = MINPRNGLO; prn <= MAXPRNGLO; prn++)\r\n\t\t\t{\r\n\t\t\t\tSat.prn\t= prn;\r\n\t\t\t\tid = entry.name + \":\" + Sat.id();\r\n\t\t\t\t// entry.Sat = Sat;\r\n\t\t\t\tpushBiasSinex(id, entry);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if\t( Sat.sys == +E_Sys::GLO\r\n\t\t\t\t&&Sat.prn != 0)\r\n\t\t{\r\n\t\t\t// this can be a receiver or satellite\r\n\t\t\tid = id + \":\" + Sat.id();\r\n\t\t\tpushBiasSinex(id, entry);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// this can be a receiver or satellite\r\n\t\t\tid = id + \":\" + Sat.sysChar();\r\n\t\t\tpushBiasSinex(id, entry);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/* read ionex header ---------------------------------------------------------*/\r\ndouble readionexh(\r\n\tstd::ifstream& in,\r\n\tdouble* lats, \r\n\tdouble* lons, \r\n\tdouble* hgts, \r\n\tdouble& rb, \r\n\tdouble& nexp,\r\n\tnav_t* navi)\r\n{\r\n\tdouble ver = 0;\r\n\r\n\tBOOST_LOG_TRIVIAL(debug)\r\n\t<< \"readionexh:\";\r\n\r\n\tstring line;\r\n\twhile (std::getline(in, line))\r\n\t{\r\n\t\tchar* buff = &line[0];\r\n\r\n\t\tif (strlen(buff) < 60)\r\n\t\t\tcontinue;\r\n\r\n\t\tchar* label = buff + 60;\r\n\r\n\t\tif (strstr(label, \"IONEX VERSION / TYPE\") == label)\r\n\t\t{\r\n\t\t\tif (buff[20] == 'I')\r\n\t\t\t\tver = str2num(buff, 0, 8);\r\n\r\n\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t<< \" ver= \" << ver;\r\n\t\t}\r\n\t\telse if (strstr(label, \"BASE RADIUS\") == label)\r\n\t\t{\r\n\t\t\trb = str2num(buff, 0, 8);\r\n\r\n\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t<< \" rad= \" << rb;\r\n\t\t}\r\n\t\telse if (strstr(label, \"HGT1 / HGT2 / DHGT\") == label)\r\n\t\t{\r\n\t\t\thgts[0] = str2num(buff, 2, 6);\r\n\t\t\thgts[1] = str2num(buff, 8, 6);\r\n\t\t\thgts[2] = str2num(buff, 14, 6);\r\n\r\n\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t<< \" heights= \" << hgts[0] << \" \" << hgts[1] << \" \" << hgts[2];\r\n\t\t}\r\n\t\telse if (strstr(label, \"LAT1 / LAT2 / DLAT\") == label)\r\n\t\t{\r\n\t\t\tlats[0] = str2num(buff, 2, 6);\r\n\t\t\tlats[1] = str2num(buff, 8, 6);\r\n\t\t\tlats[2] = str2num(buff, 14, 6);\r\n\r\n\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t<< \" lats= \" << lats[0] << \" \" << lats[1] << \" \" << lats[2];\r\n\t\t}\r\n\t\telse if (strstr(label, \"LON1 / LON2 / DLON\") == label)\r\n\t\t{\r\n\t\t\tlons[0] = str2num(buff, 2,  6);\r\n\t\t\tlons[1] = str2num(buff, 8,  6);\r\n\t\t\tlons[2] = str2num(buff, 14, 6);\r\n\r\n\t\t\tBOOST_LOG_TRIVIAL(debug)\r\n\t\t\t<< \" lons= \" << lons[0] << \" \" << lons[1] << \" \" << lons[2];\r\n\t\t}\r\n\t\telse if ( strstr(label, \"EXPONENT\") == label)\r\n\t\t{\r\n\t\t\tnexp = str2num(buff, 0, 6);\r\n\t\t}\r\n\t\telse if\t( strstr(label,\t\"START OF AUX DATA\") == label\r\n\t\t\t\t&&strstr(buff,\t\"DIFFERENTIAL CODE BIASES\"))\r\n\t\t{\r\n\t\t\treadionexdcb(in, navi);\r\n\t\t}\r\n\t\telse if (strstr(label, \"END OF HEADER\") == label)\r\n\t\t{\r\n\t\t\treturn ver;\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n/* read ionex body -----------------------------------------------------------*/\r\nint readionexb(\r\n\tstd::ifstream& in,\r\n\tconst double* lats,\r\n\tconst double* lons,\r\n\tconst double* hgts,\r\n\tdouble rb,\r\n\tdouble nexp,\r\n\tnav_t* navi)\r\n{\r\n\tGTime time = {};\r\n\tint type = 0;\r\n\r\n\t// if (fdebug)\r\n\t// \tfprintf(fdebug, \"readionexb:\\n\");\r\n\r\n\tstring line;\r\n\twhile (std::getline(in, line))\r\n\t{\r\n\t\tchar* buff = &line[0];\r\n\t\tchar* label = buff + 60;\r\n\r\n\t\tif (strlen(buff) < 60)\r\n\t\t\tcontinue;\r\n\r\n\t\tif \t\t(strstr(label, \"START OF TEC MAP\")\t\t== label)\r\n\t\t{\r\n\t\t\ttype = 1;\r\n\t\t\ttime.time = 0;\r\n\t\t\t\r\n\t\t}\r\n\t\telse if (strstr(label, \"END OF TEC MAP\")\t\t== label)\r\n\t\t{\r\n\t\t\t// if (fdebug)\r\n\t\t\t// \tfprintf(fdebug, \"%5ld data and %5ld rms entries for %s\\n\", navi->tecList[time.time].data.size(), navi->tecList[time.time].rms.size(), time.to_string(0).c_str());\r\n\r\n\t\t\ttype = 0;\r\n\t\t}\r\n\t\telse if (strstr(label, \"START OF RMS MAP\")\t\t== label)\r\n\t\t{\r\n\t\t\ttype = 2;\r\n\t\t\ttime.time = 0;\r\n\t\t}\r\n\t\telse if (strstr(label, \"END OF RMS MAP\")\t\t== label)\r\n\t\t{\r\n\t\t\t// if (fdebug)\r\n\t\t\t// \tfprintf(fdebug, \"%5ld data and %5ld rms entries for %s\\n\", navi->tecList[time.time].data.size(), navi->tecList[time.time].rms.size(), time.to_string(0).c_str());\r\n\r\n\t\t\ttype = 0;\r\n\t\t}\r\n\t\telse if (strstr(label, \"EPOCH OF CURRENT MAP\")\t== label)\r\n\t\t{\r\n\t\t\tif (str2time(buff, 0, 36, time))\r\n\t\t\t{\r\n\t\t\t\t// fprintf(fdebug, \"ionex epoch invalid: %-36.36s\\n\", buff);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tauto& epochTec = navi->tecMap[time];\r\n\t\t\t\r\n\t\t\tif (type == 1)\r\n\t\t\t{\r\n\t\t\t\tepochTec.time\t\t= time;\r\n\t\t\t\tepochTec.ndata[0]\t= nitem(lats);\r\n\t\t\t\tepochTec.ndata[1]\t= nitem(lons);\r\n\t\t\t\tepochTec.ndata[2]\t= nitem(hgts);\r\n\t\t\t\tepochTec.rb\t\t\t= rb;\r\n\r\n\t\t\t\tfor (int i = 0; i < 3; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tepochTec.lats[i] = lats[i];\r\n\t\t\t\t\tepochTec.lons[i] = lons[i];\r\n\t\t\t\t\tepochTec.hgts[i] = hgts[i];\r\n\t\t\t\t}\r\n\r\n\t\t\t\tepochTec.tecPointVector.resize(epochTec.ndata[0] * epochTec.ndata[1] * epochTec.ndata[2]);\r\n\t\t\t\t\r\n\t\t\t\tstd::fill(epochTec.tecPointVector.begin(), epochTec.tecPointVector.end(), TECPoint{});\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if\t( strstr(label, \"LAT/LON1/LON2/DLON/H\")\t== label\r\n\t\t\t\t&& time.time\r\n\t\t\t\t&& type)\r\n\t\t{\r\n\t\t\tdouble lon[3];\r\n\t\t\tdouble\tlat\t\t= str2num(buff, 2,  6);\r\n\t\t\t\t\tlon[0]\t= str2num(buff, 8,  6);\r\n\t\t\t\t\tlon[1]\t= str2num(buff, 14, 6);\r\n\t\t\t\t\tlon[2]\t= str2num(buff, 20, 6);\r\n\t\t\tdouble\thgt\t\t= str2num(buff, 26, 6);\r\n\r\n\t\t\tint i = getindex(lat, lats);\r\n\t\t\tint k = getindex(hgt, hgts);\r\n\t\t\tint n = nitem(lon);\r\n\r\n\t\t\tauto& epochTec = navi->tecMap[time];\r\n\t\t\t\r\n\t\t\tfor (int m = 0; m < n; m++)\r\n\t\t\t{\r\n\t\t\t\tif\t(  m % 16 == 0\r\n\t\t\t\t\t&& !std::getline(in, line))\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tbuff = &line[0];\r\n\r\n\t\t\t\tint j = getindex(lon[0] + lon[2] * m, lons);\r\n\r\n\t\t\t\tint index = dataindex(i, j, k, epochTec.ndata);\r\n\t\t\t\tif (index  < 0)\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t\r\n\t\t\t\tdouble x = str2num(buff, m % 16 * 5, 5);\r\n\t\t\t\tif (x == 9999)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tif (type == 1)\t\tepochTec.tecPointVector[index].data\t= x * pow(10, nexp);\r\n\t\t\t\tif (type == 2)\t\tepochTec.tecPointVector[index].rms\t= x * pow(10, nexp);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn 1;\r\n}\r\n\r\n/* read ionex tec grid file ----------------------------------------------------\r\n* read ionex ionospheric tec grid file\r\n* args   : char   *file       I   ionex tec grid file\r\n*                                 (wind-card * is expanded)\r\n*          nav_t  *nav        IO  navigation data\r\n*                                 nav->nt, nav->ntmax and nav->tec are modified\r\n* notes  : see ref [1]\r\n*-----------------------------------------------------------------------------*/\r\nvoid readtec(\r\n\tstring file,\r\n\tnav_t* navi)\r\n{\r\n\tBOOST_LOG_TRIVIAL(debug)\r\n\t<< \"readtec : file=\" << file;\r\n\r\n\tstd::ifstream inputStream(file);\r\n\tif (!inputStream)\r\n\t{\r\n\t\tBOOST_LOG_TRIVIAL(error)\r\n\t\t<< \"ionex file open error \" << file;\r\n\r\n\t\treturn;\r\n\t}\r\n\r\n\t/* read ionex header */\r\n\tdouble nexp = -1;\r\n\tdouble rb\t= 0;\r\n\tdouble lats[3] = {};\r\n\tdouble lons[3] = {};\r\n\tdouble hgts[3] = {};\r\n\tdouble version = readionexh(inputStream, lats, lons, hgts, rb, nexp, navi);\r\n\tif (version <= 0)\r\n\t{\r\n\t\tBOOST_LOG_TRIVIAL(error)\r\n\t\t<< \"ionex file format error \" << file;\r\n\r\n\t\treturn;\r\n\t}\r\n\r\n\t/* read ionex body */\r\n\treadionexb(inputStream, lats, lons, hgts, rb, nexp, navi);\r\n}\r\n\r\n/* interpolate tec grid data -------------------------------------------------*/\r\nint interptec(\r\n\tconst tec_t& tec,\r\n\tint k, \r\n\tconst double* posp,\r\n\tdouble& value,\r\n\tdouble& rms)\r\n{\r\n\t// if (fdebug)\r\n\t// \tfprintf(fdebug, \"%s: k=%d posp=%.2f %.2f\\n\",__FUNCTION__, k, posp[0]*R2D, posp[1]*R2D);\r\n\r\n\tvalue\t= 0;\r\n\trms\t\t= 0;\r\n\r\n\tif\t( tec.lats[2] == 0\r\n\t\t||tec.lons[2] == 0)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tdouble dlat = posp[0] * R2D - tec.lats[0];\r\n\tdouble dlon = posp[1] * R2D - tec.lons[0];\r\n\r\n\tif (tec.lons[2] > 0)\tdlon -= floor( dlon / 360) * 360; /*  0<=dlon<360 */\r\n\telse\t\t\t\t\tdlon += floor(-dlon / 360) * 360; /* -360<dlon<=0 */\r\n\r\n\tdouble a = dlat / tec.lats[2];\r\n\tdouble b = dlon / tec.lons[2];\r\n\tint i = (int) floor(a); \t\t\ta -= i;\r\n\tint j = (int) floor(b); \t\t\tb -= j;\r\n\r\n\t/* get gridded tec data */\r\n\tdouble d[4] = {};\r\n\tdouble r[4] = {};\r\n\tfor (int n = 0; n < 4; n++)\r\n\t{\r\n\t\tint index = dataindex(i + (n % 2), j + (n < 2 ? 0 : 1), k, tec.ndata);\r\n\t\tif (index < 0)\r\n\t\t\tcontinue;\r\n\r\n\t\tauto& tecPoint = tec.tecPointVector[index];\r\n\t\t\r\n\t\td[n] = tecPoint.data;\r\n\t\tr[n] = tecPoint.rms;\r\n\t}\r\n\r\n\tif\t(  d[0] > 0\r\n\t\t&& d[1] > 0\r\n\t\t&& d[2] > 0\r\n\t\t&& d[3] > 0)\r\n\t{\r\n\t\t/* bilinear interpolation (inside of grid) */\r\n\t\tvalue\t= (1 - a) * (1 - b) * d[0] \t\t+ a * (1 - b) * d[1] \t\t+ (1 - a) * b * d[2] \t\t+ a * b * d[3];\r\n\t\trms\t\t= (1 - a) * (1 - b) * r[0] \t\t+ a * (1 - b) * r[1] \t\t+ (1 - a) * b * r[2] \t\t+ a * b * r[3];\r\n\r\n\t\t// if (fdebug)\r\n\t\t// \tfprintf(fdebug, \"  gridpoints: %8.2f %8.2f %8.2f %8.2f -> %9.3f\\n\", d[0], d[1], d[2], d[3], value);\r\n\t}\r\n\t/* nearest-neighbour extrapolation (outside of grid) */\r\n\telse if (a <=\t0.5 && b <= 0.5 && d[0] > 0) \t{\tvalue = d[0];\t\trms = r[0];\t\t}\r\n\telse if (a >\t0.5 && b <= 0.5 && d[1] > 0) \t{\tvalue = d[1];\t\trms = r[1];\t\t}\r\n\telse if (a <=\t0.5 && b >\t0.5 && d[2] > 0) \t{\tvalue = d[2];\t\trms = r[2];\t\t}\r\n\telse if (a >\t0.5 && b >\t0.5 && d[3] > 0) \t{\tvalue = d[3];\t\trms = r[3];\t\t}\r\n\telse\r\n\t{\r\n\t\ti = 0;\r\n\r\n\t\tfor (int n = 0; n < 4; n++)\r\n\t\tif (d[n] > 0)\r\n\t\t{\r\n\t\t\ti++;\r\n\t\t\tvalue\t+= d[n];\r\n\t\t\trms\t\t+= r[n];\r\n\t\t}\r\n\r\n\t\tif (i == 0)\r\n\t\t\treturn 0;\r\n\r\n\t\tvalue\t/= i;\r\n\t\trms\t\t/= i;\r\n\t}\r\n\r\n\treturn 1;\r\n}\r\n\r\n/* ionosphere delay by tec grid data -----------------------------------------*/\r\nint iondelay(\r\n\tGTime time, \r\n\tconst tec_t& tec,\r\n\tconst double* pos, \r\n\tconst double* azel,\r\n\tint opt,\r\n\tdouble& delay,\r\n\tdouble& var)\r\n{\r\n\t// if (fdebug)\r\n\t// \tfprintf(fdebug, \"%s: time=%s pos=%.1f %.1f azel=%.1f %.1f\\n\", __FUNCTION__, time.to_string(0).c_str(), pos[0]*R2D, pos[1]*R2D, azel[0]*R2D, azel[1]*R2D);\r\n\r\n\tdelay\t= 0;\r\n\tvar\t\t= 0;\r\n\r\n\tfor (int i = 0; i < tec.ndata[2]; i++)\r\n\t{\r\n\t\tdouble hion = tec.hgts[0] + tec.hgts[2] * i;\r\n\r\n\t\t/* ionospheric pierce point position */\r\n\t\tdouble posp[3] = {};\r\n\t\tdouble fs = ionppp(pos, azel, tec.rb, hion, posp);\r\n\r\n\t\tif (opt & 2)\r\n\t\t{\r\n\t\t\t/* modified single layer mapping function (M-SLM) ref [2] */\r\n\t\t\tdouble rp = tec.rb / (tec.rb + hion) * sin(0.9782 * (PI / 2 - azel[1]));\r\n\t\t\tfs = 1 / sqrt(1 - rp * rp);\r\n\t\t}\r\n\r\n\t\tif (opt & 1)\r\n\t\t{\r\n\t\t\t/* earth rotation correction (sun-fixed coordinate) */\r\n\t\t\tposp[1] += 2 * PI * (time - tec.time) / 86400;\r\n\t\t}\r\n\r\n\t\t/* interpolate tec grid data */\r\n\t\tdouble rms;\r\n\t\tdouble vtec;\r\n\t\tif (!interptec(tec, i, posp, vtec, rms))\r\n\t\t\treturn 0;\r\n\r\n\t\tconst double fact = 40.30E16 / FREQ1 / FREQ1; /* tecu->L1 iono (m) */\r\n\t\tdelay\t+= fact * fs * vtec;\r\n\t\tvar\t\t+= SQR(fact * fs * rms);\r\n\t}\r\n\r\n\t// if (fdebug)\r\n\t// \tfprintf(fdebug, \"%s: delay=%7.2f std=%6.2f\\n\",__FUNCTION__, delay, sqrt(var));\r\n\r\n\treturn 1;\r\n}\r\n\r\n/* ionosphere model by tec grid data -------------------------------------------\r\n* compute ionospheric delay by tec grid data\r\n* args   : gtime_t time     I   time (gpst)\r\n*          nav_t  *nav      I   navigation data\r\n*          double *pos      I   receiver position {lat,lon,h} (rad,m)\r\n*          double *azel     I   azimuth/elevation angle {az,el} (rad)\r\n*          int    opt       I   model option\r\n*                                bit0: 0:earth-fixed,1:sun-fixed\r\n*                                bit1: 0:single-layer,1:modified single-layer\r\n*          double *delay    O   ionospheric delay (L1) (m)\r\n*          double *var      O   ionospheric dealy (L1) variance (m^2)\r\n* return : status (1:ok,0:error)\r\n* notes  : before calling the function, read tec grid data by calling readtec()\r\n*          return ok with delay=0 and var=VAR_NOTEC if el<MIN_EL or h<MIN_HGT\r\n*-----------------------------------------------------------------------------*/\r\nint iontec(\r\n\tGTime time,\r\n\tconst nav_t*\tnav,\r\n\tconst double*\tpos,\r\n\tconst double*\tazel,\r\n\tint\t\t\t\topt,\r\n\tdouble&\t\t\tdelay,\r\n\tdouble&\t\t\tvar)\r\n{\r\n\t// if (fdebug)\r\n\t// \tfprintf(fdebug, \"iontec  : time=%s pos=%.1f %.1f azel=%.1f %.1f nt=%ld\\n\", time.to_string(0).c_str(), pos[0]*R2D, pos[1]*R2D, azel[0]*R2D, azel[1]*R2D, nav->tecList.size());\r\n\r\n\tdelay\t= 0;\r\n\tvar\t\t= VAR_NOTEC;\r\n\r\n\tif\t(  azel[1]\t< MIN_EL\r\n\t\t|| pos[2]\t< MIN_HGT)\r\n\t{\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tauto it = nav->tecMap.lower_bound(time);\r\n\tif (it == nav->tecMap.end())\r\n\t{\r\n\t\t// if (fdebug)\r\n\t\t// \tfprintf(fdebug, \"%s: tec grid out of period\\n\", time.to_string(0).c_str());\r\n\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tint stat[2] = {};\r\n\tdouble dels[2];\r\n\tdouble vars[2];\r\n\t\r\n\tauto& [t0, tec0] = *it;\r\n\tstat[0] = iondelay(time, tec0, pos, azel, opt, dels[0], vars[0]);\r\n\t\t\r\n\tif (it == nav->tecMap.begin())\r\n\t{\r\n\t\tdelay\t= dels[0];\r\n\t\tvar\t\t= vars[0];\r\n\t\treturn stat[0];\r\n\t}\r\n\t\r\n\t//go forward and get the next timestep if available\r\n\tit--;\r\n\t\r\n\tauto& [t1, tec1] = *it;\r\n\tstat[1] = iondelay(time, tec1, pos, azel, opt, dels[1], vars[1]);\r\n\r\n\t\r\n\r\n\tif\t(  stat[0]\r\n\t\t&& stat[1])\r\n\t{\r\n\t\t/* linear interpolation by time */\r\n\t\tdouble tt\t= (tec1.time\t- tec0.time);\r\n\t\tdouble a\t= (time\t\t\t- tec0.time) / tt;\r\n\t\t\r\n\t\tdelay\t= dels[0] * (1 - a) + dels[1] * a;\r\n\t\tvar\t\t= vars[0] * (1 - a) + vars[1] * a;\r\n\t}\r\n\telse if (stat[0])   /* nearest-neighbour extrapolation by time */\r\n\t{\r\n\t\tdelay\t= dels[0];\r\n\t\tvar\t\t= vars[0];\r\n\t}\r\n\telse if (stat[1])\r\n\t{\r\n\t\tdelay\t= dels[1];\r\n\t\tvar\t\t= vars[1];\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// if (fdebug)\r\n\t\t// \tfprintf(fdebug, \"%s: tec grid out of area pos=%6.2f %7.2f azel=%6.1f %5.1f\\n\",  time.to_string(0).c_str(), pos[0]*R2D, pos[1]*R2D, azel[0]*R2D, azel[1]*R2D);\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t// if (fdebug)\r\n\t// \tfprintf(fdebug, \"iontec  : delay=%5.2f std=%5.2f\\n\", delay, sqrt(var));\r\n\r\n\treturn 1;\r\n}\r\n", "meta": {"hexsha": "089fcc46ffa22d61b55780c04d46306aa8f885d9", "size": 17810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/rtklib/ionex.cpp", "max_stars_repo_name": "HiTMonitor/ginan", "max_stars_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/rtklib/ionex.cpp", "max_issues_repo_name": "HiTMonitor/ginan", "max_issues_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/rtklib/ionex.cpp", "max_forks_repo_name": "HiTMonitor/ginan", "max_forks_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3638850889, "max_line_length": 179, "alphanum_fraction": 0.5016282987, "num_tokens": 6280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771176, "lm_q2_score": 0.053403334696110465, "lm_q1q2_score": 0.02524287470067859}}
{"text": "\n/** \\file utils.hpp\n * collection of general utilities\n */\n\n#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cassert>\n#include <bitset>\n#include <boost/unordered_set.hpp>\n#include <boost/unordered_map.hpp>\n\n#define default_buckets boost::unordered::detail::default_bucket_count\n\n\n#ifndef M_PI\n#define M_PI 3.14159265359f\n#endif\n#define byte unsigned char\n#define SIZE_T_BITS (unsigned)(8*sizeof(size_t))\n// avoid the clutter for map-emplaces where both constructors take just one argument\n#define DEEP_EMPLACE(x,y) emplace(std::piecewise_construct, std::make_tuple(x), std::make_tuple(y))\n#define DEEP_EMPLACE_TWO(x,y,z) emplace(std::piecewise_construct, std::make_tuple(x), std::make_tuple(y, z))\n// avoid the clutter for map-emplaces where the target is default constructed\n#define DEFAULT_EMPLACE(x) emplace(std::piecewise_construct, std::make_tuple(x), std::make_tuple())\n// merge two lists\n#define SPLICE_LISTS(x,y) x.splice(x.end(), y)\n\n#ifdef LONG_WIDTH\n  #define MAX_TW (byte)LONG_WIDTH\n#else\n  #define MAX_TW (byte)64\n#endif\n\n// on debuglevel 3 all DEBUG1, DEBUG2, and DEBUG3 statements are evaluated\n#ifndef NDEBUG\n  #ifndef debuglevel\n    #define debuglevel 5\n  #endif\n#else\n  #define debuglevel 0\n#endif\n\n#if debuglevel > 0\n#define DEBUG1(x) x\n#else\n#define DEBUG1(x)\n#endif\n\n#if debuglevel > 1\n#define DEBUG2(x) x\n#else\n#define DEBUG2(x)\n#endif\n\n#if debuglevel > 2\n#define DEBUG3(x) x\n#else\n#define DEBUG3(x)\n#endif\n\n#if debuglevel > 3\n#define DEBUG4(x) x\n#else\n#define DEBUG4(x)\n#endif\n\n#if debuglevel > 4\n#define DEBUG5(x) x\n#else\n#define DEBUG5(x)\n#endif\n\n#if debuglevel > 5\n#define DEBUG6(x) x\n#else\n#define DEBUG6(x)\n#endif\n\n#ifdef STATISTICS\n#define STAT(x) x\n#else\n#define STAT(x) \n#endif\n\n\n// inverse error function (approximative)\n// thx to\n// https://stackoverflow.com/questions/27229371/inverse-error-function-in-c\n// and\n// A handy approximation for the error function and its inverse\" by Sergei Winitzki.\nfloat erf_inv_apx(const float& p)\n{\n  const float sgn = (p < 0) ? -1.0f : 1.0f;\n\n  // lnx = log(1 - x*x)\n  const float lnx = logf((1 - p)*(1 + p));\n\n  const float tt1 = 2/(M_PI*0.147) + 0.5f * lnx;\n  const float tt2 = 1/(0.147) * lnx;\n\n  return sgn*sqrtf(-tt1 + sqrtf(tt1*tt1 - tt2));\n}\n\n\n//! return whether a pair is pareto-smaller than another pair\ntemplate <typename ElementA, typename ElementB>\nbool pareto_le(const std::pair<ElementA,ElementB>& p1, const std::pair<ElementA,ElementB>& p2)\n{\n  return (p1.first <= p2.first) && (p1.second <= p2.second);\n}\n\n//! output list of things\ntemplate<typename Element>\nstd::ostream& operator<<(std::ostream& os, const std::list<Element>& lst)\n{\n  for(auto i : lst) os << i << \"  \";\n  return os;\n}\n//! output map of things\ntemplate<typename Element1, typename Element2>\nstd::ostream& operator<<(std::ostream& os, const boost::unordered_map<Element1, Element2>& map)\n{\n  for(auto i : map) os << i << \"  \";\n  return os;\n}\n\n//! a more readable containment check\n/** \\param s any container object that implements find() and cend()\n * \\param el some element to check containment of in s\n */\ntemplate <class Set, typename Element>\ninline bool contains(const Set& s, const Element& el)\n{\n  return s.find(el) != s.cend();\n}\n\n//! a hash computation for an unordered set, XORing its members\ntemplate<typename T>\nsize_t hash_value(const boost::unordered_set<T>& S)\n{\n  size_t result = 0;\n  for(const auto& i : S)\n    result = (result << 1) ^ hash_value(i);\n  return result;\n}\n\n//! set intersection for unordered sets\n/** removes all elements from S1 that are not in S2 */\ntemplate<typename T>\nvoid operator&=(boost::unordered_set<T>& S1, const boost::unordered_set<T>& S2)\n{\n  for(typename boost::unordered_set<T>::iterator i = S1.begin(); i != S1.end();)\n    if(!contains(S2, *i)) i = S1.erase(i); else ++i;\n}\n\n//! setminus for unordered sets\n/** removes all elements from S1 that are in S2 */\ntemplate<typename T>\nvoid operator-=(boost::unordered_set<T>& S1, const boost::unordered_set<T>& S2)\n{\n  for(typename boost::unordered_set<T>::iterator i = S1.begin(); i != S1.end();)\n    if(contains(S2, *i)) i = S1.erase(i); else ++i;\n}\n\n//! symmetric set difference for unordered sets\n/** removes all elements of S1 that are not in S2 and emplaces copies of all elements of S2 that are not in S1 */\ntemplate<typename T>\nvoid operator^=(boost::unordered_set<T>& S1, const boost::unordered_set<T>& S2)\n{\n  for(typename boost::unordered_set<T>::iterator i = S1.begin(); i != S1.end();)\n    if(contains(S2, *i)) i = S1.erase(i); else ++i;\n  for(typename boost::unordered_set<T>::iterator i = S2.begin(); i != S2.end(); ++i) S1.emplace(*i);\n}\n\n//! testing whether a file exists by trying to open it\ninline bool file_exists(const std::string& filename) \n{\n  return std::ifstream(filename.c_str()).good();\n}\n\n//! reverse a pair of things, that is, turn (x,y) into (y,x)\ntemplate<typename A, typename B>\ninline std::pair<B,A> reverse(const std::pair<A,B>& p)\n{\n  return {p.second, p.first};\n}\n\n//! add two pairs of things\ntemplate <typename A, typename B>\nstd::pair<A,B> operator+(const std::pair<A,B>& l, const std::pair<A,B>& r)\n{\n\treturn {l.first + r.first, l.second + r.second};\n}\n\ntemplate <typename A, typename B>\nstd::ostream& operator<<(std::ostream& os, const std::pair<A,B>& p)\n{\n\treturn os << \"(\"<<p.first<<\", \"<<p.second<<\")\";\n}\n\n\n\n\n#endif\n", "meta": {"hexsha": "91626f0dfebc6a1e46909bf645cb9f5b4b32b87e", "size": 5360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/utils.hpp", "max_stars_repo_name": "PACE-challenge/phylo_converter", "max_stars_repo_head_hexsha": "47b69017599f473ed584458cffef4bdf2ad5879e", "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": "utils/utils.hpp", "max_issues_repo_name": "PACE-challenge/phylo_converter", "max_issues_repo_head_hexsha": "47b69017599f473ed584458cffef4bdf2ad5879e", "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": "utils/utils.hpp", "max_forks_repo_name": "PACE-challenge/phylo_converter", "max_forks_repo_head_hexsha": "47b69017599f473ed584458cffef4bdf2ad5879e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5238095238, "max_line_length": 113, "alphanum_fraction": 0.6938432836, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.05340333469611046, "lm_q1q2_score": 0.025242873907282075}}
{"text": "#ifndef STAN_MODEL_INDEXING_RVALUE_HPP\n#define STAN_MODEL_INDEXING_RVALUE_HPP\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <stan/model/indexing/index.hpp>\n#include <stan/model/indexing/index_list.hpp>\n#include <stan/model/indexing/rvalue_at.hpp>\n#include <stan/model/indexing/rvalue_index_size.hpp>\n#include <stan/model/indexing/rvalue_return.hpp>\n#include <vector>\n\nnamespace stan {\n\nnamespace model {\n\n// all indexing from 1\n\n/**\n * Return the result of indexing a specified value with\n * a nil index list, which just returns the value.\n *\n * Types:  T[] : T\n *\n * @tparam T Scalar type.\n * @param[in] c Value to index.\n * @return Input value.\n */\ntemplate <typename T>\ninline T rvalue(const T& c, const nil_index_list& /*idx*/,\n                const char* /*name*/ = \"\", int /*depth*/ = 0) {\n  return c;\n}\n\n/**\n * Return the result of indexing the specified Eigen vector with a\n * sequence containing one single index, returning a scalar.\n *\n * Types:  vec[single] : scal\n *\n * @tparam T Scalar type.\n * @param[in] v Vector being indexed.\n * @param[in] idx One single index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing vector.\n */\ntemplate <typename T>\ninline T rvalue(const Eigen::Matrix<T, Eigen::Dynamic, 1>& v,\n                const cons_index_list<index_uni, nil_index_list>& idx,\n                const char* name = \"ANON\", int depth = 0) {\n  int ones_idx = idx.head_.n_;\n  math::check_range(\"vector[single] indexing\", name, v.size(), ones_idx);\n  return v.coeff(ones_idx - 1);\n}\n\n/**\n * Return the result of indexing the specified Eigen row vector\n * with a sequence containing one single index, returning a\n * scalar.\n *\n * Types:  rowvec[single] : scal\n *\n * @tparam T Scalar type.\n * @param[in] rv Row vector being indexed.\n * @param[in] idx One single index in list.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing row vector.\n */\ntemplate <typename T>\ninline T rvalue(const Eigen::Matrix<T, 1, Eigen::Dynamic>& rv,\n                const cons_index_list<index_uni, nil_index_list>& idx,\n                const char* name = \"ANON\", int depth = 0) {\n  int n = idx.head_.n_;\n  math::check_range(\"row_vector[single] indexing\", name, rv.size(), n);\n  return rv.coeff(n - 1);\n}\n\n/**\n * Return the result of indexing the specified Eigen vector with a\n * sequence containing one multiple index, returning a vector.\n *\n * Types: vec[multiple] : vec\n *\n * @tparam T Scalar type.\n * @tparam I Multi-index type.\n * @param[in] v Eigen vector.\n * @param[in] idx Index consisting of one multi-index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing vector.\n */\ntemplate <typename T, typename I>\ninline typename boost::disable_if<boost::is_same<I, index_uni>,\n                                  Eigen::Matrix<T, Eigen::Dynamic, 1> >::type\nrvalue(const Eigen::Matrix<T, Eigen::Dynamic, 1>& v,\n       const cons_index_list<I, nil_index_list>& idx, const char* name = \"ANON\",\n       int depth = 0) {\n  int size = rvalue_index_size(idx.head_, v.size());\n  Eigen::Matrix<T, Eigen::Dynamic, 1> a(size);\n  for (int i = 0; i < size; ++i) {\n    int n = rvalue_at(i, idx.head_);\n    math::check_range(\"vector[multi] indexing\", name, v.size(), n);\n    a(i) = v.coeff(n - 1);\n  }\n  return a;\n}\n\n/**\n * Return the result of indexing the specified Eigen row vector\n * with a sequence containing one multiple index, returning a row\n * vector.\n *\n * Types:  row_vec[multiple] : rowvec\n *\n * @tparam T Scalar type.\n * @tparam I Multi-index type.\n * @param[in] rv Eigen row vector.\n * @param[in] idx Index consisting of one multi-index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing vector.\n */\ntemplate <typename T, typename I>\ninline typename boost::disable_if<boost::is_same<I, index_uni>,\n                                  Eigen::Matrix<T, 1, Eigen::Dynamic> >::type\nrvalue(const Eigen::Matrix<T, 1, Eigen::Dynamic>& rv,\n       const cons_index_list<I, nil_index_list>& idx, const char* name = \"ANON\",\n       int depth = 0) {\n  int size = rvalue_index_size(idx.head_, rv.size());\n  Eigen::Matrix<T, 1, Eigen::Dynamic> a(size);\n  for (int i = 0; i < size; ++i) {\n    int n = rvalue_at(i, idx.head_);\n    math::check_range(\"row_vector[multi] indexing\", name, rv.size(), n);\n    a(i) = rv.coeff(n - 1);\n  }\n  return a;\n}\n\n/**\n * Return the result of indexing the specified Eigen matrix with a\n * sequence consisting of one single index, returning a row vector.\n *\n * Types:  mat[single] : rowvec\n *\n * @tparam T Scalar type.\n * @param[in] a Eigen matrix.\n * @param[in] idx Index consisting of one uni-index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing matrix.\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 1, Eigen::Dynamic> rvalue(\n    const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& a,\n    const cons_index_list<index_uni, nil_index_list>& idx,\n    const char* name = \"ANON\", int depth = 0) {\n  int n = idx.head_.n_;\n  math::check_range(\"matrix[uni] indexing\", name, a.rows(), n);\n  return a.row(n - 1);\n}\n\n/**\n * Return the result of indexing the specified Eigen matrix with a\n * sequence consisting of a one multiple index, returning a matrix.\n *\n * Types:  mat[multiple] : mat\n *\n * @tparam T Scalar type.\n * @tparam I Type of multiple index.\n * @param[in] a Matrix to index.\n * @param[in] idx Index consisting of single multiple index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing matrix.\n */\ntemplate <typename T, typename I>\ninline typename boost::disable_if<\n    boost::is_same<I, index_uni>,\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> >::type\nrvalue(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& a,\n       const cons_index_list<I, nil_index_list>& idx, const char* name = \"ANON\",\n       int depth = 0) {\n  int n_rows = rvalue_index_size(idx.head_, a.rows());\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> b(n_rows, a.cols());\n  for (int i = 0; i < n_rows; ++i) {\n    int n = rvalue_at(i, idx.head_);\n    math::check_range(\"matrix[multi] indexing\", name, a.rows(), n);\n    b.row(i) = a.row(n - 1);\n  }\n  return b;\n}\n\n/**\n * Return the result of indexing the specified Eigen matrix with a\n * sequence consisting of two single indexes, returning a scalar.\n *\n * Types:  mat[single,single] : scalar\n *\n * @tparam T Scalar type.\n * @param[in] a Matrix to index.\n * @param[in] idx Pair of single indexes.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing matrix.\n */\ntemplate <typename T>\ninline T rvalue(\n    const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& a,\n    const cons_index_list<index_uni,\n                          cons_index_list<index_uni, nil_index_list> >& idx,\n    const char* name = \"ANON\", int depth = 0) {\n  int m = idx.head_.n_;\n  int n = idx.tail_.head_.n_;\n  math::check_range(\"matrix[uni,uni] indexing, row\", name, a.rows(), m);\n  math::check_range(\"matrix[uni,uni] indexing, col\", name, a.cols(), n);\n  return a.coeff(m - 1, n - 1);\n}\n\n/**\n * Return the result of indexing the specified Eigen matrix with a\n * sequence consisting of a single index and multiple index,\n * returning a row vector.\n *\n * Types:  mat[single,multiple] : row vector\n *\n * @tparam T Scalar type.\n * @tparam I Type of multiple index.\n * @param[in] a Matrix to index.\n * @param[in] idx Pair of single index and multiple index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing matrix.\n */\ntemplate <typename T, typename I>\ninline typename boost::disable_if<boost::is_same<I, index_uni>,\n                                  Eigen::Matrix<T, 1, Eigen::Dynamic> >::type\nrvalue(\n    const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& a,\n    const cons_index_list<index_uni, cons_index_list<I, nil_index_list> >& idx,\n    const char* name = \"ANON\", int depth = 0) {\n  int m = idx.head_.n_;\n  math::check_range(\"matrix[uni,multi] indexing, row\", name, a.rows(), m);\n  Eigen::Matrix<T, 1, Eigen::Dynamic> r = a.row(m - 1);\n  return rvalue(r, idx.tail_);\n}\n\n/**\n * Return the result of indexing the specified Eigen matrix with a\n * sequence consisting of a multiple index and a single index,\n * returning a vector.\n *\n * Types:  mat[multiple,single] : vector\n *\n * @tparam T Scalar type.\n * @tparam I Type of multiple index.\n * @param[in] a Matrix to index.\n * @param[in] idx Pair multiple index and single index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing matrix.\n */\ntemplate <typename T, typename I>\ninline typename boost::disable_if<boost::is_same<I, index_uni>,\n                                  Eigen::Matrix<T, Eigen::Dynamic, 1> >::type\nrvalue(\n    const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& a,\n    const cons_index_list<I, cons_index_list<index_uni, nil_index_list> >& idx,\n    const char* name = \"ANON\", int depth = 0) {\n  int rows = rvalue_index_size(idx.head_, a.rows());\n  Eigen::Matrix<T, Eigen::Dynamic, 1> c(rows);\n  for (int i = 0; i < rows; ++i) {\n    int m = rvalue_at(i, idx.head_);\n    int n = idx.tail_.head_.n_;\n    math::check_range(\"matrix[multi,uni] index row\", name, a.rows(), m);\n    math::check_range(\"matrix[multi,uni] index col\", name, a.cols(), n);\n    c(i) = a.coeff(m - 1, n - 1);\n  }\n  return c;\n}\n\n/**\n * Return the result of indexing the specified Eigen matrix with a\n * sequence consisting of a pair o multiple indexes, returning a\n * a matrix.\n *\n * Types:  mat[multiple,multiple] : mat\n *\n * @tparam T Scalar type.\n * @tparam I Type of multiple index.\n * @param[in] a Matrix to index.\n * @param[in] idx Pair of multiple indexes.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing matrix.\n */\ntemplate <typename T, typename I1, typename I2>\ninline typename boost::disable_if_c<\n    boost::is_same<I1, index_uni>::value\n        || boost::is_same<I2, index_uni>::value,\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> >::type\nrvalue(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& a,\n       const cons_index_list<I1, cons_index_list<I2, nil_index_list> >& idx,\n       const char* name = \"ANON\", int depth = 0) {\n  int rows = rvalue_index_size(idx.head_, a.rows());\n  int cols = rvalue_index_size(idx.tail_.head_, a.cols());\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> c(rows, cols);\n  for (int j = 0; j < cols; ++j) {\n    for (int i = 0; i < rows; ++i) {\n      int m = rvalue_at(i, idx.head_);\n      int n = rvalue_at(j, idx.tail_.head_);\n      math::check_range(\"matrix[multi,multi] row index\", name, a.rows(), m);\n      math::check_range(\"matrix[multi,multi] col index\", name, a.cols(), n);\n      c(i, j) = a.coeff(m - 1, n - 1);\n    }\n  }\n  return c;\n}\n\n/**\n * Return the result of indexing the specified array with\n * a list of indexes beginning with a single index;  the result is\n * determined recursively.  Note that arrays are represented as\n * standard library vectors.\n *\n * Types:  std::vector<T>[single | L] : T[L]\n *\n * @tparam T Type of list elements.\n * @tparam L Index list type for indexes after first index.\n * @param[in] c Container of list elements.\n * @param[in] idx Index list beginning with single index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing array.\n */\ntemplate <typename T, typename L>\ninline\n    typename rvalue_return<std::vector<T>, cons_index_list<index_uni, L> >::type\n    rvalue(const std::vector<T>& c, const cons_index_list<index_uni, L>& idx,\n           const char* name = \"ANON\", int depth = 0) {\n  int n = idx.head_.n_;\n  math::check_range(\"array[uni,...] index\", name, c.size(), n);\n  return rvalue(c[n - 1], idx.tail_, name, depth + 1);\n}\n\n/**\n * Return the result of indexing the specified array with\n * a list of indexes beginning with a multiple index;  the result is\n * determined recursively.  Note that arrays are represented as\n * standard library vectors.\n *\n * Types:  std::vector<T>[multiple | L] : std::vector<T[L]>\n *\n * @tparam T Type of list elements.\n * @tparam L Index list type for indexes after first index.\n * @param[in] c Container of list elements.\n * @param[in] idx Index list beginning with multiple index.\n * @param[in] name String form of expression being evaluated.\n * @param[in] depth Depth of indexing dimension.\n * @return Result of indexing array.\n */\ntemplate <typename T, typename I, typename L>\ninline typename rvalue_return<std::vector<T>, cons_index_list<I, L> >::type\nrvalue(const std::vector<T>& c, const cons_index_list<I, L>& idx,\n       const char* name = \"ANON\", int depth = 0) {\n  typename rvalue_return<std::vector<T>, cons_index_list<I, L> >::type result;\n  for (int i = 0; i < rvalue_index_size(idx.head_, c.size()); ++i) {\n    int n = rvalue_at(i, idx.head_);\n    math::check_range(\"array[multi,...] index\", name, c.size(), n);\n    result.push_back(rvalue(c[n - 1], idx.tail_, name, depth + 1));\n  }\n  return result;\n}\n\n}  // namespace model\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "6d2c833bf2fdd12ec97da46d61bcbd602df27e97", "size": 13664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/model/indexing/rvalue.hpp", "max_stars_repo_name": "Dr-G/stan", "max_stars_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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/model/indexing/rvalue.hpp", "max_issues_repo_name": "Dr-G/stan", "max_issues_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/model/indexing/rvalue.hpp", "max_forks_repo_name": "Dr-G/stan", "max_forks_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "max_forks_repo_licenses": ["BSD-3-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.9578947368, "max_line_length": 80, "alphanum_fraction": 0.6695696721, "num_tokens": 3644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.053403326975043915, "lm_q1q2_score": 0.0252428702576615}}
{"text": "#include <rbdl/rbdl.h>\n\n#include \"urdfreader.h\"\n\n#include <assert.h>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <stack>\n\n#ifdef RBDL_USE_ROS_URDF_LIBRARY\n  #include <urdf_model/model.h>\n  #include <urdf_parser/urdf_parser.h>\n  #include <boost/shared_ptr.hpp>\n\n  typedef urdf::LinkSharedPtr LinkPtr;\n  typedef const urdf::LinkConstSharedPtr ConstLinkPtr;\n  typedef urdf::JointSharedPtr JointPtr;\n  typedef urdf::ModelInterfaceSharedPtr ModelPtr;\n\n#else\n  #include <urdf/urdfdom_headers/urdf_model/include/urdf_model/model.h>\n  #include <urdf/urdfdom/urdf_parser/include/urdf_parser/urdf_parser.h>\n\n  typedef my_shared_ptr<urdf::Link> LinkPtr;\n  typedef const my_shared_ptr<const urdf::Link> ConstLinkPtr;\n  typedef my_shared_ptr<urdf::Joint> JointPtr;\n  typedef my_shared_ptr<urdf::ModelInterface> ModelPtr;\n\n#endif\n\nusing namespace std;\n\nnamespace RigidBodyDynamics\n{\n\nnamespace Addons\n{\n\nusing namespace Math;\n\ntypedef vector<LinkPtr> URDFLinkVector;\ntypedef vector<JointPtr> URDFJointVector;\ntypedef map<string, LinkPtr> URDFLinkMap;\ntypedef map<string, JointPtr> URDFJointMap;\n\nbool construct_model(Model *rbdl_model, ModelPtr urdf_model, bool floating_base,\n                     bool verbose)\n{\n  LinkPtr urdf_root_link;\n\n  URDFLinkMap link_map;\n  link_map = urdf_model->links_;\n\n  URDFJointMap joint_map;\n  joint_map = urdf_model->joints_;\n\n  vector<string> joint_names;\n\n  // Holds the links that we are processing in our depth first traversal\n  // with the top element being the current link.\n  stack<LinkPtr> link_stack;\n  // Holds the child joint index of the current link\n  stack<int> joint_index_stack;\n\n  // add the bodies in a depth-first order of the model tree\n  link_stack.push(link_map[(urdf_model->getRoot()->name)]);\n\n  // add the root body\n  ConstLinkPtr &root = urdf_model->getRoot();\n  Vector3d root_inertial_rpy;\n  Vector3d root_inertial_position;\n  Matrix3d root_inertial_inertia;\n  double root_inertial_mass;\n\n  if (root->inertial) {\n    root_inertial_mass = root->inertial->mass;\n\n    root_inertial_position.set(\n      root->inertial->origin.position.x,\n      root->inertial->origin.position.y,\n      root->inertial->origin.position.z);\n\n    root_inertial_inertia(0, 0) = root->inertial->ixx;\n    root_inertial_inertia(0, 1) = root->inertial->ixy;\n    root_inertial_inertia(0, 2) = root->inertial->ixz;\n\n    root_inertial_inertia(1, 0) = root->inertial->ixy;\n    root_inertial_inertia(1, 1) = root->inertial->iyy;\n    root_inertial_inertia(1, 2) = root->inertial->iyz;\n\n    root_inertial_inertia(2, 0) = root->inertial->ixz;\n    root_inertial_inertia(2, 1) = root->inertial->iyz;\n    root_inertial_inertia(2, 2) = root->inertial->izz;\n\n    root->inertial->origin.rotation.getRPY(root_inertial_rpy[0],\n                                           root_inertial_rpy[1], \n                                           root_inertial_rpy[2]);\n\n    Body root_link = Body(root_inertial_mass,\n                          root_inertial_position,\n                          root_inertial_inertia);\n\n    Joint root_joint(JointTypeFixed);\n    if (floating_base) {\n      root_joint = JointTypeFloatingBase;\n    }\n\n    SpatialTransform root_joint_frame = SpatialTransform();\n\n    if (verbose) {\n      cout << \"+ Adding Root Body \" << endl;\n      cout << \"  joint frame: \" << root_joint_frame << endl;\n      if (floating_base) {\n        cout << \"  joint type : floating\" << endl;\n      } else {\n        cout << \"  joint type : fixed\" << endl;\n      }\n      cout << \"  body inertia: \" << endl\n           << root_link.mInertia << endl;\n      cout << \"  body mass   : \" << root_link.mMass << endl;\n      cout << \"  body name   : \" << root->name << endl;\n    }\n\n    rbdl_model->AppendBody(root_joint_frame,\n                           root_joint,\n                           root_link,\n                           root->name);\n  }\n\n  // depth first traversal: push the first child onto our joint_index_stack\n  joint_index_stack.push(0);\n\n  while (link_stack.size() > 0) {\n    LinkPtr cur_link = link_stack.top();\n\n    unsigned int joint_idx = joint_index_stack.top();\n\n    // Add any child bodies and increment current joint index if we still\n    // have child joints to process.\n    if (joint_idx < cur_link->child_joints.size()) {\n      JointPtr cur_joint = cur_link->child_joints[joint_idx];\n\n      // increment joint index\n      joint_index_stack.pop();\n      joint_index_stack.push(joint_idx + 1);\n\n      link_stack.push(link_map[cur_joint->child_link_name]);\n      joint_index_stack.push(0);\n\n      if (verbose) {\n        for (unsigned int i = 1; i < joint_index_stack.size() - 1; i++) {\n          cout << \"  \";\n        }\n        cout << \"joint '\" << cur_joint->name << \"' child link '\" <<\n             link_stack.top()->name << \"' type = \" << cur_joint->type << endl;\n      }\n\n      joint_names.push_back(cur_joint->name);\n    } else {\n      link_stack.pop();\n      joint_index_stack.pop();\n    }\n  }\n\n  unsigned int j;\n  for (j = 0; j < joint_names.size(); j++) {\n    JointPtr urdf_joint = joint_map[joint_names[j]];\n    LinkPtr urdf_parent = link_map[urdf_joint->parent_link_name];\n    LinkPtr urdf_child = link_map[urdf_joint->child_link_name];\n\n    // determine where to add the current joint and child body\n    unsigned int rbdl_parent_id = 0;\n\n    if (urdf_parent->name != \"base_link\") {\n      rbdl_parent_id = rbdl_model->GetBodyId(urdf_parent->name.c_str());\n    }\n\n    if (rbdl_parent_id == std::numeric_limits<unsigned int>::max())\n      cerr << \"Error while processing joint '\" << urdf_joint->name\n           << \"': parent link '\" << urdf_parent->name\n           << \"' could not be found.\" << endl;\n\n    // create the joint\n    Joint rbdl_joint;\n    if (urdf_joint->type == urdf::Joint::REVOLUTE ||\n        urdf_joint->type == urdf::Joint::CONTINUOUS) {\n      rbdl_joint = Joint(SpatialVector(urdf_joint->axis.x, urdf_joint->axis.y,\n                                       urdf_joint->axis.z, 0., 0., 0.));\n    } else if (urdf_joint->type == urdf::Joint::PRISMATIC) {\n      rbdl_joint = Joint(SpatialVector(0., 0., 0., urdf_joint->axis.x,\n                                       urdf_joint->axis.y, urdf_joint->axis.z));\n    } else if (urdf_joint->type == urdf::Joint::FIXED) {\n      rbdl_joint = Joint(JointTypeFixed);\n    } else if (urdf_joint->type == urdf::Joint::FLOATING) {\n      // todo: what order of DoF should be used?\n      rbdl_joint = Joint(\n                     SpatialVector(0., 0., 0., 1., 0., 0.),\n                     SpatialVector(0., 0., 0., 0., 1., 0.),\n                     SpatialVector(0., 0., 0., 0., 0., 1.),\n                     SpatialVector(1., 0., 0., 0., 0., 0.),\n                     SpatialVector(0., 1., 0., 0., 0., 0.),\n                     SpatialVector(0., 0., 1., 0., 0., 0.));\n    } else if (urdf_joint->type == urdf::Joint::PLANAR) {\n      // todo: which two directions should be used that are perpendicular\n      // to the specified axis?\n      cerr << \"Error while processing joint '\" << urdf_joint->name <<\n           \"': planar joints not yet supported!\" << endl;\n      return false;\n    }\n\n    // compute the joint transformation\n    Vector3d joint_rpy;\n    Vector3d joint_translation;\n    urdf_joint->parent_to_joint_origin_transform.rotation.getRPY(joint_rpy[0],\n        joint_rpy[1], joint_rpy[2]);\n    joint_translation.set(\n      urdf_joint->parent_to_joint_origin_transform.position.x,\n      urdf_joint->parent_to_joint_origin_transform.position.y,\n      urdf_joint->parent_to_joint_origin_transform.position.z);\n    SpatialTransform rbdl_joint_frame =\n      Xrot(joint_rpy[0], Vector3d(1., 0., 0.)) * Xrot(joint_rpy[1], Vector3d(0., 1.,\n          0.)) * Xrot(joint_rpy[2], Vector3d(0., 0.,\n                      1.)) * Xtrans(Vector3d(joint_translation));\n\n    // assemble the body\n    Vector3d link_inertial_position;\n    Vector3d link_inertial_rpy;\n    Matrix3d link_inertial_inertia = Matrix3d::Zero();\n    double link_inertial_mass = 0.;\n\n    // but only if we actually have inertial data\n    if (urdf_child->inertial) {\n      link_inertial_mass = urdf_child->inertial->mass;\n\n      link_inertial_position.set(\n        urdf_child->inertial->origin.position.x,\n        urdf_child->inertial->origin.position.y,\n        urdf_child->inertial->origin.position.z);\n      urdf_child->inertial->origin.rotation.getRPY(link_inertial_rpy[0],\n          link_inertial_rpy[1], link_inertial_rpy[2]);\n\n      link_inertial_inertia(0, 0) = urdf_child->inertial->ixx;\n      link_inertial_inertia(0, 1) = urdf_child->inertial->ixy;\n      link_inertial_inertia(0, 2) = urdf_child->inertial->ixz;\n\n      link_inertial_inertia(1, 0) = urdf_child->inertial->ixy;\n      link_inertial_inertia(1, 1) = urdf_child->inertial->iyy;\n      link_inertial_inertia(1, 2) = urdf_child->inertial->iyz;\n\n      link_inertial_inertia(2, 0) = urdf_child->inertial->ixz;\n      link_inertial_inertia(2, 1) = urdf_child->inertial->iyz;\n      link_inertial_inertia(2, 2) = urdf_child->inertial->izz;\n\n      if (link_inertial_rpy != Vector3d(0., 0., 0.)) {\n        cerr << \"Error while processing body '\" << urdf_child->name <<\n             \"': rotation of body frames not yet supported. Please rotate\" <<\n             \"the joint frame instead.\"\n             << endl;\n        return false;\n      }\n    }\n\n    Body rbdl_body = Body(link_inertial_mass, link_inertial_position,\n                          link_inertial_inertia);\n\n    if (verbose) {\n      cout << \"+ Adding Body: \" << urdf_child->name << endl;\n      cout << \"  parent_id  : \" << rbdl_parent_id << endl;\n      cout << \"  joint frame: \" << rbdl_joint_frame << endl;\n      cout << \"  joint dofs : \" << rbdl_joint.mDoFCount << endl;\n      for (unsigned int j = 0; j < rbdl_joint.mDoFCount; j++) {\n        cout << \"    \" << j << \": \" << rbdl_joint.mJointAxes[j].transpose() << endl;\n      }\n      cout << \"  body inertia: \" << endl\n           << rbdl_body.mInertia << endl;\n      cout << \"  body mass   : \" << rbdl_body.mMass << endl;\n      cout << \"  body name   : \" << urdf_child->name << endl;\n    }\n\n    if (urdf_joint->type == urdf::Joint::FLOATING) {\n      Matrix3d zero_matrix = Matrix3d::Zero();\n      Body null_body(0., Vector3d::Zero(3), zero_matrix);\n      Joint joint_txtytz(JointTypeTranslationXYZ);\n      string trans_body_name = urdf_child->name + \"_Translate\";\n      rbdl_model->AddBody(rbdl_parent_id, rbdl_joint_frame, joint_txtytz, null_body,\n                          trans_body_name);\n\n      Joint joint_euler_zyx(JointTypeEulerXYZ);\n      rbdl_model->AppendBody(SpatialTransform(), joint_euler_zyx, rbdl_body,\n                             urdf_child->name);\n    } else {\n      rbdl_model->AddBody(rbdl_parent_id, rbdl_joint_frame, rbdl_joint, rbdl_body,\n                          urdf_child->name);\n    }\n  }\n\n  return true;\n}\n\nRBDL_DLLAPI bool URDFReadFromFile(const char *filename, Model *model,\n                                  bool floating_base, bool verbose)\n{\n  ifstream model_file(filename);\n  if (!model_file) {\n    cerr << \"Error opening file '\" << filename << \"'.\" << endl;\n    abort();\n  }\n\n  // reserve memory for the contents of the file\n  string model_xml_string;\n  model_file.seekg(0, std::ios::end);\n  model_xml_string.reserve(model_file.tellg());\n  model_file.seekg(0, std::ios::beg);\n  model_xml_string.assign((std::istreambuf_iterator<char>(model_file)),\n                          std::istreambuf_iterator<char>());\n\n  model_file.close();\n\n  return URDFReadFromString(model_xml_string.c_str(), model, floating_base,\n                            verbose);\n}\n\nRBDL_DLLAPI bool URDFReadFromString(const char *model_xml_string, Model *model,\n                                    bool floating_base, bool verbose)\n{\n  assert(model);\n\n  ModelPtr urdf_model = urdf::parseURDF(model_xml_string);\n\n  if (!construct_model(model, urdf_model, floating_base, verbose)) {\n    cerr << \"Error constructing model from urdf file.\" << endl;\n    return false;\n  }\n\n  model->gravity.set(0., 0., -9.81);\n\n  return true;\n}\n\n} // namespace Addons\n\n} // namespace RigidBodyDynamics\n\n", "meta": {"hexsha": "3d6be1124ebb5bbcc11c3dccbad2850f5ccca66f", "size": 12000, "ext": "cc", "lang": "C++", "max_stars_repo_path": "addons/urdfreader/urdfreader.cc", "max_stars_repo_name": "yycho0108/rbdl-orb", "max_stars_repo_head_hexsha": "f6d342b3be61c8d3c3197bf042a693ddf5b8a83f", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "addons/urdfreader/urdfreader.cc", "max_issues_repo_name": "yycho0108/rbdl-orb", "max_issues_repo_head_hexsha": "f6d342b3be61c8d3c3197bf042a693ddf5b8a83f", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "addons/urdfreader/urdfreader.cc", "max_forks_repo_name": "yycho0108/rbdl-orb", "max_forks_repo_head_hexsha": "f6d342b3be61c8d3c3197bf042a693ddf5b8a83f", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-03T18:47:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T18:47:58.000Z", "avg_line_length": 34.7826086957, "max_line_length": 84, "alphanum_fraction": 0.6310833333, "num_tokens": 3314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733884, "lm_q2_score": 0.054198724476223134, "lm_q1q2_score": 0.02519707217542946}}
{"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/marketdata/marketdatum.hpp\n    \\brief Market data representation\n    \\ingroup marketdata\n*/\n\n#pragma once\n\n#include <boost/make_shared.hpp>\n#include <ql/currency.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/time/date.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/types.hpp>\n#include <string>\n\nnamespace ore {\nnamespace data {\nusing std::string;\nusing QuantLib::Real;\nusing QuantLib::Size;\nusing QuantLib::Date;\nusing QuantLib::Period;\nusing QuantLib::Quote;\nusing QuantLib::SimpleQuote;\nusing QuantLib::Handle;\nusing QuantLib::DayCounter;\nusing QuantLib::Natural;\nusing QuantLib::Month;\nusing QuantLib::Months;\n\n//! Base market data class\n/*!\n  This class holds a single market point, a SimpleQuote pointer and generic\n  additional information.\n\n  The market point is classified by an instrument type, a quote type and\n  a name string. The name's structure depends on the market point's type\n  with tokens separated by \"/\".\n\n  Specific market data classes are derived from this base class and hold\n  additional specific data that are represented by the market point's name.\n\n  \\ingroup marketdata\n*/\nclass MarketDatum {\npublic:\n    //! Supported market instrument types\n    enum class InstrumentType {\n        ZERO,\n        DISCOUNT,\n        MM,\n        MM_FUTURE,\n        FRA,\n        IMM_FRA,\n        IR_SWAP,\n        BASIS_SWAP,\n        BMA_SWAP,\n        CC_BASIS_SWAP,\n        CC_FIX_FLOAT_SWAP,\n        CDS,\n        CDS_INDEX,\n        FX_SPOT,\n        FX_FWD,\n        HAZARD_RATE,\n        RECOVERY_RATE,\n        SWAPTION,\n        CAPFLOOR,\n        FX_OPTION,\n        ZC_INFLATIONSWAP,\n        ZC_INFLATIONCAPFLOOR,\n        YY_INFLATIONSWAP,\n        YY_INFLATIONCAPFLOOR,\n        SEASONALITY,\n        EQUITY_SPOT,\n        EQUITY_FWD,\n        EQUITY_DIVIDEND,\n        EQUITY_OPTION,\n        BOND,\n        BOND_OPTION,\n        INDEX_CDS_OPTION,\n        COMMODITY_SPOT,\n        COMMODITY_FWD,\n        CORRELATION,\n        COMMODITY_OPTION,\n        CPR\n    };\n\n    //! Supported market quote types\n    enum class QuoteType {\n        BASIS_SPREAD,\n        CREDIT_SPREAD,\n        YIELD_SPREAD,\n        HAZARD_RATE,\n        RATE,\n        RATIO,\n        PRICE,\n        RATE_LNVOL,\n        RATE_NVOL,\n        RATE_SLNVOL,\n        BASE_CORRELATION,\n        SHIFT\n    };\n\n    //! Constructor\n    MarketDatum(Real value, Date asofDate, const string& name, QuoteType quoteType, InstrumentType instrumentType)\n        : quote_(boost::make_shared<SimpleQuote>(value)), asofDate_(asofDate), name_(name),\n          instrumentType_(instrumentType), quoteType_(quoteType) {}\n\n    //! Default destructor\n    virtual ~MarketDatum() {}\n\n    //! \\name Inspectors\n    //@{\n    const string& name() const { return name_; }\n    const Handle<Quote>& quote() const { return quote_; }\n    Date asofDate() const { return asofDate_; }\n    InstrumentType instrumentType() const { return instrumentType_; }\n    QuoteType quoteType() const { return quoteType_; }\n    //@}\nprotected:\n    Handle<Quote> quote_;\n    Date asofDate_;\n    string name_;\n    InstrumentType instrumentType_;\n    QuoteType quoteType_;\n};\n\n//! Money market data class\n/*!\n  This class holds single market points of type\n  - MM\n\n  Specific data comprise currency, fwdStart, term\n\n  \\ingroup marketdata\n*/\nclass MoneyMarketQuote : public MarketDatum {\npublic:\n    //! Constructor\n    MoneyMarketQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Period fwdStart,\n                     Period term)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::MM), ccy_(ccy), fwdStart_(fwdStart),\n          term_(term) {}\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const Period& fwdStart() const { return fwdStart_; }\n    const Period& term() const { return term_; }\n    //@}\nprivate:\n    string ccy_;\n    Period fwdStart_;\n    Period term_;\n};\n\n//! FRA market data class\n/*!\n  This class holds single market points of type\n  - FRA\n\n  Specific data comprise currency, fwdStart, term\n\n  \\ingroup marketdata\n*/\nclass FRAQuote : public MarketDatum {\npublic:\n    //! Constructor\n    FRAQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Period fwdStart,\n             Period term)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::FRA), ccy_(ccy), fwdStart_(fwdStart),\n          term_(term) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const Period& fwdStart() const { return fwdStart_; }\n    const Period& term() const { return term_; }\n    //@}\nprivate:\n    string ccy_;\n    Period fwdStart_;\n    Period term_;\n};\n\n//! IMM FRA market data class\n/*!\n    This class holds single market points of type\n    - IMM FRA\n\n    Specific data comprise currency, IMM 1 and IMM 2\n\n    IMM 1 & 2 are strings representing the IMM dates - 1 is the next date,\n    up to 9, and then A, B, C, D\n\n\\ingroup marketdata\n*/\nclass ImmFraQuote : public MarketDatum {\npublic:\n    //! Constructor\n    ImmFraQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Size imm1, Size imm2)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::IMM_FRA), ccy_(ccy), imm1_(imm1), imm2_(imm2) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const Size& imm1() const { return imm1_; }\n    const Size& imm2() const { return imm2_; }\n    //@}\nprivate:\n    string ccy_;\n    Size imm1_;\n    Size imm2_;\n};\n\n//! Swap market data class\n/*!\n  This class holds single market points of type\n  - IR_SWAP\n\n  Specific data comprise currency, fwdStart, tenor, term\n\n  \\ingroup marketdata\n*/\nclass SwapQuote : public MarketDatum {\npublic:\n    //! Constructor\n    SwapQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Period fwdStart,\n              Period term, Period tenor)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::IR_SWAP), ccy_(ccy), fwdStart_(fwdStart),\n          term_(term), tenor_(tenor) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const Period& fwdStart() const { return fwdStart_; }\n    const Period& term() const { return term_; }\n    const Period& tenor() const { return tenor_; }\n    //@}\nprivate:\n    string ccy_;\n    Period fwdStart_;\n    Period term_;\n    Period tenor_;\n};\n\n//! Zero market data class\n/*!\n  This class holds single market points of type\n  - ZERO.\n  Specific data comprise currency, date and day counter.\n\n  Zero rates are hardly quoted in the market, but derived from quoted\n  yields such as deposits, swaps, as well as futures prices.\n  This data type is included here nevertheless\n  to enable consistency checks between ORE and reference systems.\n\n  \\ingroup marketdata\n*/\nclass ZeroQuote : public MarketDatum {\npublic:\n    //! Constructor\n    ZeroQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, const string& ccy, Date date,\n              DayCounter dayCounter, Period tenor = Period())\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::ZERO), ccy_(ccy), date_(date),\n          dayCounter_(dayCounter), tenor_(tenor) {\n        // Minimal adjustment in the absence of a calendar\n        QL_REQUIRE(date_ != Date() || tenor != Period(), \"ZeroQuote: either date or period is required\");\n        tenorBased_ = (date_ == Date());\n    }\n    //! Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    Date date() const { return date_; }\n    DayCounter dayCounter() const { return dayCounter_; }\n    const Period& tenor() const { return tenor_; }\n    bool tenorBased() const { return tenorBased_; }\n    //@}\nprivate:\n    string ccy_;\n    Date date_;\n    DayCounter dayCounter_;\n    Period tenor_;\n    bool tenorBased_;\n};\n\n//! Discount market data class\n/*!\n  This class holds single market points of type\n  - DISCOUNT.\n  Specific data comprise currency, date.\n\n  \\ingroup marketdata\n*/\nclass DiscountQuote : public MarketDatum {\npublic:\n    //! Constructor\n    DiscountQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Date date)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::DISCOUNT), ccy_(ccy), date_(date) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    Date date() const { return date_; }\n    //@}\nprivate:\n    string ccy_;\n    Date date_;\n};\n\n//! Money Market Future data class\n/*! This class holds single market points of type - MM_FUTURE.\n    Specific data comprise currency, expiry, contract and future tenor.\n\n    \\warning expiry parameter is expected in the format YYYY-MM e.g.\n             2013-06 for Jun 2013, 1998-05 for May 1998, etc.\n\n    \\ingroup marketdata\n*/\nclass MMFutureQuote : public MarketDatum {\npublic:\n    //! Constructor\n    MMFutureQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, string expiry,\n                  string contract = \"\", Period tenor = 3 * Months)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::MM_FUTURE), ccy_(ccy), expiry_(expiry),\n          contract_(contract), tenor_(tenor) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const string& expiry() const { return expiry_; }\n    Natural expiryYear() const;\n    Month expiryMonth() const;\n    const string& contract() const { return contract_; }\n    const Period& tenor() const { return tenor_; }\n    //@}\n\nprivate:\n    string ccy_;\n    string expiry_;\n    string contract_;\n    Period tenor_;\n};\n\n//! Basis Swap data class\n/*!\n  This class holds single market points of type\n  - BASIS_SWAP SPREAD\n  Specific data comprise\n  - flat term\n  - term\n\n  The quote (in Basis Points) is then interpreted as follows:\n\n  A fair Swap pays the reference index with \"flat term\" with spread zero\n  and receives the reference index with \"term\" plus the quoted spread.\n\n  \\ingroup marketdata\n*/\nclass BasisSwapQuote : public MarketDatum {\npublic:\n    //! Constructor\n    BasisSwapQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, Period flatTerm, Period term,\n                   string ccy = \"USD\", Period maturity = 3 * Months)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::BASIS_SWAP), flatTerm_(flatTerm), term_(term),\n          ccy_(ccy), maturity_(maturity) {}\n\n    //! \\name Inspectors\n    //@{\n    const Period& flatTerm() const { return flatTerm_; }\n    const Period& term() const { return term_; }\n    const string& ccy() const { return ccy_; }\n    const Period& maturity() const { return maturity_; }\n    //@}\nprivate:\n    Period flatTerm_;\n    Period term_;\n    string ccy_;\n    Period maturity_;\n};\n\n//! BMA Swap data class\n/*!\nThis class holds single market points of type\n- BMA_SWAP\nSpecific data comprise\n- term\n- currency\n- maturity\n\nThe quote (in Basis Points) is then interpreted as follows:\n\nA fair Swap pays the libor index with gearing equal to the quote\nand receives the bma index.\n\n\\ingroup marketdata\n*/\nclass BMASwapQuote : public MarketDatum {\npublic:\n    //! Constructor\n    BMASwapQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, Period term, string ccy = \"USD\",\n                 Period maturity = 3 * Months)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::BMA_SWAP), term_(term), ccy_(ccy),\n          maturity_(maturity) {}\n\n    //! \\name Inspectors\n    //@{\n    const Period& term() const { return term_; }\n    const string& ccy() const { return ccy_; }\n    const Period& maturity() const { return maturity_; }\n    //@}\nprivate:\n    Period term_;\n    string ccy_;\n    Period maturity_;\n};\n\n//! Cross Currency Basis Swap data class\n/*!\n  This class holds single market points of type\n  - CC_BASIS_SWAP BASIS_SPREAD\n  Specific data comprise\n  - flat currency\n  - currency\n\n  The quote in Basis Points is then interpreted as follows:\n\n  A fair Swap pays the reference index of \"flat currency\" in \"flat currency\"\n  with spread zero and receives the reference index of \"currency\" in\n  \"currency\" plus the quoted spread.\n\n  \\ingroup marketdata\n*/\nclass CrossCcyBasisSwapQuote : public MarketDatum {\npublic:\n    //! Constructor\n    CrossCcyBasisSwapQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string flatCcy,\n                           Period flatTerm, string ccy, Period term, Period maturity = 3 * Months)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::CC_BASIS_SWAP), flatCcy_(flatCcy),\n          flatTerm_(flatTerm), ccy_(ccy), term_(term), maturity_(maturity) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& flatCcy() const { return flatCcy_; }\n    const Period& flatTerm() const { return flatTerm_; }\n    const string& ccy() const { return ccy_; }\n    const Period& term() const { return term_; }\n    const Period& maturity() const { return maturity_; }\n    //@}\n\nprivate:\n    string flatCcy_;\n    Period flatTerm_;\n    string ccy_;\n    Period term_;\n    Period maturity_;\n};\n\n//! Cross Currency Fix Float Swap quote holder\n/*! Holds the quote for the fair fixed rate on a fixed against float\n    cross currency swap.\n\n    \\ingroup marketdata\n*/\nclass CrossCcyFixFloatSwapQuote : public MarketDatum {\npublic:\n    //! Constructor\n    CrossCcyFixFloatSwapQuote(QuantLib::Real value, const QuantLib::Date& asof, const std::string& name,\n                              QuoteType quoteType, const QuantLib::Currency& floatCurrency,\n                              const QuantLib::Period& floatTenor, const QuantLib::Currency& fixedCurrency,\n                              const QuantLib::Period& fixedTenor, const QuantLib::Period& maturity)\n        : MarketDatum(value, asof, name, quoteType, InstrumentType::CC_FIX_FLOAT_SWAP), floatCurrency_(floatCurrency),\n          floatTenor_(floatTenor), fixedCurrency_(fixedCurrency), fixedTenor_(fixedTenor), maturity_(maturity) {}\n\n    //! \\name Inspectors\n    //@{\n    const QuantLib::Currency& floatCurrency() const { return floatCurrency_; }\n    const QuantLib::Period& floatTenor() const { return floatTenor_; }\n    const QuantLib::Currency& fixedCurrency() const { return fixedCurrency_; }\n    const QuantLib::Period& fixedTenor() const { return fixedTenor_; }\n    const QuantLib::Period& maturity() const { return maturity_; }\n    //@}\n\nprivate:\n    QuantLib::Currency floatCurrency_;\n    QuantLib::Period floatTenor_;\n    QuantLib::Currency fixedCurrency_;\n    QuantLib::Period fixedTenor_;\n    QuantLib::Period maturity_;\n};\n\n//! CDS Spread data class\n/*!\n  This class holds single market points of type\n  - CREDIT_SPREAD\n\n  \\ingroup marketdata\n*/\nclass CdsSpreadQuote : public MarketDatum {\npublic:\n    //! COnstructor\n    CdsSpreadQuote(Real value, Date asofDate, const string& name, const string& underlyingName, const string& seniority,\n                   const string& ccy, Period term)\n        : MarketDatum(value, asofDate, name, QuoteType::CREDIT_SPREAD, InstrumentType::CDS),\n          underlyingName_(underlyingName), seniority_(seniority), ccy_(ccy), term_(term) {}\n\n    //! \\name Inspectors\n    //@{\n    const Period& term() const { return term_; }\n    const string& seniority() const { return seniority_; }\n    const string& ccy() const { return ccy_; }\n    const string& underlyingName() const { return underlyingName_; }\n    //@}\nprivate:\n    string underlyingName_;\n    string seniority_;\n    string ccy_;\n    Period term_;\n};\n\n//! Hazard rate data class\n/*!\n  This class holds single market points of type\n  - HAZARD_RATE\n\n  \\ingroup marketdata\n*/\nclass HazardRateQuote : public MarketDatum {\npublic:\n    //! Constructor\n    HazardRateQuote(Real value, Date asofDate, const string& name, const string& underlyingName,\n                    const string& seniority, const string& ccy, Period term)\n        : MarketDatum(value, asofDate, name, QuoteType::RATE, InstrumentType::HAZARD_RATE),\n          underlyingName_(underlyingName), seniority_(seniority), ccy_(ccy), term_(term) {}\n\n    //! \\name Inspectors\n    //@{\n    const Period& term() const { return term_; }\n    const string& seniority() const { return seniority_; }\n    const string& ccy() const { return ccy_; }\n    const string& underlyingName() const { return underlyingName_; }\n    //@}\nprivate:\n    string underlyingName_;\n    string seniority_;\n    string ccy_;\n    Period term_;\n};\n\n//! Recovery rate data class\n/*!\n  This class holds single market points of type\n  - RECOVERY_RATE\n  \\ingroup marketdata\n*/\nclass RecoveryRateQuote : public MarketDatum {\npublic:\n    //! Constructor\n    RecoveryRateQuote(Real value, Date asofDate, const string& name, const string& underlyingName,\n                      const string& seniority, const string& ccy)\n        : MarketDatum(value, asofDate, name, QuoteType::RATE, InstrumentType::RECOVERY_RATE),\n          underlyingName_(underlyingName), seniority_(seniority), ccy_(ccy) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& seniority() const { return seniority_; }\n    const string& ccy() const { return ccy_; }\n    const string& underlyingName() const { return underlyingName_; }\n    //@}\nprivate:\n    string underlyingName_;\n    string seniority_;\n    string ccy_;\n};\n\n//! Swaption data class\n/*!\n  This class holds single market points of type\n  - SWAPTION\n  Specific data comprise\n  - currency\n  - expiry\n  - term\n  - at-the-money flag (is an at-the-money swaption quote?)\n  - strike\n\n  \\ingroup marketdata\n*/\nclass SwaptionQuote : public MarketDatum {\npublic:\n    //! Constructor\n    SwaptionQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Period expiry,\n                  Period term, string dimension, Real strike = 0.0)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::SWAPTION), ccy_(ccy), expiry_(expiry),\n          term_(term), dimension_(dimension), strike_(strike) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const Period& expiry() const { return expiry_; }\n    const Period& term() const { return term_; }\n    const string& dimension() const { return dimension_; }\n    Real strike() { return strike_; }\n    //@}\nprivate:\n    string ccy_;\n    Period expiry_;\n    Period term_;\n    string dimension_;\n    Real strike_;\n};\n\n//! Shift data class (for SLN swaption volatilities)\n/*!\n  This class holds single market points of type\n  - SHIFT\n  Specific data comprise\n  - currency\n  - term\n\n  \\ingroup marketdata\n*/\nclass SwaptionShiftQuote : public MarketDatum {\npublic:\n    //! Constructor\n    SwaptionShiftQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Period term)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::SWAPTION), ccy_(ccy), term_(term) {\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::SHIFT, \"quote type must be SHIFT for shift data\");\n    }\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const Period& term() const { return term_; }\n    //@}\nprivate:\n    string ccy_;\n    Period term_;\n};\n\n//! Bond option data class\n/*!\nThis class holds single market points of type\n- BOND_OPTION\nSpecific data comprise\n- qualifier\n- expiry\n- term\n\n\\ingroup marketdata\n*/\n\nclass BondOptionQuote : public MarketDatum {\npublic:\n    //! Constructor\n    BondOptionQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string qualifier, Period expiry,\n                    Period term)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::BOND_OPTION), qualifier_(qualifier),\n          expiry_(expiry), term_(term) {}\n    //! \\name Inspectors\n    //@{\n    const string& qualifier() const { return qualifier_; }\n    const Period& expiry() const { return expiry_; }\n    const Period& term() const { return term_; }\n    //@}\nprivate:\n    string qualifier_;\n    Period expiry_;\n    Period term_;\n};\n\n//! Shift data class (for SLN bond option volatilities)\n/*!\nThis class holds single market points of type\n- SHIFT\nSpecific data comprise\n- qualifier\n- term\n\n\\ingroup marketdata\n*/\n\nclass BondOptionShiftQuote : public MarketDatum {\npublic:\n    //! Constructor\n    BondOptionShiftQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string qualifier,\n                         Period term)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::BOND_OPTION), qualifier_(qualifier),\n          term_(term) {\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::SHIFT, \"quote type must be SHIFT for shift data\");\n    }\n    //! \\name Inspectors\n    //@{\n    const string& qualifier() const { return qualifier_; }\n    const Period& term() const { return term_; }\n    //@}\nprivate:\n    string qualifier_;\n    Period term_;\n};\n\n//! Cap/Floor data class\n/*!\n  This class holds single market points of type\n  - CAPFLOOR\n  Specific data comprise\n  - currency\n  - term\n  - underlying index tenor\n  - at-the-money flag (is an at-the-money cap/floor quote?)\n  - relative quotation flag (quote to be added to the at-the-money quote?)\n  - strike\n\n  \\ingroup marketdata\n*/\nclass CapFloorQuote : public MarketDatum {\npublic:\n    //! Constructor\n    CapFloorQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string ccy, Period term,\n                  Period underlying, bool atm, bool relative, Real strike = 0.0)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::CAPFLOOR), ccy_(ccy), term_(term),\n          underlying_(underlying), atm_(atm), relative_(relative), strike_(strike) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& ccy() const { return ccy_; }\n    const Period& term() const { return term_; }\n    const Period& underlying() const { return underlying_; }\n    bool atm() const { return atm_; }\n    bool relative() const { return relative_; }\n    Real strike() { return strike_; }\n    //@}\nprivate:\n    string ccy_;\n    Period term_;\n    Period underlying_;\n    bool atm_;\n    bool relative_;\n    Real strike_;\n};\n\n//! Shift data class (for SLN cap/floor volatilities)\n/*! This class holds, for a given currency and index tenor, single market points of type\n    - SHIFT\n    \\ingroup marketdata\n*/\nclass CapFloorShiftQuote : public MarketDatum {\npublic:\n    CapFloorShiftQuote(Real value, const Date& asofDate, const string& name, QuoteType quoteType, const string& ccy,\n                       const Period& indexTenor)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::CAPFLOOR), ccy_(ccy), indexTenor_(indexTenor) {\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::SHIFT, \"Quote type must be SHIFT for shift data\");\n    }\n\n    const string& ccy() const { return ccy_; }\n    const Period& indexTenor() const { return indexTenor_; }\n\nprivate:\n    string ccy_;\n    Period indexTenor_;\n};\n\n//! Foreign exchange rate data class\n/*!\n  This class holds single market points of type\n  - FX_SPOT\n  Specific data comprise\n  - unit currency\n  - currency\n\n  The quote is then interpreted as follows:\n\n  1 unit of \"unit currency\" = quote * 1 unit of \"currency\"\n\n  \\ingroup marketdata\n*/\nclass FXSpotQuote : public MarketDatum {\npublic:\n    //! Constructor\n    FXSpotQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string unitCcy, string ccy)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::FX_SPOT), unitCcy_(unitCcy), ccy_(ccy) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& unitCcy() const { return unitCcy_; }\n    const string& ccy() const { return ccy_; }\n    //@}\nprivate:\n    string unitCcy_;\n    string ccy_;\n};\n\n//! Foreign exchange rate data class\n/*!\n  This class holds single market points of type\n  - FX_FWD\n  Specific data comprise\n  - unit currency\n  - currency\n  - term\n  - conversion factor\n\n  The quote is expected in \"forward points\" = (FXFwd - FXSpot) / conversionFactor\n\n  \\ingroup marketdata\n*/\nclass FXForwardQuote : public MarketDatum {\npublic:\n    //! Constructor\n    FXForwardQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string unitCcy, string ccy,\n                   const Period& term, Real conversionFactor = 1.0)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::FX_FWD), unitCcy_(unitCcy), ccy_(ccy),\n          term_(term), conversionFactor_(conversionFactor) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& unitCcy() const { return unitCcy_; }\n    const string& ccy() const { return ccy_; }\n    const Period& term() const { return term_; }\n    Real conversionFactor() const { return conversionFactor_; }\n    //@}\nprivate:\n    string unitCcy_;\n    string ccy_;\n    Period term_;\n    Real conversionFactor_;\n};\n\n//! FX Option data class\n/*!\n  This class holds single market points of type\n  - FX_OPTION\n  Specific data comprise\n  - unit currency\n  - currency\n  - expiry\n  - \"strike\" (25 delta butterfly \"25BF\", 25 delta risk reversal \"25RR\", atm straddle ATM)\n  we do not yet support ATMF or individual delta put/call quotes.\n\n  \\ingroup marketdata\n*/\nclass FXOptionQuote : public MarketDatum {\npublic:\n    //! Constructor\n    FXOptionQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string unitCcy, string ccy,\n                  Period expiry, string strike)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::FX_OPTION), unitCcy_(unitCcy), ccy_(ccy),\n          expiry_(expiry), strike_(strike) {\n        QL_REQUIRE(strike == \"ATM\" || strike == \"25BF\" || strike == \"25RR\",\n                   \"Invalid FXOptionQuote strike (\" << strike << \")\");\n    }\n\n    //! \\name Inspectors\n    //@{\n    const string& unitCcy() const { return unitCcy_; }\n    const string& ccy() const { return ccy_; }\n    const Period& expiry() const { return expiry_; }\n    const string& strike() const { return strike_; }\n    //@}\nprivate:\n    string unitCcy_;\n    string ccy_;\n    Period expiry_;\n    string strike_; // TODO: either: ATM, 25RR, 25BF. Should be an enum?\n};\n\n//! ZC Inflation swap data class\n/*!\n This class holds single market points of type\n - ZC_INFLATIONSWAP\n Specific data comprise index, term.\n\n \\ingroup marketdata\n */\nclass ZcInflationSwapQuote : public MarketDatum {\npublic:\n    ZcInflationSwapQuote(Real value, Date asofDate, const string& name, const string& index, Period term)\n        : MarketDatum(value, asofDate, name, QuoteType::RATE, InstrumentType::ZC_INFLATIONSWAP), index_(index),\n          term_(term) {}\n    string index() { return index_; }\n    Period term() { return term_; }\n\nprivate:\n    string index_;\n    Period term_;\n};\n\n//! Inflation Cap Floor data class\n/*!\nThis class holds single market points of type\n- INFLATION_CAPFLOOR\nSpecific data comprise type (can be price or nvol or slnvol),\nindex, term, cap/floor, strike\n\n\\ingroup marketdata\n*/\nclass InflationCapFloorQuote : public MarketDatum {\npublic:\n    InflationCapFloorQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, const string& index,\n                           Period term, bool isCap, const string& strike, InstrumentType instrumentType)\n        : MarketDatum(value, asofDate, name, quoteType, instrumentType), index_(index), term_(term), isCap_(isCap),\n          strike_(strike) {}\n    string index() { return index_; }\n    Period term() { return term_; }\n    bool isCap() { return isCap_; }\n    string strike() { return strike_; }\n\nprivate:\n    string index_;\n    Period term_;\n    bool isCap_;\n    string strike_;\n};\n\n//! ZC Cap Floor data class\n/*!\n This class holds single market points of type\n - ZC_INFLATION_CAPFLOOR\n Specific data comprise type (can be price or nvol or slnvol),\n index, term, cap/floor, strike\n\n \\ingroup marketdata\n */\nclass ZcInflationCapFloorQuote : public InflationCapFloorQuote {\npublic:\n    ZcInflationCapFloorQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, const string& index,\n                             Period term, bool isCap, const string& strike)\n        : InflationCapFloorQuote(value, asofDate, name, quoteType, index, term, isCap, strike,\n                                 InstrumentType::ZC_INFLATIONCAPFLOOR) {}\n};\n\n//! YoY Inflation swap data class\n/*!\n This class holds single market points of type\n - YOY_INFLATIONSWAP\n Specific data comprise index, term.\n\n \\ingroup marketdata\n */\nclass YoYInflationSwapQuote : public MarketDatum {\npublic:\n    YoYInflationSwapQuote(Real value, Date asofDate, const string& name, const string& index, Period term)\n        : MarketDatum(value, asofDate, name, QuoteType::RATE, InstrumentType::YY_INFLATIONSWAP), index_(index),\n          term_(term) {}\n    string index() { return index_; }\n    Period term() { return term_; }\n\nprivate:\n    string index_;\n    Period term_;\n};\n\n//! YY Cap Floor data class\n/*!\nThis class holds single market points of type\n- YY_INFLATION_CAPFLOOR\nSpecific data comprise type (can be price or nvol or slnvol),\nindex, term, cap/floor, strike\n\n\\ingroup marketdata\n*/\nclass YyInflationCapFloorQuote : public InflationCapFloorQuote {\npublic:\n    YyInflationCapFloorQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, const string& index,\n                             Period term, bool isCap, const string& strike)\n        : InflationCapFloorQuote(value, asofDate, name, quoteType, index, term, isCap, strike,\n                                 InstrumentType::YY_INFLATIONCAPFLOOR) {}\n};\n\n//! Inflation seasonality data class\n/*!\n This class holds single market points of type\n - SEASONALITY\n Specific data comprise inflation index, factor type (ADD, MULT) and month (JAN to DEC).\n\n \\ingroup marketdata\n */\nclass SeasonalityQuote : public MarketDatum {\npublic:\n    SeasonalityQuote(Real value, Date asofDate, const string& name, const string& index, const string& type,\n                     const string& month)\n        : MarketDatum(value, asofDate, name, QuoteType::RATE, InstrumentType::SEASONALITY), index_(index), type_(type),\n          month_(month) {}\n    string index() { return index_; }\n    string type() { return type_; }\n    string month() { return month_; }\n    QuantLib::Size applyMonth() const;\n\nprivate:\n    string index_;\n    string type_;\n    string month_;\n};\n\n//! Equity/Index spot price data class\n/*!\nThis class holds single market points of type\n- EQUITY_SPOT\nSpecific data comprise\n- Equity/Index name\n- currency\n\n\\ingroup marketdata\n*/\nclass EquitySpotQuote : public MarketDatum {\npublic:\n    //! Constructor\n    EquitySpotQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string equityName, string ccy)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::EQUITY_SPOT), eqName_(equityName), ccy_(ccy) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& eqName() const { return eqName_; }\n    const string& ccy() const { return ccy_; }\n    //@}\nprivate:\n    string eqName_;\n    string ccy_;\n};\n\n//! Equity forward data class\n/*!\nThis class holds single market points of type\n- EQUITY_FWD\nSpecific data comprise\n- Equity/Index name\n- currency\n- expiry date\n\nThe quote is expected as a forward price\n\n\\ingroup marketdata\n*/\nclass EquityForwardQuote : public MarketDatum {\npublic:\n    //! Constructor\n    EquityForwardQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string equityName,\n                       string ccy, const Date& expiryDate)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::EQUITY_FWD), eqName_(equityName), ccy_(ccy),\n          expiry_(expiryDate) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& eqName() const { return eqName_; }\n    const string& ccy() const { return ccy_; }\n    const Date& expiryDate() const { return expiry_; }\n    //@}\nprivate:\n    string eqName_;\n    string ccy_;\n    Date expiry_;\n};\n\n//! Equity/Index Dividend yield data class\n/*!\nThis class holds single market points of type\n- EQUITY_DIVIDEND\nSpecific data comprise\n- Equity/Index name\n- currency\n- yield tenor date\n\nThe quote is expected as a forward price\n\n\\ingroup marketdata\n*/\nclass EquityDividendYieldQuote : public MarketDatum {\npublic:\n    //! Constructor\n    EquityDividendYieldQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string equityName,\n                             string ccy, const Date& tenorDate)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::EQUITY_DIVIDEND), eqName_(equityName),\n          ccy_(ccy), tenor_(tenorDate) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& eqName() const { return eqName_; }\n    const string& ccy() const { return ccy_; }\n    const Date& tenorDate() const { return tenor_; }\n    //@}\nprivate:\n    string eqName_;\n    string ccy_;\n    Date tenor_;\n};\n\n//! Equity/Index Option data class\n/*!\nThis class holds single market points of type\n- EQUITY_OPTION\nSpecific data comprise\n- Equity/Index name\n- currency\n- expiry\n- strike - can be \"ATMF\" or an actual strike\n\n\\ingroup marketdata\n*/\nclass EquityOptionQuote : public MarketDatum {\npublic:\n    //! Constructor\n    EquityOptionQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, string equityName, string ccy,\n                      string expiry, string strike);\n\n    //! \\name Inspectors\n    //@{\n    const string& eqName() const { return eqName_; }\n    const string& ccy() const { return ccy_; }\n    const string& expiry() const { return expiry_; }\n    const string& strike() const { return strike_; }\n    //@}\nprivate:\n    string eqName_;\n    string ccy_;\n    string expiry_;\n    string strike_;\n};\n\n//! Bond spread data class\n/*!\nThis class holds single market points of type\n- BOND SPREAD\n\\ingroup marketdata\n*/\nclass SecuritySpreadQuote : public MarketDatum {\npublic:\n    //! Constructor\n    SecuritySpreadQuote(Real value, Date asofDate, const string& name, const string& securityID)\n        : MarketDatum(value, asofDate, name, QuoteType::YIELD_SPREAD, InstrumentType::BOND), securityID_(securityID) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& securityID() const { return securityID_; }\n    //@}\nprivate:\n    string securityID_;\n};\n\n//! Base correlation data class\n/*!\nThis class holds single market points of type\n- CDS_INDEX BASE_CORRELATION\n\\ingroup marketdata\n*/\nclass BaseCorrelationQuote : public MarketDatum {\npublic:\n    //! Constructor\n    BaseCorrelationQuote(Real value, Date asofDate, const string& name, QuoteType quoteType, const string& cdsIndexName,\n                         Period term, Real detachmentPoint)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::CDS_INDEX), cdsIndexName_(cdsIndexName),\n          term_(term), detachmentPoint_(detachmentPoint) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& cdsIndexName() const { return cdsIndexName_; }\n    Real detachmentPoint() const { return detachmentPoint_; }\n    Period term() const { return term_; }\n    //@}\nprivate:\n    string cdsIndexName_;\n    Period term_;\n    Real detachmentPoint_;\n};\n\n//! CDS Index Option data class\n/*!\nThis class holds single market points of type\n- INDEX_CDS_OPTION\nSpecific data comprise\n- index name\n- option expiry (either a date or a period)\n\n\\ingroup marketdata\n*/\nclass IndexCDSOptionQuote : public MarketDatum {\npublic:\n    //! Constructor\n    IndexCDSOptionQuote(Real value, Date asofDate, const string& name, const string& indexName, const string& expiry)\n        : MarketDatum(value, asofDate, name, QuoteType::RATE_LNVOL, InstrumentType::INDEX_CDS_OPTION),\n          indexName_(indexName), expiry_(expiry) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& indexName() const { return indexName_; }\n    const string& expiry() const { return expiry_; }\n    //@}\nprivate:\n    string indexName_;\n    string expiry_;\n};\n\n//! Commodity spot quote class\n/*! This class holds a spot price for a commodity in a given currency\n    \\ingroup marketdata\n*/\nclass CommoditySpotQuote : public MarketDatum {\npublic:\n    //! Constructor\n    CommoditySpotQuote(QuantLib::Real value, const QuantLib::Date& asofDate, const std::string& name,\n                       QuoteType quoteType, const std::string& commodityName, const std::string& quoteCurrency)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::COMMODITY_SPOT), commodityName_(commodityName),\n          quoteCurrency_(quoteCurrency) {\n        QL_REQUIRE(quoteType == QuoteType::PRICE, \"Commodity spot quote must be of type 'PRICE'\");\n    }\n\n    //! \\name Inspectors\n    //@{\n    const std::string& commodityName() const { return commodityName_; }\n    const std::string& quoteCurrency() const { return quoteCurrency_; }\n    //@}\n\nprivate:\n    std::string commodityName_;\n    std::string quoteCurrency_;\n};\n\n//! Commodity forward quote class\n/*! This class holds a forward price for a commodity in a given currency\n    \\ingroup marketdata\n*/\nclass CommodityForwardQuote : public MarketDatum {\npublic:\n    //! Constructor\n    CommodityForwardQuote(QuantLib::Real value, const QuantLib::Date& asofDate, const std::string& name,\n                          QuoteType quoteType, const std::string& commodityName, const std::string& quoteCurrency,\n                          const QuantLib::Date& expiryDate)\n        : MarketDatum(value, asofDate, name, quoteType, InstrumentType::COMMODITY_FWD), commodityName_(commodityName),\n          quoteCurrency_(quoteCurrency), expiryDate_(expiryDate) {\n        QL_REQUIRE(quoteType == QuoteType::PRICE, \"Commodity forward quote must be of type 'PRICE'\");\n    }\n\n    //! \\name Inspectors\n    //@{\n    const std::string& commodityName() const { return commodityName_; }\n    const std::string& quoteCurrency() const { return quoteCurrency_; }\n    const QuantLib::Date& expiryDate() const { return expiryDate_; }\n    //@}\n\nprivate:\n    std::string commodityName_;\n    std::string quoteCurrency_;\n    QuantLib::Date expiryDate_;\n};\n\n//! Commodity option data class\n/*! This class holds single market points of type COMMODITY_OPTION\n    \\ingroup marketdata\n*/\nclass CommodityOptionQuote : public MarketDatum {\npublic:\n    //! Constructor\n    /*! \\param value         The volatility value\n        \\param asof          The quote date\n        \\param name          The quote name\n        \\param quoteType     The quote type, should be RATE_NVOL\n        \\param commodityName The name of the underlying commodity\n        \\param quoteCurrency The quote currency\n        \\param expiry        Expiry can be a period or a date\n        \\param strike        Can be underlying commodity price or ATMF\n    */\n    CommodityOptionQuote(QuantLib::Real value, const QuantLib::Date& asof, const std::string& name, QuoteType quoteType,\n                         const std::string& commodityName, const std::string& quoteCurrency, const std::string& expiry,\n                         const std::string& strike);\n\n    //! \\name Inspectors\n    //@{\n    const std::string& commodityName() const { return commodityName_; }\n    const std::string& quoteCurrency() const { return quoteCurrency_; }\n    const std::string& expiry() const { return expiry_; }\n    const std::string& strike() const { return strike_; }\n    //@}\n\nprivate:\n    std::string commodityName_;\n    std::string quoteCurrency_;\n    std::string expiry_;\n    std::string strike_;\n};\n\n//! Spread data class\n/*! This class holds single market points of type SPREAD\n    \\ingroup marketdata\n*/\nclass CorrelationQuote : public MarketDatum {\npublic:\n    //! Constructor\n    /*! \\param value         The correlation value\n        \\param asof          The quote date\n        \\param name          The quote name\n        \\param quoteType     The quote type, should be RATE or PRICE\n        \\param index1        The name of the first index\n        \\param index2        The name of the second index\n        \\param expiry        Expiry can be a period or a date\n        \\param strike        Can be underlying commodity price or ATM\n    */\n    CorrelationQuote(QuantLib::Real value, const QuantLib::Date& asof, const std::string& name, QuoteType quoteType,\n                     const std::string& index1, const std::string& index2, const std::string& expiry,\n                     const std::string& strike);\n\n    //! \\name Inspectors\n    //@{\n    const std::string& index1() const { return index1_; }\n    const std::string& index2() const { return index2_; }\n    const std::string& expiry() const { return expiry_; }\n    const std::string& strike() const { return strike_; }\n    //@}\n\nprivate:\n    std::string index1_;\n    std::string index2_;\n    std::string expiry_;\n    std::string strike_;\n};\n\n//! CPR data class\n/*!\nThis class holds single market points of type\n- CPR\n\\ingroup marketdata\n*/\nclass CPRQuote : public MarketDatum {\npublic:\n    //! Constructor\n    CPRQuote(Real value, Date asofDate, const string& name, const string& securityId)\n        : MarketDatum(value, asofDate, name, QuoteType::RATE, InstrumentType::CPR), securityID_(securityId) {}\n\n    //! \\name Inspectors\n    //@{\n    const string& securityID() const { return securityID_; }\n    //@}\nprivate:\n    string securityID_;\n};\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "7e858aa5c28f912f219f296ca3d607330b2b0ab4", "size": 41728, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/marketdata/marketdatum.hpp", "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": "OREData/ored/marketdata/marketdatum.hpp", "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": "OREData/ored/marketdata/marketdatum.hpp", "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": 30.8183161004, "max_line_length": 120, "alphanum_fraction": 0.6758052147, "num_tokens": 10316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.057493275974271806, "lm_q1q2_score": 0.025171907262594155}}
{"text": "/*\n * Copyright 2021 IFPEN-CEA\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#include <map>\n#include <mpi.h>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/cmdline.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include <arccore/message_passing_mpi/StandaloneMpiMessagePassingMng.h>\n#include <arccore/trace/ITraceMng.h>\n#include <arccore/base/StringBuilder.h>\n\n#include <alien/distribution/MatrixDistribution.h>\n#include <alien/distribution/VectorDistribution.h>\n#include <alien/index_manager/IIndexManager.h>\n#include <alien/index_manager/IndexManager.h>\n#include <alien/index_manager/functional/DefaultAbstractFamily.h>\n\n#include <alien/ref/AlienRefSemantic.h>\n\n#include <alien/kernels/simple_csr/algebra/SimpleCSRLinearAlgebra.h>\n#include <alien/kernels/simple_csr/algebra/SimpleCSRInternalLinearAlgebra.h>\n\n#ifdef ALIEN_USE_SYCL\n#include <alien/kernels/sycl/SYCLPrecomp.h>\n#include <alien/kernels/sycl/data/SYCLBEllPackMatrix.h>\n#include <alien/kernels/sycl/data/SYCLVector.h>\n#include <alien/kernels/sycl/algebra/SYCLLinearAlgebra.h>\n#include <alien/kernels/sycl/algebra/SYCLInternalLinearAlgebra.h>\n\n#include \"alien/kernels/sycl/data/SYCLEnv.h\"\n#include \"alien/kernels/sycl/data/SYCLEnvInternal.h\"\n#include <alien/kernels/sycl/algebra/SYCLKernelInternal.h>\n#endif\n\n#include <alien/expression/krylov/AlienKrylov.h>\n\n#include <alien/utils/StdTimer.h>\n\nnamespace Environment\n{\nvoid initialize(int argc, char** argv)\n{\n  MPI_Init(&argc, &argv);\n}\n\nvoid finalize()\n{\n  MPI_Finalize();\n}\n\nArccore::MessagePassing::IMessagePassingMng*\nparallelMng()\n{\n  return Arccore::MessagePassing::Mpi::StandaloneMpiMessagePassingMng::create(\n  MPI_COMM_WORLD);\n}\n\nArccore::ITraceMng*\ntraceMng()\n{\n  return Arccore::arccoreCreateDefaultTraceMng();\n}\n} // namespace Environment\n\n// Define index type for local ids\ntypedef Arccore::Integer LID;\n// Define index type for global (unique) ids\ntypedef Arccore::Int64 UID;\n\nint main(int argc, char** argv)\n{\n\n  // clang-format off\n  using namespace boost::program_options ;\n  options_description desc;\n  desc.add_options()\n      (\"help\",                                                            \"produce help\")\n      (\"nx\",                  value<int>()->default_value(10),            \"nx\")\n      (\"ny\",                  value<int>()->default_value(10),            \"ny\")\n      (\"solver\",              value<std::string>()->default_value(\"bicgs\"),\"solver [cg,bicgs]\")\n      (\"precond\",             value<std::string>()->default_value(\"diag\"),\"preconditioner [diag,cheb,neumann,ilu0,filu0]\")\n      (\"output-level\",        value<int>()->default_value(0),             \"output level\")\n      (\"asynch\",              value<int>()->default_value(0),             \"Asynch mode synch : 0 or asynch 1\")\n      (\"dot-algo\",            value<int>()->default_value(0),             \"dot algo choice\")\n      (\"max-iter\",            value<int>()->default_value(1000),          \"max iterations\")\n      (\"tol\",                 value<double>()->default_value(1.e-6),      \"tolerance\")\n      (\"poly-factor\",         value<double>()->default_value(0.5),        \"polynome factor\")\n      (\"poly-factor-max-iter\",value<int>()->default_value(10),            \"polynome factor max iterations\")\n      (\"poly-order\",          value<int>()->default_value(3),             \"polynome order\")\n      (\"filu-factor-niter\",   value<int>()->default_value(0),             \"nb ILU Factorization iter\")\n      (\"filu-solver-niter\",   value<int>()->default_value(3),             \"nb ILU resolution iter\")\n      (\"filu-tol\",            value<double>()->default_value(3),          \"nb ILU tolerance\")\n      (\"kernel\",              value<std::string>()->default_value(\"simplecsr\"), \"Kernel type [simplecsr sycl]\")\n      (\"test\",                value<std::string>()->default_value(\"solver\"),    \"test [solver,mult,all]\");\n  // clang-format on\n\n  variables_map vm;\n  store(parse_command_line(argc, argv, desc), vm);\n  notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return 1;\n  }\n\n  /*\n   * Example : LAPLACIAN PROBLEM on a 2D square mesh of size NX x NY\n   * Unknowns on nodes (i,j)\n   * Use a 5-Points stencil\n   *\n   *\n   *           (I,J+1)\n   *              |\n   * (I-1,J) -- (I,J) -- (I+1,J)\n   *              |\n   *           (I,J-1)\n   *\n   * TUTORIAL : LINEAR SYSTEM mat.X=rhs DEFINITION\n   * =========================================\n   */\n  int Nx = vm[\"nx\"].as<int>();\n  int Ny = vm[\"ny\"].as<int>();\n  // int space_size = Nx * Ny;\n\n  // INITIALIZE PARALLEL ENVIRONMENT\n  Environment::initialize(argc, argv);\n\n  auto parallel_mng = Environment::parallelMng();\n  auto trace_mng = Environment::traceMng();\n\n  auto comm_size = Environment::parallelMng()->commSize();\n  auto comm_rank = Environment::parallelMng()->commRank();\n\n  Arccore::StringBuilder filename(\"krylov.log\");\n  Arccore::ReferenceCounter<Arccore::ITraceStream> ofile;\n  if (comm_size > 1) {\n    filename += comm_rank;\n    ofile = Arccore::ITraceStream::createFileStream(filename.toString());\n    trace_mng->setRedirectStream(ofile.get());\n  }\n  trace_mng->finishInitialize();\n\n  Alien::setTraceMng(trace_mng);\n  Alien::setVerbosityLevel(Alien::Verbosity::Debug);\n\n  trace_mng->info() << \"INFO START KRYLOV TEST\";\n  trace_mng->info() << \"NB PROC = \" << comm_size;\n  trace_mng->info() << \"RANK    = \" << comm_rank;\n  trace_mng->flush();\n\n  /*\n     * MESH PARTITION ALONG Y AXIS\n     *\n     */\n  int local_ny = Ny / comm_size;\n  int r = Ny % comm_size;\n\n  std::vector<int> y_offset(comm_size + 1);\n  y_offset[0] = 0;\n  for (int ip = 0; ip < r; ++ip)\n    y_offset[ip + 1] = y_offset[ip] + local_ny + 1;\n\n  for (int ip = r; ip < comm_size; ++ip)\n    y_offset[ip + 1] = y_offset[ip] + local_ny;\n\n  // Define a lambda function to compute node uids from the 2D (i,j) coordinates\n  // (i,j) -> uid = node_uid(i,j)\n  auto node_uid = [&](int i, int j) { return j * Nx + i; };\n\n  /*\n     * DEFINITION of Unknowns Unique Ids and  Local Ids\n     */\n  Alien::UniqueArray<UID> uid;\n  Alien::UniqueArray<Arccore::Integer> owners;\n  Alien::UniqueArray<LID> lid;\n  std::map<UID, LID> uid2lid;\n  int first_j = y_offset[comm_rank];\n  int last_j = y_offset[comm_rank + 1];\n\n  int index = 0;\n  for (int j = first_j; j < last_j; ++j) {\n    for (int i = 0; i < Nx; ++i) {\n      int n_uid = node_uid(i, j);\n      uid.add(n_uid);\n      owners.add(comm_rank);\n      lid.add(index);\n      uid2lid[n_uid] = index;\n      ++index;\n    }\n  }\n\n  int nb_ghost = 0;\n  if (comm_size > 1) {\n    if (comm_rank > 0) {\n      for (int i = 0; i < Nx; ++i) {\n        int n_uid = node_uid(i, first_j - 1);\n        uid.add(n_uid);\n        owners.add(comm_rank - 1);\n        lid.add(index);\n        uid2lid[n_uid] = index;\n        ++index;\n        ++nb_ghost;\n      }\n    }\n    if (comm_rank < comm_size - 1) {\n      for (int i = 0; i < Nx; ++i) {\n        int n_uid = node_uid(i, last_j);\n        uid.add(n_uid);\n        owners.add(comm_rank + 1);\n        lid.add(index);\n        uid2lid[n_uid] = index;\n        ++index;\n        ++nb_ghost;\n      }\n    }\n  }\n\n  /*\n     * DEFINITION of an abstract family of unknowns\n     */\n  Alien::DefaultAbstractFamily family(uid, owners, parallel_mng);\n\n  Alien::IndexManager index_manager(parallel_mng);\n\n  /*\n     * Creation of a set of indexes\n     */\n  auto indexSetU = index_manager.buildScalarIndexSet(\"U\", family, 0);\n\n  // Combine all index set and create Linear system index system\n  index_manager.prepare();\n\n  auto global_size = index_manager.globalSize();\n  auto local_size = index_manager.localSize();\n\n  trace_mng->info() << \"GLOBAL SIZE : \" << global_size;\n  trace_mng->info() << \"LOCAL SIZE  : \" << local_size;\n  trace_mng->info() << \"GHOST SIZE  : \" << nb_ghost;\n  trace_mng->flush();\n\n  /*\n   * DEFINITION of\n   * - Alien Space,\n   * - matrix and vector distributions\n   * to manage the distribution of indexes between all MPI processes\n   */\n\n  auto space = Alien::Space(global_size, \"MySpace\");\n\n  auto matrix_dist =\n  Alien::MatrixDistribution(global_size, global_size, local_size, parallel_mng);\n  auto vector_dist = Alien::VectorDistribution(global_size, local_size, parallel_mng);\n\n  trace_mng->info() << \"MATRIX DISTRIBUTION INFO\";\n  trace_mng->info() << \"GLOBAL ROW SIZE : \" << matrix_dist.globalRowSize();\n  trace_mng->info() << \"LOCAL ROW SIZE  : \" << matrix_dist.localRowSize();\n  trace_mng->info() << \"GLOBAL COL SIZE : \" << matrix_dist.globalColSize();\n  trace_mng->info() << \"LOCAL COL SIZE  : \" << matrix_dist.localColSize();\n\n  trace_mng->info() << \"VECTOR DISTRIBUTION INFO\";\n  trace_mng->info() << \"GLOBAL SIZE : \" << vector_dist.globalSize();\n  trace_mng->info() << \"LOCAL SIZE  : \" << vector_dist.localSize();\n  trace_mng->flush();\n\n  auto allUIndex = index_manager.getIndexes(indexSetU);\n\n  double off_diag = 0.5;\n  /*\n   *  Assemble matrix.\n   */\n  auto A = Alien::Matrix(matrix_dist);\n\n  /* Two passes */\n\n  // PROFILE DEFINITION\n  {\n    Alien::MatrixProfiler profiler(A);\n\n    for (int j = first_j; j < last_j; ++j) {\n      // BOUCLE SUIVANT AXE X\n      for (int i = 0; i < Nx; ++i) {\n        auto n_uid = node_uid(i, j);\n        auto n_lid = uid2lid[n_uid];\n        auto irow = allUIndex[n_lid];\n\n        // DEFINE DIAGONAL\n        profiler.addMatrixEntry(irow, irow);\n\n        // OFF DIAG\n        // lower\n        if (j > 0) {\n          auto off_uid = node_uid(i, j - 1);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1)\n            profiler.addMatrixEntry(irow, jcol);\n        }\n        // left\n        if (i > 0) {\n          auto off_uid = node_uid(i - 1, j);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1)\n            profiler.addMatrixEntry(irow, jcol);\n        }\n        // right\n        if (i < Nx - 1) {\n          auto off_uid = node_uid(i + 1, j);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1)\n            profiler.addMatrixEntry(irow, jcol);\n        }\n        // upper\n        if (j < Ny - 1) {\n          auto off_uid = node_uid(i, j + 1);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1)\n            profiler.addMatrixEntry(irow, jcol);\n        }\n      }\n    }\n  }\n\n  // SECOND STEP : MATRIX FILLING STEP\n  {\n    Alien::ProfiledMatrixBuilder builder(A, Alien::ProfiledMatrixOptions::eResetValues);\n    // Loop on Y-axis\n    for (int j = first_j; j < last_j; ++j) {\n      // Loop on X-axis\n      for (int i = 0; i < Nx; ++i) {\n        auto n_uid = node_uid(i, j);\n        auto n_lid = uid2lid[n_uid];\n        auto irow = allUIndex[n_lid];\n\n        double diag = 0.;\n        // OFF DIAG\n        // lower\n        if (j > 0) {\n          auto off_uid = node_uid(i, j - 1);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1) {\n            builder(irow, jcol) = -off_diag;\n            diag += off_diag;\n          }\n        }\n        // left\n        if (i > 0) {\n          auto off_uid = node_uid(i - 1, j);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1) {\n            builder(irow, jcol) = -off_diag;\n            diag += off_diag;\n          }\n        }\n        // right\n        if (i < Nx - 1) {\n          auto off_uid = node_uid(i + 1, j);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1) {\n            builder(irow, jcol) = -off_diag;\n            diag += off_diag;\n          }\n        }\n        if (i == Nx - 1) {\n          // Dirichlet Boundary Condition on XMAX\n          diag += off_diag;\n        }\n\n        // upper\n        if (j < Ny - 1) {\n          auto off_uid = node_uid(i, j + 1);\n          auto off_lid = uid2lid[off_uid];\n          auto jcol = allUIndex[off_lid];\n          if (jcol != -1) {\n            builder(irow, jcol) = -off_diag;\n            diag += off_diag;\n          }\n        }\n        // DIAGONAL\n        builder(irow, irow) = diag;\n      }\n    }\n  }\n\n  /*\n   * Build rhs vector\n   */\n  auto b = Alien::Vector(vector_dist);\n  auto x = Alien::Vector(vector_dist);\n\n  {\n    Alien::VectorWriter writer_b(b);\n    Alien::VectorWriter writer_x(x);\n\n    // Loop on Y-axis\n    for (int j = first_j; j < last_j; ++j) {\n      // Loop on X-axis\n      for (int i = 0; i < Nx; ++i) {\n        auto n_uid = node_uid(i, j);\n        auto n_lid = uid2lid[n_uid];\n        auto irow = allUIndex[n_lid];\n\n        //writer[irow] = 1. / (1. + i + j);\n        //writer[irow] = 1. ;\n        writer_b[irow] = 0.;\n        writer_x[irow] = 0.;\n        if (i == Nx - 1) {\n          writer_b[irow] += off_diag;\n        }\n      }\n    }\n  }\n\n  // clang-format off\n  typedef Alien::StdTimer   TimerType ;\n  typedef TimerType::Sentry SentryType ;\n  // clang-format on\n\n  TimerType timer;\n  std::string kernel = vm[\"kernel\"].as<std::string>();\n\n  if (vm[\"test\"].as<std::string>().compare(\"all\") == 0 || vm[\"test\"].as<std::string>().compare(\"mult\") == 0) {\n\n    auto x0 = Alien::Vector(vector_dist);\n    auto y = Alien::Vector(vector_dist);\n    {\n      Alien::VectorWriter writer_x0(x0);\n      writer_x0 = 1.;\n    }\n\n    // clang-format off\n    auto run = [&](auto& alg)\n              {\n                typedef typename\n                    boost::remove_reference<decltype(alg)>::type AlgebraType ;\n                typedef typename AlgebraType::BackEndType        BackEndType ;\n                typedef Alien::Iteration<AlgebraType>            StopCriteriaType ;\n\n\n                auto const& true_A = A.impl()->get<BackEndType>() ;\n                auto const& true_x0 = x0.impl()->get<BackEndType>() ;\n                auto&       true_y = y.impl()->get<BackEndType>(true) ;\n\n                alg.mult(true_A,true_x0,true_y) ;\n              } ;\n    // clang-format on\n\n    if (kernel.compare(\"simplecsr\") == 0) {\n      Alien::SimpleCSRInternalLinearAlgebra alg;\n      SentryType sentry(timer, \"CSR-SPMV\");\n      run(alg);\n    }\n    if (kernel.compare(\"sycl\") == 0) {\n#ifdef ALIEN_USE_SYCL\n      Alien::SYCLInternalLinearAlgebra alg;\n      SentryType sentry(timer, \"SYCL-SPMV\");\n      run(alg);\n#else\n      trace_mng->info() << \"SYCL BackEnd not available\";\n#endif\n    }\n  }\n\n  if (vm[\"test\"].as<std::string>().compare(\"all\") == 0 || vm[\"test\"].as<std::string>().compare(\"solver\") == 0) {\n    // clang-format off\n    int         max_iteration = vm[\"max-iter\"].as<int>();\n    double      tol           = vm[\"tol\"].as<double>();\n    std::string solver        = vm[\"solver\"].as<std::string>();\n    std::string precond       = vm[\"precond\"].as<std::string>();\n    int         output_level  = vm[\"output-level\"].as<int>();\n    int         asynch        = vm[\"asynch\"].as<int>();\n    // clang-format on\n\n    // clang-format off\n    auto run = [&](auto& alg)\n              {\n                typedef typename\n                    boost::remove_reference<decltype(alg)>::type AlgebraType ;\n                typedef typename AlgebraType::BackEndType        BackEndType ;\n                typedef Alien::Iteration<AlgebraType>            StopCriteriaType ;\n\n\n                auto const& true_A = A.impl()->get<BackEndType>() ;\n                auto const& true_b = b.impl()->get<BackEndType>() ;\n                auto&       true_x = x.impl()->get<BackEndType>(true) ;\n\n                StopCriteriaType stop_criteria{alg,true_b,tol,max_iteration,output_level>0?trace_mng:nullptr} ;\n\n                if(solver.compare(\"cg\")==0)\n                {\n                  typedef Alien::CG<AlgebraType> SolverType ;\n\n                  SolverType solver{alg,trace_mng} ;\n                  solver.setOutputLevel(output_level) ;\n\n                  if(precond.compare(\"diag\")==0)\n                    {\n                      trace_mng->info()<<\"DIAG PRECONDITIONER\";\n                      trace_mng->flush() ;\n                      typedef Alien::DiagPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType      precond{alg,true_A} ;\n                      precond.init() ;\n                      SentryType sentry(timer,\"CG-Diag\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                  if(precond.compare(\"cheb\")==0)\n                    {\n                      trace_mng->info()<<\"CHEBYSHEV PRECONDITIONER\";\n                      double polynom_factor          = vm[\"poly-factor\"].as<double>() ;\n                      int    polynom_order           = vm[\"poly-order\"].as<int>() ;\n                      int    polynom_factor_max_iter = vm[\"poly-factor-max-iter\"].as<int>() ;\n\n                      typedef Alien::ChebyshevPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType      precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,trace_mng} ;\n                      precond.setOutputLevel(output_level) ;\n                      precond.init() ;\n\n                      SentryType sentry(timer,\"CG-ChebyshevPoly\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                  if(precond.compare(\"neumann\")==0)\n                    {\n                      trace_mng->info()<<\"NEUMANN PRECONDITIONER\";\n                      double polynom_factor          = vm[\"poly-factor\"].as<double>() ;\n                      int    polynom_order           = vm[\"poly-order\"].as<int>() ;\n                      int    polynom_factor_max_iter = vm[\"poly-factor-max-iter\"].as<int>() ;\n\n                      typedef Alien::NeumannPolyPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,trace_mng} ;\n                      precond.init() ;\n\n                      SentryType sentry(timer,\"CG-NeumanPoly\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                }\n\n                if(solver.compare(\"bicgs\")==0)\n                {\n                  typedef Alien::BiCGStab<AlgebraType> SolverType ;\n                  SolverType solver{alg,trace_mng} ;\n                  solver.setOutputLevel(output_level) ;\n                  if(precond.compare(\"diag\")==0)\n                    {\n                      trace_mng->info()<<\"DIAG PRECONDITIONER\";\n                      trace_mng->flush() ;\n                      typedef Alien::DiagPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType      precond{alg,true_A} ;\n                      precond.init() ;\n                      SentryType sentry(timer,\"BiCGS-Diag\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                  if(precond.compare(\"cheb\")==0)\n                    {\n                      trace_mng->info()<<\"CHEBYSHEV PRECONDITIONER\";\n                      double polynom_factor          = vm[\"poly-factor\"].as<double>() ;\n                      int    polynom_order           = vm[\"poly-order\"].as<int>() ;\n                      int    polynom_factor_max_iter = vm[\"poly-factor-max-iter\"].as<int>() ;\n\n                      typedef Alien::ChebyshevPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType      precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,trace_mng} ;\n                      precond.setOutputLevel(output_level) ;\n                      precond.init() ;\n\n                      SentryType sentry(timer,\"BiCGS-ChebyshevPoly\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                  if(precond.compare(\"neumann\")==0)\n                    {\n                      trace_mng->info()<<\"NEUMANN PRECONDITIONER\";\n                      double polynom_factor          = vm[\"poly-factor\"].as<double>() ;\n                      int    polynom_order           = vm[\"poly-order\"].as<int>() ;\n                      int    polynom_factor_max_iter = vm[\"poly-factor-max-iter\"].as<int>() ;\n\n                      typedef Alien::NeumannPolyPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,trace_mng} ;\n                      precond.init() ;\n\n                      SentryType sentry(timer,\"BiCGS-NeumanPoly\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                  if(precond.compare(\"ilu0\")==0)\n                    {\n                      trace_mng->info()<<\"ILU0 PRECONDITIONER\";\n                      typedef Alien::ILU0Preconditioner<AlgebraType> PrecondType ;\n                      PrecondType precond{alg,true_A,trace_mng} ;\n                      precond.init() ;\n\n                      SentryType sentry(timer,\"BiCGS-ILU0\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                  if(precond.compare(\"filu0\")==0)\n                    {\n                      trace_mng->info()<<\"FILU0 PRECONDITIONER\";\n                      typedef Alien::FILU0Preconditioner<AlgebraType> PrecondType ;\n                      PrecondType precond{alg,true_A,trace_mng} ;\n                      precond.setParameter(\"nb-factor-iter\",vm[\"filu-factor-niter\"].as<int>()) ;\n                      precond.setParameter(\"nb-solver-iter\",vm[\"filu-solver-niter\"].as<int>()) ;\n                      precond.setParameter(\"tol\",           vm[\"filu-tol\"].as<double>()) ;\n                      precond.init() ;\n\n                      SentryType sentry(timer,\"BiCGS-FILU0\") ;\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                }\n\n                if(stop_criteria.getStatus())\n                {\n                  trace_mng->info()<<\"Solver has converged\";\n                  trace_mng->info()<<\"Nb iterations  : \"<<stop_criteria();\n                  trace_mng->info()<<\"Criteria value : \"<<stop_criteria.getValue();\n                }\n                else\n                {\n                  trace_mng->info()<<\"Solver convergence failed\";\n                }\n              } ;\n    // clang-format on\n\n    if (kernel.compare(\"simplecsr\") == 0) {\n      Alien::SimpleCSRInternalLinearAlgebra alg;\n      run(alg);\n    }\n    if (kernel.compare(\"sycl\") == 0) {\n#ifdef ALIEN_USE_SYCL\n      Alien::SYCLInternalLinearAlgebra alg;\n      alg.setDotAlgo(vm[\"dot-algo\"].as<int>());\n      run(alg);\n#else\n      trace_mng->info() << \"SYCL BackEnd not available\";\n#endif\n    }\n  }\n\n  timer.printInfo(trace_mng->info().file(), \"KRYLOV-BENCH\");\n\n  Environment::finalize();\n\n  return 0;\n}\n", "meta": {"hexsha": "40c8335a2f812a8f9f0f965a2d457e4b92326e0b", "size": 24495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/test_krylov.cpp", "max_stars_repo_name": "cedricga91/alien", "max_stars_repo_head_hexsha": "2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T08:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T18:39:32.000Z", "max_issues_repo_path": "examples/test_krylov.cpp", "max_issues_repo_name": "cedricga91/alien", "max_issues_repo_head_hexsha": "2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 42.0, "max_issues_repo_issues_event_min_datetime": "2021-07-01T17:32:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T14:53:56.000Z", "max_forks_repo_path": "examples/test_krylov.cpp", "max_forks_repo_name": "cedricga91/alien", "max_forks_repo_head_hexsha": "2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T12:59:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T06:35:01.000Z", "avg_line_length": 35.5515239478, "max_line_length": 123, "alphanum_fraction": 0.5450500102, "num_tokens": 6160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05033062832405111, "lm_q1q2_score": 0.025165314162025554}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#ifndef BOOST_MULTIPRECISION_RATIONAL_ADAPTOR_HPP\n#define BOOST_MULTIPRECISION_RATIONAL_ADAPTOR_HPP\n\n#include <boost/multiprecision/number.hpp>\n#include <boost/multiprecision/detail/hash.hpp>\n#include <boost/multiprecision/detail/float128_functions.hpp>\n#include <boost/multiprecision/detail/no_exceptions_support.hpp>\n\nnamespace boost {\nnamespace multiprecision {\nnamespace backends {\n\ntemplate <class Backend>\nstruct rational_adaptor\n{\n   //\n   // Each backend need to declare 3 type lists which declare the types\n   // with which this can interoperate.  These lists must at least contain\n   // the widest type in each category - so \"long long\" must be the final\n   // type in the signed_types list for example.  Any narrower types if not\n   // present in the list will get promoted to the next wider type that is\n   // in the list whenever mixed arithmetic involving that type is encountered.\n   //\n   typedef typename Backend::signed_types    signed_types;\n   typedef typename Backend::unsigned_types  unsigned_types;\n   typedef typename Backend::float_types     float_types;\n\n   typedef typename std::tuple_element<0, unsigned_types>::type ui_type;\n\n   static Backend get_one()\n   {\n      Backend t;\n      t = static_cast<ui_type>(1);\n      return t;\n   }\n   static Backend get_zero()\n   {\n      Backend t;\n      t = static_cast<ui_type>(0);\n      return t;\n   }\n\n   static const Backend& one()\n   {\n      static const Backend result(get_one());\n      return result;\n   }\n   static const Backend& zero()\n   {\n      static const Backend result(get_zero());\n      return result;\n   }\n\n   void normalize()\n   {\n      using default_ops::eval_gcd;\n      using default_ops::eval_eq;\n      using default_ops::eval_divide;\n\n      Backend g, t;\n      eval_gcd(g, m_num, m_denom);\n      if (!eval_eq(g, one()))\n      {\n         eval_divide(t, m_num, g);\n         m_num.swap(t);\n         eval_divide(t, m_denom, g);\n         m_denom = std::move(t);\n      }\n   }\n\n   // We must have a default constructor:\n   rational_adaptor()\n      : m_num(zero()), m_denom(one()) {}\n\n   rational_adaptor(const rational_adaptor& o) : m_num(o.m_num), m_denom(o.m_denom) {}\n   rational_adaptor(rational_adaptor&& o) = default;\n\n   // Optional constructors, we can make this type slightly more efficient\n   // by providing constructors from any type we can handle natively.\n   // These will also cause number<> to be implicitly constructible\n   // from these types unless we make such constructors explicit.\n   //\n   template <class Arithmetic>\n   rational_adaptor(const Arithmetic& val, typename std::enable_if<std::is_constructible<Backend, Arithmetic>::value && !std::is_floating_point<Arithmetic>::value>::type const* = nullptr)\n      : m_num(val), m_denom(one()) {}\n\n   //\n   // Pass-through 2-arg construction of components:\n   //\n   template <class T, class U>\n   rational_adaptor(const T& a, const U& b, typename std::enable_if<std::is_constructible<Backend, T const&>::value && std::is_constructible<Backend, U const&>::value>::type const* = nullptr)\n      : m_num(a), m_denom(b) \n   {\n      normalize();\n   }\n   template <class T, class U>\n   rational_adaptor(T&& a, const U& b, typename std::enable_if<std::is_constructible<Backend, T>::value && std::is_constructible<Backend, U>::value>::type const* = nullptr)\n      : m_num(static_cast<T&&>(a)), m_denom(b) \n   {\n      normalize();\n   }\n   template <class T, class U>\n   rational_adaptor(T&& a, U&& b, typename std::enable_if<std::is_constructible<Backend, T>::value && std::is_constructible<Backend, U>::value>::type const* = nullptr)\n      : m_num(static_cast<T&&>(a)), m_denom(static_cast<U&&>(b)) \n   {\n      normalize();\n   }\n   template <class T, class U>\n   rational_adaptor(const T& a, U&& b, typename std::enable_if<std::is_constructible<Backend, T>::value && std::is_constructible<Backend, U>::value>::type const* = nullptr)\n      : m_num(a), m_denom(static_cast<U&&>(b)) \n   {\n      normalize();\n   }\n   //\n   // In the absense of converting constructors, operator= takes the strain.\n   // In addition to the usual suspects, there must be one operator= for each type\n   // listed in signed_types, unsigned_types, and float_types plus a string constructor.\n   //\n   rational_adaptor& operator=(const rational_adaptor& o) = default;\n   rational_adaptor& operator=(rational_adaptor&& o) = default;\n   template <class Arithmetic>\n   inline typename std::enable_if<!std::is_floating_point<Arithmetic>::value, rational_adaptor&>::type operator=(const Arithmetic& i)\n   {\n      m_num = i;\n      m_denom = one();\n      return *this;\n   }\n   rational_adaptor& operator=(const char* s)\n   {\n      using default_ops::eval_eq;\n\n      std::string                        s1;\n      multiprecision::number<Backend>    v1, v2;\n      char                               c;\n      bool                               have_hex = false;\n      const char* p = s; // saved for later\n\n      while ((0 != (c = *s)) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F'))))\n      {\n         if (c == 'x' || c == 'X')\n            have_hex = true;\n         s1.append(1, c);\n         ++s;\n      }\n      v1.assign(s1);\n      s1.erase();\n      if (c == '/')\n      {\n         ++s;\n         while ((0 != (c = *s)) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F'))))\n         {\n            if (c == 'x' || c == 'X')\n               have_hex = true;\n            s1.append(1, c);\n            ++s;\n         }\n         v2.assign(s1);\n      }\n      else\n         v2 = 1;\n      if (*s)\n      {\n         BOOST_MP_THROW_EXCEPTION(std::runtime_error(std::string(\"Could not parse the string \\\"\") + p + std::string(\"\\\" as a valid rational number.\")));\n      }\n      multiprecision::number<Backend> gcd;\n      eval_gcd(gcd.backend(), v1.backend(), v2.backend());\n      if (!eval_eq(gcd.backend(), one()))\n      {\n         v1 /= gcd;\n         v2 /= gcd;\n      }\n      num() = std::move(std::move(v1).backend());\n      denom() = std::move(std::move(v2).backend());\n      return *this;\n   }\n   template <class Float>\n   typename std::enable_if<std::is_floating_point<Float>::value, rational_adaptor&>::type operator=(Float i)\n   {\n      using default_ops::eval_eq;\n      BOOST_MP_FLOAT128_USING using std::floor; using std::frexp; using std::ldexp;\n\n      int   e;\n      Float f = frexp(i, &e);\n#ifdef BOOST_HAS_FLOAT128\n      f = ldexp(f, std::is_same<float128_type, Float>::value ? 113 : std::numeric_limits<Float>::digits);\n      e -= std::is_same<float128_type, Float>::value ? 113 : std::numeric_limits<Float>::digits;\n#else\n      f = ldexp(f, std::numeric_limits<Float>::digits);\n      e -= std::numeric_limits<Float>::digits;\n#endif\n      number<Backend> num(f);\n      number<Backend> denom(1u);\n      if (e > 0)\n      {\n         num <<= e;\n      }\n      else if (e < 0)\n      {\n         denom <<= -e;\n      }\n      number<Backend> gcd;\n      eval_gcd(gcd.backend(), num.backend(), denom.backend());\n      if (!eval_eq(gcd.backend(), one()))\n      {\n         num /= gcd;\n         denom /= gcd;\n      }\n      this->num() = std::move(std::move(num).backend());\n      this->denom() = std::move(std::move(denom).backend());\n      return *this;\n   }\n\n   void swap(rational_adaptor& o)\n   {\n      m_num.swap(o.m_num);\n      m_denom.swap(o.m_denom);\n   }\n   std::string str(std::streamsize digits, std::ios_base::fmtflags f) const\n   {\n      using default_ops::eval_eq;\n      //\n      // We format the string ourselves so we can match what GMP's mpq type does:\n      //\n      std::string result = num().str(digits, f);\n      if (!eval_eq(denom(), one()))\n      {\n         result.append(1, '/');\n         result.append(denom().str(digits, f));\n      }\n      return result;\n   }\n   void negate()\n   {\n      m_num.negate();\n   }\n   int compare(const rational_adaptor& o) const\n   {\n      std::ptrdiff_t s1 = eval_get_sign(*this);\n      std::ptrdiff_t s2 = eval_get_sign(o);\n      if (s1 != s2)\n      {\n         return s1 < s2 ? -1 : 1;\n      }\n      else if (s1 == 0)\n         return 0; // both zero.\n\n      bool neg = false;\n      if (s1 >= 0)\n      {\n         s1 = eval_msb(num()) + eval_msb(o.denom());\n         s2 = eval_msb(o.num()) + eval_msb(denom());\n      }\n      else\n      {\n         Backend t(num());\n         t.negate();\n         s1 = eval_msb(t) + eval_msb(o.denom());\n         t = o.num();\n         t.negate();\n         s2 = eval_msb(t) + eval_msb(denom());\n         neg = true;\n      }\n      s1 -= s2;\n      if (s1 < -1)\n         return neg ? 1 : -1;\n      else if (s1 > 1)\n         return neg ? -1 : 1;\n\n      Backend t1, t2;\n      eval_multiply(t1, num(), o.denom());\n      eval_multiply(t2, o.num(), denom());\n      return t1.compare(t2);\n   }\n   //\n   // Comparison with arithmetic types, default just constructs a temporary:\n   //\n   template <class A>\n   typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A>::value, int>::type compare(A i) const\n   {\n      rational_adaptor t;\n      t = i;  //  Note: construct directly from i if supported.\n      return compare(t);\n   }\n\n   Backend& num() { return m_num; }\n   const Backend& num()const { return m_num; }\n   Backend& denom() { return m_denom; }\n   const Backend& denom()const { return m_denom; }\n\n   #ifndef BOOST_MP_STANDALONE\n   template <class Archive>\n   void serialize(Archive& ar, const std::integral_constant<bool, true>&)\n   {\n      // Saving\n      number<Backend> n(num()), d(denom());\n      ar& boost::make_nvp(\"numerator\", n);\n      ar& boost::make_nvp(\"denominator\", d);\n   }\n   template <class Archive>\n   void serialize(Archive& ar, const std::integral_constant<bool, false>&)\n   {\n      // Loading\n      number<Backend> n, d;\n      ar& boost::make_nvp(\"numerator\", n);\n      ar& boost::make_nvp(\"denominator\", d);\n      num() = n.backend();\n      denom() = d.backend();\n   }\n   template <class Archive>\n   void serialize(Archive& ar, const unsigned int /*version*/)\n   {\n      using tag = typename Archive::is_saving;\n      using saving_tag = std::integral_constant<bool, tag::value>;\n      serialize(ar, saving_tag());\n   }\n   #endif // BOOST_MP_STANDALONE\n   \n private:\n   Backend m_num, m_denom;\n};\n\n//\n// Helpers:\n//\ntemplate <class T>\ninline constexpr typename std::enable_if<std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_signed, bool>::type\nis_minus_one(const T&)\n{\n   return false;\n}\ntemplate <class T>\ninline constexpr typename std::enable_if<!std::numeric_limits<T>::is_specialized || std::numeric_limits<T>::is_signed, bool>::type\nis_minus_one(const T& val)\n{\n   return val == -1;\n}\n\n//\n// Required non-members:\n//\ntemplate <class Backend> \ninline void eval_add(rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   eval_add_subtract_imp(a, a, b, true);\n}\ntemplate <class Backend> \ninline void eval_subtract(rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   eval_add_subtract_imp(a, a, b, false);\n}\n\ntemplate <class Backend> \ninline void eval_multiply(rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   eval_multiply_imp(a, a, b.num(), b.denom());\n}\n\ntemplate <class Backend> \nvoid eval_divide(rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   using default_ops::eval_divide;\n   rational_adaptor<Backend> t;\n   eval_divide(t, a, b);\n   a = std::move(t);\n}\n//\n// Conversions:\n//\ntemplate <class R, class IntBackend>\ninline typename std::enable_if<number_category<R>::value == number_kind_floating_point>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)\n{\n   //\n   // The generic conversion is as good as anything we can write here:\n   //\n   ::boost::multiprecision::detail::generic_convert_rational_to_float(*result, backend);\n}\n\ntemplate <class R, class IntBackend>\ninline typename std::enable_if<(number_category<R>::value != number_kind_integer) && (number_category<R>::value != number_kind_floating_point) && !std::is_enum<R>::value>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)\n{\n   using default_ops::eval_convert_to;\n   R d;\n   eval_convert_to(result, backend.num());\n   eval_convert_to(&d, backend.denom());\n   *result /= d;\n}\n\ntemplate <class R, class Backend>\ninline typename std::enable_if<number_category<R>::value == number_kind_integer>::type eval_convert_to(R* result, const rational_adaptor<Backend>& backend)\n{\n   using default_ops::eval_divide;\n   using default_ops::eval_convert_to;\n   Backend t;\n   eval_divide(t, backend.num(), backend.denom());\n   eval_convert_to(result, t);\n}\n\n//\n// Hashing support, not strictly required, but it is used in our tests:\n//\ntemplate <class Backend>\ninline std::size_t hash_value(const rational_adaptor<Backend>& arg)\n{\n   std::size_t result = hash_value(arg.num());\n   std::size_t result2 = hash_value(arg.denom());\n   boost::multiprecision::detail::hash_combine(result, result2);\n   return result;\n}\n//\n// assign_components:\n//\ntemplate <class Backend>\nvoid assign_components(rational_adaptor<Backend>& result, Backend const& a, Backend const& b)\n{\n   using default_ops::eval_gcd;\n   using default_ops::eval_divide;\n   using default_ops::eval_eq;\n\n   Backend g;\n   eval_gcd(g, a, b);\n   if (eval_eq(g, rational_adaptor<Backend>::one()))\n   {\n      result.num() = a;\n      result.denom() = b;\n   }\n   else\n   {\n      eval_divide(result.num(), a, g);\n      eval_divide(result.denom(), b, g);\n   }\n}\n//\n// Again for arithmetic types, overload for whatever arithmetic types are directly supported:\n//\ntemplate <class Backend, class Arithmetic1, class Arithmetic2>\ninline void assign_components(rational_adaptor<Backend>& result, const Arithmetic1& a, const Arithmetic2& b)\n{\n   using default_ops::eval_gcd;\n   using default_ops::eval_divide;\n   using default_ops::eval_eq;\n\n   Backend g;\n   result.num()   = a;\n   eval_gcd(g, result.num(), b);\n   if (eval_eq(g, rational_adaptor<Backend>::one()))\n   {\n      result.denom() = b;\n   }\n   else\n   {\n      eval_divide(result.num(), g);\n      eval_divide(result.denom(), b, g);\n   }\n}\n//\n// Optional comparison operators:\n//\ntemplate <class Backend>\ninline bool eval_is_zero(const rational_adaptor<Backend>& arg)\n{\n   using default_ops::eval_is_zero;\n   return eval_is_zero(arg.num());\n}\n\ntemplate <class Backend>\ninline int eval_get_sign(const rational_adaptor<Backend>& arg)\n{\n   using default_ops::eval_get_sign;\n   return eval_get_sign(arg.num());\n}\n\ntemplate <class Backend>\ninline bool eval_eq(const rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   using default_ops::eval_eq;\n   return eval_eq(a.num(), b.num()) && eval_eq(a.denom(), b.denom());\n}\n\ntemplate <class Backend, class Arithmetic>\ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value&& std::is_integral<Arithmetic>::value, bool>::type \n   eval_eq(const rational_adaptor<Backend>& a, Arithmetic b)\n{\n   using default_ops::eval_eq;\n   return eval_eq(a.denom(), rational_adaptor<Backend>::one()) && eval_eq(a.num(), b);\n}\n\ntemplate <class Backend, class Arithmetic>\ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value&& std::is_integral<Arithmetic>::value, bool>::type \n   eval_eq(Arithmetic b, const rational_adaptor<Backend>& a)\n{\n   using default_ops::eval_eq;\n   return eval_eq(a.denom(), rational_adaptor<Backend>::one()) && eval_eq(a.num(), b);\n}\n\n//\n// Arithmetic operations, starting with addition:\n//\ntemplate <class Backend, class Arithmetic> \nvoid eval_add_subtract_imp(rational_adaptor<Backend>& result, const Arithmetic& arg, bool isaddition)\n{\n   using default_ops::eval_multiply;\n   using default_ops::eval_divide;\n   using default_ops::eval_add;\n   using default_ops::eval_gcd;\n   Backend t;\n   eval_multiply(t, result.denom(), arg);\n   if (isaddition)\n      eval_add(result.num(), t);\n   else\n      eval_subtract(result.num(), t);\n   //\n   // There is no need to re-normalize here, we have \n   // (a + bm) / b\n   // and gcd(a + bm, b) = gcd(a, b) = 1\n   //\n   /*\n   eval_gcd(t, result.num(), result.denom());\n   if (!eval_eq(t, rational_adaptor<Backend>::one()) != 0)\n   {\n      Backend t2;\n      eval_divide(t2, result.num(), t);\n      t2.swap(result.num());\n      eval_divide(t2, result.denom(), t);\n      t2.swap(result.denom());\n   }\n   */\n}\n\ntemplate <class Backend, class Arithmetic> \ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_add(rational_adaptor<Backend>& result, const Arithmetic& arg)\n{\n   eval_add_subtract_imp(result, arg, true);\n}\n\ntemplate <class Backend, class Arithmetic> \ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_subtract(rational_adaptor<Backend>& result, const Arithmetic& arg)\n{\n   eval_add_subtract_imp(result, arg, false);\n}\n\ntemplate <class Backend>\nvoid eval_add_subtract_imp(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b, bool isaddition)\n{\n   using default_ops::eval_eq;\n   using default_ops::eval_multiply;\n   using default_ops::eval_divide;\n   using default_ops::eval_add;\n   using default_ops::eval_subtract;\n   //\n   // Let  a = an/ad\n   //      b = bn/bd\n   //      g = gcd(ad, bd)\n   // result = rn/rd\n   //\n   // Then:\n   // rn = an * (bd/g) + bn * (ad/g)\n   // rd = ad * (bd/g)\n   //    = (ad/g) * (bd/g) * g\n   //\n   // And the whole thing can then be rescaled by\n   //      gcd(rn, g)\n   //\n   Backend gcd, t1, t2, t3, t4;\n   //\n   // Begin by getting the gcd of the 2 denominators:\n   //\n   eval_gcd(gcd, a.denom(), b.denom());\n   //\n   // Do we have gcd > 1:\n   //\n   if (!eval_eq(gcd, rational_adaptor<Backend>::one()))\n   {\n      //\n      // Scale the denominators by gcd, and put the results in t1 and t2:\n      //\n      eval_divide(t1, b.denom(), gcd);\n      eval_divide(t2, a.denom(), gcd);\n      //\n      // multiply the numerators by the scale denominators and put the results in t3, t4:\n      //\n      eval_multiply(t3, a.num(), t1);\n      eval_multiply(t4, b.num(), t2);\n      //\n      // Add them up:\n      //\n      if (isaddition)\n         eval_add(t3, t4);\n      else\n         eval_subtract(t3, t4);\n      //\n      // Get the gcd of gcd and our numerator (t3):\n      //\n      eval_gcd(t4, t3, gcd);\n      if (eval_eq(t4, rational_adaptor<Backend>::one()))\n      {\n         result.num() = t3;\n         eval_multiply(result.denom(), t1, a.denom());\n      }\n      else\n      {\n         //\n         // Uncommon case where gcd is not 1, divide the numerator\n         // and the denominator terms by the new gcd.  Note we perform division\n         // on the existing gcd value as this is the smallest of the 3 denominator\n         // terms we'll be multiplying together, so there's a good chance it's a\n         // single limb value already:\n         //\n         eval_divide(result.num(), t3, t4);\n         eval_divide(t3, gcd, t4);\n         eval_multiply(t4, t1, t2);\n         eval_multiply(result.denom(), t4, t3);\n      }\n   }\n   else\n   {\n      //\n      // Most common case (approx 60%) where gcd is one:\n      //\n      eval_multiply(t1, a.num(), b.denom());\n      eval_multiply(t2, a.denom(), b.num());\n      if (isaddition)\n         eval_add(result.num(), t1, t2);\n      else\n         eval_subtract(result.num(), t1, t2);\n      eval_multiply(result.denom(), a.denom(), b.denom());\n   }\n}\n\n\ntemplate <class Backend>\ninline void eval_add(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   eval_add_subtract_imp(result, a, b, true);\n}\ntemplate <class Backend>\ninline void eval_subtract(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   eval_add_subtract_imp(result, a, b, false);\n}\n\ntemplate <class Backend, class Arithmetic>\nvoid eval_add_subtract_imp(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const Arithmetic& b, bool isaddition)\n{\n   using default_ops::eval_add;\n   using default_ops::eval_subtract;\n   using default_ops::eval_multiply;\n\n   if (&result == &a)\n      return eval_add_subtract_imp(result, b, isaddition);\n\n   eval_multiply(result.num(), a.denom(), b);\n   if (isaddition)\n      eval_add(result.num(), a.num());\n   else\n      BOOST_IF_CONSTEXPR(std::numeric_limits<Backend>::is_signed == false)\n   {\n      Backend t;\n      eval_subtract(t, a.num(), result.num());\n      result.num() = std::move(t);\n   }\n   else\n   {\n      eval_subtract(result.num(), a.num());\n      result.negate();\n   }\n   result.denom() = a.denom();\n   //\n   // There is no need to re-normalize here, we have \n   // (a + bm) / b\n   // and gcd(a + bm, b) = gcd(a, b) = 1\n   //\n}\ntemplate <class Backend, class Arithmetic>\ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_add(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const Arithmetic& b)\n{\n   eval_add_subtract_imp(result, a, b, true);\n}\ntemplate <class Backend, class Arithmetic>\ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_subtract(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const Arithmetic& b)\n{\n   eval_add_subtract_imp(result, a, b, false);\n}\n\n//\n// Multiplication:\n//\ntemplate <class Backend> \nvoid eval_multiply_imp(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const Backend& b_num, const Backend& b_denom)\n{\n   using default_ops::eval_multiply;\n   using default_ops::eval_divide;\n   using default_ops::eval_gcd;\n   using default_ops::eval_get_sign;\n   using default_ops::eval_eq;\n\n   Backend gcd_left, gcd_right, t1, t2;\n   eval_gcd(gcd_left, a.num(), b_denom);\n   eval_gcd(gcd_right, b_num, a.denom());\n   //\n   // Unit gcd's are the most likely case:\n   //\n   bool b_left = eval_eq(gcd_left, rational_adaptor<Backend>::one());\n   bool b_right = eval_eq(gcd_right, rational_adaptor<Backend>::one());\n\n   if (b_left && b_right)\n   {\n      eval_multiply(result.num(), a.num(), b_num);\n      eval_multiply(result.denom(), a.denom(), b_denom);\n   }\n   else if (b_left)\n   {\n      eval_divide(t2, b_num, gcd_right);\n      eval_multiply(result.num(), a.num(), t2);\n      eval_divide(t1, a.denom(), gcd_right);\n      eval_multiply(result.denom(), t1, b_denom);\n   }\n   else if (b_right)\n   {\n      eval_divide(t1, a.num(), gcd_left);\n      eval_multiply(result.num(), t1, b_num);\n      eval_divide(t2, b_denom, gcd_left);\n      eval_multiply(result.denom(), a.denom(), t2);\n   }\n   else\n   {\n      eval_divide(t1, a.num(), gcd_left);\n      eval_divide(t2, b_num, gcd_right);\n      eval_multiply(result.num(), t1, t2);\n      eval_divide(t1, a.denom(), gcd_right);\n      eval_divide(t2, b_denom, gcd_left);\n      eval_multiply(result.denom(), t1, t2);\n   }\n   //\n   // We may have b_denom negative if this is actually division, if so just correct things now:\n   //\n   if (eval_get_sign(b_denom) < 0)\n   {\n      result.num().negate();\n      result.denom().negate();\n   }\n}\n\ntemplate <class Backend> \nvoid eval_multiply(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   using default_ops::eval_multiply;\n\n   if (&a == &b)\n   {\n      // squaring, gcd's are 1:\n      eval_multiply(result.num(), a.num(), b.num());\n      eval_multiply(result.denom(), a.denom(), b.denom());\n      return;\n   }\n   eval_multiply_imp(result, a, b.num(), b.denom());\n}\n\ntemplate <class Backend, class Arithmetic> \nvoid eval_multiply_imp(Backend& result_num, Backend& result_denom, Arithmetic arg)\n{\n   if (arg == 0)\n   {\n      result_num = rational_adaptor<Backend>::zero();\n      result_denom = rational_adaptor<Backend>::one();\n      return;\n   }\n   else if (arg == 1)\n      return;\n\n   using default_ops::eval_multiply;\n   using default_ops::eval_divide;\n   using default_ops::eval_gcd;\n   using default_ops::eval_convert_to;\n\n   Backend gcd, t;\n   Arithmetic integer_gcd;\n   eval_gcd(gcd, result_denom, arg);\n   eval_convert_to(&integer_gcd, gcd);\n   arg /= integer_gcd;\n   if (boost::multiprecision::detail::unsigned_abs(arg) > 1)\n   {\n      eval_multiply(t, result_num, arg);\n      result_num = std::move(t);\n   }\n   else if (is_minus_one(arg))\n      result_num.negate();\n   if (integer_gcd > 1)\n   {\n      eval_divide(t, result_denom, integer_gcd);\n      result_denom = std::move(t);\n   }\n}\ntemplate <class Backend> \nvoid eval_multiply_imp(Backend& result_num, Backend& result_denom, Backend arg)\n{\n   using default_ops::eval_multiply;\n   using default_ops::eval_divide;\n   using default_ops::eval_gcd;\n   using default_ops::eval_convert_to;\n   using default_ops::eval_is_zero;\n   using default_ops::eval_eq;\n   using default_ops::eval_get_sign;\n\n   if (eval_is_zero(arg))\n   {\n      result_num = rational_adaptor<Backend>::zero();\n      result_denom = rational_adaptor<Backend>::one();\n      return;\n   }\n   else if (eval_eq(arg, rational_adaptor<Backend>::one()))\n      return;\n\n   Backend gcd, t;\n   eval_gcd(gcd, result_denom, arg);\n   if (!eval_eq(gcd, rational_adaptor<Backend>::one()))\n   {\n      eval_divide(t, arg, gcd);\n      arg = t;\n   }\n   else\n      t = arg;\n   if (eval_get_sign(arg) < 0)\n      t.negate();\n\n   if (!eval_eq(t, rational_adaptor<Backend>::one()))\n   {\n      eval_multiply(t, result_num, arg);\n      result_num = std::move(t);\n   }\n   else if (eval_get_sign(arg) < 0)\n      result_num.negate();\n   if (!eval_eq(gcd, rational_adaptor<Backend>::one()))\n   {\n      eval_divide(t, result_denom, gcd);\n      result_denom = std::move(t);\n   }\n}\n\ntemplate <class Backend, class Arithmetic> \ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_multiply(rational_adaptor<Backend>& result, const Arithmetic& arg)\n{\n   eval_multiply_imp(result.num(), result.denom(), arg);\n}\n\ntemplate <class Backend, class Arithmetic> \ntypename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && std::is_integral<Arithmetic>::value>::type\n   eval_multiply_imp(rational_adaptor<Backend>& result, const Backend& a_num, const Backend& a_denom, Arithmetic b)\n{\n   if (b == 0)\n   {\n      result.num() = rational_adaptor<Backend>::zero();\n      result.denom() = rational_adaptor<Backend>::one();\n      return;\n   }\n   else if (b == 1)\n   {\n      result.num() = a_num;\n      result.denom() = a_denom;\n      return;\n   }\n\n   using default_ops::eval_multiply;\n   using default_ops::eval_divide;\n   using default_ops::eval_gcd;\n   using default_ops::eval_convert_to;\n\n   Backend gcd;\n   Arithmetic integer_gcd;\n   eval_gcd(gcd, a_denom, b);\n   eval_convert_to(&integer_gcd, gcd);\n   b /= integer_gcd;\n   if (boost::multiprecision::detail::unsigned_abs(b) > 1)\n      eval_multiply(result.num(), a_num, b);\n   else if (is_minus_one(b))\n   {\n      result.num() = a_num;\n      result.num().negate();\n   }\n   else\n      result.num() = a_num;\n   if (integer_gcd > 1)\n      eval_divide(result.denom(), a_denom, integer_gcd);\n   else\n      result.denom() = a_denom;\n}\ntemplate <class Backend> \ninline void eval_multiply_imp(rational_adaptor<Backend>& result, const Backend& a_num, const Backend& a_denom, const Backend& b)\n{\n   result.num() = a_num;\n   result.denom() = a_denom;\n   eval_multiply_imp(result.num(), result.denom(), b);\n}\n\ntemplate <class Backend, class Arithmetic> \ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_multiply(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const Arithmetic& b)\n{\n   if (&result == &a)\n      return eval_multiply(result, b);\n\n   eval_multiply_imp(result, a.num(), a.denom(), b);\n}\n\ntemplate <class Backend, class Arithmetic> \ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_multiply(rational_adaptor<Backend>& result, const Arithmetic& b, const rational_adaptor<Backend>& a)\n{\n   return eval_multiply(result, a, b);\n}\n\n//\n// Division:\n//\ntemplate <class Backend>\ninline void eval_divide(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, const rational_adaptor<Backend>& b)\n{\n   using default_ops::eval_multiply;\n   using default_ops::eval_get_sign;\n\n   if (eval_get_sign(b.num()) == 0)\n   {\n      BOOST_MP_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n      return;\n   }\n   if (&a == &b)\n   {\n      // Huh? Really?\n      result.num() = result.denom() = rational_adaptor<Backend>::one();\n      return;\n   }\n   if (&result == &b)\n   {\n      rational_adaptor<Backend> t(b);\n      return eval_divide(result, a, t);\n   }\n   eval_multiply_imp(result, a, b.denom(), b.num());\n}\n\ntemplate <class Backend, class Arithmetic> \ninline typename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && (std::is_integral<Arithmetic>::value || std::is_same<Arithmetic, Backend>::value)>::type\n   eval_divide(rational_adaptor<Backend>& result, const Arithmetic& b, const rational_adaptor<Backend>& a)\n{\n   using default_ops::eval_get_sign;\n\n   if (eval_get_sign(a.num()) == 0)\n   {\n      BOOST_MP_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n      return;\n   }\n   if (&a == &result)\n   {\n      eval_multiply_imp(result.denom(), result.num(), b);\n      result.num().swap(result.denom());\n   }\n   else\n      eval_multiply_imp(result, a.denom(), a.num(), b);\n\n   if (eval_get_sign(result.denom()) < 0)\n   {\n      result.num().negate();\n      result.denom().negate();\n   }\n}\n\ntemplate <class Backend, class Arithmetic>\ntypename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && std::is_integral<Arithmetic>::value>::type\neval_divide(rational_adaptor<Backend>& result, Arithmetic arg)\n{\n   if (arg == 0)\n   {\n      BOOST_MP_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n      return;\n   }\n   else if (arg == 1)\n      return;\n   else if (is_minus_one(arg))\n   {\n      result.negate();\n      return;\n   }\n   if (eval_get_sign(result) == 0)\n   {\n      return;\n   }\n\n\n   using default_ops::eval_multiply;\n   using default_ops::eval_gcd;\n   using default_ops::eval_convert_to;\n   using default_ops::eval_divide;\n\n   Backend gcd, t;\n   Arithmetic integer_gcd;\n   eval_gcd(gcd, result.num(), arg);\n   eval_convert_to(&integer_gcd, gcd);\n   arg /= integer_gcd;\n\n   eval_multiply(t, result.denom(), boost::multiprecision::detail::unsigned_abs(arg));\n   result.denom() = std::move(t);\n   if (arg < 0)\n   {\n      result.num().negate();\n   }\n   if (integer_gcd > 1)\n   {\n      eval_divide(t, result.num(), integer_gcd);\n      result.num() = std::move(t);\n   }\n}\ntemplate <class Backend>\nvoid eval_divide(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, Backend arg)\n{\n   using default_ops::eval_multiply;\n   using default_ops::eval_gcd;\n   using default_ops::eval_convert_to;\n   using default_ops::eval_divide;\n   using default_ops::eval_is_zero;\n   using default_ops::eval_eq;\n   using default_ops::eval_get_sign;\n\n   if (eval_is_zero(arg))\n   {\n      BOOST_MP_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n      return;\n   }\n   else if (eval_eq(a, rational_adaptor<Backend>::one()) || (eval_get_sign(a) == 0))\n   {\n      if (&result != &a)\n         result = a;\n      return;\n   }\n\n   Backend gcd, u_arg, t;\n   eval_gcd(gcd, a.num(), arg);\n   bool has_unit_gcd = eval_eq(gcd, rational_adaptor<Backend>::one());\n   if (!has_unit_gcd)\n   {\n      eval_divide(u_arg, arg, gcd);\n      arg = u_arg;\n   }\n   else\n      u_arg = arg;\n   if (eval_get_sign(u_arg) < 0)\n      u_arg.negate();\n\n   eval_multiply(t, a.denom(), u_arg);\n   result.denom() = std::move(t);\n   \n   if (!has_unit_gcd)\n   {\n      eval_divide(t, a.num(), gcd);\n      result.num() = std::move(t);\n   }\n   else if (&result != &a)\n      result.num() = a.num();\n\n   if (eval_get_sign(arg) < 0)\n   {\n      result.num().negate();\n   }\n}\ntemplate <class Backend>\nvoid eval_divide(rational_adaptor<Backend>& result, Backend arg)\n{\n   eval_divide(result, result, arg);\n}\n\ntemplate <class Backend, class Arithmetic>\ntypename std::enable_if<std::is_convertible<Arithmetic, Backend>::value && std::is_integral<Arithmetic>::value>::type\n   eval_divide(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& a, Arithmetic arg)\n{\n   if (&result == &a)\n      return eval_divide(result, arg);\n   if (arg == 0)\n   {\n      BOOST_MP_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n      return;\n   }\n   else if (arg == 1)\n   {\n      result = a;\n      return;\n   }\n   else if (is_minus_one(arg))\n   {\n      result = a;\n      result.num().negate();\n      return;\n   }\n\n   if (eval_get_sign(a) == 0)\n   {\n      result = a;\n      return;\n   }\n\n   using default_ops::eval_multiply;\n   using default_ops::eval_divide;\n   using default_ops::eval_gcd;\n   using default_ops::eval_convert_to;\n\n   Backend gcd;\n   Arithmetic integer_gcd;\n   eval_gcd(gcd, a.num(), arg);\n   eval_convert_to(&integer_gcd, gcd);\n   arg /= integer_gcd;\n   eval_multiply(result.denom(), a.denom(), boost::multiprecision::detail::unsigned_abs(arg));\n\n   if (integer_gcd > 1)\n   {\n      eval_divide(result.num(), a.num(), integer_gcd);\n   }\n   else\n      result.num() = a.num();\n   if (arg < 0)\n   {\n      result.num().negate();\n   }\n}\n\n//\n// Increment and decrement:\n//\ntemplate <class Backend> \ninline void eval_increment(rational_adaptor<Backend>& arg)\n{\n   using default_ops::eval_add;\n   eval_add(arg.num(), arg.denom());\n}\ntemplate <class Backend> \ninline void eval_decrement(rational_adaptor<Backend>& arg)\n{\n   using default_ops::eval_subtract;\n   eval_subtract(arg.num(), arg.denom());\n}\n\n//\n// abs:\n//\ntemplate <class Backend> \ninline void eval_abs(rational_adaptor<Backend>& result, const rational_adaptor<Backend>& arg)\n{\n   using default_ops::eval_abs;\n   eval_abs(result.num(), arg.num());\n   result.denom() = arg.denom();\n}\n\n} // namespace backends\n\n//\n// Import the backend into this namespace:\n//\nusing boost::multiprecision::backends::rational_adaptor;\n//\n// Define a category for this number type, one of:\n// \n//    number_kind_integer\n//    number_kind_floating_point\n//    number_kind_rational\n//    number_kind_fixed_point\n//    number_kind_complex\n//\ntemplate<class Backend>\nstruct number_category<rational_adaptor<Backend> > : public std::integral_constant<int, number_kind_rational>\n{};\n\ntemplate <class IntBackend>\nstruct expression_template_default<backends::rational_adaptor<IntBackend> > : public expression_template_default<IntBackend>\n{};\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\nstruct component_type<number<rational_adaptor<Backend>, ExpressionTemplates> >\n{\n   typedef number<Backend, ExpressionTemplates> type;\n};\n\ntemplate <class IntBackend, expression_template_option ET>\ninline number<IntBackend, ET> numerator(const number<rational_adaptor<IntBackend>, ET>& val)\n{\n   return val.backend().num();\n}\ntemplate <class IntBackend, expression_template_option ET>\ninline number<IntBackend, ET> denominator(const number<rational_adaptor<IntBackend>, ET>& val)\n{\n   return val.backend().denom();\n}\n\ntemplate <class Backend>\nstruct is_unsigned_number<rational_adaptor<Backend> > : public is_unsigned_number<Backend>\n{};\n\n\n}} // namespace boost::multiprecision\n\nnamespace std {\n\n   template <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>\n   class numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> > : public std::numeric_limits<boost::multiprecision::number<IntBackend, ExpressionTemplates> >\n   {\n      using base_type = std::numeric_limits<boost::multiprecision::number<IntBackend> >;\n      using number_type = boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend> >;\n\n   public:\n      static constexpr bool is_integer = false;\n      static constexpr bool is_exact = true;\n      static constexpr      number_type(min)() { return (base_type::min)(); }\n      static constexpr      number_type(max)() { return (base_type::max)(); }\n      static constexpr number_type lowest() { return -(max)(); }\n      static constexpr number_type epsilon() { return base_type::epsilon(); }\n      static constexpr number_type round_error() { return epsilon() / 2; }\n      static constexpr number_type infinity() { return base_type::infinity(); }\n      static constexpr number_type quiet_NaN() { return base_type::quiet_NaN(); }\n      static constexpr number_type signaling_NaN() { return base_type::signaling_NaN(); }\n      static constexpr number_type denorm_min() { return base_type::denorm_min(); }\n   };\n\n   template <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>\n   constexpr bool numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> >::is_integer;\n   template <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>\n   constexpr bool numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> >::is_exact;\n\n} // namespace std\n\n#endif\n", "meta": {"hexsha": "efe8cd8406d55c83a40522f4029f29346a01b61c", "size": 37981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/multiprecision/rational_adaptor.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/rational_adaptor.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/rational_adaptor.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": 30.7538461538, "max_line_length": 248, "alphanum_fraction": 0.6505621232, "num_tokens": 10006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881208232718, "lm_q2_score": 0.051082737318206645, "lm_q1q2_score": 0.025142316487156948}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_UNITS_CODATA_DEUTERON_CONSTANTS_HPP\r\n#define BOOST_UNITS_CODATA_DEUTERON_CONSTANTS_HPP\r\n\r\n#include <boost/units/static_constant.hpp>\r\n\r\n#include <boost/units/systems/detail/constants.hpp>\r\n#include <boost/units/systems/si/amount.hpp>\r\n#include <boost/units/systems/si/area.hpp>\r\n#include <boost/units/systems/si/electric_charge.hpp>\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/frequency.hpp>\r\n#include <boost/units/systems/si/length.hpp>\r\n#include <boost/units/systems/si/mass.hpp>\r\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\r\n#include <boost/units/systems/si/time.hpp>\r\n#include <boost/units/systems/si/wavenumber.hpp>\r\n\r\n#include <boost/units/systems/si/codata/typedefs.hpp>\r\n\r\n/// \\file\r\n/// CODATA recommended values of fundamental atomic and nuclear constants\r\n/// CODATA 2006 values as of 2007/03/30\r\n\r\nnamespace boost {\r\n\r\nnamespace units { \r\n\r\nnamespace si {\r\n                            \r\nnamespace constants {\r\n\r\nnamespace codata {\r\n\r\n/// CODATA recommended values of the fundamental physical constants: NIST SP 961\r\n\r\n/// deuteron mass\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_d,quantity<mass>,3.34358320e-27*kilograms,1.7e-34*kilograms);\r\n/// deuteron-electron mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_d_over_m_e,quantity<dimensionless>,3670.4829654*dimensionless(),1.6e-6*dimensionless());\r\n/// deuteron-proton mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_d_over_m_p,quantity<dimensionless>,1.99900750108*dimensionless(),2.2e-10*dimensionless());\r\n/// deuteron molar mass\r\nBOOST_UNITS_PHYSICAL_CONSTANT(M_d,quantity<mass_over_amount>,2.013553212724e-3*kilograms/mole,7.8e-14*kilograms/mole);\r\n/// deuteron rms charge radius\r\nBOOST_UNITS_PHYSICAL_CONSTANT(R_d,quantity<length>,2.1402e-15*meters,2.8e-18*meters);\r\n/// deuteron magnetic moment\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_d,quantity<energy_over_magnetic_flux_density>,0.433073465e-26*joules/tesla,1.1e-34*joules/tesla);\r\n/// deuteron-Bohr magneton ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_d_over_mu_B,quantity<dimensionless>,0.4669754556e-3*dimensionless(),3.9e-12*dimensionless());\r\n/// deuteron-nuclear magneton ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_d_over_mu_N,quantity<dimensionless>,0.8574382308*dimensionless(),7.2e-9*dimensionless());\r\n/// deuteron g-factor\r\nBOOST_UNITS_PHYSICAL_CONSTANT(g_d,quantity<dimensionless>,0.8574382308*dimensionless(),7.2e-9*dimensionless());\r\n/// deuteron-electron magnetic moment ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_d_over_mu_e,quantity<dimensionless>,-4.664345537e-4*dimensionless(),3.9e-12*dimensionless());\r\n/// deuteron-proton magnetic moment ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_d_over_mu_p,quantity<dimensionless>,0.3070122070*dimensionless(),2.4e-9*dimensionless());\r\n/// deuteron-neutron magnetic moment ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_d_over_mu_n,quantity<dimensionless>,-0.44820652*dimensionless(),1.1e-7*dimensionless());\r\n\r\n} // namespace codata\r\n\r\n} // namespace constants    \r\n\r\n} // namespace si\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_UNITS_CODATA_DEUTERON_CONSTANTS_HPP\r\n", "meta": {"hexsha": "81f5d3241d0ab05153753bcb6b8b8d997f13579c", "size": 3480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/units/systems/si/codata/deuteron_constants.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/units/systems/si/codata/deuteron_constants.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/units/systems/si/codata/deuteron_constants.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 42.4390243902, "max_line_length": 131, "alphanum_fraction": 0.7775862069, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.06656919313716142, "lm_q1q2_score": 0.025132576765901332}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n#include <votca/xtp/aomatrix.h>\n#include <votca/xtp/bsecoupling.h>\n#include <votca/tools/constants.h>\n#include <boost/format.hpp>\n\n\nnamespace votca { namespace xtp {\n\nusing boost::format;\nusing namespace tools;\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     \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        _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\nvoid BSECoupling::WriteToProperty(const Orbitals& orbitalsA, const Orbitals& orbitalsB, \n                        Property& summary, const QMState& stateA, const QMState& stateB){\n  Property &coupling_summary = summary.add(\"coupling\",\"\"); \n  double energyA =0; \n   double energyB =0; \n  double JAB_pert=0;\n  double JAB_diag=0;\n  if(stateA.Type()==QMStateType::Singlet){\n      energyA=orbitalsA.BSESingletEnergies()(stateA.Index())*conv::hrt2ev;\n      energyB=orbitalsB.BSESingletEnergies()(stateB.Index())*conv::hrt2ev;\n      JAB_pert=getSingletCouplingElement(stateA.Index(),stateB.Index(),0);\n      JAB_diag=getSingletCouplingElement(stateA.Index(),stateB.Index(),1);\n  }else if(stateA.Type()==QMStateType::Triplet){\n      energyA=orbitalsA.BSETripletEnergies()(stateA.Index())*conv::hrt2ev;\n      energyB=orbitalsB.BSETripletEnergies()(stateB.Index())*conv::hrt2ev;\n      JAB_pert=getTripletCouplingElement(stateA.Index(),stateB.Index(),0);\n      JAB_diag=getTripletCouplingElement(stateA.Index(),stateB.Index(),1);\n  }\n  coupling_summary.setAttribute(\"stateA\", stateA.ToString());\n  coupling_summary.setAttribute(\"stateB\", stateB.ToString());\n  coupling_summary.setAttribute(\"eA\", (format(\"%1$1.6e\") % energyA).str());\n  coupling_summary.setAttribute(\"eB\", (format(\"%1$1.6e\") % energyB).str());\n  coupling_summary.setAttribute(\"j_pert\", (format(\"%1$1.6e\") % JAB_pert).str());\n  coupling_summary.setAttribute(\"j_diag\", (format(\"%1$1.6e\") % JAB_diag).str());\n}\n\nvoid BSECoupling::Addoutput(Property &type_summary,const Orbitals& orbitalsA, \n                               const Orbitals& orbitalsB){\n    tools::Property& bsecoupling= type_summary.add(Identify(),\"\");\n    string algorithm=\"j_diag\";\n    if (_output_perturbation){\n        algorithm=\"j_pert\";\n    }\n    if (_doSinglets){\n        QMStateType singlet=QMStateType(QMStateType::Singlet);\n        Property &singlet_summary = bsecoupling.add(singlet.ToLongString(),\"\");\n        singlet_summary.setAttribute(\"algorithm\",algorithm);\n        for (int stateA = 0; stateA < _levA ; ++stateA ) {\n             QMState qmstateA=QMState(singlet,stateA,false);\n           for (int stateB = 0; stateB <_levB ; ++stateB ) {             \n               QMState qmstateB=QMState(singlet,stateB,false);\n               WriteToProperty(orbitalsA, orbitalsB, singlet_summary, qmstateA, qmstateB);    \n           } \n        }\n    }\n     \n    if ( _doTriplets){\n        QMStateType triplet=QMStateType(QMStateType::Triplet);\n        Property &triplet_summary = bsecoupling.add(triplet.ToLongString(),\"\");\n        triplet_summary.setAttribute(\"algorithm\",algorithm);\n        for (int stateA = 0; stateA < _levA ; ++stateA ) {\n               QMState qmstateA=QMState(triplet,stateA,false);\n           for (int stateB = 0; stateB <_levB ; ++stateB ) {             \n               QMState qmstateB=QMState(triplet,stateB,false);\n               WriteToProperty(orbitalsA, orbitalsB, triplet_summary, qmstateA, qmstateB);           \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    return JAB_triplet[methodindex]( levelA  , levelB + _levA ) * votca::tools::conv::hrt2ev;\n}\n\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 */\nvoid BSECoupling::CalculateCouplings(const Orbitals& orbitalsA, const Orbitals& orbitalsB, Orbitals& orbitalsAB) {\n       CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"  Calculating exciton couplings\" << flush;\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    CheckAtomCoordinates(orbitalsA, orbitalsB, orbitalsAB);\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        throw std::runtime_error(\"Basis set size is not stored in monomers\");\n    }\n\n    // number of levels stored in monomers\n    int levelsA = orbitalsA.getNumberOfLevels();\n    int levelsB = orbitalsB.getNumberOfLevels();\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().cols();\n    int _bseA_triplet_exc = orbitalsA.BSETripletCoefficients().cols();\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    Eigen::MatrixXi 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().cols();\n    int _bseB_triplet_exc = orbitalsB.BSETripletCoefficients().cols();\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    Eigen::MatrixXi 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    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    // 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_triplet() && _doTriplets){\n       throw std::runtime_error( \"BSE EH for triplets not stored \" );\n    }\n    if ( ! orbitalsAB.hasEHinteraction_singlet() && _doSinglets){\n       throw std::runtime_error( \"BSE EH for singlets not stored \" );\n    }\n    const MatrixXfd&    eh_t = orbitalsAB.eh_t(); \n    const MatrixXfd&    eh_s = orbitalsAB.eh_s(); \n    if(_doTriplets){\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   dimer AB has BSE EH interaction triplet with dimension \" << eh_t.rows() << \" x \" <<  eh_t.cols() << flush;\n    }\n    if(_doSinglets){\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   dimer AB has BSE EH interaction singlet with dimension \" << eh_s.rows() << \" x \" <<  eh_s.cols() << flush;\n    }\n    // now, two storage assignment matrices for two-particle functions\n    Eigen::MatrixXi 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) = _bseAB_vmin + _v;\n            combAB(cnt,1) = _bseAB_vmin + _bseAB_vtotal + _c;\n            cnt++;\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    if ( ( levelsA == 0 ) || (levelsB == 0) ) {\n        throw std::runtime_error(\"No information about number of occupied/unoccupied levels is stored\" );\n    } \n    \n    //       | Orbitals_A          0 |      | Overlap_A |     \n    //       | 0          Orbitals_B |.T  X   | Overlap_B |  X  ( Orbitals_AB )\n    \n    Eigen::MatrixXd psi_AxB =Eigen::MatrixXd::Zero( levelsA + levelsB, basisA + basisB  );\n    // constructing merged orbitals\n    psi_AxB.block(0,0,levelsA , basisA) = orbitalsA.MOCoefficients().block(_bseA_vmin,0, _bseA_cmax+1-_bseA_vmin, basisA );\n    psi_AxB.block(levelsA, basisA,levelsB,basisB) =orbitalsB.MOCoefficients().block(_bseB_vmin,0,_bseB_cmax+1-_bseA_vmin,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    Eigen::MatrixXd 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        overlapAB=CalculateOverlapMatrix(orbitalsAB);\n    }\n  \n    Eigen::MatrixXd psi_AxB_dimer_basis = psi_AxB.transpose()*overlapAB*orbitalsAB.MOCoefficients();  \n    overlapAB.resize(0,0);\n    int LevelsA = levelsA;\n    for (int i=0;i<psi_AxB_dimer_basis.rows();i++){\n        double mag=psi_AxB_dimer_basis.row(i).squaredNorm();\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            CTP_LOG(ctp::logERROR,*_pLog) << \"\\nERROR: \" << i << \" Projection of orbital \" \n                    << level << \" of monomer \" << monomer << \" on dimer is insufficient,mag=\"\n                    <<mag<<\" maybe the orbital order is screwed up, otherwise increase dimer basis.\\n\"<<flush;\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    Eigen::MatrixXi comb_CTAB=Eigen::MatrixXi::Zero(noAB,2);\n    cnt = 0;   \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    Eigen::MatrixXi  comb_CTBA=Eigen::MatrixXi::Zero(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    // 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    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    _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    _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    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()   << \"   construct projection of product functions \" << flush; \n \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                Eigen::MatrixXd Hamiltonian_AB = eh_s.cast<double>();\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Setup Hamiltonian\" << flush;\n                const Eigen::MatrixXd bseA_T = orbitalsA.BSESingletCoefficients().block(0,0,orbitalsA.BSESingletCoefficients().rows(),_levA).transpose().cast<double>();\n                const Eigen::MatrixXd bseB_T =orbitalsB.BSESingletCoefficients().block(0,0,orbitalsB.BSESingletCoefficients().rows(),_levB).transpose().cast<double>();\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                Eigen::MatrixXd Hamiltonian_AB = eh_s.cast<double>();\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"  Converted Hamiltonian to double\" << flush;         \n                const Eigen::MatrixXd bseA_T = orbitalsA.BSETripletCoefficients().block(0,0,orbitalsA.BSETripletCoefficients().rows(),_levA).transpose().cast<double>();\n                const Eigen::MatrixXd bseB_T =orbitalsB.BSETripletCoefficients().block(0,0,orbitalsB.BSETripletCoefficients().rows(),_levB).transpose().cast<double>();\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;\n};\n\n\nstd::vector< Eigen::MatrixXd > BSECoupling::ProjectExcitons(const Eigen::MatrixXd& bseA_T, const Eigen::MatrixXd& bseB_T, \n                                  Eigen::MatrixXd& H){\n   \n     // get projection of monomer excitons on dimer product functions\n     Eigen::MatrixXd _proj_excA = bseA_T* _kap;\n     Eigen::MatrixXd _proj_excB =  bseB_T* _kbp;\n     \n     _bse_exc=_levA+_levB;\n     int ctABsize=ctAB.rows();\n     int ctBAsize=ctBA.rows();\n     _ct=ctABsize+ctBAsize;\n     int nobasisfunc=H.rows();\n \n     Eigen::MatrixXd fe_states=Eigen::MatrixXd::Zero(_bse_exc,nobasisfunc);\n     fe_states.block(0,0, _levA, nobasisfunc )=_proj_excA;\n     fe_states.block( _levA,0,_levB,nobasisfunc )=_proj_excB;\n      \n     Eigen::MatrixXd ct_states=Eigen::MatrixXd::Zero(_ct,nobasisfunc);\n\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 (ctABsize > 0) {\n          ct_states.block(0, 0, ctABsize, nobasisfunc) = ctAB;\n        }\n        if (ctBAsize > 0) {\n          ct_states.block(ctABsize, 0, ctBAsize, nobasisfunc) = ctBA;\n        }\n\n        //orthogonalize ct-states with respect to FE states\n        Eigen::MatrixXd correction = ct_states * fe_states.transpose() * fe_states;\n        ct_states -= correction;\n        correction.resize(0, 0);\n        //normalize\n        Eigen::VectorXd norm=ct_states.rowwise().norm();\n        for (int i = 0; i < _ct; i++) {\n          ct_states.row(i) /= norm(i);\n        }\n        int minstateindex=0;\n        double minnorm=norm.minCoeff(&minstateindex);\n        if(minnorm<0.95){\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" WARNING: CT-state \" << minstateindex << \" norm is only \" << minnorm << flush;\n        }\n        }\n     Eigen::MatrixXd projection(_bse_exc+_ct,nobasisfunc);\n     CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \" merging projections into one vector  \" << flush;\n  projection.block(0 ,0, _bse_exc,nobasisfunc)=fe_states;\n   \n     if(_ct>0){\n    projection.block(_bse_exc,0,_ct ,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    //  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     // this only works for hermitian/symmetric H so only in TDA\n    \n     Eigen::MatrixXd J_dimer=projection*H*projection.transpose();\n     H.resize(0,0);\n    \n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \"   Setting up overlap matrix size \"<< _bse_exc +_ct<<\"x\"<<_bse_exc +_ct << flush;    \n    Eigen::MatrixXd S_dimer=projection*projection.transpose();\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    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(S_dimer);\n    Eigen::MatrixXd Sm1=es.operatorInverseSqrt();\n    J_dimer=Sm1*J_dimer*Sm1;\n   \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) << Sm1<<flush;\n     CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\"<<flush;\n    }\n     CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()  << \n             \"   Smallest value of dimer overlapmatrix is \"<<es.eigenvalues()(0)<< flush;\n     \n    std::vector< Eigen::MatrixXd >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\nEigen::MatrixXd BSECoupling::Perturbation(const Eigen::MatrixXd& J_dimer){\n    \n    Eigen::MatrixXd Jmatrix =Eigen::MatrixXd::Zero(_bse_exc, _bse_exc);\n    bool diag_ct = true;\n    Eigen::MatrixXd J_result=J_dimer;\n    if (_ct > 0 && diag_ct) {\n        Eigen::MatrixXd transformation = Eigen::MatrixXd::Identity(_bse_exc + _ct, _bse_exc + _ct);\n        Eigen::MatrixXd Ct = J_dimer.block(_bse_exc,_bse_exc,_ct, _ct);\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Ct);\n        transformation.block(_bse_exc, _bse_exc ,_ct,_ct) = es.eigenvectors();\n        Ct.resize(0, 0);\n\n        if (tools::globals::verbose) {\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"FE state hamiltonian\" << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << J_dimer.block(0,0, _bse_exc,_bse_exc) << flush;\n            if (_ct > 0) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"eigenvalues of CT states\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << es.eigenvalues() << flush;\n            }\n        }\n\n     J_result = transformation.transpose()*J_dimer*transformation;\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 + _levA;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Calculating coupling between exciton A\" \n                    << 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 (int 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 \" \n                            << 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 \"\n                            << 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            Jmatrix(stateA, stateBd) = J;\n            Jmatrix(stateBd, stateA) = J;\n\n\n        }\n    }           \n    return Jmatrix;\n}\n\n\nEigen::MatrixXd BSECoupling::Fulldiag(const Eigen::MatrixXd& J_dimer){\n    Eigen::MatrixXd Jmat = Eigen::MatrixXd::Zero(_bse_exc, _bse_exc);\n   \n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(J_dimer);\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        CTP_LOG(ctp::logDEBUG, *_pLog) << es.eigenvectors() << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog) << \"J_eigenvalues[Hrt]\" << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog) << es.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 + _levA;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Calculating coupling between exciton A\" << stateA + 1 << \" and exciton B\" << stateB + 1 << flush;\n            std::vector<int> index;\n            std::vector<int> signvec;\n            for (int i = 0; i < _bse_exc + _ct; i++) {\n                if (i == int(stateA) || i == int(stateBd)) {\n                    double close = 0.0;\n                    int ind = 0;\n                    int sign = 0;\n                    //row\n                    for (int 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                        if (check && std::abs(es.eigenvalues()(i, j)) > close) {\n                            ind = j;\n                            close = std::abs(es.eigenvalues()(i, j));\n                            if (es.eigenvalues()(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 Tmat and diagonal matrix Emat for the eigenvalues;\n            Eigen::MatrixXd Emat = Eigen::MatrixXd::Zero(2, 2);\n            Eigen::MatrixXd Tmat = Eigen::MatrixXd::Zero(2, 2);\n            //find the eigenvectors which are most similar to the initial states\n            //row \n            for (int i = 0; i < 2; i++) {\n                int k = index[i];\n                double sign = signvec[i];\n                double normr = 1 / std::sqrt(es.eigenvectors()(stateA, k) * es.eigenvectors()(stateA, k) + es.eigenvectors()(stateBd, k) * es.eigenvectors()(stateBd, k));\n                Tmat(0, i) = sign * es.eigenvectors()(stateA, k) * normr;\n                Tmat(1, i) = sign * es.eigenvectors()(stateBd, k) * normr;\n                Emat(i, i) = es.eigenvectors()(k);\n            }\n\n            if ((Tmat(1, 1) * Tmat(0, 0) - Tmat(1, 0) * Tmat(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                Tmat(0, 1) = -Tmat(0, 1);\n                Tmat(1, 1) = -Tmat(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) << Tmat << flush;\n\n            }\n\n            Eigen::MatrixXd S_small = Tmat*Tmat.transpose();\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            \n            Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> ss(S_small);\n            Eigen::MatrixXd sm1=ss.operatorInverseSqrt();\n            Emat=sm1*Emat*sm1;\n            \n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \"   Smallest value of dimer overlapmatrix is \" << ss.eigenvalues()(0) << flush;\n            if (tools::globals::verbose) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"S-1/2\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << sm1 << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"E_ortho\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << Emat << flush;\n            }\n            Tmat = Tmat*sm1;\n           \n            if (tools::globals::verbose) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"T_ortho\" << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << Tmat << flush;\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"---------------------------------------\" << flush;\n            }\n\n\n            Eigen::MatrixXd J_small = Tmat*Emat*Tmat.transpose();\n            if (tools::globals::verbose) {\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            Jmat(stateA, stateBd) = J_small(0, 1);\n            Jmat(stateBd, stateA) = J_small(1, 0);\n\n        }\n    }\n       \n    return Jmat;\n}\n\n\n    \n}}\n", "meta": {"hexsha": "4665a83ffc256d138fd54c338536c8aba351fec1", "size": 35599, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/bsecoupling.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/bsecoupling.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/bsecoupling.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4068877551, "max_line_length": 186, "alphanum_fraction": 0.5761678699, "num_tokens": 10777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.05261895817608201, "lm_q1q2_score": 0.025077124726891328}}
{"text": "#include \"mantella_bits/optimisationAlgorithm/hookeJeevesAlgorithm.hpp\"\n\n// C++ standard library\n#include <functional>\n#include <string>\n#include <utility>\n\n// Armadillo\n#include <armadillo>\n\n// Mantella\n#include \"mantella_bits/optimisationProblem.hpp\"\n#include \"mantella_bits/probability.hpp\"\n\nnamespace mant {\n  HookeJeevesAlgorithm::HookeJeevesAlgorithm()\n      : OptimisationAlgorithm(),\n        stepSize_(0) {\n    setInitialisingFunctions(\n        {{[this](\n              const arma::uword numberOfDimensions_,\n              const arma::mat& initialParameters_) {\n            stepSize_ = getInitialStepSize();\n\n            return initialParameters_;\n          },\n          \"Reset step size to the initial one\"}});\n\n    setNextParametersFunctions(\n        {{[this](\n              const arma::uword numberOfDimensions_,\n              const arma::mat& parameters_,\n              const arma::rowvec& objectiveValues_,\n              const arma::rowvec& differences_) {\n            if (arma::all(differences_ >= 0)) {\n              stepSize_ *= getStepSizeDecrease();\n            }\n\n            return parameters_;\n          },\n          \"Decrease the step size if the last objective values where worse than the best one\"},\n         {[this](\n              const arma::uword numberOfDimensions_,\n              const arma::mat& parameters_,\n              const arma::rowvec& objectiveValues_,\n              const arma::rowvec& differences_) {\n            arma::mat nextParameters(numberOfDimensions_, 2 * numberOfDimensions_);\n            for (arma::uword n = 0; n < numberOfDimensions_; ++n) {\n              arma::vec nextParameterCandidate = getBestFoundParameter();\n\n              nextParameterCandidate(n) += stepSize_;\n              nextParameters.col(2 * n) = nextParameterCandidate;\n\n              nextParameterCandidate(n) -= 2 * stepSize_;\n              nextParameters.col(2 * n + 1) = nextParameterCandidate;\n            }\n\n            return nextParameters;\n          },\n          \"Hooke-Jeeves algorithm\"}});\n\n    setInitialStepSize(1.0);\n    setStepSizeDecrease(0.5);\n  }\n\n  void HookeJeevesAlgorithm::optimise(\n      OptimisationProblem& optimisationProblem) {\n    optimise(optimisationProblem, uniformRandomNumbers(optimisationProblem.numberOfDimensions_));\n  }\n\n  void HookeJeevesAlgorithm::setInitialStepSize(\n      const double initialStepSize) {\n    initialStepSize_ = initialStepSize;\n  }\n\n  double HookeJeevesAlgorithm::getInitialStepSize() const {\n    return initialStepSize_;\n  }\n\n  void HookeJeevesAlgorithm::setStepSizeDecrease(\n      const double stepSizeDecrease) {\n    stepSizeDecrease_ = stepSizeDecrease;\n  }\n\n  double HookeJeevesAlgorithm::getStepSizeDecrease() const {\n    return stepSizeDecrease_;\n  }\n}\n", "meta": {"hexsha": "51415bddc32a42fee273478bdd71472cb00b1c10", "size": 2734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimisationAlgorithm/hookeJeevesAlgorithm.cpp", "max_stars_repo_name": "OpusV/AstroMechanics", "max_stars_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T22:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T22:06:56.000Z", "max_issues_repo_path": "src/optimisationAlgorithm/hookeJeevesAlgorithm.cpp", "max_issues_repo_name": "OpusV/AstroMechanics", "max_issues_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimisationAlgorithm/hookeJeevesAlgorithm.cpp", "max_forks_repo_name": "OpusV/AstroMechanics", "max_forks_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7191011236, "max_line_length": 97, "alphanum_fraction": 0.643013899, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.051082734790127565, "lm_q1q2_score": 0.024942851184320144}}
{"text": "#include <hpx/hpx.hpp>\n#include <hpx/hpx_init.hpp>\n#include <hpx/runtime/serialization/serialize.hpp>\n#include <hpx/util/unused.hpp>\n\n#include <boost/shared_array.hpp>\n\n#include <cstddef>\n#include <cstdint>\n#include <iostream>\n#include <stdlib.h>\n#include <utility>\n#include <vector>\n\n///////////////////////////////////////////////////////////////////////////////\ninline std::size_t idx(std::size_t i, std::size_t j, std::size_t s)\n{\n    return i * s + j;\n}\n\ninline std::size_t locidx(\n    std::size_t i, std::size_t j, std::size_t T, std::size_t nl)\n{\n    std::size_t tnl = T / nl;\n    if (T % nl > 0)\n        ++tnl;\n    return i / tnl;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nstruct partition_data\n{\nprivate:\n    typedef hpx::serialization::serialize_buffer<double> buffer_type;\n\npublic:\n    partition_data()\n      : n_(0)\n      , t_(0)\n      , i_(0)\n      , j_(0)\n    {\n    }\n\n    // Create a new (uninitialized) partition of the given size.\n    partition_data(std::size_t n)\n      : data_(\n            std::allocator<double>().allocate(n * n), n * n, buffer_type::take)\n      , n_(n)\n      , t_(0)\n      , i_(0)\n      , j_(0)\n    {\n    }\n\n    // Create a new (initialized) partition of the given size.\n    partition_data(std::size_t n, std::size_t t, std::size_t i, std::size_t j)\n      : data_(\n            std::allocator<double>().allocate(n * n), n * n, buffer_type::take)\n      , n_(n)\n      , t_(t)\n      , i_(i)\n      , j_(j)\n    {\n        srand(idx(i, j, n));\n        for (std::size_t k = 0; k != n * n; ++k)\n            data_[k] = (double) ((rand() % 2000) - 1000) / 100;\n    }\n\n    partition_data(partition_data const& base)\n      : data_(base.data_.data(), base.size(), buffer_type::copy)\n      , n_(base.n_)\n      , t_(base.t_)\n      , i_(base.i_)\n      , j_(base.j_)\n    {\n    }\n\n    double& operator[](std::size_t idx)\n    {\n        return data_[idx];\n    }\n    double operator[](std::size_t idx) const\n    {\n        return data_[idx];\n    }\n\n    std::size_t size() const\n    {\n        return n_ * n_;\n    }\n\n    std::size_t dim() const\n    {\n        return n_;\n    }\n\n    std::size_t nt() const\n    {\n        return t_;\n    }\n\n    std::size_t pos_i() const\n    {\n        return i_;\n    }\n\n    std::size_t pos_j() const\n    {\n        return j_;\n    }\n\nprivate:\n    // Serialization support: even if all of the code below runs on one\n    // locality only, we need to provide an (empty) implementation for the\n    // serialization as all arguments passed to actions have to support this.\n    friend class hpx::serialization::access;\n\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int version)\n    {\n        ar& data_& n_& t_& i_& j_;\n    }\n\nprivate:\n    buffer_type data_;\n    std::size_t n_;\n    std::size_t t_;\n    std::size_t i_;\n    std::size_t j_;\n};\n\nstd::ostream& operator<<(std::ostream& os, partition_data const& c)\n{\n    os << \"== block i(\" << c.pos_i() << \") j(\" << c.pos_j() << \")\" <<  std::endl;\n    for (std::size_t i = 0; i != c.dim(); ++i)\n    {\n        for (std::size_t j = 0; j != c.dim(); ++j)\n        {\n            os << c.pos_i() * c.dim() + i << \" \" << c.pos_j() * c.dim() + j << \" \" << c[i * c.dim() + j]\n               << std::endl;\n        }\n    }\n    return os;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// This is the server side representation of the data. We expose this as a HPX\n// component which allows for it to be created and accessed remotely through\n// a global address (hpx::id_type).\nstruct partition_server : hpx::components::component_base<partition_server>\n{\n    // construct new instances\n    partition_server() {}\n\n    partition_server(partition_data const& data)\n      : data_(data)\n    {\n    }\n\n    partition_server(std::size_t n, std::size_t t, std::size_t i, std::size_t j)\n      : data_(n, t, i, j)\n    {\n    }\n\n    // Access data.\n    partition_data get_data() const\n    {\n        return data_;\n    }\n\n    // Every member function which has to be invoked remotely needs to be\n    // wrapped into a component action. The macro below defines a new type\n    // 'get_data_action' which represents the (possibly remote) member function\n    // partition::get_data().\n    HPX_DEFINE_COMPONENT_DIRECT_ACTION(\n        partition_server, get_data, get_data_action);\n\nprivate:\n    partition_data data_;\n};\n\n// The macros below are necessary to generate the code required for exposing\n// our partition type remotely.\n//\n// HPX_REGISTER_COMPONENT() exposes the component creation\n// through hpx::new_<>().\ntypedef hpx::components::component<partition_server> partition_server_type;\nHPX_REGISTER_COMPONENT(partition_server_type, partition_server);\n\n// HPX_REGISTER_ACTION() exposes the component member function for remote\n// invocation.\ntypedef partition_server::get_data_action get_data_action;\nHPX_REGISTER_ACTION(get_data_action);\n\n///////////////////////////////////////////////////////////////////////////////\n// This is a client side helper class allowing to hide some of the tedious\n// boilerplate.\nstruct partition : hpx::components::client_base<partition, partition_server>\n{\n    typedef hpx::components::client_base<partition, partition_server> base_type;\n\n    partition() {}\n\n    // Create new component on locality 'where' and initialize the held data\n    partition(hpx::id_type where, std::size_t n, std::size_t t, std::size_t i, std::size_t j)\n      : base_type(hpx::new_<partition_server>(where, n, t, i, j))\n    {\n    }\n\n    // Create a new component on the locality co-located to the id 'where'. The\n    // new instance will be initialized from the given partition_data.\n    partition(hpx::id_type where, partition_data const& data)\n      : base_type(hpx::new_<partition_server>(hpx::colocated(where), data))\n    {\n    }\n\n    // Attach a future representing a (possibly remote) partition.\n    partition(hpx::future<hpx::id_type>&& id)\n      : base_type(std::move(id))\n    {\n    }\n\n    // Unwrap a future<partition> (a partition already holds a future to the\n    // id of the referenced object, thus unwrapping accesses this inner future).\n    partition(hpx::future<partition>&& c)\n      : base_type(std::move(c))\n    {\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // Invoke the (remote) member function which gives us access to the data.\n    // This is a pure helper function hiding the async.\n    hpx::future<partition_data> get_data() const\n    {\n        partition_server::get_data_action act;\n        return hpx::async(act, get_id());\n    }\n};\n\n///////////////////////////////////////////////////////////////////////////////\nstruct stepper\n{\n    // Our data for one time step\n    typedef std::vector<partition> space;\n\n    static partition_data inv_core(partition_data const& A_)\n    {\n        double tmp;\n        partition_data A(A_);\n        partition_data v(A_.dim());\n\n        for (int i = 0; i < A.dim(); ++i)\n        {\n            for (int j = 0; j < A.dim(); ++j)\n            {\n                v[i * A.dim() + j] = 0;\n            }\n            v[i * A.dim() + i] = 1;\n        }\n        for (int k = 0; k < A.dim(); ++k)\n        {\n            tmp = A[k * A.dim() + k];\n            for (int j = 0; j < A.dim(); ++j)\n            {\n                v[k * A.dim() + j] /= tmp;\n                A[k * A.dim() + j] /= tmp;\n            }\n\n            // can be parallalized\n            for (int i = 0; i < k; ++i)\n            {\n                tmp = A[i * A.dim() + k];\n                for (int j = 0; j < A.dim(); ++j)\n                {\n                    v[i * A.dim() + j] -= tmp * v[k * A.dim() + j];\n                    A[i * A.dim() + j] -= tmp * A[k * A.dim() + j];\n                }\n            }\n            for (int i = k + 1; i < A.dim(); ++i)\n            {\n                tmp = A[i * A.dim() + k];\n                for (int j = 0; j < A.dim(); ++j)\n                {\n                    v[i * A.dim() + j] -= tmp * v[k * A.dim() + j];\n                    A[i * A.dim() + j] -= tmp * A[k * A.dim() + j];\n                }\n            }\n        }\n        return v;\n    }\n\n    //A = A * B\n    static partition_data pmm_core(partition_data const& A, partition_data const& B)\n    {\n        partition_data r(A);\n\n        // i and j can be parallalized\n        for (int i = 0; i < A.dim(); ++i)\n        {\n            for (int j = 0; j < A.dim(); ++j)\n            {\n                r[i * A.dim() + j] = 0;\n                for (int k = 0; k < A.dim(); ++k)\n                {\n                    r[i * A.dim() + j] += A[i * A.dim() + k] * B[k * A.dim() + j];\n                }\n            }\n        }\n        return r;\n    }\n\n    //C = C - A * B\n    static partition_data pmm_d_core(\n        partition_data const& A, partition_data const& B, partition_data const& C)\n    {\n        partition_data r(C);\n\n        // i and j can be parallalized\n        for (int i = 0; i < A.dim(); ++i)\n        {\n            for (int j = 0; j < A.dim(); ++j)\n            {\n                for (int k = 0; k < A.dim(); ++k)\n                {\n                    r[i * A.dim() + j] -= A[i * A.dim() + k] * B[k * A.dim() + j];\n                }\n            }\n        }\n        return r;\n    }\n\n    static partition inv_part(partition const& A_p, partition const& inv_p)\n    {\n        using hpx::dataflow;\n        using hpx::util::unwrapping;\n\n        hpx::shared_future<partition_data> A_data = A_p.get_data();\n        return dataflow(hpx::launch::async,\n            unwrapping([inv_p](partition_data const& A) -> partition {\n                partition_data m_inv = stepper::inv_core(A);\n                return partition(inv_p.get_id(), m_inv);\n            }),\n            A_data);\n    }\n\n    static partition pmm_part(partition const& A_p, partition const& B_p)\n    {\n        using hpx::dataflow;\n        using hpx::util::unwrapping;\n\n        hpx::shared_future<partition_data> A_data = A_p.get_data();\n        hpx::shared_future<partition_data> B_data = B_p.get_data();\n        return dataflow(hpx::launch::async,\n            unwrapping([A_p](partition_data const& A,\n                           partition_data const& B) -> partition {\n                partition_data r = stepper::pmm_core(A, B);\n                return partition(A_p.get_id(), r);\n            }),\n            A_data, B_data);\n    }\n\n    static partition pmm_d_part(\n        partition const& A_p, partition const& B_p, partition const& C_p)\n    {\n        using hpx::dataflow;\n        using hpx::util::unwrapping;\n\n        hpx::shared_future<partition_data> A_data = A_p.get_data();\n        hpx::shared_future<partition_data> B_data = B_p.get_data();\n        hpx::shared_future<partition_data> C_data = C_p.get_data();\n        return dataflow(hpx::launch::async,\n            unwrapping([C_p](partition_data const& A, partition_data const& B,\n                           partition_data const& C) -> partition {\n                partition_data r = stepper::pmm_d_core(A, B, C);\n                return partition(C_p.get_id(), r);\n            }),\n            A_data, B_data, C_data);\n    }\n\n    // do all the work on 'np' partitions, 'nx' data points each, for 'nt'\n    // time steps\n    space do_lu(std::size_t T, std::size_t N, bool print_matrices);\n};\n\nHPX_PLAIN_ACTION(stepper::inv_part, inv_part_action);\nHPX_PLAIN_ACTION(stepper::pmm_part, pmm_part_action);\nHPX_PLAIN_ACTION(stepper::pmm_d_part, pmm_d_part_action);\n\n///////////////////////////////////////////////////////////////////////////////\n// do all the work on 'np' partitions, 'nx' data points each, for 'nt'\n// time steps\nstepper::space stepper::do_lu(std::size_t T, std::size_t N, bool print_matrices)\n{\n    using hpx::dataflow;\n\n    std::vector<hpx::id_type> localities = hpx::find_all_localities();\n    std::size_t nl = localities.size();    // Number of localities\n\n    space tiles;\n    tiles.resize(T * T);\n\n    space invs;\n    invs.resize(T);\n\n    for (std::size_t i = 0; i != T; ++i)\n        for (std::size_t j = 0; j != T; ++j)\n            tiles[idx(i, j, T)] =\n                partition(localities[locidx(i, j, T, nl)], N, T, i, j);\n\n    if (print_matrices) {\n        std::cout << \"== a == \" << std::endl;\n        for (std::size_t i = 0; i != T * T; ++i)\n        {\n            tiles[i].get_data().wait();\n            std::cout << tiles[i].get_data().get();\n        }\n        std::cout << \"== a == \" << std::endl;\n    }\n\n    for (std::size_t i = 0; i != T; ++i)\n        invs[i] = partition(localities[locidx(i, 0, T, nl)], N, T, i, 0);\n\n    inv_part_action act_inv;\n    pmm_part_action act_pmm;\n    pmm_d_part_action act_pmm_d;\n\n    for (std::size_t k = 0; k < T - 1; ++k)\n    {\n        using hpx::util::placeholders::_1;\n        using hpx::util::placeholders::_2;\n        auto Op =\n            hpx::util::bind(act_inv, localities[locidx(k, 0, T, nl)], _1, _2);\n        invs[k] =\n            dataflow(hpx::launch::async, Op, tiles[idx(k, k, T)], invs[k]);\n        for (std::size_t i = k + 1; i < T; ++i)\n        {\n            using hpx::util::placeholders::_1;\n            using hpx::util::placeholders::_2;\n            auto Op = hpx::util::bind(\n                act_pmm, localities[locidx(k, 0, T, nl)], _1, _2);\n            tiles[idx(i, k, T)] =\n                dataflow(hpx::launch::async, Op, tiles[idx(i, k, T)], invs[k]);\n            for (std::size_t j = k + 1; j < T; ++j)\n            {\n                using hpx::util::placeholders::_1;\n                using hpx::util::placeholders::_2;\n                using hpx::util::placeholders::_3;\n                auto Op = hpx::util::bind(\n                    act_pmm_d, localities[locidx(i, j, T, nl)], _1, _2, _3);\n                tiles[idx(i, j, T)] =\n                    dataflow(hpx::launch::async, Op, tiles[idx(i, k, T)],\n                        tiles[idx(k, j, T)], tiles[idx(i, j, T)]);\n            }\n        }\n    }\n\n    // Return the LU factorization\n    return tiles;\n}\n\n///////////////////////////////////////////////////////////////////////////////\nint hpx_main(boost::program_options::variables_map& vm)\n{\n    std::uint64_t N = vm[\"N\"].as<std::uint64_t>();\n    std::uint64_t T = vm[\"T\"].as<std::uint64_t>();\n\n    std::vector<hpx::id_type> localities = hpx::find_all_localities();\n    std::size_t nl = localities.size();    // Number of localities\n\n    if (N * N < nl)\n    {\n        std::cout << \"The number of tiles should not be smaller than \"\n                     \"the number of localities\"\n                  << std::endl;\n        return hpx::finalize();\n    }\n\n    // Create the stepper object\n    stepper step;\n\n    // Measure execution time.\n    std::uint64_t t = hpx::util::high_resolution_clock::now();\n\n    // Execute nt time steps on nx grid points and print the final solution.\n    stepper::space solution = step.do_lu(T, N, vm.count(\"print-matrices\"));\n    for (std::size_t i = 0; i != T * T; ++i)\n        solution[i].get_data().wait();\n\n    std::uint64_t elapsed = hpx::util::high_resolution_clock::now() - t;\n    std::cout << elapsed / 1e9 << std::endl;\n\n    // Print the final solution\n    if (vm.count(\"print-matrices\"))\n    {\n        std::cout << \"== lu == \" << std::endl;\n        for (std::size_t i = 0; i != T * T; ++i)\n        {\n            std::cout << solution[i].get_data().get();\n        }\n        std::cout << \"== lu == \" << std::endl;\n    }\n    std::uint64_t const num_worker_threads = hpx::get_num_worker_threads();\n    hpx::future<std::uint32_t> locs = hpx::get_num_localities();\n\n    return hpx::finalize();\n}\n\nint main(int argc, char* argv[])\n{\n    using namespace boost::program_options;\n\n    options_description desc_commandline;\n    desc_commandline.add_options()(\n        \"print-matrices\", \"print generated A and computed LU (default: false)\")(\"N\",\n        value<std::uint64_t>()->default_value(10),\n        \"Dimension of the submatrices\")(\"T\",\n        value<std::uint64_t>()->default_value(10),\n        \"Number of subblocks in each dimension\");\n\n    // Initialize and run HPX\n    return hpx::init(desc_commandline, argc, argv);\n}\n", "meta": {"hexsha": "c426f5cf92f7d24a72158f63cc1855f724353b5f", "size": 15973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lu_tiled_dist.cpp", "max_stars_repo_name": "jgurhem/HPX_LA", "max_stars_repo_head_hexsha": "22effbd77134b488104c0baa0d02feb282c5e251", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-26T12:42:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-26T12:42:13.000Z", "max_issues_repo_path": "lu_tiled_dist.cpp", "max_issues_repo_name": "jgurhem/HPX_LA", "max_issues_repo_head_hexsha": "22effbd77134b488104c0baa0d02feb282c5e251", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lu_tiled_dist.cpp", "max_forks_repo_name": "jgurhem/HPX_LA", "max_forks_repo_head_hexsha": "22effbd77134b488104c0baa0d02feb282c5e251", "max_forks_repo_licenses": ["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.4828244275, "max_line_length": 104, "alphanum_fraction": 0.5216928567, "num_tokens": 4224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.06097517830536819, "lm_q1q2_score": 0.024837226697532466}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis\t\t\t\t\t\t  |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford\t  |\n|\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  |\n|  This program is free software; you can redistribute it and/or modify\t\t  |\n|  it under the terms of the GNU General Public License as published by\t\t  |\n|  the Free Software Foundation; either version 2 of the License, or\t\t  |\n|  (at your option) any later version.\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\t  |\n|  This program is distributed in the hope that it will be useful,\t\t\t  |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of\t\t\t  |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\t\t\t  |\n|  GNU General Public License for more details.\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\t  |\n|  You should have received a copy of the GNU General Public License along\t  |\n|  with this program; if not, write to the Free Software Foundation, Inc.,\t  |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\t\t\t\t  |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#include \"square_matrix.hpp\"\n\n#include <boost/format.hpp>\n\n#include \"ncl/nxsallocatematrix.h\"\n\n\nnamespace phycas\n{\n\nunsigned SquareMatrix::k = 0;\t//temporary!\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSquareMatrix default constructor. Sets `dim' and `m' data members to 0.\n*/\nSquareMatrix::SquareMatrix()\n  :\t id(++k), m(0), dim(0)\n\t{\n\t//std::cerr << \"|----> constructing default SquareMatrix \" << id << \" <----\" << std::endl;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSquareMatrix constructor. Creates square matrix `m' with dimension `sz' and sets all elements of `m' to `value'.\n*/\nSquareMatrix::SquareMatrix(\n  unsigned sz,\t\t/**< the row and column dimension of the matrix */\n  double value)\t\t/**< the value to which to set all elements */\n  : id(++k), m(0), dim(0)\n\t{\n\t//std::cerr << \"|----> constructing SquareMatrix \" << id << \" of size \" << sz << \" with all values set to \" << value << \" <----\" << (this) << std::endl;\n\tCreateMatrix(sz, value);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSquareMatrix copy constructor. This is necessary because the standard vector resize function in some implementations\n|\tof the standard template library creates only one element with the default constructor, then creates the remaining\n|\telements using the copy constructor.\n*/\nSquareMatrix::SquareMatrix(\n  const SquareMatrix & other)\t/**< is the SquareMatrix to copy */\n  : id(++k), m(0), dim(other.dim)\n\t{\n\t//std::cerr << \"|----> copy constructing SquareMatrix \" << id << \" from \" << other.id << \" <----\" << (this) << std::endl;\n\tif (dim > 0)\n\t\t{\n\t\tCreateMatrix(dim, 0.0);\n\t\tdouble * pother = &other.m[0][0];\n\t\tdouble * p = &m[0][0];\n\t\tunsigned last = dim*dim;\n\t\tfor (unsigned i = 0; i < last; ++i)\n\t\t\t*p++ = *pother++;\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSquareMatrix destructor. If `m' exists, deletes it.\n*/\nSquareMatrix::~SquareMatrix()\n\t{\n\t//std::cerr << \"|----> destroying SquareMatrix \" << id << \" <----\" << (this) << std::endl;\n    Clear();\n\tid = UINT_MAX;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns object to state it would be in if just constructed using the default constructor. Leaves `id' at the same\n|   value it had when this object was constucted, however.\n*/\nvoid SquareMatrix::Clear()\n\t{\n\tif (m)\n\t\tDeleteTwoDArray<double>(m);\n\tm = 0;\n\tdim = 0;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAllocates memory for `m' data member and calls SquareMatrix::Identity.\n*/\nvoid SquareMatrix::CreateMatrix(\n  unsigned sz,\t\t/**< is the row and column dimension of the square matrix to be created */\n  double value)\t\t/**< is the value to which each element will be set */\n\t{\n\t//std::cerr << \"----> SquareMatrix::CreateMatrix \" << id << \", sz = \" << sz << \", value = \" << value << \" <----\" << std::endl;\n    dim = sz;\n\tif (m)\n\t\tDeleteTwoDArray<double>(m);\n\tm = 0;\n\tif (sz > 0)\n\t\t{\n\t\tm = NewTwoDArray<double>(sz, sz);\n\t\tFill(value);\n\t\t}\n\n\t//std::cerr << \"----> SquareMatrix::CreateMatrix \" << id << \", sz = \" << sz << \", value = \" << value << \" <----\\n\";\n    //for (unsigned i = 0; i < sz; ++i)\n    //    {\n    //    for (unsigned j = 0; j < sz; ++j)\n    //        {\n    //        std::cerr << boost::str(boost::format(\"%12.1f\") % m[i][j]);\n    //        }\n    //    std::cerr << \"\\n\";\n    //    }\n    //std::cerr << std::endl;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|   Fills `p_mat_trans_scratch' with transpose of `p_mat'. Assumes both `p_mat_trans_scratch' and `p_mat' are allocated\n|   square matrices of doubles and are of the same dimension. Overwrites any values currently in `p_mat_trans_scratch'.\n*/\nvoid fillTranspose(double ** p_mat_trans_scratch, const double * const *p_mat, unsigned dim)\n\t{\n\tfor (unsigned j = 0; j < dim; ++j)\n\t\t{\n\t\tfor (unsigned k = 0 ; k < dim; ++k)\n\t\t\tp_mat_trans_scratch[j][k] = p_mat[k][j];\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the dimension of the data member `m' (the row and column dimension are the same).\n*/\nunsigned SquareMatrix::GetDimension() const\n\t{\n\treturn dim;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the sum of the elements on the main diagonal.\n*/\ndouble SquareMatrix::Trace() const\n\t{\n    double trace = 0.0;\n    for (unsigned i = 0; i < dim; ++i)\n        trace += m[i][i];\n\treturn trace;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAccessor function that simply returns `m'. This allows `m' to be passed to functions that expect a two-dimensional\n|\tarray of doubles, but keep in mind that this is somewhat unsafe.\n*/\ndouble * * SquareMatrix::GetMatrixAsRawPointer() const\n\t{\n\treturn m;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tOperator that allows access to this SquareMatrix object as if it were a two-dimensional array of doubles.\n*/\ndouble * SquareMatrix::operator[](\n  unsigned i) const\n\t{\n\tPHYCAS_ASSERT(i < GetDimension());\n\treturn m[i];\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns string representation of the matrix.\n*/\nstd::string SquareMatrix::GetStringRepresentation() const\n\t{\n    std::string s;\n    std::string fmt = \"\\t%g\";\n    MatrixToString(s, fmt);\n    return s;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns string representation of the matrix.\n*/\nstd::string SquareMatrix::GetFormattedStringRepresentation(std::string fmt = \"%g\") const\n\t{\n    std::string s;\n    MatrixToString(s, fmt);\n    return s;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns element at row `i', column `'j of the matrix.\n*/\ndouble SquareMatrix::GetElement(unsigned i, unsigned j) const\n\t{\n\tPHYCAS_ASSERT(i < dim);\n\tPHYCAS_ASSERT(j < dim);\n    return m[i][j];\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets element at row `i', column `j' of the matrix to the value `v'.\n*/\nvoid SquareMatrix::SetElement(unsigned i, unsigned j, double v)\n\t{\n\tPHYCAS_ASSERT(i < dim);\n\tPHYCAS_ASSERT(j < dim);\n    m[i][j] = v;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets element at row `i', column `j' of the matrix to the current value plus `v'.\n*/\nvoid SquareMatrix::AddToElement(unsigned i, unsigned j, double v)\n\t{\n\tPHYCAS_ASSERT(i < dim);\n\tPHYCAS_ASSERT(j < dim);\n    m[i][j] += v;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the entire matrix as a vector by row.\n*/\nstd::vector<double> SquareMatrix::GetMatrix() const\n\t{\n    std::vector<double> v;\n    double * ptr = (double *)&m[0];\n    for (unsigned i = 0; i < dim*dim; ++i)\n        v.push_back(ptr[i]);\n    return v;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCopies supplied vector `v' into this matrix. Vector `v' is expected to have length `sz'*`sz', and matrix is read\n|   from `v' by row. The data member `dim' is set equal to `sz'.\n*/\nvoid SquareMatrix::SetMatrix(unsigned sz, std::vector<double> v)\n\t{\n\tPHYCAS_ASSERT(sz == (int)sqrt(v.size()));\n    CreateMatrix(sz, 0.0);\n    double * ptr = (double *)&m[0][0];\n    for (std::vector<double>::iterator it = v.begin(); it != v.end(); ++it)\n        {\n        double val = *it;\n        *ptr++ = val;\n        }\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tFills all cells of matrix `m' with `value'.\n*/\nvoid SquareMatrix::Fill(\n  double value) /**< is the value to which every element in matrix is to be set */\n\t{\n    unsigned dim = GetDimension();\n\tunsigned last = dim*dim;\n\tdouble * p = &m[0][0];\n\tfor (unsigned i = 0; i < last; ++i)\n\t\t*p++ = value;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAssumes dimension > 0 and `m' exists. Converts `m' to the identity matrix.\n*/\nvoid SquareMatrix::Identity()\n\t{\n\t//std::cerr << \"----> SquareMatrix::Identity \" << id << \" <----\" << std::endl;\n\tPHYCAS_ASSERT(dim > 0);\n\tunsigned i;\n\tunsigned last = dim*dim;\n\tdouble * p = &m[0][0];\n\tfor (i = 0; i < last; ++i)\n\t\t*p++ = 0.0;\n\tfor (i = 0; i < dim; ++i)\n\t\tm[i][i] = 1.0;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAssumes dimension > 0 and `m' exists. Multiplies each element of `m' by the supplied `scalar'.\n*/\nvoid SquareMatrix::ScalarMultiply(\n  double scalar)\t/**< is the scalar value multiplied by each element */\n\t{\n\t//std::cerr << \"----> SquareMatrix::ScalarMultiply \" << id << \", scalar = \" << scalar << \" <----\" << std::endl;\n\tPHYCAS_ASSERT(dim > 0);\n\tunsigned last = dim*dim;\n\tdouble * p = &m[0][0];\n\tfor (unsigned i = 0; i < last; ++i)\n\t\t*p++ *= scalar;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAssumes dimension > 0 and `m' exists. Subtracts each element of `other' from the corresponding element of this.\n*/\nvoid SquareMatrix::Subtract(\n  const SquareMatrix & other)\t /**< is the matrix to subtract from this */\n\t{\n\tPHYCAS_ASSERT(dim > 0);\n\tunsigned last = dim*dim;\n\tdouble * otherp = &other.m[0][0];\n\tdouble * p = &m[0][0];\n\tfor (unsigned i = 0; i < last; ++i)\n\t\t*p++ -= *otherp++;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAssumes dimension > 0 and `m' exists. Sets each element of `m' to the supplied `scalar'.\n*/\nvoid SquareMatrix::SetToScalar(\n  double scalar)\t/**< is the scalar value to which each element is set */\n\t{\n\t//std::cerr << \"----> SquareMatrix::SetToScalar \" << id << \", scalar = \" << scalar << \" <----\" << std::endl;\n\tPHYCAS_ASSERT(dim > 0);\n\tunsigned last = dim*dim;\n\tdouble * p = &m[0][0];\n\tfor (unsigned i = 0; i < last; ++i)\n\t\t*p++ = scalar;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSaves a representation of the matrix to the supplied string for use in debugging. The caller should supply a format\n|\tstring suitable for representing a single value of the matrix: e.g. \"%12.5f\\t\".\n*/\nvoid SquareMatrix::MatrixToString(\n  std::string & s,\t\t /**< the string to which a representation will be saved */\n  std::string fmt) const /**< the format string */\n\t{\n    unsigned dim = GetDimension();\n\t//s += boost::str(boost::format(\"This is SquareMatrix %d\\n\") % id);\n\tfor (unsigned i = 0; i < dim; ++i)\n\t\t{\n\t\tfor (unsigned j = 0; j < dim; ++j)\n\t\t\t{\n\t\t\ts += str(boost::format(fmt) % m[i][j]);\n\t\t\t}\n\t\ts += '\\n';\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the Cholesky decomposition of this SquareMatrix as a lower-triangular matrix. Assumes this SquareMatrix is\n|   symmetric and positive definite.\n*/\nSquareMatrix * SquareMatrix::CholeskyDecomposition() const\n    {\n\tPHYCAS_ASSERT(dim > 0);\n    SquareMatrix * L = new SquareMatrix(*this);\n    double * p = new double[dim];\n    double ** a = L->GetMatrixAsRawPointer();\n\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        for (unsigned j = i; j < dim; ++j)\n            {\n            double sum = a[i][j];\n            for (int k = i-1; k >= 0; --k)\n                {\n                sum -= a[i][k]*a[j][k];\n                }\n            if (i == j)\n                {\n                if (sum <= 0.0)\n                    {\n                    // matrix is not positive definite\n                    return 0;\n                    }\n                p[i] = sqrt(sum);\n                }\n            else\n                {\n                a[j][i] = sum/p[i];\n                }\n            }\n        }\n\n    // zero out upper diagonal and copy diagonal elements\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        a[i][i] = p[i];\n        for (unsigned j = i+1; j < dim; ++j)\n            {\n            a[i][j] = 0.0;\n            }\n        }\n\n    return L;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the LU decomposition of this SquareMatrix.\n*/\nSquareMatrix * SquareMatrix::LUDecomposition() const\n    {\n\tPHYCAS_ASSERT(dim > 0);\n    SquareMatrix * L = new SquareMatrix(*this);\n    double * scaling = new double[dim];\n    int * permutation = new int[dim];\n    double ** a = L->GetMatrixAsRawPointer();\n\tint err_code = LUDecompose(a, dim, scaling, permutation, NULL);\n    if (err_code == 0)\n        {\n        // LUDecompose worked\n        delete [] scaling;\n        delete [] permutation;\n        return L;\n        }\n\n    // Should throw an exception here\n    delete L;\n    delete [] scaling;\n    delete [] permutation;\n    return 0;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the natural logarithm of the product of the eigenvalues of this SquareMatrix.\n*/\ndouble SquareMatrix::LogDeterminant() const\n    {\n\tPHYCAS_ASSERT(dim > 0);\n    double * fv = new double[dim];\n    double * w = new double[dim];\n    double ** a = this->GetMatrixAsRawPointer();\n    SquareMatrix * Z = new SquareMatrix(dim, 0.0);\n    double ** z = Z->GetMatrixAsRawPointer();\n\n\t// Calculate eigenvalues (w) and eigenvectors (z)\n    // int n        input: the order of the matrix a\n    // double **a   input: the real symmetric matrix\n    // double *fv   input: temporary storage array of at least n elements\n    // double **z   output: the eigenvectors\n    // double *w    output: the eigenvalues in ascending order\n\tint err_code = EigenRealSymmetric(dim, a, w, z, fv);\n    if (err_code != 0)\n        {\n        delete Z;\n        delete [] fv;\n        delete [] w;\n        return 0;\n        }\n\n    double log_det = 0.0;\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        double v = w[i];\n        log_det += log(v);\n        }\n\n    delete Z;\n    delete [] fv;\n    delete [] w;\n\n    return log_det;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the natural logarithm of the product of the terms on the main diagonal of this SquareMatrix. If this matrix\n|   is triangular, this is equal to the log of the determinant.\n*/\ndouble SquareMatrix::LogProdMainDiag() const\n    {\n\tPHYCAS_ASSERT(dim > 0);\n    double sumLog = 0.0;\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        double tmp = GetElement(i, i);\n        PHYCAS_ASSERT(tmp > 0.0);\n        sumLog += log(tmp);\n        }\n    return sumLog;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns a copy of this matrix'.\n*/\nSquareMatrix * SquareMatrix::Duplicate() const\n    {\n\tif (dim == 0)\n        return new SquareMatrix();\n\n    SquareMatrix * Z = new SquareMatrix(dim, 0.0);\n    double * pZ = &Z->m[0][0];\n    double * p = &m[0][0];\n    unsigned last = dim*dim;\n    for (unsigned i = 0; i < last; ++i)\n        *pZ++ = *p++;\n    return Z;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates and returns a matrix that represents this matrix raised to the power `p'.\n*/\nSquareMatrix * SquareMatrix::Power(\n  double p) const   /**< the power to which this matrix should be raised */\n    {\n\tPHYCAS_ASSERT(dim > 0);\n\t//PHYCAS_ASSERT(p > 0.0);\n    double * fv = new double[dim];\n    double * w = new double[dim];\n    double ** a = this->GetMatrixAsRawPointer();\n    SquareMatrix * Z = new SquareMatrix(dim, 0.0);\n    double ** z = Z->GetMatrixAsRawPointer();\n\n\t// Calculate eigenvalues (w) and eigenvectors (z)\n    // int n        input: the order of the matrix a\n    // double **a   input: the real symmetric matrix\n    // double *fv   input: temporary storage array of at least n elements\n    // double **z   output: the eigenvectors\n    // double *w    output: the eigenvalues in ascending order\n\tint err_code = EigenRealSymmetric(dim, a, w, z, fv);\n    if (err_code != 0)\n        {\n        delete Z;\n        delete [] fv;\n        delete [] w;\n        return 0;\n        }\n\n    SquareMatrix * Zinv = Z->Inverse();\n    SquareMatrix * Lp = new SquareMatrix(dim, 0.0);\n\n    // create diagonal matrix of scaled eigenvalues\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        double v = pow(w[i],p);\n        Lp->SetElement(i, i, v);\n        }\n\n    // Zinv * A * Z = L\n    //            A = Z * L * Zinv\n    //          A^p = Z * L^p * Zinv\n    SquareMatrix * ZLp = Z->RightMultiplyMatrix(*Lp);\n    SquareMatrix * Ap = ZLp->RightMultiplyMatrix(*Zinv);\n\n    delete Z;\n    delete Zinv;\n    delete Lp;\n    delete ZLp;\n    delete [] fv;\n    delete [] w;\n\n    return Ap;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates and returns a matrix that represents the inverse of this SquareMatrix.\n*/\nSquareMatrix * SquareMatrix::Inverse() const\n    {\n    double * col = new double[dim];\n    int * permutation = new int[dim];\n    SquareMatrix * tmp = new SquareMatrix(*this);\n    double ** a = tmp->GetMatrixAsRawPointer();\n    SquareMatrix * inv = new SquareMatrix(*this);\n    double ** a_inv = inv->GetMatrixAsRawPointer();\n\n    // double **  a           matrix represented as vector of row pointers\n    // int        n           order of matrix\n    // double *   col         work vector of size n\n    // int *      permutation work vector of size n\n    // double **  a_inv       inverse of input matrix a (matrix a is destroyed)\n    int result = InvertMatrix(a, dim, col, permutation, a_inv);\n    delete tmp;\n    delete [] col;\n    delete [] permutation;\n    if (result != 0)\n        {\n        delete inv;\n        return 0;\n        }\n    return inv;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates and returns a matrix that represents the product of `matrixOnLeft' with this matrix.\n*/\nSquareMatrix * SquareMatrix::LeftMultiplyMatrix(SquareMatrix & matrixOnLeft) const\n    {\n    double ** l = matrixOnLeft.GetMatrixAsRawPointer();\n    double ** r = GetMatrixAsRawPointer();\n    SquareMatrix * tmp = new SquareMatrix(*this);\n    double ** t = tmp->GetMatrixAsRawPointer();\n\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        for (unsigned j = 0; j < dim; ++j)\n            {\n            double vsum = 0.0;\n            for (unsigned k = 0; k < dim; ++k)\n                {\n                vsum += l[i][k]*r[k][j];\n                }\n            t[i][j] = vsum;\n            }\n        }\n    return tmp;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates and returns a matrix that represents the product of this matrix with `matrixOnRight'.\n*/\nSquareMatrix * SquareMatrix::RightMultiplyMatrix(SquareMatrix & matrixOnRight) const\n    {\n    double ** l = GetMatrixAsRawPointer();\n    double ** r = matrixOnRight.GetMatrixAsRawPointer();\n    SquareMatrix * tmp = new SquareMatrix(*this);\n    double ** t = tmp->GetMatrixAsRawPointer();\n\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        for (unsigned j = 0; j < dim; ++j)\n            {\n            double vsum = 0.0;\n            for (unsigned k = 0; k < dim; ++k)\n                {\n                vsum += l[i][k]*r[k][j];\n                }\n            t[i][j] = vsum;\n            }\n        }\n    return tmp;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates and returns a matrix that represents the product of  (transposed) `vectorOnLeft' (1xdim) and this\n|   matrix (dimxdim). Returns transposed vector (1xdim).\n*/\nstd::vector<double> SquareMatrix::LeftMultiplyVector(const std::vector<double> & vectorOnLeft) const\n    {\n    double ** r = GetMatrixAsRawPointer();\n    //work.clear();\n    std::vector<double> tmp;\n\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        double vsum = 0.0;\n        for (unsigned k = 0; k < dim; ++k)\n            {\n            vsum += vectorOnLeft[k]*r[k][i];\n            }\n        tmp.push_back(vsum);\n        }\n    return tmp;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCreates and returns a matrix that represents the product of this matrix (dimxdim)with `vectorOnRight' (dimx1).\n|   Returns vector (dimx1).\n*/\nstd::vector<double> SquareMatrix::RightMultiplyVector(const std::vector<double> & vectorOnRight) const\n    {\n    double ** l = GetMatrixAsRawPointer();\n    //work.clear();\n    std::vector<double> tmp;\n\n    for (unsigned i = 0; i < dim; ++i)\n        {\n        double vsum = 0.0;\n        for (unsigned k = 0; k < dim; ++k)\n            {\n            vsum += l[i][k]*vectorOnRight[k];\n            }\n        tmp.push_back(vsum);\n        }\n    return tmp;\n    }\n\n\n} // namespace phycas\n", "meta": {"hexsha": "f7fd1147a1889da818be8d2e8dad5e43de19f517", "size": 23237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/square_matrix.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/square_matrix.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/square_matrix.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 34.3234859675, "max_line_length": 153, "alphanum_fraction": 0.4739854542, "num_tokens": 5396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.05665242968796326, "lm_q1q2_score": 0.024803764999305367}}
{"text": "//\n// Created by robin on 2018/9/1.\n// Copyright (c) 2018 Robin. All rights reserved.\n//\n\n#include \"polynomial.h\"\n#include \"bytes.h\"\n\n#include <boost/lexical_cast.hpp>\n#include <experimental/iterator>\n\nnamespace satz::gf2::v2 {\n\nPolynomial Polynomial::from_ulong (unsigned long l) {\n  static_assert(sizeof(l) == 8);\n  uint8_t* start = reinterpret_cast<uint8_t*>(&l);\n  return from_bytes({start, start + sizeof(l)});\n}\n\nPolynomial Polynomial::from_bytes (gsl::span<uint8_t> bytes) {\n  return Polynomial(satz::bytes::make_indices<int_type>(bytes));\n}\n\nPolynomial Polynomial::from_bytes (gsl::span<uint8_t> bytes,\n    Polynomial::int_type degree) {\n\n  Expects(bytes.size() * 8 > degree);\n\n  std::vector<int_type> d = satz::bytes::make_indices<int_type>(bytes);\n  auto it = std::lower_bound(d.begin(), d.end(), degree);\n  if (it == d.end() || *it != degree) {\n    d.erase(it, d.end());\n    d.push_back(static_cast<int>(degree));\n  } else { // `*it == degree`\n    std::advance(it, 1);\n    d.erase(it, d.end());\n  }\n\n  return Polynomial(std::move(d));\n}\n\nPolynomial Polynomial::make_random (Polynomial::int_type degree) {\n  auto bytes = satz::bytes::make_random_bytes(static_cast<int>(degree / 8 + 1));\n  return Polynomial::from_bytes(bytes, degree);\n}\n\nPolynomial Polynomial::make_irreducible (Polynomial::int_type degree) {\n  Expects(degree > 0);\n\n  // According to\n  //    Some applications of Rabin’s fingerprinting method [Broder],\n  // the total number of irreducible polynomials of degree $k$ with\n  // coefficients in $Z_2$ is greater than $(2^k - 2^{k/2})/k$. Thus\n  // the probability of picking an irreducible polynomial with a\n  // uniformly random draw is roughly greater than $1/k$. If we try\n  // $m$ independent draws, the probability of failing to obtain an\n  // irreducible polynomial is roughly less than $(1 - 1/k)^m$, which\n  // is roughly $e^{-m/k}$.\n  int magic_number = 15;\n  auto trials = degree * magic_number;\n  while (trials-- > 0) {\n    auto p = Polynomial::make_random(degree);\n    if (is_irreducible(p)) return p;\n  }\n\n  throw std::runtime_error(\"fail to obtain an irreducible polynomial\");\n}\n\nstd::vector<uint8_t> Polynomial::to_bytes () const {\n  const int d = degree();\n  const size_t count = (d >= 0) ? (d / 8 + 1) : 0;\n\n  std::vector<uint8_t> ret(count, 0);\n  std::for_each(deg_.begin(),\n                deg_.end(),\n                [&] (int_type n) {\n                  const auto i = n / 8;\n                  const auto j = n % 8;\n                  ret[i] = ret[i] | uint8_t(0x1 << j);\n                });\n  return ret;\n}\n\nPolynomial::operator bool () const {return !empty();}\n\nbool operator == (const Polynomial& lhs, const Polynomial& rhs) {\n  return lhs.deg_ == rhs.deg_;\n}\n\nbool operator != (const Polynomial& lhs, const Polynomial& rhs) {\n  return !(rhs == lhs);\n}\n\nPolynomial& Polynomial::operator ^= (const Polynomial& rhs) {\n  Polynomial res = *this ^rhs;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial& Polynomial::operator |= (const Polynomial& rhs) {\n  Polynomial res = *this | rhs;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial& Polynomial::operator &= (const Polynomial& rhs) {\n  Polynomial res = *this & rhs;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial& Polynomial::operator += (const Polynomial& rhs) {\n  Polynomial res = *this + rhs;\n  deg_.swap(res.deg_);\n  return *this;\n\n}\n\nPolynomial& Polynomial::operator -= (const Polynomial& rhs) {\n  Polynomial res = *this - rhs;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial& Polynomial::operator *= (const Polynomial& rhs) {\n  Polynomial res = *this * rhs;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial& Polynomial::operator %= (const Polynomial& rhs) {\n  Polynomial res = *this % rhs;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial& Polynomial::operator <<= (Polynomial::int_type n) {\n  Expects(n >= 0);\n  Polynomial res = *this << n;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial& Polynomial::operator >>= (Polynomial::int_type n) {\n  Expects(n >= 0);\n  Polynomial res = *this >> n;\n  deg_.swap(res.deg_);\n  return *this;\n}\n\nPolynomial operator ^ (const Polynomial& lhs, const Polynomial& rhs) {\n  Polynomial ret;\n  std::set_symmetric_difference(lhs.deg_.begin(),\n                                lhs.deg_.end(),\n                                rhs.deg_.begin(),\n                                rhs.deg_.end(),\n                                std::back_inserter(ret.deg_));\n  return ret;\n}\n\nPolynomial operator | (const Polynomial& lhs, const Polynomial& rhs) {\n  Polynomial ret;\n  std::set_union(lhs.deg_.begin(),\n                 lhs.deg_.end(),\n                 rhs.deg_.begin(),\n                 rhs.deg_.end(),\n                 std::back_inserter(ret.deg_));\n  return ret;\n}\n\nPolynomial operator & (const Polynomial& lhs, const Polynomial& rhs) {\n  Polynomial ret;\n  std::set_intersection(lhs.deg_.begin(),\n                        lhs.deg_.end(),\n                        rhs.deg_.begin(),\n                        rhs.deg_.end(),\n                        std::back_inserter(ret.deg_));\n  return ret;\n}\n\nPolynomial operator + (const Polynomial& lhs, const Polynomial& rhs) {\n  return lhs ^ rhs;\n}\n\nPolynomial operator - (const Polynomial& lhs, const Polynomial& rhs) {\n  return lhs ^ rhs;\n}\n\ntemplate<typename T, typename N>\nstatic void flip (std::vector<T>& bytes, N n) {\n  bytes[n / 8] ^= (1 << (n % 8));\n}\n\nPolynomial operator * (const Polynomial& lhs, const Polynomial& rhs) {\n  if (lhs.degree() == 0 || rhs.degree() == 0) return Polynomial{};\n\n  auto degree_sum = lhs.degree() + rhs.degree();\n  std::vector<uint8_t> bytes(degree_sum / 8 + 1, 0);\n  for (const auto& x : lhs.deg_)\n    for (const auto& y : rhs.deg_)\n      flip(bytes, x + y);\n  return Polynomial::from_bytes(bytes);\n}\n\nPolynomial Polynomial::operator << (Polynomial::int_type n) const {\n  Expects(n >= 0);\n\n  Polynomial ret;\n  std::transform(deg_.begin(),\n                 deg_.end(),\n                 std::back_inserter(ret.deg_),\n                 [&n] (const auto& m) {return m + n;});\n  return ret;\n}\n\nPolynomial Polynomial::operator >> (Polynomial::int_type n) const {\n  Expects(n >= 0);\n\n  Polynomial ret;\n  auto start = std::find_if(deg_.begin(),\n                            deg_.end(),\n                            [&n] (const auto& m) {return m > n;});\n  std::transform(start,\n                 deg_.end(),\n                 std::back_inserter(ret.deg_),\n                 [&n] (const auto& m) {return m - n;});\n  return ret;\n}\n\nPolynomial operator % (const Polynomial& lhs, const Polynomial& rhs) {\n\n  Polynomial ret{lhs};\n\n  using N = Polynomial::int_type;\n  const N dl = lhs.degree();\n  const N dr = rhs.degree();\n\n  if (dl >= dr) {\n    N i = dl - dr;\n    do {\n      if (ret.contains(i + dr)) ret -= (rhs << i);\n    } while (N(0) != i--);\n  }\n\n  return ret;\n}\n\nstd::ostream& operator << (std::ostream& os, const Polynomial& obj) {\n  // @formatter:off\n  auto to_string = [] (const auto& n) {\n    return\n      n > 1 ? (\"x^\" + boost::lexical_cast<std::string>(n)) :\n      n == 1 ? \"x\" :\n      n == 0 ? \"1\" :\n      throw std::runtime_error(\"n should be nonnegative\");\n  };\n  // @formatter:on\n\n  const auto& d = obj.deg_;\n  if (d.empty()) {\n    os << \"0\";\n  } else {\n    std::transform(d.rbegin(),\n                   d.rend(),\n                   std::experimental::make_ostream_joiner(os, \"+\"),\n                   to_string);\n  }\n  return os;\n}\n\nbool Polynomial::empty () const {return deg_.empty();}\n\nPolynomial::int_type Polynomial::degree () const {\n  return empty() ? -1 : *deg_.rbegin();\n}\n\nPolynomial::int_type Polynomial::nnz () const {\n  return static_cast<int_type>(deg_.size());\n}\n\nbool Polynomial::contains (Polynomial::int_type n) const {\n  return std::binary_search(deg_.begin(), deg_.end(), n);\n}\n\nPolynomial::Polynomial (Polynomial::container_type&& v) : deg_(std::move(v)) {\n  Expects(std::all_of(deg_.begin(),\n                      deg_.end(),\n                      [] (const auto& n) {return n >= 0;}));\n  Expects(std::is_sorted(deg_.begin(), deg_.end()));\n}\n\nbool operator < (const Polynomial& lhs, const Polynomial& rhs) {\n  return std::lexicographical_compare(lhs.deg_.rbegin(),\n                                      lhs.deg_.rend(),\n                                      rhs.deg_.rbegin(),\n                                      rhs.deg_.rend());\n}\n\nbool operator > (const Polynomial& lhs, const Polynomial& rhs) {\n  return rhs < lhs;\n}\n\nbool operator <= (const Polynomial& lhs, const Polynomial& rhs) {\n  return !(rhs < lhs);\n}\n\nbool operator >= (const Polynomial& lhs, const Polynomial& rhs) {\n  return !(lhs < rhs);\n}\n\n}", "meta": {"hexsha": "7a3a95eb68c2ff496a7be2e7f45318ada61252a4", "size": 8556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/polynomial.cpp", "max_stars_repo_name": "lie-yan/rabin-fingerprint", "max_stars_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "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/polynomial.cpp", "max_issues_repo_name": "lie-yan/rabin-fingerprint", "max_issues_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomial.cpp", "max_forks_repo_name": "lie-yan/rabin-fingerprint", "max_forks_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T11:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T11:41:15.000Z", "avg_line_length": 27.5112540193, "max_line_length": 80, "alphanum_fraction": 0.5951379149, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.05033063580254644, "lm_q1q2_score": 0.02477214180529766}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012-20 John Maddock. \n//  Copyright 2019-20 Christopher Kormanyos. \n//  Copyright 2019-20 Madhur Chauhan. \n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n//\n// Comparison operators for cpp_int_backend:\n//\n#ifndef BOOST_MP_CPP_INT_MUL_HPP\n#define BOOST_MP_CPP_INT_MUL_HPP\n\n#include <limits>\n#include <boost/multiprecision/detail/standalone_config.hpp>\n#include <boost/multiprecision/detail/endian.hpp>\n#include <boost/multiprecision/detail/assert.hpp>\n#include <boost/multiprecision/integer.hpp>\n\nnamespace boost { namespace multiprecision { namespace backends {\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4127) // conditional expression is constant\n#endif\n//\n// Multiplication by a single limb:\n//\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n    const limb_type&                                                            val) noexcept((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   if (!val)\n   {\n      result = static_cast<limb_type>(0);\n      return;\n   }\n   if ((void*)&a != (void*)&result)\n      result.resize(a.size(), a.size());\n   double_limb_type                                                                                  carry = 0;\n   typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_pointer       p     = result.limbs();\n   typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_pointer       pe    = result.limbs() + result.size();\n   typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::const_limb_pointer pa    = a.limbs();\n   while (p != pe)\n   {\n      carry += static_cast<double_limb_type>(*pa) * static_cast<double_limb_type>(val);\n#ifdef __MSVC_RUNTIME_CHECKS\n      *p = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n#else\n      *p = static_cast<limb_type>(carry);\n#endif\n      carry >>= cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n      ++p, ++pa;\n   }\n   if (carry)\n   {\n      std::size_t i = result.size();\n      result.resize(i + 1, i + 1);\n      if (result.size() > i)\n         result.limbs()[i] = static_cast<limb_type>(carry);\n   }\n   result.sign(a.sign());\n   if (is_fixed_precision<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value)\n      result.normalize();\n}\n\n//\n// resize_for_carry forces a resize of the underlying buffer only if a previous request\n// for \"required\" elements could possibly have failed, *and* we have checking enabled.\n// This will cause an overflow error inside resize():\n//\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline BOOST_MP_CXX14_CONSTEXPR void resize_for_carry(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& /*result*/, std::size_t /*required*/) {}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, class Allocator1>\ninline BOOST_MP_CXX14_CONSTEXPR void resize_for_carry(cpp_int_backend<MinBits1, MaxBits1, SignType1, checked, Allocator1>& result, std::size_t required)\n{\n   if (result.size() < required)\n      result.resize(required, required);\n}\n//\n// Minimum number of limbs required for Karatsuba to be worthwhile:\n//\n#ifdef BOOST_MP_KARATSUBA_CUTOFF\nconst size_t karatsuba_cutoff = BOOST_MP_KARATSUBA_CUTOFF;\n#else\nconst size_t karatsuba_cutoff = 40;\n#endif\n//\n// Core (recursive) Karatsuba multiplication, all the storage required is allocated upfront and \n// passed down the stack in this routine.  Note that all the cpp_int_backend's must be the same type\n// and full variable precision.  Karatsuba really doesn't play nice with fixed-size integers.  If necessary\n// fixed precision integers will get aliased as variable-precision types before this is called.\n//\ntemplate <std::size_t MinBits, std::size_t MaxBits, cpp_int_check_type Checked, class Allocator>\ninline void multiply_karatsuba(\n    cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, Allocator>&       result,\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, Allocator>& a,\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, Allocator>& b,\n    typename cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, Allocator>::scoped_shared_storage& storage)\n{\n   using cpp_int_type = cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, Allocator>;\n\n   std::size_t as = a.size();\n   std::size_t bs = b.size();\n   //\n   // Termination condition: if either argument is smaller than karatsuba_cutoff\n   // then schoolboy multiplication will be faster:\n   //\n   if ((as < karatsuba_cutoff) || (bs < karatsuba_cutoff))\n   {\n      eval_multiply(result, a, b);\n      return;\n   }\n   //\n   // Partitioning size: split the larger of a and b into 2 halves\n   //\n   std::size_t n  = (as > bs ? as : bs) / 2 + 1;\n   //\n   // Partition a and b into high and low parts.\n   // ie write a, b as a = a_h * 2^n + a_l, b = b_h * 2^n + b_l\n   //\n   // We could copy the high and low parts into new variables, but we'll\n   // use aliasing to reference the internal limbs of a and b.  There is one wart here:\n   // if a and b are mismatched in size, then n may be larger than the smaller\n   // of a and b.  In that situation the high part is zero, and we have no limbs\n   // to alias, so instead alias a local variable.\n   // This raises 2 questions:\n   // * Is this the best way to partition a and b?\n   // * Since we have one high part zero, the arithmetic simplifies considerably, \n   //   so should we have a special routine for this?\n   // \n   std::size_t          sz = (std::min)(as, n);\n   const cpp_int_type a_l(a.limbs(), 0, sz);\n\n   sz = (std::min)(bs, n);\n   const cpp_int_type b_l(b.limbs(), 0, sz);\n\n   limb_type          zero = 0;\n   const cpp_int_type a_h(as > n ? a.limbs() + n : &zero, 0, as > n ? as - n : 1);\n   const cpp_int_type b_h(bs > n ? b.limbs() + n : &zero, 0, bs > n ? bs - n : 1);\n   //\n   // The basis for the Karatsuba algorithm is as follows:\n   //\n   // let                x = a_h * b_ h\n   //                    y = a_l * b_l\n   //                    z = (a_h + a_l)*(b_h + b_l) - x - y\n   // and therefore  a * b = x * (2 ^ (2 * n))+ z * (2 ^ n) + y\n   //\n   // Begin by allocating our temporaries, these alias the memory already allocated in the shared storage:\n   //\n   cpp_int_type t1(storage, 2 * n + 2);\n   cpp_int_type t2(storage, n + 1);\n   cpp_int_type t3(storage, n + 1);\n   //\n   // Now we want:\n   //\n   // result = | a_h*b_h  | a_l*b_l |\n   // (bits)              <-- 2*n -->\n   //\n   // We create aliases for the low and high parts of result, and multiply directly into them:\n   //\n   cpp_int_type result_low(result.limbs(), 0, 2 * n);\n   cpp_int_type result_high(result.limbs(), 2 * n, result.size() - 2 * n);\n   //\n   // low part of result is a_l * b_l:\n   //\n   multiply_karatsuba(result_low, a_l, b_l, storage);\n   //\n   // We haven't zeroed out memory in result, so set to zero any unused limbs,\n   // if a_l and b_l have mostly random bits then nothing happens here, but if\n   // one is zero or nearly so, then a memset might be faster... it's not clear\n   // that it's worth the extra logic though (and is darn hard to measure\n   // what the \"average\" case is).\n   //\n   for (std::size_t i = result_low.size(); i < 2 * n; ++i)\n      result.limbs()[i] = 0;\n   //\n   // Set the high part of result to a_h * b_h:\n   //\n   multiply_karatsuba(result_high, a_h, b_h, storage);\n   for (std::size_t i = result_high.size() + 2 * n; i < result.size(); ++i)\n      result.limbs()[i] = 0;\n   //\n   // Now calculate (a_h+a_l)*(b_h+b_l):\n   //\n   add_unsigned(t2, a_l, a_h);\n   add_unsigned(t3, b_l, b_h);\n   multiply_karatsuba(t1, t2, t3, storage); // t1 = (a_h+a_l)*(b_h+b_l)\n   //\n   // There is now a slight deviation from Karatsuba, we want to subtract\n   // a_l*b_l + a_h*b_h from t1, but rather than use an addition and a subtraction\n   // plus one temporary, we'll use 2 subtractions.  On the minus side, a subtraction\n   // is on average slightly slower than an addition, but we save a temporary (ie memory)\n   // and also hammer the same piece of memory over and over rather than 2 disparate\n   // memory regions.  Overall it seems to be a slight win.\n   //\n   subtract_unsigned(t1, t1, result_high);\n   subtract_unsigned(t1, t1, result_low);\n   //\n   // The final step is to left shift t1 by n bits and add to the result.\n   // Rather than do an actual left shift, we can simply alias the result\n   // and add to the alias:\n   //\n   cpp_int_type result_alias(result.limbs(), n, result.size() - n);\n   add_unsigned(result_alias, result_alias, t1);\n   //\n   // Free up storage for use by sister branches to this one:\n   //\n   storage.deallocate(t1.capacity() + t2.capacity() + t3.capacity());\n\n   result.normalize();\n}\n\ninline std::size_t karatsuba_storage_size(std::size_t s)\n{\n   // \n   // This estimates how much memory we will need based on\n   // s-limb multiplication.  In an ideal world the number of limbs\n   // would halve with each recursion, and our storage requirements\n   // would be 4s in the limit, and rather less in practice since\n   // we bail out long before we reach one limb.  In the real world\n   // we don't quite halve s in each recursion, so this is an heuristic\n   // which over-estimates how much we need.  We could compute an exact\n   // value, but it would be rather time consuming.\n   //\n   return 5 * s;\n}\n//\n// There are 2 entry point routines for Karatsuba multiplication:\n// one for variable precision types, and one for fixed precision types.\n// These are responsible for allocating all the storage required for the recursive\n// routines above, and are always at the outermost level.\n//\n// Normal variable precision case comes first:\n//\ntemplate <std::size_t MinBits, std::size_t MaxBits, cpp_integer_type SignType, cpp_int_check_type Checked, class Allocator>\ninline typename std::enable_if<!is_fixed_precision<cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> >::value>::type\nsetup_karatsuba(\n   cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>& result,\n   const cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>& a,\n   const cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>& b)\n{\n   std::size_t as = a.size();\n   std::size_t bs = b.size();\n   std::size_t s = as > bs ? as : bs;\n   std::size_t storage_size = karatsuba_storage_size(s);\n   if (storage_size < 300)\n   {\n      //\n      // Special case: if we don't need too much memory, we can use stack based storage\n      // and save a call to the allocator, this allows us to use Karatsuba multiply\n      // at lower limb counts than would otherwise be possible:\n      //\n      limb_type limbs[300];\n      typename cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>::scoped_shared_storage storage(limbs, storage_size);\n      multiply_karatsuba(result, a, b, storage);\n   }\n   else\n   {\n      typename cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>::scoped_shared_storage storage(result.allocator(), storage_size);\n      multiply_karatsuba(result, a, b, storage);\n   }\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2, std::size_t MinBits3, std::size_t MaxBits3, cpp_integer_type SignType3, cpp_int_check_type Checked3, class Allocator3>\ninline typename std::enable_if<is_fixed_precision<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value || is_fixed_precision<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value || is_fixed_precision<cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3> >::value>::type\nsetup_karatsuba(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n    const cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>& b)\n{\n   //\n   // Now comes the fixed precision case.\n   // In fact Karatsuba doesn't really work with fixed precision since the logic\n   // requires that we calculate all the bits of the result (especially in the\n   // temporaries used internally).  So... we'll convert all the arguments\n   // to variable precision types by aliasing them, this also\n   // reduce the number of template instantations:\n   //\n   using variable_precision_type = cpp_int_backend<0, 0, signed_magnitude, unchecked, std::allocator<limb_type> >;\n   variable_precision_type a_t(a.limbs(), 0, a.size()), b_t(b.limbs(), 0, b.size());\n   std::size_t as = a.size();\n   std::size_t bs = b.size();\n   std::size_t s = as > bs ? as : bs;\n   std::size_t sz = as + bs;\n   std::size_t storage_size = karatsuba_storage_size(s);\n\n   if (!is_fixed_precision<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value || (sz * sizeof(limb_type) * CHAR_BIT <= MaxBits1))\n   {\n      // Result is large enough for all the bits of the result, so we can use aliasing:\n      result.resize(sz, sz);\n      variable_precision_type t(result.limbs(), 0, result.size());\n      typename variable_precision_type::scoped_shared_storage storage(t.allocator(), storage_size);\n      multiply_karatsuba(t, a_t, b_t, storage);\n      result.resize(t.size(), t.size());\n   }\n   else\n   {\n      //\n      // Not enough bit in result for the answer, so we must use a temporary\n      // and then truncate (ie modular arithmetic):\n      //\n      typename variable_precision_type::scoped_shared_storage storage(variable_precision_type::allocator_type(), sz + storage_size);\n      variable_precision_type t(storage, sz);\n      multiply_karatsuba(t, a_t, b_t, storage);\n      //\n      // If there is truncation, and result is a checked type then this will throw:\n      //\n      result = t;\n   }\n}\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2, std::size_t MinBits3, std::size_t MaxBits3, cpp_integer_type SignType3, cpp_int_check_type Checked3, class Allocator3>\ninline typename std::enable_if<!is_fixed_precision<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_fixed_precision<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value && !is_fixed_precision<cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3> >::value>::type\nsetup_karatsuba(\n   cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,\n   const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n   const cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>& b)\n{\n   //\n   // Variable precision, mixed arguments, just alias and forward:\n   //\n   using variable_precision_type = cpp_int_backend<0, 0, signed_magnitude, unchecked, std::allocator<limb_type> >;\n   variable_precision_type a_t(a.limbs(), 0, a.size()), b_t(b.limbs(), 0, b.size());\n   std::size_t as = a.size();\n   std::size_t bs = b.size();\n   std::size_t s = as > bs ? as : bs;\n   std::size_t sz = as + bs;\n   std::size_t storage_size = karatsuba_storage_size(s);\n\n   result.resize(sz, sz);\n   variable_precision_type t(result.limbs(), 0, result.size());\n   typename variable_precision_type::scoped_shared_storage storage(t.allocator(), storage_size);\n   multiply_karatsuba(t, a_t, b_t, storage);\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2, std::size_t MinBits3, std::size_t MaxBits3, cpp_integer_type SignType3, cpp_int_check_type Checked3, class Allocator3>\ninline BOOST_MP_CXX14_CONSTEXPR void\neval_multiply_comba(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n    const cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>& b) noexcept((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   // \n   // see PR #182\n   // Comba Multiplier - based on Paul Comba's\n   // Exponentiation cryptosystems on the IBM PC, 1990\n   //\n   std::ptrdiff_t as                                                                                         = a.size(),\n       bs                                                                                         = b.size(),\n       rs                                                                                         = result.size();\n   typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_pointer pr = result.limbs();\n\n   double_limb_type carry    = 0,\n                    temp     = 0;\n   limb_type      overflow   = 0;\n   const std::size_t limb_bits  = sizeof(limb_type) * CHAR_BIT;\n   const bool     must_throw = rs < as + bs - 1;\n   for (std::ptrdiff_t r = 0, lim = (std::min)(rs, as + bs - 1); r < lim; ++r, overflow = 0)\n   {\n      std::ptrdiff_t i = r >= as ? as - 1 : r,\n          j = r - i,\n          k = i < bs - j ? i + 1 : bs - j; // min(i+1, bs-j);\n\n      typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::const_limb_pointer pa = a.limbs() + i;\n      typename cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>::const_limb_pointer pb = b.limbs() + j;\n\n      temp = carry;\n      carry += static_cast<double_limb_type>(*(pa)) * (*(pb));\n      overflow += carry < temp;\n      for (--k; k; k--)\n      {\n         temp = carry;\n         carry += static_cast<double_limb_type>(*(--pa)) * (*(++pb));\n         overflow += carry < temp;\n      }\n      *(pr++) = static_cast<limb_type>(carry);\n      carry   = (static_cast<double_limb_type>(overflow) << limb_bits) | (carry >> limb_bits);\n   }\n   if (carry || must_throw)\n   {\n      resize_for_carry(result, as + bs);\n      if (static_cast<int>(result.size()) >= as + bs)\n         *pr = static_cast<limb_type>(carry);\n   }\n}\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2, std::size_t MinBits3, std::size_t MaxBits3, cpp_integer_type SignType3, cpp_int_check_type Checked3, class Allocator3>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n    const cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>& b) \n   noexcept((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value \n      && (karatsuba_cutoff * sizeof(limb_type) * CHAR_BIT > MaxBits1) \n      && (karatsuba_cutoff * sizeof(limb_type)* CHAR_BIT > MaxBits2) \n      && (karatsuba_cutoff * sizeof(limb_type)* CHAR_BIT > MaxBits3)))\n{\n   // Uses simple (O(n^2)) multiplication when the limbs are less\n   // otherwise switches to karatsuba algorithm based on experimental value (~40 limbs)\n   //\n   // Trivial cases first:\n   //\n   std::size_t                                                                                          as = a.size();\n   std::size_t                                                                                          bs = b.size();\n   typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::const_limb_pointer pa = a.limbs();\n   typename cpp_int_backend<MinBits3, MaxBits3, SignType3, Checked3, Allocator3>::const_limb_pointer pb = b.limbs();\n   if (as == 1)\n   {\n      bool s = b.sign() != a.sign();\n      if (bs == 1)\n      {\n         result = static_cast<double_limb_type>(*pa) * static_cast<double_limb_type>(*pb);\n      }\n      else\n      {\n         limb_type l = *pa;\n         eval_multiply(result, b, l);\n      }\n      result.sign(s);\n      return;\n   }\n   if (bs == 1)\n   {\n      bool      s = b.sign() != a.sign();\n      limb_type l = *pb;\n      eval_multiply(result, a, l);\n      result.sign(s);\n      return;\n   }\n\n   if ((void*)&result == (void*)&a)\n   {\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(a);\n      eval_multiply(result, t, b);\n      return;\n   }\n   if ((void*)&result == (void*)&b)\n   {\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(b);\n      eval_multiply(result, a, t);\n      return;\n   }\n\n   constexpr const double_limb_type limb_max = ~static_cast<limb_type>(0u);\n   constexpr const double_limb_type double_limb_max = ~static_cast<double_limb_type>(0u);\n\n   result.resize(as + bs, as + bs - 1);\n#ifndef BOOST_MP_NO_CONSTEXPR_DETECTION\n   if (!BOOST_MP_IS_CONST_EVALUATED(as) && (as >= karatsuba_cutoff && bs >= karatsuba_cutoff))\n#else\n   if (as >= karatsuba_cutoff && bs >= karatsuba_cutoff)\n#endif\n   {\n      setup_karatsuba(result, a, b);\n      //\n      // Set the sign of the result:\n      //\n      result.sign(a.sign() != b.sign());\n      return;\n   }\n   typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_pointer pr = result.limbs();\n   static_assert(double_limb_max - 2 * limb_max >= limb_max * limb_max, \"failed limb size sanity check\");\n\n#ifndef BOOST_MP_NO_CONSTEXPR_DETECTION\n   if (BOOST_MP_IS_CONST_EVALUATED(as))\n   {\n      for (std::size_t i = 0; i < result.size(); ++i)\n         pr[i] = 0;\n   }\n   else\n#endif\n   std::memset(pr, 0, result.size() * sizeof(limb_type));   \n\n#if defined(BOOST_MP_COMBA)\n       // \n       // Comba Multiplier might not be efficient because of less efficient assembly\n       // by the compiler as of 09/01/2020 (DD/MM/YY). See PR #182\n       // Till then this will lay dormant :(\n       //\n       eval_multiply_comba(result, a, b);\n#else\n\n   double_limb_type carry = 0;\n   for (std::size_t i = 0; i < as; ++i)\n   {\n      BOOST_MP_ASSERT(result.size() > i);\n      std::size_t inner_limit = !is_fixed_precision<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value ? bs : (std::min)(result.size() - i, bs);\n      std::size_t j           = 0;\n      for (; j < inner_limit; ++j)\n      {\n         BOOST_MP_ASSERT(i + j < result.size());\n#if (!defined(__GLIBCXX__) && !defined(__GLIBCPP__)) || !BOOST_WORKAROUND(BOOST_GCC_VERSION, <= 50100)\n         BOOST_MP_ASSERT(!std::numeric_limits<double_limb_type>::is_specialized || ((std::numeric_limits<double_limb_type>::max)() - carry >\n                                                                                 static_cast<double_limb_type>(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::max_limb_value) * static_cast<double_limb_type>(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::max_limb_value)));\n#endif\n         carry += static_cast<double_limb_type>(pa[i]) * static_cast<double_limb_type>(pb[j]);\n         BOOST_MP_ASSERT(!std::numeric_limits<double_limb_type>::is_specialized || ((std::numeric_limits<double_limb_type>::max)() - carry >= pr[i + j]));\n         carry += pr[i + j];\n#ifdef __MSVC_RUNTIME_CHECKS\n         pr[i + j] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n#else\n         pr[i + j] = static_cast<limb_type>(carry);\n#endif\n         carry >>= cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n         BOOST_MP_ASSERT(carry <= (cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::max_limb_value));\n      }\n      if (carry)\n      {\n         resize_for_carry(result, i + j + 1); // May throw if checking is enabled\n         if (i + j < result.size())\n#ifdef __MSVC_RUNTIME_CHECKS\n            pr[i + j] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n#else\n            pr[i + j] = static_cast<limb_type>(carry);\n#endif\n      }\n      carry = 0;\n   }\n#endif // ifdef(BOOST_MP_COMBA) ends\n\n   result.normalize();\n   //\n   // Set the sign of the result:\n   //\n   result.sign(a.sign() != b.sign());\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a) \n   noexcept((noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>&>()))))\n{\n   eval_multiply(result, result, a);\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const limb_type& val) \n   noexcept((noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const limb_type&>()))))\n{\n   eval_multiply(result, result, val);\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n    const double_limb_type&                                                     val) \n   noexcept(\n      (noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>&>(), std::declval<const limb_type&>())))\n      && (noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>())))\n   )\n{\n   if (val <= (std::numeric_limits<limb_type>::max)())\n   {\n      eval_multiply(result, a, static_cast<limb_type>(val));\n   }\n   else\n   {\n#if BOOST_MP_ENDIAN_LITTLE_BYTE && !defined(BOOST_MP_TEST_NO_LE)\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(val);\n#else\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t;\n      t = val;\n#endif\n      eval_multiply(result, a, t);\n   }\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const double_limb_type& val)\n   noexcept((noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const double_limb_type&>()))))\n{\n   eval_multiply(result, result, val);\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n    const signed_limb_type&                                                     val) \n   noexcept((noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>&>(), std::declval<const limb_type&>()))))\n{\n   if (val > 0)\n      eval_multiply(result, a, static_cast<limb_type>(val));\n   else\n   {\n      eval_multiply(result, a, static_cast<limb_type>(boost::multiprecision::detail::unsigned_abs(val)));\n      result.negate();\n   }\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const signed_limb_type& val)\n   noexcept((noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const limb_type&>()))))\n{\n   eval_multiply(result, result, val);\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>& a,\n    const signed_double_limb_type&                                              val)\n   noexcept(\n   (noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>&>(), std::declval<const limb_type&>())))\n      && (noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>())))\n   )\n{\n   if (val > 0)\n   {\n      if (val <= (std::numeric_limits<limb_type>::max)())\n      {\n         eval_multiply(result, a, static_cast<limb_type>(val));\n         return;\n      }\n   }\n   else if (val >= -static_cast<signed_double_limb_type>((std::numeric_limits<limb_type>::max)()))\n   {\n      eval_multiply(result, a, static_cast<limb_type>(boost::multiprecision::detail::unsigned_abs(val)));\n      result.negate();\n      return;\n   }\n#if BOOST_MP_ENDIAN_LITTLE_BYTE && !defined(BOOST_MP_TEST_NO_LE)\n   cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(val);\n#else\n   cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t;\n   t = val;\n#endif\n   eval_multiply(result, a, t);\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const signed_double_limb_type& val)\n   noexcept(\n   (noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const limb_type&>())))\n   && (noexcept(eval_multiply(std::declval<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>(), std::declval<const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&>())))\n   )\n{\n   eval_multiply(result, result, val);\n}\n\n//\n// Now over again for trivial cpp_int's:\n//\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && (is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value || is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value)>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& o) noexcept((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   *result.limbs() = detail::checked_multiply(*result.limbs(), *o.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());\n   result.sign(result.sign() != o.sign());\n   result.normalize();\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && is_unsigned_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& o) noexcept((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   *result.limbs() = detail::checked_multiply(*result.limbs(), *o.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());\n   result.normalize();\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && (is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value || is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value)>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a,\n    const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b) noexcept((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   *result.limbs() = detail::checked_multiply(*a.limbs(), *b.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());\n   result.sign(a.sign() != b.sign());\n   result.normalize();\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && is_unsigned_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a,\n    const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b) noexcept((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   *result.limbs() = detail::checked_multiply(*a.limbs(), *b.limbs(), typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());\n   result.normalize();\n}\n\n//\n// Special routines for multiplying two integers to obtain a multiprecision result:\n//\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,\n    signed_double_limb_type a, signed_double_limb_type b)\n{\n   constexpr const signed_double_limb_type mask = ~static_cast<limb_type>(0);\n   constexpr const std::size_t limb_bits = sizeof(limb_type) * CHAR_BIT;\n\n   bool s = false;\n   if (a < 0)\n   {\n      a = -a;\n      s = true;\n   }\n   if (b < 0)\n   {\n      b = -b;\n      s = !s;\n   }\n   double_limb_type w = a & mask;\n   double_limb_type x = a >> limb_bits;\n   double_limb_type y = b & mask;\n   double_limb_type z = b >> limb_bits;\n\n   result.resize(4, 4);\n   limb_type* pr = result.limbs();\n\n   double_limb_type carry = w * y;\n#ifdef __MSVC_RUNTIME_CHECKS\n   pr[0] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   carry >>= limb_bits;\n   carry += w * z + x * y;\n   pr[1] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   carry >>= limb_bits;\n   carry += x * z;\n   pr[2] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   pr[3] = static_cast<limb_type>(carry >> limb_bits);\n#else\n   pr[0] = static_cast<limb_type>(carry);\n   carry >>= limb_bits;\n   carry += w * z + x * y;\n   pr[1] = static_cast<limb_type>(carry);\n   carry >>= limb_bits;\n   carry += x * z;\n   pr[2] = static_cast<limb_type>(carry);\n   pr[3] = static_cast<limb_type>(carry >> limb_bits);\n#endif\n   result.sign(s);\n   result.normalize();\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,\n    double_limb_type a, double_limb_type b)\n{\n   constexpr const signed_double_limb_type mask = ~static_cast<limb_type>(0);\n   constexpr const std::size_t limb_bits = sizeof(limb_type) * CHAR_BIT;\n\n   double_limb_type w = a & mask;\n   double_limb_type x = a >> limb_bits;\n   double_limb_type y = b & mask;\n   double_limb_type z = b >> limb_bits;\n\n   result.resize(4, 4);\n   limb_type* pr = result.limbs();\n\n   double_limb_type carry = w * y;\n#ifdef __MSVC_RUNTIME_CHECKS\n   pr[0] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   carry >>= limb_bits;\n   carry += w * z;\n   pr[1] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   carry >>= limb_bits;\n   pr[2] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   carry = x * y + pr[1];\n   pr[1] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   carry >>= limb_bits;\n   carry += pr[2] + x * z;\n   pr[2] = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n   pr[3] = static_cast<limb_type>(carry >> limb_bits);\n#else\n   pr[0] = static_cast<limb_type>(carry);\n   carry >>= limb_bits;\n   carry += w * z;\n   pr[1] = static_cast<limb_type>(carry);\n   carry >>= limb_bits;\n   pr[2] = static_cast<limb_type>(carry);\n   carry = x * y + pr[1];\n   pr[1] = static_cast<limb_type>(carry);\n   carry >>= limb_bits;\n   carry += pr[2] + x * z;\n   pr[2] = static_cast<limb_type>(carry);\n   pr[3] = static_cast<limb_type>(carry >> limb_bits);\n#endif\n   result.sign(false);\n   result.normalize();\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1,\n          std::size_t MinBits2, std::size_t MaxBits2, cpp_integer_type SignType2, cpp_int_check_type Checked2, class Allocator2>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value && is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> >::value>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>&       result,\n    cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> const& a,\n    cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2> const& b)\n{\n   using canonical_type = typename boost::multiprecision::detail::canonical<typename cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2, Allocator2>::local_limb_type, cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::type;\n   eval_multiply(result, static_cast<canonical_type>(*a.limbs()), static_cast<canonical_type>(*b.limbs()));\n   result.sign(a.sign() != b.sign());\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class SI>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_signed<SI>::value && boost::multiprecision::detail::is_integral<SI>::value && (sizeof(SI) <= sizeof(signed_double_limb_type) / 2)>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,\n    SI a, SI b)\n{\n   result = static_cast<signed_double_limb_type>(a) * static_cast<signed_double_limb_type>(b);\n}\n\ntemplate <std::size_t MinBits1, std::size_t MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class UI>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_unsigned<UI>::value && (sizeof(UI) <= sizeof(signed_double_limb_type) / 2)>::type\neval_multiply(\n    cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,\n    UI a, UI b)\n{\n   result = static_cast<double_limb_type>(a) * static_cast<double_limb_type>(b);\n}\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n}}} // namespace boost::multiprecision::backends\n\n#endif\n", "meta": {"hexsha": "ad0809288cd362f206268666170d399ddfac3ea3", "size": 45478, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/multiprecision/cpp_int/multiply.hpp", "max_stars_repo_name": "mariospr/multiprecision", "max_stars_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/multiprecision/cpp_int/multiply.hpp", "max_issues_repo_name": "mariospr/multiprecision", "max_issues_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/multiprecision/cpp_int/multiply.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": 53.566548881, "max_line_length": 405, "alphanum_fraction": 0.7064074937, "num_tokens": 12809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.05033063384389279, "lm_q1q2_score": 0.02477214084127157}}
{"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#include <boost/graph/adjacency_list.hpp>\n#include <boost/pending/ct_if.hpp>\n#include <boost/type_traits/same_traits.hpp>\n\nnamespace boost {\n\n  template <class VertexAndEdgeListGraph, class DistanceMatrix,\n            class VertexID, class Weight, class DistanceZero>\n  bool\n  johnson_all_pairs_shortest_paths(VertexAndEdgeListGraph& g1, \n               DistanceMatrix& D,\n               VertexID id1, Weight w1, DistanceZero zero)\n  {\n    typedef graph_traits<VertexAndEdgeListGraph> Traits1;\n    typedef typename property_traits<Weight>::value_type DT;\n    function_requires< BasicMatrixConcept<DistanceMatrix,\n      typename Traits1::vertices_size_type, DT> >();\n\n    typedef typename Traits1::directed_category DirCat;\n    bool is_undirected = is_same<DirCat, undirected_tag>::value;\n\n    typedef adjacency_list<vecS, vecS, directedS, \n      property< vertex_distance_t, DT>,\n      property< edge_weight_t, DT, \n      property< edge_weight2_t, DT > > > Graph2;\n    typedef graph_traits<Graph2> Traits2;\n\n    Graph2 g2(num_vertices(g1) + 1);\n    typename property_map<Graph2, edge_weight_t>::type \n      w = get(edge_weight, g2);\n    typename property_map<Graph2, edge_weight2_t>::type \n      w_hat = get(edge_weight2, g2);\n    typename property_map<Graph2, vertex_distance_t>::type \n      d = get(vertex_distance, g2);\n    typedef typename property_map<Graph2, vertex_index_t>::type VertexID2;\n    VertexID2 id2 = get(vertex_index, g2);\n\n    // Construct g2 where V[g2] = V[g1] U {s}\n    //   and  E[g2] = E[g1] U {(s,v)| v in V[g1]}\n    std::vector<typename Traits1::vertex_descriptor> \n      verts1(num_vertices(g1) + 1);\n    typename Traits2::vertex_descriptor s = *vertices(g2).first;\n    {\n      typename Traits1::vertex_iterator v, v_end;\n      int i = 1;\n      for (tie(v, v_end) = vertices(g1); v != v_end; ++v, ++i) {\n        typename Traits2::edge_descriptor e; bool z;\n        tie(e, z) = add_edge(s, id1[*v] + 1, g2);\n        w[e] = zero;\n        verts1[i] = *v;\n      }\n      typename Traits1::edge_iterator e, e_end;\n      for (tie(e, e_end) = edges(g1); e != e_end; ++e) {\n        typename Traits2::edge_descriptor e2; bool z;\n        tie(e2, z) = add_edge(id1[source(*e, g1)] + 1, \n                             id1[target(*e, g1)] + 1, g2);\n        w[e2] = get(w1, *e);\n        if (is_undirected) {\n          tie(e2, z) = add_edge(id1[target(*e, g1)] + 1, \n                                id1[source(*e, g1)] + 1, g2);\n          w[e2] = get(w1, *e);\n        }\n      }\n    }\n    typename Traits2::vertex_iterator v, v_end, u, u_end;\n    typename Traits2::edge_iterator e, e_end;\n    std::vector<DT> h_vec(num_vertices(g2));\n    typedef typename std::vector<DT>::iterator iter_t;\n    iterator_property_map<iter_t,VertexID2,DT,DT&> h(h_vec.begin(), id2);\n\n    DT inf = (std::numeric_limits<DT>::max)();\n    for (tie(v, v_end) = vertices(g2); v != v_end; ++v)\n      d[*v] = inf;\n\n    put(d, s, zero);\n    // Using the non-named parameter versions of bellman_ford and\n    // dijkstra for portability reasons.\n    dummy_property_map pred; closed_plus<DT> combine;\n    std::less<DT> compare; bellman_visitor<> bvis;\n    if (bellman_ford_shortest_paths\n        (g2, num_vertices(g2), w, pred, d, combine, compare, bvis)) {\n      for (tie(v, v_end) = vertices(g2); v != v_end; ++v)\n        put(h, *v, get(d, *v));\n      // Reweight the edges to remove negatives\n      for (tie(e, e_end) = edges(g2); e != e_end; ++e) {\n        typename Traits2::vertex_descriptor a = source(*e, g2),\n          b = target(*e, g2);\n        put(w_hat, *e, get(w, *e) + get(h, a) - get(h, b));\n      }\n      for (tie(u, u_end) = vertices(g2); u != u_end; ++u) {\n        dijkstra_visitor<> dvis;\n        dijkstra_shortest_paths\n          (g2, *u, pred, d, w_hat, id2, compare, combine, inf, zero,dvis);\n        for (tie(v, v_end) = vertices(g2); v != v_end; ++v) {\n          if (*u != s && *v != s) {\n            typename Traits1::vertex_descriptor u1, v1;\n            u1 = verts1[id2[*u]]; v1 = verts1[id2[*v]];\n            D[id2[*u]-1][id2[*v]-1] = get(d, *v) + get(h, *v) - get(h, *u);\n          }\n        }\n      }\n      return true;\n    } else\n      return false;\n  }\n\n  namespace detail {\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      \n      return johnson_all_pairs_shortest_paths\n        (g, D, id, w,\n         choose_param(get_param(params, distance_zero_t()), 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} // namespace boost\n\n#endif // BOOST_GRAPH_JOHNSON_HPP\n\n\n", "meta": {"hexsha": "edfac606a856633ea7d5866410276b2b6267a560", "size": 7423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/johnson_all_pairs_shortest.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/graph/johnson_all_pairs_shortest.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/graph/johnson_all_pairs_shortest.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": 36.9303482587, "max_line_length": 75, "alphanum_fraction": 0.6333018995, "num_tokens": 2019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.051845465184771775, "lm_q1q2_score": 0.024708493706992494}}
{"text": "//\n// Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.\n// Copyright (c) 2015-2017, University of Bremen\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// 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 <stdlib.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\nnamespace maps { namespace tools {\n\nclass SurfaceIntersection\n{\npublic:\n\n/**\n * Computes the intersection points between a plane and an axis aligned box.\n * Note: This method doesn't check if the plane intersects with the box.\n * Note: The intersection points are appended to the vector, i.e., the caller must make sure it is empty.\n */\ntemplate<class Scalar, int MatrixOptions, class Allocator>\nstatic void computeIntersections(const Eigen::Hyperplane<Scalar, 3>& plane, const Eigen::AlignedBox<Scalar, 3>& box,\n        std::vector< Eigen::Matrix<Scalar, 3, 1, MatrixOptions>, Allocator >& intersections)\n{\n    typedef Eigen::Matrix<Scalar, 3, 1, MatrixOptions> Vec;\n    Vec normal = plane.normal();\n    Vec box_center = box.center();\n    Vec extents = box.max() - box_center;\n    const Scalar dist = -plane.signedDistance(box_center);\n\n    // find the max coefficient of the normal:\n    int i=0, j=1, k=2;\n    if(std::abs(normal[i]) < std::abs(normal[j])) std::swap(i,j);\n    if(std::abs(normal[i]) < std::abs(normal[k])) std::swap(i,k);\n\n    const Scalar dotj = extents[j] * normal[j];\n    const Scalar dotk = extents[k] * normal[k];\n\n    Vec prev_p;\n    enum { NONE, LOW, BOX, HIGH } prev_pos = NONE, pos;\n    // calculate intersections in direction i:\n    for(int n=0; n<5; ++n)\n    {\n        Vec p(0,0,0);\n        Scalar dotp = Scalar(0.0);\n        if((n+1)&2)\n            dotp += dotj, p[j] = extents[j];\n        else\n            dotp -= dotj, p[j] = -extents[j];\n        if(n&2)\n            dotp += dotk, p[k] = extents[k];\n        else\n            dotp -= dotk, p[k] = -extents[k];\n\n        p[i] = (dist - dotp) / normal[i];\n\n        if( p[i] < -extents[i])\n            pos = LOW;\n        else if( p[i] > extents[i])\n            pos = HIGH;\n        else\n            pos = BOX;\n\n        if( (prev_pos == LOW || prev_pos == HIGH) && pos != prev_pos )\n        {\n            // clipping in\n            const Scalar h = prev_pos == LOW ? -extents[i] : extents[i];\n            const Scalar s = (h - prev_p[i]) / (p[i] - prev_p[i]);\n            intersections.push_back(box_center + prev_p + (p - prev_p) * s);\n        }\n        if( pos == BOX )\n        {\n            if( n==4 ) break; // n==4 is only for clipping in\n            intersections.push_back(box_center + p);\n        }\n        else if( pos != prev_pos && prev_pos != NONE )\n        {\n            // clipping out\n            const Scalar h = pos == LOW ? -extents[i] : extents[i];\n            const Scalar s = (h - prev_p[i]) / (p[i] - prev_p[i]);\n            intersections.push_back(box_center + prev_p + (p - prev_p) * s);\n        }\n\n        prev_pos = pos;\n        prev_p = p;\n    }\n}\n};\n\n}}\n", "meta": {"hexsha": "3ebdf8de6e72bf5d9c73f1d37dfbfe6711928153", "size": 4235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tools/SurfaceIntersection.hpp", "max_stars_repo_name": "JanWehrmann/slam-maps", "max_stars_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T05:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T02:34:18.000Z", "max_issues_repo_path": "src/tools/SurfaceIntersection.hpp", "max_issues_repo_name": "JanWehrmann/slam-maps", "max_issues_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T18:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T15:20:31.000Z", "max_forks_repo_path": "src/tools/SurfaceIntersection.hpp", "max_forks_repo_name": "JanWehrmann/slam-maps", "max_forks_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-03-10T10:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T05:50:10.000Z", "avg_line_length": 36.8260869565, "max_line_length": 116, "alphanum_fraction": 0.6299881936, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.05261895669043021, "lm_q1q2_score": 0.024667273679325957}}
{"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_SMAT_SMAT_MULT_INCLUDE\n#define MTL_SMAT_SMAT_MULT_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/transposed_matrix_type.hpp>\n#include <boost/numeric/mtl/operation/mult_assign_mode.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl {\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void smat_smat_mult(const MatrixA& A, const MatrixB& B, MatrixC& C, Assign, \n\t\t\t   tag::row_major,  // orientation A \n\t\t\t   tag::row_major)  // orientation B\n{\n    if (Assign::init_to_zero) set_to_zero(C);\n    \n    // Average numbers of non-zeros per row\n    double ava= num_cols(A) ? double(A.nnz()) / num_cols(A) : 0, \n\t   avb= num_rows(B) ? double(B.nnz()) / num_rows(B) : 0; \n\n    // Define Updater type corresponding to assign mode\n    typedef typename Collection<MatrixC>::value_type                            C_value_type;\n    typedef typename operations::update_assign_mode<Assign, C_value_type>::type Updater;\n\n    // Reserve 20% over the average's product for entries in C\n    mat::inserter<MatrixC, Updater>     ins(C, int( ava * avb * 1.4 ));\n\n    typename traits::row<MatrixA>::type             row_A(A); \n    typename traits::col<MatrixA>::type             col_A(A); \n    typename traits::const_value<MatrixA>::type     value_A(A); \n\n    typename traits::col<MatrixB>::type             col_B(B); \n    typename traits::const_value<MatrixB>::type     value_B(B); \n\n    typedef typename traits::range_generator<tag::row, MatrixA>::type  cursor_type;\n    cursor_type cursor = begin<tag::row>(A), cend = end<tag::row>(A); \n    for (unsigned ra= 0; cursor != cend; ++ra, ++cursor) {\n\t// Iterate over non-zeros of each row of A\n\ttypedef typename traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\tfor (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor) {\n\t    typename Collection<MatrixA>::size_type     ca= col_A(*icursor);   // column of non-zero\n\t    typename Collection<MatrixA>::value_type    va= value_A(*icursor); // value of non-zero\n \n\t    // Get cursor corresponding to row 'ca' in matrix B\n\t    typedef typename traits::range_generator<tag::row, MatrixB>::type  B_cursor_type;\n\t    B_cursor_type B_cursor = begin<tag::row>(B);\n\t\tB_cursor += int(ca); // not elegant but prevents warning\n\n\t    // Iterate over non-zeros of this row \n\t    typedef typename traits::range_generator<tag::nz, B_cursor_type>::type ib_cursor_type;\n\t    for (ib_cursor_type ib_cursor = begin<tag::nz>(B_cursor), ib_cend = end<tag::nz>(B_cursor); \n\t\t ib_cursor != ib_cend; ++ib_cursor) {\n\t\ttypename Collection<MatrixB>::size_type     cb= col_B(*ib_cursor);   // column of non-zero\n\t\ttypename Collection<MatrixB>::value_type    vb= value_B(*ib_cursor); // value of non-zero\n\t\tins(ra, cb) << va * vb;\t\t\n\t    }\n\t}\n    }\n}\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void smat_smat_mult(const MatrixA& A, const MatrixB& B, MatrixC& C, Assign, \n\t\t\t   tag::col_major,  // orientation A \n\t\t\t   tag::col_major)  // orientation B\n{\n    if (Assign::init_to_zero) set_to_zero(C);\n    \n    // Average numbers of non-zeros per column\n    double ava= double(A.nnz()) / num_cols(A), avb= double(B.nnz()) / num_cols(B); \n\n    // Define Updater type corresponding to assign mode\n    typedef typename Collection<MatrixC>::value_type                            C_value_type;\n    typedef typename operations::update_assign_mode<Assign, C_value_type>::type Updater;\n\n    // Reserve 20% over the average's product for entries in C\n    mat::inserter<MatrixC, Updater>     ins(C, int( ava * avb * 1.2 ));\n\n    typename traits::row<MatrixA>::type             row_A(A); \n    typename traits::col<MatrixA>::type             col_A(A); \n    typename traits::const_value<MatrixA>::type     value_A(A); \n\n    typename traits::row<MatrixB>::type             row_B(B); \n    typename traits::col<MatrixB>::type             col_B(B); \n    typename traits::const_value<MatrixB>::type     value_B(B); \n\n    typedef typename traits::range_generator<tag::col, MatrixB>::type  cursor_type;\n    cursor_type cursor = begin<tag::col>(B), cend = end<tag::col>(B); \n    for (unsigned cb= 0; cursor != cend; ++cb, ++cursor) {\n\t// Iterate over non-zeros of each column of B\n\ttypedef typename traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\tfor (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor) {\n\t    typename Collection<MatrixB>::size_type     rb= row_B(*icursor);   // row of non-zero\n\t    typename Collection<MatrixB>::value_type    vb= value_B(*icursor); // value of non-zero\n \n\t    // Get cursor corresponding to column 'rb' in matrix A\n\t    typedef typename traits::range_generator<tag::col, MatrixA>::type  A_cursor_type;\n\t    A_cursor_type A_cursor = begin<tag::col>(A);\n\t    A_cursor+= rb;\n\n\t    // Iterate over non-zeros of this column\n\t    typedef typename traits::range_generator<tag::nz, A_cursor_type>::type ia_cursor_type;\n\t    for (ia_cursor_type ia_cursor = begin<tag::nz>(A_cursor), ia_cend = end<tag::nz>(A_cursor); \n\t\t ia_cursor != ia_cend; ++ia_cursor) {\n\t\ttypename Collection<MatrixA>::size_type     ra= row_A(*ia_cursor);   // row of non-zero\n\t\ttypename Collection<MatrixA>::value_type    va= value_A(*ia_cursor); // value of non-zero\n\t\tins(ra, cb) << va * vb;\t\t\n\t    }\n\t}\n    }\n}\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void smat_smat_mult(const MatrixA& A, const MatrixB& B, MatrixC& C, Assign, \n\t\t\t   tag::col_major,  // orientation A \n\t\t\t   tag::row_major)  // orientation B\n{\n    if (Assign::init_to_zero) set_to_zero(C);\n    \n    // Average numbers of non-zeros per row\n    double ava= double(A.nnz()) / num_rows(A), avb= double(B.nnz()) / num_rows(B); \n\n    // Define Updater type corresponding to assign mode\n    typedef typename Collection<MatrixC>::value_type                            C_value_type;\n    typedef typename operations::update_assign_mode<Assign, C_value_type>::type Updater;\n\n    // Reserve 20% over the average's product for entries in C\n    mat::inserter<MatrixC, Updater>     ins(C, int( ava * avb * 1.2 ));\n\n    typename traits::row<MatrixA>::type             row_A(A); \n    typename traits::col<MatrixA>::type             col_A(A); \n    typename traits::const_value<MatrixA>::type     value_A(A); \n\n    typename traits::row<MatrixB>::type             row_B(B); \n    typename traits::col<MatrixB>::type             col_B(B); \n    typename traits::const_value<MatrixB>::type     value_B(B); \n\n    typedef typename traits::range_generator<tag::col, MatrixA>::type  A_cursor_type;\n    A_cursor_type A_cursor = begin<tag::col>(A), A_cend = end<tag::col>(A); \n\n    typedef typename traits::range_generator<tag::row, MatrixB>::type  B_cursor_type;\n    B_cursor_type B_cursor = begin<tag::row>(B);\n\n    for (unsigned ca= 0; A_cursor != A_cend; ++ca, ++A_cursor, ++B_cursor) {\n\n\t// Iterate over non-zeros of A's column\n\ttypedef typename traits::range_generator<tag::nz, A_cursor_type>::type ia_cursor_type;\n\tfor (ia_cursor_type ia_cursor = begin<tag::nz>(A_cursor), ia_cend = end<tag::nz>(A_cursor); \n\t     ia_cursor != ia_cend; ++ia_cursor) \n        {\n\t    typename Collection<MatrixA>::size_type     ra= row_A(*ia_cursor);   // row of non-zero\n\t    typename Collection<MatrixA>::value_type    va= value_A(*ia_cursor); // value of non-zero\n\n\t    // Iterate over non-zeros of B's row \n\t    typedef typename traits::range_generator<tag::nz, B_cursor_type>::type ib_cursor_type;\n\t    for (ib_cursor_type ib_cursor = begin<tag::nz>(B_cursor), ib_cend = end<tag::nz>(B_cursor); \n\t\t ib_cursor != ib_cend; ++ib_cursor) \n            {\n\t\ttypename Collection<MatrixB>::size_type     cb= col_B(*ib_cursor);   // column of non-zero\n\t\ttypename Collection<MatrixB>::value_type    vb= value_B(*ib_cursor); // value of non-zero\n\t\tins(ra, cb) << va * vb;\t\t\n\t    }\n\t}\n    }\n}\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void smat_smat_mult(const MatrixA& A, const MatrixB& B, MatrixC& C, Assign, \n\t\t\t   tag::row_major,  // orientation A \n\t\t\t   tag::col_major)  // orientation B\n{\n\tvampir_trace<4020> tracer;\n    // Copy B into a sparse row-major matrix\n    typename mtl::traits::transposed_sparse_matrix_type<MatrixB>::type B_copy(num_rows(B), num_cols(B));\n    B_copy= B;\n    smat_smat_mult(A, B_copy, C, Assign(), tag::row_major(), tag::row_major());\n}\n\n} // namespace mtl\n\n#endif // MTL_SMAT_SMAT_MULT_INCLUDE\n", "meta": {"hexsha": "14b84cd75ffa6876073eb12b695be3ae5b365e4e", "size": 9102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/smat_smat_mult.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/operation/smat_smat_mult.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/operation/smat_smat_mult.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": 45.7386934673, "max_line_length": 113, "alphanum_fraction": 0.6742474181, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.05834583979298737, "lm_q1q2_score": 0.024651387734663258}}
{"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_UPPER_TRISOLVE_INCLUDE\n#define MTL_UPPER_TRISOLVE_INCLUDE\n\n#include <boost/mpl/int.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/exception.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/category.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace mat {\n\n\nnamespace detail {\n\n    /// Class that implements upper trisolver\n    /** DiaTag can be tag::regular_diagonal, tag::unit_diagonal, or tag::inverse_diagonal.\n\tCompactStorage means that matrix contains only upper entries (strict upper when DiaTag == unit_diagonal).  \\sa \\ref trisolve_object **/\n    template <typename Matrix, typename DiaTag, bool CompactStorage= false>\n    struct upper_trisolve_t\n    {\n\tMTL_STATIC_ASSERT((boost::is_same<DiaTag, tag::regular_diagonal>::value\n\t\t\t   || boost::is_same<DiaTag, tag::unit_diagonal>::value\n\t\t\t   || boost::is_same<DiaTag, tag::inverse_diagonal>::value),\n\t\t\t  \"DiaTag must be either tag::regular_diagonal, tag::unit_diagonal, or tag::inverse_diagonal.\");\n\n\ttypedef typename Collection<Matrix>::value_type           value_type;\n\ttypedef typename Collection<Matrix>::size_type            size_type;\n\ttypedef typename OrientedCollection<Matrix>::orientation  my_orientation;\n\ttypedef typename mtl::traits::category<Matrix>::type      my_category;\n\ttypedef typename mtl::traits::range_generator<tag::major, Matrix>::type   a_cur_type; // row or col accordingly\n\ttypedef typename mtl::traits::range_generator<tag::nz, a_cur_type>::type  a_icur_type;   \n\n\t/// Construction from matrix \\p A\n\tupper_trisolve_t(const Matrix& A) : A(A), value_a(A), col_a(A), row_a(A)\n\t{    MTL_THROW_IF(num_rows(A) != num_cols(A), matrix_not_square());\t}\n\n\ttemplate <typename M, typename D, bool C>\n\tstruct generic_version\n\t  : boost::mpl::int_<mtl::traits::is_row_major<M>::value ? 1 : 2> {};\n\n\ttemplate <typename M, typename D, bool C>\n\tstruct version\n\t  : generic_version<M, D, C> {};\n\n\ttemplate <typename Value, typename Para, typename D>\n\tstruct version<compressed2D<Value, Para>, D, true>\n\t  : boost::mpl::if_<mtl::traits::is_row_major<Para>,\n\t\t\t    boost::mpl::int_<3>,\n\t\t\t    generic_version<compressed2D<Value, Para>, D, true>\n\t                   >::type {};\n\n\t/// Solve \\p w = A * \\p v\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid operator()(const VectorIn& v, VectorOut& w) const\n\t{\n\t    apply(v, w, version<Matrix, DiaTag, CompactStorage>());\n\t}\n\n\t/// Solves the upper triangular matrix A  with the rhs v returns the solution\n\ttemplate <typename Vector>\n\tVector operator()(const Vector& v) const\n\t{\n\t    Vector w(resource(v));\n\t    (*this)(v, w);\n\t    return w;\n\t}\n\n    private:\n\t// Initialization for regular and inverse diagonal is the same\n\ttemplate <typename Cursor, typename Value>\n\tvoid row_init(size_type MTL_DEBUG_ARG(r), Cursor& aic, Cursor& MTL_DEBUG_ARG(aiend), Value& dia, tag::universe_diagonal) const\n\t{\n\t    MTL_DEBUG_THROW_IF(aic == aiend || col_a(*aic) != r, missing_diagonal());\n\t    dia= value_a(*aic); ++aic;\n\t}\n\n\ttemplate <typename Cursor, typename Value>\n\tvoid row_init(size_type, Cursor&, Cursor&, Value&, tag::unit_diagonal) const {}\n\n\ttemplate <typename Value> void row_update(Value& res, Value& rr, const Value& dia, tag::regular_diagonal) const { res= rr / dia; }\n\ttemplate <typename Value> void row_update(Value& res, Value& rr, const Value& dia, tag::inverse_diagonal) const { res= rr * dia; }\n\ttemplate <typename Value> void row_update(Value& res, Value& rr, const Value&    , tag::unit_diagonal)    const { res= rr; }\n\n\ttemplate <typename Tag> int dia_inc(Tag) const { return 0; }\n\tint dia_inc(tag::unit_diagonal) const { return 1; }\n\n\t// Generic row-major\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid inline apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<1>) const\n\t{\n\t    // vampir_trace<5042> tracer;\n\t    using namespace tag; \n\t    typedef typename mtl::Collection<VectorOut>::value_type out_value_type;\n\t    a_cur_type ac= begin<row>(A), aend= end<row>(A); \n\t    for (size_type r= num_rows(A) - 1; ac != aend--; --r) {\n\t\ta_icur_type aic= CompactStorage ? begin<nz>(aend) : lower_bound<nz>(aend, r + dia_inc(DiaTag())), \n\t\t            aiend= end<nz>(aend);\n\t\tout_value_type rr= v[r], dia;\n\t\trow_init(r, aic, aiend, dia, DiaTag()); \n\t\tfor (; aic != aiend; ++aic) {\n\t\t    MTL_DEBUG_THROW_IF(col_a(*aic) <= r, logic_error(\"Matrix entries must be sorted for this.\"));\n\t\t    rr-= value_a(*aic) * w[col_a(*aic)];\n\t\t}\n\t\trow_update(w[r], rr, dia, DiaTag());\n\t    }\n\t}\n\n\t// Generic column-major\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<2>) const\n\t{\n\t    // vampir_trace<5043> tracer;\n\t    using namespace tag; \n\t    typedef typename mtl::Collection<VectorOut>::value_type out_value_type;\n\t    w= v;\n\t    a_cur_type ac= begin<col>(A), aend= end<col>(A); \n\t    for (size_type r= num_rows(A) - 1; ac != aend--; --r) {\n\t\ta_icur_type aic= begin<nz>(aend), \n\t\t            aiend= CompactStorage ? end<nz>(aend) : lower_bound<nz>(aend, r + 1 - dia_inc(DiaTag()));\n\t\tout_value_type rr;\n\t\tcol_init(r, aic, aiend, rr, w[r], DiaTag());\n\n\t\tfor (; aic != aiend; ++aic) {\n\t\t    MTL_DEBUG_THROW_IF(row_a(*aic) >= r, logic_error(\"Matrix entries must be sorted for this.\"));\n\t\t    w[row_a(*aic)]-= value_a(*aic) * rr;\n\t\t}\n\t    }\n\t}\n\n\ttemplate <typename Value> \n\tvoid crs_row_init(size_type MTL_DEBUG_ARG(r), size_type& j0, size_type MTL_DEBUG_ARG(cj1), Value& dia, tag::universe_diagonal) const\n\t{\n\t    MTL_DEBUG_THROW_IF(j0 == cj1 || A.ref_minor()[j0] != r, missing_diagonal());\n\t    dia= A.data[j0++];\n\t}\n\ttemplate <typename Value> void crs_row_init(size_type, size_type&, size_type, Value&, tag::unit_diagonal) const {}\n\n\t// Tuning for IC_0 and similar using compressed2D row-major compact\n\ttemplate <typename VectorIn, typename VectorOut>\n\tvoid apply(const VectorIn& v, VectorOut& w, boost::mpl::int_<3>) const\n\t{\n\t    // vampir_trace<5046> tracer;\n\t    typedef typename mtl::Collection<VectorOut>::value_type out_value_type;\n\t    for (size_type r= num_rows(A); r-- > 0; ) {\n\t\tsize_type j0= A.ref_major()[r];\n\t\tconst size_type cj1= A.ref_major()[r+1];\n\t\tout_value_type rr= v[r], dia;\n\t\tcrs_row_init(r, j0, cj1, dia, DiaTag()); \n\t\tfor (; j0 != cj1; ++j0) {\n\t\t    MTL_DEBUG_THROW_IF(A.ref_minor()[j0] <= r, logic_error(\"Matrix entries must be sorted for this.\"));\n\t\t    rr-= A.data[j0] * w[A.ref_minor()[j0]];\n\t\t}\n\t\trow_update(w[r], rr, dia, DiaTag());\n\t    }\n\t}\n\n\ttemplate <typename Cursor, typename Value>\n\tvoid col_init(size_type MTL_DEBUG_ARG(r), Cursor& MTL_DEBUG_ARG(aic), Cursor& aiend, Value& rr, Value& res, tag::regular_diagonal) const\n\t{\n\t    MTL_DEBUG_THROW_IF(aic == aiend, missing_diagonal());\n\t    --aiend;\n\t    MTL_DEBUG_THROW_IF(row_a(*aiend) != r, missing_diagonal());\n\t    rr= res/= value_a(*aiend);\n\t}\n\t\n\ttemplate <typename Cursor, typename Value>\n\tvoid col_init(size_type MTL_DEBUG_ARG(r), Cursor& MTL_DEBUG_ARG(aic), Cursor& aiend, Value& rr, Value& res, tag::inverse_diagonal) const\n\t{\n\t    MTL_DEBUG_THROW_IF(aic == aiend, missing_diagonal());\n\t    --aiend;\n\t    MTL_DEBUG_THROW_IF(row_a(*aiend) != r, missing_diagonal());\n\t    rr= res*= value_a(*aiend);\n\t}\n\n\ttemplate <typename Cursor, typename Value>\n\tvoid col_init(size_type, Cursor&, Cursor&, Value& rr, Value& res, tag::unit_diagonal) const\n\t{\n\t    rr= res;\n\t}\n\n\n\tconst Matrix& A;\n\ttypename mtl::traits::const_value<Matrix>::type  value_a; \n\ttypename mtl::traits::col<Matrix>::type          col_a; \n\ttypename mtl::traits::row<Matrix>::type          row_a;\n    };\n\n}\n\n/// Solves the upper triangular matrix A  with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename Vector>\nVector inline upper_trisolve(const Matrix& A, const Vector& v)\n{\n    // vampir_trace<3043> tracer;\n    return detail::upper_trisolve_t<Matrix, tag::regular_diagonal>(A)(v);\n}\n\n/// Solves the upper triangular matrix A  with the rhs v while solution vector w is passed as reference\ntemplate <typename Matrix, typename VectorIn, typename VectorOut>\nvoid inline upper_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w)\n{\n    // vampir_trace<3043> tracer;\n    detail::upper_trisolve_t<Matrix, tag::regular_diagonal> solver(A); // use of anonymous variable causes weird error\n    solver(v, w);\n}\n\n/// Solves the upper triangular matrix A (only one's in the diagonal) with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename Vector>\nVector inline unit_upper_trisolve(const Matrix& A, const Vector& v)\n{\n    // vampir_trace<3044> tracer;\n    return detail::upper_trisolve_t<Matrix, tag::unit_diagonal>(A)(v);\n}\n\n/// Solves the upper triangular matrix A (only one's in the diagonal) with the rhs v while solution vector w is passed as reference\ntemplate <typename Matrix, typename VectorIn, typename VectorOut>\nvoid inline unit_upper_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w)\n{\n    // vampir_trace<3044> tracer;\n    detail::upper_trisolve_t<Matrix, tag::unit_diagonal> solver(A);\n    solver(v, w);\n}\n\n/// Solves the upper triangular matrix A  (inverse the diagonal) with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename Vector>\nVector inline inverse_upper_trisolve(const Matrix& A, const Vector& v)\n{\n    // vampir_trace<3045> tracer;\n    return detail::upper_trisolve_t<Matrix, tag::inverse_diagonal>(A)(v);\n}\n\n/// Solves the upper triangular matrix A  (inverse the diagonal) with the rhs v while solution vector w is passed as reference\ntemplate <typename Matrix, typename VectorIn, typename VectorOut>\nvoid inline inverse_upper_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w)\n{\n    // vampir_trace<3045> tracer;\n    detail::upper_trisolve_t<Matrix, tag::inverse_diagonal> solver(A);\n    solver(v, w);\n}\n\n/// Solves the upper triangular matrix A  with the rhs v and returns the solution vector\ntemplate <typename Matrix, typename Vector, typename DiaTag>\nVector inline upper_trisolve(const Matrix& A, const Vector& v, DiaTag)\n{\n    // vampir_trace<3046> tracer;\n    return detail::upper_trisolve_t<Matrix, DiaTag>(A)(v);\n}\n\n/// Solves the upper triangular matrix A  with the rhs v while solution vector w is passed as reference\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename DiaTag>\nvoid inline upper_trisolve(const Matrix& A, const VectorIn& v, VectorOut& w, DiaTag)\n{\n    // vampir_trace<3046> tracer;\n    detail::upper_trisolve_t<Matrix, DiaTag> solver(A);\n    solver(v, w);\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_UPPER_TRISOLVE_INCLUDE\n", "meta": {"hexsha": "44b2f26de42068f8a0d3870ca97b20dce3e3a897", "size": 11359, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/upper_trisolve.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/operation/upper_trisolve.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/operation/upper_trisolve.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": 40.280141844, "max_line_length": 137, "alphanum_fraction": 0.7059600317, "num_tokens": 3108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988313272769, "lm_q2_score": 0.05921024742104523, "lm_q1q2_score": 0.024566262457590575}}
{"text": "#include \"octree.h\"\r\n#include <pcl/console/print.h>\r\n#include <pcl/console/time.h>\r\n#include <pcl/pcl_macros.h>\r\n#include <boost/shared_ptr.hpp>\r\n#include <vector>\r\n#include <stdint.h>\r\n#include <cmath>\r\n#include <fstream>\r\n#include <iostream>\r\n\r\nvoid\r\ncpu_tsdf::OctreeNode::getCenter(float &x, float &y, float &z) const\r\n{\r\n\tx = ctr_x_;\r\n\ty = ctr_y_;\r\n\tz = ctr_z_;\r\n};\r\n\r\nvoid\r\ncpu_tsdf::OctreeNode::getSize(float &size_x, float &size_y, float &size_z) const\r\n{\r\n\tsize_x = size_;\r\n\tsize_y = size_;\r\n\tsize_z = size_;\r\n}\r\n\r\nfloat\r\ncpu_tsdf::OctreeNode::getMaxSize() const\r\n{\r\n\treturn (std::sqrt(3) * size_);\r\n}\r\n\r\nfloat\r\ncpu_tsdf::OctreeNode::getMinSize() const\r\n{\r\n\treturn (size_);\r\n}\r\n\r\nbool\r\ncpu_tsdf::OctreeNode::hasChildren() const\r\n{\r\n\treturn (!children_.empty());\r\n}\r\n\r\nstd::vector<cpu_tsdf::OctreeNode::Ptr>&\r\ncpu_tsdf::OctreeNode::getChildren()\r\n{\r\n\treturn children_;\r\n}\r\n\r\nconst std::vector<cpu_tsdf::OctreeNode::Ptr>&\r\ncpu_tsdf::OctreeNode::getChildren() const\r\n{\r\n\treturn children_;\r\n}\r\n\r\nvoid\r\ncpu_tsdf::OctreeNode::getLeaves(std::vector<cpu_tsdf::OctreeNode::Ptr> &leaves, int num_levels)\r\n{\r\n\tfor (size_t i = 0; i < children_.size(); i++)\r\n\t{\r\n\t\tconst OctreeNode::Ptr &child = children_[i];\r\n\t\tif (child->hasChildren() && num_levels != 0)\r\n\t\t\tchild->getLeaves(leaves, num_levels - 1);\r\n\t\telse\r\n\t\t\tleaves.push_back(child);\r\n\t}\r\n}\r\n\r\n// Get the voxel which contains this point\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::OctreeNode::getContainingVoxel(float x, float y, float z, float min_size)\r\n{\r\n\tif (!hasChildren() || (min_size > 0 && size_ <= min_size))\r\n\t\treturn (this);\r\n\telse\r\n\t{\r\n\t\treturn children_[((x - ctr_x_) > 0) * 4 + ((y - ctr_y_) > 0) * 2 + (z - ctr_z_ > 0)]->getContainingVoxel(x, y, z, min_size);\r\n\t}\r\n}\r\n\r\n// Get the voxel which contains this point\r\nconst cpu_tsdf::OctreeNode*\r\ncpu_tsdf::OctreeNode::getContainingVoxel(float x, float y, float z, float min_size) const\r\n{\r\n\tif (!hasChildren() || (min_size > 0 && size_ <= min_size))\r\n\t\treturn (this);\r\n\telse\r\n\t{\r\n\t\treturn children_[((x - ctr_x_) > 0) * 4 + ((y - ctr_y_) > 0) * 2 + (z - ctr_z_ > 0)]->getContainingVoxel(x, y, z, min_size);\r\n\t}\r\n}\r\n\r\n\r\nbool\r\ncpu_tsdf::OctreeNode::getData(float &d, float &w) const\r\n{\r\n\td = d_;\r\n\tw = w_;\r\n\treturn (true);\r\n}\r\n\r\nbool\r\ncpu_tsdf::OctreeNode::setData(float d, float w)\r\n{\r\n\td_ = d;\r\n\tw_ = w;\r\n\treturn (true);\r\n}\r\n\r\nbool\r\ncpu_tsdf::OctreeNode::addObservation(float d_new, float w_new, float max_weight)\r\n{\r\n\tfloat d_old = d_;\r\n\td_ = (d_ * w_ + d_new * w_new) / (w_ + w_new);\r\n\tw_ += w_new;\r\n\tif (w_ > max_weight)\r\n\t\tw_ = max_weight;\r\n\tM_ += w_new * (d_new - d_) * (d_new - d_old);\r\n\t++nsample_;\r\n\treturn (true);\r\n}\r\n\r\n\r\nbool\r\ncpu_tsdf::OctreeNode::addObservation(float d_new, float w_new, float max_weight,\r\n\tuint8_t r, uint8_t g, uint8_t b)\r\n{\r\n\treturn (addObservation(d_new, w_new, max_weight));\r\n}\r\n\r\nbool\r\ncpu_tsdf::OctreeNode::getRGB(uint8_t &r, uint8_t &g, uint8_t &b) const\r\n{\r\n\tr = g = b = 127;\r\n\treturn (false);\r\n}\r\n\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::OctreeNode::instantiateNode(float x, float y, float z, float sx, float sy, float sz)\r\n{\r\n\treturn (new OctreeNode(x, y, z, sx, sy, sz));\r\n}\r\n\r\nstd::string\r\ncpu_tsdf::OctreeNode::getTypeString()\r\n{\r\n\treturn (\"NOCOLOR\");\r\n}\r\n\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::OctreeNode::instantiateByTypeString(const std::string &str)\r\n{\r\n\tif (str == \"NOCOLOR\")\r\n\t\treturn (new OctreeNode);\r\n\telse if (str == \"RGB\")\r\n\t\treturn (new RGBNode);\r\n\telse if (str == \"RGBNormalized\")\r\n\t\treturn (new RGBNormalized);\r\n\telse if (str == \"LAB\")\r\n\t\treturn (new LABNode);\r\n\t// Handle more examples\r\n\tPCL_ERROR(\"[cpu_tsdf::OctreeNode::instantiateByTypeString] Requested invalid type string %s\\n\", str.c_str());\r\n\treturn (NULL);\r\n}\r\n\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::OctreeNode::instantiateByTypeString(const std::string &str,\r\n\tfloat x, float y, float z, float sx, float sy, float sz)\r\n{\r\n\tcpu_tsdf::OctreeNode* empty_node = instantiateByTypeString(str);\r\n\tcpu_tsdf::OctreeNode* node = empty_node->instantiateNode(x, y, z, sx, sy, sz);\r\n\tdelete empty_node;\r\n\treturn (node);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::OctreeNode::updateAverage()\r\n{\r\n\tif (children_.empty())\r\n\t\treturn;\r\n\r\n\tfloat d_avg = 0;\r\n\tfloat w_avg = 0;\r\n\tint ngood = 0;\r\n\tfor (size_t i = 0; i < children_.size(); ++i)\r\n\t{\r\n\t\tchildren_[i]->updateAverage();\r\n\t\tif (children_[i]->w_ > 0)\r\n\t\t{\r\n\t\t\td_avg += children_[i]->d_;\r\n\t\t\tw_avg += children_[i]->w_;\r\n\t\t\t++ngood;\r\n\t\t}\r\n\t}\r\n\tif (ngood > 0)\r\n\t{\r\n\t\td_ = d_avg / ngood;\r\n\t\tw_ = w_avg / ngood;\r\n\t}\r\n}\r\n\r\nstd::vector<cpu_tsdf::OctreeNode::Ptr>&\r\ncpu_tsdf::OctreeNode::split()\r\n{\r\n\tchildren_.resize(8);\r\n\t//float off_x = size_x_ / 4;\r\n\t//float off_y = size_y_ / 4;\r\n\t//float off_z = size_z_ / 4;\r\n\tfloat off_x = size_ / 4;\r\n\tfloat off_y = size_ / 4;\r\n\tfloat off_z = size_ / 4;\r\n\tfloat newsize_x = size_ / 2;\r\n\tfloat newsize_y = size_ / 2;\r\n\tfloat newsize_z = size_ / 2;\r\n\tchildren_[0].reset(instantiateNode(ctr_x_ - off_x, ctr_y_ - off_y, ctr_z_ - off_z, newsize_x, newsize_y, newsize_z));\r\n\tchildren_[1].reset(instantiateNode(ctr_x_ - off_x, ctr_y_ - off_y, ctr_z_ + off_z, newsize_x, newsize_y, newsize_z));\r\n\tchildren_[2].reset(instantiateNode(ctr_x_ - off_x, ctr_y_ + off_y, ctr_z_ - off_z, newsize_x, newsize_y, newsize_z));\r\n\tchildren_[3].reset(instantiateNode(ctr_x_ - off_x, ctr_y_ + off_y, ctr_z_ + off_z, newsize_x, newsize_y, newsize_z));\r\n\tchildren_[4].reset(instantiateNode(ctr_x_ + off_x, ctr_y_ - off_y, ctr_z_ - off_z, newsize_x, newsize_y, newsize_z));\r\n\tchildren_[5].reset(instantiateNode(ctr_x_ + off_x, ctr_y_ - off_y, ctr_z_ + off_z, newsize_x, newsize_y, newsize_z));\r\n\tchildren_[6].reset(instantiateNode(ctr_x_ + off_x, ctr_y_ + off_y, ctr_z_ - off_z, newsize_x, newsize_y, newsize_z));\r\n\tchildren_[7].reset(instantiateNode(ctr_x_ + off_x, ctr_y_ + off_y, ctr_z_ + off_z, newsize_x, newsize_y, newsize_z));\r\n\treturn (children_);\r\n}\r\n\r\n\r\nvoid\r\ncpu_tsdf::OctreeNode::splitRecursive(int num_left)\r\n{\r\n\tif (num_left <= 0)\r\n\t\treturn;\r\n\tsplit();\r\n\tfor (size_t i = 0; i < children_.size(); i++)\r\n\t{\r\n\t\tchildren_[i]->splitRecursive(num_left - 1);\r\n\t}\r\n}\r\n\r\nfloat\r\ncpu_tsdf::OctreeNode::getVariance() const\r\n{\r\n\tif (nsample_ < 5)\r\n\t\treturn (std::numeric_limits<float>::infinity());\r\n\treturn ((M_ / w_)*(nsample_ / (nsample_ - 1)));\r\n}\r\n\r\nvoid\r\ncpu_tsdf::OctreeNode::serialize(std::ostream &f) const\r\n{\r\n\tf.write((char*)&d_, sizeof(float));\r\n\tf.write((char*)&w_, sizeof(float));\r\n\tf.write((char*)&ctr_x_, sizeof(float));\r\n\tf.write((char*)&ctr_y_, sizeof(float));\r\n\tf.write((char*)&ctr_z_, sizeof(float));\r\n\tf.write((char*)&size_, sizeof(float));\r\n\tf.write((char*)&M_, sizeof(float));\r\n\tf.write((char*)&nsample_, sizeof(int));\r\n\tsize_t nchild = children_.size();\r\n\tf.write((char*)&nchild, sizeof(size_t));\r\n\tfor (size_t i = 0; i < nchild; ++i)\r\n\t\tchildren_[i]->serialize(f);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::OctreeNode::deserialize(std::istream &f)\r\n{\r\n\tf.read((char*)&d_, sizeof(float));\r\n\tf.read((char*)&w_, sizeof(float));\r\n\tf.read((char*)&ctr_x_, sizeof(float));\r\n\tf.read((char*)&ctr_y_, sizeof(float));\r\n\tf.read((char*)&ctr_z_, sizeof(float));\r\n\tf.read((char*)&size_, sizeof(float));\r\n\tf.read((char*)&M_, sizeof(float));\r\n\tf.read((char*)&nsample_, sizeof(int));\r\n\tsize_t nchild;\r\n\tf.read((char*)&nchild, sizeof(size_t));\r\n\tchildren_.resize(nchild);\r\n\tfor (size_t i = 0; i < nchild; ++i)\r\n\t{\r\n\t\tchildren_[i].reset(instantiateNode(0, 0, 0, 0, 0, 0));\r\n\t\tchildren_[i]->deserialize(f);\r\n\t}\r\n}\r\n\r\n// RGBNode\r\nbool\r\ncpu_tsdf::RGBNode::addObservation(float d_new, float w_new, float max_weight,\r\n\tuint8_t r, uint8_t g, uint8_t b)\r\n{\r\n\tfloat wsum = w_ + w_new;\r\n\tr_ = static_cast<uint8_t> ((w_*r_ + w_new*r) / wsum);\r\n\tg_ = static_cast<uint8_t> ((w_*g_ + w_new*g) / wsum);\r\n\tb_ = static_cast<uint8_t> ((w_*b_ + w_new*b) / wsum);\r\n\treturn (OctreeNode::addObservation(d_new, w_new, max_weight));\r\n}\r\n\r\nbool\r\ncpu_tsdf::RGBNode::getRGB(uint8_t &r, uint8_t &g, uint8_t &b) const\r\n{\r\n\tr = r_;\r\n\tg = g_;\r\n\tb = b_;\r\n\treturn (true);\r\n}\r\n\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::RGBNode::instantiateNode(float x, float y, float z, float sx, float sy, float sz)\r\n{\r\n\treturn (new RGBNode(x, y, z, sx, sy, sz));\r\n}\r\n\r\nstd::string\r\ncpu_tsdf::RGBNode::getTypeString()\r\n{\r\n\treturn (\"RGB\");\r\n}\r\n\r\nvoid\r\ncpu_tsdf::RGBNode::serialize(std::ostream &f) const\r\n{\r\n\tf.write((char*)&r_, sizeof(uint8_t));\r\n\tf.write((char*)&g_, sizeof(uint8_t));\r\n\tf.write((char*)&b_, sizeof(uint8_t));\r\n\tOctreeNode::serialize(f);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::RGBNode::deserialize(std::istream &f)\r\n{\r\n\tf.read((char*)&r_, sizeof(uint8_t));\r\n\tf.read((char*)&g_, sizeof(uint8_t));\r\n\tf.read((char*)&b_, sizeof(uint8_t));\r\n\tOctreeNode::deserialize(f);\r\n}\r\n\r\n// RGBNormalized\r\nbool\r\ncpu_tsdf::RGBNormalized::addObservation(float d_new, float w_new, float max_weight,\r\n\tuint8_t r, uint8_t g, uint8_t b)\r\n{\r\n\tfloat wsum = w_ + w_new;\r\n\tfloat i = std::sqrt((float)r * (float)r + (float)g*(float)g + (float)b*(float)b);\r\n\tfloat r_f = r / i;\r\n\tfloat g_f = g / i;\r\n\tfloat b_f = b / i;\r\n\tr_n_ = (w_*r_n_ + w_new*r_f) / wsum;\r\n\tg_n_ = (w_*g_n_ + w_new*g_f) / wsum;\r\n\tb_n_ = (w_*b_n_ + w_new*b_f) / wsum;\r\n\ti_ = (w_*i_ + w_new*i) / wsum;\r\n\treturn (OctreeNode::addObservation(d_new, w_new, max_weight));\r\n}\r\n\r\nbool\r\ncpu_tsdf::RGBNormalized::getRGB(uint8_t &r, uint8_t &g, uint8_t &b) const\r\n{\r\n\tr = r_n_ * i_;\r\n\tg = g_n_ * i_;\r\n\tb = b_n_ * i_;\r\n\treturn (true);\r\n}\r\n\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::RGBNormalized::instantiateNode(float x, float y, float z, float sx, float sy, float sz)\r\n{\r\n\treturn (new RGBNormalized(x, y, z, sx, sy, sz));\r\n}\r\n\r\nstd::string\r\ncpu_tsdf::RGBNormalized::getTypeString()\r\n{\r\n\treturn (\"RGBNormalized\");\r\n}\r\n\r\nvoid\r\ncpu_tsdf::RGBNormalized::serialize(std::ostream &f) const\r\n{\r\n\tf.write((char*)&r_n_, sizeof(uint8_t));\r\n\tf.write((char*)&g_n_, sizeof(uint8_t));\r\n\tf.write((char*)&b_n_, sizeof(uint8_t));\r\n\tf.write((char*)&i_, sizeof(uint8_t));\r\n\tOctreeNode::serialize(f);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::RGBNormalized::deserialize(std::istream &f)\r\n{\r\n\tf.read((char*)&r_n_, sizeof(uint8_t));\r\n\tf.read((char*)&g_n_, sizeof(uint8_t));\r\n\tf.read((char*)&b_n_, sizeof(uint8_t));\r\n\tf.read((char*)&i_, sizeof(uint8_t));\r\n\tOctreeNode::deserialize(f);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::RGB2LAB(uint8_t r, uint8_t g, uint8_t b,\r\n\tfloat &L, float &A, float &B)\r\n{\r\n\t// RGB to XYZ\r\n\tfloat rf = (static_cast<float> (r) / 255.);\r\n\tfloat gf = (static_cast<float> (g) / 255.);\r\n\tfloat bf = (static_cast<float> (b) / 255.);\r\n\tif (rf > 0.0405)\r\n\t\trf = std::pow(((rf + 0.055) / 1.055), 2.4);\r\n\telse\r\n\t\trf /= 12.92;\r\n\tif (gf > 0.0405)\r\n\t\tgf = std::pow(((gf + 0.055) / 1.055), 2.4);\r\n\telse\r\n\t\tgf /= 12.92;\r\n\tif (bf > 0.0405)\r\n\t\tbf = std::pow(((bf + 0.055) / 1.055), 2.4);\r\n\telse\r\n\t\tbf /= 12.92;\r\n\trf *= 100;\r\n\tgf *= 100;\r\n\tbf *= 100;\r\n\tfloat X = rf * 0.4124 + gf * 0.3576 + bf * 0.1805;\r\n\tfloat Y = rf * 0.2126 + gf * 0.7152 + bf * 0.0722;\r\n\tfloat Z = rf * 0.0193 + gf * 0.1192 + bf * 0.9505;\r\n\t// XYZ to LAB\r\n\tX /= 95.047;\r\n\tY /= 100.;\r\n\tZ /= 108.883;\r\n\tif (X > 0.008856)\r\n\t\tX = std::pow(static_cast<double> (X), 1 / 3.);\r\n\telse\r\n\t\tX = 7.787 * X + (16 / 116.);\r\n\tif (Y > 0.008856)\r\n\t\tY = std::pow(static_cast<double> (Y), 1 / 3.);\r\n\telse\r\n\t\tY = 7.787 * Y + (16 / 116.);\r\n\tif (Z > 0.008856)\r\n\t\tZ = std::pow(static_cast<double> (Z), 1 / 3.);\r\n\telse\r\n\t\tZ = 7.787 * Z + (16 / 116.);\r\n\tL = (116 * Y) - 16;\r\n\tA = 500 * (X - Y);\r\n\tB = 200 * (Y - Z);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::LAB2RGB(float L, float A, float B,\r\n\tuint8_t &r, uint8_t &g, uint8_t &b)\r\n{\r\n\t// LAB to XYZ\r\n\tfloat Y = (L + 16) / 116.;\r\n\tfloat X = A / 500. + Y;\r\n\tfloat Z = Y - (B / 200.);\r\n\tif (std::pow(X, 3) > 0.008856)\r\n\t\tX = std::pow(X, 3);\r\n\telse\r\n\t\tX = (X - 16 / 116.) / 7.787;\r\n\tif (std::pow(Y, 3) > 0.008856)\r\n\t\tY = std::pow(Y, 3);\r\n\telse\r\n\t\tY = (Y - 16 / 116.) / 7.787;\r\n\tif (std::pow(Z, 3) > 0.008856)\r\n\t\tZ = std::pow(Z, 3);\r\n\telse\r\n\t\tZ = (Z - 16 / 116.) / 7.787;\r\n\tX *= 95.047;\r\n\tY *= 100.;\r\n\tZ *= 108.883;\r\n\t// XYZ to RGB\r\n\tX /= 100;\r\n\tY /= 100;\r\n\tZ /= 100;\r\n\tfloat rf = X * +3.2406 + Y * -1.5372 + Z * -0.4986;\r\n\tfloat gf = X * -0.9689 + Y * +1.8758 + Z * +0.0415;\r\n\tfloat bf = X * +0.0557 + Y * -0.2040 + Z * +1.0570;\r\n\tif (rf > 0.0031308)\r\n\t\trf = 1.055 * std::pow(static_cast<double> (rf), 1. / 2.4) - 0.055;\r\n\telse\r\n\t\trf *= 12.92;\r\n\tif (gf > 0.0031308)\r\n\t\tgf = 1.055 * std::pow(static_cast<double> (gf), 1. / 2.4) - 0.055;\r\n\telse\r\n\t\tgf *= 12.92;\r\n\tif (bf > 0.0031308)\r\n\t\tbf = 1.055 * std::pow(static_cast<double> (bf), 1. / 2.4) - 0.055;\r\n\telse\r\n\t\tbf *= 12.92;\r\n\tr = static_cast<uint8_t> (rf * 255);\r\n\tg = static_cast<uint8_t> (gf * 255);\r\n\tb = static_cast<uint8_t> (bf * 255);\r\n}\r\n\r\n// LABNode\r\nbool\r\ncpu_tsdf::LABNode::addObservation(float d_new, float w_new, float max_weight,\r\n\tuint8_t r, uint8_t g, uint8_t b)\r\n{\r\n\tfloat wsum = w_ + w_new;\r\n\tfloat L_new, A_new, B_new;\r\n\tRGB2LAB(r, g, b, L_new, A_new, B_new);\r\n\tuint8_t r_reconv, g_reconv, b_reconv;\r\n\tLAB2RGB(L_new, A_new, B_new, r_reconv, g_reconv, b_reconv);\r\n\tL_ = (w_*L_ + w_new*L_new) / wsum;\r\n\tA_ = (w_*A_ + w_new*A_new) / wsum;\r\n\tB_ = (w_*B_ + w_new*B_new) / wsum;\r\n\treturn (OctreeNode::addObservation(d_new, w_new, max_weight));\r\n}\r\n\r\nbool\r\ncpu_tsdf::LABNode::getRGB(uint8_t &r, uint8_t &g, uint8_t &b) const\r\n{\r\n\tLAB2RGB(L_, A_, B_, r, g, b);\r\n\treturn (true);\r\n}\r\n\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::LABNode::instantiateNode(float x, float y, float z, float sx, float sy, float sz)\r\n{\r\n\treturn (new LABNode(x, y, z, sx, sy, sz));\r\n}\r\n\r\nstd::string\r\ncpu_tsdf::LABNode::getTypeString()\r\n{\r\n\treturn (\"LAB\");\r\n}\r\n\r\nvoid\r\ncpu_tsdf::LABNode::serialize(std::ostream &f) const\r\n{\r\n\tf.write((char*)&L_, sizeof(uint8_t));\r\n\tf.write((char*)&A_, sizeof(uint8_t));\r\n\tf.write((char*)&B_, sizeof(uint8_t));\r\n\tOctreeNode::serialize(f);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::LABNode::deserialize(std::istream &f)\r\n{\r\n\tf.read((char*)&L_, sizeof(uint8_t));\r\n\tf.read((char*)&A_, sizeof(uint8_t));\r\n\tf.read((char*)&B_, sizeof(uint8_t));\r\n\tOctreeNode::deserialize(f);\r\n}\r\n\r\n// Octree\r\nvoid\r\ncpu_tsdf::Octree::init(int num_splits)\r\n{\r\n\t// Starts with just one root node\r\n\troot_.reset(OctreeNode::instantiateByTypeString\r\n\t(voxel_type_, 0, 0, 0, size_x_, size_y_, size_z_));\r\n\troot_->splitRecursive(num_splits);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::Octree::init(float max_size_x, float max_size_y, float max_size_z)\r\n{\r\n\tint desired_res = std::max(size_x_ / max_size_x, std::max(size_y_ / max_size_y, size_z_ / max_size_z));\r\n\tint num_levels = std::ceil(std::log(desired_res) / std::log(2));\r\n\tinit(num_levels);\r\n}\r\n\r\ncpu_tsdf::OctreeNode::Ptr&\r\ncpu_tsdf::Octree::getRoot()\r\n{\r\n\treturn root_;\r\n}\r\n\r\nvoid\r\ncpu_tsdf::Octree::getLeaves(std::vector<OctreeNode::Ptr> &leaves, int num_levels) const\r\n{\r\n\t// Recursively find leaf nodes\r\n\tpcl::console::TicToc tt;\r\n\ttt.tic();\r\n\tif (num_levels == 0)\r\n\t\tleaves.push_back(root_);\r\n\telse\r\n\t\troot_->getLeaves(leaves, num_levels - 1);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::Octree::getLeaves(std::vector<OctreeNode::Ptr> &leaves, float max_size_x, float max_size_y, float max_size_z) const\r\n{\r\n\tint desired_res = std::max(size_x_ / max_size_x, std::max(size_y_ / max_size_y, size_z_ / max_size_z));\r\n\tint num_levels = std::ceil(std::log(desired_res) / std::log(2));\r\n\tgetLeaves(leaves, num_levels);\r\n}\r\n\r\n// Get the voxel which contains this point\r\nconst cpu_tsdf::OctreeNode*\r\ncpu_tsdf::Octree::getContainingVoxel(float x, float y, float z, float min_size) const\r\n{\r\n\tif (pcl_isnan(z) || std::fabs(x) > size_x_ / 2 || std::fabs(y) > size_y_ / 2 || std::fabs(z) > size_z_ / 2)\r\n\t\treturn (NULL);\r\n\treturn (root_->getContainingVoxel(x, y, z, min_size));\r\n}\r\n\r\n// Get the voxel which contains this point\r\ncpu_tsdf::OctreeNode*\r\ncpu_tsdf::Octree::getContainingVoxel(float x, float y, float z, float min_size)\r\n{\r\n\tif (pcl_isnan(z) || std::fabs(x) > size_x_ / 2 || std::fabs(y) > size_y_ / 2 || std::fabs(z) > size_z_ / 2)\r\n\t\treturn (NULL);\r\n\treturn (root_->getContainingVoxel(x, y, z, min_size));\r\n}\r\n\r\nvoid\r\ncpu_tsdf::Octree::serialize(std::ostream &f) const\r\n{\r\n\tf << root_->getTypeString() << std::endl;\r\n\tf << \"#OCTREEBINARY\" << std::endl;\r\n\tf.write((char*)&res_x_, sizeof(size_t));\r\n\tf.write((char*)&res_y_, sizeof(size_t));\r\n\tf.write((char*)&res_z_, sizeof(size_t));\r\n\tf.write((char*)&size_x_, sizeof(float));\r\n\tf.write((char*)&size_y_, sizeof(float));\r\n\tf.write((char*)&size_z_, sizeof(float));\r\n\troot_->serialize(f);\r\n}\r\n\r\nvoid\r\ncpu_tsdf::Octree::deserialize(std::istream &f)\r\n{\r\n\tstd::string root_type;\r\n\tf >> root_type;\r\n\troot_.reset(OctreeNode::instantiateByTypeString(root_type));\r\n\tchar tmp[1024];\r\n\tdo\r\n\t{\r\n\t\tf.getline(tmp, 1024);\r\n\t} while (!(tmp[0] == '#' && tmp[1] == 'O'));\r\n\tf.read((char*)&res_x_, sizeof(size_t));\r\n\tf.read((char*)&res_y_, sizeof(size_t));\r\n\tf.read((char*)&res_z_, sizeof(size_t));\r\n\tf.read((char*)&size_x_, sizeof(float));\r\n\tf.read((char*)&size_y_, sizeof(float));\r\n\tf.read((char*)&size_z_, sizeof(float));\r\n\troot_->deserialize(f);\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "355c56773bb6112064163ad3d684b3c7cf95b350", "size": 16619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VS2015/build/octree.cpp", "max_stars_repo_name": "DQ0408/cpu_tsdf", "max_stars_repo_head_hexsha": "79a8670ede8587dafbff26c4b225ac8e67f307d2", "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": "VS2015/build/octree.cpp", "max_issues_repo_name": "DQ0408/cpu_tsdf", "max_issues_repo_head_hexsha": "79a8670ede8587dafbff26c4b225ac8e67f307d2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VS2015/build/octree.cpp", "max_forks_repo_name": "DQ0408/cpu_tsdf", "max_forks_repo_head_hexsha": "79a8670ede8587dafbff26c4b225ac8e67f307d2", "max_forks_repo_licenses": ["BSD-3-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.9671875, "max_line_length": 127, "alphanum_fraction": 0.6294602563, "num_tokens": 5600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.06008665311947338, "lm_q1q2_score": 0.024475300712535494}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"tabulatedpotential.h\"\n#include \"../../include/votca/csg/version.h\"\n#include \"analysistool.h\"\n#include \"bondedstatistics.h\"\n#include <boost/lexical_cast.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <votca/tools/constants.h>\n#include <votca/tools/histogram.h>\n\nusing namespace std;\nusing namespace votca::tools;\n\nnamespace votca {\nnamespace csg {\n/******************************************************************************\n * Public Facing Methods\n ******************************************************************************/\nTabulatedPotential::TabulatedPotential() {\n  tab_smooth1_ = tab_smooth2_ = 0;\n  Temperature_ = 300;\n}\n\nvoid TabulatedPotential::Register(map<string, AnalysisTool *> &lib) {\n  lib[\"tab\"] = this;\n  lib[\"hist\"] = this;\n}\n\nvoid TabulatedPotential::Command(BondedStatistics &bs, const string &cmd,\n                                 vector<string> &args) {\n  if (args[0] == \"set\") {\n    if (cmd == \"hist\") {\n      SetOption_(hist_options_, args);\n    } else if (cmd == \"tab\") {\n      if (!SetOption_(tab_options_, args)) {\n        if (args.size() > 2) {\n          if (args[1] == \"smooth_pdf\") {\n            tab_smooth1_ = boost::lexical_cast<Index>(args[2]);\n          } else if (args[1] == \"smooth_pot\") {\n            tab_smooth2_ = boost::lexical_cast<Index>(args[2]);\n          } else if (args[1] == \"T\") {\n            Temperature_ = boost::lexical_cast<double>(args[2]);\n          } else {\n            cout << \"unknown option \" << args[2] << endl;\n            return;\n          }\n        }\n      }\n      if (args.size() <= 2) {\n        cout << \"smooth_pdf: \" << tab_smooth1_ << endl;\n        cout << \"smooth_pot: \" << tab_smooth2_ << endl;\n        cout << \"T: \" << Temperature_ << endl;\n      }\n    }\n  } else if (args.size() >= 2) {\n    if (cmd == \"hist\") {\n      WriteHistogram(bs, args);\n    } else if (cmd == \"tab\") {\n      WritePotential(bs, args);\n    }\n  } else {\n    cout << \"wrong number of arguments\" << endl;\n  }\n}\n\nvoid TabulatedPotential::Help(const string &cmd, vector<string> &args) {\n  if (args.size() == 0) {\n    if (cmd == \"tab\") {\n      cout << \"tab <file> <selection>\\n\"\n           << \"Calculate tabulated potential by inverting the distribution \"\n              \"function. Statistics is calculated using all interactions in \"\n              \"selection.\\nsee also: help tab set\\n\\nexample:\\ntab set scale \"\n              \"bond\\ntab U_bond.txt *:bond:*\\n\";\n    }\n    if (cmd == \"hist\") {\n      cout << \"hist <file> <selection>\\n\"\n           << \"Calculate distribution function for selection. Statistics is \"\n              \"calculated using all interactions in selection.\\n see also: help\"\n              \" hist set\\n\\nexample:hist U_bond.txt *:bond:*\\n\";\n    }\n    return;\n  }\n  if (args[0] == \"set\") {\n    if (args.size() == 1) {\n      cout << cmd << \" set <option> <value>\\n\"\n           << \"set option for this command. Use \\\"\" << cmd\n           << \" set\\\" for a list of available options. To get help on a \"\n              \"specific option use e.g.\\n\"\n           << cmd << \" set periodic\\n\";\n      return;\n    }\n    if (args[1] == \"n\") {\n      cout << cmd << \"set n <integer>\\n\"\n           << \"set number of bins for table\\n\";\n      return;\n    }\n    if (args[1] == \"min\") {\n      cout << cmd << \"set min <value>\\n\"\n           << \"minimum value of interval for histogram (see also periodic, \"\n              \"extend)\\n\";\n      return;\n    }\n    if (args[1] == \"max\") {\n      cout << cmd << \"set max <value>\\n\"\n           << \"maximum value of interval for histogram (see also periodic, \"\n              \"extend)\\n\";\n      return;\n    }\n    if (args[1] == \"periodic\") {\n      cout << cmd << \"set periodic <value>\\n\"\n           << \"can be 1 for periodic interval (e.g. dihedral) or 0 for \"\n              \"non-periodic (e.g. bond)\\n\";\n      return;\n    }\n    if (args[1] == \"auto\") {\n      cout << cmd\n           << \"set auto <value>\\n\"\n              \"can be 1 for automatically determine the interval for the table \"\n              \"(min, max, extend will be ignored) or 0 to use min/max as \"\n              \"specified\\n\";\n      return;\n    }\n    if (args[1] == \"extend\") {\n      cout << cmd\n           << \"set extend <value>\\n\"\n              \"should only be used with auto=0. Can be 1 for extend the \"\n              \"interval if values are out of bounds (min/max) or 0 to \"\n              \"ignore values which are out of the interal\\n\";\n      return;\n    }\n    if (args[1] == \"scale\") {\n      cout << cmd\n           << \"set scale <value>\\n\"\n              \"volume normalization of pdf. Can be no (no scaling), bond \"\n              \"(1/r^2) or angle ( 1/sin(phi) ). See VOTCA manual, section \"\n              \"theoretical background for details\\n\";\n      return;\n    }\n    if (args[1] == \"normalize\") {\n      cout\n          << cmd\n          << \"set normalize <value>\\n\"\n             \"can be 1 for a normalized histogram or 0 to skip normalization\\n\";\n      return;\n    }\n\n    if (cmd == \"tab\") {\n      if (args[1] == \"smooth_pdf\") {\n        cout << \"tab set smooth_pdf <value>\\n\"\n                \"Perform so many smoothing iterations on the distribution \"\n                \"function before inverting the potential\\n\";\n        return;\n      }\n      if (args[1] == \"smooth_pot\") {\n        cout << \"tab set smooth_pot <value>\\n\"\n                \"Perform so many smoothing iterations on tabulated potential \"\n                \"after inverting the potential\\n\";\n        return;\n      }\n      if (args[1] == \"T\") {\n        cout << \"tab set T <value>\\n\"\n                \"Temperature in Kelvin the simulation was performed\\n\";\n        return;\n      }\n    }\n  }\n\n  cout << \"no help text available\" << endl;\n}\n\ndouble TabulatedPotential::getTemperature() const { return Temperature_; }\n\npair<Index, Index> TabulatedPotential::getSmoothIterations() const {\n  return pair<Index, Index>(tab_smooth1_, tab_smooth2_);\n}\n\nvoid TabulatedPotential::WriteHistogram(BondedStatistics &bs,\n                                        vector<string> &args) {\n  ofstream out;\n  DataCollection<double>::selection *sel = nullptr;\n\n  for (size_t i = 1; i < args.size(); i++) {\n    sel = bs.BondedValues().select(args[i], sel);\n  }\n  Histogram h(hist_options_);\n  h.ProcessData(sel);\n  out.open(args[0]);\n  out << h;\n  out.close();\n  cout << \"histogram created using \" << sel->size() << \" data-rows, written to \"\n       << args[0] << endl;\n  delete sel;\n}\n\nvoid TabulatedPotential::WritePotential(BondedStatistics &bs,\n                                        vector<string> &args) {\n  ofstream out;\n  DataCollection<double>::selection *sel = nullptr;\n\n  // Appends all the interactions that are specified in args to selection\n  // pointer given by sel\n\n  for (size_t i = 1; i < args.size(); i++) {\n    sel = bs.BondedValues().select(args[i], sel);\n  }\n\n  Histogram h(tab_options_);\n\n  h.ProcessData(sel);\n  for (Index i = 0; i < tab_smooth1_; ++i) {\n    Smooth_(h.getPdf(), tab_options_.periodic_);\n  }\n  BoltzmannInvert_(h.getPdf());\n  for (Index i = 0; i < tab_smooth2_; ++i) {\n    Smooth_(h.getPdf(), tab_options_.periodic_);\n  }\n  out.open(args[0]);\n\n  vector<double> F;\n  assert(h.getInterval() > 0 && \"Interval for pdf histogram is 0\");\n  CalcForce_(h.getPdf(), F, h.getInterval(), tab_options_.periodic_);\n  for (Index i = 0; i < h.getN(); i++) {\n    out << h.getMin() + h.getInterval() * ((double)i) << \" \" << h.getPdf()[i]\n        << \" \" << F[i] << endl;\n  }\n  out.close();\n  cout << \"histogram created using \" << sel->size() << \" data-rows, written to \"\n       << args[0] << endl;\n  delete sel;\n}\n\n/******************************************************************************\n * Private Facing Methods\n ******************************************************************************/\nbool TabulatedPotential::SetOption_(Histogram::options_t &op,\n                                    const vector<string> &args) {\n  if (args.size() > 2) {\n    if (args[1] == \"n\") {\n      op.n_ = boost::lexical_cast<Index>(args[2]);\n    } else if (args[1] == \"min\") {\n      op.min_ = boost::lexical_cast<double>(args[2]);\n    } else if (args[1] == \"max\") {\n      op.max_ = boost::lexical_cast<double>(args[2]);\n    } else if (args[1] == \"periodic\") {\n      op.periodic_ = boost::lexical_cast<bool>(args[2]);\n    } else if (args[1] == \"auto\") {\n      op.auto_interval_ = boost::lexical_cast<bool>(args[2]);\n    } else if (args[1] == \"extend\") {\n      op.extend_interval_ = boost::lexical_cast<bool>(args[2]);\n    } else if (args[1] == \"normalize\") {\n      op.normalize_ = boost::lexical_cast<bool>(args[2]);\n    } else if (args[1] == \"scale\") {\n      if (args[2] == \"no\" || args[2] == \"bond\" || args[2] == \"angle\") {\n        op.scale_ = args[2];\n      } else {\n        cout << \"scale can be: no, bond or angle\\n\";\n      }\n    } else {\n      return false;\n    }\n  } else {\n    cout << \"n: \" << op.n_ << endl;\n    cout << \"min: \" << op.min_ << endl;\n    cout << \"max: \" << op.max_ << endl;\n    cout << \"periodic: \" << op.periodic_ << endl;\n    cout << \"auto: \" << op.auto_interval_ << endl;\n    cout << \"extend: \" << op.extend_interval_ << endl;\n    cout << \"scale: \" << op.scale_ << endl;\n    cout << \"normalize: \" << op.normalize_ << endl;\n  }\n  return true;\n}\n\nvoid TabulatedPotential::CalcForce_(vector<double> &U, vector<double> &F,\n                                    double dx, bool bPeriodic) {\n  size_t n = U.size();\n  double f = 0.5 / dx;\n  F.resize(n);\n  if (bPeriodic) {\n    F[n - 1] = F[0] = -(U[1] - U[n - 2]) * f;\n  } else {\n    F[0] = -(U[1] - U[0]) * 2 * f;\n    F[n - 1] = -(U[n - 1] - U[n - 2]) * 2 * f;\n  }\n  for (size_t i = 1; i < n - 1; i++) {\n    F[i] = -(U[i + 1] - U[i - 1]) * f;\n  }\n}\n\nvoid TabulatedPotential::Smooth_(vector<double> &data, bool bPeriodic) {\n  double old[3];\n  Index n = Index(data.size());\n  if (bPeriodic) {\n    old[0] = data[n - 3];\n    old[1] = data[n - 2];\n  } else {\n    old[0] = data[0];\n    old[1] = data[0];\n  }\n  Index i;\n  for (i = 0; i < Index(data.size()) - 2; i++) {\n    old[2] = data[i];\n    data[i] =\n        (old[0] + 2. * old[1] + 3. * data[i] + 2. * data[i + 1] + data[i + 2]) /\n        9.;\n    old[0] = old[1];\n    old[1] = old[2];\n  }\n  if (bPeriodic) {\n    data[i] =\n        (old[0] + 2. * old[1] + 3. * data[i] + 2. * data[i + 1] + data[0]) / 9.;\n    data[n - 1] = data[0];\n  } else {\n    data[i] = (old[0] + 2. * old[1] + 3. * data[i] + 3. * data[i + 1]) / 9.;\n    old[0] = old[1];\n    old[1] = data[i];\n    i++;\n    data[i] = (old[0] + 2. * old[1] + 6. * data[i]) / 9.;\n  }\n}\n\nvoid TabulatedPotential::BoltzmannInvert_(vector<double> &data) {\n\n  double min = std::numeric_limits<double>::max();\n  double max = std::numeric_limits<double>::min();\n\n  for (double i : data) {\n    max = std::max(i, max);\n    if (i > 0) {\n      min = std::min(i, min);\n    }\n  }\n  max = -conv::kB * conv::ev2kj_per_mol * Temperature_ * std::log(max);\n  min = -conv::kB * conv::ev2kj_per_mol * Temperature_ * std::log(min) - max;\n\n  for (double &i : data) {\n    if (i == 0) {\n      i = min;\n    } else {\n      i = -conv::kB * conv::ev2kj_per_mol * Temperature_ * std::log(i) - max;\n    }\n  }\n}\n\n}  // namespace csg\n}  // namespace votca\n", "meta": {"hexsha": "601949e1c522a80da2bd730cb4f218d4349067ef", "size": 11786, "ext": "cc", "lang": "C++", "max_stars_repo_path": "csg/src/csg_boltzmann/tabulatedpotential.cc", "max_stars_repo_name": "ipelupessy/votca", "max_stars_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "csg/src/csg_boltzmann/tabulatedpotential.cc", "max_issues_repo_name": "ipelupessy/votca", "max_issues_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "csg/src/csg_boltzmann/tabulatedpotential.cc", "max_forks_repo_name": "ipelupessy/votca", "max_forks_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1144414169, "max_line_length": 80, "alphanum_fraction": 0.5275750891, "num_tokens": 3356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.05340332565681315, "lm_q1q2_score": 0.02441262095842508}}
{"text": "/*****************************************************************************\n *   GATB : Genome Assembly Tool Box\n *   Copyright (C) 2014  INRIA\n *   Authors: R.Chikhi, G.Rizk, E.Drezen\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\n *  published by the Free Software Foundation, either version 3 of the\n *  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 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/** \\file Integer.hpp\n *  \\date 01/03/2013\n *  \\author edrezen\n *  \\brief Entry point class for large integer usage\n */\n#ifndef _GATB_CORE_TOOLS_MATH_INTEGER_HPP_\n#define _GATB_CORE_TOOLS_MATH_INTEGER_HPP_\n\n/********************************************************************************/\n#include <gatb/tools/math/LargeInt.hpp>\n#include <gatb/system/api/Exception.hpp>\n\n#include <boost/variant.hpp>\n\n/********************************************************************************/\nnamespace gatb  {  namespace core  { namespace tools {  namespace math  {\n/********************************************************************************/\n\n/** \\brief Class for large integers calculus\n *\n * The IntegerTemplate is implemented as a boost variant, which means that it can act like T1, T2, T3 or T4 type\n * according to the configuration.\n *\n * The IntegerTemplate should be specialized with 4 different LargeInt implementation\n * classes.\n *\n * All the methods are implemented through a boost variant visitor.\n *\n *  According to the INTEGER_KIND compilation flag, we define the Integer class\n *  as an alias of one from several possible implementations.\n *\n *  Note that we have 2 possible native implementations (NativeInt64 and NativeInt128)\n *  that rely on native types uint64_t and __uint128_t.\n *\n *  For larger integer, a multi-precision LargeInt is used.\n *\n *  From the user point of view, [s]he has just to include this file and use the Integer\n *  class.\n *\n */\ntemplate<typename T1, typename T2, typename T3, typename T4>\nclass IntegerTemplate\n{\nprivate:\n\n    typedef boost::variant<T1,T2,T3,T4> Type;\n    Type v;\n\n          Type& operator *()       { return v; }\n    const Type& operator *() const { return v; }\n\npublic:\n\n    /** Get a number telling which template class is actually used by the variant.\n     * \\return an integer n, meaning that the Tn template type is used.\n     */\n    static char& getType()  {  static char instance = 0; return instance; }\n\n    /** Set the type of which template class has to be used by the variant.\n     * \\param[in] type : integer value\n     */\n    static void setType (char type)  {  getType() = type; }\n\n    /** Constructor. Note that the type (see getType and setType) has to be first initialized\n     * otherwise no instance can be created (exception thrown).\n     * \\param[in] n : value for initialization of the integer.\n     */\n    IntegerTemplate (int64_t n=0)\n    {\n        switch (getType())\n        {\n        case PREC_1: v = T1(n); break;\n        case PREC_2: v = T2(n); break;\n        case PREC_3: v = T3(n); break;\n        case PREC_4: v = T4(n); break;\n        default:  if (getType()<=PREC_4) { v = T4(n);  break; }\n                  else { throw system::Exception (\"class Integer not initialized\"); }\n        }\n    }\n\n    /** Copy constructor. Relies on the copy constructor of boost variant\n     * \\param[in] t : the object to be used for initialization\n     */\n    template<typename T>  explicit IntegerTemplate (const T& t) : v (t)  {}\n\n    /** Affectation operator. Relies on the affectation operator of boost variant\n     * \\param[in] t : object to be copied\n     * \\return the current object.\n     */\n    template<typename T>\n    IntegerTemplate& operator=(const T& t)\n    {\n        v = t;\n        return *this;\n    }\n\n    /** Get the name of the class used by the variant (ie. one of the Ti template class parameters)\n     * \\return the class name.\n     */\n    const char*  getName ()         { return boost::apply_visitor (Integer_name(),  *(*this)); }\n\n    /** Get the size of an instance of the class used by the variant  (ie. one of the Ti template class parameters)\n     * \\return the size of an object (in bits).\n     */\n    const size_t getSize ()         { return boost::apply_visitor (Integer_size(),  *(*this)); }\n\n    /** Get the HDF5 type for the the class used by the variant  (ie. one of the Ti template class parameters)\n     * \\param[in] isCompound : tells whether the type is composed or not\n     * \\return a HDF5 identifier for the type.\n     */\n    hid_t hdf5 (bool& isCompound)   { return boost::apply_visitor (Integer_hdf5(isCompound),  *(*this)); }\n\n    /** Operator +\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return sum of the two operands.\n     */\n    inline friend IntegerTemplate   operator+  (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_plus(),  *a, *b);  }\n\n    /** Operator -\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return substraction of the two operands.\n     */\n    inline friend IntegerTemplate   operator-  (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_minus(), *a, *b);  }\n\n    /** Operator |\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return 'or' of the two operands.\n     */\n    inline friend IntegerTemplate   operator|  (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_or(),    *a, *b);  }\n\n    /** Operator ^\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return 'xor' of the two operands.\n     */\n    inline friend IntegerTemplate   operator^  (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_xor(),   *a, *b);  }\n\n    /** Operator &\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return 'and' of the two operands.\n     */\n    inline friend IntegerTemplate   operator&  (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_and(),   *a, *b);  }\n\n    /** Operator ~\n     * \\param[in] a : operand\n     * \\return negation of the operand\n     */\n    inline friend IntegerTemplate   operator~  (const IntegerTemplate& a)                    {  Integer_compl v; return  boost::apply_visitor (v, *a);  }\n\n    /** Operator ==\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return equality of the two operands.\n     */\n    inline friend bool      operator== (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_equals(), *a, *b);  }\n\n    /** Operator !=\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return inequality of the two operands.\n     */\n    inline friend bool      operator!= (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  ! (*a==*b);  }\n\n    /** Operator <\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return '<' of the two operands.\n     */\n    inline friend bool      operator<  (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_less(),   *a, *b);  }\n\n    /** Operator <=\n     * \\param[in] a : first operand\n     * \\param[in] b : second operand\n     * \\return '<=' of the two operands.\n     */\n    inline friend bool      operator<= (const IntegerTemplate& a, const IntegerTemplate& b)  {  return  boost::apply_visitor (Integer_lesseq(), *a, *b);  }\n\n    /** Operator *\n     * \\param[in] a : first operand\n     * \\param[in] c : second operand\n     * \\return multiplication of the two operands.\n     */\n    inline friend IntegerTemplate   operator*  (const IntegerTemplate& a, const int&       c)  {  return  boost::apply_visitor (Integer_mult(c), *a);  }\n\n    /** Operator /\n     * \\param[in] a : first operand\n     * \\param[in] c : second operand\n     * \\return division of the two operands.\n     */\n    inline friend IntegerTemplate   operator/  (const IntegerTemplate& a, const u_int32_t& c)  {  return  boost::apply_visitor (Integer_div(c),  *a);  }\n\n    /** Operator %\n     * \\param[in] a : first operand\n     * \\param[in] c : second operand\n     * \\return modulo of the two operands.\n     */\n    inline friend u_int32_t operator%  (const IntegerTemplate& a, const u_int32_t& c)  {  return  boost::apply_visitor (Integer_mod(c),  *a);  }\n\n    /** Operator >>\n     * \\param[in] a : first operand\n     * \\param[in] c : second operand\n     * \\return right shift of the two operands.\n     */\n    inline friend IntegerTemplate   operator>> (const IntegerTemplate& a, const int& c)  {  return  boost::apply_visitor (Integer_shiftLeft(c),   *a);  }\n\n    /** Operator <<\n     * \\param[in] a : first operand\n     * \\param[in] c : second operand\n     * \\return left shift of the two operands.\n     */\n    inline friend IntegerTemplate   operator<< (const IntegerTemplate& a, const int& c)  {  return  boost::apply_visitor (Integer_shiftRight(c),  *a);  }\n\n    /** Operator +=\n     * \\param[in] a : first operand\n     * \\return addition and affectation.\n     */\n    void operator+= (const IntegerTemplate& a)  {  boost::apply_visitor (Integer_plusaffect(),  *(*this), *a);  }\n\n    /** Operator ^=\n     * \\param[in] a : first operand\n     * \\return xor and affectation.\n     */\n    void operator^= (const IntegerTemplate& a)  {  boost::apply_visitor (Integer_xoraffect(),   *(*this), *a);  }\n\n    /** Operator[] access the ith nucleotide in the given integer. For instance a[4] get the 5th nucleotide of\n     * a kmer encoded as an Integer object.\n     * \\param[in] idx : index of the nucleotide to be retrieved\n     * \\return the nucleotide value as follow: A=0, C=1, T=2 and G=3\n     */\n    u_int8_t  operator[]  (size_t idx) const   { return  boost::apply_visitor (Integer_value_at(idx), *(*this)); }\n\n    /** Get the reverse complement of a kmer encoded as an IntegerTemplate object. Note that the kmer size must be known.\n     * \\param[in] a : kmer value to be reversed-complemented\n     * \\param[in] sizeKmer : size of the kmer\n     * \\return the reverse complement kmer as a IntegerTemplate value\n     */\n    friend IntegerTemplate revcomp (const IntegerTemplate& a,  size_t sizeKmer)  {  return  boost::apply_visitor (Integer_revomp(sizeKmer),  *a);  }\n\n    /** Get a hash value on 64 bits for a given IntegerTemplate object.\n     * \\param[in] a : the integer value\n     * \\param[in] seed : some seed value used for the hash computation.\n     * \\return the hash value on 64 bits.\n     */\n    friend u_int64_t hash1        (const IntegerTemplate& a,  u_int64_t seed)  {  return  boost::apply_visitor (Integer_hash1(seed),  *a);          }\n\n    /** Get a hash value on 64 bits for a given IntegerTemplate object.\n     * \\param[in] a : the integer value\n     * \\return the hash value on 64 bits.\n     */\n    friend u_int64_t oahash       (const IntegerTemplate& a)                   {  return  boost::apply_visitor (Integer_oahash(), *a);              }\n\n    /** Get a hash value on 64 bits for a given IntegerTemplate object.\n     * Note: although we return 64 bits, only the first 16 bits are set\n     * \\param[in] a : the integer value\n     * \\param[in] shift : some value used for the hash computation.\n     * \\return the hash value on 64 bits.\n     */\n    friend u_int64_t simplehash16 (const IntegerTemplate& a,  int shift)       {  return  boost::apply_visitor (Integer_simplehash16(shift),  *a);  }\n\n    /** Get an ASCII string representation of a kmer encoded as a IntegerTemplate object\n     * \\param[in] sizeKmer : size of the kmer\n     * \\return the ASCII representation of the kmer.\n     */\n    std::string toString (size_t sizeKmer) const  {  return boost::apply_visitor (Integer_toString(sizeKmer), *(*this)); }\n\n    /** Output stream operator for the IntegerTemplate class\n     * \\param[in] s : the output stream to be used.\n     * \\param[in] a : the object to output\n     * \\return the modified output stream.\n     */\n    friend std::ostream & operator<<(std::ostream & s, const IntegerTemplate& a)  {  s << *a;  return s;  }\n\n    /** Get the value of the IntegerTemplate object as a U type, U being one of the T1,T2,T3,T4\n     * template class parameters. This method can be seen as a converter from the IntegerTemplate class\n     * to a specific U type (given as a template parameter of this method).\n     * \\return  the converted value as a U type.\n     */\n    template<typename U>\n    const U& get ()  const  {  return * boost::get<U>(&v);  }\n\nprivate:\n\n    struct Integer_name : public boost::static_visitor<const char*>    {\n        template<typename T>  const char* operator() (const T& a) const { return a.getName();  }};\n\n    struct Integer_size : public boost::static_visitor<const size_t>    {\n        template<typename T>  const size_t operator() (const T& a) const  { return a.getSize();  }};\n\n    struct Integer_plus : public boost::static_visitor<IntegerTemplate>    {\n        template<typename T>              IntegerTemplate operator() (const T& a, const T& b) const  { return IntegerTemplate(a + b);  }\n        template<typename T, typename U>  IntegerTemplate operator() (const T& a, const U& b) const  { return IntegerTemplate();       }\n    };\n\n    struct Integer_minus : public boost::static_visitor<IntegerTemplate>    {\n        template<typename T>              IntegerTemplate operator() (const T& a, const T& b) const  { return IntegerTemplate(a - b);  }\n        template<typename T, typename U>  IntegerTemplate operator() (const T& a, const U& b) const  { return IntegerTemplate();  }\n    };\n\n    struct Integer_or : public boost::static_visitor<IntegerTemplate>    {\n        template<typename T>              IntegerTemplate operator() (const T& a, const T& b) const  { return IntegerTemplate(a | b);  }\n        template<typename T, typename U>  IntegerTemplate operator() (const T& a, const U& b) const  { return IntegerTemplate();  }\n    };\n\n    struct Integer_xor : public boost::static_visitor<IntegerTemplate>    {\n        template<typename T>              IntegerTemplate operator() (const T& a, const T& b) const  { return IntegerTemplate(a ^ b);  }\n        template<typename T, typename U>  IntegerTemplate operator() (const T& a, const U& b) const  { return IntegerTemplate();  }\n    };\n\n    struct Integer_and : public boost::static_visitor<IntegerTemplate>    {\n        template<typename T>              IntegerTemplate operator() (const T& a, const T& b) const  { return IntegerTemplate(a & b);  }\n        template<typename T, typename U>  IntegerTemplate operator() (const T& a, const U& b) const  { return IntegerTemplate();  }\n    };\n\n    struct Integer_less : public boost::static_visitor<bool>    {\n        template<typename T>              bool operator() (const T& a, const T& b) const  { return a < b;  }\n        template<typename T, typename U>  bool operator() (const T& a, const U& b) const  { return false;  }\n    };\n\n    struct Integer_lesseq : public boost::static_visitor<bool>    {\n        template<typename T>              bool operator() (const T& a, const T& b) const  { return a <= b;  }\n        template<typename T, typename U>  bool operator() (const T& a, const U& b) const  { return false;   }\n    };\n\n    struct Integer_equals : public boost::static_visitor<bool>    {\n        template<typename T>              bool operator() (const T& a, const T& b) const  { return a == b;  }\n        template<typename T, typename U>  bool operator() (const T& a, const U& b) const  { return false;   }\n    };\n\n    struct Integer_plusaffect : public boost::static_visitor<>    {\n        template<typename T>              void operator() ( T& a, const T& b) const  { a += b;  }\n        template<typename T, typename U>  void operator() ( T& a, const U& b) const  {   }\n    };\n\n    struct Integer_xoraffect : public boost::static_visitor<>    {\n        template<typename T>              void operator() ( T& a, const T& b) const  { a ^= b;  }\n        template<typename T, typename U>  void operator() ( T& a, const U& b) const  {   }\n    };\n\n    struct Integer_compl : public boost::static_visitor<IntegerTemplate>    {\n        template<typename T>  IntegerTemplate operator() (const T& a)  { return IntegerTemplate(~a);  }};\n\n    template<typename Result, typename Arg>\n    struct Visitor : public boost::static_visitor<Result>\n    {\n        Visitor (Arg a=Arg()) : arg(a) {}\n        Arg arg;\n    };\n\n\n\n\t\n    struct Integer_hdf5 : public Visitor<hid_t,bool&>   {\n        Integer_hdf5 (bool& c) : Visitor<IntegerTemplate,bool&>(c) {}\n        template<typename T>  hid_t operator() (const T& a)  { return a.hdf5 (this->arg);  }};\n\n    struct Integer_mult : public Visitor<IntegerTemplate,const int>    {\n        Integer_mult (const int& c) : Visitor<IntegerTemplate,const int>(c) {}\n        template<typename T>  IntegerTemplate operator() (const T& a) const  { return IntegerTemplate(a*this->arg);  }};\n\n    struct Integer_div : public Visitor<IntegerTemplate,const u_int32_t>    {\n        Integer_div (const u_int32_t& c) : Visitor<IntegerTemplate,const u_int32_t>(c) {}\n        template<typename T>  IntegerTemplate operator() (const T& a) const  { return IntegerTemplate(a/this->arg);  }};\n\n    struct Integer_mod : public Visitor<u_int32_t,const u_int32_t>    {\n        Integer_mod (const u_int32_t& c) : Visitor<u_int32_t,const u_int32_t>(c) {}\n        template<typename T>  u_int32_t operator() (const T& a) const  { return (a%this->arg);  }};\n\n    struct Integer_shiftLeft : public Visitor<IntegerTemplate,const int>    {\n        Integer_shiftLeft (const int& c) : Visitor<IntegerTemplate,const int>(c) {}\n        template<typename T>  IntegerTemplate operator() (const T& a) const  { return IntegerTemplate (a >> this->arg);  }};\n\n    struct Integer_shiftRight : public Visitor<IntegerTemplate,const int>    {\n        Integer_shiftRight (const int& c) : Visitor<IntegerTemplate,const int>(c) {}\n        template<typename T>  IntegerTemplate operator() (const T& a) const  { return IntegerTemplate (a << this->arg);  }};\n\n    struct Integer_revomp : public Visitor<IntegerTemplate,size_t>    {\n        Integer_revomp (const size_t& c) : Visitor<IntegerTemplate,size_t>(c) {}\n        template<typename T>  IntegerTemplate operator() (const T& a) const  { return IntegerTemplate (revcomp(a,this->arg));  }};\n\n    struct Integer_hash1 : public Visitor<u_int64_t,u_int64_t>    {\n        Integer_hash1 (const u_int64_t& c) : Visitor<u_int64_t,u_int64_t>(c) {}\n        template<typename T>  u_int64_t operator() (const T& a) const  { return (hash1(a,this->arg));  }};\n\n    struct Integer_oahash : public boost::static_visitor<u_int64_t>    {\n        template<typename T>  u_int64_t operator() (const T& a) const  { return (oahash(a));  }};\n\n\t\n    struct Integer_simplehash16 : public Visitor<u_int64_t,int>    {\n        Integer_simplehash16 (const int& c) : Visitor<u_int64_t,int>(c) {}\n        template<typename T>  u_int64_t operator() (const T& a) const  { return (simplehash16(a,this->arg));  }};\n\n    struct Integer_value_at : public Visitor<u_int8_t,size_t>   {\n        Integer_value_at (size_t idx) : Visitor<u_int8_t,size_t>(idx) {}\n        template<typename T>  u_int8_t operator() (const T& a) const { return a[this->arg];  }};\n\n    struct Integer_toString : public Visitor<std::string,size_t>   {\n        Integer_toString (size_t c) : Visitor<std::string,size_t>(c) {}\n        template<typename T>  std::string operator() (const T& a) const  { return a.toString(this->arg);  }};\n};\n\n/********************************************************************************/\n\n#define INTEGER_TYPES   LargeInt<PREC_1>,LargeInt<PREC_2>,LargeInt<PREC_3>,LargeInt<PREC_4>\n\ntypedef IntegerTemplate <INTEGER_TYPES> Integer;\n\n/********************************************************************************/\n}}}};\n/********************************************************************************/\n\n#endif /* _GATB_CORE_TOOLS_MATH_INTEGER_HPP_ */\n", "meta": {"hexsha": "680d9733964577044b2b8f6819079d2d39fd2e4d", "size": 20508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/src/gatb/tools/math/Integer.hpp", "max_stars_repo_name": "cwright7101/llvm_sarvavid", "max_stars_repo_head_hexsha": "7567d617a7be78fecfde71ab04ebd8e9506a64e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/src/gatb/tools/math/Integer.hpp", "max_issues_repo_name": "cwright7101/llvm_sarvavid", "max_issues_repo_head_hexsha": "7567d617a7be78fecfde71ab04ebd8e9506a64e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SarvLibrary/ErrorCorrection/LoRDEC/thirdparty/gatb-core/src/gatb/tools/math/Integer.hpp", "max_forks_repo_name": "cwright7101/llvm_sarvavid", "max_forks_repo_head_hexsha": "7567d617a7be78fecfde71ab04ebd8e9506a64e4", "max_forks_repo_licenses": ["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.1448275862, "max_line_length": 162, "alphanum_fraction": 0.622927638, "num_tokens": 5177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.05419872905933377, "lm_q1q2_score": 0.024356509636615727}}
{"text": "/*=============================================================================\n  Copyright (c) 2010-2016 Bolero MURAKAMI\n  https://github.com/bolero-MURAKAMI/Sprig\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 SPRIG_NTL_FROM_ZZ_HPP\n#define SPRIG_NTL_FROM_ZZ_HPP\n\n#include <sprig/config/config.hpp>\n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_signed.hpp>\n#include <boost/type_traits/is_unsigned.hpp>\n#include <boost/type_traits/is_float.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/not.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <sprig/external/ntl/zz.hpp>\n#include <sprig/external/ntl/rr.hpp>\n#include <sprig/external/ntl/xdouble.hpp>\n#include <sprig/external/ntl/quad_float.hpp>\n\nnamespace sprig {\n\t//\n\t// from_ZZ\n\t//\n\t// specialization from_ZZ: T == NTL::ZZ\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<typename boost::remove_const<T>::type, NTL::ZZ>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn target;\n\t}\n\t//\n\t// specialization from_ZZ: T == NTL::RR\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<typename boost::remove_const<T>::type, NTL::RR>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_RR(target);\n\t}\n\t//\n\t// specialization from_ZZ: T == NTL::xdouble\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<typename boost::remove_const<T>::type, NTL::xdouble>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_xdouble(target);\n\t}\n\t//\n\t// specialization from_ZZ: T == NTL::quad_float\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<typename boost::remove_const<T>::type, NTL::quad_float>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_quad_float(target);\n\t}\n\t//\n\t// specialization from_ZZ: T == int\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<typename boost::remove_const<T>::type, int>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_int(target);\n\t}\n\t//\n\t// specialization from_ZZ: is_signed(T) && T != int\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::mpl::and_<\n\t\t\t\tboost::is_signed<T>,\n\t\t\t\tboost::mpl::not_<\n\t\t\t\t\tboost::is_same<typename boost::remove_const<T>::type, int>\n\t\t\t\t>\n\t\t\t>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_long(target);\n\t}\n\t//\n\t// specialization from_ZZ: T == unsigned int\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<typename boost::remove_const<T>::type, unsigned int>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_uint(target);\n\t}\n\t//\n\t// specialization from_ZZ: is_unsigned(T) && T != unsigned int\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::mpl::and_<\n\t\t\t\tboost::is_unsigned<T>,\n\t\t\t\tboost::mpl::not_<\n\t\t\t\t\tboost::is_same<typename boost::remove_const<T>::type, unsigned int>\n\t\t\t\t>\n\t\t\t>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_ulong(target);\n\t}\n\t//\n\t// specialization from_ZZ: T == float\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<typename boost::remove_const<T>::type, float>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_float(target);\n\t}\n\t//\n\t// specialization from_ZZ: is_float(T) && T != float\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE T from_ZZ(\n\t\tNTL::ZZ const& target,\n\t\ttypename boost::enable_if<\n\t\t\tboost::mpl::and_<\n\t\t\t\tboost::is_float<T>,\n\t\t\t\tboost::mpl::not_<\n\t\t\t\t\tboost::is_same<typename boost::remove_const<T>::type, float>\n\t\t\t\t>\n\t\t\t>\n\t\t>::type* = 0\n\t\t)\n\t{\n\t\treturn NTL::to_double(target);\n\t}\n}\t// namespace sprig\n\n#endif\t// #ifndef SPRIG_NTL_FROM_ZZ_HPP\n", "meta": {"hexsha": "38dc1bbf2de2fd710219c359e0d9bd828352f6c0", "size": 4184, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/ntl/from_ZZ.hpp", "max_stars_repo_name": "bolero-MURAKAMI/Sprig", "max_stars_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-24T13:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-28T13:21:22.000Z", "max_issues_repo_path": "sprig/ntl/from_ZZ.hpp", "max_issues_repo_name": "bolero-MURAKAMI/Sprig", "max_issues_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "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": "sprig/ntl/from_ZZ.hpp", "max_forks_repo_name": "bolero-MURAKAMI/Sprig", "max_forks_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T03:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-28T13:21:22.000Z", "avg_line_length": 23.1160220994, "max_line_length": 79, "alphanum_fraction": 0.6520076482, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.07263670535703559, "lm_q1q2_score": 0.02430347465988284}}
{"text": "#pragma once\n#include <boost/program_options.hpp>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <fstream>\n#include <math.h>\n\n/*\nREADME\nTo avoid confusion in indexing:\n  x goes along heigth\n  y goes along width\n*/\n\nnamespace utils {\n\n  struct Options {\n    // Command line arguments (with default values)\n    unsigned num_ipus;\n    unsigned height;\n    unsigned width;\n    unsigned num_iterations;\n    float my1;\n    float my2;\n    float k;\n    float epsilon;\n    float b;\n    float a;\n    float h;\n    float dt;\n    float delta;\n    bool cpu;\n    bool save_cpu;\n    // Other arguments which are a consequence of the code or environment\n    std::string architecture; // Assigned when creating device\n    unsigned num_tiles_available = 0;\n    std::size_t halo_volume = 0;\n    unsigned nh = 0;\n    unsigned nw = 0;\n    float upper_bound_dt;\n    std::vector<std::size_t> smallest_slice = {std::numeric_limits<size_t>::max(),1};\n    std::vector<std::size_t> largest_slice = {0,0};\n  };\n\n  inline\n  Options parseOptions(int argc, char** argv) {\n    Options options;\n    namespace po = boost::program_options;\n    po::options_description desc(\"Flags\");\n    // Construction of exactly cubic sub-grids\n    desc.add_options()\n    (\"help\", \"Show command help.\")\n    (\n      \"num-ipus\",\n      po::value<unsigned>(&options.num_ipus)->default_value(1),\n      \"Number of IPUs to use.\"\n    )\n    (\n      \"height\", \n      po::value<unsigned>(&options.height)->default_value(7000),\n      \"Heigth of a custom 2D grid.\"\n    )\n    (\n      \"width\",\n      po::value<unsigned>(&options.width)->default_value(7000),\n      \"Width of a custom 2D grid.\"\n    )\n    (\n      \"num-iterations\",\n      po::value<unsigned>(&options.num_iterations)->default_value(1000),\n      \"PDE: number of iterations to execute on grid.\"\n    )\n    (\n      \"my1\",\n      po::value<float>(&options.my1)->default_value(0.07),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"my2\",\n      po::value<float>(&options.my2)->default_value(0.3),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"k\",\n      po::value<float>(&options.k)->default_value(8.0),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"epsilon\",\n      po::value<float>(&options.epsilon)->default_value(0.01),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"b\",\n      po::value<float>(&options.b)->default_value(0.1),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"a\",\n      po::value<float>(&options.a)->default_value(0.1),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"dt\",\n      po::value<float>(&options.dt)->default_value(0.0001),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"h\",\n      po::value<float>(&options.h)->default_value(0.000143),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"delta\",\n      po::value<float>(&options.delta)->default_value(5.0e-5),\n      \"A constant in the forward Euler Aliev-Panfilov equations.\"\n    )\n    (\n      \"cpu\",\n      po::bool_switch(&options.cpu)->default_value(false),\n      \"Also perform CPU execution to control results from IPU.\"\n    )\n    (\n      \"save-cpu\",\n      po::bool_switch(&options.save_cpu)->default_value(false),\n      \"Save CPU results to csv files in data folder.\"\n    ); // NOTE: remember to remove this semicolon if more options are added in future\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      throw std::runtime_error(\"Show help\");\n    }\n    po::notify(vm);\n\n    return options;\n  }\n\n} // End of namespace Utils\n\npoplar::Device getDevice(unsigned numIpus) {\n  /* return a Poplar device with the desired number of IPUs */\n  auto manager = poplar::DeviceManager::createDeviceManager();\n  auto devices = manager.getDevices(poplar::TargetType::IPU, numIpus);\n  // Use the first available device\n  for (auto &device : devices)\n    if (device.attach()) \n      return std::move(device);\n\n  throw std::runtime_error(\"No hardware device available.\");\n}\n\ninline float randomFloat() {\n  return static_cast <float> (rand() / static_cast <float> (RAND_MAX));\n}\n\ninline static unsigned index(unsigned x, unsigned y, unsigned width) { \n  return y + (x*width);\n}\n\ninline static unsigned block_low(unsigned id, unsigned p, unsigned n) {\n  return (id*n)/p; \n}\n\ninline static unsigned block_high(unsigned id, unsigned p, unsigned n) {\n  return block_low(id+1, p, n); \n}\n\ninline static unsigned block_size(unsigned id, unsigned p, unsigned n) {\n  return block_high(id, p, n) - block_low(id, p, n); \n}\n\nstd::size_t area(std::vector<std::size_t> shape) {\n  // return area of shape vector (2D)\n  return shape[0]*shape[1];\n}\n\nvoid workDivision(utils::Options &options) {\n  /* Function UPDATES options.nh and options.nw\n   * nh and nw will be chosen so that\n   * 1) all tiles will be used, hence options.num_tiles_available must\n   *    previously be updated by using the target object\n   * 2) find work division which results in most square patches (sub-grids)\n   */\n  unsigned tile_count = options.num_tiles_available;\n  unsigned H = options.height - 2; // Actual height (boundaries wont be computed)\n  unsigned W = options.width - 2; // Actual width\n  float best_patch_ratio = std::numeric_limits<float>::infinity();\n  bool height_dominant = (H >= W);\n\n  // Try all unique combinations where i*j = tile_count\n  for (unsigned i = 1; i*i <= tile_count; ++i) {\n    if ((tile_count % i) == 0) {\n      unsigned j = tile_count / i; // j >= i\n      unsigned nh = height_dominant ? j : i;\n      unsigned nw = height_dominant ? i : j;\n\n      unsigned h = float(H) / nh;\n      unsigned w = float(W) / nw;\n      // largest side length / smallest side length\n      // this will result in a ratio >= 1, where the ratio\n      // which is closest to 1, has the most square patches (1=perfect square)\n      float patch_ratio = (h > w) ? float(h)/w : float(w)/h;\n      if (patch_ratio < best_patch_ratio) {\n        best_patch_ratio = patch_ratio;\n        options.nh = nh;\n        options.nw = nw;\n      }\n    }\n  }\n\n  if (options.nw == 0 || options.nh == 0) {\n    std::cout << \"Work division went wrong. Using 1 tile.\\n\";\n    options.nh = 1;\n    options.nw = 1;\n  }\n}\n\nvoid print2dVector(std::vector<float> grid, utils::Options &options, std::string name) {\n  int h = options.height;\n  int w = options.width;\n  std::cout << name << \":\\n\";\n  for (int i = 0; i < h; ++i) {\n    if (i == 0) {\n      std::cout << \"[\";\n    } else {\n      std::cout << \" \";\n    }\n    for (int j = 0; j < w; ++j) {\n      if (j == 0) std::cout << \"[\"; \n      std::cout << grid[j + i*w];\n      if (j < w - 1) {\n        std::cout << \", \";\n      } else {\n        std::cout << \"]\";\n      }\n    }\n    if (i < h - 1) {\n      std::cout << \"\\n\";\n    } else {\n      std::cout << \"]\\n\\n\";\n    }\n  }\n}\n\nvoid save2dVector(std::vector<float> grid, utils::Options &options, std::string filename) {\n  int h = options.height;\n  int w = options.width;\n  std::ofstream outfile;\n  outfile.open(filename);\n  for (int i = 0; i < h; ++i) {\n    for (int j = 0; j < w; ++j) {\n      outfile << grid[j + i*w];\n      if (j < w - 1)\n        outfile << \",\";\n    }\n    if (i < h - 1) outfile << \"\\n\";\n  }\n  outfile.close();\n}\n\nvoid solveAlievPanfilovCpu(\n  const std::vector<float> initial_e, const std::vector<float> initial_r, \n  std::vector<float> &cpu_e, std::vector<float> &cpu_r, utils::Options &options) {\n\n  int N = initial_e.size();\n  int w = options.width;\n  int h = options.height;\n  float rhs;\n  std::vector<float> temp_e(N);\n  for (int i = 0 ; i < N; ++i) {\n    cpu_e[i] = initial_e[i];\n    cpu_r[i] = initial_r[i];\n    temp_e[i] = initial_e[i];\n  }\n  const float d_h2 = options.delta/(options.h*options.h);\n  const float minus_epsilon = -options.epsilon;\n  const float b_plus_one = options.b + 1;\n  float west, north, east, south;\n  int c = 0;\n\n  for (int t = 0; t < options.num_iterations; ++t) {\n    for (int i = 0; i < h; ++i) {\n      for (int j = 0; j < w; ++j) {\n        \n        // Boundary condition (zero gradient)\n        west = (j == 0) ? cpu_e[(j+1)+i*w] : cpu_e[(j-1)+i*w];\n        east = (j == w - 1) ? cpu_e[(j-1)+i*w] : cpu_e[(j+1)+i*w];\n        north = (i == 0) ? cpu_e[j+(i+1)*w] : cpu_e[j+(i-1)*w];\n        south = (i == h - 1) ? cpu_e[j+(i-1)*w] : cpu_e[j+(i+1)*w];\n        \n        // Computation of new e\n        rhs = d_h2*(-4*cpu_e[j+i*w] + west + east + south + north);\n        rhs -= options.k*cpu_e[j+i*w]*(cpu_e[j+i*w] - options.a)*(cpu_e[j+i*w] - 1);\n        rhs -= cpu_e[j+i*w]*cpu_r[j+i*w];\n        temp_e[j+i*w] = cpu_e[j+i*w] + rhs*options.dt;\n\n        // Computation of new r\n        rhs = minus_epsilon - options.my1*cpu_r[j+i*w]/(options.my2 + cpu_e[j+i*w]);\n        rhs *= cpu_r[j+i*w] + options.k*cpu_e[j+i*w]*(cpu_e[j+i*w] - b_plus_one);\n        cpu_r[j+i*w] += rhs*options.dt;\n      }\n    }\n    for (int i = 0; i < h; ++i) {\n      for (int j = 0; j < w; ++j) {\n        cpu_e[j+i*w] = temp_e[j+i*w];\n      }\n    }\n    if (t % 500 == 0 && options.save_cpu) {\n      save2dVector(cpu_e, options, \"./data/e\"+std::to_string(c)+\".csv\");\n      save2dVector(cpu_r, options, \"./data/r\"+std::to_string(c)+\".csv\");\n      c++; // nice\n    }\n  }\n}\n\nvoid printGeneralInfo(utils::Options &options) {\n  std::cout\n    << \"\\nAliev-Panfilov Forward Euler Method\"\n    << \"\\n-----------------------------------\"\n    << \"\\n\\nProblem\"\n    << \"\\n-------\"\n    << \"\\n2D Grids = \" << options.height << \"x\" << options.width << \" elements\"\n    << \"\\nWork Division = \" << options.nh << \"x\" << options.nw << \" partitions\"\n    << \"\\nNo. Time Steps = \" << options.num_iterations\n    << \"\\n\\nConstants\"\n    << \"\\n---------\"\n    << \"\\ndelta = \" << options.delta\n    << \"\\nmy1 = \" << options.my1\n    << \"\\nmy2 = \" << options.my2\n    << \"\\na = \" << options.a\n    << \"\\nb = \" << options.b\n    << \"\\nk = \" << options.k\n    << \"\\ndx = \" << options.h\n    << \"\\ndy = \" << options.h\n    << \"\\ndt = \" << options.dt << \" (upper bound = \" << options.upper_bound_dt << \")\"\n    << \"\\nepsilon = \" << options.epsilon\n    << \"\\n\\n\";\n}\n\nvoid testUpperBoundDt(utils::Options &options) {\n  float ka = options.k*options.a;\n  float k_1_a = options.k*(1 - options.a);\n  float max = (ka > k_1_a) ? ka : k_1_a;\n  float lambda = options.delta/(options.h*options.h);\n  float r_plus = options.k*(options.b+1)*(options.b+1)/4.0;\n  options.upper_bound_dt = 1.0/(4*lambda + max + r_plus);\n  if (options.dt > options.upper_bound_dt) \n    throw std::runtime_error(\n      \"Forward Euler method is not stable, because dt (\"+std::to_string(options.dt)+\n      \") > upper bound (\"+std::to_string(options.upper_bound_dt)+\").\"\n    );\n}\n\nvoid reportCpuVsIpu(std::vector<float> cpu_e, std::vector<float> cpu_r, \n  std::vector<float> ipu_e, std::vector<float> ipu_r, utils::Options &options) {\n  \n  std::size_t w = options.width;\n  std::size_t h = options.height;\n  float MSE_e = 0;\n  float MSE_r = 0;\n  for (int i = 0; i < options.height; ++i) {\n    for (int j = 0; j < options.width; ++j) {\n      float diff_e = cpu_e[j + i*w] - ipu_e[j + i*w];\n      float diff_r = cpu_r[j + i*w] - ipu_r[j + i*w];\n      MSE_e += diff_e*diff_e;\n      MSE_r += diff_r*diff_r;\n    }\n  }\n  MSE_e /= w*h;\n  MSE_r /= w*h;\n  std::cout\n    << \"\\nAliev-Panfilov IPU vs. CPU error\"\n    << \"\\n--------------------------------\"\n    << \"\\nMSE of e = \" << MSE_e;\n  if (MSE_e == 0) std::cout << \" (exactly)\";\n  std::cout << \"\\nMSE of r = \" << MSE_r;\n  if (MSE_r == 0) std::cout << \" (exactly)\";\n  std::cout << \"\\n\\n\";\n}\n\nvoid printPerformance(double wall_time, utils::Options &options) {\n  double flops_per_element = 28.0;\n  double elements_per_time = (double) options.height * (double) options.width * (double) options.num_iterations / (double) wall_time;\n  double flops = flops_per_element * elements_per_time;\n  double comp_mem_bw = 8*elements_per_time*sizeof(float); // 6 loads (5-point stencil for e, and r) + 2 stores (e and r)\n  double comm_mem_bw = 2.0*(double)options.halo_volume*sizeof(float)*(double) options.num_iterations / (double) wall_time; \n  double minimal_bw = comp_mem_bw + comm_mem_bw;\n  std::cout\n    << \"\\nPerformance\"\n    << \"\\n-----------\" << std::fixed\n    << \"\\nTime       = \" << std::setprecision(2) << wall_time << \" s\"\n    << \"\\nThroughput = \" << std::setprecision(2) << flops*1e-12 << \" TFLOPS\"\n    << \"\\nMinimal BW = \" << std::setprecision(2) << minimal_bw*1e-12 << \" TB/s\"\n    << \"\\n\\n\";\n}", "meta": {"hexsha": "46708b18d4c24b6f0167d404b8f53089f9052de1", "size": 12593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AlievPanfilovModel/utils.hpp", "max_stars_repo_name": "simehaa/IPU", "max_stars_repo_head_hexsha": "89f8a3a298a09ab011157366a9cfe05a042e2988", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T08:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T08:27:31.000Z", "max_issues_repo_path": "AlievPanfilovModel/utils.hpp", "max_issues_repo_name": "simehaa/IPU", "max_issues_repo_head_hexsha": "89f8a3a298a09ab011157366a9cfe05a042e2988", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AlievPanfilovModel/utils.hpp", "max_forks_repo_name": "simehaa/IPU", "max_forks_repo_head_hexsha": "89f8a3a298a09ab011157366a9cfe05a042e2988", "max_forks_repo_licenses": ["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.6407035176, "max_line_length": 133, "alphanum_fraction": 0.5857222266, "num_tokens": 3727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.057493278396655245, "lm_q1q2_score": 0.02429117659324928}}
{"text": "#ifndef ALEPH_TOPOLOGY_SIMPLEX_HH__\n#define ALEPH_TOPOLOGY_SIMPLEX_HH__\n\n#include <boost/functional/hash.hpp>\n\n#include <boost/iterator/iterator_adaptor.hpp>\n#include <boost/iterator/filter_iterator.hpp>\n\n#include <algorithm>\n#include <initializer_list>\n#include <iosfwd>\n#include <stdexcept>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n/**\n  @class Simplex\n\n  This class describes an abstract simplex of arbitrary dimensionality\n  with an optional *weight* or *data* value. This makes it possible to\n  use the class together with persistent homology calculations.\n\n  @see SimplicialComplex\n\n  @tparam D Data (weight) type, e.g. `double`\n  @tparam V Vertex type; usually, you do not have to change this type,\n            except if you want to change the memory footprint.\n*/\n\ntemplate <\n  class D,\n  class V = unsigned short\n>\nclass Simplex\n{\npublic:\n\n  // Aliases & declarations -------------------------------------------\n  //\n  // Note that these aliases follow the STL conventions in order to make it\n  // easier to use the class with STL algorithms.\n\n  using DataType                      = D;          ///< Data type alias\n  using VertexType                    = V;          ///< Vertex type alias\n\n  using data_type                     = DataType;   ///< Data type alias, STL-style\n  using vertex_type                   = VertexType; ///< Vertex type alias, STL-style\n\n  using vertex_container_type         = std::vector<vertex_type>;\n  using vertex_iterator               = typename vertex_container_type::iterator;\n  using const_vertex_iterator         = typename vertex_container_type::const_iterator;\n  using reverse_vertex_iterator       = typename vertex_container_type::reverse_iterator;\n  using const_reverse_vertex_iterator = typename vertex_container_type::const_reverse_iterator;\n\n  // I cannot describe the class inline because boost::iterator_adaptor expects\n  // a _complete_ class.\n  class boundary_iterator;\n\n  // Constructors ------------------------------------------------------\n\n  /** Creates an empty simplex */\n  Simplex()\n    : _data( DataType() )\n  {\n  }\n\n  /**\n    Creates a new 0-simplex from the given vertex.\n\n    @param u    Vertex\n    @param data Data to assign to simplex\n  */\n\n  Simplex( VertexType u, DataType data = DataType() )\n    : _vertices( 1, u )\n    , _data( data )\n  {\n  }\n\n  /**\n    Creates a new simplex from another simplex while setting the data for the\n    new simplex. This is handy for copying the vertices but not the data of a\n    given simplex, which occurs in cases where the data for the new simplex is\n    \\i not determined by the simplex that is to be copied.\n\n    @param simplex Simplex to copy vertices from\n    @param data    Data to assign new simplex\n  */\n\n  explicit Simplex( const Simplex<DataType, VertexType>& simplex, DataType data )\n    : _vertices( simplex._vertices )\n    , _data( data )\n  {\n  }\n\n  /**\n    Creates a new simplex from a range of vertices. The input iterators are\n    supposed to belong to a range of vertices for the simplex. This range need\n    not be ordered. Note that the simplex will \\b not check for duplicate\n    values.\n\n    @param begin Iterator to begin of vertex range\n    @param end   Iterator to end of vertex range\n    @param data  Data to assign to simplex\n  */\n\n  template <class InputIterator>\n  Simplex( InputIterator begin, InputIterator end,\n           DataType data = DataType() )\n    : _vertices( begin, end )\n    , _data( data )\n  {\n    std::sort( _vertices.begin(), _vertices.end(), std::greater<VertexType>() );\n\n    // Ensures that the simplex does not contain the same vertex\n    // multiple times. This may result in the empty simplex, but\n    // there is no way around that.\n    _vertices.erase(\n      std::unique( _vertices.begin(), _vertices.end() ),\n      _vertices.end()\n    );\n  }\n\n  /**\n    Creates a new simplex from a range of vertices. The vertices are not\n    assumed to be ordered. It must be possible for me to convert them to\n    the vertex type of the simplex.\n\n    @param vertices Vertices\n    @param data     Data to assign to simplex\n  */\n\n  template <class Vertex>\n  Simplex( const std::initializer_list<Vertex>& vertices,\n           DataType data = DataType() )\n    : Simplex( vertices.begin(), vertices.end(), data )\n  {\n  }\n\n  // vertices ----------------------------------------------------------\n\n  /** @returns Iterator to begin of simplex vertex range */\n  const_vertex_iterator begin() const\n  {\n    return _vertices.begin();\n  }\n\n  /** @returns Iterator to end of simplex vertex range */\n  const_vertex_iterator end() const\n  {\n    return _vertices.end();\n  }\n\n  /** @returns Reverse begin iterator of simplex vertex range */\n  const_reverse_vertex_iterator rbegin() const\n  {\n    return _vertices.rbegin();\n  }\n\n  /** @returns Reverse end iterator of simplex vertex range */\n  const_reverse_vertex_iterator rend() const\n  {\n    return _vertices.rend();\n  }\n\n  /**\n    Checks whether the current simplex contains a given vertex. This is\n    required for intersection queries, for example.\n\n    @param vertex Vertex to search for\n\n    @returns true if the simplex contains the current vertex at least once,\n    else false.\n  */\n\n  bool contains( VertexType vertex ) const\n  {\n    return std::find( this->begin(), this->end(), vertex ) != this->end();\n  }\n\n  // boundary ----------------------------------------------------------\n\n  /** @returns Boundary iterator to begin of boundary */\n  boundary_iterator begin_boundary() const\n  {\n    // Check dimension directly in order to handle the empty simplex\n    if( _vertices.empty() || _vertices.size() <= 1 )\n      return this->end_boundary();\n\n    return boundary_iterator( _vertices.begin(), _vertices);\n  }\n\n  /** @returns Boundary iterator to end of boundary */\n  boundary_iterator end_boundary() const\n  {\n    return boundary_iterator( _vertices.end(), _vertices);\n  }\n\n  // Data --------------------------------------------------------------\n\n  /**\n    Assigns the simplex a new value for its data object. This function does not\n    perform any sanity checks. The value is simply copied and stored.\n\n    @param data Data to assign\n  */\n\n  void setData( DataType data = DataType() )\n  {\n    _data = data;\n  }\n\n  /** @returns Current value of simplex data object */\n  DataType data() const\n  {\n    return _data;\n  }\n\n  // Attribute access --------------------------------------------------\n\n  /** @returns true if the simplex is empty, i.e. it has no vertices */\n  bool empty() const\n  {\n    return _vertices.empty();\n  }\n\n  /**\n    @returns true if the simplex is valid, i.e. it is not empty. This function\n    allows the simplex class to be used in expressions such as this one:\n\n    @code\n    Simplex<double> mySimplex( 2, 2.0 ); // 0-simplex\n    if( mySimplex )\n    {\n      // Do stuff with a valid simplex.\n    }\n    @endcode\n  */\n\n  explicit operator bool() const\n  {\n    // A bit verbose but more readable :)\n    return this->empty() ? false : true;\n  }\n\n  /**\n    @returns Dimension of simplex\n\n    @throws std::runtime_error if the dimension of the empty simplex is\n    queried. If you do this, it's your own fault.\n  */\n\n  std::size_t dimension() const\n  {\n    if( _vertices.empty() )\n      throw std::runtime_error( \"Querying dimension of empty simplex\" );\n    else\n      return _vertices.size() - 1;\n  }\n\n  /** @returns Number of vertices of the simplex */\n  std::size_t size() const\n  {\n    return _vertices.size();\n  }\n\n  /**\n    Returns a vertex (specified by an index) of the current simplex.\n\n    @param   index Index of vertex in simplex\n    @returns Vertex of simplex, specified by an index.\n    @throws  std::out_of_range if the index is out of range.\n  */\n\n  VertexType operator[]( std::size_t index ) const\n  {\n    return _vertices.at( index );\n  }\n\n  // Comparison operators ----------------------------------------------\n\n  /**\n    Checks whether two simplices are equal. Two simplices are considered equal\n    if their vertices are being equal. Simplex data is \\b not checked by this\n    function as this would complicate simplex queries in a simplicial complex.\n\n    @param other Simplex to check for equality\n    @returns true if the two simplices are equal (see above), else false.\n  */\n\n  bool operator==( const Simplex& other ) const\n  {\n    return this->_vertices == other._vertices;\n  }\n\n  /**\n    Checks whether two simplices are inequal. This function is simply the\n    negation of operator==.\n\n    @param other Simplex to check for inequality\n    @returns true if the two simplices differ, else false.\n  */\n\n  bool operator!=( const Simplex& other ) const\n  {\n    return !this->operator==( other );\n  }\n\n  /**\n    Comparison operator for simplices. Uses lexicographical comparison to\n    obtain a weak ordering of the simplices. This is used in many algorithms.\n\n    @param other Simplex to compare current simplex to\n    @returns  true if current simplex is to be sorted before other simplex.\n  */\n\n  bool operator<( const Simplex& other ) const\n  {\n    return std::lexicographical_compare( this->_vertices.begin(), this->_vertices.end(),\n                                         other._vertices.begin(), other._vertices.end() );\n  }\n\n  // Convenience functions ---------------------------------------------\n\n  template <class DataType>                   friend std::size_t hash_value( const Simplex<DataType>& s );\n  template <class DataType, class VertexType> friend std::size_t hash_value( const Simplex<DataType, VertexType>& s );\n\nprivate:\n\n  /**\n    The vertices making up the current simplex. Their values are irrelevant,\n    though it is assumed that the vertices represent some data points stored\n    _outside_ the simplex.\n  */\n\n  vertex_container_type _vertices;\n\n  /**\n    Data stored within the simplex. The type and semantics of this member\n    variable depend on the template parameters of the simplex class. For\n    example, a \\c double value is used at several places in order to add a \\i\n    weight or a \\i distance for the simplex.\n  */\n\n  DataType _data;\n};\n\n// ---------------------------------------------------------------------\n\ntemplate <class DataType, class VertexType>\nstd::size_t hash_value( const Simplex<DataType, VertexType>& s )\n{\n  boost::hash< typename Simplex<DataType, VertexType>::vertex_container_type > hasher;\n  return hasher( s._vertices );\n}\n\ntemplate <class DataType> std::size_t hash_value( const Simplex<DataType>& s )\n{\n  return hash_value<DataType, typename Simplex<DataType>::vertex_type>( s );\n}\n\n// ---------------------------------------------------------------------\n\n/**\n  @class boundary_iterator\n  @brief Iterator for traversing the boundary of a given simplex\n\n  This iterator, inspired by Dmitriy Morozov's \"Dionysus\" framework, calculates\n  the boundary of a given simplex while traversing it. Since the boundary\n  simplices are created from scratch, they will _not_ have the correct weights\n  set. Hence, the boundary iterator is only useful if some kind of lookup of\n  generated simplices exists---as is the case for a simplicial complex, for\n  example.\n*/\n\ntemplate <\n    class DataType,\n    class VertexType\n>\nclass Simplex<DataType, VertexType>::boundary_iterator\n  : public boost::iterator_adaptor<boundary_iterator,\n                                   const_vertex_iterator,\n                                   Simplex<DataType, VertexType>,\n                                   boost::use_default,\n                                   Simplex<DataType, VertexType> >\n{\npublic:\n\n  using Iterator = const_vertex_iterator ;\n  using Parent   = boost::iterator_adaptor<boundary_iterator,\n                                           Iterator,\n                                           Simplex<DataType, VertexType>,\n                                           boost::use_default,\n                                           Simplex<DataType, VertexType> >;\n\n  /**\n    Creates a new boundary iterator from a parent iterator (i.e. a simplex) and a\n    set of vertices (i.e. the vertices of the parent simplex).\n\n    @param it       Parent iterator\n    @param vertices VertexType set\n  */\n\n  explicit boundary_iterator( Iterator it, const vertex_container_type& vertices )\n    : Parent(it)\n    , _vertices(vertices)\n  {\n  }\n\nprivate:\n\n  friend class boost::iterator_core_access;\n\n  /** @returns Current boundary simplex */\n  Simplex<DataType, VertexType> dereference() const\n  {\n    // This returns a new simplex. The simplex is created from a set of\n    // vertices, which in turn is created by applying a filter to the set of\n    // vertices stored in this iterator: Namely, the filter iterator will\n    // return all vertices that are _not_ equal to its current position.\n\n    using std::placeholders::_1;\n\n    vertex_container_type vertices(\n          boost::make_filter_iterator( std::bind( std::not_equal_to<vertex_type>(), _1, *( this->base() ) ),\n                                                     _vertices.begin(),\n                                                     _vertices.end() ),\n          boost::make_filter_iterator( std::bind( std::not_equal_to<vertex_type>(), _1, *( this->base() ) ),\n                                                     _vertices.end(),\n                                                     _vertices.end() )\n          );\n\n    return Simplex<DataType, VertexType>( vertices.begin(), vertices.end() );\n  }\n\n  /**\n    Reference to vertex set; this is required because the boundary iterator\n    iterates over a set of vertices and may thus not exist without one.\n  */\n\n  const vertex_container_type& _vertices;\n};\n\n// ---------------------------------------------------------------------\n\n/**\n  Outputs a simplex to an ostream. This is used for debugging purposes.\n\n  @param o Output stream\n  @param s Simplex to be added to o\n\n  @returns Output stream with information about simplex s.\n*/\n\ntemplate <class DataType, class VertexType>\nstd::ostream& operator<<( std::ostream& o, const topology::Simplex<DataType, VertexType>& s )\n{\n  auto numVertices = s.size();\n\n  o << \"{\";\n\n  for( decltype(numVertices) i = 0; i < numVertices; i++ )\n  {\n    if( i != 0 )\n      o << \" \";\n\n    o << s[i];\n  }\n\n  if( s.data() != DataType() )\n    o << \" (\" << s.data() << \")\";\n\n  o << \"}\";\n\n  return o;\n}\n\n// ---------------------------------------------------------------------\n\n} // namespace topology\n\n} // namespace aleph\n\nnamespace std\n{\n\n/**\n  This specialization permits using simplices in std::unordered_map and\n  std::unordered_set. This struct wraps the hash value function defined\n  above.\n*/\n\ntemplate<class DataType, class VertexType> struct hash<aleph::topology::Simplex<DataType, VertexType> >\n{\n  using argument_type = aleph::topology::Simplex<DataType, VertexType>;\n  using result_type   = std::size_t;\n\n  result_type operator()( const argument_type& simplex ) const noexcept\n  {\n    return aleph::topology::hash_value( simplex );\n  }\n};\n\n} // namespace std\n\n#endif\n", "meta": {"hexsha": "4b465e27afb5c4b915f67e671489a472aaeb9d66", "size": 14901, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/topology/Simplex.hh", "max_stars_repo_name": "vishalbelsare/Aleph-1", "max_stars_repo_head_hexsha": "df6b1c0bc070d25a6383d9095c9be98b64c36f89", "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/topology/Simplex.hh", "max_issues_repo_name": "Submanifold/Aleph", "max_issues_repo_head_hexsha": "df6b1c0bc070d25a6383d9095c9be98b64c36f89", "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/topology/Simplex.hh", "max_forks_repo_name": "vishalbelsare/Aleph-1", "max_forks_repo_head_hexsha": "df6b1c0bc070d25a6383d9095c9be98b64c36f89", "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": 29.103515625, "max_line_length": 118, "alphanum_fraction": 0.6277431045, "num_tokens": 3249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.05749327314815791, "lm_q1q2_score": 0.02429117437573483}}
{"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 \"esop_minimization.hpp\"\n\n#include <iomanip>\n#include <list>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/assign/std/list.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/format.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/algorithm_ext/push_back.hpp>\n#include <boost/range/numeric.hpp>\n\n#include <core/io/read_pla_to_bdd.hpp>\n#include <core/utils/range_utils.hpp>\n#include <core/utils/terminal.hpp>\n#include <core/utils/timer.hpp>\n\nusing namespace boost::assign;\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\nenum decomposition_type\n{\n  NegativeDavio,\n  PositiveDavio,\n  Shannon\n};\n\nenum var_values_enum\n{\n  VariableNegative = 0,\n  VariablePositive,\n  VariableAbsent\n};\n\nstd::ostream& operator<<( std::ostream& os, const cube_t& cube )\n{\n  for ( unsigned i = 0u; i < cube.first.size(); ++i )\n  {\n    os << ( cube.second[i] ? ( cube.first[i] ? \"1\" : \"0\" ) : \"-\" );\n  }\n  return os;\n}\n\nboost::dynamic_bitset<> diff_cube( const cube_t& c1, const cube_t& c2 )\n{\n  return ((c1.second ^ c2.second) | ((c1.second & c1.first) ^ (c2.second & c2.first)));\n}\n\n/* Returns the distance of c1 and c2. If distance is 1 and bit_pos == -1, then bit_pos stores\n * the bit position in which they differ.\n */\nboost::dynamic_bitset<>::size_type compute_distance( const cube_t& c1, const cube_t& c2, int& bit_pos )\n{\n  boost::dynamic_bitset<> diff = diff_cube( c1, c2 );\n  auto d = diff.count();\n  if ( d == 1 && bit_pos == -1 )\n  {\n    bit_pos = diff.find_first();\n  }\n  return d;\n}\n\n/* This changes cube c1 at position with respect to the value of c2 at this position. */\nvoid change( cube_t& c1, const cube_t& c2, unsigned position )\n{\n  if ( c1.second[position] && c2.second[position] ) /* 0, 1 -> - */\n  {\n    c1.first.reset( position );\n    c1.second.reset( position );\n  }\n  else if ( !c1.second[position] ) /* -, X -> ~X */\n  {\n    c1.first.set( position, !c2.first[position] );\n    c1.second.set( position );\n  }\n  else if ( !c2.second[position] ) /* X, - -> ~X */\n  {\n    c1.first.flip( position );\n  }\n}\n\n/* Alternative implementation of change, but seems to be a tiny bit slower. */\nvoid change_alternative( cube_t& c1, const cube_t& c2, unsigned position )\n{\n  bool V1 = c1.first[position];\n  bool V2 = c2.first[position];\n  bool C1 = c1.second[position];\n  bool C2 = c2.second[position];\n\n  c1.first.set( !V1 && !V2 && (C1 ^ C2) );\n  c1.second.set( !C1 && !C2 && (V1 ^ V2) );\n}\n\nclass esop_manager\n{\npublic:\n  typedef std::pair<unsigned, unsigned> cube_pair_t;\n  typedef std::list<cube_pair_t> cube_pair_list_t;\n\n  esop_manager( DdManager * cudd, bool verbose = false, unsigned capacity = 1000u )\n    : cudd( cudd ),\n      verbose( verbose ),\n      distance_lists( 3u )\n  {\n    _cubes.reserve( capacity );\n  }\n\n  void add_cube( cube_t cube )\n  {\n    unsigned cubeid = 0u;\n    std::vector<char> distances( _cubes.size() );\n    int bit_pos = -1;\n\n    for ( ; cubeid < _cubes.size(); ++cubeid )\n    {\n      const cube_t& c = _cubes.at( cubeid );\n\n      /* distance-0 */\n      if ( ( distances[cubeid] = compute_distance( c, cube, bit_pos ) ) == 0 )\n      {\n        remove_cube( cubeid );\n        return;\n      }\n    }\n\n    /* distance-1 */\n    auto it = boost::find( distances, 1 );\n    if ( it != distances.end() )\n    {\n      unsigned distance_one_cubeid = std::distance( distances.begin(), it );\n      cube_t c = _cubes.at( distance_one_cubeid );\n      change( c, cube, bit_pos );\n      remove_cube( distance_one_cubeid );\n      add_cube( c );\n      return;\n    }\n\n    /* Add cube */\n    for ( unsigned i = 0u ; i < distances.size(); ++i )\n    {\n      if ( distances[i] <= 4 )\n      {\n        distance_lists[distances[i] - 2u] += std::make_pair( i, _cubes.size() );\n      }\n    }\n\n    _cubes += cube;\n  }\n\n  void remove_from_distance_list( cube_pair_list_t& l, unsigned cubeid, bool remove_first = true, bool remove_second = true )\n  {\n    l.remove_if( [&cubeid, &remove_first, &remove_second]( const std::pair<unsigned, unsigned>& p ) {\n        return ( remove_first && p.first == cubeid ) || ( remove_second && p.second == cubeid );\n      } );\n    for ( auto it = l.begin(); it != l.end(); ++it )\n    {\n      if ( remove_first  && it->first  > cubeid ) { it->first--;  }\n      if ( remove_second && it->second > cubeid ) { it->second--; }\n    }\n  }\n\n  void remove_cube( unsigned cubeid )\n  {\n    _cubes.erase( _cubes.begin() + cubeid );\n\n    /* remove from distance lists */\n    for ( unsigned i = 0u; i < 3u; ++i )\n    {\n      remove_from_distance_list( distance_lists[i], cubeid );\n    }\n  }\n\n  /* We know the distance when we call this function, so we do not want to recompute it */\n  void get_different_positions( const cube_t& c1, const cube_t& c2, unsigned distance, std::vector<unsigned>& positions )\n  {\n    boost::dynamic_bitset<> diff = diff_cube( c1, c2 );\n    unsigned pos;\n\n    for ( unsigned i = 0u; i < distance; ++i )\n    {\n      positions += ( pos = diff.find_first() );\n      diff.flip( pos );\n    }\n  }\n\n  std::string pair_list_to_string( const cube_pair_list_t& l )\n  {\n    using boost::adaptors::transformed;\n\n    return boost::join( l | transformed( []( const cube_pair_t& p ) {\n          return boost::str( boost::format( \"(%d,%d)\" ) % p.first % p.second ); } ), \", \" );\n  }\n\n  void get_exorlink_group( const cube_t& c1, const cube_t& c2, cube_t * tmp_cubes, unsigned group, const std::vector<unsigned>& positions )\n  {\n    /* distance is positions.size() */\n    unsigned distance = positions.size();\n    for ( unsigned i = 0u; i < distance; ++i )\n    {\n      tmp_cubes[i] = c1;\n      for ( unsigned j = 0u; j < distance; ++j )\n      {\n        switch ( cube_groups[cube_group_offsets[distance - 2u] + group * distance * distance + i * distance + j] )\n        {\n        case 1u:\n          tmp_cubes[i].first.set( positions[j], c2.first[positions[j]] );\n          tmp_cubes[i].second.set( positions[j], c2.second[positions[j]] );\n          break;\n        case 2u:\n          change( tmp_cubes[i], c2, positions[j] );\n          break;\n        }\n      }\n    }\n  }\n\n  bool leads_to_improvement( unsigned cubeid1, unsigned cubeid2, unsigned distance )\n  {\n    assert( cubeid1 < cubeid2 );\n\n    using boost::adaptors::transformed;\n\n    const cube_t& c1 = _cubes.at( cubeid1 ); /* easy access to c1 */\n    const cube_t& c2 = _cubes.at( cubeid2 ); /* easy access to c2 */\n\n    std::vector<unsigned> positions;        /* positions of different cubes in c1 and c2 */\n    cube_t tmp_cubes[4];                    /* used for current cube computation */\n    int improvement;                        /* store the current possible improvement */\n    int bit_pos;\n\n    get_different_positions( c1, c2, distance, positions );\n\n    /* loop over all grous */\n    for ( unsigned group = 0u; group < cube_group_count[distance - 2u]; ++group )\n    {\n      if ( verbose )\n      {\n        std::cout << \"  Group: \" << group << std::endl;\n      }\n\n      /* reset values */\n      improvement = distance - 2;\n\n      get_exorlink_group( c1, c2, tmp_cubes, group, positions );\n\n      /* follow exor link */\n      for ( unsigned i = 0; i < distance; ++i )\n      {\n        if ( verbose )\n        {\n          std::cout << \"    \" << i << \": \" << tmp_cubes[i] << std::endl;\n        }\n\n        bit_pos = -1;\n        for ( unsigned cubeid = 0u; cubeid < _cubes.size(); ++cubeid )\n        {\n          /* do not calculate distance to given cubes */\n          if ( cubeid == cubeid1 || cubeid == cubeid2 ) continue;\n\n          const cube_t& ex_cube = _cubes.at( cubeid );\n          auto d = compute_distance( ex_cube, tmp_cubes[i], bit_pos );\n          if ( d == 0u )\n          {\n            improvement -= 2;\n          }\n          else if ( d == 1u )\n          {\n            improvement -= 1;\n          }\n        }\n      }\n\n      /* did we find a good permutation? */\n      if ( ( distance == 2u && improvement < 0 ) || ( distance >= 3u && improvement <= 0 ) )\n      {\n        if ( verbose )\n        {\n          std::cout << \"    Found improvement\" << std::endl;\n        }\n\n        /* remove old pair */\n        remove_cube( cubeid2 );\n        remove_cube( cubeid1 );\n\n        /* add new cubes */\n        for ( unsigned i = 0u; i < distance; ++i )\n        {\n          add_cube( tmp_cubes[i] );\n        }\n\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  bool exorlink( unsigned distance )\n  {\n    using boost::adaptors::transformed;\n\n    assert( distance >= 2 && distance <= 4 );\n\n    if ( verbose )\n    {\n      print_banner( boost::str( boost::format( \"EXOR-LINK (d = %d)\" ) % distance ) );\n    }\n\n    std::vector<unsigned> positions;\n    for ( const auto& p : distance_lists.at( distance - 2u ) )\n    {\n      if ( verbose )\n      {\n        std::cout << \"Try to optimize with cube \" << p.first << \" and \" << p.second << std::endl;\n      }\n\n      if ( leads_to_improvement( p.first, p.second, distance ) )\n      {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  inline unsigned cube_count() const\n  {\n    return _cubes.size();\n  }\n\n  inline unsigned literal_count() const\n  {\n    using boost::adaptors::transformed;\n\n    return boost::accumulate( _cubes | transformed( []( const cube_t& c ) { return c.second.count(); } ), 0u );\n  }\n\n  inline const std::vector<cube_t>& cubes() const\n  {\n    return _cubes;\n  }\n\n  void print_statistics()\n  {\n    using boost::adaptors::indexed;\n    using boost::adaptors::transformed;\n\n    print_banner( \"Statistics\" );\n\n    std::cout << \"Number of cubes:    \" << cube_count() << std::endl;\n    std::cout << \"Number of literals: \" << literal_count() << std::endl;\n    std::cout << \"Cubes:\" << std::endl;\n    for ( auto it : index( _cubes ) )\n    {\n      std::cout << boost::format( \"%4d: \" ) % it.index << it.value << std::endl;\n    }\n    std::cout << \"Distance lists:\" << std::endl;\n    for ( unsigned i = 0u; i < 3u; ++i )\n    {\n      std::cout << boost::format( \"%4d: \" ) % (i + 2u);\n      std::cout << pair_list_to_string( distance_lists[i] ) << std::endl;\n    }\n  }\n\n  DdNode * to_bdd( const cube_t& cube )\n  {\n    DdNode * cubef = Cudd_ReadOne( cudd ), *tmp;\n    Cudd_Ref( cubef );\n\n    for ( unsigned i = 0u; i < cube.first.size(); ++i )\n    {\n      if ( cube.second[i] )\n      {\n        tmp = Cudd_bddAnd( cudd, cubef, cube.first[i] ? Cudd_bddIthVar( cudd, i ) : Cudd_Not( Cudd_bddIthVar( cudd, i ) ) );\n        Cudd_Ref( tmp );\n        Cudd_RecursiveDeref( cudd, cubef );\n        cubef = tmp;\n      }\n    }\n\n    return cubef;\n  }\n\n  DdNode * to_bdd( const std::vector<cube_t>& cube_list )\n  {\n    DdNode * f = Cudd_ReadLogicZero( cudd ), * tmp;\n    Cudd_Ref( f );\n\n    for ( const auto& cube : cube_list )\n    {\n      DdNode * cubef = to_bdd( cube );\n\n      tmp = Cudd_bddXor( cudd, f, cubef );\n      Cudd_Ref( tmp );\n      Cudd_RecursiveDeref( cudd, f );\n      Cudd_RecursiveDeref( cudd, cubef );\n      f = tmp;\n    }\n\n    return f;\n  }\n\n  DdNode * to_bdd()\n  {\n    return to_bdd( _cubes );\n  }\n\n  bool verify( DdNode * f )\n  {\n    DdNode * esopf = to_bdd();\n    DdNode * compare = Cudd_bddXnor( cudd, f, esopf );\n    Cudd_Ref( compare );\n    Cudd_RecursiveDeref( cudd, esopf );\n\n    bool equal = compare == Cudd_ReadOne( cudd );\n\n    Cudd_RecursiveDeref( cudd, compare );\n\n    return equal;\n  }\n\nprivate:\n  DdManager * cudd;\n  bool verbose;\n  std::vector<cube_t> _cubes;\n  std::vector<cube_pair_list_t> distance_lists;\n\n  static unsigned cube_groups[];\n  static unsigned cube_group_count[];\n  static unsigned cube_group_offsets[];\n};\n\n/**\n * (2 0) (1 2)\n * (0 2) (2 1)\n */\n\n/**\n * (2 0 0) (1 2 0) (1 1 2)\n * (2 0 0) (1 0 2) (1 2 1)\n * (0 2 0) (2 1 0) (1 1 2)\n * (0 2 0) (0 1 2) (2 1 1)\n * (0 0 2) (2 0 1) (1 2 1)\n * (0 0 2) (0 2 1) (2 1 1)\n */\n\n/**\n * (2 0 0 0) (1 2 0 0) (1 1 2 0) (1 1 1 2)\n * (2 0 0 0) (1 2 0 0) (1 1 0 2) (1 1 2 1)\n * (2 0 0 0) (1 0 2 0) (1 2 1 0) (1 1 1 2)\n * (2 0 0 0) (1 0 2 0) (1 0 1 2) (1 2 1 1)\n * (2 0 0 0) (1 0 0 2) (1 2 0 1) (1 1 2 1)\n * (2 0 0 0) (1 0 0 2) (1 0 2 1) (1 2 1 1)\n * (0 2 0 0) (2 1 0 0) (1 1 2 0) (1 1 1 2)\n * (0 2 0 0) (2 1 0 0) (1 1 0 2) (1 1 2 1)\n * (0 2 0 0) (0 1 2 0) (2 1 1 0) (1 1 1 2)\n * (0 2 0 0) (0 1 2 0) (0 1 1 2) (2 1 1 1)\n * (0 2 0 0) (0 1 0 2) (2 1 0 1) (1 1 2 1)\n * (0 2 0 0) (0 1 0 2) (0 1 2 1) (2 1 1 1)\n * (0 0 2 0) (2 0 1 0) (1 2 1 0) (1 1 1 2)\n * (0 0 2 0) (2 0 1 0) (1 0 1 2) (1 2 1 1)\n * (0 0 2 0) (0 2 1 0) (2 1 1 0) (1 1 1 2)\n * (0 0 2 0) (0 2 1 0) (0 1 1 2) (2 1 1 1)\n * (0 0 2 0) (0 0 1 2) (2 0 1 1) (1 2 1 1)\n * (0 0 2 0) (0 0 1 2) (0 2 1 1) (2 1 1 1)\n * (0 0 0 2) (2 0 0 1) (1 2 0 1) (1 1 2 1)\n * (0 0 0 2) (2 0 0 1) (1 0 2 1) (1 2 1 1)\n * (0 0 0 2) (0 2 0 1) (2 1 0 1) (1 1 2 1)\n * (0 0 0 2) (0 2 0 1) (0 1 2 1) (2 1 1 1)\n * (0 0 0 2) (0 0 2 1) (2 0 1 1) (1 2 1 1)\n * (0 0 0 2) (0 0 2 1) (0 2 1 1) (2 1 1 1)\n */\nunsigned esop_manager::cube_groups[] = { 2, 0, 1, 2,\n                                         0, 2, 2, 1,\n                                         2, 0, 0, 1, 2, 0, 1, 1, 2,\n                                         2, 0, 0, 1, 0, 2, 1, 2, 1,\n                                         0, 2, 0, 2, 1, 0, 1, 1, 2,\n                                         0, 2, 0, 0, 1, 2, 2, 1, 1,\n                                         0, 0, 2, 2, 0, 1, 1, 2, 1,\n                                         0, 0, 2, 0, 2, 1, 2, 1, 1,\n                                         2, 0, 0, 0, 1, 2, 0, 0, 1, 1, 2, 0, 1, 1, 1, 2,\n                                         2, 0, 0, 0, 1, 2, 0, 0, 1, 1, 0, 2, 1, 1, 2, 1,\n                                         2, 0, 0, 0, 1, 0, 2, 0, 1, 2, 1, 0, 1, 1, 1, 2,\n                                         2, 0, 0, 0, 1, 0, 2, 0, 1, 0, 1, 2, 1, 2, 1, 1,\n                                         2, 0, 0, 0, 1, 0, 0, 2, 1, 2, 0, 1, 1, 1, 2, 1,\n                                         2, 0, 0, 0, 1, 0, 0, 2, 1, 0, 2, 1, 1, 2, 1, 1,\n                                         0, 2, 0, 0, 2, 1, 0, 0, 1, 1, 2, 0, 1, 1, 1, 2,\n                                         0, 2, 0, 0, 2, 1, 0, 0, 1, 1, 0, 2, 1, 1, 2, 1,\n                                         0, 2, 0, 0, 0, 1, 2, 0, 2, 1, 1, 0, 1, 1, 1, 2,\n                                         0, 2, 0, 0, 0, 1, 2, 0, 0, 1, 1, 2, 2, 1, 1, 1,\n                                         0, 2, 0, 0, 0, 1, 0, 2, 2, 1, 0, 1, 1, 1, 2, 1,\n                                         0, 2, 0, 0, 0, 1, 0, 2, 0, 1, 2, 1, 2, 1, 1, 1,\n                                         0, 0, 2, 0, 2, 0, 1, 0, 1, 2, 1, 0, 1, 1, 1, 2,\n                                         0, 0, 2, 0, 2, 0, 1, 0, 1, 0, 1, 2, 1, 2, 1, 1,\n                                         0, 0, 2, 0, 0, 2, 1, 0, 2, 1, 1, 0, 1, 1, 1, 2,\n                                         0, 0, 2, 0, 0, 2, 1, 0, 0, 1, 1, 2, 2, 1, 1, 1,\n                                         0, 0, 2, 0, 0, 0, 1, 2, 2, 0, 1, 1, 1, 2, 1, 1,\n                                         0, 0, 2, 0, 0, 0, 1, 2, 0, 2, 1, 1, 2, 1, 1, 1,\n                                         0, 0, 0, 2, 2, 0, 0, 1, 1, 2, 0, 1, 1, 1, 2, 1,\n                                         0, 0, 0, 2, 2, 0, 0, 1, 1, 0, 2, 1, 1, 2, 1, 1,\n                                         0, 0, 0, 2, 0, 2, 0, 1, 2, 1, 0, 1, 1, 1, 2, 1,\n                                         0, 0, 0, 2, 0, 2, 0, 1, 0, 1, 2, 1, 2, 1, 1, 1,\n                                         0, 0, 0, 2, 0, 0, 2, 1, 2, 0, 1, 1, 1, 2, 1, 1,\n                                         0, 0, 0, 2, 0, 0, 2, 1, 0, 2, 1, 1, 2, 1, 1, 1 };\n\nunsigned esop_manager::cube_group_count[] = { 2u, 6u, 24u };\n\nunsigned esop_manager::cube_group_offsets[] = { 0u, 8u, 62u };\n\n/******************************************************************************\n * PSDKRO functions                                                           *\n ******************************************************************************/\nexp_cost_t count_cubes_in_exact_psdkro( DdManager * cudd, DdNode * f, exp_cache_t& exp_cache )\n{\n  exp_cost_t r;\n\n  // terminal cases\n  if ( f == Cudd_ReadLogicZero( cudd ) ) return std::make_pair( PositiveDavio, 0u );\n  if ( f == Cudd_ReadOne( cudd ) )       return std::make_pair( PositiveDavio, 1u );\n\n  // in cache?\n  auto it = exp_cache.find( f );\n  if ( it != exp_cache.end() )\n  {\n    return it->second;\n  }\n\n  // get co-factors\n  DdNode * f0 = Cudd_NotCond( Cudd_E( f ), Cudd_IsComplement( f ) );\n  DdNode * f1 = Cudd_NotCond( Cudd_T( f ), Cudd_IsComplement( f ) );\n  DdNode * f2 = Cudd_bddXor( cudd, f0, f1 );\n  Cudd_Ref( f2 );\n\n  // recursively solve subproblems\n  int n0, n1, n2, nmax;\n  n0 = count_cubes_in_exact_psdkro( cudd, f0, exp_cache ).second;\n  n1 = count_cubes_in_exact_psdkro( cudd, f1, exp_cache ).second;\n  n2 = count_cubes_in_exact_psdkro( cudd, f2, exp_cache ).second;\n\n  // determine the mostly costly expansion\n  nmax = n0 > n1 ? n0 : n1;\n  nmax = n2 > nmax ? n2 : nmax;\n\n  // choose the least costly expansion\n  if      ( nmax == n0 ) r = std::make_pair( NegativeDavio, n1 + n2 );\n  else if ( nmax == n1 ) r = std::make_pair( PositiveDavio, n0 + n2 );\n  else                   r = std::make_pair( Shannon,       n0 + n1 );\n\n  //Cudd_RecursiveDeref( cudd, f2 );\n\n  // cache and return result\n  return exp_cache[f] = r;\n}\n\n// TODO can we do something nicer with last_index\nvoid generate_exact_psdkro( DdManager * cudd, DdNode * f, char * var_values, int last_index, const exp_cache_t& exp_cache, const std::function<void()>& on_cube )\n{\n  // terminal cases\n  if ( f == Cudd_ReadLogicZero( cudd ) ) return;\n  if ( f == Cudd_ReadOne( cudd ) )\n  {\n    using boost::adaptors::indexed;\n\n    unsigned n = Cudd_ReadSize( cudd );\n    for ( unsigned i = last_index + 1; i < n; ++i )\n    {\n      var_values[i] = VariableAbsent;\n    }\n\n    on_cube();\n    return;\n  }\n\n  // find the best expansion by a cache lookup\n  unsigned exp = exp_cache.find( f )->second.first;\n\n  // determine the top-most variable\n  int index = Cudd_NodeReadIndex( f );\n\n  // clear intermediate variables that have not been used\n  for ( int i = last_index + 1; i < index; ++i )\n  {\n    var_values[i] = VariableAbsent;\n  }\n\n  // get co-factors\n  DdNode * f0 = Cudd_NotCond( Cudd_E( f ), Cudd_IsComplement( f ) );\n  DdNode * f1 = Cudd_NotCond( Cudd_T( f ), Cudd_IsComplement( f ) );\n  DdNode * f2 = Cudd_bddXor( cudd, f0, f1 );\n  Cudd_Ref( f2 );\n\n  if ( exp == PositiveDavio )\n  {\n    var_values[index] = VariableAbsent;\n    generate_exact_psdkro( cudd, f0, var_values, index, exp_cache, on_cube );\n    var_values[index] = VariablePositive;\n    generate_exact_psdkro( cudd, f2, var_values, index, exp_cache, on_cube );\n  }\n  else if ( exp == NegativeDavio )\n  {\n    var_values[index] = VariableAbsent;\n    generate_exact_psdkro( cudd, f1, var_values, index, exp_cache, on_cube );\n    var_values[index] = VariableNegative;\n    generate_exact_psdkro( cudd, f2, var_values, index, exp_cache, on_cube );\n  }\n  else\n  {\n    var_values[index] = VariableNegative;\n    generate_exact_psdkro( cudd, f0, var_values, index, exp_cache, on_cube );\n    var_values[index] = VariablePositive;\n    generate_exact_psdkro( cudd, f1, var_values, index, exp_cache, on_cube );\n  }\n\n  Cudd_RecursiveDeref( cudd, f2 );\n}\n\nvoid generate_exact_psdkro( esop_manager& esop, DdManager * cudd, DdNode * f, char * var_values, int last_index, const exp_cache_t& exp_cache )\n{\n  generate_exact_psdkro( cudd, f, var_values, last_index, exp_cache, [&esop, &cudd, &var_values]() {\n      const auto n = Cudd_ReadSize( cudd );\n      boost::dynamic_bitset<> lits( n, 0u ), care( n, 0u );\n\n      auto index = 0u;\n      for ( auto it : boost::make_iterator_range( var_values, var_values + Cudd_ReadSize( cudd ) ) )\n      {\n        lits.set( index, it == VariablePositive );\n        care.set( index, it != VariableAbsent );\n        ++index;\n      }\n\n      esop.add_cube( std::make_pair( lits, care ) );\n    } );\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nvoid esop_minimization( DdManager * cudd, DdNode * f, properties::ptr settings, properties::ptr statistics )\n{\n  using boost::adaptors::map_keys;\n\n  /* Settings */\n  bool            verbose = get( settings, \"verbose\", false             );\n  unsigned        runs    = get( settings, \"runs\",    1u                );\n  bool            verify  = get( settings, \"verify\",  false             );\n  cube_function_t on_cube = get( settings, \"on_cube\", cube_function_t() );\n\n  esop_manager esop( cudd, verbose );\n\n  /* block for timing */\n  {\n    properties_timer t( statistics );\n\n    /* get initial cover using exact PSDKRO optimization */\n    exp_cache_t exp_cache;\n    count_cubes_in_exact_psdkro( cudd, f, exp_cache );\n\n    char * var_values = new char[Cudd_ReadSize( cudd )];\n    std::fill( var_values, var_values + Cudd_ReadSize( cudd ), VariableAbsent );\n    generate_exact_psdkro( esop, cudd, f, var_values, -1, exp_cache );\n\n    delete[] var_values;\n\n    if ( verbose )\n    {\n      esop.print_statistics();\n    }\n\n    /* EXOR-LINK */\n    for ( unsigned i = 0u; i < runs; ++i )\n    {\n      unsigned old_count, cur_count = esop.cube_count();\n\n      do {\n        old_count = cur_count;\n\n        do {\n          old_count = cur_count;\n\n          esop.exorlink( 2u );\n          esop.exorlink( 3u );\n          esop.exorlink( 4u );\n\n          cur_count = esop.cube_count();\n        } while ( cur_count < old_count );\n\n        /* last gasp */\n        for ( unsigned j = 0u; j < 10u; ++j )\n        {\n          esop.exorlink( 4u );\n        }\n\n        cur_count = esop.cube_count();\n      } while ( cur_count < old_count );\n    }\n\n    if ( verbose )\n    {\n      esop.print_statistics();\n    }\n  }\n\n  /* pass cubes */\n  if ( on_cube )\n  {\n    boost::for_each( esop.cubes(), on_cube );\n  }\n\n  if ( statistics )\n  {\n    statistics->set( \"cube_count\", esop.cube_count() );\n    statistics->set( \"literal_count\", esop.literal_count() );\n  }\n\n  if ( verify )\n  {\n    assert( esop.verify( f ) );\n  }\n}\n\nvoid esop_minimization( const std::string& filename, properties::ptr settings, properties::ptr statistics )\n{\n  BDDTable bdd;\n  read_pla_to_bdd( bdd, filename );\n\n  esop_minimization( bdd.cudd, bdd.outputs.front().second, settings, statistics );\n}\n\ndd_based_esop_optimization_func dd_based_esop_minimization_func(properties::ptr settings, properties::ptr statistics)\n{\n  dd_based_esop_optimization_func f = [&settings, &statistics]( DdManager * cudd, DdNode * node ) {\n    return esop_minimization( cudd, node, settings, statistics );\n  };\n  f.init( settings, statistics );\n  return f;\n}\n\npla_based_esop_optimization_func pla_based_esop_minimization_func(properties::ptr settings, properties::ptr statistics)\n{\n  pla_based_esop_optimization_func f = [&settings, &statistics]( const std::string& filename ) {\n    return esop_minimization( filename, settings, statistics );\n  };\n  f.init( settings, statistics );\n  return f;\n}\n\n\n/******************************************************************************\n * Tests                                                                      *\n ******************************************************************************/\n\nvoid test_change_performance()\n{\n  unsigned n = 10u;\n  unsigned count = 1u << 21u;\n\n  boost::random::mt19937 gen;\n  boost::random::uniform_int_distribution<> dist( 0u, (1u << n) - 1u );\n\n  std::vector<std::pair<cube_t, cube_t> > cubes( count );\n  boost::generate( cubes, [&n, &gen, &dist]() { return std::make_pair(\n                                                                      std::make_pair( boost::dynamic_bitset<>( n, dist( gen ) ), boost::dynamic_bitset<>( n, dist( gen ) ) ),\n                                                                      std::make_pair( boost::dynamic_bitset<>( n, dist( gen ) ), boost::dynamic_bitset<>( n, dist( gen ) ) ) ); } );\n\n  {\n    print_timer t;\n\n    for ( const auto& p : cubes )\n    {\n      cube_t c = p.first;\n      change( c, p.second, 5u );\n    }\n  }\n\n  {\n    print_timer t;\n\n    for ( const auto& p : cubes )\n    {\n      cube_t c = p.first;\n      change_alternative( c, p.second, 5u );\n    }\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": "367314e9e547ce9ed5ce0496ba6acec768830a49", "size": 25732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/optimization/esop_minimization.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/optimization/esop_minimization.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/optimization/esop_minimization.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": 31.0024096386, "max_line_length": 180, "alphanum_fraction": 0.5286413804, "num_tokens": 8404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.052618955947604316, "lm_q1q2_score": 0.02425822160174117}}
{"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_MATRIX_RECURATOR_INCLUDE\n#define MTL_MATRIX_RECURATOR_INCLUDE\n\n#include <cmath>\n#include <boost/shared_ptr.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/sub_matrix.hpp>\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/matrix/transposed_view.hpp>\n#include <boost/numeric/mtl/recursion/dim_splitter.hpp>\n#include <boost/numeric/mtl/recursion/utility.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n\nnamespace mtl { namespace mat {\n\n\ntemplate <typename Recursator1, typename Recursator2>\nvoid inline equalize_depth(Recursator1& r1, Recursator2& r2);\n\ntemplate <typename Recursator1, typename Recursator2, typename Recursator3>\nvoid inline equalize_depth(Recursator1& r1, Recursator2& r2, Recursator3& r3);\n\n\n/*! Class for matrix recursator\n\n    How to use this class is described in the \\ref rec_intro \"recursion introduction\".\n\n    \\sa \\ref mtl::mat::north_west, \\ref mtl::mat::north_east, \n    \\ref mtl::mat::south_west, \\ref mtl::mat::south_east, \n    \\ref mtl::mat::is_empty(const recursator<Matrix>&), \n    \\ref mtl::mat::is_full(const recursator<Matrix>&), \n    \\ref mtl::mat::num_rows(const recursator<Matrix>&), \n    \\ref mtl::mat::num_cols(const recursator<Matrix>&),\n    \\ref mtl::mat::size(const recursator<Matrix>&)\n**/\ntemplate <typename Matrix>\nstruct recursator\n{\n    typedef recursator                                     self;\n    typedef Matrix                                                matrix_type;\n    typedef typename sub_matrix_t<Matrix>::sub_matrix_type        sub_matrix_type;\n    typedef typename sub_matrix_t<Matrix>::const_sub_matrix_type  const_sub_matrix_type;\n    typedef typename Collection<Matrix>::size_type                size_type;\n    typedef typename Collection<Matrix>::value_type               matrix_value_type;\n    typedef recursion::outer_bound_splitter<self>                 splitter_type;\n\nprivate:\n    \n    template <typename MatrixType> // why was it templated ???\n    sub_matrix_type constructor_helper(MatrixType const& matrix)\n    {\n\treturn sub_matrix(matrix, matrix.begin_row(), matrix.end_row(),\n\t\t\t  matrix.begin_col(), matrix.end_col());\n    }\n\n    // For views without own data, we need to generate a new sub_matrix as shared_ptr\n    template <typename MatrixType>\n    sub_matrix_type constructor_helper(transposed_view<MatrixType> const& view)\n    {\n\ttypedef typename boost::remove_const<MatrixType>::type   tmp_type;\n\ttypedef typename sub_matrix_t<tmp_type>::sub_matrix_type ref_sub_type;\n\ttypedef boost::shared_ptr<ref_sub_type>                  pointer_type;\n\ttypedef typename transposed_view<MatrixType>::other      ref_type;\n\n\t// Submatrix of referred matrix, colums and rows interchanged\n\t// Create a submatrix, whos address will be kept by transposed_view\n\tpointer_type p(new ref_sub_type(sub_matrix(const_cast<ref_type&>(view.ref), view.begin_col(), view.end_col(), \n\t\t\t\t\t\t   view.begin_row(), view.end_row())));\n\treturn sub_matrix_type(p); \n    }\n\npublic:\n    /*! Construct a recursator from a matrix.\n        \\param matrix The matrix to which the recursator refers.\n\t\\param bound  Explicit bound declaration; must not be smaller than the numbers of rows and the number of columns;\n\t              must also be a power of 2.\n\n        Constructor takes the entire matrix as sub-matrix.\n        This allows to have different type for the matrix and the sub-matrix.\n    **/\n    explicit recursator(Matrix const& matrix,\n\t\t\t       size_type bound= 0\n\t\t\t       ) \n\t: my_sub_matrix(constructor_helper(matrix)), my_bound(recursion::outer_bound(matrix)),\n\t  my_first_row(0), my_first_col(0)         // splitter(*this)\n    {\n      if (bound == 0)\n\tmy_bound= recursion::outer_bound(matrix);\n      else {\n\tMTL_DEBUG_THROW_IF(!recursion::is_power_of_2(bound), range_error(\"Bound must be a power of 2\"));\n\tMTL_DEBUG_THROW_IF(bound < num_rows(matrix) || bound < num_cols(matrix), \n\t\t\t   range_error(\"Bound must not be smaller than matrix dimensions\"));\n\tmy_bound= bound;\n      }\n    }\n\n\nprivate:\n\n    template <typename SubMatrix>\n    sub_matrix_type get_value_dispatch(const SubMatrix& , \n\t\t\t\t   size_type br, size_type er, size_type bc, size_type ec) const\n    {\n\treturn sub_matrix(my_sub_matrix, br, er, bc, ec);\n    }\n\n    template <typename SubMatrix>\n    sub_matrix_type get_value_dispatch(transposed_view<SubMatrix> view, \n\t\t\t\t       size_type br, size_type er, size_type bc, size_type ec) const\n    {\n\ttypedef typename sub_matrix_t<SubMatrix>::sub_matrix_type   ref_sub_type;\n\ttypedef boost::shared_ptr<ref_sub_type>                     pointer_type;\n\ttypedef typename transposed_view<SubMatrix>::other          ref_type;\n\n\tpointer_type p(new ref_sub_type(sub_matrix(const_cast<ref_type&>(view.ref), bc, ec, br, er)));\n\treturn sub_matrix_type(p); \t\n    }\n\n\npublic:\n    sub_matrix_type get_value() const\n    {\n\tusing std::min;\n\tsize_type begin_row= my_sub_matrix.begin_row() + my_first_row,\n\t          end_row= min(begin_row + my_bound, my_sub_matrix.end_row()),\n\t          begin_col= my_sub_matrix.begin_col() + my_first_col,\n\t          end_col= min(begin_col + my_bound, my_sub_matrix.end_col());\n\n#if 0\n\tstd::cout << \"get_value [\" << begin_row << \"-\" << end_row << \"][\"\n\t\t  << begin_col << \"-\" << end_col << \"]\\n\";\n#endif\n\treturn get_value_dispatch(my_sub_matrix, begin_row, end_row, begin_col, end_col);\n    }\n\n    /// Compute the sub-matrix corresponding to this recursator.\n    sub_matrix_type operator*() const\n    {\n\treturn get_value();\n    }\n\n    // Returning quadrants for non-const recursator\n\n    self north_west() const\n    {\n\tself tmp(*this);\n\ttmp.my_bound >>= 1; // divide by 2\n\treturn tmp;\n    }\n\n    self south_west() const\n    {\n\tself tmp(*this);\n\ttmp.my_bound >>= 1; // divide by 2\n\ttmp.my_first_row += tmp.my_bound;\n\treturn tmp;\n    }\n\n    self north_east() const\n    {\n\tself tmp(*this);\n\ttmp.my_bound >>= 1; // divide by 2\n\ttmp.my_first_col += tmp.my_bound;\n\treturn tmp;\n    }\n\n    self south_east() const\n    {\n\tself tmp(*this);\n\ttmp.my_bound >>= 1; // divide by 20\n\ttmp.my_first_row += tmp.my_bound;\n\ttmp.my_first_col += tmp.my_bound;\n\treturn tmp;\n    }\n\n    bool is_empty() const\n    {\n\treturn my_first_row >= num_rows(my_sub_matrix) || my_first_col >= num_cols(my_sub_matrix);\n    }\n\n\n    /// Return the bound of the recursator\n    size_type bound() const\n    {\n\treturn my_bound;\n    }\n\n    /*! Set the bound of the recursator.\n\t\\param b  The new virtual bound; must be a power of 2.\n\n        This function allows to declare a virtual bound smaller than the number of rows and/or columns.\n\tIt must be used with uttermost care.\n    **/\n    void set_bound(size_type b)\n    {\n\tmy_bound= b;\n    }\n\n    template <typename R1, typename R2> friend void equalize_depth (R1&, R2&);   \n    template <typename R1, typename R2, typename R3> friend void equalize_depth (R1&, R2&, R3&);\n\n    template <typename M> friend typename recursator<M>::size_type num_rows(const recursator<M>& rec);\n    template <typename M> friend typename recursator<M>::size_type num_cols(const recursator<M>& rec);\n\n    // Dirty feature to be used with care\n    matrix_value_type* first_address()\n    {\n\treturn &my_sub_matrix[my_first_row][my_first_col];\n    }\n\n    const matrix_value_type* first_address() const\n    {\n\treturn &my_sub_matrix[my_first_row][my_first_col];\n    }\n    \n  protected:\n    sub_matrix_type     my_sub_matrix; /// Referred matrix (from which the sub-matrices are built)\n    size_type           my_bound,      /// Virtual matrix size, i.e. upper bound for size of sub-matrix.\n\t                my_first_row,  /// Row of first entry in submatrix\n                        my_first_col;  /// Row of first entry in submatrix \n};\n\n#if 0\n\n// Obsolete, only left in code because discussed in a paper\n// To use recursator with const matrices Reference must be 'Matrix const&'\ntemplate <typename Matrix, typename Splitter = recursion::max_dim_splitter<Matrix> >\nstruct recursator_s\n{\n    typedef recursator_s                                    self;\n    typedef Matrix                                                matrix_type;\n    typedef Splitter                                              splitter_type;\n    typedef typename sub_matrix_t<Matrix>::sub_matrix_type        sub_matrix_type;\n    typedef typename sub_matrix_t<Matrix>::const_sub_matrix_type  const_sub_matrix_type;\n    typedef typename Matrix::size_type                            size_type;\n    // typedef outer_bound_splitter<self>                            splitter_type;\n\nprivate:\n    \n    // template <typename Matrix> why was it templated ???\n    sub_matrix_type constructor_helper(Matrix const& matrix)\n    {\n\treturn sub_matrix(matrix, matrix.begin_row(), matrix.end_row(),\n\t\t\t  matrix.begin_col(), matrix.end_col());\n    }\n\n    // For views without own data, we need to generate a new sub_matrix as shared_ptr\n    // template <typename Matrix>\n    sub_matrix_type constructor_helper(transposed_view<Matrix> const& matrix)\n    {\n\ttypedef typename sub_matrix_t<Matrix>::sub_matrix_type   ref_sub_type;\n\ttypedef boost::shared_ptr<ref_sub_type>                  pointer_type;\n\n\t// Submatrix of referred matrix, colums and rows interchanged\n\t// Create a submatrix, whos address will be kept by transposed_view\n\tpointer_type p(new ref_sub_type(sub_matrix(matrix.ref, matrix.begin_col(), matrix.end_col(), \n\t\t\t\t\t\t   matrix.begin_row(), matrix.end_row())));\n\treturn sub_matrix_type(p); \n    }\n\npublic:\n    // Constructor takes the whole matrix as sub-matrix\n    // This allows to have different type for the matrix and the sub-matrix\n    // This also enables matrices to have references as sub-matrices\n    explicit recursator_s(Matrix const& matrix, size_type bound= 0) \n\t: my_sub_matrix(constructor_helper(matrix)), my_bound(outer_bound(matrix)),\n\t  splitter(my_sub_matrix)\n    {\n      if (bound == 0)\n\tmy_bound= outer_bound(matrix);\n      else {\n\tassert(is_power_of_2(bound));\n\tassert(bound >= matrix.num_rows() && bound >= matrix.num_cols());\n\tmy_bound= bound;\n      }\n    }\n\n    // Sub-matrices are copied directly\n    // explicit recursator(sub_matrix_type sub_matrix) : my_sub_matrix(sub_matrix) {}\n    \n    sub_matrix_type& get_value()\n    {\n\treturn my_sub_matrix;\n    }\n\n    sub_matrix_type const& get_value() const\n    {\n\treturn my_sub_matrix;\n    }\n\n    // Returning quadrants for non-const recursator\n\n    self north_west()\n    {\n\tsub_matrix_type sm(sub_matrix(my_sub_matrix, my_sub_matrix.begin_row(), splitter.row_split(),\n\t\t\t\t      my_sub_matrix.begin_col(), splitter.col_split()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    self south_west()\n    {\n\tsub_matrix_type sm(sub_matrix(my_sub_matrix, splitter.row_split(), my_sub_matrix.end_row(), \n\t\t\t\t      my_sub_matrix.begin_col(), splitter.col_split()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    self north_east()\n    {\n\tsub_matrix_type sm(sub_matrix(my_sub_matrix, my_sub_matrix.begin_row(), splitter.row_split(),\n\t\t\t\t      splitter.col_split(), my_sub_matrix.end_col()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    self south_east()\n    {\n\tsub_matrix_type sm(sub_matrix(my_sub_matrix, splitter.row_split(), my_sub_matrix.end_row(), \n\t\t\t\t      splitter.col_split(), my_sub_matrix.end_col()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    // Returning quadrants for const recursator\n\n    self const north_west() const\n    {\n\tsub_matrix_type sm(sub_matrix(const_cast<self*>(this)->my_sub_matrix, my_sub_matrix.begin_row(), splitter.row_split(),\n\t\t\t\t      my_sub_matrix.begin_col(), splitter.col_split()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    self const south_west() const \n    {\n\tsub_matrix_type sm(sub_matrix(const_cast<self*>(this)->my_sub_matrix, splitter.row_split(), my_sub_matrix.end_row(), \n\t\t\t\t      my_sub_matrix.begin_col(), splitter.col_split()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    self const north_east() const \n    {\n\tsub_matrix_type sm(sub_matrix(const_cast<self*>(this)->my_sub_matrix, my_sub_matrix.begin_row(), splitter.row_split(),\n\t\t\t\t      splitter.col_split(), my_sub_matrix.end_col()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    self const south_east() const \n    {\n\tsub_matrix_type sm(sub_matrix(const_cast<self*>(this)->my_sub_matrix, splitter.row_split(), my_sub_matrix.end_row(), \n\t\t\t\t      splitter.col_split(), my_sub_matrix.end_col()));\n\tself tmp(sm, my_bound / 2);\n\treturn tmp;\n    }\n\n    // Checking whether a quadrant is empty\n\n    // For completeness\n    bool north_west_empty() const\n    {\n\treturn false;\n    }\n\n    bool north_east_empty() const\n    {\n\treturn splitter.col_split() == my_sub_matrix.end_col();\n    }\n\n    bool south_west_empty() const\n    {\n\treturn splitter.row_split() == my_sub_matrix.end_row();\n    }\n\n    bool south_east_empty() const\n    {\n\treturn splitter.row_split() == my_sub_matrix.end_row() \n\t       || splitter.col_split() == my_sub_matrix.end_col();\n    }\n\n    bool is_empty() const\n    {\n\treturn my_sub_matrix.begin_row() == my_sub_matrix.end_row()\n\t       || my_sub_matrix.begin_col() == my_sub_matrix.end_col();\n    }\n\n#if 0\n    bool is_leaf() const\n    {\n\treturn my_sub_matrix.num_rows() < 2 || my_sub_matrix.num_cols() < 2;\n    }\n#endif\n\n    size_type bound() const\n    {\n\tassert(my_bound >= my_sub_matrix.num_rows() && my_bound >= my_sub_matrix.num_cols());\n\treturn my_bound;\n    }\n\n    template <typename R1, typename R2> friend void equalize_depth (R1&, R2&);   \n    template <typename R1, typename R2, typename R3> friend void equalize_depth (R1&, R2&, R3&);\n\n  protected:\n    sub_matrix_type     my_sub_matrix;\n    size_type           my_bound;\n    splitter_type       splitter;\n};\n\n#endif\n\ntemplate <typename Recursator1, typename Recursator2>\nvoid inline equalize_depth(Recursator1& r1, Recursator2& r2)\n{\n    typename Recursator1::size_type max_bound= std::max(r1.bound(), r2.bound());\n    r1.my_bound= max_bound;\n    r2.my_bound= max_bound;\n}\n\ntemplate <typename Recursator1, typename Recursator2, typename Recursator3>\nvoid inline equalize_depth(Recursator1& r1, Recursator2& r2, Recursator3& r3)\n{\n    typename Recursator1::size_type max_bound= std::max(std::max(r1.bound(), r2.bound()), r3.bound());\n    r1.my_bound= max_bound;\n    r2.my_bound= max_bound;\n    r3.my_bound= max_bound;\n}\n\n\n// Define free functions (from member functions)\n\n/*! Compute the north-west quadrant of a recursator (i.e. its referred matrix).\n    The result is itself a recursator.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\nrecursator<Matrix> inline north_west(const recursator<Matrix>& rec)\n{\n    return rec.north_west();\n}\n\n/*! Compute the north-east quadrant of a recursator (i.e. its referred matrix).\n    The result is itself a recursator.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\nrecursator<Matrix> inline north_east(const recursator<Matrix>& rec)\n{\n    return rec.north_east();\n}\n\n/*! Compute the south-west quadrant of a recursator (i.e. its referred matrix).\n    The result is itself a recursator.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\nrecursator<Matrix> inline south_west(const recursator<Matrix>& rec)\n{\n    return rec.south_west();\n}\n\n/*! Compute the south-east quadrant of a recursator (i.e. its referred matrix).\n    The result is itself a recursator.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\nrecursator<Matrix> inline south_east(const recursator<Matrix>& rec)\n{\n    return rec.south_east();\n}\n\n\n/*! Check if a recursator (i.e. its referred matrix) is empty.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\nbool inline is_empty(const recursator<Matrix>& rec)\n{\n    return rec.is_empty();\n}\n\n/*! Check if a recursator (i.e. its referred matrix) fills the\n    entire block, i.e. if the number of rows and columns are both\n    equal to the virtual bound.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\nbool inline is_full(const recursator<Matrix>& rec)\n{\n    return num_rows(rec) == rec.bound() && num_cols(rec) == rec.bound();\n}\n\n/*! The number of rows that a sub-matrix would have if it was constructed.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\ntypename recursator<Matrix>::size_type\ninline num_rows(const recursator<Matrix>& rec)\n{\n    using std::min;\n    typename recursator<Matrix>::size_type tmp= num_rows(rec.my_sub_matrix);\n    return rec.my_first_row >= tmp ? 0 : min(rec.my_bound, tmp - rec.my_first_row);\n}\n\n/*! The number of columns that a sub-matrix would have if it was constructed.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\ntypename recursator<Matrix>::size_type\ninline num_cols(const recursator<Matrix>& rec)\n{\n    using std::min;\n    typename recursator<Matrix>::size_type tmp= num_cols(rec.my_sub_matrix);\n    return rec.my_first_col >= tmp ? 0 : min(rec.my_bound, tmp - rec.my_first_col);\n}\n\n/*! The number of elements (rows times columns) that a sub-matrix would have if it was constructed.\n    \\sa \\ref rec_intro \"recursion intro\"\n**/\ntemplate <typename Matrix>\ntypename recursator<Matrix>::size_type\ninline size(const recursator<Matrix>& rec)\n{\n    return num_rows(rec) * num_cols(rec);\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_RECURATOR_INCLUDE\n", "meta": {"hexsha": "4141233de8d759d16387c10e9f060045adef8510", "size": 17753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/recursion/matrix_recursator.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/recursion/matrix_recursator.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/recursion/matrix_recursator.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": 32.6341911765, "max_line_length": 119, "alphanum_fraction": 0.6913197769, "num_tokens": 4317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.052618948147933046, "lm_q1q2_score": 0.02425821800596184}}
{"text": "/**\n * @file bidirectional_dijkstra_impl.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 KSPWLO_BIDIRECTIONAL_DIJKSTRA_IMPL_HPP\n#define KSPWLO_BIDIRECTIONAL_DIJKSTRA_IMPL_HPP\n\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <arlib/routing_kernels/visitor.hpp>\n#include <arlib/type_traits.hpp>\n\n#include <deque>\n#include <iostream>\n#include <limits>\n#include <queue>\n#include <unordered_map>\n#include <vector>\n\nnamespace arlib {\n/**\n * Implementations details of kSPwLO algorithms\n */\nnamespace details {\n//===----------------------------------------------------------------------===//\n//                      Bidirectional Dijkstra types\n//===----------------------------------------------------------------------===//\n\n/**\n * Enum to describe whether a forward or a backward step of bidirectional\n * dijkstra is executing.\n */\nenum class Direction { forward = 1, backward };\n\n/**\n * Returns the opposite direction.\n *\n * @param prev_dir The current execution direction.\n * @return Direction::forward if @p prev_dir == Direction::backward.\n *         Direction::backward otherwise.\n */\nconstexpr Direction switch_direction(Direction prev_dir) {\n  return (prev_dir == Direction::backward) ? Direction::forward\n                                           : Direction::backward;\n}\n\n/**\n * Return code of bi_dijkstra_step()\n */\nenum class BiDijkStepRes {\n  next = 1, /**< arlib::bidirectional_dijkstra() should execute another step. */\n  end,      /**< arlib::bidirectional_dijkstra() should end. */\n  negative_weights /**< arlib::bidirectional_dijkstra() should exit because\n                        preconditions are violated. */\n};\n\n//===----------------------------------------------------------------------===//\n//                      Bidirectional Dijkstra  aliases\n//===----------------------------------------------------------------------===//\ntemplate <typename Vertex>\nusing PathMap =\n    std::unordered_map<Vertex, std::vector<Vertex>, boost::hash<Vertex>>;\n\ntemplate <typename Vertex, typename Length>\nusing FringeElem = std::pair<Vertex, Length>;\n\ntemplate <typename Vertex, typename Length> struct FringeComparator {\n  using Elem = FringeElem<Vertex, Length>;\n  bool operator()(const Elem &lhs, const Elem &rhs) const {\n    return lhs.second > rhs.second;\n  }\n};\n\ntemplate <typename Vertex, typename Length>\nusing Fringe = std::priority_queue<FringeElem<Vertex, Length>,\n                                   std::vector<FringeElem<Vertex, Length>>,\n                                   FringeComparator<Vertex, Length>>;\n\ntemplate <typename Vertex, typename Length>\nusing Seen = std::unordered_map<Vertex, Length, boost::hash<Vertex>>;\n//===----------------------------------------------------------------------===//\n//                      Bidirectional Dijkstra routines\n//===----------------------------------------------------------------------===//\n/**\n * Initialize a DistanceMap with @c infinite value for each vertex in the\n * graph.\n *\n * @post For each vertex @c v in @p G, <tt>distance[v] = +inf</tt>, given\n *       <tt>inf = std::numeric_limits<distance_type>::max()</tt>\n *\n * @tparam Graph A Boost::Graph.\n * @tparam DistanceMap The distance PropertyMap.\n * @param G The graph.\n * @param distance the DistanceMap to initialize.\n */\ntemplate <typename Graph, typename DistanceMap>\nvoid init_distance_vector(Graph &G, DistanceMap distance) {\n  using Length = typename boost::property_traits<DistanceMap>::value_type;\n  constexpr Length inf = std::numeric_limits<Length>::max();\n\n  for (auto [it, end] = vertices(G); it != end; ++it) {\n    distance[*it] = inf;\n  }\n}\n\ntemplate <typename Vertex, typename PredecessorMap, typename BackPredecessorMap>\nvoid merge_paths(Vertex s, Vertex t, Vertex w, PredecessorMap predecessor_f,\n                 BackPredecessorMap predecessor_b,\n                 std::deque<Vertex> &final_path) {\n  final_path.clear();\n  final_path.push_front(w);\n  // Fill with forward partial result\n  auto cur_f = w;\n  while (cur_f != s) {\n    auto pred_f = predecessor_f[cur_f];\n    assert(pred_f != cur_f); // otherwise cur_f wouldnt be reachable, but if\n                             // cur_f wouldnt be reachable we shouldnt be here.\n    final_path.push_front(pred_f);\n    cur_f = pred_f;\n  }\n\n  auto cur_b = w;\n  while (cur_b != t) {\n    auto pred_b = predecessor_b[cur_b];\n    assert(pred_b != cur_b); // otherwise cur_b wouldnt be reachable, but if\n                             // cur_b wouldnt be reachable we shouldnt be here.\n    final_path.push_back(pred_b);\n    cur_b = pred_b;\n  }\n}\n\ntemplate <typename Vertex, typename Length, typename PredecessorMap,\n          typename BackPredecessorMap>\nvoid compare_and_update_shortest_path(Seen<Vertex, Length> &seen_f,\n                                      Seen<Vertex, Length> &seen_b,\n                                      PredecessorMap predecessor_f,\n                                      BackPredecessorMap predecessor_b,\n                                      Vertex s, Vertex t, Vertex w,\n                                      Length &final_distance,\n                                      std::deque<Vertex> &final_path) {\n  auto search_w_f = seen_f.find(w);\n  auto search_w_b = seen_b.find(w);\n  if (search_w_f != std::end(seen_f) && search_w_b != std::end(seen_b)) {\n    auto total_distance = search_w_f->second + search_w_b->second;\n    if (final_distance > total_distance) {\n      final_distance = total_distance;\n      // With predecessor map\n      merge_paths(s, t, w, predecessor_f, predecessor_b, final_path);\n    }\n  }\n}\n\ntemplate <typename Graph, typename PredecessorMap, typename DistanceMap,\n          typename WeightMap, typename OtherPredecessorMap,\n          typename OtherDistanceMap, typename BiDijkstraVisitorImpl,\n          typename Vertex = vertex_of_t<Graph>,\n          typename Length = value_of_t<DistanceMap>>\nBiDijkStepRes bi_dijkstra_step(\n    const Graph &G, Vertex s, Vertex t, PredecessorMap predecessor,\n    DistanceMap distance, WeightMap weight, Fringe<Vertex, Length> &fringe,\n    Seen<Vertex, Length> &seen, OtherPredecessorMap other_predecessor,\n    OtherDistanceMap other_distance, Fringe<Vertex, Length> &other_fringe,\n    Seen<Vertex, Length> &other_seen, Direction direction,\n    Length &final_distance, std::deque<Vertex> &final_path,\n    BiDijkstraVisitor<BiDijkstraVisitorImpl> &visitor) {\n  constexpr Length inf = std::numeric_limits<Length>::max();\n  // Extract closest node to expand\n  const auto [v, dist] = fringe.top();\n  fringe.pop();\n\n  if (distance[v] != inf) {\n    // Shortest path to 'node' already found. Continue.\n    return BiDijkStepRes::next;\n  }\n\n  // Ask the visitor if vertex should be expanded\n  auto lower_bound_v = other_fringe.top().second;\n  if (!visitor.expand_vertex(v, dist, lower_bound_v, final_distance)) {\n    return BiDijkStepRes::next;\n  }\n\n  // Update distance\n  distance[v] = dist; // Equal to seen[v]\n  if (other_distance[v] != inf) {\n    // If we have scanned v in both directions we are done,\n    // we have now discovered the shortest path. But the visitor may ask to keep\n    // on searching.\n\n    // Check terminating condition:\n    auto min_dist = fringe.top().second;\n    auto other_min_dist = other_fringe.top().second;\n\n    if (visitor.terminating_condition(min_dist, other_min_dist,\n                                      final_distance)) {\n      return BiDijkStepRes::end;\n    }\n    // Please refer to:\n    // Andreas Paraskevopoulos, Christos Zaroliagis. Improved Alternative Route\n    // Planning. Daniele Frigioni and Sebastian Stiller. ATMOS - 13th Workshop\n    // on Algorithmic Approaches for Transportation Modelling, Optimizations and\n    // Systems - 2013\n    // auto terminating_condition = min_dist + other_min_dist > d_s_t;\n  }\n\n  // Compute neighbor distances\n  for (auto [it, end] = out_edges(v, G); it != end; ++it) {\n    using boost::get;\n    auto w = target(*it, G);\n    auto min_weight = get(weight, *it);\n    auto vw_length = distance[v] + min_weight;\n\n    if (distance[w] != inf) {\n      if (vw_length < distance[v]) {\n        // Throw some exception \"Contradictory paths found: negative weights?\"\n        return BiDijkStepRes::negative_weights;\n      }\n    } else if (auto search_w = seen.find(w);\n               search_w == std::end(seen) || vw_length < search_w->second) {\n      // Relax v-w edge\n      seen.insert_or_assign(w, vw_length);\n      fringe.push(std::make_pair(w, vw_length));\n\n      // Build new path to w\n      predecessor[w] = v;\n\n      // See if this path is better than the already discovered shortests path\n      if (direction == Direction::forward) {\n        compare_and_update_shortest_path(seen, other_seen, predecessor,\n                                         other_predecessor, s, t, w,\n                                         final_distance, final_path);\n      } else {\n        compare_and_update_shortest_path(other_seen, seen, other_predecessor,\n                                         predecessor, s, t, w, final_distance,\n                                         final_path);\n      }\n    }\n  }\n  // Everything went fine, go with other direction\n  return BiDijkStepRes::next;\n}\n\ntemplate <typename PredecessorMap, typename Vertex>\nvoid fill_predecessor(PredecessorMap predecessor,\n                      const std::deque<Vertex> &final_path) {\n  if (!final_path.empty()) {\n    for (std::size_t i = 0; i < final_path.size() - 1; ++i) {\n      predecessor[final_path[i + 1]] = final_path[i];\n    }\n  }\n}\n} // namespace details\n} // namespace arlib\n\n#endif", "meta": {"hexsha": "5170e30bd913ca8487cc5c5da6c8aed124d85749", "size": 10866, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/routing_kernels/details/bidirectional_dijkstra_impl.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/routing_kernels/details/bidirectional_dijkstra_impl.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/routing_kernels/details/bidirectional_dijkstra_impl.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": 38.2605633803, "max_line_length": 80, "alphanum_fraction": 0.6355604638, "num_tokens": 2415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.05108273208147154, "lm_q1q2_score": 0.024145962636620045}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::sampler.hpp                                                          //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_ARS_SAMPLER_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ARS_SAMPLER_HPP_ER_2009\n#include <boost/ars/error.hpp>\n#include <boost/ars/proposal_sampler.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace ars{\n\n// This class adds a rejection steop to proposal_sampler \n//\n// PropS is an instance of the class template proposal_sampler\ntemplate<typename PropS>\nclass sampler : public PropS{\n    typedef PropS super_t;\n    public:\n\n    sampler():\n    super_t(),n_max_reject_(super_t::param_::n_max_reject),n_reject_(0){}\n\n    sampler(const sampler& that)\n    :PropS(that),n_max_reject_(that.n_max_reject_),n_reject_(that.n_reject_)\n    {}\n\n    sampler& operator=(const sampler& that){\n        if(&that!=this){\n            PropS::operator=(that);\n            n_max_reject_ = that.n_max_reject_;\n            n_reject_ = that.n_reject_;\n        }\n        return *this;\n    }\n\n    void set_n_max_reject(unsigned n){ n_max_reject_ = n; }\n\n    template<typename U>\n    typename super_t::result_type operator()(U& u)const{\n        static const char* method\n            = \"ars::sampler::operator()(U&) after n = %1%\";\n        typename super_t::result_type draw;\n        for(typename super_t::size_type i = 0; i<n_max_reject(); i++){\n            n_reject_ = i;\n            if(this->sample(u,draw)){\n                return draw;\n            }\n        }\n        boost::format f(method); f%n_max_reject();\n        throw exception(method,f.str(),*this);\n    }\n    typename super_t::size_type n_max_reject()const{ return n_max_reject_; }\n    typename super_t::size_type n_reject()const{ return n_reject_; }\n\n    protected:\n    typename super_t::size_type n_max_reject_;\n    mutable typename super_t::size_type n_reject_;\n};\n\n\n}// ars\n}// detail\n}// statistics\n}// boost\n\n#endif ", "meta": {"hexsha": "d2c21d86e8e473b59f17d4ac743e77d90bcb2789", "size": 2370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/boost/ars/sampler.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": "adaptive_rejection_sampling/boost/ars/sampler.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": "adaptive_rejection_sampling/boost/ars/sampler.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": 32.9166666667, "max_line_length": 79, "alphanum_fraction": 0.5717299578, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04813677521322845, "lm_q1q2_score": 0.024068387606614224}}
{"text": "/**********************************************************************************/\n/* This file is part of spla project                                              */\n/* https://github.com/JetBrains-Research/spla                                     */\n/**********************************************************************************/\n/* MIT License                                                                    */\n/*                                                                                */\n/* Copyright (c) 2021 JetBrains-Research                                          */\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 SPLA_SPLAINDICESTOROWOFFSETS_HPP\n#define SPLA_SPLAINDICESTOROWOFFSETS_HPP\n\n#include <boost/compute/algorithm.hpp>\n#include <boost/compute/command_queue.hpp>\n\n#include <algorithm>\n#include <numeric>\n#include <vector>\n\n#include <spla-cpp/SplaConfig.hpp>\n\nnamespace spla {\n\n    /**\n     * @addtogroup Internal\n     * @{\n     */\n\n    /**\n     * @brief Compute row offsets from coo row indices buffer.\n     *\n     * Result offsets array has size n + 1.\n     * Offsets[i] stores first index of row i in indices buffer.\n     * Offsets[i + 1] - Offsets[i] equals number of nnz values in row i in indices buffer.\n     * Offsets[n] equals number off values in indices buffer.\n     * Lengths[i] equals number of nnz values in row i in indices buffer.\n     *\n     * @param indices Array of rows indices\n     * @param[out] offsets Output array with offsets\n     * @param[out] lengths Output array of row lengths\n     * @param n Number of rows in matrix\n     * @param queue Command queue to execute\n     */\n    inline void IndicesToRowOffsets(const boost::compute::vector<unsigned int> &indices,\n                                    boost::compute::vector<unsigned int> &offsets,\n                                    boost::compute::vector<unsigned int> &lengths,\n                                    std::size_t n,\n                                    boost::compute::command_queue &queue) {\n        using namespace boost;\n\n        lengths.resize(n + 1, queue);\n        offsets.resize(n + 1, queue);\n        compute::fill(lengths.begin(), lengths.end(), 0u, queue);\n\n        if (indices.empty()) {\n            compute::fill(offsets.begin(), offsets.end(), 0u, queue);\n            return;\n        }\n\n        BOOST_COMPUTE_CLOSURE(void, countRowLengths, (unsigned int i), (indices, lengths), {\n            uint rowId = indices[i];\n            atomic_inc(&lengths[rowId]);\n        });\n\n        compute::for_each_n(compute::counting_iterator<unsigned int>(0), indices.size(), countRowLengths, queue);\n        compute::exclusive_scan(lengths.begin(), lengths.end(), offsets.begin(), queue);\n    }\n\n    /**\n     * Overload\n     */\n    inline void IndicesToRowOffsets(const boost::compute::vector<unsigned int> &indices,\n                                    boost::compute::vector<unsigned int> &offsets,\n                                    std::size_t n,\n                                    boost::compute::command_queue &queue) {\n        using namespace boost;\n        boost::compute::vector<unsigned int> lengths(queue.get_context());\n        IndicesToRowOffsets(indices, offsets, lengths, n, queue);\n    }\n\n    /**\n     * @brief Compute row offsets from coo row indices buffer.\n     *\n     * Result offsets array has size n + 1.\n     * Offsets[i] stores first index of row i in indices buffer.\n     * Offsets[i + 1] - Offsets[i] equals number of nnz values in row i in indices buffer.\n     * Offsets[n] equals number off values in indices buffer.\n     * Lengths[i] equals number of nnz values in row i in indices buffer.\n     *\n     * @param indices Array of rows indices\n     * @param[out] offsets Output array with offsets\n     * @param[out] lengths Output array of row lengths\n     * @param n Number of rows in matrix\n     */\n    inline void IndicesToRowOffsets(const std::vector<unsigned int> &indices,\n                                    std::vector<Index> &offsets,\n                                    std::vector<Index> &lengths,\n                                    std::size_t n) {\n        offsets.resize(n + 1);\n        lengths.resize(n + 1);\n        std::fill(lengths.begin(), lengths.end(), 0u);\n\n        if (indices.empty()) {\n            std::fill(offsets.begin(), offsets.end(), 0u);\n            return;\n        }\n\n        std::for_each(indices.begin(), indices.end(), [&](auto i) { lengths[i] += 1; });\n        std::exclusive_scan(lengths.begin(), lengths.end(), offsets.begin(), 0u);\n    }\n\n    /**\n     * Overload\n     */\n    inline void IndicesToRowOffsets(const std::vector<unsigned int> &indices,\n                                    std::vector<Index> &offsets,\n                                    std::size_t n) {\n        std::vector<unsigned int> lengths;\n        IndicesToRowOffsets(indices, offsets, lengths, n);\n    }\n\n    /**\n     * @}\n     */\n\n}// namespace spla\n\n#endif//SPLA_SPLAINDICESTOROWOFFSETS_HPP\n", "meta": {"hexsha": "e941ce72831d5159e8acc49eeeac7d43121d9706", "size": 6530, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/compute/SplaIndicesToRowOffsets.hpp", "max_stars_repo_name": "mfkiwl/spla", "max_stars_repo_head_hexsha": "9a7515f6ff5176bc0250734a09aac0fcafbfd3da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-09-24T03:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T09:09:01.000Z", "max_issues_repo_path": "sources/compute/SplaIndicesToRowOffsets.hpp", "max_issues_repo_name": "mfkiwl/spla", "max_issues_repo_head_hexsha": "9a7515f6ff5176bc0250734a09aac0fcafbfd3da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 78.0, "max_issues_repo_issues_event_min_datetime": "2021-09-11T09:39:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T19:50:07.000Z", "max_forks_repo_path": "sources/compute/SplaIndicesToRowOffsets.hpp", "max_forks_repo_name": "mfkiwl/spla", "max_forks_repo_head_hexsha": "9a7515f6ff5176bc0250734a09aac0fcafbfd3da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T15:43:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T11:29:52.000Z", "avg_line_length": 44.4217687075, "max_line_length": 113, "alphanum_fraction": 0.5232771822, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.06560483837252302, "lm_q1q2_score": 0.024050061308431778}}
{"text": "﻿#ifndef GRAPH_HPP\n#define GRAPH_HPP\n\nusing namespace std;\n\n#ifdef MPI_ENABLED\n\n//#include <cereal/types/map.hpp>\n//#include <cereal/types/set.hpp>\n//#include <cereal/types/vector.hpp>\n//#include <cereal/access.hpp>\n\n#include <boost/serialization/map.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/access.hpp>\n\n#else\n\n#include <map>\n#include <set>\n#include <vector>\n\n#endif\n\n#include <fmt/format.h>\n#include \"util.hpp\"\n\n#include <climits>\n#include <cmath> /* floor, ceil */\n#include <cassert>\n#include <mutex>\n#include <random>\n#include <sstream>\n\nclass Graph\n{\nprivate:\n#ifdef MPI_ENABLED\n\t//friend class cereal::access;\n\tfriend class boost::serialization::access;\n\n#endif\n\n\tstruct FoldedVertices\n\t{\n\t\tint u{-1};\n\t\tint v{-1};\n\t\tint w{-1};\n\t\t/*this id is negative so it does not get confused with\n\t\t\tpositive vertices' names, then negative vertices in graph\n\t\t\twill be those ones who were folded*/\n\t\t//int id;\n\n\t\tFoldedVertices()\n\t\t{\n\t\t}\n\n\t\tFoldedVertices(int u, int v, int w)\n\t\t{\n\t\t\tthis->u = u;\n\t\t\tthis->v = v;\n\t\t\tthis->w = w;\n\t\t}\n#ifdef MPI_ENABLED\n\t\t// cereal\n\t\t//template <class Archive>\n\t\t//void serialize(Archive &ar, const unsigned int version)\n\t\t//{\n\t\t//\tar(u, v, w);\n\t\t//}\n\n\t\t//boost\n\t\ttemplate <class Archive>\n\t\tvoid serialize(Archive &ar, const unsigned int version)\n\t\t{\n\t\t\tar &u;\n\t\t\tar &v;\n\t\t\tar &w;\n\t\t}\n#endif\n\t};\n\n\tvoid _addRowToList(int vec0)\n\t{\n\t\tthis->adj.insert(pair<int16_t, set<int16_t>>(vec0, rows));\n\t\tthis->rows.clear();\n\t}\n\n\tvoid _calculerVertexMaxDegree()\n\t{\n\t\tint DEG;\n\t\t/*Finding vertex degrees, in order to start exploring by these ones.*/\n\t\tif (!vertexDegree.empty())\n\t\t{\n\t\t\tvertexDegree.clear();\n\t\t\tidsMax.clear();\n\t\t\tmax = INT_MIN;\n\t\t}\n\n\t\tfor (auto const &[v, neighbours] : adj)\n\t\t{\n\t\t\tDEG = neighbours.size();\n\t\t\tthis->vertexDegree.insert({v, DEG});\n\t\t\tif (DEG > max)\n\t\t\t\tmax = DEG;\n\t\t}\n\n\t\tfor (auto const &[v, neighbours] : adj)\n\t\t{\n\t\t\tif (vertexDegree[v] == max)\n\t\t\t\tidsMax.push_back(v);\n\t\t}\n\t}\n\n\tvoid _calculerVertexMinDegree()\n\t{\n\t\tint DEG;\n\t\t/*Finding vertex degrees, in order to start exploring by these ones.*/\n\t\tif (!vertexDegree.empty())\n\t\t{\n\t\t\tvertexDegree.clear();\n\t\t\tidsMin.clear();\n\t\t\tmin = INT_MAX;\n\t\t}\n\n\t\tfor (auto const &[v, neighbours] : adj)\n\t\t{\n\t\t\tDEG = neighbours.size();\n\t\t\tthis->vertexDegree.insert({v, DEG});\n\t\t\tif (DEG < min)\n\t\t\t\tmin = DEG;\n\t\t}\n\n\t\tfor (auto const &[v, neighbours] : adj)\n\t\t{\n\t\t\tif (vertexDegree[v] == min)\n\t\t\t\tidsMin.push_back(v);\n\t\t}\n\t}\n\n\tvoid _updateVertexDegree()\n\t{\n\t\t//Recalculating the vertex with maximum number of edges\n\t\tint max_tmp = INT_MIN;\n\t\tint min_tmp = INT_MAX;\n\n\t\tfor (auto &[v, degree] : vertexDegree)\n\t\t{\n\t\t\tif (degree > max_tmp)\n\t\t\t\tmax_tmp = degree;\n\n\t\t\tif (degree < min_tmp)\n\t\t\t\tmin_tmp = degree;\n\t\t}\n\n\t\tmax = max_tmp;\n\t\tmin = min_tmp;\n\t\tidsMax.clear();\n\t\tidsMin.clear();\n\t\t/*storing position of highest degree vertices within adjacency list*/\n\t\tfor (auto &[v, degree] : vertexDegree)\n\t\t{\n\t\t\tif (degree == max)\n\t\t\t\tthis->idsMax.push_back(v);\n\t\t\tif (degree == min)\n\t\t\t\tthis->idsMin.push_back(v);\n\t\t}\n\t}\n\n\tint _getRandomVertex(std::vector<int16_t> &target)\n\t{\n\t\t/*Here this will explore the list of higest degree vertices and\n\t\t\tit will choose any of them randomly*/\n\n\t\tstd::random_device rd;\t// Will be used to obtain a seed for the random number engine\n\t\tstd::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()\n\t\tstd::uniform_int_distribution<> distrib(0, target.size() - 1);\n\n\t\tint random = distrib(gen);\n\t\treturn target[random];\n\t}\n\n\tvoid _readEdgesFromGraph()\n\t{\n\n\t\tint _counterEdges = 0;\n\t\tauto adj_cpy = this->adj;\n\t\tauto it = adj_cpy.begin();\n\n\t\twhile (it != adj_cpy.end())\n\t\t{\n\t\t\t_counterEdges += it->second.size();\n\t\t\tauto it2 = it->second.begin();\n\t\t\twhile (it2 != it->second.end())\n\t\t\t{\n\t\t\t\tadj_cpy[*it2].erase(it->first);\n\t\t\t\t++it2;\n\t\t\t}\n\t\t\t++it;\n\t\t}\n\t\tthis->numEdges = _counterEdges;\n\t}\n\n\t/*Preprocessing methods*/\n\t/*An isolated vertex (one of degree zero) cannot be in a vertex\n\tcover of optimal size. Because there are no edges incident upon\n\tsuch a vertex, there is no benefit in including it in any cover.\n\tThus, in G0, an isolated vertex can be eliminated, reducing n0 by one.\n\tThis rule is applied repeatedly until all isolated\n\tvertices are eliminated.*/\n\tbool _rule1(map<int16_t, set<int16_t>> &adj)\n\t{\n\t\tstd::vector<int16_t> degree_zero;\n\n\t\t// this loop finds vertices of degree zero\n\t\tfor (auto const &[v, neighbours] : adj)\n\t\t{\n\t\t\tif (neighbours.size() == 0)\n\t\t\t\tdegree_zero.push_back(v);\n\t\t}\n\n\t\tif (degree_zero.size() == 0)\n\t\t\treturn false; // no vertices then no changes where made\n\n\t\t// this loop removes vertices of zero degree from the adjacency list\n\t\tfor (auto &vertex : degree_zero)\n\t\t{\n\t\t\tadj.erase(vertex);\n\t\t\tvertexDegree.erase(vertex);\n\t\t}\n\t\treturn true;\n\t}\n\n\t/*In the case of a pendant vertex (one of degree one), there is\n\tan optimal vertex cover that does not contain the pendant vertex\n\tbut does contain its unique neighbor. Thus, in G0, both the pendant\n\tvertex and its neighbor can be eliminated. This also eliminates any\n\tadditional edges incident on the neighbor, which may leave isolated\n\tvertices for deletion under Rule 1. This reduces n0 by the number\n\tof deleted vertices and reduces k by one. This rule is applied repeatedly\n\tuntil all pendant vertices are eliminated.*/\n\tbool _rule2(map<int16_t, set<int16_t>> &adj, int16_t &added_to_cover)\n\t{\n\t\tvector<int16_t> pendant_neighbour;\n\t\tvector<pair<int16_t, int16_t>> matching_ccs;\n\n\t\tfor (auto &[v, neighbours] : adj)\n\t\t{\n\t\t\tif (neighbours.size() == 1)\n\t\t\t{\n\t\t\t\tint w = *neighbours.begin(); // only neighbour of v\n\t\t\t\tpendant_neighbour.push_back(w);\n\n\t\t\t\t//special case : what if the neighbor also has degree 1?\n\t\t\t\tif (adj[w].size() == 1) // v is only neighbour of w?\n\t\t\t\t{\n\t\t\t\t\tif (v < w) //not add the same matching twice\n\t\t\t\t\t\tmatching_ccs.push_back(make_pair(v, w));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!_cover.contains(w)) // avoid added_to_cover++ twice for the same pendant vertex\n\t\t\t\t\t{\n\t\t\t\t\t\t_cover.insert(w);\n\t\t\t\t\t\tadded_to_cover++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (pendant_neighbour.size() == 0 && matching_ccs.size() == 0)\n\t\t\treturn false; // no vertices then no changes where made\n\n\t\tfor (auto &match : matching_ccs)\n\t\t{\n\t\t\t_cover.insert(match.first);\n\t\t\tthis->erase(adj, match.first); // only one is erased, since erase(..) has its own way to handle counter\n\t\t\t//this->erase(adj, match.second); // this will be handled by _rule1(..) since it is  iterative\n\t\t\tadded_to_cover++;\n\t\t}\n\n\t\tfor (auto &neighbour : pendant_neighbour)\n\t\t{\n\t\t\tthis->erase(adj, neighbour);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/* this rule states that having a vertex u with two adjacent neighbours v and w,\n\t\tthen v and w will be in the MVC*/\n\tbool _rule3(map<int16_t, set<int16_t>> &adj, int16_t &added_to_cover)\n\t{\n\t\t/*\t\tu ---- v ~~~\n\t\t\t\t \\\t  /\n\t\t\t\t  \\  /\n\t\t\t\t   w ~~~\n\t\t*/\n\t\tbool flag = false;\n\t\tstd::once_flag oo_flag;\n\n\t\tauto ite = adj.begin();\n\t\twhile (ite != adj.end())\n\t\t{\n\t\t\tif (ite->second.size() == 2)\n\t\t\t{\n\t\t\t\tint16_t u = ite->first;\n\t\t\t\tauto it = ite->second.begin();\n\t\t\t\tint16_t v = *it;\n\t\t\t\tit++;\n\t\t\t\tint16_t w = *it;\n\n\t\t\t\tif (adj[v].contains(w) && adj[w].contains(v))\n\t\t\t\t{\n\t\t\t\t\t_cover.insert(v); // u is included in the MVC\n\t\t\t\t\t_cover.insert(w); // w is included in the MVC\n\t\t\t\t\tadded_to_cover += 2;\n\n\t\t\t\t\terase(adj, u); // u is discarded from the MVC\n\t\t\t\t\terase(adj, v); // v is removed from list since it was already included in the MVC\n\t\t\t\t\terase(adj, w); // w is removed from list since it was already included in the MVC\n\n\t\t\t\t\tflag = true; // graph has been changed\n\t\t\t\t\t//reset iterator in here\n\t\t\t\t\tite = adj.begin(); // loop reseted since after performing deletions, graph might end up with more similar cases\n\t\t\t\t\t// also the iterator breaks\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tite++;\n\t\t\t}\n\t\t\telse\n\t\t\t\tite++;\n\t\t}\n\n\t\treturn flag;\n\t}\n\n\tbool _rule4(map<int16_t, set<int16_t>> &adj)\n\t{\n\t\t/*\t\tu ---- v ~~~\n\t\t\t\t \\\t\t\t\t==>  ~~~(u')~~~\n\t\t\t\t  \\\n\t\t\t\t   w ~~~\n\t\t*/\n\n\t\tauto it = adj.begin();\n\t\tmap<int16_t, set<int16_t>> folded_vertices;\n\t\tstd::once_flag oo_flag;\n\n\t\tint16_t id = -1;\n\n\t\tbool flag = false;\n\n\t\twhile (it != adj.end())\n\t\t{\n\t\t\tif (it->second.size() == 2)\n\t\t\t{\n\t\t\t\tint16_t u = it->first;\n\t\t\t\t/*adjacent neighbours*/\n\t\t\t\tset<int16_t>::const_iterator an = it->second.begin();\n\t\t\t\tint16_t v = *an;\n\t\t\t\tan++;\n\t\t\t\tint16_t w = *an;\n\t\t\t\tif (!adj[v].contains(w) && !adj[w].contains(v))\n\t\t\t\t{\n\t\t\t\t\t//Check to not fold already folded vertices\n\t\t\t\t\tif (it->first < 0 || v < 0 || w < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tit++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t//Create (u')\n\t\t\t\t\tFoldedVertices u_prime(u, v, w);\n\t\t\t\t\t//push to a adj of all the folded vertices\n\t\t\t\t\tfoldedVertices.insert(pair<int16_t, FoldedVertices>(id, u_prime));\n\n\t\t\t\t\t//Check neighbours of v\n\t\t\t\t\tset<int16_t> foldedNeigbours;\n\t\t\t\t\tfor (auto vertex : adj[v])\n\t\t\t\t\t{\n\t\t\t\t\t\tif (vertex != u)\n\t\t\t\t\t\t\tfoldedNeigbours.insert(vertex);\n\t\t\t\t\t}\n\n\t\t\t\t\t//Check neighbours of w\n\t\t\t\t\tfor (auto vertex : adj[w])\n\t\t\t\t\t{\n\t\t\t\t\t\tif (vertex != u)\n\t\t\t\t\t\t\tfoldedNeigbours.insert(vertex);\n\t\t\t\t\t}\n\n\t\t\t\t\t//Erase u,v and w from the graph\n\t\t\t\t\terase(adj, u);\n\t\t\t\t\terase(adj, v);\n\t\t\t\t\terase(adj, w);\n\n\t\t\t\t\t//Insert (u') into graph\n\t\t\t\t\tadj.insert(pair<int16_t, set<int16_t>>(id, foldedNeigbours));\n\t\t\t\t\t//link the neighbours of v and w to (u')\n\t\t\t\t\tfor (auto f_vertex : foldedNeigbours)\n\t\t\t\t\t{\n\t\t\t\t\t\tadj[f_vertex].insert(id);\n\t\t\t\t\t\tnumEdges++;\n\t\t\t\t\t}\n\n\t\t\t\t\t// post-processed graph has two fewer edges due to the folding\n\t\t\t\t\t//numEdges -= 2;\n\n\t\t\t\t\tid--;\n\t\t\t\t\t// graph was changed\n\t\t\t\t\tflag = true;\n\t\t\t\t\t// restar iterator\n\n\t\t\t\t\tit = adj.begin();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tit++;\n\t\t\t}\n\t\t\telse\n\t\t\t\tit++;\n\t\t}\n\t\treturn flag;\n\t}\n\n\tvoid erase(map<int16_t, set<int16_t>> &adj, int16_t v)\n\t{\n\t\ttry\n\t\t{\n\t\t\t// this loop removes vertex v from all its neighbours\n\t\t\tfor (auto &vertex : adj[v])\n\t\t\t{\n\t\t\t\tadj[vertex].erase(v);\n\t\t\t\tthis->vertexDegree[vertex]--;\n\t\t\t}\n\t\t\tnumEdges -= adj[v].size();\t // number of edges reduced by the number of neighbours that v had\n\t\t\tadj.erase(v);\t\t\t\t // vertex v totally removed from adj list\n\t\t\tthis->vertexDegree.erase(v); // removed from the vertexDegree list as well\n\t\t}\n\t\tcatch (const std::exception &e)\n\t\t{\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"Exception while erasing vertex from adj\"\n\t\t\t   << '\\n'\n\t\t\t   << e.what() << '\\n';\n\n\t\t\tstd::cerr << ss.str();\n\t\t}\n\t}\n\n\tvoid build(int n, double p)\n\t{\n\t\tint maxEdgesPossible = n * (n - 1) / 2;\n\t\tint maxEdgesPerNode = maxEdgesPossible / n;\n\t\tthis->max = 0;\n\t\tthis->min = 0;\n\t\tthis->numEdges = 0;\n\t\tthis->numVertices = 0;\n\n\t\tdouble _p = p * (double)maxEdgesPerNode / 100.0;\n\n\t\tint r = 0, m = 0;\n\n\t\t//srand(time(NULL)); //this commented to obtain always the same graph\n\t\t// Build the edges\n\t\tstd::random_device rd;\t// Will be used to obtain a seed for the random number engine\n\t\tstd::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()\n\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tfor (int j = i + 1; j < n; j++)\n\t\t\t{\n\n\t\t\t\tstd::uniform_int_distribution<> distrib(1, n);\n\t\t\t\tr = distrib(gen);\n\t\t\t\t//r = rand() % n + 1;\n\n\t\t\t\t//if (r <= _p) {\n\t\t\t\tif (r <= p)\n\t\t\t\t{\n\t\t\t\t\t++m;\n\t\t\t\t\tadj[i].insert(j);\n\t\t\t\t\tadj[j].insert(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*This second loop is used only if adj.size() != n*/\n\t\t// rand()%a + b => interval-> [b, b + a)\n\t\tif (adj.size() < (size_t)n)\n\t\t{\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\tif (!adj.contains(i))\n\t\t\t\t{\n\t\t\t\t\tm++;\n\t\t\t\t\tint interval1 = i - 0;\n\t\t\t\t\tint interval2 = n - i;\n\n\t\t\t\t\tint low_bnd;\n\t\t\t\t\tint upp_bnd;\n\t\t\t\t\tint j;\n\n\t\t\t\t\tif (interval1 > interval2)\n\t\t\t\t\t{\n\t\t\t\t\t\tupp_bnd = i - 1;\n\t\t\t\t\t\tstd::uniform_int_distribution<> distrib(0, upp_bnd);\n\t\t\t\t\t\tint tmp = distrib(gen);\n\t\t\t\t\t\t//int tmp = rand() % upp_bnd;\n\t\t\t\t\t\tj = tmp;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tlow_bnd = i + 1;\n\t\t\t\t\t\tupp_bnd = n - (i + 1);\n\t\t\t\t\t\tstd::uniform_int_distribution<> distrib(low_bnd, upp_bnd);\n\t\t\t\t\t\tint tmp = distrib(gen);\n\t\t\t\t\t\t//int tmp = rand() % upp_bnd + low_bnd;\n\t\t\t\t\t\tj = tmp;\n\t\t\t\t\t}\n\t\t\t\t\tadj[i].insert(j);\n\t\t\t\t\tadj[j].insert(i);\n\t\t\t\t\t//if (adj.size() > n)\n\t\t\t\t\t//{\n\t\t\t\t\t//\tint var = 5;\n\t\t\t\t\t//}\n\t\t\t\t}\n\t\t\t\tif (adj.size() == (size_t)n)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tthis->numEdges = m;\n\t\tthis->numVertices = n;\n\t\t/*begin<----------4 testing purposes-------*/\n\t\tdouble mean = (double)m / n;\n\t\t//double density = mean / (double)maxEdgesPerNode;\n\t}\n\npublic:\n\tbool empty()\n\t{\n\t\treturn _cover.empty();\n\t}\n\t//Default constructor\n\tGraph()\n\t{\n\t\tthis->max = 0;\n\t\tthis->min = 0;\n\t\tthis->numEdges = 0;\n\t\tthis->numVertices = 0;\n\n\t\t//const size_t BOUND = 1000000;\n\n\t\t//std::random_device rd;\t// Will be used to obtain a seed for the random number engine\n\t\t//std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()\n\t\t//std::uniform_int_distribution<> distrib(0, BOUND);\n\t\t//\n\t\t//for (size_t i = 0; i < BOUND; i++)\n\t\t//{\n\t\t//\tint random = distrib(gen);\n\t\t//\tmemory_hog.push_back(random);\n\t\t//}\n\t}\n\n\t//Parameterized constructor\n\t//N size, p propability out of 100\n\tGraph(int n, double p)\n\t{\n\t\tbuild(n, p);\n\t\t/*------------------------------------->end*/\n\t\t_calculerVertexMaxDegree();\n\t\t_calculerVertexMinDegree();\n\t}\n\n\tvoid addNeighbour(int val)\n\t{\n\t\tthis->rows.insert(val);\n\t}\n\n\t// removes all vertices of degree zero, it returns the number of removed vertices\n\tint removeZeroVertexDegree()\n\t{\n\t\tint size0 = adj.size();\n\t\t_rule1(this->adj);\n\t\tint size1 = adj.size();\n\t\treturn abs(size0 - size1);\n\t}\n\n\tvoid removeEdge(const int &v, const int &w)\n\t{\n\t\tadj[v].erase(w);\n\t\tadj[w].erase(v);\n\n\t\tvertexDegree[v]--;\n\t\tvertexDegree[w]--;\n\n\t\tif (adj[v].size() == 0)\n\t\t\t_zeroVertexDegree.insert(v);\n\t\tif (adj[w].size() == 0)\n\t\t\t_zeroVertexDegree.insert(w);\n\n\t\tnumEdges--;\n\t\t_updateVertexDegree();\n\t}\n\n\tint removeVertex(int v)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (!adj.contains(v))\n\t\t\t{\n\t\t\t\tfmt::print(\"_VERTEX_NOT_FOUND\\n\");\n\t\t\t\tthrow \"_VERTEX_NOT_FOUND\";\n\t\t\t}\n\t\t\tnumEdges = numEdges - adj[v].size();\n\n\t\t\t/*Here we explore all the neighbours of v, and then we find\n\t\t\tvertex v inside of those neighbours in order to erase v of them*/\n\t\t\tfor (auto &neighbour : adj[v])\n\t\t\t{\n\t\t\t\tadj[neighbour].erase(v);\n\t\t\t\tif (adj[neighbour].size() == 0)\n\t\t\t\t{\n\t\t\t\t\t// store temporary position of vertices that end up with no neighbours\n\t\t\t\t\tthis->_zeroVertexDegree.insert(neighbour);\n\t\t\t\t}\n\t\t\t\tthis->vertexDegree[neighbour]--;\n\t\t\t}\n\n\t\t\t/*After v is been erased from its neighbours, then v is erased\n\t\t\tfrom graph and the VertexDegree is updated*/\n\t\t\tthis->adj.erase(v);\n\t\t\tthis->vertexDegree.erase(v);\n\n\t\t\tthis->_cover.insert(v);\n\t\t\t_updateVertexDegree();\n\n\t\t\tnumVertices = adj.size();\n\t\t}\n\t\tcatch (const std::exception &e)\n\t\t{\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"Exception while removing vertex : \"\n\t\t\t   << v\n\t\t\t   << '\\n'\n\t\t\t   << e.what() << '\\n';\n\t\t\tstd::cerr << ss.str();\n\t\t}\n\t\treturn 0;\n\t}\n\n\t// it returns the number of neighbours that were removed\n\tint removeNv(int v)\n\t{\n\t\tstd::set<int16_t> neighboursOfv(adj[v]); //copy of neigbours of vertex v\n\t\tint numNeighours = neighboursOfv.size();\n\t\tfor (auto vertex : neighboursOfv)\n\t\t{\n\t\t\tif (adj.contains(vertex))\n\t\t\t{\n\t\t\t\tthis->_cover.insert(vertex);\n\t\t\t\tremoveVertex(vertex);\n\t\t\t}\n\t\t}\n\t\treturn numNeighours;\n\t}\n\n\tvoid readGraph(string NameOfFile, string directory)\n\t{\n\t\tusing namespace std;\n\t\tstring line;\n\t\tvector<string> split;\n\t\tint i = 0;\n\t\tint _counter_vertices = 0;\n\n\t\twhile (1)\n\t\t{\n\t\t\tline = Util::GetFileLine(directory + NameOfFile, i);\n\t\t\tif (line == \"\")\n\t\t\t\tbreak;\n\t\t\tsplit = Util::Split(line, \"\\t\");\n\n\t\t\tfor (int i = 1; i != split.size(); i++)\n\t\t\t{\n\t\t\t\taddNeighbour(Util::ToInt(split[i]));\n\t\t\t}\n\t\t\t_addRowToList(Util::ToInt(split[0]));\n\t\t\t_counter_vertices++;\n\n\t\t\ti++;\n\t\t}\n\t\t_calculerVertexMaxDegree();\n\t\t_readEdgesFromGraph();\n\t\t//Graph::currentMVCSize = adj.size();\n\t\tthis->numVertices = _counter_vertices;\n\t}\n\n\tvoid readDimacs(string &NameOfFile)\n\t{\n\t\tstd::fstream file;\n\t\tfile.open(NameOfFile, ios::in);\n\n\t\tif (!file.is_open())\n\t\t\tthrow \"File not found\";\n\n\t\tstd::string line;\n\n\t\twhile (std::getline(file, line))\n\t\t{\n\t\t\tif (line[0] == 'e')\n\t\t\t{\n\t\t\t\tauto split = Util::Split(line, \" \");\n\t\t\t\tint u = std::stoi(split[1]);\n\t\t\t\tint v = std::stoi(split[2]);\n\t\t\t\tadd_edge(u, v);\n\t\t\t\tnumEdges++;\n\t\t\t}\n\t\t}\n\t\tnumVertices = adj.size();\n\t\t_calculerVertexMaxDegree();\n\t\t_calculerVertexMinDegree();\n\n\t\treturn;\n\t}\n\n\tvoid add_edge(int u, int v)\n\t{\n\t\tadj[u].insert(v);\n\t\tadj[v].insert(u);\n\t}\n\n\tvoid readEdges(string NameOfFile)\n\t{\n\n\t\tstd::ifstream file(NameOfFile);\n\n\t\tif (!file.is_open())\n\t\t{\n\t\t\tthrow std::runtime_error(\"Input file not found\\n\");\n\t\t}\n\n\t\tint u, v;\n\t\tint i = 0;\n\t\twhile (!file.eof())\n\t\t{\n\t\t\ti++;\n\t\t\tfile >> u >> v;\n\t\t\tadj[u].insert(v);\n\t\t\tadj[v].insert(u);\n\t\t}\n\n\t\tnumEdges = i;\n\t\tnumVertices = adj.size();\n\n\t\t/*4 testing*/\n\t\tdouble mean = (double)numEdges / (double)numVertices;\n\t\t//double prob = mean * 100 / (double)numVertices;\n\n\t\tdouble maxEdgesPossible = numVertices * (numVertices - 1) / 2;\n\t\tdouble maxEdgesPerNode = maxEdgesPossible / (double)numVertices;\n\t\t//double density = mean / maxEdgesPerNode;\n\n\t\t_calculerVertexMaxDegree();\n\t\t_calculerVertexMinDegree();\n\t}\n\n\t/*It explores the highest degree edges and choses whether\n\t\tthe first one in the list or arbitrarily*/\n\t[[nodiscard]] int id_max(bool random = true)\n\t{\n\t\treturn random ? _getRandomVertex(this->idsMax) : idsMax[0];\n\t}\n\n\t[[nodiscard]] int id_min(bool random = true)\n\t{\n\t\treturn random ? _getRandomVertex(this->idsMin) : idsMin[0];\n\t}\n\n\t[[nodiscard]] int d_max()\n\t{\n\t\treturn max;\n\t}\n\n\t[[nodiscard]] int d_min()\n\t{\n\t\treturn min;\n\t}\n\n\t//Returns graph's size\n\tint size()\n\t{\n\t\treturn this->adj.size();\n\t}\n\n\t//returns cover size\n\n\tint coverSize()\n\t{\n\t\treturn this->_cover.size();\n\t}\n\n\t//BETA:...\n\tbool isCovered()\n\t{\n\t\treturn numEdges == 0 ? 1 : 0;\n\t}\n\n\t//gets neighbours of v, Nv(v) = {w1,w2, ... ,wi}\n\tstd::set<int16_t> &operator[](const int16_t v)\n\t{\n\t\tif (!adj.contains(v))\n\t\t\tthrow \"_VERTEX_NOT_FOUND\";\n\t\telse\n\t\t\treturn adj[v];\n\t}\n\n\ttypedef std::map<int16_t, set<int16_t>>::iterator iterator;\n\n\titerator begin() { return adj.begin(); }\n\titerator end() { return adj.end(); }\n\n\tsize_t preprocessing()\n\t{\n\n\t\tclean_graph(INT_MAX);\n\t\tauto _adj = this->adj;\n\t\tbool flag = true;\n\t\tflag = _rule4(_adj);\n\t\tthis->adj = _adj;\n\t\tclean_graph(INT_MAX);\n\n\t\t_readEdgesFromGraph();\n\t\t_calculerVertexMaxDegree();\n\t\t_calculerVertexMinDegree();\n\n\t\tthis->numVertices = this->adj.size();\n\n\t\treturn adj.size();\n\t}\n\n\tint clean_graph()\n\t{\n\t\tint16_t added_to_cover = 0;\n\t\tbool flag = true;\n\t\tbool flag2 = true;\n\t\twhile (flag2)\n\t\t{\n\t\t\tif (flag2)\n\t\t\t{\n\t\t\t\tflag = true;\n\t\t\t\twhile (flag)\n\t\t\t\t{\n\t\t\t\t\tflag = _rule1(this->adj);\n\t\t\t\t\tflag = _rule2(this->adj, added_to_cover);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tflag2 = _rule3(this->adj, added_to_cover);\n\t\t}\n\n\t\tthis->_zeroVertexDegree.clear();\n\t\t_updateVertexDegree();\n\t\tnumVertices = adj.size();\n\t\treturn added_to_cover;\n\t}\n\n\tint clean_graph(int16_t k)\n\t{\n\t\tint16_t added_to_cover = 0;\n\t\tbool flag = true;\n\t\tbool flag2 = true;\n\t\twhile (flag2)\n\t\t{\n\t\t\tif (flag2)\n\t\t\t{\n\t\t\t\tflag = true;\n\t\t\t\twhile (flag)\n\t\t\t\t{\n\t\t\t\t\tflag = _rule1(this->adj);\n\t\t\t\t\tflag = _rule2(this->adj, added_to_cover);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tflag2 = _rule3(this->adj, added_to_cover);\n\t\t}\n\n\t\tthis->_zeroVertexDegree.clear();\n\t\t_updateVertexDegree();\n\t\tnumVertices = adj.size();\n\t\treturn added_to_cover;\n\t}\n\n\tint clean_graph2()\n\t{\n\t\tint16_t added_to_cover = 0;\n\t\tbool flag = true;\n\n\t\twhile (flag)\n\t\t{\n\t\t\tflag = _rule1(this->adj);\n\t\t\tflag = _rule2(this->adj, added_to_cover);\n\t\t}\n\n\t\tthis->_zeroVertexDegree.clear();\n\t\t_updateVertexDegree();\n\t\treturn added_to_cover;\n\t}\n\n\tstd::set<int16_t> cover()\n\t{\n\t\treturn _cover;\n\t}\n\n\tstd::set<int16_t> postProcessing()\n\t{\n\t\t//_cover.insert(-2);\n\t\tauto it = _cover.begin();\n\t\tset<int16_t> unfolded_vertices;\n\t\t/*If a vertex is negative, it means it was folded, then we look up\n\t\t\tthe foldedVertices to unfold it*/\n\t\twhile (it != _cover.end())\n\t\t{\n\t\t\t/*It finds folded vertices (u'), which are negatives,\n\t\t\t\tif (u') is included in the cover, then, vertices\n\t\t\t\tu and v must be present in the cover*/\n\t\t\tif (*it < 0)\n\t\t\t{\n\t\t\t\tunfolded_vertices.insert(foldedVertices[*it].v);\n\t\t\t\tunfolded_vertices.insert(foldedVertices[*it].w);\n\t\t\t\tfoldedVertices.erase(*it);\n\t\t\t\t_cover.erase(*it);\n\t\t\t\tit = _cover.begin();\n\t\t\t}\n\t\t\telse\n\t\t\t\tit++;\n\t\t}\n\n\t\t/* ******************************************************** */\n\n\t\t/* if (u') was not included in the cover, then u must be\n\t\t\tpresent in the cover */\n\t\tauto i = foldedVertices.begin();\n\t\twhile (i != foldedVertices.end())\n\t\t{\n\t\t\tunfolded_vertices.insert(i->second.u);\n\t\t\tfoldedVertices.erase(i->first);\n\t\t\ti = foldedVertices.begin();\n\t\t}\n\n\t\t/* ******************************************************** */\n\n\t\t/*Build minimum vertex cover*/\n\t\tauto j = unfolded_vertices.begin();\n\n\t\twhile (j != unfolded_vertices.end())\n\t\t{\n\t\t\tthis->_cover.insert(*j);\n\t\t\tj++;\n\t\t}\n\t\treturn _cover;\n\t}\n\n\tint max_k()\n\t{\n\t\tif (!adj.empty())\n\t\t{\n\t\t\t//double mxDegrees = list[idsMax[0]].size();\n\t\t\t//return floor((double)list.size() / (1.0 + (1.0 / (mxDegrees))));\n\t\t\treturn ceil((double)adj.size() / (1.0 + (1.0 / (max))));\n\t\t}\n\t\treturn 0;\n\t}\n\n\tint min_k()\n\t{\n\t\tif (!adj.empty())\n\t\t{\n\t\t\t//\tdouble mxDegrees = list[idsMax[0]].size();\n\t\t\t//\tdouble minDegrees = list[idsMin[0]].size();\n\t\t\t//return floor((double)list.size() / (1.0 + (mxDegrees / minDegrees)));\n\t\t\treturn floor((double)adj.size() / (1.0 + ((double)max / (double)min)));\n\t\t}\n\t\treturn 0;\n\t}\n\n\tint getNumEdges()\n\t{\n\t\treturn this->numEdges;\n\t}\n\n\tvoid build_graph(int SIZE, int p)\n\t{\n\n\t\tbuild(SIZE, p);\n\t}\n\n\tvoid print_edges(std::ofstream &file)\n\t{\n\t\tauto it = adj.begin();\n\n\t\t/*Fix this to not printing duplicated edges*/\n\n\t\twhile (!adj.empty())\n\t\t{\n\t\t\tauto it2 = (*it).second.begin();\n\t\t\twhile (!(*it).second.empty())\n\t\t\t{\n\t\t\t\tfile << (*it).first << \"\\t\" << *it2;\n\t\t\t\tint v = (*it).first;\n\t\t\t\tint w = *it2;\n\t\t\t\tremoveEdge(v, w);\n\n\t\t\t\tif (!(*it).second.empty())\n\t\t\t\t\tfile << endl;\n\n\t\t\t\tit2 = (*it).second.begin();\n\t\t\t}\n\t\t\tremoveZeroVertexDegree();\n\t\t\tif (!adj.empty())\n\t\t\t\tfile << endl;\n\n\t\t\tit = adj.begin();\n\t\t}\n\t}\n\n\tint find_vi(std::vector<int> &vi)\n\t{\n\t\tauto adj_cpy = adj;\n\t\tsize_t sum = 0;\n\t\tsize_t MAX = max;\n\t\tsize_t edges_p = numEdges;\n\n\t\tauto findMax = [&adj_cpy]()\n\t\t{\n\t\t\tint max = 0;\n\n\t\t\tfor (auto &[key, val] : adj_cpy)\n\t\t\t{\n\t\t\t\tif (val.size() > max)\n\t\t\t\t\tmax = val.size();\n\t\t\t}\n\t\t\treturn max;\n\t\t};\n\n\t\tauto iterator = adj_cpy.begin();\n\t\twhile (iterator != adj_cpy.end())\n\t\t{\n\t\t\tint key = iterator->first;\n\t\t\tauto &neigbours = iterator->second;\n\t\t\tif (neigbours.size() == MAX)\n\t\t\t{\n\t\t\t\tvi.push_back(key);\n\t\t\t\tsum += neigbours.size();\n\n\t\t\t\tedges_p -= neigbours.size();\n\n\t\t\t\tfor (auto &neighbour : neigbours)\n\t\t\t\t{\n\t\t\t\t\tadj_cpy[neighbour].erase(key);\n\t\t\t\t}\n\t\t\t\tadj_cpy.erase(key);\n\t\t\t\tMAX = findMax();\n\n\t\t\t\tif (sum >= numEdges)\n\t\t\t\t\tbreak;\n\n\t\t\t\titerator = adj_cpy.begin();\n\t\t\t}\n\t\t\telse\n\t\t\t\titerator++;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tint DegLB()\n\t{\n\t\tif (adj.size() == 0)\n\t\t\treturn 0;\n\n\t\tstd::vector<int> vi;\n\t\tauto adj_cpy = adj;\n\t\tsize_t sum = 0;\n\n\t\tsize_t edges_p = numEdges;\n\n\t\tauto findMaxVertex = [&adj_cpy]()\n\t\t{\n\t\t\tint maxdeg_v = adj_cpy.begin()->second.size();\n\n\t\t\tfor (auto &[key, val] : adj_cpy)\n\t\t\t{\n\t\t\t\tif (val.size() > adj_cpy[maxdeg_v].size())\n\t\t\t\t\tmaxdeg_v = key;\n\t\t\t}\n\t\t\treturn maxdeg_v;\n\t\t};\n\n\t\tauto iterator = adj_cpy.begin();\n\t\twhile (true)\n\t\t{\n\t\t\t//todo : use priority queue to maintain max degree guy\n\t\t\tint max_v = findMaxVertex();\n\n\t\t\tvi.push_back(max_v);\n\t\t\tsum += adj[max_v].size(); //neigbours.size();\n\n\t\t\tedges_p -= adj_cpy[max_v].size();\n\n\t\t\tfor (auto &neighbour : adj_cpy[max_v])\n\t\t\t{\n\t\t\t\tadj_cpy[neighbour].erase(max_v);\n\t\t\t}\n\t\t\tadj_cpy.erase(max_v);\n\n\t\t\tif (sum >= numEdges)\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (edges_p <= 0 || adj_cpy.size() == 0)\n\t\t\treturn vi.size();\n\n\t\tint nextv = findMaxVertex();\n\n\t\tif (adj[nextv].size() == 0)\n\t\t\treturn vi.size();\n\n\t\treturn vi.size() + edges_p / adj[nextv].size();\n\t}\n\n\tint antiColoringLB()\n\t{\n\t\tif (adj.size() == 0)\n\t\t\treturn 0;\n\n\t\tmap<int, int> colors;\n\t\tint maxcol = 0;\n\n\t\tfor (auto it = adj.begin(); it != adj.end(); ++it)\n\t\t{\n\t\t\tint v = it->first;\n\t\t\tset<int> taken;\n\t\t\tfor (auto it2 = adj.begin(); it2 != adj.end(); ++it2)\n\t\t\t{\n\t\t\t\tint w = it2->first;\n\t\t\t\tif (w >= v)\n\t\t\t\t\tbreak;\n\t\t\t\tif (!adj[v].contains(w) && colors.contains(w))\n\t\t\t\t{\n\t\t\t\t\ttaken.insert(colors[w]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < adj.size(); ++i)\n\t\t\t{\n\t\t\t\tif (!taken.contains(i))\n\t\t\t\t{\n\t\t\t\t\t//cout<<\"color \"<<v<<\" with \"<<i<<endl;\n\t\t\t\t\tcolors[v] = i;\n\t\t\t\t\tmaxcol = std::max(maxcol, i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint isub = maxcol + 1;\n\t\treturn adj.size() - isub;\n\t}\n\n\t/*\t\tTEMPORARY\t\t*/\n\n\tstd::vector<std::vector<int16_t>> ADJ_MATRIX()\n\t{\n\n\t\tint16_t N = adj.size();\n\t\tstd::vector<std::vector<int16_t>> tmp(N, std::vector<int16_t>(N, 0));\n\n\t\tauto it = adj.begin();\n\t\twhile (it != adj.end())\n\t\t{\n\t\t\tauto jt = it->second.begin();\n\t\t\twhile (jt != it->second.end())\n\t\t\t{\n\t\t\t\ttmp[it->first][*jt] = 1;\n\t\t\t\tjt++;\n\t\t\t}\n\t\t\tit++;\n\t\t}\n\t\treturn tmp;\n\t}\n\n\tstd::vector<int16_t> DEGREE()\n\t{\n\t\tstd::vector<int16_t> tmp;\n\n\t\tauto it = adj.cbegin();\n\n\t\twhile (it != adj.cend())\n\t\t{\n\t\t\ttmp.push_back(it->second.size());\n\t\t\tit++;\n\t\t}\n\t\treturn tmp;\n\t}\n\n\t//Graph(const Graph &) = default;\n\t//Graph(Graph &&) = default;\n\t//Graph &operator=(const Graph &) = default;\n\t//Graph &operator=(Graph &&) = default;\n\t//virtual ~Graph() = default;\n#ifdef MPI_ENABLED\n\t/*\n\ttemplate <class Archive>\n\tvoid serialize(Archive &ar)\n\t{\n\t\tar(max,\n\t\t   min,\n\t\t   idsMax,\n\t\t   idsMin,\n\t\t   adj,\n\t\t   rows,\n\t\t   vertexDegree,\n\t\t   _zeroVertexDegree,\n\t\t   foldedVertices,\n\t\t   _cover,\n\t\t   numEdges,\n\t\t   numVertices);\n\t} */\n\n\ttemplate <class Archive>\n\tvoid serialize(Archive &ar, const unsigned int version)\n\t{\n\t\tar &max;\n\t\tar &min;\n\t\tar &idsMax;\n\t\tar &idsMin;\n\t\tar &adj;\n\t\t//ar &rows;\n\t\tar &vertexDegree;\n\t\t//ar &_zeroVertexDegree;\n\t\tar &foldedVertices;\n\t\tar &_cover;\n\t\tar &numEdges;\n\t\tar &numVertices;\n\t}\n#endif\n\n\tstd::map<int16_t, std::set<int16_t>> adj; /*Adjacency list*/\n\nprivate:\n\tint max;\t\t\t\t\t\t\t\t /*Highest degree within graph*/\n\tint min;\t\t\t\t\t\t\t\t /*Lowest degree within graph*/\n\tstd::vector<int16_t> idsMax;\t\t\t /*Stores the positions of max degree vertices within the adjacency adj*/\n\tstd::vector<int16_t> idsMin;\t\t\t /*same as above but for min degree*/\n\tstd::set<int16_t> rows;\t\t\t\t\t /*Temporary variable to store*/\n\tstd::map<int16_t, int16_t> vertexDegree; /*list of vertices with their corresponding\n\t\t\t\t\t\t\t\t\tnumber of edges*/\n\tstd::set<int16_t> _zeroVertexDegree;\t /*List of vertices with zero degree*/\n\n\tstd::map<int16_t, FoldedVertices> foldedVertices;\n\tstd::set<int16_t> _cover;\n\n\tint numEdges;\t //number of edges\n\tint numVertices; //number of vertices\n};\n\n#endif", "meta": {"hexsha": "56ae735f1fac58651def87511ed9b97e7e25fad7", "size": 26270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Graph.hpp", "max_stars_repo_name": "rapastranac/gempba", "max_stars_repo_head_hexsha": "3b50f9809af95e2001615ab704bb055db68f50c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T13:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T13:52:06.000Z", "max_issues_repo_path": "include/Graph.hpp", "max_issues_repo_name": "rapastranac/gempba", "max_issues_repo_head_hexsha": "3b50f9809af95e2001615ab704bb055db68f50c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-31T14:58:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-07T01:55:06.000Z", "max_forks_repo_path": "include/Graph.hpp", "max_forks_repo_name": "rapastranac/gempba", "max_forks_repo_head_hexsha": "3b50f9809af95e2001615ab704bb055db68f50c8", "max_forks_repo_licenses": ["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.7176656151, "max_line_length": 116, "alphanum_fraction": 0.6023601066, "num_tokens": 8065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.06187598702110207, "lm_q1q2_score": 0.024046123976617404}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2014 - 2022 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 \"ibamr/IBMethod.h\"\n#include \"ibamr/PenaltyIBMethod.h\"\n\n#include \"ibtk/IBTK_CHKERRQ.h\"\n#include \"ibtk/IBTK_MPI.h\"\n#include \"ibtk/LData.h\"\n#include \"ibtk/LDataManager.h\"\n#include \"ibtk/LInitStrategy.h\"\n#include \"ibtk/LSiloDataWriter.h\"\n#include \"ibtk/ibtk_utilities.h\"\n\n#include \"BasePatchHierarchy.h\"\n#include \"BasePatchLevel.h\"\n#include \"GriddingAlgorithm.h\"\n#include \"IntVector.h\"\n#include \"PatchHierarchy.h\"\n#include \"tbox/Database.h\"\n#include \"tbox/MathUtilities.h\"\n#include \"tbox/PIO.h\"\n#include \"tbox/Pointer.h\"\n#include \"tbox/RestartManager.h\"\n#include \"tbox/Utilities.h\"\n\n#include \"petscvec.h\"\n\n#include \"ibamr/namespaces.h\" // IWYU pragma: keep\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <boost/multi_array.hpp>\nIBTK_ENABLE_EXTRA_WARNINGS\n\n#include <algorithm>\n#include <cmath>\n#include <ostream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace SAMRAI\n{\nnamespace xfer\n{\ntemplate <int DIM>\nclass CoarsenSchedule;\ntemplate <int DIM>\nclass RefineSchedule;\n} // namespace xfer\n} // namespace SAMRAI\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\nnamespace IBAMR\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\nnamespace\n{\n// Version of PenaltyIBMethod restart file data.\nstatic const int PENALTY_IB_METHOD_VERSION = 1;\n} // namespace\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nPenaltyIBMethod::PenaltyIBMethod(std::string object_name, Pointer<Database> input_db, bool register_for_restart)\n    : IBMethod(std::move(object_name), input_db, register_for_restart)\n{\n    // NOTE: Parent class constructor registers class with the restart manager, sets object\n    // name.\n\n    // Initialize object with data read from the input and restart databases.\n    bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (from_restart) getFromRestart();\n    if (input_db) getFromInput(input_db, from_restart);\n    return;\n} // PenaltyIBMethod\n\nvoid\nPenaltyIBMethod::preprocessIntegrateData(double current_time, double new_time, int num_cycles)\n{\n    IBMethod::preprocessIntegrateData(current_time, new_time, num_cycles);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Look-up or allocate Lagangian data.\n    d_K_data.resize(finest_ln + 1);\n    d_M_data.resize(finest_ln + 1);\n    d_Y_current_data.resize(finest_ln + 1);\n    d_Y_new_data.resize(finest_ln + 1);\n    d_V_current_data.resize(finest_ln + 1);\n    d_V_new_data.resize(finest_ln + 1);\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        d_K_data[ln] = d_l_data_manager->getLData(\"K\", ln);\n        d_M_data[ln] = d_l_data_manager->getLData(\"M\", ln);\n        d_Y_current_data[ln] = d_l_data_manager->getLData(\"Y\", ln);\n        d_Y_new_data[ln] = d_l_data_manager->createLData(\"Y_new\", ln, NDIM);\n        d_V_current_data[ln] = d_l_data_manager->getLData(\"V\", ln);\n        d_V_new_data[ln] = d_l_data_manager->createLData(\"V_new\", ln, NDIM);\n\n        // Initialize Y^{n+1} and V^{n+1} to equal Y^{n} and V^{n}.\n        int ierr;\n        ierr = VecCopy(d_Y_current_data[ln]->getVec(), d_Y_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n        ierr = VecCopy(d_V_current_data[ln]->getVec(), d_V_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n    }\n    return;\n} // preprocessIntegrateData\n\nvoid\nPenaltyIBMethod::postprocessIntegrateData(double current_time, double new_time, int num_cycles)\n{\n    IBMethod::postprocessIntegrateData(current_time, new_time, num_cycles);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Reset time-dependent Lagrangian data.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        int ierr;\n        ierr = VecSwap(d_Y_current_data[ln]->getVec(), d_Y_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n        ierr = VecSwap(d_V_current_data[ln]->getVec(), d_V_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n    }\n\n    // Deallocate Lagrangian scratch data.\n    d_K_data.clear();\n    d_M_data.clear();\n    d_Y_current_data.clear();\n    d_Y_new_data.clear();\n    d_V_current_data.clear();\n    d_V_new_data.clear();\n    return;\n} // postprocessIntegrateData\n\nvoid\nPenaltyIBMethod::forwardEulerStep(const double current_time, const double new_time)\n{\n    IBMethod::forwardEulerStep(current_time, new_time);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = new_time - current_time;\n\n    // Update the values of Y^{n+1} and V^{n+1} using forward Euler.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        const double* const K = d_K_data[ln]->getLocalFormArray()->data();\n        const double* const M = d_M_data[ln]->getLocalFormArray()->data();\n        const double* const X = d_X_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const Y = d_Y_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const V = d_V_current_data[ln]->getLocalFormVecArray()->data();\n        double* const Y_new = d_Y_new_data[ln]->getLocalFormVecArray()->data();\n        double* const V_new = d_V_new_data[ln]->getLocalFormVecArray()->data();\n        const unsigned int n_local = d_X_current_data[ln]->getLocalNodeCount();\n        unsigned int i, d;\n        for (i = 0; i < n_local; ++i)\n        {\n            for (d = 0; d < NDIM; ++d)\n            {\n                Y_new[NDIM * i + d] = Y[NDIM * i + d] + dt * V[NDIM * i + d];\n                V_new[NDIM * i + d] = V[NDIM * i + d] + dt * (-K[i] * (Y[NDIM * i + d] - X[NDIM * i + d]) / M[i] +\n                                                              d_gravitational_acceleration[d]);\n            }\n        }\n    }\n    return;\n} // eulerStep\n\nvoid\nPenaltyIBMethod::midpointStep(const double current_time, const double new_time)\n{\n    IBMethod::midpointStep(current_time, new_time);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = new_time - current_time;\n\n    // Update the values of Y^{n+1} and V^{n+1} using the midpoint rule.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        const double* const K = d_K_data[ln]->getLocalFormArray()->data();\n        const double* const M = d_M_data[ln]->getLocalFormArray()->data();\n        const double* const X = d_X_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const Y = d_Y_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const V = d_V_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const X_new = d_X_new_data[ln]->getLocalFormVecArray()->data();\n        double* const Y_new = d_Y_new_data[ln]->getLocalFormVecArray()->data();\n        double* const V_new = d_V_new_data[ln]->getLocalFormVecArray()->data();\n        const unsigned int n_local = d_X_current_data[ln]->getLocalNodeCount();\n        unsigned int i, d;\n        double X_half, Y_half, V_half;\n        for (i = 0; i < n_local; ++i)\n        {\n            for (d = 0; d < NDIM; ++d)\n            {\n                X_half = 0.5 * (X[NDIM * i + d] + X_new[NDIM * i + d]);\n                Y_half = 0.5 * (Y[NDIM * i + d] + Y_new[NDIM * i + d]);\n                V_half = 0.5 * (V[NDIM * i + d] + V_new[NDIM * i + d]);\n                Y_new[NDIM * i + d] = Y[NDIM * i + d] + dt * V_half;\n                V_new[NDIM * i + d] =\n                    V[NDIM * i + d] + dt * (-K[i] * (Y_half - X_half) / M[i] + d_gravitational_acceleration[d]);\n            }\n        }\n    }\n    return;\n} // midpointStep\n\nvoid\nPenaltyIBMethod::trapezoidalStep(const double current_time, const double new_time)\n{\n    IBMethod::trapezoidalStep(current_time, new_time);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = new_time - current_time;\n\n    // Update the values of Y^{n+1} and V^{n+1} using the trapezoidal rule.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        const double* const K = d_K_data[ln]->getLocalFormArray()->data();\n        const double* const M = d_M_data[ln]->getLocalFormArray()->data();\n        const double* const X = d_X_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const Y = d_Y_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const V = d_V_current_data[ln]->getLocalFormVecArray()->data();\n        const double* const X_new = d_X_new_data[ln]->getLocalFormVecArray()->data();\n        double* const Y_new = d_Y_new_data[ln]->getLocalFormVecArray()->data();\n        double* const V_new = d_V_new_data[ln]->getLocalFormVecArray()->data();\n        const unsigned int n_local = d_X_current_data[ln]->getLocalNodeCount();\n        unsigned int i, d;\n        double X_half, Y_half, V_half;\n        for (i = 0; i < n_local; ++i)\n        {\n            for (d = 0; d < NDIM; ++d)\n            {\n                X_half = 0.5 * (X[NDIM * i + d] + X_new[NDIM * i + d]);\n                Y_half = 0.5 * (Y[NDIM * i + d] + Y_new[NDIM * i + d]);\n                V_half = 0.5 * (V[NDIM * i + d] + V_new[NDIM * i + d]);\n                Y_new[NDIM * i + d] = Y[NDIM * i + d] + dt * V_half;\n                V_new[NDIM * i + d] =\n                    V[NDIM * i + d] + dt * (-K[i] * (Y_half - X_half) / M[i] + d_gravitational_acceleration[d]);\n            }\n        }\n    }\n    return;\n} // trapezoidalStep\n\nvoid\nPenaltyIBMethod::computeLagrangianForce(const double data_time)\n{\n    IBMethod::computeLagrangianForce(data_time);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    double max_displacement = 0.0;\n\n    if (IBTK::rel_equal_eps(data_time, d_current_time))\n    {\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n            double* const F = d_F_current_data[ln]->getLocalFormVecArray()->data();\n            const double* const K = d_K_data[ln]->getLocalFormArray()->data();\n            const double* const X = d_X_current_data[ln]->getLocalFormVecArray()->data();\n            const double* const Y = d_Y_current_data[ln]->getLocalFormVecArray()->data();\n            const unsigned int n_local = d_X_current_data[ln]->getLocalNodeCount();\n            for (unsigned int i = 0; i < n_local; ++i)\n            {\n                double dX = 0.0;\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    F[NDIM * i + d] += K[i] * (Y[NDIM * i + d] - X[NDIM * i + d]);\n                    dX += (Y[NDIM * i + d] - X[NDIM * i + d]) * (Y[NDIM * i + d] - X[NDIM * i + d]);\n                }\n                dX = std::sqrt(dX);\n                max_displacement = std::max(max_displacement, dX);\n            }\n        }\n        d_F_current_needs_ghost_fill = true;\n    }\n    else if (IBTK::rel_equal_eps(data_time, d_half_time))\n    {\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n            double* const F = d_F_half_data[ln]->getLocalFormVecArray()->data();\n            const double* const K = d_K_data[ln]->getLocalFormArray()->data();\n            const double* const X = d_X_current_data[ln]->getLocalFormVecArray()->data();\n            const double* const Y = d_Y_current_data[ln]->getLocalFormVecArray()->data();\n            const double* const X_new = d_X_new_data[ln]->getLocalFormVecArray()->data();\n            const double* const Y_new = d_Y_new_data[ln]->getLocalFormVecArray()->data();\n            const unsigned int n_local = d_X_current_data[ln]->getLocalNodeCount();\n            for (unsigned int i = 0; i < n_local; ++i)\n            {\n                double dX = 0.0;\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    const double X_half = 0.5 * (X[NDIM * i + d] + X_new[NDIM * i + d]);\n                    const double Y_half = 0.5 * (Y[NDIM * i + d] + Y_new[NDIM * i + d]);\n                    F[NDIM * i + d] += K[i] * (Y_half - X_half);\n                    dX += (Y_half - X_half) * (Y_half - X_half);\n                }\n                dX = std::sqrt(dX);\n                max_displacement = std::max(max_displacement, dX);\n            }\n        }\n        d_F_half_needs_ghost_fill = true;\n    }\n    else if (IBTK::rel_equal_eps(data_time, d_new_time))\n    {\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n            double* const F = d_F_new_data[ln]->getLocalFormVecArray()->data();\n            const double* const K = d_K_data[ln]->getLocalFormArray()->data();\n            const double* const X = d_X_new_data[ln]->getLocalFormVecArray()->data();\n            const double* const Y = d_Y_new_data[ln]->getLocalFormVecArray()->data();\n            const unsigned int n_local = d_X_current_data[ln]->getLocalNodeCount();\n            for (unsigned int i = 0; i < n_local; ++i)\n            {\n                double dX = 0.0;\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    F[NDIM * i + d] += K[i] * (Y[NDIM * i + d] - X[NDIM * i + d]);\n                    dX += (Y[NDIM * i + d] - X[NDIM * i + d]) * (Y[NDIM * i + d] - X[NDIM * i + d]);\n                }\n                dX = std::sqrt(dX);\n                max_displacement = std::max(max_displacement, dX);\n            }\n        }\n        d_F_new_needs_ghost_fill = true;\n    }\n\n    if (d_do_log)\n    {\n        max_displacement = IBTK_MPI::maxReduction(max_displacement);\n        plog << d_object_name << \"::computeLagrangianForce(): maximum point displacement: \" << max_displacement << \"\\n\";\n    }\n    return;\n} // computeLagrangianForce\n\nvoid\nPenaltyIBMethod::initializePatchHierarchy(Pointer<PatchHierarchy<NDIM> > hierarchy,\n                                          Pointer<GriddingAlgorithm<NDIM> > gridding_alg,\n                                          int u_data_idx,\n                                          const std::vector<Pointer<CoarsenSchedule<NDIM> > >& u_synch_scheds,\n                                          const std::vector<Pointer<RefineSchedule<NDIM> > >& u_ghost_fill_scheds,\n                                          int integrator_step,\n                                          double init_data_time,\n                                          bool initial_time)\n{\n    IBMethod::initializePatchHierarchy(hierarchy,\n                                       gridding_alg,\n                                       u_data_idx,\n                                       u_synch_scheds,\n                                       u_ghost_fill_scheds,\n                                       integrator_step,\n                                       init_data_time,\n                                       initial_time);\n\n    // Initialize velocity and position data objects for massive points.\n    if (initial_time)\n    {\n        const int coarsest_ln = 0;\n        const int finest_ln = d_hierarchy->getFinestLevelNumber();\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n\n            Pointer<LData> X_data = d_l_data_manager->getLData(LDataManager::POSN_DATA_NAME, ln);\n            Pointer<LData> U_data = d_l_data_manager->getLData(LDataManager::VEL_DATA_NAME, ln);\n            Pointer<LData> Y_data = d_l_data_manager->createLData(\"Y\", ln, NDIM, /*manage_data*/ true);\n            Pointer<LData> V_data = d_l_data_manager->createLData(\"V\", ln, NDIM, /*manage_data*/ true);\n\n            if (d_silo_writer)\n            {\n                d_silo_writer->registerVariableData(\"Y\", Y_data, ln);\n            }\n\n            // Set initial conditions.\n            int ierr;\n            ierr = VecCopy(X_data->getVec(), Y_data->getVec());\n            IBTK_CHKERRQ(ierr);\n            ierr = VecCopy(U_data->getVec(), V_data->getVec());\n            IBTK_CHKERRQ(ierr);\n        }\n    }\n    return;\n} // initializePatchHierarchy\n\nvoid\nPenaltyIBMethod::initializeLevelData(Pointer<BasePatchHierarchy<NDIM> > hierarchy,\n                                     int level_number,\n                                     double init_data_time,\n                                     bool can_be_refined,\n                                     bool initial_time,\n                                     Pointer<BasePatchLevel<NDIM> > old_level,\n                                     bool allocate_data)\n{\n    IBMethod::initializeLevelData(\n        hierarchy, level_number, init_data_time, can_be_refined, initial_time, old_level, allocate_data);\n\n    if (initial_time && d_l_data_manager->levelContainsLagrangianData(level_number))\n    {\n        // Initialize Mass and Spring constant data.\n        // Position and Velocity will be copied later.\n        Pointer<LData> M_data = d_l_data_manager->createLData(\"M\",\n                                                              level_number,\n                                                              1,\n                                                              /*manage_data*/ true);\n        Pointer<LData> K_data = d_l_data_manager->createLData(\"K\",\n                                                              level_number,\n                                                              1,\n                                                              /*manage_data*/ true);\n        static const int global_index_offset = 0;\n        static const int local_index_offset = 0;\n        d_l_initializer->initializeMassDataOnPatchLevel(global_index_offset,\n                                                        local_index_offset,\n                                                        M_data,\n                                                        K_data,\n                                                        hierarchy,\n                                                        level_number,\n                                                        init_data_time,\n                                                        can_be_refined,\n                                                        initial_time,\n                                                        d_l_data_manager);\n\n        if (d_silo_writer)\n        {\n            d_silo_writer->registerVariableData(\"M\", M_data, level_number);\n        }\n    }\n    return;\n}\n\nvoid\nPenaltyIBMethod::putToDatabase(Pointer<Database> db)\n{\n    IBMethod::putToDatabase(db);\n\n    db->putInteger(\"PENALTY_IB_METHOD_VERSION\", PENALTY_IB_METHOD_VERSION);\n    db->putDoubleArray(\"d_gravitational_acceleration\", &d_gravitational_acceleration[0], NDIM);\n    return;\n} // putToDatabase\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\nPenaltyIBMethod::getFromInput(Pointer<Database> db, bool is_from_restart)\n{\n    if (!is_from_restart)\n    {\n        if (db->keyExists(\"gravitational_acceleration\"))\n        {\n            db->getDoubleArray(\"gravitational_acceleration\", &d_gravitational_acceleration[0], NDIM);\n        }\n        else\n        {\n            TBOX_WARNING(d_object_name << \":  \"\n                                       << \"Using penalty-IB method but key data \"\n                                          \"`gravitational_acceleration' not found in input.\");\n        }\n    }\n    return;\n} // getFromInput\n\nvoid\nPenaltyIBMethod::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(d_object_name << \":  Restart database corresponding to \" << d_object_name\n                                 << \" not found in restart file.\" << std::endl);\n    }\n    int ver = db->getInteger(\"PENALTY_IB_METHOD_VERSION\");\n    if (ver != PENALTY_IB_METHOD_VERSION)\n    {\n        TBOX_ERROR(d_object_name << \":  Restart file version different than class version.\" << std::endl);\n    }\n    db->getDoubleArray(\"d_gravitational_acceleration\", &d_gravitational_acceleration[0], NDIM);\n    return;\n} // getFromRestart\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n} // namespace IBAMR\n\n//////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "b4b8bbc6ed492411732eb30c16ad1f7361ca7926", "size": 21341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IB/PenaltyIBMethod.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "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/IB/PenaltyIBMethod.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T17:54:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-30T17:54:49.000Z", "max_forks_repo_path": "src/IB/PenaltyIBMethod.cpp", "max_forks_repo_name": "akashdhruv/IBAMR", "max_forks_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T03:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T03:40:20.000Z", "avg_line_length": 40.9616122841, "max_line_length": 120, "alphanum_fraction": 0.5542383206, "num_tokens": 5258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.04958902070158601, "lm_q1q2_score": 0.02382646711238834}}
{"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_OSWALD_HH\n#define DUNE_GDT_OPERATORS_OSWALD_HH\n\n#include <vector>\n#include <set>\n#include <limits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/stuff/aliases.hh>\n#include <dune/stuff/common/vector.hh>\n#include <dune/stuff/common/float_cmp.hh>\n#include <dune/stuff/common/print.hh>\n#include <dune/stuff/common/ranges.hh>\n#include <dune/stuff/grid/walker.hh>\n\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/playground/spaces/dg/fem.hh>\n#include <dune/gdt/playground/spaces/block.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Operators {\n\n\n// forward\ntemplate< class GridViewImp, class FieldImp = double >\nclass OswaldInterpolation;\n\n\nnamespace internal {\n\n\ntemplate< class GridViewImp, class FieldImp >\nclass OswaldInterpolationTraits\n{\npublic:\n  typedef OswaldInterpolation< GridViewImp, FieldImp > derived_type;\n  typedef GridViewImp                                  GridViewType;\n  typedef FieldImp                                     FieldType;\n};\n\n\n} // namespace internal\n\n\ntemplate< class GridViewImp, class FieldImp >\nclass OswaldInterpolation\n  : public OperatorInterface< internal::OswaldInterpolationTraits< GridViewImp, FieldImp > >\n{\npublic:\n  typedef internal::OswaldInterpolationTraits< GridViewImp, FieldImp > Traits;\n  typedef typename Traits::GridViewType GridViewType;\n  typedef typename Traits::FieldType    FieldType;\n  static const size_t                   dimDomain = GridViewType::dimension;\n\n  OswaldInterpolation(const GridViewType& grd_vw, const bool zero_boundary = true)\n    : grid_view_(grd_vw)\n    , zero_boundary_(zero_boundary)\n  {}\n\n  template< class SGP, class SV, class RGP, class RV >\n  void apply(const ConstDiscreteFunction< Spaces::DG::FemBased< SGP, 1, FieldType, 1, 1 >, SV >&\n                source,\n             DiscreteFunction< Spaces::DG::FemBased< RGP, 1, FieldType, 1, 1 >, RV >&\n                range) const\n  {\n    apply_dg_fem(source, range);\n  }\n\n  template< class SGP, class SV, class RGP, class RV >\n  void apply(const ConstDiscreteFunction< Spaces::Block< Spaces::DG::FemBased< SGP, 1, FieldType, 1, 1 > >, SV >&\n                source,\n             DiscreteFunction< Spaces::Block< Spaces::DG::FemBased< RGP, 1, FieldType, 1, 1 > >, RV >&\n                range) const\n  {\n    apply_dg_fem(source, range);\n  }\n\nprivate:\n  template< class SourceType, class RangeType >\n  void apply_dg_fem(const SourceType& source, RangeType& range) const\n  {\n    // data structures we need\n    // * a map from a global vertex index to global DoF indices\n    //   given a vertex, one obtains a set of all global DoF ids, which are associated with this vertex\n    std::map< size_t, std::set< size_t > > global_vertex_id_to_global_DoF_id_map;\n    // * a map from a global DoF index to the global index of its associated vertex\n    std::vector< size_t > global_DoF_id_to_global_vertex_id_map(source.space().mapper().size());\n    // * a set to hold the global id of all boundary vertices\n    std::set< size_t > boundary_vertices;\n\n    const auto entity_it_end = grid_view_.template end< 0 >();\n    //walk the grid to create the maps explained above and to find the boundary vertices\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 size_t num_vertices = boost::numeric_cast< size_t >(entity.template count< dimDomain >());\n      const auto basis = source.space().base_function_set(entity);\n      if (basis.size() != num_vertices)\n        DUNE_THROW(Dune::Stuff::Exceptions::internal_error, \"basis.size() = \" << basis.size());\n\n      //loop over all vertices of the entitity, to find their associated global DoF indices\n      for (size_t local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {\n        const auto vertex_ptr = entity.template subEntity< dimDomain >(boost::numeric_cast< int >(local_vertex_id));\n        const auto global_vertex_id = grid_view_.indexSet().index(*vertex_ptr);\n        const auto vertex = vertex_ptr->geometry().center();\n        // find the local basis function which corresponds to this vertex\n        const auto basis_values = basis.evaluate(entity.geometry().local(vertex));\n        if (basis_values.size() != num_vertices)\n          DUNE_THROW(Dune::Stuff::Exceptions::internal_error, \"basis_values.size() = \" << basis_values.size());\n        size_t ones = 0;\n        size_t zeros = 0;\n        size_t failures = 0;\n        size_t local_DoF_index = 0;\n        for (size_t ii = 0; ii < basis.size(); ++ii) {\n          if (std::abs(basis_values[ii][0] - 1.0) < 1e-14) {\n            local_DoF_index = ii;\n            ++ones;\n          } else if (std::abs(basis_values[ii][0] - 0.0) < 1e-14)\n            ++zeros;\n          else\n            ++failures;\n        }\n        if (ones != 1 || zeros != (basis.size() - 1) || failures > 0) {\n          std::stringstream ss;\n          ss << \"ones = \" << ones << \", zeros = \" << zeros << \", failures = \" << failures << \", num_vertices = \"\n             << num_vertices << \", entity \" << grid_view_.indexSet().index(entity)\n             << \", vertex \" << local_vertex_id << \": [ \" << vertex << \"], \";\n          Stuff::Common::print(basis_values, \"basis_values\", ss);\n          DUNE_THROW(Dune::Stuff::Exceptions::internal_error, ss.str());\n        }\n        // now we know that the local DoF index of this vertex is ii\n        const size_t global_DoF_index = source.space().mapper().mapToGlobal(entity, local_DoF_index);\n        global_DoF_id_to_global_vertex_id_map[global_DoF_index] = global_vertex_id;\n        global_vertex_id_to_global_DoF_id_map[global_vertex_id].insert(global_DoF_index);\n      } //loop over all vertices\n\n      if (zero_boundary_) {\n        // in order to determine the boundary vertices, we need to\n        // loop over all intersections\n        const auto intersectionEndIt = grid_view_.iend(entity);\n        for (auto intersectionIt = grid_view_.ibegin(entity); intersectionIt != intersectionEndIt; ++intersectionIt) {\n          const auto& intersection = *intersectionIt;\n          if (intersection.boundary() && !intersection.neighbor()) {\n            const auto& intersection_geometry = intersection.geometry();\n            for (auto local_intersection_corner_id : DSC::valueRange(intersection_geometry.corners())) {\n              const auto global_intersection_corner = intersection_geometry.corner(local_intersection_corner_id);\n              // now, we need to find the entity's vertex this intersection's corner point equals to, so we\n              // loop over all vertices of the entity\n              for (size_t local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {\n                const auto vertex_ptr = entity.template subEntity< dimDomain >(boost::numeric_cast< int >(local_vertex_id));\n                const auto global_vertex_id = grid_view_.indexSet().index(*vertex_ptr);\n                const auto vertex = vertex_ptr->geometry().center();\n                if (Stuff::Common::FloatCmp::eq(global_intersection_corner, vertex))\n                  boundary_vertices.insert(global_vertex_id);\n              } // loop over all vertices of the entity\n            } //loop over all intersection corners\n          } // if (intersection.boundary() && !intersection.neighbor())\n        } // loop over all intersections\n      } // if(zero_boundary)\n    } //walk the grid for the first time\n\n    // walk the grid for the second time\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 num_vertices = boost::numeric_cast< size_t >(entity.template count< dimDomain >());\n      // get the local functions\n      const auto local_source = source.local_discrete_function(entity);\n      const auto& local_source_DoF_vector = local_source->vector();\n\n      // * loop over all local DoFs\n      for (size_t local_DoF_id = 0; local_DoF_id < num_vertices; ++local_DoF_id) {\n      const size_t global_DoF_index = source.space().mapper().mapToGlobal(entity, local_DoF_id);\n      const size_t global_vertex_id = global_DoF_id_to_global_vertex_id_map[global_DoF_index];\n        // if we are on the domain boundary\n        if (zero_boundary_ && boundary_vertices.count(global_vertex_id)) {\n          // set the dof to zero (we have dirichlet zero)\n          range.vector().set_entry(global_DoF_index, FieldType(0));\n        } else {\n          // do the oswald projection\n          const size_t num_DoFS_per_vertex = global_vertex_id_to_global_DoF_id_map[global_vertex_id].size();\n          // * get the source DoF\n          const FieldType source_DoF_value = local_source_DoF_vector.get(local_DoF_id);\n          // * and add it to all target DoFs\n          for (size_t target_global_DoF_id : global_vertex_id_to_global_DoF_id_map[global_vertex_id])\n            range.vector().add_to_entry(target_global_DoF_id, source_DoF_value / num_DoFS_per_vertex);\n        } // if (boundary_vertices.find(global_vertex_id))\n      } // loop over all local DoFs\n    } // walk the grid for the second time\n  } // ... apply(...)\n\n\n  const GridViewType& grid_view_;\n  const bool zero_boundary_;\n}; // class OswaldInterpolation\n\n\n} // namespace Operators\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_OPERATORS_OSWALD_HH\n", "meta": {"hexsha": "475baa8ca12cba892b03f514c5ee31d94fe2d159", "size": 9587, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/operators/oswaldinterpolation.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/oswaldinterpolation.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/oswaldinterpolation.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": 45.6523809524, "max_line_length": 124, "alphanum_fraction": 0.6714300615, "num_tokens": 2311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.05419873249666699, "lm_q1q2_score": 0.023729478709245345}}
{"text": "#ifndef GENTLE_BOOST_ENSEMBLE\n#define GENTLE_BOOST_ENSEMBLE\n\n/* Implements a Gentle Boost classification ensemble */\n\n#include <type_traits>\n#include <memory>\n#include <limits>\n#include <vector>\n#include <exception>\n\n#include <armadillo>\n\n#include \"types.hpp\"\n#include \"regression_stump.hpp\"\n\n\n/*!\n    Implements a Gentle Boost ensemble (Friedmann et al.).\n    It inherits std::enable_shared_from_this because multiple RegressionStump\n    objects will contain a std::shared_ptr to this object. Therefore a\n    shared_from_this() shared_ptr is passed to avoid double deletion.\n!*/\nclass GentleBoostEnsemble: public std::enable_shared_from_this<GentleBoostEnsemble> {\n\nprivate:\n    Matrix _x;\n    Vector _y;\n    Vector _x_weights;\n    std::vector<std::shared_ptr<RegressionStump>> _base_learners;\n    int _iteration = 0;\n    double _weight = 1.0;\n\n    std::shared_ptr<GentleBoostEnsemble> get_ptr ( );\n\npublic:\n    // max number of weak learners (max number of boosting iterations)\n    static int _T;\n    // misc\n    std::vector<double> _max;\n\n    // constructors\n    GentleBoostEnsemble ( );\n    GentleBoostEnsemble ( const Matrix&, const Vector& );\n    GentleBoostEnsemble ( const GentleBoostEnsemble& );\n    ~GentleBoostEnsemble ( );\n\n    // misc\n    const bool create_base_learners ( );\n\n\n    // setters\n    void set_x ( const Matrix& x ) { _x = x; }\n    void set_y ( const Vector& y ) { _y = y; }\n    void set_x_weights ( const Vector& x_weights ) { _x_weights = x_weights; }\n    void set_base_learners ( const std::vector<std::shared_ptr<RegressionStump>> base_learners) { _base_learners = base_learners; }\n    void set_iteration ( const int& iteration ) { _iteration = iteration; }\n    void set_weight ( const double& weight ) { _weight = weight; }\n\n    //getters\n    const Matrix& get_x ( ) const { return _x; }\n    Matrix get_x_copy ( ) const { return _x; }\n    Matrix& get_x_nonconst ( ) { return _x; }\n    const Vector& get_y ( ) const  { return _y; }\n    Matrix get_y_copy ( ) const { return _y; }\n    Vector& get_y_nonconst ( ) { return _y; }\n    const Vector& get_x_weights ( ) const { return _x_weights; }\n    Vector get_x_weights_copy ( ) const { return _x_weights; }\n    Vector& get_x_weights_nonconst ( ) { return _x_weights; }\n    const std::vector<std::shared_ptr<RegressionStump>>& get_base_learners ( ) const { return _base_learners; }\n    const int& get_iteration ( ) const { return _iteration; }\n    const double& get_weight ( ) const { return _weight; }\n\n    // training functionalities\n    friend void RegressionStump::train ( );\n    friend void RegressionStump::retrain_on_last ( double, int );\n    void train_single ( );\n    void train_single_no_update ( );\n    void train ( const int& );\n    void retrain_current ( int );\n    void train_full ( Matrix&, Vector&, Matrix&, Vector& );\n\n    inline void update_weights ( const Vector& );\n    void update_and_normalize_weights();\n    inline void reset_weights_uniform ( );\n    inline void normalize_weights ( );\n    void update_max ( );\n\n    //prediction functionalities\n    friend inline Vector RegressionStump::predict ( ) const;\n    friend inline Vector RegressionStump::predict ( const Matrix& ) const;\n    friend inline Vector RegressionStump::compute_margins ( ) const;\n    friend inline Vector RegressionStump::compute_margins ( const Matrix&, const Vector& ) const;\n    Vector predict_real ( ) const;\n    Vector predict_real ( const Matrix& ) const;\n    Vector predict_discrete ( ) const;\n    Vector predict_discrete ( const Matrix& ) const;\n    Vector compute_margins ( ) const;\n    Vector compute_margins ( const Matrix&, const Vector& ) const;\n    double compute_error_rate ( const Matrix&, const Vector& ) const;\n    void report_errors ( Matrix&, Vector&, Matrix&, Vector& ) const;\n\n};\n\n\n/*!\n    Normalize the weights such that they all sum up to one\n!*/\ninline void GentleBoostEnsemble::normalize_weights ( ) {\n    _x_weights /= sum(_x_weights);\n}\n\n/*!\n    Updates the weights by the negative of the margins\n!*/\ninline void GentleBoostEnsemble::update_weights ( const Vector& arg ) {\n    Vector exponents = arma::exp(-arg);\n    _x_weights = _x_weights % exponents;\n}\n\n/*!\n    Resets the weights so that they form a uniform probability distribution\n!*/\ninline void GentleBoostEnsemble::reset_weights_uniform ( ) {\n    _x_weights = 1.0/ (double)_x_weights.n_elem * arma::ones<Vector>(_x_weights.n_elem);\n}\n\n\n#endif //GENTLE_BOOST_ENSEMBLE\n", "meta": {"hexsha": "1f87755f56d1e44b43d4e85880ed2f6c07359464", "size": 4421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gentle_boost_ensemble.hpp", "max_stars_repo_name": "ninoarsov/collaborative_bagging_of_gentle_boost_ensembles", "max_stars_repo_head_hexsha": "6c67794f545f615c795baccc4ac97e5b508363a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gentle_boost_ensemble.hpp", "max_issues_repo_name": "ninoarsov/collaborative_bagging_of_gentle_boost_ensembles", "max_issues_repo_head_hexsha": "6c67794f545f615c795baccc4ac97e5b508363a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gentle_boost_ensemble.hpp", "max_forks_repo_name": "ninoarsov/collaborative_bagging_of_gentle_boost_ensembles", "max_forks_repo_head_hexsha": "6c67794f545f615c795baccc4ac97e5b508363a3", "max_forks_repo_licenses": ["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.0076923077, "max_line_length": 131, "alphanum_fraction": 0.701425017, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04742587772156364, "lm_q1q2_score": 0.02371293886078182}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <set>\n#include <gsl/gsl_rng.h>\n#include <boost/tuple/tuple.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"types.hpp\"\n#include \"randvars2.hpp\"\n#include \"bgl_graph_info.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n\nstatic const size_t npos = -1; //defined in string::npos, for find() not found\n\n/*\n * Generate the graph to run simulation on.\n * Make a preference file that itm can then use to generate the graph\n * Prefernece file has special values, see comments below.\n *\n*/\n\nvoid gen_graph(user_input *i,\n\t       unsigned\t   seed){\n\n  int syscheck = 0; //return value for system calls\n\n  /* Makes gt-itm not crash.*/\n  fprintf(stderr, \"Exporting MALLOC_CHECK_=0\\n\");\n  syscheck = system(\"export MALLOC_CHECK_=0\"); //makes itm not crash\n  if (syscheck != 0){\n    fprintf(stderr, \"Export Command Failed!\");\n    exit(1);\n  }\n\n  /* create a file to use for prefrences for gt-itm*/\n  ofstream pref;\n  pref.open(\"pref\");\n\n  /* \n   * geo: flat random graph \n   * hier: N-level hierarchial graph\n   * ts: transit-stub graph\n   * \n   * Fromat:\n   * <method> [above] <# of graphs> <seed> [optional]\n  */\n\n  pref << \"geo 1 \" << seed << endl; // if needed can change this so it isnt flat\n\n  /*\n   * Graph Parameters:\n   * n: number of nodes in graph\n   * scale: one-sided dimension of space in which nodes are distributed\n   * edgemethod:\n   *   1) Waxman 1\n   *   2) Waxman 2\n   *   3) Pure Random \n   *   4) Door-Leslie\n   *   5) Exponential \n   *   6) Locality\n   * alpha: random graph parameter (0 =< alpha =< 1.0)\n   * beta: \" \" (0 <= beta)\n   * gamma: \" \" (0 <= gamma)\n   * geo: <n> <scale> <edgemethod> <alpha> [<beta><gamma>]\n  */\n  char preferences[255];\n  DEBUGE(\"verts: %d : edge: %f\\n\", i->get_vertices(), i->get_edgechance());\n  sprintf(preferences, \"%d %d %d %f\\n\", \n  i->get_vertices(), 10, 3, i->get_edgechance());\n  \n  pref << preferences;\n  pref.close();\n\n  /* Run itm on pref file created above. */\n  fprintf(stderr,\"Calling ../bin/itm pref\\n\");  \n  syscheck = system(\"../bin/itm pref\");  \n  if (syscheck != 0){\n    fprintf(stderr, \"itm not found or failed to run!\\n\");\n    exit(1);\n  }\n\n  /*convert gb file to readable alternate format*/\n  fprintf(stderr,\"Calling ../bin/sgb2alt pref-0.gb pref.alt\\n\");\n  syscheck = system(\"../bin/sgb2alt pref-0.gb pref.alt\");\n  if (syscheck == 1){\n    fprintf(stderr, \"sgb2alt failed to run, not found, incompatable file!\\n\");\n    exit(1);\n  }\n\n}\n\n/*\n * Convert the graph from the alternative format to a dot format\n * that can easily be loaded into BGL as a graph.\n * This function will have some hard coding variables that may need to be\n * changed at a later date.\n*/\n\nGraph con_graph(UI in){\n  ifstream alt;\n  alt.open(\"pref.alt\");\n  if (!alt){\n    fprintf(stderr, \"Error: pref.alt does not Exist\\n\");\n  }\n\n  gsl_rng_env_setup(); //set up our random\n  r = gsl_rng_alloc(gsl_rng_mt19937);\n  gsl_rng_set(r, in->get_seed()); //use seed\n\n  string line, v1, v2, weight, whitespace;\n  int V1, V2;\n  int num_verts = 1; //max of V1, V2.\n  vector <pair< pair <int,int>, pair <int, long> > > edges;\n  while(getline(alt,line) != NULL){\n    if (line.find(\"EDGES\") != npos){\n      while(getline(alt,line) != NULL){\n        istringstream stream(line);\n        stream >> v1;\n        stream >> v2;\n        stream >> weight; //throw away itm weight, generate our own.\n        V1 = atoi(v1.c_str());\n        V2 = atoi(v2.c_str());\n        /*\n         * This code will determine the number of vertices that are used\n         * in the graph, it will do this by checking if either number found\n         * is larger than a previous one, this will find the number of\n         * vertices under the assumption that gt-itm will generate fully\n         * connected graphs, and therefore, the largest value will be the\n         * the highest value seen.  It will also be offset by 1, because\n         * gt-itm starts nodes at 0. This is compensated later in the code.\n         */\n        if (V1 > num_verts || V2 > num_verts){\n          if (V1 > V2){\n            num_verts = V1;\n          } else {\n            num_verts = V2;\n          }\n        }\n        /* generate weights and capacities for this link*/\n        long weight;\n        long minw = in->get_minw();\n        long maxw = in->get_maxw();\n        long maxc = in->get_maxcap(); // Use maxcap() for core links.\n        if (minw == maxw){\n          weight = minw; //if they are set to same value, all links have\n        } else {\n          weight = UniformD(minw,maxw);  //otherwise, distributed\n        }\n        /* make them into pairs, then through int a vector.*/\n        pair<int,int> edge (V1,V2);\n        pair <int, long> w_c (weight,maxc);\n        pair < pair <int, int> , pair <int, long> > edge_prop (edge,w_c);\n        edges.push_back(edge_prop);\n      }\n    }\n  }\n\n  num_verts += 1;  //above code doesnt take into account gt-itm starts at 0\n  Graph g(num_verts); //generate graph with num_verts nodes.\n  //convert from alternative format to dot format for graphviz.\n  for (int itor = 0; itor < num_verts; ++itor){\n    //set the name for each node to its index\n    g[itor].name = lexical_cast<string>(itor);\n  }\n  \n  //add the edges to the graph now.\n  for(vector< pair< pair < int, int>, pair <int, long> > >::iterator \n    it = edges.begin(); it != edges.end(); ++it) {\n    //let ele = be ((u,v),(w,c)) for both edge and properties\n    pair< pair < int, int>, pair <int, long> > ele = (*it);\n    edge_info prop; //set the properties to add to the graph with the edge.\n    prop.weight = ele.second.first;\n    prop.capacity = ele.second.second;\n    pair<edge_desc, bool> res; // make sure that it added the edge.\n    res = add_edge(ele.first.first,ele.first.second, prop, g);\n    if (res.second == false){\n      DEBUGE(\"Failed to add edge to graph!\\n\");\n      DEBUGE(\"Edge in question: %d-%ld\\n\",\n              ele.first.first,ele.second.second);\n      exit(3);\n    }\n  }\n\n  /* now open up the dot file and write the graph to it */\n  ofstream dot(\"graph.dot\");\n  write_graphviz(dot, g, \n    boost::make_label_writer(boost::get(&vert_info::name, g)),\n    make_edge_writer(boost::get(&edge_info::weight,g), \n    boost::get(&edge_info::capacity,g)));\n\n  DEBUGE(\"Converting dot file to pdf format -- RUN WAS A:  \");\n  errno = system(\"dot -Tpdf graph.dot -o graph.pdf &> /dev/null\");\n  if (errno == 0){\n    DEBUGE(\"SUCCESS!\\n\");\n  } else {\n    DEBUGE(\"FAILURE!\\n\");\n  }\n\n  return g;\n}\n", "meta": {"hexsha": "b1c2e07d7a7d110e8c405dd83060e4d8466b53f4", "size": 6626, "ext": "cc", "lang": "C++", "max_stars_repo_path": "working_dir/file_format.cc", "max_stars_repo_name": "lthurlow/Genome-Simulation-Platform", "max_stars_repo_head_hexsha": "d701ef207d26015db40b69954c5168b9327d9f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "working_dir/file_format.cc", "max_issues_repo_name": "lthurlow/Genome-Simulation-Platform", "max_issues_repo_head_hexsha": "d701ef207d26015db40b69954c5168b9327d9f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "working_dir/file_format.cc", "max_forks_repo_name": "lthurlow/Genome-Simulation-Platform", "max_forks_repo_head_hexsha": "d701ef207d26015db40b69954c5168b9327d9f62", "max_forks_repo_licenses": ["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.2547169811, "max_line_length": 80, "alphanum_fraction": 0.6172653184, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04813676923902951, "lm_q1q2_score": 0.023692346711380072}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <NTL/BasicThreadPool.h>\n\n#include \"recryption.h\"\n#include \"EncryptedArray.h\"\n#include \"EvalMap.h\"\n#include \"powerful.h\"\n#include \"CtPtrs.h\"\n#include \"intraSlot.h\"\n#include \"norms.h\"\n#include \"sample.h\"\n#include \"debugging.h\"\n#include \"fhe_stats.h\"\n\nNTL_CLIENT\n\n\n#ifdef DEBUG_PRINTOUT\n#include \"debugging.h\"\nlong printFlag = FLAG_PRINT_VEC;\n#endif\n\n/************************ Some local functions ***********************/\n/*********************************************************************/\n\nstatic void\ncheckCriticalValue(const vector<ZZX>& zzParts, const DoubleCRT& sKey,\n                   const RecryptData& rcData, long q);\n\nstatic void\ncheckRecryptBounds(const vector<ZZX>& zzParts, const DoubleCRT& sKey,\n                   const FHEcontext& context, long q);\n\nstatic void\ncheckRecryptBounds_v(const vector<ZZX>& v, const DoubleCRT& sKey,\n                     const FHEcontext& context, long q);\n\n// Return in poly a polynomial with X^i encoded in all the slots\nstatic void x2iInSlots(ZZX& poly, long i,\n\t\t       vector<ZZX>& xVec, const EncryptedArray& ea)\n{\n  xVec.resize(ea.size());\n  ZZX x2i = ZZX(i,1);\n  for (long j=0; j<(long)xVec.size(); j++) xVec[j] = x2i;\n  ea.encode(poly, xVec);\n}\n\n// Make every entry of vec divisible by p2e by adding/subtracting q, while\n// keeping the added multiples small.  Specifically, for q = 1 mod p2e and any\n// integer z can be made divisible by p2e via z' = z + v*q, with |v| <= p2e/2.\n\nstatic void newMakeDivisible(ZZX& poly, long p2e, long q, \n                          const FHEcontext& context, ZZX& vpoly)\n{\n  if (p2e == 1) {\n    vpoly = 0;\n    return;\n  }\n\n  helib::assertTrue<helib::InvalidArgument>(q > 0l, \"q must be positive\");\n  helib::assertTrue<helib::InvalidArgument>(p2e > 0l, \"p2e must be positive\");\n\n  helib::assertEq<helib::InvalidArgument>(q % p2e, 1l, \"q must equal 1 modulo p2e\");\n\n\n\n  long p = context.zMStar.getP();\n\n  const RecryptData& rcData = context.rcData;\n  const PowerfulDCRT& p2d_conv = *rcData.p2dConv;\n\n\n  Vec<ZZ> pwrfl;\n  p2d_conv.ZZXtoPowerful(pwrfl, poly);\n\n\n#ifdef DEBUG_PRINTOUT\n  Vec<ZZ> vvec(INIT_SIZE, pwrfl.length());\n#endif\n  \n  for (long i: range(pwrfl.length())) {\n    ZZ& z = pwrfl[i];\n    long u, v;\n\n    // What to add to z to make it divisible by p2e?\n    long zMod = rem(z, p2e); // zMod is in [0,p2e-1]\n    // NOTE: this makes sure we get a truly balanced remainder\n    if (zMod > p2e/2 || (p==2 && zMod == p2e/2 && RandomBnd(2))) { \n      // randomize so that v has expected value 0\n      zMod = p2e - zMod;\n    }\n    else {\n      // need to add a negative number\n      zMod = -zMod;\n    }\n    v = zMod;\n    z += to_ZZ(q)*v; // make z divisible by p2e\n\n    if (rem(z,p2e) != 0) { // sanity check\n      cerr << \"**error: original z[\"<<i<<\"]=\" << (z-(to_ZZ(q)*v))\n\t   << std::dec << \", p^e=\"<<p2e << endl;\n      cerr << \"z' = z + \"<<v<<\"*q = \"<<z<<endl;\n      exit(1);\n    }\n\n#ifdef DEBUG_PRINTOUT\n    vvec[i] = v;\n#endif\n  }\n\n  p2d_conv.powerfulToZZX(poly, pwrfl);\n\n#ifdef DEBUG_PRINTOUT\n  p2d_conv.powerfulToZZX(vpoly, vvec);\n#endif\n  \n}\n\n/*********************************************************************/\n/*********************************************************************/\n\nRecryptData::~RecryptData()\n{\n  if (alMod!=NULL)     delete alMod;\n  if (ea!=NULL)        delete ea;\n  if (firstMap!=NULL)  delete firstMap;\n  if (secondMap!=NULL) delete secondMap;\n  if (p2dConv!=NULL)   delete p2dConv;\n}\n\n\n/**\n * Summary of Appendix A from https://ia.cr/2014/873 (version from 2019):\n * Assume that we already chosen e, e' and t.\n * \n * Based in this analysis, we need\n *    (1) (f*p^{e'} + 2*p^r+2))*B <= p^e/2\n * where B is a certain high-probability bound and f is a certain\n * fudge factor.\n *\n **/\n\n// the routine compute_fudge is used to correct for the fact that\n// the v-coeffs are not quite uniform\n\nstatic \ndouble compute_fudge(long p2ePrime, long p2e)\n{\n  double eps = 0;\n\n  if (p2ePrime > 1) {\n\n\n      if (p2ePrime%2 == 0) {\n         eps = 1/fsquare(p2ePrime);\n\n\t // The exact variance in this case is at most the variance\n         // of a random variable that is distributed over\n         //    -N..+N\n         // where N = 2^{e'}/2. \n         // Each endpoint occurs with probability 1/(4*N),\n         // and the remaining values each occur with the same probability \n         // 1/(2*N)\n\n         // This variance is exactly computed as\n\t //    (N^2)/3 + 1/6 = ((N^2)/3)*(1 + 1/(2*N^2)), where N = 2^{e'}/2\n\t // So the std dev is at most\n\t //    N/sqrt(3)*(1 + 1/(4*N^2))\n\n      }\n      else{\n         eps = 1/double(p2e);\n\n         // We are computing X + Y mod p^{e'}, where\n         // X and Y are independent.\n         // Y is uniformly distributed over \n         //    -floor(p^{r}/2)..floor(p^{r}/2)\n         // X is distributed over \n         //    -floor(p^e/2)-1..floor(p^e/2)+1,\n         // where each endpoint occurs with probability 1 / (2*(p^e+1)),\n         // and the remaining p^e values are equally likely\n\n         // The variance in this case is bounded by \n         //   (N^2)/3*(1-eps) + (N^2)*eps = (N^2)/3*(1+2*eps),\n         //       where N = p^{e'}/2 and eps < 1/p^e\n         // So the std dev is bounded by\n         //    N/sqrt(3)*sqrt(1+2*eps) <= N/sqrt(3)*(1+eps)   \n\n      }\n\n  }\n\n  return 1 + eps;\n}\n\nlong RecryptData::setAE(long& e, long& ePrime,\n                    const FHEcontext& context, long targetWeight)\n{\n  bool default_target=false;\n  if (targetWeight<=0) {\n    targetWeight = RecryptData::defSkHwt;\n    default_target=true;\n  }\n\n  double coeff_bound = context.boundForRecryption(targetWeight);\n  // coeff_bound is ultimately a high prob bound on |w0+w1*s|,\n  // the coeffs of w0, w1 are chosen uniformly on [-1/2,1/2]\n\n  long p = context.zMStar.getP();\n  long p2r = context.alMod.getPPowR();\n  long r = context.alMod.getR();\n  long frstTerm = 2*p2r+2; \n\n  long e_bnd = 0;\n  long p2e_bnd = 1;\n  while (p2e_bnd <= ((1L << 30)-2)/p) { // NOTE: this avoids overflow\n    e_bnd++;\n    p2e_bnd *= p;\n  }\n  // e_bnd is largest e such that p^e+1 < 2^30\n\n  // Start with the smallest e s.t. p^e/2 >= frstTerm*coeff_bound\n  ePrime = 0;\n  e = r+1;\n  while (e <= e_bnd && power_long(p, e) < frstTerm*coeff_bound*2) \n    e++;\n\n  if (e > e_bnd) Error(\"setAE: cannot find suitable e\");\n\n  //long ePrimeTry = r+1;\n  long ePrimeTry = 1;\n\n  while (ePrimeTry <= e_bnd) {\n    long p2ePrimeTry = power_long(p, ePrimeTry);\n    //long eTry = ePrimeTry+1; \n    long eTry = max(r+1, ePrimeTry+1);\n    while (eTry <= e_bnd && eTry-ePrimeTry < e-ePrime) {\n      long p2eTry = power_long(p, eTry);\n      double fudge = compute_fudge(p2ePrimeTry, p2eTry);\n      if (p2eTry >= (p2ePrimeTry*fudge+frstTerm)*coeff_bound*2) break;\n\n      eTry++;\n    }\n\n    if (eTry <= e_bnd && eTry-ePrimeTry < e-ePrime) {\n      e = eTry;\n      ePrime = ePrimeTry;\n    }\n\n    ePrimeTry++;\n  } \n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"RecryptData::setAE(): e=\"<<e<<\", e'=\"<<ePrime\n       << endl;\n#endif\n  return targetWeight;\n}\n\n\nbool RecryptData::operator==(const RecryptData& other) const\n{\n  if (mvec != other.mvec) return false;\n  if (skHwt != other.skHwt) return false;\n\n  return true;\n}\n\n\n\n// The main method\nvoid RecryptData::init(const FHEcontext& context, const Vec<long>& mvec_,\n                  bool enableThick, long t, bool build_cache_, bool minimal)\n{\n  if (alMod != NULL) { // were we called for a second time?\n    cerr << \"@Warning: multiple calls to RecryptData::init\\n\";\n    return;\n  }\n  helib::assertEq(computeProd(mvec_), (long)context.zMStar.getM(), \"Cyclotomic polynomial mismatch\"); // sanity check\n\n  // Record the arguments to this function\n  mvec = mvec_;\n  build_cache = build_cache_;\n\n  bool mvec_ok = true;\n  for (long i: range(mvec.length())) {\n    Vec<Pair<long,long>> factors;\n    factorize(factors, mvec[i]);\n    if (factors.length() > 1) mvec_ok = false;\n  }\n\n  if (!mvec_ok) {\n    Warning(\"prime power factorization recommended for bootstrapping\");\n  }\n\n\n  skHwt = setAE(e, ePrime, context, t);\n  long p = context.zMStar.getP();\n  long r = context.alMod.getR();\n\n  // First part of Bootstrapping works wrt plaintext space p^{r'}\n  alMod = new PAlgebraMod(context.zMStar, e-ePrime+r);\n  ea = new EncryptedArray(context, *alMod);\n         // Polynomial defaults to F0, PAlgebraMod explicitly given\n\n  p2dConv = new PowerfulDCRT(context, mvec);\n\n  if (!enableThick) return;\n\n  // Initialize the linear polynomial for unpacking the slots\n  zz_pBak bak; bak.save(); ea->getAlMod().restoreContext();\n  long nslots = ea->size();\n  long d = ea->getDegree();\n\n  const Mat<zz_p>& CBi=ea->getDerived(PA_zz_p()).getNormalBasisMatrixInverse();\n\n  vector<ZZX> LM;\n  LM.resize(d);\n  for (long i = 0; i < d; i++) // prepare the linear polynomial\n    LM[i] = rep(CBi[i][0]);\n\n  vector<ZZX> C; \n  ea->buildLinPolyCoeffs(C, LM); // \"build\" the linear polynomial\n\n  unpackSlotEncoding.resize(d);  // encode the coefficients\n\n  for (long j = 0; j < d; j++) {\n    vector<ZZX> v(nslots);\n    for (long k = 0; k < nslots; k++) v[k] = C[j];\n    ea->encode(unpackSlotEncoding[j], v);\n  }\n  firstMap = new EvalMap(*ea, minimal, mvec, true, build_cache);\n  secondMap = new EvalMap(*context.ea, minimal, mvec, false, build_cache);\n}\n\n/********************************************************************/\n/********************************************************************/\n\n// Extract digits from fully packed slots\nvoid extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime,\n\t\t\t const vector<ZZX>& unpackSlotEncoding);\n\n// Extract digits from unpacked slots\nvoid extractDigitsThin(Ctxt& ctxt, long botHigh, long r, long ePrime);\n\n// bootstrap a ciphertext to reduce noise\nvoid FHEPubKey::reCrypt(Ctxt &ctxt)\n{\n  FHE_TIMER_START;\n\n  // Some sanity checks for dummy ciphertext\n  long ptxtSpace = ctxt.getPtxtSpace();\n  if (ctxt.isEmpty()) return;\n  if (ctxt.parts.size()==1 && ctxt.parts[0].skHandle.isOne()) {\n    // Dummy encryption, just ensure that it is reduced mod p\n    ZZX poly = to_ZZX(ctxt.parts[0]);\n    for (long i=0; i<poly.rep.length(); i++)\n      poly[i] = to_ZZ( rem(poly[i],ptxtSpace) );\n    poly.normalize();\n    ctxt.DummyEncrypt(poly);\n    return;\n  }\n\n  //OLD: assert(recryptKeyID>=0); // check that we have bootstrapping data\n  helib::assertTrue(recryptKeyID>=0l, \"No bootstrapping data\");\n\n  long p = getContext().zMStar.getP();\n  long r = getContext().alMod.getR();\n  long p2r = getContext().alMod.getPPowR();\n\n  long intFactor = ctxt.intFactor;\n\n  // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}.\n  const RecryptData& rcData = getContext().rcData;\n  long e = rcData.e;\n  long ePrime = rcData.ePrime;\n  long p2ePrime = power_long(p,ePrime);\n  long q = power_long(p,e)+1;\n  //OLD: assert(e>=r);\n  helib::assertTrue(e>=r, \"rcData.e must be at least alMod.r\");\n\n#ifdef DEBUG_PRINTOUT\n  cerr << \"reCrypt: p=\"<<p<<\", r=\"<<r<<\", e=\"<<e<<\" ePrime=\"<<ePrime\n       << \", q=\"<<q<<endl;\n  CheckCtxt(ctxt, \"init\");\n#endif\n\n  // can only bootstrap ciphertext with plaintext-space dividing p^r\n  //OLD: assert(p2r % ptxtSpace == 0);\n  helib::assertEq(p2r % ptxtSpace, 0l, \"ptxtSpace must divide p^r when bootstrapping\");\n\n  ctxt.dropSmallAndSpecialPrimes();\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after mod down\");\n#endif\n\n\n  FHE_NTIMER_START(AAA_preProcess);\n\n  // Make sure that this ciphertxt is in canonical form\n  if (!ctxt.inCanonicalForm()) ctxt.reLinearize();\n\n  // Mod-switch down if needed\n  IndexSet s = ctxt.getPrimeSet() / context.specialPrimes;\n  //OLD: assert(s <= context.ctxtPrimes);\n  helib::assertTrue(s <= context.ctxtPrimes,  \"prime set is messed up\");\n  if (s.card()>3) { // leave only first three ciphertext primes\n    long first = s.first();\n    IndexSet s3(first, first+2);\n    s.retain(s3); \n  }\n  ctxt.modDownToSet(s);\n\n  // key-switch to the bootstrapping key\n  ctxt.reLinearize(recryptKeyID);\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after key switching\");\n#endif\n\n  // \"raw mod-switch\" to the bootstrapping mosulus q=p^e+1.\n  vector<ZZX> zzParts; // the mod-switched parts, in ZZX format\n\n  double mfac = ctxt.getContext().zMStar.getNormBnd();\n  double noise_est = ctxt.rawModSwitch(zzParts, q) * mfac;\n  // noise_est is an upper bound on the L-infty norm of the scaled noise \n  // in the pwrfl basis\n  double noise_bnd = 0.66*p2r*ctxt.getContext().boundForRecryption();\n  // noise_bnd is the bound assumed in selecting the parameters \n  double noise_rat = noise_est/noise_bnd;\n\n  FHE_STATS_UPDATE(\"raw-mod-switch-noise\", noise_rat);\n\n  if (noise_rat > 1) {\n    Warning(\"rawModSwitch scaled noise exceeds bound: \" + std::to_string(noise_rat));\n  }\n\n\n  //OLD: assert(zzParts.size() == 2);\n  helib::assertEq(zzParts.size(), (std::size_t)2, \"Exactly 2 parts required for mod-switching in thin bootstrapping\");\n\n\n#ifdef DEBUG_PRINTOUT\n  if (dbgKey) {\n    checkRecryptBounds(zzParts, dbgKey->sKeys[recryptKeyID],\n                       ctxt.getContext(), q);\n  }\n#endif\n\n  vector<ZZX> v;\n  v.resize(2);\n\n\n  // Add multiples of q to make the zzParts divisible by p^{e'}\n  for (long i: range(2)) {\n    // make divisible by p^{e'}\n\n    newMakeDivisible(zzParts[i], p2ePrime, q, ctxt.getContext(), v[i]);\n\n  }\n\n#ifdef DEBUG_PRINTOUT\n  if (dbgKey) {\n    checkRecryptBounds_v(v, dbgKey->sKeys[recryptKeyID],\n\t\t       ctxt.getContext(), q);\n    checkCriticalValue(zzParts, dbgKey->sKeys[recryptKeyID],\n                       ctxt.getContext().rcData, q);\n  }\n#endif\n\n\n  for (long i: range(zzParts.size())) {\n    zzParts[i] /= p2ePrime;   // divide by p^{e'}\n  }\n\n  // NOTE: here we lose the intFactor associated with ctxt.\n  // We will restore it below.\n  ctxt = recryptEkey;\n\n  ctxt.multByConstant(zzParts[1]);\n  ctxt.addConstant(zzParts[0]);\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after preProcess\");\n#endif\n  FHE_NTIMER_STOP(AAA_preProcess);\n\n  // Move the powerful-basis coefficients to the plaintext slots\n  FHE_NTIMER_START(AAA_LinearTransform1);\n  ctxt.getContext().rcData.firstMap->apply(ctxt);\n  FHE_NTIMER_STOP(AAA_LinearTransform1);\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after LinearTransform1\");\n#endif\n\n  // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots)\n  FHE_NTIMER_START(AAA_extractDigitsPacked);\n  extractDigitsPacked(ctxt, e-ePrime, r, ePrime,\n\t\t      context.rcData.unpackSlotEncoding);\n  FHE_NTIMER_STOP(AAA_extractDigitsPacked);\n\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after extractDigitsPacked\");\n#endif\n\n  // Move the slots back to powerful-basis coefficients\n  FHE_NTIMER_START(AAA_LinearTransform2);\n  ctxt.getContext().rcData.secondMap->apply(ctxt);\n  FHE_NTIMER_STOP(AAA_LinearTransform2);\n\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after linearTransform2\");\n#endif\n\n  // restore intFactor\n  if (intFactor != 1)\n    ctxt.intFactor = MulMod(ctxt.intFactor, intFactor, ptxtSpace);\n}\n\n#ifdef FHE_BOOT_THREADS\n\n\n// Extract digits from fully packed slots, multithreaded version\nvoid extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime,\n\t\t\t const vector<ZZX>& unpackSlotEncoding)\n{\n  FHE_TIMER_START;\n\n  // Step 1: unpack the slots of ctxt\n  FHE_NTIMER_START(unpack);\n  ctxt.cleanUp();\n\n  // Apply the d automorphisms and store them in scratch area\n  long d = ctxt.getContext().zMStar.getOrdP();\n\n  vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt));\n  { // explicit scope to force all temporaries to be released\n    vector< shared_ptr<DoubleCRT> > coeff_vector;\n    vector<double> coeff_vector_sz;\n    coeff_vector.resize(d);\n    coeff_vector_sz.resize(d);\n\n    FHE_NTIMER_START(unpack1);\n    for (long i = 0; i < d; i++) {\n      coeff_vector[i] = shared_ptr<DoubleCRT>(new \n        DoubleCRT(unpackSlotEncoding[i], ctxt.getContext(), ctxt.getPrimeSet()) );\n      coeff_vector_sz[i] = \n        conv<double>( embeddingLargestCoeff(unpackSlotEncoding[i], \n                                            ctxt.getContext().zMStar) );\n    }\n    FHE_NTIMER_STOP(unpack1);\n\n    FHE_NTIMER_START(unpack2);\n    vector<Ctxt> frob(d, Ctxt(ZeroCtxtLike, ctxt));\n\n    NTL_EXEC_RANGE(d, first, last)\n    // FIXME: implement using hoisting!\n        for (long j = first; j < last; j++) { // process jth Frobenius \n          frob[j] = ctxt;\n          frob[j].frobeniusAutomorph(j);\n          frob[j].cleanUp();\n          // FIXME: not clear if we should call cleanUp here\n        }\n    NTL_EXEC_RANGE_END\n\n    FHE_NTIMER_STOP(unpack2);\n\n    FHE_NTIMER_START(unpack3);\n    Ctxt tmp1(ZeroCtxtLike, ctxt);\n    for (long i = 0; i < d; i++) {\n      for (long j = 0; j < d; j++) {\n        tmp1 = frob[j];\n        tmp1.multByConstant(*coeff_vector[mcMod(i+j, d)],\n                            coeff_vector_sz[mcMod(i+j, d)]);\n        unpacked[i] += tmp1;\n      }\n    }\n    FHE_NTIMER_STOP(unpack3);\n  }\n  FHE_NTIMER_STOP(unpack);\n\n  //#ifdef DEBUG_PRINTOUT\n  //  CheckCtxt(unpacked[0], \"after unpack\");\n  //#endif\n\n  NTL_EXEC_RANGE(d, first, last)\n  for (long i = first; i < last; i++) {\n    extractDigitsThin(unpacked[i], botHigh, r, ePrime);\n  }\n  NTL_EXEC_RANGE_END\n\n  //#ifdef DEBUG_PRINTOUT\n  //CheckCtxt(unpacked[0], \"before repack\");\n  //#endif\n\n  // Step 3: re-pack the slots\n  FHE_NTIMER_START(repack);\n  const EncryptedArray& ea2 = *ctxt.getContext().ea;\n  ZZX xInSlots;\n  vector<ZZX> xVec(ea2.size());\n  ctxt = unpacked[0];\n  for (long i=1; i<d; i++) {\n    x2iInSlots(xInSlots, i, xVec, ea2);\n    unpacked[i].multByConstant(xInSlots);\n    ctxt += unpacked[i];\n  }\n  FHE_NTIMER_STOP(repack);\n  //#ifdef DEBUG_PRINTOUT\n  //CheckCtxt(ctxt, \"after repack\");\n  //#endif\n}\n\n\n#else\n\n// Extract digits from fully packed slots\nvoid extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime,\n\t\t\t const vector<ZZX>& unpackSlotEncoding)\n{\n  FHE_TIMER_START;\n\n  // Step 1: unpack the slots of ctxt\n  FHE_NTIMER_START(unpack);\n  ctxt.cleanUp();\n\n  // Apply the d automorphisms and store them in scratch area\n  long d = ctxt.getContext().zMStar.getOrdP();\n\n  vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt));\n  { // explicit scope to force all temporaries to be released\n    vector< shared_ptr<DoubleCRT> > coeff_vector;\n    vector<double> coeff_vector_sz;\n    coeff_vector.resize(d);\n    coeff_vector_sz.resize(d);\n    for (long i = 0; i < d; i++) {\n      coeff_vector[i] = shared_ptr<DoubleCRT>(new \n        DoubleCRT(unpackSlotEncoding[i], ctxt.getContext(), ctxt.getPrimeSet()) );\n      coeff_vector_sz[i] = \n        conv<double>( embeddingLargestCoeff(unpackSlotEncoding[i], \n                                            ctxt.getContext().zMStar) );\n    }\n\n    Ctxt tmp1(ZeroCtxtLike, ctxt);\n    Ctxt tmp2(ZeroCtxtLike, ctxt);\n\n    // FIXME: implement using hoisting!\n    for (long j = 0; j < d; j++) { // process jth Frobenius \n      tmp1 = ctxt;\n      tmp1.frobeniusAutomorph(j);\n      tmp1.cleanUp();\n      // FIXME: not clear if we should call cleanUp here\n\n      for (long i = 0; i < d; i++) {\n        tmp2 = tmp1;\n        tmp2.multByConstant(*coeff_vector[mcMod(i+j, d)], \n                            coeff_vector_sz[mcMod(i+j, d)]);\n        unpacked[i] += tmp2;\n      }\n    }\n  }\n  FHE_NTIMER_STOP(unpack);\n\n  //#ifdef DEBUG_PRINTOUT\n  //  CheckCtxt(unpacked[0], \"after unpack\");\n  //#endif\n\n  for (long i=0; i<(long)unpacked.size(); i++) {\n    extractDigitsThin(unpacked[i], botHigh, r, ePrime); \n  }\n\n  //#ifdef DEBUG_PRINTOUT\n  //  CheckCtxt(unpacked[0], \"before repack\");\n  //#endif\n\n  // Step 3: re-pack the slots\n  FHE_NTIMER_START(repack);\n  const EncryptedArray& ea2 = *ctxt.getContext().ea;\n  ZZX xInSlots;\n  vector<ZZX> xVec(ea2.size());\n  ctxt = unpacked[0];\n  for (long i=1; i<d; i++) {\n    x2iInSlots(xInSlots, i, xVec, ea2);\n    unpacked[i].multByConstant(xInSlots);\n    ctxt += unpacked[i];\n  }\n  FHE_NTIMER_STOP(repack);\n}\n\n#endif\n\n\n// Use packed bootstrapping, so we can bootstrap all in just one go.\nvoid packedRecrypt(const CtPtrs& cPtrs,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea)\n{\n  FHEPubKey& pKey = (FHEPubKey&)cPtrs[0]->getPubKey();\n\n  // Allocate temporary ciphertexts for the recryption\n  int nPacked = divc(cPtrs.size(), ea.getDegree()); // ceil(totoalNum/d)\n  std::vector<Ctxt> cts(nPacked, Ctxt(pKey));\n\n  repack(CtPtrs_vectorCt(cts), cPtrs, ea);  // pack ciphertexts\n  //  cout << \"@\"<< lsize(cts)<<std::flush;\n  for (Ctxt& c: cts) {     // then recrypt them\n    c.reducePtxtSpace(2);  // we only have recryption data for binary ctxt\n    pKey.reCrypt(c);\n  }\n  unpack(cPtrs, CtPtrs_vectorCt(cts), ea, unpackConsts);\n}\n\n// recrypt all ctxt at level < belowLvl\nvoid packedRecrypt(const CtPtrs& array,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea, long belowLvl)\n{\n  std::vector<Ctxt*> v;\n  for (long i=0; i<array.size(); i++)\n    if ( array.isSet(i) && !array[i]->isEmpty()\n         && array[i]->bitCapacity()<belowLvl*(array[i]->getContext().BPL()) )\n      v.push_back(array[i]);\n  packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea);\n}\nvoid packedRecrypt(const CtPtrMat& m,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea, long belowLvl)\n{\n  std::vector<Ctxt*> v;\n  for (long i=0; i<m.size(); i++)\n    for (long j=0; j<m[i].size(); j++)\n      if ( m[i].isSet(j) && !m[i][j]->isEmpty()\n           && m[i][j]->bitCapacity()<belowLvl*(m[i][j]->getContext().BPL()) )\n        v.push_back(m[i][j]);\n  packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea);\n}\n\n\n\n//===================== Thin Bootstrapping stuff ==================\n\nThinRecryptData::~ThinRecryptData()\n{\n  if (coeffToSlot!=NULL)  delete coeffToSlot;\n  if (slotToCoeff!=NULL) delete slotToCoeff;\n}\n\n\n// This code was copied from RecryptData::init, and is mostly\n// the same, except for the linear-map-related stuff.\n// FIXME: There is really too much code (and data!) duplication here.\nvoid ThinRecryptData::init(const FHEcontext& context, const Vec<long>& mvec_,\n                      bool alsoThick, long t, bool build_cache_, bool minimal)\n{\n  RecryptData::init(context, mvec_, alsoThick, t, build_cache_, minimal);\n  coeffToSlot = new ThinEvalMap(*ea, minimal, mvec, true, build_cache);\n  slotToCoeff = new ThinEvalMap(*context.ea, minimal, mvec, false, build_cache);\n}\n\n\n// Extract digits from thinly packed slots\n\n\nlong fhe_force_chen_han = 0;\n\nvoid extractDigitsThin(Ctxt& ctxt, long botHigh, long r, long ePrime)\n{\n  FHE_TIMER_START;\n\n  Ctxt unpacked(ctxt);\n  unpacked.cleanUp();\n \n  vector<Ctxt> scratch;\n\n  long p = ctxt.getContext().zMStar.getP();\n  long p2r = power_long(p,r);\n  long topHigh = botHigh + r-1;\n\n\n  // degree Chen/Han technique is p^{bot-1}(p-1)r\n  // degree of basic technique is p^{bot-1}p^r, \n  //     or p^{bot-1}p^{r-1} if p==2, r > 1, and bot+r > 2\n\n  bool use_chen_han = false;\n  if (r > 1) {\n    double chen_han_cost = log(p-1) + log(r);\n    double basic_cost;\n    if (p == 2 && botHigh + r > 2)\n       basic_cost = (r-1)*log(p);\n    else\n       basic_cost = r*log(p);\n\n    //cerr << \"*** basic: \" << basic_cost << \"\\n\";\n    //cerr << \"*** chen/han: \" << chen_han_cost << \"\\n\";\n\n\n    double thresh = 1.5;\n    if (p == 2) thresh = 1.75;\n    // increasing thresh makes chen_han less likely to be chosen.\n    // For p == 2, the basic algorithm is just squaring, \n    // and so is a bit cheaper, so we raise thresh a bit.\n    // This is all a bit heuristic.\n\n    if (basic_cost > thresh*chen_han_cost)\n      use_chen_han = true;\n  }\n\n  if (fhe_force_chen_han > 0)\n    use_chen_han = true;\n  else if (fhe_force_chen_han < 0)\n    use_chen_han = false;\n\n\n  if (use_chen_han) {\n    // use Chen and Han technique\n\n    extendExtractDigits(scratch, unpacked, botHigh, r);\n\n#if 0\n    for (long i: range(scratch.size())) {\n      CheckCtxt(scratch[i], \"**\");\n    }\n#endif\n\n    for (long j = 0; j < botHigh; j++) {\n      unpacked -= scratch[j];\n      unpacked.divideByP();\n    }\n\n    if (p==2 && botHigh>0)   // For p==2, subtract also the previous bit\n      unpacked += scratch[botHigh-1];\n    unpacked.negate();\n\n    if (r>ePrime) {          // Add in digits from the bottom part, if any\n      long topLow = r-1 - ePrime;\n      Ctxt tmp = scratch[topLow];\n      for (long j=topLow-1; j>=0; --j) {\n\ttmp.multByP();\n\ttmp += scratch[j];\n      }\n      if (ePrime>0)\n\ttmp.multByP(ePrime); // multiply by p^e'\n      unpacked += tmp;\n    }\n    unpacked.reducePtxtSpace(p2r); // Our plaintext space is now mod p^r\n\n    ctxt = unpacked;\n  }\n  else {\n\n    if (p==2 && r>1 && topHigh+1 > 2)\n      topHigh--; // For p==2 we sometime get a bit for free\n\n    extractDigits(scratch, unpacked, topHigh+1);\n\n    // set upacked = -\\sum_{j=botHigh}^{topHigh} scratch[j] * p^{j-botHigh}\n    if (topHigh >= LONG(scratch.size())) {\n      topHigh = scratch.size() -1;\n      cerr << \" @ suspect: not enough digits in extractDigitsPacked\\n\";\n    }\n\n    unpacked = scratch[topHigh];\n    for (long j=topHigh-1; j>=botHigh; --j) {\n      unpacked.multByP();\n      unpacked += scratch[j];\n    }\n    if (p==2 && botHigh>0)   // For p==2, subtract also the previous bit\n      unpacked += scratch[botHigh-1];\n    unpacked.negate();\n\n    if (r>ePrime) {          // Add in digits from the bottom part, if any\n      long topLow = r-1 - ePrime;\n      Ctxt tmp = scratch[topLow];\n      for (long j=topLow-1; j>=0; --j) {\n\ttmp.multByP();\n\ttmp += scratch[j];\n      }\n      if (ePrime>0)\n\ttmp.multByP(ePrime); // multiply by p^e'\n      unpacked += tmp;\n    }\n    unpacked.reducePtxtSpace(p2r); // Our plaintext space is now mod p^r\n    ctxt = unpacked;\n  }\n\n}\n\n\n// Hack to get at private fields of public key\nstruct FHEPubKeyHack { // The public key\n  const FHEcontext& context; // The context\n\n  //! @var Ctxt pubEncrKey\n  //! The public encryption key is an encryption of 0,\n  //! relative to the first secret key\n  Ctxt pubEncrKey;\n\n  std::vector<long> skHwts; // The Hamming weight of the secret keys\n  std::vector<KeySwitch> keySwitching; // The key-switching matrices\n\n  // The keySwitchMap structure contains pointers to key-switching matrices\n  // for re-linearizing automorphisms. The entry keySwitchMap[i][n] contains\n  // the index j such that keySwitching[j] is the first matrix one needs to\n  // use when re-linearizing s_i(X^n). \n  std::vector< std::vector<long> > keySwitchMap;\n\n  NTL::Vec<int> KS_strategy; // NTL Vec's support I/O, which is\n                             // more convenient\n\n  // bootstrapping data\n\n  long recryptKeyID; // index of the bootstrapping key\n  Ctxt recryptEkey;  // the key itself, encrypted under key #0\n\n};\n\n// bootstrap a ciphertext to reduce noise\nvoid FHEPubKey::thinReCrypt(Ctxt &ctxt)\n{\n  FHE_TIMER_START;\n\n  // Some sanity checks for dummy ciphertext\n  long ptxtSpace = ctxt.getPtxtSpace();\n  if (ctxt.isEmpty()) return;\n\n  if (ctxt.parts.size()==1 && ctxt.parts[0].skHandle.isOne()) {\n    // Dummy encryption, just ensure that it is reduced mod p\n    ZZX poly = to_ZZX(ctxt.parts[0]);\n    for (long i=0; i<poly.rep.length(); i++)\n      poly[i] = to_ZZ( rem(poly[i],ptxtSpace) );\n    poly.normalize();\n    ctxt.DummyEncrypt(poly);\n    return;\n  }\n\n  //OLD: assert(recryptKeyID>=0); // check that we have bootstrapping data\n  helib::assertTrue(recryptKeyID>=0l, \"Bootstrapping data not present\");\n\n  long p = ctxt.getContext().zMStar.getP();\n  long r = ctxt.getContext().alMod.getR();\n  long p2r = ctxt.getContext().alMod.getPPowR();\n\n  long intFactor = ctxt.intFactor;\n\n  const ThinRecryptData& trcData = ctxt.getContext().rcData;\n\n  // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}.\n  long e = trcData.e;\n  long ePrime = trcData.ePrime;\n  long p2ePrime = power_long(p,ePrime);\n  long q = power_long(p,e)+1;\n  //OLD: assert(e>=r);\n  helib::assertTrue(e>=r, \"trcData.e must be at least alMod.r\");\n\n  // can only bootstrap ciphertext with plaintext-space dividing p^r\n  //OLD: assert(p2r % ptxtSpace == 0);\n  helib::assertEq(p2r % ptxtSpace, 0l, \"ptxtSpace must divide p^r when thin bootstrapping\");\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"init\");\n#endif\n\n  ctxt.dropSmallAndSpecialPrimes();\n\n#define DROP_BEFORE_THIN_RECRYPT\n#define THIN_RECRYPT_NLEVELS (3)\n#ifdef DROP_BEFORE_THIN_RECRYPT\n  // experimental code...we should drop down to a reasonably low level\n  // before doing the first linear map.\n  long first = context.ctxtPrimes.first();\n  long last = min(context.ctxtPrimes.last(),\n                  first + THIN_RECRYPT_NLEVELS - 1);\n  ctxt.bringToSet(IndexSet(first, last));\n#endif\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after mod down\");\n#endif\n\n  // Move the slots to powerful-basis coefficients\n  FHE_NTIMER_START(AAA_slotToCoeff);\n  trcData.slotToCoeff->apply(ctxt);\n  FHE_NTIMER_STOP(AAA_slotToCoeff);\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after slotToCoeff\");\n#endif\n\n  FHE_NTIMER_START(AAA_bootKeySwitch);\n\n  // Make sure that this ciphertxt is in canonical form\n  if (!ctxt.inCanonicalForm()) ctxt.reLinearize();\n\n  // Mod-switch down if needed\n  IndexSet s = ctxt.getPrimeSet() / context.specialPrimes;\n  //OLD: assert(s <= context.ctxtPrimes);\n  helib::assertTrue(s <= context.ctxtPrimes,  \"prime set is messed up\");\n  if (s.card()>3) { // leave only first three ciphertext primes\n    long first = s.first();\n    IndexSet s3(first, first+2);\n    s.retain(s3); \n  }\n  ctxt.modDownToSet(s);\n\n  // key-switch to the bootstrapping key\n  ctxt.reLinearize(recryptKeyID);\n\n#ifdef DEBUG_PRINTOUT\n  CheckCtxt(ctxt, \"after key switching\");\n#endif\n\n  // \"raw mod-switch\" to the bootstrapping mosulus q=p^e+1.\n  vector<ZZX> zzParts; // the mod-switched parts, in ZZX format\n\n  double mfac = ctxt.getContext().zMStar.getNormBnd();\n  double noise_est = ctxt.rawModSwitch(zzParts, q) * mfac;\n  // noise_est is an upper bound on the L-infty norm of the scaled noise \n  // in the pwrfl basis\n  double noise_bnd = 0.66*p2r*ctxt.getContext().boundForRecryption();\n  // noise_bnd is the bound assumed in selecting the parameters \n  double noise_rat = noise_est/noise_bnd;\n\n  FHE_STATS_UPDATE(\"raw-mod-switch-noise\", noise_rat);\n\n  if (noise_rat > 1) {\n    Warning(\"rawModSwitch scaled noise exceeds bound: \" + std::to_string(noise_rat));\n  }\n  \n\n  //OLD: assert(zzParts.size() == 2);\n  helib::assertEq(zzParts.size(), (std::size_t)2, \"Exactly 2 parts required for mod-switching in thin bootstrapping\");\n\n\n#ifdef DEBUG_PRINTOUT\n  if (dbgKey) {\n    checkRecryptBounds(zzParts, dbgKey->sKeys[recryptKeyID],\n                       ctxt.getContext(), q);\n  }\n#endif\n\n  vector<ZZX> v;\n  v.resize(2);\n\n\n  // Add multiples of q to make the zzParts divisible by p^{e'}\n  for (long i: range(2)) {\n    // make divisible by p^{e'}\n\n    newMakeDivisible(zzParts[i], p2ePrime, q, ctxt.getContext(), v[i]);\n\n  }\n\n#ifdef DEBUG_PRINTOUT\n  if (dbgKey) {\n    checkRecryptBounds_v(v, dbgKey->sKeys[recryptKeyID],\n\t\t       ctxt.getContext(), q);\n    checkCriticalValue(zzParts, dbgKey->sKeys[recryptKeyID],\n                       ctxt.getContext().rcData, q);\n  }\n#endif\n\n  for (long i: range(zzParts.size())) {\n    zzParts[i] /= p2ePrime;   // divide by p^{e'}\n  }\n\n  // NOTE: here we lose the intFactor associated with ctxt.\n  // We will restore it below.\n  ctxt = recryptEkey;\n\n  ctxt.multByConstant(zzParts[1]);\n  ctxt.addConstant(zzParts[0]);\n\n#ifdef DEBUG_PRINTOUT\n   CheckCtxt(ctxt, \"after bootKeySwitch\");\n#endif\n\n  FHE_NTIMER_STOP(AAA_bootKeySwitch);\n\n  // Move the powerful-basis coefficients to the plaintext slots\n  FHE_NTIMER_START(AAA_coeffToSlot);\n  trcData.coeffToSlot->apply(ctxt);\n  FHE_NTIMER_STOP(AAA_coeffToSlot);\n\n#ifdef DEBUG_PRINTOUT\n   CheckCtxt(ctxt, \"after coeffToSlot\");\n#endif\n\n  // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots)\n  FHE_NTIMER_START(AAA_extractDigitsThin);\n  extractDigitsThin(ctxt, e-ePrime, r, ePrime);\n  FHE_NTIMER_STOP(AAA_extractDigitsThin);\n\n\n#ifdef DEBUG_PRINTOUT\n   CheckCtxt(ctxt, \"after extractDigitsThin\");\n#endif\n\n  // restore intFactor\n  if (intFactor != 1)\n    ctxt.intFactor = MulMod(ctxt.intFactor, intFactor, ptxtSpace);\n}\n\n\n\nstatic void\ncheckCriticalValue(const vector<ZZX>& zzParts, const DoubleCRT& sKey,\n                   const RecryptData& rcData, long q)\n{\n  ZZX ptxt;\n  rawDecrypt(ptxt, zzParts, sKey); // no mod q\n\n  Vec<ZZ> powerful;\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n  xdouble max_pwrfl = conv<xdouble>(largestCoeff(powerful));\n  double critical_value = conv<double>((max_pwrfl/q)/q);\n\n  vecRed(powerful, powerful, q, false);\n  max_pwrfl = conv<xdouble>(largestCoeff(powerful));\n  critical_value += conv<double>(max_pwrfl/q);\n\n  FHE_STATS_UPDATE(\"critical-value\", critical_value);\n\n  cerr << \"=== critical_value=\" << critical_value;\n  if (critical_value > 0.5) cerr << \" BAD-BOUND\";\n\n  cerr << \"\\n\";\n}\n\nstatic void\ncheckRecryptBounds(const vector<ZZX>& zzParts, const DoubleCRT& sKey,\n                   const FHEcontext& context, long q)\n{\n  const RecryptData& rcData = context.rcData;\n  double coeff_bound = context.boundForRecryption();\n  long p2r = context.alMod.getPPowR();\n\n  ZZX ptxt;\n  rawDecrypt(ptxt, zzParts, sKey); // no mod q\n\n  Vec<ZZ> powerful;\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n  double max_pwrfl = conv<double>(largestCoeff(powerful));\n  double ratio = max_pwrfl/(2*q*coeff_bound);\n\n  FHE_STATS_UPDATE(\"|x|/bound\", ratio);\n\n  cerr << \"=== |x|/bound=\" << ratio;\n  if (ratio > 1.0) cerr << \" BAD-BOUND\";\n\n  vecRed(powerful, powerful, q, false);\n  max_pwrfl = conv<double>(largestCoeff(powerful));\n  ratio = max_pwrfl/(2*p2r*coeff_bound);\n\n  FHE_STATS_UPDATE(\"|x%q|/bound\", ratio);\n\n  cerr << \", (|x%q|)/bound=\" << ratio;\n  if (ratio > 1.0) cerr << \" BAD-BOUND\";\n\n  cerr << \"\\n\";\n}\n\n\nstatic void\ncheckRecryptBounds_v(const vector<ZZX>& v, const DoubleCRT& sKey,\n                     const FHEcontext& context, long q)\n{\n  const RecryptData& rcData = context.rcData;\n\n\n  long p = context.zMStar.getP();\n  long e = rcData.e;\n  long p2e = power_long(p, e);\n  long ePrime = rcData.ePrime;\n  long p2ePrime = power_long(p, ePrime);\n  long phim = context.zMStar.getPhiM();\n  long k = context.zMStar.getNFactors();\n  long skHwt = rcData.skHwt;\n\n  double fudge = compute_fudge(p2ePrime, p2e);\n\n  double coeff_bound = context.boundForRecryption() * fudge;\n\n  double sigma = context.stdDevForRecryption() * fudge;\n\n  ZZX ptxt;\n  rawDecrypt(ptxt, v, sKey); // no mod q\n\n  Vec<ZZ> powerful;\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n  double max_pwrfl = conv<double>(largestCoeff(powerful));\n\n\n  double denom = p2ePrime*coeff_bound;\n  double ratio = max_pwrfl/denom;\n\n  FHE_STATS_UPDATE(\"|v|/bound\", ratio);\n\n  cerr << \"=== |v|/bound=\" << ratio;\n  if (ratio > 1.0) cerr << \" BAD-BOUND\";\n  cerr << \"\\n\";\n\n  ptxt -= v[0];  // so now ptxt is just sKey * v[1]\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n\n  helib::assertEq(powerful.length(), phim, \"length should be phim\");\n\n  double ran_pwrfl = conv<double>(powerful[RandomBnd(phim)]);\n  // pick a random coefficient in the poweful basis\n\n  double std_devs = fabs(ran_pwrfl)/(p2ePrime*sigma);\n  // number of standard deviations away from mean\n\n  // update various indicator variables\n  FHE_STATS_UPDATE(\"sigma_0_5\", double(std_devs <= 0.5)); // 0.383\n  FHE_STATS_UPDATE(\"sigma_1_0\", double(std_devs <= 1.0)); // 0.683\n  FHE_STATS_UPDATE(\"sigma_1_5\", double(std_devs <= 1.5)); // 0.866\n  FHE_STATS_UPDATE(\"sigma_2_0\", double(std_devs <= 2.0)); // 0.954\n  FHE_STATS_UPDATE(\"sigma_2_5\", double(std_devs <= 2.5)); // 0.988\n  FHE_STATS_UPDATE(\"sigma_3_0\", double(std_devs <= 3.0)); // 0.997, 1 in 370\n  FHE_STATS_UPDATE(\"sigma_3_5\", double(std_devs <= 3.5)); // 0.999535, 1 in 2149\n  FHE_STATS_UPDATE(\"sigma_4_0\", double(std_devs <= 4.0)); // 0.999937, 1 in 15787\n\n  // compute sample variance, and scale by the variance we expect\n  FHE_STATS_UPDATE(\"sigma_calc\", fsquare(ran_pwrfl)/fsquare(p2ePrime*sigma));\n\n  // save the scaled value for application of other tests\n  FHE_STATS_SAVE(\"v_values\", ran_pwrfl/(p2ePrime*sigma));\n}\n\n\n#if 0\nvoid fhe_stats_print(long iter, const FHEcontext& context)\n{\n   long phim = context.zMStar.getPhiM();\n\n   cerr << \"||||| recryption stats ||||\\n\";\n   cerr << \"**** averages ****\\n\";\n   cerr << \"=== critical_value=\" << (fhe_stats_cv_sum/iter) << \"\\n\";\n   cerr << \"=== |x|/bound=\" << (fhe_stats_x_sum/iter) << \"\\n\";\n   cerr << \"=== |x%q|/bound=\" << (fhe_stats_xmod_sum/iter) << \"\\n\";\n   cerr << \"=== |u|/bound=\" << (fhe_stats_u_sum/iter) << \"\\n\";\n   cerr << \"=== |v|/bound=\" << (fhe_stats_v_sum/iter) << \"\\n\";\n   cerr << \"**** maxima ****\\n\";\n   cerr << \"=== critical_value=\" << (fhe_stats_cv_max) << \"\\n\";\n   cerr << \"=== |x|/bound=\" << (fhe_stats_x_max) << \"\\n\";\n   cerr << \"=== |x%q|/bound=\" << (fhe_stats_xmod_max) << \"\\n\";\n   cerr << \"=== |u|/bound=\" << (fhe_stats_u_max) << \"\\n\";\n   cerr << \"=== |v|/bound=\" << (fhe_stats_v_max) << \"\\n\";\n   cerr << \"**** theoretical bounds ***\\n\";\n   cerr << \"=== single-max=\" << (sqrt(2.0*log(phim))/context.scale) << \"\\n\";\n   cerr << \"=== global-max=\" << (sqrt(2.0*(log(iter)+log(phim)))/context.scale) << \"\\n\";\n\n\n}\n#endif\n", "meta": {"hexsha": "be01cb6167dacee87b4460283e6ca5511e7b9cb4", "size": 37363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/recryption.cpp", "max_stars_repo_name": "pememoni/HElib", "max_stars_repo_head_hexsha": "96838a91b4d248573f9be7e3428d060bc4813da3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T04:55:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-04T04:55:29.000Z", "max_issues_repo_path": "src/recryption.cpp", "max_issues_repo_name": "PNIDEMOOO/HElib", "max_issues_repo_head_hexsha": "7427ed3709bb9872835324dd0007a97b3ca3baca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/recryption.cpp", "max_forks_repo_name": "PNIDEMOOO/HElib", "max_forks_repo_head_hexsha": "7427ed3709bb9872835324dd0007a97b3ca3baca", "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.4428684003, "max_line_length": 118, "alphanum_fraction": 0.639911142, "num_tokens": 11304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.052618953347713764, "lm_q1q2_score": 0.023646570067707373}}
{"text": "// Copyright (C) 2018  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n#include \"opaque_types.h\"\n#include <dlib/python.h>\n#include \"dlib/pixel.h\"\n#include <dlib/image_transforms.h>\n#include <dlib/image_processing.h>\n\nusing namespace dlib;\nusing namespace std;\n\nnamespace py = pybind11;\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\nline ht_get_line (\n    const hough_transform& ht,\n    const dlib::vector<T,2>& p\n)  \n{ \n    DLIB_CASSERT(get_rect(ht).contains(p));\n    auto temp = ht.get_line(p); \n    return line(temp.first, temp.second);\n}\n\ntemplate <typename T>\ndouble ht_get_line_angle_in_degrees (\n    const hough_transform& ht,\n    const dlib::vector<T,2>& p \n)  \n{ \n    DLIB_CASSERT(get_rect(ht).contains(p));\n    return ht.get_line_angle_in_degrees(p); \n}\n\ntemplate <typename T>\npy::tuple ht_get_line_properties (\n    const hough_transform& ht,\n    const dlib::vector<T,2>& p\n)  \n{ \n    DLIB_CASSERT(get_rect(ht).contains(p));\n    double angle_in_degrees;\n    double radius;\n    ht.get_line_properties(p, angle_in_degrees, radius);\n    return py::make_tuple(angle_in_degrees, radius);\n}\n\npoint ht_get_best_hough_point (\n    hough_transform& ht,\n    const point& p,\n    const numpy_image<float>& himg\n) \n{ \n    DLIB_CASSERT(num_rows(himg) == ht.size() && num_columns(himg) == ht.size() &&\n        get_rect(ht).contains(p) == true,\n        \"\\t point hough_transform::get_best_hough_point()\"\n        << \"\\n\\t Invalid arguments given to this function.\"\n        << \"\\n\\t num_rows(himg): \" << num_rows(himg)\n        << \"\\n\\t num_columns(himg): \" << num_columns(himg)\n        << \"\\n\\t size():    \" << ht.size()\n        << \"\\n\\t p:         \" << p \n    );\n    return ht.get_best_hough_point(p,himg); \n}\n\ntemplate <\n    typename T \n    >\nnumpy_image<float> compute_ht (\n    const hough_transform& ht,\n    const numpy_image<T>& img,\n    const rectangle& box\n) \n{\n    numpy_image<float> out;\n    ht(img, box, out);\n    return out;\n}\n\ntemplate <\n    typename T \n    >\nnumpy_image<float> compute_ht2 (\n    const hough_transform& ht,\n    const numpy_image<T>& img\n) \n{\n    numpy_image<float> out;\n    ht(img, out);\n    return out;\n}\n\ntemplate <\n    typename T \n    >\npy::list ht_find_pixels_voting_for_lines (\n    const hough_transform& ht,\n    const numpy_image<T>& img,\n    const rectangle& box,\n    const std::vector<point>& hough_points,\n    const unsigned long angle_window_size = 1,\n    const unsigned long radius_window_size = 1\n) \n{\n    return vector_to_python_list(ht.find_pixels_voting_for_lines(img, box, hough_points, angle_window_size, radius_window_size));\n}\n\ntemplate <\n    typename T \n    >\npy::list ht_find_pixels_voting_for_lines2 (\n    const hough_transform& ht,\n    const numpy_image<T>& img,\n    const std::vector<point>& hough_points,\n    const unsigned long angle_window_size = 1,\n    const unsigned long radius_window_size = 1\n) \n{\n    return vector_to_python_list(ht.find_pixels_voting_for_lines(img, hough_points, angle_window_size, radius_window_size));\n}\n\nstd::vector<point> ht_find_strong_hough_points(\n    hough_transform& ht,\n    const numpy_image<float>& himg,\n    const float hough_count_thresh,\n    const double angle_nms_thresh,\n    const double radius_nms_thresh\n)\n{\n    return ht.find_strong_hough_points(himg, hough_count_thresh, angle_nms_thresh, radius_nms_thresh);\n}\n\n\n// ----------------------------------------------------------------------------------------\n\nvoid register_hough_transform(py::module& m)\n{\n    const char* class_docs =\n\"This object is a tool for computing the line finding version of the Hough transform \\n\\\ngiven some kind of edge detection image as input.  It also allows the edge pixels \\n\\\nto be weighted such that higher weighted edge pixels contribute correspondingly \\n\\\nmore to the output of the Hough transform, allowing stronger edges to create \\n\\\ncorrespondingly stronger line detections in the final Hough transform.\";\n\n\n    const char* doc_constr = \n\"requires \\n\\\n    - size_ > 0 \\n\\\nensures \\n\\\n    - This object will compute Hough transforms that are size_ by size_ pixels.   \\n\\\n      This is in terms of both the Hough accumulator array size as well as the \\n\\\n      input image size. \\n\\\n    - size() == size_\";\n        /*!\n            requires\n                - size_ > 0\n            ensures\n                - This object will compute Hough transforms that are size_ by size_ pixels.  \n                  This is in terms of both the Hough accumulator array size as well as the\n                  input image size.\n                - size() == size_\n        !*/\n\n    py::class_<hough_transform>(m, \"hough_transform\", class_docs)\n        .def(py::init<unsigned long>(), doc_constr, py::arg(\"size_\"))\n        .def_property_readonly(\"size\", &hough_transform::size,\n            \"returns the size of the Hough transforms generated by this object.  In particular, this object creates Hough transform images that are size by size pixels in size.\")\n        .def(\"get_line\", &ht_get_line<long>, py::arg(\"p\"))\n        .def(\"get_line\", &ht_get_line<double>, py::arg(\"p\"),\n\"requires \\n\\\n    - rectangle(0,0,size-1,size-1).contains(p) == true \\n\\\n      (i.e. p must be a point inside the Hough accumulator array) \\n\\\nensures \\n\\\n    - returns the line segment in the original image space corresponding \\n\\\n      to Hough transform point p.  \\n\\\n    - The returned points are inside rectangle(0,0,size-1,size-1).\") \n    /*!\n        requires\n            - rectangle(0,0,size-1,size-1).contains(p) == true\n              (i.e. p must be a point inside the Hough accumulator array)\n        ensures\n            - returns the line segment in the original image space corresponding\n              to Hough transform point p. \n            - The returned points are inside rectangle(0,0,size-1,size-1).\n    !*/\n\n        .def(\"get_line_angle_in_degrees\", &ht_get_line_angle_in_degrees<long>, py::arg(\"p\"))\n        .def(\"get_line_angle_in_degrees\", &ht_get_line_angle_in_degrees<double>, py::arg(\"p\"),\n\"requires \\n\\\n    - rectangle(0,0,size-1,size-1).contains(p) == true \\n\\\n      (i.e. p must be a point inside the Hough accumulator array) \\n\\\nensures \\n\\\n    - returns the angle, in degrees, of the line corresponding to the Hough \\n\\\n      transform point p.\")\n    /*!\n        requires\n            - rectangle(0,0,size-1,size-1).contains(p) == true\n              (i.e. p must be a point inside the Hough accumulator array)\n        ensures\n            - returns the angle, in degrees, of the line corresponding to the Hough\n              transform point p.\n    !*/\n\n\n        .def(\"get_line_properties\", &ht_get_line_properties<long>, py::arg(\"p\"))\n        .def(\"get_line_properties\", &ht_get_line_properties<double>, py::arg(\"p\"),\n\"requires \\n\\\n    - rectangle(0,0,size-1,size-1).contains(p) == true \\n\\\n      (i.e. p must be a point inside the Hough accumulator array) \\n\\\nensures \\n\\\n    - Converts a point in the Hough transform space into an angle, in degrees, \\n\\\n      and a radius, measured in pixels from the center of the input image. \\n\\\n    - let ANGLE_IN_DEGREES == the angle of the line corresponding to the Hough \\n\\\n      transform point p.  Moreover: -90 <= ANGLE_IN_DEGREES < 90. \\n\\\n    - RADIUS == the distance from the center of the input image, measured in \\n\\\n      pixels, and the line corresponding to the Hough transform point p. \\n\\\n      Moreover: -sqrt(size*size/2) <= RADIUS <= sqrt(size*size/2) \\n\\\n    - returns a tuple of (ANGLE_IN_DEGREES, RADIUS)\" )\n    /*!\n        requires\n            - rectangle(0,0,size-1,size-1).contains(p) == true\n              (i.e. p must be a point inside the Hough accumulator array)\n        ensures\n            - Converts a point in the Hough transform space into an angle, in degrees,\n              and a radius, measured in pixels from the center of the input image.\n            - let ANGLE_IN_DEGREES == the angle of the line corresponding to the Hough\n              transform point p.  Moreover: -90 <= ANGLE_IN_DEGREES < 90.\n            - RADIUS == the distance from the center of the input image, measured in\n              pixels, and the line corresponding to the Hough transform point p.\n              Moreover: -sqrt(size*size/2) <= RADIUS <= sqrt(size*size/2)\n            - returns a tuple of (ANGLE_IN_DEGREES, RADIUS)\n    !*/\n\n        .def(\"get_best_hough_point\", &ht_get_best_hough_point, py::arg(\"p\"), py::arg(\"himg\"),\n\"requires \\n\\\n    - himg has size rows and columns. \\n\\\n    - rectangle(0,0,size-1,size-1).contains(p) == true \\n\\\nensures \\n\\\n    - This function interprets himg as a Hough image and p as a point in the \\n\\\n      original image space.  Given this, it finds the maximum scoring line that \\n\\\n      passes though p.  That is, it checks all the Hough accumulator bins in \\n\\\n      himg corresponding to lines though p and returns the location with the \\n\\\n      largest score.   \\n\\\n    - returns a point X such that get_rect(himg).contains(X) == true\")\n    /*!\n        requires\n            - himg has size rows and columns.\n            - rectangle(0,0,size-1,size-1).contains(p) == true\n        ensures\n            - This function interprets himg as a Hough image and p as a point in the\n              original image space.  Given this, it finds the maximum scoring line that\n              passes though p.  That is, it checks all the Hough accumulator bins in\n              himg corresponding to lines though p and returns the location with the\n              largest score.  \n            - returns a point X such that get_rect(himg).contains(X) == true\n    !*/\n\n        .def(\"__call__\", &compute_ht<uint8_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<uint16_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<uint32_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<uint64_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<int8_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<int16_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<int32_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<int64_t>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<float>, py::arg(\"img\"), py::arg(\"box\"))\n        .def(\"__call__\", &compute_ht<double>, py::arg(\"img\"), py::arg(\"box\"),\n\"requires \\n\\\n    - box.width() == size \\n\\\n    - box.height() == size \\n\\\nensures \\n\\\n    - Computes the Hough transform of the part of img contained within box. \\n\\\n      In particular, we do a grayscale version of the Hough transform where any \\n\\\n      non-zero pixel in img is treated as a potential component of a line and \\n\\\n      accumulated into the returned Hough accumulator image.  However, rather than \\n\\\n      adding 1 to each relevant accumulator bin we add the value of the pixel \\n\\\n      in img to each Hough accumulator bin.  This means that, if all the \\n\\\n      pixels in img are 0 or 1 then this routine performs a normal Hough \\n\\\n      transform.  However, if some pixels have larger values then they will be \\n\\\n      weighted correspondingly more in the resulting Hough transform. \\n\\\n    - The returned hough transform image will be size rows by size columns. \\n\\\n    - The returned image is the Hough transform of the part of img contained in \\n\\\n      box.  Each point in the Hough image corresponds to a line in the input box. \\n\\\n      In particular, the line for hough_image[y][x] is given by get_line(point(x,y)).  \\n\\\n      Also, when viewing the Hough image, the x-axis gives the angle of the line \\n\\\n      and the y-axis the distance of the line from the center of the box.  The \\n\\\n      conversion between Hough coordinates and angle and pixel distance can be \\n\\\n      obtained by calling get_line_properties().\" )\n    /*!\n        requires\n            - box.width() == size\n            - box.height() == size\n        ensures\n            - Computes the Hough transform of the part of img contained within box.\n              In particular, we do a grayscale version of the Hough transform where any\n              non-zero pixel in img is treated as a potential component of a line and\n              accumulated into the returned Hough accumulator image.  However, rather than\n              adding 1 to each relevant accumulator bin we add the value of the pixel\n              in img to each Hough accumulator bin.  This means that, if all the\n              pixels in img are 0 or 1 then this routine performs a normal Hough\n              transform.  However, if some pixels have larger values then they will be\n              weighted correspondingly more in the resulting Hough transform.\n            - The returned hough transform image will be size rows by size columns.\n            - The returned image is the Hough transform of the part of img contained in\n              box.  Each point in the Hough image corresponds to a line in the input box.\n              In particular, the line for hough_image[y][x] is given by get_line(point(x,y)). \n              Also, when viewing the Hough image, the x-axis gives the angle of the line\n              and the y-axis the distance of the line from the center of the box.  The\n              conversion between Hough coordinates and angle and pixel distance can be\n              obtained by calling get_line_properties().\n    !*/\n\n        .def(\"__call__\", &compute_ht2<uint8_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<uint16_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<uint32_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<uint64_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<int8_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<int16_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<int32_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<int64_t>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<float>, py::arg(\"img\"))\n        .def(\"__call__\", &compute_ht2<double>, py::arg(\"img\"),\n            \"    simply performs: return self(img, get_rect(img)).  That is, just runs the hough transform on the whole input image.\")\n\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<uint8_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<uint16_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<uint32_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<uint64_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<int8_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<int16_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<int32_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<int64_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<float>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines<double>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1,\n\"requires \\n\\\n    - box.width() == size \\n\\\n    - box.height() == size \\n\\\n    - for all valid i: \\n\\\n        - rectangle(0,0,size-1,size-1).contains(hough_points[i]) == true \\n\\\n          (i.e. hough_points must contain points in the output Hough transform \\n\\\n          space generated by this object.) \\n\\\n    - angle_window_size >= 1 \\n\\\n    - radius_window_size >= 1 \\n\\\nensures \\n\\\n    - This function computes the Hough transform of the part of img contained \\n\\\n      within box.  It does the same computation as __call__() defined above, \\n\\\n      except instead of accumulating into an image we create an explicit list \\n\\\n      of all the points in img that contributed to each line (i.e each point in \\n\\\n      the Hough image). To do this we take a list of Hough points as input and \\n\\\n      only record hits on these specifically identified Hough points.  A \\n\\\n      typical use of find_pixels_voting_for_lines() is to first run the normal \\n\\\n      Hough transform using __call__(), then find the lines you are interested \\n\\\n      in, and then call find_pixels_voting_for_lines() to determine which \\n\\\n      pixels in the input image belong to those lines. \\n\\\n    - This routine returns a vector, CONSTITUENT_POINTS, with the following \\n\\\n      properties: \\n\\\n        - CONSTITUENT_POINTS.size == hough_points.size \\n\\\n        - for all valid i: \\n\\\n            - Let HP[i] = centered_rect(hough_points[i], angle_window_size, radius_window_size) \\n\\\n            - Any point in img with a non-zero value that lies on a line \\n\\\n              corresponding to one of the Hough points in HP[i] is added to \\n\\\n              CONSTITUENT_POINTS[i].  Therefore, when this routine finishes, \\n\\\n              #CONSTITUENT_POINTS[i] will contain all the points in img that \\n\\\n              voted for the lines associated with the Hough accumulator bins in \\n\\\n              HP[i]. \\n\\\n            - #CONSTITUENT_POINTS[i].size == the number of points in img that \\n\\\n              voted for any of the lines HP[i] in Hough space.  Note, however, \\n\\\n              that if angle_window_size or radius_window_size are made so large \\n\\\n              that HP[i] overlaps HP[j] for i!=j then the overlapping regions \\n\\\n              of Hough space are assigned to HP[i] or HP[j] arbitrarily. \\n\\\n              That is, we treat HP[i] and HP[j] as disjoint even if their boxes \\n\\\n              overlap.  In this case, the overlapping region is assigned to \\n\\\n              either HP[i] or HP[j] in an arbitrary manner.\" )\n    /*!\n        requires\n            - box.width() == size\n            - box.height() == size\n            - for all valid i:\n                - rectangle(0,0,size-1,size-1).contains(hough_points[i]) == true\n                  (i.e. hough_points must contain points in the output Hough transform\n                  space generated by this object.)\n            - angle_window_size >= 1\n            - radius_window_size >= 1\n        ensures\n            - This function computes the Hough transform of the part of img contained\n              within box.  It does the same computation as __call__() defined above,\n              except instead of accumulating into an image we create an explicit list\n              of all the points in img that contributed to each line (i.e each point in\n              the Hough image). To do this we take a list of Hough points as input and\n              only record hits on these specifically identified Hough points.  A\n              typical use of find_pixels_voting_for_lines() is to first run the normal\n              Hough transform using __call__(), then find the lines you are interested\n              in, and then call find_pixels_voting_for_lines() to determine which\n              pixels in the input image belong to those lines.\n            - This routine returns a vector, CONSTITUENT_POINTS, with the following\n              properties:\n                - CONSTITUENT_POINTS.size == hough_points.size\n                - for all valid i:\n                    - Let HP[i] = centered_rect(hough_points[i], angle_window_size, radius_window_size)\n                    - Any point in img with a non-zero value that lies on a line\n                      corresponding to one of the Hough points in HP[i] is added to\n                      CONSTITUENT_POINTS[i].  Therefore, when this routine finishes,\n                      #CONSTITUENT_POINTS[i] will contain all the points in img that\n                      voted for the lines associated with the Hough accumulator bins in\n                      HP[i].\n                    - #CONSTITUENT_POINTS[i].size == the number of points in img that\n                      voted for any of the lines HP[i] in Hough space.  Note, however,\n                      that if angle_window_size or radius_window_size are made so large\n                      that HP[i] overlaps HP[j] for i!=j then the overlapping regions\n                      of Hough space are assigned to HP[i] or HP[j] arbitrarily.\n                      That is, we treat HP[i] and HP[j] as disjoint even if their boxes\n                      overlap.  In this case, the overlapping region is assigned to\n                      either HP[i] or HP[j] in an arbitrary manner.\n    !*/\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<uint8_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<uint16_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<uint32_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<uint64_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<int8_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<int16_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<int32_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<int64_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<float>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\n        .def(\"find_pixels_voting_for_lines\", &ht_find_pixels_voting_for_lines2<double>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1,\n\"    performs: return find_pixels_voting_for_lines(img, get_rect(img), hough_points, angle_window_size, radius_window_size); \\n\\\nThat is, just runs the routine on the whole input image.\" )\n\n        .def(\"find_strong_hough_points\", &ht_find_strong_hough_points, py::arg(\"himg\"), py::arg(\"hough_count_thresh\"), py::arg(\"angle_nms_thresh\"), py::arg(\"radius_nms_thresh\"),\n\"requires \\n\\\n    - himg has size() rows and columns. \\n\\\n    - angle_nms_thresh >= 0 \\n\\\n    - radius_nms_thresh >= 0 \\n\\\nensures \\n\\\n    - This routine finds strong lines in a Hough transform and performs \\n\\\n      non-maximum suppression on the detected lines.  Recall that each point in \\n\\\n      Hough space is associated with a line. Therefore, this routine finds all \\n\\\n      the pixels in himg (a Hough transform image) with values >= \\n\\\n      hough_count_thresh and performs non-maximum suppression on the \\n\\\n      identified list of pixels.  It does this by discarding lines that are \\n\\\n      within angle_nms_thresh degrees of a stronger line or within \\n\\\n      radius_nms_thresh distance (in terms of radius as defined by \\n\\\n      get_line_properties()) to a stronger Hough point. \\n\\\n    - The identified lines are returned as a list of coordinates in himg. \\n\\\n    - The returned points are sorted so that points with larger Hough transform \\n\\\n      values come first.\" \n    /*!\n        requires\n            - himg has size() rows and columns.\n            - angle_nms_thresh >= 0\n            - radius_nms_thresh >= 0\n        ensures\n            - This routine finds strong lines in a Hough transform and performs\n              non-maximum suppression on the detected lines.  Recall that each point in\n              Hough space is associated with a line. Therefore, this routine finds all\n              the pixels in himg (a Hough transform image) with values >=\n              hough_count_thresh and performs non-maximum suppression on the\n              identified list of pixels.  It does this by discarding lines that are\n              within angle_nms_thresh degrees of a stronger line or within\n              radius_nms_thresh distance (in terms of radius as defined by\n              get_line_properties()) to a stronger Hough point.\n            - The identified lines are returned as a list of coordinates in himg.\n            - The returned points are sorted so that points with larger Hough transform\n              values come first.\n    !*/\n        );\n\n\n    m.def(\"get_rect\", [](const hough_transform& ht){ return get_rect(ht); },\n        \"returns a rectangle(0,0,ht.size()-1,ht.size()-1).  Therefore, it is the rectangle that bounds the Hough transform image.\", \n        py::arg(\"ht\")  );\n}\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\nnumpy_image<T> py_transform_image (\n    const numpy_image<T>& img,\n    const point_transform_projective& map_point,\n    long rows,\n    long columns\n)\n{\n    DLIB_CASSERT(rows > 0 && columns > 0, \"The requested output image dimensions are invalid.\");\n    numpy_image<T> out(rows, columns);\n\n    transform_image(img, out, interpolate_bilinear(), map_point);\n\n    return out;\n}\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\nnumpy_image<T> py_extract_image_chip (\n    const numpy_image<T>& img,\n    const chip_details& chip_location \n)\n{\n    numpy_image<T> out;\n    extract_image_chip(img, chip_location, out);\n    return out;\n}\n\ntemplate <typename T>\npy::list py_extract_image_chips (\n    const numpy_image<T>& img,\n    const py::list& chip_locations\n)\n{\n    dlib::array<numpy_image<T>> out;\n    extract_image_chips(img, python_list_to_vector<chip_details>(chip_locations), out);\n    py::list ret;\n    for (const auto& i : out)\n        ret.append(i);\n    return ret;\n}\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\ndpoint py_max_point(const numpy_image<T>& img)\n{\n    DLIB_CASSERT(img.size() != 0);\n    return max_point(mat(img));\n}\n\ntemplate <typename T>\ndpoint py_max_point_interpolated(const numpy_image<T>& img)\n{\n    DLIB_CASSERT(img.size() != 0);\n    return max_point_interpolated(mat(img));\n}\n\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\nvoid py_zero_border_pixels (\n    numpy_image<T>& img,\n    long x_border_size,\n    long y_border_size\n)\n{\n    zero_border_pixels(img, x_border_size, y_border_size);\n}\n\ntemplate <typename T>\nvoid py_zero_border_pixels2 (\n    numpy_image<T>& img,\n    const rectangle& inside\n)\n{\n    zero_border_pixels(img, inside);\n}\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\npy::tuple py_spatially_filter_image (\n    const numpy_image<T>& img,\n    const numpy_image<T>& filter\n)\n{\n    DLIB_CASSERT(filter.size() != 0);\n    numpy_image<T> out;\n    auto rect = spatially_filter_image(img, out, mat(filter));\n    return py::make_tuple(out, rect);\n}\n\ntemplate <typename T>\nbool is_vector(\n    const py::array_t<T>& m\n)\n{\n    const size_t dims = m.ndim();\n    const size_t size = m.size();\n    if (dims == 1)\n        return true;\n\n    for (size_t i = 0; i < dims; ++i)\n    {\n        if (m.shape(i) != 1 && m.shape(i) != size)\n            return false;\n    }\n\n    return true;\n}\n\ntemplate <typename T>\npy::tuple py_spatially_filter_image_separable (\n    const numpy_image<T>& img,\n    const py::array_t<T>& row_filter,\n    const py::array_t<T>& col_filter\n)\n{\n    DLIB_CASSERT(row_filter.size() != 0);\n    DLIB_CASSERT(col_filter.size() != 0);\n    DLIB_CASSERT(is_vector(row_filter), \"The row filter must be either a row or column vector.\");\n    DLIB_CASSERT(is_vector(col_filter), \"The column filter must be either a row or column vector.\");\n\n    numpy_image<T> out;\n    auto rect = spatially_filter_image_separable(img, out, mat(row_filter.data(),row_filter.size()), mat(col_filter.data(),col_filter.size()));\n    return py::make_tuple(out, rect);\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid bind_image_classes4(py::module& m)\n{\n\n    const char* docs = \"\";\n\n    register_hough_transform(m);\n\n    m.def(\"transform_image\", &py_transform_image<uint8_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<uint16_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<uint32_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<uint64_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<int8_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<int16_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<int32_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<int64_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<float>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<double>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\n    m.def(\"transform_image\", &py_transform_image<rgb_pixel>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"),\n\"requires \\n\\\n    - rows > 0 \\n\\\n    - columns > 0 \\n\\\nensures \\n\\\n    - Returns an image that is the given rows by columns in size and contains a \\n\\\n      transformed part of img.  To do this, we interpret map_point as a mapping \\n\\\n      from pixels in the returned image to pixels in the input img.  transform_image()  \\n\\\n      uses this mapping and bilinear interpolation to fill the output image with an \\n\\\n      interpolated copy of img.   \\n\\\n    - Any locations in the output image that map to pixels outside img are set to 0.\" \n    /*!\n        requires\n            - rows > 0\n            - columns > 0\n        ensures\n            - Returns an image that is the given rows by columns in size and contains a\n              transformed part of img.  To do this, we interpret map_point as a mapping\n              from pixels in the returned image to pixels in the input img.  transform_image() \n              uses this mapping and bilinear interpolation to fill the output image with an\n              interpolated copy of img.  \n            - Any locations in the output image that map to pixels outside img are set to 0.\n    !*/\n        );\n\n    m.def(\"max_point\", &py_max_point<uint8_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<uint16_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<uint32_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<uint64_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<int8_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<int16_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<int32_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<int64_t>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<float>, py::arg(\"img\"));\n    m.def(\"max_point\", &py_max_point<double>, py::arg(\"img\"),\n\"requires \\n\\\n    - m.size > 0 \\n\\\nensures \\n\\\n    - returns the location of the maximum element of the array, that is, if the \\n\\\n      returned point is P then it will be the case that: img[P.y,P.x] == img.max().\" \n    /*!\n        requires\n            - m.size > 0\n        ensures\n            - returns the location of the maximum element of the array, that is, if the\n              returned point is P then it will be the case that: img[P.y,P.x] == img.max().\n    !*/\n        );\n\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<uint8_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<uint16_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<uint32_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<uint64_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<int8_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<int16_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<int32_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<int64_t>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<float>, py::arg(\"img\"));\n    m.def(\"max_point_interpolated\", &py_max_point_interpolated<double>, py::arg(\"img\"),\n\"requires \\n\\\n    - m.size > 0 \\n\\\nensures \\n\\\n    - Like max_point(), this function finds the location in m with the largest \\n\\\n      value.  However, we additionally use some quadratic interpolation to find the \\n\\\n      location of the maximum point with sub-pixel accuracy.  Therefore, the \\n\\\n      returned point is equal to max_point(m) + some small sub-pixel delta.\" \n    /*!\n        requires\n            - m.size > 0\n        ensures\n            - Like max_point(), this function finds the location in m with the largest\n              value.  However, we additionally use some quadratic interpolation to find the\n              location of the maximum point with sub-pixel accuracy.  Therefore, the\n              returned point is equal to max_point(m) + some small sub-pixel delta.\n    !*/\n        );\n\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<uint8_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<uint16_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<uint32_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<uint64_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<int8_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<int16_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<int32_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<int64_t>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<float>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<double>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels<rgb_pixel>, py::arg(\"img\"), py::arg(\"x_border_size\"), py::arg(\"y_border_size\"),\n\"requires \\n\\\n    - x_border_size >= 0 \\n\\\n    - y_border_size >= 0 \\n\\\nensures \\n\\\n    - The size and shape of img isn't changed by this function. \\n\\\n    - for all valid r such that r+y_border_size or r-y_border_size gives an invalid row \\n\\\n        - for all valid c such that c+x_border_size or c-x_border_size gives an invalid column  \\n\\\n            - assigns the pixel img[r][c] to 0.  \\n\\\n              (i.e. assigns 0 to every pixel in the border of img)\" \n    /*!\n        requires\n            - x_border_size >= 0\n            - y_border_size >= 0\n        ensures\n            - The size and shape of img isn't changed by this function.\n            - for all valid r such that r+y_border_size or r-y_border_size gives an invalid row\n                - for all valid c such that c+x_border_size or c-x_border_size gives an invalid column \n                    - assigns the pixel img[r][c] to 0. \n                      (i.e. assigns 0 to every pixel in the border of img)\n    !*/\n        );\n\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<uint8_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<uint16_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<uint32_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<uint64_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<int8_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<int16_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<int32_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<int64_t>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<float>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<double>, py::arg(\"img\"), py::arg(\"inside\"));\n    m.def(\"zero_border_pixels\", &py_zero_border_pixels2<rgb_pixel>, py::arg(\"img\"), py::arg(\"inside\"),\n\"ensures \\n\\\n    - The size and shape of img isn't changed by this function. \\n\\\n    - All the pixels in img that are not contained inside the inside rectangle \\n\\\n      given to this function are set to 0.  That is, anything not \\\"inside\\\" is on \\n\\\n      the border and set to 0.\" \n    /*!\n        ensures\n            - The size and shape of img isn't changed by this function.\n            - All the pixels in img that are not contained inside the inside rectangle\n              given to this function are set to 0.  That is, anything not \"inside\" is on\n              the border and set to 0.\n    !*/\n        );\n\n\n\n    m.def(\"spatially_filter_image\", &py_spatially_filter_image<uint8_t>, py::arg(\"img\"), py::arg(\"filter\"));\n    m.def(\"spatially_filter_image\", &py_spatially_filter_image<float>,   py::arg(\"img\"), py::arg(\"filter\"));\n    m.def(\"spatially_filter_image\", &py_spatially_filter_image<double>,  py::arg(\"img\"), py::arg(\"filter\"),\n\"requires \\n\\\n    - filter.size != 0 \\n\\\nensures \\n\\\n    - Applies the given spatial filter to img and returns the result (i.e. we  \\n\\\n      cross-correlate img with filter).  We also return a rectangle which \\n\\\n      indicates what pixels in the returned image are considered non-border pixels \\n\\\n      and therefore contain output from the filter.  E.g. \\n\\\n        - filtered_img,rect = spatially_filter_image(img, filter) \\n\\\n      would give you the filtered image and the rectangle in question.  Since the \\n\\\n      returned image has the same shape as img we fill the border pixels by setting \\n\\\n      them to 0. \\n\\\n \\n\\\n    - The filter is applied such that it's centered over the pixel it writes its \\n\\\n      output into.  For centering purposes, we consider the center element of the \\n\\\n      filter to be filter[filter.shape[0]/2,filter.shape[1]/2].  This means that \\n\\\n      the filter that writes its output to a pixel at location point(c,r) and is W \\n\\\n      by H (width by height) pixels in size operates on exactly the pixels in the \\n\\\n      rectangle centered_rect(point(c,r),W,H) within img.\" \n    /*!\n        requires\n            - filter.size != 0\n        ensures\n            - Applies the given spatial filter to img and returns the result (i.e. we \n              cross-correlate img with filter).  We also return a rectangle which\n              indicates what pixels in the returned image are considered non-border pixels\n              and therefore contain output from the filter.  E.g.\n                - filtered_img,rect = spatially_filter_image(img, filter)\n              would give you the filtered image and the rectangle in question.  Since the\n              returned image has the same shape as img we fill the border pixels by setting\n              them to 0.\n\n            - The filter is applied such that it's centered over the pixel it writes its\n              output into.  For centering purposes, we consider the center element of the\n              filter to be filter[filter.shape[0]/2,filter.shape[1]/2].  This means that\n              the filter that writes its output to a pixel at location point(c,r) and is W\n              by H (width by height) pixels in size operates on exactly the pixels in the\n              rectangle centered_rect(point(c,r),W,H) within img.\n    !*/\n        );\n\n    m.def(\"spatially_filter_image_separable\", &py_spatially_filter_image_separable<uint8_t>, py::arg(\"img\"), py::arg(\"row_filter\"), py::arg(\"col_filter\"));\n    m.def(\"spatially_filter_image_separable\", &py_spatially_filter_image_separable<float>,   py::arg(\"img\"), py::arg(\"row_filter\"), py::arg(\"col_filter\"));\n    m.def(\"spatially_filter_image_separable\", &py_spatially_filter_image_separable<double>,  py::arg(\"img\"), py::arg(\"row_filter\"), py::arg(\"col_filter\"),\n\"requires \\n\\\n    - row_filter.size != 0 \\n\\\n    - col_filter.size != 0 \\n\\\n    - row_filter and col_filter are both either row or column vectors.  \\n\\\nensures \\n\\\n    - Applies the given separable spatial filter to img and returns the result \\n\\\n      (i.e. we cross-correlate img with the filters).  In particular, calling this \\n\\\n      function has the same effect as calling the regular spatially_filter_image() \\n\\\n      routine with a filter, FILT, defined as follows:  \\n\\\n        - FILT(r,c) == col_filter(r)*row_filter(c) \\n\\\n      Therefore, the return value of this routine is the same as if it were \\n\\\n      implemented as:    \\n\\\n        return spatially_filter_image(img, FILT) \\n\\\n      Except that this version should be faster for separable filters.\" \n    /*!\n        requires\n            - row_filter.size != 0\n            - col_filter.size != 0\n            - row_filter and col_filter are both either row or column vectors. \n        ensures\n            - Applies the given separable spatial filter to img and returns the result\n              (i.e. we cross-correlate img with the filters).  In particular, calling this\n              function has the same effect as calling the regular spatially_filter_image()\n              routine with a filter, FILT, defined as follows: \n                - FILT(r,c) == col_filter(r)*row_filter(c)\n              Therefore, the return value of this routine is the same as if it were\n              implemented as:   \n                return spatially_filter_image(img, FILT)\n              Except that this version should be faster for separable filters.\n    !*/\n        );\n}\n\n\n", "meta": {"hexsha": "65d29c53576a4ed466a9dce97fa73ca63497c34a", "size": 44191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/tools/python/src/image4.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/image4.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/image4.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": 52.4211150652, "max_line_length": 210, "alphanum_fraction": 0.6439320224, "num_tokens": 11264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.05261895056211689, "lm_q1q2_score": 0.023646568815880654}}
{"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_STD_CONCEPT_INCLUDE\n#define MTL_STD_CONCEPT_INCLUDE\n\n#ifdef __GXX_CONCEPTS__\n#  include <concepts>\n#else\n// Use Joel de Guzman's return type deduction\n#  include <boost/numeric/ublas/detail/returntype_deduction.hpp>\n#  include <boost/mpl/at.hpp>\n#  include <boost/numeric/linear_algebra/pseudo_concept.hpp>\n#endif\n\n// #include <boost/numeric/mtl/utility/is_what.hpp>         -> leads to cyclic inclusions\n// #include <boost/numeric/mtl/operation/mult_result.hpp>\n\nnamespace mtl {\n\n/**\n * \\defgroup Concepts Concepts\n */\n/*@{*/\n\n\n    // Use Joel de Guzman's return type deduction\n    // Adapted from uBLAS\n    // Differences: \n    //   - Separate types for all operations\n    //   - result_type like in concept\n\n    /// Concept Addable: Binary operation\n    /** In concept-free compilations also used for return type deduction.\n        If available use decltype instead of meta-programming. */ \n    template<class X, class Y>\n    struct Addable\n    {\n#    ifdef MTL_WITH_AUTO\n\t/// Result of addition\n\ttypedef decltype(X() + Y())   result_type;\n#    else\n      private:\n        typedef boost::numeric::ublas::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        static const std::size_t size = sizeof (\n                   boost::numeric::ublas::type_deduction_detail::test<\n                        typename base_type::x_type\n                      , typename base_type::y_type\n\t\t   >(x + y)     \n                );\n\n        static const std::size_t index = (size / sizeof (char)) - 1;\n        typedef typename boost::mpl::at_c<\n    \ttypename base_type::types, index>::type id;\n      public:\n\t/// Result of addition\n        typedef typename id::type result_type;\n#    endif\n    };\n\n\n    /// Concept Subtractable: Binary operation\n    /** In concept-free compilations also used for return type deduction.\n        If available use decltype instead of meta-programming. */ \n    template<class X, class Y>\n    struct Subtractable\n    {\n#    ifdef MTL_WITH_AUTO\n\t/// Result of addition\n\ttypedef decltype(X() - Y())   result_type;\n#    else\n      private:\n        typedef boost::numeric::ublas::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        static const std::size_t size = sizeof (\n                   boost::numeric::ublas::type_deduction_detail::test<\n                        typename base_type::x_type\n                      , typename base_type::y_type\n\t\t   >(x - y)     \n                );\n\n        static const std::size_t index = (size / sizeof (char)) - 1;\n        typedef typename boost::mpl::at_c<\n    \ttypename base_type::types, index>::type id;\n      public:\n\t/// Result of subtraction\n        typedef typename id::type result_type;\n#    endif\n    };\n\n\n    /// Concept Multiplicable: Binary operation\n    /** In concept-free compilations also used for return type deduction.\n        If available use decltype instead of meta-programming.  */ \n    template<class X, class Y>\n    struct Multiplicable\n    {\n#    ifdef MTL_WITH_AUTO\n\t/// Result of multiplication\n\ttypedef decltype(X() * Y())   result_type;\n#    else\n      private:\n        typedef boost::numeric::ublas::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        static const std::size_t size = sizeof (\n                   boost::numeric::ublas::type_deduction_detail::test<\n                        typename base_type::x_type\n                      , typename base_type::y_type\n                    >(x * y)     \n                );\n\n        static const std::size_t index = (size / sizeof (char)) - 1;\n        typedef typename boost::mpl::at_c<\n    \ttypename base_type::types, index>::type id;\n      public:\n\t/// Result of multiplication\n        typedef typename id::type result_type;\n#    endif\n    };\n\n    /// Concept Divisible: Binary operation\n    /** In concept-free compilations also used for return type deduction.\n        If available use decltype instead of meta-programming.  */ \n    template<class X, class Y>\n    struct Divisible\n    {\n#    ifdef MTL_WITH_AUTO\n\t/// Result of division\n\ttypedef decltype(X() / Y())   result_type;\n#    else\n      private:\n        typedef boost::numeric::ublas::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        static const std::size_t size = sizeof (\n                   boost::numeric::ublas::type_deduction_detail::test<\n                        typename base_type::x_type\n                      , typename base_type::y_type\n                    >(x / y)     \n                );\n\n        static const std::size_t index = (size / sizeof (char)) - 1;\n        typedef typename boost::mpl::at_c<\n    \ttypename base_type::types, index>::type id;\n      public:\n\t/// Result of division\n        typedef typename id::type result_type;\n#    endif\n    };\n        \n\n    /// Concept UnaryFunctor\n    /** With concept corresponds to std::Callable1 */ \n    template <typename T>\n    struct UnaryFunctor\n    {\n\t/// Result type of operator()\n\ttypedef associated_type result_type;\n\t\n\t/// The unary  function\n\tresult_type operator()(T);\n    };\n\n\n    /// Concept UnaryStaticFunctor\n    /**\n       \\par Refinement of:\n       - std::Callable1 < T >\n    */\n    template <typename T>\n    struct UnaryStaticFunctor\n      : public UnaryFunctor<T>\n    {\n\t/// Result type of apply\n\ttypedef associated_type result_type;\n\t\n\t/// The unary static function\n\tstatic result_type apply(T);\n\n\t/// The application operator behaves like apply. Exists for compatibility with UnaryFunctor\n\tresult_type operator()(T);\n    };\n\n    /// Concept BinaryFunctor\n    /** With concept corresponds to std::Callable2 */ \n    template <typename T, typename U>\n    struct BinaryFunctor\n    {\n\t/// Result type of operator()\n\ttypedef associated_type result_type;\n\t\n\t/// The unary  function\n\tresult_type operator()(T, U);\n    };\n\n    /// Concept BinaryStaticFunctor\n    /**\n       \\par Refinement of:\n       - BinaryFunctor <T, U>\n    */\n    template <typename T, typename U>\n    struct BinaryStaticFunctor\n\t: public BinaryFunctor <T, U>\n    {\n\t/// Result type of apply\n\ttypedef associated_type result_type;\n\t\n\t/// The unary static function\n\tstatic result_type apply(T, U);\n\n\t/// The application operator behaves like apply. Exists for compatibility with BinaryFunctor\n\tresult_type operator()(T, U);\n    };\n\n/*@}*/ // end of group Concepts\n\n} // namespace mtl\n\n#endif // MTL_STD_CONCEPT_INCLUDE\n", "meta": {"hexsha": "42df7737446475ee118b94c5361c9d717bb4a14f", "size": 7103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/concept/std_concept.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/mtl/concept/std_concept.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/mtl/concept/std_concept.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4849785408, "max_line_length": 94, "alphanum_fraction": 0.6343798395, "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111085480195975, "lm_q2_score": 0.05749328404888364, "lm_q1q2_score": 0.02363611315070843}}
{"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#ifndef BOOST_GRAPH_STRONG_COMPONENTS_HPP\n#define BOOST_GRAPH_STRONG_COMPONENTS_HPP\n\n#include <stack>\n#include <boost/config.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/type_traits/conversion_traits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/graph/overloading.hpp>\n#include <boost/concept/assert.hpp>\n\nnamespace boost {\n\n  //==========================================================================\n  // This is Tarjan's algorithm for strongly connected components\n  // from his paper \"Depth first search and linear graph algorithms\".\n  // It calculates the components in a single application of DFS.\n  // We implement the algorithm as a dfs-visitor.\n\n  namespace detail {\n    \n    template <typename ComponentMap, typename RootMap, typename DiscoverTime,\n              typename Stack>\n    class tarjan_scc_visitor : public dfs_visitor<> \n    {\n      typedef typename property_traits<ComponentMap>::value_type comp_type;\n      typedef typename property_traits<DiscoverTime>::value_type time_type;\n    public:\n      tarjan_scc_visitor(ComponentMap comp_map, RootMap r, DiscoverTime d, \n                         comp_type& c_, Stack& s_)\n        : c(c_), comp(comp_map), root(r), discover_time(d),\n          dfs_time(time_type()), s(s_) { }\n\n      template <typename Graph>\n      void discover_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                           const Graph&) {\n        put(root, v, v);\n        put(comp, v, (std::numeric_limits<comp_type>::max)());\n        put(discover_time, v, dfs_time++);\n        s.push(v);\n      }\n      template <typename Graph>\n      void finish_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                         const Graph& g) {\n        typename graph_traits<Graph>::vertex_descriptor w;\n        typename graph_traits<Graph>::out_edge_iterator ei, ei_end;\n        for (boost::tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei) {\n          w = target(*ei, g);\n          if (get(comp, w) == (std::numeric_limits<comp_type>::max)())\n            put(root, v, this->min_discover_time(get(root,v), get(root,w)));\n        }\n        if (get(root, v) == v) {\n          do {\n            w = s.top(); s.pop();\n            put(comp, w, c);\n          } while (w != v);\n          ++c;\n        }\n      }\n    private:\n      template <typename Vertex>\n      Vertex min_discover_time(Vertex u, Vertex v) {\n        return get(discover_time, u) < get(discover_time,v) ? u : v;\n      }\n\n      comp_type& c;\n      ComponentMap comp;\n      RootMap root;\n      DiscoverTime discover_time;\n      time_type dfs_time;\n      Stack& s;\n    };\n    \n    template <class Graph, class ComponentMap, class RootMap,\n              class DiscoverTime, class P, class T, class R>\n    typename property_traits<ComponentMap>::value_type\n    strong_components_impl\n      (const Graph& g,    // Input\n       ComponentMap comp, // Output\n       // Internal record keeping\n       RootMap root, \n       DiscoverTime discover_time,\n       const bgl_named_params<P, T, R>& params)\n    {\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<ComponentMap, Vertex> ));\n      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<RootMap, Vertex> ));\n      typedef typename property_traits<RootMap>::value_type RootV;\n      BOOST_CONCEPT_ASSERT(( ConvertibleConcept<RootV, Vertex> ));\n      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<DiscoverTime, Vertex> ));\n\n      typename property_traits<ComponentMap>::value_type total = 0;\n\n      std::stack<Vertex> s;\n      detail::tarjan_scc_visitor<ComponentMap, RootMap, DiscoverTime, \n        std::stack<Vertex> > \n        vis(comp, root, discover_time, total, s);\n      depth_first_search(g, params.visitor(vis));\n      return total;\n    }\n\n    //-------------------------------------------------------------------------\n    // The dispatch functions handle the defaults for the rank and discover\n    // time property maps.\n    // dispatch with class specialization to avoid VC++ bug\n\n    template <class DiscoverTimeMap>\n    struct strong_comp_dispatch2 {\n      template <class Graph, class ComponentMap, class RootMap, class P, class T, class R>\n      inline static typename property_traits<ComponentMap>::value_type\n      apply(const Graph& g,\n            ComponentMap comp,\n            RootMap r_map,\n            const bgl_named_params<P, T, R>& params,\n            DiscoverTimeMap time_map)\n      {\n        return strong_components_impl(g, comp, r_map, time_map, params);\n      }\n    };\n\n\n    template <>\n    struct strong_comp_dispatch2<param_not_found> {\n      template <class Graph, class ComponentMap, class RootMap,\n                class P, class T, class R>\n      inline static typename property_traits<ComponentMap>::value_type\n      apply(const Graph& g,\n            ComponentMap comp,\n            RootMap r_map,\n            const bgl_named_params<P, T, R>& params,\n            param_not_found)\n      {\n        typedef typename graph_traits<Graph>::vertices_size_type size_type;\n        size_type       n = num_vertices(g) > 0 ? num_vertices(g) : 1;\n        std::vector<size_type> time_vec(n);\n        return strong_components_impl\n          (g, comp, r_map,\n           make_iterator_property_map(time_vec.begin(), choose_const_pmap\n                                      (get_param(params, vertex_index),\n                                       g, vertex_index), time_vec[0]),\n           params);\n      }\n    };\n\n    template <class Graph, class ComponentMap, class RootMap,\n              class P, class T, class R, class DiscoverTimeMap>\n    inline typename property_traits<ComponentMap>::value_type\n    scc_helper2(const Graph& g,\n                ComponentMap comp,\n                RootMap r_map,\n                const bgl_named_params<P, T, R>& params,\n                DiscoverTimeMap time_map)\n    {\n      return strong_comp_dispatch2<DiscoverTimeMap>::apply(g, comp, r_map, params, time_map);\n    }\n\n    template <class RootMap>\n    struct strong_comp_dispatch1 {\n\n      template <class Graph, class ComponentMap, class P, class T, class R>\n      inline static typename property_traits<ComponentMap>::value_type\n      apply(const Graph& g,\n            ComponentMap comp,\n            const bgl_named_params<P, T, R>& params,\n            RootMap r_map)\n      {\n        return scc_helper2(g, comp, r_map, params, get_param(params, vertex_discover_time));\n      }\n    };\n    template <>\n    struct strong_comp_dispatch1<param_not_found> {\n\n      template <class Graph, class ComponentMap, \n                class P, class T, class R>\n      inline static typename property_traits<ComponentMap>::value_type\n      apply(const Graph& g,\n            ComponentMap comp,\n            const bgl_named_params<P, T, R>& params,\n            param_not_found)\n      {\n        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n        typename std::vector<Vertex>::size_type\n          n = num_vertices(g) > 0 ? num_vertices(g) : 1;\n        std::vector<Vertex> root_vec(n);\n        return scc_helper2\n          (g, comp, \n           make_iterator_property_map(root_vec.begin(), choose_const_pmap\n                                      (get_param(params, vertex_index),\n                                       g, vertex_index), root_vec[0]),\n           params, \n           get_param(params, vertex_discover_time));\n      }\n    };\n\n    template <class Graph, class ComponentMap, class RootMap,\n              class P, class T, class R>\n    inline typename property_traits<ComponentMap>::value_type\n    scc_helper1(const Graph& g,\n               ComponentMap comp,\n               const bgl_named_params<P, T, R>& params,\n               RootMap r_map)\n    {\n      return detail::strong_comp_dispatch1<RootMap>::apply(g, comp, params,\n                                                           r_map);\n    }\n\n  } // namespace detail \n\n  template <class Graph, class ComponentMap, \n            class P, class T, class R>\n  inline typename property_traits<ComponentMap>::value_type\n  strong_components(const Graph& g, ComponentMap comp,\n                    const bgl_named_params<P, T, R>& params\n                    BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph, vertex_list_graph_tag))\n  {\n    typedef typename graph_traits<Graph>::directed_category DirCat;\n    BOOST_STATIC_ASSERT((is_convertible<DirCat*, directed_tag*>::value == true));\n    return detail::scc_helper1(g, comp, params, \n                               get_param(params, vertex_root_t()));\n  }\n\n  template <class Graph, class ComponentMap>\n  inline typename property_traits<ComponentMap>::value_type\n  strong_components(const Graph& g, ComponentMap comp\n                    BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph, vertex_list_graph_tag))\n  {\n    typedef typename graph_traits<Graph>::directed_category DirCat;\n    BOOST_STATIC_ASSERT((is_convertible<DirCat*, directed_tag*>::value == true));\n    bgl_named_params<int, int> params(0);\n    return strong_components(g, comp, params);\n  }\n\n  template <typename Graph, typename ComponentMap, typename ComponentLists>\n  void build_component_lists\n    (const Graph& g,\n     typename graph_traits<Graph>::vertices_size_type num_scc,\n     ComponentMap component_number,\n     ComponentLists& components)\n  {\n    components.resize(num_scc);\n    typename graph_traits<Graph>::vertex_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n      components[component_number[*vi]].push_back(*vi);\n  }\n\n\n} // namespace boost\n\n#include <queue>\n#include <vector>\n#include <boost/graph/transpose_graph.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/graph/connected_components.hpp> // for components_recorder\n\nnamespace boost {\n\n  //==========================================================================\n  // This is the version of strongly connected components from\n  // \"Intro. to Algorithms\" by Cormen, Leiserson, Rivest, which was\n  // adapted from \"Data Structure and Algorithms\" by Aho, Hopcroft,\n  // and Ullman, who credit the algorithm to S.R. Kosaraju and M. Sharir.\n  // The algorithm is based on computing DFS forests the graph\n  // and its transpose.\n\n  // This algorithm is slower than Tarjan's by a constant factor, uses\n  // more memory, and puts more requirements on the graph type.\n\n  template <class Graph, class DFSVisitor, class ComponentsMap,\n            class DiscoverTime, class FinishTime,\n            class ColorMap>\n  typename property_traits<ComponentsMap>::value_type\n  kosaraju_strong_components(Graph& G, ComponentsMap c,\n                             FinishTime finish_time, ColorMap color)\n  {\n    BOOST_CONCEPT_ASSERT(( MutableGraphConcept<Graph> ));\n    // ...\n    \n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n    typename property_traits<FinishTime>::value_type time = 0;\n    depth_first_search\n     (G, make_dfs_visitor(stamp_times(finish_time, time, on_finish_vertex())),\n      color);\n\n    Graph G_T(num_vertices(G));\n    transpose_graph(G, G_T);\n\n    typedef typename property_traits<ComponentsMap>::value_type count_type;\n\n    count_type c_count(0);\n    detail::components_recorder<ComponentsMap>\n      vis(c, c_count);\n\n    // initialize G_T\n    typename graph_traits<Graph>::vertex_iterator ui, ui_end;\n    for (boost::tie(ui, ui_end) = vertices(G_T); ui != ui_end; ++ui)\n      put(color, *ui, Color::white());\n\n    typedef typename property_traits<FinishTime>::value_type D;\n    typedef indirect_cmp< FinishTime, std::less<D> > Compare;\n\n    Compare fl(finish_time);\n    std::priority_queue<Vertex, std::vector<Vertex>, Compare > Q(fl);\n\n    typename graph_traits<Graph>::vertex_iterator i, j, iend, jend;\n    boost::tie(i, iend) = vertices(G_T);\n    boost::tie(j, jend) = vertices(G);\n    for ( ; i != iend; ++i, ++j) {\n      put(finish_time, *i, get(finish_time, *j));\n       Q.push(*i);\n    }\n\n    while ( !Q.empty() ) {\n      Vertex u = Q.top();\n      Q.pop();\n      if  (get(color, u) == Color::white()) {\n        depth_first_visit(G_T, u, vis, color);\n        ++c_count; \n      }\n    }\n    return c_count;\n  }\n\n} // namespace boost\n\n#ifdef BOOST_GRAPH_USE_MPI\n#  include <boost/graph/distributed/strong_components.hpp>\n#endif\n\n#endif // BOOST_GRAPH_STRONG_COMPONENTS_HPP\n", "meta": {"hexsha": "61345bdcb8dc7200f614c7088de45fffc132555e", "size": 12828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/strong_components.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "boost/boost/graph/strong_components.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "boost/boost/graph/strong_components.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 412.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T07:31:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:41:41.000Z", "avg_line_length": 37.3994169096, "max_line_length": 93, "alphanum_fraction": 0.6294823823, "num_tokens": 2859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.049589026144341374, "lm_q1q2_score": 0.023633120776457715}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/preprocessor/arithmetic/sub.hpp>\n#include <boost/preprocessor/list/for_each.hpp>\n#include <boost/preprocessor/punctuation/comma_if.hpp>\n#include <boost/preprocessor/repetition/repeat.hpp>\n#include <boost/preprocessor/tuple/enum.hpp>\n#include <boost/preprocessor/tuple/to_list.hpp>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"Utilities/TMPL.hpp\"\n#include \"Utilities/TypeTraits.hpp\"\n\n/// \\cond\nclass DataVector;\nnamespace EquationsOfState {\ntemplate <bool IsRelativistic>\nclass DarkEnergyFluid;\ntemplate <bool IsRelativistic>\nclass IdealFluid;\ntemplate <bool IsRelativistic>\nclass PolytropicFluid;\nclass Spectral;\n}  // namespace EquationsOfState\n/// \\endcond\n\n/// Contains all equations of state, including base class\nnamespace EquationsOfState {\n\nnamespace detail {\ntemplate <bool IsRelativistic, size_t ThermodynamicDim>\nstruct DerivedClasses {};\n\ntemplate <>\nstruct DerivedClasses<true, 1> {\n  using type = tmpl::list<Spectral, PolytropicFluid<true>>;\n};\n\ntemplate <>\nstruct DerivedClasses<false, 1> {\n  using type = tmpl::list<PolytropicFluid<false>>;\n};\n\ntemplate <>\nstruct DerivedClasses<true, 2> {\n  using type = tmpl::list<DarkEnergyFluid<true>, IdealFluid<true>>;\n};\n\ntemplate <>\nstruct DerivedClasses<false, 2> {\n  using type = tmpl::list<IdealFluid<false>>;\n};\n\n}  // namespace detail\n\n/*!\n * \\ingroup EquationsOfStateGroup\n * \\brief Base class for equations of state depending on whether or not the\n * system is relativistic, and the number of independent thermodynamic variables\n * (`ThermodynamicDim`) needed to determine the pressure.\n *\n * The template parameter `IsRelativistic` is `true` for relativistic equations\n * of state and `false` for non-relativistic equations of state.\n */\ntemplate <bool IsRelativistic, size_t ThermodynamicDim>\nclass EquationOfState;\n\n/*!\n * \\ingroup EquationsOfStateGroup\n * \\brief Base class for equations of state which need one thermodynamic\n * variable in order to determine the pressure.\n *\n * The template parameter `IsRelativistic` is `true` for relativistic equations\n * of state and `false` for non-relativistic equations of state.\n */\ntemplate <bool IsRelativistic>\nclass EquationOfState<IsRelativistic, 1>\n    : public PUP::able {\n public:\n  static constexpr bool is_relativistic = IsRelativistic;\n  static constexpr size_t thermodynamic_dim = 1;\n  using creatable_classes =\n      typename detail::DerivedClasses<IsRelativistic, 1>::type;\n\n  EquationOfState() = default;\n  EquationOfState(const EquationOfState&) = default;\n  EquationOfState& operator=(const EquationOfState&) = default;\n  EquationOfState(EquationOfState&&) = default;\n  EquationOfState& operator=(EquationOfState&&) = default;\n  ~EquationOfState() override = default;\n\n  WRAPPED_PUPable_abstract(EquationOfState);  // NOLINT\n\n  /// @{\n  /*!\n   * Computes the pressure \\f$p\\f$ from the rest mass density \\f$\\rho\\f$.\n   */\n  virtual Scalar<double> pressure_from_density(\n      const Scalar<double>& /*rest_mass_density*/) const = 0;\n  virtual Scalar<DataVector> pressure_from_density(\n      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes the rest mass density \\f$\\rho\\f$ from the specific enthalpy\n   * \\f$h\\f$.\n   */\n  virtual Scalar<double> rest_mass_density_from_enthalpy(\n      const Scalar<double>& /*specific_enthalpy*/) const = 0;\n  virtual Scalar<DataVector> rest_mass_density_from_enthalpy(\n      const Scalar<DataVector>& /*specific_enthalpy*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes the specific enthalpy \\f$h\\f$ from the rest mass density\n   * \\f$\\rho\\f$.\n   */\n  virtual Scalar<double> specific_enthalpy_from_density(\n      const Scalar<double>& /*rest_mass_density*/) const = 0;\n  virtual Scalar<DataVector> specific_enthalpy_from_density(\n      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes the specific internal energy \\f$\\epsilon\\f$ from the rest mass\n   * density \\f$\\rho\\f$.\n   */\n  virtual Scalar<double> specific_internal_energy_from_density(\n      const Scalar<double>& /*rest_mass_density*/) const = 0;\n  virtual Scalar<DataVector> specific_internal_energy_from_density(\n      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes \\f$\\chi=\\partial p / \\partial \\rho\\f$ from \\f$\\rho\\f$, where\n   * \\f$p\\f$ is the pressure and \\f$\\rho\\f$ is the rest mass density.\n   */\n  virtual Scalar<double> chi_from_density(\n      const Scalar<double>& /*rest_mass_density*/) const = 0;\n  virtual Scalar<DataVector> chi_from_density(\n      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes \\f$\\kappa p/\\rho^2=(p/\\rho^2)\\partial p / \\partial \\epsilon\\f$\n   * from \\f$\\rho\\f$, where \\f$p\\f$ is the pressure, \\f$\\rho\\f$ is the rest mass\n   * density, and \\f$\\epsilon\\f$ is the specific internal energy.\n   *\n   * The reason for not returning just\n   * \\f$\\kappa=\\partial p / \\partial \\epsilon\\f$ is to avoid division by zero\n   * for small values of \\f$\\rho\\f$ when assembling the speed of sound with\n   * some equations of state.\n   */\n  virtual Scalar<double> kappa_times_p_over_rho_squared_from_density(\n      const Scalar<double>& /*rest_mass_density*/) const = 0;\n  virtual Scalar<DataVector> kappa_times_p_over_rho_squared_from_density(\n      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;\n\n  /// The lower bound of the rest mass density that is valid for this EOS\n  virtual double rest_mass_density_lower_bound() const = 0;\n\n  /// The upper bound of the rest mass density that is valid for this EOS\n  virtual double rest_mass_density_upper_bound() const = 0;\n\n  /// The lower bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  virtual double specific_internal_energy_lower_bound(\n      const double rest_mass_density) const = 0;\n\n  /// The upper bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  virtual double specific_internal_energy_upper_bound(\n      const double rest_mass_density) const = 0;\n\n  /// The lower bound of the specific enthalpy that is valid for this EOS\n  virtual double specific_enthalpy_lower_bound() const = 0;\n};\n\n/*!\n * \\ingroup EquationsOfStateGroup\n * \\brief Base class for equations of state which need two independent\n * thermodynamic variables in order to determine the pressure.\n *\n * The template parameter `IsRelativistic` is `true` for relativistic equations\n * of state and `false` for non-relativistic equations of state.\n */\ntemplate <bool IsRelativistic>\nclass EquationOfState<IsRelativistic, 2>\n    : public PUP::able {\n public:\n  static constexpr bool is_relativistic = IsRelativistic;\n  static constexpr size_t thermodynamic_dim = 2;\n  using creatable_classes =\n      typename detail::DerivedClasses<IsRelativistic, 2>::type;\n\n  EquationOfState() = default;\n  EquationOfState(const EquationOfState&) = default;\n  EquationOfState& operator=(const EquationOfState&) = default;\n  EquationOfState(EquationOfState&&) = default;\n  EquationOfState& operator=(EquationOfState&&) = default;\n  ~EquationOfState() override = default;\n\n  WRAPPED_PUPable_abstract(EquationOfState);  // NOLINT\n\n  /// @{\n  /*!\n   * Computes the pressure \\f$p\\f$ from the rest mass density \\f$\\rho\\f$ and the\n   * specific internal energy \\f$\\epsilon\\f$.\n   */\n  virtual Scalar<double> pressure_from_density_and_energy(\n      const Scalar<double>& /*rest_mass_density*/,\n      const Scalar<double>& /*specific_internal_energy*/) const = 0;\n  virtual Scalar<DataVector> pressure_from_density_and_energy(\n      const Scalar<DataVector>& /*rest_mass_density*/,\n      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes the pressure \\f$p\\f$ from the rest mass density \\f$\\rho\\f$ and the\n   * specific enthalpy \\f$h\\f$.\n   */\n  virtual Scalar<double> pressure_from_density_and_enthalpy(\n      const Scalar<double>& /*rest_mass_density*/,\n      const Scalar<double>& /*specific_enthalpy*/) const = 0;\n  virtual Scalar<DataVector> pressure_from_density_and_enthalpy(\n      const Scalar<DataVector>& /*rest_mass_density*/,\n      const Scalar<DataVector>& /*specific_enthalpy*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes the specific enthalpy \\f$h\\f$ from the rest mass density\n   * \\f$\\rho\\f$ and the specific internal energy \\f$\\epsilon\\f$.\n   */\n  virtual Scalar<double> specific_enthalpy_from_density_and_energy(\n      const Scalar<double>& /*rest_mass_density*/,\n      const Scalar<double>& /*specific_internal_energy*/) const = 0;\n  virtual Scalar<DataVector> specific_enthalpy_from_density_and_energy(\n      const Scalar<DataVector>& /*rest_mass_density*/,\n      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes the specific internal energy \\f$\\epsilon\\f$ from the rest mass\n   * density \\f$\\rho\\f$ and the pressure \\f$p\\f$.\n   */\n  virtual Scalar<double> specific_internal_energy_from_density_and_pressure(\n      const Scalar<double>& /*rest_mass_density*/,\n      const Scalar<double>& /*pressure*/) const = 0;\n  virtual Scalar<DataVector> specific_internal_energy_from_density_and_pressure(\n      const Scalar<DataVector>& /*rest_mass_density*/,\n      const Scalar<DataVector>& /*pressure*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes \\f$\\chi=\\partial p / \\partial \\rho\\f$ from the \\f$\\rho\\f$ and\n   * \\f$\\epsilon\\f$, where \\f$p\\f$ is the pressure, \\f$\\rho\\f$ is the rest mass\n   * density, and \\f$\\epsilon\\f$ is the specific internal energy.\n   */\n  virtual Scalar<double> chi_from_density_and_energy(\n      const Scalar<double>& /*rest_mass_density*/,\n      const Scalar<double>& /*specific_internal_energy*/) const = 0;\n  virtual Scalar<DataVector> chi_from_density_and_energy(\n      const Scalar<DataVector>& /*rest_mass_density*/,\n      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;\n  /// @}\n\n  /// @{\n  /*!\n   * Computes \\f$\\kappa p/\\rho^2=(p/\\rho^2)\\partial p / \\partial \\epsilon\\f$\n   * from \\f$\\rho\\f$ and \\f$\\epsilon\\f$, where \\f$p\\f$ is the pressure,\n   * \\f$\\rho\\f$ is the rest mass density, and \\f$\\epsilon\\f$ is the specific\n   * internal energy.\n   *\n   * The reason for not returning just\n   * \\f$\\kappa=\\partial p / \\partial \\epsilon\\f$ is to avoid division by zero\n   * for small values of \\f$\\rho\\f$ when assembling the speed of sound with\n   * some equations of state.\n   */\n  virtual Scalar<double> kappa_times_p_over_rho_squared_from_density_and_energy(\n      const Scalar<double>& /*rest_mass_density*/,\n      const Scalar<double>& /*specific_internal_energy*/) const = 0;\n  virtual Scalar<DataVector>\n  kappa_times_p_over_rho_squared_from_density_and_energy(\n      const Scalar<DataVector>& /*rest_mass_density*/,\n      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;\n  /// @}\n\n  /// The lower bound of the rest mass density that is valid for this EOS\n  virtual double rest_mass_density_lower_bound() const = 0;\n\n  /// The upper bound of the rest mass density that is valid for this EOS\n  virtual double rest_mass_density_upper_bound() const = 0;\n\n  /// The lower bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  virtual double specific_internal_energy_lower_bound(\n      const double rest_mass_density) const = 0;\n\n  /// The upper bound of the specific internal energy that is valid for this EOS\n  /// at the given rest mass density \\f$\\rho\\f$\n  virtual double specific_internal_energy_upper_bound(\n      const double rest_mass_density) const = 0;\n\n  /// The lower bound of the specific enthalpy that is valid for this EOS\n  virtual double specific_enthalpy_lower_bound() const = 0;\n};\n}  // namespace EquationsOfState\n\n/// \\cond\n#define EQUATION_OF_STATE_FUNCTIONS_1D                                    \\\n  (pressure_from_density, rest_mass_density_from_enthalpy,                \\\n   specific_enthalpy_from_density, specific_internal_energy_from_density, \\\n   chi_from_density, kappa_times_p_over_rho_squared_from_density)\n\n#define EQUATION_OF_STATE_FUNCTIONS_2D                                   \\\n  (pressure_from_density_and_energy, pressure_from_density_and_enthalpy, \\\n   specific_enthalpy_from_density_and_energy,                            \\\n   specific_internal_energy_from_density_and_pressure,                   \\\n   chi_from_density_and_energy,                                          \\\n   kappa_times_p_over_rho_squared_from_density_and_energy)\n\n#define EQUATION_OF_STATE_ARGUMENTS_EXPAND(z, n, type) \\\n  BOOST_PP_COMMA_IF(n) const Scalar<type>&\n\n#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS_HELPER(r, DIM,        \\\n                                                         FUNCTION_NAME) \\\n  Scalar<double> FUNCTION_NAME(BOOST_PP_REPEAT(                         \\\n      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND, double)) const override; \\\n  Scalar<DataVector> FUNCTION_NAME(BOOST_PP_REPEAT(                     \\\n      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND, DataVector)) const override;\n\n/// \\endcond\n\n/*!\n * \\ingroup EquationsOfStateGroup\n * \\brief Macro used to generate forward declarations of member functions in\n * derived classes\n */\n#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS(DERIVED, DIM)               \\\n  BOOST_PP_LIST_FOR_EACH(                                                     \\\n      EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS_HELPER, DIM,                  \\\n      BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_ELEM(                             \\\n          BOOST_PP_SUB(DIM, 1),                                               \\\n          (EQUATION_OF_STATE_FUNCTIONS_1D, EQUATION_OF_STATE_FUNCTIONS_2D)))) \\\n                                                                              \\\n  /* clang-tidy: do not use non-const references */                           \\\n  void pup(PUP::er& p) override; /* NOLINT */                                 \\\n                                                                              \\\n  explicit DERIVED(CkMigrateMessage* /*unused*/);\n\n/// \\cond\n#define EQUATION_OF_STATE_FORWARD_ARGUMENTS(z, n, unused) \\\n  BOOST_PP_COMMA_IF(n) arg##n\n\n#define EQUATION_OF_STATE_ARGUMENTS_EXPAND_NAMED(z, n, type) \\\n  BOOST_PP_COMMA_IF(n) const Scalar<type>& arg##n\n\n#define EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER(                        \\\n    TEMPLATE, DERIVED, DATA_TYPE, DIM, FUNCTION_NAME)                       \\\n  TEMPLATE                                                                  \\\n  Scalar<DATA_TYPE> DERIVED::FUNCTION_NAME(BOOST_PP_REPEAT(                 \\\n      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND_NAMED, DATA_TYPE)) const {    \\\n    return FUNCTION_NAME##_impl(                                            \\\n        BOOST_PP_REPEAT(DIM, EQUATION_OF_STATE_FORWARD_ARGUMENTS, UNUSED)); \\\n  }\n\n#define EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER_2(r, ARGS, FUNCTION_NAME) \\\n  EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER(                                \\\n      BOOST_PP_TUPLE_ELEM(0, ARGS), BOOST_PP_TUPLE_ELEM(1, ARGS),             \\\n      BOOST_PP_TUPLE_ELEM(2, ARGS), BOOST_PP_TUPLE_ELEM(3, ARGS),             \\\n      FUNCTION_NAME)\n/// \\endcond\n\n#define EQUATION_OF_STATE_MEMBER_DEFINITIONS(TEMPLATE, DERIVED, DATA_TYPE, \\\n                                             DIM)                          \\\n  BOOST_PP_LIST_FOR_EACH(                                                  \\\n      EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER_2,                       \\\n      (TEMPLATE, DERIVED, DATA_TYPE, DIM),                                 \\\n      BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_ELEM(                          \\\n          BOOST_PP_SUB(DIM, 1),                                            \\\n          (EQUATION_OF_STATE_FUNCTIONS_1D, EQUATION_OF_STATE_FUNCTIONS_2D))))\n\n/// \\cond\n#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS_HELPER(r, DIM,        \\\n                                                              FUNCTION_NAME) \\\n  template <class DataType>                                                  \\\n  Scalar<DataType> FUNCTION_NAME##_impl(BOOST_PP_REPEAT(                     \\\n      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND, DataType)) const;\n/// \\endcond\n\n#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS(DIM)       \\\n  BOOST_PP_LIST_FOR_EACH(                                         \\\n      EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS_HELPER, DIM, \\\n      BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_ELEM(                 \\\n          BOOST_PP_SUB(DIM, 1),                                   \\\n          (EQUATION_OF_STATE_FUNCTIONS_1D, EQUATION_OF_STATE_FUNCTIONS_2D))))\n", "meta": {"hexsha": "8b257a7c09af38d25af9e0ff448166292b8ae8e3", "size": 16781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp", "max_stars_repo_name": "Shabibti/spectre", "max_stars_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:17:33.000Z", "max_issues_repo_path": "src/PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp", "max_issues_repo_name": "Shabibti/spectre", "max_issues_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_issues_repo_licenses": ["MIT"], "max_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/EquationOfState.hpp", "max_forks_repo_name": "Shabibti/spectre", "max_forks_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_forks_repo_licenses": ["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.9292682927, "max_line_length": 80, "alphanum_fraction": 0.6708181872, "num_tokens": 3926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.04958902087715876, "lm_q1q2_score": 0.023633118266225665}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <limits>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Domain/OrientationMap.hpp\"\n#include \"Utilities/TypeTraits.hpp\"\n\n/// \\cond\nnamespace PUP {\nclass er;\n}  // namespace PUP\n/// \\endcond\n\nnamespace CoordinateMaps {\n\n/// \\ingroup CoordinateMapsGroup\n///\n/// Frustum map from the cube to a rectangular frustum where the bases of the\n/// frustum are perpendicular to the z-axis. The `lower_bound` and\n/// `upper_bound` values correspond to the locations of the bases along this\n/// axis. The `face_vertices` values determine the size of the two rectangular\n/// bases along the other two axes. For example, for a frustum along the z-axis,\n/// with the lower base starting at (x,y) = (-2.0,3.0) and extending to\n/// (2.0,5.0), and with the upper base extending from (0.0,1.0) to (1.0,3.0),\n/// the corresponding value for `face_vertices` is `{{{{-2.0,3.0}}, {{2.0,5.0}},\n/// {{0.0,1.0}}, {{1.0,3.0}}}}`. The user may reorient the frustum by passing\n/// an `OrientationMap` to the constructor. If `with_equiangular_map` is true,\n/// then this coordinate map applies a tangent function mapping to the logical\n/// xi and eta coordinates.\nclass Frustum {\n public:\n  static constexpr size_t dim = 3;\n  Frustum(const std::array<std::array<double, 2>, 4>& face_vertices,\n          double lower_bound, double upper_bound,\n          OrientationMap<3> orientation_of_frustum,\n          bool with_equiangular_map = false) noexcept;\n  Frustum() = default;\n  ~Frustum() = default;\n  Frustum(Frustum&&) = default;\n  Frustum(const Frustum&) = default;\n  Frustum& operator=(const Frustum&) = default;\n  Frustum& operator=(Frustum&&) = default;\n\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 3> operator()(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  /// Returns boost::none if \\f$z\\f$ is at or beyond the \\f$z\\f$-coordinate of\n  /// the apex of the pyramid, tetrahedron, or triangular prism that is\n  /// formed by extending the `Frustum` (for a\n  /// \\f$z\\f$-oriented `Frustum`).\n  boost::optional<std::array<double, 3>> inverse(\n      const std::array<double, 3>& target_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> inv_jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  // clang-tidy: google runtime references\n  void pup(PUP::er& p) noexcept;  // NOLINT\n\n private:\n  friend bool operator==(const Frustum& lhs, const Frustum& rhs) noexcept;\n\n  OrientationMap<3> orientation_of_frustum_{};\n  double sum_midpoint_x_{std::numeric_limits<double>::signaling_NaN()};\n  double dif_midpoint_x_{std::numeric_limits<double>::signaling_NaN()};\n  double sum_half_length_x_{std::numeric_limits<double>::signaling_NaN()};\n  double dif_half_length_x_{std::numeric_limits<double>::signaling_NaN()};\n  double sum_midpoint_y_{std::numeric_limits<double>::signaling_NaN()};\n  double dif_midpoint_y_{std::numeric_limits<double>::signaling_NaN()};\n  double sum_half_length_y_{std::numeric_limits<double>::signaling_NaN()};\n  double dif_half_length_y_{std::numeric_limits<double>::signaling_NaN()};\n  double midpoint_z_{std::numeric_limits<double>::signaling_NaN()};\n  double half_length_z_{std::numeric_limits<double>::signaling_NaN()};\n  bool with_equiangular_map_{false};\n};\n\nbool operator!=(const Frustum& lhs, const Frustum& rhs) noexcept;\n}  // namespace CoordinateMaps\n", "meta": {"hexsha": "cbd1281cf151c569c0ec62833044f468b3cefeaf", "size": 3689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/Frustum.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/Domain/CoordinateMaps/Frustum.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/Domain/CoordinateMaps/Frustum.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": 40.097826087, "max_line_length": 80, "alphanum_fraction": 0.7205204663, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796659321432, "lm_q2_score": 0.04958901771684945, "lm_q1q2_score": 0.02363311749739924}}
{"text": "/*\nAuthors: Deepak Kumaraswamy, Kanav Gupta\nCopyright:\nCopyright (c) 2022 Microsoft Research\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:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"utils.h\"\n#include \"array.h\"\n#include \"comms.h\"\n#include <assert.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n\nvoid MatAdd(int s1, int s2, GroupElement *A, GroupElement* B, GroupElement *C)\n{\n    for (int i = 0; i < s1; i++)\n    {\n        for (int j = 0; j < s2; j++)\n        {\n            Arr2DIdxRowM(C, s1, s2, i, j).value = Arr2DIdxRowM(A, s1, s2, i, j).value + Arr2DIdxRowM(B, s1, s2, i, j).value;\n        }\n    }\n}\n\nvoid MatAdd4(int s0, int s1, int s2, int s3, GroupElement* A, GroupElement* B, GroupElement* C)\n{\n    for (int i = 0; i < s0; i++)\n    {\n        for (int j = 0; j < s1; j++)\n        {\n            for (int k = 0; k < s2; k++)\n            {\n                for (int l = 0; l < s3; l++)\n                {\n                    Arr4DIdxRowM(C, s0, s1, s2, s3, i, j, k, l).value = Arr4DIdxRowM(A, s0, s1, s2, s3, i, j, k, l).value + Arr4DIdxRowM(B, s0, s1, s2, s3, i, j, k, l).value;\n                }\n            }\n        }\n    }\n}\n\nvoid MatSub(int s1, int s2, GroupElement *A, GroupElement* B, GroupElement *C)\n{\n    for (int i = 0; i < s1; i++)\n    {\n        for (int j = 0; j < s2; j++)\n        {\n            Arr2DIdxRowM(C, s1, s2, i, j).value = Arr2DIdxRowM(A, s1, s2, i, j).value - Arr2DIdxRowM(B, s1, s2, i, j).value;\n        }\n    }\n}\n\nvoid MatSub4(int s0, int s1, int s2, int s3, GroupElement* A, GroupElement* B, GroupElement* C)\n{\n    for (int i = 0; i < s0; i++)\n    {\n        for (int j = 0; j < s1; j++)\n        {\n            for (int k = 0; k < s2; k++)\n            {\n                for (int l = 0; l < s3; l++)\n                {\n                    Arr4DIdxRowM(C, s0, s1, s2, s3, i, j, k, l).value = Arr4DIdxRowM(A, s0, s1, s2, s3, i, j, k, l).value - Arr4DIdxRowM(B, s0, s1, s2, s3, i, j, k, l).value;\n                }\n            }\n        }\n    }\n}\n\nvoid matmul_cleartext_eigen(int dim1, int dim2, int dim3, GroupElement *inA,\n                            GroupElement *inB, GroupElement *outC) {\n  Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_A(dim1, dim2);\n  Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_B(dim2, dim3);\n  Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_C(dim1, dim3);\n\n  for (int i = 0; i < dim1; i++) {\n    for (int j = 0; j < dim2; j++) {\n      eigen_A(i, j) = Arr2DIdxRowM(inA, dim1, dim2, i, j).value;\n    }\n  }\n  for (int i = 0; i < dim2; i++) {\n    for (int j = 0; j < dim3; j++) {\n      eigen_B(i, j) = Arr2DIdxRowM(inB, dim2, dim3, i, j).value;\n    }\n  }\n  eigen_C = eigen_A * eigen_B;\n  for (int i = 0; i < dim1; i++) {\n    for (int j = 0; j < dim3; j++) {\n      Arr2DIdxRowM(outC, dim1, dim3, i, j).value = eigen_C(i, j);\n    }\n  }\n}\n\nvoid MatMul(int s1, int s2, int s3, GroupElement *A, GroupElement* B, GroupElement *C)\n{\n    // for (int i = 0; i < s1; i++)\n    // {\n    //     for (int k = 0; k < s3; k++)\n    //     {\n    //         Arr2DIdxRowM(C, s1, s3, i, k).value = 0;\n    //         for (int j = 0; j < s2; j++)\n    //         {\n    //             Arr2DIdxRowM(C, s1, s3, i, k).value = Arr2DIdxRowM(C, s1, s3, i, k).value + Arr2DIdxRowM(A, s1, s2, i, j).value * Arr2DIdxRowM(B, s2, s3, j, k).value;\n    //         }\n    //     }\n    // }\n    matmul_cleartext_eigen(s1, s2, s3, A, B, C);\n}\n\nvoid Conv2DReshapeFilter(int FH, int FW, int CI, int CO, GroupElement* filter, GroupElement* reshapedFilter)\n{\n    for(int co = 0; co < CO; co++){\n        for(int fh = 0; fh < FH; fh++){\n            for(int fw = 0; fw < FW; fw++){\n                for(int ci = 0; ci < CI; ci++){\n                    Arr2DIdxRowM(reshapedFilter, CO, FH*FW*CI, co, (fh*FW*CI) + (fw*CI) + ci).value = Arr4DIdxRowM(filter, FH, FW, CI, CO, fh, fw, ci, co).value;\n                }\n            }\n        }\n    }\n}\n\nvoid Conv2DReshapeInput(int N, int H, int W, int CI, int FH, int FW, int zPadHLeft, int zPadHRight, int zPadWLeft, int zPadWRight, int strideH, int strideW, int RRows, int RCols, GroupElement *inputArr, GroupElement *outputArr)\n{\n    int linIdxFilterMult = 0;\n\tfor (int n = 0; n < N; n++){\n\t\tint leftTopCornerH = 0 - zPadHLeft;\n\t\tint extremeRightBottomCornerH = H - 1 + zPadHRight;\n\t\twhile((leftTopCornerH + FH - 1) <= extremeRightBottomCornerH){\n\t\t\tint leftTopCornerW = 0 - zPadWLeft;\n\t\t\tint extremeRightBottomCornerW = W - 1 + zPadWRight;\n\t\t\twhile((leftTopCornerW + FW - 1) <= extremeRightBottomCornerW){\n\n\t\t\t\tfor (int fh = 0; fh < FH; fh++){\n\t\t\t\t\tfor (int fw = 0; fw < FW; fw++){\n\t\t\t\t\t\tint curPosH = leftTopCornerH + fh;\n\t\t\t\t\t\tint curPosW = leftTopCornerW + fw;\n\t\t\t\t\t\tfor (int ci = 0; ci < CI; ci++){\n\t\t\t\t\t\t\tif ((((curPosH < 0) || (curPosH >= H)) || ((curPosW < 0) || (curPosW >= W)))){\n\t\t\t\t\t\t\t\tArr2DIdxRowM(outputArr, RRows, RCols,(fh*FW*CI) + (fw*CI) + ci, linIdxFilterMult).value = 0L;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tArr2DIdxRowM(outputArr, RRows, RCols,(fh*FW*CI) + (fw*CI) + ci, linIdxFilterMult).value = Arr4DIdxRowM(inputArr, N, H, W, CI, n, curPosH, curPosW, ci).value;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlinIdxFilterMult = linIdxFilterMult + 1;\n\t\t\t\tleftTopCornerW = leftTopCornerW + strideW;\n\t\t\t}\n\n\t\t\tleftTopCornerH = leftTopCornerH + strideH;\n\t\t}\n\t}\n}\n\nvoid Conv2DReshapeOutput(int N, int finalH, int finalW, int CO, GroupElement *inputArr, GroupElement *outputArr)\n{\n    for (int co = 0; co < CO; ++co){\n\t\tfor (int n = 0; n < N; ++n){\n\t\t\tfor(int h = 0; h < finalH; ++h){\n\t\t\t\tfor (int w = 0; w < finalW; ++w){\n\t\t\t\t\tArr4DIdxRowM(outputArr, N, finalH, finalW, CO, n, h, w, co).value = Arr2DIdxRowM(inputArr, CO, N*finalH*finalW, co, (n*finalH*finalW) + (h*finalW) + w).value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\nvoid PrintMatrix(matrix<GroupElement> matrix)\n{\n    for(int i=0; i<matrix.size(); i++){\n        for(int j=0; j<matrix[0].size(); j++){\n            std::cout << matrix[i][j].value << \" \";\n        }\n        std::cout << std::endl;\n    }\n}\n\nvoid Conv2DPlaintext(int N, int H, int W, int CI, \n\t\t\t\t   int FH, int FW, int CO, \n\t\t\t\t   int zPadHLeft, int zPadHRight, int zPadWLeft, int zPadWRight, \n\t\t\t\t   int strideH, int strideW, \n\t\t\t\t   GroupElement *inputArr, \n\t\t\t\t   GroupElement * filterArr, \n\t\t\t\t   GroupElement * outArr)\n{\n    int reshapedFilterRows = CO;\n\tint reshapedFilterCols = FH*FW*CI;\n\tint reshapedIPRows = FH*FW*CI;\n\tint newH = (((H + (zPadHLeft+zPadHRight) - FH)/strideH) + 1);\n\tint newW = (((W + (zPadWLeft+zPadWRight) - FW)/strideW) + 1);\n\tint reshapedIPCols = N * newH * newW;\n\n    GroupElement *filterReshaped = make_array<GroupElement>(reshapedFilterRows, reshapedFilterCols);\n\tGroupElement *inputReshaped = make_array<GroupElement>(reshapedIPRows, reshapedIPCols);\n\tGroupElement *matmulOP = make_array<GroupElement>(reshapedFilterRows, reshapedIPCols);\n    \n    Conv2DReshapeInput(N, H, W, CI, FH, FW, zPadHLeft, zPadHRight, zPadWLeft, zPadWRight, strideH, strideW, reshapedIPRows, reshapedIPCols, inputArr, inputReshaped);\n    Conv2DReshapeFilter(FH, FW, CI, CO, filterArr, filterReshaped);\n    MatMul(reshapedFilterRows, reshapedFilterCols, reshapedIPCols, filterReshaped, inputReshaped, matmulOP);\n    Conv2DReshapeOutput(N, newH, newW, CO, matmulOP, outArr);\n\n    delete[] filterReshaped;\n    delete[] inputReshaped;\n    delete[] matmulOP;\n\n}\n\nvoid VecCopy(int s, GroupElement *input, GroupElement *output)\n{\n    for(int i = 0; i < s; i++){\n        output[i].value = input[i].value;\n    }\n}\n\nvoid MatCopy(int s1, int s2, GroupElement *input, GroupElement *output){\n    VecCopy(s1*s2, input, output);\n}\n\n// C = C - A*B\nvoid MatSubMul(int s1, int s2, int s3, GroupElement *A, GroupElement* B, GroupElement *C)\n{\n    for (int i = 0; i < s1; i++)\n    {\n        for (int k = 0; k < s3; k++)\n        {\n            for (int j = 0; j < s2; j++)\n            {\n                Arr2DIdxRowM(C, s1, s3, i, k).value = Arr2DIdxRowM(C, s1, s3, i, k).value - Arr2DIdxRowM(A, s1, s2, i, j).value * Arr2DIdxRowM(B, s2, s3, j, k).value;\n            }\n        }\n    }\n}\n\n// C = C + A*B\nvoid MatAddMul(int s1, int s2, int s3, GroupElement *A, GroupElement* B, GroupElement *C)\n{\n    for (int i = 0; i < s1; i++)\n    {\n        for (int k = 0; k < s3; k++)\n        {\n            for (int j = 0; j < s2; j++)\n            {\n                Arr2DIdxRowM(C, s1, s3, i, k).value = Arr2DIdxRowM(C, s1, s3, i, k).value + Arr2DIdxRowM(A, s1, s2, i, j).value * Arr2DIdxRowM(B, s2, s3, j, k).value;\n            }\n        }\n    }\n}\n\nvoid MatCopy4(int s1, int s2, int s3, int s4, GroupElement *input, GroupElement *output){\n    for(int i = 0; i < s1; i++)\n    {\n        for(int j = 0; j < s2; j++)\n        {\n            for(int k = 0; k < s3; k++)\n            {\n                for(int l = 0; l < s4; l++)\n                {\n                    Arr4DIdxRowM(output, s1, s2, s3, s4, i, j, k, l).value = Arr4DIdxRowM(input, s1, s2, s3, s4, i, j, k, l).value;\n                }\n            }\n        }\n    }\n}\n\nvoid MatFinalize4(int s1, int s2, int s3, int s4, GroupElement *input)\n{\n    for(int i = 0; i < s1; i++)\n    {\n        for(int j = 0; j < s2; j++)\n        {\n            for(int k = 0; k < s3; k++)\n            {\n                for(int l = 0; l < s4; l++)\n                {\n                    mod(Arr4DIdxRowM(input, s1, s2, s3, s4, i, j, k, l));\n                }\n            }\n        }\n    }\n}\n\nstd::vector<GroupElement> generateOffsetPolynomial(int bitsize, const std::vector<GroupElement> &poly, GroupElement rin)\n{\n    // given input coeffs of poly(x), output coeffs of poly(x - rin)\n    int n = poly.size() - 1;\n\n    // make sure rin has correct bitsize\n    rin = GroupElement(rin.value, bitsize);\n\n    GroupElement binomials[n + 1][n + 1];\n    for (int i = 0; i < n + 1; ++i) {\n        for(int j = 0; j < n + 1; ++j) {\n            binomials[i][j] = 0;\n        }\n    }\n    binomials[0][0] = GroupElement(1, bitsize);\n    for (int i = 1; i <= n; ++i)\n    {\n        binomials[i][0] = GroupElement(1, bitsize);\n        for (int j = 1; j < i; ++j)\n        {\n            // calculate iCj\n            binomials[i][j] = binomials[i - 1][j - 1] + binomials[i - 1][j];\n        }\n        binomials[i][i] = GroupElement(1, bitsize);\n    }\n\n    std::vector<GroupElement> coeffs(n + 1);\n    for (int i = n; i >= 0; --i)\n    {\n        GroupElement val = GroupElement(0, bitsize);\n        for (int k = i; k <= n; ++k)\n        {\n            GroupElement t = binomials[k][i] * pow(rin, k - i) * poly[n - k];\n            if ((k - i) % 2 == 1)\n            {\n                t = -t;\n            }\n            val = val + t;\n        }\n        coeffs[n - i] = val;\n    }\n    return coeffs;\n}\n\nstd::vector<GroupElement> generateOffsetPolynomial_bitsize_accurate(int final_bitsize, const std::vector<GroupElement> &poly, GroupElement rin)\n{\n\n    /* for the special case where poly coefficients are set to bitsize just sufficient \n    final_bitsize is usually 64*/\n\n    // given input coeffs of poly(x), output coeffs of poly(x - rin)\n    int n = poly.size() - 1;\n\n    // make sure rin has largest bitsize\n    auto rin_upscaled = changeBitsize(rin, final_bitsize);\n\n    GroupElement binomials[n + 1][n + 1];\n    for (int i = 0; i < n + 1; ++i) {\n        for(int j = 0; j < n + 1; ++j) {\n            binomials[i][j] = 0;\n        }\n    }\n    binomials[0][0] = GroupElement(1, final_bitsize);\n    for (int i = 1; i <= n; ++i)\n    {\n        binomials[i][0] = GroupElement(1, final_bitsize);\n        for (int j = 1; j < i; ++j)\n        {\n            // calculate iCj\n            binomials[i][j] = binomials[i - 1][j - 1] + binomials[i - 1][j];\n        }\n        binomials[i][i] = GroupElement(1, final_bitsize);\n    }\n\n    std::vector<GroupElement> coeffs(n + 1);\n    for (int i = n; i >= 0; --i)\n    {\n        // val will represent coeffs[n-i] so it should have same bitsize as poly[n-i]\n        int cur_bitsize = poly[n - i].bitsize;\n        GroupElement val = GroupElement(0, cur_bitsize);\n        for (int k = i; k <= n; ++k)\n        {\n            // first do mult in 64 bits, then set to correct bitsize\n            GroupElement t = binomials[k][i] * pow(rin, k - i) * changeBitsize(poly[n - k], cur_bitsize);\n            if ((k - i) % 2 == 1)\n            {\n                t = -t;\n            }\n            t = changeBitsize(t, cur_bitsize);\n            val = val + t;\n        }\n        coeffs[n - i] = val;\n    }\n    return coeffs;\n}\n\nGroupElement evalPoly(std::vector<GroupElement> poly, GroupElement inp)\n{\n    int inpB = inp.bitsize, coefB = poly[0].bitsize, degree = poly.size() - 1;\n    int B = inpB;\n    if (inpB != coefB) B = coefB;\n    GroupElement res(0, B);\n    GroupElement curr(1, B);\n    for (int i = degree; i >= 0; --i)\n    {\n        res = res + curr * poly[i];\n        curr = curr * inp;\n    }\n    return res;\n}\n\nGroupElement changeBitsize(GroupElement x, int newbitsize) {\n    int oldbitsize = x.bitsize;\n    if (oldbitsize == newbitsize) {\n        return x;\n    }\n    else if (oldbitsize > newbitsize) {\n        return GroupElement(x.value, newbitsize);\n    }\n    else {\n        // oldbitsize < newbitsize\n        // replace all bits to left of msb(x) with msb(x)\n        uint8_t msb = x[0];\n\n        GroupElement new_x(x.value, newbitsize);\n\n        if (msb == 0) return new_x;\n\n        // msb(x) is 1\n        // std::cout << \"msb is 1\" << std::endl;\n        for (int i = oldbitsize; i < newbitsize; i++) {\n            new_x.value = new_x.value | ((uint64_t)1 << i);\n        }\n        return new_x;\n    }\n}\n\nGroupElement signedDivide(GroupElement x, GroupElement y)\n {\n    // assumes that underlying signed value of y is positive\n    // todo: instead of recomputing N every time, store it in GE? what are the tradeoffs?\n\n    assert(x.bitsize == y.bitsize);\n    assert(x.bitsize <= 64);\n    GroupElement N(0, x.bitsize);\n\n    int64_t value, num, den;\n    num = static_cast<int64_t>(x.value);\n    den = static_cast<int64_t>(y.value);\n\n    if (x.bitsize == 64){\n        value = num / den;\n    }\n    else {\n        N.value = ((uint64_t)1 << (x.bitsize));\n        if (x.value >= (N.value >> 1)) {\n            num = num - N.value;\n        }\n        value = num / den;\n    }\n\n    // -5/3 in c++ returns -1 but we want ans -2\n    if (den * value > num) {\n        value = value - 1;\n    }\n\n    return GroupElement(value, x.bitsize);\n\n }\n\n GroupElement signedMod(GroupElement x, GroupElement y)\n {\n     // assumes that underlying signed value of y is positive\n     // todo: handle other bitlengths\n     // we dont use this anymore\n\n    if (x.bitsize == 32) {\n        int32_t value = static_cast<int32_t>(x.value) % static_cast<int32_t>(y.value);\n\n            // using the above exprn as the formula gives a problem\n            // for e.g. with -5%3 we expect the answer to be 1 because -5 = 3*-2 + 1\n            // but above line says -5%3 = -2\n            // therefore using this if condn\n\n            // value = static_cast<uint64_t>((static_cast<int64_t>(x.value)) % (static_cast<int64_t>(y.value)) );\n\n            if ((value != 0) && (static_cast<int32_t>(x.value) < 0)) {\n\n                value += y.value;\n            }\n\n            return GroupElement(static_cast<uint32_t>(value), x.bitsize);\n    }\n\n    int64_t value = static_cast<int64_t>(x.value) % static_cast<int64_t>(y.value);\n\n    // using the above exprn as the formula gives a problem\n    // for e.g. with -5%3 we expect the answer to be 1 because -5 = 3*-2 + 1\n    // but above line says -5%3 = -2\n    // therefore using this if condn\n\n    // value = static_cast<uint64_t>((static_cast<int64_t>(x.value)) % (static_cast<int64_t>(y.value)) );\n\n    if ((value != 0) && (static_cast<int64_t>(x.value) < 0)) {\n\n        value += y.value;\n    }\n\n    return GroupElement(static_cast<uint64_t>(value), x.bitsize);\n }\n\nGroupElement flt2fxd(uint64_t x, int scale, int inp_bitlen){\n    uint64_t fxdval = x << scale;\n    return GroupElement(fxdval, inp_bitlen);\n}\n\nlong double fxd2flt(GroupElement x, int scale, int inp_bitlen){\n    assert(x.bitsize == inp_bitlen);\n    uint64_t N_half = ((uint64_t)1 << (inp_bitlen - 1));\n    long double fval;\n    if (x.value >= N_half){\n        fval = (long double) x.value - N_half - N_half;\n    }\n    else{\n        fval = x.value;\n    }\n\n    return (fval / ((uint64_t)1<<scale));\n}\n\nint64_t getSignedValue(GroupElement x) {\n    if (x.bitsize == 64) {\n        return static_cast<int64_t>(x.value);\n    }\n    int msb = x[0];\n    x.value = x.value % ((uint64_t)1 << x.bitsize);\n    int64_t val = x.value;\n    if (msb == 1) {\n        val = val - ((uint64_t)1 << x.bitsize);\n    }\n    return val;\n}\n\nvoid matmul_eval_helper(int dim1, int dim2, int dim3, GroupElement *A,\n                            GroupElement *B, GroupElement *C, GroupElement *ka, GroupElement *kb, GroupElement *kc) {\n    Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_A(dim1, dim2);\n    Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_ka(dim1, dim2);\n    Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_B(dim2, dim3);\n    Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_kb(dim2, dim3);\n    Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_C(dim1, dim3);\n    Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_kc(dim1, dim3);\n\n    for (int i = 0; i < dim1; i++) {\n        for (int j = 0; j < dim2; j++) {\n            eigen_A(i, j) = Arr2DIdxRowM(A, dim1, dim2, i, j).value;\n        }\n    }\n    for (int i = 0; i < dim2; i++) {\n        for (int j = 0; j < dim3; j++) {\n            eigen_B(i, j) = Arr2DIdxRowM(B, dim2, dim3, i, j).value;\n        }\n    }\n    for (int i = 0; i < dim1; i++) {\n        for (int j = 0; j < dim2; j++) {\n            eigen_ka(i, j) = Arr2DIdxRowM(ka, dim1, dim2, i, j).value;\n        }\n    }\n    for (int i = 0; i < dim2; i++) {\n        for (int j = 0; j < dim3; j++) {\n            eigen_kb(i, j) = Arr2DIdxRowM(kb, dim2, dim3, i, j).value;\n        }\n    }\n    for (int i = 0; i < dim1; i++) {\n        for (int j = 0; j < dim3; j++) {\n            eigen_kc(i, j) = Arr2DIdxRowM(kc, dim1, dim3, i, j).value;\n        }\n    }\n    if (party == SERVER) {\n        eigen_C = eigen_A * eigen_B - eigen_ka * eigen_B - eigen_A * eigen_kb + eigen_kc;\n    }\n    else {\n        eigen_C = eigen_kc - eigen_ka * eigen_B - eigen_A * eigen_kb;\n    }\n    for (int i = 0; i < dim1; i++) {\n        for (int j = 0; j < dim3; j++) {\n            Arr2DIdxRowM(C, dim1, dim3, i, j).value = eigen_C(i, j);\n        }\n    }\n}", "meta": {"hexsha": "ae46150f758572e0d830ffa99acdd84c223bf9a9", "size": 19308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FSS/src/utils.cpp", "max_stars_repo_name": "kanav99/EzPC", "max_stars_repo_head_hexsha": "094e75111d00883dd90ef328bd47a7c0a1eb689f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FSS/src/utils.cpp", "max_issues_repo_name": "kanav99/EzPC", "max_issues_repo_head_hexsha": "094e75111d00883dd90ef328bd47a7c0a1eb689f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FSS/src/utils.cpp", "max_forks_repo_name": "kanav99/EzPC", "max_forks_repo_head_hexsha": "094e75111d00883dd90ef328bd47a7c0a1eb689f", "max_forks_repo_licenses": ["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.6700507614, "max_line_length": 227, "alphanum_fraction": 0.5533457634, "num_tokens": 6440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.05033063562448701, "lm_q1q2_score": 0.02359453021290041}}
{"text": "#include <boost/python/module.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/args.hpp>\n\n#include <string>\n\n#include <scitbx/array_family/shared.h>\n#include <scitbx/array_family/versa.h>\n#include <scitbx/array_family/accessors/c_grid.h>\n\n#include \"cma/cmaes_interface.h\"\n\n/* ============================================================================\n   Wrapper for the Covariance Matrix Adaptation Evolution Strategy (CMA-ES)\n\n   The cma directory contains the original source code from\n\n   http://www.lri.fr/~hansen/cmaesintro.html\n\n   The changes are that cmaes.cpp is a copy of cmaes.c (for building the shared\n   library in scons) and the license in cmaes.c was revised by the original\n   author to the Lesser GNU Public License (LGPL) instead of the GNU Public\n   License.\n\n   This C++ class just keeps track of the cmaes_t struct and exposes the most\n   basic functions for minimization to Python.  See example1.c, example2.c,\n   and tst_cma_es.py for how to use the minimizer.\n\n   Constructors:\n     cma_es - dimensions (int), initial guess (double array), standard\n              deviations for guesses (double array)\n       This is the most basic constructor providing the bare minimum\n       information required for the minimizer.  All other parameters are set\n       to their defaults.\n     cma_es - file name (string)\n       This is the more advanced constructor where all parameters can be\n       specified in the file.  See initials.par for the format.\n\n   Member functions:\n     sample_population - returns the points to sample\n       This returns a 2-d array where the first dimension is the population\n       size and the second dimension is the number of dimensions for the target\n       function (size of guess)\n     update_distribution - updated target function values (double array)\n       Updates the minimizer with the new target function values\n     converged - returns true is the minimization has converged\n     get_result - returns the best guess ever encountered\n   ----------------------------------------------------------------------------\n*/\n\nnamespace cma_es {\n\n  // wrapper class for calling CMA-ES minimizer based on\n  // example1.c and example2.c\n  class cma_es {\n\n  public:\n    cma_es(const int&, scitbx::af::ref<double>, scitbx::af::ref<double>);\n    cma_es(const int&, scitbx::af::ref<double>, scitbx::af::ref<double>,\n           const int&);\n    cma_es(std::string);\n    ~cma_es();\n    scitbx::af::versa<double,scitbx::af::c_grid<2> > sample_population();\n    void update_distribution(const scitbx::af::const_ref<double>&);\n    bool converged();\n    scitbx::af::shared<double> get_result();\n\n  private:\n    int N, pop_size;\n    cmaes_t evo;\n    double *arFunvals, *const*pop, *xfinal;\n  };\n\n  // default parameters, only dimension and initial guess required\n  cma_es::cma_es(const int& dimension, scitbx::af::ref<double> x,\n                 scitbx::af::ref<double> std_dev) {\n    N = dimension;\n    arFunvals = cmaes_init(&evo,N,x.begin(),std_dev.begin(),0,0,\"non\");\n    pop_size = cmaes_Get(&evo,\"popsize\");\n  }\n\n  // default parameters plus population size\n  cma_es::cma_es(const int& dimension, scitbx::af::ref<double> x,\n                 scitbx::af::ref<double> std_dev, const int& lambda) {\n    N = dimension;\n    arFunvals = cmaes_init(&evo,N,x.begin(),std_dev.begin(),0,lambda,\"non\");\n    pop_size = cmaes_Get(&evo,\"popsize\");\n  }\n\n  // all parameters from file (see initials.par)\n  cma_es::cma_es(std::string parameters) {\n    arFunvals = cmaes_init(&evo,0,NULL,NULL,0,0,parameters.c_str());\n    N = cmaes_Get(&evo,\"dim\");\n    pop_size = cmaes_Get(&evo,\"popsize\");\n  }\n\n  cma_es::~cma_es() {\n    cmaes_exit(&evo);\n  }\n\n  // returns new population for function evaluation\n  scitbx::af::versa<double,scitbx::af::c_grid<2> >\n  cma_es::sample_population() {\n    pop = cmaes_SamplePopulation(&evo);\n    scitbx::af::versa<double,scitbx::af::c_grid<2> >\n      p(scitbx::af::c_grid<2>(pop_size,N));\n    for (int i=0; i<pop_size; i++) {\n      for (int j=0; j<N; j++) {\n        p(i,j) = pop[i][j];\n      }\n    }\n    return p;\n  }\n\n  // updates minizmizer with new function values\n  void cma_es::update_distribution\n  (const scitbx::af::const_ref<double>& new_function_values) {\n    cmaes_UpdateDistribution(&evo,new_function_values.begin());\n  }\n\n  bool cma_es::converged() {\n    return cmaes_TestForTermination(&evo);\n  }\n\n  scitbx::af::shared<double> cma_es::get_result() {\n    xfinal = cmaes_GetNew(&evo,\"xbestever\");\n    scitbx::af::shared<double> result(&xfinal[0],&xfinal[0] + N);\n    return result;\n  }\n\n  // wrapper for Python\n  namespace boost_python {\n    struct cma_es_wrapper\n    {\n      static void\n      wrap()\n      {\n        using namespace boost::python;\n        class_<cma_es>(\"cma_es\",\n                       init<const int&,scitbx::af::ref<double>,\n                            scitbx::af::ref<double> >() )\n          .def(init<const int&,scitbx::af::ref<double>,\n                    scitbx::af::ref<double>,const int&>() )\n          .def(init<std::string>() )\n          .def(\"sample_population\",\n               &cma_es::sample_population)\n          .def(\"update_distribution\",\n               &cma_es::update_distribution)\n          .def(\"converged\",\n               &cma_es::converged)\n          .def(\"get_result\",\n               &cma_es::get_result)\n          ;\n      }\n    };\n  }\n}\n\nBOOST_PYTHON_MODULE(cma_es_ext)\n{\n  cma_es::boost_python::cma_es_wrapper::wrap();\n}\n", "meta": {"hexsha": "72b3e799fca89dfcb357926593c437ef5a6475d4", "size": 5442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cma_es/cma_es_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": "cma_es/cma_es_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": "cma_es/cma_es_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": 33.3865030675, "max_line_length": 79, "alphanum_fraction": 0.6352443954, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.047425876711786524, "lm_q1q2_score": 0.023527684793965876}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// Definitions corresponding to analytic1d.hpp\n\n#include <complex>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <analytic1d.hpp>\n#include <bulk_properties.hpp>\n#include <io_utils.hpp>\n#include <utilities.hpp>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\nnamespace alma {\n\nnamespace analytic1D {\n\n/////////////////// BasicProperties_calculator ///////////////////\n\nBasicProperties_calculator::BasicProperties_calculator(\n    const alma::Crystal_structure* poscar_init,\n    const alma::Gamma_grid* grid_init,\n    const Eigen::ArrayXXd* w_init,\n    double T_init)\n\n    : poscar(poscar_init), grid(grid_init), w(w_init), T(T_init)\n\n{\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n    if (static_cast<std::size_t>(this->w->rows()) != nmodes ||\n        static_cast<std::size_t>(this->w->cols()) != nqpoints)\n        throw alma::value_error(\"BasicProperties_calculator > Dimensions of \"\n                                \"scattering rate matrix are inconsistent with \"\n                                \"wavevector grid.\");\n\n    this->unitvector = Eigen::Vector3d(1.0, 0.0, 0.0);\n    this->thinfilm = false;\n    this->kappacumulIdentifier = this->resolve_by_MFP;\n    this->updateMe();\n}\n\nvoid BasicProperties_calculator::setDirection(const Eigen::Vector3d u) {\n    this->unitvector = u;\n    (this->unitvector).normalize();\n    this->updateMe();\n}\n\nvoid BasicProperties_calculator::setLogMFPbins(double MFPmin,\n                                               double MFPmax,\n                                               int Nbins) {\n    this->MFPbins = alma::logSpace(MFPmin, MFPmax, Nbins);\n}\n\nvoid BasicProperties_calculator::setAutoProjMFPbins(int Nbins) {\n    this->setLogMFPbins(1e-6 * this->internal_MFPprojmax,\n                        2.0 * this->internal_MFPprojmax,\n                        Nbins);\n}\n\nvoid BasicProperties_calculator::setAutoMFPbins(int Nbins) {\n    this->setLogMFPbins(\n        1e-6 * this->internal_MFPmax, 2.0 * this->internal_MFPmax, Nbins);\n}\n\nvoid BasicProperties_calculator::setAutoRTbins(int Nbins) {\n    this->setLogRTbins(\n        1e-6 * this->internal_taumax, 2.0 * this->internal_taumax, Nbins);\n}\n\nvoid BasicProperties_calculator::setLogRTbins(double taumin,\n                                              double taumax,\n                                              int Nbins) {\n    this->taubins = alma::logSpace(taumin, taumax, Nbins);\n}\n\nvoid BasicProperties_calculator::setLinOmegabins(double omegamin,\n                                                 double omegamax,\n                                                 int Nbins) {\n    this->omegabins.setLinSpaced(Nbins, omegamin, omegamax);\n}\n\nvoid BasicProperties_calculator::setAutoOmegabins(int Nbins) {\n    this->setLinOmegabins(0.0, 1.1 * this->internal_omegamax, Nbins);\n}\n\n\nEigen::VectorXd BasicProperties_calculator::getMFPbins() {\n    return this->MFPbins;\n}\n\nEigen::VectorXd BasicProperties_calculator::getRTbins() {\n    return this->taubins;\n}\n\nEigen::VectorXd BasicProperties_calculator::getOmegabins() {\n    return this->omegabins;\n}\n\n\nvoid BasicProperties_calculator::setBulk() {\n    this->thinfilm = false;\n    this->updateMe();\n}\n\nvoid BasicProperties_calculator::setCrossPlaneFilm(double d) {\n    this->thinfilm = true;\n    this->crossplane = true;\n    this->filmthickness = d;\n    this->updateMe();\n}\n\nvoid BasicProperties_calculator::setInPlaneFilm(double d,\n                                                const Eigen::Vector3d n,\n                                                double specul) {\n    this->thinfilm = true;\n    this->crossplane = false;\n    this->filmthickness = d;\n    this->normalvector = n;\n    this->normalvector.normalize();\n    this->specularity = specul;\n    this->updateMe();\n}\n\nvoid BasicProperties_calculator::initFuchsRotation() {\n    // obtain spherical coordinate angles that describe the film normal\n\n    double theta = std::acos(this->normalvector(2));\n    double phi = 0.0;\n\n    if (std::abs(this->normalvector(2)) < 1.0) {\n        phi = std::atan2(this->normalvector(1), this->normalvector(0));\n    }\n\n    // Construct the 3D rotation matrix that maps the film normal to (0,0,1)\n\n    Eigen::Matrix3d R;\n    R << std::cos(phi) * std::cos(theta), std::sin(phi) * std::cos(theta),\n        -std::sin(theta), -std::sin(phi), std::cos(phi), 0.0,\n        std::sin(theta) * std::cos(phi), std::sin(theta) * std::sin(phi),\n        std::cos(theta);\n\n    this->FuchsRotation = R;\n}\n\nvoid BasicProperties_calculator::updateMe() {\n    if (this->thinfilm && !this->crossplane) {\n        this->initFuchsRotation();\n    }\n\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    this->kappa = 0.0;\n    this->Cv = 0.0;\n    this->dominantProjMFP = 0.0;\n    this->dominantRT = 0.0;\n\n    const double prefactor =\n        1e27 * alma::constants::kB / this->grid->nqpoints / this->poscar->V;\n\n    // obtain heat capacity at gamma point\n    auto sp0 = this->grid->get_spectrum_at_q(0);\n\n    for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n        // obtain volumetric heat capacity of these modes [J/m^3-K]\n        double C = prefactor * alma::bose_einstein_kernel(sp0.omega[im], T);\n\n        this->Cv += C;\n    }\n\n    // obtain heat capacity and conductivity of all other modes\n\n    double MFPmax = -1.0;\n    double MFPprojmax = -1.0;\n    double taumax = -1.0;\n    double omegamax = -1.0;\n\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp = grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // scattering rate\n            double w0 = w->operator()(im, iq);\n            // obtain relaxation time [seconds]\n            double tau0 = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain phonon frequency\n            double omega0 = 1e12 * sp.omega(im);\n            if (omega0 > omegamax) {\n                omegamax = omega0;\n            }\n\n            // obtain volumetric heat capacity [J/m^3-K]\n            double C = prefactor * alma::bose_einstein_kernel(sp.omega[im], T);\n            this->Cv += C;\n\n            // obtain projected group velocity [m/s] and MFP [m]\n            double vg = 1e3 * sp.vg.col(im).matrix().norm();\n            Eigen::Vector3d vg_vector = sp.vg.col(im);\n            double vg_proj = 1e3 * this->unitvector.dot(sp.vg.col(im).matrix());\n\n            double MFP = vg * tau0;\n            double MFP_proj = std::abs(vg_proj * tau0);\n\n            // perform corrections for thin films if needed\n\n            double suppression_factor = 1.0;\n\n            if (this->thinfilm) {\n                if (this->crossplane) {\n                    // Obtain cross-plane suppression factor as derived in\n                    // B. Vermeersch, J. Carrete, N. Mingo\n                    // Applied Physics Letters 108, 193104 (2016)\n                    // http://dx.doi.org/10.1063/1.4948968\n\n                    suppression_factor =\n                        1.0 / (1.0 + 2.0 * MFP_proj / this->filmthickness);\n\n                } // end crossplane film\n\n                else {\n                    // Obtain in-plane suppression by applying Fuchs-Sondheimer\n                    // correction\n                    // As we process each mode within the discrete wavevector\n                    // grid individually,\n                    // F-S formula before integration over solid angle must be\n                    // applied.\n\n                    // (1) Obtain the group velocity within the transformed\n                    // coordinate\n                    //     system that describes the thin film\n                    Eigen::Vector3d vg_rotated =\n                        this->FuchsRotation * vg_vector;\n\n                    // (2) Calculate generalised Knudsen number\n                    double K_prime =\n                        MFP * std::abs(vg_rotated(2) / vg_rotated.norm()) /\n                        this->filmthickness;\n\n                    // (3) Evaluate suppression factor\n                    // This step is bypassed when\n                    //  (a) K_prime = 0 (limit of suppression factor is 1)\n                    //  (b) vg_proj = 0 (mode does not contribute to\n                    //  conductivity anyway)\n\n                    if (std::abs(vg_proj) > 0.0 && K_prime > 0.0) {\n                        double buffer1 =\n                            1.0 - this->specularity * std::exp(-1.0 / K_prime) -\n                            (1.0 - this->specularity) * K_prime *\n                                (1.0 - std::exp(-1.0 / K_prime));\n                        double buffer2 =\n                            1.0 - this->specularity * exp(-1.0 / K_prime);\n\n                        suppression_factor = buffer1 / buffer2;\n                    }\n\n                } // end in-plane film\n\n            } // end film corrections\n\n            // correct phonon properties\n            MFP *= suppression_factor;\n            MFP_proj *= suppression_factor;\n            tau0 *= suppression_factor;\n\n            // keep track of maximum values\n            if (MFP > MFPmax) {\n                MFPmax = MFP;\n            }\n            if (MFP_proj > MFPprojmax) {\n                MFPprojmax = MFP_proj;\n            }\n            if (tau0 > taumax) {\n                taumax = tau0;\n            };\n\n            // register contributions of this mode\n            double kappa_mode = vg_proj * vg_proj * tau0 * C;\n            this->kappa += kappa_mode;\n            this->dominantProjMFP += MFP_proj * kappa_mode;\n            this->dominantRT += tau0 * kappa_mode;\n        }\n    }\n\n    this->dominantProjMFP = this->dominantProjMFP / this->kappa;\n    this->dominantRT = this->dominantRT / this->kappa;\n\n    this->internal_MFPmax = MFPmax;\n    this->internal_MFPprojmax = MFPprojmax;\n    this->internal_omegamax = omegamax;\n    this->internal_taumax = taumax;\n}\n\ndouble BasicProperties_calculator::getSpectralConductivity() {\n    if (this->thinfilm && !this->crossplane) {\n        if (std::abs(this->unitvector.dot(this->normalvector)) > 1e-12) {\n            std::cout\n                << \"BasicProperties_calculator::getSpectralConductivity() > \"\n                << std::endl;\n            std::cout << \"WARNING: the transport axis and film normal that \"\n                         \"were provided for in-plane film are not orthogonal.\"\n                      << std::endl;\n            std::cout << \"Computation results likely invalid.\" << std::endl;\n        }\n    }\n\n    // number of frequency bins to be used in calculations\n    int Nbins = 100;\n\n    int nqpoints = this->grid->nqpoints;\n    int Nbranches = this->grid->get_spectrum_at_q(0).omega.size();\n\n    // obtain largest phonon energy for each phonon branch\n    Eigen::VectorXd omegamax(Nbranches);\n    omegamax.setConstant(-1.0);\n    double omega_mode;\n\n    for (int nq = 1; nq < nqpoints; nq++) {\n        auto sp = grid->get_spectrum_at_q(nq);\n\n        for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n            omega_mode = sp.omega[nbranch];\n            if (omega_mode > omegamax(nbranch)) {\n                omegamax(nbranch) = omega_mode;\n            }\n        }\n    }\n\n    // set up frequency bins\n    Eigen::MatrixXd omega(Nbins + 1, Nbranches);\n    Eigen::VectorXd omegabranch;\n    for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n        omegabranch.setLinSpaced(Nbins + 1, 0.0, omegamax(nbranch));\n        omega.col(nbranch) = omegabranch;\n    }\n\n    Eigen::MatrixXd Cbin(Nbins, Nbranches); // total capacity in each bin\n    Cbin.fill(0.0);\n    Eigen::MatrixXd Dbin(Nbins, Nbranches); // average diffusivity in each bin\n    Dbin.fill(0.0);\n    Eigen::MatrixXi bincount(Nbins, Nbranches); // number of modes in each bin\n    bincount.fill(0);\n\n    int binindex;\n    double tau, MFP, vg;\n    const double prefactor =\n        1e27 * alma::constants::kB / this->grid->nqpoints / this->poscar->V;\n\n    // perform frequency binning\n\n    for (int nq = 1; nq < nqpoints; nq++) {\n        auto sp = grid->get_spectrum_at_q(nq);\n\n        for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n            // scattering rate\n            double w0 = w->operator()(nbranch, nq);\n            // relaxation time [seconds]\n            tau = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // calculate binindex\n            omega_mode = sp.omega[nbranch];\n            binindex = static_cast<int>(std::floor(\n                omega_mode * static_cast<double>(Nbins) / omegamax(nbranch)));\n            if (binindex == Nbins) { // occurs for maximum frequency\n                binindex = Nbins - 1;\n            }\n            if (binindex < 0) {\n                binindex = 0;\n            }\n\n            if (binindex >= 0 &&\n                tau > 0.0) { // ignore anomalous negative frequency points\n\n                Cbin(binindex, nbranch) +=\n                    prefactor * alma::bose_einstein_kernel(omega_mode, T);\n                bincount(binindex, nbranch) += 1;\n\n                // obtain group velocity [m/s] and MFP [m]\n                vg = 1e3 * sp.vg.col(nbranch).matrix().norm();\n                MFP = vg * tau;\n                Dbin(binindex, nbranch) += MFP * MFP / (3.0 * tau);\n            }\n        }\n    }\n\n    // calculate average diffusivity in each bin\n\n    for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n        for (int nbin = 0; nbin < Nbins; nbin++) {\n            if (bincount(nbin, nbranch) > 0) {\n                Dbin(nbin, nbranch) /=\n                    static_cast<double>(bincount(nbin, nbranch));\n            }\n        }\n    }\n\n    // evaluate conductivity\n\n    double result = 0.0;\n\n    for (int nbranch = 0; nbranch < Nbranches; nbranch++) {\n        for (int nbin = 0; nbin < Nbins; nbin++) {\n            if (bincount(nbin, nbranch) > 0) {\n                result += Cbin(nbin, nbranch) * Dbin(nbin, nbranch);\n            }\n        }\n    }\n\n    return result;\n}\n\nvoid BasicProperties_calculator::setDOSgridsize(int nbins) {\n    this->DOS_Nbins = nbins;\n}\n\nEigen::VectorXd BasicProperties_calculator::getDOSgrid() {\n    Eigen::VectorXd result;\n    result.setLinSpaced(this->DOS_Nbins, 0.0, this->internal_omegamax);\n\n    // conversion from phonon frequency to energy in meV\n    return (1e3 * alma::constants::hbar / alma::constants::e) * result;\n}\n\nEigen::VectorXd BasicProperties_calculator::getDOS() {\n    // number of bins to be used in calculations\n    int Nbins = this->DOS_Nbins;\n\n    // set up frequency bins\n    Eigen::VectorXi bincount(Nbins);\n    bincount.setConstant(0);\n\n    // Perform frequency binning\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp = grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // calculate binindex\n            double omega_mode = 1e12 * sp.omega[im];\n\n            if (omega_mode > 0.0) {\n                int binindex = static_cast<int>(\n                    std::floor(omega_mode * static_cast<double>(Nbins) /\n                               this->internal_omegamax));\n                if (binindex >= Nbins) {\n                    binindex = Nbins - 1;\n                };\n                bincount(binindex)++;\n            }\n        }\n    }\n\n    // convert bincounts to DOS versus energy in meV\n\n    double deltaomega = this->internal_omegamax / static_cast<double>(Nbins);\n    int Nmodes = bincount.sum();\n    double deltaE =\n        1e3 * deltaomega * alma::constants::hbar / alma::constants::e;\n\n    return bincount.cast<double>() / (deltaE * static_cast<double>(Nmodes));\n}\n\ndouble BasicProperties_calculator::getAnisotropyIndex() {\n    Eigen::Matrix3d kappa_tensor =\n        alma::calc_kappa(*(this->poscar), *(this->grid), *(this->w), this->T);\n\n    Eigen::Vector3d kappa_diag = kappa_tensor.diagonal();\n\n    return kappa_diag.maxCoeff() / kappa_diag.minCoeff();\n}\n\ndouble BasicProperties_calculator::getConductivity() {\n    if (this->thinfilm && !this->crossplane) {\n        if (std::abs(this->unitvector.dot(this->normalvector)) > 1e-12) {\n            std::cout << \"BasicProperties_calculator::getConductivity() > \"\n                      << std::endl;\n            std::cout << \"WARNING: the transport axis and film normal that \"\n                         \"were provided for in-plane film are not orthogonal.\"\n                      << std::endl;\n            std::cout << \"Computation results likely invalid.\" << std::endl;\n        }\n    }\n\n    return this->kappa;\n}\n\ndouble BasicProperties_calculator::getCapacity() {\n    return this->Cv;\n}\n\ndouble BasicProperties_calculator::getDiffusivity() {\n    if (this->thinfilm && !this->crossplane) {\n        if (std::abs(this->unitvector.dot(this->normalvector)) > 1e-12) {\n            std::cout << \"BasicProperties_calculator::getDiffusivity() > \"\n                      << std::endl;\n            std::cout << \"WARNING: the transport axis and film normal that \"\n                         \"were provided for in-plane film are not orthogonal.\"\n                      << std::endl;\n            std::cout << \"Computation results likely invalid.\" << std::endl;\n        }\n    }\n\n    return (this->kappa / this->Cv);\n}\n\ndouble BasicProperties_calculator::getDominantProjMFP() {\n    if (this->thinfilm && !this->crossplane) {\n        if (std::abs(this->unitvector.dot(this->normalvector)) > 1e-12) {\n            std::cout << \"BasicProperties_calculator::getDominantProjMFP() > \"\n                      << std::endl;\n            std::cout << \"WARNING: the transport axis and film normal that \"\n                         \"were provided for in-plane film are not orthogonal.\"\n                      << std::endl;\n            std::cout << \"Computation results likely invalid.\" << std::endl;\n        }\n    }\n\n    return this->dominantProjMFP;\n}\n\ndouble BasicProperties_calculator::getDominantRT() {\n    if (this->thinfilm && !this->crossplane) {\n        if (std::abs(this->unitvector.dot(this->normalvector)) > 1e-12) {\n            std::cout << \"BasicProperties_calculator::getDominantRT() > \"\n                      << std::endl;\n            std::cout << \"WARNING: the transport axis and film normal that \"\n                         \"were provided for in-plane film are not orthogonal.\"\n                      << std::endl;\n            std::cout << \"Computation results likely invalid.\" << std::endl;\n        }\n    }\n\n    return this->dominantRT;\n}\n\nvoid BasicProperties_calculator::resolveByMFP() {\n    this->kappacumulIdentifier = this->resolve_by_MFP;\n}\n\nvoid BasicProperties_calculator::resolveByProjMFP() {\n    this->kappacumulIdentifier = this->resolve_by_ProjMFP;\n}\n\nvoid BasicProperties_calculator::resolveByRT() {\n    this->kappacumulIdentifier = this->resolve_by_RT;\n}\n\nvoid BasicProperties_calculator::resolveByOmega() {\n    this->kappacumulIdentifier = this->resolve_by_omega;\n}\n\nEigen::VectorXd BasicProperties_calculator::getCumulativeConductivity() {\n    if (this->thinfilm && !this->crossplane) {\n        if (std::abs(this->unitvector.dot(this->normalvector)) > 1e-12) {\n            std::cout\n                << \"BasicProperties_calculator::getCumulativeConductivity() > \"\n                << std::endl;\n            std::cout << \"WARNING: the transport axis and film normal that \"\n                         \"were provided for in-plane film are not orthogonal.\"\n                      << std::endl;\n            std::cout << \"Computation results likely invalid.\" << std::endl;\n        }\n    }\n\n    int Nbins;\n\n    if (this->kappacumulIdentifier == this->resolve_by_MFP ||\n        this->kappacumulIdentifier == this->resolve_by_ProjMFP) {\n        Nbins = this->MFPbins.size();\n    }\n\n    if (this->kappacumulIdentifier == this->resolve_by_RT) {\n        Nbins = this->taubins.size();\n    }\n\n    if (this->kappacumulIdentifier == this->resolve_by_omega) {\n        Nbins = this->omegabins.size();\n    }\n\n    this->kappacumul.resize(Nbins);\n    this->kappacumul.setConstant(0.0);\n\n    Eigen::VectorXd kappabins(Nbins);\n    kappabins.setConstant(0.0);\n\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp0 = grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // angular frequency of this mode\n            double omega0 = 1e12 * sp0.omega(im);\n\n            // scattering rate\n            double w0 = w->operator()(im, iq);\n            // obtain relaxation time of these modes [seconds]\n            double tau0 = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain volumetric heat capacity of these modes [J/m^3-K]\n            double prefactor = 1e27 * alma::constants::kB /\n                               this->grid->nqpoints / this->poscar->V;\n            double C = prefactor * alma::bose_einstein_kernel(sp0.omega[im], T);\n\n            // obtain projected group velocity [m/s] and MFP [m]\n            Eigen::Vector3d vg_vector = 1e3 * sp0.vg.col(im);\n            double vg = vg_vector.norm();\n            double vg_proj = this->unitvector.dot(vg_vector);\n\n            double MFP = vg * tau0;\n            double MFP_proj = std::abs(vg_proj * tau0);\n\n            // perform corrections for thin films if needed\n\n            double suppression_factor = 1.0;\n\n            if (this->thinfilm) {\n                if (this->crossplane) {\n                    // Obtain cross-plane suppression factor as derived in\n                    // B. Vermeersch, J. Carrete, N. Mingo\n                    // Applied Physics Letters 108, 193104 (2016)\n                    // http://dx.doi.org/10.1063/1.4948968\n\n                    suppression_factor =\n                        1.0 / (1.0 + 2.0 * MFP_proj / this->filmthickness);\n\n                } // end crossplane film\n\n                else {\n                    // Obtain in-plane suppression by applying Fuchs-Sondheimer\n                    // correction\n                    // As we process each mode within the discrete wavevector\n                    // grid individually,\n                    // F-S formula before integration over solid angle must be\n                    // applied.\n\n                    // (1) Obtain the group velocity within the transformed\n                    // coordinate\n                    //     system that describes the thin film\n                    Eigen::Vector3d vg_rotated =\n                        this->FuchsRotation * vg_vector;\n\n                    // (2) Calculate generalised Knudsen number\n                    double K_prime =\n                        MFP * std::abs(vg_rotated(2) / vg_rotated.norm()) /\n                        this->filmthickness;\n\n                    // (3) Evaluate suppression factor\n                    // This step is bypassed when\n                    //  (a) K_prime = 0 (limit of suppression factor is 1)\n                    //  (b) vg_proj = 0 (mode does not contribute to\n                    //  conductivity anyway)\n\n                    if (std::abs(vg_proj) > 0.0 && K_prime > 0.0) {\n                        double buffer1 =\n                            1.0 - this->specularity * std::exp(-1.0 / K_prime) -\n                            (1.0 - this->specularity) * K_prime *\n                                (1.0 - std::exp(-1.0 / K_prime));\n                        double buffer2 =\n                            1.0 - this->specularity * exp(-1.0 / K_prime);\n\n                        suppression_factor = buffer1 / buffer2;\n                    }\n\n                } // end in-plane film\n\n            } // end film corrections\n\n            // conductivity of these modes\n            double contribution =\n                suppression_factor * vg_proj * vg_proj * tau0 * C;\n\n            // determine which bin these modes belong to\n\n            double minvalue = 0.0;\n            double maxvalue = 0.0;\n            double targetvalue = 0.0;\n\n            if (this->kappacumulIdentifier == this->resolve_by_MFP) {\n                minvalue = std::log10(this->MFPbins(0));\n                maxvalue = std::log10(this->MFPbins(Nbins - 1));\n                targetvalue = std::log10(MFP);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_ProjMFP) {\n                minvalue = std::log10(this->MFPbins(0));\n                maxvalue = std::log10(this->MFPbins(Nbins - 1));\n                targetvalue = std::log10(MFP_proj);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_RT) {\n                minvalue = std::log10(this->taubins(0));\n                maxvalue = std::log10(this->taubins(Nbins - 1));\n                targetvalue = std::log10(tau0);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_omega) {\n                minvalue = 0.0;\n                maxvalue = this->omegabins(Nbins - 1);\n                targetvalue = omega0;\n            }\n\n            int binindex = static_cast<int>(\n                std::floor((targetvalue - minvalue) *\n                           static_cast<double>(Nbins) / (maxvalue - minvalue)));\n            if (binindex < 0) {\n                binindex = 0;\n            }\n            if (binindex >= Nbins) {\n                binindex = Nbins - 1;\n            }\n\n            kappabins(binindex) += contribution;\n        }\n    }\n\n    this->kappacumul(0) = kappabins(0);\n\n    for (int nbin = 1; nbin < Nbins; nbin++) {\n        this->kappacumul(nbin) = this->kappacumul(nbin - 1) + kappabins(nbin);\n    }\n\n    return this->kappacumul;\n}\n\n\nEigen::VectorXd BasicProperties_calculator::getCumulativel2RTAiso() {\n    if (this->thinfilm && !this->crossplane) {\n        if (std::abs(this->unitvector.dot(this->normalvector)) > 1e-12) {\n            std::cout\n                << \"BasicProperties_calculator::getCumulativel2RTAiso() > \"\n                << std::endl;\n            std::cout << \"WARNING: the transport axis and film normal that \"\n                         \"were provided for in-plane film are not orthogonal.\"\n                      << std::endl;\n            std::cout << \"Computation results likely invalid.\" << std::endl;\n        }\n    }\n\n    int Nbins;\n\n    if (this->kappacumulIdentifier == this->resolve_by_MFP ||\n        this->kappacumulIdentifier == this->resolve_by_ProjMFP) {\n        Nbins = this->MFPbins.size();\n    }\n\n    if (this->kappacumulIdentifier == this->resolve_by_RT) {\n        Nbins = this->taubins.size();\n    }\n\n    if (this->kappacumulIdentifier == this->resolve_by_omega) {\n        Nbins = this->omegabins.size();\n    }\n\n    this->l2cumul.resize(Nbins);\n    this->l2cumul.setConstant(0.0);\n\n    Eigen::VectorXd l2binsNum(Nbins);\n    Eigen::VectorXd l2binsDen(Nbins);\n    l2binsNum.setConstant(0.0);\n    l2binsDen.setConstant(0.0);\n\n\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp0 = grid->get_spectrum_at_q(iq);\n\n        /// Get momentum\n\n        double moment_proj;\n        auto Qcarts = poscar->map_to_firstbz(grid->get_q(iq));\n        Eigen::Vector3d momentum;\n\n        momentum(0) = 1.0e+9 * alma::constants::hbar * Qcarts.row(0).mean();\n        momentum(1) = 1.0e+9 * alma::constants::hbar * Qcarts.row(1).mean();\n        momentum(2) = 1.0e+9 * alma::constants::hbar * Qcarts.row(2).mean();\n\n        moment_proj = this->unitvector.dot(momentum);\n\n\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // angular frequency of this mode\n            double omega0 = 1e12 * sp0.omega(im);\n\n            // scattering rate\n            double w0 = w->operator()(im, iq);\n            // obtain relaxation time of these modes [seconds]\n            double tau0 = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain volumetric heat capacity of these modes [J/m^3-K]\n            if (alma::almost_equal(sp0.omega[im], 0.))\n                continue;\n\n            double dfBE_T = alma::constants::kB *\n                            alma::bose_einstein_kernel(sp0.omega[im], T) /\n                            (alma::constants::hbar * 1.0e+12 * sp0.omega[im]);\n\n\n            // obtain projected group velocity [m/s] and MFP [m]\n            Eigen::Vector3d vg_vector = 1e3 * sp0.vg.col(im);\n            double vg = vg_vector.norm();\n            double vg_proj = this->unitvector.dot(vg_vector);\n\n            double MFP = vg * tau0;\n            double MFP_proj = std::abs(vg_proj * tau0);\n\n\n            // perform corrections for thin films if needed\n\n            double suppression_factor = 1.0;\n\n            if (this->thinfilm) {\n                /// TODO: Implement anisotropy\n                std::cout << \"#WARNING: current implementation is \";\n                std::cout << \"isotropic so it is not valid for nanosystems\";\n                std::cout << \"the MFP resolved l2 for bulk is recommended\";\n                exit(1);\n\n                if (this->crossplane) {\n                    // Obtain cross-plane suppression factor as derived in\n                    // B. Vermeersch, J. Carrete, N. Mingo\n                    // Applied Physics Letters 108, 193104 (2016)\n                    // http://dx.doi.org/10.1063/1.4948968\n\n                    suppression_factor =\n                        1.0 / (1.0 + 2.0 * MFP_proj / this->filmthickness);\n\n                } // end crossplane film\n\n                else {\n                    // Obtain in-plane suppression by applying Fuchs-Sondheimer\n                    // correction\n                    // As we process each mode within the discrete wavevector\n                    // grid individually,\n                    // F-S formula before integration over solid angle must be\n                    // applied.\n\n                    // (1) Obtain the group velocity within the transformed\n                    // coordinate\n                    //     system that describes the thin film\n                    Eigen::Vector3d vg_rotated =\n                        this->FuchsRotation * vg_vector;\n\n                    // (2) Calculate generalised Knudsen number\n                    double K_prime =\n                        MFP * std::abs(vg_rotated(2) / vg_rotated.norm()) /\n                        this->filmthickness;\n\n                    // (3) Evaluate suppression factor\n                    // This step is bypassed when\n                    //  (a) K_prime = 0 (limit of suppression factor is 1)\n                    //  (b) vg_proj = 0 (mode does not contribute to\n                    //  conductivity anyway)\n\n                    if (std::abs(vg_proj) > 0.0 && K_prime > 0.0) {\n                        double buffer1 =\n                            1.0 - this->specularity * std::exp(-1.0 / K_prime) -\n                            (1.0 - this->specularity) * K_prime *\n                                (1.0 - std::exp(-1.0 / K_prime));\n                        double buffer2 =\n                            1.0 - this->specularity * exp(-1.0 / K_prime);\n\n                        suppression_factor = buffer1 / buffer2;\n                    }\n\n                } // end in-plane film\n\n            } // end film corrections\n\n            double tauS = tau0 * suppression_factor;\n\n            // conductivity of these modes\n            double contributionNum =\n                moment_proj * vg_proj *\n                (-tauS * tauS * dfBE_T * vg_proj * vg_proj);\n            double contributionDen = -5.0 * moment_proj * vg_proj * dfBE_T;\n\n            // determine which bin these modes belong to\n\n            double minvalue = 0.0;\n            double maxvalue = 0.0;\n            double targetvalue = 0.0;\n\n            if (this->kappacumulIdentifier == this->resolve_by_MFP) {\n                minvalue = std::log10(this->MFPbins(0));\n                maxvalue = std::log10(this->MFPbins(Nbins - 1));\n                targetvalue = std::log10(MFP);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_ProjMFP) {\n                minvalue = std::log10(this->MFPbins(0));\n                maxvalue = std::log10(this->MFPbins(Nbins - 1));\n                targetvalue = std::log10(MFP_proj);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_RT) {\n                minvalue = std::log10(this->taubins(0));\n                maxvalue = std::log10(this->taubins(Nbins - 1));\n                targetvalue = std::log10(tau0);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_omega) {\n                minvalue = 0.0;\n                maxvalue = this->omegabins(Nbins - 1);\n                targetvalue = omega0;\n            }\n\n            int binindex = static_cast<int>(\n                std::floor((targetvalue - minvalue) *\n                           static_cast<double>(Nbins) / (maxvalue - minvalue)));\n            if (binindex < 0) {\n                binindex = 0;\n            }\n            if (binindex >= Nbins) {\n                binindex = Nbins - 1;\n            }\n\n            l2binsNum(binindex) += contributionNum;\n            l2binsDen(binindex) += contributionDen;\n        }\n    }\n\n    Eigen::VectorXd l2cumulNum(Nbins), l2cumulDen(Nbins);\n    l2cumulDen.fill(0);\n    l2cumulNum.fill(0);\n\n    l2cumulNum(0) = l2binsNum(0);\n    l2cumulDen(0) = l2binsDen(0);\n\n    for (int nbin = 1; nbin < Nbins; nbin++) {\n        l2cumulNum(nbin) = l2cumulNum(nbin - 1) + l2binsNum(nbin);\n        l2cumulDen(nbin) = l2cumulDen(nbin - 1) + l2binsDen(nbin);\n    }\n\n    this->l2cumul = l2cumulNum.array() / l2cumulDen.array();\n\n    return this->l2cumul;\n}\n\n\nEigen::VectorXd BasicProperties_calculator::getCumulativeCapacity() {\n    int Nbins = -1;\n\n    if (this->kappacumulIdentifier == this->resolve_by_MFP ||\n        this->kappacumulIdentifier == this->resolve_by_ProjMFP) {\n        Nbins = this->MFPbins.size();\n    }\n\n    if (this->kappacumulIdentifier == this->resolve_by_RT) {\n        Nbins = this->taubins.size();\n    }\n\n    if (this->kappacumulIdentifier == this->resolve_by_omega) {\n        Nbins = this->omegabins.size();\n    }\n\n    this->Cvcumul.resize(Nbins);\n    this->Cvcumul.setConstant(0.0);\n\n    Eigen::VectorXd Cvbins(Nbins);\n    Cvbins.setConstant(0.0);\n\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    for (decltype(nqpoints) iq = 0; iq < nqpoints; ++iq) {\n        auto sp0 = grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // angular frequency\n            double omega0 = 1e12 * sp0.omega(im);\n\n            // scattering rate\n            double w0 = w->operator()(im, iq);\n            // obtain relaxation time of these modes [seconds]\n            double tau = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain volumetric heat capacity of these modes [J/m^3-K]\n            double prefactor = 1e27 * alma::constants::kB /\n                               this->grid->nqpoints / this->poscar->V;\n            double C = prefactor * alma::bose_einstein_kernel(sp0.omega[im], T);\n\n            // obtain projected group velocity [m/s] and MFP [m]\n            double vg = 1e3 * sp0.vg.col(im).matrix().norm();\n            double vg_proj =\n                1e3 * this->unitvector.dot(sp0.vg.col(im).matrix());\n\n            double MFP = vg * tau;\n            double MFP_proj = std::abs(vg_proj * tau);\n\n            // heat capcity of these modes\n            double contribution = C;\n\n            // determine which bin these modes belong to\n\n            double minvalue = 0.0;\n            double maxvalue = 0.0;\n            double targetvalue = 0.0;\n\n            if (this->kappacumulIdentifier == this->resolve_by_MFP) {\n                minvalue = std::log10(this->MFPbins(0));\n                maxvalue = std::log10(this->MFPbins(Nbins - 1));\n                targetvalue = std::log10(MFP);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_ProjMFP) {\n                minvalue = std::log10(this->MFPbins(0));\n                maxvalue = std::log10(this->MFPbins(Nbins - 1));\n                targetvalue = std::log10(MFP_proj);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_RT) {\n                minvalue = std::log10(this->taubins(0));\n                maxvalue = std::log10(this->taubins(Nbins - 1));\n                targetvalue = std::log10(tau);\n            }\n            else if (this->kappacumulIdentifier == this->resolve_by_omega) {\n                minvalue = 0.0;\n                maxvalue = this->omegabins(Nbins - 1);\n                targetvalue = omega0;\n            }\n\n            int binindex = static_cast<int>(\n                std::floor((targetvalue - minvalue) *\n                           static_cast<double>(Nbins) / (maxvalue - minvalue)));\n            if (binindex < 0) {\n                binindex = 0;\n            }\n            if (binindex >= Nbins) {\n                binindex = Nbins - 1;\n            }\n\n            Cvbins(binindex) += contribution;\n        }\n    }\n\n    this->Cvcumul(0) = Cvbins(0);\n\n    for (int nbin = 1; nbin < Nbins; nbin++) {\n        this->Cvcumul(nbin) = this->Cvcumul(nbin - 1) + Cvbins(nbin);\n    }\n\n    return this->Cvcumul;\n}\n\n/////////////////// psi_calculator ///////////////////\n\npsi_calculator::psi_calculator(const alma::Crystal_structure* poscar_init,\n                               const alma::Gamma_grid* grid_init,\n                               const Eigen::ArrayXXd* w_init,\n                               double T_init)\n\n    : poscar(poscar_init), grid(grid_init), w(w_init), T(T_init)\n\n{\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n    if (static_cast<std::size_t>(this->w->rows()) != nmodes ||\n        static_cast<std::size_t>(this->w->cols()) != nqpoints)\n        throw alma::value_error(\"psi_calculator > Dimensions of scattering \"\n                                \"rate matrix are inconsistent with wavevector \"\n                                \"grid.\");\n\n    this->unitvector = Eigen::Vector3d(1.0, 0.0, 0.0);\n    this->scaleoutput = false;\n    this->updateDiffusivity();\n}\n\nvoid psi_calculator::setDirection(const Eigen::Vector3d u) {\n    this->unitvector = u;\n    (this->unitvector).normalize();\n    this->updateDiffusivity();\n}\n\nvoid psi_calculator::setLinGrid(double ximin, double ximax, int Nxi) {\n    this->xi.setLinSpaced(Nxi, ximin, ximax);\n}\n\nvoid psi_calculator::setLogGrid(double ximin, double ximax, int Nxi) {\n    this->xi = alma::logSpace(ximin, ximax, Nxi);\n}\n\nvoid psi_calculator::setXiGrid(const Eigen::Ref<const Eigen::VectorXd> xigrid) {\n    this->xi = xigrid;\n}\n\nEigen::VectorXd psi_calculator::getSpatialFrequencies() {\n    return this->xi;\n}\n\nvoid psi_calculator::normaliseOutput(bool norm) {\n    this->scaleoutput = norm;\n}\n\nvoid psi_calculator::updateDiffusivity() {\n    alma::analytic1D::BasicProperties_calculator propCalc(\n        this->poscar, this->grid, this->w, this->T);\n    propCalc.setDirection(this->unitvector);\n\n    this->Dbulk = propCalc.getDiffusivity();\n}\n\ndouble psi_calculator::getDiffusivity() {\n    return this->Dbulk;\n}\n\nEigen::VectorXd psi_calculator::getPsi() {\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    int Nxi = this->xi.size();\n    Eigen::VectorXd ones(Nxi);\n    ones.setConstant(1.0);\n\n    Eigen::VectorXd numerator(Nxi);\n    Eigen::VectorXd denominator(Nxi);\n    numerator.setConstant(0.0);\n    denominator.setConstant(0.0);\n\n    // The Gamma point is ignored.\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp = this->grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // scattering rate\n            double w0 = w->operator()(im, iq);\n            // relaxation time [seconds]\n            double tau0 = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain volumetric heat capacity [J/m^3-K]\n            double prefactor = 1e27 * alma::constants::kB /\n                               this->grid->nqpoints / this->poscar->V;\n            double C = prefactor * alma::bose_einstein_kernel(sp.omega[im], T);\n\n            // obtain projected group velocity [m/s] and MFP [m]\n            double vg_proj = 1e3 * this->unitvector.dot(sp.vg.col(im).matrix());\n            double MFP_proj = std::abs(vg_proj * tau0);\n\n            numerator.array() += C * vg_proj * vg_proj * tau0 * ones.array() /\n                                 (ones.array() + MFP_proj * MFP_proj *\n                                                     this->xi.array().square());\n\n            denominator.array() +=\n                C * ones.array() /\n                (ones.array() +\n                 MFP_proj * MFP_proj * this->xi.array().square());\n        }\n    }\n\n    this->psi = this->xi.array() * this->xi.array() *\n                (numerator.array() / denominator.array());\n\n    if (this->scaleoutput) {\n        this->psi =\n            this->psi.array() / (this->Dbulk * this->xi.array().square());\n    }\n\n    return this->psi;\n}\n\n/////////////////// SPR_calculator_FourierLaplace ///////////////////\n\nSPR_calculator_FourierLaplace::SPR_calculator_FourierLaplace(\n    const alma::Crystal_structure* poscar_init,\n    const alma::Gamma_grid* grid_init,\n    const Eigen::ArrayXXd* w_init,\n    double T_init)\n\n    : poscar(poscar_init), grid(grid_init), w(w_init), T(T_init)\n\n{\n    this->unitvector = Eigen::Vector3d(1.0, 0.0, 0.0);\n}\n\nvoid SPR_calculator_FourierLaplace::setDirection(const Eigen::Vector3d u) {\n    this->unitvector = u;\n    (this->unitvector).normalize();\n}\n\nvoid SPR_calculator_FourierLaplace::setLinSpatialGrid(double ximin,\n                                                      double ximax,\n                                                      int Nxi) {\n    this->xi.setLinSpaced(Nxi, ximin, ximax);\n}\n\nvoid SPR_calculator_FourierLaplace::setLogSpatialGrid(double ximin,\n                                                      double ximax,\n                                                      int Nxi) {\n    this->xi = alma::logSpace(ximin, ximax, Nxi);\n}\n\nvoid SPR_calculator_FourierLaplace::setLinTemporalGrid(double fmin,\n                                                       double fmax,\n                                                       int Nf) {\n    this->f.setLinSpaced(Nf, fmin, fmax);\n    this->s = std::complex<double>(0.0, 2.0 * alma::constants::pi) *\n              f.cast<std::complex<double>>();\n}\n\nvoid SPR_calculator_FourierLaplace::setLogTemporalGrid(double fmin,\n                                                       double fmax,\n                                                       int Nf) {\n    this->f = alma::logSpace(fmin, fmax, Nf);\n    this->s = std::complex<double>(0.0, 2.0 * alma::constants::pi) *\n              f.cast<std::complex<double>>();\n}\n\nEigen::VectorXd SPR_calculator_FourierLaplace::getSpatialFrequencies() {\n    return this->xi;\n}\n\nEigen::VectorXd SPR_calculator_FourierLaplace::getTemporalFrequencies() {\n    return this->f;\n}\n\nEigen::MatrixXcd SPR_calculator_FourierLaplace::getSPR() {\n    int Nxi = this->xi.size();\n    int Ns = this->s.size();\n\n    this->Pxis.resize(Nxi, Ns);\n\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    Eigen::MatrixXcd numerator(Nxi, Ns);\n    Eigen::MatrixXcd denominator(Nxi, Ns);\n    numerator.fill(std::complex<double>(0.0, 0.0));\n    denominator.fill(std::complex<double>(0.0, 0.0));\n\n    // The Gamma point is ignored.\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp = this->grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // obtain relaxation time [seconds]\n            double w0 = this->w->operator()(im, iq);\n            double tau0 = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain volumetric heat capacity [J/m^3-K]\n            double prefactor = 1e27 * alma::constants::kB /\n                               this->grid->nqpoints / this->poscar->V;\n            double C = prefactor * alma::bose_einstein_kernel(sp.omega[im], T);\n\n            // obtain projected group velocity [m/s] and MFP [m]\n            double vg_proj = 1e3 * this->unitvector.dot(sp.vg.col(im).matrix());\n            double MFP_proj = std::abs(vg_proj * tau0);\n\n            for (int nxi = 0; nxi < Nxi; nxi++) {\n                double xival = this->xi(nxi);\n\n                for (int ns = 0; ns < Ns; ns++) {\n                    std::complex<double> sval = this->s(ns);\n                    std::complex<double> buffer =\n                        (std::complex<double>(1.0, 0.0) + sval * tau0) /\n                        ((std::complex<double>(1.0, 0.0) + sval * tau0) *\n                             (std::complex<double>(1.0, 0.0) + sval * tau0) +\n                         xival * xival * MFP_proj * MFP_proj);\n                    numerator(nxi, ns) += C * buffer;\n                    if (tau0 > 0.0)\n                        denominator(nxi, ns) +=\n                            (C / tau0) *\n                            (std::complex<double>(1.0, 0.0) - buffer);\n                }\n            }\n        }\n    }\n\n    this->Pxis = numerator.array() / denominator.array();\n\n    return this->Pxis;\n}\n\n\n/////////////////// SPR_calculator_RealSpace ///////////////////\n\nSPR_calculator_RealSpace::SPR_calculator_RealSpace(\n    const alma::Crystal_structure* poscar_init,\n    const alma::Gamma_grid* grid_init,\n    const Eigen::ArrayXXd* w_init,\n    double T_init)\n\n    : poscar(poscar_init), grid(grid_init), w(w_init), T(T_init)\n\n{\n    this->unitvector = Eigen::Vector3d(1.0, 0.0, 0.0);\n    this->normaliseoutput = false;\n    this->gridIsNormalised = false;\n\n    this->t = 10e-9;\n\n    this->updateDiffusivity();\n}\n\nvoid SPR_calculator_RealSpace::setDirection(const Eigen::Vector3d u) {\n    this->unitvector = u;\n    (this->unitvector).normalize();\n\n    this->updateDiffusivity();\n}\n\nvoid SPR_calculator_RealSpace::setLinGrid(double xmin, double xmax, int Nx) {\n    this->x.setLinSpaced(Nx, xmin, xmax);\n}\n\nvoid SPR_calculator_RealSpace::setLogGrid(double xmin, double xmax, int Nx) {\n    this->x = alma::logSpace(xmin, xmax, Nx);\n}\n\nvoid SPR_calculator_RealSpace::declareGridNormalised(bool norm) {\n    this->gridIsNormalised = norm;\n}\n\nvoid SPR_calculator_RealSpace::normaliseOutput(bool norm) {\n    this->normaliseoutput = norm;\n}\n\nvoid SPR_calculator_RealSpace::setTime(double t) {\n    this->t = t;\n}\n\nvoid SPR_calculator_RealSpace::setLogMFPbins(double MFPmin,\n                                             double MFPmax,\n                                             int Nbins) {\n    this->MFPbins = alma::logSpace(MFPmin, MFPmax, Nbins);\n}\n\nEigen::VectorXd SPR_calculator_RealSpace::getGrid() {\n    if (this->gridIsNormalised) {\n        return std::sqrt(2.0 * this->Dbulk * this->t) * this->x;\n    }\n    else {\n        return this->x;\n    }\n}\n\nEigen::VectorXd SPR_calculator_RealSpace::getNormalisedGrid() {\n    if (this->gridIsNormalised) {\n        return this->x;\n    }\n    else {\n        return (this->x) / std::sqrt(2.0 * this->Dbulk * this->t);\n    }\n}\n\ndouble SPR_calculator_RealSpace::getTime() {\n    return this->t;\n}\n\nEigen::VectorXd SPR_calculator_RealSpace::getMFPbins() {\n    return this->MFPbins;\n}\n\nvoid SPR_calculator_RealSpace::updateDiffusivity() {\n    alma::analytic1D::BasicProperties_calculator propCalc(\n        this->poscar, this->grid, this->w, this->T);\n    propCalc.setDirection(this->unitvector);\n\n    this->Dbulk = propCalc.getDiffusivity();\n}\n\ndouble SPR_calculator_RealSpace::getDiffusivity() {\n    return this->Dbulk;\n}\n\nEigen::VectorXd SPR_calculator_RealSpace::getSourceTransient(\n    const Eigen::Ref<Eigen::VectorXd> timegrid) {\n    // output variable\n    int Nt = timegrid.size();\n    Eigen::VectorXd result(Nt);\n    result.setConstant(0.0);\n\n    // calculate the propagator function psi(xi) over a\n    // logarithmic spatial frequency grid.\n    // The following choices are recommended to assure sufficient accuracy\n    // of the quadrature scheme: Nxi > 5000, ximin = 1e-3, ximax = 1e10;\n\n    int Nxi = 5001;\n    double ximin = 1e-3;\n    double ximax = 1e10;\n\n    psi_calculator psiCalc(this->poscar, this->grid, this->w, this->T);\n    psiCalc.setDirection(unitvector);\n    psiCalc.setLogGrid(ximin, ximax, Nxi);\n\n    Eigen::VectorXd psi(psiCalc.getPsi());\n    Eigen::VectorXd xi(psiCalc.getSpatialFrequencies());\n\n    // fix potential numerical issues\n    for (int nxi = 0; nxi < Nxi; nxi++) {\n        if (xi(nxi) < 1e3) {\n            psi(nxi) = this->Dbulk * xi(nxi) * xi(nxi);\n        }\n    }\n\n    // perform piecewise integration of (1/pi)*exp(-psi(xi)*t) over xi\n\n    for (int nt = 0; nt < Nt; nt++) {\n        double t = timegrid(nt);\n\n        for (int nxi = 0; nxi < Nxi - 1; nxi++) {\n            if (std::abs(psi(nxi + 1) - psi(nxi)) <\n                1e-12) { // \"psileft = psiright\"\n                result(nt) += std::exp(-psi(nxi) * t) * (xi(nxi + 1) - xi(nxi));\n            }\n            else {\n                result(nt) +=\n                    (std::exp(-psi(nxi) * t) - std::exp(-psi(nxi + 1) * t)) *\n                    (xi(nxi + 1) - xi(nxi)) / ((psi(nxi + 1) - psi(nxi)) * t);\n            }\n        }\n    }\n\n    return (1.0 / alma::constants::pi) * result.array();\n}\n\nEigen::VectorXd SPR_calculator_RealSpace::getSPR() {\n    // output variable\n    int Nx = this->x.size();\n    this->Pxt.resize(Nx, 1);\n    this->Pxt.setConstant(0.0);\n\n    // calculate the propagator function psi(xi) over a\n    // logarithmic spatial frequency grid.\n    // The number of xi points must be odd so that the grid contains\n    // an integer number (Nxi-1)/2 of successive xi triplets.\n    //\n    // The following choices are recommended to assure sufficient accuracy\n    // of the quadrature scheme: Nxi > 5000, ximin = 1e-3, ximax = 1e10;\n\n    int Nxi = 5001;\n    double ximin = 1e-3;\n    double ximax = 1e10;\n\n    psi_calculator psiCalc(this->poscar, this->grid, this->w, this->T);\n    psiCalc.setDirection(unitvector);\n    psiCalc.setLogGrid(ximin, ximax, Nxi);\n\n    Eigen::VectorXd psi(psiCalc.getPsi());\n    Eigen::VectorXd xi(psiCalc.getSpatialFrequencies());\n\n    // group information with respect to successive xi triplets\n    int N3 = (Nxi - 1) / 2;\n    Eigen::VectorXd xileft(N3);\n    Eigen::VectorXd psileft(N3);\n    Eigen::VectorXd xiright(N3);\n    Eigen::VectorXd psiright(N3);\n    Eigen::VectorXd ximiddle(N3);\n    Eigen::VectorXd psimiddle(N3);\n\n    for (int n3 = 0; n3 < N3; n3++) {\n        xileft(n3) = xi(2 * n3);\n        psileft(n3) = psi(2 * n3);\n        ximiddle(n3) = xi(2 * n3 + 1);\n        psimiddle(n3) = psi(2 * n3 + 1);\n        xiright(n3) = xi(2 * n3 + 2);\n        psiright(n3) = psi(2 * n3 + 2);\n    }\n\n    // perform piecewise power law fit psi(xi) = A0*xi^alpha0 over the\n    // successive xi intervals\n\n    Eigen::VectorXd A0(N3);\n    Eigen::VectorXd alpha0(N3);\n    Eigen::VectorXd buffer1 = (psiright.array() / psileft.array()).log();\n    Eigen::VectorXd buffer2 = (xiright.array() / xileft.array()).log();\n    alpha0 = buffer1.array() / buffer2.array();\n    A0 = psimiddle.array() / Eigen::pow(ximiddle.array(), alpha0.array());\n\n    // use power law fittings for piecewise Taylor series expansions of\n    // exp(-t*psi(xi)) around the midpoints of the xi intervals:\n    // exp(-t*psi(xi)) \\approx exp(-t*psimiddle) * (1 + B1*(xi-ximiddle) +\n    // B2*(xi-xmiddle)^2)\n\n    Eigen::VectorXd ones(N3);\n    ones.setConstant(1.0);\n    Eigen::VectorXd twos(N3);\n    twos.setConstant(2.0);\n    Eigen::VectorXd alphamin1 = alpha0 - ones;\n    Eigen::VectorXd alphamin2 = alpha0 - twos;\n    Eigen::VectorXd twoalphamin2 = 2.0 * alphamin1;\n\n    Eigen::VectorXd B1 =\n        -this->t * alpha0.array() * A0.array() *\n        (Eigen::pow(ximiddle.array(), alphamin1.array())).array();\n    buffer1 = this->t * alpha0.array().square() * A0.array().square() *\n              (Eigen::pow(ximiddle.array(), (twoalphamin2).array())).array();\n\n    buffer2 = alpha0.array() * alphamin1.array() * A0.array() *\n              (Eigen::pow(ximiddle.array(), alphamin2.array())).array();\n\n    Eigen::VectorXd B2 = 0.5 * this->t * (buffer1.array() - buffer2.array());\n\n    // rewrite (1+B1*(xi-ximiddle)+B2*(xi-ximiddle)^2) as\n    // (C0 + C1*xi + C2*xi^2) and perform piecewise evaluation of\n    // Fourier inversion integral exp(-psi(xi)*t)*cos(xi*x)\n\n    Eigen::VectorXd expfactors = (-this->t * psimiddle).array().exp();\n    Eigen::VectorXd C0 =\n        expfactors.array() * (ones.array() - B1.array() * ximiddle.array() +\n                              B2.array() * ximiddle.array().square());\n    Eigen::VectorXd C1 = expfactors.array() *\n                         (B1.array() - (2.0 * B2).array() * ximiddle.array());\n    Eigen::VectorXd C2 = expfactors.array() * B2.array();\n\n    Eigen::VectorXd primitive_left(N3);\n    Eigen::VectorXd primitive_right(N3);\n    Eigen::VectorXd argument(N3);\n    Eigen::VectorXd SIN(N3);\n    Eigen::VectorXd COS(N3);\n\n    for (int nx = 0; nx < Nx; nx++) {\n        double xval;\n\n        if (this->gridIsNormalised) {\n            xval = this->x(nx) * std::sqrt(2.0 * this->Dbulk * this->t);\n        }\n        else {\n            xval = this->x(nx);\n        }\n\n        argument = xval * xiright;\n        SIN = argument.array().sin();\n        COS = argument.array().cos();\n\n        primitive_right =\n            (C0 / xval).array() * SIN.array() +\n            (C1 / (xval * xval)).array() *\n                (COS.array() + argument.array() * SIN.array()) +\n            (C2 / (xval * xval * xval)).array() *\n                ((-2.0 * SIN).array() + (2.0 * argument).array() * COS.array() +\n                 (argument.array().square()).array() * SIN.array());\n\n\n        argument = xval * xileft;\n        SIN = argument.array().sin();\n        COS = argument.array().cos();\n\n        primitive_left =\n            (C0 / xval).array() * SIN.array() +\n            (C1 / (xval * xval)).array() *\n                (COS.array() + argument.array() * SIN.array()) +\n            (C2 / (xval * xval * xval)).array() *\n                ((-2.0 * SIN).array() + (2.0 * argument).array() * COS.array() +\n                 (argument.array().square()).array() * SIN.array());\n\n        double integral =\n            (primitive_right.array() - primitive_left.array()).sum();\n\n        this->Pxt(nx) = integral / alma::constants::pi;\n    }\n\n    if (this->normaliseoutput) {\n        this->Pxt =\n            std::sqrt(4.0 * alma::constants::pi * this->Dbulk * this->t) *\n            this->Pxt;\n    }\n\n    return this->Pxt;\n}\n\nEigen::MatrixXd SPR_calculator_RealSpace::resolveSPRbyMFP() {\n    // output variable\n    int Nx = this->x.size();\n    int Nbins = this->MFPbins.size();\n\n    this->Pmodes.resize(Nx, Nbins);\n    this->Pmodes.fill(0.0);\n\n    // calculate the propagator function psi(xi) over a\n    // logarithmic spatial frequency grid.\n    // The number of xi points must be odd so that the grid contains\n    // an integer number (Nxi-1)/2 of successive xi triplets.\n    //\n    // The following choices are recommended to assure sufficient accuracy\n    // of the quadrature scheme: Nxi > 5000, ximin = 1e-3, ximax = 1e10;\n\n    int Nxi = 5001;\n    double ximin = 1e-3;\n    double ximax = 1e10;\n\n    psi_calculator psiCalc(this->poscar, this->grid, this->w, this->T);\n    psiCalc.setDirection(unitvector);\n    psiCalc.setLogGrid(ximin, ximax, Nxi);\n\n    Eigen::VectorXd psi(psiCalc.getPsi());\n    Eigen::VectorXd xi(psiCalc.getSpatialFrequencies());\n\n    // group information with respect to successive xi triplets\n    int N3 = (Nxi - 1) / 2;\n\n    Eigen::VectorXd xileft(N3);\n    Eigen::VectorXd psileft(N3);\n    Eigen::VectorXd xiright(N3);\n    Eigen::VectorXd psiright(N3);\n    Eigen::VectorXd ximiddle(N3);\n    Eigen::VectorXd psimiddle(N3);\n\n    for (int n3 = 0; n3 < N3; n3++) {\n        xileft(n3) = xi(2 * n3);\n        psileft(n3) = psi(2 * n3);\n        ximiddle(n3) = xi(2 * n3 + 1);\n        psimiddle(n3) = psi(2 * n3 + 1);\n        xiright(n3) = xi(2 * n3 + 2);\n        psiright(n3) = psi(2 * n3 + 2);\n    }\n\n    // perform piecewise power law fit psi(xi) = A0*xi^alpha0 over the\n    // successive xi intervals\n\n    Eigen::VectorXd A0(N3);\n    Eigen::VectorXd alpha0(N3);\n\n    Eigen::VectorXd buffer1 = (psiright.array() / psileft.array()).log();\n    Eigen::VectorXd buffer2 = (xiright.array() / xileft.array()).log();\n    alpha0 = buffer1.array() / buffer2.array();\n    A0 = psimiddle.array() / Eigen::pow(ximiddle.array(), alpha0.array());\n\n    // use power law fittings for piecewise Taylor series expansions of\n    // exp(-t*psi(xi)) around the midpoints of the xi intervals:\n    // exp(-t*psi(xi)) \\approx exp(-t*psimiddle) * (1 + B1*(xi-ximiddle) +\n    // B2*(xi-xmiddle)^2)\n\n    Eigen::VectorXd ones(N3);\n    ones.setConstant(1.0);\n    Eigen::VectorXd twos(N3);\n    twos.setConstant(2.0);\n\n    Eigen::VectorXd alphamin1 = alpha0 - ones;\n    Eigen::VectorXd alphamin2 = alpha0 - twos;\n    Eigen::VectorXd twoalphamin2 = 2.0 * alphamin1;\n\n    Eigen::VectorXd B1 =\n        -t * alpha0.array() * A0.array() *\n        (Eigen::pow(ximiddle.array(), alphamin1.array())).array();\n    buffer1 = t * alpha0.array().square() * A0.array().square() *\n              (Eigen::pow(ximiddle.array(), (twoalphamin2).array())).array();\n\n    buffer2 = alpha0.array() * alphamin1.array() * A0.array() *\n              (Eigen::pow(ximiddle.array(), alphamin2.array())).array();\n\n    Eigen::VectorXd B2 = 0.5 * t * (buffer1.array() - buffer2.array());\n\n    // the Fourier image of the energy contained within a mode pair\n    // (forward and backward group velocities) is given by\n    // (Cmode/Ctotal) * F(xi) * exp[-psi(xi)*t] with\n    // F(xi) = [1 + tau*psi(xi)] / (1 + xi^2*MFPproj^2).\n    // Expand F in a Taylor series around the midpoints of the xi intervals:\n    // F(xi) \\approx D0 + D1*(xi-ximiddle) + D2*(xi-ximiddle)^2\n\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    double Cv_tot = 1e27 * alma::calc_cv(*this->poscar, *this->grid, this->T);\n\n    // The Gamma point is ignored.\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp = this->grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // obtain relaxation time of these modes [seconds]\n            double w0 = this->w->operator()(im, iq);\n            double tau0 = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain volumetric heat capacity of these modes [J/m^3-K]\n            double prefactor = 1e27 * alma::constants::kB /\n                               this->grid->nqpoints / this->poscar->V;\n            double Cv = prefactor * alma::bose_einstein_kernel(sp.omega[im], T);\n\n            // obtain projected group velocity [m/s] and MFP [m]\n            double vg = 1e3 * sp.vg.col(im).matrix().norm();\n            double vg_proj = 1e3 * this->unitvector.dot(sp.vg.col(im).matrix());\n\n            double MFP = vg * tau0;\n            double MFP_proj = std::abs(vg_proj * tau0);\n\n            double tau = tau0; // initialise to intrinsic value\n\n            Eigen::VectorXd spacedecay =\n                (1.0 + MFP_proj * MFP_proj * ximiddle.array().square());\n\n            // calculate Taylor expansion of F(xi)\n            Eigen::VectorXd D0 =\n                (1.0 + tau * psimiddle.array()).array() / spacedecay.array();\n\n            Eigen::VectorXd D1 =\n                tau * A0.array() * alpha0.array() *\n                Eigen::pow(ximiddle.array(), alphamin1.array()) /\n                spacedecay.array();\n            D1 = D1.array() -\n                 2.0 * MFP_proj * MFP_proj *\n                     (1 + tau * A0.array() *\n                              Eigen::pow(ximiddle.array(), alpha0.array())) *\n                     ximiddle.array() / spacedecay.array().square();\n\n            Eigen::VectorXd D2 =\n                0.5 * tau * A0.array() * alpha0.array() * alphamin1.array() *\n                Eigen::pow(ximiddle.array(), alphamin2.array()) /\n                spacedecay.array();\n            D2 = D2.array() - tau * MFP_proj * MFP_proj * A0.array() *\n                                  Eigen::pow(ximiddle.array(), alpha0.array()) *\n                                  (2.0 * alpha0.array() + 1.0) /\n                                  spacedecay.array().square();\n            D2 = D2.array() +\n                 4.0 * std::pow(MFP_proj, 4.0) * ximiddle.array().square() *\n                     (1 + tau * A0.array() *\n                              Eigen::pow(ximiddle.array(), alpha0.array())) /\n                     spacedecay.array().cube();\n            D2 = D2.array() - MFP_proj * MFP_proj * ones.array() /\n                                  spacedecay.array().square();\n\n            // evaluate Taylor expansion of exp[-psi(xi)*t] * F(xi) up to second\n            // order\n\n            Eigen::VectorXd B0tot = D0;\n            Eigen::VectorXd B1tot = D1.array() + D0.array() * B1.array();\n            Eigen::VectorXd B2tot =\n                D0.array() * B2.array() + D1.array() * B1.array() + D2.array();\n\n            // rewrite (B0tot+B1tot*(xi-ximiddle)+B2tot*(xi-ximiddle)^2) as\n            // (C0 + C1*xi + C2*xi^2) and perform piecewise evaluation of\n            // Fourier inversion integral exp(-psi(xi)*t)*cos(xi*x)\n\n            Eigen::VectorXd expfactors = (-t * psimiddle).array().exp();\n            Eigen::VectorXd C0 =\n                expfactors.array() *\n                (B0tot.array() - B1tot.array() * ximiddle.array() +\n                 B2tot.array() * ximiddle.array().square());\n            Eigen::VectorXd C1 =\n                expfactors.array() *\n                (B1tot.array() - (2.0 * B2tot).array() * ximiddle.array());\n            Eigen::VectorXd C2 = expfactors.array() * B2tot.array();\n\n            // perform piecewise integration\n\n            Eigen::VectorXd prim_left(N3);\n            Eigen::VectorXd prim_right(N3);\n            Eigen::VectorXd argument(N3);\n            Eigen::VectorXd SIN(N3);\n            Eigen::VectorXd COS(N3);\n\n            for (int nx = 0; nx < Nx; nx++) {\n                double xval;\n\n                if (this->gridIsNormalised) {\n                    xval = this->x(nx) * std::sqrt(2.0 * this->Dbulk * this->t);\n                }\n                else {\n                    xval = this->x(nx);\n                }\n\n                argument = xval * xiright;\n                SIN = argument.array().sin();\n                COS = argument.array().cos();\n\n                prim_right =\n                    (C0 / xval).array() * SIN.array() +\n                    (C1 / (xval * xval)).array() *\n                        (COS.array() + argument.array() * SIN.array()) +\n                    (C2 / (xval * xval * xval)).array() *\n                        ((-2.0 * SIN).array() +\n                         (2.0 * argument).array() * COS.array() +\n                         (argument.array().square()).array() * SIN.array());\n\n                argument = xval * xileft;\n                SIN = argument.array().sin();\n                COS = argument.array().cos();\n\n                prim_left =\n                    (C0 / xval).array() * SIN.array() +\n                    (C1 / (xval * xval)).array() *\n                        (COS.array() + argument.array() * SIN.array()) +\n                    (C2 / (xval * xval * xval)).array() *\n                        ((-2.0 * SIN).array() +\n                         (2.0 * argument).array() * COS.array() +\n                         (argument.array().square()).array() * SIN.array());\n\n                double integral =\n                    (prim_right.array() - prim_left.array()).sum() /\n                    alma::constants::pi;\n\n                // determine to which MFP bin this mode belongs\n\n                double logL = std::log10(MFP);\n                double logMFPmin = std::log10(this->MFPbins(0));\n                double logMFPmax = std::log10(this->MFPbins(Nbins - 1));\n                int binindex = static_cast<int>(\n                    std::floor((logL - logMFPmin) * static_cast<double>(Nbins) /\n                               (logMFPmax - logMFPmin)));\n                if (binindex < 0) {\n                    binindex = 0;\n                }\n                if (binindex >= Nbins) {\n                    binindex = Nbins - 1;\n                }\n\n                this->Pmodes(nx, binindex) += (Cv / Cv_tot) * integral;\n            }\n        }\n    }\n\n    if (this->normaliseoutput) {\n        this->Pmodes =\n            std::sqrt(4.0 * alma::constants::pi * this->Dbulk * this->t) *\n            this->Pmodes;\n    }\n\n    return this->Pmodes;\n}\n\n/////////////////// MSD_calculator_Laplace ///////////////////\n\nMSD_calculator_Laplace::MSD_calculator_Laplace(\n    const alma::Crystal_structure* poscar_init,\n    const alma::Gamma_grid* grid_init,\n    const Eigen::ArrayXXd* w_init,\n    double T_init)\n\n    : poscar(poscar_init), grid(grid_init), w(w_init), T(T_init)\n\n{\n    this->unitvector = Eigen::Vector3d(1.0, 0.0, 0.0);\n}\n\nvoid MSD_calculator_Laplace::setDirection(const Eigen::Vector3d u) {\n    this->unitvector = u;\n    (this->unitvector).normalize();\n}\n\nvoid MSD_calculator_Laplace::setLinGrid(double fmin, double fmax, int Nf) {\n    this->f.setLinSpaced(Nf, fmin, fmax);\n    this->s = std::complex<double>(0.0, 2.0 * alma::constants::pi) *\n              f.cast<std::complex<double>>();\n}\n\nvoid MSD_calculator_Laplace::setLogGrid(double fmin, double fmax, int Nf) {\n    this->f = alma::logSpace(fmin, fmax, Nf);\n    this->s = std::complex<double>(0.0, 2.0 * alma::constants::pi) *\n              f.cast<std::complex<double>>();\n}\n\nvoid MSD_calculator_Laplace::setLaplaceGrid(\n    const Eigen::Ref<const Eigen::VectorXcd> sgrid) {\n    this->s = sgrid;\n}\n\nEigen::VectorXd MSD_calculator_Laplace::getGrid() {\n    return this->f;\n}\n\nEigen::VectorXcd MSD_calculator_Laplace::getLaplaceGrid() {\n    return this->s;\n}\n\nEigen::VectorXcd MSD_calculator_Laplace::getMSD() {\n    int Ns = this->s.size();\n\n    Eigen::VectorXcd numerator(Ns);\n    Eigen::VectorXcd denominator(Ns);\n    numerator.setConstant(std::complex<double>(0.0, 0.0));\n    denominator.setConstant(std::complex<double>(0.0, 0.0));\n\n    auto nqpoints = this->grid->nqpoints;\n    auto nmodes =\n        static_cast<std::size_t>(this->grid->get_spectrum_at_q(0).omega.size());\n\n    // The Gamma point is ignored.\n    for (decltype(nqpoints) iq = 1; iq < nqpoints; ++iq) {\n        auto sp = this->grid->get_spectrum_at_q(iq);\n        for (decltype(nmodes) im = 0; im < nmodes; ++im) {\n            // obtain relaxation time [seconds]\n            double w0 = this->w->operator()(im, iq);\n            double tau0 = (w0 == 0.) ? 0. : (1e-12 / w0);\n\n            // obtain volumetric heat capacity [J/m^3-K]\n            double prefactor = 1e27 * alma::constants::kB /\n                               this->grid->nqpoints / this->poscar->V;\n            double C = prefactor * alma::bose_einstein_kernel(sp.omega[im], T);\n\n            // obtain projected group velocity [m/s]\n            double vg_proj = 1e3 * this->unitvector.dot(sp.vg.col(im).matrix());\n\n            for (int ns = 0; ns < Ns; ns++) {\n                std::complex<double> sval = this->s(ns);\n                std::complex<double> buffer =\n                    std::complex<double>(1.0, 0.0) + sval * tau0;\n                numerator(ns) +=\n                    C * vg_proj * vg_proj * tau0 / (buffer * buffer);\n                denominator(ns) += C / buffer;\n            }\n        }\n    }\n\n    this->MSD = std::complex<double>(2.0, 0.0) * numerator.array() /\n                (denominator.array() * this->s.array() * this->s.array());\n\n    return this->MSD;\n}\n\n/////////////////// MSD_calculator_RealTime ///////////////////\n\nMSD_calculator_RealTime::MSD_calculator_RealTime(\n    const alma::Crystal_structure* poscar_init,\n    const alma::Gamma_grid* grid_init,\n    const Eigen::ArrayXXd* w_init,\n    double T_init)\n\n    : poscar(poscar_init), grid(grid_init), w(w_init), T(T_init)\n\n{\n    this->unitvector = Eigen::Vector3d(1.0, 0.0, 0.0);\n    this->normaliseoutput = false;\n    this->updateDiffusivity();\n\n    // initialise Gaver-Stehfest coefficients\n\n    this->GS_depth = 16;\n    this->GS_coeffs.resize(this->GS_depth);\n    this->GS_coeffs.setConstant(0.0);\n\n    int nn2 = this->GS_depth / 2;\n\n    for (int n = 1; n <= this->GS_depth; n++) {\n        double coeff_buffer = 0.0;\n\n        for (int k = std::floor((n + 1) / 2); k <= std::min(n, nn2); k++) {\n            coeff_buffer += ((std::pow(k, nn2)) * this->factorial(2 * k)) /\n                            (this->factorial(nn2 - k) * this->factorial(k) *\n                             this->factorial(k - 1) * this->factorial(n - k) *\n                             this->factorial(2 * k - n));\n        }\n\n        this->GS_coeffs(n - 1) = std::pow(-1, n + nn2) * coeff_buffer;\n    }\n}\n\nvoid MSD_calculator_RealTime::setDirection(const Eigen::Vector3d u) {\n    this->unitvector = u;\n    (this->unitvector).normalize();\n    this->updateDiffusivity();\n}\n\nvoid MSD_calculator_RealTime::setLinGrid(double tmin, double tmax, int Nt) {\n    this->t.setLinSpaced(Nt, tmin, tmax);\n}\n\nvoid MSD_calculator_RealTime::setLogGrid(double tmin, double tmax, int Nt) {\n    this->t = alma::logSpace(tmin, tmax, Nt);\n}\n\nvoid MSD_calculator_RealTime::setTimeGrid(\n    const Eigen::Ref<const Eigen::VectorXd> tgrid) {\n    this->t = tgrid;\n}\n\nEigen::VectorXd MSD_calculator_RealTime::getGrid() {\n    return this->t;\n}\n\ndouble MSD_calculator_RealTime::factorial(int n) {\n    return (n == 1 || n == 0) ? 1\n                              : this->factorial(n - 1) * static_cast<double>(n);\n}\n\nvoid MSD_calculator_RealTime::normaliseOutput(bool norm) {\n    this->normaliseoutput = norm;\n}\n\nvoid MSD_calculator_RealTime::updateDiffusivity() {\n    alma::analytic1D::BasicProperties_calculator propCalc(\n        this->poscar, this->grid, this->w, this->T);\n    propCalc.setDirection(this->unitvector);\n\n    this->Dbulk = propCalc.getDiffusivity();\n}\n\ndouble MSD_calculator_RealTime::getDiffusivity() {\n    return this->Dbulk;\n}\n\nEigen::VectorXd MSD_calculator_RealTime::getMSD() {\n    int Nt = this->t.size();\n    this->MSD.resize(Nt);\n\n    // set up Laplace calculator\n\n    alma::analytic1D::MSD_calculator_Laplace LaplaceCalc(\n        this->poscar, this->grid, this->w, this->T);\n    LaplaceCalc.setDirection(this->unitvector);\n\n    Eigen::VectorXcd MSD_Laplace(this->GS_depth * Nt);\n    Eigen::VectorXd result;\n\n    // calculate MSD in time domain\n\n    Eigen::VectorXcd sgrid(this->GS_depth * Nt);\n\n    Eigen::VectorXd sbuffer(this->GS_depth);\n    sbuffer.setLinSpaced(\n        this->GS_depth, 1.0, static_cast<double>(this->GS_depth));\n    Eigen::VectorXcd sbase(sbuffer.cast<std::complex<double>>());\n\n    Eigen::VectorXd prefactors(Nt);\n\n    for (int nt = 0; nt < Nt; nt++) { // build Laplace grid\n\n        double s0 = std::log(2.0) / this->t(nt);\n        prefactors(nt) = s0;\n        Eigen::VectorXcd ssegment = s0 * sbase;\n        sgrid.segment(nt * this->GS_depth, this->GS_depth) = ssegment;\n    }\n\n    LaplaceCalc.setLaplaceGrid(sgrid);\n    MSD_Laplace = LaplaceCalc.getMSD();\n    Eigen::VectorXcd Laplace_segment(this->GS_depth);\n\n    for (int nt = 0; nt < Nt; nt++) {\n        Laplace_segment =\n            MSD_Laplace.segment(nt * this->GS_depth, this->GS_depth);\n        result = prefactors(nt) * this->GS_coeffs.transpose() *\n                 (Laplace_segment.array().real()).matrix();\n        this->MSD(nt) = result(0);\n    }\n\n    if (this->normaliseoutput) {\n        this->MSD = MSD.array() / (2.0 * this->Dbulk * this->t.array());\n    }\n\n    return this->MSD;\n}\n\n} // end namespace analytic1D\n} // end namespace alma\n", "meta": {"hexsha": "6029c79ab678210eab67cfb3258c4f924c4348a4", "size": 72396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analytic1d.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/analytic1d.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/analytic1d.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": 35.3151219512, "max_line_length": 80, "alphanum_fraction": 0.5489806067, "num_tokens": 19234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04742586947505113, "lm_q1q2_score": 0.023527681203866103}}
{"text": "/*\r\n *  Copyright 2011-2015 Maxim Milakov\r\n *\r\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  you may not use this file except in compliance with the License.\r\n *  You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *  Unless required by applicable law or agreed to in writing, software\r\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  See the License for the specific language governing permissions and\r\n *  limitations under the License.\r\n */\r\n\r\n#include \"convolution_layer.h\"\r\n\r\n#include \"layer_factory.h\"\r\n#include \"neural_network_exception.h\"\r\n#include \"nn_types.h\"\r\n#include \"proto/nnforge.pb.h\"\r\n\r\n#include <algorithm>\r\n#include <numeric>\r\n#include <boost/lambda/lambda.hpp>\r\n#include <boost/format.hpp>\r\n#include <opencv2/core/core.hpp>\r\n\r\nnamespace nnforge\r\n{\r\n\t// {5957B44F-699E-4DDB-836E-3FB3EEB54965}\r\n\tconst boost::uuids::uuid convolution_layer::layer_guid =\r\n\t\t{ 0x59, 0x57, 0xb4, 0x4f\r\n\t\t, 0x69, 0x9e\r\n\t\t, 0x4d, 0xdb\r\n\t\t, 0x83, 0x6e\r\n\t\t, 0x3f, 0xb3, 0xee, 0xb5, 0x49, 0x65 };\r\n\r\n\t// {8AD07635-DDFE-43B4-B26A-15CA19155A65}\r\n\tconst boost::uuids::uuid convolution_layer::layer_guid_v1 =\r\n\t\t{ 0x8a, 0xd0, 0x76, 0x35\r\n\t\t, 0xdd, 0xfe\r\n\t\t, 0x43, 0xb4\r\n\t\t, 0xb2, 0x6a\r\n\t\t, 0x15, 0xca, 0x19, 0x15, 0x5a, 0x65 };\r\n\r\n\tconst std::string convolution_layer::layer_type_name = \"Convolution\";\r\n\r\n\tconvolution_layer::convolution_layer(\r\n\t\tconst std::vector<unsigned int>& window_sizes,\r\n\t\tunsigned int input_feature_map_count,\r\n\t\tunsigned int output_feature_map_count,\r\n\t\tconst std::vector<unsigned int>& left_zero_padding,\r\n\t\tconst std::vector<unsigned int>& right_zero_padding)\r\n\t\t: window_sizes(window_sizes),\r\n\t\tinput_feature_map_count(input_feature_map_count),\r\n\t\toutput_feature_map_count(output_feature_map_count)\r\n\t{\r\n\t\tif ((left_zero_padding.size() != 0) && (left_zero_padding.size() != window_sizes.size()))\r\n\t\t\tthrow std::runtime_error((boost::format(\"Invalid dimension count %1% for left zero padding\") % left_zero_padding.size()).str());\r\n\t\tif ((right_zero_padding.size() != 0) && (right_zero_padding.size() != window_sizes.size()))\r\n\t\t\tthrow std::runtime_error((boost::format(\"Invalid dimension count %1% for right zero padding\") % right_zero_padding.size()).str());\r\n\r\n\t\tif (left_zero_padding.empty())\r\n\t\t\tthis->left_zero_padding.resize(window_sizes.size(), 0);\r\n\t\telse\r\n\t\t\tthis->left_zero_padding = left_zero_padding;\r\n\r\n\t\tif (right_zero_padding.empty())\r\n\t\t\tthis->right_zero_padding.resize(window_sizes.size(), 0);\r\n\t\telse\r\n\t\t\tthis->right_zero_padding = right_zero_padding;\r\n\r\n\t\tcheck();\r\n\t}\r\n\r\n\tvoid convolution_layer::check()\r\n\t{\r\n\t\tif (window_sizes.size() == 0)\r\n\t\t\tthrow neural_network_exception(\"window sizes for convolution layer may not be empty\");\r\n\r\n\t\tfor(unsigned int i = 0; i < window_sizes.size(); i++)\r\n\t\t\tif (window_sizes[i] == 0)\r\n\t\t\t\tthrow neural_network_exception(\"window dimension for convolution layer may not be zero\");\r\n\r\n\t\tfor(unsigned int i = 0; i < window_sizes.size(); i++)\r\n\t\t\tif (left_zero_padding[i] >= window_sizes[i])\r\n\t\t\t\tthrow neural_network_exception((boost::format(\"left zero padding %1% of dimension (%2%) is greater or equal than layer window size (%3%)\") % left_zero_padding[i] % i % window_sizes[i]).str());\r\n\r\n\t\tfor(unsigned int i = 0; i < window_sizes.size(); i++)\r\n\t\t\tif (right_zero_padding[i] >= window_sizes[i])\r\n\t\t\t\tthrow neural_network_exception((boost::format(\"right zero padding %1% of dimension (%2%) is greater or equal than layer window size (%3%)\") % right_zero_padding[i] % i % window_sizes[i]).str());\r\n\t}\r\n\r\n\tconst boost::uuids::uuid& convolution_layer::get_uuid() const\r\n\t{\r\n\t\treturn layer_guid;\r\n\t}\r\n\r\n\tconst std::string& convolution_layer::get_type_name() const\r\n\t{\r\n\t\treturn layer_type_name;\r\n\t}\r\n\r\n\tlayer_smart_ptr convolution_layer::clone() const\r\n\t{\r\n\t\treturn layer_smart_ptr(new convolution_layer(*this));\r\n\t}\r\n\r\n\tlayer_configuration convolution_layer::get_layer_configuration(const layer_configuration& input_configuration) const\r\n\t{\r\n\t\tif ((input_configuration.feature_map_count >= 0) && (input_configuration.feature_map_count != static_cast<int>(input_feature_map_count)))\r\n\t\t\tthrow neural_network_exception((boost::format(\"Feature map count in layer (%1%) and input configuration (%2%) don't match\") % input_feature_map_count % input_configuration.feature_map_count).str());\r\n\r\n\t\tif ((input_configuration.dimension_count >= 0) && (input_configuration.dimension_count != static_cast<int>(window_sizes.size())))\r\n\t\t\tthrow neural_network_exception((boost::format(\"Dimension count in layer (%1%) and input configuration (%2%) don't match\") % window_sizes.size() % input_configuration.dimension_count).str());\r\n\r\n\t\treturn layer_configuration(output_feature_map_count, static_cast<int>(window_sizes.size()));\r\n\t}\r\n\r\n\tlayer_configuration_specific convolution_layer::get_output_layer_configuration_specific(const layer_configuration_specific& input_configuration_specific) const\r\n\t{\r\n\t\tif (input_configuration_specific.feature_map_count != input_feature_map_count)\r\n\t\t\tthrow neural_network_exception((boost::format(\"Feature map count in layer (%1%) and input configuration (%2%) don't match\") % input_feature_map_count % input_configuration_specific.feature_map_count).str());\r\n\r\n\t\tif (input_configuration_specific.get_dimension_count() != window_sizes.size())\r\n\t\t\tthrow neural_network_exception((boost::format(\"Dimension count in layer (%1%) and input configuration (%2%) don't match\") % window_sizes.size() % input_configuration_specific.get_dimension_count()).str());\r\n\r\n\t\tlayer_configuration_specific res(output_feature_map_count);\r\n\r\n\t\tfor(unsigned int i = 0; i < window_sizes.size(); ++i)\r\n\t\t{\r\n\t\t\tunsigned int total_input_dimension_size = input_configuration_specific.dimension_sizes[i] + left_zero_padding[i] + right_zero_padding[i];\r\n\t\t\tif (total_input_dimension_size < window_sizes[i])\r\n\t\t\t\tthrow neural_network_exception((boost::format(\"Too small total dimension size (with padding) %1% of dimension (%2%) is smaller than layer window size (%3%)\") % total_input_dimension_size % i % window_sizes[i]).str());\r\n\r\n\t\t\tres.dimension_sizes.push_back(total_input_dimension_size + 1 - window_sizes[i]);\r\n\t\t}\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tlayer_configuration_specific convolution_layer::get_input_layer_configuration_specific(const layer_configuration_specific& output_configuration_specific) const\r\n\t{\r\n\t\tif (output_configuration_specific.feature_map_count != output_feature_map_count)\r\n\t\t\tthrow neural_network_exception((boost::format(\"Feature map count in layer (%1%) and output configuration (%2%) don't match\") % output_feature_map_count % output_configuration_specific.feature_map_count).str());\r\n\r\n\t\tif (output_configuration_specific.get_dimension_count() != window_sizes.size())\r\n\t\t\tthrow neural_network_exception((boost::format(\"Dimension count in layer (%1%) and output configuration (%2%) don't match\") % window_sizes.size() % output_configuration_specific.get_dimension_count()).str());\r\n\r\n\t\tlayer_configuration_specific res(input_feature_map_count);\r\n\r\n\t\tfor(unsigned int i = 0; i < window_sizes.size(); ++i)\r\n\t\t\tres.dimension_sizes.push_back(output_configuration_specific.dimension_sizes[i] + window_sizes[i] - 1 - left_zero_padding[i] - right_zero_padding[i]);\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tstd::vector<std::pair<unsigned int, unsigned int> > convolution_layer::get_input_rectangle_borders(const std::vector<std::pair<unsigned int, unsigned int> >& output_rectangle_borders) const\r\n\t{\r\n\t\tif (output_rectangle_borders.size() != window_sizes.size())\r\n\t\t\tthrow neural_network_exception((boost::format(\"Dimension count in layer (%1%) and output borders (%2%) don't match\") % window_sizes.size() % output_rectangle_borders.size()).str());\r\n\r\n\t\tstd::vector<std::pair<unsigned int, unsigned int> > res;\r\n\r\n\t\tfor(unsigned int i = 0; i < window_sizes.size(); ++i)\r\n\t\t\tres.push_back(\r\n\t\t\t\tstd::make_pair(\r\n\t\t\t\t\tstatic_cast<unsigned int>(std::max(0, static_cast<int>(output_rectangle_borders[i].first) - static_cast<int>(left_zero_padding[i]))),\r\n\t\t\t\t\t(output_rectangle_borders[i].second + window_sizes[i] - 1) - left_zero_padding[i]\r\n\t\t\t\t)\r\n\t\t\t);\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tvoid convolution_layer::write(std::ostream& binary_stream_to_write_to) const\r\n\t{\r\n\t\tbinary_stream_to_write_to.write(reinterpret_cast<const char*>(&input_feature_map_count), sizeof(input_feature_map_count));\r\n\t\tbinary_stream_to_write_to.write(reinterpret_cast<const char*>(&output_feature_map_count), sizeof(output_feature_map_count));\r\n\r\n\t\tunsigned int dimension_count = static_cast<unsigned int>(window_sizes.size());\r\n\t\tbinary_stream_to_write_to.write(reinterpret_cast<const char*>(&dimension_count), sizeof(dimension_count));\r\n\t\tbinary_stream_to_write_to.write(reinterpret_cast<const char*>(&(*window_sizes.begin())), sizeof(unsigned int) * dimension_count);\r\n\t\tbinary_stream_to_write_to.write(reinterpret_cast<const char*>(&(*left_zero_padding.begin())), sizeof(unsigned int) * dimension_count);\r\n\t\tbinary_stream_to_write_to.write(reinterpret_cast<const char*>(&(*right_zero_padding.begin())), sizeof(unsigned int) * dimension_count);\r\n\t}\r\n\r\n\tvoid convolution_layer::write_proto(void * layer_proto) const\r\n\t{\r\n\t\tprotobuf::Layer * layer_proto_typed = reinterpret_cast<protobuf::Layer *>(layer_proto);\r\n\t\tprotobuf::ConvolutionalParam * param = layer_proto_typed->mutable_convolution_param();\r\n\r\n\t\tparam->set_output_feature_map_count(output_feature_map_count);\r\n\t\tparam->set_input_feature_map_count(input_feature_map_count);\r\n\r\n\t\tfor(int i = 0; i < window_sizes.size(); ++i)\r\n\t\t{\r\n\t\t\tprotobuf::ConvolutionalParam_ConvolutionalDimensionParam * dim_param = param->add_dimension_param();\r\n\t\t\tdim_param->set_kernel_size(window_sizes[i]);\r\n\t\t\tif (left_zero_padding[i] > 0)\r\n\t\t\t\tdim_param->set_left_padding(left_zero_padding[i]);\r\n\t\t\tif (right_zero_padding[i] > 0)\r\n\t\t\t\tdim_param->set_right_padding(right_zero_padding[i]);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid convolution_layer::read(\r\n\t\tstd::istream& binary_stream_to_read_from,\r\n\t\tconst boost::uuids::uuid& layer_read_guid)\r\n\t{\r\n\t\tbinary_stream_to_read_from.read(reinterpret_cast<char*>(&input_feature_map_count), sizeof(input_feature_map_count));\r\n\t\tbinary_stream_to_read_from.read(reinterpret_cast<char*>(&output_feature_map_count), sizeof(output_feature_map_count));\r\n\r\n\t\tunsigned int dimension_count;\r\n\t\tbinary_stream_to_read_from.read(reinterpret_cast<char*>(&dimension_count), sizeof(dimension_count));\r\n\t\twindow_sizes.resize(dimension_count);\r\n\t\tbinary_stream_to_read_from.read(reinterpret_cast<char*>(&(*window_sizes.begin())), sizeof(unsigned int) * dimension_count);\r\n\r\n\t\tleft_zero_padding.resize(dimension_count, 0);\r\n\t\tright_zero_padding.resize(dimension_count, 0);\r\n\t\tif (layer_read_guid != layer_guid_v1)\r\n\t\t{\r\n\t\t\tbinary_stream_to_read_from.read(reinterpret_cast<char*>(&(*left_zero_padding.begin())), sizeof(unsigned int) * dimension_count);\r\n\t\t\tbinary_stream_to_read_from.read(reinterpret_cast<char*>(&(*right_zero_padding.begin())), sizeof(unsigned int) * dimension_count);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid convolution_layer::read_proto(const void * layer_proto)\r\n\t{\r\n\t\tconst protobuf::Layer * layer_proto_typed = reinterpret_cast<const protobuf::Layer *>(layer_proto);\r\n\t\tif (!layer_proto_typed->has_convolution_param())\r\n\t\t\tthrow neural_network_exception((boost::format(\"No convolution_param specified for layer %1% of type %2%\") % instance_name % layer_proto_typed->type()).str());\r\n\r\n\t\tinput_feature_map_count = layer_proto_typed->convolution_param().input_feature_map_count();\r\n\t\toutput_feature_map_count = layer_proto_typed->convolution_param().output_feature_map_count();\r\n\r\n\t\twindow_sizes.resize(layer_proto_typed->convolution_param().dimension_param_size());\r\n\t\tleft_zero_padding.resize(layer_proto_typed->convolution_param().dimension_param_size());\r\n\t\tright_zero_padding.resize(layer_proto_typed->convolution_param().dimension_param_size());\r\n\r\n\t\tfor(int i = 0; i < layer_proto_typed->convolution_param().dimension_param_size(); ++i)\r\n\t\t{\r\n\t\t\twindow_sizes[i] = layer_proto_typed->convolution_param().dimension_param(i).kernel_size();\r\n\t\t\tleft_zero_padding[i] = layer_proto_typed->convolution_param().dimension_param(i).left_padding();\r\n\t\t\tright_zero_padding[i] = layer_proto_typed->convolution_param().dimension_param(i).right_padding();\r\n\t\t}\r\n\r\n\t\tcheck();\r\n\t}\r\n\r\n\tdata_config convolution_layer::get_data_config() const\r\n\t{\r\n\t\tdata_config res;\r\n\r\n\t\tunsigned int weight_count = input_feature_map_count * output_feature_map_count;\r\n\t\tstd::for_each(window_sizes.begin(), window_sizes.end(), weight_count *= boost::lambda::_1);\r\n\r\n\t\tres.push_back(weight_count);\r\n\r\n\t\tres.push_back(output_feature_map_count);\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tvoid convolution_layer::randomize_data(\r\n\t\tlayer_data& data,\r\n\t\tlayer_data_custom& data_custom,\r\n\t\trandom_generator& generator) const\r\n\t{\r\n\t\tunsigned int weight_count = 1;\r\n\t\tstd::for_each(window_sizes.begin(), window_sizes.end(), weight_count *= boost::lambda::_1);\r\n\r\n\t\tfloat average_feature_map_count = sqrtf(static_cast<float>(input_feature_map_count) * static_cast<float>(output_feature_map_count));\r\n\r\n\t\tfloat standard_deviation = sqrtf(1.0F / (average_feature_map_count * static_cast<float>(weight_count)));\r\n\t\tfloat max_abs_value = 100.0F * standard_deviation;\r\n\r\n\t\tnnforge_normal_distribution<float> nd(0.0F, standard_deviation);\r\n\r\n\t\tfor(unsigned int i = 0; i < data[0].size(); ++i)\r\n\t\t{\r\n\t\t\tfloat val = nd(generator);\r\n\t\t\twhile (fabs(val) > max_abs_value)\r\n\t\t\t\tval = nd(generator);\r\n\r\n\t\t\tdata[0][i] = val;\r\n\t\t}\r\n\r\n\t\tstd::fill(data[1].begin(), data[1].end(), 0.0F);\r\n\t}\r\n\r\n\tvoid convolution_layer::randomize_orthogonal_data(\r\n\t\tlayer_data& data,\r\n\t\tlayer_data_custom& data_custom,\r\n\t\trandom_generator& generator) const\r\n\t{\r\n\t\tunsigned int weight_count = 1;\r\n\t\tstd::for_each(window_sizes.begin(), window_sizes.end(), weight_count *= boost::lambda::_1);\r\n\t\tunsigned int weight_col_count = weight_count * input_feature_map_count;\r\n\t\tunsigned int weight_row_count = output_feature_map_count;\r\n\r\n\t\tnnforge_normal_distribution<float> nd(0.0F, 1.0F);\r\n\t\tfor(unsigned int i = 0; i < data[0].size(); ++i)\r\n\t\t{\r\n\t\t\tfloat val = nd(generator);\r\n\t\t\tdata[0][i] = val;\r\n\t\t}\r\n\t\tcv::Mat1f weights(weight_row_count, weight_col_count, &(data[0][0]));\r\n\t\tcv::Mat1f w;\r\n\t\tcv::Mat1f u;\r\n\t\tcv::Mat1f vt;\r\n\t\tcv::SVD::compute(weights, w, u, vt, cv::SVD::MODIFY_A);\r\n\r\n\t\tcv::Mat1f orth;\r\n\t\tif ((u.rows == weights.rows) && (u.cols == weights.cols))\r\n\t\t\torth = u;\r\n\t\telse if ((vt.rows == weights.rows) && (vt.cols == weights.cols))\r\n\t\t\torth = vt;\r\n\t\telse\r\n\t\t\tthrow neural_network_exception(\"Internal error when doing SVD\");\r\n\r\n\t\tstd::copy(orth.begin(), orth.end(), weights.begin());\r\n\r\n\t\tstd::fill(data[1].begin(), data[1].end(), 0.0F);\r\n\t}\r\n\r\n\tfloat convolution_layer::get_forward_flops(const layer_configuration_specific& input_configuration_specific) const\r\n\t{\r\n\t\tunsigned int neuron_count = get_output_layer_configuration_specific(input_configuration_specific).get_neuron_count();\r\n\t\tunsigned int per_item_flops = input_feature_map_count * 2;\r\n\t\tstd::for_each(window_sizes.begin(), window_sizes.end(), per_item_flops *= boost::lambda::_1);\r\n\t\tper_item_flops -= 1;\r\n\r\n\t\treturn static_cast<float>(neuron_count) * static_cast<float>(per_item_flops);\r\n\t}\r\n\r\n\tfloat convolution_layer::get_backward_flops(const layer_configuration_specific& input_configuration_specific) const\r\n\t{\r\n\t\tunsigned int neuron_count = get_output_layer_configuration_specific(input_configuration_specific).get_neuron_count();\r\n\t\tunsigned int per_item_flops = input_feature_map_count * 2;\r\n\t\tstd::for_each(window_sizes.begin(), window_sizes.end(), per_item_flops *= boost::lambda::_1);\r\n\r\n\t\treturn static_cast<float>(neuron_count) * static_cast<float>(per_item_flops);\r\n\t}\r\n\r\n\tfloat convolution_layer::get_weights_update_flops(const layer_configuration_specific& input_configuration_specific) const\r\n\t{\r\n\t\tunsigned int neuron_count = get_output_layer_configuration_specific(input_configuration_specific).get_neuron_count();\r\n\t\tunsigned int per_item_flops = input_feature_map_count * 2;\r\n\t\tstd::for_each(window_sizes.begin(), window_sizes.end(), per_item_flops *= boost::lambda::_1);\r\n\r\n\t\treturn static_cast<float>(neuron_count) * static_cast<float>(per_item_flops);\r\n\t}\r\n\r\n\tlayer_data_configuration_list convolution_layer::get_layer_data_configuration_list() const\r\n\t{\r\n\t\tlayer_data_configuration_list res;\r\n\t\tres.push_back(layer_data_configuration(input_feature_map_count, output_feature_map_count, window_sizes));\r\n\t\tres.push_back(layer_data_configuration(1, output_feature_map_count, std::vector<unsigned int>()));\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tstd::set<unsigned int> convolution_layer::get_weight_decay_part_id_set() const\r\n\t{\r\n\t\tstd::set<unsigned int> res;\r\n\t\tres.insert(0);\r\n\t\treturn res;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "14da89b7973deb60df0e391b1c0268564962bd45", "size": 16745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nnforge/convolution_layer.cpp", "max_stars_repo_name": "anshumang/nnForgeINST", "max_stars_repo_head_hexsha": "1e9ea1b539cadbb03daa39f5d81025c1b17c21d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T08:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-18T21:10:36.000Z", "max_issues_repo_path": "nnforge/convolution_layer.cpp", "max_issues_repo_name": "anshumang/nnForgeINST", "max_issues_repo_head_hexsha": "1e9ea1b539cadbb03daa39f5d81025c1b17c21d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nnforge/convolution_layer.cpp", "max_forks_repo_name": "anshumang/nnForgeINST", "max_forks_repo_head_hexsha": "1e9ea1b539cadbb03daa39f5d81025c1b17c21d8", "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.8927613941, "max_line_length": 222, "alphanum_fraction": 0.745177665, "num_tokens": 3953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.05665242331706965, "lm_q1q2_score": 0.023505025865573945}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2021 Andreas Wagner.\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n////////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUMORMODELS_PETSC_MAT_HPP\n#define TUMORMODELS_PETSC_MAT_HPP\n\n#include <numeric>\n#include <vector>\n\n#include \"gmm.h\"\n#include \"petsc.h\"\n#include <Eigen/Dense>\n\nnamespace macrocirculation {\n\nclass PetscMat {\npublic:\n  PetscMat(const std::string &name, const std::vector<std::shared_ptr<DofMap>> &dof_map)\n      : PetscMat(name,\n                 std::accumulate(dof_map.begin(), dof_map.end(), 0, [](auto v, auto dm) { return v + dm->num_owned_dofs(); }),\n                 std::accumulate(dof_map.begin(), dof_map.end(), 0, [](auto v, auto dm) { return v + dm->num_dof(); })) {}\n\n  PetscMat(const std::string &name, const DofMap &dof_map)\n      : PetscMat(name, dof_map.num_owned_dofs(), dof_map.num_dof()) {}\n\n  PetscMat(const std::string &name, std::size_t num_owned_dofs, std::size_t num_dofs) {\n    CHKERRABORT(PETSC_COMM_WORLD, MatCreate(PETSC_COMM_WORLD, &d_mat));\n    CHKERRABORT(PETSC_COMM_WORLD, MatSetType(d_mat, MATMPIAIJ));\n    CHKERRABORT(PETSC_COMM_WORLD, MatSetSizes(d_mat, num_owned_dofs, num_owned_dofs, num_dofs, num_dofs));\n    // we overestimate the number non-zero entries, otherwise matrix assembly is incredibly slow :\n    CHKERRABORT(PETSC_COMM_WORLD, MatMPIAIJSetPreallocation(d_mat, 1000, nullptr, 1000, nullptr));\n    CHKERRABORT(PETSC_COMM_WORLD, PetscObjectSetName((PetscObject) d_mat, name.c_str()));\n  }\n\n  PetscMat(const PetscMat &) = delete;\n  PetscMat(PetscMat &&) = delete;\n  PetscMat &operator=(const PetscMat &) = delete;\n  PetscMat &operator=(PetscMat &&) = delete;\n\n  ~PetscMat() {\n    CHKERRABORT(PETSC_COMM_WORLD, MatDestroy(&d_mat));\n  }\n\n  void add(const std::vector<size_t> &row_dofs, const std::vector<size_t> &col_dofs, gmm::row_matrix<gmm::wsvector<double>> &mat_loc) {\n    assert(row_dofs.size() == mat_loc.nrows());\n    assert(col_dofs.size() == mat_loc.ncols());\n\n    // we have no guarantees that gmm's memory is continuous\n    // thus we copy it over\n    std::vector<double> mat_memory(row_dofs.size() * col_dofs.size(), 0);\n    for (int r = 0; r < row_dofs.size(); r += 1)\n      for (int c = 0; c < col_dofs.size(); c += 1)\n        mat_memory[c + r * col_dofs.size()] = mat_loc[r][c];\n\n    std::vector<PetscInt> row_dofs_(row_dofs.size(), 0);\n    for (int r = 0; r < row_dofs.size(); r += 1)\n      row_dofs_[r] = static_cast<PetscInt>(row_dofs[r]);\n\n    std::vector<PetscInt> col_dofs_(col_dofs.size(), 0);\n    for (int c = 0; c < col_dofs.size(); c += 1)\n      col_dofs_[c] = static_cast<PetscInt>(col_dofs[c]);\n\n    // pass it to petsc\n    CHKERRABORT(PETSC_COMM_WORLD,\n                MatSetValues(d_mat,\n                             static_cast<PetscInt>(row_dofs.size()),\n                             row_dofs_.data(),\n                             static_cast<PetscInt>(col_dofs.size()),\n                             col_dofs_.data(),\n                             mat_memory.data(),\n                             ADD_VALUES));\n  }\n\n  void add(const std::vector<size_t> &row_dofs, const std::vector<size_t> &col_dofs, Eigen::MatrixXd &mat_loc) {\n    assert(row_dofs.size() == mat_loc.rows());\n    assert(col_dofs.size() == mat_loc.cols());\n\n    // we have no guarantees that gmm's memory is continuous\n    // thus we copy it over\n    std::vector<double> mat_memory(row_dofs.size() * col_dofs.size(), 0);\n    for (int r = 0; r < row_dofs.size(); r += 1)\n      for (int c = 0; c < col_dofs.size(); c += 1)\n        mat_memory[c + r * col_dofs.size()] = mat_loc(r, c);\n\n    std::vector<PetscInt> row_dofs_(row_dofs.size(), 0);\n    for (int r = 0; r < row_dofs.size(); r += 1)\n      row_dofs_[r] = static_cast<PetscInt>(row_dofs[r]);\n\n    std::vector<PetscInt> col_dofs_(col_dofs.size(), 0);\n    for (int c = 0; c < col_dofs.size(); c += 1)\n      col_dofs_[c] = static_cast<PetscInt>(col_dofs[c]);\n\n    // pass it to petsc\n    CHKERRABORT(PETSC_COMM_WORLD,\n                MatSetValues(d_mat,\n                             static_cast<PetscInt>(row_dofs.size()),\n                             row_dofs_.data(),\n                             static_cast<PetscInt>(col_dofs.size()),\n                             col_dofs_.data(),\n                             mat_memory.data(),\n                             ADD_VALUES));\n  }\n\n  double norm1() const {\n    double value;\n    CHKERRABORT(PETSC_COMM_WORLD, MatNorm(d_mat, NORM_1, &value));\n    return value;\n  }\n\n  void zero() {\n    MatZeroEntries(d_mat);\n  }\n\n  void assemble() {\n    CHKERRABORT(PETSC_COMM_WORLD, MatAssemblyBegin(d_mat, MAT_FINAL_ASSEMBLY));\n    CHKERRABORT(PETSC_COMM_WORLD, MatAssemblyEnd(d_mat, MAT_FINAL_ASSEMBLY));\n  }\n\n  Mat &get_mat() { return d_mat; }\n\n  size_t first_dof() const {\n    PetscInt start = 0;\n    PetscInt end = 0;\n    CHKERRABORT(PETSC_COMM_WORLD, MatGetOwnershipRange(d_mat, &start, &end));\n    return start;\n  }\n\n  size_t last_dof() const {\n    PetscInt start = 0;\n    PetscInt end = 0;\n    CHKERRABORT(PETSC_COMM_WORLD, MatGetOwnershipRange(d_mat, &start, &end));\n    return end;\n  }\n\n  double get(size_t i, size_t j) const {\n    double value;\n    PetscInt ii = i;\n    PetscInt jj = j;\n    CHKERRABORT(PETSC_COMM_WORLD, MatGetValues(d_mat, 1, &ii, 1, &jj, &value));\n    return value;\n  }\n\n  void print() const {\n    CHKERRABORT(PETSC_COMM_WORLD, MatView(d_mat, PETSC_VIEWER_STDOUT_WORLD));\n    }\n\nprivate:\n  Mat d_mat{};\n};\n\ntemplate<typename Stream>\ninline Stream &operator<<(Stream &out, const PetscMat &m) {\n  auto ldof = m.last_dof();\n  for (size_t k = m.first_dof(); k < ldof; k += 1) {\n    for (size_t j = m.first_dof(); j < ldof; j += 1)\n      out << m.get(k, j) << \" \";\n    out << \"\\n\";\n  }\n  return out;\n}\n\n\n} // namespace macrocirculation\n\n#endif //TUMORMODELS_PETSC_MAT_HPP\n", "meta": {"hexsha": "8acb0f6ddd7793d7045f46540b18ed95f172e607", "size": 5986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/macrocirculation/petsc/petsc_mat.hpp", "max_stars_repo_name": "CancerModeling/Flows1D0D3D", "max_stars_repo_head_hexsha": "ca87bd11acd1f558ee64c379d051e41175a13b6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-12T11:42:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T11:42:31.000Z", "max_issues_repo_path": "src/macrocirculation/petsc/petsc_mat.hpp", "max_issues_repo_name": "CancerModeling/Flows1D0D3D", "max_issues_repo_head_hexsha": "ca87bd11acd1f558ee64c379d051e41175a13b6a", "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/macrocirculation/petsc/petsc_mat.hpp", "max_forks_repo_name": "CancerModeling/Flows1D0D3D", "max_forks_repo_head_hexsha": "ca87bd11acd1f558ee64c379d051e41175a13b6a", "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.2117647059, "max_line_length": 135, "alphanum_fraction": 0.6064149683, "num_tokens": 1723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.05582313799303739, "lm_q1q2_score": 0.023372974538385407}}
{"text": "/*\n * fold_pairs.hpp\n *\n *  Created on: Aug 28, 2009\n *      Author: stewie\n */\n\n#ifndef FOLD_PAIRS_HPP_\n#define FOLD_PAIRS_HPP_\n\n#include <functional>\n\n#include <boost/next_prior.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n\nnamespace bn {\n\nnamespace util {\n\n/**\n * Applies binary functions @a s and @a p on all the <em>2-combinations without\n * repetition</em> of elements in the given ranges.\n *\n * See fold_cartesian_product() for a formal description of the algorithm\n * replacing the cartesian product with the sequence of 2-combinations.\n * @param first forward iterator to the initial position of the range\n * @param last forward iterator to the final position of the range\n * @param init initial value for the accumulator\n * @param s binary function that implements the sum\n * @param p binary function that implements the product\n * @return the accumulated value\n *\n * @see for_each_pair() for the iteration version.\n */\ntemplate<class ForwardIterator, class T, class Sum, class Product> T fold_pairs(\n\t\tForwardIterator first, ForwardIterator last, T init, Sum s = std::plus<\n\t\t\t\tT>(), Product p = std::multiplies<T>()) {\n\tfor (; first != last; ++first)\n\t\tfor (ForwardIterator it = boost::next(first); it != last; ++it)\n\t\t\tinit = s(init, p(*first, *it));\n\treturn init;\n}\n\ntemplate<class ForwardRange, class T, class Sum, class Product> T fold_pairs(\n\t\tForwardRange& r, T init, Sum s = std::plus<T>(), Product p =\n\t\t\t\tstd::multiplies<T>()) {\n\treturn fold_pairs(boost::begin(r), boost::end(r), init, s, p);\n}\n\ntemplate<class ForwardRange, class T, class Sum, class Product> T fold_pairs(\n\t\tconst ForwardRange& r, T init, Sum s = std::plus<T>(), Product p =\n\t\t\t\tstd::multiplies<T>()) {\n\treturn fold_pairs(boost::begin(r), boost::end(r), init, s, p);\n}\n\n}\n\n}\n\n#endif /* FOLD_PAIRS_HPP_ */\n", "meta": {"hexsha": "3a80ab478a458233bdb5ce69fb8e91eaadb1ea25", "size": 1818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/util/algorithm/fold_pairs.hpp", "max_stars_repo_name": "Markfrancisrogers/BooleanNetwork", "max_stars_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-04T14:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-04T19:03:51.000Z", "max_issues_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/util/algorithm/fold_pairs.hpp", "max_issues_repo_name": "Markfrancisrogers/BooleanNetwork", "max_issues_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/util/algorithm/fold_pairs.hpp", "max_forks_repo_name": "Markfrancisrogers/BooleanNetwork", "max_forks_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "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.3225806452, "max_line_length": 80, "alphanum_fraction": 0.699669967, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04672495846016152, "lm_q1q2_score": 0.02336247923008076}}
{"text": "/*\r\n *@description - this file implements the the parallel Johnson's algorithm for\r\n                 single source shortest path on sparse graphs using MPI. It\r\n                 assumes the input graph file is in the format like the graph\r\n                 http://snap.stanford.edu/data/web-Google.html\r\n                 The node numbers are continuous intergers starting from 0.\r\n                 The implementation depends on the Boost library.\r\n *@author: Yao Zhu (yzhucs@gmail.com).\r\n */\r\n\r\n#include <algorithm>\r\n#include <boost/heap/fibonacci_heap.hpp>\r\n#include <climits>\r\n#include <cmath>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <mpi.h>\r\n#include <sstream>\r\n#include <string>\r\n#include <sys/time.h>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing namespace boost::heap;\r\n\r\n// some constants definition.\r\n#define INT_INF \t\t\t100000//INT_MAX\t// indicate an inf value.\r\n\r\n// output a vector in column format to a stream.\r\nvoid output_vector(ostream &out, const int* const z, const int len) {\r\n\tif (z == NULL) {\r\n\t\tcerr << \"z cannot be NULL in output_vector().\" << endl;\r\n\t\texit(-1);\r\n\t}\r\n\r\n\tout << \"the vector is:\" << endl;\r\n\tfor (int i = 0; i < len; i++) {\r\n\t\tif (z[i] != INT_INF) {\r\n\t\t\tout << z[i] << endl;\r\n\t\t} else {\r\n\t\t\tout << \"inf\" << endl;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n// let process 0 print out some message for showing the progress.\r\nvoid print_msg(string msg, int rank) {\r\n\tif (rank == 0) {\r\n\t\tcerr << msg << endl;\r\n\t}\r\n}\r\n\r\n/*\r\n *@description - read in the webgraph data. (src[m], dest[m]) is a directed edge\r\n \t \t \t \t in the webgraph. This function also returns the maximum node\r\n \t \t \t \t number, which is number of nodes - 1 (we assume the node\r\n \t \t \t \t number starts from 0).\r\n *@param - webgraph_file, name of the webgraph file.\r\n *@param[out] - src, the array of source nodes.\r\n *@param[out] - dest, the array of the destination nodes.\r\n *@param[out] - nnz, number of edges.\r\n *@return - the maximum node number.\r\n */\r\nint read_webgraph(const char *webgraph_file, int **src, int **dest, int *nnz) {\r\n\tstd::ifstream wbfile(webgraph_file);\r\n\tstring line;\r\n\t*nnz = 0;\r\n\t// count the number of edges.\r\n\twhile (std::getline(wbfile, line)) {\r\n\t\t// check the 1st character of this line.\r\n\t\tif (line[0] >= '0' && line[0] <= '9') {\r\n\t\t\t(*nnz)++;\r\n\t\t}\r\n\t}\r\n\t// allocate storage in coordinate format.\r\n\t*src = new int[*nnz];\r\n\t*dest = new int[*nnz];\r\n\tif (*src == NULL || *dest == NULL) {\r\n\t\tcerr << \"cannot allocate src or dest in read_webgraph().\" << endl;\r\n\t\texit(-1);\r\n\t}\r\n\t// return to the beginning of the input file.\r\n\twbfile.clear();\r\n\twbfile.seekg(0, ios::beg);\r\n\tint i = 0;\r\n\tint max_nn = -1;\t// maximum node number.\r\n\twhile (std::getline(wbfile, line)) {\r\n\t\t// check the 1st character of this line.\r\n\t\tif (line[0] >= '0' && line[0] <= '9') {\r\n\t\t\tstd::istringstream iss(line);\r\n\t\t\tiss >> (*src)[i] >> (*dest)[i];\r\n\t\t\tif ((*src)[i] > max_nn) {\r\n\t\t\t\tmax_nn = (*src)[i];\r\n\t\t\t}\r\n\t\t\tif ((*dest)[i] > max_nn) {\r\n\t\t\t\tmax_nn = (*dest)[i];\r\n\t\t\t}\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\twbfile.close();\r\n\treturn max_nn;\r\n}\r\n\r\n/*\r\n *@description - construct the CSR format of the sparse digraph matrix\r\n \t \t \t \t (src, dest) from the coordinate format given by (src, dest).\r\n *@param - (src, dest) defines the web graph edges.\r\n *@param - nnz, number of nonzero elements. it's the length of\r\n \t \t   src, dest, val, and col_ind.\r\n *@param - N, number of nodes, it's the length of row_ptr.\r\n *@param - (val, col_ind, row_ptr) represents the CSR format of the sparse\r\n \t \t   digraph matrix (src, dest).\r\n */\r\nvoid coord2csr(const int* const src, const int* const dest,\r\n\t\t\t   const int nnz, const int N,\r\n\t\t\t   int *val, int *col_ind, int *row_ptr) {\r\n\tif (src == NULL || dest == NULL) {\r\n\t\tcerr << \"none of src and dest can be NULL in coord2csr().\" << endl;\r\n\t\texit(-1);\r\n\t}\r\n\tif (val == NULL || col_ind == NULL || row_ptr == NULL) {\r\n\t\tcerr << \"none of val, col_ind, and row_ptr can be NULL in \"\r\n\t\t\t\t\"coord2csr().\" << endl;\r\n\t\texit(-1);\r\n\t}\r\n\t// we need the out_degree to construct the CSR format.\r\n\tint *out_degree = new int[N];\r\n\tstd::fill(out_degree, out_degree + N, 0);\r\n\tfor (int l = 0; l < nnz; l++) {\r\n\t\tint i = src[l];\r\n\t\tout_degree[i]++;\r\n\t}\r\n\t// compute row_ptr as the cumsum of out_degree.\r\n\t// note row_ptr[N] = nnz. the node numbers are in [0..N-1].\r\n\trow_ptr[0] = 0;\r\n\tfor (int i = 1; i < N+1; i++) {\r\n\t\trow_ptr[i] = row_ptr[i-1] + out_degree[i-1];\r\n\t}\r\n\t// construct val and col_ind according to row_ptr.\r\n\tfor (int l = 0; l < nnz; l++) {\r\n\t\tint i = src[l];\r\n\t\tint j = dest[l];\r\n\t\tcol_ind[row_ptr[i]] = j;\r\n\t\tval[row_ptr[i]] = 1;\r\n\t\trow_ptr[i]++;\r\n\t}\r\n\t// recompute row_ptr as the cumsum of out_degree.\r\n\trow_ptr[0] = 0;\r\n\tfor (int i = 1; i < N+1; i++) {\r\n\t\trow_ptr[i] = row_ptr[i-1] + out_degree[i-1];\r\n\t}\r\n\t// deallocate out_degree.\r\n\tif (out_degree != NULL) {\r\n\t\tdelete [] out_degree;\r\n\t}\r\n}\r\n\r\n/*\r\n *@description - get the rank of the process that has the node with the given\r\n \t \t \t \t node number. This partition assumes all the remnant elements\r\n \t \t \t \t are given to the last process.\r\n *@param - nn, node number.\r\n *@param - N, total number of nodes.\r\n *@param - nproc, number of processes.\r\n */\r\nint nn2rank(const int nn, const int N, const int nproc) {\r\n\tint quota = int(N / nproc);\r\n\tif (nn >= quota * nproc) {\r\n\t\treturn (nproc - 1);\r\n\t} else {\r\n\t\treturn int(nn / quota);\r\n\t}\r\n}\r\n\r\n/*\r\n *@description - get the number of rows a process p has from the row partition\r\n \t\t\t\t scheme.\r\n *@param - N, total number of rows (one row correspond to one node).\r\n *@param - nproc, total number of processes.\r\n *@param - rank, of the process.\r\n */\r\nint get_Nlocal(const int N, const int nproc, const int rank) {\r\n\tint quota = int(N / nproc);\r\n\tif (rank == nproc - 1) {\t// the last process.\r\n\t\treturn (N - (nproc - 1) * quota);\r\n\t} else {\r\n\t\treturn quota;\r\n\t}\r\n}\r\n\r\n/*\r\n *@description - get the first node number that belongs to a process p.\r\n */\r\nint get_start_nn(const int N, const int nproc, const int rank) {\r\n\tint quota = int(N / nproc);\r\n\treturn (quota * rank);\r\n}\r\n\r\n/*\r\n *@description - definition of a data item stored in the priority queue.\r\n */\r\nstruct pq_data\r\n{\r\n    int node_number;\t\t//the global node number.\r\n    int dist;\t\t\t\t//current value of distance from the source node.\r\n\r\n    pq_data(int nn, int d): node_number(nn), dist(d) {}\r\n\r\n    bool operator< (pq_data const & data) const\r\n    {\r\n    \t// we define this way because we want our priority queue to be min-heap.\r\n        return dist > data.dist;\r\n    }\r\n};\r\n\r\ntypedef fibonacci_heap<pq_data>::handle_type handle_t;\r\n\r\n/*\r\n *@description - this function is to encapsulate the operation to the local\r\n \t \t \t \t priority queue.\r\n *@param - total_out_num will index into node_buffer and dist_buffer.\r\n */\r\nvoid extract_local_pq(int *sp, fibonacci_heap<pq_data> &local_pq,\r\n\t\t\t\t\t  handle_t *handle_local_pq, const int N, const int nproc,\r\n\t\t\t\t\t  const int rank, const int start_nn,\r\n\t\t\t\t\t  const int* const local_row_ptr,\r\n\t\t\t\t\t  const int* const local_col_ind,\r\n\t\t\t\t\t  const int* const local_val, int *sendcnts,\r\n\t\t\t\t\t  int *node_buffer, int *dist_buffer, int &total_out_num) {\r\n\tif (!local_pq.empty()) {\r\n\t\t// get the top data item.\r\n\t\tpq_data data_item = local_pq.top();\r\n\t\tif (data_item.dist != INT_INF) {\r\n\t\t\t// extract it from the queue.\r\n\t\t\tlocal_pq.pop();\r\n\t\t\tint u = data_item.node_number;\r\n\t\t\tsp[u] = data_item.dist;\r\n\t\t\t// scan the adjacency list of this node.\r\n\t\t\tfor (int l = local_row_ptr[u-start_nn];\r\n\t\t\t\t l < local_row_ptr[u-start_nn+1]; l++) {\r\n\t\t\t\t// v is the neighbor node number (in global value).\r\n\t\t\t\tint v = local_col_ind[l];\r\n\t\t\t\tint edge_weight = local_val[l];\r\n\t\t\t\t// check whether v is a node belong itself or not.\r\n\t\t\t\tif (nn2rank(v, N, nproc) == rank) {\r\n\t\t\t\t\tif (sp[v] == INT_INF) { // v still in the queue.\r\n\t\t\t\t\t\tif ((*handle_local_pq[v-start_nn]).dist >\r\n\t\t\t\t \t \t \tsp[u] + edge_weight) {\r\n\t\t\t\t\t\t\t// decrease dist value to v.\r\n\t\t\t\t\t\t\tpq_data temp_data_item(v, sp[u] + edge_weight);\r\n\t\t\t\t\t\t\tlocal_pq.decrease(handle_local_pq[v-start_nn],\r\n\t\t\t\t\t\t\t\t\t\t\t  temp_data_item);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else if (sp[v] > sp[u] + edge_weight) {\r\n\t\t\t\t\t\t\t// v is already extracted.\r\n\t\t\t\t\t\t// insert v back to queue.\r\n\t\t\t\t\t\tpq_data temp_data_item(v, sp[u] + edge_weight);\r\n\t\t\t\t\t\thandle_local_pq[v-start_nn] =\r\n\t\t\t\t\t\t\t\tlocal_pq.push(temp_data_item);\r\n\t\t\t\t\t\tsp[v] = INT_INF;\t// mark it in the queue again.\r\n\t\t\t\t\t}\r\n\t\t\t\t} else { // v belong to another process.\r\n\t\t\t\t\t// record v and distance to it.\r\n\t\t\t\t\tnode_buffer[total_out_num] = v;\r\n\t\t\t\t\tdist_buffer[total_out_num] = sp[u] + edge_weight;\r\n\t\t\t\t\ttotal_out_num++;\r\n\t\t\t\t\t// get the process that has v.\r\n\t\t\t\t\tint proc_rank = nn2rank(v, N, nproc);\r\n\t\t\t\t\t// we send the node number and its distance.\r\n\t\t\t\t\tsendcnts[proc_rank] += 2;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} // if (!local_pq.empty())\r\n}\r\n\r\n/*\r\n *@descriptioni - it assumes the node number starts from 0.\r\n *@param - argv[1] - name of the file storing web graph.\r\n *@param - argv[2] - the node number (starts from 0) of the source node.\r\n *@param - argv[3] - file to store the solution vector.\r\n */\r\nint parallel_johnson(int argc, char *argv[]) {\r\n\tint nproc;\t\t\t\t\t\t\t// total number of processes.\r\n\tint N;\t\t\t\t\t\t\t\t// total number of nodes.\r\n\tint rank;\t\t\t\t\t\t\t// rank of the process.\r\n\r\n\tMPI_Comm_size(MPI_COMM_WORLD, &nproc);\r\n\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\r\n\r\n\tif (argc != 4) {\r\n\t\tif (rank == 0) {\r\n\t\t\tcerr << \"to run this program must supply the following command \"\r\n\t\t\t\t\t\"line arguments (in order)\" << endl;\r\n\t\t\tcerr << \"argv[1]---web graph file.\" << endl;\r\n\t\t\tcerr << \"argv[2]---source node number.\" << endl;\r\n\t\t\tcerr << \"argv[3]---file to save the solution.\" << endl;\r\n\t\t}\r\n\t\texit(-1);\r\n\t}\r\n\r\n\t//--------process 0 reads in the web graph, change it to CSR format\r\n\t//--------and then partition the nodes and distributes them to each process.\r\n\r\n\t// data only used by process 0 for reading in the webgraph.\r\n\tint *val = NULL;\r\n\tint *col_ind = NULL;\r\n\tint *row_ptr = NULL;\r\n\r\n\tif (rank == 0) {\r\n\t\tprint_msg(\"process 0 reads in the web graph data......\", rank);\r\n\t\t// process 0 reads in the web graph from file in coordinate format.\r\n\t\tint *src = NULL;\r\n\t\tint *dest = NULL;\r\n\t\tint nnz = 0;\r\n\t\tN = read_webgraph(argv[1], &src, &dest, &nnz) + 1;\r\n\t\tcerr << \"N = \" << N << endl;\r\n\t\t// construct the CSR format of the sparse matrix P from the\r\n\t\t// coordinate format.\r\n\t\tval = new int[nnz];\r\n\t\tcol_ind = new int[nnz];\r\n\t\trow_ptr = new int[N+1];\r\n\t\tcoord2csr(src, dest, nnz, N, val, col_ind, row_ptr);\r\n\r\n\t\t// we no longer need src and dest.\r\n\t\tif (src != NULL) {\r\n\t\t\tdelete [] src;\r\n\t\t\tsrc = NULL;\r\n\t\t}\r\n\t\tif (dest != NULL) {\r\n\t\t\tdelete [] dest;\r\n\t\t\tdest = NULL;\r\n\t\t}\r\n\t\tnnz = 0;\r\n\t}\r\n\r\n\tprint_msg(\"read in the webgraph is done.\", rank);\r\n\r\n\t/***collective communications for scattering necessary information.***/\r\n\t// broadcast the total number of nodes.\r\n\tMPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);\r\n\t// process 0 prepare the information for scattering P.\r\n\t// nnz of the row block local to each process. it's also the sendcounts\r\n\t// buffer used to scatter val and col_ind.\r\n\tint *local_nnz = NULL;\r\n\t// the data sent to process p start at location displs_csr[p] when\r\n\t// scattering val and col_ind.\r\n\tint *displs_csr = NULL;\r\n\t// the sendcounts buffer used to scatter row_ptr.\r\n\tint *sendcounts_node = NULL;\r\n\t// the data sent to process p start at location displs_node[p] when\r\n\t// scattering row_ptr.\r\n\tint *displs_node = NULL;\r\n\tif (rank == 0) {\r\n\t\tint quota = int(N / nproc);\r\n\t\tlocal_nnz = new int[nproc];\r\n\t\tdispls_csr = new int[nproc];\r\n\t\tsendcounts_node = new int[nproc];\r\n\t\tdispls_node = new int[nproc];\r\n\t\tfor (int p = 0; p < nproc; p++) {\r\n\t\t\tint sp = p * quota;\r\n\t\t\tint tp;\r\n\t\t\tif (p != nproc - 1) {\r\n\t\t\t\ttp = (p + 1) * quota - 1;\r\n\t\t\t} else {\r\n\t\t\t\ttp = N - 1;\r\n\t\t\t}\r\n\t\t\tlocal_nnz[p] = row_ptr[tp+1] - row_ptr[sp];\r\n\t\t\tdispls_csr[p] = row_ptr[sp];\r\n\t\t\tsendcounts_node[p] = get_Nlocal(N, nproc, p);\r\n\t\t\tdispls_node[p] = sp;\r\n\t\t}\r\n\t}\r\n\t// (local_val, local_col_ind, local_row_ptr) represents the CSR format\r\n\t// of the row block local to this process.\r\n\tint *local_val = NULL;\r\n\tint *local_col_ind = NULL;\r\n\tint *local_row_ptr = NULL;\r\n\t// allocate space for local_row_ptr according to the row parition scheme.\r\n\tint start_nn = get_start_nn(N, nproc, rank);\t// first node belong to the\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// process.\r\n\t// this process will possess node numbers [start_nn..start_nn+Nlocal]\r\n\t// assuming the contiguous row partition.\r\n\tint Nlocal = get_Nlocal(N, nproc, rank);\r\n\tlocal_row_ptr = new int[Nlocal + 1];\t// local_row_ptr[Nlocal] stores nnz\r\n\t\t\t\t\t\t\t\t\t\t\t// local to this process from\r\n\t\t\t\t\t\t\t\t\t\t\t// row partition.\r\n\t// process 0 scatter local_nnz to each process.\r\n\tMPI_Scatter(local_nnz, 1, MPI_INT, local_row_ptr+Nlocal, 1, MPI_INT,\r\n\t\t\t\t0, MPI_COMM_WORLD);\r\n\t// allocate space for local_val and local_col_ind with the size given by\r\n\t// local_row_ptr[Nlocal].\r\n\tlocal_val = new int[local_row_ptr[Nlocal]];\r\n\tlocal_col_ind = new int[local_row_ptr[Nlocal]];\r\n\t/***process 0 scatterv the sparse matrix P in CSR format.***/\r\n\t// process 0 scatterv val and col_ind to each process.\r\n\tMPI_Scatterv(val, local_nnz, displs_csr, MPI_INT, local_val,\r\n\t\t\t\t local_row_ptr[Nlocal], MPI_INT, 0, MPI_COMM_WORLD);\r\n\tMPI_Scatterv(col_ind, local_nnz, displs_csr, MPI_INT, local_col_ind,\r\n\t\t\t\t local_row_ptr[Nlocal], MPI_INT, 0, MPI_COMM_WORLD);\r\n\t// process 0 scatterv row_ptr to each process.\r\n\tMPI_Scatterv(row_ptr, sendcounts_node, displs_node, MPI_INT,\r\n\t\t\t\t local_row_ptr, Nlocal, MPI_INT, 0, MPI_COMM_WORLD);\r\n\t// adjust local_row_ptr to make it start from 0.\r\n\tfor (int i = Nlocal - 1; i >= 0; i--) {\r\n\t\tlocal_row_ptr[i] -= local_row_ptr[0];\r\n\t}\r\n\r\n\tprint_msg(\"distribute sparse matrix is done.\", rank);\r\n\r\n\t// process 0 cleans up some space no longer needed.\r\n\tif (rank == 0) {\r\n\t\tif (val != NULL) {\r\n\t\t\tdelete [] val;\r\n\t\t\tval = NULL;\r\n\t\t}\r\n\t\tif (col_ind != NULL) {\r\n\t\t\tdelete [] col_ind;\r\n\t\t\tcol_ind = NULL;\r\n\t\t}\r\n\t\tif (row_ptr != NULL) {\r\n\t\t\tdelete [] row_ptr;\r\n\t\t\trow_ptr = NULL;\r\n\t\t}\r\n\t\tif (local_nnz != NULL) {\r\n\t\t\tdelete [] local_nnz;\r\n\t\t\tlocal_nnz = NULL;\r\n\t\t}\r\n\t\tif (displs_csr != NULL) {\r\n\t\t\tdelete [] displs_csr;\r\n\t\t\tdispls_csr = NULL;\r\n\t\t}\r\n\t\t// sendcounts_node and displs_node will be reused when gathering\r\n\t\t// the solution back.\r\n\t}\r\n\r\n\t// we store the sp vector in full. but each process only needs to\r\n\t// operate on the elements it need. sp stores the snapshot shortest path\r\n\t// distance from s to each node.\r\n\tint *sp = new int[N];\r\n\t// initialize sp to be INT_INF.\r\n\tstd::fill(sp + start_nn, sp + start_nn + Nlocal, INT_INF);\r\n\r\n\t// get the source node number from command line.\r\n\tint source_node = atoi(argv[2]);\r\n\tif (rank == 0) {\r\n\t\tcerr << \"compute shortest paths from source node: \"\r\n\t\t\t << source_node << endl;\r\n\t\tcerr << \"parallel Johnson's algorithm starts......\" << endl;\r\n\t}\r\n\r\n\t// time variables for profiling. we need to include the time for\r\n\t// constructing the dependency among processes.\r\n\tstruct timeval start_tv, end_tv;\r\n\t// barrier for time profiling.\r\n\tMPI_Barrier(MPI_COMM_WORLD);\r\n\tif (rank == 0) {\r\n\t\tgettimeofday(&start_tv, NULL);\r\n\t}\r\n\r\n\t//--------parallel Johnson's algorithm through MPI.-----------\r\n\r\n\tfibonacci_heap<pq_data> local_pq;\t// local priority queue.\r\n\t//typedef fibonacci_heap<pq_data>::handle_type handle_t;\r\n\t// handle to local_pq. it provides the random access to queue elements,\r\n\t// as well as for changing the key directly.\r\n\thandle_t *handle_local_pq = NULL;\r\n\tint local_pq_len = 0;\t\t\t\t// length of local_pq.\r\n\tint total_pq_len = 0;\t\t\t\t// total length of all local_pq across\r\n\t\t\t\t\t\t\t\t\t\t// processes.\r\n\r\n\t// initialize the local priority queue and its handle.\r\n\thandle_local_pq = new handle_t[Nlocal];\r\n\tfor (int i = 0; i < Nlocal; i++) {\r\n\t\tint dist;\r\n\t\tif ((i + start_nn) == source_node) {\r\n\t\t\tdist = 0;\r\n\t\t} else {\r\n\t\t\tdist = INT_INF;\r\n\t\t}\r\n\t\tpq_data data_item(start_nn + i, dist);\r\n\t\thandle_local_pq[i] = local_pq.push(data_item);\r\n\t}\r\n\r\n\t// space to communicate possible shortest distances to nodes across\r\n\t// processes.\r\n\tint senddisp[nproc];\r\n\tint sendcnts[nproc];\r\n\tint recvdisp[nproc];\r\n\tint recvcnts[nproc];\r\n\t// we will send and recv node number and its distances simultaneously.\r\n\tint *sendbuf = new int[2 * N];\r\n\tint *recvbuf = new int[2 * N];\r\n\r\n\t// buffer to store the node number and distance to them, for communicating\r\n\t// to other processes.\r\n\tint *node_buffer = new int[N];\r\n\tint *dist_buffer = new int[N];\r\n\tint total_out_num;\t// total number of nodes to send out. it will be\r\n\t\t\t\t\t\t// the effective length of node_buffer and dist_buffer.\r\n\tint total_in_num;\t// total number of nodes to recv. the effective length\r\n\t\t\t\t\t\t// of recvbuf is 2*total_in_num.\r\n\r\n\tdo {\r\n\t\t// initialize space for communication.\r\n\t\tstd::fill(sendcnts, sendcnts + nproc, 0);\r\n\t\tstd::fill(recvcnts, recvcnts + nproc, 0);\r\n\t\ttotal_out_num = 0;\r\n\r\n\t\t// check the local priority queue.\r\n\t\tconst int async_iter = 30;\r\n\t\tfor (int l = 0; l < async_iter; l++) {\r\n\t\t\textract_local_pq(sp, local_pq, handle_local_pq, N, nproc, rank,\r\n\t\t\t\t\t\t\t start_nn, local_row_ptr, local_col_ind, local_val,\r\n\t\t\t\t\t\t\t sendcnts, node_buffer, dist_buffer, total_out_num);\r\n\t\t}\r\n\t\t// use MPI_Alltoall() to let each process aware of the number of\r\n\t\t// (node, distance) it will receive from each other process.\r\n\t\tMPI_Alltoall(sendcnts, 1, MPI_INT, recvcnts, 1, MPI_INT,\r\n\t\t\t\t\t MPI_COMM_WORLD);\r\n\t\t// prepare senddisp and recvdisp.\r\n\t\ttotal_in_num = 0;\r\n\t\tfor (int i = 0; i < nproc; i++) {\r\n\t\t\ttotal_in_num += recvcnts[i]/2;\r\n\t\t\tif (i > 0) {\r\n\t\t\t\tsenddisp[i] = senddisp[i-1] + sendcnts[i-1];\r\n\t\t\t\trecvdisp[i] = recvdisp[i-1] + recvcnts[i-1];\r\n\t\t\t} else {\r\n\t\t\t\tsenddisp[i] = 0;\r\n\t\t\t\trecvdisp[i] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\t// prepared the content of the sendbuf using senddisp.\r\n\t\tfor(int j = 0; j < total_out_num; j++) {\r\n\t\t\tint i = nn2rank(node_buffer[j], N, nproc);\r\n\t\t\t// put the key and value in sendbuf.\r\n\t\t\tsendbuf[senddisp[i]++] = node_buffer[j];\r\n\t\t\tsendbuf[senddisp[i]++] = dist_buffer[j];\r\n\t\t}\r\n\r\n\t\t// reconstruct senddisp.\r\n\t\tfor (int i = 0; i < nproc; i++) {\r\n\t\t\tif (i > 0) {\r\n\t\t\t\tsenddisp[i] = senddisp[i-1] + sendcnts[i-1];\r\n\t\t\t} else {\r\n\t\t\t\tsenddisp[i] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\t// use MPI_Alltoallv() to communicate the nodes and distances.\r\n\t\tMPI_Alltoallv(sendbuf, sendcnts, senddisp, MPI_INT, recvbuf,\r\n\t\t\t\t\t  recvcnts, recvdisp, MPI_INT, MPI_COMM_WORLD);\r\n\r\n\t\t// scan the recvbuf for distances found by other processes.\r\n\t\tfor (int j = 0; j < total_in_num; j++) {\r\n\t\t\tint v = recvbuf[2*j];\r\n\t\t\tint v_dist = recvbuf[2*j + 1];\r\n\t\t\tif (sp[v] == INT_INF) { // v still in the queue.\r\n\t\t\t\tif ((*handle_local_pq[v-start_nn]).dist > v_dist) {\r\n\t\t\t\t\t// decrease dist value to v.\r\n\t\t\t\t\tpq_data temp_data_item(v, v_dist);\r\n\t\t\t\t\tlocal_pq.decrease(handle_local_pq[v-start_nn],\r\n\t\t\t\t\t\t\t\t\t  temp_data_item);\r\n\t\t\t\t}\r\n\t\t\t} else if (sp[v] > v_dist) { // v is already extracted.\r\n\t\t\t\t// insert v back to queue.\r\n\t\t\t\tpq_data temp_data_item(v, v_dist);\r\n\t\t\t\thandle_local_pq[v-start_nn] = local_pq.push(temp_data_item);\r\n\t\t\t\tsp[v] = INT_INF;\t// mark it in the queue again.\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// MPI_Allreduce to get the total length of local priority queues\r\n\t\t// to detect termination.\r\n\t\t// we need to check the effective size of local_pq, i.e., #elements\r\n\t\t// with finite values in local_pq. We only need to check the top.\r\n\t\tif (!local_pq.empty()) {\r\n\t\t\tpq_data check_data_item = local_pq.top();\r\n\t\t\tif (check_data_item.dist != INT_INF) {\r\n\t\t\t\tlocal_pq_len = 1;\r\n\t\t\t} else {\r\n\t\t\t\tlocal_pq_len = 0;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tlocal_pq_len = 0;\r\n\t\t}\r\n\t\tMPI_Allreduce(&local_pq_len, &total_pq_len, 1,\r\n\t\t\t\t\t  MPI_INT, MPI_SUM, MPI_COMM_WORLD);\r\n\t\tif (total_pq_len == 0) { // when every process is done.\r\n\t\t\tbreak;\r\n\t\t}\r\n\t} while (true);\r\n\r\n\t// barrier for time profiling.\r\n\tMPI_Barrier(MPI_COMM_WORLD);\r\n\tif (rank == 0) {\r\n\t\tgettimeofday(&end_tv, NULL);\r\n\t\tdouble tElapsed = (end_tv.tv_sec + end_tv.tv_usec/1000000.0) -\r\n\t\t\t\t\t\t  (start_tv.tv_sec + start_tv.tv_usec/1000000.0);\r\n\t\tcerr << \"parallel Johnson's algorithm completes.\" << endl;\r\n\t\tcout << \"Time: \" << tElapsed << \" seconds when using \"\r\n\t\t\t << nproc << \" processes.\" << endl;\r\n\t}\r\n\r\n\t// process 0 gather the sp vector and stores it.\r\n\tint *sp_sol = NULL;\t\t\t// the final vector of shortest path distance.\r\n\tif (rank == 0) {\r\n\t\tsp_sol = new int[N];\r\n\t}\r\n\tMPI_Gatherv(sp + start_nn, Nlocal, MPI_INT, sp_sol,\r\n\t\t\t    sendcounts_node, displs_node, MPI_INT, 0,\r\n\t\t\t    MPI_COMM_WORLD);\r\n\tif (rank == 0) {\r\n\t\t// save the sp_sol vector.\r\n\t\tofstream out(argv[3], ios::trunc);\r\n\t\toutput_vector(out, sp_sol, N);\r\n\t\tcerr << \"the shortest path distance vector has been saved in file \"\r\n\t\t\t << argv[3] << endl;\r\n\t\t// we no longer need sendcounts_node and displs_node.\r\n\t\tif (sendcounts_node != NULL) {\r\n\t\t\tdelete [] sendcounts_node;\r\n\t\t\tsendcounts_node = NULL;\r\n\t\t}\r\n\t\tif (displs_node != NULL) {\r\n\t\t\tdelete [] displs_node;\r\n\t\t\tdispls_node = NULL;\r\n\t\t}\r\n\t\t// we no longer need sp_sol.\r\n\t\tif (sp_sol != NULL) {\r\n\t\t\tdelete [] sp_sol;\r\n\t\t\tsp_sol = NULL;\r\n\t\t}\r\n\t}\r\n\r\n\t// clean up all the space.\r\n\tif (local_val != NULL) {\r\n\t\tdelete [] local_val;\r\n\t\tlocal_val = NULL;\r\n\t}\r\n\tif (local_col_ind != NULL) {\r\n\t\tdelete [] local_col_ind;\r\n\t\tlocal_col_ind = NULL;\r\n\t}\r\n\tif (local_row_ptr != NULL) {\r\n\t\tdelete [] local_row_ptr;\r\n\t\tlocal_row_ptr = NULL;\r\n\t}\r\n\tif (sp != NULL) {\r\n\t\tdelete [] sp;\r\n\t\tsp = NULL;\r\n\t}\r\n\tif (handle_local_pq != NULL) {\r\n\t\tdelete [] handle_local_pq;\r\n\t\thandle_local_pq = NULL;\r\n\t}\r\n\tif (sendbuf != NULL) {\r\n\t\tdelete [] sendbuf;\r\n\t\tsendbuf = NULL;\r\n\t}\r\n\tif (recvbuf != NULL) {\r\n\t\tdelete [] recvbuf;\r\n\t\trecvbuf = NULL;\r\n\t}\r\n\tif (node_buffer != NULL) {\r\n\t\tdelete [] node_buffer;\r\n\t\tnode_buffer = NULL;\r\n\t}\r\n\tif (dist_buffer != NULL) {\r\n\t\tdelete [] dist_buffer;\r\n\t\tdist_buffer = NULL;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tMPI_Init(&argc, &argv);\r\n\r\n\tparallel_johnson(argc, argv);\r\n\r\n\tMPI_Finalize();\r\n}\r\n", "meta": {"hexsha": "c32e26120da768983fca91f259d9fc7c9c06b528", "size": 21714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ParallelJohnson.cpp", "max_stars_repo_name": "yzhucs/ParallelJohnson", "max_stars_repo_head_hexsha": "ce719f0fc6db49ab7b7adb16c5c4cfdfe7c3b022", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-12T10:33:19.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-12T10:33:19.000Z", "max_issues_repo_path": "ParallelJohnson.cpp", "max_issues_repo_name": "yzhucs/ParallelJohnson", "max_issues_repo_head_hexsha": "ce719f0fc6db49ab7b7adb16c5c4cfdfe7c3b022", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ParallelJohnson.cpp", "max_forks_repo_name": "yzhucs/ParallelJohnson", "max_forks_repo_head_hexsha": "ce719f0fc6db49ab7b7adb16c5c4cfdfe7c3b022", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-01-20T03:37:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T16:00:18.000Z", "avg_line_length": 31.699270073, "max_line_length": 81, "alphanum_fraction": 0.6230081975, "num_tokens": 6264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.06187598615612916, "lm_q1q2_score": 0.02336070206264609}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#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// Handbook of Statistical Distributions with Applications, K Krishnamoorthy, ISBN 1-58488-635-8, Chapter 23, pp 257 - 267.\n// Caution KK's a and b are the reverse of Mathworld!\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_scale(\n        const char* function,\n        RealType scale,\n        RealType* result, const Policy& pol)\n      {\n        if((boost::math::isfinite)(scale))\n        { // any > 0 finite value is OK.\n          if (scale > 0)\n          {\n            return true;\n          }\n          else\n          {\n            *result = policies::raise_domain_error<RealType>(\n              function,\n              \"Scale parameter is %1%, but must be > 0!\", scale, pol);\n            return false;\n          }\n        }\n        else\n        { // Not finite.\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"Scale parameter is %1%, but must be finite!\", scale, pol);\n          return false;\n        }\n      } // bool check_pareto_scale\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 scale,\n        RealType shape,\n        RealType* result, const Policy& pol)\n      {\n        return check_pareto_scale(function, scale, 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 l_scale = 1, RealType l_shape = 1)\n        : m_scale(l_scale), m_shape(l_shape)\n      { // Constructor.\n        RealType result = 0;\n        detail::check_pareto(\"boost::math::pareto_distribution<%1%>::pareto_distribution\", l_scale, l_shape, &result, Policy());\n      }\n\n      RealType scale()const\n      { // AKA Xm and Wolfram b and beta\n        return m_scale;\n      }\n\n      RealType shape()const\n      { // AKA k and Wolfram a and alpha\n        return m_shape;\n      }\n    private:\n      // Data members:\n      RealType m_scale;  // distribution scale (xm) or beta\n      RealType m_shape;  // distribution shape (k) or alpha\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>(static_cast<RealType>(0), max_value<RealType>()); // scale 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.scale(), max_value<RealType>() ); // scale 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 scale = dist.scale();\n      RealType shape = dist.shape();\n      RealType result = 0;\n      if(false == (detail::check_pareto_x(function, x, &result, Policy())\n         && detail::check_pareto(function, scale, shape, &result, Policy())))\n         return result;\n      if (x < scale)\n      { // regardless of shape, pdf is zero (or should be disallow x < scale and throw an exception?).\n        return 0;\n      }\n      result = shape * pow(scale, 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 scale = dist.scale();\n      RealType shape = dist.shape();\n      RealType result = 0;\n\n      if(false == (detail::check_pareto_x(function, x, &result, Policy())\n         && detail::check_pareto(function, scale, shape, &result, Policy())))\n         return result;\n\n      if (x <= scale)\n      { // regardless of shape, cdf is zero.\n        return 0;\n      }\n\n      // result = RealType(1) - pow((scale / x), shape);\n      result = -boost::math::powm1(scale/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 = 0;\n      RealType scale = dist.scale();\n      RealType shape = dist.shape();\n      if(false == (detail::check_probability(function, p, &result, Policy())\n           && detail::check_pareto(function, scale, shape, &result, Policy())))\n      {\n        return result;\n      }\n      if (p == 0)\n      {\n        return scale; // x must be scale (or less).\n      }\n      if (p == 1)\n      {\n        return tools::max_value<RealType>(); // x = + infinity.\n      }\n      result = scale /\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 = 0;\n       RealType x = c.param;\n       RealType scale = c.dist.scale();\n       RealType shape = c.dist.shape();\n       if(false == (detail::check_pareto_x(function, x, &result, Policy())\n           && detail::check_pareto(function, scale, shape, &result, Policy())))\n         return result;\n\n       if (x <= scale)\n       { // regardless of shape, cdf is zero, and complement is unity.\n         return 1;\n       }\n       result = pow((scale/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 = 0;\n      RealType q = c.param;\n      RealType scale = c.dist.scale();\n      RealType shape = c.dist.shape();\n      if(false == (detail::check_probability(function, q, &result, Policy())\n           && detail::check_pareto(function, scale, shape, &result, Policy())))\n      {\n        return result;\n      }\n      if (q == 1)\n      {\n        return scale; // x must be scale (or less).\n      }\n      if (q == 0)\n      {\n        return tools::max_value<RealType>(); // x = + infinity.\n      }\n      result = scale / (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 = 0;\n      static const char* function = \"boost::math::mean(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, dist.scale(), dist.shape(), &result, Policy()))\n      {\n        return result;\n      }\n      if (dist.shape() > RealType(1))\n      {\n        return dist.shape() * dist.scale() / (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.scale();\n    } // mode\n\n    template <class RealType, class Policy>\n    inline RealType median(const pareto_distribution<RealType, Policy>& dist)\n    {\n      RealType result = 0;\n      static const char* function = \"boost::math::median(const pareto_distribution<%1%>&, %1%)\";\n      if(false == detail::check_pareto(function, dist.scale(), dist.shape(), &result, Policy()))\n      {\n        return result;\n      }\n      BOOST_MATH_STD_USING\n      return dist.scale() * 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 = 0;\n      RealType scale = dist.scale();\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, scale, shape, &result, Policy()))\n      {\n        return result;\n      }\n      if (shape > 2)\n      {\n        result = (scale * scale * 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 = 0;\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.scale(), 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 = 0;\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.scale(), 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 = 0;\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.scale(), 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": "66d98a6eaab3917ab0c55135d4bd2c9500113d9b", "size": 15174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/distributions/pareto.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.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": "boost/math/distributions/pareto.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.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": "boost/math/distributions/pareto.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.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": 34.0988764045, "max_line_length": 128, "alphanum_fraction": 0.5925925926, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.048857777583473906, "lm_q1q2_score": 0.02328462259247868}}
{"text": "﻿#include <cstdio>\r\n#include <iostream>\r\n#include <algorithm>\r\n#include <string>\r\n#include <vector>\r\n#include <cmath>\r\n#include <stack>\r\n#include <set>\r\n#include <map>\r\n#include <boost/algorithm/string.hpp>\r\n#define Reg register\r\n#define gmax(_a, _b) ((_a) > (_b) ? (_a) : (_b))\r\n#define gmin(_a, _b) ((_a) < (_b) ? (_a) : (_b))\r\n#define cmax(_a, _b) (_a < (_b) ? _a = (_b) : 0)\r\n#define cmin(_a, _b) (_a > (_b) ? _a = (_b) : 0)\r\n#define FOR(_i,_a,_b) for (Reg int _i = (_a) ; _i <= (_b) ; _i++)\r\n#define REP(_i,_a,_b) for (Reg int _i = (_a) ; _i >= (_b) ; _i--)\r\n#define FOR_LETTER(_i) for (Reg int _i = 'A'; _i <= 'z'; _i != 'Z' ? (_i++) : (_i = 'a'))\r\n#define ll long long\r\nusing namespace std;\r\nconst int maxn = 1000;\r\nstring BeginSym;\r\nset <string> termin, non_termin;\r\nmap <string, set<string> > first, follow;\r\nset <string> created_first, created_follow;\r\nvector<string> boostsplit(const string & input);\r\nstruct Proce;\r\nvector<Proce> proce;\r\nmap <string, vector<Proce> > proce_index;\r\nmap <string, map<string, Proce> > Table;\r\nstack<string> Stack;\r\nstruct Proce\r\n{\r\n    string ori;\r\n    string left;\r\n    vector<string> right;\r\n    Proce() {};\r\n    Proce(const string & _p)\r\n    {\r\n        ori = _p;\r\n        vector<string> syms = boostsplit(_p);\r\n        left = syms[0];\r\n        int l = syms.size();\r\n        FOR(i, 2, l - 1)\r\n            right.push_back(syms[i]);\r\n        proce_index[left].push_back(*this);\r\n    }\r\n};\r\nvoid init()\r\n{\r\n    proce.push_back(Proce(\"E -> T E'\"));\r\n    proce.push_back(Proce(\"E' -> + T E'\"));\r\n    proce.push_back(Proce(\"E' -> - T E'\"));\r\n    proce.push_back(Proce(\"E' -> epsilon\"));\r\n    proce.push_back(Proce(\"T -> F T'\"));\r\n    proce.push_back(Proce(\"T' -> * F T'\"));\r\n    proce.push_back(Proce(\"T' -> / F T'\"));\r\n    proce.push_back(Proce(\"T' -> epsilon\"));\r\n    proce.push_back(Proce(\"F -> ( E )\"));\r\n    proce.push_back(Proce(\"F -> num\"));\r\n\r\n    termin.insert(\"num\");\r\n    termin.insert(\"+\");\r\n    termin.insert(\"-\");\r\n    termin.insert(\"*\");\r\n    termin.insert(\"/\");\r\n    termin.insert(\"(\");\r\n    termin.insert(\")\");\r\n    termin.insert(\"epsilon\");\r\n    termin.insert(\"$\");\r\n\r\n    non_termin.insert(\"E\");\r\n    non_termin.insert(\"E'\");\r\n    non_termin.insert(\"T\");\r\n    non_termin.insert(\"T'\");\r\n    non_termin.insert(\"F\");\r\n\r\n    BeginSym = \"E\";\r\n\r\n}\r\n\r\nvector<string> boostsplit(const std::string& input)\r\n{\r\n    std::vector <std::string> fields;\r\n    boost::split(fields, input, boost::is_any_of(\" \"));\r\n    return fields;\r\n}\r\n\r\nvoid CreateFirst(const string & sym)\r\n{\r\n    vector<Proce> & Pv = proce_index[sym];\r\n    \r\n    for (vector<Proce>::iterator it = Pv.begin(); it != Pv.end(); ++it)\r\n    {\r\n        Proce &P = (*it);\r\n        string left = P.left;\r\n        bool all_epsilon = true;\r\n        for (vector<string>::iterator j = P.right.begin(); j != P.right.end(); j++)\r\n        {\r\n            \r\n            if (termin.find(*j) != termin.end())\r\n            {\r\n                first[left].insert(*j);\r\n                break;\r\n            }\r\n\r\n            if (created_first.find(*j) == created_first.end())\r\n            {\r\n                CreateFirst(*j);\r\n            }\r\n\r\n            first[left].insert(first[*j].begin(), first[*j].end());\r\n\r\n            if (first[*j].find(\"epsilon\") == first[*j].end())\r\n            {\r\n                all_epsilon = false;\r\n                break;\r\n            }\r\n            else\r\n                first[left].erase(\"epsilon\");\r\n\r\n            if (all_epsilon)\r\n                first[left].insert(\"epsilon\");\r\n        }\r\n    }\r\n    created_first.insert(sym);\r\n}\r\n\r\nvoid CreateFollow()\r\n{\r\n    follow[BeginSym].insert(\"$\");\r\n    bool changed = true;\r\n    while (changed)\r\n    {\r\n        changed = false;\r\n        for (vector<Proce>::iterator it1 = proce.begin(); it1 != proce.end(); it1++)      //遍历所有产生式\r\n        {\r\n            Proce& P = *it1;\r\n            for (vector<string>::iterator it2 = P.right.begin(); it2 != P.right.end(); it2++)\r\n            {\r\n                string X = *it2;\r\n                int old_size = follow[X].size();\r\n                bool all_epsilon = true;\r\n                for (vector<string>::iterator it3 = it2 + 1; it3 != P.right.end() && all_epsilon; it3++)\r\n                {\r\n                    string b = *it3;\r\n                    bool show_epsilon = false;\r\n                    for (set<string>::iterator it4 = first[b].begin(); it4 != first[b].end(); it4++)\r\n                    {\r\n                        string a = *it4;\r\n                        if (a != \"epsilon\")\r\n                            follow[X].insert(a);\r\n                        else\r\n                            show_epsilon = true;\r\n                    }\r\n                    all_epsilon &= show_epsilon;\r\n                }\r\n                if (all_epsilon)\r\n                    for (set<string>::iterator it5 = follow[P.left].begin(); it5 != follow[P.left].end(); it5++)\r\n                        follow[X].insert(*it5);\r\n                if (follow[X].size() > old_size)\r\n                    changed = true;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid CreateTable()\r\n{\r\n    for (vector<Proce>::iterator it1 = proce.begin(); it1 != proce.end(); it1++)\r\n    {\r\n        Proce& P = *it1;\r\n        bool show_epsilon = false;\r\n        for (set<string>::iterator it2 = first[P.right[0]].begin(); it2 != first[P.right[0]].end(); it2++)\r\n        {\r\n            string a = *it2;\r\n            if (a != \"epsilon\")\r\n                Table[P.left][a] = P;\r\n            else\r\n                show_epsilon = true;\r\n        }\r\n        if (show_epsilon)\r\n            for (set<string>::iterator it3 = follow[P.left].begin(); it3 != follow[P.left].end(); it3++)\r\n            {\r\n                string b = *it3;\r\n                Table[P.left][b] = P;\r\n            }   \r\n    }\r\n}\r\n\r\nvoid error(string w, int pointer)\r\n{\r\n    cout << \"出现错误！错误出现在字符串'\" << w.substr(0, pointer) << \"'结尾处\" << endl;\r\n}\r\n\r\nvoid Prase(string w)\r\n{\r\n    w += \"$\";\r\n    int pointer = 0;\r\n    while (!Stack.empty())\r\n        Stack.pop();\r\n    Stack.push(\"$\");\r\n    Stack.push(BeginSym);\r\n    while (!Stack.empty())\r\n    {\r\n        string X = Stack.top();\r\n        string a = w.substr(pointer, 1);\r\n        if (w[pointer] >= '0' && w[pointer] <= '9')\r\n        {\r\n            a = \"num\";\r\n            while (w[pointer + 1] >= '0' && w[pointer + 1] <= '9') pointer++;\r\n        }\r\n        if (termin.find(X) != termin.end())\r\n        {\r\n            if (X == a)\r\n            {\r\n                Stack.pop();\r\n                pointer++;\r\n            }          \r\n            else\r\n            {\r\n                error(w, pointer);\r\n                return;\r\n            }\r\n                \r\n        }\r\n        else\r\n        {\r\n            if (Table.find(X) != Table.end() && Table[X].find(a) != Table[X].end())\r\n            {\r\n                Stack.pop();\r\n                Proce P = Table[X][a];\r\n                int length = P.right.size();\r\n                for (int i = length - 1; i >= 0; i--)\r\n                {\r\n                    string Y = P.right[i];\r\n                    if (Y != \"epsilon\")\r\n                        Stack.push(Y);\r\n                }\r\n                cout << P.ori << endl;\r\n            }\r\n            else\r\n            {\r\n                error(w, pointer);\r\n                return;\r\n            }        \r\n        }   \r\n    }\r\n    cout << \"分析完成！\" << endl;\r\n}\r\n\r\nint main()\r\n{\r\n    init();\r\n    cout << \"First:\" << endl;\r\n    for (set<string>::iterator it = non_termin.begin(); it != non_termin.end(); it++)\r\n    {\r\n        CreateFirst(*it);\r\n        cout << *it << \": \";\r\n        for (set<string>::iterator j = first[*it].begin(); j != first[*it].end(); j++)\r\n            cout << *j << \" \";\r\n        cout << endl;\r\n    }\r\n    for (set<string>::iterator it = termin.begin(); it != termin.end(); it++)\r\n    {\r\n        first[*it].insert(*it);\r\n    }\r\n\r\n    CreateFollow();\r\n    cout << \"Follow:\" << endl;\r\n    for (set<string>::iterator it = non_termin.begin(); it != non_termin.end(); it++)\r\n    {\r\n        cout << *it << \": \";\r\n        for (set<string>::iterator j = follow[*it].begin(); j != follow[*it].end(); j++)\r\n            cout << *j << \" \";\r\n        cout << endl;\r\n    }\r\n\r\n    CreateTable();\r\n\r\n    for (set<string>::iterator it1 = non_termin.begin(); it1 != non_termin.end(); it1++)\r\n    {\r\n        string A = *it1;\r\n        if (Table.find(A) != Table.end())\r\n        {\r\n            for (set<string>::iterator it2 = termin.begin(); it2 != termin.end(); it2++)\r\n            {\r\n                string a = *it2;\r\n                if (Table[A].find(a) != Table[A].end())\r\n                {\r\n                    cout << \"M[\" << A << \" , \" << a << \"] = \" << Table[A][a].ori << endl;\r\n                }\r\n            }\r\n        }\r\n        \r\n    }\r\n    string input_string;\r\n    while (1)\r\n    {\r\n        cin >> input_string;\r\n        Prase(input_string);\r\n    }\r\n    \r\n}", "meta": {"hexsha": "8b98649b4cab02ef6d6861571260083dcbdedc3a", "size": 8829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Principle_of_Compiler/语法分析/方法二-code/LL(1).cpp", "max_stars_repo_name": "TianYi2000/BUPT-Homework", "max_stars_repo_head_hexsha": "cd38d4561814424d004bcb5bad903e9df8668380", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Principle_of_Compiler/语法分析/方法二-code/LL(1).cpp", "max_issues_repo_name": "TianYi2000/BUPT-Homework", "max_issues_repo_head_hexsha": "cd38d4561814424d004bcb5bad903e9df8668380", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Principle_of_Compiler/语法分析/方法二-code/LL(1).cpp", "max_forks_repo_name": "TianYi2000/BUPT-Homework", "max_forks_repo_head_hexsha": "cd38d4561814424d004bcb5bad903e9df8668380", "max_forks_repo_licenses": ["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.0427631579, "max_line_length": 113, "alphanum_fraction": 0.4332313965, "num_tokens": 2227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.06656918943346386, "lm_q1q2_score": 0.023209023158039153}}
{"text": "// fp_traits.hpp\n\n#ifndef BOOST_SPIRIT_MATH_FP_TRAITS_HPP\n#define BOOST_SPIRIT_MATH_FP_TRAITS_HPP\n\n// Copyright (c) 2006 Johan Rade\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#if defined(__vms) && defined(__DECCXX) && !__IEEE_FLOAT\n#   error The VAX floating point mode on VMS is not supported.\n#endif\n\n#if defined(_MSC_VER)\n#pragma once\n#endif\n\n#include <cstring>\n\n#include <boost/assert.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/detail/endian.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n\n//------------------------------------------------------------------------------\n\nnamespace boost {\nnamespace spirit {\nnamespace math {\nnamespace detail {\n\n//------------------------------------------------------------------------------\n\n/*\nMost processors support three different floating point precisions:\nsingle precision (32 bits), double precision (64 bits)\nand extended double precision (>64 bits)\n\nNote that the C++ type long double can be implemented\nboth as double precision and extended double precision.\n*/\n\nstruct single_precision_tag {};\nstruct double_precision_tag {};\nstruct extended_double_precision_tag {};\n\n//------------------------------------------------------------------------------\n\n/*\ntemplate<class T, class U> struct fp_traits_impl;\n\n  This is traits class that describes the binary structure of floating\n  point numbers of C++ type T and precision U\n\nRequirements:\n\n  T = float, double or long double\n  U = single_precision_tag, double_precision_tag\n      or extended_double_precision_tag\n\nTypedef members:\n\n  bits -- the target type when copying the leading bytes of a floating\n      point number. It is a typedef for uint32_t or uint64_t.\n\n  coverage -- tells us whether all bytes are copied or not.\n      It is a typedef for all_bits or not_all_bits.\n\nStatic data members:\n\n  sign, exponent, flag, mantissa -- bit masks that give the meaning of the bits\n      in the leading bytes.\n\nStatic function members:\n\n  init() -- initializes the static data members, if needed.\n            (Is a no-op in the specialized versions of the template.)\n\n  get_bits(), set_bits() -- provide access to the leading bytes.\n*/\n\nstruct all_bits {};\nstruct not_all_bits {};\n\n// Generic version -------------------------------------------------------------\n\n// The generic version uses run time initialization to determine the floating\n// point format. It is capable of handling most formats,\n// but not the Motorola 68K extended double precision format.\n\n// Currently the generic version is used only for extended double precision\n// on Itanium. In all other cases there are specializations of the template\n// that use compile time initialization.\n\ntemplate<class T> struct uint32_t_coverage\n{\n    typedef not_all_bits type;\n};\n\ntemplate<> struct uint32_t_coverage<single_precision_tag>\n{\n    typedef all_bits type;\n};\n\ntemplate<class T, class U> struct fp_traits_impl\n{\n    typedef uint32_t bits;\n    typedef BOOST_DEDUCED_TYPENAME uint32_t_coverage<U>::type coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign = 0x80000000);\n    static uint32_t exponent;\n    static uint32_t flag;\n    static uint32_t mantissa;\n\n    static void init()\n    {\n        if(is_init_) return;\n        do_init_();\n        is_init_ = true;\n    }\n\n    static void get_bits(T x, uint32_t& a)\n    {\n        memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);\n    }\n\n    static void set_bits(T& x, uint32_t a)\n    {\n        memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);\n    }\n\nprivate:\n    static size_t offset_;\n    static bool is_init_;\n    static void do_init_();\n};\n\n//..............................................................................\n\ntemplate<class T, class U> uint32_t fp_traits_impl<T,U>::exponent;\ntemplate<class T, class U> uint32_t fp_traits_impl<T,U>::flag;\ntemplate<class T, class U> uint32_t fp_traits_impl<T,U>::mantissa;\ntemplate<class T, class U> size_t   fp_traits_impl<T,U>::offset_;\ntemplate<class T, class U> bool     fp_traits_impl<T,U>::is_init_;\n\n// In a single-threaded program, do_init will be called exactly once.\n// In a multi-threaded program, do_init may be called simultaneously\n// by more then one thread. That should not be a problem.\n\n//..............................................................................\n\ntemplate<class T, class U> void fp_traits_impl<T,U>::do_init_()\n{\n    T x = static_cast<T>(3) / static_cast<T>(4);\n    // sign bit = 0\n    // exponent: first and last bit = 0, all other bits  = 1\n    // flag bit (if present) = 1\n    // mantissa: first bit = 1, all other bits = 0\n\n    uint32_t a;\n\n    for(size_t k = 0; k <= sizeof(T) - 4; ++k) {\n\n        memcpy(&a, reinterpret_cast<unsigned char*>(&x) + k, 4);\n\n        switch(a) {\n\n        case 0x3f400000:      // IEEE single precision format\n\n            offset_  = k;\n            exponent = 0x7f800000;\n            flag     = 0x00000000;\n            mantissa = 0x007fffff;\n            return;\n\n        case 0x3fe80000:      // IEEE double precision format\n                              // and PowerPC extended double precision format\n            offset_  = k;\n            exponent = 0x7ff00000;\n            flag     = 0x00000000;\n            mantissa = 0x000fffff;\n            return;\n\n        case 0x3ffe0000:      // Motorola extended double precision format\n\n            // Must not get here. Must be handled by specialization.\n            // To get accurate cutoff between normals and subnormals\n            // we must use the flag bit that is in the 5th byte.\n            // Otherwise this cutoff will be off by a factor 2.\n            // If we do get here, then we have failed to detect the Motorola\n            // processor at compile time.\n\n            BOOST_ASSERT(false &&\n                \"Failed to detect the Motorola processor at compile time\");\n            return;\n\n        case 0x3ffe8000:      // IEEE extended double precision format\n                              // with 15 exponent bits\n            offset_  = k;\n            exponent = 0x7fff0000;\n            flag     = 0x00000000;\n            mantissa = 0x0000ffff;\n            return;\n\n        case 0x3ffec000:      // Intel extended double precision format\n\n            offset_  = k;\n            exponent = 0x7fff0000;\n            flag     = 0x00008000;\n            mantissa = 0x00007fff;\n            return;\n\n        default:\n            continue;\n        }\n    }\n\n    BOOST_ASSERT(false);\n\n    // Unknown format.\n}\n\n\n// float (32 bits) -------------------------------------------------------------\n\ntemplate<> struct fp_traits_impl<float, single_precision_tag>\n{\n    typedef uint32_t bits;\n    typedef all_bits coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign     = 0x80000000);\n    BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7f800000);\n    BOOST_STATIC_CONSTANT(uint32_t, flag     = 0x00000000);\n    BOOST_STATIC_CONSTANT(uint32_t, mantissa = 0x007fffff);\n\n    static void init() {}\n    static void get_bits(float x, uint32_t& a) { memcpy(&a, &x, 4); }\n    static void set_bits(float& x, uint32_t a) { memcpy(&x, &a, 4); }\n};\n\n\n// double (64 bits) ------------------------------------------------------------\n\n#if defined(BOOST_NO_INT64_T) || defined(BOOST_NO_INCLASS_MEMBER_INITIALIZATION)\n\ntemplate<> struct fp_traits_impl<double, double_precision_tag>\n{\n    typedef uint32_t bits;\n    typedef not_all_bits coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign     = 0x80000000);\n    BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7ff00000);\n    BOOST_STATIC_CONSTANT(uint32_t, flag     = 0);\n    BOOST_STATIC_CONSTANT(uint32_t, mantissa = 0x000fffff);\n\n    static void init() {}\n\n    static void get_bits(double x, uint32_t& a)\n    {\n        memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);\n    }\n\n    static void set_bits(double& x, uint32_t a)\n    {\n        memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);\n    }\n\nprivate:\n\n#if defined(BOOST_BIG_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 0);\n#elif defined(BOOST_LITTLE_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 4);\n#else\n    BOOST_STATIC_ASSERT(false);\n#endif\n};\n\n//..............................................................................\n\n#else\n\ntemplate<> struct fp_traits_impl<double, double_precision_tag>\n{\n    typedef uint64_t bits;\n    typedef all_bits coverage;\n\n    static const uint64_t sign     = (uint64_t)0x80000000 << 32;\n    static const uint64_t exponent = (uint64_t)0x7ff00000 << 32;\n    static const uint64_t flag     = 0;\n    static const uint64_t mantissa\n        = ((uint64_t)0x000fffff << 32) + (uint64_t)0xffffffff;\n\n    static void init() {}\n    static void get_bits(double x, uint64_t& a) { memcpy(&a, &x, 8); }\n    static void set_bits(double& x, uint64_t a) { memcpy(&x, &a, 8); }\n};\n\n#endif\n\n\n// long double (64 bits) -------------------------------------------------------\n\n#if defined(BOOST_NO_INT64_T) || defined(BOOST_NO_INCLASS_MEMBER_INITIALIZATION)\n\ntemplate<> struct fp_traits_impl<long double, double_precision_tag>\n{\n    typedef uint32_t bits;\n    typedef not_all_bits coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign     = 0x80000000);\n    BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7ff00000);\n    BOOST_STATIC_CONSTANT(uint32_t, flag     = 0);\n    BOOST_STATIC_CONSTANT(uint32_t, mantissa = 0x000fffff);\n\n    static void init() {}\n\n    static void get_bits(long double x, uint32_t& a)\n    {\n        memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);\n    }\n\n    static void set_bits(long double& x, uint32_t a)\n    {\n        memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);\n    }\n\nprivate:\n\n#if defined(BOOST_BIG_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 0);\n#elif defined(BOOST_LITTLE_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 4);\n#else\n    BOOST_STATIC_ASSERT(false);\n#endif\n};\n\n//..............................................................................\n\n#else\n\ntemplate<> struct fp_traits_impl<long double, double_precision_tag>\n{\n    typedef uint64_t bits;\n    typedef all_bits coverage;\n\n    static const uint64_t sign     = (uint64_t)0x80000000 << 32;\n    static const uint64_t exponent = (uint64_t)0x7ff00000 << 32;\n    static const uint64_t flag     = 0;\n    static const uint64_t mantissa\n        = ((uint64_t)0x000fffff << 32) + (uint64_t)0xffffffff;\n\n    static void init() {}\n    static void get_bits(long double x, uint64_t& a) { memcpy(&a, &x, 8); }\n    static void set_bits(long double& x, uint64_t a) { memcpy(&x, &a, 8); }\n};\n\n#endif\n\n\n// long double (>64 bits), x86 and x64 -----------------------------------------\n\n#if defined(__i386) || defined(__i386__) || defined(_M_IX86) \\\n    || defined(__amd64) || defined(__amd64__)  || defined(_M_AMD64) \\\n    || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)\n\n// Intel extended double precision format (80 bits)\n\ntemplate<> struct fp_traits_impl<long double, extended_double_precision_tag>\n{\n    typedef uint32_t bits;\n    typedef not_all_bits coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign     = 0x80000000);\n    BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7fff0000);\n    BOOST_STATIC_CONSTANT(uint32_t, flag     = 0x00008000);\n    BOOST_STATIC_CONSTANT(uint32_t, mantissa = 0x00007fff);\n\n    static void init() {}\n\n    static void get_bits(long double x, uint32_t& a)\n    {\n        memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + 6, 4);\n    }\n\n    static void set_bits(long double& x, uint32_t a)\n    {\n        memcpy(reinterpret_cast<unsigned char*>(&x) + 6, &a, 4);\n    }\n};\n\n\n// long double (>64 bits), Itanium ---------------------------------------------\n\n#elif defined(__ia64) || defined(__ia64__) || defined(_M_IA64)\n\n// The floating point format is unknown at compile time\n// No template specialization is provided.\n// The generic definition is used.\n\n// The Itanium supports both\n// the Intel extended double precision format (80 bits) and\n// the IEEE extended double precision format with 15 exponent bits (128 bits).\n\n\n// long double (>64 bits), PowerPC ---------------------------------------------\n\n#elif defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__) \\\n    || defined(__ppc) || defined(__ppc__) || defined(__PPC__)\n\n// PowerPC extended double precision format (128 bits)\n\ntemplate<> struct fp_traits_impl<long double, extended_double_precision_tag>\n{\n    typedef uint32_t bits;\n    typedef not_all_bits coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign     = 0x80000000);\n    BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7ff00000);\n    BOOST_STATIC_CONSTANT(uint32_t, flag     = 0x00000000);\n    BOOST_STATIC_CONSTANT(uint32_t, mantissa = 0x000fffff);\n\n    static void init() {}\n\n    static void get_bits(long double x, uint32_t& a)\n    {\n        memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);\n    }\n\n    static void set_bits(long double& x, uint32_t a)\n    {\n        memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);\n    }\n\nprivate:\n\n#if defined(BOOST_BIG_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 0);\n#elif defined(BOOST_LITTLE_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 12);\n#else\n    BOOST_STATIC_ASSERT(false);\n#endif\n};\n\n\n// long double (>64 bits), Motorola 68K ----------------------------------------\n\n#elif defined(__m68k) || defined(__m68k__) \\\n    || defined(__mc68000) || defined(__mc68000__) \\\n\n// Motorola extended double precision format (96 bits)\n\n// It is the same format as the Intel extended double precision format,\n// except that 1) it is big-endian, 2) the 3rd and 4th byte are padding, and\n// 3) the flag bit is not set for infinity\n\ntemplate<> struct fp_traits_impl<long double, extended_double_precision_tag>\n{\n    typedef uint32_t bits;\n    typedef not_all_bits coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign     = 0x80000000);\n    BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7fff0000);\n    BOOST_STATIC_CONSTANT(uint32_t, flag     = 0x00008000);\n    BOOST_STATIC_CONSTANT(uint32_t, mantissa = 0x00007fff);\n\n    static void init() {}\n\n    // copy 1st, 2nd, 5th and 6th byte. 3rd and 4th byte are padding.\n\n    static void get_bits(long double x, uint32_t& a)\n    {\n        memcpy(&a, &x, 2);\n        memcpy(reinterpret_cast<unsigned char*>(&a) + 2,\n               reinterpret_cast<const unsigned char*>(&x) + 4, 2);\n    }\n\n    static void set_bits(long double& x, uint32_t a)\n    {\n        memcpy(&x, &a, 2);\n        memcpy(reinterpret_cast<unsigned char*>(&x) + 4,\n               reinterpret_cast<const unsigned char*>(&a) + 2, 2);\n    }\n};\n\n\n// long double (>64 bits), All other processors --------------------------------\n\n#else\n\n// IEEE extended double precision format with 15 exponent bits (128 bits)\n\ntemplate<> struct fp_traits_impl<long double, extended_double_precision_tag>\n{\n    typedef uint32_t bits;\n    typedef not_all_bits coverage;\n\n    BOOST_STATIC_CONSTANT(uint32_t, sign     = 0x80000000);\n    BOOST_STATIC_CONSTANT(uint32_t, exponent = 0x7fff0000);\n    BOOST_STATIC_CONSTANT(uint32_t, flag     = 0x00000000);\n    BOOST_STATIC_CONSTANT(uint32_t, mantissa = 0x0000ffff);\n\n    static void init() {}\n\n    static void get_bits(long double x, uint32_t& a)\n    {\n        memcpy(&a, reinterpret_cast<const unsigned char*>(&x) + offset_, 4);\n    }\n\n    static void set_bits(long double& x, uint32_t a)\n    {\n        memcpy(reinterpret_cast<unsigned char*>(&x) + offset_, &a, 4);\n    }\n\nprivate:\n\n#if defined(BOOST_BIG_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 0);\n#elif defined(BOOST_LITTLE_ENDIAN)\n    BOOST_STATIC_CONSTANT(int, offset_ = 12);\n#else\n    BOOST_STATIC_ASSERT(false);\n#endif\n};\n\n#endif\n\n\n//------------------------------------------------------------------------------\n\n// size_to_precision is a type switch for converting a C++ floating point type\n// to the corresponding precision type.\n\ntemplate<int n> struct size_to_precision;\n\ntemplate<> struct size_to_precision<4>\n{\n    typedef single_precision_tag type;\n};\n\ntemplate<> struct size_to_precision<8>\n{\n    typedef double_precision_tag type;\n};\n\ntemplate<> struct size_to_precision<10>\n{\n    typedef extended_double_precision_tag type;\n};\n\ntemplate<> struct size_to_precision<12>\n{\n    typedef extended_double_precision_tag type;\n};\n\ntemplate<> struct size_to_precision<16>\n{\n    typedef extended_double_precision_tag type;\n};\n\n// fp_traits is a type switch that selects the right fp_traits_impl\n\ntemplate<class T> struct fp_traits\n{\n    BOOST_STATIC_ASSERT(boost::is_floating_point<T>::value);\n    typedef BOOST_DEDUCED_TYPENAME size_to_precision<sizeof(T)>::type precision;\n    typedef fp_traits_impl<T, precision> type;\n};\n\n\n//------------------------------------------------------------------------------\n\n}   // namespace detail\n}   // namespace math\n}   // namespace spirit\n}   // namespace boost\n\n#endif\n", "meta": {"hexsha": "ce1b765ddba8918c7ac5fe6d5b2c146b8ec1217e", "size": 16887, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/spirit/home/support/detail/math/detail/fp_traits.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/spirit/home/support/detail/math/detail/fp_traits.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/spirit/home/support/detail/math/detail/fp_traits.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": 28.9160958904, "max_line_length": 80, "alphanum_fraction": 0.6359921833, "num_tokens": 4047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.04742587082142043, "lm_q1q2_score": 0.023157265229544824}}
{"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/cholesky.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/utility/papi.hpp>\n\nusing namespace mtl;\nusing namespace mtl::recursion; \nusing namespace std;  \n\n\n\n// Maximum time for a single measurement\n// is 5 min\nconst double max_time= 300;\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;\n\nutility::papi_t papi;\nint l1i= papi.add_event(\"PAPI_L1_DCM\");\nint l2i= papi.add_event(\"PAPI_L2_DCM\");\nint tlbi= papi.add_event(\"PAPI_TLB_DM\");\n\n\n// ugly short cuts\ntypedef dense2D<double>                                       dr_t;\ntypedef dense2D<double, mat::parameters<col_major> >        dc_t;\n\n#ifdef MTL_HAS_LAPACK\nextern \"C\" {\n  void dpotrf_(char* uplo, int*, double*, int*, int*);\n}\n#endif\n\nstruct dpotrf_t\n{\n    void operator()(dc_t& a)\n    {\n#ifdef MTL_HAS_LAPACK\n\tint size= a.num_rows(), info;\n\tdpotrf_(\"U\", &size, &a[0][0], &size, &info);\n#endif\n    }\n};\n\n\n\nvoid print_time_and_mflops(double time, double size)\n{\n    // time and MFlops of single measure\n    std::cout << time << \", \" << 0.333333333333333333 * size * size * size / time / 1e6f << \", \";\n}\n\n\n// Matrices are only placeholder to provide the type\ntemplate <typename Visitor, typename Matrix>\nvoid single_measure(Matrix&, Visitor visitor, unsigned size, std::vector<int>& enabled, int i)\n{\n    Matrix matrix(size, size);\n    fill_matrix_for_cholesky(matrix);\n\n    if (enabled[i]) {\n\tint reps= 0;\n\tboost::timer start;\t\n\tpapi.reset();\n\tfor (; start.elapsed() < 5; reps++)\n\t    recursive_cholesky(matrix, visitor);\n\tpapi.read();\n\tdouble time= start.elapsed() / double(reps);\n\tprint_time_and_mflops(time, size);\n\tstd::cout << papi[l1i]/reps << \", \" << papi[l2i]/reps << \", \" << papi[tlbi]/reps << \", \";\n\tif (time > max_time)\n\t    enabled[i]= 0;\n    } else\n\tstd::cout << \", , , , , \";\n}\n\n\n// Matrices are only placeholder to provide the type\ntemplate <typename Matrix, typename Functor>\nvoid single_measure_dpotrf(Matrix&, Functor fcholesky, unsigned size, std::vector<int>& enabled, int i)\n{\n    Matrix matrix(size, size);\n    fill_matrix_for_cholesky(matrix);\n\n    if (enabled[i]) {\n\tint reps= 0;\n\tboost::timer start;\t\n\tpapi.reset();\n\tfor (; start.elapsed() < 5; reps++)\n\t    fcholesky(matrix);\n\tpapi.read();\n\tdouble time= start.elapsed() / double(reps);\n\tprint_time_and_mflops(time, size);\n\tstd::cout << papi[l1i]/reps << \", \" << papi[l2i]/reps << \", \" << papi[tlbi]/reps << \", \";\n\tif (time > max_time)\n\t    enabled[i]= 0;\n    } else\n\tstd::cout << \", , , , , \";\n}\n\n\ntemplate <typename Visitor>\nvoid measure(unsigned size, std::vector<int>& enabled)\n{\n    \n    // The matrices in the following functions are only place holders, the real matrices are used in single_measure\n    morton_dense<double,  morton_mask>             md(4, 4);\n    morton_dense<double,  morton_z_mask>           mzd(4, 4);\n    dense2D<double>                                dr(4, 4);\n    dense2D<double, mat::parameters<col_major> > dc(4, 4);\n    morton_dense<double,  doppled_32_row_mask>     d32r(4, 4);\n    morton_dense<double,  doppled_64_row_mask>     d64r(4, 4);\n\n    std::cout << size << \", \";\n\n    Visitor visitor;\n    single_measure(md, visitor, size, enabled, 0);\n    single_measure(mzd, visitor, size, enabled, 1);\n    single_measure(dr, visitor, size, enabled, 2);\n    single_measure(dc, visitor, size, enabled, 3);\n    single_measure(d32r, visitor, size, enabled, 4);\n    single_measure(d64r, visitor, size, enabled, 5);\n\n    single_measure_dpotrf(dc, dpotrf_t(), size, enabled, 6);\n    \n    std::cout << \"0\\n\"; // to not finish with comma\n    std::cout.flush();\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\"; \n    std::cout << \"# N-order, Z-order, row, col, 32 row, 64 row\\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\nint main(int argc, char* argv[])\n{\n    papi.start();\n\n    std::vector<std::string> scenarii;\n    scenarii.push_back(string(\"Comparing canonical implementation with different matrix types\"));\n    scenarii.push_back(string(\"Comparing iterator implementation with different matrix types\"));\n    scenarii.push_back(string(\"Comparing prev. using fast Schur update (2x2 tiling) with different matrix types\"));\n    scenarii.push_back(string(\"Comparing prev. using fast Schur update (4x4 tiling) with different matrix types\"));\n\n    using std::cout;\n    if (argc < 4) {\n\tcerr << \"usage: recursive_mult_timing <scenario> <steps> <max_size>\\nScenarii:\\n\"; \n\tfor (unsigned i= 0; i < scenarii.size(); i++)\n\t    cout << i << \": \" << scenarii[i] << \"\\n\";\n\texit(1);\n    }\n    unsigned int scenario= atoi(argv[1]), steps= atoi(argv[2]), max_size= atoi(argv[3]), size= 32; \n\n    typedef with_bracket::recursive_cholesky_base_visitor_t     bracket_t;\n    typedef with_iterator::recursive_cholesky_base_visitor_t    iterator_t;\n\n    typedef detail::mult_schur_update_t<gen_tiling_22_dense_mat_mat_mult_t<assign::minus_sum> > schur_update_22_t;\n    typedef recursive_cholesky_visitor_t<recursion::bound_test_static<64>, with_iterator::cholesky_base_t, with_iterator::tri_solve_base_t, \n\t                                 with_iterator::tri_schur_base_t, schur_update_22_t>   \n\ttiling_22_t;\n\n    typedef detail::mult_schur_update_t<gen_tiling_44_dense_mat_mat_mult_t<assign::minus_sum> > schur_update_44_t;\n    typedef recursive_cholesky_visitor_t<recursion::bound_test_static<64>, with_iterator::cholesky_base_t, with_iterator::tri_solve_base_t, \n\t                                 with_iterator::tri_schur_base_t, schur_update_44_t>   \n\ttiling_44_t;\n\n\n    switch (scenario) {\n      case 0: \tseries(steps, max_size, measure<bracket_t>, scenarii[0]); break;\n      case 1: \tseries(steps, max_size, measure<iterator_t>, scenarii[1]); break;\n      case 2: \tseries(steps, max_size, measure<tiling_22_t>, scenarii[2]); break;\n      case 3: \tseries(steps, max_size, measure<tiling_44_t>, scenarii[3]); break;\n    }\n\n    return 0; \n\n}\n \n\n\n// Compile command:\n// g++4 cholesky_timing.cpp -o cholesky_timing -O3 -DNDEBUG -ffast-math  -mcpu=opteron -mtune=opteron -msse2 -mfpmath=sse  -I${MTL_BOOST_ROOT} -I${BOOST_ROOT} -I/usr/local/include -L/usr/local/lib -lpapi -DMTL_HAS_PAPI -DMTL_HAS_BLAS -DMTL_HAS_LAPACK -L/u/htor/projekte/mathlibs/acml-2-6-0-gnu-64bit/gnu64/lib -lacml -L/usr/lib/gcc/x86_64-redhat-linux/3.4.3 -lg2c\n", "meta": {"hexsha": "0da7c4f3c97195363b116d0eeda2315ddf0ce3a8", "size": 9338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/cholesky_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/cholesky_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/cholesky_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": 37.8056680162, "max_line_length": 363, "alphanum_fraction": 0.6980081388, "num_tokens": 2783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.04813676736142426, "lm_q1q2_score": 0.023128690347316766}}
{"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// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, University of Notre Dame, Notre\r\n// Dame, IN 46556.\r\n//\r\n// Permission to modify the code and to distribute modified code is\r\n// granted, provided the text of this NOTICE is retained, a notice that\r\n// the code was modified is included with the above COPYRIGHT NOTICE and\r\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\r\n// file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#ifndef BOOST_SELF_AVOIDING_WALK_HPP\r\n#define BOOST_SELF_AVOIDING_WALK_HPP\r\n\r\n/*\r\n  This file defines necessary components for SAW. \r\n\r\n  mesh language: (defined by myself to clearify what is what)\r\n  A triangle in mesh is called an triangle.\r\n  An edge in mesh is called an line. \r\n  A vertex in mesh is called a point.\r\n\r\n  A triangular mesh corresponds to a graph in which a vertex is a\r\n  triangle and an edge(u, v) stands for triangle u and triangle v \r\n  share an line.\r\n\r\n  After this point, a vertex always refers to vertex in graph,\r\n  therefore it is a traingle in mesh. \r\n\r\n */\r\n\r\n#include <utility>\r\n#include <boost/config.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/property_map.hpp>\r\n\r\n#define SAW_SENTINAL -1\r\n\r\nnamespace boost {\r\n\r\n  template <class T1, class T2, class T3>\r\n  struct triple {\r\n    T1 first;\r\n    T2 second;\r\n    T3 third;\r\n    triple(const T1& a, const T2& b, const T3& c) : first(a), second(b), third(c) {}\r\n    triple() : first(SAW_SENTINAL), second(SAW_SENTINAL), third(SAW_SENTINAL) {}\r\n  };\r\n \r\n  typedef triple<int, int, int> Triple;\r\n\r\n  /* Define a vertex property which has a triangle inside. Triangle is\r\n    represented by a triple.  */\r\n  struct triangle_tag { enum { num = 100 }; };\r\n  typedef property<triangle_tag,Triple> triangle_property;\r\n\r\n  /* Define an edge property with a line. A line is represented by a\r\n    pair.  This is not required for SAW though.\r\n  */\r\n  struct line_tag { enum { num = 101 }; };\r\n  template <class T> struct line_property\r\n    : public property<line_tag, std::pair<T,T> > { };\r\n\r\n  /*Precondition: Points in a Triangle are in order */\r\n  template <class Triangle, class Line>\r\n  inline void get_sharing(const Triangle& a, const Triangle& b, Line& l)\r\n  {\r\n    l.first = SAW_SENTINAL;\r\n    l.second = SAW_SENTINAL;\r\n\r\n    if ( a.first == b.first ) {\r\n      l.first = a.first;\r\n      if ( a.second == b.second || a.second == b.third )\r\n        l.second = a.second;\r\n      else if ( a.third == b.second || a.third == b.third )\r\n        l.second = a.third; \r\n\r\n    }  else if ( a.first == b.second ) {\r\n      l.first = a.first;\r\n      if ( a.second == b.third )\r\n        l.second = a.second;\r\n      else if ( a.third == b.third )\r\n        l.second = a.third; \r\n\r\n    } else if ( a.first == b.third ) {\r\n      l.first = a.first;\r\n\r\n\r\n    } else if ( a.second == b.first ) {\r\n      l.first = a.second;\r\n      if ( a.third == b.second || a.third == b.third )\r\n        l.second = a.third;\r\n\r\n    } else if ( a.second == b.second ) {\r\n      l.first = a.second;\r\n      if ( a.third == b.third ) \r\n        l.second = a.third;\r\n\r\n    } else if ( a.second == b.third ) {\r\n      l.first = a.second;\r\n\r\n\r\n    } else if ( a.third == b.first \r\n                || a.third == b.second  \r\n                || a.third == b.third )\r\n      l.first = a.third; \r\n\r\n    /*Make it in order*/\r\n    if ( l.first > l.second ) {\r\n      typename Line::first_type i = l.first;\r\n      l.first = l.second;\r\n      l.second = i;\r\n    }\r\n\r\n  }\r\n\r\n  template <class TriangleDecorator, class Vertex, class Line>\r\n  struct get_vertex_sharing {\r\n    typedef std::pair<Vertex, Line> Pair;\r\n    get_vertex_sharing(const TriangleDecorator& _td) : td(_td) {}\r\n    inline Line operator()(const Vertex& u, const Vertex& v) const {\r\n      Line l;\r\n      get_sharing(td[u], td[v], l);\r\n      return l;\r\n    }\r\n    inline Line operator()(const Pair& u, const Vertex& v) const {\r\n      Line l;\r\n      get_sharing(td[u.first], td[v], l);\r\n      return l;\r\n    }\r\n    inline Line operator()(const Pair& u, const Pair& v) const {\r\n      Line l;\r\n      get_sharing(td[u.first], td[v.first], l);\r\n      return l;\r\n    }\r\n    TriangleDecorator td;\r\n  };\r\n  \r\n  /* HList has to be a handle of data holder so that pass-by-value is\r\n   * in right logic.\r\n   *\r\n   * The element of HList is a pair of vertex and line. (remember a\r\n   * line is a pair of two ints.). That indicates the walk w from\r\n   * current vertex is across line. (If the first of line is -1, it is\r\n   * a point though.\r\n   */\r\n  template < class TriangleDecorator, class HList, class IteratorD>\r\n  class SAW_visitor\r\n    : public bfs_visitor<>, public dfs_visitor<>\r\n  {\r\n    typedef typename boost::property_traits<IteratorD>::value_type iter;\r\n    /*use boost shared_ptr*/\r\n    typedef typename HList::element_type::value_type::second_type     Line;\r\n  public:\r\n\r\n    typedef tree_edge_tag category;\r\n\r\n    inline SAW_visitor(TriangleDecorator _td, HList _hlist, IteratorD ia)\r\n      : td(_td), hlist(_hlist), iter_d(ia) {}\r\n\r\n    template <class Vertex, class Graph>\r\n    inline void start_vertex(Vertex v, Graph&) {\r\n      Line l1;\r\n      l1.first = SAW_SENTINAL;\r\n      l1.second = SAW_SENTINAL;\r\n      hlist->push_front(std::make_pair(v, l1));\r\n      iter_d[v] = hlist->begin();\r\n    }\r\n\r\n    /*Several symbols:\r\n      w(i): i-th triangle in walk w\r\n      w(i) |- w(i+1): w enter w(i+1) from w(i) over a line\r\n      w(i) ~> w(i+1): w enter w(i+1) from w(i) over a point\r\n      w(i) -> w(i+1): w enter w(i+1) from w(i)\r\n      w(i) ^ w(i+1): the line or point w go over from w(i) to w(i+1)\r\n    */\r\n    template <class Edge, class Graph>\r\n    bool tree_edge(Edge e, Graph& G) {\r\n          using std::make_pair;\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\r\n      Vertex tau = target(e, G);\r\n      Vertex i   = source(e, G); \r\n\r\n      get_vertex_sharing<TriangleDecorator, Vertex, Line> get_sharing_line(td);\r\n      \r\n      Line tau_i = get_sharing_line(tau, i);\r\n      \r\n      iter w_end = hlist->end();\r\n\r\n      iter w_i = iter_d[i];\r\n\r\n      iter w_i_m_1 = w_i;\r\n      iter w_i_p_1 = w_i;\r\n\r\n      /*----------------------------------------------------------\r\n       *             true             false\r\n       *==========================================================\r\n       *a       w(i-1) |- w(i)    w(i-1) ~> w(i) or w(i-1) is null\r\n       *----------------------------------------------------------\r\n       *b       w(i) |- w(i+1)    w(i) ~> w(i+1) or no w(i+1) yet\r\n       *----------------------------------------------------------\r\n       */\r\n      \r\n      bool a = false, b = false;\r\n\r\n      --w_i_m_1;\r\n      ++w_i_p_1;\r\n      b = ( w_i->second.first != SAW_SENTINAL );\r\n\r\n      if ( w_i_m_1 != w_end ) {\r\n        a = ( w_i_m_1->second.first != SAW_SENTINAL );\r\n      }      \r\n      \r\n      if ( a ) {\r\n        \r\n        if ( b ) {\r\n          /*Case 1: \r\n            \r\n            w(i-1) |- w(i) |- w(i+1)\r\n          */\r\n          Line l1 = get_sharing_line(*w_i_m_1, tau);\r\n\r\n          iter w_i_m_2 = w_i_m_1;\r\n          --w_i_m_2;\r\n\r\n          bool c = true;\r\n          \r\n          if ( w_i_m_2 != w_end ) {\r\n            c = w_i_m_2->second != l1;\r\n          }\r\n\r\n          if ( c ) {  /* w(i-1) ^ tau != w(i-2) ^ w(i-1)  */\r\n            /*extension: w(i-1) -> tau |- w(i) */\r\n            w_i_m_1->second = l1;\r\n            /*insert(pos, const T&) is to insert before pos*/\r\n            iter_d[tau] = hlist->insert(w_i, make_pair(tau, tau_i));  \r\n            \r\n          } else {  /* w(i-1) ^ tau == w(i-2) ^ w(i-1)  */\r\n            /*must be w(i-2) ~> w(i-1) */\r\n            \r\n            bool d = true;\r\n            //need to handle the case when w_i_p_1 is null\r\n            Line l3 = get_sharing_line(*w_i_p_1, tau);\r\n            if ( w_i_p_1 != w_end )\r\n              d = w_i_p_1->second != l3;\r\n            if ( d ) { /* w(i+1) ^ tau != w(i+1) ^ w(i+2) */\r\n              /*extension: w(i) |- tau -> w(i+1) */\r\n              w_i->second = tau_i;\r\n              iter_d[tau] = hlist->insert(w_i_p_1, make_pair(tau, l3));\r\n            } else { /* w(i+1) ^ tau == w(i+1) ^ w(i+2) */\r\n              /*must be w(1+1) ~> w(i+2) */\r\n              Line l5 = get_sharing_line(*w_i_m_1, *w_i_p_1);\r\n              if ( l5 != w_i_p_1->second ) { /* w(i-1) ^ w(i+1) != w(i+1) ^ w(i+2) */\r\n                /*extension: w(i-2) -> tau |- w(i) |- w(i-1) -> w(i+1) */\r\n                w_i_m_2->second = get_sharing_line(*w_i_m_2, tau);\r\n                iter_d[tau] = hlist->insert(w_i, make_pair(tau, tau_i));\r\n                w_i->second = w_i_m_1->second;\r\n                w_i_m_1->second = l5;\r\n                iter_d[w_i_m_1->first] = hlist->insert(w_i_p_1, *w_i_m_1);\r\n                hlist->erase(w_i_m_1);\r\n              } else {\r\n                /*mesh is tetrahedral*/\r\n                // dont know what that means.\r\n                ;\r\n              }\r\n            }\r\n            \r\n          }\r\n        } else { \r\n          /*Case 2:\r\n            \r\n            w(i-1) |- w(i) ~> w(1+1)\r\n          */\r\n          \r\n          if ( w_i->second.second == tau_i.first \r\n               || w_i->second.second == tau_i.second ) {  /*w(i) ^ w(i+1) < w(i) ^ tau*/\r\n            /*extension: w(i) |- tau -> w(i+1) */\r\n            w_i->second = tau_i;\r\n            Line l1 = get_sharing_line(*w_i_p_1, tau);\r\n            iter_d[tau] = hlist->insert(w_i_p_1, make_pair(tau, l1));\r\n          } else { /*w(i) ^ w(i+1) !< w(i) ^ tau*/\r\n            Line l1 = get_sharing_line(*w_i_m_1, tau);\r\n            bool c = true;\r\n            iter w_i_m_2 = w_i_m_1;\r\n            --w_i_m_2;\r\n            if ( w_i_m_2 != w_end )\r\n              c =  l1 != w_i_m_2->second;\r\n            if (c) { /*w(i-1) ^ tau != w(i-2) ^ w(i-1)*/\r\n              /*extension: w(i-1) -> tau |- w(i)*/\r\n              w_i_m_1->second = l1;\r\n              iter_d[tau] = hlist->insert(w_i, make_pair(tau, tau_i));\r\n            } else { /*w(i-1) ^ tau == w(i-2) ^ w(i-1)*/\r\n              /*must be w(i-2)~>w(i-1)*/\r\n              /*extension: w(i-2) -> tau |- w(i) |- w(i-1) -> w(i+1)*/\r\n              w_i_m_2->second = get_sharing_line(*w_i_m_2, tau);\r\n              iter_d[tau] = hlist->insert(w_i, make_pair(tau, tau_i));\r\n              w_i->second = w_i_m_1->second;\r\n              w_i_m_1->second = get_sharing_line(*w_i_m_1, *w_i_p_1);\r\n              iter_d[w_i_m_1->first] = hlist->insert(w_i_p_1, *w_i_m_1);\r\n              hlist->erase(w_i_m_1);\r\n            }\r\n            \r\n          }    \r\n          \r\n        }\r\n        \r\n      } else {\r\n        \r\n        if ( b ) {\r\n          /*Case 3:\r\n            \r\n            w(i-1) ~> w(i) |- w(i+1)\r\n          */\r\n          bool c = false;\r\n          if ( w_i_m_1 != w_end )\r\n            c = ( w_i_m_1->second.second == tau_i.first)\r\n              || ( w_i_m_1->second.second == tau_i.second);\r\n          \r\n          if ( c ) {  /*w(i-1) ^ w(i) < w(i) ^ tau*/\r\n            /* extension: w(i-1) -> tau |- w(i) */\r\n            if ( w_i_m_1 != w_end )\r\n              w_i_m_1->second = get_sharing_line(*w_i_m_1, tau);\r\n            iter_d[tau] = hlist->insert(w_i, make_pair(tau, tau_i));\r\n          } else {\r\n            bool d = true;\r\n            Line l1;\r\n            l1.first = SAW_SENTINAL;\r\n            l1.second = SAW_SENTINAL;\r\n            if ( w_i_p_1 != w_end ) {\r\n              l1 = get_sharing_line(*w_i_p_1, tau);\r\n              d = l1 != w_i_p_1->second;\r\n            }\r\n            if (d) { /*w(i+1) ^ tau != w(i+1) ^ w(i+2)*/\r\n              /*extension: w(i) |- tau -> w(i+1) */\r\n              w_i->second = tau_i;\r\n              iter_d[tau] = hlist->insert(w_i_p_1, make_pair(tau, l1));\r\n            } else {\r\n              /*must be w(i+1) ~> w(i+2)*/\r\n              /*extension: w(i-1) -> w(i+1) |- w(i) |- tau -> w(i+2) */\r\n              iter w_i_p_2 = w_i_p_1;\r\n              ++w_i_p_2;\r\n              \r\n              w_i_p_1->second = w_i->second;\r\n              iter_d[i] = hlist->insert(w_i_p_2, make_pair(i, tau_i));\r\n              hlist->erase(w_i);\r\n              Line l2 = get_sharing_line(*w_i_p_2, tau);\r\n              iter_d[tau] = hlist->insert(w_i_p_2, make_pair(tau, l2));\r\n            }\r\n          }\r\n          \r\n        } else {\r\n          /*Case 4:\r\n            \r\n            w(i-1) ~> w(i) ~> w(i+1)\r\n            \r\n          */\r\n          bool c = false;\r\n          if ( w_i_m_1 != w_end ) {\r\n            c = (w_i_m_1->second.second == tau_i.first) \r\n              || (w_i_m_1->second.second == tau_i.second);\r\n          }\r\n          if ( c ) {   /*w(i-1) ^ w(i) < w(i) ^ tau */\r\n            /*extension: w(i-1) -> tau |- w(i) */\r\n            if ( w_i_m_1 != w_end )\r\n              w_i_m_1->second = get_sharing_line(*w_i_m_1, tau);\r\n            iter_d[tau] = hlist->insert(w_i, make_pair(tau, tau_i));\r\n          } else { \r\n            /*extension: w(i) |- tau -> w(i+1) */\r\n            w_i->second = tau_i;\r\n            Line l1;\r\n            l1.first = SAW_SENTINAL;\r\n            l1.second = SAW_SENTINAL;\r\n            if ( w_i_p_1 != w_end ) \r\n              l1 = get_sharing_line(*w_i_p_1, tau);\r\n            iter_d[tau] = hlist->insert(w_i_p_1, make_pair(tau, l1));\r\n          }\r\n        }\r\n        \r\n      }\r\n\r\n      return true;\r\n    }\r\n    \r\n  protected:\r\n    TriangleDecorator td; /*a decorator for vertex*/\r\n    HList             hlist;\r\n    /*This must be a handle of list to record the SAW\r\n      The element type of the list is pair<Vertex, Line>\r\n     */\r\n   \r\n    IteratorD         iter_d; \r\n    /*Problem statement: Need a fast access to w for triangle i.\r\n     *Possible solution: mantain an array to record. \r\n     iter_d[i] will return an iterator \r\n     which points to w(i), where i is a vertex\r\n     representing triangle i.\r\n    */\r\n  };\r\n\r\n  template <class Triangle, class HList, class Iterator>\r\n  inline \r\n  SAW_visitor<Triangle, HList, Iterator>\r\n  visit_SAW(Triangle t, HList hl, Iterator i) {\r\n    return SAW_visitor<Triangle, HList, Iterator>(t, hl, i);\r\n  }\r\n\r\n  template <class Tri, class HList, class Iter>\r\n  inline \r\n  SAW_visitor< random_access_iterator_property_map<Tri*,Tri,Tri&>,\r\n    HList, random_access_iterator_property_map<Iter*,Iter,Iter&> >\r\n  visit_SAW_ptr(Tri* t, HList hl, Iter* i) {\r\n    typedef random_access_iterator_property_map<Tri*,Tri,Tri&> TriD;\r\n    typedef random_access_iterator_property_map<Iter*,Iter,Iter&> IterD;\r\n    return SAW_visitor<TriD, HList, IterD>(t, hl, i);\r\n  }\r\n\r\n  // should also have combo's of pointers, and also const :(\r\n  \r\n}\r\n\r\n#endif /*BOOST_SAW_H*/\r\n", "meta": {"hexsha": "6aba718b535643208b22dcf4a7fac3f78219f252", "size": 15311, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/boost/graph/detail/self_avoiding_walk.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/boost/graph/detail/self_avoiding_walk.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "sdk/boost_1_30_0/boost/graph/detail/self_avoiding_walk.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 35.1977011494, "max_line_length": 89, "alphanum_fraction": 0.5018614068, "num_tokens": 4292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.05834583651821275, "lm_q1q2_score": 0.023108928479493536}}
{"text": "/**  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n#ifndef GRAPHLAB_DISTRIBUTED_INGRESS_EDGE_DECISION_HPP\n#define GRAPHLAB_DISTRIBUTED_INGRESS_EDGE_DECISION_HPP\n\n#include <graphlab/graph/distributed_graph.hpp>\n#include <graphlab/graph/graph_basic_types.hpp>\n#include <graphlab/graph/graph_hash.hpp>\n#include <graphlab/rpc/distributed_event_log.hpp>\n#include <graphlab/util/dense_bitset.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\nnamespace graphlab {\n  template<typename VertexData, typename EdgeData>\n  class distributed_graph;\n \n template<typename VertexData, typename EdgeData>\n class ingress_edge_decision {\n\n    public:\n      typedef graphlab::vertex_id_type vertex_id_type;\n      typedef distributed_graph<VertexData, EdgeData> graph_type;\n      typedef fixed_dense_bitset<RPC_MAX_N_PROCS> bin_counts_type; \n\n    public:\n      /** \\brief A decision object for computing the edge assingment. */\n      ingress_edge_decision(distributed_control& dc) { }\n\n      /** Random assign (source, target) to a machine p in {0, ... numprocs-1} */\n      procid_t edge_to_proc_random (const vertex_id_type source, \n          const vertex_id_type target,\n          size_t numprocs) {\n        typedef std::pair<vertex_id_type, vertex_id_type> edge_pair_type;\n        const edge_pair_type edge_pair(std::min(source, target), \n            std::max(source, target));\n        return graph_hash::hash_edge(edge_pair) % (numprocs);\n      };\n\n      /** Random assign (source, target) to a machine p in a list of candidates */\n      procid_t edge_to_proc_random (const vertex_id_type source, \n          const vertex_id_type target,\n          const std::vector<procid_t> & candidates) {\n        typedef std::pair<vertex_id_type, vertex_id_type> edge_pair_type;\n        const edge_pair_type edge_pair(std::min(source, target), \n            std::max(source, target));\n\n        return candidates[graph_hash::hash_edge(edge_pair) % (candidates.size())];\n      };\n\n\n      /** Greedy assign (source, target) to a machine using: \n       *  bitset<MAX_MACHINE> src_degree : the degree presence of source over machines\n       *  bitset<MAX_MACHINE> dst_degree : the degree presence of target over machines\n       *  vector<size_t>      proc_num_edges : the edge counts over machines\n       * */\n      procid_t edge_to_proc_greedy (const vertex_id_type source, \n          const vertex_id_type target,\n          bin_counts_type& src_degree,\n          bin_counts_type& dst_degree,\n          std::vector<size_t>& proc_num_edges,\n          bool usehash = false,\n          bool userecent = false) {\n        size_t numprocs = proc_num_edges.size();\n\n        // Compute the score of each proc.\n        procid_t best_proc = -1; \n        double maxscore = 0.0;\n        double epsilon = 1.0; \n        std::vector<double> proc_score(numprocs); \n        size_t minedges = *std::min_element(proc_num_edges.begin(), proc_num_edges.end());\n        size_t maxedges = *std::max_element(proc_num_edges.begin(), proc_num_edges.end());\n\n        for (size_t i = 0; i < numprocs; ++i) {\n          size_t sd = src_degree.get(i) + (usehash && (source % numprocs == i));\n          size_t td = dst_degree.get(i) + (usehash && (target % numprocs == i));\n          double bal = (maxedges - proc_num_edges[i])/(epsilon + maxedges - minedges);\n          proc_score[i] = bal + ((sd > 0) + (td > 0));\n        }\n        maxscore = *std::max_element(proc_score.begin(), proc_score.end());\n\n        std::vector<procid_t> top_procs; \n        for (size_t i = 0; i < numprocs; ++i)\n          if (std::fabs(proc_score[i] - maxscore) < 1e-5)\n            top_procs.push_back(i);\n\n        // Hash the edge to one of the best procs.\n        typedef std::pair<vertex_id_type, vertex_id_type> edge_pair_type;\n        const edge_pair_type edge_pair(std::min(source, target), \n            std::max(source, target));\n        best_proc = top_procs[graph_hash::hash_edge(edge_pair) % top_procs.size()];\n\n        ASSERT_LT(best_proc, numprocs);\n        if (userecent) {\n          src_degree.clear();\n          dst_degree.clear();\n        }\n        src_degree.set_bit(best_proc);\n        dst_degree.set_bit(best_proc);\n        ++proc_num_edges[best_proc];\n        return best_proc;\n      };\n\n      procid_t edge_to_proc_rdma (const vertex_id_type source, \n          const vertex_id_type target,\n          bin_counts_type& src_degree,\n          bin_counts_type& dst_degree,\n          std::vector<size_t>& proc_num_edges,\n          size_t start_proc,\n          size_t end_proc,\n          bool usehash = false,\n          bool userecent = false) {\n        size_t numprocs = proc_num_edges.size();\n\n        // Compute the score of each proc.\n        procid_t best_proc = -1; \n        double maxscore = 0.0;\n        double epsilon = 1.0; \n        std::vector<double> proc_score(numprocs); \n        size_t minedges = *std::min_element(proc_num_edges.begin()+start_proc, proc_num_edges.begin()+end_proc+1);\n        size_t maxedges = *std::max_element(proc_num_edges.begin()+start_proc, proc_num_edges.begin()+end_proc+1);\n        \n        for (size_t i = start_proc; i <= end_proc; ++i) {\n          size_t sd = src_degree.get(i) + (usehash && (source % numprocs == i));\n          size_t td = dst_degree.get(i) + (usehash && (target % numprocs == i));\n          double bal = (maxedges - proc_num_edges[i])/(epsilon + maxedges - minedges);\n          proc_score[i] = bal + ((sd > 0) + (td > 0));\n        }\n        maxscore = *std::max_element(proc_score.begin()+start_proc, proc_score.begin()+end_proc+1);\n\n        std::vector<procid_t> top_procs; \n        for (size_t i = start_proc; i <= end_proc; ++i) {\n          if (std::fabs(proc_score[i] - maxscore) < 1e-5)\n            top_procs.push_back(i);\n        }\n\n        // Hash the edge to one of the best procs.\n        typedef std::pair<vertex_id_type, vertex_id_type> edge_pair_type;\n        const edge_pair_type edge_pair(std::min(source, target), \n            std::max(source, target));\n        best_proc = top_procs[graph_hash::hash_edge(edge_pair) % top_procs.size()];\n\n        ASSERT_LT(best_proc, numprocs);\n        if (userecent) {\n          src_degree.clear();\n          dst_degree.clear();\n        }\n        src_degree.set_bit(best_proc);\n        dst_degree.set_bit(best_proc);\n        ++proc_num_edges[best_proc];\n        return best_proc;\n      };\n\n      /** Greedy assign (source, target) to a machine using: \n       *  bitset<MAX_MACHINE> src_degree : the degree presence of source over machines\n       *  bitset<MAX_MACHINE> dst_degree : the degree presence of target over machines\n       *  vector<size_t>      proc_num_edges : the edge counts over machines\n       * */\n      procid_t edge_to_proc_greedy (const vertex_id_type source, \n          const vertex_id_type target,\n          bin_counts_type& src_degree,\n          bin_counts_type& dst_degree,\n          std::vector<procid_t>& candidates,\n          std::vector<size_t>& proc_num_edges,\n          bool usehash = false,\n          bool userecent = false\n          ) {\n        size_t numprocs = proc_num_edges.size();\n\n        // Compute the score of each proc.\n        procid_t best_proc = -1; \n        double maxscore = 0.0;\n        double epsilon = 1.0; \n        std::vector<double> proc_score(candidates.size()); \n        size_t minedges = *std::min_element(proc_num_edges.begin(), proc_num_edges.end());\n        size_t maxedges = *std::max_element(proc_num_edges.begin(), proc_num_edges.end());\n\n        for (size_t j = 0; j < candidates.size(); ++j) {\n          size_t i = candidates[j];\n          size_t sd = src_degree.get(i) + (usehash && (source % numprocs == i));\n          size_t td = dst_degree.get(i) + (usehash && (target % numprocs == i));\n          double bal = (maxedges - proc_num_edges[i])/(epsilon + maxedges - minedges);\n          proc_score[j] = bal + ((sd > 0) + (td > 0));\n        }\n        maxscore = *std::max_element(proc_score.begin(), proc_score.end());\n\n        std::vector<procid_t> top_procs; \n        for (size_t j = 0; j < candidates.size(); ++j)\n          if (std::fabs(proc_score[j] - maxscore) < 1e-5)\n            top_procs.push_back(candidates[j]);\n\n        // Hash the edge to one of the best procs.\n        typedef std::pair<vertex_id_type, vertex_id_type> edge_pair_type;\n        const edge_pair_type edge_pair(std::min(source, target), \n            std::max(source, target));\n        best_proc = top_procs[graph_hash::hash_edge(edge_pair) % top_procs.size()];\n\n        ASSERT_LT(best_proc, numprocs);\n        if (userecent) {\n          src_degree.clear();\n          dst_degree.clear();\n        }\n        src_degree.set_bit(best_proc);\n        dst_degree.set_bit(best_proc);\n        ++proc_num_edges[best_proc];\n        return best_proc;\n      };\n      \n     /** HDRF greedy assign (source, target) to a machine using: \n      *  bitset<MAX_MACHINE> src_degree : the degree presence of source over machines\n      *  bitset<MAX_MACHINE> dst_degree : the degree presence of target over machines\n      *  size_t              src_true_degree : the degree of source vertex over machines\n      *  size_t              dst_true_degree : the degree of target vertex over machines\n      *  vector<size_t>      proc_num_edges : the edge counts over machines\n      *\n      *  author : Fabio Petroni [www.fabiopetroni.com]\n\t  *           Giorgio Iacoboni [g.iacoboni@gmail.com]\n      *\n      *  Based on the publication:\t\n      *  F. Petroni, L. Querzoni, K. Daudjee, S. Kamali and G. Iacoboni: \n      *  \"HDRF: Stream-Based Partitioning for Power-Law Graphs\". \n      *  CIKM, 2015.\n      * */\n     procid_t edge_to_proc_hdrf (const vertex_id_type source, \n          const vertex_id_type target,\n          bin_counts_type& src_degree,\n          bin_counts_type& dst_degree,\n          size_t& src_true_degree,\n          size_t& dst_true_degree,\n          std::vector<size_t>& proc_num_edges,\n          bool usehash = false,\n          bool userecent = false) {\n        \n        size_t numprocs = proc_num_edges.size();\n        \n        size_t degree_u = src_true_degree;\n        degree_u = degree_u +1;\n        size_t degree_v = dst_true_degree;\n        degree_v = degree_v +1;\n        size_t SUM = degree_u + degree_v;\n        double fu = degree_u;\n        fu /= SUM;\n        double fv = degree_v;\n        fv /= SUM;\n        \n        // Compute the score of each proc.\n        procid_t best_proc = -1; \n        double maxscore = 0.0;\n        double epsilon = 1.0; \n        std::vector<double> proc_score(numprocs); \n        size_t minedges = *std::min_element(proc_num_edges.begin(), proc_num_edges.end());\n        size_t maxedges = *std::max_element(proc_num_edges.begin(), proc_num_edges.end());\n        \n        for (size_t i = 0; i < numprocs; ++i) {\n\t\t  double new_sd = 0;\n\t\t  double new_td = 0;\n\t\t  size_t sd = src_degree.get(i) + (usehash && (source % numprocs == i));\n\t\t  size_t td = dst_degree.get(i) + (usehash && (target % numprocs == i));\n\t\t  if (sd > 0){\n\t\t    new_sd = 1+(1-fu);\n\t\t  }\n\t\t  if (td > 0){\n\t\t    new_td = 1+(1-fv);\n\t\t  }\n         double bal = (maxedges - proc_num_edges[i])/(epsilon + maxedges - minedges);\n\n         proc_score[i] = bal + new_sd + new_td;\n        }\n        \n        maxscore = *std::max_element(proc_score.begin(), proc_score.end());\n        \n        std::vector<procid_t> top_procs; \n        for (size_t i = 0; i < numprocs; ++i)\n          if (std::fabs(proc_score[i] - maxscore) < 1e-5)\n            top_procs.push_back(i);\n        \n        // Hash the edge to one of the best procs.\n        typedef std::pair<vertex_id_type, vertex_id_type> edge_pair_type;\n        const edge_pair_type edge_pair(std::min(source, target), std::max(source, target));\n        best_proc = top_procs[graph_hash::hash_edge(edge_pair) % top_procs.size()];\n        \n        ASSERT_LT(best_proc, numprocs);\n        if (userecent) {\n          src_degree.clear();\n          dst_degree.clear();\n        }\n        src_degree.set_bit(best_proc);\n        dst_degree.set_bit(best_proc);\n        ++proc_num_edges[best_proc];\n        ++src_true_degree;\n        ++dst_true_degree;\n        return best_proc;\n     };\n  };// end of ingress_edge_decision\n}\n\n#endif\n", "meta": {"hexsha": "c8bd6f36d2a3a509f2691f3a5c6e331b7e597547", "size": 12836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graphlab/graph/ingress/ingress_edge_decision.hpp", "max_stars_repo_name": "RGraph/RGraph", "max_stars_repo_head_hexsha": "42f3d55248cce700a8e85d4fc31caf58142bf7c0", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T14:39:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-24T01:50:28.000Z", "max_issues_repo_path": "src/graphlab/graph/ingress/ingress_edge_decision.hpp", "max_issues_repo_name": "adeelaslam852/RGraph", "max_issues_repo_head_hexsha": "0a65895bbc0701ef445fdd28688fab37b2186cda", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphlab/graph/ingress/ingress_edge_decision.hpp", "max_forks_repo_name": "adeelaslam852/RGraph", "max_forks_repo_head_hexsha": "0a65895bbc0701ef445fdd28688fab37b2186cda", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T14:39:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T01:50:29.000Z", "avg_line_length": 40.6202531646, "max_line_length": 114, "alphanum_fraction": 0.6216110938, "num_tokens": 3200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338856, "lm_q2_score": 0.04958902719777796, "lm_q1q2_score": 0.02305401666712468}}
{"text": "/*\nCopyright 2015 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n#ifndef MATH_GENERALISE_TYPE_HPP_INCLUDED\n#define MATH_GENERALISE_TYPE_HPP_INCLUDED\n\n#include <type_traits>\n\n#include <boost/mpl/eval_if.hpp>\n#include <boost/mpl/identity.hpp>\n\n#include \"meta/vector.hpp\"\n\n#include \"magma.hpp\"\n\nnamespace math {\n\nnamespace detail {\n\n    template <class Operations, class Magma> struct generalise_type_once;\n\n    template <class Magma> struct generalise_type_once <meta::vector<>, Magma>\n    { typedef Magma type; };\n\n    template <class FirstOperation, class ... Operations, class Magma>\n        struct generalise_type_once <\n            meta::vector <FirstOperation, Operations ...>, Magma>\n    {\n        typedef typename std::result_of <FirstOperation (Magma, Magma)>::type\n            operation_result_type;\n        typedef typename merge_magma::apply <Magma, operation_result_type>::type\n            next_type;\n        typedef typename generalise_type_once <\n            meta::vector <Operations ...>, next_type>::type type;\n    };\n\n} // namespace detail\n\n/**\nConvert a magma type to a type in the same magma that can contain the result of\nany combination of a number of binary operations applied to it.\n\nFor example, a \\ref single_sequence under \\ref plus will generalise to\n\\ref optional_sequence; under \\ref times (or under both) it will generalise to a\n\\ref sequence.\n\n\\tparam Operations\n    A meta::vector of binary operations, usually from namespace callable.\n\\tparam Magma\n    The magma type to be generalised.\n*/\ntemplate <class Operations, class Magma> struct generalise_type {\n    typedef typename std::decay <Magma>::type magma_type;\n    typedef typename detail::generalise_type_once <Operations, magma_type>::type\n        next_type;\n\n    typedef typename boost::mpl::eval_if <\n            std::is_same <Magma, next_type>,\n            boost::mpl::identity <Magma>,\n            generalise_type <Operations, next_type>\n        >::type type;\n};\n\n} // namespace math\n\n#endif  // MATH_GENERALISE_TYPE_HPP_INCLUDED\n", "meta": {"hexsha": "5d7b68b246fc6ae73bb7076668954182754403fa", "size": 2521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/generalise_type.hpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/generalise_type.hpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/generalise_type.hpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5125, "max_line_length": 80, "alphanum_fraction": 0.7266957557, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.04958902526647757, "lm_q1q2_score": 0.023054016504552976}}
{"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-2011 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 PARTIALINDEXSET_HH\n#define PARTIALINDEXSET_HH\n\n#include <cassert>\n#include <vector>\n\n#include <boost/mpl/range_c.hpp>\n\n#include <boost/fusion/algorithm.hpp>\n\n#include \"dune/grid/common/indexidset.hh\"\n#include \"dune/grid/common/referenceelements.hh\"\n\n#include \"fem/fetransfer.hh\"\n\n/**\n *\\todo recompute internal representation whenever grid changes.\n *\n * Part has to provide a method bool contains(typename Grid::Traits::template Codim<0>::Entity const&) const;\n */\ntemplate<class Grid, class IndexSet, class Part>\nclass PartialIndexSet {\n  typedef PartialIndexSet<Grid,IndexSet,Part> Self;\n  typedef typename Grid::Traits::template Codim<0>::Entity Cell;\n  \npublic:\n  template <int cd>\n  struct Codim\n  {\n    template <Dune::PartitionIteratorType pitype>\n    struct Partition\n    {\n      class Iterator\n      {\n        typedef typename IndexSet::template Codim<cd>::template Partition<pitype>::Iterator Iter;\n        \n      public:\n        typedef typename Grid::template Codim<0>::Entity Entity;\n        \n        Iterator(Iter const& cur_, Iter const& end_, Part const& part_):\n          cur(cur_), end(end_), part(part_) {\n          ahead();\n        }\n\n        Iterator& operator++() \n        {\n          if (cur!=end)\n            ++cur;\n          ahead();\n          return *this;\n        }\n\n        Entity& operator*() const { return *cur; }\n        Entity* operator->() const { return &*cur; }\n\n        bool operator==(Iterator const& i) const { return cur==i.cur; }\n        bool operator!=(Iterator const& i) const { return !(*this == i); }\n        \n        operator typename Grid::Traits::template Codim<0>::EntityPointer() const \n        {\n          return cur;\n        }\n        \n      private:\n        void ahead() \n        {\n          while (cur!=end && !part.contains(*cur))\n            ++cur;\n        }\n            \n        Iter cur, end;\n        Part const& part;\n      };\n    };\n  };\n\n  PartialIndexSet(GridSignals& signals, IndexSet const& indexSet_, Part const& part_):\n    indexSet(indexSet_), part(part_)\n  {\n    typedef typename IndexSet::template Codim<0>::\n        template Partition<Dune::All_Partition>::Iterator CellIterator;\n    CellIterator end = indexSet.template end<0,Dune::All_Partition>();\n    for (CellIterator ci=indexSet.template begin<0,Dune::All_Partition>(); ci!=end; ++ci) \n      if (part.contains(*ci)) {\n        insert(ci->type(),indexSet.index(*ci));\n        boost::fusion::for_each(boost::mpl::range_c<int,1,Grid::dimension+1>(),\n                                Update(*this,*ci));\n      }\n  }\n  \n      \n  template <int cc>\n  int index (typename Grid::Traits::template Codim<cc>::Entity const& e) const \n  {\n    typename Map::const_iterator i = idx.find(e.type());\n    if (i==idx.end()) return -1;\n    else              return i->second.first[indexSet.index(e)];\n  }\n\n  template<class EntityType>\n  int index (const EntityType& e) const\n  {\n    return index<EntityType::codimension>(e);\n  }\n\n  template<int cc>\n  int subIndex (Cell const& e, int i) const\n  {\n    // unfortunately the following is not implemented in every grid interface...\n    // return index(*e.template entity<cc>(i));\n\n    Dune::GeometryType subentityType =\n      Dune::ReferenceElements<typename Grid::ctype,Grid::dimension>::general(e.type()).type(i,cc);\n    typename Map::const_iterator it = idx.find(subentityType);\n    if (it==idx.end()) return -1;\n    else               return it->second.first[indexSet.template subIndex<cc>(e,i)];\n  }\n  \n  const std::vector<Dune::GeometryType>& geomTypes (int codim) const\n  {\n    return indexSet.geomTypes(codim);\n  }\n\n  int size (Dune::GeometryType type) const\n  {\n    typename Map::const_iterator i= idx.find(type);\n    if (i==idx.end()) return 0;\n    else              return i->second.second;\n  }\n\n  int size (int codim) const\n  {\n    int count = 0;\n    for (typename Map::const_iterator i=idx.begin(); i!=idx.end(); ++i)\n      if (i->first.dim() == Grid::dimension-codim)\n        count += i->second.second;\n    return count;\n  }\n\n  template<class EntityType>\n  bool contains (const EntityType& e) const\n  {\n    return indexSet.contains(e) && index(e)>=0;\n  }\n\n  template<int cd, Dune::PartitionIteratorType pitype>\n  typename Codim<cd>::template Partition<pitype>::Iterator begin () const\n  {\n    return typename Codim<cd>::template Partition<pitype>::Iterator(indexSet.template begin<cd,pitype>(),\n                                                                    indexSet.template end<cd,pitype>(),\n                                                                    part);\n  }\n  \n  template<int cd, Dune::PartitionIteratorType pitype>\n  typename Codim<cd>::template Partition<pitype>::Iterator end () const\n  {\n    return typename Codim<cd>::template Partition<pitype>::Iterator(indexSet.template end<cd,pitype>(),\n                                                                    indexSet.template end<cd,pitype>(),\n                                                                    part);\n  }\n\nprivate:\n  IndexSet const& indexSet;\n  Part const& part;\n\n  // For each geometry type, separate contiguous indices are\n  // maintained, which are stored according to the underlying index\n  // set. A negative value denotes entities which are not contained in\n  // the partial index set. The second part in the data type is a\n  // running counter used for generating contiguous indices.\n  typedef std::map<Dune::GeometryType,std::pair<std::vector<int>,int> > Map;\n  Map idx;\n\n  void insert(Dune::GeometryType gt, int index) \n  {\n    std::pair<std::vector<int>,int>& gtIdx = idx[gt];\n\n    if (gtIdx.first.empty()) {\n      gtIdx.first.resize(indexSet.size(gt),-1);\n      gtIdx.second = 0;\n    }\n\n    if (gtIdx.first[index]<0) \n      gtIdx.first[index] = gtIdx.second++;\n  }\n  \n  // A MPL/fusion functor which inserts all the cell's subentities of\n  // given codimension into the index map.\n  struct Update \n  {\n    Update(Self& pis_, Cell const& cell_): pis(pis_), cell(cell_) {}\n    \n    template <class Integer>\n    void operator()(Integer const /* codim */) const \n    {\n      int const codim = Integer::value;\n      int const count = cell.template count<codim>();\n      \n\n      for (int i=0; i<count; ++i)\n        pis.insert(Dune::ReferenceElements<typename Grid::ctype,Grid::dimension>::general(cell.type()).type(i,codim),\n                   pis.indexSet.template subIndex<codim>(cell,i));\n    }\n\n  private:\n    Self& pis;\n    Cell const& cell;\n  };\n};\n\n\n#endif\n", "meta": {"hexsha": "d3caa4f06b9be518ee44f83428ae49142e95de66", "size": 7317, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/partialindexset.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/partialindexset.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/partialindexset.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 32.52, "max_line_length": 117, "alphanum_fraction": 0.5603389367, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.055005292553523225, "lm_q1q2_score": 0.02303054678833629}}
{"text": "#include \"script_reader.h\"\r\n#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n#include <string>\r\n#include <boost/qvm/vec.hpp>\r\n#include <boost/algorithm/string.hpp>\r\n#include \"Body.h\"\r\n\r\n// load data from file path provided by command line arg\r\ninitial_state load_input_data(char* input_file_path)\r\n{\r\n    std::ifstream input_file(input_file_path, std::ios_base::in);\r\n\r\n    if (!input_file.is_open())\r\n    {\r\n        std::cout << \"error: could not open\" << input_file_path << std::endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n    initial_state input_state;\r\n    double m;\r\n    boost::qvm::vec<double, 3> r, v;\r\n    std::string line;\r\n    std::vector<std::string> parsed_line;\r\n\r\n    // add conditionals to replicated Julia code\r\n    while (getline(input_file, line))\r\n    {\r\n        boost::algorithm::split(parsed_line, line, boost::is_any_of(\" \"));\r\n\r\n        if (parsed_line[0] == \"time\")\r\n        {\r\n            input_state.t = atof(parsed_line[1].c_str());\r\n        }\r\n        else if (parsed_line[0] == \"step_size\")\r\n        {\r\n            input_state.dt = atof(parsed_line[1].c_str());\r\n        }\r\n        else if (parsed_line[0] == \"save_interval\")\r\n        {\r\n            input_state.save_interval = atof(parsed_line[1].c_str());\r\n        }\r\n        else if (parsed_line[0] == \"body\")\r\n        {\r\n            m =   atof(parsed_line[1].c_str());\r\n            r = { atof(parsed_line[2].c_str()),\r\n                  atof(parsed_line[3].c_str()),\r\n                  atof(parsed_line[4].c_str()) };\r\n            v = { atof(parsed_line[5].c_str()),\r\n                  atof(parsed_line[6].c_str()),\r\n                  atof(parsed_line[7].c_str()) };\r\n\r\n            input_state.system.push_back(Body(m, r, v));\r\n        }\r\n        else\r\n        {\r\n            std::cout << \"error: incorrect syntax: \" << line << std::endl;\r\n            exit(EXIT_FAILURE);\r\n        }\r\n    }\r\n\r\n    return input_state;\r\n}", "meta": {"hexsha": "58fe3bbdd508005920ea46cf42c9f18809ff48e1", "size": 1914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/script_reader.cpp", "max_stars_repo_name": "ilovematter/nbody_cpp", "max_stars_repo_head_hexsha": "94b0e26b65a2fdf4534b58e447ae25578513416e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/script_reader.cpp", "max_issues_repo_name": "ilovematter/nbody_cpp", "max_issues_repo_head_hexsha": "94b0e26b65a2fdf4534b58e447ae25578513416e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/script_reader.cpp", "max_forks_repo_name": "ilovematter/nbody_cpp", "max_forks_repo_head_hexsha": "94b0e26b65a2fdf4534b58e447ae25578513416e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.90625, "max_line_length": 78, "alphanum_fraction": 0.5386624869, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.050330629392407525, "lm_q1q2_score": 0.023007978676306585}}
{"text": "//   Copyright 2019 <Huawei Technologies Co., Ltd>\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 <pybind11/complex.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/pytypes.h>\n#include <pybind11/stl.h>\n\n#include <complex>\n#include <iostream>\n#include <vector>\n#if defined(_OPENMP)\n#     include <omp.h>\n#endif\n#include <boost/container/vector.hpp>\n\n#include \"simulator-mpi/SimulatorMPI.hpp\"\n\nnamespace pybind11\n{\nnamespace detail\n{\n     template <typename Type, typename Alloc>\n     struct type_caster<boost::container::vector<Type, Alloc>>\n         : list_caster<boost::container::vector<Type, Alloc>, Type>\n     {};\n}  // namespace detail\n}  // namespace pybind11\n\nnamespace py = pybind11;\n\nusing c_type = std::complex<double>;\nusing ArrayType = std::vector<c_type, aligned_allocator<c_type, 64>>;\nusing MatrixType = std::vector<ArrayType>;\nusing QuRegs = std::vector<std::vector<unsigned>>;\n\ntemplate <class QR>\nvoid emulate_math_wrapper(SimulatorMPI& sim, py::function const& pyfunc,\n                          QR const& qr, Fusion::IndexVector const& ctrls)\n{\n     auto f = [&](std::vector<int>& x) {\n          pybind11::gil_scoped_acquire acquire;\n          x = std::move(pyfunc(x).cast<std::vector<int>>());\n     };\n     pybind11::gil_scoped_release release;\n     sim.emulate_math(f, qr, ctrls);\n}\n\nPYBIND11_MODULE(_cppsim_mpi, m)\n{\n     py::class_<SimulatorMPI>(m, \"SimulatorMPI\")\n         .def(py::init<uint64_t, int, int>())\n         .def(\"get_qubits_ids\", &SimulatorMPI::GetQubitsPermutation)\n         .def(\"get_local_qubits_ids\", &SimulatorMPI::GetLocalQubitsPermutation)\n         .def(\"get_global_qubits_ids\",\n              &SimulatorMPI::GetGlobalQubitsPermutation)\n         .def(\"set_qubits_perm\", &SimulatorMPI::SetQubitsPermutation)\n         .def(\"swap_qubits\", &SimulatorMPI::SwapQubitsWrapper)\n         .def(\"allocate_qureg\", &SimulatorMPI::AllocateQureg)\n         .def(\"allocate_qubit\", &SimulatorMPI::AllocateQubit)\n         .def(\"deallocate_qubit\", &SimulatorMPI::DeallocateQubit)\n         .def(\"measure_qubits\", &SimulatorMPI::MeasureQubits)\n         .def(\"apply_controlled_gate\", &SimulatorMPI::ApplyGate)\n         .def(\"emulate_math\", &emulate_math_wrapper<QuRegs>)\n         .def(\"get_amplitude\", &SimulatorMPI::GetAmplitude)\n         .def(\"get_probability\", &SimulatorMPI::GetProbability)\n         .def(\"run\", &SimulatorMPI::Run)\n         .def(\"entropy\", &SimulatorMPI::Entropy)\n         .def(\"cheat_local\", &SimulatorMPI::cheat_local)\n         .def(\"collapse_wavefunction\", &SimulatorMPI::collapseWaveFunction);\n}\n", "meta": {"hexsha": "74d2f38778a375b790e06ddffce14a59f1c09a39", "size": 3111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_cppsim_mpi.cpp", "max_stars_repo_name": "thexdesk/HiQsimulator", "max_stars_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T01:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T14:51:01.000Z", "max_issues_repo_path": "_cppsim_mpi.cpp", "max_issues_repo_name": "thexdesk/HiQsimulator", "max_issues_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T01:45:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T02:37:32.000Z", "max_forks_repo_path": "_cppsim_mpi.cpp", "max_forks_repo_name": "thexdesk/HiQsimulator", "max_forks_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2019-07-10T20:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T14:51:20.000Z", "avg_line_length": 37.0357142857, "max_line_length": 79, "alphanum_fraction": 0.68723883, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04672495846016151, "lm_q1q2_score": 0.022997470196138507}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2014 - 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/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#include \"ibamr/GeneralizedIBMethod.h\"\n#include \"ibamr/IBHierarchyIntegrator.h\"\n#include \"ibamr/IBKirchhoffRodForceGen.h\"\n#include \"ibamr/IBMethod.h\"\n#include \"ibamr/namespaces.h\" // IWYU pragma: keep\n\n#include \"ibtk/HierarchyGhostCellInterpolation.h\"\n#include \"ibtk/HierarchyMathOps.h\"\n#include \"ibtk/IBTK_CHKERRQ.h\"\n#include \"ibtk/LData.h\"\n#include \"ibtk/LDataManager.h\"\n#include \"ibtk/LInitStrategy.h\"\n#include \"ibtk/LSiloDataWriter.h\"\n#include \"ibtk/ibtk_utilities.h\"\n\n#include \"BasePatchHierarchy.h\"\n#include \"BasePatchLevel.h\"\n#include \"CellVariable.h\"\n#include \"CoarsenSchedule.h\"\n#include \"GriddingAlgorithm.h\"\n#include \"HierarchyDataOpsReal.h\"\n#include \"IntVector.h\"\n#include \"MultiblockDataTranslator.h\"\n#include \"PatchHierarchy.h\"\n#include \"PatchLevel.h\"\n#include \"RefineAlgorithm.h\"\n#include \"RefineOperator.h\"\n#include \"RefineSchedule.h\"\n#include \"SideVariable.h\"\n#include \"Variable.h\"\n#include \"VariableContext.h\"\n#include \"tbox/Database.h\"\n#include \"tbox/MathUtilities.h\"\n#include \"tbox/Pointer.h\"\n#include \"tbox/RestartManager.h\"\n#include \"tbox/Utilities.h\"\n\n#include \"petscvec.h\"\n\n#include \"Eigen/src/Core/GeneralProduct.h\"\n\nIBTK_DISABLE_EXTRA_WARNINGS\n#include <boost/multi_array.hpp>\nIBTK_ENABLE_EXTRA_WARNINGS\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <ostream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace IBTK\n{\nclass RobinPhysBdryPatchStrategy;\n} // namespace IBTK\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\nnamespace IBAMR\n{\n/////////////////////////////// STATIC ///////////////////////////////////////\n\nnamespace\n{\n// Version of GeneralizedIBMethod restart file data.\nstatic const int GENERALIZED_IB_METHOD_VERSION = 1;\n} // namespace\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nGeneralizedIBMethod::GeneralizedIBMethod(std::string object_name, Pointer<Database> input_db, bool register_for_restart)\n    : IBMethod(std::move(object_name), input_db, register_for_restart)\n{\n    // NOTE: Parent class constructor registers class with the restart manager,\n    // sets object name.\n\n    // Initialize object with data read from the input and restart databases.\n    bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (from_restart) getFromRestart();\n    if (input_db) getFromInput(input_db, from_restart);\n\n    return;\n} // GeneralizedIBMethod\n\nvoid\nGeneralizedIBMethod::registerIBKirchhoffRodForceGen(Pointer<IBKirchhoffRodForceGen> ib_force_and_torque_fcn)\n{\n#if !defined(NDEBUG)\n    TBOX_ASSERT(ib_force_and_torque_fcn);\n#endif\n    d_ib_force_and_torque_fcn = ib_force_and_torque_fcn;\n    return;\n} // registerIBKirchhoffRodForceGen\n\nvoid\nGeneralizedIBMethod::registerEulerianVariables()\n{\n    IBMethod::registerEulerianVariables();\n\n    const IntVector<NDIM> ib_ghosts = getMinimumGhostCellWidth();\n    const IntVector<NDIM> no_ghosts = 0;\n\n    Pointer<Variable<NDIM> > u_var = d_ib_solver->getVelocityVariable();\n    Pointer<CellVariable<NDIM, double> > u_cc_var = u_var;\n    Pointer<SideVariable<NDIM, double> > u_sc_var = u_var;\n    if (u_cc_var)\n    {\n        d_f_var = new CellVariable<NDIM, double>(d_object_name + \"::f\", NDIM);\n        d_w_var = new CellVariable<NDIM, double>(d_object_name + \"::w\", NDIM);\n        d_n_var = new CellVariable<NDIM, double>(d_object_name + \"::n\", NDIM);\n    }\n    else if (u_sc_var)\n    {\n        d_f_var = new SideVariable<NDIM, double>(d_object_name + \"::f\");\n        d_w_var = new SideVariable<NDIM, double>(d_object_name + \"::w\");\n        d_n_var = new SideVariable<NDIM, double>(d_object_name + \"::n\");\n    }\n    else\n    {\n        TBOX_ERROR(d_object_name << \"::registerEulerianVariables():\\n\"\n                                 << \"  unsupported velocity data centering\" << std::endl);\n    }\n    registerVariable(d_f_idx, d_f_var, no_ghosts, d_ib_solver->getScratchContext());\n    registerVariable(d_w_idx, d_w_var, ib_ghosts, d_ib_solver->getScratchContext());\n    registerVariable(d_n_idx, d_n_var, ib_ghosts, d_ib_solver->getScratchContext());\n    return;\n} // registerEulerianVariables\n\nvoid\nGeneralizedIBMethod::registerEulerianCommunicationAlgorithms()\n{\n    IBMethod::registerEulerianCommunicationAlgorithms();\n\n    Pointer<RefineAlgorithm<NDIM> > refine_alg;\n    Pointer<RefineOperator<NDIM> > refine_op;\n\n    refine_alg = new RefineAlgorithm<NDIM>();\n    refine_op = nullptr;\n    refine_alg->registerRefine(d_w_idx, d_w_idx, d_w_idx, refine_op);\n    registerGhostfillRefineAlgorithm(d_object_name + \"::w\", refine_alg);\n\n    refine_alg = new RefineAlgorithm<NDIM>();\n    refine_op = nullptr;\n    refine_alg->registerRefine(d_n_idx, d_n_idx, d_n_idx, refine_op);\n    registerGhostfillRefineAlgorithm(d_object_name + \"::n\", refine_alg);\n    return;\n} // registerEulerianCommunicationAlgorithms\n\nvoid\nGeneralizedIBMethod::preprocessIntegrateData(double current_time, double new_time, int num_cycles)\n{\n    d_ib_force_and_torque_fcn_needs_init = d_ib_force_fcn_needs_init || d_ib_force_and_torque_fcn_needs_init;\n    IBMethod::preprocessIntegrateData(current_time, new_time, num_cycles);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double start_time = d_ib_solver->getStartTime();\n\n    if (d_ib_force_and_torque_fcn)\n    {\n        if (d_ib_force_and_torque_fcn_needs_init)\n        {\n            const bool initial_time = MathUtilities<double>::equalEps(current_time, start_time);\n            resetLagrangianForceAndTorqueFunction(current_time, initial_time);\n            d_ib_force_and_torque_fcn_needs_init = false;\n        }\n    }\n\n    // Look-up or allocate Lagangian data.\n    d_D_current_data.resize(finest_ln + 1);\n    d_D_new_data.resize(finest_ln + 1);\n    d_N_current_data.resize(finest_ln + 1);\n    d_N_new_data.resize(finest_ln + 1);\n    d_W_current_data.resize(finest_ln + 1);\n    d_W_new_data.resize(finest_ln + 1);\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        d_D_current_data[ln] = d_l_data_manager->getLData(\"D\", ln);\n        d_D_new_data[ln] = d_l_data_manager->createLData(\"D_new\", ln, NDIM * NDIM);\n        d_N_current_data[ln] = d_l_data_manager->createLData(\"N\", ln, NDIM);\n        d_N_new_data[ln] = d_l_data_manager->createLData(\"N_new\", ln, NDIM);\n        d_W_current_data[ln] = d_l_data_manager->getLData(\"W\", ln);\n        d_W_new_data[ln] = d_l_data_manager->createLData(\"W_new\", ln, NDIM);\n\n        // Initialize D^{n+1} to equal D^{n}, and initialize W^{n+1} to equal\n        // W^{n}.\n        int ierr;\n        ierr = VecCopy(d_D_current_data[ln]->getVec(), d_D_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n        ierr = VecCopy(d_W_current_data[ln]->getVec(), d_W_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n    }\n    return;\n} // preprocessIntegrateData\n\nvoid\nGeneralizedIBMethod::postprocessIntegrateData(double current_time, double new_time, int num_cycles)\n{\n    IBMethod::postprocessIntegrateData(current_time, new_time, num_cycles);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n    // Reset time-dependent Lagrangian data.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        int ierr;\n        ierr = VecSwap(d_D_current_data[ln]->getVec(), d_D_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n        ierr = VecSwap(d_W_current_data[ln]->getVec(), d_W_new_data[ln]->getVec());\n        IBTK_CHKERRQ(ierr);\n    }\n\n    // Deallocate Lagrangian scratch data.\n    d_D_current_data.clear();\n    d_D_new_data.clear();\n    d_N_current_data.clear();\n    d_N_new_data.clear();\n    d_W_current_data.clear();\n    d_W_new_data.clear();\n    return;\n} // postprocessIntegrateData\n\nvoid\nGeneralizedIBMethod::interpolateVelocity(const int u_data_idx,\n                                         const std::vector<Pointer<CoarsenSchedule<NDIM> > >& u_synch_scheds,\n                                         const std::vector<Pointer<RefineSchedule<NDIM> > >& u_ghost_fill_scheds,\n                                         const double data_time)\n{\n    // Interpolate the linear velocities.\n    IBMethod::interpolateVelocity(u_data_idx, u_synch_scheds, u_ghost_fill_scheds, data_time);\n\n    // Interpolate the angular velocities.\n    std::vector<Pointer<LData> >* W_data = nullptr;\n    if (MathUtilities<double>::equalEps(data_time, d_current_time))\n    {\n        W_data = &d_W_current_data;\n    }\n    else if (MathUtilities<double>::equalEps(data_time, d_half_time))\n    {\n        TBOX_ERROR(d_object_name << \"::interpolateVelocity():\\n\"\n                                 << \"  time-stepping type MIDPOINT_RULE not supported by \"\n                                    \"class GeneralizedIBMethod;\\n\"\n                                 << \"  use TRAPEZOIDAL_RULE instead.\\n\");\n    }\n    else if (MathUtilities<double>::equalEps(data_time, d_new_time))\n    {\n        W_data = &d_W_new_data;\n    }\n    TBOX_ASSERT(W_data);\n\n    Pointer<Variable<NDIM> > u_var = d_ib_solver->getVelocityVariable();\n    Pointer<CellVariable<NDIM, double> > u_cc_var = u_var;\n    Pointer<SideVariable<NDIM, double> > u_sc_var = u_var;\n    if (u_cc_var)\n    {\n        Pointer<CellVariable<NDIM, double> > w_cc_var = d_w_var;\n        getHierarchyMathOps()->curl(d_w_idx, w_cc_var, u_data_idx, u_cc_var, nullptr, data_time);\n    }\n    else if (u_sc_var)\n    {\n        Pointer<SideVariable<NDIM, double> > w_sc_var = d_w_var;\n        getHierarchyMathOps()->curl(d_w_idx, w_sc_var, u_data_idx, u_sc_var, nullptr, data_time);\n    }\n    else\n    {\n        TBOX_ERROR(d_object_name << \"::interpolateVelocity():\\n\"\n                                 << \"  unsupported velocity data centering\" << std::endl);\n    }\n    std::vector<Pointer<LData> >* X_LE_data;\n    bool* X_LE_needs_ghost_fill;\n    getLECouplingPositionData(&X_LE_data, &X_LE_needs_ghost_fill, data_time);\n    getVelocityHierarchyDataOps()->scale(d_w_idx, 0.5, d_w_idx);\n    d_l_data_manager->interp(d_w_idx,\n                             *W_data,\n                             *X_LE_data,\n                             std::vector<Pointer<CoarsenSchedule<NDIM> > >(),\n                             getGhostfillRefineSchedules(d_object_name + \"::w\"),\n                             data_time);\n    resetAnchorPointValues(*W_data,\n                           /*coarsest_ln*/ 0,\n                           /*finest_ln*/ d_hierarchy->getFinestLevelNumber());\n    return;\n} // interpolateVelocity\n\nvoid\nGeneralizedIBMethod::forwardEulerStep(const double current_time, const double new_time)\n{\n    IBMethod::forwardEulerStep(current_time, new_time);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = new_time - current_time;\n\n    // Update the value of D^{n+1} using forward Euler.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        boost::multi_array_ref<double, 2>& D_current_data = *d_D_current_data[ln]->getLocalFormVecArray();\n        boost::multi_array_ref<double, 2>& W_current_data = *d_W_current_data[ln]->getLocalFormVecArray();\n        boost::multi_array_ref<double, 2>& D_new_data = *d_D_new_data[ln]->getLocalFormVecArray();\n        const int n_local = d_l_data_manager->getNumberOfLocalNodes(ln);\n        Matrix3d R;\n        Vector3d e;\n        for (int l = 0; l < n_local; ++l)\n        {\n            for (int d = 0; d < NDIM; ++d)\n            {\n                e(d) = W_current_data[l][d];\n            }\n            const double norm_e = e.norm();\n            if (norm_e > std::numeric_limits<double>::epsilon())\n            {\n                const double theta = norm_e * dt;\n                e /= norm_e;\n                const double c_t = std::cos(theta);\n                const double s_t = std::sin(theta);\n                R << c_t + (1.0 - c_t) * e(0) * e(0), (1.0 - c_t) * e(0) * e(1) - s_t * e(2),\n                    (1.0 - c_t) * e(0) * e(2) + s_t * e(1), (1.0 - c_t) * e(1) * e(0) + s_t * e(2),\n                    c_t + (1.0 - c_t) * e(1) * e(1), (1.0 - c_t) * e(1) * e(2) - s_t * e(0),\n                    (1.0 - c_t) * e(2) * e(0) - s_t * e(1), (1.0 - c_t) * e(2) * e(1) + s_t * e(0),\n                    c_t + (1.0 - c_t) * e(2) * e(2);\n                for (int alpha = 0; alpha < 3; ++alpha)\n                {\n                    Eigen::Map<const Vector3d> D_current_alpha(&D_current_data[l][3 * alpha]);\n                    Eigen::Map<Vector3d> D_new_alpha(&D_new_data[l][3 * alpha]);\n                    D_new_alpha = R * D_current_alpha;\n                }\n            }\n            else\n            {\n                for (int alpha = 0; alpha < 3; ++alpha)\n                {\n                    Eigen::Map<const Vector3d> D_current_alpha(&D_current_data[l][3 * alpha]);\n                    Eigen::Map<Vector3d> D_new_alpha(&D_new_data[l][3 * alpha]);\n                    D_new_alpha = D_current_alpha;\n                }\n            }\n        }\n    }\n    return;\n} // eulerStep\n\nvoid\nGeneralizedIBMethod::midpointStep(const double /*current_time*/, const double /*new_time*/)\n{\n    TBOX_ERROR(d_object_name << \"::midpointStep():\\n\"\n                             << \"  time-stepping type MIDPOINT_RULE not \"\n                                \"supported by class GeneralizedIBMethod;\\n\"\n                             << \"  use TRAPEZOIDAL_RULE instead.\\n\");\n    return;\n} // midpointStep\n\nvoid\nGeneralizedIBMethod::trapezoidalStep(const double current_time, const double new_time)\n{\n    IBMethod::trapezoidalStep(current_time, new_time);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const double dt = new_time - current_time;\n\n    // Update the value of D^{n+1} using the trapezoidal rule.\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        boost::multi_array_ref<double, 2>& D_current_data = *d_D_current_data[ln]->getLocalFormVecArray();\n        boost::multi_array_ref<double, 2>& W_current_data = *d_W_current_data[ln]->getLocalFormVecArray();\n        boost::multi_array_ref<double, 2>& D_new_data = *d_D_new_data[ln]->getLocalFormVecArray();\n        boost::multi_array_ref<double, 2>& W_new_data = *d_W_new_data[ln]->getLocalFormVecArray();\n        const int n_local = d_l_data_manager->getNumberOfLocalNodes(ln);\n        Matrix3d R;\n        Vector3d e;\n        for (int l = 0; l < n_local; ++l)\n        {\n            for (int d = 0; d < NDIM; ++d)\n            {\n                e(d) = 0.5 * (W_current_data[l][d] + W_new_data[l][d]);\n            }\n            const double norm_e = e.norm();\n            if (norm_e > std::numeric_limits<double>::epsilon())\n            {\n                const double theta = norm_e * dt;\n                e /= norm_e;\n                const double c_t = std::cos(theta);\n                const double s_t = std::sin(theta);\n                R << c_t + (1.0 - c_t) * e(0) * e(0), (1.0 - c_t) * e(0) * e(1) - s_t * e(2),\n                    (1.0 - c_t) * e(0) * e(2) + s_t * e(1), (1.0 - c_t) * e(1) * e(0) + s_t * e(2),\n                    c_t + (1.0 - c_t) * e(1) * e(1), (1.0 - c_t) * e(1) * e(2) - s_t * e(0),\n                    (1.0 - c_t) * e(2) * e(0) - s_t * e(1), (1.0 - c_t) * e(2) * e(1) + s_t * e(0),\n                    c_t + (1.0 - c_t) * e(2) * e(2);\n                for (int alpha = 0; alpha < 3; ++alpha)\n                {\n                    Eigen::Map<const Vector3d> D_current_alpha(&D_current_data[l][3 * alpha]);\n                    Eigen::Map<Vector3d> D_new_alpha(&D_new_data[l][3 * alpha]);\n                    D_new_alpha = R * D_current_alpha;\n                }\n            }\n            else\n            {\n                for (int alpha = 0; alpha < 3; ++alpha)\n                {\n                    Eigen::Map<const Vector3d> D_current_alpha(&D_current_data[l][3 * alpha]);\n                    Eigen::Map<Vector3d> D_new_alpha(&D_new_data[l][3 * alpha]);\n                    D_new_alpha = D_current_alpha;\n                }\n            }\n        }\n    }\n    return;\n} // trapezoidalStep\n\nvoid\nGeneralizedIBMethod::computeLagrangianForce(const double data_time)\n{\n    IBMethod::computeLagrangianForce(data_time);\n\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    int ierr;\n    std::vector<Pointer<LData> >* F_data = nullptr;\n    std::vector<Pointer<LData> >* N_data = nullptr;\n    std::vector<Pointer<LData> >* X_data = nullptr;\n    std::vector<Pointer<LData> >* D_data = nullptr;\n    if (MathUtilities<double>::equalEps(data_time, d_current_time))\n    {\n        d_F_current_needs_ghost_fill = true;\n        d_N_current_needs_ghost_fill = true;\n        F_data = &d_F_current_data;\n        N_data = &d_N_current_data;\n        X_data = &d_X_current_data;\n        D_data = &d_D_current_data;\n    }\n    else if (MathUtilities<double>::equalEps(data_time, d_half_time))\n    {\n        TBOX_ERROR(d_object_name << \"::computeLagrangianForce():\\n\"\n                                 << \"  time-stepping type MIDPOINT_RULE not supported by \"\n                                    \"class GeneralizedIBMethod;\\n\"\n                                 << \"  use TRAPEZOIDAL_RULE instead.\\n\");\n    }\n    else if (MathUtilities<double>::equalEps(data_time, d_new_time))\n    {\n        d_F_new_needs_ghost_fill = true;\n        d_N_new_needs_ghost_fill = true;\n        F_data = &d_F_new_data;\n        N_data = &d_N_new_data;\n        X_data = &d_X_new_data;\n        D_data = &d_D_new_data;\n    }\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        ierr = VecSet((*N_data)[ln]->getVec(), 0.0);\n        IBTK_CHKERRQ(ierr);\n        if (d_ib_force_and_torque_fcn)\n        {\n            d_ib_force_and_torque_fcn->computeLagrangianForceAndTorque((*F_data)[ln],\n                                                                       (*N_data)[ln],\n                                                                       (*X_data)[ln],\n                                                                       (*D_data)[ln],\n                                                                       d_hierarchy,\n                                                                       ln,\n                                                                       data_time,\n                                                                       d_l_data_manager);\n        }\n    }\n    resetAnchorPointValues(*F_data, coarsest_ln, finest_ln);\n    resetAnchorPointValues(*N_data, coarsest_ln, finest_ln);\n    return;\n} // computeLagrangianForce\n\nvoid\nGeneralizedIBMethod::spreadForce(const int f_data_idx,\n                                 RobinPhysBdryPatchStrategy* f_phys_bdry_op,\n                                 const std::vector<Pointer<RefineSchedule<NDIM> > >& f_prolongation_scheds,\n                                 const double data_time)\n{\n    IBMethod::spreadForce(f_data_idx, f_phys_bdry_op, f_prolongation_scheds, data_time);\n\n    std::vector<Pointer<LData> >* N_data = nullptr;\n    bool* N_needs_ghost_fill = nullptr;\n    if (MathUtilities<double>::equalEps(data_time, d_current_time))\n    {\n        N_data = &d_N_current_data;\n        N_needs_ghost_fill = &d_N_current_needs_ghost_fill;\n    }\n    else if (MathUtilities<double>::equalEps(data_time, d_half_time))\n    {\n        TBOX_ERROR(d_object_name << \"::spreadForce():\\n\"\n                                 << \"  time-stepping type MIDPOINT_RULE not supported by \"\n                                    \"class GeneralizedIBMethod;\\n\"\n                                 << \"  use TRAPEZOIDAL_RULE instead.\\n\");\n    }\n    else if (MathUtilities<double>::equalEps(data_time, d_new_time))\n    {\n        N_data = &d_N_new_data;\n        N_needs_ghost_fill = &d_N_new_needs_ghost_fill;\n    }\n    TBOX_ASSERT(N_data);\n    TBOX_ASSERT(N_needs_ghost_fill);\n\n    std::vector<Pointer<LData> >* X_LE_data;\n    bool* X_LE_needs_ghost_fill;\n    getLECouplingPositionData(&X_LE_data, &X_LE_needs_ghost_fill, data_time);\n    getVelocityHierarchyDataOps()->setToScalar(d_n_idx, 0.0, false);\n    d_l_data_manager->spread(d_n_idx,\n                             *N_data,\n                             *X_LE_data,\n                             f_phys_bdry_op,\n                             std::vector<Pointer<RefineSchedule<NDIM> > >(),\n                             data_time,\n                             *N_needs_ghost_fill,\n                             *X_LE_needs_ghost_fill);\n    *N_needs_ghost_fill = false;\n    *X_LE_needs_ghost_fill = false;\n    const int coarsest_ln = 0;\n    const int finest_ln = d_hierarchy->getFinestLevelNumber();\n    const std::vector<Pointer<RefineSchedule<NDIM> > >& n_ghostfill_scheds =\n        getGhostfillRefineSchedules(d_object_name + \"::n\");\n    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);\n        n_ghostfill_scheds[ln]->fillData(data_time);\n    }\n    Pointer<Variable<NDIM> > u_var = d_ib_solver->getVelocityVariable();\n    Pointer<CellVariable<NDIM, double> > u_cc_var = u_var;\n    Pointer<SideVariable<NDIM, double> > u_sc_var = u_var;\n    if (u_cc_var)\n    {\n        Pointer<CellVariable<NDIM, double> > f_cc_var = d_f_var;\n        Pointer<CellVariable<NDIM, double> > n_cc_var = d_n_var;\n        getHierarchyMathOps()->curl(d_f_idx, f_cc_var, d_n_idx, n_cc_var, nullptr, data_time);\n    }\n    else if (u_sc_var)\n    {\n        Pointer<SideVariable<NDIM, double> > f_sc_var = d_f_var;\n        Pointer<SideVariable<NDIM, double> > n_sc_var = d_n_var;\n        getHierarchyMathOps()->curl(d_f_idx, f_sc_var, d_n_idx, n_sc_var, nullptr, data_time);\n    }\n    else\n    {\n        TBOX_ERROR(d_object_name << \"::spreadForce():\\n\"\n                                 << \"  unsupported velocity data centering\" << std::endl);\n    }\n    getVelocityHierarchyDataOps()->axpy(f_data_idx, 0.5, d_f_idx, f_data_idx);\n    return;\n} // spreadForce\n\nvoid\nGeneralizedIBMethod::initializePatchHierarchy(Pointer<PatchHierarchy<NDIM> > hierarchy,\n                                              Pointer<GriddingAlgorithm<NDIM> > gridding_alg,\n                                              int u_data_idx,\n                                              const std::vector<Pointer<CoarsenSchedule<NDIM> > >& u_synch_scheds,\n                                              const std::vector<Pointer<RefineSchedule<NDIM> > >& u_ghost_fill_scheds,\n                                              int integrator_step,\n                                              double init_data_time,\n                                              bool initial_time)\n{\n    // Initialize various Lagrangian data objects required by the conventional\n    // IB method.\n    IBMethod::initializePatchHierarchy(hierarchy,\n                                       gridding_alg,\n                                       u_data_idx,\n                                       u_synch_scheds,\n                                       u_ghost_fill_scheds,\n                                       integrator_step,\n                                       init_data_time,\n                                       initial_time);\n\n    // Initialize various Lagrangian data objects required by the gIB method.\n    if (initial_time)\n    {\n        // Lookup the range of hierarchy levels.\n        const int coarsest_ln = 0;\n        const int finest_ln = d_hierarchy->getFinestLevelNumber();\n\n        // Initialize the interpolated angular velocity field.\n        std::vector<Pointer<LData> > W_data(finest_ln + 1);\n        std::vector<Pointer<LData> > X_data(finest_ln + 1);\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n            X_data[ln] = d_l_data_manager->getLData(LDataManager::POSN_DATA_NAME, ln);\n            W_data[ln] = d_l_data_manager->getLData(\"W\", ln);\n        }\n        Pointer<Variable<NDIM> > u_var = d_ib_solver->getVelocityVariable();\n        Pointer<CellVariable<NDIM, double> > u_cc_var = u_var;\n        Pointer<SideVariable<NDIM, double> > u_sc_var = u_var;\n        if (u_cc_var)\n        {\n            Pointer<CellVariable<NDIM, double> > w_cc_var = d_w_var;\n            getHierarchyMathOps()->curl(d_w_idx, w_cc_var, u_data_idx, u_cc_var, nullptr, init_data_time);\n        }\n        else if (u_sc_var)\n        {\n            Pointer<SideVariable<NDIM, double> > w_sc_var = d_w_var;\n            getHierarchyMathOps()->curl(d_w_idx, w_sc_var, u_data_idx, u_sc_var, nullptr, init_data_time);\n        }\n        else\n        {\n            TBOX_ERROR(d_object_name << \"::initializePatchHierarchy():\\n\"\n                                     << \"  unsupported velocity data centering\" << std::endl);\n        }\n        getVelocityHierarchyDataOps()->scale(d_w_idx, 0.5, d_w_idx);\n        d_l_data_manager->interp(d_w_idx,\n                                 W_data,\n                                 X_data,\n                                 std::vector<Pointer<CoarsenSchedule<NDIM> > >(),\n                                 getGhostfillRefineSchedules(d_object_name + \"::w\"),\n                                 init_data_time);\n        resetAnchorPointValues(W_data, coarsest_ln, finest_ln);\n    }\n\n    // Indicate that the force-and-torque strategy needs to be re-initialized.\n    d_ib_force_and_torque_fcn_needs_init = true;\n    return;\n} // initializePatchHierarchy\n\nvoid\nGeneralizedIBMethod::initializeLevelData(Pointer<BasePatchHierarchy<NDIM> > hierarchy,\n                                         int level_number,\n                                         double init_data_time,\n                                         bool can_be_refined,\n                                         bool initial_time,\n                                         Pointer<BasePatchLevel<NDIM> > old_level,\n                                         bool allocate_data)\n{\n    IBMethod::initializeLevelData(\n        hierarchy, level_number, init_data_time, can_be_refined, initial_time, old_level, allocate_data);\n    if (initial_time && d_l_data_manager->levelContainsLagrangianData(level_number))\n    {\n        // 1. Allocate LData corresponding to the curvilinear mesh node\n        //    directors and angular velocities.\n        Pointer<LData> D_data = d_l_data_manager->createLData(\"D\",\n                                                              level_number,\n                                                              NDIM * NDIM,\n                                                              /*manage_data*/ true);\n        Pointer<LData> W_data = d_l_data_manager->createLData(\"W\", level_number, NDIM, /*manage_data*/ true);\n\n        // 2. Initialize the Lagrangian data.\n        static const int global_index_offset = 0;\n        static const int local_index_offset = 0;\n        d_l_initializer->initializeDirectorDataOnPatchLevel(global_index_offset,\n                                                            local_index_offset,\n                                                            D_data,\n                                                            hierarchy,\n                                                            level_number,\n                                                            init_data_time,\n                                                            can_be_refined,\n                                                            initial_time,\n                                                            d_l_data_manager);\n\n        // 3. Register data with any registered data writer.\n        if (d_silo_writer)\n        {\n            d_silo_writer->registerVariableData(\"D1\", D_data, 0, 3, level_number);\n            d_silo_writer->registerVariableData(\"D2\", D_data, 3, 3, level_number);\n            d_silo_writer->registerVariableData(\"D3\", D_data, 6, 3, level_number);\n            d_silo_writer->registerVariableData(\"W\", W_data, level_number);\n        }\n    }\n    return;\n} // initializeLevelData\n\nvoid\nGeneralizedIBMethod::putToDatabase(Pointer<Database> db)\n{\n    IBMethod::putToDatabase(db);\n    db->putInteger(\"GENERALIZED_IB_METHOD_VERSION\", GENERALIZED_IB_METHOD_VERSION);\n    return;\n} // putToDatabase\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\nGeneralizedIBMethod::resetLagrangianForceAndTorqueFunction(const double init_data_time, const bool initial_time)\n{\n    if (!d_ib_force_and_torque_fcn) return;\n    for (int ln = 0; ln <= d_hierarchy->getFinestLevelNumber(); ++ln)\n    {\n        if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue;\n        d_ib_force_and_torque_fcn->initializeLevelData(d_hierarchy, ln, init_data_time, initial_time, d_l_data_manager);\n    }\n    return;\n} // resetLagrangianForceAndTorqueFunction\n\nvoid\nGeneralizedIBMethod::getFromInput(Pointer<Database> /*db*/, bool /*is_from_restart*/)\n{\n    // intentionally blank\n    return;\n} // getFromInput\n\nvoid\nGeneralizedIBMethod::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(d_object_name << \":  Restart database corresponding to \" << d_object_name\n                                 << \" not found in restart file.\" << std::endl);\n    }\n    int ver = db->getInteger(\"GENERALIZED_IB_METHOD_VERSION\");\n    if (ver != GENERALIZED_IB_METHOD_VERSION)\n    {\n        TBOX_ERROR(d_object_name << \":  Restart file version different than class version.\" << std::endl);\n    }\n    return;\n} // getFromRestart\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n} // namespace IBAMR\n\n//////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "742efac192022517f3c9df93a5b19ef4e4b5ce88", "size": 30606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IB/GeneralizedIBMethod.cpp", "max_stars_repo_name": "hongk45/IBAMR", "max_stars_repo_head_hexsha": "698d419fc6688470a8b9400822ba893da9d07ae2", "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/IB/GeneralizedIBMethod.cpp", "max_issues_repo_name": "hongk45/IBAMR", "max_issues_repo_head_hexsha": "698d419fc6688470a8b9400822ba893da9d07ae2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-30T14:22:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-01T21:28:24.000Z", "max_forks_repo_path": "src/IB/GeneralizedIBMethod.cpp", "max_forks_repo_name": "hongk45/IBAMR", "max_forks_repo_head_hexsha": "698d419fc6688470a8b9400822ba893da9d07ae2", "max_forks_repo_licenses": ["BSD-3-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.2479784367, "max_line_length": 120, "alphanum_fraction": 0.5790694635, "num_tokens": 7462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04672495779643793, "lm_q1q2_score": 0.022997469869461634}}
{"text": "/*\n * Copyright (C) 2014, Computing Systems Laboratory (CSLab), NTUA.\n * Copyright (C) 2014, Vasileios Karakasis\n * All rights reserved.\n *\n * This file is distributed under the BSD License. See LICENSE.txt for details.\n */\n\n/**\n * \\file Xform.hpp\n * \\brief Matrix coordinate transformations\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_XFORM_HPP\n#define SPARSEX_INTERNALS_XFORM_HPP\n\n#include <sparsex/internals/Element.hpp>\n#include <sparsex/internals/Encodings.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/function.hpp>\n#include <cassert>\n\nnamespace bll = boost::lambda;\nusing namespace std;\n\nnamespace sparsex {\n  namespace csx {\n\n    // Coordinate transformation functions\n    // The variant with the pair argument is used for chaining transformations\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformHoriz(IndexType r, IndexType c,\n\t\t\t\t\t  IndexType nr_rows = 0,\n\t\t\t\t\t  IndexType nr_cols = 0)\n    {\n      // Identinty function\n      return make_pair(r, c);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformHoriz(pair<IndexType, IndexType> coord,\n\t\t\t\t\t  IndexType nr_rows = 0,\n\t\t\t\t\t  IndexType nr_cols = 0)\n    {\n      return XformHoriz<IndexType>(coord.first, coord.second);\n    }\n\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> RevXformHoriz(IndexType r, IndexType c,\n\t\t\t\t\t     IndexType nr_rows = 0,\n\t\t\t\t\t     IndexType nr_cols = 0)\n    {\n      // Identinty transformation\n      return make_pair(r, c);\n    }\n\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> RevXformHoriz(pair<IndexType, IndexType> coord,\n\t\t\t\t\t     IndexType nr_rows = 0,\n\t\t\t\t\t     IndexType nr_cols = 0)\n    {\n      return RevXformHoriz<IndexType>(coord.first, coord.second);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformVert(IndexType r, IndexType c,\n\t\t\t\t\t IndexType nr_rows = 0,\n\t\t\t\t\t IndexType nr_cols = 0)\n    {\n      return make_pair(c, r);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformVert(pair<IndexType, IndexType> coord,\n\t\t\t\t\t IndexType nr_rows = 0,\n\t\t\t\t\t IndexType nr_cols = 0)\n    {\n      return XformVert<IndexType>(coord.first, coord.second);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> RevXformVert(IndexType r, IndexType c,\n\t\t\t\t\t    IndexType nr_rows = 0,\n\t\t\t\t\t    IndexType nr_cols = 0)\n    {\n      return XformVert<IndexType>(r, c);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> RevXformVert(pair<IndexType, IndexType> coord,\n\t\t\t\t\t    IndexType nr_rows = 0,\n\t\t\t\t\t    IndexType nr_cols = 0)\n    {\n      return RevXformVert<IndexType>(coord.first, coord.second);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformDiag(IndexType r, IndexType c,\n\t\t\t\t\t IndexType nr_rows,\n\t\t\t\t\t IndexType nr_cols = 0)\n    {\n      assert(nr_rows + c - r > 0);\n      return make_pair(nr_rows + c - r, (c < r) ? c : r);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformDiag(pair<IndexType, IndexType> coord,\n\t\t\t\t\t IndexType nr_rows,\n\t\t\t\t\t IndexType nr_cols = 0)\n    {\n      return XformDiag<IndexType>(coord.first, coord.second, nr_rows);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> RevXformDiag(IndexType r, IndexType c,\n\t\t\t\t\t    IndexType nr_rows,\n\t\t\t\t\t    IndexType nr_cols = 0)\n    {\n      if (r < nr_rows)\n        return make_pair(nr_rows + c - r, c);\n      else\n        return make_pair(c, r + c - nr_rows);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> RevXformDiag(pair<IndexType, IndexType> coord,\n\t\t\t\t\t    IndexType nr_rows,\n\t\t\t\t\t    IndexType nr_cols = 0)\n    {\n      return RevXformDiag<IndexType>(coord.first, coord.second, nr_rows);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformAntiDiag(IndexType r, IndexType c,\n\t\t\t\t\t     IndexType nr_rows,\n\t\t\t\t\t     IndexType nr_cols)\n    {\n      IndexType new_r = r + c - 1;\n      return make_pair(new_r, (new_r <= nr_cols) ? r : nr_cols - c + 1);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> XformAntiDiag(pair<IndexType, IndexType> coord,\n\t\t\t\t\t     IndexType nr_rows,\n\t\t\t\t\t     IndexType nr_cols)\n    {\n      return XformAntiDiag<IndexType>(coord.first, coord.second,\n\t\t\t\t      nr_rows, nr_cols);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType> RevXformAntiDiag(IndexType r, IndexType c,\n\t\t\t\t\t\tIndexType nr_rows,\n\t\t\t\t\t\tIndexType nr_cols)\n    {\n      if (r <= nr_cols)\n        return make_pair(c, r - c + 1);\n      else\n        return make_pair(r + c - nr_cols, nr_cols - c + 1);\n    }\n\n    template<typename IndexType>\n    pair<IndexType, IndexType>\n    RevXformAntiDiag(pair<IndexType, IndexType> coord,\n\t\t     IndexType nr_rows,\n\t\t     IndexType nr_cols)\n    {\n      return RevXformAntiDiag<IndexType>(coord.first, coord.second,\n\t\t\t\t\t nr_rows, nr_cols);\n    }\n\n    template<typename IndexType, IndexType R>\n    pair<IndexType, IndexType> XformBlockRow(IndexType r, IndexType c,\n\t\t\t\t\t     IndexType nr_rows = 0,\n\t\t\t\t\t     IndexType nr_cols = 0)\n    {\n      return make_pair((r - 1) / R + 1,\n\t\t       (r - 1) % R + R*(c - 1) + 1);\n    }\n\n    template<typename IndexType, IndexType R>\n    pair<IndexType, IndexType> XformBlockRow(pair<IndexType, IndexType> coord,\n\t\t\t\t\t     IndexType nr_rows = 0,\n\t\t\t\t\t     IndexType nr_cols = 0)\n    {\n      return XformBlockRow<IndexType, R>(coord.first, coord.second);\n    }\n\n    template<typename IndexType, IndexType R>\n    pair<IndexType, IndexType> RevXformBlockRow(IndexType r, IndexType c,\n\t\t\t\t\t\tIndexType nr_rows = 0,\n\t\t\t\t\t\tIndexType nr_cols = 0)\n    {\n      return make_pair(R*(r - 1) + (c - 1) % R + 1,\n\t\t       (c - 1) / R + 1);\n    }\n\n    template<typename IndexType, IndexType R>\n    pair<IndexType, IndexType>\n    RevXformBlockRow(pair<IndexType, IndexType> coord,\n\t\t     IndexType nr_rows = 0,\n\t\t     IndexType nr_cols = 0)\n    {   \n      return RevXformBlockRow<IndexType, R>(coord.first, coord.second);\n    }\n\n    template<typename IndexType, IndexType C>\n    pair<IndexType, IndexType> XformBlockCol(IndexType r, IndexType c,\n\t\t\t\t\t     IndexType nr_rows = 0,\n\t\t\t\t\t     IndexType nr_cols = 0)\n    {\n      pair<IndexType, IndexType> vert = XformVert<IndexType>(r, c);\n      return XformBlockRow<IndexType, C>(vert.first, vert.second);\n    }\n\n    template<typename IndexType, IndexType C>\n    pair<IndexType, IndexType> XformBlockCol(pair<IndexType, IndexType> coord,\n\t\t\t\t\t     IndexType nr_rows = 0,\n\t\t\t\t\t     IndexType nr_cols = 0)\n    {\n      return XformBlockCol<IndexType, C>(coord.first, coord.second);\n    }\n\n    template<typename IndexType, IndexType C>\n    pair<IndexType, IndexType> RevXformBlockCol(IndexType r, IndexType c,\n\t\t\t\t\t\tIndexType nr_rows = 0,\n\t\t\t\t\t\tIndexType nr_cols = 0)\n    {\n      pair<IndexType, IndexType> rblock = RevXformBlockRow<IndexType, C>(r, c);\n      return RevXformVert<IndexType>(rblock.first, rblock.second);\n    }\n\n    template<typename IndexType, IndexType C>\n    pair<IndexType, IndexType>\n    RevXformBlockCol(pair<IndexType, IndexType> coord,\n\t\t     IndexType nr_rows = 0,\n\t\t     IndexType nr_cols = 0)\n    {\n      return RevXformBlockCol<IndexType, C>(coord.first, coord.second);\n    }\n\n    // Transform function type\n    template<typename IndexType>\n    struct TransformFn {\n      typedef boost::function<\n        pair<IndexType, IndexType>\n        (pair<IndexType, IndexType>, IndexType, IndexType)> type;\n    };\n\n    template<typename IndexType>\n    typename TransformFn<IndexType>::type GetXformFnFromHoriz(Encoding::Type to)\n    {\n      typename TransformFn<IndexType>::type ret;\n\n      switch (to) {\n      case Encoding::Horizontal:\n        ret = bll::bind(XformHoriz<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::Vertical:\n        ret = bll::bind(XformVert<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::Diagonal:\n        ret = bll::bind(XformDiag<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::AntiDiagonal:\n        ret = bll::bind(XformAntiDiag<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow1:\n        ret = bll::bind(XformBlockRow<IndexType, 1>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow2:\n        ret = bll::bind(XformBlockRow<IndexType, 2>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow3:\n        ret = bll::bind(XformBlockRow<IndexType, 3>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow4:\n        ret = bll::bind(XformBlockRow<IndexType, 4>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow5:\n        ret = bll::bind(XformBlockRow<IndexType, 5>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow6:\n        ret = bll::bind(XformBlockRow<IndexType, 6>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow7:\n        ret = bll::bind(XformBlockRow<IndexType, 7>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow8:\n        ret = bll::bind(XformBlockRow<IndexType, 8>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol1:\n        ret = bll::bind(XformBlockCol<IndexType, 1>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol2:\n        ret = bll::bind(XformBlockCol<IndexType, 2>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol3:\n        ret = bll::bind(XformBlockCol<IndexType, 3>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol4:\n        ret = bll::bind(XformBlockCol<IndexType, 4>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol5:\n        ret = bll::bind(XformBlockCol<IndexType, 5>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol6:\n        ret = bll::bind(XformBlockCol<IndexType, 6>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol7:\n        ret = bll::bind(XformBlockCol<IndexType, 7>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol8:\n        ret = bll::bind(XformBlockCol<IndexType, 8>, bll::_1, bll::_2, bll::_3);\n        break;\n      default:\n        assert(false && \"[BUG] `to' is not handled\");\n      }\n\n      return ret;\n    }\n\n    template<typename IndexType>\n    typename TransformFn<IndexType>::type GetXformFnToHoriz(Encoding::Type from)\n    {\n      typename TransformFn<IndexType>::type ret;\n\n      switch (from) {\n      case Encoding::Horizontal:\n        ret = bll::bind(RevXformHoriz<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::Vertical:\n        ret = bll::bind(RevXformVert<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::Diagonal:\n        ret = bll::bind(RevXformDiag<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::AntiDiagonal:\n        ret = bll::bind(RevXformAntiDiag<IndexType>, bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow1:\n        ret = bll::bind(RevXformBlockRow<IndexType, 1>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow2:\n        ret = bll::bind(RevXformBlockRow<IndexType, 2>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow3:\n        ret = bll::bind(RevXformBlockRow<IndexType, 3>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow4:\n        ret = bll::bind(RevXformBlockRow<IndexType, 4>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow5:\n        ret = bll::bind(RevXformBlockRow<IndexType, 5>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow6:\n        ret = bll::bind(RevXformBlockRow<IndexType, 6>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow7:\n        ret = bll::bind(RevXformBlockRow<IndexType, 7>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockRow8:\n        ret = bll::bind(RevXformBlockRow<IndexType, 8>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol1:\n        ret = bll::bind(RevXformBlockCol<IndexType, 1>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol2:\n        ret = bll::bind(RevXformBlockCol<IndexType, 2>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol3:\n        ret = bll::bind(RevXformBlockCol<IndexType, 3>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol4:\n        ret = bll::bind(RevXformBlockCol<IndexType, 4>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol5:\n        ret = bll::bind(RevXformBlockCol<IndexType, 5>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol6:\n        ret = bll::bind(RevXformBlockCol<IndexType, 6>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol7:\n        ret = bll::bind(RevXformBlockCol<IndexType, 7>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      case Encoding::BlockCol8:\n        ret = bll::bind(RevXformBlockCol<IndexType, 8>,\n                        bll::_1, bll::_2, bll::_3);\n        break;\n      default:\n        assert(false && \"[BUG] `from' is not handled\");\n      }\n\n      return ret;\n    }\n\n    template<typename IndexType>\n    typename TransformFn<IndexType>::type GetXformFn(Encoding::Type from,\n\t\t\t\t\t\t     Encoding::Type to)\n    {\n      typename TransformFn<IndexType>::type ret;\n\n      if (from == to)\n        ret = bll::bind(XformHoriz<IndexType>, bll::_1, bll::_2, bll::_3);\n      else if (from == Encoding::Horizontal)\n        ret = GetXformFnFromHoriz<IndexType>(to);\n      else if (to == Encoding::Horizontal)\n        ret = GetXformFnToHoriz<IndexType>(from);\n      else {\n        typename TransformFn<IndexType>::type from_horiz =\n\t  GetXformFnFromHoriz<IndexType>(to);\n        typename TransformFn<IndexType>::type to_horiz =\n\t  GetXformFnToHoriz<IndexType>(from);\n        ret = bll::bind(from_horiz,\n                        bll::bind(to_horiz, bll::_1, bll::_2, bll::_3),\n                        bll::_2, bll::_3);\n      }\n\n      return ret;\n    }\n\n  }   // end of namespace csx\n}   // end of namespace sparsex\n\n#endif  // SPARSEX_INTERNALS_XFORM_HPP\n", "meta": {"hexsha": "dd1cf1eb19aafe76b1b5124045e4049a0117b0c7", "size": 14665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sparsex/internals/Xform.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/Xform.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/Xform.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": 32.6614699332, "max_line_length": 80, "alphanum_fraction": 0.6066825776, "num_tokens": 4277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.053403332059648596, "lm_q1q2_score": 0.022971301691107185}}
{"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 _Q, array_tf _q,\n                        array_tf _R, array_tf _r,\n                        array_tf _P, array_tf _p,\n                        array_tf _F, array_tf _G,\n                        array_tf _T, array_tf _U,\n                        array_tf _V, array_tf _X,\n                        array_tf _Y, array_tf _Z,\n                        double lmbda, int reg,\n                        int nb_bdim, int nb_udim, int nb_steps) {\n\n    // inputs\n    cube Q = array_to_cube(_Q);\n    mat q = array_to_mat(_q);\n\n    cube R = array_to_cube(_R);\n    mat r = array_to_mat(_r);\n\n    cube P = array_to_cube(_P);\n    mat p = array_to_mat(_p);\n\n    cube F = array_to_cube(_F);\n    cube G = array_to_cube(_G);\n\n    cube T = array_to_cube(_T);\n    cube U = array_to_cube(_U);\n    cube V = array_to_cube(_V);\n\n    cube X = array_to_cube(_X);\n    cube Y = array_to_cube(_Y);\n    cube Z = array_to_cube(_Z);\n\n    // outputs\n    cube C(nb_bdim, nb_bdim, nb_steps);\n    mat c(nb_bdim, nb_steps);\n\n    cube D(nb_udim, nb_udim, nb_steps);\n    mat d(nb_udim, nb_steps);\n\n    cube E(nb_udim, nb_bdim, nb_steps);\n    mat e(nb_bdim * nb_bdim, nb_steps);\n\n    cube Ereg(nb_udim, nb_bdim, nb_steps);\n    cube Dreg(nb_udim, nb_udim, nb_steps);\n    cube Dinv(nb_udim, nb_udim, nb_steps);\n\n    cube S(nb_bdim, nb_bdim, nb_steps + 1);\n    mat s(nb_bdim, nb_steps + 1);\n    mat tau(nb_bdim * nb_bdim, nb_steps + 1);\n\n    vec dS(2);\n\n    cube Sreg(nb_bdim, nb_bdim, nb_steps + 1);\n\n    cube K(nb_udim, nb_bdim, nb_steps);\n    mat kff(nb_udim, nb_steps);\n\n    int _diverge = 0;\n\n    // init last time step\n    S.slice(nb_steps) = Q.slice(nb_steps);\n    s.col(nb_steps) = q.col(nb_steps);\n    tau.col(nb_steps) = p.col(nb_steps);\n\n\tfor(int i = nb_steps - 1; i>= 0; --i)\n\t{\n        C.slice(i) = Q.slice(i) + F.slice(i).t() * S.slice(i+1) * F.slice(i);\n        D.slice(i) = R.slice(i) + G.slice(i).t() * S.slice(i+1) * G.slice(i);\n        E.slice(i) = (P.slice(i) + F.slice(i).t() * S.slice(i+1) * G.slice(i)).t();\n\n        c.col(i) = q.col(i) + F.slice(i).t() * s.col(i+1) + T.slice(i).t() * tau.col(i+1)\n                   + 0.5 * X.slice(i).t() * vectorise(S.slice(i+1));\n\n        d.col(i) = r.col(i) + G.slice(i).t() * s.col(i+1) + V.slice(i).t() * tau.col(i+1)\n                   + 0.5 * Z.slice(i).t() * vectorise(S.slice(i+1));\n\n        e.col(i) = p.col(i) + U.slice(i).t() * tau.col(i) + 0.5 * Y.slice(i).t() * vectorise(S.slice(i+1));\n\n        Sreg.slice(i+1) = S.slice(i+1);\n        if (reg==2)\n            Sreg.slice(i+1) += lmbda * eye(nb_bdim, nb_bdim);\n\n        Ereg.slice(i) = (P.slice(i) + F.slice(i).t() * Sreg.slice(i+1) * G.slice(i)).t();\n\n        Dreg.slice(i) = R.slice(i) + G.slice(i).t() * Sreg.slice(i+1) * G.slice(i);\n        if (reg==1)\n            Dreg.slice(i) += lmbda * eye(nb_udim, nb_udim);\n\n        if (!(Dreg.slice(i)).is_sympd()) {\n            _diverge = i;\n            break;\n        }\n\n        Dinv.slice(i) = inv(Dreg.slice(i));\n        K.slice(i) = - Dinv.slice(i) * Ereg.slice(i);\n        kff.col(i) = - Dinv.slice(i) * d.col(i);\n\n        dS += join_vert(kff.col(i).t() * d.col(i), 0.5 * kff.col(i).t() * D.slice(i) * kff.col(i));\n\n        tau.col(i) = e.col(i);\n\n        s.col(i) = c.col(i) + K.slice(i).t() * D.slice(i) * kff.col(i) +\n                   K.slice(i).t() * d.col(i) + E.slice(i).t() * kff.col(i);\n\n        S.slice(i) = C.slice(i) + K.slice(i).t() * D.slice(i) * K.slice(i) +\n                     K.slice(i).t() * E.slice(i) + E.slice(i).t() * K.slice(i);\n        S.slice(i) = 0.5 * (S.slice(i) + S.slice(i).t());\n\t}\n\n    // transform outputs to numpy\n    array_tf _S = cube_to_array(S);\n    array_tf _s = mat_to_array(s);\n    array_tf _tau = mat_to_array(tau);\n\n    array_tf _dS = vec_to_array(dS);\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(_S, _s, _tau,\n                                       _dS, _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": "ff68797e94e5aaf1738f96c250ae41b9416c67cd", "size": 5750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trajopt/bspilqr/src/util.cpp", "max_stars_repo_name": "JoeMWatson/trajopt", "max_stars_repo_head_hexsha": "8b98718721e0c373cd7dc01a35f42447c1134713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-17T08:42:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T08:42:17.000Z", "max_issues_repo_path": "trajopt/bspilqr/src/util.cpp", "max_issues_repo_name": "JoeMWatson/trajopt", "max_issues_repo_head_hexsha": "8b98718721e0c373cd7dc01a35f42447c1134713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trajopt/bspilqr/src/util.cpp", "max_forks_repo_name": "JoeMWatson/trajopt", "max_forks_repo_head_hexsha": "8b98718721e0c373cd7dc01a35f42447c1134713", "max_forks_repo_licenses": ["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.2511848341, "max_line_length": 107, "alphanum_fraction": 0.5645217391, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.048136771116634815, "lm_q1q2_score": 0.022941005582097853}}
{"text": "/**\n * @file onepass_plus.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 Licence\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_ONEPASS_PLUS_HPP\n#define BOOST_ONEPASS_PLUS_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/onepass_plus_impl.hpp>\n\n#include <cassert>\n#include <iostream>\n#include <memory>\n#include <queue>\n#include <unordered_map>\n#include <vector>\n\n/**\n * An Alternative-Routing library for Boost.Graph\n */\nnamespace arlib {\n/**\n * An implementation of OnePass+ k-shortest path with limited overlap for\n * Boost::Graph.\n *\n * This implementation refers to the following publication:\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 *\n */\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename Terminator = arlib::always_continue,\n          typename Vertex = vertex_of_t<Graph>>\nvoid onepass_plus(const Graph &G, WeightMap weight,\n                  MultiPredecessorMap &predecessors, Vertex s, Vertex t, int k,\n                  double theta, Terminator &&terminator = Terminator{}) {\n  using namespace boost;\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n  using Length = typename boost::property_traits<WeightMap>::value_type;\n\n  BOOST_CONCEPT_ASSERT((VertexAndEdgeListGraphConcept<Graph>));\n  BOOST_CONCEPT_ASSERT((LvaluePropertyMapConcept<WeightMap, Edge>));\n  BOOST_CONCEPT_ASSERT(\n      (ReadablePropertyMapConcept<MultiPredecessorMap, Vertex>));\n\n  auto resPathsEdges = std::vector<std::vector<Edge>>{};\n\n  // resEdges keeps track of the edges that make the paths in resPaths and which\n  // path includes it.\n  using resPathIndex = typename decltype(resPathsEdges)::size_type;\n  auto resEdges =\n      std::unordered_map<Edge, std::vector<resPathIndex>, boost::hash<Edge>>{};\n\n  // Min-priority queue\n  using Label = details::OnePassLabel<Graph, Length>;\n  using LabelPtr = std::unique_ptr<Label>;\n  auto Q =\n      std::priority_queue<Label *, std::vector<Label *>,\n                          details::OnePassPlusASComparator<Graph, Length>>{};\n  auto created_labels = std::vector<LabelPtr>{};\n\n  // Skyline for dominance checkind (Lemma 2)\n  auto skyline = details::SkylineContainer<Graph, Length>{};\n\n  // Compute lower bounds for AStar\n  auto lower_bounds = details::distance_from_target<Length>(G, t);\n\n  // Compute shortest path from s to t\n  auto sp_path = details::compute_shortest_path(G, weight, s, t);\n  if (!sp_path) {\n    auto oss = std::ostringstream{};\n    oss << \"Vertex \" << t << \" is unreachable from \" << s;\n    throw details::target_not_found{oss.str()};\n  }\n\n  // P_LO <-- {shortest path p_0(s, t)};\n  resPathsEdges.push_back(*sp_path);\n  resPathIndex paths_count = 1;\n\n  // If we need the shortest path only\n  if (k == 1) {\n    details::fill_multi_predecessor(resPathsEdges.begin(), resPathsEdges.end(),\n                                    G, predecessors);\n    return;\n  }\n\n  // For each edge in the candidate path, we check if it's already in any of the\n  // resPaths. If not, we add it to resEdges. If yes, we keep track of which\n  // path includes it.\n  details::update_res_edges(*sp_path, resEdges, paths_count);\n\n  // Initialize min-priority queue Q with <s, empty_set>\n  auto init_label =\n      std::make_unique<Label>(s, 0, lower_bounds[s], k, paths_count - 1);\n  Q.push(init_label.get());\n  created_labels.push_back(std::move(init_label));\n\n  // While Q is not empty\n  while (!Q.empty()) {\n    // The remainder code is the hot part of the algorithm. So we check here\n    // if the algorithm should terminate\n    if (terminator.should_stop()) {\n      throw terminator_stop_error{\n          \"OnePass+ terminated before completing due to a Terminator. Please \"\n          \"discard partial output.\"};\n    }\n\n    // Current path\n    auto label = Q.top();\n    Q.pop();\n\n    // Perform lazy update of the similairty vector of 'label', since new paths\n    // might have been added to P_LO from the time this 'label' was pushed into\n    // priority queue.\n    if (label->is_outdated(paths_count - 1)) {\n      bool below_sim_threshold = details::update_label_similarity(\n          *label, G, resEdges, resPathsEdges, weight, theta, paths_count);\n\n      label->set_last_check(paths_count - 1); // Update last check time step\n      if (!below_sim_threshold) {\n        continue; // Skip candidate path\n      }\n    }\n\n    // If we found the target node\n    if (label->get_node() == t) {\n      // Build the new k-th shortest path\n      resPathsEdges.push_back(label->get_path(G));\n\n      auto &tmpPath = resPathsEdges.back();\n      ++paths_count;\n\n      if (static_cast<int>(paths_count) == k) { // we found k paths. End.\n        // Add computed alternatives to resPaths\n        details::fill_multi_predecessor(resPathsEdges.begin(),\n                                        resPathsEdges.end(), G, predecessors);\n        break;\n      }\n\n      // For each edge in the candidate path see if it's already in any of the\n      // P_LO paths. If not, add it to the resEdges. If so, keep track of which\n      // path includes it\n      details::update_res_edges(tmpPath, resEdges, paths_count);\n\n    } else { // Expand Search\n      if (skyline.dominates(*label)) {\n        continue; // Prune path by Lemma 2\n      }\n\n      skyline.insert(label);\n      auto node_n = label->get_node();\n      // For each outgoing edge\n      for (auto adj_it = adjacent_vertices(node_n, G).first;\n           adj_it != adjacent_vertices(node_n, G).second; ++adj_it) {\n        // Expand path\n        auto c_edge = edge(node_n, *adj_it, G).first;\n        auto c_label =\n            details::expand_path(label, *adj_it, lower_bounds[*adj_it],\n                                 weight[c_edge], paths_count - 1);\n\n        // Check for acyclicity\n        bool acyclic = label->is_path_acyclic(*adj_it);\n\n        if (acyclic) {\n          auto c_similarity_map = label->get_similarity_map();\n\n          // Check Lemma 1 for similarity thresholding\n          bool below_sim_threshold = details::is_below_sim_threshold(\n              c_edge, c_similarity_map, theta, resEdges, resPathsEdges, weight);\n\n          if (below_sim_threshold) {\n            c_label->set_similarities(std::begin(c_similarity_map),\n                                      std::end(c_similarity_map));\n            Q.push(c_label.get());\n            created_labels.push_back(std::move(c_label));\n          }\n        }\n      }\n    }\n  }\n\n  if (static_cast<int>(paths_count) != k) {\n    // Add computed alternatives to resPaths\n    details::fill_multi_predecessor(resPathsEdges.begin(), resPathsEdges.end(),\n                                    G, predecessors);\n  }\n}\n\n/**\n * An implementation of OnePass+ 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 onepass_plus(const Graph &G, WeightMap weight,\n *                   MultiPredecessorMap &predecessors, Vertex s, Vertex t, int\n *                   k, double theta)\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>>\nvoid onepass_plus(const PropertyGraph &G, MultiPredecessorMap &predecessors,\n                  Vertex s, Vertex t, int k, double theta,\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  onepass_plus(G, weight, predecessors, s, t, k, theta,\n               std::forward<Terminator>(terminator));\n}\n} // namespace arlib\n\n#endif", "meta": {"hexsha": "e2b4ef07e20372d7da6b0b1f009a91406fdc542a", "size": 11375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/onepass_plus.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/onepass_plus.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/onepass_plus.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": 39.4965277778, "max_line_length": 80, "alphanum_fraction": 0.6764835165, "num_tokens": 2689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.0488577737749038, "lm_q1q2_score": 0.02290406638350041}}
{"text": "/*\n * morpho.cxx\n *\n *  Created on: Aug 21, 2013\n *      Author: Thomas Walter\n */\n\n\n// define PY_ARRAY_UNIQUE_SYMBOL (required by the numpy C-API)\n#define PY_ARRAY_UNIQUE_SYMBOL vigranumpymorpho_PyArray_API\n\n// include the vigranumpy C++ API\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/list.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n\n// specific includes\n#include <vigra/morpho_basic.hxx>\n#include <vigra/morpho_utilities.hxx>\n#include <vigra/morpho_geodesy.hxx>\n#include <vigra/morpho_criteria.hxx>\n#include <vigra/morpho_watershed.hxx>\n#include <vigra/morpho_dynamic.hxx>\n\n// implementation of your wrapper functions and classes\n//template <class PixelType>\n//NumpyAnyArray\n//pythonConvolveImage(NumpyArray<3, Multiband<PixelType> > image,\n//                    TwoDKernel const & kernel,\n//                    NumpyArray<3, Multiband<PixelType> > res = python::object())\n//{\n//    res.reshapeIfEmpty(image.taggedShape(),\n//            \"convolve(): Output array has wrong shape.\");\n//\n//    {\n//        PyAllowThreads _pythread;\n//        for(int k=0;k<image.shape(2);++k)\n//        {\n//            MultiArrayView<2, PixelType, StridedArrayTag> bimage = image.bindOuter(k);\n//            MultiArrayView<2, PixelType, StridedArrayTag> bres = res.bindOuter(k);\n//            convolveImage(srcImageRange(bimage), destImage(bres),\n//                          kernel2d(kernel));\n//        }\n//    }\n//    return res;\n//}\n\nnamespace python = boost::python;\n\nnamespace vigra\n{\n\n//template<class T>\n//void pythonInitExplicitlyKernel1D(Kernel1D<T> &k, int left, int right, NumpyArray<1,T> contents)\n//{\n//    vigra_precondition(contents.size() == 1 || right-left+1 == contents.shape(0),\n//              \"Kernel1D::initExplicitly(): 'contents' must contain as many elements as the kernel (or just one element).\");\n//\n//    k.initExplicitly(left,right);\n//    for(int i=left; i<=right; ++i)\n//    {\n//        k[i] = (contents.size() == 1)\n//                     ? contents(0)\n//                     : contents(i-left);\n//    }\n//}\n\n//NumpyArray<2, Singleband<PixelType> > image,\n\nclass structuringElement2D_Conv: public morpho::structuringElement2D\n{\n    public:\n        structuringElement2D_Conv(): structuringElement2D() {}\n        structuringElement2D_Conv(boost::python::list a, int s=1) {\n            size = s;\n            boost::python::ssize_t len = boost::python::len(a);\n            for(int i=0; i<len;i++){\n                Diff2D from_python((int)boost::python::extract<int>(a[i][0]),\n                                   (int)boost::python::extract<int>(a[i][1]));\n                support.push_back(from_python);\n\n            }\n            CalculateExtension();\n        }\n};\n\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoReconstructionByDilation(NumpyArray<2, Singleband<PixelType> > marker,\n                                     NumpyArray<2, Singleband<PixelType> > mask,\n                                     int neighborhood_graph\n                                   )\n{\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(marker.width(), marker.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoReconstructionByDilation(destImageRange(marker), srcImage(mask), nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoReconstructionByDilation(destImageRange(marker), srcImage(mask), nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoOpeningByReconstruction(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return marker;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoReconstructionByErosion(NumpyArray<2, Singleband<PixelType> > marker,\n                                     NumpyArray<2, Singleband<PixelType> > mask,\n                                     int neighborhood_graph\n                                   )\n{\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(marker.width(), marker.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoReconstructionByErosion(destImageRange(marker), srcImage(mask), nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoReconstructionByErosion(destImageRange(marker), srcImage(mask), nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoOpeningByReconstruction(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return marker;\n}\n\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoOpeningByReconstruction(NumpyArray<2, Singleband<PixelType> > image,\n                                    structuringElement2D_Conv se,\n                                    int neighborhood_graph,\n                                    NumpyArray<2, Singleband<PixelType> > res\n                                   )\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoOpeningByReconstruction(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoOpeningByReconstruction(image, res, se, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoOpeningByReconstruction(image, res, se, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoOpeningByReconstruction(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            //std::cout << \"This neighborhood is not defined.\" << std::endl;\n            break;\n        }\n    };\n\n    //morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n    //morpho::morphoOpeningByReconstruction(image, res, se, nb);\n\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoDiameterOpening(NumpyArray<2, Singleband<PixelType> > image,\n                            int diameter,\n                            int neighborhood_graph,\n                            NumpyArray<2, Singleband<PixelType> > res\n                            )\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoDiameterOpening(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoDiameterOpening(image, res, diameter, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoDiameterOpening(image, res, diameter, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoDiameterOpening(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType, class LabelType>\nNumpyAnyArray\npythonMorphoWatershed(NumpyArray<2, Singleband<PixelType> > image,\n                      int neighborhood_graph,\n                      NumpyArray<2, Singleband<LabelType> > res)\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoWatershed(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoWatershed(image, res, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoWatershed(image, res, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoWatershed(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\n\ntemplate <class PixelType, class LabelType>\nNumpyAnyArray\npythonMorphoSelectiveWatershed(NumpyArray<2, Singleband<PixelType> > image,\n                               int dyn_thresh,\n                               int neighborhood_graph,\n                               NumpyArray<2, Singleband<LabelType> > res)\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoSelectiveWatershed(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoSelectiveWatershed(image, res, dyn_thresh, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoSelectiveWatershed(image, res, dyn_thresh, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoSelectiveWatershed(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoDynMinima(NumpyArray<2, Singleband<PixelType> > image,\n                      int neighborhood_graph,\n                      NumpyArray<2, Singleband<PixelType> > res)\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n                       \"pythonMorphoDynMinima(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n//\n//    def(\"morphoDynMinima\", registerConverters(&pythonMorphoDynMinima<UInt8>),\n//        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n//        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n//        \"(default is 8 neighborhood) as inputs. \"\n//        \"The function calculates the morphological dynamics for each minimum\"\n//        \"and returns an image which is only non-zero on the local minima and \");\n//    def(\"morphoDynMinima\", registerConverters(&pythonMorphoDynMinima<UInt16>),\n//        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n//        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n//        \"(default is 8 neighborhood) as inputs. \"\n//        \"The function calculates the morphological dynamics for each minimum\"\n//        \"and returns an image which is only non-zero on the local minima and \");\n\n    //std::vector<PixelType> dynamics;\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoDynMinima(image, res, nb);\n            //vigra::NumpyArray<2, vigra::Singleband<unsigned short>, vigra::StridedArrayTag>::value_type\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            //morpho::morphoDynMinima(srcImageRange(image), destImageRange(res), nb);\n            morpho::morphoDynMinima(image, res, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoDynMinima(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType, class LabelType>\nNumpyAnyArray\npythonMorphoBifurcationPoints(NumpyArray<2, Singleband<PixelType> > image,\n                              int neighborhood_graph,\n                              NumpyArray<2, Singleband<LabelType> > res)\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n                       \"morphoBifurcationPoints(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoBifurcationPoints(image, res, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoBifurcationPoints(image, res, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoBifurcationPoints(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType, class MarkerType, class LabelType>\nNumpyAnyArray\npythonMorphoConstrainedWatershed(NumpyArray<2, Singleband<PixelType> > image,\n                                 NumpyArray<2, Singleband<MarkerType> > marker_image,\n                                 int neighborhood_graph,\n                                 NumpyArray<2, Singleband<LabelType> > res)\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoConstrainedWatershed(): Output array has wrong shape.\");\n\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoConstrainedWatershed(image, marker_image, res, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoConstrainedWatershed(image, marker_image, res, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoConstrainedWatershed(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoDiameterClosing(NumpyArray<2, Singleband<PixelType> > image,\n                            int diameter,\n                            int neighborhood_graph,\n                            NumpyArray<2, Singleband<PixelType> > res\n                            )\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoDiameterClosing(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoDiameterClosing(image, res, diameter, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoDiameterClosing(image, res, diameter, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoDiameterClosing(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoAreaOpening(NumpyArray<2, Singleband<PixelType> > image,\n                                    int area,\n                                    int neighborhood_graph,\n                                    NumpyArray<2, Singleband<PixelType> > res\n                                   )\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoAreaOpening(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoAreaOpening(image, res, area, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoAreaOpening(image, res, area, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoAreaOpening(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            //std::cout << \"This neighborhood is not defined.\" << std::endl;\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoAreaClosing(NumpyArray<2, Singleband<PixelType> > image,\n                                    int area,\n                                    int neighborhood_graph,\n                                    NumpyArray<2, Singleband<PixelType> > res\n                                   )\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoAreaClosing(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoAreaClosing(image, res, area, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoAreaClosing(image, res, area, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoAreaClosing(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            //std::cout << \"This neighborhood is not defined.\" << std::endl;\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoClosingByReconstruction(NumpyArray<2, Singleband<PixelType> > image,\n                                    structuringElement2D_Conv se,\n                                    int neighborhood_graph,\n                                    NumpyArray<2, Singleband<PixelType> > res\n                                   )\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoClosingByReconstruction(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoClosingByReconstruction(image, res, se, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoClosingByReconstruction(image, res, se, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoClosingByReconstruction(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\n\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoOpeningByDynamics(NumpyArray<2, Singleband<PixelType> > image,\n                              int h,\n                              int neighborhood_graph,\n                              NumpyArray<2, Singleband<PixelType> > res\n)\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoClosingByReconstruction(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoOpeningByDynamics(image, res, h, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoOpeningByDynamics(image, res, h, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoOpeningByDynamics(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoClosingByDynamics(NumpyArray<2, Singleband<PixelType> > image,\n                              int h,\n                              int neighborhood_graph,\n                              NumpyArray<2, Singleband<PixelType> > res)\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoClosingByReconstruction(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    Diff2D image_size = Diff2D(image.width(), image.height());\n\n    switch(neighborhood_graph) {\n        case 8:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER8, image_size);\n            morpho::morphoClosingByDynamics(image, res, h, nb);\n            break;\n        }\n        case 4:\n        {\n            morpho::neighborhood2D nb(morpho::WITHOUTCENTER4, image_size);\n            morpho::morphoClosingByDynamics(image, res, h, nb);\n            break;\n        }\n        default:\n        {\n            vigra_precondition(false,\n                         \"pythonMorphoClosingByDynamics(): Unknown neighborhood graph.\\n\"\n                         \"This function is only defined for 4- and 8-neighborhoods.\");\n            break;\n        }\n    };\n\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoDilation(NumpyArray<2, Singleband<PixelType> > image,\n                    structuringElement2D_Conv se,\n                    NumpyArray<2, Singleband<PixelType> > res // = python::object(),\n                    )\n{\n\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoErosion(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    morpho::morphoDilation(srcImageRange(image), destImageRange(res), se);\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoOpening(NumpyArray<2, Singleband<PixelType> > image,\n                    structuringElement2D_Conv se,\n                    NumpyArray<2, Singleband<PixelType> > res // = python::object(),\n                    )\n{\n\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoErosion(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    morpho::morphoOpening(srcImageRange(image), destImageRange(res), se);\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoClosing(NumpyArray<2, Singleband<PixelType> > image,\n                    structuringElement2D_Conv se,\n                    NumpyArray<2, Singleband<PixelType> > res // = python::object(),\n                    )\n{\n\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoErosion(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    morpho::morphoClosing(srcImageRange(image), destImageRange(res), se);\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoInternalGradient(NumpyArray<2, Singleband<PixelType> > image,\n                             structuringElement2D_Conv se,\n                             NumpyArray<2, Singleband<PixelType> > res // = python::object(),\n)\n{\n\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoErosion(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    morpho::morphoInternalGradient(srcImageRange(image), destImageRange(res), se);\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoExternalGradient(NumpyArray<2, Singleband<PixelType> > image,\n                             structuringElement2D_Conv se,\n                    NumpyArray<2, Singleband<PixelType> > res // = python::object(),\n                    )\n{\n\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoErosion(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    morpho::morphoExternalGradient(srcImageRange(image), destImageRange(res), se);\n    return res;\n}\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoGradient(NumpyArray<2, Singleband<PixelType> > image,\n                     structuringElement2D_Conv se,\n                     NumpyArray<2, Singleband<PixelType> > res\n                    )\n{\n\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoErosion(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    morpho::morphoGradient(srcImageRange(image), destImageRange(res), se);\n    return res;\n}\n\n\ntemplate <class PixelType>\nNumpyAnyArray\npythonMorphoErosion(NumpyArray<2, Singleband<PixelType> > image,\n                    structuringElement2D_Conv se,\n                    NumpyArray<2, Singleband<PixelType> > res // = python::object(),\n                    )\n{\n    res.reshapeIfEmpty(image.taggedShape(),\n            \"morphoErosion(): Output array has wrong shape.\");\n    PyAllowThreads _pythread;\n\n    morpho::morphoErosion(srcImageRange(image), destImageRange(res), se);\n    return res;\n}\n\n//struct Diff2Dlist_from_python_pointlist\n//{\n//\n//  // Determine if obj_ptr can be converted in a QString\n//  static void* convertible(PyObject* obj_ptr)\n//    {\n//      //if (!PyString_Check(obj_ptr)) return 0;\n//      //return obj_ptr;\n//    }\n//\n//  // Convert obj_ptr into a list of points\n//   static void construct(\n//     PyObject* obj_ptr,\n//     boost::python::converter::rvalue_from_python_stage1_data* data)\n//     {\n//       // Extract the character data from the python string\n//       const char* value = PyString_AsString(obj_ptr);\n//\n//       // Verify that obj_ptr is a string (should be ensured by convertible())\n//       assert(value);\n//\n//       // Grab pointer to memory into which to construct the new QString\n//       void* storage = (\n//         (boost::python::converter::rvalue_from_python_storage<QString>*)\n//         data)->storage.bytes;\n//\n//       // in-place construct the new QString using the character data\n//       // extraced from the python object\n//       new (storage) QString(value);\n//\n//       // Stash the memory chunk pointer for later use by boost.python\n//       data->convertible = storage;\n//     }\n//\n//};\n\n\n//class VecTest {\n//\n//    protected:\n//        std::vector<int> myvec;\n//\n//    public:\n//        //VecTest(std::vector<int> a): myvec(a) {}\n//        VecTest(boost::python::list a)\n//        {\n//\n//            boost::python::ssize_t len = boost::python::len(a);\n//            for(int i=0; i<len;i++){\n//                myvec.push_back((int)boost::python::extract<int>(a[i]));\n//            }\n//        }\n//\n//        void output() {\n//            for(std::vector<int>::iterator iter = myvec.begin();\n//              iter != myvec.end();\n//              ++iter)\n//              {\n//                std::cout << (*iter) << std::endl;\n//              }\n//            std::cout << std::endl;\n//        };\n//};\n//\n//class PointList {\n//\n//    protected:\n//        std::vector<int> x;\n//        std::vector<int> y;\n//\n//    public:\n//        //VecTest(std::vector<int> a): myvec(a) {}\n//        PointList(boost::python::list a)\n//        {\n//\n//            boost::python::ssize_t len = boost::python::len(a);\n//            std::cout << \"length of list: \" << len << std::endl;\n//            for(int i=0; i<len;i++){\n//                x.push_back((int)boost::python::extract<int>(a[i][0]));\n//            }\n//        }\n//\n//        void output() {\n//            for(std::vector<int>::iterator iter = x.begin();\n//              iter != x.end();\n//              ++iter)\n//              {\n//                std::cout << (*iter) << std::endl;\n//              }\n//            std::cout << std::endl;\n//        };\n//};\n//\n\nusing namespace boost::python;\n\n// the argument of the init macro must be the module name\nBOOST_PYTHON_MODULE_INIT(morpho)\n{\n    // initialize numpy and vigranumpy\n    vigra::import_vigranumpy();\n\n    // Structuring elements\n    //class_<morpho::structuringElement2D>(\"structuringElement2D\", init<std::vector<vigra::Diff2D> >())\n    //    .def(\"output\", &morpho::structuringElement2D::output);\n//    class_<std::vector<int> >(\"VectorOfInt\")\n//            .def(vector_indexing_suite<std::vector<int> >() )\n//        ;\n\n    //typedef std::vector<int> VectorOfInt;\n\n//    class_<VecTest>(\"VecTest\", init<boost::python::list>())\n//        .def(\"output\", &VecTest::output)\n//        ;\n//\n//    class_<PointList>(\"PointList\", init<boost::python::list>())\n//        .def(\"output\", &PointList::output)\n//        ;\n\n//    class_<TCurrency>( \"TCurrency\" )\n//        .def( init<long> )\n//        .def( init<const std::string&> )\n//        ...\n//        ;\n//\n    class_<structuringElement2D_Conv>(\"structuringElement2D\",\n                                      \"\\nA Structuring Element in two dimensions for morphological operations. \"\n                                      \"\\nThe constructor takes a a list of points (python list of lists).\"\n                                      \"\\nThe structuring element is needed for morphological operations such as erosion, dilation\"\n                                      \"opening, closing. \"\n                                      \"\\n\\nExample: simple 4 neighborhood structuring element:\"\n                                      \"\\n>>> se = vigra.morpho.structuringElement2D([[0,0], [1,0], [0,1], [-1, 0], [0, -1]])\"\n                                      \"\\n\\nExample: simple 8 neighborhood structuring element:\"\n                                      \"\\n>>> se = vigra.morpho.structuringElement2D([[0,0], [1,0], [0,1], [-1, 0], [0, -1], [1, 1], [1, -1], [-1, -1], [-1, 1]])\"\n                                      )\n        .def(init<boost::python::list>())//(\"structuringElement2D\", init<boost::python::list>())\n        .def(init<boost::python::list, int>())\n        .def(\"output\", &structuringElement2D_Conv::output)\n        .def(\"numberOfPixels\", &structuringElement2D_Conv::numberOfPixels)\n        .def_readwrite(\"size\", &structuringElement2D_Conv::size)\n        .def(\"transpose\", &structuringElement2D_Conv::transpose)\n        ;\n\n    // export morphological functions\n//    def(\"morphoDilation\", registerConverters(&pythonMorphoDilation<UInt8>),\n//        (arg(\"image\"), arg(\"size\"), arg(\"res\")=object()),\n//        \"Morphological Dilation of the image with a structuring element.\"\n//        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\"\n//        \"At the moment we only accept size as a parameter, and the structuring\"\n//        \"element is a square with radius of this size \"\n//        \"(i.e. with each side of length 2*size + 1)\");\n\n    def(\"morphoDilation\", registerConverters(&pythonMorphoDilation<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Dilation of the image with a structuring element.\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoDilation\", registerConverters(&pythonMorphoDilation<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Dilation of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoErosion\", registerConverters(&pythonMorphoErosion<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Erosion of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoErosion\", registerConverters(&pythonMorphoErosion<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Erosion of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoOpening\", registerConverters(&pythonMorphoOpening<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Opening of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoOpening\", registerConverters(&pythonMorphoOpening<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Opening of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoClosing\", registerConverters(&pythonMorphoClosing<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Closing of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoClosing\", registerConverters(&pythonMorphoClosing<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Closing of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoInternalGradient\", registerConverters(&pythonMorphoInternalGradient<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Internal gradient (f - ero(f)) of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoInternalGradient\", registerConverters(&pythonMorphoInternalGradient<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological Internal gradient (f - ero(f)) of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoExternalGradient\", registerConverters(&pythonMorphoExternalGradient<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological external gradient (dil(f) - f) of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoExternalGradient\", registerConverters(&pythonMorphoExternalGradient<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"res\")=object()),\n        \"Morphological external gradient (dil(f) - f) of the image with a structuring element.\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoOpeningByReconstruction\", registerConverters(&pythonMorphoOpeningByReconstruction<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Morphological opening, followed by a reconstruction of the opened image under the original image.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoOpeningByReconstruction\", registerConverters(&pythonMorphoOpeningByReconstruction<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Morphological opening, followed by a reconstruction of the opened image under the original image.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoClosingByReconstruction\", registerConverters(&pythonMorphoClosingByReconstruction<UInt8>),\n        (arg(\"image\"), arg(\"se\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Morphological closing, followed by a reconstruction of the closed image over the original image.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n    def(\"morphoClosingByReconstruction\", registerConverters(&pythonMorphoClosingByReconstruction<UInt16>),\n        (arg(\"image\"), arg(\"se\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Morphological closing, followed by a reconstruction of the closed image over the original image.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\"\n        \"The structuring element is of type vigra.morpho.structuringElement2D\");\n\n    def(\"morphoClosingByDynamics\", registerConverters(&pythonMorphoClosingByDynamics<UInt8>),\n        (arg(\"image\"), arg(\"h\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Let f be an image and h a positive constant. This function calculates then the \"\n        \"morphological reconstruction of f + h over f.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\");\n    def(\"morphoClosingByDynamics\", registerConverters(&pythonMorphoClosingByDynamics<UInt16>),\n        (arg(\"image\"), arg(\"h\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Let f be an image and h a positive constant. This function calculates then the \"\n        \"morphological reconstruction of f + h over f.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\");\n\n    def(\"morphoOpeningByDynamics\", registerConverters(&pythonMorphoOpeningByDynamics<UInt8>),\n        (arg(\"image\"), arg(\"h\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Let f be an image and h a positive constant. This function calculates then the \"\n        \"morphological reconstruction of f - h under f.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\");\n    def(\"morphoOpeningByDynamics\", registerConverters(&pythonMorphoOpeningByDynamics<UInt16>),\n        (arg(\"image\"), arg(\"h\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"Let f be an image and h a positive constant. This function calculates then the \"\n        \"morphological reconstruction of f - h under f.\"\n        \"This function is only implemented for Uint8 and Uint16 images\"\n        \"(for other images, you can use img_mod = img.astype(np.dtype('uint16')) for conversion)\");\n\n    def(\"morphoReconstructionByDilation\", registerConverters(&pythonMorphoReconstructionByDilation<UInt8>),\n        (arg(\"marker\"), arg(\"mask\"), arg(\"neighborhood_graph\")=8),\n        \"Takes two images and calculates the morphological reconstruction of the\"\n        \"first under the second. Typically the first image is a marker image and the second is the original\"\n        \"image to be analyzed.\");\n    def(\"morphoReconstructionByDilation\", registerConverters(&pythonMorphoReconstructionByDilation<UInt16>),\n        (arg(\"marker\"), arg(\"mask\"), arg(\"neighborhood_graph\")=8),\n        \"Takes two images and calculates the morphological reconstruction of the\"\n        \"first under the second. Typically the first image is a marker image and the second is the original\"\n        \"image to be analyzed.\");\n\n    def(\"morphoReconstructionByErosion\", registerConverters(&pythonMorphoReconstructionByErosion<UInt8>),\n        (arg(\"marker\"), arg(\"mask\"), arg(\"neighborhood_graph\")=8),\n        \"Takes two images and calculates the morphological reconstruction of the\"\n        \"first over the second. For this, the first image has to be greater than the second (pointwise).\"\n        \"Typically the first image is a marker image and the second is the original\"\n        \"image to be analyzed.\");\n    def(\"morphoReconstructionByErosion\", registerConverters(&pythonMorphoReconstructionByErosion<UInt16>),\n        (arg(\"marker\"), arg(\"mask\"), arg(\"neighborhood_graph\")=8),\n        \"Takes two images and calculates the morphological reconstruction of the\"\n        \"first over the second. For this, the first image has to be greater than the second (pointwise).\"\n        \"Typically the first image is a marker image and the second is the original\"\n        \"image to be analyzed.\");\n\n\n    def(\"morphoAreaOpening\", registerConverters(&pythonMorphoAreaOpening<UInt8>),\n        (arg(\"image\"), arg(\"area\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, an area parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the area opening of the input image, i.e.\"\n        \"the largest output image smaller than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least <area> pixels.\");\n    def(\"morphoAreaOpening\", registerConverters(&pythonMorphoAreaOpening<UInt16>),\n        (arg(\"image\"), arg(\"area\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, an area parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the area opening of the input image, i.e.\"\n        \"the largest output image smaller than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least <area> pixels.\");\n\n    def(\"morphoAreaClosing\", registerConverters(&pythonMorphoAreaClosing<UInt8>),\n        (arg(\"image\"), arg(\"area\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, an area parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the area closing of the input image, i.e.\"\n        \"the smallest output image larger than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least <area> pixels.\");\n    def(\"morphoAreaClosing\", registerConverters(&pythonMorphoAreaClosing<UInt16>),\n        (arg(\"image\"), arg(\"area\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, an area parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the area closing of the input image, i.e.\"\n        \"the smallest output image larger than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least <area> pixels.\");\n\n    def(\"morphoWatershed\", registerConverters(&pythonMorphoWatershed<UInt8, UInt16>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates a watershed from the local minima.\");\n    def(\"morphoWatershed\", registerConverters(&pythonMorphoWatershed<UInt16, UInt16>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates a watershed from the local minima.\");\n\n    def(\"morphoSelectiveWatershed\", registerConverters(&pythonMorphoSelectiveWatershed<UInt8, UInt16>),\n        (arg(\"image\"), arg(\"dyn_thresh\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image a dynamic threshold and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates a watershed from the local minima.\");\n    def(\"morphoSelectiveWatershed\", registerConverters(&pythonMorphoSelectiveWatershed<UInt16, UInt16>),\n        (arg(\"image\"), arg(\"dyn_thresh\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image a dynamic threshold and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates a watershed from the local minima.\");\n\n    def(\"morphoDynMinima\", registerConverters(&pythonMorphoDynMinima<UInt8>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates the morphological dynamics for each minimum\"\n        \"and returns an image which is only non-zero on the local minima and \");\n    def(\"morphoDynMinima\", registerConverters(&pythonMorphoDynMinima<UInt16>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates the morphological dynamics for each minimum\"\n        \"and returns an image which is only non-zero on the local minima and \");\n\n    def(\"morphoBifurcationPoints\", registerConverters(&pythonMorphoBifurcationPoints<UInt8, UInt8>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=4, arg(\"res\")=object()),\n        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The input image is supposed to contain a skeleton, where all non-zero pixels are taken as\"\n        \"foreground (i.e. belonging to the pixel).\"\n        \"The function finds the bifurcation points (all points with more than 2 neighbors).\");\n    def(\"morphoBifurcationPoints\", registerConverters(&pythonMorphoBifurcationPoints<UInt16, UInt16>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=4, arg(\"res\")=object()),\n        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The input image is supposed to contain a skeleton, where all non-zero pixels are taken as\"\n        \"foreground (i.e. belonging to the pixel).\"\n        \"The function finds the bifurcation points (all points with more than 2 neighbors).\");\n    def(\"morphoBifurcationPoints\", registerConverters(&pythonMorphoBifurcationPoints<float, float>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=4, arg(\"res\")=object()),\n        \"takes an image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The input image is supposed to contain a skeleton, where all non-zero pixels are taken as\"\n        \"foreground (i.e. belonging to the pixel).\"\n        \"The function finds the bifurcation points (all points with more than 2 neighbors).\");\n\n    def(\"morphoConstrainedWatershed\", registerConverters(&pythonMorphoConstrainedWatershed<UInt8, UInt8, UInt16>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, a marker image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates calculates a constrained watershed from the markers.\");\n    def(\"morphoConstrainedWatershed\", registerConverters(&pythonMorphoConstrainedWatershed<UInt16, UInt16, UInt16>),\n        (arg(\"image\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, a marker image and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is 8 neighborhood) as inputs. \"\n        \"The function calculates calculates a constrained watershed from the markers.\");\n\n    def(\"morphoDiameterOpening\", registerConverters(&pythonMorphoDiameterOpening<UInt8>),\n        (arg(\"image\"), arg(\"diameter\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, a diameter parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the diameter opening of the input image, i.e.\"\n        \"the largest output image smaller than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least a diameter of <diameter>\");\n    def(\"morphoDiameterOpening\", registerConverters(&pythonMorphoDiameterOpening<UInt16>),\n        (arg(\"image\"), arg(\"diameter\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, a diameter parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the diameter opening of the input image, i.e.\"\n        \"the largest output image smaller than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least a diameter of <diameter>\");\n\n    def(\"morphoDiameterClosing\", registerConverters(&pythonMorphoDiameterClosing<UInt8>),\n        (arg(\"image\"), arg(\"diameter\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, a diameter parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the diameter closing of the input image, i.e.\"\n        \"the smallest output image larger than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least a diameter of <diameter>\");\n    def(\"morphoDiameterClosing\", registerConverters(&pythonMorphoDiameterClosing<UInt16>),\n        (arg(\"image\"), arg(\"diameter\"), arg(\"neighborhood_graph\")=8, arg(\"res\")=object()),\n        \"takes an image, a diameter parameter and (optionally) a constant (4 or 8) indicating the neighborhood graph\"\n        \"(default is a 8 neighborhood) as inputs. \"\n        \"The function calculates the diameter closing of the input image, i.e.\"\n        \"the smallest output image larger than the input image for which any \"\n        \"connected component resulting from a threshold operation would have at least a diameter of <diameter>\");\n\n\n}\n} // end of namespace vigra\n\n", "meta": {"hexsha": "9052a9351558170ee2ec023274ea5aee9aceb6fc", "size": 51653, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vigranumpy/src/core/morpho.cxx", "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/morpho.cxx", "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/morpho.cxx", "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": 42.3385245902, "max_line_length": 161, "alphanum_fraction": 0.6204092695, "num_tokens": 12294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.05419873364244478, "lm_q1q2_score": 0.022899216953215812}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n/**\n * \\file not_adaptive.hpp\n * \\date Febuary 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <type_traits>\n\n#include <Eigen/Dense>\n\n#include <fl/util/traits.hpp>\n#include <fl/util/meta.hpp>\n#include <fl/model/adaptive_model.hpp>\n#include <fl/model/transition/interface/transition_function.hpp>\n#include <fl/model/sensor/interface/sensor_function.hpp>\n\nnamespace fl\n{\n\n/**\n * \\ingroup meta\n *\n * Not-Adaptive operator\n */\ntemplate <typename... Model> class NotAdaptive;\n\n/**\n * \\ingroup meta\n *\n * Traits of Non-Adaptive model\n */\ntemplate <typename Model>\nstruct Traits<NotAdaptive<Model>>\n    : Traits<Model>\n{\n    typedef typename Traits<Model>::Scalar Scalar;\n\n    enum : signed int { ParamDim = 0 };\n    typedef Eigen::Matrix<Scalar, ParamDim, 1> Param;\n    typedef AdaptiveModel<Param> AdaptiveModelBase;\n};\n\n/**\n * \\ingroup meta\n *\n * \\brief The NotAdaptive operator decorates any model such that it represents a\n * non-adaptive model. This operator can be applied to any model inparticular\n * to models which do not implement the AdaptiveModel interface.\n *\n * The way this operates is simply by overriding the AdaptiveModel interface\n * and deactivating it. If the model does not implement the AdaptiveModel\n * interface, then the NotAdaptive injects the interface with a deactivated\n * adaptivity.\n *\n * \\cond internal\n * NotAdaptive operator specialization forwarding to the according ModelType\n * (i.e. either internal::SensorType or internal::TransitionType).\n * \\endcond\n */\ntemplate <typename Model>\nclass NotAdaptive<Model>\n  : public NotAdaptive<\n               Model,\n               typename Model::ModelType,\n               Options<\n                   std::is_base_of<internal::AdaptiveModelType, Model>::value\n                >\n            >\n{\npublic:\n    typedef NotAdaptive<\n                Model,\n                typename Model::ModelType,\n                Options<\n                    std::is_base_of<internal::AdaptiveModelType, Model>::value\n                >\n            > Base;\n\n    /**\n     * Conversion constructor. This converts the actual model instance into\n     * a NotAdaptive instances\n     *\n     * \\param model     Actual model instance\n     */\n    template <typename ... M>\n    NotAdaptive(const M& ... model) : Base(model...) { }\n};\n\n/**\n * \\internal\n * \\ingroup meta\n *\n * Traits of Non-Adaptive observation models\n */\ntemplate <typename Model, int Adaptivity>\nstruct Traits<\n           NotAdaptive<Model, internal::SensorType, Options<Adaptivity>>\n       >\n    : Traits<NotAdaptive<Model>>\n{ };\n\n/**\n * \\internal\n * \\ingroup meta\n *\n * Traits of Non-Adaptive process model\n */\ntemplate <typename Model, int Adaptivity>\nstruct Traits<\n           NotAdaptive<Model, internal::TransitionType, Options<Adaptivity>>\n        >\n    : Traits<NotAdaptive<Model>>\n{ };\n\n\n/**\n * \\internal\n * \\ingroup meta\n *\n * NotAdaptive operator implementation of the observation model\n */\ntemplate <typename Model>\nclass NotAdaptive<Model, internal::SensorType, Options<IsNotAdaptive>>\n  : public Model,\n    public Traits<\n               NotAdaptive<\n                   Model,\n                   internal::SensorType,\n                   Options<IsNotAdaptive>\n               >\n           >::AdaptiveModelBase\n{\npublic:\n    typedef NotAdaptive<\n                Model,\n                internal::SensorType,\n                Options<IsNotAdaptive>\n            > This;\n\n    typedef typename Traits<This>::Obsrv Obsrv;\n    typedef typename Traits<This>::State State;\n    typedef typename Traits<This>::Noise Noise;\n    typedef typename Traits<This>::Param Param;\n\n    /**\n     * Conversion constructor. This converts the actual model instance into\n     * a NotAdaptive instances\n     *\n     * \\param model     Actual model instance\n     */\n    template <typename ... M>\n    NotAdaptive(const M& ... model) : Model(model...) { }\n\n    virtual Obsrv predict_obsrv(const State& state,\n                                const Noise& noise,\n                                double delta_time)\n    {\n        assert(state.rows() == state_dimension());\n\n        return Model::predict_obsrv(state.topRows(Model::state_dimension()),\n                                    noise, delta_time);\n    }\n\n    virtual int state_dimension() const\n    {\n        return Model::state_dimension() + param_dimension();\n    }\n\n    virtual void param(Param) {  }\n    virtual const Param& param() const { return param_; }\n    virtual int param_dimension() const { return 0; }\n\nprotected:\n    Param param_;\n};\n\n/**\n * \\internal\n * \\ingroup meta\n *\n * NotAdaptive operator implementation of the observation model\n */\ntemplate <typename Model>\nclass NotAdaptive<Model, internal::SensorType, Options<IsAdaptive>>\n  : public Model\n{\npublic:\n    typedef NotAdaptive<\n                Model,\n                internal::SensorType,\n                Options<IsAdaptive>\n            > This;\n\n    typedef typename Traits<This>::Obsrv Obsrv;\n    typedef typename Traits<This>::State State;\n    typedef typename Traits<This>::Noise Noise;\n    typedef typename Traits<This>::Param Param;\n\n    /**\n     * Conversion constructor. This converts the actual model instance into\n     * a NotAdaptive instances\n     *\n     * \\param model     Actual model instance\n     */\n    template <typename ... M>\n    NotAdaptive(const M& ... model) : Model(model...) { }\n\n    virtual Obsrv predict_obsrv(const State& state,\n                                const Noise& noise,\n                                double delta_time)\n    {\n        assert(state.rows() == state_dimension());\n\n        return Model::predict_obsrv(state.topRows(Model::state_dimension()),\n                                    noise, delta_time);\n    }\n\n    virtual int state_dimension() const\n    {\n        return Model::state_dimension() + param_dimension();\n    }\n\n    virtual void param(Param) {  }\n//    virtual const Param& param() const { return param_; }\n    virtual int param_dimension() const { return 0; }\n\nprotected:\n    Param param_;\n};\n\n/**\n * \\internal\n * \\ingroup meta\n *\n * NotAdaptive operator implementation of the process model\n */\ntemplate <typename Model>\nclass NotAdaptive<Model, internal::TransitionType, Options<IsNotAdaptive>>\n  : public Model,\n    public Traits<\n               NotAdaptive<\n                   Model,\n                   internal::TransitionType,\n                   Options<IsNotAdaptive>>\n           >::AdaptiveModelBase\n{\npublic:\n    typedef NotAdaptive<\n                Model,\n                internal::TransitionType,\n                Options<IsNotAdaptive>\n            > This;\n\n    typedef typename Traits<This>::Input Input;\n    typedef typename Traits<This>::State State;\n    typedef typename Traits<This>::Noise Noise;\n    typedef typename Traits<This>::Param Param;\n\n    /**\n     * Conversion constructor. This converts the actual model instance into\n     * a NotAdaptive instances\n     *\n     * \\param model     Actual model instance\n     */\n    template <typename ... M>\n    NotAdaptive(const M& ... model) : Model(model...) { }\n\n    virtual State predict_state(double delta_time,\n                                const State& state,\n                                const Noise& noise,\n                                const Input& input)\n    {\n        assert(state.rows() == state_dimension());\n\n        return Model::predict_state(\n                    delta_time,\n                    state.topRows(Model::state_dimension()),\n                    noise,\n                    input);\n    }\n\n    virtual int state_dimension() const\n    {\n        return Model::state_dimension() + param_dimension();\n    }\n\n    virtual void param(Param) {  }\n    virtual const Param& param() const { return param_; }\n    virtual int param_dimension() const { return 0; }\n\nprotected:\n    Param param_;\n};\n\n\n\n/**\n * \\internal\n * \\ingroup meta\n *\n * NotAdaptive operator implementation of the process model\n */\ntemplate <typename Model>\nclass NotAdaptive<Model, internal::TransitionType, Options<IsAdaptive>>\n  : public Model\n{\npublic:\n    typedef NotAdaptive<\n                Model,\n                internal::TransitionType,\n                Options<IsAdaptive>\n            > This;\n\n    typedef typename Traits<This>::Input Input;\n    typedef typename Traits<This>::State State;\n    typedef typename Traits<This>::Noise Noise;\n    typedef typename Traits<This>::Param Param;\n\n    /**\n     * Conversion constructor. This converts the actual model instance into\n     * a NotAdaptive instances\n     *\n     * \\param model     Actual model instance\n     */\n    template <typename ... M>\n    NotAdaptive(const M& ... model) : Model(model...) { }\n\n    virtual State predict_state(double delta_time,\n                                const State& state,\n                                const Noise& noise,\n                                const Input& input)\n    {\n        assert(state.rows() == state_dimension());\n\n        return Model::predict_state(\n                    delta_time,\n                    state.topRows(Model::state_dimension()),\n                    noise,\n                    input);\n    }\n\n    virtual int state_dimension() const\n    {\n        return Model::state_dimension() + param_dimension();\n    }\n\n    virtual void param(Param) {  }\n//    virtual const Param& param() const { return param_; }\n    virtual int param_dimension() const { return 0; }\n\nprotected:\n    Param param_;\n};\n\n}\n\n\n", "meta": {"hexsha": "2cb6e422a4da5e442ab06bce37c6ab4c395d087a", "size": 9789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/util/meta/operator/not_adaptive.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/util/meta/operator/not_adaptive.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/util/meta/operator/not_adaptive.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 26.2439678284, "max_line_length": 80, "alphanum_fraction": 0.607007866, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.04958901964814955, "lm_q1q2_score": 0.02286137012744506}}
{"text": "//---------------------------------------------------------------------------\n//\n//    FCST: Fuel Cell Simulation Toolbox\n//\n//    Copyright (C) 2009-13 by Energy Systems Design Laboratory, University of Alberta\n//\n//    This software is distributed under the MIT License.\n//    For more information, see the README file in /doc/LICENSE\n//\n//    - Class: picard.cc\n//    - Description: Picard solver\n//    - Developers: Mayank Sabharwal\n//\n//---------------------------------------------------------------------------\n\n#include <solvers/picard.h> \n#include <deal.II/base/data_out_base.h>\n#include <deal.II/lac/block_vector.h>\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <cmath>\n\nusing namespace FuelCell::ApplicationCore;\n\n\n//---------------------------------------------------------------------------\nPicard::Picard(ApplicationBase& app)\n    : PicardBase(app),\n    underrelaxation(false)\n{\n  FcstUtilities::log << \"->Picard\";\n}\n\n//---------------------------------------------------------------------------\nvoid\nPicard::declare_parameters(ParameterHandler& param)\n{\n    PicardBase::declare_parameters(param);\n    param.enter_subsection(\"Picard\");\n    {\n        param.declare_entry(\"Under-relaxation\",\n                            \"false\",\n                            Patterns::Bool(),\n                            \"Use adaptive under-relaxation\");\n        param.declare_entry(\"Alpha\", \n                            \"4\", \n                            Patterns::Double(),\n                            \"Alpha value for underrelaxation;Range of 2-6 works best\");\n        param.declare_entry(\"Gamma min\", \n                            \"0.6\", \n                            Patterns::Double(),\n                            \"Gamma min value for underrelaxation;Range of 0.1-0.6 works best\");\n    }\n    param.leave_subsection();      \n}\n\n//---------------------------------------------------------------------------\nvoid\nPicard::initialize (ParameterHandler& param)\n{\n    PicardBase::initialize(param);\n    param.enter_subsection(\"Picard\");\n    {\n        underrelaxation = param.get_bool(\"Under-relaxation\");\n        alpha = param.get_double(\"Alpha\");\n        gamma_min = param.get_double(\"Gamma min\");\n    }\n    param.leave_subsection();\n}\n\n//---------------------------------------------------------------------------\nvoid\nPicard::solve (FuelCell::ApplicationCore::FEVector& u, const FuelCell::ApplicationCore::FEVectors& in_vectors)\n{\n    this->step = 0;\n\n    if (debug>2)\n        FcstUtilities::log << \"u: \" << u.l2_norm() << std::endl;\n\n    FEVector u_n;\n    FEVector res;\n\n    res.reinit(u);\n    u_n.reinit(u);\n    FEVectors src1;\n    FEVectors src2;\n    src1.add_vector(u, \"Solution\");\n    src1.merge(in_vectors);\n    src2.add_vector(res, \"residual\");\n    src2.merge(src1);\n\n    double residual = app->residual(res, src1);\n    double old_residual = residual;\n    \n    double abs_error = 1.e6;\n    double rel_error = 1.e6;\n    \n    this->debug_output(u, u_n, res);\n    app->notify(Event::assign(\"Picard\"));\n    double old_error = 1e5;\n    \n    //\n    while ((abs_error > this->abs_tolerance) && (rel_error > this->rel_tolerance) && (this->step < this->maxsteps))\n    {\n        u_n.reinit(u);\n        app->solve (u_n, src2);\n\n\n        abs_error = 0;\n        rel_error = 0;\n        FEVector error;\n        error.reinit(u);\n        \n        double gamma, delta=0, gamma_min=this->gamma_min, alpha= this->alpha, epsilon=this->abs_tolerance;\n\n        this->compute_errors(u,u_n,error,abs_error,rel_error,delta);\n            \n        // Adaptive under-relaxation scheme\n        if (this->underrelaxation)\n        {\n            \n            FcstUtilities::log<<\"Delta: \"<<delta<<std::endl;\n\n            double rho=0.95;    //damping factor if solution starts to diverge\n            \n            // If solution diverges then gamma and alpha are further damped \n            while(old_error<abs_error && rho>0 && this->step>1)\n            {\n                FcstUtilities::log<<\"New solution diverging! Damping gamma and alpha\"<<std::endl;\n                gamma_min*=rho;\n                \n                alpha = - log((gamma*rho - gamma_min)/(1-gamma_min))/(delta-epsilon);\n                gamma = gamma_min+(1-gamma_min)*exp (-alpha*(delta-epsilon));\n                \n                for(unsigned int i=0; i<u_n.size();i++)\n                    u(i)=u(i)+gamma*(u_n(i)-u(i));\n                residual = app->residual(res, src1);\n                app->notify(Event::assign(\"Picard\"));\n                u_n.reinit(u);\n                app->solve(u_n,src2);\n                abs_error = 0;\n                rel_error = 0;\n                \n                FcstUtilities::log<<\"Gamma: \"<<gamma<<std::endl;\n                double new_delta = 0;\n                this->compute_errors(u,u_n,error,abs_error,rel_error,new_delta);\n\n                FcstUtilities::log<<\"Delta: \"<<new_delta<<std::endl;\n                if (old_error>abs_error)\n                    delta = new_delta;\n                rho-=0.1;\n            }\n            if (delta>epsilon)\n                gamma = gamma_min+(1-gamma_min)*exp (-alpha*(delta-epsilon));\n            else\n                gamma = 1;\n            FcstUtilities::log<<\"Gamma: \"<<gamma<<std::endl;\n            for(unsigned int i=0; i<u_n.size();i++)\n                u(i)=u(i)+gamma*(u_n(i)-u(i));\n        }\n        //Pure Picard scheme\n        else\n            u=u_n;\n        \n        // Changing type of solver in order to assemble the cell residual using the assemble_cell_residual function of equation class\n        FEVector temp_res;\n        FEVectors temp_src;\n        temp_src.merge(src1);\n        this->data->set_nonlinear_solver(\"NewtonLineSearch\");\n        double new_residual = app->residual(temp_res,temp_src,false);\n        \n        // Reset the non-linear solver to Picard\n        this->data->set_nonlinear_solver(\"Picard\");\n        old_residual = residual;\n        residual = app->residual(res, src1);\n\n        // Output the global residual and the equation specific residual:\n        FcstUtilities::log << \"Overall absolute error at iteration \"<<this->step<<\" = \" << abs_error << std::endl;\n        FcstUtilities::log << \"Overall relative error at iteration \"<<this->step<<\" = \" << rel_error << std::endl;\n\n\n        for (unsigned int i = 0; i<res.n_blocks(); i++)\n            FcstUtilities::log << \"Residual for equation \"<<i<<\" is: \"<<temp_res.block(i).l2_norm() << std::endl;\n\n        // Debug output options:\n        this->debug_output(u, u_n, res);\n        old_error=abs_error;\n        this->step+=1;\n    }\n\n    AssertThrow((abs_error< this->abs_tolerance)||(rel_error< this->rel_tolerance),SolverControl::NoConvergence (this->step,abs_error));\n   \n}\n\nvoid \nPicard::compute_errors ( FEVector &u, FEVector &u_n, FEVector &error, double &abs_error, double &rel_error, double &delta)\n{\n    int flag =0;\n    double dofs=u.size();\n    for(unsigned int i=0; i<u_n.size();i++)\n    {\n        if (u_n(i)<0)\n        {\n            flag=1;\n            u_n(i)=0;\n        }\n        abs_error+=pow((u(i)-u_n(i)),2);\n        error(i)=u(i)-u_n(i);\n        if (fabs(u(i)-u_n(i))>delta)\n            delta = fabs(u(i)-u_n(i));\n    }\n    abs_error = sqrt(abs_error)/dofs;\n    rel_error = error.l2_norm()/u_n.l2_norm();\n    if (flag)\n        FcstUtilities::log<<\"Negative values in solution were set to zero!!!\"<<std::endl;\n}", "meta": {"hexsha": "fb1afff24f3771565aabaa5a8492cd2ffba21cc8", "size": 7384, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/fcst/source/solvers/picard.cc", "max_stars_repo_name": "jeremyjiezhou/Learn-PyTorch", "max_stars_repo_head_hexsha": "7e4404609bacd2ec796f6ca3ea118e8e34ab4a22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-04T20:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T19:07:10.000Z", "max_issues_repo_path": "src/fcst/source/solvers/picard.cc", "max_issues_repo_name": "jeremyjiezhou/Learn-PyTorch", "max_issues_repo_head_hexsha": "7e4404609bacd2ec796f6ca3ea118e8e34ab4a22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fcst/source/solvers/picard.cc", "max_forks_repo_name": "jeremyjiezhou/Learn-PyTorch", "max_forks_repo_head_hexsha": "7e4404609bacd2ec796f6ca3ea118e8e34ab4a22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-12-11T22:15:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T13:51:05.000Z", "avg_line_length": 33.5636363636, "max_line_length": 136, "alphanum_fraction": 0.5272210184, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.05340333431947304, "lm_q1q2_score": 0.022766994534423796}}
{"text": "/**************************************************************************\n * Copyright (c) 2017-2019 by the mfmg authors                            *\n * All rights reserved.                                                   *\n *                                                                        *\n * This file is part of the mfmg library. mfmg is distributed under a BSD *\n * 3-clause license. For the licensing terms see the LICENSE file in the  *\n * top-level directory                                                    *\n *                                                                        *\n * SPDX-License-Identifier: BSD-3-Clause                                  *\n *************************************************************************/\n\n#ifndef AMG_TEMPLATES_HPP\n#define AMG_TEMPLATES_HPP\n\n#include <mfmg/common/amge.hpp>\n#include <mfmg/common/exceptions.hpp>\n#include <mfmg/common/utils.hpp>\n\n#include <deal.II/distributed/tria.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/lac/sparsity_tools.h>\n#include <deal.II/numerics/data_out.h>\n\n#include <algorithm>\n#include <fstream>\n#include <map>\n#include <unordered_map>\n\n#ifdef DEAL_II_TRILINOS_WITH_ZOLTAN\n// Zoltan random seed control is in an internal zz_rand.h file which is not\n// installed with Trilinos. Thus, we duplicate the signature and the\n// initialization value here.\n#define ZOLTAN_RAND_INIT 123456789U\nextern \"C\"\n{\n  extern void Zoltan_Srand(unsigned int, unsigned int *);\n}\n#endif\n\nnamespace mfmg\n{\ntemplate <int dim, typename VectorType>\nAMGe<dim, VectorType>::AMGe(MPI_Comm comm,\n                            dealii::DoFHandler<dim> const &dof_handler)\n    : _comm(comm), _dof_handler(dof_handler)\n{\n}\n\ntemplate <int dim, typename VectorType>\nunsigned int AMGe<dim, VectorType>::build_agglomerates(\n    boost::property_tree::ptree const &ptree) const\n{\n  std::string partitioner_type = ptree.get<std::string>(\"partitioner\");\n  std::transform(partitioner_type.begin(), partitioner_type.end(),\n                 partitioner_type.begin(), ::tolower);\n  if ((partitioner_type == \"zoltan\") || (partitioner_type == \"metis\"))\n  {\n#ifdef DEAL_II_TRILINOS_WITH_ZOLTAN\n    // Always use the same seed for Zoltan\n    Zoltan_Srand(ZOLTAN_RAND_INIT, NULL);\n#endif\n    unsigned int const n_desired_agglomerates =\n        ptree.get<unsigned int>(\"n_agglomerates\");\n\n    return build_agglomerates_partitioner(partitioner_type,\n                                          n_desired_agglomerates);\n  }\n  else if (partitioner_type == \"block\")\n  {\n    std::array<unsigned int, dim> agglomerate_dim;\n    agglomerate_dim[0] = ptree.get<unsigned int>(\"nx\");\n    agglomerate_dim[1] = ptree.get<unsigned int>(\"ny\");\n    if (dim == 3)\n      agglomerate_dim[2] = ptree.get<unsigned int>(\"nz\");\n\n    return build_agglomerates_block(agglomerate_dim);\n  }\n  else\n    ASSERT_THROW(false, partitioner_type +\n                            \" is not a valid choice for the partitioner. The \"\n                            \"acceptable values are zoltan, metis, and block.\");\n  return 0;\n}\n\ntemplate <int dim, typename VectorType>\nstd::pair<std::vector<std::vector<unsigned int>>,\n          std::vector<std::vector<unsigned int>>>\nAMGe<dim, VectorType>::build_boundary_agglomerates() const\n{\n  auto filtered_iterators_range =\n      filter_iterators(_dof_handler.active_cell_iterators(),\n                       dealii::IteratorFilters::LocallyOwnedCell());\n  std::vector<std::set<unsigned int>> agg_cell_set(_n_agglomerates);\n  for (auto cell : filtered_iterators_range)\n  {\n    // The cell used_index 0 is reserved for artificial cell however to fill in\n    // the vector we need to decrease the user_index by one to make sure that we\n    // start filling the vector from the beginning.\n    unsigned int const agg_index = cell->user_index() - 1;\n    unsigned int const active_cell_index = cell->active_cell_index();\n    agg_cell_set[agg_index].insert(active_cell_index);\n  }\n\n  dealii::DynamicSparsityPattern connectivity;\n  dealii::GridTools::get_vertex_connectivity_of_cells(\n      _dof_handler.get_triangulation(), connectivity);\n\n  // TODO do this using multithreading. Maybe it's better to do everything in\n  // the following for loop\n  // Each agglomerate will create two new agglomerates: one composed of the\n  // cells of the agglomerate which are on the boundary with another agglomerate\n  // and another one composed of cells on other agglomerates that share a\n  // boundary with the current agglomerate\n  std::vector<std::vector<unsigned int>> interior_agglomerates;\n  std::vector<std::vector<unsigned int>> halo_agglomerates;\n  for (auto const &agg_cell : agg_cell_set)\n  {\n    std::vector<unsigned int> interior_boundary_cells;\n    std::set<unsigned int> halo_cells_in_agg;\n    for (auto const &agg_cell_it : agg_cell)\n    {\n      bool cell_in_agg = false;\n      // Get the connectivity for the current cell\n      auto connectivity_begin = connectivity.begin(agg_cell_it);\n      auto connectivity_end = connectivity.end(agg_cell_it);\n      for (auto connectivity_it = connectivity_begin;\n           connectivity_it != connectivity_end; ++connectivity_it)\n      {\n        // Cells that are on the boundary of agglomerates and have in their\n        // connectivity cells that are not part of the agglomerates\n        if (agg_cell.count(connectivity_it->column()) == 0)\n        {\n          if (cell_in_agg == false)\n          {\n            interior_boundary_cells.push_back(agg_cell_it);\n            cell_in_agg = true;\n          }\n          halo_cells_in_agg.insert(connectivity_it->column());\n        }\n      }\n    }\n\n    interior_agglomerates.emplace_back(interior_boundary_cells);\n    halo_agglomerates.emplace_back(halo_cells_in_agg.begin(),\n                                   halo_cells_in_agg.end());\n  }\n\n  return {interior_agglomerates, halo_agglomerates};\n}\n\ntemplate <int dim, typename VectorType>\nvoid AMGe<dim, VectorType>::build_agglomerate_triangulation(\n    unsigned int agglomerate_id,\n    dealii::Triangulation<dim> &agglomerate_triangulation,\n    std::map<typename dealii::Triangulation<dim>::active_cell_iterator,\n             typename dealii::DoFHandler<dim>::active_cell_iterator>\n        &agglomerate_to_global_tria_map) const\n{\n  std::vector<typename dealii::DoFHandler<dim>::active_cell_iterator>\n      agglomerate;\n  for (auto cell : _dof_handler.active_cell_iterators())\n    if (cell->user_index() == agglomerate_id)\n      agglomerate.push_back(cell);\n\n  build_agglomerate_triangulation(agglomerate, agglomerate_triangulation,\n                                  agglomerate_to_global_tria_map);\n}\n\ntemplate <int dim, typename VectorType>\nvoid AMGe<dim, VectorType>::build_agglomerate_triangulation(\n    std::vector<unsigned int> const &cell_index,\n    dealii::Triangulation<dim> &agglomerate_triangulation,\n    std::map<typename dealii::Triangulation<dim>::active_cell_iterator,\n             typename dealii::DoFHandler<dim>::active_cell_iterator>\n        &agglomerate_to_global_tria_map) const\n{\n  std::vector<typename dealii::DoFHandler<dim>::active_cell_iterator>\n      agglomerate;\n  agglomerate.reserve(cell_index.size());\n  if (cell_index.size() > 0)\n  {\n    auto cell = _dof_handler.begin_active();\n    std::advance(cell, cell_index[0]);\n    agglomerate.push_back(cell);\n\n    for (unsigned int i = 1; i < cell_index.size(); ++i)\n    {\n      std::advance(cell, cell_index[i] - cell_index[i - 1]);\n      agglomerate.push_back(cell);\n    }\n  }\n\n  build_agglomerate_triangulation(agglomerate, agglomerate_triangulation,\n                                  agglomerate_to_global_tria_map);\n}\n\ntemplate <int dim, typename VectorType>\nstd::vector<dealii::types::global_dof_index>\nAMGe<dim, VectorType>::compute_dof_index_map(\n    std::map<typename dealii::Triangulation<dim>::active_cell_iterator,\n             typename dealii::DoFHandler<dim>::active_cell_iterator> const\n        &patch_to_global_map,\n    dealii::DoFHandler<dim> const &agglomerate_dof_handler) const\n{\n  std::vector<dealii::types::global_dof_index> dof_indices(\n      agglomerate_dof_handler.n_dofs());\n\n  unsigned int const dofs_per_cell = _dof_handler.get_fe().dofs_per_cell;\n  std::vector<dealii::types::global_dof_index> agg_dof_indices(dofs_per_cell);\n  std::vector<dealii::types::global_dof_index> global_dof_indices(\n      dofs_per_cell);\n\n  for (auto agg_cell : agglomerate_dof_handler.active_cell_iterators())\n  {\n    agg_cell->get_dof_indices(agg_dof_indices);\n    auto global_cell = patch_to_global_map.at(agg_cell);\n    global_cell->get_dof_indices(global_dof_indices);\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n      dof_indices[agg_dof_indices[i]] = global_dof_indices[i];\n  }\n\n  return dof_indices;\n}\n\ntemplate <int dim, typename VectorType>\nvoid AMGe<dim, VectorType>::output(std::string const &filename) const\n{\n  dealii::DataOut<dim> data_out;\n  data_out.attach_dof_handler(_dof_handler);\n\n  unsigned int const n_active_cells =\n      _dof_handler.get_triangulation().n_active_cells();\n  dealii::Vector<float> subdomain(n_active_cells);\n  for (unsigned int i = 0; i < n_active_cells; ++i)\n    subdomain(i) = _dof_handler.get_triangulation().locally_owned_subdomain();\n  data_out.add_data_vector(subdomain, \"subdomain\");\n\n  dealii::Vector<float> agglomerates(n_active_cells);\n  unsigned int n = 0;\n  for (auto cell : _dof_handler.active_cell_iterators())\n  {\n    if (cell->is_locally_owned())\n      agglomerates(n) = cell->user_index();\n    ++n;\n  }\n  data_out.add_data_vector(agglomerates, \"agglomerates\");\n\n  data_out.build_patches();\n\n  std::string full_filename =\n      filename +\n      std::to_string(\n          _dof_handler.get_triangulation().locally_owned_subdomain());\n  std::ofstream output((full_filename + \".vtu\").c_str());\n  data_out.write_vtu(output);\n\n  if (dealii::Utilities::MPI::this_mpi_process(_comm) == 0)\n  {\n    unsigned int const comm_size =\n        dealii::Utilities::MPI::n_mpi_processes(_comm);\n    std::vector<std::string> full_filenames(comm_size);\n    for (unsigned int i = 0; i < comm_size; ++i)\n      full_filenames[0] = filename + std::to_string(i) + \".vtu\";\n    std::ofstream master_output(filename + \".pvtu\");\n    data_out.write_pvtu_record(master_output, full_filenames);\n  }\n}\n\ntemplate <int dim, typename VectorType>\nvoid AMGe<dim, VectorType>::compute_restriction_sparse_matrix(\n    std::vector<dealii::Vector<typename VectorType::value_type>> const\n        &eigenvectors,\n    std::vector<std::vector<typename VectorType::value_type>> const\n        &diag_elements,\n    std::vector<std::vector<dealii::types::global_dof_index>> const\n        &dof_indices_maps,\n    std::vector<unsigned int> const &n_local_eigenvectors,\n    dealii::LinearAlgebra::distributed::Vector<\n        typename VectorType::value_type> const &locally_relevant_global_diag,\n    dealii::TrilinosWrappers::SparseMatrix &restriction_sparse_matrix) const\n{\n  // Compute the sparsity pattern (Epetra_FECrsGraph)\n  dealii::TrilinosWrappers::SparsityPattern restriction_sp =\n      compute_restriction_sparsity_pattern(eigenvectors, dof_indices_maps,\n                                           n_local_eigenvectors);\n\n  // Build the restriction sparse matrix\n  restriction_sparse_matrix.reinit(restriction_sp);\n  std::pair<dealii::types::global_dof_index,\n            dealii::types::global_dof_index> const local_range =\n      restriction_sp.local_range();\n  unsigned int const n_agglomerates = n_local_eigenvectors.size();\n  unsigned int pos = 0;\n  ASSERT(n_agglomerates == dof_indices_maps.size(),\n         \"dof_indices_maps has the wrong size: \" +\n             std::to_string(dof_indices_maps.size()) + \" instead of \" +\n             std::to_string(n_agglomerates));\n  for (unsigned int i = 0; i < n_agglomerates; ++i)\n  {\n    unsigned int const n_local_eig = n_local_eigenvectors[i];\n    for (unsigned int k = 0; k < n_local_eig; ++k)\n    {\n      unsigned int const n_elem = eigenvectors[pos].size();\n      ASSERT(n_elem == dof_indices_maps[i].size(),\n             \"dof_indices_maps[i] has the wrong size: \" +\n                 std::to_string(dof_indices_maps[i].size()) + \" instead of \" +\n                 std::to_string(n_elem));\n      for (unsigned int j = 0; j < n_elem; ++j)\n      {\n        dealii::types::global_dof_index const global_pos =\n            dof_indices_maps[i][j];\n        restriction_sparse_matrix.add(\n            local_range.first + pos, global_pos,\n            diag_elements[i][j] / locally_relevant_global_diag[global_pos] *\n                eigenvectors[pos][j]);\n      }\n      ++pos;\n    }\n  }\n\n  // Compress the matrix\n  restriction_sparse_matrix.compress(dealii::VectorOperation::add);\n}\n\ntemplate <int dim, typename VectorType>\nvoid AMGe<dim, VectorType>::compute_restriction_sparse_matrix(\n    std::vector<dealii::Vector<typename VectorType::value_type>> const\n        &eigenvectors,\n    std::vector<std::vector<typename VectorType::value_type>> const\n        &diag_elements,\n    std::vector<std::vector<dealii::types::global_dof_index>> const\n        &dof_indices_maps,\n    std::vector<unsigned int> const &n_local_eigenvectors,\n    dealii::LinearAlgebra::distributed::Vector<\n        typename VectorType::value_type> const &locally_relevant_global_diag,\n    std::shared_ptr<dealii::TrilinosWrappers::SparseMatrix>\n        restriction_sparse_matrix,\n    std::unique_ptr<dealii::TrilinosWrappers::SparseMatrix>\n        &eigenvector_sparse_matrix,\n    std::unique_ptr<dealii::TrilinosWrappers::SparseMatrix>\n        &delta_eigenvector_matrix) const\n{\n  // Compute the sparsity pattern (Epetra_FECrsGraph)\n  dealii::TrilinosWrappers::SparsityPattern restriction_sp =\n      compute_restriction_sparsity_pattern(eigenvectors, dof_indices_maps,\n                                           n_local_eigenvectors);\n\n  // Build the sparse matrices\n  restriction_sparse_matrix->reinit(restriction_sp);\n  eigenvector_sparse_matrix.reset(\n      new dealii::TrilinosWrappers::SparseMatrix(restriction_sp));\n  // The sparsity pattern is different than for the other sparse matrices\n  // because some of the entries that do not correspond to agglomerate boundary\n  // are zeros. Because reinit requires the SparsityPattern which is harder to\n  // compute, we instead use the constructor that computes the SparsityPattern\n  // when compress() is called).\n  delta_eigenvector_matrix.reset(new dealii::TrilinosWrappers::SparseMatrix(\n      eigenvector_sparse_matrix->locally_owned_range_indices(),\n      eigenvector_sparse_matrix->locally_owned_domain_indices(),\n      eigenvector_sparse_matrix->get_mpi_communicator()));\n\n  std::pair<dealii::types::global_dof_index,\n            dealii::types::global_dof_index> const local_range =\n      restriction_sp.local_range();\n  unsigned int const n_agglomerates = n_local_eigenvectors.size();\n  unsigned int pos = 0;\n  ASSERT(n_agglomerates == dof_indices_maps.size(),\n         \"dof_indices_maps has the wrong size: \" +\n             std::to_string(dof_indices_maps.size()) + \" instead of \" +\n             std::to_string(n_agglomerates));\n  for (unsigned int i = 0; i < n_agglomerates; ++i)\n  {\n    unsigned int const n_local_eig = n_local_eigenvectors[i];\n    for (unsigned int k = 0; k < n_local_eig; ++k)\n    {\n      unsigned int const n_elem = eigenvectors[pos].size();\n      ASSERT(n_elem == dof_indices_maps[i].size(),\n             \"dof_indices_maps[i] has the wrong size: \" +\n                 std::to_string(dof_indices_maps[i].size()) + \" instead of \" +\n                 std::to_string(n_elem));\n      for (unsigned int j = 0; j < n_elem; ++j)\n      {\n        dealii::types::global_dof_index const global_pos =\n            dof_indices_maps[i][j];\n        // Fill restriction sparse matrix\n        restriction_sparse_matrix->add(\n            local_range.first + pos, global_pos,\n            diag_elements[i][j] / locally_relevant_global_diag[global_pos] *\n                eigenvectors[pos][j]);\n        // Fill eigenvector sparse matrix\n        eigenvector_sparse_matrix->add(local_range.first + pos, global_pos,\n                                       eigenvectors[pos][j]);\n        // Fill delta eigenvector sparse matrix\n        delta_eigenvector_matrix->set(\n            local_range.first + pos, global_pos,\n            (diag_elements[i][j] / locally_relevant_global_diag[global_pos] -\n             1.) *\n                eigenvectors[pos][j]);\n      }\n      ++pos;\n    }\n  }\n\n  // Compress the matrices\n  restriction_sparse_matrix->compress(dealii::VectorOperation::add);\n  eigenvector_sparse_matrix->compress(dealii::VectorOperation::add);\n  delta_eigenvector_matrix->compress(dealii::VectorOperation::insert);\n}\n\ntemplate <int dim, typename VectorType>\nunsigned int AMGe<dim, VectorType>::build_agglomerates_block(\n    std::array<unsigned int, dim> const &agglomerate_dim) const\n{\n  // Faces in deal.II are ordered as follows: left (x_m) = 0, right (x_p) = 1,\n  // front (y_m) = 2, back (y_p) = 3, bottom (z_m) = 4, top (z_p) = 5\n  unsigned int constexpr x_p = 1;\n  unsigned int constexpr y_p = 3;\n  unsigned int constexpr z_p = 5;\n\n  // Flag the cells to create the agglomerates\n  unsigned int agglomerate = 1;\n  for (auto cell : _dof_handler.active_cell_iterators())\n  {\n    if ((cell->is_locally_owned()) && (cell->user_index() == 0))\n    {\n#if MFMG_DEBUG\n      int const cell_level = cell->level();\n#endif\n      cell->set_user_index(agglomerate);\n      auto current_z_cell = cell;\n      unsigned int const d_3 = (dim < 3) ? 1 : agglomerate_dim.back();\n      for (unsigned int k = 0; k < d_3; ++k)\n      {\n        auto current_y_cell = current_z_cell;\n        for (unsigned int j = 0; j < agglomerate_dim[1]; ++j)\n        {\n          auto current_cell = current_y_cell;\n          for (unsigned int i = 0; i < agglomerate_dim[0]; ++i)\n          {\n            current_cell->set_user_index(agglomerate);\n            if (current_cell->at_boundary(x_p) == false)\n            {\n              // TODO For now, we assume that there is no adaptive refinement.\n              // When we change this, we will need to switch to hp::DoFHandler\n              auto neighbor_cell = current_cell->neighbor(x_p);\n#if MFMG_DEBUG\n              if ((!neighbor_cell->active()) ||\n                  (neighbor_cell->level() != cell_level))\n                throw std::runtime_error(\"Mesh locally refined\");\n#endif\n              if (neighbor_cell->is_locally_owned())\n                current_cell = neighbor_cell;\n            }\n            else\n              break;\n          }\n          if (current_y_cell->at_boundary(y_p) == false)\n          {\n            auto neighbor_y_cell = current_y_cell->neighbor(y_p);\n            if (neighbor_y_cell->is_locally_owned())\n            {\n#if MFMG_DEBUG\n              if ((!neighbor_y_cell->active()) ||\n                  (neighbor_y_cell->level() != cell_level))\n                throw std::runtime_error(\"Mesh locally refined\");\n#endif\n              current_y_cell = neighbor_y_cell;\n            }\n          }\n          else\n            break;\n        }\n        if ((dim == 3) && (current_z_cell->at_boundary(z_p) == false))\n        {\n          auto neighbor_z_cell = current_z_cell->neighbor(z_p);\n          if (neighbor_z_cell->is_locally_owned())\n          {\n#if MFMG_DEBUG\n            if ((!neighbor_z_cell->active()) ||\n                (neighbor_z_cell->level() != cell_level))\n              throw std::runtime_error(\"Mesh locally refined\");\n#endif\n            current_z_cell = neighbor_z_cell;\n          }\n        }\n        else\n          break;\n      }\n\n      ++agglomerate;\n    }\n  }\n\n  _n_agglomerates = agglomerate - 1;\n\n  return _n_agglomerates;\n}\n\ntemplate <int dim, typename VectorType>\nunsigned int AMGe<dim, VectorType>::build_agglomerates_partitioner(\n    std::string const &partitioner_type, unsigned int n_agglomerates) const\n{\n  // We cannot use deal.II wrappers to create the agglomerates because\n  //   1) the wrappers only works on serial Triangulation\n  //   2) they override the subdomain_id which is already used by p4est\n  // Instead, we create the connectivity graph ourselves and then, we do the\n  // partitioning.\n\n  unsigned int const n_local_cells =\n      _dof_handler.get_triangulation().n_active_cells();\n\n  // Create the DynamicSparsityPattern\n  dealii::DynamicSparsityPattern connectivity(n_local_cells);\n\n  // Associate a local index to each cell\n  unsigned int local_index = 0;\n  std::map<std::pair<unsigned int, unsigned int>, unsigned int> index_map;\n  for (auto cell : _dof_handler.active_cell_iterators())\n  {\n    if (cell->is_locally_owned())\n    {\n      index_map[std::make_pair(cell->level(), cell->index())] = local_index;\n      ++local_index;\n    }\n  }\n\n  // Fill the dynamic connectivity sparsity pattern\n  for (auto cell : _dof_handler.active_cell_iterators())\n  {\n    if (cell->is_locally_owned())\n    {\n      unsigned int const index =\n          index_map.at(std::make_pair(cell->level(), cell->index()));\n      connectivity.add(index, index);\n      for (unsigned int f = 0; f < dealii::GeometryInfo<dim>::faces_per_cell;\n           ++f)\n      {\n        if ((cell->at_boundary(f) == false) &&\n            (cell->neighbor(f)->is_locally_owned() == true) &&\n            (cell->neighbor(f)->has_children() == false))\n        {\n          unsigned int const neighbor_index = index_map.at(std::make_pair(\n              cell->neighbor(f)->level(), cell->neighbor(f)->index()));\n          connectivity.add(index, neighbor_index);\n          connectivity.add(neighbor_index, index);\n        }\n      }\n    }\n  }\n\n  dealii::SparsityPattern cell_connectivity;\n  cell_connectivity.copy_from(connectivity);\n\n  // Partition the connection graph\n  dealii::SparsityTools::Partitioner partitioner;\n  if (partitioner_type == \"metis\")\n    partitioner = dealii::SparsityTools::Partitioner::metis;\n  else\n    partitioner = dealii::SparsityTools::Partitioner::zoltan;\n  std::vector<unsigned int> partition_indices(n_local_cells);\n  dealii::SparsityTools::partition(cell_connectivity, n_agglomerates,\n                                   partition_indices, partitioner);\n\n  // Assign the agglomerate ID to all the locally owned cells. Zoltan does not\n  // guarantee that the agglomerate IDs will consecutive so we need to\n  // renumber them. The lowest agglomerate ID is one because zero is reserved\n  // for ghost and artificial cells.\n  unsigned int n_zoltan_agglomerates = 0;\n  std::unordered_map<unsigned int, unsigned int> agglomerate_renumbering;\n  for (auto cell : _dof_handler.active_cell_iterators())\n  {\n    if (cell->is_locally_owned())\n    {\n      unsigned int const index =\n          index_map.at(std::make_pair(cell->level(), cell->index()));\n      auto agg_id = agglomerate_renumbering.find(partition_indices[index]);\n      if (agg_id == agglomerate_renumbering.end())\n      {\n        ++n_zoltan_agglomerates;\n        agglomerate_renumbering[partition_indices[index]] =\n            n_zoltan_agglomerates;\n        cell->set_user_index(n_zoltan_agglomerates);\n      }\n      else\n        cell->set_user_index(agg_id->second);\n    }\n  }\n\n  _n_agglomerates = n_zoltan_agglomerates;\n\n  return _n_agglomerates;\n}\n\ntemplate <int dim, typename VectorType>\ndealii::TrilinosWrappers::SparsityPattern\nAMGe<dim, VectorType>::compute_restriction_sparsity_pattern(\n    std::vector<dealii::Vector<double>> const &eigenvectors,\n    std::vector<std::vector<dealii::types::global_dof_index>> const\n        &dof_indices_maps,\n    std::vector<unsigned int> const &n_local_eigenvectors) const\n{\n  // Compute the row IndexSet\n  int const n_procs = dealii::Utilities::MPI::n_mpi_processes(this->_comm);\n  int const rank = dealii::Utilities::MPI::this_mpi_process(this->_comm);\n  unsigned int const n_local_rows(eigenvectors.size());\n  std::vector<unsigned int> n_rows_per_proc(n_procs);\n  n_rows_per_proc[rank] = n_local_rows;\n  MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, &n_rows_per_proc[0], 1,\n                MPI_UNSIGNED, this->_comm);\n\n  dealii::types::global_dof_index n_total_rows =\n      std::accumulate(n_rows_per_proc.begin(), n_rows_per_proc.end(),\n                      static_cast<dealii::types::global_dof_index>(0));\n  dealii::types::global_dof_index n_rows_before =\n      std::accumulate(n_rows_per_proc.begin(), n_rows_per_proc.begin() + rank,\n                      static_cast<dealii::types::global_dof_index>(0));\n  dealii::IndexSet row_indexset(n_total_rows);\n  row_indexset.add_range(n_rows_before, n_rows_before + n_local_rows);\n  row_indexset.compress();\n\n  // Build the sparsity pattern\n  dealii::TrilinosWrappers::SparsityPattern sp(\n      row_indexset, this->_dof_handler.locally_owned_dofs(), this->_comm);\n\n  unsigned int const n_agglomerates = n_local_eigenvectors.size();\n  unsigned int row = 0;\n  for (unsigned int i = 0; i < n_agglomerates; ++i)\n  {\n    unsigned int const n_local_eig = n_local_eigenvectors[i];\n    for (unsigned int j = 0; j < n_local_eig; ++j)\n    {\n      sp.add_entries(n_rows_before + row, dof_indices_maps[i].begin(),\n                     dof_indices_maps[i].end());\n      ++row;\n    }\n  }\n\n  sp.compress();\n\n  return sp;\n}\n\ntemplate <int dim, typename VectorType>\nvoid AMGe<dim, VectorType>::build_agglomerate_triangulation(\n    std::vector<typename dealii::DoFHandler<dim>::active_cell_iterator> const\n        &agglomerate,\n    dealii::Triangulation<dim> &agglomerate_triangulation,\n    std::map<typename dealii::Triangulation<dim>::active_cell_iterator,\n             typename dealii::DoFHandler<dim>::active_cell_iterator>\n        &agglomerate_to_global_tria_map) const\n{\n  if (agglomerate.empty())\n    return;\n  // Map between the cells on the boundary and the faces on the boundary and the\n  // associated boundary id.\n  std::map<typename dealii::DoFHandler<dim>::active_cell_iterator,\n           std::vector<std::pair<unsigned int, unsigned int>>>\n      boundary_ids;\n  for (auto cell : agglomerate)\n    if (cell->at_boundary())\n    {\n      for (unsigned int f = 0; f < dealii::GeometryInfo<dim>::faces_per_cell;\n           ++f)\n      {\n        if (cell->face(f)->at_boundary())\n        {\n          boundary_ids[cell].push_back(\n              std::make_pair(f, cell->face(f)->boundary_id()));\n        }\n      }\n    }\n\n  // If the agglomerate has hanging nodes, the patch is bigger than\n  // what we may expect because we cannot create a coarse triangulation with\n  // hanging nodes. Thus, we need to use FE_Nothing to get ride of unwanted\n  // cells.\n  dealii::GridTools::build_triangulation_from_patch<dealii::DoFHandler<dim>>(\n      agglomerate, agglomerate_triangulation, agglomerate_to_global_tria_map);\n\n  // Copy the boundary IDs to the agglomerate triangulation\n  for (auto const &boundary : boundary_ids)\n  {\n    auto const boundary_cell = boundary.first;\n\n    auto agg_cell =\n        std::find_if(agglomerate_to_global_tria_map.begin(),\n                     agglomerate_to_global_tria_map.end(),\n                     [&](auto const &agglomerate_cell) {\n                       return (agglomerate_cell.second == boundary_cell);\n                     });\n    if (agg_cell != agglomerate_to_global_tria_map.end())\n      for (auto &boundary_face : boundary.second)\n        agg_cell->first->face(boundary_face.first)\n            ->set_boundary_id(boundary_face.second);\n  }\n}\n} // namespace mfmg\n\n#endif\n", "meta": {"hexsha": "9601b9813855a686f1279cc60296799775d91df5", "size": 27243, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mfmg/common/amge.templates.hpp", "max_stars_repo_name": "Rombur/mfmg", "max_stars_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-03T15:13:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T19:33:10.000Z", "max_issues_repo_path": "include/mfmg/common/amge.templates.hpp", "max_issues_repo_name": "Rombur/mfmg", "max_issues_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 199.0, "max_issues_repo_issues_event_min_datetime": "2017-11-03T13:33:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-07T22:46:18.000Z", "max_forks_repo_path": "include/mfmg/common/amge.templates.hpp", "max_forks_repo_name": "Rombur/mfmg", "max_forks_repo_head_hexsha": "b7c66dfb58bc880b04f52ce22b454047f82d69ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-11-03T12:44:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T05:51:23.000Z", "avg_line_length": 38.8076923077, "max_line_length": 80, "alphanum_fraction": 0.6683184671, "num_tokens": 6670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.05419872524007488, "lm_q1q2_score": 0.0226928387490374}}
{"text": "//\n// Copyright (c) 2015-2019 CNRS INRIA\n// Copyright (c) 2015-2016 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#ifndef __pinocchio_joint_prismatic_hpp__\n#define __pinocchio_joint_prismatic_hpp__\n\n#include \"pinocchio/macros.hpp\"\n#include \"pinocchio/multibody/joint/joint-base.hpp\"\n#include \"pinocchio/multibody/constraint.hpp\"\n#include \"pinocchio/spatial/inertia.hpp\"\n#include \"pinocchio/spatial/spatial-axis.hpp\"\n#include \"pinocchio/utils/axis-label.hpp\"\n\nnamespace pinocchio\n{\n  \n  template<typename Scalar, int Options, int _axis> struct MotionPrismaticTpl;\n  \n  template<typename Scalar, int Options, int axis>\n  struct SE3GroupAction< MotionPrismaticTpl<Scalar,Options,axis> >\n  {\n    typedef MotionTpl<Scalar,Options> ReturnType;\n  };\n  \n  template<typename Scalar, int Options, int axis, typename MotionDerived>\n  struct MotionAlgebraAction< MotionPrismaticTpl<Scalar,Options,axis>, MotionDerived>\n  {\n    typedef MotionTpl<Scalar,Options> ReturnType;\n  };\n\n  template<typename _Scalar, int _Options, int _axis>\n  struct traits < MotionPrismaticTpl<_Scalar,_Options,_axis> >\n  {\n    typedef _Scalar Scalar;\n    enum { Options = _Options };\n    typedef Eigen::Matrix<Scalar,3,1,Options> Vector3;\n    typedef Eigen::Matrix<Scalar,6,1,Options> Vector6;\n    typedef Eigen::Matrix<Scalar,6,6,Options> Matrix6;\n    typedef typename PINOCCHIO_EIGEN_REF_CONST_TYPE(Vector6) ToVectorConstReturnType;\n    typedef typename PINOCCHIO_EIGEN_REF_TYPE(Vector6) ToVectorReturnType;\n    typedef Vector3 AngularType;\n    typedef Vector3 LinearType;\n    typedef const Vector3 ConstAngularType;\n    typedef const Vector3 ConstLinearType;\n    typedef Matrix6 ActionMatrixType;\n    typedef MotionTpl<Scalar,Options> MotionPlain;\n    typedef MotionPlain PlainReturnType;\n    enum {\n      LINEAR = 0,\n      ANGULAR = 3\n    };\n  }; // struct traits MotionPrismaticTpl\n\n  template<typename _Scalar, int _Options, int _axis>\n  struct MotionPrismaticTpl\n  : MotionBase < MotionPrismaticTpl<_Scalar,_Options,_axis> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    MOTION_TYPEDEF_TPL(MotionPrismaticTpl);\n    \n    enum { axis = _axis };\n    \n    typedef SpatialAxis<_axis+LINEAR> Axis;\n    typedef typename Axis::CartesianAxis3 CartesianAxis3;\n\n    MotionPrismaticTpl() {}\n    MotionPrismaticTpl(const Scalar & v) : m_v(v) {}\n\n    inline PlainReturnType plain() const { return Axis() * m_v; }\n    \n    template<typename OtherScalar>\n    MotionPrismaticTpl __mult__(const OtherScalar & alpha) const\n    {\n      return MotionPrismaticTpl(alpha*m_v);\n    }\n    \n    template<typename Derived>\n    void addTo(MotionDense<Derived> & other) const\n    {\n      typedef typename MotionDense<Derived>::Scalar OtherScalar;\n      other.linear()[_axis] += (OtherScalar) m_v;\n    }\n    \n    template<typename MotionDerived>\n    void setTo(MotionDense<MotionDerived> & other) const\n    {\n      for(Eigen::DenseIndex k = 0; k < 3; ++k)\n        other.linear()[k] = k == axis ? m_v : (Scalar)0;\n      other.angular().setZero();\n    }\n    \n    template<typename S2, int O2, typename D2>\n    void se3Action_impl(const SE3Tpl<S2,O2> & m, MotionDense<D2> & v) const\n    {\n      v.angular().setZero();\n      v.linear().noalias() = m_v * (m.rotation().col(axis));\n    }\n    \n    template<typename S2, int O2>\n    MotionPlain se3Action_impl(const SE3Tpl<S2,O2> & m) const\n    {\n      MotionPlain res;\n      se3Action_impl(m,res);\n      return res;\n    }\n    \n    template<typename S2, int O2, typename D2>\n    void se3ActionInverse_impl(const SE3Tpl<S2,O2> & m, MotionDense<D2> & v) const\n    {\n      // Linear\n      v.linear().noalias() = m_v * (m.rotation().transpose().col(axis));\n      \n      // Angular\n      v.angular().setZero();\n    }\n    \n    template<typename S2, int O2>\n    MotionPlain se3ActionInverse_impl(const SE3Tpl<S2,O2> & m) const\n    {\n      MotionPlain res;\n      se3ActionInverse_impl(m,res);\n      return res;\n    }\n    \n    template<typename M1, typename M2>\n    void motionAction(const MotionDense<M1> & v, MotionDense<M2> & mout) const\n    {\n      // Linear\n      CartesianAxis3::alphaCross(-m_v,v.angular(),mout.linear());\n\n      // Angular\n      mout.angular().setZero();\n    }\n    \n    template<typename M1>\n    MotionPlain motionAction(const MotionDense<M1> & v) const\n    {\n      MotionPlain res;\n      motionAction(v,res);\n      return res;\n    }\n    \n    Scalar & linearRate() { return m_v; }\n    const Scalar & linearRate() const { return m_v; }\n    \n    bool isEqual_impl(const MotionPrismaticTpl & other) const\n    {\n      return m_v == other.m_v;\n    }\n    \n  protected:\n    \n    Scalar m_v;\n  }; // struct MotionPrismaticTpl\n\n  template<typename Scalar, int Options, int axis, typename MotionDerived>\n  typename MotionDerived::MotionPlain\n  operator+(const MotionPrismaticTpl<Scalar,Options,axis> & m1,\n            const MotionDense<MotionDerived> & m2)\n  {\n    typename MotionDerived::MotionPlain res(m2);\n    res += m1;\n    return res;\n  }\n  \n  template<typename MotionDerived, typename S2, int O2, int axis>\n  EIGEN_STRONG_INLINE\n  typename MotionDerived::MotionPlain\n  operator^(const MotionDense<MotionDerived> & m1, const MotionPrismaticTpl<S2,O2,axis> & m2)\n  {\n    return m2.motionAction(m1);\n  }\n  \n  template<typename Scalar, int Options, int axis> struct TransformPrismaticTpl;\n  \n  template<typename _Scalar, int _Options, int _axis>\n  struct traits< TransformPrismaticTpl<_Scalar,_Options,_axis> >\n  {\n    enum {\n      axis = _axis,\n      Options = _Options,\n      LINEAR = 0,\n      ANGULAR = 3\n    };\n    typedef _Scalar Scalar;\n    typedef SE3Tpl<Scalar,Options> PlainType;\n    typedef Eigen::Matrix<Scalar,3,1,Options> Vector3;\n    typedef Eigen::Matrix<Scalar,3,3,Options> Matrix3;\n    typedef typename Matrix3::IdentityReturnType AngularType;\n    typedef AngularType AngularRef;\n    typedef AngularType ConstAngularRef;\n    typedef Vector3 LinearType;\n    typedef const Vector3 LinearRef;\n    typedef const Vector3 ConstLinearRef;\n    typedef typename traits<PlainType>::ActionMatrixType ActionMatrixType;\n    typedef typename traits<PlainType>::HomogeneousMatrixType HomogeneousMatrixType;\n  }; // traits TransformPrismaticTpl\n  \n  template<typename Scalar, int Options, int axis>\n  struct SE3GroupAction< TransformPrismaticTpl<Scalar,Options,axis> >\n  { typedef typename traits <TransformPrismaticTpl<Scalar,Options,axis> >::PlainType ReturnType; };\n\n  template<typename _Scalar, int _Options, int axis>\n  struct TransformPrismaticTpl : SE3Base< TransformPrismaticTpl<_Scalar,_Options,axis> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    PINOCCHIO_SE3_TYPEDEF_TPL(TransformPrismaticTpl);\n    typedef typename traits<TransformPrismaticTpl>::PlainType PlainType;\n    \n    typedef SpatialAxis<axis+LINEAR> Axis;\n    typedef typename Axis::CartesianAxis3 CartesianAxis3;\n    \n    TransformPrismaticTpl() {}\n    TransformPrismaticTpl(const Scalar & displacement)\n    : m_displacement(displacement)\n    {}\n    \n    PlainType plain() const\n    {\n      PlainType res(PlainType::Identity());\n      res.rotation().setIdentity();\n      res.translation()[axis] = m_displacement;\n      \n      return res;\n    }\n    \n    operator PlainType() const { return plain(); }\n    \n    template<typename S2, int O2>\n    typename SE3GroupAction<TransformPrismaticTpl>::ReturnType\n    se3action(const SE3Tpl<S2,O2> & m) const\n    {\n      typedef typename SE3GroupAction<TransformPrismaticTpl>::ReturnType ReturnType;\n      ReturnType res(m);\n      res.translation()[axis] += m_displacement;\n      \n      return res;\n    }\n    \n    const Scalar & displacement() const { return m_displacement; }\n    Scalar & displacement() { return m_displacement; }\n    \n    ConstLinearRef translation() const { return CartesianAxis3()*displacement(); };\n    AngularType rotation() const { return AngularType(3,3); }\n    \n    bool isEqual(const TransformPrismaticTpl & other) const\n    {\n      return m_displacement == other.m_displacement;\n    }\n\n  protected:\n    \n    Scalar m_displacement;\n  };\n\n  template<typename Scalar, int Options, int axis> struct ConstraintPrismaticTpl;\n  \n  template<typename _Scalar, int _Options, int axis>\n  struct traits< ConstraintPrismaticTpl<_Scalar,_Options,axis> >\n  {\n    typedef _Scalar Scalar;\n    enum { Options = _Options };\n    enum {\n      LINEAR = 0,\n      ANGULAR = 3\n    };\n    typedef MotionPrismaticTpl<Scalar,Options,axis> JointMotion;\n    typedef Eigen::Matrix<Scalar,1,1,Options> JointForce;\n    typedef Eigen::Matrix<Scalar,6,1,Options> DenseBase;\n    typedef DenseBase MatrixReturnType;\n    typedef const DenseBase ConstMatrixReturnType;\n  }; // traits ConstraintRevolute\n  \n  template<typename Scalar, int Options, int axis>\n  struct SE3GroupAction< ConstraintPrismaticTpl<Scalar,Options,axis> >\n  { typedef Eigen::Matrix<Scalar,6,1,Options> ReturnType; };\n  \n  template<typename Scalar, int Options, int axis, typename MotionDerived>\n  struct MotionAlgebraAction< ConstraintPrismaticTpl<Scalar,Options,axis>, MotionDerived >\n  { typedef Eigen::Matrix<Scalar,6,1,Options> ReturnType; };\n\n  template<typename Scalar, int Options, int axis, typename ForceDerived>\n  struct ConstraintForceOp< ConstraintPrismaticTpl<Scalar,Options,axis>, ForceDerived>\n  { typedef typename ForceDense<ForceDerived>::ConstLinearType::template ConstFixedSegmentReturnType<1>::Type ReturnType; };\n  \n  template<typename Scalar, int Options, int axis, typename ForceSet>\n  struct ConstraintForceSetOp< ConstraintPrismaticTpl<Scalar,Options,axis>, ForceSet>\n  { typedef typename Eigen::MatrixBase<ForceSet>::ConstRowXpr ReturnType; };\n\n  template<typename _Scalar, int _Options, int axis>\n  struct ConstraintPrismaticTpl\n  : ConstraintBase < ConstraintPrismaticTpl <_Scalar,_Options,axis> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    PINOCCHIO_CONSTRAINT_TYPEDEF_TPL(ConstraintPrismaticTpl)\n    enum { NV = 1 };\n    \n    typedef SpatialAxis<LINEAR+axis> Axis;\n    \n    ConstraintPrismaticTpl() {};\n\n    template<typename Vector1Like>\n    JointMotion __mult__(const Eigen::MatrixBase<Vector1Like> & v) const\n    {\n      EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector1Like,1);\n      assert(v.size() == 1);\n      return JointMotion(v[0]);\n    }\n\n    template<typename S2, int O2>\n    typename SE3GroupAction<ConstraintPrismaticTpl>::ReturnType\n    se3Action(const SE3Tpl<S2,O2> & m) const\n    { \n      typename SE3GroupAction<ConstraintPrismaticTpl>::ReturnType res;\n      MotionRef<DenseBase> v(res);\n      v.linear() = m.rotation().col(axis);\n      v.angular().setZero();\n      return res;\n    }\n    \n    template<typename S2, int O2>\n    typename SE3GroupAction<ConstraintPrismaticTpl>::ReturnType\n    se3ActionInverse(const SE3Tpl<S2,O2> & m) const\n    {\n      typename SE3GroupAction<ConstraintPrismaticTpl>::ReturnType res;\n      MotionRef<DenseBase> v(res);\n      v.linear() = m.rotation().transpose().col(axis);\n      v.angular().setZero();\n      return res;\n    }\n\n    int nv_impl() const { return NV; }\n\n    struct TransposeConst\n    {\n      const ConstraintPrismaticTpl & ref; \n      TransposeConst(const ConstraintPrismaticTpl & ref) : ref(ref) {}\n\n      template<typename ForceDerived>\n      typename ConstraintForceOp<ConstraintPrismaticTpl,ForceDerived>::ReturnType\n      operator* (const ForceDense<ForceDerived> & f) const\n      { return f.linear().template segment<1>(axis); }\n\n      /* [CRBA]  MatrixBase operator* (Constraint::Transpose S, ForceSet::Block) */\n      template<typename Derived>\n      typename ConstraintForceSetOp<ConstraintPrismaticTpl,Derived>::ReturnType\n      operator*(const Eigen::MatrixBase<Derived> & F )\n      {\n        assert(F.rows()==6);\n        return F.row(LINEAR+axis);\n      }\n\n    }; // struct TransposeConst\n    TransposeConst transpose() const { return TransposeConst(*this); }\n\n    /* CRBA joint operators\n     *   - ForceSet::Block = ForceSet\n     *   - ForceSet operator* (Inertia Y,Constraint S)\n     *   - MatrixBase operator* (Constraint::Transpose S, ForceSet::Block)\n     *   - SE3::act(ForceSet::Block)\n     */\n    DenseBase matrix_impl() const\n    {\n      DenseBase S;\n      MotionRef<DenseBase> v(S);\n      v << Axis();\n      return S;\n    }\n    \n    template<typename MotionDerived>\n    typename MotionAlgebraAction<ConstraintPrismaticTpl,MotionDerived>::ReturnType\n    motionAction(const MotionDense<MotionDerived> & m) const\n    {\n      typename MotionAlgebraAction<ConstraintPrismaticTpl,MotionDerived>::ReturnType res;\n      MotionRef<DenseBase> v(res);\n      v = m.cross(Axis());\n      return res;\n    }\n    \n    bool isEqual(const ConstraintPrismaticTpl &) const { return true; }\n\n  }; // struct ConstraintPrismaticTpl\n  \n  template<typename S1, int O1,typename S2, int O2, int axis>\n  struct MultiplicationOp<InertiaTpl<S1,O1>, ConstraintPrismaticTpl<S2,O2,axis> >\n  {\n    typedef Eigen::Matrix<S2,6,1,O2> ReturnType;\n  };\n  \n  /* [CRBA] ForceSet operator* (Inertia Y,Constraint S) */\n  namespace impl\n  {\n    template<typename S1, int O1, typename S2, int O2>\n    struct LhsMultiplicationOp<InertiaTpl<S1,O1>, ConstraintPrismaticTpl<S2,O2,0> >\n    {\n      typedef InertiaTpl<S1,O1> Inertia;\n      typedef ConstraintPrismaticTpl<S2,O2,0> Constraint;\n      typedef typename MultiplicationOp<Inertia,Constraint>::ReturnType ReturnType;\n      static inline ReturnType run(const Inertia & Y,\n                                   const Constraint & /*constraint*/)\n      {\n        ReturnType res;\n        \n        /* Y(:,0) = ( 1,0, 0, 0 , z , -y ) */\n        const S1\n        &m = Y.mass(),\n        &y = Y.lever()[1],\n        &z = Y.lever()[2];\n        res << m, S1(0), S1(0), S1(0), m*z, -m*y;\n        \n        return res;\n      }\n    };\n    \n    template<typename S1, int O1, typename S2, int O2>\n    struct LhsMultiplicationOp<InertiaTpl<S1,O1>, ConstraintPrismaticTpl<S2,O2,1> >\n    {\n      typedef InertiaTpl<S1,O1> Inertia;\n      typedef ConstraintPrismaticTpl<S2,O2,1> Constraint;\n      typedef typename MultiplicationOp<Inertia,Constraint>::ReturnType ReturnType;\n      static inline ReturnType run(const Inertia & Y,\n                                   const Constraint & /*constraint*/)\n      {\n        ReturnType res;\n        \n        /* Y(:,1) = ( 0,1, 0, -z , 0 , x) */\n        const S1\n        &m = Y.mass(),\n        &x = Y.lever()[0],\n        &z = Y.lever()[2];\n        \n        res << S1(0), m, S1(0), -m*z, S1(0), m*x;\n        \n        return res;\n      }\n    };\n    \n    template<typename S1, int O1, typename S2, int O2>\n    struct LhsMultiplicationOp<InertiaTpl<S1,O1>, ConstraintPrismaticTpl<S2,O2,2> >\n    {\n      typedef InertiaTpl<S1,O1> Inertia;\n      typedef ConstraintPrismaticTpl<S2,O2,2> Constraint;\n      typedef typename MultiplicationOp<Inertia,Constraint>::ReturnType ReturnType;\n      static inline ReturnType run(const Inertia & Y,\n                                   const Constraint & /*constraint*/)\n      {\n        ReturnType res;\n        \n        /* Y(:,2) = ( 0,0, 1, y , -x , 0) */\n        const S1\n        &m = Y.mass(),\n        &x = Y.lever()[0],\n        &y = Y.lever()[1];\n        \n        res << S1(0), S1(0), m, m*y, -m*x, S1(0);\n        \n        return res;\n      }\n    };\n  } // namespace impl\n  \n  template<typename M6Like,typename S2, int O2, int axis>\n  struct MultiplicationOp<Eigen::MatrixBase<M6Like>, ConstraintPrismaticTpl<S2,O2,axis> >\n  {\n    typedef typename M6Like::ConstColXpr ReturnType;\n  };\n  \n  /* [ABA] operator* (Inertia Y,Constraint S) */\n  namespace impl\n  {\n    template<typename M6Like, typename Scalar, int Options, int axis>\n    struct LhsMultiplicationOp<Eigen::MatrixBase<M6Like>, ConstraintPrismaticTpl<Scalar,Options,axis> >\n    {\n      typedef ConstraintPrismaticTpl<Scalar,Options,axis> Constraint;\n      typedef typename MultiplicationOp<Eigen::MatrixBase<M6Like>,Constraint>::ReturnType ReturnType;\n      static inline ReturnType run(const Eigen::MatrixBase<M6Like> & Y,\n                             const Constraint & /*constraint*/)\n      {\n        EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(M6Like,6,6);\n        return Y.derived().col(Inertia::LINEAR + axis);\n      }\n    };\n  } // namespace impl\n  \n  template<typename _Scalar, int _Options, int _axis>\n  struct JointPrismaticTpl\n  {\n    typedef _Scalar Scalar;\n    \n    enum\n    {\n      Options = _Options,\n      axis = _axis\n    };\n  };\n\n  template<typename _Scalar, int _Options, int axis>\n  struct traits< JointPrismaticTpl<_Scalar,_Options,axis> >\n  {\n    enum {\n      NQ = 1,\n      NV = 1\n    };\n    typedef _Scalar Scalar;\n    enum { Options = _Options };\n    typedef JointDataPrismaticTpl<Scalar,Options,axis> JointDataDerived;\n    typedef JointModelPrismaticTpl<Scalar,Options,axis> JointModelDerived;\n    typedef ConstraintPrismaticTpl<Scalar,Options,axis> Constraint_t;\n    typedef TransformPrismaticTpl<Scalar,Options,axis> Transformation_t;\n    typedef MotionPrismaticTpl<Scalar,Options,axis> Motion_t;\n    typedef MotionZeroTpl<Scalar,Options> Bias_t;\n\n    // [ABA]\n    typedef Eigen::Matrix<Scalar,6,NV,Options> U_t;\n    typedef Eigen::Matrix<Scalar,NV,NV,Options> D_t;\n    typedef Eigen::Matrix<Scalar,6,NV,Options> UD_t;\n    \n    PINOCCHIO_JOINT_DATA_BASE_ACCESSOR_DEFAULT_RETURN_TYPE\n\n    typedef Eigen::Matrix<Scalar,NQ,1,Options> ConfigVector_t;\n    typedef Eigen::Matrix<Scalar,NV,1,Options> TangentVector_t;\n  };\n\n  template<typename Scalar, int Options, int axis>\n  struct traits< JointDataPrismaticTpl<Scalar,Options,axis> >\n  { typedef JointPrismaticTpl<Scalar,Options,axis> JointDerived; };\n  \n  template<typename Scalar, int Options, int axis>\n  struct traits< JointModelPrismaticTpl<Scalar,Options,axis> >\n  { typedef JointPrismaticTpl<Scalar,Options,axis> JointDerived; };\n\n  template<typename _Scalar, int _Options, int axis>\n  struct JointDataPrismaticTpl : public JointDataBase< JointDataPrismaticTpl<_Scalar,_Options,axis> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    typedef JointPrismaticTpl<_Scalar,_Options,axis> JointDerived;\n    PINOCCHIO_JOINT_DATA_TYPEDEF_TEMPLATE(JointDerived);\n    PINOCCHIO_JOINT_DATA_BASE_DEFAULT_ACCESSOR\n\n    Constraint_t S;\n    Transformation_t M;\n    Motion_t v;\n    Bias_t c;\n\n    // [ABA] specific data\n    U_t U;\n    D_t Dinv;\n    UD_t UDinv;\n\n    JointDataPrismaticTpl()\n    : M((Scalar)0)\n    , v((Scalar)0)\n    , U(U_t::Zero())\n    , Dinv(D_t::Zero())\n    , UDinv(UD_t::Zero())\n    {}\n\n    static std::string classname()\n    {\n      return std::string(\"JointDataP\") + axisLabel<axis>();\n    }\n    std::string shortname() const { return classname(); }\n\n  }; // struct JointDataPrismaticTpl\n  \n  template<typename NewScalar, typename Scalar, int Options, int axis>\n  struct CastType< NewScalar, JointModelPrismaticTpl<Scalar,Options,axis> >\n  {\n    typedef JointModelPrismaticTpl<NewScalar,Options,axis> type;\n  };\n\n  template<typename _Scalar, int _Options, int axis>\n  struct JointModelPrismaticTpl\n  : public JointModelBase< JointModelPrismaticTpl<_Scalar,_Options,axis> >\n  {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    typedef JointPrismaticTpl<_Scalar,_Options,axis> JointDerived;\n    PINOCCHIO_JOINT_TYPEDEF_TEMPLATE(JointDerived);\n    \n    typedef JointModelBase<JointModelPrismaticTpl> Base;\n    using Base::id;\n    using Base::idx_q;\n    using Base::idx_v;\n    using Base::setIndexes;\n    \n    JointDataDerived createData() const { return JointDataDerived(); }\n    \n    template<typename ConfigVector>\n    void calc(JointDataDerived & data,\n              const typename Eigen::MatrixBase<ConfigVector> & qs) const\n    {\n      typedef typename ConfigVector::Scalar Scalar;\n      const Scalar & q = qs[idx_q()];\n      data.M.displacement() = q;\n    }\n\n    template<typename ConfigVector, typename TangentVector>\n    void calc(JointDataDerived & data,\n              const typename Eigen::MatrixBase<ConfigVector> & qs,\n              const typename Eigen::MatrixBase<TangentVector> & vs) const\n    {\n      calc(data,qs.derived());\n      \n      typedef typename TangentVector::Scalar S2;\n      const S2 & v = vs[idx_v()];\n      data.v.linearRate() = v;\n    }\n    \n    template<typename Matrix6Like>\n    void calc_aba(JointDataDerived & data, const Eigen::MatrixBase<Matrix6Like> & I, const bool update_I) const\n    {\n      data.U = I.col(Inertia::LINEAR + axis);\n      data.Dinv[0] = 1./I(Inertia::LINEAR + axis, Inertia::LINEAR + axis);\n      data.UDinv.noalias() = data.U * data.Dinv[0];\n      \n      if (update_I)\n        PINOCCHIO_EIGEN_CONST_CAST(Matrix6Like,I) -= data.UDinv * data.U.transpose();\n    }\n    \n    static std::string classname()\n    {\n      return std::string(\"JointModelP\") + axisLabel<axis>();\n    }\n    std::string shortname() const { return classname(); }\n    \n    /// \\returns An expression of *this with the Scalar type casted to NewScalar.\n    template<typename NewScalar>\n    JointModelPrismaticTpl<NewScalar,Options,axis> cast() const\n    {\n      typedef JointModelPrismaticTpl<NewScalar,Options,axis> ReturnType;\n      ReturnType res;\n      res.setIndexes(id(),idx_q(),idx_v());\n      return res;\n    }\n\n  }; // struct JointModelPrismaticTpl\n\n  typedef JointPrismaticTpl<double,0,0> JointPX;\n  typedef JointDataPrismaticTpl<double,0,0> JointDataPX;\n  typedef JointModelPrismaticTpl<double,0,0> JointModelPX;\n\n  typedef JointPrismaticTpl<double,0,1> JointPY;\n  typedef JointDataPrismaticTpl<double,0,1> JointDataPY;\n  typedef JointModelPrismaticTpl<double,0,1> JointModelPY;\n\n  typedef JointPrismaticTpl<double,0,2> JointPZ;\n  typedef JointDataPrismaticTpl<double,0,2> JointDataPZ;\n  typedef JointModelPrismaticTpl<double,0,2> JointModelPZ;\n\n} //namespace pinocchio\n\n#include <boost/type_traits.hpp>\n\nnamespace boost\n{\n  template<typename Scalar, int Options, int axis>\n  struct has_nothrow_constructor< ::pinocchio::JointModelPrismaticTpl<Scalar,Options,axis> >\n  : public integral_constant<bool,true> {};\n  \n  template<typename Scalar, int Options, int axis>\n  struct has_nothrow_copy< ::pinocchio::JointModelPrismaticTpl<Scalar,Options,axis> >\n  : public integral_constant<bool,true> {};\n  \n  template<typename Scalar, int Options, int axis>\n  struct has_nothrow_constructor< ::pinocchio::JointDataPrismaticTpl<Scalar,Options,axis> >\n  : public integral_constant<bool,true> {};\n  \n  template<typename Scalar, int Options, int axis>\n  struct has_nothrow_copy< ::pinocchio::JointDataPrismaticTpl<Scalar,Options,axis> >\n  : public integral_constant<bool,true> {};\n}\n\n#endif // ifndef __pinocchio_joint_prismatic_hpp__\n", "meta": {"hexsha": "48372cf743b2947614c3e3e8d6ac0c354f9fa249", "size": 22322, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multibody/joint/joint-prismatic.hpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "src/multibody/joint/joint-prismatic.hpp", "max_issues_repo_name": "yDMhaven/pinocchio", "max_issues_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "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/multibody/joint/joint-prismatic.hpp", "max_forks_repo_name": "yDMhaven/pinocchio", "max_forks_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "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": 33.0207100592, "max_line_length": 124, "alphanum_fraction": 0.6839888899, "num_tokens": 5727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.046033903380812265, "lm_q1q2_score": 0.022657341084953216}}
{"text": "/**\n * Copyright (c) 2013 Jonan Cruz-Martin\n * \n * Distributed under the terms of the MIT license, see the accompanying\n * file COPYING or http://opensource.org/licenses/MIT.\n * \n * @file\n * @brief Implement uniform refinement of a domain.\n * \n * This module provides the `refine_uniformly` function for triangular and tetrahedral domains. This\n * function refines all edges of the given domain and segmentation.\n */\n\n#ifndef ALGORITHMS_REFINE_UNIFORMLY_HPP\n#define ALGORITHMS_REFINE_UNIFORMLY_HPP\n\n#include \"../domains/linear.hpp\"\n#include \"../domains/triangular.hpp\"\n#include \"../domains/quadrilateral.hpp\"\n#include \"../domains/tetrahedral.hpp\"\n\n#include \"../segmentations/linear.hpp\"\n#include \"../segmentations/triangular.hpp\"\n#include \"../segmentations/quadrilateral.hpp\"\n#include \"../segmentations/tetrahedral.hpp\"\n\n#include <boost/python.hpp>\nusing namespace boost::python;\n\n////////////////\n// Triangular //\n////////////////\n\n/**\n * Refine all edges of the given triangular cartesian 2D domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TriangularCartesian2D_Domain_refine_uniformly(TriangularCartesian2D_Domain domain_in, TriangularCartesian2D_Segmentation segmentation_in);\n\n/**\n * Refine all edges of the given triangular cartesian 3D domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TriangularCartesian3D_Domain_refine_uniformly(TriangularCartesian3D_Domain domain_in, TriangularCartesian3D_Segmentation segmentation_in);\n\n/**\n * Refine all edges of the given triangular cylindrical domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TriangularCylindrical3D_Domain_refine_uniformly(TriangularCylindrical3D_Domain domain_in, TriangularCylindrical3D_Segmentation segmentation_in);\n\n/**\n * Refine all edges of the given triangular polar domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TriangularPolar2D_Domain_refine_uniformly(TriangularPolar2D_Domain domain_in, TriangularPolar2D_Segmentation segmentation_in);\n\n/**\n * Refine all edges of the given triangular spherical domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TriangularSpherical3D_Domain_refine_uniformly(TriangularSpherical3D_Domain domain_in, TriangularSpherical3D_Segmentation segmentation_in);\n\n/////////////////\n// Tetrahedral //\n/////////////////\n\n/**\n * Refine all edges of the given tetrahedral cartesian 3D domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TetrahedralCartesian3D_Domain_refine_uniformly(TetrahedralCartesian3D_Domain domain_in, TetrahedralCartesian3D_Segmentation segmentation_in);\n\n/**\n * Refine all edges of the given tetrahedral cylindrical domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TetrahedralCylindrical3D_Domain_refine_uniformly(TetrahedralCylindrical3D_Domain domain_in, TetrahedralCylindrical3D_Segmentation segmentation_in);\n\n/**\n * Refine all edges of the given tetrahedral spherical domain and segmentation.\n * \n * @param domain_in Domain to be refined.\n * @param segmentation_in Segmentation of the domain to be refined.\n * @return Python tuple with two elements:\n *         1. the refined domain, and\n *         2. the refined segmentation.\n * \n * @since 0.1.0\n */\ntuple TetrahedralSpherical3D_Domain_refine_uniformly(TetrahedralSpherical3D_Domain domain_in, TetrahedralSpherical3D_Segmentation segmentation_in);\n\n#endif /* end of include guard: ALGORITHMS_REFINE_UNIFORMLY_HPP */\n", "meta": {"hexsha": "d1dbd52cb76c5cff7a63c803f65945bd29fe7c56", "size": 4980, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/algorithms/refine_uniformly.hpp", "max_stars_repo_name": "jonancm/viennagrid-python", "max_stars_repo_head_hexsha": "a56f23ab65cf82b2f06ff546d45c056bb9d326b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithms/refine_uniformly.hpp", "max_issues_repo_name": "jonancm/viennagrid-python", "max_issues_repo_head_hexsha": "a56f23ab65cf82b2f06ff546d45c056bb9d326b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-05-13T08:28:52.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-13T08:28:52.000Z", "max_forks_repo_path": "src/algorithms/refine_uniformly.hpp", "max_forks_repo_name": "jonancm/viennagrid-python", "max_forks_repo_head_hexsha": "a56f23ab65cf82b2f06ff546d45c056bb9d326b2", "max_forks_repo_licenses": ["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.8251748252, "max_line_length": 153, "alphanum_fraction": 0.7437751004, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.04672495663492165, "lm_q1q2_score": 0.02263263843266179}}
{"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__UTILS__SPARSE_HPP_\n#define SMOOTH__FEEDBACK__UTILS__SPARSE_HPP_\n\n/**\n * @file\n * @brief Sparse matrix utilities.\n */\n\n#include <Eigen/Sparse>\n\n#include <numeric>\n#include <optional>\n\nnamespace smooth::feedback {\n\n/**\n * @brief Add block into a sparse matrix.\n *\n * After this function the output variable dest is s.t.\n *\n * dest[row0 + r, col0 + c] += scale * source[r, c]\n *\n * @param dest destination\n * @param row0 starting row for block\n * @param col0 starting column for block\n * @param source block values\n * @param scale scaling parameter\n * @param upper_only only add into upper triangular part\n *\n * @note Values are accessed with coeffRef().\n */\ntemplate<typename Source, int Options>\n  requires(std::is_base_of_v<Eigen::EigenBase<Source>, Source>)\ninline void block_add(\n  Eigen::SparseMatrix<double, Options> & dest,\n  Eigen::Index row0,\n  Eigen::Index col0,\n  const Source & source,\n  double scale      = 1,\n  double upper_only = false)\n{\n  for (auto c = 0; c < source.outerSize(); ++c) {\n    for (Eigen::InnerIterator it(source, c); it; ++it) {\n      if (!upper_only || row0 + it.row() <= col0 + it.col()) {\n        dest.coeffRef(row0 + it.row(), col0 + it.col()) += scale * it.value();\n      }\n    }\n  }\n}\n\n/**\n * @brief Write block into a sparse matrix.\n *\n * After this function the output variable dest is s.t.\n *\n * dest[row0 + r, col0 + c] = scale * source[r, c]\n *\n * @param dest destination\n * @param row0 starting row for block\n * @param col0 starting column for block\n * @param source block values\n * @param scale scaling parameter\n * @param upper_only only add into upper triangular part\n *\n * @note Values are accessed with coeffRef().\n */\ntemplate<typename Source, int Options>\n  requires(std::is_base_of_v<Eigen::EigenBase<Source>, Source>)\ninline void block_write(\n  Eigen::SparseMatrix<double, Options> & dest,\n  Eigen::Index row0,\n  Eigen::Index col0,\n  const Source & source,\n  double scale      = 1,\n  double upper_only = false)\n{\n  for (auto c = 0; c < source.outerSize(); ++c) {\n    for (Eigen::InnerIterator it(source, c); it; ++it) {\n      if (!upper_only || row0 + it.row() <= col0 + it.col()) {\n        dest.coeffRef(row0 + it.row(), col0 + it.col()) = scale * it.value();\n      }\n    }\n  }\n}\n\n/**\n * @brief Add identity matrix block into sparse matrix.\n *\n * After this function the output variable dest is s.t.\n *\n * dest[row0 + k, col0 + k] += scale, k = 0...n-1\n *\n * @param dest destination\n * @param row0 starting row for block\n * @param col0 starting column for block\n * @param n size of identity matrix\n * @param scale scaling parameter\n *\n * @note Values are accessed with coeffRef().\n */\ntemplate<int Options>\ninline void block_add_identity(\n  Eigen::SparseMatrix<double, Options> & dest,\n  Eigen::Index row0,\n  Eigen::Index col0,\n  Eigen::Index n,\n  double scale = 1)\n{\n  for (auto k = 0u; k < n; ++k) { dest.coeffRef(row0 + k, col0 + k) += scale; }\n}\n\n/**\n * @brief Write identity matrix block into sparse matrix.\n *\n * After this function the output variable dest is s.t.\n *\n * dest[row0 + k, col0 + k] += scale, k = 0...n-1\n *\n * @param dest destination\n * @param row0 starting row for block\n * @param col0 starting column for block\n * @param n size of identity matrix\n * @param scale scaling parameter\n *\n * @note Values are accessed with coeffRef().\n */\ntemplate<int Options>\ninline void block_write_identity(\n  Eigen::SparseMatrix<double, Options> & dest,\n  Eigen::Index row0,\n  Eigen::Index col0,\n  Eigen::Index n,\n  double scale = 1)\n{\n  for (auto k = 0u; k < n; ++k) { dest.coeffRef(row0 + k, col0 + k) = scale; }\n}\n\n/**\n * @brief Zero a sparse matrix expression without changing allocation.\n *\n * @note Expression must be write-able.\n *\n * @note More efficient for compressed expressions.\n */\ntemplate<typename SparseMat>\n  requires(std::is_base_of_v<\n           Eigen::SparseCompressedBase<std::decay_t<SparseMat>>,\n           std::decay_t<SparseMat>>)\ninline void set_zero(SparseMat && mat)\n{\n  if (mat.isCompressed()) {\n    mat.coeffs().setZero();\n  } else {\n    for (auto i = 0; i < mat.outerSize(); ++i) {\n      for (typename std::decay_t<decltype(mat)>::InnerIterator it(mat, i); it; ++it) {\n        it.valueRef() = 0;\n      }\n    }\n  }\n}\n\n/**\n * @brief Count number of explicit zeros in sparse matrix.\n *\n * @param mat sparse matrix\n */\ntemplate<typename Mat>\n  requires(std::is_base_of_v<Eigen::EigenBase<Mat>, Mat>)\nuint64_t count_explicit_zeros(const Mat & mat)\n{\n  uint64_t ret = 0;\n  for (auto c = 0; c < mat.outerSize(); ++c) {\n    for (Eigen::InnerIterator it(mat, c); it; ++it) {\n      if (it.value() == 0) { ++ret; }\n    }\n  }\n  return ret;\n}\n\n/**\n * @brief Mark explicit zeros in sparse matrix.\n *\n * @param mat sparse matrix\n *\n * Returns a matrix that has values as follows:\n *  - 0 for implicit zeros\n *  - 1 for non-zeros\n *  - 9 for explicit zeros\n */\ntemplate<typename Mat>\n  requires(std::is_base_of_v<Eigen::EigenBase<Mat>, Mat>)\nEigen::MatrixX<typename Mat::Scalar> mark_explicit_zeros(const Mat & mat)\n{\n  Eigen::MatrixX<typename Mat::Scalar> ret;\n  ret.setConstant(mat.rows(), mat.cols(), 0);\n  for (auto c = 0; c < mat.outerSize(); ++c) {\n    for (Eigen::InnerIterator it(mat, c); it; ++it) {\n      if (it.value() == 0) {\n        ret(it.row(), it.col()) = 9;\n      } else {\n        ret(it.row(), it.col()) = 1;\n      }\n    }\n  }\n  return ret;\n}\n\n/**\n * @brief (Right) Hessian of composed function \\f$ (f \\circ g)(x) \\f$.\n *\n * @param[out] out result                           [No x No*Nx]\n * @param[in] Jf (Right) Jacobian of f at y = g(x)  [No x Ny   ]\n * @param[in] Hf (Right) Hessian of f at y = g(x)   [Ny x No*Ny]\n * @param[in] Jg (Right) Jacobian of g at x         [Ny x Nx   ]\n * @param[in] Hg (Right) Hessian of g at x          [Nx x Ny*Nx]\n * @param[in] r0 row to insert result\n * @param[in] r0 col to insert result\n *\n * @note out must have appropriate size\n */\ntemplate<typename S1, typename S2, typename S3, typename S4>\n  requires(\n    std::is_base_of_v<Eigen::EigenBase<S1>, S1> && std::is_base_of_v<Eigen::EigenBase<S2>, S2> &&\n      std::is_base_of_v<Eigen::EigenBase<S3>, S3> && std::is_base_of_v<Eigen::EigenBase<S4>, S4>)\ninline void d2r_fog(\n  Eigen::SparseMatrix<double> & out,\n  const S1 & Jf,\n  const S2 & Hf,\n  const S3 & Jg,\n  const S4 & Hg,\n  Eigen::Index r0 = 0,\n  Eigen::Index c0 = 0)\n{\n  const auto No = Jf.rows();\n  const auto Ny = Jf.cols();\n\n  [[maybe_unused]] const auto Ni = Jg.rows();\n  const auto Nx                  = Jg.cols();\n\n  // check some dimensions\n  assert(Ny == Ni);\n  assert(Hf.rows() == Ny);\n  assert(Hf.cols() == No * Ny);\n  assert(Hg.rows() == Nx);\n  assert(Hg.cols() == Ni * Nx);\n\n  for (auto no = 0u; no < No; ++no) {\n    // TODO sparse-sparse-sparse product is expensive and allocates temporary\n    block_add(out, r0, c0 + no * Nx, Jg.transpose() * Hf.middleCols(no * Ny, Ny) * Jg);\n  }\n\n  for (auto i = 0u; i < Jf.outerSize(); ++i) {\n    for (Eigen::InnerIterator it(Jf, i); it; ++it) {\n      block_add(out, r0, c0 + it.row() * Nx, Hg.middleCols(it.col() * Nx, Nx), it.value());\n    }\n  }\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__UTILS__SPARSE_HPP_\n", "meta": {"hexsha": "0c7ad5e24bfbc5df3cf6912554ba673863db3dae", "size": 8429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/utils/sparse.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/utils/sparse.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/utils/sparse.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.3693379791, "max_line_length": 97, "alphanum_fraction": 0.6495432436, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.05921025115631602, "lm_q1q2_score": 0.022572106263728495}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <gtkmm.h>\n#include \"gui.h\"\n#include <fstream>\n\nusing namespace std;\nusing Eigen::MatrixXd;\n\nint main(int argc, char *argv[]) {\n    /// \n    /// The main function shall be responsible for calling various other functions and instantiating the classes for using their functions cop290\n    ///\n        \n    // check3Dfile();\n    auto app =\n        Gtk::Application::create(argc, argv,\n        \"org.gtkmm.examples\");\n    MainWindow window;\n    return app->run(window);\n    // check2D();\n    // return 0;\n}\n\nint check3D() {\n    double thisarr [4] = {0,1,0,0};\n    Object3D obj;\n    Point v1,v2,v3,v4,v5;\n    v1.setCoordinates(2,2,0);\n    v2.setCoordinates(2,1,0);\n    v3.setCoordinates(1,1,0);\n    v4.setCoordinates(2,1,1); \n    v5.setCoordinates(1,1,1);\n    obj.vertices.push_back(v1);\n    obj.vertices.push_back(v2);\n    obj.vertices.push_back(v3);\n    obj.vertices.push_back(v4);\n    obj.vertices.push_back(v5);\n    Edge e1,e2,e3,e4,e5,e6,e7,e8;\n    e1.p1 = v1; e1.p2 = v2; e2.p1 = v1; e2.p2 = v3;\n    e3.p1 = v1; e3.p2 = v4; e4.p1 = v1; e4.p2 = v5;\n    e5.p1 = v2; e5.p2 = v4; e6.p1 = v2; e6.p2 = v3;\n    e7.p1 = v4; e7.p2 = v5; e8.p1 = v3; e8.p2 = v5;\n    obj.edges.push_back(e1);\n    obj.edges.push_back(e2);\n    obj.edges.push_back(e3);\n    obj.edges.push_back(e4);\n    obj.edges.push_back(e5);\n    obj.edges.push_back(e6);\n    obj.edges.push_back(e7);\n    obj.edges.push_back(e8);\n    Face f1,f2,f3,f4,f5;\n    f1.vertices.push_back(0);\n    f1.vertices.push_back(1);\n    f1.vertices.push_back(2);\n    f2.vertices.push_back(0);\n    f2.vertices.push_back(1);\n    f2.vertices.push_back(3);\n    f3.vertices.push_back(0);\n    f3.vertices.push_back(3);\n    f3.vertices.push_back(4);\n    f4.vertices.push_back(0);\n    f4.vertices.push_back(2);\n    f4.vertices.push_back(4);\n    f5.vertices.push_back(1);\n    f5.vertices.push_back(2);\n    f5.vertices.push_back(3);\n    f5.vertices.push_back(4);\n    obj.faces.push_back(f1);\n    obj.faces.push_back(f2);\n    obj.faces.push_back(f3);\n    obj.faces.push_back(f4);\n    obj.faces.push_back(f5);\n    PlaneProjection* p = obj.project3D(thisarr);\n    cout << \"Projection: \" << *p << endl;\n    p->rotatePlane();\n    cout << \"Rotated Projection: \" << *p << endl;\n    return 0;\n}\n\nPlaneProjection* input3Dfile(string filename){\n    ///\n    /// Function to get input of the 3D Object from file\n    ///\n    ifstream inFile (filename);\n    string output;\n    Object3D obj;\n    double planearr [4];\n    if(!(inFile.is_open())){\n        cout<< \"not started\" <<endl;\n    }\n    map<string, int> labeltoindex;\n    if(inFile.is_open()){\n        cout << \"start file\"<<endl;\n        if(!inFile.eof()){\n            inFile >> output;\n            cout<< \"getting vertices\"<<endl;\n            if(output==\"Vertices\"){\n                // inFile>> output;\n                int tempindex = 0;\n                while(output!=\";\"){\n                    inFile >> output;\n                    double n1 = atof(output.c_str());\n                    inFile >> output;\n                    double n2 = atof(output.c_str());\n                    inFile >> output;\n                    double n3 = atof(output.c_str());\n                    inFile >> output;\n                    string label = output;\n                    Point tempoint;\n                    tempoint.setCoordinatesAndLabel(n1,n2,n3, label);\n                    // cout << \"point is \"<< tempoint<< endl;\n                    obj.vertices.push_back(tempoint);\n                    labeltoindex[label] = tempindex;\n                    inFile >> output;\n                    tempindex++;\n                }\n            }\n            cout << \"vertices finished\" <<endl;\n            inFile >> output;\n            cout << \"edges begin \"<< endl;\n            if(output==\"Edges\"){\n                while(output!=\";\"){\n                    inFile >> output;\n                    string label1 = output;\n                    inFile >> output;\n                    string label2 = output;\n                    auto point1ptr = find_if(obj.vertices.begin(),obj.vertices.end(),[label1](Point p)->bool{\n                        return(p.label == label1);\n                    });\n                    auto point2ptr = find_if(obj.vertices.begin(),obj.vertices.end(),[label2](Point p)->bool{\n                        return(p.label == label2);\n                    });\n                    Edge tempedge;\n                    tempedge.p1 = * point1ptr;\n                    tempedge.p2 = * point2ptr;\n                    obj.edges.push_back(tempedge);\n                    inFile >> output;\n                }\n            }\n            cout << \"edges finished\"<< endl;\n            inFile >> output;\n            cout << \"faces starting\" << endl;\n            if(output==\"Faces\"){\n                while(output!=\";\"){\n                    inFile >> output;\n                    // vector<string> labelvec;\n                    Face tempface;\n                    while(output!=\",\" && output!=\";\"){\n                        string tempstr = output;\n                        // labelvec.push_back(tempstr);\n                        // cout << \"tempstr is \" <<tempstr << endl;\n                        inFile >> output;\n                        tempface.vertices.push_back(labeltoindex[tempstr]);\n                        \n                    }\n                    obj.faces.push_back(tempface);\n                    // cout << \"pushed face\"<<endl;\n                    // break;\n                    // inFile >> output;\n                }\n            }\n            cout << \"faces finished\" <<endl;\n            inFile >> output;\n            cout << \"plane started \"<< endl;\n            if(output==\"Plane\"){\n                inFile >> output;\n                double n1 = atof(output.c_str());\n                inFile >> output;\n                double n2 = atof(output.c_str());\n                inFile >> output;\n                double n3 = atof(output.c_str());\n                inFile >> output;\n                double n4 = atof(output.c_str());\n                // inFile >> output\n                // planearr={n1,n2,n3,n4};\n                planearr[0]=n1;\n                planearr[1]=n2;\n                planearr[2]=n3;\n                planearr[3]=n4;\n            }\n            // cout << \"plane finished\" << endl;\n        }\n        cout << \"file complete\"<<endl;\n        cout << \"Object created from file: \" << endl << obj << endl; \n        PlaneProjection* p = new PlaneProjection;\n        p = obj.project3D(planearr);\n        cout << \"Projection: \" << *p << endl;\n        p->rotatePlane();\n        cout << \"Rotated Projection: \" << *p << endl;\n        return p;\n    }\n    return 0;\n}\n\nint check2D() {\n    Point etop, atop, btop, ctop, dtop, afront,dfront, bfront,cfront, efront, eside, dside, cside, aside, bside;\n    etop.setCoordinatesAndLabel(1.5,1.5,0,\"e\");\n    atop.setCoordinatesAndLabel(1,1,0,\"a\");\n    btop.setCoordinatesAndLabel(2,1,0,\"b\");\n    ctop.setCoordinatesAndLabel(2,2,0,\"c\");\n    dtop.setCoordinatesAndLabel(1,2,0,\"d\");\n    efront.setCoordinatesAndLabel(1.5,0,2,\"e\");\n    afront.setCoordinatesAndLabel(1,0,1,\"a\");\n    bfront.setCoordinatesAndLabel(2,0,1,\"b\");\n    cfront.setCoordinatesAndLabel(2,0,1,\"c\");\n    dfront.setCoordinatesAndLabel(1,0,1,\"d\");\n    eside.setCoordinatesAndLabel(0,1.5,2,\"e\");\n    aside.setCoordinatesAndLabel(0,1,1,\"a\");\n    bside.setCoordinatesAndLabel(0,1,1,\"b\");\n    cside.setCoordinatesAndLabel(0,2,1,\"c\");\n    dside.setCoordinatesAndLabel(0,2,1,\"d\");\n    ClusteredPoint atopcl,btopcl, etopcl, dtopcl, ctopcl, efrontcl, adfrontcl,bcfrontcl,esidecl, dcsidecl, absidecl;\n    atopcl.points.push_back(atop);\n    btopcl.points.push_back(btop);\n    dtopcl.points.push_back(dtop);\n    etopcl.points.push_back(etop);\n    ctopcl.points.push_back(ctop);\n    efrontcl.points.push_back(efront);\n    adfrontcl.points.push_back(afront);\n    adfrontcl.points.push_back(dfront);\n    bcfrontcl.points.push_back(bfront);\n    bcfrontcl.points.push_back(cfront);\n    esidecl.points.push_back(eside);\n    dcsidecl.points.push_back(dside);\n    dcsidecl.points.push_back(cside);\n    absidecl.points.push_back(aside);\n    absidecl.points.push_back(bside);\n    OrthoProjection topview, frontview,sideview;\n    ClusteredPoint topspoints[] = {atopcl,btopcl,dtopcl,etopcl,ctopcl};\n    for(int i=0;i<5;i++){\n        topview.vertices.push_back(topspoints[i]);\n    }\n    //ClusteredPoint temp =topview.vertices[2];\n    //cout << topview.vertices[2].points[0].label << endl;\n    ClusteredPoint frontspoints[] ={efrontcl,adfrontcl,bcfrontcl};\n    for(int i=0;i<3;i++){\n        frontview.vertices.push_back(frontspoints[i]);\n    }\n    ClusteredPoint sidespoints[] = {esidecl,dcsidecl,absidecl};\n    for(int i=0;i<3;i++){\n        sideview.vertices.push_back(sidespoints[i]);\n    }\n    Edge2D abtope,bctope,cdtope,adtope,aetope,betope,cetope,detope,actope,bdtope;\n    abtope.cp1 = atopcl; abtope.cp2 = btopcl;\n    bctope.cp1 = btopcl; bctope.cp2 = ctopcl;\n    cdtope.cp1 = ctopcl; cdtope.cp2 = dtopcl;\n    adtope.cp1 = atopcl; adtope.cp2 = dtopcl;\n    aetope.cp1 = atopcl; aetope.cp2 = etopcl;\n    betope.cp1 = btopcl; betope.cp2 = etopcl;\n    cetope.cp1 = ctopcl; cetope.cp2 = etopcl;\n    detope.cp1 = dtopcl; detope.cp2 = etopcl;\n    actope.cp1 = atopcl; actope.cp2 = ctopcl;\n    bdtope.cp1 = btopcl; bdtope.cp2 = dtopcl;\n    Edge2D topsedges[] ={abtope,bctope,cdtope,adtope,aetope,betope,cetope,detope,actope,bdtope};\n    //cout << sizeof(topsedges)/sizeof(Edge2D);\n    for(int i=0;i<10;i++){\n        topview.edges.push_back(topsedges[i]);\n    }\n    Edge2D ebcfronte, adbcfronte,eadfronte;\n    ebcfronte.cp1=efrontcl; ebcfronte.cp2=bcfrontcl;\n    adbcfronte.cp1=adfrontcl; adbcfronte.cp2=bcfrontcl;\n    eadfronte.cp1=efrontcl; eadfronte.cp2=adfrontcl;\n    Edge2D frontsedges[] = {ebcfronte, adbcfronte,eadfronte};\n    for(int i=0;i<3;i++){\n        frontview.edges.push_back(frontsedges[i]);\n    }\n    Edge2D eabsidee, dcabsidee, edcsidee;\n    eabsidee.cp1=esidecl; eabsidee.cp2=absidecl;\n    dcabsidee.cp1=dcsidecl; dcabsidee.cp2=absidecl;\n    edcsidee.cp1=esidecl; edcsidee.cp2=dcsidecl;\n    Edge2D sidesedges[] ={eabsidee, dcabsidee, edcsidee};\n    for(int i=0;i<3;i++){\n        sideview.edges.push_back(sidesedges[i]);\n    }\n    Projection2D myproj;\n    myproj.frontview=frontview;\n    myproj.sideview=sideview;\n    myproj.topview =topview;\n    myproj.create3D();\n    return 0;\n}\n\nWireframe* input2Dfile(string filename){\n    ///\n    /// Function to get input of 2D Projections from a file\n    ///\n    // ofstream inFile;\n    cout <<\"start\" <<endl;\n\t// inFile.open(\"example.txt\");\n    ifstream inFile (filename);\n    if(!(inFile.is_open())){\n        cout<< \"not started\" <<endl;\n    }\n\n\t//char output[100];\n\tOrthoProjection top,front,side;\n\tPoint temp2dpoint;\n\tstring output;\n    cout<< \"file started\"<<endl;\n    if(inFile.is_open()){\n        if(!inFile.eof())\n\t\t{\n\t\t\tinFile >> output;\n\t\t\t//transform(output.begin(), output.end(), output.begin(), ::tolower);\n            cout<<\"begin\" <<endl;\n\t\t\tif(output == \"Top\"){\n                cout << \"entered Top \"<<endl;\n                inFile >> output;\n                map<string, ClusteredPoint> sampmap;\n                if(output==\"Vertices\"){\n                    cout << \"entered Vertices\" << endl;\n                    inFile >> output;\n                    while(output!=\";\"){\n                        double n1 = atof(output.c_str());\n                        // cout << n1 << endl;\n                        inFile >> output;\n                        double n2 = atof(output.c_str());\n                        inFile >> output;\n                        vector<string> thisstr;\n                        inFile >> output;\n                        while(output!=\"]\"){\n                            // inFile >> output;\n                            thisstr.push_back(output);\n                            inFile >> output;\n                        }\n                        ClusteredPoint tempcluster;\n                        for(int i=0;i<thisstr.size();i++){\n                            Point tempoint;\n                            tempoint.x = n1;\n                            tempoint.y = n2;\n                            tempoint.z = 0 ;\n                            tempoint.label = thisstr[i];\n                            cout << tempoint.label << endl;\n                            cout << tempoint << endl;\n                            tempcluster.points.push_back(tempoint);\n                        }\n                        sampmap[tempcluster.points[0].label] = tempcluster;\n                        top.vertices.push_back(tempcluster);\n                        inFile >> output;\n                    }\n\n                    while(output!=\";;\"){\n                        cout << \"ended vertices\" << endl;\n                        inFile >> output;\n                        if(output==\"Edges\"){\n                            cout << \"entered edges \" <<endl;\n                            \n                            while(output!=\";;\"){\n                                inFile >> output;\n                                string a1 = output;\n                                inFile >> output;\n                                string a2 = output;\n                                // cout << \"a1 and a2 are \" <<a1<<\" \"<<a2<<endl; \n                                ClusteredPoint c1 = sampmap[a1];\n                                ClusteredPoint c2 = sampmap[a2];\n                                Edge2D thisedge2d;\n                                thisedge2d.cp1 = c1;\n                                thisedge2d.cp2 = c2;\n                                top.edges.push_back(thisedge2d);\n                                inFile >> output;\n                            }\n                            cout << \"edge size is \" << top.edges.size() << endl;\n                            // cout << \"last edge is \" << top.edges[top.edges.size()-1].cp1.points[0] << \" : \"<< top.edges[top.edges.size()-1].cp2.points[0] <<endl;\n                        }\n                    }\n                    \n                }\n\n            }\n            //yha se\n            inFile >> output;\n            if(output==\"Front\"){\n                cout << \"entered Front\" <<endl;\n                inFile >> output;\n\n                map<string, ClusteredPoint> sampmap;\n                if(output==\"Vertices\"){\n                    cout << \"entered Vertices\" << endl;\n                    inFile >> output;\n                    while(output!=\";\"){\n                        double n1 = atof(output.c_str());\n                        // cout << n1 << endl;\n                        inFile >> output;\n                        double n2 = atof(output.c_str());\n                        inFile >> output;\n                        vector<string> thisstr;\n                        inFile >> output;\n                        while(output!=\"]\"){\n                            // inFile >> output;\n                            thisstr.push_back(output);\n                            inFile >> output;\n                        }\n                        ClusteredPoint tempcluster;\n                        for(int i=0;i<thisstr.size();i++){\n                            Point tempoint;\n                            tempoint.x = n1;\n                            tempoint.y = 0;\n                            tempoint.z = n2 ;\n                            tempoint.label = thisstr[i];\n                            cout << tempoint.label << endl;\n                            cout << tempoint << endl;\n                            tempcluster.points.push_back(tempoint);\n                        }\n                        sampmap[tempcluster.points[0].label] = tempcluster;\n                        front.vertices.push_back(tempcluster);\n                        inFile >> output;\n                    }\n\n                    while(output!=\";;\"){\n                        cout << \"ended vertices\" << endl;\n                        inFile >> output;\n                        if(output==\"Edges\"){\n                            cout << \"entered edges \" <<endl;\n                            \n                            while(output!=\";;\"){\n                                inFile >> output;\n                                string a1 = output;\n                                inFile >> output;\n                                string a2 = output;\n                                ClusteredPoint c1 = sampmap[a1];\n                                ClusteredPoint c2 = sampmap[a2];\n                                Edge2D thisedge2d;\n                                thisedge2d.cp1 = c1;\n                                thisedge2d.cp2 = c2;\n                                front.edges.push_back(thisedge2d);\n                                inFile >> output;\n                            }\n                            cout << \"edge size is \" << front.edges.size() << endl;\n                        }\n                    }   \n                }\n                //end doc\n            }\n            inFile >> output;\n            if(output==\"Side\"){\n\n                cout << \"entered Side\" <<endl;\n                inFile >> output;\n\n                map<string, ClusteredPoint> sampmap;\n                if(output==\"Vertices\"){\n                    cout << \"entered Vertices\" << endl;\n                    inFile >> output;\n                    while(output!=\";\"){\n                        double n1 = atof(output.c_str());\n                        // cout << n1 << endl;\n                        inFile >> output;\n                        double n2 = atof(output.c_str());\n                        inFile >> output;\n                        vector<string> thisstr;\n                        inFile >> output;\n                        while(output!=\"]\"){\n                            // inFile >> output;\n                            thisstr.push_back(output);\n                            inFile >> output;\n                        }\n                        ClusteredPoint tempcluster;\n                        for(int i=0;i<thisstr.size();i++){\n                            Point tempoint;\n                            tempoint.x = 0;\n                            tempoint.y = n1 ;\n                            tempoint.z = n2 ;\n                            tempoint.label = thisstr[i];\n                            cout << tempoint.label << endl;\n                            cout << tempoint << endl;\n                            tempcluster.points.push_back(tempoint);\n                        }\n                        sampmap[tempcluster.points[0].label] = tempcluster;\n                        side.vertices.push_back(tempcluster);\n                        inFile >> output;\n                    }\n\n                    while(output!=\";;\"){\n                        cout << \"ended vertices\" << endl;\n                        inFile >> output;\n                        if(output==\"Edges\"){\n                            cout << \"entered edges \" <<endl;\n                            \n                            while(output!=\";;\"){\n                                inFile >> output;\n                                string a1 = output;\n                                inFile >> output;\n                                string a2 = output;\n                                ClusteredPoint c1 = sampmap[a1];\n                                ClusteredPoint c2 = sampmap[a2];\n                                Edge2D thisedge2d;\n                                thisedge2d.cp1 = c1;\n                                thisedge2d.cp2 = c2;\n                                side.edges.push_back(thisedge2d);\n                                inFile >> output;\n                            }\n                            cout << \"edge size is \" << side.edges.size() << endl;\n                            inFile >> output;\n                        }\n                    }   \n                }\n            //end doc\n            }\n\t\t}\n        cout << \"lets start the computation now \"<< endl;\n        // we have top front side\n        Wireframe frame;\n        Projection2D myproj;\n        myproj.frontview = front;\n        myproj.sideview = side;\n        myproj.topview = top;\n        frame = myproj.create3D();\n        Wireframe* retFrame;\n        retFrame = new Wireframe;\n        for(int i = 0; i < frame.vertices.size(); i++) {\n            retFrame->vertices.push_back(frame.vertices[i]);\n        }\n        for(int i = 0; i < frame.edges.size(); i++) {\n            Edge edge;\n            edge.p1.setCoordinates(frame.edges[i].p1.x,frame.edges[i].p1.y,frame.edges[i].p1.z);\n            edge.p2.setCoordinates(frame.edges[i].p2.x,frame.edges[i].p2.y,frame.edges[i].p2.z);        \n            retFrame->edges.push_back(edge);\n        }\n        // cout << \"retFrame: \" << *retFrame << endl;\n        retFrame->normalise();\n        // cout << \"retFrame after normalise: \" << endl << *retFrame << endl;    \n        return retFrame;\n    }\n    return 0;\n}\n\nPlaneProjection* createObject(Object3D* object, double plane[4]) {\n    ///\n    /// This function shall make use of the gtk library, to interactively take input from the user and returns the 3D object created from the user input\n    ///\n    cout << \"In createObject\" << endl; // ----------Remove\n    Object3D temp_obj;\n    for(int i = 0; i < object->vertices.size(); i++)\n        temp_obj.vertices.push_back(object->vertices[i]);\n    for(int i = 0; i < object->edges.size(); i++)\n        temp_obj.edges.push_back(object->edges[i]);\n    for(int i = 0; i < object->faces.size(); i++)\n        temp_obj.faces.push_back(object->faces[i]);\n    cout << \"Input Object:\" << endl << temp_obj;\n    for(int i = 0; i < 4; i++)\n        cout << plane[i];\n    PlaneProjection* res = new PlaneProjection;\n    res = temp_obj.project3D(plane);\n    cout << \"Object Returned: \" << endl; // --------Remove\n    cout << *res << endl; // --------Remove\n    res->rotatePlane();\n    cout << \"Plane Rotated:\" << endl; // ---------Remove\n    cout << *res << endl; // ---------Remove\n    return res;\n}\n\nWireframe* createProjection(Projection2D* projection) {\n    ///\n    /// This function shall make use of the gtk library, to interactively take input from the user, to form a 2D projection and returns the Projection created from the user input\n    ///\n    cout << \"In createProjection\" << endl; // ----------Remove\n    Wireframe newFrame;\n    newFrame = projection->create3D();\n    Wireframe* retFrame;\n    retFrame = new Wireframe;\n    for(int i = 0; i < newFrame.vertices.size(); i++) {\n        retFrame->vertices.push_back(newFrame.vertices[i]);\n    }\n    for(int i = 0; i < newFrame.edges.size(); i++) {\n        Edge edge;\n        edge.p1.setCoordinates(newFrame.edges[i].p1.x,newFrame.edges[i].p1.y,newFrame.edges[i].p1.z);\n        edge.p2.setCoordinates(newFrame.edges[i].p2.x,newFrame.edges[i].p2.y,newFrame.edges[i].p2.z);        \n        retFrame->edges.push_back(edge);\n    }\n    // cout << \"retFrame: \" << *retFrame << endl;\n    retFrame->normalise();\n    // cout << \"retFrame after normalise: \" << endl << *retFrame << endl;\n    return retFrame;\n}", "meta": {"hexsha": "aa355368727a152fbc06326997d7e37a0072a60b", "size": 22920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Main.cpp", "max_stars_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_stars_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T18:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T23:07:12.000Z", "max_issues_repo_path": "src/Main.cpp", "max_issues_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_issues_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.cpp", "max_forks_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_forks_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-09T10:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-28T08:53:33.000Z", "avg_line_length": 39.7916666667, "max_line_length": 178, "alphanum_fraction": 0.4708987784, "num_tokens": 5235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.04885778139204431, "lm_q1q2_score": 0.022524257021705466}}
{"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:16\n\n#ifndef HSSUSY_INPUT_PARAMETERS_H\n#define HSSUSY_INPUT_PARAMETERS_H\n\n#include <complex>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nstruct HSSUSY_input_parameters {\n   double MSUSY;\n   double M1Input;\n   double M2Input;\n   double M3Input;\n   double MuInput;\n   double mAInput;\n   double MEWSB;\n   double AtInput;\n   double TanBeta;\n   double LambdaLoopOrder;\n   Eigen::Matrix<double,3,3> msq2;\n   Eigen::Matrix<double,3,3> msu2;\n   Eigen::Matrix<double,3,3> msd2;\n   Eigen::Matrix<double,3,3> msl2;\n   Eigen::Matrix<double,3,3> mse2;\n\n   HSSUSY_input_parameters()\n      : MSUSY(0), M1Input(0), M2Input(0), M3Input(0), MuInput(0), mAInput(0),\n   MEWSB(0), AtInput(0), TanBeta(0), LambdaLoopOrder(0), msq2(Eigen::Matrix<\n   double,3,3>::Zero()), msu2(Eigen::Matrix<double,3,3>::Zero()), msd2(\n   Eigen::Matrix<double,3,3>::Zero()), msl2(Eigen::Matrix<double,3,3>::Zero()),\n   mse2(Eigen::Matrix<double,3,3>::Zero())\n\n   {}\n\n   Eigen::ArrayXd get() const;\n   void set(const Eigen::ArrayXd&);\n};\n\nstd::ostream& operator<<(std::ostream&, const HSSUSY_input_parameters&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "abf558253afa2c25ae11c1ce4eec3c495aac8818", "size": 1990, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/HSSUSY/HSSUSY_input_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/HSSUSY/HSSUSY_input_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/HSSUSY/HSSUSY_input_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": 31.09375, "max_line_length": 79, "alphanum_fraction": 0.6577889447, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.04603390289002631, "lm_q1q2_score": 0.022477590401860783}}
{"text": "/* vim: set tabstop=4 : */\n/********************************************************************\n\t@file set_op.hpp\n\t@brief set operations\n\n\t@date\t2006-10-23 14:02\n\t@author\tleipeng\n\t@{\n*********************************************************************/\n#pragma once\n\n// #include <boost/preprocessor/iteration/local.hpp>\n// #include <boost/preprocessor/enum.hpp>\n// #include <boost/preprocessor/enum_params.hpp>\n// #include <boost/mpl/at.hpp>\n// #include <boost/mpl/map.hpp>\n//\n\n#include <assert.h>\n#include <stdlib.h>\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <stdexcept>\n#include <boost/tuple/tuple.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/multi_index/identity.hpp>\n#include \"stdtypes.hpp\"\n#include \"util/compare.hpp\"\n\nnamespace terark {\n//@{\n/**\n @brief multi set intersection -- result is copy from [_First1, _Last1)\n\n [dest, result) is [_First1, _Last1) AND [_First2, _Last2)\n\n predictions:\n   for any [x1, x2) in [_First1, _Last1), _Pred(x2, x1) = false,\n   that is say: x1 <= x2\n   allow same key in sequence\n @note\n  - result is copy from [_First1, _Last1)\n  - values in sequence can be equal, when values are equal, multi values will be copied\n  - _InIt1::value_type, _InIt2::value_type, _OutIt::value_type need not be same\n  - _InIt1::value_type and _InIt2::value_type must comparable by _Pr\n  - _InIt1::value_type must assignable to _OutIt::value_type\n  - _InIt2::value_type need not assignable to _OutIt::value_type\n */\ntemplate<class _InIt1, class _InIt2, class _OutIt, class _Pr>\ninline\n_OutIt multiset_intersection(_InIt1 _First1, _InIt1 _Last1,\n\t\t\t\t\t\t\t _InIt2 _First2, _InIt2 _Last2, _OutIt dest, _Pr _Pred)\n{\n\tfor (; _First1 != _Last1 && _First2 != _Last2; )\n\t{\n\t\tif (_Pred(*_First1, *_First2))\n\t\t\t++_First1;\n\t\telse if (_Pred(*_First2, *_First1))\n\t\t\t++_First2;\n\t\telse\n\t\t\t*dest++ = *_First1++; // do not increment _First2\n\t}\n\treturn (dest);\n}\n\ntemplate<class _InIt1, class _RandInIt2, class _OutIt, class _Pr>\ninline\n_OutIt multiset_1small_intersection(_InIt1 _First1, _InIt1 _Last1,\n\t\t\t\t\t\t\t\t\t_RandInIt2 _First2, _RandInIt2 _Last2, _OutIt dest, _Pr _Pred)\n{\n\tfor (; _First1 != _Last1 && _First2 != _Last2; )\n\t{\n\t\tstd::pair<_RandInIt2, _RandInIt2> range = std::equal_range(_First2, _Last2, *_First1, _Pred);\n\t\tif (range.first == range.second)\n\t\t\t++_First1;\n\t\telse {\n\t\t\t// !(*range.first < *_First1) --> *_First1 <= *range.first\n\t\t\twhile (_First1 != _Last1 && !_Pred(*range.first, *_First1))\n\t\t\t\t*dest++ = *_First1++;\n\t\t}\n\t\t_First2 = range.second;\n\t}\n\treturn (dest);\n}\n\ntemplate<class _InIt1, class _RandInIt2, class _OutIt, class _Pr>\ninline\n_OutIt multiset_fast_intersection(_InIt1 _First1, _InIt1 _Last1,\n\t\t\t\t\t\t\t\t  _RandInIt2 _First2, _RandInIt2 _Last2, _OutIt dest, _Pr _Pred, ptrdiff_t threshold = 32)\n{\n\tif (std::distance(_First1, _Last1) * threshold < std::distance(_First2, _Last2))\n\t\treturn multiset_1small_intersection(_First1, _Last1, _First2, _Last2, dest, _Pred);\n\telse\n\t\treturn multiset_intersection(_First1, _Last1, _First2, _Last2, dest, _Pred);\n}\n//@}\n\n//////////////////////////////////////////////////////////////////////////\n\n//@{\n/**\n @brief multi set intersection2 -- result is copy from [_First2, _Last2)\n\n [dest, result) is [_First1, _Last1) AND [_First2, _Last2)\n for any [x1, x2) in [_First1, _Last1), _Pred(x2, x1) = false\n allow same key in sequence\n\n @note\n  - result is copy from [_First2, _Last2)\n  - values in sequence can be equal, when values are equal, multi values will be copied\n  - _InIt1::value_type, _InIt2::value_type, _OutIt::value_type need not be same\n  - _InIt1::value_type and _InIt2::value_type must comparable by _Pr\n  - _InIt2::value_type must assignable to _OutIt::value_type\n  - _InIt1::value_type need not assignable to _OutIt::value_type\n */\ntemplate<class _InIt1, class _InIt2, class _OutIt, class _Pr>\ninline\n_OutIt multiset_intersection2(_InIt1 _First1, _InIt1 _Last1,\n\t\t\t\t\t\t\t  _InIt2 _First2, _InIt2 _Last2, _OutIt dest, _Pr _Pred)\n{\n\tfor (; _First1 != _Last1 && _First2 != _Last2; )\n\t{\n\t\tif (_Pred(*_First1, *_First2))\n\t\t\t++_First1;\n\t\telse if (_Pred(*_First2, *_First1))\n\t\t\t++_First2;\n\t\telse\n\t\t\t*dest++ = *_First2++; // do not increment _First1\n\t}\n\treturn (dest);\n}\n\ntemplate<class _InIt1, class _RandInIt2, class _OutIt, class _Pr>\ninline\n_OutIt multiset_1small_intersection2(_InIt1 _First1, _InIt1 _Last1,\n\t\t\t\t\t\t\t\t\t _RandInIt2 _First2, _RandInIt2 _Last2, _OutIt dest, _Pr _Pred)\n{\n\tfor (; _First1 != _Last1 && _First2 != _Last2; )\n\t{\n\t\tstd::pair<_RandInIt2, _RandInIt2> range = std::equal_range(_First2, _Last2, *_First1, _Pred);\n\t\tif (range.first != range.second)\n\t\t{\n\t\t\tdest = std::copy(range.first, range.second, dest);\n\t\t}\n\t\t_First2 = range.second;\n\t\t++_First1;\n\t}\n\treturn (dest);\n}\n\ntemplate<class _RandInIt1, class _RandInIt2, class _OutIt, class _Pr>\ninline\n_OutIt multiset_fast_intersection2(_RandInIt1 _First1, _RandInIt1 _Last1,\n\t\t\t\t\t\t\t\t   _RandInIt2 _First2, _RandInIt2 _Last2, _OutIt dest, _Pr _Pred, ptrdiff_t threshold = 32)\n{\n\tif (std::distance(_First1, _Last1) * threshold < std::distance(_First2, _Last2))\n\t\treturn multiset_1small_intersection2(_First1, _Last1, _First2, _Last2, dest, _Pred);\n\telse\n\t\treturn multiset_intersection2(_First1, _Last1, _First2, _Last2, dest, _Pred);\n}\n//@}\n\n//! 一定是调用 pred(prev, curr), 而不是 pred(curr, prev)\n//!\n//! 可以保证对有序序列 pred(prev, curr) 等效于 !equal_to(prev, curr)\n//! 从而可以对有序序列使用 set_unique(first, last, terark::not2(less_than_comp))\n//! 来删除重复元素\n//!\ntemplate<class _FwdIt, class _Pr> inline\n_FwdIt set_unique(_FwdIt _First, _FwdIt _Last, _Pr _Pred)\n{\t// remove each matching previous\n\tfor (_FwdIt _Firstb; (_Firstb = _First) != _Last && ++_First != _Last; )\n\t\tif (_Pred(*_Firstb, *_First))\n\t\t\t{\t// copy down\n\t\t\tfor (; ++_First != _Last; )\n\t\t\t\tif (!_Pred(*_Firstb, *_First))\n\t\t\t\t\t*++_Firstb = *_First;\n\t\t\treturn (++_Firstb);\n\t\t\t}\n\treturn (_Last);\n}\n\ntemplate<class _FwdIt> inline\n\t_FwdIt set_unique(_FwdIt _First, _FwdIt _Last)\n{\n\treturn set_unique(_First, _Last,\n\t\tstd::equal_to<typename std::iterator_traits<_FwdIt>::value_type>()\n\t\t);\n}\n\ntemplate<class _Pr>\nclass not1_functor\n{\n\t_Pr m_pr;\n\npublic:\n\ttypedef bool result_type;\n\n\texplicit not1_functor(_Pr _Pred) : m_pr(_Pred) {}\n\tnot1_functor() {}\n\n\ttemplate<class T1>\n\tbool operator()(const T1& x) const\n\t{\n\t\treturn !m_pr(x);\n\t}\n};\n\ntemplate<class _Pr>\nclass not2_functor\n{\n\t_Pr m_pr;\n\npublic:\n\ttypedef bool result_type;\n\n\texplicit not2_functor(_Pr _Pred) : m_pr(_Pred) {}\n\tnot2_functor() {}\n\n\ttemplate<class T1, class T2>\n\tbool operator()(const T1& x, const T2& y) const\n\t{\n\t\treturn !m_pr(x, y);\n\t}\n};\n\ntemplate<class _Pr>\nnot1_functor<_Pr> not1(const _Pr& _Pred)\n{\n\treturn not1_functor<_Pr>(_Pred);\n}\ntemplate<class _Pr>\nnot2_functor<_Pr> not2(const _Pr& _Pred)\n{\n\treturn not2_functor<_Pr>(_Pred);\n}\n\n//////////////////////////////////////////////////////////////////////////\n//! find in predicted near range, if not found, find it in the whole range\n//!\ntemplate<class IterT, class CompareT>\nIterT find_next_larger(IterT first, IterT prediction, IterT last, CompareT comp)\n{\n\tIterT iter = std::upper_bound(first, prediction, *first, comp);\n\tif (iter == prediction && !comp(*first, *prediction)) // *first == *prediction\n\t\treturn std::upper_bound(prediction, last, *first, comp);\n\telse\n\t\treturn iter;\n}\n\n//////////////////////////////////////////////////////////////////////////\n\n//! Call Convert(*iter) to convert the iterator\ntemplate<class InputIter, class ConvertedType, class Convertor>\nclass convertor_iterator_adaptor :\n\tpublic std::iterator< typename std::iterator_traits<InputIter>::iterator_category\n\t\t\t\t\t\t, ConvertedType>\n{\n\ttypedef convertor_iterator_adaptor<InputIter, ConvertedType, Convertor> self_t;\n\n\tConvertor m_convert;\n\npublic:\n\tInputIter m_iter;\n\n\ttypedef typename std::iterator_traits<InputIter>::difference_type difference_type;\n\n\texplicit convertor_iterator_adaptor(InputIter iter, const Convertor& convert = Convertor())\n\t\t: m_iter(iter), m_convert(convert) {}\n\n\tConvertedType operator*() const { return m_convert(*m_iter); }\n\n\tself_t& operator++() { ++m_iter; return *this; }\n\tself_t& operator--() { --m_iter; return *this; }\n\n\tself_t operator++(int) { self_t temp(*this); ++m_iter; return temp; }\n\tself_t operator--(int) { self_t temp(*this); --m_iter; return temp; }\n\n\tbool operator==(const self_t& y) const { return m_iter == y.m_iter; }\n\tbool operator!=(const self_t& y) const { return m_iter != y.m_iter; }\n\n\tbool operator<=(const self_t& y) const { return m_iter <= y.m_iter; }\n\tbool operator>=(const self_t& y) const { return m_iter >= y.m_iter; }\n\n\tbool operator<(const self_t& y) const { return m_iter < y.m_iter; }\n\tbool operator>(const self_t& y) const { return m_iter > y.m_iter; }\n\n\tdifference_type operator-(const self_t& y) const { return m_iter - y.m_iter; }\n\n\tself_t  operator+(difference_type y) const { return self_t(m_iter + y, m_convert); }\n\n\tself_t& operator+=(difference_type i) { m_iter += i; return *this; }\n\tself_t& operator-=(difference_type i) { m_iter -= i; return *this; }\n};\ntemplate<class ConvertedType, class InputIter, class Convertor>\nconvertor_iterator_adaptor<InputIter, ConvertedType, Convertor>\nconvert_iterator(InputIter iter, const Convertor& convertor)\n{\n\treturn convertor_iterator_adaptor<InputIter, ConvertedType, Convertor>(iter, convertor);\n}\n\n//! Call extractor(iter) to convert source iter to target iter\n//!\n//! if *iter is something computed from iter, the adapter can avoid to calling *iter\n//! @note\n//!  -# Extractor is applied on iter, not '*iter'\n//!  -# Extractor should be a functor\ntemplate<class InputIter, class MemberType, class Extractor>\nclass member_iterator_adaptor\n  : public std::iterator< typename std::iterator_traits<InputIter>::iterator_category\n\t\t\t\t\t\t, MemberType>\n{\n\ttypedef member_iterator_adaptor<InputIter, MemberType, Extractor> self_t;\n\nprivate:\n\tExtractor m_extr;\n\npublic:\n\tInputIter m_iter;\n\n\ttypedef typename std::iterator_traits<InputIter>::difference_type difference_type;\n\n\texplicit member_iterator_adaptor(InputIter iter, const Extractor& convert = Extractor())\n\t\t: m_iter(iter), m_extr(convert) {}\n\n\tMemberType operator*() const { return m_extr(m_iter); }\n\n\tself_t& operator++() { ++m_iter; return *this; }\n\tself_t& operator--() { --m_iter; return *this; }\n\n\tself_t operator++(int) { self_t temp(*this); ++m_iter; return temp; }\n\tself_t operator--(int) { self_t temp(*this); --m_iter; return temp; }\n\n\tbool operator==(const self_t& y) const { return m_iter == y.m_iter; }\n\tbool operator!=(const self_t& y) const { return m_iter != y.m_iter; }\n\n\tbool operator<=(const self_t& y) const { return m_iter <= y.m_iter; }\n\tbool operator>=(const self_t& y) const { return m_iter >= y.m_iter; }\n\n\tbool operator<(const self_t& y) const { return m_iter < y.m_iter; }\n\tbool operator>(const self_t& y) const { return m_iter > y.m_iter; }\n\n\tdifference_type operator-(const self_t& y) const { return m_iter - y.m_iter; }\n\n\tself_t  operator+(difference_type y) const { return self_t(m_iter + y, m_extr); }\n\n\tself_t& operator+=(difference_type i) { m_iter += i; return *this; }\n\tself_t& operator-=(difference_type i) { m_iter -= i; return *this; }\n};\ntemplate<class MemberType, class InputIter, class Extractor>\nmember_iterator_adaptor<InputIter, MemberType, Extractor>\nmember_iterator(InputIter iter, const Extractor& convertor)\n{\n\treturn member_iterator_adaptor<InputIter, MemberType, Extractor>(iter, convertor);\n}\n//////////////////////////////////////////////////////////////////////////\n\ntemplate<class Iter>\ntypename std::iterator_traits<Iter>::value_type\nsum(Iter first, Iter last)\n{\n\ttypename std::iterator_traits<Iter>::value_type s =\n\ttypename std::iterator_traits<Iter>::value_type();\n\tfor (; first != last; ++first)\n\t\ts += *first;\n\treturn s;\n}\ntemplate<class C>\ntypename C::value_type\nsum(const C& c)\n{\n\treturn sum(c.begin(), c.end());\n}\ntemplate<class Iter, class Extractor>\ntypename Extractor::key_type\nsum(Iter first, Iter last, Extractor ex)\n{\n\ttypename Extractor::key_type s = typename Extractor::key_type();\n\tfor (; first != last; ++first)\n\t\ts += ex(*first);\n\treturn s;\n}\ntemplate<class C, class Extractor>\ntypename Extractor::key_type\nsum(const C& c, Extractor ex)\n{\n\treturn sum(c.begin(), c.end(), ex);\n}\n\n//////////////////////////////////////////////////////////////////////////\n/**\n @brief\n - like std::remove_if, but use std::swap\n */\ntemplate<class ForwIter, class Pred>\nForwIter\nremove_swap_if(ForwIter first, ForwIter last, Pred pred) {\n\tfor (; first != last; ++first)\n\t\tif (pred(*first))\n\t\t\tgoto DoErase;\n\treturn last;\nDoErase: {\n\tForwIter dest = first;\n\tfor (++first; first != last; ++first) {\n\t\tusing std::swap;\n\t\tif (!pred(*first))\n\t\t\tswap(*dest, *first), ++dest;\n\t}\n\treturn dest;\n  }\n}\n\nnamespace multi_way\n{\n\n/**\n @brief can be better inline when pass by param\n */\nclass FirstEqualSecond {\npublic:\n\ttemplate<class T>\n\tbool operator()(const std::pair<T,T>& x)const{return x.first==x.second;}\n};\n\nclass MustProvideKeyExtractor;\n\nstruct tag_cache_default {}; //!< default select\nstruct tag_cache_none {};\nstruct tag_cache_key {};\nstruct tag_cache_value {};\n\ntemplate<class Value>\nclass CacheValueArray {\nprotected: // sizeof(*this) == sizeof(void*)\n\tValue* m_cache;\npublic:\n\tCacheValueArray() { m_cache = NULL; }\n\t~CacheValueArray() {\n\t\tif (m_cache)\n\t\t\tdelete []m_cache;\n\t}\n\tvoid resize_cache(size_t size) {\n\t\tif (m_cache)\n\t\t\tdelete []m_cache;\n\t\tm_cache = new Value[size];\n\t\tif (NULL == m_cache)\n\t\t\tabort(); // non-exception-safe, must abort\n\t}\n};\n\ntemplate<class Value>\nclass CacheValueArray0 {\nprotected: // sizeof(*this) >= 3 * sizeof(void*)\n\tstd::vector<Value> m_cache;\npublic:\n\tvoid resize_cache(size_t size) { m_cache.resize(size); }\n};\n\ntemplate<class Key, class KeyExtractor>\nclass KeyExtractor_get_key : protected KeyExtractor {\npublic:\n\ttemplate<class Value>\n\tconst Key& get_key(const Value& x) const { return (*this)(x); }\n};\n\ntemplate<class InputIter, class KeyType, class KeyExtractor, class HowCache>\nclass CacheStrategy; // template proto-type definition\n\ntemplate<class InputIter, class KeyType, class KeyExtractor>\nclass CacheStrategy<InputIter, KeyType, KeyExtractor, tag_cache_none>\n  : protected KeyExtractor_get_key<KeyType, KeyExtractor>\n{\npublic:\n\ttypedef typename std::iterator_traits<InputIter>::value_type value_type;\n\ttypedef tag_cache_none           cache_category;\n\ttypedef boost::tuples::null_type cache_item_type;\nprotected:\n\t//! 这个函数必须要带 cache_category 参数\n\t//! 对 tag_cache_none, 这个函数是在 derived class 中实现的\n\t//! 但是，因为 derived class 中使用了 using super::get_cache_key, 所以这里必须有 get_cache_key 成员\n\t//! Just an empty function\n\tinline void get_cache_key(size_t/*,tag_cache_none*/) const {}\n\tinline void load_cache_item(size_t, const InputIter&) {/*do nothing...*/}\n\tinline void resize_cache(size_t) {/*do nothing...*/}\n\n// just used by LoserTree::start_yan_wu\n// has no this function, LoserTree::start_yan_wu don't support tag_cache_none\n// \tvoid set_cache_item(size_t i, const cache_item_type&) {}\n};\n\ntemplate<class InputIter, class KeyType, class KeyExtractor>\nclass CacheStrategy<InputIter, KeyType, KeyExtractor, tag_cache_key>\n  : protected CacheValueArray<KeyType>\n  , protected KeyExtractor_get_key<KeyType, KeyExtractor>\n{\npublic:\n\ttypedef typename std::iterator_traits<InputIter>::value_type value_type;\n\ttypedef tag_cache_key           cache_category;\n\ttypedef KeyType                 cache_item_type;\nprotected:\n\t//! 这个函数必须要带 cache_category 参数\n\tinline const KeyType&\n\tget_cache_key(size_t nth,tag_cache_key)const{return this->m_cache[nth];}\n\n\tinline void\n\tload_cache_item(size_t i,InputIter p){this->m_cache[i]=this->get_key(*p);}\n\n\t// just used by LoserTree::start_yan_wu\n\tvoid set_cache_item(size_t i, const KeyType& k) { this->m_cache[i] = k; }\n};\n\ntemplate<class InputIter, class KeyType, class KeyExtractor>\nclass CacheStrategy<InputIter, KeyType, KeyExtractor, tag_cache_value>\n  : protected CacheValueArray<typename std::iterator_traits<InputIter>::value_type>\n  , protected KeyExtractor_get_key<KeyType, KeyExtractor>\n{\npublic:\n\ttypedef typename std::iterator_traits<InputIter>::value_type value_type;\n\ttypedef tag_cache_value           cache_category;\n\ttypedef value_type                cache_item_type;\nprotected:\n\t//! 这个函数必须要带 cache_category 参数\n\tinline const KeyType&\n\tget_cache_key(size_t i, tag_cache_value) const {\n\t\treturn this->get_key(this->m_cache[i]); }\n\n\tinline void\n\tload_cache_item(size_t i, InputIter iter) { this->m_cache[i] = *iter; }\n\n\t// just used by LoserTree::start_yan_wu\n\tvoid set_cache_item(size_t i, const value_type& x){this->m_cache[i] = x;}\n};\n\ntemplate<class InputIter, class KeyType, class KeyExtractor>\nclass CacheStrategy<InputIter, KeyType, KeyExtractor, tag_cache_default>\n\t/**\n\t @brief cache_item_type is KeyType or value_type\n\n\t 为了 cache 的效率，仅缓存必要的数据(CPU cache, or disk cache)\n\t - input_iterator_tag 表示同一个数据只从 iterator 读一次，因此缓存整个 value\n\t - forward_iterator_tag 及更高级，可以允许从 iterator 读多次，因此只缓存 key\n\t */\n\t: public boost::mpl::if_c<\n\t\tboost::is_same<std::input_iterator_tag,\n\t\t\t\t\t   typename std::iterator_traits<InputIter>::iterator_category\n\t\t\t\t\t  >::value,\n\t\tCacheStrategy<InputIter, KeyType, KeyExtractor, tag_cache_value>,\n\t\tCacheStrategy<InputIter, KeyType, KeyExtractor, tag_cache_key>\n\t>::type\n{};\n\ntemplate< class way_iter_t\n\t\t, class KeyType = typename std::iterator_traits<way_iter_t>::value_type\n\t\t, bool StableSort = false //!< same Key in various way will output by way order\n\t\t, class Compare = std::less<KeyType>\n\t\t, class KeyExtractor = typename boost::mpl::if_c<\n\t\t\t\tboost::is_same<KeyType,\n\t\t\t\t\t\t\t   typename std::iterator_traits<way_iter_t>::value_type\n\t\t\t\t\t\t\t  >::value,\n\t\t\t\tboost::multi_index::identity<KeyType>,\n\t\t\t\tMustProvideKeyExtractor\n\t\t\t>::type\n\t    , class HowCache = tag_cache_default\n\t\t>\nclass LoserTree : protected Compare,\n\tpublic CacheStrategy<way_iter_t, KeyType, KeyExtractor, HowCache>\n{\n\tDECLARE_NONE_COPYABLE_CLASS(LoserTree)\n\ttypedef CacheStrategy<way_iter_t, KeyType, KeyExtractor, HowCache> super;\npublic:\n\ttypedef typename std::iterator_traits<way_iter_t>::value_type value_type;\n\ttypedef KeyType  key_type;\n\ttypedef KeyExtractor key_extractor;\n\ttypedef boost::integral_constant<bool, StableSort> is_stable_sort;\n\ttypedef typename super::cache_category  cache_category;\n\ttypedef typename super::cache_item_type cache_item_type;\n\ttypedef boost::mpl::true_  TriCompare1, StableSort1;\n\ttypedef boost::mpl::false_ TriCompare0, StableSort0;\n\npublic:\n\t/**\n\t @brief construct\n\n\t @par 图示如下：\n\t @code\n\n\t m_ways                                             this is guard value\n\t  ||                                                          ||\n\t  ||                                                          ||\n\t  \\/                                                          \\/\n\t -------> 0 way_iter_t [min_value.........................max_value]\n\t   /      1 way_iter_t [min_value.........................max_value] <--- 每个序列均已\n\t   |      2 way_iter_t [min_value.........................max_value]      按 comp 排序\n\t   |      3 way_iter_t [min_value.........................max_value]\n\t  <       4 way_iter_t [min_value.........................max_value]\n\t   |      5 way_iter_t [min_value.........................max_value]\n\t   |      7 way_iter_t [min_value.........................max_value]\n\t   \\      8 way_iter_t [min_value.........................max_value]\n\t -------> end\n\n\t @endcode\n\n\t @param comp    value 的比较器\n\n\t @note 每个序列最后必须要有一个 max_value 作为序列结束标志，否则会导致未定义行为\n\t */\n\tLoserTree(const KeyType& max_key,\n\t\t\t  const Compare& comp = Compare(),\n\t\t\t  const KeyExtractor& keyExtractor = KeyExtractor())\n\t\t: Compare(comp), m_max_key(max_key)\n\t{\n\t\tm_tree = NULL;\n\t\tstatic_cast<KeyExtractor&>(*this) = keyExtractor;\n\t}\n\t~LoserTree() {\n\t\tif (m_tree) free(m_tree);\n\t}\n\n\t/**\n\t @brief 初始化\n\n\t- 共有 n 个内部结点，n 个外部结点\n\t- winner 只用于初始化时计算败者树，算完后即丢弃\n\t- winner/loser 的第 0 个单元都不是内部结点，不属于树中的一员\n\t- winner 的第 0 个单元未用\n\t- m_tree 的第 0 个单元用于保存最终的赢者, 其它单元保存败者\n\n\t- 该初始化需要的 n-1 次比较，总的时间复杂度是 O(n)\n\n\t- 严蔚敏&吴伟民 的 LoserTree 初始化复杂度是 O(n*log(n))，并且还需要一个 min_key,\n\t  但是他们的初始化不需要额外的 winner 数组\n\n    - 并且，这个实现比 严蔚敏&吴伟民 的 LoserTree 初始化更强壮\n\t */\n\tvoid start() {\n\t\tsize_t len = m_ways.size();\n\t\tif (terark_unlikely(len <= 0))\n\t\t\tthrow std::invalid_argument(\"LoserTree: way sequence must not be empty\");\n\n\t\t{\n\t\t\tsize_t* t = (size_t*)realloc(m_tree, sizeof(size_t) * len);\n\t\t\tif (NULL == t) throw std::bad_alloc();\n\t\t\tm_tree = t;\n\t\t}\n\t\tthis->resize_cache(len);\n\t\tsize_t i;\n\t\tfor (i = 0; i != len; ++i) {\n\t\t\t// load first value from every sequence\n\t\t\tthis->load_cache_item(i, m_ways[i]);\n\t\t}\n\t\tif (terark_unlikely(1 == len)) {\n\t\t\tm_head = 0;\n\t\t\treturn;\n\t\t}\n\n\t\tsize_t minInnerToEx = len / 2;\n\t\tstd::vector<size_t> winner(len);\n\n\t\tfor (i = len - 1; i > minInnerToEx; --i)\n\t\t\texter_loser_winner(m_tree[i], winner[i], i, len);\n\t\tsize_t left, right;\n\t\tif (len & 1) { // odd\n\t\t// left child is last inner node, right child is first external node\n\t\t\tleft = winner[len-1];\n\t\t\tright = 0;\n\t\t} else {\n\t\t\tleft = 0;\n\t\t\tright = 1;\n\t\t}\n\t\tget_loser_winner(m_tree[minInnerToEx], winner[minInnerToEx], left, right);\n\n\t\tfor (i = minInnerToEx; i > 0; i /= 2)\n\t\t\tfor (size_t j = i; j > i/2; ) {\n\t\t\t\t--j;\n\t\t\t\tinner_loser_winner(m_tree[j], winner[j], j, winner);\n\t\t\t}\n\t\tm_head = winner[1];\n\t}\n\n\t//! 严蔚敏&吴伟民 的 LoserTree 初始化\n\t//! 复杂度是 O(n*log(n))，并且还需要一个 min_key\n\tvoid start_yan_wu(const cache_item_type& min_item,\n\t\t\t\t\t  const cache_item_type& max_item)\n\t{\n\t\t//! this function do not support tag_cache_none\n\t\tsize_t len = m_ways.size();\n\t\tthis->resize_cache(len+1);\n\t\tthis->set_cache_item(len, min_item);\n\n\t\tsize_t i;\n\t\tfor (i = 0; i < len; ++i) {\n\t\t\tm_tree[i] = len;\n\t\t\t// load first value from every sequence\n\t\t\tthis->load_cache_item(i, m_ways[i]);\n\t\t}\n\t\tfor (i = len; i > 0; ) ajust(--i);\n\n\t\t// 防止 cache 的最后一个成员上升到 top ??.....\n\t\t//\n\t\tthis->set_cache_item(len, max_item);\n\n\t//\tassert(!m_ways.empty());\n\t//\tif (m_head == len)\n\t//\t\tajust(len); // 会导致在 ajust 中 m_tree[parent] 越界\n\t}\n\n\tconst value_type& current_value() const {\n\t\tassert(!m_ways.empty());\n\t//\tassert(!empty()); // 允许访问末尾的 guardValue, 便于简化 app\n\t\treturn current_value_aux(cache_category());\n\t}\n\n\t/**\n\t @brief return current way NO.\n\t */\n\tsize_t current_way() const {\n\t\tassert(!m_ways.empty());\n\t//\tassert(!empty()); // allow this use\n\t\treturn m_head;\n\t}\n\n\tsize_t total_ways() const { return m_ways.size(); }\n\tbool is_any_way_end() const { return empty(); }\n\n\tbool empty() const {\n\t\tassert(!m_ways.empty());\n\t\tconst KeyType& cur_key = get_cache_key(m_head, cache_category());\n\t\tconst Compare& cmp = *this;\n\t\treturn !cmp(cur_key, m_max_key); // cur_key >= max_value\n\t}\n\n\tvoid increment() {\n\t\tassert(!m_ways.empty());\n\t\tassert(!empty());\n\t\tsize_t top = m_head;\n\t\tthis->load_cache_item(top, ++m_ways[top]);\n\t\tajust(top);\n\t}\n\n\tvoid ajust_for_update_top() {\n\t\tassert(!m_ways.empty());\n\t\tsize_t top = m_head;\n\t\tthis->load_cache_item(top, m_ways[top]);\n\t\tajust(top);\n\t}\n\n\tway_iter_t& top_iter() { assert(!m_ways.empty()); return  m_ways[m_head]; }\n\tconst size_t* get_tree() const { return m_tree; }\n\nprotected:\n\tvoid ajust(size_t s) {\n\t\tsize_t parent = s + m_ways.size();\n\t\tsize_t*ptree =  m_tree;\n\t\twhile ((parent /= 2) > 0) {\n\t\t\tsize_t& tparent = ptree[parent];\n\t\t\tif (comp_cache_item(tparent, s, cache_category(), is_stable_sort()))\n\t\t\t\tstd::swap(s, tparent);\n\t\t}\n\t\tm_head = s;\n\t}\n\n\tvoid exter_loser_winner(size_t& loser, size_t& winner, size_t parent, size_t len) const {\n\t\tsize_t left  = 2 * parent - len;\n\t\tsize_t right = left + 1;\n\t\tget_loser_winner(loser, winner, left, right);\n\t}\n\tvoid inner_loser_winner(size_t& loser, size_t& winner, size_t parent,\n\t\t\t\tconst std::vector<size_t>& winner_vec) const {\n\t\tsize_t left  = 2 * parent;\n\t\tsize_t right = 2 * parent + 1;\n\t\tleft  = winner_vec[left];\n\t\tright = winner_vec[right];\n\t\tget_loser_winner(loser, winner, left, right);\n\t}\n\tvoid get_loser_winner(size_t& loser, size_t& winner, size_t left, size_t right) const {\n\t\tif (comp_cache_item(left, right, cache_category(), is_stable_sort())) {\n\t\t\tloser  = right;\n\t\t\twinner = left;\n\t\t} else {\n\t\t\tloser = left;\n\t\t\twinner = right;\n\t\t}\n\t}\n\n\tconst value_type& current_value_aux(tag_cache_none) const {\n\t\tassert(m_head < m_ways.size());\n\t\treturn *m_ways[m_head];\n\t}\n\tconst value_type& current_value_aux(tag_cache_key) const {\n\t\tassert(m_head < m_ways.size());\n\t\treturn *m_ways[m_head];\n\t}\n\tconst value_type& current_value_aux(tag_cache_value) const {\n\t\tassert(m_head < m_ways.size());\n\t\treturn this->m_cache[m_head];\n\t}\n\n\tusing super::get_cache_key;\n\tinline const KeyType& get_cache_key(size_t nth, tag_cache_none) const {\n\t\treturn this->get_key(*m_ways[nth]); }\n\n\ttemplate<class CacheCategory>\n\tinline bool\n\tcomp_cache_item(size_t x, size_t y, CacheCategory, StableSort0) const {\n\t\tconst KeyType& kx = get_cache_key(x, CacheCategory());\n\t\tconst KeyType& ky = get_cache_key(y, CacheCategory());\n\t\treturn static_cast<const Compare&>(*this)(kx, ky);\n\t}\n\ttemplate<class CacheCategory>\n\tinline bool\n\tcomp_cache_item(size_t x, size_t y, CacheCategory, StableSort1) const {\n\t\tconst KeyType& kx = get_cache_key(x, CacheCategory());\n\t\tconst KeyType& ky = get_cache_key(y, CacheCategory());\n\t\treturn comp_key_stable(x, y, kx, ky, HasTriCompare<Compare>());\n\t}\n\tinline bool\n\tcomp_key_stable(size_t x, size_t y, const KeyType& kx, const KeyType& ky, TriCompare1) const {\n\t\tptrdiff_t ret = Compare::compare(kx, ky);\n\t\tif (ret < 0) return true;\n\t\tif (ret > 0) return false;\n\t\tret = Compare::compare(kx, m_max_key);\n\t\tassert(ret <= 0);\n\t\tif (0==ret) return false;\n\t\telse        return x < y;\n\t}\n\tinline bool\n\tcomp_key_stable(size_t x, size_t y, const KeyType& kx, const KeyType& ky, TriCompare0) const {\n\t\tconst Compare& cmp = *this;\n\t\tif ( cmp(kx, ky)) return true;\n\t\tif ( cmp(ky, kx)) return false;\n\t\tif (!cmp(kx, m_max_key)) {// kx >= max_key --> kx == max_key\n\t\t\t// max_key is the max, so must assert this:\n\t\t\tassert(!cmp(m_max_key, kx));\n\t\t\treturn false;\n\t\t}\n\t\telse return x < y;\n\t}\n\nprotected:\n\tsize_t* m_tree;\n\tsize_t  m_head; // access m_tree[0] need an extra memory load\n\tKeyType m_max_key;\npublic:\n\tstd::vector<way_iter_t> m_ways;\ntypedef LoserTree MyType;\n#include \"multi_way_basic.hpp\"\n#include \"multi_way_algo_loser_tree.hpp\"\n};\n\ntemplate<class _InIt>\nstruct Heap_WayIterEx : public std::pair<_InIt, _InIt> {\n\tsize_t index;\n\ttemplate<class _InIt2>\n\tHeap_WayIterEx(const Heap_WayIterEx<_InIt2>& y)\n\t  : std::pair<_InIt, _InIt>(y.first, y.second), index(y.index) {}\n\tHeap_WayIterEx(size_t index, const _InIt& i1, const _InIt& i2)\n\t  : std::pair<_InIt, _InIt>(i1, i2), index(index) {}\n};\ntemplate<class _InIt>\nHeap_WayIterEx<_InIt>\nmake_way_iter_ex(size_t index, const _InIt& i1, const _InIt& i2) {\n\treturn Heap_WayIterEx<_InIt>(index, i1, i2); }\n\ntemplate< class _InIt\n\t\t, class KeyType = typename std::iterator_traits<_InIt>::value_type\n\t\t, bool StableSort = false //!< same Key in various way will output by way order\n\t\t, class Compare = std::less<KeyType>\n\t\t, class KeyExtractor = typename boost::mpl::if_c<\n\t\t\t\tboost::is_same<KeyType,\n\t\t\t\t\t\t\t   typename std::iterator_traits<_InIt>::value_type\n\t\t\t\t\t\t\t  >::value,\n\t\t\t\tboost::multi_index::identity<KeyType>,\n\t\t\t\tMustProvideKeyExtractor\n\t\t\t>::type\n\t\t, class WayIter = typename boost::mpl::if_c<StableSort, Heap_WayIterEx<_InIt>, std::pair<_InIt, _InIt> >::type\n\t\t>\nclass HeapMultiWay_TrivalWayIter : private Compare {\n\tDECLARE_NONE_COPYABLE_CLASS(HeapMultiWay_TrivalWayIter)\npublic:\n\ttypedef typename std::iterator_traits<_InIt>::value_type value_type;\n\ttypedef KeyExtractor key_extractor;\n\ttypedef KeyType  key_type;\n\ttypedef Compare  compare_t;\n\ttypedef WayIter  way_iter_t;\n\ttypedef boost::mpl::true_  TriCompare1, StableSort1;\n\ttypedef boost::mpl::false_ TriCompare0, StableSort0;\n\n\tclass HeapCompare {\n\t\tconst HeapMultiWay_TrivalWayIter& heap;\n\tpublic:\n\t\t//! 反转输入参数，用做堆操作的比较\n\t\tbool operator()(const way_iter_t& x, const way_iter_t& y) const {\n\t\t\tassert(x.first != x.second);\n\t\t\tassert(y.first != y.second);\n\t\t\tboost::integral_constant<bool, StableSort> is_stable_sort;\n\t\t\treturn heap.comp_item_aux(y, x, is_stable_sort);\n\t\t}\n\t\texplicit HeapCompare(const HeapMultiWay_TrivalWayIter& heap) : heap(heap) {}\n\t};\n\tfriend class HeapCompare;\n\npublic:\n\tHeapMultiWay_TrivalWayIter(Compare comp = Compare()) : Compare(comp) {}\n\n\tvoid start() {\n\t#ifndef NDEBUG\n\t\tfor (size_t i = 0, n = m_ways.size(); i < n; ++i) {\n\t\t\tassert(m_ways[i].first != m_ways[i].second); }\n\t#endif\n\t\tm_old_size = m_ways.size();\n\t\tstd::make_heap(m_ways.begin(), m_ways.end(), HeapCompare(*this));\n\t}\n\n\tbool empty() { return m_ways.empty(); }\n\n\tconst value_type& current_value() const {\n\t\tassert(!m_ways.empty());\n\t\treturn *m_ways.front().first;\n\t}\n\n\tconst WayIter& current_input() const {\n\t\tassert(!m_ways.empty());\n\t\treturn  m_ways.front();\n\t}\n\n\tsize_t current_way() const {\n\t\tassert(!m_ways.empty());\n\t\treturn  m_ways.front().index;\n\t}\n\n\tvoid increment() {\n\t\tassert(!m_ways.empty());\n\t\t++m_ways.front().first;\n\t\tajust_for_update_top();\n\t}\n\n\tvoid ajust_for_update_top() {\n\t\tif (FirstEqualSecond()(m_ways.front())) {\n\t\t\tpop_heap_ignore_top(m_ways.begin(), m_ways.end(), HeapCompare(*this));\n\t\t\tm_ways.pop_back();\n\t\t} else\n\t\t\tadjust_heap_top(m_ways.begin(), m_ways.end(), HeapCompare(*this));\n\t}\n\n\tWayIter& top_iter() { assert(!m_ways.empty()); return m_ways.front(); }\n\n\t/*\n\t @par 图示如下：\n\t @code\n\t   [                m_ways                   ]\n\t 0 [first..............................second]\n\t 1 [first..............................second]\n\t 2 [first..............................second] <--- 每个序列均已按 comp 排序\n\t 3 [first..............................second]\n\t 4 [first..............................second]\n\t 5 [first..............................second]\n\t @endcode\n\t way_iter_t 是一个 pair<_InIt, _InIt>，表示一个递增序列 [first, second)\n\t*/\n\tstd::vector<way_iter_t> m_ways; // public\nprivate:\n\tsize_t     m_old_size;\n\n\tinline bool\n\tcomp_item_aux(const way_iter_t& x, const way_iter_t& y, StableSort0) const {\n\t\tassert(x.first != x.second);\n\t\tassert(y.first != y.second);\n\t\treturn (*this)(*x.first, *y.first);\n\t}\n\tinline bool\n\tcomp_item_aux(const way_iter_t& x, const way_iter_t& y, StableSort1) const {\n\t\tassert(x.first != x.second);\n\t\tassert(y.first != y.second);\n\t\treturn comp_key_stable(x.index, y.index, *x.first, *y.first,\n\t\t\t\ttypename HasTriCompare<Compare>::type());\n\t}\n\tinline bool\n\tcomp_key_stable(size_t x, size_t y, const value_type& kx, const value_type& ky, TriCompare1) const {\n\t\tptrdiff_t ret = Compare::compare(kx, ky);\n\t\tif (ret < 0) return true;\n\t\tif (ret > 0) return false;\n\t\telse         return x < y;\n\t}\n\tinline bool\n\tcomp_key_stable(size_t x, size_t y, const value_type& kx, const value_type& ky, TriCompare0) const {\n\t\tconst Compare& cmp = *this;\n\t\tif (cmp(kx, ky)) return true;\n\t\tif (cmp(ky, kx)) return false;\n\t\telse             return x < y;\n\t}\npublic:\n\tsize_t total_ways() const { return m_old_size; }\n\tbool is_any_way_end() const { return m_ways.size() != m_old_size; }\n\ntypedef HeapMultiWay_TrivalWayIter MyType;\n#include \"multi_way_basic.hpp\"\n#include \"multi_way_algo_heap.hpp\"\n};\n\ntemplate< class InputIter\n\t\t, class KeyType = typename std::iterator_traits<InputIter>::value_type\n\t\t, bool StableSort = false //!< same Key in various way will output by way order\n\t\t, class Compare = std::less<KeyType>\n\t\t, class KeyExtractor = typename boost::mpl::if_c<\n\t\t\t\tboost::is_same<KeyType,\n\t\t\t\t\ttypename std::iterator_traits<InputIter>::value_type\n\t\t\t\t\t\t\t  >::value,\n\t\t\t\tboost::multi_index::identity<KeyType>,\n\t\t\t\tMustProvideKeyExtractor\n\t\t\t>::type\n\t    , class HowCache = tag_cache_default\n\t\t>\nclass HeapMultiWay : private Compare,\n\tpublic CacheStrategy<InputIter, KeyType, KeyExtractor, HowCache>\n{\n\tDECLARE_NONE_COPYABLE_CLASS(HeapMultiWay)\n\ttypedef CacheStrategy<InputIter, KeyType, KeyExtractor, HowCache> super;\npublic:\n\ttypedef std::pair<InputIter, InputIter>  iipair;\n\ttypedef typename std::iterator_traits<InputIter>::value_type value_type;\n\ttypedef KeyType      key_type;\n\ttypedef KeyExtractor key_extractor;\n\ttypedef typename super::cache_category cache_category;\n\ttypedef boost::mpl::true_  TriCompare1, StableSort1;\n\ttypedef boost::mpl::false_ TriCompare0, StableSort0;\n\n\tclass HeapCompare {\n\t\tconst HeapMultiWay& heap;\n\tpublic:\n\t\t//! 反转输入参数，用做堆操作的比较\n\t\tinline bool operator()(size_t x, size_t y) const {\n\t\t\tassert(heap.m_ways[x].first != heap.m_ways[x].second);\n\t\t\tassert(heap.m_ways[y].first != heap.m_ways[y].second);\n\t\t\tboost::integral_constant<bool, StableSort> is_stable_sort;\n\t\t\treturn heap.comp_cache_item(y, x, cache_category(), is_stable_sort);\n\t\t}\n\t\texplicit HeapCompare(const HeapMultiWay& heap) : heap(heap) {}\n\t};\n\tfriend class HeapCompare;\n\npublic:\n\t/**\n\t @brief construct\n\n\t @par 图示如下：\n\t @code\n\t m_ways     first                              second\n      ||         ||                                   ||\n\t  ||         ||                                   ||\n\t  \\/         \\/                                   \\/\n\t  0 iipair [min_value..............................)\n\t  1 iipair [min_value..............................) <--- 每个序列均已\n\t  2 iipair [min_value..............................)      按 comp 排序\n\t  3 iipair [min_value..............................)\n\t  4 iipair [min_value..............................)\n\t  5 iipair [min_value..............................)\n\t  7 iipair [min_value..............................)\n\t  8 iipair [min_value..............................)\n\t @endcode\n\n\t @param first, last [in,out] 每个元素都是一个 iipair, 表示一个递增子序列 [first, second)\n\t @param comp    value 的比较器\n\n\t @note\n\t  - 一般情况下，这个类的性能不如 LoserTree, 但是，这个类也有一些优点：\n\t    - 对每个序列用 make_pair(first, last) 来表示，概念上更清晰\n\t    - 序列最后不需要一个 max_value 结束标志，这一点上胜于 LoserTree\n\t\t  - 当无法提供 max_value 时，使用这个类也许是更好的办法，比如当 int key 在整个 int 值域内都有定义时\n\t  - LoserTree 的每个序列只用一个 iterator 表示，序列结束用 MAX_KEY 做标志\n\t */\n\tHeapMultiWay(const Compare& comp = Compare(),\n\t\t\t\t const KeyExtractor& keyExtractor = KeyExtractor())\n\t{\n\t\tstatic_cast<KeyExtractor&>(*this) = keyExtractor;\n\t}\n\tvoid start() {\n\t\tassert(!m_ways.empty());\n\t\tm_old_size = m_ways.size();\n\t\tm_heap.reserve(m_old_size);\n\t\tthis->resize_cache(m_old_size);\n\t\tfor (size_t way_idx = 0; way_idx < m_old_size; ++way_idx) {\n\t\t\tif (m_ways[way_idx].first != m_ways[way_idx].second) {\n\t\t\t\tm_heap.push_back(way_idx);\n\t\t\t\t// read first value from every sequence\n\t\t\t\tthis->load_cache_item(way_idx, m_ways[way_idx].first);\n\t\t\t}\n\t\t}\n\t\tstd::make_heap(m_heap.begin(), m_heap.end(), HeapCompare(*this));\n\t}\n\n\tbool empty() const { return m_heap.empty(); }\n\n\tconst value_type& current_value() const {\n\t\tassert(!m_heap.empty());\n\t\treturn current_value_aux(cache_category());\n\t}\n\tsize_t current_way() const { assert(!m_heap.empty()); return m_heap[0]; }\n\n\tvoid increment() {\n\t\tassert(!m_heap.empty());\n\t\tsize_t top_way = m_heap[0];\n\t\tiipair& top = *(m_ways + top_way);\n\t\t++top.first;\n\t\tif (terark_unlikely(top.first == top.second)) {\n\t\t\tpop_heap_ignore_top(m_heap.begin(), m_heap.end(), HeapCompare(*this));\n\t\t\tm_heap.pop_back();\n\t\t} else {\n\t\t\tthis->load_cache_item(top_way, top.first);\n\t\t\tadjust_heap_top(m_heap.begin(), m_heap.end(), HeapCompare(*this));\n\t\t}\n\t}\n\n\tvoid ajust_for_update_top() {\n\t\tassert(!m_heap.empty());\n\t\tsize_t top_way = m_heap[0];\n\t\tiipair& top = m_ways[top_way];\n\t//\t++top.first; // caller may inc multi for top.first\n\t\tif (terark_unlikely(top.first == top.second)) {\n\t\t\tpop_heap_ignore_top(m_heap.begin(), m_heap.end(), HeapCompare(*this));\n\t\t\tm_heap.pop_back();\n\t\t} else {\n\t\t\tthis->load_cache_item(top_way, top.first);\n\t\t\tadjust_heap_top(m_heap.begin(), m_heap.end(), HeapCompare(*this));\n\t\t}\n\t}\n\n\tiipair& top_iter() { assert(!m_heap.empty()); return m_ways[m_heap[0]]; }\n\nprotected:\n\tconst value_type& current_value_aux(tag_cache_none) const {\n\t\tassert(m_heap[0] < m_old_size);\n\t\treturn *(*(m_ways + m_heap[0])).first;\n\t}\n\tconst value_type& current_value_aux(tag_cache_key) const {\n\t\tassert(m_heap[0] < m_old_size);\n\t\treturn *(*(m_ways + m_heap[0])).first;\n\t}\n\tconst value_type& current_value_aux(tag_cache_value) const {\n\t\tassert(m_heap[0] < m_old_size);\n\t\treturn this->m_cache[m_heap[0]];\n\t}\n\n\tusing super::get_cache_key;\n\tinline KeyType get_cache_key(size_t nth, tag_cache_none) const {\n\t\tassert(nth < m_old_size);\n\t\tconst iipair& p = *(m_ways + nth);\n\t\tassert(p.first != p.second);\n\t\treturn this->get_key(*p.first);\n\t}\n\n\ttemplate<class CacheCategory>\n\tinline bool\n\tcomp_cache_item(size_t x, size_t y,\tCacheCategory, StableSort0) const {\n\t\tconst KeyType& kx = get_cache_key(x, CacheCategory());\n\t\tconst KeyType& ky = get_cache_key(y, CacheCategory());\n\t\treturn static_cast<const Compare&>(*this)(kx, ky);\n\t}\n\ttemplate<class CacheCategory>\n\tinline bool\n\tcomp_cache_item(size_t x, size_t y, CacheCategory, StableSort1) const {\n\t\tconst KeyType& kx = get_cache_key(x, CacheCategory());\n\t\tconst KeyType& ky = get_cache_key(y, CacheCategory());\n\t\treturn comp_key_stable(x, y, kx, ky, HasTriCompare<Compare>());\n\t}\n\tinline bool\n\tcomp_key_stable(size_t x, size_t y, const KeyType& kx, const KeyType& ky, TriCompare1) const {\n\t\tptrdiff_t ret = Compare::compare(kx, ky);\n\t\tif (ret < 0) return true;\n\t\tif (ret > 0) return false;\n\t\telse         return x < y;\n\t}\n\tinline bool\n\tcomp_key_stable(size_t x, size_t y, const KeyType& kx, const KeyType& ky, TriCompare0) const {\n\t\tconst Compare& cmp = *this;\n\t\tif (cmp(kx, ky)) return true;\n\t\tif (cmp(ky, kx)) return false;\n\t\telse             return x < y;\n\t}\n\n\tbool is_any_way_end() const { return m_heap.size() != m_old_size; }\n\tsize_t total_ways() const { return m_old_size; }\n\nprotected:\n\tstd::vector<iipair> m_ways;\n\tstd::vector<size_t> m_heap;\n\tsize_t\t\t\tm_old_size;\n\ntypedef HeapMultiWay MyType;\n#include \"multi_way_basic.hpp\"\n#include \"multi_way_algo_heap.hpp\"\n};\n\n\n//! TODO:\n\ntemplate<class InputIterator>\nclass InputIteratorReader {\n\tInputIterator m_end;\npublic:\n\tbool empty(const InputIterator& iter) const { return iter != m_end; }\n};\n\n/**\n @brief 当相同元素的数目超过 minDup 时，将元素拷贝到输出\n\n 这是一个很有用的 multi_way_copy_if._Cond, 并且也作为一个编写 _Cond 的示例\n 可以在 MultiWay_CopyAtLeastDup 中对 value 进行某方面的统计（例如记录每个 value 的重复次数）\n */\nclass MultiWay_CopyAtLeastDup {\n\tptrdiff_t m_minDup;\npublic:\n\tMultiWay_CopyAtLeastDup(ptrdiff_t minDup) : m_minDup(minDup) {}\n\n\ttemplate<class ValueT>\n\tbool operator()(ptrdiff_t equal_count,\n\t\t\t\t\tconst ValueT& /*prev_value*/,\n\t\t\t\t\tconst ValueT& /*curr_value*/) const\n\t{\n\t\t// 仅当 equal_count 第一次达到 m_minDup 时才返回 true\n\t\t// 返回 equal_count >= m_minDup 会导致多次拷贝\n\n\t\treturn equal_count == m_minDup;\n\t}\n};\n\n} // namespace multi_way\n\ntemplate<class Container>\nclass any_inserter_iterator :\n\tpublic std::iterator<std::output_iterator_tag, typename Container::value_type>\n{\npublic:\n\ttypedef Container container_type;\n\ttypedef typename Container::reference reference;\n\n\texplicit any_inserter_iterator(Container& _Cont) : container(&_Cont) {}\n\n\ttemplate<class T>\n\tany_inserter_iterator&\n\toperator=(const T& x) { container->insert(x); return *this; }\n\n\t// pretend to return designated value\n\tany_inserter_iterator& operator*() { return *this; }\n\n\t// pretend to preincrement\n\tany_inserter_iterator& operator++() { return *this; }\n\n\t// pretend to postincrement\n\tany_inserter_iterator operator++(int) { return *this; }\n\nprotected:\n\tContainer *container;\n};\n\ntemplate<class Container>\nany_inserter_iterator<Container>\nany_inserter(Container& c) { return any_inserter_iterator<Container>(c); }\n\n} // namespace terark\n", "meta": {"hexsha": "49d471dcc7222895a7410cccfdae395562ca84c2", "size": 38966, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/terark/set_op.hpp", "max_stars_repo_name": "topling/topling-zip", "max_stars_repo_head_hexsha": "32c0218091c6a47c5c8a1811bfd0afa5107befd9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-11-19T04:57:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T12:44:17.000Z", "max_issues_repo_path": "src/terark/set_op.hpp", "max_issues_repo_name": "topling/topling-zip", "max_issues_repo_head_hexsha": "32c0218091c6a47c5c8a1811bfd0afa5107befd9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/terark/set_op.hpp", "max_forks_repo_name": "topling/topling-zip", "max_forks_repo_head_hexsha": "32c0218091c6a47c5c8a1811bfd0afa5107befd9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T10:17:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T10:17:01.000Z", "avg_line_length": 30.8763866878, "max_line_length": 112, "alphanum_fraction": 0.6797207822, "num_tokens": 11512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.046724963438088754, "lm_q1q2_score": 0.022450348664569676}}
{"text": "/*\nAll modification made by Intel Corporation: © 2016 Intel Corporation\n\nAll contributions by the University of California:\nCopyright (c) 2014, 2015, The Regents of the University of California (Regents)\nAll rights reserved.\n\nAll other contributions:\nCopyright (c) 2014, 2015, the respective contributors\nAll rights reserved.\nFor the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md\n\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,\n      this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and/or other materials provided with the distribution.\n    * Neither the name of Intel Corporation nor the names of its contributors\n      may be used to endorse or promote products derived from this software\n      without specific prior written permission.\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 OWNER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#if USE_MKL\n#include <mkl_vml_functions.h>\n#include <mkl_vsl.h>\n#endif\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <algorithm>\n#include <limits>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/cpu_info.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\nnamespace caffe {\n\ntemplate<>\nvoid caffe_cpu_gemm<float>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float alpha, const float* A, const float* B, const float beta,\n    float* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\ntemplate<>\nvoid caffe_cpu_gemm<double>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const double alpha, const double* A, const double* B, const double beta,\n    double* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<float>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float alpha, const float* A, const float* x,\n    const float beta, float* y) {\n  cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<double>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const double alpha, const double* A, const double* x,\n    const double beta, double* y) {\n  cblas_dgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_axpy<float>(const int N, const float alpha, const float* X,\n    float* Y) { cblas_saxpy(N, alpha, X, 1, Y, 1); }\n\ntemplate <>\nvoid caffe_axpy<double>(const int N, const double alpha, const double* X,\n    double* Y) { cblas_daxpy(N, alpha, X, 1, Y, 1); }\n\ntemplate <typename Dtype>\nvoid caffe_set(const int N, const Dtype alpha, Dtype* Y) {\n  // If we are executing parallel region already then do not start another one\n  // if also number of data to be processed is smaller than arbitrary:\n  // threashold 12*4 cachelines per thread then no parallelization is to be made\n  #ifdef _OPENMP\n\n  int nthr = omp_get_max_threads();\n  int threshold = nthr * caffe::cpu::OpenMpManager::getProcessorSpeedMHz() / 3;\n  bool run_parallel =  // Do not do parallel computation from non major threads\n       caffe::cpu::OpenMpManager::isMajorThread(boost::this_thread::get_id());\n\n  // Note: we Assume GPU's CPU path is single threaded\n  if (omp_in_parallel() == 0) {\n    // inactive parallel region may mean also batch 1,\n    // but no new threads are to be created\n    run_parallel = run_parallel && (Caffe::mode() != Caffe::GPU) &&\n                   (N >= threshold);\n  } else {\n    // If we are running active parallel region then it is CPU\n    run_parallel = run_parallel && (N >= threshold);\n  }\n\n  if (run_parallel) {\n    #pragma omp parallel for\n    for (int i = 0; i < N; ++i) {\n      Y[i] = alpha;\n    }\n\n    return;\n  }\n\n  #endif\n\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n  } else {\n    std::fill(Y, Y + N, alpha);\n  }\n}\n\ntemplate void caffe_set<char>(const int N, const char alpha, char* Y);\ntemplate void caffe_set<int>(const int N, const int alpha, int* Y);\ntemplate void caffe_set<float>(const int N, const float alpha, float* Y);\ntemplate void caffe_set<double>(const int N, const double alpha, double* Y);\ntemplate void caffe_set<size_t>(const int N, const size_t alpha, size_t* Y);\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const float alpha, float* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const double alpha, double* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <typename Dtype>\nvoid caffe_cpu_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X == Y) return;\n\n#ifdef _OPENMP\n  static const int threshold = omp_get_max_threads() *\n                          caffe::cpu::OpenMpManager::getProcessorSpeedMHz() / 3;\n  const bool run_parallel =\n    (N >= threshold) &&\n    (omp_in_parallel() == 0) &&\n    (Caffe::mode() != Caffe::GPU) &&\n    (caffe::cpu::OpenMpManager::isMajorThread(boost::this_thread::get_id()));\n\n  if (run_parallel) {\n    const int block_mem_size = 256*1024;\n    const int block_size = block_mem_size / sizeof(Dtype);\n    #pragma omp parallel for\n    for (int i = 0; i < N; i += block_size)\n      memcpy(Y + i, X + i,\n              (i + block_size > N) ? (N-i)*sizeof(Dtype): block_mem_size);\n\n    return;\n  }\n#endif\n\n  memcpy(Y, X, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n}\n\ntemplate void caffe_cpu_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_cpu_copy<unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate void caffe_cpu_copy<float>(const int N, const float* X, float* Y);\ntemplate void caffe_cpu_copy<double>(const int N, const double* X, double* Y);\n\ntemplate <typename Dtype>\nvoid caffe_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X != Y) {\n#ifndef CPU_ONLY\n    if (\n#ifdef _OPENMP\n         // If there are more than one openmp thread (we are in active region)\n         // then checking Caffe::mode can create additional GPU Context\n        (omp_in_parallel() == 0) &&\n#endif\n        (Caffe::mode() == Caffe::GPU)) {\n      // NOLINT_NEXT_LINE(caffe/alt_fn)\n      CUDA_CHECK(cudaMemcpy(Y, X, sizeof(Dtype) * N, cudaMemcpyDefault));\n    } else {\n#endif\n      caffe_cpu_copy<Dtype>(N, X, Y);\n#ifndef CPU_ONLY\n    }\n#endif\n  }\n}\n\ntemplate void caffe_copy<bool>(const int N, const bool* X, bool* Y);\ntemplate void caffe_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_copy<unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate void caffe_copy<float>(const int N, const float* X, float* Y);\ntemplate void caffe_copy<double>(const int N, const double* X, double* Y);\ntemplate void caffe_copy<char>(const int N, const char* X, char* Y);\ntemplate void caffe_copy<size_t>(const int N, const size_t* X, size_t* Y);\n\ntemplate <>\nvoid caffe_scal<float>(const int N, const float alpha, float *X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<double>(const int N, const double alpha, double *X) {\n  cblas_dscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<size_t>(const int N, const size_t alpha, size_t *X) {\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_axpy<size_t>(const int N, const size_t alpha, const size_t* X,\n    size_t* Y) { }\n\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_add<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<float>(const int n, const float* a, const float b,\n    float* y) {\n  vsPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<double>(const int n, const double* a, const double b,\n    double* y) {\n  vdPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sqr<float>(const int n, const float* a, float* y) {\n  vsSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqr<double>(const int n, const double* a, double* y) {\n  vdSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<float>(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<double>(const int n, const double* a, double* y) {\n  vdExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<float>(const int n, const float* a, float* y) {\n  vsLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<double>(const int n, const double* a, double* y) {\n  vdLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<float>(const int n, const float* a, float* y) {\n    vsAbs(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<double>(const int n, const double* a, double* y) {\n    vdAbs(n, a, y);\n}\n\nunsigned int caffe_rng_rand() {\n#ifdef DETERMINISTIC\n    return 5153;\n#else\n    return (*caffe_rng())();\n#endif\n}\n\ntemplate <typename Dtype>\nDtype caffe_nextafter(const Dtype b) {\n  return boost::math::nextafter<Dtype>(\n      b, std::numeric_limits<Dtype>::max());\n}\n\ntemplate\nfloat caffe_nextafter(const float b);\n\ntemplate\ndouble caffe_nextafter(const double b);\n\ntemplate <typename Dtype>\nvoid caffe_rng_uniform(const int n, const Dtype a, const Dtype b, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_LE(a, b);\n  boost::uniform_real<Dtype> random_distribution(a, caffe_nextafter<Dtype>(b));\n  boost::variate_generator<caffe::rng_t*, boost::uniform_real<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\nvoid caffe_rng_uniform<float>(const int n, const float a, const float b,\n                              float* r);\n\ntemplate\nvoid caffe_rng_uniform<double>(const int n, const double a, const double b,\n                               double* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_gaussian(const int n, const Dtype a,\n                        const Dtype sigma, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GT(sigma, 0);\n  boost::normal_distribution<Dtype> random_distribution(a, sigma);\n  boost::variate_generator<caffe::rng_t*, boost::normal_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\nvoid caffe_rng_gaussian<float>(const int n, const float mu,\n                               const float sigma, float* r);\n\ntemplate\nvoid caffe_rng_gaussian<double>(const int n, const double mu,\n                                const double sigma, double* r);\n\n#ifdef USE_MKL\nstatic void bernoulli_generate(int n, double p, int* r) {\n  int seed = 17 + caffe_rng_rand() % 4096;\n\n#ifdef _OPENMP\n  int nthr = omp_get_max_threads();\n  int threshold = nthr * caffe::cpu::OpenMpManager::getProcessorSpeedMHz() / 3;\n  bool run_parallel =\n    (Caffe::mode() != Caffe::GPU) &&\n    (omp_in_parallel() == 0) &&\n    (n >= threshold);\n  if (!run_parallel) nthr = 1;\n\n# pragma omp parallel num_threads(nthr)\n  {\n    const int ithr = omp_get_thread_num();\n    const int avg_amount = (n + nthr - 1) / nthr;\n    const int my_offset = ithr * avg_amount;\n    const int my_amount = std::min(my_offset + avg_amount, n) - my_offset;\n#else\n  {\n    const int my_amount = n;\n    const int my_offset = 0;\n#endif\n\n    if (my_amount > 0) {\n      VSLStreamStatePtr stream;\n      vslNewStream(&stream, VSL_BRNG_MCG31, seed);\n      vslSkipAheadStream(stream, my_offset);\n      viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, stream, my_amount,\n        r + my_offset, p);\n      vslDeleteStream(&stream);\n    }\n  }\n}\n#endif\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n#ifdef USE_MKL\n  bernoulli_generate(n, p, r);\n#else\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n#endif\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double>(const int n, const double p, int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float>(const int n, const float p, int* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, unsigned int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n#ifdef USE_MKL\n  bernoulli_generate(n, p, reinterpret_cast<int *>(r));\n#else\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n#endif\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double>(const int n, const double p, unsigned int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float>(const int n, const float p, unsigned int* r);\n\ntemplate <>\nfloat caffe_cpu_strided_dot<float>(const int n, const float* x, const int incx,\n    const float* y, const int incy) {\n  return cblas_sdot(n, x, incx, y, incy);\n}\n\ntemplate <>\ndouble caffe_cpu_strided_dot<double>(const int n, const double* x,\n    const int incx, const double* y, const int incy) {\n  return cblas_ddot(n, x, incx, y, incy);\n}\n\ntemplate <>\nsize_t caffe_cpu_strided_dot<size_t>(const int n, const size_t* x,\n        const int incx, const size_t* y, const int incy) {\n  return 0;\n}\n\ntemplate <typename Dtype>\nDtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y) {\n  return caffe_cpu_strided_dot(n, x, 1, y, 1);\n}\n\ntemplate\nfloat caffe_cpu_dot<float>(const int n, const float* x, const float* y);\n\ntemplate\ndouble caffe_cpu_dot<double>(const int n, const double* x, const double* y);\n\ntemplate\nsize_t caffe_cpu_dot<size_t>(const int n, const size_t* x, const size_t* y);\n\ntemplate <>\nfloat caffe_cpu_asum<float>(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_asum<double>(const int n, const double* x) {\n  return cblas_dasum(n, x, 1);\n}\n\ntemplate <>\nsize_t caffe_cpu_asum<size_t>(const int n, const size_t* x) {\n  return 0;\n}\n\ntemplate <>\nvoid caffe_cpu_scale<float>(const int n, const float alpha, const float *x,\n                            float* y) {\n  cblas_scopy(n, x, 1, y, 1);\n  cblas_sscal(n, alpha, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_scale<double>(const int n, const double alpha, const double *x,\n                             double* y) {\n  cblas_dcopy(n, x, 1, y, 1);\n  cblas_dscal(n, alpha, y, 1);\n}\n\n}  // namespace caffe\n", "meta": {"hexsha": "a777209dc9c689f13326072090868bd43b3bf9d2", "size": 16762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "vraoresearch/caffe", "max_stars_repo_head_hexsha": "b8cb4f59e2ada03b1f9209e768cb03af763068a3", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-29T10:52:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-29T10:52:28.000Z", "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "jlaiman/caffe-yolo-cpp", "max_issues_repo_head_hexsha": "8f374f85f629e73f428d1264a11d2901c1eebfe5", "max_issues_repo_licenses": ["Intel", "BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/util/math_functions.cpp", "max_forks_repo_name": "jlaiman/caffe-yolo-cpp", "max_forks_repo_head_hexsha": "8f374f85f629e73f428d1264a11d2901c1eebfe5", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-29T10:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-29T10:52:30.000Z", "avg_line_length": 29.4070175439, "max_line_length": 92, "alphanum_fraction": 0.6761722945, "num_tokens": 4741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.04672495729864523, "lm_q1q2_score": 0.022450345714697964}}
{"text": "// Copyright 2008 Gautam Sewani\n// Copyright 2008 John Maddock\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_DISTRIBUTIONS_DETAIL_HG_PDF_HPP\n#define BOOST_MATH_DISTRIBUTIONS_DETAIL_HG_PDF_HPP\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/lanczos.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\n#ifdef BOOST_MATH_INSTRUMENT\n#include <typeinfo>\n#endif\n\nnamespace boost{ namespace math{ namespace detail{\n\ntemplate <class T, class Func>\nvoid bubble_down_one(T* first, T* last, Func f)\n{\n   using std::swap;\n   T* next = first;\n   ++next;\n   while((next != last) && (!f(*first, *next)))\n   {\n      swap(*first, *next);\n      ++first;\n      ++next;\n   }\n}\n\ntemplate <class T>\nstruct sort_functor\n{\n   sort_functor(const T* exponents) : m_exponents(exponents){}\n   bool operator()(int i, int j)\n   {\n      return m_exponents[i] > m_exponents[j];\n   }\nprivate:\n   const T* m_exponents;\n};\n\ntemplate <class T, class Lanczos, class Policy>\nT hypergeometric_pdf_lanczos_imp(T /*dummy*/, unsigned x, unsigned r, unsigned n, unsigned N, const Lanczos&, const Policy&)\n{\n   BOOST_MATH_STD_USING\n\n   BOOST_MATH_INSTRUMENT_FPU\n   BOOST_MATH_INSTRUMENT_VARIABLE(x);\n   BOOST_MATH_INSTRUMENT_VARIABLE(r);\n   BOOST_MATH_INSTRUMENT_VARIABLE(n);\n   BOOST_MATH_INSTRUMENT_VARIABLE(N);\n   BOOST_MATH_INSTRUMENT_VARIABLE(typeid(Lanczos).name());\n\n   T bases[9] = {\n      T(n) + static_cast<T>(Lanczos::g()) + 0.5f,\n      T(r) + static_cast<T>(Lanczos::g()) + 0.5f,\n      T(N - n) + static_cast<T>(Lanczos::g()) + 0.5f,\n      T(N - r) + static_cast<T>(Lanczos::g()) + 0.5f,\n      1 / (T(N) + static_cast<T>(Lanczos::g()) + 0.5f),\n      1 / (T(x) + static_cast<T>(Lanczos::g()) + 0.5f),\n      1 / (T(n - x) + static_cast<T>(Lanczos::g()) + 0.5f),\n      1 / (T(r - x) + static_cast<T>(Lanczos::g()) + 0.5f),\n      1 / (T(N - n - r + x) + static_cast<T>(Lanczos::g()) + 0.5f)\n   };\n   T exponents[9] = {\n      n + T(0.5f),\n      r + T(0.5f),\n      N - n + T(0.5f),\n      N - r + T(0.5f),\n      N + T(0.5f),\n      x + T(0.5f),\n      n - x + T(0.5f),\n      r - x + T(0.5f),\n      N - n - r + x + T(0.5f)\n   };\n   int base_e_factors[9] = {\n      -1, -1, -1, -1, 1, 1, 1, 1, 1\n   };\n   int sorted_indexes[9] = {\n      0, 1, 2, 3, 4, 5, 6, 7, 8\n   };\n#ifdef BOOST_MATH_INSTRUMENT\n   BOOST_MATH_INSTRUMENT_FPU\n   for(unsigned i = 0; i < 9; ++i)\n   {\n      BOOST_MATH_INSTRUMENT_VARIABLE(i);\n      BOOST_MATH_INSTRUMENT_VARIABLE(bases[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(exponents[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(base_e_factors[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(sorted_indexes[i]);\n   }\n#endif\n   std::sort(sorted_indexes, sorted_indexes + 9, sort_functor<T>(exponents));\n#ifdef BOOST_MATH_INSTRUMENT\n   BOOST_MATH_INSTRUMENT_FPU\n   for(unsigned i = 0; i < 9; ++i)\n   {\n      BOOST_MATH_INSTRUMENT_VARIABLE(i);\n      BOOST_MATH_INSTRUMENT_VARIABLE(bases[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(exponents[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(base_e_factors[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(sorted_indexes[i]);\n   }\n#endif\n\n   do{\n      exponents[sorted_indexes[0]] -= exponents[sorted_indexes[1]];\n      bases[sorted_indexes[1]] *= bases[sorted_indexes[0]];\n      if((bases[sorted_indexes[1]] < tools::min_value<T>()) && (exponents[sorted_indexes[1]] != 0))\n      {\n         return 0;\n      }\n      base_e_factors[sorted_indexes[1]] += base_e_factors[sorted_indexes[0]];\n      bubble_down_one(sorted_indexes, sorted_indexes + 9, sort_functor<T>(exponents));\n\n#ifdef BOOST_MATH_INSTRUMENT\n      for(unsigned i = 0; i < 9; ++i)\n      {\n         BOOST_MATH_INSTRUMENT_VARIABLE(i);\n         BOOST_MATH_INSTRUMENT_VARIABLE(bases[i]);\n         BOOST_MATH_INSTRUMENT_VARIABLE(exponents[i]);\n         BOOST_MATH_INSTRUMENT_VARIABLE(base_e_factors[i]);\n         BOOST_MATH_INSTRUMENT_VARIABLE(sorted_indexes[i]);\n      }\n#endif\n   }while(exponents[sorted_indexes[1]] > 1);\n\n   //\n   // Combine equal powers:\n   //\n   int j = 8;\n   while(exponents[sorted_indexes[j]] == 0) --j;\n   while(j)\n   {\n      while(j && (exponents[sorted_indexes[j-1]] == exponents[sorted_indexes[j]]))\n      {\n         bases[sorted_indexes[j-1]] *= bases[sorted_indexes[j]];\n         exponents[sorted_indexes[j]] = 0;\n         base_e_factors[sorted_indexes[j-1]] += base_e_factors[sorted_indexes[j]];\n         bubble_down_one(sorted_indexes + j, sorted_indexes + 9, sort_functor<T>(exponents));\n         --j;\n      }\n      --j;\n\n#ifdef BOOST_MATH_INSTRUMENT\n      BOOST_MATH_INSTRUMENT_VARIABLE(j);\n      for(unsigned i = 0; i < 9; ++i)\n      {\n         BOOST_MATH_INSTRUMENT_VARIABLE(i);\n         BOOST_MATH_INSTRUMENT_VARIABLE(bases[i]);\n         BOOST_MATH_INSTRUMENT_VARIABLE(exponents[i]);\n         BOOST_MATH_INSTRUMENT_VARIABLE(base_e_factors[i]);\n         BOOST_MATH_INSTRUMENT_VARIABLE(sorted_indexes[i]);\n      }\n#endif\n   }\n\n#ifdef BOOST_MATH_INSTRUMENT\n   BOOST_MATH_INSTRUMENT_FPU\n   for(unsigned i = 0; i < 9; ++i)\n   {\n      BOOST_MATH_INSTRUMENT_VARIABLE(i);\n      BOOST_MATH_INSTRUMENT_VARIABLE(bases[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(exponents[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(base_e_factors[i]);\n      BOOST_MATH_INSTRUMENT_VARIABLE(sorted_indexes[i]);\n   }\n#endif\n\n   T result;\n   BOOST_MATH_INSTRUMENT_VARIABLE(bases[sorted_indexes[0]] * exp(static_cast<T>(base_e_factors[sorted_indexes[0]])));\n   BOOST_MATH_INSTRUMENT_VARIABLE(exponents[sorted_indexes[0]]);\n   {\n      BOOST_FPU_EXCEPTION_GUARD\n      result = pow(bases[sorted_indexes[0]] * exp(static_cast<T>(base_e_factors[sorted_indexes[0]])), exponents[sorted_indexes[0]]);\n   }\n   BOOST_MATH_INSTRUMENT_VARIABLE(result);\n   for(unsigned i = 1; (i < 9) && (exponents[sorted_indexes[i]] > 0); ++i)\n   {\n      BOOST_FPU_EXCEPTION_GUARD\n      if(result < tools::min_value<T>())\n         return 0; // short circuit further evaluation\n      if(exponents[sorted_indexes[i]] == 1)\n         result *= bases[sorted_indexes[i]] * exp(static_cast<T>(base_e_factors[sorted_indexes[i]]));\n      else if(exponents[sorted_indexes[i]] == 0.5f)\n         result *= sqrt(bases[sorted_indexes[i]] * exp(static_cast<T>(base_e_factors[sorted_indexes[i]])));\n      else\n         result *= pow(bases[sorted_indexes[i]] * exp(static_cast<T>(base_e_factors[sorted_indexes[i]])), exponents[sorted_indexes[i]]);\n   \n      BOOST_MATH_INSTRUMENT_VARIABLE(result);\n   }\n\n   result *= Lanczos::lanczos_sum_expG_scaled(static_cast<T>(n + 1))\n      * Lanczos::lanczos_sum_expG_scaled(static_cast<T>(r + 1))\n      * Lanczos::lanczos_sum_expG_scaled(static_cast<T>(N - n + 1))\n      * Lanczos::lanczos_sum_expG_scaled(static_cast<T>(N - r + 1))\n      / \n      ( Lanczos::lanczos_sum_expG_scaled(static_cast<T>(N + 1))\n         * Lanczos::lanczos_sum_expG_scaled(static_cast<T>(x + 1))\n         * Lanczos::lanczos_sum_expG_scaled(static_cast<T>(n - x + 1))\n         * Lanczos::lanczos_sum_expG_scaled(static_cast<T>(r - x + 1))\n         * Lanczos::lanczos_sum_expG_scaled(static_cast<T>(N - n - r + x + 1)));\n   \n   BOOST_MATH_INSTRUMENT_VARIABLE(result);\n   return result;\n}\n\ntemplate <class T, class Policy>\nT hypergeometric_pdf_lanczos_imp(T /*dummy*/, unsigned x, unsigned r, unsigned n, unsigned N, const boost::math::lanczos::undefined_lanczos&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   return exp(\n      boost::math::lgamma(T(n + 1), pol)\n      + boost::math::lgamma(T(r + 1), pol)\n      + boost::math::lgamma(T(N - n + 1), pol)\n      + boost::math::lgamma(T(N - r + 1), pol)\n      - boost::math::lgamma(T(N + 1), pol)\n      - boost::math::lgamma(T(x + 1), pol)\n      - boost::math::lgamma(T(n - x + 1), pol)\n      - boost::math::lgamma(T(r - x + 1), pol)\n      - boost::math::lgamma(T(N - n - r + x + 1), pol));\n}\n\ntemplate <class T>\ninline T integer_power(const T& x, int ex)\n{\n   if(ex < 0)\n      return 1 / integer_power(x, -ex);\n   switch(ex)\n   {\n   case 0:\n      return 1;\n   case 1:\n      return x;\n   case 2:\n      return x * x;\n   case 3:\n      return x * x * x;\n   case 4:\n      return boost::math::pow<4>(x);\n   case 5:\n      return boost::math::pow<5>(x);\n   case 6:\n      return boost::math::pow<6>(x);\n   case 7:\n      return boost::math::pow<7>(x);\n   case 8:\n      return boost::math::pow<8>(x);\n   }\n   BOOST_MATH_STD_USING\n#ifdef __SUNPRO_CC\n   return pow(x, T(ex));\n#else\n   return pow(x, ex);\n#endif\n}\ntemplate <class T>\nstruct hypergeometric_pdf_prime_loop_result_entry\n{\n   T value;\n   const hypergeometric_pdf_prime_loop_result_entry* next;\n};\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4510 4512 4610)\n#endif\n\nstruct hypergeometric_pdf_prime_loop_data\n{\n   const unsigned x;\n   const unsigned r;\n   const unsigned n;\n   const unsigned N;\n   unsigned prime_index;\n   unsigned current_prime;\n};\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\ntemplate <class T>\nT hypergeometric_pdf_prime_loop_imp(hypergeometric_pdf_prime_loop_data& data, hypergeometric_pdf_prime_loop_result_entry<T>& result)\n{\n   while(data.current_prime <= data.N)\n   {\n      unsigned base = data.current_prime;\n      int prime_powers = 0;\n      while(base <= data.N)\n      {\n         prime_powers += data.n / base;\n         prime_powers += data.r / base;\n         prime_powers += (data.N - data.n) / base;\n         prime_powers += (data.N - data.r) / base;\n         prime_powers -= data.N / base;\n         prime_powers -= data.x / base;\n         prime_powers -= (data.n - data.x) / base;\n         prime_powers -= (data.r - data.x) / base;\n         prime_powers -= (data.N - data.n - data.r + data.x) / base;\n         base *= data.current_prime;\n      }\n      if(prime_powers)\n      {\n         T p = integer_power<T>(static_cast<T>(data.current_prime), prime_powers);\n         if((p > 1) && (tools::max_value<T>() / p < result.value))\n         {\n            //\n            // The next calculation would overflow, use recursion\n            // to sidestep the issue:\n            //\n            hypergeometric_pdf_prime_loop_result_entry<T> t = { p, &result };\n            data.current_prime = prime(++data.prime_index);\n            return hypergeometric_pdf_prime_loop_imp<T>(data, t);\n         }\n         if((p < 1) && (tools::min_value<T>() / p > result.value))\n         {\n            //\n            // The next calculation would underflow, use recursion\n            // to sidestep the issue:\n            //\n            hypergeometric_pdf_prime_loop_result_entry<T> t = { p, &result };\n            data.current_prime = prime(++data.prime_index);\n            return hypergeometric_pdf_prime_loop_imp<T>(data, t);\n         }\n         result.value *= p;\n      }\n      data.current_prime = prime(++data.prime_index);\n   }\n   //\n   // When we get to here we have run out of prime factors,\n   // the overall result is the product of all the partial\n   // results we have accumulated on the stack so far, these\n   // are in a linked list starting with \"data.head\" and ending\n   // with \"result\".\n   //\n   // All that remains is to multiply them together, taking\n   // care not to overflow or underflow.\n   //\n   // Enumerate partial results >= 1 in variable i\n   // and partial results < 1 in variable j:\n   //\n   hypergeometric_pdf_prime_loop_result_entry<T> const *i, *j;\n   i = &result;\n   while(i && i->value < 1)\n      i = i->next;\n   j = &result;\n   while(j && j->value >= 1)\n      j = j->next;\n\n   T prod = 1;\n\n   while(i || j)\n   {\n      while(i && ((prod <= 1) || (j == 0)))\n      {\n         prod *= i->value;\n         i = i->next;\n         while(i && i->value < 1)\n            i = i->next;\n      }\n      while(j && ((prod >= 1) || (i == 0)))\n      {\n         prod *= j->value;\n         j = j->next;\n         while(j && j->value >= 1)\n            j = j->next;\n      }\n   }\n\n   return prod;\n}\n\ntemplate <class T, class Policy>\ninline T hypergeometric_pdf_prime_imp(unsigned x, unsigned r, unsigned n, unsigned N, const Policy&)\n{\n   hypergeometric_pdf_prime_loop_result_entry<T> result = { 1, 0 };\n   hypergeometric_pdf_prime_loop_data data = { x, r, n, N, 0, prime(0) };\n   return hypergeometric_pdf_prime_loop_imp<T>(data, result);\n}\n\ntemplate <class T, class Policy>\nT hypergeometric_pdf_factorial_imp(unsigned x, unsigned r, unsigned n, unsigned N, const Policy&)\n{\n   BOOST_MATH_STD_USING\n   BOOST_ASSERT(N <= boost::math::max_factorial<T>::value);\n   T result = boost::math::unchecked_factorial<T>(n);\n   T num[3] = {\n      boost::math::unchecked_factorial<T>(r),\n      boost::math::unchecked_factorial<T>(N - n),\n      boost::math::unchecked_factorial<T>(N - r)\n   };\n   T denom[5] = {\n      boost::math::unchecked_factorial<T>(N),\n      boost::math::unchecked_factorial<T>(x),\n      boost::math::unchecked_factorial<T>(n - x),\n      boost::math::unchecked_factorial<T>(r - x),\n      boost::math::unchecked_factorial<T>(N - n - r + x)\n   };\n   int i = 0;\n   int j = 0;\n   while((i < 3) || (j < 5))\n   {\n      while((j < 5) && ((result >= 1) || (i >= 3)))\n      {\n         result /= denom[j];\n         ++j;\n      }\n      while((i < 3) && ((result <= 1) || (j >= 5)))\n      {\n         result *= num[i];\n         ++i;\n      }\n   }\n   return result;\n}\n\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type \n   hypergeometric_pdf(unsigned x, unsigned r, unsigned n, unsigned N, const Policy&)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_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   value_type result;\n   if(N <= boost::math::max_factorial<value_type>::value)\n   {\n      //\n      // If N is small enough then we can evaluate the PDF via the factorials\n      // directly: table lookup of the factorials gives the best performance\n      // of the methods available:\n      //\n      result = detail::hypergeometric_pdf_factorial_imp<value_type>(x, r, n, N, forwarding_policy());\n   }\n   else if(N <= boost::math::prime(boost::math::max_prime - 1))\n   {\n      //\n      // If N is no larger than the largest prime number in our lookup table\n      // (104729) then we can use prime factorisation to evaluate the PDF,\n      // this is slow but accurate:\n      //\n      result = detail::hypergeometric_pdf_prime_imp<value_type>(x, r, n, N, forwarding_policy());\n   }\n   else\n   {\n      //\n      // Catch all case - use the lanczos approximation - where available - \n      // to evaluate the ratio of factorials.  This is reasonably fast\n      // (almost as quick as using logarithmic evaluation in terms of lgamma)\n      // but only a few digits better in accuracy than using lgamma:\n      //\n      result = detail::hypergeometric_pdf_lanczos_imp(value_type(), x, r, n, N, evaluation_type(), forwarding_policy());\n   }\n\n   if(result > 1)\n   {\n      result = 1;\n   }\n   if(result < 0)\n   {\n      result = 0;\n   }\n\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(result, \"boost::math::hypergeometric_pdf<%1%>(%1%,%1%,%1%,%1%)\");\n}\n\n}}} // namespaces\n\n#endif\n\n", "meta": {"hexsha": "4364266514f468b0e35822b858c6b583844e582e", "size": 15527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/distributions/detail/hypergeometric_pdf.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/distributions/detail/hypergeometric_pdf.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/distributions/detail/hypergeometric_pdf.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.7525562372, "max_line_length": 160, "alphanum_fraction": 0.6270367747, "num_tokens": 4386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.04672495331630389, "lm_q1q2_score": 0.022450343801267862}}
{"text": "﻿\r\n/******\r\n6 成员函数模板\r\n6.3 特化\r\n有些资料上说目前的C++标准不允许在类模板之外全特化一个未被特化的类模板（指的是类模板A）的成员函数。\r\n整体感觉：类模板中的成员函数全特化可能还不算太完善，编码时要注意测试。\r\n在实际工作中，建议把这些特化版本写在类模板内部，然后类模板一般也要写在头文件。\r\n\r\n7 类 / 类模板中的类模板（嵌套）\r\n\r\n*****/\r\n\r\n\r\n#include <iostream>\r\n//#include <boost/type_index.hpp>\r\n\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\nnamespace _nmsp1\r\n{\r\n\ttemplate <typename T1>\r\n\tclass A\r\n\t{\r\n\tpublic:\r\n\t\ttemplate <typename T2>\r\n\t\tA(T2 v1, T2 v2); //构造函数模板，引入了自己的模板参数T2，与类A的模板参数T1没有关系\r\n\r\n\tpublic:\r\n\t\tA(double v1, double v2)\r\n\t\t{\r\n\t\t\tcout << \"A::A(double,double)执行了!\" << endl;\r\n\t\t}\r\n\t\tA(T1 v1, T1 v2)\r\n\t\t{\r\n\t\t\tcout << \"A::A(T1,T1)执行了!\" << endl;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t//拷贝构造函数模板\r\n\t\ttemplate <typename U>\r\n\t\tA(const A<U>& other)\r\n\t\t//A(A<U>& other)\r\n\t\t{\r\n\t\t\tcout << \"A::A(const A<U>& other)拷贝构造函数模板执行了!\" << endl;\r\n\t\t}\r\n\r\n\t\t//拷贝赋值运算符模板\r\n\t\ttemplate <typename U>\r\n\t\tA<T1>& operator=(const A<U>& other)\r\n\t\t//A<T1>& operator=(A<U>& other)\r\n\t\t{\r\n\t\t\t//.....\r\n\t\t\tcout << \"operator=(const A<U>& other)拷贝赋值运算符模板执行了!\" << endl;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\t////拷贝赋值运算符\r\n\t\t//A<T1>& operator=(const A<T1>& other)\r\n\t\t//{\r\n\t\t//\tcout << \"operator=(const A<T1>& other)拷贝赋值运算符执行了!\" << endl;\r\n\t\t//\treturn *this;\r\n\t\t//}\r\n\r\n\r\n\t\t//---------------------------------\r\n\t\t/*template <typename T4>\r\n\t\tvirtual void myvirfunc() {}*/\r\n\t\tvirtual void myvirfunc2() {}\r\n\r\n\t\t//----------------------------------\r\n\t\t//template <typename T3>\r\n\t\t//void myft(T3 tmpt) //普通成员函数模板\r\n\t\t//{\r\n\t\t//\tcout << tmpt << endl;\r\n\t\t//}\r\n\t\ttemplate <typename T3, typename T4> //普通成员函数模板\r\n\t\tvoid myft(T3 tmpt,T4 tmpt2)\r\n\t\t{\r\n\t\t\tcout << \"myft()泛化版本\" << endl;\r\n\t\t\tcout << tmpt << endl;\r\n\t\t\tcout << tmpt2 << endl;\r\n\t\t}\r\n\r\n\t\ttemplate <typename T4> //偏特化\r\n\t\tvoid myft(int tmpt, T4 tmpt2);\r\n\t\t/*{\r\n\t\t\tcout << \"myft(int,T4)偏特化版本\" << endl;\r\n\t\t\tcout << tmpt << endl;\r\n\t\t\tcout << tmpt2 << endl;\r\n\t\t}*/\r\n\r\n\t\ttemplate <> //全特化\r\n\t\tvoid myft(int tmpt, float tmpt2);\r\n\t\t/*{\r\n\t\t\tcout << \"myft(int,float)全特化版本\" << endl;\r\n\t\t\tcout << tmpt << endl;\r\n\t\t\tcout << tmpt2 << endl;\r\n\t\t}*/\r\n\r\n\r\n\tpublic:\r\n\t\ttemplate <typename U>\r\n\t\tclass OtherC\r\n\t\t{\r\n\t\tpublic:\r\n\t\t\tvoid myfOC();\r\n\t\t\t/*{\r\n\t\t\t\tcout << \"myfOC执行了\" << endl;\r\n\t\t\t}*/\r\n\t\t};\r\n\r\n\r\n\r\n\t\tT1 m_ic;\r\n\t\tstatic constexpr int m_stcvalue = 200;\r\n\t};\r\n\r\n\t//在类外实现类模板的构造函数模板\r\n\ttemplate <typename T1>\r\n\ttemplate <typename T2>\r\n\tA<T1>::A(T2 v1, T2 v2)\r\n\t{\r\n\t\tcout << \"A::A(T2,T2)执行了!\" << endl;\r\n\t}\r\n\r\n\t//在类外实现类模板A的myft成员函数模板的偏特化版本\r\n\ttemplate <typename T1>\r\n\ttemplate <typename T4>\r\n\tvoid A<T1>::myft(int tmpt, T4 tmpt2)\r\n\t{\r\n\t\tcout << \"myft(int,T4)偏特化版本\" << endl;\r\n\t\tcout << tmpt << endl;\r\n\t\tcout << tmpt2 << endl;\r\n\t}\r\n\r\n\t//将myfOC实现在类外面\r\n\ttemplate <typename T1>\r\n\ttemplate <typename U>\r\n\tvoid A<T1>::OtherC<U>::myfOC()\r\n\t{\r\n\t\tcout << \"类模板A的myfOC执行了\" << endl;\r\n\t}\r\n\r\n\t//在类外实现类模板A的myft成员函数模板的全特化版本\r\n\t//template <typename T1>\r\n\t//template <> //全特化\r\n\t//void A<T1>::myft(int tmpt, float tmpt2)\r\n\t//{\r\n\t//\tcout << \"myft(int,float)全特化版本\" << endl;\r\n\t//\tcout << tmpt << endl;\r\n\t//\tcout << tmpt2 << endl;\r\n\t//}\r\n\r\n\t//类模板A的全特化版本\r\n\ttemplate <>\r\n\tclass A<float>\r\n\t{\r\n\tpublic:\r\n\t\ttemplate <typename T3, typename T4> //普通成员函数模板\r\n\t\tvoid myft(T3 tmpt, T4 tmpt2)\r\n\t\t{\r\n\t\t\tcout << \"类A特化版本的myft()泛化版本\" << endl;\r\n\t\t\tcout << tmpt << endl;\r\n\t\t\tcout << tmpt2 << endl;\r\n\t\t}\r\n\t\t//template <> //全特化\r\n\t\t//void myft(int tmpt, float tmpt2);\r\n\r\n\tpublic:\r\n\t\ttemplate <typename U>\r\n\t\tclass OtherC\r\n\t\t{\r\n\t\tpublic:\r\n\t\t\tvoid myfOC();\r\n\t\t\t/*{\r\n\t\t\t\tcout << \"myfOC执行了\" << endl;\r\n\t\t\t}*/\r\n\t\t};\r\n\t};\r\n\r\n\r\n\t//A<float>中有泛化版本的myft，因此不用在A<float>中声明如下的全特化版本。\r\n\ttemplate <> //全特化\r\n\tvoid A<float>::myft(int tmpt, float tmpt2)\r\n\t{\r\n\t\tcout << \"类A特化版本的myft(int,float)全特化版本\" << endl;\r\n\t\tcout << tmpt << endl;\r\n\t\tcout << tmpt2 << endl;\r\n\t}\r\n\r\n\r\n\t//将myfOC实现在类外面\r\n\ttemplate <typename U>\r\n\tvoid A<float>::OtherC<U>::myfOC()\r\n\t{\r\n\t\tcout << \"myfOC执行了\" << endl;\r\n\t}\r\n\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\t/*_nmsp1::A<float> a2(1, 2);\r\n\ta2.myft(3.1, 2);\r\n\ta2.myft(3, 2);\r\n\ta2.myft(3, 2.5f);*/\r\n\r\n\t/*_nmsp1::A<float> a3;\r\n\ta3.myft(3, 2.5f);\r\n\ta3.myft(3.1,2);*/\r\n\r\n\t/*_nmsp1::A<float>::OtherC<float> myobjc;\r\n\tmyobjc.myfOC(); */\r\n\r\n\t_nmsp1::A<int>::OtherC<float> myobjc;\r\n\tmyobjc.myfOC();\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "6552ccbdfd2c3b8401fdd4db742333af4085f3be", "size": 4068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/208.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/208.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/208.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 18.3243243243, "max_line_length": 65, "alphanum_fraction": 0.5440019666, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1710612001304791, "lm_q2_score": 0.1311732203653401, "lm_q1q2_score": 0.02243864850067488}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_ROUSS_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_ROUSS_HPP\r\n\r\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\r\n// This file is automatically generated. DO NOT EDIT.\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 4.9.1\r\n\r\n// Original copyright notice:\r\n\r\n// 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#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/proj_mdist.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct rouss {};\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 rouss\r\n    {\r\n            template <typename T>\r\n            struct par_rouss\r\n            {\r\n                T s0;\r\n                T A1, A2, A3, A4, A5, A6;\r\n                T B1, B2, B3, B4, B5, B6, B7, B8;\r\n                T C1, C2, C3, C4, C5, C6, C7, C8;\r\n                T D1, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11;\r\n                MDIST<T> en;\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_rouss_ellipsoid : public base_t_fi<base_rouss_ellipsoid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>\r\n            {\r\n\r\n                typedef CalculationType geographic_type;\r\n                typedef CalculationType cartesian_type;\r\n\r\n                par_rouss<CalculationType> m_proj_parm;\r\n\r\n                inline base_rouss_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_rouss_ellipsoid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(e_forward)  ellipsoid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    CalculationType s, al, cp, sp, al2, s2;\r\n\r\n                    cp = cos(lp_lat);\r\n                    sp = sin(lp_lat);\r\n                    s = proj_mdist(lp_lat, sp, cp,  this->m_proj_parm.en) - this->m_proj_parm.s0;\r\n                    s2 = s * s;\r\n                    al = lp_lon * cp / sqrt(1. - this->m_par.es * sp * sp);\r\n                    al2 = al * al;\r\n                    xy_x = this->m_par.k0 * al*(1.+s2*(this->m_proj_parm.A1+s2*this->m_proj_parm.A4)-al2*(this->m_proj_parm.A2+s*this->m_proj_parm.A3+s2*this->m_proj_parm.A5\r\n                                +al2*this->m_proj_parm.A6));\r\n                    xy_y = this->m_par.k0 * (al2*(this->m_proj_parm.B1+al2*this->m_proj_parm.B4)+\r\n                        s*(1.+al2*(this->m_proj_parm.B3-al2*this->m_proj_parm.B6)+s2*(this->m_proj_parm.B2+s2*this->m_proj_parm.B8)+\r\n                        s*al2*(this->m_proj_parm.B5+s*this->m_proj_parm.B7)));\r\n                }\r\n\r\n                // INVERSE(e_inverse)  ellipsoid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    CalculationType s, al, x = xy_x / this->m_par.k0, y = xy_y / this->m_par.k0, x2, y2;;\r\n\r\n                    x2 = x * x;\r\n                    y2 = y * y;\r\n                    al = x*(1.-this->m_proj_parm.C1*y2+x2*(this->m_proj_parm.C2+this->m_proj_parm.C3*y-this->m_proj_parm.C4*x2+this->m_proj_parm.C5*y2-this->m_proj_parm.C7*x2*y)\r\n                        +y2*(this->m_proj_parm.C6*y2-this->m_proj_parm.C8*x2*y));\r\n                    s = this->m_proj_parm.s0 + y*(1.+y2*(-this->m_proj_parm.D2+this->m_proj_parm.D8*y2))+\r\n                        x2*(-this->m_proj_parm.D1+y*(-this->m_proj_parm.D3+y*(-this->m_proj_parm.D5+y*(-this->m_proj_parm.D7+y*this->m_proj_parm.D11)))+\r\n                        x2*(this->m_proj_parm.D4+y*(this->m_proj_parm.D6+y*this->m_proj_parm.D10)-x2*this->m_proj_parm.D9));\r\n                    lp_lat=proj_inv_mdist(s, this->m_proj_parm.en);\r\n                    s = sin(lp_lat);\r\n                    lp_lon=al * sqrt(1. - this->m_par.es * s * s)/cos(lp_lat);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"rouss_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Roussilhe Stereographic\r\n            template <typename Parameters, typename T>\r\n            inline void setup_rouss(Parameters& par, par_rouss<T>& proj_parm)\r\n            {\r\n                T N0, es2, t, t2, R_R0_2, R_R0_4;\r\n\r\n                if (!proj_mdist_ini(par.es, proj_parm.en))\r\n                    BOOST_THROW_EXCEPTION( projection_exception(0) );\r\n                es2 = sin(par.phi0);\r\n                proj_parm.s0 = proj_mdist(par.phi0, es2, cos(par.phi0), proj_parm.en);\r\n                t = 1. - (es2 = par.es * es2 * es2);\r\n                N0 = 1./sqrt(t);\r\n                R_R0_2 = t * t / par.one_es;\r\n                R_R0_4 = R_R0_2 * R_R0_2;\r\n                t = tan(par.phi0);\r\n                t2 = t * t;\r\n                proj_parm.C1 = proj_parm.A1 = R_R0_2 / 4.;\r\n                proj_parm.C2 = proj_parm.A2 = R_R0_2 * (2 * t2 - 1. - 2. * es2) / 12.;\r\n                proj_parm.A3 = R_R0_2 * t * (1. + 4. * t2)/ ( 12. * N0);\r\n                proj_parm.A4 = R_R0_4 / 24.;\r\n                proj_parm.A5 = R_R0_4 * ( -1. + t2 * (11. + 12. * t2))/24.;\r\n                proj_parm.A6 = R_R0_4 * ( -2. + t2 * (11. - 2. * t2))/240.;\r\n                proj_parm.B1 = t / (2. * N0);\r\n                proj_parm.B2 = R_R0_2 / 12.;\r\n                proj_parm.B3 = R_R0_2 * (1. + 2. * t2 - 2. * es2)/4.;\r\n                proj_parm.B4 = R_R0_2 * t * (2. - t2)/(24. * N0);\r\n                proj_parm.B5 = R_R0_2 * t * (5. + 4.* t2)/(8. * N0);\r\n                proj_parm.B6 = R_R0_4 * (-2. + t2 * (-5. + 6. * t2))/48.;\r\n                proj_parm.B7 = R_R0_4 * (5. + t2 * (19. + 12. * t2))/24.;\r\n                proj_parm.B8 = R_R0_4 / 120.;\r\n                proj_parm.C3 = R_R0_2 * t * (1. + t2)/(3. * N0);\r\n                proj_parm.C4 = R_R0_4 * (-3. + t2 * (34. + 22. * t2))/240.;\r\n                proj_parm.C5 = R_R0_4 * (4. + t2 * (13. + 12. * t2))/24.;\r\n                proj_parm.C6 = R_R0_4 / 16.;\r\n                proj_parm.C7 = R_R0_4 * t * (11. + t2 * (33. + t2 * 16.))/(48. * N0);\r\n                proj_parm.C8 = R_R0_4 * t * (1. + t2 * 4.)/(36. * N0);\r\n                proj_parm.D1 = t / (2. * N0);\r\n                proj_parm.D2 = R_R0_2 / 12.;\r\n                proj_parm.D3 = R_R0_2 * (2 * t2 + 1. - 2. * es2) / 4.;\r\n                proj_parm.D4 = R_R0_2 * t * (1. + t2)/(8. * N0);\r\n                proj_parm.D5 = R_R0_2 * t * (1. + t2 * 2.)/(4. * N0);\r\n                proj_parm.D6 = R_R0_4 * (1. + t2 * (6. + t2 * 6.))/16.;\r\n                proj_parm.D7 = R_R0_4 * t2 * (3. + t2 * 4.)/8.;\r\n                proj_parm.D8 = R_R0_4 / 80.;\r\n                proj_parm.D9 = R_R0_4 * t * (-21. + t2 * (178. - t2 * 26.))/720.;\r\n                proj_parm.D10 = R_R0_4 * t * (29. + t2 * (86. + t2 * 48.))/(96. * N0);\r\n                proj_parm.D11 = R_R0_4 * t * (37. + t2 * 44.)/(96. * N0);\r\n            }\r\n\r\n    }} // namespace detail::rouss\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Roussilhe Stereographic 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         - Ellipsoid\r\n        \\par Example\r\n        \\image html ex_rouss.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct rouss_ellipsoid : public detail::rouss::base_rouss_ellipsoid<CalculationType, Parameters>\r\n    {\r\n        inline rouss_ellipsoid(const Parameters& par) : detail::rouss::base_rouss_ellipsoid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::rouss::setup_rouss(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::rouss, rouss_ellipsoid, rouss_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        template <typename CalculationType, typename Parameters>\r\n        class rouss_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                    return new base_v_fi<rouss_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void rouss_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"rouss\", new rouss_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_ROUSS_HPP\r\n\r\n", "meta": {"hexsha": "446d277a64e83df7d2259501f99873f8f326ba8e", "size": 11289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/rouss.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/rouss.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/rouss.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": 46.6487603306, "max_line_length": 178, "alphanum_fraction": 0.5608114093, "num_tokens": 3139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.05033063722702185, "lm_q1q2_score": 0.02242378614308448}}
{"text": "#ifndef HEADER_GUARD_29f4d32dfe1b79d9bff92b3f9359cd94\n#define HEADER_GUARD_29f4d32dfe1b79d9bff92b3f9359cd94\n\n#include <openssl/bn.h>\n#include \"./error.hpp\"\n#include <boost/endian/conversion.hpp>\n#include \"jbms/enable_if.hpp\"\n#include \"jbms/is_byte.hpp\"\n#include \"jbms/assign_endian.hpp\"\n#include \"jbms/division.hpp\"\n#include <vector>\n#include <cctype>\n\nnamespace jbms {\nnamespace openssl {\n\nclass bn_ctx {\n  BN_CTX *x_;\npublic:\n  bn_ctx() {\n    x_ = BN_CTX_new();\n    throw_last_error_if(x_ == nullptr);\n  }\n  explicit bn_ctx(BN_CTX *x_)\n    : x_(x_)\n  {}\n\n  ~bn_ctx() {\n    if (x_)\n      BN_CTX_free(x_);\n  }\n\n  bn_ctx(bn_ctx &&other) {\n    x_ = other.x_;\n    other.x_ = nullptr;\n  }\n\n  bn_ctx(bn_ctx const &) = delete;\n  bn_ctx &operator=(bn_ctx const &) = delete;\n  bn_ctx &operator=(bn_ctx &&other) = delete;\n  operator BN_CTX *() { return x_; }\n  BN_CTX *get() { return x_; }\n  void swap(bn_ctx &other) {\n    std::swap(x_, other.x_);\n  }\n};\n\nclass bignum;\ninline bignum &as_bignum(BIGNUM &bn) {\n  return reinterpret_cast<bignum &>(bn);\n}\ninline bignum const &as_bignum(BIGNUM const &bn) {\n  return reinterpret_cast<bignum const &>(bn);\n}\n\n\nstruct bn_ctx_frame {\n  BN_CTX *ctx;\n  bn_ctx_frame(BN_CTX *ctx) : ctx(ctx) {\n    BN_CTX_start(ctx);\n  }\n  bignum &get() {\n    auto *result = BN_CTX_get(ctx);\n    throw_last_error_if(result == nullptr);\n    return as_bignum(*result);\n  }\n\n  ~bn_ctx_frame() {\n    BN_CTX_end(ctx);\n  }\n};\n\nclass bignum {\n  BIGNUM bn_;\npublic:\n  operator BIGNUM *() { return &bn_; }\n  operator BIGNUM const *() const { return &bn_; }\n  BIGNUM *get() { return &bn_; }\n  BIGNUM const *get() const { return &bn_; }\n  BIGNUM *operator->() { return &bn_; }\n  BIGNUM const *operator->() const { return &bn_; }\n\n  bignum() {\n    BN_init(get());\n  }\n  bignum(unsigned long w) : bignum() {\n    *this = w;\n  }\n  ~bignum() {\n    BN_free(get());\n  }\n  bignum(bignum const &other) : bignum() {\n    *this = other;\n  }\n\n  bignum(bignum &&other) : bignum() {\n    swap(other);\n  }\n\n  void swap(bignum &other) {\n    BN_swap(get(), other.get());\n  }\n\n  bignum &operator=(bignum const &other) {\n    BN_copy(get(), other.get());\n    return *this;\n  }\n\n  bignum &operator=(bignum &&other) {\n    swap(other);\n    return *this;\n  }\n\n  void clear() {\n    BN_clear(get());\n  }\n\n  int num_bytes() const { return BN_num_bytes(get()); }\n  int num_bits() const { return BN_num_bits(get()); }\n\n  bool is_negative() const { return BN_is_negative(get()); }\n  void set_negative(int n) { BN_set_negative(get(), n); }\n\n  static bignum const &one() { return as_bignum(*BN_value_one()); }\n  bignum &operator=(unsigned long w) {\n    set_word(w);\n    return *this;\n  }\n  bignum &operator=(long w) {\n    if (w >= 0)\n      set_word((unsigned long)w);\n    else {\n      set_word((unsigned long)-w);\n      set_negative(true);\n    }\n    return *this;\n  }\n\n  void set_word(unsigned long w) {\n    throw_last_error_if(BN_set_word(get(), w) == 0);\n  }\n\n  void set_zero() {\n    throw_last_error_if(BN_zero(get()) == 0);\n  }\n  void set_one() {\n    throw_last_error_if(BN_one(get()) == 0);\n  }\n  void set_bit(int n) {\n    throw_last_error_if(BN_set_bit(get(), n) == 0);\n  }\n\n  // Returns true if number has at least n bits\n  bool clear_bit(int n) {\n    return (BN_clear_bit(get(), n) == 1);\n  }\n\n\n  bool is_bit_set(int n) const {\n    return BN_is_bit_set(get(), n);\n  }\n\n  void set_bit(int n, bool value) {\n    if (value)\n      set_bit(n);\n    else\n      clear_bit(n);\n  }\n\n  // Returns true if the number was longer than n bits\n  bool mask_bits(int n) {\n    return BN_mask_bits(get(), n) == 1;\n  }\n\n  bool is_zero() const {\n    return BN_is_zero(get());\n  }\n\n  bool is_one() const {\n    return BN_is_one(get());\n  }\n\n  bool is_word(unsigned long w) const {\n    return BN_is_word(get(), w);\n  }\n\n  bool is_odd() const {\n    return BN_is_odd(get());\n  }\n\n  void set_from_hex(const char *x) {\n    BIGNUM *ptr = get();\n    throw_last_error_if(BN_hex2bn(&ptr, x) == 0);\n  }\n  void set_from_hex(std::string const &x) {\n    set_from_hex(x.c_str());\n  }\n\n  std::string to_hex() const {\n    char *temp = BN_bn2hex(get());\n    throw_last_error_if(temp == nullptr);\n    std::string result(temp);\n    OPENSSL_free(temp);\n    return result;\n  }\n\n  // Returns lowercase hex representation without leading zeros\n  std::string to_canonical_hex() const {\n    // Remove leading zeros\n    std::string temp = to_hex();\n    size_t i = 0;\n    for (; i + 1 < temp.size(); ++i) {\n      if (temp[i] != '0')\n        break;\n    }\n    // Make lowercase for consistency\n    for (auto &x : temp)\n      x = std::tolower(x);\n    return temp.substr(i);\n  }\n\n  std::string to_dec() const {\n    char *temp = BN_bn2dec(get());\n    throw_last_error_if(temp == nullptr);\n    std::string result(temp);\n    OPENSSL_free(temp);\n    return result;\n  }\n\n  void set_from_dec(const char *x) {\n    BIGNUM *ptr = get();\n    throw_last_error_if(BN_dec2bn(&ptr, x) == 0);\n  }\n  void set_from_dec(std::string const &x) {\n    set_from_dec(x.c_str());\n  }\n\n  bignum &operator+=(unsigned long w) {\n    throw_last_error_if(BN_add_word(get(), w) == 0);\n    return *this;\n  }\n\n  bignum &operator-=(unsigned long w) {\n    throw_last_error_if(BN_sub_word(get(), w) == 0);\n    return *this;\n  }\n\n  bignum &operator*=(unsigned long w) {\n    throw_last_error_if(BN_mul_word(get(), w) == 0);\n    return *this;\n  }\n};\n\n/**\n * Invokes wrapper.data on a uint8_t array of length num_bytes\n *\n * x is set to be the contents of that buffer, interpreted as order endianness\n **/\ntemplate <class Func, boost::endian::order order,\n          JBMS_ENABLE_IF_EXPR(std::declval<Func>()(std::declval<uint8_t *>()))>\ninline void fill(bignum &x, size_t num_bytes, endian_wrapper<Func,order> wrapper) {\n  x.set_zero();\n  size_t num_words = jbms::div_ceil(num_bytes, sizeof(BN_ULONG));\n\n  // ensure there is enough space\n  bn_wexpand(x.get(), num_words);\n  x.get()->top = num_words;\n\n  // set final word to 0 since it might not be completely overwritten by the function\n  if (num_words > 0)\n    x.get()->d[num_words-1] = 0;\n\n  // call function\n  auto buf = (uint8_t *)x.get()->d;\n  wrapper.data(buf);\n\n  // reverse bytes if big endian\n  if (order == boost::endian::order::big)\n    std::reverse(buf, buf + num_bytes);\n\n  // convert endian (no-op if order == little endian)\n  for (size_t i = 0; i < num_words; ++i) {\n    boost::endian::little_to_native_inplace(x.get()->d[i]);\n  }\n\n  bn_fix_top(x.get());\n}\n\n\n/**\n *  Interoperability with assign_endian functionality.\n **/\n\n// result must have size == x.num_bytes\ntemplate <class Dest, JBMS_ENABLE_IF(is_byte_range<Dest>)>\ninline void assign(endian_wrapper<Dest,boost::endian::order::big> wrapper,\n                   bignum const &x) {\n  wrapper.ensure_size_equals(x.num_bytes());\n\n  // always writes exactly x.num_bytes(), doesn't produce errors\n  BN_bn2bin(x.get(), wrapper.data.data());\n}\n\n// result must have size == x.num_bytes\ntemplate <class Dest, JBMS_ENABLE_IF(is_byte_range<Dest>)>\ninline void assign(endian_wrapper<Dest,boost::endian::order::little> wrapper,\n                   bignum const &x) {\n  wrapper.ensure_size_equals(x.num_bytes());\n\n  // always writes exactly x.num_bytes(), doesn't produce errors\n  BN_bn2bin(x.get(), wrapper.data.data());\n\n  // OpenSSL doesn't provide access to little endian representation directly, so we just reverse big endian output\n  std::reverse(wrapper.data.begin(), wrapper.data.end());\n}\n\ntemplate <class Source, boost::endian::order order, JBMS_ENABLE_IF(is_byte_range<Source>)>\nvoid assign(bignum &x, endian_wrapper<Source, order> source) {\n  fill(x,\n       source.data.size(),\n       jbms::make_endian_wrapper<order>([&](uint8_t *buf) { memcpy(buf, source.data.data(), source.data.size()); }));\n}\n\n// r = a + b\n// r may alias a or b\ninline void add(bignum &r, const bignum &a, const bignum &b) {\n  throw_last_error_if(BN_add(r.get(), a.get(), b.get()) == 0);\n}\n\n// r = a - b\n// r may alias a or b\ninline void sub(bignum &r, const bignum &a, const bignum &b) {\n  throw_last_error_if(BN_sub(r.get(), a.get(), b.get()) == 0);\n}\n\n// r = a * b\n// r may alias a or b\ninline void mul(bignum &r, const bignum &a, const bignum &b, BN_CTX *ctx) {\n  throw_last_error_if(BN_mul(r.get(), a.get(), b.get(), ctx) == 0);\n}\n\n\n// r = a * b\n// r may alias a\ninline void sqr(bignum &r, const bignum &a, BN_CTX *ctx) {\n  throw_last_error_if(BN_sqr(r.get(), a.get(), ctx) == 0);\n}\n\n// either of dv or rem can be nullptr\ninline void div(BIGNUM *dv, BIGNUM *rem, const bignum &a, const bignum &d, BN_CTX *ctx) {\n  throw_last_error_if(BN_div(dv, rem, a.get(), d.get(), ctx) == 0);\n}\n\ninline void mod(bignum &rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod(rem.get(), a, m, ctx) == 0);\n}\n\ninline void nnmod(bignum &r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {\n  throw_last_error_if(BN_nnmod(r.get(), a, m, ctx) == 0);\n}\n\ninline void mod_add(bignum &r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_add(r.get(), a, b, m, ctx) == 0);\n}\n\ninline void mod_sub(bignum &r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_sub(r.get(), a, b, m, ctx) == 0);\n}\n\ninline void mod_mul(bignum &r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_mul(r.get(), a, b, m, ctx) == 0);\n}\n\ninline void mod_sqr(bignum &r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_sqr(r.get(), a, m, ctx) == 0);\n}\n\ninline void exp(bignum &r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_exp(r.get(), a, p, ctx) == 0);\n}\n\ninline void mod_exp(bignum &r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_exp(r.get(), a, p, m, ctx) == 0);\n}\n\n/* r may alias a */\ninline void mod_inverse(bignum &r, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_inverse(r.get(), a, n, ctx) == 0);\n}\n\ninline void gcd(bignum &r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) {\n  throw_last_error_if(BN_gcd(r.get(), a, b, ctx) == 0);\n}\n\ninline int compare(bignum const &a, bignum const &b) {\n  return BN_cmp(a, b);\n}\n\ninline int abs_compare(bignum const &a, bignum const &b) {\n  return BN_ucmp(a, b);\n}\n\n#define OPENSSL_PP_BIGNUM_COMPARE(op)                                               \\\n  inline bool operator op(bignum const &a, bignum const &b) { return compare(a, b) op 0; } \\\n/**/\n\nOPENSSL_PP_BIGNUM_COMPARE(==)\nOPENSSL_PP_BIGNUM_COMPARE(!=)\nOPENSSL_PP_BIGNUM_COMPARE(<)\nOPENSSL_PP_BIGNUM_COMPARE(<=)\nOPENSSL_PP_BIGNUM_COMPARE(>)\nOPENSSL_PP_BIGNUM_COMPARE(>=)\n\n#undef OPENSSL_PP_BIGNUM_COMPARE\n\ninline bool operator==(bignum const &a, unsigned long w) { return a.is_word(w); }\ninline bool operator==(unsigned long w, bignum const &a) { return a.is_word(w); }\ninline bool operator!=(bignum const &a, unsigned long w) { return !(a == w); }\ninline bool operator!=(unsigned long w, bignum const &a) { return !(a == w); }\n\n// We want to be able to use bignum interchangeable with BIGNUM\nstatic_assert(sizeof(bignum) == sizeof(BIGNUM), \"\");\n\nclass bn_recp_ctx {\n  BN_RECP_CTX x_;\npublic:\n  bn_recp_ctx() {\n    BN_RECP_CTX_init(&x_);\n  }\n  ~bn_recp_ctx() {\n    BN_RECP_CTX_free(&x_);\n  }\n\n  bn_recp_ctx(bn_recp_ctx const &other) : bn_recp_ctx() {\n    *this = other;\n  }\n  bn_recp_ctx(bn_recp_ctx &&other) : bn_recp_ctx() {\n    swap(other);\n  }\n\n  bn_recp_ctx(const BIGNUM *m, BN_CTX *ctx) : bn_recp_ctx() {\n    set(m, ctx);\n  }\n\n  bn_recp_ctx &operator=(bn_recp_ctx const &other) {\n    x_.num_bits = other->num_bits;\n    x_.shift = other->shift;\n    x_.flags = other->flags;\n    divisor() = other.divisor();\n    reciprocal() = other.reciprocal();\n    return *this;\n  }\n\n  void swap(bn_recp_ctx &other) {\n    std::swap(x_.num_bits, other->num_bits);\n    std::swap(x_.shift, other->shift);\n    std::swap(x_.flags, other->flags);\n    divisor().swap(other.divisor());\n    reciprocal().swap(other.reciprocal());\n  }\n\n  bn_recp_ctx &operator=(bn_recp_ctx &&other) {\n    swap(other);\n    return *this;\n  }\n\n  void set(const BIGNUM *m, BN_CTX *ctx) {\n    throw_last_error_if(BN_RECP_CTX_set(get(), m, ctx) == 0);\n  }\n\n  operator BN_RECP_CTX *() { return &x_; }\n  BN_RECP_CTX *get() { return &x_; }\n\n  BN_RECP_CTX *operator->() { return &x_; }\n  BN_RECP_CTX const *operator->() const { return &x_; }\n\n  bignum &divisor() { return as_bignum(x_.N); }\n  bignum const &divisor() const { return as_bignum(x_.N); }\n\n  bignum &reciprocal() { return as_bignum(x_.Nr); }\n  bignum const &reciprocal() const { return as_bignum(x_.Nr); }\n};\nstatic_assert(sizeof(bn_recp_ctx) == sizeof(BN_RECP_CTX),\"\");\n\ninline void div_recp(BIGNUM *dv, BIGNUM *rem, bignum const &a, BN_RECP_CTX *recp, BN_CTX *ctx) {\n  throw_last_error_if(BN_div_recp(dv, rem, a.get(), recp, ctx) == 0);\n}\n\ninline void mod_mul_reciprocal(bignum &r, BIGNUM const *a, BIGNUM const *b, BN_RECP_CTX *recp, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_mul_reciprocal(r.get(), a, b, recp, ctx) == 0);\n}\n\nclass bn_mont_ctx {\n  BN_MONT_CTX ctx_;\npublic:\n  BN_MONT_CTX *get() { return &ctx_; }\n  BN_MONT_CTX const *get() const { return &ctx_; }\n  operator BN_MONT_CTX * () { return &ctx_; }\n  operator BN_MONT_CTX const * () const { return &ctx_; }\n  BN_MONT_CTX *operator->() { return &ctx_; }\n  BN_MONT_CTX const *operator->() const { return &ctx_; }\n\n  bn_mont_ctx() {\n    BN_MONT_CTX_init(get());\n  }\n  ~bn_mont_ctx() {\n    BN_MONT_CTX_free(get());\n  }\n  bignum const &RR() const { return as_bignum(ctx_.RR); }\n  bignum &RR() { return as_bignum(ctx_.RR); }\n\n  // The modulus\n  bignum const &N() const { return as_bignum(ctx_.N); }\n  bignum &N() { return as_bignum(ctx_.N); }\n\n  bignum const &Ni() const { return as_bignum(ctx_.Ni); }\n  bignum &Ni() { return as_bignum(ctx_.Ni); }\n\n  bn_mont_ctx(bn_mont_ctx const &other) : bn_mont_ctx() {\n    *this = other;\n  }\n\n  bn_mont_ctx(bn_mont_ctx &&other) : bn_mont_ctx() {\n    swap(other);\n  }\n\n  bn_mont_ctx(BIGNUM const *m, BN_CTX *ctx) {\n    set(m, ctx);\n  }\n\n  bn_mont_ctx &operator=(bn_mont_ctx const &other) {\n    throw_last_error_if(BN_MONT_CTX_copy(get(), const_cast<BN_MONT_CTX *>(other.get())) == nullptr);\n    return *this;\n  }\n\n  void swap(bn_mont_ctx &other) {\n    std::swap(ctx_.ri, other->ri);\n    RR().swap(other.RR());\n    N().swap(other.N());\n    Ni().swap(other.Ni());\n    std::swap(ctx_.n0, other->n0);\n    std::swap(ctx_.flags, other->flags);\n  }\n  bn_mont_ctx &operator=(bn_mont_ctx &&other) {\n    swap(other);\n    return *this;\n  }\n\n  void set(const BIGNUM *m, BN_CTX *ctx) {\n    throw_last_error_if(BN_MONT_CTX_set(get(), m, ctx) == 0);\n  }\n\n};\nstatic_assert(sizeof(bn_mont_ctx) == sizeof(BN_MONT_CTX), \"\");\n\ninline void from_montgomery(bignum &r, BIGNUM const *a, BN_MONT_CTX const *mont, BN_CTX *ctx) {\n  throw_last_error_if(BN_from_montgomery(r.get(), a, const_cast<BN_MONT_CTX *>(mont), ctx) == 0);\n}\n\ninline void to_montgomery(bignum &r, BIGNUM const *a, BN_MONT_CTX const *mont, BN_CTX *ctx) {\n  throw_last_error_if(BN_to_montgomery(r.get(), a, const_cast<BN_MONT_CTX *>(mont), ctx) == 0);\n}\n\n// r may alias a\n// a may alias b\ninline void mod_mul_montgomery(bignum &r, BIGNUM const *a, BIGNUM const *b, BN_MONT_CTX const *mont, BN_CTX *ctx) {\n  throw_last_error_if(BN_mod_mul_montgomery(r.get(), a, b, const_cast<BN_MONT_CTX *>(mont), ctx) == 0);\n}\n\n\n#ifndef OPENSSL_NO_EC2M\n\n// For all of the variants that accept a const int p[] argument, the modulus p is specified as a (-1)-terminated, decreasing list of 1 coefficients.\n// The array variants are more efficient because the non-array variants are mapped by OpenSSL to the array variants.\n\n// r, a, b are GF(2^m) field elements\n// r = a + b\n// r may alias a or b\ninline void GF2m_add(bignum &r, BIGNUM const *a, BIGNUM const *b) {\n  throw_last_error_if(BN_GF2m_add(r.get(), a, b) == 0);\n}\n\n// r, a, p are GF(2^m) field elements\n// r = a mod p\n// r may alias a.\ninline void GF2m_mod(bignum &r, BIGNUM const *a, BIGNUM const *p) {\n  throw_last_error_if(BN_GF2m_mod(r.get(), a, p) == 0);\n}\ninline void GF2m_mod(bignum &r, BIGNUM const *a, const int p[]) {\n  throw_last_error_if(BN_GF2m_mod_arr(r.get(), a, p) == 0);\n}\n\n\n// r, a, b, p are GF(2^m) field elements\n// r = (a * b) mod p\n// r may alias a or b\n// a may alias b\ninline void GF2m_mod_mul(bignum &r, BIGNUM const *a, BIGNUM const *b, BIGNUM const *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_mul(r.get(), a, b, p, ctx) == 0);\n}\ninline void GF2m_mod_mul(bignum &r, BIGNUM const *a, BIGNUM const *b, const int p[], BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_mul_arr(r.get(), a, b, p, ctx) == 0);\n}\n\n// r, a, p are GF(2^m) field elements\n// r = (a * a) mod p\n// r may alias a\ninline void GF2m_mod_sqr(bignum &r, BIGNUM const *a, BIGNUM const *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_sqr(r.get(), a, p, ctx) == 0);\n}\ninline void GF2m_mod_sqr(bignum &r, BIGNUM const *a, const int p[], BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_sqr_arr(r.get(), a, p, ctx) == 0);\n}\n\n// r, a, p are GF(2^m) field elements\n// r = a^{-1} mod p\n// r may alias a\ninline void GF2m_mod_inv(bignum &r, BIGNUM const *a, BIGNUM const *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_inv(r.get(), a, p, ctx) == 0);\n}\ninline void GF2m_mod_inv(bignum &r, BIGNUM const *a, const int p[], BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_inv_arr(r.get(), a, p, ctx) == 0);\n}\n\n// r, a, b, p are GF(2^m) field elements\n// r = (a / b) mod p\n// r may alias a or b\n// a may alias b\ninline void GF2m_mod_div(bignum &r, BIGNUM const *a, BIGNUM const *b, BIGNUM const *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_div(r.get(), a, b, p, ctx) == 0);\n}\ninline void GF2m_mod_div(bignum &r, BIGNUM const *a, BIGNUM const *b, const int p[], BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_div_arr(r.get(), a, b, p, ctx) == 0);\n}\n\n// r, a are GF(2^m) field elements\n// Computes r such that r^2 = a\n// r may alias a\ninline void GF2m_mod_sqrt(bignum &r, BIGNUM const *a, BIGNUM const *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_sqrt(r.get(), a, p, ctx) == 0);\n}\ninline void GF2m_mod_sqrt(bignum &r, BIGNUM const *a, const int p[], BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_sqrt_arr(r.get(), a, p, ctx) == 0);\n}\n\n// r, a are GF(2^m) field elements\n// b is an integer\n// r = a^b mod p\n// r may alias a\ninline void GF2m_mod_exp(bignum &r, BIGNUM const *a, BIGNUM const *b, BIGNUM const *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_exp(r.get(), a, b, p, ctx) == 0);\n}\ninline void GF2m_mod_exp(bignum &r, BIGNUM const *a, BIGNUM const *b, const int p[], BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_exp_arr(r.get(), a, b, p, ctx) == 0);\n}\n\n\n// r, a, p are GF(2^m) field elements\n// r^2 + r = a mod p\n// r may alias a\n// Returns 0 if no such r exists.\ninline void GF2m_mod_solve_quad(bignum &r, BIGNUM const *a, BIGNUM const *p, BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_solve_quad(r.get(), a, p, ctx) == 0);\n}\ninline void GF2m_mod_solve_quad(bignum &r, BIGNUM const *a, const int p[], BN_CTX *ctx) {\n  throw_last_error_if(BN_GF2m_mod_solve_quad_arr(r.get(), a, p, ctx) == 0);\n}\n\n// p is a (-1)-terminated array of coefficients\ninline void GF2m_arr2poly(const int p[], bignum &a) {\n  throw_last_error_if(BN_GF2m_arr2poly(p, a.get()) == 0);\n}\n\n// Sets p to be a (-1)-terminated array of 1 coefficients\n// Only up to max values in p are set (the -1 will only be appended if there is sufficient space)\n// Returns the size of p that would be required to avoid truncation.\ninline int GF2m_poly2arr(bignum const &a, int p[], int max) {\n  return BN_GF2m_poly2arr(a.get(), p, max);\n}\n\ninline std::vector<int> GF2m_poly2arr(bignum const &a) {\n  std::vector<int> result;\n  int max = GF2m_poly2arr(a, result.data(), 0);\n  result.resize(max);\n  GF2m_poly2arr(a, result.data(), max);\n  return result;\n}\n\n#endif // end if !defined(OPENSSL_NO_EC2M)\n\n\n/**\n * If top equals:\n *  -1 :  top bit is random (i.e. can be 0)\n *   0 :  top bit will be 1\n *   1 :  top two bits will be 1\n *\n * If bottom equals:\n *   1  : number is odd (bottom bit is 1)\n *   0  : bottom bit is random (i.e. can be 0)\n **/\ninline void rand(bignum &r, int bits, int top, int bottom) {\n  throw_last_error_if(BN_rand(r.get(), bits, top, bottom) == 0);\n}\n\n// Same as rand, but not cryptographically secure\ninline void pseudo_rand(bignum &r, int bits, int top, int bottom) {\n  throw_last_error_if(BN_pseudo_rand(r.get(), bits, top, bottom) == 0);\n}\n\n// Post-condition: 0 <= r < range\ninline void rand_range(bignum &r, bignum const &range) {\n  throw_last_error_if(BN_rand_range(r.get(), range.get()) == 0);\n}\n// Same as rand_range, but not cryptographically secure\ninline void pseudo_rand_range(bignum &r, bignum const &range) {\n  throw_last_error_if(BN_pseudo_rand_range(r.get(), range.get()) == 0);\n}\n\n\n}\n}\n\n#endif /* HEADER GUARD */\n", "meta": {"hexsha": "b3187ad9cb3cfbfe94006848b97cc4fcebdc4e80", "size": 20759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/jbms/openssl/bn.hpp", "max_stars_repo_name": "ezhu5121/jbms-openssl", "max_stars_repo_head_hexsha": "25c1f232e74a1ee717eefaf12584b660a8e67e32", "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/jbms/openssl/bn.hpp", "max_issues_repo_name": "ezhu5121/jbms-openssl", "max_issues_repo_head_hexsha": "25c1f232e74a1ee717eefaf12584b660a8e67e32", "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/jbms/openssl/bn.hpp", "max_forks_repo_name": "ezhu5121/jbms-openssl", "max_forks_repo_head_hexsha": "25c1f232e74a1ee717eefaf12584b660a8e67e32", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T23:26:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T23:26:37.000Z", "avg_line_length": 28.6331034483, "max_line_length": 148, "alphanum_fraction": 0.6541740932, "num_tokens": 6662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.05500528480794332, "lm_q1q2_score": 0.022405488889825104}}
{"text": "/// \\file   slam.cpp\n/// \\brief  Implementation of the extended Kalman Filter SLAM\n///\n/// PARAMETERS:\n///     frequency (int): control loop frequency\n///     reset_flag (bool): specifies when new pose is read\n///     wheel_base (float): The distance between the wheels\n///     wheel_radius (float): The radius of the wheels\n///     odom_frame_id (std::string): The name of the odometry tf frame\n///     body_frame_id (std::string): The name of the body tf frame\n///     left_wheel_joint (std::string): The name of the left wheel joint\n///     right_wheel_joint (std::string): The name of the right wheel joint\n///\n///     joint_msg (sensor_msgs::JointState): message to publish wheel angle\n///         readings to /joint_states topic\n///     static_world_broadcaster (StaticTransformBroadcaster): Broadcast the\n///         static transform between world_frame_id and the map_frame_id on /tf\n///         using a tf2\n///     odom_broadcaster (TransformBroadcaster): Broadcast the transform between\n///         map_frame_id and the odom_frame_id on /tf using a tf2\n///     map_broadcaster (TransformBroadcaster): Broadcast the transform between\n///         odom_frame_id and the body_frame_id on /tf using a tf2\n///     static_world_tf(geometry_msgs::TransformStamped): static world transform\n///     map_tf(geometry_msgs::TransformStamped): map transform\n///     odom_tf(geometry_msgs::TransformStamped): odometry transform\n///     odom(nav_msgs::Odometry): odometry message\n///     slam (nav_msgs::Odometry): slam message\n///     slam_marker_array (visualization_msgs::MarkerArray): an array of\n///         obstacles publishing to the slam simulator.\n///\n///     odom_pose (rigid2d::Config2D): the robot's position (based on the wheel\n///         angles)\n///     reset_pose (rigid2d::Config2D): the robot's reset position\n///     twist(rigid2d::Twist2D): the robot's twist\n///     twist_del (rigid2d::Twist2D): the delta between the robot's new twist\n///         to the robot's last twist\n///     diff_drive (rigid2d::DiffDrive): an instance of the diff_drive robot\n///     wheel_vel (rigid2d::WheelVelocity): the velocity of the robot's wheels\n///     wheel_angle (rigid2d::WheelAngle): the angle of the robot's wheels\n///\n///     measurements (std::vector<nuslam::Measurement>): a vector with\n///     components of type nuslam::Measurement. m_t (arma::mat): the map matrix,\n///     as measured in the slam simulator. q_t(arma::mat): the state matrix, as\n///     measured in the slam simulator.\n///\n/// PUBLISHES:\n///     odom (nav_msgs/Odometry): publishes Odometry message on the odom topic.\n///     landmarks_pub (visualization_msgs/MarkerArray): publishes real\n///     landmarks. slam_landmarks_pub (visualization_msgs/MarkerArray):\n///     publishes landmark\n///         to be subscribed by the slam simulation.\n///\n/// SUBSCRIBES:\n///     landmarks_sub (visualization_msgs/Marker): Subscribes to the MarkerArray\n///         that's publish by the simulation.\n///\n/// SERVICES:\n///     SetPose (set_pose): Restarts the location of the odometry, so that the\n///         robot thinksit is at the requested configuration.\n\n#include \"nuslam/nuslam.hpp\"\n#include \"rigid2d/diff_drive.hpp\"\n#include \"rigid2d/rigid2d.hpp\"\n\n#include \"ros/ros.h\"\n\n#include <geometry_msgs/Quaternion.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/JointState.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <tf2_ros/transform_broadcaster.h>\n#include <visualization_msgs/MarkerArray.h>\n\n#include <rigid2d/SetPose.h>\n\n#include <armadillo>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <utility>\n#include <vector>\n\n/// \\brief Class KFSlam\nclass KFSlam\n{\npublic:\n  KFSlam()\n  {\n    ROS_INFO(\"Initialize the variables\");\n    // Init Parameters\n    load_parameter();\n\n    // Init publishers, subscribers, and services\n    odom_pub = nh.advertise<nav_msgs::Odometry>(\"/odom\", 1);\n    slam_landmarks_pub =\n        nh.advertise<visualization_msgs::MarkerArray>(\"/slam_landmarks\", 1);\n\n    joint_states_sub =\n        nh.subscribe(\"/joint_states\", 1, &KFSlam::joint_state_callback, this);\n    landmarks_sub =\n        nh.subscribe(\"/fake_sensor\", 1, &KFSlam::landmarks_callback, this);\n\n    set_pose_srv =\n        nh.advertiseService(\"/set_pose\", &KFSlam::set_pose_callback, this);\n  }\n\n  /// \\brief Load the parameters from the parameter server\n  /// \\returns void\n  void load_parameter()\n  {\n    nh.getParam(\"wheel_base\", wheel_base);     // The distance between the wheels\n    nh.getParam(\"wheel_radius\", wheel_radius); // The radius of the wheels\n    nh.getParam(\"world_frame_id\",\n                world_frame_id);               // The name of the world tf frame\n    nh.getParam(\"map_frame_id\", map_frame_id); // The name of the map tf frame\n    nh.getParam(\"odom_frame_id\",\n                odom_frame_id); // The name of the odometry tf frame\n    nh.getParam(\"body_frame_id\",\n                body_frame_id); // The name of the body tf frame\n    nh.getParam(\"left_wheel_joint\",\n                left_wheel_joint); // The name of the left wheel joint\n    nh.getParam(\"right_wheel_joint\",\n                right_wheel_joint); // The name of the right wheel joint\n    nh.getParam(\"obstacles_radius\",\n                obstacles_radius); // The radous of the cardboard tubes [m]\n  }\n\n  /// \\brief Subscribes to the robot's joint_states.\n  /// \\param joint_state - constant pointer to joint_states\n  /// \\returns void\n  void\n  joint_state_callback(const sensor_msgs::JointState::ConstPtr &joint_state)\n  {\n    // ROS_INFO(\"Subscribing to joint state\");\n    right_angle = joint_state->position.at(0);\n    left_angle = joint_state->position.at(1);\n\n    joint_state_flag = true;\n  }\n\n  /// \\brief Subscribes to the map's landmarks.\n  /// \\param markers - markers visualization msgs.\n  /// \\returns void\n  void landmarks_callback(const visualization_msgs::MarkerArray &markers)\n  {\n    // ROS_INFO(\"Subscribing to landmarks\");\n    for (auto &marker : markers.markers)\n    {\n      double x = marker.pose.position.x;\n      double y = marker.pose.position.y;\n      int id = marker.id;\n      measurements.push_back(nuslam::Measurement(x, y, id));\n    }\n\n    // Raise the landmarks flag\n    landmarks_flag = true;\n  }\n\n  /// \\brief Restarts the location of the odometry, so that the robot thinks\n  /// it is at the requested configuration.\n  /// \\param req - SetPose request.\n  /// \\param res - SetPose response.\n  /// \\returns bool\n  bool set_pose_callback(rigid2d::SetPose::Request &req,\n                         rigid2d::SetPose::Response &res)\n  {\n    // ROS_INFO(\"Setting pose\");\n    reset_pose.x = req.x;\n    reset_pose.y = req.y;\n    reset_pose.theta = req.theta;\n    res.result = true;\n\n    // Raise the reset flag\n    reset_flag = true;\n\n    return true;\n  }\n\n  /// \\brief Gets markers from map\n  /// \\returns void\n  void get_marker_from_map()\n  {\n    slam_marker_array.markers.resize(m_t.size());\n    for (unsigned int i = 0; i < m_t.n_rows / 2; i++)\n    {\n      slam_marker_array.markers.resize(m_t.n_rows / 2);\n      slam_marker_array.markers[i].header.frame_id = map_frame_id;\n      slam_marker_array.markers[i].header.stamp = ros::Time();\n      slam_marker_array.markers[i].ns = \"marker\";\n      slam_marker_array.markers[i].id = i;\n      slam_marker_array.markers[i].type = visualization_msgs::Marker::CYLINDER;\n      slam_marker_array.markers[i].action = visualization_msgs::Marker::ADD;\n      slam_marker_array.markers[i].pose.position.x = m_t(2 * i, 0);\n      slam_marker_array.markers[i].pose.position.y = m_t(2 * i + 1, 0);\n      slam_marker_array.markers[i].pose.position.z = 0.0;\n      slam_marker_array.markers[i].pose.orientation.x = 0.0;\n      slam_marker_array.markers[i].pose.orientation.y = 0.0;\n      slam_marker_array.markers[i].pose.orientation.z = 0.0;\n      slam_marker_array.markers[i].pose.orientation.w = 1.0;\n      slam_marker_array.markers[i].scale.x = 3 * obstacles_radius;\n      slam_marker_array.markers[i].scale.y = 3 * obstacles_radius;\n      slam_marker_array.markers[i].scale.z = 0.5;\n      slam_marker_array.markers[i].color.a = 1.0;\n      slam_marker_array.markers[i].color.r = 0.0;\n      slam_marker_array.markers[i].color.g = 0.0;\n      slam_marker_array.markers[i].color.b = 1.0;\n\n      slam_landmarks_pub.publish(slam_marker_array);\n    }\n  }\n\n  /// \\brief Broadcast the static \"world\" to \"map\" transform\n  /// \\returns void\n  void world_map_transform()\n  {\n    // Transform from \"world\" to \"map\" frame\n    static_world_tf.header.stamp = ros::Time::now();\n    static_world_tf.header.frame_id = world_frame_id;\n    static_world_tf.child_frame_id = map_frame_id;\n    static_world_tf.transform.translation.x = 0;\n    static_world_tf.transform.translation.y = 0;\n    static_world_tf.transform.translation.z = 0;\n    static_world_tf.transform.rotation.x = 0.0;\n    static_world_tf.transform.rotation.y = 0.0;\n    static_world_tf.transform.rotation.z = 0.0;\n    static_world_tf.transform.rotation.w = 1.0;\n\n    static_world_broadcaster.sendTransform(static_world_tf);\n  }\n\n  /// \\brief Broadcast the \"map\" to \"odom\" transform\n  /// \\returns void\n  void map_odom_transform()\n  {\n    rigid2d::Transform2D T_mo, T_om;\n    rigid2d::Vector2D v_mb, v_ob;\n    // double angle_mb, angle_ob;\n\n    // angle_mb = q_t(0, 0);\n    v_mb.x = q_t(1, 0);\n    v_mb.y = q_t(2, 0);\n\n    rigid2d::Transform2D T_mb(v_mb, 0); // angle_mb\n\n    // angle_ob = odom_pose.theta;\n    v_ob.x = odom_pose.x;\n    v_ob.y = odom_pose.y;\n    rigid2d::Transform2D T_ob(v_ob, 0); // angle_ob\n\n    T_mo = T_mb * T_ob.inv();\n\n    // Transform from \"map\" to \"odom\" frame\n    map_tf.header.stamp = ros::Time::now(); // TODO\n    map_tf.header.frame_id = map_frame_id;\n    map_tf.child_frame_id = odom_frame_id;\n    map_tf.transform.translation.x = 0; // T_mo.x();\n    map_tf.transform.translation.y = 0; // T_mo.y();\n    map_tf.transform.translation.z = 0;\n    quat.setRPY(0, 0, 0); // T_mo.theta()\n    map_quat = tf2::toMsg(quat);\n    map_tf.transform.rotation = map_quat;\n\n    map_broadcaster.sendTransform(map_tf);\n  }\n\n  /// \\brief Broadcast the \"odom\" to \"body\" transform\n  /// \\returns void\n  void odom_body_transform()\n  {\n    // Transform from \"odom\" to \"body\" frame\n    odom_tf.header.stamp = ros::Time::now();\n    odom_tf.header.frame_id = odom_frame_id;\n    odom_tf.child_frame_id = body_frame_id;\n    odom_tf.transform.translation.x = odom_pose.x;\n    odom_tf.transform.translation.y = odom_pose.y;\n    odom_tf.transform.translation.z = 0;\n    quat.setRPY(0, 0, odom_pose.theta);\n    odom_quat = tf2::toMsg(quat);\n    odom_tf.transform.rotation = odom_quat;\n    odom_broadcaster.sendTransform(odom_tf);\n  }\n\n  /// \\brief Broadcast the \"world\" to \"slam\" transform\n  /// \\returns void\n  void world_slam_transform()\n  {\n    // Transform from \"world\" to \"slam\" frame\n    slam_tf.header.stamp = ros::Time::now();\n    slam_tf.header.frame_id = world_frame_id;\n    slam_tf.child_frame_id = \"slam\";\n    slam_tf.transform.translation.x = q_t(1, 0);\n    slam_tf.transform.translation.y = q_t(2, 0);\n    slam_tf.transform.translation.z = 0;\n    quat.setRPY(0, 0, q_t(0, 0));\n    odom_quat = tf2::toMsg(quat);\n    slam_tf.transform.rotation = odom_quat;\n    slam_broadcaster.sendTransform(slam_tf);\n  }\n\n  /// \\brief Publish odometry messages\n  /// \\returns void\n  void publish_odometry()\n  {\n    odom.header.stamp = current_time;\n    odom.header.frame_id = odom_frame_id;\n    odom.child_frame_id = body_frame_id;\n    odom.pose.pose.position.x = odom_pose.x;\n    odom.pose.pose.position.y = odom_pose.y;\n    odom.pose.pose.position.z = 0.0;\n    quat.setRPY(0, 0, odom_pose.theta);\n    odom_quat = tf2::toMsg(quat);\n    odom.pose.pose.orientation = odom_quat;\n    odom.twist.twist.linear.x = twist.xdot;\n    odom.twist.twist.linear.y = twist.ydot;\n    odom.twist.twist.angular.z = twist.thetadot;\n\n    odom_pub.publish(odom);\n  }\n\n  /// \\brief Main loop for the turtle's motion\n  /// \\returns void\n  void main_loop()\n  {\n    // ROS_INFO(\"Entering the loop\");\n    ros::Rate loop_rate(frequency);\n\n    // Initializing Extended Kalman Filter\n    nuslam::EKF Kalman_Filter;\n    diff_drive = rigid2d::DiffDrive();\n    wheel_angle_old = {0, 0};\n\n    while (ros::ok())\n    {\n      current_time = ros::Time::now();\n\n      if (joint_state_flag)\n      {\n        // ROS_INFO(\"wheel_angle = %f, %f\\n\\r\", right_angle, left_angle);\n\n        diff_drive.updateOdometryWithAngles(right_angle, left_angle);\n        odom_pose = diff_drive.get_config();\n        // ROS_INFO(\"odom_pose = %f, %f\\n\\r\", odom_pose.x, odom_pose.y);\n\n        joint_state_flag = false;\n      }\n\n      // If the set_pose_callback was called\n      if (reset_flag)\n      {\n        diff_drive.set_config(reset_pose);\n\n        // Provide the configuration of the robot\n        ROS_INFO(\"Reset robot position:\");\n        ROS_INFO(\"x = %f\\n\\r\", diff_drive.get_config().x);\n        ROS_INFO(\"y = %f\\n\\r\", diff_drive.get_config().y);\n        ROS_INFO(\"theta = %f\\n\\r\", diff_drive.get_config().theta);\n\n        // Remove the set_pose flag\n        reset_flag = false;\n      }\n\n      if (landmarks_flag)\n      {\n        wheel_angle_new = diff_drive.get_wheel_angle();\n        // ROS_INFO(\"wheel_angle_old = %f, %f \\n\\r\",\n        // wheel_angle_old.right_wheel_angle,\n        // wheel_angle_old.right_wheel_angle); ROS_INFO(\"wheel_angle_new = %f,\n        // %f \\n\\r\", wheel_angle_new.right_wheel_angle,\n        // wheel_angle_new.right_wheel_angle);\n        wheel_vel_del.right_wheel_vel =\n            rigid2d::normalize_angle(wheel_angle_new.right_wheel_angle -\n                                     wheel_angle_old.right_wheel_angle);\n        wheel_vel_del.left_wheel_vel =\n            rigid2d::normalize_angle(wheel_angle_new.left_wheel_angle -\n                                     wheel_angle_old.left_wheel_angle);\n\n        twist_del = diff_drive.wheels2Twist(wheel_vel_del);\n        wheel_angle_old = wheel_angle_new;\n\n        // Running Extended Kalman Filter\n        Kalman_Filter.run_ekf(twist_del, measurements);\n        q_t = Kalman_Filter.output_state();\n        m_t = Kalman_Filter.output_map_state();\n\n        measurements.clear();\n\n        // Publishing map markers\n        get_marker_from_map();\n\n        landmarks_flag = false;\n      }\n\n      // Setting transformations\n      world_map_transform();\n      world_slam_transform(); // TODO\n      map_odom_transform();\n      odom_body_transform();\n\n      // Publish odometry messages\n      publish_odometry();\n\n      loop_rate.sleep();\n      ros::spinOnce();\n    }\n  }\n\nprivate:\n  int frequency = 10;\n  bool joint_state_flag = false;\n  bool landmarks_flag = false;\n  bool reset_flag = false;\n  double wheel_base, wheel_radius, right_angle, left_angle, obstacles_radius;\n  std::string world_frame_id, map_frame_id, odom_frame_id, body_frame_id,\n      left_wheel_joint, right_wheel_joint;\n\n  arma::mat m_t;\n  arma::mat q_t = arma::mat(3, 1).fill(0.0);\n\n  ros::NodeHandle nh;\n  ros::Publisher odom_pub, slam_pub, landmarks_pub, slam_landmarks_pub;\n  ros::Subscriber joint_states_sub, landmarks_sub;\n  ros::ServiceServer set_pose_srv;\n  ros::Time current_time;\n\n  visualization_msgs::MarkerArray slam_marker_array;\n  tf2::Quaternion quat;\n  tf2_ros::TransformBroadcaster map_broadcaster, odom_broadcaster,\n      slam_broadcaster;\n  tf2_ros::StaticTransformBroadcaster static_world_broadcaster;\n  geometry_msgs::TransformStamped map_tf, odom_tf, slam_tf;\n  geometry_msgs::TransformStamped static_world_tf;\n\n  geometry_msgs::Quaternion odom_quat, map_quat;\n  nav_msgs::Odometry odom, slam;\n\n  rigid2d::Config2D odom_pose, reset_pose;\n  rigid2d::Twist2D twist, twist_del;\n  rigid2d::DiffDrive diff_drive;\n  rigid2d::WheelVelocity wheel_vel, wheel_vel_del;\n  rigid2d::WheelAngle wheel_angle, wheel_angle_new, wheel_angle_old;\n\n  std::vector<nuslam::Measurement> measurements;\n};\n\n/// \\brief Main function\n/// \\param argc - input int argument\n/// \\param argv - input array argument\n/// \\returns int\nint main(int argc, char *argv[])\n{\n  ros::init(argc, argv, \"slam\");\n  KFSlam node;\n  node.main_loop();\n  ros::spin();\n  return 0;\n}\n", "meta": {"hexsha": "9524e7a08b936383edb22f29ac3f67235260205d", "size": 16149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nuslam/src/slam.cpp", "max_stars_repo_name": "YaelBenShalom/Turtlebot3-SLAM-from-scratch", "max_stars_repo_head_hexsha": "82c118f8598549c4824c43c33b0f85d51b17f465", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-20T11:55:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T19:00:34.000Z", "max_issues_repo_path": "nuslam/src/slam.cpp", "max_issues_repo_name": "YaelBenShalom/Turtlebot3-SLAM-from-scratch", "max_issues_repo_head_hexsha": "82c118f8598549c4824c43c33b0f85d51b17f465", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nuslam/src/slam.cpp", "max_forks_repo_name": "YaelBenShalom/Turtlebot3-SLAM-from-scratch", "max_forks_repo_head_hexsha": "82c118f8598549c4824c43c33b0f85d51b17f465", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-20T09:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T09:25:22.000Z", "avg_line_length": 35.1065217391, "max_line_length": 81, "alphanum_fraction": 0.6779367143, "num_tokens": 4142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.04813677231147459, "lm_q1q2_score": 0.022378861088447555}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_MBT_FPS_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_MBT_FPS_HPP\r\n\r\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\r\n// This file is automatically generated. DO NOT EDIT.\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 4.9.1\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/aasincos.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct mbt_fps {};\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 mbt_fps\r\n    {\r\n\r\n            static const int MAX_ITER = 10;\r\n            static const double LOOP_TOL = 1e-7;\r\n            static const double C1 = 0.45503;\r\n            static const double C2 = 1.36509;\r\n            static const double C3 = 1.41546;\r\n            static const double C_x = 0.22248;\r\n            static const double C_y = 1.44492;\r\n            //static const double C1_2 = 0.33333333333333333333333333;\r\n\r\n            template <typename T>\r\n            inline T C1_2() { return detail::THIRD<T>(); }\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename CalculationType, typename Parameters>\r\n            struct base_mbt_fps_spheroid : public base_t_fi<base_mbt_fps_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>\r\n            {\r\n\r\n                typedef CalculationType geographic_type;\r\n                typedef CalculationType cartesian_type;\r\n\r\n\r\n                inline base_mbt_fps_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_mbt_fps_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    static const CalculationType C1_2 = mbt_fps::C1_2<CalculationType>();\r\n\r\n                    CalculationType k, V, t;\r\n                    int i;\r\n\r\n                    k = C3 * sin(lp_lat);\r\n                    for (i = MAX_ITER; i ; --i) {\r\n                        t = lp_lat / C2;\r\n                        lp_lat -= V = (C1 * sin(t) + sin(lp_lat) - k) /\r\n                            (C1_2 * cos(t) + cos(lp_lat));\r\n                        if (fabs(V) < LOOP_TOL)\r\n                            break;\r\n                    }\r\n                    t = lp_lat / C2;\r\n                    xy_x = C_x * lp_lon * (1. + 3. * cos(lp_lat)/cos(t) );\r\n                    xy_y = C_y * sin(t);\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    CalculationType t;\r\n\r\n                    lp_lat = C2 * (t = aasin(xy_y / C_y));\r\n                    lp_lon = xy_x / (C_x * (1. + 3. * cos(lp_lat)/cos(t)));\r\n                    lp_lat = aasin((C1 * sin(t) + sin(lp_lat)) / C3);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"mbt_fps_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // McBryde-Thomas Flat-Pole Sine (No. 2)\r\n            template <typename Parameters>\r\n            inline void setup_mbt_fps(Parameters& par)\r\n            {\r\n                par.es = 0;\r\n            }\r\n\r\n    }} // namespace detail::mbt_fps\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief McBryde-Thomas Flat-Pole Sine (No. 2) 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        \\par Example\r\n        \\image html ex_mbt_fps.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct mbt_fps_spheroid : public detail::mbt_fps::base_mbt_fps_spheroid<CalculationType, Parameters>\r\n    {\r\n        inline mbt_fps_spheroid(const Parameters& par) : detail::mbt_fps::base_mbt_fps_spheroid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::mbt_fps::setup_mbt_fps(this->m_par);\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::mbt_fps, mbt_fps_spheroid, mbt_fps_spheroid)\r\n\r\n        // Factory entry(s)\r\n        template <typename CalculationType, typename Parameters>\r\n        class mbt_fps_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                    return new base_v_fi<mbt_fps_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void mbt_fps_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"mbt_fps\", new mbt_fps_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_MBT_FPS_HPP\r\n\r\n", "meta": {"hexsha": "14feb1e88998764c5d73cd09d891548d0cf56a4a", "size": 7747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/mbt_fps.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/mbt_fps.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/mbt_fps.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": 39.7282051282, "max_line_length": 132, "alphanum_fraction": 0.6140441461, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.054198731350889234, "lm_q1q2_score": 0.02228168755694483}}
{"text": "#ifndef PARSER_FINITEAUTOMATON_HPP\n#define PARSER_FINITEAUTOMATON_HPP\n\n#include <iostream>\n#include <boost/spirit/home/x3.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/io.hpp>\n\n#include <boost/spirit/include/support_istream_iterator.hpp>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\nnamespace formal_device\n{\nnamespace finite_automaton\n{\nnamespace ast\n{\n\nstruct Symbol\n{\n    std::string m_value;\n};\n\nstruct TransitionSymbols\n{\n    std::vector<Symbol> m_transition_symbols;\n};\n\nstruct Transition\n{\n    std::vector<Symbol> m_transitions;\n};\n\nstruct State\n{\n    Symbol m_state;\n    std::vector<Transition> m_transitions;\n};\n\nstruct Document\n{\n    TransitionSymbols m_transition_symbols;\n    std::vector<State> m_states;\n};\n\n}\n}\n}\n\nBOOST_FUSION_ADAPT_STRUCT(formal_device::finite_automaton::ast::Symbol, m_value)\nBOOST_FUSION_ADAPT_STRUCT(formal_device::finite_automaton::ast::TransitionSymbols, m_transition_symbols)\nBOOST_FUSION_ADAPT_STRUCT(formal_device::finite_automaton::ast::Transition, m_transitions)\nBOOST_FUSION_ADAPT_STRUCT(formal_device::finite_automaton::ast::State, m_state, m_transitions)\nBOOST_FUSION_ADAPT_STRUCT(formal_device::finite_automaton::ast::Document, m_transition_symbols, m_states)\n\nnamespace formal_device\n{\nnamespace finite_automaton\n{\nnamespace parser {\n    namespace x3    = boost::spirit::x3;\n    namespace ascii = x3::ascii;\n\n    x3::rule<class symbol_, ast::Symbol>         symbol{\"symbol\"};\n    x3::rule<class transition_symbols_, ast::TransitionSymbols> transition_symbols{\"transition_symbols\"};\n    x3::rule<class transition_, ast::Transition> transition{\"transition\"};\n    x3::rule<class state_, ast::State>           state{\"state\"};\n    x3::rule<class document_, ast::Document>     document{\"document\"};\n\n    const auto identifier             = x3::lexeme[+x3::char_(\"->a-zA-Z0-9*\") - '\\n'];\n    const auto symbol_def             = identifier;\n    const auto transition_symbols_def = x3::lit(\"+ |\") >> symbol % \"|\";\n    const auto transition_def         = -x3::lit(\"{\") >> (symbol % \",\") >> -x3::lit(\"}\");\n    const auto state_def              = symbol >> \"|\" >> transition % \"|\";\n    const auto document_def           = transition_symbols >> x3::eol >> (state % x3::eol);\n\n    BOOST_SPIRIT_DEFINE(symbol, transition_symbols, transition, state, document);\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "d57c0314f0cd8a38181c519b883d9e4e1a558444", "size": 2359, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "formal_languages/parsers/FiniteAutomatonParser.hpp", "max_stars_repo_name": "Bonotto/INE5421", "max_stars_repo_head_hexsha": "d47da55eec17d1c1cab52e4cdf3d50c1e23cad3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "formal_languages/parsers/FiniteAutomatonParser.hpp", "max_issues_repo_name": "Bonotto/INE5421", "max_issues_repo_head_hexsha": "d47da55eec17d1c1cab52e4cdf3d50c1e23cad3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "formal_languages/parsers/FiniteAutomatonParser.hpp", "max_forks_repo_name": "Bonotto/INE5421", "max_forks_repo_head_hexsha": "d47da55eec17d1c1cab52e4cdf3d50c1e23cad3e", "max_forks_repo_licenses": ["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.7529411765, "max_line_length": 105, "alphanum_fraction": 0.7151335312, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.05834584429580278, "lm_q1q2_score": 0.022242578275649724}}
{"text": "//\n//  Copyright (c) 2000-2010\n//  Joerg Walter, Mathias Koch, David Bellot\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n//\n\n#ifndef _BOOST_UBLAS_IO_\n#define _BOOST_UBLAS_IO_\n\n// Only forward definition required to define stream operations\n#include <iosfwd>\n#include <sstream>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    /** \\brief output stream operator for vector expressions\n     *\n     * Any vector expressions can be written to a standard output stream\n     * as defined in the C++ standard library. For example:\n     * \\code\n     * vector<float> v1(3),v2(3);\n     * for(size_t i=0; i<3; i++)\n     * {\n     *       v1(i) = i+0.2;\n     *       v2(i) = i+0.3;\n     * }\n     * cout << v1+v2 << endl;\n     * \\endcode\n     * will display the some of the 2 vectors like this:\n     * \\code\n     * [3](0.5,2.5,4.5)\n     * \\endcode\n     *\n     * \\param os is a standard basic output stream\n     * \\param v is a vector expression\n     * \\return a reference to the resulting output stream\n     */\n    template<class E, class T, class VE>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    std::basic_ostream<E, T> &operator << (std::basic_ostream<E, T> &os,\n                                           const vector_expression<VE> &v) {\n        typedef typename VE::size_type size_type;\n        size_type size = v ().size ();\n        std::basic_ostringstream<E, T, std::allocator<E> > s;\n        s.flags (os.flags ());\n        s.imbue (os.getloc ());\n        s.precision (os.precision ());\n        s << '[' << size << \"](\";\n        if (size > 0)\n            s << v () (0);\n        for (size_type i = 1; i < size; ++ i)\n            s << ',' << v () (i);\n        s << ')';\n        return os << s.str ().c_str ();\n    }\n\n    /** \\brief input stream operator for vectors\n     *\n     * This is used to feed in vectors with data stored as an ASCII representation\n     * from a standard input stream.\n     *\n     * From a file or any valid stream, the format is: \n     * \\c [<vector size>](<data1>,<data2>,...<dataN>) like for example:\n     * \\code\n     * [5](1,2.1,3.2,3.14,0.2)\n     * \\endcode\n     *\n     * You can use it like this\n     * \\code\n     * my_input_stream >> my_vector;\n     * \\endcode\n     *\n     * You can only put data into a valid \\c vector<> not a \\c vector_expression\n     *\n     * \\param is is a standard basic input stream\n     * \\param v is a vector\n     * \\return a reference to the resulting input stream\n     */\n    template<class E, class T, class VT, class VA>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    std::basic_istream<E, T> &operator >> (std::basic_istream<E, T> &is,\n                                           vector<VT, VA> &v) {\n        typedef typename vector<VT, VA>::size_type size_type;\n        E ch;\n        size_type size;\n        if (is >> ch && ch != '[') {\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (is >> size >> ch && ch != ']') {\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (! is.fail ()) {\n            vector<VT, VA> s (size);\n            if (is >> ch && ch != '(') {\n                is.putback (ch);\n                is.setstate (std::ios_base::failbit);\n            } else if (! is.fail ()) {\n                for (size_type i = 0; i < size; i ++) {\n                    if (is >> s (i) >> ch && ch != ',') {\n                        is.putback (ch);\n                        if (i < size - 1)\n                            is.setstate (std::ios_base::failbit);\n                        break;\n                    }\n                }\n                if (is >> ch && ch != ')') {\n                    is.putback (ch);\n                    is.setstate (std::ios_base::failbit);\n                }\n            }\n            if (! is.fail ())\n                v.swap (s);\n        }\n        return is;\n    }\n\n    /** \\brief output stream operator for matrix expressions\n     *\n     * it outpus the content of a \\f$(M \\times N)\\f$ matrix to a standard output \n     * stream using the following format:\n     * \\c[<rows>,<columns>]((<m00>,<m01>,...,<m0N>),...,(<mM0>,<mM1>,...,<mMN>))\n     *\n     * For example:\n     * \\code\n     * matrix<float> m(3,3) = scalar_matrix<float>(3,3,1.0) - diagonal_matrix<float>(3,3,1.0);\n     * cout << m << endl;\n     * \\encode\n     * will display\n     * \\code\n     * [3,3]((0,1,1),(1,0,1),(1,1,0))\n     * \\endcode\n     * This output is made for storing and retrieving matrices in a simple way but you can\n     * easily recognize the following: \n     * \\f[ \\left( \\begin{array}{ccc} 1 & 1 & 1\\\\ 1 & 1 & 1\\\\ 1 & 1 & 1 \\end{array} \\right) - \\left( \\begin{array}{ccc} 1 & 0 & 0\\\\ 0 & 1 & 0\\\\ 0 & 0 & 1 \\end{array} \\right) = \\left( \\begin{array}{ccc} 0 & 1 & 1\\\\ 1 & 0 & 1\\\\ 1 & 1 & 0 \\end{array} \\right) \\f]\n     *\n     * \\param os is a standard basic output stream\n     * \\param m is a matrix expression\n     * \\return a reference to the resulting output stream\n     */\n    template<class E, class T, class ME>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    std::basic_ostream<E, T> &operator << (std::basic_ostream<E, T> &os,\n                                           const matrix_expression<ME> &m) {\n        typedef typename ME::size_type size_type;\n        size_type size1 = m ().size1 ();\n        size_type size2 = m ().size2 ();\n        std::basic_ostringstream<E, T, std::allocator<E> > s;\n        s.flags (os.flags ());\n        s.imbue (os.getloc ());\n        s.precision (os.precision ());\n        s << '[' << size1 << ',' << size2 << \"](\";\n        if (size1 > 0) {\n            s << '(' ;\n            if (size2 > 0)\n                s << m () (0, 0);\n            for (size_type j = 1; j < size2; ++ j)\n                s << ',' << m () (0, j);\n            s << ')';\n        }\n        for (size_type i = 1; i < size1; ++ i) {\n            s << \",(\" ;\n            if (size2 > 0)\n                s << m () (i, 0);\n            for (size_type j = 1; j < size2; ++ j)\n                s << ',' << m () (i, j);\n            s << ')';\n        }\n        s << ')';\n        return os << s.str ().c_str ();\n    }\n\n    /** \\brief input stream operator for matrices\n     *\n     * This is used to feed in matrices with data stored as an ASCII representation\n     * from a standard input stream.\n     *\n     * From a file or any valid standard stream, the format is:\n     * \\c[<rows>,<columns>]((<m00>,<m01>,...,<m0N>),...,(<mM0>,<mM1>,...,<mMN>))\n     *\n     * You can use it like this\n     * \\code\n     * my_input_stream >> my_matrix;\n     * \\endcode\n     *\n     * You can only put data into a valid \\c matrix<> not a \\c matrix_expression\n     *\n     * \\param is is a standard basic input stream\n     * \\param m is a matrix\n     * \\return a reference to the resulting input stream\n     */\n    template<class E, class T, class MT, class MF, class MA>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    std::basic_istream<E, T> &operator >> (std::basic_istream<E, T> &is,\n                                           matrix<MT, MF, MA> &m) {\n        typedef typename matrix<MT, MF, MA>::size_type size_type;\n        E ch;\n        size_type size1, size2;\n        if (is >> ch && ch != '[') {\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (is >> size1 >> ch && ch != ',') {\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (is >> size2 >> ch && ch != ']') {\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (! is.fail ()) {\n            matrix<MT, MF, MA> s (size1, size2);\n            if (is >> ch && ch != '(') {\n                is.putback (ch);\n                is.setstate (std::ios_base::failbit);\n            } else if (! is.fail ()) {\n                for (size_type i = 0; i < size1; i ++) {\n                    if (is >> ch && ch != '(') {\n                        is.putback (ch);\n                        is.setstate (std::ios_base::failbit);\n                        break;\n                    }\n                    for (size_type j = 0; j < size2; j ++) {\n                        if (is >> s (i, j) >> ch && ch != ',') {\n                            is.putback (ch);\n                            if (j < size2 - 1) {\n                                is.setstate (std::ios_base::failbit);\n                                break;\n                            }\n                        }\n                    }\n                    if (is >> ch && ch != ')') {\n                        is.putback (ch);\n                        is.setstate (std::ios_base::failbit);\n                        break;\n                    }\n                    if (is >> ch && ch != ',') {\n                       is.putback (ch);\n                       if (i < size1 - 1) {\n                            is.setstate (std::ios_base::failbit);\n                            break;\n                       }\n                    }\n                }\n                if (is >> ch && ch != ')') {\n                    is.putback (ch);\n                    is.setstate (std::ios_base::failbit);\n                }\n            }\n            if (! is.fail ())\n                m.swap (s);\n        }\n        return is;\n    }\n\n    /** \\brief special input stream operator for symmetric matrices\n     *\n     * This is used to feed in symmetric matrices with data stored as an ASCII \n     * representation from a standard input stream.\n     *\n     * You can simply write your matrices in a file or any valid stream and read them again \n     * at a later time with this function. The format is the following:\n     * \\code [<rows>,<columns>]((<m00>,<m01>,...,<m0N>),...,(<mM0>,<mM1>,...,<mMN>)) \\endcode\n     *\n     * You can use it like this\n     * \\code\n     * my_input_stream >> my_symmetric_matrix;\n     * \\endcode\n     *\n     * You can only put data into a valid \\c symmetric_matrix<>, not in a \\c matrix_expression\n     * This function also checks that input data form a valid symmetric matrix\n     *\n     * \\param is is a standard basic input stream\n     * \\param m is a \\c symmetric_matrix\n     * \\return a reference to the resulting input stream\n     */\n    template<class E, class T, class MT, class MF1, class MF2, class MA>\n    // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n    std::basic_istream<E, T> &operator >> (std::basic_istream<E, T> &is,\n                                           symmetric_matrix<MT, MF1, MF2, MA> &m) {\n        typedef typename symmetric_matrix<MT, MF1, MF2, MA>::size_type size_type;\n        E ch;\n        size_type size1, size2;\n        MT value;\n        if (is >> ch && ch != '[') {\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (is >> size1 >> ch && ch != ',') {\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (is >> size2 >> ch && (size2 != size1 || ch != ']')) { // symmetric matrix must be square\n            is.putback (ch);\n            is.setstate (std::ios_base::failbit);\n        } else if (! is.fail ()) {\n            symmetric_matrix<MT, MF1, MF2, MA> s (size1, size2);\n            if (is >> ch && ch != '(') {\n                is.putback (ch);\n                is.setstate (std::ios_base::failbit);\n             } else if (! is.fail ()) {\n                for (size_type i = 0; i < size1; i ++) {\n                    if (is >> ch && ch != '(') {\n                        is.putback (ch);\n                        is.setstate (std::ios_base::failbit);\n                        break;\n                    }\n                    for (size_type j = 0; j < size2; j ++) {\n                        if (is >> value >> ch && ch != ',') {\n                            is.putback (ch);\n                            if (j < size2 - 1) {\n                                is.setstate (std::ios_base::failbit);\n                                break;\n                            }\n                        }\n                        if (i <= j) { \n                             // this is the first time we read this element - set the value\n                            s(i,j) = value;\n                        }\n                        else if ( s(i,j) != value ) {\n                            // matrix is not symmetric\n                            is.setstate (std::ios_base::failbit);\n                            break;\n                        }\n                     }\n                     if (is >> ch && ch != ')') {\n                         is.putback (ch);\n                         is.setstate (std::ios_base::failbit);\n                         break;\n                     }\n                     if (is >> ch && ch != ',') {\n                        is.putback (ch);\n                        if (i < size1 - 1) {\n                             is.setstate (std::ios_base::failbit);\n                             break;\n                        }\n                     }\n                }\n                if (is >> ch && ch != ')') {\n                    is.putback (ch);\n                    is.setstate (std::ios_base::failbit);\n                }\n            }\n            if (! is.fail ())\n                m.swap (s);\n        }\n        return is;\n    }\n \n\n}}}\n\n#endif\n", "meta": {"hexsha": "1dee6afce64ef138feba879dd2b017ece72d47ba", "size": 13687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/ublas/io.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/numeric/ublas/io.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/numeric/ublas/io.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": 38.4466292135, "max_line_length": 258, "alphanum_fraction": 0.4470665595, "num_tokens": 3517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.055005283258827455, "lm_q1q2_score": 0.022198309103588065}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef bempp_default_iterative_solver_hpp\n#define bempp_default_iterative_solver_hpp\n\n#include \"../common/common.hpp\"\n#include \"bempp/common/config_trilinos.hpp\"\n\n#ifdef WITH_TRILINOS\n\n#include \"solver.hpp\"\n\n#include \"belos_solver_wrapper_fwd.hpp\" // for default parameter lists\n#include \"preconditioner.hpp\"\n\n#include \"../common/deprecated.hpp\"\n\n#include <boost/scoped_ptr.hpp>\n\nnamespace Thyra {\n/** \\cond FORWARD_DECL */\ntemplate <typename ValueType> class PreconditionerBase;\n/** \\endcond */\n} // namespace Thyra\n\nnamespace Bempp {\n\n/** \\ingroup linalg\n  * \\brief Default iterative solver for boundary integral equations.\n  *\n  * This class provides an interface to various iterative solvers available via\n  * the Stratimikos interface to the Belos solver family from Trilinos (see <a\n  * href=\"http://trilinos.sandia.gov/packages/docs/r10.10/packages/stratimikos/doc/html/index.html\">Stratimikos\n  * documentation</a>). Convergence can be tested either in range space or in\n  * the dual space to the range space. A standard Galerkin discretisation of\n  * the form \\f$Ax=b\\f$, maps into the dual space of the range of the operator.\n  * By choosing to test in the range space the equation \\f$M^\\dagger\n  * Ax=M^\\dagger b\\f$ is solved, where \\f$M\\f$ is the mass matrix, mapping from\n  * the range space into its dual and \\f$M^\\dagger\\f$ is its pseudoinverse.\n  *\n  */\ntemplate <typename BasisFunctionType, typename ResultType>\nclass DefaultIterativeSolver : public Solver<BasisFunctionType, ResultType> {\npublic:\n  typedef Solver<BasisFunctionType, ResultType> Base;\n\n  /** \\brief Constructor of the <tt>DefaultIterativeSolver</tt> class.\n    *\n    * \\param[in] boundaryOp\n    *   Non-blocked boundary operator.\n    * \\param[in] mode\n    *   Convergence test mode. Default:\n    *<tt>TEST_CONVERGENCE_IN_DUAL_TO_RANGE</tt>.\n    *\n    */\n  DefaultIterativeSolver(\n      const BoundaryOperator<BasisFunctionType, ResultType> &boundaryOp,\n      ConvergenceTestMode::Mode mode =\n          ConvergenceTestMode::TEST_CONVERGENCE_IN_DUAL_TO_RANGE);\n\n  /** \\brief Constructor of the <tt>DefaultIterativeSolver</tt> class.\n    *\n    * \\param[in] boundaryOp\n    *   Blocked boundary operator.\n    * \\param[in] mode\n    *   Convergence test mode. Default:\n    *<tt>TEST_CONVERGENCE_IN_DUAL_TO_RANGE</tt>.\n    *\n    */\n  DefaultIterativeSolver(\n      const BlockedBoundaryOperator<BasisFunctionType, ResultType> &boundaryOp,\n      ConvergenceTestMode::Mode mode =\n          ConvergenceTestMode::TEST_CONVERGENCE_IN_DUAL_TO_RANGE);\n\n  virtual ~DefaultIterativeSolver();\n\n  /** \\brief Define a preconditioner.\n    *\n    * The preconditioner is passed on to the Belos solver.\n    *\n    * \\param[in] preconditioner\n    *\n    * \\note This function has no effect if it is called after\n    *initializeSolver().\n    *\n    * \\deprecated Do not use this function in new code. Instead, pass the\n    *   preconditioner to initializeSolver().\n    */\n  BEMPP_DEPRECATED void\n  setPreconditioner(const Preconditioner<ResultType> &preconditioner);\n\n  /** \\brief Initialize a Belos iterative solver.\n    *\n    * \\param[in] paramList\n    *   Parameter lists can be read in from XML files or defined in code. Use\n    *   defaultGmresParameterList() and defaultCgParameterList() to construct\n    *   default parameter lists for the GMRES and CG solvers.\n    */\n  void initializeSolver(const Teuchos::RCP<Teuchos::ParameterList> &paramList);\n\n  /** \\brief Initialize a preconditioned Belos iterative solver.\n    *\n    * \\param[in] paramList\n    *   Parameter lists can be read in from XML files or defined in code. Use\n    *   defaultGmresParameterList() and defaultCgParameterList() to construct\n    *   default parameter lists for the GMRES and CG solvers.\n    * \\param[in] preconditioner\n    *   Preconditioner to be used by the solver.\n    */\n  void initializeSolver(const Teuchos::RCP<Teuchos::ParameterList> &paramList,\n                        const Preconditioner<ResultType> &preconditioner);\n\nprivate:\n  virtual Solution<BasisFunctionType, ResultType> solveImplNonblocked(\n      const GridFunction<BasisFunctionType, ResultType> &rhs) const;\n  virtual BlockedSolution<BasisFunctionType, ResultType> solveImplBlocked(\n      const std::vector<GridFunction<BasisFunctionType, ResultType>> &rhs)\n      const;\n\nprivate:\n  struct Impl;\n  boost::scoped_ptr<Impl> m_impl;\n};\n\n} // namespace Bempp\n\n#endif // WITH_TRILINOS\n\n#endif\n", "meta": {"hexsha": "0dafa29684e603c726e17856d59e59db2543afc8", "size": 5524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/linalg/default_iterative_solver.hpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/linalg/default_iterative_solver.hpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/linalg/default_iterative_solver.hpp", "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": 37.3243243243, "max_line_length": 111, "alphanum_fraction": 0.7328023172, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.04813677043386924, "lm_q1q2_score": 0.02219185887191871}}
{"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:59:12\n\n#ifndef MSSMNoFV_INPUT_PARAMETERS_H\n#define MSSMNoFV_INPUT_PARAMETERS_H\n\n#include <complex>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nstruct MSSMNoFV_input_parameters {\n   double TanBeta{};\n   int SignMu{1};\n   double Qin{};\n   double M1{};\n   double M2{};\n   double M3{};\n   double AtIN{};\n   double AbIN{};\n   double AtauIN{};\n   double AcIN{};\n   double AsIN{};\n   double AmuonIN{};\n   double AuIN{};\n   double AdIN{};\n   double AeIN{};\n   double mHd2IN{};\n   double mHu2IN{};\n   double ml11IN{};\n   double ml22IN{};\n   double ml33IN{};\n   double me11IN{};\n   double me22IN{};\n   double me33IN{};\n   double mq11IN{};\n   double mq22IN{};\n   double mq33IN{};\n   double mu11IN{};\n   double mu22IN{};\n   double mu33IN{};\n   double md11IN{};\n   double md22IN{};\n   double md33IN{};\n\n\n   Eigen::ArrayXd get() const;\n   void set(const Eigen::ArrayXd&);\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMNoFV_input_parameters&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "741a3db671b440db21268db3143d317d18e98152", "size": 1854, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/MSSMNoFV_input_parameters.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/MSSMNoFV_input_parameters.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/MSSMNoFV_input_parameters.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 25.397260274, "max_line_length": 74, "alphanum_fraction": 0.6370010787, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.0534033330012421, "lm_q1q2_score": 0.02215698122391584}}
{"text": "#include <unordered_set>\n\n#include <arrow/compute/api.h>\n#include <spdlog/spdlog.h>\n#include <Eigen/Dense>\n\n#include \"arrow_utils.h\"\n#include \"compute_utils.h\"\n\nnamespace stream_data_processor {\nnamespace compute_utils {\n\nnamespace {\n\narrow::Status sort(\n    const std::vector<std::string>& column_names, size_t i,\n    const std::shared_ptr<arrow::RecordBatch>& source,\n    std::vector<std::shared_ptr<arrow::RecordBatch>>* targets) {\n  if (i == column_names.size()) {\n    targets->push_back(source);\n    return arrow::Status::OK();\n  }\n\n  if (source->GetColumnByName(column_names[i]) == nullptr) {\n    ARROW_RETURN_NOT_OK(sort(column_names, i + 1, source, targets));\n    return arrow::Status::OK();\n  }\n\n  ARROW_ASSIGN_OR_RAISE(auto sorted_batch,\n                        sortByColumn(column_names[i], source));\n  while (true) {\n    auto sorted_keys = sorted_batch->GetColumnByName(column_names[i]);\n\n    ARROW_ASSIGN_OR_RAISE(auto min_val, sorted_keys->GetScalar(0));\n\n    ARROW_ASSIGN_OR_RAISE(auto max_val,\n                          sorted_keys->GetScalar(sorted_keys->length() - 1));\n\n    arrow::Datum equals_datum;\n    ARROW_ASSIGN_OR_RAISE(\n        equals_datum,\n        arrow::compute::Compare(sorted_keys, min_val,\n                                arrow::compute::CompareOptions(\n                                    arrow::compute::CompareOperator::EQUAL)));\n\n    ARROW_ASSIGN_OR_RAISE(auto filter_datum,\n                          arrow::compute::Filter(sorted_batch, equals_datum));\n\n    ARROW_RETURN_NOT_OK(\n        sort(column_names, i + 1, filter_datum.record_batch(), targets));\n\n    if (min_val->Equals(max_val)) {\n      break;\n    }\n\n    arrow::Datum not_equals_datum;\n    ARROW_ASSIGN_OR_RAISE(\n        not_equals_datum,\n        arrow::compute::Compare(\n            sorted_keys, min_val,\n            arrow::compute::CompareOptions(\n                arrow::compute::CompareOperator::NOT_EQUAL)));\n\n    arrow::Datum filter_not_equals_datum;\n    ARROW_ASSIGN_OR_RAISE(\n        filter_not_equals_datum,\n        arrow::compute::Filter(sorted_batch, not_equals_datum));\n\n    sorted_batch = filter_not_equals_datum.record_batch();\n  }\n\n  return arrow::Status::OK();\n}\n\n}  // namespace\n\narrow::Result<arrow::RecordBatchVector> groupSortingByColumns(\n    const std::vector<std::string>& column_names,\n    const std::shared_ptr<arrow::RecordBatch>& record_batch) {\n  arrow::RecordBatchVector grouped;\n  ARROW_RETURN_NOT_OK(sort(column_names, 0, record_batch, &grouped));\n  return grouped;\n}\n\narrow::Result<std::shared_ptr<arrow::RecordBatch>> sortByColumn(\n    const std::string& column_name,\n    const std::shared_ptr<arrow::RecordBatch>& source) {\n  auto sorting_column = source->GetColumnByName(column_name);\n  if (sorting_column == nullptr) {\n    return arrow::Status::KeyError(\n        fmt::format(\"No such column with name {}\", column_name));\n  }\n\n  if (sorting_column->type_id() == arrow::Type::TIMESTAMP) {\n    ARROW_ASSIGN_OR_RAISE(sorting_column,\n                          sorting_column->View(arrow::int64()));\n  }\n\n  ARROW_ASSIGN_OR_RAISE(auto sorted_idx,\n                        arrow::compute::SortIndices(*sorting_column));\n\n  ARROW_ASSIGN_OR_RAISE(auto sorted_datum,\n                        arrow::compute::Take(source, sorted_idx));\n\n  return sorted_datum.record_batch();\n}\n\narrow::Result<std::pair<size_t, size_t>> argMinMax(\n    std::shared_ptr<arrow::Array> array) {\n  if (array->type_id() == arrow::Type::TIMESTAMP) {\n    ARROW_ASSIGN_OR_RAISE(array, array->View(arrow::int64()));\n  }\n\n  ARROW_ASSIGN_OR_RAISE(auto min_max_ts, arrow::compute::MinMax(array));\n\n  int64_t arg_min = -1;\n  int64_t arg_max = -1;\n  size_t i = 0;\n  while (i < array->length() && (arg_min == -1 || arg_max == -1)) {\n    ARROW_ASSIGN_OR_RAISE(auto value_scalar, array->GetScalar(i));\n    if (value_scalar->Equals(\n            min_max_ts.scalar_as<arrow::StructScalar>().value[0])) {\n      arg_min = i;\n    }\n\n    if (value_scalar->Equals(\n            min_max_ts.scalar_as<arrow::StructScalar>().value[1])) {\n      arg_max = i;\n    }\n\n    ++i;\n  }\n\n  return std::pair{arg_min, arg_max};\n}\n\narrow::Result<size_t> tsLowerBound(const arrow::Array& sorted_ts_array,\n                                   const std::function<bool(int64_t)>& pred,\n                                   arrow::TimeUnit::type time_unit) {\n  size_t left_bound = 0;\n  size_t right_bound = sorted_ts_array.length();\n  while (left_bound != right_bound - 1) {\n    auto middle = (left_bound + right_bound) / 2;\n\n    ARROW_ASSIGN_OR_RAISE(auto ts_scalar,\n                          arrow_utils::castTimestampScalar(\n                              sorted_ts_array.GetScalar(middle), time_unit));\n\n    int64_t ts =\n        std::static_pointer_cast<arrow::TimestampScalar>(ts_scalar)->value;\n\n    if (pred(ts)) {\n      right_bound = middle;\n    } else {\n      left_bound = middle;\n    }\n  }\n\n  ARROW_ASSIGN_OR_RAISE(\n      auto ts_scalar, arrow_utils::castTimestampScalar(\n                          sorted_ts_array.GetScalar(left_bound), time_unit));\n\n  int64_t ts =\n      std::static_pointer_cast<arrow::TimestampScalar>(ts_scalar)->value;\n\n  if (pred(ts)) {\n    return left_bound;\n  } else {\n    return right_bound;\n  }\n}\n\ndouble FDDerivativeCalculator::calculateDerivative(\n    const std::deque<double>& xs, const std::deque<double>& ys, double x_der,\n    size_t order) const {\n  if (xs.size() != ys.size()) {\n    throw ComputeException(\n        fmt::format(\"Argument and value arrays have different sizes: {} and \"\n                    \"{}\",\n                    xs.size(), ys.size()));\n  }\n\n  if (xs.size() < order + 1) {\n    throw ComputeException(\n        fmt::format(\"For calculating {}-order derivative at least {} values \"\n                    \"are needed\",\n                    order, order + 1));\n  }\n\n  std::unordered_set<double> xs_set;\n  Eigen::MatrixXd taylor_coeffs_matrix(xs.size(), xs.size());\n  for (size_t k = 0; k < xs.size(); ++k) {\n    if (xs_set.find(xs[k]) != xs_set.end()) {\n      throw ComputeException(fmt::format(\n          \"Found repeating argument {} which is not allowed\", xs[k]));\n    } else {\n      xs_set.insert(xs[k]);\n    }\n\n    double delta = xs[k] - x_der;\n    double coeff = 1;\n    taylor_coeffs_matrix(0, k) = coeff;\n    for (int64_t n = 1; n < xs.size(); ++n) {\n      coeff *= delta / n;\n      taylor_coeffs_matrix(n, k) = coeff;\n    }\n  }\n\n  Eigen::VectorXd result_vector = Eigen::VectorXd::Zero(xs.size());\n  result_vector(order) = 1;\n\n  Eigen::VectorXd der_coeffs;\n\n  switch (linear_solver_) {\n    case AUTO:\n    case PARTIAL_PIV_LU:\n      der_coeffs = taylor_coeffs_matrix.partialPivLu().solve(result_vector);\n      break;\n    case HOUSEHOLDER_QR:\n      der_coeffs = taylor_coeffs_matrix.householderQr().solve(result_vector);\n      break;\n    case COL_PIV_HOUSEHOLDER_QR:\n      der_coeffs =\n          taylor_coeffs_matrix.colPivHouseholderQr().solve(result_vector);\n      break;\n    default:\n      throw ComputeException(\n          fmt::format(\"Unexpected linear solver type: {}\", linear_solver_));\n  }\n\n  double der_result = 0;\n  for (size_t i = 0; i < ys.size(); ++i) {\n    der_result += ys[i] * der_coeffs(i);\n  }\n\n  return der_result;\n}\n\n}  // namespace compute_utils\n}  // namespace stream_data_processor\n", "meta": {"hexsha": "cb0bbdf802858c2e5461d038ae661bc1a62f3a19", "size": 7210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/compute_utils.cpp", "max_stars_repo_name": "QratorLabs/stream-data-processor", "max_stars_repo_head_hexsha": "10be5b5d7c9ffa2f481218f6bf7c3c1ee12a0752", "max_stars_repo_licenses": ["MIT"], "max_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/compute_utils.cpp", "max_issues_repo_name": "QratorLabs/stream-data-processor", "max_issues_repo_head_hexsha": "10be5b5d7c9ffa2f481218f6bf7c3c1ee12a0752", "max_issues_repo_licenses": ["MIT"], "max_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/compute_utils.cpp", "max_forks_repo_name": "QratorLabs/stream-data-processor", "max_forks_repo_head_hexsha": "10be5b5d7c9ffa2f481218f6bf7c3c1ee12a0752", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-11T15:32:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T15:32:34.000Z", "avg_line_length": 29.9170124481, "max_line_length": 78, "alphanum_fraction": 0.6355062413, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538605, "lm_q2_score": 0.04885778398879701, "lm_q1q2_score": 0.022145369460698672}}
{"text": "/**\n * @file   SuccessiveLinearizationOptimizer.cpp\n * @brief  \n * @date   Jul 24, 2012\n * @author Yong-Dian Jian\n */\n\n#include <gtsam/nonlinear/SuccessiveLinearizationOptimizer.h>\n#include <gtsam/inference/EliminationTree.h>\n#include <gtsam/linear/GaussianJunctionTree.h>\n#include <gtsam/linear/SubgraphSolver.h>\n#include <gtsam/linear/VectorValues.h>\n#include <boost/shared_ptr.hpp>\n#include <stdexcept>\n\nnamespace gtsam {\n\nvoid SuccessiveLinearizationParams::setIterativeParams(const SubgraphSolverParameters &params) {\n  iterativeParams = boost::make_shared<SubgraphSolverParameters>(params);\n}\n\nvoid SuccessiveLinearizationParams::print(const std::string& str) const {\n  NonlinearOptimizerParams::print(str);\r\n  switch ( linearSolverType ) {\r\n  case MULTIFRONTAL_CHOLESKY:\r\n    std::cout << \"         linear solver type: MULTIFRONTAL CHOLESKY\\n\";\r\n    break;\r\n  case MULTIFRONTAL_QR:\r\n    std::cout << \"         linear solver type: MULTIFRONTAL QR\\n\";\r\n    break;\r\n  case SEQUENTIAL_CHOLESKY:\r\n    std::cout << \"         linear solver type: SEQUENTIAL CHOLESKY\\n\";\r\n    break;\r\n  case SEQUENTIAL_QR:\r\n    std::cout << \"         linear solver type: SEQUENTIAL QR\\n\";\r\n    break;\r\n  case CHOLMOD:\r\n    std::cout << \"         linear solver type: CHOLMOD\\n\";\r\n    break;\r\n  case CONJUGATE_GRADIENT:\r\n    std::cout << \"         linear solver type: CONJUGATE GRADIENT\\n\";\r\n    break;\r\n  default:\r\n    std::cout << \"         linear solver type: (invalid)\\n\";\r\n    break;\r\n  }\r\n\r\n  if(ordering)\r\n    std::cout << \"                   ordering: custom\\n\";\r\n  else\r\n    std::cout << \"                   ordering: COLAMD\\n\";\r\n\r\n  std::cout.flush();\r\n}\n\nVectorValues solveGaussianFactorGraph(const GaussianFactorGraph &gfg, const SuccessiveLinearizationParams &params) {\n  gttic(solveGaussianFactorGraph);\n  VectorValues delta;\n  if (params.isMultifrontal()) {\n    delta = GaussianJunctionTree(gfg).optimize(params.getEliminationFunction());\n  } else if(params.isSequential()) {\n    const boost::shared_ptr<GaussianBayesNet> gbn =\n      EliminationTree<GaussianFactor>::Create(gfg)->eliminate(params.getEliminationFunction());\n    delta = gtsam::optimize(*gbn);\n  }\n  else if ( params.isCG() ) {\n    if ( !params.iterativeParams ) throw std::runtime_error(\"solveGaussianFactorGraph: cg parameter has to be assigned ...\");\n    if ( boost::dynamic_pointer_cast<SubgraphSolverParameters>(params.iterativeParams) ) {\n      SubgraphSolver solver (gfg, *boost::dynamic_pointer_cast<SubgraphSolverParameters>(params.iterativeParams));\n      delta = solver.optimize();\n    }\n    else {\n      throw std::runtime_error(\"solveGaussianFactorGraph: special cg parameter type is not handled in LM solver ...\");\n    }\n  }\n  else {\n    throw std::runtime_error(\"solveGaussianFactorGraph: Optimization parameter is invalid\");\n  }\n  return delta;\n}\n\n}\n", "meta": {"hexsha": "0e8e4d748ecaff367b9f62a9ff165097ca095e78", "size": 2826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/nonlinear/SuccessiveLinearizationOptimizer.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "gtsam/nonlinear/SuccessiveLinearizationOptimizer.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/nonlinear/SuccessiveLinearizationOptimizer.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0481927711, "max_line_length": 125, "alphanum_fraction": 0.6893135173, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.045352578457547636, "lm_q1q2_score": 0.022144910994672088}}
{"text": "/*\n * cte.cpp\n *\n *  Created on: 14 Sep 2018\n *      Author: radu\n *\n * Copyright (c) 2015, International Business Machines Corporation\n * and University of California Irvine. All rights reserved.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n\n#include \"cte.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace boost;\ntypedef adjacency_list<vecS, vecS, undirectedS, no_property,\n\t\tproperty<edge_weight_t, int> > BoostGraph;\ntypedef graph_traits<BoostGraph>::edge_descriptor BoostEdge;\ntypedef graph_traits<BoostGraph>::vertex_descriptor BoostVertex;\ntypedef std::pair<int, int> E;\n\nnamespace merlin {\n\n// Initialize the clique tree\nvoid cte::init() {\n\n\t// Prologue\n\tif (m_verbose > 0) {\n\t\tstd::cout << \"[CTE] + inference task   : \" << m_task << std::endl;\n\t}\n\n\tif (m_query.empty() == false) {\n\t\tif (m_verbose > 0) {\n\t\t\tstd::cout << \"[CTE] + query vars       : \";\n\t\t\tstd::copy(m_query.begin(), m_query.end(), std::ostream_iterator<vindex>(std::cout, \" \"));\n\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t\t// Add a dummy factor over the query variables\n\t\tif (m_query.size() <= MERLIN_MAXSIZE_JOINT_MARGINAL) {\n\t\t\tvariable_set scope;\n\t\t\tfor (size_t i = 0; i < m_query.size(); ++i) {\n\t\t\t\tscope |= m_gmo.var(m_query[i]);\n\t\t\t}\n\n\t\t\tfactor q(scope, 1.0);\n\t\t\tm_gmo.add_factor(q);\n\t\t}\n\t}\n\n\tif (m_order.size() == 0) { // if we need to construct an elimination ordering\n\t\tm_order = m_gmo.order(m_order_method);\n\t}\n\n\n\tif (m_verbose > 0) {\n\t\tstd::cout << \"[CTE] + ordering method  : \" << m_order_method << std::endl;\n\t\tstd::cout << \"[CTE] + elimination      : \";\n\t\tstd::copy(m_order.begin(), m_order.end(),\n\t\t\t\tstd::ostream_iterator<size_t>(std::cout, \" \"));\n\t\tstd::cout << std::endl;\n\n\t\t// Calculate the induced width of the elimination ordering\n\t\tsize_t wstar = m_gmo.induced_width(m_order);\n\t\tstd::cout << \"[CTE] + induced width    : \" << wstar << std::endl;\n\t\tstd::cout << \"[CTE] + exact inference  : Yes\" << std::endl;\n\t\tstd::cout << \"[CTE] + ordering time    : \" << (timeSystem() - m_start_time) << \" seconds\" << std::endl;\n\t\tstd::cout << \"[CTE] Building clique tree ... \" << std::endl;\n\t}\n\n\t// Get the factors scopes\n\tsize_t n = m_gmo.num_nodes();\n\tvector<variable_set> fin;\n\tfor (vector<factor>::const_iterator i = m_gmo.get_factors().begin();\n\t\t\ti != m_gmo.get_factors().end(); ++i) {\n\t\tfin.push_back((*i).vars());\n\t}\n\n\t// Create the graph\n\tgraph g(n);\n\tg.init(fin);\n\n\t// Triangulate the graph\n\tg.triangulate(m_order);\n\n\t// Find the maximal cliques\n\tstd::vector<std::set<size_t> > clusters = g.maximal_cliques(m_order);\n\n\t// Build the clique tree\n\tbuild_clique_tree(clusters);\n\n\tif (m_verbose > 0) {\n\t\tstd::cout << \"[CTE] Created clique tree with \" << m_clusters.size()\n\t\t\t\t<< \" clique factors\" << std::endl;\n\t}\n\n\tsize_t max_clique_size = 0, max_sepset_size = 0;\n\tfor (size_t i = 0; i < m_edges.size(); ++i) {\n\t\tdetail::edge* e = m_edges[i];\n\t\tmax_clique_size = std::max(max_clique_size, e->first->clique.size());\n\t\tmax_clique_size = std::max(max_clique_size, e->second->clique.size());\n\t\tmax_sepset_size = std::max(max_sepset_size, e->sepset.size());\n\t}\n\n\t// Initialize beliefs (marginals)\n\tm_logz = 0;\n\tm_beliefs.clear();\n\tm_beliefs.resize(m_gmo.nvar(), factor(1.0));\n\n\t// Output the bucket tree statistics\n\tif (m_verbose > 0) {\n\t\tdouble elapsed = (timeSystem() - m_start_time);\n\t\tstd::cout << \"[CTE] Number of cliques  : \" << m_clusters.size() << std::endl;\n\t\tstd::cout << \"[CTE] Number of edges    : \" << m_edges.size() << std::endl;\n\t\tstd::cout << \"[CTE] Max clique size    : \" << max_clique_size << std::endl;\n\t\tstd::cout << \"[CTE] Max separator size : \" << max_sepset_size << std::endl;\n\t\tstd::cout << \"[CTE] Finished initialization in \" << elapsed << \" seconds\" << std::endl;\n\t}\n}\n\n// Build the join tree and initialize the cluster factors\nvoid cte::build_clique_tree(std::vector<std::set<size_t> >& cliques) {\n\n\tsize_t n = cliques.size();\n\tstd::vector<std::vector<int> > adjacencies;\n\tadjacencies.resize(n);\n\tfor (std::vector<std::vector<int> >::iterator it = adjacencies.begin();\n\t\t\tit != adjacencies.end(); ++it) {\n\t\tit->resize(n);\n\t}\n\n\t// create nodes\n\tm_clusters.resize(n);\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tm_clusters[i].id = i;\n\t\tfor (std::set<size_t>::iterator j = cliques[i].begin();\n\t\t\t\tj != cliques[i].end(); ++j) {\n\t\t\tm_clusters[i].clique |= var(*j);\n\t\t}\n\t}\n\n\t// fill in the weights\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tfor (size_t j = 0; j < n; ++j) {\n\t\t\tif (i != j) {\n\t\t\t\tdetail::node& ni = m_clusters[i];\n\t\t\t\tdetail::node& nj = m_clusters[j];\n\n\t\t\t\tstd::set<int> sep;\n\t\t\t\tstd::set_intersection(ni.clique.begin(), ni.clique.end(),\n\t\t\t\t\t\tnj.clique.begin(), nj.clique.end(),\n\t\t\t\t\t\tstd::inserter(sep, sep.begin()));\n\n\t\t\t\tif (sep.empty()) {\n\t\t\t\t\tadjacencies[i][j] = (100000);\n\t\t\t\t} else {\n\t\t\t\t\tadjacencies[i][j] = -(sep.size());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// create a boost weighted graph and run Kruskal on it\n\tconst int num_nodes = n;\n\tstd::vector<E> temp1;\n\tstd::vector<int> temp2;\n\tfor (int i = 0; i < num_nodes - 1; ++i) {\n\t\tfor (int j = i + 1; j < num_nodes; ++j) {\n\t\t\tif (i != j) {\n\t\t\t\ttemp1.push_back( E(i, j) );\n\t\t\t\ttemp2.push_back( adjacencies[i][j] );\n\t\t\t}\n\t\t}\n\t}\n\n\tE* edge_array = new E[temp1.size()];\n\tint* weights = new int[temp1.size()];\n\tfor (size_t i = 0; i < temp1.size(); ++i) {\n\t\tedge_array[i] = temp1[i];\n\t\tweights[i] = temp2[i];\n\t}\n\n\tstd::size_t num_edges = temp1.size();\n\n\tBoostGraph g(edge_array, edge_array + num_edges, weights, num_nodes);\n\tstd::vector<BoostEdge> spanning_tree;\n\n\tkruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n\tif (m_debug) {\n\t\tstd::cout << \"Undirected junction tree (MST):\" << std::endl;\n\t\tproperty_map<BoostGraph, edge_weight_t>::type weight = get(edge_weight, g);\n\t\tfor (std::vector<BoostEdge>::iterator ei = spanning_tree.begin();\n\t\t\t\tei != spanning_tree.end(); ++ei) {\n\t\t\tstd::cout << source(*ei, g) << \" <--> \" << target(*ei, g)\n\t\t\t\t\t<< \" with weight of \" << weight[*ei] << \"\\n\";\n\t\t}\n\t}\n\n\t// select the root and redirect edges outwards\n\tm_root = &(m_clusters.back());\n\tsize_t root = m_root->id;\n\tstd::set<size_t> visited;\n\tstd::stack<size_t> dfs;\n\tdfs.push(root);\n\twhile ( !dfs.empty() ) {\n\n\t\tsize_t c = dfs.top(); // current node\n\t\tdfs.pop();\n\n\t\t// get all unvisited children and direct them towards n\n\t\tfor (std::vector<BoostEdge>::iterator ei = spanning_tree.begin();\n\t\t\t\tei != spanning_tree.end(); ++ei) {\n\t\t\tsize_t src = (size_t) source(*ei, g);\n\t\t\tsize_t trg = (size_t) target(*ei, g);\n\t\t\tdetail::node* from = NULL, *to = NULL;\n\n\t\t\tif (src == c &&\n\t\t\t\tstd::find(visited.begin(), visited.end(), trg) == visited.end()) {\n\n\t\t\t\tfrom = &(m_clusters[trg]); // from\n\t\t\t\tto = &(m_clusters[src]); // to\n\t\t\t\tdfs.push(trg);\n\t\t\t}\n\n\t\t\tif (trg == c &&\n\t\t\t\tstd::find(visited.begin(), visited.end(), src) == visited.end()) {\n\n\t\t\t\tfrom = &(m_clusters[src]); // from\n\t\t\t\tto = &(m_clusters[trg]); // to\n\t\t\t\tdfs.push(src);\n\t\t\t}\n\n\t\t\t// create the directed edge\n\t\t\tif (from != NULL && to != NULL) {\n\t\t\t\tdetail::edge* e = new detail::edge(from, to);\n\t\t\t\tm_edges.push_back(e);\n\t\t\t\tfrom->edges.push_back(e);\n\t\t\t\tto->edges.push_back(e);\n\t\t\t\tto->children.push_back(from);\n\t\t\t\tfrom->parent = to;\n\t\t\t}\n\t\t}\n\n\t\tvisited.insert(c);\n\t}\n\n\t// find the message order (schedule) by a bfs of the junction tree\n\tstd::queue<detail::node*> bfs;\n\tbfs.push(m_root);\n\twhile (!bfs.empty()) {\n\t\tdetail::node* c = bfs.front();\n\t\tbfs.pop();\n\t\tvector<detail::edge*>& elist = c->edges;\n\t\tfor (vector<detail::edge*>::iterator it = elist.begin();\n\t\t\t\tit != elist.end(); ++it) {\n\t\t\tdetail::edge* e = (*it);\n\t\t\tif (e->second->id == c->id) {\n\t\t\t\tm_messages.push_back(e);\n\t\t\t}\n\t\t}\n\n\t\tfor (vector<detail::node*>::iterator it = c->children.begin();\n\t\t\t\tit != c->children.end(); ++it) {\n\t\t\tbfs.push(*it);\n\t\t}\n\t}\n\n\t// safety checks\n\tassert(m_messages.size() == m_edges.size());\n\n\t// reverse the order to start from the leaves\n\tstd::reverse(m_messages.begin(), m_messages.end());\n\n\t// clean up\n\tdelete[] weights;\n\tdelete[] edge_array;\n\n\tif (m_debug) {\n\t\tstd::ofstream fout(\"kruskal.dot\");\n\t\tfout << \"digraph JT {\\n\" << \" rankdir=LR\\n\" << \" size=\\\"3,3\\\"\\n\"\n\t\t\t\t<< \" ratio=\\\"filled\\\"\\n\" << \" edge[style=\\\"bold\\\"]\\n\"\n\t\t\t\t<< \" node[shape=\\\"circle\\\"]\\n\";\n\t\t// nodes\n\t\tfor (size_t i = 0; i < m_clusters.size(); ++i) {\n\t\t\tstd::stringstream label;\n\t\t\tlabel << m_clusters[i].id << \": \" << m_clusters[i].clique;\n\t\t\tfout << \"node\" << m_clusters[i].id\n\t\t\t\t<< \"[ label = \\\"\" << label.str() << \"\\\"];\\n\";\n\t\t}\n\n\t\t// edges\n\t\tfor (size_t i = 0; i < m_edges.size(); ++i) {\n\t\t\tdetail::edge* e = m_edges[i];\n\t\t\tfout << \"node\" << e->first->id << \" -> \" << \"node\" << e->second->id << \";\\n\";\n\t\t}\n\n\t\tfout << \"}\\n\";\n\t\tfout.close();\n\t}\n\n\t// Map variables to clusters\n\tm_var2clique.resize(m_gmo.nvar(), -1);\n\tfor (size_t i = 0; i < m_clusters.size(); ++i) {\n\t\tdetail::node& cl = m_clusters[i];\n\t\tvariable_set& vars = cl.clique;\n\t\tfor (variable_set::const_iterator j = vars.begin();\n\t\t\t\tj != vars.end(); ++j) {\n\t\t\tsize_t v = (*j).label();\n\t\t\tif (m_var2clique[v] < 0) {\n\t\t\t\tm_var2clique[v] = cl.id;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Allocate original functions to clusters and compute clique factors\n\tsize_t idx = 0;\n\tfor (vector<factor>::const_iterator fi = m_gmo.get_factors().begin();\n\t\t\tfi != m_gmo.get_factors().end(); ++fi, ++idx) {\n\n\t\tconst factor& f = (*fi);\n\t\tfor (size_t ci = 0; ci != m_clusters.size(); ++ci) {\n\t\t\tdetail::node& cl = m_clusters[ci];\n\t\t\tif ((f.vars() & cl.clique) == f.vars()) {\n\t\t\t\tcl.originals.push_back(idx);\n\t\t\t\tcl.theta *= f;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (m_debug) {\n\t\tstd::cout << \"Initial cluster factors:\" << std::endl;\n\t\tfor (size_t ci = 0; ci != m_clusters.size(); ++ci) {\n\t\t\tdetail::node& cl = m_clusters[ci];\n\t\t\tstd::cout << \" \" << ci << \" -> \" << cl.theta << std::endl;\n\t\t}\n\t}\n}\n\n// Update the collection of factors, recompute the clique factors and reset the\n// messages. We assume there is a one-to-one mapping between the old factors\n// and the new factors. This method is to be used only for EM param learning.\nvoid cte::reinit(const std::vector<factor>& factors) {\n\n\t// Set the new factors\n\tfor (size_t i = 0; i < factors.size(); ++i) {\n\t\tm_gmo.set_factor(i, factors[i]);\n\t}\n\n\t// Recompute the clique factors\n\tfor (size_t ci = 0; ci != m_clusters.size(); ++ci) {\n\t\tdetail::node& cl = m_clusters[ci];\n\t\tcl.theta = factor(1.0);\n\t\tfor (size_t j = 0; j < cl.originals.size(); ++j) {\n\t\t\tconst factor& f = m_gmo.get_factor(cl.originals[j]);\n\t\t\tcl.theta *= f;\n\t\t}\n\t}\n\n\t// Reset the edge messages\n\tfor (vector<detail::edge*>::iterator it = m_edges.begin();\n\t\t\tit != m_edges.end(); ++it) {\n\t\t(*it)->reset();\n\t}\n\n\t// Reset the log partition function and beliefs\n\tm_logz = 0;\n\tm_beliefs.clear();\n\tm_beliefs.resize(m_gmo.nvar(), factor(1.0));\n\n\tif (m_debug) {\n\t\tstd::cout << \"Initial cluster factors:\" << std::endl;\n\t\tfor (size_t ci = 0; ci != m_clusters.size(); ++ci) {\n\t\t\tdetail::node& cl = m_clusters[ci];\n\t\t\tstd::cout << \" \" << ci << \" -> \" << cl.theta << std::endl;\n\t\t}\n\t}\n}\n\n// Forward message propagation (from leaves to root)\nvoid cte::forward() {\n\tdouble timestamp = timeSystem();\n\tfor (vector<detail::edge*>::iterator i = m_messages.begin();\n\t\t\ti != m_messages.end(); ++i) {\n\t\tdetail::edge* e = (*i);\n\t\te->messageFwd();\n\t}\n\n\tif (m_verbose > 0) {\n\t\tstd::cout << \"[CTE] Finished forward pass in \" << (timeSystem() - timestamp)\n\t\t\t<< \" seconds\" << std::endl;\n\t}\n}\n\n// Forward message propagation with evidence (from leaves to root)\nvoid cte::forward(std::vector<int>& evidence) {\n\tfor (vector<detail::edge*>::iterator i = m_messages.begin();\n\t\t\ti != m_messages.end(); ++i) {\n\t\tdetail::edge* e = (*i);\n\t\te->messageFwd(evidence);\n\n\t\tif (m_debug) {\n\t\t\tstd::cout << \" -> forward msg from \"\n\t\t\t\t<< e->first->id << \" to \" << e->second->id\n\t\t\t\t<< \": \" << e->fwd << std::endl;\n\t\t}\n\t}\n}\n\n// Forward message on an edge\nvoid detail::edge::messageFwd() {\n\n\t// collect the original functions\n\tfactor F = first->theta;\n\n\t// collect the incoming messages (should already be projected)\n\tfor (size_t i = 0; i < first->edges.size(); ++i) {\n\t\tdetail::edge* e = first->edges[i];\n\t\tif (e == this) {\n\t\t\tcontinue; // skip current edge\n\t\t}\n\t\tif (e->first->id == first->id) {\n\t\t\tF *= e->bwd; //e->getMessage2();\n\t\t} else if (e->second->id == first->id) {\n\n\t\t\tF *= e->fwd; //e->getMessage1();\n\t\t}\n\t}\n\n\t// marginalize the eliminator\n\tvariable_set elim = (first->clique - sepset);\n\tif (elim.size() > 0) {\n\t\tF = F.sum(elim);\n\t}\n\n\t// update the forward message\n\tthis->fwd = F;\n}\n\n// Forward message computed with evidence on an edge\nvoid detail::edge::messageFwd(std::vector<int>& evidence) {\n\n\t// collect the original functions\n\tfactor F = first->theta;\n\tF = F.condition(evidence);\n\n\t// collect the incoming messages (should already be projected)\n\tfor (size_t i = 0; i < first->edges.size(); ++i) {\n\t\tdetail::edge* e = first->edges[i];\n\t\tif (e == this) {\n\t\t\tcontinue; // skip current edge\n\t\t}\n\t\tif (e->first->id == first->id) {\n\t\t\tF *= e->bwd.condition(evidence);\n\t\t} else if (e->second->id == first->id) {\n\n\t\t\tF *= e->fwd.condition(evidence);\n\t\t}\n\t}\n\n\t// Find the evidence variables in the scope of the cluster\n\tvariable_set evid;\n\tfor (variable_set::const_iterator i = first->clique.begin();\n\t\t\ti != first->clique.end(); ++i) {\n\t\tint v = i->label();\n\t\tif (evidence[v] >= 0) {\n\t\t\tevid |= *i;\n\t\t}\n\t}\n\n\t// Marginalize the non-evidence eliminator\n\t//F = F.condition(evidence);\n\tvariable_set elim = (first->clique - sepset);\n\telim -= evid;\n\tif (elim.size() > 0) {\n\t\tF = F.sum(elim);\n\t}\n\n\t// update the forward message\n\tthis->fwd = F;\n\n}\n\n// Backward message propagation (from root to leaves)\nvoid cte::backward() {\n\tdouble timestamp = timeSystem();\n\tfor (vector<detail::edge*>::reverse_iterator ri = m_messages.rbegin();\n\t\t\tri != m_messages.rend(); ++ri) {\n\t\tdetail::edge* e = (*ri);\n\t\te->messageBwd();\n\t}\n\n\tif (m_verbose > 0) {\n\t\tstd::cout << \"[CTE] Finished backward pass in \" << (timeSystem() - timestamp)\n\t\t\t<< \" seconds\" << std::endl;\n\t}\n}\n\n// Backward message propagation with evidence (from root to leaves)\nvoid cte::backward(std::vector<int>& evidence) {\n\tfor (vector<detail::edge*>::reverse_iterator ri = m_messages.rbegin();\n\t\t\tri != m_messages.rend(); ++ri) {\n\t\tdetail::edge* e = (*ri);\n\t\te->messageBwd(evidence);\n\n\t\tif (m_debug) {\n\t\t\tstd::cout << \" <- backward msg from \"\n\t\t\t\t<< e->second->id << \" to \" << e->first->id\n\t\t\t\t<< \": \" << e->bwd << std::endl;\n\t\t}\n\t}\n}\n\n// Backward message on an edge\nvoid detail::edge::messageBwd() {\n\n\t// collect the original functions\n\tfactor F = second->theta;\n\n\t// collect the incoming messages\n\tfor (size_t i = 0; i < second->edges.size(); ++i) {\n\t\tdetail::edge* e = second->edges[i];\n\t\tif (e == this) {\n\t\t\tcontinue; // skip current edge\n\t\t}\n\t\tif (e->first->id == second->id) {\n\t\t\tF *= e->bwd; //e->getMessage2();\n\t\t} else if (e->second->id == second->id) {\n\t\t\tF *= e->fwd; //e->getMessage1();\n\t\t}\n\t}\n\n\t// marginalize the eliminator\n\tvariable_set elim = (second->clique - sepset);\n\tif (elim.size() > 0) {\n\t\tF = F.sum(elim);\n\t}\n\n\tthis->bwd = F;\n}\n\n// Backward message computed with evidence on an edge\nvoid detail::edge::messageBwd(std::vector<int>& evidence) {\n\n\t// collect the original functions\n\tfactor F = second->theta;\n\tF = F.condition(evidence);\n\n\t// collect the incoming messages\n\tfor (size_t i = 0; i < second->edges.size(); ++i) {\n\t\tdetail::edge* e = second->edges[i];\n\t\tif (e == this) {\n\t\t\tcontinue; // skip current edge\n\t\t}\n\t\tif (e->first->id == second->id) {\n\t\t\tF *= e->bwd.condition(evidence); //e->getMessage2();\n\t\t} else if (e->second->id == second->id) {\n\t\t\tF *= e->fwd.condition(evidence); //e->getMessage1();\n\t\t}\n\t}\n\n\t// find the evidence variables in the scope of the cluster\n\tvariable_set evid;\n\tfor (variable_set::const_iterator i = second->clique.begin();\n\t\t\ti != second->clique.end(); ++i) {\n\t\tint v = i->label();\n\t\tif (evidence[v] >= 0) {\n\t\t\tevid |= *i;\n\t\t}\n\t}\n\n\t// marginalize the eliminator\n\tvariable_set elim = (second->clique - sepset);\n\telim -= evid;\n\tif (elim.size() > 0) {\n\t\tF = F.sum(elim);\n\t}\n\n\tthis->bwd = F;\n\n}\n\n// Clique tree calibration\nvoid cte::calibrate() {\n\n\tforward();\n\tbackward();\n}\n\n// Update the beliefs (marginals or max-marginals)\nvoid cte::update() {\n\n\t// Compute the clique beliefs\n\tfor (size_t i = 0; i < m_clusters.size(); ++i) {\n\t\tdetail::node& cl = m_clusters[i];\n\t\tcl.belief = cl.theta;\n\t\tfor (vector<detail::edge*>::iterator ei = cl.edges.begin();\n\t\t\t\tei != cl.edges.end(); ++ei) {\n\t\t\tdetail::edge* e = (*ei);\n\t\t\tif (e->second->id == cl.id) {\n\t\t\t\tcl.belief *= e->fwd;\n\t\t\t}\n\t\t\tif (e->first->id == cl.id) {\n\t\t\t\tcl.belief *= e->bwd;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compute the log partition function\n\tm_logz = std::log(m_root->belief.sum());\n\n\t// Compute the marginals\n\tfor (size_t v = 0; v < m_var2clique.size(); ++v) {\n\t\tsize_t ci = m_var2clique[v];\n\t\tdetail::node& cl = m_clusters[ci];\n\t\tvariable VX = m_gmo.var(v);\n\n\t\tm_beliefs[v] = marg(cl.belief, VX);\n\t\tm_beliefs[v].normalize(); // normalize\n\t}\n}\n\n// Compute the joint marginal of a set of variables\nvoid cte::joint_marginal(const variable_set& scope) {\n\n\t// Find the shallowest cliques that contain the scope\n\tstd::vector<int> nodes;\n\tvariable_set temp = scope;\n\twhile (temp.size() > 0) {\n\t\tint max_id = -1, max_score = -1;\n\t\tstd::queue<detail::node*> bfs;\n\t\tbfs.push(m_root);\n\t\twhile (!bfs.empty()) {\n\t\t\tdetail::node* c = bfs.front();\n\t\t\tbfs.pop();\n\n\t\t\tint score = (c->clique & temp).size();\n\t\t\tif (score > 0 && score > max_score) {\n\t\t\t\tmax_score = score;\n\t\t\t\tmax_id = c->id;\n\t\t\t}\n\n\t\t\tfor (vector<detail::node*>::iterator it = c->children.begin();\n\t\t\t\t\tit != c->children.end(); ++it) {\n\t\t\t\tbfs.push(*it);\n\t\t\t}\n\t\t}\n\n\t\tassert(max_id >= 0);\n\t\tnodes.push_back(max_id);\n\t\ttemp = temp - (temp & m_clusters[max_id].clique);\n\t}\n\n\tif (m_debug) {\n\t\tstd::cout << \"[DEBUG] Found the shallowest nodes: \";\n\t\tstd::copy(nodes.begin(), nodes.end(),\n\t\t\t\tstd::ostream_iterator<int>(std::cout, \" \"));\n\t\tstd::cout << std::endl;\n\t}\n\n\t// Check if the scope is included in one clique\n\tif (nodes.size() == 1) { // one clique\n\t\tm_marginal = marg(m_clusters[nodes.at(0)].belief, scope);\n\t\tm_marginal.normalize();\n\t} else { // multiple cliques\n\n\t\t// Collect all relevant factors\n\t\tvector<factor> factors;\n\t\tfactors.push_back(m_root->belief);\n\t\tfor (size_t i = 0; i < nodes.size(); ++i) {\n\t\t\tdetail::node* c = &(m_clusters.at(nodes[i]));\n\t\t\twhile (c != NULL) {\n\t\t\t\tfor (vector<detail::edge*>::iterator ei = c->edges.begin();\n\t\t\t\t\t\tei != c->edges.end(); ++ei) {\n\t\t\t\t\tdetail::edge* e = (*ei);\n\t\t\t\t\tif (e->first->id == c->id) {\n\t\t\t\t\t\tfactor f = c->belief;\n\t\t\t\t\t\tf /= e->fwd;\n\t\t\t\t\t\tfactors.push_back(f);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tc = c->parent;\n\t\t\t\tif (c == m_root) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvariable_set all_vars, elim_vars;\n\t\tfor (vector<factor>::iterator fi = factors.begin();\n\t\t\t\tfi != factors.end(); ++fi) {\n\t\t\tall_vars |= fi->vars();\n\t\t}\n\t\telim_vars = (all_vars - scope);\n\n\t\t// Run variables elimination over these factors\n\t\tvariable_order_t order;\n\t\tfor (size_t i = 0; i < m_order.size(); ++i) {\n\t\t\tsize_t v = m_order[i];\n\t\t\tif (elim_vars.contains(m_gmo.var(v))) {\n\t\t\t\torder.push_back(v);\n\t\t\t}\n\t\t}\n\n\t\tif (m_debug) {\n\t\t\tstd::cout << \"[DEBUG] All vars: \" << all_vars << std::endl;\n\t\t\tstd::cout << \"[DEBUG] Scope: \" << scope << std::endl;\n\t\t\tstd::cout << \"[DEBUG] Elim: \" << elim_vars << std::endl;\n\t\t\tstd::cout << \"[DEBUG] Factors: \" << factors.size() << std::endl;\n\t\t\tstd::cout << \"[DEBUG] Elim order: \";\n\t\t\tstd::copy(order.begin(), order.end(),\n\t\t\t\t\tstd::ostream_iterator<size_t>(std::cout, \" \"));\n\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t\t// Run variable elimination\n\t\tfor (size_t i = 0; i < order.size(); ++i) {\n\t\t\tsize_t v = order[i];\n\t\t\tvariable VX = m_gmo.var(v);\n\n\t\t\t// Collect all factors mentioning VX\n\t\t\tfactor f(1.0);\n\t\t\tfor (vector<factor>::iterator it = factors.begin();\n\t\t\t\t\tit != factors.end();) {\n\t\t\t\tif (it->variables().contains(VX)) {\n\t\t\t\t\tf *= (*it);\n\t\t\t\t\tit = factors.erase(it);\n\t\t\t\t} else {\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Eliminate the variable\n\t\t\tf = elim(f, VX);\n\t\t\tfactors.push_back(f);\n\t\t}\n\n\t\t// Compute the joint marginal\n\t\tm_marginal = factor(1.0);\n\t\tfor (vector<factor>::iterator it = factors.begin();\n\t\t\t\tit != factors.end(); ++it) {\n\t\t\tm_marginal *= (*it);\n\t\t\tm_marginal.normalize();\n\t\t}\n\t}\n}\n\n// The scope must be included in one cluster (Bayes nets only)\nvoid cte::joint_marginal(const variable_set& scope, std::vector<int>& evidence) {\n\n\t// Get the cluster that contains the scope\n\tbool found = false;\n\tsize_t j = 0;\n\tfor (size_t i = 0; i < m_clusters.size(); ++i) {\n\t\tdetail::node& cl = m_clusters[i];\n\t\tvariable_set temp = (cl.clique & scope);\n\t\tif (temp == scope) {\n\t\t\tfound = true;\n\t\t\tj = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Safety check\n\tassert(found);\n\n\t// Compute the joint marginal (belief) subject to evidence\n\tm_marginal = factor(scope, 0.0);\n\tdetail::node& n = m_clusters[j];\n\tn.belief = n.theta.condition(evidence);\n\tfor (vector<detail::edge*>::iterator ei = n.edges.begin();\n\t\t\tei != n.edges.end(); ++ei) {\n\t\tdetail::edge* e = (*ei);\n\t\tif (e->second->id == n.id) {\n\t\t\tn.belief *= e->fwd;\n\t\t}\n\t\tif (e->first->id == n.id) {\n\t\t\tn.belief *= e->bwd;\n\t\t}\n\t}\n\n\t// Update the belief entries subject to evidence\n\tvariable_set v_rem;\n\tfor (variable_set::const_iterator vi = n.clique.begin();\n\t\t\tvi != n.clique.end(); ++vi) {\n\t\tif (!scope.contains(*vi) && evidence[vi->label()] < 0) {\n\t\t\tv_rem |= *vi;\n\t\t}\n\t}\n\tn.belief = n.belief.sum(v_rem);\n\n\tif (m_debug) {\n\t\tstd::cout << \"[DEBUG] Joint marginal scope: \" << m_marginal.vars() << std::endl;\n\t\tstd::cout << \"[DEBUG] Actual belief scope:  \" << n.belief << std::endl;\n\t}\n\n\t// Fill in all configurations of the marginal (including the evidence)\n\tindex_config cv1(m_marginal.vars(), true);\n\tconfig_index cv2(n.belief.vars(), true);\n\tfor (size_t i = 0; i < m_marginal.num_states(); ++i) {\n\t\tstd::map<size_t, size_t> config = cv1.convert(i);\n\t\tif (is_compatible(config, evidence)) {\n\t\t\tsize_t j = cv2.convert(config);\n\t\t\tdouble v = n.belief.get(j);\n\t\t\tm_marginal.set(i, v);\n\t\t} else {\n\t\t\tm_marginal.set(i, 0.0);\n\t\t}\n\t}\n\n\t// Normalize by P(evidence)\n\tm_marginal /= std::exp(m_logz);\n\n\tif (m_debug) {\n\t\tstd::cout << \"[DEBUG] Joint marginal: \" << m_marginal << std::endl;\n\t}\n}\n\n// Check if a variable configuration is compatible with the evidence vector\nbool cte::is_compatible(std::map<size_t, size_t>& config,\n\t\tstd::vector<int>& evidence) {\n\tbool ok = true;\n\tfor (std::map<size_t, size_t>::iterator mi = config.begin();\n\t\t\tmi != config.end(); ++mi) {\n\t\tsize_t var = mi->first;\n\t\tsize_t val = mi->second;\n\t\tif (evidence[var] < 0) {\n\t\t\tcontinue; // skip non-evidence variable\n\t\t} else {\n\t\t\tif (val != evidence[var]) {\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ok;\n}\n\n// Run the clique-tree algorithm with evidence (for EM learning)\n// Returns *true* if P(evidence) > 0, and *false* otherwise\nbool cte::propagate_evidence(std::vector<int>& evidence) {\n\n\t// Save the current evidence\n\tif (m_debug) {\n\t\tstd::cout << \"[CTE] Propagate evidence: \";\n\t\tstd::copy(evidence.begin(), evidence.end(), std::ostream_iterator<int>(std::cout, \" \"));\n\t\tstd::cout << std::endl;\n\t}\n\n\tm_evidence = evidence;\n\tforward(evidence);\n\tbackward(evidence);\n\n\t// Compute the posterior marginals for all variables (evidence, non-evidence)\n\tfor (size_t i = 0; i < m_clusters.size(); ++i) {\n\t\tdetail::node& cl = m_clusters[i];\n\t\tcl.belief = cl.theta.condition(evidence);\n\t\tfor (vector<detail::edge*>::iterator ei = cl.edges.begin();\n\t\t\t\tei != cl.edges.end(); ++ei) {\n\t\t\tdetail::edge* e = (*ei);\n\t\t\tif (e->second->id == cl.id) {\n\t\t\t\tcl.belief *= e->fwd;\n\t\t\t}\n\t\t\tif (e->first->id == cl.id) {\n\t\t\t\tcl.belief *= e->bwd;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compute the root clique belief (to get log partition function)\n\tm_root->belief = m_root->theta.condition(evidence);\n\tfor (vector<detail::edge*>::iterator ei = m_root->edges.begin();\n\t\tei != m_root->edges.end(); ++ei) {\n\t\tdetail::edge* e = (*ei);\n\t\tif (e->second->id == m_root->id) {\n\t\t\tm_root->belief *= e->fwd;\n\t\t}\n\t\tif (e->first->id == m_root->id) {\n\t\t\tm_root->belief *= e->bwd;\n\t\t}\n\t}\n\n\t// Compute the probability of evidence\n\tbool result = true;\n\tfactor::value pe = m_root->belief.sum();\n\tif (pe == 0.0) {\n\t\tresult = false;\n\t}\n\n\t// Update the log partition function\n\tm_logz = std::log(m_root->belief.sum());\n\n\t// Compute the marginals\n\tfor (size_t v = 0; v < m_var2clique.size(); ++v) {\n\t\tsize_t ci = m_var2clique[v];\n\t\tdetail::node& cl = m_clusters[ci];\n\t\tvariable VX = m_gmo.var(v);\n\n\t\tif (evidence[v] >= 0) {\n\t\t\tfactor tmp(variable_set(VX), 0.0);\n\t\t\ttmp.set(evidence[v], 1.0);\n\t\t\tm_beliefs[v] = tmp;\n\t\t} else {\n\t\t\tm_beliefs[v] = marg(cl.belief, VX);\n\t\t\tm_beliefs[v].normalize(); // normalize\n\t\t}\n\t}\n\n\tif (m_debug) {\n\t\tstd::cout << \"[CTE] Finished propagating evidence with logZ = \"\n\t\t\t\t<< m_logz << \" (\" << std::exp(m_logz) << \")\" << std::endl;\n\t\tstd::cout << \"[CTE] Posterior marginals:\" << std::endl;\n\t\tfor (size_t i = 0; i < m_beliefs.size(); ++i) {\n\t\t\tstd::cout << \" \" << m_beliefs[i] << std::endl;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/// Run the clique-tree elimination algorithm.\nvoid cte::run() {\n\n\t// Start the timer and store it\n\tm_start_time = timeSystem();\n\n\tinit();\n\tcalibrate();\n\tupdate();\n\tif (!m_query.empty()) {\n\t\tvariable_set scope;\n\t\tfor (size_t i = 0; i < m_query.size(); ++i) {\n\t\t\tscope |= m_gmo.var(m_query[i]);\n\t\t}\n\n\t\tjoint_marginal(scope);\n\t}\n\n\t// Output solution (UAI output format)\n\tif (m_verbose > 0) {\n\t\tstd::cout << \"[CTE] Finished in \" << (timeSystem() - m_start_time)\n\t\t\t<< \" seconds\" << std::endl;\n\t}\n\n\t// Compute the joint marginal given in query\n\n\tswitch (m_task) {\n\tcase Task::PR:\t// partition function\n\t\t{\n\t\t\tstd::cout << \"PR\" << std::endl;\n\t\t\tstd::cout << std::fixed << std::setprecision(MERLIN_PRECISION)\n\t\t\t\t<< m_logz << \" (\" << std::scientific\n\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t<< std::exp(m_logz) << \")\" << std::endl;\n\n\t\t\tif (isinf(m_logz)) {\n\t\t\t\tstd::cout << \"STATUS\" << std::endl;\n\t\t\t\tstd::cout << \"false: Inconsistent evidence or underflow\" << std::endl;\n\t\t\t} else {\n\t\t\t\tstd::cout << \"STATUS\" << std::endl;\n\t\t\t\tstd::cout << \"true: Consistent evidence\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\tcase Task::MAR:\t// marginals\n\t\t{\n\t\t\tstd::cout << \"PR\" << std::endl;\n\t\t\tstd::cout << std::fixed << std::setprecision(MERLIN_PRECISION)\n\t\t\t\t<< m_logz << \" (\" << std::scientific\n\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t<< std::exp(m_logz) << \")\" << std::endl;\n\n\t\t\tif (isinf(m_logz)) {\n\t\t\t\tstd::cout << \"STATUS\" << std::endl;\n\t\t\t\tstd::cout << \"false: Inconsistent evidence or underflow\" << std::endl;\n\t\t\t} else {\n\t\t\t\tstd::cout << \"STATUS\" << std::endl;\n\t\t\t\tstd::cout << \"true: Consistent evidence\" << std::endl;\n\t\t\t}\n\n\t\t\tstd::cout << \"MAR\" << std::endl;\n\t\t\tstd::cout << m_gmo.nvar();\n\t\t\tfor (vindex v = 0; v < m_gmo.nvar(); ++v) {\n\t\t\t\tvariable VX = m_gmo.var(v);\n\t\t\t\tstd::cout << \" \" << VX.states();\n\t\t\t\tfor (size_t k = 0; k < VX.states(); ++k) {\n\t\t\t\t\tstd::cout << \" \" << std::fixed\n\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t<< belief(VX)[k];\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t\tif (!m_query.empty()) {\n\t\t\t\tvariable_set scope = m_marginal.variables();\n\t\t\t\tstd::cout << \"JOINT_MAR : \" << scope << std::endl;\n\t\t\t\tstd::vector<size_t> dims(scope.size());\n\t\t\t\tsize_t j = 0;\n\t\t\t\tfor (variable_set::const_iterator si = scope.begin(); si != scope.end(); ++si) {\n\t\t\t\t\tdims[j++] = (*si).states();\n\t\t\t\t}\n\n\t\t\t\tfor (size_t index = 0; index < m_marginal.numel(); ++index) {\n\t\t\t\t\tstd::vector<size_t> I(dims.size(), 0); // configuration of source variables\n\t\t\t\t\tsize_t i = index;\n\t\t\t\t\tfor (size_t v = 0; v < dims.size(); ++v) {\n\t\t\t\t\t\tI[v] = i % dims[v];\n\t\t\t\t\t\ti -= I[v];\n\t\t\t\t\t\ti /= dims[v];\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (size_t j = 0; j < I.size(); ++j) {\n\t\t\t\t\t\tstd::cout << I[j] << \" \";\n\t\t\t\t\t}\n\t\t\t\t\tstd::cout << \": \" << std::fixed\n\t\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t\t<< m_marginal[index]\n\t\t\t\t\t\t\t<< std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\tdefault:\n\t\tbreak;\n\t}\n}\n\n/// Write the solution to the output stream\nvoid cte::write_solution(std::ostream& out, const std::map<size_t, size_t>& evidence,\n\t\tconst std::map<size_t, size_t>& old2new, const graphical_model& orig,\n\t\tconst std::set<size_t>& dummies, int output_format) {\n\n\tif (output_format == MERLIN_OUTPUT_JSON) {\n\t\tout << \"{\";\n\t\tout << \" \\\"algorithm\\\" : \\\"cte\\\", \";\n\t\tswitch (m_task) {\n\t\tcase Task::PR:\n\t\t\t{\n\t\t\t\tdouble val = m_logz + std::log(orig.get_global_const());\n\t\t\t\tdouble prob = std::exp(val);\n\n\t\t\t\tout << \" \\\"task\\\" : \\\"PR\\\", \";\n\t\t\t\tout << \" \\\"value\\\" : \" << std::fixed\n\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t<< (m_logz + std::log(orig.get_global_const())) << \", \";\n\t\t\t\tif (prob == 0.0) { // probability of evidence is 0\n\t\t\t\t\tout << \" \\\"status\\\" : \\\"false\\\", \";\n\t\t\t\t\tout << \" \\\"message\\\" : \\\"Inconsistent evidence or underflow\\\" \";\n\t\t\t\t} else {\n\t\t\t\t\tout << \" \\\"status\\\" : \\\"true\\\", \";\n\t\t\t\t\tout << \" \\\"message\\\" : \\\"Consistent evidence\\\" \";\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase Task::MAR:\n\t\t\t{\n\t\t\t\tdouble val = m_logz + std::log(orig.get_global_const());\n\t\t\t\tdouble prob = std::exp(val);\n\n\t\t\t\tout << \" \\\"task\\\" : \\\"MAR\\\", \";\n\t\t\t\tout << \" \\\"value\\\" : \" << std::fixed\n\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t<< (m_logz + std::log(orig.get_global_const())) << \", \";\n\n\t\t\t\tif (prob == 0.0) { // probability of evidence is 0\n\t\t\t\t\tout << \" \\\"status\\\" : \\\"false\\\", \";\n\t\t\t\t\tout << \" \\\"message\\\" : \\\"Inconsistent evidence or underflow\\\", \";\n\t\t\t\t\tout << \" \\\"marginals\\\" : [] \";\n\t\t\t\t} else {\n\t\t\t\t\tout << \" \\\"status\\\" : \\\"true\\\", \";\n\t\t\t\t\tout << \" \\\"message\\\" : \\\"Consistent evidence\\\", \";\n\t\t\t\t\tout << \" \\\"marginals\\\" : [ \";\n\n\t\t\t\t\tfor (vindex i = 0; i < orig.nvar(); ++i) {\n\t\t\t\t\t\tif (dummies.find(i) != dummies.end()) {\n\t\t\t\t\t\t\tcontinue; // skip dummy variables from output\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvariable v = orig.var(i);\n\t\t\t\t\t\tout << \"{\";\n\t\t\t\t\t\tout << \" \\\"variable\\\" : \" << v.label() << \", \";\n\t\t\t\t\t\tout << \" \\\"states\\\" : \" << v.states() << \", \";\n\t\t\t\t\t\tout << \" \\\"probabilities\\\" : [\";\n\t\t\t\t\t\ttry { // evidence variable\n\t\t\t\t\t\t\tsize_t val = evidence.at(i);\n\t\t\t\t\t\t\tfor (size_t k = 0; k < v.states(); ++k) {\n\t\t\t\t\t\t\t\tout << std::fixed\n\t\t\t\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t\t\t\t<< (k == val ? 1.0 : 0.0);\n\t\t\t\t\t\t\t\tif (k != v.states() - 1) {\n\t\t\t\t\t\t\t\t\tout << \", \";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tout << \"] \";\n\t\t\t\t\t\t} catch(std::out_of_range& e) { // non-evidence variable\n\t\t\t\t\t\t\tvindex vx = old2new.at(i);\n\t\t\t\t\t\t\tvariable VX = var(vx);\n\t\t\t\t\t\t\tfor (size_t k = 0; k < VX.states(); ++k) {\n\t\t\t\t\t\t\t\tout << std::fixed\n\t\t\t\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t\t\t\t<< belief(VX)[k];\n\t\t\t\t\t\t\t\tif (k != VX.states() - 1) {\n\t\t\t\t\t\t\t\t\tout << \", \";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tout << \"] \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tout << \"}\";\n\t\t\t\t\t\tif (i != orig.nvar() - 1) {\n\t\t\t\t\t\t\tout << \", \";\n\t\t\t\t\t\t}\n\t\t\t\t\t} // end for\n\t\t\t\t\tout << \"] \";\n\n\t\t\t\t\tif (!m_query.empty()) {\n\t\t\t\t\t\tout << \", \";\n\t\t\t\t\t\tout << \"\\\"joint_marginal\\\" : {\";\n\t\t\t\t\t\tvariable_set scope = m_marginal.variables();\n\t\t\t\t\t\tout << \"\\\"scope\\\" : [\";\n\t\t\t\t\t\tfor (size_t i = 0; i < m_query.size(); ++i) {\n\t\t\t\t\t\t\tout << m_query[i];\n\t\t\t\t\t\t\tif (i < m_query.size() - 1) {\n\t\t\t\t\t\t\t\tout << \",\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tout << \"], \" << std::endl;\n\t\t\t\t\t\tout << \"\\\"probabilities\\\" : [\";\n\n\t\t\t\t\t\tstd::vector<size_t> dims(scope.size());\n\t\t\t\t\t\tsize_t j = 0;\n\t\t\t\t\t\tfor (variable_set::const_iterator si = scope.begin();\n\t\t\t\t\t\t\t\tsi != scope.end(); ++si) {\n\t\t\t\t\t\t\tdims[j++] = (*si).states();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsize_t N = m_marginal.numel();\n\t\t\t\t\t\tfor (size_t index = 0; index < N; ++index) {\n\t\t\t\t\t\t\tstd::vector<size_t> I(dims.size(), 0); // configuration of source variables\n\t\t\t\t\t\t\tsize_t i = index;\n\t\t\t\t\t\t\tfor (size_t v = 0; v < dims.size(); ++v) {\n\t\t\t\t\t\t\t\tI[v] = i % dims[v];\n\t\t\t\t\t\t\t\ti -= I[v];\n\t\t\t\t\t\t\t\ti /= dims[v];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tout << \"{\\\"config\\\" : [\";\n\t\t\t\t\t\t\tfor (size_t j = 0; j < I.size(); ++j) {\n\t\t\t\t\t\t\t\tout << I[j];\n\t\t\t\t\t\t\t\tif (j < I.size() - 1) {\n\t\t\t\t\t\t\t\t\tout << \",\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tout << \"], \";\n\t\t\t\t\t\t\tout << \"\\\"value\\\" : \" << std::fixed\n\t\t\t\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t\t\t\t<< m_marginal[index]\n\t\t\t\t\t\t\t\t\t<< \"}\";\n\t\t\t\t\t\t\tif (index < N - 1) {\n\t\t\t\t\t\t\t\tout << \", \";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tout << \"]}\";\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tout << \"}\";\n\t} else if (output_format == MERLIN_OUTPUT_UAI) {\n\t\tswitch (m_task) {\n\t\tcase Task::PR:\n\t\tcase Task::MAR:\n\t\t\t{\n\t\t\t\tdouble val = m_logz + std::log(orig.get_global_const());\n\t\t\t\tdouble prob = std::exp(val);\n\n\t\t\t\tout << \"PR\" << std::endl;\n\t\t\t\tout << std::fixed << std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t<< (m_logz + std::log(orig.get_global_const())) << \" (\"\n\t\t\t\t\t<< std::scientific << std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t<< std::exp(m_logz + std::log(orig.get_global_const()))\n\t\t\t\t\t<< \")\" << std::endl;\n\n\t\t\t\tif (prob == 0.0) {\n\t\t\t\t\tout << \"STATUS\" << std::endl;\n\t\t\t\t\tout << \"false: Inconsistent evidence or underflow\" << std::endl;\n\t\t\t\t} else {\n\t\t\t\t\tout << \"STATUS\" << std::endl;\n\t\t\t\t\tout << \"true: Consistent evidence\" << std::endl;\n\t\t\t\t}\n\n\t\t\t\tout << \"MAR\" << std::endl;\n\t\t\t\tout << orig.nvar() - dummies.size();\n\t\t\t\tfor (vindex i = 0; i < orig.nvar(); ++i) {\n\t\t\t\t\tif (dummies.find(i) != dummies.end()) {\n\t\t\t\t\t\tcontinue; // skip dummy variables from output\n\t\t\t\t\t}\n\n\t\t\t\t\tvariable v = orig.var(i);\n\t\t\t\t\ttry { // evidence variable\n\t\t\t\t\t\tsize_t val = evidence.at(i);\n\t\t\t\t\t\tout << \" \" << v.states();\n\t\t\t\t\t\tfor (size_t k = 0; k < v.states(); ++k) {\n\t\t\t\t\t\t\tout << \" \" << std::fixed\n\t\t\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t\t\t<< (k == val ? 1.0 : 0.0);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch(std::out_of_range& e) { // non-evidence variable\n\t\t\t\t\t\tvindex vx = old2new.at(i);\n\t\t\t\t\t\tvariable VX = var(vx);\n\t\t\t\t\t\tout << \" \" << VX.states();\n\t\t\t\t\t\tfor (size_t k = 0; k < VX.states(); ++k) {\n\t\t\t\t\t\t\tout << \" \" << std::fixed\n\t\t\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t\t\t<< belief(VX)[k];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} // end for\n\t\t\t\tout << std::endl;\n\n\t\t\t\tif (!m_query.empty()) {\n\t\t\t\t\tvariable_set scope = m_marginal.variables();\n\t\t\t\t\tout << \"JOINT_MAR : [\";\n\t\t\t\t\tfor (size_t i = 0; i < m_query.size(); ++i) {\n\t\t\t\t\t\tout << m_query[i];\n\t\t\t\t\t\tif (i < m_query.size() - 1) {\n\t\t\t\t\t\t\tout << \",\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tout << \"]\" << std::endl;\n\n\t\t\t\t\tstd::vector<size_t> dims(scope.size());\n\t\t\t\t\tsize_t j = 0;\n\t\t\t\t\tfor (variable_set::const_iterator si = scope.begin();\n\t\t\t\t\t\t\tsi != scope.end(); ++si) {\n\t\t\t\t\t\tdims[j++] = (*si).states();\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (size_t index = 0; index < m_marginal.numel(); ++index) {\n\t\t\t\t\t\tstd::vector<size_t> I(dims.size(), 0); // configuration of source variables\n\t\t\t\t\t\tsize_t i = index;\n\t\t\t\t\t\tfor (size_t v = 0; v < dims.size(); ++v) {\n\t\t\t\t\t\t\tI[v] = i % dims[v];\n\t\t\t\t\t\t\ti -= I[v];\n\t\t\t\t\t\t\ti /= dims[v];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (size_t j = 0; j < I.size(); ++j) {\n\t\t\t\t\t\t\tout << I[j] << \" \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tout << \": \" << std::fixed\n\t\t\t\t\t\t\t\t<< std::setprecision(MERLIN_PRECISION)\n\t\t\t\t\t\t\t\t<< m_marginal[index]\n\t\t\t\t\t\t\t\t<< std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t} else {\n\t\tstd::string err_msg(\"Unknown output format.\");\n\t\tthrow std::runtime_error(err_msg);\n\t}\n}\n\n\n} // namespace\n\n", "meta": {"hexsha": "ba170cf3376462f7375e68ae114b629f39f4cee0", "size": 35281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cte.cpp", "max_stars_repo_name": "Nedriano/merlin", "max_stars_repo_head_hexsha": "008d910307a2043f9446676f28010079ea49ec15", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T01:38:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T01:38:40.000Z", "max_issues_repo_path": "src/cte.cpp", "max_issues_repo_name": "Nedriano/merlin", "max_issues_repo_head_hexsha": "008d910307a2043f9446676f28010079ea49ec15", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cte.cpp", "max_forks_repo_name": "Nedriano/merlin", "max_forks_repo_head_hexsha": "008d910307a2043f9446676f28010079ea49ec15", "max_forks_repo_licenses": ["BSD-3-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.244015444, "max_line_length": 105, "alphanum_fraction": 0.5750120461, "num_tokens": 10980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.05749327435934956, "lm_q1q2_score": 0.022129858715733426}}
{"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 <third_party/align_point_clouds.h>\n\n#include <glog/logging.h>\n#include <Eigen/Dense>\n\nnamespace theia {\n\nvoid AlignPointCloudsUmeyama(const std::vector<Eigen::Vector3d>& left,\n                             const std::vector<Eigen::Vector3d>& right,\n                             Eigen::Matrix3d* rotation,\n                             Eigen::Vector3d* translation, double* scale) {\n  std::vector<double> weights(left.size(), 1.0);\n  AlignPointCloudsUmeyamaWithWeights(left, right, weights, rotation,\n                                     translation, scale);\n}\n\nvoid AlignPointCloudsUmeyamaWithWeights(\n    const std::vector<Eigen::Vector3d>& left,\n    const std::vector<Eigen::Vector3d>& right,\n    const std::vector<double>& weights, Eigen::Matrix3d* rotation,\n    Eigen::Vector3d* translation, double* scale) {\n  CHECK_EQ(left.size(), right.size());\n  CHECK_EQ(left.size(), weights.size());\n  CHECK_NOTNULL(rotation);\n  CHECK_NOTNULL(translation);\n  CHECK_NOTNULL(scale);\n\n  // Fill outputs (useful when it fails)\n  *scale = 1.0;\n  *translation = Eigen::Vector3d::Zero();\n  *rotation = Eigen::Matrix3d::Identity();\n\n  const size_t num_points = left.size();\n  Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic> > left_points(\n      left[0].data(), 3, num_points);\n  Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic> > right_points(\n      right[0].data(), 3, num_points);\n\n  Eigen::Vector3d left_centroid, right_centroid;\n  left_centroid.setZero();\n  right_centroid.setZero();\n  double weights_sum = 0.0;\n  for (size_t i = 0; i < num_points; i++) {\n    CHECK_GE(weights[i], 0)\n        << \"The point weight must be greater or equal to zero.\";\n    weights_sum += weights[i];\n    left_centroid += left[i] * weights[i];\n    right_centroid += right[i] * weights[i];\n  }\n  // Check if the sum is valid\n  CHECK_GT(weights_sum, 0) << \"The sum of weights must be greater than zero.\";\n\n  left_centroid /= weights_sum;\n  right_centroid /= weights_sum;\n\n  double sigma = 0.0;\n  for (size_t i = 0; i < num_points; i++) {\n    sigma += (left[i] - left_centroid).squaredNorm() * weights[i];\n  }\n  sigma /= weights_sum;\n\n  // Calculate cross correlation matrix based on the points shifted about the\n  // centroid.\n  Eigen::Matrix3d cross_correlation = Eigen::Matrix3d::Zero();\n  for (int i = 0; i < num_points; i++) {\n    cross_correlation += weights[i] * (left_points.col(i) - left_centroid) *\n                         (right_points.col(i) - right_centroid).transpose();\n  }\n  cross_correlation /= weights_sum;\n\n  // Compute SVD decomposition of the cross correlation.\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(\n      cross_correlation.transpose(), Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n  const Eigen::Matrix3d& umatrix = svd.matrixU();\n  const Eigen::Matrix3d& vtmatrix = svd.matrixV().transpose();\n  const Eigen::Vector3d& singular_values = svd.singularValues();\n\n  const double det = umatrix.determinant() * vtmatrix.determinant();\n  Eigen::Matrix3d s = Eigen::Matrix3d::Identity();\n  s(2, 2) = det > 0 ? 1 : -1;\n\n  *scale =\n      (singular_values(0) + singular_values(1) + s(2, 2) * singular_values(2)) /\n      sigma;\n  *rotation = umatrix * s * vtmatrix;\n  *translation = right_centroid - (*scale) * (*rotation) * left_centroid;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "03d3ccca667ee35f6e40f3dd124ea45d4f76fa71", "size": 5069, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/third_party/align_point_clouds.cc", "max_stars_repo_name": "vfragoso/gp4pc", "max_stars_repo_head_hexsha": "6a3f66f2485f1f7b1e93b073ee65772dfda9c7b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T02:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T12:53:43.000Z", "max_issues_repo_path": "src/third_party/align_point_clouds.cc", "max_issues_repo_name": "vfragoso/gp4pc", "max_issues_repo_head_hexsha": "6a3f66f2485f1f7b1e93b073ee65772dfda9c7b3", "max_issues_repo_licenses": ["MIT"], "max_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/align_point_clouds.cc", "max_forks_repo_name": "vfragoso/gp4pc", "max_forks_repo_head_hexsha": "6a3f66f2485f1f7b1e93b073ee65772dfda9c7b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-14T12:52:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T15:23:46.000Z", "avg_line_length": 40.552, "max_line_length": 80, "alphanum_fraction": 0.6900769383, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04603389978171545, "lm_q1q2_score": 0.022118307312508478}}
{"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#ifndef ATCODER_FENWICKTREE_HPP\n#define ATCODER_FENWICKTREE_HPP 1\n\n#include <cassert>\n#include <type_traits>\n#include <vector>\n\nnamespace atcoder {\n\nnamespace internal {\n\n#ifndef _MSC_VER\ntemplate <class T>\nusing is_signed_int128 =\n\ttypename std::conditional<std::is_same<T, __int128_t>::value ||\n\t\t\t\t\t\t\t\t  std::is_same<T, __int128>::value,\n\t\t\t\t\t\t\t  std::true_type,\n\t\t\t\t\t\t\t  std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int128 =\n\ttypename std::conditional<std::is_same<T, __uint128_t>::value ||\n\t\t\t\t\t\t\t\t  std::is_same<T, unsigned __int128>::value,\n\t\t\t\t\t\t\t  std::true_type,\n\t\t\t\t\t\t\t  std::false_type>::type;\n\ntemplate <class T>\nusing make_unsigned_int128 =\n\ttypename std::conditional<std::is_same<T, __int128_t>::value,\n\t\t\t\t\t\t\t  __uint128_t,\n\t\t\t\t\t\t\t  unsigned __int128>;\n\ntemplate <class T>\nusing is_integral = typename std::conditional<std::is_integral<T>::value ||\n\t\t\t\t\t\t\t\t\t\t\t\t  is_signed_int128<T>::value ||\n\t\t\t\t\t\t\t\t\t\t\t\t  is_unsigned_int128<T>::value,\n\t\t\t\t\t\t\t\t\t\t\t  std::true_type,\n\t\t\t\t\t\t\t\t\t\t\t  std::false_type>::type;\n\ntemplate <class T>\nusing is_signed_int = typename std::conditional<(is_integral<T>::value &&\n\t\t\t\t\t\t\t\t\t\t\t\t std::is_signed<T>::value) ||\n\t\t\t\t\t\t\t\t\t\t\t\t\tis_signed_int128<T>::value,\n\t\t\t\t\t\t\t\t\t\t\t\tstd::true_type,\n\t\t\t\t\t\t\t\t\t\t\t\tstd::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n\ttypename std::conditional<(is_integral<T>::value &&\n\t\t\t\t\t\t\t   std::is_unsigned<T>::value) ||\n\t\t\t\t\t\t\t\t  is_unsigned_int128<T>::value,\n\t\t\t\t\t\t\t  std::true_type,\n\t\t\t\t\t\t\t  std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<\n\tis_signed_int128<T>::value,\n\tmake_unsigned_int128<T>,\n\ttypename std::conditional<std::is_signed<T>::value,\n\t\t\t\t\t\t\t  std::make_unsigned<T>,\n\t\t\t\t\t\t\t  std::common_type<T>>::type>::type;\n\n#else\n\ntemplate <class T>\nusing is_integral = typename std::is_integral<T>;\n\ntemplate <class T>\nusing is_signed_int =\n\ttypename std::conditional<is_integral<T>::value && std::is_signed<T>::value,\n\t\t\t\t\t\t\t  std::true_type,\n\t\t\t\t\t\t\t  std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n\ttypename std::conditional<is_integral<T>::value &&\n\t\t\t\t\t\t\t\t  std::is_unsigned<T>::value,\n\t\t\t\t\t\t\t  std::true_type,\n\t\t\t\t\t\t\t  std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<is_signed_int<T>::value,\n\t\t\t\t\t\t\t\t\t\t\t  std::make_unsigned<T>,\n\t\t\t\t\t\t\t\t\t\t\t  std::common_type<T>>::type;\n\n#endif\n\ntemplate <class T>\nusing is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;\n\ntemplate <class T>\nusing is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;\n\ntemplate <class T>\nusing to_unsigned_t = typename to_unsigned<T>::type;\n\n} // namespace internal\n\n// Reference: https://en.wikipedia.org/wiki/Fenwick_tree\ntemplate <class T>\nstruct fenwick_tree {\n\tusing U = internal::to_unsigned_t<T>;\n\n\tpublic:\n\tfenwick_tree() : _n(0) {}\n\tfenwick_tree(int n) : _n(n), data(n) {}\n\n\tvoid add(int p, T x) {\n\t\tassert(0 <= p && p < _n);\n\t\tp++;\n\t\twhile(p <= _n) {\n\t\t\tdata[p - 1] += U(x);\n\t\t\tp += p & -p;\n\t\t}\n\t}\n\n\tT sum(int l, int r) {\n\t\tassert(0 <= l && l <= r && r <= _n);\n\t\treturn sum(r) - sum(l);\n\t}\n\n\tprivate:\n\tint _n;\n\tstd::vector<U> data;\n\n\tU sum(int r) {\n\t\tU s = 0;\n\t\twhile(r > 0) {\n\t\t\ts += data[r - 1];\n\t\t\tr -= r & -r;\n\t\t}\n\t\treturn s;\n\t}\n};\n\n} // namespace atcoder\n\n#endif // ATCODER_FENWICKTREE_HPP\n\nusing namespace atcoder;\nint main() {\n\tint n;\n\tcin >> n;\n\tVI a(n);\n\tEACH(e, a) { cin >> e; }\n\n\tauto fw = fenwick_tree<ll>(n + 1);\n\tll inv_sum = 0;\n\tfor(int i = n - 1; i >= 0; i--) {\n\t\tfw.add(a[i], 1);\n\t\tinv_sum += fw.sum(0, a[i]);\n\t}\n\n\tREP(i, n) {\n\t\tcout << inv_sum << endl;\n\t\tinv_sum -= a[i];\n\t\tinv_sum += n - a[i] - 1;\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "3e795395e65d5bc70432e33213800de5a2bac48f", "size": 6244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC190/F.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/ABC190/F.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/ABC190/F.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.1259259259, "max_line_length": 77, "alphanum_fraction": 0.6385329917, "num_tokens": 1815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.396068180531364, "lm_q2_score": 0.05582313838573451, "lm_q1q2_score": 0.022109768851988412}}
{"text": "// Copyright (C) 2018  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n#include \"opaque_types.h\"\r\n#include <dlib/python.h>\r\n#include \"dlib/pixel.h\"\r\n#include <dlib/image_transforms.h>\r\n#include <dlib/image_processing.h>\r\n\r\nusing namespace dlib;\r\nusing namespace std;\r\n\r\nnamespace py = pybind11;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\ntemplate <typename T>\r\nnumpy_image<T> py_resize_image (\r\n    const numpy_image<T>& img,\r\n    unsigned long rows,\r\n    unsigned long cols\r\n)\r\n{\r\n    numpy_image<T> out;\r\n    set_image_size(out, rows, cols);\r\n    resize_image(img, out);\r\n    return out;\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\ntemplate <typename T>\r\nnumpy_image<T> py_equalize_histogram (\r\n    const numpy_image<T>& img\r\n)\r\n{\r\n    numpy_image<T> out;\r\n    equalize_histogram(img,out);\r\n    return out;\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nclass py_hough_transform\r\n{\r\npublic:\r\n\r\n    py_hough_transform(\r\n        unsigned long size\r\n    ) : ht(size) \r\n    {\r\n        DLIB_CASSERT(size > 0);\r\n    }\r\n\r\n    unsigned long size(\r\n    ) const { return ht.size(); }\r\n\r\n    long nr(\r\n    ) const { return ht.nr(); }\r\n\r\n    long nc(\r\n    ) const { return ht.nc(); }\r\n\r\n    line get_line (\r\n        const point& p\r\n    ) const \r\n    { \r\n        DLIB_CASSERT(rectangle(0,0,size()-1,size()-1).contains(p));\r\n        auto temp = ht.get_line(p); \r\n        return line(temp.first, temp.second);\r\n    }\r\n\r\n    double get_line_angle_in_degrees (\r\n        const point& p \r\n    ) const \r\n    { \r\n        DLIB_CASSERT(rectangle(0,0,size()-1,size()-1).contains(p));\r\n        return ht.get_line_angle_in_degrees(p); \r\n    }\r\n\r\n    py::tuple get_line_properties (\r\n        const point& p\r\n    ) const \r\n    { \r\n        DLIB_CASSERT(rectangle(0,0,size()-1,size()-1).contains(p));\r\n        double angle_in_degrees;\r\n        double radius;\r\n        ht.get_line_properties(p, angle_in_degrees, radius);\r\n        return py::make_tuple(angle_in_degrees, radius);\r\n    }\r\n\r\n    point get_best_hough_point (\r\n        const point& p,\r\n        const numpy_image<float>& himg\r\n    ) \r\n    { \r\n        DLIB_ASSERT(himg.nr() == size() && himg.nc() == size() &&\r\n            rectangle(0,0,size()-1,size()-1).contains(p) == true,\r\n            \"\\t point hough_transform::get_best_hough_point()\"\r\n            << \"\\n\\t Invalid arguments given to this function.\"\r\n            << \"\\n\\t himg.nr(): \" << himg.nr()\r\n            << \"\\n\\t himg.nc(): \" << himg.nc()\r\n            << \"\\n\\t size():    \" << size()\r\n            << \"\\n\\t p:         \" << p \r\n        );\r\n        return ht.get_best_hough_point(p,himg); \r\n    }\r\n\r\n    template <\r\n        typename T \r\n        >\r\n    numpy_image<float> compute_ht (\r\n        const numpy_image<T>& img,\r\n        const rectangle& box\r\n    ) const\r\n    {\r\n        numpy_image<float> out;\r\n        ht(img, box, out);\r\n        return out;\r\n    }\r\n\r\n    template <\r\n        typename T \r\n        >\r\n    numpy_image<float> compute_ht2 (\r\n        const numpy_image<T>& img\r\n    ) const\r\n    {\r\n        numpy_image<float> out;\r\n        ht(img, out);\r\n        return out;\r\n    }\r\n\r\n    template <\r\n        typename T \r\n        >\r\n    py::list find_pixels_voting_for_lines (\r\n        const numpy_image<T>& img,\r\n        const rectangle& box,\r\n        const std::vector<point>& hough_points,\r\n        const unsigned long angle_window_size = 1,\r\n        const unsigned long radius_window_size = 1\r\n    ) const\r\n    {\r\n        return vector_to_python_list(ht.find_pixels_voting_for_lines(img, box, hough_points, angle_window_size, radius_window_size));\r\n    }\r\n\r\n    template <\r\n        typename T \r\n        >\r\n    py::list find_pixels_voting_for_lines2 (\r\n        const numpy_image<T>& img,\r\n        const std::vector<point>& hough_points,\r\n        const unsigned long angle_window_size = 1,\r\n        const unsigned long radius_window_size = 1\r\n    ) const\r\n    {\r\n        return vector_to_python_list(ht.find_pixels_voting_for_lines(img, hough_points, angle_window_size, radius_window_size));\r\n    }\r\n\r\n    std::vector<point> find_strong_hough_points(\r\n        const numpy_image<float>& himg,\r\n        const float hough_count_threshold,\r\n        const double angle_nms_thresh,\r\n        const double radius_nms_thresh\r\n    )\r\n    {\r\n        return ht.find_strong_hough_points(himg, hough_count_threshold, angle_nms_thresh, radius_nms_thresh);\r\n    }\r\n\r\nprivate:\r\n    hough_transform ht;\r\n};\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid register_hough_transform(py::module& m)\r\n{\r\n    const char* class_docs =\r\n\"This object is a tool for computing the line finding version of the Hough transform \\n\\\r\ngiven some kind of edge detection image as input.  It also allows the edge pixels \\n\\\r\nto be weighted such that higher weighted edge pixels contribute correspondingly \\n\\\r\nmore to the output of the Hough transform, allowing stronger edges to create \\n\\\r\ncorrespondingly stronger line detections in the final Hough transform.\";\r\n\r\n\r\n    const char* doc_constr = \r\n\"requires \\n\\\r\n    - size_ > 0 \\n\\\r\nensures \\n\\\r\n    - This object will compute Hough transforms that are size_ by size_ pixels.   \\n\\\r\n      This is in terms of both the Hough accumulator array size as well as the \\n\\\r\n      input image size. \\n\\\r\n    - size() == size_\";\r\n        /*!\r\n            requires\r\n                - size_ > 0\r\n            ensures\r\n                - This object will compute Hough transforms that are size_ by size_ pixels.  \r\n                  This is in terms of both the Hough accumulator array size as well as the\r\n                  input image size.\r\n                - size() == size_\r\n        !*/\r\n\r\n    py::class_<py_hough_transform>(m, \"hough_transform\", class_docs)\r\n        .def(py::init<unsigned long>(), doc_constr, py::arg(\"size_\"))\r\n        .def(\"size\", &py_hough_transform::size,\r\n            \"returns the size of the Hough transforms generated by this object.  In particular, this object creates Hough transform images that are size() by size() pixels in size.\")\r\n        .def(\"get_line\", &py_hough_transform::get_line, py::arg(\"p\"),\r\n\"requires \\n\\\r\n    - rectangle(0,0,size()-1,size()-1).contains(p) == true \\n\\\r\n      (i.e. p must be a point inside the Hough accumulator array) \\n\\\r\nensures \\n\\\r\n    - returns the line segment in the original image space corresponding \\n\\\r\n      to Hough transform point p.  \\n\\\r\n    - The returned points are inside rectangle(0,0,size()-1,size()-1).\") \r\n    /*!\r\n        requires\r\n            - rectangle(0,0,size()-1,size()-1).contains(p) == true\r\n              (i.e. p must be a point inside the Hough accumulator array)\r\n        ensures\r\n            - returns the line segment in the original image space corresponding\r\n              to Hough transform point p. \r\n            - The returned points are inside rectangle(0,0,size()-1,size()-1).\r\n    !*/\r\n\r\n        .def(\"get_line_angle_in_degrees\", &py_hough_transform::get_line_angle_in_degrees, py::arg(\"p\"),\r\n\"requires \\n\\\r\n    - rectangle(0,0,size()-1,size()-1).contains(p) == true \\n\\\r\n      (i.e. p must be a point inside the Hough accumulator array) \\n\\\r\nensures \\n\\\r\n    - returns the angle, in degrees, of the line corresponding to the Hough \\n\\\r\n      transform point p.\")\r\n    /*!\r\n        requires\r\n            - rectangle(0,0,size()-1,size()-1).contains(p) == true\r\n              (i.e. p must be a point inside the Hough accumulator array)\r\n        ensures\r\n            - returns the angle, in degrees, of the line corresponding to the Hough\r\n              transform point p.\r\n    !*/\r\n\r\n\r\n        .def(\"get_line_properties\", &py_hough_transform::get_line_properties, py::arg(\"p\"),\r\n\"requires \\n\\\r\n    - rectangle(0,0,size()-1,size()-1).contains(p) == true \\n\\\r\n      (i.e. p must be a point inside the Hough accumulator array) \\n\\\r\nensures \\n\\\r\n    - Converts a point in the Hough transform space into an angle, in degrees, \\n\\\r\n      and a radius, measured in pixels from the center of the input image. \\n\\\r\n    - let ANGLE_IN_DEGREES == the angle of the line corresponding to the Hough \\n\\\r\n      transform point p.  Moreover: -90 <= ANGLE_IN_DEGREES < 90. \\n\\\r\n    - RADIUS == the distance from the center of the input image, measured in \\n\\\r\n      pixels, and the line corresponding to the Hough transform point p. \\n\\\r\n      Moreover: -sqrt(size()*size()/2) <= RADIUS <= sqrt(size()*size()/2) \\n\\\r\n    - returns a tuple of (ANGLE_IN_DEGREES, RADIUS)\" )\r\n    /*!\r\n        requires\r\n            - rectangle(0,0,size()-1,size()-1).contains(p) == true\r\n              (i.e. p must be a point inside the Hough accumulator array)\r\n        ensures\r\n            - Converts a point in the Hough transform space into an angle, in degrees,\r\n              and a radius, measured in pixels from the center of the input image.\r\n            - let ANGLE_IN_DEGREES == the angle of the line corresponding to the Hough\r\n              transform point p.  Moreover: -90 <= ANGLE_IN_DEGREES < 90.\r\n            - RADIUS == the distance from the center of the input image, measured in\r\n              pixels, and the line corresponding to the Hough transform point p.\r\n              Moreover: -sqrt(size()*size()/2) <= RADIUS <= sqrt(size()*size()/2)\r\n            - returns a tuple of (ANGLE_IN_DEGREES, RADIUS)\r\n    !*/\r\n\r\n        .def(\"get_best_hough_point\", &py_hough_transform::get_best_hough_point, py::arg(\"p\"), py::arg(\"himg\"),\r\n\"requires \\n\\\r\n    - himg has size() rows and columns. \\n\\\r\n    - rectangle(0,0,size()-1,size()-1).contains(p) == true \\n\\\r\nensures \\n\\\r\n    - This function interprets himg as a Hough image and p as a point in the \\n\\\r\n      original image space.  Given this, it finds the maximum scoring line that \\n\\\r\n      passes though p.  That is, it checks all the Hough accumulator bins in \\n\\\r\n      himg corresponding to lines though p and returns the location with the \\n\\\r\n      largest score.   \\n\\\r\n    - returns a point X such that get_rect(himg).contains(X) == true\")\r\n    /*!\r\n        requires\r\n            - himg has size() rows and columns.\r\n            - rectangle(0,0,size()-1,size()-1).contains(p) == true\r\n        ensures\r\n            - This function interprets himg as a Hough image and p as a point in the\r\n              original image space.  Given this, it finds the maximum scoring line that\r\n              passes though p.  That is, it checks all the Hough accumulator bins in\r\n              himg corresponding to lines though p and returns the location with the\r\n              largest score.  \r\n            - returns a point X such that get_rect(himg).contains(X) == true\r\n    !*/\r\n\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<uint8_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<uint16_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<uint32_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<uint64_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<int8_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<int16_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<int32_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<int64_t>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<float>, py::arg(\"img\"), py::arg(\"box\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht<double>, py::arg(\"img\"), py::arg(\"box\"),\r\n\"requires \\n\\\r\n    - box.width() == size() \\n\\\r\n    - box.height() == size() \\n\\\r\nensures \\n\\\r\n    - Computes the Hough transform of the part of img contained within box. \\n\\\r\n      In particular, we do a grayscale version of the Hough transform where any \\n\\\r\n      non-zero pixel in img is treated as a potential component of a line and \\n\\\r\n      accumulated into the returned Hough accumulator image.  However, rather than \\n\\\r\n      adding 1 to each relevant accumulator bin we add the value of the pixel \\n\\\r\n      in img to each Hough accumulator bin.  This means that, if all the \\n\\\r\n      pixels in img are 0 or 1 then this routine performs a normal Hough \\n\\\r\n      transform.  However, if some pixels have larger values then they will be \\n\\\r\n      weighted correspondingly more in the resulting Hough transform. \\n\\\r\n    - The returned hough transform image will be size() rows by size() columns. \\n\\\r\n    - The returned image is the Hough transform of the part of img contained in \\n\\\r\n      box.  Each point in the Hough image corresponds to a line in the input box. \\n\\\r\n      In particular, the line for hough_image[y][x] is given by get_line(point(x,y)).  \\n\\\r\n      Also, when viewing the Hough image, the x-axis gives the angle of the line \\n\\\r\n      and the y-axis the distance of the line from the center of the box.  The \\n\\\r\n      conversion between Hough coordinates and angle and pixel distance can be \\n\\\r\n      obtained by calling get_line_properties().\" )\r\n    /*!\r\n        requires\r\n            - box.width() == size()\r\n            - box.height() == size()\r\n        ensures\r\n            - Computes the Hough transform of the part of img contained within box.\r\n              In particular, we do a grayscale version of the Hough transform where any\r\n              non-zero pixel in img is treated as a potential component of a line and\r\n              accumulated into the returned Hough accumulator image.  However, rather than\r\n              adding 1 to each relevant accumulator bin we add the value of the pixel\r\n              in img to each Hough accumulator bin.  This means that, if all the\r\n              pixels in img are 0 or 1 then this routine performs a normal Hough\r\n              transform.  However, if some pixels have larger values then they will be\r\n              weighted correspondingly more in the resulting Hough transform.\r\n            - The returned hough transform image will be size() rows by size() columns.\r\n            - The returned image is the Hough transform of the part of img contained in\r\n              box.  Each point in the Hough image corresponds to a line in the input box.\r\n              In particular, the line for hough_image[y][x] is given by get_line(point(x,y)). \r\n              Also, when viewing the Hough image, the x-axis gives the angle of the line\r\n              and the y-axis the distance of the line from the center of the box.  The\r\n              conversion between Hough coordinates and angle and pixel distance can be\r\n              obtained by calling get_line_properties().\r\n    !*/\r\n\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<uint8_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<uint16_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<uint32_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<uint64_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<int8_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<int16_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<int32_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<int64_t>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<float>, py::arg(\"img\"))\r\n        .def(\"__call__\", &py_hough_transform::compute_ht2<double>, py::arg(\"img\"),\r\n            \"    simply performs: return self(img, get_rect(img)).  That is, just runs the hough transform on the whole input image.\")\r\n\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<uint8_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<uint16_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<uint32_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<uint64_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<int8_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<int16_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<int32_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<int64_t>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<float>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines<double>, py::arg(\"img\"), py::arg(\"box\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1,\r\n\"requires \\n\\\r\n    - box.width() == size() \\n\\\r\n    - box.height() == size() \\n\\\r\n    - for all valid i: \\n\\\r\n        - rectangle(0,0,size()-1,size()-1).contains(hough_points[i]) == true \\n\\\r\n          (i.e. hough_points must contain points in the output Hough transform \\n\\\r\n          space generated by this object.) \\n\\\r\n    - angle_window_size >= 1 \\n\\\r\n    - radius_window_size >= 1 \\n\\\r\nensures \\n\\\r\n    - This function computes the Hough transform of the part of img contained \\n\\\r\n      within box.  It does the same computation as __call__() defined above, \\n\\\r\n      except instead of accumulating into an image we create an explicit list \\n\\\r\n      of all the points in img that contributed to each line (i.e each point in \\n\\\r\n      the Hough image). To do this we take a list of Hough points as input and \\n\\\r\n      only record hits on these specifically identified Hough points.  A \\n\\\r\n      typical use of find_pixels_voting_for_lines() is to first run the normal \\n\\\r\n      Hough transform using __call__(), then find the lines you are interested \\n\\\r\n      in, and then call find_pixels_voting_for_lines() to determine which \\n\\\r\n      pixels in the input image belong to those lines. \\n\\\r\n    - This routine returns a vector, CONSTITUENT_POINTS, with the following \\n\\\r\n      properties: \\n\\\r\n        - CONSTITUENT_POINTS.size() == hough_points.size() \\n\\\r\n        - for all valid i: \\n\\\r\n            - Let HP[i] = centered_rect(hough_points[i], angle_window_size, radius_window_size) \\n\\\r\n            - Any point in img with a non-zero value that lies on a line \\n\\\r\n              corresponding to one of the Hough points in HP[i] is added to \\n\\\r\n              CONSTITUENT_POINTS[i].  Therefore, when this routine finishes, \\n\\\r\n              #CONSTITUENT_POINTS[i] will contain all the points in img that \\n\\\r\n              voted for the lines associated with the Hough accumulator bins in \\n\\\r\n              HP[i]. \\n\\\r\n            - #CONSTITUENT_POINTS[i].size() == the number of points in img that \\n\\\r\n              voted for any of the lines HP[i] in Hough space.  Note, however, \\n\\\r\n              that if angle_window_size or radius_window_size are made so large \\n\\\r\n              that HP[i] overlaps HP[j] for i!=j then the overlapping regions \\n\\\r\n              of Hough space are assign to HP[i] or HP[j] arbitrarily. \\n\\\r\n              Therefore, all points in CONSTITUENT_POINTS are unique, that is, \\n\\\r\n              there is no overlap in points between any two elements of \\n\\\r\n              CONSTITUENT_POINTS.\" )\r\n    /*!\r\n        requires\r\n            - box.width() == size()\r\n            - box.height() == size()\r\n            - for all valid i:\r\n                - rectangle(0,0,size()-1,size()-1).contains(hough_points[i]) == true\r\n                  (i.e. hough_points must contain points in the output Hough transform\r\n                  space generated by this object.)\r\n            - angle_window_size >= 1\r\n            - radius_window_size >= 1\r\n        ensures\r\n            - This function computes the Hough transform of the part of img contained\r\n              within box.  It does the same computation as __call__() defined above,\r\n              except instead of accumulating into an image we create an explicit list\r\n              of all the points in img that contributed to each line (i.e each point in\r\n              the Hough image). To do this we take a list of Hough points as input and\r\n              only record hits on these specifically identified Hough points.  A\r\n              typical use of find_pixels_voting_for_lines() is to first run the normal\r\n              Hough transform using __call__(), then find the lines you are interested\r\n              in, and then call find_pixels_voting_for_lines() to determine which\r\n              pixels in the input image belong to those lines.\r\n            - This routine returns a vector, CONSTITUENT_POINTS, with the following\r\n              properties:\r\n                - CONSTITUENT_POINTS.size() == hough_points.size()\r\n                - for all valid i:\r\n                    - Let HP[i] = centered_rect(hough_points[i], angle_window_size, radius_window_size)\r\n                    - Any point in img with a non-zero value that lies on a line\r\n                      corresponding to one of the Hough points in HP[i] is added to\r\n                      CONSTITUENT_POINTS[i].  Therefore, when this routine finishes,\r\n                      #CONSTITUENT_POINTS[i] will contain all the points in img that\r\n                      voted for the lines associated with the Hough accumulator bins in\r\n                      HP[i].\r\n                    - #CONSTITUENT_POINTS[i].size() == the number of points in img that\r\n                      voted for any of the lines HP[i] in Hough space.  Note, however,\r\n                      that if angle_window_size or radius_window_size are made so large\r\n                      that HP[i] overlaps HP[j] for i!=j then the overlapping regions\r\n                      of Hough space are assign to HP[i] or HP[j] arbitrarily.\r\n                      Therefore, all points in CONSTITUENT_POINTS are unique, that is,\r\n                      there is no overlap in points between any two elements of\r\n                      CONSTITUENT_POINTS.\r\n    !*/\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<uint8_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<uint16_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<uint32_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<uint64_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<int8_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<int16_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<int32_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<int64_t>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<float>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1)\r\n        .def(\"find_pixels_voting_for_lines\", &py_hough_transform::find_pixels_voting_for_lines2<double>, py::arg(\"img\"), py::arg(\"hough_points\"), py::arg(\"angle_window_size\")=1, py::arg(\"radius_window_size\")=1,\r\n\"    performs: return find_pixels_voting_for_lines(img, get_rect(img), hough_points, angle_window_size, radius_window_size); \\n\\\r\nThat is, just runs the routine on the whole input image.\" )\r\n\r\n        .def(\"find_strong_hough_points\", &py_hough_transform::find_strong_hough_points, py::arg(\"himg\"), py::arg(\"hough_count_threshold\"), py::arg(\"angle_nms_thresh\"), py::arg(\"radius_nms_thresh\"),\r\n\"requires \\n\\\r\n    - himg has size() rows and columns. \\n\\\r\n    - angle_nms_thresh >= 0 \\n\\\r\n    - radius_nms_thresh >= 0 \\n\\\r\nensures \\n\\\r\n    - This routine finds strong lines in a Hough transform and performs \\n\\\r\n      non-maximum suppression on the detected lines.  Recall that each point in \\n\\\r\n      Hough space is associated with a line. Therefore, this routine finds all \\n\\\r\n      the pixels in himg (a Hough transform image) with values >= \\n\\\r\n      hough_count_threshold and performs non-maximum suppression on the \\n\\\r\n      identified list of pixels.  It does this by discarding lines that are \\n\\\r\n      within angle_nms_thresh degrees of a stronger line or within \\n\\\r\n      radius_nms_thresh distance (in terms of radius as defined by \\n\\\r\n      get_line_properties()) to a stronger Hough point. \\n\\\r\n    - The identified lines are returned as a list of coordinates in himg.\" );\r\n    /*!\r\n        requires\r\n            - himg has size() rows and columns.\r\n            - angle_nms_thresh >= 0\r\n            - radius_nms_thresh >= 0\r\n        ensures\r\n            - This routine finds strong lines in a Hough transform and performs\r\n              non-maximum suppression on the detected lines.  Recall that each point in\r\n              Hough space is associated with a line. Therefore, this routine finds all\r\n              the pixels in himg (a Hough transform image) with values >=\r\n              hough_count_threshold and performs non-maximum suppression on the\r\n              identified list of pixels.  It does this by discarding lines that are\r\n              within angle_nms_thresh degrees of a stronger line or within\r\n              radius_nms_thresh distance (in terms of radius as defined by\r\n              get_line_properties()) to a stronger Hough point.\r\n            - The identified lines are returned as a list of coordinates in himg.\r\n    !*/\r\n\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nstd::vector<point> py_remove_incoherent_edge_pixels (\r\n    const std::vector<point>& line,\r\n    const numpy_image<float>& horz_gradient,\r\n    const numpy_image<float>& vert_gradient,\r\n    double angle_threshold\r\n)\r\n{\r\n\r\n    DLIB_CASSERT(num_rows(horz_gradient) == num_rows(vert_gradient));\r\n    DLIB_CASSERT(num_columns(horz_gradient) == num_columns(vert_gradient));\r\n    DLIB_CASSERT(angle_threshold >= 0);\r\n    for (auto& p : line)\r\n        DLIB_CASSERT(get_rect(horz_gradient).contains(p), \"All line points must be inside the given images.\");\r\n\r\n    return remove_incoherent_edge_pixels(line, horz_gradient, vert_gradient, angle_threshold);\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\ntemplate <typename T>\r\nnumpy_image<T> py_transform_image (\r\n    const numpy_image<T>& img,\r\n    const point_transform_projective& map_point,\r\n    long rows,\r\n    long columns\r\n)\r\n{\r\n    DLIB_CASSERT(rows > 0 && columns > 0, \"The requested output image dimensions are invalid.\");\r\n    numpy_image<T> out_;\r\n    image_view<numpy_image<T>> out(out_);\r\n    out.set_size(rows, columns);\r\n\r\n    transform_image(img, out_, interpolate_bilinear(), map_point);\r\n\r\n    return out_;\r\n}\r\n// ----------------------------------------------------------------------------------------\r\n\r\ntemplate <typename T>\r\nnumpy_image<T> py_extract_image_4points (\r\n    const numpy_image<T>& img,\r\n    const py::list& corners,\r\n    long rows,\r\n    long columns\r\n)\r\n{\r\n    DLIB_CASSERT(rows >= 0);\r\n    DLIB_CASSERT(columns >= 0);\r\n    DLIB_CASSERT(len(corners) == 4);\r\n\r\n    numpy_image<T> out;\r\n    set_image_size(out, rows, columns);\r\n    try\r\n    {\r\n        extract_image_4points(img, out, python_list_to_array<dpoint,4>(corners));\r\n        return out;\r\n    } \r\n    catch (py::cast_error&){}\r\n\r\n    try\r\n    {\r\n        extract_image_4points(img, out, python_list_to_array<line,4>(corners));\r\n        return out;\r\n    }\r\n    catch(py::cast_error&)\r\n    {\r\n        throw dlib::error(\"extract_image_4points() requires the corners argument to be a list of 4 dpoints or 4 lines.\");\r\n    }\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\ntemplate <typename T>\r\nnumpy_image<T> py_mbd (\r\n    const numpy_image<T>& img,\r\n    size_t iterations,\r\n    bool do_left_right_scans \r\n)\r\n{\r\n    numpy_image<T> out;\r\n    min_barrier_distance(img, out, iterations, do_left_right_scans);\r\n    return out;\r\n}\r\n\r\nnumpy_image<unsigned char> py_mbd2 (\r\n    const numpy_image<rgb_pixel>& img,\r\n    size_t iterations,\r\n    bool do_left_right_scans \r\n)\r\n{\r\n    numpy_image<unsigned char> out;\r\n    min_barrier_distance(img, out, iterations, do_left_right_scans);\r\n    return out;\r\n}\r\n\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid bind_image_classes2(py::module& m)\r\n{\r\n\r\n    const char* docs = \"Resizes img, using bilinear interpolation, to have the indicated number of rows and columns.\";\r\n\r\n\r\n    m.def(\"resize_image\", &py_resize_image<uint8_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<uint16_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<uint32_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<uint64_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<int8_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<int16_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<int32_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<int64_t>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<float>, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<double>, docs, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n    m.def(\"resize_image\", &py_resize_image<rgb_pixel>, docs, py::arg(\"img\"), py::arg(\"rows\"), py::arg(\"cols\"));\r\n\r\n\r\n    docs = \"Returns a histogram equalized version of img.\";\r\n    m.def(\"equalize_histogram\", &py_equalize_histogram<uint8_t>, py::arg(\"img\"));\r\n    m.def(\"equalize_histogram\", &py_equalize_histogram<uint16_t>, docs, py::arg(\"img\"));\r\n\r\n    m.def(\"min_barrier_distance\", &py_mbd<uint8_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<uint16_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<uint32_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<uint64_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<int8_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<int16_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<int32_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<int64_t>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<float>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd<double>, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true);\r\n    m.def(\"min_barrier_distance\", &py_mbd2, py::arg(\"img\"), py::arg(\"iterations\")=10, py::arg(\"do_left_right_scans\")=true,\r\n\"requires \\n\\\r\n    - iterations > 0 \\n\\\r\nensures \\n\\\r\n    - This function implements the salient object detection method described in the paper: \\n\\\r\n        \\\"Minimum barrier salient object detection at 80 fps\\\" by Zhang, Jianming, et al.  \\n\\\r\n      In particular, we compute the minimum barrier distance between the borders of \\n\\\r\n      the image and all the other pixels.  The resulting image is returned.  Note that \\n\\\r\n      the paper talks about a bunch of other things you could do beyond computing \\n\\\r\n      the minimum barrier distance, but this function doesn't do any of that. It's \\n\\\r\n      just the vanilla MBD. \\n\\\r\n    - We will perform iterations iterations of MBD passes over the image.  Larger \\n\\\r\n      values might give better results but run slower. \\n\\\r\n    - During each MBD iteration we make raster scans over the image.  These pass \\n\\\r\n      from top->bottom, bottom->top, left->right, and right->left.  If \\n\\\r\n      do_left_right_scans==false then the left/right passes are not executed. \\n\\\r\n      Skipping them makes the algorithm about 2x faster but might reduce the \\n\\\r\n      quality of the output.\" \r\n    /*!\r\n        requires\r\n            - iterations > 0\r\n        ensures\r\n            - This function implements the salient object detection method described in the paper:\r\n                \"Minimum barrier salient object detection at 80 fps\" by Zhang, Jianming, et al. \r\n              In particular, we compute the minimum barrier distance between the borders of\r\n              the image and all the other pixels.  The resulting image is returned.  Note that\r\n              the paper talks about a bunch of other things you could do beyond computing\r\n              the minimum barrier distance, but this function doesn't do any of that. It's\r\n              just the vanilla MBD.\r\n            - We will perform iterations iterations of MBD passes over the image.  Larger\r\n              values might give better results but run slower.\r\n            - During each MBD iteration we make raster scans over the image.  These pass\r\n              from top->bottom, bottom->top, left->right, and right->left.  If\r\n              do_left_right_scans==false then the left/right passes are not executed.\r\n              Skipping them makes the algorithm about 2x faster but might reduce the\r\n              quality of the output.\r\n    !*/\r\n    );\r\n\r\n    register_hough_transform(m);\r\n\r\n    m.def(\"normalize_image_gradients\", normalize_image_gradients<numpy_image<double>>, py::arg(\"img1\"), py::arg(\"img2\"));\r\n    m.def(\"normalize_image_gradients\", normalize_image_gradients<numpy_image<float>>, py::arg(\"img1\"), py::arg(\"img2\"),\r\n\"requires \\n\\\r\n    - img1 and img2 have the same dimensions. \\n\\\r\nensures \\n\\\r\n    - This function assumes img1 and img2 are the two gradient images produced by a \\n\\\r\n      function like sobel_edge_detector().  It then unit normalizes the gradient \\n\\\r\n      vectors. That is, for all valid r and c, this function ensures that: \\n\\\r\n        - img1[r][c]*img1[r][c] + img2[r][c]*img2[r][c] == 1  \\n\\\r\n          unless both img1[r][c] and img2[r][c] were 0 initially, then they stay zero.\");\r\n    /*!\r\n        requires\r\n            - img1 and img2 have the same dimensions.\r\n        ensures\r\n            - This function assumes img1 and img2 are the two gradient images produced by a\r\n              function like sobel_edge_detector().  It then unit normalizes the gradient\r\n              vectors. That is, for all valid r and c, this function ensures that:\r\n                - img1[r][c]*img1[r][c] + img2[r][c]*img2[r][c] == 1 \r\n                  unless both img1[r][c] and img2[r][c] were 0 initially, then they stay zero.\r\n    !*/\r\n\r\n\r\n    m.def(\"remove_incoherent_edge_pixels\", &py_remove_incoherent_edge_pixels, py::arg(\"line\"), py::arg(\"horz_gradient\"),\r\n        py::arg(\"vert_gradient\"), py::arg(\"angle_thresh\"),\r\n\"requires \\n\\\r\n    - horz_gradient and vert_gradient have the same dimensions. \\n\\\r\n    - horz_gradient and vert_gradient represent unit normalized vectors.  That is, \\n\\\r\n      you should have called normalize_image_gradients(horz_gradient,vert_gradient) \\n\\\r\n      or otherwise caused all the gradients to have unit norm. \\n\\\r\n    - for all valid i: \\n\\\r\n        get_rect(horz_gradient).contains(line[i]) \\n\\\r\nensures \\n\\\r\n    - This routine looks at all the points in the given line and discards the ones that \\n\\\r\n      have outlying gradient directions.  To be specific, this routine returns a set \\n\\\r\n      of points PTS such that:  \\n\\\r\n        - for all valid i,j: \\n\\\r\n            - The difference in angle between the gradients for PTS[i] and PTS[j] is  \\n\\\r\n              less than angle_threshold degrees.   \\n\\\r\n        - len(PTS) <= len(line) \\n\\\r\n        - PTS is just line with some elements removed.\" );\r\n    /*!\r\n        requires\r\n            - horz_gradient and vert_gradient have the same dimensions.\r\n            - horz_gradient and vert_gradient represent unit normalized vectors.  That is,\r\n              you should have called normalize_image_gradients(horz_gradient,vert_gradient)\r\n              or otherwise caused all the gradients to have unit norm.\r\n            - for all valid i:\r\n                get_rect(horz_gradient).contains(line[i])\r\n        ensures\r\n            - This routine looks at all the points in the given line and discards the ones that\r\n              have outlying gradient directions.  To be specific, this routine returns a set\r\n              of points PTS such that: \r\n                - for all valid i,j:\r\n                    - The difference in angle between the gradients for PTS[i] and PTS[j] is \r\n                      less than angle_threshold degrees.  \r\n                - len(PTS) <= len(line)\r\n                - PTS is just line with some elements removed.\r\n    !*/\r\n\r\n    py::register_exception<no_convex_quadrilateral>(m, \"no_convex_quadrilateral\");\r\n\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<uint8_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<uint16_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<uint32_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<uint64_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<int8_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<int16_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<int32_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<int64_t>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<float>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<double>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"extract_image_4points\", &py_extract_image_4points<rgb_pixel>, py::arg(\"img\"), py::arg(\"corners\"), py::arg(\"rows\"), py::arg(\"columns\"),\r\n\"requires \\n\\\r\n    - corners is a list of dpoint or line objects. \\n\\\r\n    - len(corners) == 4 \\n\\\r\n    - rows >= 0 \\n\\\r\n    - columns >= 0 \\n\\\r\nensures \\n\\\r\n    - The returned image has the given number of rows and columns. \\n\\\r\n    - if (corners contains dpoints) then \\n\\\r\n        - The 4 points in corners define a convex quadrilateral and this function \\n\\\r\n          extracts that part of the input image img and returns it.  Therefore, \\n\\\r\n          each corner of the quadrilateral is associated to a corner of the \\n\\\r\n          extracted image and bilinear interpolation and a projective mapping is \\n\\\r\n          used to transform the pixels in the quadrilateral into the output image. \\n\\\r\n          To determine which corners of the quadrilateral map to which corners of \\n\\\r\n          the returned image we fit the tightest possible rectangle to the \\n\\\r\n          quadrilateral and map its vertices to their nearest rectangle corners. \\n\\\r\n          These corners are then trivially mapped to the output image (i.e.  upper \\n\\\r\n          left corner to upper left corner, upper right corner to upper right \\n\\\r\n          corner, etc.). \\n\\\r\n    - else \\n\\\r\n        - This routine finds the 4 intersecting points of the given lines which \\n\\\r\n          form a convex quadrilateral and uses them as described above to extract \\n\\\r\n          an image.   i.e. It just then calls: extract_image_4points(img, \\n\\\r\n          intersections_between_lines, rows, columns). \\n\\\r\n        - If no convex quadrilateral can be made from the given lines then this \\n\\\r\n          routine throws no_convex_quadrilateral.\" \r\n    /*!\r\n        requires\r\n            - corners is a list of dpoint or line objects.\r\n            - len(corners) == 4\r\n            - rows >= 0\r\n            - columns >= 0\r\n        ensures\r\n            - The returned image has the given number of rows and columns.\r\n            - if (corners contains dpoints) then\r\n                - The 4 points in corners define a convex quadrilateral and this function\r\n                  extracts that part of the input image img and returns it.  Therefore,\r\n                  each corner of the quadrilateral is associated to a corner of the\r\n                  extracted image and bilinear interpolation and a projective mapping is\r\n                  used to transform the pixels in the quadrilateral into the output image.\r\n                  To determine which corners of the quadrilateral map to which corners of\r\n                  the returned image we fit the tightest possible rectangle to the\r\n                  quadrilateral and map its vertices to their nearest rectangle corners.\r\n                  These corners are then trivially mapped to the output image (i.e.  upper\r\n                  left corner to upper left corner, upper right corner to upper right\r\n                  corner, etc.).\r\n            - else\r\n                - This routine finds the 4 intersecting points of the given lines which\r\n                  form a convex quadrilateral and uses them as described above to extract\r\n                  an image.   i.e. It just then calls: extract_image_4points(img,\r\n                  intersections_between_lines, rows, columns).\r\n                - If no convex quadrilateral can be made from the given lines then this\r\n                  routine throws no_convex_quadrilateral.\r\n    !*/\r\n          );\r\n\r\n\r\n    m.def(\"transform_image\", &py_transform_image<uint8_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<uint16_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<uint32_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<uint64_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<int8_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<int16_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<int32_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<int64_t>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<float>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<double>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"));\r\n    m.def(\"transform_image\", &py_transform_image<rgb_pixel>, py::arg(\"img\"), py::arg(\"map_point\"), py::arg(\"rows\"), py::arg(\"columns\"),\r\n\"requires \\n\\\r\n    - rows > 0 \\n\\\r\n    - columns > 0 \\n\\\r\nensures \\n\\\r\n    - Returns an image that is the given rows by columns in size and contains a \\n\\\r\n      transformed part of img.  To do this, we interpret map_point as a mapping \\n\\\r\n      from pixels in the returned image to pixels in the input img.  transform_image()  \\n\\\r\n      uses this mapping and bilinear interpolation to fill the output image with an \\n\\\r\n      interpolated copy of img.   \\n\\\r\n    - Any locations in the output image that map to pixels outside img are set to 0.\" \r\n    /*!\r\n        requires\r\n            - rows > 0\r\n            - columns > 0\r\n        ensures\r\n            - Returns an image that is the given rows by columns in size and contains a\r\n              transformed part of img.  To do this, we interpret map_point as a mapping\r\n              from pixels in the returned image to pixels in the input img.  transform_image() \r\n              uses this mapping and bilinear interpolation to fill the output image with an\r\n              interpolated copy of img.  \r\n            - Any locations in the output image that map to pixels outside img are set to 0.\r\n    !*/\r\n        );\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "0d23cdf8dc48915a9f49638ad937f1b8d204009e", "size": 47341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/python/src/image2.cpp", "max_stars_repo_name": "oms1226/dlib-19.13", "max_stars_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_stars_repo_licenses": ["MIT"], "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/image2.cpp", "max_issues_repo_name": "oms1226/dlib-19.13", "max_issues_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_issues_repo_licenses": ["MIT"], "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/image2.cpp", "max_forks_repo_name": "oms1226/dlib-19.13", "max_forks_repo_head_hexsha": "0bb55d112324edb700a42a3e6baca09c03967754", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.2244655582, "max_line_length": 228, "alphanum_fraction": 0.6270674468, "num_tokens": 11705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.05184546555102378, "lm_q1q2_score": 0.02210284219586081}}
{"text": "// json parser\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\nnamespace pt = boost::property_tree;\n\n#include \"PermittivityDrude.h\"\n\nPermittivityDrude::PermittivityDrude(double omega_p, double gamma)\n    : omega_p(omega_p), gamma(gamma) {}\n\n// constructor for drude model from .json file\nPermittivityDrude::PermittivityDrude(const std::string &input_file) {\n\n  // Create a root\n  pt::ptree root;\n\n  // Load the json file in this ptree\n  pt::read_json(input_file, root);\n\n  // check if type is right\n  std::string type = root.get<std::string>(\"Permittivity.type\");\n  assert(type == \"drude\");\n\n  // read parameters\n  this->gamma = root.get<double>(\"Permittivity.gamma\");\n  this->omega_p = root.get<double>(\"Permittivity.omega_p\");\n}\n\n// calculate the permittivity\nstd::complex<double> PermittivityDrude::calculate(double omega) const {\n  // dummies for result and complex unit\n  std::complex<double> result;\n  std::complex<double> I(0.0, 1.0);\n\n  // calculate the result\n  result = 1.0 - omega_p * omega_p / (omega * (omega + I * gamma));\n\n  return result;\n}\n\n// calculate the permittivity scaled by omega\nstd::complex<double>\nPermittivityDrude::calculate_times_omega(double omega) const {\n  // dummies for result and complex unit\n  std::complex<double> result;\n  std::complex<double> I(0.0, 1.0);\n\n  // calculate the result\n  result = omega - omega_p * omega_p / (omega + I * gamma);\n\n  return result;\n}\n\nvoid PermittivityDrude::print_info(std::ostream &stream) const {\n  stream << \"# PermittivityDrude\\n#\\n\"\n         << \"# omega_p = \" << omega_p << \"\\n\"\n         << \"# gamma = \" << gamma << \"\\n\";\n}\n", "meta": {"hexsha": "f58e58f4d31480de643c839fa27168699b4420b6", "size": 1639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Permittivity/PermittivityDrude.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "src/Permittivity/PermittivityDrude.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "src/Permittivity/PermittivityDrude.cpp", "max_forks_repo_name": "myoelmy/quaca", "max_forks_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7796610169, "max_line_length": 71, "alphanum_fraction": 0.6900549115, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.049589021930595244, "lm_q1q2_score": 0.022093374613969523}}
{"text": "//  Copyright 2014 Marco Guazzone (marco.guazzone@gmail.com)\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 Hyper-Exponential distribution.\r\n//\r\n// References:\r\n// - \"Queueing Theory in Manufacturing Systems Analysis and Design\" by H.T. Papadopolous, C. Heavey and J. Browne (Chapman & Hall/CRC, 1993)\r\n// - http://reference.wolfram.com/language/ref/HyperexponentialDistribution.html\r\n// - http://en.wikipedia.org/wiki/Hyperexponential_distribution\r\n//\r\n\r\n#ifndef BOOST_MATH_DISTRIBUTIONS_HYPEREXPONENTIAL_HPP\r\n#define BOOST_MATH_DISTRIBUTIONS_HYPEREXPONENTIAL_HPP\r\n\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/math/tools/cxx03_warn.hpp>\r\n#include <boost/math/distributions/complement.hpp>\r\n#include <boost/math/distributions/detail/common_error_handling.hpp>\r\n#include <boost/math/distributions/exponential.hpp>\r\n#include <boost/math/policies/policy.hpp>\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n#include <boost/math/tools/precision.hpp>\r\n#include <boost/math/tools/roots.hpp>\r\n#include <boost/range/begin.hpp>\r\n#include <boost/range/end.hpp>\r\n#include <boost/range/size.hpp>\r\n#include <boost/type_traits/has_pre_increment.hpp>\r\n#include <cstddef>\r\n#include <iterator>\r\n#include <limits>\r\n#include <numeric>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)\r\n# include <initializer_list>\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning (push)\r\n# pragma warning(disable:4127) // conditional expression is constant\r\n# pragma warning(disable:4389) // '==' : signed/unsigned mismatch in test_tools\r\n#endif // _MSC_VER\r\n\r\nnamespace boost { namespace math {\r\n\r\nnamespace detail {\r\n\r\ntemplate <typename Dist>\r\ntypename Dist::value_type generic_quantile(const Dist& dist, const typename Dist::value_type& p, const typename Dist::value_type& guess, bool comp, const char* function);\r\n\r\n} // Namespace detail\r\n\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nclass hyperexponential_distribution;\r\n\r\n\r\nnamespace /*<unnamed>*/ { namespace hyperexp_detail {\r\n\r\ntemplate <typename T>\r\nvoid normalize(std::vector<T>& v)\r\n{\r\n   if(!v.size())\r\n      return;  // Our error handlers will get this later\r\n    const T sum = std::accumulate(v.begin(), v.end(), static_cast<T>(0));\r\n    T final_sum = 0;\r\n    const typename std::vector<T>::iterator end = --v.end();\r\n    for (typename std::vector<T>::iterator it = v.begin();\r\n         it != end;\r\n         ++it)\r\n    {\r\n        *it /= sum;\r\n        final_sum += *it;\r\n    }\r\n    *end = 1 - final_sum;  // avoids round off errors, ensures the probs really do sum to 1.\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nbool check_probabilities(char const* function, std::vector<RealT> const& probabilities, RealT* presult, PolicyT const& pol)\r\n{\r\n    BOOST_MATH_STD_USING\r\n    const std::size_t n = probabilities.size();\r\n    RealT sum = 0;\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        if (probabilities[i] < 0\r\n            || probabilities[i] > 1\r\n            || !(boost::math::isfinite)(probabilities[i]))\r\n        {\r\n            *presult = policies::raise_domain_error<RealT>(function,\r\n                                                           \"The elements of parameter \\\"probabilities\\\" must be >= 0 and <= 1, but at least one of them was: %1%.\",\r\n                                                           probabilities[i],\r\n                                                           pol);\r\n            return false;\r\n        }\r\n        sum += probabilities[i];\r\n    }\r\n\r\n    //\r\n    // We try to keep phase probabilities correctly normalized in the distribution constructors,\r\n    // however in practice we have to allow for a very slight divergence from a sum of exactly 1:\r\n    //\r\n    if (fabs(sum - 1) > tools::epsilon<RealT>() * 2)\r\n    {\r\n        *presult = policies::raise_domain_error<RealT>(function,\r\n                                                       \"The elements of parameter \\\"probabilities\\\" must sum to 1, but their sum is: %1%.\",\r\n                                                       sum,\r\n                                                       pol);\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nbool check_rates(char const* function, std::vector<RealT> const& rates, RealT* presult, PolicyT const& pol)\r\n{\r\n    const std::size_t n = rates.size();\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        if (rates[i] <= 0\r\n            || !(boost::math::isfinite)(rates[i]))\r\n        {\r\n            *presult = policies::raise_domain_error<RealT>(function,\r\n                                                           \"The elements of parameter \\\"rates\\\" must be > 0, but at least one of them is: %1%.\",\r\n                                                           rates[i],\r\n                                                           pol);\r\n            return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nbool check_dist(char const* function, std::vector<RealT> const& probabilities, std::vector<RealT> const& rates, RealT* presult, PolicyT const& pol)\r\n{\r\n    BOOST_MATH_STD_USING\r\n    if (probabilities.size() != rates.size())\r\n    {\r\n        *presult = policies::raise_domain_error<RealT>(function,\r\n                                                       \"The parameters \\\"probabilities\\\" and \\\"rates\\\" must have the same length, but their size differ by: %1%.\",\r\n                                                       fabs(static_cast<RealT>(probabilities.size())-static_cast<RealT>(rates.size())),\r\n                                                       pol);\r\n        return false;\r\n    }\r\n\r\n    return check_probabilities(function, probabilities, presult, pol)\r\n           && check_rates(function, rates, presult, pol);\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nbool check_x(char const* function, RealT x, RealT* presult, PolicyT const& pol)\r\n{\r\n    if (x < 0 || (boost::math::isnan)(x))\r\n    {\r\n        *presult = policies::raise_domain_error<RealT>(function, \"The random variable must be >= 0, but is: %1%.\", x, pol);\r\n        return false;\r\n    }\r\n    return true;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nbool check_probability(char const* function, RealT p, RealT* presult, PolicyT const& pol)\r\n{\r\n    if (p < 0 || p > 1 || (boost::math::isnan)(p))\r\n    {\r\n        *presult = policies::raise_domain_error<RealT>(function, \"The probability be >= 0 and <= 1, but is: %1%.\", p, pol);\r\n        return false;\r\n    }\r\n    return true;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT quantile_impl(hyperexponential_distribution<RealT, PolicyT> const& dist, RealT const& p, bool comp)\r\n{\r\n    // Don't have a closed form so try to numerically solve the inverse CDF...\r\n\r\n    typedef typename policies::evaluation<RealT, PolicyT>::type value_type;\r\n    typedef typename policies::normalise<PolicyT,\r\n                                         policies::promote_float<false>,\r\n                                         policies::promote_double<false>,\r\n                                         policies::discrete_quantile<>,\r\n                                         policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n    static const char* function = comp ? \"boost::math::quantile(const boost::math::complemented2_type<boost::math::hyperexponential_distribution<%1%>, %1%>&)\"\r\n                                       : \"boost::math::quantile(const boost::math::hyperexponential_distribution<%1%>&, %1%)\";\r\n\r\n    RealT result = 0;\r\n\r\n    if (!check_probability(function, p, &result, PolicyT()))\r\n    {\r\n        return result;\r\n    }\r\n\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    // A possible (but inaccurate) approximation is given below, where the\r\n    // quantile is given by the weighted sum of exponential quantiles:\r\n    RealT guess = 0;\r\n    if (comp)\r\n    {\r\n        for (std::size_t i = 0; i < n; ++i)\r\n        {\r\n            const exponential_distribution<RealT,PolicyT> exp(rates[i]);\r\n\r\n            guess += probs[i]*quantile(complement(exp, p));\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for (std::size_t i = 0; i < n; ++i)\r\n        {\r\n            const exponential_distribution<RealT,PolicyT> exp(rates[i]);\r\n\r\n            guess += probs[i]*quantile(exp, p);\r\n        }\r\n    }\r\n\r\n    // Fast return in case the Hyper-Exponential is essentially an Exponential\r\n    if (n == 1)\r\n    {\r\n        return guess;\r\n    }\r\n\r\n    value_type q;\r\n    q = detail::generic_quantile(hyperexponential_distribution<RealT,forwarding_policy>(probs, rates),\r\n                                 p,\r\n                                 guess,\r\n                                 comp,\r\n                                 function);\r\n\r\n    result = policies::checked_narrowing_cast<RealT,forwarding_policy>(q, function);\r\n\r\n    return result;\r\n}\r\n\r\n}} // Namespace <unnamed>::hyperexp_detail\r\n\r\n\r\ntemplate <typename RealT = double, typename PolicyT = policies::policy<> >\r\nclass hyperexponential_distribution\r\n{\r\n    public: typedef RealT value_type;\r\n    public: typedef PolicyT policy_type;\r\n\r\n\r\n    public: hyperexponential_distribution()\r\n    : probs_(1, 1),\r\n      rates_(1, 1)\r\n    {\r\n        RealT err;\r\n        hyperexp_detail::check_dist(\"boost::math::hyperexponential_distribution<%1%>::hyperexponential_distribution\",\r\n                                    probs_,\r\n                                    rates_,\r\n                                    &err,\r\n                                    PolicyT());\r\n    }\r\n\r\n    // Four arg constructor: no ambiguity here, the arguments must be two pairs of iterators:\r\n    public: template <typename ProbIterT, typename RateIterT>\r\n            hyperexponential_distribution(ProbIterT prob_first, ProbIterT prob_last,\r\n                                          RateIterT rate_first, RateIterT rate_last)\r\n    : probs_(prob_first, prob_last),\r\n      rates_(rate_first, rate_last)\r\n    {\r\n        hyperexp_detail::normalize(probs_);\r\n        RealT err;\r\n        hyperexp_detail::check_dist(\"boost::math::hyperexponential_distribution<%1%>::hyperexponential_distribution\",\r\n                                    probs_,\r\n                                    rates_,\r\n                                    &err,\r\n                                    PolicyT());\r\n    }\r\n\r\n    // Two arg constructor from 2 ranges, we SFINAE this out of existence if\r\n    // either argument type is incrementable as in that case the type is\r\n    // probably an iterator:\r\n    public: template <typename ProbRangeT, typename RateRangeT>\r\n            hyperexponential_distribution(ProbRangeT const& prob_range,\r\n                                          RateRangeT const& rate_range,\r\n                                          typename boost::disable_if_c<boost::has_pre_increment<ProbRangeT>::value || boost::has_pre_increment<RateRangeT>::value>::type* = 0)\r\n    : probs_(boost::begin(prob_range), boost::end(prob_range)),\r\n      rates_(boost::begin(rate_range), boost::end(rate_range))\r\n    {\r\n        hyperexp_detail::normalize(probs_);\r\n\r\n        RealT err;\r\n        hyperexp_detail::check_dist(\"boost::math::hyperexponential_distribution<%1%>::hyperexponential_distribution\",\r\n                                    probs_,\r\n                                    rates_,\r\n                                    &err,\r\n                                    PolicyT());\r\n    }\r\n\r\n    // Two arg constructor for a pair of iterators: we SFINAE this out of\r\n    // existence if neither argument types are incrementable.\r\n    // Note that we allow different argument types here to allow for\r\n    // construction from an array plus a pointer into that array.\r\n    public: template <typename RateIterT, typename RateIterT2>\r\n            hyperexponential_distribution(RateIterT const& rate_first, \r\n                                          RateIterT2 const& rate_last, \r\n                                          typename boost::enable_if_c<boost::has_pre_increment<RateIterT>::value || boost::has_pre_increment<RateIterT2>::value>::type* = 0)\r\n    : probs_(std::distance(rate_first, rate_last), 1), // will be normalized below\r\n      rates_(rate_first, rate_last)\r\n    {\r\n        hyperexp_detail::normalize(probs_);\r\n\r\n        RealT err;\r\n        hyperexp_detail::check_dist(\"boost::math::hyperexponential_distribution<%1%>::hyperexponential_distribution\",\r\n                                    probs_,\r\n                                    rates_,\r\n                                    &err,\r\n                                    PolicyT());\r\n    }\r\n\r\n#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)\r\n      // Initializer list constructor: allows for construction from array literals:\r\npublic: hyperexponential_distribution(std::initializer_list<RealT> l1, std::initializer_list<RealT> l2)\r\n      : probs_(l1.begin(), l1.end()),\r\n        rates_(l2.begin(), l2.end())\r\n      {\r\n         hyperexp_detail::normalize(probs_);\r\n\r\n         RealT err;\r\n         hyperexp_detail::check_dist(\"boost::math::hyperexponential_distribution<%1%>::hyperexponential_distribution\",\r\n            probs_,\r\n            rates_,\r\n            &err,\r\n            PolicyT());\r\n      }\r\n\r\npublic: hyperexponential_distribution(std::initializer_list<RealT> l1)\r\n      : probs_(l1.size(), 1),\r\n        rates_(l1.begin(), l1.end())\r\n      {\r\n         hyperexp_detail::normalize(probs_);\r\n\r\n         RealT err;\r\n         hyperexp_detail::check_dist(\"boost::math::hyperexponential_distribution<%1%>::hyperexponential_distribution\",\r\n            probs_,\r\n            rates_,\r\n            &err,\r\n            PolicyT());\r\n      }\r\n#endif // !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)\r\n\r\n    // Single argument constructor: argument must be a range.\r\n    public: template <typename RateRangeT>\r\n    hyperexponential_distribution(RateRangeT const& rate_range)\r\n    : probs_(boost::size(rate_range), 1), // will be normalized below\r\n      rates_(boost::begin(rate_range), boost::end(rate_range))\r\n    {\r\n        hyperexp_detail::normalize(probs_);\r\n\r\n        RealT err;\r\n        hyperexp_detail::check_dist(\"boost::math::hyperexponential_distribution<%1%>::hyperexponential_distribution\",\r\n                                    probs_,\r\n                                    rates_,\r\n                                    &err,\r\n                                    PolicyT());\r\n    }\r\n\r\n    public: std::vector<RealT> probabilities() const\r\n    {\r\n        return probs_;\r\n    }\r\n\r\n    public: std::vector<RealT> rates() const\r\n    {\r\n        return rates_;\r\n    }\r\n\r\n    public: std::size_t num_phases() const\r\n    {\r\n        return rates_.size();\r\n    }\r\n\r\n\r\n    private: std::vector<RealT> probs_;\r\n    private: std::vector<RealT> rates_;\r\n}; // class hyperexponential_distribution\r\n\r\n\r\n// Convenient type synonym for double.\r\ntypedef hyperexponential_distribution<double> hyperexponential;\r\n\r\n\r\n// Range of permissible values for random variable x\r\ntemplate <typename RealT, typename PolicyT>\r\nstd::pair<RealT,RealT> range(hyperexponential_distribution<RealT,PolicyT> const&)\r\n{\r\n    if (std::numeric_limits<RealT>::has_infinity)\r\n    {\r\n        return std::make_pair(static_cast<RealT>(0), std::numeric_limits<RealT>::infinity()); // 0 to +inf.\r\n    }\r\n\r\n    return std::make_pair(static_cast<RealT>(0), tools::max_value<RealT>()); // 0 to +<max value>\r\n}\r\n\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\ntemplate <typename RealT, typename PolicyT>\r\nstd::pair<RealT,RealT> support(hyperexponential_distribution<RealT,PolicyT> const&)\r\n{\r\n    return std::make_pair(tools::min_value<RealT>(), tools::max_value<RealT>()); // <min value> to +<max value>.\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT pdf(hyperexponential_distribution<RealT, PolicyT> const& dist, RealT const& x)\r\n{\r\n    BOOST_MATH_STD_USING\r\n    RealT result = 0;\r\n\r\n    if (!hyperexp_detail::check_x(\"boost::math::pdf(const boost::math::hyperexponential_distribution<%1%>&, %1%)\", x, &result, PolicyT()))\r\n    {\r\n        return result;\r\n    }\r\n\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        const exponential_distribution<RealT,PolicyT> exp(rates[i]);\r\n\r\n        result += probs[i]*pdf(exp, x);\r\n        //result += probs[i]*rates[i]*exp(-rates[i]*x);\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT cdf(hyperexponential_distribution<RealT, PolicyT> const& dist, RealT const& x)\r\n{\r\n    RealT result = 0;\r\n\r\n    if (!hyperexp_detail::check_x(\"boost::math::cdf(const boost::math::hyperexponential_distribution<%1%>&, %1%)\", x, &result, PolicyT()))\r\n    {\r\n        return result;\r\n    }\r\n\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        const exponential_distribution<RealT,PolicyT> exp(rates[i]);\r\n\r\n        result += probs[i]*cdf(exp, x);\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT quantile(hyperexponential_distribution<RealT, PolicyT> const& dist, RealT const& p)\r\n{\r\n    return hyperexp_detail::quantile_impl(dist, p , false);\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT cdf(complemented2_type<hyperexponential_distribution<RealT,PolicyT>, RealT> const& c)\r\n{\r\n    RealT const& x = c.param;\r\n    hyperexponential_distribution<RealT,PolicyT> const& dist = c.dist;\r\n\r\n    RealT result = 0;\r\n\r\n    if (!hyperexp_detail::check_x(\"boost::math::cdf(boost::math::complemented2_type<const boost::math::hyperexponential_distribution<%1%>&, %1%>)\", x, &result, PolicyT()))\r\n    {\r\n        return result;\r\n    }\r\n\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        const exponential_distribution<RealT,PolicyT> exp(rates[i]);\r\n\r\n        result += probs[i]*cdf(complement(exp, x));\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT quantile(complemented2_type<hyperexponential_distribution<RealT, PolicyT>, RealT> const& c)\r\n{\r\n    RealT const& p = c.param;\r\n    hyperexponential_distribution<RealT,PolicyT> const& dist = c.dist;\r\n\r\n    return hyperexp_detail::quantile_impl(dist, p , true);\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT mean(hyperexponential_distribution<RealT, PolicyT> const& dist)\r\n{\r\n    RealT result = 0;\r\n\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        const exponential_distribution<RealT,PolicyT> exp(rates[i]);\r\n\r\n        result += probs[i]*mean(exp);\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT variance(hyperexponential_distribution<RealT, PolicyT> const& dist)\r\n{\r\n    RealT result = 0;\r\n\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        result += probs[i]/(rates[i]*rates[i]);\r\n    }\r\n\r\n    const RealT mean = boost::math::mean(dist);\r\n\r\n    result = 2*result-mean*mean;\r\n\r\n    return result;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT skewness(hyperexponential_distribution<RealT,PolicyT> const& dist)\r\n{\r\n    BOOST_MATH_STD_USING\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    RealT s1 = 0; // \\sum_{i=1}^n \\frac{p_i}{\\lambda_i}\r\n    RealT s2 = 0; // \\sum_{i=1}^n \\frac{p_i}{\\lambda_i^2}\r\n    RealT s3 = 0; // \\sum_{i=1}^n \\frac{p_i}{\\lambda_i^3}\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        const RealT p = probs[i];\r\n        const RealT r = rates[i];\r\n        const RealT r2 = r*r;\r\n        const RealT r3 = r2*r;\r\n\r\n        s1 += p/r;\r\n        s2 += p/r2;\r\n        s3 += p/r3;\r\n    }\r\n\r\n    const RealT s1s1 = s1*s1;\r\n\r\n    const RealT num = (6*s3 - (3*(2*s2 - s1s1) + s1s1)*s1);\r\n    const RealT den = (2*s2 - s1s1);\r\n\r\n    return num / pow(den, static_cast<RealT>(1.5));\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT kurtosis(hyperexponential_distribution<RealT,PolicyT> const& dist)\r\n{\r\n    const std::size_t n = dist.num_phases();\r\n    const std::vector<RealT> probs = dist.probabilities();\r\n    const std::vector<RealT> rates = dist.rates();\r\n\r\n    RealT s1 = 0; // \\sum_{i=1}^n \\frac{p_i}{\\lambda_i}\r\n    RealT s2 = 0; // \\sum_{i=1}^n \\frac{p_i}{\\lambda_i^2}\r\n    RealT s3 = 0; // \\sum_{i=1}^n \\frac{p_i}{\\lambda_i^3}\r\n    RealT s4 = 0; // \\sum_{i=1}^n \\frac{p_i}{\\lambda_i^4}\r\n    for (std::size_t i = 0; i < n; ++i)\r\n    {\r\n        const RealT p = probs[i];\r\n        const RealT r = rates[i];\r\n        const RealT r2 = r*r;\r\n        const RealT r3 = r2*r;\r\n        const RealT r4 = r3*r;\r\n\r\n        s1 += p/r;\r\n        s2 += p/r2;\r\n        s3 += p/r3;\r\n        s4 += p/r4;\r\n    }\r\n\r\n    const RealT s1s1 = s1*s1;\r\n\r\n    const RealT num = (24*s4 - 24*s3*s1 + 3*(2*(2*s2 - s1s1) + s1s1)*s1s1);\r\n    const RealT den = (2*s2 - s1s1);\r\n\r\n    return num/(den*den);\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT kurtosis_excess(hyperexponential_distribution<RealT,PolicyT> const& dist)\r\n{\r\n    return kurtosis(dist) - 3;\r\n}\r\n\r\ntemplate <typename RealT, typename PolicyT>\r\nRealT mode(hyperexponential_distribution<RealT,PolicyT> const& /*dist*/)\r\n{\r\n    return 0;\r\n}\r\n\r\n}} // namespace boost::math\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning (pop)\r\n#endif\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#include <boost/math/distributions/detail/generic_quantile.hpp>\r\n\r\n#endif // BOOST_MATH_DISTRIBUTIONS_HYPEREXPONENTIAL\r\n", "meta": {"hexsha": "33e782a982d2e3f41d45f13566497b1b4a1bcbf7", "size": 22522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/distributions/hyperexponential.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/hyperexponential.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/hyperexponential.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": 35.4119496855, "max_line_length": 175, "alphanum_fraction": 0.5931533612, "num_tokens": 5400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.04672495945574692, "lm_q1q2_score": 0.022086116280491227}}
{"text": "\n// The quad_float module is derived from the doubledouble\n// library originally developed by Keith Briggs:\n//    http://keithbriggs.info/doubledouble.html\n// I attach the original copyright notice.\n\n\n/*\n\nCopyright (C) 1997 Keith Martin Briggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n*/\n\n// The configure script tries to prevent this, but we\n// double check here.  Note that while it is strongly \n// discouraged, other parts of NTL probably work even with \n// \"fast math\"; however, quad_float will definitely break.\n\n#if (defined(__GNUC__) && __FAST_MATH__)\n#error \"do not compile quad_float.cpp with -ffast-math!!\"\n#endif\n\n// The configure script should define NTL_FP_CONTRACT_OFF\n// for icc via the NOCONTRACT variable\n#ifdef NTL_FP_CONTRACT_OFF\n#pragma fp_contract(off)\n#endif\n\n#if 0\n// The configure script should ensure that all NTL files\n// are compiled with --fp-model precise on icc.\n#ifdef __INTEL_COMPILER\n#pragma float_control(precise,on)\n#endif\n#endif\n\n#include <NTL/quad_float.h>\n#include <cfloat>\n\n\nNTL_START_IMPL\n\n#if (NTL_EXT_DOUBLE && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))\n\n#if (!defined(NTL_X86_FIX) && !defined(NTL_NO_X86_FIX))\n\n#define NTL_X86_FIX\n\n#endif\n\n#endif\n\n\n#if (NTL_EXT_DOUBLE && !defined(NTL_X86_FIX))\n\n#define DOUBLE volatile double\n\n#else\n\n#define DOUBLE double\n\n#endif\n\n\n#ifdef NTL_X86_FIX\n\n\n#define START_FIX \\\n  unsigned short __old_cw, __new_cw; \\\n  __asm__ volatile (\"fnstcw %0\":\"=m\" (__old_cw)::\"memory\"); \\\n  __new_cw = (__old_cw & ~0x300) | 0x200; \\\n  __asm__ volatile (\"fldcw %0\"::\"m\" (__new_cw):\"memory\");\n\n\n#define END_FIX  __asm__ volatile (\"fldcw %0\": :\"m\" (__old_cw));\n\n// NOTE: \"asm volatile\" does not guarantee that the asm does \n// not move.  However, the \"memory\" clobber makes these\n// memory barriers that cannot move past a load/store\n\n#define NO_INLINE __attribute__ ((noinline))\n// to protect against LTO inlining which could break the memory\n// barriers in START_FIX and END_FIX.  I've done some testing\n// on gcc, clang, and icc.  The noinline attribute and the volatile\n// asm together should ensure that the function gets called\n// and doesn't get inlined during LTO.\n// That said, I wouln't really recommend applying LTO to NTL...\n// and especially to quad_float.cpp.\n\n\n// NOTE: gcc 8.1 seems a bit buggy: it warns when overloading a function\n// with different inline atrributes.  Earlier versions are fine.\n// ICC and CLANG are fine.\n\n// NOTE: starting with gcc 8.1, there is a function attribute called\n// \"noipa\" which really does exactly what I want.  It would also be useful\n// for ForceToMem, for example.  \n\n#else\n\n#define START_FIX\n#define END_FIX\n\n#define NO_INLINE\n\n#endif\n\n\n\n\nNO_INLINE void quad_float_normalize(quad_float& z, const double& xhi, const double& xlo)\n{\nSTART_FIX\n   DOUBLE u, v;\n\n   u = xhi + xlo; \n   v = xhi - u;    \n   v = v + xlo;    \n\n   z.hi = u;\n   z.lo = v;\nEND_FIX\n}\n\nNO_INLINE void quad_float_in_place_add(quad_float& x, const quad_float& y ) {\nSTART_FIX\n        DOUBLE    H, h, T, t, S, s, e, f;\n        DOUBLE    t1;\n\n        S = x.hi + y.hi;\n        T = x.lo + y.lo;\n        e = S - x.hi;\n        f = T - x.lo;\n\n        t1 = S-e;\n        t1 = x.hi-t1;\n        s = y.hi-e;\n        s = s + t1;\n        \n        t1 = T-f;\n        t1 = x.lo-t1;\n        t = y.lo-f;\n        t = t + t1;\n\n\n        s = s + T;\n        H = S + s;\n        h = S - H;\n        h = h + s;\n\n        h = h + t;\n        e = H + h; \n        f = H - e;\n        f = f + h;\n\n        x.hi = e;\n        x.lo = f;\nEND_FIX\n}\n\n\nNO_INLINE void quad_float_in_place_sub(quad_float& x, const quad_float& y ) {\nSTART_FIX\n        DOUBLE    H, h, T, t, S, s, e, f;\n        DOUBLE    t1, yhi, ylo;\n\n        yhi = -y.hi;\n        ylo = -y.lo;\n\n        S = x.hi + yhi;\n        T = x.lo + ylo;\n        e = S - x.hi;\n        f = T - x.lo;\n\n        t1 = S-e;\n        t1 = x.hi-t1;\n        s = yhi-e;\n        s = s + t1;\n        \n        t1 = T-f;\n        t1 = x.lo-t1;\n        t = ylo-f;\n        t = t + t1;\n\n\n        s = s + T;\n        H = S + s;\n        h = S - H;\n        h = h + s;\n\n        h = h + t;\n        e = H + h; \n        f = H - e;\n        f = f + h;\n\n        x.hi = e;\n        x.lo = f;\nEND_FIX\n}\n\nNO_INLINE void quad_float_in_place_negate(quad_float& x)\n{\nSTART_FIX\n   DOUBLE xhi, xlo, u, v;\n\n   xhi = -x.hi;\n   xlo = -x.lo;\n\n   // it is a good idea to renormalize here, just in case\n   // the rounding rule depends on sign, and thus we will\n   // maintain the \"normal form\" for quad_float's.\n  \n   u = xhi + xlo;\n   v = xhi - u;\n   v = v + xlo;\n\n   x.hi = u;\n   x.lo = v;\nEND_FIX\n}\n\n\n\n#if (NTL_FMA_DETECTED && !defined(NTL_CONTRACTION_FIXED))\n\n\n// The configure script should ensure that no FMA's are issued\n// fo most compilers (at least gcc, clang, and icc), but if not,\n// this is a last ditch effort to fix the problem (which seems to work).\n\ndouble quad_float_zero = 0;\n\nstatic inline\ndouble Protect(double x) { return x + quad_float_zero; }\n\n#else\n\n\nstatic inline\ndouble Protect(double x) { return x; }\n\n\n#endif\n\n\n\n\nNO_INLINE void quad_float_in_place_mul(quad_float& x,const quad_float& y ) {\nSTART_FIX\n  DOUBLE hx, tx, hy, ty, C, c;\n  DOUBLE t1, t2;\n\n  C = Protect(NTL_QUAD_FLOAT_SPLIT*x.hi);\n  hx = C-x.hi;\n  c = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);\n  hx = C-hx;\n  tx = x.hi-hx;\n  hy = c-y.hi;\n  C = Protect(x.hi*y.hi);\n  hy = c-hy;\n  ty = y.hi-hy;\n\n  // c = ((((hx*hy-C)+hx*ty)+tx*hy)+tx*ty)+(x.hi*y.lo+x.lo*y.hi);\n  \n  t1 = Protect(hx*hy);\n  t1 = t1-C;\n  t2 = Protect(hx*ty);\n  t1 = t1+t2;\n  t2 = Protect(tx*hy);\n  t1 = t1+t2;\n  t2 = Protect(tx*ty);\n  c = t1+t2;\n  t1 = Protect(x.hi*y.lo);\n  t2 = Protect(x.lo*y.hi);\n  t1 = t1+t2;\n  c = c + t1;\n\n\n  hx = C+c;\n  tx = C-hx;\n  tx = tx+c;\n\n  x.hi = hx;\n  x.lo = tx;\nEND_FIX\n}\n\n\nNO_INLINE void quad_float_in_place_div(quad_float& x, const quad_float& y ) {\nSTART_FIX\n  DOUBLE hc, tc, hy, ty, C, c, U, u;\n  DOUBLE t1;\n\n  C = x.hi/y.hi;\n  c = Protect(NTL_QUAD_FLOAT_SPLIT*C);\n  hc = c-C;\n  u = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);\n  hc = c-hc;\n  tc = C-hc;\n  hy = u-y.hi;\n  U = Protect(C * y.hi);\n  hy = u-hy;\n  ty = y.hi-hy;\n\n  // u = (((hc*hy-U)+hc*ty)+tc*hy)+tc*ty;\n\n  u = Protect(hc*hy);\n  u = u-U;\n  t1 = Protect(hc*ty);\n  u = u+t1;\n  t1 = Protect(tc*hy);\n  u = u+t1;\n  t1 = Protect(tc*ty);\n  u = u+t1;\n\n  // c = ((((x.hi-U)-u)+x.lo)-C*y.lo)/y.hi;\n\n  c = x.hi-U;\n  c = c-u;\n  c = c+x.lo;\n  t1 = Protect(C*y.lo);\n  c = c - t1;\n  c = c/y.hi;\n  \n  hy = C+c;\n  ty = C-hy;\n  ty = ty+c;\n\n  x.hi = hy;\n  x.lo = ty;\nEND_FIX\n}\n\n\nNO_INLINE void quad_float_in_place_sqrt(quad_float& y, double& c_ref) {\nSTART_FIX\n  DOUBLE c = c_ref;\n  DOUBLE p,q,hx,tx,u,uu,cc;\n  DOUBLE t1;\n\n  p = Protect(NTL_QUAD_FLOAT_SPLIT*c); \n  hx = (c-p); \n  hx = hx+p; \n  tx = c-hx;\n  p = Protect(hx*hx);\n  q = Protect(hx*tx);\n  q = q+q;\n\n  u = p+q;\n  uu = p-u;\n  uu = uu+q;\n  t1 = Protect(tx*tx);\n  uu = uu+t1;\n\n\n  cc = y.hi-u;\n  cc = cc-uu;\n  cc = cc+y.lo;\n  t1 = c+c;\n  cc = cc/t1;\n\n  hx = c+cc;\n  tx = c-hx;\n  tx = tx+cc;\n\n  y.hi = hx;\n  y.lo = tx;\nEND_FIX\n}\n\n\nNO_INLINE void quad_float_PrecisionOK(long& res, const double& one)\n{\nSTART_FIX\n   long k;\n   DOUBLE l1 = one;\n   DOUBLE lh = one/double(2);\n   DOUBLE epsilon;\n   DOUBLE fudge, oldfudge;\n\n   epsilon = l1;\n   fudge = l1+l1;\n\n   k = 0;\n\n   do {\n      k++;\n      epsilon = epsilon * lh;\n      oldfudge = fudge;\n      fudge = l1 + epsilon;\n   } while (fudge > l1 && fudge < oldfudge);\n\n   res = (k == NTL_DOUBLE_PRECISION);\nEND_FIX\n}\n\n\n\n\nNTL_END_IMPL\n\n", "meta": {"hexsha": "9a7ed15ff0aa41f97f2099ee61e06b04f9b30aee", "size": 8083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/quad_float.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": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T06:14:16.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/quad_float.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T22:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T10:03:13.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/quad_float.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T07:59:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-17T10:27:23.000Z", "avg_line_length": 19.4302884615, "max_line_length": 88, "alphanum_fraction": 0.6029939379, "num_tokens": 2664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.0510827411103255, "lm_q1q2_score": 0.021973105647103548}}
{"text": "#pragma once\n\n#include \"tags/QF_BV.hpp\"\n#include \"result_wrapper.hpp\"\n\n#include <boost/mpl/vector.hpp>\n#include <boost/proto/core.hpp>\n#include <boost/variant.hpp>\n#include <boost/any.hpp>\n#include <boost/foreach.hpp>\n#include <boost/tuple/tuple.hpp>\n\nnamespace metaSMT {\n  namespace proto = boost::proto;\n  namespace bvtags = ::metaSMT::logic::QF_BV::tag;\n  namespace predtags = ::metaSMT::logic::tag;\n\n  // Forward declaration\n  struct addclause_cmd;\n  namespace features\n  {\n    struct addclause_api;\n  }\n\n  template <typename PredicateSolver>\n  struct BitBlast {\n    typedef BitBlast<PredicateSolver> this_type;\n\n    typedef typename PredicateSolver::result_type result_base;\n    typedef std::vector< result_base >  bv_result;\n\n    typedef typename boost::mpl::vector2<\n      result_base, bv_result\n    >::type result_types_vec;\n\n    typedef typename boost::make_variant_over< result_types_vec >::type \n      result_type;\n      \n    typedef boost::tuple<uint64_t, unsigned>  bvuint_tuple;\n    typedef boost::tuple< int64_t, unsigned>  bvsint_tuple;\n    \n        void assertion( result_type e ) { \n          _solver.assertion( boost::get<result_base>(e) );\n        }\n\n        void assumption( result_type e ) { \n          _solver.assumption( boost::get<result_base>(e) );\n        }\n        \n        unsigned get_bv_width( result_type const &e ) {\n          try {\n            return boost::get<bv_result>(e).size();\n          } catch ( boost::bad_get ) {\n            return 0;\n          }\n        }\n\n        bool solve() {\n          return _solver.solve();\n        }\n\n        result_type operator() (bvtags::var_tag var, boost::any arg ) {\n          //printf(\"bitvec\\n\");\n          bv_result ret(var.width);\n          for (unsigned i = 0; i < var.width; ++i) {\n            ret[i]= _solver(predtags::var_tag(), arg);\n          }\n          return ret;\n        }\n\n        result_type operator() ( bvtags::bvand_tag , result_type arg1, result_type arg2 ) \n        {\n          //printf(\"bvand\\n\");\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          bv_result ret(a.size());\n          predtags::and_tag and_;\n\n          for (unsigned i = 0; i < a.size(); ++i) {\n            ret[i]= _solver(and_, a[i], b[i]);\n          }\n          return ret;\n        }\n        \n        \n        result_type operator() ( bvtags::bvnand_tag , result_type arg1, result_type arg2 ) \n        {\n          //printf(\"bvnand\\n\");\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          bv_result ret(a.size());\n          predtags::nand_tag nand_;\n\n          for (unsigned i = 0; i < a.size(); ++i) {\n            ret[i]= _solver(nand_, a[i], b[i]);\n          }\n          return ret;\n        }\n        \n        result_type operator() ( bvtags::bvor_tag , result_type arg1, result_type arg2 ) \n        {\n          //printf(\"bvor\\n\");\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          bv_result ret(a.size());\n          predtags::or_tag or_;\n\n          for (unsigned i = 0; i < a.size(); ++i) {\n            ret[i]= _solver(or_, a[i], b[i]);\n          }\n          return ret;\n        }\n      \n        result_type operator() ( bvtags::bvnor_tag , result_type arg1, result_type arg2 ) \n        {\n          //printf(\"bvnor\\n\");\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          bv_result ret(a.size());\n          predtags::nor_tag tag_;\n\n          for (unsigned i = 0; i < a.size(); ++i) {\n            ret[i]= _solver(tag_, a[i], b[i]);\n          }\n          return ret;\n        }\n           \n        result_type operator() ( bvtags::bvnot_tag , result_type arg1 ) \n        {\n         //printf(\"bvnot\\n\");\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result ret(a.size());\n          predtags::not_tag not_;\n          \n          for (unsigned i = 0; i < a.size(); ++i) {\n            ret[i] = _solver(not_,a[i]);\n          }\n          return ret;\n        }\n       \n       \n       result_type operator() ( bvtags::bvxor_tag , result_type arg1, result_type arg2 ) \n       {\n          //printf(\"bvxor\\n\");\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          bv_result ret(a.size());\n          predtags::xor_tag xor_;\n\n          for (unsigned i = 0; i < a.size(); ++i) {\n            ret[i]= _solver(xor_, a[i], b[i]);\n          }\n          return ret;\n       }\n       \n       result_type operator() ( bvtags::bvxnor_tag , result_type arg1, result_type arg2 ) \n       {\n          //printf(\"bvxnor\\n\");\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          bv_result ret(a.size());\n          predtags::xnor_tag xnor_;\n\n          for (unsigned i = 0; i < a.size(); ++i) {\n            ret[i]= _solver(xnor_, a[i], b[i]);\n          }\n          return ret;\n        }\n      \n      \n       result_type operator() (bvtags::bvult_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          \n          result_base not_a = _solver(predtags::not_tag(), *ai);\n          result_base ret = _solver(predtags::and_tag(),not_a, *bi);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n         \n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            not_a = _solver(predtags::not_tag(), *ai);\n            result_base now_less = _solver(predtags::and_tag(),not_a, *bi);\n            result_base now   = _solver(predtags::and_tag(), equal, now_less);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          return ret;\n       }\n       \n       result_type operator() (bvtags::bvugt_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          \n          result_base not_b = _solver(predtags::not_tag(), *bi);\n          result_base ret = _solver(predtags::and_tag(), *ai, not_b);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n         \n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            not_b = _solver(predtags::not_tag(), *bi);\n            result_base now_great = _solver(predtags::and_tag(),*ai, not_b);\n            result_base now   = _solver(predtags::and_tag(), equal, now_great);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          return ret;\n       }\n       \n       result_type operator() (bvtags::bvsgt_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          result_base not_a = _solver(predtags::not_tag(), *ai);\n          result_base not_b = _solver(predtags::not_tag(), *bi);\n          result_base ret = _solver(predtags::and_tag(), not_a, *bi);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n         \n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            not_b = _solver(predtags::not_tag(), *bi);\n            \n            result_base now_great = _solver(predtags::and_tag(),*ai, not_b);\n            result_base now   = _solver(predtags::and_tag(), equal, now_great);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          return ret;\n       }\n       \n\n        result_type operator() (bvtags::bvslt_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          result_base not_a = _solver(predtags::not_tag(), *ai);\n          result_base not_b = _solver(predtags::not_tag(), *bi);\n          result_base ret = _solver(predtags::and_tag(), *ai, not_b);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n         \n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            not_a = _solver(predtags::not_tag(), *ai);\n            result_base now_less = _solver(predtags::and_tag(),not_a, *bi);\n            result_base now   = _solver(predtags::and_tag(), equal, now_less);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          return ret;\n       }\n       \n       \n        result_type operator() (bvtags::bvule_tag, result_type arg1, result_type arg2)\n        {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          result_base not_a = _solver(predtags::not_tag(), *ai);\n        //  result_base not_b = _solver(predtags::not_tag(), *bi);\n          result_base less = _solver(predtags::and_tag(), not_a, *bi);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n          result_base ret = less; \n          \n          \n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            not_a = _solver(predtags::not_tag(), *ai);\n            result_base now_less = _solver(predtags::and_tag(),not_a, *bi);\n            result_base now   = _solver(predtags::and_tag(), equal, now_less);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          ret = _solver(predtags::or_tag(), ret, equal);\n          return ret;\n        }\n        \n        \n\n\n        result_type operator() (bvtags::bvuge_tag, result_type arg1, result_type arg2)\n        {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          result_base not_b = _solver(predtags::not_tag(), *bi);\n        //  result_base not_b = _solver(predtags::not_tag(), *bi);\n          result_base great = _solver(predtags::and_tag(), *ai, not_b);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n          result_base ret = great;\n\n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            not_b = _solver(predtags::not_tag(), *bi);\n            result_base now_great = _solver(predtags::and_tag(),*ai, not_b);\n            result_base now   = _solver(predtags::and_tag(), equal, now_great);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          ret = _solver(predtags::or_tag(), ret, equal);\n          return ret;\n        }\n       \n       result_type operator() (bvtags::bvsge_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          result_base not_a = _solver(predtags::not_tag(), *ai);\n          result_base not_b = _solver(predtags::not_tag(), *bi);\n          result_base great = _solver(predtags::and_tag(), not_a, *bi);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n          result_base ret = great;\n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            not_b = _solver(predtags::not_tag(), *bi);\n            result_base now_great = _solver(predtags::and_tag(),*ai, not_b);\n            result_base now   = _solver(predtags::and_tag(), equal, now_great);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          ret = _solver(predtags::or_tag(), ret, equal);\n          return ret;\n       }\n       \n\n        result_type operator() (bvtags::bvsle_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          assert(a.size()>0);\n          \n          typename bv_result::reverse_iterator ai, bi, end;\n          ai = a.rbegin();\n          bi = b.rbegin();\n          end= a.rend();\n                  \n          result_base not_b = _solver(predtags::not_tag(), *bi);\n          result_base less = _solver(predtags::and_tag(), *ai, not_b);  \n          result_base equal = _solver(predtags::xnor_tag(), *ai, *bi);\n          result_base ret = less;\n\n          for (++ai, ++bi ; ai != end; ++ai, ++bi) \n          {\n            result_base not_a = _solver(predtags::not_tag(), *ai);\n            result_base now_less = _solver(predtags::and_tag(),not_a, *bi);\n            result_base now   = _solver(predtags::and_tag(), equal, now_less);\n            \n            result_base now_equal = _solver(predtags::xnor_tag(), *ai, *bi);\n            equal = _solver(predtags::and_tag(), now_equal, equal);\n\n            ret = _solver(predtags::or_tag(), ret, now);\n          }\n          ret = _solver(predtags::or_tag(), ret, equal);\n          return ret;\n       }\n       \n        result_type operator() (bvtags::bvadd_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          assert(a.size()==b.size());\n          \n          bv_result ret(a.size());\n          \n          result_base carry = _solver(predtags::false_tag(), boost::any());\n          \n          result_base xor1, or1, and1, and2;\n         \n          for (unsigned i = 0; i < a.size(); ++i) {\n              \n              xor1 = _solver(predtags::xor_tag(), a[i], b[i]);\n              ret[i] = _solver(predtags::xor_tag(), xor1, carry);\n              \n              // a&b | c&(a|b) \n              and1 = _solver(predtags::and_tag(), a[i], b[i]);\n              or1  = _solver(predtags::or_tag(),a[i],b[i]);\n              and2 = _solver(predtags::and_tag(),carry, or1);\n              carry  = _solver(predtags::or_tag(), and1, and2);\n                          \n            }\n          return ret;\n       }\n\n       result_type operator() (bvtags::bvmul_tag, result_type arg1, result_type arg2)\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n          result_type ret = bv_result (a.size(), _solver( predtags::false_tag(), boost::any() ) );\n          result_type tmp1;\n          \n          for(unsigned i = 0 ; i < a.size() ; ++i)\n          {\n            tmp1 = (*this)(bvtags::sign_extend_tag(),a.size()-1,bv_result(1,a[i]));\n            tmp1 = (*this)(bvtags::bvand_tag(),arg2,tmp1);\n            tmp1 = shiftL( boost::get<bv_result>(tmp1),i);\n            \n            ret = (*this)(bvtags::bvadd_tag(),ret,tmp1);\n          }\n          return ret;\n       }\n     \n       result_type operator() ( bvtags::bvneg_tag, result_type arg1 )\n       {\n       \n          bv_result a = boost::get<bv_result>(arg1);\n          \n          bv_result tmp1(a.size(),_solver(predtags::false_tag(),boost::any()));\n          tmp1.front()= _solver(predtags::true_tag(), boost::any());\n          result_type tmp2 = (*this)(bvtags::bvnot_tag(), arg1);\n          \n          return (*this)(bvtags::bvadd_tag(),tmp2,tmp1);\n       }\n       \n       result_type operator() ( bvtags::bvudiv_tag, result_type arg1, result_type arg2 )\n       {\n            return uDivRem(arg1,arg2,true);\n       }\n   \n       result_type operator() ( bvtags::bvsdiv_tag, result_type arg1, result_type arg2 )\n       {\n        return sDivRem(arg1,arg2,true); \n       }\n\n       result_type operator() ( bvtags::bvsrem_tag, result_type arg1, result_type arg2 )\n       {\n        return sDivRem(arg1,arg2,false); \n       }\n     \n     result_type operator() ( bvtags::bvhex_tag , boost::any arg )\n       {\n               std::string str = boost::any_cast<std::string>(arg);\n               result_base _0 = _solver(predtags::false_tag(),boost::any());               \n               result_base _1 = _solver(predtags::true_tag(),boost::any());               \n               bv_result ret(str.size()*4,_0);\n               typename bv_result::iterator iter = ret.begin();\n          \n          BOOST_REVERSE_FOREACH( const char c, str) {\n            switch ( c ) {\n              case '0':\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _0;                \n               break;\n              case '1':\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _0;                \n               break;\n              case '2':\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _0;              \n               break;\n              case '3':\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _0;                \n               break;\n              case '4':\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _0;                \n               break;\n              case '5':\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _0;                \n               break;\n              case '6':\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _0;                \n               break;\n              case '7':\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _0;                \n               break;\n              case '8':\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _1;                \n               break;\n              case '9':\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _1;                \n               break;\n              case 'a':\n              case 'A':\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _1;                \n               break;\n              case 'b':\n              case 'B':\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _1;                \n               break;\n              case 'c':\n              case 'C':\n                *(iter++) = _0;\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _1;                \n               break;\n              case 'd':\n              case 'D':\n                *(iter++) = _1;\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _1;                \n               break;\n              case 'e':\n              case 'E':\n                *(iter++) = _0;\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _1;                \n               break;\n              case 'f':\n              case 'F':\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _1;\n                *(iter++) = _1;                  \n               break;                        \n             }   \n          }\n          \n          return ret;\n          \n       }\n      \n       result_type operator() ( bvtags::bvurem_tag, result_type arg1, result_type arg2 )\n       {\n            return uDivRem(arg1,arg2, false);\n       }\n            \n       result_type operator() ( bvtags::bvsub_tag, result_type arg1, result_type arg2 )\n       {\n          result_type tmp ((*this)(bvtags::bvneg_tag(), arg2));\n                          \n           return (*this)(bvtags::bvadd_tag(), arg1,tmp);\n       }\n\n     result_type operator() ( bvtags::bvcomp_tag, result_type arg1, result_type arg2 )\n       {\n          result_type tmp = (*this)(predtags::equal_tag(), arg1,arg2);\n          \n          result_base ret = boost::get<result_base>(tmp);\n                     \n          return bv_result(1,ret);\n       }\n\n       result_type operator() ( bvtags::zero_extend_tag, unsigned width, result_type arg1 )\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result tmp(a.size()+width,_solver(predtags::false_tag(),boost::any()));\n          \n          std::copy(a.begin(), a.end(), tmp.begin());\n          return tmp;\n       }\n       \n       result_type operator() ( bvtags::sign_extend_tag, unsigned width, result_type arg1 )\n       {\n          bv_result a = boost::get<bv_result>(arg1);\n          assert(!a.empty());\n          bv_result tmp(a.size()+width, a.back());\n          \n          std::copy(a.begin(), a.end(), tmp.begin());\n          return tmp;\n       }\n       \n\n       result_type operator() ( predtags::equal_tag eq, result_type arg1, result_type arg2 ) \n       {\n          result_base ret;\n          //printf(\"try to compare bv\\n\");\n          try {\n            //printf(\"read arg1\\n\");\n            bv_result a = boost::get<bv_result>(arg1);\n            //printf(\"read arg2\\n\");\n            bv_result b = boost::get<bv_result>(arg2);\n            assert(a.size()==b.size());\n            ret = _solver(predtags::true_tag(), boost::any());\n            for (unsigned i = 0; i < a.size(); ++i) {\n              result_base cur = _solver(eq, a[i], b[i]);\n              ret = _solver(predtags::and_tag(), cur, ret);\n            }\n          } catch (boost::bad_get) {\n            //printf(\"try to compare bool\\n\");\n            //printf(\"read arg1\\n\");\n            result_base a = boost::get<result_base>(arg1);\n            //printf(\"read arg2\\n\");\n            result_base b = boost::get<result_base>(arg2);\n            ret = _solver(eq, a, b);\n          }\n          //printf(\"compare done\\n\");\n          return ret;\n       }\n\n       result_type operator() ( predtags::nequal_tag neq, result_type arg1, result_type arg2 ) \n       {\n          result_base ret;\n          //printf(\"try to compare bv\\n\");\n          try {\n            //printf(\"read arg1\\n\");\n            bv_result a = boost::get<bv_result>(arg1);\n            //printf(\"read arg2\\n\");\n            bv_result b = boost::get<bv_result>(arg2);\n            assert(a.size()==b.size());\n            ret = _solver(predtags::false_tag(), boost::any());\n            for (unsigned i = 0; i < a.size(); ++i) {\n              result_base cur = _solver(neq, a[i], b[i]);\n              ret = _solver(predtags::or_tag(), cur, ret);\n            }\n          } catch (boost::bad_get) {\n            //printf(\"try to compare bool\\n\");\n            //printf(\"read arg1\\n\");\n            result_base a = boost::get<result_base>(arg1);\n            //printf(\"read arg2\\n\");\n            result_base b = boost::get<result_base>(arg2);\n            ret = _solver(neq, a, b);\n          }\n          //printf(\"compare done\\n\");\n          return ret;\n       }\n\n        \n        result_type operator() (bvtags::bvbin_tag , boost::any arg ) {\n          //printf(\"bvbin\\n\");\n          std::string value = boost::any_cast<std::string>(arg);\n          bv_result ret (value.size());\n          result_base one  = _solver(predtags::true_tag (), boost::any());\n          result_base zero = _solver(predtags::false_tag(), boost::any());\n          std::string::reverse_iterator vite = value.rbegin();\n          typename bv_result::iterator rite = ret.begin();\n          for (unsigned i = 0; i < value.size(); ++i) {\n            *rite = (*vite)=='1' ? one : zero;\n            ++rite;\n            ++vite;\n          }\n          return ret;\n        }\n        \n        result_type operator() (bvtags::bvuint_tag , boost::any arg ) {\n          uint64_t value;\n          unsigned width;\n          boost::tie(value, width) = boost::any_cast<bvuint_tuple>(arg);\n        \n          bv_result ret (width);\n          result_base one  = _solver(predtags::true_tag (), boost::any());\n          result_base zero = _solver(predtags::false_tag(), boost::any());\n          for (unsigned i = 0; i < width; ++i) {\n            ret[i] = (value & 1) ? one : zero;\n            value >>=1;\n          }\n          return ret;\n        }\n\n        result_type operator() (bvtags::bvsint_tag , boost::any arg ) {\n          int64_t value;\n          unsigned width;\n          boost::tie(value, width) = boost::any_cast<bvsint_tuple>(arg);\n        \n          bv_result ret (width);\n          result_base one  = _solver(predtags::true_tag (), boost::any());\n          result_base zero = _solver(predtags::false_tag(), boost::any());\n          for (unsigned i = 0; i < width; ++i) {\n            ret[i] = (value & 1) ? one : zero;\n            value >>=1;\n          }\n          return ret;\n        }\n       \n        \n        result_type operator() (bvtags::bit0_tag , boost::any arg ) {\n          //printf(\"bit0\\n\");\n          return bv_result(1,_solver(predtags::false_tag(), arg));\n        }\n\n        result_type operator() (bvtags::bit1_tag , boost::any arg ) {\n          //printf(\"bit1\\n\");\n          return bv_result(1,_solver(predtags::true_tag(), arg));\n        }\n\n        result_type operator() (bvtags::bvshr_tag, result_type arg1, result_type value) {\n          bv_result a = boost::get<bv_result>(arg1);\n          \n          result_base zero = _solver(predtags::false_tag(),boost::any());\n          result_type ret = bv_result(a.size(), zero);\n          predtags:: ite_tag ite;\n          \n          for(unsigned i = 0; i < a.size(); ++i)\n          {\n            result_type index = (*this)(bvtags::bvuint_tag()\n                ,boost::any(bvuint_tuple(i, a.size())));\n            ret = (*this)(ite, \n                (*this)(predtags::equal_tag(), value, index)\n              , shiftR(a, i, zero)\n              , ret\n            );\n          }\n         \n          return ret; \n        }\n      \n        result_type operator() (bvtags::bvshl_tag, result_type arg1, result_type value ) {\n          \n          bv_result a = boost::get<bv_result>(arg1);\n          \n          result_type ret = bv_result(a.size(), _solver(predtags::false_tag(), boost::any()));\n          predtags:: ite_tag ite;\n          \n          for(unsigned i = 0; i < a.size(); ++i)\n          {\n            result_type index = (*this)(bvtags::bvuint_tag()\n                ,boost::any(bvuint_tuple(i, a.size())));\n            ret = (*this)(ite, \n                (*this)(predtags::equal_tag(), value, index)\n              , shiftL(a, i)\n              , ret\n            );\n          }\n          return ret;         \n        }\n        \n        result_type operator() (bvtags::bvashr_tag, result_type arg1, result_type value ) {\n        bv_result a = boost::get<bv_result>(arg1);\n          \n \n          result_type ret = bv_result(a.size(), a.back());\n          predtags:: ite_tag ite;\n          \n          for(unsigned i = 0; i < a.size(); ++i)\n          {\n            result_type index = (*this)(bvtags::bvuint_tag()\n                ,boost::any(bvuint_tuple(i, a.size())));\n            ret = (*this)(ite, \n                (*this)(predtags::equal_tag(), value, index)\n              , shiftR(a, i, a.back())\n              , ret\n            );\n          }\n         \n          return ret; \n        }\n        \n        \n        result_type operator() (predtags::ite_tag, result_type arg1, result_type arg2, result_type arg3 ) {\n                 \n          result_base c = boost::get<result_base>(arg1);\n          predtags::ite_tag ite;\n          \n          try {\n           bv_result a = boost::get<bv_result>(arg2);\n           bv_result b = boost::get<bv_result>(arg3);\n           bv_result ret(a.size());\n           assert(a.size()==b.size());\n          \n           for (unsigned i = 0; i < a.size(); ++i) {\n               ret[i]= _solver(ite,c,a[i],b[i]);\n           }\n          \n           return ret;\n          } \n           catch (boost::bad_get) {\n           result_base a = boost::get<result_base>(arg2);\n           result_base b = boost::get<result_base>(arg3);\n            return _solver(ite,c,a,b); \n          }\n          \n         \n        }\n\n        struct bv_getter : public boost::static_visitor<bv_result> {\n          bv_result operator() (bv_result const & bv) const {\n            return bv;\n          }\n          template <typename T>\n          bv_result operator() (T) const {\n            assert(false && \"expected bitvector here.\");\n            return bv_result();\n          }\n        };\n\n        result_type operator() (bvtags::extract_tag const & \n            , unsigned upper, unsigned lower\n            , result_type e\n        ) {\n          bv_result ret(upper-lower+1);\n          bv_result bv = boost::apply_visitor(bv_getter(), e);\n          std::copy(bv.begin()+lower, bv.begin()+upper+1, ret.begin());\n          return ret;\n        }\n\n        result_type operator() (bvtags::concat_tag const & \n            , result_type e1, result_type e2\n        ) {\n          bv_result bv1 = boost::apply_visitor(bv_getter(), e1);\n          bv_result bv2 = boost::apply_visitor(bv_getter(), e2);\n          bv_result ret(bv1.size()+bv2.size());\n          std::copy(bv2.begin(), bv2.end(), ret.begin() );\n          std::copy(bv1.begin(), bv1.end(), ret.begin() + bv2.size() );\n          return ret;\n        }\n\n        result_wrapper read_value(result_type var)\n        { \n          try {\n            return read_value(boost::get<result_base>(var)); \n          } catch ( boost::bad_get ) {\n            return read_value(boost::get<bv_result>(var)); \n          }\n        }\n\n        result_wrapper read_value(result_base var)\n        { \n          return _solver.read_value(var); \n        }\n\n        result_wrapper read_value(bv_result const & vars)\n        { \n          std::vector<boost::logic::tribool> ret(vars.size());\n          std::vector<boost::logic::tribool>::iterator it\n            = ret.begin();\n\n          for (unsigned i = 0; i < vars.size(); ++i, ++it) {\n            *it = _solver.read_value( vars[i] );\n          }\n      \n          return result_wrapper(ret);\n        }\n\n        ////////////////////////\n        // Fallback operators //\n        ////////////////////////\n\n        template <typename TagT, typename Any>\n        //boost::disable_if< boost::is_same(Any, bv_result)::type, result_type >::type\n        result_type \n        operator() (TagT tag, Any args ) {\n          try {\n            // std::cout << \"operator \" << tag << std::endl;\n           return _solver(tag, args);\n          } catch (boost::bad_get) {\n//            std::cout << \"Error bad_get in operator \" << typeid(tag).name() << std::endl;\n            throw;\n          }\n        }\n\n        template <typename TagT>\n        result_type operator() (TagT tag, result_type a ) {\n          return _solver( tag\n            , boost::get<result_base>(a)\n          );\n        }\n\n        template <typename TagT>\n        result_type operator() (TagT tag, result_type a, result_type b) {\n          try {\n          return _solver( tag\n            , boost::get<result_base>(a)\n            , boost::get<result_base>(b)\n          );\n          } catch (boost::bad_get) {\n//            std::cout << \"Error bad_get in operator \" << typeid(tag).name() << std::endl;\n            throw;\n          }\n        }\n\n        template <typename TagT>\n        result_type operator() (TagT tag, result_type a, result_type b, result_type c) {\n          try {\n          return _solver( tag\n            , boost::get<result_base>(a)\n            , boost::get<result_base>(b)\n            , boost::get<result_base>(c)\n          );\n          } catch (boost::bad_get) {\n//            std::cout << \"Error bad_get in operator \" << typeid(tag).name() << std::endl;\n            throw;\n          }\n        }\n\n      /* pseudo command */\n      void command ( BitBlast<PredicateSolver> const & ) { };\n      template<typename Command, typename Expr>\n      void command ( Command const& cmd, Expr& expr )\n      {\n        _solver.command ( cmd, expr );\n      }\n\n\n    private:\n      result_type sDivRem (result_type arg1, result_type arg2, bool value) {\n  \n        bv_result a = boost::get<bv_result>(arg1);       \n        bv_result b = boost::get<bv_result>(arg2);\n         \n        predtags:: ite_tag ite;\n        predtags:: xor_tag xor_;\n        bvtags:: bvneg_tag neg;\n        \n        result_type tmp1 = (*this)(neg,arg1);\n        result_type tmp2 = (*this)(neg,arg2);\n   \n      \n        result_type aneg = (*this)(ite, a.back(), (*this)(neg,arg1),arg1);\n        result_type bneg = (*this)(ite, b.back(), (*this)(neg,arg2),arg2);\n          \n             \n        result_type test = uDivRem(aneg,bneg,value);\n            \n        test = (*this)(ite, _solver(xor_, a.back(), b.back()), (*this)(neg,test),test);\n        \n        return test;        \n      }  \n      \n    private: \n      result_type uDivRem (result_type arg1, result_type arg2, bool value) {\n        \n          bv_result a = boost::get<bv_result>(arg1);\n          bv_result b = boost::get<bv_result>(arg2);\n        \n          result_type divisor = arg2 ;\n\n          result_base zero = _solver(predtags::false_tag(), boost::any());\n          result_base one = _solver(predtags::true_tag(), boost::any());\n          \n          bv_result ret(a.size(),zero);\n          result_type checker = zero; \n          predtags::ite_tag ite;\n         /*\n         \n          bvtags:: bvand_tag and_;\n          bvtags:: bvneg_tag neg;\n                   \n        result_type ret1 = (*this)(bvtags::bvuge_tag(), a, ret);\n        result_type ret2 = (*this)(bvtags::bvuge_tag(), b, ret); \n        result_type ret3 = (*this)(bvtags::bvslt_tag(), a, ret);\n        result_type ret4 = (*this)(bvtags::bvslt_tag(), b, ret);\n                \n       result_type bneg = (*this)(ite, _solver(and_, ret1, ret4), (*this)(bvtags::bvneg_tag(),arg2),b);\n       b = boost::get<bv_result>(bneg);\n       \n       result_type aneg = (*this)(ite, _solver(and_, ret3, ret2), (*this)(bvtags::bvneg_tag(),arg1),a);\n       a = boost::get<bv_result>(aneg);\n        \n        result_type aeg = (*this)(ite, _solver(and_, ret3, ret4), (*this)(bvtags::bvneg_tag(),arg1),a);\n        a = boost::get<bv_result>(aeg);\n        \n        result_type args1 = a;\n        result_type args2 = b; \n        */  \n           for(unsigned i = 0; i < a.size(); ++i)\n          {\n             result_type tmp = b.back();\n             divisor = (*this)(ite,tmp, divisor, shiftL(b,1));\n             b = boost::get<bv_result>(divisor);\n          }\n          \n          for(unsigned i = 1; i <=a.size(); ++i)\n          {\n            result_type bef_dev = divisor;\n            result_type do_devide = (*this)(bvtags::bvuge_tag(), arg1, divisor);\n            result_type eq = (*this)(predtags::equal_tag(),bef_dev,arg2);    \n            \n             arg1 = (*this)(ite, do_devide, (*this)(bvtags::bvsub_tag(), arg1, divisor),arg1);\n       \n        \n            divisor = (*this)(ite, eq, divisor, shiftR(boost::get<bv_result>(divisor), 1, zero));    \n             \n             do_devide = (*this)(ite,checker,zero, do_devide);      \n             ret[a.size()-i] = boost::get<result_base>(do_devide);\n        \n             result_type bo = (*this)(ite,checker,shiftR(ret,1, zero),ret);\n             \n             ret = boost::get<bv_result>(bo);\n             \n             \n             checker = (*this)(ite, eq , one, checker); \n         } \n                   \n          if(value)\n          {\n            return ret;\n          }\n        \n        return arg1; \n       }\n    \n    \n    \n    \n    private:\n      result_type shiftR (bv_result a, unsigned value, result_base & x) {\n                \n        //bv_result a = boost::get<bv_result>(arg);\n        bv_result ret(a.size());\n        \n        if(value == 0)\n        {\n          return a;\n        } \n        \n        for(unsigned i= 0; i < a.size(); ++value,++i)\n        {\n          if(value < a.size())\n          {\n            ret[i] = a[value];\n          } else\n            ret[i] = x;\n        }\n       return ret; \n      } \n\n   private:\n      result_type shiftL (bv_result a, unsigned value) {\n                \n        //bv_result a = boost::get<bv_result>(arg);\n        bv_result ret(a.size());\n        \n        if(value == 0)\n        {\n          return a;\n        } \n        \n        for(unsigned i= 0; i < a.size(); ++i)\n        {\n          if( i < value)\n          {\n             ret[i] = _solver(predtags::false_tag(),boost::any());\n          } else\n             ret[i] = a[i-value];\n        }\n       return ret; \n      } \n\n    private:\n        PredicateSolver _solver;\n\n  };\n\n  namespace features {\n    /* Stack supports stack api */\n    template<typename Context>\n    struct supports< BitBlast<Context>, features::addclause_api>\n    : boost::mpl::true_ {};\n\n    /* Forward all other supported operations */\n    template<typename Context, typename Feature>\n    struct supports< BitBlast<Context>, Feature>\n    : supports<Context, Feature>::type {};\n  }\n\n\n} // namespace metaSMT \n\n//  vim: ft=cpp:ts=2:sw=2:expandtab\n", "meta": {"hexsha": "231d159bb28223986ccb487fedf72760c2565c2c", "size": 39581, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/metaSMT/BitBlast.hpp", "max_stars_repo_name": "voertler/metaSMT", "max_stars_repo_head_hexsha": "726a78e0a18e0c06faa4483e7d7af34cee055529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T10:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-29T08:39:16.000Z", "max_issues_repo_path": "src/metaSMT/BitBlast.hpp", "max_issues_repo_name": "voertler/metaSMT", "max_issues_repo_head_hexsha": "726a78e0a18e0c06faa4483e7d7af34cee055529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-08-02T10:46:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T09:17:46.000Z", "max_forks_repo_path": "src/metaSMT/BitBlast.hpp", "max_forks_repo_name": "voertler/metaSMT", "max_forks_repo_head_hexsha": "726a78e0a18e0c06faa4483e7d7af34cee055529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-08T12:55:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T14:52:45.000Z", "avg_line_length": 34.0042955326, "max_line_length": 107, "alphanum_fraction": 0.4767438923, "num_tokens": 9805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.0453525845865351, "lm_q1q2_score": 0.021967888744204935}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// Definitions corresponding to vasp_io.hpp.\n\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <boost/format.hpp>\n#include <vasp_io.hpp>\n#include <utilities.hpp>\n#include <exceptions.hpp>\n\nnamespace alma {\nstd::unique_ptr<Crystal_structure> load_POSCAR(const char* filename) {\n    std::ifstream f(filename);\n\n    if (!f) {\n        throw value_error(\"could not open file\");\n    }\n    // The first line in the file can be either a description or an\n    // element list.\n    std::string firstline;\n    std::getline(f, firstline);\n    // The next line contains a multiplicative factor.\n    double factor;\n    f >> factor;\n    factor /= 10.;\n    // The next three lines contain the lattice vectors, one per\n    // line.\n    Eigen::Matrix3d lattvec;\n\n    for (auto i = 0; i < 3; ++i)\n        for (auto j = 0; j < 3; ++j)\n            f >> lattvec(j, i);\n    lattvec *= factor;\n    // The next line can either contain an element list or a list of\n    // integers.\n    std::string line;\n    flush_istream(f);\n    std::getline(f, line);\n    std::vector<std::string> elements;\n    std::vector<int> numbers;\n    try {\n        numbers = tokenize_homogeneous_line<int>(line);\n        // The list of elements must have been in the first line.\n        elements = tokenize_homogeneous_line<std::string>(firstline);\n    }\n    catch (boost::bad_lexical_cast& e) {\n        elements = tokenize_homogeneous_line<std::string>(line);\n        // The list of integers must come next.\n        std::getline(f, line);\n        numbers = tokenize_homogeneous_line<int>(line);\n    }\n    // Next we can have \"Selective dynamics\", which we ignore.\n    std::getline(f, line);\n\n    if (starts_with_character(line, \"Ss\"))\n        std::getline(f, line);\n    // The next line tells us about the type of coordinates contained\n    // in the file: Direct or Cartesian.\n    auto cartesian = starts_with_character(line, \"CcKk\");\n    // Finally, read the coordinates.\n    auto natoms = std::accumulate(numbers.begin(), numbers.end(), 0);\n    Eigen::Matrix<double, 3, Eigen::Dynamic> positions(3, natoms);\n\n    for (int i = 0; i < natoms; ++i)\n        for (auto j = 0; j < 3; ++j)\n            f >> positions(j, i);\n\n    // Make sure that we store lattice coordinates.\n    if (cartesian)\n        positions = lattvec.colPivHouseholderQr().solve(positions);\n\n    // The code expects direct coordinates to lie in the\n    // [0.,1.) range.\n    for (int i = 0; i < natoms; ++i)\n        for (auto j = 0; j < 3; ++j) {\n            positions(j, i) = std::fmod(positions(j, i), 1.);\n\n            if (positions(j, i) < 0.)\n                positions(j, i) += 1.;\n        }\n    // Build and return the object.\n    return std::make_unique<Crystal_structure>(\n        lattvec, positions, elements, numbers);\n}\n\n\nstd::unique_ptr<Harmonic_ifcs> load_FORCE_CONSTANTS(\n    const char* filename,\n    const Crystal_structure& cell,\n    const int na,\n    const int nb,\n    const int nc) {\n    if (std::min({na, nb, nc}) <= 0)\n        throw value_error(\"na, nb and nc must be positive\");\n    std::ifstream f(filename);\n\n    if (!f) {\n        throw value_error(\"could not open file\");\n    }\n    // The first line of the file contains the number of atoms in the\n    // supercell.\n    int ntot;\n    f >> ntot;\n    auto natoms = cell.get_natoms();\n    auto ndof = 3 * natoms;\n    auto nexpected = na * nb * nc * natoms;\n\n    if (ntot != nexpected)\n        throw value_error(boost::str(\n            boost::format(\"expected %1% atoms, got %2%\") % nexpected % ntot));\n    // Then comes one block for each atom pair.\n    // This means that the file is either highly redundant or\n    // inconsistent. Here we assume the former.\n    int field;\n    std::string line;\n    Triple_int_map<Eigen::MatrixXd> matrices;\n    auto builder = Supercell_index_builder(na, nb, nc, natoms);\n\n    for (auto i = 0; i < ntot; ++i) {\n        for (auto j = 0; j < ntot; ++j) {\n            f >> field;\n            auto index1 = builder.create_index_safely(field - 1);\n            f >> field;\n            auto index2 = builder.create_index_safely(field - 1);\n\n            if ((index1.index != i) || (index2.index != j))\n                throw input_error(\"unexpected cell indices\");\n            // If there is anything else in the line, discard it.\n            std::string tmp;\n            std::getline(f, tmp);\n\n            if ((index1.ia == 0) && (index1.ib == 0) && (index1.ic == 0)) {\n                // The first unit cell is (0, 0, 0). Read and store\n                // the data.\n                auto key = index2.get_pos();\n\n                if (matrices.find(key) == matrices.end())\n                    // If the submatrix does not exist, create it.\n                    matrices[key] = Eigen::MatrixXd(ndof, ndof);\n\n                for (auto k = 0; k < 3; ++k)\n                    for (auto l = 0; l < 3; ++l)\n                        f >> matrices[key](3 * index1.iatom + k,\n                                           3 * index2.iatom + l);\n            }\n            else {\n                // Redundant block. Skip those lines.\n                flush_istream(f);\n\n                for (auto k = 0; k < 3; ++k)\n                    std::getline(f, line);\n            }\n        }\n    }\n    // Put the results into data structures that can be passed to the\n    // constructor.\n    std::vector<Triple_int> pos;\n    std::vector<Eigen::MatrixXd> ifcs;\n    std::tie(pos, ifcs) = split_keys_and_values(matrices);\n    return std::make_unique<Harmonic_ifcs>(pos, ifcs, na, nb, nc);\n}\n\n\nEigen::ArrayXXd load_FORCE_CONSTANTS_raw(const char* filename) {\n    std::ifstream f(filename);\n\n    if (!f) {\n        throw value_error(\"could not open file\");\n    }\n    std::size_t ntot;\n    f >> ntot;\n    std::size_t ndof = 3 * ntot;\n    Eigen::ArrayXXd nruter{ndof, ndof};\n\n    for (std::size_t i = 0; i < ntot; ++i) {\n        for (std::size_t j = 0; j < ntot; ++j) {\n            std::size_t index;\n            f >> index;\n\n            if (index - 1 != i)\n                throw input_error(\"unexpected index\");\n            f >> index;\n\n            if (index - 1 != j)\n                throw input_error(\"unexpected index\");\n            std::string tmp;\n            std::getline(f, tmp);\n\n            for (auto k = 0; k < 3; ++k)\n                for (auto l = 0; l < 3; ++l)\n                    f >> nruter(3 * i + k, 3 * j + l);\n        }\n    }\n    return nruter;\n}\n\n\nstd::unique_ptr<Dielectric_parameters> load_BORN(const char* filename) {\n    std::ifstream f(filename);\n\n    if (!f) {\n        throw value_error(\"could not open file\");\n    }\n    // The first line of the file contains a unit conversion factor\n    // employed by Phonopy. We ignore it.\n    std::string line;\n    std::getline(f, line);\n    // Then come the nine components of the dielectric tensor.\n    Eigen::Matrix3d epsilon;\n\n    for (auto k = 0; k < 3; ++k)\n        for (auto l = 0; l < 3; ++l)\n            f >> epsilon(k, l);\n    // And finally the born charge tensors for each atom.\n    flush_istream(f);\n    std::vector<Eigen::MatrixXd> born;\n\n    do {\n        std::getline(f, line);\n        auto fields = tokenize_homogeneous_line<double>(line);\n\n        if (fields.size() == 0) {\n            continue;\n        }\n        else if (fields.size() == 9) {\n            auto tensor = Eigen::MatrixXd(3, 3);\n\n            for (auto k = 0; k < 3; ++k)\n                for (auto l = 0; l < 3; ++l)\n                    tensor(k, l) = fields[3 * k + l];\n            born.emplace_back(tensor);\n        }\n        else {\n            throw input_error(\"wrong number of fields in a line\");\n        }\n    } while (!f.eof());\n    return std::make_unique<Dielectric_parameters>(born, epsilon);\n}\n\n\nstd::unique_ptr<std::vector<Thirdorder_ifcs>> load_FORCE_CONSTANTS_3RD(\n    const char* filename,\n    const Crystal_structure& cell) {\n    std::ifstream f(filename);\n\n    if (!f) {\n        throw value_error(\"could not open file\");\n    }\n    auto solver = cell.lattvec.colPivHouseholderQr();\n    // The first line is the number of blocks in the file.\n    std::size_t nblocks;\n    f >> nblocks;\n    auto nruter = std::make_unique<std::vector<Thirdorder_ifcs>>();\n    nruter->reserve(nblocks);\n\n    // For each block.\n    for (decltype(nblocks) iblock = 0; iblock < nblocks; ++iblock) {\n        std::size_t tmp;\n        // Read the block number and complain if it does not\n        // match our expectations.\n        f >> tmp;\n\n        if (tmp != iblock + 1)\n            throw value_error(\"wrong block number\");\n        // Read the Cartesian coordinates of the second unit cell.\n        Eigen::VectorXd rj(3);\n        f >> rj(0) >> rj(1) >> rj(2);\n        // Read the Cartesian coordinates of the third unit cell.\n        Eigen::VectorXd rk(3);\n        f >> rk(0) >> rk(1) >> rk(2);\n        // Convert these coordinates to nm and\n        // round each vector to the closest unit cell.\n        Eigen::VectorXd solj = solver.solve(rj / 10.);\n        Eigen::VectorXd solk = solver.solve(rk / 10.);\n\n        for (auto ic = 0; ic < 3; ++ic) {\n            solj(ic) = std::round(solj(ic));\n            solk(ic) = std::round(solk(ic));\n        }\n        rj = cell.lattvec * solj;\n        rk = cell.lattvec * solk;\n        // The next line contains the three atom indices.\n        std::size_t i;\n        std::size_t j;\n        std::size_t k;\n        f >> i >> j >> k;\n        // Create an empty Thirdorder_ifcs object.\n        Thirdorder_ifcs block(rj, rk, i - 1, j - 1, k - 1);\n\n        // And read the contents of the 27 remaining lines to fill\n        // in the values of the ifcs.\n        for (auto ic = 0; ic < 27; ++ic) {\n            int p1;\n            int p2;\n            int p3;\n            f >> p1 >> p2 >> p3;\n            f >> block.ifc(p1 - 1, p2 - 1, p3 - 1);\n        }\n        // Add the new block to the vector.\n        nruter->emplace_back(block);\n    }\n    return nruter;\n}\n} // namespace alma\n", "meta": {"hexsha": "09410b5e4b505c858cea709f21388205c378fd90", "size": 10468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vasp_io.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/vasp_io.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/vasp_io.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": 32.7125, "max_line_length": 78, "alphanum_fraction": 0.5610431792, "num_tokens": 2779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.045352578941415034, "lm_q1q2_score": 0.021967886009821202}}
{"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 COUPLING_MONITOR_H\n#define COUPLING_MONITOR_H\n\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n#include \"logger.hpp\"\n#include \"error.hpp\"\n\nnamespace flexiblesusy {\n\n/**\n * @class Coupling_monitor\n * @brief stores model parameters at different scales\n *\n * Template arguments are the model type and the parameter getter\n * type.  The paramameter getter has to provide two functions:\n * get_parameters() which returns the values of the parameters, and\n * get_parameter_names() wich returns the names of the parameters.\n *\n * Example:\n * @code\n * class MSSM_parameter_getter {\n * public:\n *    Eigen::ArrayXd get_parameters(const MSSM& model) {\n *       return model.get();\n *    }\n *    std::vector<std::string> get_parameter_names() const {\n *       return ...;\n *    }\n * };\n *\n * MSSM model;\n * MSSM_parameter_getter getter;\n * Coupling_monitor<MSSM, MSSM_parameter_getter> cm(model, getter);\n *\n * const double start_scale = 100.;\n * const double stop_scale = 1.0e12;\n * const unsigned number_of_points = 50;\n * const bool include_endpoint = true;\n *\n * cm.run(start_scale, stop_scale, number_of_points, include_endpoint);\n * cm.write_to_file(\"running_coupling.dat\");\n * @endcode\n */\ntemplate <class Model, class DataGetter>\nclass Coupling_monitor {\npublic:\n   typedef std::pair<double, Eigen::ArrayXd> TTouple;///< touple of scale and couplings\n\n   Coupling_monitor(const Model&, const DataGetter&);\n   ~Coupling_monitor() {}\n\n   /// get couplings at all scales\n   void run(double, double, unsigned int number_of_steps = 20, bool include_endpoint = false);\n   /// get maximum scale\n   TTouple get_max_scale() const;\n   /// delete all saved couplings\n   void clear();\n   /// write couplings to file\n   void write_to_file(const std::string&, bool overwrite = true) const;\n\nprivate:\n   typedef std::vector<TTouple> TData; ///< container for the scales and couplings\n   struct TDataComp {\n      bool operator() (const TData::value_type& i,const TData::value_type& j) {\n         return i.first < j.first;\n      }\n   };\n\n   TData couplings;        ///< all couplings at all scales\n   Model model;            ///< the model\n   DataGetter data_getter; ///< hepler class which extracts the model parameters\n   unsigned width;         ///< width of columns in output table\n\n   /// write line with parameter names\n   void write_parameter_names_line(std::ofstream&) const;\n   /// write a comment line\n   void write_comment_line(std::ofstream&) const;\n};\n\ntemplate <class Model, class DataGetter>\nCoupling_monitor<Model,DataGetter>::Coupling_monitor(const Model& model_, const DataGetter& data_getter_)\n   : couplings(TData())\n   , model(model_)\n   , data_getter(data_getter_)\n   , width(16)\n{\n}\n\n/**\n * Get the couplings at the largest scale\n *\n * @return a pair with the scale and a Eigen::ArrayXd which contains the\n * couplings at this scale\n */\ntemplate <class Model, class DataGetter>\ntypename Coupling_monitor<Model,DataGetter>::TTouple Coupling_monitor<Model,DataGetter>::get_max_scale() const\n{\n   if (couplings.empty()) {\n      ERROR(\"Data container is empty!\");\n      return TTouple(0.0, Eigen::ArrayXd(1));\n   }\n\n   // find gauge couplings at the greatest scale\n   TData::const_iterator maxScale\n      = max_element(couplings.begin(), couplings.end(), TDataComp());\n\n   return *maxScale;\n}\n\n/**\n * Delete all internal couplings.\n */\ntemplate <class Model, class DataGetter>\nvoid Coupling_monitor<Model,DataGetter>::clear()\n{\n   couplings.clear();\n}\n\n/**\n * write line with parameter names\n *\n * @param fout output stream\n */\ntemplate <class Model, class DataGetter>\nvoid Coupling_monitor<Model,DataGetter>::write_parameter_names_line(std::ofstream& fout) const\n{\n   if (!fout.good() || couplings.empty())\n      return;\n\n   const std::size_t number_of_couplings = couplings.front().second.size();\n   const std::vector<std::string> parameter_names(data_getter.get_parameter_names());\n\n   if (number_of_couplings != parameter_names.size()) {\n      ERROR(\"number of couplings != length of list of parameter names\");\n   }\n\n   fout << std::left << std::setw(width) << \"scale\";\n\n   for (std::size_t i = 0; i < number_of_couplings; ++i)\n      fout << std::left << std::setw(width) << parameter_names[i];\n\n   fout << '\\n';\n}\n\n/**\n * write help line which describes the written data\n *\n * @param fout output stream\n */\ntemplate <class Model, class DataGetter>\nvoid Coupling_monitor<Model,DataGetter>::write_comment_line(std::ofstream& fout) const\n{\n   if (!fout.good() || couplings.empty())\n      return;\n\n   const std::size_t number_of_couplings = couplings.front().second.size();\n   const std::vector<std::string> parameter_names(data_getter.get_parameter_names());\n\n   if (number_of_couplings != parameter_names.size()) {\n      ERROR(\"number of couplings != length of list of parameter names\");\n   }\n\n   fout << std::left << std::setw(width) << \"# [1] scale\";\n\n   for (std::size_t i = 0; i < number_of_couplings; ++i) {\n      std::ostringstream parameter;\n      parameter << '[' << (i+2) << \"] \" << parameter_names[i];\n\n      fout << std::left << std::setw(width) << parameter.str();\n   }\n\n   fout << '\\n';\n}\n\n/**\n * Write all couplings to a text file.\n *\n * @param file_name name of file to write the data to\n * @param overwrite if true, file is overwritten, otherwise content is appended\n */\ntemplate <class Model, class DataGetter>\nvoid Coupling_monitor<Model,DataGetter>::write_to_file(const std::string& file_name, bool overwrite) const\n{\n   if (couplings.empty())\n      return;\n\n   const std::ios_base::openmode openmode\n      = (overwrite ? std::ios::out : std::ios::app);\n\n   std::ofstream filestr(file_name.c_str(), openmode);\n   VERBOSE_MSG(\"Coupling_monitor<>::write_to_file: opening file: \"\n               << file_name.c_str());\n   if (filestr.fail()) {\n      ERROR(\"can't open file \" << file_name\n            << \" for writing running couplings\");\n      return;\n   }\n\n   write_comment_line(filestr);\n   write_parameter_names_line(filestr);\n\n   // write data\n   for (TData::const_iterator it = couplings.begin();\n        it != couplings.end(); ++it) {\n      if (!filestr.good()) {\n         ERROR(\"file \" << file_name << \" is corrupted\");\n         break;\n      }\n\n      filestr << std::left << std::setw(width) << it->first;\n\n      // write all gauge couplings in order\n      for (int i = 0; i < it->second.size(); ++i) {\n         filestr << std::left << std::setw(width) << it->second(i);\n      }\n\n      filestr << '\\n';\n   }\n\n   filestr.close();\n   VERBOSE_MSG(\"Coupling_monitor<>::write_to_file: file written: \"\n               << file_name.c_str());\n}\n\n/**\n * Add running couplings between scale q1 and q2.\n *\n * @param q1 scale to start at\n * @param q2 end scale\n * @param number_of_steps number of steps\n * @param include_endpoint include the endpoint q2 in the running\n *        (false by default)\n */\ntemplate <class Model, class DataGetter>\nvoid Coupling_monitor<Model,DataGetter>::run(double q1, double q2,\n                                             unsigned int number_of_steps, bool include_endpoint)\n{\n   if (q1 <= 0.0 || q2 <= 0.0) {\n      ERROR(\"negative scales are not allowed: q1=\" << q1 << \", q2=\" << q2);\n      return;\n   }\n\n   if (number_of_steps < 1)\n      number_of_steps = 1;\n\n   // if the endpoint should be included, the scale loop must run from\n   // (n == 0) to (n == number_of_steps); otherwise it runs from (n == 0) to (n\n   // == number_of_steps - 1)\n   const unsigned int endpoint_offset = include_endpoint ? 1 : 0;\n\n   // run from q1 to q2\n   for (unsigned int n = 0; n < number_of_steps + endpoint_offset; ++n) {\n      const double scale = exp(log(q1) + n * (log(q2) - log(q1)) / number_of_steps);\n      try {\n         model.run_to(scale);\n      } catch (const Error&) {\n         ERROR(\"Coupling_monitor::run: run to scale \"\n               << scale << \" failed\");\n         break;\n      }\n      couplings.push_back(TData::value_type(scale, data_getter.get_parameters(model)));\n   }\n\n   std::sort(couplings.begin(), couplings.end(), TDataComp());\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "988b982dd21dba1e6ca0fd9586006c4213051312", "size": 8930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/coupling_monitor.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/coupling_monitor.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/coupling_monitor.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": 30.2711864407, "max_line_length": 110, "alphanum_fraction": 0.6547592385, "num_tokens": 2191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702254064929193, "lm_q2_score": 0.05921024617595501, "lm_q1q2_score": 0.021921137459038762}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file traits.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include \"types.hpp\"\n#include \"profiling.hpp\"\n\nnamespace fl\n{\n\n/**\n * \\ingroup traits\n * \\def from_traits\n * \\brief Helper macro to import typedefs from the traits of a class\n *\n * typedef from_traits(SomeTypeName);\n *\n * is the short hand for\n *\n * typedef typename Traits<This>::SomeTypeName SomeTypeName;\n *\n * \\note from_this(.) requires the typedef \\c This of the current class\n */\n#define from_traits(TypeName) typename Traits<This>::TypeName TypeName\n\n#if defined(__GXX_EXPERIMENTAL_CXX0X__)\n    #define override\n#endif\n\n/**\n * \\ingroup traits\n * \\brief Generic trait template\n *\n * Filters, models and distributions may specify a \\c Traits specialization\n */\ntemplate <typename> struct Traits { };\n\n/**\n * \\ingroup traits\n *\n * \\brief \\c IsDynamic<int> trait for static dynamic-size checks.\n *\n * Generic IsDynamic<int> definition which evaluates to false.\n *\n * Examples\n *\n * static_assert(IsDynamic<MyEigenMatrixType::SizeAtCompileTime>(), \"\");\n *\n * if (IsDynamic<MyEigenMatrixType::SizeAtCompileTime>::value) ...\n */\ntemplate <int Size> struct IsDynamic\n{\n    static_assert(Size > Eigen::Dynamic, \"Invalid static size\");\n\n    static constexpr bool value = false;\n    constexpr operator bool () const { return value; }\n};\n\n/**\n * \\ingroup traits\n * \\brief \\c IsDynamic<-1> or \\c IsDynamic<Eigen::Dynamic> trait for static\n * dynamic-size checks.\n *\n * A specialization IsDynamic<Eigen::Dynamic> definition which evaluates to\n * true.\n *\n * Examples\n *\n * // overloaded operator bool ()\n * static_assert(!IsDynamic<MyEigenMatrixType::SizeAtCompileTime>(), \"\");\n *\n * if (!IsDynamic<MyEigenMatrixType::SizeAtCompileTime>::value) ...\n */\ntemplate <> struct IsDynamic<Eigen::Dynamic>\n{\n    static constexpr bool value = true;\n    constexpr operator bool () const { return value; }\n};\n\n/**\n * \\ingroup traits\n *\n * \\brief \\c IsFixed<int> trait for static fixed-size checks.\n *\n * Generic IsFixed<int> definition which evaluates to true. This traits is the\n * opposite of IsDynamic.\n *\n * Examples\n *\n * static_assert(IsFixed<MyEigenMatrixType::SizeAtCompileTime>::value, \"\");\n *\n * // overloaded operator bool ()\n * if (IsFixed<MyEigenMatrixType::SizeAtCompileTime>()) ...\n */\ntemplate <int Size> struct IsFixed\n{\n    static_assert(Size > Eigen::Dynamic, \"Invalid static size\");\n\n    static constexpr bool value = true;\n    constexpr operator bool () const { return value; }\n};\n\n/**\n * \\ingroup traits\n * \\brief \\c IsFixed<-1> or \\c IsFixed<Eigen::Dynamic> trait for static\n * fixed-size checks.\n *\n * A specialization IsFixed<Eigen::Dynamic> definition which evaluates to\n * false. This traits is the opposite of IsDynamic<Eigen::Dynamic>.\n *\n * Examples\n *\n * static_assert(!IsFixed<MyEigenMatrixType::SizeAtCompileTime>(), \"\");\n *\n * if (!IsFixed<MyEigenMatrixType::SizeAtCompileTime>::value) ...\n */\ntemplate <> struct IsFixed<Eigen::Dynamic>\n{\n    static constexpr bool value = false;\n    constexpr operator bool () const { return value; }\n};\n\n/**\n * \\ingroup traits\n *\n * \\brief Mapps Eigen::Dynamic onto 0.\n *\n * For any type matrix or column vector the dimension is the number of rows,\n * i.e. Matrix::RowsAtCompileTime. If the Matrix::SizeAtCompileTime enum is not\n * equal Eigen::Dynamic (-1) the dimension is set to Matrix::RowsAtCompileTime.\n * Otherwise, 0 is returned.\n *\n * Examples\n *\n * static_assert(DimensionOf<MyEigenMatrixType>() > 0, \"Dim must be greater 0\");\n *\n * static_assert(DimensionOf<MyEigenMatrixType>::value > 0, \"Dim must be .. 0\");\n *\n * Eigen::VectorXd vector(DimensionOf<MyEigenMatrixType>());\n */\ntemplate <typename Matrix> struct DimensionOf\n{\n    enum : signed int { Value = IsFixed<Matrix::SizeAtCompileTime>()\n                                    ? Matrix::RowsAtCompileTime\n                                    : 0 };\n\n    constexpr operator int () const { return Value; }\n};\n\n/**\n * \\ingroup traits\n * \\brief Returns the compile time size of a matrix or vector.\n *\n * SizeOf<M>() is shorthand for M::SizeAtCompileTime\n */\ntemplate <typename Matrix> struct SizeOf\n{\n    enum : signed int { Value = Matrix::SizeAtCompileTime };\n\n    constexpr operator int () const { return Value; }\n};\n\n/**\n * \\ingroup traits\n *\n */\ntemplate <int Dimension> struct ToDimension\n{\n    enum : signed int { Value = Dimension == Eigen::Dynamic ? 0 : Dimension };\n\n    constexpr operator int () const { return Value; }\n};\n\n\n/**\n * \\ingroup traits\n *\n * \\brief Returns simple the max integer of A and B\n */\ntemplate <int A, int B> struct MaxOf\n{\n    enum : signed int { Value = (A > B) ? A : B };\n    static constexpr int value = (A > B) ? A : B;\n    constexpr operator int () const { return Value; }\n};\n\n/**\n * \\ingroup traits\n *\n * \\brief Returns simple the min integer of A and B\n */\ntemplate <int A, int B> struct MinOf\n{\n    enum : signed int { Value = (A < B) ? A : B };\n    static constexpr int value = (A < B) ? A : B;\n    constexpr operator int () const { return Value; }\n};\n\n/**\n * \\ingroup traits\n *\n * Defines the second moment type of a given variate\n */\ntemplate <typename Variate>\nstruct SecondMomentOf\n{\n    enum: signed int { Dimension = SizeOf<Variate>::Value };\n    typedef Eigen::Matrix<Real, Dimension, Dimension> Type;\n};\n\n/**\n * \\ingroup traits\n */\ntemplate <typename Variate>\nstruct FirstMomentOf\n{\n    enum: signed int { Dimension = SizeOf<Variate>::Value };\n    typedef Eigen::Matrix<Real, Dimension, 1> Type;\n};\n\n/**\n * \\ingroup traits\n *\n * Defines the second moment type of a given variate\n */\ntemplate <typename Variate>\nstruct DiagonalSecondMomentOf\n{\n    enum: signed int { Dimension = SizeOf<Variate>::Value };\n    typedef Eigen::DiagonalMatrix<Real, Dimension> Type;\n};\n\n/**\n * \\ingroup traits\n *\n * Defines the second moment type of a given variate\n */\ntemplate <>\nstruct SecondMomentOf<Real>\n{\n    typedef Real Type;\n};\n\n/**\n * \\ingroup traits\n */\ntemplate <>\nstruct FirstMomentOf<Real>\n{\n    typedef Real Type;\n};\n\n\n/**\n * \\ingroup traits\n * Defines a Real variate of the specified size\n */\ntemplate <int Size>\nstruct VariateOfSize\n{\n    typedef Eigen::Matrix<Real, Size, 1> Type;\n};\n\n\n/**\n * \\ingroup traits\n */\ntemplate <typename Model> struct IsAdditive\n{\n    enum: bool\n    {\n        Value = std::is_base_of<internal::AdditiveNoiseModelType, Model>::value\n    };\n};\n\n/**\n * \\ingroup traits\n */\ntemplate <typename Model> struct IsAdditiveUncorrelated\n{\n    enum: bool\n    {\n        Value = std::is_base_of<\n                    internal::AdditiveUncorrelatedNoiseModelType,\n                    Model\n                >::value\n    };\n};\n\n/**\n * \\ingroup traits\n */\ntemplate <typename Model> struct IsNonAdditive\n{\n    enum: bool\n    {\n        Value = std::is_base_of<internal::NonAdditiveNoiseModelType, Model>::value\n    };\n};\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model, typename ...> struct AdditivityOf;\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model>\nstruct AdditivityOf<Model, internal::AdditiveNoiseModelType>\n{\n    typedef Additive<Model> Type;\n};\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model>\nstruct AdditivityOf<Model, internal::AdditiveUncorrelatedNoiseModelType>\n{\n    typedef AdditiveUncorrelated<Model> Type;\n};\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model>\nstruct AdditivityOf<Model, internal::NonAdditiveNoiseModelType>\n{\n    typedef NonAdditive<Model> Type;\n};\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model>\nstruct AdditivityOf<Additive<Model>>\n{\n    typedef Additive<Model> Type;\n};\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model>\nstruct AdditivityOf<AdditiveUncorrelated<Model>>\n{\n    typedef AdditiveUncorrelated<Model> Type;\n};\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model>\nstruct AdditivityOf<NonAdditive<Model>>\n{\n    typedef NonAdditive<Model> Type;\n};\n\n/**\n * \\ingroup traits\n * \\brief Provides access to the type of the model\n *\n * The model type will be one of the following\n *  - \\c NonAdditive (Noise)\n *  - \\c Additive (Noise)\n *  - \\c AdditiveUncorrelated (Noise)\n */\ntemplate <typename Model> struct AdditivityOf<Model>\n{\n    typedef typename AdditivityOf<Model, typename Model::Type>::Type Type;\n};\n\n/**\n * \\internal\n * \\ingroup traits\n */\ntemplate <typename Model> struct RemoveAdditivityOf\n{\n    typedef Model Type;\n};\n\ntemplate <typename Model>\nstruct RemoveAdditivityOf<Additive<Model>>\n{\n    typedef Model Type;\n};\n\ntemplate <typename Model>\nstruct RemoveAdditivityOf<AdditiveUncorrelated<Model>>\n{\n    typedef Model Type;\n};\n\ntemplate <typename Model>\nstruct RemoveAdditivityOf<NonAdditive<Model>>\n{\n    typedef Model Type;\n};\n\n/**\n * \\internal\n *\n * \\ingroup traits\n */\ntemplate <typename Model>\nstruct ForwardLinearModelOnly\n{\n    static_assert(std::is_base_of<internal::LinearModelType, Model>::value,\n                  \"The specified model is not linear!\");\n\n    typedef Model Type;\n};\n\n}\n\n\n\n", "meta": {"hexsha": "ed1bc6ad61f8c4d26df96515235e062fc3ff681b", "size": 9391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/util/traits.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/util/traits.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/util/traits.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 21.0560538117, "max_line_length": 82, "alphanum_fraction": 0.6760728357, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.055823141527311576, "lm_q1q2_score": 0.02190147360353381}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2018 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n/*! \\file JointStopR.cpp\n\n*/\n\n#include \"JointStopR.hpp\"\n#include <NewtonEulerDS.hpp>\n#include <Interaction.hpp>\n#include <boost/math/quaternion.hpp>\n#include <BlockVector.hpp>\n#include <cfloat>\n#include <iostream>\n\n// #define DEBUG_BEGIN_END_ONLY\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include \"debug.h\"\n\n/** Initialize a joint stop for a common case: a single axis with a\n * single stop, either positive or negative. For use with\n * NewtonImpactNSL. */\nJointStopR::JointStopR(SP::NewtonEulerJointR joint, double pos, bool dir,\n                       unsigned int axis)\n  : NewtonEulerR()\n  , _joint(joint)\n  , _axis(std11::make_shared< std::vector<unsigned int> >())\n  , _pos(std11::make_shared<SiconosVector>(1))\n  , _dir(std11::make_shared<SiconosVector>(1))\n{\n  _axis->push_back(axis);\n  _pos->setValue(0, pos);\n  _dir->setValue(0, dir ? -1 : 1);\n  _axisMin = axis;\n  _axisMax = axis;\n  assert( (_axisMax - _axisMin + 1) <= _joint->numberOfDoF() );\n}\n\n/** Initialize a multidimensional joint stop, e.g. the cone stop on\n * a ball joint. For use with NewtonImpactFrictionNSL size 2 or 3. */\nJointStopR::JointStopR(SP::NewtonEulerJointR joint, SP::SiconosVector pos,\n                       SP::SiconosVector dir, SP::UnsignedIntVector axes)\n  : NewtonEulerR()\n  , _joint(joint)\n  , _axis(axes)\n  , _pos(pos)\n  , _dir(dir)\n{\n  _axisMin = 100;\n  _axisMax = 0;\n  for (unsigned int i=0; i < _axis->size(); i++)\n  {\n    if ((*_axis)[i] > _axisMax) _axisMax = (*_axis)[i];\n    if ((*_axis)[i] < _axisMin) _axisMin = (*_axis)[i];\n  }\n  assert( (_axisMax - _axisMin + 1) <= _joint->numberOfDoF() );\n}\n\n#if 0  // Disabled, see JointStopR.hpp.  Use multiple JointStopR instead.\n/** Initialize a joint stop for a common case: a single axis with a\n * double stop, one positive and one negative. */\nJointStopR::JointStopR(SP::NewtonEulerJointR joint, double pos, double neg,\n                       unsigned int axis)\n  : NewtonEulerR()\n  , _joint(joint)\n  , _axis(std11::make_shared< std::vector<unsigned int> >())\n  , _pos(std11::make_shared<SiconosVector>(2))\n  , _dir(std11::make_shared<SiconosVector>(2))\n{\n  _axis->push_back(axis);\n  _axis->push_back(axis);\n  _pos->setValue(0, pos);\n  _pos->setValue(1, neg);\n  _dir->setValue(0, 1);\n  _dir->setValue(1, -1);\n  _axisMin = axis;\n  _axisMax = axis;\n  assert( (_axisMax - _axisMin + 1) <= _joint->numberOfDoF() );\n}\n#endif\n\nvoid JointStopR::computeh(double time, BlockVector& q0, SiconosVector& y)\n{\n  // Common cases optimisation\n  bool case_onestop = y.size()==1;\n  bool case_posneg = y.size()==2 && (*_axis)[0] == (*_axis)[1];\n  if (case_onestop || case_posneg)\n  {\n    _joint->computehDoF(time, q0, y, (*_axis)[0]);\n\n    y.setValue(0, (y.getValue(0) - _pos->getValue(0)) * _dir->getValue(0));\n    if (case_posneg)\n      y.setValue(1, (y.getValue(0) - _pos->getValue(1)) * _dir->getValue(1));\n    return;\n  }\n\n  // Get h for each relevant axis\n  SiconosVector tmp_y(_axisMax - _axisMin + 1);\n  _joint->computehDoF(time, q0, tmp_y, _axisMin);\n\n  // Copy and scale each stop for its axis/position/direction\n  for (unsigned int i=0; i < y.size(); i++) {\n    y.setValue(i, (tmp_y.getValue((*_axis)[i])\n                   - _pos->getValue(i))*_dir->getValue(i));\n  }\n}\n\nvoid JointStopR::computeJachq(double time, Interaction& inter, SP::BlockVector q0)\n{\n  unsigned int n = _axisMax - _axisMin + 1;\n\n  if (!_jachqTmp || !(_jachqTmp->size(1) == q0->size() &&\n                      _jachqTmp->size(0) == n))\n  {\n    _jachqTmp = std11::make_shared<SimpleMatrix>(n, q0->size());\n  }\n\n  // Compute the jacobian for the required range of axes\n  _joint->computeJachqDoF(time, inter, q0, *_jachqTmp, _axisMin);\n\n  // Copy indicated axes into the stop jacobian, possibly flipped for negative stops\n  for (unsigned int i=0; i<_jachq->size(0); i++)\n    for (unsigned int j=0; j<_jachq->size(1); j++)\n      _jachq->setValue(i,j,\n                       _jachqTmp->getValue((*_axis)[i]-_axisMin,j) * _dir->getValue(i));\n}\n\nunsigned int JointStopR::numberOfConstraints()\n{\n  return _axis->size();\n}\n", "meta": {"hexsha": "b88bcc401498e3e04e97702b03fbd4c950d50550", "size": 4726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mechanics/src/joints/JointStopR.cpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "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": "mechanics/src/joints/JointStopR.cpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mechanics/src/joints/JointStopR.cpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "avg_line_length": 32.1496598639, "max_line_length": 88, "alphanum_fraction": 0.6639864579, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.05261895520477843, "lm_q1q2_score": 0.021831543020124904}}
{"text": "/**\n * \\file   MeshSurfaceExtraction.cpp\n * \\author Karsten Rink\n * \\date   2013-04-04\n * \\brief  Implementation of the MeshSurfaceExtraction class.\n *\n * \\copyright\n * Copyright (c) 2012-2016, 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 \"MeshSurfaceExtraction.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"logog/include/logog.hpp\"\n\n#include \"GeoLib/Point.h\"\n\n#include \"MeshLib/Mesh.h\"\n#include \"MeshLib/Elements/Line.h\"\n#include \"MeshLib/Elements/Tri.h\"\n#include \"MeshLib/Elements/Quad.h\"\n#include \"MeshLib/MeshEditing/DuplicateMeshComponents.h\"\n#include \"MeshLib/MeshQuality/MeshValidation.h\"\n#include \"MeshLib/MeshSearch/NodeSearch.h\"\n#include \"MeshLib/MeshEditing/RemoveMeshComponents.h\"\n\nnamespace MeshLib {\n\nstd::vector<double> MeshSurfaceExtraction::getSurfaceAreaForNodes(const MeshLib::Mesh &mesh)\n{\n    std::vector<double> node_area_vec;\n    if (mesh.getDimension() != 2)\n    {\n        ERR (\"Error in MeshSurfaceExtraction::getSurfaceAreaForNodes() - Given mesh is no surface mesh (dimension != 2).\");\n        return node_area_vec;\n    }\n\n    double total_area (0);\n\n    // for each node, a vector containing all the element idget every element\n    const std::vector<MeshLib::Node*> &nodes = mesh.getNodes();\n    const std::size_t nNodes ( mesh.getNumberOfNodes() );\n    for (std::size_t n=0; n<nNodes; ++n)\n    {\n        double node_area (0);\n\n        std::vector<MeshLib::Element*> conn_elems = nodes[n]->getElements();\n        const std::size_t nConnElems (conn_elems.size());\n\n        for (std::size_t i=0; i<nConnElems; ++i)\n        {\n            const MeshLib::Element* elem (conn_elems[i]);\n            const unsigned nElemParts = (elem->getGeomType() == MeshElemType::TRIANGLE) ? 3 : 4;\n            const double area = conn_elems[i]->getContent() / nElemParts;\n            node_area += area;\n            total_area += area;\n        }\n\n        node_area_vec.push_back(node_area);\n    }\n\n    INFO (\"Total surface Area: %f\", total_area);\n\n    return node_area_vec;\n}\n\nMeshLib::Mesh* MeshSurfaceExtraction::getMeshSurface(\n    const MeshLib::Mesh& mesh, const MathLib::Vector3& dir, double angle,\n    std::string const& subsfc_node_id_backup_prop_name)\n{\n    if (angle < 0 || angle > 90)\n    {\n        ERR (\"Supported angle between 0 and 90 degrees only.\");\n        return nullptr;\n    }\n\n    INFO (\"Extracting mesh surface...\");\n    std::vector<MeshLib::Element*> sfc_elements;\n    get2DSurfaceElements(mesh.getElements(), sfc_elements, dir, angle, mesh.getDimension());\n\n    if (sfc_elements.empty())\n        return nullptr;\n\n    std::vector<MeshLib::Node*> sfc_nodes;\n    std::vector<std::size_t> node_id_map(mesh.getNumberOfNodes());\n    get2DSurfaceNodes(sfc_nodes, mesh.getNumberOfNodes(), sfc_elements, node_id_map);\n\n    // create new elements vector with newly created nodes\n    std::vector<MeshLib::Element*> new_elements;\n    new_elements.reserve(sfc_elements.size());\n    for (auto elem = sfc_elements.cbegin(); elem != sfc_elements.cend(); ++elem)\n    {\n        unsigned const n_elem_nodes ((*elem)->getNumberOfBaseNodes());\n        MeshLib::Node** new_nodes = new MeshLib::Node*[n_elem_nodes];\n        for (unsigned k(0); k<n_elem_nodes; k++)\n            new_nodes[k] = sfc_nodes[node_id_map[(*elem)->getNode(k)->getID()]];\n        if ((*elem)->getGeomType() == MeshElemType::TRIANGLE)\n            new_elements.push_back(new MeshLib::Tri(new_nodes));\n        else {\n            assert((*elem)->getGeomType() == MeshElemType::QUAD);\n            new_elements.push_back(new MeshLib::Quad(new_nodes));\n        }\n        delete *elem;\n    }\n\n    std::vector<std::size_t> id_map;\n    if (!subsfc_node_id_backup_prop_name.empty())\n    {\n        id_map.reserve(sfc_nodes.size());\n        for (auto node = sfc_nodes.cbegin(); node != sfc_nodes.cend(); ++node)\n            id_map.push_back((*node)->getID());\n    }\n    MeshLib::Mesh* result (new Mesh(mesh.getName()+\"-Surface\", sfc_nodes, new_elements));\n    // transmit the original node ids of the subsurface mesh as a property\n    if (!subsfc_node_id_backup_prop_name.empty()) {\n        boost::optional<MeshLib::PropertyVector<std::size_t>&> orig_node_ids(\n            result->getProperties().createNewPropertyVector<std::size_t>(\n                subsfc_node_id_backup_prop_name , MeshLib::MeshItemType::Node, 1));\n        if (orig_node_ids) {\n            orig_node_ids->resize(id_map.size());\n            std::copy(id_map.cbegin(), id_map.cend(), orig_node_ids->begin());\n        }\n    }\n    return result;\n}\n\nMeshLib::Mesh* MeshSurfaceExtraction::getMeshBoundary(const MeshLib::Mesh &mesh)\n{\n    if (mesh.getDimension()==1)\n        return nullptr;\n\n    // For 3D meshes return the 2D surface\n    if (mesh.getDimension()==3)\n    {\n        MathLib::Vector3 dir(0,0,0);\n        return getMeshSurface(mesh, dir, 90);\n    }\n\n    // For 2D meshes return the boundary lines\n    std::vector<MeshLib::Node*> nodes = MeshLib::copyNodeVector(mesh.getNodes());\n    std::vector<MeshLib::Element*> boundary_elements;\n\n    std::vector<MeshLib::Element*> const& org_elems (mesh.getElements());\n    for (auto it=org_elems.begin(); it!=org_elems.end(); ++it)\n    {\n        MeshLib::Element* elem (*it);\n        std::size_t const n_edges (elem->getNumberOfEdges());\n        for (std::size_t i=0; i<n_edges; ++i)\n            if (elem->getNeighbor(i) == nullptr)\n            {\n                MeshLib::Element const*const edge (elem->getEdge(i));\n                boundary_elements.push_back(MeshLib::copyElement(edge, nodes));\n                delete edge;\n            }\n    }\n    MeshLib::Mesh* result = new MeshLib::Mesh(\"Boundary Mesh\", nodes, boundary_elements);\n    MeshLib::NodeSearch ns(*result);\n    if (ns.searchUnused() == 0) {\n        return result;\n    } else {\n        auto removed = MeshLib::removeNodes(*result, ns.getSearchedNodeIDs(), result->getName());\n        delete result;\n        return removed;\n    }\n}\n\nvoid MeshSurfaceExtraction::get2DSurfaceElements(const std::vector<MeshLib::Element*> &all_elements, std::vector<MeshLib::Element*> &sfc_elements, const MathLib::Vector3 &dir, double angle, unsigned mesh_dimension)\n{\n    if (mesh_dimension<2 || mesh_dimension>3)\n        ERR(\"Cannot handle meshes of dimension %i\", mesh_dimension);\n\n    bool const complete_surface = (MathLib::scalarProduct(dir, dir) == 0);\n\n    double const pi (boost::math::constants::pi<double>());\n    double const cos_theta (std::cos(angle * pi / 180.0));\n    MathLib::Vector3 const norm_dir (dir.getNormalizedVector());\n\n    for (auto elem = all_elements.cbegin(); elem != all_elements.cend(); ++elem)\n    {\n        const unsigned element_dimension ((*elem)->getDimension());\n        if (element_dimension < mesh_dimension)\n            continue;\n\n        if (element_dimension == 2)\n        {\n            if (!complete_surface)\n            {\n                MeshLib::Element* face = *elem;\n                if (MathLib::scalarProduct(FaceRule::getSurfaceNormal(face).getNormalizedVector(), norm_dir) > cos_theta)\n                    continue;\n            }\n            sfc_elements.push_back(*elem);\n        }\n        else\n        {\n            if (!(*elem)->isBoundaryElement())\n                continue;\n            const unsigned nFaces ((*elem)->getNumberOfFaces());\n            for (unsigned j=0; j<nFaces; ++j)\n            {\n                if ((*elem)->getNeighbor(j) != nullptr)\n                    continue;\n\n                auto const face = std::unique_ptr<MeshLib::Element const>{(*elem)->getFace(j)};\n                if (!complete_surface)\n                {\n                    if (MathLib::scalarProduct(FaceRule::getSurfaceNormal(face.get()).getNormalizedVector(), norm_dir) < cos_theta)\n                    {\n                        continue;\n                    }\n                }\n                if (face->getGeomType() == MeshElemType::TRIANGLE)\n                    sfc_elements.push_back(new MeshLib::Tri(*static_cast<const MeshLib::Tri*>(face.get())));\n                else\n                    sfc_elements.push_back(new MeshLib::Quad(*static_cast<const MeshLib::Quad*>(face.get())));\n            }\n        }\n    }\n}\n\nvoid MeshSurfaceExtraction::get2DSurfaceNodes(std::vector<MeshLib::Node*> &sfc_nodes, std::size_t n_all_nodes, const std::vector<MeshLib::Element*> &sfc_elements, std::vector<std::size_t> &node_id_map)\n{\n    const std::size_t nNewElements (sfc_elements.size());\n    std::vector<const MeshLib::Node*> tmp_nodes(n_all_nodes, nullptr);\n    for (std::size_t i=0; i<nNewElements; ++i)\n    {\n        const MeshLib::Element* elem (sfc_elements[i]);\n        for (unsigned j=0; j<elem->getNumberOfBaseNodes(); ++j)\n        {\n            const MeshLib::Node* node (elem->getNode(j));\n            tmp_nodes[node->getID()] = node;\n        }\n    }\n    const std::size_t nNodes (tmp_nodes.size());\n    for (unsigned i=0; i<nNodes; ++i)\n    {\n        if (tmp_nodes[i])\n        {\n            node_id_map[i] = sfc_nodes.size();\n            sfc_nodes.push_back(new MeshLib::Node(tmp_nodes[i]->getCoords(), tmp_nodes[i]->getID()));\n        }\n    }\n}\n\nstd::vector<GeoLib::Point*> MeshSurfaceExtraction::getSurfaceNodes(const MeshLib::Mesh &mesh, const MathLib::Vector3 &dir, double angle)\n{\n    INFO (\"Extracting surface nodes...\");\n    std::vector<MeshLib::Element*> sfc_elements;\n    get2DSurfaceElements(mesh.getElements(), sfc_elements, dir, angle, mesh.getDimension());\n\n    std::vector<MeshLib::Node*> sfc_nodes;\n    std::vector<std::size_t> node_id_map(mesh.getNumberOfNodes());\n    get2DSurfaceNodes(sfc_nodes, mesh.getNumberOfNodes(), sfc_elements, node_id_map);\n\n    for (auto e : sfc_elements)\n        delete e;\n\n    const std::size_t nNodes (sfc_nodes.size());\n    std::vector<GeoLib::Point*> surface_pnts(nNodes);\n    for (std::size_t i=0; i<nNodes; ++i)\n    {\n        surface_pnts[i] = new GeoLib::Point(*(sfc_nodes[i]), sfc_nodes[i]->getID());\n        delete sfc_nodes[i];\n    }\n    return surface_pnts;\n}\n\n} // end namespace MeshLib\n", "meta": {"hexsha": "57a8f6373ebac78a8bdd89b7d62f0d24f41bf168", "size": 10124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MeshLib/MeshSurfaceExtraction.cpp", "max_stars_repo_name": "norihiro-w/ogs", "max_stars_repo_head_hexsha": "ac990b1aa06a583dba3e32efa3009ef0c6f46ae4", "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": "MeshLib/MeshSurfaceExtraction.cpp", "max_issues_repo_name": "norihiro-w/ogs", "max_issues_repo_head_hexsha": "ac990b1aa06a583dba3e32efa3009ef0c6f46ae4", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2015-02-04T20:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-10T20:19:57.000Z", "max_forks_repo_path": "MeshLib/MeshSurfaceExtraction.cpp", "max_forks_repo_name": "norihiro-w/ogs", "max_forks_repo_head_hexsha": "ac990b1aa06a583dba3e32efa3009ef0c6f46ae4", "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": 36.9489051095, "max_line_length": 214, "alphanum_fraction": 0.6249506124, "num_tokens": 2503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.04468087106771079, "lm_q1q2_score": 0.02181692742971725}}
{"text": "/** \r\nMIT License\r\n\r\nCopyright (c) [2022] [Michel Kakulphimp]\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n**/\r\n \r\n// C/C++ includes\r\n#include <iostream>\r\n#include <fstream>\r\n#include <cmath>\r\n#include <chrono>\r\n#include <ctime>\r\n#include <locale>\r\n#include <vector>\r\n\r\n// Eigen includes\r\n#define EIGEN_USE_BLAS // use external BLAS routines\r\n#define EIGEN_USE_LAPACKE_STRICT // use LAPACKE C interface to use LAPACK routines (STRICT: disable\r\n                                 // less numerically robust routines)\r\n#include <Eigen/Dense>\r\n// This is a workaround needed to enable the use of EIGEN_USE_LAPACKE\r\n// https://github.com/libigl/libigl/issues/651 for more info\r\n#undef I\r\n\r\n// Boost includes\r\n#include <boost/format.hpp>\r\n#include <boost/program_options.hpp>\r\nnamespace po = boost::program_options;\r\n\r\n// OMP includes\r\n#include <omp.h>\r\n\r\n// BLAS includes\r\n#include <cblas.h>\r\n\r\n// CUDA\r\n#include <cuda.h>\r\n\r\n// Program includes\r\n#include \"main.hpp\"\r\n#include \"config.hpp\"\r\n#include \"console.hpp\"\r\n#include \"kernel.h\"\r\n#include \"version.hpp\"\r\n#include \"perfmon.hpp\"\r\n\r\n// Clean up code a bit by using aliases and typedefs\r\nusing namespace std;\r\nusing namespace boost;\r\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> EigenFloatMatrix_t;\r\ntypedef Eigen::Matrix<float, Eigen::Dynamic, 1> EigenFloatColVector_t;\r\ntypedef Eigen::Matrix<float, 1, Eigen::Dynamic> EigenFloatRowVector_t;\r\ntypedef Eigen::Map<EigenFloatMatrix_t> EigenFloatMatrixMap_t;\r\ntypedef Eigen::Map<EigenFloatColVector_t> EigenFloatColVectorMap_t;\r\n\r\n// Naughty naughty global!!!\r\nint program_verbosity;\r\n\r\nvoid parse_program_options(int argc, char **argv, Cfg_t &config)\r\n{\r\n    po::variables_map vm;\r\n    po::options_description desc(\"EHFS options\");\r\n    stringstream ss;\r\n    desc.add_options()\r\n        (\"help\", \"produce help message\")\r\n        (\"iterations\", po::value<int>()->default_value(20), \"set maximum number of iterations\")\r\n        (\"partitions\", po::value<int>()->default_value(12), \"set number of partitions to divide solution space\")\r\n        (\"limit\", po::value<int>()->default_value(4), \"set the solution space maximum x=y=z limit\")\r\n        (\"convergence\", po::value<float>()->default_value(0.01), \"set the convergence condition (%)\")\r\n        (\"structure\", po::value<int>()->default_value(0), \"set the atomic structure: (0:He, 1:H2)\")\r\n        (\"verbosity\", po::value<int>()->default_value(2), \"set the verbosity of the program\")\r\n        (\"max-threads\", po::value<int>()->default_value(16), \"set the maximum number of threads that CPU operations can spawn\")\r\n        (\"use-gpu-int\", po::value<bool>()->default_value(1), \"enable CUDA GPU acceleration for numerical integration\")\r\n        (\"use-gpu-eig\", po::value<bool>()->default_value(1), \"enable CUDA GPU acceleration for the eigensolver\")\r\n        (\"csv-header\", po::value<bool>()->default_value(0), \"enable CSV output (header) of simulation run for piping to file (disables other messages)\")\r\n        (\"csv-data-all\", po::value<bool>()->default_value(0), \"enable CSV output (all data) of simulation run for piping to file (disables other messages)\")\r\n        (\"csv-data-avg\", po::value<bool>()->default_value(0), \"enable CSV output (average data) of simulation run for piping to file (disables other messages)\")\r\n    ;\r\n    po::store(po::parse_command_line(argc, argv, desc), vm);\r\n    po::notify(vm);    \r\n    if (vm.count(\"help\"))\r\n    {\r\n        ss << desc << \"\\n\";\r\n        console_print(0, ss.str(), CLIENT_SIM);\r\n        exit(1);\r\n    }\r\n\r\n    if (vm[\"structure\"].as<int>() >= ATOMIC_STRUCTURE_NUM)\r\n    {\r\n        ss << \"Invalid atomic structure selection: \" << vm[\"structure\"].as<int>() << endl;\r\n        ss << \"Valid options: (0:He, 1:H2)\" << endl;\r\n        console_print(0, ss.str(), CLIENT_SIM);\r\n        exit(0);\r\n    }\r\n    else\r\n    {\r\n        config.atomic_structure = (atomic_structure_e)(vm[\"structure\"].as<int>());\r\n    }\r\n\r\n    // Program configuration from CLI\r\n    config.num_partitions = vm[\"partitions\"].as<int>();\r\n    config.limit = vm[\"limit\"].as<int>();\r\n    config.max_iterations = vm[\"iterations\"].as<int>();\r\n    config.num_solutions = 6;\r\n    config.convergence_percentage = vm[\"convergence\"].as<float>();\r\n    config.verbosity = vm[\"verbosity\"].as<int>();\r\n    config.max_num_threads = vm[\"max-threads\"].as<int>();\r\n    config.enable_cuda_integration = vm[\"use-gpu-int\"].as<bool>();\r\n    config.enable_cuda_eigensolver = vm[\"use-gpu-eig\"].as<bool>();\r\n    config.enable_csv_header_output = vm[\"csv-header\"].as<bool>();\r\n    config.enable_csv_data_all_output = vm[\"csv-data-all\"].as<bool>();\r\n    config.enable_csv_data_average_output = vm[\"csv-data-avg\"].as<bool>();\r\n    if (config.enable_csv_header_output || config.enable_csv_data_all_output || config.enable_csv_data_average_output)\r\n    {\r\n        config.verbosity = -1;\r\n    }\r\n    program_verbosity = config.verbosity;\r\n}\r\n\r\nvoid print_header(void)\r\n{\r\n    stringstream ss;\r\n\r\n    ss  << ANSI_FG_COLOR_MAGENTA \"                                           \" ANSI_COLOR_RESET << endl\r\n        << ANSI_FG_COLOR_MAGENTA \"     ██████╗ ███████╗██╗  ██╗███████╗      \" ANSI_COLOR_RESET << endl\r\n        << ANSI_FG_COLOR_MAGENTA \"     ██╔══██╗██╔════╝██║  ██║██╔════╝      \" ANSI_COLOR_RESET << endl\r\n        << ANSI_FG_COLOR_MAGENTA \"     ██║  ██║███████╗███████║█████╗        \" ANSI_COLOR_RESET << endl\r\n        << ANSI_FG_COLOR_MAGENTA \"     ██║  ██║╚════██║██╔══██║██╔══╝        \" ANSI_COLOR_RESET << endl\r\n        << ANSI_FG_COLOR_MAGENTA \"     ██████╔╝███████║██║  ██║██║           \" ANSI_COLOR_RESET << endl\r\n        << ANSI_FG_COLOR_MAGENTA \"     ╚═════╝ ╚══════╝╚═╝  ╚═╝╚═╝           \" ANSI_COLOR_RESET << endl\r\n        << ANSI_FG_COLOR_MAGENTA \"                                           \" ANSI_COLOR_RESET << endl\r\n        <<                       \" < Discrete Space Hartree-Fock Simulator > \" << endl << endl\r\n        << \"Author: Michel Kakulphimp\" << endl\r\n        << \"Build Date: \" __DATE__ \" \" __TIME__ << endl\r\n        << \"Git Branch: \" << GIT_BRANCH << endl\r\n        << \"Git Hash: \" << GIT_COMMIT_HASH << endl << endl;\r\n\r\n    console_print_hr(0, CLIENT_SIM);\r\n    console_print(0, ss.str(), CLIENT_SIM);\r\n}\r\n\r\nvoid populate_lookup_values(Cfg_t &config, Lut_t &lut)\r\n{\r\n    // Memory for the arrays filled out in this function should have been\r\n    // allocated already. Maybe check for null later. TODO.\r\n\r\n    // Populate LUTs\r\n    for (size_t coordinate_index = 0; coordinate_index < lut.matrix_dim; coordinate_index++)\r\n    {\r\n        // convert coordinate index to x,y,z coordinate indices\r\n        int base_10_num = coordinate_index;\r\n        for (int i = 0; i < IDX_NUM; i++)\r\n        {\r\n            lut.coordinate_index_array[i * lut.matrix_dim + coordinate_index] =\r\n                base_10_num % config.num_partitions;\r\n            base_10_num /= config.num_partitions;\r\n\r\n            lut.coordinate_value_array[i * lut.matrix_dim + coordinate_index] =\r\n                (float)(-config.limit) + ((float)lut.coordinate_index_array[i * lut.matrix_dim + coordinate_index]\r\n                    * lut.step_size);\r\n        }\r\n    }\r\n}\r\n\r\n// Generate the 3D Laplacian matrix for the given number of partitions\r\nvoid generate_laplacian_matrix(Lut_t lut, float *matrix)\r\n{\r\n    size_t col_index_x;\r\n    size_t col_index_y;\r\n    size_t col_index_z;\r\n    size_t row_index_x;\r\n    size_t row_index_y;\r\n    size_t row_index_z;\r\n\r\n    for (size_t row_coordinate_index = 0; row_coordinate_index < lut.matrix_dim; row_coordinate_index++)\r\n    {\r\n        for (size_t col_coordinate_index = 0; col_coordinate_index < lut.matrix_dim; col_coordinate_index++)\r\n        {\r\n            col_index_x = lut.coordinate_index_array[IDX_X * lut.matrix_dim + col_coordinate_index];\r\n            col_index_y = lut.coordinate_index_array[IDX_Y * lut.matrix_dim + col_coordinate_index];\r\n            col_index_z = lut.coordinate_index_array[IDX_Z * lut.matrix_dim + col_coordinate_index];\r\n\r\n            row_index_x = lut.coordinate_index_array[IDX_X * lut.matrix_dim + row_coordinate_index];\r\n            row_index_y = lut.coordinate_index_array[IDX_Y * lut.matrix_dim + row_coordinate_index];\r\n            row_index_z = lut.coordinate_index_array[IDX_Z * lut.matrix_dim + row_coordinate_index];\r\n\r\n            // U(x,y,z)\r\n            if (row_coordinate_index == col_coordinate_index)\r\n            {\r\n                matrix[row_coordinate_index + col_coordinate_index*lut.matrix_dim] = -6.0;\r\n            }\r\n\r\n            if ((row_index_y == col_index_y) && (row_index_z == col_index_z))\r\n            {\r\n                // U(x-1,y,z)\r\n                if (row_index_x == col_index_x + 1)\r\n                {\r\n                    matrix[row_coordinate_index + col_coordinate_index*lut.matrix_dim] = 1.0;\r\n                }\r\n                // U(x+1,y,z)\r\n                if (row_index_x == col_index_x - 1)\r\n                {\r\n                    matrix[row_coordinate_index + col_coordinate_index*lut.matrix_dim] = 1.0;\r\n                }\r\n            }\r\n\r\n            if ((row_index_x == col_index_x) && (row_index_z == col_index_z))\r\n            {\r\n                // U(x,y-1,z)\r\n                if (row_index_y == col_index_y + 1)\r\n                {\r\n                    matrix[row_coordinate_index + col_coordinate_index*lut.matrix_dim] = 1.0;\r\n                }\r\n                // U(x,y+1,z)\r\n                if (row_index_y == col_index_y - 1)\r\n                {\r\n                    matrix[row_coordinate_index + col_coordinate_index*lut.matrix_dim] = 1.0;\r\n                }\r\n            }\r\n\r\n            if ((row_index_x == col_index_x) && (row_index_y == col_index_y))\r\n            {\r\n                // U(x,y,z-1)\r\n                if (row_index_z == col_index_z + 1)\r\n                {\r\n                    matrix[row_coordinate_index + col_coordinate_index*lut.matrix_dim] = 1.0;\r\n                }\r\n                // U(x,y,z+1)\r\n                if (row_index_z == col_index_z - 1)\r\n                {\r\n                    matrix[row_coordinate_index + col_coordinate_index*lut.matrix_dim] = 1.0;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n// Helium atom nucleus-electron Coulombic attraction function\r\nfloat attraction_function_helium(Lut_t lut, int linear_coordinates)\r\n{\r\n    const float epsilon = EPSILON;\r\n\r\n    float x = lut.coordinate_value_array[IDX_X * lut.matrix_dim + linear_coordinates];\r\n    float y = lut.coordinate_value_array[IDX_Y * lut.matrix_dim + linear_coordinates];\r\n    float z = lut.coordinate_value_array[IDX_Z * lut.matrix_dim + linear_coordinates];\r\n\r\n    float denominator = sqrt(pow(x, 2.0) + pow(y + Y_OFFSET, 2.0) + pow(z + Z_OFFSET, 2.0));\r\n\r\n    if (abs(denominator) < epsilon)\r\n    {\r\n        denominator = sqrt(TINY_NUMBER);\r\n    }\r\n\r\n    return (2.0/(denominator));\r\n}\r\n\r\n// Hydrogen molecule nucleus-electron Coulombic attraction function\r\nfloat attraction_function_hydrogen(Lut_t lut, int linear_coordinates)\r\n{\r\n    const float epsilon = EPSILON;\r\n\r\n    float x = lut.coordinate_value_array[IDX_X * lut.matrix_dim + linear_coordinates];\r\n    float y = lut.coordinate_value_array[IDX_Y * lut.matrix_dim + linear_coordinates];\r\n    float z = lut.coordinate_value_array[IDX_Z * lut.matrix_dim + linear_coordinates];\r\n\r\n    float denominator_1 = sqrt(pow((H2_BOND_LENGTH_ATOMIC_UNITS/2.0) - x, 2.0) + pow(y + Y_OFFSET, 2.0) + pow(z + Z_OFFSET, 2.0));\r\n    float denominator_2 = sqrt(pow((-H2_BOND_LENGTH_ATOMIC_UNITS/2.0) - x, 2.0) + pow(y + Y_OFFSET, 2.0) + pow(z + Z_OFFSET, 2.0));\r\n\r\n    if (abs(denominator_1) < epsilon)\r\n    {\r\n        denominator_1 = sqrt(TINY_NUMBER);\r\n    }\r\n\r\n    if (abs(denominator_2) < epsilon)\r\n    {\r\n        denominator_2 = sqrt(TINY_NUMBER);\r\n    }\r\n\r\n    return ((1.0/(denominator_1)) + (1.0/(denominator_2)));\r\n}\r\n\r\n// Generate the attraction matrix\r\nvoid generate_attraction_matrix(Lut_t lut, atomic_structure_e atomic_structure, float *matrix)\r\n{\r\n    if (atomic_structure == HELIUM_ATOM)\r\n    {\r\n        for (size_t diagonal_index = 0; diagonal_index < lut.matrix_dim; diagonal_index++)\r\n        {\r\n            matrix[diagonal_index + diagonal_index*lut.matrix_dim] = attraction_function_helium(lut, diagonal_index);\r\n        }\r\n    }\r\n    else if (atomic_structure == HYDROGEN_MOLECULE)\r\n    {\r\n        for (size_t diagonal_index = 0; diagonal_index < lut.matrix_dim; diagonal_index++)\r\n        {\r\n            matrix[diagonal_index + diagonal_index*lut.matrix_dim] = attraction_function_hydrogen(lut, diagonal_index);\r\n        }\r\n    }\r\n}\r\n\r\n// Electron-electron Coulombic repulsion function\r\nfloat repulsion_function(Lut_t lut, int linear_coordinates_1, int linear_coordinates_2)\r\n{\r\n    const float epsilon = EPSILON;\r\n\r\n    float x1 = lut.coordinate_value_array[IDX_X * lut.matrix_dim + linear_coordinates_1];\r\n    float y1 = lut.coordinate_value_array[IDX_Y * lut.matrix_dim + linear_coordinates_1];\r\n    float z1 = lut.coordinate_value_array[IDX_Z * lut.matrix_dim + linear_coordinates_1];\r\n\r\n    float x2 = lut.coordinate_value_array[IDX_X * lut.matrix_dim + linear_coordinates_2];\r\n    float y2 = lut.coordinate_value_array[IDX_Y * lut.matrix_dim + linear_coordinates_2];\r\n    float z2 = lut.coordinate_value_array[IDX_Z * lut.matrix_dim + linear_coordinates_2];\r\n\r\n    float denominator = sqrt(pow(x2 - x1, 2.0) + pow(y2 - y1, 2.0) + pow(z2 - z1, 2.0));\r\n\r\n    if (abs(denominator) < epsilon)\r\n    {\r\n        denominator = sqrt(TINY_NUMBER);\r\n    }\r\n\r\n    return (1.0/(denominator));\r\n}\r\n\r\nfloat repulsion_diagonal_integrand_function(Lut_t lut, float *orbital_values, int linear_coords_1, int linear_coords_2)\r\n{\r\n    return pow(orbital_values[linear_coords_2], 2.0)*repulsion_function(lut, linear_coords_1, linear_coords_2);\r\n}\r\n\r\nfloat exchange_diagonal_integrand_function(Lut_t lut, float *orbital_values, int linear_coords_1, int linear_coords_2)\r\n{\r\n    return orbital_values[linear_coords_1]*orbital_values[linear_coords_2]*repulsion_function(lut, linear_coords_1, linear_coords_2);\r\n}\r\n\r\nvoid generate_repulsion_diagonal(Lut_t lut, DynamicDataPointers_t ddp)\r\n{\r\n    for (size_t electron_one_coordinate_index = 0; electron_one_coordinate_index < lut.matrix_dim; electron_one_coordinate_index++)\r\n    {\r\n        float sum = 0;\r\n        for (size_t electron_two_coordinate_index = 0; electron_two_coordinate_index < lut.matrix_dim; electron_two_coordinate_index++)\r\n        {\r\n            sum += repulsion_diagonal_integrand_function(lut, ddp.orbital_values_data, electron_one_coordinate_index, electron_two_coordinate_index);\r\n        }\r\n        ddp.repulsion_diagonal_data[electron_one_coordinate_index] = sum*lut.step_size_cubed;\r\n    }\r\n}\r\n\r\n\r\nvoid generate_exchange_diagonal(Lut_t lut, DynamicDataPointers_t ddp)\r\n{\r\n    for (size_t electron_one_coordinate_index = 0; electron_one_coordinate_index < lut.matrix_dim; electron_one_coordinate_index++)\r\n    {\r\n        float sum = 0;\r\n        for (size_t electron_two_coordinate_index = 0; electron_two_coordinate_index < lut.matrix_dim; electron_two_coordinate_index++)\r\n        {\r\n            sum += exchange_diagonal_integrand_function(lut, ddp.orbital_values_data, electron_one_coordinate_index, electron_two_coordinate_index);\r\n        }\r\n        ddp.exchange_diagonal_data[electron_one_coordinate_index] = sum*lut.step_size_cubed;\r\n    }\r\n}\r\n\r\ntemplate <typename A, typename B, typename C, typename D, typename E>\r\nfloat calculate_total_energy(Eigen::MatrixBase<A> &orbital_values, Eigen::MatrixBase<B> &kinetic_matrix, Eigen::MatrixBase<C> &attraction_matrix, Eigen::MatrixBase<D> &repulsion_diagonal, Eigen::MatrixBase<E> &exchange_diagonal)\r\n{ \r\n    // orbital values are real, so no need to take conjugate\r\n    EigenFloatRowVector_t psi_prime = orbital_values.transpose();\r\n    EigenFloatColVector_t psi = orbital_values;\r\n\r\n    EigenFloatMatrix_t repulsion_matrix = repulsion_diagonal.asDiagonal();\r\n    EigenFloatMatrix_t exchange_matrix = exchange_diagonal.asDiagonal();\r\n\r\n    float energy_sum = 0;\r\n\r\n    console_print_hr(1, CLIENT_SIM);\r\n    console_print(1, \"Calculating total energy\", CLIENT_SIM);\r\n\r\n    // sum for the total number of electrons in the systems: 2\r\n    for (int i = 0; i < 2; i++)\r\n    {\r\n        auto hermitian_term = psi_prime * (-kinetic_matrix - attraction_matrix) * psi;\r\n        auto hf_term = 0.5 * psi_prime * (2.0 * repulsion_matrix - exchange_matrix) * psi;\r\n        energy_sum += (hermitian_term(0) + hf_term(0));\r\n    }\r\n\r\n    return energy_sum;\r\n}\r\n\r\n// Using the LAPACK routines directly by reimplementing the LAPACKE wrapper\r\n// without querying for sizes. I was originally using LAPACKE_ssyevd directly\r\n// from LAPACKE.h, but for some reason, the automatic work size was returning an\r\n// invalid number. I'm re-implementing the core of that function in this\r\n// version, but I'm using manual lwork and liwork calculations instead. From the\r\n// LAPACK documentation on ssyevd(): SSYEVD computes all eigenvalues and,\r\n// optionally, eigenvectors of a real symmetric matrix A. If eigenvectors are\r\n// desired, it uses a divide and conquer algorithm.The divide and conquer\r\n// algorithm makes very mild assumptions about floating point arithmetic.\r\n//\r\n// @param[in]  lut     Program constants\r\n// @param      matrix       The matrix originally containing the matrix to be\r\n//                          solved and the resulting eigenvectors\r\n// @param      eigenvalues  The eigenvalues of the solution\r\n//\r\n// @return     True if the solver found solutions, false if the solver failed\r\n//             for some reason\r\n//\r\nbool lapack_solve_eigh(Lut_t &lut, DynamicDataPointers_t ddp)\r\n{\r\n    char jobz = 'V'; // compute eigenvalues and eigenvectors.\r\n    char uplo = 'U'; // perform calculation on upper triangle of matrix\r\n    lapack_int n = lut.matrix_dim; // order of the matrix (size)\r\n    lapack_int lda = lut.matrix_dim; // the leading dimension of the array A. LDA >= max(1,N).\r\n    lapack_int info = 0;\r\n    lapack_int liwork;\r\n    lapack_int lwork;\r\n    lapack_int* iwork = nullptr;\r\n    float* work = nullptr;\r\n\r\n    auto lapack_start = chrono::system_clock::now();\r\n\r\n    console_print(0, \"LAPACK ssyevd start\", CLIENT_LAPACK);\r\n    console_print(2, TAB1 \"LAPACK solver debug\", CLIENT_LAPACK);\r\n    console_print(2, str(format(TAB2 \"n = %d\") % n), CLIENT_LAPACK);\r\n    console_print(2, str(format(TAB2 \"lda = %d\") % lda), CLIENT_LAPACK);\r\n\r\n    // Setting lwork and liwork manually based on the LAPACK documentation\r\n    lwork = 1 + 6*n + 2*n*n;\r\n    liwork = 3 + 5*n;\r\n\r\n    console_print(2, str(format(TAB2 \"liwork = %d\") % liwork), CLIENT_LAPACK);\r\n    console_print(2, str(format(TAB2 \"lwork = %d\") % lwork), CLIENT_LAPACK);\r\n\r\n    // Allocate memory for work arrays\r\n    iwork = (lapack_int*)malloc(sizeof(lapack_int) * liwork);\r\n    if(iwork == nullptr)\r\n    {\r\n        info = LAPACK_WORK_MEMORY_ERROR;\r\n        console_print_err(2, TAB2 \"FATAL! Could not allocate iwork array\", CLIENT_LAPACK);\r\n    }\r\n    work = (float*)malloc(sizeof(float) * lwork);\r\n    if(work == nullptr)\r\n    {\r\n        info = LAPACK_WORK_MEMORY_ERROR;\r\n        console_print_err(2, TAB2 \"FATAL! Could not allocate work array\", CLIENT_LAPACK);\r\n    }\r\n\r\n    // Call LAPACK function and adjust info if our work areas are OK\r\n    if ((iwork != nullptr) && (work != nullptr))\r\n    {\r\n        console_print(2, TAB2 \"calling LAPACK function\", CLIENT_LAPACK);\r\n        LAPACK_ssyevd(&jobz, &uplo, &n, ddp.eigenvectors_data, &lda, ddp.eigenvalues_data, work, &lwork, iwork, &liwork, &info);\r\n        if( info < 0 ) {\r\n            info = info - 1;\r\n        }\r\n    }\r\n\r\n    // Release memory and exit\r\n    LAPACKE_free(iwork);\r\n    LAPACKE_free(work);\r\n\r\n    console_print(2, str(format(TAB2 \"info = %d\") % info), CLIENT_LAPACK);\r\n\r\n    auto lapack_end = chrono::system_clock::now();\r\n    auto lapack_time = chrono::duration<float>(lapack_end - lapack_start);\r\n\r\n    console_print(0, str(format(\"LAPACK ssyevd took: %0.3f seconds\") % (float)(lapack_time.count())), CLIENT_LAPACK);\r\n\r\n    return (info==0);\r\n}\r\n\r\nint cpu_allocate_integration_memory(Lut_t &lut, DynamicDataPointers_t &ddp)\r\n{\r\n    int rv = 0;\r\n\r\n    console_print_hr(2, CLIENT_SIM);\r\n    console_print(2, \"Allocating memory for CPU integration\", CLIENT_SIM);\r\n\r\n    size_t orbital_vector_size_bytes = lut.matrix_dim;\r\n    size_t repulsion_exchange_matrices_size_bytes = lut.matrix_dim;\r\n    size_t coordinate_luts_size_bytes = IDX_NUM * lut.matrix_dim;\r\n\r\n    ddp.orbital_values_data = (float*)(calloc(orbital_vector_size_bytes, sizeof(float)));\r\n    ddp.repulsion_diagonal_data = (float*)(calloc(repulsion_exchange_matrices_size_bytes, sizeof(float)));\r\n    ddp.exchange_diagonal_data = (float*)(calloc(repulsion_exchange_matrices_size_bytes, sizeof(float)));\r\n\r\n    lut.coordinate_value_array = (float*)(calloc(coordinate_luts_size_bytes, sizeof(float)));\r\n    lut.coordinate_index_array = (float*)(calloc(coordinate_luts_size_bytes, sizeof(float)));\r\n\r\n    if ( (ddp.orbital_values_data == nullptr) || (ddp.repulsion_diagonal_data == nullptr) || (ddp.exchange_diagonal_data == nullptr) ||\r\n         (lut.coordinate_value_array == nullptr) || (lut.coordinate_index_array == nullptr) )\r\n    {\r\n        console_print_err(0, \"Memory allocation error!\", CLIENT_SIM);\r\n        rv = 1;\r\n    }\r\n    else\r\n    {\r\n        console_print(2, str(format(\"Allocated %d bytes for orbital values vector\") % orbital_vector_size_bytes), CLIENT_SIM);\r\n        console_print(2, str(format(\"Allocated %d bytes for repulsion matrix diagonal\") % repulsion_exchange_matrices_size_bytes), CLIENT_SIM);\r\n        console_print(2, str(format(\"Allocated %d bytes for exchange matrix diagonal\") % repulsion_exchange_matrices_size_bytes), CLIENT_SIM);\r\n        console_print(2, str(format(\"Allocated 3x %d bytes for coordinate LUTs\") % coordinate_luts_size_bytes), CLIENT_SIM);\r\n    }\r\n\r\n    return rv;\r\n}\r\n\r\nint cpu_allocate_eigensolver_memory(Lut_t &lut, DynamicDataPointers_t &ddp)\r\n{\r\n    int rv = 0;\r\n\r\n    console_print_hr(2, CLIENT_SIM);\r\n    console_print(2, \"Allocating memory for CPU eigensolver\", CLIENT_SIM);\r\n\r\n    size_t eigenvectors_size_bytes = sizeof(float) * lut.matrix_dim * lut.matrix_dim;\r\n    size_t eigenvalues_size_bytes = sizeof(float) * lut.matrix_dim;\r\n\r\n    ddp.eigenvectors_data = (float*)(malloc(eigenvectors_size_bytes));\r\n    ddp.eigenvalues_data = (float*)(malloc(eigenvalues_size_bytes));\r\n\r\n    if ((ddp.eigenvectors_data == nullptr) || (ddp.eigenvalues_data == nullptr))\r\n    {\r\n        console_print_err(0, \"Memory allocation error!\", CLIENT_SIM);\r\n        rv = 1;\r\n    }\r\n    else\r\n    {\r\n        console_print(2, str(format(\"Allocated %d bytes for eigenvector matrix\") % eigenvectors_size_bytes), CLIENT_SIM);\r\n        console_print(2, str(format(\"Allocated %d bytes for eigenvalue vector\") % eigenvalues_size_bytes), CLIENT_SIM);\r\n    }\r\n\r\n    return rv;\r\n}\r\n\r\nint cpu_free_integration_memory(Lut_t &lut, DynamicDataPointers_t &ddp)\r\n{\r\n    int rv = 0;\r\n\r\n    console_print(2, \"Freeing allocated integration memory...\", CLIENT_SIM);\r\n\r\n    free(ddp.orbital_values_data);\r\n    free(ddp.repulsion_diagonal_data);\r\n    free(ddp.exchange_diagonal_data);\r\n    free(lut.coordinate_value_array);\r\n    free(lut.coordinate_index_array);\r\n\r\n    // null the pointers\r\n    (ddp.orbital_values_data) = nullptr;\r\n    (ddp.repulsion_diagonal_data) = nullptr;\r\n    (ddp.exchange_diagonal_data) = nullptr;\r\n    (lut.coordinate_value_array) = nullptr;\r\n    (lut.coordinate_index_array) = nullptr;\r\n\r\n    console_print(2, \"Successfully freed allocated integration memory\", CLIENT_SIM);\r\n\r\n    return rv;\r\n}\r\n\r\nint cpu_free_eigensolver_memory(DynamicDataPointers_t &ddp)\r\n{\r\n    int rv = 0;\r\n\r\n    console_print(2, \"Freeing allocated eigensolver memory...\", CLIENT_SIM);\r\n\r\n    free(ddp.eigenvectors_data);\r\n    free(ddp.eigenvalues_data);\r\n\r\n    // null the pointers\r\n    ddp.eigenvectors_data = nullptr;\r\n    ddp.eigenvalues_data = nullptr;\r\n\r\n    console_print(2, \"Successfully freed allocated eigensolver memory\", CLIENT_SIM);\r\n\r\n    return rv;\r\n}\r\n\r\nvoid print_program_configurations(Cfg_t &config, Lut_t &lut)\r\n{\r\n    // Print program information\r\n    console_print_hr(0, CLIENT_SIM);\r\n    console_print(0, \"Program Configurations:\\n\", CLIENT_SIM);\r\n    console_print(0, str(format(TAB1 \"Verbosity = %d\") % config.verbosity), CLIENT_SIM);\r\n    console_print(0, str(format(TAB1 \"Iterations = %d\") % config.max_iterations), CLIENT_SIM);\r\n    console_print(0, str(format(TAB1 \"Num Partitions = %d\") % config.num_partitions), CLIENT_SIM);\r\n    console_print(0, str(format(TAB1 \"Limits = %d\") % config.limit), CLIENT_SIM);\r\n    console_print(0, str(format(TAB1 \"Matrix Dimension = %d\") % lut.matrix_dim), CLIENT_SIM);\r\n    console_print(0, str(format(TAB1 \"Step Size = %f\") % lut.step_size), CLIENT_SIM);\r\n\r\n    if (config.atomic_structure == HELIUM_ATOM)\r\n    {\r\n        console_print(0, TAB1 \"Atomic Structure: Helium Atom\", CLIENT_SIM);\r\n    }\r\n    else if (config.atomic_structure == HYDROGEN_MOLECULE)\r\n    {\r\n        console_print(0, TAB1 \"Atomic Structure: Hydrogen Molecule\", CLIENT_SIM);\r\n    }\r\n    console_print(0, str(format(TAB1 \"Maximum CPU Threads = %d\") % config.max_num_threads), CLIENT_SIM);\r\n}\r\n\r\nvoid config_cuda(Cfg_t &config)\r\n{\r\n    if (config.enable_cuda_eigensolver || config.enable_cuda_integration)\r\n    {\r\n        console_print(0, \"Checking for available CUDA devices\", CLIENT_SIM);\r\n        int num_cuda_devices = cuda_get_device_info();\r\n        if ((num_cuda_devices == 0) && (config.enable_cuda_eigensolver || config.enable_cuda_integration))\r\n        {\r\n            console_print_warn(0, \"Disabling CUDA acceleration since no device is available\", CLIENT_SIM);\r\n            config.enable_cuda_integration = false;\r\n            config.enable_cuda_eigensolver = false;\r\n        }\r\n    }\r\n}\r\n\r\n// Solve for Fock matrix eigenvectors\r\nvoid eigensolver(Cfg_t config, Lut_t &lut, PerformanceMonitor &perfmon, DynamicDataPointers_t ddp)\r\n{\r\n    console_print(1, \"Obtaining eigenvalues and eigenvectors\", CLIENT_SIM);\r\n\r\n    auto eig_start = chrono::system_clock::now();\r\n\r\n    if (config.enable_cuda_eigensolver)\r\n    {\r\n        // CUDA cuSOLVER\r\n        if (!cuda_eigensolver(lut, ddp))\r\n        {\r\n            console_print_err(0, \"Something went horribly wrong with the CUDA solver, aborting\", CLIENT_SIM);\r\n            exit(EXIT_FAILURE);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // Eigen solver, slow.\r\n        // EigenFloatMatrixMap_t eigenvectors(eigenvectors_data, lut.matrix_dim, lut.matrix_dim);\r\n        // EigenFloatColVectorMap_t eigenvalues(eigenvalues_data, lut.matrix_dim, 1);\r\n        // Eigen::SelfAdjointEigenSolver<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>> solver(eigenvectors);\r\n        // eigenvectors = solver.eigenvectors();\r\n        // eigenvalues = solver.eigenvalues();\r\n\r\n        // CPU LAPACK solver\r\n        if (!lapack_solve_eigh(lut, ddp))\r\n        {\r\n            console_print_err(0, \"Something went horribly wrong with the LAPACK solver, aborting\", CLIENT_SIM);\r\n            exit(EXIT_FAILURE);\r\n        }\r\n    }\r\n\r\n    auto eig_end = chrono::system_clock::now();\r\n    auto eig_time = chrono::duration<float>(eig_end - eig_start);\r\n    perfmon.record(PerformanceMonitor::ITERATION_EIGENSOLVER_TIME, (float)(eig_time.count()));\r\n    console_print(0, str(format(\"Eigenvalues and eigenvectors computed in: %0.3f seconds\") % (float)(eig_time.count())), CLIENT_SIM);\r\n}\r\n\r\nvoid generate_repulsion_and_integration_matrices(Cfg_t &config, Lut_t &lut, PerformanceMonitor &perfmon, DynamicDataPointers_t ddp)\r\n{\r\n    auto int_start = chrono::system_clock::now();\r\n\r\n    if (config.enable_cuda_integration)\r\n    {\r\n        console_print(0, \"Generating repulsion and exchange matrices on GPU\", CLIENT_SIM);\r\n\r\n        // generate repulsion and exchange matrices on GPU\r\n        cuda_numerical_integration(lut, ddp);\r\n    }\r\n    else\r\n    {\r\n        console_print(0, \"Generating repulsion and exchange matrices on CPU\", CLIENT_SIM);\r\n\r\n        // generate repulsion and exchange matrices on CPU\r\n        generate_repulsion_diagonal(lut, ddp);\r\n        generate_exchange_diagonal(lut, ddp);\r\n    }\r\n\r\n    auto int_end = chrono::system_clock::now();\r\n    auto int_time = chrono::duration<float>(int_end - int_start);\r\n    perfmon.record(PerformanceMonitor::ITERATION_INTEGRATION_TIME, (float)(int_time.count()));\r\n    console_print(0, str(format(\"Repulsion and exchange matrix computed in: %0.3f seconds\") % (float)(int_time.count())), CLIENT_SIM);\r\n}\r\n\r\nvoid print_csv_header(PerformanceMonitor &perfmon)\r\n{\r\n    cout << perfmon.str_csv_header();\r\n}\r\n\r\nvoid print_csv_data_all(Cfg_t &config, Lut_t &lut, PerformanceMonitor &perfmon)\r\n{\r\n    cout << perfmon.str_csv_data_all(config, lut);\r\n}\r\n\r\nvoid print_csv_data_average(Cfg_t &config, Lut_t &lut, PerformanceMonitor &perfmon)\r\n{\r\n    cout << perfmon.str_csv_data_average(config, lut);\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n    // Performance monitor object\r\n    PerformanceMonitor perfmon;\r\n    // Program config struct\r\n    Cfg_t config;\r\n    // Program lookup table values\r\n    Lut_t lut;\r\n\r\n    // Boost Program options\r\n    parse_program_options(argc, argv, config);\r\n\r\n    // Print the CSV header if requested, and exit the program\r\n    if (config.enable_csv_header_output)\r\n    {\r\n        print_csv_header(perfmon);\r\n        exit(EXIT_SUCCESS);\r\n    }\r\n\r\n    // Set the maximum number of thread to use for OMP and Eigen. This doesn't\r\n    // appear to modulate the number of threads the LAPACK solver is using, so\r\n    // something isn't right here. Leaving here anyways just in case I can fix\r\n    // it sometime later.\r\n    omp_set_dynamic(0); // Disable dynamic teams in OpenMP\r\n    omp_set_num_threads(config.max_num_threads); // Set the number of maximum threads to use for OMP (Eigen will use this value)\r\n\r\n    // Print the header\r\n    print_header();\r\n\r\n    // Fill out lut (the rest is done in populate_lookup_values once memory\r\n    // has been allocated for the arrays inside)\r\n    lut.matrix_dim = pow(config.num_partitions, 3.0);\r\n    lut.step_size = (float)(4<<1)/(float)(config.num_partitions - 1);\r\n    lut.step_size_cubed = pow(lut.step_size, 3.0);\r\n\r\n    // Print program configuration\r\n    print_program_configurations(config, lut);\r\n\r\n    // Get and print CUDA information\r\n    config_cuda(config);\r\n\r\n    // Matrix declarations\r\n    EigenFloatMatrix_t laplacian_matrix;\r\n    EigenFloatMatrix_t kinetic_matrix;\r\n    EigenFloatMatrix_t attraction_matrix;\r\n    EigenFloatColVectorMap_t repulsion_diagonal(nullptr, lut.matrix_dim, 1);\r\n    EigenFloatColVectorMap_t exchange_diagonal(nullptr, lut.matrix_dim, 1);\r\n    EigenFloatMatrix_t fock_matrix;\r\n    // Orbital values\r\n    EigenFloatColVectorMap_t orbital_values(nullptr, lut.matrix_dim, 1);\r\n    // Eigenvectors and eigenvalues\r\n    EigenFloatColVectorMap_t eigenvalues(nullptr, lut.matrix_dim, 1);\r\n    EigenFloatMatrixMap_t eigenvectors(nullptr, lut.matrix_dim, 1);\r\n\r\n    // For the repulsion, exchange, and orbital values, we will overlay the\r\n    // Eigen objects over unified memory that is allocated via CUDA (if\r\n    // enabled). Otherwise we will malloc data normally. This overlay is\r\n    // performed using the Eigen::Map object, which allows one to map a pointer\r\n    // to data allocated outside of Eigen to an Eigen object, like a matrix or\r\n    // vector. kernel.h externs the three pointers that are used to store the\r\n    // addresses and the following call will allocate memory for them. We will\r\n    // also allocate memory for the lookup tables used.\r\n    DynamicDataPointers_t ddp;\r\n    int allocate_error = 0;\r\n\r\n    allocate_error |= cpu_allocate_integration_memory(lut, ddp);\r\n    allocate_error |= cpu_allocate_eigensolver_memory(lut, ddp);\r\n\r\n    if (!allocate_error)\r\n    {\r\n        new (&orbital_values) EigenFloatColVectorMap_t(ddp.orbital_values_data, lut.matrix_dim, 1);\r\n        new (&repulsion_diagonal) EigenFloatColVectorMap_t(ddp.repulsion_diagonal_data, lut.matrix_dim, 1);\r\n        new (&exchange_diagonal) EigenFloatColVectorMap_t(ddp.exchange_diagonal_data, lut.matrix_dim, 1);\r\n        new (&eigenvectors) EigenFloatMatrixMap_t(ddp.eigenvectors_data, lut.matrix_dim, lut.matrix_dim);\r\n        new (&eigenvalues) EigenFloatColVectorMap_t(ddp.eigenvalues_data, lut.matrix_dim, 1);\r\n        // Populate LUTs\r\n        populate_lookup_values(config, lut);\r\n    }\r\n    else\r\n    {\r\n        console_print_err(0, \"Something went horribly wrong when allocating memory, aborting\", CLIENT_SIM);\r\n        exit(EXIT_FAILURE);\r\n    }\r\n\r\n    // Instantiate matrices and vectors\r\n    new (&laplacian_matrix) EigenFloatMatrix_t(lut.matrix_dim, lut.matrix_dim);\r\n    new (&kinetic_matrix) EigenFloatMatrix_t(lut.matrix_dim, lut.matrix_dim);\r\n    new (&attraction_matrix) EigenFloatMatrix_t(lut.matrix_dim, lut.matrix_dim);\r\n    new (&fock_matrix) EigenFloatMatrix_t(lut.matrix_dim, lut.matrix_dim);\r\n\r\n    // Trimmed eigenvectors and eigenvalues\r\n    EigenFloatColVector_t trimmed_eigenvalues(config.num_solutions, 1);\r\n    EigenFloatMatrix_t trimmed_eigenvectors(lut.matrix_dim, config.num_solutions);\r\n\r\n    console_print_hr(0, CLIENT_SIM);\r\n    console_print(0, \"Simulation start!\", CLIENT_SIM);\r\n    console_print_hr(0, CLIENT_SIM);\r\n    auto sim_start = chrono::system_clock::now();\r\n\r\n    // generate the second order Laplacian matrix for 3D space\r\n    console_print(1, \"Generating Laplacian matrix\", CLIENT_SIM);\r\n    generate_laplacian_matrix(lut, laplacian_matrix.data());\r\n    // generate the kinetic energy matrix\r\n    console_print(1, \"Generating kinetic energy matrix\", CLIENT_SIM);\r\n    kinetic_matrix = (laplacian_matrix/(2.0*lut.step_size*lut.step_size));\r\n    // generate the Coulombic attraction matrix\r\n    console_print(1, \"Generating electron-nucleus Coulombic attraction matrix\", CLIENT_SIM);\r\n    generate_attraction_matrix(lut, config.atomic_structure, attraction_matrix.data());\r\n\r\n    // Main HF loop\r\n    float last_total_energy = 0;\r\n    float total_energy;\r\n    float total_energy_percent_diff;\r\n    int interation_count = 0;\r\n\r\n    // initial solution\r\n    fock_matrix = -kinetic_matrix - attraction_matrix;\r\n\r\n    console_print(1, \"Solving for initial solution\", CLIENT_SIM);\r\n    // Solve for Fock matrix eigenvectors\r\n    eigenvectors = fock_matrix;\r\n    eigensolver(config, lut, perfmon, ddp);\r\n    orbital_values = eigenvectors.col(0);\r\n\r\n    do\r\n    {\r\n        console_print_hr(0, CLIENT_SIM);\r\n        console_print(0, str(format(\"Iteration Start: %d\") % interation_count), CLIENT_SIM);\r\n        console_print_hr(0, CLIENT_SIM);\r\n\r\n        auto iteration_start = chrono::system_clock::now();\r\n\r\n        // Generate repulsion and integraion matrices\r\n        generate_repulsion_and_integration_matrices(config, lut, perfmon, ddp);\r\n\r\n        // form fock matrix\r\n        console_print(1, \"Generating Fock matrix\", CLIENT_SIM);\r\n        fock_matrix = -kinetic_matrix - attraction_matrix + 2.0 * EigenFloatMatrix_t(repulsion_diagonal.asDiagonal()) - EigenFloatMatrix_t(exchange_diagonal.asDiagonal());\r\n\r\n        // Solve for Fock matrix eigenvectors and eigenvalues\r\n        eigenvectors = fock_matrix;\r\n        eigensolver(config, lut, perfmon, ddp);\r\n        orbital_values = eigenvectors.col(0);\r\n\r\n        // Extract num_solutions eigenvalues\r\n        trimmed_eigenvalues = eigenvalues.block(0, 0, config.num_solutions, 1);\r\n        // Extract num_solutions eigenvectors\r\n        trimmed_eigenvectors = eigenvectors.block(0, 0, lut.matrix_dim, config.num_solutions);\r\n\r\n        total_energy = calculate_total_energy(orbital_values, kinetic_matrix, attraction_matrix, repulsion_diagonal, exchange_diagonal);\r\n        perfmon.record(PerformanceMonitor::ITERATION_TOTAL_ENERGY, total_energy);\r\n        total_energy_percent_diff = abs((total_energy - last_total_energy)/((total_energy + last_total_energy) / 2.0));\r\n\r\n        console_print_hr(0, CLIENT_SIM);\r\n        console_print(0, str(format(\"Total energy: %.3f\") % (total_energy)), CLIENT_SIM);\r\n        console_print(0, str(format(\"Energy %% diff: %.3f%%\") % (total_energy_percent_diff * 100.0)), CLIENT_SIM);\r\n\r\n        // update last value\r\n        last_total_energy = total_energy;\r\n        // update iteration count\r\n        interation_count++;\r\n\r\n        auto iteration_end = chrono::system_clock::now();\r\n        auto iteration_time = chrono::duration<float>(iteration_end - iteration_start);\r\n        perfmon.record(PerformanceMonitor::ITERATION_TOTAL_TIME, (float)(iteration_time.count()));\r\n        console_print(0, str(format(\"Iteration end! Iteration time: %0.3f seconds\") % (float)(iteration_time.count())), CLIENT_SIM);\r\n\r\n        // Increment performance monitor data\r\n        perfmon.next_iteration();\r\n\r\n        // check if we've hit the maximum iteration limit\r\n        if (interation_count == config.max_iterations)\r\n        {\r\n            break;\r\n        }\r\n\r\n        // check if we meet convergence condition\r\n        if (abs(total_energy_percent_diff) < (config.convergence_percentage/100.0))\r\n        {\r\n            break;\r\n        }\r\n    }\r\n    while(1);\r\n\r\n    cpu_free_integration_memory(lut, ddp);\r\n    cpu_free_eigensolver_memory(ddp);\r\n\r\n    console_print_hr(0, CLIENT_SIM);\r\n    console_print(0, \"Final Eigenvalues:\", CLIENT_SIM);\r\n    stringstream ss;\r\n    ss << trimmed_eigenvalues.transpose();\r\n    console_print(0, ss.str(), CLIENT_SIM);\r\n    ss.str(string()); // clear ss\r\n    console_print_hr(0, CLIENT_SIM);\r\n    console_print(0, str(format(\"Final Total energy: %.3f\") % (total_energy)), CLIENT_SIM);\r\n    console_print_hr(0, CLIENT_SIM);\r\n\r\n    auto sim_end = chrono::system_clock::now();\r\n    auto sim_time = chrono::duration<float>(sim_end - sim_start);\r\n    perfmon.total_time = (float)(sim_time.count());\r\n    console_print(0, str(format(\"Simulation end! Total time: %0.3f seconds\") % (float)(sim_time.count())), CLIENT_SIM);\r\n\r\n    console_print_hr(0, CLIENT_SIM);\r\n    console_print(0, \"Performance monitor records:\", CLIENT_SIM);\r\n    console_print(0, perfmon.str(), CLIENT_SIM);\r\n    console_print_hr(0, CLIENT_SIM);\r\n\r\n    if (config.enable_csv_data_all_output)\r\n    {\r\n        print_csv_data_all(config, lut, perfmon);\r\n    }\r\n    else if (config.enable_csv_data_average_output)\r\n    {\r\n        print_csv_data_average(config, lut, perfmon);\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "7b276081e043da071f615a969401d86240ef0063", "size": 39215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project/cpp/main.cpp", "max_stars_repo_name": "umamibeef/UBC-ELEC-542-Coursework", "max_stars_repo_head_hexsha": "33145e95730a5c9d9cfb1252cc67ebe6820c58c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/cpp/main.cpp", "max_issues_repo_name": "umamibeef/UBC-ELEC-542-Coursework", "max_issues_repo_head_hexsha": "33145e95730a5c9d9cfb1252cc67ebe6820c58c4", "max_issues_repo_licenses": ["MIT"], "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/cpp/main.cpp", "max_forks_repo_name": "umamibeef/UBC-ELEC-542-Coursework", "max_forks_repo_head_hexsha": "33145e95730a5c9d9cfb1252cc67ebe6820c58c4", "max_forks_repo_licenses": ["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.2575431034, "max_line_length": 229, "alphanum_fraction": 0.6698712227, "num_tokens": 9471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.04468086804648062, "lm_q1q2_score": 0.021816925954500726}}
{"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// Adapted from GLAS implementation by Karl Meerbergen and Toon Knappen\n\n\n#ifndef MTL_DENSE_VECTOR_INCLUDE\n#define MTL_DENSE_VECTOR_INCLUDE\n\n\n#include <iostream>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <boost/static_assert.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_integral.hpp>\n\n#include <boost/numeric/mtl/utility/assert.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/vector/all_vec_expr.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/detail/contiguous_memory_block.hpp>\n#include <boost/numeric/mtl/vector/crtp_base_vector.hpp>\n#include <boost/numeric/mtl/utility/dense_el_cursor.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/utility/is_static.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/transposed_orientation.hpp>\n#include <boost/numeric/mtl/operation/is_negative.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#ifdef MTL_WITH_INITLIST\n# include <initializer_list>\n#endif\n\nnamespace mtl { namespace vec {\n\n/// Dense vector\ntemplate <class Value, typename Parameters = parameters<> >\nclass dense_vector\n  : public vec_expr<dense_vector<Value, Parameters> >,\n    public ::mtl::detail::contiguous_memory_block< Value, Parameters::on_stack, Parameters::dimension::value >,\n    public crtp_base_vector< dense_vector<Value, Parameters>, Value, std::size_t >\n{\n  public:\n    typedef dense_vector<Value, Parameters>                                          self;\n    typedef ::mtl::detail::contiguous_memory_block< Value, Parameters::on_stack, \n                                                    Parameters::dimension::value >   memory_base;\n    typedef crtp_base_vector< self, Value, std::size_t >                             crtp_base;\n    typedef crtp_vector_assign< self, Value, std::size_t >                           assign_base;\n    typedef vec_expr<dense_vector<Value, Parameters> >                               expr_base;\n    typedef Value             value_type ; \n    typedef std::size_t       size_type ;\n    typedef value_type&       reference ;\n    typedef value_type const& const_reference ;\n    typedef Value*            pointer ;\n    typedef Value const*      const_pointer ;\n    typedef typename Parameters::orientation  orientation;\n\n    typedef const_pointer     key_type;\n    \n    /// Check whether index is non-negative and less than size\n    void check_index( size_type MTL_DEBUG_ARG(i) ) const\n    {\n\tMTL_CRASH_IF( is_negative(i) ||  i >= this->used_memory(), \"Index out of range!\");\n    }\n\n    /// Check for a given vector if the sizes are equal or this has size 0 (and can take the size of source)\n    void check_dim( size_type MTL_DEBUG_ARG(s) ) const\n    {\n\tMTL_CRASH_IF( this->used_memory() != 0 && this->used_memory() != s, \"Incompatible size!\");\n    }\n\n    /// Check at compile time for a given vector if the sizes are equal\n    void static_check( size_type MTL_DEBUG_ARG(s) ) const\n    {\n\tassert(!traits::is_static<self>::value || s == size(typename Parameters::dimension()));\n    }\n\n    /// Check if a given vector expression whether it has the same shape as the object\n    /** Both must be row vectors or column vectors. The elements must have the same\n\talgebraic shape, e.g. a row vector of scalars is not compatible with a row\n\tvector of matrices. **/\n    template <class E>\n    void check_consistent_shape( vec_expr<E> const& ) const\n    {\n\tMTL_CRASH_IF((!boost::is_same<\n\t\t\t        typename ashape::ashape<self>::type\n\t\t\t      , typename ashape::ashape<E>::type\n\t\t\t    >::value),\n\t\t\t   \"Incompatible shape!\");\n    }\n\n    /// Default constructor\n    dense_vector( ) : memory_base( Parameters::dimension::value ) {}\n    \n    /// Constructor for size \\p n\n    explicit dense_vector( size_type n ) : memory_base( n ) { static_check( n ); }\n    \n    /// Constructor for size \\p n and value \\p value that is set in all entries\n    explicit dense_vector( size_type n, value_type value )\n      : memory_base( n ) \n    {\n\tstatic_check( n );\n\tstd::fill(begin(), end(), value);\n    }\n\n    /// Constructor for size \\p n and \\p address\n    /** Can be used to handle vectors from other libraries, even in other languages like Fortran **/\n    explicit dense_vector( size_type n, value_type *address )\n      : memory_base( address, n, true ) \n    { static_check( n ); }\n\n    /// Copy constructor\n    dense_vector( const self& src )\n      : memory_base( src ) \n    {\n\tvampir_trace<2042> tracer;\n\tusing std::copy;\n\tcopy(src.begin(), src.end(), this->begin());\n    }\n\n#ifdef MTL_WITH_MOVE\n    dense_vector(self&& src) : memory_base(std::move(src)) {}\n#endif\n\n    /// Clone constructor\n    /** Copies every vector, even those that refer to external data, sub-vectors, or rows and columns in a matrix **/\n    dense_vector( const self& src, clone_ctor )\n      : memory_base( src, clone_ctor()) {} \n\n    struct dummy_type {};\n\n    /// Constructor from vector expressions\n    template <typename VectorSrc>\n    explicit dense_vector(const VectorSrc& src,\n\t\t\t  typename boost::disable_if<boost::is_integral<VectorSrc>, dummy_type>::type= dummy_type())\n    {\tvampir_trace<2043> tracer; *this= src;    }\n\n#ifdef MTL_WITH_INITLIST\n    /// Constructor for initializer list \\p values \n    template <typename Value2>\n    dense_vector(std::initializer_list<Value2> values)\n      : memory_base(values.size()) \n    {\n\tstatic_check(values.size());\n\tstd::copy(values.begin(), values.end(), begin());\n    }\n\n    /// Assignment from initializer list \\p values \n    template <typename Value2>\n    self& operator=(std::initializer_list<Value2> values)\n    {\n\tchecked_change_dim(values.size());\n\tstd::copy(values.begin(), values.end(), begin());\n\treturn *this;\n    }\n#endif\n\n    /// Constructor from std::vector; value_type must be identic\n    explicit dense_vector(const std::vector<value_type>& src)\n      : memory_base(src.size()) \n    {\tstd::copy(src.begin(), src.end(), this->begin());    }\n\n    /// Stride is always 1 \n    size_type stride() const { return 1 ; }\n\n    /// i-th entry\n    reference operator()( size_type i ) \n    {\n        check_index(i);\n        return this->value_n( i ) ;\n    }\n\n    /// i-th entry (constant)\n    const_reference operator()( size_type i ) const \n    {\n        check_index(i);\n        return this->value_n( i ) ;\n    }\n\n    reference operator[]( size_type i ) { return (*this)( i ) ; } ///< i-th entry\n    const_reference operator[]( size_type i ) const { return (*this)( i ) ;  } ///< i-th entry (constant)\n\n    self operator[]( irange r ) { return sub_vector(*this, r.start(), r.finish()); } ///< sub-vector\n    const self  operator[]( irange r ) const { return sub_vector(*this, r.start(), r.finish());  } ///< sub-vector\n    \n    void delay_assign() const {}\n\n    // Compatibility with STL\n    const_pointer begin() const { return this->elements() ; }\n    const_pointer end() const { return this->elements() + this->used_memory(); }    \n    pointer begin() { return this->elements() ; }\n    pointer end() { return this->elements() + this->used_memory(); }\n    bool empty() const { return this->used_memory() == 0; } ///< Whether it is empty\n\n\n    /// Address of first data entry; to be used with care.\n    value_type* address_data() { return begin(); }\n    const value_type* address_data() const { return begin(); }\n    \n\n#ifdef MTL_VECTOR_MOVE_EMULATION\n    /// Move assignment\n    self& operator=(self src)\n    {\n\t// Self-copy would be an indication of an error\n\tassert(this != &src);\n\n\tchecked_change_dim(src.used_memory());\n\tmemory_base::move_assignment(src);\n\treturn *this;\n    }\n#else\n// #if defined(_MSC_VER) && !defined(MTL_VECTOR_MOVE_EMULATION)\n    /// Copy assignment\n    self& operator=(const self& src)\n    {\n\tif (this == &src)\n\t    return *this;\n\n\tchecked_change_dim(src.used_memory());\n\tmemory_base::operator=(src);\n\treturn *this;\n    }\n#endif\n\n#ifdef MTL_WITH_MOVE\n    self& operator=(self&& src)\n    {\n\tchecked_change_dim(src.used_memory());\n\tmemory_base::move_assignment(src);\n\treturn *this;\n    }\n#endif\n\n#if 0 // def __PGI\n    using crtp_base::operator=;\n#else\n    using assign_base::operator=;\n#endif\n\n    template <typename Value2> friend void fill(self&, const Value2&);\n\n    /// swap two vectors\n    friend void swap(self& vector1, self& vector2)\n    {\n\tswap(static_cast<memory_base&>(vector1), static_cast<memory_base&>(vector2));\n    }\n\n    void change_resource(size_type n) { this->realloc(n); } ///< Change resource, like \\ref change_dim\n    void change_dim(size_type n) { this->realloc(n); } ///< Change dimension of vector\n    void checked_change_dim(size_type n) { check_dim(n); change_dim(n); } ///< Only change dim if it was empty before\n    \n    void crop() {} ///< Delete structural zeros, only dummy here for completeness\n\n} ; // dense_vector\n\n\n/// Size of v\ntemplate <typename Value, typename Parameters>\ninline typename dense_vector<Value, Parameters>::size_type \nsize(const dense_vector<Value, Parameters>& v)  \n{ return v.used_memory() ; }\n\n\n\n// ================\n// Free functions\n// ================\n\n/// Fill \\p vector with \\p value\ntemplate <typename Value, typename Parameters, typename Value2>\ninline void fill(dense_vector<Value, Parameters>& vector, const Value2& value)\n{\n    std::fill(vector.begin(), vector.end(), value);    \n}\n\n\ntemplate <typename Value, typename Parameters>\ntypename dense_vector<Value, Parameters>::size_type\ninline num_rows_aux(const dense_vector<Value, Parameters>& , tag::row_major)\n{\n    return 1;\n}\n\ntemplate <typename Value, typename Parameters>\ntypename dense_vector<Value, Parameters>::size_type\ninline num_rows_aux(const dense_vector<Value, Parameters>& vector, tag::col_major)\n{\n    return vector.used_memory();\n}\n\n/// Number of rows: is size for column vectors and 1 for row vectors\ntemplate <typename Value, typename Parameters>\ntypename dense_vector<Value, Parameters>::size_type\ninline num_rows(const dense_vector<Value, Parameters>& vector)\n{\n    return num_rows_aux(vector, typename Parameters::orientation());\n}\n\n\n/// Number of columns: is size for row vectors and 1 for column vectors\ntemplate <typename Value, typename Parameters>\ntypename dense_vector<Value, Parameters>::size_type\ninline num_cols(const dense_vector<Value, Parameters>& vector)\n{\n    return num_rows_aux(vector, typename mtl::traits::transposed_orientation<typename Parameters::orientation>::type());\n}\n\n/// Sub-vector function, more convenient with irange\ntemplate <typename Value, typename Parameters>\ndense_vector<Value, Parameters>\ninline sub_vector(dense_vector<Value, Parameters>& v, \n\t\t  typename dense_vector<Value, Parameters>::size_type start,\n\t\t  typename dense_vector<Value, Parameters>::size_type finish)\n{\n    typedef dense_vector<Value, Parameters>    Vector;\n\n    MTL_CRASH_IF( is_negative(start) || is_negative(finish), \"Index out of range!\");\n    irange r= intersection(irange(start, finish), irange(0, mtl::vec::size(v)));\n    return r.empty() ? Vector() : Vector(r.size(), &v[r.start()]);\n\n#if 0\n    finish= min(finish, size(v));\n    start= min(start, finish); // implies min(start, size(v))\n    return start < finish ? Vector(finish - start, &v[start]) : Vector();\n#endif\n}\n\ntemplate <typename Value, typename Parameters>\nconst dense_vector<Value, Parameters>\ninline sub_vector(const dense_vector<Value, Parameters>& v, \n\t\t  typename dense_vector<Value, Parameters>::size_type start,\n\t\t  typename dense_vector<Value, Parameters>::size_type finish)\n{\n    typedef dense_vector<Value, Parameters>    Vector;\n    return sub_vector(const_cast<Vector&>(v), start, finish);\n}\n\n\n}} // namespace mtl::vector\n\nnamespace mtl {\n\n    // Enable cloning of dense vectors\n    template <typename Value, typename Parameters>\n    struct is_clonable< vec::dense_vector<Value, Parameters> > : boost::mpl::true_ {};\n        \n} // namespace mtl\n\nnamespace mtl { namespace traits {\n\n\n// ================\n// Range generators\n// For cursors\n// ================\n\n    template <typename Value, class Parameters>\n    struct range_generator<tag::all, mtl::vec::dense_vector<Value, Parameters> >\n      : public detail::dense_element_range_generator<mtl::vec::dense_vector<Value, Parameters>,\n\t\t\t\t\t\t     dense_el_cursor<Value>, complexity_classes::linear_cached>\n    {};\n\n    template <typename Value, class Parameters>\n    struct range_generator<tag::nz, mtl::vec::dense_vector<Value, Parameters> >\n\t: public range_generator<tag::all, mtl::vec::dense_vector<Value, Parameters> >\n    {};\n\n    template <typename Value, class Parameters>\n    struct range_generator<tag::iter::all, mtl::vec::dense_vector<Value, Parameters> >\n    {\n\ttypedef mtl::vec::dense_vector<Value, Parameters>   collection_t;\n\ttypedef complexity_classes::linear_cached complexity;\n\tstatic int const                          level = 1;\n\ttypedef typename collection_t::pointer    type;\n\n\ttype begin(collection_t& collection)\n\t{\n\t    return collection.begin();\n\t}\n\ttype end(collection_t& collection)\n\t{\n\t    return collection.end();\n\t}\n    };\n\n    template <typename Value, class Parameters>\n    struct range_generator<tag::iter::nz, mtl::vec::dense_vector<Value, Parameters> >\n\t: public range_generator<tag::iter::all, mtl::vec::dense_vector<Value, Parameters> >\n    {};\n\n    template <typename Value, class Parameters>\n    struct range_generator<tag::const_iter::all, mtl::vec::dense_vector<Value, Parameters> >\n    {\n\ttypedef mtl::vec::dense_vector<Value, Parameters>   collection_t;\n\ttypedef complexity_classes::linear_cached complexity;\n\tstatic int const                          level = 1;\n\ttypedef typename collection_t::const_pointer type;\n\n\ttype begin(const collection_t& collection) const\n\t{\n\t    return collection.begin();\n\t}\n\ttype end(const collection_t& collection) const\n\t{\n\t    return collection.end();\n\t}\n    };\n\n    template <typename Value, class Parameters>\n    struct range_generator<tag::const_iter::nz, mtl::vec::dense_vector<Value, Parameters> >\n\t: public range_generator<tag::const_iter::all, mtl::vec::dense_vector<Value, Parameters> >\n    {};\n\n\t\n}} // namespace mtl::traits\n\nnamespace mtl {\n    using vec::dense_vector;\n}\n\n#endif // MTL_DENSE_VECTOR_INCLUDE\n\n", "meta": {"hexsha": "066f2bff338d4d5b8e29510190ab2661ddd8c58d", "size": 14710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/vector/dense_vector.hpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/vector/dense_vector.hpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/vector/dense_vector.hpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 33.5844748858, "max_line_length": 120, "alphanum_fraction": 0.6847722638, "num_tokens": 3422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.059210255721647315, "lm_q1q2_score": 0.02170587285205405}}
{"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_NLOPT_BASE_HPP\n#define LIMBO_OPT_NLOPT_BASE_HPP\n\n#ifndef USE_NLOPT\n#warning No NLOpt\n#else\n#include <Eigen/Core>\n\n#include <vector>\n\n#include <nlopt.hpp>\n\n#include <limbo/opt/optimizer.hpp>\n#include <limbo/tools/macros.hpp>\n\nnamespace limbo {\n    namespace opt {\n        /**\n          @ingroup opt\n        Base class for NLOpt wrappers\n        */\n        template <typename Params, nlopt::algorithm Algorithm>\n        struct NLOptBase {\n        public:\n            virtual void initialize(int dim)\n            {\n                _opt = nlopt::opt(Algorithm, dim);\n                _initialized = true;\n            }\n\n            template <typename F>\n            Eigen::VectorXd operator()(const F& f, const Eigen::VectorXd& init, bool bounded)\n            {\n                int dim = init.size();\n                if (!_initialized)\n                    initialize(dim);\n\n                _opt.set_max_objective(nlopt_func<F>, (void*)&f);\n\n                std::vector<double> x(dim);\n                Eigen::VectorXd::Map(&x[0], dim) = init;\n\n                if (bounded) {\n                    _opt.set_lower_bounds(std::vector<double>(dim, 0));\n                    _opt.set_upper_bounds(std::vector<double>(dim, 1));\n                }\n\n                double max;\n\n                try {\n                    _opt.optimize(x, max);\n                }\n                catch (nlopt::roundoff_limited& e) {\n                    // In theory it's ok to ignore this error\n                    std::cerr << \"[NLOptNoGrad]: \" << e.what() << std::endl;\n                }\n                catch (std::invalid_argument& e) {\n                    // In theory it's ok to ignore this error\n                    std::cerr << \"[NLOptNoGrad]: \" << e.what() << std::endl;\n                }\n                catch (std::runtime_error& e) {\n                    // In theory it's ok to ignore this error\n                    std::cerr << \"[NLOptGrad]: \" << e.what() << std::endl;\n                }\n\n                return Eigen::VectorXd::Map(x.data(), x.size());\n            }\n\n            // Inequality constraints of the form f(x) <= 0\n            template <typename F>\n            void add_inequality_constraint(const F& f, double tolerance = 1e-8)\n            {\n                if (_initialized)\n                    _opt.add_inequality_constraint(nlopt_func<F>, (void*)&f, tolerance);\n                else\n                    std::cerr << \"[NLOptNoGrad]: Trying to set an inequality constraint without having initialized the optimizer! Nothing will be done!\" << std::endl;\n            }\n\n            // Equality constraints of the form f(x) = 0\n            template <typename F>\n            void add_equality_constraint(const F& f, double tolerance = 1e-8)\n            {\n                if (_initialized)\n                    _opt.add_equality_constraint(nlopt_func<F>, (void*)&f, tolerance);\n                else\n                    std::cerr << \"[NLOptNoGrad]: Trying to set an equality constraint without having initialized the optimizer! Nothing will be done!\" << std::endl;\n            }\n\n        protected:\n            nlopt::opt _opt;\n            bool _initialized = false;\n\n            template <typename F>\n            static double nlopt_func(const std::vector<double>& x, std::vector<double>& grad, void* my_func_data)\n            {\n                F* f = (F*)(my_func_data);\n                Eigen::VectorXd params = Eigen::VectorXd::Map(x.data(), x.size());\n                double v;\n                if (!grad.empty()) {\n                    auto r = eval_grad(*f, params);\n                    v = opt::fun(r);\n                    Eigen::VectorXd g = opt::grad(r);\n                    Eigen::VectorXd::Map(&grad[0], g.size()) = g;\n                }\n                else {\n                    v = eval(*f, params);\n                }\n                return v;\n            }\n        };\n    } // namespace opt\n} // namespace limbo\n\n#endif\n#endif\n", "meta": {"hexsha": "7dc89cf139c9e54f7dab1a6b1cab5d08f31e7f7f", "size": 6341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/opt/nlopt_base.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/nlopt_base.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/nlopt_base.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.3850931677, "max_line_length": 166, "alphanum_fraction": 0.5800346948, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.04742587284097444, "lm_q1q2_score": 0.021680107803201308}}
{"text": "/**\n * \\file der_snr.cpp\n * \\brief An C++ implementation of the der_snr fortran code from: \n * F. Stoehr et al: DER_SNR: A Simple & General Spectroscopic Signal-to-Noise Measurement Algorithm,\\n\n    394, Astronomical Data Analysis Software and Systems (ADASS) XVII\\n\n    2008ASPC..394..505S\n * \\author Audric Lemonnier\n * \\version 0.2\n * \\date 18/04/2020\n */\n\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <cmath>\n#include <functional> \n#include <thread>\n#include <future>\n#include <tuple>\n#include <chrono>\n\n#include <boost/program_options.hpp>\n\n#if __has_include (<boost/timer/timer.hpp>)\n#include <boost/timer/timer.hpp> \n#define HAS_BOOST_TIMER /**< boost::timer availability */\n#endif\n\n#if __has_include (<sys/syscall.h>)\n#include <sys/syscall.h>\n#define HAS_SYSCALL /**< linux syscall availability */\n#endif\n\n#if __has_include (<filesystem>)\n#include <filesystem>\n#define FS_STD /**< std::filesystem availability (C++17) */\nnamespace fs = std::filesystem;\n#elif __has_include (<experimental/filesystem>) && !__has_include (<filesystem>)\n#include <experimental/filesystem>\n#define FS_STDEXP /**< std::experimental::filesystem availability */\nnamespace fs = std::experimental::filesystem;\n#elif __has_include(<boost/filesystem.hpp>) && !__has_include (<filesystem>) && !__has_include (<experimental/filesystem>)\n#include <boost/filesystem.hpp>\n#define FS_BOOST /**< boost::filesystem availability */\nnamespace fs = boost::filesystem;\n#else\n#error \"No filesystem header found\"\n#endif\n\n#include <csv.h>\n#include <msg.h>\n#include <log.h>\n#include <der_snr.h>\n\n// Reference\n// ----------------------------------------------------\n// F. Stoehr et al: DER_SNR: A Simple & General Spectroscopic Signal-to-Noise Measurement Algorithm\n// 394, Astronomical Data Analysis Software and Systems (ADASS) XVII\n// 2008ASPC..394..505S\n// ----------------------------------------------------\n\nint main(int argc, char** argv) {\n    \n#ifdef HAS_BOOST_TIMER    \n    boost::timer::cpu_timer btTimer;\n#endif\n    \n    _msg msgM;\n    msgM.set_name(\"der_snr\");\n    msgM.set_log(LOGFILE);\n    \n// Parse cmd line\n// ----------------------------------------------------  \n    namespace po = boost::program_options;\n    po::options_description description(\"Usage\");\n    \n    description.add_options()\n    (\"help,h\", \"Display this help message\")\n    (\"filename,f\",  po::value<std::string>(),\"Filename of the spectrum\")\n    (\"directory,d\",  po::value<std::string>(),\"Directory where compute the S/N\")\n    (\"output,o\",  po::value<std::string>()->default_value(\"output.csv\"),\"Filename of results\")\n    (\"separator,s\",  po::value<char>()->default_value('\\t'),\"The column separator. Do not set this option for \\\\tab.\")\n    (\"exclude,e\",  po::value<std::string>(),\"Exclude a string in filenames\");\n    \n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(description).run(), vm);\n    po::notify(vm);\n    \n     if (vm.count(\"help\") || vm.size()<1 || !(vm.count(\"filename\") ^ vm.count(\"directory\"))) {\n        msgM.enable_log(false);\n        std::cout << description;\n        std::cout << std::endl;\n        std::cout << \"Examples:\\n\";\n        std::cout << \"./der_snr -f CPD-591792.obs\\n\";\n        msgM.msg(_msg::eMsg::START);\n        msgM.msg(_msg::eMsg::MID, \"check command line\");\n        msgM.msg(_msg::eMsg::MID, \"compute S/N for 1 file\");\n        msgM.msg(_msg::eMsg::MID, \"CPD-591792.obs: S/N = 95.68\");\n        msgM.msg(_msg::eMsg::MID, \"output: output.csv\");\n        msgM.msg(_msg::eMsg::END, \" 0.039347s wall, 0.040000s user + 0.000000s system = 0.040000s CPU (101.7%)\\n\");\n        std::cout << std::endl;\n        \n        std::cout << \"./der_snr -d data\\n\";\n        msgM.msg(_msg::eMsg::START);\n        msgM.msg(_msg::eMsg::MID, \"check command line\");\n        msgM.msg(_msg::eMsg::MID, \"CPU utilization: 0 %\");\n        msgM.msg(_msg::eMsg::MID, \"starting 8 async threads\");\n        msgM.set_threadname(\"compute\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 521 files\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 521 files\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 521 files\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 521 files\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 521 files\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 521 files\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 521 files\");\n        msgM.msg(_msg::eMsg::THREADS, \"S/N for 524 files\");\n        msgM.set_name(\"merge()\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part1_snr.csv\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part2_snr.csv\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part3_snr.csv\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part4_snr.csv\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part5_snr.csv\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part6_snr.csv\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part7_snr.csv\");\n        msgM.msg(_msg::eMsg::MID, \"merge file part8_snr.csv\");\n        msgM.set_name(\"der_snr\");\n        msgM.msg(_msg::eMsg::MID, \"output: output.csv\");        \n        msgM.msg(_msg::eMsg::END, \" 56.395825s wall, 323.050000s user + 0.450000s system = 323.500000s CPU (573.6%)\\n\");\n        \n        std::cout << \"\\nRef:\\n\";\n        std::cout << \"F. Stoehr et al: DER_SNR: A Simple & General Spectroscopic Signal-to-Noise Measurement Algorithm\\n\";\n        std::cout << \"394, Astronomical Data Analysis Software and Systems (ADASS) XVII\\n\";\n        std::cout << \"2008ASPC..394..505S\\n\";\n        return EXIT_SUCCESS;\n    }\n    \n    bool bDefExclude=false;\n    bool bDefSep=false;\n    \n    std::string sOutput;\n    std::string sExclude;\n    \n    char cSep;\n    \n    fs::path pDirectory;\n    fs::path pFilename;\n    fs::path pOutput;\n    \n    // ----------------------------------------------------\n    msgM.msg(_msg::eMsg::START);\n    \n    _log log;\n    log.set_execname(argv);\n    log.set_historyname(HISTFILE);\n    log.set_logname(LOGFILE);\n    \n    // Write history\n    // ----------------------------------------------------  \n    msgM.msg(_msg::eMsg::MID, \"write history\");\n    if (!log.write_history(vm))\n        msgM.msg(_msg::eMsg::ERROR, \"cannot open history\");\n    // ----------------------------------------------------    \n    \n    // Remove duplicates\n    // ----------------------------------------------------\n    msgM.msg(_msg::eMsg::MID, \"remove duplicates in history\");\n    if (!log.remove_duplicate())\n        msgM.msg(_msg::eMsg::ERROR, \"cannot open history\");\n    // ----------------------------------------------------\n    \n    msgM.msg(_msg::eMsg::MID, \"check command line\");\n    \n    if (vm.count(\"directory\") && vm.count(\"filename\")) {\n        msgM.msg(_msg::eMsg::ERROR, \"ambiguous entries\");\n        return EXIT_FAILURE;\n    }\n    \n    if (vm.count(\"directory\")) {\n        pDirectory=fs::path(vm[\"directory\"].as<std::string>());\n        if (!fs::is_directory(pDirectory)) {\n            msgM.msg(_msg::eMsg::ERROR, pDirectory.string(),\"does not exist\");\n            return EXIT_FAILURE;\n        }\n    }\n    \n    if (vm.count(\"filename\")) {\n        pFilename=fs::path(vm[\"filename\"].as<std::string>());\n        if (!fs::exists(pFilename)) {\n            msgM.msg(_msg::eMsg::ERROR, \"error:\", pFilename.string(),\"does not exist\");\n            return EXIT_FAILURE;\n        }\n    }\n    \n    if (vm.count(\"output\")) {\n        pOutput=fs::path(vm[\"output\"].as<std::string>());\n        if (fs::exists(pOutput)) {\n            msgM.msg(_msg::eMsg::MID, pOutput.string(), \" exists: deleting\");\n            fs::remove(pOutput);\n        }\n        sOutput=vm[\"output\"].as<std::string>();\n    }\n    \n    if (vm.count(\"separator\")) {\n        cSep=vm[\"separator\"].as<char>();\n        bDefSep=true;\n    }\n    \n    if (vm.count(\"exclude\")) {\n        sExclude=vm[\"exclude\"].as<std::string>();\n        bDefExclude=true;\n    }\n    \n    if (vm.count(\"filename\")) {\n        msgM.msg(_msg::eMsg::MID, \"compute S/N for 1 file\");\n        \n        std::string sFilename=vm[\"filename\"].as<std::string>();\n        \n        _csv<float> csv(sFilename, '\\t');\n        \n        if(csv.read()) {\n            csv.set_verbose(_csv<float>::eVerbose::QUIET);\n            msgM.msg(_msg::eMsg::MID,sFilename,\": S/N =\", der_snr(csv.select_column(1)));\n        }\n    }\n    \n    if (vm.count(\"directory\")) {\n        \n        fs::recursive_directory_iterator step0(pDirectory);\n        std::vector<std::string> list;\n        \n        if (bDefExclude) {\n            for(auto &file: boost::make_iterator_range(step0,{}) ) \n                // csv<> unable to parse non csv file\n                if (!fs::is_directory(file) && \n                    file.path().has_extension() && \n                    file.path().filename().string().find(std::string(\".tar\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".tar.gz\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".tgz\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".zip\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".txt\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".directory\"))==std::string::npos &&\n                    file.path().filename().string().find(sExclude)==std::string::npos )\n                    list.emplace_back(file.path().relative_path().string());       \n        }\n        else {\n            for(auto &file: boost::make_iterator_range(step0,{}) ) \n                // csv<> unable to parse non csv file\n                if (!fs::is_directory(file) && \n                    file.path().has_extension() && \n                    file.path().filename().string().find(std::string(\".tar\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".tar.gz\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".tgz\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".zip\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".txt\"))==std::string::npos &&\n                    file.path().filename().string().find(std::string(\".directory\"))==std::string::npos )\n                    list.emplace_back(file.path().relative_path().string());\n        }\n        int iMax_thread=std::thread::hardware_concurrency();\n        \n// Limit CPU usage -------------------------------------\n#if defined (__linux__)\n    msgM.msg(_msg::eMsg::MID, \"CPU utilization:\", static_cast<int>(CPU_utilization()), \"%\");\n    if (CPU_utilization()>50) {\n        iMax_thread=1;\n        msgM.msg(_msg::eMsg::MID, \"Reduce max thread\");\n    }\n#endif\n// -----------------------------------------------------\n        \n        if (iMax_thread>1) {\n            const std::size_t stSize_divided=list.size()/iMax_thread;\n            \n            std::vector<std::vector<std::string> > vvsList_divided;\n            \n            for(std::size_t i=0; i< iMax_thread-1; i++) \n                vvsList_divided.emplace_back(std::vector<std::string>(list.begin()+i*stSize_divided, list.begin() + stSize_divided*(i+1)));\n            \n            // 1 extra thread for extra files : rest of division\n            vvsList_divided.emplace_back(std::vector<std::string>(list.begin()+(iMax_thread-1)*stSize_divided, list.end()));\n            \n            msgM.msg(_msg::eMsg::MID, \"starting\", iMax_thread, \" async threads\");\n            \n            // let's don't decide the flag\n            std::launch lFlag=std::launch::async | std::launch::deferred;\n            \n            std::vector<std::future<void> > vfThread;\n            std::vector<std::vector<std::string> > vvsRes;\n            \n            if (bDefSep) {\n                int iCount=0;\n                for(auto t_list: vvsList_divided) {\n                    iCount++;\n                    std::string sNewoutput=\"part\"+std::to_string(iCount)+\"_\"+sOutput; \n                    vfThread.emplace_back(std::async(lFlag, compute_sep, t_list, sNewoutput, cSep));\n                }\n            }\n            else {\n                int iCount=0;\n                for(auto t_list: vvsList_divided) {\n                    iCount++;\n                    std::string sNewoutput=\"part\"+std::to_string(iCount)+\"_\"+sOutput; \n                    vfThread.emplace_back(std::async(lFlag, compute, t_list, sNewoutput));\n                }\n            }\n            std::for_each(vfThread.begin(), vfThread.end(), [](std::future<void> &th) { th.get(); });\n            merge(sOutput);            \n        }  \n        else {\n            msgM.msg(_msg::eMsg::MID, \"multi-threading disabled\");\n            compute(list, sOutput);\n        }\n    }\n    \n    msgM.msg(_msg::eMsg::MID, \"output:\", sOutput);   \n    \n#ifdef HAS_BOOST_TIMER\n    msgM.msg(_msg::eMsg::END, btTimer.format());\n#endif\n     \n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "cb109a4da7c84ac106ab5d586a0d3103b8c72df2", "size": 13005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/der_snr.cpp", "max_stars_repo_name": "a-lemonnier/spec_tools", "max_stars_repo_head_hexsha": "5ec9c38aaa31b1a677024bf9c53994142affdac3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T19:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T19:52:29.000Z", "max_issues_repo_path": "src/der_snr.cpp", "max_issues_repo_name": "a-lemonnier/spec_tools", "max_issues_repo_head_hexsha": "5ec9c38aaa31b1a677024bf9c53994142affdac3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/der_snr.cpp", "max_forks_repo_name": "a-lemonnier/spec_tools", "max_forks_repo_head_hexsha": "5ec9c38aaa31b1a677024bf9c53994142affdac3", "max_forks_repo_licenses": ["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.7706422018, "max_line_length": 139, "alphanum_fraction": 0.5507112649, "num_tokens": 3310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04401865017647433, "lm_q1q2_score": 0.02166545736730477}}
{"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#pragma once\n\n#include \"detail/random.hpp\"\n#include \"config.h\"\n#include <boost/align/aligned_allocator.hpp>\n#include <gsl/gsl-lite.hpp>\n#include <mkl_cblas.h>\n#include <mkl_vsl.h>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <type_traits>\n\nTCM_NAMESPACE_BEGIN\n\nnamespace detail {\n/// Checks that the last `vslRng*` operation succeeded. Throws an exception\n/// otherwise.\ninline auto check_vsl_status_after_generation(int const status) -> void\n{\n    if (status == VSL_STATUS_OK) { return; }\n    char const* const msg = [](auto code) {\n        switch (code) {\n        case VSL_ERROR_NULL_PTR: return \"`stream` is a NULL pointer\";\n        case VSL_RNG_ERROR_BAD_STREAM:\n            return \"`stream` is not a valid random stream\";\n        case VSL_RNG_ERROR_BAD_UPDATE:\n            return \"callback function for an abstract BRNG returns an \"\n                   \"invalid number of updated entries in a buffer, \"\n                   \"that is, < 0 or > nmax\";\n        case VSL_RNG_ERROR_NO_NUMBERS:\n            return \"callback function for an abstract BRNG returns 0 \"\n                   \"as the number of updated entries in a buffer.\";\n        case VSL_RNG_ERROR_QRNG_PERIOD_ELAPSED:\n            return \"period of the generator has been exceeded\";\n        case VSL_RNG_ERROR_NONDETERM_NRETRIES_EXCEEDED:\n            return \"number of retries to generate a random number by \"\n                   \"using non-deterministic random number generator \"\n                   \"exceeds threshold\";\n        case VSL_RNG_ERROR_ARS5_NOT_SUPPORTED:\n            return \"ARS-5 random number generator is not supported on \"\n                   \"the CPU running the application\";\n        default: return \"unknown error code: a bug in Intel MKL?\";\n        } // end switch\n    }(status);\n    throw std::runtime_error{msg};\n}\n\n/// Uses Intel MKL to generate numbers distributed according to\n/// `Gamma(shape, scale)`.\n///\n/// https://en.wikipedia.org/wiki/Gamma_distribution.\ntemplate <class RealT> class buffered_gamma_distribution_t { // {{{\n    static_assert(std::is_same_v<RealT, float> || std::is_same_v<RealT, double>,\n                  \"tcm::detail::buffered_gamma_distribution_t currently only \"\n                  \"supports `float`s and `double`s.\");\n\n  public:\n    /// Generation method.\n    ///\n    /// Possible values are:\n    ///\n    ///   * `VSL_RNG_METHOD_GAMMA_GNORM`\n    ///   * `VSL_RNG_METHOD_GAMMA_GNORM_ACCURATE`\n    ///\n    /// See https://software.intel.com/en-us/mkl-developer-reference-c-vrnggamma\n    /// for more info.\n    static constexpr MKL_INT method = VSL_RNG_METHOD_GAMMA_GNORM_ACCURATE;\n\n    static constexpr size_t default_buffer_size = 1024;\n\n    /// Buffer type.\n    ///\n    /// Performance of Intel MKL's random number generation increases\n    /// considerably when multiple variates a generated at once (see\n    /// https://software.intel.com/en-us/mkl-vsperfdata-uniform).\n    using buffer_type =\n        std::vector<RealT, boost::alignment::aligned_allocator<RealT, 64u>>;\n\n    using stream_type = VSLStreamStatePtr;\n\n    /// Distribution parameters.\n    class param_type {\n        RealT _shape; ///< Shape parameter\n        RealT _scale; ///< Scale parameter\n\n      public:\n        constexpr explicit param_type(RealT const shape,\n                                      RealT const scale) TCM_NOEXCEPT\n            : _shape{shape}\n            , _scale{scale}\n        {\n            TCM_ASSERT(shape > 0, \"`shape` must be positive\");\n            TCM_ASSERT(scale > 0, \"`scale` must be positive\");\n        }\n\n        constexpr param_type(param_type const&) noexcept = default;\n        constexpr param_type(param_type&&) noexcept      = default;\n        constexpr param_type& operator=(param_type const&) noexcept = default;\n        constexpr param_type& operator=(param_type&&) noexcept = default;\n\n        constexpr auto shape() const noexcept { return _shape; }\n        constexpr auto scale() const noexcept { return _scale; }\n    };\n\n    static_assert(std::is_trivially_copyable_v<param_type>);\n\n  private:\n    stream_type _stream; ///< Intel MKL random number generator stream\n                         ///<\n    buffer_type _buffer; ///< Output buffer where the generated\n                         ///< numbers are written to\n    size_t _i; ///< Current position in `_buffer`. `_i == _buffer.size()`\n               ///< indicates that the buffer needs to be refilled.\n    param_type _params; ///< Shape and scale parameters\n                        ///<\n\n  public:\n    /// Constructs a new Gamma distribution and allocates memory for internal\n    /// buffers.\n    buffered_gamma_distribution_t(\n        stream_type const stream, RealT const alpha, RealT const beta,\n        size_t const buffer_size = default_buffer_size)\n        : _stream{stream}\n        , _buffer(buffer_size)\n        , _i{buffer_size}\n        , _params{alpha, beta}\n    {\n        TCM_ASSERT(stream != nullptr, \"`stream` should not be null\");\n        TCM_ASSERT(buffer_size > 0, \"buffer should not be empty\");\n    }\n\n    /// Deleted copy constructor to avoid unintentionally copying potentially\n    /// big buffers.\n    buffered_gamma_distribution_t(buffered_gamma_distribution_t const&) =\n        delete;\n\n    /// Move constructor.\n    buffered_gamma_distribution_t(buffered_gamma_distribution_t&&) noexcept =\n        default;\n\n    /// Deleted copy assignment operator to avoid unintentionally copying\n    /// potentially big buffers.\n    buffered_gamma_distribution_t&\n    operator=(buffered_gamma_distribution_t const&) = delete;\n\n    /// Move assignment operator.\n    buffered_gamma_distribution_t&\n    operator=(buffered_gamma_distribution_t&&) noexcept = default;\n\n    constexpr auto param() const noexcept -> param_type { return _params; }\n\n    constexpr auto param(param_type const& params) noexcept -> void\n    {\n        _params = params;\n        _i      = _buffer.size();\n    }\n\n#if 0 // This is probably too low-level and should not be exposed.\n    constexpr auto buffer() noexcept -> gsl::span<RealT> { return {_buffer}; }\n\n    constexpr auto buffer() const noexcept -> gsl::span<RealT const>\n    {\n        return {_buffer};\n    }\n#endif\n\n    constexpr auto stream() const noexcept -> VSLStreamStatePtr\n    {\n        return _stream;\n    }\n\n    auto resize(size_t const buffer_size) -> void\n    {\n        TCM_ASSERT(buffer_size > 0, \"buffer should not be empty\");\n        // TODO(twesterhout): We could implement an optimisation here which\n        // would copy the unused part of the buffer. This could potentially\n        // avoid generating some random numbers.\n        _buffer.resize(buffer_size);\n        _i = buffer_size;\n    }\n\n  private:\n    static auto vsl_generate(VSLStreamStatePtr const stream, MKL_INT const n,\n                             float* const r, float const alpha, float const a,\n                             float const beta) -> int\n    {\n        return vsRngGamma(method, stream, n, r, alpha, a, beta);\n    }\n\n    static auto vsl_generate(VSLStreamStatePtr const stream, MKL_INT const n,\n                             double* const r, double const alpha,\n                             double const a, double const beta) -> int\n    {\n        return vdRngGamma(method, stream, n, r, alpha, a, beta);\n    }\n\n    static auto fill(gsl::span<RealT> out, VSLStreamStatePtr const stream,\n                     param_type const& params) -> void\n    {\n        // NOTE: Intel MKL calls the scale parameter `beta`. Do not confuse\n        // `beta` with the _inverse_ scale parameter.\n        auto const status =\n            vsl_generate(stream, static_cast<MKL_INT>(out.size()), out.data(),\n                         /*alpha = */ params.shape(),\n                         /*displacement = */ RealT{0},\n                         /*beta = */ params.scale());\n        check_vsl_status_after_generation(status);\n    }\n\n  public:\n    auto operator()(gsl::span<RealT> out, param_type const& params) const\n        -> void\n    {\n        fill(out, _stream, params);\n    }\n\n    auto operator()(gsl::span<RealT> out) const -> void\n    {\n        (*this)(out, _params);\n    }\n\n    auto operator()() -> RealT\n    {\n        TCM_ASSERT(_i <= _buffer.size(), \"Pre-condition violated\");\n        if (_i == _buffer.size()) {\n            fill(_buffer, _stream, _params);\n            _i = 0;\n        }\n        return _buffer[_i++];\n    }\n};\n// }}}\n\n/// Uses Intel MKL to generate numbers distributed according to N(mu, sigma^2).\n///\n/// See https://en.wikipedia.org/wiki/Normal_distribution.\ntemplate <class RealT> class buffered_gauss_distribution_t { // {{{\n    static_assert(std::is_same_v<RealT, float> || std::is_same_v<RealT, double>,\n                  \"tcm::detail::buffered_gauss_distribution_t currently only \"\n                  \"supports `float`s and `double`s.\");\n\n  public:\n    /// Generation method.\n    ///\n    /// Possible values are:\n    ///\n    ///   * `VSL_RNG_METHOD_GAUSSIAN_BOXMULLER`\n    ///   * `VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2`\n    ///   * `VSL_RNG_METHOD_GAUSSIAN_ICDF`\n    ///\n    /// See https://software.intel.com/en-us/mkl-developer-reference-c-vrnggaussian\n    /// for more info.\n    static constexpr MKL_INT method = VSL_RNG_METHOD_GAUSSIAN_BOXMULLER;\n\n    static constexpr size_t default_buffer_size = 1024;\n\n    /// Buffer type.\n    ///\n    /// Performance of Intel MKL's random number generation increases\n    /// considerably when multiple variates a generated at once (see\n    /// https://software.intel.com/en-us/mkl-vsperfdata-uniform).\n    using buffer_type =\n        std::vector<RealT, boost::alignment::aligned_allocator<RealT, 64u>>;\n\n    using stream_type = VSLStreamStatePtr;\n\n    class param_type {\n        RealT _mu;    ///< Mean\n        RealT _sigma; ///< Standard deviation\n\n      public:\n        constexpr explicit param_type(RealT const mu,\n                                      RealT const sigma) TCM_NOEXCEPT\n            : _mu{mu}\n            , _sigma{sigma}\n        {\n            TCM_ASSERT(sigma > 0, \"`sigma` must be positive\");\n        }\n\n        constexpr param_type(param_type const&) noexcept = default;\n        constexpr param_type(param_type&&) noexcept      = default;\n        constexpr param_type& operator=(param_type const&) noexcept = default;\n        constexpr param_type& operator=(param_type&&) noexcept = default;\n\n        constexpr auto mu() const noexcept { return _mu; }\n        constexpr auto sigma() const noexcept { return _sigma; }\n    };\n\n  private:\n    stream_type _stream; ///< Intel MKL random number generator stream.\n                         ///<\n    buffer_type _buffer; ///< Output buffer where the generated numbers\n                         ///< are written.\n    size_t _i; ///< Current position in `_buffer`. `_i == _buffer.size()`\n               ///< means that the buffer needs to be refilled.\n    param_type _params; ///< Distribution parameters.\n                        ///<\n\n  public:\n    buffered_gauss_distribution_t(\n        stream_type const stream, RealT const mu, RealT const sigma,\n        size_t const buffer_size = default_buffer_size) TCM_NOEXCEPT\n        : _stream{stream}\n        , _buffer(buffer_size)\n        , _i{buffer_size}\n        , _params{mu, sigma}\n    {\n        TCM_ASSERT(stream != nullptr, \"`stream` should not be null\");\n        TCM_ASSERT(buffer_size > 0, \"buffer should not be empty\");\n    }\n\n    buffered_gauss_distribution_t(buffered_gauss_distribution_t const&) =\n        delete;\n\n    buffered_gauss_distribution_t(buffered_gauss_distribution_t&&) noexcept =\n        default;\n\n    buffered_gauss_distribution_t&\n    operator=(buffered_gauss_distribution_t const&) = delete;\n\n    buffered_gauss_distribution_t&\n    operator=(buffered_gauss_distribution_t&&) noexcept = default;\n\n    constexpr auto param() const noexcept -> param_type { return _params; }\n    constexpr auto param(param_type const params) noexcept -> void\n    {\n        _params = params;\n        _i      = _buffer.size();\n    }\n\n#if 0\n    constexpr auto buffer() noexcept -> gsl::span<RealT> { return {_buffer}; }\n    constexpr auto buffer() const noexcept -> gsl::span<RealT const>\n    {\n        return {_buffer};\n    }\n#endif\n\n    auto resize(size_t const buffer_size) -> void\n    {\n        TCM_ASSERT(buffer_size > 0, \"buffer should not be empty\");\n        // TODO(twesterhout): We could implement an optimisation here which\n        // would copy the unused part of the buffer. This could potentially\n        // avoid generating some random numbers.\n        _buffer.resize(buffer_size);\n        _i = buffer_size;\n    }\n\n    constexpr auto stream() const noexcept -> VSLStreamStatePtr\n    {\n        return _stream;\n    }\n\n  private:\n    static auto vsl_generate(VSLStreamStatePtr const stream, MKL_INT const n,\n                             float* const r, float const a, float const sigma)\n        -> int\n    {\n        return vsRngGaussian(method, stream, n, r, a, sigma);\n    }\n\n    static auto vsl_generate(VSLStreamStatePtr const stream, MKL_INT const n,\n                             double* const r, double const a,\n                             double const sigma) -> int\n    {\n        return vdRngGaussian(method, stream, n, r, a, sigma);\n    }\n\n    static auto fill(gsl::span<RealT> out, VSLStreamStatePtr stream,\n                     param_type const& params) -> void\n    {\n        auto const status =\n            vsl_generate(stream, static_cast<MKL_INT>(out.size()), out.data(),\n                         /*a = */ params.mu(),\n                         /*sigma = */ params.sigma());\n        check_vsl_status_after_generation(status);\n    }\n\n  public:\n    auto operator()(gsl::span<RealT> out, param_type const& params) const\n        -> void\n    {\n        fill(out, _stream, params);\n    }\n\n    auto operator()(gsl::span<RealT> out) const -> void\n    {\n        (*this)(out, _params);\n    }\n\n    auto operator()() -> RealT\n    {\n        TCM_ASSERT(_i <= _buffer.size(), \"Pre-condition violated\");\n        if (_i == _buffer.size()) {\n            fill(_buffer, _stream, _params);\n            _i = 0;\n        }\n        return _buffer[_i++];\n    }\n};\n// }}}\n\ntemplate <class RealT> class buffered_tsallis_distribution_t { // {{{\n    static_assert(std::is_same_v<RealT, float> || std::is_same_v<RealT, double>,\n                  \"Currently, only `float`s and `double`s are supported.\");\n\n  private:\n    /// Calculation of \\f$p\\f$ given \\f$q_V\\f$ (see `Tsallis_RNG` function in\n    /// [@Schanze2006] for an explanation).\n    ///\n    /// [@Schanze2006]: Thomas Schanze, \"An exact D-dimensional Tsallis random\n    ///                 number generator for generalized simulated annealing\", 2006.\n    static constexpr auto get_p(RealT const q_V) noexcept -> RealT\n    {\n        using R = RealT;\n        return (R{3} - q_V) / (R{2} * (q_V - R{1}));\n    }\n\n    /// Calculation of \\f$s\\f$ given \\f$q_V\\f$ and \\f$t_V\\f$ (see `Tsallis_RNG`\n    /// function in [@Schanze2006] for an explanation).\n    ///\n    /// [@Schanze2006]: Thomas Schanze, \"An exact D-dimensional Tsallis random\n    ///                 number generator for generalized simulated annealing\", 2006.\n    static /*constexpr*/ auto get_s(RealT const q_V, RealT const t_V) noexcept\n        -> RealT\n    {\n        using R = RealT;\n        return std::sqrt(R{2} * (q_V - R{1}))\n               / std::pow(t_V, R{1} / (R{3} - q_V));\n    }\n\n  public:\n    static constexpr size_t default_buffer_size = 1024;\n\n    /// Buffer type.\n    ///\n    /// Performance of Intel MKL's random number generation increases\n    /// considerably when multiple variates a generated at once (see\n    /// https://software.intel.com/en-us/mkl-vsperfdata-uniform).\n    using buffer_type =\n        std::vector<RealT, boost::alignment::aligned_allocator<RealT, 64u>>;\n\n    class param_type {\n        RealT _q_V; ///< Visiting distribution shape parameter\n        RealT _t_V; ///< Visiting temperature\n        RealT _s;   ///< Variable `s` from `Tsallis_RNG` in [@Schanze2006].\n\n      public:\n        explicit param_type(RealT const q_V, RealT const t_V) TCM_NOEXCEPT\n            : _q_V{q_V}\n            , _t_V{t_V}\n        {\n            TCM_ASSERT(1 < q_V && q_V < 3, \"`q_V` must be in (1, 3)\");\n            TCM_ASSERT(t_V > 0, \"`t_V` must be positive\");\n            _s = get_s(q_V, t_V);\n        }\n\n        constexpr param_type(param_type const&) noexcept = default;\n        constexpr param_type(param_type&&) noexcept      = default;\n        constexpr param_type& operator=(param_type const&) noexcept = default;\n        constexpr param_type& operator=(param_type&&) noexcept = default;\n\n        constexpr auto q_V() const noexcept { return _q_V; }\n        constexpr auto t_V() const noexcept { return _t_V; }\n        constexpr auto s() const noexcept { return _s; }\n    };\n\n  private:\n    buffered_gamma_distribution_t<RealT> _gamma_dist;\n    buffered_gauss_distribution_t<RealT> _gauss_dist;\n    param_type                           _params;\n\n  public:\n    buffered_tsallis_distribution_t(\n        VSLStreamStatePtr const stream, RealT const q_V, RealT const t_V,\n        size_t const buffer_size = default_buffer_size)\n        : _gamma_dist{stream, get_p(q_V), RealT{1}, buffer_size}\n        , _gauss_dist{stream, RealT{0}, RealT{1}, buffer_size}\n        , _params{q_V, t_V}\n    {}\n\n    constexpr auto param() const noexcept -> param_type { return _params; }\n    constexpr auto param(param_type const params) noexcept -> void\n    {\n        _gamma_dist.param(\n            typename buffered_gamma_distribution_t<RealT>::param_type{\n                get_p(params.q_V()), RealT{1}});\n        // _gauss_dist doesn't depend on params\n        _params = params;\n    }\n\n    constexpr auto stream() const noexcept -> VSLStreamStatePtr\n    {\n        return _gamma_dist.stream();\n    }\n\n  private:\n    auto fill(gsl::span<RealT> out) -> void\n    {\n        using R      = RealT;\n        using Params = typename buffered_gauss_distribution_t<R>::param_type;\n\n        // Updates internal buffer and is the reason `fill` is not const.\n        auto const u = _gamma_dist();\n        auto const y = _params.s() * std::sqrt(u);\n\n        // TODO(twesterhout): Profile what is more efficient: using different\n        // sigma or calling cblas_?scal.\n        _gauss_dist(out, Params{R{0}, R{1} / y});\n\n        // NOLINTNEXTLINE(readability-braces-around-statements)\n        // if constexpr (std::is_same_v<R, float>) {\n        //     cblas_sscal(static_cast<MKL_INT>(out.size()), R{1} / y, out.data(),\n        //                 1);\n        // }\n        // else {\n        //     cblas_dscal(static_cast<MKL_INT>(out.size()), R{1} / y, out.data(),\n        //                 1);\n        // }\n    }\n\n  public:\n    // Generates an N-dimensional sample\n    auto operator()(gsl::span<RealT> out) { fill(out); }\n\n    // Generates a 1-dimensional sample\n    auto operator()() -> RealT\n    {\n        auto const u = _gamma_dist();\n        auto const y = _params.s() * std::sqrt(u);\n        auto const x = _gauss_dist();\n        return x / y;\n    }\n};\n// }}}\n\ntemplate class buffered_gamma_distribution_t<float>;\ntemplate class buffered_gamma_distribution_t<double>;\n\ntemplate class buffered_gauss_distribution_t<float>;\ntemplate class buffered_gauss_distribution_t<double>;\n\ntemplate class buffered_tsallis_distribution_t<float>;\ntemplate class buffered_tsallis_distribution_t<double>;\n\n} // namespace detail\n\ntemplate <class EnergyFn, class WrapFn> class sa_chain_t;\n\nstruct sa_pars_t {\n    float    q_V;\n    float    q_A;\n    float    t_0;\n    unsigned dimension;\n    unsigned num_iterations;\n};\n\nclass sa_buffers_t { // {{{\n  public:\n    template <class EnergyFn, class WrapFn> friend class sa_chain_t;\n\n    using buffer_type =\n        std::vector<float, boost::alignment::aligned_allocator<float, 64u>>;\n\n    struct state_type {\n        float       value;\n        buffer_type buffer;\n\n      private:\n        /// Rounds x up to the closest multiple of 64.\n        static constexpr auto round_up_to_64(size_t const x) noexcept -> size_t\n        {\n            constexpr size_t N = 64;\n            return (x + N - 1) & N;\n        }\n\n      public:\n        /// Allocates a buffer of the specified size.\n        explicit state_type(size_t const size)\n            : value{std::numeric_limits<float>::infinity()}, buffer{}\n        {\n            resize(size);\n        }\n\n        state_type(state_type const&)     = default;\n        state_type(state_type&&) noexcept = default;\n        state_type& operator=(state_type const&) = default;\n        state_type& operator=(state_type&&) noexcept = default;\n\n        /// Ensures buffer is big enough to hold `size` elements.\n        ///\n        /// We use a small trick here. We round `size` up to a multiple of 64 so\n        /// that we can safely use SIMD instructions without worrying about\n        /// writing past the end of the buffer.\n        auto resize(size_t const size) -> void\n        {\n            buffer.reserve(round_up_to_64(size));\n            buffer.resize(size);\n        }\n    };\n\n  private:\n    using distribution_type = detail::buffered_tsallis_distribution_t<float>;\n\n    state_type        _current;\n    state_type        _proposed;\n    state_type        _best;\n    distribution_type _tsallis;\n\n  public:\n    sa_buffers_t(sa_pars_t const&  params,\n                 VSLStreamStatePtr stream = random_stream());\n\n    sa_buffers_t(sa_buffers_t const&)     = delete;\n    sa_buffers_t(sa_buffers_t&&) noexcept = default;\n    sa_buffers_t& operator=(sa_buffers_t const&) = delete;\n    sa_buffers_t& operator=(sa_buffers_t&&) = default;\n\n    auto reset(sa_pars_t const& params) -> void;\n    auto reset(distribution_type::param_type const& params) -> void;\n\n    template <class Initialise> auto guess(Initialise&& init) -> void;\n};\n\ninline sa_buffers_t::sa_buffers_t(sa_pars_t const&  params,\n                                  VSLStreamStatePtr stream)\n    : _current{params.dimension}\n    , _proposed{params.dimension}\n    , _best{params.dimension}\n    , _tsallis{stream, params.q_V, params.t_0}\n{}\n\ninline auto sa_buffers_t::reset(sa_pars_t const& params) -> void\n{\n    _current.resize(params.dimension);\n    _proposed.resize(params.dimension);\n    _best.resize(params.dimension);\n    _tsallis.param(distribution_type::param_type{params.q_V, params.t_0});\n}\n\ninline auto sa_buffers_t::reset(distribution_type::param_type const& params)\n    -> void\n{\n    _tsallis.param(params);\n}\n\ntemplate <class Initialise> auto sa_buffers_t::guess(Initialise&& init) -> void\n{\n    std::forward<Initialise>(init)(gsl::span<float>{_current.buffer});\n}\n// }}}\n\ntemplate <class EnergyFn, class WrapFn> class sa_chain_t { // {{{\n  public:\n    using energy_fn_type    = EnergyFn;\n    using wrap_fn_type      = WrapFn;\n    using tsallis_dist_type = detail::buffered_tsallis_distribution_t<float>;\n\n  private:\n    energy_fn_type _energy_fn; ///< Energy function `f`.\n                               ///<\n    wrap_fn_type _wrap_fn;     ///< Wrapping function `wrap` which ensures that\n                               ///< `wrap(x + dx)` is in the domain of `f`.\n    sa_buffers_t&    _buffers;\n    sa_pars_t const& _params;\n    size_t           _i; ///< Current iteration.\n                         ///<\n\n  public:\n    sa_chain_t(sa_buffers_t& buffers, sa_pars_t const& params,\n               energy_fn_type energy_fn, wrap_fn_type wrap_fn);\n\n    sa_chain_t(sa_chain_t const&) = delete;\n    sa_chain_t(sa_chain_t&&)      = delete;\n    sa_chain_t& operator=(sa_chain_t const&) = delete;\n    sa_chain_t& operator=(sa_chain_t&&) = delete;\n\n    inline auto    operator()() -> void;\n    constexpr auto restart() noexcept -> void;\n    constexpr auto current() const noexcept -> sa_buffers_t::state_type const&;\n    constexpr auto best() const noexcept -> sa_buffers_t::state_type const&;\n\n  private:\n    constexpr auto t_0() const noexcept { return _params.t_0; }\n    constexpr auto q_V() const noexcept { return _params.q_V; }\n    constexpr auto q_A() const noexcept { return _params.q_A; }\n\n    /// Returns the dimension of the parameter space.\n    auto dim() const noexcept { return _buffers._current.buffer.size(); }\n\n    /// Calculates the visiting temperature `t_V` for the given iteration.\n    inline auto temperature(size_t i) const noexcept -> float;\n\n    /// Sets the best state equal to current.\n    inline auto update_best() noexcept -> void;\n\n    /// Accepts the move, i.e. `proposed` becomes `current`\n    inline auto accept_full() noexcept -> void;\n    inline auto accept_one(size_t i, float const x) noexcept -> void;\n\n    /// Rejects the move.\n    inline auto reject_full() noexcept -> void;\n    inline auto reject_one(size_t i, float const x) noexcept -> void;\n\n    /// Returns a uniform random number\n    ///\n    /// TODO(twesterhout): This function is terribly inefficient.\n    inline auto uniform() -> float;\n\n    template <class Accept, class Reject>\n    inline auto accept_or_reject(float const dE, float const t_A,\n                                 Accept&& accept, Reject&& reject) -> void;\n\n    inline auto generate_full() -> void;\n    inline auto generate_one(size_t const i) -> std::tuple<float, float>;\n};\n// }}}\n\n// {{{ sa_chain_t IMPLEMENTATION\ntemplate <class E, class W>\ninline sa_chain_t<E, W>::sa_chain_t(sa_buffers_t&    buffers,\n                                    sa_pars_t const& params,\n                                    energy_fn_type   energy_fn,\n                                    wrap_fn_type     wrap_fn)\n    : _energy_fn{std::move(energy_fn)}\n    , _wrap_fn{std::move(wrap_fn)}\n    , _buffers{buffers}\n    , _params{params}\n    , _i{0}\n{\n    _buffers._current.value = _energy_fn(_buffers._current.buffer);\n    update_best();\n}\n\ntemplate <class E, class W>\ninline auto sa_chain_t<E, W>::temperature(std::size_t const i) const noexcept\n    -> float\n{\n    auto const num = t_0() * (std::pow(2.0f, q_V() - 1.0f) - 1.0f);\n    auto const den = std::pow(static_cast<float>(2 + i), q_V() - 1.0f) - 1.0f;\n    return num / den;\n}\n\ntemplate <class E, class W>\ninline auto sa_chain_t<E, W>::update_best() noexcept -> void\n{\n    using std::begin, std::end;\n    std::copy(begin(_buffers._current.buffer), end(_buffers._current.buffer),\n              begin(_buffers._best.buffer));\n    _buffers._best.value = _buffers._current.value;\n}\n\ntemplate <class E, class W>\nTCM_NOINLINE auto sa_chain_t<E, W>::uniform() -> float\n{\n    float      r;\n    auto const status =\n        vsRngUniform(VSL_RNG_METHOD_UNIFORM_STD, _buffers._tsallis.stream(), 1,\n                     &r, 0.0f, 1.0f);\n    detail::check_vsl_status_after_generation(status);\n    return r;\n}\n\ntemplate <class E, class W>\ntemplate <class Accept, class Reject>\ninline auto sa_chain_t<E, W>::accept_or_reject(float const dE, float const t_A,\n                                               Accept&& accept, Reject&& reject)\n    -> void\n{\n#if 0\n    auto const accept = [this]() {\n        using std::swap;\n        swap(_buffers._current, _buffers._proposed);\n        if (_buffers._current.value < _buffers._best.value) { update_best(); }\n    };\n    auto const reject = []() {};\n#endif\n\n    // Always accept moves that reduce the energy\n    if (dE < 0.0f) {\n        std::forward<Accept>(accept)();\n        return;\n    }\n\n    // Eq. (5)\n    //\n    // pqv_temp = (q_A - 1.0) * (e - self.energy_state.current_energy) / ( self.temperature_step + 1.)\n    //\n    // auto const factor = 1.0f + (q_A() - 1.0f) * dE / t_A;\n    auto const factor = 1.0f + (q_A() - 1.0f) * dE / t_A;\n    auto const P_qA =\n        factor <= 0.0f ? 0.0f : std::pow(factor, 1.0f / (1.0f - q_A()));\n    if (uniform() <= P_qA) {\n        // std::fprintf(stderr, \"Ping!\\n\");\n        std::forward<Accept>(accept)();\n    }\n    else {\n        // std::fprintf(stderr, \"T_A = %f, factor = %f, r = %f, P_qA = %f\\n\",\n        //              static_cast<double>(t_A), static_cast<double>(factor),\n        //              static_cast<double>(r), static_cast<double>(P_qA));\n        std::forward<Reject>(reject)();\n    }\n}\n\ntemplate <class E, class W>\ninline auto sa_chain_t<E, W>::generate_full() -> void\n{\n    using std::begin, std::end;\n    _buffers._tsallis(_buffers._proposed.buffer);\n    std::transform(\n        begin(_buffers._current.buffer), end(_buffers._current.buffer),\n        begin(_buffers._proposed.buffer), begin(_buffers._proposed.buffer),\n        [this](auto const x, auto const dx) -> float {\n            return _wrap_fn(x + dx);\n        });\n    _buffers._proposed.value = _energy_fn(_buffers._proposed.buffer);\n}\n\ntemplate <class E, class W>\ninline auto sa_chain_t<E, W>::generate_one(std::size_t const i)\n    -> std::tuple<float, float>\n{\n    auto const x = _wrap_fn(_buffers._current.buffer[i] + _buffers._tsallis());\n    auto       temp_buffer = _buffers._current.buffer;\n    temp_buffer[i]         = x;\n    auto const value       = _energy_fn(temp_buffer);\n    // auto const value =\n    //     _energy_fn(i, x, _buffers._current.value, _buffers._current.buffer);\n    return std::make_tuple(x, value);\n}\n\ntemplate <class E, class W>\nconstexpr auto sa_chain_t<E, W>::current() const noexcept\n    -> sa_buffers_t::state_type const&\n{\n    return _buffers._current;\n}\n\ntemplate <class E, class W>\nconstexpr auto sa_chain_t<E, W>::best() const noexcept\n    -> sa_buffers_t::state_type const&\n{\n    return _buffers._best;\n}\n\ntemplate <class E, class W>\nconstexpr auto sa_chain_t<E, W>::restart() noexcept -> void\n{\n    _i = 0;\n}\n\ntemplate <class E, class W>\nTCM_NOINLINE auto sa_chain_t<E, W>::operator()() -> void\n{\n    // (iv) Calculate new temperature...\n    auto const t_V = temperature(_i);\n    auto const t_A = t_V / static_cast<float>(_i + 1);\n    _buffers._tsallis.param(typename tsallis_dist_type::param_type{q_V(), t_V});\n\n    // Markov chain at constant temperature\n    for (auto j = size_t{0}; j < dim(); ++j) {\n        auto const accept = [this]() {\n            using std::swap;\n            swap(_buffers._current, _buffers._proposed);\n            if (_buffers._current.value < _buffers._best.value) {\n                update_best();\n            }\n            std::cerr << _buffers._current.value << '\\n';\n        };\n        auto const reject = []() {};\n        generate_full();\n        accept_or_reject(_buffers._proposed.value - _buffers._current.value,\n                         t_A, accept, reject);\n    }\n    for (auto j = size_t{0}; j < dim(); ++j) {\n        auto const [x, value] = generate_one(j);\n        auto const accept     = [this, j, x = x, value = value]() {\n            _buffers._current.buffer[j] = x;\n            _buffers._current.value     = value;\n            if (_buffers._current.value < _buffers._best.value) {\n                update_best();\n            }\n            std::cerr << _buffers._current.value << '\\n';\n        };\n        auto const reject = []() {};\n        accept_or_reject(value - _buffers._current.value, t_A, accept, reject);\n    }\n\n    // NOTE: Don't forget this!\n    ++_i;\n\n#if 0\n        for (auto j = std::size_t{0}; j < 2 * dim(); ++j) {\n            // (ii) Then randomly generate x...\n            if (j < dim()) { generate_full(); }\n            else {\n                generate_one(j - dim());\n            }\n            // (iii)\n            auto const proposed_energy = std::get<0>(_proposed);\n            auto const current_energy  = std::get<0>(_current);\n            accept_or_reject(proposed_energy - current_energy, t_A);\n            auto const proposed_energy = std::get<0>(_proposed);\n            auto const current_energy  = std::get<0>(_current);\n            if (proposed_energy < current_energy) { accept(); }\n            else {\n                real_type r;\n                int       status = vsRngUniform(\n                    VSL_RNG_METHOD_UNIFORM_STD_ACCURATE, _stream, 1, &r,\n                    /*a = */ real_type{0}, /*b = */ real_type{1});\n                if (status != VSL_STATUS_OK)\n                    throw std::runtime_error{\"vsRngUniform failed.\"};\n\n                // Eq. (5)\n                auto const factor = real_type{1}\n                                    + (_params.q_A - 1)\n                                          * (proposed_energy - current_energy)\n                                          / t_A;\n                auto const P_qA =\n                    factor <= 0\n                        ? real_type{0}\n                        : std::pow(factor,\n                                   real_type{1} / (real_type{1} - _params.q_A));\n                if (r <= P_qA) {\n                    std::fprintf(stderr, \"Ping!\\n\");\n                    accept();\n                }\n                else {\n                    std::fprintf(\n                        stderr, \"T_V = %f, factor = %f, r = %f, P_qA = %f\\n\",\n                        static_cast<double>(t_V),\n                        static_cast<double>(factor), static_cast<double>(r),\n                        static_cast<double>(P_qA));\n                    reject();\n                }\n            }\n        }\n#endif\n}\n// }}}\n\ninline auto simulated_annealing_buffers(sa_pars_t const& params)\n    -> sa_buffers_t&\n{\n    constexpr auto default_params = sa_pars_t{/*q_V=*/2.62f,\n                                              /*q_A=*/-5.0f,\n                                              /*t_0=*/5230.0f,\n                                              /*dimension=*/1000000,\n                                              /*num_iterations=*/1000};\n\n    thread_local sa_buffers_t buffers{default_params, random_stream()};\n    buffers.reset(params);\n    return buffers;\n}\n\ntemplate <class EnergyFn, class WrapFn, class Initialise, class Finalise>\ninline auto minimise_using_simulated_annealing(EnergyFn energy, WrapFn wrap,\n                                               sa_pars_t const& params,\n                                               Initialise&&     input,\n                                               Finalise&&       output) -> void\n{\n    auto& buffers = simulated_annealing_buffers(params);\n    buffers.guess(std::forward<Initialise>(input));\n\n    sa_chain_t chain{buffers, params, std::move(energy), std::move(wrap)};\n    for (auto i = 0u; i < params.num_iterations; ++i) {\n        chain();\n    }\n    auto const& best = chain.best();\n    std::forward<Finalise>(output)(gsl::span<float const>{best.buffer});\n}\n\nTCM_NAMESPACE_END\n", "meta": {"hexsha": "afcd80ad5c82c8a75eb1b880816f33444f21bd82", "size": 35694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/detail/simulated_annealing.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/simulated_annealing.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/simulated_annealing.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": 35.5872382851, "max_line_length": 102, "alphanum_fraction": 0.6069087242, "num_tokens": 8468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111088366237647, "lm_q2_score": 0.05261895260488792, "lm_q1q2_score": 0.02163222410278418}}
{"text": "/****************************************************************************\n * Copyright (c) 2021 by the Picasso authors                                *\n * All rights reserved.                                                     *\n *                                                                          *\n * This file is part of the Picasso library. Picasso is distributed under a *\n * BSD 3-clause license. For the licensing terms see the LICENSE file in    *\n * the top-level directory.                                                 *\n *                                                                          *\n * SPDX-License-Identifier: BSD-3-Clause                                    *\n ****************************************************************************/\n\n#ifndef PICASSO_PARTICLELEVELSET_HPP\n#define PICASSO_PARTICLELEVELSET_HPP\n\n#include <Picasso_FieldManager.hpp>\n#include <Picasso_LevelSet.hpp>\n#include <Picasso_Types.hpp>\n\n#include <Cajita.hpp>\n\n#include <ArborX.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <cfloat>\n#include <cmath>\n\n//---------------------------------------------------------------------------//\n// ArborX Data\n//---------------------------------------------------------------------------//\n// Search primitives. We build the tree from particles of the color we want\n// the level set for.\nnamespace Picasso\n{\ntemplate <class CoordinateSlice, class ViewType>\nstruct ParticleLevelSetPrimitiveData\n{\n    using memory_space = typename CoordinateSlice::memory_space;\n    using size_type = typename CoordinateSlice::size_type;\n    CoordinateSlice x;\n    ViewType c;\n    int num_color;\n};\n\n// Predicate storage - store the the 3d index of the mesh entity we are going to\n// search the tree with along with its coordinates.\ntemplate <class IndexType>\nstruct ParticleLevelSetPredicateStorage\n{\n    using size_type = IndexType;\n    size_type i;\n    size_type j;\n    size_type k;\n    float x;\n    float y;\n    float z;\n};\n\n// Search predicates. We search the tree with the mesh entities on which we\n// want to build the level set.\ntemplate <class LocalMesh, class EntityType>\nstruct ParticleLevelSetPredicateData\n{\n    using memory_space = typename LocalMesh::memory_space;\n    using size_type = int;\n    using entity_type = EntityType;\n    LocalMesh local_mesh;\n    size_type size;\n    size_type i_size;\n    size_type ij_size;\n\n    template <class LocalGrid>\n    ParticleLevelSetPredicateData( const LocalMesh& lm,\n                                   const LocalGrid& local_grid )\n        : local_mesh( lm )\n    {\n        auto ghost_entities = local_grid.indexSpace(\n            Cajita::Ghost(), entity_type(), Cajita::Local() );\n        size = ghost_entities.size();\n        i_size = ghost_entities.extent( Dim::I );\n        ij_size = i_size * ghost_entities.extent( Dim::J );\n    }\n\n    KOKKOS_FUNCTION void\n    convertIndexTo3d( size_type i,\n                      ParticleLevelSetPredicateStorage<size_type>& ijk ) const\n    {\n        ijk.k = i / ij_size;\n        size_type k_size = ijk.k * ij_size;\n        ijk.j = ( i - k_size ) / i_size;\n        ijk.i = i - ijk.j * i_size - k_size;\n    }\n};\n\n//---------------------------------------------------------------------------//\n// Query callback. When the query occurs we store the distance to the closest\n// point. We don't use the tree graph so we don't insert anything into the\n// graph.\ntemplate <class CoordinateSlice, class DistanceEstimateView>\nstruct ParticleLevelSetCallback\n{\n    ParticleLevelSetPrimitiveData<\n        CoordinateSlice,\n        Kokkos::View<int*, typename CoordinateSlice::memory_space>>\n        primitive_data;\n    DistanceEstimateView distance_estimate;\n    float radius;\n\n    template <typename Predicate>\n    KOKKOS_FUNCTION void operator()( Predicate const& predicate,\n                                     int primitive_index ) const\n    {\n        // Get the actual index of the particle.\n        auto p = primitive_data.c( primitive_index );\n\n        // Get the predicate storage.\n        auto storage = getData( predicate );\n\n        // Compute the distance from the grid entity to the particle sphere.\n        float dx = static_cast<float>( primitive_data.x( p, 0 ) ) - storage.x;\n        float dy = static_cast<float>( primitive_data.x( p, 1 ) ) - storage.y;\n        float dz = static_cast<float>( primitive_data.x( p, 2 ) ) - storage.z;\n        distance_estimate( storage.i, storage.j, storage.k, 0 ) =\n            sqrt( dx * dx + dy * dy + dz * dz ) - radius;\n    }\n};\n\n} // end namespace Picasso\n\n//---------------------------------------------------------------------------//\n// ArborX traits.\nnamespace ArborX\n{\n\n// Create the primitives we build the tree from. These are the particle\n// coordinates of the color we build the level set for.\ntemplate <class CoordinateSlice, class ViewType>\nstruct AccessTraits<\n    Picasso::ParticleLevelSetPrimitiveData<CoordinateSlice, ViewType>,\n    PrimitivesTag>\n{\n    using primitive_data =\n        Picasso::ParticleLevelSetPrimitiveData<CoordinateSlice, ViewType>;\n    using memory_space = typename primitive_data::memory_space;\n    using size_type = typename primitive_data::size_type;\n    static size_type size( const primitive_data& data )\n    {\n        return data.num_color;\n    }\n    static KOKKOS_FUNCTION Point get( const primitive_data& data, size_type i )\n    {\n        // Get the actual index of the particle.\n        auto p = data.c( i );\n\n        // Return a point made from the particles.\n        return { static_cast<float>( data.x( p, 0 ) ),\n                 static_cast<float>( data.x( p, 1 ) ),\n                 static_cast<float>( data.x( p, 2 ) ) };\n    }\n};\n\n// Create the predicates we search the tree with. These are the mesh entities\n// on which we build the level set.\ntemplate <class LocalMesh, class EntityType>\nstruct AccessTraits<\n    Picasso::ParticleLevelSetPredicateData<LocalMesh, EntityType>,\n    PredicatesTag>\n{\n    using predicate_data =\n        Picasso::ParticleLevelSetPredicateData<LocalMesh, EntityType>;\n    using entity_type = typename predicate_data::entity_type;\n    using memory_space = typename predicate_data::memory_space;\n    using size_type = typename predicate_data::size_type;\n    static size_type size( const predicate_data& data ) { return data.size; }\n    static KOKKOS_FUNCTION auto get( const predicate_data& data, size_type i )\n    {\n        // Get the entity index.\n        Picasso::ParticleLevelSetPredicateStorage<size_type> storage;\n        data.convertIndexTo3d( i, storage );\n        int index[3] = { storage.i, storage.j, storage.k };\n\n        // Get the coordinates of the entity.\n        double x[3];\n        data.local_mesh.coordinates( entity_type(), index, x );\n        storage.x = x[0];\n        storage.y = x[1];\n        storage.z = x[2];\n\n        // Find the nearest particle to the entity. Attach the entity index to\n        // use in the callback.\n        return attach( nearest( Point{ storage.x, storage.y, storage.z }, 1 ),\n                       storage );\n    }\n};\n\n} // end namespace ArborX\n\n//---------------------------------------------------------------------------//\nnamespace Picasso\n{\n//---------------------------------------------------------------------------//\n// Particle level set. Composes a signed distance function for particles of a\n// given color.\ntemplate <class MeshType, class SignedDistanceLocation>\nclass ParticleLevelSet\n{\n  public:\n    using mesh_type = MeshType;\n    using memory_space = typename mesh_type::memory_space;\n    using location_type = SignedDistanceLocation;\n    using entity_type = typename location_type::entity_type;\n    using halo_type = Cajita::Halo<memory_space>;\n    using level_set = LevelSet<MeshType, SignedDistanceLocation>;\n\n    /*!\n      \\brief Construct the level set with particles of a given color. If the\n      input color is negative then all particles will be used in the level set\n      regardless of color.\n      \\param ptree Level set settings.\n      \\param mesh The mesh over which to build the signed distnace function.\n      \\param color The particle color over which to build the level set. Use\n      -1 if the level set is to be built over all particles.\n    */\n    ParticleLevelSet( const boost::property_tree::ptree& ptree,\n                      const std::shared_ptr<MeshType>& mesh, const int color )\n        : _color( color )\n        , _ls( createLevelSet<SignedDistanceLocation>( ptree, mesh ) )\n    {\n        // Extract parameters.\n        const auto& params = ptree.get_child( \"particle_level_set\" );\n\n        // Particles have an analytic spherical level set. Get the radius as a\n        // fraction of the cell size.\n        _dx = mesh->localGrid()->globalGrid().globalMesh().cellSize( 0 );\n        _radius = _dx * params.get<double>( \"particle_radius\", 0.5 );\n    }\n\n    Kokkos::View<const int*, memory_space> colorIndex() const\n    {\n        return _color_indices;\n    }\n\n    int colorCount() const { return _color_count; }\n\n    /*!\n      \\brief Update the set of particle indices for the color we are building\n      the set for. This operation is needed any time the particle population\n      is updated (e.g. after a redistribution) and therefore is separated from\n      the distance estimate because it may only be called periodically.\n      \\param exec_space The execution space to use for parallel kernels.\n      \\param c_p A view or slice containing the particle colors. The number\n      and order of particles with respect to these colors must remain\n      consistent in between calls to this function (e.g. in subsequent calls\n      to estimateSignedDistance()).\n    */\n    template <class ExecutionSpace, class ParticleColors>\n    void updateParticleColors( const ExecutionSpace& exec_space,\n                               const ParticleColors& c_p )\n    {\n        // Initialize color indices.\n        _color_indices = Kokkos::View<int*, memory_space>(\n            Kokkos::ViewAllocateWithoutInitializing( \"color_indices\" ),\n            c_p.size() );\n\n        // If we dont have any particles on this rank we have nothing to do.\n        if ( 0 == c_p.size() )\n        {\n            _color_count = 0;\n            return;\n        }\n\n        // If the color is not negative then count how many particles have the\n        // color we want and compute the indices.\n        else if ( _color >= 0 )\n        {\n            Kokkos::View<int, memory_space> color_count( \"color_count\" );\n            int color = _color;\n            auto color_ind = _color_indices;\n            Kokkos::parallel_for(\n                \"Picasso::ParticleLevelSet::CountColor\",\n                Kokkos::RangePolicy<ExecutionSpace>( exec_space, 0,\n                                                     c_p.size() ),\n                KOKKOS_LAMBDA( const int p ) {\n                    if ( color == c_p( p ) )\n                    {\n                        color_ind(\n                            Kokkos::atomic_fetch_add( &color_count(), 1 ) ) = p;\n                    }\n                } );\n            Kokkos::deep_copy( _color_count, color_count );\n            _color_indices = color_ind;\n        }\n\n        // Otherwise a negative color means all particles are included in the\n        // level set so we can more efficiently generate the array.\n        else\n        {\n            int color_count = c_p.size();\n            auto color_ind = _color_indices;\n            Kokkos::parallel_for(\n                \"Picasso::ParticleLevelSet::FillColorIndices\",\n                Kokkos::RangePolicy<ExecutionSpace>( exec_space, 0,\n                                                     c_p.size() ),\n                KOKKOS_LAMBDA( const int p ) { color_ind( p ) = p; } );\n\n            _color_count = color_count;\n            _color_indices = color_ind;\n        }\n    }\n\n    /*!\n      \\brief Compute the signed distance function estimate from the current\n      particle locations. All the positive values will be correct but the\n      negative values will only have the correct sign until redistanced.\n      \\param exec_space The execution space to use for parallel kernels.\n      \\param x_p A view or slice of particle positions. If the grid is\n      adaptive these positions must be in the logical frame. The number and\n      order of particles with respect to these positions must be consistent\n      with the colors provided to the last call to updateParticleColors().\n    */\n    template <class ExecutionSpace, class ParticlePositions>\n    void estimateSignedDistance( const ExecutionSpace& exec_space,\n                                 const ParticlePositions& x_p )\n    {\n        // Distance estimate.\n        auto distance_estimate = _ls->getDistanceEstimate();\n\n        // View of the distance estimate.\n        auto estimate_view = distance_estimate->view();\n\n        // Local mesh.\n        auto local_grid = distance_estimate->layout()->localGrid();\n        auto local_mesh = Cajita::createLocalMesh<memory_space>( *local_grid );\n\n        // If we have no particles of the given color on this rank then we are\n        // in a region of positive distance. Estimate the signed distance\n        // everywhere to be the minimum halo width as this is the minimum\n        // distance to a particle surface we could have resolved that wouldn't\n        // show up in the min-reduce operation.\n        if ( 0 == _color_count )\n        {\n            double min_dist = _dx * local_grid->haloCellWidth();\n            Cajita::ArrayOp::assign( *distance_estimate, min_dist,\n                                     Cajita::Ghost() );\n        }\n\n        // Otherwise we have particles so build a tree from the particles of\n        // the given color and estimate the distance.\n        else\n        {\n            // Build the tree\n            ParticleLevelSetPrimitiveData<ParticlePositions,\n                                          Kokkos::View<int*, memory_space>>\n                primitive_data;\n            primitive_data.x = x_p;\n            primitive_data.c = _color_indices;\n            primitive_data.num_color = _color_count;\n            ArborX::BVH<memory_space> bvh( exec_space, primitive_data );\n\n            // Make the search predicates.\n            ParticleLevelSetPredicateData<decltype( local_mesh ), entity_type>\n                predicate_data( local_mesh, *local_grid );\n\n            // Make the distance callback.\n            ParticleLevelSetCallback<ParticlePositions,\n                                     decltype( estimate_view )>\n                distance_callback;\n            distance_callback.primitive_data = primitive_data;\n            distance_callback.distance_estimate = estimate_view;\n            distance_callback.radius = static_cast<float>( _radius );\n\n            // Query the particle tree with the mesh entities to find the\n            // closest particle and compute the initial signed distance\n            // estimate. Dummy arguments are needed even though we don't care\n            // about the output.\n            bvh.query( exec_space, predicate_data, distance_callback );\n        }\n\n        // Do a reduction to get the minimum distance within the minimum halo\n        // width.\n        _ls->getHalo()->scatter( exec_space, Cajita::ScatterReduce::Min(),\n                                 *distance_estimate );\n    }\n\n    // Get the particle radius.\n    double particleRadius() const { return _radius; }\n\n    // Get the level set.\n    std::shared_ptr<level_set> levelSet() const { return _ls; }\n\n  private:\n    int _color;\n    double _radius;\n    double _dx;\n    Kokkos::View<int*, memory_space> _color_indices;\n    int _color_count;\n    std::shared_ptr<level_set> _ls;\n};\n\n//---------------------------------------------------------------------------//\n/*!\n  \\brief Create a particle level set over particles of the given color. A\n  color of -1 will create the level set over all particles.\n  \\param ptree Level set settings.\n  \\param mesh The mesh over which to build the signed distance function.\n  \\param color The particle color over which to build the level set. Use -1 if\n  the level set is to be built over all particles.\n*/\ntemplate <class SignedDistanceLocation, class MeshType>\nstd::shared_ptr<ParticleLevelSet<MeshType, SignedDistanceLocation>>\ncreateParticleLevelSet( const boost::property_tree::ptree& ptree,\n                        const std::shared_ptr<MeshType>& mesh, const int color )\n{\n    return std::make_shared<ParticleLevelSet<MeshType, SignedDistanceLocation>>(\n        ptree, mesh, color );\n}\n\n//---------------------------------------------------------------------------//\n\n} // end namespace Picasso\n\n#endif // end PICASSO_PARTICLELEVELSET_HPP\n", "meta": {"hexsha": "d399db0cf84dd79b44844107328adff87b82caa0", "size": 16607, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Picasso_ParticleLevelSet.hpp", "max_stars_repo_name": "abisner/picasso", "max_stars_repo_head_hexsha": "06c1ae58e75f7da4c3eb2421c3297e5258c2ad90", "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/Picasso_ParticleLevelSet.hpp", "max_issues_repo_name": "abisner/picasso", "max_issues_repo_head_hexsha": "06c1ae58e75f7da4c3eb2421c3297e5258c2ad90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Picasso_ParticleLevelSet.hpp", "max_forks_repo_name": "abisner/picasso", "max_forks_repo_head_hexsha": "06c1ae58e75f7da4c3eb2421c3297e5258c2ad90", "max_forks_repo_licenses": ["BSD-3-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.2600472813, "max_line_length": 80, "alphanum_fraction": 0.6021557175, "num_tokens": 3393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.045352582005908706, "lm_q1q2_score": 0.02161411770721272}}
{"text": "/* FreeCT_ICD is MBIR CT reconstruction Software */\n/* Copyright (C) 2018  John Hoffman, Stefano Young, Frederic Noo */\n\n/* This program is free software; you can redistribute it and/or */\n/* modify it under the terms of the GNU General Public License */\n/* as published by the Free Software Foundation; either version 2 */\n/* of the License, or (at your option) any later version. */\n\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the */\n/* GNU General Public License for more details. */\n\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, USA. */\n\n/* Questions and comments should be directed to */\n/* jmhoffman@mednet.ucla.edu with \"FreeCT_ICD\" in the subject line*/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <math.h>\n\n#include <chrono>\n\n#include <omp.h>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\nnamespace ublas = boost::numeric::ublas;\n\n#include \"spinner.h\"\n#include \"recon_structs.h\"\n#include \"icd_iteration.h\"\n#include \"penalties.h\"\n\n#define OMP_N_THREADS 11\n\nvoid icd_iteration(const struct recon_params * rp, struct ct_data * data){\n\n    size_t data_size = rp->Readings*rp->n_channels*rp->Nrows_projection;\n    \n    // Allocate sinogram estimate (all zeros)\n    double * sinogram_estimate = new double[rp->Readings*rp->n_channels*rp->Nrows_projection]();\n    double * reconstructed_image= new double[rp->num_voxels_x*rp->num_voxels_y*rp->num_voxels_z];\n\n    // Copy the float recon volume into the vector array (if uninitialized, will just copy zeros);\n    for (int i=0; i<rp->num_voxels_x; i++){\n        for (int j=0; j<rp->num_voxels_y; j++){\n            for (int k=0; k<rp->num_voxels_z; k++){\n                size_t idx=i+j*rp->num_voxels_x+k*rp->num_voxels_x*rp->num_voxels_y;\n                reconstructed_image[idx]=(double)data->recon_volume[idx];\n            }\n        }\n    }\n\n    std::ifstream file(rp->matrix_path, std::ios_base::binary);\n    \n    // If WFBP was used to inialize the reconstructions, we need to initialize our sinogram estimate.\n    if (rp->wfbp_initialize){\n        std::cout << \"Initializing sinogram estimate...\" << std::endl;       \n\n        // run a forward projection to initialize\n        init_spinner();\n        for (int j=0; j<rp->num_voxels_y; j++){\n            update_spinner(j,rp->num_voxels_x);\n            for (int i=0; i<rp->num_voxels_x; i++){        \n                // Extract column of projection matrix\n                size_t nnz;\n                file.read((char*)&nnz, sizeof(nnz));                \n                int num_nonzeros = (int)nnz; // cast to int to avoid potential issues\n                struct pair{\n                    int index;\n                    float value;\n                };\n                //std::vector<pair> nonzeros(num_nonzeros);\n\n                struct pair * nonzeros = new struct pair[num_nonzeros];\n                if (num_nonzeros > 0)\n                    file.read((char*)&nonzeros[0], num_nonzeros*sizeof(pair));\n\n                // Loop over all slices for current x,y\n                for (int k=0; k<rp->num_voxels_z; k++){\n        \n                    size_t central_idx=data->slice_indices[k];\n                    // If using flying focal spots, need to guarantee that offset corresponds to the first projection in a FFS \"stack\"\n                    if (rp->Zffs || rp->Phiffs){\n                        int n_focal_spots=pow(2.0,rp->Zffs)*pow(2.0,rp->Phiffs);\n                        int mod=central_idx%n_focal_spots;\n                        central_idx=central_idx-mod;\n                    }\n                    \n                    int offset = (central_idx - rp->num_views_for_system_matrix/2)*rp->n_channels*rp->Nrows_projection; // offset is a projection index\n                    \n#pragma omp parallel num_threads(OMP_N_THREADS)\n                    {\n#pragma omp for\n                    for (int m = 0; m<num_nonzeros; m++){\n                        int index = nonzeros[m].index + offset; // Raw data index\n                        if ((index > -1) && (index < data_size)){\n                            size_t voxel_idx=i+j*rp->num_voxels_x+k*rp->num_voxels_x*rp->num_voxels_y;\n                            sinogram_estimate[index] = sinogram_estimate[index] + reconstructed_image[voxel_idx]*nonzeros[m].value;\n                        }\n                    }\n                    }\n                }\n                delete[] nonzeros;\n            }            \n        }\n        destroy_spinner();\n        file.clear();\n        file.seekg(0, std::ios_base::beg);\n    }\n\n\n    // Write pre-iteration reconstruction to disk \n    std::ostringstream recon_path;       \n    recon_path << rp->output_dir << \"/reconstructions/iteration0.rcn\";\n    std::ofstream recon_file(recon_path.str(), std::ios_base::binary);\n    recon_file.write((char*)&reconstructed_image[0], rp->num_voxels_x*rp->num_voxels_y*rp->num_voxels_z*sizeof(reconstructed_image[0]));\n    recon_file.close();\n    std::cout << \"Wrote initial image to disk.\" << std::endl;\n        \n    // Write reconstruction to disk\n    std::ostringstream sino_est_path;       \n    sino_est_path << rp->output_dir << \"/reconstructions/sino_estimation\" << \".rcn\";\n    std::ofstream sino_file(sino_est_path.str(), std::ios_base::binary);\n    sino_file.write((char*)sinogram_estimate, rp->Readings*rp->Nrows_projection*rp->n_channels*sizeof(double));\n    sino_file.close();\n    std::cout << \"Wrote initial sinogram to disk.\" << std::endl;    \n\n    //tk end debugging\n\n    ublas::compressed_vector<float> col(rp->Readings*rp->n_channels*rp->Nrows_projection);\n\n    // Initialize iterative parameters\n    // Current implementation limited to 2D (hard coded)\n    struct iterative_params ip;\n    initialize_2d_weights(&ip);\n    ip.lambda = rp->lambda;\n    ip.Nx=rp->num_voxels_x;\n    ip.Ny=rp->num_voxels_y;\n    ip.Nz=rp->num_voxels_z;    \n    ip.delta  = rp->delta;\n\n    for (int n = 0; n < rp->num_iterations; n++){\n        \n        std::cout << \"Iteration #\" << n+1 << std::endl;\n        std::chrono::high_resolution_clock::time_point start=std::chrono::high_resolution_clock::now();\n\n        double fov_limit=(rp->acquisition_fov/2.0)*(rp->acquisition_fov/2.0);\n\n        init_spinner();\n        for (int j = 0; j < rp->num_voxels_y; j++){\n            update_spinner(j,rp->num_voxels_y);\n            double y = (j - rp->center_voxel_y)*rp->voxel_size_y;\n            for (int i = 0; i < rp->num_voxels_x; i++){\n\n                double x = (i - rp->center_voxel_x)*rp->voxel_size_x;\n\n                size_t nnz;\n                file.read((char*)&nnz, sizeof(nnz));\n                \n                int num_nonzeros = (int)nnz; // cast to int to avoid potential issues\n\n                struct pair{\n                    int index;\n                    float value;\n                };\n\n                //std::vector<pair> nonzeros(num_nonzeros);\n\n                struct pair * nonzeros = new struct pair[num_nonzeros];\n\n                if (num_nonzeros > 0)\n                    file.read((char*)&nonzeros[0], num_nonzeros*sizeof(pair));\n\n                if ((x*x + y*y) < fov_limit){\n\n                    int q0 = i + rp->num_voxels_x*j;\n\n                    for (int k = 0; k < (rp->num_voxels_z); k++){ \n\n                        /// Grab the Z slice locations (spatial+idx)\n                        double curr_slice_location=data->slice_locations[k];\n                        size_t central_idx=data->slice_indices[k];\n\n                        int q = q0 + rp->num_voxels_x*rp->num_voxels_y*k;\n\n                        // This is the key spot to select slice location (done via the \"central_idx\" variable)                        \n                        // If using flying focal spots, need to guarantee that offset corresponds to the first projection in a FFS \"stack\"\n                        int start_idx=(central_idx - rp->num_views_for_system_matrix/2);\n                        int offset = start_idx*rp->n_channels*rp->Nrows_projection;\n                        \n                        double alpha = 0.0;\n                        double beta  = 0.0;\n\n#pragma omp parallel num_threads(OMP_N_THREADS)\n                        {\n#pragma omp for reduction(+:alpha,beta)\n                            for (int m = 0; m<num_nonzeros; m++){\n                                int index = nonzeros[m].index + offset;\n                                \n                                if ((index > -1) && (index < data_size)){\n                                    alpha += nonzeros[m].value * nonzeros[m].value;\n                                    beta  += nonzeros[m].value * ((double)data->raw[index] - sinogram_estimate[index]);\n                                }                                \n                            }\n                        }\n\n                        ip.alpha = alpha;\n                        ip.beta  = beta;\n                        \n                        // Apply selected penalty functions\n                        double pixel_update=0.0;\n                        /* Quadratic */\n                        if (rp->penalty.compare(\"quadratic\")==0){\n                            pixel_update=quadratic(q,&ip,reconstructed_image);\n                        }\n                        /* Edge Preserving*/\n                        else if(rp->penalty.compare(\"edge-preserving\")==0){\n                            pixel_update=edge_preserving(q,&ip,reconstructed_image);\n                        }\n                        else{\n                            std::cout << \"Unrecognized penalty selected. Exiting.\" << std::endl;\n                            exit(1);\n                        }\n\n                        //Enforce positivity\n                        if (pixel_update+reconstructed_image[q]<0)\n                            pixel_update = -reconstructed_image[q];\n                        \n                        //Update image\n                        reconstructed_image[q] += pixel_update;\n\n                        //Update the forward-projection data\n#pragma omp parallel num_threads(OMP_N_THREADS)\n                        {\n#pragma omp for\n                            for (int m = 0; m<num_nonzeros; m++){\n                                int index = nonzeros[m].index + offset;\n\n                                if ((index > -1) && (index < data_size))\n                                    sinogram_estimate[index] += pixel_update*nonzeros[m].value;\n                            }\n                        }\n\n                    }\n                }\n                delete[] nonzeros;\n            }\n        }\n\n        destroy_spinner();\n\n        // Close up our timer\n        std::chrono::high_resolution_clock::time_point end=std::chrono::high_resolution_clock::now();\n        auto duration=std::chrono::duration_cast<std::chrono::seconds>(end-start).count();\n        std::cout << duration << \" s\" << std::endl;\n\n        // Write reconstruction to disk\n        std::ostringstream recon_path;       \n        recon_path << rp->output_dir << \"/reconstructions/iteration\" << n+1 << \".rcn\";\n        std::ofstream recon_file(recon_path.str(), std::ios_base::binary);\n        recon_file.write((char*)&reconstructed_image[0], rp->num_voxels_x*rp->num_voxels_y*rp->num_voxels_z*sizeof(reconstructed_image[0]));\n        recon_file.close();\n\n        // \"Rewind\" the matrix file for the next iteration\n        file.clear();\n        file.seekg(0, std::ios_base::beg);        \n    }\n\n    // Copy the final reconstructed volume back into our data structure\n    for (int i=0; i<rp->num_voxels_x; i++){\n        for (int j=0; j<rp->num_voxels_y; j++){\n            for (int k=0; k<rp->num_voxels_z; k++){\n                size_t idx=i+j*rp->num_voxels_x+k*rp->num_voxels_x*rp->num_voxels_y;\n                data->recon_volume[idx]=(float)reconstructed_image[idx];\n            }            \n        }        \n    }\n\n}\n\n\n", "meta": {"hexsha": "581cdcec0e06144cf6c45bb3dd5fd4a6ffcd3e24", "size": 12189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/fct_icd/src/icd_iteration.cpp", "max_stars_repo_name": "FreeCT/FreeCT", "max_stars_repo_head_hexsha": "bf6a7c2bb73dab3f3c4962a9c8de42aa6979792f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-06-29T02:33:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T08:57:08.000Z", "max_issues_repo_path": "applications/fct_icd/src/icd_iteration.cpp", "max_issues_repo_name": "FreeCT/FreeCT", "max_issues_repo_head_hexsha": "bf6a7c2bb73dab3f3c4962a9c8de42aa6979792f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2020-07-03T18:32:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T08:13:53.000Z", "max_forks_repo_path": "applications/fct_icd/src/icd_iteration.cpp", "max_forks_repo_name": "FreeCT/FreeCT", "max_forks_repo_head_hexsha": "bf6a7c2bb73dab3f3c4962a9c8de42aa6979792f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:57:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-24T16:35:04.000Z", "avg_line_length": 42.1764705882, "max_line_length": 151, "alphanum_fraction": 0.5373697596, "num_tokens": 2759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250462027098473, "lm_q2_score": 0.05108274056859422, "lm_q1q2_score": 0.02158269390633513}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS_CODATA_NEUTRON_CONSTANTS_HPP\n#define BOOST_UNITS_CODATA_NEUTRON_CONSTANTS_HPP\n\n#include <boost/units/static_constant.hpp>\n\n#include <boost/units/systems/detail/constants.hpp>\n#include <boost/units/systems/si/amount.hpp>\n#include <boost/units/systems/si/area.hpp>\n#include <boost/units/systems/si/electric_charge.hpp>\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/systems/si/frequency.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/wavenumber.hpp>\n\n#include <boost/units/systems/si/codata/typedefs.hpp>\n\n/// \\file\n/// CODATA recommended values of fundamental atomic and nuclear constants\n/// CODATA 2006 values as of 2007/03/30\n\nnamespace boost {\n\nnamespace units { \n\nnamespace si {\n                            \nnamespace constants {\n\nnamespace codata {\n\n/// CODATA recommended values of the fundamental physical constants: NIST SP 961\n\n/// neutron mass\nBOOST_UNITS_PHYSICAL_CONSTANT(m_n,quantity<mass>,1.674927211e-27*kilograms,8.4e-35*kilograms);\n/// neutron-electron mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_n_over_m_e,quantity<dimensionless>,1838.6836605*dimensionless(),1.1e-6*dimensionless());\n/// neutron-muon mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_n_over_m_mu,quantity<dimensionless>,8.89248409*dimensionless(),2.3e-7*dimensionless());\n/// neutron-tau mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_n_over_m_tau,quantity<dimensionless>,0.528740*dimensionless(),8.6e-5*dimensionless());\n/// neutron-proton mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_n_over_m_p,quantity<dimensionless>,1.00137841918*dimensionless(),4.6e-10*dimensionless());\n/// neutron molar mass\nBOOST_UNITS_PHYSICAL_CONSTANT(M_n,quantity<mass_over_amount>,1.00866491597e-3*kilograms/mole,4.3e-13*kilograms/mole);\n/// neutron Compton wavelength\nBOOST_UNITS_PHYSICAL_CONSTANT(lambda_C_n,quantity<length>,1.3195908951e-15*meters,2.0e-24*meters);\n/// neutron magnetic moment\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_n,quantity<energy_over_magnetic_flux_density>,-0.96623641e-26*joules/tesla,2.3e-33*joules/tesla);\n/// neutron g-factor\nBOOST_UNITS_PHYSICAL_CONSTANT(g_n,quantity<dimensionless>,-3.82608545*dimensionless(),9.0e-7*dimensionless());\n/// neutron-electron magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_n_over_mu_e,quantity<dimensionless>,1.04066882e-3*dimensionless(),2.5e-10*dimensionless());\n/// neutron-proton magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_n_over_mu_p,quantity<dimensionless>,-0.68497934*dimensionless(),1.6e-7*dimensionless());\n/// neutron-shielded proton magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_n_over_mu_p_prime,quantity<dimensionless>,-0.68499694*dimensionless(),1.6e-7*dimensionless());\n/// neutron gyromagnetic ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(gamma_n,quantity<frequency_over_magnetic_flux_density>,1.83247185e8/second/tesla,4.3e1/second/tesla);\n\n} // namespace codata\n\n} // namespace constants    \n\n} // namespace si\n\n} // namespace units\n\n} // namespace boost\n\n#endif // BOOST_UNITS_CODATA_NEUTRON_CONSTANTS_HPP\n", "meta": {"hexsha": "44d89bc089a86a5e70e4649e1fd34efeb9c33250", "size": 3548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/units/systems/si/codata/neutron_constants.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/units/systems/si/codata/neutron_constants.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/units/systems/si/codata/neutron_constants.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 42.2380952381, "max_line_length": 131, "alphanum_fraction": 0.7981961669, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668680822513, "lm_q2_score": 0.05340333224796729, "lm_q1q2_score": 0.02155181554046805}}
{"text": "//\n//  Copyright (c) 2010 Athanasios Iliopoulos\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 ASSIGNMENT_HPP\n#define ASSIGNMENT_HPP\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n\n/*! \\file assignment.hpp\n    \\brief uBlas assignment operator <<=.\n*/\n\nnamespace boost { namespace numeric { namespace ublas {\n\n/** \\brief A CRTP and Barton-Nackman trick index manipulator wrapper class.\n *\n * This class is not meant to be used directly.\n */\ntemplate <class TV>\nclass index_manipulator {\npublic:\n    typedef TV type;\n    BOOST_UBLAS_INLINE\n    const type &operator () () const {\n        return *static_cast<const type *> (this);\n    }\n    BOOST_UBLAS_INLINE\n    type &operator () () {\n        return *static_cast<type *> (this);\n    }\n};\n\n/** \\brief A move_to vector index manipulator.\n *\n * When member function \\c manip is called the referenced\n * index will be set to the manipulators' index.\n *\n * \\sa move_to(T i)\n */\ntemplate <typename T>\nclass vector_move_to_manip: public index_manipulator<vector_move_to_manip<T> > {\npublic:\n    BOOST_UBLAS_INLINE\n    vector_move_to_manip(const T &k): i(k) { }\n\n    template <typename V>\n    BOOST_UBLAS_INLINE\n    void manip(V &k) const { k=i; }\nprivate:\n    T i;\n};\n\n/** \\brief An object generator that returns a move_to vector index manipulator\n *\n * \\param i The element number the manipulator will move to when \\c manip member function is called\n * \\return A move_to vector manipulator\n *\n * Example usage:\n * \\code\n * vector<double> a(6, 0);\n * a <<= 1, 2, move_to(5), 3;\n * \\endcode\n * will result in:\n * \\code\n * 1 2 0 0 0 3\n * \\endcode\n *\n * \\tparam T Size type\n * \\sa move_to()\n */\ntemplate <typename T>\nBOOST_UBLAS_INLINE vector_move_to_manip<T>  move_to(T i) {\n    return vector_move_to_manip<T>(i);\n}\n\n/** \\brief A static move to vector manipulator.\n *\n * When member function \\c manip is called the referenced\n * index will be set to the manipulators' index\n *\n * \\sa move_to(T i) and move_to()\n*/\ntemplate <std::size_t I>\nclass static_vector_move_to_manip: public index_manipulator<static_vector_move_to_manip<I> > {\npublic:\n    template <typename V>\n    BOOST_UBLAS_INLINE\n    void manip(V &k) const { k=I; }\n};\n\n/** \\brief An object generator that returns a static move_to vector index  manipulator.\n *\n * Typically faster than the dynamic version, but can be used only when the\n * values are known at compile time.\n *\n * \\return A static move_to vector manipulator\n *\n * Example usage:\n * \\code\n * vector<double> a(6, 0);\n * a <<= 1, 2, move_to<5>(), 3;\n * \\endcode\n * will result in:\n * \\code\n * 1 2 0 0 0 3\n * \\endcode\n *\n * \\tparam I The number of elements the manipulator will traverse the index when \\c manip function is called\n */\ntemplate <std::size_t I>\nBOOST_UBLAS_INLINE static_vector_move_to_manip<I>  move_to() {\n    return static_vector_move_to_manip<I>();\n}\n\n/** \\brief A move vector index manipulator.\n *\n * When member function traverse is called the manipulators'\n * index will be added to the referenced index.\n *\n * \\see move(T i)\n */\ntemplate <typename T>\nclass vector_move_manip: public index_manipulator<vector_move_manip<T> > {\npublic:\n    BOOST_UBLAS_INLINE\n    vector_move_manip(const T &k): i(k) { }\n\n    template <typename V>\n    BOOST_UBLAS_INLINE void manip(V &k) const { k+=i; }\nprivate:\n    T i;\n};\n\n/**\n* \\brief  An object generator that returns a move vector index manipulator\n*\n* \\tparam T Size type\n* \\param i The number of elements the manipulator will traverse the index when \\c manip\n* member function is called. Negative values can be used.\n* \\return A move vector manipulator\n*\n* Example usage:\n* \\code\n* vector<double> a(6, 0);\n* a <<= 1, 2, move(3), 3;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0 0 0 3\n* \\endcode\n*\n*/\ntemplate <typename T>\nBOOST_UBLAS_INLINE vector_move_manip<T>  move(T i) {\n    return vector_move_manip<T>(i);\n}\n\n/**\n* \\brief A static move vector manipulator\n*\n* When member function \\c manip is called the manipulators\n* index will be added to the referenced index\n*\n* \\sa move()\n*\n* \\todo Doxygen has some problems with similar template functions. Correct that.\n*/\ntemplate <std::size_t I>\nclass static_vector_move_manip: public index_manipulator<static_vector_move_manip<I> > {\npublic:\n    template <typename V>\n    BOOST_UBLAS_INLINE void manip(V &k) const { k+=I; }\n};\n\n/**\n* \\brief An object generator that returns a static move vector index manipulator.\n*\n* Typically faster than the dynamic version, but can be used only when the\n* values are known at compile time.\n* \\tparam I The Number of elements the manipulator will traverse the index when \\c manip\n* function is called.Negative values can be used.\n* \\return A static move vector manipulator\n*\n* Example usage:\n* \\code\n* vector<double> a(6, 0);\n* a <<= 1, 2, move<3>(), 3;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0 0 0 3\n* \\endcode\n*\n* \\todo Doxygen has some problems with similar template functions. Correct that.\n*/\ntemplate <std::size_t I>\nBOOST_UBLAS_INLINE static_vector_move_manip<I>  move() {\n    return static_vector_move_manip<I>();\n}\n\n/**\n* \\brief A move_to matrix manipulator\n*\n* When member function \\c manip is called the referenced\n* index will be set to the manipulators' index\n*\n* \\sa move_to(T i, T j)\n*\n* \\todo Doxygen has some problems with similar template functions. Correct that.\n*/\ntemplate <typename T>\nclass matrix_move_to_manip: public index_manipulator<matrix_move_to_manip<T> > {\npublic:\n    BOOST_UBLAS_INLINE\n    matrix_move_to_manip(T k, T l): i(k), j(l) { }\n\n    template <typename V1, typename V2>\n    BOOST_UBLAS_INLINE\n    void manip(V1 &k, V2 &l) const {\n        k=i;\n        l=j;\n    }\nprivate:\n    T i, j;\n};\n\n/**\n* \\brief  An object generator that returns a \"move_to\" matrix index manipulator\n*\n* \\tparam size type\n* \\param i The row number the manipulator will move to when \\c manip\n* member function is called\n* \\param j The column number the manipulator will move to when \\c manip\n* member function is called\n* \\return A move matrix manipulator\n*\n* Example usage:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, move_to(A.size1()-1, A.size1()-1), 3;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0\n* 0 0 0\n* 0 0 3\n* \\endcode\n* \\sa move_to(T i, T j) and static_matrix_move_to_manip\n*\n* \\todo Doxygen has some problems with similar template functions. Correct that.\n*/\ntemplate <typename T>\nBOOST_UBLAS_INLINE matrix_move_to_manip<T>  move_to(T i, T j) {\n    return matrix_move_to_manip<T>(i, j);\n}\n\n\n/**\n* \\brief A static move_to matrix manipulator\n* When member function traverse is called the referenced\n* index will be set to the manipulators' index\n*\n* \\sa move_to()\n*\n* \\todo Doxygen has some problems with similar template functions. Correct that.\n*/\ntemplate <std::size_t I, std::size_t J>\nclass static_matrix_move_to_manip: public index_manipulator<static_matrix_move_to_manip<I, J> > {\npublic:\n    template <typename V, typename K>\n    BOOST_UBLAS_INLINE\n    void manip(V &k, K &l) const {\n        k=I;\n        l=J;\n    }\n};\n\n/**\n* \\brief  An object generator that returns a static move_to matrix index manipulator.\n*\n* Typically faster than the dynamic version, but can be used only when the\n* values are known at compile time.\n* \\tparam I The row number the manipulator will set the matrix assigner index to.\n* \\tparam J The column number the manipulator will set the matrix assigner index to.\n* \\return A static move_to matrix manipulator\n*\n* Example usage:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, move_to<2,2>, 3;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0\n* 0 0 0\n* 0 0 3\n* \\endcode\n* \\sa move_to(T i, T j) and static_matrix_move_to_manip\n*/\ntemplate <std::size_t I, std::size_t J>\nBOOST_UBLAS_INLINE static_matrix_move_to_manip<I, J>  move_to() {\n    return static_matrix_move_to_manip<I, J>();\n}\n\n/**\n* \\brief A move matrix index manipulator.\n*\n* When member function \\c manip is called the manipulator's\n* index will be added to the referenced' index.\n*\n* \\sa move(T i, T j)\n*/\ntemplate <typename T>\nclass matrix_move_manip: public index_manipulator<matrix_move_manip<T> > {\npublic:\n    BOOST_UBLAS_INLINE\n    matrix_move_manip(T k, T l): i(k), j(l) { }\n\n    template <typename V, typename K>\n    BOOST_UBLAS_INLINE\n    void manip(V &k, K &l) const {\n        k+=i;\n        l+=j;\n    }\nprivate:\n    T i, j;\n};\n\n/**\n* \\brief  An object generator that returns a move matrix index manipulator\n*\n* \\tparam size type\n* \\param i The number of rows the manipulator will traverse the index when \"manip\"\n* member function is called\n* \\param j The number of columns the manipulator will traverse the index when \"manip\"\n* member function is called\n* \\return A move matrix manipulator\n*\n* Example:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, move(1,0),\n*            3,;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0\n* 0 0 3\n* 0 0 0\n* \\endcode\n*/\ntemplate <typename T>\nBOOST_UBLAS_INLINE matrix_move_manip<T>  move(T i, T j) {\n    return matrix_move_manip<T>(i, j);\n}\n\n/**\n* \\brief A static move matrix index manipulator.\n*\n* When member function traverse is called the manipulator's\n* index will be added to the referenced' index.\n*\n* \\sa move()\n*\n* \\todo Doxygen has some problems with similar template functions. Correct that.\n*/\ntemplate <std::size_t I, std::size_t J>\nclass static_matrix_move_manip: public index_manipulator<static_matrix_move_manip<I, J> > {\npublic:\n    template <typename V, typename K>\n    BOOST_UBLAS_INLINE\n    void manip(V &k, K &l) const {\n        k+=I;\n        l+=J;\n    }\n};\n\n/**\n* \\brief  An object generator that returns a static \"move\" matrix index manipulator.\n*\n* Typically faster than the dynamic version, but can be used only when the\n* values are known at compile time. Negative values can be used.\n* \\tparam I The number of rows the manipulator will trasverse the matrix assigner index.\n* \\tparam J The number of columns the manipulator will trasverse the matrix assigner index.\n* \\tparam size type\n* \\return A static move matrix manipulator\n*\n* Example:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, move<1,0>(),\n*            3,;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0\n* 0 0 3\n* 0 0 0\n* \\endcode\n*\n* \\sa move_to()\n*\n* \\todo Doxygen has some problems with similar template functions. Correct that.\n*/\ntemplate <std::size_t I, std::size_t J>\nBOOST_UBLAS_INLINE static_matrix_move_manip<I, J>  move() {\n    return static_matrix_move_manip<I, J>();\n}\n\n/**\n* \\brief A begining of row manipulator\n*\n* When member function \\c manip is called the referenced\n* index will be be set to the begining of the row (i.e. column = 0)\n*\n* \\sa begin1()\n*/\nclass begin1_manip: public index_manipulator<begin1_manip > {\npublic:\n    template <typename V, typename K>\n    BOOST_UBLAS_INLINE\n    void manip(V & k, K &/*l*/) const {\n        k=0;\n    }\n};\n\n/**\n* \\brief  An object generator that returns a begin1 manipulator.\n*\n* The resulted manipulator will traverse the index to the begining\n* of the current column when its' \\c manip member function is called.\n*\n* \\return A begin1 matrix index manipulator\n*\n* Example usage:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, next_row(),\n*      3, 4, begin1(), 1;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 1\n* 3 4 0\n* 0 0 0\n* \\endcode\n* \\sa begin2()\n*/\ninline begin1_manip  begin1() {\n    return begin1_manip();\n}\n\n/**\n* \\brief A begining of column manipulator\n*\n* When member function \\c manip is called the referenced\n* index will be be set to the begining of the column (i.e. row = 0).\n*\n*\n* \\sa begin2()\n*/\nclass begin2_manip: public index_manipulator<begin2_manip > {\npublic:\n    template <typename V, typename K>\n    BOOST_UBLAS_INLINE\n    void manip(V &/*k*/, K &l) const {\n        l=0;\n    }\n};\n\n/**\n* \\brief  An object generator that returns a begin2 manipulator to be used to traverse a matrix.\n*\n* The resulted manipulator will traverse the index to the begining\n* of the current row when its' \\c manip member function is called.\n*\n* \\return A begin2 matrix manipulator\n*\n* Example:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, move<1,0>(),\n*      3, begin2(), 1;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0\n* 1 0 3\n* 0 0 0\n* \\endcode\n* \\sa begin1() begin2_manip\n*/\ninline begin2_manip  begin2() {\n    return begin2_manip();\n}\n\n\n/**\n* \\brief A next row matrix manipulator.\n*\n* When member function traverse is called the referenced\n* index will be traveresed to the begining of next row.\n*\n* \\sa next_row()\n*/\nclass next_row_manip: public index_manipulator<next_row_manip> {\npublic:\n    template <typename V, typename K>\n    BOOST_UBLAS_INLINE\n    void manip(V &k, K &l) const {\n        k++;\n        l=0;\n    }\n};\n\n/**\n* \\brief  An object generator that returns a next_row manipulator.\n*\n* The resulted manipulator will traverse the index to the begining\n* of the next row when it's manip member function is called.\n*\n* \\return A next_row matrix manipulator.\n*\n* Example:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, next_row(),\n*      3, 4;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 0\n* 3 4 0\n* 0 0 0\n* \\endcode\n* \\sa next_column()\n*/\ninline next_row_manip  next_row() {\n    return next_row_manip();\n}\n\n/**\n* \\brief A next column matrix manipulator.\n*\n* When member function traverse is called the referenced\n* index will be traveresed to the begining of next column.\n*\n* \\sa next_column()\n*/\nclass next_column_manip: public index_manipulator<next_column_manip> {\npublic:\n    template <typename V, typename K>\n    BOOST_UBLAS_INLINE\n    void manip(V &k, K &l) const {\n        k=0;\n        l++;\n    }\n};\n\n/**\n* \\brief  An object generator that returns a next_row manipulator.\n*\n* The resulted manipulator will traverse the index to the begining\n* of the next column when it's manip member function is called.\n*\n* \\return A next_column matrix manipulator.\n*\n* Example:\n* \\code:\n* matrix<double> A(3, 3, 0);\n* A <<= 1, 2, 0,\n*      3, next_column(), 4;\n* \\endcode\n* will result in:\n* \\code\n* 1 2 4\n* 3 0 0\n* 0 0 0\n* \\endcode\n*\n*/\ninline next_column_manip next_column() {\n    return next_column_manip();\n}\n\n/**\n* \\brief  A wrapper for fill policy classes\n*\n*/\ntemplate <class T>\nclass fill_policy_wrapper {\npublic:\n    typedef T type;\n};\n\n// Collection of the fill policies\nnamespace fill_policy {\n\n    /**\n    * \\brief  An index assign policy\n    *\n    * This policy is used to for the simplified ublas assign through\n    * normal indexing.\n    *\n    *\n    */\n    class index_assign :public fill_policy_wrapper<index_assign> {\n    public:\n        template <class T, typename S, typename V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const V &v) {\n            e()(i) = v;\n        }\n        template <class T, typename S, typename V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const S &j, const V &v) {\n            e()(i, j) = v;\n        }\n    };\n\n    /**\n    * \\brief  An index plus assign policy\n    *\n    * This policy is used when the assignment is desired to be followed\n    * by an addition.\n    *\n    *\n    */\n    class index_plus_assign :public fill_policy_wrapper<index_plus_assign> {\n    public:\n        template <class T, typename S, typename V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const V &v) {\n            e()(i) += v;\n        }\n        template <class T, typename S, typename V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const S &j, const V &v) {\n            e()(i, j) += v;\n        }\n    };\n\n    /**\n    * \\brief  An index minus assign policy\n    *\n    * This policy is used when the assignment is desired to be followed\n    * by a substraction.\n    *\n    *\n    */\n    class index_minus_assign :public fill_policy_wrapper<index_minus_assign> {\n    public:\n        template <class T, typename S, typename V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const V &v) {\n            e()(i) -= v;\n        }\n        template <class T, typename S, typename V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const S &j, const V &v) {\n            e()(i, j) -= v;\n        }\n    };\n\n    /**\n    * \\brief  The sparse push_back fill policy.\n    *\n    * This policy is adequate for sparse types, when fast filling is required, where indexing\n    * assign is pretty slow.\n\n    * It is important to note that push_back assign cannot be used to add elements before elements\n    * already existing in a sparse container. To achieve that please use the sparse_insert fill policy.\n    */\n    class sparse_push_back :public fill_policy_wrapper<sparse_push_back > {\n    public:\n        template <class T, class S, class V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const V &v) {\n            e().push_back(i, v);\n        }\n        template <class T, class S, class V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const S &j, const V &v) {\n            e().push_back(i,j, v);\n        }\n    };\n\n    /**\n    * \\brief  The sparse insert fill policy.\n    *\n    * This policy is adequate for sparse types, when fast filling is required, where indexing\n    * assign is pretty slow. It is slower than sparse_push_back fill policy, but it can be used to\n    * insert elements anywhere inside the container.\n    */\n    class sparse_insert :public fill_policy_wrapper<sparse_insert> {\n    public:\n        template <class T, class S, class V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const V &v) {\n            e().insert_element(i, v);\n        }\n        template <class T, class S, class V>\n        BOOST_UBLAS_INLINE\n        static void apply(T &e, const S &i, const S &j, const V &v) {\n            e().insert_element(i,j, v);\n        }\n    };\n\n}\n\n/** \\brief A wrapper for traverse policy classes\n*\n*/\ntemplate <class T>\nclass traverse_policy_wrapper {\npublic:\n    typedef T type;\n};\n\n// Collection of the traverse policies\nnamespace traverse_policy {\n\n\n    /**\n    * \\brief  The no wrap policy.\n    *\n    * The no wrap policy does not allow wrapping when assigning to a matrix\n    */\n    struct no_wrap {\n        /**\n        * \\brief  Element wrap method\n        */\n        template <class S1, class S2, class S3>\n        BOOST_UBLAS_INLINE\n        static void apply1(const S1 &/*s*/, S2 &/*i*/, S3 &/*j*/) {\n        }\n\n        /**\n        * \\brief  Matrix block wrap method\n        */\n        template <class S1, class S2, class S3>\n        BOOST_UBLAS_INLINE\n        static void apply2(const S1 &/*s1*/, const S1 &/*s2*/, S2 &/*i1*/, S3 &/*i2*/) {\n        }\n    };\n\n    /**\n    * \\brief  The wrap policy.\n    *\n    * The wrap policy enables element wrapping when assigning to a matrix\n    */\n    struct wrap {\n        /**\n        * \\brief  Element wrap method\n        */\n        template <class S1, class S2, class S3>\n        BOOST_UBLAS_INLINE\n        static void apply1(const S1 &s, S2 &i1, S3 &i2) {\n            if (i2>=s) {\n                i1++;\n                i2=0;\n            }\n        }\n\n        /**\n        * \\brief  Matrix block wrap method\n        */\n        template <class S1, class S2, class S3>\n        BOOST_UBLAS_INLINE\n        static void apply2(const S1 &s1, const S1 &s2, S2 &i1, S3 &i2) {\n            if (i2>=s2) i2=0;   // Wrap to the next block\n            else i1-=s1;        // Move up (or right) one block\n        }\n    };\n\n    /**\n    * \\brief  The row_by_row traverse policy\n    *\n    * This policy is used when the assignment is desired to happen\n    * row_major wise for performance or other reasons.\n    *\n    * This is the default behaviour. To change it globally please define BOOST_UBLAS_DEFAULT_ASSIGN_BY_COLUMN\n    * in the compilation options or in an adequate header file.\n    *\n    * Please see EXAMPLES_LINK for usage information.\n    *\n    * \\todo Add examples link\n    */\n    template <class Wrap = wrap>\n    class by_row_policy :public traverse_policy_wrapper<by_row_policy<Wrap> > {\n    public:\n        template <typename S1, typename S2>\n        BOOST_UBLAS_INLINE\n        static void advance(S1 &/*i*/, S2 &j) { j++;}\n\n        template <class E1, class E2, typename S1, typename S2, typename S3, typename S4, typename S5>\n        BOOST_UBLAS_INLINE\n        static bool next(const E1 &e, const E2 &me, S1 &i, S2 &j, const S3 &/*i0*/, const S3 &j0, S4 &k, S5 &l) {\n            l++; j++;\n            if (l>=e().size2()) {\n                l=0; k++; j=j0; i++;\n                // It is assumed that the iteration starts from 0 and happens only using this function from within\n                // an assigner object.\n                // Otherwise (i.e. if it is called outside the assigner object) apply2 should have been\n                // outside the if statement.\n                if (k>=e().size1()) {\n                    j=j0+e().size2();\n                    Wrap::apply2(e().size1(), me().size2(), i, j);\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        template <class E, typename S1, typename S2>\n        BOOST_UBLAS_INLINE\n        static void apply_wrap(const E& e, S1 &i, S2 &j) {\n            Wrap::apply1(e().size2(), i, j);\n        }\n    };\n\n    /**\n    * \\brief  The column_by_column traverse policy\n    *\n    * This policy is used when the assignment is desired to happen\n    * column_major wise, for performance or other reasons.\n    *\n    * This is the NOT the default behaviour. To set this as the default define BOOST_UBLAS_DEFAULT_ASSIGN_BY_COLUMN\n    * in the compilation options or in an adequate header file.\n    *\n    * Please see EXAMPLES_LINK for usage information.\n    *\n    * \\todo Add examples link\n    */\n    template <class Wrap = wrap>\n    class by_column_policy :public traverse_policy_wrapper<by_column_policy<Wrap> > {\n    public:\n        template <typename S1, typename S2>\n        BOOST_UBLAS_INLINE\n        static void advance(S1 &i, S2 &/*j*/) { i++;}\n\n        template <class E1, class E2, typename S1, typename S2, typename S3, typename S4, typename S5>\n        BOOST_UBLAS_INLINE\n        static bool next(const E1 &e, const E2 &me, S1 &i, S2 &j, const S3 &i0, const S3 &/*j0*/, S4 &k, S5 &l) {\n            k++; i++;\n            if (k>=e().size1()) {\n                k=0; l++; i=i0; j++;\n                // It is assumed that the iteration starts from 0 and happens only using this function from within\n                // an assigner object.\n                // Otherwise (i.e. if it is called outside the assigner object) apply2 should have been\n                // outside the if statement.\n                if (l>=e().size2()) {\n                    i=i0+e().size1();\n                    Wrap::apply2(e().size2(), me().size1(), j, i);\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        template <class E, typename S1, typename S2>\n        BOOST_UBLAS_INLINE\n        static void apply_wrap(const E& e, S1 &i, S2 &j) {\n            Wrap::apply1(e().size1(), j, i);\n        }\n    };\n}\n#ifndef BOOST_UBLAS_DEFAULT_NO_WRAP_POLICY\n    typedef traverse_policy::wrap DEFAULT_WRAP_POLICY;\n#else\n    typedef traverse_policy::no_wrap DEFAULT_WRAP_POLICY;\n#endif\n\n#ifndef BOOST_UBLAS_DEFAULT_ASSIGN_BY_COLUMN\n    typedef traverse_policy::by_row_policy<DEFAULT_WRAP_POLICY> DEFAULT_TRAVERSE_POLICY;\n#else\n    typedef traverse_policy::by_column<DEFAULT_WRAP_POLICY> DEFAULT_TRAVERSE_POLICY;\n#endif\n\n // Traverse policy namespace\nnamespace traverse_policy {\n\n    inline by_row_policy<DEFAULT_WRAP_POLICY> by_row() {\n    return by_row_policy<DEFAULT_WRAP_POLICY>();\n    }\n\n    inline by_row_policy<wrap> by_row_wrap() {\n        return by_row_policy<wrap>();\n    }\n\n    inline by_row_policy<no_wrap> by_row_no_wrap() {\n        return by_row_policy<no_wrap>();\n    }\n\n    inline by_column_policy<DEFAULT_WRAP_POLICY> by_column() {\n        return by_column_policy<DEFAULT_WRAP_POLICY>();\n    }\n\n    inline by_column_policy<wrap> by_column_wrap() {\n        return by_column_policy<wrap>();\n    }\n\n    inline by_column_policy<no_wrap> by_column_no_wrap() {\n        return by_column_policy<no_wrap>();\n    }\n\n}\n\n/**\n* \\brief  An assigner object used to fill a vector using operator <<= and operator, (comma)\n*\n* This object is meant to be created by appropriate object generators.\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E, class Fill_Policy = fill_policy::index_assign>\nclass vector_expression_assigner {\npublic:\n    typedef typename E::expression_type::value_type value_type;\n    typedef typename E::expression_type::size_type size_type;\n\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner(E &e):ve(e), i(0) {\n    }\n\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner(size_type k, E &e):ve(e), i(k) {\n        // Overloaded like that so it can be differentiated from (E, val).\n        // Otherwise there would be an ambiquity when value_type == size_type.\n    }\n\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner(E &e, value_type val):ve(e), i(0) {\n        operator,(val);\n    }\n\n    template <class AE>\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner(E &e, const vector_expression<AE> &nve):ve(e), i(0) {\n        operator,(nve);\n    }\n\n    template <typename T>\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner(E &e, const index_manipulator<T> &ta):ve(e), i(0) {\n        operator,(ta);\n    }\n\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner &operator, (const value_type& val) {\n        apply(val);\n        return *this;\n    }\n\n    template <class AE>\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner &operator, (const vector_expression<AE> &nve) {\n        for (typename AE::size_type k = 0; k!= nve().size(); k++)\n            operator,(nve()(k));\n        return *this;\n    }\n\n    template <typename T>\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner &operator, (const index_manipulator<T> &ta) {\n        ta().manip(i);\n        return *this;\n    }\n\n    template <class T>\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner<E, T> operator, (fill_policy_wrapper<T>) const {\n        return vector_expression_assigner<E, T>(i, ve);\n    }\n\nprivate:\n    BOOST_UBLAS_INLINE\n    vector_expression_assigner &apply(const typename E::expression_type::value_type& val) {\n        Fill_Policy::apply(ve, i++, val);\n        return *this;\n    }\n\nprivate:\n    E &ve;\n    size_type i;\n};\n\n/*\n// The following static assigner is about 30% slower than the dynamic one, probably due to the recursive creation of assigner objects.\n// It remains commented here for future reference.\n\ntemplate <class E, std::size_t I=0>\nclass static_vector_expression_assigner {\npublic:\n    typedef typename E::expression_type::value_type value_type;\n    typedef typename E::expression_type::size_type size_type;\n\n    BOOST_UBLAS_INLINE\n    static_vector_expression_assigner(E &e):ve(e) {\n    }\n\n    BOOST_UBLAS_INLINE\n    static_vector_expression_assigner(E &e, value_type val):ve(e) {\n        operator,(val);\n    }\n\n    BOOST_UBLAS_INLINE\n    static_vector_expression_assigner<E, I+1> operator, (const value_type& val) {\n        return apply(val);\n    }\n\nprivate:\n    BOOST_UBLAS_INLINE\n    static_vector_expression_assigner<E, I+1> apply(const typename E::expression_type::value_type& val) {\n        ve()(I)=val;\n        return static_vector_expression_assigner<E, I+1>(ve);\n    }\n\nprivate:\n    E &ve;\n};\n\ntemplate <class E>\nBOOST_UBLAS_INLINE\nstatic_vector_expression_assigner<vector_expression<E>, 1 > test_static(vector_expression<E> &v, const typename E::value_type &val) {\n    v()(0)=val;\n    return static_vector_expression_assigner<vector_expression<E>, 1 >(v);\n}\n*/\n\n\n/**\n* \\brief  A vector_expression_assigner generator used with operator<<= for simple types\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E>\nBOOST_UBLAS_INLINE\nvector_expression_assigner<vector_expression<E> > operator<<=(vector_expression<E> &v, const typename E::value_type &val) {\n    return vector_expression_assigner<vector_expression<E> >(v,val);\n}\n\n/**\n* \\brief  ! A vector_expression_assigner generator used with operator<<= for vector expressions\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E1, class E2>\nBOOST_UBLAS_INLINE\nvector_expression_assigner<vector_expression<E1> > operator<<=(vector_expression<E1> &v, const vector_expression<E2> &ve) {\n    return vector_expression_assigner<vector_expression<E1> >(v,ve);\n}\n\n/**\n* \\brief  A vector_expression_assigner generator used with operator<<= for traverse manipulators\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E, typename T>\nBOOST_UBLAS_INLINE\nvector_expression_assigner<vector_expression<E> > operator<<=(vector_expression<E> &v, const index_manipulator<T> &nv) {\n    return vector_expression_assigner<vector_expression<E> >(v,nv);\n}\n\n/**\n* \\brief  A vector_expression_assigner generator used with operator<<= for choice of fill policy\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E, typename T>\nBOOST_UBLAS_INLINE\nvector_expression_assigner<vector_expression<E>, T> operator<<=(vector_expression<E> &v, fill_policy_wrapper<T>) {\n    return vector_expression_assigner<vector_expression<E>, T>(v);\n}\n\n/**\n* \\brief  An assigner object used to fill a vector using operator <<= and operator, (comma)\n*\n* This object is meant to be created by appropriate object generators.\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E, class Fill_Policy = fill_policy::index_assign, class Traverse_Policy = DEFAULT_TRAVERSE_POLICY >\nclass matrix_expression_assigner {\npublic:\n    typedef typename E::expression_type::size_type size_type;\n\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner(E &e): me(e), i(0), j(0) {\n    }\n\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner(E &e, size_type k, size_type l): me(e), i(k), j(l) {\n    }\n\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner(E &e, typename E::expression_type::value_type val): me(e), i(0), j(0) {\n        operator,(val);\n    }\n\n    template <class AE>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner(E &e, const vector_expression<AE> &nve):me(e), i(0), j(0) {\n        operator,(nve);\n    }\n\n    template <class AE>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner(E &e, const matrix_expression<AE> &nme):me(e), i(0), j(0) {\n        operator,(nme);\n    }\n\n    template <typename T>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner(E &e, const index_manipulator<T> &ta):me(e), i(0), j(0) {\n        operator,(ta);\n    }\n\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner &operator, (const typename E::expression_type::value_type& val) {\n        Traverse_Policy::apply_wrap(me, i ,j);\n        return apply(val);\n    }\n\n    template <class AE>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner &operator, (const vector_expression<AE> &nve) {\n        for (typename AE::size_type k = 0; k!= nve().size(); k++) {\n            operator,(nve()(k));\n        }\n        return *this;\n    }\n\n    template <class AE>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner &operator, (const matrix_expression<AE> &nme) {\n        return apply(nme);\n    }\n\n    template <typename T>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner &operator, (const index_manipulator<T> &ta) {\n        ta().manip(i, j);\n        return *this;\n    } \n\n    template <class T>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner<E, T, Traverse_Policy> operator, (fill_policy_wrapper<T>) const {\n        return matrix_expression_assigner<E, T, Traverse_Policy>(me, i, j);\n    }\n\n\n    template <class T>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner<E, Fill_Policy, T> operator, (traverse_policy_wrapper<T>) {\n        Traverse_Policy::apply_wrap(me, i ,j);\n        return matrix_expression_assigner<E, Fill_Policy, T>(me, i, j);\n    }\n\nprivate:\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner &apply(const typename E::expression_type::value_type& val) {\n        Fill_Policy::apply(me, i, j, val);\n        Traverse_Policy::advance(i,j);\n        return *this;\n    }\n\n    template <class AE>\n    BOOST_UBLAS_INLINE\n    matrix_expression_assigner &apply(const matrix_expression<AE> &nme) {\n        size_type bi = i;\n        size_type bj = j;\n        typename AE::size_type k=0, l=0;\n        Fill_Policy::apply(me, i, j, nme()(k, l));\n        while (Traverse_Policy::next(nme, me, i, j, bi, bj, k, l))\n            Fill_Policy::apply(me, i, j, nme()(k, l));\n        return *this;\n    }\n\nprivate:\n    E &me;\n    size_type i, j;\n};\n\n/**\n* \\brief  A matrix_expression_assigner generator used with operator<<= for simple types\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E>\nBOOST_UBLAS_INLINE\nmatrix_expression_assigner<matrix_expression<E> > operator<<=(matrix_expression<E> &me, const typename E::value_type &val) {\n    return matrix_expression_assigner<matrix_expression<E> >(me,val);\n}\n\n/**\n* \\brief  A matrix_expression_assigner generator used with operator<<= for choice of fill policy\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E, typename T>\nBOOST_UBLAS_INLINE\nmatrix_expression_assigner<matrix_expression<E>, T> operator<<=(matrix_expression<E> &me, fill_policy_wrapper<T>) {\n    return matrix_expression_assigner<matrix_expression<E>, T>(me);\n}\n\n/**\n* \\brief  A matrix_expression_assigner generator used with operator<<= for traverse manipulators\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E, typename T>\nBOOST_UBLAS_INLINE\nmatrix_expression_assigner<matrix_expression<E> > operator<<=(matrix_expression<E> &me, const index_manipulator<T> &ta) {\n    return matrix_expression_assigner<matrix_expression<E> >(me,ta);\n}\n\n/**\n* \\brief  A matrix_expression_assigner generator used with operator<<= for traverse manipulators\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E, typename T>\nBOOST_UBLAS_INLINE\nmatrix_expression_assigner<matrix_expression<E>, fill_policy::index_assign, T> operator<<=(matrix_expression<E> &me, traverse_policy_wrapper<T>) {\n    return matrix_expression_assigner<matrix_expression<E>, fill_policy::index_assign, T>(me);\n}\n\n/**\n* \\brief  A matrix_expression_assigner generator used with operator<<= for vector expressions\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E1, class E2>\nBOOST_UBLAS_INLINE\nmatrix_expression_assigner<matrix_expression<E1> > operator<<=(matrix_expression<E1> &me, const vector_expression<E2> &ve) {\n    return matrix_expression_assigner<matrix_expression<E1> >(me,ve);\n}\n\n/**\n* \\brief  A matrix_expression_assigner generator used with operator<<= for matrix expressions\n*\n* Please see EXAMPLES_LINK for usage information.\n*\n* \\todo Add examples link\n*/\ntemplate <class E1, class E2>\nBOOST_UBLAS_INLINE\nmatrix_expression_assigner<matrix_expression<E1> > operator<<=(matrix_expression<E1> &me1, const matrix_expression<E2> &me2) {\n    return matrix_expression_assigner<matrix_expression<E1> >(me1,me2);\n}\n\n} } }\n\n#endif // ASSIGNMENT_HPP\n", "meta": {"hexsha": "d505d0e5d3786b4cf51c6ab5c59ae35972898fb7", "size": 35343, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/numeric/ublas/assignment.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/numeric/ublas/assignment.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/numeric/ublas/assignment.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": 27.5686427457, "max_line_length": 146, "alphanum_fraction": 0.6640918994, "num_tokens": 9533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455914759599, "lm_q2_score": 0.07159119498766672, "lm_q1q2_score": 0.021530736281036605}}
{"text": "/*  ==========================================================================================\n    Author: Leonardo Citraro\n    Company:\n    Filename: ext3DLBPpy.cpp\n    Last modifed:   09.04.2017 by Leonardo Citraro\n    Description:    Boost-Python wrappers\n    * \n    Please cite the article:    L. Citraro, S. Mahmoodi, A. Darekar, B. Vollmer,\n                                Extended three-dimensional rotation invariant local binary patterns, \n                                Image and Vision Computing (2017), \n                                http://dx.doi.org/10.1016/j.imavis.2017.03.004\n\n    ==========================================================================================\n    Copyright (c) 2017 Leonardo Citraro <ldo.citraro@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy of this\n    software and associated documentation files (the \"Software\"), to deal in the Software\n    without restriction, including without limitation the rights to use, copy, modify,\n    merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n    permit persons to whom the Software is furnished to do so, subject to the following\n    conditions:\n\n    The above copyright notice and this permission notice shall be included in all copies\n    or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n    INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n    PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\n    FOR ANY CLAIM, 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 USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n    ==========================================================================================\n*/\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/numeric.hpp>\n#include <numpy/ndarrayobject.h>\n#include \"ext3DLBP.hpp\"\n\nusing namespace ext3DLBP;\nusing namespace boost::python;\n\ntemplate<typename T, size_t K>\nArray3D<T,K,K,K> convert_numpy_to_STL(const numeric::array& data) {\n    Array3D<T,K,K,K> array;\n    for(int k=0; k<K; ++k) {\n        for(int j=0; j<K; ++j) {\n            for(int i=0; i<K; ++i) {\n                array[i][j][k] = extract<T>(data[i][j][k]);\n            }\n        }\n    } \n    return array;\n}\n\ntemplate<typename T, size_t K>\nArray3D<T,K,K,K> my_slice(const numeric::array& data, const int istart, const int jstart, const int kstart) {\n    Array3D<T,K,K,K> array;\n    for(int k=0; k<K; ++k) {\n        for(int j=0; j<K; ++j) {\n            for(int i=0; i<K; ++i) {\n                array[i][j][k] = extract<T>(data[i+istart][j+jstart][k+kstart]);\n            }\n        }\n    } \n    return array;\n}\n\nboost::python::tuple convert_to_python_return(const Array1D<int,2>& data) {\n    return boost::python::make_tuple(data[0], data[1]);\n}\nboost::python::tuple convert_to_python_return(const Array1D<int,3>& data) {\n    return boost::python::make_tuple(data[0], data[1], data[2]);\n}\nint convert_to_python_return(const int data) {\n    return data;\n}\n\n//=========================================================================\n// CI-LBP\n//=========================================================================\nstruct CI_LBP_ : public CI_LBP {\n    const static int bins = CI_LBP::bins;\n    CI_LBP_(const double mur) : CI_LBP(mur) {}\n    auto convert(const boost::python::numeric::array data) {\n        int shape0 = extract<int>(data.attr(\"shape\")[0]);\n        if(shape0 == 3)\n            return CI_LBP::convert(convert_numpy_to_STL<int,3>(data));\n        else if(shape0 == 5)\n            return CI_LBP::convert(convert_numpy_to_STL<int,5>(data));\n        else if(shape0 == 7)\n            return CI_LBP::convert(convert_numpy_to_STL<int,7>(data));\n    }\n    auto convert_3d_image(const numeric::array& image) {\n        int depth = extract<int>(image.attr(\"shape\")[0]);\n        int cols = extract<int>(image.attr(\"shape\")[1]);\n        int rows = extract<int>(image.attr(\"shape\")[2]);\n        \n        npy_intp size[3] = {depth-2, cols-2, rows-2};\n        PyObject* arr_3d_1Obj = PyArray_SimpleNew(3, size, NPY_INT);\n        \n        for(int k=0; k<(depth); ++k) {\n            for(int j=0; j<(cols); ++j) {\n                for(int i=0; i<(rows); ++i) {\n                    int chunk = extract<int>(image[i][j][k]);\n                    int* ptr = (int*) PyArray_GETPTR3(arr_3d_1Obj, i, j, k);\n                    *ptr = CI_LBP::convert(chunk);\n                }\n            }\n        }\n        boost::python::handle<> handle( arr_3d_1Obj );\n        boost::python::numeric::array arr_3d_1( handle );\n        return arr_3d_1;\n    }\n};\nconst int CI_LBP_::bins;\n\n//=========================================================================\n// NI-LBP\n//=========================================================================\n\n#define wrapper_class_1     struct fullname : public parent {\\\n                                const static int P = parent::P;\\\n                                const static int O = parent::O;\\\n                                const static int bins = parent::bins;\\\n                                const static int R = parent::R;\\\n                                const static int K = parent::K;\\\n                                fullname(const double mur, const int V) : parent(mur,V) {}\\\n                                auto convert(const boost::python::numeric::array& data) {\\\n                                    return convert_to_python_return(parent::convert(convert_numpy_to_STL<int,K>(data)));\\\n                                }\\\n                                auto convert_3d_image(const numeric::array& image) {\\\n                                    int depth = extract<int>(image.attr(\"shape\")[0]);\\\n                                    int cols = extract<int>(image.attr(\"shape\")[1]);\\\n                                    int rows = extract<int>(image.attr(\"shape\")[2]);\\\n                                    \\\n                                    npy_intp size[3] = {depth-2*R, cols-2*R, rows-2*R};\\\n                                    PyObject* arr_3d_1Obj = PyArray_SimpleNew(3, size, NPY_INT);\\\n                                    \\\n                                    for(int k=0; k<(depth-K+1); ++k) {\\\n                                        for(int j=0; j<(cols-K+1); ++j) {\\\n                                            for(int i=0; i<(rows-K+1); ++i) {\\\n                                                auto chunk = my_slice<int,K>(image,i,j,k);\\\n                                                int* ptr = (int*) PyArray_GETPTR3(arr_3d_1Obj, i, j, k);\\\n                                                *ptr = parent::convert(chunk);\\\n                                            }\\\n                                        }\\\n                                    }\\\n                                    boost::python::handle<> handle( arr_3d_1Obj );\\\n                                    boost::python::numeric::array arr_3d_1( handle );\\\n                                    return arr_3d_1;\\\n                                }\\\n                            };\\\n                            const int fullname::P;\\\n                            const int fullname::bins;\\\n                            const int fullname::O;\\\n                            const int fullname::R;\\\n                            const int fullname::K;\\\n\n#define wrapper_class_2     struct fullname : public parent {\\\n                                const static int P = parent::P;\\\n                                const static int O = parent::O;\\\n                                const static int bins = parent::bins;\\\n                                const static int R = parent::R;\\\n                                const static int K = parent::K;\\\n                                fullname(const double mur, const int V) : parent(mur,V) {}\\\n                                auto convert(const boost::python::numeric::array& data) {\\\n                                    return convert_to_python_return(parent::convert(convert_numpy_to_STL<int,K>(data)));\\\n                                }\\\n                                auto convert_3d_image(const numeric::array& image) {\\\n                                    int depth = extract<int>(image.attr(\"shape\")[0]);\\\n                                    int cols = extract<int>(image.attr(\"shape\")[1]);\\\n                                    int rows = extract<int>(image.attr(\"shape\")[2]);\\\n                                    \\\n                                    npy_intp size[3] = {depth-2*R, cols-2*R, rows-2*R};\\\n                                    PyObject* arr_3d_1Obj = PyArray_SimpleNew(3, size, NPY_INT);\\\n                                    PyObject* arr_3d_2Obj = PyArray_SimpleNew(3, size, NPY_INT);\\\n                                    \\\n                                    for(int k=0; k<(depth-K+1); ++k) {\\\n                                        for(int j=0; j<(cols-K+1); ++j) {\\\n                                            for(int i=0; i<(rows-K+1); ++i) {\\\n                                                auto chunk = my_slice<int,K>(image,i,j,k);\\\n                                                Array1D<int,2> codes = parent::convert(chunk);\\\n                                                int* ptr = (int*) PyArray_GETPTR3(arr_3d_1Obj, i, j, k);\\\n                                                *ptr = codes[0];\\\n                                                ptr = (int*) PyArray_GETPTR3(arr_3d_2Obj, i, j, k);\\\n                                                *ptr = codes[1];\\\n                                            }\\\n                                        }\\\n                                    }\\\n                                    boost::python::handle<> handle1( arr_3d_1Obj );\\\n                                    boost::python::numeric::array arr_3d_1( handle1 );\\\n                                    boost::python::handle<> handle2( arr_3d_2Obj );\\\n                                    boost::python::numeric::array arr_3d_2( handle2 );\\\n                                    return make_tuple(arr_3d_1, arr_3d_2);\\\n                                }\\\n                            };\\\n                            const int fullname::P;\\\n                            const int fullname::bins;\\\n                            const int fullname::O;\\\n                            const int fullname::R;\\\n                            const int fullname::K;\\\n                            \n#define wrapper_class_3     struct fullname : public parent {\\\n                                const static int P = parent::P;\\\n                                const static int O = parent::O;\\\n                                const static int bins = parent::bins;\\\n                                const static int R = parent::R;\\\n                                const static int K = parent::K;\\\n                                fullname(const double mur, const int V) : parent(mur,V) {}\\\n                                auto convert(const boost::python::numeric::array& data) {\\\n                                    return convert_to_python_return(parent::convert(convert_numpy_to_STL<int,K>(data)));\\\n                                }\\\n                                auto convert_3d_image(const numeric::array& image) {\\\n                                    int depth = extract<int>(image.attr(\"shape\")[0]);\\\n                                    int cols = extract<int>(image.attr(\"shape\")[1]);\\\n                                    int rows = extract<int>(image.attr(\"shape\")[2]);\\\n                                    \\\n                                    npy_intp size[3] = {depth-2*R, cols-2*R, rows-2*R};\\\n                                    PyObject* arr_3d_1Obj = PyArray_SimpleNew(3, size, NPY_INT);\\\n                                    PyObject* arr_3d_2Obj = PyArray_SimpleNew(3, size, NPY_INT);\\\n                                    PyObject* arr_3d_3Obj = PyArray_SimpleNew(3, size, NPY_INT);\\\n                                    \\\n                                    for(int k=0; k<(depth-K+1); ++k) {\\\n                                        for(int j=0; j<(cols-K+1); ++j) {\\\n                                            for(int i=0; i<(rows-K+1); ++i) {\\\n                                                auto chunk = my_slice<int,K>(image,i,j,k);\\\n                                                Array1D<int,3> codes = parent::convert(chunk);\\\n                                                int* ptr = (int*) PyArray_GETPTR3(arr_3d_1Obj, i, j, k);\\\n                                                *ptr = codes[0];\\\n                                                ptr = (int*) PyArray_GETPTR3(arr_3d_2Obj, i, j, k);\\\n                                                *ptr = codes[1];\\\n                                                ptr = (int*) PyArray_GETPTR3(arr_3d_3Obj, i, j, k);\\\n                                                *ptr = codes[2];\\\n                                            }\\\n                                        }\\\n                                    }\\\n                                    boost::python::handle<> handle1( arr_3d_1Obj );\\\n                                    boost::python::numeric::array arr_3d_1( handle1 );\\\n                                    boost::python::handle<> handle2( arr_3d_2Obj );\\\n                                    boost::python::numeric::array arr_3d_2( handle2 );\\\n                                    boost::python::handle<> handle3( arr_3d_3Obj );\\\n                                    boost::python::numeric::array arr_3d_3( handle3 );\\\n                                    return make_tuple(arr_3d_1, arr_3d_2, arr_3d_3);\\\n                                }\\\n                            };\\\n                            const int fullname::P;\\\n                            const int fullname::bins;\\\n                            const int fullname::O;\\\n                            const int fullname::R;\\\n                            const int fullname::K;\\\n                            \n// P42g\n#define fullname NI_LBP_P42g_R1\n#define parent NI_LBP<P42g, R1>\nwrapper_class_1\n\n#define fullname NI_LBP_P42g_R2\n#define parent NI_LBP<P42g, R2>\nwrapper_class_1\n\n// P92g\n#define fullname NI_LBP_P92g_R1\n#define parent NI_LBP<P92g, R1>\nwrapper_class_1\n\n#define fullname NI_LBP_P92g_R2\n#define parent NI_LBP<P92g, R2>\nwrapper_class_1\n\n#define fullname NI_LBP_P92g_R3\n#define parent NI_LBP<P92g, R3>\nwrapper_class_1\n\n// P252g\n#define fullname NI_LBP_P252g_R2\n#define parent NI_LBP<P252g, R2>\nwrapper_class_1\n\n#define fullname NI_LBP_P252g_R3\n#define parent NI_LBP<P252g, R3>\nwrapper_class_1\n\n//=========================================================================\n// RD-LBP\n//=========================================================================\n// P42g\n#define fullname RD_LBP_P42g_R1\n#define parent RD_LBP<P42g, R1>\nwrapper_class_1\n\n#define fullname RD_LBP_P42g_R2\n#define parent RD_LBP<P42g, R2>\nwrapper_class_1\n\n// P92g\n#define fullname RD_LBP_P92g_R1\n#define parent RD_LBP<P92g, R1>\nwrapper_class_1\n\n#define fullname RD_LBP_P92g_R2\n#define parent RD_LBP<P92g, R2>\nwrapper_class_1\n\n#define fullname RD_LBP_P92g_R3\n#define parent RD_LBP<P92g, R3>\nwrapper_class_1\n\n\n\n// P252g\n#define fullname RD_LBP_P252g_R2\n#define parent RD_LBP<P252g, R2>\nwrapper_class_1\n\n#define fullname RD_LBP_P252g_R3\n#define parent RD_LBP<P252g, R3>\nwrapper_class_1\n\n//=========================================================================\n// NI-RD-LBP\n//=========================================================================\n//P42g\n#define fullname NI_RD_LBP_P42g_R1\n#define parent NI_RD_LBP<P42g, R1>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P42g_R2\n#define parent NI_RD_LBP<P42g, R2>\nwrapper_class_2\n\n//P92g\n#define fullname NI_RD_LBP_P92g_R1\n#define parent NI_RD_LBP<P92g, R1>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P92g_R2\n#define parent NI_RD_LBP<P92g, R2>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P92g_R3\n#define parent NI_RD_LBP<P92g, R3>\nwrapper_class_2\n\n//P252g\n#define fullname NI_RD_LBP_P252g_R2\n#define parent NI_RD_LBP<P252g, R2>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P252g_R3\n#define parent NI_RD_LBP<P252g, R3>\nwrapper_class_2\n\n//=========================================================================\n// NI-RD-CI-LBP\n//=========================================================================\n//P42g\n#define fullname NI_RD_CI_LBP_P42g_R1\n#define parent NI_RD_CI_LBP<P42g, R1>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P42g_R2\n#define parent NI_RD_CI_LBP<P42g, R2>\nwrapper_class_3\n\n//P92g\n#define fullname NI_RD_CI_LBP_P92g_R1\n#define parent NI_RD_CI_LBP<P92g, R1>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P92g_R2\n#define parent NI_RD_CI_LBP<P92g, R2>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P92g_R3\n#define parent NI_RD_CI_LBP<P92g, R3>\nwrapper_class_3\n\n//P252g\n#define fullname NI_RD_CI_LBP_P252g_R2\n#define parent NI_RD_CI_LBP<P252g, R2>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P252g_R3\n#define parent NI_RD_CI_LBP<P252g, R3>\nwrapper_class_3\n\nBOOST_PYTHON_MODULE(ext3DLBPpy) {\n    boost::python::numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n    \n    import_array();\n    \n    // CI-LBP\n    class_<CI_LBP_>(\"CI_LBP\",init<double>())\n        .def_readonly(\"mur\", &CI_LBP_::mur)\n        .def_readonly(\"bins\", &CI_LBP_::bins)\n        .def(\"convert\", &CI_LBP_::convert)\n        .def(\"convert_3d_image\", &CI_LBP_::convert_3d_image);\n\n#define STRINGIZE_NX(A) #A\n#define STRINGIZE(A) STRINGIZE_NX(A)\n#define boost_python_definition class_<fullname>(STRINGIZE(fullname),init<double, int>())\\\n                                .def_readonly(\"P\", &fullname::P)\\\n                                .def_readonly(\"O\", &fullname::O)\\\n                                .def_readonly(\"bins\", &fullname::bins)\\\n                                .def_readonly(\"R\", &fullname::R)\\\n                                .def_readonly(\"K\", &fullname::K)\\\n                                .def_readonly(\"mur\", &fullname::mur)\\\n                                .def_readonly(\"V\", &fullname::V)\\\n                                .def(\"convert\", &fullname::convert) \\\n                                .def(\"convert_3d_image\", &fullname::convert_3d_image);\n// NI-LBP\n#define fullname NI_LBP_P42g_R1\nboost_python_definition\n\n#define fullname NI_LBP_P42g_R2\nboost_python_definition\n        \n\n#define fullname NI_LBP_P92g_R1\nboost_python_definition\n\n#define fullname NI_LBP_P92g_R2\nboost_python_definition\n\n#define fullname NI_LBP_P92g_R3\nboost_python_definition\n        \n\n#define fullname NI_LBP_P252g_R2\nboost_python_definition\n\n#define fullname NI_LBP_P252g_R3\nboost_python_definition\n\n// RD-LBP\n#define fullname RD_LBP_P42g_R1\nboost_python_definition\n\n#define fullname RD_LBP_P42g_R2\nboost_python_definition\n        \n        \n#define fullname RD_LBP_P92g_R1\nboost_python_definition\n\n#define fullname RD_LBP_P92g_R2\nboost_python_definition\n\n#define fullname RD_LBP_P92g_R3\nboost_python_definition\n        \n    \n#define fullname RD_LBP_P252g_R2\nboost_python_definition\n\n#define fullname RD_LBP_P252g_R3\nboost_python_definition\n        \n// NI-RD-LBP\n#define fullname NI_RD_LBP_P42g_R1\nboost_python_definition\n\n#define fullname NI_RD_LBP_P42g_R2\nboost_python_definition\n        \n    \n#define fullname NI_RD_LBP_P92g_R1\nboost_python_definition\n\n#define fullname NI_RD_LBP_P92g_R2\nboost_python_definition\n\n#define fullname NI_RD_LBP_P92g_R3\nboost_python_definition\n        \n        \n#define fullname NI_RD_LBP_P252g_R2\nboost_python_definition\n\n#define fullname NI_RD_LBP_P252g_R3\nboost_python_definition\n        \n    \n// NI-RD-CI-LBP\n#define fullname NI_RD_CI_LBP_P42g_R1\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P42g_R2\nboost_python_definition\n        \n\n#define fullname NI_RD_CI_LBP_P92g_R1\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P92g_R2\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P92g_R3\nboost_python_definition\n        \n    \n\n#define fullname NI_RD_CI_LBP_P252g_R2\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P252g_R3\nboost_python_definition\n\n};\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e7d652e6c6d8764432b24751a4539514c1654599", "size": 20237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python_wrapper/ext3DLBPpy.cpp", "max_stars_repo_name": "johndpope/ext3DLBP", "max_stars_repo_head_hexsha": "0704ae6a9dda7e74f1f52b45acd71d1b6f622efd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python_wrapper/ext3DLBPpy.cpp", "max_issues_repo_name": "johndpope/ext3DLBP", "max_issues_repo_head_hexsha": "0704ae6a9dda7e74f1f52b45acd71d1b6f622efd", "max_issues_repo_licenses": ["MIT"], "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_wrapper/ext3DLBPpy.cpp", "max_forks_repo_name": "johndpope/ext3DLBP", "max_forks_repo_head_hexsha": "0704ae6a9dda7e74f1f52b45acd71d1b6f622efd", "max_forks_repo_licenses": ["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.8426103647, "max_line_length": 121, "alphanum_fraction": 0.4988881751, "num_tokens": 4538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.05184546957979609, "lm_q1q2_score": 0.021510625488448887}}
{"text": "// File:  pointPicker.cpp\n// Date:  7/29/2016\n// Auth:  K. Loux\n// Desc:  Object for picking points from images.\n\n// Standard C++ headers\n#include <cstdlib>\n#include <cassert>\n#include <cmath>\n#include <limits>\n\n// wxWidgets headers\n#include <wx/clipbrd.h>\n\n// Eigen headers\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4018)// signed/unsigned mismatch\n#pragma warning(disable:4456)// declaration hides previous local declaration\n#pragma warning(disable:4714)// function marked as __forceinline not inlined\n#pragma warning(disable:4800)// forcing value to bool 'true' or 'false'\n#pragma warning(disable:4189)// local variable is initialized but not referenced\n#endif\n#include <Eigen/Dense>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n// Local headers\n#include \"pointPicker.h\"\n#include \"pointEntryDialog.h\"\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tPointPicker\n//\n// Description:\t\tConstructor for PointPicker class.\n//\n// Input Arguments:\n//\t\tNone\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nPointPicker::PointPicker()\n{\n\tclipMode = ClipboardMode::None;\n\tdataMode = DataExtractionMode::None;\n\tcurveIndex = 0;\n\tResetErrorString();\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tAddPoint\n//\n// Description:\t\tProcesses new point data.\n//\n// Input Arguments:\n//\t\trawX\t= const double&\n//\t\trawY\t= const double&\n//\t\txScale\t= const double&\n//\t\tyScale\t= const double&\n//\t\txOffset\t= const double&\n//\t\tyOffset\t= const double&\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::AddPoint(const double& rawX, const double& rawY,\n\tconst double& xScale, const double& yScale,\n\tconst double& xOffset, const double& yOffset)\n{\n\tconst double x(ScaleOrdinate(rawX, xScale, xOffset));\n\tconst double y(ScaleOrdinate(rawY, yScale, yOffset));\n\n\tHandleClipboardMode(x, y);\n\tHandleDataMode(x, y);\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tHandleClipboardMode\n//\n// Description:\t\tHandles necessary clipboard interaction.\n//\n// Input Arguments:\n//\t\tx\t= const double&\n//\t\ty\t= const double&\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::HandleClipboardMode(const double& x, const double& y) const\n{\n\tif (clipMode != ClipboardMode::None && wxTheClipboard->Open())\n\t{\n\t\tif (clipMode == ClipboardMode::X)\n\t\t\twxTheClipboard->SetData(new wxTextDataObject(wxString::Format(_T(\"%f\"), x)));\n\t\telse if (clipMode == ClipboardMode::Y)\n\t\t\twxTheClipboard->SetData(new wxTextDataObject(wxString::Format(_T(\"%f\"), y)));\n\t\telse if (clipMode == ClipboardMode::Both)\n\t\t\twxTheClipboard->SetData(new wxTextDataObject(wxString::Format(_T(\"%f\\t%f\"), x, y)));\n\t\telse\n\t\t\tassert(false);\n\n\t\twxTheClipboard->Close();\n\t}\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tHandleDataMode\n//\n// Description:\t\tHandles necessary data collection.\n//\n// Input Arguments:\n//\t\tx\t= const double&\n//\t\ty\t= const double&\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::HandleDataMode(const double& x, const double& y)\n{\n\tif (dataMode == DataExtractionMode::None)\n\t\treturn;\n\n\tif (dataMode == DataExtractionMode::Curve)\n\t{\n\t\twhile (curvePoints.size() <= curveIndex)\n\t\t\tcurvePoints.push_back(std::vector<Point>(0));\n\n\t\tlastPoint.x = x;\n\t\tlastPoint.y = y;\n\t\tcurvePoints[curveIndex].push_back(lastPoint);\n\t\treturn;\n\t}\n\n\tPointEntryDialog dialog(nullptr, wxID_ANY, _T(\"Coordinate Input\"));\n\tif (dialog.ShowModal() == wxID_CANCEL)\n\t\treturn;\n\n\tif (dataMode == DataExtractionMode::References)\n\t{\n\t\tlastPoint = dialog.GetPoint();\n\t\treferencePoints.push_back(ReferencePair(Point(x, y), lastPoint));\n\t\tUpdateTransformation();\n\t}\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tUpdateTransformation\n//\n// Description:\t\tUpdates the transformation matrix according to all stored\n//\t\t\t\t\treference points.\n//\n// Input Arguments:\n//\t\tNone\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::UpdateTransformation()\n{\n\tif (referencePoints.size() < 4)\n\t{\n\t\tResetErrorString();\n\t\treturn;\n\t}\n\telse\n\t\terrorString.clear();\n\n\t// Use the Direct Linear Transform approach to solve for the unknown\n\t// projective transforms.  Solve for the transforms assuming all different\n\t// combination of linear and logarithmic scales in order to determine\n\t// which combination provides the lowest error.\n\tdouble xLinYLinError;\n\tEigen::MatrixXd xLinYLinTransformation(ComputeTransformation(referencePoints, PlotScaling::Linear, xLinYLinError));\n\tif (referencePoints.size() == 4)// Not enough information to determine if scaling is logarithmic\n\t{\n\t\ttransformationMatrix = xLinYLinTransformation;\n\t\txIsLogarithmic = false;\n\t\tyIsLogarithmic = false;\n\t\treturn;\n\t}\n\n\tbool xLogIsOption(true);\n\tbool yLogIsOption(true);\n\n\tfor (unsigned int i = 0; i < referencePoints.size(); i++)\n\t{\n\t\tif (referencePoints[i].valueCoords.x <= 0.0)\n\t\t\txLogIsOption = false;\n\t\tif (referencePoints[i].valueCoords.y <= 0.0)\n\t\t\tyLogIsOption = false;\n\t}\n\n\tdouble xLinYLogError(std::numeric_limits<double>::max());\n\tdouble xLogYLinError(std::numeric_limits<double>::max());\n\tdouble xLogYLogError(std::numeric_limits<double>::max());\n\n\tEigen::MatrixXd xLinYLogTransformation;\n\tEigen::MatrixXd xLogYLinTransformation;\n\tEigen::MatrixXd xLogYLogTransformation;\n\n\tif (yLogIsOption)\n\t{\n\t\txLinYLogTransformation = ComputeTransformation(referencePoints, PlotScaling::SemiLogY, xLinYLogError);\n\t\tif (xLogIsOption)\n\t\t\txLogYLogTransformation = ComputeTransformation(referencePoints, PlotScaling::SemiLogX, xLogYLogError);\n\t}\n\n\tif (xLogIsOption)\n\t\txLogYLinTransformation = ComputeTransformation(referencePoints, PlotScaling::LogLog, xLogYLinError);\n\n\t// For linearly-scaled axes, the log-scaled transforms can have very similar error values to the\n\t// proper linear transforms but still give poor results.  When the correct scaling is logarithmic,\n\t// however, the linear transform will give an error that is orders of magnitude higher than that\n\t// given by the log transform.  So we assume linear unless the error is many times better when\n\t// using a log transform.\n\tconst double linLogErrorRatio(1.0);\n\n\tif (xLinYLinError < xLinYLogError * linLogErrorRatio &&\n\t\txLinYLinError < xLogYLinError * linLogErrorRatio &&\n\t\txLinYLinError < xLogYLogError * linLogErrorRatio)\n\t{\n\t\ttransformationMatrix = xLinYLinTransformation;\n\t\txIsLogarithmic = false;\n\t\tyIsLogarithmic = false;\n\t}\n\telse if (xLinYLogError < xLogYLinError &&\n\t\txLinYLogError < xLogYLogError)\n\t{\n\t\ttransformationMatrix = xLinYLogTransformation;\n\t\txIsLogarithmic = false;\n\t\tyIsLogarithmic = true;\n\t}\n\telse if (xLogYLinError < xLogYLogError)\n\t{\n\t\ttransformationMatrix = xLogYLinTransformation;\n\t\txIsLogarithmic = true;\n\t\tyIsLogarithmic = false;\n\t}\n\telse\n\t{\n\t\ttransformationMatrix = xLogYLogTransformation;\n\t\txIsLogarithmic = true;\n\t\tyIsLogarithmic = true;\n\t}\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tComputeTransformation\n//\n// Description:\t\tComputes the transformation for the specified correspondances.\n//\n// Input Arguments:\n//\t\tparis\t= const std::vector<ReferencePair>&\n//\t\tscaling\t= const PlotScaling&\n//\n// Output Arguments:\n//\t\terror\t= double&\n//\n// Return Value:\n//\t\tEigen::Matrix3d\n//\n//==========================================================================\nEigen::Matrix3d PointPicker::ComputeTransformation(\n\tconst std::vector<ReferencePair>& pairs, const PlotScaling& scaling, double& error)\n{\n\tEigen::Matrix<double, Eigen::Dynamic, 9> model(2 * pairs.size(), 9);\n\n\t// Set up columns that will all have the same value\n\tmodel.block(0,2,pairs.size(),1).setOnes();\n\tmodel.block(0,3,pairs.size(),3).setZero();\n\tmodel.block(pairs.size(),0,pairs.size(),3).setZero();\n\tmodel.block(pairs.size(),5,pairs.size(),1).setOnes();\n\n\tconst bool xLog(scaling == PlotScaling::LogLog || scaling == PlotScaling::SemiLogX);\n\tconst bool yLog(scaling == PlotScaling::LogLog || scaling == PlotScaling::SemiLogY);\n\n\tfor (unsigned int i = 0; i < pairs.size(); i++)\n\t{\n\t\tauto adjustValue([](const double& v, const bool& isLog)\n\t\t{\n\t\t\tif (isLog)\n\t\t\t\treturn log10(v);\n\t\t\treturn v;\n\t\t});\n\n\t\tconst double xVal(adjustValue(pairs[i].valueCoords.x, xLog));\n\t\tconst double yVal(adjustValue(pairs[i].valueCoords.y, yLog));\n\n\t\t// X-ordinate\n\t\tmodel(i,0) = pairs[i].imageCoords.x;\n\t\tmodel(i,1) = pairs[i].imageCoords.y;\n\n\t\tmodel(i,6) = -xVal * pairs[i].imageCoords.x;\n\t\tmodel(i,7) = -xVal * pairs[i].imageCoords.y;\n\t\tmodel(i,8) = -xVal;\n\n\t\t// Y-ordinate\n\t\tmodel(i + pairs.size(),3) = pairs[i].imageCoords.x;\n\t\tmodel(i + pairs.size(),4) = pairs[i].imageCoords.y;\n\n\t\tmodel(i + pairs.size(),6) = -yVal * pairs[i].imageCoords.x;\n\t\tmodel(i + pairs.size(),7) = -yVal * pairs[i].imageCoords.y;\n\t\tmodel(i + pairs.size(),8) = -yVal;\n\t}\n\n\tEigen::JacobiSVD<Eigen::Matrix<double, Eigen::Dynamic, 9>> svd(model, Eigen::ComputeFullV);\n\tEigen::Matrix<double, 9, 1> nullspace(svd.matrixV().col(8));\n\tEigen::Matrix3d transform;\n\ttransform.row(0) = nullspace.head<3>();\n\ttransform.row(1) = nullspace.segment<3>(3);\n\ttransform.row(2) = nullspace.tail<3>();\n\n\t// This doesn't work for log-scaled axes\n\t/*Eigen::VectorXd errorVector(model * nullspace);\n\terror = errorVector.dot(errorVector);*/\n\n\terror = 0.0;\n\tfor (const auto& p : pairs)\n\t{\n\t\tEigen::Vector3d imagePoint(p.imageCoords.x, p.imageCoords.y, 1.0);\n\t\tEigen::Vector3d plotPoint(transform * imagePoint);\n\t\tPoint result(plotPoint(0) / plotPoint(2), plotPoint(1) / plotPoint(2));\n\t\tif (xLog)\n\t\t\tresult.x = pow(10, result.x);\n\t\tif (yLog)\n\t\t\tresult.y = pow(10, result.y);\n\n\t\terror += (result.x - p.valueCoords.x) * (result.x - p.valueCoords.x) + (result.y - p.valueCoords.y) * (result.y - p.valueCoords.y);\n\t}\n\n\treturn transform;\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tGetReferences\n//\n// Description:\t\tReturns list of references.\n//\n// Input Arguments:\n//\t\tNone\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tstd::vector<PointPicker::Point>\n//\n//==========================================================================\nstd::vector<PointPicker::Point> PointPicker::GetReferences() const\n{\n\tstd::vector<Point> refs(referencePoints.size());\n\tfor (unsigned int i = 0; i < refs.size(); ++i)\n\t\trefs[i] = referencePoints[i].valueCoords;\n\n\treturn refs;\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tRemoveReference\n//\n// Description:\t\tRemoves the specified element from the list of references.\n//\n// Input Arguments:\n//\t\ti\t= const unsigned int&\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::RemoveReference(const unsigned int& i)\n{\n\treferencePoints.erase(referencePoints.begin() + i);\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tScaleOrdinate\n//\n// Description:\t\tScales the value according to the specified length and offset.\n//\n// Input Arguments:\n//\t\tvalue\t= const double&\n//\t\tscale\t= const double&\n//\t\toffset\t= const double&\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tdouble\n//\n//==========================================================================\ndouble PointPicker::ScaleOrdinate(const double& value, const double& scale,\n\tconst double& offset)\n{\n\treturn value * scale + offset;\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tResetReferences\n//\n// Description:\t\tResets the stored reference data.\n//\n// Input Arguments:\n//\t\tNone\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::ResetReferences()\n{\n\treferencePoints.clear();\n\tResetErrorString();\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tResetCurveData\n//\n// Description:\t\tResets the stored curve data.\n//\n// Input Arguments:\n//\t\tcurve\t= const unsigned int&\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::ResetCurveData(const unsigned int& curve)\n{\n\tcurvePoints.erase(curvePoints.begin() + curve);\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tReset\n//\n// Description:\t\tResets all stored data.\n//\n// Input Arguments:\n//\t\tNone\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::Reset()\n{\n\tResetReferences();\n\n\tcurvePoints.clear();\n\tcurveIndex = 0;\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tGetCurveData\n//\n// Description:\t\tReturns processed curve data.\n//\n// Input Arguments:\n//\t\tNone\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tstd::vector<std::vector<PointPicker::Point>>\n//\n//==========================================================================\nstd::vector<std::vector<PointPicker::Point>> PointPicker::GetCurveData() const\n{\n\tif (!errorString.empty())\n\t\treturn std::vector<std::vector<Point>>(0);\n\n\tstd::vector<std::vector<Point>> data(curvePoints);\n\tfor (unsigned int i = 0; i < curvePoints.size(); i++)\n\t{\n\t\tfor (unsigned int j = 0; j < curvePoints[i].size(); j++)\n\t\t\tdata[i][j] = ScalePoint(curvePoints[i][j]);\n\t}\n\n\treturn data;\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tScalePoint\n//\n// Description:\t\tConverts the specified point from image to plot coordinates.\n//\n// Input Arguments:\n//\t\timagePointIn\t= const Point&\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tPointPicker::Point\n//\n//==========================================================================\nPointPicker::Point PointPicker::ScalePoint(const Point& imagePointIn) const\n{\n\tEigen::Vector3d imagePoint(imagePointIn.x, imagePointIn.y, 1.0);\n\tEigen::Vector3d plotPoint(transformationMatrix * imagePoint);\n\n\tPoint p(plotPoint(0) / plotPoint(2), plotPoint(1) / plotPoint(2));\n\n\tif (xIsLogarithmic)\n\t\tp.x = pow(10.0, p.x);\n\n\tif (yIsLogarithmic)\n\t\tp.y = pow(10.0, p.y);\n\n\treturn p;\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tScaleSinglePoint\n//\n// Description:\t\tProcesses data for single point.\n//\n// Input Arguments:\n//\t\trawX\t= const double&\n//\t\trawY\t= const double&\n//\t\txScale\t= const double&\n//\t\tyScale\t= const double&\n//\t\txOffset\t= const double&\n//\t\tyOffset\t= const double&\n//\n// Output Arguments:\n//\t\tx\t\t= double&\n//\t\ty\t\t= double&\n//\n// Return Value:\n//\t\tPoint\n//\n//==========================================================================\nPointPicker::Point PointPicker::ScaleSinglePoint(const double& rawX, const double& rawY,\n\tconst double& xScale, const double& yScale,\n\tconst double& xOffset, const double& yOffset, double& x, double& y) const\n{\n\tx = ScaleOrdinate(rawX, xScale, xOffset);\n\ty = ScaleOrdinate(rawY, yScale, yOffset);\n\n\tif (!errorString.empty())\n\t\treturn Point(0.0, 0.0);\n\n\treturn ScalePoint(Point(x, y));\n}\n\n//==========================================================================\n// Class:\t\t\tPointPicker\n// Function:\t\tResetErrorString\n//\n// Description:\t\tResets the error string.\n//\n// Input Arguments:\n//\t\tNone\n//\n// Output Arguments:\n//\t\tNone\n//\n// Return Value:\n//\t\tNone\n//\n//==========================================================================\nvoid PointPicker::ResetErrorString() const\n{\n\terrorString = _T(\"Not enough reference points\");\n}\n", "meta": {"hexsha": "79ba1167d30a45c3cc7da6f74e37a8b8d584f270", "size": 16384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pointPicker.cpp", "max_stars_repo_name": "KerryL/PointPicker", "max_stars_repo_head_hexsha": "7de66782f1cd0bfed02873ef7bb860604fec22d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pointPicker.cpp", "max_issues_repo_name": "KerryL/PointPicker", "max_issues_repo_head_hexsha": "7de66782f1cd0bfed02873ef7bb860604fec22d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-02T00:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-02T00:43:25.000Z", "max_forks_repo_path": "src/pointPicker.cpp", "max_forks_repo_name": "KerryL/PointPicker", "max_forks_repo_head_hexsha": "7de66782f1cd0bfed02873ef7bb860604fec22d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-08T08:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-08T08:22:05.000Z", "avg_line_length": 26.5542949757, "max_line_length": 133, "alphanum_fraction": 0.5928955078, "num_tokens": 3944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790695, "lm_q2_score": 0.044680866615371656, "lm_q1q2_score": 0.021468203725388633}}
{"text": "#include \"drake/solvers/scs_solver.h\"\n\n#include <Eigen/Sparse>\n#include <fmt/format.h>\n\n// clang-format off\n// scs.h should be included before linsys/amatrix.h, since amatrix.h uses types\n// scs_float, scs_int, etc, defined in scs.h\n#include <scs.h>\n#include <cones.h>\n#include <linalg.h>\n#include <util.h>\n#include \"linsys/amatrix.h\"\n// clang-format on\n\n#include \"drake/common/text_logging.h\"\n#include \"drake/math/eigen_sparse_triplet.h\"\n#include \"drake/math/quadratic_form.h\"\n#include \"drake/solvers/mathematical_program.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace {\nvoid ParseLinearCost(const MathematicalProgram& prog, std::vector<double>* c,\n                     double* constant) {\n  for (const auto& linear_cost : prog.linear_costs()) {\n    // Each linear cost is in the form of aᵀx + b\n    const auto& a = linear_cost.evaluator()->a();\n    const VectorXDecisionVariable& x = linear_cost.variables();\n    for (int i = 0; i < a.rows(); ++i) {\n      (*c)[prog.FindDecisionVariableIndex(x(i))] += a(i);\n    }\n    (*constant) += linear_cost.evaluator()->b();\n  }\n}\n\n// Add a rotated Lorentz cone constraint that A_cone * x + b_cone is in the\n// rotated Lorentz cone.\n// @param A_cone_triplets The triplets of non-zero entries in A_cone.\n// @param b_cone A_cone * x + b_cone is in the rotated Lorentz cone.\n// @param x_indices The index of the variable in SCS.\n// @param A_triplets[in/out] The non-zero entry triplet in A before and after\n// adding the Lorentz cone.\n// @param b[in/out] The right-hand side vector b before and after adding the\n// Lorentz cone.\n// @param A_row_count[in/out] The number of rows in A before and after adding\n// the Lorentz cone.\n// @param lorentz_cone_length[in/out] The length of each Lorentz cone before\n// and after adding the Lorentz cone constraint.\nvoid ParseRotatedLorentzConeConstraint(\n    const std::vector<Eigen::Triplet<double>>& A_cone_triplets,\n    const Eigen::Ref<const Eigen::VectorXd>& b_cone,\n    const std::vector<int>& x_indices,\n    std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,\n    int* A_row_count, std::vector<int>* lorentz_cone_length) {\n  // Our RotatedLorentzConeConstraint encodes that Ax + b is in the rotated\n  // Lorentz cone, namely\n  //  (a₀ᵀx + b₀) (a₁ᵀx + b₁) ≥ (a₂ᵀx + b₂)² + ... + (aₙ₋₁ᵀx + bₙ₋₁)²\n  //  (a₀ᵀx + b₀) ≥ 0\n  //  (a₁ᵀx + b₁) ≥ 0\n  // , where aᵢᵀ is the i'th row of A, bᵢ is the i'th row of b. Equivalently the\n  // vector\n  // [ 0.5(a₀ + a₁)ᵀx + 0.5(b₀ + b₁) ]\n  // [ 0.5(a₀ - a₁)ᵀx + 0.5(b₀ - b₁) ]\n  // [           a₂ᵀx +           b₂ ]\n  //             ...\n  // [         aₙ₋₁ᵀx +         bₙ₋₁ ]\n  // is in the Lorentz cone. We convert this to the SCS form, that\n  //  Cx + s = d\n  //  s in Lorentz cone,\n  // where C = [ -0.5(a₀ + a₁)ᵀ ]   d = [ 0.5(b₀ + b₁) ]\n  //           [ -0.5(a₀ - a₁)ᵀ ]       [ 0.5(b₀ - b₁) ]\n  //           [           -a₂ᵀ ]       [           b₂ ]\n  //                 ...                      ...\n  //           [         -aₙ₋₁ᵀ ]       [          bₙ₋₁]\n  for (const auto& Ai_triplet : A_cone_triplets) {\n    const int x_index = x_indices[Ai_triplet.col()];\n    if (Ai_triplet.row() == 0) {\n      A_triplets->emplace_back(*A_row_count, x_index,\n                               -0.5 * Ai_triplet.value());\n      A_triplets->emplace_back(*A_row_count + 1, x_index,\n                               -0.5 * Ai_triplet.value());\n    } else if (Ai_triplet.row() == 1) {\n      A_triplets->emplace_back(*A_row_count, x_index,\n                               -0.5 * Ai_triplet.value());\n      A_triplets->emplace_back(*A_row_count + 1, x_index,\n                               0.5 * Ai_triplet.value());\n    } else {\n      A_triplets->emplace_back(*A_row_count + Ai_triplet.row(), x_index,\n                               -Ai_triplet.value());\n    }\n  }\n  b->push_back(0.5 * (b_cone(0) + b_cone(1)));\n  b->push_back(0.5 * (b_cone(0) - b_cone(1)));\n  for (int i = 2; i < b_cone.rows(); ++i) {\n    b->push_back(b_cone(i));\n  }\n  *A_row_count += b_cone.rows();\n  lorentz_cone_length->push_back(b_cone.rows());\n}\n\nvoid ParseQuadraticCost(const MathematicalProgram& prog, std::vector<double>* c,\n                        std::vector<Eigen::Triplet<double>>* A_triplets,\n                        std::vector<double>* b, int* A_row_count,\n                        std::vector<int>* lorentz_cone_length, int* num_x) {\n  // A QuadraticCost encodes cost of the form\n  //   0.5 zᵀQz + pᵀz + r\n  // Since SCS only supports linear cost, we introduce a new slack variable y\n  // as the upper bound of the cost, with the rotated Lorentz cone constraint\n  // 2(y - r - pᵀz) ≥ zᵀQz.\n  // We only need to minimize y then.\n  for (const auto& cost : prog.quadratic_costs()) {\n    // We will convert the expression 2(y - r - pᵀz) ≥ zᵀQz, to the constraint\n    // that the vector A_cone * x + b_cone is in the rotated Lorentz cone, where\n    // x = [z; y], and A_cone * x + b_cone is\n    // [y - r - pᵀz]\n    // [          2]\n    // [        C*z]\n    // where C satisfies Cᵀ*C = Q\n    const VectorXDecisionVariable& z = cost.variables();\n    const int y_index = z.rows();\n    // Ai_triplets are the non-zero entries in the matrix A_cone.\n    std::vector<Eigen::Triplet<double>> Ai_triplets;\n    Ai_triplets.emplace_back(0, y_index, 1);\n    for (int i = 0; i < z.rows(); ++i) {\n      Ai_triplets.emplace_back(0, i, -cost.evaluator()->b()(i));\n    }\n    // Decompose Q to Cᵀ*C\n    const Eigen::MatrixXd& Q = cost.evaluator()->Q();\n    const Eigen::MatrixXd C =\n        math::DecomposePSDmatrixIntoXtransposeTimesX(Q, 1E-10);\n    for (int i = 0; i < C.rows(); ++i) {\n      for (int j = 0; j < C.cols(); ++j) {\n        if (C(i, j) != 0) {\n          Ai_triplets.emplace_back(2 + i, j, C(i, j));\n        }\n      }\n    }\n    // append the variable y to the end of x\n    (*num_x)++;\n    std::vector<int> Ai_var_indices = prog.FindDecisionVariableIndices(z);\n    Ai_var_indices.push_back(*num_x - 1);\n    // Set b_cone\n    Eigen::VectorXd b_cone = Eigen::VectorXd::Zero(2 + C.rows());\n    b_cone(0) = -cost.evaluator()->c();\n    b_cone(1) = 2;\n    // Add the rotated Lorentz cone constraint\n    ParseRotatedLorentzConeConstraint(Ai_triplets, b_cone, Ai_var_indices,\n                                      A_triplets, b, A_row_count,\n                                      lorentz_cone_length);\n    // Add the cost y.\n    c->push_back(1);\n  }\n}\n\nvoid ParseLinearConstraint(const MathematicalProgram& prog,\n                           std::vector<Eigen::Triplet<double>>* A_triplets,\n                           std::vector<double>* b, int* A_row_count,\n                           ScsCone* cone) {\n  // The linear constraint lb ≤ aᵀx ≤ ub is converted to\n  //  aᵀx + s1 = ub,\n  // -aᵀx + s2 = lb\n  // s1, s2 in the positive cone.\n  // The special cases are when ub = ∞ or lb = -∞.\n  // When ub = ∞, then we only add the constraint\n  // -aᵀx + s = lb, s in the positive cone.\n  // When lb = -∞, then we only add the constraint\n  // aᵀx + s = ub, s in the positive cone.\n  int num_linear_constraint_rows = 0;\n  for (const auto& linear_constraint : prog.linear_constraints()) {\n    const Eigen::VectorXd& ub = linear_constraint.evaluator()->upper_bound();\n    const Eigen::VectorXd& lb = linear_constraint.evaluator()->lower_bound();\n    const VectorXDecisionVariable& x = linear_constraint.variables();\n    const Eigen::MatrixXd& Ai = linear_constraint.evaluator()->A();\n    for (int i = 0; i < linear_constraint.evaluator()->num_constraints();\n         ++i) {\n      const bool is_ub_finite{!std::isinf(ub(i))};\n      const bool is_lb_finite{!std::isinf(lb(i))};\n      if (is_ub_finite || is_lb_finite) {\n        // If lb != -∞, then the constraint -aᵀx + s = lb will be added to the\n        // matrix A, in the row lower_bound_row_index.\n        const int lower_bound_row_index =\n            *A_row_count + num_linear_constraint_rows;\n        // If ub != ∞, then the constraint aᵀx + s = ub will be added to the\n        // matrix A, in the row upper_bound_row_index.\n        const int upper_bound_row_index =\n            *A_row_count + num_linear_constraint_rows + (is_lb_finite ? 1 : 0);\n        for (int j = 0; j < x.rows(); ++j) {\n          if (Ai(i, j) != 0) {\n            const int xj_index = prog.FindDecisionVariableIndex(x(j));\n            if (is_ub_finite) {\n              A_triplets->emplace_back(upper_bound_row_index, xj_index,\n                                       Ai(i, j));\n            }\n            if (is_lb_finite) {\n              A_triplets->emplace_back(lower_bound_row_index, xj_index,\n                                       -Ai(i, j));\n            }\n          }\n        }\n        if (is_lb_finite) {\n          b->push_back(-lb(i));\n          ++num_linear_constraint_rows;\n        }\n        if (is_ub_finite) {\n          b->push_back(ub(i));\n          ++num_linear_constraint_rows;\n        }\n      }\n    }\n  }\n  *A_row_count += num_linear_constraint_rows;\n  cone->l += num_linear_constraint_rows;\n}\n\nvoid ParseLinearEqualityConstraint(\n    const MathematicalProgram& prog,\n    std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,\n    int* A_row_count, ScsCone* cone) {\n  int num_linear_equality_constraints_rows = 0;\n  // The linear equality constraint A x = b is converted to\n  // A x + s = b. s in zero cone.\n  for (const auto& linear_equality_constraint :\n       prog.linear_equality_constraints()) {\n    const Eigen::SparseMatrix<double> Ai =\n        linear_equality_constraint.evaluator()->GetSparseMatrix();\n    const std::vector<Eigen::Triplet<double>> Ai_triplets =\n        math::SparseMatrixToTriplets(Ai);\n    A_triplets->reserve(A_triplets->size() + Ai_triplets.size());\n    const solvers::VectorXDecisionVariable& x =\n        linear_equality_constraint.variables();\n    // x_indices[i] is the index of x(i)\n    const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);\n    for (const auto& Ai_triplet : Ai_triplets) {\n      A_triplets->emplace_back(Ai_triplet.row() + *A_row_count,\n                               x_indices[Ai_triplet.col()], Ai_triplet.value());\n    }\n    const int num_Ai_rows =\n        linear_equality_constraint.evaluator()->num_constraints();\n    b->reserve(b->size() + num_Ai_rows);\n    for (int i = 0; i < num_Ai_rows; ++i) {\n      b->push_back(linear_equality_constraint.evaluator()->lower_bound()(i));\n    }\n    *A_row_count += num_Ai_rows;\n    num_linear_equality_constraints_rows += num_Ai_rows;\n  }\n  cone->f += num_linear_equality_constraints_rows;\n}\n\nvoid ParseBoundingBoxConstraint(const MathematicalProgram& prog,\n                                std::vector<Eigen::Triplet<double>>* A_triplets,\n                                std::vector<double>* b, int* A_row_count,\n                                ScsCone* cone) {\n  // A bounding box constraint lb ≤ x ≤ ub is converted to the SCS form as\n  // x + s1 = ub, -x + s2 = -lb, s1, s2 in the positive cone.\n  // TODO(hongkai.dai) : handle the special case l = u, such that we can convert\n  // it to x + s = l, s in zero cone.\n  int num_bounding_box_constraint_rows = 0;\n  for (const auto& bounding_box_constraint : prog.bounding_box_constraints()) {\n    int num_scs_new_constraint = 0;\n    const VectorXDecisionVariable& xi = bounding_box_constraint.variables();\n    const int num_xi_rows = xi.rows();\n    A_triplets->reserve(A_triplets->size() + 2 * num_xi_rows);\n    b->reserve(b->size() + 2 * num_xi_rows);\n    for (int i = 0; i < num_xi_rows; ++i) {\n      if (!std::isinf(bounding_box_constraint.evaluator()->upper_bound()(i))) {\n        // if ub != ∞, then add the constraint x + s1 = ub, s1 in the positive\n        // cone.\n        A_triplets->emplace_back(num_scs_new_constraint + *A_row_count,\n                                 prog.FindDecisionVariableIndex(xi(i)), 1);\n        b->push_back(bounding_box_constraint.evaluator()->upper_bound()(i));\n        ++num_scs_new_constraint;\n      }\n      if (!std::isinf(bounding_box_constraint.evaluator()->lower_bound()(i))) {\n        // if lb != -∞, then add the constraint -x + s2 = -lb, s2 in the\n        // positive cone.\n        A_triplets->emplace_back(num_scs_new_constraint + *A_row_count,\n                                 prog.FindDecisionVariableIndex(xi(i)), -1);\n        b->push_back(-bounding_box_constraint.evaluator()->lower_bound()(i));\n        ++num_scs_new_constraint;\n      }\n    }\n    *A_row_count += num_scs_new_constraint;\n    num_bounding_box_constraint_rows += num_scs_new_constraint;\n  }\n  cone->l += num_bounding_box_constraint_rows;\n}\n\nvoid ParseSecondOrderConeConstraints(\n    const MathematicalProgram& prog,\n    std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,\n    int* A_row_count, std::vector<int>* lorentz_cone_length) {\n  // Our LorentzConeConstraint encodes that Ax + b is in Lorentz cone. We\n  // convert this to SCS form, as -Ax + s = b, s in Lorentz cone.\n  for (const auto& lorentz_cone_constraint : prog.lorentz_cone_constraints()) {\n    // x_indices[i] is the index of x(i)\n    const VectorXDecisionVariable& x = lorentz_cone_constraint.variables();\n    const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);\n    const Eigen::SparseMatrix<double> Ai =\n        lorentz_cone_constraint.evaluator()->A();\n    const std::vector<Eigen::Triplet<double>> Ai_triplets =\n        math::SparseMatrixToTriplets(Ai);\n    for (const auto& Ai_triplet : Ai_triplets) {\n      A_triplets->emplace_back(Ai_triplet.row() + *A_row_count,\n                               x_indices[Ai_triplet.col()],\n                               -Ai_triplet.value());\n    }\n    const int num_Ai_rows = lorentz_cone_constraint.evaluator()->A().rows();\n    for (int i = 0; i < num_Ai_rows; ++i) {\n      b->push_back(lorentz_cone_constraint.evaluator()->b()(i));\n    }\n    lorentz_cone_length->push_back(num_Ai_rows);\n    *A_row_count += num_Ai_rows;\n  }\n\n  for (const auto& rotated_lorentz_cone :\n       prog.rotated_lorentz_cone_constraints()) {\n    const VectorXDecisionVariable& x = rotated_lorentz_cone.variables();\n    const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);\n    const Eigen::SparseMatrix<double> Ai =\n        rotated_lorentz_cone.evaluator()->A();\n    const Eigen::VectorXd& bi = rotated_lorentz_cone.evaluator()->b();\n    const std::vector<Eigen::Triplet<double>> Ai_triplets =\n        math::SparseMatrixToTriplets(Ai);\n    ParseRotatedLorentzConeConstraint(Ai_triplets, bi, x_indices, A_triplets, b,\n                                      A_row_count, lorentz_cone_length);\n  }\n}\n\n// This function parses both PositiveSemidefinite and\n// LinearMatrixInequalityConstraint.\nvoid ParsePositiveSemidefiniteConstraint(\n    const MathematicalProgram& prog,\n    std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,\n    int* A_row_count, ScsCone* cone) {\n  std::vector<int> psd_cone_length;\n  const double sqrt2 = std::sqrt(2);\n  for (const auto& psd_constraint : prog.positive_semidefinite_constraints()) {\n    // PositiveSemidefiniteConstraint encodes the matrix X being psd.\n    // We convert it to SCS form\n    // A * x + s = 0\n    // s in positive semidefinite cone.\n    // where A is a diagonal matrix, with its diagonal entries being the stacked\n    // column vector of the lower triangular part of matrix\n    // ⎡ -1 -√2 -√2 ... -√2⎤\n    // ⎢-√2  -1 -√2 ... -√2⎥\n    // ⎢-√2 -√2  -1 ... -√2⎥\n    // ⎢    ...            ⎥\n    // ⎣-√2 -√2 -√2 ...  -1⎦\n    // The √2 scaling factor in the off-diagonal entries are required by SCS,\n    // as it uses only the lower triangular part of the symmetric matrix, as\n    // explained in https://github.com/cvxgrp/scs\n    // x is the stacked column vector of the lower triangular part of the\n    // symmetric matrix X.\n    const int X_rows = psd_constraint.evaluator()->matrix_rows();\n    int x_index_count = 0;\n    const VectorXDecisionVariable& flat_X = psd_constraint.variables();\n    DRAKE_DEMAND(flat_X.rows() == X_rows * X_rows);\n    b->reserve(b->size() + X_rows * (X_rows + 1) / 2);\n    for (int j = 0; j < X_rows; ++j) {\n      A_triplets->emplace_back(\n          *A_row_count + x_index_count,\n          prog.FindDecisionVariableIndex(flat_X(j * X_rows + j)), -1);\n      b->push_back(0);\n      ++x_index_count;\n      for (int i = j + 1; i < X_rows; ++i) {\n        A_triplets->emplace_back(\n            *A_row_count + x_index_count,\n            prog.FindDecisionVariableIndex(flat_X(j * X_rows + i)), -sqrt2);\n        b->push_back(0);\n        ++x_index_count;\n      }\n    }\n    (*A_row_count) += X_rows * (X_rows + 1) / 2;\n    psd_cone_length.push_back(X_rows);\n  }\n  for (const auto& lmi_constraint :\n       prog.linear_matrix_inequality_constraints()) {\n    // LinearMatrixInequalityConstraint encodes\n    // F₀ + x₁*F₁ + x₂*F₂ + ... + xₙFₙ is p.s.d\n    // We convert this to SCS form as\n    // A_cone * x + s = b_cone\n    // s in SCS positive semidefinite cone.\n    // where\n    //              ⎡  F₁(0, 0)   F₂(0, 0) ...   Fₙ(0, 0)⎤\n    //              ⎢√2F₁(1, 0) √2F₂(1, 0) ... √2Fₙ(1, 0)⎥\n    //   A_cone = - ⎢√2F₁(2, 0) √2F₂(2, 0) ... √2Fₙ(2, 0)⎥,\n    //              ⎢            ...                     ⎥\n    //              ⎣  F₁(m, m)   F₂(m, m) ...   Fₙ(m, m)⎦\n    //\n    //              ⎡  F₀(0, 0)⎤\n    //              ⎢√2F₀(1, 0)⎥\n    //   b_cone =   ⎢√2F₀(2, 0)⎥,\n    //              ⎢   ...    ⎥\n    //              ⎣  F₀(m, m)⎦\n    // and\n    //   x = [x₁; x₂; ... ; xₙ].\n    // As explained above, the off-diagonal rows are scaled by √2. Please refer\n    // to https://github.com/cvxgrp/scs about the scaling factor √2.\n    const std::vector<Eigen::MatrixXd>& F = lmi_constraint.evaluator()->F();\n    const VectorXDecisionVariable& x = lmi_constraint.variables();\n    const int F_rows = lmi_constraint.evaluator()->matrix_rows();\n    const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);\n    int A_cone_row_count = 0;\n    b->reserve(b->size() + F_rows * (F_rows + 1) / 2);\n    for (int j = 0; j < F_rows; ++j) {\n      for (int i = j; i < F_rows; ++i) {\n        const double scale_factor = i == j ? 1 : sqrt2;\n        for (int k = 1; k < static_cast<int>(F.size()); ++k) {\n          A_triplets->emplace_back(*A_row_count + A_cone_row_count,\n                                   x_indices[k - 1],\n                                   -scale_factor * F[k](i, j));\n        }\n        b->push_back(scale_factor * F[0](i, j));\n        ++A_cone_row_count;\n      }\n    }\n    *A_row_count += F_rows * (F_rows + 1) / 2;\n    psd_cone_length.push_back(F_rows);\n  }\n  cone->ssize = psd_cone_length.size();\n  cone->s = static_cast<scs_int*>(scs_calloc(cone->ssize, sizeof(scs_int)));\n  for (int i = 0; i < cone->ssize; ++i) {\n    cone->s[i] = psd_cone_length[i];\n  }\n}\n\nvoid ParseExponentialConeConstraint(\n    const MathematicalProgram& prog,\n    std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,\n    int* A_row_count, ScsCone* cone) {\n  cone->ep = static_cast<int>(prog.exponential_cone_constraints().size());\n  for (const auto& binding : prog.exponential_cone_constraints()) {\n    // drake::solvers::ExponentialConstraint enforces that z = A * x + b is in\n    // the exponential cone (z₀ ≥ z₁*exp(z₂ / z₁)). This is different from the\n    // exponential cone used in SCS. In SCS, a vector s is in the exponential\n    // cone, if s₂≥ s₁*exp(s₀ / s₁). To transform drake's Exponential cone to\n    // SCS's exponential cone, we use\n    // -[A.row(2); A.row(1); A.row(0)] * x + s = [b(2); b(1); b(0)], and s is\n    // in SCS's exponential cone, where A = binding.evaluator()->A(), b =\n    // binding.evaluator()->b().\n    const int num_bound_variables = binding.variables().rows();\n    for (int i = 0; i < num_bound_variables; ++i) {\n      A_triplets->reserve(A_triplets->size() +\n                          binding.evaluator()->A().nonZeros());\n      const int decision_variable_index =\n          prog.FindDecisionVariableIndex(binding.variables()(i));\n      for (Eigen::SparseMatrix<double>::InnerIterator it(\n               binding.evaluator()->A(), i);\n           it; ++it) {\n        // 2 - it.row() is used for reverse the row order, as mentioned in the\n        // function documentation above.\n        A_triplets->emplace_back(*A_row_count + 2 - it.row(),\n                                 decision_variable_index, -it.value());\n      }\n    }\n    // The exponential cone constraint is on a 3 x 1 vector, hence for each\n    // ExponentialConeConstraint, we append 3 rows to A and b.\n    b->reserve(b->size() + 3);\n    for (int i = 0; i < 3; ++i) {\n      b->push_back(binding.evaluator()->b()(2 - i));\n    }\n    *A_row_count += 3;\n  }\n}\n\nstd::string Scs_return_info(scs_int scs_status) {\n  switch (scs_status) {\n    case SCS_INFEASIBLE_INACCURATE:\n      return \"SCS infeasible inaccurate\";\n    case SCS_UNBOUNDED_INACCURATE:\n      return \"SCS unbounded inaccurate\";\n    case SCS_SIGINT:\n      return \"SCS sigint\";\n    case SCS_FAILED:\n      return \"SCS failed\";\n    case SCS_INDETERMINATE:\n      return \"SCS indeterminate\";\n    case SCS_INFEASIBLE:\n      return \"SCS primal infeasible, dual unbounded\";\n    case SCS_UNBOUNDED:\n      return \"SCS primal unbounded, dual infeasible\";\n    case SCS_UNFINISHED:\n      return \"SCS unfinished\";\n    case SCS_SOLVED:\n      return \"SCS solved\";\n    case SCS_SOLVED_INACCURATE:\n      return \"SCS solved inaccurate\";\n    default:\n      throw std::runtime_error(\"Unknown scs status.\");\n  }\n}\n\nvoid SetScsProblemData(int A_row_count, int num_vars,\n                       const Eigen::SparseMatrix<double>& A,\n                       const std::vector<double>& b,\n                       const std::vector<double>& c,\n                       ScsData* scs_problem_data) {\n  scs_problem_data->m = A_row_count;\n  scs_problem_data->n = num_vars;\n\n  scs_problem_data->A = static_cast<ScsMatrix*>(malloc(sizeof(ScsMatrix)));\n  scs_problem_data->A->x =\n      static_cast<scs_float*>(scs_calloc(A.nonZeros(), sizeof(scs_float)));\n\n  scs_problem_data->A->i =\n      static_cast<scs_int*>(scs_calloc(A.nonZeros(), sizeof(scs_int)));\n\n  scs_problem_data->A->p = static_cast<scs_int*>(\n      scs_calloc(scs_problem_data->n + 1, sizeof(scs_int)));\n\n  // TODO(hongkai.dai): should I use memcpy for the assignment in the for loop?\n  for (int i = 0; i < A.nonZeros(); ++i) {\n    scs_problem_data->A->x[i] = *(A.valuePtr() + i);\n    scs_problem_data->A->i[i] = *(A.innerIndexPtr() + i);\n  }\n  for (int i = 0; i < scs_problem_data->n + 1; ++i) {\n    scs_problem_data->A->p[i] = *(A.outerIndexPtr() + i);\n  }\n  scs_problem_data->A->m = scs_problem_data->m;\n  scs_problem_data->A->n = scs_problem_data->n;\n\n  scs_problem_data->b =\n      static_cast<scs_float*>(scs_calloc(b.size(), sizeof(scs_float)));\n\n  for (int i = 0; i < static_cast<int>(b.size()); ++i) {\n    scs_problem_data->b[i] = b[i];\n  }\n  scs_problem_data->c =\n      static_cast<scs_float*>(scs_calloc(num_vars, sizeof(scs_float)));\n  for (int i = 0; i < num_vars; ++i) {\n    scs_problem_data->c[i] = c[i];\n  }\n\n  // Set the parameters to default values.\n  scs_problem_data->stgs =\n      static_cast<ScsSettings*>(scs_calloc(1, sizeof(ScsSettings)));\n  scs_set_default_settings(scs_problem_data);\n}\n}  // namespace\n\nbool ScsSolver::is_available() { return true; }\n\nnamespace {\nvoid SetScsSettings(std::unordered_map<std::string, int>* solver_options_int,\n                    SCS_SETTINGS* scs_settings) {\n  auto it = solver_options_int->find(\"max_iters\");\n  if (it != solver_options_int->end()) {\n    scs_settings->max_iters = it->second;\n    solver_options_int->erase(it);\n  }\n  it = solver_options_int->find(\"normalize\");\n  if (it != solver_options_int->end()) {\n    scs_settings->normalize = it->second;\n    solver_options_int->erase(it);\n  }\n  it = solver_options_int->find(\"verbose\");\n  if (it != solver_options_int->end()) {\n    scs_settings->verbose = it->second;\n    solver_options_int->erase(it);\n  }\n  it = solver_options_int->find(\"warm_start\");\n  if (it != solver_options_int->end()) {\n    scs_settings->warm_start = it->second;\n    solver_options_int->erase(it);\n  }\n  it = solver_options_int->find(\"acceleration_lookback\");\n  if (it != solver_options_int->end()) {\n    scs_settings->acceleration_lookback = it->second;\n    solver_options_int->erase(it);\n  }\n  if (!solver_options_int->empty()) {\n    throw std::invalid_argument(\"Unsupported SCS solver options.\");\n  }\n}\n\nvoid SetScsSettings(\n    std::unordered_map<std::string, double>* solver_options_double,\n    SCS_SETTINGS* scs_settings) {\n  auto it = solver_options_double->find(\"scale\");\n  if (it != solver_options_double->end()) {\n    scs_settings->scale = it->second;\n    solver_options_double->erase(it);\n  }\n  it = solver_options_double->find(\"rho_x\");\n  if (it != solver_options_double->end()) {\n    scs_settings->rho_x = it->second;\n    solver_options_double->erase(it);\n  }\n  it = solver_options_double->find(\"eps\");\n  if (it != solver_options_double->end()) {\n    scs_settings->eps = it->second;\n    solver_options_double->erase(it);\n  }\n  it = solver_options_double->find(\"alpha\");\n  if (it != solver_options_double->end()) {\n    scs_settings->alpha = it->second;\n    solver_options_double->erase(it);\n  }\n  it = solver_options_double->find(\"cg_rate\");\n  if (it != solver_options_double->end()) {\n    scs_settings->cg_rate = it->second;\n    solver_options_double->erase(it);\n  }\n  if (!solver_options_double->empty()) {\n    throw std::invalid_argument(\"Unsupported SCS solver options.\");\n  }\n}\n}  // namespace\n\nvoid ScsSolver::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      \"ScsSolver doesn't support the feature of variable scaling.\");\n  }\n\n  // TODO(hongkai.dai): allow warm starting SCS with initial guess on\n  // primal/dual variables and primal residues.\n  unused(initial_guess);\n  // The initial guess for SCS is unused.\n  // SCS solves the problem in this form\n  // min  cᵀx\n  // s.t A x + s = b\n  //     s in K\n  // where K is a Cartesian product of some primitive cones.\n  // The cones have to be in this order\n  // Zero cone {x | x = 0 }\n  // Positive orthant {x | x ≥ 0 }\n  // Second-order cone {(t, x) | |x|₂ ≤ t }\n  // Positive semidefinite cone { X | min(eig(X)) ≥ 0, X = Xᵀ }\n  // There are more types that are supported by SCS, after the Positive\n  // semidefinite cone. Please refer to https://github.com/cvxgrp/scs for more\n  // details on the cone types.\n  // Notice that due to the special problem form supported by SCS, we need to\n  // convert our generic constraints to SCS form. For example, a linear\n  // inequality constraint\n  //   A x ≤ b\n  // will be converted as\n  //   A x + s = b\n  //   s in positive orthant cone.\n  // by introducing the slack variable s.\n\n  // num_x is the number of variables in `x`. It can contain more variables\n  // than in prog. For some constraint/cost, we need to append slack variables\n  // to convert the constraint/cost to the SCS form. For example, SCS does not\n  // support quadratic cost. So we need to convert the quadratic cost\n  //   min 0.5zᵀQz + bᵀz + d\n  // to the form\n  //   min y\n  //   s.t 2(y - bᵀz - d) ≥ zᵀQz     (1)\n  // now the cost is a linear function of y, with a rotated Lorentz cone\n  // constraint(1). So we need to append the slack variable `y` to the variables\n  // in `prog`.\n  int num_x = prog.num_vars();\n\n  // We need to construct a sparse matrix in Column Compressed Storage (CCS)\n  // format. On the other hand, we add the constraint row by row, instead of\n  // column by column, as preferred by CCS. As a result, we use Eigen sparse\n  // matrix to construct a sparse matrix in column order first, and then\n  // compress it to get CCS.\n  std::vector<Eigen::Triplet<double>> A_triplets;\n\n  // cone stores all the cones K in the problem.\n  ScsCone* cone = static_cast<ScsCone*>(scs_calloc(1, sizeof(ScsCone)));\n\n  // A_row_count will increment, when we add each constraint.\n  int A_row_count = 0;\n  std::vector<double> b;\n\n  // `c` is the coefficient in the linear cost cᵀx\n  std::vector<double> c(num_x, 0.0);\n\n  // Our cost (LinearCost, QuadraticCost, etc) also allows a constant term, we\n  // add these constant terms to `cost_constant`.\n  double cost_constant{0};\n\n  // Parse linear cost\n  ParseLinearCost(prog, &c, &cost_constant);\n\n  // Parse linear equality constraint\n  ParseLinearEqualityConstraint(prog, &A_triplets, &b, &A_row_count, cone);\n\n  // Parse bounding box constraint\n  ParseBoundingBoxConstraint(prog, &A_triplets, &b, &A_row_count, cone);\n\n  // Parse linear constraint\n  ParseLinearConstraint(prog, &A_triplets, &b, &A_row_count, cone);\n\n  // Parse Lorentz cone and rotated Lorentz cone constraint\n  std::vector<int> lorentz_cone_length;\n  ParseSecondOrderConeConstraints(prog, &A_triplets, &b, &A_row_count,\n                                  &lorentz_cone_length);\n\n  // Parse quadratic cost. This MUST be called after parsing the second order\n  // cone constraint, as we convert quadratic cost to second order cone\n  // constraint.\n  ParseQuadraticCost(prog, &c, &A_triplets, &b, &A_row_count,\n                     &lorentz_cone_length, &num_x);\n\n  // Set the lorentz cone length in the SCS cone.\n  cone->qsize = lorentz_cone_length.size();\n  cone->q = static_cast<scs_int*>(scs_calloc(cone->qsize, sizeof(scs_int)));\n  for (int i = 0; i < cone->qsize; ++i) {\n    cone->q[i] = lorentz_cone_length[i];\n  }\n\n  // Parse PositiveSemidefiniteConstraint and LinearMatrixInequalityConstraint.\n  ParsePositiveSemidefiniteConstraint(prog, &A_triplets, &b, &A_row_count,\n                                      cone);\n\n  // Parse ExponentialConeConstraint.\n  ParseExponentialConeConstraint(prog, &A_triplets, &b, &A_row_count, cone);\n\n  Eigen::SparseMatrix<double> A(A_row_count, num_x);\n  A.setFromTriplets(A_triplets.begin(), A_triplets.end());\n  A.makeCompressed();\n\n  ScsData* scs_problem_data =\n      static_cast<ScsData*>(scs_calloc(1, sizeof(ScsData)));\n  SetScsProblemData(A_row_count, num_x, A, b, c, scs_problem_data);\n  std::unordered_map<std::string, int> input_solver_options_int =\n      merged_options.GetOptionsInt(id());\n  std::unordered_map<std::string, double> input_solver_options_double =\n      merged_options.GetOptionsDouble(id());\n  SetScsSettings(&input_solver_options_int, scs_problem_data->stgs);\n  SetScsSettings(&input_solver_options_double, scs_problem_data->stgs);\n\n  ScsInfo scs_info{0};\n\n  ScsSolution* scs_sol =\n      static_cast<ScsSolution*>(scs_calloc(1, sizeof(ScsSolution)));\n\n  ScsSolverDetails& solver_details =\n      result->SetSolverDetailsType<ScsSolverDetails>();\n  solver_details.scs_status = scs(scs_problem_data, cone, scs_sol, &scs_info);\n\n  solver_details.iter = scs_info.iter;\n  solver_details.primal_objective = scs_info.pobj;\n  solver_details.dual_objective = scs_info.dobj;\n  solver_details.primal_residue = scs_info.res_pri;\n  solver_details.residue_infeasibility = scs_info.res_infeas;\n  solver_details.residue_unbounded = scs_info.res_unbdd;\n  solver_details.relative_duality_gap = scs_info.rel_gap;\n  solver_details.scs_setup_time = scs_info.setup_time;\n  solver_details.scs_solve_time = scs_info.solve_time;\n\n  SolutionResult solution_result{SolutionResult::kUnknownError};\n  solver_details.y.resize(A_row_count);\n  solver_details.s.resize(A_row_count);\n  for (int i = 0; i < A_row_count; ++i) {\n    solver_details.y(i) = scs_sol->y[i];\n    solver_details.s(i) = scs_sol->s[i];\n  }\n  if (solver_details.scs_status == SCS_SOLVED ||\n      solver_details.scs_status == SCS_SOLVED_INACCURATE) {\n    solution_result = SolutionResult::kSolutionFound;\n    result->set_x_val(\n        (Eigen::Map<VectorX<scs_float>>(scs_sol->x, prog.num_vars()))\n            .cast<double>());\n    result->set_optimal_cost(scs_info.pobj + cost_constant);\n  } else if (solver_details.scs_status == SCS_UNBOUNDED ||\n             solver_details.scs_status == SCS_UNBOUNDED_INACCURATE) {\n    solution_result = SolutionResult::kUnbounded;\n    result->set_optimal_cost(MathematicalProgram::kUnboundedCost);\n  } else if (solver_details.scs_status == SCS_INFEASIBLE ||\n             solver_details.scs_status == SCS_INFEASIBLE_INACCURATE) {\n    solution_result = SolutionResult::kInfeasibleConstraints;\n    result->set_optimal_cost(MathematicalProgram::kGlobalInfeasibleCost);\n  }\n  if (solver_details.scs_status != SCS_SOLVED) {\n    drake::log()->info(\"SCS returns code {}, with message \\\"{}\\\".\\n\",\n                       solver_details.scs_status,\n                       Scs_return_info(solver_details.scs_status));\n  }\n\n  result->set_solution_result(solution_result);\n\n  // Free allocated memory\n  scs_free_data(scs_problem_data, cone);\n  scs_free_sol(scs_sol);\n}\n\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "ee73a49bfecde4ddd22ac4a635eb946c08dfae9e", "size": 32693, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/scs_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/scs_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/scs_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": 41.4359949303, "max_line_length": 80, "alphanum_fraction": 0.6347230294, "num_tokens": 9493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.04603390043609667, "lm_q1q2_score": 0.021401232649187456}}
{"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 headers go here\n#include <vector>\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <fstream>\n#include <typeinfo>\n#include <tuple>\n#include <limits>\n\n// Boost headers go here\n#include <boost/filesystem.hpp>\n#include <boost/math/special_functions.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n\n// Geneva headers go here\n#include \"common/GCommonEnums.hpp\"\n#include \"common/GExceptions.hpp\"\n#include \"common/GLogger.hpp\"\n#include \"common/GErrorStreamer.hpp\"\n#include \"common/GCommonMathHelperFunctions.hpp\"\n\nnamespace Gem {\nnamespace Common {\n\nconst bool GWARNINGONLY = true;\nconst bool GERRORONLY = false;\n\n/******************************************************************************/\n/**\n * Enforces a value inside of a given range (both boundaries inclusive) for the\n * first parameter. Note that the value of this parameter may change.\n *\n * @param val The value to be adapted\n * @param lower The lower boundary of the allowed value range\n * @param upper The upper (inclusive) boundary of the allowed value range\n */\ntemplate<typename fp_type>\nfp_type enforceRangeConstraint(\n\tfp_type &val\n\t, const fp_type &lower\n\t, const fp_type &upper\n\t, const std::string& caller = \"empty\"\n\t, bool verbose = false\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n   if(lower > upper) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< (caller==\"empty\"?\"\":(\"[\"+caller+\"] \")) << \"In enforceRangeConstraint<fp_type>(): Error!\" << std::endl\n\t\t\t\t<< \"Lower boundary > upper boundary: \" << lower << \" / \" << upper << std::endl\n\t\t);\n   }\n\n\tif (val < lower) {\n\t\tif(verbose) {\n\t\t\tglogger\n\t\t\t\t<< (caller == \"empty\" ? \"\" : (\"[\" + caller + \"] \")) << \"In Gem::Common::enforceRangeConstraint(): \" << std::endl\n\t\t\t\t<< \"value \" << val << \" < lower boundary \" << lower << std::endl\n\t\t\t\t<< \"Will be adapted to \" << lower << std::endl\n\t\t\t\t<< GWARNING;\n\t\t}\n\t\tval = lower;\n\t} else if (val > upper) {\n\t\tif(verbose) {\n\t\t\tglogger\n\t\t\t\t<< (caller == \"empty\" ? \"\" : (\"[\" + caller + \"] \")) << \"In Gem::Common::enforceRangeConstraint(): \" << std::endl\n\t\t\t \t<< \"value \" << val << \" > upper boundary \" << upper << std::endl\n\t\t\t\t<< \"Will be adapted to \" << upper << std::endl\n\t\t\t\t<< GWARNING;\n\t\t}\n\t\tval = upper;\n\t}\n\n\treturn val;\n}\n\n/******************************************************************************/\n/**\n * Checks that a given floating point value is inside of a given set of boundaries (both inclusive)\n *\n * @param val The value to be check\n * @param lower The lower boundary of the allowed value range\n * @param upper The upper boundary of the allowed value range\n */\ntemplate<typename fp_type>\nbool checkRangeCompliance(\n\tconst fp_type &val\n\t, const fp_type &lower\n\t, const fp_type &upper\n\t, const std::string& caller = \"empty\"\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n   if(lower > upper) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< (caller==\"empty\"?\"\":(\"[\"+caller+\"] \")) << \"In checkRangeCompliance<fp_type>(...): Error!\" << std::endl\n\t\t\t\t<< \"Lower boundary > upper boundary: \" << lower << \" / \" << upper << std::endl\n\t\t);\n   }\n\n\treturn not (val < lower || val > upper);\n}\n\n/******************************************************************************/\n/**\n * Checks that a given floating point value is inside of a given set of boundaries (both inclusive)\n *\n * @param val The value to be check\n * @param lower The lower boundary of the allowed value range\n * @param upper The upper boundary of the allowed value range\n */\ntemplate<typename int_type>\nbool checkRangeCompliance(\n\tconst int_type &val\n\t, const int_type &lower\n\t, const int_type &upper\n\t, const std::string& caller = \"empty\"\n\t, typename std::enable_if<std::is_integral<int_type>::value>::type *dummy = nullptr\n) {\n\tif(lower > upper) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< (caller==\"empty\"?\"\":(\"[\"+caller+\"] \")) << \"In checkRangeCompliance<int_type>(...): Error!\" << std::endl\n\t\t\t\t<< \"Lower boundary > upper boundary: \" << lower << \" / \" << upper << std::endl\n\t\t);\n\t}\n\n\treturn not (val < lower || val > upper);\n}\n\n/******************************************************************************/\n/**\n * Retrieves the worst known value for a given floating point type, depending\n * on whether maximal or minimal values are considered to be better\n */\ntemplate<typename fp_type>\nfp_type getWorstCase(\n\tbool maxMode\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\treturn (\n\t\tmaxMode\n\t\t? boost::numeric::bounds<fp_type>::lowest()\n\t\t: boost::numeric::bounds<fp_type>::highest()\n\t);\n}\n\n/******************************************************************************/\n/**\n * Retrieves the best known value for a given floating point type, depending\n * on whether maximal or minimal values are considered to be better\n */\ntemplate<typename fp_type>\nfp_type getBestCase(\n\tbool maxMode\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\treturn (\n\t\tmaxMode\n\t\t? boost::numeric::bounds<fp_type>::highest()\n\t\t: boost::numeric::bounds<fp_type>::lowest()\n\t);\n}\n\n\n/******************************************************************************/\n/**\n * Retrieves the worst known value for a given floating point type, depending\n * on whether maximal or minimal values are considered to be better\n */\ntemplate<typename fp_type>\nfp_type getWorstCase(\n\tGem::Common::sortOrder sortOrder\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\treturn (\n\t\tsortOrder==Gem::Common::sortOrder::HIGHERISBETTER\n\t\t? boost::numeric::bounds<fp_type>::lowest()\n\t\t: boost::numeric::bounds<fp_type>::highest()\n\t);\n}\n\n/******************************************************************************/\n/**\n * Retrieves the best known value for a given floating point type, depending\n * on whether maximal or minimal values are considered to be better\n */\ntemplate<typename fp_type>\nfp_type getBestCase(\n\tGem::Common::sortOrder sortOrder\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\treturn (\n\t\tsortOrder==Gem::Common::sortOrder::HIGHERISBETTER\n\t\t? boost::numeric::bounds<fp_type>::highest()\n\t\t: boost::numeric::bounds<fp_type>::lowest()\n\t);\n}\n\n/******************************************************************************/\n/**\n * Checks that a floating point value is contained in a given range\n *\n * @param val The value to be checked for containment\n * @param min The lower boundary (included)\n * @param max The upper boundary (possibly included)\n * @param lowerOpen Determines whether the lower boundary must be smaller or may be equal to val (default: closed)\n * @param upperOpen Determines whether the upper boundary must be larger or may be equal to val (default: closed)\n * @param warnOnly Will warn only if the condition isn't met\n * @return The value being checked\n */\nconst bool GFPLOWERCLOSED = false;\nconst bool GFPLOWEROPEN = true;\nconst bool GFPUPPERCLOSED = false;\nconst bool GFPUPPEROPEN = true;\nconst bool GFWARNONLY = true;\nconst bool GFNOWARNING = false;\n\ntemplate<typename fp_type>\nfp_type checkValueRange(\n\tfp_type val\n\t, fp_type min\n\t, fp_type max\n\t, bool lowerOpen = false\n\t, bool upperOpen = false\n\t, bool warnOnly = false\n\t, std::string varName = std::string()\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\tbool inValueRange = true;\n\n\tif (lowerOpen) {\n\t\tif (val < boost::math::float_next<fp_type>(min)) inValueRange = false;\n\t} else {\n\t\tif (val < min) inValueRange = false;\n\t}\n\n\tif (upperOpen) {\n\t\tif (val > boost::math::float_prior<fp_type>(max)) inValueRange = false;\n\t} else {\n\t\tif (val > max) inValueRange = false;\n\t}\n\n\tif (not inValueRange) {\n\t\tif (warnOnly) {\n\t\t\tglogger\n\t\t\t<< \"In checkValueRange<fp_type>(): Error!\" << std::endl\n\t\t\t<< \"Value \" << val << (varName.empty() ? \"\" : (\" of variable \" + varName)) << \" outside of recommended range \" << std::endl\n\t\t\t<< min << (lowerOpen ? \" (open) - \" : \" (closed) - \") << max << (upperOpen ? \" (open)\" : \" (closed)\") << std::endl\n\t\t\t<< GWARNING;\n\t\t} else {\n\t\t\tthrow gemfony_exception(\n\t\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t\t<< \"In checkValueRange<fp_type>(): Error!\" << std::endl\n\t\t\t\t\t<< \"Value \" << val << (varName.empty() ? \"\" : (\" of variable \" + varName)) << \" outside of allowed range \" << std::endl\n\t\t\t\t\t<< min << (lowerOpen ? \" (open) - \" : \" (closed) - \") << max << (upperOpen ? \" (open)\" : \" (closed)\") << std::endl\n\t\t\t);\n\t\t}\n\t}\n\n\treturn val;\n}\n\n/******************************************************************************/\n/**\n * Checks that an integral value is contained in a given range\n *\n * @param val The value to be checked for containment\n * @param min The lower boundary (included)\n * @param max The upper boundary (possibly included)\n * @param lowerOpen Determines whether the lower boundary must be smaller or may be equal to val (default: closed)\n * @param upperOpen Determines whether the upper boundary must be larger or may be equal to val (default: closed)\n * @param warnOnly Will warn only if the condition isn't met\n * @return The value being checked\n */\nconst bool GINTLOWERCLOSED = false;\nconst bool GINTLOWEROPEN = true;\nconst bool GINTUPPERCLOSED = false;\nconst bool GINTUPPEROPEN = true;\n\ntemplate<typename int_type>\nint_type checkValueRange(\n\tint_type val, int_type min, int_type max, bool lowerOpen = false, bool upperOpen = false, bool warnOnly = false,\n\ttypename std::enable_if<std::is_integral<int_type>::value>::type *dummy = nullptr\n) {\n\tbool inValueRange = true;\n\n\tif (lowerOpen) {\n\t\tif (val <= min) inValueRange = false;\n\t} else {\n\t\tif (val < min) inValueRange = false;\n\t}\n\n\tif (upperOpen) {\n\t\tif (val >= max) inValueRange = false;\n\t} else {\n\t\tif (val > max) inValueRange = false;\n\t}\n\n\tif (not inValueRange) {\n\t\tif (warnOnly) {\n\t\t\tglogger\n\t\t\t<< \"Warning:\" << std::endl\n\t\t\t<< \"In checkValueRange<int_type>(): Error!\" << std::endl\n\t\t\t<< \"Value \" << val << \" outside of recommended range \" << std::endl\n\t\t\t<< min << (lowerOpen ? \" (open) - \" : \" (closed) - \") << max << (upperOpen ? \" (open)\" : \" (closed)\") <<  std::endl\n\t\t\t<< GWARNING;\n\t\t} else {\n\t\t\tthrow gemfony_exception(\n\t\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t\t<< \"In checkValueRange<int_type>(): Error!\" << std::endl\n\t\t\t\t\t<< \"Value \" << val << \" outside of allowed range \" << std::endl\n\t\t\t\t\t<< min << (lowerOpen ? \" (open) - \" : \" (closed) - \") << max << (upperOpen ? \" (open)\" : \" (closed)\") << std::endl\n\t\t\t);\n\t\t}\n\t}\n\n\treturn val;\n}\n\n/******************************************************************************/\n/**\n * Finds the minimum and maximum component in a vector of undefined types. This\n * function requires that x_type_undet can be compared using the usual operators.\n *\n * @param extDat The vector holding the data, for which extreme values should be calculated\n * @return A std::tuple holding the extreme values\n */\ntemplate<typename x_type_undet>\nauto getMinMax(const std::vector<x_type_undet> &extDat) {\n\t// Do some error checking\n\tif (extDat.size() < (std::size_t) 2) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In GBasePlotter::getMinMax(1D): Error!\" << std::endl\n\t\t\t\t<< \"Got vector of invalid size \" << extDat.size() << std::endl\n\t\t);\n\t}\n\n\tx_type_undet min = extDat.at(0), max = min;\n\n\tfor (std::size_t i = 1; i < extDat.size(); i++) {\n\t\tif (extDat.at(i) < min) min = extDat.at(i);\n\t\tif (extDat.at(i) > max) max = extDat.at(i);\n\t}\n\n\treturn std::tuple<x_type_undet, x_type_undet>{min, max};\n}\n\n/******************************************************************************/\n/**\n * Find the minimum and maximum component in a vector of 2d-Tuples of undefined types.\n * This function requires that x_type_undet and y_type_undet can be compared using the\n * usual operators\n *\n * @param extDat The vector holding the data, for which extreme values should be calculated\n * @return A std::tuple holding the extreme values\n */\ntemplate<typename x_type_undet, typename y_type_undet>\nauto getMinMax(const std::vector<std::tuple<x_type_undet, y_type_undet>> &extDat) {\n\t// Do some error checking\n\tif (extDat.size() < (std::size_t) 2) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In GBasePlotter::getMinMax(2D): Error!\" << std::endl\n\t\t\t\t<< \"Got vector of invalid size \" << extDat.size() << std::endl\n\t\t);\n\t}\n\n\tx_type_undet minX = std::get<0>(extDat.at(0)), maxX = minX;\n\ty_type_undet minY = std::get<1>(extDat.at(0)), maxY = minY;\n\n\tfor (std::size_t i = 1; i < extDat.size(); i++) {\n\t\tif (std::get<0>(extDat.at(i)) < minX) minX = std::get<0>(extDat.at(i));\n\t\tif (std::get<0>(extDat.at(i)) > maxX) maxX = std::get<0>(extDat.at(i));\n\t\tif (std::get<1>(extDat.at(i)) < minY) minY = std::get<1>(extDat.at(i));\n\t\tif (std::get<1>(extDat.at(i)) > maxY) maxY = std::get<1>(extDat.at(i));\n\t}\n\n\treturn std::tuple<x_type_undet, x_type_undet, y_type_undet, y_type_undet>{minX, maxX, minY, maxY};\n}\n\n/******************************************************************************/\n/**\n * Find the minimum and maximum component in a vector of 3d-Tuples of undefined types.\n * This function requires that x_type_undet, y_type_undet and z_type_undet can be compared\n * using the usual operators\n *\n * @param extDat The vector holding the data, for which extreme values should be calculated\n * @return A std::tuple holding the extreme values\n */\ntemplate<typename x_type_undet, typename y_type_undet, typename z_type_undet>\nauto getMinMax(const std::vector<std::tuple<x_type_undet, y_type_undet, z_type_undet>> &extDat) {\n\t// Do some error checking\n\tif (extDat.size() < (std::size_t) 2) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In GBasePlotter::getMinMax(3D): Error!\" << std::endl\n\t\t\t\t<< \"Got vector of invalid size \" << extDat.size() << std::endl\n\t\t);\n\t}\n\n\tx_type_undet minX = std::get<0>(extDat.at(0)), maxX = minX;\n\ty_type_undet minY = std::get<1>(extDat.at(0)), maxY = minY;\n\tz_type_undet minZ = std::get<2>(extDat.at(0)), maxZ = minZ;\n\n\tfor (std::size_t i = 1; i < extDat.size(); i++) {\n\t\tif (std::get<0>(extDat.at(i)) < minX) minX = std::get<0>(extDat.at(i));\n\t\tif (std::get<0>(extDat.at(i)) > maxX) maxX = std::get<0>(extDat.at(i));\n\t\tif (std::get<1>(extDat.at(i)) < minY) minY = std::get<1>(extDat.at(i));\n\t\tif (std::get<1>(extDat.at(i)) > maxY) maxY = std::get<1>(extDat.at(i));\n\t\tif (std::get<2>(extDat.at(i)) < minZ) minZ = std::get<2>(extDat.at(i));\n\t\tif (std::get<2>(extDat.at(i)) > maxZ) maxZ = std::get<2>(extDat.at(i));\n\t}\n\n\treturn std::tuple<x_type_undet, x_type_undet, y_type_undet, y_type_undet, z_type_undet, z_type_undet>{minX, maxX, minY, maxY, minZ, maxZ};\n}\n\n/******************************************************************************/\n/**\n * Find the minimum and maximum component in a vector of 3d-Tuples of undefined types.\n * This function requires that x_type_undet, y_type_undet and z_type_undet can be compared\n * using the usual operators\n *\n * @param extDat The vector holding the data, for which extreme values should be calculated\n * @return A std::tuple holding the extreme values\n */\ntemplate<typename x_type_undet, typename y_type_undet, typename z_type_undet, typename w_type_undet>\nauto getMinMax(const std::vector<std::tuple<x_type_undet, y_type_undet, z_type_undet, w_type_undet>> &extDat) {\n\t// Do some error checking\n\tif (extDat.size() < (std::size_t) 2) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In GBasePlotter::getMinMax(3D): Error!\" << std::endl\n\t\t\t\t<< \"Got vector of invalid size \" << extDat.size() << std::endl\n\t\t);\n\t}\n\n\tx_type_undet minX = std::get<0>(extDat.at(0)), maxX = minX;\n\ty_type_undet minY = std::get<1>(extDat.at(0)), maxY = minY;\n\tz_type_undet minZ = std::get<2>(extDat.at(0)), maxZ = minZ;\n\tw_type_undet minW = std::get<3>(extDat.at(0)), maxW = minW;\n\n\tfor (std::size_t i = 1; i < extDat.size(); i++) {\n\t\tif (std::get<0>(extDat.at(i)) < minX) minX = std::get<0>(extDat.at(i));\n\t\tif (std::get<0>(extDat.at(i)) > maxX) maxX = std::get<0>(extDat.at(i));\n\t\tif (std::get<1>(extDat.at(i)) < minY) minY = std::get<1>(extDat.at(i));\n\t\tif (std::get<1>(extDat.at(i)) > maxY) maxY = std::get<1>(extDat.at(i));\n\t\tif (std::get<2>(extDat.at(i)) < minZ) minZ = std::get<2>(extDat.at(i));\n\t\tif (std::get<2>(extDat.at(i)) > maxZ) maxZ = std::get<2>(extDat.at(i));\n\t\tif (std::get<3>(extDat.at(i)) < minW) minW = std::get<3>(extDat.at(i));\n\t\tif (std::get<3>(extDat.at(i)) > maxW) maxW = std::get<3>(extDat.at(i));\n\t}\n\n\treturn std::tuple<x_type_undet, x_type_undet, y_type_undet, y_type_undet, z_type_undet, z_type_undet, w_type_undet, w_type_undet>{minX, maxX, minY, maxY, minZ, maxZ, minW, maxW};\n}\n\n/******************************************************************************/\n/**\n * Calculates the mean value from a std::vector of floating point values\n *\n * @param parVec The vector of values for which the mean should be calculated\n * @return The mean value of parVec\n */\ntemplate<typename T>\nT GMean(\n\tconst std::vector<T> &parVec\n\t, typename std::enable_if<std::is_floating_point<T>::value>::type *dummy = nullptr\n) {\n\tT mean = 0.;\n\n#ifdef DEBUG\n   if(parVec.empty()) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In T GMean(const std::vector<T>&): Error!\" << std::endl\n\t\t\t\t<< \"parVec has size 0\" << std::endl\n\t\t);\n   }\n#endif /* DEBUG */\n\n\ttypename std::vector<T>::const_iterator cit;\n\tfor (cit = parVec.begin(); cit != parVec.end(); ++cit) {\n\t\tmean += *cit;\n\t}\n\n\treturn mean / boost::numeric_cast<T>(parVec.size());\n}\n\n\n/******************************************************************************/\n/**\n * Calculates the mean and standard deviation for a std::vector of floating point values\n *\n * @param parVec The vector of values for which the standard deviation should be calculated\n * @return A std::tuple holding the mean value and the standard deviation of the values stored in parVec\n */\ntemplate<typename T>\nauto GStandardDeviation(\n\tconst std::vector<T> &parVec, typename std::enable_if<std::is_floating_point<T>::value>::type *dummy = nullptr\n) {\n\tT mean = GMean(parVec), sigma = 0.;\n\n#ifdef DEBUG\n   if(parVec.size() == 0) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In std::tuple<T,T> GStandardDeviation(const std::vector<T>&): Error!\" << std::endl\n\t\t\t\t<< \"parVec is empty\" << std::endl\n\t\t);\n   }\n#endif /* DEBUG */\n\n\t// It is easy if the size is 1\n\tif (parVec.size() == 1) {\n\t\treturn std::tuple<T, T>{parVec.at(0), 0.};\n\t}\n\n\ttypename std::vector<T>::const_iterator cit;\n\tfor (cit = parVec.begin(); cit != parVec.end(); ++cit) {\n\t\tsigma += GSQUARED(*cit - mean);\n\n\t}\n\tsigma /= parVec.size() - 1;\n\tsigma = sqrt(sigma);\n\n\treturn std::tuple<T, T>{mean, sigma};\n}\n\n/******************************************************************************/\n/**\n * Calculates the mean and standard deviation for each row of a \"matrix\" made up from several\n * std:vector<T> objects of equal size. E.g., if you have 5 std::vector<double> of size 10, you will\n * get back a std::vector<std::tuple<double, double>>, of size 10, holding the mean and standard\n * deviation of the corresponding positions in the 5 vectors.\n *\n * @param parVec The vectors for which the standard deviations should be calculated\n * @param result A std::vector holdung tuples with the mean and sigma values for each row\n */\ntemplate<typename T>\nvoid GVecStandardDeviation(\n\tconst std::vector<std::vector<T>> &parVec, std::vector<std::tuple<T, T>> &result,\n\ttypename std::enable_if<std::is_floating_point<T>::value>::type *dummy = nullptr\n) {\n\n#ifdef DEBUG\n   // Check that there are entries in the vector\n   if(parVec.size() == 0) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In void GVecStandardDeviation(): Error!\" << std::endl\n\t\t\t\t<< \"parVec is empty\" << std::endl\n\t\t);\n   }\n\n   // Check that the first entry has at least one component\n   if(parVec.at(0).empty()) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In void GVecStandardDeviation(): Error!\" << std::endl\n\t\t\t\t<< \"parVec has empty component\" << std::endl\n\t\t);\n   }\n\n   // Check that all entries have the same size\n   if(parVec.size() > 1) {\n      std::size_t sizeFirst = parVec.at(0).size(), pos=0;\n      for(auto const &p: parVec) {\n\t\t\tif(p.size() != sizeFirst) {\n\t\t\t\tthrow gemfony_exception(\n\t\t\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t\t\t<< \"In void GVecStandardDeviation(): Error!\" << std::endl\n\t\t\t\t\t\t<< \"Found parVec component of different size: \" << sizeFirst << \" / \" << pos << \" / \" << p.size() << std::endl\n\t\t\t\t);\n         }\n         pos++;\n      }\n   }\n\n   // Now we know that there is at least one component with at least one entry,\n   // and that all components have the same size. This is sufficient to calculate\n   // the mean and standard deviation for each row of the \"matrix\" (made up from\n   // the vectors,\n#endif /* DEBUG */\n\n\t// Make sure our result vector is empty\n\tresult.clear();\n\n\ttypename std::vector<std::vector<T>>::const_iterator cit;\n\tfor (std::size_t pos = 0; pos < parVec.at(0).size(); pos++) {\n\t\tstd::vector<T> indPar;\n\n\t\t// Extract the individual parameters\n\t\tfor (cit = parVec.begin(); cit != parVec.end(); ++cit) {\n\t\t\tindPar.push_back(cit->at(pos));\n\t\t}\n\n\t\t// Calculate the mean and standard deviation\n\t\tresult.push_back(GStandardDeviation(indPar));\n\t}\n}\n\n/******************************************************************************/\n/**\n * Calculation of pow for small positive integers using template metaprogramming\n */\ntemplate<std::size_t B, std::size_t E>\nstruct PowSmallPosInt {\n\tenum : std::size_t {\n\t\tresult = B * PowSmallPosInt<B, E - 1>::result\n\t};\n};\n\ntemplate<std::size_t B>\nstruct PowSmallPosInt<B, 2> {\n\tenum : std::size_t {\n\t\tresult = B * B\n\t};\n};\n\ntemplate<std::size_t B>\nstruct PowSmallPosInt<B, 1> {\n\tenum : std::size_t {\n\t\tresult = B\n\t};\n};\n\ntemplate<std::size_t B>\nstruct PowSmallPosInt<B, 0> {\n\tenum : std::size_t {\n\t\tresult = 1\n\t};\n};\n\n/******************************************************************************/\n/**\n * Takes two std::vector<> and subtracts each position of the second vector from the\n * corresponding position of the first vector. Note that we assume here that T understands\n * the operator-= . Note that after this function has been called, a will have changed.\n *\n * @param a The vector from whose elements numbers will be subtracted\n * @param b The vector whose elements will be subtracted from the elements of a\n */\ntemplate<typename T>\nvoid subtractVec(\n\tstd::vector<T> &a, const std::vector<T> &b\n) {\n#ifdef DEBUG\n   // Do some error checking\n   if(a.size() != b.size()) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In subtractVec(std::vector<T>, const std::vector<T>&): Error!\" << std::endl\n\t\t\t\t<< \"Found invalid sizes: \" << a.size() << \" / \" << b.size() << std::endl\n\t\t);\n   }\n#endif /* DEBUG */\n\n\ttypename std::vector<T>::iterator it_a;\n\ttypename std::vector<T>::const_iterator cit_b;\n\n\t// Subtract the elements\n\tfor (it_a = a.begin(), cit_b = b.begin(); it_a != a.end(); ++it_a, ++cit_b) {\n\t\t(*it_a) -= (*cit_b);\n\t}\n}\n\n/******************************************************************************/\n/**\n * Takes two std::vector<> and adds each position of the second vector to the\n * corresponding position of the first vector. Note that we assume here that T understands\n * the operator+= . Note that after this function has been called, a will have changed.\n *\n * @param a The vector to whose elements numbers will be added\n * @param b The vector whose elements will be added to the elements of a\n */\ntemplate<typename T>\nvoid addVec(\n\tstd::vector<T> &a, const std::vector<T> &b\n) {\n#ifdef DEBUG\n   // Do some error checking\n   if(a.size() != b.size()) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In addVec(std::vector<T>, const std::vector<T>&): Error!\" << std::endl\n\t\t\t\t<< \"Found invalid sizes: \" << a.size() << \" / \" << b.size() << std::endl\n\t\t);\n   }\n#endif /* DEBUG */\n\n\ttypename std::vector<T>::iterator it_a;\n\ttypename std::vector<T>::const_iterator cit_b;\n\n\t// Subtract the elements\n\tfor (it_a = a.begin(), cit_b = b.begin(); it_a != a.end(); ++it_a, ++cit_b) {\n\t\t(*it_a) += (*cit_b);\n\t}\n}\n\n/******************************************************************************/\n/**\n * Multiplies each position of a std::vector<> with a constant. Note that we assume here that\n * T understands the operator*= . Note that after this function has been called, a will have changed.\n *\n * @param a The vector to whose elements numbers will be added\n * @param c The constant which will be multiplied with each position of a\n */\ntemplate<typename T>\nvoid multVecConst(\n\tstd::vector<T> &a, const T &c\n) {\n\ttypename std::vector<T>::iterator it_a;\n\n\t// Subtract the elements\n\tfor (it_a = a.begin(); it_a != a.end(); ++it_a) {\n\t\t(*it_a) *= c;\n\t}\n}\n\n/******************************************************************************/\n/**\n * Assigns a constant value to each position of the vector. Note that we assume here that\n * T understands the operator*= . Note that after this function has been called, a will have changed.\n *\n * @param a The vector to whose elements c will be assigned\n * @param c The constant which will be assigned each position of a\n */\ntemplate<typename T>\nvoid assignVecConst(\n\tstd::vector<T> &a, const T &c\n) {\n\ttypename std::vector<T>::iterator it_a;\n\n\t// Assign c to each element\n\tfor (it_a = a.begin(); it_a != a.end(); ++it_a) {\n\t\t(*it_a) = c;\n\t}\n}\n\n/******************************************************************************/\n/**\n * Summs up the x- and y-components individually of a vector of 2d-tuples\n */\ntemplate<typename fp_type>\nstd::tuple<fp_type, fp_type> sumTupleVec(\n\tconst std::vector<std::tuple<fp_type, fp_type>> &dataPoints,\n\ttypename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\tstd::tuple<fp_type, fp_type> result = std::tuple<fp_type, fp_type>(fp_type(0.), fp_type(0.));;\n\n\ttypename std::vector<std::tuple<fp_type, fp_type>>::const_iterator cit;\n\tfor (cit = dataPoints.begin(); cit != dataPoints.end(); ++cit) {\n\t\tstd::get<0>(result) += std::get<0>(*cit);\n\t\tstd::get<1>(result) += std::get<1>(*cit);\n\t}\n\n\treturn result;\n}\n\n/******************************************************************************/\n/**\n * Summs up the squares of x- and y-components individually of a vector of 2d-tuples\n */\ntemplate<typename fp_type>\nstd::tuple<fp_type, fp_type> squareSumTupleVec(\n\tconst std::vector<std::tuple<fp_type, fp_type>> &dataPoints,\n\ttypename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\tstd::tuple<fp_type, fp_type> result = std::tuple<fp_type, fp_type>(fp_type(0.), fp_type(0.));\n\n\ttypename std::vector<std::tuple<fp_type, fp_type>>::const_iterator cit;\n\tfor (cit = dataPoints.begin(); cit != dataPoints.end(); ++cit) {\n\t\tstd::get<0>(result) += gpow(std::get<0>(*cit), 2.);\n\t\tstd::get<1>(result) += gpow(std::get<1>(*cit), 2.);\n\t}\n\n\treturn result;\n}\n\n/******************************************************************************/\n/**\n * Summs up the product of x- and y-components of a vector of 2d-tuples\n */\ntemplate<typename fp_type>\nfp_type productSumTupleVec(\n\tconst std::vector<std::tuple<fp_type, fp_type>> &dataPoints,\n\ttypename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\tfp_type result = fp_type(0.);\n\n\ttypename std::vector<std::tuple<fp_type, fp_type>>::const_iterator cit;\n\tfor (cit = dataPoints.begin(); cit != dataPoints.end(); ++cit) {\n\t\tresult += (std::get<0>(*cit) * std::get<1>(*cit));\n\t}\n\n\treturn result;\n}\n\n/******************************************************************************/\n/**\n * Calculates the \"square deviation\" of a set of floating point tuples from\n * a line defined through a + b*x .\n *\n * @param dataPoints A vector of bi-tuples with x-y data points\n * @param a The offset of a line\n * @param b The slope of a line\n * @return The square deviation of the data points from the line\n */\ntemplate<typename fp_type>\nfp_type squareDeviation(\n\tconst std::vector<std::tuple<fp_type, fp_type>> &dataPoints, const fp_type &a, const fp_type &b,\n\ttypename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\tfp_type result = fp_type(0);\n\ttypename std::vector<std::tuple<fp_type, fp_type>>::const_iterator cit;\n\tfor (cit = dataPoints.begin(); cit != dataPoints.end(); ++cit) {\n\t\tresult += gpow(std::get<1>(*cit) - a - b * std::get<0>(*cit), 2.);\n\t}\n\treturn result;\n}\n\n/******************************************************************************/\n/**\n * Calculates the parameters a and b of a regression line, plus errors. The return\n * value is a std::tuple of four fp_type values: a, error_a, b, error_b, with the\n * line being defined by L(x)=a+b*x .\n *\n * @param dataPoints A vector of data points to which the lines parameters should fit\n * @return Regression parameters for a line defined by the input data points\n */\ntemplate<typename fp_type>\nauto getRegressionParameters(\n\tconst std::vector<std::tuple<fp_type, fp_type>> &dataPoints,\n\ttypename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\tif (dataPoints.empty()) {\n\t\treturn std::tuple<fp_type, fp_type, fp_type, fp_type>{fp_type(0.), fp_type(0.), fp_type(0.), fp_type(0.)};\n\t}\n\n\tfp_type a = fp_type(0), b = fp_type(0);\n\tfp_type n = fp_type(dataPoints.size());\n\n\tstd::tuple<fp_type, fp_type> sum_xy = sumTupleVec(dataPoints);\n\tfp_type sum_x = std::get<0>(sum_xy);\n\tfp_type sum_y = std::get<1>(sum_xy);\n\n\tstd::tuple<fp_type, fp_type> sq_sum_xy = squareSumTupleVec(dataPoints);\n\tfp_type sq_sum_x = std::get<0>(sq_sum_xy);\n\tfp_type sq_sum_y = std::get<1>(sq_sum_xy);\n\n\tfp_type prod_sum_xy = productSumTupleVec(dataPoints);\n\n\ta = (sum_y * sq_sum_x - sum_x * prod_sum_xy) / (n * sq_sum_x - gpow(sum_x, 2.));\n\tb = (n * prod_sum_xy - sum_x * sum_y) / (n * sq_sum_x - gpow(sum_x, 2.));\n\n\tfp_type dev = squareDeviation(dataPoints, a, b);\n\n\tfp_type sigma_a = gsqrt(dev / (n - 2.)) * gsqrt(sq_sum_x / (n * sq_sum_x - gpow(sum_x, 2.)));\n\tfp_type sigma_b = gsqrt(dev / (n - 2.)) * gsqrt(n / (n * sq_sum_x - gpow(sum_x, 2.)));\n\n\treturn std::tuple<fp_type, fp_type, fp_type, fp_type>{a, sigma_a, b, sigma_b};\n}\n\n/******************************************************************************/\n/**\n * Calculates the error of a function f=s/p , where s and p are independent\n * quantities, each with its own error. Returns:\n * - The sleep time\n * - The error on the sleep-time (always 0)\n * - the quantity s/p\n * - error on s/p\n * s and p have the same structure\n */\ntemplate<typename fp_type>\nauto getRatioError(\n\tconst std::tuple<fp_type, fp_type, fp_type, fp_type> &s, const std::tuple<fp_type, fp_type, fp_type, fp_type> &p,\n\ttypename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\t// p may not ne 0\n\tif (0. == std::get<2>(p)) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In getRatioError(): Error!\" << std::endl\n\t\t\t\t<< \"Attempted division by 0.\" << std::endl\n\t\t);\n\t}\n\n\tfp_type sleep_time = std::get<0>(s);\n\n\t// Check that the sleep-times for s and p are the same\n\tif (sleep_time != std::get<0>(p)) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In getRatioError(): Error!\" << std::endl\n\t\t\t\t<< \"Sleep times differ: \" << sleep_time << \" / \" << std::get<0>(p) << std::endl\n\t\t);\n\t}\n\n\tfp_type s_val = std::get<2>(s);\n\tfp_type s_err = std::get<3>(s);\n\tfp_type p_val = std::get<2>(p);\n\tfp_type p_err = std::get<3>(p);\n\n\treturn std::tuple<fp_type, fp_type, fp_type, fp_type>{\n\t\tsleep_time\n\t\t, 0.\n\t\t, s_val / p_val\n\t\t, gsqrt(gpow(s_err / p_val, fp_type(2.)) + gpow(s_val * p_err / gpow(p_val, fp_type(2.)), fp_type(2.)))\n\t};\n}\n\n/******************************************************************************/\n/**\n * Calculates the error for a function f=s/p , where s and p are independent\n * quantities, each with its own error. The function is applied to a std::vector\n * of different s and p (together with their errors). It returns a vector\n * of s/p together with their errors.\n */\ntemplate<typename fp_type>\nstd::vector<std::tuple<fp_type, fp_type, fp_type, fp_type>> getRatioErrors(\n\tconst std::vector<std::tuple<fp_type, fp_type, fp_type, fp_type>> &sn,\n\tconst std::vector<std::tuple<fp_type, fp_type, fp_type, fp_type>> &pn,\n\ttypename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\t// Check that both vectors have the same size, otherwise complain\n\tif (sn.size() != pn.size()) {\n\t\tthrow gemfony_exception(\n\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t<< \"In getRatioErrors(): Error!\" << std::endl\n\t\t\t\t<< \"Vectors have invalid sizes: \" << sn.size() << \" / \" << pn.size() << std::endl\n\t\t);\n\t}\n\n\tstd::vector<std::tuple<fp_type, fp_type, fp_type, fp_type>> spn;\n\ttypename std::vector<std::tuple<fp_type, fp_type, fp_type, fp_type>>::const_iterator s_cit, p_cit;\n\tfor (s_cit = sn.begin(), p_cit = pn.begin(); s_cit != sn.end(); ++s_cit, ++p_cit) {\n\t\tspn.push_back(getRatioError(*s_cit, *p_cit));\n\t}\n\n\treturn spn;\n}\n\n/******************************************************************************/\n/**\n * This function checks whether a given floating point value is \"close\" to a given\n * target value, with a maximum difference provided as a parameter\n */\ntemplate<typename fp_type>\nbool isClose(\n\tfp_type val\n\t, fp_type target = 0\n\t, fp_type margin = fp_type(0.00001)\n\t, typename std::enable_if<std::is_floating_point<fp_type>::value>::type *dummy = nullptr\n) {\n\treturn (gfabs(val - target) <= margin);\n}\n\n/******************************************************************************/\n\n} /* namespace Common */\n} /* namespace Gem */\n", "meta": {"hexsha": "cc475b7c33b500e0ec37a524345e68111232d6ed", "size": 35654, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/GCommonMathHelperFunctionsT.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/common/GCommonMathHelperFunctionsT.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/common/GCommonMathHelperFunctionsT.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": 35.4061569017, "max_line_length": 179, "alphanum_fraction": 0.6223425142, "num_tokens": 9582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04272219861296325, "lm_q1q2_score": 0.021361099306481626}}
{"text": "//\r\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n\r\n\r\n#include \"Mesh_SmoothMesh.h\"\r\n\r\n#include <assert.h>\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <Eigen/Core>\r\n\r\n#pragma warning(push, 0)\r\n#include <igl/adjacency_list.h>\r\n#pragma warning(pop)\r\n\r\n#include \"ConversionUtilities.h\"\r\n#include \"TriMesh.h\"\r\n\r\nusing namespace Urho3D;\r\n\r\nString Mesh_SmoothMesh::iconTexture = \"Textures/Icons/Mesh_SmoothMesh.png\";\r\n\r\nMesh_SmoothMesh::Mesh_SmoothMesh(Context* context) : IoComponentBase(context, 3, 1)\r\n{\r\n\tSetName(\"SmoothMesh\");\r\n\tSetFullName(\"Smooth Mesh\");\r\n\tSetDescription(\"Perform smoothing on triangle mesh\");\r\n\tSetGroup(IoComponentGroup::MESH);\r\n\tSetSubgroup(\"Operators\");\r\n\r\n\tinputSlots_[0]->SetName(\"Mesh\");\r\n\tinputSlots_[0]->SetVariableName(\"M\");\r\n\tinputSlots_[0]->SetDescription(\"Mesh before smoothing\");\r\n\tinputSlots_[0]->SetVariantType(VariantType::VAR_VARIANTMAP);\r\n\tinputSlots_[0]->SetDataAccess(DataAccess::ITEM);\r\n\r\n\tinputSlots_[1]->SetName(\"Iterations\");\r\n\tinputSlots_[1]->SetVariableName(\"I\");\r\n\tinputSlots_[1]->SetDescription(\"Number of smoothing iterations\");\r\n\tinputSlots_[1]->SetVariantType(VariantType::VAR_INT);\r\n\tinputSlots_[1]->SetDataAccess(DataAccess::ITEM);\r\n\tinputSlots_[1]->SetDefaultValue(Variant(1));\r\n\tinputSlots_[1]->DefaultSet();\r\n\r\n\tinputSlots_[2]->SetName(\"Target Factor\");\r\n\tinputSlots_[2]->SetVariableName(\"F\");\r\n\tinputSlots_[2]->SetDescription(\"Move towards smoothed target by factor\");\r\n\tinputSlots_[2]->SetVariantType(VariantType::VAR_FLOAT);\r\n\tinputSlots_[2]->SetDataAccess(DataAccess::ITEM);\r\n\tinputSlots_[2]->SetDefaultValue(Variant(0.5f));\r\n\tinputSlots_[2]->DefaultSet();\r\n\r\n\toutputSlots_[0]->SetName(\"Mesh\");\r\n\toutputSlots_[0]->SetVariableName(\"M\");\r\n\toutputSlots_[0]->SetDescription(\"Mesh after smoothing\");\r\n\toutputSlots_[0]->SetVariantType(VariantType::VAR_VARIANTMAP);\r\n\toutputSlots_[0]->SetDataAccess(DataAccess::ITEM);\r\n}\r\n\r\nvoid Mesh_SmoothMesh::SolveInstance(\r\n\tconst Vector<Variant>& inSolveInstance,\r\n\tVector<Variant>& outSolveInstance\r\n)\r\n{\r\n\tassert(inSolveInstance.Size() == inputSlots_.Size());\r\n\tassert(outSolveInstance.Size() == outputSlots_.Size());\r\n\r\n\t///////////////////\r\n\t// VERIFY & EXTRACT\r\n\r\n\t// Verify input slot 0\r\n\tVariant inMesh = inSolveInstance[0];\r\n\tif (!TriMesh_Verify(inMesh)) {\r\n\t\tURHO3D_LOGWARNING(\"M must be a valid mesh.\");\r\n\t\toutSolveInstance[0] = Variant();\r\n\t\treturn;\r\n\t}\r\n\t// Verify input slot 1\r\n\tVariantType type1 = inSolveInstance[1].GetType();\r\n\tif (type1 != VariantType::VAR_INT) {\r\n\t\tURHO3D_LOGWARNING(\"I must be a valid integer.\");\r\n\t\toutSolveInstance[0] = Variant();\r\n\t\treturn;\r\n\t}\r\n\tint steps = inSolveInstance[1].GetInt();\r\n\tif (steps < 0) {\r\n\t\tsteps = 0;\r\n\t}\r\n\t// Verify input slot 2\r\n\tVariantType type2 = inSolveInstance[2].GetType();\r\n\tif (type2 != VariantType::VAR_FLOAT) {\r\n\t\tURHO3D_LOGWARNING(\"F must be a valid float.\");\r\n\t\toutSolveInstance[0] = Variant();\r\n\t\treturn;\r\n\t}\r\n\tfloat targetFactor = inSolveInstance[2].GetFloat();\r\n\tif (targetFactor < 0.0f || targetFactor > 1.0f) {\r\n\t\tURHO3D_LOGWARNING(\"F must be in range 0 <= F <= 1.\");\r\n\t\toutSolveInstance[0] = Variant();\r\n\t\treturn;\r\n\t}\r\n\r\n\t///////////////////\r\n\t// COMPONENT'S WORK\r\n\r\n\tEigen::MatrixXf V;\r\n\tEigen::MatrixXi F;\r\n\tbool loadSuccess = IglMeshToMatrices(inMesh, V, F);\r\n\tVariant outMesh;\r\n\r\n\tif (loadSuccess) {\r\n\t\tEigen::MatrixXf W = V;\r\n\r\n\t\tstd::vector<std::vector<unsigned> > adj;\r\n\t\tigl::adjacency_list(F, adj);\r\n\r\n\t\tfor (int index = 0; index < steps; ++index) {\r\n\t\t\tfor (unsigned i = 0; i < adj.size(); ++i) {\r\n\t\t\t\tstd::vector<unsigned> cur_adj = adj[i];\r\n\t\t\t\tEigen::RowVector3f v(0.0f, 0.0f, 0.0f);\r\n\t\t\t\tfor (unsigned j = 0; j < cur_adj.size(); ++j) {\r\n\t\t\t\t\tv += W.row(cur_adj[j]);\r\n\t\t\t\t}\r\n\t\t\t\tif (cur_adj.size() > 0) {\r\n\t\t\t\t\tfloat scalar = 1.0f / cur_adj.size();\r\n\t\t\t\t\tv = scalar * v;\r\n\t\t\t\t}\r\n\t\t\t\tW.row(i) = v;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (unsigned i = 0; i < V.rows(); ++i) {\r\n\t\t\tV.row(i) = (1.0f - targetFactor) * V.row(i) + targetFactor * W.row(i);\r\n\t\t}\r\n\t\t//outMesh = IglMatricesToMesh(V, F);\r\n\t\toutMesh = TriMesh_Make(V, F);\r\n\t}\r\n\telse {\r\n\t\tURHO3D_LOGWARNING(\"Smooth operation failed.\");\r\n\t\toutSolveInstance[0] = Variant();\r\n\t\treturn;\r\n\t}\r\n\r\n\t/////////////////\r\n\t// ASSIGN OUTPUTS\r\n\r\n\toutSolveInstance[0] = outMesh;\r\n}\r\n", "meta": {"hexsha": "63fcbcde900471e71e2ac822b45674be7e7c5e27", "size": 5294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Components/Mesh_SmoothMesh.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Components/Mesh_SmoothMesh.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Components/Mesh_SmoothMesh.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 31.325443787, "max_line_length": 84, "alphanum_fraction": 0.679070646, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.05340332904654947, "lm_q1q2_score": 0.0213512726070681}}
{"text": "// \n//  Copyright © 2015 Claus Christmann <hcc |ä| gatech.edu>.\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 __CREATE_DUAL_2D_GRAPH_HPP__\n#define __CREATE_DUAL_2D_GRAPH_HPP__\n \n#include <vector>\n \n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/planar_face_traversal.hpp>\n\n#include \"Geometry/geometry.h\"\n\nnamespace Graph {\n\n  \ntemplate< typename VertexPositionMap,\n          typename Ring  = Geometry::Polygon_2D::ring_type\n        >\nclass FaceGeometry_visitor : public boost::planar_face_traversal_visitor\n{\npublic:  \n  \n  using Point = boost::range_value<Ring>::type;\n  \n  FaceGeometry_visitor(VertexPositionMap vertexPositionMap)\n  :pos_map(vertexPositionMap)\n  {\n    using namespace boost;\n    BOOST_CONCEPT_ASSERT(( geometry::concept::Ring< typename Ring > ));\n    BOOST_CONCEPT_ASSERT(( geometry::concept::Point< typename Point > ));\n    \n//     BOOST_CONCEPT_ASSERT(( ));\n    BOOST_CONCEPT_ASSERT(( geometry::concept::Point< typename property_traits<PositionMap>::value_type >  ));\n  };\n  \n  void begin_face()\n  {\n    // start by creating a new face geometry \n    face_geometry.clear();\n  };\n  \n\n  \n  void end_face()\n  {\n    boost::geometry::correct(face_geometry);\n    geometries.push_back(face_geometry); \n    \n//       std::cout \n//         << boost::geometry::dsv(face_geometry) \n//         << \" -> \" \n//         << boost::geometry::area(face_geometry) << std::endl;\n  };\n  \n  std::vector<FaceGeometry> getFaceGeometries() const\n  { return geometries; };\n  \n  \nprotected:\n  Ring face_geometry;\n  VertexPositionMap pos_map;\n  std::vector<Ring> geometries;\n  \n};  \n  \n  \n/** \\brief A planar graph visitor to extract the 2D positioned dual graph.\n  * \n  * \\note The visitor logic to create the dual graph is copy-and-pasted from \n  * http://aawblog.wordpress.com/2009/12/16/boost-graph-library-planar-dual/\n  * (Retrieved 8/16/2013)\n  * \n  */\ntemplate< typename InputGraph,\n          typename OutputGraph,\n          typename EdgeIndexMap,\n          typename VertexPositionMap>\nclass dual_graph_2D_visitor : public FaceGeometry_visitor<VertexPositionMap>\n{\npublic:\n  \n  using vertex_t  = typename boost::graph_traits<OutputGraph>::vertex_descriptor;\n  using edge_t    = typename boost::graph_traits<InputGraph>::edge_descriptor;\n  using vertex_vector_t = typename std::vector<vertex_t>;\n  using edge_to_face_map_t = boost::iterator_property_map< typename vertex_vector_t::iterator, EdgeIndexMap >;\n\n  dual_graph_2D_visitor(InputGraph& graph_in,\n                        OutputGraph& graphDual_out,\n                        EdgeIndexMap edgeIndexMap,\n                        VertexPositionMap vertexPosMap\n                        )\n    :FaceGeometry_visitor<VertexPositionMap>(vertexPosMap)\n    ,g(graph_in)\n    ,dual_g(graphDual_out)\n    ,em(edgeIndexMap)\n    ,edge_to_face_vector(boost::num_edges(g), boost::graph_traits<OutputGraph>::null_vertex())\n    ,edge_to_face( edge_to_face_vector.begin(), em)\n  {};\n  ~dual_graph_2D_visitor() = default;\n  \n  void begin_face()\n  {\n    FaceGeometry_visitor<VertexPositionMap>::begin_face();\n    current_face = boost::add_vertex(dual_g);\n  };\n  \n  template< typename Edge >\n  void next_edge(Edge e)\n  {\n    vertex_t existing_face = edge_to_face[e];\n    if (existing_face == boost::graph_traits<OutputGraph>::null_vertex())\n    {\n      edge_to_face[e] = current_face;\n    }\n    else\n    {\n      boost::add_edge(existing_face, current_face, dual_g);\n    }\n  };\n  \n  void end_face()\n  {\n    FaceGeometry_visitor<VertexPositionMap>::end_face();\n    Geometry::Point_2D face_centroid;\n    boost::geometry::centroid(FaceGeometry_visitor<VertexPositionMap>::face_geometry,face_centroid);\n    \n    boost::put(boost::vertex_position_2D,dual_g,current_face,face_centroid);\n  };\n  \nprotected:\n  \n  \n  InputGraph& g; ///< \\brief The Voronoi graph.\n  OutputGraph& dual_g; ///< \\brief  The obstacle graph.\n  EdgeIndexMap em;\n  vertex_t current_face; ///< \\brief The currently processed face of the Voronoi graph.\n  vertex_vector_t edge_to_face_vector;\n  edge_to_face_map_t edge_to_face;\n};\n\n\ntemplate <typename InputGraph,\n          typename OutputGraph,\n          typename PlanarEmbedding,\n          typename EdgeIndexMap,\n          typename VertexPositionMap\n          >\nvoid create_dual_2D_graph(InputGraph& g,\n                          OutputGraph& dual_g,\n                          PlanarEmbedding embedding,\n                          EdgeIndexMap em,\n                          VertexPositionMap pm)\n{\n  using namespace boost;\n\n  dual_graph_2D_visitor<InputGraph, OutputGraph, EdgeIndexMap, VertexPositionMap>\n  visitor(g, dual_g, em, pm);\n  planar_face_traversal(g, embedding, visitor, em);\n}\n\ntemplate <typename InputGraph,\n          typename OutputGraph,\n          typename PlanarEmbedding\n          >\nvoid create_dual_2D_graph(InputGraph& g,\n                          OutputGraph& dual_g,\n                          PlanarEmbedding embedding\n                          )\n{\n  using namespace boost;\n  create_dual_2D_graph(g, dual_g, embedding,\n                        get(edge_index,g),\n                        get(vertex_position_2D,g)\n                      );\n}\n\n  \n} // namespace Graph\n \n#endif //__CREATE_DUAL_2D_GRAPH_HPP__", "meta": {"hexsha": "4555a2bb25aa5613694b0338a95c9eaeadf1955a", "size": 5791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/Graph/dual_2D_graph.hpp", "max_stars_repo_name": "mvsframework/mvs", "max_stars_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "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/core/Graph/dual_2D_graph.hpp", "max_issues_repo_name": "mvsframework/mvs", "max_issues_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/Graph/dual_2D_graph.hpp", "max_forks_repo_name": "mvsframework/mvs", "max_forks_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "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.5459183673, "max_line_length": 110, "alphanum_fraction": 0.6738041789, "num_tokens": 1353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.04336580092752893, "lm_q1q2_score": 0.021344132712559614}}
{"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 followig 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/* ============================================================================\n * DerivativeHelpers re-implements the exterior derivative calculations\n * from the following vtk modules:\n *\n * * vtkLine.cxx\n *   - re-implemented vtkLine::Derivatives to EdgeDeriv::operator()\n * * vtkTriangle.cxx\n *   - re-implemented vtkTriangle::Derivatives to TriangleDeriv::operator()\n * * vtkQuad.cxx\n *   - re-implemented vtkQuad::Derivatives to QuadDeriv::operator()\n * * vtkTetra.cxx\n *   - re-implemented vtkTetra::Derivatives to TetDeriv::operator()\n * * vtkHexahedron.cxx\n *   - re-implemented vtkHexahedron::Derivatives to HexDeriv::operator()\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n#include \"DerivativeHelpers.h\"\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\n#include \"SIMPLib/Geometry/EdgeGeom.h\"\n#include \"SIMPLib/Geometry/HexahedralGeom.h\"\n#include \"SIMPLib/Geometry/QuadGeom.h\"\n#include \"SIMPLib/Geometry/TetrahedralGeom.h\"\n#include \"SIMPLib/Geometry/TriangleGeom.h\"\n#include \"SIMPLib/Math/GeometryMath.h\"\n#include \"SIMPLib/Math/MatrixMath.h\"\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DerivativeHelpers::EdgeDeriv::operator()(EdgeGeom* edges, size_t edgeId, double values[2], double derivs[3])\n{\n  float vert0_f[3] = {0.0f, 0.0f, 0.0f};\n  float vert1_f[3] = {0.0f, 0.0f, 0.0f};\n  double vert0[3] = {0.0, 0.0, 0.0};\n  double vert1[3] = {0.0, 0.0, 0.0};\n  double delta[3] = {0.0, 0.0, 0.0};\n  size_t verts[2] = {0, 0};\n\n  edges->getVertsAtEdge(edgeId, verts);\n  edges->getCoords(verts[0], vert0_f);\n  edges->getCoords(verts[1], vert1_f);\n\n  std::copy(vert0_f, vert0_f + 3, vert0);\n  std::copy(vert1_f, vert1_f + 3, vert1);\n\n  for(size_t i = 0; i < 3; i++)\n  {\n    delta[i] = vert1[i] - vert0[i];\n  }\n\n  for(size_t i = 0; i < 3; i++)\n  {\n    if(delta[i] != 0.0)\n    {\n      derivs[i] = (values[1] - values[0]) / delta[i];\n    }\n    else\n    {\n      derivs[i] = 0.0;\n    }\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DerivativeHelpers::TriangleDeriv::operator()(TriangleGeom* triangles, size_t triId, double values[3], double derivs[3])\n{\n  float vert0_f[3] = {0.0f, 0.0f, 0.0f};\n  float vert1_f[3] = {0.0f, 0.0f, 0.0f};\n  float vert2_f[3] = {0.0f, 0.0f, 0.0f};\n  double vert0[3] = {0.0, 0.0, 0.0};\n  double vert1[3] = {0.0, 0.0, 0.0};\n  double vert2[3] = {0.0, 0.0, 0.0};\n  double vert0_2d[2] = {0.0, 0.0};\n  double vert1_2d[2] = {0.0, 0.0};\n  double vert2_2d[2] = {0.0, 0.0};\n  double vector20[3] = {0.0, 0.0, 0.0};\n  double basis1[3] = {0.0, 0.0, 0.0};\n  double basis2[3] = {0.0, 0.0, 0.0};\n  double mag_basis1 = 0.0;\n  double mag_basis2 = 0.0;\n  double normal[3] = {0.0, 0.0, 0.0};\n  double shapeFunctions[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n  double sum[2] = {0.0, 0.0};\n  double dBydx = 0.0;\n  double dBydy = 0.0;\n  size_t verts[3] = {0, 0, 0};\n\n  triangles->getVertsAtTri(triId, verts);\n  triangles->getCoords(verts[0], vert0_f);\n  triangles->getCoords(verts[1], vert1_f);\n  triangles->getCoords(verts[2], vert2_f);\n\n  std::copy(vert0_f, vert0_f + 3, vert0);\n  std::copy(vert1_f, vert1_f + 3, vert1);\n  std::copy(vert2_f, vert2_f + 3, vert2);\n\n  GeometryMath::FindPlaneNormalVector(vert0, vert1, vert2, normal);\n  MatrixMath::Normalize3x1(normal);\n\n  for(size_t i = 0; i < 3; i++)\n  {\n    basis1[i] = vert1[i] - vert0[i];\n    vector20[i] = vert2[i] - vert0[i];\n  }\n\n  MatrixMath::CrossProduct(normal, basis1, basis2);\n\n  mag_basis1 = MatrixMath::Magnitude3x1(basis1);\n  mag_basis2 = MatrixMath::Magnitude3x1(basis2);\n\n  if(mag_basis1 <= 0.0 || mag_basis2 <= 0.0)\n  {\n    for(size_t i = 0; i < 3; i++)\n    {\n      derivs[i] = 0.0;\n    }\n    return;\n  }\n\n  MatrixMath::Normalize3x1(basis1);\n  MatrixMath::Normalize3x1(basis2);\n\n  // Project the 3D triangle onto a 2D local system\n  // Basis vectors for 2D system are the vector between triangle vertex 1 and 0 (basis1)\n  // and the normal of the plane defined by the triangle normal and basis1 (basis2)\n  vert0_2d[0] = vert0_2d[1] = 0.0;\n  vert1_2d[0] = mag_basis1;\n  vert1_2d[1] = 0.0;\n  vert2_2d[0] = MatrixMath::DotProduct3x1(vector20, basis1);\n  vert2_2d[1] = MatrixMath::DotProduct3x1(vector20, basis2);\n\n  // Compute interpolation function derivatives\n  triangles->getShapeFunctions(nullptr, shapeFunctions);\n\n  // Compute Jacobian and inverse Jacobian using Eigen\n  // Jacobian is constant for a triangle, so inverse must exist\n  double jPtr[4] = {0.0, 0.0, 0.0, 0.0};\n\n  jPtr[0] = vert1_2d[0] - vert0_2d[0];\n  jPtr[1] = vert1_2d[1] - vert0_2d[1];\n  jPtr[2] = vert2_2d[0] - vert0_2d[0];\n  jPtr[3] = vert2_2d[1] - vert0_2d[1];\n\n  Eigen::Map<TriangleJacobian> jMat(jPtr);\n  TriangleJacobian jMatI;\n\n  jMatI = jMat.inverse();\n\n  // Loop over derivative values. For each set of values, compute\n  // derivatives in local 2D system and then transform into original 3D system\n  for(size_t i = 0; i < 3; i++)\n  {\n    sum[0] += shapeFunctions[i] * values[i];\n    sum[1] += shapeFunctions[3 + i] * values[i];\n  }\n\n  dBydx = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1);\n  dBydy = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1);\n\n  derivs[0] = dBydx * basis1[0] + dBydy * basis2[0];\n  derivs[1] = dBydx * basis1[1] + dBydy * basis2[1];\n  derivs[2] = dBydx * basis1[2] + dBydy * basis2[2];\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DerivativeHelpers::QuadDeriv::operator()(QuadGeom* quads, size_t quadId, double values[4], double derivs[3])\n{\n  float vert0_f[3] = {0.0f, 0.0f, 0.0f};\n  float vert1_f[3] = {0.0f, 0.0f, 0.0f};\n  float vert2_f[3] = {0.0f, 0.0f, 0.0f};\n  float vert3_f[3] = {0.0f, 0.0f, 0.0f};\n  double vert0[3] = {0.0, 0.0, 0.0};\n  double vert1[3] = {0.0, 0.0, 0.0};\n  double vert2[3] = {0.0, 0.0, 0.0};\n  double vert3[3] = {0.0, 0.0, 0.0};\n  double vert0_2d[2] = {0.0, 0.0};\n  double vert1_2d[2] = {0.0, 0.0};\n  double vert2_2d[2] = {0.0, 0.0};\n  double vert3_2d[2] = {0.0, 0.0};\n  double vector20[3] = {0.0, 0.0, 0.0};\n  double vector30[3] = {0.0, 0.0, 0.0};\n  double basis1[3] = {0.0, 0.0, 0.0};\n  double basis2[3] = {0.0, 0.0, 0.0};\n  double mag_basis1 = 0.0;\n  double mag_basis2 = 0.0;\n  double normal[3] = {0.0, 0.0, 0.0};\n  double shapeFunctions[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n  double pCoords[3]{0.0, 0.0, 0.0};\n  double sum[2] = {0.0, 0.0};\n  double dBydx = 0.0;\n  double dBydy = 0.0;\n  size_t verts[4] = {0, 0, 0, 0};\n\n  quads->getVertsAtQuad(quadId, verts);\n  quads->getCoords(verts[0], vert0_f);\n  quads->getCoords(verts[1], vert1_f);\n  quads->getCoords(verts[2], vert2_f);\n  quads->getCoords(verts[3], vert3_f);\n\n  std::copy(vert0_f, vert0_f + 3, vert0);\n  std::copy(vert1_f, vert1_f + 3, vert1);\n  std::copy(vert2_f, vert2_f + 3, vert2);\n  std::copy(vert3_f, vert3_f + 3, vert3);\n\n  GeometryMath::FindPlaneNormalVector(vert0, vert1, vert2, normal);\n  MatrixMath::Normalize3x1(normal);\n\n  // If vertices 0, 1, & 2 are co-linear, use vertex 3 to find the normal\n  if(normal[0] == 0.0 && normal[1] == 0.0 && normal[2] == 0.0)\n  {\n    GeometryMath::FindPlaneNormalVector(vert0, vert1, vert2, normal);\n    MatrixMath::Normalize3x1(normal);\n  }\n\n  for(size_t i = 0; i < 3; i++)\n  {\n    basis1[i] = vert1[i] - vert0[i];\n    vector20[i] = vert2[i] - vert0[i];\n    vector30[i] = vert3[i] - vert0[i];\n  }\n\n  MatrixMath::CrossProduct(normal, basis1, basis2);\n\n  mag_basis1 = MatrixMath::Magnitude3x1(basis1);\n  mag_basis2 = MatrixMath::Magnitude3x1(basis2);\n\n  if(mag_basis1 <= 0.0 || mag_basis2 <= 0.0)\n  {\n    for(size_t i = 0; i < 3; i++)\n    {\n      derivs[i] = 0.0;\n    }\n    return;\n  }\n\n  MatrixMath::Normalize3x1(basis1);\n  MatrixMath::Normalize3x1(basis2);\n\n  // Project the 3D quad onto a 2D local system\n  // Basis vectors for 2D system are the vector between quad vertex 1 and 0 (basis1)\n  // and the normal of the plane defined by the quad normal and basis1 (basis2)\n  vert0_2d[0] = vert0_2d[1] = 0.0;\n  vert1_2d[0] = mag_basis1;\n  vert1_2d[1] = 0.0;\n  vert2_2d[0] = MatrixMath::DotProduct3x1(vector20, basis1);\n  vert2_2d[1] = MatrixMath::DotProduct3x1(vector20, basis2);\n  vert3_2d[0] = MatrixMath::DotProduct3x1(vector30, basis1);\n  vert3_2d[1] = MatrixMath::DotProduct3x1(vector30, basis2);\n\n  quads->getParametricCenter(pCoords);\n  quads->getShapeFunctions(pCoords, shapeFunctions);\n\n  // Compute Jacobian and inverse Jacobian using Eigen\n  double jPtr[4] = {0.0, 0.0, 0.0, 0.0};\n\n  jPtr[0] = vert0_2d[0] * shapeFunctions[0] + vert1_2d[0] * shapeFunctions[1] + vert2_2d[0] * shapeFunctions[2] + vert3_2d[0] * shapeFunctions[3];\n  jPtr[1] = vert0_2d[1] * shapeFunctions[0] + vert1_2d[1] * shapeFunctions[1] + vert2_2d[1] * shapeFunctions[2] + vert3_2d[1] * shapeFunctions[3];\n  jPtr[2] = vert0_2d[0] * shapeFunctions[4] + vert1_2d[0] * shapeFunctions[5] + vert2_2d[0] * shapeFunctions[6] + vert3_2d[0] * shapeFunctions[7];\n  jPtr[3] = vert0_2d[1] * shapeFunctions[4] + vert1_2d[1] * shapeFunctions[5] + vert2_2d[1] * shapeFunctions[6] + vert3_2d[1] * shapeFunctions[7];\n\n  Eigen::Map<QuadJacobian> jMat(jPtr);\n  QuadJacobian jMatI;\n  bool invertible = false;\n\n  jMat.computeInverseWithCheck(jMatI, invertible);\n\n  // Jacobian is non-constant for a quad, so must check if inverse exists\n  // If the Jacobian is not invertible, set derivatives to 0\n  if(!invertible)\n  {\n    for(size_t i = 0; i < 3; i++)\n    {\n      derivs[i] = 0.0;\n    }\n  }\n\n  // Loop over derivative values. For each set of values, compute\n  // derivatives in local 2D system and then transform into original 3D system\n  for(size_t i = 0; i < 4; i++)\n  {\n    sum[0] += shapeFunctions[i] * values[i];\n    sum[1] += shapeFunctions[4 + i] * values[i];\n  }\n\n  dBydx = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1);\n  dBydy = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1);\n\n  derivs[0] = dBydx * basis1[0] + dBydy * basis2[0];\n  derivs[1] = dBydx * basis1[1] + dBydy * basis2[1];\n  derivs[2] = dBydx * basis1[2] + dBydy * basis2[2];\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DerivativeHelpers::TetDeriv::operator()(TetrahedralGeom* tets, size_t tetId, double values[4], double derivs[3])\n{\n  double shapeFunctions[12] = {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  size_t verts[4] = {0, 0, 0, 0};\n  double sum[3] = {0.0, 0.0, 0.0};\n\n  tets->getShapeFunctions(nullptr, shapeFunctions);\n\n  // Compute 3x3 Jacobian from vertex coordinates and tet shape functions,\n  // then find the inverse Jacobian using Eigen\n  double jPtr[9] = {\n      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n  };\n\n  tets->getVertsAtTet(tetId, verts);\n\n  for(size_t i = 0; i < 4; i++)\n  {\n    float tmpCoords_f[3] = {0.0, 0.0, 0.0};\n    double tmpCoords[3] = {0.0, 0.0, 0.0};\n    tets->getCoords(verts[i], tmpCoords_f);\n    std::copy(tmpCoords_f, tmpCoords_f + 3, tmpCoords);\n    for(size_t j = 0; j < 3; j++)\n    {\n      jPtr[j] += tmpCoords[j] * shapeFunctions[i];\n      jPtr[j + 3] += tmpCoords[j] * shapeFunctions[4 + i];\n      jPtr[j + 6] += tmpCoords[j] * shapeFunctions[8 + i];\n    }\n  }\n\n  Eigen::Map<TetJacobian> jMat(jPtr);\n  TetJacobian jMatI;\n  bool invertible = false;\n\n  jMat.computeInverseWithCheck(jMatI, invertible);\n\n  // Jacobian is non-constant for a tet, so must check if inverse exists\n  // If the Jacobian is not invertible, set derivatives to 0\n  if(!invertible)\n  {\n    for(size_t i = 0; i < 3; i++)\n    {\n      derivs[i] = 0.0;\n    }\n  }\n\n  for(size_t i = 0; i < 4; i++)\n  {\n    sum[0] += shapeFunctions[i] * values[i];\n    sum[1] += shapeFunctions[4 + i] * values[i];\n    sum[2] += shapeFunctions[8 + i] * values[i];\n  }\n\n  derivs[0] = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1) + sum[2] * jMatI(0, 2);\n  derivs[1] = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1) + sum[2] * jMatI(1, 2);\n  derivs[2] = sum[0] * jMatI(2, 0) + sum[1] * jMatI(2, 1) + sum[2] * jMatI(2, 2);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid DerivativeHelpers::HexDeriv::operator()(HexahedralGeom* hexas, size_t hexId, double values[8], double derivs[3])\n{\n  double shapeFunctions[24] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n  size_t verts[8] = {0, 0, 0, 0, 0, 0, 0, 0};\n  double sum[3] = {0.0, 0.0, 0.0};\n  double pCoords[3] = {0.0, 0.0, 0.0};\n\n  hexas->getParametricCenter(pCoords);\n  hexas->getShapeFunctions(pCoords, shapeFunctions);\n\n  // Compute 3x3 Jacobian from vertex coordinates and tet shape functions,\n  // then find the inverse Jacobian using Eigen\n  double jPtr[9] = {\n      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n  };\n\n  hexas->getVertsAtHex(hexId, verts);\n\n  for(size_t i = 0; i < 8; i++)\n  {\n    float tmpCoords_f[3] = {0.0, 0.0, 0.0};\n    double tmpCoords[3] = {0.0, 0.0, 0.0};\n    hexas->getCoords(verts[i], tmpCoords_f);\n    std::copy(tmpCoords_f, tmpCoords_f + 3, tmpCoords);\n    for(size_t j = 0; j < 3; j++)\n    {\n      jPtr[j] += tmpCoords[j] * shapeFunctions[i];\n      jPtr[j + 3] += tmpCoords[j] * shapeFunctions[8 + i];\n      jPtr[j + 6] += tmpCoords[j] * shapeFunctions[16 + i];\n    }\n  }\n\n  Eigen::Map<HexJacobian> jMat(jPtr);\n  HexJacobian jMatI;\n  bool invertible = false;\n\n  jMat.computeInverseWithCheck(jMatI, invertible);\n\n  // Jacobian is non-constant for a tet, so must check if inverse exists\n  // If the Jacobian is not invertible, set derivatives to 0\n  if(!invertible)\n  {\n    for(size_t i = 0; i < 3; i++)\n    {\n      derivs[i] = 0.0;\n    }\n  }\n\n  for(size_t i = 0; i < 8; i++)\n  {\n    sum[0] += shapeFunctions[i] * values[i];\n    sum[1] += shapeFunctions[8 + i] * values[i];\n    sum[2] += shapeFunctions[16 + i] * values[i];\n  }\n\n  derivs[0] = sum[0] * jMatI(0, 0) + sum[1] * jMatI(0, 1) + sum[2] * jMatI(0, 2);\n  derivs[1] = sum[0] * jMatI(1, 0) + sum[1] * jMatI(1, 1) + sum[2] * jMatI(1, 2);\n  derivs[2] = sum[0] * jMatI(2, 0) + sum[1] * jMatI(2, 1) + sum[2] * jMatI(2, 2);\n}\n", "meta": {"hexsha": "51d28944b7aa18b6ef4a9df0461dac25657a36ac", "size": 16238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/SIMPLib/Geometry/DerivativeHelpers.cpp", "max_stars_repo_name": "jmarquisbq/SIMPL", "max_stars_repo_head_hexsha": "375653013742cfe9aed603fc9a6bab6d9c96be31", "max_stars_repo_licenses": ["NRL"], "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/SIMPLib/Geometry/DerivativeHelpers.cpp", "max_issues_repo_name": "jmarquisbq/SIMPL", "max_issues_repo_head_hexsha": "375653013742cfe9aed603fc9a6bab6d9c96be31", "max_issues_repo_licenses": ["NRL"], "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/SIMPLib/Geometry/DerivativeHelpers.cpp", "max_forks_repo_name": "jmarquisbq/SIMPL", "max_forks_repo_head_hexsha": "375653013742cfe9aed603fc9a6bab6d9c96be31", "max_forks_repo_licenses": ["NRL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4541484716, "max_line_length": 151, "alphanum_fraction": 0.5938539229, "num_tokens": 6004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04336580077298449, "lm_q1q2_score": 0.02134413263649467}}
{"text": "#ifndef BOOST_QVM_GEN_VEC_OPERATIONS3_HPP_INCLUDED\n#define BOOST_QVM_GEN_VEC_OPERATIONS3_HPP_INCLUDED\n\n/// Copyright (c) 2008-2021 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/// 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_assign3.hpp>\n#include <boost/qvm/math.hpp>\n#include <boost/qvm/static_assert.hpp>\n#include <boost/qvm/throw_exception.hpp>\n\nnamespace boost { namespace qvm {\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\n    deduce_vec2<A,B,3> >::type\noperator+( A const & a, B const & b )\n    {\n    typedef typename deduce_vec2<A,B,3>::type R;\n    BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim==3);\n    R r;\n    vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)+vec_traits<B>::template read_element<0>(b);\n    vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)+vec_traits<B>::template read_element<1>(b);\n    vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)+vec_traits<B>::template read_element<2>(b);\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator+;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct plus_vv_defined;\n\n    template <>\n    struct\n    plus_vv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\n    deduce_vec2<A,B,3> >::type\noperator-( A const & a, B const & b )\n    {\n    typedef typename deduce_vec2<A,B,3>::type R;\n    BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim==3);\n    R r;\n    vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)-vec_traits<B>::template read_element<0>(b);\n    vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)-vec_traits<B>::template read_element<1>(b);\n    vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)-vec_traits<B>::template read_element<2>(b);\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator-;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct minus_vv_defined;\n\n    template <>\n    struct\n    minus_vv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\n    A &>::type\noperator+=( A & a, B const & b )\n    {\n    vec_traits<A>::template write_element<0>(a)+=vec_traits<B>::template read_element<0>(b);\n    vec_traits<A>::template write_element<1>(a)+=vec_traits<B>::template read_element<1>(b);\n    vec_traits<A>::template write_element<2>(a)+=vec_traits<B>::template read_element<2>(b);\n    return a;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator+=;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct plus_eq_vv_defined;\n\n    template <>\n    struct\n    plus_eq_vv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\n    A &>::type\noperator-=( A & a, B const & b )\n    {\n    vec_traits<A>::template write_element<0>(a)-=vec_traits<B>::template read_element<0>(b);\n    vec_traits<A>::template write_element<1>(a)-=vec_traits<B>::template read_element<1>(b);\n    vec_traits<A>::template write_element<2>(a)-=vec_traits<B>::template read_element<2>(b);\n    return a;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator-=;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct minus_eq_vv_defined;\n\n    template <>\n    struct\n    minus_eq_vv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    vec_traits<A>::dim==3 && is_scalar<B>::value,\n    deduce_vec2<A,B,vec_traits<A>::dim> >::type\noperator*( A const & a, B b )\n    {\n    typedef typename deduce_vec2<A,B,vec_traits<A>::dim>::type R;\n    R r;\n    vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)*b;\n    vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)*b;\n    vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)*b;\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator*;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct mul_vs_defined;\n\n    template <>\n    struct\n    mul_vs_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    is_scalar<A>::value && vec_traits<B>::dim==3,\n    deduce_vec2<A,B,vec_traits<B>::dim> >::type\noperator*( A a, B const & b )\n    {\n    typedef typename deduce_vec2<A,B,vec_traits<B>::dim>::type R;\n    R r;\n    vec_traits<R>::template write_element<0>(r)=a*vec_traits<B>::template read_element<0>(b);\n    vec_traits<R>::template write_element<1>(r)=a*vec_traits<B>::template read_element<1>(b);\n    vec_traits<R>::template write_element<2>(r)=a*vec_traits<B>::template read_element<2>(b);\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator*;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct mul_sv_defined;\n\n    template <>\n    struct\n    mul_sv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class  B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    vec_traits<A>::dim==3 && is_scalar<B>::value,\n    A &>::type\noperator*=( A & a, B b )\n    {\n    vec_traits<A>::template write_element<0>(a)*=b;\n    vec_traits<A>::template write_element<1>(a)*=b;\n    vec_traits<A>::template write_element<2>(a)*=b;\n    return a;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator*=;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct mul_eq_vs_defined;\n\n    template <>\n    struct\n    mul_eq_vs_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    vec_traits<A>::dim==3 && is_scalar<B>::value,\n    deduce_vec2<A,B,vec_traits<A>::dim> >::type\noperator/( A const & a, B b )\n    {\n    typedef typename deduce_vec2<A,B,vec_traits<A>::dim>::type R;\n    R r;\n    vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)/b;\n    vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)/b;\n    vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)/b;\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator/;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct div_vs_defined;\n\n    template <>\n    struct\n    div_vs_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class  B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    vec_traits<A>::dim==3 && is_scalar<B>::value,\n    A &>::type\noperator/=( A & a, B b )\n    {\n    vec_traits<A>::template write_element<0>(a)/=b;\n    vec_traits<A>::template write_element<1>(a)/=b;\n    vec_traits<A>::template write_element<2>(a)/=b;\n    return a;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator/=;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct div_eq_vs_defined;\n\n    template <>\n    struct\n    div_eq_vs_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class R,class A>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    is_vec<A>::value &&\n    vec_traits<R>::dim==3 && vec_traits<A>::dim==3,\n    R>::type\nconvert_to( A const & a )\n    {\n    R r;\n    vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a);\n    vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a);\n    vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a);\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::convert_to;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct convert_to_v_defined;\n\n    template <>\n    struct\n    convert_to_v_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\nbool>::type\noperator==( A const & a, B const & b )\n    {\n    return\n        vec_traits<A>::template read_element<0>(a)==vec_traits<B>::template read_element<0>(b) &&\n        vec_traits<A>::template read_element<1>(a)==vec_traits<B>::template read_element<1>(b) &&\n        vec_traits<A>::template read_element<2>(a)==vec_traits<B>::template read_element<2>(b);\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator==;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct eq_vv_defined;\n\n    template <>\n    struct\n    eq_vv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\nbool>::type\noperator!=( A const & a, B const & b )\n    {\n    return\n        !(vec_traits<A>::template read_element<0>(a)==vec_traits<B>::template read_element<0>(b)) ||\n        !(vec_traits<A>::template read_element<1>(a)==vec_traits<B>::template read_element<1>(b)) ||\n        !(vec_traits<A>::template read_element<2>(a)==vec_traits<B>::template read_element<2>(b));\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator!=;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct neq_vv_defined;\n\n    template <>\n    struct\n    neq_vv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    vec_traits<A>::dim==3,\n    deduce_vec<A> >::type\noperator-( A const & a )\n    {\n    typedef typename deduce_vec<A>::type R;\n    R r;\n    vec_traits<R>::template write_element<0>(r)=-vec_traits<A>::template read_element<0>(a);\n    vec_traits<R>::template write_element<1>(r)=-vec_traits<A>::template read_element<1>(a);\n    vec_traits<R>::template write_element<2>(r)=-vec_traits<A>::template read_element<2>(a);\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::operator-;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct minus_v_defined;\n\n    template <>\n    struct\n    minus_v_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    is_vec<A>::value && vec_traits<A>::dim==3,\n    typename vec_traits<A>::scalar_type>::type\nmag( A const & a )\n    {\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 a2=vec_traits<A>::template read_element<2>(a);\n    T const m2=a0*a0+a1*a1+a2*a2;\n    T const mag=sqrt(m2);\n    return mag;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::mag;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct mag_v_defined;\n\n    template <>\n    struct\n    mag_v_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    is_vec<A>::value && vec_traits<A>::dim==3,\n    typename vec_traits<A>::scalar_type>::type\nmag_sqr( A const & a )\n    {\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 a2=vec_traits<A>::template read_element<2>(a);\n    T const m2=a0*a0+a1*a1+a2*a2;\n    return m2;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::mag_sqr;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct mag_sqr_v_defined;\n\n    template <>\n    struct\n    mag_sqr_v_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    vec_traits<A>::dim==3,\n    deduce_vec<A> >::type\nnormalized( A const & a )\n    {\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 a2=vec_traits<A>::template read_element<2>(a);\n    T const m2=a0*a0+a1*a1+a2*a2;\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(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    vec_traits<R>::template write_element<2>(r)=a2*rm;\n    return r;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::normalized;\n    }\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\ntypename enable_if_c<\n    vec_traits<A>::dim==3,\n    void>::type\nnormalize( A & a )\n    {\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 a2=vec_traits<A>::template read_element<2>(a);\n    T const m2=a0*a0+a1*a1+a2*a2;\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(m2);\n    vec_traits<A>::template write_element<0>(a)*=rm;\n    vec_traits<A>::template write_element<1>(a)*=rm;\n    vec_traits<A>::template write_element<2>(a)*=rm;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::normalize;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct normalize_v_defined;\n\n    template <>\n    struct\n    normalize_v_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\ntemplate <class A,class B>\nBOOST_QVM_INLINE_OPERATIONS\ntypename lazy_enable_if_c<\n    vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\n    deduce_scalar<typename vec_traits<A>::scalar_type,typename vec_traits<B>::scalar_type> >::type\ndot( A const & a, B const & b )\n    {\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    Ta const a2=vec_traits<A>::template read_element<2>(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    Tb const b2=vec_traits<B>::template read_element<2>(b);\n    Tr const dot=a0*b0+a1*b1+a2*b2;\n    return dot;\n    }\n\nnamespace\nsfinae\n    {\n    using ::boost::qvm::dot;\n    }\n\nnamespace\nqvm_detail\n    {\n    template <int D>\n    struct dot_vv_defined;\n\n    template <>\n    struct\n    dot_vv_defined<3>\n        {\n        static bool const value=true;\n        };\n    }\n\n} }\n\n#endif\n", "meta": {"hexsha": "33bf60eae191700a2be0d38a7ebd67263926c663", "size": 15547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/qvm/gen/vec_operations3.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": "2019-10-27T21:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T21:15:52.000Z", "max_issues_repo_path": "lib/boost_1.78.0/boost/qvm/gen/vec_operations3.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-12-07T22:56:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T22:13:37.000Z", "max_forks_repo_path": "lib/boost_1.78.0/boost/qvm/gen/vec_operations3.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-07-30T12:45:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T11:18:30.000Z", "avg_line_length": 23.9553158706, "max_line_length": 134, "alphanum_fraction": 0.6488711649, "num_tokens": 4383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800991636031, "lm_q2_score": 0.04401865378204584, "lm_q1q2_score": 0.021321759883995678}}
{"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_CRTP_BASE_VECTOR_INCLUDE\n#define MTL_CRTP_BASE_VECTOR_INCLUDE\n\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/type_traits/is_base_of.hpp>\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/vector/all_vec_expr.hpp>\n#include <boost/numeric/mtl/vector/assigner.hpp>\n#include <boost/numeric/mtl/vector/decrementer.hpp>\n#include <boost/numeric/mtl/vector/incrementer.hpp>\n#include <boost/numeric/mtl/operation/mat_cvec_times_expr.hpp>\n#include <boost/numeric/mtl/operation/mult.hpp>\n#include <boost/numeric/mtl/operation/mat_vec_mult.hpp>\n#include <boost/numeric/mtl/operation/mult_assign_mode.hpp>\n#include <boost/numeric/mtl/operation/right_scale_inplace.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/flatcat.hpp>\n#include <boost/numeric/mtl/utility/is_distributed.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n\n#include <boost/numeric/itl/itl_fwd.hpp>\n\nnamespace mtl { namespace vector {\n\n\nnamespace detail {\n\n    template <typename Vector, typename Source, typename SCat, typename VCat>\n    struct crtp_assign {};\t\n\n    /// Assign scalar to a vector by setting all values to the scalar\n    template <typename Vector, typename Source, typename VCat>\n    struct crtp_assign<Vector, Source, VCat, ashape::scal>\n    {\n\ttypedef vec_scal_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type(vector, src);\n\t}\n    };\t\n\n    /// Assign vector to a vector\n    template <typename Vector, typename Source, typename Cat>\n    struct crtp_assign<Vector, Source, Cat, Cat>\n    {\n\ttypedef vec_vec_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type(vector, src);\n\t}\n    };\t\n\n    template <typename Vector, typename Source>\n    struct assign_assigner\n    {\n\ttypedef const Vector& type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    src.assign_to(vector);\n\t    return vector;\n\t}\n    };\n\n} // namespace detail\n\ntemplate <typename Vector, typename Source>\nstruct crtp_assign \n  : boost::mpl::if_\n     <boost::is_base_of<assigner_base, Source>,\n      detail::assign_assigner <Vector, Source>, \n      detail::crtp_assign<Vector, Source, typename ashape::ashape<Vector>::type, typename ashape::ashape<Source>::type>\n     >::type\n{};\n\n/// Assign matrix vector product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_assign<Vector, mat_cvec_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src)\n    {\n\tvector.checked_change_resource(src);\n\tset_to_zero(vector);\n\tmat_cvec_mult(src.first, src.second, vector, assign::assign_sum(), traits::mat_cvec_flatcat<E1>());\n\treturn vector;\n    }\n};\n\n\n/// Assign vector matrix product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_assign<Vector, rvec_mat_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src)\n    {\n\tvector.checked_change_resource(src);\n\trvec_mat_mult(src.first, src.second, vector, assign::assign_sum(), traits::mat_cvec_flatcat<E2>());\n\treturn vector;\n    }\n};\n\n/// Assign c-style 1D-array, because it's easier to initialize.\ntemplate <typename Vector, typename Value, unsigned Rows>\nstruct crtp_assign<Vector, Value[Rows]>\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const Value src[Rows])\n    {\n\ttypedef typename Collection<Vector>::size_type size_type;\n\t\n\tvector.checked_change_dim(Rows);\n\n\tfor (size_type r= 0; r < Rows; ++r)\n\t    vector[r]= src[r];\n\treturn vector;\n    }\n};\n\n\nnamespace detail {\n\n    template <typename Vector, typename Source, typename SCat, typename VCat>\n    struct crtp_plus_assign {};\t\n\n    /// Assign-add vector to a vector\n    template <typename Vector, typename Source, typename Cat>\n    struct crtp_plus_assign<Vector, Source, Cat, Cat>\n    {\n\ttypedef vec_vec_plus_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type( vector, src );\n\t}\n    };\t\n\n    /// Increment a vector by a scalar\n    template <typename Vector, typename Source, typename VCat>\n    struct crtp_plus_assign<Vector, Source, VCat, ashape::scal>\n    {\n\ttypedef vec_scal_plus_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type(vector, src);\n\t}\n    };\t\n\n    template <typename Vector, typename Source>\n    struct assign_incrementer\n    {\n\ttypedef const Vector& type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    src.increment_it(vector);\n\t    return vector;\n\t}\n    };\n\n} // namespace detail\n\ntemplate <typename Vector, typename Source>\nstruct crtp_plus_assign \n  : boost::mpl::if_\n     <boost::is_base_of<incrementer_base, Source>,\n      detail::assign_incrementer<Vector, Source>,\n      detail::crtp_plus_assign<Vector, Source, typename ashape::ashape<Vector>::type, \n\t\t\t       typename ashape::ashape<Source>::type>\n     >::type\n{};\n\n/// Assign-add matrix vector product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_plus_assign<Vector, mat_cvec_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src)\n    {\n\tmat_cvec_mult(src.first, src.second, vector, assign::plus_sum(), traits::mat_cvec_flatcat<E1>());\n\treturn vector;\n    }\n};\n\n/// Assign-add vector matrix product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_plus_assign<Vector, rvec_mat_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src)\n    {\n\trvec_mat_mult(src.first, src.second, vector, assign::plus_sum(), traits::mat_cvec_flatcat<E2>());\n\treturn vector;\n    }\n};\n\n\nnamespace detail {\n\n    template <typename Vector, typename Source, typename VCat, typename SCat>\n    struct crtp_minus_assign {};\t\n\n    /// Assign-add vector to a vector\n    template <typename Vector, typename Source, typename Cat>\n    struct crtp_minus_assign<Vector, Source, Cat, Cat>\n    {\n\ttypedef vec_vec_minus_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type(vector, src);\n\t}\n    };\t\n\n    /// Decrement a vector by a scalar\n    template <typename Vector, typename Source, typename VCat>\n    struct crtp_minus_assign<Vector, Source, VCat, ashape::scal>\n    {\n\ttypedef vec_scal_minus_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type(vector, src);\n\t}\n    };\t\n\n    template <typename Vector, typename Source>\n    struct assign_decrementer\n    {\n\ttypedef const Vector& type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    src.decrement_it(vector);\n\t    return vector;\n\t}\n    };\n\n} // namespace detail\n\ntemplate <typename Vector, typename Source>\nstruct crtp_minus_assign \n  : boost::mpl::if_\n     <boost::is_base_of<decrementer_base, Source>,\n      detail::assign_decrementer<Vector, Source>,\n      detail::crtp_minus_assign<Vector, Source, typename ashape::ashape<Vector>::type, \n\t\t\t       typename ashape::ashape<Source>::type>\n     >::type\n{};\n\n/// Assign-subtract matrix vector product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_minus_assign<Vector, mat_cvec_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src)\n    {\n\tmat_cvec_mult(src.first, src.second, vector, assign::minus_sum(), traits::mat_cvec_flatcat<E1>());\n\treturn vector;\n    }\n};\n\n/// Assign-subtract vector matrix product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_minus_assign<Vector, rvec_mat_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src)\n    {\n\trvec_mat_mult(src.first, src.second, vector, assign::minus_sum(), traits::mat_cvec_flatcat<E2>());\n\treturn vector;\n    }\n};\n\n#if 1\nnamespace detail {\n\n    template <typename Vector, typename Source, typename SCat, typename VCat>\n    struct crtp_times_assign {};\n\n    /// Assign-add vector to a vector\n    template <typename Vector, typename Source, typename Cat>\n    struct crtp_times_assign<Vector, Source, Cat, Cat>\n    {\n\ttypedef vec_vec_times_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type( vector, src );\n\t}\n    };\n\n    /// Increment a vector by a scalar\n    template <typename Vector, typename Source, typename VCat>\n    struct crtp_times_assign<Vector, Source, VCat, ashape::scal>\n    {\n\ttypedef vec_scal_times_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type(vector, src);\n\t}\n    };\n\n    template <typename Vector, typename Source>\n    struct assign_multiplyer\n    {\n\ttypedef const Vector& type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    src.multiply_it(vector);\n\t    return vector;\n\t}\n    };\n\n} // namespace detail\n\ntemplate <typename Vector, typename Source>\nstruct crtp_times_assign\n  : boost::mpl::if_\n     <boost::is_base_of<incrementer_base, Source>,\n      detail::assign_multiplyer<Vector, Source>,\n      detail::crtp_times_assign<Vector, Source, typename ashape::ashape<Vector>::type,\n\t\t\t       typename ashape::ashape<Source>::type>\n     >::type\n{};\n\n/// Assign-add matrix vector product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_times_assign<Vector, mat_cvec_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src)\n    {\n\tmat_cvec_mult(src.first, src.second, vector, assign::times_sum(), traits::mat_cvec_flatcat<E1>());\n\treturn vector;\n    }\n};\n\n/// Assign-add vector matrix product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_times_assign<Vector, rvec_mat_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src)\n    {\n\trvec_mat_mult(src.first, src.second, vector, assign::times_sum(), traits::mat_cvec_flatcat<E2>());\n\treturn vector;\n    }\n};\n\n\nnamespace detail {\n\n    template <typename Vector, typename Source, typename SCat, typename VCat>\n    struct crtp_div_assign {};\n\n    /// Assign-divide vector to a vector\n    template <typename Vector, typename Source, typename Cat>\n    struct crtp_div_assign<Vector, Source, Cat, Cat>\n    {\n\ttypedef vec_vec_div_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type( vector, src );\n\t}\n    };\n\n    /// Divide a vector by a scalar\n    template <typename Vector, typename Source, typename VCat>\n    struct crtp_div_assign<Vector, Source, VCat, ashape::scal>\n    {\n\ttypedef vec_scal_div_asgn_expr<Vector, Source> type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    return type(vector, src);\n\t}\n    };\n\n    template <typename Vector, typename Source>\n    struct assign_divider\n    {\n\ttypedef const Vector& type;\n\ttype operator()(Vector& vector, const Source& src)\n\t{\n\t    src.divide_it(vector);\n\t    return vector;\n\t}\n    };\n\n} // namespace detail\n\ntemplate <typename Vector, typename Source>\nstruct crtp_div_assign\n  : boost::mpl::if_\n     <boost::is_base_of<incrementer_base, Source>,\n      detail::assign_divider<Vector, Source>,\n      detail::crtp_div_assign<Vector, Source, typename ashape::ashape<Vector>::type,\n\t\t\t       typename ashape::ashape<Source>::type>\n     >::type\n{};\n\n/// Assign-divide matrix vector product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_div_assign<Vector, mat_cvec_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src)\n    {\n\tmat_cvec_mult(src.first, src.second, vector, assign::divide_sum(), traits::mat_cvec_flatcat<E1>());\n\treturn vector;\n    }\n};\n\n/// Assign-divide vector matrix product by calling mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename Vector, typename E1, typename E2>\nstruct crtp_div_assign<Vector, rvec_mat_times_expr<E1, E2> >\n{\n    typedef Vector& type;\n    type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src)\n    {\n\trvec_mat_mult(src.first, src.second, vector, assign::divide_sum(), traits::mat_cvec_flatcat<E2>());\n\treturn vector;\n    }\n};\n\n#endif\n\n\n\n/// Base class to provide vector assignment operators generically \ntemplate <typename Vector, typename ValueType, typename SizeType>\nstruct crtp_vector_assign\n{\n    /// Templated assignment implemented by functor to allow for partial specialization\n    template <typename E>\n    typename boost::disable_if<boost::is_same<Vector, E>, \n\t\t\t       typename crtp_assign<Vector, E>::type>::type\n    operator=(const E& e)\n    {\n\treturn crtp_assign<Vector, E>()(static_cast<Vector&>(*this), e);\n    }\n\n    /// Assign-add vector expression\n    template <class E>\n    typename crtp_plus_assign<Vector, E>::type operator+=(const E& e)\n    {\n\treturn crtp_plus_assign<Vector, E>()(static_cast<Vector&>(*this), e);\n    }\n\n    /// Assign-subtract vector expression\n    template <class E>\n    typename crtp_minus_assign<Vector, E>::type operator-=(const E& e)\n    {\n\treturn crtp_minus_assign<Vector, E>()(static_cast<Vector&>(*this), e);\n    }\n\n\n#if 1\n    /// Assign-times vector expression\n    template <class E>\n    typename crtp_times_assign<Vector, E>::type operator*=(const E& e)\n    {\n    \treturn crtp_times_assign<Vector, E>()(static_cast<Vector&>(*this), e);\n    }\n\n    /// Assign-div vector expression\n    template <class E>\n    typename crtp_div_assign<Vector, E>::type operator/=(const E& e)\n    {\n    \treturn crtp_div_assign<Vector, E>()(static_cast<Vector&>(*this), e);\n    }\n#endif\n\n#if 0\n    /// Scale vector (in place) with scalar value \n    /** In the future, row vectors be possibly scaled by a matrix **/\n    template <typename Factor>\n    vec_scal_times_asgn_expr<Vector, Factor> operator*=(const Factor& alpha)\n    {\n\treturn vec_scal_times_asgn_expr<Vector, Factor>( static_cast<Vector&>(*this), alpha );\n    }\t\n\n    /// Devide vector (in place) by a scalar value\n\t// added by Hui Li 12/11/2007\n    template <typename Factor>\n    vec_scal_div_asgn_expr<Vector, Factor> operator/=(const Factor& alpha)\n    {\n\treturn vec_scal_div_asgn_expr<Vector, Factor>( static_cast<Vector&>(*this), alpha );\n    }\t\n#endif\n    /// Check whether source and target have compatible resources and adapt empty target\n    /** For expressions like u= v + w, u can be set to the size of v and w if still is 0. **/\n    template <typename Src>\n    void checked_change_resource(const Src& src) \n    {\tchecked_change_resource_aux(src, typename mtl::traits::is_distributed<Vector>::type()); }    \n\n    template <typename Src>\n    void checked_change_resource_aux(const Src& src, boost::mpl::false_) \n    {   checked_change_dim(mtl::vector::size(src));  }\n\n\n    /// Check whether vector size is compatible or if vector is 0 change it s.\n    void checked_change_dim(SizeType s)\n    {\n\tVector& vector= static_cast<Vector&>(*this);\n\tvector.check_dim(s);\n\tvector.change_dim(s);\n    }\n};\n\n\ntemplate <typename Vector, typename ValueType, typename SizeType>\nstruct const_crtp_base_vector \n{};\n\ntemplate <typename Vector, typename ValueType, typename SizeType>\nstruct mutable_crtp_base_vector \n  : public crtp_vector_assign<Vector, ValueType, SizeType>\n{};\n\n\n\ntemplate <typename Vector, typename ValueType, typename SizeType>\nstruct crtp_base_vector \n  : boost::mpl::if_<boost::is_const<Vector>,\n\t\t    const_crtp_base_vector<Vector, ValueType, SizeType>,\n\t\t    mutable_crtp_base_vector<Vector, ValueType, SizeType>\n                   >::type\n{};\n\n\n}} // namespace mtl::vector\n\n#endif // MTL_CRTP_BASE_VECTOR_INCLUDE\n", "meta": {"hexsha": "2d6a6a050b29957523173f3f3c12d8d071b4b401", "size": 16937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/vector/crtp_base_vector.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/vector/crtp_base_vector.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/vector/crtp_base_vector.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.5171171171, "max_line_length": 119, "alphanum_fraction": 0.7086851272, "num_tokens": 4155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368159568461, "lm_q2_score": 0.054198731732815156, "lm_q1q2_score": 0.021264157836951975}}
{"text": "// Author(s): Wieger Wesselink\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file transform.cpp\n\n#include <chrono>\n#include <iostream>\n#include <fstream>\n#include <memory>\n#include <string>\n\n#include <boost/lexical_cast.hpp>\n\n#include \"mcrl2/core/detail/print_utility.h\"\n#include \"mcrl2/data/rewriter.h\"\n#include \"mcrl2/pbes/io.h\"\n#include \"mcrl2/pbes/remove_equations.h\"\n#include \"mcrl2/pbes/rewrite.h\"\n#include \"mcrl2/pbes/rewriters/data_rewriter.h\"\n#include \"mcrl2/pbes/rewriters/enumerate_quantifiers_rewriter.h\"\n#include \"mcrl2/pbes/rewriters/one_point_rule_rewriter.h\"\n#include \"mcrl2/pbes/rewriters/quantifiers_inside_rewriter.h\"\n#include \"mcrl2/pbes/rewriters/simplify_quantifiers_rewriter.h\"\n#include \"mcrl2/pbes/rewriters/simplify_rewriter.h\"\n\n#include \"mcrl2/utilities/input_output_tool.h\"\n\nusing namespace mcrl2;\n\n/// \\brief Saves text to the file filename, or to stdout if filename equals \"-\".\ninline\nvoid write_text(const std::string& filename, const std::string& text)\n{\n  if (filename.empty())\n  {\n    std::cout << text;\n  }\n  else\n  {\n    std::ofstream out(filename);\n    out << text;\n  }\n}\n\n/// \\brief\nstruct command\n{\n  std::string name;\n  const std::string& input_filename;\n  const std::string& output_filename;\n  const std::vector<std::string>& options;\n\n  command(const std::string& name_,\n          const std::string& input_filename_,\n          const std::string& output_filename_,\n          const std::vector<std::string>& options_\n         )\n    : name(name_),\n      input_filename(input_filename_),\n      output_filename(output_filename_),\n      options(options_)\n  {}\n\n  virtual void execute() = 0;\n};\n\nstruct pbescommand: public command\n{\n  pbes_system::pbes pbesspec;\n\n  pbescommand(const std::string& name,\n              const std::string& input_filename,\n              const std::string& output_filename,\n              const std::vector<std::string>& options\n             )\n    : command(name, input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbes_system::load_pbes(pbesspec, input_filename);\n  }\n};\n\n// PBES rewriters\nstruct rewrite_pbes_data_rewriter_command: public pbescommand\n{\n  rewrite_pbes_data_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-data-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    data::rewriter r(pbesspec.data());\n    pbes_system::data_rewriter<data::rewriter> R(r);\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct rewrite_pbes_enumerate_quantifiers_rewriter_command: public pbescommand\n{\n  rewrite_pbes_enumerate_quantifiers_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-enumerate-quantifiers-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    data::rewriter r(pbesspec.data());\n    pbes_system::enumerate_quantifiers_rewriter R(r, pbesspec.data());\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct rewrite_pbes_simplify_rewriter_command: public pbescommand\n{\n  rewrite_pbes_simplify_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-simplify-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    pbes_system::simplify_rewriter R;\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct rewrite_pbes_simplify_data_rewriter_command: public pbescommand\n{\n  rewrite_pbes_simplify_data_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-simplify-data-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    data::rewriter r(pbesspec.data());\n    pbes_system::simplify_data_rewriter<data::rewriter> R(r);\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct rewrite_pbes_simplify_quantifiers_rewriter_command: public pbescommand\n{\n  rewrite_pbes_simplify_quantifiers_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-simplify-quantifiers-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    pbes_system::simplify_quantifiers_rewriter R;\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct rewrite_pbes_simplify_quantifiers_data_rewriter_command: public pbescommand\n{\n  rewrite_pbes_simplify_quantifiers_data_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-simplify-quantifiers-data-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    data::rewriter r(pbesspec.data());\n    pbes_system::simplify_data_rewriter<data::rewriter> R(r);\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct rewrite_pbes_one_point_rule_rewriter_command: public pbescommand\n{\n  rewrite_pbes_one_point_rule_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-one-point-rule-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    pbes_system::one_point_rule_rewriter R;\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct rewrite_pbes_quantifiers_inside_rewriter_command: public pbescommand\n{\n  rewrite_pbes_quantifiers_inside_rewriter_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"pbes-quantifiers-inside-rewriter\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    pbes_system::quantifiers_inside_rewriter R;\n    pbes_rewrite(pbesspec, R);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nstruct remove_unused_pbes_equations_command: public pbescommand\n{\n  remove_unused_pbes_equations_command(const std::string& input_filename, const std::string& output_filename, const std::vector<std::string>& options)\n    : pbescommand(\"remove-unused-pbes-equations\", input_filename, output_filename, options)\n  {}\n\n  void execute()\n  {\n    pbescommand::execute();\n    pbes_system::remove_unreachable_variables(pbesspec);\n    pbes_system::save_pbes(pbesspec, output_filename);\n  }\n};\n\nclass transform_tool: public utilities::tools::input_output_tool\n{\n  protected:\n    typedef utilities::tools::input_output_tool super;\n\n    std::string algorithm_and_options;\n    int algorithm_number = -1;\n    bool print_algorithms = false;\n\n    void parse_options(const utilities::command_line_parser& parser)\n    {\n      super::parse_options(parser);\n      algorithm_and_options = parser.option_argument(\"algorithm\");\n      algorithm_number = parser.option_argument_as<int>(\"number\");\n      print_algorithms = parser.options.count(\"print-algorithms\") > 0;\n    }\n\n    void add_options(utilities::interface_description& desc)\n    {\n      super::add_options(desc);\n      desc.add_option(\"algorithm\", utilities::make_optional_argument<std::string>(\"NAME\", \"\"), \"the algorithm that is to be applied\", 'a');\n      desc.add_option(\"number\", utilities::make_optional_argument<int>(\"NAME\", \"-1\"), \"the number of the algorithm that is to be applied\", 'n');\n      desc.add_option(\"print-algorithms\", \"print the available algorithms\", 'p');\n    }\n\n    inline\n    void add_command(std::map<std::string, std::shared_ptr<command>>& commands, const std::shared_ptr<command>& command) const\n    {\n      commands[command->name] = command;\n    }\n\n  public:\n    transform_tool()\n      : super(\"mcrl2transform\",\n              \"Wieger Wesselink\",\n              \"applies a transformation to a PBES\",\n              \"Transform the PBES in INFILE and write the result to OUTFILE. If OUTFILE \"\n              \"is not present, stdout is used. If INFILE is not present, stdin is used.\"\n             )\n    {}\n\n    bool run()\n    {\n      std::vector<std::string> options;\n      std::set<std::string> algorithms;\n      std::string algorithm;\n      std::map<std::string, std::shared_ptr<command>> commands;\n\n      // PBES algorithms\n      add_command(commands, std::make_shared<rewrite_pbes_data_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<rewrite_pbes_enumerate_quantifiers_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<rewrite_pbes_simplify_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<rewrite_pbes_simplify_data_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<rewrite_pbes_simplify_quantifiers_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<rewrite_pbes_simplify_quantifiers_data_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<rewrite_pbes_one_point_rule_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<rewrite_pbes_quantifiers_inside_rewriter_command>(input_filename(), output_filename(), options));\n      add_command(commands, std::make_shared<remove_unused_pbes_equations_command>(input_filename(), output_filename(), options));\n\n      for (auto i = commands.begin(); i != commands.end(); ++i)\n      {\n        algorithms.insert(i->first);\n      }\n\n      if (algorithm_number >= 0 && !algorithm_and_options.empty())\n      {\n        throw mcrl2::runtime_error(\"It is not allowed to set both number and algorithm!\");\n      }\n\n      // print the algorithms\n      if (print_algorithms || (algorithm_number < 0 && algorithm_and_options.empty()))\n      {\n        int index = 1;\n        std::cout << \"The following algorithms are available:\" << std::endl;\n        for (auto const& algorithm: algorithms)\n        {\n          std::cout << index++ << \") \" << algorithm << std::endl;\n        }\n        return true;\n      }\n\n      // if a number was specified, lookup the corresponding algorithm\n      if (algorithm_number >= 0)\n      {\n        int index = 1;\n        for (auto const& algo: algorithms)\n        {\n          if (index++ == algorithm_number)\n          {\n            algorithm = algo;\n          }\n        }\n      }\n      else\n      {\n        options = utilities::regex_split(algorithm_and_options, \"\\\\s+\");\n        algorithm = options[0];\n        options.erase(options.begin());\n      }\n\n      // run the algorithm\n      auto i = commands.find(algorithm);\n      if (i == commands.end())\n      {\n        throw std::runtime_error(\"Unknown algorithm \" + algorithm);\n      }\n      i->second->execute();\n\n      return true;\n    }\n};\n\nint main(int argc, char* argv[])\n{\n  return transform_tool().execute(argc, argv);\n}", "meta": {"hexsha": "cd3e8e007fbce02986d5ca001f2a6e16238cecc9", "size": 11744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/pbestransform/pbestransform.cpp", "max_stars_repo_name": "gijskant/mcrl2-pmc", "max_stars_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/pbestransform/pbestransform.cpp", "max_issues_repo_name": "gijskant/mcrl2-pmc", "max_issues_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/pbestransform/pbestransform.cpp", "max_forks_repo_name": "gijskant/mcrl2-pmc", "max_forks_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1395348837, "max_line_length": 169, "alphanum_fraction": 0.7124489101, "num_tokens": 2829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.04813677572530268, "lm_q1q2_score": 0.021260714417598418}}
{"text": "\n///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2019, LAAS-CNRS\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_MULTIBODY_FRAMES_HPP_\n#define CROCODDYL_MULTIBODY_FRAMES_HPP_\n\n#include <Eigen/Dense>\n#include <pinocchio/spatial/se3.hpp>\n#include <pinocchio/spatial/motion.hpp>\n#include <pinocchio/spatial/force.hpp>\n\nnamespace crocoddyl {\n\ntypedef std::size_t FrameIndex;\n\nstruct FrameTranslation {\n  FrameTranslation(const FrameIndex& frame, const Eigen::Vector3d& oxf) : frame(frame), oxf(oxf) {}\n  friend std::ostream& operator<<(std::ostream& os, const FrameTranslation& X) {\n    os << \"      frame: \" << X.frame << std::endl << \"translation: \" << std::endl << X.oxf.transpose() << std::endl;\n    return os;\n  }\n\n  FrameIndex frame;\n  Eigen::Vector3d oxf;\n};\n\nstruct FrameRotation {\n  FrameRotation(const FrameIndex& frame, const Eigen::Matrix3d& oRf) : frame(frame), oRf(oRf) {}\n  friend std::ostream& operator<<(std::ostream& os, const FrameRotation& X) {\n    os << \"   frame: \" << X.frame << std::endl << \"rotation: \" << std::endl << X.oRf << std::endl;\n    return os;\n  }\n\n  FrameIndex frame;\n  Eigen::Matrix3d oRf;\n};\n\nstruct FramePlacement {\n  FramePlacement(const FrameIndex& frame, const pinocchio::SE3& oMf) : frame(frame), oMf(oMf) {}\n  friend std::ostream& operator<<(std::ostream& os, const FramePlacement& X) {\n    os << \"    frame: \" << X.frame << std::endl << \"placement: \" << std::endl << X.oMf << std::endl;\n    return os;\n  }\n\n  FrameIndex frame;\n  pinocchio::SE3 oMf;\n};\n\nstruct FrameMotion {\n  FrameMotion(const FrameIndex& frame, const pinocchio::Motion& oMf) : frame(frame), oMf(oMf) {}\n  friend std::ostream& operator<<(std::ostream& os, const FrameMotion& X) {\n    os << \" frame: \" << X.frame << std::endl << \"motion: \" << std::endl << X.oMf << std::endl;\n    return os;\n  }\n\n  FrameIndex frame;\n  pinocchio::Motion oMf;\n};\n\nstruct FrameForce {\n  FrameForce(const FrameIndex& frame, const pinocchio::Force& oFf) : frame(frame), oFf(oFf) {}\n  friend std::ostream& operator<<(std::ostream& os, const FrameForce& X) {\n    os << \"frame: \" << X.frame << std::endl << \"force: \" << std::endl << X.oFf << std::endl;\n    return os;\n  }\n\n  FrameIndex frame;\n  pinocchio::Force oFf;\n};\n\n}  // namespace crocoddyl\n\n#endif  // CROCODDYL_MULTIBODY_FRAMES_HPP_\n", "meta": {"hexsha": "dbe22b574984a688e81707472aef9a235b4eb302", "size": 2498, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/multibody/frames.hpp", "max_stars_repo_name": "jcarpent/crocoddyl", "max_stars_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T13:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T13:17:23.000Z", "max_issues_repo_path": "include/crocoddyl/multibody/frames.hpp", "max_issues_repo_name": "boyali/crocoddyl", "max_issues_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/multibody/frames.hpp", "max_forks_repo_name": "boyali/crocoddyl", "max_forks_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.225, "max_line_length": 116, "alphanum_fraction": 0.6208967174, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.04603390289002632, "lm_q1q2_score": 0.021222401649535847}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n#include <algorithm>\n#include <vector>\n\n#include <popart/error.hpp>\n#include <popart/logging.hpp>\n#include <popart/maxclique.hpp>\n\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/undirected_graph.hpp>\n\nnamespace popart {\nnamespace graphclique {\n\nclass AGraphImpl : public boost::adjacency_matrix<boost::undirectedS> {\npublic:\n  AGraphImpl(int size_) : boost::adjacency_matrix<boost::undirectedS>(size_) {}\n  AGraphImpl(AGraphImpl const &other)\n      : boost::adjacency_matrix<boost::undirectedS>(other) {}\n};\n\nAGraph::AGraph(int size_) : pimpl(new AGraphImpl(size_)) {}\n\nAGraph::AGraph(AGraph const &other)\n    : pimpl(std::make_unique<AGraphImpl>(*other.pimpl)) {}\n\nAGraph::~AGraph() {}\n\nvoid AGraph::addEdge(int i, int j) { boost::add_edge(i, j, *pimpl); }\n\nint AGraph::numVertices() const {\n  return static_cast<int>(boost::num_vertices(*pimpl));\n}\n\nbool AGraph::getEdge(int i, int j) const { return pimpl->get_edge(i, j); }\n\nMaxClique::MaxClique(AGraph agraph) : agraph_(agraph) {}\n\nbool MaxClique::getEdge(int i, int j) const {\n  if (i < 0 || i >= agraph_.numVertices()) {\n    throw error(\"Vertex index i={} out of bounds.\", i);\n  }\n  if (j < 0 || j >= agraph_.numVertices()) {\n    throw error(\"Vertex index j={} out of bounds.\", j);\n  }\n  return agraph_.getEdge(i, j);\n}\n\nstd::vector<std::vector<int>>\nMaxClique::getMaximumCliques(int minSize, int maxCount, const float stepLimit) {\n  stepLimit_  = stepLimit;\n  numVerices_ = agraph_.numVertices();\n\n  std::vector<bool> used(numVerices_, false);\n  std::vector<std::vector<int>> cliques;\n\n  do {\n    // Prepare with remaining vertices\n    vertices_.clear();\n    colors_.clear();\n    groupColor_.clear();\n    maxGroupColor_.clear();\n    steps_ = 0;\n\n    vertices_.reserve(numVerices_);\n    for (int i = 0; i < agraph_.numVertices(); ++i) {\n      if (!used[i]) {\n        vertices_.emplace_back(i, 0);\n      }\n    }\n\n    if (vertices_.size() != numVerices_) {\n      throw error(\"Inconsistent vertices size {} vs. numVertices {}\",\n                  vertices_.size(),\n                  numVerices_);\n    }\n\n    colors_.resize(numVerices_ + 1);\n    for (auto &color : colors_) {\n      color.reserve(numVerices_ + 1);\n    }\n    stepCount_.resize(numVerices_ + 1);\n\n    // Main algorithm\n    updateDegree(vertices_);\n    sortByDegree(vertices_);\n    setColorsToDegrees(vertices_);\n    for (int i = 0; i < numVerices_ + 1; ++i) {\n      stepCount_[i].first  = 0;\n      stepCount_[i].second = 0;\n    }\n\n    // Branch-and-bound\n    logging::trace(\"[MaxClique] branch-and-bound for {} vertices\",\n                   vertices_.size());\n    branch(vertices_, 1);\n\n    // Check if maximum clique in this iteration fulfills criteria\n    if (maxGroupColor_.size() >= minSize) {\n      cliques.push_back(maxGroupColor_);\n      for (int i : maxGroupColor_) {\n        used[i] = true;\n        // Remove vertices already in a group\n        numVerices_--;\n      }\n    }\n  } while (maxGroupColor_.size() >= minSize && cliques.size() < maxCount &&\n           numVerices_ > 0);\n\n  return cliques;\n}\n\nvoid MaxClique::updateDegree(Vertices &vs) {\n  for (int i = 0; i < vs.size(); i++) {\n    int degree = 0;\n    for (int j = 0; j < vs.size(); j++) {\n      if (getEdge(vs[i].first, vs[j].first)) {\n        degree++;\n      }\n    }\n    vs[i].second = degree;\n  }\n}\n\nvoid MaxClique::sortByDegree(Vertices &vs) {\n  std::sort(vs.begin(), vs.end(), [](const Vertex &v0, const Vertex &v1) {\n    return v0.second > v1.second;\n  });\n}\n\nvoid MaxClique::setColorsToDegrees(Vertices &vs) {\n  const int max_degree = vs.front().second;\n  for (int i = 0; i < max_degree; i++) {\n    vs[i].second = i + 1;\n  }\n  for (int i = max_degree; i < vs.size(); i++) {\n    vs[i].second = max_degree + 1;\n  }\n}\n\nvoid MaxClique::sortByColor(Vertices &vs) {\n  int j       = 0;\n  int upper_k = 1;\n  int lower_k =\n      static_cast<int>(maxGroupColor_.size() - groupColor_.size()) + 1;\n  colors_[1].clear();\n  colors_[2].clear();\n  int k = 1;\n  for (int i = 0; i < vs.size(); ++i) {\n    int vindex = vs.at(i).first;\n    k          = 1;\n    while (colorCut(vindex, colors_[k])) {\n      k++;\n    }\n    if (k > upper_k) {\n      upper_k = k;\n      colors_[upper_k + 1].clear();\n    }\n    colors_[k].push_back(vindex);\n    if (k < lower_k) {\n      vs.at(j).first = vindex;\n      ++j;\n    }\n  }\n  if (j > 0) {\n    vs.at(j - 1).second = 0;\n  }\n  if (lower_k <= 0) {\n    lower_k = 1;\n  }\n  for (k = lower_k; k <= upper_k; ++k) {\n    for (int i = 0; i < colors_[k].size(); ++i) {\n      vs.at(j).first  = colors_[k].at(i);\n      vs.at(j).second = k;\n      ++j;\n    }\n  }\n}\n\nbool MaxClique::colorCut(const int vindex, const ColorGroup &cg) {\n  for (int i = 0; i < cg.size(); ++i)\n    if (getEdge(vindex, cg.at(i)))\n      return true;\n  return false;\n}\n\nvoid MaxClique::verticesCut(const Vertices &vs0, Vertices &vs1) {\n  for (int i = 0; i < vs0.size() - 1; ++i) {\n    if (getEdge(vs0.back().first, vs0.at(i).first))\n      vs1.emplace_back(vs0.at(i).first, 0);\n  }\n}\n\nvoid MaxClique::branch(Vertices vs, int depth) {\n  stepCount_.at(depth).first =\n      (stepCount_.at(depth).first + stepCount_.at(depth - 1).first -\n       stepCount_.at(depth).second);\n\n  stepCount_.at(depth).second = (stepCount_.at(depth - 1).first);\n\n  while (!vs.empty()) {\n    if (groupColor_.size() + vs.back().second > maxGroupColor_.size()) {\n      groupColor_.push_back(vs.back().first);\n      Vertices vsx;\n      vsx.reserve(vs.size());\n      verticesCut(vs, vsx);\n      if (vsx.size()) {\n        ++steps_;\n        if (static_cast<float>(stepCount_.at(depth).first) / steps_ <\n            stepLimit_) {\n          updateDegree(vsx);\n          sortByDegree(vsx);\n        }\n        sortByColor(vsx);\n        stepCount_.at(depth).first++;\n        branch(vsx, depth + 1);\n      } else if (groupColor_.size() > maxGroupColor_.size()) {\n        maxGroupColor_ = groupColor_;\n      }\n      groupColor_.pop_back();\n    } else {\n      return;\n    }\n    vs.pop_back();\n  }\n}\n\n} // namespace graphclique\n} // namespace popart\n", "meta": {"hexsha": "c84d48e8ec32a2446adc12b1caffeea1959b442e", "size": 6046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "willow/src/maxclique.cpp", "max_stars_repo_name": "gglin001/popart", "max_stars_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:51.000Z", "max_issues_repo_path": "willow/src/maxclique.cpp", "max_issues_repo_name": "gglin001/popart", "max_issues_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T01:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T11:13:14.000Z", "max_forks_repo_path": "willow/src/maxclique.cpp", "max_forks_repo_name": "gglin001/popart", "max_forks_repo_head_hexsha": "3225214343f6d98550b6620e809a3544e8bcbfc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T06:55:00.000Z", "avg_line_length": 26.2869565217, "max_line_length": 80, "alphanum_fraction": 0.5957657956, "num_tokens": 1806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.04272220150767497, "lm_q1q2_score": 0.021194220549370767}}
{"text": "/*\nThe Original EM/MPM algorithm was developed by Mary L. Comer and is distributed\nunder the BSD License.\nCopyright (c) <2010>, <Mary L. Comer>\nAll rights reserved.\n\n[1] Comer, Mary L., and Delp, Edward J.,  ÒThe EM/MPM Algorithm for Segmentation\nof Textured Images: Analysis and Further Experimental Results,Ó IEEE Transactions\non Image Processing, Vol. 9, No. 10, October 2000, pp. 1731-1744.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\n\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\nNeither the name of <Mary L. Comer> nor the names of its contributors may be\nused to endorse or promote products derived from this software without specific\nprior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/* acvmpm.c */\n\n/* Modified by Joel Dumke on 1/30/09 */\n\n/* Heavily modified from the original by Michael A. Jackson for BlueQuartz Software\n * and funded by the Air Force Research Laboratory, Wright-Patterson AFB.\n */\n#include \"MPMCalculation.h\"\n\n\n#include <stdlib.h>\n#include <stddef.h>\n#include <string.h>\n#include <stdio.h>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\n\n#include \"EMMPMLib/Core/EMMPM.h\"\n#include \"EMMPMLib/Common/MSVCDefines.h\"\n#include \"EMMPMLib/Common/EMMPM_Math.h\"\n#include \"EMMPMLib/Common/EMTime.h\"\n#include \"EMMPMLib/Core/EMMPMUtilities.h\"\n\n#define USE_TBB_TASK_GROUP 0\n#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)\n#include <tbb/task_scheduler_init.h>\n#include <tbb/parallel_for.h>\n#include <tbb/blocked_range2d.h>\n#include <tbb/partitioner.h>\n#include <tbb/task_group.h>\n\n#endif\n\n#define COMPUTE_C_CLIQUE( C, x, y, ci, cj)\\\nif((x) < 0 || (x) >= colEnd || (y) < 0 || (y) >= rowEnd) {\\\n  C[ci][cj] = classes;\\\n}\\\nelse\\\n{\\\n  ij = (cols * (y)) + (x);\\\n  C[ci][cj] = xt[ij];\\\n}\n\n\n\n\n/**\n * @class ParallelCalcLoop ParallelCalcLoop.h EMMPM/Curvature/ParallelCalcLoop.h\n * @brief This class can calculate the parts of the MPM loop in parallel\n * @author Michael A. Jackson for BlueQuartz Software\n * @date March 11, 2012\n * @version 1.0\n */\nclass ParallelMPMLoop\n{\n  public:\n#if USE_TBB_TASK_GROUP\n    ParallelCalcLoop(EMMPM_Data* dPtr, real_t* ykPtr, real_t* rnd, int rowStart, int rowEnd,\n                     int colStart, int colEnd) :\n    m_RowStart(rowStart),\n    m_RowEnd(rowEnd),\n    m_ColStart(colStart),\n    m_ColEnd(colEnd),\n#else\n    ParallelMPMLoop(EMMPM_Data* dPtr, real_t* ykPtr, real_t* rnd) :\n#endif\n\n    data(dPtr),\n    yk(ykPtr),\n    rnd(rnd)\n    {}\n    virtual ~ParallelMPMLoop(){}\n\n\n    void calc(int rowStart, int rowEnd,\n                  int colStart, int colEnd) const\n    {\n      //uint64_t millis = EMMPM_getMilliSeconds();\n    //  int l;\n      real_t prior;\n      int32_t ij, lij;\n      int rows = data->rows;\n      int cols = data->columns;\n      int classes = data->classes;\n\n      real_t xrnd, current;\n      real_t post[EMMPM_MAX_CLASSES], sum, edge;\n\n      size_t nsCols = data->columns - 1;\n      size_t ewCols = data->columns;\n      size_t swCols = data->columns - 1;\n      size_t nwCols = data->columns - 1;\n\n      unsigned char* xt = data->xt;\n      real_t* probs = data->probs;\n      real_t* ccost = data->ccost;\n      real_t* ns = data->ns;\n      real_t* ew = data->ew;\n      real_t* sw = data->sw;\n      real_t* nw = data->nw;\n      real_t curvature_value = (real_t)0.0;\n\n\n      int C[3][3]; // This is the Clique for the current Pixel\n//      --------- X -----\n//      |   | 0 | 1 | 2 |\n//      -----------------\n//   Y  | 0 |   |   |   |\n//      -----------------\n//      | 1 |   | P |   |\n//      -----------------\n//      | 2 |   |   |   |\n//\n// When we calculate the \"C\" matrix if the pixel value for the specific index of\n// the clique would be off the image then a value = number of classes is\n// used for the C[i][j]. That way we can figure out if we are off the image\n\n      std::stringstream ss;\n      unsigned int cSize = classes + 1;\n      real_t* coupling = data->couplingBeta;\n\n      for (int32_t y = rowStart; y < rowEnd; y++)\n       {\n         for (int32_t x = colStart; x < colEnd; x++)\n         {\n\n           /* -------------  */\n          COMPUTE_C_CLIQUE(C, x-1, y-1, 0, 0);\n          COMPUTE_C_CLIQUE(C,   x, y-1, 1, 0);\n          COMPUTE_C_CLIQUE(C, x+1, y-1, 2, 0);\n          COMPUTE_C_CLIQUE(C, x-1,   y, 0, 1);\n          COMPUTE_C_CLIQUE(C, x+1,   y, 2, 1);\n          COMPUTE_C_CLIQUE(C, x-1, y+1, 0, 2);\n          COMPUTE_C_CLIQUE(C,   x, y+1, 1, 2);\n          COMPUTE_C_CLIQUE(C, x+1, y+1, 2, 2);\n\n#if 0\n          if (y == rowStart + 1 && x == colStart + 1)\n          {\n              ss << \"------------------------------\" << std::endl;\n              ss << \"|\" << C[0][0] << \"\\t\" << C[1][0] << \"\\t\" << C[2][0] << std::endl;\n              ss << \"|\" << C[0][1] << \"\\t\" << C[1][1] << \"\\t\" << C[2][1] << std::endl;\n              ss << \"|\" << C[0][2] << \"\\t\" << C[1][2] << \"\\t\" << C[2][2] << std::endl;\n              ss << \"------------------------------\" << std::endl;\n              std::cout << ss.str() << std::endl;\n          }\n#endif\n\n          ij = (cols*y)+x;\n          sum = 0;\n          for (int l = 0; l < classes; ++l)\n          {\n            prior = 0;\n            edge = 0;\n\n            prior += coupling[(cSize*l)+ C[0][0]];\n            prior += coupling[(cSize*l)+ C[1][0]];\n            prior += coupling[(cSize*l)+ C[2][0]];\n            prior += coupling[(cSize*l)+ C[0][1]];\n            prior += coupling[(cSize*l)+ C[2][1]];\n            prior += coupling[(cSize*l)+ C[0][2]];\n            prior += coupling[(cSize*l)+ C[1][2]];\n            prior += coupling[(cSize*l)+ C[2][2]];\n\n#if 0\n            if (y == rowStart + 1 && x == colStart + 1)\n            {\n                std::cout << \"Class: \" << l << \"\\t prior: \" << prior << std::endl;\n            }\n#endif\n\n            // now check for the gradient penalty. If our current class is NOT equal\n            // to the class at index[i][j] AND the value of C[i][j] does NOT equal\n            // to the Number of Classes then add in the gradient penalty.\n            if (data->useGradientPenalty)\n            {\n              if (C[0][0] != l && C[0][0] != classes) edge += sw[(swCols*(y-1))+x-1];\n              if (C[1][0] != l && C[1][0] != classes) edge += ew[(ewCols*(y-1))+x];\n              if (C[2][0] != l && C[2][0] != classes) edge += nw[(nwCols*(y-1))+x];\n              if (C[0][1] != l && C[0][1] != classes) edge += ns[(nsCols*y)+x-1];\n              if (C[2][1] != l && C[2][1] != classes) edge += ns[(nsCols*y)+x];\n              if (C[0][2] != l && C[0][2] != classes) edge += nw[(nwCols*y)+x-1];\n              if (C[1][2] != l && C[1][2] != classes) edge += ew[(ewCols*y)+x];\n              if (C[2][2] != l && C[2][2] != classes) edge += sw[(swCols*y)+x];\n            }\n\n\n            lij = (cols * rows * l) + (cols * y) + x;\n            curvature_value = 0.0;\n            if (data->useCurvaturePenalty)\n            {\n              curvature_value = data->beta_c * ccost[lij];\n            }\n            real_t arg = data->workingKappa * (yk[lij] - (prior) - (edge) - (curvature_value) - data->w_gamma[l]);\n            post[l] = expf(arg);\n            sum += post[l];\n          }\n\n           xrnd = rnd[ij];\n           current = 0.0;\n\n           for (int l = 0; l < classes; l++)\n           {\n             lij = (cols * rows * l) + ij;\n             real_t arg = post[l] / sum;\n             if ((xrnd >= current) && (xrnd <= (current + arg)))\n             {\n               xt[ij] = l;\n               probs[lij] += 1.0;\n             }\n             current += arg;\n           }\n#if 0\n           Dont even THINK about using this code...\n                   This classifys the pixel based on the largest\n                   in magnitude  probability\n           real_t max = 0.0;\n           int maxClass = 0;\n           for (int l = 0; l < classes; l++)\n           {\n             lij = (cols * rows * l) + ij;\n             //real_t arg = post[l] / sum;\n             if (probs[lij] > max)\n             {\n                 max = probs[lij];\n                 maxClass = l;\n             }\n           }\n           //Assign class based on Maximum probability\n           xt[ij] = maxClass;\n#endif\n         }\n       }\n    //  std::cout << \"     --\" << EMMPM_getMilliSeconds() - millis << \"--\" << std::endl;\n     }\n\n\n#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)\n#if USE_TBB_TASK_GROUP\n    void operator()() const\n    {\n      calc(m_RowStart, m_RowEnd, m_ColStart, m_ColEnd);\n    }\n#else\n    void operator()(const tbb::blocked_range2d<int> &r) const\n    {\n      calc(r.rows().begin(), r.rows().end(), r.cols().begin(), r.cols().end());\n    }\n#endif\n#endif\n\n\nprivate:\n#if USE_TBB_TASK_GROUP\n    int m_RowStart;\n    int m_RowEnd;\n    int m_ColStart;\n    int m_ColEnd;\n#endif\n    const EMMPM_Data* data;\n    const real_t* yk;\n    const real_t* rnd;\n\n};\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nMPMCalculation::MPMCalculation() :\nm_StatsDelegate(NULL)\n{\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nMPMCalculation::~MPMCalculation()\n{\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid MPMCalculation::execute()\n{\n  EMMPM_Data* data = m_Data.get();\n\n  real_t* yk;\n  real_t sqrt2pi, con[EMMPM_MAX_CLASSES];\n  real_t post[EMMPM_MAX_CLASSES];\n\n  // int k, l;\n // unsigned int i, j, d;\n  size_t ld, ijd, lij;\n  unsigned int dims = data->dims;\n  unsigned int rows = data->rows;\n  unsigned int cols = data->columns;\n  unsigned int classes = data->classes;\n\n//  int rowEnd = rows/2;\n  unsigned char* y = data->y;\n  real_t* probs = data->probs;\n  real_t* m = data->mean;\n  real_t* v = data->variance;\n\n  char msgbuff[256];\n  float totalLoops;\n\n  int currentLoopCount;\n\n//  real_t curvature_value = (real_t)0.0;\n\n  memset(post, 0, EMMPM_MAX_CLASSES * sizeof(real_t));\n  memset(con, 0,  EMMPM_MAX_CLASSES * sizeof(real_t));\n\n  totalLoops = (float)(data->emIterations * data->mpmIterations + data->mpmIterations);\n  memset(msgbuff, 0, 256);\n  data->progress++;\n\n  yk = (real_t*)malloc(cols * rows * classes * sizeof(real_t));\n\n  sqrt2pi = sqrt(2.0 * M_PI);\n\n  for (uint32_t l = 0; l < classes; l++)\n  {\n    con[l] = 0;\n    for (uint32_t d = 0; d < dims; d++)\n    {\n      ld = dims * l + d;\n      con[l] += -log(sqrt2pi * sqrt(v[ld]));\n    }\n  }\n\n  for (uint32_t i = 0; i < rows; i++)\n  {\n    for (uint32_t j = 0; j < cols; j++)\n    {\n      for (uint32_t l = 0; l < classes; l++)\n      {\n        lij = (cols * rows * l) + (cols * i) + j;\n        probs[lij] = 0;\n        yk[lij] = con[l];\n        for (uint32_t d = 0; d < dims; d++)\n        {\n          ld = dims * l + d;\n          ijd = (dims * cols * i) + (dims * j) + d;\n          yk[lij] += ((y[ijd] - m[ld]) * (y[ijd] - m[ld]) / (-2.0 * v[ld]));\n        }\n      }\n    }\n  }\n\n  const float rangeMin = 0;\n  const float rangeMax = 1.0f;\n  typedef boost::uniform_real<real_t> NumberDistribution;\n  typedef boost::mt19937 RandomNumberGenerator;\n  typedef boost::variate_generator<RandomNumberGenerator&,\n                                   NumberDistribution> Generator;\n\n  NumberDistribution distribution(rangeMin, rangeMax);\n  RandomNumberGenerator generator;\n  Generator numberGenerator(generator, distribution);\n  generator.seed(EMMPM_getMilliSeconds()); // seed with the current time\n\n  // Generate all the numbers up front\n  size_t total = rows * cols;\n  std::vector<real_t> rndNumbers(total);\n  real_t* rndNumbersPtr = &(rndNumbers.front());\n  for(size_t i = 0; i < total; ++i)\n  {\n    rndNumbersPtr[i] = numberGenerator(); // Work directly with the pointer for speed.\n  }\n\n  //unsigned long long int millis = EMMPM_getMilliSeconds();\n  //std::cout << \"------------------------------------------------\" << std::endl;\n  /* Perform the MPM loops */\n  for (int32_t k = 0; k < data->mpmIterations; k++)\n  {\n\n    data->currentMPMLoop = k;\n    if (data->cancel) { data->progress = 100.0; break; }\n    data->inside_mpm_loop = 1;\n\n#if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)\n    tbb::task_scheduler_init init;\n    int threads = init.default_num_threads();\n#if USE_TBB_TASK_GROUP\n    tbb::task_group* g = new tbb::task_group;\n    unsigned int rowIncrement = rows/threads;\n    unsigned int rowStop = 0 + rowIncrement;\n    unsigned int rowStart = 0;\n    for (int t = 0; t < threads; ++t)\n    {\n      g->run(ParallelCalcLoop(data, yk, &(rndNumbers.front()), rowStart, rowStop, 0, cols) );\n      rowStart = rowStop;\n      rowStop = rowStop + rowIncrement;\n      if (rowStop >= rows)\n      {\n        rowStop = rows;\n      }\n    }\n    g->wait();\n    delete g;\n#else\n    tbb::parallel_for(tbb::blocked_range2d<int>(0, rows, rows/threads, 0, cols, cols),\n                      ParallelMPMLoop(data, yk, &(rndNumbers.front())),\n                      tbb::simple_partitioner());\n#endif\n\n#else\n    ParallelMPMLoop pcl(data, yk, &(rndNumbers.front()));\n    pcl.calc(0, rows, 0, cols);\n#endif\n\n\n    //std::cout << \"Counter: \" << counter << std::endl;\n    EMMPMUtilities::ConvertXtToOutputImage(getData());\n\n    data->currentMPMLoop = k;\n   // snprintf(msgbuff, 256, \"MPM Loop %d\", data->currentMPMLoop);\n   // notify(msgbuff, 0, UpdateProgressMessage);\n\n    currentLoopCount = data->mpmIterations * data->currentEMLoop + data->currentMPMLoop;\n    data->progress = currentLoopCount / totalLoops * 100.0;\n\n   // notify(\"\", data->progress, UpdateProgressValue);\n    if (m_StatsDelegate != NULL)\n    {\n      m_StatsDelegate->reportProgress(m_Data);\n    }\n  }\n#if 0\n  #if defined (EMMPMLib_USE_PARALLEL_ALGORITHMS)\n    std::cout << \"Parrallel MPM Loop Time to Complete:\";\n#else\n    std::cout << \"Serial MPM Loop Time To Complete: \";\n#endif\n    std::cout << (EMMPM_getMilliSeconds() - millis) << std::endl;\n#endif\n\n\n  data->inside_mpm_loop = 0;\n\n  if (!data->cancel)\n  {\n  /* Normalize probabilities */\n    for (uint32_t i = 0; i < data->rows; i++)\n    {\n      for (uint32_t j = 0; j < data->columns; j++)\n      {\n        for (uint32_t l = 0; l < classes; l++)\n        {\n          lij = (cols * rows * l) + (cols * i) + j;\n          data->probs[lij] = data->probs[lij] / (real_t)data->mpmIterations;\n        }\n      }\n    }\n  }\n\n  /* Clean Up Memory */\n  free(yk);\n\n}\n", "meta": {"hexsha": "e13d8da3b9d667f0a9864ffe394061460cdec758", "size": 15499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/EMMPMLib/Core/MPMCalculation.cpp", "max_stars_repo_name": "BlueQuartzSoftware/emmpm", "max_stars_repo_head_hexsha": "edfc6d5840e6d18ad784b763c845356432eae9d6", "max_stars_repo_licenses": ["libtiff"], "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/EMMPMLib/Core/MPMCalculation.cpp", "max_issues_repo_name": "BlueQuartzSoftware/emmpm", "max_issues_repo_head_hexsha": "edfc6d5840e6d18ad784b763c845356432eae9d6", "max_issues_repo_licenses": ["libtiff"], "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/EMMPMLib/Core/MPMCalculation.cpp", "max_forks_repo_name": "BlueQuartzSoftware/emmpm", "max_forks_repo_head_hexsha": "edfc6d5840e6d18ad784b763c845356432eae9d6", "max_forks_repo_licenses": ["libtiff"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8131212724, "max_line_length": 114, "alphanum_fraction": 0.5485515195, "num_tokens": 4445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04272219663237113, "lm_q1q2_score": 0.021194218130762617}}
{"text": "#include <iostream>\n#include <typeinfo>\n\n#include <map>\n\nusing std::cout;\nusing std::endl;\n\n\n#include \"viennagrid/forwards.hpp\"\n\n#include \"viennagrid/storage/view.hpp\"\n#include \"viennagrid/storage/container_collection.hpp\"\n#include \"viennagrid/storage/inserter.hpp\"\n#include \"viennagrid/storage/id_generator.hpp\"\n#include \"viennagrid/storage/hidden_key_map.hpp\"\n#include \"viennagrid/storage/range.hpp\"\n\n\n#include \"viennagrid/topology/vertex.hpp\"\n#include \"viennagrid/topology/line.hpp\"\n#include \"viennagrid/topology/simplex.hpp\"\n\n\n#include \"viennagrid/element/element_key.hpp\"\n#include \"viennagrid/element/element_orientation.hpp\"\n\n#include \"viennagrid/config/element_config.hpp\"\n#include \"viennagrid/config/mesh_config.hpp\"\n\n#include \"viennagrid/point.hpp\"\n\n#include \"viennagrid/mesh/mesh.hpp\"\n#include \"viennagrid/mesh/element_creation.hpp\"\n\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\nnamespace ublas = boost::numeric::ublas;\n\ntypedef ublas::vector<double> vector_type;\n\nclass my_mesh_config\n{\n  private:\n    //typedef viennagrid::storage::pointer_handle_tag handle_tag;\n    //typedef viennagrid::storage::iterator_handle_tag handle_tag;\n    typedef viennagrid::storage::id_handle_tag          handle_tag;\n\n  public:\n\n    typedef viennagrid::config::result_of::full_mesh_config< viennagrid::tetrahedron_tag, vector_type, handle_tag >::type     type;\n};\n\n\nint main()\n{\n\n\n    //\n    // typedefing and setting up the geometric mesh\n    //\n\n    typedef viennagrid::mesh<my_mesh_config> mesh_type;\n    mesh_type mesh;\n\n    //\n    // typedefs for the element types\n    //\n\n    typedef viennagrid::result_of::element<mesh_type, viennagrid::vertex_tag>::type vertex_type;\n    typedef viennagrid::result_of::handle<mesh_type, viennagrid::vertex_tag>::type vertex_handle_type;\n\n    typedef viennagrid::result_of::element<mesh_type, viennagrid::line_tag>::type line_type;\n    typedef viennagrid::result_of::element<mesh_type, viennagrid::triangle_tag>::type triangle_type;\n\n    typedef viennagrid::result_of::element<mesh_type, viennagrid::tetrahedron_tag>::type tetrahedron_type;\n    typedef viennagrid::result_of::handle<mesh_type, viennagrid::tetrahedron_tag>::type tetrahedron_handle_type;\n\n\n//     typedef viennagrid::result_of::handle<mesh_type, viennagrid::polygon_tag>::type tetrahedron_handle_type;\n\n\n    //\n    // Adding a tetrahedron\n    //\n\n    // creates four vertices within the mesh, vh is short vor vertex handle\n    // make_element is responsible for resizing all meta-info container which are associated with vertex_type\n    vertex_handle_type vh0 = viennagrid::make_vertex( mesh );\n    vertex_handle_type vh1 = viennagrid::make_vertex( mesh );\n    vertex_handle_type vh2 = viennagrid::make_vertex( mesh );\n    vertex_handle_type vh3 = viennagrid::make_vertex( mesh );\n\n\n    // create geometric information for the vertices\n    vector_type p0(3);\n    p0[0] = 0.0; p0[1] = 0.0; p0[2] = 0.0;\n    vector_type p1(3);\n    p1[0] = 1.0; p1[1] = 0.0; p1[2] = 0.0;\n    vector_type p2(3);\n    p2[0] = 0.0; p2[1] = 1.0; p2[2] = 0.0;\n    vector_type p3(3);\n    p3[0] = 0.0; p3[1] = 0.0; p3[2] = 1.0;\n\n\n    // set the geometric information for the vertices\n    // is equivalent to viennagrid::look_up<vector_type>(mesh, vhX)\n    viennagrid::point(mesh, vh0) = p0;\n    viennagrid::point(mesh, vh1) = p1;\n    viennagrid::point(mesh, vh2) = p2;\n    viennagrid::point(mesh, vh3) = p3;\n\n\n    // creates a handle buffer for the vertex handles of the tetdrahedron\n    std::vector<vertex_handle_type> handles(4);\n    handles[0] = vh0; handles[1] = vh1; handles[2] = vh2; handles[3] = vh3;\n\n    // creates the tetrahedron within the mesh, all boundary cell generation is done here implicit\n    tetrahedron_handle_type tet = viennagrid::make_element<tetrahedron_type>( mesh, handles.begin(), handles.end() );\n    std::cout << tet << std::endl;\n\n    // set a double value to a tetdrahedron\n//     viennagrid::look_up<double>(mesh, tet) = 1.0;\n\n    //\n    // display the mesh content\n    //\n\n    cout << \"All vertices of the mesh\" << endl;\n    std::copy( viennagrid::elements<viennagrid::vertex_tag>(mesh).begin(), viennagrid::elements<viennagrid::vertex_tag>(mesh).end(), std::ostream_iterator<vertex_type>(cout, \"\\n\") );\n    cout << endl;\n\n    cout << \"All lines of the mesh\" << endl;\n    std::copy( viennagrid::elements<viennagrid::line_tag>(mesh).begin(), viennagrid::elements<viennagrid::line_tag>(mesh).end(), std::ostream_iterator<line_type>(cout, \"\\n\") );\n    cout << endl;\n\n    cout << \"All triangles of the mesh\" << endl;\n    std::copy( viennagrid::elements<viennagrid::triangle_tag>(mesh).begin(), viennagrid::elements<viennagrid::triangle_tag>(mesh).end(), std::ostream_iterator<triangle_type>(cout, \"\\n\") );\n    cout << endl;\n\n    cout << \"All tetraherons of the mesh\" << endl;\n    std::copy( viennagrid::elements<viennagrid::tetrahedron_tag>(mesh).begin(), viennagrid::elements<viennagrid::tetrahedron_tag>(mesh).end(), std::ostream_iterator<tetrahedron_type>(cout, \"\\n\") );\n    cout << endl;\n\n\n    //\n    // doing some boundary cell iteration\n    //\n\n    const tetrahedron_type & test_tet = *viennagrid::elements<viennagrid::tetrahedron_tag>(mesh).begin();\n    const triangle_type & test_tri = *viennagrid::elements<viennagrid::triangle_tag>(mesh).begin();\n\n\n\n    typedef viennagrid::result_of::const_element_range<tetrahedron_type, viennagrid::triangle_tag>::type tetrahedron_triangle_range;\n    typedef viennagrid::result_of::const_iterator<tetrahedron_triangle_range>::type tetrahedron_triangle_iterator;\n\n    cout << \"All triangles of the first tetdrahedron in the mesh\" << endl;\n    tetrahedron_triangle_range tri_range = viennagrid::elements<viennagrid::triangle_tag>(test_tet);\n    for (tetrahedron_triangle_iterator it = tri_range.begin(); it != tri_range.end(); ++it)\n        cout << *it << endl;\n    cout << endl;\n\n    cout << \"Once more with std::copy\" << endl;\n    std::copy( tri_range.begin(), tri_range.end(), std::ostream_iterator<triangle_type>(cout, \"\\n\") );\n    cout << endl;\n\n\n\n\n    typedef viennagrid::result_of::const_element_range<triangle_type, viennagrid::line_tag>::type triangle_line_range;\n    typedef viennagrid::result_of::const_iterator<triangle_line_range>::type triangle_line_iterator;\n\n    cout << \"All lines of the first triangle in the mesh\" << endl;\n    triangle_line_range lin_range = viennagrid::elements<viennagrid::line_tag>(test_tri);\n    for (triangle_line_iterator it = lin_range.begin(); it != lin_range.end(); ++it)\n        cout << *it << endl;\n    cout << endl;\n\n    cout << \"Once more with std::copy\" << endl;\n    std::copy( lin_range.begin(), lin_range.end(), std::ostream_iterator<line_type>(cout, \"\\n\") );\n    cout << endl;\n\n\n\n\n    //\n    // geometric iteration\n    //\n\n    // iterating over all vertices and piping out the point information\n//     typedef viennagrid::result_of::const_element_range<tetrahedron_type, viennagrid::vertex_tag>::type tetrahedron_vertex_range;\n//     typedef viennagrid::result_of::const_iterator<tetrahedron_vertex_range>::type tetrahedron_vertex_iterator;\n//\n//     cout << \"All vertices of the first tetdrahedron in the mesh USING ncells<dim>()\" << endl;\n//     tetrahedron_vertex_range vtx_range = viennagrid::elements<viennagrid::vertex_tag>(test_tet);\n//     for (tetrahedron_vertex_iterator it = vtx_range.begin(); it != vtx_range.end(); ++it)\n//         cout << *it << \" geometric information: \" << viennagrid::look_up<vector_type>( mesh, *it ) << endl;\n//     cout << endl;\n//\n//\n//     typedef viennagrid::result_of::const_element_range<mesh_type, viennagrid::vertex_tag>::type mesh_vertex_range_2;\n//     typedef viennagrid::result_of::const_iterator<mesh_vertex_range_2>::type mesh_vertex_iterator_2;\n//\n//     cout << \"All vertices of the first tetdrahedron in the mesh USING elements<tag>()\" << endl;\n//     mesh_vertex_range_2 mesh_vtx_range_2 = viennagrid::elements<viennagrid::vertex_tag>(mesh);\n//     for (mesh_vertex_iterator_2 it = mesh_vtx_range_2.begin(); it != mesh_vtx_range_2.end(); ++it)\n//         cout << *it << \" geometric information: \" << viennagrid::look_up<vector_type>( mesh, *it ) << endl;\n//     cout << endl;\n//\n//\n//     typedef viennagrid::result_of::const_element_range<mesh_type, vertex_type>::type mesh_vertex_range_3;\n//     typedef viennagrid::result_of::const_iterator<mesh_vertex_range_3>::type mesh_vertex_iterator_3;\n//\n//     cout << \"All vertices of the first tetdrahedron in the mesh USING elements<type>()\" << endl;\n//     mesh_vertex_range_3 mesh_vtx_range_3 = viennagrid::elements<vertex_type>(mesh);\n//     for (mesh_vertex_iterator_3 it = mesh_vtx_range_3.begin(); it != mesh_vtx_range_3.end(); ++it)\n//         cout << *it << \" geometric information: \" << viennagrid::look_up<vector_type>( mesh, *it ) << endl;\n//     cout << endl;\n//\n//\n//     // iterating over all tetrahedrons and piping out the double meta-information\n//     typedef viennagrid::result_of::const_element_range<mesh_type, viennagrid::tetrahedron_tag>::type tetrahedron_range;\n//     typedef viennagrid::result_of::const_iterator<tetrahedron_range>::type tetrahedron_iterator;\n//\n//     cout << \"All tetdrahedrons in the mesh\" << endl;\n//     tetrahedron_range tet_range = viennagrid::elements<viennagrid::tetrahedron_tag>(mesh);\n//     for (tetrahedron_iterator it = tet_range.begin(); it != tet_range.end(); ++it)\n//     {\n//         cout << *it << endl;\n//         cout << \"   geometric information: \" << viennagrid::look_up<double>( mesh, *it ) << endl;\n//     }\n//     cout << endl;\n\n\n\n\n\n\n\n\n\n\n\n\n    const mesh_type & test = mesh;\n\n    typedef viennagrid::result_of::const_element_range<mesh_type, viennagrid::vertex_tag>::type const_vertex_range;\n    typedef viennagrid::result_of::iterator<const_vertex_range>::type const_vertex_iterator;\n\n    const_vertex_range r = viennagrid::elements<viennagrid::vertex_tag>(test);\n    for (const_vertex_iterator i = r.begin(); i != r.end(); ++i)\n    {\n        cout << *i << endl;\n        cout << viennagrid::point(test, *i) << endl;\n    }\n\n\n    return 0;\n}\n", "meta": {"hexsha": "4f8397322e170427d439dac4de8dcc7f34e3087f", "size": 10045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/old/mesh_test_2.cpp", "max_stars_repo_name": "viennagrid/viennagrid-dev", "max_stars_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-09-13T03:50:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T14:24:49.000Z", "max_issues_repo_path": "examples/tutorial/old/mesh_test_2.cpp", "max_issues_repo_name": "viennagrid/viennagrid-dev", "max_issues_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/old/mesh_test_2.cpp", "max_forks_repo_name": "viennagrid/viennagrid-dev", "max_forks_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-03T07:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T00:51:58.000Z", "avg_line_length": 38.3396946565, "max_line_length": 197, "alphanum_fraction": 0.7036336486, "num_tokens": 2749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.042722196022958195, "lm_q1q2_score": 0.021194217828436616}}
{"text": "// Copyright 2010 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//           Andrew Lumsdaine\n\n#ifndef BOOST_GRAPH_LOOP_ERASED_RANDOM_WALK_HPP\n#define BOOST_GRAPH_LOOP_ERASED_RANDOM_WALK_HPP\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/next_prior.hpp>\n#include <vector>\n#include <boost/assert.hpp>\n\nnamespace boost\n{\n\nstruct BOOST_SYMBOL_VISIBLE loop_erased_random_walk_stuck\n: public std::exception\n{\n    virtual ~loop_erased_random_walk_stuck() throw() {}\n    inline virtual const char* what() const throw()\n    {\n        return \"Loop-erased random walk found a vertex with no out-edges\";\n    }\n};\n\n// Do a loop-erased random walk from vertex s to any vertex colored black (or\n// actually any color other than white or gray) in the color map.  The color\n// white is for vertices that are not part of the path, while gray is for\n// those that are on the path (for cycle detection).  The vector path is used\n// for temporary storage and as the result of the algorithm; while all\n// elements of the path except the last have their colors set to gray upon\n// return.  Vertex s must start off colored white.\n//\n// Useful references:\n// http://everything2.com/title/loop-erased+random+walk\n// Wikipedia page on \"Loop-Erased Random Walk\"\n\ntemplate < typename Graph, typename ColorMap, typename NextEdge >\nvoid loop_erased_random_walk(const Graph& g,\n    typename boost::graph_traits< Graph >::vertex_descriptor s,\n    NextEdge next_edge, ColorMap color,\n    std::vector< typename boost::graph_traits< Graph >::vertex_descriptor >&\n        path)\n{\n    typedef typename boost::graph_traits< Graph >::vertex_descriptor\n        vertex_descriptor;\n    typedef\n        typename boost::graph_traits< Graph >::edge_descriptor edge_descriptor;\n    typedef typename boost::property_traits< ColorMap >::value_type color_t;\n    typedef boost::color_traits< color_t > color_gen;\n\n    BOOST_ASSERT(get(color, s) == color_gen::white());\n    path.clear();\n    path.push_back(s);\n    put(color, s, color_gen::gray());\n    while (true)\n    {\n        edge_descriptor e = next_edge(s, g);\n        vertex_descriptor t = target(e, g);\n        color_t t_color = get(color, t);\n        if (t_color == color_gen::white())\n        {\n            path.push_back(t);\n            put(color, t, color_gen::gray());\n            s = t;\n        }\n        else if (t_color == color_gen::gray())\n        {\n            // Found a loop; delete from path from the first occurrence of t to\n            // the end, coloring vertices white.\n            typename std::vector< vertex_descriptor >::iterator it\n                = std::find(path.begin(), path.end(), t);\n            BOOST_ASSERT(it != path.end());\n            ++it;\n            for (typename std::vector< vertex_descriptor >::iterator j = it;\n                 j != path.end(); ++j)\n            {\n                put(color, *j, color_gen::white());\n            }\n            path.erase(it, path.end());\n            s = t;\n        }\n        else\n        {\n            // Done\n            path.push_back(t);\n            break;\n        }\n    }\n}\n\ntemplate < typename Graph, typename Gen > class unweighted_random_out_edge_gen\n{\n    Gen& gen;\n\n    typedef boost::graph_traits< Graph > gt;\n\npublic:\n    unweighted_random_out_edge_gen(Gen& gen) : gen(gen) {}\n\n    typename gt::edge_descriptor operator()(\n        typename gt::vertex_descriptor src, const Graph& g) const\n    {\n        if (out_degree(src, g) == 0)\n            throw loop_erased_random_walk_stuck();\n        return boost::random_out_edge(g, src, gen);\n    }\n};\n\ntemplate < typename Graph, typename WeightMap, typename Gen >\nclass weighted_random_out_edge_gen\n{\n    WeightMap weight;\n    Gen& gen;\n\n    typedef boost::graph_traits< Graph > gt;\n\npublic:\n    weighted_random_out_edge_gen(const WeightMap& weight, Gen& gen)\n    : weight(weight), gen(gen)\n    {\n    }\n\n    typename gt::edge_descriptor operator()(\n        typename gt::vertex_descriptor src, const Graph& g) const\n    {\n        if (out_degree(src, g) == 0)\n            throw loop_erased_random_walk_stuck();\n        return boost::weighted_random_out_edge(g, src, weight, gen);\n    }\n};\n}\n\n#endif // BOOST_GRAPH_LOOP_ERASED_RANDOM_WALK_HPP\n", "meta": {"hexsha": "3c3f3c765cf17cd1b9532c8245c735b653370f52", "size": 4436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/loop_erased_random_walk.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/loop_erased_random_walk.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/loop_erased_random_walk.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": 31.2394366197, "max_line_length": 79, "alphanum_fraction": 0.6510369702, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04272219587060496, "lm_q1q2_score": 0.02119421775285512}}
{"text": "/*\ngruneisen.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 \"gruneisen.h\"\n#include \"constants.h\"\n#include \"dynamical.h\"\n#include \"error.h\"\n#include \"fcs_phonon.h\"\n#include \"kpoint.h\"\n#include \"mathfunctions.h\"\n#include \"memory.h\"\n#include \"parsephon.h\"\n#include \"pointers.h\"\n#include \"system.h\"\n#include \"anharmonic_core.h\"\n#include \"version.h\"\n#include <iostream>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/version.hpp>\n#include <cmath>\n\nusing namespace PHON_NS;\n\nGruneisen::Gruneisen(PHON *phon): Pointers(phon)\n{\n    set_default_variables();\n};\n\nGruneisen::~Gruneisen()\n{\n    deallocate_variables();\n};\n\nvoid Gruneisen::set_default_variables()\n{\n    delta_a = 0.01;\n    print_gruneisen = false;\n    print_newfcs = false;\n    gruneisen = nullptr;\n    xshift_s = nullptr;\n}\n\nvoid Gruneisen::deallocate_variables()\n{\n    if (gruneisen) {\n        memory->deallocate(gruneisen);\n    }\n    if (xshift_s) {\n        memory->deallocate(xshift_s);\n    }\n    delta_fc2.clear();\n    delta_fc3.clear();\n}\n\n\nvoid Gruneisen::setup()\n{\n    MPI_Bcast(&delta_a, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&print_newfcs, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n\n    memory->allocate(xshift_s, 27, 3);\n\n    for (int i = 0; i < 3; ++i) xshift_s[0][i] = 0.0;\n\n    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    if (print_gruneisen || print_newfcs) {\n        prepare_delta_fcs(fcs_phonon->force_constant_with_cell[1], delta_fc2);\n    }\n\n    if (print_newfcs && anharmonic_core->quartic_mode > 0) {\n        prepare_delta_fcs(fcs_phonon->force_constant_with_cell[2], delta_fc3);\n    }\n    if (print_gruneisen) {\n        memory->allocate(gruneisen, kpoint->nk, dynamical->neval);\n    }\n\n    if (mympi->my_rank == 0) {\n        if (print_newfcs) {\n            std::cout << std::endl;\n            if (anharmonic_core->quartic_mode > 0) {\n                std::cout << \" NEWFCS = 1 : Harmonic and cubic force constants of \" << std::endl;\n            } else {\n                std::cout << \" NEWFCS = 1 : Harmonic force constants of \" << std::endl;\n            }\n            std::cout << \"              expanded/compressed systems will be estimated\" << std::endl;\n            std::cout << \"              with DELTA_A = \" << std::setw(5) << delta_a << std::endl;\n        }\n    }\n    //   print_stress_energy();\n}\n\n\nvoid Gruneisen::calc_gruneisen()\n{\n    auto ns = dynamical->neval;\n    auto nk = kpoint->nk;\n    std::complex<double> **dfc2_reciprocal;\n\n    memory->allocate(dfc2_reciprocal, ns, ns);\n\n    if (mympi->my_rank == 0) {\n        std::cout << std::endl;\n        std::cout << \" GRUNEISEN = 1 : Calculating Gruneisen parameters ... \";\n    }\n\n    for (auto ik = 0; ik < nk; ++ik) {\n\n        calc_dfc2_reciprocal(dfc2_reciprocal, kpoint->xk[ik]);\n\n        for (auto is = 0; is < ns; ++is) {\n\n            gruneisen[ik][is] = std::complex<double>(0.0, 0.0);\n\n            for (unsigned int i = 0; i < ns; ++i) {\n                for (unsigned int j = 0; j < ns; ++j) {\n                    gruneisen[ik][is] += std::conj(dynamical->evec_phonon[ik][is][i])\n                        * dfc2_reciprocal[i][j]\n                        * dynamical->evec_phonon[ik][is][j];\n                }\n            }\n\n            double gamma_imag = gruneisen[ik][is].imag();\n            if (std::abs(gamma_imag) > eps10) {\n                error->warn(\"calc_gruneisen\", \"Gruneisen parameter is not real\");\n            }\n\n            if (std::abs(dynamical->eval_phonon[ik][is]) < eps8) {\n                gruneisen[ik][is] = 0.0;\n            } else {\n                gruneisen[ik][is] /= - 6.0 * std::pow(dynamical->eval_phonon[ik][is], 2);\n            }\n        }\n    }\n    memory->deallocate(dfc2_reciprocal);\n\n    if (mympi->my_rank == 0) {\n        std::cout << \"done!\" << std::endl;\n    }\n}\n\nvoid Gruneisen::calc_dfc2_reciprocal(std::complex<double> **dphi2,\n                                     const double *xk_in)\n{\n    unsigned int i;\n    unsigned int ns = dynamical->neval;\n\n    double vec[3];\n\n    std::complex<double> im(0.0, 1.0);\n\n\n    for (i = 0; i < ns; ++i) {\n        for (unsigned int j = 0; j < ns; ++j) {\n            dphi2[i][j] = std::complex<double>(0.0, 0.0);\n        }\n    }\n\n    for (const auto &it : delta_fc2) {\n\n        unsigned int atm1 = it.pairs[0].index / 3;\n        unsigned int xyz1 = it.pairs[0].index % 3;\n        unsigned int atm2 = it.pairs[1].index / 3;\n        unsigned int xyz2 = it.pairs[1].index % 3;\n\n        unsigned int tran = it.pairs[1].tran;\n        unsigned int cell_s = it.pairs[1].cell_s;\n\n        unsigned int atm1_s = system->map_p2s_anharm[atm1][0];\n        unsigned int atm2_s = system->map_p2s_anharm[atm2][tran];\n\n\n        for (i = 0; i < 3; ++i) {\n            vec[i] = system->xr_s_anharm[atm2_s][i] + xshift_s[cell_s][i]\n                - system->xr_s_anharm[system->map_p2s_anharm[atm2][0]][i];\n        }\n\n        rotvec(vec, vec, system->lavec_s_anharm);\n        rotvec(vec, vec, system->rlavec_p);\n\n        double phase = vec[0] * xk_in[0] + vec[1] * xk_in[1] + vec[2] * xk_in[2];\n\n        dphi2[3 * atm1 + xyz1][3 * atm2 + xyz2]\n            += it.fcs_val * std::exp(im * phase)\n            / std::sqrt(system->mass_anharm[atm1_s] * system->mass_anharm[atm2_s]);\n\n    }\n}\n\n\nvoid Gruneisen::prepare_delta_fcs(const std::vector<FcsArrayWithCell> &fcs_in,\n                                  std::vector<FcsArrayWithCell> &delta_fcs) const\n{\n    unsigned int i;\n    double vec[3];\n    double fcs_tmp = 0.0;\n\n    std::vector<FcsAlignedForGruneisen> fcs_aligned;\n    std::vector<AtomCellSuper> pairs_vec;\n    std::vector<int> index_old, index_now;\n    std::vector<int> index_with_cell;\n    std::set<std::vector<int>> set_index_uniq;\n    AtomCellSuper pairs_tmp;\n\n    unsigned int norder = fcs_in[0].pairs.size();\n    unsigned int nmulti;\n\n    delta_fcs.clear();\n    fcs_aligned.clear();\n\n    for (auto it = fcs_in.cbegin(); it != fcs_in.cend(); ++it) {\n        fcs_aligned.emplace_back((*it).fcs_val, (*it).pairs);\n    }\n    std::sort(fcs_aligned.begin(), fcs_aligned.end());\n\n    index_old.clear();\n    unsigned int nelems = 2 * (norder - 2) + 1;\n    for (i = 0; i < nelems; ++i) index_old.push_back(-1);\n\n    index_with_cell.clear();\n    set_index_uniq.clear();\n\n    for (auto it = fcs_aligned.cbegin(); it != fcs_aligned.cend(); ++it) {\n\n        index_now.clear();\n        index_with_cell.clear();\n\n        index_now.push_back((*it).pairs[0].index);\n        index_with_cell.push_back((*it).pairs[0].index);\n\n        for (i = 1; i < norder - 1; ++i) {\n            index_now.push_back((*it).pairs[i].index);\n            index_now.push_back((*it).pairs[i].tran);\n\n            index_with_cell.push_back((*it).pairs[i].index);\n            index_with_cell.push_back((*it).pairs[i].tran);\n            index_with_cell.push_back((*it).pairs[i].cell_s);\n        }\n\n        if (index_now != index_old) {\n\n            if (index_old[0] != -1) {\n\n                nmulti = set_index_uniq.size();\n                fcs_tmp /= static_cast<double>(nmulti);\n\n                if (std::abs(fcs_tmp) > eps15) {\n                    for (const auto &it2 : set_index_uniq) {\n\n                        pairs_vec.clear();\n\n                        pairs_tmp.index = it2[0];\n                        pairs_tmp.tran = 0;\n                        pairs_tmp.cell_s = 0;\n                        pairs_vec.push_back(pairs_tmp);\n                        for (i = 1; i < norder - 1; ++i) {\n                            pairs_tmp.index = it2[3 * i - 2];\n                            pairs_tmp.tran = it2[3 * i - 1];\n                            pairs_tmp.cell_s = it2[3 * i];\n                            pairs_vec.push_back(pairs_tmp);\n                        }\n                        delta_fcs.emplace_back(fcs_tmp, pairs_vec);\n                    }\n                }\n                set_index_uniq.clear();\n            }\n\n            fcs_tmp = 0.0;\n            index_old.clear();\n            index_old.reserve(index_now.size());\n            std::copy(index_now.begin(), index_now.end(), std::back_inserter(index_old));\n        }\n\n        set_index_uniq.insert(index_with_cell);\n\n        for (i = 0; i < 3; ++i) {\n            vec[i] = system->xr_s_anharm[system->map_p2s_anharm[(*it).pairs[norder - 1].index / 3][(*it).pairs[norder -\n                    1].tran]]\n                [i]\n                - system->xr_s_anharm[system->map_p2s_anharm[(*it).pairs[0].index / 3][0]][i]\n                + xshift_s[(*it).pairs[norder - 1].cell_s][i];\n        }\n\n        rotvec(vec, vec, system->lavec_s_anharm);\n\n        fcs_tmp += (*it).fcs_val * vec[(*it).pairs[norder - 1].index % 3];\n    }\n\n    nmulti = set_index_uniq.size();\n    fcs_tmp /= static_cast<double>(nmulti);\n\n    if (std::abs(fcs_tmp) > eps15) {\n        for (const auto &it2 : set_index_uniq) {\n\n            pairs_vec.clear();\n\n            pairs_tmp.index = it2[0];\n            pairs_tmp.tran = 0;\n            pairs_tmp.cell_s = 0;\n            pairs_vec.push_back(pairs_tmp);\n            for (i = 1; i < norder - 1; ++i) {\n                pairs_tmp.index = it2[3 * i - 2];\n                pairs_tmp.tran = it2[3 * i - 1];\n                pairs_tmp.cell_s = it2[3 * i];\n                pairs_vec.push_back(pairs_tmp);\n            }\n            delta_fcs.emplace_back(fcs_tmp, pairs_vec);\n        }\n    }\n\n    fcs_aligned.clear();\n    set_index_uniq.clear();\n}\n\nvoid Gruneisen::write_new_fcsxml_all()\n{\n    std::cout << std::endl;\n\n    if (fcs_phonon->update_fc2) {\n        error->warn(\"write_new_fcsxml_all\",\n                    \"NEWFCS = 1 cannot be combined with the FC2XML.\");\n    } else {\n        std::cout << \" NEWFCS = 1 : Following XML files are created. \" << std::endl;\n\n        std::string file_xml = input->job_title + \"_+.xml\";\n        write_new_fcsxml(file_xml, delta_a);\n\n        std::cout << \"  \" << std::setw(input->job_title.length() + 12) << std::left << file_xml;\n        std::cout << \" : Force constants of the system expanded by \"\n            << std::fixed << std::setprecision(3) << delta_a * 100 << \" %\" << std::endl;\n\n        file_xml = input->job_title + \"_-.xml\";\n        write_new_fcsxml(file_xml, -delta_a);\n\n        std::cout << \"  \" << std::setw(input->job_title.length() + 12) << std::left << file_xml;\n        std::cout << \" : Force constants of the system compressed by \"\n            << std::fixed << std::setprecision(3) << delta_a * 100 << \" %\" << std::endl;\n    }\n}\n\nvoid Gruneisen::write_new_fcsxml(const std::string filename_xml,\n                                 const double change_ratio_of_a)\n{\n    int i, j;\n    double lattice_vector[3][3];\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            lattice_vector[i][j] = (1.0 + change_ratio_of_a) * system->lavec_s[i][j];\n        }\n    }\n\n    using boost::property_tree::ptree;\n\n    ptree pt;\n    std::string str_pos[3];\n\n    pt.put(\"Data.ANPHON_version\", ALAMODE_VERSION);\n    pt.put(\"Data.Description.OriginalXML\", fcs_phonon->file_fcs);\n    pt.put(\"Data.Description.Delta_A\", double2string(change_ratio_of_a));\n\n    pt.put(\"Data.Structure.NumberOfAtoms\", system->nat);\n    pt.put(\"Data.Structure.NumberOfElements\", system->nkd);\n\n    for (i = 0; i < system->nkd; ++i) {\n        ptree &child = pt.add(\"Data.Structure.AtomicElements.element\",\n                              system->symbol_kd[i]);\n        child.put(\"<xmlattr>.number\", i + 1);\n    }\n\n    for (i = 0; i < 3; ++i) {\n        str_pos[i].clear();\n        for (j = 0; j < 3; ++j) {\n            str_pos[i] += \" \" + double2string(lattice_vector[j][i]);\n        }\n    }\n    pt.put(\"Data.Structure.LatticeVector\", \"\");\n    pt.put(\"Data.Structure.LatticeVector.a1\", str_pos[0]);\n    pt.put(\"Data.Structure.LatticeVector.a2\", str_pos[1]);\n    pt.put(\"Data.Structure.LatticeVector.a3\", str_pos[2]);\n\n    pt.put(\"Data.Structure.Position\", \"\");\n    std::string str_tmp;\n\n    for (i = 0; i < system->nat; ++i) {\n        str_tmp.clear();\n        for (j = 0; j < 3; ++j) str_tmp += \" \" + double2string(system->xr_s[i][j]);\n        ptree &child = pt.add(\"Data.Structure.Position.pos\", str_tmp);\n        child.put(\"<xmlattr>.index\", i + 1);\n        child.put(\"<xmlattr>.element\", system->symbol_kd[system->kd[i]]);\n    }\n\n    pt.put(\"Data.Symmetry.NumberOfTranslations\", system->ntran);\n    for (i = 0; i < system->ntran; ++i) {\n        for (j = 0; j < system->natmin; ++j) {\n            ptree &child = pt.add(\"Data.Symmetry.Translations.map\",\n                                  system->map_p2s[j][i] + 1);\n            child.put(\"<xmlattr>.tran\", i + 1);\n            child.put(\"<xmlattr>.atom\", j + 1);\n        }\n    }\n\n    pt.put(\"Data.ForceConstants\", \"\");\n    str_tmp.clear();\n\n    for (const auto &it : fcs_phonon->force_constant_with_cell[0]) {\n\n        ptree &child = pt.add(\"Data.ForceConstants.HARMONIC.FC2\", double2string(it.fcs_val));\n\n        child.put(\"<xmlattr>.pair1\",\n                  std::to_string(it.pairs[0].index / 3 + 1)\n                  + \" \" + std::to_string(it.pairs[0].index % 3 + 1));\n        child.put(\"<xmlattr>.pair2\",\n                  std::to_string(system->map_p2s[it.pairs[1].index / 3][it.pairs[1].tran] + 1)\n                  + \" \" + std::to_string(it.pairs[1].index % 3 + 1)\n                  + \" \" + std::to_string(it.pairs[1].cell_s + 1));\n    }\n\n    for (const auto &it : delta_fc2) {\n\n        if (std::abs(it.fcs_val) < eps12) continue;\n\n        ptree &child = pt.add(\"Data.ForceConstants.HARMONIC.FC2\",\n                              double2string(change_ratio_of_a * it.fcs_val));\n\n        child.put(\"<xmlattr>.pair1\",\n                  std::to_string(it.pairs[0].index / 3 + 1)\n                  + \" \" + std::to_string(it.pairs[0].index % 3 + 1));\n        child.put(\"<xmlattr>.pair2\",\n                  std::to_string(system->map_p2s[it.pairs[1].index / 3][it.pairs[1].tran] + 1)\n                  + \" \" + std::to_string(it.pairs[1].index % 3 + 1)\n                  + \" \" + std::to_string(it.pairs[1].cell_s + 1));\n    }\n\n    if (anharmonic_core->quartic_mode) {\n        for (const auto &it : fcs_phonon->force_constant_with_cell[1]) {\n\n            if (it.pairs[1].index > it.pairs[2].index) continue;\n\n            ptree &child = pt.add(\"Data.ForceConstants.ANHARM3.FC3\",\n                                  double2string(it.fcs_val));\n\n            child.put(\"<xmlattr>.pair1\",\n                      std::to_string(it.pairs[0].index / 3 + 1)\n                      + \" \" + std::to_string(it.pairs[0].index % 3 + 1));\n            child.put(\"<xmlattr>.pair2\",\n                      std::to_string(system->map_p2s[it.pairs[1].index / 3][it.pairs[1].tran] + 1)\n                      + \" \" + std::to_string(it.pairs[1].index % 3 + 1)\n                      + \" \" + std::to_string(it.pairs[1].cell_s + 1));\n            child.put(\"<xmlattr>.pair3\",\n                      std::to_string(system->map_p2s[it.pairs[2].index / 3][it.pairs[2].tran] + 1)\n                      + \" \" + std::to_string(it.pairs[2].index % 3 + 1)\n                      + \" \" + std::to_string(it.pairs[2].cell_s + 1));\n        }\n\n        for (const auto &it : delta_fc3) {\n\n            if (std::abs(it.fcs_val) < eps12) continue;\n\n            if (it.pairs[1].index > it.pairs[2].index) continue;\n\n            ptree &child = pt.add(\"Data.ForceConstants.ANHARM3.FC3\",\n                                  double2string(change_ratio_of_a * it.fcs_val));\n\n            child.put(\"<xmlattr>.pair1\",\n                      std::to_string(it.pairs[0].index / 3 + 1)\n                      + \" \" + std::to_string(it.pairs[0].index % 3 + 1));\n            child.put(\"<xmlattr>.pair2\",\n                      std::to_string(system->map_p2s[it.pairs[1].index / 3][it.pairs[1].tran] + 1)\n                      + \" \" + std::to_string(it.pairs[1].index % 3 + 1)\n                      + \" \" + std::to_string(it.pairs[1].cell_s + 1));\n            child.put(\"<xmlattr>.pair3\",\n                      std::to_string(system->map_p2s[it.pairs[2].index / 3][it.pairs[2].tran] + 1)\n                      + \" \" + std::to_string(it.pairs[2].index % 3 + 1)\n                      + \" \" + std::to_string(it.pairs[2].cell_s + 1));\n        }\n    }\n\n    using namespace boost::property_tree::xml_parser;\n    const int indent = 2;\n\n#if BOOST_VERSION >= 105600\n    write_xml(filename_xml, pt, std::locale(),\n              xml_writer_make_settings<ptree::key_type>(' ', indent, widen<std::string>(\"utf-8\")));\n#else\n    write_xml(filename_xml, pt, std::locale(),\n        xml_writer_make_settings(' ', indent, widen<char>(\"utf-8\")));\n#endif\n}\n\n\nstd::string Gruneisen::double2string(const double d) const\n{\n    std::string rt;\n    std::stringstream ss;\n\n    ss << std::scientific << std::setprecision(15) << d;\n    ss >> rt;\n    return rt;\n}\n\n\n// double Gruneisen::calc_stress_energy2(const std::vector<FcsArrayWithCell> fcs_in)\n// {\n//     unsigned int i, j;\n//     double ret = 0.0;\n//     double **vec, **pos;\n//     double tmp, tmp2;\n//     double xshift[3];\n//     unsigned int itran;\n//     unsigned int norder = fcs_in[0].pairs.size();\n// \n//     memory->allocate(vec, norder, 3);\n//     memory->allocate(pos, norder, 3);\n// \n//     for (std::vector<FcsArrayWithCell>::const_iterator it = fcs_in.begin(); it != fcs_in.end(); ++it) {\n// \n//         for (i = 0; i < norder; ++i) {\n//             for (j = 0; j < 3; ++j) {\n//                 vec[i][j] = system->xr_s[system->map_p2s[(*it).pairs[i].index / 3][(*it).pairs[i].tran]][j]\n//                 + xshift_s[(*it).pairs[i].cell_s][j];\n// \n//                 pos[i][j] = system->xr_s[system->map_p2s[(*it).pairs[i].index / 3][0]][j];\n//             //    vec[i][j] = system->xr_s[system->map_p2s[0][(*it).pairs[i].tran]][j] + xshift_s[(*it).pairs[i].cell_s][j];\n//             }\n//             rotvec(vec[i], vec[i], system->lavec_s);\n//             rotvec(pos[i], pos[i], system->lavec_s);\n//         } \n// \n//         \n//         ret += (*it).fcs_val \n//             * (vec[1][(*it).pairs[0].index % 3] - pos[0][(*it).pairs[0].index % 3])\n//             * (vec[1][(*it).pairs[1].index % 3] - pos[0][(*it).pairs[1].index % 3]);\n//     }\n// \n//     memory->deallocate(vec);\n//     memory->deallocate(pos);\n//     return ret;\n// }\n// \n// void Gruneisen::calc_stress_energy3(const std::vector<FcsArrayWithCell> fcs_in, double ****ret)\n// {\n//     unsigned int i, j, k, l;\n//     double **vec, **pos;\n//     double tmp, tmp2;\n//     double xshift[3];\n//     unsigned int itran;\n//     unsigned int norder = fcs_in[0].pairs.size();\n//     unsigned int crd[4];\n// \n//     memory->allocate(vec, norder, 3);\n//     memory->allocate(pos, norder, 3);\n// \n//     for (i = 0; i < 3; ++i) {\n//         for (j = 0; j < 3; ++j) {\n//             for (k = 0; k < 3; ++k) {\n//                 for (l = 0; l < 3; ++l) {\n//                     ret[i][j][k][l] = 0.0;\n//                 }\n//             }\n//         }\n//     }\n// \n//     for (std::vector<FcsArrayWithCell>::const_iterator it = fcs_in.begin(); it != fcs_in.end(); ++it) {\n// \n//         for (i = 0; i < norder; ++i) {\n//             for (j = 0; j < 3; ++j) {\n//                 vec[i][j] = system->xr_s[system->map_p2s[(*it).pairs[i].index / 3][(*it).pairs[i].tran]][j]\n//                 + xshift_s[(*it).pairs[i].cell_s][j];\n// \n//                 pos[i][j] = system->xr_s[system->map_p2s[(*it).pairs[i].index / 3][0]][j];\n//             }\n//             rotvec(vec[i], vec[i], system->lavec_s);\n//             rotvec(pos[i], pos[i], system->lavec_s);\n//         }\n// \n//         crd[0] = (*it).pairs[0].index % 3;\n//         crd[1] = (*it).pairs[1].index % 3;\n// \n//         for (k = 0; k < 3; ++k) {\n//             \n//             crd[2] = k;\n// \n//             for (l = 0; l < 3; ++l) {\n// \n//                 crd[3] = l;\n// \n//                 ret[crd[0]][crd[1]][k][l] += (*it).fcs_val * (vec[1][k] - pos[0][k]) * (vec[1][l] - pos[0][l]);\n//             }\n//         }\n//     }\n// \n//     memory->deallocate(vec);\n//     memory->deallocate(pos);\n// \n//     for (i = 0; i < 3; ++i) {\n//         for (j = 0; j < 3; ++j) {\n//             for (k = 0; k < 3; ++k) {\n//                 for (l = 0; l < 3; ++l) {\n//                     ret[i][j][k][l] *= -0.5;\n//                 }\n//             }\n//         }\n//     }\n// }\n// \n// \n// void Gruneisen::print_stress_energy()\n// {\n// \n//     double volume = system->volume_p * std::pow(Bohr_in_Angstrom, 3) * 1.0e-30;\n// \n// \n//     double ****A, ****C;\n// \n//     memory->allocate(A, 3, 3, 3, 3);\n//     memory->allocate(C, 3, 3, 3, 3);\n// \n//     calc_stress_energy3(fcs_phonon->force_constant_with_cell[0], A);\n// \n//     unsigned int i, j, k, l;\n// \n//     std::cout << \"# A [Ryd]\" << std::endl;\n// \n//     for (i = 0; i < 3; ++i) {\n//         for (j = 0; j < 3; ++j) {\n//             for (k = 0; k < 3; ++k) {\n//                 for (l = 0; l < 3; ++l) {\n//                     std::cout << std::setw(3) << i + 1;\n//                     std::cout << std::setw(3) << j + 1;\n//                     std::cout << std::setw(3) << k + 1;\n//                     std::cout << std::setw(3) << l + 1;\n//                     std::cout << std::setw(15) << std::fixed << A[i][j][k][l];\n//                     std::cout << std::endl;\n//                 }\n//             }\n//         }\n//     }\n// \n//     std::cout << std::endl;\n//     std::cout << \"# C [GPa]\" << std::endl;\n// \n//     for (i = 0; i < 3; ++i) {\n//         for (j = 0; j < 3; ++j) {\n//             for (k = 0; k < 3; ++k) {\n//                 for (l = 0; l < 3; ++l) {\n//                     C[i][j][k][l] = A[i][k][j][l] + A[j][k][i][l] - A[i][j][k][l];\n//                     C[i][j][k][l] *= 1.0e-9 * Ryd / volume;\n//                     std::cout << std::setw(3) << i + 1;\n//                     std::cout << std::setw(3) << j + 1;\n//                     std::cout << std::setw(3) << k + 1;\n//                     std::cout << std::setw(3) << l + 1;\n//                     std::cout << std::setw(15) << std::fixed << C[i][j][k][l];\n//                     std::cout << std::endl;\n// \n//                 }\n//             }\n//         }\n//     }\n// \n//     std::cout << \"Bulk Modulus [GPa] = \" << (C[0][0][0][0] + 2.0 * C[0][0][1][1]) / 3.0 << std::endl;\n// \n//     memory->deallocate(A);\n//     memory->deallocate(C);\n// }\n", "meta": {"hexsha": "794a0663a9bf3422e4f89b085230d56adf14b7ac", "size": 22821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/gruneisen.cpp", "max_stars_repo_name": "wichoi77/alamode", "max_stars_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T19:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T19:05:03.000Z", "max_issues_repo_path": "anphon/gruneisen.cpp", "max_issues_repo_name": "wichoi77/alamode", "max_issues_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "anphon/gruneisen.cpp", "max_forks_repo_name": "wichoi77/alamode", "max_forks_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T14:01:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T14:01:15.000Z", "avg_line_length": 33.0260492041, "max_line_length": 127, "alphanum_fraction": 0.4952017878, "num_tokens": 7019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.056652424909793, "lm_q1q2_score": 0.02118097197516062}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <tuple>\n#include <complex>\n#include <array>\n#include <vector>\n#include <memory>\n#include <numeric>\n#include <string>\n#include <boost/format.hpp>\n\nusing namespace std;\nusing myfloat_t = double;\nusing c_t = complex<myfloat_t>;\n\ntemplate<typename T>\nstruct Rect {\n  Rect(const T& xmin = T(), const T& ymin = T(), const T& xmax = T(), const T& ymax = T())\n  : xmin_{xmin}, ymin_{ymin}, xmax_{xmax}, ymax_{ymax}\n  {\n    normalize();\n  }\n  Rect(const Rect&) = default;\n  Rect& operator=(const Rect&) = default;\n  friend bool operator==(const Rect<T>& a, const Rect<T>& b) { \n    return std::tie(a.xmin_, a.ymin_, a.xmax_, a.ymax_) == std::tie(b.xmin_, b.ymin_, b.xmax_, b.ymax_); \n  }\n  friend bool operator<(const Rect<T>& a, const Rect<T>& b) { \n    return std::tie(a.xmin_, a.ymin_, a.xmax_, a.ymax_) < std::tie(b.xmin_, b.ymin_, b.xmax_, b.ymax_); \n  }\n  friend bool operator<=(const Rect<T>& a, const Rect<T>& b) { \n    return (a < b) || (a == b); \n  }\n  friend bool operator>(const Rect<T>& a, const Rect<T>& b) { \n    return (b < a); \n  }\n  friend bool operator>=(const Rect<T>& a, const Rect<T>& b) { \n    return (b < a) || (a == b); \n  }\n  friend bool operator!=(const Rect<T>& a, const Rect<T>& b) { \n    return !(a == b); \n  }\n  friend std::ostream& operator<<(std::ostream& o, const Rect<T>& r) {\n    std::string fmts = \"[%6.5f, %6.5f, %6.5f, %6.5f]\";\n    if (std::is_integral<T>::value) {\n      fmts = \"[%d, %d, %d, %d]\";\n    }\n    boost::format fmt{fmts};\n    o << fmt % r.xmin_ % r.ymin_ % r.xmax_ % r.ymax_;\n    return o;\n  }\n  void normalize() {\n    if (xmax_ < xmin_)\n      swap(xmax_, xmin_);\n    if (ymax_ < ymin_)\n      swap(ymax_, ymin_);\n  }\n  T width() const { \n    if (std::is_integral<T>::value)\n      return xmax_ - xmin_ + 1; \n    else \n      return xmax_ - xmin_; \n  }\n  T height() const { \n    if (std::is_integral<T>::value)\n      return ymax_ - ymin_ + 1; \n    else \n      return ymax_ - ymin_; \n  }\n  void zoom(myfloat_t f) {\n    auto w = width();\n    auto h = height();\n    auto centerx = xmin_ + w/2.0;\n    auto centery = ymin_ + h/2.0;\n    auto nw = w * f;\n    auto nh = h * f;\n    xmin_ = centerx - nw/2.0;\n    ymin_ = centery - nh/2.0;\n    xmax_ = centerx + nw/2.0;\n    ymax_ = centery + nh/2.0;\n  }\n  void move(const T& x, const T& y) {\n    xmin_ += x;\n    ymin_ += y;\n    xmax_ += x;\n    ymax_ += y;\n  }\n  T xmin_, ymin_, xmax_, ymax_;\n};\n\nusing FRect = Rect<myfloat_t>;\nusing URect = Rect<unsigned>;\n\nstruct RenderParams {\n  unsigned  maxit_  { 2000 };\n  myfloat_t test_   { 4.0  };\n  unsigned  width_  { 61   };\n  unsigned  height_ { 23   };\n  myfloat_t gamma_  { 0.6  };\n  std::vector<char> alpha_ // { ' ', '.', ':', '-', '+', 'i', 'o', 'x', 'I', 'X', 'N', 'M', 'W', '%'};\n  { ' ', '.', '\\'', '`', '^', '\"', ',', ':', ';', 'I', 'l', '!', 'i', '>', '<', '~', '+', '_', '-', '?'\n  , ']', '[', '}', '{', '1', ')', '(', '|', '\\\\', '/', 't', 'f', 'j', 'r', 'x', 'n', 'u', 'v', 'c', 'z'\n  , 'X', 'Y', 'U', 'J', 'C', 'L', 'Q', '0', 'O', 'Z', 'm', 'w', 'q', 'p', 'd', 'b', 'k', 'h', 'a', 'o'\n  , '*', '#', 'M', 'W', '&', '8', '%', 'B', '@', '$'};\n  friend std::ostream& operator<<(std::ostream& o, const RenderParams& rp) {\n    boost::format fmt{\"Iterations: %d  Test:%4.2f  Gamma: %4.3f\"};\n    o << fmt % rp.maxit_ % rp.test_ % rp.gamma_;\n    return o;\n  }\n};\n\nclass MImage {\npublic:\n  explicit MImage(unsigned width, unsigned height) \n  : width_{width}, height_{height}, rpp_{nullptr}\n  , px_(width_ * height_, 0)\n  {}\n  unsigned& operator()(unsigned x, unsigned y) {\n    return px_[y * width_ + x];\n  }\n  const unsigned& operator()(unsigned x, unsigned y) const {\n    return px_[y * width_ + x];\n  }\n  unsigned width() const { return width_; }\n  unsigned height() const { return height_; }\n  MImage render(const RenderParams& param = RenderParams()) {\n    MImage out(width(), height());\n    out.rpp_ = std::unique_ptr<RenderParams>(new RenderParams(param));\n    myfloat_t maxa = static_cast<myfloat_t>(param.alpha_.size() - 1);\n    myfloat_t maxi = static_cast<myfloat_t>(param.maxit_);\n    std::transform(cbegin(), cend(), out.begin()\n      , [maxa, maxi, param](const decltype(*cbegin())& i) { return static_cast<unsigned>(pow(static_cast<myfloat_t>(i)/maxi, param.gamma_) * maxa); }\n      );\n    return out;\n  }\n  myfloat_t average() {\n    auto acc = std::accumulate(cbegin(), cend(), 0);\n    return static_cast<myfloat_t>(acc)/px_.size();\n  }\n  myfloat_t standard_derivation() {\n    auto avg = average();\n    myfloat_t res = 0;\n    for(const auto& e : px_) {\n      res += std::pow(static_cast<myfloat_t>(e) - avg, 2.0);\n    }\n    return std::sqrt(res);\n  }\n  friend std::ostream& operator<<(std::ostream& o, MImage& img) {\n    if (img.rpp_) {\n      unsigned n = 0;\n      for(const auto& e : img) {\n        o << img.rpp_->alpha_[e];\n        ++n;\n        if (n % img.width() == 0)\n          o << std::endl;\n      }\n    } else {\n      unsigned n = 0;\n      for(const auto& e : img) {\n        o << e << ' ';\n        ++n;\n        if (n % img.width() == 0)\n          o << std::endl;\n      }\n    }\n    return o;\n  }\nprivate:\n  unsigned width_, height_;\n  std::vector<unsigned> px_;\n  std::unique_ptr<RenderParams> rpp_;\npublic:\n  decltype(px_.begin()) begin() { return px_.begin(); }\n  decltype(px_.end())   end()   { return px_.end(); }\n  decltype(px_.cbegin()) cbegin() { return px_.cbegin(); }\n  decltype(px_.cend())   cend()   { return px_.cend(); }\n};\n\nstruct Mandelbrot {\n  // Mandelbrot(const FRect& r)\n  FRect r_ { -2.5, -1.5, 1.0, 1.5};\n  MImage compute(const RenderParams& param = RenderParams()) const {\n    MImage img(param.width_, param.height_);\n    double fcols = r_.width()  / param.width_;\n    double frows = r_.height() / param.height_;\n    auto iit = img.begin(); \n    for(unsigned iy = 0; iy < param.height_; ++iy) {\n      double y = r_.ymax_ - frows/2.0 - iy * frows;\n      double x = r_.xmin_ + fcols/2.0;\n      for(unsigned ix = 0; ix < param.width_; ++ix) {\n        x += fcols;\n        c_t c(x, y), cc(c);\n        unsigned i;\n        for(i = 0; norm(c) < param.test_ && i < param.maxit_ - 1; ++i) {\n          c = c * c + cc;\n          //c = pow(c, 2.6) + cc;\n        }\n        //img(ix, iy) = i;\n        *iit = i;\n        ++iit;\n      }\n    }\n    return img;\n  }\n\n};\n\nint main(int argn, char* argv[]) {\n  ios_base::sync_with_stdio(false);\n  boost::format fmt{\"gamma: %6.3f standard_derivation: %8.4f\"};\n  Mandelbrot m;\n  RenderParams rp;\n  bool ok = true;\n  std::string s;\n  do {\n    auto img = m.compute(rp);\n    auto img2 = img.render(rp);\n    std::cout << img2 << std::endl << m.r_ << rp << std::endl;\n    std::cout << \"Zoom + -  Move a w s d  Params t T i I g G r R c C Quit q:\";\n    std::cin  >> s;\n    for (auto c : s) {\n      switch(c) {\n        case '+':\n          m.r_.zoom(0.5);\n          break;\n        case '-':\n          m.r_.zoom(2.0);\n          break;\n        case 'a':\n          m.r_.move(- m.r_.width() * 0.25, 0);\n          break;\n        case 'd':\n          m.r_.move(m.r_.width() * 0.25, 0);\n          break;\n        case 'w':\n          m.r_.move(0, m.r_.height() * 0.25);\n          break;\n        case 's':\n          m.r_.move(0, -m.r_.height() * 0.25);\n          break;\n        case 't':\n          rp.test_ *= 2.0;\n          break;\n        case 'T':\n          rp.test_ *= 0.5;\n          break;\n        case 'i':\n          rp.maxit_ *= 2.0;\n          break;\n        case 'I':\n          rp.maxit_ *= 0.5;\n          break;\n        case 'g':\n          if (rp.gamma_ < 2.0)\n            rp.gamma_ += 0.1;\n          break;\n        case 'G':\n          if (rp.gamma_ > 0.1)\n            rp.gamma_ -= 0.1;\n          break;\n        case 'c':\n          rp.width_ += 4;\n          break;\n        case 'C':\n          rp.width_ -= 4;\n          break;\n        case 'r':\n          rp.height_ += 2;\n          break;\n        case 'R':\n          rp.height_ -= 2;\n          break;\n        case 'q':\n          ok = false;\n          break;\n      }\n    }\n    if(!ok)\n      break;\n  } while(1);\n  // for(myfloat_t g = 1.2; g > 0.0; g-=0.1) {\n  //   rp.gamma_ = g;\n  //   auto img2 = img.render(rp);\n  //   std::cout << fmt % g % img2.standard_derivation() << std::endl;\n  //   std::cout << img2 << std::endl;\n  // }\n  return 0;\n}", "meta": {"hexsha": "345e2ba933293cc29ded298cf58e6002beead01d", "size": 8228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/gamma.cpp", "max_stars_repo_name": "noeld/cpp", "max_stars_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "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": "experiments/gamma.cpp", "max_issues_repo_name": "noeld/cpp", "max_issues_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "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": "experiments/gamma.cpp", "max_forks_repo_name": "noeld/cpp", "max_forks_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "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.5694444444, "max_line_length": 149, "alphanum_fraction": 0.5035245503, "num_tokens": 2721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.0467249614469178, "lm_q1q2_score": 0.02117864237387763}}
{"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 simulate_aig.hpp\n *\n * @brief AIG simuation\n *\n * @author Mathias Soeken\n * @since  2.0\n */\n\n#ifndef SIMULATE_AIG_HPP\n#define SIMULATE_AIG_HPP\n\n#include <functional>\n#include <map>\n#include <unordered_map>\n\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/algorithm_ext/push_back.hpp>\n\n#include <core/properties.hpp>\n#include <core/utils/timer.hpp>\n#include <classical/aig.hpp>\n#include <classical/utils/aig_dfs.hpp>\n#include <classical/utils/aig_utils.hpp>\n#include <classical/utils/truth_table_utils.hpp>\n\n#include <cuddObj.hh>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Abstract class for simulators                                              *\n ******************************************************************************/\n\ntemplate<typename T>\nclass aig_simulator\n{\npublic:\n  /**\n   * @brief Simulator routine when input is encountered\n   *\n   * @param node AIG node reference in the `aig' graph\n   * @param name Name of that node\n   * @param pos  Position of that node (usually wrt. to `aig' inputs vector)\n   * @param aig  AIG graph\n   */\n  virtual T get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const = 0;\n  virtual T get_constant() const = 0;\n  virtual T invert( const T& v ) const = 0;\n  virtual T and_op( const aig_node& node, const T& v1, const T& v2 ) const = 0;\n\n  virtual bool terminate( const aig_node& node, const aig_graph& aig ) const\n  {\n    return false;\n  }\n};\n\n/******************************************************************************\n * Several simulator implementations                                          *\n ******************************************************************************/\n\nclass pattern_simulator : public aig_simulator<bool>\n{\npublic:\n  pattern_simulator( const boost::dynamic_bitset<>& pattern );\n\n  bool get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  bool get_constant() const;\n  bool invert( const bool& v ) const;\n  bool and_op( const aig_node& node, const bool& v1, const bool& v2 ) const;\n\nprivate:\n  boost::dynamic_bitset<> pattern;\n};\n\nclass simple_assignment_simulator : public aig_simulator<bool>\n{\npublic:\n  using aig_name_value_map = std::unordered_map<std::string, bool>;\n\n  simple_assignment_simulator( const aig_name_value_map& assignment );\n\n  bool get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  bool get_constant() const;\n  bool invert( const bool& v ) const;\n  bool and_op( const aig_node& node, const bool& v1, const bool& v2 ) const;\n\nprivate:\n  const aig_name_value_map& assignment;\n};\n\nclass simple_node_assignment_simulator : public aig_simulator<bool>\n{\npublic:\n  using aig_node_value_map = std::unordered_map<aig_node, bool>;\n\n  simple_node_assignment_simulator( const aig_node_value_map& assignment );\n\n  bool get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  bool get_constant() const;\n  bool invert( const bool& v ) const;\n  bool and_op( const aig_node& node, const bool& v1, const bool& v2 ) const;\n  bool terminate( const aig_node& node, const aig_graph& aig ) const;\n\nprivate:\n  const aig_node_value_map& assignment;\n};\n\nclass word_assignment_simulator : public aig_simulator<boost::dynamic_bitset<>>\n{\npublic:\n  using aig_name_value_map = std::unordered_map<std::string, boost::dynamic_bitset<>>;\n\n  word_assignment_simulator( const aig_name_value_map& assignment );\n\n  boost::dynamic_bitset<> get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  boost::dynamic_bitset<> get_constant() const;\n  boost::dynamic_bitset<> invert( const boost::dynamic_bitset<>& v ) const;\n  boost::dynamic_bitset<> and_op( const aig_node& node, const boost::dynamic_bitset<>& v1, const boost::dynamic_bitset<>& v2 ) const;\n\nprivate:\n  const aig_name_value_map& assignment;\n};\n\nclass word_node_assignment_simulator : public aig_simulator<boost::dynamic_bitset<>>\n{\npublic:\n  using aig_node_value_map = std::unordered_map<aig_node, boost::dynamic_bitset<>>;\n\n  word_node_assignment_simulator( const aig_node_value_map& assignment );\n\n  boost::dynamic_bitset<> get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  boost::dynamic_bitset<> get_constant() const;\n  boost::dynamic_bitset<> invert( const boost::dynamic_bitset<>& v ) const;\n  boost::dynamic_bitset<> and_op( const aig_node& node, const boost::dynamic_bitset<>& v1, const boost::dynamic_bitset<>& v2 ) const;\n  bool terminate( const aig_node& node, const aig_graph& aig ) const;\n\nprivate:\n  const aig_node_value_map& assignment;\n};\n\nclass tt_simulator : public aig_simulator<tt>\n{\npublic:\n  tt get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  tt get_constant() const;\n  tt invert( const tt& v ) const;\n  tt and_op( const aig_node& node, const tt& v1, const tt& v2 ) const;\n};\n\nclass bdd_simulator : public aig_simulator<BDD>\n{\npublic:\n  bdd_simulator() : mgr( Cudd() ) {}\n  bdd_simulator( const Cudd& mgr ) : mgr( mgr ) {}\n\n  BDD get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  BDD get_constant() const;\n  BDD invert( const BDD& v ) const;\n  BDD and_op( const aig_node& node, const BDD& v1, const BDD& v2 ) const;\n\nprotected:\n  Cudd mgr;\n};\n\nclass depth_simulator : public aig_simulator<unsigned>\n{\npublic:\n  unsigned get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const;\n  unsigned get_constant() const;\n  unsigned invert( const unsigned& v ) const;\n  unsigned and_op( const aig_node& node, const unsigned& v1, const unsigned& v2 ) const;\n};\n\ntemplate<typename T>\nclass partial_simulator : public aig_simulator<T>\n{\npublic:\n  partial_simulator( const aig_simulator<T>& total_simulator,\n                     const std::map<aig_node, T>& assignment,\n                     const aig_graph& aig )\n    : total_simulator( total_simulator ),\n      assignment( assignment )\n  {\n    for ( const auto& n : aig_info( aig ).inputs )\n    {\n      if ( assignment.find( n ) == assignment.end() )\n      {\n        real_inputs.push_back( n );\n      }\n    }\n  }\n\n  T get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const\n  {\n    /* Is in assignment? */\n    auto it = assignment.find( node );\n    if ( it != assignment.end() )\n    {\n      return it->second;\n    }\n    else\n    {\n      unsigned real_pos = std::distance( real_inputs.begin(), boost::find( real_inputs, node ) );\n      return total_simulator.get_input( node, name, real_pos, aig );\n    }\n  }\n\n  T get_constant() const { return total_simulator.get_constant(); }\n  T invert( const T& v ) const { return total_simulator.invert( v ); }\n  T and_op( const aig_node& node, const T& v1, const T& v2 ) const { return total_simulator.and_op( node, v1, v2 ); }\n\nprivate:\n  const aig_simulator<T>& total_simulator;\n  const std::map<aig_node, T>& assignment;\n\n  std::vector<aig_node> real_inputs;\n};\n\ntemplate<typename T>\nclass aig_partial_node_assignment_simulator : public aig_simulator<T>\n{\npublic:\n  aig_partial_node_assignment_simulator( const aig_simulator<T>& total_simulator,\n                                         const std::map<aig_node, T>& assignment,\n                                         const T& default_value )\n    : total_simulator( total_simulator ),\n      assignment( assignment ),\n      default_value( default_value ) {}\n\n  T get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const\n  {\n    auto it = assignment.find( node );\n    if ( it == assignment.end() )\n    {\n      std::cout << \"[w] no assignment given for '\" << node << \"', assume default\" << std::endl;\n      return default_value;\n    }\n    else\n    {\n      return it->second;\n    }\n  }\n\n  T get_constant() const { return total_simulator.get_constant(); }\n  T invert( const T& v ) const { return total_simulator.invert( v ); }\n  T and_op( const aig_node& node, const T& v1, const T& v2 ) const\n  {\n    auto it = assignment.find( node );\n    if ( it == assignment.end() )\n    {\n      return total_simulator.and_op( node, v1, v2 );\n    }\n    else\n    {\n      return it->second;\n    }\n  }\n\n  bool terminate( const aig_node& node, const aig_graph& aig ) const\n  {\n    return assignment.find( node ) != assignment.end();\n  }\n\nprivate:\n  const aig_simulator<T>& total_simulator;\n  const std::map<aig_node, T>& assignment;\n  T default_value;\n};\n\ntemplate<typename T>\nclass aig_lambda_simulator : public aig_simulator<T>\n{\npublic:\n  aig_lambda_simulator( const std::function<T(const aig_node&, const std::string&, unsigned, const aig_graph&)>& get_input_func,\n                        const std::function<T()>& get_constant_func,\n                        const std::function<T(const T&)>& invert_func,\n                        const std::function<T(const aig_node&, const T&, const T&)>& and_op_func )\n    : get_input_func( get_input_func ),\n      get_constant_func( get_constant_func ),\n      invert_func( invert_func ),\n      and_op_func( and_op_func )\n  {\n  }\n\n  T get_input( const aig_node& node, const std::string& name, unsigned pos, const aig_graph& aig ) const\n  {\n    return get_input_func( node, name, pos, aig );\n  }\n\n  T get_constant() const\n  {\n    return get_constant_func();\n  }\n\n  T invert( const T& v ) const\n  {\n    return invert_func( v );\n  }\n\n  T and_op( const aig_node& node, const T& v1, const T& v2 ) const\n  {\n    return and_op_func( node, v1, v2 );\n  }\n\nprivate:\n  std::function<T(const aig_node&, const std::string&, unsigned, const aig_graph&)> get_input_func;\n  std::function<T()> get_constant_func;\n  std::function<T(const T&)> invert_func;\n  std::function<T(const aig_node&, const T&, const T&)> and_op_func;\n};\n\n/******************************************************************************\n * DFS visitor for actual simulation                                          *\n ******************************************************************************/\n\nusing aig_node_color_map = circuit_traits<aig_graph>::node_color_map;\n\ntemplate<typename T>\nstruct simulate_aig_node_visitor : public aig_dfs_visitor\n{\npublic:\n  simulate_aig_node_visitor( const aig_graph& aig, const aig_simulator<T>& simulator, std::map<aig_node, T>& node_values )\n    : aig_dfs_visitor( aig ),\n      simulator( simulator ),\n      node_values( node_values ) {}\n\n  void finish_input( const aig_node& node, const std::string& name, const aig_graph& aig )\n  {\n    unsigned pos = std::distance( graph_info.inputs.begin(), boost::find( graph_info.inputs, node ) );\n    node_values[node] = simulator.get_input( node, name, pos, aig );\n  }\n\n  void finish_constant( const aig_node& node, const aig_graph& aig )\n  {\n    node_values[node] = simulator.get_constant();\n  }\n\n  void finish_aig_node( const aig_node& node, const aig_function& left, const aig_function& right, const aig_graph& aig )\n  {\n    T tleft, tright;\n\n    const auto itleft  = node_values.find( left.node );\n    const auto itright = node_values.find( right.node );\n\n    if ( itleft != node_values.end() )\n    {\n      tleft = left.complemented ? simulator.invert( itleft->second ) : itleft->second;\n    }\n    if ( itright != node_values.end() )\n    {\n      tright = right.complemented ? simulator.invert( itright->second ) : itright->second;\n    }\n\n    node_values[node] = simulator.and_op( node, tleft, tright );\n  }\n\nprivate:\n  const aig_simulator<T>& simulator;\n  std::map<aig_node, T>& node_values;\n};\n\n/******************************************************************************\n * Methods to trigger simulation                                              *\n ******************************************************************************/\n\ntemplate<typename T>\nT simulate_aig_node( const aig_graph& aig, const aig_node& node,\n                     const aig_simulator<T>& simulator,\n                     aig_node_color_map& colors,\n                     std::map<aig_node, T>& node_values )\n{\n  boost::depth_first_visit( aig, node,\n                            simulate_aig_node_visitor<T>( aig, simulator, node_values ),\n                            boost::make_assoc_property_map( colors ),\n                            [&simulator]( const aig_node& node, const aig_graph& aig ) { return simulator.terminate( node, aig ); } );\n\n  return node_values[node];\n}\n\ntemplate<typename T>\nT simulate_aig_node( const aig_graph& aig, const aig_node& node,\n                     const aig_simulator<T>& simulator )\n{\n  aig_node_color_map colors;\n  std::map<aig_node, T> node_values;\n\n  return simulate_aig_node<T>( aig, node, simulator, colors, node_values );\n}\n\ntemplate<typename T>\nT simulate_aig_function( const aig_graph& aig, const aig_function& f,\n                         const aig_simulator<T>& simulator,\n                         aig_node_color_map& colors,\n                         std::map<aig_node, T>& node_values )\n{\n  T value = simulate_aig_node<T>( aig, f.node, simulator, colors, node_values );\n  return f.complemented ? simulator.invert( value ) : value;\n}\n\ntemplate<typename T>\nT simulate_aig_function( const aig_graph& aig, const aig_function& f,\n                         const aig_simulator<T>& simulator )\n{\n  T value = simulate_aig_node<T>( aig, f.node, simulator );\n  return f.complemented ? simulator.invert( value ) : value;\n}\n\ntemplate<typename T>\nstd::map<aig_function, T> simulate_aig( const aig_graph& aig, const aig_simulator<T>& simulator,\n                                        const std::vector< aig_function >& fs,\n                                        const properties::ptr& settings = properties::ptr(),\n                                        const properties::ptr& statistics = properties::ptr() )\n{\n  /* settings */\n  auto verbose = get( settings, \"verbose\", false );\n\n  /* timer */\n  properties_timer t( statistics );\n\n  aig_node_color_map colors;\n  std::map<aig_node, T> node_values;\n\n  std::map<aig_function, T> results;\n  \n  for ( const auto& f : fs )\n  {\n    if ( verbose )\n    {\n      std::cout << \"[i] simulate '\" << f.node << \"'\" << std::endl;\n    }\n    T value = simulate_aig_node<T>( aig, f.node, simulator, colors, node_values );\n\n    /* value may need to be inverted */\n    results[f] = f.complemented ? simulator.invert( value ) : value;\n  }\n\n  set( statistics, \"node_values\", node_values );\n\n  return results;\n}\n\ntemplate<typename T>\nstd::map<aig_function, T> simulate_aig_full( const aig_graph& aig, const aig_simulator<T>& simulator,\n                                             const properties::ptr& settings = properties::ptr(),\n                                             const properties::ptr& statistics = properties::ptr() )\n{\n  auto in_degrees = precompute_in_degrees( aig );\n\n  std::vector<aig_function> fs;\n\n  std::set<aig_node> ignore_nodes;\n  ignore_nodes.insert( 0 );\n  for ( const auto& i : aig_info( aig ).inputs )\n  {\n    ignore_nodes.insert( i );\n  }\n  for ( const auto& o : aig_info( aig ).outputs )\n  {\n    ignore_nodes.insert( o.first.node );\n    fs.push_back( o.first );\n  }\n\n  for ( const auto& node : boost::make_iterator_range( vertices( aig ) ) )\n  {\n    if ( ignore_nodes.find( node ) != ignore_nodes.end() )\n    {\n      continue;\n    }\n\n    if ( in_degrees[ node ] == 0u )\n    {\n      fs.push_back( aig_function( { node, false } ) );\n    }\n  }\n\n  return simulate_aig( aig, simulator, fs, settings, statistics );\n}\n\ntemplate<typename T>\nstd::map<aig_function, T> simulate_aig( const aig_graph& aig, const aig_simulator<T>& simulator,\n                                        const properties::ptr& settings = properties::ptr(),\n                                        const properties::ptr& statistics = properties::ptr() )\n{\n  /* settings */\n  auto verbose = get( settings, \"verbose\", false );\n\n  /* timer */\n  properties_timer t( statistics );\n\n  aig_node_color_map colors;\n  std::map<aig_node, T> node_values;\n\n  std::map<aig_function, T> results;\n  \n  for ( const auto& o : aig_info( aig ).outputs )\n  {\n    if ( verbose )\n    {\n      std::cout << \"[i] simulate '\" << o.second << \"'\" << std::endl;\n    }\n    T value = simulate_aig_node<T>( aig, o.first.node, simulator, colors, node_values );\n\n    /* value may need to be inverted */\n    results[o.first] = o.first.complemented ? simulator.invert( value ) : value;\n  }\n\n  set( statistics, \"node_values\", node_values );\n\n  return results;\n}\n\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": "df1075f9e74c28684f42f26eae51dfc0b1f0286d", "size": 17957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/classical/functions/simulate_aig.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": "src/classical/functions/simulate_aig.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": "src/classical/functions/simulate_aig.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": 32.5898366606, "max_line_length": 134, "alphanum_fraction": 0.6403630896, "num_tokens": 4485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.061875987886074985, "lm_q1q2_score": 0.021135754597340517}}
{"text": "//\n// Created by jiangkangkang on 2020/3/9.\n//\n\n#ifndef R_BUILD\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#else\n\n#include <RcppEigen.h>\n\n#endif\n\n#include <string.h>\n\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef R_BUILD\nEigen::MatrixXd Pointer2MatrixXd(double *x, int x_row, int x_col) {\n    Eigen::MatrixXd x_matrix(x_row, x_col);\n    int i, j;\n    for (i = 0; i < x_row; i++) {\n        for (j = 0; j < x_col; j++) {\n            x_matrix(i, j) = x[i * x_col + j];\n        }\n    }\n    return x_matrix;\n}\n\nEigen::MatrixXi Pointer2MatrixXi(int *x, int x_row, int x_col) {\n    Eigen::MatrixXi x_matrix(x_row, x_col);\n    int i, j;\n    for (i = 0; i < x_row; i++) {\n        for (j = 0; j < x_col; j++) {\n            x_matrix(i, j) = x[i * x_col + j];\n        }\n    }\n    return x_matrix;\n}\n\nEigen::VectorXd Pointer2VectorXd(double *x, int x_len) {\n    Eigen::VectorXd x_vector(x_len);\n    int i;\n    for (i = 0; i < x_len; i++) {\n        x_vector[i] = x[i];\n    }\n    return x_vector;\n}\n\nEigen::VectorXi Pointer2VectorXi(int *x, int x_len) {\n    Eigen::VectorXi x_vector(x_len);\n    int i;\n    for (i = 0; i < x_len; i++) {\n        x_vector[i] = x[i];\n    }\n    return x_vector;\n}\n\nvoid MatrixXd2Pointer(Eigen::MatrixXd x_matrix, double *x) {\n    int x_matrix_row, x_matrix_col, i, j;\n    x_matrix_row = x_matrix.rows();\n    x_matrix_col = x_matrix.cols();\n    for (i = 0; i < x_matrix_row; i++) {\n        for (j = 0; j < x_matrix_col; j++) {\n            x[i * x_matrix_col + j] = x_matrix(i, j);\n        }\n    }\n    return;\n}\n\n// void MatrixXi2Pointer(Eigen::MatrixXi x_matrix, int *x)\n// {\n//     int x_matrix_row, x_matrix_col, i, j;\n//     x_matrix_row = x_matrix.rows();\n//     x_matrix_col = x_matrix.cols();\n//     for (i = 0; i < x_matrix_row; i++)\n//     {\n//         for (j = 0; j < x_matrix_col; j++)\n//         {\n//             x[i * x_matrix_col + j] = x_matrix(i, j);\n//         }\n//     }\n// }\n\nvoid VectorXd2Pointer(Eigen::VectorXd x_vector, double *x) {\n    int x_matrix_len, i;\n    x_matrix_len = x_vector.size();\n\n    for (i = 0; i < x_matrix_len; i++) {\n        x[i] = x_vector[i];\n    }\n    return;\n}\n\n// void VectorXi2Pointer(Eigen::VectorXi x_vector, int *x)\n// {\n//     int x_matrix_len, i;\n//     x_matrix_len = x_vector.size();\n\n//     for (i = 0; i < x_matrix_len; i++)\n//     {\n//         x[i] = x_vector[i];\n//     }\n// }\n#endif\n\nEigen::VectorXi find_ind(Eigen::VectorXi &L, Eigen::VectorXi &index, Eigen::VectorXi &gsize, int beta_size, int N) {\n    if (L.size() == N) {\n        return Eigen::VectorXi::LinSpaced(beta_size, 0, beta_size - 1);\n    } else {\n        int mark = 0;\n        Eigen::VectorXi ind = Eigen::VectorXi::Zero(beta_size);\n\n        for (int i = 0; i < L.size(); i++) {\n            ind.segment(mark, gsize(L(i))) =\n                Eigen::VectorXi::LinSpaced(gsize(L(i)), index(L(i)), index(L(i)) + gsize(L(i)) - 1);\n            mark = mark + gsize(L(i));\n        }\n        return ind.head(mark).eval();\n    }\n}\n\nEigen::Matrix<Eigen::MatrixXd, -1, -1> invPhi(Eigen::Matrix<Eigen::MatrixXd, -1, -1> &Phi, int N) {\n    Eigen::Matrix<Eigen::MatrixXd, -1, -1> invPhi(N, 1);\n    int row;\n    for (int i = 0; i < N; i++) {\n        row = (Phi(i, 0)).rows();\n        invPhi(i, 0) = (Phi(i, 0)).ldlt().solve(Eigen::MatrixXd::Identity(row, row));\n    }\n    return invPhi;\n}\n\nvoid slice_assignment(Eigen::VectorXd &nums, Eigen::VectorXi &ind, double value) {\n    if (ind.size() != 0) {\n        for (int i = 0; i < ind.size(); i++) {\n            nums(ind(i)) = value;\n        }\n    }\n    return;\n}\n\n// Eigen::VectorXd vector_slice(Eigen::VectorXd &nums, Eigen::VectorXi &ind)\n// {\n//     Eigen::VectorXd sub_nums(ind.size());\n//     if (ind.size() != 0)\n//     {\n//         for (int i = 0; i < ind.size(); i++)\n//         {\n//             sub_nums(i) = nums(ind(i));\n//         }\n//     }\n//     return sub_nums;\n// }\n\nEigen::VectorXi vector_slice(Eigen::VectorXi &nums, Eigen::VectorXi &ind) {\n    Eigen::VectorXi sub_nums(ind.size());\n    if (ind.size() != 0) {\n        for (int i = 0; i < ind.size(); i++) {\n            sub_nums(i) = nums(ind(i));\n        }\n    }\n    return sub_nums;\n}\n\n// Eigen::MatrixXd matrix_slice(Eigen::MatrixXd &nums, Eigen::VectorXi &ind, int axis)\n// {\n//     if (axis == 0)\n//     {\n//         Eigen::MatrixXd sub_nums(ind.size(), nums.cols());\n//         if (ind.size() != 0)\n//         {\n//             for (int i = 0; i < ind.size(); i++)\n//             {\n//                 sub_nums.row(i) = nums.row(ind(i));\n//             }\n//         }\n//         return sub_nums;\n//     }\n//     else\n//     {\n//         Eigen::MatrixXd sub_nums(nums.rows(), ind.size());\n//         if (ind.size() != 0)\n//         {\n//             for (int i = 0; i < ind.size(); i++)\n//             {\n//                 sub_nums.col(i) = nums.col(ind(i));\n//             }\n//         }\n//         return sub_nums;\n//     }\n// }\n\n// Eigen::MatrixXd row_slice(Eigen::MatrixXd &nums, Eigen::VectorXi &ind)\n// {\n//     Eigen::MatrixXd sub_nums(ind.size(), nums.cols());\n//     if (ind.size() != 0)\n//     {\n//         for (int i = 0; i < ind.size(); i++)\n//         {\n//             sub_nums.row(i) = nums.row(ind(i));\n//         }\n//     }\n//     return sub_nums;\n// }\n\n// Eigen::VectorXi get_value_index(Eigen::VectorXd &nums, double value)\n// {\n//     Eigen::VectorXi ind(nums.size());\n//     int cur_index = 0;\n//     for (int i = 0; i < nums.size(); i++)\n//     {\n//         if (nums(i) == value)\n//         {\n//             ind(cur_index) = i;\n//             cur_index += 1;\n//         }\n//     }\n//     return ind.head(cur_index).eval();\n// }\n\n// replace B by C in A\n// to do : binary search\nEigen::VectorXi diff_union(Eigen::VectorXi A, Eigen::VectorXi &B, Eigen::VectorXi &C) {\n    unsigned int k;\n    for (unsigned int i = 0; i < B.size(); i++) {\n        for (k = 0; k < A.size(); k++) {\n            if (B(i) == A(k)) {\n                A(k) = C(i);\n                break;\n            }\n        }\n    }\n    sort(A.data(), A.data() + A.size());\n    return A;\n}\n\nEigen::VectorXi min_k(Eigen::VectorXd &vec, int k, bool sort_by_value) {\n    Eigen::VectorXi ind = Eigen::VectorXi::LinSpaced(vec.size(), 0, vec.size() - 1);  // [0 1 2 3 ... N-1]\n    auto rule = [vec](int i, int j) -> bool { return vec(i) < vec(j); };              // sort rule\n    std::nth_element(ind.data(), ind.data() + k, ind.data() + ind.size(), rule);\n    if (sort_by_value) {\n        std::sort(ind.data(), ind.data() + k, rule);\n    } else {\n        std::sort(ind.data(), ind.data() + k);\n    }\n\n    return ind.head(k).eval();\n}\n\nEigen::VectorXi max_k(Eigen::VectorXd &vec, int k, bool sort_by_value) {\n    Eigen::VectorXi ind = Eigen::VectorXi::LinSpaced(vec.size(), 0, vec.size() - 1);  // [0 1 2 3 ... N-1]\n    auto rule = [vec](int i, int j) -> bool { return vec(i) > vec(j); };              // sort rule\n    std::nth_element(ind.data(), ind.data() + k, ind.data() + ind.size(), rule);\n    if (sort_by_value) {\n        std::sort(ind.data(), ind.data() + k, rule);\n    } else {\n        std::sort(ind.data(), ind.data() + k);\n    }\n    return ind.head(k).eval();\n}\n\n// Eigen::VectorXi max_k_2(Eigen::VectorXd &vec, int k)\n// {\n//     Eigen::VectorXi ind = Eigen::VectorXi::LinSpaced(vec.size(), 0, vec.size() - 1); //[0 1 2 3 ... N-1]\n//     auto rule = [vec](int i, int j) -> bool\n//     {\n//         return vec(i) > vec(j);\n//     }; // sort rule\n//     std::nth_element(ind.data(), ind.data() + k, ind.data() + ind.size(), rule);\n//     std::sort(ind.data(), ind.data() + k);\n//     return ind.head(k).eval();\n// }\n\n// Ac\nEigen::VectorXi Ac(Eigen::VectorXi &A, int N) {\n    int A_size = A.size();\n    if (A_size == 0) {\n        return Eigen::VectorXi::LinSpaced(N, 0, N - 1);\n    } else if (A_size == N) {\n        Eigen::VectorXi I(0);\n        return I;\n    } else {\n        Eigen::VectorXi I(N - A_size);\n        int cur_index = 0;\n        int A_index = 0;\n        for (int i = 0; i < N; i++) {\n            if (A_index >= A_size) {\n                I(cur_index) = i;\n                cur_index += 1;\n                continue;\n            }\n            if (i != A(A_index)) {\n                I(cur_index) = i;\n                cur_index += 1;\n            } else {\n                A_index += 1;\n            }\n        }\n        return I;\n    }\n}\n\n// // Ac\n// Eigen::VectorXi Ac(Eigen::VectorXi &A, Eigen::VectorXi &U)\n// {\n//     int A_size = A.size();\n//     int N = U.size();\n//     if (A_size == 0)\n//     {\n//         return U;\n//     }\n//     else if (A_size == N)\n//     {\n//         Eigen::VectorXi I(0);\n//         return I;\n//     }\n//     else\n//     {\n//         Eigen::VectorXi I(N - A_size);\n//         int cur_index = 0;\n//         int A_index = 0;\n//         for (int i = 0; i < N; i++)\n//         {\n//             if (A_index < A.size() && U(i) == A(A_index))\n//             {\n//                 A_index += 1;\n//                 continue;\n//             }\n//             else\n//             {\n//                 I(cur_index) = U(i);\n//                 cur_index += 1;\n//             }\n//         }\n//         return I;\n//     }\n// }\n\nvoid slice(Eigen::VectorXd &nums, Eigen::VectorXi &ind, Eigen::VectorXd &A, int axis) {\n    if (ind.size() == 0) {\n        A = Eigen::VectorXd::Zero(0);\n    } else {\n        A = Eigen::VectorXd::Zero(ind.size());\n        for (int i = 0; i < ind.size(); i++) {\n            A(i) = nums(ind(i));\n        }\n    }\n    return;\n}\n\nvoid slice(Eigen::MatrixXd &nums, Eigen::VectorXi &ind, Eigen::MatrixXd &A, int axis) {\n    if (axis == 0) {\n        A = Eigen::MatrixXd::Zero(ind.size(), nums.cols());\n        if (ind.size() != 0) {\n            for (int i = 0; i < ind.size(); i++) {\n                A.row(i) = nums.row(ind(i));\n            }\n        }\n    } else {\n        A = Eigen::MatrixXd::Zero(nums.rows(), ind.size());\n        if (ind.size() != 0) {\n            for (int i = 0; i < ind.size(); i++) {\n                A.col(i) = nums.col(ind(i));\n            }\n        }\n    }\n    return;\n}\n\nvoid slice(Eigen::SparseMatrix<double> &nums, Eigen::VectorXi &ind, Eigen::SparseMatrix<double> &A, int axis) {\n    if (axis == 0) {\n        Eigen::SparseMatrix<double, Eigen::RowMajor> nums_row(nums);\n        Eigen::SparseMatrix<double, Eigen::RowMajor> A_row(ind.size(), nums.cols());\n        A_row.reserve(nums.nonZeros());\n\n        if (ind.size() != 0) {\n            for (int i = 0; i < ind.size(); i++) {\n                A_row.row(i) = nums_row.row(ind(i));\n            }\n        }\n\n        A = A_row;\n    } else {\n        A.resize(nums.rows(), ind.size());\n        A.reserve(nums.nonZeros());\n        if (ind.size() != 0) {\n            for (int i = 0; i < ind.size(); i++) {\n                A.col(i) = nums.col(ind(i));\n            }\n        }\n    }\n    return;\n}\n\nvoid slice_restore(Eigen::VectorXd &A, Eigen::VectorXi &ind, Eigen::VectorXd &nums, int axis) {\n    if (ind.size() == 0) {\n        nums = Eigen::VectorXd::Zero(nums.size());\n    } else {\n        nums = Eigen::VectorXd::Zero(nums.size());\n        for (int i = 0; i < ind.size(); i++) {\n            nums(ind(i)) = A(i);\n        }\n    }\n    return;\n}\n\nvoid slice_restore(Eigen::MatrixXd &A, Eigen::VectorXi &ind, Eigen::MatrixXd &nums, int axis) {\n    if (axis == 0) {\n        nums = Eigen::MatrixXd::Zero(nums.rows(), nums.cols());\n        if (ind.size() != 0) {\n            for (int i = 0; i < ind.size(); i++) {\n                nums.row(ind(i)) = A.row(i);\n            }\n        }\n    } else {\n        nums = Eigen::MatrixXd::Zero(nums.rows(), nums.cols());\n        if (ind.size() != 0) {\n            for (int i = 0; i < ind.size(); i++) {\n                nums.col(ind(i)) = A.col(i);\n            }\n        }\n    }\n    return;\n}\n\nvoid coef_set_zero(int p, int M, Eigen::VectorXd &beta, double &coef0) {\n    beta = Eigen::VectorXd::Zero(p);\n    coef0 = 0.;\n    return;\n}\n\nvoid coef_set_zero(int p, int M, Eigen::MatrixXd &beta, Eigen::VectorXd &coef0) {\n    beta = Eigen::MatrixXd::Zero(p, M);\n    coef0 = Eigen::VectorXd::Zero(M);\n    return;\n}\n\nEigen::VectorXd array_product(Eigen::VectorXd &A, Eigen::VectorXd &B, int axis) {\n    A = A.array() * B.array();\n    return A;\n}\n\nEigen::MatrixXd array_product(Eigen::MatrixXd &A, Eigen::VectorXd &B, int axis) {\n    if (axis == 0) {\n        for (int i = 0; i < A.rows(); i++) {\n            A.row(i) = A.row(i).array() * B.array();\n        }\n    } else {\n        for (int i = 0; i < A.cols(); i++) {\n            A.col(i) = A.col(i).array() * B.array();\n        }\n    }\n    return A;\n}\n\n// Eigen::SparseMatrix<double> array_product(Eigen::SparseMatrix<double> &A, Eigen::VectorXd &B, int axis)\n// {\n//     for (int i = 0; i < A.cols(); i++)\n//     {\n//         A.col(i) = A.col(i) * B;\n//     }\n//     return A;\n// }\n\nvoid array_quotient(Eigen::VectorXd &A, Eigen::VectorXd &B, int axis) {\n    A = A.array() / B.array();\n    return;\n}\nvoid array_quotient(Eigen::MatrixXd &A, Eigen::VectorXd &B, int axis) {\n    if (axis == 0) {\n        for (int i = 0; i < A.rows(); i++) {\n            A.row(i) = A.row(i).array() / B.array();\n        }\n    } else {\n        for (int i = 0; i < A.cols(); i++) {\n            A.col(i) = A.col(i).array() / B.array();\n        }\n    }\n    return;\n}\n\ndouble matrix_dot(Eigen::VectorXd &A, Eigen::VectorXd &B) { return A.dot(B); }\n\nEigen::VectorXd matrix_dot(Eigen::MatrixXd &A, Eigen::VectorXd &B) { return A.transpose() * B; }\n\n// void matrix_sqrt(Eigen::MatrixXd &A, Eigen::MatrixXd &B)\n// {\n//     A.sqrt().evalTo(B);\n// }\n\n// void matrix_sqrt(Eigen::SparseMatrix<double> &A, Eigen::MatrixXd &B)\n// {\n//     if (A.rows() == 1)\n//     {\n//         B = Eigen::MatrixXd::Ones(1, 1) * A.cwiseSqrt();\n//     }\n//     else\n//     {\n//         Eigen::SelfAdjointEigenSolver<Eigen::SparseMatrix<double>>\n//             adjoint_eigen_solver(A);\n//         // const auto &eigenvalues = adjoint_eigen_solver.eigenvalues();\n//         // CHECK_GT(eigenvalues.minCoeff(), -1e-5) //R.minCoeff() 意思是 min(R(:))最小值\n//         //     << \"MatrixSqrt failed with negative eigenvalues: \"\n//         //     << eigenvalues.transpose();\n\n//         B = adjoint_eigen_solver.eigenvectors() * (adjoint_eigen_solver.eigenvalues().cwiseSqrt().asDiagonal()) *\n//         adjoint_eigen_solver.eigenvectors().transpose();\n//         //    .cwiseMax(Eigen::Matrix<FloatType, N, 1>::Zero()) //R.cwiseMax(P)\n//         //    .cwiseSqrt()  // R.cwiseSqrt()\n//         //    .asDiagonal() * // x.asDiagonal()\n//         //    adjoint_eigen_solver.eigenvectors().transpose();\n//     }\n// }\n\nvoid add_constant_column(Eigen::MatrixXd &X) {\n    X.col(0) = Eigen::MatrixXd::Ones(X.rows(), 1);\n    return;\n}\n\nvoid add_constant_column(Eigen::SparseMatrix<double> &X) {\n    for (int i = 0; i < X.rows(); i++) {\n        X.insert(i, 0) = 1.0;\n    }\n    return;\n}\n\n// void set_nonzeros(Eigen::MatrixXd &X, Eigen::MatrixXd &x)\n// {\n//     return;\n// }\n\n// void set_nonzeros(Eigen::SparseMatrix<double> &X, Eigen::SparseMatrix<double> &x)\n// {\n//     X.reserve(x.nonZeros() + x.rows());\n// }\n\n// void overload_ldlt(Eigen::SparseMatrix<double> &X_new, Eigen::SparseMatrix<double> &X, Eigen::VectorXd &Z,\n// Eigen::VectorXd &beta)\n// {\n//     // Eigen::SparseMatrix<double> XTX = X_new.transpose() * X;\n\n//     // Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n//     // solver.compute(X_new.transpose() * X);\n//     // beta = solver.solve(X_new.transpose() * Z);\n//     Eigen::MatrixXd XTX = X_new.transpose() * X;\n//     beta = (XTX).ldlt().solve(X_new.transpose() * Z);\n//     return;\n// }\n\n// void overload_ldlt(Eigen::SparseMatrix<double> &X_new, Eigen::SparseMatrix<double> &X, Eigen::MatrixXd &Z,\n// Eigen::MatrixXd &beta)\n// {\n//     // Eigen::SparseMatrix<double> XTX = X_new.transpose() * X;\n\n//     // Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n//     // solver.compute(X_new.transpose() * X);\n//     // beta = solver.solve(X_new.transpose() * Z);\n\n//     Eigen::MatrixXd XTX = X_new.transpose() * X;\n\n//     beta = (XTX).ldlt().solve(X_new.transpose() * Z);\n\n//     return;\n// }\n\n// void overload_ldlt(Eigen::MatrixXd &X_new, Eigen::MatrixXd &X, Eigen::VectorXd &Z, Eigen::VectorXd &beta)\n// {\n//     beta = (X_new.transpose() * X).ldlt().solve(X_new.transpose() * Z);\n//     return;\n// }\n\n// void overload_ldlt(Eigen::MatrixXd &X_new, Eigen::MatrixXd &X, Eigen::MatrixXd &Z, Eigen::MatrixXd &beta)\n// {\n//     beta = (X_new.transpose() * X).ldlt().solve(X_new.transpose() * Z);\n//     return;\n// }\n\n// bool check_ill_condition(Eigen::MatrixXd &M){\n//     Eigen::JacobiSVD<Eigen::MatrixXd> svd(M);\n//     double l1 = svd.singularValues()(0);\n//     double l2 = svd.singularValues()(svd.singularValues().size()-1);\n//     return ((l2 == 0 || l1 / l2 > 1e+10) ? true : false);\n// }\n\n// to do\nvoid add_weight(Eigen::MatrixXd &x, Eigen::VectorXd &y, Eigen::VectorXd weights) {\n    Eigen::VectorXd sqrt_weight = weights.array().sqrt();\n    int n = x.rows();\n    for (int i = 0; i < n; i++) {\n        x.row(i) = x.row(i) * sqrt_weight(i);\n    }\n    array_product(y, sqrt_weight, 1);\n};\n\nvoid add_weight(Eigen::MatrixXd &x, Eigen::MatrixXd &y, Eigen::VectorXd weights) {\n    Eigen::VectorXd sqrt_weight = weights.array().sqrt();\n    int n = x.rows();\n    for (int i = 0; i < n; i++) {\n        x.row(i) = x.row(i) * sqrt_weight(i);\n    }\n    array_product(y, sqrt_weight, 1);\n};\n\nvoid add_weight(Eigen::SparseMatrix<double> &x, Eigen::VectorXd &y, Eigen::VectorXd weights) {\n    for (int k = 0; k < x.outerSize(); ++k) {\n        for (SparseMatrix<double>::InnerIterator it(x, k); it; ++it) {\n            x.coeffRef(int(it.row()), int(it.col())) = x.coeffRef(int(it.row()), int(it.col())) * weights(it.row());\n        }\n    }\n    Eigen::VectorXd sqrt_weight = weights.array().sqrt();\n    array_product(y, sqrt_weight, 1);\n};\n\nvoid add_weight(Eigen::SparseMatrix<double> &x, Eigen::MatrixXd &y, Eigen::VectorXd weights) {\n    for (int k = 0; k < x.outerSize(); ++k) {\n        for (SparseMatrix<double>::InnerIterator it(x, k); it; ++it) {\n            x.coeffRef(int(it.row()), int(it.col())) = x.coeffRef(int(it.row()), int(it.col())) * weights(it.row());\n        }\n    }\n    Eigen::VectorXd sqrt_weight = weights.array().sqrt();\n    array_product(y, sqrt_weight, 1);\n};\n", "meta": {"hexsha": "bf5754a9d05995c749c9872fd51976a89a836427", "size": 18224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utilities.cpp", "max_stars_repo_name": "Jiang-Kangkang/abess-test_python_whl_install", "max_stars_repo_head_hexsha": "48d535bf724d3a79c930741632c2fc5cafc99a06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 272.0, "max_stars_repo_stars_event_min_datetime": "2021-05-05T03:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:37:36.000Z", "max_issues_repo_path": "src/utilities.cpp", "max_issues_repo_name": "Jiang-Kangkang/abess-test_python_whl_install", "max_issues_repo_head_hexsha": "48d535bf724d3a79c930741632c2fc5cafc99a06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2021-05-16T02:16:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:46:26.000Z", "max_forks_repo_path": "src/utilities.cpp", "max_forks_repo_name": "Jiang-Kangkang/abess-test_python_whl_install", "max_forks_repo_head_hexsha": "48d535bf724d3a79c930741632c2fc5cafc99a06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-04-03T10:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T13:04:15.000Z", "avg_line_length": 29.0191082803, "max_line_length": 116, "alphanum_fraction": 0.509547849, "num_tokens": 5410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824860330003, "lm_q2_score": 0.06187597966883276, "lm_q1q2_score": 0.021135750961007276}}
{"text": "// 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// Operations that can deal with very large values (256-bit).\n//\n// The intermediate results with decimal can be larger than what can fit into 128-bit,\n// but the final results can fit in 128-bit after scaling down. These functions deal\n// with operations on the intermediate values.\n//\n\n#include \"gandiva/decimal_xlarge.h\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <limits>\n#include <vector>\n\n#include \"arrow/util/basic_decimal.h\"\n#include \"arrow/util/logging.h\"\n#include \"gandiva/decimal_type_util.h\"\n\n#ifndef GANDIVA_UNIT_TEST\n#include \"gandiva/engine.h\"\n#include \"gandiva/exported_funcs.h\"\n\nnamespace gandiva {\n\nvoid ExportedDecimalFunctions::AddMappings(Engine* engine) const {\n  std::vector<llvm::Type*> args;\n  auto types = engine->types();\n\n  // gdv_multiply_and_scale_down\n  args = {types->i64_type(),      // int64_t x_high\n          types->i64_type(),      // uint64_t x_low\n          types->i64_type(),      // int64_t y_high\n          types->i64_type(),      // uint64_t x_low\n          types->i32_type(),      // int32_t reduce_scale_by\n          types->i64_ptr_type(),  // int64_t* out_high\n          types->i64_ptr_type(),  // uint64_t* out_low\n          types->i8_ptr_type()};  // bool* overflow\n\n  engine->AddGlobalMappingForFunc(\n      \"gdv_xlarge_multiply_and_scale_down\", types->void_type() /*return_type*/, args,\n      reinterpret_cast<void*>(gdv_xlarge_multiply_and_scale_down));\n\n  // gdv_xlarge_scale_up_and_divide\n  args = {types->i64_type(),      // int64_t x_high\n          types->i64_type(),      // uint64_t x_low\n          types->i64_type(),      // int64_t y_high\n          types->i64_type(),      // uint64_t y_low\n          types->i32_type(),      // int32_t increase_scale_by\n          types->i64_ptr_type(),  // int64_t* out_high\n          types->i64_ptr_type(),  // uint64_t* out_low\n          types->i8_ptr_type()};  // bool* overflow\n\n  engine->AddGlobalMappingForFunc(\n      \"gdv_xlarge_scale_up_and_divide\", types->void_type() /*return_type*/, args,\n      reinterpret_cast<void*>(gdv_xlarge_scale_up_and_divide));\n\n  // gdv_xlarge_mod\n  args = {types->i64_type(),       // int64_t x_high\n          types->i64_type(),       // uint64_t x_low\n          types->i32_type(),       // int32_t x_scale\n          types->i64_type(),       // int64_t y_high\n          types->i64_type(),       // uint64_t y_low\n          types->i32_type(),       // int32_t y_scale\n          types->i64_ptr_type(),   // int64_t* out_high\n          types->i64_ptr_type()};  // uint64_t* out_low\n\n  engine->AddGlobalMappingForFunc(\"gdv_xlarge_mod\", types->void_type() /*return_type*/,\n                                  args, reinterpret_cast<void*>(gdv_xlarge_mod));\n\n  // gdv_xlarge_compare\n  args = {types->i64_type(),   // int64_t x_high\n          types->i64_type(),   // uint64_t x_low\n          types->i32_type(),   // int32_t x_scale\n          types->i64_type(),   // int64_t y_high\n          types->i64_type(),   // uint64_t y_low\n          types->i32_type()};  // int32_t y_scale\n\n  engine->AddGlobalMappingForFunc(\"gdv_xlarge_compare\", types->i32_type() /*return_type*/,\n                                  args, reinterpret_cast<void*>(gdv_xlarge_compare));\n}\n\n}  // namespace gandiva\n\n#endif  // !GANDIVA_UNIT_TEST\n\nusing arrow::BasicDecimal128;\nusing boost::multiprecision::int256_t;\n\nnamespace gandiva {\nnamespace internal {\n\n// Convert to 256-bit integer from 128-bit decimal.\nstatic int256_t ConvertToInt256(BasicDecimal128 in) {\n  int256_t v = in.high_bits();\n  v <<= 64;\n  v |= in.low_bits();\n  return v;\n}\n\n// Convert to 128-bit decimal from 256-bit integer.\n// If there is an overflow, the output is undefined.\nstatic BasicDecimal128 ConvertToDecimal128(int256_t in, bool* overflow) {\n  BasicDecimal128 result;\n  constexpr int256_t UINT64_MASK = std::numeric_limits<uint64_t>::max();\n\n  int256_t in_abs = abs(in);\n  bool is_negative = in < 0;\n\n  uint64_t low = (in_abs & UINT64_MASK).convert_to<uint64_t>();\n  in_abs >>= 64;\n  uint64_t high = (in_abs & UINT64_MASK).convert_to<uint64_t>();\n  in_abs >>= 64;\n\n  if (in_abs > 0) {\n    // we've shifted in by 128-bit, so nothing should be left.\n    *overflow = true;\n  } else if (high > INT64_MAX) {\n    // the high-bit must not be set (signed 128-bit).\n    *overflow = true;\n  } else {\n    result = BasicDecimal128(static_cast<int64_t>(high), low);\n    if (result > BasicDecimal128::GetMaxValue()) {\n      *overflow = true;\n    }\n  }\n  return is_negative ? -result : result;\n}\n\nstatic constexpr int32_t kMaxLargeScale = 2 * DecimalTypeUtil::kMaxPrecision;\n\n// Compute the scale multipliers once.\nstatic std::array<int256_t, kMaxLargeScale + 1> kLargeScaleMultipliers =\n    ([]() -> std::array<int256_t, kMaxLargeScale + 1> {\n      std::array<int256_t, kMaxLargeScale + 1> values;\n      values[0] = 1;\n      for (int32_t idx = 1; idx <= kMaxLargeScale; idx++) {\n        values[idx] = values[idx - 1] * 10;\n      }\n      return values;\n    })();\n\nstatic int256_t GetScaleMultiplier(int scale) {\n  DCHECK_GE(scale, 0);\n  DCHECK_LE(scale, kMaxLargeScale);\n\n  return kLargeScaleMultipliers[scale];\n}\n\n// divide input by 10^reduce_by, and round up the fractional part.\nstatic int256_t ReduceScaleBy(int256_t in, int32_t reduce_by) {\n  if (reduce_by == 0) {\n    // nothing to do.\n    return in;\n  }\n\n  int256_t divisor = GetScaleMultiplier(reduce_by);\n  DCHECK_GT(divisor, 0);\n  DCHECK_EQ(divisor % 2, 0);  // multiple of 10.\n  auto result = in / divisor;\n  auto remainder = in % divisor;\n  // round up (same as BasicDecimal128::ReduceScaleBy)\n  if (abs(remainder) >= (divisor >> 1)) {\n    result += (in > 0 ? 1 : -1);\n  }\n  return result;\n}\n\n// multiply input by 10^increase_by.\nstatic int256_t IncreaseScaleBy(int256_t in, int32_t increase_by) {\n  DCHECK_GE(increase_by, 0);\n  DCHECK_LE(increase_by, 2 * DecimalTypeUtil::kMaxPrecision);\n\n  return in * GetScaleMultiplier(increase_by);\n}\n\n}  // namespace internal\n}  // namespace gandiva\n\nextern \"C\" {\n\nvoid gdv_xlarge_multiply_and_scale_down(int64_t x_high, uint64_t x_low, int64_t y_high,\n                                        uint64_t y_low, int32_t reduce_scale_by,\n                                        int64_t* out_high, uint64_t* out_low,\n                                        bool* overflow) {\n  BasicDecimal128 x{x_high, x_low};\n  BasicDecimal128 y{y_high, y_low};\n  auto intermediate_result =\n      gandiva::internal::ConvertToInt256(x) * gandiva::internal::ConvertToInt256(y);\n  intermediate_result =\n      gandiva::internal::ReduceScaleBy(intermediate_result, reduce_scale_by);\n  auto result = gandiva::internal::ConvertToDecimal128(intermediate_result, overflow);\n  *out_high = result.high_bits();\n  *out_low = result.low_bits();\n}\n\nvoid gdv_xlarge_scale_up_and_divide(int64_t x_high, uint64_t x_low, int64_t y_high,\n                                    uint64_t y_low, int32_t increase_scale_by,\n                                    int64_t* out_high, uint64_t* out_low,\n                                    bool* overflow) {\n  BasicDecimal128 x{x_high, x_low};\n  BasicDecimal128 y{y_high, y_low};\n\n  int256_t x_large = gandiva::internal::ConvertToInt256(x);\n  int256_t x_large_scaled_up =\n      gandiva::internal::IncreaseScaleBy(x_large, increase_scale_by);\n  int256_t y_large = gandiva::internal::ConvertToInt256(y);\n  int256_t result_large = x_large_scaled_up / y_large;\n  int256_t remainder_large = x_large_scaled_up % y_large;\n\n  // Since we are scaling up and then, scaling down, round-up the result (+1 for +ve,\n  // -1 for -ve), if the remainder is >= 2 * divisor.\n  if (abs(2 * remainder_large) >= abs(y_large)) {\n    // x +ve and y +ve, result is +ve =>   (1 ^ 1)  + 1 =  0 + 1 = +1\n    // x +ve and y -ve, result is -ve =>  (-1 ^ 1)  + 1 = -2 + 1 = -1\n    // x +ve and y -ve, result is -ve =>   (1 ^ -1) + 1 = -2 + 1 = -1\n    // x -ve and y -ve, result is +ve =>  (-1 ^ -1) + 1 =  0 + 1 = +1\n    result_large += (x.Sign() ^ y.Sign()) + 1;\n  }\n  auto result = gandiva::internal::ConvertToDecimal128(result_large, overflow);\n  *out_high = result.high_bits();\n  *out_low = result.low_bits();\n}\n\nvoid gdv_xlarge_mod(int64_t x_high, uint64_t x_low, int32_t x_scale, int64_t y_high,\n                    uint64_t y_low, int32_t y_scale, int64_t* out_high,\n                    uint64_t* out_low) {\n  BasicDecimal128 x{x_high, x_low};\n  BasicDecimal128 y{y_high, y_low};\n\n  int256_t x_large = gandiva::internal::ConvertToInt256(x);\n  int256_t y_large = gandiva::internal::ConvertToInt256(y);\n  if (x_scale < y_scale) {\n    x_large = gandiva::internal::IncreaseScaleBy(x_large, y_scale - x_scale);\n  } else {\n    y_large = gandiva::internal::IncreaseScaleBy(y_large, x_scale - y_scale);\n  }\n  auto intermediate_result = x_large % y_large;\n  bool overflow = false;\n  auto result = gandiva::internal::ConvertToDecimal128(intermediate_result, &overflow);\n  DCHECK_EQ(overflow, false);\n\n  *out_high = result.high_bits();\n  *out_low = result.low_bits();\n}\n\nint32_t gdv_xlarge_compare(int64_t x_high, uint64_t x_low, int32_t x_scale,\n                           int64_t y_high, uint64_t y_low, int32_t y_scale) {\n  BasicDecimal128 x{x_high, x_low};\n  BasicDecimal128 y{y_high, y_low};\n\n  int256_t x_large = gandiva::internal::ConvertToInt256(x);\n  int256_t y_large = gandiva::internal::ConvertToInt256(y);\n  if (x_scale < y_scale) {\n    x_large = gandiva::internal::IncreaseScaleBy(x_large, y_scale - x_scale);\n  } else {\n    y_large = gandiva::internal::IncreaseScaleBy(y_large, x_scale - y_scale);\n  }\n\n  if (x_large == y_large) {\n    return 0;\n  } else if (x_large < y_large) {\n    return -1;\n  } else {\n    return 1;\n  }\n}\n\n}  // extern \"C\"\n", "meta": {"hexsha": "caebd8b09e63a261fb514afc4bd6bb9983c19c90", "size": 10391, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/gandiva/decimal_xlarge.cc", "max_stars_repo_name": "timkpaine/arrow", "max_stars_repo_head_hexsha": "a96297e65e17e728e4321cdecc7ace146e1363fb", "max_stars_repo_licenses": ["CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT"], "max_stars_count": 9734.0, "max_stars_repo_stars_event_min_datetime": "2016-02-17T13:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:35:00.000Z", "max_issues_repo_path": "cpp/src/gandiva/decimal_xlarge.cc", "max_issues_repo_name": "timkpaine/arrow", "max_issues_repo_head_hexsha": "a96297e65e17e728e4321cdecc7ace146e1363fb", "max_issues_repo_licenses": ["CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT"], "max_issues_count": 11470.0, "max_issues_repo_issues_event_min_datetime": "2016-02-19T15:30:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:27:21.000Z", "max_forks_repo_path": "cpp/src/gandiva/decimal_xlarge.cc", "max_forks_repo_name": "XpressAI/arrow", "max_forks_repo_head_hexsha": "eafd885e06f6bbc1eb169ed64016f804c1810bec", "max_forks_repo_licenses": ["CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT"], "max_forks_count": 2637.0, "max_forks_repo_forks_event_min_datetime": "2016-02-17T10:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:20:13.000Z", "avg_line_length": 36.4596491228, "max_line_length": 90, "alphanum_fraction": 0.6610528342, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.04468086804648062, "lm_q1q2_score": 0.021119908046629266}}
{"text": "//=======================================================================\n// Copyright 2000 University of Notre Dame.\n// Authors: Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef BOOST_PUSH_RELABEL_MAX_FLOW_HPP\n#define BOOST_PUSH_RELABEL_MAX_FLOW_HPP\n\n#include <boost/config.hpp>\n#include <boost/assert.hpp>\n#include <vector>\n#include <list>\n#include <iosfwd>\n#include <algorithm> // for std::min and std::max\n\n#include <boost/pending/queue.hpp>\n#include <boost/limits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/named_function_params.hpp>\n\nnamespace boost {\n\n  namespace detail {\n    \n   // This implementation is based on Goldberg's \n   // \"On Implementing Push-Relabel Method for the Maximum Flow Problem\"\n   // by B.V. Cherkassky and A.V. Goldberg, IPCO '95, pp. 157--171\n   // and on the h_prf.c and hi_pr.c code written by the above authors.\n\n   // This implements the highest-label version of the push-relabel method\n   // with the global relabeling and gap relabeling heuristics.\n\n   // The terms \"rank\", \"distance\", \"height\" are synonyms in\n   // Goldberg's implementation, paper and in the CLR.  A \"layer\" is a\n   // group of vertices with the same distance. The vertices in each\n   // layer are categorized as active or inactive.  An active vertex\n   // has positive excess flow and its distance is less than n (it is\n   // not blocked).\n\n    template <class Vertex>\n    struct preflow_layer {\n      std::list<Vertex> active_vertices;\n      std::list<Vertex> inactive_vertices;\n    };\n\n    template <class Graph, \n              class EdgeCapacityMap,    // integer value type\n              class ResidualCapacityEdgeMap,\n              class ReverseEdgeMap,\n              class VertexIndexMap,     // vertex_descriptor -> integer\n              class FlowValue>\n    class push_relabel\n    {\n    public:\n      typedef graph_traits<Graph> Traits;\n      typedef typename Traits::vertex_descriptor vertex_descriptor;\n      typedef typename Traits::edge_descriptor edge_descriptor;\n      typedef typename Traits::vertex_iterator vertex_iterator;\n      typedef typename Traits::out_edge_iterator out_edge_iterator;\n      typedef typename Traits::vertices_size_type vertices_size_type;\n      typedef typename Traits::edges_size_type edges_size_type;\n\n      typedef preflow_layer<vertex_descriptor> Layer;\n      typedef std::vector< Layer > LayerArray;\n      typedef typename LayerArray::iterator layer_iterator;\n      typedef typename LayerArray::size_type distance_size_type;\n\n      typedef color_traits<default_color_type> ColorTraits;\n\n      //=======================================================================\n      // Some helper predicates\n\n      inline bool is_admissible(vertex_descriptor u, vertex_descriptor v) {\n        return get(distance, u) == get(distance, v) + 1;\n      }\n      inline bool is_residual_edge(edge_descriptor a) {\n        return 0 < get(residual_capacity, a);\n      }\n      inline bool is_saturated(edge_descriptor a) {\n        return get(residual_capacity, a) == 0;\n      }\n\n      //=======================================================================\n      // Layer List Management Functions\n\n      typedef typename std::list<vertex_descriptor>::iterator list_iterator;\n\n      void add_to_active_list(vertex_descriptor u, Layer& layer) {\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        layer.active_vertices.push_front(u);\n        max_active = max BOOST_PREVENT_MACRO_SUBSTITUTION(get(distance, u), max_active);\n        min_active = min BOOST_PREVENT_MACRO_SUBSTITUTION(get(distance, u), min_active);\n        layer_list_ptr[u] = layer.active_vertices.begin();\n      }\n      void remove_from_active_list(vertex_descriptor u) {\n        layers[get(distance, u)].active_vertices.erase(layer_list_ptr[u]);    \n      }\n\n      void add_to_inactive_list(vertex_descriptor u, Layer& layer) {\n        layer.inactive_vertices.push_front(u);\n        layer_list_ptr[u] = layer.inactive_vertices.begin();\n      }\n      void remove_from_inactive_list(vertex_descriptor u) {\n        layers[get(distance, u)].inactive_vertices.erase(layer_list_ptr[u]);    \n      }\n\n      //=======================================================================\n      // initialization\n      push_relabel(Graph& g_, \n                   EdgeCapacityMap cap,\n                   ResidualCapacityEdgeMap res,\n                   ReverseEdgeMap rev,\n                   vertex_descriptor src_, \n                   vertex_descriptor sink_,\n                   VertexIndexMap idx)\n        : g(g_), n(num_vertices(g_)), capacity(cap), src(src_), sink(sink_), \n          index(idx),\n          excess_flow_data(num_vertices(g_)),\n          excess_flow(excess_flow_data.begin(), idx),\n          current_data(num_vertices(g_), out_edges(*vertices(g_).first, g_)),\n          current(current_data.begin(), idx),\n          distance_data(num_vertices(g_)),\n          distance(distance_data.begin(), idx),\n          color_data(num_vertices(g_)),\n          color(color_data.begin(), idx),\n          reverse_edge(rev),\n          residual_capacity(res),\n          layers(num_vertices(g_)),\n          layer_list_ptr_data(num_vertices(g_), \n                              layers.front().inactive_vertices.end()),\n          layer_list_ptr(layer_list_ptr_data.begin(), idx),\n          push_count(0), update_count(0), relabel_count(0), \n          gap_count(0), gap_node_count(0),\n          work_since_last_update(0)\n      {\n        vertex_iterator u_iter, u_end;\n        // Don't count the reverse edges\n        edges_size_type m = num_edges(g) / 2;\n        nm = alpha() * n + m;\n\n        // Initialize flow to zero which means initializing\n        // the residual capacity to equal the capacity.\n        out_edge_iterator ei, e_end;\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n          for (boost::tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei) {\n            put(residual_capacity, *ei, get(capacity, *ei));\n          }\n\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n          vertex_descriptor u = *u_iter;\n          put(excess_flow, u, 0);\n          current[u] = out_edges(u, g);\n        }\n\n        bool overflow_detected = false;\n        FlowValue test_excess = 0;\n\n        out_edge_iterator a_iter, a_end;\n        for (boost::tie(a_iter, a_end) = out_edges(src, g); a_iter != a_end; ++a_iter)\n          if (target(*a_iter, g) != src)\n            test_excess += get(residual_capacity, *a_iter);\n        if (test_excess > (std::numeric_limits<FlowValue>::max)())\n          overflow_detected = true;\n\n        if (overflow_detected)\n          put(excess_flow, src, (std::numeric_limits<FlowValue>::max)());\n        else {\n          put(excess_flow, src, 0);\n          for (boost::tie(a_iter, a_end) = out_edges(src, g); \n               a_iter != a_end; ++a_iter) {\n            edge_descriptor a = *a_iter;\n            vertex_descriptor tgt = target(a, g);\n            if (tgt != src) {\n              ++push_count;\n              FlowValue delta = get(residual_capacity, a);\n              put(residual_capacity, a, get(residual_capacity, a) - delta);\n              edge_descriptor rev = get(reverse_edge, a);\n              put(residual_capacity, rev, get(residual_capacity, rev) + delta);\n              put(excess_flow, tgt, get(excess_flow, tgt) + delta);\n            }\n          }\n        }\n        max_distance = num_vertices(g) - 1;\n        max_active = 0;\n        min_active = n;\n\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n          vertex_descriptor u = *u_iter;\n          if (u == sink) {\n            put(distance, u, 0);\n            continue;\n          } else if (u == src && !overflow_detected)\n            put(distance, u, n);\n          else\n            put(distance, u, 1);\n\n          if (get(excess_flow, u) > 0)\n            add_to_active_list(u, layers[1]);\n          else if (get(distance, u) < n)\n            add_to_inactive_list(u, layers[1]);\n        }       \n\n      } // push_relabel constructor\n\n      //=======================================================================\n      // This is a breadth-first search over the residual graph\n      // (well, actually the reverse of the residual graph).\n      // Would be cool to have a graph view adaptor for hiding certain\n      // edges, like the saturated (non-residual) edges in this case.\n      // Goldberg's implementation abused \"distance\" for the coloring.\n      void global_distance_update()\n      {\n        BOOST_USING_STD_MAX();\n        ++update_count;\n        vertex_iterator u_iter, u_end;\n        for (boost::tie(u_iter,u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n          put(color, *u_iter, ColorTraits::white());\n          put(distance, *u_iter, n);\n        }\n        put(color, sink, ColorTraits::gray());\n        put(distance, sink, 0);\n        \n        for (distance_size_type l = 0; l <= max_distance; ++l) {\n          layers[l].active_vertices.clear();\n          layers[l].inactive_vertices.clear();\n        }\n        \n        max_distance = max_active = 0;\n        min_active = n;\n\n        Q.push(sink);\n        while (! Q.empty()) {\n          vertex_descriptor u = Q.top();\n          Q.pop();\n          distance_size_type d_v = get(distance, u) + 1;\n\n          out_edge_iterator ai, a_end;\n          for (boost::tie(ai, a_end) = out_edges(u, g); ai != a_end; ++ai) {\n            edge_descriptor a = *ai;\n            vertex_descriptor v = target(a, g);\n            if (get(color, v) == ColorTraits::white()\n                && is_residual_edge(get(reverse_edge, a))) {\n              put(distance, v, d_v);\n              put(color, v, ColorTraits::gray());\n              current[v] = out_edges(v, g);\n              max_distance = max BOOST_PREVENT_MACRO_SUBSTITUTION(d_v, max_distance);\n\n              if (get(excess_flow, v) > 0)\n                add_to_active_list(v, layers[d_v]);\n              else\n                add_to_inactive_list(v, layers[d_v]);\n\n              Q.push(v);\n            }\n          }\n        }\n      } // global_distance_update()\n\n      //=======================================================================\n      // This function is called \"push\" in Goldberg's h_prf implementation,\n      // but it is called \"discharge\" in the paper and in hi_pr.c.\n      void discharge(vertex_descriptor u)\n      {\n        BOOST_ASSERT(get(excess_flow, u) > 0);\n        while (1) {\n          out_edge_iterator ai, ai_end;\n          for (boost::tie(ai, ai_end) = current[u]; ai != ai_end; ++ai) {\n            edge_descriptor a = *ai;\n            if (is_residual_edge(a)) {\n              vertex_descriptor v = target(a, g);\n              if (is_admissible(u, v)) {\n                ++push_count;\n                if (v != sink && get(excess_flow, v) == 0) {\n                  remove_from_inactive_list(v);\n                  add_to_active_list(v, layers[get(distance, v)]);\n                }\n                push_flow(a);\n                if (get(excess_flow, u) == 0)\n                  break;\n              } \n            } \n          } // for out_edges of i starting from current\n\n          Layer& layer = layers[get(distance, u)];\n          distance_size_type du = get(distance, u);\n\n          if (ai == ai_end) {   // i must be relabeled\n            relabel_distance(u);\n            if (layer.active_vertices.empty()\n                && layer.inactive_vertices.empty())\n              gap(du);\n            if (get(distance, u) == n)\n              break;\n          } else {              // i is no longer active\n            current[u].first = ai;\n            add_to_inactive_list(u, layer);\n            break;\n          }\n        } // while (1)\n      } // discharge()\n\n      //=======================================================================\n      // This corresponds to the \"push\" update operation of the paper,\n      // not the \"push\" function in Goldberg's h_prf.c implementation.\n      // The idea is to push the excess flow from from vertex u to v.\n      void push_flow(edge_descriptor u_v)\n      {\n        vertex_descriptor\n          u = source(u_v, g),\n          v = target(u_v, g);\n        \n        BOOST_USING_STD_MIN();\n        FlowValue flow_delta\n          = min BOOST_PREVENT_MACRO_SUBSTITUTION(get(excess_flow, u), get(residual_capacity, u_v));\n\n        put(residual_capacity, u_v, get(residual_capacity, u_v) - flow_delta);\n        edge_descriptor rev = get(reverse_edge, u_v);\n        put(residual_capacity, rev, get(residual_capacity, rev) + flow_delta);\n\n        put(excess_flow, u, get(excess_flow, u) - flow_delta);\n        put(excess_flow, v, get(excess_flow, v) + flow_delta);\n      } // push_flow()\n\n      //=======================================================================\n      // The main purpose of this routine is to set distance[v]\n      // to the smallest value allowed by the valid labeling constraints,\n      // which are:\n      // distance[t] = 0\n      // distance[u] <= distance[v] + 1   for every residual edge (u,v)\n      //\n      distance_size_type relabel_distance(vertex_descriptor u)\n      {\n        BOOST_USING_STD_MAX();\n        ++relabel_count;\n        work_since_last_update += beta();\n\n        distance_size_type min_distance = num_vertices(g);\n        put(distance, u, min_distance);\n\n        // Examine the residual out-edges of vertex i, choosing the\n        // edge whose target vertex has the minimal distance.\n        out_edge_iterator ai, a_end, min_edge_iter;\n        for (boost::tie(ai, a_end) = out_edges(u, g); ai != a_end; ++ai) {\n          ++work_since_last_update;\n          edge_descriptor a = *ai;\n          vertex_descriptor v = target(a, g);\n          if (is_residual_edge(a) && get(distance, v) < min_distance) {\n            min_distance = get(distance, v);\n            min_edge_iter = ai;\n          }\n        }\n        ++min_distance;\n        if (min_distance < n) {\n          put(distance, u, min_distance);     // this is the main action\n          current[u].first = min_edge_iter;\n          max_distance = max BOOST_PREVENT_MACRO_SUBSTITUTION(min_distance, max_distance);\n        }\n        return min_distance;\n      } // relabel_distance()\n\n      //=======================================================================\n      // cleanup beyond the gap\n      void gap(distance_size_type empty_distance)\n      {\n        ++gap_count;\n\n        distance_size_type r; // distance of layer before the current layer\n        r = empty_distance - 1;\n\n        // Set the distance for the vertices beyond the gap to \"infinity\".\n        for (layer_iterator l = layers.begin() + empty_distance + 1;\n             l < layers.begin() + max_distance; ++l) {\n          list_iterator i;\n          for (i = l->inactive_vertices.begin(); \n               i != l->inactive_vertices.end(); ++i) {\n            put(distance, *i, n);\n            ++gap_node_count;\n          }\n          l->inactive_vertices.clear();\n        }\n        max_distance = r;\n        max_active = r;\n      }\n\n      //=======================================================================\n      // This is the core part of the algorithm, \"phase one\".\n      FlowValue maximum_preflow()\n      {\n        work_since_last_update = 0;\n\n        while (max_active >= min_active) { // \"main\" loop\n\n          Layer& layer = layers[max_active];\n          list_iterator u_iter = layer.active_vertices.begin();\n\n          if (u_iter == layer.active_vertices.end())\n            --max_active;\n          else {\n            vertex_descriptor u = *u_iter;\n            remove_from_active_list(u);\n            \n            discharge(u);\n\n            if (work_since_last_update * global_update_frequency() > nm) {\n              global_distance_update();\n              work_since_last_update = 0;\n            }\n          }\n        } // while (max_active >= min_active)\n\n        return get(excess_flow, sink);\n      } // maximum_preflow()\n\n      //=======================================================================\n      // remove excess flow, the \"second phase\"\n      // This does a DFS on the reverse flow graph of nodes with excess flow.\n      // If a cycle is found, cancel it.\n      // Return the nodes with excess flow in topological order.\n      //\n      // Unlike the prefl_to_flow() implementation, we use\n      //   \"color\" instead of \"distance\" for the DFS labels\n      //   \"parent\" instead of nl_prev for the DFS tree\n      //   \"topo_next\" instead of nl_next for the topological ordering\n      void convert_preflow_to_flow()\n      {\n        vertex_iterator u_iter, u_end;\n        out_edge_iterator ai, a_end;\n\n        vertex_descriptor r, restart, u;\n\n        std::vector<vertex_descriptor> parent(n);\n        std::vector<vertex_descriptor> topo_next(n);\n\n        vertex_descriptor tos(parent[0]), \n          bos(parent[0]); // bogus initialization, just to avoid warning\n        bool bos_null = true;\n\n        // handle self-loops\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n          for (boost::tie(ai, a_end) = out_edges(*u_iter, g); ai != a_end; ++ai)\n            if (target(*ai, g) == *u_iter)\n              put(residual_capacity, *ai, get(capacity, *ai));\n\n        // initialize\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n          u = *u_iter;\n          put(color, u, ColorTraits::white());\n          parent[get(index, u)] = u;\n          current[u] = out_edges(u, g);\n        }\n        // eliminate flow cycles and topologically order the vertices\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n          u = *u_iter;\n          if (get(color, u) == ColorTraits::white() \n              && get(excess_flow, u) > 0\n              && u != src && u != sink ) {\n            r = u;\n            put(color, r, ColorTraits::gray());\n            while (1) {\n              for (; current[u].first != current[u].second; ++current[u].first) {\n                edge_descriptor a = *current[u].first;\n                if (get(capacity, a) == 0 && is_residual_edge(a)) {\n                  vertex_descriptor v = target(a, g);\n                  if (get(color, v) == ColorTraits::white()) {\n                    put(color, v, ColorTraits::gray());\n                    parent[get(index, v)] = u;\n                    u = v;\n                    break;\n                  } else if (get(color, v) == ColorTraits::gray()) {\n                    // find minimum flow on the cycle\n                    FlowValue delta = get(residual_capacity, a);\n                    while (1) {\n                      BOOST_USING_STD_MIN();\n                      delta = min BOOST_PREVENT_MACRO_SUBSTITUTION(delta, get(residual_capacity, *current[v].first));\n                      if (v == u)\n                        break;\n                      else\n                        v = target(*current[v].first, g);\n                    }\n                    // remove delta flow units\n                    v = u;\n                    while (1) {\n                      a = *current[v].first;\n                      put(residual_capacity, a, get(residual_capacity, a) - delta);\n                      edge_descriptor rev = get(reverse_edge, a);\n                      put(residual_capacity, rev, get(residual_capacity, rev) + delta);\n                      v = target(a, g);\n                      if (v == u)\n                        break;\n                    }\n\n                    // back-out of DFS to the first saturated edge\n                    restart = u;\n                    for (v = target(*current[u].first, g); v != u; v = target(a, g)){\n                      a = *current[v].first;\n                      if (get(color, v) == ColorTraits::white() \n                          || is_saturated(a)) {\n                        put(color, target(*current[v].first, g), ColorTraits::white());\n                        if (get(color, v) != ColorTraits::white())\n                          restart = v;\n                      }\n                    }\n                    if (restart != u) {\n                      u = restart;\n                      ++current[u].first;\n                      break;\n                    }\n                  } // else if (color[v] == ColorTraits::gray())\n                } // if (get(capacity, a) == 0 ...\n              } // for out_edges(u, g)  (though \"u\" changes during loop)\n              \n              if ( current[u].first == current[u].second ) {\n                // scan of i is complete\n                put(color, u, ColorTraits::black());\n                if (u != src) {\n                  if (bos_null) {\n                    bos = u;\n                    bos_null = false;\n                    tos = u;\n                  } else {\n                    topo_next[get(index, u)] = tos;\n                    tos = u;\n                  }\n                }\n                if (u != r) {\n                  u = parent[get(index, u)];\n                  ++current[u].first;\n                } else\n                  break;\n              }\n            } // while (1)\n          } // if (color[u] == white && excess_flow[u] > 0 & ...)\n        } // for all vertices in g\n\n        // return excess flows\n        // note that the sink is not on the stack\n        if (! bos_null) {\n          for (u = tos; u != bos; u = topo_next[get(index, u)]) {\n            boost::tie(ai, a_end) = out_edges(u, g);\n            while (get(excess_flow, u) > 0 && ai != a_end) {\n              if (get(capacity, *ai) == 0 && is_residual_edge(*ai))\n                push_flow(*ai);\n              ++ai;\n            }\n          }\n          // do the bottom\n          u = bos;\n          boost::tie(ai, a_end) = out_edges(u, g);\n          while (get(excess_flow, u) > 0 && ai != a_end) {\n            if (get(capacity, *ai) == 0 && is_residual_edge(*ai))\n              push_flow(*ai);\n            ++ai;\n          }\n        }\n        \n      } // convert_preflow_to_flow()\n\n      //=======================================================================\n      inline bool is_flow()\n      {\n        vertex_iterator u_iter, u_end;\n        out_edge_iterator ai, a_end;\n\n        // check edge flow values\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n          for (boost::tie(ai, a_end) = out_edges(*u_iter, g); ai != a_end; ++ai) {\n            edge_descriptor a = *ai;\n            if (get(capacity, a) > 0)\n              if ((get(residual_capacity, a) + get(residual_capacity, get(reverse_edge, a))\n                   != get(capacity, a) + get(capacity, get(reverse_edge, a)))\n                  || (get(residual_capacity, a) < 0)\n                  || (get(residual_capacity, get(reverse_edge, a)) < 0))\n              return false;\n          }\n        }\n        \n        // check conservation\n        FlowValue sum;  \n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter) {\n          vertex_descriptor u = *u_iter;\n          if (u != src && u != sink) {\n            if (get(excess_flow, u) != 0)\n              return false;\n            sum = 0;\n            for (boost::tie(ai, a_end) = out_edges(u, g); ai != a_end; ++ai) \n              if (get(capacity, *ai) > 0)\n                sum -= get(capacity, *ai) - get(residual_capacity, *ai);\n              else\n                sum += get(residual_capacity, *ai);\n\n            if (get(excess_flow, u) != sum)\n              return false;\n          }\n        }\n\n        return true;\n      } // is_flow()\n\n      bool is_optimal() {\n        // check if mincut is saturated...\n        global_distance_update();\n        return get(distance, src) >= n;\n      }\n\n      void print_statistics(std::ostream& os) const {\n        os << \"pushes:     \" << push_count << std::endl\n           << \"relabels:   \" << relabel_count << std::endl\n           << \"updates:    \" << update_count << std::endl\n           << \"gaps:       \" << gap_count << std::endl\n           << \"gap nodes:  \" << gap_node_count << std::endl\n           << std::endl;\n      }\n\n      void print_flow_values(std::ostream& os) const {\n        os << \"flow values\" << std::endl;\n        vertex_iterator u_iter, u_end;\n        out_edge_iterator ei, e_end;\n        for (boost::tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n          for (boost::tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n            if (get(capacity, *ei) > 0)\n              os << *u_iter << \" \" << target(*ei, g) << \" \" \n                 << (get(capacity, *ei) - get(residual_capacity, *ei)) << std::endl;\n        os << std::endl;\n      }\n\n      //=======================================================================\n\n      Graph& g;\n      vertices_size_type n;\n      vertices_size_type nm;\n      EdgeCapacityMap capacity;\n      vertex_descriptor src;\n      vertex_descriptor sink;\n      VertexIndexMap index;\n\n      // will need to use random_access_property_map with these\n      std::vector< FlowValue > excess_flow_data;\n      iterator_property_map<typename std::vector<FlowValue>::iterator, VertexIndexMap> excess_flow;\n      std::vector< std::pair<out_edge_iterator, out_edge_iterator> > current_data;\n      iterator_property_map<\n        typename std::vector< std::pair<out_edge_iterator, out_edge_iterator> >::iterator,\n        VertexIndexMap> current;\n      std::vector< distance_size_type > distance_data;\n      iterator_property_map<\n        typename std::vector< distance_size_type >::iterator,\n        VertexIndexMap> distance;\n      std::vector< default_color_type > color_data;\n      iterator_property_map<\n        std::vector< default_color_type >::iterator,\n        VertexIndexMap> color;\n\n      // Edge Property Maps that must be interior to the graph\n      ReverseEdgeMap reverse_edge;\n      ResidualCapacityEdgeMap residual_capacity;\n\n      LayerArray layers;\n      std::vector< list_iterator > layer_list_ptr_data;\n      iterator_property_map<typename std::vector< list_iterator >::iterator, VertexIndexMap> layer_list_ptr;\n      distance_size_type max_distance;  // maximal distance\n      distance_size_type max_active;    // maximal distance with active node\n      distance_size_type min_active;    // minimal distance with active node\n      boost::queue<vertex_descriptor> Q;\n\n      // Statistics counters\n      long push_count;\n      long update_count;\n      long relabel_count;\n      long gap_count;\n      long gap_node_count;\n\n      inline double global_update_frequency() { return 0.5; }\n      inline vertices_size_type alpha() { return 6; }\n      inline long beta() { return 12; }\n\n      long work_since_last_update;\n    };\n\n  } // namespace detail\n  \n  template <class Graph, \n            class CapacityEdgeMap, class ResidualCapacityEdgeMap,\n            class ReverseEdgeMap, class VertexIndexMap>\n  typename property_traits<CapacityEdgeMap>::value_type\n  push_relabel_max_flow\n    (Graph& g, \n     typename graph_traits<Graph>::vertex_descriptor src,\n     typename graph_traits<Graph>::vertex_descriptor sink,\n     CapacityEdgeMap cap, ResidualCapacityEdgeMap res,\n     ReverseEdgeMap rev, VertexIndexMap index_map)\n  {\n    typedef typename property_traits<CapacityEdgeMap>::value_type FlowValue;\n    \n    detail::push_relabel<Graph, CapacityEdgeMap, ResidualCapacityEdgeMap, \n      ReverseEdgeMap, VertexIndexMap, FlowValue>\n      algo(g, cap, res, rev, src, sink, index_map);\n    \n    FlowValue flow = algo.maximum_preflow();\n    \n    algo.convert_preflow_to_flow();\n    \n    BOOST_ASSERT(algo.is_flow());\n    BOOST_ASSERT(algo.is_optimal());\n    \n    return flow;\n  } // push_relabel_max_flow()\n  \n  template <class Graph, class P, class T, class R>\n  typename detail::edge_capacity_value<Graph, P, T, R>::type\n  push_relabel_max_flow\n    (Graph& g, \n     typename graph_traits<Graph>::vertex_descriptor src,\n     typename graph_traits<Graph>::vertex_descriptor sink,\n     const bgl_named_params<P, T, R>& params)\n  {\n    return push_relabel_max_flow\n      (g, src, sink,\n       choose_const_pmap(get_param(params, edge_capacity), g, edge_capacity),\n       choose_pmap(get_param(params, edge_residual_capacity), \n                   g, edge_residual_capacity),\n       choose_const_pmap(get_param(params, edge_reverse), g, edge_reverse),\n       choose_const_pmap(get_param(params, vertex_index), g, vertex_index)\n       );\n  }\n\n  template <class Graph>\n  typename property_traits<\n    typename property_map<Graph, edge_capacity_t>::const_type\n  >::value_type\n  push_relabel_max_flow\n    (Graph& g, \n     typename graph_traits<Graph>::vertex_descriptor src,\n     typename graph_traits<Graph>::vertex_descriptor sink)\n  {\n    bgl_named_params<int, buffer_param_t> params(0); // bogus empty param\n    return push_relabel_max_flow(g, src, sink, params);\n  }\n\n} // namespace boost\n\n#endif // BOOST_PUSH_RELABEL_MAX_FLOW_HPP\n\n", "meta": {"hexsha": "10215ff16b255ed9e7ce0844dcee9d35ef47fd01", "size": 28973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/push_relabel_max_flow.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/push_relabel_max_flow.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/push_relabel_max_flow.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": 38.7858099063, "max_line_length": 117, "alphanum_fraction": 0.5428847548, "num_tokens": 6493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.04535258523169172, "lm_q1q2_score": 0.021084488812535097}}
{"text": "\n/******************************************************************************\n\n  Various energy minimization algorithms for MRF models.\n\n  Copyright (c) 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 OPTIMIZATION_HPP_40C9F0DC_7E18_4316_A594_63DAFD793CCA_\n#define OPTIMIZATION_HPP_40C9F0DC_7E18_4316_A594_63DAFD793CCA_\n\n#include <cstddef>\n#include <cmath>\n#include <ctime>\n#include <limits>\n#include <functional>\n#include <boost/noncopyable.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/random.hpp>\n\n#include \"bo/mrf/mrf_2d.hpp\"\n#include \"bo/mrf/type_values.hpp\"\n\nnamespace bo {\nnamespace mrf {\n\n// A basic class for MRF minimization algorithms. Takes (and captures sole ownership\n// over it) an istance of TypePossibleValues<NodeType> to let its descendants sample\n// possible values of type NodeType during optimization.\ntemplate <typename NodeType, typename DataType, typename RealType>\nclass MRF2DOptimizer: boost::noncopyable\n{\npublic:\n    typedef TypeValues<NodeType> NodePossibleLabels;\n    typedef boost::scoped_ptr<NodePossibleLabels> NodePossibleLabelsPtr;\n\n    MRF2DOptimizer(NodePossibleLabels* possible_values): values_(possible_values)\n    { }\n\n    // Performs the maximum-likelihood estimation (MLE) method for the given MRF.\n    // This method is usually used to obtain initial configuration of the MRF.\n    virtual void mle(MRF2D<NodeType, DataType, RealType>& mrf)\n    {\n        for (std::size_t col = 0; col < mrf.width(); ++col) {\n            for (std::size_t row = 0; row < mrf.height(); ++row) {\n\n                RealType min_energy = std::numeric_limits<RealType>::max();\n                NodeType min_value = values_->next();\n\n                values_->reset();\n                std::size_t count = values_->count();\n\n                while (count--)\n                {\n                    NodeType value = values_->next();\n                    RealType energy = mrf.compute_local_likelihood(value, col, row);\n\n                    if (energy < min_energy)\n                    {\n                        min_energy = energy;\n                        min_value = value;\n                    }\n                }\n\n                mrf(col, row) = min_value;\n        }   }\n    }\n\n    virtual void next_iteration(MRF2D<NodeType, DataType, RealType>&) = 0;\n\n    virtual ~MRF2DOptimizer()\n    { }\n\nprotected:\n    NodePossibleLabelsPtr values_;\n};\n\n// A class impementing iterated conditional modes minimization algorithm. As its\n// parent, captures sole ownership over an istance of TypePossibleValues<NodeType>.\ntemplate <typename NodeType, typename DataType, typename RealType>\nclass ICM2D: public MRF2DOptimizer<NodeType, DataType, RealType>\n{\npublic:\n    typedef MRF2DOptimizer<NodeType, DataType, RealType> BaseType;\n\n    typedef typename BaseType::NodePossibleLabels NodePossibleLabels;\n\n    ICM2D(NodePossibleLabels* possible_values): BaseType(possible_values)\n    { }\n\n    void next_iteration(MRF2D<NodeType, DataType, RealType>& mrf)\n    {\n        for (std::size_t col = 0; col < mrf.width(); ++col) {\n            for (std::size_t row = 0; row < mrf.height(); ++row) {\n                RealType min_energy = std::numeric_limits<RealType>::max();\n                NodeType min_value = this->values_->next();\n\n                // Reset the possible labels so we can iterate through the whole\n                // variety only once.\n                this->values_->reset();\n                std::size_t count = this->values_->count();\n\n                while (count--)\n                {\n                    NodeType value = this->values_->next();\n                    RealType energy = mrf.compute_local_energy(value, col, row);\n\n                    if (energy < min_energy)\n                    {\n                        min_energy = energy;\n                        min_value = value;\n                    }\n                }\n\n                // Apply the \"best\" value.\n                mrf(col, row) = min_value;\n        }   }\n    }\n};\n\n// A class implementing Metropolis dynamics algorithm minimization algorithm. As its\n// parent, captures sole ownership over an istance of TypePossibleValues<NodeType>.\n// Additionally takes initial temperature and decreasing multiplier for it, and\n// precomputed probability for MMD modification if this modification was requested.\ntemplate <typename NodeType, typename DataType, typename RealType>\nclass MD2D: public MRF2DOptimizer<NodeType, DataType, RealType>\n{\npublic:\n    typedef MRF2DOptimizer<NodeType, DataType, RealType> BaseType;\n\n    typedef typename BaseType::NodePossibleLabels NodePossibleLabels;\n    typedef boost::uniform_real<RealType> RealDistribution;\n    typedef boost::variate_generator<boost::mt19937, RealDistribution> Generator;\n\n    MD2D(NodePossibleLabels* possible_values, RealType temp, RealType temp_delta,\n         bool is_modified, RealType mmd_probability)\n        : BaseType(possible_values), t_(temp), t_delta_(temp_delta),\n        is_modified_(is_modified), mmd_log_probab_(std::log(mmd_probability)),\n        rng_(boost::mt19937(static_cast<boost::uint32_t>(std::time(NULL))), RealDistribution(0, 1))\n    { }\n\n    void next_iteration(MRF2D<NodeType, DataType, RealType>& mrf)\n    {\n        // If a modified version of MD algo (MMD) is used, then the decision probability\n        // is fixed and obtained as a parameter. Otherwise, it is generated every time.\n        RealType decision_probab = mmd_log_probab_;\n\n        // Update current temperature. See algorithm description for details.\n        t_ *= t_delta_;\n\n        // Do an inner iteration pixelwise.\n        for (std::size_t col = 0; col < mrf.width(); ++col) {\n            for (std::size_t row = 0; row < mrf.height(); ++row) {\n                // Randomly generate a new state for the current pixel.\n                NodeType old_value = mrf(col, row);\n                NodeType new_value = this->values_->random();\n\n                // if classical version is used, generate the decision probability.\n                if (!is_modified_)\n                    decision_probab = std::log(rng_());\n\n                // Compute local energy and accept it or reject.\n                if (decision_probab <=\n                    (mrf.compute_local_energy(old_value, col, row) -\n                     mrf.compute_local_energy(new_value, col, row)) / t_)\n                {   // Accept new state.\n                    mrf(col, row) = new_value;\n                }\n        }   }\n    }\n\nprivate:\n    RealType t_;\n    RealType t_delta_;\n    bool is_modified_;\n    RealType mmd_log_probab_;\n    Generator rng_;\n};\n\n} // namespace mrf\n} // namespace bo\n\n#endif // OPTIMIZATION_HPP_40C9F0DC_7E18_4316_A594_63DAFD793CCA_\n", "meta": {"hexsha": "9b92e94cd29e51bf016b449b9d51ed9ceeb889de", "size": 8021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/mrf/optimization.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/optimization.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/optimization.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": 38.5625, "max_line_length": 99, "alphanum_fraction": 0.6450567261, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.05033063829537844, "lm_q1q2_score": 0.021073281970019148}}
{"text": "/**  \\file ublas_extra.hpp \\brief Extra functions for Ublas library */\n/*\n-----------------------------------------------------------------------------\n   Copyright (C) 2011 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\n#ifndef __UBLAS_EXTRA_HPP__\n#define __UBLAS_EXTRA_HPP__\n\n#include <typeinfo>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace bayesopt\n{\n  /// Extra utils: math functions, ublas helpers, etc.\n  namespace utils\n  {\n    template<class V, class D>\n    void append(V& vect, D element)\n    {\n      typedef typename V::value_type VD;\n      assert(typeid(VD) == typeid(D));\n      \n      // This method is super inefficient but there seems to be the uBlas style.\n      const size_t size = vect.size();\n      vect.resize(size+1,true);\n      vect(size) = element;\n    };\n\n    template<class V, class I>\n    void erase(V& vect, I begin)\n    {\n      typedef typename V::iterator VI;\n      assert(typeid(VI) == typeid(I));\n     \n      for(VI it = begin; it != vect.end()-1; ++it)\n\t{\n\t  *it = *(it+1); \n\t}\n      vect.resize(vect.size()-1);\n    };\n\n    template<class M>\n    void erase_column(M& mat, size_t pos)\n    {\n      for(size_t i = pos; i < mat.size2()-1; ++i)\n\t{\n\t  column(mat,i) = column(mat,i+1);\n\t}\n      mat.resize(mat.size1(),mat.size2()-1);\n    };\n\n    template<class M, class V>\n    void add_to_diagonal(M& mat, const V& vec)\n    {\n      assert(mat.size1()==mat.size2());\n      assert(mat.size1()==vec.size());\n      const size_t ll = vec.size();\n      for(size_t ii = 0; ii < ll; ++ii)\n\t{\n\t  mat(ii,ii) += vec(ii);\n\t}\n    };\n\n    boost::numeric::ublas::vector<double> array2vector(const double array[], \n\t\t\t\t\t\t       const size_t n);\n\n  } //  namespace utils\n} //namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "1dafa6ab76a0596a7932e90d504a92312f491ede", "size": 2460, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/utils/ublas_extra.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_extra.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_extra.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 28.6046511628, "max_line_length": 80, "alphanum_fraction": 0.6008130081, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804730998169, "lm_q2_score": 0.07921032845635174, "lm_q1q2_score": 0.02106047960436669}}
{"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 \"edge_labeler.h\"\n\n#include <Eigen/Dense>\n\n#include \"g2o/stuff/unscented.h\"\n\nnamespace g2o {\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef SigmaPoint<VectorXd> MySigmaPoint;\n\nEdgeLabeler::EdgeLabeler(SparseOptimizer* optimizer) { _optimizer = optimizer; }\n\nint EdgeLabeler::labelEdges(std::set<OptimizableGraph::Edge*>& edges) {\n  // assume the system is \"solved\"\n  // compute the sparse pattern of the inverse\n  std::set<std::pair<int, int> > pattern;\n  for (std::set<OptimizableGraph::Edge*>::iterator it = edges.begin();\n       it != edges.end(); ++it) {\n    augmentSparsePattern(pattern, *it);\n  }\n\n  SparseBlockMatrix<MatrixXd> spInv;\n\n  bool result = computePartialInverse(spInv, pattern);\n  // cerr << \"partial inverse computed = \" << result << endl;\n  // cerr << \"non zero blocks\" << spInv.nonZeroBlocks() << endl;\n\n  if (!result) {\n    return -1;\n  }\n  int count = 0;\n  for (std::set<OptimizableGraph::Edge*>::iterator it = edges.begin();\n       it != edges.end(); ++it) {\n    count += labelEdge(spInv, *it) ? 1 : 0;\n  }\n  return count;\n}\n\nvoid EdgeLabeler::augmentSparsePattern(std::set<std::pair<int, int> >& pattern,\n                                       OptimizableGraph::Edge* e) {\n  for (size_t i = 0; i < e->vertices().size(); i++) {\n    const OptimizableGraph::Vertex* v =\n        (const OptimizableGraph::Vertex*)e->vertices()[i];\n    int ti = v->hessianIndex();\n    if (ti == -1) continue;\n    for (size_t j = i; j < e->vertices().size(); j++) {\n      const OptimizableGraph::Vertex* v =\n          (const OptimizableGraph::Vertex*)e->vertices()[j];\n      int tj = v->hessianIndex();\n      if (tj == -1) continue;\n      if (tj < ti) swap(ti, tj);\n      pattern.insert(std::make_pair(ti, tj));\n    }\n  }\n}\n\nbool EdgeLabeler::computePartialInverse(\n    SparseBlockMatrix<MatrixXd>& spinv,\n    const std::set<std::pair<int, int> >& pattern) {\n  std::vector<std::pair<int, int> > blockIndices(pattern.size());\n  // Why this does not work???\n  // std::copy(pattern.begin(),pattern.end(),blockIndices.begin());\n\n  int k = 0;\n  for (std::set<std::pair<int, int> >::const_iterator it = pattern.begin();\n       it != pattern.end(); ++it) {\n    blockIndices[k++] = *it;\n  }\n\n  // cerr << \"sparse pattern contains \" << blockIndices.size() << \" blocks\" <<\n  // endl;\n  return _optimizer->computeMarginals(spinv, blockIndices);\n}\n\nbool EdgeLabeler::labelEdge(const SparseBlockMatrix<MatrixXd>& spinv,\n                            OptimizableGraph::Edge* e) {\n  Eigen::Map<MatrixXd> info(e->informationData(), e->dimension(),\n                            e->dimension());\n  // cerr << \"original information matrix\" << endl;\n  // cerr << info << endl;\n\n  int maxDim = 0;\n  for (size_t i = 0; i < e->vertices().size(); i++) {\n    const OptimizableGraph::Vertex* v =\n        (const OptimizableGraph::Vertex*)e->vertices()[i];\n    int ti = v->hessianIndex();\n    if (ti == -1) continue;\n    maxDim += v->minimalEstimateDimension();\n  }\n\n  // cerr << \"maxDim= \" << maxDim << endl;\n  MatrixXd cov(maxDim, maxDim);\n  int cumRow = 0;\n  for (size_t i = 0; i < e->vertices().size(); i++) {\n    const OptimizableGraph::Vertex* vr =\n        (const OptimizableGraph::Vertex*)e->vertices()[i];\n    int ti = vr->hessianIndex();\n    if (ti > -1) {\n      int cumCol = 0;\n      for (size_t j = 0; j < e->vertices().size(); j++) {\n        const OptimizableGraph::Vertex* vc =\n            (const OptimizableGraph::Vertex*)e->vertices()[j];\n        int tj = vc->hessianIndex();\n        if (tj > -1) {\n          // cerr << \"ti=\" << ti << \" tj=\" << tj\n          //    << \" cumRow=\" << cumRow << \" cumCol=\" << cumCol << endl;\n          if (ti <= tj) {\n            assert(spinv.block(ti, tj));\n            // cerr << \"cblock_ptr\" << spinv.block(ti, tj) << endl;\n            // cerr << \"cblock.size=\" << spinv.block(ti, tj)->rows() << \",\" <<\n            // spinv.block(ti, tj)->cols() << endl; cerr << \"cblock\" << endl;\n            // cerr << *spinv.block(ti, tj) << endl;\n            cov.block(cumRow, cumCol, vr->minimalEstimateDimension(),\n                      vc->minimalEstimateDimension()) = *spinv.block(ti, tj);\n          } else {\n            assert(spinv.block(tj, ti));\n            // cerr << \"cblock.size=\" << spinv.block(tj, ti)->cols() << \",\" <<\n            // spinv.block(tj, ti)->rows() << endl; cerr << \"cblock\" << endl;\n            // cerr << spinv.block(tj, ti)->transpose() << endl;\n            cov.block(cumRow, cumCol, vr->minimalEstimateDimension(),\n                      vc->minimalEstimateDimension()) =\n                spinv.block(tj, ti)->transpose();\n          }\n          cumCol += vc->minimalEstimateDimension();\n        }\n      }\n      cumRow += vr->minimalEstimateDimension();\n    }\n  }\n\n  // cerr << \"covariance assembled\" << endl;\n  // cerr << cov << endl;\n  // now cov contains the aggregate marginals of the state variables in the edge\n  VectorXd incMean(maxDim);\n  incMean.fill(0);\n  std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> >\n      incrementPoints;\n  if (!sampleUnscented(incrementPoints, incMean, cov)) {\n    cerr << \"sampleUnscented fail\" << endl;\n    return false;\n  }\n  // now determine the zero-error measure by applying the error function of the\n  // edge with a zero measurement\n  // TODO!!!\n  bool smss = e->setMeasurementFromState();\n  if (!smss) {\n    cerr << \"FATAL: Edge::setMeasurementFromState() not implemented\" << endl;\n  }\n  assert(smss && \"Edge::setMeasurementFromState() not implemented\");\n\n  // std::vector<MySigmaPoint> globalPoints(incrementPoints.size());\n  std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> >\n      errorPoints(incrementPoints.size());\n\n  // for each sigma point, project it to the global space, by considering those\n  // variables that are involved\n  // cerr << \"sigma points are extracted, remapping to measurement space\" <<\n  // endl;\n  for (size_t i = 0; i < incrementPoints.size(); i++) {\n    int cumPos = 0;\n    // VectorXd globalPoint(maxDim);\n\n    // push all the \"active\" state variables\n    for (size_t j = 0; j < e->vertices().size(); j++) {\n      OptimizableGraph::Vertex* vr =\n          (OptimizableGraph::Vertex*)e->vertices()[j];\n      int tj = vr->hessianIndex();\n      if (tj == -1) continue;\n      vr->push();\n    }\n\n    for (size_t j = 0; j < e->vertices().size(); j++) {\n      OptimizableGraph::Vertex* vr =\n          (OptimizableGraph::Vertex*)e->vertices()[j];\n      int tj = vr->hessianIndex();\n      if (tj == -1) continue;\n      vr->oplus(&incrementPoints[i]._sample[cumPos]);\n      // assert(vr->getMinimalEstimateData(&globalPoint[cumPos]) &&\n      // \"Vertex::getMinimalEstimateData(...) not implemented\");\n      cumPos += vr->minimalEstimateDimension();\n    }\n\n    // construct the sigma point in the global space\n    // globalPoints[i]._sample=globalPoint;\n    // globalPoints[i]._wi=incrementPoints[i]._wi;\n    // globalPoints[i]._wp=incrementPoints[i]._wp;\n\n    // construct the sigma point in the error space\n    e->computeError();\n    Map<VectorXd> errorPoint(e->errorData(), e->dimension());\n\n    errorPoints[i]._sample = errorPoint;\n    errorPoints[i]._wi = incrementPoints[i]._wi;\n    errorPoints[i]._wp = incrementPoints[i]._wp;\n\n    // pop all the \"active\" state variables\n    for (size_t j = 0; j < e->vertices().size(); j++) {\n      OptimizableGraph::Vertex* vr =\n          (OptimizableGraph::Vertex*)e->vertices()[j];\n      int tj = vr->hessianIndex();\n      if (tj == -1) continue;\n      vr->pop();\n    }\n  }\n\n  // reconstruct the covariance of the error by the sigma points\n  MatrixXd errorCov(e->dimension(), e->dimension());\n  VectorXd errorMean(e->dimension());\n  reconstructGaussian(errorMean, errorCov, errorPoints);\n\n  // info=errorCov.inverse();\n  //  cerr << \"remapped information matrix\" << endl;\n  //  cerr << info << endl;\n  return true;\n}\n\n}  // namespace g2o\n", "meta": {"hexsha": "8089bc10c7112d2aee7fb6965fa96464e2f3a582", "size": 9263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/g2o/g2o/apps/g2o_hierarchical/edge_labeler.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/apps/g2o_hierarchical/edge_labeler.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/apps/g2o_hierarchical/edge_labeler.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": 37.5020242915, "max_line_length": 80, "alphanum_fraction": 0.6230163014, "num_tokens": 2432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04208772356010582, "lm_q1q2_score": 0.02104386178005291}}
{"text": "#include <Core/Geometry/Approximation/VariationalShapeApproximation.hpp>\r\n\r\n#include <Core/Geometry/TriangleOperation.hpp>\r\n#include <Core/Utils/Log.hpp>\r\n#include <Eigen/Eigenvalues>\r\n#include <random>\r\n#include <set>\r\n\r\nnamespace Ra {\r\nnamespace Core {\r\nnamespace Geometry {\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// CONSTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline VariationalShapeApproximationBase<K_Region>::VariationalShapeApproximationBase(\r\n    const Mesh& mesh ) :\r\n    m_mesh( mesh ),\r\n    m_queue(),\r\n    m_region(),\r\n    m_proxy(),\r\n    m_init( false ) {}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline VariationalShapeApproximationBase<K_Region>::~VariationalShapeApproximationBase() {}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// INIT\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::init() {\r\n    this->compute_data();\r\n    this->compute_seed();\r\n    this->m_init = true;\r\n}\r\n\r\ntemplate <uint K_Region>\r\ninline bool VariationalShapeApproximationBase<K_Region>::initialized() const {\r\n    return m_init;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// EXECUTION\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::exec( const uint iteration ) {\r\n    if ( !this->initialized() )\r\n    {\r\n        CORE_WARN_IF( false, \"V.S.A. NOT INITIALIZED\" );\r\n        return;\r\n    }\r\n    LOG( Utils::logDEBUG ) << \"Computing V.S.A. ...\";\r\n    for ( uint i = 0; i < iteration; ++i )\r\n    {\r\n        this->proxy_fitting();\r\n        this->geometry_partitioning();\r\n    }\r\n    LOG( Utils::logDEBUG ) << \"V.S.A. completed.\";\r\n}\r\n\r\ntemplate <uint K_Region>\r\ntemplate <uint Iteration>\r\ninline void VariationalShapeApproximationBase<K_Region>::exec() {\r\n    if ( !this->initialized() )\r\n    {\r\n        CORE_WARN_IF( false, \"V.S.A. NOT INITIALIZED\" );\r\n        return;\r\n    }\r\n    LOG( Utils::logDEBUG ) << \"Computing V.S.A. ...\";\r\n    for ( uint i = 0; i < Iteration; ++i )\r\n    {\r\n        this->proxy_fitting();\r\n        this->geometry_partitioning();\r\n    }\r\n    LOG( Utils::logDEBUG ) << \"V.S.A. completed.\";\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// REGION\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline const typename VariationalShapeApproximationBase<K_Region>::Region&\r\nVariationalShapeApproximationBase<K_Region>::region( const uint i ) const {\r\n    return m_region.at( i );\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline const typename VariationalShapeApproximationBase<K_Region>::Proxy&\r\nVariationalShapeApproximationBase<K_Region>::proxy( const uint i ) const {\r\n    return m_proxy.at( i );\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// COLOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::create_region_color() {\r\n    for ( uint i = 0; i < K; ++i )\r\n    {\r\n        const Scalar q = Scalar( i ) / static_cast<Scalar>( K - 1 );\r\n        for ( const auto& T : this->m_region[i] )\r\n        {\r\n            this->m_fvalue[T] = q;\r\n        }\r\n    }\r\n}\r\n\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::create_energy_color() {\r\n    for ( uint i = 0; i < K; ++i )\r\n    {\r\n        for ( const auto& T : this->m_region[i] )\r\n        {\r\n            this->m_fvalue[T] = this->E( T, this->m_proxy[i] );\r\n        }\r\n    }\r\n}\r\n\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::shuffle_regions() {\r\n    // This function was made in order to have a chance for neighboring regions\r\n    // to have distant IDs, hence having a different color.\r\n    std::array<uint, K> id;\r\n    RegionList tmp_region;\r\n    ProxyList tmp_proxy;\r\n    for ( uint i = 0; i < K; ++i )\r\n    {\r\n        id[i] = i;\r\n    }\r\n    std::random_shuffle( id.begin(), id.end() );\r\n    for ( uint i = 0; i < K; ++i )\r\n    {\r\n        tmp_region[i] = this->m_region[id[i]];\r\n        tmp_proxy[i] = this->m_proxy[id[i]];\r\n    }\r\n    std::swap( tmp_region, this->m_region );\r\n    std::swap( tmp_proxy, this->m_proxy );\r\n    for ( uint i = 0; i < K; ++i )\r\n    {\r\n        for ( const auto& T : this->m_region[i] )\r\n        {\r\n            this->m_fregion[T] = i;\r\n        }\r\n    }\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DATA\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::compute_data() {\r\n    const uint size = this->m_mesh.m_triangles.size();\r\n    this->m_fbary.resize( size );\r\n    this->m_fnormal.resize( size );\r\n    this->m_farea.resize( size );\r\n    this->m_fregion.resize( size, -1 );\r\n    this->m_fvisited.resize( size, false );\r\n    this->m_fvalue.resize( 0 );\r\n    this->m_fadj.resize( size );\r\n\r\n    std::vector<std::vector<TriangleIdx>> vadj( this->m_mesh.m_vertices.size() );\r\n    for ( uint t = 0; t < size; ++t )\r\n    {\r\n        const Triangle& T = this->m_mesh.m_triangles[t];\r\n        const uint i = T[0];\r\n        const uint j = T[1];\r\n        const uint k = T[2];\r\n        const Math::Vector3 v[3] = {this->m_mesh.m_vertices[i], this->m_mesh.m_vertices[j],\r\n                              this->m_mesh.m_vertices[k]};\r\n        this->m_fbary[t] = triangleBarycenter( v[0], v[1], v[2] );\r\n        this->m_fnormal[t] = triangleNormal( v[0], v[1], v[2] );\r\n        this->m_farea[t] = triangleArea( v[0], v[1], v[2] );\r\n        vadj[i].push_back( t );\r\n        vadj[j].push_back( t );\r\n        vadj[k].push_back( t );\r\n    }\r\n\r\n    for ( const auto& list : vadj )\r\n    {\r\n        for ( uint i = 0; i < list.size(); ++i )\r\n        {\r\n            for ( uint j = i + 1; j < list.size(); ++j )\r\n            {\r\n                this->m_fadj[list[i]].insert( list[j] );\r\n                this->m_fadj[list[j]].insert( list[i] );\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// SEED\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::compute_seed() {\r\n    std::set<TriangleIdx> t;\r\n    std::default_random_engine g( time( 0 ) );\r\n    std::uniform_int_distribution<TriangleIdx> rnd( 0, this->m_mesh.m_triangles.size() - 1 );\r\n    while ( t.size() != K )\r\n    {\r\n        t.insert( rnd( g ) );\r\n    }\r\n    for ( uint i = 0; i < K; ++i )\r\n    {\r\n        m_region[i].push_back( *t.begin() );\r\n        t.erase( t.begin() );\r\n    }\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// GEOMETRY PARTITIONING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximationBase<K_Region>::geometry_partitioning() {\r\n    // Reset the visited flag\r\n    for ( TriangleIdx T = 0; T < this->m_mesh.m_triangles.size(); ++T )\r\n    {\r\n        this->m_fvisited[T] = false;\r\n    }\r\n\r\n    // Force the queue to be empty\r\n    this->m_queue = PriorityQueue();\r\n\r\n    // Choose best triangle in each region\r\n    for ( uint i = 0; i < K; ++i )\r\n    {\r\n        assert( !this->m_region[i].empty() );\r\n        Energy min_e = std::numeric_limits<Energy>::max();\r\n        TriangleIdx T;\r\n        for ( const auto& t : this->m_region[i] )\r\n        {\r\n            const Energy e = this->E( t, this->m_proxy[i] );\r\n            if ( e < min_e )\r\n            {\r\n                min_e = e;\r\n                T = t;\r\n            }\r\n        }\r\n        this->add_neighbors_to_queue( T, i );\r\n\r\n        // Clear the region\r\n        this->m_region[i].clear();\r\n        this->m_region[i].push_back( T );\r\n        this->m_fregion[T] = i;\r\n        this->m_fvisited[T] = true;\r\n    }\r\n\r\n    // While the queue is not empty\r\n    while ( !this->m_queue.empty() )\r\n    {\r\n        const auto q = this->m_queue.top();\r\n        this->m_queue.pop();\r\n        const TriangleIdx t = q.second.first;\r\n        if ( this->m_fvisited[t] )\r\n        {\r\n            continue;\r\n        }\r\n        const uint R = q.second.second;\r\n        this->m_region[R].push_back( t );\r\n        this->m_fregion[t] = R;\r\n        this->m_fvisited[t] = true;\r\n\r\n        this->add_neighbors_to_queue( t, R );\r\n    }\r\n}\r\n\r\ntemplate <uint K_Region>\r\ninline void\r\nVariationalShapeApproximationBase<K_Region>::add_neighbors_to_queue( const TriangleIdx& T,\r\n                                                                     const uint proxy_id ) {\r\n    for ( const auto& r : this->m_fadj[T] )\r\n    {\r\n        this->m_queue.push(\r\n            QueueEntry( this->E( r, this->m_proxy[proxy_id] ), Pair( r, proxy_id ) ) );\r\n    }\r\n}\r\n\r\n//============================================================================\r\n//============================================================================\r\n//============================================================================\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region, MetricType Type>\r\nVariationalShapeApproximation<K_Region, Type>::~VariationalShapeApproximation() {}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY FITTING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region, MetricType Type>\r\ninline void VariationalShapeApproximation<K_Region, Type>::proxy_fitting() {\r\n    static const Scalar c = 2.0 / 72.0;\r\n    Matrix3 m;\r\n    m << 10.0, 7.0, 0.0, 7.0, 10.0, 0.0, 0.0, 0.0, 0.0;\r\n    for ( uint i = 0; i < this->K; ++i )\r\n    {\r\n\r\n        Scalar area_sum = 0;\r\n        this->m_proxy[i].first = Vector3::Zero();\r\n        Matrix3 Q = Matrix3::Zero();\r\n\r\n        for ( const auto& T : this->m_region[i] )\r\n        {\r\n            const Math::Vector3 v[3] = {this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][0]],\r\n                                  this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][1]],\r\n                                  this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][2]]};\r\n            const Math::Vector3& g = this->m_fbary[T];\r\n\r\n            Matrix3 M;\r\n            M.row( 0 ) = v[1] - v[0];\r\n            M.row( 1 ) = v[2] - v[0];\r\n            M.row( 2 ) = Vector3::Zero();\r\n\r\n            Q += ( c * this->m_farea[T] * M * m * M.transpose() ) +\r\n                 ( this->m_farea[T] * g * g.transpose() );\r\n\r\n            this->m_proxy[i].first += this->m_farea[T] * g;\r\n            area_sum += this->m_farea[T];\r\n        }\r\n        this->m_proxy[i].first /= area_sum;\r\n        Q -= area_sum * this->m_proxy[i].first * this->m_proxy[i].first.transpose();\r\n        this->m_proxy[i].second =\r\n            Eigen::SelfAdjointEigenSolver<Matrix3>( Q ).eigenvectors().col( 0 ).normalized();\r\n    }\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// ENERGY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region, MetricType Type>\r\ninline Scalar VariationalShapeApproximation<K_Region, Type>::E( const TriangleIdx& T,\r\n                                                                const Proxy& P ) const {\r\n    static const Scalar c = 1.0 / 6.0;\r\n    const Math::Vector3 v[3] = {this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][0]],\r\n                          this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][1]],\r\n                          this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][2]]};\r\n    const Math::Vector3 p = P.first;\r\n    const Math::Vector3 n = P.second;\r\n    Scalar d[3];\r\n    d[0] = std::abs( n.dot( p - v[0] ) );\r\n    d[1] = std::abs( n.dot( p - v[1] ) );\r\n    d[2] = std::abs( n.dot( p - v[2] ) );\r\n    return ( c *\r\n             ( ( d[0] * d[0] ) + ( d[1] * d[1] ) + ( d[2] * d[2] ) + ( d[0] * d[1] ) +\r\n               ( d[0] * d[2] ) + ( d[1] * d[2] ) ) *\r\n             this->m_farea[T] );\r\n}\r\n\r\n//============================================================================\r\n//============================================================================\r\n//============================================================================\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\nVariationalShapeApproximation<K_Region, MetricType::L21>::~VariationalShapeApproximation() {}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY FITTING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximation<K_Region, MetricType::L21>::proxy_fitting() {\r\n    for ( uint i = 0; i < this->K; ++i )\r\n    {\r\n        Scalar area_sum = 0;\r\n        this->m_proxy[i].first = Vector3::Zero();\r\n        this->m_proxy[i].second = Vector3::Zero();\r\n        for ( const auto& T : this->m_region[i] )\r\n        {\r\n            this->m_proxy[i].first += this->m_farea[T] * this->m_fbary[T];\r\n            this->m_proxy[i].second += this->m_farea[T] * this->m_fnormal[T];\r\n            area_sum += this->m_farea[T];\r\n        }\r\n        this->m_proxy[i].first /= area_sum;\r\n        this->m_proxy[i].second = this->m_proxy[i].second.normalized();\r\n    }\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// ENERGY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline Scalar VariationalShapeApproximation<K_Region, MetricType::L21>::E( const TriangleIdx& T,\r\n                                                                           const Proxy& P ) const {\r\n    const Scalar a = this->m_farea[T];\r\n    const Math::Vector3 n = this->m_fnormal[T];\r\n    const Math::Vector3 d = n - P.second;\r\n    const Scalar result = a * d.squaredNorm();\r\n    return result;\r\n}\r\n\r\n//============================================================================\r\n//============================================================================\r\n//============================================================================\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\nVariationalShapeApproximation<K_Region, MetricType::LLOYD>::~VariationalShapeApproximation() {}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY FITTING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline void VariationalShapeApproximation<K_Region, MetricType::LLOYD>::proxy_fitting() {\r\n    for ( uint i = 0; i < this->K; ++i )\r\n    {\r\n        this->m_proxy[i].first = Vector3::Zero();\r\n        this->m_proxy[i].second = Vector3::Zero();\r\n        for ( const auto& T : this->m_region[i] )\r\n        {\r\n            this->m_proxy[i].first += this->m_fbary[T];\r\n            this->m_proxy[i].second += this->m_fnormal[T];\r\n        }\r\n        this->m_proxy[i].first /= this->m_region[i].size();\r\n        this->m_proxy[i].second = this->m_proxy[i].second.normalized();\r\n    }\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// ENERGY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate <uint K_Region>\r\ninline Scalar\r\nVariationalShapeApproximation<K_Region, MetricType::LLOYD>::E( const TriangleIdx& T,\r\n                                                               const Proxy& P ) const {\r\n    const Math::Vector3& b = this->m_fbary[T];\r\n    const Scalar result = ( b - P.first ).norm();\r\n    return result;\r\n}\r\n\r\n} // namespace Geometry\r\n} // namespace Core\r\n} // namespace Ra\r\n", "meta": {"hexsha": "2e835172439b4007d8fc452954fc3e004482f29a", "size": 16702, "ext": "inl", "lang": "C++", "max_stars_repo_path": "src/Core/Geometry/VariationalShapeApproximation.inl", "max_stars_repo_name": "sylvaindeker/Radium-Engine", "max_stars_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T13:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-16T13:55:45.000Z", "max_issues_repo_path": "src/Core/Geometry/VariationalShapeApproximation.inl", "max_issues_repo_name": "sylvaindeker/Radium-Engine", "max_issues_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/Geometry/VariationalShapeApproximation.inl", "max_forks_repo_name": "sylvaindeker/Radium-Engine", "max_forks_repo_head_hexsha": "64164a258b3f7864c73a07c070e49b7138488d62", "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.5325842697, "max_line_length": 100, "alphanum_fraction": 0.4292899054, "num_tokens": 3630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.04336579984571784, "lm_q1q2_score": 0.021005529784007645}}
{"text": "/*!\n * @file traits.cpp\n * \n * @author Andrzej Ciarkowski <mailto:andrzej.ciarkowski@gmail.com>\n */\n\n#include <dsp++/config.h>\n#include <dsp++/fftw/plan_unavailable.h>\n\n// emit vtable and type_info for the exception in this translation unit\ndsp::dft::fftw::plan_unavailable::~plan_unavailable() throw() {}\n\n#if !DSP_FFTW_DISABLED\n\n#include <dsp++/export.h>\n#include <dsp++/fft.h> // for dft::sign::forward/dft::sign::backward\n#include <dsp++/fftw/allocator.h>\n#include <dsp++/fftw/dft.h>\n#include <boost/static_assert.hpp>\n\n#include <fftw3.h> // Visual Studio build: place fftw3 distribution in directory pointed by %FFTW3_ROOT% environment variable and x64 version of thereof in %FFTW3_ROOT%\\x64\n\n#if defined(_MSC_VER) && !defined(DSPXX_STATIC)\n#if DSP_FFTW_HAVE_FLOAT\n#pragma comment(lib, \"libfftw3f-3.lib\")\n#endif // DSP_FFTW_HAVE_FLOAT\n#if DSP_FFTW_HAVE_DOUBLE\n#pragma comment(lib, \"libfftw3-3.lib\")\n#endif // DSP_FFTW_HAVE_DOUBLE\n#if DSP_FFTW_HAVE_LONG_DOUBLE\n#pragma comment(lib, \"libfftw3l-3.lib\")\n#endif // DSP_FFTW_HAVE_LONG_DOUBLE\n#if DSP_FFTW_HAVE_QUAD\n#pragma comment(lib, \"libfftw3q-3.lib\")\n#endif // DSP_FFTW_HAVE_QUAD\n#endif // _MSC_VER && !DSPXX_STATIC\n\nusing namespace dsp::dft::fftw;\n\nvoid dsp::dft::fftw::detail::verify_plan_available(void* plan)\n{\n\tif (NULL == plan)\n\t\tthrow plan_unavailable();\n}\n\nnamespace {\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::R2HC) == FFTW_R2HC);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::HC2R) == FFTW_HC2R);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::DHT) == FFTW_DHT);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::REDFT00) == FFTW_REDFT00);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::REDFT01) == FFTW_REDFT01);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::REDFT10) == FFTW_REDFT10);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::REDFT11) == FFTW_REDFT11);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::RODFT00) == FFTW_RODFT00);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::RODFT01) == FFTW_RODFT01);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::RODFT10) == FFTW_RODFT10);\n\tBOOST_STATIC_ASSERT(static_cast<int>(r2r::RODFT11) == FFTW_RODFT11);\n\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::measure) == FFTW_MEASURE);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::destroy_input) == FFTW_DESTROY_INPUT);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::unaligned) == FFTW_UNALIGNED);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::conserve_memory) == FFTW_CONSERVE_MEMORY);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::exhaustive) == FFTW_EXHAUSTIVE);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::preserve_input) == FFTW_PRESERVE_INPUT);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::patient) == FFTW_PATIENT);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::estimate) == FFTW_ESTIMATE);\n\tBOOST_STATIC_ASSERT(static_cast<int>(flag::wisdom_only) == FFTW_WISDOM_ONLY);\n\n\tBOOST_STATIC_ASSERT(static_cast<int>(dsp::dft::sign::forward) == FFTW_FORWARD);\n\tBOOST_STATIC_ASSERT(static_cast<int>(dsp::dft::sign::backward) == FFTW_BACKWARD);\n\tBOOST_STATIC_ASSERT(sizeof(int) == sizeof(unsigned));\t// unsigned is (unsigned int), so it must be the same size and it should be fine to cast unsigned/signed pointers too\n}\n\n#define MANGLE(prefix, name) prefix ## name\n#define COMPLEX_CAST(prefix, param) reinterpret_cast<MANGLE(prefix, complex)*>(param)\n#define KIND_CAST(prefix, param) static_cast<MANGLE(prefix, r2r_kind)>(param)\n#define PKIND_CAST(prefix, param) reinterpret_cast<const MANGLE(prefix, r2r_kind)*>(param)\n#define INT(param) static_cast<int>(param)\n#define CPINT(param) reinterpret_cast<const int*>(param)\n\n#define DEFINE_TRAITS(prefix, type) \\\nBOOST_STATIC_ASSERT(sizeof(dsp::dft::fftw::r2r::kind) == sizeof(MANGLE(prefix, r2r_kind)));\\\n\\\nvoid traits<type>::execute(const plan_type p) {MANGLE(prefix, execute)(p);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft(size_t rank, const unsigned* n,\\\n\t\t    complex_type* in, complex_type* out, dsp::dft::sign::spec sign, unsigned flags)\\\n{return MANGLE(prefix, plan_dft)(INT(rank), CPINT(n), COMPLEX_CAST(prefix, in), COMPLEX_CAST(prefix, out), static_cast<int>(sign), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_1d(size_t n, complex_type* in, complex_type* out, dsp::dft::sign::spec sign,\\\n\t\t       unsigned flags)\\\n{return MANGLE(prefix, plan_dft_1d)(INT(n), COMPLEX_CAST(prefix, in), COMPLEX_CAST(prefix, out), static_cast<int>(sign), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_2d(size_t n0, size_t n1,\\\n\t\t       complex_type* in, complex_type* out, dsp::dft::sign::spec sign, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_2d)(INT(n0), INT(n1), COMPLEX_CAST(prefix, in), COMPLEX_CAST(prefix, out), static_cast<int>(sign), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_3d(size_t n0, size_t n1, size_t n2,\\\n\t\t       complex_type* in, complex_type* out, dsp::dft::sign::spec sign, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_3d)(INT(n0), INT(n1), INT(n2), COMPLEX_CAST(prefix, in), COMPLEX_CAST(prefix, out), static_cast<int>(sign), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_many_dft(size_t rank, const unsigned* n,\\\n                         size_t howmany,\\\n                         complex_type* in, const int* inembed,\\\n                         int istride, int idist,\\\n                         complex_type* out, const int* onembed,\\\n                         int ostride, int odist,\\\n                         dsp::dft::sign::spec sign, unsigned flags)\\\n{return MANGLE(prefix, plan_many_dft)(INT(rank), CPINT(n), INT(howmany), COMPLEX_CAST(prefix, in), inembed, istride, idist, COMPLEX_CAST(prefix, out), onembed, ostride, odist, static_cast<int>(sign), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru_dft(size_t rank, const fftw_iodim* dims,\\\n\t\t\t size_t howmany_rank,\\\n\t\t\t const fftw_iodim* howmany_dims,\\\n\t\t\t complex_type* in, complex_type* out,\\\n\t\t\t dsp::dft::sign::spec sign, unsigned flags)\\\n{return MANGLE(prefix, plan_guru_dft)(INT(rank), dims, INT(howmany_rank), howmany_dims, COMPLEX_CAST(prefix, in), COMPLEX_CAST(prefix, out), static_cast<int>(sign), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru_split_dft(size_t rank, const fftw_iodim* dims,\\\n\t\t\t size_t howmany_rank,\\\n\t\t\t const fftw_iodim* howmany_dims,\\\n\t\t\t real_type* ri, real_type* ii, real_type* ro, real_type* io,\\\n\t\t\t unsigned flags)\\\n{return MANGLE(prefix, plan_guru_split_dft)(INT(rank), dims, INT(howmany_rank), howmany_dims, ri, ii, ro, io, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru64_dft(size_t rank,\\\n                         const fftw_iodim64* dims,\\\n\t\t\t size_t howmany_rank,\\\n\t\t\t const fftw_iodim64* howmany_dims,\\\n\t\t\t complex_type* in, complex_type* out,\\\n\t\t\t dsp::dft::sign::spec sign, unsigned flags)\\\n{return MANGLE(prefix, plan_guru64_dft)(INT(rank), dims, INT(howmany_rank), howmany_dims, COMPLEX_CAST(prefix, in), COMPLEX_CAST(prefix, out), static_cast<int>(sign), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru64_split_dft(size_t rank,\\\n                         const fftw_iodim64* dims,\\\n\t\t\t size_t howmany_rank,\\\n\t\t\t const fftw_iodim64* howmany_dims,\\\n\t\t\t real_type* ri, real_type* ii, real_type* ro, real_type* io,\\\n\t\t\t unsigned flags)\\\n{return MANGLE(prefix, plan_guru64_split_dft)(INT(rank), dims, INT(howmany_rank), howmany_dims, ri, ii, ro, io, flags);}\\\n\\\nvoid traits<type>::execute_dft(const plan_type p, complex_type* in, complex_type* out)\\\n{MANGLE(prefix, execute_dft)(p, COMPLEX_CAST(prefix, in), COMPLEX_CAST(prefix, out));}\\\n\\\nvoid traits<type>::execute_split_dft(const plan_type p, real_type* ri, real_type* ii,\\\n                                      real_type* ro, real_type* io)\\\n{MANGLE(prefix, execute_split_dft)(p, ri, ii, ro, io);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_many_dft_r2c(size_t rank, const unsigned* n,\\\n                             size_t howmany,\\\n                             real_type* in, const int* inembed,\\\n                             int istride, int idist,\\\n                             complex_type* out, const int* onembed,\\\n                             int ostride, int odist,\\\n                             unsigned flags)\\\n{return MANGLE(prefix, plan_many_dft_r2c)(INT(rank), CPINT(n), INT(howmany), in, inembed, istride, idist, COMPLEX_CAST(prefix, out), onembed, ostride, odist, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_r2c(size_t rank, const unsigned* n,\\\n                        real_type* in, complex_type* out, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_r2c)(INT(rank), CPINT(n), in, COMPLEX_CAST(prefix, out), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_r2c_1d(size_t n,real_type* in,complex_type* out,unsigned flags)\\\n{return MANGLE(prefix, plan_dft_r2c_1d)(INT(n), in, COMPLEX_CAST(prefix, out), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_r2c_2d(size_t n0, size_t n1,\\\n\t\t\t   real_type* in, complex_type* out, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_r2c_2d)(INT(n0), INT(n1), in, COMPLEX_CAST(prefix, out), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_r2c_3d(size_t n0, size_t n1, size_t n2,\\\n\t\t\t   real_type* in, complex_type* out, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_r2c_3d)(INT(n0), INT(n1), INT(n2), in, COMPLEX_CAST(prefix, out), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_many_dft_c2r(size_t rank, const unsigned* n,\\\n\t\t\t     size_t howmany,\\\n\t\t\t     complex_type* in, const int* inembed,\\\n\t\t\t     int istride, int idist,\\\n\t\t\t     real_type* out, const int* onembed,\\\n\t\t\t     int ostride, int odist,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_many_dft_c2r)(INT(rank), CPINT(n), INT(howmany), COMPLEX_CAST(prefix, in), inembed, istride, idist, out, onembed, ostride, odist, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_c2r(size_t rank, const unsigned* n,\\\n                        complex_type* in, real_type* out, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_c2r)(INT(rank), CPINT(n), COMPLEX_CAST(prefix, in), out, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_c2r_1d(size_t n, complex_type* in, real_type* out,unsigned flags)\\\n{return MANGLE(prefix, plan_dft_c2r_1d)(INT(n), COMPLEX_CAST(prefix, in), out, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_c2r_2d(size_t n0, size_t n1,\\\n\t\t\t   complex_type* in, real_type* out, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_c2r_2d)(INT(n0), INT(n1), COMPLEX_CAST(prefix, in), out, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_dft_c2r_3d(size_t n0, size_t n1, size_t n2,\\\n\t\t\t   complex_type* in, real_type* out, unsigned flags)\\\n{return MANGLE(prefix, plan_dft_c2r_3d)(INT(n0), INT(n1), INT(n2), COMPLEX_CAST(prefix, in), out, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru_dft_r2c(size_t rank, const fftw_iodim* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim* howmany_dims,\\\n\t\t\t     real_type* in, complex_type* out,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru_dft_r2c)(INT(rank), dims, INT(howmany_rank), howmany_dims, in, COMPLEX_CAST(prefix, out), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru_dft_c2r(size_t rank, const fftw_iodim* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim* howmany_dims,\\\n\t\t\t     complex_type* in, real_type* out,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru_dft_c2r)(INT(rank), dims, INT(howmany_rank), howmany_dims, COMPLEX_CAST(prefix, in), out, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru_split_dft_r2c(\\\n                             size_t rank, const fftw_iodim* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim* howmany_dims,\\\n\t\t\t     real_type* in, real_type* ro, real_type* io,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru_split_dft_r2c)(INT(rank), dims, INT(howmany_rank), howmany_dims, in, ro, io, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru_split_dft_c2r(\\\n                             size_t rank, const fftw_iodim* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim* howmany_dims,\\\n\t\t\t     real_type* ri, real_type* ii, real_type* out,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru_split_dft_c2r)(INT(rank), dims, INT(howmany_rank), howmany_dims, ri, ii, out, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru64_dft_r2c(size_t rank,\\\n                             const fftw_iodim64* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim64* howmany_dims,\\\n\t\t\t     real_type* in, complex_type* out,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru64_dft_r2c)(INT(rank), dims, INT(howmany_rank), howmany_dims, in, COMPLEX_CAST(prefix, out), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru64_dft_c2r(size_t rank,\\\n                             const fftw_iodim64* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim64* howmany_dims,\\\n\t\t\t     complex_type* in, real_type* out,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru64_dft_c2r)(INT(rank), dims, INT(howmany_rank), howmany_dims, COMPLEX_CAST(prefix, in), out, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru64_split_dft_r2c(\\\n                             size_t rank, const fftw_iodim64* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim64* howmany_dims,\\\n\t\t\t     real_type* in, real_type* ro, real_type* io,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru64_split_dft_r2c)(INT(rank), dims, INT(howmany_rank), howmany_dims, in, ro, io, flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru64_split_dft_c2r(\\\n                             size_t rank, const fftw_iodim64* dims,\\\n\t\t\t     size_t howmany_rank,\\\n\t\t\t     const fftw_iodim64* howmany_dims,\\\n\t\t\t     real_type* ri, real_type* ii, real_type* out,\\\n\t\t\t     unsigned flags)\\\n{return MANGLE(prefix, plan_guru64_split_dft_c2r)(INT(rank), dims, INT(howmany_rank), howmany_dims, ri, ii, out, flags);}\\\n\\\nvoid traits<type>::execute_dft_r2c(const plan_type p, real_type* in, complex_type* out)\\\n{MANGLE(prefix, execute_dft_r2c)(p, in, COMPLEX_CAST(prefix, out));}\\\n\\\nvoid traits<type>::execute_dft_c2r(const plan_type p, complex_type* in, real_type* out)\\\n{MANGLE(prefix, execute_dft_c2r)(p, COMPLEX_CAST(prefix, in), out);}\\\n\\\nvoid traits<type>::execute_split_dft_r2c(const plan_type p,\\\n                                          real_type* in, real_type* ro, real_type* io)\\\n{MANGLE(prefix, execute_split_dft_r2c)(p, in, ro, io);}\\\n\\\nvoid traits<type>::execute_split_dft_c2r(const plan_type p,\\\n                                          real_type* ri, real_type* ii, real_type* out)\\\n{MANGLE(prefix, execute_split_dft_c2r)(p, ri, ii, out);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_many_r2r(size_t rank, const unsigned* n,\\\n                         size_t howmany,\\\n                         real_type* in, const int* inembed,\\\n                         int istride, int idist,\\\n                         real_type* out, const int* onembed,\\\n                         int ostride, int odist,\\\n                         const r2r::kind* kind, unsigned flags)\\\n{return MANGLE(prefix, plan_many_r2r)(INT(rank), CPINT(n), INT(howmany), in, inembed, istride, idist, out, onembed, ostride, odist, PKIND_CAST(prefix, kind), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_r2r(size_t rank, const unsigned* n, real_type* in, real_type* out,\\\n                    const r2r::kind* kind, unsigned flags)\\\n{return MANGLE(prefix, plan_r2r)(INT(rank), CPINT(n), in, out, PKIND_CAST(prefix, kind), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_r2r_1d(size_t n, real_type* in, real_type* out,\\\n                       r2r::kind kind, unsigned flags)\\\n{return MANGLE(prefix, plan_r2r_1d)(INT(n), in, out, KIND_CAST(prefix, kind), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_r2r_2d(size_t n0, size_t n1, real_type* in, real_type* out,\\\n                       r2r::kind kind0, r2r::kind kind1,\\\n                       unsigned flags)\\\n{return MANGLE(prefix, plan_r2r_2d)(INT(n0), INT(n1), in, out, KIND_CAST(prefix, kind0), KIND_CAST(prefix, kind1), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_r2r_3d(size_t n0, size_t n1, size_t n2,\\\n                       real_type* in, real_type* out, r2r::kind kind0,\\\n                       r2r::kind kind1, r2r::kind kind2,\\\n                       unsigned flags)\\\n{return MANGLE(prefix, plan_r2r_3d)(INT(n0), INT(n1), INT(n2), in, out, KIND_CAST(prefix, kind0), KIND_CAST(prefix, kind1), KIND_CAST(prefix, kind2), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru_r2r(size_t rank, const fftw_iodim* dims,\\\n                         size_t howmany_rank,\\\n                         const fftw_iodim* howmany_dims,\\\n                         real_type* in, real_type* out,\\\n                         const r2r::kind* kind, unsigned flags)\\\n{return MANGLE(prefix, plan_guru_r2r)(INT(rank), dims, INT(howmany_rank), howmany_dims, in, out, PKIND_CAST(prefix, kind), flags);}\\\n\\\ntraits<type>::plan_type traits<type>::plan_guru64_r2r(size_t rank, const fftw_iodim64* dims,\\\n                         size_t howmany_rank,\\\n                         const fftw_iodim64* howmany_dims,\\\n                         real_type* in, real_type* out,\\\n                         const r2r::kind* kind, unsigned flags)\\\n{return MANGLE(prefix, plan_guru64_r2r)(INT(rank), dims, INT(howmany_rank), howmany_dims, in, out, PKIND_CAST(prefix, kind), flags);}\\\n\\\nvoid traits<type>::execute_r2r(const plan_type p, real_type* in, real_type* out)\\\n{MANGLE(prefix, execute_r2r)(p, in, out);}\\\n\\\nvoid traits<type>::destroy_plan(plan_type p)\\\n{MANGLE(prefix, destroy_plan)(p);}\\\n\\\nvoid traits<type>::forget_wisdom(void)\\\n{MANGLE(prefix, forget_wisdom)();}\\\n\\\nvoid traits<type>::cleanup(void)\\\n{MANGLE(prefix, cleanup)();}\\\n\\\nvoid traits<type>::set_timelimit(double t)\\\n{MANGLE(prefix, set_timelimit)(t);}\\\n\\\nvoid traits<type>::plan_with_nthreads(unsigned nthreads)\\\n{MANGLE(prefix, plan_with_nthreads)(INT(nthreads));}\\\n\\\nint traits<type>::init_threads(void)\\\n{return MANGLE(prefix, init_threads)();}\\\n\\\nvoid traits<type>::cleanup_threads(void)\\\n{MANGLE(prefix, cleanup_threads)();}\\\n\\\nint traits<type>::export_wisdom_to_filename(const char* filename)\\\n{return MANGLE(prefix, export_wisdom_to_filename)(filename);}\\\n\\\nvoid traits<type>::export_wisdom_to_file(FILE* output_file)\\\n{MANGLE(prefix, export_wisdom_to_file)(output_file);}\\\n\\\nchar* traits<type>::export_wisdom_to_string(void)\\\n{return MANGLE(prefix, export_wisdom_to_string)();}\\\n\\\nvoid traits<type>::export_wisdom(fftw_write_char_func write_char,\\\n                                  void* data)\\\n{MANGLE(prefix, export_wisdom)(write_char, data);}\\\n\\\nint traits<type>::import_system_wisdom(void)\\\n{return MANGLE(prefix, import_system_wisdom)();}\\\n\\\nint traits<type>::import_wisdom_from_filename(const char* filename)\\\n{return MANGLE(prefix, import_wisdom_from_filename)(filename);}\\\n\\\nint traits<type>::import_wisdom_from_file(FILE* input_file)\\\n{return MANGLE(prefix, import_wisdom_from_file)(input_file);}\\\n\\\nint traits<type>::import_wisdom_from_string(const char* input_string)\\\n{return MANGLE(prefix, import_wisdom_from_string)(input_string);}\\\n\\\nint traits<type>::import_wisdom(fftw_read_char_func read_char, void* data)\\\n{return MANGLE(prefix, import_wisdom)(read_char, data);}\\\n\\\nvoid traits<type>::fprint_plan(const plan_type p, FILE* output_file)\\\n{MANGLE(prefix, fprint_plan)(p, output_file);}\\\n\\\nvoid traits<type>::print_plan(const plan_type p)\\\n{MANGLE(prefix, print_plan)(p);}\\\n\\\nvoid* traits<type>::malloc(size_t n)\\\n{return MANGLE(prefix, malloc)(n);}\\\n\\\ntraits<type>::real_type* traits<type>::alloc_real(size_t n)\\\n{return MANGLE(prefix, alloc_real)(n);}\\\n\\\ntraits<type>::complex_type* traits<type>::alloc_complex(size_t n)\\\n{return reinterpret_cast<complex_type*>(MANGLE(prefix, alloc_complex)(n));}\\\n\\\nvoid traits<type>::free(void* p)\\\n{MANGLE(prefix, free)(p);}\\\n\\\nvoid traits<type>::flops(const plan_type p,\\\n                          double* add, double* mul, double* fmas)\\\n{MANGLE(prefix, flops)(p, add, mul, fmas);}\\\n\\\ndouble traits<type>::estimate_cost(const plan_type p)\\\n{return MANGLE(prefix, estimate_cost)(p);}\\\n\\\ndouble traits<type>::cost(const plan_type p)\\\n{return MANGLE(prefix, cost)(p);} \\\n\\\ntemplate class DSPXX_API dsp::dft::fftw::dft<type, type>; \\\ntemplate class DSPXX_API dsp::dft::fftw::dft<type, std::complex<type> >; \\\ntemplate class DSPXX_API dsp::dft::fftw::dft<std::complex<type>, type>; \\\ntemplate class DSPXX_API dsp::dft::fftw::dft<std::complex<type>, std::complex<type> >;\n    \n#if DSP_FFTW_HAVE_FLOAT\nDEFINE_TRAITS(fftwf_, float)\n#endif // DSP_FFTW_HAVE_FLOAT\n\n#if DSP_FFTW_HAVE_DOUBLE\nDEFINE_TRAITS(fftw_, double)\n#endif // DSP_FFTW_HAVE_FLOAT\n\n#if DSP_FFTW_HAVE_LONG_DOUBLE\nDEFINE_TRAITS(fftwl_, long double)\n#endif // DSP_FFTW_HAVE_FLOAT\n\n#if DSP_FFTW_HAVE_QUAD\nDEFINE_TRAITS(fftwq_, quad)\n#endif // DSP_FFTW_HAVE_FLOAT\n\nvoid* allocator_base::allocate(size_t n)\n{\n\tvoid* p =\n#if DSP_FFTW_HAVE_FLOAT\n\t\t\ttraits<float>::malloc(n);\n#elif DSP_FFTW_HAVE_DOUBLE\n\t\t\ttraits<double>::malloc(n);\n#elif DSP_FFTW_HAVE_LONG_DOUBLE\n\t\t\ttraits<long double>::malloc(n);\n#elif DSP_FFTW_HAVE_QUAD\n\t\t\ttraits<quad>::malloc(n);\n#else\n\t\t\tmalloc(n);\n#endif\n\tif (NULL == p)\n\t\tthrow std::bad_alloc();\n\treturn p;\n}\n\nvoid allocator_base::deallocate(void* p)\n{\n#if DSP_FFTW_HAVE_FLOAT\n\t\t\ttraits<float>::free(p);\n#elif DSP_FFTW_HAVE_DOUBLE\n\t\t\ttraits<double>::free(p);\n#elif DSP_FFTW_HAVE_LONG_DOUBLE\n\t\t\ttraits<long double>::free(p);\n#elif DSP_FFTW_HAVE_QUAD\n\t\t\ttraits<quad>::free(p);\n#else\n\t\t\tfree(p);\n#endif\n}\n    \n\n\n#endif // !DSP_FFTW3_DISABLED\n\n", "meta": {"hexsha": "2f5fb3c14e11f168e74e6575696a17242ed31191", "size": 21436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dsp++/src/fftw/traits.cpp", "max_stars_repo_name": "andrzejc/dsp-", "max_stars_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dsp++/src/fftw/traits.cpp", "max_issues_repo_name": "andrzejc/dsp-", "max_issues_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsp++/src/fftw/traits.cpp", "max_forks_repo_name": "andrzejc/dsp-", "max_forks_repo_head_hexsha": "fd39d2395a37ade36e3b551d261de0177b78296b", "max_forks_repo_licenses": ["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.3200883002, "max_line_length": 209, "alphanum_fraction": 0.6929464452, "num_tokens": 6076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.0550052937153603, "lm_q1q2_score": 0.020969094211961786}}
{"text": "//  Copyright (c) 2006, Giovanni P. Deretta\n//\n//  This code may be used under either of the following two licences:\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 \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 FROM, \n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN \n//  THE SOFTWARE. OF SUCH DAMAGE.\n//\n//  Or:\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#include <cstdlib>\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_io.hpp>\n#include <boost/bind.hpp>\n#include <boost/coroutine/coroutine.hpp>\n\n/*\n * Play the iterated prisoner dilemma between two prisoners.\n * Each prisoner is impersonated by a coroutine using the actor model.\n * Each coroutine can implement a different strategy.\n * On paper this looked as a great coroutine demonstrator, because\n * each player might use a complex algorithm better implemented in a coroutine. \n * Unfortunately the best known solution (tit-for-tat) is so trivially\n * simple that doesn't need state!.\n */\nnamespace coroutines = boost::coroutines;\nusing coroutines::coroutine;\n\nenum option {cooperate, defect};\n\ntypedef coroutine<option(option)> coroutine_type;\n\ntypedef boost::tuple<int, int> score_type;\n\nvoid add_score(score_type& x, option a, option b) {\n  if(a == cooperate && b == defect) {\n    x.get<0>() += 0;\n    x.get<1>() += 5;\n  } else if(a == defect && b == defect) {\n    x.get<0>() += 1;\n    x.get<1>() += 1;\n  } else if(a == defect && b == cooperate) {\n    x.get<0>() += 5;\n    x.get<1>() += 0;\n  } else  /* if(a == cooperate && b == cooperate) */ { \n    x.get<0>() += 3;\n    x.get<1>() += 3;\n  }\n}\n\nscore_type play(coroutine_type plr1, \n\t\tcoroutine_type plr2, \n\t\tsize_t iterations) {\n  score_type score(0,0);\n  option a = cooperate;\n  option b = cooperate;\n  while(iterations--) {\n    option new_a = plr1(b);\n    option new_b = plr2(a);\n    a = new_a;\n    b = new_b;\n    add_score(score, a, b);\n  }\n  return score;\n}\n\noption always_cooperate(coroutine_type::self& self, option) {\n  while(true) \n    self.yield(cooperate);\n  return cooperate;\n}\n\noption always_defect(coroutine_type::self& self, option) {\n  while(true) \n    self.yield(defect);\n  return defect;\n}\n\noption random_result(coroutine_type::self& self, option) {\n  while(true) \n    self.yield(std::rand()%2? defect: cooperate);\n  return defect;\n}\n\noption tit_for_tat(coroutine_type::self& self, option a) {\n  while(true) \n    a = self.yield(a);\n  return cooperate;\n}\n\noption tit_for_tat_forgiving(coroutine_type::self& self, option a, int forgiveness) {\n  while(true) \n    a = self.yield((std::rand() %100) < forgiveness? cooperate: a);\n  return cooperate;\n}\n\nint main() {\n  coroutine_type list[] = {\n    coroutine_type(always_cooperate),\n    coroutine_type(always_defect),\n    coroutine_type(random_result),\n    coroutine_type(tit_for_tat),\n    coroutine_type(boost::bind(tit_for_tat_forgiving, _1, _2, 15)),\n    coroutine_type(boost::bind(tit_for_tat_forgiving, _1, _2, 10))\n  };\n\n  int scores [sizeof(list)] = {};\n  (void)scores;\n  const int rounds = 100;\n  std::cout << play(coroutine_type(always_cooperate),\n\t\t    coroutine_type(always_cooperate),\n\t\t    rounds)<<\"\\n\";\n  std::cout << play(coroutine_type(always_cooperate),\n\t\t    coroutine_type(always_defect),\n\t\t    rounds)<<\"\\n\";\n  std::cout << play(coroutine_type(always_defect),\n\t\t    coroutine_type(always_defect),\n\t\t    rounds)<<\"\\n\";\n  std::cout << play(coroutine_type(always_cooperate),\n\t\t    coroutine_type(random_result),\n\t\t    rounds)<<\"\\n\";\n  std::cout << play(coroutine_type(always_defect),\n\t\t    coroutine_type(random_result),\n\t\t    rounds)<<\"\\n\";\n  std::cout << play(coroutine_type(tit_for_tat),\n\t\t    coroutine_type(always_cooperate),\n\t\t    rounds)<<\"\\n\";\n  std::cout << play(coroutine_type(tit_for_tat),\n\t\t    coroutine_type(always_defect),\n\t\t    rounds)<<\"\\n\";\n  std::cout << play(coroutine_type(tit_for_tat),\n\t\t    coroutine_type(random_result),\n\t\t    rounds)<<\"\\n\";\n}\n", "meta": {"hexsha": "5f6efdc9eb53d8827cd6c4039fb7632efd2a218b", "size": 4944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/coroutine/example/prisonerdilemma.cpp", "max_stars_repo_name": "erikfrey/coroutine", "max_stars_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-10-19T02:52:00.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-09T09:52:25.000Z", "max_issues_repo_path": "libs/coroutine/example/prisonerdilemma.cpp", "max_issues_repo_name": "erikfrey/coroutine", "max_issues_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/coroutine/example/prisonerdilemma.cpp", "max_forks_repo_name": "erikfrey/coroutine", "max_forks_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "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.1038961039, "max_line_length": 85, "alphanum_fraction": 0.6895226537, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.06954174209535333, "lm_q1q2_score": 0.020914371487049544}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <cstddef>\n#include <tuple>\n#include <algorithm>\n#include <NTL/BasicThreadPool.h>\n#include <helib/matmul.h>\n#include <helib/norms.h>\n#include <helib/fhe_stats.h>\n#include <helib/apiAttributes.h>\n\nnamespace helib {\n\nint fhe_test_force_bsgs = 0;\nint fhe_test_force_hoist = 0;\n\nstatic bool comp_bsgs(bool bsgs)\n{\n  if (fhe_test_force_bsgs > 0)\n    return true;\n  if (fhe_test_force_bsgs < 0)\n    return false;\n  return bsgs;\n}\n\n#if 0\nstatic bool comp_hoist(bool hoist)\n{\n   if (fhe_test_force_hoist > 0) return true;\n   if (fhe_test_force_hoist < 0) return false;\n   return hoist;\n}\n#endif\n\n/********************************************************************/\n/****************** Auxiliary stuff: should go elsewhere   **********/\n\n/**\n * @class BasicAutomorphPrecon\n * @brief Pre-computation to speed many automorphism on the same ciphertext.\n *\n * The expensive part of homomorphic automorphism is breaking the ciphertext\n * parts into digits. The usual setting is we first rotate the ciphertext\n * parts, then break them into digits. But when we apply many automorphisms\n * it is faster to break the original ciphertext into digits, then rotate\n * the digits (as opposed to first rotate, then break).\n * An BasicAutomorphPrecon object breaks the original ciphertext and keeps\n * the digits, then when you call automorph is only needs to apply the\n * native automorphism and key switching to the digits, which is fast(er).\n **/\nclass BasicAutomorphPrecon\n{\n  Ctxt ctxt;\n  NTL::xdouble noise;\n  std::vector<DoubleCRT> polyDigits;\n\npublic:\n  BasicAutomorphPrecon(const Ctxt& _ctxt) : ctxt(_ctxt), noise(1.0)\n  {\n    HELIB_TIMER_START;\n    if (ctxt.parts.size() >= 1)\n      assertTrue(\n          ctxt.parts[0].skHandle.isOne(),\n          \"Invalid ciphertext (secret key handle for part 0 is not one)\");\n    if (ctxt.parts.size() <= 1)\n      return; // nothing to do\n\n    ctxt.cleanUp();\n    const Context& context = ctxt.getContext();\n    const PubKey& pubKey = ctxt.getPubKey();\n    long keyID = ctxt.getKeyID();\n\n    // The call to cleanUp() should ensure that this assertion passes.\n    assertTrue(ctxt.inCanonicalForm(keyID),\n               \"Ciphertext is not in canonical form\");\n\n    // Compute the number of digits that we need and the estimated\n    // added noise from switching this ciphertext.\n\n    NTL::xdouble addedNoise = ctxt.parts[1].breakIntoDigits(polyDigits);\n    NTL::xdouble max_ks_noise(0.0);\n    for (const KeySwitch& ks : pubKey.keySWlist()) {\n      if (max_ks_noise < ks.noiseBound)\n        max_ks_noise = ks.noiseBound;\n    }\n    addedNoise *= max_ks_noise;\n\n    double logProd = context.logOfProduct(context.specialPrimes);\n    noise = ctxt.getNoiseBound() * NTL::xexp(logProd);\n\n    HELIB_STATS_UPDATE(\"KS-noise-ratio-hoist\",\n                       NTL::conv<double>(addedNoise / noise));\n    // std::stderr << \"*** HOIST INIT\\n\";\n    // fprintf(stderr, \"   KS-log-noise-ratio-hoist: %f\\n\",\n    // log(addedNoise/noise)/log(2.0));\n\n    noise += addedNoise;\n  }\n\n  std::shared_ptr<Ctxt> automorph(long k) const\n  {\n    HELIB_TIMER_START;\n\n    // A hack: record this automorphism rather than actually performing it\n    if (isSetAutomorphVals()) { // defined in NumbTh.h\n      recordAutomorphVal(k);\n      return std::make_shared<Ctxt>(ctxt);\n    }\n\n    if (k == 1 || ctxt.isEmpty())\n      return std::make_shared<Ctxt>(ctxt); // nothing to do\n\n    const Context& context = ctxt.getContext();\n    const PubKey& pubKey = ctxt.getPubKey();\n    // empty ctxt\n    std::shared_ptr<Ctxt> result = std::make_shared<Ctxt>(ZeroCtxtLike, ctxt);\n    result->noiseBound = noise; // noise estimate\n    result->intFactor = ctxt.intFactor;\n\n    if (ctxt.isCKKS()) {\n      result->ptxtMag = ctxt.ptxtMag;\n      double logProd = context.logOfProduct(context.specialPrimes);\n      result->ratFactor = ctxt.ratFactor * NTL::xexp(logProd);\n    }\n\n    if (ctxt.parts.size() == 1) { // only constant part, no need to key-switch\n      CtxtPart tmpPart = ctxt.parts[0];\n      tmpPart.automorph(k);\n      tmpPart.addPrimesAndScale(context.specialPrimes);\n      result->addPart(tmpPart, /*matchPrimeSet=*/true);\n      return result;\n    }\n\n    // Ensure that we have a key-switching matrices for this automorphism\n    long keyID = ctxt.getKeyID();\n    if (!pubKey.isReachable(k, keyID)) {\n      throw LogicError(\"no key-switching matrices for k=\" + std::to_string(k) +\n                       \", keyID=\" + std::to_string(keyID));\n    }\n\n    // Get the first key-switching matrix for this automorphism\n    const KeySwitch& W = pubKey.getNextKSWmatrix(k, keyID);\n    long amt = W.fromKey.getPowerOfX();\n\n    // Start by rotating the constant part, no need to key-switch it\n    CtxtPart tmpPart = ctxt.parts[0];\n    tmpPart.automorph(amt);\n    tmpPart.addPrimesAndScale(context.specialPrimes);\n    result->addPart(tmpPart, /*matchPrimeSet=*/true);\n\n    // Then rotate the digits and key-switch them\n    std::vector<DoubleCRT> tmpDigits = polyDigits;\n    for (auto&& tmp : tmpDigits) // rotate each of the digits\n      tmp.automorph(amt);\n\n    result->keySwitchDigits(W, tmpDigits); // key-switch the digits\n\n    long m = context.zMStar.getM();\n    if ((amt - k) % m != 0) { // amt != k (mod m), more automorphisms to do\n      k = NTL::MulMod(k, NTL::InvMod(amt, m), m); // k *= amt^{-1} mod m\n      result->smartAutomorph(k);                  // call usual smartAutomorph\n    }\n    return result;\n  }\n};\n\nclass GeneralAutomorphPrecon\n{\npublic:\n  virtual ~GeneralAutomorphPrecon() {}\n\n  virtual std::shared_ptr<Ctxt> automorph(long i) const = 0;\n};\n\nclass GeneralAutomorphPrecon_UNKNOWN : public GeneralAutomorphPrecon\n{\nprivate:\n  Ctxt ctxt;\n  long dim;\n  const PAlgebra& zMStar;\n\npublic:\n  GeneralAutomorphPrecon_UNKNOWN(const Ctxt& _ctxt,\n                                 long _dim,\n                                 const EncryptedArray& ea) :\n      ctxt(_ctxt), dim(_dim), zMStar(ea.getPAlgebra())\n  {\n    ctxt.cleanUp();\n  }\n\n  std::shared_ptr<Ctxt> automorph(long i) const override\n  {\n    std::shared_ptr<Ctxt> result = std::make_shared<Ctxt>(ctxt);\n\n    // guard against i == 0, as dim may be #gens\n    if (i != 0)\n      result->smartAutomorph(zMStar.genToPow(dim, i));\n\n    return result;\n  }\n};\n\nclass GeneralAutomorphPrecon_FULL : public GeneralAutomorphPrecon\n{\nprivate:\n  BasicAutomorphPrecon precon;\n  long dim;\n  const PAlgebra& zMStar;\n\npublic:\n  GeneralAutomorphPrecon_FULL(const Ctxt& _ctxt,\n                              long _dim,\n                              const EncryptedArray& ea) :\n      precon(_ctxt), dim(_dim), zMStar(ea.getPAlgebra())\n  {}\n\n  std::shared_ptr<Ctxt> automorph(long i) const override\n  {\n    return precon.automorph(zMStar.genToPow(dim, i));\n  }\n};\n\nclass GeneralAutomorphPrecon_BSGS : public GeneralAutomorphPrecon\n{\nprivate:\n  long dim;\n  const PAlgebra& zMStar;\n\n  long D;\n  long g;\n  long h;\n  std::vector<std::shared_ptr<BasicAutomorphPrecon>> precon;\n\npublic:\n  GeneralAutomorphPrecon_BSGS(const Ctxt& _ctxt,\n                              long _dim,\n                              const EncryptedArray& ea) :\n      dim(_dim), zMStar(ea.getPAlgebra())\n  {\n    D = (dim == -1) ? zMStar.getOrdP() : zMStar.OrderOf(dim);\n    g = KSGiantStepSize(D);\n    h = divc(D, g);\n\n    BasicAutomorphPrecon precon0(_ctxt);\n    precon.resize(h);\n\n    // parallel for k in [0..h)\n    NTL_EXEC_RANGE(h, first, last)\n    for (long k = first; k < last; k++) {\n      std::shared_ptr<Ctxt> p = precon0.automorph(zMStar.genToPow(dim, g * k));\n      precon[k] = std::make_shared<BasicAutomorphPrecon>(*p);\n    }\n    NTL_EXEC_RANGE_END\n  }\n\n  std::shared_ptr<Ctxt> automorph(long i) const override\n  {\n    assertInRange(i, 0l, D, \"Automorphism index i is not in [0, D)\");\n    long j = i % g;\n    long k = i / g;\n    // i == j + g*k\n    return precon[k]->automorph(zMStar.genToPow(dim, j));\n  }\n};\n\nstd::shared_ptr<GeneralAutomorphPrecon> buildGeneralAutomorphPrecon(\n    const Ctxt& ctxt,\n    long dim,\n    const EncryptedArray& ea)\n{\n  // allow dim == -1 (Frobenius)\n  // allow dim == #gens (the dummy generator of order 1)\n  assertInRange(dim,\n                -1l,\n                ea.dimension(),\n                \"Dimension dim is not in [-1, ea.dimension()] (-1 Frobenius)\",\n                true);\n\n  if (fhe_test_force_hoist >= 0) {\n    switch (ctxt.getPubKey().getKSStrategy(dim)) {\n    case HELIB_KSS_BSGS:\n      return std::make_shared<GeneralAutomorphPrecon_BSGS>(ctxt, dim, ea);\n\n    case HELIB_KSS_FULL:\n      return std::make_shared<GeneralAutomorphPrecon_FULL>(ctxt, dim, ea);\n\n    default:\n      return std::make_shared<GeneralAutomorphPrecon_UNKNOWN>(ctxt, dim, ea);\n    }\n  } else {\n    return std::make_shared<GeneralAutomorphPrecon_UNKNOWN>(ctxt, dim, ea);\n  }\n}\n\n/********************************************************************/\n/****************** Linear transformation classes *******************/\n\nstruct ConstMultiplier\n{ // stores a constant in either zzX or DoubleCRT format\n\n  virtual ~ConstMultiplier() {}\n\n  virtual void mul(Ctxt& ctxt) const = 0;\n\n  virtual std::shared_ptr<ConstMultiplier> upgrade(\n      const Context& context) const = 0;\n  // Upgrade to DCRT. Returns null if no upgrade required\n};\n\nstruct ConstMultiplier_DoubleCRT : ConstMultiplier\n{\n  DoubleCRT data;\n  double sz;\n\n  ConstMultiplier_DoubleCRT(const DoubleCRT& _data, double _sz) :\n      data(_data), sz(_sz)\n  {}\n\n  void mul(Ctxt& ctxt) const override { ctxt.multByConstant(data, sz); }\n\n  std::shared_ptr<ConstMultiplier> upgrade(\n      UNUSED const Context& context) const override\n  {\n    return nullptr;\n  }\n};\n\nstruct ConstMultiplier_zzX : ConstMultiplier\n{\n  zzX data;\n\n  ConstMultiplier_zzX(const zzX& _data) : data(_data) {}\n\n  void mul(Ctxt& ctxt) const override { ctxt.multByConstant(data); }\n\n  std::shared_ptr<ConstMultiplier> upgrade(\n      const Context& context) const override\n  {\n    double sz = embeddingLargestCoeff(data, context.zMStar);\n\n    return std::make_shared<ConstMultiplier_DoubleCRT>(\n        DoubleCRT(data, context, context.fullPrimes()),\n        sz);\n  }\n};\n\ntemplate <typename RX>\nstd::shared_ptr<ConstMultiplier> build_ConstMultiplier(const RX& poly)\n{\n  if (IsZero(poly))\n    return nullptr;\n  else\n    return std::make_shared<ConstMultiplier_zzX>(balanced_zzX(poly));\n}\n\ntemplate <typename RX, typename type>\nstd::shared_ptr<ConstMultiplier> build_ConstMultiplier(\n    const RX& poly,\n    long dim,\n    long amt,\n    const EncryptedArrayDerived<type>& ea)\n{\n  if (IsZero(poly))\n    return nullptr;\n  else {\n    RX poly1;\n    plaintextAutomorph(poly1, poly, dim, amt, ea);\n    return std::make_shared<ConstMultiplier_zzX>(balanced_zzX(poly1));\n  }\n}\n\nvoid MulAdd(Ctxt& x, const std::shared_ptr<ConstMultiplier>& a, const Ctxt& b)\n// x += a*b\n{\n  if (a) {\n    Ctxt tmp(b);\n    a->mul(tmp);\n    x += tmp;\n  }\n}\n\nvoid DestMulAdd(Ctxt& x, const std::shared_ptr<ConstMultiplier>& a, Ctxt& b)\n// x += a*b, b may be modified\n{\n  if (a) {\n    a->mul(b);\n    x += b;\n  }\n}\n\nvoid ConstMultiplierCache::upgrade(const Context& context)\n{\n  HELIB_TIMER_START;\n\n  long n = multiplier.size();\n  NTL_EXEC_RANGE(n, first, last)\n  for (long i : range(first, last)) {\n    if (multiplier[i])\n      if (auto newptr = multiplier[i]->upgrade(context))\n        multiplier[i] = std::shared_ptr<ConstMultiplier>(newptr);\n  }\n  NTL_EXEC_RANGE_END\n}\n\nstatic inline long dimSz(const EncryptedArray& ea, long dim)\n{\n  return (dim == ea.dimension()) ? 1 : ea.sizeOfDimension(dim);\n}\n\nstatic inline long dimSz(const EncryptedArrayBase& ea, long dim)\n{\n  return (dim == ea.dimension()) ? 1 : ea.sizeOfDimension(dim);\n}\n\nstatic inline long dimNative(const EncryptedArray& ea, long dim)\n{\n  return (dim == ea.dimension()) ? true : ea.nativeDimension(dim);\n}\n\nstatic inline long dimNative(const EncryptedArrayBase& ea, long dim)\n{\n  return (dim == ea.dimension()) ? true : ea.nativeDimension(dim);\n}\n\ntemplate <typename type>\nstruct MatMul1D_derived_impl\n{\n  PA_INJECT(type)\n\n  static void processDiagonal1(RX& poly,\n                               long i,\n                               const EncryptedArrayDerived<type>& ea,\n                               const MatMul1D_derived<type>& mat)\n  {\n    long dim = mat.getDim();\n    long D = dimSz(ea, dim);\n\n    std::vector<RX> tmpDiag(D);\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n    RX entry;\n\n    // Process the entries in this diagonal one at a time\n    for (long j = 0; j < D; j++) { // process entry j\n      bool zEntry = mat.get(entry, mcMod(j - i, D), j, 0);\n      // entry [j-i mod D, j]\n\n      assertTrue(zEntry || deg(entry) < ea.getDegree(),\n                 \"Entry is non zero and degree of entry greater or \"\n                 \"equal than ea.getDegree()\");\n      // get(...) returns true if the entry is empty, false otherwise\n\n      if (!zEntry && IsZero(entry))\n        zEntry = true; // zero is an empty entry too\n\n      if (!zEntry) {   // not a zero entry\n        zDiag = false; // mark diagonal as non-empty\n\n        // clear entries between last nonzero entry and this one\n        for (long jj = nzLast + 1; jj < j; jj++)\n          clear(tmpDiag[jj]);\n        tmpDiag[j] = entry;\n        nzLast = j;\n      }\n    }\n    if (zDiag) {\n      clear(poly);\n    } else {\n\n      // clear trailing zero entries\n      for (long jj = nzLast + 1; jj < D; jj++)\n        clear(tmpDiag[jj]);\n\n      std::vector<RX> diag(ea.size());\n      if (D == 1)\n        diag.assign(ea.size(), tmpDiag[0]); // dimension of size one\n      else {\n        for (long j = 0; j < ea.size(); j++)\n          diag[j] = tmpDiag[ea.coordinate(dim, j)];\n        // rearrange the indexes based on the current dimension\n      }\n\n      ea.encode(poly, diag);\n    }\n  }\n\n  static void processDiagonal2(RX& poly,\n                               long idx,\n                               const EncryptedArrayDerived<type>& ea,\n                               const MatMul1D_derived<type>& mat)\n  {\n    long dim = mat.getDim();\n    long D = dimSz(ea, dim);\n\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n    RX entry;\n\n    long n = ea.size();\n\n    // Process the entries in this diagonal one at a time\n    long blockIdx, innerIdx;\n    std::vector<RX> diag(n);\n    for (long j = 0; j < n; j++) {\n      if (D == 1) {\n        blockIdx = j;\n        innerIdx = 0;\n      } else {\n        std::tie(blockIdx, innerIdx) // std::pair<long,long> idxes\n            = ea.getPAlgebra().breakIndexByDim(j, dim);\n        //\tblockIdx = idxes.first;  // which transformation\n        //\tinnerIdx = idxes.second; // index along dimension dim\n      }\n      // process entry j\n      bool zEntry =\n          mat.get(entry, mcMod(innerIdx - idx, D), innerIdx, blockIdx);\n      // entry [i,j-i mod D] in the block corresponding to blockIdx\n      // get(...) returns true if the entry is empty, false otherwise\n\n      // If non-zero, make sure the degree is not too large\n      assertTrue(zEntry || deg(entry) < ea.getDegree(),\n                 \"Entry is non zero and degree of entry greater or \"\n                 \"equal than ea.getDegree()\");\n\n      if (!zEntry && IsZero(entry))\n        zEntry = true; // zero is an empty entry too\n\n      if (!zEntry) {   // not a zero entry\n        zDiag = false; // mark diagonal as non-empty\n\n        // clear entries between last nonzero entry and this one\n        for (long jj = nzLast + 1; jj < j; jj++)\n          clear(diag[jj]);\n        nzLast = j;\n        diag[j] = entry;\n      }\n    }\n    if (zDiag) {\n      clear(poly);\n    } else {\n\n      // clear trailing zero entries\n      for (long jj = nzLast + 1; jj < ea.size(); jj++)\n        clear(diag[jj]);\n\n      ea.encode(poly, diag);\n    }\n  }\n\n  // Get the i'th diagonal, encoded as a single constant.\n  static void processDiagonal(RX& poly,\n                              long i,\n                              const EncryptedArrayDerived<type>& ea,\n                              const MatMul1D_derived<type>& mat)\n  {\n    if (mat.multipleTransforms())\n      processDiagonal2(poly, i, ea, mat);\n    else\n      processDiagonal1(poly, i, ea, mat);\n  }\n};\n\ntemplate <typename type>\nvoid MatMul1D_derived<type>::processDiagonal(\n    RX& poly,\n    long i,\n    const EncryptedArrayDerived<type>& ea) const\n{\n  MatMul1D_derived_impl<type>::processDiagonal(poly, i, ea, *this);\n}\n\n// explicit instantiations\ntemplate void MatMul1D_derived<PA_GF2>::processDiagonal(\n    RX& poly,\n    long i,\n    const EncryptedArrayDerived<PA_GF2>& ea) const;\n\ntemplate void MatMul1D_derived<PA_zz_p>::processDiagonal(\n    RX& poly,\n    long i,\n    const EncryptedArrayDerived<PA_zz_p>& ea) const;\n\n#define ALT_MATMUL (1)\n\ntemplate <typename type>\nstruct MatMul1DExec_construct\n{\n  PA_INJECT(type)\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    const MatMul1D& mat_basetype,\n                    std::vector<std::shared_ptr<ConstMultiplier>>& vec,\n                    std::vector<std::shared_ptr<ConstMultiplier>>& vec1,\n                    long g)\n  {\n    const MatMul1D_partial<type>& mat =\n        dynamic_cast<const MatMul1D_partial<type>&>(mat_basetype);\n\n    long dim = mat.getDim();\n    long D = dimSz(ea, dim);\n    bool native = dimNative(ea, dim);\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    if (native) {\n\n      vec.resize(D);\n\n      for (long i : range(D)) {\n        // i == j + g * k (where j = (g != 0) ? i % g : i)\n        long k;\n\n        if (g) {\n          k = i / g;\n        } else {\n          k = 1;\n        }\n\n        RX poly;\n        mat.processDiagonal(poly, i, ea);\n        vec[i] = build_ConstMultiplier(poly, dim, -g * k, ea);\n      }\n    } else {\n      vec.resize(D);\n      vec1.resize(D);\n\n      for (long i : range(D)) {\n        // i == j + g * k (where j = (g != 0) ? i % g : i)\n        long k;\n\n        if (g) {\n          k = i / g;\n        } else {\n          k = 1;\n        }\n\n        RX poly;\n        mat.processDiagonal(poly, i, ea);\n\n        if (IsZero(poly)) {\n          vec[i] = nullptr;\n          vec1[i] = nullptr;\n          continue;\n        }\n\n        const RX& mask = ea.getTab().getMaskTable()[dim][i];\n        const RXModulus& PhimXMod = ea.getTab().getPhimXMod();\n\n        RX poly1, poly2;\n        MulMod(poly1, poly, mask, PhimXMod);\n        sub(poly2, poly, poly1);\n\n        // poly1 = poly w/ first i slots zeroed out\n        // poly2 = poly w/ last D-i slots zeroed out\n\n        vec[i] = build_ConstMultiplier(poly1, dim, -g * k, ea);\n\n#if (ALT_MATMUL)\n        long DD = D;\n        if (g)\n          DD = 0;\n        vec1[i] = build_ConstMultiplier(poly2, dim, DD - g * k, ea);\n#else\n        vec1[i] = build_ConstMultiplier(poly2, dim, D - g * k, ea);\n#endif\n      }\n    }\n  }\n};\n\n// HERE\nvoid MatMul1D_CKKS::processDiagonal(zzX& poly,\n                                    double& size,\n                                    double& factor,\n                                    long i,\n                                    const EncryptedArrayCx& ea) const\n{\n  long D = ea.size();\n\n  std::vector<std::complex<double>> diag(D);\n\n  bool zDiag = true; // is this a zero diagonal?\n\n  // Process the entries in this diagonal one at a time\n  for (long j = 0; j < D; j++) { // process entry j\n    diag[j] = this->get(mcMod(j - i, D), j);\n    // entry [j-i mod D, j]\n\n    if (diag[j] != 0.0)\n      zDiag = false; // mark diagonal as non-empty\n  }\n\n  size = factor = 0;\n  if (zDiag)\n    clear(poly);\n  else {\n    size = max_abs(diag);\n    factor = ea.encode(poly, diag, 1.0);\n    // VJS-FIXME: we are using size=1.0.\n    // Maybe we should allow this to be parameterized?\n    // We could also allow a more general precision parameter??\n  }\n}\n\nvoid plaintextAutomorph_CKKS(zzX& b,\n                             const zzX& a,\n                             long j,\n                             const EncryptedArrayCx& ea)\n{\n  const PAlgebra& zMStar = ea.getPAlgebra();\n  long k = zMStar.genToPow(0, j);\n  long m = zMStar.getM();\n  long d = a.length() - 1;\n\n  // compute b(X) = a(X^k) mod (X^{m/2}+1)\n  if (k == 1 || d <= 0) {\n    b = a;\n    return;\n  }\n\n  b.SetLength(m / 2);\n  NTL::mulmod_precon_t precon = NTL::PrepMulModPrecon(k, m);\n\n  for (long j = 0; j <= d; j++) {\n    long pos = NTL::MulModPrecon(j, k, m, precon);\n    long c = a[j];\n    if (pos >= m / 2) {\n      c = -c;\n      pos -= m / 2;\n    }\n    b[pos] = c;\n  }\n\n  normalize(b);\n}\n\nstruct ConstMultiplier_DoubleCRT_CKKS : ConstMultiplier\n{\n  DoubleCRT data;\n  double size, factor;\n\n  ConstMultiplier_DoubleCRT_CKKS(const DoubleCRT& _data,\n                                 double _size,\n                                 double _factor) :\n      data(_data), size(_size), factor(_factor)\n  {}\n\n  void mul(Ctxt& ctxt) const override\n  {\n    ctxt.multByConstantCKKS(data,\n                            NTL::to_xdouble(size),\n                            NTL::to_xdouble(factor));\n  }\n  // we use the default RoundingError parameter\n\n  std::shared_ptr<ConstMultiplier> upgrade(\n      UNUSED const Context& context) const override\n  {\n    return nullptr;\n  }\n};\n\nstruct ConstMultiplier_zzX_CKKS : ConstMultiplier\n{\n  zzX data;\n  double size, factor;\n\n  ConstMultiplier_zzX_CKKS(const zzX& _data, double _size, double _factor) :\n      data(_data), size(_size), factor(_factor)\n  {}\n\n  void mul(Ctxt& ctxt) const override\n  {\n    DoubleCRT dcrt(data, ctxt.getContext(), ctxt.getPrimeSet());\n    ctxt.multByConstantCKKS(dcrt,\n                            NTL::to_xdouble(size),\n                            NTL::to_xdouble(factor));\n  }\n\n  std::shared_ptr<ConstMultiplier> upgrade(\n      const Context& context) const override\n  {\n    return std::make_shared<ConstMultiplier_DoubleCRT_CKKS>(\n        DoubleCRT(data, context, context.fullPrimes()),\n        size,\n        factor);\n  }\n};\n\nstatic std::shared_ptr<ConstMultiplier> build_ConstMultiplier_CKKS(\n    const zzX& poly,\n    long amt,\n    double size,\n    double factor,\n    const EncryptedArrayCx& ea)\n{\n  if (IsZero(poly))\n    return nullptr;\n  else {\n    zzX poly1;\n    plaintextAutomorph_CKKS(poly1, poly, amt, ea);\n    return std::make_shared<ConstMultiplier_zzX_CKKS>(poly1, size, factor);\n  }\n}\n\nstatic void MatMul1DExec_construct_CKKS(\n    const EncryptedArrayCx& ea,\n    const MatMul1D& mat_basetype,\n    std::vector<std::shared_ptr<ConstMultiplier>>& vec,\n    long g)\n{\n  const MatMul1D_CKKS& mat = dynamic_cast<const MatMul1D_CKKS&>(mat_basetype);\n\n  long dim = mat.getDim();\n  long D = dimSz(ea, dim);\n  bool native = dimNative(ea, dim);\n\n  if (dim != 0 || D != ea.size() || !native)\n    throw LogicError(\"MatMul1DExec_construct_CKKS: bad params\");\n\n  vec.resize(D);\n\n  for (long i : range(D)) {\n    // i == j + g * k (where j = (g != 0) ? i % g : i)\n    long k;\n\n    if (g) {\n      k = i / g;\n    } else {\n      k = 1;\n    }\n\n    zzX poly;\n    double size, factor;\n    mat.processDiagonal(poly, size, factor, i, ea);\n    vec[i] = build_ConstMultiplier_CKKS(poly, -g * k, size, factor, ea);\n  }\n}\n\n#define HELIB_BSGS_MUL_THRESH HELIB_KEYSWITCH_THRESH\n// uses a BSGS multiplication strategy if sizeof(dim) > HELIB_BSGS_MUL_THRESH;\n// otherwise uses the old strategy (but potentially with hoisting)\n\n// For performance purposes, should not exceed HELIB_KEYSWITCH_THRESH\n// For testing purposes:\n//    set to 1 to always use BSGS\n//    set to infty to never use BSGS\n\nMatMul1DExec::MatMul1DExec(const MatMul1D& mat, bool _minimal) :\n    ea(mat.getEA()), minimal(_minimal)\n{\n  HELIB_NTIMER_START(MatMul1DExec);\n\n  dim = mat.getDim();\n  assertInRange(dim,\n                0l,\n                ea.dimension(),\n                \"Matrix dimension not in [0, ea.dimension()]\",\n                true);\n\n  D = dimSz(ea, dim);\n  native = dimNative(ea, dim);\n\n  bool bsgs = comp_bsgs(D > HELIB_BSGS_MUL_THRESH ||\n                        (minimal && D > HELIB_KEYSWITCH_MIN_THRESH));\n\n  if (!bsgs)\n    g = 0; // do not use BSGS\n  else\n    g = KSGiantStepSize(D); // use BSGS\n\n  if (ea.getTag() == PA_cx_tag) {\n    MatMul1DExec_construct_CKKS(ea.getCx(), mat, cache.multiplier, g);\n  } else {\n    ea.dispatch<MatMul1DExec_construct>(mat,\n                                        cache.multiplier,\n                                        cache1.multiplier,\n                                        g);\n  }\n}\n\n/***************************************************************************\n\nBS/GS logic:\n\n  \\sum_{i=0}^{D-1} const_i rot^i(v)\n    = \\sum_k \\sum_j const_{j+g*k} rot^{j+g*k}(v)\n    = \\sum_k rot^{g*k}[ \\sum_j rot^{-g*k}(const_{j+g*k}) rot^j(v) ]\n\nSo we first compute baby_steps[j] = rot^j(v) for j in [0..g).\nThen for each k in [0..ceil(D/g)), we compute\n   giant_steps[k] = \\rot^{g*k}[ rot^{-g*k}(const_{j+g*k}) baby_steps[j] ]\nThen we add up all the giant_steps.\n\nIn bad dimensions:\n\nWe need to compute\n\\[\n  \\sum_{j,k} c_{j+gk} r^{j+gk}(x)\n\\]\nwhere $r^i$ denotes rotation by $i$.\nIn bad dimensions, we have\n\\[\n r^i(x) = d_i \\rho^i(x) + e_i \\rho^{i-D}(x)\n\\]\nfor constants $d_i$ and $e_i$.\nHere, d_i is maskTable[i][amt] and e_i = 1-d_i\n\nSo putting it all together\n\\[\n  \\sum_{j,k} c_{j+gk} r^{j+gk}(x)\n= \\sum_{j,k} d'_{j+gk} \\rho^{j+gk}(x) + e'_{j+gk} \\rho^{j+gk-D}(x)\n     \\text{where $d'_i=c_i d_i$ and $e'_i = c_i e_i$}\n\n\n=               \\sum_k \\rho^{gk}[ \\sum_j d''_{j+gk} \\rho^j(x) ]\n   + \\rho^{-D}[ \\sum_k \\rho^{gk}[ \\sum_j e''_{j+gk} \\rho^j(x) ] ]\n      \\text{where $d''_{j+gk} = \\rho^{-gk}(d'_{j+gk})$ and\n                  $e''_{j+gk} = \\rho^{D-gk}(d'_{j+gk})$}\n\n\\]\n\n***************************************************************************/\n\nvoid GenBabySteps(std::vector<std::shared_ptr<Ctxt>>& v,\n                  const Ctxt& ctxt,\n                  long dim,\n                  bool clean)\n{\n  long n = v.size();\n  assertTrue<InvalidArgument>(n > 0, \"Empty vector v\");\n\n  if (n == 1) {\n    v[0] = std::make_shared<Ctxt>(ctxt);\n    if (clean)\n      v[0]->cleanUp();\n    return;\n  }\n\n  const PAlgebra& zMStar = ctxt.getContext().zMStar;\n\n  // std::cerr << \"*** STRATEGY FOR dim \" << dim << \" = \" <<\n  // ctxt.getPubKey().getKSStrategy(dim) << \"\\n\";\n\n  if (fhe_test_force_hoist >= 0 &&\n      ctxt.getPubKey().getKSStrategy(dim) != HELIB_KSS_UNKNOWN) {\n    BasicAutomorphPrecon precon(ctxt);\n\n    NTL_EXEC_RANGE(n, first, last)\n    for (long j : range(first, last)) {\n      v[j] = precon.automorph(zMStar.genToPow(dim, j));\n      if (clean)\n        v[j]->cleanUp();\n    }\n    NTL_EXEC_RANGE_END\n  } else {\n    Ctxt ctxt0(ctxt);\n    ctxt0.cleanUp();\n\n    NTL_EXEC_RANGE(n, first, last)\n    for (long j : range(first, last)) {\n      v[j] = std::make_shared<Ctxt>(ctxt0);\n      v[j]->smartAutomorph(zMStar.genToPow(dim, j));\n      if (clean)\n        v[j]->cleanUp();\n    }\n    NTL_EXEC_RANGE_END\n  }\n}\n\nvoid MatMul1DExec::mul(Ctxt& ctxt) const\n{\n  HELIB_NTIMER_START(mul_MatMul1DExec);\n\n  assertEq(&ea.getContext(),\n           &ctxt.getContext(),\n           \"Cannot multiply ciphertexts with context different to \"\n           \"encrypted array one\");\n  const PAlgebra& zMStar = ea.getPAlgebra();\n\n  ctxt.cleanUp();\n\n  bool iterative = false;\n  if (ctxt.getPubKey().getKSStrategy(dim) == HELIB_KSS_MIN)\n    iterative = true;\n\n  if (g != 0) {\n    // baby-step / giant-step\n\n    if (native) {\n\n      if (iterative) {\n\n        std::vector<Ctxt> baby_steps(g, Ctxt(ZeroCtxtLike, ctxt));\n        baby_steps[0] = ctxt;\n        for (long j : range(1, g)) {\n          baby_steps[j] = baby_steps[j - 1];\n          baby_steps[j].smartAutomorph(zMStar.genToPow(dim, 1));\n          baby_steps[j].cleanUp();\n        }\n\n        long h = divc(D, g);\n        Ctxt sum(ZeroCtxtLike, ctxt);\n        for (long k = h - 1; k >= 0; k--) {\n          if (k < h - 1) {\n            sum.smartAutomorph(zMStar.genToPow(dim, g));\n            sum.cleanUp();\n          }\n\n          for (long j : range(g)) {\n            long i = j + g * k;\n            if (i >= D)\n              break;\n            MulAdd(sum, cache.multiplier[i], baby_steps[j]);\n          }\n        }\n\n        ctxt = sum;\n\n      } else {\n\n        long h = divc(D, g);\n        std::vector<std::shared_ptr<Ctxt>> baby_steps(g);\n        GenBabySteps(baby_steps, ctxt, dim, true);\n\n        NTL::PartitionInfo pinfo(h);\n        long cnt = pinfo.NumIntervals();\n\n        std::vector<Ctxt> acc(cnt, Ctxt(ZeroCtxtLike, ctxt));\n\n        // parallel for loop: k in [0..h)\n        NTL_EXEC_INDEX(cnt, index)\n        long first, last;\n        pinfo.interval(first, last, index);\n\n        for (long k : range(first, last)) {\n          Ctxt acc_inner(ZeroCtxtLike, ctxt);\n\n          for (long j : range(g)) {\n            long i = j + g * k;\n            if (i >= D)\n              break;\n            MulAdd(acc_inner, cache.multiplier[i], *baby_steps[j]);\n          }\n\n          if (k > 0)\n            acc_inner.smartAutomorph(zMStar.genToPow(dim, g * k));\n          acc[index] += acc_inner;\n        }\n        NTL_EXEC_INDEX_END\n\n        ctxt = acc[0];\n        for (long i : range(1, cnt))\n          ctxt += acc[i];\n      }\n    } else {\n#if (ALT_MATMUL)\n      if (iterative) {\n\n        std::vector<Ctxt> baby_steps(g, Ctxt(ZeroCtxtLike, ctxt));\n        baby_steps[0] = ctxt;\n        for (long j : range(1, g)) {\n          baby_steps[j] = baby_steps[j - 1];\n          baby_steps[j].smartAutomorph(zMStar.genToPow(dim, 1));\n          baby_steps[j].cleanUp();\n        }\n\n        std::vector<Ctxt> baby_steps1(g, Ctxt(ZeroCtxtLike, ctxt));\n        baby_steps1[0] = ctxt;\n        baby_steps1[0].smartAutomorph(zMStar.genToPow(dim, -D));\n\n        for (long j : range(1, g)) {\n          baby_steps1[j] = baby_steps1[j - 1];\n          baby_steps1[j].smartAutomorph(zMStar.genToPow(dim, 1));\n          baby_steps1[j].cleanUp();\n        }\n\n        long h = divc(D, g);\n        Ctxt sum(ZeroCtxtLike, ctxt);\n        for (long k = h - 1; k >= 0; k--) {\n          if (k < h - 1) {\n            sum.smartAutomorph(zMStar.genToPow(dim, g));\n            sum.cleanUp();\n          }\n\n          for (long j : range(g)) {\n            long i = j + g * k;\n            if (i >= D)\n              break;\n            MulAdd(sum, cache.multiplier[i], baby_steps[j]);\n            MulAdd(sum, cache1.multiplier[i], baby_steps1[j]);\n          }\n        }\n        ctxt = sum;\n      } else {\n        long h = divc(D, g);\n        std::vector<std::shared_ptr<Ctxt>> baby_steps(g);\n        std::vector<std::shared_ptr<Ctxt>> baby_steps1(g);\n\n        GenBabySteps(baby_steps, ctxt, dim, false);\n\n        Ctxt ctxt1(ctxt);\n        ctxt1.smartAutomorph(zMStar.genToPow(dim, -D));\n        GenBabySteps(baby_steps1, ctxt1, dim, false);\n\n        NTL::PartitionInfo pinfo(h);\n        long cnt = pinfo.NumIntervals();\n\n        std::vector<Ctxt> acc(cnt, Ctxt(ZeroCtxtLike, ctxt));\n\n        // parallel for loop: k in [0..h)\n        NTL_EXEC_INDEX(cnt, index)\n\n        long first, last;\n        pinfo.interval(first, last, index);\n\n        for (long k : range(first, last)) {\n          Ctxt acc_inner(ZeroCtxtLike, ctxt);\n\n          for (long j : range(g)) {\n            long i = j + g * k;\n            if (i >= D)\n              break;\n            MulAdd(acc_inner, cache.multiplier[i], *baby_steps[j]);\n            MulAdd(acc_inner, cache1.multiplier[i], *baby_steps1[j]);\n          }\n\n          if (k > 0) {\n            acc_inner.smartAutomorph(zMStar.genToPow(dim, g * k));\n          }\n\n          acc[index] += acc_inner;\n        }\n\n        NTL_EXEC_INDEX_END\n\n        for (long i : range(1, cnt))\n          acc[0] += acc[i];\n        ctxt = acc[0];\n      }\n#else\n      if (iterative) {\n\n        std::vector<Ctxt> baby_steps(g, Ctxt(ZeroCtxtLike, ctxt));\n        baby_steps[0] = ctxt;\n        for (long j : range(1, g)) {\n          baby_steps[j] = baby_steps[j - 1];\n          baby_steps[j].smartAutomorph(zMStar.genToPow(dim, 1));\n          baby_steps[j].cleanUp();\n        }\n\n        long h = divc(D, g);\n        Ctxt sum(ZeroCtxtLike, ctxt);\n        Ctxt sum1(ZeroCtxtLike, ctxt);\n        for (long k = h - 1; k >= 0; k--) {\n          if (k < h - 1) {\n            sum.smartAutomorph(zMStar.genToPow(dim, g));\n            sum.cleanUp();\n            sum1.smartAutomorph(zMStar.genToPow(dim, g));\n            sum1.cleanUp();\n          }\n\n          for (long j : range(g)) {\n            long i = j + g * k;\n            if (i >= D)\n              break;\n            MulAdd(sum, cache.multiplier[i], baby_steps[j]);\n            MulAdd(sum1, cache1.multiplier[i], baby_steps[j]);\n          }\n        }\n        sum1.smartAutomorph(zMStar.genToPow(dim, -D));\n        sum += sum1;\n        ctxt = sum;\n      } else {\n        long h = divc(D, g);\n        std::vector<std::shared_ptr<Ctxt>> baby_steps(g);\n        GenBabySteps(baby_steps, ctxt, dim, true);\n\n        NTL::PartitionInfo pinfo(h);\n        long cnt = pinfo.NumIntervals();\n\n        std::vector<Ctxt> acc(cnt, Ctxt(ZeroCtxtLike, ctxt));\n        std::vector<Ctxt> acc1(cnt, Ctxt(ZeroCtxtLike, ctxt));\n\n        // parallel for loop: k in [0..h)\n        NTL_EXEC_INDEX(cnt, index)\n\n        long first, last;\n        pinfo.interval(first, last, index);\n\n        for (long k : range(first, last)) {\n          Ctxt acc_inner(ZeroCtxtLike, ctxt);\n          Ctxt acc_inner1(ZeroCtxtLike, ctxt);\n\n          for (long j : range(g)) {\n            long i = j + g * k;\n            if (i >= D)\n              break;\n            MulAdd(acc_inner, cache.multiplier[i], *baby_steps[j]);\n            MulAdd(acc_inner1, cache1.multiplier[i], *baby_steps[j]);\n          }\n\n          if (k > 0) {\n            acc_inner.smartAutomorph(zMStar.genToPow(dim, g * k));\n            acc_inner1.smartAutomorph(zMStar.genToPow(dim, g * k));\n          }\n\n          acc[index] += acc_inner;\n          acc1[index] += acc_inner1;\n        }\n        NTL_EXEC_INDEX_END\n\n        for (long i : range(1, cnt))\n          acc[0] += acc[i];\n        for (long i : range(1, cnt))\n          acc1[0] += acc1[i];\n\n        acc1[0].smartAutomorph(zMStar.genToPow(dim, -D));\n        acc[0] += acc1[0];\n        ctxt = acc[0];\n      }\n#endif\n    }\n  } else if (!iterative) {\n    if (native) {\n      std::shared_ptr<GeneralAutomorphPrecon> precon =\n          buildGeneralAutomorphPrecon(ctxt, dim, ea);\n\n      NTL::PartitionInfo pinfo(D);\n      long cnt = pinfo.NumIntervals();\n\n      std::vector<Ctxt> acc(cnt, Ctxt(ZeroCtxtLike, ctxt));\n\n      // parallel for loop: i in [0..D)\n      NTL_EXEC_INDEX(cnt, index)\n      long first, last;\n      pinfo.interval(first, last, index);\n\n      for (long i : range(first, last)) {\n        if (cache.multiplier[i]) {\n          std::shared_ptr<Ctxt> tmp = precon->automorph(i);\n          DestMulAdd(acc[index], cache.multiplier[i], *tmp);\n        }\n      }\n      NTL_EXEC_INDEX_END\n\n      ctxt = acc[0];\n      for (long i : range(1, cnt)) {\n        ctxt += acc[i];\n      }\n    } else {\n      std::shared_ptr<GeneralAutomorphPrecon> precon =\n          buildGeneralAutomorphPrecon(ctxt, dim, ea);\n\n      NTL::PartitionInfo pinfo(D);\n      long cnt = pinfo.NumIntervals();\n\n      std::vector<Ctxt> acc(cnt, Ctxt(ZeroCtxtLike, ctxt));\n      std::vector<Ctxt> acc1(cnt, Ctxt(ZeroCtxtLike, ctxt));\n\n      // parallel for loop: i in [0..D)\n      NTL_EXEC_INDEX(cnt, index)\n      long first, last;\n      pinfo.interval(first, last, index);\n\n      for (long i : range(first, last)) {\n        if (cache.multiplier[i] || cache1.multiplier[i]) {\n          std::shared_ptr<Ctxt> tmp = precon->automorph(i);\n          MulAdd(acc[index], cache.multiplier[i], *tmp);\n          DestMulAdd(acc1[index], cache1.multiplier[i], *tmp);\n        }\n      }\n      NTL_EXEC_INDEX_END\n\n      for (long i : range(1, cnt))\n        acc[0] += acc[i];\n      for (long i : range(1, cnt))\n        acc1[0] += acc1[i];\n\n      acc1[0].smartAutomorph(zMStar.genToPow(dim, -D));\n      acc[0] += acc1[0];\n      ctxt = acc[0];\n    }\n  } else /* iterative */ {\n    if (native) {\n      Ctxt acc(ZeroCtxtLike, ctxt);\n      Ctxt sh_ctxt(ctxt);\n\n      for (long i : range(D)) {\n        if (i > 0) {\n          sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n          sh_ctxt.cleanUp();\n        }\n        MulAdd(acc, cache.multiplier[i], sh_ctxt);\n      }\n\n      ctxt = acc;\n    } else {\n      Ctxt acc(ZeroCtxtLike, ctxt);\n      Ctxt acc1(ZeroCtxtLike, ctxt);\n      Ctxt sh_ctxt(ctxt);\n\n      for (long i : range(D)) {\n        if (i > 0) {\n          sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n          sh_ctxt.cleanUp();\n        }\n        MulAdd(acc, cache.multiplier[i], sh_ctxt);\n        MulAdd(acc1, cache1.multiplier[i], sh_ctxt);\n      }\n\n      acc1.smartAutomorph(zMStar.genToPow(dim, -D));\n      acc += acc1;\n      ctxt = acc;\n    }\n  }\n}\n\n// ========================== BlockMatMul1D stuff =====================\n\ntemplate <typename type>\nstruct BlockMatMul1D_derived_impl\n{\n  PA_INJECT(type)\n\n  // return true if zero\n  static bool processDiagonal1(std::vector<RX>& poly,\n                               long i,\n                               const EncryptedArrayDerived<type>& ea,\n                               const BlockMatMul1D_derived<type>& mat)\n  {\n    long dim = mat.getDim();\n    long D = dimSz(ea, dim);\n    long nslots = ea.size();\n    long d = ea.getDegree();\n\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n\n    mat_R entry(NTL::INIT_SIZE, d, d);\n    std::vector<RX> entry1(d);\n    std::vector<std::vector<RX>> tmpDiag(D);\n\n    std::vector<std::vector<RX>> diag(nslots);\n\n    // Process the entries in this diagonal one at a time\n    for (long j : range(D)) { // process entry j\n      bool zEntry =\n          mat.get(entry, mcMod(j - i, D), j, 0); // entry [j-i mod D, j]\n      // get(...) returns true if the entry is empty, false otherwise\n\n      if (!zEntry && IsZero(entry))\n        zEntry = true; // zero is an empty entry too\n      assertTrue(zEntry || (entry.NumRows() == d && entry.NumCols() == d),\n                 \"Non zero entry and number of entry rows and columns \"\n                 \"are not equal to d\");\n\n      if (!zEntry) {   // not a zero entry\n        zDiag = false; // mark diagonal as non-empty\n\n        for (long jj : range(nzLast + 1, j)) { // clear from last nonzero entry\n          tmpDiag[jj].assign(d, RX());\n        }\n        nzLast = j; // current entry is the last nonzero one\n\n        // recode entry as a vector of polynomials\n        for (long k : range(d))\n          conv(entry1[k], entry[k]);\n\n        // compute the linearized polynomial coefficients\n        ea.buildLinPolyCoeffs(tmpDiag[j], entry1);\n      }\n    }\n    if (zDiag)\n      return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj : range(nzLast + 1, D)) {\n      tmpDiag[jj].assign(d, RX());\n    }\n\n    if (D == 1)\n      diag.assign(nslots, tmpDiag[0]); // dimension of size one\n    else {\n      for (long j : range(nslots))\n        diag[j] = tmpDiag[ea.coordinate(dim, j)];\n      // rearrange the indexes based on the current dimension\n    }\n\n    // transpose and encode diag to form polys\n\n    std::vector<RX> slots(nslots);\n    poly.resize(d);\n    for (long i : range(d)) {\n      for (long j : range(nslots))\n        slots[j] = diag[j][i];\n      ea.encode(poly[i], slots);\n    }\n\n    return false; // a nonzero diagonal\n  }\n\n  // return true if zero\n  static bool processDiagonal2(std::vector<RX>& poly,\n                               long idx,\n                               const EncryptedArrayDerived<type>& ea,\n                               const BlockMatMul1D_derived<type>& mat)\n  {\n    long dim = mat.getDim();\n    long D = dimSz(ea, dim);\n    long nslots = ea.size();\n    long d = ea.getDegree();\n\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n\n    mat_R entry(NTL::INIT_SIZE, d, d);\n    std::vector<RX> entry1(d);\n\n    std::vector<std::vector<RX>> diag(nslots);\n\n    // Get the slots in this diagonal one at a time\n    long blockIdx, rowIdx, colIdx;\n    for (long j : range(nslots)) { // process entry j\n      if (dim == ea.dimension()) { // \"special\" last dimension of size 1\n        rowIdx = colIdx = 0;\n        blockIdx = j;\n      } else {\n        std::tie(blockIdx, colIdx) = ea.getPAlgebra().breakIndexByDim(j, dim);\n        rowIdx = mcMod(colIdx - idx, D);\n      }\n      bool zEntry = mat.get(entry, rowIdx, colIdx, blockIdx);\n      // entry [i,j-i mod D] in the block corresponding to blockIdx\n      // get(...) returns true if the entry is empty, false otherwise\n\n      if (!zEntry && IsZero(entry))\n        zEntry = true; // zero is an empty entry too\n      assertTrue(zEntry || (entry.NumRows() == d && entry.NumCols() == d),\n                 \"Non zero entry and number of entry rows and columns \"\n                 \"are not equal to d\");\n\n      if (!zEntry) {   // non-empty entry\n        zDiag = false; // mark diagonal as non-empty\n\n        for (long jj : range(nzLast + 1, j)) // clear from last nonzero entry\n          diag[jj].assign(d, RX());\n\n        nzLast = j; // current entry is the last nonzero one\n\n        // recode entry as a vector of polynomials\n        for (long k : range(d))\n          conv(entry1[k], entry[k]);\n\n        // compute the linearized polynomial coefficients\n        ea.buildLinPolyCoeffs(diag[j], entry1);\n      }\n    }\n    if (zDiag)\n      return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj : range(nzLast + 1, nslots))\n      diag[jj].assign(d, RX());\n\n    // transpose and encode diag to form polys\n\n    std::vector<RX> slots(nslots);\n    poly.resize(d);\n    for (long i : range(d)) {\n      for (long j : range(nslots))\n        slots[j] = diag[j][i];\n      ea.encode(poly[i], slots);\n    }\n\n    return false; // a nonzero diagonal\n  }\n\n  // return true if zero\n  static bool processDiagonal(std::vector<RX>& poly,\n                              long i,\n                              const EncryptedArrayDerived<type>& ea,\n                              const BlockMatMul1D_derived<type>& mat)\n  {\n    if (mat.multipleTransforms())\n      return processDiagonal2(poly, i, ea, mat);\n    else\n      return processDiagonal1(poly, i, ea, mat);\n  }\n};\n\ntemplate <typename type>\nbool BlockMatMul1D_derived<type>::processDiagonal(\n    std::vector<RX>& poly,\n    long i,\n    const EncryptedArrayDerived<type>& ea) const\n{\n  return BlockMatMul1D_derived_impl<type>::processDiagonal(poly, i, ea, *this);\n}\n\n// explicit instantiations\ntemplate bool BlockMatMul1D_derived<PA_GF2>::processDiagonal(\n    std::vector<RX>& poly,\n    long i,\n    const EncryptedArrayDerived<PA_GF2>& ea) const;\n\ntemplate bool BlockMatMul1D_derived<PA_zz_p>::processDiagonal(\n    std::vector<RX>& poly,\n    long i,\n    const EncryptedArrayDerived<PA_zz_p>& ea) const;\n\ntemplate <typename type>\nstruct BlockMatMul1DExec_construct\n{\n  PA_INJECT(type)\n\n  // Basic logic:\n  // We are computing \\sum_i \\sum_j c_{ij} \\sigma^j rot^i(v),\n  // where \\sigma = frobenius, rot = rotation\n  // For good dimensions, rot = \\rho (the basic automorphism),\n  // so we need to compute\n  //     \\sum_i \\sum_j c_{ij} \\sigma^j \\rho^i(v)\n  //  =  \\sum_j \\sigma^j[ \\sigma^{-j}(c_{ij}) \\rho^i(v) ]\n\n  // For bad dimensions, we have\n  //   rot^i(v) = d_i \\rho^i(v) + e_i \\rho^{i-D}(v)\n  // and so we need to compute\n  //   \\sum_i \\sum_j c_{ij} \\sigma^j (d_i \\rho^i(v) + e_i \\rho^{i-D}(v))\n  // =      \\sum_j \\sigma_j[  \\sigma^{-j}(c_{ij}) d_i \\rho^i(v) ] +\n  //   \\rho^{-D}[ \\sum_j \\sigma_j[ \\rho^{D}{\\sigma^{-j}(c_{ij}) e_i} \\rho^i(v) ]\n  //   ]\n\n  // strategy == +1 : factor \\sigma\n  // strategy == -1 : factor \\rho\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    const BlockMatMul1D& mat_basetype,\n                    std::vector<std::shared_ptr<ConstMultiplier>>& vec,\n                    std::vector<std::shared_ptr<ConstMultiplier>>& vec1,\n                    long strategy)\n  {\n    const BlockMatMul1D_partial<type>& mat =\n        dynamic_cast<const BlockMatMul1D_partial<type>&>(mat_basetype);\n\n    long dim = mat.getDim();\n    long D = dimSz(ea, dim);\n    long d = ea.getDegree();\n    bool native = dimNative(ea, dim);\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    std::vector<RX> poly;\n\n    switch (strategy) {\n    case +1: // factor \\sigma\n\n      if (native) {\n        vec.resize(D * d);\n        for (long i : range(D)) {\n          bool zero = mat.processDiagonal(poly, i, ea);\n          if (zero) {\n            for (long j : range(d))\n              vec[i * d + j] = nullptr;\n          } else {\n            for (long j : range(d)) {\n              vec[i * d + j] = build_ConstMultiplier(poly[j], -1, -j, ea);\n            }\n          }\n        }\n      } else {\n        vec.resize(D * d);\n        vec1.resize(D * d);\n        for (long i : range(D)) {\n          bool zero = mat.processDiagonal(poly, i, ea);\n          if (zero) {\n            for (long j : range(d)) {\n              vec[i * d + j] = nullptr;\n              vec1[i * d + j] = nullptr;\n            }\n          } else {\n            const RX& mask = ea.getTab().getMaskTable()[dim][i];\n            const RXModulus& F = ea.getTab().getPhimXMod();\n\n            for (long j : range(d)) {\n              plaintextAutomorph(poly[j], poly[j], -1, -j, ea);\n\n              RX poly1;\n              MulMod(poly1,\n                     poly[j],\n                     mask,\n                     F); // poly[j] w/ first i slots zeroed out\n              vec[i * d + j] = build_ConstMultiplier(poly1);\n\n              sub(poly1,\n                  poly[j],\n                  poly1); // poly[j] w/ last D-i slots zeroed out\n              vec1[i * d + j] = build_ConstMultiplier(poly1, dim, D, ea);\n            }\n          }\n        }\n      }\n      break;\n\n    case -1: // factor \\rho\n\n      if (native) {\n        vec.resize(D * d);\n        for (long i : range(D)) {\n          bool zero = mat.processDiagonal(poly, i, ea);\n          if (zero) {\n            for (long j : range(d))\n              vec[i + j * D] = nullptr;\n          } else {\n            for (long j : range(d)) {\n              vec[i + j * D] = build_ConstMultiplier(poly[j], dim, -i, ea);\n            }\n          }\n        }\n      } else {\n        vec.resize(D * d);\n        vec1.resize(D * d);\n        for (long i : range(D)) {\n          bool zero = mat.processDiagonal(poly, i, ea);\n          if (zero) {\n            for (long j : range(d)) {\n              vec[i + j * D] = nullptr;\n              vec1[i + j * D] = nullptr;\n            }\n          } else {\n            const RX& mask = ea.getTab().getMaskTable()[dim][i];\n            const RXModulus& F = ea.getTab().getPhimXMod();\n\n            for (long j : range(d)) {\n              RX poly1, poly2;\n              MulMod(poly1,\n                     poly[j],\n                     mask,\n                     F); // poly[j] w/ first i slots zeroed out\n              sub(poly2,\n                  poly[j],\n                  poly1); // poly[j] w/ last D-i slots zeroed out\n\n              vec[i + j * D] = build_ConstMultiplier(poly1, dim, -i, ea);\n              vec1[i + j * D] = build_ConstMultiplier(poly2, dim, D - i, ea);\n            }\n          }\n        }\n      }\n\n      break;\n\n    default:\n      throw InvalidArgument(\"Unknown strategy\");\n    }\n  }\n};\n\nBlockMatMul1DExec::BlockMatMul1DExec(const BlockMatMul1D& mat,\n                                     UNUSED bool minimal) :\n    ea(mat.getEA())\n{\n  HELIB_TIMER_START;\n\n  dim = mat.getDim();\n  assertInRange(dim,\n                0l,\n                ea.dimension(),\n                \"Matrix dimension not in [0, ea.dimension()]\",\n                true);\n  D = dimSz(ea, dim);\n  d = ea.getDegree();\n  native = dimNative(ea, dim);\n\n  if (D >= d)\n    strategy = +1;\n  else\n    strategy = -1;\n\n  ea.dispatch<BlockMatMul1DExec_construct>(mat,\n                                           cache.multiplier,\n                                           cache1.multiplier,\n                                           strategy);\n}\n\nvoid BlockMatMul1DExec::mul(Ctxt& ctxt) const\n{\n  HELIB_NTIMER_START(mul_BlockMatMul1DExec);\n  assertEq(&ea.getContext(),\n           &ctxt.getContext(),\n           \"Cannot multiply ciphertexts with context different to \"\n           \"encrypted array one\");\n  const PAlgebra& zMStar = ea.getPAlgebra();\n\n  ctxt.cleanUp();\n\n  if (strategy == 0) {\n    // assumes minimal KS matrices present\n\n    if (native) {\n      Ctxt acc(ZeroCtxtLike, ctxt);\n      Ctxt sh_ctxt(ctxt);\n\n      for (long i : range(D)) {\n        if (i > 0)\n          sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n        Ctxt sh_ctxt1(sh_ctxt);\n\n        for (long j : range(d)) {\n          if (j > 0)\n            sh_ctxt1.smartAutomorph(zMStar.genToPow(-1, 1));\n          MulAdd(acc, cache.multiplier[i * d + j], sh_ctxt1);\n        }\n      }\n\n      ctxt = acc;\n    } else {\n      Ctxt acc(ZeroCtxtLike, ctxt);\n      Ctxt acc1(ZeroCtxtLike, ctxt);\n      Ctxt sh_ctxt(ctxt);\n\n      for (long i : range(D)) {\n        if (i > 0)\n          sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n        Ctxt sh_ctxt1(sh_ctxt);\n\n        for (long j : range(d)) {\n          if (j > 0)\n            sh_ctxt1.smartAutomorph(zMStar.genToPow(-1, 1));\n          MulAdd(acc, cache.multiplier[i * d + j], sh_ctxt1);\n          MulAdd(acc1, cache1.multiplier[i * d + j], sh_ctxt1);\n        }\n      }\n\n      acc1.smartAutomorph(zMStar.genToPow(dim, -D));\n      acc += acc1;\n      ctxt = acc;\n    }\n\n    return;\n  }\n\n  long d0, d1;\n  long dim0, dim1;\n\n  if (strategy == +1) {\n    d0 = D;\n    dim0 = dim;\n    d1 = d;\n    dim1 = -1;\n  } else {\n    d1 = D;\n    dim1 = dim;\n    d0 = d;\n    dim0 = -1;\n  }\n\n  const long par_buf_max = 50;\n\n  bool iterative0 = false;\n  if (ctxt.getPubKey().getKSStrategy(dim0) == HELIB_KSS_MIN)\n    iterative0 = true;\n\n  bool iterative1 = false;\n  if (ctxt.getPubKey().getKSStrategy(dim1) == HELIB_KSS_MIN)\n    iterative1 = true;\n  if (ctxt.getPubKey().getKSStrategy(dim1) != HELIB_KSS_FULL &&\n      NTL::AvailableThreads() == 1)\n    iterative1 = true;\n\n  if (native) {\n\n    std::vector<Ctxt> acc(d1, Ctxt(ZeroCtxtLike, ctxt));\n\n    if (iterative0) {\n      Ctxt sh_ctxt(ctxt);\n\n      for (long i : range(d0)) {\n        if (i > 0) {\n          sh_ctxt.smartAutomorph(zMStar.genToPow(dim0, 1));\n          sh_ctxt.cleanUp();\n        }\n        for (long j : range(d1)) {\n          MulAdd(acc[j], cache.multiplier[i * d1 + j], sh_ctxt);\n        }\n      }\n    } else {\n\n      std::shared_ptr<GeneralAutomorphPrecon> precon =\n          buildGeneralAutomorphPrecon(ctxt, dim0, ea);\n\n      long par_buf_sz = 1;\n      if (NTL::AvailableThreads() > 1)\n        par_buf_sz = std::min(d0, par_buf_max);\n\n      std::vector<std::shared_ptr<Ctxt>> par_buf(par_buf_sz);\n\n      for (long first_i = 0; first_i < d0; first_i += par_buf_sz) {\n        long last_i = std::min(first_i + par_buf_sz, d0);\n\n        // for i in [first_i..last_i), generate automorphism i and store\n        // in par_buf[i-first_i]\n\n        NTL_EXEC_RANGE(last_i - first_i, first, last)\n\n        for (long idx : range(first, last)) {\n          long i = idx + first_i;\n          par_buf[idx] = precon->automorph(i);\n        }\n\n        NTL_EXEC_RANGE_END\n\n        NTL_EXEC_RANGE(d1, first, last)\n\n        for (long j : range(first, last)) {\n          for (long i : range(first_i, last_i)) {\n            MulAdd(acc[j], cache.multiplier[i * d1 + j], *par_buf[i - first_i]);\n          }\n        }\n\n        NTL_EXEC_RANGE_END\n      }\n    }\n\n    if (iterative1) {\n\n      Ctxt sum(acc[d1 - 1]);\n      for (long j = d1 - 2; j >= 0; j--) {\n        sum.smartAutomorph(zMStar.genToPow(dim1, 1));\n        sum.cleanUp();\n        sum += acc[j];\n      }\n\n      ctxt = sum;\n\n    } else {\n\n      NTL::PartitionInfo pinfo(d1);\n      long cnt = pinfo.NumIntervals();\n\n      std::vector<Ctxt> sum(cnt, Ctxt(ZeroCtxtLike, ctxt));\n\n      // for j in [0..d1)\n      NTL_EXEC_INDEX(cnt, index)\n      long first, last;\n      pinfo.interval(first, last, index);\n      for (long j : range(first, last)) {\n        if (j > 0)\n          acc[j].smartAutomorph(zMStar.genToPow(dim1, j));\n        sum[index] += acc[j];\n      }\n      NTL_EXEC_INDEX_END\n\n      ctxt = sum[0];\n      for (long i : range(1, cnt))\n        ctxt += sum[i];\n    }\n  } else {\n\n    std::vector<Ctxt> acc(d1, Ctxt(ZeroCtxtLike, ctxt));\n    std::vector<Ctxt> acc1(d1, Ctxt(ZeroCtxtLike, ctxt));\n\n    if (iterative0) {\n      Ctxt sh_ctxt(ctxt);\n\n      for (long i : range(d0)) {\n        if (i > 0) {\n          sh_ctxt.smartAutomorph(zMStar.genToPow(dim0, 1));\n          sh_ctxt.cleanUp();\n        }\n        for (long j : range(d1)) {\n          MulAdd(acc[j], cache.multiplier[i * d1 + j], sh_ctxt);\n          MulAdd(acc1[j], cache1.multiplier[i * d1 + j], sh_ctxt);\n        }\n      }\n    } else {\n\n      std::shared_ptr<GeneralAutomorphPrecon> precon =\n          buildGeneralAutomorphPrecon(ctxt, dim0, ea);\n\n      long par_buf_sz = 1;\n      if (NTL::AvailableThreads() > 1)\n        par_buf_sz = std::min(d0, par_buf_max);\n\n      std::vector<std::shared_ptr<Ctxt>> par_buf(par_buf_sz);\n\n      for (long first_i = 0; first_i < d0; first_i += par_buf_sz) {\n        long last_i = std::min(first_i + par_buf_sz, d0);\n\n        // for i in [first_i..last_i), generate automorphism i and store\n        // in par_buf[i-first_i]\n\n        NTL_EXEC_RANGE(last_i - first_i, first, last)\n\n        for (long idx : range(first, last)) {\n          long i = idx + first_i;\n          par_buf[idx] = precon->automorph(i);\n        }\n\n        NTL_EXEC_RANGE_END\n\n        NTL_EXEC_RANGE(d1, first, last)\n\n        for (long j : range(first, last)) {\n          for (long i : range(first_i, last_i)) {\n            MulAdd(acc[j], cache.multiplier[i * d1 + j], *par_buf[i - first_i]);\n            MulAdd(acc1[j],\n                   cache1.multiplier[i * d1 + j],\n                   *par_buf[i - first_i]);\n          }\n        }\n\n        NTL_EXEC_RANGE_END\n      }\n    }\n\n    if (iterative1) {\n\n      Ctxt sum(acc[d1 - 1]);\n      Ctxt sum1(acc1[d1 - 1]);\n\n      for (long j = d1 - 2; j >= 0; j--) {\n        sum.smartAutomorph(zMStar.genToPow(dim1, 1));\n        sum.cleanUp();\n        sum += acc[j];\n        sum1.smartAutomorph(zMStar.genToPow(dim1, 1));\n        sum1.cleanUp();\n        sum1 += acc1[j];\n      }\n\n      sum1.smartAutomorph(zMStar.genToPow(dim, -D));\n      ctxt = sum;\n      ctxt += sum1;\n    } else {\n\n      NTL::PartitionInfo pinfo(d1);\n      long cnt = pinfo.NumIntervals();\n\n      std::vector<Ctxt> sum(cnt, Ctxt(ZeroCtxtLike, ctxt));\n      std::vector<Ctxt> sum1(cnt, Ctxt(ZeroCtxtLike, ctxt));\n\n      // for j in [0..d1)\n      NTL_EXEC_INDEX(cnt, index)\n      long first, last;\n      pinfo.interval(first, last, index);\n      for (long j : range(first, last)) {\n        if (j > 0) {\n          acc[j].smartAutomorph(zMStar.genToPow(dim1, j));\n          acc1[j].smartAutomorph(zMStar.genToPow(dim1, j));\n        }\n        sum[index] += acc[j];\n        sum1[index] += acc1[j];\n      }\n      NTL_EXEC_INDEX_END\n\n      for (long i : range(1, cnt))\n        sum[0] += sum[i];\n      for (long i : range(1, cnt))\n        sum1[0] += sum1[i];\n      sum1[0].smartAutomorph(zMStar.genToPow(dim, -D));\n      ctxt = sum[0];\n      ctxt += sum1[0];\n    }\n  }\n}\n\n// ===================== MatMulFull stuff ==================\n\ntemplate <typename type>\nclass MatMulFullHelper : public MatMul1D_partial<type>\n{\npublic:\n  PA_INJECT(type)\n\n  const EncryptedArray& ea_basetype;\n  const MatMulFull_derived<type>& mat;\n  std::vector<long> init_idxes;\n  long dim;\n\n  MatMulFullHelper(const EncryptedArray& _ea_basetype,\n                   const MatMulFull_derived<type>& _mat,\n                   const std::vector<long>& _init_idxes,\n                   long _dim) :\n      ea_basetype(_ea_basetype), mat(_mat), init_idxes(_init_idxes), dim(_dim)\n  {}\n\n  void processDiagonal(RX& epmat,\n                       long offset,\n                       const EncryptedArrayDerived<type>& ea) const override\n  {\n    std::vector<long> idxes;\n    ea.EncryptedArrayBase::rotate1D(idxes, init_idxes, dim, offset);\n\n    std::vector<RX> pmat; // the plaintext diagonal\n    pmat.resize(ea.size());\n    bool zDiag = true; // is this a zero diagonal\n    for (long j : range(ea.size())) {\n      long i = idxes[j];\n      RX val;\n      if (mat.get(val, i, j)) // returns true if the entry is zero\n        clear(pmat[j]);\n      else { // not a zero entry\n        pmat[j] = val;\n        zDiag = false; // not a zero diagonal\n      }\n    }\n    // Now we have the constants for all the diagonal entries, encode the\n    // diagonal as a single polynomial with these constants in the slots\n    if (!zDiag)\n      ea.encode(epmat, pmat);\n    else\n      epmat = 0;\n  }\n\n  const EncryptedArray& getEA() const override { return ea_basetype; }\n  long getDim() const override { return dim; }\n};\n\ntemplate <typename type>\nstruct MatMulFullExec_construct\n{\n  PA_INJECT(type)\n\n  static long rec_mul(long dim,\n                      long idx,\n                      const std::vector<long>& idxes,\n                      std::vector<MatMul1DExec>& transforms,\n                      bool minimal,\n                      const std::vector<long>& dims,\n                      const EncryptedArray& ea_basetype,\n                      const EncryptedArrayDerived<type>& ea,\n                      const MatMulFull_derived<type>& mat)\n  {\n    if (dim >= ea.dimension() - 1) {\n      // Last dimension (recursion edge condition)\n\n      MatMulFullHelper<type> helper(ea_basetype, mat, idxes, dims[dim]);\n      transforms.emplace_back(helper, minimal);\n      idx++;\n      return idx;\n    }\n\n    // not the last dimension, make a recursive call\n    long sdim = ea.sizeOfDimension(dims[dim]);\n\n    // compute \"in spirit\" sum_i (pdata >> i) * i'th-diagonal, but\n    // adjust the indexes so that we only need to rotate the ciphertext\n    // along the different dimensions separately\n    for (long offset : range(sdim)) {\n      std::vector<long> idxes1;\n      ea.EncryptedArrayBase::rotate1D(idxes1, idxes, dims[dim], offset);\n      idx = rec_mul(dim + 1,\n                    idx,\n                    idxes1,\n                    transforms,\n                    minimal,\n                    dims,\n                    ea_basetype,\n                    ea,\n                    mat);\n    }\n\n    return idx;\n  }\n\n  // helper class to sort dimensions, so that\n  //  - small dimensions come before large dimensions\n  //  - we break ties by putting good dimensions before\n  //    bad dimensions...by doing so, we may save on\n  //    some noise if the last dimension is bad (as it gets\n  //    processed by MatMul1D).\n\n  struct MatMulDimComp\n  {\n    const EncryptedArrayDerived<type>* ea;\n    MatMulDimComp(const EncryptedArrayDerived<type>* _ea) : ea(_ea) {}\n\n    bool operator()(long i, long j)\n    {\n      long si = ea->sizeOfDimension(i);\n      bool ni = ea->nativeDimension(i);\n      long sj = ea->sizeOfDimension(j);\n      bool nj = ea->nativeDimension(j);\n\n      return (si < sj) || ((si == sj) && ni && !nj);\n    }\n  };\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    const EncryptedArray& ea_basetype,\n                    const MatMulFull& mat_basetype,\n                    std::vector<MatMul1DExec>& transforms,\n                    bool minimal,\n                    std::vector<long>& dims)\n  {\n    const MatMulFull_derived<type>& mat =\n        dynamic_cast<const MatMulFull_derived<type>&>(mat_basetype);\n\n    long nslots = ea.size();\n    long ndims = ea.dimension();\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    dims.resize(ndims);\n    for (long i : range(ndims))\n      dims[i] = i;\n    sort(dims.begin(), dims.end(), MatMulDimComp(&ea));\n\n    std::vector<long> idxes(nslots);\n    for (long i : range(nslots))\n      idxes[i] = i;\n\n    rec_mul(0, 0, idxes, transforms, minimal, dims, ea_basetype, ea, mat);\n  }\n};\n\nMatMulFullExec::MatMulFullExec(const MatMulFull& mat, bool _minimal) :\n    ea(mat.getEA()), minimal(_minimal)\n{\n  HELIB_NTIMER_START(MatMulFullExec);\n\n  ea.dispatch<MatMulFullExec_construct>(ea, mat, transforms, minimal, dims);\n}\n\nlong MatMulFullExec::rec_mul(Ctxt& acc,\n                             const Ctxt& ctxt,\n                             long dim_idx,\n                             long idx) const\n{\n  if (dim_idx >= ea.dimension() - 1) {\n    // Last dimension (recursion edge condition)\n\n    Ctxt tmp = ctxt;\n    transforms[idx].mul(tmp);\n    acc += tmp;\n\n    idx++;\n\n  } else {\n    long dim = dims[dim_idx];\n    long sdim = ea.sizeOfDimension(dim);\n    bool native = ea.nativeDimension(dim);\n    const PAlgebra& zMStar = ea.getPAlgebra();\n\n    bool iterative = false;\n    if (ctxt.getPubKey().getKSStrategy(dim) == HELIB_KSS_MIN)\n      iterative = true;\n\n    if (!iterative) {\n\n      if (native) {\n        std::shared_ptr<GeneralAutomorphPrecon> precon =\n            buildGeneralAutomorphPrecon(ctxt, dim, ea);\n\n        for (long i : range(sdim)) {\n          std::shared_ptr<Ctxt> tmp = precon->automorph(i);\n          idx = rec_mul(acc, *tmp, dim_idx + 1, idx);\n        }\n      } else {\n        Ctxt ctxt1 = ctxt;\n        ctxt1.smartAutomorph(zMStar.genToPow(dim, -sdim));\n        std::shared_ptr<GeneralAutomorphPrecon> precon =\n            buildGeneralAutomorphPrecon(ctxt, dim, ea);\n        std::shared_ptr<GeneralAutomorphPrecon> precon1 =\n            buildGeneralAutomorphPrecon(ctxt1, dim, ea);\n\n        for (long i : range(sdim)) {\n          if (i == 0)\n            idx = rec_mul(acc, ctxt, dim_idx + 1, idx);\n          else {\n            std::shared_ptr<Ctxt> tmp = precon->automorph(i);\n            std::shared_ptr<Ctxt> tmp1 = precon1->automorph(i);\n\n            zzX mask = ea.getAlMod().getMask_zzX(dim, i);\n            double sz = embeddingLargestCoeff(mask, zMStar);\n\n            DoubleCRT m1(mask,\n                         ea.getContext(),\n                         tmp->getPrimeSet() | tmp1->getPrimeSet());\n\n            // Compute tmp = tmp*m1 + tmp1 - tmp1*m1\n            tmp->multByConstant(m1, sz);\n            *tmp += *tmp1;\n            tmp1->multByConstant(m1, sz);\n            *tmp -= *tmp1;\n\n            idx = rec_mul(acc, *tmp, dim_idx + 1, idx);\n          }\n        }\n      }\n\n    } else {\n\n      if (native) {\n        Ctxt sh_ctxt = ctxt;\n        for (long offset : range(sdim)) {\n          if (offset > 0)\n            sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n          idx = rec_mul(acc, sh_ctxt, dim_idx + 1, idx);\n        }\n      } else {\n        Ctxt sh_ctxt = ctxt;\n        Ctxt sh_ctxt1 = ctxt;\n        sh_ctxt1.smartAutomorph(zMStar.genToPow(dim, -sdim));\n\n        for (long offset : range(sdim)) {\n          if (offset == 0)\n            idx = rec_mul(acc, ctxt, dim_idx + 1, idx);\n          else {\n            sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n            sh_ctxt1.smartAutomorph(zMStar.genToPow(dim, 1));\n\n            zzX mask = ea.getAlMod().getMask_zzX(dim, offset);\n            double sz = embeddingLargestCoeff(mask, zMStar);\n\n            Ctxt tmp = sh_ctxt;\n            Ctxt tmp1 = sh_ctxt1;\n\n            DoubleCRT m1(mask,\n                         ea.getContext(),\n                         tmp.getPrimeSet() | tmp1.getPrimeSet());\n\n            // Compute tmp = tmp*m1 + tmp1 - tmp1*m1\n            tmp.multByConstant(m1, sz);\n            tmp += tmp1;\n            tmp1.multByConstant(m1, sz);\n            tmp -= tmp1;\n\n            idx = rec_mul(acc, tmp, dim_idx + 1, idx);\n          }\n        }\n      }\n    }\n  }\n\n  return idx;\n}\n\nvoid MatMulFullExec::mul(Ctxt& ctxt) const\n{\n  HELIB_NTIMER_START(mul_MatMulFullExec);\n  assertEq(&ea.getContext(),\n           &ctxt.getContext(),\n           \"Cannot multiply ciphertexts with context different to \"\n           \"encrypted array one\");\n\n  assertTrue(ea.size() > 1l, \"Number of slots is less than 2\");\n  // FIXME: right now, the code does not work if ea.size() == 1\n  // (which means that # dimensions == 0).  This is a corner case\n  // that is hardly worth dealing with (although we could).\n\n  ctxt.cleanUp();\n\n  Ctxt acc(ZeroCtxtLike, ctxt);\n  rec_mul(acc, ctxt, 0, 0);\n\n  ctxt = acc;\n}\n\n// ================= BlockMatMulFull stuff ===============\n\n// lightly massaged version of MatMulFull code...some unfortunate\n// code duplication here\n\ntemplate <typename type>\nclass BlockMatMulFullHelper : public BlockMatMul1D_partial<type>\n{\npublic:\n  PA_INJECT(type)\n\n  const EncryptedArray& ea_basetype;\n  const BlockMatMulFull_derived<type>& mat;\n  std::vector<long> init_idxes;\n  long dim;\n\n  BlockMatMulFullHelper(const EncryptedArray& _ea_basetype,\n                        const BlockMatMulFull_derived<type>& _mat,\n                        const std::vector<long>& _init_idxes,\n                        long _dim) :\n      ea_basetype(_ea_basetype), mat(_mat), init_idxes(_init_idxes), dim(_dim)\n  {}\n\n  bool processDiagonal(std::vector<RX>& poly,\n                       long offset,\n                       const EncryptedArrayDerived<type>& ea) const override\n  {\n    std::vector<long> idxes;\n    ea.EncryptedArrayBase::rotate1D(idxes, init_idxes, dim, offset);\n\n    long d = ea.getDegree();\n    long nslots = ea.size();\n    bool zDiag = true; // is this a zero diagonal?\n    long nzLast = -1;  // index of last non-zero entry\n\n    mat_R entry(NTL::INIT_SIZE, d, d);\n    std::vector<RX> entry1(d);\n\n    std::vector<std::vector<RX>> diag(nslots);\n\n    for (long j : range(nslots)) {\n      long i = idxes[j];\n      bool zEntry = mat.get(entry, i, j);\n\n      // the remainder is copied and pasted from the processDiagonal2 logic\n      // for BlockMatMul1D....FIXME: code duplication\n\n      if (!zEntry && IsZero(entry))\n        zEntry = true; // zero is an empty entry too\n      assertTrue(zEntry || (entry.NumRows() == d && entry.NumCols() == d),\n                 \"Non zero entry and number of entry rows and columns \"\n                 \"are not equal to d\");\n\n      if (!zEntry) {   // non-empty entry\n        zDiag = false; // mark diagonal as non-empty\n\n        for (long jj : range(nzLast + 1, j)) // clear from last nonzero entry\n          diag[jj].assign(d, RX());\n\n        nzLast = j; // current entry is the last nonzero one\n\n        // recode entry as a vector of polynomials\n        for (long k : range(d))\n          conv(entry1[k], entry[k]);\n\n        // compute the linearized polynomial coefficients\n        ea.buildLinPolyCoeffs(diag[j], entry1);\n      }\n    }\n    if (zDiag)\n      return true; // zero diagonal, nothing to do\n\n    // clear trailing zero entries\n    for (long jj : range(nzLast + 1, nslots))\n      diag[jj].assign(d, RX());\n\n    // transpose and encode diag to form polys\n\n    std::vector<RX> slots(nslots);\n    poly.resize(d);\n    for (long i : range(d)) {\n      for (long j : range(nslots))\n        slots[j] = diag[j][i];\n      ea.encode(poly[i], slots);\n    }\n\n    return false; // a nonzero diagonal\n  }\n\n  const EncryptedArray& getEA() const override { return ea_basetype; }\n  long getDim() const override { return dim; }\n};\n\ntemplate <typename type>\nstruct BlockMatMulFullExec_construct\n{\n  PA_INJECT(type)\n\n  static long rec_mul(long dim,\n                      long idx,\n                      const std::vector<long>& idxes,\n                      std::vector<BlockMatMul1DExec>& transforms,\n                      bool minimal,\n                      const std::vector<long>& dims,\n                      const EncryptedArray& ea_basetype,\n                      const EncryptedArrayDerived<type>& ea,\n                      const BlockMatMulFull_derived<type>& mat)\n  {\n    if (dim >= ea.dimension() - 1) {\n      // Last dimension (recursion edge condition)\n\n      BlockMatMulFullHelper<type> helper(ea_basetype, mat, idxes, dims[dim]);\n      transforms.emplace_back(helper, minimal);\n      idx++;\n      return idx;\n    }\n\n    // not the last dimension, make a recursive call\n    long sdim = ea.sizeOfDimension(dims[dim]);\n\n    // compute \"in spirit\" sum_i (pdata >> i) * i'th-diagonal, but\n    // adjust the indexes so that we only need to rotate the ciphertext\n    // along the different dimensions separately\n    for (long offset : range(sdim)) {\n      std::vector<long> idxes1;\n      ea.EncryptedArrayBase::rotate1D(idxes1, idxes, dims[dim], offset);\n      idx = rec_mul(dim + 1,\n                    idx,\n                    idxes1,\n                    transforms,\n                    minimal,\n                    dims,\n                    ea_basetype,\n                    ea,\n                    mat);\n    }\n\n    return idx;\n  }\n\n  // helper class to sort dimensions, so that\n  //  - small dimensions come before large dimensions\n  //  - we break ties by putting good dimensions before\n  //    bad dimensions...by doing so, we may save on\n  //    some noise if the last dimension is bad (as it gets\n  //    processed by BlockMatMul1D).\n\n  struct BlockMatMulDimComp\n  {\n    const EncryptedArrayDerived<type>* ea;\n    BlockMatMulDimComp(const EncryptedArrayDerived<type>* _ea) : ea(_ea) {}\n\n    bool operator()(long i, long j)\n    {\n      long si = ea->sizeOfDimension(i);\n      bool ni = ea->nativeDimension(i);\n      long sj = ea->sizeOfDimension(j);\n      bool nj = ea->nativeDimension(j);\n\n      return (si < sj) || ((si == sj) && ni && !nj);\n    }\n  };\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    const EncryptedArray& ea_basetype,\n                    const BlockMatMulFull& mat_basetype,\n                    std::vector<BlockMatMul1DExec>& transforms,\n                    bool minimal,\n                    std::vector<long>& dims)\n  {\n    const BlockMatMulFull_derived<type>& mat =\n        dynamic_cast<const BlockMatMulFull_derived<type>&>(mat_basetype);\n\n    long nslots = ea.size();\n    long ndims = ea.dimension();\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    dims.resize(ndims);\n    for (long i : range(ndims))\n      dims[i] = i;\n    sort(dims.begin(), dims.end(), BlockMatMulDimComp(&ea));\n\n    std::vector<long> idxes(nslots);\n    for (long i : range(nslots))\n      idxes[i] = i;\n\n    rec_mul(0, 0, idxes, transforms, minimal, dims, ea_basetype, ea, mat);\n  }\n};\n\nBlockMatMulFullExec::BlockMatMulFullExec(const BlockMatMulFull& mat,\n                                         bool _minimal) :\n    ea(mat.getEA()), minimal(_minimal)\n{\n  HELIB_NTIMER_START(BlockMatMulFullExec);\n\n  ea.dispatch<BlockMatMulFullExec_construct>(ea,\n                                             mat,\n                                             transforms,\n                                             minimal,\n                                             dims);\n}\n\nlong BlockMatMulFullExec::rec_mul(Ctxt& acc,\n                                  const Ctxt& ctxt,\n                                  long dim_idx,\n                                  long idx) const\n{\n  if (dim_idx >= ea.dimension() - 1) {\n    // Last dimension (recursion edge condition)\n\n    Ctxt tmp = ctxt;\n    transforms[idx].mul(tmp);\n    acc += tmp;\n\n    idx++;\n\n  } else {\n    long dim = dims[dim_idx];\n    long sdim = ea.sizeOfDimension(dim);\n    bool native = ea.nativeDimension(dim);\n    const PAlgebra& zMStar = ea.getPAlgebra();\n\n    bool iterative = false;\n    if (ctxt.getPubKey().getKSStrategy(dim) == HELIB_KSS_MIN)\n      iterative = true;\n\n    if (!iterative) {\n\n      if (native) {\n        std::shared_ptr<GeneralAutomorphPrecon> precon =\n            buildGeneralAutomorphPrecon(ctxt, dim, ea);\n\n        for (long i : range(sdim)) {\n          std::shared_ptr<Ctxt> tmp = precon->automorph(i);\n          idx = rec_mul(acc, *tmp, dim_idx + 1, idx);\n        }\n      } else {\n        Ctxt ctxt1 = ctxt;\n        ctxt1.smartAutomorph(zMStar.genToPow(dim, -sdim));\n        std::shared_ptr<GeneralAutomorphPrecon> precon =\n            buildGeneralAutomorphPrecon(ctxt, dim, ea);\n        std::shared_ptr<GeneralAutomorphPrecon> precon1 =\n            buildGeneralAutomorphPrecon(ctxt1, dim, ea);\n\n        for (long i : range(sdim)) {\n          if (i == 0)\n            idx = rec_mul(acc, ctxt, dim_idx + 1, idx);\n          else {\n            std::shared_ptr<Ctxt> tmp = precon->automorph(i);\n            std::shared_ptr<Ctxt> tmp1 = precon1->automorph(i);\n\n            zzX mask = ea.getAlMod().getMask_zzX(dim, i);\n            double sz = embeddingLargestCoeff(mask, zMStar);\n\n            DoubleCRT m1(mask,\n                         ea.getContext(),\n                         tmp->getPrimeSet() | tmp1->getPrimeSet());\n\n            // Compute tmp = tmp*m1 + tmp1 - tmp1*m1\n            tmp->multByConstant(m1, sz);\n            *tmp += *tmp1;\n            tmp1->multByConstant(m1, sz);\n            *tmp -= *tmp1;\n\n            idx = rec_mul(acc, *tmp, dim_idx + 1, idx);\n          }\n        }\n      }\n\n    } else {\n\n      if (native) {\n        Ctxt sh_ctxt = ctxt;\n        for (long offset : range(sdim)) {\n          if (offset > 0)\n            sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n          idx = rec_mul(acc, sh_ctxt, dim_idx + 1, idx);\n        }\n      } else {\n        Ctxt sh_ctxt = ctxt;\n        Ctxt sh_ctxt1 = ctxt;\n        sh_ctxt1.smartAutomorph(zMStar.genToPow(dim, -sdim));\n\n        for (long offset : range(sdim)) {\n          if (offset == 0)\n            idx = rec_mul(acc, ctxt, dim_idx + 1, idx);\n          else {\n            sh_ctxt.smartAutomorph(zMStar.genToPow(dim, 1));\n            sh_ctxt1.smartAutomorph(zMStar.genToPow(dim, 1));\n\n            zzX mask = ea.getAlMod().getMask_zzX(dim, offset);\n            double sz = embeddingLargestCoeff(mask, zMStar);\n\n            Ctxt tmp = sh_ctxt;\n            Ctxt tmp1 = sh_ctxt1;\n\n            DoubleCRT m1(mask,\n                         ea.getContext(),\n                         tmp.getPrimeSet() | tmp1.getPrimeSet());\n\n            // Compute tmp = tmp*m1 + tmp1 - tmp1*m1\n            tmp.multByConstant(m1, sz);\n            tmp += tmp1;\n            tmp1.multByConstant(m1, sz);\n            tmp -= tmp1;\n\n            idx = rec_mul(acc, tmp, dim_idx + 1, idx);\n          }\n        }\n      }\n    }\n  }\n\n  return idx;\n}\n\nvoid BlockMatMulFullExec::mul(Ctxt& ctxt) const\n{\n  HELIB_NTIMER_START(mul_BlockMatMulFullExec);\n  assertEq(&ea.getContext(),\n           &ctxt.getContext(),\n           \"Cannot multiply ciphertexts with context different to \"\n           \"encrypted array one\");\n\n  assertTrue(ea.size() > 1l, \"Number of slots is less than 2\");\n  // FIXME: right now, the code does not work if ea.size() == 1\n  // (which means that # dimensions == 0).  This is a corner case\n  // that is hardly worth dealing with (although we could).\n\n  ctxt.cleanUp();\n\n  Ctxt acc(ZeroCtxtLike, ctxt);\n  rec_mul(acc, ctxt, 0, 0);\n\n  ctxt = acc;\n}\n\n// ================= plaintext mul stuff stuff ===============\n\ntemplate <typename type>\nstruct mul_MatMul1D_impl\n{\n  PA_INJECT(type)\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    PlaintextArray& pa,\n                    const MatMul1D& mat_basetype)\n  {\n    const MatMul1D_derived<type>& mat =\n        dynamic_cast<const MatMul1D_derived<type>&>(mat_basetype);\n    long dim = mat.getDim();\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    long n = ea.size();\n    long D = ea.sizeOfDimension(dim);\n\n    std::vector<std::vector<RX>> data1(n / D);\n    for (long k : range(n / D))\n      data1[k].resize(D);\n\n    // copy the data into a vector of 1D vectors\n    std::vector<RX>& data = pa.getData<type>();\n    for (long i : range(n)) {\n      long k, j;\n      std::tie(k, j) = ea.getContext().zMStar.breakIndexByDim(i, dim);\n      data1[k][j] = data[i]; // k= along dim, j = the rest of i\n    }\n\n    // multiply each one of the vectors by the same matrix\n    for (long k : range(n / D)) {\n      for (long j : range(D)) { // simple matrix-vector multiplication\n        std::pair<long, long> p(k, j);\n        long idx = ea.getContext().zMStar.assembleIndexByDim(p, dim);\n\n        RX acc, val, tmp;\n        acc = 0;\n        for (long i : range(D)) {\n          bool zero = mat.get(val, i, j, k);\n          if (!zero) {\n            NTL::mul(tmp, data1[k][i], val);\n            NTL::add(acc, acc, tmp);\n          }\n        }\n        rem(data[idx], acc, ea.getG()); // store the result in the data array\n      }\n    }\n  }\n};\n\nvoid mul(PlaintextArray& pa, const MatMul1D& mat)\n{\n  const EncryptedArray& ea = mat.getEA();\n  ea.dispatch<mul_MatMul1D_impl>(pa, mat);\n}\n\ntemplate <typename type>\nstruct mul_BlockMatMul1D_impl\n{\n  PA_INJECT(type)\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    PlaintextArray& pa,\n                    const BlockMatMul1D& mat_basetype)\n  {\n    const BlockMatMul1D_derived<type>& mat =\n        dynamic_cast<const BlockMatMul1D_derived<type>&>(mat_basetype);\n    const PAlgebra& zMStar = ea.getPAlgebra();\n    long dim = mat.getDim();\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    long n = ea.size();\n    long D = ea.sizeOfDimension(dim);\n    long d = ea.getDegree();\n\n    std::vector<std::vector<RX>> data1(n / D);\n    for (long k : range(n / D))\n      data1[k].resize(D);\n\n    // copy the data into a vector of 1D vectors\n    std::vector<RX>& data = pa.getData<type>();\n    for (long i : range(n)) {\n      long k, j;\n      std::tie(k, j) = zMStar.breakIndexByDim(i, dim);\n      data1[k][j] = data[i]; // k= along dim, j = the rest of i\n    }\n\n    for (long k : range(n / D)) { // multiply each vector by a matrix\n      for (long j : range(D)) {   // matrix-vector multiplication\n        vec_R acc, tmp, tmp1;\n        mat_R val;\n        acc.SetLength(d);\n        for (long i = 0; i < D; i++) {\n          bool zero = mat.get(val, i, j, k);\n          if (!zero) { // if non-zero, multiply and add\n            VectorCopy(tmp1, data1[k][i], d);\n            mul(tmp, tmp1, val);\n            add(acc, acc, tmp);\n          }\n        }\n        long idx = zMStar.assembleIndexByDim(std::make_pair(k, j), dim);\n        conv(data[idx], acc);\n      }\n    }\n  }\n};\n\nvoid mul(PlaintextArray& pa, const BlockMatMul1D& mat)\n{\n  const EncryptedArray& ea = mat.getEA();\n  ea.dispatch<mul_BlockMatMul1D_impl>(pa, mat);\n}\n\ntemplate <typename type>\nstruct mul_MatMulFull_impl\n{\n  PA_INJECT(type)\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    PlaintextArray& pa,\n                    const MatMulFull& mat_basetype)\n  {\n    const MatMulFull_derived<type>& mat =\n        dynamic_cast<const MatMulFull_derived<type>&>(mat_basetype);\n    long n = ea.size();\n    const RX& G = ea.getG();\n    std::vector<RX>& data = pa.getData<type>();\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    std::vector<RX> res;\n    res.resize(n);\n    for (long j : range(n)) {\n      RX acc, val, tmp;\n      acc = 0;\n      for (long i : range(n)) {\n        if (!mat.get(val, i, j)) {\n          mul(tmp, data[i], val);\n          add(acc, acc, tmp);\n        }\n      }\n      rem(acc, acc, G);\n      res[j] = acc;\n    }\n\n    data = res;\n  }\n};\n\nvoid mul(PlaintextArray& pa, const MatMulFull& mat)\n{\n  const EncryptedArray& ea = mat.getEA();\n  ea.dispatch<mul_MatMulFull_impl>(pa, mat);\n}\n\ntemplate <typename type>\nstruct mul_BlockMatMulFull_impl\n{\n  PA_INJECT(type)\n\n  static void apply(const EncryptedArrayDerived<type>& ea,\n                    PlaintextArray& pa,\n                    const BlockMatMulFull& mat_basetype)\n  {\n    const BlockMatMulFull_derived<type>& mat =\n        dynamic_cast<const BlockMatMulFull_derived<type>&>(mat_basetype);\n    long n = ea.size();\n    long d = ea.getDegree();\n    std::vector<RX>& data = pa.getData<type>();\n\n    RBak bak;\n    bak.save();\n    ea.getTab().restoreContext();\n\n    std::vector<RX> res;\n    res.resize(n);\n    for (long j : range(n)) {\n      vec_R acc, tmp, tmp1;\n      mat_R val;\n      acc.SetLength(d);\n      for (long i : range(n)) {\n        if (!mat.get(val, i, j)) {\n          VectorCopy(tmp1, data[i], d);\n          mul(tmp, tmp1, val);\n          add(acc, acc, tmp);\n        }\n      }\n      conv(res[j], acc);\n    }\n\n    data = res;\n  }\n};\n\nvoid mul(PlaintextArray& pa, const BlockMatMulFull& mat)\n{\n  const EncryptedArray& ea = mat.getEA();\n  ea.dispatch<mul_BlockMatMulFull_impl>(pa, mat);\n}\n\n//================= traceMap ====================\n\n#define HELIB_TRACE_THRESH (50)\n// This should probably just be the same as HELIB_KEYSWITCH_THRESH,\n// but it can be adjusted.\n\nvoid traceMap(Ctxt& ctxt)\n{\n  const Context& context = ctxt.getContext();\n  const PAlgebra& zMStar = context.zMStar;\n  long d = context.zMStar.getOrdP();\n\n  if (d == 1)\n    return;\n\n  Ctxt orig = ctxt;\n\n  long strategy = ctxt.getPubKey().getKSStrategy(-1);\n\n  if (strategy == HELIB_KSS_FULL && d <= HELIB_TRACE_THRESH) {\n    BasicAutomorphPrecon precon(ctxt);\n    Ctxt acc(ctxt);\n\n    for (long i : range(1, d)) {\n      std::shared_ptr<Ctxt> tmp = precon.automorph(zMStar.genToPow(-1, i));\n      acc += *tmp;\n    }\n\n    ctxt = acc;\n  } else if (strategy == HELIB_KSS_MIN) {\n    if (d <= HELIB_KEYSWITCH_MIN_THRESH) {\n      // simple iterative procedure\n\n      Ctxt acc(ctxt);\n      for (long i = 1; i < d; ++i) {\n        acc.frobeniusAutomorph(1);\n        acc += ctxt;\n      }\n      ctxt = acc;\n    } else {\n      long g = KSGiantStepSize(d);\n      long q = d / g;\n      long r = d - g * q; // d = g*q + r\n\n      if (r == 0) {\n        // baby step / giant step w/ no remainder\n\n        // compute baby_sum = sum_{i=0}^{g-1} \\sigma^i(ctxt)\n        Ctxt baby_sum(ctxt);\n        for (long i = 1; i < g; ++i) {\n          baby_sum.frobeniusAutomorph(1);\n          baby_sum += ctxt;\n        }\n\n        Ctxt acc(baby_sum);\n        for (long i = 1; i < q; ++i) {\n          acc.frobeniusAutomorph(g);\n          acc += baby_sum;\n        }\n\n        ctxt = acc;\n      } else {\n        // baby step / giant step w/ remainder\n\n        // compute baby_sum = sum_{i=0}^{g-1} \\sigma^i(ctxt)\n        //   and store rem_sum = sum_{i=0}^{r-1} \\sigma^i(ctxt)\n        Ctxt baby_sum(ctxt);\n        Ctxt rem_sum(ZeroCtxtLike, ctxt);\n        for (long i : range(1, g)) {\n          if (i == r)\n            rem_sum = baby_sum;\n          baby_sum.frobeniusAutomorph(1);\n          baby_sum += ctxt;\n        }\n\n        Ctxt acc(rem_sum);\n        for (long i = 0; i < q; ++i) {\n          acc.frobeniusAutomorph(g);\n          acc += baby_sum;\n        }\n\n        ctxt = acc;\n      }\n    }\n  } else {\n\n    long k = NTL::NumBits(d);\n    long e = 1;\n\n    for (long i = k - 2; i >= 0; i--) {\n      Ctxt tmp1 = ctxt;\n      tmp1.frobeniusAutomorph(e);\n      ctxt += tmp1;\n      e = 2 * e;\n\n      if (NTL::bit(d, i)) {\n        ctxt.frobeniusAutomorph(1);\n        ctxt += orig;\n        e += 1;\n      }\n    }\n  }\n}\n\n} // namespace helib\n", "meta": {"hexsha": "f5365e5a1d254d1e458b6f155e4a1fa16da48e32", "size": 82780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matmul.cpp", "max_stars_repo_name": "andrey-mindrin/HElib", "max_stars_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "src/matmul.cpp", "max_issues_repo_name": "felipeturing/HElib", "max_issues_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 226.0, "max_issues_repo_issues_event_min_datetime": "2015-01-13T08:07:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T09:26:24.000Z", "max_forks_repo_path": "src/matmul.cpp", "max_forks_repo_name": "felipeturing/HElib", "max_forks_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 402.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T04:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T00:50:34.000Z", "avg_line_length": 28.2622055309, "max_line_length": 80, "alphanum_fraction": 0.5582024644, "num_tokens": 22901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.04813676684935012, "lm_q1q2_score": 0.020890464588204708}}
{"text": "#pragma once\n\n#include <fftw3.h>\n#include <boost/assert.hpp>\n#include <iomanip>\n#include <iostream>\n#include <mutex>\n#include <stdexcept>\n#include <tuple>\n#include <unordered_map>\n\n// own includes\n// ----------------------------------------------------------------------\n#include \"base/hash_specializations.hpp\"\n#include \"base/types.hpp\"\n\n\n/**\n * @brief Handler to manage FFTW plans for real2complex transforms. Before use,\n *        `create_and_get_plan` must be invoked for all sizes / directions\n * required\n *        later. After it was initialized, plans can be queried weith get_plan\n * (thread-safe).\n *\n */\nclass PlannerR2C\n{\n public:\n  enum DIR\n  {\n    FWD,\n    INV\n  };\n\n private:\n  /// tuple types are: (n0, n1, flags, dir, fft type)\n  typedef std::tuple<int, int, unsigned int, int, int> key_t;\n\n public:\n  /**\n    * @brief Returns plan (if not already present, it is created, which requires\n   * to lock a\n    * mutex). This method is thread-safe. WARNING: overhead due to malloc for\n   * in, out arrays.\n    *\n    * @param n\n    * @param flags\n    * @param dir\n    *\n    * @return\n    */\n  fftw_plan create_and_get_plan(int n0, int n1, DIR dir, enum ft_type type = ft_type::R2C);\n\n  /**\n   * @brief Returns a plan if available and null otherwise. This method is\n   * thread-safe.\n   *\n   * @param n\n   * @param flags\n   * @param dir\n   *\n   * @return\n   */\n  fftw_plan get_plan(int n[2], DIR dir, enum ft_type type = ft_type::R2C) const;\n\n  /**\n   * @brief set fftw flags /\n   *\n   * @param flags\n   */\n  void set_flags(unsigned int flags)\n  {\n    if (flags != flags_) plans_.clear();\n    flags_ = flags;\n  }\n\n  virtual ~PlannerR2C()\n  {\n    for (auto &v : plans_) {\n      fftw_destroy_plan(v.second);\n    }\n  }\n\n  void print(std::ostream &out = std::cout) const;\n\n protected:\n  unsigned int flags_ = FFTW_ESTIMATE;\n  std::unordered_map<key_t, fftw_plan> plans_;\n  std::mutex mutex_;\n};\n\n// -------------------------------------------------------------------------------------\ninline fftw_plan\nPlannerR2C::create_and_get_plan(int n0, int n1, DIR dir, enum ft_type type)\n{\n  // the only thread safe routine in fftw is fftw_execute, thus we need a lock\n  // here\n  std::lock_guard<std::mutex> lock(mutex_);\n\n  // const int n0 = n[0];\n  // const int n1 = n[1];\n  int n[2] = {n0, n1};\n  int embed[2] = {n0, n1};\n  key_t key = std::make_tuple(n0, n1, flags_, int(dir), int(type));\n  auto it = plans_.find(key);\n\n  BOOST_ASSERT_MSG((dir == FWD) || (dir == INV), \"invalid direction flag\");\n\n  if (it != plans_.end()) {\n    return it->second;\n  } else {\n    if (type == ft_type::R2C) {\n      if (dir == FWD) {\n        fftw_complex *out = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n[0] * n[1]);\n        double *in = (double *)fftw_malloc(sizeof(double) * n[0] * n[1]);\n        fftw_plan fwd_plan = fftw_plan_many_dft_r2c(2 /* rank */,\n                                                    n /* dims */,\n                                                    1 /* num dfts */,\n                                                    in,\n                                                    embed,\n                                                    1 /* stride */,\n                                                    embed[0] * embed[1],\n                                                    out,\n                                                    embed,\n                                                    1 /*stride */,\n                                                    embed[0] * embed[1],\n                                                    flags_);\n        fftw_free(out);\n        fftw_free(in);\n        BOOST_ASSERT_MSG(fwd_plan != NULL, \"FFTW failed to create plan\");\n        plans_[key] = fwd_plan;\n        return fwd_plan;\n\n      } else if (dir == INV) {\n        fftw_complex *out = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n[0] * n[1]);\n        double *in = (double *)fftw_malloc(sizeof(double) * n[0] * n[1]);\n        fftw_plan inv_plan = fftw_plan_many_dft_c2r(2 /* rank */,\n                                                    n /* dims */,\n                                                    1 /* num dfts */,\n                                                    out,\n                                                    embed,\n                                                    1 /* stride */,\n                                                    embed[0] * embed[1],\n                                                    in,\n                                                    embed,\n                                                    1 /*stride */,\n                                                    embed[0] * embed[1],\n                                                    flags_);\n        fftw_free(out);\n        fftw_free(in);\n        BOOST_ASSERT_MSG(inv_plan != NULL, \"FFTW failed to create plan\");\n        plans_[key] = inv_plan;\n        return inv_plan;\n      }\n    } else if (type == ft_type::C2C) {\n      if (dir == FWD) {\n        fftw_complex *out = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n[0] * n[1]);\n        fftw_complex *in = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n[0] * n[1]);\n        fftw_plan fwd_plan = fftw_plan_dft_2d(n0, n1, in, out, FFTW_FORWARD, flags_);\n        fftw_free(out);\n        fftw_free(in);\n        BOOST_ASSERT_MSG(fwd_plan != NULL, \"FFTW failed to create plan\");\n        plans_[key] = fwd_plan;\n        return fwd_plan;\n      } else if (dir == INV) {\n        fftw_complex *out = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n[0] * n[1]);\n        fftw_complex *in = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n[0] * n[1]);\n        fftw_plan inv_plan = fftw_plan_dft_2d(n0, n1, in, out, FFTW_BACKWARD, flags_);\n        fftw_free(out);\n        fftw_free(in);\n        BOOST_ASSERT_MSG(inv_plan != NULL, \"FFTW failed to create plan\");\n        plans_[key] = inv_plan;\n        return inv_plan;\n      }\n    } else {\n      throw std::runtime_error(\"unknown fft type\");\n    }\n  }\n}\n\n// --------------------------------------------------------------------------------\ninline fftw_plan\nPlannerR2C::get_plan(int n[2], DIR dir, enum ft_type type) const\n{\n  auto it = plans_.find(std::make_tuple(n[0], n[1], flags_, int(dir), int(type)));\n  if (it != plans_.end())\n    return it->second;\n  else\n    return NULL;\n}\n\n// --------------------------------------------------------------------------------\ninline void\nPlannerR2C::print(std::ostream &out) const\n{\n  for (auto it = plans_.begin(); it != plans_.end(); ++it) {\n    auto key = it->first;\n    int nx = std::get<0>(key);\n    int ny = std::get<1>(key);\n    unsigned int flags = std::get<2>(key);\n    int dir = std::get<3>(key);\n    int type = std::get<4>(key);\n\n    std::map<int, std::string> flag2names;\n    std::map<int, std::string> type2names;\n\n    flag2names[FFTW_ESTIMATE] = \"FFTW_ESTIMATE\";\n    flag2names[FFTW_MEASURE] = \"FFTW_MEASURE\";\n    flag2names[FFTW_ESTIMATE_PATIENT] = \"FFTW_ESTIMATE_PATIENT\";\n    flag2names[FFTW_EXHAUSTIVE] = \"FFTW_EXHAUSTIVE\";\n\n    type2names[int(ft_type::C2C)] = \"C2C\";\n    type2names[int(ft_type::R2C)] = \"R2C\";\n\n    if (dir == FWD)\n      out << \"FWD: \" << type2names[type] << \" \" << std::setw(10) << nx << \" \" << std::setw(10) << ny\n          << \": \" << flag2names.at(flags) << std::endl;\n    else if (dir == INV)\n      out << \"INV: \" << type2names[type] << \" \" << std::setw(10) << nx << \" \" << std::setw(10) << ny\n          << \": \" << flag2names.at(flags) << std::endl;\n    else\n      out << \"FFTW PLANNER: DIR NOT FOUND!\\n\";\n  }\n}\n\n// =====================================================================================\n// =====================================================================================\n// =====================================================================================\n/**\n * @brief Creates plans upon request. Every call to get_plan invovles obtaining\n * a lock.\n *        This class and all it's methods are thread-safe.\n *\n */\nclass PlannerR2COD : public PlannerR2C\n{\n public:\n  /**\n   * @brief WARNING: overhead due to malloc for in, out arrays.\n   *\n   * @param n   [nx, ny]\n   * @param dir cf. PlannerR2C::DIR\n   *\n   * @return fftw_plan\n   */\n  fftw_plan get_plan(int n[2], DIR dir, enum ft_type type = ft_type::R2C)\n  {\n    return PlannerR2C::create_and_get_plan(n[0], n[1], dir, type);\n  }\n\n  fftw_plan get_plan(int n[2], DIR dir, enum ft_type type = ft_type::R2C) const = delete;\n};\n", "meta": {"hexsha": "8b193de1fdc27d15a58c21da2b297ba8dca4fb15", "size": 8403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fft/planner.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "fft/planner.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft/planner.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": 33.2134387352, "max_line_length": 100, "alphanum_fraction": 0.480185648, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.05582314427619164, "lm_q1q2_score": 0.020870923995964276}}
{"text": "\n// nothing to do with ATLAS bindings ;o) \n// various initializations from `utils.h' \n\n#include <iostream>\n#include <complex> \n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include \"utils.h\"\n\n#ifndef F_FLOAT\ntypedef double real_t;\n#else\ntypedef float real_t;\n#endif \n\n#ifndef F_COMPLEX\ntypedef real_t elem_t;\n#else\ntypedef std::complex<real_t> elem_t;\n#endif \n\ntypedef boost::numeric::ublas::vector<elem_t> vct_t; \n#ifdef F_ROW_MAJOR\ntypedef boost::numeric::ublas::matrix<elem_t> matr_t; \n#else\ntypedef boost::numeric::ublas::matrix<\n  elem_t,\n  boost::numeric::ublas::column_major\n> matr_t; \n#endif \n\nint main() {\n  std::cout << std::endl; \n\n  vct_t v (10); \n\n  // v[i] = i || (i, 0)\n  init_v<ident> (v); \n  print_v (v); \n  std::cout << std::endl; \n\n  // v[i] = i+1 || (i+1, 0)\n  init_v (v, iplus1()); \n  print_v (v); \n  std::cout << std::endl; \n\n  // v[i] = k || (k, 0) ; i = 0, k = 5 ;  ++i, ++k\n  init_v (v, kpp (5)); \n  print_v (v); \n  std::cout << std::endl; \n\n  // v[i] = 2 || (2, 0)\n  init_v (v, const_val<elem_t> (2)); \n  print_v (v); \n  std::cout << std::endl; \n\n  // v[i] = 10 i || (10 i, 0)\n  init_v (v, times_plus<elem_t> (10)); \n  print_v (v); \n  std::cout << std::endl; \n\n  // v[i] = i+0.1 || (i+0.1, 0)\n  init_v (v, times_plus<elem_t> (1, 0.1)); \n  print_v (v); \n  std::cout << std::endl; \n  std::cout << std::endl; \n\n  matr_t m (5, 7); \n\n  // m[i, j] = k ; i = 0, j = 0, k = 0 ; ++j, ++k\n  init_m<kpp> (m); \n  print_m (m); \n  std::cout << std::endl; \n\n#ifndef F_COMPLEX\n  elem_t s (10); \n#else\n  elem_t s (10, -1); \n#endif \n\n  // m[i, j] = s (i+1) + (j+0.1)\n  init_m (m, times_plus<elem_t> (s, 1, 0.1)); \n  print_m (m); \n  std::cout << std::endl; \n\n#ifndef F_COMPLEX\n  elem_t c (-2); \n#else\n  elem_t c (2, -2); \n#endif \n\n  // m[i, j] = c\n  init_m (m, const_val<elem_t> (c)); \n  print_m (m); \n  std::cout << std::endl; \n\n  // m[i, j] = i\n  init_m<rws> (m); \n  print_m (m); \n  std::cout << std::endl; \n\n  // m[i, j] = j+1\n  init_m (m, cls1()); \n  print_m (m); \n  std::cout << std::endl; \n\n  matr_t sm (4, 4); \n\n  // [4 3 2 1]\n  // [0 4 3 2]\n  // [0 0 4 3]\n  // [0 0 0 4]\n  init_symm (sm, 'u'); \n  print_m (sm); \n  std::cout << std::endl; \n  print_m_data (sm);\n  std::cout << std::endl; \n\n  init_m (sm, const_val<elem_t> (0)); \n  // [4 3 2 1]\n  // [3 4 3 2]\n  // [2 3 4 3]\n  // [1 2 3 4]\n  init_symm (sm); \n  print_m (sm); \n  std::cout << std::endl; \n  print_m_data (sm);\n  std::cout << std::endl; \n\n  init_m (sm, const_val<elem_t> (0)); \n  // [4 0 0 0]\n  // [3 4 0 0]\n  // [2 3 4 0]\n  // [1 2 3 4]\n  init_symm (sm, 'L'); \n  print_m (sm); \n  std::cout << std::endl; \n  print_m_data (sm);\n  std::cout << std::endl; \n\n} \n", "meta": {"hexsha": "4cf3c5f4e67446a413fae5bef8dfe5450a88a419", "size": 2774, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/init.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/init.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/init.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 19.1310344828, "max_line_length": 54, "alphanum_fraction": 0.5421773612, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.0460339010904779, "lm_q1q2_score": 0.020865411079627513}}
{"text": "#ifndef SUNDIALS_CVODE_INTERFACE_HPP\n#define SUNDIALS_CVODE_INTERFACE_HPP\n\n#include <iostream>\n#include <algorithm>\n#include <limits>\n#include <type_traits>\n#include <vector>\n#include <functional>\n#include <memory>\n\n#include <cassert>\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 <sunmatrix/sunmatrix_band.h>     // access to band SUNMatrix\n#include <sunlinsol/sunlinsol_band.h>     // access to band SUNLinearSolver\n#include <sunlinsol/sunlinsol_spgmr.h>    // access to SPGMR SUNLinearSolver\n#include <sunlinsol/sunlinsol_spfgmr.h>   // access to SPGMR SUNLinearSolver\n#include <sunlinsol/sunlinsol_spbcgs.h>   // access to SPBCGS SUNLinearSolver\n#include <sunlinsol/sunlinsol_sptfqmr.h>  // access to SPTFQMR SUNLinearSolver \n#include <sundials/sundials_types.h>      // defs. of realtype, sunindextype\n\n#include <fmt/format.h>\n\n#include <boost/optional.hpp>\n\n#include \"sundials/cvode/types.hpp\"\n#include \"sundials/cvode/client.hpp\"\n\nnamespace SUNDIALS {\n\n  namespace CVODE {\n  \n    /* \n       ---------------------------------------------------------------------------\n       CVODE inetrafce\n       Implementation: strategy pattern\n       Strategies:\n       - Direct methods:\n       * Dense matrix\n       * Band matrix\n       - Iterative methods:\n       * SPGMR   = Scaled Preconditioned Generalized Minimal Residual\n       * SPFGMR  = Scaled Preconditioned Flexible Generalized Minimal\n       * SPBCGS  = Scaled Preconditioned Bi-Conjugate Gradient Stable\n       * SPTFQMR = Scaled Preconditioned Transpose-Free Quasi-Minimal Residual \n       ---------------------------------------------------------------------------\n    */\n  \n    // ------------ CVODE strategy interface\n    class IStrategy {\n\n    protected:\n    \n      void* memory;\n      Client* client;\n      SUNLinearSolver linear_solver;\n    \n    private:\n    \n      Types::LinearMultisptepMethod linear_multi_step_meth;\n      Types::TimeStepcontrol time_step_ctrl;\n      Types::SolverControl solver_ctrl;\n      bool is_initialised;\n      bool must_be_reinitialised;\n    \n      virtual int SetLinearSolver() = 0;\n      virtual int BindUserFunctions() = 0;\n    \n    public:\n\n      IStrategy();\n      virtual ~IStrategy();\n      void SetLinearMultiStepMethod( Types::LinearMultisptepMethod const linear_multi_step_meth_ );\n      void SetClientData( void* const user_data_ );\n      boost::optional<int> SetInitStepSize( realtype const init_step );\n      boost::optional<int> SetMinStepSize( realtype const min_step );\n      boost::optional<int> SetMaxStepSize( realtype const max_step );\n      boost::optional<int> SetMaxNumSteps( long int const n_steps );\n      void SetMaxOrder( int const max_order );\n      boost::optional<int> SetMaxWarnMessages( int const max_warn_msgs );\n      boost::optional<int> SetStabilityLimitDetection( bool const stab_lib_det_active );\n      boost::optional<int> SetMaxErrorTestFailures( int const max_err_test_fails );\n      boost::optional<int> SetMaxNonlinearIterations( int const max_nonlin_iters );\n      boost::optional<int> SetMaxConvergenceFailures( int const max_conv_fails );\n      boost::optional<int> SetNonlinConvergenceCoefficient( realtype const nonlin_conv_coef );  \n      int Initialise();\n      int ReInitialise( realtype const time_init,\n                        std::vector<realtype> const& state );\n      int ReInitialise( realtype const time_init,\n                        realtype const * const state );  \n      int Integrate( realtype const time_target );\n      realtype* Solution() const;\n      realtype Solution( sunindextype const i ) const;\n      int MainSolverStatistics( Types::MainSolverStatistics& stats ) const;\n      int LinearSolverStatistics( Types::LinearSolverStatistics& stats ) const;\n      std::string PrintSolverStatistics() const;\n    };\n\n    // ------------ Direct solvers interface\n    class Direct: public IStrategy {\n    public:\n      Direct();\n      ~Direct();        \n    \n    protected:\n      SUNMatrix matrix;\n\n    private:\n      int BindUserFunctions() override;\n    \n    };\n\n    // ------------ Dense matrix direct strategy\n    class Dense : public Direct {\n    public:\n      Dense();    \n      ~Dense();\n    \n    private:\n      int SetLinearSolver() override;\n    };\n\n    // ------------ Band matrix direct strategy\n    class Band : public Direct {\n    public:\n      Band();\n      ~Band();\n      void SetMatrixBandwidth( Types::Bandwidth const bandwidth_ );\n      void SetMatrixBandwidth( sunindextype const upper\n                               , sunindextype const lower );\n\n    private:\n      Types::Bandwidth bandwidth;\n      int SetLinearSolver() override;    \n    };\n \n    // ------------ Iterative solvers interface\n    class Iterative: public IStrategy {\n    public:\n      Iterative();    \n      ~Iterative();\n      void SetLinearSolverOptions( Types::Preconditioner const preconditioner\n                                   , Types::GramSchmidt const gram_schmidt\n                                   , int const n_krylov_basis_vectors\n                                   , int const max_restarts );\n  \n    private:\n      int BindUserFunctions() override;\n\n    protected:\n      Types::IterativeLinarSolverOptions options;\n    };\n\n    // ------------ SPGMR iterative strategy\n    class SPGMR : public Iterative {\n    public:\n      SPGMR();\n      ~SPGMR();\n    \n    private:\n      int SetLinearSolver() override;\n    };\n\n    // ------------ SPFGMR iterative strategy\n    class SPFGMR : public Iterative {\n    public:\n      SPFGMR();\n      ~SPFGMR();\n    \n    private:\n      int SetLinearSolver() override;\n    };\n\n    // ------------ SPBCGS iterative strategy\n    class SPBCGS : public Iterative {\n    public:\n      SPBCGS();\n      ~SPBCGS();\n    \n    private:\n      int SetLinearSolver() override;\n    };\n  \n    // ------------ SPTFQMR iterative strategy\n    class SPTFQMR : public Iterative {\n    public:\n      SPTFQMR();    \n      ~SPTFQMR();\n    \n    private:\n      int SetLinearSolver() override;\n    };\n  \n\n    // CVODE client - context\n    class Solver {\n    \n    private:\n    \n      IStrategy* strategy;\n\n    public:\n\n      explicit Solver()\n        : strategy( nullptr )\n      {}\n    \n      explicit Solver( IStrategy* strategy_ )\n        : strategy( strategy_ )\n      {}\n    \n      void SetStrategy( IStrategy* strategy_ ) {\n        strategy = strategy_;\n      }\n\n      void SetLinearMultiStepMethod( Types::LinearMultisptepMethod\n                                     const linear_multi_step_meth ) {\n        strategy->SetLinearMultiStepMethod( linear_multi_step_meth );\n      }\n    \n      void SetClientData( void* const user_data ) {\n        strategy->SetClientData( user_data );\n      }\n\n      boost::optional<int> SetInitStepSize( realtype const init_step ) const {\n        return strategy->SetInitStepSize( init_step );\n      }\n    \n      boost::optional<int> SetMinStepSize( realtype const min_step ) const {\n        return strategy->SetMinStepSize( min_step );\n      }\n    \n      boost::optional<int> SetMaxStepSize( realtype const max_step ) const {\n        return strategy->SetMaxStepSize( max_step );\n      }\n    \n      boost::optional<int> SetMaxNumSteps( long int const n_steps ) const {\n        return strategy->SetMaxNumSteps( n_steps );\n      }\n\n      void SetMaxOrder( int const max_order ) const {\n        return strategy->SetMaxOrder( max_order );\n      }\n    \n      boost::optional<int> SetMaxWarnMessages( int const max_warn_msgs ) const {\n        return strategy->SetMaxWarnMessages( max_warn_msgs );\n      }\n    \n      boost::optional<int> SetStabilityLimitDetection( bool const stab_lib_det_active ) const {\n        return strategy->SetStabilityLimitDetection( stab_lib_det_active );\n      }\n    \n      boost::optional<int> SetMaxErrorTestFailures( int const max_err_test_fails ) const {\n        return strategy->SetMaxErrorTestFailures( max_err_test_fails );\n      }\n    \n      boost::optional<int> SetMaxNonlinearIterations( int const max_nonlin_iters ) const {\n        return strategy->SetMaxNonlinearIterations( max_nonlin_iters );\n      }\n    \n      boost::optional<int> SetMaxConvergenceFailures( int const max_conv_fails ) const {\n        return strategy->SetMaxConvergenceFailures( max_conv_fails );\n      }\n    \n      boost::optional<int> SetNonlinConvergenceCoefficient( realtype const\n                                                            nonlin_conv_coef ) const {\n        return strategy->SetNonlinConvergenceCoefficient( nonlin_conv_coef );\n      }\n    \n      int Initialise() const {\n        return strategy->Initialise();\n      }\n    \n      int Integrate( realtype const time_target ) const {\n        return strategy->Integrate( time_target );\n      }\n\n      realtype* Solution() const {\n        return strategy->Solution( );\n      }\n    \n      int MainSolverStatistics( Types::MainSolverStatistics& stats ) const {\n        return strategy->MainSolverStatistics( stats );\n      }\n\n      int LinearSolverStatistics( Types::LinearSolverStatistics& stats ) const {\n        return strategy->LinearSolverStatistics( stats );\n      }\n    \n      std::string PrintSolverStatistics() const {\n        return strategy->PrintSolverStatistics();\n      }\n    };\n\n  } // namespace CVODE\n\n} // namespace SUNDIALS\n\n\n#endif // SUNDIALS_CVODE_INTERFACE_HPP\n", "meta": {"hexsha": "c50678b12599545fa43213fcab1436c38186e5b7", "size": 9505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sundials/cvode/interface.hpp", "max_stars_repo_name": "ahmades/ChemTools", "max_stars_repo_head_hexsha": "16c901dd1c7050d1219a9ada807adfe729c651d0", "max_stars_repo_licenses": ["MIT"], "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/sundials/cvode/interface.hpp", "max_issues_repo_name": "ahmades/ChemTools", "max_issues_repo_head_hexsha": "16c901dd1c7050d1219a9ada807adfe729c651d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2021-05-18T22:14:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T14:54:33.000Z", "max_forks_repo_path": "include/sundials/cvode/interface.hpp", "max_forks_repo_name": "ahmades/ChemTools", "max_forks_repo_head_hexsha": "16c901dd1c7050d1219a9ada807adfe729c651d0", "max_forks_repo_licenses": ["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.1639344262, "max_line_length": 99, "alphanum_fraction": 0.6280904787, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.054198728295481974, "lm_q1q2_score": 0.02086174873651601}}
{"text": "/*\n * greentea_math_functions.cpp\n *\n *  Created on: Apr 6, 2015\n *      Author: Fabian Tschopp\n */\n\n#include \"caffe/common.hpp\"\n#include \"caffe/device.hpp\"\n\n#ifdef USE_GREENTEA\n#include \"caffe/greentea/greentea.hpp\"\n#include \"caffe/greentea/greentea_math_functions.hpp\"\n\n#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <functional>\n#include <limits>\n#include <random>\n#include <vector>\n\n#include \"viennacl/backend/opencl.hpp\"\n#include \"viennacl/ocl/backend.hpp\"\n#include \"viennacl/ocl/context.hpp\"\n#include \"viennacl/ocl/device.hpp\"\n#include \"viennacl/ocl/platform.hpp\"\n\n#include \"caffe/util/math_functions.hpp\"\n\n#if defined(USE_CLBLAS)\n  #include <clBLAS.h>       // NOLINT\n#elif defined(USE_CLBLAST)\n  #include <clblast.h>      // NOLINT\n#else\n  #include \"viennacl/linalg/inner_prod.hpp\"\n  #include \"viennacl/linalg/norm_1.hpp\"\n  #include \"viennacl/linalg/norm_2.hpp\"\n  #include \"viennacl/linalg/norm_inf.hpp\"\n  #include \"viennacl/linalg/prod.hpp\"\n  #include \"viennacl/matrix.hpp\"\n  #include \"viennacl/scalar.hpp\"\n  #include \"viennacl/vector.hpp\"\n#endif\n\n// ViennaCL 1.5.1 compability fix\n#ifndef VIENNACL_MINOR_VERSION\n#define VIENNACL_MINOR_VERSION 5\n#endif\n\n#if VIENNACL_MINOR_VERSION > 5\n#define VCL_ROW_MAJOR , true\n#define VCL_COL_MAJOR , false\n#else\n#define VCL_ROW_MAJOR\n#define VCL_COL_MAJOR\n#endif\n\nnamespace caffe {\n\nvoid greentea_memset(const int_tp ctx_id, const uint_tp N, const int_tp alpha,\n                     cl_mem X, const int_tp offX) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  // OpenCL Version >= 1.2 approach\n  // clEnqueueFillBuffer(ctx.get_queue().handle().get(),\n  //  X, &alpha, sizeof(int_tp),\n  //                     offX, N, 0, NULL, NULL);\n  // OpenCL Version < 1.2 fallback\n  typedef float Dtype;\n  viennacl::ocl::kernel &oclk_fill = program.get_kernel(\n      CL_KERNEL_SELECT(\"fillbuffer\"));\n  viennacl::ocl::enqueue(\n      oclk_fill(static_cast<int_tp>(N), static_cast<unsigned char>(alpha),\n                WrapHandle(X, &ctx), offX),\n      ctx.get_queue());\n}\n\n// Copy from OpenCL buffer to main memory\nvoid greentea_gpu_memcpy(const uint_tp N, const cl_mem X, const int_tp offX,\n                         void *Y, viennacl::ocl::context *ctx) {\n  if (Y != NULL) {\n    clEnqueueReadBuffer(ctx->get_queue().handle().get(), X, CL_TRUE, offX, N, Y,\n                        0,\n                        NULL,\n                        NULL);\n  }\n}\n\n// Copy from main memory to OpenCL buffer\nvoid greentea_gpu_memcpy(const uint_tp N, const void* X, cl_mem Y,\n                         const int_tp offY, viennacl::ocl::context *ctx) {\n  if (X != NULL) {\n    clEnqueueWriteBuffer(ctx->get_queue().handle().get(), Y,\n    CL_TRUE,\n                         offY, N, X, 0, NULL, NULL);\n  }\n}\n\n// Copy from OpenCL to OpenCL buffer\nvoid greentea_gpu_memcpy(const uint_tp N, const cl_mem X, const int_tp offX,\n                         cl_mem Y, const int_tp offY,\n                         viennacl::ocl::context *ctx) {\n  clEnqueueCopyBuffer(ctx->get_queue().handle().get(), X, Y, offX, offY, N, 0,\n  NULL,\n                      NULL);\n}\n\ntemplate<typename Dtype>\nvoid greentea_copy(const int_tp N, const cl_mem X, const int_tp offX, Dtype* Y,\n                   viennacl::ocl::context *ctx) {\n  greentea_gpu_memcpy(sizeof(Dtype) * N, X, offX * sizeof(Dtype), Y, ctx);\n}\n\ntemplate<typename Dtype>\nvoid greentea_copy(const int_tp N, const Dtype* X, cl_mem Y, const int_tp offY,\n                   viennacl::ocl::context *ctx) {\n  greentea_gpu_memcpy(sizeof(Dtype) * N, X, Y, offY * sizeof(Dtype), ctx);\n}\n\n// Copy from OpenCL buffer to OpenCL buffer\ntemplate<typename Dtype>\nvoid greentea_copy(const int_tp N, const cl_mem X, const int_tp offX, cl_mem Y,\n                   const int_tp offY, viennacl::ocl::context *ctx) {\n  greentea_gpu_memcpy(sizeof(Dtype) * N, X, offX * sizeof(Dtype), Y,\n                      offY * sizeof(Dtype), ctx);\n}\n\n// Explicit instantiations\ntemplate void greentea_copy<int_tp>(const int_tp N, const cl_mem X,\n                                    const int_tp offX,\n                                    int_tp* Y,\n                                    viennacl::ocl::context *ctx);\ntemplate void greentea_copy<uint_tp>(const int_tp N, const cl_mem X,\n                                     const int_tp offX, uint_tp* Y,\n                                     viennacl::ocl::context *ctx);\ntemplate void greentea_copy<float>(const int_tp N, const cl_mem X,\n                                   const int_tp offX, float* Y,\n                                   viennacl::ocl::context *ctx);\ntemplate void greentea_copy<double>(const int_tp N, const cl_mem X,\n                                    const int_tp offX, double* Y,\n                                    viennacl::ocl::context *ctx);\ntemplate void greentea_copy<int_tp>(const int_tp N, const int_tp* X, cl_mem Y,\n                                    const int_tp offY,\n                                    viennacl::ocl::context *ctx);\ntemplate void greentea_copy<uint_tp>(const int_tp N, const uint_tp* X, cl_mem Y,\n                                     const int_tp offY,\n                                     viennacl::ocl::context *ctx);\ntemplate void greentea_copy<float>(const int_tp N, const float* X, cl_mem Y,\n                                   const int_tp offY,\n                                   viennacl::ocl::context *ctx);\ntemplate void greentea_copy<double>(const int_tp N, const double* X, cl_mem Y,\n                                    const int_tp offY,\n                                    viennacl::ocl::context *ctx);\ntemplate void greentea_copy<int_tp>(const int_tp N, const cl_mem X,\n                                    const int_tp offX, cl_mem Y,\n                                    const int_tp offY,\n                                    viennacl::ocl::context *ctx);\ntemplate void greentea_copy<uint_tp>(const int_tp N, const cl_mem X,\n                                     const int_tp offX, cl_mem Y,\n                                     const int_tp offY,\n                                     viennacl::ocl::context *ctx);\ntemplate void greentea_copy<float>(const int_tp N, const cl_mem X,\n                                   const int_tp offX, cl_mem Y,\n                                   const int_tp offY,\n                                   viennacl::ocl::context *ctx);\ntemplate void greentea_copy<double>(const int_tp N, const cl_mem X,\n                                    const int_tp offX, cl_mem Y,\n                                    const int_tp offY,\n                                    viennacl::ocl::context *ctx);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_gemm(const int_tp ctx_id, const CBLAS_TRANSPOSE TransA,\n                       const CBLAS_TRANSPOSE TransB, const int_tp M,\n                       const int_tp N, const int_tp K, const Dtype alpha,\n                       const cl_mem A, const int_tp offA, const cl_mem B,\n                       const int_tp offB, const Dtype beta, cl_mem C,\n                       const int_tp offC) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n\n  if (ctx.devices()[0].type() == CL_DEVICE_TYPE_CPU) {\n    Dtype* Aptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), A, true, CL_MAP_READ,\n        sizeof(Dtype) * offA, sizeof(Dtype) * M * K, 0, NULL, NULL, NULL));\n    Dtype* Bptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), B, true, CL_MAP_READ,\n        sizeof(Dtype) * offB, sizeof(Dtype) * N * K, 0, NULL, NULL, NULL));\n    Dtype* Cptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), C, true, CL_MAP_READ | CL_MAP_WRITE,\n        sizeof(Dtype) * offC, sizeof(Dtype) * M * N, 0, NULL, NULL, NULL));\n\n    caffe_cpu_gemm<Dtype>(TransA, TransB, M, N, K, alpha, Aptr, Bptr, beta,\n                          Cptr);\n\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), A, Aptr, 0, NULL,\n    NULL);\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), B, Bptr, 0, NULL,\n    NULL);\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), C, Cptr, 0, NULL,\n    NULL);\n  } else {\n    int_tp lda = (TransA == CblasNoTrans) ? K : M;\n    int_tp ldb = (TransB == CblasNoTrans) ? N : K;\n    int_tp ldc = N;\n\n#if defined(USE_CLBLAS)\n\n    clblasOrder clOrder = clblasRowMajor;\n    clblasTranspose clTransA =\n    (TransA == CblasNoTrans) ? clblasNoTrans : clblasTrans;\n    clblasTranspose clTransB =\n    (TransB == CblasNoTrans) ? clblasNoTrans : clblasTrans;\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasSgemm(clOrder, clTransA, clTransB,\n              M, N, K, alpha, A, offA, lda, B, offB, ldb, beta,\n              C, offC, ldc, 1, &queue, 0, NULL, NULL));\n    } else {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasDgemm(clOrder, clTransA, clTransB,\n              M, N, K, alpha, A, offA, lda, B, offB, ldb, beta,\n              C, offC, ldc, 1, &queue, 0, NULL, NULL));\n    }\n\n#elif defined(USE_CLBLAST)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    clblast::Layout layout = clblast::Layout::kRowMajor;\n    clblast::Transpose a_transpose = (TransA == CblasNoTrans) ?\n      clblast::Transpose::kNo : clblast::Transpose::kYes;\n    clblast::Transpose b_transpose = (TransB == CblasNoTrans) ?\n      clblast::Transpose::kNo : clblast::Transpose::kYes;\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Gemm<float>(\n          layout, a_transpose, b_transpose,\n          M, N, K,\n          alpha,\n          A, offA, lda,\n          B, offB, ldb,\n          beta,\n          C, offC, ldc,\n          &queue));\n    } else {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Gemm<double>(\n          layout, a_transpose, b_transpose,\n          M, N, K,\n          alpha,\n          A, offA, lda,\n          B, offB, ldb,\n          beta,\n          C, offC, ldc,\n          &queue));\n    }\n\n#else  // default (ViennaCL)\n\n    typedef typename viennacl::matrix_base<Dtype,\n        uint_tp, int_tp>::size_type size_type;\n    typedef typename viennacl::matrix_base<Dtype,\n        uint_tp, int_tp>::size_type difference_type;\n\n    size_type A_size1 = static_cast<size_type>((TransA == CblasTrans) ? K : M);\n    size_type A_size2 = static_cast<size_type>((TransA == CblasTrans) ? M : K);\n\n    size_type B_size1 = static_cast<size_type>((TransB == CblasTrans) ? N : K);\n    size_type B_size2 = static_cast<size_type>((TransB == CblasTrans) ? K : N);\n\n    viennacl::matrix_base<Dtype, size_t, ptrdiff_t> matA(A, ctx, A_size1,\n                                                       size_type(0),\n                                                       difference_type(1),\n                                                       size_type(M), A_size2,\n                                                       size_type(offA),\n                                                       difference_type(1),\n                                                       size_type(lda)\n                                                       VCL_ROW_MAJOR);\n\n    viennacl::matrix_base<Dtype, size_t, ptrdiff_t> matB(B, ctx, B_size1,\n                                                       size_type(0),\n                                                       difference_type(1),\n                                                       size_type(K), B_size2,\n                                                       size_type(offB),\n                                                       difference_type(1),\n                                                       size_type(ldb)\n                                                       VCL_ROW_MAJOR);\n\n    viennacl::matrix_base<Dtype, size_t, ptrdiff_t> matC(C, ctx, size_type(M),\n                                                       size_type(0),\n                                                       difference_type(1),\n                                                       size_type(M),\n                                                       size_type(N),\n                                                       size_type(offC),\n                                                       difference_type(1),\n                                                       size_type(ldc)\n                                                       VCL_ROW_MAJOR);\n\n    if (TransA == CblasTrans && TransB == CblasTrans)\n      viennacl::linalg::prod_impl(viennacl::trans(matA), viennacl::trans(matB),\n                                  matC, alpha, beta);\n    else if (TransA == CblasTrans && TransB == CblasNoTrans)\n      viennacl::linalg::prod_impl(viennacl::trans(matA), matB, matC, alpha,\n                                  beta);\n    else if (TransA == CblasNoTrans && TransB == CblasTrans)\n      viennacl::linalg::prod_impl(matA, viennacl::trans(matB), matC, alpha,\n                                  beta);\n    else if (TransA == CblasNoTrans && TransB == CblasNoTrans)\n      viennacl::linalg::prod_impl(matA, matB, matC, alpha, beta);\n\n#endif  // clBLAS, CLBlast, or default (ViennaCL)\n  }\n}\n\ntemplate void greentea_gpu_gemm<float>(const int_tp ctx_id,\n                                       const CBLAS_TRANSPOSE TransA,\n                                       const CBLAS_TRANSPOSE TransB,\n                                       const int_tp M, const int_tp N,\n                                       const int_tp K, const float alpha,\n                                       const cl_mem A, const int_tp offA,\n                                       const cl_mem B, const int_tp offB,\n                                       const float beta, cl_mem C,\n                                       const int_tp offC);\ntemplate void greentea_gpu_gemm<double>(const int_tp ctx_id,\n                                        const CBLAS_TRANSPOSE TransA,\n                                        const CBLAS_TRANSPOSE TransB,\n                                        const int_tp M, const int_tp N,\n                                        const int_tp K, const double alpha,\n                                        const cl_mem A, const int_tp offA,\n                                        const cl_mem B, const int_tp offB,\n                                        const double beta, cl_mem C,\n                                        const int_tp offC);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_gemv(const int_tp ctx_id, const CBLAS_TRANSPOSE TransA,\n                       const int_tp M, const int_tp N, const Dtype alpha,\n                       const cl_mem A, const int_tp offA, const cl_mem x,\n                       const int_tp offx, const Dtype beta, cl_mem y,\n                       const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n\n  if (ctx.devices()[0].type() == CL_DEVICE_TYPE_CPU) {\n    Dtype* Aptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), A, true, CL_MAP_READ,\n        sizeof(Dtype) * offA, sizeof(Dtype) * M * N, 0, NULL, NULL, NULL));\n    Dtype* xptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), x, true, CL_MAP_READ,\n        sizeof(Dtype) * offx, sizeof(Dtype) * (TransA == CblasTrans) ? M : N, 0,\n        NULL,\n        NULL, NULL));\n    Dtype* yptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), y, true, CL_MAP_READ | CL_MAP_WRITE,\n        sizeof(Dtype) * offy, sizeof(Dtype) * (TransA == CblasTrans) ? N : M, 0,\n        NULL,\n        NULL, NULL));\n\n    caffe_cpu_gemv<Dtype>(TransA, M, N, alpha, Aptr, xptr, beta, yptr);\n\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), A, Aptr, 0, NULL,\n    NULL);\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), x, xptr, 0, NULL,\n    NULL);\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), y, yptr, 0, NULL,\n    NULL);\n  } else {\n#if defined(USE_CLBLAS)\n\n    clblasTranspose clTransA =\n    (TransA == CblasNoTrans) ? clblasNoTrans : clblasTrans;\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasSgemv(clblasRowMajor,\n              clTransA, M, N, alpha, A, offA, N, x, offx, 1,\n              beta, y, offy, 1, 1, &queue, 0, NULL, NULL));\n    } else {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasDgemv(clblasRowMajor,\n              clTransA, M, N, alpha, A, offA, N, x, offx, 1,\n              beta, y, offy, 1, 1, &queue, 0, NULL, NULL));\n    }\n\n#elif defined(USE_CLBLAST)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    clblast::Layout layout = clblast::Layout::kRowMajor;\n    clblast::Transpose a_transpose = (TransA == CblasNoTrans) ?\n      clblast::Transpose::kNo : clblast::Transpose::kYes;\n\n    const size_t ldA = N;\n    const size_t incx = 1;\n    const size_t incy = 1;\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Gemv<float>(\n          layout, a_transpose,\n          M, N,\n          alpha,\n          A, offA, ldA,\n          x, offx, incx,\n          beta,\n          y, offy, incy,\n          &queue));\n    } else {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Gemv<double>(\n          layout, a_transpose,\n          M, N,\n          alpha,\n          A, offA, ldA,\n          x, offx, incx,\n          beta,\n          y, offy, incy,\n          &queue));\n    }\n\n#else  // default (ViennaCL)\n\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type size_type;\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type difference_type;\n\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v1(\n        x, size_type((TransA == CblasTrans) ? M : N), size_type(offx),\n        difference_type(1), ctx);\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v2(\n        y, size_type((TransA == CblasTrans) ? N : M), size_type(offy),\n        difference_type(1), ctx);\n    viennacl::matrix_base<Dtype, size_t, ptrdiff_t> mat(A, ctx, size_type(M),\n                                                      size_type(0),\n                                                      difference_type(1),\n                                                      size_type(M),\n                                                      size_type(N),\n                                                      size_type(offA),\n                                                      difference_type(1),\n                                                      size_type(N)\n                                                      VCL_ROW_MAJOR);\n    v2 *= beta;\n    if (TransA == CblasTrans) {\n      v2 += alpha * viennacl::linalg::prod(viennacl::trans(mat), v1);\n    } else {\n      v2 += alpha * viennacl::linalg::prod(mat, v1);\n    }\n\n#endif  // clBLAS, CLBlast, or default (ViennaCL)\n  }\n}\n\ntemplate void greentea_gpu_gemv<float>(const int_tp ctx_id,\n                                       const CBLAS_TRANSPOSE TransA,\n                                       const int_tp M, const int_tp N,\n                                       const float alpha, const cl_mem A,\n                                       const int_tp offA, const cl_mem x,\n                                       const int_tp offx, const float beta,\n                                       cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_gemv<double>(const int_tp ctx_id,\n                                        const CBLAS_TRANSPOSE TransA,\n                                        const int_tp M, const int_tp N,\n                                        const double alpha, const cl_mem A,\n                                        const int_tp offA, const cl_mem x,\n                                        const int_tp offx, const double beta,\n                                        cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_axpy(const int_tp ctx_id, const int_tp N, const Dtype alpha,\n                       const cl_mem X, const int_tp offX, cl_mem Y,\n                       const int_tp offY) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n\n  if (ctx.devices()[0].type() == CL_DEVICE_TYPE_CPU) {\n    Dtype* Xptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), X, true, CL_MAP_READ,\n        sizeof(Dtype) * offX, sizeof(Dtype) * N, 0, NULL, NULL, NULL));\n    Dtype* Yptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), Y, true, CL_MAP_WRITE,\n        sizeof(Dtype) * offY, sizeof(Dtype) * N, 0, NULL, NULL, NULL));\n\n    caffe_axpy<Dtype>(N, alpha, Xptr, Yptr);\n\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), X, Xptr, 0, NULL,\n    NULL);\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), Y, Yptr, 0, NULL,\n    NULL);\n  } else {\n#if defined(USE_CLBLAS)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasSaxpy(N, alpha, X, offX,\n              1, Y, offY, 1, 1, &queue, 0, NULL, NULL));\n    } else {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasDaxpy(N, alpha, X, offX,\n              1, Y, offY, 1, 1, &queue, 0, NULL, NULL));\n    }\n\n#elif defined(USE_CLBLAST)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    const size_t incX = 1;\n    const size_t incY = 1;\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Axpy<float>(\n          N,\n          alpha,\n          X, offX, incX,\n          Y, offY, incY,\n          &queue));\n    } else {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Axpy<double>(\n          N,\n          alpha,\n          X, offX, incX,\n          Y, offY, incY,\n          &queue));\n    }\n\n#else  // default (ViennaCL)\n\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type size_type;\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type difference_type;\n\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v1(X, size_type(N),\n                                                     size_type(offX),\n                                                     difference_type(1), ctx);\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v2(Y, size_type(N),\n                                                     size_type(offY),\n                                                     difference_type(1), ctx);\n    v2 += alpha * v1;\n\n#endif  // clBLAS, CLBlast, or default (ViennaCL)\n  }\n}\n\ntemplate void greentea_gpu_axpy<float>(const int_tp ctx_id, const int_tp N,\n                                       const float alpha, const cl_mem X,\n                                       const int_tp offX, cl_mem Y,\n                                       const int_tp offY);\ntemplate void greentea_gpu_axpy<double>(const int_tp ctx_id, const int_tp N,\n                                        const double alpha, const cl_mem X,\n                                        const int_tp offX, cl_mem Y,\n                                        const int_tp offY);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_mul(const int_tp ctx_id, const int_tp N, const cl_mem a,\n                      const int_tp offa, const cl_mem b, const int_tp offb,\n                      cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_mul = program.get_kernel(CL_KERNEL_SELECT(\"mul\"));\n  viennacl::ocl::enqueue(\n      oclk_mul(N, WrapHandle(a, &ctx), offa, WrapHandle(b, &ctx), offb,\n               WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_mul<float>(const int_tp ctx_id, const int_tp N,\n                                      const cl_mem a, const int_tp offa,\n                                      const cl_mem b, const int_tp offb,\n                                      cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_mul<double>(const int_tp ctx_id, const int_tp N,\n                                       const cl_mem a, const int_tp offa,\n                                       const cl_mem b, const int_tp offb,\n                                       cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_div(const int_tp ctx_id, const int_tp N, const cl_mem a,\n                      const int_tp offa, const cl_mem b, const int_tp offb,\n                      cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_div = program.get_kernel(CL_KERNEL_SELECT(\"div\"));\n  viennacl::ocl::enqueue(\n      oclk_div(N, WrapHandle(a, &ctx), offa, WrapHandle(b, &ctx), offb,\n               WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_div<float>(const int_tp ctx_id, const int_tp N,\n                                      const cl_mem a, const int_tp offa,\n                                      const cl_mem b, const int_tp offb,\n                                      cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_div<double>(const int_tp ctx_id, const int_tp N,\n                                       const cl_mem a, const int_tp offa,\n                                       const cl_mem b, const int_tp offb,\n                                       cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_scal(const int_tp ctx_id, const int_tp N, const Dtype alpha,\n                       cl_mem x, int_tp offx) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n\n  if (ctx.devices()[0].type() == CL_DEVICE_TYPE_CPU) {\n    Dtype* xptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), x, true, CL_MAP_READ | CL_MAP_WRITE,\n        sizeof(Dtype) * offx, sizeof(Dtype) * N, 0, NULL, NULL, NULL));\n\n    caffe_scal<Dtype>(N, alpha, xptr);\n\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), x, xptr, 0, NULL,\n    NULL);\n  } else {\n#if defined(USE_CLBLAS)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CL_BLAS_CHECK(clblasSscal(N, alpha, x, offx,\n              1, 1, &queue, 0, NULL, NULL));\n    } else {\n      GREENTEA_CL_BLAS_CHECK(clblasDscal(N, alpha, x, offx,\n              1, 1, &queue, 0, NULL, NULL));\n    }\n\n#elif defined(USE_CLBLAST)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    const size_t incx = 1;\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Scal<float>(\n          N,\n          alpha,\n          x, offx, incx,\n          &queue));\n    } else {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Scal<double>(\n          N,\n          alpha,\n          x, offx, incx,\n          &queue));\n    }\n\n#else  // default (ViennaCL)\n\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type size_type;\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type difference_type;\n\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v1(x, size_type(N),\n                                                     size_type(offx),\n                                                     difference_type(1), ctx);\n    v1 *= alpha;\n\n#endif  // clBLAS, CLBlast, or default (ViennaCL)\n  }\n}\n\ntemplate void greentea_gpu_scal<float>(const int_tp ctx_id, const int_tp N,\n                                       const float alpha, cl_mem x,\n                                       const int_tp offx);\ntemplate void greentea_gpu_scal<double>(const int_tp ctx_id, const int_tp N,\n                                        const double alpha, cl_mem x,\n                                        const int_tp offx);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_axpby(const int_tp ctx_id, const int_tp N, const Dtype alpha,\n                        const cl_mem X, const int_tp offX, const Dtype beta,\n                        cl_mem Y, const int_tp offY) {\n  greentea_gpu_scal<Dtype>(ctx_id, N, beta, Y, offY);\n  greentea_gpu_axpy<Dtype>(ctx_id, N, alpha, X, offX, Y, offY);\n}\n\ntemplate void greentea_gpu_axpby<float>(const int_tp ctx_id, const int_tp N,\n                                        const float alpha, const cl_mem X,\n                                        const int_tp offX, const float beta,\n                                        cl_mem Y, const int_tp offY);\n\ntemplate void greentea_gpu_axpby<double>(const int_tp ctx_id, const int_tp N,\n                                         const double alpha, const cl_mem X,\n                                         const int_tp offX, const double beta,\n                                         cl_mem Y, const int_tp offY);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_dot(const int_tp ctx_id, const int_tp n, const cl_mem X,\n                      const int_tp offX, const cl_mem Y, const int_tp offY,\n                      Dtype* out) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n\n  if (ctx.devices()[0].type() == CL_DEVICE_TYPE_CPU) {\n    Dtype* Xptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), X, true, CL_MAP_READ,\n        sizeof(Dtype) * offX, sizeof(Dtype) * n, 0, NULL, NULL, NULL));\n    Dtype* Yptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), Y, true, CL_MAP_READ,\n        sizeof(Dtype) * offY, sizeof(Dtype) * n, 0, NULL, NULL, NULL));\n\n    *out = caffe_cpu_dot<Dtype>(n, Xptr, Yptr);\n\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), X, Xptr, 0, NULL,\n    NULL);\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), Y, Yptr, 0, NULL,\n    NULL);\n\n  } else {\n#if defined(USE_CLBLAS)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    cl_int err;\n    cl_mem gpuout = clCreateBuffer(ctx.handle().get(), CL_MEM_READ_WRITE,\n        sizeof(Dtype), NULL, &err);\n    cl_mem scratch = clCreateBuffer(ctx.handle().get(), CL_MEM_READ_WRITE,\n        n * sizeof(Dtype), NULL, &err);\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasSdot(n, gpuout, 0, X, offX, 1, Y,\n              offY, 1, scratch, 1, &queue, 0, NULL, NULL));\n    } else {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasDdot(n, gpuout, 0, X, offX, 1, Y,\n              offY, 1, scratch, 1, &queue, 0, NULL, NULL));\n    }\n\n    greentea_gpu_memcpy(sizeof(Dtype), gpuout, 0, out, &ctx);\n\n    clReleaseMemObject(gpuout);\n    clReleaseMemObject(scratch);\n\n#elif defined(USE_CLBLAST)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    cl_int err = CL_SUCCESS;\n    cl_mem Z = clCreateBuffer(ctx.handle().get(), CL_MEM_READ_WRITE,\n      sizeof(Dtype), NULL, &err);\n    // TODO: error handling.\n\n    const size_t offZ = 0;\n    const size_t incX = 1;\n    const size_t incY = 1;\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Dot<float>(\n          n,\n          Z, offZ,\n          X, offX, incX,\n          Y, offY, incY,\n          &queue));\n    } else {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Dot<double>(\n          n,\n          Z, offZ,\n          X, offX, incX,\n          Y, offY, incY,\n          &queue));\n    }\n\n    greentea_gpu_memcpy(sizeof(Dtype), Z, offZ, out, &ctx);\n    clReleaseMemObject(Z);\n\n#else  // default (ViennaCL)\n\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type size_type;\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type difference_type;\n\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v1(X, size_type(n),\n                                                     size_type(offX),\n                                                     difference_type(1), ctx);\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v2(Y, size_type(n),\n                                                     size_type(offY),\n                                                     difference_type(1), ctx);\n\n    *out = viennacl::linalg::inner_prod(v1, v2);\n\n#endif  // clBLAS, CLBlast, or default (ViennaCL)\n  }\n}\n\ntemplate void greentea_gpu_dot<float>(const int_tp ctx_id, const int_tp n,\n                                      const cl_mem X, const int_tp offX,\n                                      const cl_mem Y, const int_tp offY,\n                                      float* out);\ntemplate void greentea_gpu_dot<double>(const int_tp ctx_id, const int_tp n,\n                                       const cl_mem X, const int_tp offX,\n                                       const cl_mem Y, const int_tp offY,\n                                       double* out);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_asum(const int_tp ctx_id, const int_tp n, const cl_mem X,\n                       const int_tp offX, Dtype* Y) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n\n  if (ctx.devices()[0].type() == CL_DEVICE_TYPE_CPU) {\n    Dtype* Xptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), X, true, CL_MAP_READ,\n        sizeof(Dtype) * offX, sizeof(Dtype) * n, 0, NULL, NULL, NULL));\n\n    *Y = caffe_cpu_asum<Dtype>(n, Xptr);\n\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), X, Xptr, 0, NULL,\n    NULL);\n  } else {\n#if defined(USE_CLBLAS)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    cl_int err;\n    cl_mem gpuout = clCreateBuffer(ctx.handle().get(), CL_MEM_READ_WRITE,\n        sizeof(Dtype), NULL, &err);\n    cl_mem scratch = clCreateBuffer(ctx.handle().get(), CL_MEM_READ_WRITE,\n        n * sizeof(Dtype), NULL, &err);\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasSasum(n, gpuout, 0, X, offX, 1,\n              scratch, 1, &queue, 0, NULL, NULL));\n    } else {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasDasum(n, gpuout, 0, X, offX, 1,\n              scratch, 1, &queue, 0, NULL, NULL));\n    }\n\n    greentea_gpu_memcpy(sizeof(Dtype), gpuout, 0, Y, &ctx);\n\n    clReleaseMemObject(gpuout);\n    clReleaseMemObject(scratch);\n\n#elif defined(USE_CLBLAST)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    cl_int err = CL_SUCCESS;\n    cl_mem Z = clCreateBuffer(ctx.handle().get(), CL_MEM_READ_WRITE,\n      sizeof(Dtype), NULL, &err);\n    // TODO: error handling.\n\n    const size_t offZ = 0;\n    const size_t incX = 1;\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Asum<float>(\n          n,\n          Z, offZ,\n          X, offX, incX,\n          &queue));\n    } else {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Asum<double>(\n          n,\n          Z, offZ,\n          X, offX, incX,\n          &queue));\n    }\n\n    greentea_gpu_memcpy(sizeof(Dtype), Z, offZ, Y, &ctx);\n\n    clReleaseMemObject(Z);\n\n#else  // default (ViennaCL)\n\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type size_type;\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type difference_type;\n\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v1(X, size_type(n),\n                                                     size_type(offX),\n                                                     difference_type(1), ctx);\n\n    *Y = viennacl::linalg::norm_1(v1);\n\n#endif  // clBLAS, CLBlast, or default (ViennaCL)\n  }\n}\n\ntemplate void greentea_gpu_asum<float>(const int_tp ctx_id, const int_tp n,\n                                       const cl_mem X, const int_tp offX,\n                                       float* Y);\ntemplate void greentea_gpu_asum<double>(const int_tp ctx_id, const int_tp n,\n                                        const cl_mem X, const int_tp offX,\n                                        double* Y);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_scale(const int_tp ctx_id, const int_tp n, const Dtype alpha,\n                        const cl_mem X, const int_tp offX, cl_mem Y,\n                        const int_tp offY) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n\n  if (ctx.devices()[0].type() == CL_DEVICE_TYPE_CPU) {\n    Dtype* Xptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), X, true, CL_MAP_READ,\n        sizeof(Dtype) * offX, sizeof(Dtype) * n, 0, NULL, NULL, NULL));\n    Dtype* Yptr = reinterpret_cast<Dtype*>(clEnqueueMapBuffer(\n        ctx.get_queue().handle().get(), Y, true, CL_MAP_WRITE,\n        sizeof(Dtype) * offY, sizeof(Dtype) * n, 0, NULL, NULL, NULL));\n\n    caffe_cpu_scale<Dtype>(n, alpha, Xptr, Yptr);\n\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), X, Xptr, 0, NULL,\n    NULL);\n    clEnqueueUnmapMemObject(ctx.get_queue().handle().get(), Y, Yptr, 0, NULL,\n    NULL);\n  } else {\n#if defined(USE_CLBLAS)\n\n    // FIXME: Remove, as can reuse ctx obtained above?\n    viennacl::ocl::context ctx = viennacl::ocl::get_context(ctx_id);\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    // FIXME: Use xAXPY with beta = 0?\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasScopy(n, X, offX, 1, Y, offY, 1, 1, &queue, 0, NULL, NULL));\n      GREENTEA_CL_BLAS_CHECK(\n          clblasSscal(n, alpha, Y, offY, 1, 1, &queue, 0, NULL, NULL));\n    } else {\n      GREENTEA_CL_BLAS_CHECK(\n          clblasDcopy(n, X, offX, 1, Y, offY, 1, 1, &queue, 0, NULL, NULL));\n      GREENTEA_CL_BLAS_CHECK(\n          clblasDscal(n, alpha, Y, offY, 1, 1, &queue, 0, NULL, NULL));\n    }\n\n#elif defined(USE_CLBLAST)\n\n    cl_command_queue queue = ctx.get_queue().handle().get();\n\n    const size_t incX = 1;\n    const size_t incY = 1;\n\n    if (std::is_same<Dtype, float>::value) {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Copy<float>(\n          n,\n          X, offX, incX,\n          Y, offY, incY,\n          &queue));\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Scal<float>(\n          n,\n          alpha,\n          Y, offY, incY,\n          &queue));\n    } else {\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Copy<double>(\n          n,\n          X, offX, incX,\n          Y, offY, incY,\n          &queue));\n      GREENTEA_CLBLAST_CHECK(\n        clblast::Scal<double>(\n          n,\n          alpha,\n          Y, offY, incY,\n          &queue));\n    }\n\n#else  // default (ViennaCL)\n\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type size_type;\n    typedef typename viennacl::vector_base<Dtype,\n        uint_tp, int_tp>::size_type difference_type;\n\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v1(X, size_type(n),\n                                                     size_type(offX),\n                                                     difference_type(1), ctx);\n    viennacl::vector_base<Dtype, size_t, ptrdiff_t> v2(Y, size_type(n),\n                                                     size_type(offY),\n                                                     difference_type(1), ctx);\n\n    v2 = v1 * alpha;\n\n#endif  // clBLAS, CLBlast, or default (ViennaCL)\n  }\n}\n\ntemplate void greentea_gpu_scale<float>(const int_tp ctx_id, const int_tp n,\n                                        const float alpha, const cl_mem X,\n                                        const int_tp offX, cl_mem Y,\n                                        const int_tp offY);\n\ntemplate void greentea_gpu_scale<double>(const int_tp ctx_id, const int_tp n,\n                                         const double alpha, const cl_mem X,\n                                         const int_tp offX, cl_mem Y,\n                                         const int_tp offY);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_set(const int_tp ctx_id, const int_tp N, const Dtype alpha,\n                      cl_mem Y, const int_tp offY) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n  // OpenCL Version >= 1.2 approach\n  // clEnqueueFillBuffer(ctx.get_queue().handle().get(),\n  //                  Y, &alpha, sizeof(Dtype),\n  //                  offY, N, 0, NULL, NULL);\n\n  // OpenCL Version < 1.2 fallback\n  viennacl::ocl::kernel &oclk_fill = program.get_kernel(\n      CL_KERNEL_SELECT(\"fill\"));\n  viennacl::ocl::enqueue(oclk_fill(N, alpha, WrapHandle(Y, &ctx), offY),\n                         ctx.get_queue());\n}\n\ntemplate void greentea_gpu_set<int_tp>(const int_tp ctx_id, const int_tp N,\n                                       const int_tp alpha, cl_mem Y,\n                                       const int_tp offY);\ntemplate void greentea_gpu_set<float>(const int_tp ctx_id, const int_tp N,\n                                      const float alpha, cl_mem Y,\n                                      const int_tp offY);\ntemplate void greentea_gpu_set<double>(const int_tp ctx_id, const int_tp N,\n                                       const double alpha, cl_mem Y,\n                                       const int_tp offY);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_add_scalar(const int_tp ctx_id, const int_tp N,\n                             const Dtype alpha, cl_mem Y, const int_tp offY) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_add_scalar = program.get_kernel(\n      CL_KERNEL_SELECT(\"add_scalar\"));\n  viennacl::ocl::enqueue(oclk_add_scalar(N, alpha, WrapHandle(Y, &ctx), offY),\n                         ctx.get_queue());\n}\n\ntemplate void greentea_gpu_add_scalar<float>(const int_tp ctx_id,\n                                             const int_tp N, const float alpha,\n                                             cl_mem Y, const int_tp offY);\ntemplate void greentea_gpu_add_scalar<double>(const int_tp ctx_id,\n                                              const int_tp N,\n                                              const double alpha, cl_mem Y,\n                                              const int_tp offY);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_add(const int_tp ctx_id, const int_tp n, const cl_mem a,\n                      const int_tp offa, const cl_mem b, const int_tp offb,\n                      cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_add = program.get_kernel(CL_KERNEL_SELECT(\"add\"));\n  viennacl::ocl::enqueue(\n      oclk_add(n, WrapHandle(a, &ctx), offa, WrapHandle(b, &ctx), offb,\n               WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_add<float>(const int_tp ctx_id, const int_tp n,\n                                      const cl_mem a, const int_tp offa,\n                                      const cl_mem b, const int_tp offb,\n                                      cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_add<double>(const int_tp ctx_id, const int_tp n,\n                                       const cl_mem a, const int_tp offa,\n                                       const cl_mem b, const int_tp offb,\n                                       cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_sub(const int_tp ctx_id, const int_tp n, const cl_mem a,\n                      const int_tp offa, const cl_mem b, const int_tp offb,\n                      cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_sub = program.get_kernel(CL_KERNEL_SELECT(\"sub\"));\n  viennacl::ocl::enqueue(\n      oclk_sub(n, WrapHandle(a, &ctx), offa, WrapHandle(b, &ctx), offb,\n               WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_sub<float>(const int_tp ctx_id, const int_tp n,\n                                      const cl_mem a, const int_tp offa,\n                                      const cl_mem b, const int_tp offb,\n                                      cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_sub<double>(const int_tp ctx_id, const int_tp n,\n                                       const cl_mem a, const int_tp offa,\n                                       const cl_mem b, const int_tp offb,\n                                       cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_abs(const int_tp ctx_id, const int_tp N, const cl_mem a,\n                      const int_tp offa, cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_abs = program.get_kernel(CL_KERNEL_SELECT(\"abs\"));\n  viennacl::ocl::enqueue(\n      oclk_abs(N, WrapHandle(a, &ctx), offa, WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_abs<float>(const int_tp ctx_id, const int_tp N,\n                                      const cl_mem a, const int_tp offa,\n                                      cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_abs<double>(const int_tp ctx_id, const int_tp N,\n                                       const cl_mem a, const int_tp offa,\n                                       cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_exp(const int_tp ctx_id, const int_tp N, const cl_mem a,\n                      const int_tp offa, cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_exp = program.get_kernel(CL_KERNEL_SELECT(\"exp\"));\n  viennacl::ocl::enqueue(\n      oclk_exp(N, WrapHandle(a, &ctx), offa, WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_exp<float>(const int_tp ctx_id, const int_tp N,\n                                      const cl_mem a, const int_tp offa,\n                                      cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_exp<double>(const int_tp ctx_id, const int_tp N,\n                                       const cl_mem a, const int_tp offa,\n                                       cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_sqrt(const int_tp ctx_id, const int_tp n,\n                       const cl_mem a, const int_tp offa,\n                       cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_sqrt = program.get_kernel(\n      CL_KERNEL_SELECT(\"sqrt\"));\n  viennacl::ocl::enqueue(\n      oclk_sqrt(n, WrapHandle(a, &ctx), offa, WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_sqrt<float>(const int_tp ctx_id, const int_tp n,\n                                       const cl_mem a, const int_tp offa,\n                                       cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_sqrt<double>(const int_tp ctx_id, const int_tp n,\n                                        const cl_mem a, const int_tp offa,\n                                        cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_powx(const int_tp ctx_id, const int_tp N, const cl_mem a,\n                       const int_tp offa, const Dtype alpha, cl_mem y,\n                       const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_powx = program.get_kernel(\n      CL_KERNEL_SELECT(\"powx\"));\n  viennacl::ocl::enqueue(\n      oclk_powx(N, WrapHandle(a, &ctx), offa, alpha, WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_powx<float>(const int_tp ctx_id, const int_tp N,\n                                       const cl_mem a, const int_tp offa,\n                                       const float alpha, cl_mem y,\n                                       const int_tp offy);\ntemplate void greentea_gpu_powx<double>(const int_tp ctx_id, const int_tp N,\n                                        const cl_mem a, const int_tp offa,\n                                        const double alpha, cl_mem y,\n                                        const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_log(const int_tp ctx_id, const int_tp N, const cl_mem a,\n                      const int_tp offa, cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_log = program.get_kernel(CL_KERNEL_SELECT(\"log\"));\n  viennacl::ocl::enqueue(\n      oclk_log(N, WrapHandle(a, &ctx), offa, WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_log<float>(const int_tp ctx_id, const int_tp N,\n                                      const cl_mem a, const int_tp offa,\n                                      cl_mem y, const int_tp offy);\ntemplate void greentea_gpu_log<double>(const int_tp ctx_id, const int_tp N,\n                                       const cl_mem a, const int_tp offa,\n                                       cl_mem y, const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_sign(const int_tp ctx_id, const int_tp n, const cl_mem x,\nint_tp offx,\n                       cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_sign = program.get_kernel(\n      CL_KERNEL_SELECT(\"sign\"));\n  viennacl::ocl::enqueue(\n      oclk_sign(n, WrapHandle(x, &ctx), offx, WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_sign<float>(const int_tp ctx_id, const int_tp n,\n                                       const cl_mem x, int_tp offx, cl_mem y,\n                                       const int_tp offy);\ntemplate void greentea_gpu_sign<double>(const int_tp ctx_id, const int_tp n,\n                                        const cl_mem x, int_tp offx, cl_mem y,\n                                        const int_tp offy);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_sgnbit(const int_tp ctx_id, const int_tp n, const cl_mem x,\nint_tp offx,\n                         cl_mem y, const int_tp offy) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  viennacl::ocl::program &program = (Caffe::Get().GetDevice(ctx_id, false))\n      ->program();\n\n  viennacl::ocl::kernel &oclk_sgnbit = program.get_kernel(\n      CL_KERNEL_SELECT(\"sgnbit\"));\n  viennacl::ocl::enqueue(\n      oclk_sgnbit(n, WrapHandle(x, &ctx), offx, WrapHandle(y, &ctx), offy),\n      ctx.get_queue());\n}\n\ntemplate void greentea_gpu_sgnbit<float>(const int_tp ctx_id, const int_tp n,\n                                         const cl_mem x, int_tp offx, cl_mem y,\n                                         const int_tp offy);\ntemplate void greentea_gpu_sgnbit<double>(const int_tp ctx_id, const int_tp n,\n                                          const cl_mem x, int_tp offx, cl_mem y,\n                                          const int_tp offy);\n\nvoid greentea_gpu_rng_uniform(const int_tp ctx_id, const int_tp n, cl_mem r,\nint_tp offr) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  std::vector<uint_tp> random(n);  //NOLINT\n  caffe_rng_uniform(n, &random[0]);\n  greentea_gpu_memcpy(sizeof(uint_tp) * n, &random[0], r, offr, &ctx);\n}\n\ntemplate<typename Dtype>\nvoid greentea_gpu_rng_uniform(const int_tp ctx_id, const int_tp n,\n                              const Dtype a, const Dtype b, cl_mem r,\n                              const int_tp offr) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  std::vector<Dtype> random(n);  // NOLINT\n  caffe_rng_uniform(n, a, b, &random[0]);\n  greentea_gpu_memcpy(sizeof(Dtype) * n, &random[0], r, offr, &ctx);\n}\n\ntemplate void greentea_gpu_rng_uniform<float>(const int_tp ctx_id,\n                                              const int_tp n, const float a,\n                                              const float b, cl_mem r,\n                                              const int_tp offr);\ntemplate void greentea_gpu_rng_uniform<double>(const int_tp ctx_id,\n                                               const int_tp n, const double a,\n                                               const double b, cl_mem r,\n                                               const int_tp offr);\n\ntemplate<typename Dtype>\nvoid greentea_gpu_rng_gaussian(const int_tp ctx_id, const int_tp n,\n                               const Dtype mu, const Dtype sigma, cl_mem r,\n                               const int_tp offr) {\n  viennacl::ocl::context &ctx = viennacl::ocl::get_context(ctx_id);\n  std::vector<Dtype> random(n);  // NOLINT\n  caffe_rng_gaussian(n, mu, sigma, &random[0]);\n  greentea_gpu_memcpy(sizeof(Dtype) * n, &random[0], r, offr, &ctx);\n}\n\ntemplate void greentea_gpu_rng_gaussian<float>(const int_tp ctx_id,\n                                               const int_tp n, const float mu,\n                                               const float sigma, cl_mem r,\n                                               const int_tp offr);\n\ntemplate void greentea_gpu_rng_gaussian<double>(const int_tp ctx_id,\n                                                const int_tp n, const double mu,\n                                                const double sigma, cl_mem r,\n                                                const int_tp offr);\n\n}  // namespace caffe\n#endif  // USE_GREENTEA\n", "meta": {"hexsha": "802e66dd1dd4f184e5f873edbf9dd51c78d8e8f8", "size": 54209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/greentea/greentea_math_functions.cpp", "max_stars_repo_name": "abhiTronix/caffe-opencl-windows-amd", "max_stars_repo_head_hexsha": "1de97750d3c97756f39899d3b158120971a8a5da", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-06-29T14:51:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T04:10:38.000Z", "max_issues_repo_path": "src/caffe/greentea/greentea_math_functions.cpp", "max_issues_repo_name": "KorJeongHyeonLee/Caffe-CL-Origin", "max_issues_repo_head_hexsha": "430344adbb3a05b4611b1b821a68c82d6480ba26", "max_issues_repo_licenses": ["Intel", "BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-12T11:57:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-30T03:31:09.000Z", "max_forks_repo_path": "src/caffe/greentea/greentea_math_functions.cpp", "max_forks_repo_name": "KorJeongHyeonLee/Caffe-CL-Origin", "max_forks_repo_head_hexsha": "430344adbb3a05b4611b1b821a68c82d6480ba26", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-31T20:13:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-29T14:51:33.000Z", "avg_line_length": 41.34935164, "max_line_length": 80, "alphanum_fraction": 0.5482484458, "num_tokens": 13430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.04272219434707264, "lm_q1q2_score": 0.020860538110277143}}
{"text": "/*\n * Copyright (c) 2009 Carnegie Mellon University.\n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n * \\file cgs_lda.cpp\n *\n * \\brief This file contains a GraphLab based implementation of the\n * Collapsed Gibbs Sampler (CGS) for the Latent Dirichlet Allocation\n * (LDA) model.\n *\n * \n *\n * \\author Joseph Gonzalez, Diana Hu\n */\n\n#include <vector>\n#include <set>\n#include <algorithm>\n\n#include \"util/atomic.hpp\"\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <vector>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_stl.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/input_sequence.hpp>\n\n\n// Global Types\n// ============================================================================\ntypedef int count_type;\n\n\n/**\n * \\brief The factor type is used to store the counts of tokens in\n * each topic for words, documents, and assignments.\n *\n * Atomic counts are used because we violate the abstraction by\n * modifying adjacent vertex data on scatter.  As a consequence\n * multiple threads on the same machine may try to update the same\n * vertex data at the same time.  The graphlab::atomic type ensures\n * that multiple increments are serially consistent.\n */\ntypedef std::vector< graphchi::atomic<count_type> > factor_type;\n\n\n/**\n * \\brief We use the factor type in accumulators and so we define an\n * operator+=\n */\ninline factor_type& operator+=(factor_type& lvalue,\n                               const factor_type& rvalue) {\n  if(!rvalue.empty()) {\n    if(lvalue.empty()) lvalue = rvalue;\n    else {\n      for(size_t t = 0; t < lvalue.size(); ++t) lvalue[t] += rvalue[t];\n    }\n  }\n  return lvalue;\n} // end of operator +=\n\n\n\n\n\n\n\n/**\n * \\brief The latent topic id of a token is the smallest reasonable\n * type.\n */\ntypedef uint16_t topic_id_type;\n\n// We require a null topic to represent the topic assignment for\n// tokens that have not yet been assigned.\n#define NULL_TOPIC (topic_id_type(-1))\n\n#define NTOPICS 20\n\n\n/**\n * \\brief The assignment type is used on each edge to store the\n * assignments of each token.  There can be several occurrences of the\n * same word in a given document and so a vector is used to store the\n * assignments of each occurrence.\n */\ntypedef uint16_t assignment_type[NTOPICS];\n\n\n// Global Variables\n// ============================================================================\n\n/**\n * \\brief The alpha parameter determines the sparsity of topics for\n * each document.\n */\ndouble ALPHA = 1;\n\n/**\n * \\brief the Beta parameter determines the sparsity of words in each\n * document.\n */\ndouble BETA = 0.1;\n\n/**\n * \\brief the total number of topics to uses\n */\n\n/**\n * \\brief The total number of words in the dataset.\n */\nsize_t NWORDS = 0;\n\n/**\n * \\brief The total number of docs in the dataset.\n */\nsize_t NDOCS = 0;\n\n/**\n * \\brief The total number of tokens in the corpus\n */\nsize_t NTOKENS = 0;\n\n\n/**\n * \\brief The number of top words to display during execution (from\n * each topic).\n */\nsize_t TOPK = 5;\n\n/**\n * \\brief The interval to display topics during execution.\n */\nsize_t INTERVAL = 10;\n\n/**\n * \\brief The global variable storing the global topic count across\n * all machines.  This is maintained periodically using aggregation.\n */\nfactor_type GLOBAL_TOPIC_COUNT;\n\n/**\n * \\brief A dictionary of words used to print the top words during\n * execution.\n */\nstd::vector<std::string> DICTIONARY;\n\n/**\n * \\brief The maximum occurences allowed for an individual term-doc\n * pair. (edge data)\n */\nsize_t MAX_COUNT = 100;\n\n\n/**\n * \\brief The time to run until the first sample is taken.  If less\n * than zero then the sampler will run indefinitely.\n */\nfloat BURNIN = -1;\n\n\n\n\n\n\n// Graph Types\n// ============================================================================\n\n/**\n * \\brief The vertex data represents each term and document in the\n * corpus and contains the counts of tokens in each topic.\n */\nstruct vertex_data {\n  ///! The total number of updates\n  uint32_t nupdates;\n  ///! The total number of changes to adjacent tokens\n  uint32_t nchanges;\n  ///! The count of tokens in each topic\n  factor_type factor;\n  vertex_data() : nupdates(0), nchanges(0), factor(NTOPICS) { }\n}; // end of vertex_data\n\n\n/**\n * \\brief The edge data represents the individual tokens (word,doc)\n * pairs and their assignment to topics.\n */\nstruct edge_data {\n  ///! The number of changes on the last update\n  uint16_t nchanges;\n  ///! The assignment of all tokens\n  assignment_type assignment;\n  edge_data(size_t ntokens = 0) : nchanges(0) {\n      for(int i=0; i<NTOPICS; i++) assignment[i] = 0;\n  }\n}; // end of edge_data\n\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\nstatic void parse(edge_data &x, const char * s) {\n    size_t count = atol(s);\n    count = std::min(count, MAX_COUNT);\n    x = (edge_data(count));\n}\n\n/**\n * \\brief Edge data parser used in graph.load_json\n *\n * Make sure that the edge file list\n * has docids from -2 to -(total #docid) and wordids 0 to (total #words -1)\n */\nbool eparser(edge_data& ed, const std::string& line){\n  const int BASE = 10;\n  char* next_char_ptr = NULL;\n  size_t count = strtoul(line.c_str(), &next_char_ptr, BASE);\n  if(next_char_ptr ==NULL) return false;\n\n  //threshold count\n  count = std::min(count, MAX_COUNT);\n  ed = (edge_data(count));\n  return true;\n}\n\n/**\n * \\brief Vertex data parser used in graph.load_json\n */\nbool vparser(vertex_data& vd, const std::string& line){\n  vd = vertex_data();\n  return true;\n}\n\n\n\n\n\n\n\n\n/**\n * \\brief Determine if the given vertex is a word vertex or a doc\n * vertex.\n *\n * For simplicity we connect docs --> words and therefore if a vertex\n * has in edges then it is a word.\n */\ninline bool is_word(const graph_type::vertex_type& vertex) {\n  return vertex.num_in_edges() > 0 ? 1 : 0;\n}\n\n\n/**\n * \\brief Determine if the given vertex is a doc vertex\n *\n * For simplicity we connect docs --> words and therefore if a vertex\n * has out edges then it is a doc\n */\ninline bool is_doc(const graph_type::vertex_type& vertex) {\n  return vertex.num_out_edges() > 0 ? 1 : 0;\n}\n\n/**\n * \\brief return the number of tokens on a particular edge.\n */\ninline size_t count_tokens(const graph_type::edge_type& edge) {\n  return edge.data().assignment.size();\n}\n\n\n/**\n * \\brief Get the other vertex in the edge.\n */\ninline graph_type::vertex_type\nget_other_vertex(const graph_type::edge_type& edge,\n                 const graph_type::vertex_type& vertex) {\n  return vertex.id() == edge.source().id()? edge.target() : edge.source();\n}\n\n\n\n// ========================================================\n// The Collapsed Gibbs Sampler Function\n\n\n\n/**\n * \\brief The gather type for the collapsed Gibbs sampler is used to\n * collect the topic counts on adjacent edges so that the apply\n * function can compute the correct topic counts for the center\n * vertex.\n *\n */\nstruct gather_type {\n  factor_type factor;\n  uint32_t nchanges;\n  gather_type() : nchanges(0) { };\n  gather_type(uint32_t nchanges) : factor(NTOPICS), nchanges(nchanges) { };\n  gather_type& operator+=(const gather_type& other) {\n    factor += other.factor;\n    nchanges += other.nchanges;\n    return *this;\n  }\n}; // end of gather type\n\n\n\n\n\n\n\n/**\n * \\brief The collapsed Gibbs sampler vertex program updates the topic\n * counts for the center vertex and then draws new topic assignments\n * for each edge durring the scatter phase.\n * \n */\nclass cgs_lda_vertex_program :\n  public graphlab::ivertex_program<graph_type, gather_type> {\npublic:\n\n  /**\n   * \\brief At termination we want to disable sampling to allow the\n   * correct final counts to be computed.\n   */\n  static bool DISABLE_SAMPLING; \n\n  /** \\brief gather on all edges */\n  edge_dir_type gather_edges(icontext_type& context,\n                             const vertex_type& vertex) const {\n    return graphlab::ALL_EDGES;\n  } // end of gather_edges\n\n  /**\n   * \\brief Collect the current topic count on each edge.\n   */\n  gather_type gather(icontext_type& context, const vertex_type& vertex,\n                     edge_type& edge) const {\n    gather_type ret(edge.data().nchanges);\n    const assignment_type& assignment = edge.data().assignment;\n    foreach(topic_id_type asg, assignment) {\n      if(asg != NULL_TOPIC) ++ret.factor[asg];\n    }\n    return ret;\n  } // end of gather\n\n\n  /**\n   * \\brief Update the topic count for the center vertex.  This\n   * ensures that the center vertex has the correct topic count before\n   * resampling the topics for each token along each edge.\n   */\n  void apply(icontext_type& context, vertex_type& vertex,\n             const gather_type& sum) {\n    const size_t num_neighbors = vertex.num_in_edges() + vertex.num_out_edges();\n    ASSERT_GT(num_neighbors, 0);\n    // There should be no new edge data since the vertex program has been cleared\n    vertex_data& vdata = vertex.data();\n    ASSERT_EQ(sum.factor.size(), NTOPICS);\n    ASSERT_EQ(vdata.factor.size(), NTOPICS);\n    vdata.nupdates++;\n    vdata.nchanges = sum.nchanges;\n    vdata.factor = sum.factor;\n  } // end of apply\n\n\n  /**\n   * \\brief Scatter on all edges if the computation is on-going.\n   * Computation stops after bunrin or when disable sampling is set to\n   * true.\n   */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const {\n    return (DISABLE_SAMPLING || (BURNIN > 0 && context.elapsed_seconds() > BURNIN))? \n      graphlab::NO_EDGES : graphlab::ALL_EDGES;\n  }; // end of scatter edges\n\n\n  /**\n   * \\brief Draw new topic assignments for each edge token.\n   *\n   * Note that we exploit the GraphLab caching model here by DIRECTLY\n   * modifying the topic counts of adjacent vertices.  Making the\n   * changes immediately visible to any adjacent vertex programs\n   * running on the same machine.  However, these changes will be\n   * overwritten during the apply step and are only used to accelerate\n   * sampling.  This is a potentially dangerous violation of the\n   * abstraction and should be taken with caution.  In our case all\n   * vertex topic counts are preallocated and atomic operations are\n   * used.  In addition during the sampling phase we must be careful\n   * to guard against potentially negative temporary counts.\n   */\n  void scatter(icontext_type& context, const vertex_type& vertex,\n               edge_type& edge) const {\n    factor_type& doc_topic_count =  is_doc(edge.source()) ?\n      edge.source().data().factor : edge.target().data().factor;\n    factor_type& word_topic_count = is_word(edge.source()) ?\n      edge.source().data().factor : edge.target().data().factor;\n    ASSERT_EQ(doc_topic_count.size(), NTOPICS);\n    ASSERT_EQ(word_topic_count.size(), NTOPICS);\n    // run the actual gibbs sampling\n    std::vector<double> prob(NTOPICS);\n    assignment_type& assignment = edge.data().assignment;\n    edge.data().nchanges = 0;\n    foreach(topic_id_type& asg, assignment) {\n      const topic_id_type old_asg = asg;\n      if(asg != NULL_TOPIC) { // construct the cavity\n        --doc_topic_count[asg];\n        --word_topic_count[asg];\n        --GLOBAL_TOPIC_COUNT[asg];\n      }\n      for(size_t t = 0; t < NTOPICS; ++t) {\n        const double n_dt =\n          std::max(count_type(doc_topic_count[t]), count_type(0));\n        const double n_wt =\n          std::max(count_type(word_topic_count[t]), count_type(0));\n        const double n_t  =\n          std::max(count_type(GLOBAL_TOPIC_COUNT[t]), count_type(0));\n        prob[t] = (ALPHA + n_dt) * (BETA + n_wt) / (BETA * NWORDS + n_t);\n      }\n      asg = graphlab::random::multinomial(prob);\n      // asg = std::max_element(prob.begin(), prob.end()) - prob.begin();\n      ++doc_topic_count[asg];\n      ++word_topic_count[asg];\n      ++GLOBAL_TOPIC_COUNT[asg];\n      if(asg != old_asg) {\n        ++edge.data().nchanges;\n      }\n    } // End of loop over each token\n    // singla the other vertex\n    context.signal(get_other_vertex(edge, vertex));\n  } // end of scatter function\n\n}; // end of cgs_lda_vertex_program\n\n\nbool cgs_lda_vertex_program::DISABLE_SAMPLING = false;\n\n\n/**\n * \\brief The icontext type associated with the cgs_lda_vertex program\n * is needed for all aggregators.\n */\ntypedef cgs_lda_vertex_program::icontext_type icontext_type;\n\n\n// ========================================================\n// Aggregators\n\n\n/**\n * \\brief The topk aggregator is used to periodically compute and\n * display the topk most common words in each topic.\n *\n * The number of words is determined by the global variable \\ref TOPK\n * and the interval is determined by the global variable \\ref INTERVAL.\n *\n */\nclass topk_aggregator {\n  typedef std::pair<float, graphlab::vertex_id_type> cw_pair_type;\nprivate:\n  std::vector< std::set<cw_pair_type> > top_words;\n  size_t nchanges, nupdates;\npublic:\n  topk_aggregator(size_t nchanges = 0, size_t nupdates = 0) :\n    nchanges(nchanges), nupdates(nupdates) { }\n\n  topk_aggregator& operator+=(const topk_aggregator& other) {\n    nchanges += other.nchanges;\n    nupdates += other.nupdates;\n    if(other.top_words.empty()) return *this;\n    if(top_words.empty()) top_words.resize(NTOPICS);\n    for(size_t i = 0; i < top_words.size(); ++i) {\n      // Merge the topk\n      top_words[i].insert(other.top_words[i].begin(),\n                          other.top_words[i].end());\n      // Remove excess elements\n      while(top_words[i].size() > TOPK)\n        top_words[i].erase(top_words[i].begin());\n    }\n    return *this;\n  } // end of operator +=\n\n  static topk_aggregator map(icontext_type& context,\n                             const graph_type::vertex_type& vertex) {\n    topk_aggregator ret_value;\n    const vertex_data& vdata = vertex.data();\n    ret_value.nchanges = vdata.nchanges;\n    ret_value.nupdates = vdata.nupdates;\n    if(is_word(vertex)) {\n      const graphlab::vertex_id_type wordid = vertex.id();\n      ret_value.top_words.resize(vdata.factor.size());\n      for(size_t i = 0; i < vdata.factor.size(); ++i) {\n        const cw_pair_type pair(vdata.factor[i], wordid);\n        ret_value.top_words[i].insert(pair);\n      }\n    }\n    return ret_value;\n  } // end of map function\n\n\n  static void finalize(icontext_type& context,\n                       const topk_aggregator& total) {\n    if(context.procid() != 0) return;\n     for(size_t i = 0; i < total.top_words.size(); ++i) {\n      std::cout << \"Topic \" << i << \": \";\n      rev_foreach(cw_pair_type pair, total.top_words[i])  {\n    \n        std::cout << DICTIONARY[pair.second]\n                  << \"(\" << pair.first << \")\" << \", \";\n      }\n      \n      std::cout << std::endl;\n    }\n   \n    std::cout << \"\\nNumber of token changes: \" << total.nchanges << std::endl;\n    std::cout << \"\\nNumber of updates:       \" << total.nupdates << std::endl;\n  } // end of finalize\n}; // end of topk_aggregator struct\n\n\n\n/**\n * \\brief The global counts aggregator computes the total number of\n * tokens in each topic across all words and documents and then\n * updates the \\ref GLOBAL_TOPIC_COUNT variable.\n *\n */\nstruct global_counts_aggregator {\n  typedef graph_type::vertex_type vertex_type;\n  static factor_type map(icontext_type& context, const vertex_type& vertex) {\n    return vertex.data().factor;\n  } // end of map function\n\n  static void finalize(icontext_type& context, const factor_type& total) {\n    size_t sum = 0;\n    for(size_t t = 0; t < total.size(); ++t) {\n      GLOBAL_TOPIC_COUNT[t] =\n        std::max(count_type(total[t]/2), count_type(0));\n      sum += GLOBAL_TOPIC_COUNT[t];\n    }\n    context.cout() << \"Total Tokens: \" << sum << std::endl;\n  } // end of finalize\n}; // end of global_counts_aggregator struct\n\n\n\n/**\n * \\brief The Likelihood aggregators maintains the current estimate of\n * the log-likelihood of the current token assignments.\n *\n *  llik_words_given_topics = ...\n *    ntopics * (gammaln(nwords * beta) - nwords * gammaln(beta)) - ...\n *    sum_t(gammaln( n_t + nwords * beta)) +\n *    sum_w(sum_t(gammaln(n_wt + beta)));\n *\n *  llik_topics = ...\n *    ndocs * (gammaln(ntopics * alpha) - ntopics * gammaln(alpha)) + ...\n *    sum_d(sum_t(gammaln(n_td + alpha)) - gammaln(sum_t(n_td) + ntopics * alpha));\n */\nclass likelihood_aggregator : public graphlab::IS_POD_TYPE {\n  typedef graph_type::vertex_type vertex_type;\n  double lik_words_given_topics;\n  double lik_topics;\npublic:\n  likelihood_aggregator() : lik_words_given_topics(0), lik_topics(0) { }\n\n  likelihood_aggregator& operator+=(const likelihood_aggregator& other) {\n    lik_words_given_topics += other.lik_words_given_topics;\n    lik_topics += other.lik_topics;\n    return *this;\n  } // end of operator +=\n\n  static likelihood_aggregator\n  map(icontext_type& context, const vertex_type& vertex) {\n    using boost::math::lgamma;\n    const factor_type& factor = vertex.data().factor;\n    ASSERT_EQ(factor.size(), NTOPICS);\n   likelihood_aggregator ret;\n    if(is_word(vertex)) {\n      for(size_t t = 0; t < NTOPICS; ++t) {\n        const double value = std::max(count_type(factor[t]), count_type(0));\n        ret.lik_words_given_topics += lgamma(value + BETA);\n      }\n    } else {  ASSERT_TRUE(is_doc(vertex));\n      double ntokens_in_doc = 0;\n      for(size_t t = 0; t < NTOPICS; ++t) {\n        const double value = std::max(count_type(factor[t]), count_type(0));\n        ret.lik_topics += lgamma(value + ALPHA);\n        ntokens_in_doc += factor[t];\n      }\n      ret.lik_topics -= lgamma(ntokens_in_doc + NTOPICS * ALPHA);\n    }\n    return ret;\n  } // end of map function\n\n  static void finalize(icontext_type& context, const likelihood_aggregator& total) {\n    using boost::math::lgamma;\n    // Address the global sum terms\n    double denominator = 0;\n    for(size_t t = 0; t < NTOPICS; ++t) {\n      denominator += lgamma(GLOBAL_TOPIC_COUNT[t] + NWORDS * BETA);\n    } // end of for loop\n\n    const double lik_words_given_topics =\n      NTOPICS * (lgamma(NWORDS * BETA) - NWORDS * lgamma(BETA)) -\n      denominator + total.lik_words_given_topics;\n\n    const double lik_topics =\n      NDOCS * (lgamma(NTOPICS * ALPHA) - NTOPICS * lgamma(ALPHA)) +\n      total.lik_topics;\n\n    const double lik = lik_words_given_topics + lik_topics;\n    context.cout() << \"Likelihood: \" << lik << std::endl;\n  } // end of finalize\n}; // end of likelihood_aggregator struct\n\n\n\n/**\n * \\brief The selective signal functions are used to signal only the\n * vertices corresponding to words or documents.  This is done by\n * using the iengine::map_reduce_vertices function.\n */\nstruct signal_only {\n  /**\n   * \\brief Signal only the document vertices and skip the word\n   * vertices.\n   */ \n  static graphlab::empty\n  docs(icontext_type& context, const graph_type::vertex_type& vertex) {\n    if(is_doc(vertex)) context.signal(vertex);\n    return graphlab::empty();\n  } // end of signal_docs\n \n /**\n  * \\brief Signal only the word vertices and skip the document\n  * vertices.\n  */\n  static graphlab::empty\n  words(icontext_type& context, const graph_type::vertex_type& vertex) {\n    if(is_word(vertex)) context.signal(vertex);\n    return graphlab::empty();\n  } // end of signal_words\n}; // end of selective_only\n\n\n\n\n\n\n/**\n * \\brief Load the dictionary global variable from the file containing\n * the terms (one term per line).\n *\n * Note that while graphs can be loaded from multiple files the\n * dictionary must be in a single file.  The dictionary is loaded\n * entirely into memory and used to display word clouds and the top\n * terms in each topic.\n *\n * \\param [in] fname the file containing the dictionary data.  The\n * data can be located on HDFS and can also be gzipped (must end in\n * \".gz\").\n * \n */\nbool load_dictionary(const std::string& fname)  {\n  // std::cout << \"staring load on: \"\n  //           << graphlab::get_local_ip_as_str() << std::endl;\n  const bool gzip = boost::ends_with(fname, \".gz\");\n  // test to see if the graph_dir is an hadoop path\n \n    std::cout << \"opening: \" << fname << std::endl;\n    std::ifstream in_file(fname.c_str(),\n                          std::ios_base::in | std::ios_base::binary);\n    boost::iostreams::filtering_stream<boost::iostreams::input> fin;\n    fin.push(in_file);\n    if(!fin.good() || !fin.good()) {\n      logstream(LOG_ERROR) << \"Error loading dictionary: \"\n                           << fname << std::endl;\n      return false;\n    }\n    std::string term;\n    std::cout << \"Loooping\" << std::endl;\n    while(std::getline(fin, term).good()) DICTIONARY.push_back(term);\n    fin.pop();\n    in_file.close();\n    // std::cout << \"Finished load on: \"\n  //           << graphlab::get_local_ip_as_str() << std::endl;\n  std::cout << \"Dictionary Size: \" << DICTIONARY.size() << std::endl;\n  return true;\n} // end of load dictionary\n\n\n\n\nstruct count_saver {\n  bool save_words;\n  count_saver(bool save_words) : save_words(save_words) { }\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  std::string save_vertex(const vertex_type& vertex) const {\n    // Skip saving vertex data if the vertex type is not consistent\n    // with the save type\n    if((save_words && is_doc(vertex)) ||\n       (!save_words && is_word(vertex))) return \"\";\n    // Proceed to save\n    std::stringstream strm;\n    if(save_words) {\n      const graphlab::vertex_id_type vid = vertex.id();\n      strm << vid << '\\t';\n    } else { // save documents\n      const graphlab::vertex_id_type vid = (-vertex.id()) - 2;\n      strm << vid << '\\t';\n    }\n    const factor_type& factor = vertex.data().factor;\n    for(size_t i = 0; i < factor.size(); ++i) { \n      strm << factor[i];\n      if(i+1 < factor.size()) strm << '\\t';\n    }\n    strm << '\\n';\n    return strm.str();\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\"; //nop\n  }\n}; // end of prediction_saver\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b82ed5dd370aa2360539f0b427444a32480c20e1", "size": 22556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "graphlab_toolkit_ports/lda/cgs_lda_vertexprogram.hpp", "max_stars_repo_name": "libingzheren/GraphChi", "max_stars_repo_head_hexsha": "cd960212ebc171bacbd3169e4c9bcd44e680aadb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T08:49:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T06:51:44.000Z", "max_issues_repo_path": "graphlab_toolkit_ports/lda/cgs_lda_vertexprogram.hpp", "max_issues_repo_name": "mrgloom/graphchi-cpp", "max_issues_repo_head_hexsha": "7dfaa37a9da8f5d8901fc95435f98fb8844c7217", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphlab_toolkit_ports/lda/cgs_lda_vertexprogram.hpp", "max_forks_repo_name": "mrgloom/graphchi-cpp", "max_forks_repo_head_hexsha": "7dfaa37a9da8f5d8901fc95435f98fb8844c7217", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-02T06:17:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T18:54:05.000Z", "avg_line_length": 29.6399474376, "max_line_length": 85, "alphanum_fraction": 0.6575190637, "num_tokens": 5598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.04672496260843418, "lm_q1q2_score": 0.020817351553670045}}
{"text": "// Copyright (C) 2007 The Trustees of Indiana University.\r\n\r\n// Use, modification and distribution is subject to the Boost Software\r\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Douglas Gregor\r\n//           Andrew Lumsdaine\r\n\r\n/**************************************************************************\r\n * This source file implements the Delta-stepping algorithm:              *\r\n *                                                                        *\r\n *   Ulrich Meyer and Peter Sanders. Parallel Shortest Path for Arbitrary *\r\n *   Graphs. In Proceedings from the 6th International Euro-Par           *\r\n *   Conference on Parallel Processing, pages 461--470, 2000.             *\r\n *                                                                        * \r\n *   Ulrich Meyer, Peter Sanders: [Delta]-stepping: A Parallelizable      *\r\n *   Shortest Path Algorithm. J. Algorithms 49(1): 114-152, 2003.         *\r\n *                                                                        *\r\n * There are several potential optimizations we could still perform for   *\r\n * this algorithm implementation:                                         *\r\n *                                                                        *\r\n *   - Implement \"shortcuts\", which bound the number of reinsertions      *\r\n *     in a single bucket (to one). The computation of shortcuts looks    *\r\n *     expensive in a distributed-memory setting, but it could be         *\r\n *     ammortized over many queries.                                      *\r\n *                                                                        *\r\n *   - The size of the \"buckets\" data structure can be bounded to         *\r\n *     max_edge_weight/delta buckets, if we treat the buckets as a        *\r\n *     circular array.                                                    *\r\n *                                                                        *\r\n *   - If we partition light/heavy edges ahead of time, we could improve  *\r\n *     relaxation performance by only iterating over the right portion    *\r\n *     of the out-edge list each time.                                    *\r\n *                                                                        *\r\n *   - Implement a more sophisticated algorithm for guessing \"delta\",     *\r\n *     based on the shortcut-finding algorithm.                           *\r\n **************************************************************************/\r\n#ifndef BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_HPP\r\n#define BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_HPP\r\n\r\n#ifndef BOOST_GRAPH_USE_MPI\r\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\r\n#endif\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <limits>\r\n#include <list>\r\n#include <vector>\r\n#include <boost/graph/parallel/container_traits.hpp>\r\n#include <boost/graph/parallel/properties.hpp>\r\n#include <boost/graph/distributed/detail/dijkstra_shortest_paths.hpp>\r\n#include <utility> // for std::pair\r\n#include <functional> // for std::logical_or\r\n#include <boost/graph/parallel/algorithm.hpp> // for all_reduce\r\n#include <cassert>\r\n#include <algorithm> // for std::min, std::max\r\n#include <boost/graph/parallel/simple_trigger.hpp>\r\n\r\n#ifdef PBGL_DELTA_STEPPING_DEBUG\r\n#  include <iostream> // for std::cerr\r\n#endif\r\n\r\nnamespace boost { namespace graph { namespace distributed {\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\nclass delta_stepping_impl {\r\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n  typedef typename graph_traits<Graph>::degree_size_type Degree;\r\n  typedef typename property_traits<EdgeWeightMap>::value_type Dist;\r\n  typedef typename boost::graph::parallel::process_group_type<Graph>::type \r\n    ProcessGroup;\r\n\r\n  typedef std::list<Vertex> Bucket;\r\n  typedef typename Bucket::iterator BucketIterator;\r\n  typedef typename std::vector<Bucket*>::size_type BucketIndex;\r\n\r\n  typedef detail::dijkstra_msg_value<DistanceMap, PredecessorMap> MessageValue;\r\n\r\n  enum { \r\n    // Relax a remote vertex. The message contains a pair<Vertex,\r\n    // MessageValue>, the first part of which is the vertex whose\r\n    // tentative distance is being relaxed and the second part\r\n    // contains either the new distance (if there is no predecessor\r\n    // map) or a pair with the distance and predecessor.\r\n    msg_relax \r\n  };\r\n\r\npublic:\r\n  delta_stepping_impl(const Graph& g,\r\n                      PredecessorMap predecessor, \r\n                      DistanceMap distance, \r\n                      EdgeWeightMap weight,\r\n                      Dist delta);\r\n\r\n  delta_stepping_impl(const Graph& g,\r\n                      PredecessorMap predecessor, \r\n                      DistanceMap distance, \r\n                      EdgeWeightMap weight);\r\n\r\n  void run(Vertex s);\r\n\r\nprivate:\r\n  // Relax the edge (u, v), creating a new best path of distance x.\r\n  void relax(Vertex u, Vertex v, Dist x);\r\n\r\n  // Synchronize all of the processes, by receiving all messages that\r\n  // have not yet been received.\r\n  void synchronize();\r\n\r\n  // Handle a relax message that contains only the target and\r\n  // distance. This kind of message will be received when the\r\n  // predecessor map is a dummy_property_map.\r\n  void handle_relax_message(Vertex v, Dist x) { relax(v, v, x); }\r\n\r\n  // Handle a relax message that contains the source (predecessor),\r\n  // target, and distance. This kind of message will be received when\r\n  // the predecessor map is not a dummy_property_map.\r\n  void handle_relax_message(Vertex v, const std::pair<Dist, Vertex>& p)\r\n  { relax(p.second, v, p.first); }\r\n  \r\n  // Setup triggers for msg_relax messages\r\n  void setup_triggers();\r\n\r\n  void handle_msg_relax(int /*source*/, int /*tag*/,\r\n                        const std::pair<Vertex, typename MessageValue::type>& data,\r\n                        trigger_receive_context)\r\n  { handle_relax_message(data.first, data.second); }\r\n\r\n  const Graph& g;\r\n  PredecessorMap predecessor;\r\n  DistanceMap distance;\r\n  EdgeWeightMap weight;\r\n  Dist delta;\r\n  ProcessGroup pg;\r\n  typename property_map<Graph, vertex_owner_t>::const_type owner;\r\n  typename property_map<Graph, vertex_local_t>::const_type local;\r\n\r\n  // A \"property map\" that contains the position of each vertex in\r\n  // whatever bucket it resides in.\r\n  std::vector<BucketIterator> position_in_bucket;\r\n\r\n  // Bucket data structure. The ith bucket contains all local vertices\r\n  // with (tentative) distance in the range [i*delta,\r\n  // (i+1)*delta). \r\n  std::vector<Bucket*> buckets;\r\n\r\n  // This \"dummy\" list is used only so that we can initialize the\r\n  // position_in_bucket property map with non-singular iterators. This\r\n  // won't matter for most implementations of the C++ Standard\r\n  // Library, but it avoids undefined behavior and allows us to run\r\n  // with library \"debug modes\".\r\n  std::list<Vertex> dummy_list;\r\n\r\n  // A \"property map\" that states which vertices have been deleted\r\n  // from the bucket in this iteration.\r\n  std::vector<bool> vertex_was_deleted;\r\n};\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\ndelta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>::\r\ndelta_stepping_impl(const Graph& g,\r\n                    PredecessorMap predecessor, \r\n                    DistanceMap distance, \r\n                    EdgeWeightMap weight,\r\n                    Dist delta)\r\n    : g(g),\r\n      predecessor(predecessor),\r\n      distance(distance),\r\n      weight(weight),\r\n      delta(delta),\r\n      pg(boost::graph::parallel::process_group_adl(g), attach_distributed_object()),\r\n      owner(get(vertex_owner, g)),\r\n      local(get(vertex_local, g))\r\n{\r\n  setup_triggers();\r\n}\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\ndelta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>::\r\ndelta_stepping_impl(const Graph& g,\r\n                    PredecessorMap predecessor, \r\n                    DistanceMap distance, \r\n                    EdgeWeightMap weight)\r\n    : g(g),\r\n      predecessor(predecessor),\r\n      distance(distance),\r\n      weight(weight),\r\n      pg(boost::graph::parallel::process_group_adl(g), attach_distributed_object()),\r\n      owner(get(vertex_owner, g)),\r\n      local(get(vertex_local, g))\r\n{\r\n  using boost::parallel::all_reduce;\r\n  using boost::parallel::maximum;\r\n  using std::max;\r\n\r\n  // Compute the maximum edge weight and degree\r\n  Dist max_edge_weight = 0;\r\n  Degree max_degree = 0;\r\n  BGL_FORALL_VERTICES_T(u, g, Graph) {\r\n    max_degree = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_degree, out_degree(u, g));\r\n    BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\r\n      max_edge_weight = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_edge_weight, get(weight, e));\r\n  }\r\n\r\n  max_edge_weight = all_reduce(pg, max_edge_weight, maximum<Dist>());\r\n  max_degree = all_reduce(pg, max_degree, maximum<Degree>());\r\n\r\n  // Take a guess at delta, based on what works well for random\r\n  // graphs.\r\n  delta = max_edge_weight / max_degree;\r\n  if (delta == 0)\r\n    delta = 1;\r\n\r\n  setup_triggers();\r\n}\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\nvoid\r\ndelta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>::\r\nrun(Vertex s)\r\n{\r\n  Dist inf = (std::numeric_limits<Dist>::max)();\r\n\r\n  // None of the vertices are stored in the bucket.\r\n  position_in_bucket.clear();\r\n  position_in_bucket.resize(num_vertices(g), dummy_list.end());\r\n\r\n  // None of the vertices have been deleted\r\n  vertex_was_deleted.clear();\r\n  vertex_was_deleted.resize(num_vertices(g), false);\r\n\r\n  // No path from s to any other vertex, yet\r\n  BGL_FORALL_VERTICES_T(v, g, Graph)\r\n    put(distance, v, inf);\r\n\r\n  // The distance to the starting node is zero\r\n  if (get(owner, s) == process_id(pg))\r\n    // Put \"s\" into its bucket (bucket 0)\r\n    relax(s, s, 0);\r\n  else\r\n    // Note that we know the distance to s is zero\r\n    cache(distance, s, 0);\r\n\r\n  BucketIndex max_bucket = (std::numeric_limits<BucketIndex>::max)();\r\n  BucketIndex current_bucket = 0;\r\n  do {\r\n    // Synchronize with all of the other processes.\r\n    synchronize();\r\n\r\n    // Find the next bucket that has something in it.\r\n    while (current_bucket < buckets.size() \r\n           && (!buckets[current_bucket] || buckets[current_bucket]->empty()))\r\n      ++current_bucket;\r\n    if (current_bucket >= buckets.size())\r\n      current_bucket = max_bucket;\r\n\r\n#ifdef PBGL_DELTA_STEPPING_DEBUG\r\n    std::cerr << \"#\" << process_id(pg) << \": lowest bucket is #\" \r\n              << current_bucket << std::endl;\r\n#endif\r\n    // Find the smallest bucket (over all processes) that has vertices\r\n    // that need to be processed.\r\n    using boost::parallel::all_reduce;\r\n    using boost::parallel::minimum;\r\n    current_bucket = all_reduce(pg, current_bucket, minimum<BucketIndex>());\r\n\r\n    if (current_bucket == max_bucket)\r\n      // There are no non-empty buckets in any process; exit. \r\n      break;\r\n\r\n#ifdef PBGL_DELTA_STEPPING_DEBUG\r\n    if (process_id(pg) == 0)\r\n      std::cerr << \"Processing bucket #\" << current_bucket << std::endl;\r\n#endif\r\n\r\n    // Contains the set of vertices that have been deleted in the\r\n    // relaxation of \"light\" edges. Note that we keep track of which\r\n    // vertices were deleted with the property map\r\n    // \"vertex_was_deleted\".\r\n    std::vector<Vertex> deleted_vertices;\r\n\r\n    // Repeatedly relax light edges\r\n    bool nonempty_bucket;\r\n    do {\r\n      // Someone has work to do in this bucket.\r\n\r\n      if (current_bucket < buckets.size() && buckets[current_bucket]) {\r\n        Bucket& bucket = *buckets[current_bucket];\r\n        // For each element in the bucket\r\n        while (!bucket.empty()) {\r\n          Vertex u = bucket.front();\r\n\r\n#ifdef PBGL_DELTA_STEPPING_DEBUG\r\n          std::cerr << \"#\" << process_id(pg) << \": processing vertex \" \r\n                    << get(vertex_global, g, u).second << \"@\" \r\n                    << get(vertex_global, g, u).first\r\n                    << std::endl;\r\n#endif\r\n\r\n          // Remove u from the front of the bucket\r\n          bucket.pop_front();\r\n          \r\n          // Insert u into the set of deleted vertices, if it hasn't\r\n          // been done already.\r\n          if (!vertex_was_deleted[get(local, u)]) {\r\n            vertex_was_deleted[get(local, u)] = true;\r\n            deleted_vertices.push_back(u);\r\n          }\r\n\r\n          // Relax each light edge. \r\n          Dist u_dist = get(distance, u);\r\n          BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\r\n            if (get(weight, e) <= delta) // light edge\r\n              relax(u, target(e, g), u_dist + get(weight, e));\r\n        }\r\n      }\r\n\r\n      // Synchronize with all of the other processes.\r\n      synchronize();\r\n\r\n      // Is the bucket empty now?\r\n      nonempty_bucket = (current_bucket < buckets.size() \r\n                         && buckets[current_bucket]\r\n                         && !buckets[current_bucket]->empty());\r\n     } while (all_reduce(pg, nonempty_bucket, std::logical_or<bool>()));\r\n\r\n    // Relax heavy edges for each of the vertices that we previously\r\n    // deleted.\r\n    for (typename std::vector<Vertex>::iterator iter = deleted_vertices.begin();\r\n         iter != deleted_vertices.end(); ++iter) {\r\n      // Relax each heavy edge. \r\n      Vertex u = *iter;\r\n      Dist u_dist = get(distance, u);\r\n      BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\r\n        if (get(weight, e) > delta) // heavy edge\r\n          relax(u, target(e, g), u_dist + get(weight, e)); \r\n    }\r\n\r\n    // Go to the next bucket: the current bucket must already be empty.\r\n    ++current_bucket;\r\n  } while (true);\r\n\r\n  // Delete all of the buckets.\r\n  for (typename std::vector<Bucket*>::iterator iter = buckets.begin();\r\n       iter != buckets.end(); ++iter) {\r\n    if (*iter) {\r\n      delete *iter;\r\n      *iter = 0;\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\nvoid\r\ndelta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>::\r\nrelax(Vertex u, Vertex v, Dist x) \r\n{\r\n#ifdef PBGL_DELTA_STEPPING_DEBUG\r\n  std::cerr << \"#\" << process_id(pg) << \": relax(\" \r\n            << get(vertex_global, g, u).second << \"@\" \r\n            << get(vertex_global, g, u).first << \", \" \r\n            << get(vertex_global, g, v).second << \"@\" \r\n            << get(vertex_global, g, v).first << \", \"\r\n            << x << \")\" << std::endl;\r\n#endif\r\n\r\n  if (x < get(distance, v)) {\r\n    // We're relaxing the edge to vertex v.\r\n    if (get(owner, v) == process_id(pg)) {\r\n      // Compute the new bucket index for v\r\n      BucketIndex new_index = static_cast<BucketIndex>(x / delta);\r\n      \r\n      // Make sure there is enough room in the buckets data structure.\r\n      if (new_index >= buckets.size()) buckets.resize(new_index + 1, 0);\r\n\r\n      // Make sure that we have allocated the bucket itself.\r\n      if (!buckets[new_index]) buckets[new_index] = new Bucket;\r\n\r\n      if (get(distance, v) != (std::numeric_limits<Dist>::max)()\r\n          && !vertex_was_deleted[get(local, v)]) {\r\n        // We're moving v from an old bucket into a new one. Compute\r\n        // the old index, then splice it in.\r\n        BucketIndex old_index \r\n          = static_cast<BucketIndex>(get(distance, v) / delta);\r\n        buckets[new_index]->splice(buckets[new_index]->end(),\r\n                                   *buckets[old_index],\r\n                                   position_in_bucket[get(local, v)]);\r\n      } else {\r\n        // We're inserting v into a bucket for the first time. Put it\r\n        // at the end.\r\n        buckets[new_index]->push_back(v);\r\n      }\r\n\r\n      // v is now at the last position in the new bucket\r\n      position_in_bucket[get(local, v)] = buckets[new_index]->end();\r\n      --position_in_bucket[get(local, v)];\r\n\r\n      // Update predecessor and tentative distance information\r\n      put(predecessor, v, u);\r\n      put(distance, v, x);\r\n    } else {\r\n#ifdef PBGL_DELTA_STEPPING_DEBUG\r\n      std::cerr << \"#\" << process_id(pg) << \": sending relax(\" \r\n                << get(vertex_global, g, u).second << \"@\" \r\n                << get(vertex_global, g, u).first << \", \" \r\n                << get(vertex_global, g, v).second << \"@\" \r\n                << get(vertex_global, g, v).first << \", \"\r\n            << x << \") to \" << get(owner, v) << std::endl;\r\n      \r\n#endif\r\n      // The vertex is remote: send a request to the vertex's owner\r\n      send(pg, get(owner, v), msg_relax, \r\n           std::make_pair(v, MessageValue::create(x, u)));\r\n\r\n      // Cache tentative distance information\r\n      cache(distance, v, x);\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\nvoid\r\ndelta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>::\r\nsynchronize()\r\n{\r\n  using boost::parallel::synchronize;\r\n\r\n  // Synchronize at the process group level.\r\n  synchronize(pg);\r\n\r\n  // Receive any relaxation request messages.\r\n//   typedef typename ProcessGroup::process_id_type process_id_type;\r\n//   while (optional<std::pair<process_id_type, int> > stp = probe(pg)) {\r\n//     // Receive the relaxation message\r\n//     assert(stp->second == msg_relax);\r\n//     std::pair<Vertex, typename MessageValue::type> data;\r\n//     receive(pg, stp->first, stp->second, data);\r\n\r\n//     // Turn it into a \"relax\" call\r\n//     handle_relax_message(data.first, data.second);\r\n//   }\r\n}\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\nvoid \r\ndelta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>::\r\nsetup_triggers() \r\n{\r\n  using boost::graph::parallel::simple_trigger;\r\n        \r\n  simple_trigger(pg, msg_relax, this, \r\n                 &delta_stepping_impl::handle_msg_relax);\r\n}\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\nvoid \r\ndelta_stepping_shortest_paths\r\n  (const Graph& g,\r\n   typename graph_traits<Graph>::vertex_descriptor s,\r\n   PredecessorMap predecessor, DistanceMap distance, EdgeWeightMap weight,\r\n   typename property_traits<EdgeWeightMap>::value_type delta)\r\n{\r\n  // The \"distance\" map needs to act like one, retrieving the default\r\n  // value of infinity.\r\n  set_property_map_role(vertex_distance, distance);\r\n\r\n  // Construct the implementation object, which will perform all of\r\n  // the actual work.\r\n  delta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>\r\n    impl(g, predecessor, distance, weight, delta);\r\n\r\n  // Run the delta-stepping algorithm. The results will show up in\r\n  // \"predecessor\" and \"weight\".\r\n  impl.run(s);\r\n}\r\n\r\ntemplate<typename Graph, typename PredecessorMap, typename DistanceMap, \r\n         typename EdgeWeightMap>\r\nvoid \r\ndelta_stepping_shortest_paths\r\n  (const Graph& g,\r\n   typename graph_traits<Graph>::vertex_descriptor s,\r\n   PredecessorMap predecessor, DistanceMap distance, EdgeWeightMap weight)\r\n{\r\n  // The \"distance\" map needs to act like one, retrieving the default\r\n  // value of infinity.\r\n  set_property_map_role(vertex_distance, distance);\r\n\r\n  // Construct the implementation object, which will perform all of\r\n  // the actual work.\r\n  delta_stepping_impl<Graph, PredecessorMap, DistanceMap, EdgeWeightMap>\r\n    impl(g, predecessor, distance, weight);\r\n\r\n  // Run the delta-stepping algorithm. The results will show up in\r\n  // \"predecessor\" and \"weight\".\r\n  impl.run(s);\r\n}\r\n   \r\n} } } // end namespace boost::graph::distributed\r\n\r\n#endif // BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_HPP\r\n", "meta": {"hexsha": "742f12c35413c89fecc796910dc045ad4fd1a910", "size": 19928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/delta_stepping_shortest_paths.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/delta_stepping_shortest_paths.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/delta_stepping_shortest_paths.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 38.7704280156, "max_line_length": 102, "alphanum_fraction": 0.6196808511, "num_tokens": 4407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.0467249533163039, "lm_q1q2_score": 0.020817346725758617}}
{"text": "/*=========================================================================\n *\n *  Copyright 2011-2013 The University of North Carolina at Chapel Hill\n *  All rights reserved.\n *\n *  Licensed under the MADAI Software License. You may obtain a copy of\n *  this license at\n *\n *         https://madai-public.cs.unc.edu/visualization/software-license/\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*/\n#include <cassert> // assert\n#include <cstdlib> // std::atof\n#include <cmath> // std::sqrt, std::pow\n#include <iostream> // std::cout\n#include <fstream> // std::ifstream\n#include <vector> // std::vector\n#include <string> // std::string\n#include <sstream> // std::stringstream\n#include <iomanip> // std::setw\n#include <limits> // inifity\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n\n\n#include \"ApplicationUtilities.h\"\n#include \"GaussianProcessEmulatorDirectoryFormatIO.h\"\n#include \"Paths.h\"\n#include \"System.h\"\n\nint main(int argc, char ** argv) {\n  if (argc < 3) {\n    std::cerr\n      << \"Usage\\n  \" << argv[0]\n      << \" statistics_directory trace_file\\n\\n\";\n    return EXIT_FAILURE;\n  }\n  std::string statisticsDirectory( argv[1] );\n  madai::EnsurePathSeparatorAtEnd( statisticsDirectory );\n\n  std::vector< madai::Parameter > parameters;\n  int numberOfParameters = 0;\n\n  if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseParameters(\n           parameters, numberOfParameters, statisticsDirectory, false )) {\n    std::cerr\n      << \"Could not read parameters from prior file '\"\n      << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << \"'\\n\";\n    return EXIT_FAILURE;\n  }\n  assert (numberOfParameters = parameters.size());\n\n  std::vector< std::string > outputNames;\n  int numberOfOutputs = 0;\n\n  if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseOutputs(\n           outputNames, numberOfOutputs, statisticsDirectory, false )) {\n    std::cerr\n      << \"Could not read outputs from prior file '\"\n      << statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << \"'\\n\";\n    return EXIT_FAILURE;\n  }\n  assert (numberOfOutputs = outputNames.size());\n\n  std::string traceFile( statisticsDirectory );\n  traceFile.append( argv[2] );\n\n  if ( !madai::System::IsFile( traceFile ) ) {\n    std::cerr << \"Trace file '\" << traceFile << \"' does not exist or is a directory.\\n\";\n    return EXIT_FAILURE;\n  }\n\n  std::ifstream file(traceFile.c_str(), std::ios_base::in | std::ios_base::binary);\n  if ( !file.good() ) {\n    std::cerr << \"Error reading trace file '\" << traceFile << \"'.\\n\";\n    return EXIT_FAILURE;\n  }\n  boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;\n  if( madai::IsTraceCompressed(traceFile) ) {\n      inbuf.push(boost::iostreams::gzip_decompressor());\n  }\n  inbuf.push(file);\n  std::istream trace(&inbuf);\n\n  std::string header;\n  std::getline(trace,header);\n  std::vector<std::string> headers = madai::SplitString(header, ',');\n\n  int numberOfFields = headers.size();\n  bool gradientsPresent = false;\n  if( numberOfFields == numberOfParameters + 3*numberOfOutputs + 1 ) {\n    numberOfFields -= 2*numberOfOutputs;\n    gradientsPresent = true;\n  }\n  assert(numberOfFields == numberOfParameters + numberOfOutputs + 1);\n\n  std::string line;\n  size_t lineCount = 0, bestIndex = 0;\n  std::vector< double > sums(numberOfFields - 1, 0.0);\n  std::vector< std::vector< double > > values(numberOfFields - 1);\n\n  double bestLogLikelihood = -std::numeric_limits< double >::infinity();\n\n  while (std::getline(trace,line)) {\n    std::vector<std::string> fields = madai::SplitString(line, ',');\n    assert(numberOfFields == (int) fields.size() - (gradientsPresent?2*numberOfOutputs:0));\n    for (int i = 0; i < numberOfFields - 1; ++i) {\n      double value = std::atof(fields[i].c_str());\n      values[i].push_back(value);\n      sums[i] += value;\n    }\n    double logLikelihood = std::atof(fields[numberOfFields - 1].c_str());\n    if (logLikelihood > bestLogLikelihood) {\n      bestLogLikelihood = logLikelihood;\n      bestIndex = lineCount;\n    }\n    ++lineCount;\n  }\n\n  file.close();\n  std::vector< double > means(numberOfFields - 1,0.0);\n\n  std::vector< double > priorStdDev(numberOfFields - 1,0.0);\n  for (int i = 0; i < numberOfParameters; ++i) {\n    priorStdDev[i] =\n      parameters[i].GetPriorDistribution()->GetStandardDeviation();\n  }\n  std::cout << std::setw(14) << \"parameter\";\n  std::cout << std::setw(14) << \"mean\";\n  std::cout << std::setw(14) << \"std.dev.\";\n  std::cout << std::setw(14) << \"scaled dev.\";\n  std::cout << std::setw(14) << \"best value\";\n  std::cout << '\\n';\n\n  for (int i = 0; i < numberOfFields - 1; ++i) {\n    means[i] = sums[i] / lineCount;\n  }\n  for (int i = 0; i < numberOfParameters; ++i) {\n    double variance = 0.0;\n    for (size_t k = 0; k < lineCount; ++k) {\n      variance += std::pow(values[i][k] - means[i], 2);\n    }\n    variance /= lineCount;\n    std::cout\n      << std::setw(14) << parameters[i].m_Name\n      << std::setw(14) << means[i]\n      << std::setw(14) << std::sqrt(variance)\n      << std::setw(14) << std::sqrt(variance) / priorStdDev[i]\n      << std::setw(14) << values[i][bestIndex]\n      << '\\n';\n  }\n\n  // Print the relative log-likelihood from the best point\n  std::cout << \"\\nbest log likelihood\\n\";\n  std::cout << std::setw(14) << bestLogLikelihood << \"\\n\";\n\n  std::vector< std::vector< double > > covariancematrix;\n  for (int i = 0; i < numberOfFields - 1; ++i)\n    covariancematrix.push_back(std::vector< double >(numberOfFields - 1, 0.0));\n\n  for (int i = 0; i < numberOfFields - 1; ++i) {\n    for (int j = 0; j <= i; ++j) {\n      double covariance = 0.0;\n      for (size_t k = 0; k < lineCount; ++k) {\n        covariance += (values[i][k] - means[i]) * (values[j][k] - means[j]);\n      }\n      covariancematrix[i][j] = covariance /= lineCount;\n      if (i != j)\n        covariancematrix[j][i] = covariancematrix[i][j];\n    }\n  }\n\n  std::cout << \"\\ncovariance:\\n\";\n  std::cout << std::setw(14) << \"\";\n  for (int j = 0; j < numberOfParameters; ++j)\n    std::cout << std::setw(14) << parameters[j].m_Name;\n  std::cout << \"\\n\";\n  for (int i = 0; i < numberOfParameters; ++i) {\n    std::cout << std::setw(14) << parameters[i].m_Name;\n    for (int j = 0; j < numberOfParameters; ++j) {\n      std::cout << std::setw(14) << covariancematrix[i][j];\n    }\n    std::cout << \"\\n\";\n  }\n\n  std::cout << \"\\nscaled covariance:\\n\";\n  std::cout << std::setw(14) << \"\";\n  for (int j = 0; j < numberOfParameters; ++j)\n    std::cout << std::setw(14) << parameters[j].m_Name;\n  std::cout << \"\\n\";\n  for (int i = 0; i < numberOfParameters; ++i) {\n    std::cout << std::setw(14) << parameters[i].m_Name;\n    for (int j = 0; j < numberOfParameters; ++j) {\n      std::cout << std::setw(14) << covariancematrix[i][j] / (\n          priorStdDev[i] * priorStdDev[j]);\n    }\n    std::cout << \"\\n\";\n  }\n\n  std::cout << \"\\nobservable-parameter correlation:\\n\";\n  std::cout << std::setw(14) << \"\";\n  for (int j = 0; j < numberOfParameters; ++j)\n    std::cout << std::setw(14) << parameters[j].m_Name;\n  std::cout << \"\\n\";\n  for (int i = 0; i < numberOfOutputs; ++i) {\n    std::cout << std::setw(14) << outputNames[i];\n    for (int j = 0; j < numberOfParameters; ++j) {\n      std::cout << std::setw(14) << covariancematrix[numberOfParameters + i][j] / (\n          std::sqrt(covariancematrix[numberOfParameters + i][numberOfParameters + i]*\n          covariancematrix[j][j]));\n    }\n    std::cout << \"\\n\";\n  }\n\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "fd30f287b6c99288bd4099528e9b088e4265f1f8", "size": 7822, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "applications/madai_analyze_trace.cxx", "max_stars_repo_name": "scottedwardpratt/MADAI", "max_stars_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-28T20:14:23.000Z", "max_issues_repo_path": "applications/madai_analyze_trace.cxx", "max_issues_repo_name": "scottedwardpratt/MADAI", "max_issues_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/madai_analyze_trace.cxx", "max_forks_repo_name": "scottedwardpratt/MADAI", "max_forks_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-08-20T14:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-28T20:15:23.000Z", "avg_line_length": 34.9196428571, "max_line_length": 91, "alphanum_fraction": 0.6130145743, "num_tokens": 2235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.051082737679360814, "lm_q1q2_score": 0.020807705957634776}}
{"text": "/*********************************************************************************\n*  This file is part of reference implementation of SIGGRAPH Asia 2021 Paper     *\n*  `Efficient and Robust Discrete Conformal Equivalence with Boundary`           *\n*  v1.0                                                                          *\n*                                                                                *\n*  The MIT License                                                               *\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 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 NON INFRINGEMENT. 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*  Author(s):                                                                    *\n*  Marcel Campen, Institute for Computer Science, Osnabrück University, Germany. *\n*  Ryan Capouellez, Hanxiao Shen, Leyi Zhu, Daniele Panozzo, Denis Zorin,        *\n*  Courant Institute of Mathematical Sciences, New York University, USA          *\n*                                          *                                     *\n*********************************************************************************/\n\n#include \"Halfedge.hh\"\n#include <Eigen/Sparse>\n\nvoid FV_to_NOB(const std::vector<std::vector<int>> &F,\n               std::vector<int> &next_he,\n               std::vector<int> &opp,\n               std::vector<int> &bnd_loops,\n               std::vector<int> &vtx_reindex)\n{\n    // Get the cumulative sum of the number of halfedges per face\n    int n_f = F.size();\n    int n_he = 0;\n    std::vector<int> F_he_cumsum(n_f);\n    for (int i = 0; i < n_f; ++i)\n    {\n        n_he += F[i].size();\n        F_he_cumsum[i] = n_he;\n    }\n\n    // Create a list of indices of halfedges per face, sequentially numbered, not including\n    // boundary-loop faces\n    std::vector<std::vector<int>> F_he(n_f);\n    F_he[0] = range(0, F_he_cumsum[0]);\n    for (int i = 1; i < n_f; ++i)\n    {\n        F_he[i] = range(F_he_cumsum[i-1], F_he_cumsum[i]);\n    }\n    // Create the per face next halfedge map\n    std::vector<std::vector<int>> F_n(n_f);\n    for (int i = 0; i < n_f; ++i)\n    {\n        F_n[i] = std::vector<int>(F_he[i].size());\n        for (int j = 0; j < F_he[i].size()-1; ++j)\n        {\n            F_n[i][j] = F_he[i][j+1];\n        }\n        F_n[i][F_he[i].size()-1] = F_he[i][0];\n    }\n\n\n    // Create the next halfedge map (without boundary-loop halfedges)\n    next_he.clear();\n    next_he.reserve(n_he);\n    flatten<int>(F_n, next_he);\n\n    // Get the indices of tail vertices of halfedges\n    std::vector<int> tail;\n    tail.reserve(n_he);\n    flatten<int>(F, tail);\n\n    // Get the per face indices of head vertices of halfedges\n    std::vector<std::vector<int>> F_head(n_f);\n    for (int i = 0; i < n_f; ++i)\n    {\n        F_head[i] = std::vector<int>(F[i].size());\n        for (int j = 0; j < F[i].size()-1; ++j)\n        {\n            F_head[i][j] = F[i][j+1];\n        }\n        F_head[i][F[i].size()-1] = F[i][0];\n    }\n\n    // Get the indices of head vertices of halfedges\n    std::vector<int> head;\n    tail.reserve(n_he);\n    flatten<int>(F_head, head);\n\n    // Shift indices by 1 to distinguish from 0 entries in the matrix\n    std::vector<int> he_index = range(1, n_he + 1);\n\n    // Get the number of vertices\n    int n_v = 0;\n    for (int i = 0; i < tail.size(); ++i)\n    {\n        n_v = std::max<int>(n_v, tail[i] + 1);\n    }\n\n    // Create the adjacency matrix (tail, head) -> halfedge index+1\n    Eigen::SparseMatrix<int> vv2he(n_v, n_v);\n    typedef Eigen::Triplet<int> Trip;\n    std::vector<Trip> trips(n_he);\n    for (int he = 0; he < n_he; ++he)\n    {\n        trips[he] = Trip(tail[he], head[he], he_index[he]);\n    }\n    vv2he.setFromTriplets(trips.begin(), trips.end());\n\n    // Create opp array\n    opp.clear();\n    opp.resize(n_he);\n    for (int he = 0; he < n_he; ++he)\n    {\n        opp[he] = vv2he.coeffRef(head[he], tail[he]) - 1;\n    }\n\n    // Add boundary loop halfedges\n    std::vector<int> next_he_ext;\n    std::vector<int> opp_ext;\n    build_boundary_loops(next_he, opp, next_he_ext, opp_ext);\n    next_he = next_he_ext;\n    opp = opp_ext;\n    \n    // Create previous halfedge array\n    std::vector<int> prev_he(next_he.size(), -1);\n    for (int he = 0; he < next_he.size(); ++he)\n    {\n        prev_he[next_he[he]] = he;\n    }\n\n    // Create circulator function array\n    std::vector<int> circ(next_he.size());\n    for (int he = 0; he < next_he.size(); ++he)\n    {\n        circ[he] = prev_he[opp[he]];\n    }\n\n    // Create vertex array from the circulator array\n    std::vector<std::vector<int>> vert;\n    build_orbits(circ, vert);\n    \n    // Map orbit indices to indices of input vertices\n    vtx_reindex.clear();\n    vtx_reindex.resize(n_v);\n    for (int i = 0; i < n_v; ++i)\n    {\n        vtx_reindex[i] = head[vert[i][0]];\n    }\n\n    // Create boundary loops\n    bnd_face_list(next_he, n_he, bnd_loops);\n}   \n\nvoid FV_to_NOB(const Eigen::MatrixXi &F,\n               std::vector<int> &next_he,\n               std::vector<int> &opp,\n               std::vector<int> &bnd_loops,\n               std::vector<int> &vtx_reindex)\n{\n    // Convert eigen matrix to vector of vectors\n    std::vector<std::vector<int>> F_vec(F.rows(),std::vector<int>(F.cols()));\n    for (int i = 0; i < F.rows(); ++i)\n    {\n        for (int j = 0; j < F.cols(); ++j)\n        {\n            F_vec[i][j] = F(i,j);\n        }\n    }\n\n    // Run FV_to_NOB method\n    FV_to_NOB(F_vec, next_he, opp, bnd_loops, vtx_reindex);\n}\n\nvoid build_boundary_loops(const std::vector<int> &next_he,\n                          const std::vector<int> &opp,\n                          std::vector<int> &next_he_ext,\n                          std::vector<int> &opp_ext)\n{\n    int n_he = opp.size();\n\n    // Get halfedges on the boundary\n    std::vector<int> bnd_he;\n    for (int he = 0; he < n_he; ++he)\n    {\n        if (opp[he] == -1)\n        {\n            bnd_he.push_back(he);\n        }\n    }\n    int n_bnd_he = bnd_he.size();\n\n    // Add boundary halfedges to the extended opp array\n    opp_ext = opp;\n    std::vector<int> opp_ext_tail(n_bnd_he, 0);\n    opp_ext.insert(opp_ext.end(), opp_ext_tail.begin(), opp_ext_tail.end());\n    for (int i = 0; i < n_bnd_he; ++i)\n    {\n        opp_ext[bnd_he[i]] = n_he + i;\n        opp_ext[n_he + i] = bnd_he[i];\n    }\n\n    // Add boundary halfedges to the extended next halfedge array\n    next_he_ext = next_he;\n    std::vector<int> next_he_ext_tail(n_bnd_he, -1);\n    next_he_ext.insert(next_he_ext.end(), next_he_ext_tail.begin(), next_he_ext_tail.end());\n    for (int i = 0; i < n_bnd_he; ++i)\n    {\n        int he = bnd_he[i];\n        int he_it = next_he[he];\n        while (opp[he_it] != -1)\n        {\n            he_it = next_he[opp[he_it]];\n        }\n        next_he_ext[opp_ext[he_it]] = opp_ext[he];\n    }\n}\n\nvoid build_orbits(const std::vector<int> &perm,\n                  std::vector<std::vector<int>> &cycles)\n{\n    int n_perm = perm.size();\n\n    // Get the maximum value in perm\n    int max_perm = 0;\n    for (int i = 0; i < n_perm; ++i)\n    {\n        max_perm = std::max(perm[i], max_perm);\n    }\n    std::vector<bool> visited(max_perm+1, false);\n\n    // Build the cycles of the permutation\n    cycles.clear();\n    for (int i = 0; i < max_perm + 1; ++i)\n    {\n        if (!visited[i])\n        {\n            cycles.push_back(std::vector<int>());\n            int i_it = i;\n            while (true)\n            {\n                visited[i_it] = true;\n                cycles.back().push_back(i_it);\n                i_it = perm[i_it];\n                if (i_it == i)\n                {\n                    break;\n                }\n            }\n        }\n    }\n}\n\nvoid bnd_face_list(const std::vector<int> &next_he,\n                   const int n_he,\n                   std::vector<int> &bnd_loops)\n{\n    std::vector<std::vector<int>> faces;\n    build_orbits(next_he, faces);\n    int n_f = faces.size();\n    bnd_loops.clear();\n    for (int i = 0; i < n_f; ++i)\n    {\n        if (faces[i][0] >= n_he)\n        {\n           bnd_loops.push_back(i);\n        }\n    }\n}\n\n\nstd::vector<int> range(int start, int end)\n{\n    std::vector<int> arr(end-start);\n    for (int i = 0; i < end - start; ++i)\n    {\n        arr[i] = start + i;\n    }\n\n    return arr;\n}\n\nvoid NOB_to_connectivity(const std::vector<int> &next_he,\n                         const std::vector<int> &opp,\n                         const std::vector<int> &bnd_loops,\n                         Connectivity &C,\n                         const std::vector<int> &diag_he)\n{\n    // Build previous halfedge array\n    int n_he = next_he.size();\n    std::vector<int> prev_he = std::vector<int>(n_he, -1);\n    for (int he = 0; he < n_he; ++he)\n    {\n        prev_he[next_he[he]] = he;\n    }\n    \n    // Construct face loops\n    std::vector<std::vector<int>> faces;\n    build_orbits(next_he, faces);\n\n    // Create a boolean array marking the diagonal halfedge indices\n    std::vector<bool> reserved_he(n_he, false);\n    for (int i = 0; i < diag_he.size(); ++i)\n    {\n        reserved_he[diag_he[i]] = true;\n    }\n\n    // Map faces to attached halfedges\n    int n_f = faces.size();\n    std::vector<int> f2he(n_f);\n    for (int i = 0; i < n_f; ++i)\n    {\n        f2he[i] = faces[i][0];\n    }\n\n    // Map halfedges to faces\n    std::vector<int> he2f_perm;\n    he2f_perm.reserve(n_he);\n    for (int i = 0; i < n_f; ++i)\n    {\n        for (int j = 0; j < faces[i].size(); ++j)\n        {\n            he2f_perm.push_back(i);\n        }\n    }\n    std::vector<int> Fhe;\n    Fhe.reserve(n_he);\n    flatten<int>(faces, Fhe);\n    std::vector<int> he2f(n_he);\n    for (int i = 0; i < n_he; ++i)\n    {\n        he2f[Fhe[i]] = he2f_perm[i];\n    }\n\n    // Create vertex list\n    std::vector<int> circ(next_he.size());\n    for (int he = 0; he < next_he.size(); ++he)\n    {\n        circ[he] = prev_he[opp[he]];\n    }\n    std::vector<std::vector<int>> vert_all;\n    build_orbits(circ, vert_all);\n    std::vector<std::vector<int>> vert;\n    vert.reserve(vert_all.size());\n    for (int i = 0; i < vert_all.size(); ++i)\n    {\n        // Skip vertices originating from diagonal halfedges\n        if (reserved_he[vert_all[i][0]])\n        {\n            continue;\n        }\n        vert.push_back(vert_all[i]);\n    }\n\n    // Create out array\n    int n_v = vert.size();\n    std::vector<int> out(n_v);\n    for (int i = 0; i < n_v; ++i)\n    {\n        out[i] = next_he[vert[i][0]];\n    }\n\n\n    // Create to array\n    std::vector<int> to(n_he);\n    std::vector<int> vind;\n    vind.reserve(n_he);\n    for (int i = 0; i < n_v; ++i)\n    {\n        for (int j = 0; j < vert[i].size(); ++j)\n        {\n            vind.push_back(i);\n        }\n    }\n    std::vector<int> vhe;\n    vhe.reserve(n_he);\n    flatten(vert, vhe);\n    for (int i = 0; i < n_he; ++i)\n    {\n        to[vhe[i]] = vind[i];\n    }\n\n    // Copy arrays to connectivity struct\n    C.n = next_he;\n    C.prev = prev_he;\n    C.to = to;\n    C.f = he2f;\n    C.h = f2he;\n    C.out = out;\n    C.opp = opp;\n}\n\nvoid NOB_to_double(const std::vector<int> &next_he_in,\n                   const std::vector<int> &opp_in,\n                   const std::vector<int> &bnd_loops_in,\n                   Connectivity &C,\n                   std::vector<char> &type,\n                   std::vector<int> &R)\n{\n    int n_f = bnd_loops_in[0];\n\n    // Build faces of the input mesh\n    std::vector<std::vector<int>> faces_in;\n    build_orbits(next_he_in, faces_in);\n\n    // Construct list of halfedges of boundary faces\n    std::vector<int> bnd_loop_he;\n    for (int i = 0; i < bnd_loops_in.size(); ++ i)\n    {\n        int l = bnd_loops_in[i];\n        bnd_loop_he.insert(bnd_loop_he.end(), faces_in[l].begin(), faces_in[l].end());\n    }\n\n    // Get the number of halfedges belonging to faces, which is the first boundary loop halfedge\n    int n_he_nb = bnd_loop_he[0];\n    for (int i = 0; i < bnd_loop_he.size(); ++i)\n    {\n        n_he_nb = std::min(bnd_loop_he[i], n_he_nb);\n    }\n\n    // Create truncated arrays excluding boundary loop halfedges\n    std::vector<int> opp_nb(opp_in.begin(), opp_in.begin() + n_he_nb);\n    std::vector<std::vector<int>> faces_nb(faces_in.begin(), faces_in.begin() + bnd_loops_in[0]);\n\n    // The symmetry map simply reverses the order of halfedges\n    R.clear();\n    R.resize(2*n_he_nb);\n    for (int i = 0; i < 2*n_he_nb; ++i)\n    {\n        R[i] = 2*n_he_nb - i - 1;\n    }\n\n    // The faces as a result of the above symmetry map definition also reverse order\n    std::vector<std::vector<int>> faces_new(n_f, std::vector<int>());\n    for (int i = 0; i < n_f; ++i)\n    {\n        int face_size = faces_nb[n_f-i-1].size();\n        faces_new[i].resize(face_size);\n        for (int j = 0; j < face_size; ++j)\n        {\n            faces_new[i][j] = R[faces_nb[n_f-i-1][face_size-j-1]];\n        }\n    }\n    std::vector<std::vector<int>> faces_double(faces_nb);\n    faces_double.insert(faces_double.end(), faces_new.begin(), faces_new.end());\n\n    // Construct the next halfedge array for the doubled mesh\n    std::vector<int> he_double;\n    he_double.reserve(2*n_he_nb);\n    flatten<int>(faces_double, he_double);\n    std::vector<std::vector<int>> next_he_double_faces(2*n_f, std::vector<int>());\n    for (int i = 0; i < 2*n_f; ++i)\n    {\n        next_he_double_faces[i].reserve(faces_double[i].size());\n        next_he_double_faces[i].insert(next_he_double_faces[i].end(),\n                                       faces_double[i].begin()+1,\n                                       faces_double[i].end());\n        next_he_double_faces[i].push_back(faces_double[i][0]);\n    }\n    std::vector<int> next_he_double;\n    next_he_double.reserve(2*n_he_nb);\n    flatten<int>(next_he_double_faces, next_he_double);\n    permute<int>(next_he_double, he_double);\n    \n    // Rebuild the faces in the the canonical oder inferred from faces\n    std::vector<std::vector<int>> ordered_faces_double;\n    build_orbits(next_he_double, ordered_faces_double);\n\n    // Rebuild the halfedges of the faces enumerated sequentially\n    //std::vector<int> he_double_ordered;\n    //he_double_ordered.reserve(2*n_he_nb);\n    //flatten<int>(ordered_faces_double, he_double_ordered);\n\n    // Construct opp for the doubled mesh\n    std::vector<int> bnd_he;\n    std::vector<int> inter_he;\n    for (int i = 0; i < opp_nb.size(); ++i)\n    {\n        if (opp_nb[i] >= n_he_nb)\n        {\n            bnd_he.push_back(i);\n        }\n        else\n        {\n            inter_he.push_back(i);\n        }\n    }\n    std::vector<int> bnd_he_new(bnd_he.size());\n    for (int i = 0; i < bnd_he.size(); ++i)\n    {\n        bnd_he_new[i] = R[bnd_he[i]];\n    }\n    for (int i = 0; i < bnd_he.size(); ++i)\n    {\n        opp_nb[bnd_he[i]] = bnd_he_new[i];\n    }\n    std::vector<int> opp_new(n_he_nb);\n    for (int i = 0; i < n_he_nb; ++i)\n    {\n        opp_new[i] = R[opp_nb[R[n_he_nb+i]]];\n    }\n    std::vector<int> opp_double(opp_nb);\n    opp_double.insert(opp_double.end(), opp_new.begin(), opp_new.end());\n\n    // There is no boundary in the doubled mesh\n    std::vector<int> bnd_loops_double;\n\n    // Create the connectivity arrays for the doubled mesh\n    NOB_to_connectivity(next_he_double, opp_double, bnd_loops_double, C);\n    \n    // Label the halfedges from the original mesh with 1 and the new mesh with 2\n    type.clear();\n    type.resize(2*n_he_nb);\n    for (int i = 0; i < n_he_nb; ++i)\n    {\n        type[i] = 1;\n    }\n    for (int i = n_he_nb; i < 2*n_he_nb; ++i)\n    {\n        type[i] = 2;\n    }\n    for (int i = 0; i < bnd_he.size(); ++i)\n    {\n        type[bnd_he[i]] = 1;\n    }\n    for (int i = 0; i < bnd_he_new.size(); ++i)\n    {\n        type[bnd_he_new[i]] = 2;\n    }\n}\n\n\nvoid find_indep_vertices(const std::vector<int> &out,\n                         const std::vector<int> &to,\n                         const std::vector<char> &type,\n                         const std::vector<int> &R,\n                         std::vector<int> &indep_vtx,\n                         std::vector<int> &dep_vtx,\n                         std::vector<int> &v_rep)\n{\n    indep_vtx.clear();\n    dep_vtx.clear();\n    v_rep.clear();\n    int n_v = out.size();\n    int n_he = to.size();\n\n    // Create a reflection map for the vertices\n    std::vector<int> refl_v(n_v);\n    for (int i = 0; i < n_v; ++i)\n    {\n        refl_v[i] = to[R[out[i]]];\n    }\n\n    // Label the vertices as type 1=D1, 2=D2, or 3=S (on the symmetry line)\n    std::vector<char> vtype(n_v);\n    for (int he = 0; he < n_he; ++he)\n    {\n        if ((type[he] == 1) || (type[he] == 2))\n        {\n            vtype[to[he]] = type[he];\n        }\n    }\n    for (int i = 0; i < n_v; ++i)\n    {\n        if (refl_v[i] == i)\n        {\n            vtype[i] = 3;\n        }\n    }\n\n    // Partition vertices of type 1 and 3 (arising from the original mesh) and vertices\n    // of type 2 (created in the double)\n    indep_vtx.reserve(n_v);\n    dep_vtx.reserve(n_v);\n    for (int i = 0; i < n_v; ++i)\n    {\n        if (vtype[i] == 2)\n        {\n            dep_vtx.push_back(i);\n        }\n        else\n        {\n            indep_vtx.push_back(i);\n        }\n    }\n\n    // Map independent vertices to unique indices and dependent vertices to their reflection's\n    // index\n    v_rep.resize(n_v);\n    for (int i = 0; i < indep_vtx.size(); ++i)\n    {\n        v_rep[indep_vtx[i]] = i;\n    }\n    for (int i = 0; i < dep_vtx.size(); ++i)\n    {\n        v_rep[dep_vtx[i]] = v_rep[refl_v[dep_vtx[i]]];\n    }\n}\n\nvoid create_tufted_cover(const std::vector<char> &type,\n                         const std::vector<int> &R,\n                         const std::vector<int> &indep_vtx,\n                         const std::vector<int> &dep_vtx,\n                         const std::vector<int> &v_rep,\n                         std::vector<int> &out,\n                         std::vector<int> &to)\n{\n    int n_v = out.size();\n    int n_he = to.size();\n\n    // Modify the to and out arrays to identify dependent vertices with their reflection\n    std::vector<int> out_tufted(indep_vtx.size());\n    for (int i = 0; i < n_he; ++i)\n    {\n        to[i] = v_rep[to[i]];\n    }\n    for (int i = 0; i < indep_vtx.size(); ++i)\n    {\n        out_tufted[i] = out[indep_vtx[i]];\n    }\n    out = out_tufted;\n}\n", "meta": {"hexsha": "c633f32af059509791ba7de6ae1975bcefc6e6bd", "size": 19547, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/conformal_ideal_delaunay/Halfedge.cc", "max_stars_repo_name": "hankstag/ConformalIdealDelaunay", "max_stars_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T03:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:34:25.000Z", "max_issues_repo_path": "src/conformal_ideal_delaunay/Halfedge.cc", "max_issues_repo_name": "hankstag/ConformalIdealDelaunay", "max_issues_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/conformal_ideal_delaunay/Halfedge.cc", "max_forks_repo_name": "hankstag/ConformalIdealDelaunay", "max_forks_repo_head_hexsha": "653a6f62908517df60a3e9f4c311ba6f2f358382", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T04:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T04:56:14.000Z", "avg_line_length": 30.8799368088, "max_line_length": 97, "alphanum_fraction": 0.5223819512, "num_tokens": 5405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.04468087090869867, "lm_q1q2_score": 0.020772207095785533}}
{"text": "#include \"simulator.hpp\"\n\n#include <iostream>\n#include <exception>\n#include <cstdint>\n#include <limits>\n#include <Eigen>\n\nSimulator::Simulator(double timeStep, uint64_t maxObjects, Integrator* integrator, DynamicsEngine* dynamicsEngine)\n: timeStep(timeStep)\n, maxObjects(maxObjects)\n, integrator(integrator)\n, dynamicsEngine(dynamicsEngine)\n, m(1, maxObjects)\n, r(1, maxObjects)\n, pos(3, maxObjects)\n, v(3, maxObjects)\n, a(3, maxObjects)\n, id2idx(maxObjects, RIGIDBODY_IDX_NULL)\n, idx2id(maxObjects, RIGIDBODY_ID_NULL)\n, availableUsedIDs{} {}\n\n\nSimulator::~Simulator() {\n    // Deallocate heap variables\n    delete this->integrator;\n    delete this->dynamicsEngine;\n}\n\n\ndouble Simulator::totalKineticEnergy() {\n    // (1/2)*sum(m_i * |v_i|^2)\n    return 0.5*active(m).cwiseProduct(active(v).colwise().squaredNorm()).sum();\n}\n\n\ndouble Simulator::totalPotentialEnergy() {\n    // Sum of potential energies\n    return this->dynamicsEngine->totalPotentialEnergy(active(pos), active(m));\n}\n\n\ndouble Simulator::totalEnergy() {\n    return this->totalKineticEnergy() + this->totalPotentialEnergy();\n}\n\n\ndouble Simulator::totalMomentOfInertia() {\n    // sum(m_i * |pos_i|^2)\n    return active(m).cwiseProduct(active(pos).colwise().squaredNorm()).sum();\n}\n\n\nEigen::Ref<Eigen::MatrixXd> Simulator::active(Eigen::Ref<Eigen::MatrixXd> mat) {\n    // Return map to slice (1, this->nextIdx). Works because SoA is densely packed.\n    if (this->nObjects() == 0) {\n        std::cerr << \"Error: Simulator method called on empty simulator.\" << std::endl;\n        throw std::runtime_error(\"Error: Simulator method called on empty simulator.\");\n    }\n\n    return mat(Eigen::all, Eigen::seq(0, this->nextIdx - 1));\n}\n\n\nRigidbody Simulator::nObjects() {\n    return this->nextIdx;\n}\n\n\nRigidbody Simulator::addObject(double m, double r, const Eigen::Vector3d& p0, const Eigen::Vector3d& v0) {\n    // Update SoA and nextIdx\n\n    // Check for max number of objects reached\n    if (this->nextIdx >= this->maxObjects) {\n        std::cerr << \"Error: Max number of objects reached.\" << std::endl;\n        throw std::overflow_error(\"Error: Max number of objects reached.\");\n    }\n\n    // Get new object's index in SoA\n    RigidbodyIdx idx = this->nextIdx++;\n\n    // If a used id is not available, increment this->nextID and use that\n    Rigidbody id;\n    if (this->availableUsedIDs.empty()) {\n        id = this->nextID++;\n    } else {\n        id = this->availableUsedIDs.front();\n        this->availableUsedIDs.pop();\n    }\n\n    // Update id-idx mappings\n    this->id2idx[id] = idx;\n    this->idx2id[idx] = id;\n\n    // Update structure of arrays\n    this->m(idx) = m;\n    this->r(idx) = r;\n    this->pos(Eigen::all, idx) = p0;\n    this->v(Eigen::all,   idx) = v0;\n    this->a(Eigen::all,   idx) = Eigen::Vector3d::Zero();\n\n    return id;\n}\n\n\nvoid Simulator::delObject(Rigidbody id) {\n    // Check object exists\n    if (!this->rb_exists(id)) {\n        std::cerr << \"Error: Rigidbody id not valid.\" << std::endl;\n        throw std::out_of_range(\"Error: Rigidbody id not valid.\");\n    }\n\n    // Get deleted object's idx\n    RigidbodyIdx idx = this->id2idx[id];\n\n    // Get index and id of topmost object (object with greatest index)\n    RigidbodyIdx topIdx = this->nextIdx - 1;\n    Rigidbody    topID  = this->idx2id[topIdx];\n\n    // Move data at topIdx to idx\n    this->m(idx) = this->m(topIdx);\n    this->r(idx) = this->r(topIdx);\n    this->pos(Eigen::all, idx) = this->pos(Eigen::all, topIdx);\n    this->v(Eigen::all,   idx) = this->v(Eigen::all,   topIdx);\n    this->a(Eigen::all,   idx) = this->a(Eigen::all,   topIdx);\n\n    // Assign: idx to topID, topID to idx, null to id, null to topIdx\n    this->id2idx[topID] = idx;\n    this->idx2id[idx] = topID;\n    this->id2idx[id] = RIGIDBODY_IDX_NULL;\n    this->idx2id[topIdx] = RIGIDBODY_ID_NULL;\n\n    // Push id to used available IDs\n    this->availableUsedIDs.push(id);\n\n    // Decrement nextIdx\n    this->nextIdx--;\n}\n\n\nbool Simulator::rb_exists(Rigidbody id) {\n    if (id < 0 || id >= this->maxObjects || this->id2idx[id] == RIGIDBODY_IDX_NULL) {\n        // ID is out of range or does not point to existing object\n        return false;\n    } else {\n        return true;\n    }\n}\n\n\nEigen::Ref<const Eigen::Vector3d> Simulator::rb_pos(Rigidbody id) {\n    return this->pos.col(this->id2idx[id]);\n}\n\n\nEigen::Ref<const Eigen::Vector3d> Simulator::rb_v(Rigidbody id) {\n    return this->v.col(this->id2idx[id]);\n}\n\n\nEigen::Ref<const Eigen::Vector3d> Simulator::rb_a(Rigidbody id) {\n    return this->a.col(this->id2idx[id]);\n}\n\n\ndouble Simulator::rb_m(Rigidbody id) {\n    return this->m(this->id2idx[id]);\n}\n\n\ndouble Simulator::rb_r(Rigidbody id) {\n    return this->r(this->id2idx[id]);\n}\n\n\nEigen::Ref<const Eigen::Matrix3Xd> Simulator::activePos() {\n    return this->active(this->pos);\n}\n\nEigen::Ref<const Eigen::Matrix3Xd> Simulator::activeV() {\n    return this->active(this->v);\n}\n\nEigen::Ref<const Eigen::Matrix3Xd> Simulator::activeA() {\n    return this->active(this->a);\n}\n\nEigen::Ref<const Eigen::RowVectorXd> Simulator::activeM() {\n    return this->active(this->m);\n}\n\nEigen::Ref<const Eigen::RowVectorXd> Simulator::activeR() {\n    return this->active(this->r);\n}\n\nvoid Simulator::updateAccelerations() {\n    this->dynamicsEngine->updateAccelerations(\n        this->active(this->a),\n        this->active(this->pos),\n        this->active(this->m)\n    );\n}\n\n\nvoid Simulator::step() {\n    this->updateAccelerations();\n    this->integrator->integrate(\n        this->timeStep,\n        this->active(this->a),\n        this->active(this->v),\n        this->active(this->pos)\n    );\n}\n", "meta": {"hexsha": "c94c71e47f6fc0d9df29cc8a706da335aa0cff8c", "size": 5591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpu/simulator.cpp", "max_stars_repo_name": "tdude92/nbody-tool", "max_stars_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-12T08:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T19:37:44.000Z", "max_issues_repo_path": "src/cpu/simulator.cpp", "max_issues_repo_name": "tdude92/nbody-tool", "max_issues_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpu/simulator.cpp", "max_forks_repo_name": "tdude92/nbody-tool", "max_forks_repo_head_hexsha": "cf8feedb974c5d23a0ab6981d8ccbeab35aeacb0", "max_forks_repo_licenses": ["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.1261682243, "max_line_length": 114, "alphanum_fraction": 0.6465748524, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.053403324150263734, "lm_q1q2_score": 0.020753494450808298}}
{"text": "/*\n Class header file\n */\n#include \"aq_base.h\"\n\n/*\n STL header files\n */\n#include <fstream>\n#include <iomanip>\n/*\n deal.II header files\n */\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/quadrature_lib.h>\n\n#include \"lsgc.h\"\n\ntemplate <int dim>\nAQBase<dim>::AQBase (const dealii::ParameterHandler &prm)\n    : k_pi(dealii::numbers::PI),\n      have_reflective_bc_(prm.get_bool(\"have reflective boundary\")),\n      transport_model_name_(prm.get(\"transport model\")),\n      n_azi_(prm.get_integer(\"angular quadrature order\")),\n      n_group_(prm.get_integer(\"number of groups\")),\n      aq_name_(prm.get(\"angular quadrature name\")) {}\n\ntemplate <int dim>\nstd::unique_ptr<AQBase<dim>> AQBase<dim>::CreateAQ(\n    const dealii::ParameterHandler &prm) {\n  \n  std::unique_ptr<AQBase<dim>> return_ptr;\n\n  if (dim == 1) {\n    return_ptr.reset(new AQBase<dim>(prm));\n  } else {\n    std::unordered_map<std::string, AQType>\n        aq_name_map = {{\"lsgc\", AQType::kLSGC}};\n\n    switch(aq_name_map[prm.get(\"angular quadrature name\")]) {\n      case AQType::kLSGC: {\n        return_ptr.reset(new LSGC<dim>(prm));\n        break;\n      }\n      default: {\n        assert(false);\n      }\n    }\n  }\n\n  return std::move(return_ptr);     \n}\n  \n\ntemplate <int dim>\nvoid AQBase<dim>::MakeAQ () {\n  ProduceAQ ();\n  InitCompInd ();\n  InitRefBCInd ();\n}\n\ntemplate <int dim>\nvoid AQBase<dim>::InitRefBCInd () {\n  // Note: here we assume square domain and assume user either\n  // uses deal.II generated mesh or mesh from gmsh with proper\n  // boundary IDs setup: {0,1,2,3,4,5} for {xmin,xmax,ymin,ymax,zmin,zmax}\n  if (have_reflective_bc_) {\n    std::vector<dealii::Tensor<1, dim>> bnv;\n    bnv.resize (2*dim);\n    // All boundary normal vectors are assume to be parallel to axes\n    // Then, only one component in each normal vector is nonzero\n    bnv[0][0] = -1.0;\n    bnv[1][0] = 1.0;\n    if (dim>=2) {\n      bnv[2][1] = -1.0;\n      bnv[3][1] = 1.0;\n      if (dim>=3) {\n        bnv[4][2] = -1.0;\n        bnv[5][2] = 1.0;\n      }\n    }\n    for (int i=0; i<2*dim; ++i)\n      for (int i_dir=0; i_dir<n_dir_; ++i_dir) {\n        dealii::Tensor<1, dim> out_angle =\n            (omega_i_[i_dir] - 2.0 * (bnv[i]*omega_i_[i_dir]) * bnv[i]);\n        //(omega_i_[i_dir] *\n        // (1.0 - 2.0 * (bnv[i] * omega_i_[i_dir])));\n        for (int r_dir=0; r_dir<n_dir_; ++r_dir) {\n          dealii::Tensor<1, dim> d_dir = out_angle;\n          dealii::Tensor<1, dim> d_minus_dir = out_angle;\n          d_dir -= omega_i_[r_dir];\n          d_minus_dir += omega_i_[r_dir];\n          // Use caution about even parity using this std::map\n          if ((transport_model_name_==\"ep\" &&\n               (d_dir.norm ()<1.0e-13 || d_minus_dir.norm ()<1.0e-13)) ||\n              (transport_model_name_!=\"ep\" && d_dir.norm ()<1.0e-13))\n            reflective_direction_index_[std::make_pair (i, i_dir)] = r_dir;\n        }\n      }\n  }\n}\n\ntemplate <int dim>\nvoid AQBase<dim>::ProduceAQ () {\n  // Only provide 1D by default\n  AssertThrow (dim==1,\n               dealii::ExcMessage(\"Only 1D is implemented in AQBase<dim>\"));\n  n_dir_ = n_azi_ / (transport_model_name_==\"ep\" ? 2 : 1);\n  total_angle_ = transport_model_name_==\"ep\" ? 4.0 : 2.0;\n  dealii::QGauss<1> mu_quad (n_azi_);\n  for (int i=0; i<n_dir_; ++i) {\n    dealii::Tensor <1,dim> omega;\n    omega[0] = mu_quad.point(i)[0]*2.0-1.0;\n    omega_i_.push_back (omega);\n    wi_.push_back (mu_quad.weight(i)*total_angle_);\n  }\n  n_total_ho_vars_ = n_dir_ * n_group_;\n}\n\ntemplate <int dim>\nvoid AQBase<dim>::InitCompInd () {\n  // initialize the map from (group, direction) to component indices\n  int ind = 0;\n  for (int g=0; g<n_group_; ++g)\n    for (int i_dir=0; i_dir<n_dir_; ++i_dir)\n    {\n      std::pair<int, int> key (g, i_dir);\n      component_index_[key] = ind;\n      inverse_component_index_[ind] = key;\n      ind += 1;\n    }\n}\n\ntemplate <int dim>\nvoid AQBase<dim>::PrintAQ () {\n  std::ofstream quadr;\n  quadr.open(\"aq.txt\");\n  PrintAQ(&quadr);\n  quadr.close ();\n}\n\ntemplate <int dim>\nvoid AQBase<dim>::PrintAQ (std::ostream *output_stream) {\n  *output_stream << \"transport model: \" << transport_model_name_\n        << \"; output_streamature name: \" << ProduceAQName () << std::endl;\n  *output_stream << \"Dim = \" << dim << \", SN order = \" << n_azi_ << std::endl;\n  *output_stream << \"Weights | Omega_x | Omega_y | mu\" << std::endl;\n  for (size_t i=0; i<omega_i_.size(); ++i) {\n    *output_stream << std::fixed << std::setprecision (15)\n          << wi_[i] << \"  \" << omega_i_[i][0] << \"  \";\n    if (dim>1) {\n      *output_stream << omega_i_[i][1] << \"  \";\n      double mu = dim>2 ? omega_i_[i][2] :\n          std::sqrt(1.-(std::pow(omega_i_[i][0],2.)\n                        +std::pow(omega_i_[i][1],2)));\n      *output_stream << mu;\n    }\n    *output_stream << std::endl;\n  }\n}\n\ntemplate <int dim>\nstd::string AQBase<dim>::ProduceAQName () const {\n  AssertThrow(aq_name_.size()>0,\n              dealii::ExcMessage(\"aq name has to be assigned\"));\n  // ToDo: more quadrature name producers\n  if (aq_name_ == \"lsgc\")\n    return \"Level Symmetric Gauss Chebyshev\";\n\n  return \"None\";\n}\n\n//public member functions to retrieve private and protected variables\ntemplate <int dim>\nstd::map<std::pair<int, int>, int> AQBase<dim>::GetCompInd () const {\n  return component_index_;\n}\n\ntemplate <int dim>\nstd::unordered_map<int, std::pair<int, int>> AQBase<dim>::GetInvCompInd () const {\n  return inverse_component_index_;\n}\n\ntemplate <int dim>\nstd::map<std::pair<int, int>, int> AQBase<dim>::GetRefDirInd () const {\n  return reflective_direction_index_;\n}\n\ntemplate <int dim>\nint AQBase<dim>::GetSnOrder () const {\n  return n_azi_;\n}\n\ntemplate <int dim>\nint AQBase<dim>::GetNDir () const {\n  return n_dir_;\n}\n\ntemplate <int dim>\nint AQBase<dim>::GetNTotalHOVars () const {\n  return n_total_ho_vars_;\n}\n\ntemplate <int dim>\nstd::vector<double> AQBase<dim>::GetAQWeights () const {\n  return wi_;\n}\n\ntemplate <int dim>\nstd::vector<dealii::Tensor<1, dim>> AQBase<dim>::GetAQDirs () const {\n  return omega_i_;\n}\n\ntemplate class AQBase<1>;\ntemplate class AQBase<2>;\ntemplate class AQBase<3>;\n", "meta": {"hexsha": "68579e0624d89087379baf08557480e096d0b2aa", "size": 6075, "ext": "cc", "lang": "C++", "max_stars_repo_path": "legacy_code/aqdata/aq_base.cc", "max_stars_repo_name": "narang-amit/BART", "max_stars_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "legacy_code/aqdata/aq_base.cc", "max_issues_repo_name": "jsrehak/BART", "max_issues_repo_head_hexsha": "0460dfffbcf5671a730448de7f45cce39fd4a485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "legacy_code/aqdata/aq_base.cc", "max_forks_repo_name": "jsrehak/BART", "max_forks_repo_head_hexsha": "0460dfffbcf5671a730448de7f45cce39fd4a485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 27.9953917051, "max_line_length": 82, "alphanum_fraction": 0.6139917695, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.04535258507040257, "lm_q1q2_score": 0.020732331838723486}}
{"text": "// Three-state boolean logic library\n\n// Copyright Douglas Gregor 2002-2004. Use, modification and\n// distribution is subject to the Boost Software License, Version\n// 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n// For more information, see http://www.boost.org\n#ifndef BOOST_LOGIC_TRIBOOL_HPP\n#define BOOST_LOGIC_TRIBOOL_HPP\n\n#include <boost/logic/tribool_fwd.hpp>\n#include <boost/config.hpp>\n#include <boost/detail/workaround.hpp>\n\n#ifdef BOOST_HAS_PRAGMA_ONCE\n#  pragma once\n#endif\n\nnamespace boost { namespace logic {\n\n/// INTERNAL ONLY\nnamespace detail {\n/**\n * INTERNAL ONLY\n *\n * \\brief A type used only to uniquely identify the 'indeterminate'\n * function/keyword.\n */\nstruct indeterminate_t\n{\n#if BOOST_WORKAROUND(BOOST_BORLANDC, < 0x0600)\n  char dummy_; // BCB would use 8 bytes by default\n#endif\n};\n\n} // end namespace detail\n\n/**\n * INTERNAL ONLY\n * The type of the 'indeterminate' keyword. This has the same type as the\n * function 'indeterminate' so that we can recognize when the keyword is\n * used.\n */\ntypedef bool (*indeterminate_keyword_t)(tribool, detail::indeterminate_t);\n\n/**\n * \\brief Keyword and test function for the indeterminate tribool value\n *\n * The \\c indeterminate function has a dual role. It's first role is\n * as a unary function that tells whether the tribool value is in the\n * \"indeterminate\" state. It's second role is as a keyword\n * representing the indeterminate (just like \"true\" and \"false\"\n * represent the true and false states). If you do not like the name\n * \"indeterminate\", and would prefer to use a different name, see the\n * macro \\c BOOST_TRIBOOL_THIRD_STATE.\n *\n * \\returns <tt>x.value == tribool::indeterminate_value</tt>\n * \\throws nothrow\n */\nBOOST_CONSTEXPR inline bool\nindeterminate(tribool x,\n              detail::indeterminate_t dummy = detail::indeterminate_t()) BOOST_NOEXCEPT;\n\n/**\n * \\brief A 3-state boolean type.\n *\n * 3-state boolean values are either true, false, or\n * indeterminate.\n */\nclass tribool\n{\n#if defined( BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS )\nprivate:\n  /// INTERNAL ONLY\n  struct dummy {\n    void nonnull() {};\n  };\n\n  typedef void (dummy::*safe_bool)();\n#endif\n\npublic:\n  /**\n   * Construct a new 3-state boolean value with the value 'false'.\n   *\n   * \\throws nothrow\n   */\n  BOOST_CONSTEXPR tribool() BOOST_NOEXCEPT : value(false_value) {}\n\n  /**\n   * Construct a new 3-state boolean value with the given boolean\n   * value, which may be \\c true or \\c false.\n   *\n   * \\throws nothrow\n   */\n  BOOST_CONSTEXPR tribool(bool initial_value) BOOST_NOEXCEPT : value(initial_value? true_value : false_value) {}\n\n  /**\n   * Construct a new 3-state boolean value with an indeterminate value.\n   *\n   * \\throws nothrow\n   */\n  BOOST_CONSTEXPR tribool(indeterminate_keyword_t) BOOST_NOEXCEPT : value(indeterminate_value) {}\n\n  /**\n   * Use a 3-state boolean in a boolean context. Will evaluate true in a\n   * boolean context only when the 3-state boolean is definitely true.\n   *\n   * \\returns true if the 3-state boolean is true, false otherwise\n   * \\throws nothrow\n   */\n#if !defined( BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS )\n\n  BOOST_CONSTEXPR explicit operator bool () const BOOST_NOEXCEPT\n  {\n    return value == true_value;\n  }\n\n#else\n\n  BOOST_CONSTEXPR operator safe_bool() const BOOST_NOEXCEPT\n  {\n    return value == true_value? &dummy::nonnull : 0;\n  }\n\n#endif\n\n  /**\n   * The actual stored value in this 3-state boolean, which may be false, true,\n   * or indeterminate.\n   */\n  enum value_t { false_value, true_value, indeterminate_value } value;\n};\n\n// Check if the given tribool has an indeterminate value. Also doubles as a\n// keyword for the 'indeterminate' value\nBOOST_CONSTEXPR inline bool indeterminate(tribool x, detail::indeterminate_t) BOOST_NOEXCEPT\n{\n  return x.value == tribool::indeterminate_value;\n}\n\n/** @defgroup logical Logical operations\n */\n//@{\n/**\n * \\brief Computes the logical negation of a tribool\n *\n * \\returns the logical negation of the tribool, according to the\n * table:\n *  <table border=1>\n *    <tr>\n *      <th><center><code>!</code></center></th>\n *      <th/>\n *    </tr>\n *    <tr>\n *      <th><center>false</center></th>\n *      <td><center>true</center></td>\n *    </tr>\n *    <tr>\n *      <th><center>true</center></th>\n *      <td><center>false</center></td>\n *    </tr>\n *    <tr>\n *      <th><center>indeterminate</center></th>\n *      <td><center>indeterminate</center></td>\n *    </tr>\n *  </table>\n * \\throws nothrow\n */\nBOOST_CONSTEXPR inline tribool operator!(tribool x) BOOST_NOEXCEPT\n{\n  return x.value == tribool::false_value? tribool(true)\n        :x.value == tribool::true_value? tribool(false)\n        :tribool(indeterminate);\n}\n\n/**\n * \\brief Computes the logical conjunction of two tribools\n *\n * \\returns the result of logically ANDing the two tribool values,\n * according to the following table:\n *       <table border=1>\n *           <tr>\n *             <th><center><code>&amp;&amp;</code></center></th>\n *             <th><center>false</center></th>\n *             <th><center>true</center></th>\n *             <th><center>indeterminate</center></th>\n *           </tr>\n *           <tr>\n *             <th><center>false</center></th>\n *             <td><center>false</center></td>\n *             <td><center>false</center></td>\n *             <td><center>false</center></td>\n *           </tr>\n *           <tr>\n *             <th><center>true</center></th>\n *             <td><center>false</center></td>\n *             <td><center>true</center></td>\n *             <td><center>indeterminate</center></td>\n *           </tr>\n *           <tr>\n *             <th><center>indeterminate</center></th>\n *             <td><center>false</center></td>\n *             <td><center>indeterminate</center></td>\n *             <td><center>indeterminate</center></td>\n *           </tr>\n *       </table>\n * \\throws nothrow\n */\nBOOST_CONSTEXPR inline tribool operator&&(tribool x, tribool y) BOOST_NOEXCEPT\n{\n  return (static_cast<bool>(!x) || static_cast<bool>(!y))\n    ? tribool(false)\n    : ((static_cast<bool>(x) && static_cast<bool>(y)) ? tribool(true) : indeterminate)\n  ;\n}\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator&&(tribool x, bool y) BOOST_NOEXCEPT\n{ return y? x : tribool(false); }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator&&(bool x, tribool y) BOOST_NOEXCEPT\n{ return x? y : tribool(false); }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator&&(indeterminate_keyword_t, tribool x) BOOST_NOEXCEPT\n{ return !x? tribool(false) : tribool(indeterminate); }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator&&(tribool x, indeterminate_keyword_t) BOOST_NOEXCEPT\n{ return !x? tribool(false) : tribool(indeterminate); }\n\n/**\n * \\brief Computes the logical disjunction of two tribools\n *\n * \\returns the result of logically ORing the two tribool values,\n * according to the following table:\n *       <table border=1>\n *           <tr>\n *             <th><center><code>||</code></center></th>\n *             <th><center>false</center></th>\n *             <th><center>true</center></th>\n *             <th><center>indeterminate</center></th>\n *           </tr>\n *           <tr>\n *             <th><center>false</center></th>\n *             <td><center>false</center></td>\n *             <td><center>true</center></td>\n *             <td><center>indeterminate</center></td>\n *           </tr>\n *           <tr>\n *             <th><center>true</center></th>\n *             <td><center>true</center></td>\n *             <td><center>true</center></td>\n *             <td><center>true</center></td>\n *           </tr>\n *           <tr>\n *             <th><center>indeterminate</center></th>\n *             <td><center>indeterminate</center></td>\n *             <td><center>true</center></td>\n *             <td><center>indeterminate</center></td>\n *           </tr>\n *       </table>\n *  \\throws nothrow\n */\nBOOST_CONSTEXPR inline tribool operator||(tribool x, tribool y) BOOST_NOEXCEPT\n{\n  return (static_cast<bool>(!x) && static_cast<bool>(!y))\n    ? tribool(false)\n    : ((static_cast<bool>(x) || static_cast<bool>(y)) ? tribool(true) : tribool(indeterminate))\n  ;\n}\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator||(tribool x, bool y) BOOST_NOEXCEPT\n{ return y? tribool(true) : x; }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator||(bool x, tribool y) BOOST_NOEXCEPT\n{ return x? tribool(true) : y; }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator||(indeterminate_keyword_t, tribool x) BOOST_NOEXCEPT\n{ return x? tribool(true) : tribool(indeterminate); }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator||(tribool x, indeterminate_keyword_t) BOOST_NOEXCEPT\n{ return x? tribool(true) : tribool(indeterminate); }\n//@}\n\n/**\n * \\brief Compare tribools for equality\n *\n * \\returns the result of comparing two tribool values, according to\n * the following table:\n *       <table border=1>\n *          <tr>\n *            <th><center><code>==</code></center></th>\n *            <th><center>false</center></th>\n *            <th><center>true</center></th>\n *            <th><center>indeterminate</center></th>\n *          </tr>\n *          <tr>\n *            <th><center>false</center></th>\n *            <td><center>true</center></td>\n *            <td><center>false</center></td>\n *            <td><center>indeterminate</center></td>\n *          </tr>\n *          <tr>\n *            <th><center>true</center></th>\n *            <td><center>false</center></td>\n *            <td><center>true</center></td>\n *            <td><center>indeterminate</center></td>\n *          </tr>\n *          <tr>\n *            <th><center>indeterminate</center></th>\n *            <td><center>indeterminate</center></td>\n *            <td><center>indeterminate</center></td>\n *            <td><center>indeterminate</center></td>\n *          </tr>\n *      </table>\n * \\throws nothrow\n */\nBOOST_CONSTEXPR inline tribool operator==(tribool x, tribool y) BOOST_NOEXCEPT\n{\n  return (indeterminate(x) || indeterminate(y))\n    ? indeterminate\n    : ((x && y) || (!x && !y))\n  ;\n}\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator==(tribool x, bool y) BOOST_NOEXCEPT { return x == tribool(y); }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator==(bool x, tribool y) BOOST_NOEXCEPT { return tribool(x) == y; }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator==(indeterminate_keyword_t, tribool x) BOOST_NOEXCEPT\n{ return tribool(indeterminate) == x; }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator==(tribool x, indeterminate_keyword_t) BOOST_NOEXCEPT\n{ return tribool(indeterminate) == x; }\n\n/**\n * \\brief Compare tribools for inequality\n *\n * \\returns the result of comparing two tribool values for inequality,\n * according to the following table:\n *       <table border=1>\n *           <tr>\n *             <th><center><code>!=</code></center></th>\n *             <th><center>false</center></th>\n *             <th><center>true</center></th>\n *             <th><center>indeterminate</center></th>\n *           </tr>\n *           <tr>\n *             <th><center>false</center></th>\n *             <td><center>false</center></td>\n *             <td><center>true</center></td>\n *             <td><center>indeterminate</center></td>\n *           </tr>\n *           <tr>\n *             <th><center>true</center></th>\n *             <td><center>true</center></td>\n *             <td><center>false</center></td>\n *             <td><center>indeterminate</center></td>\n *           </tr>\n *           <tr>\n *             <th><center>indeterminate</center></th>\n *             <td><center>indeterminate</center></td>\n *             <td><center>indeterminate</center></td>\n *             <td><center>indeterminate</center></td>\n *           </tr>\n *       </table>\n * \\throws nothrow\n */\nBOOST_CONSTEXPR inline tribool operator!=(tribool x, tribool y) BOOST_NOEXCEPT\n{\n  return (indeterminate(x) || indeterminate(y))\n    ? indeterminate\n    : !((x && y) || (!x && !y))\n  ;\n}\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator!=(tribool x, bool y) BOOST_NOEXCEPT { return x != tribool(y); }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator!=(bool x, tribool y) BOOST_NOEXCEPT { return tribool(x) != y; }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator!=(indeterminate_keyword_t, tribool x) BOOST_NOEXCEPT\n{ return tribool(indeterminate) != x; }\n\n/**\n * \\overload\n */\nBOOST_CONSTEXPR inline tribool operator!=(tribool x, indeterminate_keyword_t) BOOST_NOEXCEPT\n{ return x != tribool(indeterminate); }\n\n} } // end namespace boost::logic\n\n// Pull tribool and indeterminate into namespace \"boost\"\nnamespace boost {\n  using logic::tribool;\n  using logic::indeterminate;\n}\n\n/**\n * \\brief Declare a new name for the third state of a tribool\n *\n * Use this macro to declare a new name for the third state of a\n * tribool. This state can have any number of new names (in addition\n * to \\c indeterminate), all of which will be equivalent. The new name will be\n * placed in the namespace in which the macro is expanded.\n *\n * Example:\n *   BOOST_TRIBOOL_THIRD_STATE(true_or_false)\n *\n *   tribool x(true_or_false);\n *   // potentially set x\n *   if (true_or_false(x)) {\n *     // don't know what x is\n *   }\n */\n#define BOOST_TRIBOOL_THIRD_STATE(Name)                                 \\\ninline bool                                                             \\\nName(boost::logic::tribool x,                                           \\\n     boost::logic::detail::indeterminate_t =                            \\\n       boost::logic::detail::indeterminate_t())                         \\\n{ return x.value == boost::logic::tribool::indeterminate_value; }\n\n#endif // BOOST_LOGIC_TRIBOOL_HPP\n\n", "meta": {"hexsha": "b4c4a01154af65b617cb39e61fd46b44e957f3df", "size": 13844, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/logic/tribool.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": 177.0, "max_stars_repo_stars_event_min_datetime": "2021-02-19T02:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:31:21.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/logic/tribool.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": 188.0, "max_issues_repo_issues_event_min_datetime": "2021-02-19T04:15:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:42:15.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/logic/tribool.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": 78.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T03:01:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:10:01.000Z", "avg_line_length": 29.4553191489, "max_line_length": 112, "alphanum_fraction": 0.6100115574, "num_tokens": 3616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.05749328526007551, "lm_q1q2_score": 0.020661025309932923}}
{"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_EXAMPLES_LINEARELLIPTIC_MRS2016__5_1_HH\n#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_MRS2016__5_1_HH\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/parallel/mpihelper.hh>\n\n#if HAVE_ALUGRID\n# include <dune/grid/alugrid.hh>\n#endif\n\n#if HAVE_DUNE_FEM\n# include <dune/fem/misc/mpimanager.hh>\n#endif\n\n\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/logging.hh>\n#include <dune/stuff/common/timedlogging.hh>\n#include <dune/stuff/common/memory.hh>\n#include <dune/stuff/common/ranges.hh>\n#include <dune/stuff/grid/boundaryinfo.hh>\n#include <dune/stuff/grid/provider/cube.hh>\n\n#include <dune/hdd/linearelliptic/problems/thermalblock.hh>\n#include <dune/hdd/linearelliptic/discretizations/cg.hh>\n\nnamespace internal {\n\n\ntemplate< class GridType >\nclass Initializer\n{\n  typedef Dune::Stuff::Grid::Providers::Cube< GridType > GridProviderType;\n\npublic:\n  Initializer(const std::string& num_grid_elements,\n              const DUNE_STUFF_SSIZE_T info_log_levels,\n              const DUNE_STUFF_SSIZE_T debug_log_levels,\n              const bool enable_warnings,\n              const bool enable_colors,\n              const std::string info_color,\n              const std::string debug_color,\n              const std::string warn_color)\n  {\n    try {\n      int argc = 0;\n      char** argv = new char* [0];\n#if HAVE_DUNE_FEM\n      Dune::Fem::MPIManager::initialize(argc, argv);\n#else\n      Dune::MPIHelper::instance(argc, argv);\n#endif\n    } catch (...) {}\n    try {\n      DSC::TimedLogger().create(info_log_levels,\n                                debug_log_levels,\n                                enable_warnings,\n                                enable_colors,\n                                info_color,\n                                debug_color,\n                                warn_color);\n    } catch (Dune::Stuff::Exceptions::you_are_using_this_wrong&) {}\n    auto logger = DSC::TimedLogger().get(\"cg.thermalblock.example\");\n    logger.info() << \"creating grid... \" << std::flush;\n    grid_provider_ = GridProviderType::create(GridProviderType::default_config().add(DSC::Configuration(\"num_elements\",\n                                                                                                        num_grid_elements),\n                                                                                     \"\",\n                                                                                     true));\n#if HAVE_ALUGRID\n    if (std::is_same< GridType, Dune::ALUGrid< 2, 2, Dune::simplex, Dune::conforming > >::value)\n      grid_provider_->grid().globalRefine(1);\n#endif // HAVE_ALUGRID\n    logger.info() << \"done (has \" << grid_provider_->grid().size(0) << \" elements)\" << std::endl;\n  } // Initializer(...)\n\nprotected:\n  std::unique_ptr< GridProviderType > grid_provider_;\n}; // class Initializer\n\n\n} // namespace internal\n\n\ntemplate< class GridImp, Dune::GDT::ChooseSpaceBackend space_backend, Dune::Stuff::LA::ChooseBackend la_backend >\nclass CgExample\n  : internal::Initializer< GridImp >\n{\n  typedef internal::Initializer< GridImp >               BaseType;\n  typedef GridImp                                        GridType;\n  typedef typename GridType::template Codim< 0 >::Entity EntityType;\n  static const size_t                                    dimDomain = GridType::dimension;\n  typedef typename GridType::ctype                       DomainFieldType;\n  typedef double                                         RangeFieldType;\n  static const size_t                                    dimRange = 1;\n  typedef Dune::HDD::LinearElliptic::Problems::Thermalblock\n      < EntityType, DomainFieldType, dimDomain, RangeFieldType, 1 > ProblemType;\npublic:\n  typedef Dune::HDD::LinearElliptic::Discretizations::CG< GridType, Dune::Stuff::Grid::ChooseLayer::leaf,\n                                                          RangeFieldType, dimRange, 1,\n                                                          space_backend, la_backend > DiscretizationType;\n\n  CgExample(const std::string& num_blocks        = \"[2 2 2]\",\n            const std::string& num_grid_elements = \"[32 32 32]\",\n            const DUNE_STUFF_SSIZE_T info_log_levels  = 0,\n            const DUNE_STUFF_SSIZE_T debug_log_levels = -1,\n            const bool enable_warnings = true,\n            const bool enable_colors   = true,\n            const std::string info_color  = DSC::TimedLogging::default_info_color(),\n            const std::string debug_color = DSC::TimedLogging::default_debug_color(),\n            const std::string warn_color  = DSC::TimedLogging::default_warning_color())\n    : BaseType(num_grid_elements,\n               info_log_levels,\n               debug_log_levels,\n               enable_warnings,\n               enable_colors,\n               info_color,\n               debug_color,\n               warn_color)\n    , problem_(ProblemType::create(ProblemType::default_config().add(DSC::Configuration(\"diffusion_factor.num_elements\",\n                                                                                        num_blocks),\n                                                                     \"\",\n                                                                     true)))\n    , discretization_(*grid_provider_, Dune::Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config(), *problem_)\n  {\n    auto logger = DSC::TimedLogger().get(\"cg.thermalblock.example\");\n    logger.info() << \"initializing discretization... \" << std::flush;\n    discretization_.init();\n    logger.info() << \"done (has \" << discretization_.ansatz_space().mapper().size() << \" DoFs)\" << std::endl;\n  } // ... CgExample(...)\n\n  DiscretizationType& discretization()\n  {\n    return discretization_;\n  }\n\nprivate:\n  using BaseType::grid_provider_;\n  std::unique_ptr< ProblemType > problem_;\n  DiscretizationType discretization_;\n}; // class CgExample\n\n\n/**\n    Orthonormalize a |VectorArray| using the stabilized Gram-Schmidt algorithm.\n\n    Parameters\n    ----------\n    A\n        The |VectorArray| which is to be orthonormalized.\n    product\n        The scalar product w.r.t. which to orthonormalize, given as a linear\n        |Operator|. If `None` the Euclidean product is used.\n    atol\n        Vectors of norm smaller than `atol` are removed from the array.\n    rtol\n        Relative tolerance used to detect linear dependent vectors\n        (which are then removed from the array).\n    offset\n        Assume that the first `offset` vectors are already orthogonal and start the\n        algorithm at the `offset + 1`-th vector.\n    find_duplicates\n        If `True`, eliminate duplicate vectors before the main loop.\n    reiterate\n        If `True`, orthonormalize again if the norm of the orthogonalized vector is\n        much smaller than the norm of the original vector.\n    reiteration_threshold\n        If `reiterate` is `True`, re-orthonormalize if the ratio between the norms of\n        the orthogonalized vector and the original vector is smaller than this value.\n    check\n        If `True`, check if the resulting VectorArray is really orthonormal.\n    check_tol\n        Tolerance for the check.\n    copy\n        If `True`, create a copy of `A` instead of modifying `A` itself.\n\n\n    Returns\n    -------\n    The orthonormalized |VectorArray|.\n  **/\ntemplate< class VectorType >\nstd::vector< VectorType > gram_schmidt(const std::vector< VectorType >& A,\n                                       const bool reiterate = true,\n                                       const bool check = true,\n                                       const double atol = 1e-13,\n                                       const double rtol = 1e-13,\n                                       const DUNE_STUFF_SSIZE_T offset = 0,\n                                       const double reiteration_threshold = 1e-1,\n                                       const double check_tol = 1e-3)\n{\n  if (offset < 0)\n    DUNE_THROW(Dune::Stuff::Exceptions::index_out_of_range, offset);\n  auto logger = DSC::TimedLogger().get(\"gram_schmidt\");\n\n  auto ret = A;\n\n  // main loop\n  std::set< size_t > remove;\n  for (size_t i = offset; i < ret.size(); ++i) {\n    // first calculate norm\n    const double initial_norm = ret[i].l2_norm();\n\n    if (initial_norm < atol) {\n      logger.info() << \"Removing vector \" << i << \" of norm \" << initial_norm << std::endl;\n      remove.insert(i);\n    }\n\n    if (i == 0)\n      ret[0].scal(1./initial_norm);\n    else {\n      bool first_iteration = true;\n      double norm = initial_norm;\n      double old_norm = initial_norm;\n      // If reiterate is true, reiterate as long as the norm of the vector changes\n      // strongly during orthonormalization (due to Andreas Buhr).\n      while (first_iteration || reiterate && norm/old_norm < reiteration_threshold) {\n\n        if (first_iteration)\n          first_iteration = false;\n        else\n          logger.info() << \"Orthonormalizing vector \" << i << \" again\" << std::endl;\n\n        // orthogonalize to all vectors left\n        for (size_t j = 0; j < i; ++j) {\n          if (remove.find(j) != remove.end())\n            continue;\n          const double p = ret[i].dot(ret[j]);\n          ret[i].axpy(-p, ret[j]);\n        }\n\n        // calculate new norm\n        old_norm = norm;\n        norm = ret[i].l2_norm();\n\n        // remove vector if it got too small:\n        if (norm/initial_norm < rtol) {\n          logger.info() << \"Removing linear dependent vector \" << i << std::endl;\n          remove.insert(i);\n          break;\n        }\n      }\n      ret[i].scal(1./norm);\n    }\n  }\n\n  for (const size_t& i : remove)\n    ret.erase(ret.begin() + i);\n\n  if (check) {\n    for (size_t i = offset; i < ret.size(); ++i)\n      for (size_t j = i; j < ret.size(); ++j)\n        if (std::abs(ret[i].dot(ret[j])) - (i == j ? 1. : 0.) > check_tol)\n          DUNE_THROW(Dune::MathError,\n                     \"result not orthogonal: \\n\"\n                     << \"  A[i]*A[j] = \" << ret[i].dot(ret[j]) << \"\\n\"\n                     << \"  i = \" << i << \"\\n\"\n                     << \"  j = \" << j);\n  }\n  return ret;\n} // ... gram_schmidt(...)\n\ntemplate< class VectorType, class MatrixType >\nstd::vector< VectorType > gram_schmidt(const std::vector< VectorType >& A,\n                                       const MatrixType& product,\n                                       const bool reiterate = true,\n                                       const bool check = true,\n                                       const double atol = 1e-13,\n                                       const double rtol = 1e-13,\n                                       const DUNE_STUFF_SSIZE_T offset = 0,\n                                       const double reiteration_threshold = 1e-1,\n                                       const double check_tol = 1e-3)\n{\n  if (offset < 0)\n    DUNE_THROW(Dune::Stuff::Exceptions::index_out_of_range, offset);\n  auto logger = DSC::TimedLogger().get(\"gram_schmidt\");\n\n  auto ret = A;\n  VectorType tmp(product.rows());\n\n  // main loop\n  std::set< size_t > remove;\n  for (size_t i = offset; i < ret.size(); ++i) {\n    // first calculate norm\n    product.mv(ret[i], tmp);\n    const double initial_norm = std::sqrt(tmp*ret[i]);\n\n    if (initial_norm < atol) {\n      logger.info() << \"Removing vector \" << i << \" of norm \" << initial_norm << std::endl;\n      remove.insert(i);\n    }\n\n    if (i == 0)\n      ret[0].scal(1./initial_norm);\n    else {\n      bool first_iteration = true;\n      double norm = initial_norm;\n      double old_norm = initial_norm;\n      // If reiterate is true, reiterate as long as the norm of the vector changes\n      // strongly during orthonormalization (due to Andreas Buhr).\n      while (first_iteration || reiterate && norm/old_norm < reiteration_threshold) {\n\n        if (first_iteration)\n          first_iteration = false;\n        else\n          logger.info() << \"Orthonormalizing vector \" << i << \" again\" << std::endl;\n\n        // orthogonalize to all vectors left\n        for (size_t j = 0; j < i; ++j) {\n          if (remove.find(j) != remove.end())\n            continue;\n          product.mv(ret[i], tmp);\n          const double p = tmp*ret[j];\n          ret[i].axpy(-p, ret[j]);\n        }\n\n        // calculate new norm\n        old_norm = norm;\n        product.mv(ret[i], tmp);\n        norm = std::sqrt(tmp*ret[i]);\n\n        // remove vector if it got too small:\n        if (norm/initial_norm < rtol) {\n          logger.info() << \"Removing linear dependent vector \" << i << std::endl;\n          remove.insert(i);\n          break;\n        }\n      }\n      ret[i].scal(1./norm);\n    }\n  }\n\n  for (const size_t& i : remove)\n    ret.erase(ret.begin() + i);\n\n  if (check) {\n    for (size_t i = offset; i < ret.size(); ++i) {\n      product.mv(ret[i], tmp);\n      for (size_t j = i; j < ret.size(); ++j) {\n        if (tmp*ret[j] - (i == j ? 1. : 0.) > check_tol)\n          DUNE_THROW(Dune::MathError,\n                     \"result not orthogonal: \\n\"\n                     << \"  product.apply2(A[i], A[j]) = \" << tmp*ret[j] << \"\\n\"\n                     << \"  i = \" << i << \"\\n\"\n                     << \"  j = \" << j);\n      }\n    }\n  }\n  return ret;\n} // ... gram_schmidt(...)\n\n#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_MRS2016__5_1_HH\n", "meta": {"hexsha": "c4438671a9820633787883ad768152f88f213076", "size": 13422, "ext": "hh", "lang": "C++", "max_stars_repo_path": "examples/linearelliptic/MRS2016__5_1.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": "examples/linearelliptic/MRS2016__5_1.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": "examples/linearelliptic/MRS2016__5_1.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": 37.4916201117, "max_line_length": 123, "alphanum_fraction": 0.5550588586, "num_tokens": 3157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.05749327880038582, "lm_q1q2_score": 0.020661022988552064}}
{"text": "// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#ifndef   CPPQEDCORE_QUANTUMTRAJECTORY_MCWF_TRAJECTORY_TCC_INCLUDED\n#define   CPPQEDCORE_QUANTUMTRAJECTORY_MCWF_TRAJECTORY_TCC_INCLUDED\n\n#include \"MCWF_Trajectory.h\"\n\n#include \"StateVector.h\"\n\n#include \"EvolvedGSL.tcc\"\n#include \"QuantumTrajectory.h\"\n\n#include \"FormDouble.h\"\n\n#include <boost/range/numeric.hpp>\n#include <boost/range/algorithm/find_if.hpp>\n\n\nnamespace quantumtrajectory {\n\n//////////////////\n//\n// Implementations\n//\n//////////////////\n\ntemplate<int RANK, typename RandomEngine>\nvoid MCWF_Trajectory<RANK,RandomEngine>::derivs(double t, const StateVectorLow& psi, StateVectorLow& dpsidt) const\n{\n  if (const auto ha=this->getHa()) {\n    dpsidt=0;\n\n    ha->addContribution(t,psi,dpsidt,this->getT0());\n  }\n}\n\n\ntemplate<int RANK, typename RandomEngine>\nMCWF_Trajectory<RANK,RandomEngine>::MCWF_Trajectory(SV_Ptr psi,\n                                                    typename structure::QuantumSystem<RANK>::Ptr sys,\n                                                    const mcwf::Pars<RandomEngine>& p,\n                                                    const StateVectorLow& scaleAbs)\n  : QuantumTrajectory(sys,p.noise,\n         psi->getArray(),\n         bind(&MCWF_Trajectory::derivs,this,_1,_2,_3),\n         initialTimeStep<RANK>(sys),\n         scaleAbs,\n         p,\n         evolved::MakerGSL<StateVectorLow>(p.sf,p.nextDtTryCorrectionFactor)),\n    psi_(psi),\n    dpLimit_(p.dpLimit), overshootTolerance_(p.overshootTolerance),\n    logger_(p.logLevel,this->template nAvr<structure::LA_Li>())\n{\n  QuantumTrajectory::checkDimension(psi);\n  if (!getTime()) if(const auto li=this->getLi()) { // On startup, dpLimit should not be overshot, either.\n    Rates rates(li->rates(0.,*psi_)); calculateSpecialRates(&rates,0.);\n    manageTimeStep(rates,getEvolved().get(),false);\n  }\n}\n\n\ntemplate<int RANK, typename RandomEngine>\ndouble MCWF_Trajectory<RANK,RandomEngine>::coherentTimeDevelopment(double Dt)\n{\n  if (this->getHa()) {\n    getEvolved()->step(Dt);\n  }\n  else {\n    double stepToDo=this->getLi() ? std::min(getDtTry(),Dt) : Dt; // Cf. tracker #3482771\n    getEvolved()->update(getTime()+stepToDo,getDtTry());\n  }\n  // This defines three levels:\n  // 1. System is Hamiltonian -> internal timestep control is used with dtTry possibly modified by Liouvillean needs (cf. manageTimeStep)\n  // 2. System is not Hamiltonian, but it is Liouvillean -> dtTry is used, which is governed solely by Liouvillean in this case (cf. manageTimeStep)\n  // 3. System is neither Hamiltonian nor Liouvillean (might be of Exact) -> as step of Dt is taken\n  \n  double t=getTime();\n\n  if (const auto ex=this->getEx()) {\n    ex->actWithU(getTime(),psi_->getArray(),this->getT0());\n    QuantumTrajectory::setT0(t);\n  }\n\n  logger_.processNorm(psi_->renorm());\n\n  return t;\n}\n\n\ntemplate<int RANK, typename RandomEngine>\nauto MCWF_Trajectory<RANK,RandomEngine>::calculateSpecialRates(Rates* rates, double t) const -> const IndexSVL_tuples\n{\n  IndexSVL_tuples res;\n  for (int i=0; i<rates->size(); i++)\n    if ((*rates)(i)<0) {\n      StateVector psiTemp(*psi_);\n      this->actWithJ(t,psiTemp.getArray(),i);\n      res.push_back(IndexSVL_tuple(i,psiTemp.getArray()));\n      (*rates)(i)=mathutils::sqr(psiTemp.renorm());\n    } // psiTemp disappears here, but its storage does not, because the ownership is taken over by the StateVectorLow in the tuple\n  return res;\n}\n\n\ntemplate<int RANK, typename RandomEngine>\nbool MCWF_Trajectory<RANK,RandomEngine>::manageTimeStep(const Rates& rates, evolved::TimeStepBookkeeper* evolvedCache, bool logControl)\n{\n  const double totalRate=boost::accumulate(rates,0.);\n  const double dtDid=this->getDtDid(), dtTry=getDtTry();\n\n  const double liouvilleanSuggestedDtTry=dpLimit_/totalRate;\n\n  // Assumption: overshootTolerance_>=1 (equality is the limiting case of no tolerance)\n  if (totalRate*dtDid>overshootTolerance_*dpLimit_) {\n    evolvedCache->setDtTry(liouvilleanSuggestedDtTry);\n    (*getEvolved())=*evolvedCache;\n    logger_.stepBack(this->getLogStreamDuringRun(),totalRate*dtDid,dtDid,getDtTry(),getTime(),logControl);\n    return true; // Step-back required.\n  }\n  else if ( totalRate*dtTry>dpLimit_) {\n    logger_.overshot(this->getLogStreamDuringRun(),totalRate*dtTry,dtTry,liouvilleanSuggestedDtTry,logControl);\n  }\n\n  // dtTry-adjustment for next step:\n  getEvolved()->setDtTry(this->getHa() ? std::min(getDtTry(),liouvilleanSuggestedDtTry) : liouvilleanSuggestedDtTry);\n\n  return false; // Step-back not required.\n}\n\n\ntemplate<int RANK, typename RandomEngine>\nvoid MCWF_Trajectory<RANK,RandomEngine>::performJump(const Rates& rates, const IndexSVL_tuples& specialRates, double t)\n{\n  double random=std::uniform_real_distribution()(this->getRandomEngine())/this->getDtDid();\n\n  int lindbladNo=0; // TODO: this could be expressed with an iterator into rates\n  for (; random>0 && lindbladNo!=rates.size(); random-=rates(lindbladNo++))\n    ;\n\n  if(random<0) { // Jump corresponding to Lindblad no. lindbladNo-1 occurs\n    --lindbladNo; auto i=boost::find_if(specialRates,[=](const IndexSVL_tuple& j){return lindbladNo==std::get<0>(j);});\n    if (i!=specialRates.end())\n      // special jump\n      *psi_=std::get<1>(*i); // RHS already normalized above\n    else {\n      // normal  jump\n      this->actWithJ(t,psi_->getArray(),lindbladNo);\n      double normFactor=sqrt(rates(lindbladNo));\n      if (!boost::math::isfinite(normFactor)) throw std::runtime_error(\"Infinite detected in MCWF_Trajectory::performJump\");\n      *psi_/=normFactor;\n    }\n\n    logger_.jumpOccured(this->getLogStreamDuringRun(),t,lindbladNo);\n  }\n}\n\n\ntemplate<int RANK, typename RandomEngine>\nvoid MCWF_Trajectory<RANK,RandomEngine>::step_v(double Dt)\n{\n  const StateVector psiCache(*psi_);\n  evolved::TimeStepBookkeeper evolvedCache(*getEvolved()); // This cannot be const since dtTry might change.\n\n  double t=coherentTimeDevelopment(Dt);\n\n  if (const auto li=this->getLi()) {\n\n    Rates rates(li->rates(t,*psi_));\n    IndexSVL_tuples specialRates=calculateSpecialRates(&rates,t);\n\n    while (manageTimeStep(rates,&evolvedCache)) {\n      *psi_=psiCache;\n      t=coherentTimeDevelopment(Dt); // the next try\n      rates=li->rates(t,*psi_);\n      specialRates=calculateSpecialRates(&rates,t);\n    }\n\n    // Jump\n    performJump(rates,specialRates,t);\n\n  }\n\n  logger_.step();\n\n}\n\n\ntemplate<int RANK, typename RandomEngine>\nstd::ostream& MCWF_Trajectory<RANK,RandomEngine>::streamParameters_v(std::ostream& os) const\n{\n  using namespace std;\n  \n  this->streamCharacteristics(this->getQS()->streamParameters(Base::streamParameters_v(os)<<\"MCWF Trajectory Parameters: dpLimit=\"<<dpLimit_<<\" (overshoot tolerance factor)=\"<<overshootTolerance_<<endl<<endl))<<endl;\n\n  if (const auto li=this->getLi()) {\n    os<<\"Decay channels:\\n\";\n    {\n      size_t i=0;\n      li->streamKey(os,i);\n    }\n    os<<\"Alternative Lindblads: \";\n    {\n      const Rates rates(li->rates(0,*psi_));\n      int n=0;\n      for (int i=0; i<rates.size(); ++i) if (rates(i)<0) {os<<i<<' '; ++n;}\n      if (!n) os<<\"none\";\n    }\n    os<<endl;\n  }\n\n  return os;\n  \n}\n\n\ntemplate<int RANK, typename RandomEngine>\nstd::ostream& MCWF_Trajectory<RANK,RandomEngine>::streamKey_v(std::ostream& os, size_t& i) const\n{\n  return this->template streamKey<structure::LA_Av>(os,i);\n}\n\n\n} // quantumtrajectory\n\n\n#endif // CPPQEDCORE_QUANTUMTRAJECTORY_MCWF_TRAJECTORY_TCC_INCLUDED\n", "meta": {"hexsha": "b7ced016581e4ab970528736c3c51f054b77d0fe", "size": 7465, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/quantumtrajectory/MCWF_Trajectory.tcc", "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": "CPPQEDcore/quantumtrajectory/MCWF_Trajectory.tcc", "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": "CPPQEDcore/quantumtrajectory/MCWF_Trajectory.tcc", "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": 33.0309734513, "max_line_length": 216, "alphanum_fraction": 0.6947086403, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.04958902403746827, "lm_q1q2_score": 0.020574428119805824}}
{"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// Take as input a directory of ASTER images. Apply radiometric\n// correction to the VNIR_Band3N and VNIR_Band3B images, writing\n// <output-prefix>-Band3N.tif and <output-prefix>-Band3B.tif. Generate\n// RPC coefficients from input metadata and write\n// <output-prefix>-Band3N.xml and <output-prefix>-Band3B.xml. These\n// files can then be used as input for stereo with -t rpc.\n\n// References:\n// -----------\n// ASTER User Handbook Version 2\n// https://asterweb.jpl.nasa.gov/content/03_data/04_Documents/aster_user_guide_v2.pdf\n//\n// IMPROVEMENT OF DEM GENERATION FROM ASTER IMAGES USING SATELLITE\n// JITTER ESTIMATION AND OPEN SOURCE IMPLEMENTATION\n// Luc Girod, Christopher Nutha, and Andreas Kaab\n// http://www.int-arch-photogramm-remote-sens-spatial-inf-sci.net/XL-1-W5/249/2015/isprsarchives-XL-1-W5-249-2015.pdf\n\n#include <vw/FileIO/DiskImageView.h>\n#include <vw/Core/StringUtils.h>\n#include <vw/Cartography/Datum.h>\n#include <vw/Cartography/GeoReference.h>\n#include <asp/Core/Common.h>\n#include <asp/Core/Macros.h>\n#include <asp/Core/FileUtils.h>\n#include <asp/Camera/RPCModelGen.h>\n\n#include <limits>\n#include <cstring>\n\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n\nnamespace fs = boost::filesystem;\nnamespace po = boost::program_options;\n\nusing namespace vw;\nusing namespace std;\nusing namespace vw::cartography;\n\nstruct Options : public vw::cartography::GdalWriteOptions {\n  string input_dir, output_prefix; \n  double min_height, max_height;\n  int num_samples;\n  double penalty_weight;\n  Options(): min_height(-1), max_height(-1), num_samples(-1), penalty_weight(-1) {}\n};\n\nvoid handle_arguments(int argc, char *argv[], Options& opt) {\n  po::options_description general_options(\"\");\n  general_options.add_options()\n    (\"output-prefix,o\",   po::value(&opt.output_prefix), \"Specify the output prefix.\")\n    (\"min-height\",     po::value(&opt.min_height)->default_value(0),\n     \"The minimum height (in meters) above the WGS84 datum of the simulation box in which to compute the RPC approximation.\")\n    (\"max-height\",     po::value(&opt.max_height)->default_value(8.0e+3),\n     \"The maximum height (in meters) above the WGS84 datum of the simulation box in which to compute the RPC approximation.\")\n    (\"num-samples\",     po::value(&opt.num_samples)->default_value(100),\n     \"How many samples to use between the minimum and maximum heights.\")\n    (\"penalty-weight\",     po::value(&opt.penalty_weight)->default_value(0.1),\n     \"Penalty weight to use to keep the higher-order RPC coefficients small. Higher penalty weight results in smaller such coefficients.\");\n\n  general_options.add( vw::cartography::GdalWriteOptionsDescription(opt) );\n\n  po::options_description positional(\"\");\n  positional.add_options()\n    (\"input_dir\", po::value(&opt.input_dir), \"An ASTER data directory.\");\n\n  po::positional_options_description positional_desc;\n  positional_desc.add(\"input_dir\", 1);\n\n  string usage(\"<input directory> -o <output prefix>\");\n  bool allow_unregistered = false;\n  std::vector<std::string> unregistered;\n  po::variables_map vm =\n    asp::check_command_line(argc, argv, opt, general_options, general_options,\n\t\t\t    positional, positional_desc, usage,\n\t\t\t    allow_unregistered, unregistered);\n  \n  if ( opt.input_dir.empty() )\n    vw_throw( ArgumentErr() << \"Missing input directory.\\n\" << usage << general_options );\n\n  if ( opt.output_prefix.empty() )\n    vw_throw( ArgumentErr() << \"Missing output prefix.\\n\" << usage << general_options );\n\n  // Create the output directory\n  vw::create_out_dir(opt.output_prefix);\n}\n\n// See if the input file matches the given pattern. If yes, store the result\n// in matched_file. If matched_file is not empty originally, that means\n// we have more than one match, which is not good. \nbool match_file(std::string const& input_file, std::string const& pattern,\n\t\tstd::string & matched_file){\n\n  size_t it = input_file.find(pattern);\n\n  // No match\n  if (it == std::string::npos)\n    return false;\n\n  // Check if it does not match at the end of the string\n  if (it + pattern.size() != input_file.size() ) return false;\n\n  // Must match L1A images\n  if (input_file.find(\"L1A\") == std::string::npos) \n    return false;\n\n  // We expect only one match\n  if (matched_file != \"\") \n    vw_throw( ArgumentErr()\n\t      << \"Found two files matching: '\" << pattern << \"'. Those are: \"\n\t      << matched_file << \" and \" << input_file << \"\\n\");\n  \n  matched_file = input_file;\n\n  return true;\n}\n\n// Identify the appropriate inputs in the ASTER directory\nvoid locate_inputs(Options const& opt, \n\t\t   std::string& nadir_image,\n\t\t   std::string& back_image,\n\t\t   std::string& nadir_sat_pos,\n\t\t   std::string& back_sat_pos,\n\t\t   std::string& nadir_sight_vec,\n\t\t   std::string& back_sight_vec,\n\t\t   std::string& nadir_corr_table,\n\t\t   std::string& back_corr_table,\n\t\t   std::string& nadir_longitude,\n\t\t   std::string& back_longitude,\n\t\t   std::string& nadir_latitude,\n\t\t   std::string& back_latitude,\n\t\t   std::string& nadir_lattice_point,\n\t\t   std::string& back_lattice_point){\n  \n  // Iterate through all files\n  for (fs::directory_iterator itr(opt.input_dir); itr != fs::directory_iterator(); itr++){\n    \n    std::string file = itr->path().string();\n    \n    match_file(file, \"VNIR_Band3N.ImageData.tif\", nadir_image);\n    match_file(file, \"VNIR_Band3B.ImageData.tif\", back_image);\n    \n    match_file(file, \"VNIR_Band3N.SatellitePosition.txt\", nadir_sat_pos);\n    match_file(file, \"VNIR_Band3B.SatellitePosition.txt\", back_sat_pos);\n\n    match_file(file, \"VNIR_Band3N.SightVector.txt\", nadir_sight_vec);\n    match_file(file, \"VNIR_Band3B.SightVector.txt\", back_sight_vec);\n\n    match_file(file, \"VNIR_Band3N.RadiometricCorrTable.txt\", nadir_corr_table);\n    match_file(file, \"VNIR_Band3B.RadiometricCorrTable.txt\", back_corr_table);\n\n    match_file(file, \"VNIR_Band3N.Longitude.txt\", nadir_longitude);\n    match_file(file, \"VNIR_Band3B.Longitude.txt\", back_longitude);\n\n    match_file(file, \"VNIR_Band3N.Latitude.txt\", nadir_latitude);\n    match_file(file, \"VNIR_Band3B.Latitude.txt\", back_latitude);\n\n    match_file(file, \"VNIR_Band3N.LatticePoint.txt\", nadir_lattice_point);\n    match_file(file, \"VNIR_Band3B.LatticePoint.txt\", back_lattice_point);\n  }\n\n  if (nadir_image == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the nadir-looking camera image \"\n\t      << \"(VNIR_Band3N.ImageData.tif).\\n\");\n  if (back_image == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the backward-looking camera image \"\n\t      << \"(VNIR_Band3B.ImageData.tif).\\n\");\n  \n  if (nadir_sat_pos == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the nadir-looking satellite position \"\n\t      << \"(VNIR_Band3N.SatellitePosition.txt).\\n\");\n  if (back_sat_pos == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the back-looking satellite position \"\n\t      << \"(VNIR_Band3B.SatellitePosition.txt).\\n\");\n  \n  if (nadir_sight_vec == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the nadir-looking sight vector \"\n\t      << \"(VNIR_Band3N.SightVector.txt).\\n\");\n  if (back_sight_vec == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the back-looking sight vector \"\n\t      << \"(VNIR_Band3B.SightVector.txt).\\n\");\n\n  if (nadir_corr_table == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the nadir-looking radiometric correction table \"\n\t      << \"(VNIR_Band3N.RadiometricCorrTable.txt).\\n\");\n  if (back_corr_table == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the back-looking radiometric correction table \"\n\t      << \"(VNIR_Band3B.RadiometricCorrTable.txt).\\n\");\n  \n  if (nadir_longitude == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the nadir-looking longitude file \"\n\t      << \"(VNIR_Band3N.Longitude.txt).\\n\");\n  if (back_longitude == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the back-looking longitude file \"\n\t      << \"(VNIR_Band3B.Longitude.txt).\\n\");\n\n  if (nadir_latitude == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the nadir-looking latitude file \"\n\t      << \"(VNIR_Band3N.Latitude.txt).\\n\");\n  if (back_latitude == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the back-looking latitude file \"\n\t      << \"(VNIR_Band3B.Latitude.txt).\\n\");\n\n  if (nadir_lattice_point == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the nadir-looking lattice point file \"\n\t      << \"(VNIR_Band3N.LatticePoint.txt).\\n\");\n  if (back_lattice_point == \"\")\n    vw_throw( ArgumentErr() << \"Could not locate the back-looking lattice point file \"\n\t      << \"(VNIR_Band3B.LatticePoint.txt).\\n\");\n}\n\n// Apply the radiometric corrections\ntemplate <class ImageT>\nclass RadioCorrectView: public ImageViewBase< RadioCorrectView<ImageT> >{\n  ImageT m_img;\n  std::vector<Vector3> const& m_corr; // alias\n  bool m_has_nodata;\n  double m_nodata;\n\npublic:\n  RadioCorrectView(ImageT const& img, std::vector<Vector3> const& corr,\n\t\t   bool has_nodata, double nodata):\n    m_img(img), m_corr(corr), m_has_nodata(has_nodata), m_nodata(nodata){}\n    \n  typedef typename ImageT::pixel_type input_type;\n  typedef float pixel_type;\n  typedef float result_type;\n  typedef ProceduralPixelAccessor<RadioCorrectView> pixel_accessor;\n\n  inline int32 cols() const { return m_img.cols(); }\n  inline int32 rows() const { return m_img.rows(); }\n  inline int32 planes() const { return 1; }\n\n  inline pixel_accessor origin() const { return pixel_accessor( *this, 0, 0 ); }\n\n  inline pixel_type operator()( double/*i*/, double/*j*/, int32/*p*/ = 0 ) const {\n    vw_throw(NoImplErr() << \"RadioCorrectView::operator()(...) is not implemented\");\n    return pixel_type();\n  }\n\n  typedef CropView<ImageView<pixel_type> > prerasterize_type;\n  inline prerasterize_type prerasterize(BBox2i const& bbox) const {\n\n    ImageView<input_type> input_tile = crop(m_img, bbox); // to speed things up\n    ImageView<result_type> tile(bbox.width(), bbox.height());\n    for (int col = bbox.min().x(); col < bbox.max().x(); col++){\n      Vector3 C = m_corr[col];\n      for (int row = bbox.min().y(); row < bbox.max().y(); row++){\n\tinput_type val = input_tile(col - bbox.min().x(), row - bbox.min().y());\n\tif (m_has_nodata && val == m_nodata)\n\t  tile(col - bbox.min().x(), row - bbox.min().y() ) = val;\n\telse\n\t  tile(col - bbox.min().x(), row - bbox.min().y() ) = C[1] * val / C[2] + C[0];\n      }\n    }\n    \n    return prerasterize_type(tile, -bbox.min().x(), -bbox.min().y(),\n                             cols(), rows() );\n  }\n  \n  template <class DestT>\n  inline void rasterize(DestT const& dest, BBox2i bbox) const {\n    vw::rasterize(prerasterize(bbox), dest, bbox);\n  }\n};\ntemplate <class ImageT>\nRadioCorrectView<ImageT> radio_correct(ImageT const& img, std::vector<Vector3> const & corr,\n\t\t\t\t       bool has_nodata, double nodata){\n  return RadioCorrectView<ImageT>(img, corr, has_nodata, nodata);\n}\n\n// ASTER L1A images come with radiometric corrections appended, but not applied.\n// There is one correction per image column.\nvoid apply_radiometric_corrections(Options const& opt, \n\t\t\t\t   std::string const& input_image,\n\t\t\t\t   std::string const& corr_table,\n\t\t\t\t   std::string const& out_image){\n\n\n  // Extract the corrections\n  std::vector<Vector3> corr;\n  asp::read_3d_points(corr_table, corr);\n  \n  DiskImageView<float> input_img(input_image);\n\n  // Sanity check\n  if (input_img.cols() != int(corr.size()) ) \n    vw_throw( ArgumentErr() << \"Expecting as many corrections in \" << corr_table\n\t      << \" as image columns in \" << input_image << \"\\n\" );\n  \n  bool has_nodata = false;\n  double nodata   = -std::numeric_limits<float>::max();\n  // See if there is a no-data value\n  {\n    boost::shared_ptr<DiskImageResource> img_rsrc(new DiskImageResourceGDAL(input_image));\n    if (img_rsrc->has_nodata_read()){\n      has_nodata = true;\n      nodata = img_rsrc->nodata_read();\n    }\n  }\n\n  // No georef, this being L1A imagery\n  vw::cartography::GeoReference georef;\n  bool has_georef = read_georeference(georef, input_image);\n  if (has_georef)\n    vw_throw( ArgumentErr() << \"ASTER L1A images are not supposed to be georeferenced.\\n\" );\n\n  \n  vw_out() << \"Writing: \" << out_image << std::endl;\n  vw::cartography::block_write_gdal_image(out_image,\n\t\t\t      radio_correct(input_img, corr, has_nodata, nodata),\n\t\t\t      has_georef, georef, \n\t\t\t      has_nodata, nodata,\n\t\t\t      opt,\n\t\t\t      TerminalProgressCallback(\"asp\", \"\\t-->: \"));\n}\n\n// Generate lon-lat-height to image pixel correspondences that we will\n// use to create the RPC model.\nvoid generate_point_pairs(// Inputs\n                          double min_height, double max_height, int num_samples,\n                          double penalty_weight,\n                          std::string const& sat_pos_file,\n                          std::string const& sight_vec_file,\n                          std::string const& longitude_file,\n                          std::string const& latitude_file,\n                          std::string const& lattice_file,\n                          // Outputs\n\t\t\t  std::vector< std::vector<vw::Vector3> > & world_sight_mat,\n                          Vector3 & llh_scale, Vector3 & llh_offset,\n                          Vector2 & pixel_scale, Vector2 & pixel_offset,\n                          Vector<double> & normalized_llh,\n                          Vector<double> & normalized_pixels){\n\n  // Read the sight vectors \n  std::vector<Vector3> sight_vec;\n  asp::read_3d_points(sight_vec_file, sight_vec);\n\n  // Read the satellite positions\n  std::vector<Vector3> sat_pos;\n  asp::read_3d_points(sat_pos_file, sat_pos);\n\n  int num_rows = sat_pos.size();\n  int num_pts = sight_vec.size();\n  int num_cols = num_pts / num_rows;\n\n  // Sight vector in world coordinates\n  world_sight_mat.clear();\n  world_sight_mat.resize(num_rows);\n  \n  if (num_rows * num_cols != num_pts) \n    vw_throw( ArgumentErr()\n\t      << \"Found \" << num_rows << \" satellite positions in \"\n\t      << sat_pos_file << \" and \"\n              << num_pts << \" sight vectors in \" << sight_vec_file\n\t      << \". The latter must be a multiple of the former.\");\n  \n  // For each satellite position there many sight vectors\n  // corresponding to pixel positions on that image line. Clone the\n  // satellite positions to make them one per each sight vector. It is\n  // easier to work with things that way later.\n  std::vector<Vector3> full_sat_pos(num_pts);\n  int count = 0;\n  for (int row = 0; row < num_rows; row++) {\n    for (int col = 0; col < num_cols; col++) {\n      full_sat_pos[count] = sat_pos[row];\n      count++;\n    }\n  }\n  if (count != num_pts) \n    vw_throw( ArgumentErr() << \"Book-keeping failure!\\n\" );\n\n  std::vector<double> longitude;\n  asp::read_1d_points(longitude_file, longitude);\n  if (int(longitude.size()) != num_pts)\n    vw_throw( ArgumentErr() << \"Expecting \" << num_pts << \" longitude values in \"\n\t      << longitude_file << \" but got instead \" << longitude.size() << \".\\n\" );\n  \n  std::vector<double> latitude;\n  asp::read_1d_points(latitude_file, latitude);\n  if (int(latitude.size()) != num_pts)\n    vw_throw( ArgumentErr() << \"Expecting \" << num_pts << \" latitude values in \"\n\t      << latitude_file << \" but got instead \" << latitude.size() << \".\\n\" );\n\n  // Covert geocentric latitude to geodetic latitude. Pages 60 and 79 of\n  // https://asterweb.jpl.nasa.gov/content/03_data/04_Documents/aster_user_guide_v2.pdf\n  // Geodetic = Arctan [(tan (Latitude)) / 0.99330562]\n  double deg2rad = M_PI/180.0;\n  for (size_t i = 0; i < latitude.size(); i++) {\n    latitude[i] =  atan (tan (deg2rad*latitude[i]) / 0.99330562)/deg2rad;\n  }\n  \n  std::vector<Vector2> pixels;\n  asp::read_2d_points(lattice_file, pixels);\n  if (int(pixels.size()) != num_pts)\n    vw_throw( ArgumentErr() << \"Expecting \" << num_pts << \" pixels in \"\n\t      << lattice_file << \" but got instead \" << pixels.size() << \".\\n\" );\n\n  // Convert from geodetic coordinates to xyz\n  cartography::Datum datum;\n  datum.set_well_known_datum(\"WGS84\");\n  std::vector<Vector3> ground_xyz(num_pts);\n  for (int i = 0; i < num_pts; i++) {\n    ground_xyz[i] = datum.geodetic_to_cartesian(Vector3(longitude[i], latitude[i], 0));\n  }\n\n  // Create the sight vectors, from the camera center to the ground, in world\n  // coordinates, rather than in spacecraft coordinates, like sight_vec.\n  for (int pt = 0; pt < num_pts; pt++) {\n    Vector3 G = ground_xyz[pt]; \n    Vector3 C = full_sat_pos[pt];\n    int row   = pt/num_cols;\n    world_sight_mat[row].push_back( (G-C)/norm_2(G-C) );\n  }\n  if (world_sight_mat.empty() || (int)world_sight_mat[0].size() != num_cols) {\n    vw_throw( ArgumentErr() << \"Incorrect number of world sight vectors.\\n\");\n  }\n    \n  // Form num_samples layers between min_height and max_height.\n  // Each point there will have its corresponding pixel value.\n  int num_total_pts = num_pts*num_samples;\n  std::vector<Vector3> all_llh (num_total_pts);\n  std::vector<Vector2> all_pixels(num_total_pts);\n  count = 0;\n  for (int sample = 0; sample < num_samples; sample++) {\n    double height = min_height\n      + double(sample)*(max_height - min_height)/(num_samples - 1.0);\n\n    // Find an xyz position at roughly that height on the line\n    // connecting the original ground point and the satellite\n    // center. We need to solve a quadratic equation for that. We\n    // assume the Earth is a sphere.\n    for (int pt = 0; pt < num_pts; pt++) {\n\n      Vector3 A = ground_xyz[pt]; \n      Vector3 B = full_sat_pos[pt];\n      Vector3 D = B - A;\n\n      // Find t such that norm(A + t*D) = norm(A) + height\n      double  d = dot_prod(A, D) * dot_prod(A, D)\n        + dot_prod(D, D) * (height*height + 2*norm_2(A)*height);\n      double  t = ( -dot_prod(A, D) + sqrt(d) ) / dot_prod(D, D);\n      Vector3 P = A + t*D;\n\n      all_llh[count]  = datum.cartesian_to_geodetic(P);\n      all_pixels[count] = pixels[pt];\n      count++;\n    }\n  }\n  \n  // Find the range of lon-lat-heights\n  BBox3 llh_box;\n  for (size_t i = 0; i < all_llh.size(); i++) \n    llh_box.grow(all_llh[i]);\n  \n  // Find the range of pixels\n  BBox2 pixel_box;\n  for (size_t i = 0; i < all_pixels.size(); i++) \n    pixel_box.grow(all_pixels[i]);\n\n  llh_scale  = (llh_box.max() - llh_box.min())/2.0; // half range\n  llh_offset = (llh_box.max() + llh_box.min())/2.0; // center point\n\n  pixel_scale  = (pixel_box.max() - pixel_box.min())/2.0; // half range \n  pixel_offset = (pixel_box.max() + pixel_box.min())/2.0; // center point\n\n  normalized_llh.set_size(asp::RPCModel::GEODETIC_COORD_SIZE*num_total_pts);\n  normalized_pixels.set_size(asp::RPCModel::IMAGE_COORD_SIZE*num_total_pts\n                             + asp::RpcSolveLMA::NUM_PENALTY_TERMS);\n  for (size_t i = 0; i < normalized_pixels.size(); i++) {\n    // Important: The extra penalty terms are all set to zero here.\n    normalized_pixels[i] = 0.0; \n  }\n\n  // Form the arrays of normalized pixels and normalized llh\n  for (int pt = 0; pt < num_total_pts; pt++) {\n\n    // Normalize the pixel to -1 <> 1 range\n    Vector3 llh_n   = elem_quot(all_llh[pt]    - llh_offset,   llh_scale);\n    Vector2 pixel_n = elem_quot(all_pixels[pt] - pixel_offset, pixel_scale);\n\n    subvector(normalized_llh, asp::RPCModel::GEODETIC_COORD_SIZE*pt,\n              asp::RPCModel::GEODETIC_COORD_SIZE) = llh_n;\n    subvector(normalized_pixels, asp::RPCModel::IMAGE_COORD_SIZE*pt,\n              asp::RPCModel::IMAGE_COORD_SIZE   ) = pixel_n;\n    \n  }\n\n  return;\n}\n\n// Save an XML file having all RPC information\nvoid save_xml(int image_cols, int image_rows,\n\t      std::vector< std::vector<Vector2> > const& lattice_mat,\n\t      std::vector< std::vector<Vector3> > const& sight_mat,\n\t      std::vector< std::vector<Vector3> > const& world_sight_mat,\n\t      std::vector<Vector3>                const& sat_pos,\n\t      Vector3 const& llh_scale,\n              Vector3 const& llh_offset,\n              Vector2 const& pixel_scale,\n              Vector2 const& pixel_offset,\n              asp::RPCModel::CoeffVec const& line_num,\n              asp::RPCModel::CoeffVec const& line_den,\n              asp::RPCModel::CoeffVec const& samp_num,\n              asp::RPCModel::CoeffVec const& samp_den,\n              std::string const& out_cam_file){\n\n  std::string lineoffset   = vw::num_to_str(pixel_offset.y());\n  std::string sampoffset   = vw::num_to_str(pixel_offset.x());\n  std::string latoffset    = vw::num_to_str(llh_offset.y());\n  std::string longoffset   = vw::num_to_str(llh_offset.x());\n  std::string heightoffset = vw::num_to_str(llh_offset.z());\n  \n  std::string linescale   = vw::num_to_str(pixel_scale.y());\n  std::string sampscale   = vw::num_to_str(pixel_scale.x());\n  std::string latscale    = vw::num_to_str(llh_scale.y());\n  std::string longscale   = vw::num_to_str(llh_scale.x());\n  std::string heightscale = vw::num_to_str(llh_scale.z());\n\n  std::string linenumcoef = vw::vec_to_str(line_num);\n  std::string linedencoef = vw::vec_to_str(line_den);\n  std::string sampnumcoef = vw::vec_to_str(samp_num);\n  std::string sampdencoef = vw::vec_to_str(samp_den);\n  \n  vw_out() << \"Writing: \" << out_cam_file << std::endl;\n  std::ofstream ofs(out_cam_file.c_str());\n  \n  ofs << \"<isd>\\n\";\n\n  // Rigorous camera model\n\n  // Lattice points\n  ofs << \"    <LATTICE_POINT>\\n\";\n  for (size_t row = 0; row < lattice_mat.size(); row++) {\n    for (size_t col = 0; col < lattice_mat[row].size(); col++) {\n      ofs << vw::vec_to_str(lattice_mat[row][col]) << std::endl;\n    }\n    ofs << std::endl;\n  }\n  ofs << \"    </LATTICE_POINT>\\n\";\n\n  // Sight vector\n  ofs << \"    <SIGHT_VECTOR>\\n\";\n  for (size_t row = 0; row < sight_mat.size(); row++) {\n    for (size_t col = 0; col < sight_mat[row].size(); col++) {\n      ofs << vw::vec_to_str(sight_mat[row][col]) << std::endl;\n    }\n    ofs << std::endl;\n  }\n  ofs << \"    </SIGHT_VECTOR>\\n\";\n\n  // Sight vector in world coordinates\n  ofs << \"    <WORLD_SIGHT_VECTOR>\\n\";\n  for (size_t row = 0; row < world_sight_mat.size(); row++) {\n    for (size_t col = 0; col < world_sight_mat[row].size(); col++) {\n      ofs << vw::vec_to_str(world_sight_mat[row][col]) << std::endl;\n    }\n    ofs << std::endl;\n  }\n  ofs << \"    </WORLD_SIGHT_VECTOR>\\n\";\n  \n  // Satellite position\n  ofs << \"    <SAT_POS>\\n\";\n  for (size_t row = 0; row < sat_pos.size(); row++) {\n    ofs << vw::vec_to_str(sat_pos[row]) << std::endl;\n  }\n  ofs << \"    </SAT_POS>\\n\";\n\n  // Image size\n  ofs << \"    <IMAGE_COLS>\" << image_cols << \"</IMAGE_COLS>\\n\";\n  ofs << \"    <IMAGE_ROWS>\" << image_rows << \"</IMAGE_ROWS>\\n\";\n  \n  // RPC\n  ofs << \"    <RPB>\\n\";\n  ofs << \"        <SATID>ASTER_L1A_VNIR_Band3</SATID>\\n\";\n  ofs << \"        <IMAGE>\\n\";\n  ofs << \"            <LINEOFFSET>\"      << lineoffset   << \"</LINEOFFSET>\\n\";\n  ofs << \"            <SAMPOFFSET>\"      << sampoffset   << \"</SAMPOFFSET>\\n\";\n  ofs << \"            <LATOFFSET>\"       << latoffset    << \"</LATOFFSET>\\n\";\n  ofs << \"            <LONGOFFSET>\"      << longoffset   << \"</LONGOFFSET>\\n\";\n  ofs << \"            <HEIGHTOFFSET>\"    << heightoffset << \"</HEIGHTOFFSET>\\n\";\n  ofs << \"            <LINESCALE>\"       << linescale    << \"</LINESCALE>\\n\";\n  ofs << \"            <SAMPSCALE>\"       << sampscale    << \"</SAMPSCALE>\\n\";\n  ofs << \"            <LATSCALE>\"        << latscale     << \"</LATSCALE>\\n\";\n  ofs << \"            <LONGSCALE>\"       << longscale    << \"</LONGSCALE>\\n\";\n  ofs << \"            <HEIGHTSCALE>\"     << heightscale  << \"</HEIGHTSCALE>\\n\";\n  ofs << \"            <LINENUMCOEFList>\\n\";\n  ofs << \"                <LINENUMCOEF>\" << linenumcoef  << \"</LINENUMCOEF>\\n\";\n  ofs << \"            </LINENUMCOEFList>\\n\";\n  ofs << \"            <LINEDENCOEFList>\\n\";\n  ofs << \"                <LINEDENCOEF>\" << linedencoef  << \"</LINEDENCOEF>\\n\";\n  ofs << \"            </LINEDENCOEFList>\\n\";\n  ofs << \"            <SAMPNUMCOEFList>\\n\";\n  ofs << \"                <SAMPNUMCOEF>\" << sampnumcoef  << \"</SAMPNUMCOEF>\\n\";\n  ofs << \"            </SAMPNUMCOEFList>\\n\";\n  ofs << \"            <SAMPDENCOEFList>\\n\";\n  ofs << \"                <SAMPDENCOEF>\" << sampdencoef  << \"</SAMPDENCOEF>\\n\";\n  ofs << \"            </SAMPDENCOEFList>\\n\";\n  ofs << \"        </IMAGE>\\n\";\n  ofs << \"    </RPB>\\n\";\n  ofs << \"</isd>\\n\";\n  ofs.close();\n}\n\n// Create XML files containing rigorous camera info, and compute the RPC coefficients as well.\nvoid gen_xml(double min_height, double max_height, int num_samples,\n\t     double penalty_weight,\n\t     std::string const& image_file,\n\t     std::string const& sat_pos_file,\n\t     std::string const& sight_vec_file,\n\t     std::string const& longitude_file,\n\t     std::string const& latitude_file,\n\t     std::string const& lattice_file,\n\t     std::string const& out_cam_file){\n  \n  std::vector< std::vector<Vector2> > lattice_mat;\n  asp::read_matrix_from_file(lattice_file, lattice_mat);\n  \n  std::vector< std::vector<Vector3> > sight_mat;\n  asp::read_matrix_from_file(sight_vec_file, sight_mat);\n  \n  if (lattice_mat.empty() || sight_mat.empty()     ||\n      lattice_mat.size()     != sight_mat.size()   ||\n      lattice_mat[0].size() != sight_mat[0].size() ) {\n    vw_throw( ArgumentErr() << \"Inconsistent lattice point and sight vector information.\\n\");\n  }\n\n  // Read the satellite positions\n  std::vector<Vector3> sat_pos;\n  asp::read_3d_points(sat_pos_file, sat_pos);\n  if (sat_pos.size() != sight_mat.size()) \n    vw_throw( ArgumentErr() << \"Inconsistent satellite position and sight vector information.\\n\");\n    \n  Vector3 llh_scale, llh_offset;\n  Vector2 pixel_scale, pixel_offset;\n  Vector<double> normalized_llh;\n  Vector<double> normalized_pixels;\n  std::vector< std::vector<vw::Vector3> > world_sight_mat; // sight dir in world coords\n  generate_point_pairs(// inputs\n                       min_height, max_height, num_samples, penalty_weight,  \n                       sat_pos_file, sight_vec_file,  \n                       longitude_file, latitude_file, lattice_file,  \n                       // Outputs\n\t\t       world_sight_mat, \n                       llh_scale, llh_offset,  \n                       pixel_scale, pixel_offset,  \n                       normalized_llh,  \n                       normalized_pixels);\n  \n  // Find the RPC coefficients\n  asp::RPCModel::CoeffVec line_num, line_den, samp_num, samp_den;\n  std::string output_prefix = \"\"; \n  asp::gen_rpc(// Inputs\n               penalty_weight, output_prefix,\n               normalized_llh, normalized_pixels,  \n               llh_scale, llh_offset, pixel_scale, pixel_offset,\n               // Outputs\n               line_num, line_den, samp_num, samp_den);\n  \n#if 0\n  // Dump the output to stdout\n  asp::print_vec(\"pixel_scale\",  pixel_scale );\n  asp::print_vec(\"pixel_offset\", pixel_offset);\n  asp::print_vec(\"llh_scale\",    llh_scale   );\n  asp::print_vec(\"llh_offset\",   llh_offset  );\n  asp::print_vec(\"line_num\",     line_num    );\n  asp::print_vec(\"line_den\",     line_den    );\n  asp::print_vec(\"samp_num\",     samp_num    );\n  asp::print_vec(\"samp_den\",     samp_den    );\n#endif\n\n  int image_cols, image_rows;\n  DiskImageView<float> input_img(image_file);\n  image_cols = input_img.cols();\n  image_rows = input_img.rows();\n  \n  save_xml(image_cols, image_rows, lattice_mat,\n\t   sight_mat, world_sight_mat, sat_pos,\n\t   llh_scale, llh_offset, pixel_scale, pixel_offset,  \n           line_num, line_den, samp_num, samp_den,  \n           out_cam_file);\n}\n\nint main( int argc, char *argv[] ) {\n\n  Options opt;\n  try {\n    handle_arguments(argc, argv, opt);\n\n    std::string nadir_image, back_image, nadir_sat_pos, back_sat_pos;\n    std::string nadir_sight_vec, back_sight_vec;\n    std::string nadir_corr_table, back_corr_table;\n    std::string nadir_longitude, back_longitude;\n    std::string nadir_latitude, back_latitude;\n    std::string nadir_lattice_point, back_lattice_point;\n    \n    locate_inputs(opt, nadir_image, back_image, nadir_sat_pos, back_sat_pos,\n\t\t  nadir_sight_vec, back_sight_vec, nadir_corr_table, back_corr_table,\n\t\t  nadir_longitude, back_longitude, nadir_latitude, back_latitude,\n\t\t  nadir_lattice_point, back_lattice_point);\n\n    std::string out_nadir_image = opt.output_prefix + \"-Band3N.tif\";\n    std::string out_back_image  = opt.output_prefix + \"-Band3B.tif\";\n    \n    std::string out_nadir_cam = opt.output_prefix + \"-Band3N.xml\";\n    std::string out_back_cam  = opt.output_prefix + \"-Band3B.xml\";\n\n#if 0\n    std::cout \t<< \"nadir_image             \" \t<< nadir_image \t\t<< std::endl;\n    std::cout \t<< \"back_image              \" \t<< back_image \t\t<< std::endl;\n    std::cout \t<< \"nadir_sat_pos           \" \t<< nadir_sat_pos \t<< std::endl;\n    std::cout \t<< \"back_sat_pos            \" \t<< back_sat_pos \t<< std::endl;\n    std::cout \t<< \"nadir_sight_vec         \" \t<< nadir_sight_vec \t<< std::endl;\n    std::cout \t<< \"back_sight_vec          \" \t<< back_sight_vec \t<< std::endl;\n    std::cout \t<< \"nadir_corr_table        \" \t<< nadir_corr_table \t<< std::endl;\n    std::cout \t<< \"back_corr_table         \" \t<< back_corr_table \t<< std::endl;\n    std::cout \t<< \"nadir_longitude         \" \t<< nadir_longitude \t<< std::endl;\n    std::cout \t<< \"back_longitude          \" \t<< back_longitude \t<< std::endl;\n    std::cout \t<< \"nadir_latitude          \" \t<< nadir_latitude \t<< std::endl;\n    std::cout \t<< \"back_latitude           \" \t<< back_latitude \t<< std::endl;\n    std::cout \t<< \"nadir_lattice_point     \" \t<< nadir_lattice_point \t<< std::endl;\n    std::cout \t<< \"back_lattice_point      \" \t<< back_lattice_point \t<< std::endl;\n    std::cout \t<< \"output nadir image:     \" \t<< out_nadir_image \t<< ' '\n              \t<< out_nadir_cam \t\t<< std::endl;\n    std::cout \t<< \"output back image:      \" \t<< out_back_image  \t<< ' '\n              \t<< out_back_cam  \t\t<< std::endl;\n#endif\n    \n    gen_xml(opt.min_height, opt.max_height, opt.num_samples, opt.penalty_weight,\n\t    nadir_image, nadir_sat_pos, nadir_sight_vec, nadir_longitude, nadir_latitude,  \n\t    nadir_lattice_point, out_nadir_cam);\n    \n    gen_xml(opt.min_height, opt.max_height, opt.num_samples, opt.penalty_weight,\n\t    back_image, back_sat_pos, back_sight_vec, back_longitude, back_latitude,  \n\t    back_lattice_point, out_back_cam);\n    \n    apply_radiometric_corrections(opt, nadir_image, nadir_corr_table, out_nadir_image);\n    apply_radiometric_corrections(opt, back_image,  back_corr_table,  out_back_image);\n    \n  } ASP_STANDARD_CATCHES;\n\n  return 0;\n}\n", "meta": {"hexsha": "4e3c548458f4a2352b58655b5648f3f75cce6ae7", "size": 30937, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Tools/aster2asp.cc", "max_stars_repo_name": "AndrewAnnex/StereoPipeline", "max_stars_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "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/Tools/aster2asp.cc", "max_issues_repo_name": "AndrewAnnex/StereoPipeline", "max_issues_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "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/Tools/aster2asp.cc", "max_forks_repo_name": "AndrewAnnex/StereoPipeline", "max_forks_repo_head_hexsha": "084c3293c3a5382b052177c74388d9beeb79cf0b", "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": 40.5997375328, "max_line_length": 139, "alphanum_fraction": 0.6472831884, "num_tokens": 8474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.041462267973656895, "lm_q1q2_score": 0.02056917529760091}}
{"text": "/**\r\n * @file robot.cpp\r\n * @author Kavyashree Devadiga (kavya@umd.edu), Aswath Muthuselvam\r\n * (aswath@umd.edu)\r\n * @brief File for robot class method definitions\r\n * @version 0.1\r\n * @date 2021-10-05\r\n * @copyright All rights reserved\r\n *\r\n */\r\n\r\n#include \"robot.h\"  // NOLINT\r\n\r\n#include <unistd.h>\r\n\r\n#include <Eigen/Dense>\r\n#include <cmath>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include \"simulator.h\"  // NOLINT\r\n#include \"solver.h\"     //NOLINT\r\n\r\nusing Eigen::Matrix4d;\r\nusing Eigen::MatrixXd;\r\nusing std::cin;\r\nusing std::cout;\r\nusing std::endl;\r\nusing std::vector;\r\n\r\nRobot::Robot(Simulator* simulator_) {\r\n  simulator = simulator_;\r\n  ///< Variable to store origin\r\n  char origin_name[] = \"Floor\";\r\n\r\n  ///< Variable to store robot joint names\r\n  char joint_names[6][11] = {\"UR5_joint1\", \"UR5_joint2\", \"UR5_joint3\",\r\n                             \"UR5_joint4\", \"UR5_joint5\", \"UR5_joint6\"};\r\n\r\n  ///< Variable to store robot link names\r\n  char link_names[6][11] = {\"UR5_link1\", \"UR5_link2\", \"UR5_link3\",\r\n                            \"UR5_link4\", \"UR5_link5\", \"UR5_link6\"};\r\n\r\n  ///< Assign IDs values to handles\r\n  origin_handle = simulator->GetObjectHandle(origin_name);\r\n\r\n  for (int it = 0; it < 6; it++) {\r\n    joint_handle.push_back(simulator->GetObjectHandle(joint_names[it]));\r\n    link_handle.push_back(simulator->GetObjectHandle(link_names[it]));\r\n\r\n    // cout << \"\\n------Joint matrix \" << it + 1 << \" --------\\n\";\r\n    // float* joint_ptr = new float[12];\r\n    // joint_matrix.push_back(joint_ptr);\r\n    // simulator->GetJointMatrix(joint_handle[it], joint_matrix[it]);\r\n\r\n    // cout << \"\\n------Link matrix \" << it << \" --------\\n\";\r\n    // float* link_ptr = new float[12];\r\n    // link_matrix.push_back(link_ptr);\r\n    // simulator->GetJointMatrix(link_handle[it], link_matrix[it]);\r\n  }\r\n\r\n  solver = new Solver(simulator, joint_handle);\r\n}\r\n\r\nbool Robot::Initialize() {\r\n  State state;\r\n  try {\r\n    float theta = 0.5;\r\n    //< Perform some actions by commanding joint angles(in radians).\r\n    Controller(theta, theta, theta, theta, theta, theta);\r\n\r\n    sleep(1);\r\n\r\n    //< Get positions of objects(joints in this case).\r\n    simxFloat position[3];\r\n    simxFloat orientation[3];\r\n\r\n    ChainTransformations();\r\n\r\n    for (int it = 0; it < 6; it++) {\r\n      cout << \"\\n------Joint position of \" << it + 1\r\n           << \" [x, y, x] wrt to Origin --------\\n\";\r\n      simulator->GetObjectPosition(joint_handle[it], origin_handle, position);\r\n      simulator->GetObjectOrientation(joint_handle[it], origin_handle,\r\n                                      orientation);\r\n    }\r\n\r\n    cout << \"\\n---Joint position and orientation of 1\"\r\n         << \"  wrt to \"\r\n         << \" orgin is: \"\r\n         << \"---\\n\";\r\n    simulator->GetObjectPosition(joint_handle[0], origin_handle, position);\r\n    simulator->GetObjectOrientation(joint_handle[0], origin_handle,\r\n                                    orientation);\r\n    for (int it = 1; it < 6; it++) {\r\n      cout << \"\\n---Joint position and orientation of \" << it + 1 << \"  wrt to \"\r\n           << it << \" th joint\"\r\n           << \"---\\n\";\r\n      simulator->GetObjectPosition(joint_handle[it], joint_handle[it - 1],\r\n                                   position);\r\n      simulator->GetObjectOrientation(joint_handle[it], joint_handle[it - 1],\r\n                                      orientation);\r\n    }\r\n\r\n    //< Set a Joint Position.\r\n    // simulator->SetJointPosition(joint_handle[0], position);\r\n    // cout << position[0];\r\n    return true;\r\n  } catch (const char* msg) { /* catch exception if any */\r\n    std::cout << \"Exception occurred\" << std::endl;\r\n    return false;\r\n  }\r\n}\r\n\r\nvoid Robot::ChainTransformations() {\r\n  cout << \"\\nTransfomation matrix chain from Origin to End Effector:\" << endl;\r\n  double t1, t2, t3, t4, t5;  // t6;\r\n  double a1 = -0.0703083;\r\n  double d1 = 0.0660392;\r\n  double a2 = 0.425103;\r\n  // double d2 = 0;\r\n  double a3 = 0.392149;\r\n  double a4 = 0.0455737;\r\n  double d4 = 0.0397052;\r\n  double d5 = 0.0491754;\r\n  double a5 = 0.0144247;\r\n\r\n  t1 = simulator->GetJointAngle(joint_handle[0]);\r\n  t2 = simulator->GetJointAngle(joint_handle[1]);\r\n  t3 = simulator->GetJointAngle(joint_handle[2]);\r\n  t4 = simulator->GetJointAngle(joint_handle[3]);\r\n  t5 = simulator->GetJointAngle(joint_handle[4]);\r\n  // t6 = simulator->GetJointAngle(joint_handle[5]);\r\n\r\n  // Vector3f ot; << 0.3, -0.275, 0.04315;\r\n  Matrix4d T(4, 4);\r\n  T << 1, 0, 0, 0.3, 0, 1, 0, -0.275, 0, 0, 1, 0.04315, 0, 0, 0, 1;  // j1\r\n\r\n  Matrix4d Tn(4, 4);\r\n\r\n  Tn << cos(t1), -sin(t1), 0, a1, sin(t1), cos(t1), 0, 1.2219E-06, 0, 0, 1, d1,\r\n      0, 0, 0, 1;\r\n  T = T * Tn;\r\n\r\n  // T = T*[roty(-90) z'; z 1]*[rotz(-90) z'; z 1]; %j2\r\n  /*\r\n  Tn << 0, 0, -1, 0,\r\n  -1, 0, 0, 0,\r\n  0, 1, 0, 0,\r\n  0, 0, 0, 1;\r\n  */\r\n\r\n  // T = T*[roty(-90) z'; z 1]\r\n  Tn << 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1;\r\n\r\n  T = T * Tn;  // j2\r\n\r\n  Tn << cos(t2), -sin(t2), 0, a2, sin(t2), cos(t2), 0, 1.74344e-05, 0, 0, 1,\r\n      9.50694e-06, 0, 0, 0, 1;\r\n  T = T * Tn;  // j3\r\n\r\n  Tn << cos(t3), -sin(t3), 0, a3, sin(t3), cos(t3), 0, -1.60933e-06, 0, 0, 1,\r\n      1.40071e-06, 0, 0, 0, 1;\r\n  T = T * Tn;  // j4\r\n\r\n  Tn << cos(t4), -sin(t4), 0, a4, sin(t4), cos(t4), 0, 2.95043e-06, 0, 0, 1, d4,\r\n      0, 0, 0, 1;\r\n  T = T * Tn;\r\n  // T = T*[roty(90) [0 0 0]'; z 1]; %j5\r\n  Tn << 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 1;\r\n  T = T * Tn;\r\n\r\n  // T = T*[Rz(t5) [a5 0 d5]'; z 1]; %j6\r\n  Tn << cos(t5), -sin(t5), 0, a5, sin(t5), cos(t5), 0, 3.27826e-07, 0, 0, 1, d5,\r\n      0, 0, 0, 1;\r\n  T = T * Tn;\r\n  // T = T*[roty(-90) [0 0 0]'; z 1];\r\n  Tn << 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1;\r\n  T = T * Tn;\r\n\r\n  GetEndEffectorPosition();\r\n  float error = pow(pow(state.x - T(0, 3), 2) + pow(state.y - T(1, 3), 2) +\r\n                        pow(state.z - T(2, 3), 2),\r\n                    0.5);\r\n  cout << \"\\nTransformation matrix is: \\n\" << T << endl;\r\n  cout << \" Error is: \" << error;\r\n}\r\n\r\nvoid Robot::GetEndEffectorPosition() {\r\n  simxFloat position[3];\r\n  simulator->GetObjectPosition(joint_handle[5], origin_handle, position);\r\n  state.x = position[0];\r\n  state.y = position[1];\r\n  state.z = position[2];\r\n}\r\n\r\nvector<double> Robot::TrajectoryPlanner(double goal_x, double goal_y,\r\n                                        double goal_z) {\r\n  GetEndEffectorPosition();\r\n  std::vector<double> dx_dy_dz = {(goal_x - state.x) * 0.005,\r\n                                  (goal_y - state.y) * 0.005,\r\n                                  (goal_z - state.z) * 0.005};\r\n  return dx_dy_dz;\r\n}\r\n\r\nbool Robot::Controller(float t1, float t2, float t3, float t4, float t5,\r\n                       float t6) {\r\n  simulator->SetJointTargetAngle(joint_handle[0], t1);\r\n  simulator->SetJointTargetAngle(joint_handle[1], t2);\r\n  simulator->SetJointTargetAngle(joint_handle[2], t3);\r\n  simulator->SetJointTargetAngle(joint_handle[3], t4);\r\n  simulator->SetJointTargetAngle(joint_handle[4], t5);\r\n  simulator->SetJointTargetAngle(joint_handle[5], t6);\r\n  return true;\r\n}\r\n\r\nbool Robot::Solve(double goal_x, double goal_y, double goal_z) {\r\n  double start_x, start_y, start_z;\r\n  GetEndEffectorPosition();\r\n  start_x = state.x;\r\n  start_y = state.y;\r\n  start_z = state.z;\r\n  double dxt = 0, dyt = 0, dzt = 0;\r\n  float absolute_error =\r\n      pow(pow((state.x - goal_x), 2) + pow((state.y - goal_y), 2) +\r\n              pow((state.z - goal_z), 2),\r\n          0.5);\r\n  float threshold = 0.3;\r\n  double t1, t2, t3, t4, t5, t6;\r\n\r\n  while (absolute_error > threshold) {\r\n\r\n    std::vector<double> dx_dy_dz = TrajectoryPlanner(goal_x, goal_y, goal_z);\r\n    dxt += dx_dy_dz[0];\r\n    dyt += dx_dy_dz[1];\r\n    dzt += dx_dy_dz[2];\r\n    t1 = simulator->GetJointAngle(joint_handle[0]);\r\n    t2 = simulator->GetJointAngle(joint_handle[1]);\r\n    t3 = simulator->GetJointAngle(joint_handle[2]);\r\n    t4 = simulator->GetJointAngle(joint_handle[3]);\r\n    t5 = simulator->GetJointAngle(joint_handle[4]);\r\n    t6 = simulator->GetJointAngle(joint_handle[5]);\r\n\r\n    MatrixXd q_(4, 1);\r\n    bool status = solver->PerformIK(dx_dy_dz[0], dx_dy_dz[1], dx_dy_dz[2], &q_);\r\n    if (!status) {\r\n      cout << \"IK calculation failed, trying again in next iteration.\" << endl;\r\n      Controller(t1 + 0.0001, t2 + 0.0001, t3 + 0.0001, t4 + 0.0001,\r\n                 t5 + 0.0001, t6 + 0.0001);\r\n      continue;\r\n    }\r\n    cout << \"\\n\\nQ is: \" << q_.transpose() << endl;\r\n    t1 += q_(0, 0);\r\n    t2 += q_(1, 0);\r\n    t3 += q_(2, 0);\r\n    t4 += q_(3, 0);\r\n    float error = pow(pow((state.x - start_x + dxt), 2) +\r\n                          pow((state.y - start_y + dyt), 2) +\r\n                          pow((state.z - start_z + dzt), 2),\r\n                      0.5);\r\n    cout << \"Error from current desired position: \" << error << endl;\r\n    if (solver->IsErrorTolerable(error)) {\r\n      cout << \"Error is within tolerable limits\" << endl;\r\n    }\r\n    Controller(t1, t2, t3, t4, t5, t6);\r\n    absolute_error =\r\n        pow(pow((state.x - goal_x), 2) + pow((state.y - goal_y), 2) +\r\n                pow((state.z - goal_z), 2),\r\n            0.5);\r\n    cout << \"Distance from goal position: \" << absolute_error << endl;\r\n    sleep(0.3);\r\n\r\n  }\r\n\r\n  cout << \"Successfully reached goal position! \" << absolute_error << endl;\r\n\r\n  return true;\r\n}\r\n", "meta": {"hexsha": "6dc51355a72562bd6a1da9f0207be3e137abfcf7", "size": 9255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/robot.cpp", "max_stars_repo_name": "aswathselvam/AcmeRoboticsPathPlanner", "max_stars_repo_head_hexsha": "9e09bce423eca87d3371acfa9df1a285d2608361", "max_stars_repo_licenses": ["MIT"], "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/robot.cpp", "max_issues_repo_name": "aswathselvam/AcmeRoboticsPathPlanner", "max_issues_repo_head_hexsha": "9e09bce423eca87d3371acfa9df1a285d2608361", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-13T14:15:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-13T14:15:31.000Z", "max_forks_repo_path": "app/robot.cpp", "max_forks_repo_name": "aswathselvam/AcmeRoboticsPathPlanner", "max_forks_repo_head_hexsha": "9e09bce423eca87d3371acfa9df1a285d2608361", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-10T07:26:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T07:26:29.000Z", "avg_line_length": 33.1720430108, "max_line_length": 81, "alphanum_fraction": 0.548352242, "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.056652430484325014, "lm_q1q2_score": 0.020563086902870457}}
{"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 *      110221    K. Kumar          File created.\n *      110224    K. Kumar          Renamed class and file.\n *      110629    L. van der Ham    Added circular coplanar case.\n *      110803    L. van der Ham    Created base class and seperated approximatePlanetPositions\n *                                  from approximatePlanetPositionsCircularCoplanar.\n *      120322    D. Dirkx          Modified to new Ephemeris interfaces.\n *\n *    References\n *      Standish, E.M. Keplerian Elements for Approximate Positions of the Major Planets,\n *          http://ssd.jpl.nasa.gov/txt/aprx_pos_planets.pdf, last accessed: 24 February, 2011.\n *\n *    Notes\n *\n */\n\n#include <iostream>\n\n#include <boost/exception/all.hpp>\n#include <boost/format.hpp>\n#include <boost/throw_exception.hpp>\n\n#include \"Tudat/Astrodynamics/Ephemerides/approximatePlanetPositionsBase.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace ephemerides\n{\n\n//! Set planet.\nvoid ApproximatePlanetPositionsBase::setPlanet( BodiesWithEphemerisData bodyWithEphemerisData )\n{\n    // Check if ephemeris data has been loaded, and reload data if not.\n    if ( containerOfDataFromEphemerisFile_.size( ) == 0 )\n    {\n        reloadData( );\n    }\n\n    switch ( bodyWithEphemerisData )\n    {\n    case mercury:\n\n        parseEphemerisLineData_( 18 );\n        break;\n\n    case venus:\n\n        parseEphemerisLineData_( 20 );\n        break;\n\n    case earthMoonBarycenter:\n\n        parseEphemerisLineData_( 22 );\n        break;\n\n    case mars:\n\n        parseEphemerisLineData_( 24 );\n        break;\n\n    case jupiter:\n\n        parseEphemerisLineData_( 26 );\n        parseExtraTermsEphemerisLineData_( 48 );\n        break;\n\n    case saturn:\n\n        parseEphemerisLineData_( 28 );\n        parseExtraTermsEphemerisLineData_( 49 );\n        break;\n\n    case uranus:\n\n        parseEphemerisLineData_( 30 );\n        parseExtraTermsEphemerisLineData_( 50 );\n        break;\n\n    case neptune:\n\n        parseEphemerisLineData_( 32 );\n        parseExtraTermsEphemerisLineData_( 51 );\n        break;\n\n    case pluto:\n\n        parseEphemerisLineData_( 34 );\n        parseExtraTermsEphemerisLineData_( 52 );\n        break;\n\n    default:\n        break;\n    }\n}\n\n//! Parse ephemeris line data.\nvoid ApproximatePlanetPositionsBase::parseEphemerisLineData_( const unsigned int& firstLineNumber )\n{\n    // Parse data from container of strings using a string stream.\n\n    // Clear stringstream.\n    ephemerisLineData_.clear( );\n\n    // Read first line of data.\n    ephemerisLineData_ << containerOfDataFromEphemerisFile_[ firstLineNumber ];\n\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.planetName_;\n\n    // Check if the line number corresponds to that for \"EM Bary\".\n    if ( firstLineNumber == 22 )\n    {\n        std::string earthMoonBarycenter_;\n\n        ephemerisLineData_ >> earthMoonBarycenter_;\n        approximatePlanetPositionsDataContainer_.planetName_ += \" \" + earthMoonBarycenter_;\n    }\n\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.semiMajorAxis_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.eccentricity_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.inclination_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.meanLongitude_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.longitudeOfPerihelion_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.longitudeOfAscendingNode_;\n\n    // Clear stringstream.\n    ephemerisLineData_.clear( );\n\n    // Read second line of data.\n    ephemerisLineData_ << containerOfDataFromEphemerisFile_[ firstLineNumber + 1 ];\n\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.rateOfChangeOfSemiMajorAxis_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.rateOfChangeOfEccentricity_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.rateOfChangeOfInclination_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.rateOfChangeOfMeanLongitude_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_\n                          .rateOfChangeOfLongitudeOfPerihelion_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_\n                          .rateOfChangeOfLongitudeOfAscendingNode_;\n}\n\n//! Parse line data for extra terms for ephemeris.\nvoid ApproximatePlanetPositionsBase::parseExtraTermsEphemerisLineData_(\n    const unsigned int& lineNumber )\n{\n    // Clear stringstream.\n    ephemerisLineData_.clear( );\n\n    // Read second line of data.\n    ephemerisLineData_<< containerOfDataFromEphemerisFile_[ lineNumber ];\n\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.planetName_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.additionalTermB_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.additionalTermC_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.additionalTermS_;\n    ephemerisLineData_ >> approximatePlanetPositionsDataContainer_.additionalTermF_;\n}\n\n//! Load in ephemeris data for planets.\nvoid ApproximatePlanetPositionsBase::reloadData( )\n{\n    // Set  path to ephemeris file in file reader.\n    std::string filePath_ = input_output::getTudatRootPath( ) +\n            \"External/EphemerisData/p_elem_t2.txt\";\n\n    // Open ephemeris file.\n    std::ifstream ephemerisFile_( filePath_.c_str( ) );\n    if ( ephemerisFile_.fail( ) )\n    {\n        boost::throw_exception(\n                    boost::enable_error_info(\n                        std::runtime_error(\n                            boost::str( boost::format( \"Data file '%s' could not be opened.\" )\n                                 % filePath_.c_str( ) ) ) )\n            << boost::errinfo_file_name( filePath_.c_str( ) )\n            << boost::errinfo_file_open_mode( \"std::ios::binary\" )\n            << boost::errinfo_api_function( \"std::ifstream::open\" ) );\n    }\n\n    // Read the file into a container.\n    for ( int line = 1; line < 53; line++ )\n    {\n        std::string lineData;\n        getline( ephemerisFile_, lineData );\n        containerOfDataFromEphemerisFile_[line] = lineData;\n        if ( ephemerisFile_.fail( ) )\n        {\n            break;\n        }\n    }\n\n    // Close file.\n    ephemerisFile_.close( );\n}\n\n} // namespace ephemerides\n} // namespace tudat\n", "meta": {"hexsha": "57652b74b4aa862041f591ae6851517c9f4bc389", "size": 8092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Ephemerides/approximatePlanetPositionsBase.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/approximatePlanetPositionsBase.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/approximatePlanetPositionsBase.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": 36.2869955157, "max_line_length": 99, "alphanum_fraction": 0.7025457242, "num_tokens": 1940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.056652423715250484, "lm_q1q2_score": 0.020563085226685165}}
{"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 \"transposition_to_circuit.hpp\"\n\n#include <boost/assign/std/vector.hpp>\n\n#include \"../circuit.hpp\"\n#include \"../gate.hpp\"\n\n#include \"add_circuit.hpp\"\n#include \"add_gates.hpp\"\n#include \"reverse_circuit.hpp\"\n\nusing namespace boost::assign;\n\nnamespace cirkit\n{\n  bool transposition_to_circuit( circuit& circ, const boost::dynamic_bitset<>& inputs, const boost::dynamic_bitset<>& outputs )\n  {\n    assert( inputs.size() == outputs.size() );\n    assert( circ.lines() == inputs.size() );\n\n    unsigned b = 0u, bs = 0u;\n    circuit circ_block_a( inputs.size() );\n    circuit circ_block_b( inputs.size() );\n    circuit circ_block_bs( inputs.size() );\n    circuit circ_block_c( inputs.size() );\n    circuit circ_block_X( inputs.size() );\n    append_not( circ_block_X, 0u );\n    gate::control_container controls;\n    unsigned target;\n\n    for ( unsigned j = 0u; j < inputs.size(); ++j )\n    {\n      target = inputs.size() - 1u - j;\n      if ( !inputs.test( j ) && !outputs.test( j ) )\n      {\n        append_not( circ_block_a, target );\n      }\n      else if ( inputs.test( j ) && !outputs.test( j ) )\n      {\n        controls.clear();\n        append_not( circ_block_b, target );\n        ++b;\n        append_not( circ_block_c, target );\n        for ( unsigned k = 0u; k < inputs.size(); ++k )\n        {\n          if ( k != target )\n          {\n            controls += make_var( k );\n          }\n        }\n        append_toffoli( circ_block_c, controls, target );\n        circ_block_X.remove_gate_at( 0u );\n        append_toffoli( circ_block_X, controls, target );\n      }\n      else if ( !inputs.test( j ) && outputs.test( j ) )\n      {\n        controls.clear();\n        append_not( circ_block_bs, target );\n        ++bs;\n        append_not( circ_block_c, target );\n        for ( unsigned k = 0u; k < inputs.size(); ++k )\n        {\n          if ( k != target )\n          {\n            controls += make_var( k );\n          }\n        }\n        append_toffoli( circ_block_c, controls, target );\n        circ_block_X.remove_gate_at( 0u );\n        append_toffoli( circ_block_X, controls, target );\n      }\n    }\n\n    circ_block_c.remove_gate_at( circ_block_c.num_gates() - 1 );\n    circ_block_c.remove_gate_at( circ_block_c.num_gates() - 1 );\n\n    append_circuit( circ, circ_block_a );\n    if ( b < bs )\n    {\n      append_circuit( circ, circ_block_b );\n    }\n    else\n    {\n      append_circuit( circ, circ_block_bs );\n    }\n    append_circuit( circ, circ_block_c );\n\n    append_circuit( circ, circ_block_X );\n\n    reverse_circuit( circ_block_c );\n    append_circuit( circ, circ_block_c );\n\n    if ( b < bs )\n    {\n      append_circuit( circ, circ_block_b );\n    }\n    else\n    {\n      append_circuit( circ, circ_block_bs );\n    }\n    append_circuit( circ, circ_block_a );\n\n    return true;\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": "3e10b170881cdd78979ecb5e9d17eeb3d7f946fb", "size": 4125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/functions/transposition_to_circuit.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/functions/transposition_to_circuit.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/functions/transposition_to_circuit.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": 29.8913043478, "max_line_length": 127, "alphanum_fraction": 0.6334545455, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.04208772581295733, "lm_q1q2_score": 0.020550737660230953}}
{"text": "#ifndef __PARTICLEFILTER_HPP__\r\n#define __PARTICLEFILTER_HPP__\r\n\r\n#include <vector>\r\n#include <ros/ros.h>\r\n#include <message_filters/subscriber.h>\r\n#include <message_filters/time_synchronizer.h>\r\n#include <std_msgs/Bool.h>\r\n#include <visualization_msgs/Marker.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/transform_listener.h>\r\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\r\n#include <geometry_msgs/PoseArray.h>\r\n#include <sensor_msgs/NavSatFix.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <vector>\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_randist.h>\r\n#include <boost/random/normal_distribution.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n#include <time.h>\r\n#include <math.h>\r\n#include <sewer_graph/sewer_graph.h>\r\n#include <fstream>\r\n#include <wall_detector/WallInfo.h>\r\n#include <cmath>\r\n#include <manhole_detector/Manhole.h>\r\n#include <std_msgs/Float32.h>\r\n\r\n// Particle filter Update type\r\nenum UpdateType {\r\n  REGULAR, MANHOLE, FORK, ANGULAR, YAW, GROUND_TRUTH, UNKNOWN = 100\r\n};\r\n\r\n//Struct that contains the data concerning one Particle\r\nstruct Particle\r\n{\r\n  //Position\r\n  float x;\r\n  float y;\r\n\r\n  // Yaw angle (with respect to MAP frame)\r\n  float a;\r\n\r\n  // Weight (One weight)\r\n  float w;\r\n};\r\n\r\n//Class definition\r\nclass ParticleFilter\r\n{\r\npublic:\r\n\r\n  //!Default contructor\r\n  ParticleFilter(std::string &node_name) : lnh(\"~\"),\r\n  m_randVar(boost::mt19937(time(0)), boost::normal_distribution<>(0, 0.4)), s_g(NULL)\r\n  {\r\n    // Setup random number generator from GSL\r\n    gsl_rng_env_setup();\r\n    m_randomType = gsl_rng_default;\r\n    m_randomValue = gsl_rng_alloc(m_randomType);\r\n\r\n    // Read node parameters\r\n    if(!lnh.getParam(\"base_frame_id\", m_baseFrameId))\r\n      m_baseFrameId = \"base_link_vo\";\r\n    if(!lnh.getParam(\"odom_frame_id\", m_odomFrameId))\r\n      m_odomFrameId = \"odom\";\r\n    if(!lnh.getParam(\"global_frame_id\", m_globalFrameId))\r\n      m_globalFrameId = \"map\";\r\n\r\n    m_lastPoseCov.header.frame_id = m_globalFrameId;\r\n\r\n    // Read amcl parameters\r\n    if(!lnh.getParam(\"update_rate\", m_updateRate))\r\n      m_updateRate = 10.0;\r\n    if(!lnh.getParam(\"angular_rate\", m_angularRate))\r\n      m_angularRate = 0.2;\r\n    if(!lnh.getParam(\"min_particles\", m_minParticles))\r\n      m_minParticles = 300;\r\n    if(!lnh.getParam(\"max_particles\", m_maxParticles))\r\n      m_maxParticles = 600;\r\n    if(m_minParticles > m_maxParticles)\r\n      m_maxParticles = m_minParticles;\r\n    if(!lnh.getParam(\"odom_x_mod\", m_odomXMod))\r\n      m_odomXMod = 0.2;\r\n    if(!lnh.getParam(\"odom_y_mod\", m_odomYMod))\r\n      m_odomYMod = 0.2;\r\n    if(!lnh.getParam(\"odom_a_mod\", m_odomAMod))\r\n      m_odomAMod = 0.2;\r\n    if(!lnh.getParam(\"odom_a_noise\", m_odomANoise))\r\n      m_odomANoise = 0.05;\r\n    if(!lnh.getParam(\"initial_x\", m_initX))\r\n      m_initX = 0.0;\r\n    if(!lnh.getParam(\"initial_y\", m_initY))\r\n      m_initY = 0.0;\r\n    if(!lnh.getParam(\"initial_a\", m_initA))\r\n      m_initA = 0.0;\r\n    if(!lnh.getParam(\"initial_x_dev\", m_initXDev))\r\n      m_initXDev = 0.3;\r\n    if(!lnh.getParam(\"initial_y_dev\", m_initYDev))\r\n      m_initYDev = 0.3;\r\n    if(!lnh.getParam(\"initial_a_dev\", m_initADev))\r\n      m_initADev = 0.2;\r\n    if(!lnh.getParam(\"update_min_d\", m_dTh))\r\n      m_dTh = 0.5;\r\n    if(!lnh.getParam(\"update_min_a\", m_aTh))\r\n      m_aTh = 0.2;\r\n    if(!lnh.getParam(\"resample_interval\", m_resampleInterval))\r\n      m_resampleInterval = 0;\r\n    // Get the parameters related with the sewer\r\n    if (!lnh.getParam(\"detect_manhole_topic\", m_detectManholeTopic))\r\n      m_detectManholeTopic = \"/manhole\";\r\n\r\n    if (!lnh.getParam(\"angular_weight\", angular_weight))\r\n      angular_weight = 5.0;\r\n\r\n\r\n    if (!lnh.getParam(\"sewer_graph_file\", m_sewer_graph_file))\r\n      m_sewer_graph_file = \"/home/siar/siar_ws/src/siar_packages/localization_siar/sewer_graph/test/sewer_graph_1\";\r\n\r\n    if (!lnh.getParam(\"min_manhole_detected\", m_min_manhole_detected))\r\n      m_min_manhole_detected = 10;\r\n    if (!lnh.getParam(\"edgeDev\", m_edgeDev))\r\n      m_edgeDev = 1.0;\r\n\r\n    edgeConst1 = 1./(m_edgeDev*sqrt(2*M_PI));\r\n    edgeConst2 = 1./(2*m_edgeDev*m_edgeDev);\r\n\r\n    if (!lnh.getParam(\"forkDev\", m_forkDev))\r\n      m_forkDev = 3.0;\r\n    if (!lnh.getParam(\"fork_dist\", m_fork_dist))\r\n      m_fork_dist = 3.0;\r\n\r\n    forkConst1 = 1./(m_forkDev*sqrt(2*M_PI));\r\n    forkConst2 = 1./(2*m_forkDev*m_forkDev);\r\n\r\n    if (!lnh.getParam(\"manholeDev\", m_manholeDev))\r\n      m_manholeDev = 0.6;\r\n    if (!lnh.getParam(\"manholeThres\", m_manholeThres))\r\n      m_manholeThres = 0.15;\r\n\r\n    manholeConst1 = 1./(m_manholeDev*sqrt(2*M_PI));\r\n    manholeConst2 = 1./(2*m_manholeDev*m_manholeDev);\r\n\r\n    if (!lnh.getParam(\"angleDev\", m_angleDev))\r\n      m_angleDev = 0.03;\r\n    angleConst1 = 1./(m_angleDev*sqrt(2*M_PI));\r\n    angleConst2 = 1./(2*m_angleDev*m_angleDev);\r\n\r\n    // Save trajectory\r\n    traj_file_open = false;\r\n    if (!lnh.getParam(\"traj_file\", traj_filename))\r\n      traj_filename = \"~/traj_.txt\";\r\n    try {\r\n      traj_file.open(traj_filename.c_str());\r\n      traj_file_open = true;\r\n    }catch (std::exception &e) {\r\n      std::cerr << \"Could not open the traj file: \" << traj_filename << std::endl;\r\n    }\r\n\r\n    // Init the particle filter internal stuff\r\n    m_nUpdates = 0;\r\n    m_init = false;\r\n    m_doUpdate = false;\r\n    m_p.resize(m_maxParticles);\r\n    // Launch updater timer\r\n    updateTimer = m_nh.createTimer(ros::Duration(1.0/m_updateRate), &ParticleFilter::checkUpdateThresholdsTimer, this);\r\n\r\n    // Initialize TF from odom to map as identity\r\n    m_lastGlobalTf.setIdentity();\r\n\r\n    // Initialize sewer graph\r\n    s_g = new sewer_graph::SewerGraph(m_sewer_graph_file);\r\n\r\n    // PUblish gps reference position\r\n    ROS_INFO(\"Publishing gps position: %f, %f\", s_g->getReferencePosition().latitude, s_g->getReferencePosition().longitude);\r\n    m_gpsPub.publish(s_g->getReferencePosition());\r\n\r\n    // Initialize filter if requested\r\n    bool initialize = false;\r\n    if (!lnh.getParam(\"initialize\", initialize)) {\r\n      initialize = false;\r\n    }\r\n    if (initialize)\r\n    {\r\n      tf::Pose pose;\r\n      tf::Vector3 v(m_initX, m_initY, 0.0);\r\n      pose.setOrigin(v);\r\n      pose.setRotation(tf::createQuaternionFromYaw(m_initA));\r\n      ROS_INFO(\"Setting pose: %.3f %.3f %.3f\", pose.getOrigin().x(), pose.getOrigin().y(), getYawFromTf(pose));\r\n      setInitialPose(pose, m_initXDev, m_initYDev, m_initADev);\r\n    }\r\n    last_yaw = 1e100;\r\n    // Launch subscribers\r\n    m_detect_manhole_Sub = m_nh.subscribe(m_detectManholeTopic, 1, &ParticleFilter::manholeDetectedCallback, this);\r\n    m_initialPoseSub = m_nh.subscribe(node_name+\"/initial_pose\", 2, &ParticleFilter::initialPoseReceived, this);\r\n    m_wall_info_sub = m_nh.subscribe(\"/wall_info\", 1, &ParticleFilter::wallInfoCallback, this);\r\n    m_ground_sub = m_nh.subscribe(\"/ground_truth\", 2, &ParticleFilter::groundCallback, this);\r\n\r\n    // Launch publishers\r\n    m_posesPub = m_nh.advertise<geometry_msgs::PoseArray>(node_name+\"/particle_cloud\", 1, true);\r\n    m_posecovPub = m_nh.advertise<geometry_msgs::PoseWithCovarianceStamped>(node_name+\"/estimated_pose\", 1, true);\r\n    m_graphPub = m_nh.advertise<visualization_msgs::Marker>(node_name+\"/sewer_graph\", 0, true);\r\n    m_gpsPub = m_nh.advertise<sensor_msgs::NavSatFix>(\"/gps/fix\", 2, true);\r\n  }\r\n\r\n\r\n\r\n  //!Default destructor\r\n  virtual ~ParticleFilter()\r\n  {\r\n    gsl_rng_free(m_randomValue);\r\n    delete s_g;\r\n  }\r\n\r\n  //! Check motion and time thresholds for AMCL update\r\n  virtual bool checkUpdateThresholds()\r\n  {\r\n    // Publish current TF from odom to map\r\n    m_tfBr.sendTransform(tf::StampedTransform(m_lastGlobalTf, ros::Time::now(), m_globalFrameId, m_odomFrameId));\r\n\r\n    // If the filter is not initialized then exit\r\n    if(!m_init)\r\n      return false;\r\n\r\n    // Compute odometric trasnlation and rotation since last update\r\n    tf::StampedTransform odomTf;\r\n    try\r\n    {\r\n      m_tfListener.waitForTransform(m_odomFrameId, m_baseFrameId, ros::Time(0), ros::Duration(1.0));\r\n      m_tfListener.lookupTransform(m_odomFrameId, m_baseFrameId, ros::Time(0), odomTf);\r\n    }\r\n    catch (tf::TransformException ex)\r\n    {\r\n      ROS_ERROR(\"AMCL error: %s\",ex.what());\r\n      return false;\r\n    }\r\n    tf::Transform T = m_lastOdomTf.inverse()*odomTf;\r\n\r\n    // Check translation threshold\r\n    if(T.getOrigin().length() > m_dTh)\r\n    {\r\n      ROS_INFO(\"Translation update\");\r\n      m_doUpdate = true;\r\n    }\r\n\r\n    // Check yaw threshold\r\n    double yaw, pitch, roll;\r\n    T.getBasis().getRPY(roll, pitch, yaw);\r\n    if(fabs(yaw) > m_dTh)\r\n    {\r\n      ROS_INFO(\"Rotation update\");\r\n      m_doUpdate = true;\r\n    }\r\n\r\n    if (m_doUpdate) {\r\n      update(checkManhole());\r\n    }\r\n\r\n    return false;\r\n  }\r\n\r\n  visualization_msgs::Marker getPosMarker(const std::string &ref_frame, int id = 3, double scale = 3.0) {\r\n    float mX, mY, mA, devX, devY, devA;\r\n    computeDev(mX, mY, mA, devX, devY, devA);\r\n    visualization_msgs::Marker pos;\r\n    pos.header.frame_id = ref_frame;\r\n    pos.header.stamp = ros::Time::now();\r\n    pos.ns = \"sewer_graph\";\r\n    pos.action = visualization_msgs::Marker::ADD;\r\n    pos.pose.orientation.w = 1.0;\r\n    pos.id = id;\r\n    pos.type = visualization_msgs::Marker::SPHERE_LIST;\r\n    pos.color.b = 1.0;\r\n    pos.color.a = 1.0;\r\n    pos.scale.x = scale;\r\n    pos.scale.y = scale;\r\n    pos.scale.z = scale;\r\n\r\n    geometry_msgs::Point p;\r\n    p.x = mX;\r\n    p.y = mY;\r\n    p.z = 0.0;\r\n\r\n\r\n    pos.points.push_back(p);\r\n    return pos;\r\n  }\r\n\r\n  void publishParticles()\r\n  {\r\n    static int seq = 0;\r\n\r\n    // If the filter is not initialized then exit\r\n    if(!m_init)\r\n      return;\r\n\r\n    // Build the msg based on the particles position and orinetation\r\n    geometry_msgs::PoseArray particlesMsg;\r\n    particlesMsg.header.stamp = ros::Time::now();\r\n    particlesMsg.header.frame_id = m_globalFrameId;\r\n    particlesMsg.header.seq = seq++;\r\n    particlesMsg.poses.resize(m_p.size());\r\n    for(int i=0; i<m_p.size(); i++)\r\n    {\r\n      particlesMsg.poses[i].position.x = m_p[i].x;\r\n      particlesMsg.poses[i].position.y = m_p[i].y;\r\n      particlesMsg.poses[i].position.z = 0.0;\r\n      particlesMsg.poses[i].orientation.x = 0.0;\r\n      particlesMsg.poses[i].orientation.y = 0.0;\r\n      particlesMsg.poses[i].orientation.z = sin(m_p[i].a*0.5);\r\n      particlesMsg.poses[i].orientation.w = cos(m_p[i].a*0.5);\r\n    }\r\n\r\n    // Publisg particle cloud\r\n    m_posesPub.publish(particlesMsg);\r\n  }\r\n\r\nprotected:\r\n\r\n  inline bool isFork() {\r\n    float x, y, z, xDev, yDev, aDev;\r\n    computeDev(x, y, z, xDev, yDev, aDev);\r\n    return isFork(x,y);\r\n  }\r\n\r\n  inline bool isFork(double x, double y) {\r\n    return (s_g->getDistanceToClosestVertex(x, y, sewer_graph::FORK) < m_fork_dist);\r\n  }\r\n\r\n  void checkUpdateThresholdsTimer(const ros::TimerEvent& event)\r\n  {\r\n    checkUpdateThresholds();\r\n\r\n    // Publish markers\r\n    std::vector<visualization_msgs::Marker> markers = s_g->getMarkers(m_globalFrameId);\r\n    for (unsigned int i = 0; i < markers.size();i++) {\r\n      m_graphPub.publish(markers[i]);\r\n\r\n    }\r\n    m_graphPub.publish(getPosMarker(m_globalFrameId));\r\n  }\r\n\r\n  void initialPoseReceived(const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg)\r\n  {\r\n    // We only accept initial pose estimates in the global frame\r\n    if(msg->header.frame_id != m_globalFrameId)\r\n    {\r\n      ROS_WARN(\"Ignoring initial pose in frame \\\"%s\\\"; initial poses must be in the global frame, \\\"%s\\\"\",\r\n      msg->header.frame_id.c_str(),\r\n      m_globalFrameId.c_str());\r\n      return;\r\n    }\r\n\r\n    // Transform into the global frame\r\n    tf::Pose pose;\r\n    tf::poseMsgToTF(msg->pose.pose, pose);\r\n    double x = pose.getOrigin().x();\r\n    double y = pose.getOrigin().y();\r\n    int i,j;\r\n\r\n    // Logging the pose change\r\n    ROS_INFO(\"Setting pose: %.3f %.3f %.3f\", pose.getOrigin().x(), pose.getOrigin().y(), getYawFromTf(pose));\r\n    ROS_INFO(\"Distance to closest Edge = %f\", s_g->getDistanceToClosestEdge(x , y, i, j));\r\n    ROS_INFO(\"Vertices of the closest Edge = %d, %d\", i,j);\r\n    ROS_INFO(\"Distance to closest Manhole = %f\", s_g->getDistanceToClosestManhole(x, y));\r\n\r\n    // Initialize the filter\r\n    setInitialPose(pose, m_initXDev, m_initYDev, m_initADev);\r\n  }\r\n\r\n  //! 3D point-cloud callback\r\n  void manholeDetectedCallback(const std_msgs::BoolConstPtr& msg)\r\n  {\r\n    manhole_hist.push_back(msg->data);\r\n  }\r\n\r\n  void wallInfoCallback(const wall_detector::WallInfoConstPtr &msg) {\r\n    // last_info = *msg;\r\n    if (fabs(msg->angle) < 0.06) {\r\n      last_yaw = 0.9*msg->angle;\r\n      last_relative_time = ros::Time::now();\r\n      float x,y,a,xv,yv,av,xycov;\r\n      computeVar(x,y,a,xv,yv,av,xycov);\r\n      double detection_x = 1.5;\r\n      double man_angle_1 = s_g->getClosestEdgeAngle( x + detection_x*cos(a), y + detection_x * sin(a));\r\n      double rel_angle = a - man_angle_1;\r\n\r\n      while (fabs(rel_angle) > M_PI / 2) {\r\n        rel_angle -=  (std::signbit(rel_angle))? -M_PI :M_PI;\r\n      }\r\n      // ROS_INFO(\"Catched angle measurement. Angle = %f. Relative angle = %f\", last_yaw, rel_angle);\r\n    }\r\n\r\n\r\n  }\r\n\r\n  void groundCallback(const manhole_detector::ManholeConstPtr &msg) {\r\n     ground = *msg;\r\n     ROS_INFO(\"Ground truth received. Performing update.\");\r\n     updateParticles(GROUND_TRUTH);\r\n      // Re-compute global TF according to new weight of samples\r\n    computeGlobalTfAndPose();\r\n\r\n    //Do the resampling\r\n    m_nUpdates = 0;\r\n    resample();\r\n    publishParticles();\r\n    m_posecovPub.publish(m_lastPoseCov);\r\n  }\r\n\r\n  void update(bool detected_manhole) {\r\n    if(!predictParticles())\r\n    {\r\n      ROS_ERROR(\"ParticleFilterSewer::manholeDetectedCallback --> Prediction error!\");\r\n      return;\r\n    }\r\n\r\n    float x,y,a,xv,yv,av,xycov;\r\n    computeVar(x,y,a,xv,yv,av,xycov);\r\n\r\n    if (traj_file_open) {\r\n      traj_file << x << \"\\t\" << y << \"\\t\" << a <<\"\\t\"<< ros::Time::now().sec << \".\" << ros::Time::now().nsec<<  std::endl;\r\n    }\r\n\r\n    // Perform different particle update based on current point-cloud and available measurements\r\n    if (detected_manhole) {\r\n      ROS_INFO(\"Performing Update with Manhole\");\r\n      updateParticles(MANHOLE);\r\n    } else if (isFork(x,y)) {\r\n      ROS_INFO(\"Performing update with fork\");\r\n      updateParticles(FORK);\r\n    } else if (last_relative_time - ros::Time::now() < ros::Duration(0,100000000L) && fabs(last_yaw) < 5) {\r\n\r\n      if (gsl_rng_uniform(m_randomValue) < m_angularRate) {\r\n        ROS_INFO(\"Performing angular update. \");\r\n        updateParticles(ANGULAR);\r\n\r\n      } else {\r\n        ROS_INFO(\"Performing regular update, but detected yaw.\");\r\n        updateParticles(REGULAR);\r\n      }\r\n    } else {\r\n      ROS_INFO(\"Performing regular update\");\r\n      updateParticles(REGULAR);\r\n    }\r\n\r\n    // Re-compute global TF according to new weight of samples\r\n    computeGlobalTfAndPose();\r\n\r\n    //Do the resampling if needed\r\n    m_nUpdates++;\r\n    if(m_nUpdates > m_resampleInterval)\r\n    {\r\n      m_nUpdates = 0;\r\n      resample();\r\n    }\r\n\r\n    /*wt = 0; NOTE: this was the implementation of importance resampling\r\n    for(int i=0; i<(int)m_p.size(); i++)\r\n      wt += m_p[i].w*m_p[i].w;\r\n    float nEff = 1/wt;\r\n    if(nEff < ((float)m_p.size())/10.0)\r\n      resample();*/\r\n    //resample();\r\n\r\n    m_doUpdate = false;\r\n\r\n    // Publish particles\r\n    publishParticles();\r\n    m_posecovPub.publish(m_lastPoseCov);\r\n  }\r\n\r\n  //!This function implements the PF prediction stage. Translation in X, Y and Z\r\n  //!in meters and yaw angle incremenet in rad\r\n  //! TODO: In a first stage the predict stage will remain equal to the amcl_3d but without the z\r\n  virtual bool predictParticles()\r\n  {\r\n    // Compute odometric trasnlation and rotation since last update\r\n    tf::StampedTransform odomTf;\r\n    try\r\n    {\r\n      m_tfListener.waitForTransform(m_odomFrameId, m_baseFrameId, ros::Time(0), ros::Duration(0.1));\r\n      m_tfListener.lookupTransform(m_odomFrameId, m_baseFrameId, ros::Time(0), odomTf);\r\n    }\r\n    catch (tf::TransformException ex)\r\n    {\r\n      ROS_ERROR(\"%s\",ex.what());\r\n      return false;\r\n    }\r\n\r\n    // Extract current robot roll and pitch\r\n    double yaw, r, p;\r\n    odomTf.getBasis().getRPY(r, p, yaw);\r\n\r\n    // Perform particle prediction based on odometry\r\n    float delta_x, delta_y;\r\n    double delta_r, delta_p, delta_a;\r\n    tf::Transform T = m_lastOdomTf.inverse()*odomTf;\r\n    delta_x = T.getOrigin().getX();\r\n    delta_y = T.getOrigin().getY();\r\n    T.getBasis().getRPY(delta_r, delta_p, delta_a);\r\n\r\n    float xDev, yDev, aDev;\r\n    xDev = fabs(delta_x*m_odomXMod);\r\n    yDev = fabs(delta_y*m_odomYMod);\r\n    aDev = fabs(delta_a*m_odomAMod) + fabs(m_odomANoise);\r\n\r\n    //Make a prediction for all particles according to the odometry\r\n    for(int i=0; i<(int)m_p.size(); i++)\r\n    {\r\n      float sa = sin(m_p[i].a);\r\n      float ca = cos(m_p[i].a);\r\n      float randX = delta_x + gsl_ran_gaussian(m_randomValue, xDev);\r\n      float randY = delta_y + gsl_ran_gaussian(m_randomValue, yDev);\r\n      m_p[i].x += ca*randX - sa*randY;\r\n      m_p[i].y += sa*randX + ca*randY;\r\n      m_p[i].a += delta_a + gsl_ran_gaussian(m_randomValue, aDev);\r\n    }\r\n\r\n    m_lastOdomTf = odomTf;\r\n\r\n    return true;\r\n  }\r\n\r\n\r\n\r\n  // Update Particles taking into account\r\n  // No input is necessary --> we will get the closest Manhole, which will be used for weighting purposes(with some dispersion)\r\n  void updateParticles(const UpdateType mode)\r\n  {\r\n    double wt = 0.0;\r\n\r\n    for(int i=0; i<(int)m_p.size(); i++)\r\n    {\r\n      double tx = m_p[i].x;\r\n      double ty = m_p[i].y;\r\n      double ta = m_p[i].a;\r\n      // Evaluate the weight of the range sensors\r\n\r\n      switch (mode) {\r\n        case MANHOLE:\r\n          m_p[i].w = computeManholeWeight(tx, ty);\r\n          break;\r\n        case FORK:\r\n          m_p[i].w = computeForkWeight(tx, ty);\r\n          break;\r\n        case ANGULAR:\r\n          m_p[i].w = computeAngularWeight(tx, ty, ta);\r\n          break;\r\n        case YAW:\r\n          m_p[i].w = computeEdgeWeight(tx, ty);\r\n          m_p[i].w += angular_weight * computeAngularWeight(tx, ty, ta);\r\n          break;\r\n        case GROUND_TRUTH:\r\n          m_p[i].w = computeGroundTruthWeight(tx, ty, ground.local_pose.x, ground.local_pose.y);\r\n          break;\r\n        default:\r\n          m_p[i].w = computeEdgeWeight(tx, ty); // Compute weight as a function of the distance to the closest edge\r\n      }\r\n\r\n      //Increase the summatory of weights\r\n      wt += m_p[i].w;\r\n    }\r\n\r\n    //Normalize all weights\r\n    wt = 1.0 / wt;\r\n    for(int i=0; i<(int)m_p.size(); i++)\r\n    {\r\n      m_p[i].w *= wt;\r\n    }\r\n  }\r\n\r\n  double computeEdgeWeight(double x, double y) {\r\n    int i,j;\r\n    double dist = s_g->getDistanceToClosestEdge(x,y,i, j);\r\n\r\n    return edgeConst1*exp(-dist*dist*edgeConst2);\r\n  }\r\n\r\n  double computeForkWeight(double x, double y) {\r\n    int i,j;\r\n    double dist = s_g->getDistanceToClosestEdge(x,y,i,j);\r\n    return forkConst1*exp(-dist*dist*forkConst2);\r\n\r\n  }\r\n\r\n  double computeManholeWeight(double x, double y) {\r\n    double dist = s_g->getDistanceToClosestManhole(x, y);\r\n    return manholeConst1*exp(-dist*dist*manholeConst2) + m_manholeThres;\r\n  }\r\n\r\n  double computeGroundTruthWeight(double x, double y, double g_x, double g_y) {\r\n    double dist2 = (x-g_x)*(x-g_x) + (y-g_y)*(y-g_y);\r\n    return manholeConst1*exp(-dist2*manholeConst2) + m_manholeThres;\r\n  }\r\n\r\n  double computeAngularWeight(double tx, double ty, double ta) {\r\n    double ret = 0.0;\r\n    double detection_x = 1.5;\r\n    double man_angle_1 = s_g->getClosestEdgeAngle( tx + detection_x*cos(ta), ty + detection_x * sin(ta));\r\n    double rel_angle = ta - man_angle_1;\r\n\r\n    while (fabs(rel_angle) > M_PI / 2) {\r\n      rel_angle -=  (std::signbit(rel_angle))? -M_PI :M_PI;\r\n    }\r\n    while (fabs(last_yaw) > M_PI / 2) {\r\n      last_yaw -=  (std::signbit(last_yaw))? -M_PI :M_PI;\r\n    }\r\n\r\n    // ROS_INFO(\"ComputeAngularWeight: Estimated rel angle = %f\\t Rel angle from particle = %f\", last_yaw, rel_angle);\r\n    double angular_error = rel_angle - last_yaw; // The angles should be opposite (their sum should be zero)\r\n\r\n    ret = angleConst1*exp(-angular_error*angular_error*angleConst2);\r\n\r\n    return ret;\r\n  }\r\n\r\n  //! Set the initial pose of the particle filter\r\n  void setInitialPose(tf::Pose initPose, float xDev, float yDev, float aDev)\r\n  {\r\n    // Resize particle set\r\n    m_p.resize(m_maxParticles);\r\n\r\n    // Sample the given pose\r\n    tf::Vector3 t = initPose.getOrigin();\r\n    float a = getYawFromTf(initPose);\r\n    float dev = std::max(xDev, yDev);\r\n    float gaussConst1 = 1./(dev*sqrt(2*M_PI));\r\n    float gaussConst2 = 1./(2*dev*dev);\r\n    float dist = 0.0, wt = 0.0;\r\n    m_p[0].x = t.x();\r\n    m_p[0].y = t.y();\r\n    m_p[0].a = a;\r\n    m_p[0].w = gaussConst1;\r\n    wt = m_p[0].w;\r\n    for(int i=1; i<(int)m_p.size(); i++)\r\n    {\r\n      m_p[i].x = t.x() + gsl_ran_gaussian(m_randomValue, xDev);\r\n      m_p[i].y = t.y() + gsl_ran_gaussian(m_randomValue, yDev);\r\n      m_p[i].a = a + gsl_ran_gaussian(m_randomValue, aDev);\r\n      dist = sqrt((m_p[i].x - t.x())*(m_p[i].x - t.x()) + (m_p[i].y - t.y())*(m_p[i].y - t.y()) );\r\n      m_p[i].w = gaussConst1*exp(-dist*dist*gaussConst2);\r\n      wt += m_p[i].w;\r\n    }\r\n    for(int i=0; i<(int)m_p.size(); i++)\r\n      m_p[i].w /= wt;\r\n\r\n    // Extract TFs for future updates\r\n    bool initialized = false;\r\n    while (!initialized) {\r\n      try\r\n      {\r\n        m_tfListener.waitForTransform(m_odomFrameId, m_baseFrameId, ros::Time(0), ros::Duration(15.0));\r\n        m_tfListener.lookupTransform(m_odomFrameId, m_baseFrameId, ros::Time(0), m_lastOdomTf);\r\n        initialized = true;\r\n      }\r\n      catch (tf::TransformException ex)\r\n      {\r\n        ROS_ERROR(\"%s\",ex.what());\r\n      }\r\n      sleep(2);\r\n    }\r\n    computeGlobalTfAndPose();\r\n    m_doUpdate = false;\r\n    m_init = true;\r\n\r\n    // Publish particles\r\n    publishParticles();\r\n  }\r\n\r\n  //! Return yaw from a given TF\r\n  float getYawFromTf(tf::Pose& pose)\r\n  {\r\n    double yaw, pitch, roll;\r\n\r\n    pose.getBasis().getRPY(roll, pitch, yaw);\r\n\r\n    return (float)yaw;\r\n  }\r\n\r\n  //! resample the set of particules using low-variance sampling\r\n  int resample()\r\n  {\r\n    int i, m;\r\n    float r, u, c, factor;\r\n    std::vector<Particle> newP;\r\n\r\n    //Initialize data and vectors\r\n    newP.resize(m_p.size());\r\n    factor = 1.0/((float)m_p.size());\r\n    i = 0;\r\n    c = m_p[0].w;\r\n    r = factor * gsl_rng_uniform(m_randomValue);\r\n\r\n    //Do resamplig\r\n    for(m=0; m<m_p.size(); m++)\r\n    {\r\n      u = std::fma(factor,m, r);\r\n      while(u > c)\r\n      {\r\n        i++;\r\n        c += m_p[i].w;\r\n      }\r\n      newP[m] = m_p[i];\r\n      newP[m].w = factor;\r\n    }\r\n\r\n    //Asign the new particles set\r\n    m_p = newP;\r\n\r\n    return 0;\r\n  }\r\n\r\n  // Computes TF from odom to global frames\r\n  void computeGlobalTfAndPose()\r\n  {\r\n    // Compute mean value from particles\r\n    float mx, my, ma, xv, yv, av, xycov;\r\n    computeVar(mx, my, ma, xv, yv, av, xycov);\r\n    Particle p;\r\n    p.x = mx;\r\n    p.y = my;\r\n    p.a = ma;\r\n    p.w = 0.0;\r\n\r\n    // Compute the TF from odom to global\r\n    std::cout << \"New TF:\\n\\t\" << p.x << \", \" << p.y << std::endl;\r\n    m_lastGlobalTf = tf::Transform(tf::Quaternion(0.0, 0.0, sin(p.a*0.5), cos(p.a*0.5)), tf::Vector3(p.x, p.y, 0.0))*m_lastOdomTf.inverse();\r\n    m_lastPoseCov.header.stamp = ros::Time::now();\r\n    m_lastPoseCov.header.seq++;\r\n    geometry_msgs::Quaternion &orientation = m_lastPoseCov.pose.pose.orientation;\r\n    orientation.w = m_lastGlobalTf.getRotation().getW();\r\n    orientation.x = m_lastGlobalTf.getRotation().getX();\r\n    orientation.y = m_lastGlobalTf.getRotation().getY();\r\n    orientation.z = m_lastGlobalTf.getRotation().getZ();\r\n    geometry_msgs::Point &position = m_lastPoseCov.pose.pose.position;\r\n    position.x = mx; position.y = my; position.z = 0.0;\r\n    boost::array<double, 36> &Cov = m_lastPoseCov.pose.covariance;\r\n    Cov[0] = xv; Cov[7] = yv; Cov[35] = av;\r\n    Cov[1] = Cov[6] = xycov;\r\n  }\r\n\r\n  void computeVar(float &mX, float &mY, float &mA, float &var_x, float &var_y, float &var_a, float &cov_x_y) {\r\n    // Compute mean value from particles\r\n    var_x = mX = 0.0;\r\n    var_y = mY = 0.0;\r\n    var_a = mA = 0.0;\r\n    cov_x_y = 0.0;\r\n    for(int i=0; i<m_p.size(); i++)\r\n    {\r\n      mX += m_p[i].w * m_p[i].x;\r\n      mY += m_p[i].w * m_p[i].y;\r\n      mA += m_p[i].w * m_p[i].a;\r\n    }\r\n    for(int i=0; i<m_p.size(); i++)\r\n    {\r\n      var_x += m_p[i].w * (m_p[i].x-mX) * (m_p[i].x-mX);\r\n      var_y += m_p[i].w * (m_p[i].y-mY) * (m_p[i].y-mY);\r\n      var_a += m_p[i].w * (m_p[i].a-mA) * (m_p[i].a-mA);\r\n      cov_x_y += m_p[i].w * (m_p[i].x-mX) * (m_p[i].y-mY);\r\n\r\n    }\r\n  }\r\n\r\n  void computeDev(float &mX, float &mY, float &mA, float &devX, float &devY, float &devA)\r\n  {\r\n    // Compute mean value from particles\r\n    devX = mX = 0.0;\r\n    devY = mY = 0.0;\r\n    devA = mA = 0.0;\r\n    for(int i=0; i<m_p.size(); i++)\r\n    {\r\n      mX += m_p[i].w * m_p[i].x;\r\n      mY += m_p[i].w * m_p[i].y;\r\n      mA += m_p[i].w * m_p[i].a;\r\n    }\r\n    for(int i=0; i<m_p.size(); i++)\r\n    {\r\n      devX += m_p[i].w * (m_p[i].x-mX) * (m_p[i].x-mX);\r\n      devY += m_p[i].w * (m_p[i].y-mY) * (m_p[i].y-mY);\r\n      devA += m_p[i].w * (m_p[i].a-mA) * (m_p[i].a-mA);\r\n    }\r\n    devX = sqrt(devX);\r\n    devY = sqrt(devY);\r\n    devA = sqrt(devA);\r\n  }\r\n\r\n  bool checkManhole() {\r\n    int n_trues = 0;\r\n\r\n    for (unsigned int i = 0;i < manhole_hist.size(); i++) {\r\n\r\n      if (manhole_hist[i])\r\n        n_trues++;\r\n    }\r\n\r\n\r\n    ROS_INFO(\"Number of detections %d. Number of positive: %d\", (int)manhole_hist.size(), n_trues);\r\n\r\n    manhole_hist.clear();\r\n\r\n    return n_trues >= m_min_manhole_detected;\r\n  }\r\n\r\n  //! Indicates if the filter was initialized\r\n  bool m_init;\r\n\r\n  //! Particles\r\n  std::vector<Particle> m_p;\r\n\r\n  //! Particles roll and pich (given by IMU)\r\n  double m_roll, m_pitch;\r\n\r\n  //! Number of particles in the filter\r\n  int m_maxParticles;\r\n  int m_minParticles;\r\n\r\n  //! Odometry characterization\r\n  double m_odomXMod, m_odomYMod, m_odomZMod, m_odomAMod, m_odomANoise;\r\n  double m_initX, m_initY, m_initA;\r\n  double m_initXDev, m_initYDev, m_initADev;\r\n\r\n  //! Resampling control\r\n  int m_nUpdates;\r\n  int m_resampleInterval;\r\n\r\n  //! Yaw estimation\r\n  double last_yaw;\r\n  ros::Time last_relative_time;\r\n  double angular_weight;\r\n\r\n  //! Thresholds for filter updating\r\n  double m_dTh, m_aTh, m_tTh;\r\n  tf::StampedTransform m_lastOdomTf;\r\n  tf::Transform m_lastGlobalTf;\r\n  geometry_msgs::PoseWithCovarianceStamped m_lastPoseCov;\r\n  bool m_doUpdate;\r\n  double m_updateRate;\r\n  double m_angularRate;\r\n\r\n  //! Node parameters\r\n  std::string m_detectManholeTopic;\r\n  std::string m_baseFrameId;\r\n  std::string m_odomFrameId;\r\n  std::string m_globalFrameId;\r\n  std::string m_inOdomTfTopic;\r\n\r\n  //! ROS msgs and data\r\n  ros::NodeHandle m_nh, lnh;\r\n  tf::TransformBroadcaster m_tfBr;\r\n  tf::TransformListener m_tfListener;\r\n  ros::Subscriber m_detect_manhole_Sub, m_initialPoseSub, m_odomTfSub, m_wall_info_sub, m_ground_sub;\r\n  ros::Publisher m_posesPub, m_graphPub, m_gpsPub, m_posecovPub;\r\n  ros::Timer updateTimer;\r\n\r\n  // Sewer stuff\r\n  std::string m_sewer_graph_file;\r\n  sewer_graph::SewerGraph *s_g;\r\n\r\n  //! Random number generator\r\n  const gsl_rng_type *m_randomType;\r\n  gsl_rng *m_randomValue;\r\n\r\n  boost::variate_generator<boost::mt19937, boost::normal_distribution<> > m_randVar;\r\n\r\n  std::vector<bool> manhole_hist;\r\n  int m_min_manhole_detected;\r\n  double m_edgeDev, m_manholeDev, m_manholeThres, m_angleDev;\r\n  double edgeConst1, edgeConst2;\r\n  double manholeConst1, manholeConst2;\r\n  double angleConst1, angleConst2;\r\n  double m_forkDev, forkConst1, forkConst2, m_fork_dist;\r\n\r\n  manhole_detector::Manhole ground; // Store the ground truth data\r\n\r\n  //For saving trajetory\r\n  std::ofstream traj_file;\r\n  std::string traj_filename;\r\n  bool traj_file_open;\r\n};\r\n\r\n#endif\r\n", "meta": {"hexsha": "8e406a7f7b5bac413c561264fab2aec4c017753e", "size": 27854, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "amcl_sewer/src/particlefilter_sewer.hpp", "max_stars_repo_name": "robotics-upo/localization_siar", "max_stars_repo_head_hexsha": "6b4ca6f2bb56f7071479839dcbb88a6384eca091", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-15T16:00:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T12:38:42.000Z", "max_issues_repo_path": "amcl_sewer/src/particlefilter_sewer.hpp", "max_issues_repo_name": "robotics-upo/localization_siar", "max_issues_repo_head_hexsha": "6b4ca6f2bb56f7071479839dcbb88a6384eca091", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amcl_sewer/src/particlefilter_sewer.hpp", "max_forks_repo_name": "robotics-upo/localization_siar", "max_forks_repo_head_hexsha": "6b4ca6f2bb56f7071479839dcbb88a6384eca091", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T03:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T06:54:42.000Z", "avg_line_length": 31.4734463277, "max_line_length": 141, "alphanum_fraction": 0.6255115962, "num_tokens": 8124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.043365796136651424, "lm_q1q2_score": 0.02049829528428533}}
{"text": "//  Copyright (c) 2006, Giovanni P. Deretta\n//\n//  This code may be used under either of the following two licences:\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 \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 FROM, \n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN \n//  THE SOFTWARE. OF SUCH DAMAGE.\n//\n//  Or:\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#include <iostream>\n#include <boost/variant.hpp>\n#include <boost/variant/get.hpp>\n#include <boost/variant/recursive_variant.hpp>\n#include <boost/variant/recursive_wrapper.hpp>\n#include <boost/optional.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include <boost/mpl/deref.hpp>\n#include <boost/coroutine/coroutine.hpp>\n\n/**\n * Solve the 'same fringe problem' using coroutines.\n * Given two binary trees, they have the same fringe\n * if all leafs, read from left to right are equals.\n * This is the classical coroutine demonstration problem,\n * because it is hard to solve in O(N) (with best case O(1)) \n * without using coroutines.\n * see http://c2.com/cgi/wiki?CoRoutine\n * NOTE: this solution is an almost verbatim port of the lua solution from\n * the wiki.\n */\nnamespace coroutines = boost::coroutines;\nusing coroutines::coroutine;\n\nnamespace meta {\n  /**\n   * Compact compile-time description of binary trees of ints.\n   */\n  template<typename Left, typename Right>\n  class node{\n    typedef Left left;\n    typedef Right right;\n  };\n  \n  template<int A>\n  struct leaf {\n    enum {value = A};\n  };\n\n  typedef \n  node<node<leaf<0>, leaf<1> >, node<leaf<0>, node<leaf<5>, leaf<7> > > >\n  tree_a; // fringe: 0 1 0 5 7\n\n  typedef \n  node<leaf<0>, node<leaf<1>, node<node<leaf<0>, leaf<5> >, leaf<7> > > >\n  tree_b; // fringe: 0 1 0 5 7\n\n  typedef \n  node<leaf<1>, node<leaf<7>, node<node<leaf<5>, leaf<4> >, leaf<7> > > >\n  tree_c; // fringe: 1 7 5 4 7\n}\n\ntypedef int leaf;\nstruct node;\ntypedef boost::variant<boost::recursive_wrapper<node>,  leaf> tree_element;\n\ntypedef boost::tuple<tree_element, tree_element> node_;\nstruct node : node_ {\n  template<typename A, typename B>\n  node(const A& a, const B& b) :\n    node_(a, b) {}\n};\n\nbool is_leaf(const tree_element& x) {\n  return x.which() == 1;\n}\n\ntemplate<typename Left, typename Right>\ntree_element make_tree(meta::node<Left, Right> const&) {\n  return tree_element(node(make_tree(Left()), \n\t\t\t   make_tree(Right())));\n}\n\ntemplate<int A>\ntree_element make_tree(meta::leaf<A> const&) {\n  return tree_element(A);\n}\n\ntypedef coroutine<boost::optional<leaf>(tree_element)> coroutine_type;\n\nboost::optional<leaf>  tree_leaves(coroutine_type::self& self, tree_element tree) {\n  if (is_leaf(tree)) {\n    self.yield(boost::get<leaf>(tree));\n  } else {\n    tree_leaves(self, boost::get<node>(tree).get<0>());\n    tree_leaves(self, boost::get<node>(tree).get<1>());\n  }\n  return boost::optional<leaf>();\n}\n\nbool same_fringe(tree_element tree1, tree_element tree2) {\n  coroutine_type tree_leaves_a(tree_leaves);\n  coroutine_type tree_leaves_b(tree_leaves);\n  boost::optional<leaf> tmp1, tmp2;\n  while ((tmp1 = tree_leaves_a(tree1)) && (tmp2=tree_leaves_b(tree2))) \n    if (!(tmp1 == tmp2)) return false;\n  return true;\n}\n\nint main() {\n  std::cout<<\"same_fringe tree_a, tree_a \"<<same_fringe\n    (make_tree(meta::tree_a()), make_tree(meta::tree_a()))<<\"\\n\";\n  std::cout<<\"same_fringe tree_a, tree_b \"<<same_fringe\n    (make_tree(meta::tree_a()), make_tree(meta::tree_b()))<<\"\\n\";\n  std::cout<<\"same_fringe tree_a, tree_c \"<<same_fringe\n    (make_tree(meta::tree_a()), make_tree(meta::tree_c()))<<\"\\n\";\n}\n", "meta": {"hexsha": "69dd87f5dc3ad17af69e4c4b0660d49064331873", "size": 4579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/coroutine/example/samefringe.cpp", "max_stars_repo_name": "erikfrey/coroutine", "max_stars_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-10-19T02:52:00.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-09T09:52:25.000Z", "max_issues_repo_path": "libs/coroutine/example/samefringe.cpp", "max_issues_repo_name": "erikfrey/coroutine", "max_issues_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/coroutine/example/samefringe.cpp", "max_forks_repo_name": "erikfrey/coroutine", "max_forks_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "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.4233576642, "max_line_length": 83, "alphanum_fraction": 0.7029919196, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.04336579443666276, "lm_q1q2_score": 0.02049829448072878}}
{"text": "/*=================================================================================\n *\t                    Copyleft! 2018 William Yu\n *          Some rights reserved：CC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      版权部分所有，遵循CC(creativecommons.org)BY-NC-SA协议授权方式使用\n *\n * Filename                : \n * Description             : 视觉SLAM十四讲/ch5 学习记录\n * Reference               : 分切点云\n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET国家重点实验室FOCUS团队\n * Modification History\t   : ver1.0, 2019.01.02, William Yu\n                            \n=================================================================================*/\n\n/// Include Files\n#include <iostream>\n#include <fstream>\nusing namespace std;\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <Eigen/Geometry> \n#include <boost/format.hpp>  // for formating strings\n#include <pcl/point_types.h> \n#include <pcl/io/pcd_io.h> \n#include <pcl/visualization/pcl_visualizer.h>\n\n\n\n/// Function Definitions\n\n/**\n * @function main\n * @author William Yu\n * @brief \n */\nint main( int argc, char** argv )\n{\n    // 相机内参 \n    double cx = 325.5;\n    double cy = 253.5;\n    double fx = 518.0;\n    double fy = 519.0;\n    double depthScale = 1000.0;\n    \n    cout<<\"读入点云...\"<<endl;\n    pcl::PCDReader reader;\n    // 定义点云使用的格式：这里用的是XYZRGB\n    typedef pcl::PointXYZRGB PointT; \n    typedef pcl::PointCloud<PointT> PointCloud;\n    PointCloud::Ptr pointCloud( new PointCloud ); \n    reader.read (\"../output/map.pcd\", *pointCloud);\n    int size_pointCloud = pointCloud->points.size()/10;//只是用前面的一些点，使用全部点会报错，原因不明。应该是内存溢出。\n    std::cout << \"PointCloud before filtering has: \" << size_pointCloud << \" data points.\" << std::endl;\n\n    cv::Mat color(480,640,CV_8UC3,cv::Scalar(0,0,0) );\n    cv::Mat depth(480,640,CV_8UC1,cv::Scalar(255));\n    \n    //--每个世界坐标转换到像素坐标\n    for ( size_t p_i=0; p_i<540920; ++p_i )\n    {   \n        PointT p = pointCloud->points[p_i];//由点云中载入点\n        \n        //内参修正\n        Eigen::Vector3d point; \n        point[0] = p.x;\n        point[1] = p.y;\n        point[2] = p.z;\n        \n        unsigned int d = depthScale * point[2];\n        int u = fx * point[0] / point[2] + cx;\n        int v = fy * point[1] / point[2] + cy; \n        int d_rawdata = depth.ptr<unsigned short> (v)[u];\n        std::cout << p_i << std::endl;\n        // std::cout << \" u:\" << u\n        // << \" v:\" << v\n        // << \" d:\" << d\n        // << std::endl;\n        // std::cout << \" b:\" << (int)p.b\n        // << \" g:\" << (int)p.g\n        // << \" r:\" << (int)p.r\n        // << std::endl;\n\n        //如果新点z轴更高，跳过\n        if ( d_rawdata < d ) continue; //取下侧，仰视图\n        //如果新点更低，更新RGBD\n        depth.ptr<unsigned short> (v)[u] = d; // 深度值，其实深度值根本获取不出来\n        color.data[ v*color.step+u*color.channels() ] = p.b;\n        color.data[ v*color.step+u*color.channels()+1 ] = p.g;\n        color.data[ v*color.step+u*color.channels()+2 ] = p.r;\n\n        //释放资源\n        //delete []PointCloud;\n    }\n    \n    cv::imshow(\"splitimg\",color);\n    \n    char key = (char)cv::waitKey(0); \n    if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'\n        return 0;\n}\n", "meta": {"hexsha": "43acc6a70ad70788c49de014f5400169402c4aa8", "size": 3200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4.拼接点云/splitMap.cpp", "max_stars_repo_name": "HustRobot/VSLAM", "max_stars_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:35:49.000Z", "max_issues_repo_path": "4.拼接点云/splitMap.cpp", "max_issues_repo_name": "HustRobot/VSLAM", "max_issues_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.拼接点云/splitMap.cpp", "max_forks_repo_name": "HustRobot/VSLAM", "max_forks_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T07:27:34.000Z", "avg_line_length": 31.3725490196, "max_line_length": 104, "alphanum_fraction": 0.5121875, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.04401865346851788, "lm_q1q2_score": 0.02046434116725462}}
{"text": "/**\r\n * @file   global.hpp\r\n * @Author Leobardo Campos (leobardo.e.campos.macias@intel.com)\r\n * @date   May 22, 2019\r\n * @brief  \r\n * @section LICENSE\r\n *\r\n *  BSD-3-Clause License\r\n *\r\n * @copyright Copyright (C) 2020 Intel Corporation\r\n *\r\n * Redistribution and use in source and binary forms, with or without modification,\r\n * are permitted provided that the following conditions are met:\r\n * \r\n * 1. Redistributions of source code must retain the above copyright notice,\r\n *    this list of conditions and the following disclaimer.\r\n * 2. Redistributions in binary form must reproduce the above copyright notice,\r\n *    this list of conditions and the following disclaimer in the documentation\r\n *    and/or other materials provided with the distribution.\r\n * 3. Neither the name of the copyright holder nor the names of its contributors\r\n *    may be used to endorse or promote products derived from this software\r\n *    without specific prior written permission.\r\n *  \r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS\r\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\r\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT\r\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\r\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\r\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\r\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n**/ \r\n#ifndef RRT_GLOBAL_HPP_\r\n#define RRT_GLOBAL_HPP_\r\n\r\n#include <Eigen/Core>\r\n#include <vector>\r\n#include <stdint.h>\r\n\r\nnamespace rrt\r\n{\r\n\r\ntypedef enum {kMax=0, kMin, kNIndex}eIndex;\r\ntypedef enum {kFov=0, kMap, kNTypes}eDirection;\r\n\r\nconst double k_rrt_solution_error = 0.1;\r\n\r\n#ifndef finline\r\n  #ifdef WIN32\r\n    #define finline __forceinline\r\n  #else\r\n    #define finline inline __attribute__((always_inline))\r\n  #endif\r\n#endif\r\n\r\nclass \tNode;\r\n\r\ntypedef Eigen::Vector3d \t\t\t\t\t\t\t\tPoint;\r\ntypedef std::vector<Point> \t\t\t\t\t\t\t\tPointList;\r\ntypedef Eigen::MatrixXd \t\t\t\t\t\t\t\tMatrix;\r\ntypedef std::vector<Node>\t\t\t\t\t\t\t\tNodes;\r\n\r\n\r\nstatic Matrix CalculateRotationMatrix(const double &roll, const double &pitch, const double &yaw)\r\n{\r\n\tMatrix Rz(3,3);\r\n\tRz<< \tcos(yaw), -sin(yaw), 0.0,\r\n\t\t\tsin(yaw), cos(yaw), 0.0,\r\n\t\t\t0.0, 0.0, 1.0;\r\n\r\n\tMatrix Rx(3,3);\r\n\tRx<< \t\t1.0, 0.0, 0.0,\r\n\t\t\t0.0, cos(roll), -sin(roll),\r\n\t\t\t0.0, sin(roll), cos(roll);\r\n\r\n\tMatrix Ry(3,3);\r\n\tRy<< \tcos(pitch), 0.0, sin(pitch),\r\n\t\t\t 0.0, 1.0, 0.0,\r\n\t\t\t -sin(pitch), 0.0, cos(pitch);\r\n\treturn Rz*Ry*Rx;\r\n}\r\nstatic Matrix CalculateRotationMatrix(const double &theta)\r\n{\r\n\tMatrix Rz(2,2);\r\n\tRz<< \tcos(theta), -sin(theta),\r\n\t\t\tsin(theta), cos(theta);\r\n\treturn Rz;\r\n}\r\n\r\n} /* namespace rrt */\r\n\r\n#endif /* RRT_GLOBAL_HPP_ */\r\n", "meta": {"hexsha": "ae2460ffeba4c72ace9aff36f84593db80f4f051", "size": 3067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rrt/include/rrt/global.hpp", "max_stars_repo_name": "IntelLabs/autonomousmavs", "max_stars_repo_head_hexsha": "0e5e766102fcfe6fafede99afe2697b7511a7e01", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2020-05-06T00:29:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T03:25:27.000Z", "max_issues_repo_path": "rrt/include/rrt/global.hpp", "max_issues_repo_name": "khlaifiabilel/autonomousmavs", "max_issues_repo_head_hexsha": "0e5e766102fcfe6fafede99afe2697b7511a7e01", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-27T11:38:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T10:13:51.000Z", "max_forks_repo_path": "rrt/include/rrt/global.hpp", "max_forks_repo_name": "khlaifiabilel/autonomousmavs", "max_forks_repo_head_hexsha": "0e5e766102fcfe6fafede99afe2697b7511a7e01", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-20T00:49:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T04:52:48.000Z", "avg_line_length": 31.618556701, "max_line_length": 98, "alphanum_fraction": 0.6912292142, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.044018646727667046, "lm_q1q2_score": 0.020464338033422475}}
{"text": "/*\n * <one line to give the program's name and a brief idea of what it does.>\n * Copyright (C) 2016  <copyright holder> <email>\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, * 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 <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <algorithm>\n#include <boost/timer.hpp>\n\n#include \"myslam/config.h\"\n#include \"myslam/visual_odometry.h\"\n#include \"myslam/g2o_types.h\"\n#include \"myslam/initializer.h\"\n\nnamespace myslam\n{\n\nVisualOdometry::VisualOdometry() :\n    state_ ( INITIALIZING ), InitialFrame_(nullptr), ref_ ( nullptr ), curr_ ( nullptr ), map_ ( new Map ), num_lost_ ( 0 ), num_inliers_ ( 0 ), matcher_flann_ ( new cv::flann::LshIndexParams ( 5,10,2 ) )\n{\n    matcher = cv::DescriptorMatcher::create(cv::DescriptorMatcher::FLANNBASED);\n    num_of_features_    = Config::get<int> ( \"number_of_features\" );\n    scale_factor_       = Config::get<double> ( \"scale_factor\" );\n    level_pyramid_      = Config::get<int> ( \"level_pyramid\" );\n    match_ratio_        = Config::get<float> ( \"match_ratio\" );\n    max_num_lost_       = Config::get<float> ( \"max_num_lost\" );\n    min_inliers_        = Config::get<int> ( \"min_inliers\" );\n    key_frame_min_rot   = Config::get<double> ( \"keyframe_rotation\" );\n    key_frame_min_trans = Config::get<double> ( \"keyframe_translation\" );\n    map_point_erase_ratio_ = Config::get<double> ( \"map_point_erase_ratio\" );\n    orb_ = cv::ORB::create ( num_of_features_, scale_factor_, level_pyramid_ );\n    srand(0);\n}\n\nVisualOdometry::~VisualOdometry()\n{\n\n}\n\nbool VisualOdometry::addFrame (Frame::Ptr frame/*count 2*/ ) //Tracking module\n{\n    switch ( state_ )\n    {\n    case INITIALIZING:\n    {\n        curr_ = frame;// This pointer count 3\n        // extract features from first frame and add them into map\n        extractKeyPoints();\n        if(keypoints_curr_.size() > 100)\n        {\n            computeDescriptors();\n            if(InitialFrame_ == nullptr)\n            {\n                InitialFrame_ = frame; // count 4\n                keypoints_prev_.clear();\n                keypoints_prev_ = std::move(keypoints_curr_);\n                //for(int i=0; i< keypoints_curr_.size();i++)\n                //    keypoints_prev_.push_back(keypoints_curr_[i]);\n                descriptors_prev_ = std::move(descriptors_curr_); // opencv 4.x supports move constructor and =operator for Mat class\n                return false;\n            }\n            else if(curr_ != nullptr && InitialFrame_ != nullptr)\n            {\n                // Feature Matching\n                vector<cv::DMatch> good_matches;\n                cv::Ptr<cv::DescriptorMatcher> matcher =\n                 cv::DescriptorMatcher::create(cv::DescriptorMatcher::FLANNBASED);\n                std::vector<std::vector<cv::DMatch>> knn_matches;\n                matcher->knnMatch(descriptors_prev_,descriptors_curr_, knn_matches, 2);\n\n                const float ratio_thresh = .7f;\n                for( size_t i =0; i<knn_matches.size(); i++)\n                {\n                    if(knn_matches[i][0].distance<ratio_thresh * knn_matches[i][1].distance)\n                    {\n                        good_matches.push_back(knn_matches[i][0]);\n                    }\n                }\n\n                if(good_matches.size() < 10)\n                {\n                    InitialFrame_ = curr_;\n                    return false;\n                }\n\n                //Show Feature result\n                Mat src = InitialFrame_->color_.clone();\n                size_t sz = std::min(keypoints_curr_.size(), keypoints_prev_.size());\n                sz = good_matches.size();\n                cv::RNG rng(0);\n                for(size_t t = 0; t < sz; t++)\n                {\n                    cv::arrowedLine(src, keypoints_prev_[good_matches[t].queryIdx].pt,\n                                  keypoints_curr_[good_matches[t].trainIdx].pt,\n                                  cv::Scalar(rng(256),rng(256),rng(256)), 2);\n                }\n                cv::imshow(\"InitialFrame\", src);\n\n                vector<cv::Point2f> pts1;\n                vector<cv::Point2f> pts2;\n                pts1.reserve(good_matches.size());\n                pts2.reserve(good_matches.size());\n                for(size_t i=0;i < good_matches.size(); i++)\n                {\n                    const float x1 = keypoints_prev_[good_matches[i].queryIdx].pt.x;\n                    const float y1 = keypoints_prev_[good_matches[i].queryIdx].pt.y;\n                    const float x2 = keypoints_curr_[good_matches[i].trainIdx].pt.x;\n                    const float y2 = keypoints_curr_[good_matches[i].trainIdx].pt.y;\n\n                    pts1.emplace_back(x1,y1);\n                    pts2.emplace_back(x2,y2);\n                }\n\n                double lambda;\n                Mat inlierMask;\n                vector<bool> vbMatchesInliersF;\n                float score=0;\n                Mat F;\n                //FindFundamental(vbMatchesInliersF,score,F, pts1,pts2);\n                F = cv::findFundamentalMat(pts1,pts2,inlierMask,cv::RANSAC);\n                F.convertTo(F,CV_32F);\n\n                //Mat lines;\n                drawepipolarlines(\"Epipolar lines\", F, InitialFrame_->color_,curr_->color_,\n                                  pts1,pts2);\n                cv::waitKey(30);\n\n                vector<bool> vbTriangulated;\n                if(FindMotion(F, curr_->camera_->mK,\n                                           pts1, pts2,\n                                           inlierMask, curr_->T_c_w_, // Output pose\n                                           vIniP3D_, vbTriangulated, // Output Point, boolean\n                                           1.0, 50))\n                {\n                    const Eigen::Matrix3d IniRotation = Eigen::Matrix3d::Identity();\n                    const Eigen::Vector3d IniTranslation = Eigen::Vector3d::Zero();\n                    InitialFrame_->T_c_w_ = SE3(IniRotation, IniTranslation);\n                    cout << \"Initial Pose =\" << endl\n                         << \"R =\"<<endl\n                         << InitialFrame_->T_c_w_.rotation_matrix()\n                         << \"\\n t = \"<<std::endl\n                         << InitialFrame_->T_c_w_.translation()\n                         <<endl;\n                    cout << \"Current Pose =\" << endl\n                         << \"R =\"<<endl\n                         << curr_->T_c_w_.rotation_matrix()\n                         << \"\\n t = \"<<std::endl\n                         << curr_->T_c_w_.translation()\n                         <<endl;\n\n                    cv::waitKey(0);\n                    // Current Frame is already Setted.\n                    //CreateInitialMapMonocular();\n                }\n                else\n                {\n                    return false;\n                }\n\n               // ref_ = curr_;\n               // keypoints_prev_.clear();\n               // for(int i=0; i< keypoints_curr_.size();i++)\n               //     keypoints_prev_.push_back(keypoints_curr_[i]);\n               // descriptors_prev_ = descriptors_curr_.clone();\n                return false;\n            }\n\n\n        }\n        addKeyFrame();      // the first frame is a key-frame\n\n        ref_ = curr_;\n        keypoints_prev_.clear();\n        for(int i=0; i< keypoints_curr_.size();i++)\n            keypoints_prev_.push_back(keypoints_curr_[i]);\n        descriptors_prev_ = descriptors_curr_.clone();\n        break;\n    }\n    case OK:\n    {\n        curr_ = frame;\n        curr_->T_c_w_ = ref_->T_c_w_;\n        extractKeyPoints();\n        computeDescriptors();               // Constant Velocity Model Tracker\n        featureMatching();                  // Constant Velocity Model Tracker\n        poseEstimationPnP();                // Triangulation (Essential matrix Decomp)\n        if ( checkEstimatedPose() == true ) // a good estimation\n        {\n            curr_->T_c_w_ = T_c_w_estimated_;\n            optimizeMap();\n            num_lost_ = 0;\n            if ( checkKeyFrame() == true ) // is a key-frame\n            {\n                addKeyFrame();\n            }\n        }\n        else // bad estimation due to various reasons\n        {\n            num_lost_++;\n            if ( num_lost_ > max_num_lost_ )\n            {\n                state_ = LOST;\n            }\n            return false;\n        }\n        break;\n    }\n    case LOST:\n    {\n        cout<<\"vo has lost.\"<<endl;\n        break;\n    }\n    }\n\n    return true;\n}\n\nvoid VisualOdometry::extractKeyPoints()\n{\n    boost::timer timer;\n    orb_->detect ( curr_->color_, keypoints_curr_ );\n    //cout<<\"extract keypoints cost time: \"<<timer.elapsed() <<endl;\n}\n\nvoid VisualOdometry::computeDescriptors()\n{\n    boost::timer timer;\n    orb_->compute ( curr_->color_, keypoints_curr_, descriptors_curr_);\n    descriptors_curr_.convertTo(descriptors_curr_, CV_32F);\n    //cout<<\"descriptor computation cost time: \"<<timer.elapsed() <<endl;\n}\n\nvoid VisualOdometry::featureMatching()\n{\n    boost::timer timer;\n    vector<cv::DMatch> matches;\n    // select the candidates in map\n    Mat desp_map;\n    vector<MapPoint::Ptr> candidate;\n    for ( auto& allpoints: map_->map_points_ )\n    {\n        MapPoint::Ptr& p = allpoints.second;\n        // check if p in curr frame image\n        if ( curr_->isInFrame(p->pos_) )\n        {\n            // add to candidate\n            p->visible_times_++;\n            candidate.push_back( p );\n            desp_map.push_back( p->descriptor_ );\n        }\n    }\n\n    matcher_flann_.match ( desp_map, descriptors_curr_, matches );\n    // select the best matches\n    float min_dis = std::min_element (\n                        matches.begin(), matches.end(),\n                        [] ( const cv::DMatch& m1, const cv::DMatch& m2 )\n    {\n        return m1.distance < m2.distance;\n    } )->distance;\n\n    match_3dpts_.clear();\n    match_2dkp_index_.clear();\n    for ( cv::DMatch& m : matches )\n    {\n        if ( m.distance < max<float> ( min_dis*match_ratio_, 30.0 ) )\n        {\n            match_3dpts_.push_back( candidate[m.queryIdx] );\n            match_2dkp_index_.push_back( m.trainIdx );\n        }\n    }\n    cout<<\"good matches: \"<<match_3dpts_.size() <<endl;\n    cout<<\"match cost time: \"<<timer.elapsed() <<endl;\n}\n\nvoid VisualOdometry::poseEstimationPnP()\n{\n    // construct the 3d 2d observations\n    vector<cv::Point3f> pts3d;\n    vector<cv::Point2f> pts2d;\n\n    for ( int index:match_2dkp_index_ )\n    {\n        pts2d.push_back ( keypoints_curr_[index].pt );\n    }\n    for ( MapPoint::Ptr pt:match_3dpts_ )\n    {\n        pts3d.push_back( pt->getPositionCV() );\n    }\n\n    Mat K = ( cv::Mat_<double> ( 3,3 ) <<\n              ref_->camera_->fx_, 0, ref_->camera_->cx_,\n              0, ref_->camera_->fy_, ref_->camera_->cy_,\n              0,0,1\n            );\n    Mat rvec, tvec, inliers;\n    cv::solvePnPRansac ( pts3d, pts2d, K, Mat(), rvec, tvec, false, 100, 4.0, 0.99, inliers );\n    num_inliers_ = inliers.rows;\n    cout<<\"pnp inliers: \"<<num_inliers_<<endl;\n    T_c_w_estimated_ = SE3 (\n                           SO3 ( rvec.at<double> ( 0,0 ), rvec.at<double> ( 1,0 ), rvec.at<double> ( 2,0 ) ),\n                           Vector3d ( tvec.at<double> ( 0,0 ), tvec.at<double> ( 1,0 ), tvec.at<double> ( 2,0 ) )\n                       );\n\n    // using bundle adjustment to optimize the pose\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6,2>> Block;\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();\n    Block* solver_ptr = new Block ( linearSolver );\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap();\n    pose->setId ( 0 );\n    pose->setEstimate ( g2o::SE3Quat (\n        T_c_w_estimated_.rotation_matrix(), T_c_w_estimated_.translation()\n    ));\n    optimizer.addVertex ( pose );\n\n    // edges\n    for ( int i=0; i<inliers.rows; i++ )\n    {\n        int index = inliers.at<int> ( i,0 );\n        // 3D -> 2D projection\n        EdgeProjectXYZ2UVPoseOnly* edge = new EdgeProjectXYZ2UVPoseOnly();\n        edge->setId ( i );\n        edge->setVertex ( 0, pose );\n        edge->camera_ = curr_->camera_.get();\n        edge->point_ = Vector3d ( pts3d[index].x, pts3d[index].y, pts3d[index].z );\n        edge->setMeasurement ( Vector2d ( pts2d[index].x, pts2d[index].y ) );\n        edge->setInformation ( Eigen::Matrix2d::Identity() );\n        optimizer.addEdge ( edge );\n        // set the inlier map points\n        match_3dpts_[index]->matched_times_++;\n    }\n\n    optimizer.initializeOptimization();\n    optimizer.optimize ( 10 );\n\n    T_c_w_estimated_ = SE3 (\n        pose->estimate().rotation(),\n        pose->estimate().translation()\n    );\n\n    cout<<\"T_c_w_estimated_: \"<<endl<<T_c_w_estimated_.matrix()<<endl;\n}\n\nbool VisualOdometry::checkEstimatedPose()\n{\n    // check if the estimated pose is good\n    if ( num_inliers_ < min_inliers_ )\n    {\n        cout<<\"reject because inlier is too small: \"<<num_inliers_<<endl;\n        return false;\n    }\n    // if the motion is too large, it is probably wrong\n    SE3 T_r_c = ref_->T_c_w_ * T_c_w_estimated_.inverse();\n    Sophus::Vector6d d = T_r_c.log();\n    if ( d.norm() > 5.0 )\n    {\n        cout<<\"reject because motion is too large: \"<<d.norm() <<endl;\n        return false;\n    }\n    return true;\n}\n\nbool VisualOdometry::checkKeyFrame()\n{\n    SE3 T_r_c = ref_->T_c_w_ * T_c_w_estimated_.inverse();\n    Sophus::Vector6d d = T_r_c.log();\n    Vector3d trans = d.head<3>();\n    Vector3d rot = d.tail<3>();\n    if ( rot.norm() >key_frame_min_rot || trans.norm() >key_frame_min_trans )\n        return true;\n    return false;\n}\n\nvoid VisualOdometry::addKeyFrame()\n{\n    if ( map_->keyframes_.empty()  )// Initial KeyFrame Insert !\n    {\n        // first key-frame, add all 3d points into map\n        for ( size_t i=0; i<keypoints_curr_.size(); i++ )\n        {\n            double d = curr_->findDepth ( keypoints_curr_[i] );\n            if ( d < 0 )\n                continue;\n            Vector3d p_world = ref_->camera_->pixel2world (\n                Vector2d ( keypoints_curr_[i].pt.x, keypoints_curr_[i].pt.y ), curr_->T_c_w_, d\n            );\n            Vector3d n = p_world - ref_->getCamCenter();\n            n.normalize();\n            MapPoint::Ptr map_point = MapPoint::createMapPoint(\n                p_world, n, descriptors_curr_.row(i).clone(), curr_.get()\n            );\n            map_->insertMapPoint( map_point );\n        }\n    }\n\n    map_->insertKeyFrame ( curr_ );\n    ref_ = curr_;\n}\n\nvoid VisualOdometry::addMapPoints()\n{\n    // add the new map points into map\n    vector<bool> matched(keypoints_curr_.size(), false);\n    for ( int index:match_2dkp_index_ )\n        matched[index] = true;\n    for ( int i=0; i<keypoints_curr_.size(); i++ )\n    {\n        if ( matched[i] == true )\n            continue;\n        double d = ref_->findDepth ( keypoints_curr_[i] );\n        if ( d<0 )\n            continue;\n        Vector3d p_world = ref_->camera_->pixel2world (\n            Vector2d ( keypoints_curr_[i].pt.x, keypoints_curr_[i].pt.y ),\n            curr_->T_c_w_, d\n        );\n        Vector3d n = p_world - ref_->getCamCenter();\n        n.normalize();\n        MapPoint::Ptr map_point = MapPoint::createMapPoint(\n            p_world, n, descriptors_curr_.row(i).clone(), curr_.get()\n        );\n        map_->insertMapPoint( map_point );\n    }\n}\n\nvoid VisualOdometry::optimizeMap()\n{\n    // remove the hardly seen and no visible points\n    for ( auto iter = map_->map_points_.begin(); iter != map_->map_points_.end(); )\n    {\n        if ( !curr_->isInFrame(iter->second->pos_) )\n        {\n            iter = map_->map_points_.erase(iter);\n            continue;\n        }\n        float match_ratio = float(iter->second->matched_times_)/iter->second->visible_times_;\n        if ( match_ratio < map_point_erase_ratio_ )\n        {\n            iter = map_->map_points_.erase(iter);\n            continue;\n        }\n\n        double angle = getViewAngle( curr_, iter->second );\n        if ( angle > M_PI/6. )\n        {\n            iter = map_->map_points_.erase(iter);\n            continue;\n        }\n        if ( iter->second->good_ == false )\n        {\n            // TODO try triangulate this map point\n        }\n        iter++;\n    }\n\n    if ( match_2dkp_index_.size()<100 )\n        addMapPoints();\n    if ( map_->map_points_.size() > 1000 )\n    {\n        // TODO map is too large, remove some one\n        map_point_erase_ratio_ += 0.05;\n    }\n    else\n        map_point_erase_ratio_ = 0.1;\n    cout<<\"map points: \"<<map_->map_points_.size()<<endl;\n}\n\ndouble VisualOdometry::getViewAngle ( Frame::Ptr frame, MapPoint::Ptr point )\n{\n    Vector3d n = point->pos_ - frame->getCamCenter();\n    n.normalize();\n    return acos( n.transpose()*point->norm_ );\n}\n\n//ReconstructF\nbool VisualOdometry::FindMotion(const Mat& F, const Mat& K,\n                                 const vector<cv::Point2f>& pts1,const vector<cv::Point2f>& pts2,\n                                 const Mat& inlierMask, SE3 &pose,\n                                 //vector<Vector3d> &vP3D,\n                                 vector<cv::Point3f> &vP3D,\n                                 vector<bool> vbTriangulated,\n                                 float minParallax, int minTriangulated)\n{\n    int N=0;\n    for(size_t i=0,\n        iend = inlierMask.cols>inlierMask.rows?inlierMask.cols:inlierMask.rows;\n        i<iend;i++)\n        {\n            if(inlierMask.at<bool>(i,0))\n                N++;\n        }\n\n    cv::Mat E = K.t()*F*K;\n\n    Mat R1, R2, t1, t2;\n    cv::decomposeEssentialMat(E, R1, R2, t1);\n    t2=-t1;\n\n\n\n\n    //vector<Eigen::Vector3d> vP3D1, vP3D2, vP3D3, vP3D4;\n    vector<cv::Point3f> vP3D1, vP3D2, vP3D3, vP3D4;\n    vector<bool> vbGood1, vbGood2, vbGood3, vbGood4;\n    float parallax1, parallax2, parallax3, parallax4;\n\n    float sigma2=2.0*2.0;\n    int nGood1 = countGoodDecompose(R1,t1,pts1,pts2,inlierMask,vP3D1, 4.0*sigma2, K, vbGood1, parallax1);\n    int nGood2 = countGoodDecompose(R1,t2,pts1,pts2,inlierMask,vP3D2, 4.0*sigma2, K, vbGood2, parallax2);\n    int nGood3 = countGoodDecompose(R2,t1,pts1,pts2,inlierMask,vP3D3, 4.0*sigma2, K, vbGood3, parallax3);\n    int nGood4 = countGoodDecompose(R2,t2,pts1,pts2,inlierMask,vP3D4, 4.0*sigma2, K, vbGood4, parallax4);\n\n    cout<< \"ngood1= \" << nGood1\n        << \"\\nngood2= \" << nGood2\n        << \"\\nngood3= \" << nGood3\n        << \"\\nngood4= \" << nGood4<<endl;\n\n\n\n    int maxGood = max(nGood1, max(nGood2, max(nGood3, nGood4)));\n    cout<<\"maxGood = \"<<maxGood<<endl;\n\n\n    int nMinGood = max(static_cast<int>(0.9*N), minTriangulated);\n\n    int nsimilar = 0;\n    if(nGood1 > .7 * maxGood) nsimilar++;\n    if(nGood2 > .7 * maxGood) nsimilar++;\n    if(nGood3 > .7 * maxGood) nsimilar++;\n    if(nGood4 > .7 * maxGood) nsimilar++;\n\n    // If there is not a clear winner (nsimilar > 1)\n    // or not enough triangulated points (maxGood>nMinGood)\n    // reject initialization\n    if( maxGood>nMinGood || nsimilar> 1)\n    {\n        cout<<\"--Ignore set:Ambiguous pose or Not enough triangulated pose\"<<endl;\n        return false;\n    }\n    Eigen::Matrix3d R;\n    Eigen::Vector3d t;\n    if( maxGood == nGood1 && parallax1 > minParallax)\n    {\n        vP3D = vP3D1;\n        vbTriangulated = std::move(vbGood1);\n        cv::cv2eigen(R1, R);\n        cv::cv2eigen(t1, t);\n    }\n    else if(maxGood == nGood2 && parallax2 > minParallax)\n    {\n        vP3D = vP3D2;\n        vbTriangulated = std::move(vbGood2);\n        cv::cv2eigen(R1, R);\n        cv::cv2eigen(t2, t);\n    }\n    else if(maxGood == nGood3 && parallax3 > minParallax)\n    {\n        vP3D = vP3D1;\n        vbTriangulated = std::move(vbGood3);\n        cv::cv2eigen(R2, R);\n        cv::cv2eigen(t1, t);\n    }\n    else if(maxGood == nGood4 && parallax4 > minParallax)\n    {\n        vP3D = vP3D1;\n        vbTriangulated = std::move(vbGood4);\n        cv::cv2eigen(R2, R);\n        cv::cv2eigen(t2, t);\n    }\n    else\n    {\n        return false;\n    }\n    pose = SE3(R,t);\n    return true;\n}\nint VisualOdometry::countGoodDecompose(const cv::Mat& R,\n                        const cv::Mat& t,\n                        const vector<cv::Point2f>& pts1,\n                        const vector<cv::Point2f>& pts2,\n                        const Mat& inliers,\n                        //vector<Eigen::Vector3d> &vP3D,\n                        vector<cv::Point3f> &vP3D,\n                        const float& th2,\n                        const cv::Mat& K,\n                        vector<bool>& vbGood, float& parallax)\n{\n    const float fx = K.at<float>(0,0);\n    const float fy = K.at<float>(1,1);\n    const float cx = K.at<float>(0,2);\n    const float cy = K.at<float>(1,2);\n    vector<float> vCosParallax;\n    vCosParallax.reserve(pts1.size()); //Camera1 Projection Matrix K[I|0]\n    vP3D.resize(pts1.size());\n    vbGood = vector<bool>(pts1.size(), false);\n    Mat P1 = cv::Mat::zeros(3,4,CV_32F);\n    Mat P2 = cv::Mat::zeros(3,4,CV_32F);\n\n    K.copyTo(P1.rowRange(0,3).colRange(0,3));\n    cv::Mat O1 = cv::Mat::zeros(3,1,CV_32F);\n\n    R.copyTo(P2.rowRange(0,3).colRange(0,3));\n    t.copyTo(P2.rowRange(0,3).col(3));\n    K.convertTo(K, CV_32F);\n    P2 = K*P2;\n    cv::Mat O2 = -R.t()*t;\n    O2.convertTo(O2, CV_32F);\n\n\n    int nGood = 0;\n\n    for(size_t i=0, iend=(inliers.cols>inliers.rows?inliers.cols:inliers.rows);i<iend; i++)\n    {\n        if(!inliers.at<bool>(i,0)) continue; // Pass outlier;\n\n        const cv::Point2f p1 = pts1[i];\n        const cv::Point2f p2 = pts2[i];\n        Eigen::Vector3d p3dC1;\n        cv::Mat cvp3dC1;\n\n        //Triangulate(p1,p2, P1,P2, p3dC1); // DLT method output is 3D point in Real space 3D\n        Triangulate(p1,p2, P1,P2,cvp3dC1 );\n\n        if(!isfinite(cvp3dC1.at<float>(0)) || !isfinite(cvp3dC1.at<float>(1)) || !isfinite(cvp3dC1.at<float>(2)))\n        {\n            vbGood[i]=false;\n            continue;\n        }\n\n        // Check parallax\n        cv::Mat normal1 = cvp3dC1 - O1;\n        float dist1 = cv::norm(normal1);\n\n        cv::Mat normal2 = cvp3dC1 - O2;\n        float dist2 = cv::norm(normal2);\n\n        float cosParallax = normal1.dot(normal2)/(dist1*dist2);\n\n        // Check depth in front of first camera (only if enough parallax, as \"infinite\" points can easily go to negative depth)\n        if(cvp3dC1.at<float>(2)<=0 && cosParallax<0.99998)\n            continue;\n\n        // Check depth in front of second camera (only if enough parallax, as \"infinite\" points can easily go to negative depth)\n        cv::Mat p3dC2 = R*cvp3dC1+t;\n\n        if(p3dC2.at<float>(2)<=0 && cosParallax<0.99998)\n            continue;\n\n        // Check reprojection error in first image\n        float im1x, im1y;\n        float invZ1 = 1.0/cvp3dC1.at<float>(2);\n        im1x = fx*cvp3dC1.at<float>(0)*invZ1+cx;\n        im1y = fy*cvp3dC1.at<float>(1)*invZ1+cy;\n\n        float squareError1 = (im1x-p1.x)*(im1x-p1.x)+(im1y-p1.y)*(im1y-p1.y);\n\n        if(squareError1>th2)\n            continue;\n\n        // Check reprojection error in second image\n        float im2x, im2y;\n        float invZ2 = 1.0/p3dC2.at<float>(2);\n        im2x = fx*p3dC2.at<float>(0)*invZ2+cx;\n        im2y = fy*p3dC2.at<float>(1)*invZ2+cy;\n\n        float squareError2 = (im2x-p2.x)*(im2x-p2.x)+(im2y-p2.y)*(im2y-p2.y);\n\n        if(squareError2>th2)\n            continue;\n\n        vCosParallax.push_back(cosParallax);\n        vP3D[i] = cv::Point3f(cvp3dC1.at<float>(0),cvp3dC1.at<float>(1),cvp3dC1.at<float>(2));\n        nGood++;\n\n        if(cosParallax<0.99998)\n            vbGood[i]=true;\n    }\n\n    if(nGood>0)\n    {\n        sort(vCosParallax.begin(),vCosParallax.end());\n\n        size_t idx = min(50,int(vCosParallax.size()-1));\n        parallax = acos(vCosParallax[idx])*180/CV_PI;\n    }\n    else\n        parallax=0;\n    return nGood;\n}\n    void VisualOdometry::Triangulate(const cv::Point2f p1,const cv::Point2f p2,\n                                     Projection P1, Projection P2,\n                                     Eigen::Vector3d& p3dC1)\n    {\n        Eigen::Matrix4d T;\n        T.row(0) = p1.x * P1.row(2) - P1.row(0);\n        T.row(1) = p1.y * P1.row(2) - P1.row(1);\n        T.row(2) = p2.x * P2.row(2) - P2.row(0);\n        T.row(3) = p2.y * P2.row(2) - P2.row(1);\n\n\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(T, ComputeFullU|ComputeFullV);\n        const MatrixXd V =svd.matrixV();\n        const Vector4d temp (V(3,0),V(3,1),V(3,2),V(3,3));\n        p3dC1 = Vector3d(temp(0)/temp(3),temp(1)/temp(3), temp(2)/temp(3));\n    }\n\nvoid VisualOdometry::FindFundamental(std::vector<bool> &vbMatchesInliers, float &score,\n                        cv::Mat &F21, std::vector<cv::Point2f> &src, std::vector<cv::Point2f> &dst)\n{\n        const int N = src.size();\n        vector<vector<size_t>> mvSets;\n        const int maxIteration = 500;\n        vector<size_t> vAllindices;\n        vAllindices.reserve(N);\n        vector<size_t> vAvailableIndices;\n\n        score = 0;\n        for(size_t i=0; i<N; i++)\n        {\n            vAllindices.push_back(i);\n        }\n        mvSets = vector<vector<size_t>> (maxIteration, vector<size_t>(8,0));\n        const int min =0;\n        const int max  = vAvailableIndices.size()-1;\n        const int d = max - min + 1;\n        for(size_t i=0; i<maxIteration; i++)\n        {\n            vAvailableIndices = vAllindices;\n\n            for(size_t j=0; j<8; j++)\n            {\n                int randi = int(((double)rand()/((double)RAND_MAX + 1.0)) * d)+min;\n                int idx = vAvailableIndices[randi];\n\n                mvSets[i][j] = idx;\n\n                vAvailableIndices[randi] = vAvailableIndices.back();\n                vAvailableIndices.pop_back();\n            }\n        }\n\n        // Launch threads to compute in parallal a fundamental matrix and a homography\n        //const int N = vbMatchesInliers.size();\n\n        // Normalize Coordinates\n        vector<cv::Point2f> vPn1, vPn2;\n        cv::Mat T1, T2;\n        Normalize(src, vPn1, T1);\n        Normalize(dst, vPn2, T2);\n        cv::Mat T2t = T2.t();\n\n        // Best Results variables\n        score = 0.0f;\n        vbMatchesInliers = vector<bool>(N, false); //\n\n\n        // Iteration variables\n        vector<cv::Point2f> vPn1i(8);\n        vector<cv::Point2f> vPn2i(8);\n        cv::Mat F21i;\n        vector<bool> vbCurrentInliers(N, false);\n        float currentScore;\n\n        // Perform all RANSAC iterations and save the solution with highest score\n    for(int it=0; it<maxIteration; it++)\n    {\n        // Select a minimum set\n        for(int j=0; j<8; j++)\n        {\n            int idx = mvSets[it][j];\n\n            vPn1i[j] = vPn1[j]; // i don't input match info just point pair set\n            vPn2i[j] = vPn2[j];\n        }\n\n        cv::Mat Fn = ComputeF21(vPn1i,vPn2i);\n        F21i = T2t*Fn*T1;\n\n        currentScore = CheckFundamental(F21i, vbCurrentInliers,src, dst, 1.0);//msigma = 1.0\n\n        if(currentScore>score)\n        {\n            F21 = F21i.clone();\n            vbMatchesInliers = vbCurrentInliers;\n            score = currentScore;\n        }\n    }\n\n\n}\nvoid VisualOdometry::Normalize(const vector<cv::Point2f>& pts, vector<cv::Point2f> &res, Mat &T)\n{\n        float meanX = 0;\n        float meanY = 0;\n        const int N = pts.size();\n\n        res.resize(N);\n\n        for(size_t i = 0; i < N; i++)\n        {\n            meanX += pts[i].x;\n            meanX += pts[i].y;\n        }\n        meanX /= N;\n        meanY /= N;\n\n        float meanDevX = 0;\n        float meanDevY = 0;\n\n        for(size_t i = 0; i< N; i++)\n        {\n            res[i].x = pts[i].x - meanX;\n            res[i].y = pts[i].y - meanY;\n\n            meanDevX += fabs(res[i].x);\n            meanDevY += fabs(res[i].y);\n        }\n        meanDevX /= N;\n        meanDevY /= N;\n\n\n        float sX = 1.0/meanDevX;\n        float sY = 1.0/meanDevY;\n\n        for(size_t i = 0; i < N; i++)\n        {\n            res[i].x *= sX;\n            res[i].y *= sY;\n        }\n\n        T = Mat::eye(3,3,CV_32F);\n        T.at<float>(0,0) = sX;\n        T.at<float>(1,1) = sY;\n        T.at<float>(0,2) = -meanX*sX;\n        T.at<float>(1,2) = -meanY*sY;\n}\n\ncv::Mat VisualOdometry::ComputeF21(const vector<cv::Point2f> &vP1, const vector<cv::Point2f> &vP2)\n{\n    const int N = vP1.size();\n\n    cv::Mat A(N, 9, CV_32F);\n\n    for(size_t i=0; i<N; i++)\n    {\n        const float u1 = vP1[i].x;\n        const float v1 = vP1[i].y;\n        const float u2 = vP2[i].x;\n        const float v2 = vP2[i].y;\n\n        A.at<float>(i,0) = u2*u1;\n        A.at<float>(i,1) = u2*v1;\n        A.at<float>(i,2) = u2;\n        A.at<float>(i,3) = v2*u1;\n        A.at<float>(i,4) = v2*v1;\n        A.at<float>(i,5) = v2;\n        A.at<float>(i,6) = u1;\n        A.at<float>(i,7) = v1;\n        A.at<float>(i,8) = 1;\n    }\n\n    cv::Mat u,w,vt;\n\n    cv::SVDecomp(A,w,u,vt,cv::SVD::MODIFY_A | cv::SVD::FULL_UV);\n\n    cv::Mat Fpre = vt.row(8).reshape(0, 3);\n\n    cv::SVDecomp(Fpre,w,u,vt,cv::SVD::MODIFY_A | cv::SVD::FULL_UV);\n\n    w.at<float>(2)=0;\n\n    return  u*cv::Mat::diag(w)*vt;\n}\nfloat VisualOdometry::CheckFundamental(const cv::Mat &F21, vector<bool> &vbMatchesInliers,\n                                       const vector<cv::Point2f> &mvKeys1, const vector<cv::Point2f> &mvKeys2,\n                                        float sigma)\n{\n    const int N = mvKeys1.size();\n\n    const float f11 = F21.at<float>(0,0);\n    const float f12 = F21.at<float>(0,1);\n    const float f13 = F21.at<float>(0,2);\n    const float f21 = F21.at<float>(1,0);\n    const float f22 = F21.at<float>(1,1);\n    const float f23 = F21.at<float>(1,2);\n    const float f31 = F21.at<float>(2,0);\n    const float f32 = F21.at<float>(2,1);\n    const float f33 = F21.at<float>(2,2);\n\n    vbMatchesInliers.resize(N);\n\n    float score = 0;\n\n    const float th = 3.841;\n    const float thScore = 5.991;\n\n    const float invSigmaSquare = 1.0/(sigma*sigma);\n\n    for(int i=0; i<N; i++)\n    {\n        bool bIn = true;\n\n        const cv::Point2f &kp1 = mvKeys1[i];\n        const cv::Point2f &kp2 = mvKeys2[i];\n\n        const float u1 = kp1.x;\n        const float v1 = kp1.y;\n        const float u2 = kp2.x;\n        const float v2 = kp2.y;\n\n        // Reprojection error in second image\n        // l2=F21x1=(a2,b2,c2)\n\n        const float a2 = f11*u1+f12*v1+f13;\n        const float b2 = f21*u1+f22*v1+f23;\n        const float c2 = f31*u1+f32*v1+f33;\n\n        const float num2 = a2*u2+b2*v2+c2;\n\n        const float squareDist1 = num2*num2/(a2*a2+b2*b2);\n\n        const float chiSquare1 = squareDist1*invSigmaSquare;\n\n        if(chiSquare1>th)\n            bIn = false;\n        else\n            score += thScore - chiSquare1;\n\n        // Reprojection error in second image\n        // l1 =x2tF21=(a1,b1,c1)\n\n        const float a1 = f11*u2+f21*v2+f31;\n        const float b1 = f12*u2+f22*v2+f32;\n        const float c1 = f13*u2+f23*v2+f33;\n\n        const float num1 = a1*u1+b1*v1+c1;\n\n        const float squareDist2 = num1*num1/(a1*a1+b1*b1);\n\n        const float chiSquare2 = squareDist2*invSigmaSquare;\n\n        if(chiSquare2>th)\n            bIn = false;\n        else\n            score += thScore - chiSquare2;\n\n        if(bIn)\n            vbMatchesInliers[i]=true;\n        else\n            vbMatchesInliers[i]=false;\n    }\n\n    return score;\n}\nVector3d VisualOdometry::Down(Eigen::Matrix3d M)\n{\n    return Vector3d(M(2,1),M(0,2),M(2,0));\n}\nvoid VisualOdometry::drawepipolarlines(const std::string& title, const cv::Mat &F,\n                const cv::Mat& img1, const cv::Mat& img2,\n                const std::vector<cv::Point2f> points1,\n                const std::vector<cv::Point2f> points2,\n                const float inlierDistance)\n{\n  CV_Assert(img1.size() == img2.size() && img1.type() == img2.type());\n  cv::Mat outImg(img1.rows, img1.cols*2, CV_8UC3);\n  cv::Rect rect1(0,0, img1.cols, img1.rows);\n  cv::Rect rect2(img1.cols, 0, img1.cols, img1.rows);\n  /*\n   * Allow color drawing\n   */\n  if (img1.type() == CV_8U)\n  {\n    cv::cvtColor(img1, outImg(rect1), cv::COLOR_GRAY2BGR);\n    cv::cvtColor(img2, outImg(rect2), cv::COLOR_GRAY2BGR);\n  }\n  else\n  {\n    img1.copyTo(outImg(rect1));\n    img2.copyTo(outImg(rect2));\n  }\n  std::vector<cv::Point3f> epilines1, epilines2;\n  cv::computeCorrespondEpilines(points1, 1, F, epilines1); //Index starts with 1\n  cv::computeCorrespondEpilines(points2, 2, F, epilines2);\n\n  CV_Assert(points1.size() == points2.size() &&\n        points2.size() == epilines1.size() &&\n        epilines1.size() == epilines2.size());\n\n  cv::RNG rng(0);\n  for(size_t i=0; i<points1.size(); i++)\n  {\n    if(inlierDistance > 0)\n    {\n      if(distancePointLine(points1[i], epilines2[i]) > inlierDistance||\n        distancePointLine(points2[i], epilines1[i]) > inlierDistance)\n      {\n        //The point match is no inlier\n        continue;\n      }\n    }\n    /*\n     * Epipolar lines of the 1st point set are drawn in the 2nd image and vice-versa\n     */\n    cv::Scalar color(rng(256),rng(256),rng(256));\n\n    cv::line(outImg(rect2),\n      cv::Point(0,-epilines1[i].z/epilines1[i].y),\n      cv::Point(img1.cols,-(epilines1[i].z+epilines1[i].x*img1.cols)/epilines1[i].y),\n      color);\n    cv::circle(outImg(rect1), points1[i], 3, color, -1);\n\n    cv::line(outImg(rect1),\n      cv::Point(0,-epilines2[i].z/epilines2[i].y),\n      cv::Point(img2.cols,-(epilines2[i].z+epilines2[i].x*img2.cols)/epilines2[i].y),\n      color);\n    cv::circle(outImg(rect2), points2[i], 3, color, -1);\n  }\n  cv::imshow(title, outImg);\n}\n\nfloat VisualOdometry::distancePointLine(const cv::Point2f& point, const cv::Point3f& line)\n{\n  //Line is given as a*x + b*y + c = 0\n  return std::fabs(line.x*point.x + line.y*point.y + line.z)\n      / std::sqrt(line.x*line.x+line.y*line.y);\n}\nvoid VisualOdometry::Triangulate(const cv::Point2f &p1, const cv::Point2f &p2, const cv::Mat &P1, const cv::Mat &P2, Mat &x3D)\n{\n    cv::Mat A(4,4,CV_32F);\n    A.row(0) = p1.x*P1.row(2)-P1.row(0);\n    A.row(1) = p1.y*P1.row(2)-P1.row(1);\n    A.row(2) = p2.x*P2.row(2)-P2.row(0);\n    A.row(3) = p2.y*P2.row(2)-P2.row(1);\n\n    cv::Mat u,w,vt;\n    cv::SVD::compute(A,w,u,vt,cv::SVD::MODIFY_A| cv::SVD::FULL_UV);\n    x3D = vt.row(3).t();\n    x3D = x3D.rowRange(0,3)/x3D.at<float>(3);\n    x3D.convertTo(x3D, CV_32F);\n}\n\nvoid VisualOdometry::CreateInitialMapMonocular()\n{\n\n}\n\n}\n", "meta": {"hexsha": "6d46e97dc111ddb49a5fe9823150efae31f4c01d", "size": 34870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project/0.4/src/visual_odometry.cpp", "max_stars_repo_name": "minooisbusy/slambook", "max_stars_repo_head_hexsha": "e232ca37db923da0f3aa1261ce2d77d68db245f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project/0.4/src/visual_odometry.cpp", "max_issues_repo_name": "minooisbusy/slambook", "max_issues_repo_head_hexsha": "e232ca37db923da0f3aa1261ce2d77d68db245f3", "max_issues_repo_licenses": ["MIT"], "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/0.4/src/visual_odometry.cpp", "max_forks_repo_name": "minooisbusy/slambook", "max_forks_repo_head_hexsha": "e232ca37db923da0f3aa1261ce2d77d68db245f3", "max_forks_repo_licenses": ["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.6498127341, "max_line_length": 204, "alphanum_fraction": 0.5496128477, "num_tokens": 10136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556866, "lm_q2_score": 0.04885778364256332, "lm_q1q2_score": 0.02045660300911008}}
{"text": "#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <cstdint>\n#include <limits>\n\n#include <ast.hpp>\n#include <util.hpp>\n#include <exception.hpp>\n#include <abstraction.hpp>\n\nnamespace ila\n{\n    // ---------------------------------------------------------------------- //\n    const std::string BitvectorOp::operatorNames[] = {\n        \"invalid\",\n        // unary\n        \"neg\", \"~\",\n        \"rotate-left\", \"rotate-right\", \"zero-extend\", \"sign-extend\", \"extract\",\n        // binary\n        \"+\", \"-\", \"and\", \"or\", \"xor\", \"xnor\", \"nand\", \"nor\",\n        \"div\", \"udiv\", \"rem\", \"urem\", \"mod\", \"shl\", \"lshr\", \"ashr\", \n        \"*\", \"concat\", \"get-bit\", \"readmem\", \"read-block\",\n\t\t// ternary\n        \"if\", \"apply_fun\", \n    };\n\n    // ---------------------------------------------------------------------- //\n    BitvectorExpr::BitvectorExpr(int width) \n        : Node(NodeType::getBitvector(width))\n    {\n    }\n\n    BitvectorExpr::BitvectorExpr(NodeType t)\n        : Node(t)\n    {\n        ILA_ASSERT(t.isBitvector(), \"BitvectorExpr type mismatch.\");\n    }\n\n    BitvectorExpr::~BitvectorExpr()\n    {\n    }\n\n    // ---------------------------------------------------------------------- //\n    BitvectorVar::BitvectorVar(const std::string& n, int width) \n        : BitvectorExpr(width)\n    {\n        this->name = n;\n    }\n\n    BitvectorVar::~BitvectorVar()\n    {\n    }\n\n    Node* BitvectorVar::clone() const\n    {\n        return new BitvectorVar(name, type.bitWidth);\n    }\n\n    bool BitvectorVar::equal(const Node* that_) const\n    {\n        const BitvectorVar* that = dynamic_cast<const BitvectorVar*>(that_);\n        if (that != NULL) {\n            return that->type == this->type &&\n                   that->name == this->name;\n        } else {\n            return false;\n        }\n    }\n\n    std::ostream& BitvectorVar::write(std::ostream& out) const\n    {\n        return (out << name);\n    }\n\n\n    // ---------------------------------------------------------------------- //\n    BitvectorConst::BitvectorConst(\n        const mp_int_t& v, int w)\n        : BitvectorExpr(w)\n        , value(v)\n    {\n    }\n\n    BitvectorConst::BitvectorConst(unsigned int v, int w)\n        : BitvectorExpr(w)\n        , value(v)\n    {\n    }\n\n    BitvectorConst::BitvectorConst(const BitvectorConst& that)\n        : BitvectorExpr(that.type.bitWidth)\n        , value(that.value)\n    {\n    }\n\n    BitvectorConst::~BitvectorConst()\n    {\n    }\n\n    Node* BitvectorConst::clone() const\n    {\n        return new BitvectorConst(*this);\n    }\n\n    bool BitvectorConst::equal(const Node* that_) const\n    {\n        const BitvectorConst* that = dynamic_cast<const BitvectorConst*>(that_);\n        if (that != NULL) {\n            return that->type == this->type &&\n                   that->value == this->value;\n        } else {\n            return false;\n        }\n    }\n\n    py::object BitvectorConst::getValue() const\n    {\n        using namespace py;\n\n        std::string vstr = boost::lexical_cast<std::string>(value);\n        PyObject* l_e = PyInt_FromString((char*) vstr.c_str(), NULL, 0);\n        object o_e(handle<>(borrowed(l_e)));\n        return o_e;\n    }\n\n    std::ostream& BitvectorConst::write(std::ostream& out) const\n    {\n        return (out << value);\n    }\n\n    // ---------------------------------------------------------------------- //\n    unsigned BitvectorOp::nArgs() const\n    {\n        return args.size();\n    }\n\n    unsigned BitvectorOp::nParams() const\n    {\n        return params.size();\n    }\n\n    nptr_t BitvectorOp::arg(unsigned i) const\n    {\n        return i < args.size() ? args[i] : NULL;\n    }\n\n    int BitvectorOp::param(unsigned i) const\n    {\n        return i < params.size() ? params[i] : 0;\n    }\n    // ---------------------------------------------------------------------- //\n    int BitvectorOp::getUnaryResultWidth(Op op, const nptr_t& n)\n    {\n        // FIXME: add more code when operators are added.\n        if (op >= NEGATE && op <= RROTATE) {\n            return n->type.bitWidth;\n        } else { \n            return n->type.bitWidth;\n        }\n    }\n\n    int BitvectorOp::getBinaryResultWidth(\n        Op op, const nptr_t& n1, const nptr_t& n2)\n    {\n        // FIXME: add more code when operators are added.\n        if (op >= ADD && op <= MUL) {\n            return n1->type.bitWidth;\n        } else if (op == CONCAT) {\n            return n1->type.bitWidth + n2->type.bitWidth;\n        } else if (op == GET_BIT) {\n            return 1;\n        } else if (op == READMEM) {\n            return n1->type.dataWidth;\n        } else { \n            return n1->type.bitWidth; // INVALID\n        }\n    }\n\n    int BitvectorOp::getBinaryResultWidth(\n        Op op, const nptr_t& n1, const nptr_t& n2, int param)\n    {\n        if (op == READMEMBLOCK) {\n            return n1->type.dataWidth*param;\n        } else {\n            // INVALID\n            return 0;\n        }\n    }\n\n    int BitvectorOp::getBinaryResultWidth(\n        Op op, const nptr_t& n1, int param)\n    {\n        if (op >= Z_EXT && op <= S_EXT) {\n            return param;\n        } else {\n            return n1->type.bitWidth;\n        }\n    }\n\n    int BitvectorOp::getNaryResultWidth(\n        Op op, nptr_vec_t& args)\n    {\n        // FIXME: add more code when operators are added.\n        if (op == IF && args.size() == 3) {\n            // ITE\n            return args[1]->type.bitWidth;\n        } else if (op == APPLY_FUNC) {\n            // Apply function\n            return args[0]->type.bitWidth;\n        } else {\n            return 1;\n        }\n    }\n\n    int BitvectorOp::getNaryResultWidth(\n        Op op, nptr_vec_t& args, std::vector< int >& params)\n    {\n        // FIXME: add more code when operators are added.\n        if (op == EXTRACT && params.size() == 2) {\n            // EXTRACT\n            return (params[1] - params[0] + 1);\n        } else {\n            return 1;\n        }\n    }\n\n    bool BitvectorOp::checkUnaryOpWidth(Op op, const nptr_t& arg0, int width)\n    {\n        // FIXME: add more code when operators are added.\n        if (op >= Z_EXT && op <= S_EXT) {\n            return (arg0->type.isBitvector() && arg0->type.bitWidth <= width);\n        } else {\n            return arg0->type.isBitvector(width);\n        }\n    }\n\n    int BitvectorOp::checkBinaryOpWidth(\n        Op op, \n        const nptr_t& n1, \n        const nptr_t& n2,\n        int width)\n    {\n        // FIXME: add more code when operators are added.\n        if (op >= ADD && op <= MUL) {\n            if (!n1->type.isBitvector(width)) {\n                return 1;\n            } else if (!n2->type.isBitvector(width)) {\n                return 2;\n            } else {\n                return 0;\n            }\n        } else if (op == GET_BIT) {\n            if (!n1->type.isBitvector()) {\n                return 1;\n            } else if (!n2->type.isBitvector()) {\n                return 2;\n            } else {\n                return 0;\n            }\n        } else if (op == READMEM) {\n            if (!n1->type.isMem()) {\n                return 1;\n            } else if (!n2->type.isBitvector(n1->type.addrWidth)) {\n                return 2;\n            } else {\n                return 0;\n            }\n        }\n        // CONCAT can have different operand width\n        return 0;\n    }\n\n    int BitvectorOp::checkBinaryOpWidth(\n        Op op, \n        const nptr_t& n1, \n        const nptr_t& n2,\n        int param,\n        int width)\n    {\n        // FIXME: add more code when operators are added.\n        if (op == READMEMBLOCK) {\n            if (!n1->type.isMem()) {\n                return 1;\n            } else if (!n2->type.isBitvector(n1->type.addrWidth)) {\n                return 2;\n            } else {\n                return 0;\n            }\n        }\n        ILA_ASSERT(false, \"Unknown binary operator with param.\");\n        return 0;\n    }\n\n    int BitvectorOp::checkBinaryOpWidth(\n        Op op,\n        const nptr_t& n1,\n        int param,\n        int width)\n    {\n        if (op >= LROTATE && op <= RROTATE) {\n            if (param > width) {\n                return 2;\n            } else if (!n1->type.isBitvector(width)) {\n                return 1;\n            } else {\n                return 0;\n            }\n        } else if (op >= Z_EXT && op <= S_EXT) {\n            if (param < width) {\n                return 1;\n            } else {\n                return 0;\n            }\n        } else {\n            return 0;\n        }\n    }\n    int BitvectorOp::checkNaryOpWidth(\n        Op op,\n        nptr_vec_t& args,\n        int width)\n    {\n        // FIXME: modify the code if other n-ary ops are added.\n        if (op >= IF && op <= IF && args.size() == 3) {\n            // (cond, trueExp, falseExp)\n            for (unsigned i=1; i != args.size(); i++) {\n                if (!args[1]->type.isBitvector(width)) {\n                    return i+1;\n                }\n            }\n            if (!args[0]->type.isBool() /* or nonzero (bv) */ ) {\n                return 1;\n            } \n        } else if (op == APPLY_FUNC) {\n            // (f, ip0, ip1, ...)\n            std::vector<int> argWidth;\n            for (unsigned i = 1; i != args.size(); i++) {\n                argWidth.push_back(args[i]->type.bitWidth);\n            }\n            if (!args[0]->type.isFunc(width, argWidth)) {\n                return 1;\n            }\n            for (unsigned i = 1; i != args.size(); i++) {\n                if (!args[i]->type.isBitvector(args[0]->type.argsWidth[i-1])) {\n                    return i + 1;\n                }\n            }\n            return 0;\n        }\n        return 0;\n    }\n\n    int BitvectorOp::checkNaryOpWidth(\n        Op op,\n        nptr_vec_t& args,\n        std::vector< int >& params,\n        int width)\n    {\n        // FIXME: modify the code if other n-ary ops are added\n        if (op >= EXTRACT && op <= EXTRACT) {\n            // (bv, start, end)\n            if (params.size() == 2 && args.size() == 1) {\n                if (params[0] < 0) {\n                    return 2;\n                } else if (params[1] >= args[0]->type.bitWidth) {\n                    return 3;\n                } else if (!args[0]->type.isBitvector()) {\n                    return 1;\n                }\n            }\n        }\n        return 0;\n    }\n\n    // ---------------------------------------------------------------------- //\n    // constructor: unary ops.\n    BitvectorOp::BitvectorOp(\n        Op op, \n        const nptr_t& n1\n    )\n      : BitvectorExpr(getUnaryResultWidth(op, n1))\n      , arity(UNARY)\n      , op(op)\n    {\n\n        // check if for the correct operator.\n        if (!isUnary(op)) {\n            throw PyILAException(PyExc_ValueError, \n                                 \"Invalid unary operator: \" +\n                                 operatorNames[op]);\n        }\n        // check for the right type.\n        if (!checkUnaryOpWidth(op, n1, type.bitWidth)) {\n            throw PyILAException(\n                PyExc_TypeError, \n                \"Invalid type for unary operator argument.\");\n        }\n\n        // push this into the vector.\n        args.push_back( n1 );\n    }\n\n    // constructor: unary op with int input (ex. rotate)\n    BitvectorOp::BitvectorOp(\n        Op op,\n        const nptr_t& n1,\n        int param\n    )\n      : BitvectorExpr(getBinaryResultWidth(op, n1, param))\n      , arity(UNARY)\n      , op(op)\n    {\n        if (!isUnary(op)) {\n            throw PyILAException(PyExc_ValueError,\n                                 \"Invalid binary operator: \" + \n                                 operatorNames[op]);\n        }\n        if(!checkUnaryOpWidth(op, n1, type.bitWidth)) {\n            throw PyILAException(PyExc_TypeError,\n                \"Invalid operand for operator: \" + operatorNames[op]);\n        }\n        args.push_back( n1 );\n        params.push_back(param);\n    }\n\n    // constructor: extract\n    BitvectorOp::BitvectorOp(\n        Op op, \n        const nptr_t& n1,\n        int p1, int p2\n    )\n        : BitvectorExpr((p1 - p2)+1)\n        , arity(UNARY)\n        , op(op)\n    {\n        if(op != EXTRACT) {\n            throw PyILAException(PyExc_ValueError,\n                     \"Invalid operator: \" + operatorNames[op]);\n        } else if(p1 < p2) {\n            throw PyILAException(PyExc_ValueError,\n                     \"Invalid indices to extract.\");\n        }\n        if (!(n1->type.isBitvector()    &&\n              n1->type.bitWidth >= p1   &&\n              n1->type.bitWidth >= p2)) \n        {\n            throw PyILAException(PyExc_TypeError,\n                    \"Invalid type for operator: \" + operatorNames[op]);\n        }\n        args.push_back(n1);\n        params.push_back(p1);\n        params.push_back(p2);\n    }\n\n    // constructor: binary ops.\n    BitvectorOp::BitvectorOp(\n        Op op,\n        const nptr_t& n1,\n        const nptr_t& n2\n    )\n      : BitvectorExpr(getBinaryResultWidth(op, n1, n2))\n      , arity(BINARY)\n      , op(op)\n    {\n        if (!isBinary(op)) {\n            throw PyILAException(PyExc_ValueError,\n                                 \"Invalid binary operator: \" + \n                                 operatorNames[op]);\n        }\n\n        int error = checkBinaryOpWidth(op, n1, n2, type.bitWidth);\n        if (error != 0) {\n            throw PyILAException(PyExc_TypeError,\n                \"Invalid operand (\" + \n                boost::lexical_cast<std::string>(error) +\n                \") for operator: \" + operatorNames[op]);\n        }\n        args.push_back( n1 );\n        args.push_back( n2 );\n    }\n\n    BitvectorOp::BitvectorOp(Op op,\n        const nptr_t& n1,\n        const nptr_t& n2,\n        int blocks,\n        endianness_t e)\n      : BitvectorExpr(getBinaryResultWidth(op, n1, n2, blocks))\n      , arity(BINARY)\n      , op(op)\n    {\n        if (op != READMEMBLOCK) {\n            throw PyILAException(PyExc_ValueError,\n                                 \"Invalid binary operator; expected read-block.\");\n        }\n        if (blocks < 1) {\n            throw PyILAException(PyExc_ValueError,\n                                 \"Invalid number of chunks.\");\n        }\n        if (e != LITTLE_E && e != BIG_E) {\n            throw PyILAException(PyExc_ValueError,\n                                \"Invalid endianness value.\");\n        }\n\n        int error = checkBinaryOpWidth(op, n1, n2, blocks, type.bitWidth);\n        if (error != 0) {\n            throw PyILAException(PyExc_TypeError,\n                \"Invalid operand (\" + \n                boost::lexical_cast<std::string>(error) +\n                \") for operator: \" + operatorNames[op]);\n        }\n        args.push_back( n1 );\n        args.push_back( n2 );\n        params.push_back( blocks );\n        params.push_back( (int) e);\n    }\n\n    \n    // constructor: ternary ops\n    BitvectorOp::BitvectorOp(\n        Op op, nptr_vec_t& args_\n    )\n      : BitvectorExpr(getNaryResultWidth(op, args_))\n      , arity(NARY)\n      , op(op)\n      , args(args_)\n    {\n        if (!isTernary(op) && !isNary(op)) {\n            throw PyILAException(PyExc_ValueError,\n                                 \"Invalid n-ary operator: \" + \n                                 operatorNames[op]);\n        }\n        int error = checkNaryOpWidth(op, args, type.bitWidth);\n        if (error != 0) {\n            throw PyILAException(PyExc_TypeError,\n                \"Invalid operand (\" + \n                boost::lexical_cast<std::string>(error) +\n                \") for operator: \" + operatorNames[op]);\n        }\n    }\n\n    BitvectorOp::BitvectorOp(const BitvectorOp* other, nptr_vec_t& args_)\n      : BitvectorExpr(other->type.bitWidth)\n      , arity(other->arity)\n      , op(other->op)\n      , args(args_)\n      , params(other->params)\n    {\n    }\n\n    // destructor.\n    BitvectorOp::~BitvectorOp()\n    {\n    }\n\n    // ---------------------------------------------------------------------- //\n    // clone.\n    Node* BitvectorOp::clone() const\n    {\n        if (arity == UNARY) {\n            ILA_ASSERT(args.size() == 1, \n                \"Unary op must have exactly one argument.\");\n            // check type if it is zero/sign_extend\n            if(op == Z_EXT || op == S_EXT)\n                return new BitvectorOp(op, args[0], params[0]);\n            else if (op == EXTRACT)\n                return new BitvectorOp(op, args[0], params[0], params[1]);\n            else\n                return new BitvectorOp(op, args[0]);\n        } else if(arity == BINARY) {\n            ILA_ASSERT(args.size() == 2,\n                \"Binary op must have exactly two arguments.\");\n            return new BitvectorOp(op, args[0], args[1]);\n        } else if (arity == NARY) {\n            ILA_ASSERT(args.size() >= 1,\n                \"Nary op must have more than one arguments.\");\n            nptr_vec_t newargs;\n            for (unsigned i = 0; i != args.size(); i++)\n                newargs.push_back(args[i]);\n            return new BitvectorOp(op, newargs);\n        } else {\n            ILA_ASSERT(false, \"Unsupported arity in BitvectorOp\");\n            return NULL;\n        }\n    }\n\n    // equal.\n    bool BitvectorOp::equal(const Node* that_) const\n    {\n        const BitvectorOp* that = dynamic_cast<const BitvectorOp*>(that_);\n        if (that != NULL) {\n            // compare op and type..\n            bool t1 = that->type == this->type && this->op == that->op &&\n                      that->args.size() == this->args.size()           &&\n                      that->params.size() == this->params.size();\n            if (!t1) return false;\n\n            // compare params.\n            for (unsigned i=0; i != params.size(); i++) {\n                if (this->params[i] != that->params[i]) {\n                    return false;\n                }\n            }\n\n            // compare args.\n            for (unsigned i=0; i < args.size(); i++) {\n                if (!this->args[i]->equal(that->args[i].get())) {\n                    return false;\n                }\n            }\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    // stream output.\n    std::ostream& BitvectorOp::write(std::ostream& out) const\n    {\n        out << \"(\" << operatorNames[(int)op];\n        for (auto arg: args) {\n            out << \" \" << *arg.get();\n        }\n        for (auto p : params) {\n            out << \" #\" << p;\n        }\n        out << \")\";\n        return out;\n    }\n\n}\n\n", "meta": {"hexsha": "2ee831a8697600fe1fe72445dc71a6320f30f849", "size": 18270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "py-tmpl-synth/src/ast/bitvec.cpp", "max_stars_repo_name": "pramodsu/ILA-Tools", "max_stars_repo_head_hexsha": "e76bd90cf356ada8dd6f848fb377f57c83322c71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T03:51:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T03:51:27.000Z", "max_issues_repo_path": "py-tmpl-synth/src/ast/bitvec.cpp", "max_issues_repo_name": "pramodsu/ILA-Tools", "max_issues_repo_head_hexsha": "e76bd90cf356ada8dd6f848fb377f57c83322c71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-25T08:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-25T08:49:22.000Z", "max_forks_repo_path": "py-tmpl-synth/src/ast/bitvec.cpp", "max_forks_repo_name": "pramodsu/ILA-Tools", "max_forks_repo_head_hexsha": "e76bd90cf356ada8dd6f848fb377f57c83322c71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-06-26T11:31:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T20:16:21.000Z", "avg_line_length": 28.9082278481, "max_line_length": 82, "alphanum_fraction": 0.4603174603, "num_tokens": 4422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.051082740026862944, "lm_q1q2_score": 0.020423474834254125}}
{"text": "/*\n * Copyright (C) 2015 INRA\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 *    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 *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n * OR 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 SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef ORG_VLEPROJECT_KERNEL_DSDE_QSS2_HPP\n#define ORG_VLEPROJECT_KERNEL_DSDE_QSS2_HPP\n\n#include <vle/dsde/dsde.hpp>\n#include <vle/qss-common.hpp>\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace vle {\nnamespace dsde {\nnamespace qss2 {\n\nstruct var {\n    constexpr var() noexcept\n        : v(nan())\n        , mv(nan())\n    {}\n\n    double v;\n    double mv;\n};\n\ntemplate <std::size_t N>\nclass inputport\n{\npublic:\n    constexpr inputport() noexcept\n        : m_dirac(false)\n    {\n    }\n\n    constexpr const var &operator[](std::size_t i) const noexcept\n    {\n        return m_value[i];\n    }\n\n    constexpr var &operator[](std::size_t i) noexcept\n    {\n        return m_value[i];\n    }\n\n    constexpr void dirac() noexcept\n    {\n        m_dirac = true;\n    }\n\n    constexpr void clear() noexcept\n    {\n        m_value.fill(var());\n        m_dirac = false;\n    }\n\n    constexpr std::size_t size() const noexcept\n    {\n        return N;\n    }\n\n    constexpr bool empty() const noexcept\n    {\n        if (m_dirac)\n            return false;\n\n        for (auto val : m_value)\n            if (not std::isnan(val.v))\n                return false;\n\n        return true;\n    }\n\n    std::array <var, N> m_value;\n    bool m_dirac;\n};\n\nclass doubleport\n{\npublic:\n    constexpr const double &operator[](std::size_t i) const noexcept\n    {\n        return (i == 0) ? m_value.v : m_value.mv;\n    }\n\n    constexpr double &operator[](std::size_t i) noexcept\n    {\n        return (i == 0) ? m_value.v : m_value.mv;\n    }\n\n    constexpr std::size_t size() const noexcept\n    {\n        return 1u;\n    }\n\n    constexpr double v() const noexcept\n    {\n        return m_value.v;\n    }\n\n    constexpr double mv() const noexcept\n    {\n        return m_value.mv;\n    }\n\n    constexpr void clear() noexcept\n    {\n        m_value.v = nan();\n        m_value.mv = nan();\n    }\n\n    bool empty() const noexcept\n    {\n        return std::isnan(m_value.v);\n    }\n\n    var m_value;\n};\n\ntemplate <typename Time, std::size_t N>\nclass StaticFunction : public AtomicModel <Time, inputport <N>, doubleport>\n{\npublic:\n    using inputport_type = inputport <N>;\n    using outputport_type = doubleport;\n    using parent_type = AtomicModel <Time, inputport_type, outputport_type>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n    using array_type = std::array <double, N>;\n    using function_type = Function <Time, array_type>;\n\n    StaticFunction(const Context &ctx,\n                   Function <Time, array_type> function_)\n        : parent_type(ctx)\n        , m_integrate_function(function_)\n    {\n        static_assert(N > 0,\n                      \"vle::dsde::qss2::StaticFunction: bad system size\");\n    }\n\n    virtual time_type init(const vle::Common &/*common*/,\n                           const time_type &t) override final\n    {\n        m_variable.fill(0);\n        m_mv.fill(0);\n        m_time = t;\n        return Time::infinity();\n    }\n\n    virtual void lambda() const override final\n    {\n        parent_type::y.m_value = m_y;\n    }\n\n    virtual time_type delta(const time_type &e, const time_type &/*r*/,\n                            const time_type &t) override final\n    {\n        if (not parent_type::x.empty()) {\n            for (auto i = 0ul; i < N; ++i)\n                m_variable[i] += m_mv[i] * e;\n\n            double fv = m_integrate_function(m_variable, t);\n            array_type vaux;\n\n            for (auto i = 0ul; i < N; ++i) {\n                if (not std::isnan(parent_type::x[i].v)) {\n                    vaux[i] = m_variable[i];\n                    m_variable[i] = parent_type::x[i].v;\n                    m_mv[i] = parent_type::x[i].mv;\n                } else {\n                    vaux[i] = nan();\n                }\n            }\n\n            m_y.v = m_integrate_function(m_variable, t);\n\n            for (auto i = 0ul; i < N; ++i) {\n                if (not std::isnan(vaux[i]) and vaux[i] != m_variable[i])\n                    m_c[i] = (fv - m_y.v) / (vaux[i] - m_variable[i]);\n            }\n\n            m_y.mv = 0;\n\n            for (auto i = 0ul; i != N; ++i)\n                m_y.mv += m_mv[i] * m_c[i];\n\n            return 0;\n        }\n\n        return Time::infinity();\n    }\n\nprivate:\n    array_type m_variable;\n    array_type m_mv;\n    array_type m_c;\n    var m_y;\n    Function <Time, array_type> m_integrate_function;\n    time_type m_time;\n};\n\ntemplate <typename Time, std::size_t N>\nclass Integrator : public AtomicModel <Time, inputport <N>, doubleport>\n{\npublic:\n    using inputport_type = inputport <N>;\n    using outputport_type = doubleport;\n    using parent_type = AtomicModel <Time, inputport_type, outputport_type>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n\n    Integrator(const Context &ctx, double dq, double x)\n        : parent_type(ctx)\n        , m_dx(0)\n        , m_mdx(0)\n        , m_x(x)\n        , m_q(x)\n        , m_mq(0)\n        , m_dq(dq)\n        , m_sigma(0)\n    {}\n\n    virtual time_type init(const vle::Common &/*common*/,\n                           const time_type &/*time*/) override final\n    {\n        return m_sigma;\n    }\n\n    virtual void lambda() const override final\n    {\n        parent_type::y[0] = m_x + m_dx * m_sigma + m_mdx / 2. * m_sigma * m_sigma;\n        parent_type::y[1] = m_dx + m_mdx * m_sigma;\n    }\n\n    virtual time_type delta(const time_type &e, const time_type &/*r*/,\n                            const time_type &/*t*/) override final\n    {\n        if (parent_type::x.empty()) {\n            m_x += m_dx * m_sigma + m_mdx / 2. * m_sigma * m_sigma;\n            m_q = m_x;\n            m_dx += m_mdx * m_sigma;\n            m_mq = m_dx;\n\n            if (m_mdx == 0)\n                m_sigma = Time::infinity();\n            else\n                m_sigma = std::sqrt(2. * m_dq / std::abs(m_mdx));\n        } else {\n            double a, b, c, s;\n            m_x += m_dx * e + m_mdx / 2. * e * e;\n            m_dx = parent_type::x[0].v;\n            m_mdx = parent_type::x[0].mv;\n\n            if (m_sigma != 0) {\n                m_q = m_q + m_mq * e;\n                a = m_mdx / 2.;\n                b = m_dx - m_mq;\n                c = m_x - m_q + m_dq;\n                m_sigma = Time::infinity();\n\n                if (a == 0) {\n                    if (b != 0) {\n                        s = -c / b;\n\n                        if (s > 0)\n                            m_sigma = s;\n\n                        c = m_x - m_q - m_dq;\n                        s = -c / b;\n\n                        if (s > 0 and s < m_sigma)\n                            m_sigma = s;\n                    }\n                } else {\n                    s = (-b + std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                    if (s > 0)\n                        m_sigma = s;\n\n                    s = (-b - std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                    if (s > 0 and s < m_sigma)\n                        m_sigma = s;\n\n                    c = m_x - m_q - m_dq;\n                    s = (-b + std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                    if (s > 0 and s < m_sigma)\n                        m_sigma = s;\n\n                    s = (-b - std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                    if (s > 0 and s < m_sigma)\n                        m_sigma = s;\n                }\n            }\n        }\n\n        return m_sigma;\n    }\n\n    constexpr inline double value() const noexcept\n    {\n        return m_x;\n    }\n\nprivate:\n    std::array <double, 2> m_y;\n    double m_dx;\n    double m_mdx;\n    double m_x;\n    double m_q;\n    double m_mq;\n    double m_dq;\n    time_type m_sigma;\n};\n\ntemplate <typename Time, std::size_t N>\nclass EquationBlock : public CoupledModel <Time,\n    inputport <N>, doubleport,\n    inputport <N>, doubleport>\n{\npublic:\n    using inputport_type = inputport <N>;\n    using outputport_type = doubleport;\n\n    using parent_type = CoupledModel\n                        <Time, inputport_type, outputport_type, inputport_type, outputport_type>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n    using array_type = std::array <double, N>;\n\n    using UpdatedPort = typename parent_type::UpdatedPort;\n\n    EquationBlock(const vle::Context &ctx,\n                  double dq,\n                  double x,\n                  std::size_t id,\n                  Function <Time, array_type> function_)\n        : parent_type(ctx)\n        , m_integrator(ctx, dq, x)\n        , m_staticfunction(ctx, function_)\n        , m_id(id)\n    {\n        if (id >= N)\n            throw std::invalid_argument(\n                \"vle::dsde::qss2::EquationBlock: bad id or system size\");\n    }\n\n    virtual typename parent_type::children_t\n    children(const vle::Common &) override final\n    {\n        return { &m_integrator, &m_staticfunction };\n    }\n\n    virtual void post(const UpdatedPort &/*out*/,\n                      UpdatedPort &in) const override final\n    {\n        if (not m_staticfunction.y.empty()) {\n            m_integrator.x[0] = m_staticfunction.y.m_value;\n            in.emplace(&m_integrator);\n        }\n\n        if (not m_integrator.y.empty()) {\n            m_staticfunction.x[m_id] = m_integrator.y.m_value;\n            parent_type::y.m_value = m_integrator.y.m_value;\n            in.emplace(&m_staticfunction);\n        }\n\n        for (auto i = 0ul; i != N; ++i) {\n            if (!std::isnan(parent_type::x[i].v)) {\n                m_staticfunction.x[i] = parent_type::x[i];\n                in.emplace(&m_staticfunction);\n            }\n        }\n    }\n\n    constexpr inline double value() const noexcept\n    {\n        return m_integrator.value();\n    }\n\nprivate:\n    Integrator <Time, N> m_integrator;\n    StaticFunction <Time, N> m_staticfunction;\n    std::size_t m_id;\n};\n\n\ntemplate <typename Time, std::size_t N>\nclass Equation : public AtomicModel <Time, inputport <N>, doubleport>\n{\npublic:\n    using inputport_type = inputport <N>;\n    using outputport_type = doubleport;\n    using parent_type = AtomicModel <Time, inputport_type, outputport_type>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n    using array_type = std::array <double, N>;\n    using function_type = Function <Time, array_type>;\n\n    Equation(const Context &ctx, double dq, double x,\n             std::size_t id, Function <Time, array_type> function)\n        : parent_type(ctx)\n        , m_integrate_function(function)\n        , m_dx(0)\n        , m_mdx(0)\n        , m_q(x)\n        , m_mq(0)\n        , m_dq(dq)\n        , m_sigma(0)\n        , m_id(id)\n    {\n        static_assert(N > 0,\n                      \"vle::dsde::qss2::Equation: bad system size\");\n\n        if (id >= N)\n            throw std::invalid_argument(\n                \"vle::dsde::qss2::Equation: bad id or system size\");\n    }\n\n    virtual time_type init(const vle::Common &/*common*/,\n                           const time_type &/*t*/) override final\n    {\n        m_variable.fill(0);\n        m_mv.fill(0);\n        m_variable[m_id] = m_q;\n        return m_sigma;\n    }\n\n    virtual void lambda() const override final\n    {\n        parent_type::y[0] = m_variable[m_id] + m_dx * m_sigma +\n                            m_mdx / 2. * m_sigma * m_sigma;\n        parent_type::y[1] = m_dx + m_mdx * m_sigma;\n    }\n\n    virtual time_type delta(const time_type &e, const time_type &r,\n                            const time_type &t) override final\n    {\n        if (parent_type::x.empty() && r == 0.0) {\n            m_variable[m_id] += m_dx * m_sigma + m_mdx / 2. *\n                                m_sigma * m_sigma;\n            m_q = m_variable[m_id];\n            m_dx += m_mdx * m_sigma;\n            m_mq = m_dx;\n\n            if (m_mdx == 0)\n                m_sigma = Time::infinity();\n            else\n                m_sigma = std::sqrt(2. * m_dq / std::abs(m_mdx));\n        } else {\n            double a, b, c, s;\n            m_variable[m_id] += m_dx * e + m_mdx / 2. * e * e;\n            m_dx = m_dx + m_mdx * m_sigma;\n            var y = compute(e, t);\n            m_dx = y.v;\n            m_mdx = y.mv;\n            m_q = m_q + m_mq * e;\n            a = m_mdx / 2.;\n            b = m_dx - m_mq;\n            c = m_variable[m_id] - m_q + m_dq;\n            m_sigma = Time::infinity();\n\n            if (a == 0) {\n                if (b != 0) {\n                    s = -c / b;\n\n                    if (s > 0)\n                        m_sigma = s;\n\n                    c = m_variable[m_id] - m_q - m_dq;\n                    s = -c / b;\n\n                    if (s > 0 and s < m_sigma)\n                        m_sigma = s;\n                }\n            } else {\n                s = (-b + std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                if (s > 0)\n                    m_sigma = s;\n\n                s = (-b - std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                if (s > 0 and s < m_sigma)\n                    m_sigma = s;\n\n                c = m_variable[m_id] - m_q - m_dq;\n                s = (-b + std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                if (s > 0 and s < m_sigma)\n                    m_sigma = s;\n\n                s = (-b - std::sqrt(b * b - 4. * a * c)) / 2. / a;\n\n                if (s > 0 and s < m_sigma)\n                    m_sigma = s;\n            }\n        }\n\n        return m_sigma;\n    }\n\n    constexpr inline double value() const noexcept\n    {\n        return m_variable[m_id];\n    }\n\nprivate:\n    array_type m_variable;\n    array_type m_mv;\n    array_type m_c;\n    Function <Time, array_type> m_integrate_function;\n    double m_x;\n    double m_dx;\n    double m_mdx;\n    double m_q;\n    double m_mq;\n    double m_dq;\n    time_type m_sigma;\n    std::size_t m_id;\n\n    var compute(time_type e, time_type t)\n    {\n        for (auto i = 0ul; i < N; ++i)\n            m_variable[i] += m_mv[i] * e;\n\n        double fv = m_integrate_function(m_variable, t);\n        array_type vaux;\n\n        for (auto i = 0ul; i < N; ++i) {\n            if (not std::isnan(parent_type::x[i].v)) {\n                vaux[i] = m_variable[i];\n                m_variable[i] = parent_type::x[i].v;\n                m_mv[i] = parent_type::x[i].mv;\n            } else {\n                vaux[i] = nan();\n            }\n        }\n\n        var ret;\n        ret.v = m_integrate_function(m_variable, t);\n\n        for (auto i = 0ul; i < N; ++i) {\n            if (not std::isnan(vaux[i]) and vaux[i] != m_variable[i])\n                m_c[i] = (fv - ret.v) / (vaux[i] - m_variable[i]);\n        }\n\n        ret.mv = 0;\n\n        for (auto i = 0ul; i != N; ++i)\n            ret.mv += m_mv[i] * m_c[i];\n\n        return ret;\n    }\n};\n\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "d6da3e89b7406f3c0f3c8dce332cb3abb5e4ad2a", "size": 16029, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vle/dsde/qss2.hpp", "max_stars_repo_name": "vle-forge/Echll", "max_stars_repo_head_hexsha": "f3895dc721ec891b5828fcd17aec0d37be07fb60", "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": "vle/dsde/qss2.hpp", "max_issues_repo_name": "vle-forge/Echll", "max_issues_repo_head_hexsha": "f3895dc721ec891b5828fcd17aec0d37be07fb60", "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": "vle/dsde/qss2.hpp", "max_forks_repo_name": "vle-forge/Echll", "max_forks_repo_head_hexsha": "f3895dc721ec891b5828fcd17aec0d37be07fb60", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4, "max_line_length": 97, "alphanum_fraction": 0.511011292, "num_tokens": 4166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.05108273695705248, "lm_q1q2_score": 0.020423473606908125}}
{"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 \"optim/least_absolute_deviations.h\"\n\n#include <Eigen/SparseCholesky>\n\nnamespace colmap {\nnamespace {\n\nEigen::VectorXd Shrinkage(const Eigen::VectorXd& a, const double kappa) {\n  const Eigen::VectorXd a_plus_kappa = a.array() + kappa;\n  const Eigen::VectorXd a_minus_kappa = a.array() - kappa;\n  return a_plus_kappa.cwiseMin(0) + a_minus_kappa.cwiseMax(0);\n}\n\n}  // namespace\n\nbool SolveLeastAbsoluteDeviations(const LeastAbsoluteDeviationsOptions& options,\n                                  const Eigen::SparseMatrix<double>& A,\n                                  const Eigen::VectorXd& b,\n                                  Eigen::VectorXd* x) {\n  CHECK_NOTNULL(x);\n  CHECK_GT(options.rho, 0);\n  CHECK_GT(options.alpha, 0);\n  CHECK_GT(options.max_num_iterations, 0);\n  CHECK_GE(options.absolute_tolerance, 0);\n  CHECK_GE(options.relative_tolerance, 0);\n\n  Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> linear_solver;\n  linear_solver.compute(A.transpose() * A);\n\n  Eigen::VectorXd z = Eigen::VectorXd::Zero(A.rows());\n  Eigen::VectorXd z_old(A.rows());\n  Eigen::VectorXd u = Eigen::VectorXd::Zero(A.rows());\n\n  Eigen::VectorXd Ax(A.rows());\n  Eigen::VectorXd Ax_hat(A.rows());\n\n  const double b_norm = b.norm();\n  const double eps_pri_threshold =\n      std::sqrt(A.rows()) * options.absolute_tolerance;\n  const double eps_dual_threshold =\n      std::sqrt(A.cols()) * options.absolute_tolerance;\n\n  for (int i = 0; i < options.max_num_iterations; ++i) {\n    *x = linear_solver.solve(A.transpose() * (b + z - u));\n    if (linear_solver.info() != Eigen::Success) {\n      return false;\n    }\n\n    Ax = A * *x;\n    Ax_hat = options.alpha * Ax + (1 - options.alpha) * (z + b);\n\n    z_old = z;\n    z = Shrinkage(Ax_hat - b + u, 1 / options.rho);\n\n    u += Ax_hat - z - b;\n\n    const double r_norm = (Ax - z - b).norm();\n    const double s_norm = (-options.rho * A.transpose() * (z - z_old)).norm();\n    const double eps_pri =\n        eps_pri_threshold + options.relative_tolerance *\n                                std::max(b_norm, std::max(Ax.norm(), z.norm()));\n    const double eps_dual =\n        eps_dual_threshold +\n        options.relative_tolerance * (options.rho * A.transpose() * u).norm();\n\n    if (r_norm < eps_pri && s_norm < eps_dual) {\n      break;\n    }\n  }\n\n  return true;\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "0efff4d170476d8f765f14a67e73bcc1c1c97ed5", "size": 4013, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/optim/least_absolute_deviations.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/optim/least_absolute_deviations.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/optim/least_absolute_deviations.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": 37.858490566, "max_line_length": 80, "alphanum_fraction": 0.6797906803, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.041462277301108075, "lm_q1q2_score": 0.02040724096757104}}
{"text": "#include \"../config.h\"\n#ifdef __MATRIXWRAPPER_EIGEN__\n\n#include \"matrix_EIGEN.h\"\n#include \"vector_EIGEN.h\"\n\n#include <Eigen/LU>\n\nusing namespace std;\n\n// Passing the constructor arguments...\nMyMatrix::Matrix() : EigenMatrix() {}\nMyMatrix::Matrix(int num_rows, int num_cols) : EigenMatrix(num_rows,\n\t\t\t\t\t\t\t   num_cols){}\n\n// Destructor\nMyMatrix::~Matrix(){}\n\n// Copy constructor\nMyMatrix::Matrix(const MyMatrix& a) : EigenMatrix(a){}\n\n// ill-designed\nMyMatrix::Matrix(const EigenMatrix & a) : EigenMatrix(a){}\n\nMyMatrix::Matrix(int num_rows,const RowVector& v):EigenMatrix(num_rows,v.columns()){\n  EigenMatrix & m = *this;\n  const EigenRowVector & r = v;\n  for(unsigned int i=0;i<num_rows;i++)\n    m.row(i) = r;\n}\n\nMyRowVector MyMatrix::operator[](unsigned int i) const{\n  return this->rowCopy(i);\n}\n\n// Size/Capacity\nunsigned int MyMatrix::size() const { return this->rows();}\nunsigned int MyMatrix::capacity() const { return this->rows();}\n\n// Number of Rows/Cols\nunsigned int MyMatrix::rows() const { return ((const EigenMatrix *)this)->rows();}\nunsigned int MyMatrix::columns() const { return ((const EigenMatrix *)this)->cols();}\n\n// MATRIX - SCALAR operators\nMyMatrix& MyMatrix::operator+= (double a)\n{\n  EigenMatrix & op1 = *this;\n  op1 += EigenMatrix::Constant(op1.rows(), op1.cols(), a);\n  return (MyMatrix&)op1;\n}\n\nMyMatrix& MyMatrix::operator-= (double a)\n{\n  EigenMatrix & op1 = (*this);\n  op1 -= EigenMatrix::Constant(op1.rows(), op1.cols(), a);\n  return (MyMatrix&) op1;\n}\n\nMyMatrix& MyMatrix::operator*= (double a)\n{\n  EigenMatrix & op1 = (*this);\n  op1 *= a;\n  return *this;\n}\n\nMyMatrix& MyMatrix::operator/= (double a)\n{\n  EigenMatrix & op1 = (*this);\n  op1 /= a;\n  return (MyMatrix&) op1;\n}\n\nMyMatrix MyMatrix::operator+ (double a) const\n{\n  return (MyMatrix)(((EigenMatrix)(*this)) + EigenMatrix::Constant(rows(), cols(), a));\n}\n\nMyMatrix MyMatrix::operator- (double a) const\n{\n  return (MyMatrix)(((EigenMatrix)(*this)) - EigenMatrix::Constant(rows(), cols(), a));\n}\n\nMyMatrix MyMatrix::operator* (double a) const\n{\n  const EigenMatrix& op1 = (*this);\n  return (MyMatrix) (op1 *  a);\n}\n\nMyMatrix MyMatrix::operator/ (double a) const\n{\n  const EigenMatrix& op1 = (*this);\n  return (MyMatrix) (op1 /  a);\n}\n\nMyMatrix&\nMyMatrix::operator =(const MySymmetricMatrix& a)\n{\n  *this =(MyMatrix) a;\n\n  return *this;\n}\n\n// MATRIX - MATRIX Operators\nMyMatrix MyMatrix::operator- (const MyMatrix& a) const\n{\n  const EigenMatrix& op1 = *this;\n  const EigenMatrix& op2 = a;\n\n  return (MyMatrix)(op1 - op2);\n}\n\nMyMatrix MyMatrix::operator+ (const MyMatrix& a) const\n{\n  const EigenMatrix& op1 = *this;\n  const EigenMatrix& op2 = a;\n\n  return (MyMatrix)(op1 + op2);\n}\n\nMyMatrix MyMatrix::operator* (const MyMatrix& a) const\n{\n  const EigenMatrix& op1 = *this;\n  const EigenMatrix& op2 = a;\n\n  return (MyMatrix)(op1 * op2);\n}\n\nMyMatrix & MyMatrix::operator+= (const MyMatrix& a)\n{\n  EigenMatrix & op1 = (*this);\n  const EigenMatrix & op2 = a;\n  op1 += op2;\n  return (MyMatrix &) op1;\n}\n\nMyMatrix & MyMatrix::operator-= (const MyMatrix& a)\n{\n  EigenMatrix & op1 = (*this);\n  const EigenMatrix & op2 = a;\n  op1 -= op2;\n  return (MyMatrix &) op1;\n}\n\n\n// MATRIX - VECTOR Operators\nMyColumnVector MyMatrix::operator* (const MyColumnVector &b) const\n{\n  const EigenMatrix& op1 = (*this);\n  return (MyColumnVector) (op1 * ((const EigenColumnVector&)b));\n}\n\n\n\ndouble& MyMatrix::operator()(unsigned int a, unsigned int b)\n{\n  EigenMatrix & op1 = (*this);\n  return op1(a-1,b-1);\n}\n\ndouble MyMatrix::operator()(unsigned int a, unsigned int b) const\n{\n  const EigenMatrix & op1(*this);\n  return op1(a-1,b-1);\n}\n\nbool MyMatrix::operator==(const MyMatrix& a) const\n{\n  if (this->rows() != a.rows()) return false;\n  if (this->columns() != a.columns()) return false;\n  return(((EigenMatrix)(*this)-(EigenMatrix)a).isApproxToConstant(0.0));\n}\n\n\n// Set all elements equal to a\nMyMatrix&\n MyMatrix::operator=(double a)\n{\n  ((EigenMatrix&)(*this)).setConstant(a);\n  return *this;\n}\n\n\nMyRowVector MyMatrix::rowCopy(unsigned int r) const\n{\n  return (MyRowVector) (*this).row(r);\n}\n\nMyColumnVector MyMatrix::columnCopy(unsigned int c) const\n{\n  return (MyColumnVector) (*this).col(c);\n}\n\n\n\n\nMyMatrix MyMatrix::transpose() const\n{\n  const EigenMatrix &op1 = (*this);\n  return (MyMatrix) op1.transpose();\n}\n\ndouble MyMatrix::determinant() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  const EigenMatrix& A = (*this);\n  return A.determinant();\n}\n\n\nMyMatrix MyMatrix::inverse() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  const EigenMatrix& A = (*this);\n  return (MyMatrix) A.inverse();\n}\n\n\nint\nMyMatrix::convertToSymmetricMatrix(MySymmetricMatrix& sym)\n{\n  // test if matrix is square matrix\n  assert(this->rows() == this->columns());\n\n  const EigenMatrix & A = (EigenMatrix &) (*this);\n  sym = MySymmetricMatrix(A.selfadjointView<Eigen::Upper>());\n  return 0;\n}\n\nvoid\nMyMatrix::resize(unsigned int i, unsigned int j, bool copy, bool initialize)\n{\n  EigenMatrix & temp = (EigenMatrix &) (*this);\n  temp.resize(i,j);\n}\n\n// get sub matrix\nMyMatrix MyMatrix::sub(int i_start, int i_end, int j_start , int j_end) const\n{\n  const EigenMatrix & A = (EigenMatrix &) (*this);\n  MyMatrix submatrix(A.block(i_start-1,j_start-1,i_end-i_start+1,j_end-j_start+1));\n  return submatrix;\n}\n\n/////////////////////////////\n// CLASS SYMMETRIC MATRIX  //\n/////////////////////////////\n\nMySymmetricMatrix::SymmetricMatrix() : EigenSymmetricMatrix() {}\nMySymmetricMatrix::SymmetricMatrix(int n) : EigenSymmetricMatrix(n,n) {}\nMySymmetricMatrix::SymmetricMatrix(int num_rows,const RowVector& v):EigenSymmetricMatrix(num_rows,v.columns()){\n  EigenSymmetricMatrix & m = *this;\n  const EigenRowVector & r = v;\n  for(unsigned int i=0;i<num_rows;i++)\n    m.row(i) = r;\n}\n\nMyRowVector MySymmetricMatrix::operator[](unsigned int i) const{\n  return this->rowCopy(i);\n}\n\n\n\n// Copy constructor\nMySymmetricMatrix::SymmetricMatrix(const SymmetricMatrix& a) : EigenSymmetricMatrix(a){}\nMySymmetricMatrix::SymmetricMatrix(const EigenSymmetricMatrix& a) : EigenSymmetricMatrix(a){}\nMySymmetricMatrix::SymmetricMatrix(const EigenSymmetricView & a) : EigenSymmetricMatrix(a){}\n\n// Destructor\nMySymmetricMatrix::~SymmetricMatrix(){}\n\n// Size/Capacity\nunsigned int MySymmetricMatrix::size() const { return this->rows();}\nunsigned int MySymmetricMatrix::capacity() const { return this->rows();}\n\n// Ask Number of Rows and Columns\nunsigned int MySymmetricMatrix::rows() const { return ((const EigenSymmetricMatrix *)this)->rows();}\nunsigned int MySymmetricMatrix::columns() const { return ((const EigenSymmetricMatrix *)this)->cols();}\n\n\nMyRowVector MySymmetricMatrix::rowCopy(unsigned int r) const\n{\n  \n  unsigned int cols = columns();\n  EigenRowVector temp(cols);\n  for (unsigned int i=0; i<cols; i++)\n    temp(i) = (*this)(r,i+1);\n  return (MyRowVector) temp;\n}\n\nMySymmetricMatrix MySymmetricMatrix::transpose() const {return (*this);}\n\nMySymmetricMatrix MySymmetricMatrix::inverse() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  const EigenSymmetricMatrix& A = (*this);\n  // EigenSymmetricView A = ((const EigenSymmetricMatrix *)(this))->selfadjointView<Eigen::Upper>();\n  return MySymmetricMatrix(A.inverse());\n}\n\ndouble MySymmetricMatrix::determinant() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  const EigenSymmetricMatrix& A = (*this);\n  // EigenSymmetricView A = ((const EigenSymmetricMatrix *)(this))->selfadjointView<Eigen::Upper>();\n  return A.determinant();\n}\n\n\n// Set all elements equal to a\nMySymmetricMatrix& MySymmetricMatrix::operator=(const double a)\n{\n  ((EigenSymmetricMatrix&)(*this)).setConstant(a);\n  return *this;\n}\n\n\n// SYMMETRICMATRIX - SCALAR operators\nMySymmetricMatrix& MySymmetricMatrix::operator +=(double a)\n{\n  EigenSymmetricMatrix & op1 = *this;\n  op1 += EigenSymmetricMatrix::Constant(op1.rows(), op1.cols(), a);\n  return (MySymmetricMatrix&)op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator -=(double a)\n{\n  EigenSymmetricMatrix & op1 = *this;\n  op1 -= EigenSymmetricMatrix::Constant(op1.rows(), op1.cols(), a);\n  return (MySymmetricMatrix&)op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator *=(double b)\n{\n  EigenSymmetricMatrix & op1 = (*this);\n  op1 *= b;\n  return (MySymmetricMatrix&) op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator /=(double b)\n{\n  EigenSymmetricMatrix & op1 = (*this);\n  op1 /= b;\n  return (MySymmetricMatrix&) op1;\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator +(double a) const\n{\n  return (MySymmetricMatrix)(((EigenSymmetricMatrix)(*this)) + EigenSymmetricMatrix::Constant(rows(), cols(), a));\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator -(double a) const\n{\n  return (MySymmetricMatrix)(((EigenSymmetricMatrix)(*this)) - EigenSymmetricMatrix::Constant(rows(), cols(), a));\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator *(double b) const\n{\n const EigenSymmetricMatrix& op1 = (*this);\n  return (MySymmetricMatrix) (op1 *  b);\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator /(double b) const\n{\n  const EigenSymmetricMatrix& op1 = (*this);\n  return (MySymmetricMatrix) (op1 /  b);\n}\n\n\n\n\n// SYMMETRICMATRIX - MATRIX operators\nMyMatrix& MySymmetricMatrix::operator +=(const MyMatrix& a)\n{\n  EigenSymmetricMatrix & op1 = (*this);\n  op1 += a;\n  return (MyMatrix &) op1;\n}\n\nMyMatrix& MySymmetricMatrix::operator -=(const MyMatrix& a)\n{\n  EigenSymmetricMatrix & op1 = (*this);\n  op1 -= a;\n  return (MyMatrix &) op1;\n}\n\n\nMyMatrix MySymmetricMatrix::operator+ (const MyMatrix &a) const\n{\n  const EigenSymmetricMatrix& op1 = *this;\n  const EigenMatrix& op2 = a;\n\n  return (MyMatrix) (op1 + op2);\n}\n\nMyMatrix MySymmetricMatrix::operator- (const MyMatrix &a) const\n{\n  const EigenSymmetricMatrix& op1 = *this;\n  const EigenMatrix& op2 = a;\n\n  return (MyMatrix) (op1 - op2);\n}\n\nMyMatrix MySymmetricMatrix::operator* (const MyMatrix &a) const\n{\n  const EigenSymmetricMatrix& op1 = *this;\n  const EigenMatrix& op2 = a;\n\n  return (MyMatrix) (op1 * op2);\n}\n\n\n\n// SYMMETRICMATRIX - SYMMETRICMATRIX operators\nMySymmetricMatrix& MySymmetricMatrix::operator +=(const MySymmetricMatrix& a)\n{\n  EigenSymmetricMatrix & op1 = (*this);\n  const EigenSymmetricMatrix & op2 = a;\n  op1 += op2;\n  return (MySymmetricMatrix &) op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator -=(const MySymmetricMatrix& a)\n{\n  EigenSymmetricMatrix & op1 = (*this);\n  const EigenSymmetricMatrix & op2 = a;\n  op1 -= op2;\n  return (MySymmetricMatrix &) op1;\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator+ (const MySymmetricMatrix &a) const\n{\n  const EigenSymmetricMatrix& op1 = *this;\n  const EigenSymmetricMatrix& op2 = a;\n\n  return (MySymmetricMatrix) (op1 + op2);\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator- (const MySymmetricMatrix &a) const\n{\n  const EigenSymmetricMatrix& op1 = *this;\n  const EigenSymmetricMatrix& op2 = a;\n\n  return (MySymmetricMatrix) (op1 - op2);\n}\n\nMyMatrix MySymmetricMatrix::operator* (const MySymmetricMatrix &a) const\n{\n  const EigenSymmetricMatrix& op1 = *this;\n  const EigenSymmetricMatrix& op2 = a;\n\n  return (MyMatrix) (op1 * op2);\n}\n\n\n\n\nMyColumnVector MySymmetricMatrix::operator* (const MyColumnVector &b) const\n{\n  const EigenSymmetricMatrix& op1 = (EigenSymmetricMatrix) *this;\n  return (MyColumnVector) (op1 * ((const EigenColumnVector&)b));\n}\n\nvoid MySymmetricMatrix::multiply (const MyColumnVector &b, MyColumnVector &result) const\n{\n  const EigenSymmetricMatrix& op1 = (EigenSymmetricMatrix) *this;\n  result = (MyColumnVector) (op1 * ((const EigenColumnVector&)b));\n}\n\nMyMatrix MySymmetricMatrix::sub(int i_start, int i_end, int j_start , int j_end) const\n{\n  MyMatrix submatrix(i_end-i_start+1, j_end-j_start+1);\n  for (int i=i_start; i<=i_end; i++)\n    for (int j=j_start; j<=j_end; j++)\n      submatrix(i-i_start+1,j-j_start+1) = (*this)(i,j);\n\n  return submatrix;\n}\n\n\n\ndouble& MySymmetricMatrix::operator()(unsigned int a, unsigned int b)\n{\n  EigenSymmetricMatrix & op1 = (*this);\n  return op1(a-1,b-1);\n}\n\ndouble MySymmetricMatrix::operator()(unsigned int a, unsigned int b) const\n{\n  const EigenSymmetricMatrix & op1(*this);\n  return op1(a-1,b-1);\n}\n\nbool MySymmetricMatrix::operator==(const MySymmetricMatrix& a) const\n{\n  if (this->rows() != a.rows()) return false;\n  if (this->columns() != a.columns()) return false;\n  return(((EigenSymmetricMatrix)(*this)-(EigenSymmetricMatrix)a).isApproxToConstant(0.0));\n}\n\nvoid\nMySymmetricMatrix::resize(unsigned int i, bool copy, bool initialize)\n{\n  EigenSymmetricMatrix & temp = (EigenSymmetricMatrix &) (*this);\n  temp.resize(i,i);\n}\n\n\n#endif\n", "meta": {"hexsha": "533ca6fadb3f8f2c3b38eda96666392e2bec5dd1", "size": 12542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/wrappers/matrix/matrix_EIGEN.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/matrix/matrix_EIGEN.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/matrix/matrix_EIGEN.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": 24.4483430799, "max_line_length": 114, "alphanum_fraction": 0.6989315899, "num_tokens": 3587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04146227226724529, "lm_q1q2_score": 0.0204072384899635}}
{"text": "/*\n * Copyright (c) 2020-2021, Marco Sánchez Beeckman\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include <algorithm>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <opencv2/core.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/ml/ml.hpp>\n\n#include \"ImageUtils.h\"\n#include \"ConsensusVoter.h\"\n\n\nnamespace tfg {\n\nConsensusVoter::ConsensusVoter() {}\nConsensusVoter::ConsensusVoter(int estimateSpPerFrame, int numberOfFrames) {\n    const int estimatedTotalSuperpixels = estimateSpPerFrame * numberOfFrames;\n    this->superpixels.reserve(estimatedTotalSuperpixels);\n    this->votes.reserve(estimatedTotalSuperpixels);\n    this->saliencyScores.reserve(numberOfFrames);\n    this->frameBeginningIndex.reserve(numberOfFrames);\n}\nConsensusVoter::~ConsensusVoter() {}\n\n/**\n * Initialize motion saliency scores for each image, using precomputed optical flows.\n * The scores are stored in OpenCV's Mat objects, and are the same size as the read flows.\n * As such, the saliency scores need not be the same size as the original images, and are resized\n * to the correct values when initializing the votes. This is done this way in case the flows are computed\n * on scaled down images to diminish the execution time.\n * @param flowFile A .txt file containing the absolute path to each image's optical flow .tiff files.\n * @param minimumPercentageValidity Minimum percentage of frames with dominant motion that should exist for the computation to be considered successful.\n * @return True if the majority (at least minimumPercentageValidity) of frames have a dominant motion, false otherwise.\n */\nbool ConsensusVoter::initializeMotionSaliencyScores(std::ifstream &flowFile, float minimumPercentageValidity) {\n    this->saliencyScores.clear();\n    std::string line;\n\n    std::getline(flowFile, line);\n    const int NUMBER_OF_FRAMES = std::stoi(line); // The first line of the file tells the number of frames\n    this->saliencyScores.reserve(NUMBER_OF_FRAMES);\n    int framesWithDominantMotion = 0;\n\n    // Each frame has a certain number of optical flows attributed to it, typically both forward and backward\n    for(int f = 0; f < NUMBER_OF_FRAMES; f++) {\n        std::getline(flowFile, line);\n        const int NUMBER_OF_FLOWS = std::stoi(line); // The first line of a particular frame tells the number of flows\n\n        std::vector<cv::Mat> motionSaliencies;\n        // For each flow which the frame is the origin of, compute a motion saliency score\n        for(int i = 0; i < NUMBER_OF_FLOWS; i++) {\n            std::getline(flowFile, line);\n            cv::Mat flowu = cv::imread(line, cv::IMREAD_ANYDEPTH);\n\n            std::getline(flowFile, line);\n            cv::Mat flowv = cv::imread(line, cv::IMREAD_ANYDEPTH);\n\n            cv::Mat saliency;\n            // Call an auxiliary method to compute motion saliency scores from an optical flow\n            bool existsDominantMotion = computeMotionSaliency(flowu, flowv, saliency, 5, 1.0f, 0.55f, 10);\n            // If a dominant motion exists, store temporarily the corresponding saliencies\n            if(existsDominantMotion) {\n                std::cout << \" in flow \" << i << \" of frame \" << f << '\\n';\n                motionSaliencies.push_back(saliency);\n            }\n        }\n\n        // Extract the mean of the motion saliencies associated to the frame, and attribute it to it\n        cv::Mat frameScore = cv::Mat::zeros(1, 1, CV_32FC1);\n        if(motionSaliencies.size() > 0) {\n            elementwiseMean(motionSaliencies, frameScore);\n            framesWithDominantMotion += 1;\n        } else {\n            std::cout << \"No dominant motion in frame \" << f << \": saliency initialized to 0\" << '\\n';\n        }\n\n        this->saliencyScores.push_back(frameScore);\n    }\n\n\n    // The saliency score must be a number between 0 and 1, so dividing by the maximum value of the sequence (not per frame) is\n    // the most straightforward way to normalize the sequence of images.\n    normalizeByMaxOfSequence(this->saliencyScores);\n    \n    // If not enough frames have a dominant motion, consider the process a failure\n    // In that case, visual saliency is the way to go\n    return (framesWithDominantMotion > NUMBER_OF_FRAMES * minimumPercentageValidity);\n}\n\n/**\n * Compute motion saliency from two floating point matrices of optical flows (horizontal and vertical).\n * This method looks for two different kinds of motion: first, it tries to tell if the frame is static by comparing the median of the magnitude of the \n * flow and comparing to a low value; then, if the frame is not static, it searches for a dominant translational motion by computing a histogram of the phases\n * of the flow, and looking at the height of the largest bin.\n * The saliency is defined as the square of the deviation of the pixel value (magnitude of the flow in the static case, angle in the translational case) from the\n * dominant value (0 in the static case, the class mark of the largest bin in the translational case).\n * @param flowu A floating point matrix containing the horizontal optical flow.\n * @param flowv A floating point matrix containing the vertical optical flow.\n * @param saliency Output matrix containing the saliency scores for each pixel.\n * @param patchSize The patch size to smooth the saliencies.\n * @param staticTh The threshold value to compare with the median of the flow magnitude to tell if a frame is static or not.\n * @param transTh The threshold percentage to compare with the height of the largest bin to tell if a frame has a dominant translational motion.\n * @param orientationBins The number of bins for the histogram of flow angles.\n * @return True if the flow has either static or translational dominant motion, false otherwise.\n */\nbool ConsensusVoter::computeMotionSaliency(const cv::Mat &flowu, const cv::Mat &flowv, cv::Mat &saliency, int patchSize, float staticTh, float transTh, int orientationBins) {\n\n    // Compute the magnitude of the flow\n    cv::Mat magnitude;\n    cv::magnitude(flowu, flowv, magnitude);\n    std::vector<float> magnitudeData;\n    magnitude.reshape(0, 1).row(0).copyTo(magnitudeData);\n\n    // Compute the median of the magnitude of the flow\n    std::nth_element(magnitudeData.begin(), magnitudeData.begin() + magnitudeData.size()/2, magnitudeData.end());\n    float median;\n    if(magnitudeData.size()%2 == 1) {\n        median = magnitudeData[magnitudeData.size()/2];\n    } else {\n        auto it = std::max_element(magnitudeData.begin(), magnitudeData.begin() + magnitudeData.size()/2);\n        median = (*it + magnitudeData[magnitudeData.size()/2])/2.0f;\n    }\n\n    // If the median is low enough, the background is static\n    // In that case, the saliency score is the square of each pixel's magnitude\n    if(median < staticTh) {\n        std::cout << \"Static motion\";\n        cv::Mat magnitudeDeviation = magnitude.mul(magnitude);\n        cv::Mat kernel = cv::Mat::ones(patchSize, patchSize, CV_32FC1) / (patchSize * patchSize);\n        cv::filter2D(magnitudeDeviation, saliency, -1, kernel);\n        return true;\n    }\n\n    // Reaching here means that the background is not static, so check for a dominant translational motion\n    // To do so, compute an histogram of the orientations, and check if one bin has more than transTh*100% of the entries\n    cv::Mat orientation;\n    cv::phase(flowu, flowv, orientation);\n    int onlyChannel[] = {0};\n    int histSize[] = {orientationBins};\n    float orientationRange[] = {0, 2*CV_PI};\n    const float* ranges[] = {orientationRange};\n    cv::Mat orientationHistogram;\n\n    cv::calcHist(&orientation, 1, onlyChannel, cv::Mat(), orientationHistogram, 1, histSize, ranges);\n    cv::Scalar sumHist = cv::sum(orientationHistogram);\n    orientationHistogram /= sumHist(0) + (sumHist(0) == 0);\n\n    double minVal, maxVal;\n    int minPos[2], maxPos[2];\n    cv::minMaxIdx(orientationHistogram, &minVal, &maxVal, &minPos[0], &maxPos[0]);\n\n    // If the percentage of the largest bin is greater than a threshhold, we consider that the frame has dominant translational motion\n    if(maxVal > transTh) {\n        std::cout << \"Translational motion\";\n        // Compute the deviation of the angles with respect to the class mark of the bin with the hightest value\n        // Since an angle does not change by adding or substracting 2pi to it, the desired deviation is the elementwise minimum of\n        // the deviations adding -2pi, 0, and 2pi.\n        float classMark = (2*maxPos[0] + 1)*2*CV_PI / (2 * orientationBins);\n        cv::Mat angleDeviation = (orientation - classMark).mul(orientation - classMark);\n        cv::min(angleDeviation, (orientation - classMark + 2 * CV_PI).mul(orientation - classMark + 2 * CV_PI), angleDeviation);\n        cv::min(angleDeviation, (orientation - classMark - 2 * CV_PI).mul(orientation - classMark - 2 * CV_PI), angleDeviation);\n\n        cv::Mat kernel = cv::Mat::ones(patchSize, patchSize, CV_32FC1) / (patchSize * patchSize);\n        cv::filter2D(angleDeviation, saliency, -1, kernel);\n        return true;\n    }\n\n    return false;\n}\n\n/**\n * Compute the elementwise mean of a vector of matrices.\n * @param src A collection of OpenCV matrices.\n * @param dst An output matrix where each element contains the mean of the values in that position.\n */\nvoid ConsensusVoter::elementwiseMean(const std::vector<cv::Mat> &src, cv::Mat &dst) {\n    dst.release();\n\n    const unsigned int VECTOR_SIZE = src.size();\n    dst = cv::Mat::zeros(src[0].size(), CV_32FC1);\n    for(unsigned int i = 0; i < VECTOR_SIZE; i++) {\n        dst += src[i];\n    }\n    dst /= VECTOR_SIZE;\n}\n\n/**\n * Normalize a sequence of matrices so all the elements take values in the range [0, 1]\n * by dividing all the entries by the maximum of the whole sequence.\n * @param sequence A sequence of matrices.\n */\nvoid ConsensusVoter::normalizeByMaxOfSequence(std::vector<cv::Mat> &sequence) {\n    float max = 0;\n    for(unsigned int i = 0; i < sequence.size(); i++) {\n        double minVal, maxVal;\n        cv::minMaxIdx(sequence[i], &minVal, &maxVal);\n        max = maxVal > max ? maxVal : max;\n    }\n\n    if(max == 0) return;\n\n    for(unsigned int i = 0; i < sequence.size(); i++) {\n        sequence[i] = sequence[i] / max;\n    }\n}\n\n/**\n * Save saliency scores to a sequence of grayscale images.\n * @param folder The folder where the new files will be stored.\n * @param fileName A prefix for the name of the new files.\n */\nvoid ConsensusVoter::saveSaliencies(const std::string &folder, const std::string &fileName) {\n\n    for(unsigned int f = 0; f < this->saliencyScores.size(); f++) {\n        cv::Mat imageToBeSaved;\n        this->saliencyScores[f].convertTo(imageToBeSaved, CV_8UC1, 255);\n        std::stringstream ss;\n        ss << folder << fileName << f << \".jpg\";\n        std::string saveAs = ss.str();\n        cv::imwrite(saveAs, imageToBeSaved);\n    }\n}\n\nvoid ConsensusVoter::mergeSaliencyWithImages(const std::vector<cv::Mat> &images, std::vector<cv::Mat> &mergedImages) {\n    mergedImages.clear();\n    mergedImages.resize(images.size());\n    for(unsigned int f = 0; f < images.size(); f++) {\n        cv::Mat imageLab;\n        cv::cvtColor(images[f], imageLab, cv::COLOR_BGR2Lab);\n        std::vector<cv::Mat> imageChannels;\n        cv::split(imageLab, imageChannels);\n\n        cv::Mat saliencyOfFrame;\n        cv::resize(this->saliencyScores[f], saliencyOfFrame, images[f].size());\n        cv::Mat fourthChannel;\n        saliencyOfFrame.convertTo(fourthChannel, CV_8UC1, 255.0, 0.0);\n        imageChannels.push_back(fourthChannel);\n\n        cv::merge(imageChannels, mergedImages[f]);\n    }\n}\n\n/**\n * Add a group of regions belonging to a single frame to the list of superpixels.\n * @param spInFrame A vector of Region objects containing information of superpixels in a frame.\n */\nvoid ConsensusVoter::addRegionsByFrame(std::vector<tfg::Region> &spInFrame) {\n    const int nextFrameIndex = this->frameBeginningIndex.size() == 0 ? 0 : this->frameBeginningIndex.back() + spInFrame.size();\n    this->frameBeginningIndex.push_back(nextFrameIndex);\n    std::move(spInFrame.begin(), spInFrame.end(), std::back_inserter(this->superpixels));\n}\n\n/**\n * Initialize votes from previously computed saliency scores, by attributing to each region the mean of the scores\n * of the pixels contained inside it.\n * This is done per-frame, and the saliency matrix of the frame is resized to be the same as the image in case the flows\n * were computed on a shrunken image. If the sizes do not match, a bilineal interpolation is performed on the saliencies.\n */\nvoid ConsensusVoter::initializeVotesInFrame(int frame, const cv::Mat &pixelLabels, int numberOfSuperpixels) {\n    cv::Mat saliencyOfFrame;\n    cv::resize(this->saliencyScores[frame], saliencyOfFrame, pixelLabels.size());\n\n    for(int i = 0; i < numberOfSuperpixels; i++) {\n        cv::Mat superpixelMask(pixelLabels == i);\n        cv::Scalar regionMeanVote = cv::mean(saliencyOfFrame, superpixelMask);\n        const float vote = regionMeanVote(0);\n        this->votes.push_back(vote);\n    }\n}\n\n/**\n * Compute a random walk transition matrix. This is a sparse matrix that stores costs\n * between neighbouring regions, and is multiplied by a vector of region votes for them to\n * \"reach consensus\" (update the region votes with a weighted average of their neighbours').\n * The neighbours are computed using a KDTree-search, and a cost is attributed between two neighbours\n * based on the distance between their region descriptors.\n * @param F The number of surrounding frames forwards and backwards to search for nearest neighbours.\n * @param L A multiplier that indicates the number of possible good matches per frame to find nearest neighbours.\n * @param sigma2 The variance of the exponential variable, higher is less restrictive.\n */\nvoid ConsensusVoter::computeTransitionMatrix(int F, int L, float sigma2) {\n    computeDescriptors();\n\n    const int NUMBER_OF_REGIONS = static_cast<int>(this->superpixels.size());\n    const int NUMBER_OF_FRAMES = static_cast<int>(this->frameBeginningIndex.size());\n    const int M = L*(2*F + 1);\n    Eigen::SparseMatrix<float, Eigen::RowMajor> transM(NUMBER_OF_REGIONS, NUMBER_OF_REGIONS);\n    std::vector<Eigen::Triplet<float>> transMEntries;\n    transMEntries.reserve(M * NUMBER_OF_REGIONS);\n    transMEntries.reserve(L*(2*F + 1) * NUMBER_OF_REGIONS);\n\n    for(int f = 0; f < NUMBER_OF_FRAMES; f++) {\n        // Extract the submatrix corresponding to the descriptors of the regions in the current frame\n        cv::Rect currentFrameDelimiter;\n        currentFrameDelimiter.y = this->frameBeginningIndex[f];\n        currentFrameDelimiter.height = (f == (NUMBER_OF_FRAMES - 1)) ? (NUMBER_OF_REGIONS - this->frameBeginningIndex[f]) : (this->frameBeginningIndex[f + 1] - this->frameBeginningIndex[f]);\n        currentFrameDelimiter.x = 0;\n        currentFrameDelimiter.width = this->descriptors.cols;\n        cv::Mat descriptorsInFrame(this->descriptors, currentFrameDelimiter);\n\n        std::cout << \"Extracted descriptors of superpixels in frame \" << f << '\\n';\n\n        // Extract the submatrix corresponding to the descriptors of all the regions in the neighbouring frames\n        cv::Rect searchWindow;\n        const int yMinWindow = ((f - F) < 0) ? 0 : (f - F);\n        const int yMaxWindow = ((f + F) > (NUMBER_OF_FRAMES - 1)) ? (NUMBER_OF_FRAMES - 1) : (f + F);\n        searchWindow.y = this->frameBeginningIndex[yMinWindow];\n        searchWindow.height = (yMaxWindow == (NUMBER_OF_FRAMES - 1)) ? (NUMBER_OF_REGIONS - this->frameBeginningIndex[yMinWindow]) : (this->frameBeginningIndex[yMaxWindow + 1] - this->frameBeginningIndex[yMinWindow]);\n        searchWindow.x = 0;\n        searchWindow.width = this->descriptors.cols;\n        cv::Mat descriptorsInNeighbouringFrames(this->descriptors, searchWindow);\n\n        std::cout << \"Extracted descriptors of neighbours of frame \" << f << '\\n';\n\n        // Keep track of the position of every neighbouring region\n        // Put them in a Mat object so the KDTree returns the indices of the nearest neighbours\n        std::vector<float> neighbourIndices(searchWindow.height);\n        std::iota(neighbourIndices.begin(), neighbourIndices.end(), searchWindow.y);\n        std::cout << \"Frame \" << f << \" iota: from \" << neighbourIndices[0] << \" to \" << neighbourIndices.back() << '\\n';\n        cv::Mat regionIndices(neighbourIndices.size(), 1, CV_32FC1, neighbourIndices.data());\n\n        std::cout << \"Created matrix with neighbour indices\" << '\\n';\n\n        // Create a KDTree and train it using the descriptors in the neighbouring frames\n        // Each sample belongs to a column, and its response is the index of the region\n        cv::Ptr<cv::ml::KNearest> tree = cv::ml::KNearest::create();\n        tree->train(descriptorsInNeighbouringFrames, cv::ml::ROW_SAMPLE, regionIndices);\n\n        std::cout << \"Created and trained KDTree \" << f << '\\n';\n\n        // Search for the nearest M neighbours inside of the samples.\n        // Since there can be more than one good match per frame, we search up to L regions per frame\n        // for a total of M = L*(2*F + 1) nearest neighbours\n        // const int M = L*(yMaxWindow - yMinWindow + 1);\n        cv::Mat NNIndices;\n        cv::Mat result; // unused for our purposes, but required for the function findNearest\n        cv::Mat NNDistances2;\n        tree->findNearest(descriptorsInFrame, M, result, NNIndices, NNDistances2);\n\n        std::cout << \"Found nearest neighbours of superpixels in frame \" << f << '\\n' << '\\n';\n\n        // Knowing who the nearest neighbours are and the distance to them, define a weight based on\n        // the distance, and create a random walk transition matrix (which is sparse)\n        for(int y = 0; y < currentFrameDelimiter.height; y++) {\n            const int ownIndex = currentFrameDelimiter.y + y;\n            for(int x = 0; x < M; x++) {\n                const int neighbourIndex = static_cast<int>(NNIndices.at<float>(y, x));\n                float weight = 1.0f;\n                if(ownIndex != neighbourIndex) {\n                    const float neighbourDistance2 = NNDistances2.at<float>(y, x);\n                    weight = std::exp(-neighbourDistance2 / sigma2);\n                }\n                transMEntries.push_back(Eigen::Triplet<float>(ownIndex, neighbourIndex, weight));\n            }\n        }\n    }\n    transM.setFromTriplets(transMEntries.begin(), transMEntries.end());\n\n    std::cout << \"Created sparse transition matrix\" << '\\n';\n\n    // Upon computing the transition matrix, normalize it by dividing each row by the sum of its elements\n    Eigen::SparseMatrix<float, Eigen::RowMajor> normalizationMatrix(NUMBER_OF_REGIONS, NUMBER_OF_REGIONS);\n    std::vector<Eigen::Triplet<float>> normalizationMatrixEntries;\n    normalizationMatrixEntries.reserve(NUMBER_OF_REGIONS);\n    for(int k = 0; k < transM.outerSize(); ++k) {\n        float degree = 0.0f;\n        for(Eigen::SparseMatrix<float, Eigen::RowMajor>::InnerIterator it(transM, k); it; ++it) {\n            degree += it.value();\n        }\n        normalizationMatrixEntries.push_back(Eigen::Triplet<float>(k, k, 1 / degree));\n    }\n    normalizationMatrix.setFromTriplets(normalizationMatrixEntries.begin(), normalizationMatrixEntries.end());\n\n    std::cout << \"Created normalization matrix\" << '\\n';\n\n    // TODO: measure efficiency difference between computing normalization matrix and multiplying transM by it (as it is now),\n    // and looping through transM a second time and directly modifying the value through it.valueRef()\n    this->transitionMatrix = normalizationMatrix * transM;\n\n}\n\n/**\n * Get matrix of descriptors. This basically concatenates the already computed descriptors of each region into a single matrix to be used for\n * the nearest neighbour search.\n */\nvoid ConsensusVoter::computeDescriptors() {\n    this->descriptors.release();\n\n    std::vector<cv::Mat> descriptorsVector;\n    descriptorsVector.reserve(this->superpixels.size());\n    for(unsigned int r = 0; r < this->superpixels.size(); r++) {\n        // cv::Mat singleRegionDescriptor = this->superpixels[r].getDescriptor();\n        cv::Mat singleRegionDescriptor = this->superpixels[r].getDescriptor();\n        descriptorsVector.push_back(singleRegionDescriptor);\n    }\n    cv::vconcat(descriptorsVector, this->descriptors);\n}\n\n/**\n * Update the votes by multiplying them by the transition matrix.\n * @param iterations The number of times the votes are to be multiplied by the matrix.\n */\nvoid ConsensusVoter::reachConsensus(int iterations) {\n    const int NUMBER_OF_FRAMES = static_cast<int>(this->frameBeginningIndex.size());\n    const int NUMBER_OF_VOTES = static_cast<int>(this->votes.size());\n\n    Eigen::Map<Eigen::VectorXf> updatedVotes(this->votes.data(), NUMBER_OF_VOTES);\n\n    for(int t = 0; t < iterations; t++) {\n        updatedVotes = transitionMatrix * updatedVotes;\n\n        for(int f = 0; f < NUMBER_OF_FRAMES; f++) {\n            const int superpixelsInFrame = (f == (NUMBER_OF_FRAMES - 1)) ? (NUMBER_OF_VOTES - frameBeginningIndex[f]) : (frameBeginningIndex[f + 1] - frameBeginningIndex[f]);\n            const float maxVoteInFrame = updatedVotes.segment(frameBeginningIndex[f], superpixelsInFrame).maxCoeff();\n            updatedVotes.segment(frameBeginningIndex[f], superpixelsInFrame) /= maxVoteInFrame + (maxVoteInFrame <= 0);\n        }\n    }\n}\n\n/**\n * Threshold the existing votes and get a sequence of masks from them.\n * @param masks The output vector of masks.\n * @param threshold The threshold value.\n * @param smallBlobsThreshold Relative size to the biggest object below which small non-connected blobs should be removed.\n */\nvoid ConsensusVoter::getSegmentation(std::vector<cv::Mat> &masks, float threshold, float smallBlobsThreshold) {\n    const int NUMBER_OF_FRAMES = static_cast<int>(this->frameBeginningIndex.size());\n    const int NUMBER_OF_REGIONS = static_cast<int>(this->superpixels.size());\n    masks.clear();\n    masks.reserve(NUMBER_OF_FRAMES);\n    for(int f = 0; f < NUMBER_OF_FRAMES; f++) {\n        const int spBegin = this->frameBeginningIndex[f];\n        const int spEnd = (f == (NUMBER_OF_FRAMES - 1)) ? (NUMBER_OF_REGIONS - 1) : (this->frameBeginningIndex[f + 1] - 1);\n        // cv::Mat framePixelLabels = this->superpixels[spBegin].getFrameLabels();\n        cv::Mat framePixelLabels = this->superpixels[spBegin].getFrameLabels();\n\n        // Set the values of the mask (before thresholding) by superpixel: each pixel of a superpixel is attributed the same\n        // value as the vote for the region\n        cv::Mat maskNotThresholded(framePixelLabels.size(), CV_32FC1);\n        for(int sp = spBegin; sp <= spEnd; sp++) {\n            const int spLabelInFrame = sp - spBegin;\n            cv::Mat spLocation(framePixelLabels == spLabelInFrame);\n            maskNotThresholded.setTo(this->votes[sp], spLocation);\n        }\n\n        // The segmented images tend to have small non-connected blobs that are similar in color to the foreground,\n        // but that are really background. This function eliminates the blobs that are much smaller than the biggest object\n        // (that is assumed to be the real foreground)\n        correctVotesForSmallBlobs(maskNotThresholded, spBegin, spEnd, framePixelLabels, threshold, smallBlobsThreshold);\n        cv::Mat mask(maskNotThresholded > threshold);\n        masks.push_back(mask);\n    }\n}\n\n/**\n * Eliminate connected components of a mask whose size with respect to the biggest connected component is much smaller.\n * Then, correct the votes for the involved superpixels by setting them below the threshold.\n * @param matrix A non-thresholded mask whose pixels contain values between 0 and 1.\n * @param spBegin The index of the first superpixel of the frame the matrix corresponds to.\n * @param spEnd The index of the last superpixel of the frame the matrix corresponds to.\n * @param regionLabels A labeling of the image that separates the different superpixels in the frame.\n * @param threshold A threshold to separate background from foreground.\n * @param relativeSize The minimum relative size the blobs should at least have with respect to the biggest object in order no to be removed.\n */\nvoid ConsensusVoter::correctVotesForSmallBlobs(cv::Mat &matrix, int spBegin, int spEnd, const cv::Mat &regionLabels, float threshold, float relativeSize) {\n    tfg::removeSmallBlobs(matrix, threshold, relativeSize);\n\n    // Correct values in votes vector\n    for(int s = spBegin; s <= spEnd; s++) {\n        const int superpixelLabel = s - spBegin;\n        cv::Mat region(regionLabels == superpixelLabel);\n        cv::Scalar regionMean = cv::mean(matrix, region);\n        const float correctedVote = regionMean(0);\n        this->votes[s] = correctedVote;\n    }\n}\n    \n} // namespace tfg", "meta": {"hexsha": "317f8d08dc0982523d0a3c9ea96eb58b7e858df3", "size": 24909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nlcv/ConsensusVoter.cpp", "max_stars_repo_name": "msanchez-beeckman/tfg-video-segmentation", "max_stars_repo_head_hexsha": "b0a85df6d7a428abe21c5b6ed131cb047fecd1f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T10:29:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T10:29:22.000Z", "max_issues_repo_path": "src/nlcv/ConsensusVoter.cpp", "max_issues_repo_name": "msanchez-beeckman/tfg-video-segmentation", "max_issues_repo_head_hexsha": "b0a85df6d7a428abe21c5b6ed131cb047fecd1f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nlcv/ConsensusVoter.cpp", "max_forks_repo_name": "msanchez-beeckman/tfg-video-segmentation", "max_forks_repo_head_hexsha": "b0a85df6d7a428abe21c5b6ed131cb047fecd1f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7311608961, "max_line_length": 217, "alphanum_fraction": 0.6940864748, "num_tokens": 6041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.04208772716466829, "lm_q1q2_score": 0.020386456831048748}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_ELT_MULTIPLY_HPP\n#define STAN_MATH_PRIM_MAT_FUN_ELT_MULTIPLY_HPP\n\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/err/check_matching_dims.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the elementwise multiplication of the specified\n * matrices.\n *\n * @tparam T1 Type of scalars in first matrix.\n * @tparam T2 Type of scalars in second matrix.\n * @tparam R Row type of both matrices.\n * @tparam C Column type of both matrices.\n * @param m1 First matrix\n * @param m2 Second matrix\n * @return Elementwise product of matrices.\n */\ntemplate <typename T1, typename T2, int R, int C>\nEigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, R, C>\nelt_multiply(const Eigen::Matrix<T1, R, C>& m1,\n             const Eigen::Matrix<T2, R, C>& m2) {\n  check_matching_dims(\"elt_multiply\", \"m1\", m1, \"m2\", m2);\n  Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, R, C>\n      result(m1.rows(), m2.cols());\n  for (int i = 0; i < m1.size(); ++i)\n    result(i) = m1(i) * m2(i);\n  return result;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "04c6db77fc3b63918ab9daca296441cf76027033", "size": 1171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/mat/fun/elt_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/prim/mat/fun/elt_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/prim/mat/fun/elt_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": 30.8157894737, "max_line_length": 78, "alphanum_fraction": 0.6959863365, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.042087725963147436, "lm_q1q2_score": 0.02038645624905598}}
{"text": "#include <math.h>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <random>\n#include <sstream>\n#include <fftw3.h>\n#include \"parameters.hpp\"\n#include \"utilities.hpp\"\n#include <boost/filesystem.hpp>\n#include \"equations.hpp\"\n\n\n//--------------------------------\n// Directory & File Management\n//--------------------------------\n\nnamespace fs = boost::filesystem;\n\nvoid dir_manage(const std::string exist_dir, const std::string new_dir )\n{\n    \n    //Path of the existing data directory\n    const fs::path existpath(\"../\" + exist_dir );\n    \n    //Tries to remove all files in there. If it fails, it throws an error.\n    try {\n        fs::remove_all(existpath);\n    }\n    catch (fs::filesystem_error& ex) {\n        std::cout << ex.what() << std::endl;\n        throw;\n    }\n    \n    //Path of the newly set directory\n    const fs::path newpath(\"../\" + new_dir );\n    \n    //Tries to create a directory. If it fails, it throws an error.\n    boost::system::error_code error;\n    const bool result = fs::create_directory(newpath, error);\n    if (!result || error) {\n        std::cout << \"failed to create directory\" << std::endl;\n    }\n    \n}\n\nvoid file_manage(const std::string exist_file)\n{\n    //Path of the existing status file\n    const fs::path statuspath(\"../\" + exist_file);\n    \n    //Tries to remove the file. If it fails, it throws an error.\n    try {\n        fs::remove(statuspath);\n    }\n    catch (fs::filesystem_error& ex) {\n        std::cout << ex.what() << std::endl;\n        throw;\n    }\n    \n}\n\n//--------------------------------\n// Double Inflation Subroutines\n//--------------------------------\n\n//subroutine for zeromode output\nvoid zeromode_output(const std::string file, Vec_I_DP &xx, Mat_I_DP &yp, int timecount){\n    static int output_timecount = 0; ++output_timecount;\n    std::stringstream ss;\n    std::ofstream zeromode_output;\n    ss << \"../\" << file;\n    \n    if( output_timecount == 1 )\n    {\n        zeromode_output.open(ss.str().c_str(),std::ios::out);\n    }else{\n        zeromode_output.open(ss.str().c_str(),std::ios::app);\n    }\n    \n    DP H,la,rho,rhop,w,a;\n    Vec_DP tr(N_zero);\n    int i,j;\n    \n    for (j=0;j<timecount;j++) {\n    for (i=0;i<N_zero;i++) tr[i]=yp[i][j];\n    la=xx[j];\n    rho=rho_tot(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n    rhop=rhoandp(tr[3],tr[4],tr[5],tr[6]);\n    H=Fri(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n    w=log10(H);\n    a=exp(la);\n    //output data\n    zeromode_output << std::setw(6) << (la-Ini)*msigma/H << \" \" //t\n    << std::setw(10) << la << \" \" //log(a)\n    << std::setw(10) << tr[0] << \" \"  //buffer for yp_p[i][0] sigma\n    << std::setw(20) << std::setprecision(20) << tr[1] << \" \" //buffer for yp_p[i][1] psi\n    << std::setw(10) << tr[2] << \" \" //buffer for yp_p[i][1] phi\n    << std::setw(10) << w << \" \"     //log10(H)\n    << std::setw(10) << rho << \" \"\n    << std::setw(10) << V_11(tr[0],tr[1],tr[2]) << \" \"\n    << std::setw(10) << V_12(tr[0],tr[1],tr[2]) << \" \"\n    << std::setw(10) << V_13(tr[0],tr[1],tr[2]) << \" \"\n    << std::setw(10) << V_22(tr[0],tr[1],tr[2]) << \" \"\n    << std::setw(10) << V_23(tr[0],tr[1],tr[2]) << \" \"\n    << std::setw(10) << V_33(tr[0],tr[1],tr[2]) << \" \";\n        for(int loop = 0; loop < knum_zero.size(); loop++ ){\n            if(loop ==  knum_zero.size()-1){\n    zeromode_output << std::setw(10) << log10(UC::knum_to_kMPl(knum_zero[loop])/(a*H)) << \"\\n\";\n            }else{\n                zeromode_output << std::setw(10) << log10(UC::knum_to_kMPl(knum_zero[loop])/(a*H)) << \" \";\n            };\n        };\n        \n    };\n}\n\n//subroutine for k-analyze output\nvoid kanalyze_output(const std::string dir, std::string file, Vec_I_DP &xx, Mat_I_DP &yp, int timecount, int knum, const DP k_comoving ){\n    //output results\n    static int output_timecount = 0;\n    static int knum_static = knum;\n    if(knum_static == knum){\n        ++output_timecount;\n    }else{\n        knum_static = knum;\n        output_timecount = 1;\n    };\n    \n//    std::cout << knum_static << \"\\n\";\n//    std::cout << knum << \"\\n\";\n//    std::cout << output_timecount << \"\\n\";\n    \n    std::stringstream ss;\n    std::ofstream k_output;\n    \n    ss << \"../\" << dir << \"/\" << file << \"_\" << std::setw(4) << std::setfill('0') << knum <<\".txt\";\n    \n    if( output_timecount == 1 )\n    {\n        k_output.open(ss.str().c_str(),std::ios::out);\n    }else{\n        k_output.open(ss.str().c_str(),std::ios::app);\n    }\n    \n    DP H,la,rho,rhop,w,a,Pzeta,Pzeta_raw,PPot,P_sigma,P_psi,P_phi;\n\n    Vec_DP zeta(6);\n    Vec_DP tr(N_pert);\n    int i,j;\n    for (j=0;j<timecount;j++) {\n        for (i=0;i<N_pert;i++) tr[i]=yp[i][j];\n        la=xx[j];\n//        if(j==0){std::cout << la << \"\\n\"; };\n        rho=rho_tot(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n        rhop=rhoandp(tr[3],tr[4],tr[5],tr[6]);\n        H=Fri(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n        w=log10(H);\n        a=exp(la);\n        for (i=0;i<3;i++) zeta[i]=2*rho*(tr[i+25] + tr[i+28]/H)/(rhop) + (1 + 2*k_comoving*k_comoving*rho/(9*a*a*H*H*rhop))*3*tr[i+25];\n        for (i=0;i<3;i++) zeta[i+3]=2*rho*(tr[i+49] + tr[i+52]/H)/(rhop) + (1 + 2*k_comoving*k_comoving*rho/(9*a*a*H*H*rhop))*3*tr[i+49];\n        \n        Pzeta=0;\n        for (i=0;i<6;i++) Pzeta = Pzeta + zeta[i]*zeta[i];\n        Pzeta_raw = Pzeta;\n        Pzeta = Pzeta/(2*M_PI*M_PI*9);\n        Pzeta = log10(Pzeta) + 3*log10(k_comoving);\n        \n        PPot = 0;\n        for (i=0;i<3;i++) PPot = PPot + tr[i+25]*tr[i+25];\n        for (i=0;i<3;i++) PPot = PPot + tr[i+49]*tr[i+49];\n        PPot = PPot/(2*M_PI*M_PI);\n        PPot = log10(PPot) + 3*log10(k_comoving);\n        \n        P_sigma = 0;\n        for (i=0;i<3;i++) P_sigma = P_sigma + tr[i+7]*tr[i+7];\n        for (i=0;i<3;i++) P_sigma = P_sigma + tr[i+31]*tr[i+31];\n        P_sigma = P_sigma/(2*M_PI*M_PI);\n        P_sigma = log10(P_sigma) + 3*log10(k_comoving);\n        \n        P_psi = 0;\n        for (i=0;i<3;i++) P_psi = P_psi + tr[i+10]*tr[i+10];\n        for (i=0;i<3;i++) P_psi = P_psi + tr[i+34]*tr[i+34];\n        P_psi = P_psi/(2*M_PI*M_PI);\n        P_psi = log10(P_psi) + 3*log10(k_comoving);\n        \n        P_phi = 0;\n        for (i=0;i<3;i++) P_phi = P_phi + tr[i+13]*tr[i+13];\n        for (i=0;i<3;i++) P_phi = P_phi + tr[i+37]*tr[i+37];\n        P_phi = P_phi/(2*M_PI*M_PI);\n        P_phi = log10(P_phi) + 3*log10(k_comoving);\n        \n//        if(j==0){std::cout << la << \"\\n\"; };\n        k_output << std::setw(6) << la << \" \"               //log(a)\n        << std::setw(10) << w << \" \"                        //log(H)\n        << std::setw(10) << Pzeta << \" \"                    //log(Zeta)\n        << std::setw(10) << PPot << \" \"                    //log(Gravitational Potential)\n        << std::setw(10) << log10(rhop/rho) << \" \"        //log(p/rho)\n        << std::setw(10) << log10(H/a) << \" \"            //log(H/a)\n        << std::setw(10) << log10(k_comoving/(a*H)) << \" \"        //log(k/(a*H))\n        << std::setw(10) << P_sigma << \" \"               //log(P_sigma)\n        << std::setw(10) << P_psi << \" \"                 //log(P_psi)\n        << std::setw(10) << P_phi << \" \"                 //log(P_phi)\n        << std::setw(10) << zeta[0]*zeta[0]/Pzeta_raw << \" \"                 //\n        << std::setw(10) << zeta[1]*zeta[1]/Pzeta_raw << \" \"                 //\n        << std::setw(10) << zeta[2]*zeta[2]/Pzeta_raw << \" \"                 //\n        << std::setw(10) << zeta[3]*zeta[3]/Pzeta_raw << \" \"                 //\n        << std::setw(10) << zeta[4]*zeta[4]/Pzeta_raw << \" \"                 //\n        << std::setw(10) << zeta[5]*zeta[5]/Pzeta_raw << \" \"                 //\n        << \"\\n\";\n    };\n\n}\n\n//subroutine for spectrum output before oscillation period\nvoid spectrum_bfosc_output(const std::string file, Vec_I_DP &xx, Mat_I_DP &yp, int timecount, int knum, const DP k_comoving){\n    static int output_timecount = 0; ++output_timecount;\n    std::stringstream ss;\n    std::ofstream sp_output;\n    ss << \"../\" << file;\n    \n    if( output_timecount == 1 )\n    {\n        sp_output.open(ss.str().c_str(),std::ios::out);\n    }else{\n        sp_output.open(ss.str().c_str(),std::ios::app);\n    }\n    \n    DP H,a,la,rho,rhop,Pzeta,Pzeta_raw,PPot,P_sigma,P_psi,P_phi,PSTR;\n\n    Vec_DP zeta(6);\n    Vec_DP tr(N_pert);\n\n    int i;\n    \n    la=xx[timecount-1];\n    a=exp(la);\n\n    for (i=0;i<N_pert;i++) tr[i] = yp[i][timecount-1];\n    rho=rho_tot(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n    rhop=rhoandp(tr[3],tr[4],tr[5],tr[6]);\n    H=Fri(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n    \n    for (i=0;i<3;i++) zeta[i]=2*rho*(tr[i+25] + tr[i+28]/H)/(rhop) + (1 + 2*k_comoving*k_comoving*rho/(9*a*a*H*H*rhop))*3*tr[i+25];\n    for (i=0;i<3;i++) zeta[i+3]=2*rho*(tr[i+49] + tr[i+52]/H)/(rhop) + (1 + 2*k_comoving*k_comoving*rho/(9*a*a*H*H*rhop))*3*tr[i+49];\n    Pzeta=0;\n    for (i=0;i<6;i++) Pzeta = Pzeta + zeta[i]*zeta[i];\n    Pzeta = Pzeta/(2*M_PI*M_PI*9);\n    Pzeta = log10(Pzeta) + 3*log10(k_comoving);\n    PPot = 0;\n    for (i=0;i<3;i++) PPot = PPot + tr[i+25]*tr[i+25];\n    for (i=0;i<3;i++) PPot = PPot + tr[i+49]*tr[i+49];\n    PSTR = PPot;\n    PPot = PPot/(2*M_PI*M_PI);\n    PPot = log10(PPot) + 3*log10(k_comoving);\n    //output log(Gravitational Potential) and log(Zeta), along with k and knum.\n    sp_output << std::setprecision (10) << std::setw(10) << k_comoving << \" \" << std::setw(5) << knum << \" \" << std::setw(10) << UC::knum_to_kMpc(knum) << \" \" << std::setw(10) << PPot << \" \" << std::setw(10) << Pzeta <<  \" \" << std::setw(10) << PSTR*sqrt(k_comoving*k_comoving*k_comoving) << \"\\n\" << std::flush;\n}\n\n//subroutine for spectrum output\nvoid spectrum_output(const std::string file, Vec_I_DP &xx, Mat_I_DP &yp, int timecount, int knum, const DP k_comoving){\n    static int output_timecount = 0; ++output_timecount;\n    std::stringstream ss;\n    std::ofstream sp_output;\n    ss << \"../\" << file;\n    \n    if( output_timecount == 1 )\n    {\n        sp_output.open(ss.str().c_str(),std::ios::out);\n    }else{\n        sp_output.open(ss.str().c_str(),std::ios::app);\n    }\n    \n    DP H,a,la,rho,rhop,Pzeta,Pzeta_raw,PPot,P_sigma,P_psi,P_phi,PSTR;\n    \n    Vec_DP zeta(6);\n    Vec_DP tr(N_pert);\n    int i;\n    \n    la=xx[timecount-1];\n    a=exp(la);\n    \n    for (i=0;i<N_pert;i++) tr[i] = yp[i][timecount-1];\n\n    rho=rho_tot(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n    rhop=rhoandp(tr[3],tr[4],tr[5],tr[6]);\n    H=Fri(tr[0],tr[1],tr[2],tr[3],tr[4],tr[5],tr[6]);\n    \n    for (i=0;i<3;i++) zeta[i]=2*rho*(tr[i+25] + tr[i+28]/H)/(rhop) + (1 + 2*k_comoving*k_comoving*rho/(9*a*a*H*H*rhop))*3*tr[i+25];\n    for (i=0;i<3;i++) zeta[i+3]=2*rho*(tr[i+49] + tr[i+52]/H)/(rhop) + (1 + 2*k_comoving*k_comoving*rho/(9*a*a*H*H*rhop))*3*tr[i+49];\n    Pzeta=0;\n    for (i=0;i<6;i++) Pzeta = Pzeta + zeta[i]*zeta[i];\n    Pzeta = Pzeta/(2*M_PI*M_PI*9);\n    Pzeta = log10(Pzeta) + 3*log10(k_comoving);\n    PPot = 0;\n    for (i=0;i<3;i++) PPot = PPot + tr[i+25]*tr[i+25];\n    for (i=0;i<3;i++) PPot = PPot + tr[i+49]*tr[i+49];\n    PSTR = PPot;\n    PPot = PPot/(2*M_PI*M_PI);\n    PPot = log10(PPot) + 3*log10(k_comoving);\n    //output log(Gravitational Potential) and log(Zeta), along with k and knum.\n    sp_output << std::setprecision (10) << std::setw(10) << k_comoving << \" \" << std::setw(5) << knum << \" \" << std::setw(10) << UC::knum_to_kMpc(knum) << \" \" << std::setw(10) << PPot << \" \" << std::setw(10) << Pzeta <<  \" \" << std::setw(10) << PSTR*sqrt(k_comoving*k_comoving*k_comoving) << \"\\n\" << std::flush;\n}\n//--------------------------------\n// Lattice Simulation Subroutines\n//--------------------------------\n\ndouble rand_uniform(void)\n{\n    std::random_device rnd;\n    std::mt19937 mt( rnd() );\n    std::uniform_real_distribution<> rand( 0, 1 );\n //   std::cout << rand(mt) << \"\\n\";\n    return (rand(mt));\n}\n\nvoid set_mode(double p2, double m2, double *field, double *deriv, int real)\n{\n\n    double phase, amplitude, rms_amplitude, omega;\n    double re_f_left, im_f_left, re_f_right, im_f_right;\n#if  dim==1\n    static double norm = rescale_A*rescale_B*pow(L/(dx*dx),.5)/sqrt(4*M_PI);\n#elif  dim==2\n    static double norm =  rescale_A*rescale_B*pow(L/(dx*dx),1)/(sqrt(2*M_PI));\n#elif  dim==3\n    static double norm =  rescale_A*rescale_B*pow(L/(dx*dx),1.5)/sqrt(2);\n#endif\n    static int tachyonic = 0; //Avoid printing the same error repeatedly\n    \n    if(p2+m2>0)\n        omega=sqrt(p2+m2);\n    else\n    {\n        if(tachyonic==0)\n            std::cout << \"Warning: Tachyonic mode(s) may be initialized inaccurately\" << std::endl;\n        omega=sqrt(p2);\n        tachyonic=1;\n    }\n    \n    if(omega>0.)\n        rms_amplitude=norm/sqrt(omega)*pow(p2,.75-(double)dim/4.);\n    else\n        rms_amplitude=0.;\n        \n        //Amplitude = RMS amplitude x Rayleigh distributed random number\n        // The same amplitude is used for left and right moving waves to generate standing waves. The extra 1/sqrt(2) normalizes the initial occupation number correctly.\n        \n    amplitude = rms_amplitude/sqrt(2.)*sqrt(log(1./rand_uniform()));\n    phase = 2*M_PI*rand_uniform();\n  // std::cout << \"phase1 \" << phase/(2*M_PI) << std::endl;\n        //Left moving component\n        re_f_left = amplitude * cos( phase );\n        im_f_left = amplitude * sin( phase );\n        //Right moving component\n    phase = 2*M_PI*rand_uniform();\n  //  std::cout << \"phase2 \" << phase/(2*M_PI) << std::endl;\n        re_f_right = amplitude * cos( phase );\n        im_f_right = amplitude * sin( phase );\n    \n    field[0] = re_f_left + re_f_right;\n    field[1] = im_f_left + im_f_right;\n\n    deriv[0] = omega*(im_f_left - im_f_right);\n    deriv[1] = -omega*(re_f_left - re_f_right);\n\n    if(real==1)\n    {\n        field[1]=0;\n        deriv[1]=0;\n    }\n    return;\n   }\n\n\nvoid DFT_c2rD1( double* f)\n{\n    fftw_plan p;\n    double* out;\n    fftw_complex *in;\n    size_t in_size;\n    \n    in_size = sizeof(fftw_complex) * (N/2+1);\n    in  = (fftw_complex*)fftw_malloc( in_size );\n    out = new double [N]();\n    p = fftw_plan_dft_c2r_1d( N, in, out, FFTW_ESTIMATE );\n    \n        for( int j = 0; j < N/2+1; ++j ){\n            int idx = j;\n            if(idx==0)\n            {\n                in[idx][0] = f[idx]  ;\n                in[idx][1] = 0  ;\n                \n            }else if(idx==N/2){\n                in[idx][0] = f[1]  ;\n                in[idx][1] = 0  ;\n            }else{\n                in[idx][0] = f[2*idx]  ;\n                in[idx][1] = f[2*idx+1]  ;\n            }\n            \n        }\n    \n    fftw_execute(p);\n    \n    // Set output data\n    for( int j = 0; j < N; ++j ){\n        int idx = j;\n        f[idx] = out[idx]/N;\n    }\n    \n    if( p ) fftw_destroy_plan(p);\n    if( in ) fftw_free(in);\n    delete[] out;\n}\n/*\nvoid DFT_c2rD2d( double* df,double* fdnyquist )\n{\n    fftw_plan p;\n    double* out;\n    fftw_complex *in;\n    size_t in_size;\n    \n    in_size = sizeof(fftw_complex) * N * (N/2+1);\n    in  = (fftw_complex*)fftw_malloc( in_size );\n    out = new double [N*N]();\n    p = fftw_plan_dft_c2r_2d( N, N, in, out, FFTW_ESTIMATE );\n    \n    \n    \n    for( int j = 0; j < N; ++j ){\n        //#pragma omp parallel for schedule( static ) num_threads( num_threads )\n        for( int k = 0; k < N/2+1; ++k ){\n            int idx = (N/2+1)*j + k;\n            // int idx = j*N + k;\n            if(k == N/2){\n                in[idx][0] = (double)fdnyquist[2*j] ;\n                in[idx][1] = (double)fdnyquist[2*j+1] ;\n               // std::cout << \"in[\" << idx << \"][0] = \" << in[idx][0] << std::endl;\n               // std::cout << \"in[\" << idx << \"][1] = \" << in[idx][1] << std::endl;\n            }else {\n                in[idx][0] =  (double)df[j*N + 2*k] ;\n                in[idx][1] = (double)df[j*N + 2*k+1] ;\n               // std::cout << \"in[\" << idx << \"][0] = \" << in[idx][0] << std::endl;\n               // std::cout << \"in[\" << idx << \"][1] = \" << in[idx][1] << std::endl;\n            }\n        }\n    }\n    fftw_execute(p);\n    \n    // Set output data\n    \n    for( int j = 0; j < N; ++j ){\n        //#pragma omp parallel for schedule( static ) num_threads( num_threads )\n        for( int k = 0; k < N; ++k ){\n            int idx = j*N + k;\n            std::cout << \"out[\" << idx << \"] = \" << out[idx] << std::endl;\n            df[idx] = out[idx]/(N*N);\n        }\n    }\n    \n    if( p ) fftw_destroy_plan(p);\n    if( in ) fftw_free(in);\n    delete[] out;\n}\n*/\nvoid DFT_c2rD2( double* f,double* fnyquist )\n{\n    fftw_plan p;\n    double* out;\n    fftw_complex *in;\n    size_t in_size;\n    \n    in_size = sizeof(fftw_complex) * N * (N/2+1);\n    in  = (fftw_complex*)fftw_malloc( in_size );\n    out = new double [N*N]();\n    p = fftw_plan_dft_c2r_2d( N, N, in, out, FFTW_ESTIMATE );\n    \n    \n        for( int j = 0; j < N; ++j ){\n            for( int k = 0; k < N/2+1; ++k ){\n                int idx = (N/2+1)*j + k;\n              //  int idx = j*N + k;\n                if(k == N/2){\n                    in[idx][0] =  fnyquist[2*j] ;\n                    in[idx][1] =  fnyquist[2*j+1] ;\n                }else {\n                    in[idx][0] =  f[j*N + 2*k]; \n                    in[idx][1] =  f[j*N + 2*k+1] ;\n                }\n            }\n        }\n        fftw_execute(p);\n        \n        // Set output data\n\n     for( int j = 0; j < N; ++j ){\n        for( int k = 0; k < N; ++k ){\n            int idx = j*N + k;\n            f[idx] = out[idx]/(N*N);\n        }\n     }\n    \n    if( p ) fftw_destroy_plan(p);\n    if( in ) fftw_free(in);\n    delete[] out;\n}\n\n\n\n\nvoid DFT_c2rD3( double* f,double** fnyquist )\n{\n    fftw_plan p;\n    double* out;\n    fftw_complex *in;\n    size_t in_size;\n    \n    in_size = sizeof(fftw_complex) * N * N * (N/2+1);\n    in  = (fftw_complex*)fftw_malloc( in_size );\n    out = new double [N*N*N]();\n    p = fftw_plan_dft_c2r_3d( N, N, N, in, out, FFTW_ESTIMATE );\n    \n   \n//#pragma omp parallel for simd collapse(3) schedule( static ) num_threads( num_threads )\n        for( int j = 0; j < N; ++j ){\n            for( int k = 0; k < N; ++k ){\n                for( int l = 0; l < N/2+1; ++l ){\n                    int idx = (j*N + k)*(N/2+1) + l;\n                    if(l == N/2){\n                        in[idx][0] = fnyquist[j][2*k] ;\n                        in[idx][1] = fnyquist[j][2*k+1] ;\n                    }\n                    else{\n                        in[idx][0] =  f[(j*N + k)*N + 2*l] ;\n                        in[idx][1] =  f[(j*N + k)*N + 2*l+1] ;\n                    }\n                }\n            }\n        }\n        fftw_execute(p);\n        \n        // Set output data\n\n\n         for( int j = 0; j < N; ++j ){\n        for( int k = 0; k < N; ++k ){\n            for( int l = 0; l < N; ++l ){\n                int idx = (j*N + k)*N + l;\n                f[idx] = out[idx]/(N*N*N);\n            }\n        }\n    }\n    \n    if( p ) fftw_destroy_plan(p);\n    if( in ) fftw_free(in);\n    delete[] out;\n}\n\n/*\nvoid DFT_c2r( double** f,double* fnyquist )\n{\n\t  fftw_plan p;\n\t\tdouble* out;\n    fftw_complex *in;\n\t\tsize_t in_size;\n\t  \n\t\tswitch( dim )\n\t\t{\n\t\t\tcase 1:\n\t\t\t\tin_size = sizeof(fftw_complex) * (N/2+1);\n\t\t\t\tin  = (fftw_complex*)fftw_malloc( in_size );\n\t\t\t\tout = new double [N]();\n\t\t\t\tp = fftw_plan_dft_c2r_1d( N, in, out, FFTW_ESTIMATE );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tin_size = sizeof(fftw_complex) * N * (N/2+1);\n\t\t\t\tin  = (fftw_complex*)fftw_malloc( in_size );\n\t\t\t\tout = new double [N*N]();\n\t\t\t\tp = fftw_plan_dft_c2r_2d( N, N, in, out, FFTW_ESTIMATE );\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tin_size = sizeof(fftw_complex) * N * N * (N/2+1);\n\t\t\t\tin  = (fftw_complex*)fftw_malloc( in_size );\n\t\t\t\tout = new double [N*N*N]();\n\t\t\t\tp = fftw_plan_dft_c2r_3d( N, N, N, in, out, FFTW_ESTIMATE );\n\t\t\t\tbreak;\n\t\t}\n\n\t\tfor( int i = 0; i < num_fields; ++i )\n\t\t{\n\t\t\t\t\n\t\t\t\t// Create input data\n\t\t\t\tswitch( dim ){\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t#pragma omp parallel for schedule( static ) num_threads( num_threads )\n\t\t\t\t\t\tfor( int j = 0; j < N/2+1; ++j ){\n\t\t\t\t\t\t\tint idx = j;\n\t\t\t\t\t\t\tif(idx==0)\n                            {\n                                in[idx][0] = f[i][idx]  ;\n                                in[idx][1] = 0  ;\n                                \n                            }else if(idx==N/2){\n                                in[idx][0] = f[i][1]  ;\n                                in[idx][1] = 0  ;\n                            }else{\n                                in[idx][0] = f[i][2*idx]  ;\n                                in[idx][1] = f[i][2*idx+1]  ;\n                            }\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\t#pragma omp parallel for schedule( static ) num_threads( num_threads )\n\t\t\t\t\t\tfor( int j = 0; j < N; ++j ){\n\t\t\t\t\t\t\tfor( int k = 0; k < N/2+1; k=k+2 ){\n\t\t\t\t\t\t\t\t\tint idx = j*N + k;\n                                if(k == N/2){\n                                    in[idx][0] = fnyquist[2*j] ;\n                                    in[idx][1] = fnyquist[2*j+1] ;\n                                }else {\n                                    in[idx][0] =  f[i][idx] ;\n                                    in[idx][1] =  f[i][idx+1] ;\n                                }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\t#pragma omp parallel for schedule( static ) num_threads( num_threads )\n\t\t\t\t\t\tfor( int j = 0; j < N; ++j ){\n\t\t\t\t\t\t\tfor( int k = 0; k < N; ++k ){\n\t\t\t\t\t\t\t\t\tfor( int l = 0; l < N/2+1; l=l+2 ){\n\t\t\t\t\t\t\t\t\t\t\tint idx = (j*N + k)*N + l;\n                                        if(l == N/2){\n                                        in[idx][0] = fnyquist[j][2*k] ;\n                                        in[idx][1] = fnyquist[j][2*k+1] ;\n                                        }\n                                        else{\n                                            in[idx][0] =  f[i][idx] ;\n                                            in[idx][1] =  f[i][idx+1] ;\n                                        }\n                                        }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\n\t\t\t\tfftw_execute(p);\n\t\n\t\t\t\t// Set output data\n        #pragma omp parallel for schedule( static ) num_threads( num_threads )\n        for( int j = 0; j < N; ++j ){\n            switch( dim ){\n\t\t\t\t\t\t\tcase 1:\n                int idx = j;\n                f[i][idx] = out[idx]/N;\n\t\t\t\t\t\t\t\tbreak;\n            \tcase 2:\n                for( int k = 0; k < N; ++k ){\n                    int idx = j*N + k;\n                    f[i][idx] = out[idx]/(N*N);\n                }\n\t\t\t\t\t\t\t\tbreak;\n            \tcase 3:\n                for( int k = 0; k < N; ++k ){\n                    for( int l = 0; l < N; ++l ){\n                        int idx = (j*N + k)*N + l;\n                        f[i][idx] = out[idx]/(N*N*N);\n                    }\n                }\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n        }\n    }\n\n\t\tif( p ) fftw_destroy_plan(p);\n\t\tif( in ) fftw_free(in);\n\t\tdelete[] out;\n}\n*/\n\nvoid write_VTK_f( const std::string dir_f, double* f, std::string str, int loop )\n{\n   // double a = leapfrog->a();\n\tunsigned int size;\n\tstd::stringstream ss;\n\tstd::ofstream fout;\n    \n    \n\t\n\tif( dim == 1 ){\n\t\tss << \"../\" << dir_f << \"/\" << str << \".\" << std::setw(4) << std::setfill('0') << loop+1 <<\".txt\";\n    \tfout.open( ss.str().c_str() );\t\n \n    \tfor( int j = 0; j < N; j++ ){\n\t\t\tint idx = j;\n\t\t\tfout << idx*dx << \" \" << f[idx] << std::endl;\n\t\t}\n    }else{\n    \tss << \"../\" << dir_f << \"/\" << str << \".\" << std::setw(4) << std::setfill('0') << loop+1 <<\".vti\";\n    \tfout.open( ss.str().c_str() );\n    \n  \t  \tfout << \"<?xml version=\\\"1.0\\\"?>\" << std::endl;\n  \t\tfout << \"<VTKFile type=\\\"ImageData\\\" version=\\\"1.0\\\" byte_order=\\\"LittleEndian\\\" header_type=\\\"UInt32\\\">\" << std::endl <<std::endl;\n    \tswitch( dim ){\n    \t\tcase 2:\n\t\t\t\tsize = sizeof(double) * pow(N, 2);//8byte*pow(N,2)\n\t\t\t\tfout << \"<ImageData WholeExtent=\\\"0 \" << N-1 << \" 0 \" << N-1 << \" 0 \" << \" 0 \" << \"\\\" Origin=\\\"0 0 0\\\" Spacing=\\\"\" << dx << \" \" << dx << \" \" << dx << \"\\\">\" << std::endl;\n\t\t\t\tfout << \"<Piece Extent=\\\"0 \" << N-1 << \" 0 \" << N-1 << \" 0 \" << \" 0 \" << \"\\\">\" << std::endl;\n    \t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tsize = sizeof(double) * pow(N, 3);\n\t\t\t\tfout << \"<ImageData WholeExtent=\\\"0 \" << N-1 << \" 0 \" << N-1 <<\" 0 \" << N-1 << \"\\\" Origin=\\\"0 0 0\\\" Spacing=\\\"\" << dx << \" \" << dx << \" \" << dx << \"\\\">\" << std::endl;\n\t\t\t\tfout << \"<Piece Extent=\\\"0 \" << N-1 << \" 0 \" << N-1 << \" 0 \" << N-1 << \"\\\">\" << std::endl;\n\t\t\t\tbreak;\n    \t}\n    \tfout << \"<PointData Scalars=\\\"field\\\">\" << std::endl;\n    \tfout << \"<DataArray type=\\\"Float64\\\" Name=\\\"field\\\" format=\\\"appended\\\" offset=\\\"0\\\" />\" << std::endl;\n    \tfout << \"</PointData>\" << std::endl;\n\t    fout << \"<CellData>\" << std::endl;\n\t    fout << \"</CellData>\" << std::endl;\n\t    fout << \"</Piece>\" << std::endl << std::endl;\n\t    \n\t    fout << \"</ImageData>\" << std::endl << std::endl;\n\t    fout << \"<AppendedData encoding=\\\"raw\\\">\" << std::endl;\n\t    fout << \"_\" ;\n\t    fout.close();\n\t    \n\t    fout.open( ss.str().c_str(), std::ios::binary | std::ios::app);\n\t    fout.write( (char*) &size, sizeof(unsigned int) );//4byte\n       \n           fout.write( (char*) f, size );\n\t    fout.close();\t\n\t    fout.open( ss.str().c_str(), std::ios::app);\n\t    fout << std::endl << \"</AppendedData>\" << std::endl;\n\t\tfout << \"</VTKFile>\" ;\n\t}\n\tfout.close();\n}\n\nvoid write_VTK_ed( const std::string dir_ed, double* f, std::string str, int loop )\n{\n  //  double a = leapfrog->a();\n   // std::cout << \"aaa = \" <<  a << std::endl;\n    unsigned int size;\n    std::stringstream ss;\n    std::ofstream fout;\n    \n    \n    \n    if( dim == 1 ){\n        ss << \"../\" << dir_ed << \"/\" << str << \".\" << std::setw(4) << std::setfill('0') << loop+1 <<\".txt\";\n        fout.open( ss.str().c_str() );\n        \n        for( int j = 0; j < N; j++ ){\n            int idx = j;\n            fout << idx*dx << \" \" << f[idx] << std::endl;\n        }\n    }else{\n        ss << \"../\" << dir_ed << \"/\" << str << \".\" << std::setw(4) << std::setfill('0') << loop+1 <<\".vti\";\n        fout.open( ss.str().c_str() );\n        \n        fout << \"<?xml version=\\\"1.0\\\"?>\" << std::endl;\n        fout << \"<VTKFile type=\\\"ImageData\\\" version=\\\"1.0\\\" byte_order=\\\"LittleEndian\\\" header_type=\\\"UInt32\\\">\" << std::endl <<std::endl;\n        switch( dim ){\n            case 2:\n                size = sizeof(double) * pow(N, 2);//8byte*pow(N,2)\n                fout << \"<ImageData WholeExtent=\\\"0 \" << N-1 << \" 0 \" << N-1 << \" 0 \" << \" 0 \" << \"\\\" Origin=\\\"0 0 0\\\" Spacing=\\\"\" << dx << \" \" << dx << \" \" << dx << \"\\\">\" << std::endl;\n                fout << \"<Piece Extent=\\\"0 \" << N-1 << \" 0 \" << N-1 << \" 0 \" << \" 0 \" << \"\\\">\" << std::endl;\n                break;\n            case 3:\n                size = sizeof(double) * pow(N, 3);\n                fout << \"<ImageData WholeExtent=\\\"0 \" << N-1 << \" 0 \" << N-1 <<\" 0 \" << N-1 << \"\\\" Origin=\\\"0 0 0\\\" Spacing=\\\"\" << dx << \" \" << dx << \" \" << dx << \"\\\">\" << std::endl;\n                fout << \"<Piece Extent=\\\"0 \" << N-1 << \" 0 \" << N-1 << \" 0 \" << N-1 << \"\\\">\" << std::endl;\n                break;\n        }\n        fout << \"<PointData Scalars=\\\"energy\\\">\" << std::endl;\n        fout << \"<DataArray type=\\\"Float64\\\" Name=\\\"energy density\\\" format=\\\"appended\\\" offset=\\\"0\\\" />\" << std::endl;\n        fout << \"</PointData>\" << std::endl;\n        fout << \"<CellData>\" << std::endl;\n        fout << \"</CellData>\" << std::endl;\n        fout << \"</Piece>\" << std::endl << std::endl;\n        \n        fout << \"</ImageData>\" << std::endl << std::endl;\n        fout << \"<AppendedData encoding=\\\"raw\\\">\" << std::endl;\n        fout << \"_\" ;\n        fout.close();\n        \n        fout.open( ss.str().c_str(), std::ios::binary | std::ios::app);\n        fout.write( (char*) &size, sizeof(unsigned int) );//4byte\n        \n            fout.write( (char*) f, size );\n        \n        fout.close();\n        fout.open( ss.str().c_str(), std::ios::app);\n        fout << std::endl << \"</AppendedData>\" << std::endl;\n        fout << \"</VTKFile>\" ;\n    }\n    fout.close();\n}\n\n\nvoid write_status( const std::string status_file, Field* field, LeapFrog* leapfrog, Energy* energy, double** f, double t )\n{\n\tdouble a = leapfrog->a();\n\tstd::ofstream ofs;\n\t\n\tif( t == t0 )\n\t{\n\t\tofs.open( \"../\" + status_file, std::ios::trunc );\n\n\t\tofs << std::setw(3) << std::right << \"  t \";\n\t\tif( expansion ) ofs << \"  a \";\n\t\tfor( int i = 0; i < num_fields; ++i ) ofs << \"field_ave[\"  << i << \"] \";\n\t\tfor( int i = 0; i < num_fields; ++i ) ofs << \"field_var[\"  << i << \"] \";\n        for( int i = 0; i < num_fields; ++i ) ofs << \"field_deriv_ave[\"  << i << \"] \";\n        for( int i = 0; i < num_fields; ++i ) ofs << \"field_deriv_var[\"  << i << \"] \";\n\t\tfor( int i = 0; i < num_fields; ++i ) ofs << \"energy_ave[\" << i << \"] \";\n        for( int i = 0; i < num_fields; ++i ) ofs << \"energy_var[\" << i << \"] \";\n        ofs << \"total_energy_ave \";\n         ofs << \"time_deriv_ave \";\n         ofs << \"gradient_ave \";\n        ofs << \"potential_ave \";\n        ofs << \"hubble \";\n        ofs << \"adotdot \";\n        ofs << \"energy_max\" << std::endl;\n\t}\n\telse ofs.open( \"../\" + status_file, std::ios::app );\n\t\n\tofs << std::setw(3) << std::right << t << \" \";\n\tif( expansion )\n\t{\n\t\tofs << std::setw(3) << std::right << a << \" \";\n\t\tfor( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->f_average(f[i], i)/a << \" \"; //Reduced Plank units\n\t\tfor( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->f_variance(f[i], i)/a << \" \";//Reduced Plank units\n        for( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->df_average(f[i], i) << \" \";//Programming variable\n        for( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->df_variance(f[i], i) << \" \";//Programming variable\n\t}\n\telse\n\t{\n\t\tfor( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->f_average(f[i], i) << \" \";//Reduced Plank units\n\t\tfor( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->f_variance(f[i], i) << \" \";//Reduced Plank units\n        for( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->df_average(f[i], i) << \" \";//Programming variable\n        for( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << field->df_variance(f[i], i) << \" \";//Programming variable\n\t}\n\tfor( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << energy->average(i) << \" \";\n    for( int i = 0; i < num_fields; ++i ) ofs << std::showpos << std::scientific << std::setprecision(4) << energy->variance(i) << \" \";\n\tofs << std::showpos << std::scientific << std::setprecision(4) << energy->total_average() << \" \";\n    ofs << std::showpos << std::scientific << std::setprecision(4) << energy->timederiv_average () << \" \";\n     ofs << std::showpos << std::scientific << std::setprecision(4) << energy->grad_average ()  << \" \";\n    ofs << std::showpos << std::scientific << std::setprecision(4) << energy->potential_average () << \" \";\n    ofs << std::showpos << std::scientific << std::setprecision(4) << leapfrog->hubble() << \" \";\n    ofs << std::showpos << std::scientific << std::setprecision(4) << leapfrog->adotdot() << \" \";\n    ofs << std::showpos << std::scientific << std::setprecision(4) << energy->energy_max() << std::endl;\n    \n    \n}\n\n\n\n", "meta": {"hexsha": "02b56877a5fbacc167a182ab0bfd78e34a8f05c6", "size": 31267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utilities.cpp", "max_stars_repo_name": "embreakin/FLattice_PBH", "max_stars_repo_head_hexsha": "13451828487bb85731eb171ccfabc4cb865649b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities.cpp", "max_issues_repo_name": "embreakin/FLattice_PBH", "max_issues_repo_head_hexsha": "13451828487bb85731eb171ccfabc4cb865649b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.cpp", "max_forks_repo_name": "embreakin/FLattice_PBH", "max_forks_repo_head_hexsha": "13451828487bb85731eb171ccfabc4cb865649b5", "max_forks_repo_licenses": ["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.2305909618, "max_line_length": 311, "alphanum_fraction": 0.4689928679, "num_tokens": 10225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.04208772401067611, "lm_q1q2_score": 0.020386455303317758}}
{"text": "//     Copyright (c) 2012 Vadym Kliuchnikov sqct(dot)software(at)gmail(dot)com, Dmitri Maslov, Michele Mosca\n//\n//     This file is part of SQCT.\n//\n//     SQCT 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//     SQCT 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 SQCT.  If not, see <http://www.gnu.org/licenses/>.\n//\n\n#include \"sk.h\"\n#include \"exactdecomposer.h\"\n#include \"gcommdecomposer.h\"\n\n#include \"theoremverification.h\"\n#include \"toptimalitytest.h\"\n#include \"hoptimalitytest.h\"\n\n#include \"netgenerator.h\"\n\n#include \"output.h\"\n\n#include <fstream>\n#include <sstream>\n#include <chrono>\n\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <cmath>\n\n// command line parcing code based on http://www.boost.org/doc/libs/1_49_0/doc/html/program_options/tutorial.html#id2499896\n// and BOOST_ROOT/libs/program_options/example/first.cpp\nnamespace po = boost::program_options;\nnamespace btm = boost::timer;\n\nusing namespace std;\n\n//////////////////////////////////////////////////////////////////////////////\n\n/// \\brief Option of SK execution\nstruct SKOptions\n{\n    SKOptions() :\n            math_fr( false ), write_dot_qc(false), angle(false) {};\n\n    string in_filename; ///< input filename\n    string out_filename; ///< output statistics filename\n    bool math_fr; ///< should output be mathematica friendly\n    int iterations_default; ///< number of SK iterations to perform by default\n    bool write_dot_qc;///< should we output dot qc or not\n    string out_dir;///< path where we should output dotqc files\n    bool angle;///< how we interpret first element \\b val of each input line ( Pi/\\b val or just \\b val)\n    int max_sde;///< maximal value of sde to use during basic approximation step\n};\n\n//////////////////////////////////////////////////////////////////////////////\n\n/// \\brief Result of application of the SK algorithm\nstruct ApplicationResult\n{\n    circuit c;  ///< Circuit\n    int hc;     ///< Hadamard counts\n    int tc;     ///< T and inverse of T gates counts\n    int pc;     ///< Phase and inverse of Phase gate counts\n    int plc;    ///< Pauli matrices counts\n    int total;  ///< Total cost using cost function defined by vector gateLibrary::cost\n    double dst; ///< Trace distance to approximation\n    double tappr; ///< Time required to do an approximation\n    double tdecomp; ///< Time required to do a decomposition\n    int nr; ///< Number of iterations performed\n    int denom_reduction; ///< Difference between \\f$ sde(|\\cdot|^2) \\f$\n                         /// before and after conversion to canonical form\n    int denom ; ///< \\f$ sde(|\\cdot|^2) \\f$ of resulting unitary\n    matrix2x2<mpz_class> exact_uni; /// exact unitary corresponding to the circuit c\n\n\n    /// \\brief Summarize gate statistics for Clifford + T library\n    void updateForCliffordT()\n    {\n        typedef gateLibrary gl;\n        total = c.cost();\n        auto counts = gl::toCliffordT( c.count() );\n        hc = counts[ gl::H ];\n        tc = counts[ gl::T ];\n        pc = counts[ gl::P ];\n        plc =  counts[ gl::Z ] + counts[ gl::X ] + counts[ gl::Y ];\n    }\n\n    /// \\brief Outputs results in CSV format\n    void toCSVStream( std::ostream& out ) const\n    {\n        out.precision(5);\n        out.setf( ios_base::scientific );\n        out << nr << \",\"\n            << tc << \",\"\n            << hc << \",\"\n            << pc << \",\"\n            << plc << \",\"\n            << dst << \",\"\n            << tappr << \",\"\n            << tdecomp << \",\" << denom_reduction << \",\" << denom ;\n    }\n\n    /// \\brief Outputs results in Mathematica friendly format\n    void toMathematicaStream( std::ostream& out ) const\n    {\n        out.precision(10);\n        out.setf( ios_base::fixed ); // use fixed as mathematica does not understand scientific c++ format\n        out << \"AppResult[\"\n            << nr << \",\"\n            << tc << \",\"\n            << hc << \",\"\n            << pc << \",\"\n            << plc << \",\";\n        out.precision(60);\n        out << dst << \",\" ;\n        out.precision(10);\n        out << tappr << \",\"\n            << tdecomp << \",\" << denom_reduction << \",\" << denom << \"]\";\n    }\n\n    /// \\brief Outputs dot qc file with circuit and adds information about genration process into comments\n    void generateDotQc( std::string filename, std::string circuit_name, std::string symbolic_form )\n    {\n        ofstream ofs(filename.c_str());\n        if( !ofs )\n        {\n            cout << \"Unable to open file:\" << filename << \" for output\" <<endl;\n            return;\n        }\n\n        ofs << \"# Computed by SQCT, based on arXiv:1206.5236\" << endl;\n        ofs << \"# Published at: http://code.google.com/p/sqct/\" << endl;\n        ofs << \"# Symbolic form of unitary to approximate:\" << symbolic_form << endl;\n        ofs << \"# Distance between unitary and approximation:\" << dst << endl;\n        ofs << \"# (Formula (1) in http://arxiv.org/abs/quant-ph/0411206)\" << endl;\n        ofs << \"# Total number of gates:\" << tc + hc + pc + plc << endl;\n        ofs << \"# T and T^{Dagger} gates:\" << tc << endl;\n        ofs << \"# Hadamard gates:\" << hc << endl;\n        ofs << \"# Phase and Phase^{Dagger} gates:\" << pc << endl;\n        ofs << \"# Pauli gates:\" << plc << endl;\n        ofs << \"# Total cost: \" << total << endl;\n        ofs << \"# Number of iterations:\" << nr << endl;\n        ofs << \"# Approximation time(seconds):\" << tappr << endl;\n        ofs << \"# Decomposition time(seconds):\" << tdecomp << endl;\n        ofs << \"# Reduction:\" << denom_reduction << endl;\n        ofs << \"# sde(abs(z)^2):\" << denom << endl;\n        ofs << \"# Exact unitary:\" << endl << exact_uni << endl;\n\n        ofs << \".v 1\" << endl;\n        ofs << \".i 1\" << endl;\n        ofs << \".o 1\" << endl;\n        ofs << \"BEGIN \" << circuit_name <<\"(1)\" << endl;\n        c.toStream(ofs);\n        ofs << \"END \" << circuit_name << endl;\n        ofs << \"BEGIN\" << endl;\n        ofs << circuit_name << \" 1\" << endl;\n        ofs << \"END\" << endl;\n        ofs.close();\n    }\n\n};\n\n///////////////////////////////////////////////////////////////////\n\n/// \\brief Process input file with inputs for SK in batch mode, outputs statistics etc\nclass SKApplication\n{\npublic:\n    SKApplication( SKOptions& skopt ) :\n        opt( skopt ), skd(skopt.max_sde + 1)\n    {}\n\n    /// \\brief Finds circuit and all supplementary information for unitary\n    void calculate( const matrix2x2hpr& matrix, int recursion_level, ApplicationResult& ar )\n    {\n        boost::timer::cpu_times ct;\n        boost::timer::cpu_times ct2;\n\n        sk::Me res;\n        {\n            boost::timer::auto_cpu_timer t;\n            skd.decompose(matrix,res,recursion_level);\n            ct = t.elapsed();\n        }\n\n        int gde_before = res.min_gde_abs2();\n        res.reduce();\n        int gde_after = res.min_gde_abs2();\n        ar.denom_reduction = gde_before - gde_after;\n        ar.denom = res.max_sde_abs2();\n        ar.exact_uni = res;\n\n        {\n            boost::timer::auto_cpu_timer t;\n            ed.decompose(res,ar.c);\n            ct2 = t.elapsed();\n        }\n\n        sk::Ma conv(res);\n\n        ar.dst = trace_dist(matrix,conv);\n        ar.tappr = (double) ct.wall * 1e-9;\n        ar.tdecomp = (double) ct2.wall * 1e-9;\n        ar.nr = recursion_level;\n        ar.updateForCliffordT();\n\n    }\n\n    /// \\brief Process input file defined by opt taking into account specified options\n    void process()\n    {\n        static const double TwoPi = 2. * hprHelpers::toMachine( hprHelpers::pi() );\n        ifstream ifs( opt.in_filename.c_str() );\n        ofstream ofs( opt.out_filename.c_str() );\n        Rotation r;\n        int iter = 0;\n        ApplicationResult ar;\n        int line_number = 0;\n        while( true )\n        {\n            string line;\n            getline(ifs,line);\n            iter = opt.iterations_default;\n            istringstream ss(line,istringstream::in);\n            if( ! ifs ) break;\n\n            double val;\n            ss >> val >> r.nx >> r.ny >> r.nz >> iter;\n            if( ! opt.angle )\n            {\n                r.num = 1.0;\n                r.den = val;\n            }\n            else\n            {\n                r.num = val;\n                r.den = TwoPi;\n            }\n\n            calculate( r.matrix() , iter, ar );\n\n            stringstream fname;\n            fname <<  opt.out_dir << \"/\";\n            if( r.isSpecial() != 'N' )\n                fname << r.name() << \"-\" << iter;\n            else\n                fname << opt.out_filename << \".\" << line_number;\n            fname << \".qc\" ;\n\n            if( opt.write_dot_qc )\n                ar.generateDotQc( fname.str() ,\n                               r.name(),\n                               r.symbolic() );\n\n            if( opt.math_fr )\n            {\n                ofs << \"{\" << r.Mathematica() << \",\";\n                ar.toMathematicaStream(ofs);\n                ofs << \"}\" << endl;\n            }\n            else\n            {\n                ofs << r.CSV() << \",\";\n                ar.toCSVStream(ofs);\n                ofs << endl;\n            }\n\n            line_number++;\n        }\n    }\nprivate:\n    const SKOptions& opt;\n    sk skd;\n    exactDecomposer ed;\n};\n\n///////////////////////////////////////////////////////////////////\n\nbool print_help( const string& topic )\n{\n    map<string,string> hi;\n    hi[\"in\"] = \"Each line of input file must have the followoing form:\\n\"\n            \"val,nx,ny,nz,[iter]\\n\"\n            \"val -- interpreted depending on the value of option --angle\\n\"\n            \"       if --angle is specified then val interpreted as rotation\\n\"\n            \"       angle phi. Otherwise rotation angle phi = 2 Pi / val.\\n\"\n            \"nx -- projection of rotation axis on, x\\n\"\n            \"ny -- projection of rotation axis on, y\\n\"\n            \"nz -- projection of rotation axis on, z\\n\"\n            \"iter -- optional parameter defining number of iterations used for approximation.\\n\"\n            \"The matrix that will be approximated is I*cos(phi/2) - \\n\"\n            \"i sin(phi/2) (nx * X + ny * Y + nz * Z). If the number of iterations is not specified,\\n\"\n            \"the default values is used. It can be set using --iterations option.\\n\"\n            \"\\n\"\n            \"Default output format is CSV and each line of it contains the following:\\n\"\n            \"num,den,nx,ny,nz,N,Tc,Hc,Pc,Plc,dst,tappr,tdecomp,denom_red,denom \\n\"\n            \"[num,den,nx,ny,nz] determines input rotation with phi = num * 2Pi / den\\n\"\n            \"N -- number of iterations of SK algorithm used\"\n            \"Tc-- number of T gates in the resulting circuit\\n\"\n            \"Hc-- number of Hadamard gates in the circuit\\n\"\n            \"Pc-- number of Phase gates in the circuit\\n\"\n            \"Plc-- number of Pauli gates in the circuit\\n\"\n            \"dst-- distance to approximation, see \\n\"\n            \"(Formula (1) in http://arxiv.org/abs/quant-ph/0411206)\\n\"\n            \"tappr-- time required for approximation (seconds) \\n\"\n            \"tdecomp-- time required for exact decomposition (seconds)\\n\"\n            \"tdecomp-- time required for exact decomposition (seconds)\\n\"\n            \"denom_red -- change of the power of sqrt(2) in the denominator\\n\"\n            \"after conversion to canonical form.\\n\"\n            \"denom -- power of sqrt(2) in the denominator of the exact unitary in\\n\"\n            \"the canonical form. In the case of Mathematica output numbers are \\n\"\n            \"decorated with Rot and AppResult list headers.\\n\";\n    if( hi.count(topic) )\n    {\n        cout << hi[topic] << endl;\n        return true;\n    }\n\n    return false;\n}\n\n/////////////////////////////////////////////////////////////////////\n\nstruct ResynthOptions\n{\n    ResynthOptions() :\n        reverse(false)\n        {}\n    vector<string> circuit_files;\n    bool reverse;\n    bool math_fr;\n};\n\n////////////////////////////////////////////////////////////////////\n\n/// \\brief Resyntheisizes circuits using exact decomposition algoritm\nstruct ResynthApplication\n{\n    ResynthApplication( const ResynthOptions& opt ) :\n        ro(opt)\n    {}\n\n    void process()\n    {\n        for( const auto& fn : ro.circuit_files )\n            process(fn);\n    }\n\n    void process( const string& filename )\n    {\n        const gateLibrary& gl = gateLibrary::instance();\n        ifstream ifs(filename.c_str());\n        ofstream ofs( (filename + \".out\").c_str() );\n        // read circuit first\n        circuit in, out;\n        in.fromStream(ifs,ro.reverse);\n        ed.decompose(in,out);\n\n        auto in_cost = in.count();\n        int in_total = in.cost();\n        in_cost = gl.toCliffordT(in_cost);\n\n        auto out_cost = out.count();\n        int out_total = out.cost();\n        out_cost = gl.toCliffordT(out_cost);\n\n        string cb = \"# \";\n        string ce = \"\";\n        if( ro.math_fr )\n            cb = \"(* \",ce = \" *)\";\n\n        ofs << cb << \"Computed by SQCT, based on arXiv:1206.5236\" << ce << endl;\n        ofs << cb << \"Software published at: http://code.google.com/p/sqct/\"<< ce << endl;\n        ofs << cb << \"Gate counts for input circuit [T+Td,H,P+Pd,X,Z,Y] : [\"\n            << in_cost[gl.T] << \",\" << in_cost[gl.H] << \",\"\n            << in_cost[gl.P] << \",\" << in_cost[gl.X] << \",\"\n            << in_cost[gl.Z] << \",\" << in_cost[gl.Y] << \"]\" << ce << endl;\n        ofs << cb << \"Total cost of input:\" << in_total << ce << endl;\n\n        ofs << cb << \"Gate counts for output circuit [T+Td,H,P+Pd,X,Z,Y] : [\"\n            << out_cost[gl.T] << \",\" << out_cost[gl.H] << \",\"\n            << out_cost[gl.P] << \",\" << out_cost[gl.X] << \",\"\n            << out_cost[gl.Z] << \",\" << out_cost[gl.Y] << \"]\" << ce << endl;\n        ofs << cb << \"Total cost of output:\" << out_total << ce << endl;\n\n        if( ro.math_fr )\n            out.toMathStream(ofs);\n        else\n            out.toStreamSym(ofs);\n\n        ofs.close();\n        ifs.close();\n    }\n\n    exactDecomposer ed;\n    const ResynthOptions& ro;\n};\n\n////////////////////////////////////////////////////////////////////\n\n/// \\brief Options for epsilon net generation\nstruct enetOptions\n{\n    /// \\brief If one element specified -- upper bound for sde of epsilon net to be\n    /// generated. If two elements specified -- interval of sde to be generated.\n    vector<int> epsilon_net_layers;\n};\n\n////////////////////////////////////////////////////////////////////\n\nstruct enetApplication\n{\n    enetApplication( const enetOptions& options ) :\n        m_options(options)\n    {}\n\n    /// \\brief Checks if all layers generated on initial state are available\n    void check_initial()\n    {\n        initial_ok = true;\n        if( m_layers[0] == 0 )\n            initial_ok = false;\n\n        for( int i = 2; (i < initial_end) && initial_ok ; ++i )\n            if( m_layers[i] == 0 ) initial_ok = false;\n    }\n\n    /// \\brief Collects information about parts of epsilon net available\n    void check_files()\n    {\n         m_layers.resize(100,0);\n         // collect information about available layers\n         for( int i = 0; i < 100; ++i )\n         {\n             string name = netGenerator::fileName(i);\n             ifstream ifs(name);\n             if( !ifs )\n                 m_layers[i] = 0;\n             else\n                 m_layers[i] = 1;\n         }\n    }\n\n    /// \\brief Generates all layers with \\f$ sde(|\\cdot|^2) \\f$ in the interval [st,end)\n    void generate( int st, int end )\n    {\n        if( ! initial_ok && st < initial_end )\n            m_ng.generateInitial();\n\n        for( int i = max(initial_end,st) ; i < end; ++i )\n        {\n            if( m_layers[i] == 0 )\n            {\n                epsilonnet base_net;\n                base_net.loadFromFile( netGenerator::fileName(i-1).c_str() );\n                unique_ptr<epsilonnet> res( netGenerator::generate( base_net ) );\n                res->saveToFile( netGenerator::fileName(i).c_str() );\n            }\n        }\n    }\n\n    /// \\brief Do the work\n    void process()\n    {\n        check_files();\n        check_initial();\n\n        int sz  = m_options.epsilon_net_layers.size();\n        int b = m_options.epsilon_net_layers[0];\n        switch( sz )\n        {\n        case 1:\n            generate(0,b + 1);\n            break;\n        case 2:\n            generate(b,m_options.epsilon_net_layers[1] + 1);\n            break;\n        default:\n            std::cerr << \"Wrong number of parameters. See help.\" << endl;\n        }\n    }\n\n    void print_error_message()\n    {\n        cout << \"Epsilon net files a not available, use --epsilon-net option\" << endl\n             << \"to generate them.\" << endl;\n    }\n\n    bool check()\n    {\n        int st  = 0;\n        int end = m_options.epsilon_net_layers[0] + 1;\n        check_files();\n        check_initial();\n\n        if( ! initial_ok && st < initial_end )\n        {\n            print_error_message();\n            return false;\n        }\n\n        for( int i = max(initial_end,st) ; i < end; ++i )\n        {\n            if( m_layers[i] == 0 )\n            {\n                print_error_message();\n                return false;\n            }\n        }\n        return true;\n    }\n\n    const enetOptions& m_options;       ///< Application options\n    std::vector<int> m_layers;          ///< Ones for available layers, zeros for not availible layers\n    static const int initial_end;       ///< Maximal layer generated on initial state\n    bool initial_ok;                    ///< If all initial layers are availible\n    netGenerator m_ng;                  ///< Epsilon net generator\n};\n\nconst int enetApplication::initial_end = 21;\n\n////////////////////////////////////////////////////////////////////\n\nstruct RandomRotationsOpts\n{\n    string filename;\n    int samples;\n};\n\n////////////////////////////////////////////////////////////////////\n\nstruct RotationGeneratorApp\n{\n    RotationGeneratorApp( RandomRotationsOpts& opts) :\n        m_opt(opts)\n    {}\n    /// \\brief Generates file with rotations by random angle around random axis\n    void process()\n    {\n        ofstream ofs( m_opt.filename.c_str() );\n        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n        std::default_random_engine generator (seed);\n        static const double PI = 3.1415926535897932384626433832795028841971693993751;\n        normal_distribution<double> nd(0.0,1.0);\n        uniform_real_distribution<double> urd( 0.0, 2*PI );\n\n        for( int i = 0; i < m_opt.samples; ++i )\n        {\n            double x = nd(generator);\n            double y = nd(generator);\n            double z = nd(generator);\n            double norm = sqrt(x*x + y*y + z*z);\n            x /= norm;\n            y /= norm;\n            z /= norm;\n            double phi = urd(generator);\n            ofs << phi << \" \" << x << \" \" << y << \" \" << z << endl;\n        }\n    }\n\n    const RandomRotationsOpts& m_opt;\n};\n\n////////////////////////////////////////////////////////////////////\nstruct exactDecompositionOpts\n{\n  std::string filename;\n};\n\n////////////////////////////////////////////////////////////////////\nstruct exactDecompositionApplication\n{\n  exactDecompositionApplication( const exactDecompositionOpts& opts ) :\n    m_opts(opts)\n  {\n  }\n\n  void run()\n  {\n    ifstream ifs;\n    ifs.exceptions(std::fstream::badbit | std::fstream::failbit);\n    ifs.open(m_opts.filename);\n    matrix2x2<mpz_class> exact_uni;\n    circuit c;\n    ifs >> exact_uni;\n    cout << exact_uni << endl;\n    ed.decompose(exact_uni,c);\n    c.toStream(cout);\n  }\n\n  exactDecompositionOpts m_opts;\n  exactDecomposer ed;\n};\n\n////////////////////////////////////////////////////////////////////\n\nvoid print_about_message()\n{\ncout << \"Copyright (c) 2012 Vadym Kliuchnikov sqct(dot)software(at)gmail(dot)com\" << endl << endl;\ncout << \"SQCT is free software: you can redistribute it and/or modify\" << endl;\ncout << \"it under the terms of the GNU Lesser General Public License as published by\" << endl;\ncout << \"the Free Software Foundation, either version 3 of the License, or\" << endl;\ncout << \"(at your option) any later version.\" << endl;\ncout << \"\" << endl;\ncout << \"SQCT is distributed in the hope that it will be useful,\" << endl;\ncout << \"but WITHOUT ANY WARRANTY; without even the implied warranty of\" << endl;\ncout << \"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\" << endl;\ncout << \"GNU Lesser General Public License for more details.\" << endl;\ncout << \"\" << endl;\ncout << \"You should have received a copy of the GNU Lesser General Public License\" << endl;\ncout << \"along with SQCT.  If not, see <http://www.gnu.org/licenses/>.\" << endl;\ncout << \"\" << endl;\ncout << \"The program code based on results of http://arxiv.org/abs/1206.5236.\" << endl;\ncout << \"It also implements the version of Solovay Kitaev algorithm described\" << endl;\ncout << \"in http://arxiv.org/abs/quant-ph/0505030. \" << endl;\ncout << \"\" << endl;\ncout << \"The list of used libraries, corresponding licenses and authors:\" << endl<< endl;\ncout << \"Boost | Boost Software License\" << endl<< endl;\ncout << \"The GNU Multiple Precision Arithmetic Library | GNU Lesser General Public License v3\" << endl;\ncout << \"(by Free Software Foundation, Inc.)\" << endl<< endl;\ncout << \"The GNU MPFR Library the library | GNU Lesser General Public License v3\" << endl;\ncout << \"(by Free Software Foundation, Inc.,\" << endl;\ncout << \" Contributed by the AriC and Caramel projects, INRIA. )\" << endl << endl;\ncout << \"mpfr::real | GNU Lesser General Public License v3\" << endl;\ncout << \"(by Christian Schneider <software(at)chschneider(dot)eu> )\" << endl;\ncout << \"\" << endl;\ncout << \"Source code of this program can be obtained from: \" << endl;\n}\n\n////////////////////////////////////////////////////////////////////\n\nint main(int ac, char* av[])\n{\n    // help\n    string help_topic = \"\";\n    // sk application parameters\n    SKOptions sko;\n    // epsilon net generation\n    enetOptions eopt;\n    // resynthesise\n    ResynthOptions ro;\n    // randomized rotations\n    RandomRotationsOpts rro;\n    // exact decomposition\n    exactDecompositionOpts edo;\n\n    try {\n\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()\n\n            (\"help,H\", po::value< string >(&help_topic)->implicit_value(\"\"),\n             \"Produce help message, see help <option name> for more details \"\n             \"about specific option.\")\n\n            (\"in,I\", po::value< string >(&(sko.in_filename)),\n             \"File name with unitaries for approximation.\")\n\n            (\"iterations,N\", po::value< int >(&(sko.iterations_default))->default_value(3),\n             \"Default number of iteration used by the Solovay Kitaev algorithm, \"\n             \"when not specified in input file.\")\n\n            (\"angle,A\", po::value< bool >(&(sko.angle))->zero_tokens(),\n             \"When true program interprets first entry in each line of input file as \"\n             \"as rotation angle, and as denominator of Pi.\")\n\n            (\"out,O\", po::value< string >(&(sko.out_filename))->default_value(\"out.csv\"),\n             \"File name with summary about \"\n             \"unitary approximation results.\")\n\n            (\"math-fr,F\", po::value< bool >(&(sko.math_fr))->zero_tokens(),\n             \"Should output be Mathematica friendly. \"\n             \"Default output format is CSV.\")\n\n            (\"dotqc,C\", po::value< bool >(&(sko.write_dot_qc))->zero_tokens(),\n             \"Should we output dotqc file for each generated circuit.\")\n\n            (\"out-dir,D\", po::value< string >(&(sko.out_dir))->default_value(\"out\"),\n             \"Directory to output circuits.\")\n\n            (\"max-sde,M\", po::value< int >(&(sko.max_sde))->default_value(30),\n             \"Maximal value of sde to use during intial approximation step.\")\n\n            (\"epsilon-net,E\", po::value< vector<int> >(&(eopt.epsilon_net_layers))->multitoken(),\n             \"Generates epsilon net layers. If one values specified generates all layers \"\n             \"with sde(|.|^2) less or equal than this value. If two values specified then sde(|.|^2) \"\n             \"of result lies in interval [first,second] \")\n\n            (\"theory-topt\",\n             \"Verifies conjecture about T optimality \")\n\n            (\"theory-hopt\",\n             \"Performs brute force check necessary for proof of result in Appendix 2 \"\n             \"in http://arxiv.org/abs/1206.5236\")\n\n            (\"theory-correctness\",\n             \"Performs brute force check described by Algoritm 2 \"\n             \"in http://arxiv.org/abs/1206.5236 ( proves Lemma 3 ).\")\n\n            (\"resynth,S\", po::value< vector<string> >(&(ro.circuit_files) )->multitoken(),\n             \"Resynthesize circuit. Output may differ from original by global phase.\")\n\n            (\"reverse\", po::value< bool >(& (ro.reverse) )->zero_tokens(),\n             \"True if circuit file should be interpreted in matrix multiplication order.\")\n\n            (\"random-rot\", po::value< int >(&(rro.samples)),\n             \"Generates file with specified number of random rotations.\")\n\n            (\"exact\", po::value< string >(&(edo.filename)),\n             \"Performs an exact decomposition of a unitary over the ring.\")\n\n            (\"about\", \"Information about the program.\")\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(\"resynth\") ) {\n            ro.math_fr = sko.math_fr;\n            ResynthApplication ra(ro);\n            ra.process();\n            return 0;\n        }\n\n        if(vm.count(\"epsilon-net\"))\n        {\n            enetApplication eapp(eopt);\n            eapp.process();\n            return 0;\n        }\n\n        if( vm.count(\"theory-correctness\") ) {\n            cout << is_theorem_true() << endl;\n            return 0;\n        }\n\n        if( vm.count(\"theory-topt\") ) {\n            toptimalitytest tt;\n            return 0;\n        }\n\n        if( vm.count(\"theory-hopt\") ) {\n            hoptimalitytest ht;\n            return 0;\n        }\n\n        if ( vm.count(\"random-rot\") ) {\n            rro.filename = sko.out_filename;\n            RotationGeneratorApp rga(rro);\n            rga.process();\n            return 0;\n        }\n\n        if( vm.count(\"about\") ) {\n            print_about_message();\n            return 0;\n        }\n\n        if ( vm.count(\"in\") ) {\n            eopt.epsilon_net_layers.clear();\n            eopt.epsilon_net_layers.push_back(sko.max_sde);\n            enetApplication ea(eopt);\n            if( ea.check() )\n            {\n                SKApplication app(sko);\n                app.process();\n            }\n            return 0;\n        }\n\n        if( vm.count(\"exact\") ) {\n          exactDecompositionApplication eda(edo);\n          eda.run();\n          return 0;\n        }\n\n        if ( true ) {\n            if( !print_help(help_topic) )\n                cout << desc << endl;\n            return 0;\n        }\n\n\n    }\n    catch(exception& e) {\n        cerr << \"Error: \" << e.what() << endl;\n        return 1;\n    }\n    catch(...) {\n        cerr << \"Exception of unknown type!\" << endl;\n        return 1;\n    }\n}\n", "meta": {"hexsha": "401cac101e7197609cdb9134aa0b397adf58a942", "size": 27426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rotations/sqct/main.cpp", "max_stars_repo_name": "teaguetomesh/ScaffCC", "max_stars_repo_head_hexsha": "52b087a00ac19384a736b4c64631ca67bd1d8054", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-05T23:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T23:28:35.000Z", "max_issues_repo_path": "Rotations/sqct/main.cpp", "max_issues_repo_name": "teaguetomesh/ScaffCC", "max_issues_repo_head_hexsha": "52b087a00ac19384a736b4c64631ca67bd1d8054", "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": "Rotations/sqct/main.cpp", "max_forks_repo_name": "teaguetomesh/ScaffCC", "max_forks_repo_head_hexsha": "52b087a00ac19384a736b4c64631ca67bd1d8054", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-05T23:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T23:42:06.000Z", "avg_line_length": 34.1119402985, "max_line_length": 123, "alphanum_fraction": 0.5343105083, "num_tokens": 6449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.04272219404236619, "lm_q1q2_score": 0.02036052832938554}}
{"text": "//\n// Copyright (c) 2004-2006\n// Andreas Kloeckner\n//\n// Permission to use, copy, modify, distribute and sell this software\n// and its documentation for any purpose is hereby granted without fee,\n// provided that the above copyright notice appear in all copies and\n// that both that copyright notice and this permission notice appear\n// in supporting documentation.  The authors make no representations\n// about the suitability of this software for any purpose.\n// It is provided \"as is\" without express or implied warranty.\n//\n\n\n\n\n#ifndef HEADER_SEEN_PYUBLAS_ELEMENTWISE_OP_HPP\n#define HEADER_SEEN_PYUBLAS_ELEMENTWISE_OP_HPP\n\n\n\n\n#include <cmath>\n#include <boost/numeric/ublas/functional.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n\n\n\n\nnamespace pyublas {\n  template <class Functor>\n  struct unary_op\n  {\n    template<class E> \n    static\n    typename boost::numeric::ublas::vector_unary_traits<E, Functor>::result_type\n    apply(const boost::numeric::ublas::vector_expression<E> &e) \n    {\n      typedef typename boost::numeric::ublas::vector_unary_traits<E, Functor>\n        ::expression_type expression_type;\n      return expression_type(e());\n    }\n\n    template<class E>\n    static\n    typename boost::numeric::ublas::matrix_unary1_traits<E, Functor>::result_type\n    apply(const boost::numeric::ublas::matrix_expression<E> &e) \n    {\n      typedef typename boost::numeric::ublas::matrix_unary1_traits<E, Functor>\n        ::expression_type expression_type;\n      return expression_type(e());\n    }\n  };\n\n\n\n\n  template <class Functor>\n  struct binary_op\n  {\n    template<class E1, class E2> \n    static\n    typename boost::numeric::ublas::vector_binary_traits<E1, E2, Functor>::result_type\n    apply(\n        const boost::numeric::ublas::vector_expression<E1> &e1,\n        const boost::numeric::ublas::vector_expression<E2> &e2\n        ) \n    {\n      typedef typename boost::numeric::ublas::vector_binary_traits<E1, E2, Functor> \n        ::expression_type expression_type;\n      return expression_type(e1(), e2());\n    }\n\n    template<class E1, class E2> \n    static\n    typename boost::numeric::ublas::matrix_binary_traits<E1, E2, Functor>::result_type\n    apply(\n        const boost::numeric::ublas::matrix_expression<E1> &e1,\n        const boost::numeric::ublas::matrix_expression<E2> &e2\n        ) \n    {\n      typedef typename boost::numeric::ublas::matrix_binary_traits<E1, E2, Functor> \n        ::expression_type expression_type;\n      return expression_type(e1(), e2());\n    }\n  };\n\n\n\n\n  namespace unary_ops\n  {\n    class fabs : public boost::numeric::ublas::scalar_real_unary_functor<double>\n    {\n      private:\n        typedef boost::numeric::ublas::scalar_unary_functor<double> super;\n\n      public:\n        static super::result_type apply(super::argument_type x)\n        {\n          return ::std::fabs(x);\n        }\n    };\n  }\n  \n\n\n  \n  namespace binary_ops\n  {\n    template<class T1, class T2=T1>\n    class max : public boost::numeric::ublas::scalar_binary_functor<T1, T2> \n    {\n      private:\n        typedef boost::numeric::ublas::scalar_binary_functor<T1, T2> super;\n\n      public:\n        static typename super::result_type apply(\n            typename super::argument1_type t1, \n            typename super::argument1_type t2) \n        {\n          if (t1 >= t2)\n            return t1;\n          else\n            return t2;\n        }\n    };\n\n\n\n\n    template<class T1, class T2=T1>\n    class min : public boost::numeric::ublas::scalar_binary_functor<T1, T2> \n    {\n      private:\n        typedef boost::numeric::ublas::scalar_binary_functor<T1, T2> super;\n\n      public:\n        static typename super::result_type apply(\n            typename super::argument1_type t1, \n            typename super::argument1_type t2) \n        {\n          if (t1 <= t2)\n            return t1;\n          else\n            return t2;\n        }\n    };\n  }\n\n\n\n  \n  // square sum ---------------------------------------------------------------\n  template<class V>\n  struct vector_square_sum : \n    public boost::numeric::ublas::vector_scalar_real_unary_functor<V> \n  {\n    private:\n      typedef boost::numeric::ublas::vector_scalar_real_unary_functor<V> super;\n\n    public:\n      typedef typename super::real_type real_type;\n      typedef typename super::value_type value_type;\n      typedef typename super::result_type result_type;\n\n      template<class E>\n      static result_type \n      apply(const boost::numeric::ublas::vector_expression<E> &e) \n      {\n        using namespace boost::numeric::ublas;\n\n        real_type t = real_type ();\n        typedef typename E::size_type vector_size_type;\n        vector_size_type size (e ().size ());\n        for (vector_size_type i = 0; i < size; ++ i) {\n          typename super::real_type u (\n              type_traits<value_type>::norm_2 (e () (i)));\n          t +=  u * u;\n        }\n        return t;\n      }\n\n      // Dense case\n      template<class D, class I>\n      static result_type apply(D size, I it) \n      {\n        using namespace boost::numeric::ublas;\n\n        real_type t = real_type ();\n        while (-- size >= 0) {\n          real_type u (type_traits<value_type>::norm_2 (*it));\n          t +=  u * u;\n          ++ it;\n        }\n        return t;\n      }\n\n      // Sparse case\n      template<class I>\n      static result_type apply(I it, const I &it_end) \n      {\n        using namespace boost::numeric::ublas;\n\n        real_type t = real_type ();\n        while (it != it_end) {\n          real_type u (type_traits<value_type>::norm_2 (*it));\n          t +=  u * u;\n          ++ it;\n        }\n        return t;\n      }\n  };\n\n  template<class E>\n  inline \n  typename boost::numeric::ublas::vector_scalar_unary_traits<E, vector_square_sum<E> >::result_type\n  square_sum(const boost::numeric::ublas::vector_expression<E> &e) \n  {\n    typedef typename boost::numeric::ublas::\n      vector_scalar_unary_traits<E, vector_square_sum<E> >::expression_type \n      expression_type;\n    return expression_type(e());\n  }\n}\n\n\n\n\n#endif\n", "meta": {"hexsha": "00146ee6ec3299d16f5a3a7443f1ccc291fb9931", "size": 6049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "torlib/xorcpp/pyublas/src/cpp/pyublas/elementwise_op.hpp", "max_stars_repo_name": "ivanpustogarov/torscan", "max_stars_repo_head_hexsha": "d5aecede2070037b84e4de99f48aafbe28353386", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "torlib/xorcpp/pyublas/src/cpp/pyublas/elementwise_op.hpp", "max_issues_repo_name": "ivanpustogarov/torscan", "max_issues_repo_head_hexsha": "d5aecede2070037b84e4de99f48aafbe28353386", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "torlib/xorcpp/pyublas/src/cpp/pyublas/elementwise_op.hpp", "max_forks_repo_name": "ivanpustogarov/torscan", "max_forks_repo_head_hexsha": "d5aecede2070037b84e4de99f48aafbe28353386", "max_forks_repo_licenses": ["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.0732758621, "max_line_length": 99, "alphanum_fraction": 0.6240700942, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.04336579783664016, "lm_q1q2_score": 0.020329479541985544}}
{"text": "/*ckwg +29\n * Copyright 2015-2016 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/**\n * \\file\n * \\brief vxl estimate fundamental matrix implementation\n */\n\n#include \"estimate_fundamental_matrix.h\"\n\n#include <vital/vital_foreach.h>\n\n#include <vital/types/feature.h>\n#include <arrows/vxl/camera.h>\n#include <arrows/core/epipolar_geometry.h>\n\n#include <vgl/vgl_point_2d.h>\n#include <Eigen/LU>\n\n#include <vpgl/algo/vpgl_fm_compute_8_point.h>\n#include <vpgl/algo/vpgl_fm_compute_7_point.h>\n\nusing namespace kwiver::vital;\n\nnamespace kwiver {\nnamespace arrows {\nnamespace vxl {\n\n/// Private implementation class\nclass estimate_fundamental_matrix::priv\n{\npublic:\n  /// Constructor\n  priv()\n  : precondition(true),\n    method(EST_8_POINT)\n  {\n  }\n\n  enum method_t {EST_7_POINT, EST_8_POINT};\n\n  bool precondition;\n  method_t method;\n};\n\n\n/// Constructor\nestimate_fundamental_matrix\n::estimate_fundamental_matrix()\n: d_(new priv)\n{\n}\n\n\n/// Destructor\nestimate_fundamental_matrix\n::~estimate_fundamental_matrix()\n{\n}\n\n\n/// Get this algorithm's \\link vital::config_block configuration block \\endlink\nvital::config_block_sptr\nestimate_fundamental_matrix\n::get_configuration() const\n{\n  // get base config from base class\n  vital::config_block_sptr config =\n      vital::algo::estimate_fundamental_matrix::get_configuration();\n\n  config->set_value(\"precondition\", d_->precondition,\n                    \"If true, precondition the data before estimating the \"\n                    \"fundamental matrix\");\n\n  std::string method_name = d_->method == priv::EST_8_POINT\n                            ? \"EST_8_POINT\" : \"EST_7_POINT\";\n  config->set_value(\"method\", method_name,\n                    \"Fundamental matrix estimation method to use. \"\n                    \"(Note: does not include RANSAC).  Choices are\\n\"\n                    \"  EST_7_POINT\\n\"\n                    \"  EST_8_POINT\");\n\n  return config;\n}\n\n\n/// Set this algorithm's properties via a config block\nvoid\nestimate_fundamental_matrix\n::set_configuration(vital::config_block_sptr config)\n{\n\n  d_->precondition = config->get_value<bool>(\"precondition\",\n                                             d_->precondition);\n  std::string method_name = config->get_value<std::string>(\"method\");\n  if( method_name == \"EST_7_POINT\" )\n  {\n    d_->method = priv::EST_7_POINT;\n  }\n  else\n  {\n    d_->method = priv::EST_8_POINT;\n  }\n}\n\n\n/// Check that the algorithm's current configuration is valid\nbool\nestimate_fundamental_matrix\n::check_configuration(vital::config_block_sptr config) const\n{\n  return true;\n}\n\n\n/// Estimate an essential matrix from corresponding points\nfundamental_matrix_sptr\nestimate_fundamental_matrix\n::estimate(const std::vector<vector_2d>& pts1,\n           const std::vector<vector_2d>& pts2,\n           std::vector<bool>& inliers,\n           double inlier_scale) const\n{\n  vcl_vector<vgl_homg_point_2d<double> > right_points, left_points;\n  VITAL_FOREACH(const vector_2d& v, pts1)\n  {\n    right_points.push_back(vgl_homg_point_2d<double>(v.x(), v.y()));\n  }\n  VITAL_FOREACH(const vector_2d& v, pts2)\n  {\n    left_points.push_back(vgl_homg_point_2d<double>(v.x(), v.y()));\n  }\n\n  vpgl_fundamental_matrix<double> vfm;\n  if( d_->method == priv::EST_8_POINT )\n  {\n    vpgl_fm_compute_8_point fm_compute(d_->precondition);\n    fm_compute.compute(right_points, left_points, vfm);\n  }\n  else\n  {\n    std::vector< vpgl_fundamental_matrix<double>* > vfms;\n    vpgl_fm_compute_7_point fm_compute(d_->precondition);\n    fm_compute.compute(right_points, left_points, vfms);\n    // TODO use the multiple solutions in a RANSAC framework\n    // For now, only keep the first solution\n    vfm = *vfms[0];\n    VITAL_FOREACH(auto v, vfms)\n    {\n      delete v;\n    }\n  }\n\n  matrix_3x3d F(vfm.get_matrix().data_block());\n  F.transposeInPlace();\n\n  fundamental_matrix_sptr fm(new fundamental_matrix_d(F));\n  inliers = arrows::mark_fm_inliers(*fm, pts1, pts2, inlier_scale);\n  return fm;\n}\n\n\n} // end namespace vxl\n} // end namespace arrows\n} // end namespace kwiver\n", "meta": {"hexsha": "289f76efbcf42930214478a53b07911ca5fa6eb5", "size": 5495, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "arrows/vxl/estimate_fundamental_matrix.cxx", "max_stars_repo_name": "dstoup/kwiver", "max_stars_repo_head_hexsha": "a3a36317b446baf0feb6274235ab1ac6b4329ead", "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": "arrows/vxl/estimate_fundamental_matrix.cxx", "max_issues_repo_name": "dstoup/kwiver", "max_issues_repo_head_hexsha": "a3a36317b446baf0feb6274235ab1ac6b4329ead", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/vxl/estimate_fundamental_matrix.cxx", "max_forks_repo_name": "dstoup/kwiver", "max_forks_repo_head_hexsha": "a3a36317b446baf0feb6274235ab1ac6b4329ead", "max_forks_repo_licenses": ["BSD-3-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.324742268, "max_line_length": 81, "alphanum_fraction": 0.71155596, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.043365795363929295, "lm_q1q2_score": 0.020329477739118827}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_Measurement_def.hpp\n//! \\author Alex Robinson\n//! \\brief  The measurement class declaration.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_MEASUREMENT_DEF_HPP\n#define UTILITY_MEASUREMENT_DEF_HPP\n\n// Std Lib Includes\n#include <cmath>\n\n// Boost Includes\n#include <boost/io/ios_state.hpp>\n\nnamespace Utility{\n\n// Constructor\ntemplate<typename T>\nMeasurement<T>::Measurement( const Measurement<T>::ValueType& value, \n\t\t\t     const Measurement<T>::ValueType& uncertainty )\n  : d_value( value ),\n    d_uncertainty( uncertainty )\n{ \n  // Make sure the value is valid\n  testPrecondition( !ST::isnaninf( value ) );\n  // Make sure the uncertainty is valid\n  testPrecondition( !ST::isnaninf( uncertainty ) );\n  testPrecondition( uncertainty >= 0.0 );\n}\n\n// Copy constructor\ntemplate<typename T>\nMeasurement<T>::Measurement( const Measurement<T>& other_measurement )\n  : d_value( other_measurement.d_value ),\n    d_uncertainty( other_measurement.d_uncertainty )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !ST::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !ST::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n}\n\n// Print method\ntemplate<typename T>\ninline void Measurement<T>::print( std::ostream& os ) const\n{\n  boost::io::ios_precision_saver preision_saver(os);\n  boost::io::ios_flags_saver flags_saver(os);\n\n  os << d_value << \"(+/-\" << d_uncertainty << \")\";\n}\n\n// Return the value of the measurement\ntemplate<typename T>\ninline const typename Measurement<T>::ValueType& \nMeasurement<T>::getValue() const\n{\n  return d_value;\n}\n\n// Return the uncertainty of the measurement\ntemplate<typename T>\ninline const typename Measurement<T>::ValueType& \nMeasurement<T>::getUncertainty() const\n{\n  return d_uncertainty;\n}\n\n// Return the relative uncertainty of the measurement\ntemplate<typename T>\ninline const typename Measurement<T>::ValueType\nMeasurement<T>::getRelativeUncertainty() const\n{\n  if( d_value != 0.0 )\n    return d_uncertainty/fabs(d_value);\n  else\n    return 0.0;\n}\n\n// Return the lower bound of the measurement\ntemplate<typename T>\ninline const typename Measurement<T>::ValueType \nMeasurement<T>::getLowerBound() const\n{\n  return d_value - d_uncertainty;\n}\n\n// Return the upper bound of the measurement\ntemplate<typename T>\ninline const typename Measurement<T>::ValueType\nMeasurement<T>::getUpperBound() const\n{\n  return d_value + d_uncertainty;\n}\n\n// Value access operator\ntemplate<typename T>\ninline Measurement<T>::operator Measurement<T>::ValueType() const\n{\n  return d_value;\n}\n\n// In-place addition operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator+=( \n\t\t\t\t       const Measurement<T>::ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !ST::isnaninf( value ) );\n  \n  d_value += value;\n\n  return *this;\n}\n\n// In-place addition operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator+=(\n\t\t\t\t      const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !ST::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !ST::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n  \n  d_value += other_measurement.d_value;\n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( d_uncertainty*d_uncertainty +\n\t\t\t     other_measurement.d_uncertainty*\n\t\t\t     other_measurement.d_uncertainty );\n\n  return *this;\n}\n\n// In-place subtraction operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator-=( \n\t\t\t\t       const Measurement<T>::ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !ST::isnaninf( value ) );\n  \n  d_value -= value;\n\n  return *this;\n}\n\n// In-place subtraction operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator-=( \n\t\t\t\t      const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !ST::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !ST::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n  \n  d_value -= other_measurement.d_value;\n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( d_uncertainty*d_uncertainty +\n\t\t\t     other_measurement.d_uncertainty*\n\t\t\t     other_measurement.d_uncertainty );\n\n  return *this;\n}\n\n// In-place multiplication operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator*=( \n\t\t\t\t       const Measurement<T>::ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !ST::isnaninf( value ) );\n  \n  d_value *= value;\n  \n  d_uncertainty *= fabs( value );\n\n  return *this;\n}\n\n// In-place multiplication operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator*=( \n\t\t\t\t      const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !ST::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !ST::isnaninf( other_measurement.d_uncertainty ) );\n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( d_uncertainty*d_uncertainty*\n\t       other_measurement.d_value*other_measurement.d_value +\n\t       other_measurement.d_uncertainty*other_measurement.d_uncertainty*\n\t       d_value*d_value );\n\n  d_value *= other_measurement.d_value;\n    \n  return *this;\n}\n\n// In-place division operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator/=( \n\t\t\t\t       const Measurement<T>::ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !ST::isnaninf( value ) );\n  testPrecondition( value != 0.0 );\n  \n  d_value /= value;\n\n  d_uncertainty /= fabs( value );\n\n  return *this;\n}\n\n// In-place division operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T>::operator/=( \n\t\t\t\t      const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !ST::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !ST::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_value != 0.0 );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n  \n  double other_value_sqr = other_measurement.d_value*other_measurement.d_value;\n\n  double term_1 = d_uncertainty*d_uncertainty/other_value_sqr;\n  \n  double term_2 = \n    other_measurement.d_uncertainty*other_measurement.d_uncertainty*\n    d_value*d_value/(other_value_sqr*other_value_sqr);\n    \n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( term_1 + term_2 );\n\n  d_value /= other_measurement.d_value;\n\n  return *this;\n}\n\n} // end Utility namespace\n\n#endif // end UTILITY_MEASUREMENT_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_Measurement_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "279ace4e8c9849b5dc38c8befde88f795a218bd2", "size": 7171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/src/Utility_Measurement_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/core/src/Utility_Measurement_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/core/src/Utility_Measurement_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": 27.7945736434, "max_line_length": 79, "alphanum_fraction": 0.6958583182, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.046724960119470534, "lm_q1q2_score": 0.020277766635551565}}
{"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_MULT_INCLUDE\n#define MTL_MULT_INCLUDE\n\n#include <boost/numeric/mtl/config.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/flatcat.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/operation/dmat_dmat_mult.hpp>\n#include <boost/numeric/mtl/operation/smat_smat_mult.hpp>\n#include <boost/numeric/mtl/operation/smat_dmat_mult.hpp>\n#include <boost/numeric/mtl/operation/mat_vec_mult.hpp>\n#include <boost/numeric/mtl/operation/rvec_mat_mult.hpp> // Row vector times matrix\n#include <boost/numeric/mtl/operation/mult_specialize.hpp>\n#include <boost/numeric/mtl/operation/assign_mode.hpp>\n#include <boost/numeric/mtl/operation/mult_assign_mode.hpp>\n#include <boost/numeric/mtl/utility/enable_if.hpp>\n\n#include <boost/mpl/if.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace mat {\n\n\n/// Multiplication: mult(a, b, c) computes c= a * b; \n/** The 3 types must be compatible, e.g. all three matrices or b and c are column vectors and a is a matrix.\n    The dimensions are checked at compile time. **/\ntemplate <typename A, typename B, typename C>\ntypename mtl::traits::enable_if_matrix<A>::type\ninline mult(const A& a, const B& b, C& c)\n{\n    vampir_trace<4010> tracer;\n    MTL_DEBUG_THROW_IF(static_cast<const void*>(&a) == static_cast<const void*>(&c) \n\t\t       || static_cast<const void*>(&b) == static_cast<const void*>(&c),\n\t\t       argument_result_conflict());\n\n    // dispatch between matrices, vectors, and scalars\n    using mtl::traits::shape_flatcat;\n    gen_mult(a, b, c, assign::assign_sum(), shape_flatcat<A>(), shape_flatcat<B>(), shape_flatcat<C>());\n                                            // typename category<A>::type(), typename category<B>::type(), typename category<C>::type());\n}\n\n\n/// Multiplication: mult_add(a, b, c) computes c+= a * b; \n/** The 3 types must be compatible, e.g. all three matrices or b and c are column vectors and a is a matrix.\n    The dimensions are checked at compile time. **/\ntemplate <typename A, typename B, typename C>\ntypename mtl::traits::enable_if_matrix<A>::type\ninline mult_add(const A& a, const B& b, C& c)\n{\n    vampir_trace<4010> tracer;\n    // dispatch between matrices, vectors, and scalars\n    using mtl::traits::shape_flatcat;\n    gen_mult(a, b, c, assign::plus_sum(), shape_flatcat<A>(), shape_flatcat<B>(), shape_flatcat<C>());\n                                          // typename category<A>::type(), typename category<B>::type(), typename category<C>::type());\n}\n\n\n/// Four term multiplication: mult(a, x, y, z) computes z= a * x + y; \n/** The 4 types must be compatible, i.e. a*x must be assignable to z and z must be incrementable by y.\n    Right now, it is not more efficient than z= a * x; z+= y. For compatibility with MTL2. **/\ntemplate <typename A, typename X, typename Y, typename Z>\ninline void mult(const A& a, const X& x, const Y& y, Z& z)\n{\n    vampir_trace<4010> tracer;\n    mult(a, x, z);\n    z+= y;\n}\n\n\n// Matrix multiplication\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void gen_mult(const MatrixA& a, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::matrix>, tag::flat<tag::matrix>, tag::flat<tag::matrix>)\n{\n    vampir_trace<4011> tracer;\n#if 1\n    MTL_DEBUG_THROW_IF((const void*)&a == (const void*)&c || (const void*)&b == (const void*)&c, argument_result_conflict());\n#else \n    if ((const void*)&a == (const void*)&c || (const void*)&b == (const void*)&c) {\n\tC tmp(num_rows(c), num_cols(c)); \n\tmult(a, b, tmp);\n\tswap(C, tmp);\n\treturn;\n    }\n#endif\n\n    MTL_DEBUG_THROW_IF(num_rows(a) != num_rows(c) || num_cols(a) != num_rows(b) || num_cols(b) != num_cols(c), incompatible_size());\n    // dispatch between dense and sparse\n    using mtl::traits::sparsity_flatcat;\n    mat_mat_mult(a, b, c, Assign(), sparsity_flatcat<MatrixA>(), sparsity_flatcat<MatrixB>(), sparsity_flatcat<MatrixC>());\n\t\t // typename category<MatrixA>::type(), typename category<MatrixB>::type(), typename category<MatrixC>::type());\n}\n\n\n/// Dense matrix multiplication\n/**  The function for dense matrix multiplication defines a default multiplication functor. \n     Alternatively the user can define his own functors for specific triplets of matrix types, \n     see detail::dmat_dmat_mult_specialize.\n     The default functor for dense matrix multiplication is: \n     -# Use BLAS   if available, otherwise\n     -# Recursive multiplication with:\n        -# Platform optimized mult on blocks   if available, otherwise\n        -# Tiled multiplication on blocks      if available, otherwise\n        -# Naive multiplication on blocks\n     -# Naive multiplication on entire matrices if recursion is not available\n**/\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::dense>, tag::flat<tag::dense>, tag::flat<tag::dense>)\n{\n    vampir_trace<4012> tracer;\n    using assign::plus_sum; using assign::assign_sum; \n\n    static const unsigned long tiling1= detail::dmat_dmat_mult_tiling1<MatrixA, MatrixB, MatrixC>::value;\n    static const unsigned long tiling2= detail::dmat_dmat_mult_tiling2<MatrixA, MatrixB, MatrixC>::value;\n    typedef gen_tiling_dmat_dmat_mult_t<tiling1, tiling2, plus_sum>    tiling_mult_t;\n\n    typedef gen_platform_dmat_dmat_mult_t<plus_sum, tiling_mult_t>     platform_mult_t;\n    typedef gen_recursive_dmat_dmat_mult_t<platform_mult_t>            recursive_mult_t;\n    typedef gen_blas_dmat_dmat_mult_t<assign_sum, recursive_mult_t>    blas_mult_t;\n    typedef size_switch_dmat_dmat_mult_t<straight_dmat_dmat_mult_limit, tiling_mult_t, blas_mult_t>   variable_size_t;\n\n    typedef fully_unroll_fixed_size_dmat_dmat_mult_t<Assign>           fully_unroll_t;\n    typedef size_switch_dmat_dmat_mult_t<fully_unroll_dmat_dmat_mult_limit, fully_unroll_t, tiling_mult_t> fixed_size_t;\n\n    static const bool all_static= mtl::traits::is_static<MatrixA>::value && mtl::traits::is_static<MatrixB>::value \n\t                          && mtl::traits::is_static<MatrixC>::value;\n    typedef static_switch_dmat_dmat_mult_t<all_static, fixed_size_t, variable_size_t>  default_functor_t;\n\n    /// Use user-defined functor if provided (assign mode can be arbitrary)\n    typedef typename boost::mpl::if_<\n\tdetail::dmat_dmat_mult_specialize<MatrixA, MatrixB, MatrixC>\n      , typename detail::dmat_dmat_mult_specialize<MatrixA, MatrixB, MatrixC>::type\n      , default_functor_t\n    >::type raw_functor_type;\n\n    /// Finally substitute assign mode (consistently)\n    typename assign::mult_assign_mode<raw_functor_type, Assign>::type functor;\n\n    functor(A, b, c);\n}\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::dense>, tag::flat<tag::dense>, tag::flat<tag::sparse>)\n{\n    vampir_trace<4012> tracer;\n    // This is a useless and extremely inefficient operation!!!!\n    // We compute this with a dense matrix and copy the result back\n    dense2D<typename Collection<MatrixC>::value_type, mat::parameters<> > c_copy(num_rows(c), num_cols(c));\n    c_copy= c;\n    mat_mat_mult(A, b, c_copy, Assign(), tag::flat<tag::dense>(), tag::flat<tag::dense>(), tag::flat<tag::dense>());\n    c= c_copy;\n}\n\n/// Sparse matrix multiplication\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::sparse>, tag::flat<tag::sparse>, tag::flat<tag::sparse>)\n{\n    vampir_trace<4012> tracer;\n    smat_smat_mult(A, b, c, Assign(), typename OrientedCollection<MatrixA>::orientation(),\n\t\t   typename OrientedCollection<MatrixB>::orientation());\n}\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::sparse>, tag::flat<tag::sparse>, tag::flat<tag::dense>)\n{\n    vampir_trace<4012> tracer;\n    // This is a useless and extremely inefficient operation!!!!\n    // We compute this with a sparse matrix and copy the result back\n    compressed2D<typename Collection<MatrixC>::value_type, mat::parameters<> > c_copy(num_rows(c), num_cols(c));\n    c_copy= c;\n    smat_smat_mult(A, b, c_copy, Assign(), typename OrientedCollection<MatrixA>::orientation(),\n\t\t   typename OrientedCollection<MatrixB>::orientation());\n    c= c_copy;\n}\n\n/// Product of sparse times dense matrix\n/**  This function (specialization of mult) is intended to multiply sparse matrices with multiple matrices\n     gathered into a dense matrix.  Likewise, the resulting dense matrix corresponds to multiple vectors.\n     The default functor for this operation is: \n     -# Use tiled multiplication      if available, otherwise\n     -# Naive multiplication \n**/\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::sparse>, tag::flat<tag::dense>, tag::flat<tag::dense>)\n{\n    vampir_trace<4012> tracer;\n    using assign::plus_sum; using assign::assign_sum; \n    using namespace functor;\n\n    // static const unsigned long tiling1= detail::dmat_dmat_mult_tiling1<MatrixA, MatrixB, MatrixC>::value;\n\n    //typedef gen_smat_dmat_mult<Assign>                         default_functor_t;\n    typedef gen_tiling_smat_dmat_mult<8, Assign>                         default_functor_t;\n\n    // Finally substitute assign mode (consistently)\n    // typename assign::mult_assign_mode<raw_functor_type, Assign>::type functor;\n\n    default_functor_t functor;\n    functor(A, b, c);\n}\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::sparse>, tag::flat<tag::dense>, tag::flat<tag::sparse>)\n{\n    vampir_trace<4012> tracer;\n    // This is a useless and extremely inefficient operation!!!!\n    // We compute this with a sparse matrix and copy the result back\n    dense2D<typename Collection<MatrixC>::value_type, mat::parameters<> > c_copy(num_rows(c), num_cols(c));\n    c_copy= c;\n    mat_mat_mult(A, b, c_copy, Assign(), tag::flat<tag::sparse>(), tag::flat<tag::dense>(), tag::flat<tag::dense>());\n    c= c_copy;\n}\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::dense>, tag::flat<tag::sparse>, tag::flat<tag::dense>)\n{\n    vampir_trace<4012> tracer;\n    // This is could be a usefull operation, i.e. multiplying multiple row vectors with a sparse matrix\n    // Might be supported in future\n    // Now we compute this with a sparse matrix as first argument\n    compressed2D<typename Collection<MatrixA>::value_type, mat::parameters<> > A_copy(num_rows(A), num_cols(A));\n    A_copy= A;\n    compressed2D<typename Collection<MatrixC>::value_type, mat::parameters<> > c_copy(num_rows(c), num_cols(c));\n    c_copy= c;\n    mat_mat_mult(A_copy, b, c_copy, Assign(), tag::flat<tag::sparse>(), tag::flat<tag::sparse>(), tag::flat<tag::sparse>());\n    c= c_copy;\n}\n\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign>\ninline void mat_mat_mult(const MatrixA& A, const MatrixB& b, MatrixC& c, Assign, tag::flat<tag::dense>, tag::flat<tag::sparse>, tag::flat<tag::sparse>)\n{\n    vampir_trace<4012> tracer;\n    // This is not a usefull operation, because the result is dense\n    // Now we compute this with a sparse matrix as first argument\n    compressed2D<typename Collection<MatrixA>::value_type, mat::parameters<> > A_copy(num_rows(A), num_cols(A));\n    A_copy= A;\n    mat_mat_mult(A_copy, b, c, Assign(), tag::flat<tag::sparse>(), tag::flat<tag::sparse>(), tag::flat<tag::sparse>());\n}\n\n\n\n// Matrix vector multiplication\ntemplate <typename Matrix, typename VectorIn, typename VectorOut, typename Assign>\ninline void gen_mult(const Matrix& A, const VectorIn& v, VectorOut& w, Assign, tag::flat<tag::matrix>, tag::flat<tag::col_vector>, tag::flat<tag::col_vector>)\n{\n    vampir_trace<4011> tracer;\n    // Vector must be column vector\n    // If vector is row vector then matrix must have one column and the operation is a outer product\n    //   -> result should be a matrix too\n\n    // Check if element types are compatible (in contrast to tag dispatching, nesting is considered here)\n    MTL_STATIC_ASSERT((boost::is_same< typename ashape::mult_op<typename ashape::ashape<Matrix>::type, \n\t\t\t                                          typename ashape::ashape<VectorIn>::type >::type,\n\t\t\t                 ::mtl::ashape::mat_cvec_mult\n\t\t\t\t     >::value),\n\t\t      \"The type nesting of the arguments does not allow for a consistent matrix vector product.\");\n\n\n#if 1\n    MTL_DEBUG_THROW_IF((void*)&v == (void*)&w, argument_result_conflict());\n#else\n    if ((void*)&v == (void*)&w) {\n\tVectorOut tmp(size(w)); \n\tmult(A, b, tmp);\n\tswap(w, tmp);\n\treturn;\n    }\n#endif\n    // w.checked_change_dim(num_rows(A)); // destroys distribution in parallel -> dimension changed in assignment\n    MTL_DEBUG_THROW_IF(num_rows(A) != mtl::size(w), incompatible_size());\n    MTL_DEBUG_THROW_IF(num_cols(A) != mtl::size(v), incompatible_size());\n\n    mat_cvec_mult(A, v, w, Assign(), mtl::traits::mat_cvec_flatcat<Matrix>());\n}\n\n\n// Vector matrix multiplication\ntemplate <typename VectorIn, typename Matrix, typename VectorOut, typename Assign>\ninline void gen_mult(const VectorIn& v, const Matrix& A, VectorOut& w, Assign, tag::flat<tag::row_vector>, tag::flat<tag::matrix>, tag::flat<tag::row_vector>)\n{\n    vampir_trace<4011> tracer;\n    // Vector must be column vector\n    // If vector is row vector then matrix must have one column and the operation is a outer product\n    //   -> result should be a matrix too\n\n    // Check if element types are compatible (in contrast to tag dispatching, nesting is considered here)\n    MTL_STATIC_ASSERT((boost::is_same< typename ashape::mult_op<typename ashape::ashape<VectorIn>::type, \n\t\t\t                                          typename ashape::ashape<Matrix>::type >::type,\n\t\t\t                 ::mtl::ashape::rvec_mat_mult\n\t\t\t             >::value),\n\t\t      \"The type nesting of the arguments does not allow for a consistent matrix vector product.\");\n\n#if 1\n    MTL_DEBUG_THROW_IF((void*)&v == (void*)&w, argument_result_conflict());\n#else\n    if ((void*)&v == (void*)&w) {\n\tVectorOut tmp(size(w)); \n\tmult(A, b, tmp);\n\tswap(w, tmp);\n\treturn;\n    }\n#endif\n    // w.checked_change_dim(num_cols(A));\n    w.checked_change_resource(v);\n    MTL_DEBUG_THROW_IF(num_cols(v) != num_rows(A), incompatible_size());\n\n    // same dispatching criterion as mat_cvec_mult (until now)\n    rvec_mat_mult(v, A, w, Assign(), typename mtl::traits::mat_cvec_flatcat<Matrix>::type());\n}\n\n\n\n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MULT_INCLUDE\n", "meta": {"hexsha": "f7abdaf18487c177fc0a9009d415df5ec6f7022e", "size": 15585, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/mult.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/operation/mult.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/operation/mult.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": 46.3839285714, "max_line_length": 158, "alphanum_fraction": 0.7045877446, "num_tokens": 3982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.04672495729864523, "lm_q1q2_score": 0.020277765411365663}}
{"text": "/*\n * Copyright (c) 2012, Frederic Dubouchet\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 CERN 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 Frederic Dubouchet ``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 Frederic DUBOUCHET 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 <iostream>\n#include <vector>\n#define __CL_ENABLE_EXCEPTIONS\n#include <cl.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\n#include \"cl_util.h\"\n#include \"cl_floyd_warshall.h\"\n#include \"ewd_file.h\"\n\nusing namespace cl;\nusing namespace boost::program_options;\nusing namespace boost::posix_time;\n\nint main(int ac, char** av) {\n\tbool enable_gpu = true;\n\tunsigned int nb_loops = 1;\n\tstd::string cl_file = \"floyd_warshall.cl\";\n\tstd::string graph_in = \"rome99.txt\";\n\tstd::string graph_out = \"\";\n\ttry {\n\t\t// parse command line\n\t\toptions_description desc(\"Allowed options\");\n\t\tdesc.add_options()\n\t\t(\"help,h\", \"produce help message\")\n\t\t(\"opencl-cpu,c\", \"compute using openCL on CPU\")\n\t\t(\"opencl-gpu,g\", \"compute using openCL on GPU (default)\")\n\t\t(\"opencl-file,f\", value<std::string>(), \"input cl file\")\n\t\t(\"file-in,i\", value<std::string>(),\n\t\t \"Input graph file in EWD format\")\n\t\t(\"file-out,o\", value<std::string>(),\n\t\t \"Output graph file in EWD format\")\n\t\t(\"loop,l\", value<unsigned int>(),\n\t\t \"number of loops (only in no-window mode)\")\n\t\t;\n\t\tvariables_map vm;\n\t\tstore(command_line_parser(ac, av).options(desc).run(), vm);\n\t\tif (vm.count(\"help\")) {\n\t\t\tstd::cout << desc << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (vm.count(\"opencl-cpu\")) {\n\t\t\tenable_gpu = false;\n\t\t}\n\t\tif (vm.count(\"opencl-gpu\")) {\n\t\t\tenable_gpu = true;\n\t\t}\n\t\tstd::cout << \"OpenCL (\" << ((enable_gpu) ? \"GPU\" : \"CPU\");\n\t\tstd::cout << \")    : enable\" << std::endl;\n\t\tif (vm.count(\"file-in\")) {\n\t\t\tgraph_in = vm[\"file-in\"].as<std::string>();\n\t\t}\n\t\tstd::cout << \"Graph file (in) : \" << graph_in << std::endl;\n\t\tif (vm.count(\"file-out\")) {\n\t\t\tgraph_out = vm[\"file-out\"].as<std::string>();\n\t\t\tstd::cout << \"Graph file (out): \" << graph_out << std::endl;\n\t\t}\n\t\tif (vm.count(\"opencl-file\")) {\n\t\t\tcl_file = vm[\"opencl-file\"].as<std::string>();\n\t\t\tstd::cout << \"OpenCL file     : \" << cl_file << std::endl;\n\t\t}\n\t\tif (vm.count(\"loop\")) {\n\t\t\tnb_loops = vm[\"loop\"].as<unsigned int>();\n\t\t}\n\t\tstd::cout << \"Loop            : \" << nb_loops << std::endl;\n\t\t{\n\t\t\t// read the file with the data\n\t\t\tewd_file ef;\n\t\t\tef.import_file(graph_in);\n\t\t\tstd::vector<float> initial_state(ef.size() * ef.size());\n\t\t\tef.export_matrix(&initial_state[0], initial_state.size());\n\t\t\tif (initial_state.size() <= 256) ef.print_matrix(std::cout);\n\t\t\t// do the actual job\n\t\t\tcl_floyd_warshall cfw(enable_gpu);\n\t\t\tcfw.init(cl_file);\n\t\t\tstd::cout\n\t\t\t<< \"Setup           : (\" << ef.size() << \", \"\n\t\t\t<< ef.size() << \")\" << std::endl;\n\t\t\tcfw.setup(std::make_pair<unsigned int, unsigned int>(\n\t\t\t\tef.size(),\n\t\t\t\tef.size()));\n\t\t\ttime_duration best_time = minutes(60);\n\t\t\tfor (int i = 0; i < nb_loops; ++i) {\n\t\t\t\ttime_duration actual_time;\n\t\t\t\tstd::cout\n\t\t\t\t<< \"Prepare (buffer): \" << initial_state.size() << std::endl;\n\t\t\t\tcfw.prepare(initial_state);\n\t\t\t\tstd::cout\n\t\t\t\t<< \"Run (buffer)    : \" << initial_state.size() << std::endl;\n\t\t\t\tactual_time = cfw.run(initial_state);\n\t\t\t\tif (actual_time < best_time) best_time = actual_time;\n\t\t\t\tstd::cout\n\t\t\t\t<< \"\\riteration [\" << i + 1 << \"/\" << nb_loops << \"] : \"\n\t\t\t\t<< \"actual_time : \" << actual_time;\n\t\t\t\tstd::cout.flush();\n\t\t\t}\n\t\t\tstd::cout << std::endl\n\t\t\t<< \"Finished : [\" << nb_loops << \"] Best time : \" << best_time\n\t\t\t<< std::endl;\n\t\t\tif (graph_out.size() || initial_state.size() <= 256)\n\t\t\t\tef.import_matrix(&initial_state[0], initial_state.size());\n\t\t\t// export to file out (in case exist)\n\t\t\tif (graph_out.size()) {\n\t\t\t\tef.export_file(graph_out);\n\t\t\t}\n\t\t\tif (initial_state.size() <= 256) ef.print_matrix(std::cout);\n\t\t}\n\t\t// error handling\n\t} catch (cl::Error er) {\n\t\tstd::cerr\n\t\t<< \"exception (CL)  : \" << er.what()\n\t\t<< \"(\" << er << \")\" << std::endl;\n\t\treturn -2;\n\t} catch (std::exception& ex) {\n\t\tstd::cerr << \"exception (std) : \" << ex.what() << std::endl;\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\n", "meta": {"hexsha": "b5f1886bc86bc2a0df748f4abe6cb079a26bbbb6", "size": 5392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/FloydWarshall/main.cpp", "max_stars_repo_name": "anirul/OpenCL_Crash_Course", "max_stars_repo_head_hexsha": "4a9a2331e1c958fe12f0e0bf3e89949eeb693fe2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-02T17:04:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-02T17:04:35.000Z", "max_issues_repo_path": "Examples/FloydWarshall/main.cpp", "max_issues_repo_name": "anirul/OpenCL_Crash_Course", "max_issues_repo_head_hexsha": "4a9a2331e1c958fe12f0e0bf3e89949eeb693fe2", "max_issues_repo_licenses": ["MIT"], "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/FloydWarshall/main.cpp", "max_forks_repo_name": "anirul/OpenCL_Crash_Course", "max_forks_repo_head_hexsha": "4a9a2331e1c958fe12f0e0bf3e89949eeb693fe2", "max_forks_repo_licenses": ["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.9466666667, "max_line_length": 80, "alphanum_fraction": 0.6448442136, "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.040845712407222005, "lm_q1q2_score": 0.02026330588556662}}
{"text": "//\n// SPDX-License-Identifier: BSD-3-Clause\n// Copyright Contributors to the OpenEXR Project.\n//\n\n// clang-format off\n\n#include \"PyImathQuat.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathDecorators.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include \"PyImath.h\"\n#include \"PyImathMathExc.h\"\n#include <ImathVec.h>\n#include <ImathMatrixAlgo.h>\n#include <ImathEuler.h>\n#include \"PyImathOperators.h\"\n\n// XXX incomplete array wrapping, docstrings missing\n\nnamespace PyImath {\ntemplate <> const char *PyImath::QuatfArray::name() { return \"QuatfArray\"; }\ntemplate <> const char *PyImath::QuatdArray::name() { return \"QuatdArray\"; }\n}\n\nnamespace PyImath {\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\n\ntemplate <class T> struct QuatName { static const char *value; };\ntemplate<> const char *QuatName<float>::value  = \"Quatf\";\ntemplate<> const char *QuatName<double>::value = \"Quatd\";\n\ntemplate <class T>\nstatic std::string Quat_str(const Quat<T> &v)\n{\n    std::stringstream stream;\n    stream << QuatName<T>::value << \"(\" << v[0] << \", \" << v[1] << \", \" \n           << v[2] << \", \" << v[3] << \")\";\n    return stream.str();\n}\n\n// Non-specialized repr is same as str\ntemplate <class T>\nstatic std::string Quat_repr(const Quat<T> &v)\n{\n    return Quat_str(v);\n}\n\n// Specialization for float to full precision\ntemplate <>\nstd::string Quat_repr(const Quat<float> &v)\n{\n    return (boost::format(\"%s(%.9g, %.9g, %.9g, %.9g)\")\n                        % QuatName<float>::value\n                        % v[0] % v[1] % v[2] % v[3]).str();\n}\n\n// Specialization for double to full precision\ntemplate <>\nstd::string Quat_repr(const Quat<double> &v)\n{\n    return (boost::format(\"%s(%.17g, %.17g, %.17g, %.17g)\")\n                        % QuatName<double>::value\n                        % v[0] % v[1] % v[2] % v[3]).str();\n}\n\n\ntemplate <class T>\nstatic Quat<T> &\ninvert(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.invert();\n}\n\ntemplate <class T>\nstatic Quat<T> \ninverse(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.inverse();\n}\n\ntemplate <class T>\nstatic Quat<T> &\nnormalize(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.normalize();\n}\n\ntemplate <class T>\nstatic Quat<T> \nnormalized(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.normalized();\n}\n\ntemplate <class T>\nstatic T\nlength (Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.length();\n}\n\ntemplate <class T>\nstatic Quat<T> &\nsetAxisAngle(Quat<T> &quat, const Vec3<T> &axis, T radians)\n{\n    MATH_EXC_ON;\n    return quat.setAxisAngle(axis, radians);\n}\n\ntemplate <class T>\nstatic Quat<T> &\nsetRotation(Quat<T> &quat, const Vec3<T> &from, const Vec3<T> &to)\n{\n    MATH_EXC_ON;\n    return quat.setRotation(from, to);\n}\n\ntemplate <class T>\nstatic T\nangle (Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.angle();\n}\n\ntemplate <class T>\nstatic Vec3<T>\naxis (Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.axis();\n}\n\ntemplate <class T>\nstatic Matrix33<T>\ntoMatrix33 (Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.toMatrix33();\n}\n\ntemplate <class T>\nstatic Matrix44<T>\ntoMatrix44 (Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.toMatrix44();\n}\n\ntemplate <class T>\nstatic Quat<T> \nlog(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.log();\n}\n\ntemplate <class T>\nstatic Quat<T> \nexp(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return quat.exp();\n}\n\ntemplate <class T>\nstatic void\nsetR(Quat<T> &quat, const double &r)\n{\n    quat.r = r;\n}\n\ntemplate <class T>\nstatic void\nsetV(Quat<T> &quat, const Vec3<T> &v)\n{\n    quat.v = v;\n}\n\ntemplate <class T>\nstatic void\nextract(Quat<T> &quat, const Matrix44<T> &mat)\n{\n    MATH_EXC_ON;\n    Quat<T> q = IMATH_NAMESPACE::extractQuat(mat);\n    quat.r = q.r;\n    quat.v = q.v;\n}\n\ntemplate <class T>\nstatic T scalar(Quat<T> &quat)\n{\n    return quat.r;\n}\n\ntemplate <class T>\nstatic Vec3<T> vector(Quat<T> &quat)\n{\n    return quat.v;\n}\n\ntemplate <class T>\nstatic Quat<T>\nslerp(const Quat<T> &quat, const Quat<T> &other, T t)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::slerp (quat, other, t);\n}\n\ntemplate <class T>\nstatic const Quat<T> &\nimul (Quat<T> &quat, const Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat *= other;\n}\n\ntemplate <class T>\nstatic const Quat<T> &\nimulT (Quat<T> &quat, T t)\n{\n    MATH_EXC_ON;\n    return quat *= t;\n}\n\ntemplate <class T>\nstatic const Quat<T> &\nidiv (Quat<T> &quat, const Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat /= other;\n}\n\ntemplate <class T>\nstatic const Quat<T> &\nidivT (Quat<T> &quat, T t)\n{\n    MATH_EXC_ON;\n    return quat /= t;\n}\n\ntemplate <class T>\nstatic const Quat<T> &\niadd (Quat<T> &quat, const Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat += other;\n}\n\ntemplate <class T>\nstatic const Quat<T> &\nisub (Quat<T> &quat, const Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat -= other;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nrmulM33(Quat<T> &quat, Matrix33<T> &m)\n{\n    MATH_EXC_ON;\n    return m * quat;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nmulM33(Quat<T> &quat, Matrix33<T> &m)\n{\n    MATH_EXC_ON;\n    return quat * m;\n}\n\ntemplate <class T>\nstatic Quat<T>\nmul(Quat<T> &quat, Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat * other;\n}\n\ntemplate <class T>\nstatic Quat<T>\ndiv(Quat<T> &quat, Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat / other;\n}\n\ntemplate <class T>\nstatic Quat<T>\ndivT(Quat<T> &quat, T t)\n{\n    MATH_EXC_ON;\n    return quat / t;\n}\n\ntemplate <class T>\nstatic Quat<T>\nmulT(Quat<T> &quat, T t)\n{\n    MATH_EXC_ON;\n    return quat * t;\n}\n\ntemplate <class T>\nstatic Quat<T>\nadd(Quat<T> &quat, Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat + other;\n}\n\ntemplate <class T>\nstatic Quat<T>\nsub(Quat<T> &quat, Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat - other;\n}\n\ntemplate <class T>\nstatic Quat<T>\nneg(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return -quat;\n}\n\ntemplate <class T>\nstatic Quat<T>\nconj(Quat<T> &quat)\n{\n    MATH_EXC_ON;\n    return ~quat;\n}\n\ntemplate <class T>\nstatic T\ndot(Quat<T> &quat, Quat<T> &other)\n{\n    MATH_EXC_ON;\n    return quat ^ other;\n}\n\ntemplate <class T>\nstatic Vec3<T>\nrmulVec3(Quat<T> &quat, const Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return v * quat.toMatrix44();\n}\n\ntemplate <class T>\nstatic FixedArray< Vec3<T> >\nrmulVec3Array(Quat<T> &quat, const FixedArray< Vec3<T> > &a)\n{\n    MATH_EXC_ON;\n    Matrix44<T> m = quat.toMatrix44();\n    size_t len = a.len();\n    FixedArray< Vec3<T> > r(len);\n    for (size_t i = 0; i < len; i++)\n        r[i] = a[i] * m;\n    return r;\n}\n\ntemplate <class T>\nstatic Quat<T> *\nquatConstructor1(const Euler<T> &euler)\n{\n    MATH_EXC_ON;\n    return new Quat<T>(euler.toQuat());\n}\n\ntemplate <class T>\nstatic Quat<T> *\nquatConstructor2(const Matrix33<T> &mat)\n{\n    MATH_EXC_ON;\n    return new Quat<T>(Euler<T>(mat).toQuat());\n}\n\ntemplate <class T>\nstatic Quat<T> *\nquatConstructor3(const Matrix44<T> &mat)\n{\n    MATH_EXC_ON;\n    return new Quat<T>(Euler<T>(mat).toQuat());\n}\n\ntemplate <class T>\nclass_<Quat<T> >\nregister_Quat()\n{\n    class_<Quat<T> > quat_class(QuatName<T>::value, QuatName<T>::value,init<Quat<T> >(\"copy construction\"));\n    quat_class\n        .def(init<>(\"imath Quat initialization\") )\n        .def(init<Quat<float> >(\"imath Quat copy initialization\") )\n        .def(init<Quat<double> >(\"imath Quat copy initialization\") )\n        .def(init<T,T,T,T>(\"make Quat from components\") )\n        .def(init<T, Vec3<T> >(\"make Quat from components\") )\n        .def(\"__init__\", make_constructor(quatConstructor1<T>))\n        .def(\"__init__\", make_constructor(quatConstructor2<T>))\n        .def(\"__init__\", make_constructor(quatConstructor3<T>))\n        .def(\"identity\",&Quat<T>::identity)\n        .def(\"invert\",&invert<T>,return_internal_reference<>(),\n        \t \"q.invert() -- inverts quaternion q\\n\"\n\t\t\t \"(modifying q); returns q\")\n             \n        .def(\"inverse\",&inverse<T>,\n        \t \"q.inverse() -- returns the inverse of\\n\"\n\t\t\t \"quaternion q; q is not modified\\n\")\n             \n        .def(\"normalize\",&normalize<T>,return_internal_reference<>(),\n        \t \"q.normalize() -- normalizes quaternion q\\n\"\n\t\t\t \"(modifying q); returns q\")\n            \n        .def(\"normalized\",&normalized<T>,\n        \t \"q.normalized() -- returns a normalized version\\n\"\n\t\t\t \"of quaternion q; q is not modified\\n\")\n             \n        .def(\"length\",&length<T>)\n        .def(\"setAxisAngle\",&setAxisAngle<T>,return_internal_reference<>(),\n\t\t\t\"q.setAxisAngle(x,r) -- sets the value of\\n\"\n\t\t\t\"quaternion q so that q represents a rotation\\n\"\n\t\t\t\"of r radians around axis x\")\n             \n        .def(\"setRotation\",&setRotation<T>,return_internal_reference<>(),\n        \t \"q.setRotation(v,w) -- sets the value of\\n\"\n\t\t\t \"quaternion q so that rotating vector v by\\n\"\n\t\t\t \"q produces vector w\")\n             \n        .def(\"angle\",&angle<T>,\n        \t \"q.angle() -- returns the rotation angle\\n\"\n\t\t\t \"(in radians) represented by quaternion q\")\n             \n        .def(\"axis\",&axis<T>,\n        \t \"q.axis() -- returns the rotation axis\\n\"\n\t\t\t \"represented by quaternion q\")\n             \n        .def(\"toMatrix33\",&toMatrix33<T>,\n             \"q.toMatrix33() -- returns a 3x3 matrix that\\n\"\n\t\t\t \"represents the same rotation as quaternion q\")\n             \n        .def(\"toMatrix44\",&toMatrix44<T>,\n        \t \"q.toMatrix44() -- returns a 4x4 matrix that\\n\"\n\t\t\t \"represents the same rotation as quaternion q\")\n             \n        .def(\"log\",&log<T>)\n        .def(\"exp\",&exp<T>)\n        .def_readwrite(\"v\",&Quat<T>::v)                       \n        .def_readwrite(\"r\",&Quat<T>::r)\n        .def(\"v\", &vector<T>,\n\t\t\t  \"q.v() -- returns the v (vector) component\\n\"\n\t\t\t  \"of quaternion q\")\n              \n        .def(\"r\", &scalar<T>,\n        \t \"q.r() -- returns the r (scalar) component\\n\"\n\t\t\t \"of quaternion q\")\n                       \n        .def(\"setR\", &setR<T>,\n        \t \"q.setR(s) -- sets the r (scalar) component\\n\"\n\t\t\t \"of quaternion q to s\")\n             \n        .def(\"setV\", &setV<T>,\n        \t \"q.setV(w) -- sets the v (vector) component\\n\"\n\t\t\t \"of quaternion q to w\")\n             \n        .def(\"extract\", &extract<T>,\n        \t \"q.extract(m) -- extracts the rotation component\\n\"\n\t\t\t \"from 4x4 matrix m and stores the result in q\")\n             \n        .def(\"slerp\", &slerp<T>,\n        \t \"q.slerp(p,t) -- performs sperical linear\\n\"\n\t\t\t \"interpolation between quaternions q and p:\\n\"\n\t\t\t \"q.slerp(p,0) returns q; q.slerp(p,1) returns p.\\n\"\n\t\t\t \"q and p must be normalized\\n\")\n             \n        .def(\"__str__\",Quat_str<T>)\n        .def(\"__repr__\",Quat_repr<T>)\n        .def (\"__imul__\", &imul<T>, return_internal_reference<>())\n        .def (\"__imul__\", &imulT<T>, return_internal_reference<>())\n        .def (\"__idiv__\", idiv<T>, return_internal_reference<>())\n        .def (\"__idiv__\", &idivT<T>, return_internal_reference<>())\n        .def (\"__itruediv__\", idiv<T>, return_internal_reference<>())\n        .def (\"__itruediv__\", &idivT<T>, return_internal_reference<>())\n        .def (\"__iadd__\", &iadd<T>, return_internal_reference<>())\n        .def (\"__isub__\", &isub<T>, return_internal_reference<>())\n        .def(self == self) // NOSONAR - suppress SonarCloud bug report.\n        .def(self != self) // NOSONAR - suppress SonarCloud bug report.\n        .def (\"__rmul__\", &rmulM33<T>)\n        .def (\"__mul__\", &mulM33<T>)\n        .def (\"__mul__\", &mul<T>)\n        .def (\"__div__\", &div<T>)\n        .def (\"__div__\", &divT<T>)\n        .def (\"__truediv__\", &div<T>)\n        .def (\"__truediv__\", &divT<T>)\n        .def (\"__mul__\", &mulT<T>)\n        .def (\"__rmul__\", &mulT<T>)\n        .def (\"__add__\", &add<T>)\n        .def (\"__sub__\", &sub<T>)\n        .def (\"__neg__\", &neg<T>)\n        .def (\"__invert__\", &conj<T>)\n        .def (\"__xor__\", &dot<T>)\n        .def (\"__rmul__\", &rmulVec3<T>)\n        .def (\"__rmul__\", &rmulVec3Array<T>)\n        ;\n\n    decoratecopy(quat_class);\n\n    return quat_class;\n}\n\n// XXX fixme - template this\n// really this should get generated automatically...\n\ntemplate <class T,int index>\nstatic FixedArray<T>\nQuatArray_get(FixedArray<IMATH_NAMESPACE::Quat<T> > &qa)\n{\n    return FixedArray<T>( &(qa[0].r)+index, qa.len(), 4*qa.stride(), qa.handle());\n}\n\ntemplate <class T>\nstruct QuatArray_SetRotationTask : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Vec3<T> > &from;\n    const FixedArray<IMATH_NAMESPACE::Vec3<T> > &to;\n    FixedArray<IMATH_NAMESPACE::Quat<T> >       &result;\n\n    QuatArray_SetRotationTask (const FixedArray<IMATH_NAMESPACE::Vec3<T> > &fromIn,\n                               const FixedArray<IMATH_NAMESPACE::Vec3<T> > &toIn,\n                               FixedArray<IMATH_NAMESPACE::Quat<T> >       &resultIn)\n        : from (fromIn), to (toIn), result (resultIn) {}\n\n    void execute (size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n            result[i].setRotation (from[i], to[i]);\n    }\n};\n\ntemplate <class T> static void\nQuatArray_setRotation (FixedArray<IMATH_NAMESPACE::Quat<T> > &va,\n                       const FixedArray<IMATH_NAMESPACE::Vec3<T> > &from,\n                       const FixedArray<IMATH_NAMESPACE::Vec3<T> > &to)\n{\n    MATH_EXC_ON;\n    size_t len = va.match_dimension(from); \n    va.match_dimension(to); \n\n    QuatArray_SetRotationTask<T> task (from, to, va);\n    dispatchTask (task, len);\n}\n\ntemplate <class T>\nstruct QuatArray_OrientToVectors : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Vec3<T> > &forward;\n    const FixedArray<IMATH_NAMESPACE::Vec3<T> > &up;\n    FixedArray<IMATH_NAMESPACE::Quat<T> >       &result;\n    bool alignForward;\n\n    QuatArray_OrientToVectors (const FixedArray<IMATH_NAMESPACE::Vec3<T> > &forwardIn,\n                               const FixedArray<IMATH_NAMESPACE::Vec3<T> > &upIn,\n                               FixedArray<IMATH_NAMESPACE::Quat<T> >       &resultIn,\n                               bool alignForwardIn)\n        : forward (forwardIn), up (upIn), result (resultIn),\n          alignForward (alignForwardIn) {}\n\n    void execute (size_t start, size_t end)\n    {\n        Vec3<T> f(0), u(0);\n        Euler<T> eu(0,0,0);\n        const Vec3<T> fRef(1,0,0);\n\n        for (size_t i = start; i < end; ++i)\n        {\n            if (alignForward)\n            {\n                f = forward[i].normalized();\n                u = up[i] - f.dot(up[i])*f;\n                u.normalize();\n            }\n            else\n            {\n                u = up[i].normalized();\n                f = forward[i] - u.dot(forward[i])*u;\n                f.normalize();\n            }\n\n            extractEulerXYZ (rotationMatrixWithUpDir (fRef, f, u), eu);\n            result[i] = eu.toQuat();\n        }\n    }\n};\n\ntemplate <class T> static void\nQuatArray_orientToVectors (FixedArray<IMATH_NAMESPACE::Quat<T> >       &va,\n                           const FixedArray<IMATH_NAMESPACE::Vec3<T> > &forward,\n                           const FixedArray<IMATH_NAMESPACE::Vec3<T> > &up,\n                           bool alignForward)\n{\n    MATH_EXC_ON;\n    size_t len = va.match_dimension(forward);\n    va.match_dimension(up);\n\n    QuatArray_OrientToVectors<T> task (forward, up, va, alignForward);\n    dispatchTask (task, len);\n}\n\ntemplate <class T>\nstruct QuatArray_Axis : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Quat<T> > &va;\n    FixedArray<IMATH_NAMESPACE::Vec3<T> >       &result;\n\n    QuatArray_Axis (const FixedArray<IMATH_NAMESPACE::Quat<T> > &vaIn,\n                    FixedArray<IMATH_NAMESPACE::Vec3<T> >       &resultIn)\n        : va (vaIn), result (resultIn) {}\n\n    void execute (size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n            result[i] = va[i].axis(); \n    } \n};\n\ntemplate <class T> static FixedArray<IMATH_NAMESPACE::Vec3<T> >\nQuatArray_axis(const FixedArray<IMATH_NAMESPACE::Quat<T> > &va)\n{\n    MATH_EXC_ON;\n    size_t len = va.len(); \n    FixedArray<IMATH_NAMESPACE::Vec3<T> > retval (Py_ssize_t(len), UNINITIALIZED);\n\n    QuatArray_Axis<T> task (va, retval);\n    dispatchTask (task, len);\n    return retval;\n}\n\ntemplate <class T>\nstruct QuatArray_Angle : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Quat<T> > &va;\n    FixedArray<T>                               &result;\n\n    QuatArray_Angle (const FixedArray<IMATH_NAMESPACE::Quat<T> > &vaIn,\n                     FixedArray<T>                               &resultIn)\n        : va (vaIn), result (resultIn) {}\n\n    void execute (size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n            result[i] = va[i].angle(); \n    } \n};\n\n\ntemplate <class T> static FixedArray<T>\nQuatArray_angle(const FixedArray<IMATH_NAMESPACE::Quat<T> > &va)\n{\n    MATH_EXC_ON;\n    size_t len = va.len(); \n    FixedArray<T> retval (Py_ssize_t(len), UNINITIALIZED);\n\n    QuatArray_Angle<T> task (va, retval);\n    dispatchTask (task, len);\n    return retval;\n}\n\ntemplate <class T>\nstruct QuatArray_RmulVec3 : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Quat<T> > &a;\n    const Vec3<T>                               &v;\n    FixedArray<Vec3<T> >                        &r;\n\n    QuatArray_RmulVec3 (const FixedArray<IMATH_NAMESPACE::Quat<T> > &aIn,\n                        const Vec3<T> &vIn, FixedArray<Vec3<T> > &rIn)\n        : a (aIn), v (vIn), r (rIn) {}\n\n    void execute(size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n        {\n            Matrix44<T> m = a[i].toMatrix44();\n            r[i] = v * m;\n        }\n    }\n};\n\ntemplate <class T>\nstatic FixedArray< Vec3<T> >\nQuatArray_rmulVec3 (const FixedArray< IMATH_NAMESPACE::Quat<T> > &a, const Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    size_t len = a.len();\n    FixedArray< Vec3<T> > r (Py_ssize_t(len), UNINITIALIZED);\n\n    QuatArray_RmulVec3<T> task (a, v, r);\n    dispatchTask (task, len);\n    return r;\n}\n\ntemplate <class T>\nstruct QuatArray_RmulVec3Array : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Quat<T> > &a;\n    const FixedArray<Vec3<T> >                  &b;\n    FixedArray<Vec3<T> >                        &r;\n\n    QuatArray_RmulVec3Array (const FixedArray<IMATH_NAMESPACE::Quat<T> > &aIn,\n                             const FixedArray<Vec3<T> > &bIn,\n                             FixedArray<Vec3<T> > &rIn)\n        : a (aIn), b (bIn), r (rIn) {}\n\n    void execute(size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n        {\n            Matrix44<T> m = a[i].toMatrix44();\n            r[i] = b[i] * m;\n        }\n    }\n};\n\ntemplate <class T>\nstatic FixedArray< Vec3<T> >\nQuatArray_rmulVec3Array (const FixedArray< IMATH_NAMESPACE::Quat<T> > &a,\n                         const FixedArray< Vec3<T> > &b)\n{\n    MATH_EXC_ON;\n    size_t len = a.match_dimension(b);\n    FixedArray< Vec3<T> > r (Py_ssize_t(len), UNINITIALIZED);\n\n    QuatArray_RmulVec3Array<T> task (a, b, r);\n    dispatchTask (task, len);\n    return r;\n}\n\ntemplate <class T>\nstruct QuatArray_SetAxisAngle : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Vec3<T> > &axis;\n    const FixedArray<T>                         &angles;\n    FixedArray<IMATH_NAMESPACE::Quat<T> >       &quats;\n\n    QuatArray_SetAxisAngle (const FixedArray<IMATH_NAMESPACE::Vec3<T> > &axisIn,\n                            const FixedArray<T>                         &anglesIn,\n                            FixedArray<IMATH_NAMESPACE::Quat<T> >       &quatsIn)\n        : axis (axisIn), angles (anglesIn), quats (quatsIn) {}\n\n    void execute(size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n        {\n            quats[i].setAxisAngle (axis[i], angles[i]);\n        }\n    }\n};\n\ntemplate <class T>\nstatic void\nQuatArray_setAxisAngle (FixedArray< IMATH_NAMESPACE::Quat<T> > &quats,\n                        const FixedArray< IMATH_NAMESPACE::Vec3<T> > &axis,\n                        const FixedArray<T> &angles)\n{\n    MATH_EXC_ON;\n    size_t len = quats.match_dimension(axis);\n    quats.match_dimension(angles);\n\n    QuatArray_SetAxisAngle<T> task (axis, angles, quats);\n    dispatchTask (task, len);\n}\n\ntemplate <class T>\nstruct QuatArray_SetEulerXYZ : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Vec3<T> > &rot;\n    FixedArray<IMATH_NAMESPACE::Quat<T> >       &quats;\n\n    QuatArray_SetEulerXYZ (const FixedArray<IMATH_NAMESPACE::Vec3<T> > &rotIn,\n                           FixedArray<IMATH_NAMESPACE::Quat<T> >       &quatsIn)\n        : rot (rotIn), quats (quatsIn) {}\n\n    void execute (size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n        {\n            Eulerf e(rot[i]);\n            quats[i] = e.toQuat();\n        }\n    }\n};\n\ntemplate <class T>\nstatic void\nQuatArray_setEulerXYZ (FixedArray< IMATH_NAMESPACE::Quat<T> > &quats,\n                       const FixedArray< IMATH_NAMESPACE::Vec3<T> > &rot)\n{\n    MATH_EXC_ON;\n    size_t len = quats.match_dimension(rot);\n\n    QuatArray_SetEulerXYZ<T> task (rot, quats);\n    dispatchTask (task, len);\n}\n\ntemplate <class T>\nstruct QuatArray_Mul : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Quat<T> > &q1;\n    const FixedArray<IMATH_NAMESPACE::Quat<T> > &q2;\n    FixedArray<IMATH_NAMESPACE::Quat<T> >       &result;\n\n    QuatArray_Mul (const FixedArray<IMATH_NAMESPACE::Quat<T> > &q1In,\n                   const FixedArray<IMATH_NAMESPACE::Quat<T> > &q2In,\n                   FixedArray<IMATH_NAMESPACE::Quat<T> >       &resultIn)\n        : q1 (q1In), q2 (q2In), result (resultIn) {}\n\n    void execute (size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n        {\n            result[i] = q1[i] * q2[i];\n        }\n    }\n};\n\ntemplate <class T>\nstatic FixedArray< IMATH_NAMESPACE::Quat<T> >\nQuatArray_mul(const FixedArray< IMATH_NAMESPACE::Quat<T> > &q1,\n              const FixedArray< IMATH_NAMESPACE::Quat<T> > &q2)\n{\n    MATH_EXC_ON;\n    size_t len = q1.match_dimension(q2);\n    FixedArray< IMATH_NAMESPACE::Quat<T> > result (Py_ssize_t(len), UNINITIALIZED);\n\n    QuatArray_Mul<T> task (q1, q2, result);\n    dispatchTask (task, len);\n    return result;\n}\n\ntemplate <class T>\nstruct QuatArray_QuatConstructor1 : public Task\n{\n    const FixedArray<IMATH_NAMESPACE::Euler<T> > &euler;\n    FixedArray<IMATH_NAMESPACE::Quat<T> >        &result;\n\n    QuatArray_QuatConstructor1 (const FixedArray<IMATH_NAMESPACE::Euler<T> > &eulerIn,\n                                FixedArray<IMATH_NAMESPACE::Quat<T> >        &resultIn)\n        : euler (eulerIn), result (resultIn) {}\n\n    void execute (size_t start, size_t end)\n    {\n        for (size_t i = start; i < end; ++i)\n        {\n            result[i] = euler[i].toQuat();\n        }\n    }\n};\n\ntemplate <class T>\nstatic FixedArray<IMATH_NAMESPACE::Quat<T> > *\nQuatArray_quatConstructor1(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 =\n        new FixedArray<IMATH_NAMESPACE::Quat<T> > (Py_ssize_t(len), UNINITIALIZED);\n\n    QuatArray_QuatConstructor1<T> task (e, *result);\n    dispatchTask (task, len);\n    return result;\n}\n\ntemplate <class T>\nclass_<FixedArray<IMATH_NAMESPACE::Quat<T> > >\nregister_QuatArray()\n{\n    class_<FixedArray<IMATH_NAMESPACE::Quat<T> > > quatArray_class = FixedArray<IMATH_NAMESPACE::Quat<T> >::register_(\"Fixed length array of IMATH_NAMESPACE::Quat\");\n    quatArray_class\n        .add_property(\"r\",&QuatArray_get<T,0>)\n        .add_property(\"x\",&QuatArray_get<T,1>)\n        .add_property(\"y\",&QuatArray_get<T,2>)\n        .add_property(\"z\",&QuatArray_get<T,3>)\n        .def(\"setRotation\", &QuatArray_setRotation<T>,\n             \"set rotation angles for each quat\",\n             (args(\"from\", \"to\")))\n        .def(\"orientToVectors\", &QuatArray_orientToVectors<T>,\n             \"Sets the orientations to match the given forward and up vectors, \"\n             \"matching the forward vector exactly if 'alignForward' is True, matching \"\n             \"the up vector exactly if 'alignForward' is False.  If the vectors are \"\n             \"already orthogonal, both vectors will be matched exactly.\",\n             (args(\"forward\", \"up\", \"alignForward\")))\n        .def(\"axis\", &QuatArray_axis<T>,\n             \"get rotation axis for each quat\")\n        .def(\"angle\", &QuatArray_angle<T>,\n             \"get rotation angle about the axis returned by axis() for each quat\")\n        .def(\"setAxisAngle\", &QuatArray_setAxisAngle<T>,\n             \"set the quaternion arrays from a given axis and angle\",\n             (args(\"axis\", \"angle\")))\n        .def(\"setEulerXYZ\", &QuatArray_setEulerXYZ<T>,\n             \"set the quaternion arrays from a given euler XYZ angle vector\",\n             (args(\"euler\")))\n        .def(\"__mul__\", &QuatArray_mul<T>)\n        .def(\"__rmul__\", &QuatArray_rmulVec3<T>)\n        .def(\"__rmul__\", &QuatArray_rmulVec3Array<T>)\n        .def(\"__init__\", make_constructor(QuatArray_quatConstructor1<T>))\n        ;\n\n    add_comparison_functions(quatArray_class);\n    decoratecopy(quatArray_class);\n\n    return quatArray_class;\n}\n\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Quat<float> > register_Quat<float>();\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Quat<double> > register_Quat<double>();\n\t\t \ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Quat<float> > > register_QuatArray<float>();\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Quat<double> > > register_QuatArray<double>();\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Quat<float> FixedArrayDefaultValue<IMATH_NAMESPACE::Quat<float> >::value() { return IMATH_NAMESPACE::Quat<float>(); }\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Quat<double> FixedArrayDefaultValue<IMATH_NAMESPACE::Quat<double> >::value() { return IMATH_NAMESPACE::Quat<double>(); }\n}\n", "meta": {"hexsha": "e71f144ff6074954f3aa346a6a193fb785e59854", "size": 25546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/PyImath/PyImathQuat.cpp", "max_stars_repo_name": "TelltaleGames/Imath", "max_stars_repo_head_hexsha": "9d6cf28b3179f7ca5b8fa737d952e112ab4a626a", "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/python/PyImath/PyImathQuat.cpp", "max_issues_repo_name": "TelltaleGames/Imath", "max_issues_repo_head_hexsha": "9d6cf28b3179f7ca5b8fa737d952e112ab4a626a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python/PyImath/PyImathQuat.cpp", "max_forks_repo_name": "TelltaleGames/Imath", "max_forks_repo_head_hexsha": "9d6cf28b3179f7ca5b8fa737d952e112ab4a626a", "max_forks_repo_licenses": ["BSD-3-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.3219251337, "max_line_length": 165, "alphanum_fraction": 0.5998982228, "num_tokens": 7371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.04468086566129904, "lm_q1q2_score": 0.020252131080588445}}
{"text": "#include <boost/algorithm/string.hpp>\n#include <iostream>\n#include <limits>\n#include <stdint.h>\n#include <vector>\n\nconst int MAX_STATIONS  = 100000;\nconst uint32_t INF = std::numeric_limits<uint32_t>::max();\n\nstruct Connection {\n    uint32_t departure_station, arrival_station;\n    uint32_t departure_timestamp, arrival_timestamp;\n\n    // Connection constructor\n    Connection(std::string line) {\n        boost::trim(line);\n        std::vector<std::string> tokens;\n        boost::split(tokens, line, boost::is_any_of(\" \"));\n\n        departure_station = std::stoi(tokens[0]);\n        arrival_station = std::stoi(tokens[1]);\n        departure_timestamp = std::stoi(tokens[2]);\n        arrival_timestamp = std::stoi(tokens[3]);\n    }\n};\n\nstruct Timetable {\n    std::vector<Connection> connections;\n\n    // Timetable constructor: reads all the connections from stdin\n    Timetable() {\n        std::string line;\n        getline(std::cin, line);\n\n        while (!line.empty()) {\n            connections.push_back( Connection(line) );\n            getline(std::cin, line);\n        }\n    }\n};\n\nstruct CSA {\n    Timetable timetable;\n    std::vector<uint32_t> in_connection;\n    std::vector<uint32_t> earliest_arrival;\n\n    void main_loop(uint32_t arrival_station) {\n        uint32_t earliest = INF;\n        for (size_t i = 0; i < timetable.connections.size(); ++i) {\n            Connection connection = timetable.connections[i];\n\n            if (connection.departure_timestamp >= earliest_arrival[connection.departure_station] &&\n                    connection.arrival_timestamp < earliest_arrival[connection.arrival_station]) {\n                earliest_arrival[connection.arrival_station] = connection.arrival_timestamp;\n                in_connection[connection.arrival_station] = i;\n\n                if(connection.arrival_station == arrival_station) {\n                    earliest = std::min(earliest, connection.arrival_timestamp);\n                }\n            } else if(connection.arrival_timestamp > earliest) {\n              return;\n            }\n        }\n    }\n\n    void print_result(uint32_t arrival_station) {\n        if(in_connection[arrival_station] == INF) {\n            std::cout << \"NO_SOLUTION\" << std::endl;\n        } else {\n            std::vector<Connection> route;\n            // We have to rebuild the route from the arrival station\n            uint32_t last_connection_index = in_connection[arrival_station];\n            while (last_connection_index != INF) {\n                Connection connection = timetable.connections[last_connection_index];\n                route.push_back(connection);\n                last_connection_index = in_connection[connection.departure_station];\n            }\n\n            // And now print it out in the right direction\n            std::reverse(route.begin(), route.end());\n            for (auto connection : route) {\n                std::cout << connection.departure_station << \" \" << connection.arrival_station << \" \" <<\n                    connection.departure_timestamp << \" \" << connection.arrival_timestamp << std::endl;\n            }\n        }\n        std::cout << std::endl;\n    }\n\n    void compute(uint32_t departure_station, uint32_t arrival_station, uint32_t departure_time) {\n        in_connection.assign(MAX_STATIONS, INF);\n        earliest_arrival.assign(MAX_STATIONS, INF);\n        earliest_arrival[departure_station] = departure_time;\n\n        if (departure_station <= MAX_STATIONS && arrival_station <= MAX_STATIONS) {\n            main_loop(arrival_station);\n        }\n        print_result(arrival_station);\n    }\n};\n\nint main(int, char**) {\n    CSA csa;\n\n    std::string line;\n    std::vector<std::string> tokens;\n    getline(std::cin, line);\n\n    while (!line.empty()) {\n        boost::split(tokens, line, boost::is_any_of(\" \"));\n        csa.compute(std::stoi(tokens[0]), std::stoi(tokens[1]), std::stoi(tokens[2]));\n        getline(std::cin, line);\n    }\n}\n", "meta": {"hexsha": "6a9fb62029f220d1dd8a38aba4a6de428a584467", "size": 3920, "ext": "cc", "lang": "C++", "max_stars_repo_path": "csa.cc", "max_stars_repo_name": "BogdanArdelean/csa-challenge", "max_stars_repo_head_hexsha": "ccdbbd0c6fd9fcdff64631149284898502f05e56", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 81.0, "max_stars_repo_stars_event_min_datetime": "2015-10-02T08:14:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-04T03:12:24.000Z", "max_issues_repo_path": "csa.cc", "max_issues_repo_name": "BogdanArdelean/csa-challenge", "max_issues_repo_head_hexsha": "ccdbbd0c6fd9fcdff64631149284898502f05e56", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2015-10-02T08:17:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-28T19:11:16.000Z", "max_forks_repo_path": "csa.cc", "max_forks_repo_name": "BogdanArdelean/csa-challenge", "max_forks_repo_head_hexsha": "ccdbbd0c6fd9fcdff64631149284898502f05e56", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-10-04T12:07:47.000Z", "max_forks_repo_forks_event_max_datetime": "2016-06-07T17:56:52.000Z", "avg_line_length": 34.3859649123, "max_line_length": 104, "alphanum_fraction": 0.618622449, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.041462276856943696, "lm_q1q2_score": 0.020245341320404377}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_ComparePolicy.hpp\n//! \\author Alex Robinson\n//! \\brief  Compare policy specializations\n//! \n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_COMPARE_POLICY_HPP\n#define UTILITY_COMPARE_POLICY_HPP\n\n// Std Lib Includes\n#include <string>\n\n// Boost Includes\n#include <boost/units/quantity.hpp>\n#include <boost/units/io.hpp>\n\n// Trilinos Includes\n#include <Teuchos_FancyOStream.hpp>\n#include <Teuchos_ScalarTraits.hpp>\n\n// FRENSIE Includes\n#include \"Utility_ComparePolicyDecl.hpp\"\n#include \"Utility_Tuple.hpp\"\n\nnamespace Utility{\n\nnamespace Policy{\n\n//---------------------------------------------------------------------------//\n// ComparePolicy Helper Functions.\n//---------------------------------------------------------------------------//\n\n/*! \\brief Relative error of two values\n * \\ingroup compare_policy\n */\ntemplate<typename ScalarType>\nScalarType relError( const ScalarType first_value, \n\t\t     const ScalarType second_value )\n{\n  typedef Teuchos::ScalarTraits<ScalarType> ST;\n  typename ST::magnitudeType err;\n  if( first_value != ST::zero() && second_value != ST::zero() )\n  {\n    err = ST::magnitude( first_value - second_value )/\n      std::max( ST::magnitude( first_value ),\n\t\tST::magnitude( second_value ) );\n  }\n  else\n  {\n    err = std::max( ST::magnitude( first_value ),\n\t\t    ST::magnitude( second_value ) );\n  }\n\n  return err;\n}\n\n/*! \\brief Compare the first tuple members\n * \\ingroup compare_policy\n */\ntemplate<typename T>\nbool compareFirstTupleMembers( const T &first_value,\n\t\t\t       const std::string &first_name,\n\t\t\t       const T &second_value,\n\t\t\t       const std::string &second_name,\n\t\t\t       Teuchos::FancyOStream &out,\n\t\t\t       const int index,\n\t\t\t       const double tol )\n{\n  bool success = true; \n \n  std::stringstream first_tuple_member_name;\n  std::stringstream second_tuple_member_name;\n  // Array Element Compare\n  if( index >= 0 )\n  {\n    first_tuple_member_name << first_name << \"[\" << index << \"].first\";\n    second_tuple_member_name << second_name << \"[\" << index << \"].first\";\n  }\n  // Single Tuple Compare\n  else\n  {\n    first_tuple_member_name << first_name << \".first\";\n    second_tuple_member_name << second_name << \".first\";\n  }\n  \n  success = ComparePolicy<T>::compare( first_value,\n\t\t\t\t       first_tuple_member_name.str(),\n\t\t\t\t       second_value,\n\t\t\t\t       second_tuple_member_name.str(),\n\t\t\t\t       out,\n\t\t\t\t       -1,\n\t\t\t\t       tol );\n  return success;\n}\n\n/*! \\brief Compare the second tuple members\n * \\ingroup compare_policy\n */\ntemplate<typename T>\nbool compareSecondTupleMembers( const T &first_value,\n\t\t\t\tconst std::string &first_name,\n\t\t\t\tconst T &second_value,\n\t\t\t\tconst std::string &second_name,\n\t\t\t\tTeuchos::FancyOStream &out,\n\t\t\t\tconst int index,\n\t\t\t\tconst double tol )\n{\n  bool success = true;\n  \n  std::stringstream first_tuple_member_name;\n  std::stringstream second_tuple_member_name;\n  // Array Element Compare\n  if( index >= 0 )\n  {\n    first_tuple_member_name << first_name << \"[\" << index << \"].second\";\n    second_tuple_member_name << second_name << \"[\" << index << \"].second\";\n  }\n  // Single Tuple Compare\n  else\n  {\n    first_tuple_member_name << first_name << \".second\";\n    second_tuple_member_name << second_name << \".second\";\n  }\n  \n  success = ComparePolicy<T>::compare( first_value,\n\t\t\t\t       first_tuple_member_name.str(),\n\t\t\t\t       second_value,\n\t\t\t\t       second_tuple_member_name.str(),\n\t\t\t\t       out,\n\t\t\t\t       -1,\n\t\t\t\t       tol );\n  return success;\n}\n\n/*! \\brief Compare the third tuple members\n * \\ingroup compare_policy\n */\ntemplate<typename T>\nbool compareThirdTupleMembers( const T &first_value,\n\t\t\t       const std::string &first_name,\n\t\t\t       const T &second_value,\n\t\t\t       const std::string &second_name,\n\t\t\t       Teuchos::FancyOStream &out,\n\t\t\t       const int index,\n\t\t\t       const double tol )\n{\n  bool success = true;\n  \n  std::stringstream first_tuple_member_name;\n  std::stringstream second_tuple_member_name;\n  // Array Element Compare\n  if( index >= 0 )\n  {\n    first_tuple_member_name << first_name << \"[\" << index << \"].third\";\n    second_tuple_member_name << second_name << \"[\" << index << \"].third\";\n  }\n  // Single Tuple Compare\n  else\n  {\n    first_tuple_member_name << first_name << \".third\";\n    second_tuple_member_name << second_name << \".third\";\n  }\n  \n  success = ComparePolicy<T>::compare( first_value,\n\t\t\t\t       first_tuple_member_name.str(),\n\t\t\t\t       second_value,\n\t\t\t\t       second_tuple_member_name.str(),\n\t\t\t\t       out,\n\t\t\t\t       -1,\n\t\t\t\t       tol );\n  return success;\n}\n\n/*! \\brief Compare the fourth tuple members\n * \\ingroup compare_policy\n */\ntemplate<typename T>\nbool compareFourthTupleMembers( const T &first_value,\n\t\t\t\tconst std::string &first_name,\n\t\t\t\tconst T &second_value,\n\t\t\t\tconst std::string &second_name,\n\t\t\t\tTeuchos::FancyOStream &out,\n\t\t\t\tconst int index,\n\t\t\t\tconst double tol )\n{\n  bool success = true;\n  \n  std::stringstream first_tuple_member_name;\n  std::stringstream second_tuple_member_name;\n  // Array Element Compare\n  if( index >= 0 )\n  {\n    first_tuple_member_name << first_name << \"[\" << index << \"].fourth\";\n    second_tuple_member_name << second_name << \"[\" << index << \"].fourth\";\n  }\n  // Single Tuple Compare\n  else\n  {\n    first_tuple_member_name << first_name << \".fourth\";\n    second_tuple_member_name << second_name << \".fourth\";\n  }\n  \n  success = ComparePolicy<T>::compare( first_value,\n\t\t\t\t       first_tuple_member_name.str(),\n\t\t\t\t       second_value,\n\t\t\t\t       second_tuple_member_name.str(),\n\t\t\t\t       out,\n\t\t\t\t       -1,\n\t\t\t\t       tol );\n  return success;\n}\n\n/*! \\brief The specialization of the Utility::ComparePolicy for const int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<const int>\n{\n  typedef const int scalarType;\n  \n  static inline bool compare( const int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    bool success = true;\n      \n    // Array Element Compare\n    if( index >= 0 )\n    {\n      out << \"\\nError, \" << first_name << \"[\" << index << \"]\" << \" = \"\n\t  << first_value << \" == \" << second_name << \"[\" << index << \"]\" \n\t  << \" = \" << second_value << \": \";\n      if( first_value != second_value )\n      { \n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n    // Single Compare\n    else\n    {\n      out << first_name << \" = \" << first_value\n\t  << \" == \" << second_name << \" = \" << second_value \n\t  << \": \";\n      if( first_value != second_value )\n      {\n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n    \n    return success;\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<int>\n{\n  typedef int scalarType;\n  \n  static inline bool compare( const int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    return ComparePolicy<const int>::compare( first_value,\n\t\t\t\t\t      first_name,\n\t\t\t\t\t      second_value,\n\t\t\t\t\t      second_name,\n\t\t\t\t\t      out,\n\t\t\t\t\t      index,\n\t\t\t\t\t      tol );\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for const\n * unsigned int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<const unsigned int>\n{\n  typedef unsigned int scalarType;\n  \n  static inline bool compare( const unsigned int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const unsigned int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    bool success = true;\n      \n    // Array Element Compare\n    if( index >= 0 )\n    {\n      out << \"\\nError, \" << first_name << \"[\" << index << \"]\" << \" = \"\n\t  << first_value << \" == \" << second_name << \"[\" << index << \"]\" \n\t  << \" = \" << second_value << \": \";\n      if( first_value != second_value )\n      {\n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n    // Single Compare\n    else\n    {\n      out << first_name << \" = \" << first_value\n\t  << \" == \" << second_name << \" = \" << second_value \n\t  << \": \";\n      if( first_value != second_value )\n      {\n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n    \n    return success;\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for unsigned int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<unsigned int>\n{\n  typedef unsigned int scalarType;\n  \n  static inline bool compare( const unsigned int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const unsigned int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    return ComparePolicy<const unsigned int>::compare( first_value,\n\t\t\t\t\t\t       first_name,\n\t\t\t\t\t\t       second_value,\n\t\t\t\t\t\t       second_name,\n\t\t\t\t\t\t       out,\n\t\t\t\t\t\t       index,\n\t\t\t\t\t\t       tol );\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for const\n * unsigned long int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<const unsigned long int>\n{\n  typedef unsigned int scalarType;\n  \n  static inline bool compare( const unsigned long int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const unsigned long int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    bool success = true;\n      \n    // Array Element Compare\n    if( index >= 0 )\n    {\n      out << \"\\nError, \" << first_name << \"[\" << index << \"]\" << \" = \"\n\t  << first_value << \" == \" << second_name << \"[\" << index << \"]\" \n\t  << \" = \" << second_value << \": \";\n      if( first_value != second_value )\n      {\n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n    // Single Compare\n    else\n    {\n      out << first_name << \" = \" << first_value\n\t  << \" == \" << second_name << \" = \" << second_value \n\t  << \": \";\n      if( first_value != second_value )\n      {\n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n      \n    return success;\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for unsigned long \n * int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<unsigned long int>\n{\n  typedef unsigned int scalarType;\n  \n  static inline bool compare( const unsigned long int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const unsigned long int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    return ComparePolicy<const unsigned long int>::compare( first_value,\n\t\t\t\t\t\t\t    first_name,\n\t\t\t\t\t\t\t    second_value,\n\t\t\t\t\t\t\t    second_name,\n\t\t\t\t\t\t\t    out,\n\t\t\t\t\t\t\t    index,\n\t\t\t\t\t\t\t    tol );\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for const\n * unsigned long long int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<const unsigned long long int>\n{\n  typedef unsigned int scalarType;\n  \n  static inline bool compare( const unsigned long long int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const unsigned long long int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    bool success = true;\n      \n    // Array Element Compare\n    if( index >= 0 )\n    {\n      out << \"\\nError, \" << first_name << \"[\" << index << \"]\" << \" = \"\n\t  << first_value << \" == \" << second_name << \"[\" << index << \"]\" \n\t  << \" = \" << second_value << \": \";\n      if( first_value != second_value )\n      {\n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n    // Single Compare\n    else\n    {\n      out << first_name << \" = \" << first_value\n\t  << \" == \" << second_name << \" = \" << second_value \n\t  << \": \";\n      if( first_value != second_value )\n      {\n\tout << \"failed!\\n\";\n\n\tsuccess = false;\n      }\n      else\n\tout << \"passed\\n\";\n    }\n\n    return success;\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for unsigned long \n * long int.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<unsigned long long int>\n{\n  typedef unsigned int scalarType;\n  \n  static inline bool compare( const unsigned long long int &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const unsigned long long int &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0 )\n  {\n    return ComparePolicy<const unsigned long long int>::compare( first_value,\n\t\t\t\t\t\t\t\t first_name,\n\t\t\t\t\t\t\t\t second_value,\n\t\t\t\t\t\t\t\t second_name,\n\t\t\t\t\t\t\t\t out,\n\t\t\t\t\t\t\t\t index,\n\t\t\t\t\t\t\t\t tol );\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for const double.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<const double>\n{\n  typedef const double scalarType;\n  static inline bool compare( const double &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const double &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    bool success = true;\n      \n    if( tol == 0.0 )\n    {\n      // Array Element Compare\n      if( index >= 0 )\n      {\n\tout << \"\\nError, \" << first_name << \"[\" << index << \"]\" << \" = \"\n\t    << first_value << \" == \" << second_name << \"[\" << index << \"]\" \n\t    << \" = \" << second_value << \": \";\n\tif( first_value != second_value )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n      // Single Compare\n      else\n      {\n\tout << first_name << \" = \" << first_value\n\t    << \" == \" << second_name << \" = \" << second_value \n\t    << \": \";\n\tif( first_value != second_value )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n    }\n    else\n    {\n      double err = relError( first_value, second_value );\n      \n      // Array Element Compare\n      if( index >= 0 )\n      {\n\tout << \"\\nError, relErr(\" << first_name << \"[\" << index << \"],\"\n\t    << second_name << \"[\" << index << \"])\" << \" = relErr(\" \n\t    << first_value << \",\" << second_value << \") = \" << err\n\t    << \" <= tol = \" << tol << \": \";\n\tif( err > tol )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n      // Single Compare\n      else\n      {\n\tout << \"\\nCheck: relErr(\" << first_name << \",\" << second_name << \")\"\n\t    << \"\\n= relErr(\" << first_value << \",\" << second_value << \") = \"\n\t    << err << \"\\n<= tol = \" << tol << \": \";\n\tif( err > tol )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n    }\n    \n    return success;\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for double.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<double>\n{\n  typedef double scalarType;\n  static inline bool compare( const double &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const double &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    return ComparePolicy<const double>::compare( first_value,\n\t\t\t\t\t\t first_name,\n\t\t\t\t\t\t second_value,\n\t\t\t\t\t\t second_name,\n\t\t\t\t\t\t out,\n\t\t\t\t\t\t index,\n\t\t\t\t\t\t tol );\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for const float.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<const float>\n{\n  typedef const float scalarType;\n  static inline bool compare( const float &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const float &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0f )\n  {\n    bool success = true;\n      \n    if( tol == 0.0f )\n    {\n      // Array Element Compare\n      if( index >= 0 )\n      {\n\tout << \"\\nError, \" << first_name << \"[\" << index << \"]\" << \" = \"\n\t    << first_value << \" == \" << second_name << \"[\" << index << \"]\" \n\t    << \" = \" << second_value << \": \";\n\tif( first_value != second_value )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n      // Single Compare\n      else\n      {\n\tout << first_name << \" = \" << first_value\n\t    << \" == \" << second_name << \" = \" << second_value \n\t    << \": \";\n\tif( first_value != second_value )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n    }\n    else\n    {\n      float err = relError( first_value, second_value );\n      \n      // Array Element Compare\n      if( index >= 0 )\n      {\n\tout << \"\\nError, relErr(\" << first_name << \"[\" << index << \"],\"\n\t    << second_name << \"[\" << index << \"])\" << \" = relErr(\" \n\t    << first_value << \",\" << second_value << \") = \" << err\n\t    << \" <= tol = \" << tol << \": \";\n\tif( err > tol )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse\n\t  out << \"passed\\n\";\n      }\n      // Single Compare\n      else\n      {\n\tout << \"\\nCheck: relErr(\" << first_name << \",\" << second_name << \")\"\n\t    << \"\\n= relErr(\" << first_value << \",\" << second_value << \") = \"\n\t    << err << \"\\n<= tol = \" << tol << \": \";\n\tif( err > tol )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse\n\t  out << \"passed\\n\";\n      }\n    }\n    \n    return success;\n  }\n};\n\n/*! \\brief The specialization of the Utility::ComparePolicy for float.\n * \\ingroup compare_policy\n */\ntemplate<>\nstruct ComparePolicy<float>\n{\n  typedef float scalarType;\n  static inline bool compare( const float &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const float &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0f )\n  {\n    return ComparePolicy<const float>::compare( first_value,\n\t\t\t\t\t\tfirst_name, \n\t\t\t\t\t\tsecond_value,\n\t\t\t\t\t\tsecond_name,\n\t\t\t\t\t\tout,\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\ttol );\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for \n * const Utility::Pair. \n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2>\nstruct ComparePolicy<const Pair<T,T2> >\n{\n  typedef const double scalarType;\n  static inline bool compare( const Pair<T,T2> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const Pair<T,T2> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    bool success = true;\n    \n    // Compare the first tuple members\n    {\n      bool local_success = true;\n      local_success = compareFirstTupleMembers<T>( first_value.first,\n\t\t\t\t\t\t   first_name,\n\t\t\t\t\t\t   second_value.first,\n\t\t\t\t\t\t   second_name,\n\t\t\t\t\t\t   out,\n\t\t\t\t\t\t   index,\n\t\t\t\t\t\t   tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    // Compare the second tuple members\n    {\n      bool local_success = true;\n      local_success = compareSecondTupleMembers<T2>( first_value.second,\n\t\t\t\t\t\t     first_name,\n\t\t\t\t\t\t     second_value.second,\n\t\t\t\t\t\t     second_name,\n\t\t\t\t\t\t     out,\n\t\t\t\t\t\t     index,\n\t\t\t\t\t\t     tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    return success;\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for \n * Utility::Pair. \n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2>\nstruct ComparePolicy<Pair<T,T2> >\n{\n  typedef double scalarType;\n  static inline bool compare( const Pair<T,T2> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const Pair<T,T2> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    return ComparePolicy<const Pair<T,T2> >::compare( first_value,\n\t\t\t\t\t\t      first_name,\n\t\t\t\t\t\t      second_value,\n\t\t\t\t\t\t      second_name,\n\t\t\t\t\t\t      out,\n\t\t\t\t\t\t      index,\n\t\t\t\t\t\t      tol );\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for\n * const std::pair.\n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2>\nstruct ComparePolicy<const std::pair<T,T2> >\n{\n  typedef const double scalarType;\n  static inline bool compare( const std::pair<T,T2> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const std::pair<T,T2> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    bool success = true;\n    \n    // Compare the first tuple members\n    {\n      bool local_success = true;\n      local_success = compareFirstTupleMembers<T>( first_value.first,\n\t\t\t\t\t\t   first_name,\n\t\t\t\t\t\t   second_value.first,\n\t\t\t\t\t\t   second_name,\n\t\t\t\t\t\t   out,\n\t\t\t\t\t\t   index,\n\t\t\t\t\t\t   tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    // Compare the second tuple members\n    {\n      bool local_success = true;\n      local_success = compareSecondTupleMembers<T2>( first_value.second,\n\t\t\t\t\t\t     first_name,\n\t\t\t\t\t\t     second_value.second,\n\t\t\t\t\t\t     second_name,\n\t\t\t\t\t\t     out,\n\t\t\t\t\t\t     index,\n\t\t\t\t\t\t     tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    return success;\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for\n * std::pair.\n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2>\nstruct ComparePolicy<std::pair<T,T2> >\n{\n  typedef const double scalarType;\n  static inline bool compare( const std::pair<T,T2> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const std::pair<T,T2> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    return ComparePolicy<const std::pair<T,T2> >::compare( first_value,\n\t\t\t\t\t\t\t   first_name,\n\t\t\t\t\t\t\t   second_value,\n\t\t\t\t\t\t\t   second_name,\n\t\t\t\t\t\t\t   out,\n\t\t\t\t\t\t\t   index,\n\t\t\t\t\t\t\t   tol );\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for \n * const Utility::Trip. \n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2, typename T3>\nstruct ComparePolicy<const Trip<T,T2,T3> >\n{\n  typedef const double scalarType;\n  \n  static inline bool compare( const Trip<T,T2,T3> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const Trip<T,T2,T3> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    bool success = true;\n    \n    // Compare the first tuple members\n    {\n      bool local_success = true;\n      local_success = compareFirstTupleMembers<T>( first_value.first,\n\t\t\t\t\t\t   first_name,\n\t\t\t\t\t\t   second_value.first,\n\t\t\t\t\t\t   second_name,\n\t\t\t\t\t\t   out,\n\t\t\t\t\t\t   index,\n\t\t\t\t\t\t   tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    // Compare the second tuple members\n    {\n      bool local_success = true;\n      local_success = compareSecondTupleMembers<T2>( first_value.second,\n\t\t\t\t\t\t     first_name,\n\t\t\t\t\t\t     second_value.second,\n\t\t\t\t\t\t     second_name,\n\t\t\t\t\t\t     out,\n\t\t\t\t\t\t     index,\n\t\t\t\t\t\t     tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n    \n    // Compare the third tuple members\n    {\n      bool local_success = true;\n      local_success = compareThirdTupleMembers<T3>( first_value.third,\n\t\t\t\t\t\t    first_name,\n\t\t\t\t\t\t    second_value.third,\n\t\t\t\t\t\t    second_name,\n\t\t\t\t\t\t    out,\n\t\t\t\t\t\t    index,\n\t\t\t\t\t\t    tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    return success;\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for \n * Utility::Trip. \n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2, typename T3>\nstruct ComparePolicy<Trip<T,T2,T3> >\n{\n  typedef double scalarType;\n  \n  static inline bool compare( const Trip<T,T2,T3> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const Trip<T,T2,T3> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    return ComparePolicy<const Trip<T,T2,T3> >::compare( first_value,\n\t\t\t\t\t\t\t first_name,\n\t\t\t\t\t\t\t second_value,\n\t\t\t\t\t\t\t second_name,\n\t\t\t\t\t\t\t out,\n\t\t\t\t\t\t\t index,\n\t\t\t\t\t\t\t tol );\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for \n * const Utility::Quad. \n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2, typename T3, typename T4>\nstruct ComparePolicy<const Quad<T,T2,T3,T4> >\n{\n  typedef const double scalarType;\n  \n  static inline bool compare( const Quad<T,T2,T3,T4> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const Quad<T,T2,T3,T4> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    bool success = true;\n    \n    // Compare the first tuple members\n    {\n      bool local_success = true;\n      local_success = compareFirstTupleMembers<T>( first_value.first,\n\t\t\t\t\t\t   first_name,\n\t\t\t\t\t\t   second_value.first,\n\t\t\t\t\t\t   second_name,\n\t\t\t\t\t\t   out,\n\t\t\t\t\t\t   index,\n\t\t\t\t\t\t   tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    // Compare the second tuple members\n    {\n      bool local_success = true;\n      local_success = compareSecondTupleMembers<T2>( first_value.second,\n\t\t\t\t\t\t     first_name,\n\t\t\t\t\t\t     second_value.second,\n\t\t\t\t\t\t     second_name,\n\t\t\t\t\t\t     out,\n\t\t\t\t\t\t     index,\n\t\t\t\t\t\t     tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n    \n    // Compare the third tuple members\n    {\n      bool local_success = true;\n      local_success = compareThirdTupleMembers<T3>( first_value.third,\n\t\t\t\t\t\t    first_name,\n\t\t\t\t\t\t    second_value.third,\n\t\t\t\t\t\t    second_name,\n\t\t\t\t\t\t    out,\n\t\t\t\t\t\t    index,\n\t\t\t\t\t\t    tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    // Compare the fourth tuple members\n    {\n      bool local_success = true;\n      local_success = compareFourthTupleMembers<T4>( first_value.fourth,\n\t\t\t\t\t\t     first_name,\n\t\t\t\t\t\t     second_value.fourth,\n\t\t\t\t\t\t     second_name,\n\t\t\t\t\t\t     out,\n\t\t\t\t\t\t     index,\n\t\t\t\t\t\t     tol );\n      if( !local_success )\n\tsuccess = false;\n    }\n\n    return success;\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for \n * Utility::Quad. \n * \\ingroup compare_policy\n */\ntemplate<typename T, typename T2, typename T3, typename T4>\nstruct ComparePolicy<Quad<T,T2,T3,T4> >\n{\n  typedef double scalarType;\n  \n  static inline bool compare( const Quad<T,T2,T3,T4> &first_value,\n\t\t\t      const std::string &first_name,\n\t\t\t      const Quad<T,T2,T3,T4> &second_value,\n\t\t\t      const std::string &second_name,\n\t\t\t      Teuchos::FancyOStream &out,\n\t\t\t      const int index = -1,\n\t\t\t      const scalarType tol = 0.0 )\n  {\n    return ComparePolicy<const Quad<T,T2,T3,T4> >::compare( first_value,\n\t\t\t\t\t\t\t    first_name,\n\t\t\t\t\t\t\t    second_value,\n\t\t\t\t\t\t\t    second_name,\n\t\t\t\t\t\t\t    out,\n\t\t\t\t\t\t\t    index,\n\t\t\t\t\t\t\t    tol );\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for\n * const boost::units::quantity.\n * \\ingroup compare_policy\n */\ntemplate<typename Unit, typename T>\nstruct ComparePolicy<const boost::units::quantity<Unit,T> >\n{\n  typedef const T scalarType;\n\n  static inline bool compare(const boost::units::quantity<Unit,T>& first_value,\n\t\t\t     const std::string& first_name,\n\t\t\t     const boost::units::quantity<Unit,T>& second_value,\n\t\t\t     const std::string& second_name,\n\t\t\t     Teuchos::FancyOStream &out,\n\t\t\t     const int index = -1,\n\t\t\t     const scalarType tol = 0.0 )\n  {\n    bool success = true;\n      \n    if( tol == 0.0 )\n    {\n      // Array Element Compare\n      if( index >= 0 )\n      {\n\tout << \"\\nError, \" << first_name << \"[\" << index << \"]\" << \" = \"\n\t    << first_value << \" == \" << second_name << \"[\" << index << \"]\" \n\t    << \" = \" << second_value << \": \";\n\tif( first_value != second_value )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n      // Single Compare\n      else\n      {\n\tout << first_name << \" = \" << first_value\n\t    << \" == \" << second_name << \" = \" << second_value \n\t    << \": \";\n\tif( first_value != second_value )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n    }\n    else\n    {\n      double err = relError( first_value.value(), second_value.value() );\n      \n      // Array Element Compare\n      if( index >= 0 )\n      {\n\tout << \"\\nError, relErr(\" << first_name << \"[\" << index << \"],\"\n\t    << second_name << \"[\" << index << \"])\" << \" = relErr(\" \n\t    << first_value << \",\" << second_value << \") = \" << err\n\t    << \" <= tol = \" << tol << \": \";\n\tif( err > tol )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n      // Single Compare\n      else\n      {\n\tout << \"\\nCheck: relErr(\" << first_name << \",\" << second_name << \")\"\n\t    << \"\\n= relErr(\" << first_value << \",\" << second_value << \") = \"\n\t    << err << \"\\n<= tol = \" << tol << \": \";\n\tif( err > tol )\n\t{\n\t  out << \"failed!\\n\";\n\n\t  success = false;\n\t}\n\telse \n\t  out << \"passed\\n\";\n      }\n    }\n    \n    return success;\n  }\n};\n\n/*! \\brief The partial specialization of the Utility::ComparePolicy for\n * boost::units::quantity.\n * \\ingroup compare_policy\n */\ntemplate<typename Unit, typename T>\nstruct ComparePolicy<boost::units::quantity<Unit,T> >\n{\n  typedef T scalarType;\n\n  static inline bool compare(const boost::units::quantity<Unit,T>& first_value,\n\t\t\t     const std::string& first_name,\n\t\t\t     const boost::units::quantity<Unit,T>& second_value,\n\t\t\t     const std::string& second_name,\n\t\t\t     Teuchos::FancyOStream &out,\n\t\t\t     const int index = -1,\n\t\t\t     const scalarType tol = 0.0 )\n  {\n    return ComparePolicy<const boost::units::quantity<Unit,T> >::compare( \n\t\t\t\t\t\t\t    first_value,\n\t\t\t\t\t\t\t    first_name,\n\t\t\t\t\t\t\t    second_value,\n\t\t\t\t\t\t\t    second_name,\n\t\t\t\t\t\t\t    out,\n\t\t\t\t\t\t\t    index,\n\t\t\t\t\t\t\t    tol );\n  }\n};\t\t\t\t\t\t\t\t\t \n\n} // end Policy namespace\n\n} // end Utility namespace\n\n#endif // end UTILITY_COMPARE_POLICY_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_ComparePolicy.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "ba92adb99c78edc96d94ddfa724b9c81fd006f0b", "size": 30895, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/src/Utility_ComparePolicy.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_ComparePolicy.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_ComparePolicy.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": 24.7556089744, "max_line_length": 79, "alphanum_fraction": 0.5686357016, "num_tokens": 7338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.04146227582056014, "lm_q1q2_score": 0.02024534081435549}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Classes     : BootstrapSamplerBase, BootstrapSampler, BootstrapSamplerWithGS\n//- Description : Functors for performing bootstrap sampling on a dataset\n//- Owner       : Brian Adams\n//- Checked by  :\n//- Version     :\n\n#ifndef __DAKOTA_BOOTSTRAP_SAMPLER_H__\n#define __DAKOTA_BOOTSTRAP_SAMPLER_H__\n\n\n#include <iostream>\n#include <stdexcept>\n#include <cstring>\n#include <vector>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include \"Teuchos_SerialDenseVector.hpp\"\n#include \"Teuchos_SerialDenseHelpers.hpp\"\n\nnamespace Dakota {\n\n/// Base class/interface for the bootstrap sampler\n\n/** BootstrapSamplerBase defines the minimum interface for a bootstrap sampler\n    and handles initialization of the random variate generation used by the\n    bootstrap. Functor is templated on the data type, but does not actually\n    define a data member. */\ntemplate<typename Data>\nclass BootstrapSamplerBase\n{\npublic:\n\n  //\n  //- Heading: Static methods for access to random variate generation\n  //\n\n  static void set_seed(size_t seed)\n  {\n    bootstrapRNG.seed(seed);\n  }\n\n  //\n  //- Heading: Constructors and destructor\n  //\n\n  /// Constructor for the bootstrap functor base\n  BootstrapSamplerBase(size_t data_size, Data orig_data) : dataSize(data_size),\n                          origData(orig_data), sampler(0, data_size - 1)\n  {\n  }\n\n  /// Destructor\n  virtual ~BootstrapSamplerBase()\n  {\n    /* empty destructor */\n  }\n\n  //\n  //- Heading: Public members functions that perform for boostrap sampling\n  //\n\n  /// Generate and store a new boostrapped sample into bootstrapped_sample\n  virtual void operator()(size_t num_samp, Data& bootstrapped_sample) = 0;\n\n  /// Obatin the number of samples used in the empirical distribution\n  virtual size_t getDataSize()\n  {\n    return dataSize;\n  }\n\n  /// Generate and store an dataSize out of dataSize boostrap sample\n  virtual void operator()(Data& bootstrapped_sample)\n  {\n    (*this)(dataSize, bootstrapped_sample);\n  }\n\n  /// Return boostrapped sample\n  virtual Data operator()()\n  {\n    Data sample(origData);\n    (*this)(dataSize, sample);\n    return sample;\n  }\n\nprotected:\n\n  // Internal static members for random variate generation\n\n  /// Random number generator to use for sampling\n  static boost::random::mt19937 bootstrapRNG;\n\n  // Internal instance members\n\n  /// Uniform distribution to provide samples from the empirical distribution\n  boost::random::uniform_int_distribution<> sampler;\n\n  /// Size of the dataset defining the empirical distribution\n  const size_t dataSize;\n\n  /// Original data defining the empirical distribution\n  /// TODO: Consider if it should be const (breaks Teuchos)\n  Data origData;\n};\n\n/// The boostrap random number generator\ntemplate<typename Data>\nboost::random::mt19937 BootstrapSamplerBase<Data>::bootstrapRNG;\n\n\n/// Actual boostrap sampler implementation for common data types\n\n/** Template requires the given type to support an STL-like interface, including\n    a size method and begin and end methods returning random access iterators */\ntemplate<typename Data>\nclass BootstrapSampler : public BootstrapSamplerBase<Data>\n{\npublic:\n\n  //\n  //- Heading: Type definitions and aliases\n  //\n\n  using BootstrapSamplerBase<Data>::operator();\n\n  //\n  //- Heading: Constructors and destructor\n  //\n\n  /// Constructor for the sampler\n  BootstrapSampler(const Data& orig_data, size_t block_size = 1) :\n    BootstrapSamplerBase<Data>::BootstrapSamplerBase(\n      block_size ? orig_data.size()/block_size : orig_data.size(), orig_data),\n      blockSize(block_size ? block_size : 1)\n  {\n    if(block_size &&\n      (block_size > this->dataSize || orig_data.size() % block_size != 0))\n        throw \"Boostrap sampler data size must be a multiple of block size.\";\n  }\n\n  /// Destructor\n  virtual ~BootstrapSampler()\n  {\n    /* empty destructor */\n  }\n\n  //\n  //- Heading: Public members functions that perform for boostrap sampling\n  //\n\n  /// \\copydoc\n  virtual void operator()(size_t num_samp, Data& bootstrapped_sample)\n  {\n    if(num_samp > bootstrapped_sample.size()/blockSize)\n      throw\n        std::out_of_range(\"Number of samples exceeds the size of container\");\n\n    typename Data::iterator beg_data = this->origData.begin();\n    for(typename Data::iterator sample = bootstrapped_sample.begin();\n        sample != bootstrapped_sample.end(); sample += blockSize)\n    {\n      typename Data::iterator beg_block = beg_data + \n\t      this->sampler(this->bootstrapRNG) * blockSize;\n      for(size_t i = 0; i < blockSize; ++i)\n      {\n        *(sample + i) = *(beg_block + i);\n      }\n    }\n  }\n\nprotected:\n\n  // Internal instance members\n\n  /// Size of the block defining a sample\n  size_t blockSize;\n};\n\n\n/// Bootstrap sampler that is specialized to allow for the boostrapping of\n/// RealMatrix\ntemplate<typename OrdinalType, typename ScalarType>\nclass BootstrapSampler<Teuchos::SerialDenseMatrix<OrdinalType, ScalarType> > :\n  public BootstrapSamplerBase<Teuchos::\n                              SerialDenseMatrix<OrdinalType, ScalarType> >\n{\npublic:\n\n  //\n  //- Heading: Type definitions and aliases\n  //\n\n  /// Convenience definition\n  typedef Teuchos::SerialDenseMatrix<OrdinalType, ScalarType> MatType;\n\n  using BootstrapSamplerBase<MatType>::operator();\n\n  /// Constructor for the sampler.\n  BootstrapSampler(const MatType& orig_data, size_t block_size = 1) :\n    BootstrapSamplerBase<MatType>::BootstrapSamplerBase(\n      block_size ? orig_data.numCols()/block_size : orig_data.numCols(),\n      orig_data),\n      blockSize(block_size ? block_size : 1)\n  {\n    if(block_size &&\n      (block_size > this->dataSize || orig_data.numCols() % block_size != 0))\n        throw \"Boostrap sampler data size must be a multiple of block size.\";\n  }\n\n  /// Destructor\n  virtual ~BootstrapSampler()\n  {\n    /* empty destructor */\n  }\n\n  //\n  //- Heading: Public members functions that perform boostrap sampling\n  //\n\n  /// \\copydoc\n  virtual void operator()(size_t num_samp, MatType& bootstrapped_sample)\n  {\n    OrdinalType stride = this->origData.stride();\n    if(stride != bootstrapped_sample.stride())\n      throw\n          std::out_of_range(\"Dimension of a boostrapped sample differs from \"\n                            \"the dimension of the original dataset\");\n\n    if(num_samp > bootstrapped_sample.numCols()/blockSize)\n      throw\n        std::out_of_range(\"Number of samples exceeds the size of container\");\n\n    for(int i = 0; i < num_samp * blockSize; i += blockSize)\n    {\n      std::memcpy(bootstrapped_sample[i],\n        this->origData[this->sampler(this->bootstrapRNG) * blockSize],\n        blockSize * stride * sizeof(ScalarType));\n    }\n  }\n\nprotected:\n\n  // Internal instance members\n\n  /// Size of the block defining a sample\n  size_t blockSize;\n};\n\n\n/// A derived sampler to allow for user specification of the accessor methods\ntemplate<typename Data, typename Getter, typename Setter>\nclass BootstrapSamplerWithGS : public BootstrapSampler<Data>\n{\npublic:\n\n  //\n  //- Heading: Type definitions and aliases\n  //\n\n  using BootstrapSampler<Data>::operator();\n\n  //\n  //- Heading: Constructors and destructor\n  //\n\n  /// Constructor with extra arguments for the accessor methods\n  BootstrapSamplerWithGS(const Data& orig_data,\n                         Getter getter_method,\n                         Setter setter_method) :\n                         BootstrapSampler<Data>::BootstrapSampler(orig_data),\n                         getterMethod(getter_method),\n                         setterMethod(setter_method)\n  {\n  }\n\n  /// Destructor\n virtual  ~BootstrapSamplerWithGS()\n  {\n    /* empty destructor */\n  }\n\n  //\n  //- Heading: Public members functions that perform for boostrap sampling\n  //\n\n  /// Generate and store a new boostrapped sample into bootstrapped_sample\n  /// TODO: bounds checking\n  virtual void operator()(size_t num_samp, Data& bootstrapped_sample)\n  {\n    for(size_t i = 0; i < num_samp; ++i)\n    {\n      setterMethod(i, getterMethod(this->sampler(this->bootstrapRNG),\n                                   this->origData), bootstrapped_sample);\n    }\n  }\n\nprotected:\n\n  // Internal instance members\n\n  /// Function to obtain a single sample from a Data object. Function should\n  /// take a Data object and an unsigned integer corresponding to a sample\n  /// index and return the sample\n  Getter getterMethod;\n\n  /// Function to place a single sample into a Data object. Function should\n  /// take a Data object and an unsigned integer corresponding to the sample\n  /// index to set.\n  Setter setterMethod;\n};\n\n}\n\n#endif // __DAKOTA_BOOTSTRAP_SAMPLER_H__\n", "meta": {"hexsha": "caf5a36a3b82922ab339aae20b43c98ed597dd84", "size": 9023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BootstrapSampler.hpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BootstrapSampler.hpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BootstrapSampler.hpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0217391304, "max_line_length": 80, "alphanum_fraction": 0.6994347778, "num_tokens": 1974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.051082740026862944, "lm_q1q2_score": 0.02023224644239012}}
{"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_VECTOR_ASSIGN_H\r\n#define BOOST_UBLAS_VECTOR_ASSIGN_H\r\n\r\n#include <boost/numeric/ublas/config.hpp>\r\n#include <boost/numeric/ublas/vector_expression.hpp>\r\n\r\n// Iterators based on ideas of Jeremy Siek\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    template<class E1, class E2>\r\n    BOOST_UBLAS_INLINE\r\n    bool equals (const vector_expression<E1> &e1, const vector_expression<E2> &e2) {\r\n        typedef BOOST_UBLAS_TYPENAME type_traits<BOOST_UBLAS_TYPENAME promote_traits<BOOST_UBLAS_TYPENAME E1::value_type,\r\n                                                                                     BOOST_UBLAS_TYPENAME E2::value_type>::promote_type>::real_type real_type;\r\n#ifndef __GNUC__\r\n        return norm_inf (e1 - e2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\r\n               std::max<real_type> (std::max<real_type> (norm_inf (e1),\r\n                                                         norm_inf (e2)),\r\n                                    BOOST_UBLAS_TYPE_CHECK_MIN);\r\n#else\r\n        // GCC 3.1, oops?!\r\n        return norm_inf (e1 - e2) < BOOST_UBLAS_TYPE_CHECK_EPSILON *\r\n               (std::max) (real_type ((std::max) (real_type (norm_inf (e1)), real_type (norm_inf (e2)))),\r\n                         real_type (BOOST_UBLAS_TYPE_CHECK_MIN));\r\n#endif\r\n    }\r\n\r\n\r\n    // Make sparse proxies conformant\r\n    template<class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void make_conformant (V &v, const vector_expression<E> &e) {\r\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typedef typename V::value_type value_type;\r\n        // FIXME unbounded_array with push_back maybe better\r\n        std::vector<size_type> index;\r\n        typename V::iterator it (v.begin ());\r\n        typename V::iterator it_end (v.end ());\r\n        typename E::const_iterator ite (e ().begin ());\r\n        typename E::const_iterator ite_end (e ().end ());\r\n        if (it != it_end && ite != ite_end) {\r\n            size_type it_index = it.index (), ite_index = ite.index ();\r\n            while (true) {\r\n                difference_type compare = it_index - ite_index;\r\n                if (compare == 0) {\r\n                    ++ it, ++ ite;\r\n                    if (it != it_end && ite != ite_end) {\r\n                        it_index = it.index ();\r\n                        ite_index = ite.index ();\r\n                    } else\r\n                        break;\r\n                } else if (compare < 0) {\r\n                    increment (it, it_end, - compare);\r\n                    if (it != it_end)\r\n                        it_index = it.index ();\r\n                    else\r\n                        break;\r\n                } else if (compare > 0) {\r\n                    if (*ite != value_type (0))\r\n                        index.push_back (ite.index ());\r\n                    ++ ite;\r\n                    if (ite != ite_end)\r\n                        ite_index = ite.index ();\r\n                    else\r\n                        break;\r\n                }\r\n            }\r\n        }\r\n\r\n        while (ite != ite_end) {\r\n            if (*ite != value_type (0))\r\n                index.push_back (ite.index ());\r\n            ++ ite;\r\n        }\r\n        for (size_type k = 0; k < index.size (); ++ k)\r\n            v (index [k]) = value_type (0);\r\n    }\r\n\r\n    // Iterating case\r\n    template<class F, class V, class T>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void iterating_vector_assign_scalar (F, V &v, const T &t) {\r\n        typedef F functor_type;\r\n        typedef typename V::difference_type difference_type;\r\n        difference_type size (v.size ());\r\n        typename V::iterator it (v.begin ());\r\n        BOOST_UBLAS_CHECK (v.end () - it == size, bad_size ());\r\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\r\n        while (-- size >= 0)\r\n            functor_type::apply (*it, t), ++ it;\r\n#else\r\n        DD (size, 4, r, (functor_type::apply (*it, t), ++ it));\r\n#endif\r\n    }\r\n    // Indexing case\r\n    template<class F, class V, class T>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void indexing_vector_assign_scalar (F, V &v, const T &t) {\r\n        typedef F functor_type;\r\n        typedef typename V::size_type size_type;\r\n        size_type size (v.size ());\r\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\r\n        for (size_type i = 0; i < size; ++ i)\r\n            functor_type::apply (v (i), t);\r\n#else\r\n        size_type i (0);\r\n        DD (size, 4, r, (functor_type::apply (v (i), t), ++ i));\r\n#endif\r\n    }\r\n\r\n    // Dense (proxy) case\r\n    template<class F, class V, class T>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_assign_scalar (F, V &v, const T &t, dense_proxy_tag) {\r\n        typedef F functor_type;\r\n#ifdef BOOST_UBLAS_USE_INDEXING\r\n        indexing_vector_assign_scalar (functor_type (), v, t);\r\n#elif BOOST_UBLAS_USE_ITERATING\r\n        iterating_vector_assign_scalar (functor_type (), v, t);\r\n#else\r\n        typedef typename V::size_type size_type;\r\n        size_type size (v.size ());\r\n        if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\r\n            iterating_vector_assign_scalar (functor_type (), v, t);\r\n        else\r\n            indexing_vector_assign_scalar (functor_type (), v, t);\r\n#endif\r\n    }\r\n    // Packed (proxy) case\r\n    template<class F, class V, class T>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_assign_scalar (F, V &v, const T &t, packed_proxy_tag) {\r\n        typedef F functor_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typename V::iterator it (v.begin ());\r\n        difference_type size (v.end () - it);\r\n        while (-- size >= 0)\r\n            functor_type::apply (*it, t), ++ it;\r\n    }\r\n    // Sparse (proxy) case\r\n    template<class F, class V, class T>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_assign_scalar (F, V &v, const T &t, sparse_proxy_tag) {\r\n        typedef F functor_type;\r\n        typename V::iterator it (v.begin ());\r\n        typename V::iterator it_end (v.end ());\r\n        while (it != it_end)\r\n            functor_type::apply (*it, t), ++ it;\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class F, class V, class T>\r\n    BOOST_UBLAS_INLINE\r\n    void vector_assign_scalar (F, V &v, const T &t) {\r\n        typedef F functor_type;\r\n        typedef typename V::storage_category storage_category;\r\n        vector_assign_scalar (functor_type (), v, t, storage_category ());\r\n    }\r\n\r\n    template<class LS, class A, class RI>\r\n    struct vector_assign_traits {\r\n        typedef LS storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct vector_assign_traits<dense_tag, assign_tag, packed_random_access_iterator_tag> {\r\n        typedef packed_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<dense_tag, computed_assign_tag, packed_random_access_iterator_tag> {\r\n        typedef packed_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<dense_tag, assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<dense_tag, computed_assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct vector_assign_traits<dense_proxy_tag, assign_tag, packed_random_access_iterator_tag> {\r\n        typedef packed_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<dense_proxy_tag, computed_assign_tag, packed_random_access_iterator_tag> {\r\n        typedef packed_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<dense_proxy_tag, assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<dense_proxy_tag, computed_assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct vector_assign_traits<packed_tag, assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<packed_tag, computed_assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct vector_assign_traits<packed_proxy_tag, assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<packed_proxy_tag, computed_assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct vector_assign_traits<sparse_tag, computed_assign_tag, dense_random_access_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<sparse_tag, computed_assign_tag, packed_random_access_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n    template<>\r\n    struct vector_assign_traits<sparse_tag, computed_assign_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    // Iterating case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void iterating_vector_assign (F, V &v, const vector_expression<E> &e) {\r\n        typedef F functor_type;\r\n        typedef typename V::difference_type difference_type;\r\n        difference_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\r\n        typename V::iterator it (v.begin ());\r\n        BOOST_UBLAS_CHECK (v.end () - it == size, bad_size ());\r\n        typename E::const_iterator ite (e ().begin ());\r\n        BOOST_UBLAS_CHECK (e ().end () - ite == size, bad_size ());\r\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\r\n        while (-- size >= 0)\r\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\r\n#else\r\n        DD (size, 2, r, (functor_type::apply (*it, *ite), ++ it, ++ ite));\r\n#endif\r\n    }\r\n    // Indexing case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void indexing_vector_assign (F, V &v, const vector_expression<E> &e) {\r\n        typedef F functor_type;\r\n        typedef typename V::size_type size_type;\r\n        size_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\r\n#ifndef BOOST_UBLAS_USE_DUFF_DEVICE\r\n        for (size_type i = 0; i < size; ++ i)\r\n            functor_type::apply (v (i), e () (i));\r\n#else\r\n        size_type i (0);\r\n        DD (size, 2, r, (functor_type::apply (v (i), e () (i)), ++ i));\r\n#endif\r\n    }\r\n\r\n    // Dense (proxy) case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_assign (F, V &v, const vector_expression<E> &e, dense_proxy_tag) {\r\n        typedef F functor_type;\r\n#ifdef BOOST_UBLAS_USE_INDEXING\r\n        indexing_vector_assign (functor_type (), v, e);\r\n#elif BOOST_UBLAS_USE_ITERATING\r\n        iterating_vector_assign (functor_type (), v, e);\r\n#else\r\n        typedef typename V::size_type size_type;\r\n        size_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\r\n        if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\r\n            iterating_vector_assign (functor_type (), v, e);\r\n        else\r\n            indexing_vector_assign (functor_type (), v, e);\r\n#endif\r\n    }\r\n    // Packed (proxy) case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_assign (F, V &v, const vector_expression<E> &e, packed_proxy_tag) {\r\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\r\n        typedef F functor_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typedef typename V::value_type value_type;\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        vector<value_type> cv (v.size ());\r\n#ifndef BOOST_UBLAS_NO_ELEMENT_PROXIES\r\n        indexing_vector_assign (scalar_assign<typename vector<value_type>::reference, value_type> (), cv, v);\r\n        indexing_vector_assign (functor_type::template make_debug_functor<typename vector<value_type>::reference, value_type> (), cv, e);\r\n#else\r\n        indexing_vector_assign (scalar_assign<value_type&, value_type> (), cv, v);\r\n        indexing_vector_assign (functor_type (), cv, e);\r\n#endif\r\n#endif\r\n        typename V::iterator it (v.begin ());\r\n        typename V::iterator it_end (v.end ());\r\n        typename E::const_iterator ite (e ().begin ());\r\n        typename E::const_iterator ite_end (e ().end ());\r\n        difference_type it_size (it_end - it);\r\n        difference_type ite_size (ite_end - ite);\r\n        if (it_size > 0 && ite_size > 0) {\r\n            difference_type size ((std::min) (difference_type (it.index () - ite.index ()), ite_size));\r\n            if (size > 0) {\r\n                ite += size;\r\n                ite_size -= size;\r\n            }\r\n        }\r\n        if (it_size > 0 && ite_size > 0) {\r\n            difference_type size ((std::min) (difference_type (ite.index () - it.index ()), it_size));\r\n            if (size > 0) {\r\n                it_size -= size;\r\n                if (boost::is_same<BOOST_UBLAS_TYPENAME functor_type::assign_category, assign_tag>::value) {\r\n                    while (-- size >= 0)\r\n                        functor_type::apply (*it, value_type (0)), ++ it;\r\n                } else {\r\n                    it += size;\r\n                }\r\n            }\r\n        }\r\n        difference_type size ((std::min) (it_size, ite_size));\r\n        it_size -= size;\r\n        ite_size -= size;\r\n        while (-- size >= 0)\r\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\r\n        size = it_size;\r\n        if (boost::is_same<BOOST_UBLAS_TYPENAME functor_type::assign_category, assign_tag>::value) {\r\n            while (-- size >= 0)\r\n                functor_type::apply (*it, value_type (0)), ++ it;\r\n        } else {\r\n            it += size;\r\n        }\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        if (! disable_type_check<bool>::value)\r\n            BOOST_UBLAS_CHECK (equals (v, cv), external_logic ());\r\n#endif\r\n    }\r\n    // Sparse case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_assign (F, V &v, const vector_expression<E> &e, sparse_tag) {\r\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\r\n        typedef F functor_type;\r\n        typedef typename V::value_type value_type;\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        vector<value_type> cv (v.size ());\r\n#ifndef BOOST_UBLAS_NO_ELEMENT_PROXIES\r\n        indexing_vector_assign (scalar_assign<typename vector<value_type>::reference, value_type> (), cv, v);\r\n        indexing_vector_assign (functor_type::template make_debug_functor<typename vector<value_type>::reference, value_type> (), cv, e);\r\n#else\r\n        indexing_vector_assign (scalar_assign<value_type&, value_type> (), cv, v);\r\n        indexing_vector_assign (functor_type (), cv, e);\r\n#endif\r\n#endif\r\n        v.clear ();\r\n        typename E::const_iterator ite (e ().begin ());\r\n        typename E::const_iterator ite_end (e ().end ());\r\n        while (ite != ite_end) {\r\n            value_type t (*ite);\r\n            if (t != value_type (0))\r\n                v.insert (ite.index (), t);\r\n            ++ ite;\r\n        }\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        if (! disable_type_check<bool>::value)\r\n            BOOST_UBLAS_CHECK (equals (v, cv), external_logic ());\r\n#endif\r\n    }\r\n    // Sparse proxy case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_assign (F, V &v, const vector_expression<E> &e, sparse_proxy_tag) {\r\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\r\n        typedef F functor_type;\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typedef typename V::value_type value_type;\r\n        typedef typename V::reference reference;\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        vector<value_type> cv (v.size ());\r\n#ifndef BOOST_UBLAS_NO_ELEMENT_PROXIES\r\n        indexing_vector_assign (scalar_assign<typename vector<value_type>::reference, value_type> (), cv, v);\r\n        indexing_vector_assign (functor_type::template make_debug_functor<typename vector<value_type>::reference, value_type> (), cv, e);\r\n#else\r\n        indexing_vector_assign (scalar_assign<value_type&, value_type> (), cv, v);\r\n        indexing_vector_assign (functor_type (), cv, e);\r\n#endif\r\n#endif\r\n#ifdef BOOST_UBLAS_NON_CONFORMANT_PROXIES\r\n        make_conformant (v, e);\r\n#endif\r\n        typename V::iterator it (v.begin ());\r\n        typename V::iterator it_end (v.end ());\r\n        typename E::const_iterator ite (e ().begin ());\r\n        typename E::const_iterator ite_end (e ().end ());\r\n        if (it != it_end && ite != ite_end) {\r\n            size_type it_index = it.index (), ite_index = ite.index ();\r\n            while (true) {\r\n                difference_type compare = it_index - ite_index;\r\n                if (compare == 0) {\r\n                    functor_type::apply (*it, *ite);\r\n                    ++ it, ++ ite;\r\n                    if (it != it_end && ite != ite_end) {\r\n                        it_index = it.index ();\r\n                        ite_index = ite.index ();\r\n                    } else\r\n                        break;\r\n                } else if (compare < 0) {\r\n                    if (boost::is_same<BOOST_UBLAS_TYPENAME functor_type::assign_category, assign_tag>::value) {\r\n                        functor_type::apply (*it, value_type (0));\r\n                        ++ it;\r\n                    } else\r\n                        increment (it, it_end, - compare);\r\n                    if (it != it_end)\r\n                        it_index = it.index ();\r\n                    else\r\n                        break;\r\n                } else if (compare > 0) {\r\n                    increment (ite, ite_end, compare);\r\n                    if (ite != ite_end)\r\n                        ite_index = ite.index ();\r\n                    else\r\n                        break;\r\n                }\r\n            }\r\n        }\r\n\r\n        if (boost::is_same<BOOST_UBLAS_TYPENAME functor_type::assign_category, assign_tag>::value) {\r\n            while (it != it_end) {\r\n                functor_type::apply (*it, value_type (0));\r\n                ++ it;\r\n            }\r\n        } else {\r\n            it = it_end;\r\n        }\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        if (! disable_type_check<bool>::value)\r\n            BOOST_UBLAS_CHECK (equals (v, cv), external_logic ());\r\n#endif\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class F, class V, class E>\r\n    BOOST_UBLAS_INLINE\r\n    void vector_assign (F, V &v, const vector_expression<E> &e) {\r\n        typedef F functor_type;\r\n        typedef typename vector_assign_traits<BOOST_UBLAS_TYPENAME V::storage_category,\r\n                                              BOOST_UBLAS_TYPENAME F::assign_category,\r\n                                              BOOST_UBLAS_TYPENAME E::const_iterator::iterator_category>::storage_category storage_category;\r\n        vector_assign (functor_type (), v, e, storage_category ());\r\n    }\r\n\r\n    template<class LS, class RI>\r\n    struct vector_swap_traits {\r\n        typedef LS storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct vector_swap_traits<dense_proxy_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    template<>\r\n    struct vector_swap_traits<packed_proxy_tag, sparse_bidirectional_iterator_tag> {\r\n        typedef sparse_proxy_tag storage_category;\r\n    };\r\n\r\n    // Dense (proxy) case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_swap (F, V &v, vector_expression<E> &e, dense_proxy_tag) {\r\n        typedef F functor_type;\r\n        typedef typename V::difference_type difference_type;\r\n        difference_type size (BOOST_UBLAS_SAME (v.size (), e ().size ()));\r\n        typename V::iterator it (v.begin ());\r\n        typename E::iterator ite (e ().begin ());\r\n        while (-- size >= 0)\r\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\r\n    }\r\n    // Packed (proxy) case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_swap (F, V &v, vector_expression<E> &e, packed_proxy_tag) {\r\n        typedef F functor_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typename V::iterator it (v.begin ());\r\n        typename V::iterator it_end (v.end ());\r\n        typename E::iterator ite (e ().begin ());\r\n        typename E::iterator ite_end (e ().end ());\r\n        difference_type it_size (it_end - it);\r\n        difference_type ite_size (ite_end - ite);\r\n        if (it_size > 0 && ite_size > 0) {\r\n            difference_type size ((std::min) (difference_type (it.index () - ite.index ()), ite_size));\r\n            if (size > 0) {\r\n                ite += size;\r\n                ite_size -= size;\r\n            }\r\n        }\r\n        if (it_size > 0 && ite_size > 0) {\r\n            difference_type size ((std::min) (difference_type (ite.index () - it.index ()), it_size));\r\n            if (size > 0)\r\n                it_size -= size;\r\n        }\r\n        difference_type size ((std::min) (it_size, ite_size));\r\n        it_size -= size;\r\n        ite_size -= size;\r\n        while (-- size >= 0)\r\n            functor_type::apply (*it, *ite), ++ it, ++ ite;\r\n    }\r\n    // Sparse proxy case\r\n    template<class F, class V, class E>\r\n    // This function seems to be big. So we do not let the compiler inline it.\r\n    // BOOST_UBLAS_INLINE\r\n    void vector_swap (F, V &v, vector_expression<E> &e, sparse_proxy_tag) {\r\n        BOOST_UBLAS_CHECK (v.size () == e ().size (), bad_size ());\r\n        typedef F functor_type;\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typedef typename V::value_type value_type;\r\n#ifdef BOOST_UBLAS_NON_CONFORMANT_PROXIES\r\n        make_conformant (v, e);\r\n        make_conformant (e (), v);\r\n#endif\r\n        typename V::iterator it (v.begin ());\r\n        typename V::iterator it_end (v.end ());\r\n        typename E::iterator ite (e ().begin ());\r\n        typename E::iterator ite_end (e ().end ());\r\n        if (it != it_end && ite != ite_end) {\r\n            size_type it_index = it.index (), ite_index = ite.index ();\r\n            while (true) {\r\n                difference_type compare = it_index - ite_index;\r\n                if (compare == 0) {\r\n                    functor_type::apply (*it, *ite);\r\n                    ++ it, ++ ite;\r\n                    if (it != it_end && ite != ite_end) {\r\n                        it_index = it.index ();\r\n                        ite_index = ite.index ();\r\n                    } else\r\n                        break;\r\n                } else if (compare < 0) {\r\n                    increment (it, it_end, - compare);\r\n                    if (it != it_end)\r\n                        it_index = it.index ();\r\n                    else\r\n                        break;\r\n                } else if (compare > 0) {\r\n                    increment (ite, ite_end, compare);\r\n                    if (ite != ite_end)\r\n                        ite_index = ite.index ();\r\n                    else\r\n                        break;\r\n                }\r\n            }\r\n        }\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\n        increment (ite, ite_end);\r\n        increment (it, it_end);\r\n#endif\r\n    }\r\n\r\n    // Dispatcher\r\n    template<class F, class V, class E>\r\n    BOOST_UBLAS_INLINE\r\n    void vector_swap (F, V &v, vector_expression<E> &e) {\r\n        typedef F functor_type;\r\n        typedef typename vector_swap_traits<BOOST_UBLAS_TYPENAME V::storage_category,\r\n                                            BOOST_UBLAS_TYPENAME E::const_iterator::iterator_category>::storage_category storage_category;\r\n        vector_swap (functor_type (), v, e, storage_category ());\r\n    }\r\n\r\n}}}\r\n\r\n#endif\r\n", "meta": {"hexsha": "aceb749231a4c47dc047ed5f773459cecddbc778", "size": 25577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/vector_assign.hpp", "max_stars_repo_name": "macaurther/DOCUSA", "max_stars_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/vector_assign.hpp", "max_issues_repo_name": "macaurther/DOCUSA", "max_issues_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/numeric/ublas/vector_assign.hpp", "max_forks_repo_name": "dguenms/Dawn-of-Civilization", "max_forks_repo_head_hexsha": "1c4f510af97a869637cddb4c0859759158cea5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 41.7924836601, "max_line_length": 159, "alphanum_fraction": 0.5783320952, "num_tokens": 5894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.04742587435564, "lm_q1q2_score": 0.020218674283253628}}
{"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_DMAT_DMAT_MULT_INCLUDE\n#define MTL_DMAT_DMAT_MULT_INCLUDE\n\n#include <boost/mpl/bool.hpp>\n#include <boost/utility/enable_if.hpp>\n\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/operation/cursor_pseudo_dot.hpp>\n#include <boost/numeric/mtl/operation/multi_action_block.hpp>\n#include <boost/numeric/mtl/operation/assign_mode.hpp>\n#include <boost/numeric/mtl/operation/static_size.hpp>\n#include <boost/numeric/mtl/operation/static_num_rows.hpp>\n#include <boost/numeric/mtl/operation/static_num_cols.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/flatcat.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/glas_tag.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/is_static.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/utility/assert.hpp>\n#include <boost/numeric/meta_math/loop.hpp>\n#include <boost/numeric/mtl/recursion/base_case_test.hpp>\n#include <boost/numeric/mtl/recursion/base_case_matrix.hpp>\n#include <boost/numeric/mtl/recursion/matrix_recursator.hpp>\n#include <boost/numeric/mtl/recursion/base_case_cast.hpp>\n#include <boost/numeric/mtl/interface/blas.hpp>\n\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/operation/no_op.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <iostream>\n#include <complex>\n\nnamespace mtl {\n\n// =====================================================\n// Generic matrix product with cursors and property maps\n// =====================================================\n   \n\n// To allow 5th parameter, is ignored\n// This is the bottom line of dmat_dmat_mult implementations.\n// All MTL4 matrix types and views (so far) have cursors and property maps\n// so that we disabled the backup functor by default.\n// If some type has no cursor, one can still use a backup functor (whatever this may be).\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign= assign::assign_sum,\n\t  typename Backup= no_op> \nstruct gen_cursor_dmat_dmat_mult_ft\n{\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tapply(A, B, C, traits::flatcat1<MatrixA, tag::has_cursor>(), traits::flatcat1<MatrixB, tag::has_cursor>());\n    }   \n\nprivate:\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::universe, tag::universe)\n    {\n\tBackup()(A, B, C);\n    }\n\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::flat<tag::has_cursor>, tag::flat<tag::has_cursor>)\n    {\n\t// asm(\"#cursor\");\n\tvampir_trace<4001> tracer;\n\t// std::cout << \"Canonical cursor\\n\";\n\ttypedef glas::tag::row                                          row;\n\ttypedef glas::tag::col                                          col;\n\ttypedef glas::tag::all                                          all;\n\n        typedef typename traits::const_value<MatrixA>::type                a_value_type;\n        typedef typename traits::const_value<MatrixB>::type                b_value_type;\n        typedef typename traits::value<MatrixC>::type                      c_value_type;\n\n        typedef typename traits::range_generator<row, MatrixA>::type     a_cur_type;\n        typedef typename traits::range_generator<row, MatrixC>::type     c_cur_type;\n        \n        typedef typename traits::range_generator<col, MatrixB>::type     b_cur_type;\n        typedef typename traits::range_generator<all, c_cur_type>::type  c_icur_type;\n\n        typedef typename traits::range_generator<all, a_cur_type>::type  a_icur_type;\n        typedef typename traits::range_generator<all, b_cur_type>::type  b_icur_type;\n\n#ifndef NDEBUG\n\ttypename traits::row<MatrixA>::type                              row_a(A); \n\ttypename traits::col<MatrixA>::type                              col_a(A); \n\ttypename traits::row<MatrixB>::type                              row_b(B); \n\ttypename traits::col<MatrixB>::type                              col_b(B); \n\ttypename traits::row<MatrixC>::type                              row_c(C); \n\ttypename traits::col<MatrixC>::type                              col_c(C); \n#else\n#  undef MTL_DEBUG_DMAT_DMAT_MULT // doesn't work with NDEBUG\n#endif\n\n\tif (Assign::init_to_zero) set_to_zero(C);\n\n\ta_value_type   a_value(A);\n\tb_value_type   b_value(B);\n\tc_value_type   c_value(C);\n    \t\t\n\ta_cur_type ac= begin<row>(A), aend= end<row>(A);\n\tfor (c_cur_type cc= begin<row>(C); ac != aend; ++ac, ++cc) {\n\t    \n\t    b_cur_type bc= begin<col>(B), bend= end<col>(B);\n\t    for (c_icur_type cic= begin<all>(cc); bc != bend; ++bc, ++cic) { \n\t\t\n\t\ttypename MatrixC::value_type c_tmp(c_value(*cic));\n#ifdef MTL_DEBUG_DMAT_DMAT_MULT\n\t\tstd::cout << \"Calculating C[\" << row_c(*cic) << \"][\" << col_c(*cic) << \"], initial value is \"\n\t\t\t  << c_tmp << \"\\n\";\n#endif\n\t\ta_icur_type aic= begin<all>(ac), aiend= end<all>(ac); \n\t\tfor (b_icur_type bic= begin<all>(bc); aic != aiend; ++aic, ++bic) {\n#ifdef MTL_DEBUG_DMAT_DMAT_MULT\n\t\t    std::cout << \"Updating with A[\" << row_a(*aic) << \"][\" << col_a(*aic) << \"] /* value is \"\n\t\t\t      << a_value(*aic) << \" */ * \";\n\t\t    std::cout << \"B[\" << row_b(*bic) << \"][\" << col_b(*bic) << \"] /* value is \"\n\t\t\t      << b_value(*bic) << \" */ * \";\n#endif\n\t\t    assert(row_a(*aic) == row_c(*cic)); // Must do here because ac has no props\n\t\t    assert(col_b(*bic) == col_c(*cic));\n\t\t    assert(col_a(*aic) == row_b(*bic));\n\t\t    Assign::update(c_tmp, a_value(*aic) * b_value(*bic));\n#ifdef MTL_DEBUG_DMAT_DMAT_MULT\n\t\t    std::cout << \"C's current value is \" << c_tmp << \"\\n\";\n#endif\n\t\t}\n\t\tc_value(*cic, c_tmp);\n\t    }\n\t} \n    }\n};\n\n\ntemplate <typename Assign= assign::assign_sum,\n\t  typename Backup= no_op>     // To allow 2nd parameter, is ignored\nstruct gen_cursor_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tgen_cursor_dmat_dmat_mult_ft<MatrixA, MatrixB, MatrixC, Assign, Backup>()(A, B, C);\n    }\n};\n\n\n// =====================================\n// Generic matrix product with iterators\n// =====================================\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, \n\t  typename Assign= assign::assign_sum, \n\t  typename Backup= gen_cursor_dmat_dmat_mult_t<Assign> > \nstruct gen_dmat_dmat_mult_ft\n{\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tapply(A, B, C, traits::flatcat1<MatrixA, tag::has_iterator>(), traits::flatcat1<MatrixB, tag::has_iterator>());\n    }   \n\nprivate:\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::universe, tag::universe)\n    {\n\tBackup()(A, B, C);\n    }\n\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::flat<tag::has_iterator>, tag::flat<tag::has_iterator>)\n    {\n\t// asm(\"#iterator\");\n\tvampir_trace<4002> tracer;\n\t// std::cout << \"Canonical iterator\\n\";\n\tusing namespace tag;\n\tusing traits::range_generator;  \n        typedef typename range_generator<row, MatrixA>::type       a_cur_type;             \n        typedef typename range_generator<row, MatrixC>::type       c_cur_type;             \n\ttypedef typename range_generator<col, MatrixB>::type       b_cur_type;             \n        typedef typename range_generator<iter::all, c_cur_type>::type   c_icur_type;            \n        typedef typename range_generator<const_iter::all, a_cur_type>::type  a_icur_type;            \n        typedef typename range_generator<const_iter::all, b_cur_type>::type  b_icur_type;          \n\n\tif (Assign::init_to_zero) set_to_zero(C);\n\n\ta_cur_type ac= mtl::begin<row>(A), aend= mtl::end<row>(A);\n\tfor (c_cur_type cc= mtl::begin<row>(C); ac != aend; ++ac, ++cc) {\n\n\t    b_cur_type bc= mtl::begin<col>(B), bend= mtl::end<col>(B);\n\t    for (c_icur_type cic= mtl::begin<iter::all>(cc); bc != bend; ++bc, ++cic) { \n\t\t    \n\t\ttypename MatrixC::value_type c_tmp(*cic);\n\t\ta_icur_type aic= mtl::begin<const_iter::all>(ac), aiend= mtl::end<const_iter::all>(ac); \n\t\tfor (b_icur_type bic= mtl::begin<const_iter::all>(bc); aic != aiend; ++aic, ++bic) {\n\t\t    Assign::update(c_tmp, *aic * *bic);\n\t\t}\n\t\t*cic= c_tmp;\n\t    }\n\t}\n    }    \n};\n\n\ntemplate <typename Assign= assign::assign_sum,\n\t  typename Backup= gen_cursor_dmat_dmat_mult_t<Assign> >   \nstruct gen_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tgen_dmat_dmat_mult_ft<MatrixA, MatrixB, MatrixC, Assign, Backup>()(A, B, C);\n    }\n};\n\n\n/*\n\nUnrolling matrix product with dimensions that are not multiples of blocks\n\n1. Do with optimization:\n   C_nw += A_nw * B_nw\n   - wherby the matrix dimensions of sub-matrices are the largest multiples of block sizes \n     smaller or equal to the matrix dimensions of the original matrix\n\n\n2. Do without optimization\n   C_nw += A_ne * B_sw\n   C_ne += A_n * B_e\n   C_s += A_s * B\n\nThe inner loop can be unrolled arbitrarily. So, we can simplify\n\n1. Do with optimization:\n   C_nw += A_n * B_w\n   - wherby the matrix dimensions of sub-matrices are the largest multiples of block sizes \n     smaller or equal to the matrix dimensions of the original matrix\n\n\n2. Do with optimization only in inner loop\n   C_ne += A_n * B_e\n   C_s += A_s * B\n  \n\n*/\n\n// =======================\n// Unrolled with iterators\n// required has_2D_layout\n// =======================\n\n// Define defaults if not yet given as Compiler flag\n#ifndef MTL_DMAT_DMAT_MULT_TILING1\n#  define MTL_DMAT_DMAT_MULT_TILING1 2\n#endif\n\n#ifndef MTL_DMAT_DMAT_MULT_TILING2\n#  define MTL_DMAT_DMAT_MULT_TILING2 4\n#endif\n\n#ifndef MTL_DMAT_DMAT_MULT_INNER_UNROLL\n#  define MTL_DMAT_DMAT_MULT_INNER_UNROLL 8\n#endif\n\n\ntemplate <unsigned long Index0, unsigned long Max0, unsigned long Index1, unsigned long Max1, typename Assign>\nstruct gen_tiling_dmat_dmat_mult_block\n  : public meta_math::loop2<Index0, Max0, Index1, Max1>\n{\n    typedef meta_math::loop2<Index0, Max0, Index1, Max1>                              base;\n    typedef gen_tiling_dmat_dmat_mult_block<base::next_index0, Max0, base::next_index1, Max1, Assign>  next_t;\n\n    template <typename Value, typename ValueA, typename SizeA, typename ValueB, typename SizeB>\n    static inline void apply(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, \n\t\t\t     Value& tmp05, Value& tmp06, Value& tmp07, Value& tmp08, Value& tmp09, \n\t\t\t     Value& tmp10, Value& tmp11, Value& tmp12, Value& tmp13, Value& tmp14, Value& tmp15, \n\t\t\t     ValueA *begin_a, SizeA& ari, ValueB *begin_b, SizeB& bci)\n    {\n\ttmp00+= begin_a[ base::index0 * ari ] * begin_b[ base::index1 * bci ];\n\tnext_t::apply(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp08, tmp09, \n\t\t      tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp00, \n\t\t      begin_a, ari, begin_b, bci); \n    }\n\n    template <typename Value, typename MatrixC, typename SizeC>\n    static inline void update(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, \n\t\t\t      Value& tmp05, Value& tmp06, Value& tmp07, Value& tmp08, Value& tmp09, \n\t\t\t      Value& tmp10, Value& tmp11, Value& tmp12, Value& tmp13, Value& tmp14, Value& tmp15,\n\t\t\t      MatrixC& C, SizeC i, SizeC k)\n    {\n\tAssign::update(C(i + base::index0, k + base::index1), tmp00);\n\tnext_t::update(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp08, tmp09, \n\t\t       tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp00, \n\t\t       C, i, k);\n    }\n};\n\ntemplate <unsigned long Max0, unsigned long Max1, typename Assign>\nstruct gen_tiling_dmat_dmat_mult_block<Max0, Max0, Max1, Max1, Assign>\n    : public meta_math::loop2<Max0, Max0, Max1, Max1>\n{\n    typedef meta_math::loop2<Max0, Max0, Max1, Max1>  base;\n\n    template <typename Value, typename ValueA, typename SizeA, typename ValueB, typename SizeB>\n    static inline void apply(Value& tmp00, Value&, Value&, Value&, Value&, \n\t\t\t     Value&, Value&, Value&, Value&, Value&, \n\t\t\t     Value&, Value&, Value&, Value&, Value&, Value&, \n\t\t\t     ValueA *begin_a, SizeA& ari, ValueB *begin_b, SizeB& bci)\n    {\n\ttmp00+= begin_a[ base::index0 * ari ] * begin_b[ base::index1 * bci ];\n    }\n\n    template <typename Value, typename MatrixC, typename SizeC>\n    static inline void update(Value& tmp00, Value&, Value&, Value&, Value&, \n\t\t\t      Value&, Value&, Value&, Value&, Value&, \n\t\t\t      Value&, Value&, Value&, Value&, Value&, Value&,\n\t\t\t      MatrixC& C, SizeC i, SizeC k)\n    {\n\tAssign::update(C(i + base::index0, k + base::index1), tmp00);\n    }\n};\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC,\n\t  unsigned long Tiling1= MTL_DMAT_DMAT_MULT_TILING1,\n\t  unsigned long Tiling2= MTL_DMAT_DMAT_MULT_TILING2,\n\t  typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_tiling_dmat_dmat_mult_ft\n{\n    MTL_STATIC_ASSERT((Tiling1 * Tiling2 <= 16), \"Tile (Tiling1 * Tiling2) cannot be larger than 16.\");\n  \n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tapply(A, B, C, traits::layout_flatcat<MatrixA>(), traits::layout_flatcat<MatrixB>());\n    }   \n \nprivate:\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::universe, tag::universe)\n    {\n\tBackup()(A, B, C);\n    }\n\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::flat<tag::has_2D_layout>, tag::flat<tag::has_2D_layout>)\n    {\n\t// asm(\"#tiling\");\n\tvampir_trace<4003> tracer;\n\t// Indices run out of range for smaller matrices\n\tif (num_rows(A) < 2 || num_cols(A) < 2 || num_cols(B) < 2) {\n\t    Backup()(A, B, C);\n\t    return;\n\t}\n\n\t// std::cout << \"meta-unrolling\\n\";\n\tif (Assign::init_to_zero) set_to_zero(C);\n\n\ttypedef gen_tiling_dmat_dmat_mult_block<1, Tiling1, 1, Tiling2, Assign>  block;\n\ttypedef typename MatrixC::size_type                                          size_type;\n\ttypedef typename MatrixC::value_type                                         value_type;\n\tconst value_type z= math::zero(C[0][0]);    // if this are matrices we need their size\n\n\tsize_type i_max= num_rows(C), i_block= Tiling1 * (i_max / Tiling1),\n\t          k_max= num_cols(C), k_block= Tiling2 * (k_max / Tiling2);\n\tsize_t ari= &A(1, 0) - &A(0, 0), // how much is the offset of A's entry increased by incrementing row\n\t       aci= &A(0, 1) - &A(0, 0), bri= &B(1, 0) - &B(0, 0), bci= &B(0, 1) - &B(0, 0);\n\t    \n\t// C_nw += A_nw * B_nw\n\tfor (size_type i= 0; i < i_block; i+= Tiling1)\n\t    for (size_type k= 0; k < k_block; k+= Tiling2) {\n\n\t\tvalue_type tmp00= z, tmp01= z, tmp02= z, tmp03= z, tmp04= z,\n                           tmp05= z, tmp06= z, tmp07= z, tmp08= z, tmp09= z,\n \t\t           tmp10= z, tmp11= z, tmp12= z, tmp13= z, tmp14= z, tmp15= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri)\n\t\t    block::apply(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp08, tmp09, \n\t\t\t\t tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, \n\t\t\t\t begin_a, ari, begin_b, bci); \n\t\tblock::update(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp08, tmp09, \n\t\t\t      tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, \n\t\t\t      C, i, k);\n\t    }\n\n\t// C_ne += A_n * B_e\n\tfor (size_type i= 0; i < i_block; i++)\n\t    for (size_type k = k_block; k < k_max; k++) {\n\t\tvalue_type tmp00= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri)\n\t\t    tmp00 += *begin_a * *begin_b;\n\t\tAssign::update(C(i, k), tmp00);\n\t    }\n\n\t// C_s += A_s * B\n\tfor (size_type i= i_block; i < i_max; i++)\n\t    for (size_type k = 0; k < k_max; k++) {\n\t\tvalue_type tmp00= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri)\n\t\t    tmp00 += *begin_a * *begin_b;\n\t\tAssign::update(C(i, k), tmp00);\n\t    }\n    }\n};\n\ntemplate <unsigned long Tiling1= MTL_DMAT_DMAT_MULT_TILING1,\n\t  unsigned long Tiling2= MTL_DMAT_DMAT_MULT_TILING2,\n\t  typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_tiling_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tgen_tiling_dmat_dmat_mult_ft<\n\t     MatrixA, MatrixB, MatrixC, Tiling1, Tiling2, Assign, Backup\n\t>()(A, B, C);\n    }\n};\n\n\n\n// =================================\n// Unrolled with iterators fixed 4x4\n// required has_2D_layout\n// =================================\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, \n\t  typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_tiling_44_dmat_dmat_mult_ft\n{\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tapply(A, B, C, traits::layout_flatcat<MatrixA>(), traits::layout_flatcat<MatrixB>());\n    }   \n \nprivate:\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::universe, tag::universe)\n    {\n\tBackup()(A, B, C);\n    }\n\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::flat<tag::has_2D_layout>, tag::flat<tag::has_2D_layout>)\n    {\n\t// asm(\"#tiling44\");\n\tvampir_trace<4004> tracer;\n\t// Indices run out of range for smaller matrices\n\tif (num_rows(A) < 2 || num_cols(A) < 2 || num_cols(B) < 2) {\n\t    Backup()(A, B, C);\n\t    return;\n\t}\n\n        // std::cout << \"4x4 unrolling\\n\";\n\tif (Assign::init_to_zero) set_to_zero(C);\n\n\ttypedef typename MatrixC::size_type                                          size_type;\n\ttypedef typename MatrixC::value_type                                         value_type;\n\n\tconst size_type  Tiling1= 4, Tiling2= 4;\n\tconst value_type z= math::zero(C[0][0]);    // if this are matrices we need their size\n\n\tsize_type i_max= num_rows(C), i_block= Tiling1 * (i_max / Tiling1),\n\t          k_max= num_cols(C), k_block= Tiling2 * (k_max / Tiling2);\n\tsize_t ari= &A(1, 0) - &A(0, 0), // how much is the offset of A's entry increased by incrementing row\n\t       aci= &A(0, 1) - &A(0, 0), bri= &B(1, 0) - &B(0, 0), bci= &B(0, 1) - &B(0, 0);\n\n\t// C_nw += A_nw * B_nw\n\tfor (size_type i= 0; i < i_block; i+= Tiling1)\n\t    for (size_type k= 0; k < k_block; k+= Tiling2) {\n\n\t\tvalue_type tmp00= z, tmp01= z, tmp02= z, tmp03= z, tmp04= z,\n                           tmp05= z, tmp06= z, tmp07= z, tmp08= z, tmp09= z,\n \t\t           tmp10= z, tmp11= z, tmp12= z, tmp13= z, tmp14= z, tmp15= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri) {\n\t\t    tmp00+= begin_a[ 0 * ari ] * begin_b[ 0 * bci ];\n\t\t    tmp01+= begin_a[ 0 * ari ] * begin_b[ 1 * bci ];\n\t\t    tmp02+= begin_a[ 0 * ari ] * begin_b[ 2 * bci ];\n\t\t    tmp03+= begin_a[ 0 * ari ] * begin_b[ 3 * bci ];\n\t\t    tmp04+= begin_a[ 1 * ari ] * begin_b[ 0 * bci ];\n\t\t    tmp05+= begin_a[ 1 * ari ] * begin_b[ 1 * bci ];\n\t\t    tmp06+= begin_a[ 1 * ari ] * begin_b[ 2 * bci ];\n\t\t    tmp07+= begin_a[ 1 * ari ] * begin_b[ 3 * bci ];\n\t\t    tmp08+= begin_a[ 2 * ari ] * begin_b[ 0 * bci ];\n\t\t    tmp09+= begin_a[ 2 * ari ] * begin_b[ 1 * bci ];\n\t\t    tmp10+= begin_a[ 2 * ari ] * begin_b[ 2 * bci ];\n\t\t    tmp11+= begin_a[ 2 * ari ] * begin_b[ 3 * bci ];\n\t\t    tmp12+= begin_a[ 3 * ari ] * begin_b[ 0 * bci ];\n\t\t    tmp13+= begin_a[ 3 * ari ] * begin_b[ 1 * bci ];\n\t\t    tmp14+= begin_a[ 3 * ari ] * begin_b[ 2 * bci ];\n\t\t    tmp15+= begin_a[ 3 * ari ] * begin_b[ 3 * bci ];\n\t\t}\n\t\tAssign::update(C(i + 0, k + 0), tmp00);\n\t\tAssign::update(C(i + 0, k + 1), tmp01);\n\t\tAssign::update(C(i + 0, k + 2), tmp02);\n\t\tAssign::update(C(i + 0, k + 3), tmp03);\n\t\tAssign::update(C(i + 1, k + 0), tmp04);\n\t\tAssign::update(C(i + 1, k + 1), tmp05);\n\t\tAssign::update(C(i + 1, k + 2), tmp06);\n\t\tAssign::update(C(i + 1, k + 3), tmp07);\n\t\tAssign::update(C(i + 2, k + 0), tmp08);\n\t\tAssign::update(C(i + 2, k + 1), tmp09);\n\t\tAssign::update(C(i + 2, k + 2), tmp10);\n\t\tAssign::update(C(i + 2, k + 3), tmp11);\n\t\tAssign::update(C(i + 3, k + 0), tmp12);\n\t\tAssign::update(C(i + 3, k + 1), tmp13);\n\t\tAssign::update(C(i + 3, k + 2), tmp14);\n\t\tAssign::update(C(i + 3, k + 3), tmp15);\n\t    }\n\n\t// C_ne += A_n * B_e\n\tfor (size_type i= 0; i < i_block; i++)\n\t    for (size_type k = k_block; k < k_max; k++) {\n\t\tvalue_type tmp00= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri)\n\t\t    tmp00 += *begin_a * *begin_b;\n\t\tAssign::update(C(i, k), tmp00);\n\t    }\n\n\t// C_s += A_s * B\n\tfor (size_type i= i_block; i < i_max; i++)\n\t    for (size_type k = 0; k < k_max; k++) {\n\t\tvalue_type tmp00= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri)\n\t\t    tmp00 += *begin_a * *begin_b;\n\t\tAssign::update(C(i, k), tmp00);\n\t    }\n    }\n};\n\ntemplate <typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_tiling_44_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tgen_tiling_44_dmat_dmat_mult_ft<\n\t     MatrixA, MatrixB, MatrixC, Assign, Backup\n\t>()(A, B, C);\n    }\n};\n\n\n\n\n// =================================\n// Unrolled with iterators fixed 2x2\n// required has_2D_layout\n// =================================\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, \n\t  typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_tiling_22_dmat_dmat_mult_ft\n{\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tapply(A, B, C,  traits::layout_flatcat<MatrixA>(), traits::layout_flatcat<MatrixB>());\n    }   \n \nprivate:\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::universe, tag::universe)\n    {\n\tBackup()(A, B, C);\n    }\n\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::flat<tag::has_2D_layout>, tag::flat<tag::has_2D_layout>)\n    {\n\t// asm(\"#tiling22\");\n\tvampir_trace<4005> tracer;\n\t// Indices run out of range for smaller matrices\n\tif (num_rows(A) < 2 || num_cols(A) < 2 || num_cols(B) < 2) {\n\t    Backup()(A, B, C);\n\t    return;\n\t}\n\n        // std::cout << \"2x2 unrolling\\n\";\n\tif (Assign::init_to_zero) set_to_zero(C);\n\n\ttypedef typename MatrixC::size_type                                          size_type;\n\ttypedef typename MatrixC::value_type                                         value_type;\n\n\tconst size_type  Tiling1= 2, Tiling2= 2;\n\tconst value_type z= math::zero(C[0][0]);    // if this are matrices we need their size\n\n\tsize_type i_max= num_rows(C), i_block= Tiling1 * (i_max / Tiling1),\n\t          k_max= num_cols(C), k_block= Tiling2 * (k_max / Tiling2);\n\tsize_t ari= &A(1, 0) - &A(0, 0), // how much is the offset of A's entry increased by incrementing row\n\t       aci= &A(0, 1) - &A(0, 0), bri= &B(1, 0) - &B(0, 0), bci= &B(0, 1) - &B(0, 0);\n\n\t// C_nw += A_nw * B_nw\n\tfor (size_type i= 0; i < i_block; i+= Tiling1)\n\t    for (size_type k= 0; k < k_block; k+= Tiling2) {\n\n\t\tvalue_type tmp00= z, tmp01= z, tmp02= z, tmp03= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri) {\n\t\t    tmp00+= begin_a[ 0 ] * begin_b[ 0 ];\n\t\t    tmp01+= begin_a[ 0 ] * begin_b[bci];\n\t\t    tmp02+= begin_a[ari] * begin_b[ 0 ];\n\t\t    tmp03+= begin_a[ari] * begin_b[bci];\n\t\t}\n\t\tAssign::update(C(i + 0, k + 0), tmp00);\n\t\tAssign::update(C(i + 0, k + 1), tmp01);\n\t\tAssign::update(C(i + 1, k + 0), tmp02);\n\t\tAssign::update(C(i + 1, k + 1), tmp03);\n\t    }\n\n\t// C_ne += A_n * B_e\n\tfor (size_type i= 0; i < i_block; i++)\n\t    for (size_type k = k_block; k < k_max; k++) {\n\t\tvalue_type tmp00= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri)\n\t\t    tmp00 += *begin_a * *begin_b;\n\t\tAssign::update(C(i, k), tmp00);\n\t    }\n\n\t// C_s += A_s * B\n\tfor (size_type i= i_block; i < i_max; i++)\n\t    for (size_type k = 0; k < k_max; k++) {\n\t\tvalue_type tmp00= z;\n\t\tconst typename MatrixA::value_type *begin_a= &A(i, 0), *end_a= begin_a + num_cols(A) * aci;\n\t\tconst typename MatrixB::value_type *begin_b= &B(0, k);\n\n\t\tfor (; begin_a != end_a; begin_a+= aci, begin_b+= bri)\n\t\t    tmp00 += *begin_a * *begin_b;\n\t\tAssign::update(C(i, k), tmp00);\n\t    }\n    }\n};\n\ntemplate <typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_tiling_22_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tgen_tiling_22_dmat_dmat_mult_ft<\n\t     MatrixA, MatrixB, MatrixC, Assign, Backup\n\t>()(A, B, C);\n    }\n};\n\n\n\n\n// ========================\n// Recursive Multiplication\n// ========================\n\nnamespace wrec {\n\n    template <typename BaseMult, typename BaseTest= recursion::bound_test_static<64> >\n    struct gen_dmat_dmat_mult_t\n    {\n\ttemplate <typename RecA, typename RecB, typename RecC>\n\tvoid operator()(RecA const& rec_a, RecB const& rec_b, RecC& rec_c)\n\t{\n\t    vampir_trace<4006> tracer;\n\t    // std::cout << \"wrec::mult \\n\";\n\t    using namespace recursion;\n\t    // using mtl::mat::is_empty; // ambiguity with std::tr1::is_empty in VS2010\n\t    // Ambiguity with boost::is_empty in Open64\n\t    if (mtl::mat::is_empty(rec_a) || mtl::mat::is_empty(rec_b) || mtl::mat::is_empty(rec_c))\n\t\treturn;\n\n\t    if (BaseTest()(rec_a)) {\n\t\t//std::cout << \"base_case: A =\\n\" << *rec_a << \"B =\\n\" << *rec_b;\n#               if 0 // ndef NDEBUG\n\t\t    typename RecC::sub_matrix_type C_tmp(*rec_c);\n\t\t    typename base_case_matrix<typename RecC::sub_matrix_type, BaseTest>::type\n\t\t\tC = base_case_cast<BaseTest>(C_tmp);\n#               else\n    \t\t    typename base_case_matrix<typename RecC::matrix_type, BaseTest>::type\n\t\t\tC= base_case_cast<BaseTest>(*rec_c);\n#               endif\n\t\tBaseMult()(base_case_cast<BaseTest>(*rec_a),\n\t\t\t   base_case_cast<BaseTest>(*rec_b), C);\n\t\t//std::cout << \"base_case: C =\\n\" << C << \"*rec_c = \\n\" << *rec_c;\n#               if 0 //ndef NDEBUG\n\t\t    // MTL_ASSERT((C(0, 0) == (*rec_c)(0, 0)), \"Result was computed in a copy not in a view/reference!\"); // does not compile in set_to_zero_with_user_value_test\n#               endif\n\t    } else {\n\t\tRecC c_north_west= north_west(rec_c), c_north_east= north_east(rec_c),\n\t\t     c_south_west= south_west(rec_c), c_south_east= south_east(rec_c);\n\n\t\t(*this)(north_west(rec_a), north_west(rec_b), c_north_west);\n\t\t(*this)(north_west(rec_a), north_east(rec_b), c_north_east);\n\t\t(*this)(south_west(rec_a), north_east(rec_b), c_south_east);\n\t\t(*this)(south_west(rec_a), north_west(rec_b), c_south_west);\n\t\t(*this)(south_east(rec_a), south_west(rec_b), c_south_west);\n\t\t(*this)(south_east(rec_a), south_east(rec_b), c_south_east);\n\t\t(*this)(north_east(rec_a), south_east(rec_b), c_north_east);\n\t\t(*this)(north_east(rec_a), south_west(rec_b), c_north_west);\n\t    }\n\t}\n    };\n\n} // namespace wrec\n\n\ntemplate <typename BaseMult, \n\t  typename BaseTest= recursion::bound_test_static<64>,\n\t  typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_recursive_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tapply(A, B, C, traits::flatcat1<MatrixA, tag::qsub_divisible>(), \n\t      traits::flatcat1<MatrixB, tag::qsub_divisible>(), traits::flatcat1<MatrixC, tag::qsub_divisible>());\n    }   \n \nprivate:\n    // If one matrix is not sub-divisible then take backup function\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, tag::universe, tag::universe, tag::universe)\n    {\n\tBackup()(A, B, C);\n    }\n\n    // Only if matrix is sub-divisible, otherwise backup\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, \n\t       tag::flat<tag::qsub_divisible>, tag::flat<tag::qsub_divisible>, tag::flat<tag::qsub_divisible>)\n    {\n\tvampir_trace<4007> tracer;\n\t// std::cout << \"do recursion\\n\";\n\tif (Assign::init_to_zero) set_to_zero(C);\n\n\t// Make sure that mult functor of basecase has appropriate assign mode (in all nestings)\n\t// i.e. replace assign::assign_sum by assign::plus_sum including backup functor\n\t\n\tusing mat::recursator;\n\trecursator<MatrixA>    rec_a(A);\n\trecursator<MatrixB>    rec_b(B);\n\trecursator<MatrixC>    rec_c(C);\n\tequalize_depth(rec_a, rec_b, rec_c);\n\t\n\twrec::gen_dmat_dmat_mult_t<BaseMult, BaseTest>() (rec_a, rec_b, rec_c);\n    }\n};\n\n\n\n// ==================================\n// Plattform specific implementations\n// ==================================\n\n// Here only general definition that calls backup function\n// Special implementations needed in other files, which are included at the end\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_platform_dmat_dmat_mult_ft\n    : public Backup\n{};\n\n\ntemplate <typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_platform_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tgen_platform_dmat_dmat_mult_ft<MatrixA, MatrixB, MatrixC, Assign, Backup>()(A, B, C);\n    }\n};\n\n\n// ==================================\n// BLAS functions as far as supported\n// ==================================\n\n\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_blas_dmat_dmat_mult_ft\n    : public Backup\n{};\n\n\n#ifdef MTL_HAS_BLAS\n\nnamespace detail {\n\n    // Transform from assign representation to BLAS\n    double inline dgemm_alpha(assign::assign_sum) { return 1.0; }\n    double inline dgemm_alpha(assign::plus_sum) { return 1.0; } \n    double inline dgemm_alpha(assign::minus_sum) { return -1.0; }\n\n    // Transform from assign representation to BLAS\n    double inline dgemm_beta(assign::assign_sum) { return 0.0; }\n    double inline dgemm_beta(assign::plus_sum) { return 1.0; }\n    double inline dgemm_beta(assign::minus_sum) { return 1.0; }\n\n    template <typename Value, typename ParaA, typename ParaB, typename ParaC, typename Function, typename Assign>\n    void inline xgemm(const dense2D<Value, ParaA>& A, const dense2D<Value, ParaB>& B, \n\t\t      dense2D<Value, ParaC>& C, Function f, Assign)\n    {\n\tvampir_trace<4008> tracer;\n\t// std::cout << \"use generic BLAS\\n\";\n\tint m= num_rows(A), n= num_cols(B), k= num_cols(A), lda= A.get_ldim(), ldb= B.get_ldim(), ldc= C.get_ldim();\n\tValue alpha= dgemm_alpha(Assign()), beta= dgemm_beta(Assign());\n\tchar a_trans= traits::is_row_major<ParaA>::value ? 'T' : 'N', \n             b_trans= traits::is_row_major<ParaB>::value ? 'T' : 'N';\n\n\tif (traits::is_row_major<ParaC>::value) {\n\t    // C^T= B^T * A^T\n\t    a_trans= 'T' + 'N' - a_trans; b_trans= 'T' + 'N' - b_trans; \n\t    f(&b_trans, &a_trans, &n /* col(B) */, &m /* row(A) */, &k /* col(A)=row(B) */, \n\t\t\t\t &alpha, &B[0][0], &ldb, &A[0][0], &lda, &beta, &C[0][0], &ldc);\n\t} else \n\t    f(&a_trans, &b_trans, &m, &n, &k, &alpha, &A[0][0], &lda, &B[0][0], &ldb, &beta, &C[0][0], &ldc);\n    }\n\n} // detail\n \ntemplate<typename ParaA, typename ParaB, typename ParaC, typename Assign, typename Backup>\nstruct gen_blas_dmat_dmat_mult_ft<dense2D<float, ParaA>, dense2D<float, ParaB>, \n\t\t\t\t  dense2D<float, ParaC>, Assign, Backup>\n{\n    void operator()(const dense2D<float, ParaA>& A, const dense2D<float, ParaB>& B, \n\t\t    dense2D<float, ParaC>& C)\n    {\n\tdetail::xgemm(A, B, C, MTL_BLAS_NAME(sgemm), Assign());\n    }\n};\n\ntemplate<typename ParaA, typename ParaB, typename ParaC, typename Assign, typename Backup>\nstruct gen_blas_dmat_dmat_mult_ft<dense2D<double, ParaA>, dense2D<double, ParaB>, \n\t\t\t\t     dense2D<double, ParaC>, Assign, Backup>\n{\n    void operator()(const dense2D<double, ParaA>& A, const dense2D<double, ParaB>& B, \n\t\t    dense2D<double, ParaC>& C)\n    {\n\tdetail::xgemm(A, B, C, MTL_BLAS_NAME(dgemm), Assign());\n    }\n};\n\n\ntemplate<typename ParaA, typename ParaB, typename ParaC, typename Assign, typename Backup>\nstruct gen_blas_dmat_dmat_mult_ft<dense2D<std::complex<float>, ParaA>, dense2D<std::complex<float>, ParaB>, \n\t\t\t\t  dense2D<std::complex<float>, ParaC>, Assign, Backup>\n{\n    void operator()(const dense2D<std::complex<float>, ParaA>& A, const dense2D<std::complex<float>, ParaB>& B, \n\t\t    dense2D<std::complex<float>, ParaC>& C)\n    {\n\tdetail::xgemm(A, B, C, MTL_BLAS_NAME(cgemm), Assign());\n    }\n};\n\n\ntemplate<typename ParaA, typename ParaB, typename ParaC, typename Assign, typename Backup>\nstruct gen_blas_dmat_dmat_mult_ft<dense2D<std::complex<double>, ParaA>, dense2D<std::complex<double>, ParaB>, \n\t\t\t\t  dense2D<std::complex<double>, ParaC>, Assign, Backup>\n{\n    void operator()(const dense2D<std::complex<double>, ParaA>& A, const dense2D<std::complex<double>, ParaB>& B, \n\t\t    dense2D<std::complex<double>, ParaC>& C)\n    {\n\tdetail::xgemm(A, B, C, MTL_BLAS_NAME(zgemm), Assign());\n    }\n};\n\n\n\n#endif // MTL_HAS_BLAS\n\ntemplate <typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct gen_blas_dmat_dmat_mult_t\n  : public Backup\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tgen_blas_dmat_dmat_mult_ft<MatrixA, MatrixB, MatrixC, Assign, Backup>()(A, B, C);\n    }\n};\n\n\n// ============================================================\n// Switch between two functors depending on minimal matrix size\n// ============================================================\n\ntemplate <std::size_t SizeLimit, typename FunctorSmall, typename FunctorLarge>\nstruct size_switch_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tconst bool all_static= traits::is_static<MatrixA>::value && traits::is_static<MatrixB>::value \n\t                       && traits::is_static<MatrixC>::value;\n\tapply(A, B, C, boost::mpl::bool_<all_static>());\n    }\n    \n  private:\n    // Decided at run time\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, boost::mpl::false_)\n    {\n\tif (mtl::mat::size(A) <= SizeLimit || mtl::mat::size(B) <= SizeLimit || mtl::mat::size(C) <= SizeLimit)\n\t    FunctorSmall()(A, B, C);\n\telse\n\t    FunctorLarge()(A, B, C);\n    }\n\n    // Decided at compile time\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void apply(MatrixA const& A, MatrixB const& B, MatrixC& C, boost::mpl::true_)\n    {\n\tconst bool is_small= mtl::static_size<MatrixA>::value <= SizeLimit || mtl::static_size<MatrixB>::value <= SizeLimit \n\t    || mtl::static_size<MatrixC>::value <= SizeLimit;\n\ttypename boost::mpl::if_c<is_small, FunctorSmall, FunctorLarge>::type()(A, B, C);\n    }\n};\n\n\n// ====================================================================================\n// Switch between two functors depending on whether matrix size is know at compile time\n// ====================================================================================\n\ntemplate <bool IsStatic, typename FunctorStatic, typename FunctorDynamic>\nstruct static_switch_dmat_dmat_mult_t\n{\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    void operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\ttypename boost::mpl::if_c<IsStatic, FunctorStatic, FunctorDynamic>::type()(A, B, C);\n    }\n};\n\n// ==============================================================\n// Completely unroll fixed size computations, will be tuned later\n// ==============================================================\n\ntemplate <std::size_t Index0, std::size_t Max0, std::size_t Index1, std::size_t Max1, typename Assign>\nstruct fully_unroll_dmat_dmat_mult_init_block\n  : public meta_math::loop2<Index0, Max0, Index1, Max1>\n{\n    typedef meta_math::loop2<Index0, Max0, Index1, Max1>                              base;\n    typedef fully_unroll_dmat_dmat_mult_init_block<base::next_index0, Max0, base::next_index1, Max1, Assign>  next_t;\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    static inline void apply(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\t// Assign::first_update(C[base::index0][base::index1], A[base::index0][0] * B[0][base::index1]);\n\tAssign::first_update(C(base::index0, base::index1), A(base::index0, 0) * B(0, base::index1));\n\tnext_t::apply(A, B, C);\n    }\n};\n\ntemplate <std::size_t Max0, std::size_t Max1, typename Assign>\nstruct fully_unroll_dmat_dmat_mult_init_block<Max0, Max0, Max1, Max1, Assign>\n  : public meta_math::loop2<Max0, Max0, Max1, Max1>\n{\n    typedef meta_math::loop2<Max0, Max0, Max1, Max1>                              base;\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    static inline void apply(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tAssign::first_update(C(base::index0, base::index1), A(base::index0, 0) * B(0, base::index1));\n    }\n};\n\n\ntemplate <std::size_t Index0, std::size_t Max0, std::size_t Index1, std::size_t Max1, \n\t  std::size_t Index2, std::size_t Max2, typename Assign>\nstruct fully_unroll_dmat_dmat_mult_block\n  : public meta_math::loop3<Index0, Max0, Index1, Max1, Index2, Max2>\n{\n    typedef meta_math::loop3<Index0, Max0, Index1, Max1, Index2, Max2>                              base;\n    typedef fully_unroll_dmat_dmat_mult_block<base::next_index0, Max0, base::next_index1, Max1, base::next_index2, Max2, Assign>  next_t;\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    static inline void apply(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tAssign::update(C(base::index1, base::index2), A(base::index1, base::index0) * B(base::index0, base::index2));\n\tnext_t::apply(A, B, C);\n    }   \n};\n\ntemplate <std::size_t Max0, std::size_t Max1, std::size_t Max2, typename Assign>\nstruct fully_unroll_dmat_dmat_mult_block<Max0, Max0, Max1, Max1, Max2, Max2, Assign>\n  : public meta_math::loop3<Max0, Max0, Max1, Max1, Max2, Max2>\n{\n    typedef meta_math::loop3<Max0, Max0, Max1, Max1, Max2, Max2>                              base;\n\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    static inline void apply(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\n\tAssign::update(C(base::index1, base::index2), A(base::index1, base::index0) * B(base::index0, base::index2));\n    }   \n};\n\ntemplate <typename Assign= assign::assign_sum, \n\t  typename Backup= gen_dmat_dmat_mult_t<Assign> >\nstruct fully_unroll_fixed_size_dmat_dmat_mult_t\n{\n    // if C is empty just do nothing\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    typename boost::enable_if_c<static_size<MatrixC>::value == 0>::type\n    operator()(MatrixA const&, MatrixB const&, MatrixC&) {}\n\n    // just initialize\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    typename boost::enable_if_c<static_num_cols<MatrixA>::value == 0 && static_size<MatrixC>::value != 0>::type\n    operator()(MatrixA const&, MatrixB const&, MatrixC& C) { if (Assign::init_to_zero) set_to_zero(C); }\n\n    struct noop\n    {\n\ttemplate <typename MatrixA, typename MatrixB, typename MatrixC>\n\tstatic inline void apply(MatrixA const&, MatrixB const&, MatrixC&) {}\n    };\n\n    // really compute\n    template <typename MatrixA, typename MatrixB, typename MatrixC>\n    typename boost::enable_if_c<static_size<MatrixA>::value != 0 && static_size<MatrixC>::value != 0>::type\n    operator()(MatrixA const& A, MatrixB const& B, MatrixC& C)\n    {\t\n\tvampir_trace<1002> tracer;\n\ttypedef typename static_num_rows<MatrixC>::type size_type;\n\tstatic const size_type rows_c= static_num_rows<MatrixC>::value, cols_c= static_num_cols<MatrixC>::value, \n\t  \t               cols_a= static_num_cols<MatrixA>::value;\n\t// corresponds to C= A[all][0] * B[0][all];\n\tfully_unroll_dmat_dmat_mult_init_block<1, rows_c, 1, cols_c, Assign>::apply(A, B, C); \n\n\t// corresponds to C+= A[all][1:] * B[1:][all]; if necessary\n\ttypedef fully_unroll_dmat_dmat_mult_block<2, cols_a, 1, rows_c, 1, cols_c, Assign>  f2;\n\ttypedef typename boost::mpl::if_c<(cols_a > 1), f2, noop>::type                     f3;\n\tf3::apply(A, B, C);\n    }\n};    \n\n\n} // namespace mtl\n\n#endif // MTL_DMAT_DMAT_MULT_INCLUDE\n\n// Include plattform specific implementations\n#include <boost/numeric/mtl/operation/opteron/matrix_mult.hpp>\n\n", "meta": {"hexsha": "b43af8974f87065527fe0c50cf71406f9c020c85", "size": 41763, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/dmat_dmat_mult.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/operation/dmat_dmat_mult.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/operation/dmat_dmat_mult.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": 38.6694444444, "max_line_length": 163, "alphanum_fraction": 0.6396331681, "num_tokens": 12737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.04958901771684944, "lm_q1q2_score": 0.020199263191542156}}
{"text": "//=====================================================================//\r\n/*!\t@file\r\n\t@brief\tArithmetic クラス@n\r\n\t\t\t※数式処理をサポートする簡易演算解析クラス @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*/\r\n//=====================================================================//\r\n#include \"utils/arith.hpp\"\r\n#include <boost/foreach.hpp>\r\n\r\nnamespace utils {\r\n\r\n\tvoid arith::value::sum(char c)\r\n\t{\r\n\t\tif(c == '_') ;\t// 数字列にある '_'（アンダースコアー）は無視\r\n\t\telse if(hex_value_ == false && integer_ == 0 && point_ == false && (c =='x' || c == 'X' || c == '$')) {\r\n\t\t\thex_value_ = true;\r\n\t\t} else if(c == '.') {\r\n\t\t\tif(point_ == false) {\r\n\t\t\t\tpoint_ = true;\r\n\t\t\t} else {\t// 少数点が２つ以上ある場合\r\n\t\t\t\terror_.set(error::fatal);\r\n\t\t\t}\r\n\t\t} else if(c >= '0' && c <= '9') {\r\n\t\t\tc -= '0';\r\n\t\t\tif(point_ == false) {\r\n\t\t\t\tif(hex_value_) {\r\n\t\t\t\t\tinteger_ <<= 4;\r\n\t\t\t\t\tinteger_ |= c;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tinteger_ *= 10;\r\n\t\t\t\t\tinteger_ += c;\r\n\t\t\t\t\tfloat_ *= 10.0f;\r\n\t\t\t\t\tfloat_ += static_cast<float>(c);\r\n\t\t\t\t\tdouble_ *= 10.0;\r\n\t\t\t\t\tdouble_ += static_cast<double>(c);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tf_scale_ *= 0.1f;\r\n\t\t\t\tfloat_ += static_cast<float>(c) * f_scale_;\r\n\t\t\t\td_scale_ *= 0.1;\r\n\t\t\t\tdouble_ += static_cast<double>(c) * d_scale_;\r\n\t\t\t}\r\n\t\t} else if(hex_value_ == true && (c >= 'a' && c <= 'f')) {\r\n\t\t\tc -= 'a';\r\n\t\t\tc += 10;\r\n\t\t\tinteger_ <<= 4;\r\n\t\t\tinteger_ |= c;\r\n\t\t} else if(hex_value_ == true && (c >= 'A' && c <= 'F')) {\r\n\t\t\tc -= 'A';\r\n\t\t\tc += 10;\r\n\t\t\tinteger_ <<= 4;\r\n\t\t\tinteger_ |= c;\r\n\t\t} else {\r\n\t\t\terror_.set(error::number_fatal);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid arith::value::neg()\r\n\t{\r\n\t\tinteger_ = -integer_;\r\n\t\tfloat_   = -float_;\r\n\t\tdouble_  = -double_;\r\n\t}\r\n\r\n\r\n\tvoid arith::value::inv()\r\n\t{\r\n\t\tinteger_ = integer_ ^ -1;\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tシンボルに値を登録\r\n\t\t@param[in]\tname\tシンボル名\r\n\t\t@param[in]\tval\t\t整数値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid arith::set_symbol(const std::string& name, long val)\r\n\t{\r\n\t\tsymbol_map_it it = symbol_.find(name);\r\n\t\tif(it == symbol_.end()) {\r\n\t\t\tvalue v;\r\n\t\t\tsymbol_[name] = v;\r\n///\t\t\tsymbol_map_it it = symbol_.find(name);\r\n\t\t}\r\n\t\tvalue& vp = (*it).second;\r\n\t\tvp.integer_ = val;\r\n\t\tvp.float_ = static_cast<float>(val);\r\n\t\tvp.double_ = static_cast<double>(val);\r\n\t\tvp.point_ = false;\r\n\t\tvp.dbe_ = false;\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tシンボルに値を登録\r\n\t\t@param[in]\tname\tシンボル名\r\n\t\t@param[in]\tval\t\t浮動小数点\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid arith::set_symbol(const std::string& name, float val)\r\n\t{\r\n\t\tsymbol_map_it it = symbol_.find(name);\r\n\t\tif(it == symbol_.end()) {\r\n\t\t\tvalue v;\r\n\t\t\tsymbol_[name] = v;\r\n///\t\t\tsymbol_map_it it = symbol_.find(name);\r\n\t\t}\r\n\t\tvalue& vp = (*it).second;\r\n\t\tvp.integer_ = static_cast<long>(val);\r\n\t\tvp.float_ = val;\r\n\t\tvp.double_ = static_cast<double>(val);\r\n\t\tvp.point_ = true;\r\n\t\tvp.dbe_ = false;\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tシンボルに値を登録\r\n\t\t@param[in]\tname\tシンボル名\r\n\t\t@param[in]\tval\t\t倍精度浮動小数点\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid arith::set_symbol(const std::string& name, double val)\r\n\t{\r\n\t\tsymbol_map_it it = symbol_.find(name);\r\n\t\tif(it == symbol_.end()) {\r\n\t\t\tvalue v;\r\n\t\t\tsymbol_[name] = v;\r\n///\t\t\tsymbol_map_it it = symbol_.find(name);\r\n\t\t}\r\n\t\tvalue& vp = (*it).second;\r\n\t\tvp.integer_ = static_cast<long>(val);\r\n\t\tvp.float_ = static_cast<float>(val);\r\n\t\tvp.double_ = val;\r\n\t\tvp.point_ = true;\r\n\t\tvp.dbe_ = true;\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t数値入力\r\n\t\t@return 数値を返す\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\tarith::value arith::number_()\r\n\t{\r\n\t\tbool inv = false;\r\n\t\tbool neg = false;\r\n\r\n\t\t// 符号、反転の判定\r\n\t\tif(ch_ == '-') {\r\n\t\t\tinv = true;\r\n\t\t\tch_ = *tx_++;\r\n\t\t} else if(ch_ == '+') {\r\n\t\t\tch_ = *tx_++;\r\n\t\t} else if(ch_ == '!' || ch_ == '~') {\r\n\t\t\tneg = true;\r\n\t\t\tch_ = *tx_++;\r\n\t\t}\r\n\r\n\t\tvalue v;\r\n\t\tif(ch_ == '(') {\r\n\t\t\tv = factor_();\r\n\t\t} else {\r\n//\t\t\tlong val_bin = 0;\r\n//\t\t\tlong val_oct = 0;\r\n//\t\t\tlong val_hex = 0;\r\n\r\n//\t\t\tbool bin_ok = false;\r\n//\t\t\tbool oct_ok = false;\r\n//\t\t\tbool hex_ok = false;\r\n\r\n\t\t\tbool symbol = false;\r\n\t\t\tstd::string sym;\r\n\r\n\t\t\tif(ch_ >= 'A' && ch_ <= 'Z') symbol = true;\r\n\t\t\telse if(ch_ >= 'a' && ch_ <= 'z') symbol = true;\r\n\t\t\telse if(ch_ == '_' || ch_ == '?') symbol = true;\r\n\r\n\t\t\twhile(ch_ != 0) {\r\n\t\t\t\tif(ch_ == '+') break;\r\n\t\t\t\telse if(ch_ == '-') break;\r\n\t\t\t\telse if(ch_ == '*') break;\r\n\t\t\t\telse if(ch_ == '/') break;\r\n\t\t\t\telse if(ch_ == '&') break;\r\n\t\t\t\telse if(ch_ == '^') break;\r\n\t\t\t\telse if(ch_ == '|') break;\r\n\t\t\t\telse if(ch_ == '%') break;\r\n\t\t\t\telse if(ch_ == ')') break;\r\n\t\t\t\telse if(ch_ == '<') break;\r\n\t\t\t\telse if(ch_ == '>') break;\r\n\t\t\t\telse if(ch_ == '!') break;\r\n\t\t\t\telse if(ch_ == '~') break;\r\n\r\n\t\t\t\tif(symbol) {\r\n\t\t\t\t\tsym += ch_;\r\n\t\t\t\t} else {\r\n#if 0\r\n\t\t\t\t\tif(m_ch == 'b' || m_ch == 'B') {\r\n\t\t\t\t\t\tif(v.m_error[binary_fatal] == false) {\r\n\t\t\t\t\t\t\tbin_ok = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(m_ch == 'o' || m_ch == 'O') {\r\n\t\t\t\t\t\tif(v.m_error[octal_fatal] == false) {\r\n\t\t\t\t\t\t\toct_ok = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(m_ch == 'h' || m_ch == 'H') {\r\n\t\t\t\t\t\tif(v.m_error[hexdecimal_fatal] == false) {\r\n\t\t\t\t\t\t\thex_ok = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n#endif\r\n\t\t\t\t\tv.sum(ch_);\r\n\r\n\t\t\t\t\tif(v.error_[error::binary_fatal] == true || v.error_[error::octal_fatal] == true) ;\r\n\t\t\t\t\telse if(v.error_.any()) break;\r\n\t\t\t\t}\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t}\r\n\r\n\t\t\tif(symbol) {\r\n\t\t\t\tsymbol_map_cit cit = symbol_.find(sym);\r\n\t\t\t\tif(cit != symbol_.end()) {\r\n\t\t\t\t\tv = (*cit).second;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tv.error_.set(error::symbol_fatal);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n//\t\t\t\t\t\tv.m_error.reset(integer_fatal);\r\n//\t\t\t\t\t\tv.m_error.reset(float_fatal);\r\n//\t\t\t\t\t\tv.m_error.reset(double_fatal);\r\n\t\tif(inv) v.inv();\r\n\t\tif(neg) v.neg();\r\n\t\tv.error_.reset(error::binary_fatal);\r\n\t\tv.error_.reset(error::octal_fatal);\r\n\r\n\t\treturn v;\r\n\t}\r\n\r\n\r\n\tarith::value arith::factor_()\r\n\t{\r\n\t\tvalue v;\r\n\t\tif(ch_ != '(') {\r\n\t\t\tv = number_();\r\n\t\t} else {\r\n\t\t\tch_ = *tx_++;\r\n\t\t\tv = expression_();\r\n\t\t\tif(ch_ != ')') {\r\n\t\t\t\tv.error_.set(error::fatal);\r\n\t\t\t} else {\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn v;\r\n\t}\r\n\r\n\r\n\tarith::value arith::term_()\r\n\t{\r\n\t\tvalue v = factor_();\r\n\t\twhile(v.error_.any() != true) {\r\n\t\t\tbool fin = false;\r\n\t\t\tswitch(ch_) {\r\n\t\t\tcase '*':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tv *= factor_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase '/':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tif(ch_ == '/') {\r\n\t\t\t\t\tch_ = *tx_++;\r\n\t\t\t\t\tv %= factor_();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tv /= factor_();\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase '<':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tif(ch_ == '<') {\r\n\t\t\t\t\tch_ = *tx_++;\r\n\t\t\t\t\tv <<= factor_();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tv.error_.set(error::fatal);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase '>':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tif(ch_ == '>') {\r\n\t\t\t\t\tch_ = *tx_++;\r\n\t\t\t\t\tv <<= factor_();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tv.error_.set(error::fatal);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tfin = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(fin) break;\r\n\t\t}\r\n\t\treturn v;\r\n\t}\r\n\r\n\r\n\tarith::value arith::expression_()\r\n\t{\r\n\t\tvalue v = term_();\r\n\t\twhile(v.error_.any() != true) {\r\n\t\t\tbool fin = false;\r\n\t\t\tswitch(ch_) {\r\n\t\t\tcase '+':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tv += term_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase '-':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tv -= term_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase '&':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tv &= term_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase '^':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tv ^= term_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase '|':\r\n\t\t\t\tch_ = *tx_++;\r\n\t\t\t\tv |= term_();\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tfin = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(fin) break;\r\n\t\t}\r\n\t\treturn v;\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t解析を開始\r\n\t\t@param[in]\ttext\t解析テキスト\r\n\t\t@return\t文法にエラーがあった場合、「false」\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tbool arith::analize(const std::string& text)\r\n\t{\r\n\t\tstd::string s;\r\n\r\n\t\t// スペースと TAB を除外\r\n\t\tBOOST_FOREACH(char c, text) {\r\n\t\t\tif(c == ' ' || c == '\\t') ;\r\n\t\t\telse if(c < ' ') {\r\n\t\t\t\tvalue_.error_.set(error::fatal);\r\n\t\t\t\treturn false;\r\n\t\t\t} else {\r\n\t\t\t\ts += c;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\ttx_ = s.c_str();\r\n\t\tch_ = *tx_++;\r\n\t\tif(ch_ != 0) {\r\n\t\t\tvalue_ = expression_();\r\n\t\t} else {\r\n\t\t\tvalue_.error_.set(error::fatal);\r\n\t\t}\r\n\r\n\t\tif(value_.error_.any() == true) {\r\n\t\t\treturn false;\r\n\t\t} else if(ch_ != 0) {\r\n\t\t\tvalue_.error_.set(error::fatal);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r\n", "meta": {"hexsha": "44e1f5fdf6388dbd970797342605c2d02b3c82f0", "size": 8392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "glfw3_app/common/utils/arith.cpp", "max_stars_repo_name": "hirakuni45/glfw3_app", "max_stars_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-09-22T21:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T09:16:53.000Z", "max_issues_repo_path": "glfw3_app/common/utils/arith.cpp", "max_issues_repo_name": "hirakuni45/glfw3_app", "max_issues_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glfw3_app/common/utils/arith.cpp", "max_forks_repo_name": "hirakuni45/glfw3_app", "max_forks_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T04:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T17:24:32.000Z", "avg_line_length": 21.3536895674, "max_line_length": 106, "alphanum_fraction": 0.4323164919, "num_tokens": 2693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.053403324903538434, "lm_q1q2_score": 0.020161926252089485}}
{"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-2011 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#ifndef CHECK_DERIVATIVE_HH\n#define CHECK_DERIVATIVE_HH\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <fstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/mpl/size.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"algorithm/dune_bridge.hh\"\n#include \"utilities/linalg/scalarproducts.hh\"\n\nnamespace Kaskade{\n/// Some helper's for a correct indentation of XML-code\nnamespace XMLHelper{\n\n  static int const xml_increment=2;\n  static int xml_level;\n\n  std::string getXMLIndent()\n  {\n    std::string result;\n    for(int i=0; i<xml_level; ++i) result.append(\" \");\n    return result;\n  }\n\n  struct XMLBlock{\n    XMLBlock(std::ofstream &f, const char* s, const char* d=\"\") : file(f), str(s), data(d), offset(\"\")\n    {\n      xml_level += xml_increment;\n      getOffset();\n      writeBegin();\n    }\n    XMLBlock(std::ofstream &f, std::string &s, std::string d=\"\") : file(f), str(s), data(d), offset(\"\")\n    { \n      xml_level += xml_increment;\n      getOffset();\n      writeBegin();\n    }\n    ~XMLBlock()\n    {\n      file << offset.c_str() << \"</\" << str.c_str() << \">\" << std::endl;\n      xml_level -= xml_increment;\n    }\n\n  private:\n    void getOffset(){\n      for(int i=0; i<xml_level; ++i) offset.append(\" \");\n    }\n\n    void writeBegin(){\n      file << offset.c_str() << \"<\" << str.c_str() << data.c_str() << \">\" << std::endl;\n    }\n\n    std::ofstream& file;\n    std::string const str, data;\n    std::string offset;\n  };\n\n}\n\nnamespace DerivativeCheck\n{\n  namespace Private\n  {\n    template <class SparseInt>\n    void writeConnectivity(std::ofstream &file, SparseInt row, SparseInt col, SparseInt numRows)\n    {\n      int const upperLeftVertexId = row+col*numRows;\n      file << upperLeftVertexId << \" \" << upperLeftVertexId+1 << \" \" << upperLeftVertexId+numRows << \" \" << upperLeftVertexId+numRows+1 << \" \";\n    }\n  }\n\n  template <class Assembler, class Functional,int firstBlock=0, int lastBlock = Functional::AnsatzVars::noOfVariables>\n  typename Functional::Scalar d1(Assembler& assembler, Functional const& f, typename Functional::AnsatzVars::VariableSet& x, typename Functional::Scalar tolerance = 1e-6, typename Functional::Scalar increment = 1e-12, bool toFile=false, std::string const& filename = std::string(\"d1error\"))\n  {\n    typedef typename Functional::Scalar Scalar;\n    typedef typename Functional::AnsatzVars::template CoefficientVectorRepresentation<firstBlock,lastBlock>::type CoefficientVector;\n\n    std::cout << \"checking first derivative\" << std::endl;\n    std::cout << \"assembling...\";\n\n    // storage for the evaluation of the derivative at x and the at x+increment*e_i\n    Scalar distorted;\n\n    // get reference solution\n    assembler.assemble(linearization(f,x), Assembler::RHS | Assembler::VALUE );\n\n    CoefficientVector analytic(assembler.template rhs<firstBlock,lastBlock>());\n    std::vector<Scalar> analyticD1(assembler.template nrows<firstBlock,lastBlock>());\n    analytic.write(analyticD1.begin());\n\n    // get undistorted rhs\n    Scalar const reference_value = assembler.functional();\n\n    std::vector<Scalar> xAsVector(assembler.nrows());\n    x.write(xAsVector.begin());\n\n    // reserve storage for finite difference solution\n    std::vector<Scalar> firstDerivativeError(analyticD1.size(),0.);\n\n    size_t offset = (0!=firstBlock) ? assembler.template nrows<0,firstBlock>() : 0;\n    size_t end = (lastBlock!=Functional::AnsatzVars::noOfVariables) ? (offset + assembler.template nrows<firstBlock,lastBlock>()) : xAsVector.size();\n\n    // get finite difference gradient\n    for(size_t i=offset; i<end; ++i)\n    {\n\n      xAsVector[i] += increment;\n      x.read(xAsVector.begin());\n\n      assembler.assemble(linearization(f,x),Assembler::VALUE);\n      distorted = assembler.functional();\n      xAsVector[i] -= increment;\n\n      // store finite difference\n      firstDerivativeError[i-offset] = (distorted - reference_value)/increment;\n      if(i%100==0) std::cout << \".\";\n    }\n    // set x back to initial state\n    x.read(xAsVector.begin());\n    std::cout << \"done.\" << std::endl;\n    for(size_t i=0; i<firstDerivativeError.size(); ++i)\n        firstDerivativeError[i] -= analyticD1[i];\n\n    Scalar infinityError = LinAlg::InfinityNorm()(firstDerivativeError);\n    bool errorBelowTolerance = infinityError < tolerance;\n    if(errorBelowTolerance)\n      std::cout << \"\\n first derivative seems to be trustworthy!\\nInfinityError: \" << infinityError << std::endl << std::endl;\n    else\n      std::cout << \"\\n first derivative does not seem to be trustworthy!\\nInfinity error: \" << infinityError << std::endl << std::endl;\n\n    if(toFile) vectorToVTK(firstDerivativeError);\n\n    return infinityError;\n  }\n\n  template <class Assembler, class Functional, int firstRow=0, int lastRow=Functional::TestVars::noOfVariables, int firstCol=0, int lastCol=Functional::AnsatzVars::noOfVariables>\n  typename Functional::Scalar d2(Assembler& assembler, Functional const& f, typename Functional::AnsatzVars::VariableSet const& x, typename Functional::Scalar increment = 1e-12, typename Functional::Scalar tolerance = 1e-6, bool toFile = false, std::string const& savefilename = std::string(\"d2error\"))\n  {\n    typedef typename Functional::Scalar Scalar;\n    typedef typename Functional::TestVars::template CoefficientVectorRepresentation<firstRow,lastRow>::type  RowVector;\n    typedef typename Functional::AnsatzVars::template CoefficientVectorRepresentation<firstCol,lastCol>::type ColumnVector;\n\n    std::cout << \"checking second derivative:\" << std::endl;\n    std::cout << \"assembling...\";\n\n    // sparse storage for the analytic solution\n    typedef MatrixAsTriplet<Scalar> SparseMatrix;\n    SparseMatrix secondDerivativeError;\n\n    // get reference solution\n    assembler.assemble(linearization(f,x), Assembler::RHS, Assembler::MATRIX);\n    SparseMatrix analytic_solution = assembler.template get<SparseMatrix,firstRow,lastRow,firstCol,lastCol>(false);\n    RowVector reference_value(assembler. template rhs<firstRow,lastRow>());\n    RowVector copyOfRefVal(reference_value);\n\n    // get evaluation point\n    std::vector<Scalar> xAsVector(assembler.nrows());\n    x.write(xAsVector.begin());\n\n    size_t offset = (firstRow != 0) ? assembler.template nrows<0,firstRow>() : 0;\n    size_t end = (lastRow!=Functional::TestVars::noOfVariables) ? (offset + assembler.template nrows<firstRow,lastRow>()) : xAsVector.size();\n\n    // get finite difference gradient matrix\n    for(size_t i=offset; i<end; ++i)\n    {\n      copyOfRefVal = reference_value;\n      xAsVector[i] += increment;\n      x.read(xAsVector.begin());\n\n      assembler.assemble(linearization(f,x), Assembler::RHS);\n      RowVector distorted_value(assembler.template rhs<firstRow,lastRow>());\n\n      xAsVector[i] -= increment;\n\n      std::vector<Scalar> column(end-offset);\n      copyOfRefVal -= distorted_value;\n      copyOfRefVal.write(column.begin());\n\n      secondDerivativeError.addColumn(column,i);\n      // store finite difference\n      //      for(size_t k=0; k<numRows; ++k)\n      //      {\n      //        secondDerivativeError.addEntry(k, i, (distorted_value[k] - reference_value[k])/increment);\n      //      }\n      if(i%100==0) std::cout << \".\";\n    }\n    // set x back to initial state\n    x.read(xAsVector.begin());\n    std::cout << \"done.\" << std::endl;\n    analytic_solution *= -1;\n    secondDerivativeError += analytic_solution;\n\n\n    Scalar infinityError = LinAlg::InfinityNorm()(secondDerivativeError);\n    if( (tolerance > infinityError) )\n      std::cout << \"\\nSecond derivative seems to be trustworthy!\\nInfinity error: \" << infinityError << std::endl << std::endl;\n    else\n      std::cout << \"\\nSecond derivative does not seem to be trustworthy!\\nInfinity error: \" << infinityError << std::endl << std::endl;\n\n    return infinityError;\n  }\n\n\n  template <class Vector>\n  void vectorToVTK(Vector const& vec, std::string savefilename = std::string(\"d1error\"))\n  {\n    using std::endl;\n    using std::string;\n\n    size_t const numberOfRows = vec.size(),\n                 numberOfPoints = (1+numberOfRows)*2;\n    size_t const cell_type = 8,\n                 offset = 4;\n\n    XMLHelper::xml_level = 0;\n    typedef typename XMLHelper::XMLBlock XMLBlock;\n\n    savefilename.append(\".vtu\");\n    std::ofstream file(savefilename.c_str());\n    file << \"<?xml version=\\\"1.0\\\"?>\" << endl;\n    { XMLBlock xvtk(file, \"VTKFile\", \" type=\\\"UnstructuredGrid\\\" version=\\\"0.1\\\" byte_order=\\\"LittleEndian\\\"\");\n      { XMLBlock xgrid(file, \"UnstructuredGrid\");\n        { string str = string(\" NumberOfPoints=\\\"\") + boost::lexical_cast<string>(numberOfPoints) + \" \\\" numberOfRows=\\\"\" +\n          boost::lexical_cast<string>(numberOfRows) + \"\\\"\";\n          XMLBlock xpiece(file, \"Piece\", str.c_str());\n          { XMLBlock xcd(file, \"CellData\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"d2error\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%12==0) file << \"    \";\n                // invert row order for visualization tools\n                file << fabs(vec[numberOfRows-1-cell]) << \" \";\n                if(cell%12==11 || cell==(numberOfRows-1) ) file << endl;\n              }\n            }\n          }\n          { XMLBlock xpoints(file, \"Points\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"Coordinates\\\" NumberOfComponents=\\\"3\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows+1; ++cell){\n                if(cell%2==0) file << \"    \";\n                file << cell << \" 0 0 \" << cell << \" 1 0 \";\n                if(cell%2==1 || cell==numberOfRows) file << endl;\n              }\n            }\n          }\n          { XMLBlock xcells(file, \"Cells\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"connectivity\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%3==0) file << \"    \";\n                file << 2*cell << \" \" << 2*cell+1 << \" \" << 2*cell+2 << \" \" << 2*cell+3 << \" \" << endl;\n                if(cell%3==11 || cell==(numberOfRows-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"offsets\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell*offset << \" \";\n                if(cell%12==1 || cell==(numberOfRows-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"UInt8\\\" Name=\\\"types\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell_type << \" \";\n                if(cell%12==11 || cell==(numberOfRows-1) ) file << endl;\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  template <class Scalar, class SparseInt>\n  void matrixToVTK(MatrixAsTriplet<Scalar,SparseInt> const& matrix, std::string savefilename = std::string(\"d2error\"))\n    {\n      using std::cout;\n      using std::endl;\n      using std::string;\n\n      cout << \"writing file\";\n\n      /// store index pairs\n      std::vector<std::pair<SparseInt,SparseInt> > indices(matrix.data.size());\n      for(size_t i=0; i<indices.size(); ++i)\n        indices[i] = std::make_pair(matrix.ridx[i], matrix.cidx[i]);\n\n      SparseInt const numberOfRows = matrix.nrows()+1,\n          numberOfColumns = matrix.ncols()+1,\n          numberOfPoints = numberOfRows*numberOfColumns,\n          numberOfCells = (numberOfRows-1)*(numberOfColumns-1);\n      size_t const cell_type = 8, // = vtk_pixel\n          offset = 4;\n\n      XMLHelper::xml_level = 0;\n      string indent;\n      typedef typename XMLHelper::XMLBlock XMLBlock;\n\n      savefilename.append(\".vtu\");\n      std::ofstream file(savefilename.c_str());\n      file << \"<?xml version=\\\"1.0\\\"?>\" << endl;\n      { XMLBlock xvtk(file, \"VTKFile\", \" type=\\\"UnstructuredGrid\\\" version=\\\"0.1\\\" byte_order=\\\"LittleEndian\\\"\");\n        { XMLBlock xgrid(file, \"UnstructuredGrid\");\n          { string str = string(\" NumberOfPoints=\\\"\") + boost::lexical_cast<string>(numberOfPoints) + \" \\\" NumberOfCells=\\\"\" +\n            boost::lexical_cast<string>(numberOfCells) + \"\\\"\";\n            XMLBlock xpiece(file, \"Piece\", str.c_str());\n            { XMLBlock xcd(file, \"CellData\");\n              { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"d2error\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n                int cell = 0;\n                indent = XMLHelper::getXMLIndent();\n                for(SparseInt col=0; col<numberOfColumns-1; ++col){\n                  for(SparseInt row=0; row<numberOfRows-1; ++row){\n                    if(cell%12==0) file << indent.c_str();\n                    typename std::vector<std::pair<SparseInt,SparseInt> >::const_iterator iter = std::find(indices.begin(), indices.end(), std::make_pair(numberOfRows-2-row,col)),\n                        iterStart = indices.begin();\n                    if(iter!=indices.end())\n                      file << fabs(matrix.data[std::distance(iterStart, iter)]) << \" \";\n                    else\n                      file << 0.0 << \" \";\n                    if(cell%12==11 || cell==numberOfCells-1) file << endl;\n                    ++cell;\n                  }\n                }\n              }\n            }\n            cout << \".\";\n            { XMLBlock xp(file, \"Points\");\n              { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"Coordinates\\\" NumberOfComponents=\\\"3\\\" format=\\\"ascii\\\"\");\n                int cell = 0;\n                for(SparseInt col=0; col<numberOfColumns; ++col){\n                  for(SparseInt row=0; row<numberOfRows; ++row){\n                    if(cell%4==0) file << indent.c_str();\n                    file << row << \" \" << col << \" 0 \";\n                    if(cell%4==3 || cell==(numberOfCells-1)) file << endl;\n                    ++cell;\n                  }\n                }\n              }\n            }\n            cout << \".\";\n            { XMLBlock xcell(file, \"Cells\");\n              { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"connectivity\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n                int cell = 0;\n                for(SparseInt col=0; col<numberOfColumns-1; ++col){\n                  for(SparseInt row=0; row<numberOfRows-1; ++row){\n                    if(cell%3==0) file << indent.c_str();\n                    Private::writeConnectivity(file, row, col, numberOfRows);\n                    if(cell%3==2 || cell==(numberOfCells-1)) file << endl;\n                    ++cell;\n                  }\n                }\n              }\n              cout << \".\";\n              { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"offsets\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n                for(SparseInt cell=0; cell<numberOfCells; ++cell){\n                  if(cell%12==0) file << indent.c_str();\n                  file << (cell+1)*offset << \" \";\n                  if(cell%12==11 || cell==(numberOfCells-1)) file << endl;\n                }\n              }\n              cout << \".\";\n              { XMLBlock xda(file, \"DataArray\", \" type=\\\"UInt8\\\" Name=\\\"types\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n                for(SparseInt cell=0; cell<numberOfCells; ++cell){\n                  if(cell%12==0) file << indent.c_str();\n                  file << cell_type << \" \";\n                  if(cell%12==11 || cell==(numberOfCells-1) ) file << endl;\n                }\n              }\n            }\n          }\n        }\n      }\n      cout << \"done\" << endl;\n    }\n\n} // end of namespace DerivativeCheck\n\n/// Class that checks the derivatives of a functional at a linearization point.\n/**\n * The analytic derivatives are compared with a finite difference approximation. Note that this\n * just gives you a hint (but a good one if you don't use stupid parameters for the tolerance and\n * the increment) about the correctness of your analytically calculated derivatives.\n * Keep in mind that it is a heuristic.\n *\n * \\param checkD1 enable/disable check of first derivative (i.e. disable it if d0() has not been implemented\n *                correctly in boundary or domain cache (optional, default=true(enabled))\n * \\param SparseInt integer type used for sparse matrix indices\n */\ntemplate <class Functional, bool checkD1=true, class SparseInt=int>\nclass DerivativeChecker\n{\n  typedef VariationalFunctionalAssembler<LinearizationAt<Functional> > Assembler;\n  typedef typename Functional::AnsatzVars VariableSet;\n  typedef typename VariableSet::VariableSet EvaluationPoint;\n  typedef typename VariableSet::template CoefficientVectorRepresentation<> CoefficientVectorRepresentation;\n  typedef typename CoefficientVectorRepresentation::type CoefficientVector;\n\npublic:\n  typedef typename Functional::Scalar Scalar;\n  enum{ idOfFirstBlock = 0,\n    idOfLastBlock  = boost::mpl::size<typename Functional::AnsatzVars::Variables>::type::value };\n\n  /// Constructor\n  /**\n   * \\param functional instance of the Functional\n   * \\param x_ linearization point\n   * \\param t error tolerance (point-wise, default=1.0e-6)\n   * \\param incr increment for finite differences (default=1.0e-9)\n   */\n  DerivativeChecker(Assembler& assembler_, Functional const& f_, EvaluationPoint const& x_, VariableSet const& variableSet_, Scalar const tol = 1.0e-6, Scalar const incr = 1.0e-9) :\n    assembler(assembler_), f(f_), x(x_), variableSet(variableSet_), tolerance(tol), increment(incr)\n  {\n    if(checkD1) checkFirstDerivative();\n    checkSecondDerivative();\n  }\n\n\n  /// Check first derivative.\n  /**\n   * This function is called by the constructor. You only need to call this function if you have\n   * changed the tolerance.\n   */\n  void checkFirstDerivative()\n  {\n    std::cout << \"checking first derivative\" << std::endl;\n    std::cout << \"assembling...\";\n\n    // storage for the evaluation of the derivative at x and the at x+increment*e_i\n    Scalar distorted;\n\n    // get reference solution\n    assembler.assemble(linearization(f,x), Assembler::RHS | Assembler::VALUE );\n\n    CoefficientVector analytic(assembler.rhs());\n    std::vector<Scalar> analyticD1(assembler.nrows());\n    analytic.write(analyticD1.begin());\n\n    // get undistorted rhs\n    Scalar const reference_value = assembler.functional();\n\n    std::vector<Scalar> xAsVector(analyticD1.size());\n    x.write(xAsVector.begin());\n\n    // reserve storage for finite difference solution\n    firstDerivativeError.resize(xAsVector.size(),0);\n\n    EvaluationPoint copyOfX(x);\n    // get finite difference gradient\n    for(size_t i=0; i<xAsVector.size(); ++i)\n    {\n      xAsVector[i] += increment;\n      copyOfX.read(xAsVector.begin());\n\n      assembler.assemble(linearization(f,copyOfX),Assembler::VALUE);\n      Scalar distorted_value = assembler.functional();\n      xAsVector[i] -= increment;\n\n      // store finite difference\n      firstDerivativeError[i] = (distorted_value - reference_value)/increment;\n      if(i%100==0) std::cout << \".\";\n    }\n    std::cout << \"done.\" << std::endl;\n    for(size_t i=0; i<firstDerivativeError.size(); ++i)\n      firstDerivativeError[i] -= analyticD1[i];\n\n    Scalar infinityError = LinAlg::InfinityNorm()(firstDerivativeError);\n    firstDerivativeOk_ = infinityError < tolerance;\n    if(firstDerivativeOk_)\n      std::cout << \"\\n first derivative seems to be trustworthy!\\nInfinityError: \" << infinityError << std::endl << std::endl;\n    else\n      std::cout << \"\\n first derivative does not seem to be trustworthy!\\nInfinity error: \" << infinityError << std::endl << std::endl;\n  }\n\n\n  /// Check second derivative.\n  /**\n   * This function is called by the constructor. You only need to call this function if you have\n   * changed the tolerance.\n   */\n  void checkSecondDerivative()\n  {\n    std::cout << \"checking second derivative:\" << std::endl;\n    // Define linearization at x\n    std::cout << \"assembling...\";\n\n    // sparse storage for the analytic solution\n    typedef MatrixAsTriplet<Scalar,SparseInt> SparseMatrix;\n\n    // get reference solution\n    assembler.assemble(linearization(f,x), Assembler::RHS, Assembler::MATRIX);\n    SparseMatrix analytic_solution = assembler.template get<SparseMatrix>(false);\n    CoefficientVector reference_value(assembler.rhs());\n    CoefficientVector copyOfRefVal(reference_value);\n\n    // get evaluation point\n    std::vector<Scalar> xAsVector(assembler.nrows());\n    x.write(xAsVector.begin());\n\n    EvaluationPoint copyOfX(x);\n    // get finite difference gradient matrix\n    for(size_t i=0; i<xAsVector.size(); ++i)\n    {\n      copyOfRefVal = reference_value;\n      xAsVector[i] += increment;\n      copyOfX.read(xAsVector.begin());\n\n      assembler.assemble(linearization(f,copyOfX), Assembler::RHS);\n      CoefficientVector distorted_value(assembler.rhs());\n\n      xAsVector[i] -= increment;\n\n      std::vector<Scalar> column(xAsVector.size());\n      copyOfRefVal -= distorted_value;\n      copyOfRefVal.write(column.begin());\n\n      secondDerivativeError.addColumn(column,i);\n      // store finite difference\n//      for(size_t k=0; k<numRows; ++k)\n//      {\n//        secondDerivativeError.addEntry(k, i, (distorted_value[k] - reference_value[k])/increment);\n//      }\n      if(i%100==0) std::cout << \".\";\n    }\n    std::cout << \"done.\" << std::endl;\n    analytic_solution *= -1;\n    secondDerivativeError += analytic_solution;\n\n\n    Scalar infinityError = LinAlg::InfinityNorm()(secondDerivativeError);\n    if( (secondDerivativeOk_ = tolerance > infinityError) )\n      std::cout << \"\\nSecond derivative seems to be trustworthy!\\nInfinity error: \" << infinityError << std::endl << std::endl;\n    else\n      std::cout << \"\\nSecond derivative does not seem to be trustworthy!\\nInfinity error: \" << infinityError << std::endl << std::endl;\n  }\n\n  bool firstDerivativeOk() const { return firstDerivativeOk_; }\n\n  bool secondDerivativeOk() const { return secondDerivativeOk_; }\n\n//  /// get block of d1Error\n//  std::vector<Scalar> getBlocksD1Error(int const firstBlockId, int const lastBlockId) const\n//  {\n//    assert(firstBlockId < lastBlockId);\n//    std::pair<int,int> ids = getRowIds(firstBlockId, lastBlockId);\n//    std::vector<Scalar> result;\n//    for(int row = ids.first; row<ids.second; ++row)\n//      result.push_back(firstDerivativeError[row]);\n//    return result;\n//  }\n//\n//  /// get block of d2Error\n//  MatrixAsTriplet<Scalar> getBlocksD2Error(int const firstBlockId, int const lastBlockId) const\n//  {\n//    assert(firstBlockId < lastBlockId);\n//    std::pair<int,int> ids = getRowIds(firstBlockId, lastBlockId);\n//\n//    MatrixAsTriplet<Scalar> blocks;\n//    for(int i=0; i<secondDerivativeError.size(); ++i)\n//    {\n//      if(secondDerivativeError.ridx[i] >= ids.first && secondDerivativeError.ridx[i] < ids.second &&\n//          secondDerivativeError.cidx[i] >= ids.first && secondDerivativeError.cidx[i] < ids.second)\n//        blocks.addEntry(secondDerivativeError.ridx[i], secondDerivativeError.cidx[i], secondDerivativeError.data[i]);\n//    }\n//    return blocks;\n//  }\n\n  /// Only errors below tolerance will be displayed.\n  void setTolerance(Scalar const tol){ tolerance = tol; }\n\n  /// Set increment for finite differences\n  void setIncrement(Scalar const incr){ increment = incr; }\n\n  /// print error in first derivative (only values below tolerance)\n  void printD1Error() const\n  {\n    std::cout << \"components in D1 over tolerance:\\n\";\n    for(size_t i=0; i<firstDerivativeError.size(); ++i)\n      if(fabs(firstDerivativeError[i]) > tolerance)\n        std::cout << i << \": \" << firstDerivativeError[i] << std::endl;\n  }\n\n  /// print error in first derivative\n  void printFullD1Error() const\n  {\n    std::cout << \"components in D1:\\n\" << firstDerivativeError << std::endl;\n  }\n\n  /// print error in second derivative (only values below tolerance)\n  void printD2Error() const\n  {\n    std::cout << \"components in D2 over tolerance:\\n\";\n    secondDerivativeError.print(std::cout,tolerance);\n  }\n\n  /// print error in second derivative\n  void printFullD2Error() const\n  {\n    std::cout << \"components in D2:\\n\";\n    secondDerivativeError.print(std::cout);\n  }\n\n  /// write d2 to .vtu file\n  void d2ToVTK(){\n    assembler.assemble(linearization(f,x),Assembler::MATRIX);\n    // sparse storage for the analytic solution\n    MatrixAsTriplet<Scalar,SparseInt> analytic_solution = assembler.template get<MatrixAsTriplet<Scalar,SparseInt>>(false);\n    // get reference solution\n    matrixToVTK(analytic_solution);\n  }\n\n  /// write error in first derivative to .vtu file\n  void d1ErrorToVTK(int const steps) const { vectorToVTK(firstDerivativeError, steps); }\n\n//  /// write block of error in first derivative to .vtu file\n//  void d1BlockErrorToVTK(int const firstBlockId, int const lastBlockId) const { vectorToVTK(getBlocksD1Error(firstBlockId,lastBlockId)); }\n\n  /// write Vector vector to .vtu file\n  /**\n   * Vector must provide the function size() and  operator[](size_type n)\n   */\n  template <class Vector>\n  void vectorToVTK(Vector &vector, int const steps=0) const {\n\n    using std::endl;\n    using std::string;\n\n    size_t const numberOfRows = vector.size(),\n        numberOfPoints = (1+numberOfRows)*2;\n    size_t const cell_type = 8,\n        offset = 4;\n\n    XMLHelper::xml_level = 0;\n    typedef typename XMLHelper::XMLBlock XMLBlock;\n\n    string filename(\"d1error\");\n    filename.append(boost::lexical_cast<string>(steps)).append(\".vtu\");\n\n    std::ofstream file(filename.c_str());\n    file << \"<?xml version=\\\"1.0\\\"?>\" << endl;\n    { XMLBlock xvtk(file, \"VTKFile\", \" type=\\\"UnstructuredGrid\\\" version=\\\"0.1\\\" byte_order=\\\"LittleEndian\\\"\");\n      { XMLBlock xgrid(file, \"UnstructuredGrid\");\n        { string str = string(\" NumberOfPoints=\\\"\") + boost::lexical_cast<string>(numberOfPoints) + \" \\\" numberOfRows=\\\"\" +\n          boost::lexical_cast<string>(numberOfRows) + \"\\\"\";\n          XMLBlock xpiece(file, \"Piece\", str.c_str());\n          { XMLBlock xcd(file, \"CellData\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"d2error\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%12==0) file << \"    \";\n                // invert row order for visualization tools\n                file << fabs(vector[numberOfRows-1-cell]) << \" \";\n                if(cell%12==11 || cell==(numberOfRows-1) ) file << endl;\n              }\n            }\n          }\n          { XMLBlock xpoints(file, \"Points\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"Coordinates\\\" NumberOfComponents=\\\"3\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows+1; ++cell){\n                if(cell%2==0) file << \"    \";\n                file << cell << \" 0 0 \" << cell << \" 1 0 \";\n                if(cell%2==1 || cell==numberOfRows) file << endl;\n              }\n            }\n          }\n          { XMLBlock xcells(file, \"Cells\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"connectivity\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%3==0) file << \"    \";\n                file << 2*cell << \" \" << 2*cell+1 << \" \" << 2*cell+2 << \" \" << 2*cell+3 << \" \" << endl;\n                if(cell%3==11 || cell==(numberOfRows-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"offsets\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell*offset << \" \";\n                if(cell%12==1 || cell==(numberOfRows-1)) file << endl;\n              }\n            }\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"UInt8\\\" Name=\\\"types\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfRows; ++cell){\n                if(cell%12==0) file << \"    \";\n                file << cell_type << \" \";\n                if(cell%12==11 || cell==(numberOfRows-1) ) file << endl;\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  /// write error in second derivative to .vtu-file\n  void d2ErrorToVTK(int const steps) const { matrixToVTK(secondDerivativeError,steps); }\n\n//  /// write block of second derivative to .vtu-file\n//  void d2BlockErrorToVTK(int firstBlockId, int lastBlockId) const { matrixToVTK(getBlocksD2Error(firstBlockId,lastBlockId)); }\n\n  /// write, possibly sparse, matrix in triplet format to .vtu-file\n  void matrixToVTK(MatrixAsTriplet<Scalar,SparseInt> const& matrix, int const steps=0) const\n  {\n    using std::cout;\n    using std::endl;\n    using std::string;\n\n    cout << \"writing file\";\n\n    /// store index pairs\n    std::vector<std::pair<SparseInt,SparseInt> > indices(matrix.data.size());\n    for(size_t i=0; i<indices.size(); ++i)\n      indices[i] = std::make_pair(matrix.ridx[i], matrix.cidx[i]);\n\n    SparseInt const numberOfRows = matrix.nrows()+1,\n        numberOfColumns = matrix.ncols()+1,\n        numberOfPoints = numberOfRows*numberOfColumns,\n        numberOfCells = (numberOfRows-1)*(numberOfColumns-1);\n    size_t const cell_type = 8, // = vtk_pixel\n        offset = 4;\n\n    XMLHelper::xml_level = 0;\n    string indent;\n    typedef typename XMLHelper::XMLBlock XMLBlock;\n\n    string filename(\"d2error\");\n    filename.append(boost::lexical_cast<string>(steps)).append(\".vtu\");\n\n    std::ofstream file(filename.c_str());\n    file << \"<?xml version=\\\"1.0\\\"?>\" << endl;\n    { XMLBlock xvtk(file, \"VTKFile\", \" type=\\\"UnstructuredGrid\\\" version=\\\"0.1\\\" byte_order=\\\"LittleEndian\\\"\");\n      { XMLBlock xgrid(file, \"UnstructuredGrid\");\n        { string str = string(\" NumberOfPoints=\\\"\") + boost::lexical_cast<string>(numberOfPoints) + \" \\\" NumberOfCells=\\\"\" +\n          boost::lexical_cast<string>(numberOfCells) + \"\\\"\";\n          XMLBlock xpiece(file, \"Piece\", str.c_str());\n          { XMLBlock xcd(file, \"CellData\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"d2error\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              int cell = 0;\n              indent = XMLHelper::getXMLIndent();\n              for(SparseInt col=0; col<numberOfColumns-1; ++col){\n                for(SparseInt row=0; row<numberOfRows-1; ++row){\n                  if(cell%12==0) file << indent.c_str();\n                  typename std::vector<std::pair<SparseInt,SparseInt> >::const_iterator iter = std::find(indices.begin(), indices.end(), std::make_pair(numberOfRows-2-row,col)),\n                      iterStart = indices.begin();\n                  if(iter!=indices.end())\n                    file << fabs(matrix.data[std::distance(iterStart, iter)]) << \" \";\n                  if(cell%12==11 || cell==numberOfCells-1) file << endl;\n                  ++cell;\n                }\n              }\n            }\n          }\n          cout << \".\";\n          { XMLBlock xp(file, \"Points\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Float32\\\" Name=\\\"Coordinates\\\" NumberOfComponents=\\\"3\\\" format=\\\"ascii\\\"\");\n              int cell = 0;\n              for(size_t col=0; col<numberOfColumns; ++col){\n                for(size_t row=0; row<numberOfRows; ++row){\n                  if(cell%4==0) file << indent.c_str();\n                  file << row << \" \" << col << \" 0 \";\n                  if(cell%4==3 || cell==(numberOfCells-1)) file << endl;\n                  ++cell;\n                }\n              }\n            }\n          }\n          cout << \".\";\n          { XMLBlock xcell(file, \"Cells\");\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"connectivity\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              int cell = 0;\n              for(size_t col=0; col<numberOfColumns-1; ++col){\n                for(size_t row=0; row<numberOfRows-1; ++row){\n                  if(cell%3==0) file << indent.c_str();\n                  writeConnectivity(file, row, col, numberOfRows);\n                  if(cell%3==2 || cell==(numberOfCells-1)) file << endl;\n                  ++cell;\n                }\n              }\n            }\n            cout << \".\";\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"Int32\\\" Name=\\\"offsets\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << indent.c_str();\n                file << (cell+1)*offset << \" \";\n                if(cell%12==11 || cell==(numberOfCells-1)) file << endl;\n              }\n            }\n            cout << \".\";\n            { XMLBlock xda(file, \"DataArray\", \" type=\\\"UInt8\\\" Name=\\\"types\\\" NumberOfComponents=\\\"1\\\" format=\\\"ascii\\\"\");\n              for(size_t cell=0; cell<numberOfCells; ++cell){\n                if(cell%12==0) file << indent.c_str();\n                file << cell_type << \" \";\n                if(cell%12==11 || cell==(numberOfCells-1) ) file << endl;\n              }\n            }\n          }\n        }\n      }\n    }\n    cout << \"done\" << endl;\n  }\n\nprivate:\n//  /// get ids of first and last row in [firstBlockId,lastBlockId]\n//  std::pair<int,int> getRowIds(int const firstBlockId, int const lastBlockId) const\n//  {\n//    int const firstIdx = (firstBlockId > 0) ? linearization.rows(0,firstBlockId) : 0;\n//    int const lastIdx = firstIdx + linearization.rows(firstBlockId, lastBlockId);\n//    return std::make_pair(firstIdx, lastIdx);\n//  }\n\n  void writeConnectivity(std::ofstream &file, SparseInt row, SparseInt col, SparseInt numRows) const\n  {\n    int const upperLeftVertexId = row+col*numRows;\n    file << upperLeftVertexId << \" \" << upperLeftVertexId+1 << \" \" << upperLeftVertexId+numRows << \" \" << upperLeftVertexId+numRows+1 << \" \";\n  }\n\n  Assembler& assembler;\n  Functional const& f;\n  EvaluationPoint x;\n  VariableSet const& variableSet;\n  Scalar tolerance, increment;\n  std::vector<Scalar> firstDerivativeError;\n  MatrixAsTriplet<Scalar,SparseInt> secondDerivativeError;\n  bool firstDerivativeOk_, secondDerivativeOk_;\n};\n} // end of namespace Kaskade\n#endif /* CHECK_DERIVATIVE_HH */\n", "meta": {"hexsha": "056e84cc8c4e0f4c820a54c5e7266a72e10e39ef", "size": 35092, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/utilities/check_derivative.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/utilities/check_derivative.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/utilities/check_derivative.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": 41.6275207592, "max_line_length": 302, "alphanum_fraction": 0.5947509404, "num_tokens": 8602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.05834584347710904, "lm_q1q2_score": 0.020135458122433333}}
{"text": "#include <assert.h>\n#include <stdlib.h>\n#include <string.h>\n#include <string>\n#include <sstream>\n#include <boost/regex.hpp>\n#include <sqlite3ext.h>\n#include <cmath>\nSQLITE_EXTENSION_INIT1\n\n#ifdef REDUCED_PRECISION\ntypedef float real;\n#else\ntypedef double real;\n#endif\n\n/**\n  Get a string argument from SQLite. It assumes you already know it's there.\n  You can check that with argc() or trust SQLite to do that. */\nconst char *getSQLiteString(\n    sqlite3_context *ctx,\n    sqlite3_value *arg,\n    const std::string& func,\n    const std::string& name) {\n  const char *value = (const char *) sqlite3_value_text(arg);\n  if (value) {\n    return value;\n  } else {\n    sqlite3_result_error(ctx, (func + \"(): missing \" + name).data(), -1);\n    return NULL;\n  }\n}\n\n\nextern \"C\" {\n  /**\n   * Regular Expressions\n   **/\n\n\n  /**\n   * @brief Match a regular expression, giving a boolean.\n   */\n  void match(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n      const char *re = getSQLiteString(ctx, argv[0], \"match\", \"regular expression\");\n      const char *subject = getSQLiteString(ctx, argv[1], \"match\", \"subject\");\n      if (!re || !subject) return;\n\n      // Catch all for regex errors and API cleanliness\n      try {\n        boost::regex regex(re);\n        sqlite3_result_int(ctx, boost::regex_match(subject, regex));\n      } catch (const boost::regex_error& e) {\n        sqlite3_result_error(ctx, e.what(), -1);\n      }\n\n      return;\n  }\n\n  /**\n   * @brief Search a string with a regex.\n   *\n   * This differs from match. See Boost::regex for more information.\n   */\n  void search(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    const char *re = getSQLiteString(ctx, argv[0], \"search\", \"regular expression\");\n    const char *subject = getSQLiteString(ctx, argv[1], \"search\", \"subject\");\n    if (!re || !subject) return;\n\n    // Catch all for regex errors and API cleanliness\n    try {\n      boost::regex regex(re);\n      sqlite3_result_int(ctx, boost::regex_search(std::string(subject), regex));\n    } catch (const boost::regex_error& e) {\n      sqlite3_result_error(ctx, e.what(), -1);\n    }\n    return;\n  }\n\n  /**\n   * @brief Substitute regex matches with a formatted string.\n   * For more information about the string format, see Boost::regex or the README.\n   */\n  void sub(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    const char *re = getSQLiteString(ctx, argv[0], \"sub\", \"regular expression\");\n    const char *format = getSQLiteString(ctx, argv[1], \"sub\", \"format string\");\n    const char *subject = getSQLiteString(ctx, argv[2], \"sub\", \"subject\");\n    if (!re || !format || !subject) return;\n    // Catch all for regex errors and API cleanliness\n    try {\n      boost::regex regex(re);\n      std::string replaced = boost::regex_replace(std::string(subject), regex, format);\n      sqlite3_result_text(ctx, replaced.data(), -1, SQLITE_TRANSIENT);\n    } catch (const boost::regex_error& e) {\n      sqlite3_result_error(ctx, e.what(), -1);\n    }\n    return;\n  }\n\n\n  /*****************************************************************************\n   * Math\n   */\n\n\n   /** Helper functions */\n  /** Perform a unary operator on either a scalar or vector */\n  void vunop(sqlite3_context *ctx, sqlite3_value *arg, std::function<real(real)> unop) {\n   switch (sqlite3_value_type(arg)) {\n     case SQLITE_INTEGER:\n     case SQLITE_FLOAT:\n       sqlite3_result_double(ctx, unop(sqlite3_value_double(arg)));\n       break;\n     case SQLITE_BLOB: {\n       int len = sqlite3_value_bytes(arg) / sizeof(real);\n       real *vec = (real*) sqlite3_value_blob(arg);\n       real result_vec[len];\n       for (int i=0; i<len; i++) {\n         result_vec[i] = unop(vec[i]);\n       }\n       sqlite3_result_blob(ctx, result_vec, len*sizeof(real), SQLITE_TRANSIENT);\n       break;\n     }\n     default:\n       sqlite3_result_error(ctx,\n         \"Invalid value type for vector/scalar operation. \" \\\n         \"Possible causes:\\n\" \\\n         \"\\tPerforming operations on an empty vector, \\n\"\\\n         \"\\tUsing text as a vector or scalar (convert them first with cast() or vread()),\\n\"\\\n         \"\\tNot space-separating values for vread().\", -1);\n      break;\n   }\n  }\n\n  // Get the length of a scalar or vector, but scalars are -1 to distinguish them.\n  int vecOrScalarLen(sqlite3_value *arg) {\n    switch (sqlite3_value_type(arg)) {\n      case SQLITE_INTEGER:\n      case SQLITE_FLOAT:\n        return -1;\n      case SQLITE_BLOB:\n        return sqlite3_value_bytes(arg) / sizeof(real);\n      default:\n        return 0;\n    }\n  }\n\n  // Run a binary operation on two real vectors.\n  // It's just choosing a type that makes this operation kinda hairy.\n  void vbinop(sqlite3_context *ctx, sqlite3_value **argv, std::function<real(real, real)> binop) {\n    int left_len = vecOrScalarLen(argv[0]);\n    int right_len = vecOrScalarLen(argv[1]);\n\n    if (left_len == 0 || right_len == 0) {\n      // Error\n      sqlite3_result_error(ctx,\n        \"Invalid value type for vector/scalar operation. \" \\\n        \"Possible causes:\\n\" \\\n        \"\\tPerforming operations on an empty vector, \\n\"\\\n        \"\\tUsing text as a vector or scalar (convert them first with cast() or vread()),\\n\"\\\n        \"\\tNot space-separating values for vread().\", -1);\n      return;\n    } else if (left_len == -1 && right_len == -1) {\n      // Scalar-scalar op\n      sqlite3_result_double(ctx, binop(\n        sqlite3_value_double(argv[0]),\n        sqlite3_value_double(argv[1])\n      ));\n    } else if (left_len == -1) {\n      // Scalar-vector op\n      real left = sqlite3_value_double(argv[0]);\n      real *right_vec = (real*) sqlite3_value_blob(argv[1]);\n      real result_vec[right_len];\n      for (int i=0; i<right_len; i++) {\n        result_vec[i] = binop(left, right_vec[i]);\n      }\n      sqlite3_result_blob(ctx, result_vec, right_len*sizeof(real), SQLITE_TRANSIENT);\n    } else if (right_len == -1) {\n      // Vector-scalar op\n      real *left_vec = (real*) sqlite3_value_blob(argv[0]);\n      real right = sqlite3_value_double(argv[1]);\n      real result_vec[left_len];\n      for (int i=0; i<left_len; i++) {\n        result_vec[i] = binop(left_vec[i], right);\n      }\n      sqlite3_result_blob(ctx, result_vec, left_len*sizeof(real), SQLITE_TRANSIENT);\n    } else {\n      // Vector-vector op\n      int len = fmin(left_len, right_len);\n      real *left_vec = (real*) sqlite3_value_blob(argv[0]);\n      real *right_vec = (real*) sqlite3_value_blob(argv[1]);\n      real result_vec[len];\n      for (int i=0; i<len; i++) {\n        result_vec[i] = binop(left_vec[i], right_vec[i]);\n      }\n      sqlite3_result_blob(ctx, result_vec, len*sizeof(real), SQLITE_TRANSIENT);\n    }\n  }\n\n  /*****************************************************************************\n   * SQLite-visible functions, aggregates and wrappers (all start with sql_)\n   */\n\n   void sql_sin(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], sin);\n   }\n   void sql_asin(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], asin);\n   }\n   void sql_cos(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], cos);\n   }\n   void sql_acos(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], acos);\n   }\n   void sql_tan(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], tan);\n   }\n   void sql_atan(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], atan);\n   }\n   void sql_log(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], log);\n   }\n   void sql_exp(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], exp);\n   }\n   void sql_pow(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vbinop(ctx, argv, pow);\n   }\n   void sql_sqrt(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n     vunop(ctx, argv[0], sqrt);\n   }\n\n  // Create a new zero vector\n  void sql_vzero(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    int len = sqlite3_value_int(argv[0]);\n\n    real result_vec[len];\n    for (int i=0; i<len; i++) {\n      result_vec[i] = 0;\n    }\n    sqlite3_result_blob(ctx, result_vec, len*sizeof(real), SQLITE_TRANSIENT);\n  }\n\n  // Create a new one vector\n  void sql_vone(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    int len = sqlite3_value_int(argv[0]);\n\n    real result_vec[len];\n    for (int i=0; i<len; i++) {\n      result_vec[i] = 1;\n    }\n    sqlite3_result_blob(ctx, result_vec, len*sizeof(real), SQLITE_TRANSIENT);\n  }\n\n  // Add two vectors\n  void sql_add(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    vbinop(ctx, argv, [](real a, real b){ return a + b; });\n  }\n  // Subtract the second vector from the first\n  void sql_subtract(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    vbinop(ctx, argv, [](real a, real b){ return a - b; });\n  }\n  // Multiply two vectors\n  void sql_mult(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    vbinop(ctx, argv, [](real a, real b){ return a * b; });\n  }\n  // Divide two vectors\n  void sql_div(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    vbinop(ctx, argv, [](real a, real b){ return a / b; });\n  }\n\n  // Complain to SQLite if we don't get the vectors we want (saves code later)\n  bool must_be_vectors(\n      const char *name,\n      sqlite3_context *ctx,\n      int argc,\n      sqlite3_value **argv) {\n    for (int i=0; i<argc; i++) {\n      if (sqlite3_value_type(argv[i]) != SQLITE_BLOB) {\n        char buffer[100];\n        snprintf(buffer, 100, \"Wrong datatype supplied. %s requires %d vectors.\", name, argc);\n        sqlite3_result_error(ctx, buffer, -1);\n        return false;\n      }\n    }\n    return true;\n  }\n\n  // Compute the sum of the elements of a vector: It's not the most numerically\n  // stable way though.\n  void sql_vsum(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    if (!must_be_vectors(\"vsum\", ctx, 1, argv)) return;\n    int len = sqlite3_value_bytes(argv[0]) / sizeof(real);\n    real *vec = (real*) sqlite3_value_blob(argv[0]);\n    real end = 0.0;\n    for (int i=0; i<len; i++) {\n      end += vec[i];\n    }\n    sqlite3_result_double(ctx, end);\n  }\n\n  // Compute the product of the elements of a vector: It's not the most\n  // numerically stable way though.\n  void sql_vprod(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    if (!must_be_vectors(\"vprod\", ctx, 1, argv)) return;\n    int len = sqlite3_value_bytes(argv[0]) / sizeof(real);\n    real *vec = (real*) sqlite3_value_blob(argv[0]);\n    real end = 0.0;\n    for (int i=0; i<len; i++) {\n      end *= vec[i];\n    }\n    sqlite3_result_double(ctx, end);\n  }\n\n  // Compute the dot product: It's not the most numerically stable way though.\n  void sql_dot(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    if (!must_be_vectors(\"dot\", ctx, 2, argv)) return;\n    int len = fmin(sqlite3_value_bytes(argv[0]), sqlite3_value_bytes(argv[1]))\n              / sizeof(real);\n\n    real *a = (real*) sqlite3_value_blob(argv[0]);\n    real *b = (real*) sqlite3_value_blob(argv[1]);\n    real end = 0.0;\n    for (int i=0; i<len; i++) {\n      end += a[i] * b[i];\n    }\n    sqlite3_result_double(ctx, end);\n  }\n\n  // Compute the cosine similarity between two vectors\n  void sql_cossim(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    if (!must_be_vectors(\"cossim\", ctx, 2, argv)) return;\n    int len = fmin(sqlite3_value_bytes(argv[0]), sqlite3_value_bytes(argv[1]))\n              / sizeof(real);\n\n    real *a = (real*) sqlite3_value_blob(argv[0]);\n    real *b = (real*) sqlite3_value_blob(argv[1]);\n\n    real asq = 0.0;  for (int i=0; i<len; i++) asq  += a[i] * a[i];\n    real bsq = 0.0;  for (int i=0; i<len; i++) bsq  += b[i] * b[i];\n    real absq = 0.0; for (int i=0; i<len; i++) absq += a[i] * b[i];\n\n    sqlite3_result_double(ctx, absq / (sqrt(asq) * sqrt(bsq)));\n  }\n\n  typedef struct FatBuffer {\n    int len; // Length of the content array (in bytes)\n    int count; // Useful for accumulators.\n    real content[1]; // The actual data (probably longer than 1, btw)\n  } FatBuffer;\n  int wrapped_size(int len_reals) {\n    return (2*sizeof(int)) + (len_reals*sizeof(real));\n  };\n\n\n\n  // Compute the sum of many vectors (as part of an aggregate)\n  void sql_vsum_aggregate_step(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    if (!must_be_vectors(\"vsum_aggregate\", ctx, 1, argv)) return;\n    /// --- The only hard part here is allocating the accumulator. ---\n    // First decide how long we'd like it to be *in units*. Optimally it should\n    // be the same size as the vector we're reading right now.\n    int target_len = sqlite3_value_bytes(argv[0]) / sizeof(real);\n    if (target_len == 0) return; // Do nothing for empty vectors.\n    // Maybe allocate it (or it may return an existing buffer of any length\n    // or it may return NULL.)\n    FatBuffer *accum = (FatBuffer*) sqlite3_aggregate_context(ctx, wrapped_size(target_len));\n    if (accum == NULL) {sqlite3_result_error_nomem(ctx); return;} // die.\n    // Find out how long the buffer really is, *in bytes*\n    // If it's new, it's 0'd out so the length will be 0 and we know we got the\n    // size we asked for. Otherwise use the length we asked for.\n    if (accum->len == 0) accum->len = target_len;\n    // Now we should iterate the lesser of the two lengths (in units of reals)\n    int iter_len = fmin(accum->len, target_len);\n    real *vec = (real*) sqlite3_value_blob(argv[0]);\n    for (int i=0; i<iter_len; i++) {\n      accum->content[i] += vec[i];\n    }\n    accum->count++;\n  }\n\n  // Compute the sum of many vectors (as part of an aggregate) (final part)\n  void sql_vsum_aggregate_final(sqlite3_context *ctx) {\n    /// --- The only hard part here is allocating the accumulator. ---\n    // Maybe allocate it (or it may return an existing buffer of any length\n    // or it may return NULL.)\n    FatBuffer *accum = (FatBuffer*) sqlite3_aggregate_context(ctx, 0);\n    if (accum == NULL) {\n      // I'm not sure if a zero-length blob or NULL is better.\n      // I'm choosing this right now merely because of my dislike for NULL.\n      sqlite3_result_zeroblob(ctx, 0);\n    } else {\n      sqlite3_result_blob(ctx, accum->content, accum->len, SQLITE_TRANSIENT);\n    }\n  }\n  // Compute the average of many vectors (as part of an aggregate) (final part)\n  void sql_vavg_aggregate_final(sqlite3_context *ctx) {\n    /// --- The only hard part here is allocating the accumulator. ---\n    // Maybe allocate it (or it may return an existing buffer of any length\n    // or it may return NULL.)\n    FatBuffer *accum = (FatBuffer*) sqlite3_aggregate_context(ctx, 0);\n    if (accum == NULL) {\n      // I'm not sure if a zero-length blob or NULL is better.\n      // I'm choosing this right now merely because of my dislike for NULL.\n      sqlite3_result_zeroblob(ctx, 0);\n    } else {\n      for (int i=0; i<accum->len; i++) accum->content[i] /= accum->count;\n      sqlite3_result_blob(ctx, accum->content, accum->len, SQLITE_TRANSIENT);\n    }\n  }\n\n  // Read a vector from a space separated string\n  void sql_vread(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    const char *text = getSQLiteString(ctx, argv[0], \"vread\", \"space separated floating point values\");\n    std::string str(text);\n    std::stringstream stream(str);\n    std::vector<real> vec;\n    for (real item; stream >> item;) {\n      vec.push_back(item);\n    }\n    sqlite3_result_blob(ctx, &vec.front(), vec.size()*sizeof(real), SQLITE_TRANSIENT);\n  }\n\n  // Write a vector to a space separated string\n  void sql_vshow(sqlite3_context *ctx, int argc, sqlite3_value **argv) {\n    int len = sqlite3_value_bytes(argv[0]) / sizeof(real);\n    real *vec = (real*) sqlite3_value_blob(argv[0]);\n    std::stringstream stream;\n    for (int i=0; i<len; i++) {\n      stream << vec[i] << ' ';\n    }\n    sqlite3_result_text(ctx, stream.str().c_str(), -1, SQLITE_TRANSIENT);\n  }\n\n\n\n  int sqlite3_extension_init(sqlite3 *db, char **err, const sqlite3_api_routines *api) {\n    SQLITE_EXTENSION_INIT2(api)\n\n    // Regular Expressions\n    sqlite3_create_function(db, \"match\",  2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, match, NULL, NULL);\n    sqlite3_create_function(db, \"search\", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, search, NULL, NULL);\n    sqlite3_create_function(db, \"sub\",    3, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sub, NULL, NULL);\n\n    // Math\n    sqlite3_create_function(db, \"sin\",    1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_sin, NULL, NULL);\n    sqlite3_create_function(db, \"asin\",   1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_asin, NULL, NULL);\n    sqlite3_create_function(db, \"cos\",    1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_cos, NULL, NULL);\n    sqlite3_create_function(db, \"acos\",   1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_acos, NULL, NULL);\n    sqlite3_create_function(db, \"tan\",    1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_tan, NULL, NULL);\n    sqlite3_create_function(db, \"atan\",   1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_atan, NULL, NULL);\n    sqlite3_create_function(db, \"log\",    1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_log, NULL, NULL);\n    sqlite3_create_function(db, \"exp\",    1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_exp, NULL, NULL);\n    sqlite3_create_function(db, \"pow\",    2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_pow, NULL, NULL);\n    sqlite3_create_function(db, \"sqrt\",   1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_sqrt, NULL, NULL);\n\n    // Vector operations\n    sqlite3_create_function(db, \"vread\", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_vread, NULL, NULL);\n    sqlite3_create_function(db, \"vshow\", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_vshow, NULL, NULL);\n    //sqlite3_create_function(db, \"vburst\", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvburst, NULL, NULL);\n    //sqlite3_create_function(db, \"vcollapse\", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvcollase, NULL, NULL);\n    sqlite3_create_function(db, \"vzero\",  1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_vzero, NULL, NULL);\n    sqlite3_create_function(db, \"vone\",   1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_vone, NULL, NULL);\n    sqlite3_create_function(db, \"add\",    2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_add, NULL, NULL);\n    sqlite3_create_function(db, \"subtract\", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_subtract, NULL, NULL);\n    sqlite3_create_function(db, \"mult\",   2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_mult, NULL, NULL);\n    sqlite3_create_function(db, \"div\",    2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_div, NULL, NULL);\n    sqlite3_create_function(db, \"vsum\",   1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_vsum, NULL, NULL);\n    sqlite3_create_function(db, \"vprod\",  1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_vprod, NULL, NULL);\n    sqlite3_create_function(db, \"dot\",    2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_dot, NULL, NULL);\n    sqlite3_create_function(db, \"cossim\", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sql_cossim, NULL, NULL);\n\n    // Aggregate functions\n    sqlite3_create_function(db, \"vsum_aggregate\", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, NULL, sql_vsum_aggregate_step, sql_vsum_aggregate_final);\n    sqlite3_create_function(db, \"vavg_aggregate\", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, NULL, sql_vsum_aggregate_step, sql_vavg_aggregate_final);\n    return 0;\n  }\n}\n", "meta": {"hexsha": "2c1fab4d58a6dc0bb40137dd0ed03324f4f20f09", "size": 19406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extras.cpp", "max_stars_repo_name": "SeanTater/sqlite3-extras", "max_stars_repo_head_hexsha": "73688b0920a7cd4ad1b4d7fe0695bd73dce3d8a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-07-21T02:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:21:16.000Z", "max_issues_repo_path": "extras.cpp", "max_issues_repo_name": "SeanTater/sqlite3-extras", "max_issues_repo_head_hexsha": "73688b0920a7cd4ad1b4d7fe0695bd73dce3d8a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-03T09:43:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T09:43:09.000Z", "max_forks_repo_path": "extras.cpp", "max_forks_repo_name": "SeanTater/sqlite3-reutil", "max_forks_repo_head_hexsha": "73688b0920a7cd4ad1b4d7fe0695bd73dce3d8a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-21T16:14:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T17:47:52.000Z", "avg_line_length": 40.3451143451, "max_line_length": 152, "alphanum_fraction": 0.6514480058, "num_tokens": 5424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.04401864563031933, "lm_q1q2_score": 0.020122539142637126}}
{"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 \"loop_corrections.hpp\"\n#include \"threshold_corrections.hpp\"\n#include \"error.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n#include \"physical_input.hpp\"\n\n#include <array>\n#include <iosfwd>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace softsusy {\n   class QedQcd;\n} // namespace softsusy\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\n\nnamespace standard_model_info {\n\n   enum Particles : int {VG, Hp, Fv, Ah, hh, VP, VZ, Fd, Fu, Fe, VWp,\n      NUMBER_OF_PARTICLES};\n\n   enum Parameters : int {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\n   enum Mixings : int {ReVd00, ImVd00, ReVd01, ImVd01, ReVd02, ImVd02,\n      ReVd10, ImVd10, ReVd11, ImVd11, ReVd12, ImVd12, ReVd20, ImVd20, ReVd21,\n      ImVd21, ReVd22, ImVd22, ReUd00, ImUd00, ReUd01, ImUd01, ReUd02, ImUd02,\n      ReUd10, ImUd10, ReUd11, ImUd11, ReUd12, ImUd12, ReUd20, ImUd20, ReUd21,\n      ImUd21, ReUd22, ImUd22, ReVu00, ImVu00, ReVu01, ImVu01, ReVu02, ImVu02,\n      ReVu10, ImVu10, ReVu11, ImVu11, ReVu12, ImVu12, ReVu20, ImVu20, ReVu21,\n      ImVu21, ReVu22, ImVu22, ReUu00, ImUu00, ReUu01, ImUu01, ReUu02, ImUu02,\n      ReUu10, ImUu10, ReUu11, ImUu11, ReUu12, ImUu12, ReUu20, ImUu20, ReUu21,\n      ImUu21, ReUu22, ImUu22, ReVe00, ImVe00, ReVe01, ImVe01, ReVe02, ImVe02,\n      ReVe10, ImVe10, ReVe11, ImVe11, ReVe12, ImVe12, ReVe20, ImVe20, ReVe21,\n      ImVe21, ReVe22, ImVe22, ReUe00, ImUe00, ReUe01, ImUe01, ReUe02, ImUe02,\n      ReUe10, ImUe10, ReUe11, ImUe11, ReUe12, ImUe12, ReUe20, ImUe20, ReUe21,\n      ImUe21, ReUe22, ImUe22, NUMBER_OF_MIXINGS};\n\n   extern const double normalization_g1;\n   extern const double normalization_g2;\n   extern const double normalization_g3;\n\n   extern const std::array<int, NUMBER_OF_PARTICLES> particle_multiplicities;\n   extern const std::array<std::string, NUMBER_OF_PARTICLES> particle_names;\n   extern const std::array<std::string, NUMBER_OF_PARTICLES> particle_latex_names;\n   extern const std::array<std::string, NUMBER_OF_PARAMETERS> parameter_names;\n   extern const std::array<std::string, NUMBER_OF_MIXINGS> particle_mixing_names;\n   extern const std::string model_name;\n   constexpr bool is_low_energy_model = false;\n   constexpr bool is_supersymmetric_model = false;\n\n   class Standard_model_particle_names : public Names {\n   public:\n      virtual ~Standard_model_particle_names() = default;\n      virtual const std::string& get(int index) const override {\n         return particle_names[index];\n      }\n      virtual int size() const override {\n         return NUMBER_OF_PARAMETERS;\n      }\n   };\n\n   class Standard_model_parameter_names : public Names {\n   public:\n      virtual ~Standard_model_parameter_names() = default;\n      virtual const std::string& get(int index) const override {\n         return parameter_names[index];\n      }\n      virtual int size() const override {\n         return NUMBER_OF_PARTICLES;\n      }\n   };\n\n   const Standard_model_particle_names  particle_names_getter{};\n   const Standard_model_parameter_names parameter_names_getter{};\n\n} // namespace standard_model_info\n\nnamespace standard_model {\n\ntemplate <class T>\nclass StandardModel;\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   Standard_model(const Standard_model&) = default;\n   Standard_model(Standard_model&&) = default;\n\n   virtual ~Standard_model() = default;\n\n   Standard_model& operator=(const Standard_model&) = default;\n   Standard_model& operator=(Standard_model&&) = default;\n\n   /// number of EWSB equations\n   static const int number_of_ewsb_equations = 1;\n\n   void calculate_DRbar_masses();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(int);\n   void set_loop_corrections(const Loop_corrections&);\n   const Loop_corrections& get_loop_corrections() const;\n   void set_threshold_corrections(const Threshold_corrections&);\n   const Threshold_corrections& get_threshold_corrections() const;\n   void set_pole_mass_loop_order(int);\n   int 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& get_problems() const;\n   Problems& 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 override;\n   virtual Eigen::ArrayXd get() const override;\n   void print(std::ostream& out = std::cerr) const;\n   virtual void set(const Eigen::ArrayXd&) override;\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   virtual void run_to(double scale, double eps = -1.0) override;\n   void set_precision(double);\n   double get_precision() const;\n\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(const softsusy::QedQcd&);\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(int gI1, int gI2) const;\n   std::complex<double> CpconjHpbarFdFuPL(int gI1, int gI2) const;\n   double CpconjHpbarFeFvPR(int , int ) const;\n   std::complex<double> CpconjHpbarFeFvPL(int gI1, int 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(int gI1, int gI2) const;\n   std::complex<double> CpAhbarFdFdPL(int gI1, int gI2) const;\n   std::complex<double> CpAhbarFeFePR(int gI1, int gI2) const;\n   std::complex<double> CpAhbarFeFePL(int gI1, int gI2) const;\n   std::complex<double> CpAhbarFuFuPR(int gI1, int gI2) const;\n   std::complex<double> CpAhbarFuFuPL(int gI1, int 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(int gI1, int gI2) const;\n   std::complex<double> CphhbarFdFdPL(int gI1, int gI2) const;\n   std::complex<double> CphhbarFeFePR(int gI1, int gI2) const;\n   std::complex<double> CphhbarFeFePL(int gI1, int gI2) const;\n   std::complex<double> CphhbarFuFuPR(int gI1, int gI2) const;\n   std::complex<double> CphhbarFuFuPL(int gI1, int 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(int gI1, int gI2) const;\n   double CpVZbarFdFdPR(int gI1, int gI2) const;\n   double CpVZbarFeFePL(int gI1, int gI2) const;\n   double CpVZbarFeFePR(int gI1, int gI2) const;\n   double CpVZbarFuFuPL(int gI1, int gI2) const;\n   double CpVZbarFuFuPR(int gI1, int gI2) const;\n   double CpVZbarFvFvPL(int gI1, int gI2) const;\n   double CpVZbarFvFvPR(int , int ) 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(int gI1, int gI2) const;\n   double CpconjVWpbarFdFuPR(int , int ) const;\n   std::complex<double> CpconjVWpbarFeFvPL(int gI1, int gI2) const;\n   double CpconjVWpbarFeFvPR(int , int ) 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(int gO2, int gI1) const;\n   std::complex<double> CpbarUFdFdAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUFdhhFdPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdhhFdPR(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdVGFdPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdVGFdPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdVPFdPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdVPFdPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdVZFdPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdVZFdPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdconjHpFuPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdconjHpFuPR(int gO1, int gI2) const;\n   double CpbarUFdconjVWpFuPR(int , int ) const;\n   std::complex<double> CpbarUFdconjVWpFuPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUFuFuAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUFuhhFuPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuhhFuPR(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuHpFdPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuHpFdPR(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuVGFuPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuVGFuPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuVPFuPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuVPFuPL(int gO1, int gI2) const;\n   double CpbarUFuVWpFdPR(int , int ) const;\n   std::complex<double> CpbarUFuVWpFdPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuVZFuPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuVZFuPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeFeAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUFeFeAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUFehhFePL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFehhFePR(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeVPFePR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFeVPFePL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeVZFePR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFeVZFePL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeconjHpFvPL(int gO2, int gI2) const;\n   double CpbarUFeconjHpFvPR(int , int ) const;\n   double CpbarUFeconjVWpFvPR(int , int ) const;\n   double CpbarUFeconjVWpFvPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFdFdAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarFdFdAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarFdhhFdPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFdhhFdPR(int gO1, int gI2) const;\n   double CpbarFdVZFdPR(int gO2, int gI2) const;\n   double CpbarFdVZFdPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFdconjHpFuPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFdconjHpFuPR(int gO1, int gI2) const;\n   double CpbarFdconjVWpFuPR(int , int ) const;\n   std::complex<double> CpbarFdconjVWpFuPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFeFeAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarFeFeAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarFehhFePL(int gO2, int gI2) const;\n   std::complex<double> CpbarFehhFePR(int gO1, int gI2) const;\n   double CpbarFeVZFePR(int gO2, int gI2) const;\n   double CpbarFeVZFePL(int gO1, int gI2) const;\n   std::complex<double> CpbarFeconjHpFvPL(int gO2, int gI2) const;\n   double CpbarFeconjHpFvPR(int , int ) const;\n   double CpbarFeconjVWpFvPR(int , int ) const;\n   std::complex<double> CpbarFeconjVWpFvPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFuFuAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarFuFuAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarFuhhFuPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFuhhFuPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFuHpFdPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFuHpFdPR(int gO1, int gI2) const;\n   double CpbarFuVPFuPR(int gO2, int gI2) const;\n   double CpbarFuVPFuPL(int gO1, int gI2) const;\n   double CpbarFuVWpFdPR(int , int ) const;\n   std::complex<double> CpbarFuVWpFdPL(int gO1, int gI2) const;\n   double CpbarFuVZFuPR(int gO2, int gI2) const;\n   double CpbarFuVZFuPL(int gO1, int gI2) const;\n   std::complex<double> self_energy_Hp_1loop(double p ) const;\n   std::complex<double> self_energy_Ah_1loop(double p ) const;\n   std::complex<double> self_energy_hh_1loop(double p ) const;\n   std::complex<double> self_energy_VZ_1loop(double p ) const;\n   std::complex<double> self_energy_VWp_1loop(double p ) const;\n   std::complex<double> self_energy_Fd_1loop_1(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fd_1loop_PR(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fd_1loop_PL(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_1(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_PR(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_PL(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fe_1loop_1(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fe_1loop_PR(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fe_1loop_PL(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fd_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fd_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fd_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fe_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fe_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fe_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_1_heavy(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_PR_heavy(double p , int gO1, int gO2) const;\n   std::complex<double> self_energy_Fu_1loop_PL_heavy(double p , int gO1, int gO2) const;\n\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_1(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PR(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PL(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_1(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PR(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PL(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_1(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PR(double p) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PL(double p) const;\n\n   std::complex<double> tadpole_hh_1loop() const;\n\n   /// calculates the tadpoles at current loop order\n   Eigen::Matrix<double, number_of_ewsb_equations, 1> tadpole_equations() const;\n\n   /// calculates Higgs 2-loop self-energy\n   double self_energy_hh_2loop(double p) const;\n   /// calculates Higgs 3-loop self-energy\n   double self_energy_hh_3loop() const;\n\n   void calculate_MVG_pole();\n   void calculate_MFv_pole();\n   void calculate_Mhh_pole();\n   void calculate_MVP_pole();\n   void calculate_MVZ_pole();\n   void calculate_MFd_pole();\n   void calculate_MFu_pole();\n   void calculate_MFe_pole();\n   void calculate_MVWp_pole();\n   double calculate_MVWp_pole(double);\n   double calculate_MVZ_pole(double);\n\n   double calculate_MFv_DRbar(double, int) const;\n   double calculate_MFe_DRbar(double, int) const;\n   double calculate_MFu_DRbar(double, int) const;\n   double calculate_MFd_DRbar(double, int) const;\n   double calculate_MVP_DRbar(double);\n   double calculate_MVZ_DRbar(double);\n   double calculate_MVWp_DRbar(double);\n   double calculate_Mhh_DRbar(double);\n\n   double ThetaW() const;\n\n   double calculate_delta_alpha_em(double alphaEm) const;\n   double calculate_delta_alpha_s(double alphaS) const;\n   void calculate_Lambdax_DRbar();\n   double calculate_theta_w(const softsusy::QedQcd&, double alpha_em_drbar);\n   void calculate_Yu_DRbar(const softsusy::QedQcd&);\n   void calculate_Yd_DRbar(const softsusy::QedQcd&);\n   void calculate_Ye_DRbar(const softsusy::QedQcd&);\n   double recalculate_mw_pole(double);\n   double max_rel_diff(const Standard_model& old) const;\n\nprotected:\n\n   // Running parameters\n   double g1{};\n   double g2{};\n   double g3{};\n   double Lambdax{};\n   Eigen::Matrix<double,3,3> Yu{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> Yd{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> Ye{Eigen::Matrix<double,3,3>::Zero()};\n   double mu2{};\n   double v{};\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   using EWSB_vector_t = Eigen::Matrix<double,number_of_ewsb_equations,1>;\n\n   class EEWSBStepFailed : public Error {\n   public:\n      virtual ~EEWSBStepFailed() = default;\n      virtual std::string what() const override { return \"Could not perform EWSB step.\"; }\n   };\n\n   int ewsb_loop_order{2};\n   int pole_mass_loop_order{2};\n   bool force_output{false};      ///< switch to force output of pole masses\n   double precision{1e-3};        ///< RG running precision\n   double ewsb_iteration_precision{1e-5};\n   Standard_model_physical physical{}; ///< contains the pole masses and mixings\n   Problems problems{standard_model_info::model_name,\n                     &standard_model_info::particle_names_getter,\n                     &standard_model_info::parameter_names_getter};\n   Loop_corrections loop_corrections{}; ///< used loop pole mass corrections\n   Threshold_corrections threshold_corrections{}; ///< used low-energy threshold corrections\n   Physical_input input{};\n\n   int get_number_of_ewsb_iterations() const;\n   int get_number_of_mass_iterations() const;\n   int solve_ewsb_iteratively();\n   int solve_ewsb_iteratively(int);\n   int solve_ewsb_iteratively_with(EWSB_solver*, const Eigen::Matrix<double, number_of_ewsb_equations, 1>&);\n   int solve_ewsb_tree_level_custom();\n   EWSB_vector_t ewsb_initial_guess();\n   EWSB_vector_t ewsb_step() const;\n   void copy_DRbar_masses_to_pole_masses();\n\n   void initial_guess_for_parameters(const softsusy::QedQcd&);\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   // DR-bar masses\n   double MVG{};\n   double MHp{};\n   Eigen::Array<double,3,1> MFv{Eigen::Array<double,3,1>::Zero()};\n   double MAh{};\n   double Mhh{};\n   double MVP{};\n   double MVZ{};\n   Eigen::Array<double,3,1> MFd{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFu{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFe{Eigen::Array<double,3,1>::Zero()};\n   double MVWp{};\n   Eigen::Array<double,2,1> MVPVZ{Eigen::Array<double,2,1>::Zero()};\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<std::complex<double>,3,3> Vd{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Ud{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Vu{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Uu{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Ve{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Ue{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<double,2,2> ZZ{Eigen::Matrix<double,2,2>::Zero()};\n\n\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": "36fd2fa73aeb28ad84fe84fb3e6c81f3bad980da", "size": 30445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/standard_model.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/standard_model.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/standard_model.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": 45.2377414562, "max_line_length": 108, "alphanum_fraction": 0.7233043193, "num_tokens": 9838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.040237939314688276, "lm_q1q2_score": 0.020118969657344138}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include <boost/lexical_cast.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include \"niftkConversionUtils.h\"\n#include <math.h>\n#include <algorithm>\n\nnamespace niftk\n{\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(int x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(unsigned int x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(unsigned long long x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(long int x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(long unsigned int x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(double x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(bool x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string ConvertToString(float x)\n{\n  return boost::lexical_cast<std::string>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nint ConvertToInt(const std::string& x)\n{\n  return boost::lexical_cast<int>(x);\n}\n\n\n//-----------------------------------------------------------------------------\ndouble ConvertToDouble(const std::string& x)\n{\n  return boost::lexical_cast<double>(x);\n}\n\n\n//-----------------------------------------------------------------------------\nbool ConvertToBool(const std::string& x)\n{\n  if (\"true\" == x || \"True\" == x)\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n\n//-----------------------------------------------------------------------------\ndouble CalculateVarianceFromFWHM(double fwhm)\n{\n  // http://mathworld.wolfram.com/GaussianFunction.html\n  double variance = ((fwhm * fwhm) / (8.0 * log(2.0)));\n  return variance;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble CalculateStdDevFromFWHM(double fwhm)\n{\n  // http://mathworld.wolfram.com/GaussianFunction.html\n  double stdDev = fwhm / (2.0 * sqrt(2.0 * log(2.0)));\n  return stdDev;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble ConvertFirstVoxelCoordinateToMiddleOfImageCoordinate(\n  double millimetreCoordinateOfFirstVoxel,\n  int numberOfVoxelsInThatAxis,\n  double voxelSpacingInThatAxis)\n{\n  return (static_cast<double>(numberOfVoxelsInThatAxis - 1)\n      * voxelSpacingInThatAxis / 2.0)\n    + millimetreCoordinateOfFirstVoxel;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble ConvertMiddleOfImageCoordinateToFirstVoxelCoordinate(\n    double millimetreCoordinateOfMiddleVoxel,\n    int numberOfVoxelsInThatAxis,\n    double voxelSpacingInThatAxis)\n{\n  return (static_cast<double>(numberOfVoxelsInThatAxis - 1)\n      * voxelSpacingInThatAxis / -2.0)\n    + millimetreCoordinateOfMiddleVoxel;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble fixRangeTo1(double d)\n{\n  return std::min(std::max(d, -1.0), 1.0);\n  \n}\n\n\n//-----------------------------------------------------------------------------\nint Round(double d)\n{\n  return boost::math::iround<double>(d);\n}\n\n\n//-----------------------------------------------------------------------------\ndouble Round(double d, int numberDecimalPlaces)\n{\n  double f = pow((double)10, numberDecimalPlaces);\n  return ((double)Round(d*f))/f;\n}\n\n\n//-----------------------------------------------------------------------------\nstd::string GetLastNCharacters(std::string s, int n)\n{\n  int length = s.length();\n  if (n >= length)\n  {\n    return s;\n  }\n  else\n  {\n    int start = length - n;\n\n    if (start < 0)\n    {\n      start = 0;\n    }\n\n    return s.substr(start, n);\n  }\n}\n\n} // end namespace\n", "meta": {"hexsha": "9575773ebfc8b837b2a6af81637541a93541d708", "size": 4806, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Libraries/Common/niftkConversionUtils.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "Libraries/Common/niftkConversionUtils.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Libraries/Common/niftkConversionUtils.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 24.6461538462, "max_line_length": 79, "alphanum_fraction": 0.4598418643, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.040845719120782935, "lm_q1q2_score": 0.020103778346233406}}
{"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#define _CRT_SECURE_NO_DEPRECATE\n\n// Standard Headers\n#include <iostream> // For endl, and cout inside exception handlers\n#include <iomanip>\n#include <fstream>\n\n// C Headers\n#include <cmath>   // for maths functions\n#include <cassert> // For assertion\n#include <ctime>   // For getting the current time\n\n// Boost headers for boost functions we are using\n#include <boost/thread/thread.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/bind.hpp>\n\n// Include our local copy to src, as foreach is not a standard yet\n#include \"boost/foreach.hpp\"\n\n#include \"errors.h\"\n#include \"nslobject.h\"\n#include \"nslobjectfactory.h\"\n#include \"container.h\"\n#include \"electromagnetics.h\"\n#include \"particle.h\"\n#include \"edmexperiment.h\"\n#include \"physics.h\"\n#include \"datasets.h\"\n#include \"tools.h\"\n#include \"reporters.h\"\n#include \"random.h\"\n#include \"neutronphysics.h\"\n#include \"solver.h\"\n\nusing std::runtime_error;\nusing std::endl;\nusing std::ios;\nusing std::cout;\nusing std::ofstream;\n\nusing nsl::rand_uniform;\n\n\ndataset sampledBz;\n\n\n\nedmexperiment::edmexperiment()\n{\n\t\n\tparticlecount = 0;\n\t//reportercount = 0;\n\tparticlebox = 0;\n\tmagfield = 0;\n\telecfield = 0;\n\t\n\tvariation.parameter = \"\";\n\tvariation.value = 0.;\n\tvariation.runs = 0;\n\tvariation.varying = false;\n\t\n\tgravity = false;\n\t\n\tphase_steps = 0;\n//\tsteptime = 0.0;\n\tbounces = 0;\n\tlifetime = 0.0;\n\tcollision_offset = 0.;\t\n\t//initvals();\n\t\n\t\n\tobjecttype = \"edmexperiment\";\n\ttypes.push_back(objecttype);\n}\n\nvoid edmexperiment::setvariation( std::string parameter, long double minval, long double maxval, int maxruns, nslobject *varyobject )\n//void edmexperiment::setvariation( std::string parameter, long double thisrunvalue, int maxruns )\n{\n\tif (variation.varying)\n\t\tthrow runtime_error(\"Trying to set variation in edmexperiment object twice\");\n\t\n\tvariation.parameter = parameter;\n//\tvariation.value = thisrunvalue;\n\tvariation.runs = maxruns;\n\tvariation.maxval = maxval;\n\tvariation.minval = minval;\n\tvariation.varyobject = varyobject;\n\t\n\tvariation.varying = true;\n}\n\nbool edmexperiment::prepareobject()\n{\n\t//Iterator\n\tstd::vector<nslobject*>::iterator sublist;\n\n\t// Check we only have the right number of containers\n\tif (countchildren(\"container\") != 1)\n\t\tthrow runtime_error(\"Container number other than one specified\");\n\t//particle = findbytype(\"container\", 0);\n\t\n\t// Find and add the container object\n\t//for (sublist = subobjects.begin(); sublist != subobjects.end(); sublist++)\n\tBOOST_FOREACH( nslobject *sublist, subobjects )\n\t{\n\t\tif (sublist->isoftype(\"container\"))\n\t\t\tparticlebox = (container*)sublist;\n\t}\n\n\t// And that we have at least one particle\n\tif ((particlecount = countchildren(\"particle\")) < 1)\n\t\tthrow runtime_error(\"No particles specified under edmexperiment object\");\n\t// Add the particles to the list\n\t//for (sublist = subobjects.begin(); sublist != subobjects.end(); sublist++)\n\tBOOST_FOREACH( nslobject *subobject, subobjects )\n\t{\n\t\tif (subobject->isoftype(\"particle\"))\n//\t\t\tparticles[particlecount++] = (particle*)sublist;\n\t\t\tparticles.push_back((particle*)subobject);\n\t}\n\t\n\t// Now collect the reporters together in their piles\n\tBOOST_FOREACH( nslobject *subobject, subobjects )\n\t{\n\t\tif (subobject->isoftype(\"reporter\"))\n\t\t{\n\t\t\tswitch (((reporter*)subobject)->when()) {\n\t\t\t\tcase reporter::rfreq_run:\n\t\t\t\t\treport_run.push_back((reporter*)subobject);\n\t\t\t\t\tbreak;\n\t\t\t\tcase reporter::rfreq_step:\n\t\t\t\t\treport_step.push_back((reporter*)subobject);\n\t\t\t\t\tbreak;\n\t\t\t\tcase reporter::rfreq_bounce:\n\t\t\t\t\treport_bounce.push_back((reporter*)subobject);\n\t\t\t\t\tbreak;\n\t\t\t\tcase reporter::rfreq_none:\n\t\t\t\t\tbreak; // Don't do anything in this case\n\t\t\t\tcase reporter::rfreq_interval:\n\t\t\t\t\treport_interval.push_back((reporter*)subobject);\n\t\t\t\t\tbreak;\n\t\t\t\tcase reporter::rfreq_phase:\n\t\t\t\t\treport_phase.push_back((reporter*)subobject);\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t//reporters[reportercount++] = (reporter*)(*sublist);\n\t\n\t// EM field objects\n\tif (countchildren(\"efield\") != 1)\n\t\tthrow runtime_error(\"efield number other than one specified\");\n\tif (countchildren(\"bfield\") != 1)\n\t\tthrow runtime_error(\"bfield number other than one specified\");\n\t// Find and add the bfield object\n\tfor (sublist = subobjects.begin(); sublist != subobjects.end(); sublist++)\n\t\tif ((*sublist)->isoftype(\"bfield\"))\n\t\t\tmagfield = (bfield*)(*sublist);\n\t// Find and add the efield object\n\tfor (sublist = subobjects.begin(); sublist != subobjects.end(); sublist++)\n\t\tif ((*sublist)->isoftype(\"efield\"))\n\t\t\telecfield = (efield*)(*sublist);\n\n\t// Find and grab the solver object!\n\tif (countchildren(\"solver\") != 1)\n\t\tthrow runtime_error(\"Could not find one solver!\");\n\tthesolver = (solver*)findbytype(\"solver\", 0);\n\tif (!thesolver)\n\t\tthrow runtime_error(\"Could not find solver object!\");\n\t\n\t\n\t// Grab the steptime from the property set\n\t//if (isset(\"steptime\"))\n\t\n\t// Log the start time of this simulation run\n\ttime_t rawtime;\n\ttm * timeinfo;\n\ttime ( &rawtime );\n\ttimeinfo = localtime ( &rawtime );\n\tset(\"runtime\",  asctime(timeinfo));\n\t\n\t// If we are at this point we have the particlebox, particles, bfield and efield objects\n\t// configured\n\n\treturn true;\n}\n\nvoid edmexperiment::readsettings ( void )\n{\n//\tsteptime = getlongdouble(\"steptime\", 3e-4);\n\t\n\tphase_steps = getint(\"phase_steps\", 1);\n\tbounces = getlong(\"bounces\", 1);\n\tlifetime = getlongdouble(\"lifetime\", 0.0);\n\t\n\tbounce_loss_probability = getlongdouble(\"bounce_loss_probability\", -1.0);\n\tif (bounce_loss_probability > 0.)\n\t\tlogger << \"Probability of particle loss at bounce: \" << bounce_loss_probability << endl;\n\t\n\t// If we have set a lifetime, null out the bounces\n\tuselifetime = isset(\"lifetime\");\n\n\tthread_max = getint(\"threads\", 2);\n\t\n\t// If no intervaltime set, then set it to lifetime + 1 second\n\tif (uselifetime)\n\t{\n\t\tif (!isset(\"intervaltime\"))\n\t\t\tintervaltime = lifetime + 1.0;\n\t\telse\n\t\t\tintervaltime = getlongdouble(\"intervaltime\", 0.0);\n\t}\n\t\n\tcollision_offset = getlongdouble(\"collision_compensation_distance\", 0.0);\n\t\n\tif(get(\"gravity\", \"off\") == \"on\")\n\t\tgravity = true;\n\telse\n\t\tgravity = false;\n\t\n\t\n}\n\nbool edmexperiment::runobject()\n{\n\t// Ensure that all of our particles are within the starting volume\n\tBOOST_FOREACH( particle* part, particles) {\n\t\tif (!particlebox->isinside(part->position))\n\t\t\tthrow runtime_error(\"Particle is not starting inside of a container volume\");\n\t}\n\n\t// If we are not runnning a variation, set up an 'empty' one.\n\tif (!variation.varying)\n\t{\n\t\tvariation.minval = 1;\n\t\tvariation.maxval = 1;\n\t\tvariation.runs = 1;\n\t\tvariation.parameter = \"No_variation\";\n\t\tvariation.varying = false;\n\t\tvariation.varyobject = this;\n\t}\n\t\n\t// Inform the user what type of looping we are doing\n\tif (uselifetime)\n\t\tif (intervaltime < lifetime)\n\t\t\tlogger << \"Lifetime-based looping: Intervals of \" << intervaltime << \" for \" << lifetime << \" (seconds)\" << endl;\n\t\telse\n\t\t\tlogger << \"Lifetime-based looping for \" << lifetime << \" seconds\" << endl;\n\telse\n\t\tlogger << \"Using bounce-based looping: For \" << bounces << \" bounces.\" << endl;\n\t\n\t// Tell our reporters to all initialise\n\tBOOST_FOREACH( nslobject *ob, subobjects) {\n\t\tif (ob->isoftype(\"reporter\"))\n\t\t\t((reporter*)(ob))->preparefile(*this);\n\t}\n\t\t\t\n\t////////////////////////////////////////////////////////////////////////////\n\t// Start the simulation loops\n\n\t// Run over each variation of experimental run\n\tfor (int exprun = 0; exprun < variation.runs; exprun++)\n\t{\n\t\tupdate_variationparameters( exprun );\n\t\t\n\t\t// Reset all subobjects (this also resets all particles)\n\t\tthis->reset();\n\t\t\n\t\t// Reset the cumulative EDM each set of phase loops\n\t\tBOOST_FOREACH(particle *part, particles)\n\t\t\tpart->cumulativeedm.reset();\n\n\t\t// Loop over each phase, accumulating an edm\n\t\tfor (int phase_loop = 0; phase_loop < phase_steps; phase_loop++)\n\t\t\trun_phaseloop(phase_loop);\n\t\t\n\t\t// Calculate the Average edm!\n\t\tdataset falseedmav;\n\t\tBOOST_FOREACH(particle *part, particles)\n\t\t\tfalseedmav += part->cumulativeedm;\n\t\t\n\t\t//logger << \"   Sampled Bz: \" << std::setprecision(7) << sampledBz.average()- 1e-6 << \" +- \" << std::setprecision(2) << sampledBz.stdev() << \"(\" << sampledBz.uncert() << \")\" << endl;\n\t\t\n\t\t// Now output the calculated edm values\n\t\tlogger << \"   Calculated False-EDM : \" << std::setprecision(4) << falseedmav.average() << \" +/- \" << falseedmav.uncert() << \" E-26 e.cm\"<< endl;\n\t\t\n\t\t// Now tell all the reporters that are supposed to report every run, to report\n\t\tBOOST_FOREACH( reporter *rep, report_run ) {\n\t\t\trep->report(*this);\n\t\t}\n\t\t\n\t} // Close per value loop\n\t\n\t// Tell all of the reporters to do the file-closing 'final report'\n\tBOOST_FOREACH( nslobject *ob, subobjects) {\n\t\tif (ob->isoftype(\"reporter\"))\n\t\t\t((reporter*)(ob))->closefile(*this);\n\t}\n\t\t\n\treturn false;\n}\n\nvoid edmexperiment::update_variationparameters (int exprun )\n{\n\t// Calculate the value for the variation this loop\n\tlong double varyval = variation.minval + (variation.maxval - variation.minval)*exprun / (variation.runs-1);\n\tlogger << \"\\nOuter Loop \" << exprun+1 << \"/\" << variation.runs << \" of \" << variation.parameter << \": Value = \" << varyval << endl;\n\t// now set it!\n\tvariation.varyobject->set(variation.parameter, str(varyval));\n\tvariation.value = varyval;\n}\n\nvoid edmexperiment::run_phaseloop( int phase_loop )\n{\n\tif (phase_steps > 1)\n\t\tlogger << \"   Phase Averaging Loop \" << phase_loop+1 << \" of \" << phase_steps << endl;\n\t\n\t// Calculate the phase for this loop\n\tlong double phaseavg = phase_loop * (2.0 / phase_steps);\n\t\n\t// Reset the particles, and update their starting phase\n\tBOOST_FOREACH( particle* part, particles ) {\n\t\tpart->set(\"start_spin_phase\", str(phaseavg));\n\t\tpart->reset();\n\t}\n\t\n\t// Prepare the particles (solver-wise) - this means resetting their steptimes\n\t// for a midpointsolver\n\tthesolver->prepareparticles(particles);\n\t\n\t\n\t// Decide how to loop - two choices:\n\t// 1) Bounce for a certain number of bounces\n\t// 2) Start a loop for intervals - this will run all the particles for a specified time,\n\t//    after which they will all have identical running times (so that reports that\n\t//    depend on having an ensemble of equal-time particles can be made)\n\t\n\tbool runningintervals = true; // are we still runnning/planning to run intervals?\n\t\n\t// If we are not doing lifetime based looping, don't even bother with the loop\n\tif (!uselifetime)\n\t{\n\t\trunningintervals = false; // This cancels the loop ahead so it won't happen\n\t\truninterval(0.0); // This runs the interval - it doesn't care about time in this case\n\t}\n\t\n\t// Loop over the time intervals, as long as we have time left.. signified by \n\t// a counter of life!\n\tlong double timeleft = lifetime; //lifetime remaining\n\twhile (runningintervals)\n\t{\n\t\t// Loop through, running the simulation for an intervals length\n\t\t// Firstly, check to see if we have enough time left!\n\t\tif (timeleft < intervaltime)\n\t\t{\n\t\t\t// We have less than one intervals time remaining... run what is left\n\t\t\t// then check the var to quit the loop\n\t\t\truninterval(timeleft);\n\t\t\ttimeleft = 0;\n\t\t\trunningintervals = false;\n\t\t} else {\n\t\t\t// We have more than one interval left, so run one and reduce that from the overall\n\t\t\t// time remaining.\n\t\t\truninterval(intervaltime);\n\t\t\ttimeleft -= intervaltime;\n\t\t}\n\t\t\n\t\t// Call the interval reporters\n\t\tBOOST_FOREACH( reporter *rep, report_interval )\n\t\trep->report(*this);\n\t} // End of running intervals\n\t  // At this point we have run over all time, whether it be from bounce or interval based procedures\n\t\n\t// Calculate an edm for each particle, and accumulate it\n\tBOOST_FOREACH(particle *part, particles) {\n\t\tneutron_physics::edmcalcs(*part, *elecfield);\n\t\tpart->cumulativeedm += part->fake_edm;\n\t\t//\t\t\t\tfalseedmav += part->fake_edm;\n\t\t\n\t\tsampledBz += part->sampleBz.average();\n\t\t\n\t\t// Output the sampled magnetic field for each particle!\n\t\t//logger << \"\\tSampled Field z : \" << std::setprecision(20) << part->sampleBz.average() << endl;\n\t\t//logger << \"\\tSampled Field x,y : \" << std::setprecision(3) << part->sampleBx.average() << \", \" << part->sampleBy.average() << endl;\n\t\t\n\t\t// Group log sampler thing was here\n\t}\n\t\n\t// Call all of the phase reporters\n\tBOOST_FOREACH( reporter *rep, report_phase ) {\n\t\trep->report(*this);\n\t}\n\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n/// Runinterval function\n\n\n// The first of the runinterval functions - we are handed a time and tasked with running\n// the particles for this amount of time (over bounces or whatever).\n// This particular function is now responsible for launching threads which then sort out\n// the tasks themselves.\nvoid edmexperiment::runinterval( long double time )\n{\n\t\n\t// How many threads do we want doing the particles?\n//\tconst int thread_max = 2;\n\t\n\t// Build the storage that all threads will store access to\n\tint partsleft = particles.size();\n\t\n\t// Create the controller for the threads\n\tboost::thread_group threads;\n\t\n\t// Just launch a bunch of threads, and let them sort out the mess. (which particles to do)\n\tfor (int thread_count = 0; thread_count < thread_max; thread_count++)\n\t{\n\t\t// Launch a thread - the function has to be static which is why we pass a this pointer\n\t\tthreads.create_thread( boost::bind(&edmexperiment::runruninterval, this, time, &partsleft) );\n\t}\n\n\t// Sit and wait for all of our little pets to return to us\n\tthreads.join_all();\n\t\n\treturn;\n}\n\n/**************************************************************************************\n* Launching point for a thread to process particles. * * * * * * * * * * * * * * * * \n* Threads are created into this function, where they sort out getting a new particle  *\n* to process, and return once there are no more jobs left to do.\t\t\t\t\t  *\n* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\nvoid edmexperiment::runruninterval ( edmexperiment *thisp, long double intervaltime, int *partsleft )\n{\n\t// Enclose this in an exception block to catch any exceptions... This doesn't otherwise\n\t// seem to happen with threads - Any execution here is going to be in a thread seperate from\n\t// the main one\n\ttry {\n\t\t// Loop infinitely and let threads find out inside whether there is anything left to do\n\t\twhile(1)\n\t\t{\n\t\t\t// Which particle shall we run?\n\t\t\tint partnum = 0;\n\t\t\t\n\t\t\t// Read in the Next particle to process... it is slightly easier to do this\n\t\t\t// backwards, counting down the number of particles left. This definitely has to\n\t\t\t// be mutex locked otherwise we could get multiple threads acting on the same particle\n\t\t\t{\n\t\t\t\t// We want a static local mutex so that all threads passing through here can share it.\n\t\t\t\tstatic boost::mutex readnum_mutex;\n\t\t\t\tboost::mutex::scoped_lock lock(readnum_mutex);\n\t\t\t\t\n\t\t\t\tpartnum = --(*partsleft);\n\t\t\t}\n\t\t\t\n\t\t\t// Have we exhausted all particles? If so, quit this function (and thread).\n\t\t\tif (partnum < 0)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\t// We have generated a particle index number... run it's interval!\n\t\t\tthisp->runinterval(intervaltime, thisp->particles[partnum]);\n\t\t\t\n\t\t\t// Let the user know we are processing\n\t\t\tcout << \".\" << std::flush;\n\t\t\t\n\t\t} //while(1)\n\t\t\n\t\tcout << endl;\n\t\t\n\t// do the exception handling stuff\n\t} catch (runtime_error runt) {\n\t\tcout << \"\\a\\a\\aA runtime error has occured in a seperate thread\";\n\t\tif (runt.what())\n\t\t\tcout << \": \" << runt.what();\n\t\tcout << endl << endl;\n\t\tassert(0); // Kill the application!\n\t} catch (...) {\n\t\tcout << \"\\aAn unrecoverable, unidentified exception occured - terminating program.\" << endl;\n\t\tassert(0); // Kill the application!\n\t}\n\t\n}\n\n// This is the second (and original) runinterval function. Rather than processing threads, this\n// actually does what it's name says - runs a particle for a specified length of time!\nvoid edmexperiment::runinterval ( long double time, particle *part )\n{\n\t// Reset the time counter for this particle\n\tlong double timeleft = time;\n\tunsigned long bounce = 0; // Tracks the bounce count\n\t\n\t// Start a loop over bounces, but keep it infinite, as if we are in lifetime mode then\n\t// we don't care about the bounces and we can decide on this later\n\twhile (part->active)\n\t{\n\t\t// If we are doing bounce-based looping, track that here\n\t\t// Stop if we have reached the maximum number of bounces\n\t\tif (!uselifetime)\n\t\t\tif((unsigned long)bounces == (unsigned long)(bounce++))\n\t\t\t\tbreak;\n\t\t\t\n\t\t// Calculate the next point of intersection\n\t\tintercept\tcollisionpoint = particlebox->cast(part->position, part->velocity_vec);\n\t\t\n\t\t// Complete the collisionpoint variable with stuff not calculated in cast\n\t\tcollisionpoint.normal.scaleto(1.0);\n\t\tcollisionpoint.location = part->position + (part->velocity_vec*collisionpoint.time);\n\t\t// add the adjustments for gravity, if we are using it\n\t\tif (gravity)\n\t\t\tcollisionpoint.location.z -= 0.5*g*collisionpoint.time*collisionpoint.time;\n\t\t\n\t\t// If we get a zero-time collision, make a note of it\n\t\tif (collisionpoint.time == 0.)\n\t\t\tlogger << \"\\t------- Zero time Intersection\" << endl; //\tthrow runtime_error(\"Zero Collision-point time\");\n\t\t\n\t\t/* Now we have three possibilities:\n\t\t\t1)\tWe have enough time for a bounce to complete\n\t\t\t2)\tWe don't, so have to go halfway\n\t\t\t3)\tWe are bounce-looping - in which case (for now) short-circuit the test */\n\t\t\n\t\t// If doing bounce mode, short circuit the test ahead\n\t\tif (!uselifetime)\n\t\t\ttimeleft = collisionpoint.time + 1.;\n\t\t\n\t\t// check to see what the case is\n\t\tif (collisionpoint.time < timeleft)\n\t\t{\n\t\t\t// We have no problem with time here!\n\t\t\t\n\t\t\t\n\t\t\t// Now we know the time to collision, step over it calculating the spin changes as we go\n\t\t\tif (collisionpoint.time > 0.)\n\t\t\t\t//bigstep(*part, collisionpoint.time);\n\t\t\t\tthesolver->step(*part, collisionpoint.time);\n\t\t\t\n\t\t\t// Calculate the reflection - now done by the container being hit\n\t\t\tcollisionpoint.collideobject->reflect(part->velocity_vec, collisionpoint.normal, part->velocity);\n\t\t\t\n\t\t\t// Take away the time for the travel for this bounce from the time left\n\t\t\ttimeleft -= collisionpoint.time;\n\t\t\t\n\t\t\t// Calculate the chance that the particle is 'lost' through this collision\n\t\t\t// This test is okay - because in the event no bounce probability has been defined it\n\t\t\t// defaults to negative - and therefore the random number will never be higher.\n\t\t\t// May, however, want to skip this test if we don't want bounce losses.\n\t\t\tif (rand_uniform() < bounce_loss_probability)\n\t\t\t{\n\t\t\t\tpart->active = false;\n//\t\t\t\tlogger << \"L\" << std::flush;\n\t\t\t}\n\t\t\t\n\t\t\t// Move the particle to the collision point, plus a tiny offset - should eliminate need for fudge\n\t\t\t// whilst having a minimal physical impact (preliminary tests indicate this is usually of order\n\t\t\t// 1e-30 anyway)\n\t\t\t// Note... this automatically accounts for gravity via collisionpoint.location\n\t\t\t\n\t\t\tlong double diff = mod(collisionpoint.location - part->position);\n\t\t\tstatic long double biggest_diff = 0.;\n\t\t\tstatic ofstream stepdev(\"stepsystem_deviation.txt\");\n\t\t\tif (biggest_diff < diff)\n\t\t\t{\n\t\t\t\tstatic boost::mutex output_mutex;\n\t\t\t\tboost::mutex::scoped_lock lock(output_mutex);\n\t\t\n\t\t\t\tbiggest_diff = diff;\n\t\t\t\tstepdev << biggest_diff << endl;\n\t\t\t}\n\t\t\tpart->position = collisionpoint.location + (collisionpoint.normal * collision_offset);\n\t\t\t\n\t\t\t// Add to the particles bounce count\n\t\t\tpart->bounces++;\n\t\t\t\n\t\t\t// See if this was a wall, and if not then reduce the bouncecount.\n\t\t\t// This is for compatability with the old system, which didn't count ceiling bounces as\n\t\t\t// true bounces.\n\t\t\tif (collisionpoint.normal.z < 0.001)\n\t\t\t\t;//logger << \"Wall bounce\" << endl;\n\t\t\telse {\n\t\t\t\t//logger << \"ceil bounce\";\n\t\t\t\t//bounce--;\n\t\t\t}\n\t\t\t\n\t\t\t// Now call the reporters that report each bounce\n\t\t\tBOOST_FOREACH( reporter *repo, report_bounce) {\n\t\t\t\trepo->report(*this);\n\t\t\t}\n\t\t} else {\n\t\t\t// Now process the case where there is not enough time for a full trip across the bottle..\n\t\t\t// .. just do a partial trip\n\t\t\t//bigstep(*part, timeleft);\n\t\t\tthesolver->step(*part, timeleft);\n\t\t\ttimeleft = 0; // probably not needed - but better safe...\n\t\t\t// Duuuuuuh actually quit out of the loop.....\n\t\t\tbreak;\n\t\t}\n\t} //while(active particle) over bounces (and particle activity)\t\n}\n\n\n\n\n/*\n// Performs a large step between successive collisions. Use the E and B fields tied to\n// the edmexperiment object for now\nvoid edmexperiment::bigstep(particle& part, long double time)\n{\n\tlong steps;\n\t\n\t// calculate the Exv effect for the particle- this does not change over a bigstep\n\t// NOTE: if gravity is on, this does change over a bigstep so don't do this here\n\tif (!gravity)\n\t\tpart.updateExv(*elecfield);\n\n\t// Calculate the number of steps we are going to take\n\tsteps = (long)floorl((long double)time / (long double)part.steptime);\n\t\n\t// Now do this many smallsteps - after which we will have one step of time less\n\t// than one step to complete\n\tfor (int step = 0; step < steps; step++)\n\t{\n\t\t// We can safely callthe smallstep with steptime as inside this loop it is \n\t\t// guaranteed to be so\n\t\tsmallstep(part, part.steptime);\n\n\t}\n\n\t// Check we still have a little excess time to step\n\tlong double laststep = (time - (steps*part.steptime));\n\tif (laststep < 0.0)\n\t\tthrow runtime_error(\"Stepping routine stepped over maximum time to impact\");\n\t// Now do the actual final step\n\tsmallstep(part, laststep);\n}\n*/\n\n/*\nvoid edmexperiment::smallstep(particle& part, long double time)\n{\n\tlong double halftime = time / 2.0;\n\t\n\t// Firstly calculate the step midpoint\n\tvector3 midpoint;\n\tmidpoint = part.position + (part.velocity_vec*halftime);\n\n\t// If gravity is turned on, adjust the relevant properties\n\tif (gravity)\n\t{\n\t\t// the midpoint is different...\n\t\tmidpoint.z -= 0.5*g*halftime*halftime;\n\t\t\n\t\t// Update the particles velocity....\n\t\tpart.velocity_vec.z -= g*halftime;\n\t\tpart.velocity = mod(part.velocity_vec);\n\t\t\n\t\t// And the particles Exv effect\n\t\tpart.updateExv(*elecfield);\n\t}\n\t\n\t// Just grab the magnetic field - now we have precalculated the magnetic field\n\t// for the particle already\n\tvector3 B;\n\tmagfield->getfield(B, midpoint);\n\n\n\t// Now apply the new physical properties to the particle\n\t// Move it first\n\tpart.position += part.velocity_vec * time;\n\t\n\t//...and gravity adjustments\n\tif (gravity)\n\t{\n\t\t// Update the position properly\n\t\tpart.position.z -= 0.5*g*time*time;\n\t\t\n\t\t//and finish adjusting the velocity with the other half of the step\n\t\tpart.velocity_vec.z -= g*halftime;\n\t\tpart.velocity = mod(part.velocity_vec);\n\t\t\n\t}\n\t\n\t// Update the particles flytime\n\tpart.flytime += time;\n\t\n\t// Now spin the particle\n\tneutron_physics::spin_calculation(part, B, time);\n\t\n\t// Now (god forbid) call the reporters that report every step\n\tBOOST_FOREACH( reporter *rep, report_step ) {\n\t\trep->report(*this);\n\t}\n}\n\n*/\n\n", "meta": {"hexsha": "ba3ecee39b7c10a6b3c9090abf943be670977f01", "size": 23673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/edmexperiment.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/edmexperiment.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/edmexperiment.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": 32.6975138122, "max_line_length": 184, "alphanum_fraction": 0.6863092975, "num_tokens": 6094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.04468086852351695, "lm_q1q2_score": 0.020079253215956838}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include <speckley/Brick.h>\n#include <speckley/DefaultAssembler3D.h>\n#include <speckley/WaveAssembler3D.h>\n\n#ifdef USE_RIPLEY\n#include <speckley/CrossDomainCoupler.h>\n#endif\n\n#include <escript/index.h>\n#include <escript/FileWriter.h>\n#include <escript/FunctionSpaceFactory.h>\n#include <escript/Random.h>\n\n#include <boost/scoped_array.hpp>\n#include <boost/math/special_functions/fpclassify.hpp> // for isnan\n\n#ifdef ESYS_HAVE_NETCDF\n #ifdef NETCDF4\n  #include <ncVar.h>\n  #include <ncDim.h>\n  #include <escript/NCHelper.h>\n\n #else\n   #include <netcdfcpp.h>\n #endif\n#endif\n\n#ifdef ESYS_HAVE_SILO\n#include <silo.h>\n#ifdef ESYS_MPI\n#include <pmpio.h>\n#endif\n#endif\n\n#include <iomanip>\n#include <limits>\n\nnamespace bm=boost::math;\nusing escript::FileWriter;\nusing std::max;\nusing std::min;\nusing std::vector;\nusing std::string;\n\n#ifdef NETCDF4\nusing namespace netCDF;\n#endif\n\n\nnamespace speckley {\n\ninline int indexOfMax(dim_t a, dim_t b, dim_t c)\n{\n    if (a > b) {\n        if (c > a) {\n            return 2;\n        }\n        return 0;\n    } else if (b > c) {\n        return 1;\n    }\n    return 2;\n}\n\nBrick::Brick(int order, dim_t n0, dim_t n1, dim_t n2, double x0, double y0, double z0,\n             double x1, double y1, double z1, int d0, int d1, int d2,\n             const std::vector<double>& points, const std::vector<int>& tags,\n             const TagMap& tagnamestonums,\n             escript::SubWorld_ptr w) :\n    SpeckleyDomain(3, order, w)\n{\n    if (static_cast<long>(n0 + 1) * static_cast<long>(n1 + 1)\n            * static_cast<long>(n2 + 1) > std::numeric_limits<int>::max())\n        throw SpeckleyException(\"The number of elements has overflowed, this \"\n                \"limit may be raised in future releases.\");\n\n    if (n0 <= 0 || n1 <= 0 || n2 <= 0)\n        throw SpeckleyException(\"Number of elements in each spatial dimension \"\n                \"must be positive\");\n\n    // ignore subdivision parameters for serial run\n    if (m_mpiInfo->size == 1) {\n        d0=1;\n        d1=1;\n        d2=1;\n    }\n    bool warn=false;\n\n    std::vector<int> factors;\n    int ranks = m_mpiInfo->size;\n    dim_t epr[3] = {n0,n1,n2};\n    int d[3] = {d0,d1,d2};\n    if (d0<=0 || d1<=0 || d2<=0) {\n        for (int i = 0; i < 3; i++) {\n            if (d[i] < 1) {\n                d[i] = 1;\n                continue;\n            }\n            epr[i] = -1; // can no longer be max\n            if (ranks % d[i] != 0) {\n                throw SpeckleyException(\"Invalid number of spatial subdivisions\");\n            }\n            ranks /= d[i];\n        }\n        factorise(factors, ranks);\n        if (factors.size() != 0) {\n            warn = true;\n        }\n    }\n    while (factors.size() > 0) {\n        int i = indexOfMax(epr[0],epr[1],epr[2]);\n        int f = factors.back();\n        factors.pop_back();\n        d[i] *= f;\n        epr[i] /= f;\n    }\n    d0 = d[0]; d1 = d[1]; d2 = d[2];\n\n    // ensure number of subdivisions is valid and nodes can be distributed\n    // among number of ranks\n    if (d0*d1*d2 != m_mpiInfo->size)\n        throw SpeckleyException(\"Invalid number of spatial subdivisions\");\n\n    if (warn) {\n        std::cout << \"Warning: Automatic domain subdivision (d0=\" << d0 << \", d1=\"\n            << d1 << \", d2=\" << d2 << \"). This may not be optimal!\" << std::endl;\n    }\n\n    double l0 = x1-x0;\n    double l1 = y1-y0;\n    double l2 = z1-z0;\n    m_dx[0] = l0/n0;\n    m_dx[1] = l1/n1;\n    m_dx[2] = l2/n2;\n\n    if (n0 % d0 > 0) {\n        n0 += d0 - (n0 % d0);\n        l0 = m_dx[0]*n0;\n        std::cout << \"Warning: Adjusted number of elements and length. N0=\"\n            << n0 << \", l0=\" << l0 << std::endl;\n    }\n    if (n1 % d1 > 0) {\n        n1 += d1 - (n1 % d1);\n        l1 = m_dx[1]*n1;\n        std::cout << \"Warning: Adjusted number of elements and length. N1=\"\n            << n1 << \", l1=\" << l1 << std::endl;\n    }\n    if (n2 % d2 > 0) {\n        n2 += d2 - (n2 % d2);\n        l2 = m_dx[2]*n2;\n        std::cout << \"Warning: Adjusted number of elements and length. N2=\"\n            << n2 << \", l2=\" << l2 << std::endl;\n    }\n\n    if (n0/d0 < 1 || n1/d1 < 1 || n2/d2 < 1)\n        throw SpeckleyException(\"Too few elements for the number of ranks\");\n\n    m_gNE[0] = n0;\n    m_gNE[1] = n1;\n    m_gNE[2] = n2;\n    m_origin[0] = x0;\n    m_origin[1] = y0;\n    m_origin[2] = z0;\n    m_length[0] = l0;\n    m_length[1] = l1;\n    m_length[2] = l2;\n    m_NX[0] = d0;\n    m_NX[1] = d1;\n    m_NX[2] = d2;\n\n    // local number of elements (including overlap)\n    m_NE[0] = n0 / d0;\n    m_NE[1] = n1 / d1;\n    m_NE[2] = n2 / d2;\n\n    // local number of nodes\n    m_NN[0] = m_NE[0]*m_order+1;\n    m_NN[1] = m_NE[1]*m_order+1;\n    m_NN[2] = m_NE[2]*m_order+1;\n\n    // bottom-left-front node is at (offset0,offset1,offset2) in global mesh\n    m_offset[0] = n0/d0*(m_mpiInfo->rank%d0);\n    m_offset[1] = n1/d1*(m_mpiInfo->rank%(d0*d1)/d0);\n    m_offset[2] = n2/d2*(m_mpiInfo->rank/(d0*d1));\n\n    populateSampleIds();\n\n    for (TagMap::const_iterator i = tagnamestonums.begin();\n            i != tagnamestonums.end(); i++) {\n        setTagMap(i->first, i->second);\n    }\n    addPoints(points, tags);\n\n#ifdef ESYS_MPI\n    setCornerNeighbours();\n#endif\n\n#ifdef USE_RIPLEY\n    coupler = NULL;\n#endif\n}\n\n\nBrick::~Brick()\n{\n#ifdef USE_RIPLEY\n    if (coupler != NULL)\n        delete coupler;\n#endif\n}\n\nstd::string Brick::getDescription() const\n{\n    return \"speckley::Brick\";\n}\n\nbool Brick::operator==(const escript::AbstractDomain& other) const\n{\n    const Brick* o=dynamic_cast<const Brick*>(&other);\n    if (o) {\n        return (SpeckleyDomain::operator==(other) &&\n                m_gNE[0]==o->m_gNE[0] && m_gNE[1]==o->m_gNE[1] && m_gNE[2]==o->m_gNE[2]\n                && m_origin[0]==o->m_origin[0] && m_origin[1]==o->m_origin[1] && m_origin[2]==o->m_origin[2]\n                && m_length[0]==o->m_length[0] && m_length[1]==o->m_length[1] && m_length[2]==o->m_length[2]\n                && m_NX[0]==o->m_NX[0] && m_NX[1]==o->m_NX[1] && m_NX[2]==o->m_NX[2]);\n    }\n\n    return false;\n}\n\n#ifdef NETCDF4\n\n\nvoid Brick::readNcGrid(escript::Data& out, std::string filename, std::string varname,\n            const ReaderParameters& params) const\n{\n#ifdef ESYS_HAVE_NETCDF\n    // check destination function space\n    dim_t myN0, myN1, myN2;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NN[0];\n        myN1 = m_NN[1];\n        myN2 = m_NN[2];\n    } else if (out.getFunctionSpace().getTypeCode() == Elements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n        myN2 = m_NE[2];\n    } else\n        throw SpeckleyException(\"readNcGrid(): invalid function space for output data object\");\n\n    if (params.first.size() != 3)\n        throw SpeckleyException(\"readNcGrid(): argument 'first' must have 3 entries\");\n\n    if (params.numValues.size() != 3)\n        throw SpeckleyException(\"readNcGrid(): argument 'numValues' must have 3 entries\");\n\n    if (params.multiplier.size() != 3)\n        throw SpeckleyException(\"readNcGrid(): argument 'multiplier' must have 3 entries\");\n    for (size_t i=0; i<params.multiplier.size(); i++)\n        if (params.multiplier[i]<1)\n            throw SpeckleyException(\"readNcGrid(): all multipliers must be positive\");\n\n    // check file existence and size\n    NcFile f;\n    if (!escript::openNcFile(f, filename))\n    {\n        throw SpeckleyException(\"readNcGrid(): cannot open file\");\n    }           \n    NcVar var = f.getVar(varname.c_str());\n    if (var.isNull())\n        throw SpeckleyException(\"readNcGrid(): invalid variable name\");\n\n    // TODO: rank>0 data support\n    const int numComp = out.getDataPointSize();\n    if (numComp > 1)\n        throw SpeckleyException(\"readNcGrid(): only scalar data supported\");\n\n    const int dims = var.getDimCount();\n    vector<long> edges(dims);\n    std::vector< NcDim > vard=var.getDims();\n    for (size_t i=0;i<vard.size();++i)\n    {\n        edges[i]=vard[i].getSize();\n    }    \n\n    // is this a slice of the data object (dims!=3)?\n    // note the expected ordering of edges (as in numpy: z,y,x)\n    if ( (dims==3 && (params.numValues[2] > edges[0] ||\n                      params.numValues[1] > edges[1] ||\n                      params.numValues[0] > edges[2]))\n            || (dims==2 && params.numValues[2]>1)\n            || (dims==1 && (params.numValues[2]>1 || params.numValues[1]>1)) ) {\n        throw SpeckleyException(\"readNcGrid(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+params.numValues[0]*params.multiplier[0] <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+params.numValues[1]*params.multiplier[1] <= m_offset[1] ||\n            params.first[2] >= m_offset[2]+myN2 ||\n            params.first[2]+params.numValues[2]*params.multiplier[2] <= m_offset[2]) {\n        return;\n    }\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    const dim_t first2 = max(dim_t(0), params.first[2]-m_offset[2]);\n    // indices to first value in file (not accounting for reverse yet)\n    dim_t idx0 = max(dim_t(0), m_offset[0]-params.first[0]);\n    dim_t idx1 = max(dim_t(0), m_offset[1]-params.first[1]);\n    dim_t idx2 = max(dim_t(0), m_offset[2]-params.first[2]);\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n    const dim_t num2 = min(params.numValues[2]-idx2, myN2-first2);\n\n    // make sure we read the right block if going backwards through file\n    if (params.reverse[0])\n        idx0 = edges[dims-1]-num0-idx0;\n    if (dims>1 && params.reverse[1])\n        idx1 = edges[dims-2]-num1-idx1;\n    if (dims>2 && params.reverse[2])\n        idx2 = edges[dims-3]-num2-idx2;\n\n    vector<double> values(num0*num1*num2);\n    vector<size_t> startindex;\n    vector<size_t> counts;\n    if (dims==3) {\n        //var->set_cur(idx2, idx1, idx0);             // from old API\n        startindex.push_back(idx2);\n        startindex.push_back(idx1);\n        startindex.push_back(idx0);\n        counts.push_back(num2);\n        counts.push_back(num1);\n        counts.push_back(num0);\n        var.getVar(startindex, counts, &values[0]);   \n    } else if (dims==2) {\n        // var->set_cur(idx1, idx0);                // from old API\n        startindex.push_back(idx1);\n        startindex.push_back(idx0);\n        counts.push_back(num1);\n        counts.push_back(num0);\n        var.getVar(startindex, counts, &values[0]);   \n    } else {\n        //var->set_cur(idx0);\n        //var->get(&values[0], num0);\n        startindex.push_back(idx0);\n        counts.push_back(num0);\n        var.getVar(startindex, counts, &values[0]);   \n    }    \n\n    const int dpp = out.getNumDataPointsPerSample();\n    out.requireWrite();\n\n    // helpers for reversing\n    const dim_t x0 = (params.reverse[0] ? num0-1 : 0);\n    const int x_mult = (params.reverse[0] ? -1 : 1);\n    const dim_t y0 = (params.reverse[1] ? num1-1 : 0);\n    const int y_mult = (params.reverse[1] ? -1 : 1);\n    const dim_t z0 = (params.reverse[2] ? num2-1 : 0);\n    const int z_mult = (params.reverse[2] ? -1 : 1);\n\n    for (index_t z=0; z<num2; z++) {\n        for (index_t y=0; y<num1; y++) {\n#pragma omp parallel for\n            for (index_t x=0; x<num0; x++) {\n                const dim_t baseIndex = first0+x*params.multiplier[0]\n                                     +(first1+y*params.multiplier[1])*myN0\n                                     +(first2+z*params.multiplier[2])*myN0*myN1;\n                const dim_t srcIndex=(z0+z_mult*z)*num1*num0\n                                  +(y0+y_mult*y)*num0\n                                  +(x0+x_mult*x);\n                if (!bm::isnan(values[srcIndex])) {\n                    for (index_t m2=0; m2<params.multiplier[2]; m2++) {\n                        for (index_t m1=0; m1<params.multiplier[1]; m1++) {\n                            for (index_t m0=0; m0<params.multiplier[0]; m0++) {\n                                const dim_t dataIndex = baseIndex+m0\n                                               +m1*myN0\n                                               +m2*myN0*myN1;\n                                double* dest = out.getSampleDataRW(dataIndex);\n                                for (index_t q=0; q<dpp; q++) {\n                                    *dest++ = values[srcIndex];\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n#else\n    throw SpeckleyException(\"readNcGrid(): not compiled with netCDF support\");\n#endif\n}\n#else\n\nvoid Brick::readNcGrid(escript::Data& out, std::string filename, std::string varname,\n            const ReaderParameters& params) const\n{\n#ifdef ESYS_HAVE_NETCDF\n    // check destination function space\n    dim_t myN0, myN1, myN2;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NN[0];\n        myN1 = m_NN[1];\n        myN2 = m_NN[2];\n    } else if (out.getFunctionSpace().getTypeCode() == Elements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n        myN2 = m_NE[2];\n    } else\n        throw SpeckleyException(\"readNcGrid(): invalid function space for output data object\");\n\n    if (params.first.size() != 3)\n        throw SpeckleyException(\"readNcGrid(): argument 'first' must have 3 entries\");\n\n    if (params.numValues.size() != 3)\n        throw SpeckleyException(\"readNcGrid(): argument 'numValues' must have 3 entries\");\n\n    if (params.multiplier.size() != 3)\n        throw SpeckleyException(\"readNcGrid(): argument 'multiplier' must have 3 entries\");\n    for (size_t i=0; i<params.multiplier.size(); i++)\n        if (params.multiplier[i]<1)\n            throw SpeckleyException(\"readNcGrid(): all multipliers must be positive\");\n\n    // check file existence and size\n    NcFile f(filename.c_str(), NcFile::ReadOnly);\n    if (!f.is_valid())\n        throw SpeckleyException(\"readNcGrid(): cannot open file\");\n\n    NcVar* var = f.get_var(varname.c_str());\n    if (!var)\n        throw SpeckleyException(\"readNcGrid(): invalid variable name\");\n\n    // TODO: rank>0 data support\n    const int numComp = out.getDataPointSize();\n    if (numComp > 1)\n        throw SpeckleyException(\"readNcGrid(): only scalar data supported\");\n\n    const int dims = var->num_dims();\n    boost::scoped_array<long> edges(var->edges());\n\n    // is this a slice of the data object (dims!=3)?\n    // note the expected ordering of edges (as in numpy: z,y,x)\n    if ( (dims==3 && (params.numValues[2] > edges[0] ||\n                      params.numValues[1] > edges[1] ||\n                      params.numValues[0] > edges[2]))\n            || (dims==2 && params.numValues[2]>1)\n            || (dims==1 && (params.numValues[2]>1 || params.numValues[1]>1)) ) {\n        throw SpeckleyException(\"readNcGrid(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+params.numValues[0]*params.multiplier[0] <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+params.numValues[1]*params.multiplier[1] <= m_offset[1] ||\n            params.first[2] >= m_offset[2]+myN2 ||\n            params.first[2]+params.numValues[2]*params.multiplier[2] <= m_offset[2]) {\n        return;\n    }\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    const dim_t first2 = max(dim_t(0), params.first[2]-m_offset[2]);\n    // indices to first value in file (not accounting for reverse yet)\n    dim_t idx0 = max(dim_t(0), m_offset[0]-params.first[0]);\n    dim_t idx1 = max(dim_t(0), m_offset[1]-params.first[1]);\n    dim_t idx2 = max(dim_t(0), m_offset[2]-params.first[2]);\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n    const dim_t num2 = min(params.numValues[2]-idx2, myN2-first2);\n\n    // make sure we read the right block if going backwards through file\n    if (params.reverse[0])\n        idx0 = edges[dims-1]-num0-idx0;\n    if (dims>1 && params.reverse[1])\n        idx1 = edges[dims-2]-num1-idx1;\n    if (dims>2 && params.reverse[2])\n        idx2 = edges[dims-3]-num2-idx2;\n\n\n    vector<double> values(num0*num1*num2);\n    if (dims==3) {\n        var->set_cur(idx2, idx1, idx0);\n        var->get(&values[0], num2, num1, num0);\n    } else if (dims==2) {\n        var->set_cur(idx1, idx0);\n        var->get(&values[0], num1, num0);\n    } else {\n        var->set_cur(idx0);\n        var->get(&values[0], num0);\n    }\n\n    const int dpp = out.getNumDataPointsPerSample();\n    out.requireWrite();\n\n    // helpers for reversing\n    const dim_t x0 = (params.reverse[0] ? num0-1 : 0);\n    const int x_mult = (params.reverse[0] ? -1 : 1);\n    const dim_t y0 = (params.reverse[1] ? num1-1 : 0);\n    const int y_mult = (params.reverse[1] ? -1 : 1);\n    const dim_t z0 = (params.reverse[2] ? num2-1 : 0);\n    const int z_mult = (params.reverse[2] ? -1 : 1);\n\n    for (index_t z=0; z<num2; z++) {\n        for (index_t y=0; y<num1; y++) {\n#pragma omp parallel for\n            for (index_t x=0; x<num0; x++) {\n                const dim_t baseIndex = first0+x*params.multiplier[0]\n                                     +(first1+y*params.multiplier[1])*myN0\n                                     +(first2+z*params.multiplier[2])*myN0*myN1;\n                const dim_t srcIndex=(z0+z_mult*z)*num1*num0\n                                  +(y0+y_mult*y)*num0\n                                  +(x0+x_mult*x);\n                if (!bm::isnan(values[srcIndex])) {\n                    for (index_t m2=0; m2<params.multiplier[2]; m2++) {\n                        for (index_t m1=0; m1<params.multiplier[1]; m1++) {\n                            for (index_t m0=0; m0<params.multiplier[0]; m0++) {\n                                const dim_t dataIndex = baseIndex+m0\n                                               +m1*myN0\n                                               +m2*myN0*myN1;\n                                double* dest = out.getSampleDataRW(dataIndex);\n                                for (index_t q=0; q<dpp; q++) {\n                                    *dest++ = values[srcIndex];\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n#else\n    throw SpeckleyException(\"readNcGrid(): not compiled with netCDF support\");\n#endif\n}\n\n#endif\n\nvoid Brick::readBinaryGridFromZipped(escript::Data& out, std::string filename,\n                           const ReaderParameters& params) const\n{\n#ifdef ESYS_HAVE_BOOST_IO\n    // the mapping is not universally correct but should work on our\n    // supported platforms\n    switch (params.dataType) {\n        case DATATYPE_INT32:\n            readBinaryGridZippedImpl<int>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT32:\n            readBinaryGridZippedImpl<float>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT64:\n            readBinaryGridZippedImpl<double>(out, filename, params);\n            break;\n        default:\n            throw SpeckleyException(\"readBinaryGridZipped(): invalid or unsupported datatype\");\n    }\n#else\n    throw SpeckleyException(\"readBinaryGridZipped(): not compiled with zip support\");\n#endif\n}\n\nvoid Brick::readBinaryGrid(escript::Data& out, std::string filename,\n                           const ReaderParameters& params) const\n{\n    // the mapping is not universally correct but should work on our\n    // supported platforms\n    switch (params.dataType) {\n        case DATATYPE_INT32:\n            readBinaryGridImpl<int>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT32:\n            readBinaryGridImpl<float>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT64:\n            readBinaryGridImpl<double>(out, filename, params);\n            break;\n        default:\n            throw SpeckleyException(\"readBinaryGrid(): invalid or unsupported datatype\");\n    }\n}\n\ntemplate<typename ValueType>\nvoid Brick::readBinaryGridImpl(escript::Data& out, const std::string& filename,\n                               const ReaderParameters& params) const\n{\n    // check destination function space\n    dim_t myN0, myN1, myN2;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NE[0] + 1;\n        myN1 = m_NE[1] + 1;\n        myN2 = m_NE[2] + 1;\n//    } else if (out.getFunctionSpace().getTypeCode() == Elements) {\n//        myN0 = m_NE[0];\n//        myN1 = m_NE[1];\n//        myN2 = m_NE[2];\n    } else\n        throw SpeckleyException(\"readBinaryGrid(): invalid function space for output data object\");\n\n    if (params.first.size() != 3)\n        throw SpeckleyException(\"readBinaryGrid(): argument 'first' must have 3 entries\");\n\n    if (params.numValues.size() != 3)\n        throw SpeckleyException(\"readBinaryGrid(): argument 'numValues' must have 3 entries\");\n\n    if (params.multiplier.size() != 3)\n        throw SpeckleyException(\"readBinaryGrid(): argument 'multiplier' must have 3 entries\");\n    for (size_t i=0; i<params.multiplier.size(); i++)\n        if (params.multiplier[i]<1)\n            throw SpeckleyException(\"readBinaryGrid(): all multipliers must be positive\");\n    if (params.reverse[0] != 0 || params.reverse[1] != 0)\n        throw SpeckleyException(\"readBinaryGrid(): reversing only supported in Z-direction currently\");\n\n    // check file existence and size\n    std::ifstream f(filename.c_str(), std::ifstream::binary);\n    if (f.fail()) {\n        throw SpeckleyException(\"readBinaryGrid(): cannot open file \" + filename);\n    }\n    f.seekg(0, std::ios::end);\n    const int numComp = out.getDataPointSize();\n    const dim_t filesize = f.tellg();\n    const dim_t reqsize = params.numValues[0]*params.numValues[1]*params.numValues[2]*numComp*sizeof(ValueType);\n    if (filesize < reqsize) {\n        f.close();\n        throw SpeckleyException(\"readBinaryGrid(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+params.numValues[0]*params.multiplier[0] <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+params.numValues[1]*params.multiplier[1] <= m_offset[1] ||\n            params.first[2] >= m_offset[2]+myN2 ||\n            params.first[2]+params.numValues[2]*params.multiplier[2] <= m_offset[2]) {\n        f.close();\n        return;\n    }\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    const dim_t first2 = max(dim_t(0), params.first[2]-m_offset[2]);\n    // indices to first value in file (not accounting for reverse yet)\n    dim_t idx0 = max(dim_t(0), (m_offset[0]/params.multiplier[0])-params.first[0]);\n    dim_t idx1 = max(dim_t(0), (m_offset[1]/params.multiplier[1])-params.first[1]);\n    dim_t idx2 = max(dim_t(0), (m_offset[2]/params.multiplier[2])-params.first[2]);\n    // if restX > 0 the first value in the respective dimension has been\n    // written restX times already in a previous rank so this rank only\n    // contributes (multiplier-rank) copies of that value\n    const dim_t rest0 = m_offset[0]%params.multiplier[0];\n    const dim_t rest1 = m_offset[1]%params.multiplier[1];\n    const dim_t rest2 = m_offset[2]%params.multiplier[2];\n\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n    const dim_t num2 = min(params.numValues[2]-idx2, myN2-first2);\n\n    // make sure we read the right block if going backwards through file\n    if (params.reverse[2])\n        idx2 = params.numValues[2]-idx2-1;\n\n    // helpers for reversing\n    const int z_mult = (params.reverse[2] ? -1 : 1);\n\n    out.requireWrite();\n    vector<ValueType> values(num0*numComp);\n    const dim_t dpp = out.getNumDataPointsPerSample();\n\n    for (dim_t z=0; z<num2; z++) {\n        const dim_t m2limit = (z==0 ? params.multiplier[2]-rest2 : params.multiplier[2]);\n        dim_t dataZbase = first2 + z*params.multiplier[2];\n        if (z>0)\n            dataZbase -= rest2;\n\n        for (dim_t y=0; y<num1; y++) {\n            const dim_t fileofs = numComp*(idx0 +\n                                (idx1+y)*params.numValues[0] +\n                                (idx2+z_mult*z)*params.numValues[0]*params.numValues[1]);\n            f.seekg(fileofs*sizeof(ValueType));\n            f.read((char*)&values[0], num0*numComp*sizeof(ValueType));\n            const dim_t m1limit = (y==0 ? params.multiplier[1]-rest1 : params.multiplier[1]);\n            dim_t dataYbase = first1 + y*params.multiplier[1];\n            if (y>0)\n                dataYbase -= rest1;\n\n            for (dim_t x=0; x<num0; x++) {\n                const dim_t m0limit = (x==0 ? params.multiplier[0]-rest0 : params.multiplier[0]);\n                dim_t dataXbase = first0 + x*params.multiplier[0];\n                if (x>0)\n                    dataXbase -= rest0;\n                // write a block of mult0 x mult1 x mult2 identical values into\n                // Data object\n                for (dim_t m2=0; m2 < m2limit; m2++) {\n                    const dim_t dataZ = dataZbase + m2;\n                    if (dataZ >= myN2)\n                        break;\n                    for (dim_t m1=0; m1 < m1limit; m1++) {\n                        const dim_t dataY = dataYbase + m1;\n                        if (dataY >= myN1)\n                            break;\n                        for (dim_t m0=0; m0 < m0limit; m0++) {\n                            const dim_t dataX = dataXbase + m0;\n                            if (dataX >= myN0)\n                                break;\n                            const dim_t dataIndex = INDEX3(dataX, dataY, dataZ, m_NN[0],m_NN[1]);\n                            double* dest = out.getSampleDataRW(dataIndex*m_order);\n                            for (int c=0; c<numComp; c++) {\n                                ValueType val = values[x*numComp+c];\n\n                                if (params.byteOrder != BYTEORDER_NATIVE) {\n                                    char* cval = reinterpret_cast<char*>(&val);\n                                    // this will alter val!!\n                                    if (sizeof(ValueType)>4) {\n                                        byte_swap64(cval);\n                                    } else {\n                                        byte_swap32(cval);\n                                    }\n                                }\n                                if (!bm::isnan(val)) {\n                                    for (int q=0; q<dpp; q++) {\n                                        *dest++ = static_cast<double>(val);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    f.close();\n\n    interpolateFromCorners(out);\n}\n\n#ifdef ESYS_HAVE_BOOST_IO\ntemplate<typename ValueType>\nvoid Brick::readBinaryGridZippedImpl(escript::Data& out, const string& filename,\n                               const ReaderParameters& params) const\n{\n    // check destination function space\n    dim_t myN0, myN1, myN2;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NE[0] + 1;\n        myN1 = m_NE[1] + 1;\n        myN2 = m_NE[2] + 1;\n//    } else if (out.getFunctionSpace().getTypeCode() == Elements) {\n//        myN0 = m_NE[0];\n//        myN1 = m_NE[1];\n//        myN2 = m_NE[2];\n    } else\n        throw SpeckleyException(\"readBinaryGridFromZipped(): invalid function space for output data object\");\n\n    if (params.first.size() != 3)\n        throw SpeckleyException(\"readBinaryGridFromZipped(): argument 'first' must have 3 entries\");\n\n    if (params.numValues.size() != 3)\n        throw SpeckleyException(\"readBinaryGridFromZipped(): argument 'numValues' must have 3 entries\");\n\n    if (params.multiplier.size() != 3)\n        throw SpeckleyException(\"readBinaryGridFromZipped(): argument 'multiplier' must have 3 entries\");\n    for (size_t i=0; i<params.multiplier.size(); i++)\n        if (params.multiplier[i]<1)\n            throw SpeckleyException(\"readBinaryGridFromZipped(): all multipliers must be positive\");\n\n    // check file existence and size\n    std::ifstream f(filename.c_str(), std::ifstream::binary);\n    if (f.fail()) {\n        throw SpeckleyException(\"readBinaryGridFromZipped(): cannot open file \" + filename);\n    }\n    f.seekg(0, std::ios::end);\n    const int numComp = out.getDataPointSize();\n    dim_t filesize = f.tellg();\n    f.seekg(0, std::ios::beg);\n    std::vector<char> compressed(filesize);\n    f.read((char*)&compressed[0], filesize);\n    f.close();\n    std::vector<char> decompressed = unzip(compressed);\n    filesize = decompressed.size();\n    const dim_t reqsize = params.numValues[0]*params.numValues[1]*params.numValues[2]*numComp*sizeof(ValueType);\n    if (filesize < reqsize) {\n        throw SpeckleyException(\"readBinaryGridFromZipped(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+params.numValues[0]*params.multiplier[0] <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+params.numValues[1]*params.multiplier[1] <= m_offset[1] ||\n            params.first[2] >= m_offset[2]+myN2 ||\n            params.first[2]+params.numValues[2]*params.multiplier[2] <= m_offset[2]) {\n        return;\n    }\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    const dim_t first2 = max(dim_t(0), params.first[2]-m_offset[2]);\n    // indices to first value in file (not accounting for reverse yet)\n    dim_t idx0 = max(dim_t(0), (m_offset[0]/params.multiplier[0])-params.first[0]);\n    dim_t idx1 = max(dim_t(0), (m_offset[1]/params.multiplier[1])-params.first[1]);\n    dim_t idx2 = max(dim_t(0), (m_offset[2]/params.multiplier[2])-params.first[2]);\n    // if restX > 0 the first value in the respective dimension has been\n    // written restX times already in a previous rank so this rank only\n    // contributes (multiplier-rank) copies of that value\n    const dim_t rest0 = m_offset[0]%params.multiplier[0];\n    const dim_t rest1 = m_offset[1]%params.multiplier[1];\n    const dim_t rest2 = m_offset[2]%params.multiplier[2];\n\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n    const dim_t num2 = min(params.numValues[2]-idx2, myN2-first2);\n\n    // make sure we read the right block if going backwards through file\n    if (params.reverse[2])\n        idx2 = params.numValues[2]-idx2-1;\n\n    // helpers for reversing\n    const int z_mult = (params.reverse[2] ? -1 : 1);\n\n    out.requireWrite();\n    vector<ValueType> values(num0*numComp);\n    const int dpp = out.getNumDataPointsPerSample();\n\n    for (dim_t z=0; z<num2; z++) {\n        const dim_t m2limit = (z==0 ? params.multiplier[2]-rest2 : params.multiplier[2]);\n        dim_t dataZbase = first2 + z*params.multiplier[2];\n        if (z>0)\n            dataZbase -= rest2;\n\n        for (dim_t y=0; y<num1; y++) {\n            const dim_t fileofs = numComp*(idx0 +\n                                (idx1+y)*params.numValues[0] +\n                                (idx2+z_mult*z)*params.numValues[0]*params.numValues[1]);\n            memcpy((char*)&values[0], (char*)&decompressed[fileofs*sizeof(ValueType)], num0*numComp*sizeof(ValueType));\n            const dim_t m1limit = (y==0 ? params.multiplier[1]-rest1 : params.multiplier[1]);\n            dim_t dataYbase = first1 + y*params.multiplier[1];\n            if (y>0)\n                dataYbase -= rest1;\n\n            for (dim_t x=0; x<num0; x++) {\n                const dim_t m0limit = (x==0 ? params.multiplier[0]-rest0 : params.multiplier[0]);\n                dim_t dataXbase = first0 + x*params.multiplier[0];\n                if (x>0)\n                    dataXbase -= rest0;\n                // write a block of mult0 x mult1 x mult2 identical values into\n                // Data object\n                for (dim_t m2=0; m2 < m2limit; m2++) {\n                    const dim_t dataZ = dataZbase + m2;\n                    if (dataZ >= myN2)\n                        break;\n                    for (dim_t m1=0; m1 < m1limit; m1++) {\n                        const dim_t dataY = dataYbase + m1;\n                        if (dataY >= myN1)\n                            break;\n                        for (dim_t m0=0; m0 < m0limit; m0++) {\n                            const dim_t dataX = dataXbase + m0;\n                            if (dataX >= myN0)\n                                break;\n                            const dim_t dataIndex = INDEX3(dataX, dataY, dataZ, m_NN[0],m_NN[1]);\n                            double* dest = out.getSampleDataRW(dataIndex*m_order);\n                            for (int c=0; c<numComp; c++) {\n                                ValueType val = values[x*numComp+c];\n\n                                if (params.byteOrder != BYTEORDER_NATIVE) {\n                                    char* cval = reinterpret_cast<char*>(&val);\n                                    // this will alter val!!\n                                    if (sizeof(ValueType)>4) {\n                                        byte_swap64(cval);\n                                    } else {\n                                        byte_swap32(cval);\n                                    }\n                                }\n                                if (!bm::isnan(val)) {\n                                    for (int q=0; q<dpp; q++) {\n                                        *dest++ = static_cast<double>(val);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    interpolateFromCorners(out);\n}\n#endif\n\nvoid Brick::interpolateFromCorners(escript::Data &out) const\n{\n    const int numComp = out.getDataPointSize();\n    //interpolate the missing portions\n#pragma omp parallel for\n    for (dim_t z = 0; z < m_NN[2]; z++) {\n        const double pz = point_locations[m_order-2][z%m_order];\n        for (dim_t y = 0; y < m_NN[1]; y++) {\n            const double py = point_locations[m_order-2][y%m_order];\n            for (dim_t x = 0; x < m_NN[0]; x++) {\n                //skip the points we have values for\n                if (y % m_order == 0 && x % m_order == 0 && z % m_order == 0)\n                    continue;\n                //point location in element: x,y\n                const double px = point_locations[m_order-2][x%m_order];\n\n                //the point we're interpolating a value for\n                double *point = out.getSampleDataRW(\n                        INDEX3(x, y, z, m_NN[0], m_NN[1]));\n\n                const dim_t left = x - x%m_order;\n                const dim_t right = left < m_NN[0] - 1 ? left + m_order : left;\n                const dim_t front = y - y%m_order;\n                const dim_t back = front < m_NN[1] - 1 ? front + m_order : front;\n                const dim_t down = z - z%m_order;\n                const dim_t up = down < m_NN[2] - 1 ? down + m_order : down;\n         \n                //corner values\n                const double *dlf = out.getSampleDataRO(\n                        INDEX3(left, front, down, m_NN[0], m_NN[1]));\n                const double *dlb = out.getSampleDataRO(\n                        INDEX3(left, back, down, m_NN[0], m_NN[1]));\n                const double *drf = out.getSampleDataRO(\n                        INDEX3(right, front, down, m_NN[0], m_NN[1]));\n                const double *drb = out.getSampleDataRO(\n                        INDEX3(right, back, down, m_NN[0], m_NN[1]));\n                const double *ulf = out.getSampleDataRO(\n                        INDEX3(left, front, up, m_NN[0], m_NN[1]));\n                const double *ulb = out.getSampleDataRO(\n                        INDEX3(left, back, up, m_NN[0], m_NN[1]));\n                const double *urf = out.getSampleDataRO(\n                        INDEX3(right, front, up, m_NN[0], m_NN[1]));\n                const double *urb = out.getSampleDataRO(\n                        INDEX3(right, back, up, m_NN[0], m_NN[1]));\n\n                //the interpolation itself\n                for (int comp = 0; comp < numComp; comp++) {\n                    point[comp] = urb[comp]*px    *py    *pz\n                                + drb[comp]*px    *py    *(1-pz)\n                                + urf[comp]*px    *(1-py)*pz\n                                + drf[comp]*px    *(1-py)*(1-pz)\n                                + ulb[comp]*(1-px)*py    *pz\n                                + dlb[comp]*(1-px)*py    *(1-pz)\n                                + ulf[comp]*(1-px)*(1-py)*pz\n                                + dlf[comp]*(1-px)*(1-py)*(1-pz);\n                }\n            }\n        }\n    }\n}\n\nvoid Brick::writeBinaryGrid(const escript::Data& in, std::string filename,\n                            int byteOrder, int dataType) const\n{\n    // the mapping is not universally correct but should work on our\n    // supported platforms\n    switch (dataType) {\n        case DATATYPE_INT32:\n            writeBinaryGridImpl<int>(in, filename, byteOrder);\n            break;\n        case DATATYPE_FLOAT32:\n            writeBinaryGridImpl<float>(in, filename, byteOrder);\n            break;\n        case DATATYPE_FLOAT64:\n            writeBinaryGridImpl<double>(in, filename, byteOrder);\n            break;\n        default:\n            throw SpeckleyException(\"writeBinaryGrid(): invalid or unsupported datatype\");\n    }\n}\n\ntemplate<typename ValueType>\nvoid Brick::writeBinaryGridImpl(const escript::Data& in,\n                                const string& filename, int byteOrder) const\n{\n    // check function space and determine number of points\n    dim_t myN0, myN1, myN2;\n    dim_t totalN0, totalN1, totalN2;\n    if (in.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NE[0] + 1;\n        myN1 = m_NE[1] + 1;\n        myN2 = m_NE[2] + 1;\n        totalN0 = m_gNE[0]+1;\n        totalN1 = m_gNE[1]+1;\n        totalN2 = m_gNE[2]+1;\n    } else if (in.getFunctionSpace().getTypeCode() == Elements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n        myN2 = m_NE[2];\n        totalN0 = m_gNE[0];\n        totalN1 = m_gNE[1];\n        totalN2 = m_gNE[2];\n    } else\n        throw SpeckleyException(\"writeBinaryGrid(): invalid function space of data object\");\n\n    const int numComp = in.getDataPointSize();\n    const dim_t dpp = in.getNumDataPointsPerSample();\n    const dim_t fileSize = sizeof(ValueType)*numComp*dpp*totalN0*totalN1*totalN2;\n\n    if (numComp > 1 || dpp > 1)\n        throw SpeckleyException(\"writeBinaryGrid(): only scalar, single-value data supported\");\n\n    // from here on we know that each sample consists of one value\n    FileWriter fw;\n    fw.openFile(filename, fileSize);\n    MPIBarrier();\n\n    for (index_t z=0; z<myN2; z++) {\n        for (index_t y=0; y<myN1; y++) {\n            const dim_t fileofs = (m_offset[0]+(m_offset[1]+y)*totalN0\n                                +(m_offset[2]+z)*totalN0*totalN1)*sizeof(ValueType);\n            std::ostringstream oss;\n\n            for (index_t x=0; x<myN0; x++) {\n                const double* sample = in.getSampleDataRO(\n                                INDEX3(x,y,z,m_NN[0],m_NN[1])*m_order);\n                ValueType fvalue = static_cast<ValueType>(*sample);\n                if (byteOrder == BYTEORDER_NATIVE) {\n                    oss.write((char*)&fvalue, sizeof(fvalue));\n                } else {\n                    char* value = reinterpret_cast<char*>(&fvalue);\n                    if (sizeof(fvalue)>4) {\n                        byte_swap64(value);\n                    } else {\n                        byte_swap32(value);\n                    }\n                    oss.write(value, sizeof(fvalue));\n                }\n            }\n            fw.writeAt(oss, fileofs);\n        }\n    }\n    fw.close();\n}\n\nvoid Brick::write(const std::string& filename) const\n{\n    throw SpeckleyException(\"write: not supported\");\n}\n\nvoid Brick::dump(const string& fileName) const\n{\n#ifdef ESYS_HAVE_SILO\n    string fn(fileName);\n    if (fileName.length() < 6 || fileName.compare(fileName.length()-5, 5, \".silo\") != 0) {\n        fn+=\".silo\";\n    }\n\n    int driver=DB_HDF5;\n    string siloPath;\n    DBfile* dbfile = NULL;\n\n#ifdef ESYS_MPI\n    PMPIO_baton_t* baton = NULL;\n    const int NUM_SILO_FILES = 1;\n    const char* blockDirFmt = \"/block%04d\";\n#endif\n\n    if (m_mpiInfo->size > 1) {\n#ifdef ESYS_MPI\n        baton = PMPIO_Init(NUM_SILO_FILES, PMPIO_WRITE, m_mpiInfo->comm,\n                    0x1337, PMPIO_DefaultCreate, PMPIO_DefaultOpen,\n                    PMPIO_DefaultClose, (void*)&driver);\n        // try the fallback driver in case of error\n        if (!baton && driver != DB_PDB) {\n            driver = DB_PDB;\n            baton = PMPIO_Init(NUM_SILO_FILES, PMPIO_WRITE, m_mpiInfo->comm,\n                        0x1338, PMPIO_DefaultCreate, PMPIO_DefaultOpen,\n                        PMPIO_DefaultClose, (void*)&driver);\n        }\n        if (baton) {\n            char str[64];\n            snprintf(str, 64, blockDirFmt, PMPIO_RankInGroup(baton, m_mpiInfo->rank));\n            siloPath = str;\n            dbfile = (DBfile*) PMPIO_WaitForBaton(baton, fn.c_str(), siloPath.c_str());\n        }\n#endif\n    } else {\n        dbfile = DBCreate(fn.c_str(), DB_CLOBBER, DB_LOCAL,\n                getDescription().c_str(), driver);\n        // try the fallback driver in case of error\n        if (!dbfile && driver != DB_PDB) {\n            driver = DB_PDB;\n            dbfile = DBCreate(fn.c_str(), DB_CLOBBER, DB_LOCAL,\n                    getDescription().c_str(), driver);\n        }\n    }\n\n    if (!dbfile)\n        throw SpeckleyException(\"dump: Could not create Silo file\");\n\n    /*\n    if (driver==DB_HDF5) {\n        // gzip level 1 already provides good compression with minimal\n        // performance penalty. Some tests showed that gzip levels >3 performed\n        // rather badly on escript data both in terms of time and space\n        DBSetCompression(\"ERRMODE=FALLBACK METHOD=GZIP LEVEL=1\");\n    }\n    */\n\n    boost::scoped_ptr<double> x(new double[m_NN[0]]);\n    boost::scoped_ptr<double> y(new double[m_NN[1]]);\n    boost::scoped_ptr<double> z(new double[m_NN[2]]);\n    double* coords[3] = { x.get(), y.get(), z.get() };\n    const dim_t NN0 = m_NN[0];\n    const dim_t NN1 = m_NN[1];\n    const dim_t NN2 = m_NN[2];\n\n#pragma omp parallel\n    {\n#pragma omp for\n        for (dim_t i0 = 0; i0 < NN0; i0++) {\n            coords[0][i0]=getLocalCoordinate(i0, 0);\n        }\n#pragma omp for\n        for (dim_t i1 = 0; i1 < NN1; i1++) {\n            coords[1][i1]=getLocalCoordinate(i1, 1);\n        }\n#pragma omp for\n        for (dim_t i2 = 0; i2 < NN2; i2++) {\n            coords[2][i2]=getLocalCoordinate(i2, 2);\n        }\n    }\n    std::vector<int> dims(m_NN, m_NN+3);\n\n    // write mesh\n    DBPutQuadmesh(dbfile, \"mesh\", NULL, coords, &dims[0], 3, DB_DOUBLE,\n            DB_COLLINEAR, NULL);\n\n    // write node ids\n    DBPutQuadvar1(dbfile, \"nodeId\", \"mesh\", (void*)&m_nodeId[0], &dims[0], 3,\n            NULL, 0, DB_INT, DB_NODECENT, NULL);\n\n    // write element ids\n    dims.assign(m_NE, m_NE+3);\n    DBPutQuadvar1(dbfile, \"elementId\", \"mesh\", (void*)&m_elementId[0],\n            &dims[0], 3, NULL, 0, DB_INT, DB_ZONECENT, NULL);\n\n    // rank 0 writes multimesh and multivar\n    if (m_mpiInfo->rank == 0) {\n        vector<string> tempstrings;\n        vector<char*> names;\n        for (dim_t i=0; i<m_mpiInfo->size; i++) {\n            std::stringstream path;\n            path << \"/block\" << std::setw(4) << std::setfill('0') << std::right << i << \"/mesh\";\n            tempstrings.push_back(path.str());\n            names.push_back((char*)tempstrings.back().c_str());\n        }\n        vector<int> types(m_mpiInfo->size, DB_QUAD_RECT);\n        DBSetDir(dbfile, \"/\");\n        DBPutMultimesh(dbfile, \"multimesh\", m_mpiInfo->size, &names[0],\n               &types[0], NULL);\n        tempstrings.clear();\n        names.clear();\n        for (dim_t i=0; i<m_mpiInfo->size; i++) {\n            std::stringstream path;\n            path << \"/block\" << std::setw(4) << std::setfill('0') << std::right << i << \"/nodeId\";\n            tempstrings.push_back(path.str());\n            names.push_back((char*)tempstrings.back().c_str());\n        }\n        types.assign(m_mpiInfo->size, DB_QUADVAR);\n        DBPutMultivar(dbfile, \"nodeId\", m_mpiInfo->size, &names[0],\n               &types[0], NULL);\n        tempstrings.clear();\n        names.clear();\n        for (dim_t i=0; i<m_mpiInfo->size; i++) {\n            std::stringstream path;\n            path << \"/block\" << std::setw(4) << std::setfill('0') << std::right << i << \"/elementId\";\n            tempstrings.push_back(path.str());\n            names.push_back((char*)tempstrings.back().c_str());\n        }\n        DBPutMultivar(dbfile, \"elementId\", m_mpiInfo->size, &names[0],\n               &types[0], NULL);\n    }\n\n    if (m_mpiInfo->size > 1) {\n#ifdef ESYS_MPI\n        PMPIO_HandOffBaton(baton, dbfile);\n        PMPIO_Finish(baton);\n#endif\n    } else {\n        DBClose(dbfile);\n    }\n\n#else // ESYS_HAVE_SILO\n    throw SpeckleyException(\"dump: no Silo support\");\n#endif\n}\n\nconst dim_t* Brick::borrowSampleReferenceIDs(int fsType) const\n{\n    switch (fsType) {\n        case DegreesOfFreedom:\n        case Nodes:\n            return &m_nodeId[0];\n        case Elements:\n        case ReducedElements:\n            return &m_elementId[0];\n        case Points:\n            return &m_diracPointNodeIDs[0];\n        default:\n            break;\n    }\n\n    std::stringstream msg;\n    msg << \"borrowSampleReferenceIDs: invalid function space type \" << fsType;\n    throw SpeckleyException(msg.str());\n}\n\nbool Brick::ownSample(int fsType, index_t id) const\n{\n#ifdef ESYS_MPI\n    if (getMPISize() > 1) {\n        if (fsType == Nodes || fsType == Elements) {\n            const index_t myFirstNode = m_nodeDistribution[getMPIRank()];\n            const index_t myLastNode = m_nodeDistribution[getMPIRank()+1];\n            const index_t k = m_nodeId[id];\n            return (myFirstNode <= k && k < myLastNode);\n        } else {\n            throw SpeckleyException(\"ownSample: unsupported function space type\");\n        }\n    }\n#endif\n    return true;\n}\n\nvoid Brick::setToNormal(escript::Data& out) const\n{\n    throw SpeckleyException(\"setToNormal not implemented\");\n}\n\nvoid Brick::setToSize(escript::Data& out) const\n{\n    if (out.getFunctionSpace().getTypeCode() == Elements) {\n        out.requireWrite();\n        const dim_t numQuad = m_order + 1;\n        const dim_t numElements = getNumElements();\n        const double *quad_locs = point_locations[m_order-2];\n        //since elements are uniform, calc the first and copy to others\n        double* first_element = out.getSampleDataRW(0);\n#pragma omp parallel for\n        for (short qz = 0; qz < m_order; qz++) {\n            const double z = quad_locs[qz+1] - quad_locs[qz];\n            for (short qy = 0; qy < m_order; qy++) {\n                const double y = quad_locs[qy+1] - quad_locs[qy];\n                for (short qx = 0; qx < m_order; qx++) {\n                    const double x = quad_locs[qx+1] - quad_locs[qx];\n                    first_element[INDEX3(qx,qy,qz,numQuad,numQuad)]= sqrt(x*x + y*y + z*z);\n                }\n                first_element[INDEX3(m_order,qy,qz,numQuad,numQuad)] \n                        = first_element[INDEX3(0,qy,qz,numQuad,numQuad)];\n            }\n            for (short qx = 0; qx < numQuad; qx++) {\n                first_element[INDEX3(qx,m_order,qz,numQuad,numQuad)] \n                        = first_element[INDEX3(qx,0,qz,numQuad,numQuad)];\n            }\n        }\n        for (short qy = 0; qy < numQuad; qy++) {\n            for (short qx = 0; qx < numQuad; qx++) {\n                first_element[INDEX3(qx,qy,m_order,numQuad,numQuad)] \n                        = first_element[INDEX3(qx,qy,0,numQuad,numQuad)];\n            }\n        }\n        const size_t size = numQuad*numQuad*numQuad*sizeof(double);\n#pragma omp parallel for\n        for (index_t k = 0; k < numElements; ++k) {\n            double* o = out.getSampleDataRW(k);\n            memcpy(o, first_element, size);\n        }\n    } else {\n        std::stringstream msg;\n        msg << \"setToSize: invalid function space type \"\n            << out.getFunctionSpace().getTypeCode();\n        throw SpeckleyException(msg.str());\n    }\n}\n\nvoid Brick::Print_Mesh_Info(const bool full) const\n{\n    SpeckleyDomain::Print_Mesh_Info(full);\n    if (full) {\n        std::cout << \"     Id  Coordinates\" << std::endl;\n        std::cout.precision(15);\n        std::cout.setf(std::ios::scientific, std::ios::floatfield);\n        for (index_t i=0; i < getNumNodes(); i++) {\n            std::cout << \"  \" << std::setw(5) << m_nodeId[i]\n                << \"  \" << getLocalCoordinate(i%m_NN[0], 0)\n                << \"  \" << getLocalCoordinate(i%(m_NN[0]*m_NN[1])/m_NN[0], 1)\n                << \"  \" << getLocalCoordinate(i/(m_NN[0]*m_NN[1]), 2) << std::endl;\n        }\n    }\n}\n\n\n//protected\nvoid Brick::assembleCoordinates(escript::Data& arg) const\n{\n    int numDim = m_numDim;\n    if (!arg.isDataPointShapeEqual(1, &numDim))\n        throw SpeckleyException(\"setToX: Invalid Data object shape\");\n    if (!arg.numSamplesEqual(1, getNumNodes()))\n        throw SpeckleyException(\"setToX: Illegal number of samples in Data object\");\n\n    const dim_t NN0 = m_NN[0];\n    const dim_t NN1 = m_NN[1];\n    const dim_t NN2 = m_NN[2];\n    arg.requireWrite();\n#pragma omp parallel for\n    for (dim_t i2 = 0; i2 < NN2; i2++) {\n        for (dim_t i1 = 0; i1 < NN1; i1++) {\n            for (dim_t i0 = 0; i0 < NN0; i0++) {\n                double* point = arg.getSampleDataRW(i0+NN0*i1+NN0*NN1*i2);\n                point[0] = getLocalCoordinate(i0, 0);\n                point[1] = getLocalCoordinate(i1, 1);\n                point[2] = getLocalCoordinate(i2, 2);\n            }\n        }\n    }\n}\n\n//protected\nvoid Brick::assembleGradient(escript::Data& out, const escript::Data& in) const\n{\n    escript::Data converted;\n\n    if (in.getFunctionSpace().getTypeCode() != Elements) {\n        converted = escript::Data(in, escript::function(*this));\n    } else {\n        converted = in;\n    }\n\n    if (m_order == 2) {\n        if (in.isComplex())\n            gradient_order2<cplx_t>(out,converted);\n        else\n            gradient_order2<real_t>(out,converted);\n    } else if (m_order == 3) {\n        if (in.isComplex())\n            gradient_order3<cplx_t>(out,converted);\n        else\n            gradient_order3<real_t>(out,converted);\n    } else if (m_order == 4) {\n        if (in.isComplex())\n            gradient_order4<cplx_t>(out,converted);\n        else\n            gradient_order4<real_t>(out,converted);\n    } else if (m_order == 5) {\n        if (in.isComplex())\n            gradient_order5<cplx_t>(out,converted);\n        else\n            gradient_order5<real_t>(out,converted);\n    } else if (m_order == 6) {\n        if (in.isComplex())\n            gradient_order6<cplx_t>(out,converted);\n        else\n            gradient_order6<real_t>(out,converted);\n    } else if (m_order == 7) {\n        if (in.isComplex())\n            gradient_order7<cplx_t>(out,converted);\n        else\n            gradient_order7<real_t>(out,converted);\n    } else if (m_order == 8) {\n        if (in.isComplex())\n            gradient_order8<cplx_t>(out,converted);\n        else\n            gradient_order8<real_t>(out,converted);\n    } else if (m_order == 9) {\n        if (in.isComplex())\n            gradient_order9<cplx_t>(out,converted);\n        else\n            gradient_order9<real_t>(out,converted);\n    } else if (m_order == 10) {\n        if (in.isComplex())\n            gradient_order10<cplx_t>(out,converted);\n        else\n            gradient_order10<real_t>(out,converted);\n    }\n}\n\n//protected\nvoid Brick::assembleIntegrate(vector<real_t>& integrals,\n                              const escript::Data& arg) const\n{\n    assembleIntegrateWorker<real_t>(integrals, arg);\n}\n\n//protected\nvoid Brick::assembleIntegrate(vector<cplx_t>& integrals,\n                              const escript::Data& arg) const\n{\n    assembleIntegrateWorker<cplx_t>(integrals, arg);\n}\n\n//private\ntemplate<typename Scalar>\nvoid Brick::assembleIntegrateWorker(vector<Scalar>& integrals, const escript::Data& arg) const\n{\n    const int fs = arg.getFunctionSpace().getTypeCode();\n    if (fs != Elements)\n        throw new SpeckleyException(\"Speckley doesn't currently support integrals of non-Element functionspaces\");\n    if (!arg.actsExpanded())\n        throw new SpeckleyException(\"Speckley doesn't currently support unexpanded data\");\n\n    if (m_order == 2) {\n        integral_order2(integrals, arg);\n    } else if (m_order == 3) {\n        integral_order3(integrals, arg);\n    } else if (m_order == 4) {\n        integral_order4(integrals, arg);\n    } else if (m_order == 5) {\n        integral_order5(integrals, arg);\n    } else if (m_order == 6) {\n        integral_order6(integrals, arg);\n    } else if (m_order == 7) {\n        integral_order7(integrals, arg);\n    } else if (m_order == 8) {\n        integral_order8(integrals, arg);\n    } else if (m_order == 9) {\n        integral_order9(integrals, arg);\n    } else if (m_order == 10) {\n        integral_order10(integrals, arg);\n    }\n}\n\n//private\nvoid Brick::populateSampleIds()\n{\n    // degrees of freedom are numbered from left to right, bottom to top, front\n    // to back in each rank, continuing on the next rank (ranks also go\n    // left-right, bottom-top, front-back).\n    // This means rank 0 has id 0...n0-1, rank 1 has id n0...n1-1 etc. which\n    // helps when writing out data rank after rank.\n\n    // build node distribution vector first.\n    // rank i owns m_nodeDistribution[i+1]-nodeDistribution[i] nodes which is\n    // constant for all ranks in this implementation\n\n#define RANK_LEFT(__rank__) ((__rank__) % m_NX[0] == 0 ? 0 : 1)\n#define RANK_FRONT(__rank__) ((__rank__) % (m_NX[0]*m_NX[1])/m_NX[0] == 0 ? 0 : 1)\n#define RANK_BELOW(__rank__) ((__rank__) / (m_NX[0]*m_NX[1]) == 0 ? 0 : 1)\n\n    m_nodeDistribution.assign(m_mpiInfo->size+1, 0);\n\n    for (dim_t k = 0; k < m_mpiInfo->size - 1; k++) {\n        m_nodeDistribution[k+1] = m_nodeDistribution[k]\n                                + (m_NN[0]-RANK_LEFT(k))\n                                * (m_NN[1]-RANK_FRONT(k))\n                                * (m_NN[2]-RANK_BELOW(k));\n    }\n\n    m_nodeDistribution[m_mpiInfo->size]=getNumDataPointsGlobal();\n\n    try {\n        m_nodeId.resize(getNumNodes());\n        m_elementId.resize(getNumElements());\n    } catch (const std::length_error& le) {\n        throw SpeckleyException(\"The system does not have sufficient memory for a domain of this size.\");\n    }\n\n    // populate face element counts\n    //left\n    if (m_offset[0]==0)\n        m_faceCount[0]=m_NE[1]*m_NE[2];\n    else\n        m_faceCount[0]=0;\n    //right\n    if (m_mpiInfo->rank%m_NX[0]==m_NX[0]-1)\n        m_faceCount[1]=m_NE[1]*m_NE[2];\n    else\n        m_faceCount[1]=0;\n    //bottom\n    if (m_offset[1]==0)\n        m_faceCount[2]=m_NE[0]*m_NE[2];\n    else\n        m_faceCount[2]=0;\n    //top\n    if (m_mpiInfo->rank%(m_NX[0]*m_NX[1])/m_NX[0]==m_NX[1]-1)\n        m_faceCount[3]=m_NE[0]*m_NE[2];\n    else\n        m_faceCount[3]=0;\n    //front\n    if (m_offset[2]==0)\n        m_faceCount[4]=m_NE[0]*m_NE[1];\n    else\n        m_faceCount[4]=0;\n    //back\n    if (m_mpiInfo->rank/(m_NX[0]*m_NX[1])==m_NX[2]-1)\n        m_faceCount[5]=m_NE[0]*m_NE[1];\n    else\n        m_faceCount[5]=0;\n\n    const int rank = m_mpiInfo->rank;\n\n    const index_t left = RANK_LEFT(rank);\n    const index_t front = RANK_FRONT(rank);\n    const index_t bottom = RANK_BELOW(rank);\n\n\n    if (left && front) {\n        //re-use bottom-left-front corner node\n        if (bottom) {\n            //get lower-left-front node\n            int rank_wanted = rank\n                        - m_NX[0]*m_NX[1]   //down a layer\n                        - m_NX[0];          //towards the front\n            m_nodeId[0] = m_nodeDistribution[rank_wanted] - 1; //end of the left\n        }\n        //front left edge\n        int neighbour = rank - m_NX[0] - 1;\n        int neighboursLeft = RANK_LEFT(neighbour);\n        int neighboursFront = RANK_FRONT(neighbour);\n        index_t begin = m_nodeDistribution[neighbour] \n                    + (m_NN[0]-neighboursLeft)*(m_NN[1]-neighboursFront) - 1;\n#pragma omp parallel for\n        for (index_t z = bottom; z < m_NN[2]; z++) {\n            index_t theirs = z*(m_NN[0]-neighboursLeft)*(m_NN[1]-neighboursFront);\n            index_t mine = z*m_NN[0]*m_NN[1];\n            m_nodeId[mine] = begin + theirs;\n        }\n    }\n    //re-use nodes on bottom border\n    if (bottom) {\n        int neighbour = rank - m_NX[0]*m_NX[1];\n        //beginning, top left front of rank underneath\n        index_t begin = m_nodeDistribution[neighbour + 1] - m_NN[0]*m_NN[1];\n#pragma omp parallel for\n        for (index_t y = front; y < m_NN[1]; y++) {\n            for (index_t x = left; x < m_NN[0]; x++) {\n                index_t i = INDEX2(x,y,m_NN[0]);\n                m_nodeId[i] = begin + INDEX2(x,y,m_NN[0]);\n            }\n        }\n    }\n\n    //re-use nodes on front border\n    if (front) {\n        int neighbour = rank - m_NX[0];\n        index_t begin = m_nodeDistribution[neighbour] \n                        + (m_NN[0]-RANK_LEFT(neighbour))\n                        *(m_NN[1]-RANK_FRONT(neighbour) - 1);\n#pragma omp parallel for\n        for (index_t z = bottom; z < m_NN[2]; z++) {\n            index_t mine = z*m_NN[0]*m_NN[1] + left;\n            index_t theirs = z*(m_NN[0]-RANK_LEFT(neighbour))*(m_NN[1]-RANK_FRONT(neighbour));\n            for (index_t x = left; x < m_NN[0]; x++, theirs++, mine++) {\n                m_nodeId[mine] = begin + theirs;\n            }\n        }\n    }\n    //re-use nodes on left border\n    if (left) {\n        //is the rank to the left itself right of another rank\n        index_t neighboursLeft = RANK_LEFT(rank - 1);\n        index_t neighboursFront = RANK_FRONT(rank - 1);\n        index_t neighboursBelow = RANK_BELOW(rank - 1);\n        //end of first owned row of neighbouring rank\n        index_t end = m_nodeDistribution[rank - 1] + m_NN[0]-neighboursLeft - 1;\n#pragma omp parallel for\n        for (index_t z = bottom; z < m_NN[2]; z++) {\n            for (index_t y = front; y < m_NN[1]; y++) {\n                index_t mine = INDEX3(0,y,z,m_NN[0],m_NN[1]);\n                index_t theirs = INDEX3(0,(y-neighboursFront),(z-neighboursBelow),(m_NN[0]-neighboursLeft),(m_NN[1]-neighboursFront));\n                m_nodeId[mine] = end + theirs;\n            }\n        }\n    }\n\n    //now the new nodes\n    const index_t start = m_nodeDistribution[m_mpiInfo->rank];\n#pragma omp parallel for\n    for (index_t z = bottom; z < m_NN[2]; z++) {\n        index_t z_chunk = (z-bottom)*(m_NN[0]-left)*(m_NN[1]-front);\n        for (index_t y = front; y < m_NN[1]; y++) {\n            index_t y_chunk = (y-front)*(m_NN[0]-left);\n            for (index_t x = left; x < m_NN[0]; x++) {\n                m_nodeId[INDEX3(x, y, z, m_NN[0], m_NN[1])]\n                        =  start + z_chunk + y_chunk + (x-left);\n            }\n        }\n    }\n    m_nodeTags.assign(getNumNodes(), 0);\n    updateTagsInUse(Nodes);\n\n    m_elementTags.assign(getNumElements(), 0);\n    updateTagsInUse(Elements);\n#undef RANK_TO_LEFT\n#undef RANK_TO_RIGHT\n#undef RANK_TO_FRONT\n}\n\nvoid Brick::interpolateElementsOnNodes(escript::Data& out,\n                                  const escript::Data& in) const {\n    const dim_t numComp = in.getDataPointSize();\n    const dim_t NE0 = m_NE[0];\n    const dim_t NE1 = m_NE[1];\n    const dim_t NE2 = m_NE[2];\n    const int quads = m_order + 1;\n    const dim_t max_x = m_NN[0];\n    const dim_t max_y = m_NN[1];\n    const dim_t max_z = m_NN[2];\n    const int inFS = in.getFunctionSpace().getTypeCode();\n    out.requireWrite();\n    //init to zero so we can do some sums without undefined, may not be required\n    memset(out.getSampleDataRW(0), 0, sizeof(double)*quads*quads*numComp);\n    // the summation portion\n    if (inFS == ReducedElements) {\n        for (dim_t colouring = 0; colouring < 2; colouring++) {\n    #pragma omp parallel for\n            for (dim_t ez = colouring; ez < NE2; ez += 2) {\n                for (dim_t ey = 0; ey < NE1; ey++) {\n                    for (dim_t ex = 0; ex < NE0; ex++) {\n                        dim_t start = m_order * (INDEX3(ex, ey, ez, max_x, max_y));\n                        const double *e_in = in.getSampleDataRO(INDEX3(ex,ey,ez,NE0,NE1));\n                        for (int qz = 0; qz < quads; qz++) {\n                            for (int qy = 0; qy < quads; qy++) {\n                                for (int qx = 0; qx < quads; qx++) {\n                                    double *n_out = out.getSampleDataRW(start + INDEX3(qx, qy, qz, max_x, max_y));\n                                    for (dim_t comp = 0; comp < numComp; comp++) {\n                                        n_out[comp] += e_in[comp];\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }        \n    } else {\n        for (dim_t colouring = 0; colouring < 2; colouring++) {\n    #pragma omp parallel for\n            for (dim_t ez = colouring; ez < NE2; ez += 2) {\n                for (dim_t ey = 0; ey < NE1; ey++) {\n                    for (dim_t ex = 0; ex < NE0; ex++) {\n                        dim_t start = m_order * (INDEX3(ex, ey, ez, max_x, max_y));\n                        const double *e_in = in.getSampleDataRO(INDEX3(ex,ey,ez,NE0,NE1));\n                        for (int qz = 0; qz < quads; qz++) {\n                            for (int qy = 0; qy < quads; qy++) {\n                                for (int qx = 0; qx < quads; qx++) {\n                                    double *n_out = out.getSampleDataRW(start + INDEX3(qx, qy, qz, max_x, max_y));\n                                    for (dim_t comp = 0; comp < numComp; comp++) {\n                                        n_out[comp] += e_in[INDEX4(comp, qx, qy, qz, numComp, quads, quads)];\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n#ifdef ESYS_MPI\n    //sum and average neighbours before we average out our internal structure\n    balanceNeighbours(out, true);\n#endif\n\n    /* the averaging out (each point divided by the number of additions in\n       the summation step). By doing each edge along an axis, those points\n       requiring division by 2, 4 and 8 will be divided by 2 the right\n       number of times\n\n       border edges are skipped because they aren't shared but for the\n       points that lie along a different axes non-border edge\n    */\n    // for every non-border edge in x\n#pragma omp parallel for\n    for (index_t qz = 0; qz < max_z; qz++) {\n        for (index_t qy = 0; qy < max_y; qy++) {\n            for (index_t qx = m_order; qx < max_x - m_order; qx += m_order) {\n                double *n_out = out.getSampleDataRW(INDEX3(qx, qy, qz, max_x, max_y));\n                for (int comp = 0; comp < numComp; comp++) {\n                    n_out[comp] /= 2.;\n                }\n            }\n        }\n    }\n    // for every non-border edge in y\n#pragma omp parallel for\n    for (index_t qz = 0; qz < max_z; qz++) {\n        for (index_t qy = m_order; qy < max_y - m_order; qy += m_order) {\n            for (index_t qx = 0; qx < max_x; qx ++) {\n                double *n_out = out.getSampleDataRW(INDEX3(qx, qy, qz, max_x, max_y));\n                for (int comp = 0; comp < numComp; comp++) {\n                    n_out[comp] /= 2.;\n                }\n            }\n        }\n    }\n    // for every non-border edge in z\n    const index_t order = m_order;\n#pragma omp parallel for\n    for (index_t qz = order; qz < max_z - order; qz += order) {\n        for (index_t qy = 0; qy < max_y; qy++) {\n            for (index_t qx = 0; qx < max_x; qx++) {\n                double *n_out = out.getSampleDataRW(INDEX3(qx, qy, qz, max_x, max_y));\n                for (int comp = 0; comp < numComp; comp++) {\n                    n_out[comp] /= 2.;\n                }\n            }\n        }\n    }\n}\n\nvoid Brick::reduceElements(escript::Data& out, const escript::Data& in) const\n{\n    if (m_order == 2) {\n        if (in.isComplex())\n            reduction_order2<cplx_t>(in, out);\n        else\n            reduction_order2<real_t>(in, out);\n    } else if (m_order == 3) {\n        if (in.isComplex())\n            reduction_order3<cplx_t>(in, out);\n        else\n            reduction_order3<real_t>(in, out);\n    } else if (m_order == 4) {\n        if (in.isComplex())\n            reduction_order4<cplx_t>(in, out);\n        else\n            reduction_order4<real_t>(in, out);\n    } else if (m_order == 5) {\n        if (in.isComplex())\n            reduction_order5<cplx_t>(in, out);\n        else\n            reduction_order5<real_t>(in, out);\n    } else if (m_order == 6) {\n        if (in.isComplex())\n            reduction_order6<cplx_t>(in, out);\n        else\n            reduction_order6<real_t>(in, out);\n    } else if (m_order == 7) {\n        if (in.isComplex())\n            reduction_order7<cplx_t>(in, out);\n        else\n            reduction_order7<real_t>(in, out);\n    } else if (m_order == 8) {\n        if (in.isComplex())\n            reduction_order8<cplx_t>(in, out);\n        else\n            reduction_order8<real_t>(in, out);\n    } else if (m_order == 9) {\n        if (in.isComplex())\n            reduction_order9<cplx_t>(in, out);\n        else\n            reduction_order9<real_t>(in, out);\n    } else if (m_order == 10) {\n        if (in.isComplex())\n            reduction_order10<cplx_t>(in, out);\n        else\n            reduction_order10<real_t>(in, out);\n    }\n}\n\n//protected\nvoid Brick::interpolateNodesOnElements(escript::Data& out,\n                                       const escript::Data& in,\n                                       bool reduced) const\n{\n    if (in.isComplex())\n        interpolateNodesOnElementsWorker<cplx_t>(out, in, reduced);\n    else\n        interpolateNodesOnElementsWorker<real_t>(out, in, reduced);\n}\n\n//private\ntemplate<typename Scalar>\nvoid Brick::interpolateNodesOnElementsWorker(escript::Data& out,\n                                             const escript::Data& in,\n                                             bool reduced) const\n{\n    if (reduced) { //going to ReducedElements\n        escript::Data funcIn(in, escript::function(*this));\n        reduceElements(out, funcIn);\n        return;\n    }\n    const dim_t numComp = in.getDataPointSize();\n    const dim_t NE0 = m_NE[0];\n    const dim_t NE1 = m_NE[1];\n    const dim_t NE2 = m_NE[2];\n    const int quads = m_order + 1;\n    const dim_t max_x = m_NN[0];\n    const dim_t max_y = m_NN[1];\n    const Scalar zero = static_cast<Scalar>(0);\n\n    out.requireWrite();\n#pragma omp parallel for\n    for (dim_t ez = 0; ez < NE2; ez++) {\n        for (dim_t ey = 0; ey < NE1; ey++) {\n            for (dim_t ex = 0; ex < NE0; ex++) {\n                Scalar* e_out = out.getSampleDataRW(INDEX3(ex, ey, ez, NE0, NE1), zero);\n                dim_t start = m_order * INDEX3(ex, ey, ez, max_x, max_y);\n                int quad = 0;\n                for (int qz = 0; qz < quads; qz++) {\n                    for (int qy = 0; qy < quads; qy++) {\n                        for (int qx = 0; qx < quads; qx++, quad++) {\n                            const Scalar* n_in = in.getSampleDataRO(start + INDEX3(qx,qy,qz,max_x,max_y), zero);\n                            for (int comp = 0; comp < numComp; comp++) {\n                                e_out[INDEX4(comp, qx, qy, qz, numComp, quads, quads)] = n_in[comp];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n#ifdef ESYS_MPI\n\n//protected\nvoid Brick::balanceNeighbours(escript::Data& out, bool average) const\n{\n    // skip all this if we aren't even subdividing the domain\n    if (m_NX[0] * m_NX[1] * m_NX[2] == 1) {\n        return;\n    }\n    const int numComp = out.getDataPointSize();\n    int rx = m_mpiInfo->rank % m_NX[0];\n    int ry = m_mpiInfo->rank % (m_NX[0]*m_NX[1]) / m_NX[0];\n    int rz = m_mpiInfo->rank / (m_NX[0]*m_NX[1]);\n    //include bordering ranks in summation\n    //averaging waits til after all sharing\n    shareFaces(out, rx, ry, rz);\n    if ((m_NX[0] > 1 && m_NX[1] > 1)\n            || (m_NX[1] > 1 && m_NX[2] > 1)\n            || (m_NX[0] > 1 && m_NX[2] > 1))\n        shareEdges(out, rx, ry, rz);\n    if (m_NX[0] != 1 && m_NX[1] != 1 && m_NX[2] != 1) {\n        shareCorners(out);\n        if (!average)\n            return;\n        //averaging out corners now that all sharing done\n        for (int z = 0; z < 2; z++) {\n            for (int y = 0; y < 2; y++) {\n                for (int x = 0; x < 2; x++) {\n                    if (!neighbour_exists[INDEX3(x,y,z,2,2)])\n                        continue;\n                    double *values = out.getSampleDataRW(\n                            INDEX3(x*(m_NN[0]-1), y*(m_NN[1]-1), z*(m_NN[2]-1),\n                                            m_NN[0], m_NN[1]));\n                    for (int comp = 0; comp < numComp; comp++) {\n                        values[comp] /= 2;\n                    }\n                }\n            }\n        }\n    }\n    if (!average)\n        return;\n    // average shared-edges\n\n    const bool left = rx;\n    const bool right = rx < m_NX[0] - 1;\n    const bool front = ry;\n    const bool back = ry < m_NX[1] - 1;\n    const bool bottom = rz;\n    const bool top = rz < m_NX[2] - 1;\n    if (left) {\n        if (front) { //average Z lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(0, 0, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n        if (back) {//average Z lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(0, m_NN[1]-1, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n        if (top) {//average Y lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(0, i, m_NN[2]-1, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;;\n                }\n            }\n        }\n        if (bottom) {//average Y lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(0,i,0,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n    if (right) {\n        if (front) { //average Z lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(m_NN[0]-1, 0, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n        if (back) {//average Z lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(m_NN[0]-1,m_NN[1]-1,i,m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n        if (top) {//average Y lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(m_NN[0]-1,i,m_NN[2]-1, m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n        if (bottom) {//average Y lines\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(m_NN[0]-1, i, 0, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n\n    if (top) {\n        if (front) {//average X lines\n#pragma omp parallel for\n            for (dim_t x = 0; x < m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(x, 0, m_NN[2]-1, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n        if (back) {//average X lines\n#pragma omp parallel for\n            for (dim_t x = 0; x < m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(x,m_NN[1]-1,m_NN[2]-1,m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n    if (bottom) {\n        if (front) {//average X lines\n#pragma omp parallel for\n            for (dim_t x = 0; x < m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(x);\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n        if (back) {//average X lines\n#pragma omp parallel for\n            for (dim_t x = 0; x < m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(x, m_NN[1]-1, 0, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n\n    //average shared faces\n    //up and down\n    if (top) {\n#pragma omp parallel for\n        for (dim_t y = 0; y <m_NN[1]; y++) {\n            for (dim_t x = 0; x <m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(x, y, m_NN[2]-1, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n    if (bottom) {\n#pragma omp parallel for\n        for (dim_t y = 0; y <m_NN[1]; y++) {\n            for (dim_t x = 0; x <m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(INDEX2(x, y, m_NN[0]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n    //left and right\n    if (right) {\n#pragma omp parallel for\n        for (dim_t z = 0; z <m_NN[2]; z++) {\n            for (dim_t y = 0; y <m_NN[1]; y++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(m_NN[0]-1, y, z, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n    if (left) {\n#pragma omp parallel for\n        for (dim_t z = 0; z <m_NN[2]; z++) {\n            for (dim_t y = 0; y <m_NN[1]; y++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(0, y, z, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n    //front and back\n    if (back) {\n#pragma omp parallel for\n        for (dim_t z = 0; z <m_NN[2]; z++) {\n            for (dim_t x = 0; x <m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(x, m_NN[1]-1, z, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n    if (front) {\n#pragma omp parallel for\n        for (dim_t z = 0; z <m_NN[2]; z++) {\n            for (dim_t x = 0; x <m_NN[0]; x++) {\n                double *data = out.getSampleDataRW(\n                                INDEX3(x, 0, z, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] /= 2;\n                }\n            }\n        }\n    }\n}\n\n//private\nvoid Brick::setCornerNeighbours()\n{\n    const int rank = m_mpiInfo->rank;\n\n    const int rx = rank % m_NX[0];\n    const int ry = rank % (m_NX[0]*m_NX[1])/m_NX[0];\n    const int rz = rank / (m_NX[0]*m_NX[1]);\n\n    const bool left = rx;\n    const bool right = rx < m_NX[0] - 1;\n    const bool front = ry;\n    const bool back = ry < m_NX[1] - 1;\n    const bool bottom = rz;\n    const bool top = rz < m_NX[2] - 1;\n\n    neighbour_exists[0] = left && front && bottom;\n    neighbour_exists[1] = right && front && bottom;\n    neighbour_exists[2] = left && back && bottom;\n    neighbour_exists[3] = right && back && bottom;\n    neighbour_exists[4] = left && front && top;\n    neighbour_exists[5] = right && front && top;\n    neighbour_exists[6] = left && back && top;\n    neighbour_exists[7] = right && back && top;\n\n    neighbour_ranks[0] = rank - m_NX[0]*m_NX[1] - m_NX[0] - 1;\n    neighbour_ranks[1] = rank - m_NX[0]*m_NX[1] - m_NX[0] + 1;\n    neighbour_ranks[2] = rank - m_NX[0]*m_NX[1] + m_NX[0] - 1;\n    neighbour_ranks[3] = rank - m_NX[0]*m_NX[1] + m_NX[0] + 1;\n    neighbour_ranks[4] = rank + m_NX[0]*m_NX[1] - m_NX[0] - 1;\n    neighbour_ranks[5] = rank + m_NX[0]*m_NX[1] - m_NX[0] + 1;\n    neighbour_ranks[6] = rank + m_NX[0]*m_NX[1] + m_NX[0] - 1;\n    neighbour_ranks[7] = rank + m_NX[0]*m_NX[1] + m_NX[0] + 1;\n}\n\n//private\nvoid Brick::shareCorners(escript::Data& out) const\n{\n    //setup\n    const int tag = 0;\n    MPI_Status status;\n    MPI_Request request[8];\n    const int numComp = out.getDataPointSize();\n    const int count = numComp;\n    std::vector<double> inbuf(count, 0);\n\n    //send\n    for (int z = 0; z < 2; z++) {\n        for (int y = 0; y < 2; y++) {\n            for (int x = 0; x < 2; x++) {\n                int i = INDEX3(x,y,z,2,2);\n                if (neighbour_exists[i]) {\n                    double *data = out.getSampleDataRW(\n                                           x*(m_NN[0]-1)\n                                         + y*(m_NN[1]-1)*m_NN[0]\n                                         + z*(m_NN[2]-1)*m_NN[0]*m_NN[1]\n                                        );\n\n                    MPI_Isend(data, numComp, MPI_DOUBLE, neighbour_ranks[i], tag,\n                            m_mpiInfo->comm, request+i);\n                }\n            }\n        }\n    }\n\n    //recv\n    for (int z = 0; z < 2; z++) {\n        for (int y = 0; y < 2; y++) {\n            for (int x = 0; x < 2; x++) {\n                int i = INDEX3(x,y,z,2,2);\n                if (neighbour_exists[i]) {\n                    double *data = out.getSampleDataRW(\n                                           x*(m_NN[0]-1)\n                                         + y*(m_NN[1]-1)*m_NN[0]\n                                         + z*(m_NN[2]-1)*m_NN[0]*m_NN[1]\n                                        );\n\n                    MPI_Recv(&inbuf[0], numComp, MPI_DOUBLE, neighbour_ranks[i],\n                            tag, m_mpiInfo->comm, &status);\n                    //unpack\n                    for (int comp = 0; comp < numComp; comp++) {\n                        data[comp] += inbuf[comp];\n                    }\n                }\n            }\n        }\n    }\n\n    //wait\n    for (int i = 0; i < 8; i++) {\n        if (neighbour_exists[i]) {\n            MPI_Wait(request+i, &status);\n        }\n    }\n}\n\n//private\nvoid Brick::shareEdges(escript::Data& out, int rx, int ry, int rz) const\n{\n    const int rank = m_mpiInfo->rank;\n\n    const int tag = 0;\n    MPI_Status status[12];\n    MPI_Request request[12];\n    const int numComp = out.getDataPointSize();\n\n    const bool left = rx;\n    const bool right = rx < m_NX[0] - 1;\n    const bool front = ry;\n    const bool back = ry < m_NX[1] - 1;\n    const bool bottom = rz;\n    const bool top = rz < m_NX[2] - 1;\n\n    //BEGIN SEND\n    int reqNum = 0;\n    if (left) {\n        if (front) { //share Z lines\n            int neighbour = rank - m_NX[0] - 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0, 0, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (back) {//share Z lines\n            int neighbour = rank + m_NX[0] - 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0,m_NN[1]-1,i,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (top) {//share Y lines\n            int neighbour = rank + m_NX[0]*m_NX[1] - 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0,i,m_NN[2]-1,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (bottom) {//share Y lines\n            int neighbour = rank - m_NX[0]*m_NX[1] - 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0,i,0,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n    }\n    if (right) {\n        if (front) { //share Z lines\n            int neighbour = rank - m_NX[0] + 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                            INDEX3(m_NN[0]-1, 0, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (back) {//share Z lines\n            int neighbour = rank + m_NX[0] + 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                            INDEX3(m_NN[0]-1, m_NN[1]-1, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (top) {//share Y lines\n            int neighbour = rank + m_NX[0]*m_NX[1] + 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(m_NN[0]-1,i,m_NN[2]-1,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (bottom) {//share Y lines\n            int neighbour = rank - m_NX[0]*m_NX[1] + 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> outbuf(count);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(m_NN[0]-1,i,0,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    outbuf[i*numComp + comp] = data[comp];\n                }\n            }\n            MPI_Isend(&outbuf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n    }\n\n    if (top) {\n        const dim_t count = m_NN[0]*numComp;\n        std::vector<double> buf(count);\n        if (front) {//share X lines\n            int neighbour = rank + m_NX[0]*m_NX[1] - m_NX[0];\n            double *data = out.getSampleDataRW(m_NN[0]*m_NN[1]*(m_NN[2]-1));\n            MPI_Isend(data, count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (back) {//share X lines\n            int neighbour = rank + m_NX[0]*m_NX[1] + m_NX[0];\n            double *data = out.getSampleDataRW(m_NN[0]*m_NN[1]*(m_NN[2]-1)\n                                             + m_NN[0]*(m_NN[1]-1));\n            MPI_Isend(data, count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n    }\n    if (bottom) {\n        const dim_t count = m_NN[0]*numComp;\n        std::vector<double> buf(count);\n        if (front) {//share X lines\n            int neighbour = rank - m_NX[0]*m_NX[1] - m_NX[0];\n            double *data = out.getSampleDataRW(0);\n            MPI_Isend(data, count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n        if (back) {//share X lines\n            int neighbour = rank - m_NX[0]*m_NX[1] + m_NX[0];\n            double *data = out.getSampleDataRW(m_NN[0]*(m_NN[1]-1));\n            MPI_Isend(data, count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, request + reqNum++);\n        }\n    }\n    //END SEND\n    \n    //BEGIN RECV\n    if (left) {\n        if (front) { //share Z lines\n            int neighbour = rank - m_NX[0] - 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0, 0, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n        if (back) {//share Z lines\n            int neighbour = rank + m_NX[0] - 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0,m_NN[1]-1,i,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n        if (top) {//share Y lines\n            int neighbour = rank + m_NX[0]*m_NX[1] - 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0,i,m_NN[2]-1,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n        if (bottom) {//share Y lines\n            int neighbour = rank - m_NX[0]*m_NX[1] - 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(0,i,0,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n    }\n    if (right) {\n        if (front) { //share Z lines\n            int neighbour = rank - m_NX[0] + 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                            INDEX3(m_NN[0]-1, 0, i, m_NN[0], m_NN[1]));     \n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n        if (back) {//share Z lines\n            int neighbour = rank + m_NX[0] + 1;\n            const dim_t count = m_NN[2]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[2]; i++) {\n                double *data = out.getSampleDataRW(\n                            INDEX3(m_NN[0]-1, m_NN[1]-1, i, m_NN[0], m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n        if (top) {//share Y lines\n            int neighbour = rank + m_NX[0]*m_NX[1] + 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(m_NN[0]-1,i,m_NN[2]-1,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n        if (bottom) {//share Y lines\n            int neighbour = rank - m_NX[0]*m_NX[1] + 1;\n            const dim_t count = m_NN[1]*numComp;\n            std::vector<double> buf(count);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < m_NN[1]; i++) {\n                double *data = out.getSampleDataRW(INDEX3(m_NN[0]-1,i,0,m_NN[0],m_NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += buf[i*numComp + comp];\n                }\n            }\n        }\n    }\n\n    if (top) {\n        const dim_t count = m_NN[0]*numComp;\n        std::vector<double> buf(count);\n        if (front) {//share X lines\n            int neighbour = rank + m_NX[0]*m_NX[1] - m_NX[0];\n            double *data = out.getSampleDataRW(m_NN[0]*m_NN[1]*(m_NN[2]-1));\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < count; i++) {\n                data[i] += buf[i];\n            }\n        }\n        if (back) {//share X lines\n            int neighbour = rank + m_NX[0]*m_NX[1] + m_NX[0];\n            double *data = out.getSampleDataRW(m_NN[0]*m_NN[1]*(m_NN[2]-1)\n                                             + m_NN[0]*(m_NN[1]-1));\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < count; i++) {\n                data[i] += buf[i];\n            }\n        }\n    }\n    if (bottom) {\n        const dim_t count = m_NN[0]*numComp;\n        std::vector<double> buf(count);\n        if (front) {//share X lines\n            int neighbour = rank - m_NX[0]*m_NX[1] - m_NX[0];\n            double *data = out.getSampleDataRW(0);\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < count; i++) {\n                data[i] += buf[i];\n            }\n        }\n        if (back) {//share X lines\n            int neighbour = rank - m_NX[0]*m_NX[1] + m_NX[0];\n            double *data = out.getSampleDataRW(m_NN[0]*(m_NN[1]-1));\n            MPI_Recv(&buf[0], count, MPI_DOUBLE, neighbour, tag,\n                    m_mpiInfo->comm, status);\n#pragma omp parallel for\n            for (dim_t i = 0; i < count; i++) {\n                data[i] += buf[i];\n            }\n        }\n    }\n    //END RECV\n    \n    //finally, wait for all those Isends to be complete\n    MPI_Waitall(reqNum, request, status);\n}\n\n\nvoid frontAndBack(escript::Data& out, int ry, const int numComp, int rank,\n                    const dim_t NN[3], const int NX[3], MPI_Comm& comm) {\n    MPI_Status status;\n    const int front_neighbour = rank - NX[0];\n    const int back_neighbour = rank + NX[0];\n    const dim_t count = NN[0]*NN[2]*numComp;\n    std::vector<double> front(count);\n    std::vector<double> back(count);\n    std::vector<double> recv(count);\n#pragma omp parallel for\n    for (dim_t z = 0; z < NN[2]; z++) {\n        for (dim_t x = 0; x < NN[0]; x++) {\n            const dim_t index = INDEX2(x,z,NN[0])*numComp;\n            const double *frontData = out.getSampleDataRO(INDEX3(x, 0, z, NN[0], NN[1]));\n            std::copy(frontData, frontData + numComp, &front[index]);\n\n            const double *backData = out.getSampleDataRO(INDEX3(x, NN[1]-1, z, NN[0], NN[1]));\n            std::copy(backData, backData + numComp, &back[index]);\n        }\n    }\n\n    MPI_Request request[2];\n    if (ry) {\n        MPI_Isend(&front[0], count, MPI_DOUBLE, front_neighbour, rank,\n            comm, request);\n    }\n    \n    if (ry < NX[1] - 1) {\n        MPI_Isend(&back[0], count, MPI_DOUBLE, back_neighbour, rank,\n            comm, request+1);\n    }\n    \n    //front\n    if (ry) {\n        MPI_Recv(&recv[0], count, MPI_DOUBLE, front_neighbour, front_neighbour,\n                    comm, &status);\n        //unpack front\n#pragma omp parallel for\n        for (dim_t z = 0; z < NN[2]; z++) {\n            for (dim_t x = 0; x < NN[0]; x++) {\n                const dim_t index = INDEX2(x,z,NN[0])*numComp;\n                double *data = out.getSampleDataRW(INDEX3(x, 0, z, NN[0], NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += recv[index+comp];\n                }\n            }\n        }\n    }\n\n    //back\n    if (ry < NX[1] - 1) {\n        MPI_Recv(&recv[0], count, MPI_DOUBLE, back_neighbour, back_neighbour,\n                comm, &status);\n        //unpack back\n#pragma omp parallel for\n        for (dim_t z = 0; z < NN[2]; z++) {\n            for (dim_t x = 0; x < NN[0]; x++) {\n                const dim_t index = INDEX2(x,z,NN[0])*numComp;\n                double *data = out.getSampleDataRW(INDEX3(x, NN[1] - 1, z, NN[0], NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += recv[index+comp];\n                }\n            }\n        }\n    }\n    \n    if (ry) {\n        MPI_Wait(request, &status);\n    }\n    if (ry < NX[1] - 1) {\n        MPI_Wait(request+1, &status);\n    }\n}\n\nvoid topAndBottom(escript::Data& out, int rz, int numComp, int rank,\n                    const dim_t NN[3], const int NX[3], MPI_Comm& comm) {\n    MPI_Status status;\n    const int top_neighbour = rank + NX[0]*NX[1];\n    const int bottom_neighbour = rank - NX[0]*NX[1];\n    const dim_t count = NN[0]*NN[1]*numComp;\n    std::vector<double> top(count);\n    std::vector<double> bottom(count);\n    std::vector<double> recv(count);\n#pragma omp parallel for\n    for (dim_t y = 0; y < NN[1]; y++) {\n        for (dim_t x = 0; x < NN[0]; x++) {\n            const dim_t index = INDEX2(x,y,NN[0])*numComp;\n            const double *bottomData = out.getSampleDataRO(INDEX2(x, y, NN[0]));\n            std::copy(bottomData, bottomData + numComp, &bottom[index]);\n\n            const double *topData = out.getSampleDataRO(INDEX3(x, y, NN[2]-1, NN[0], NN[1]));\n            std::copy(topData, topData + numComp, &top[index]);\n        }\n    }\n\n    MPI_Request request[2];\n    if (rz) {\n        MPI_Isend(&bottom[0], count, MPI_DOUBLE, bottom_neighbour, rank,\n            comm, request);\n    }\n   \n    if (rz < NX[2] - 1) {\n        MPI_Isend(&top[0], count, MPI_DOUBLE, top_neighbour, rank,\n            comm, request + 1);\n    }\n\n    //bottom\n    if (rz) {\n        MPI_Recv(&recv[0], count, MPI_DOUBLE, bottom_neighbour,\n                bottom_neighbour, comm, &status);\n        //unpack to bottom\n#pragma omp parallel for\n        for (dim_t y = 0; y < NN[1]; y++) {\n            for (dim_t x = 0; x < NN[0]; x++) {\n                const dim_t index = INDEX2(x,y,NN[0])*numComp;\n                double *data = out.getSampleDataRW(INDEX2(x, y, NN[0]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += recv[index+comp];\n                }\n            }\n        }\n    }\n\n    //top\n    if (rz < NX[2] - 1) {\n        MPI_Recv(&recv[0], count, MPI_DOUBLE, top_neighbour, top_neighbour,\n                    comm, &status);\n        //unpack to top\n#pragma omp parallel for\n        for (dim_t y = 0; y < NN[1]; y++) {\n            for (dim_t x = 0; x < NN[0]; x++) {\n                const dim_t index = INDEX2(x,y,NN[0])*numComp;\n                double *data = out.getSampleDataRW(INDEX3(x, y, NN[2]-1, NN[0], NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += recv[index+comp];\n                }\n            }\n        }\n    }\n    if (rz) {\n        MPI_Wait(request, &status);\n    }\n    if (rz < NX[2] - 1) {\n        MPI_Wait(request+1, &status);\n    }\n}\n\n\nvoid leftAndRight(escript::Data& out, int rx, int numComp, int rank,\n                    const dim_t NN[3], const int NX[3], MPI_Comm& comm) {\n    MPI_Status status;\n    const int left_neighbour = rank - 1;\n    const int right_neighbour = rank + 1;\n    const dim_t count = NN[2]*NN[1]*numComp;\n    std::vector<double> left(count);\n    std::vector<double> right(count);\n    std::vector<double> recv(count);\n#pragma omp parallel for\n    for (dim_t z = 0; z < NN[2]; z++) {\n        for (dim_t y = 0; y < NN[1]; y++) {\n            const dim_t index = INDEX2(y,z,NN[1])*numComp;\n            const double *leftData = out.getSampleDataRO(INDEX3(0, y, z, NN[0], NN[1]));\n            std::copy(leftData, leftData + numComp, &left[index]);\n\n            const double *rightData = out.getSampleDataRO(INDEX3(NN[0]-1, y, z, NN[0], NN[1]));\n            std::copy(rightData, rightData + numComp, &right[index]);\n        }\n\n    }\n\n    MPI_Request request[2];\n\n    //right send\n    if (rx < NX[0] - 1) {\n        MPI_Isend(&right[0], count, MPI_DOUBLE, right_neighbour,\n                rank, comm, request);\n    }\n    //left send\n    if (rx) {\n        MPI_Isend(&left[0], count, MPI_DOUBLE, left_neighbour,\n                rank, comm, request+1);\n    }\n    \n    //right recv\n    if (rx < NX[0] - 1) {    \n        MPI_Recv(&recv[0], count, MPI_DOUBLE, right_neighbour, right_neighbour,\n                comm, &status);\n        //unpack to right\n#pragma omp parallel for\n        for (dim_t z = 0; z < NN[2]; z++) {\n            for (dim_t y = 0; y < NN[1]; y++) {\n                const dim_t index = INDEX2(y,z,NN[1])*numComp;\n                double *data = out.getSampleDataRW(INDEX3(NN[0]-1, y, z, NN[0], NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += recv[index+comp];\n                }\n            }\n        }\n    }\n    //left\n    if (rx) {\n        MPI_Recv(&recv[0], count, MPI_DOUBLE, left_neighbour, left_neighbour,\n                comm, &status);\n        //unpack to left\n#pragma omp parallel for\n        for (dim_t z = 0; z < NN[2]; z++) {\n            for (dim_t y = 0; y < NN[1]; y++) {\n                const dim_t index = INDEX2(y,z,NN[1])*numComp;\n                double *data = out.getSampleDataRW(INDEX3(0, y, z, NN[0], NN[1]));\n                for (int comp = 0; comp < numComp; comp++) {\n                    data[comp] += recv[index+comp];\n                }\n            }\n        }\n    }\n    if (rx) {\n        MPI_Wait(request+1, &status);\n    }\n    if (rx < NX[0] - 1) {\n        MPI_Wait(request, &status);\n    }\n}\n\n\n//private\nvoid Brick::shareFaces(escript::Data& out, int rx, int ry, int rz) const\n{\n    const int numComp = out.getDataPointSize();\n    if (m_NX[0] != 1)\n        leftAndRight(out, rx, numComp, m_mpiInfo->rank, m_NN, m_NX, m_mpiInfo->comm);\n    if (m_NX[1] != 1)\n        frontAndBack(out, ry, numComp, m_mpiInfo->rank, m_NN, m_NX, m_mpiInfo->comm);\n    if (m_NX[2] != 1)\n        topAndBottom(out, rz, numComp, m_mpiInfo->rank, m_NN, m_NX, m_mpiInfo->comm);\n}\n#endif //#ifdef ESYS_MPI\n\n\nescript::Data Brick::randomFill(const escript::DataTypes::ShapeType& shape,\n                                const escript::FunctionSpace& fs, long seed,\n                                const boost::python::tuple& filter) const\n{\n    const int numvals = escript::DataTypes::noValues(shape);\n    const int per_element = (m_order+1)*(m_order+1)*(m_order+1)*numvals;\n    if (len(filter) > 0) {\n        throw SpeckleyException(\"Speckley does not support filters.\");\n    }\n\n    double* src = new double[m_NE[0]*m_NE[1]*m_NE[2]*per_element*numvals];\n    escript::randomFillArray(seed, src, m_NE[0]*m_NE[1]*m_NE[2]*per_element);\n    escript::Data res(0, shape, escript::function(*this), true);\n    int current = 0;\n    for (index_t ei = 0; ei < m_NE[2]; ++ei) {\n        for (index_t ej = 0; ej < m_NE[1]; ++ej) {\n            for (index_t ek = 0; ek < m_NE[0]; ++ek) {\n                double *e = res.getSampleDataRW(INDEX3(ek,ej,ei,m_NE[0],m_NE[1]));\n                memcpy(e, &src[current], sizeof(double)*per_element);\n                current += per_element;\n            }\n        }\n    }\n    delete[] src;\n\n    if (res.getFunctionSpace() != fs) {\n        return escript::Data(res, fs);\n    }\n    return res;\n}\n\nescript::Data Brick::randomFillWorker(const escript::DataTypes::ShapeType& shape,\n        long seed, const boost::python::tuple& filter) const {\n    throw SpeckleyException(\"Brick::randomFillWorker not yet implemented\");\n}\n\nindex_t Brick::findNode(const double *coords) const {\n    const index_t NOT_MINE = -1;\n    //is the found element even owned by this rank\n    for (int dim = 0; dim < m_numDim; dim++) {\n        double min = m_origin[dim] + m_offset[dim]* m_dx[dim]\n                - m_dx[dim]/2.; //allows for point outside mapping onto node\n        double max = m_origin[dim] + (m_offset[dim] + m_NE[dim])*m_dx[dim]\n                + m_dx[dim]/2.;\n        if (min > coords[dim] || max < coords[dim]) {\n            return NOT_MINE;\n        }\n    }\n    // get distance from subdivision origin\n    double x = coords[0] - m_origin[0] - m_offset[0]*m_dx[0];\n    double y = coords[1] - m_origin[1] - m_offset[1]*m_dx[1];\n    double z = coords[2] - m_origin[2] - m_offset[2]*m_dx[2];\n\n    // distance in elements\n    dim_t ex = (dim_t) floor((x + 0.01*m_dx[0]) / m_dx[0]);\n    dim_t ey = (dim_t) floor((y + 0.01*m_dx[1]) / m_dx[1]);\n    dim_t ez = (dim_t) floor((z + 0.01*m_dx[2]) / m_dx[2]);\n    dim_t start = m_order*(INDEX3(ex,ey,ez,m_NN[0],m_NN[1]));\n    // set the min distance high enough to be outside the element plus a bit\n    index_t closest = NOT_MINE;\n    double minDist = 1;\n    for (int dim = 0; dim < m_numDim; dim++) {\n        minDist += m_dx[dim]*m_dx[dim];\n    }\n    //find the closest node\n    for (int dx = 0; dx < 2; dx++) {\n        double xdist = x - (ex + dx)*m_dx[0];\n        for (int dy = 0; dy < 2; dy++) {\n            double ydist = y - (ey + dy)*m_dx[1];\n            for (int dz = 0; dz < 2; dz++) {\n                double zdist = z - (ez + dz)*m_dx[2];\n                double total = xdist*xdist + ydist*ydist + zdist*zdist;\n                if (total < minDist) {\n                    closest = start + INDEX3(m_order*dx,dy,dz,m_NN[0],m_NN[1]);\n                    minDist = total;\n                }\n            }\n        }\n    }\n    //if this happens, we've let a dirac point slip through, which is awful\n    if (closest == NOT_MINE) {\n        throw SpeckleyException(\"Unable to map appropriate dirac point to a \"\n                \"node, implementation problem in Brick::findNode()\");\n    }\n    return closest;\n}\n\nAssembler_ptr Brick::createAssembler(std::string type,\n        const DataMap& options) const {\n    if (type.compare(\"DefaultAssembler\") == 0) {\n        return Assembler_ptr(new DefaultAssembler3D(shared_from_this(), m_dx,\n                m_NE, m_NN));\n    } else if (type.compare(\"WaveAssembler\") == 0) {\n        return Assembler_ptr(new WaveAssembler3D(shared_from_this(), m_dx, m_NE, m_NN, options));\n    } else { //else ifs would go before this for other types\n        throw SpeckleyException(\"Speckley::Brick does not support the\"\n                                \" requested assembler\");\n    }\n}\n\nbool Brick::probeInterpolationAcross(int fsType_source,\n        const escript::AbstractDomain& domain, int fsType_target) const\n{\n#ifdef USE_RIPLEY\n    return speckley::probeInterpolationAcross(fsType_source, domain,\n            fsType_target, 3);\n#else\n    return false;\n#endif\n}\n\nvoid Brick::interpolateAcross(escript::Data& target, const escript::Data& source) const\n{\n#ifdef USE_RIPLEY\n    if (coupler == NULL) {\n        coupler = new RipleyCoupler(this, m_dx, m_mpiInfo->rank);\n    }\n    coupler->interpolate(target, source);\n#else\n    throw SpeckleyException(\"Speckley::Brick interpolation to unsupported domain\");\n#endif\n}\n\n} // end of namespace speckley\n\n", "meta": {"hexsha": "6c18ca311190c4a77e1a47b37eb52958f72d6e9c", "size": 108835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "speckley/src/Brick.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "speckley/src/Brick.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "speckley/src/Brick.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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.490527041, "max_line_length": 134, "alphanum_fraction": 0.5171498139, "num_tokens": 30727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.04208772641371776, "lm_q1q2_score": 0.020058153968313067}}
{"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) 2013-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 NUMAMATRIX_HH\n#define NUMAMATRIX_HH\n\n#include <algorithm>\n#include <cassert>\n#include <vector>\n\n#include <boost/iterator/iterator_facade.hpp>\n\n#include \"linalg/dynamicMatrix.hh\"\n#include \"utilities/threading.hh\"\n\nnamespace Kaskade {\n  \n  // forward declaration\n  template <class Entry> class NumaDenseMatrix;\n  \n  /**\n   * \\cond internals\n   */\n  namespace NumaDenseMatrixDetail\n  {\n    \n    template <class Entry>\n    class ColumnIterator: public boost::iterator_facade<ColumnIterator<Entry>,Entry,boost::random_access_traversal_tag>\n    {\n    public:\n      ColumnIterator() = default;\n      \n      ColumnIterator(Entry* base_, size_t stride_, size_t idx_=0)\n      : base(base_), stride(stride_), idx(idx_) {}\n      \n      size_t index() const { return idx; }\n      \n    private:\n      friend class boost::iterator_core_access;\n      \n      bool equal(ColumnIterator<Entry> const& p) const\n      {\n        return idx==p.idx;\n      }\n      \n      void increment() { ++idx; }\n      void decrement() { --idx; }\n      void advance(typename ColumnIterator<Entry>::difference_type n) { idx += n; }\n      template <class E>\n      typename ColumnIterator<Entry>::difference_type distance_to(ColumnIterator<E> const& i) const { return i.idx - idx; }\n      \n      \n      Entry& dereference() const { return base[idx*stride]; }\n      \n      Entry* base;\n      size_t stride;\n      size_t idx;\n    };\n    \n    // ----------------------------------------------------------------------------------------------\n    \n    template <class Entry>\n    class Row \n    {\n    public:\n      typedef ColumnIterator<Entry> iterator;\n      typedef ColumnIterator<Entry const> const_iterator;\n      \n      Row() = default;\n      \n      Row(Entry* first_, size_t stride_, std::size_t cols_)\n      : first(first_), stride(stride_), cols(cols_) {}\n      \n      iterator begin() { return iterator(first,stride,0); }\n      iterator end()   { return iterator(first,stride,cols); }\n      const_iterator begin() const { return const_iterator(first,stride,0); }\n      const_iterator end()   const { return const_iterator(first,stride,cols); }\n      \n      Entry&       operator[](size_t c)       { return first[stride*c]; }\n      Entry const& operator[](size_t c) const { return first[stride*c]; }\n      \n    private:\n      Entry* first;\n      size_t stride;\n      size_t cols;\n    };\n    \n    // ----------------------------------------------------------------------------------------------\n\n    template <class Entry>\n    class RowIterator: public boost::iterator_facade<RowIterator<Entry>,\n                                                     typename std::conditional<std::is_const<Entry>::value,\n                                                                               Row<typename std::remove_const<Entry>::type> const,\n                                                                               Row<Entry>>::type,\n                                                     boost::random_access_traversal_tag>\n    {\n      typedef typename std::remove_const<Entry>::type NonConstEntry;\n      \n      typedef typename std::conditional<std::is_const<Entry>::value,\n                                        NumaDenseMatrix<NonConstEntry> const,\n                                        NumaDenseMatrix<Entry>>::type Matrix;\n      \n      typedef boost::iterator_facade<RowIterator<Entry>,\n                                    typename std::conditional<std::is_const<Entry>::value,\n                                                              Row<NonConstEntry> const,\n                                                              Row<Entry>>::type,\n                                    boost::random_access_traversal_tag> Base;\n      \n      \n    public:\n      RowIterator() = default;\n      \n      RowIterator(Matrix& mat_, size_t idx_)\n      : mat(&mat_) \n      {\n        update(idx_);\n      }\n      \n      size_t index() const { return idx; }\n      \n    private:\n      friend class boost::iterator_core_access;\n      using DifferenceType = Base::difference_type;\n      \n      bool equal(RowIterator<Entry> const& other) const { return idx==other.idx;}\n      void increment() { update(idx+1); }\n      void decrement() { update(idx-1); }\n      void advance(typename RowIterator<Entry>::difference_type n) { update(idx+n); }\n      template <class E> DifferenceType distance_to(RowIterator<E> const& i) const { return static_cast<DifferenceType>(i.idx) - idx; }\n      typename Base::reference dereference() const { return row; } \n      \n      // moves row as to represent row with index newidx.\n      void update(size_t newidx)\n      {\n        idx = newidx;\n        if (idx<mat->N()) // to not trip over the edge when arriving at end()\n        {\n          size_t chunk = uniformWeightRange(idx,mat->chunks.size(),mat->N());\n          size_t rowStart = uniformWeightRangeStart(chunk,mat->chunks.size(),mat->N());\n          size_t stride = uniformWeightRangeStart(chunk+1,mat->chunks.size(),mat->N()) - rowStart; // that's \"LDA\"\n          row = typename Base::value_type(const_cast<NonConstEntry*>(&mat->chunks[chunk][idx-rowStart]),stride,mat->M());\n        }\n      }\n      \n      Matrix* mat;\n      size_t idx; // row index\n      mutable typename Base::value_type row; // dereference is const method, but can \"point to\" mutable row value type..\n    };\n\n    // ----------------------------------------------------------------------------------------------\n\n    template <class T, int n>\n    typename Dune::FieldTraits<T>::field_type frobenius_product(Dune::FieldVector<T,n> const& x, Dune::FieldVector<T,n> const& y) \n    { \n      typename Dune::FieldTraits<T>::field_type result = 0;\n      for (int i=0; i<n; ++i)\n        result += frobenius_product(x[i],y[i]);\n      return result;\n    }\n    \n    template <class T, int n, int m>\n    typename Dune::FieldTraits<T>::field_type frobenius_product(Dune::FieldMatrix<T,n,m> const& x, Dune::FieldMatrix<T,n,m> const& y) \n    { \n      typename Dune::FieldTraits<T>::field_type result = 0;\n      for (int i=0; i<n; ++i)\n        for (int j=0; j<m; ++j)\n          result += frobenius_product(x[i][j],y[i][j]);\n      return result;\n    }\n    \n    double frobenius_product(double x, double y) { return x*y; }\n    float  frobenius_product(float x, float y)  { return x*y; }\n    \n    \n    \n    template <class T, int n>\n    typename Dune::FieldTraits<typename Dune::FieldTraits<T>::field_type>::real_type frobenius_norm2(Dune::FieldVector<T,n> const& x) { return x.two_norm2(); }\n    \n    template <class T, int n, int m>\n    typename Dune::FieldTraits<typename Dune::FieldTraits<T>::field_type>::real_type frobenius_norm2(Dune::FieldMatrix<T,n,m> const& x) { return x.frobenius_norm2(); }\n    \n    double frobenius_norm2(double x) { return x*x; }\n    float  frobenius_norm2(float x)  { return x*x; }\n    \n    \n    template <class T, int n>\n    typename Dune::FieldTraits<typename Dune::FieldTraits<T>::field_type>::real_type one_norm(Dune::FieldVector<T,n> const& x) { return x.one_norm(); }\n    \n    template <class T, int n, int m>\n    typename Dune::FieldTraits<typename Dune::FieldTraits<T>::field_type>::real_type one_norm(Dune::FieldMatrix<T,n,m> const& x) { return x.one_norm(); }\n    \n    double one_norm(double x) { return std::abs(x); }\n    float  one_norm(float x)  { return std::abs(x); }\n    \n    template <class T, int n>\n    void axpy(Dune::FieldVector<T,n>& y, typename Dune::FieldTraits<T>::field_type const& a, Dune::FieldVector<T,n> const& x) { y.axpy(a,x); }\n    \n    template <class T, int n, int m>\n    void axpy(Dune::FieldMatrix<T,n,m>& y, typename Dune::FieldTraits<T>::field_type const& a, Dune::FieldMatrix<T,n,m> const& x) { y += a*x; }\n    \n    void axpy(double& y, double a, double x) { y += a*x; }\n    void axpy(float& y,  float a,  float x) { y += a*x; }\n    \n    // ----------------------------------------------------------------------------------------------\n    \n    // forward declaration\n    template <class Entry> class VectorIterator;\n\n    /**\n     * \\ingroup linalgbasic\n     * \\brief A base class for dense matrix and vector classes.\n     * \n     * This distributes the entries across several NUMA nodes by storing a contiguous block of rows (chunk) on each node.\n     * In each chunk, the entries are stored column-major, i.e. as a LAPACK dense matrix.\n     */\n    template <class Entry>\n    class NumaDenseBase\n    {\n    protected:\n      typedef std::vector<Entry,NumaAllocator<Entry>> Chunk;  // the actual data storage type\n      typedef NumaDenseBase<Entry> Self;                      \n      \n    public:\n      typedef size_t      size_type;\n      typedef Entry       value_type;\n      \n      /**\n       * \\brief the type of the scalar field.\n       */\n      typedef typename Dune::FieldTraits<Entry>::field_type     field_type;\n      typedef typename Dune::FieldTraits<field_type>::real_type real_type;\n      \n      /**\n       * \\brief the type of matrix entries.\n       */\n      typedef Entry block_type;\n      \n      /**\n       * \\name Construction and assignment\n       * @{\n       */\n      \n      /**\n       * \\brief Creates a 0 x 0 matrix.\n       */\n      NumaDenseBase (): NumaDenseBase(0,0)\n      {\n      } \n      \n      /**\n       * \\brief Copy constructor.\n       */\n      NumaDenseBase (NumaDenseBase const& other)\n      : rows(other.rows), cols(other.cols), chunks(other.chunks.size())\n      {\n        parallelForNodes([&](int i, int n) // perform data copy on the respective\n        {                                  // NUMA node\n          chunks[i] = other.chunks[i];\n        });\n      }\n      \n      /**\n       * \\brief Move constructor.\n       */\n      NumaDenseBase(NumaDenseBase&& a) = default;\n      \n      /**\n       * \\brief Creates an r x c matrix with given entries.\n       */\n      NumaDenseBase (size_type r, size_type c, value_type v = value_type()) :\n      rows(r), cols(c)\n      {\n        size_type n = NumaThreadPool::instance().nodes();\n        chunks.reserve(n);\n        for (size_type i=0; i<n; ++i)\n          chunks.emplace_back((uniformWeightRangeStart(i+1,n,r)-uniformWeightRangeStart(i,n,r))*c,v,NumaAllocator<Entry>(i));\n      }\n      \n      /**\n       * \\brief Copy assignment.\n       */\n      NumaDenseBase& operator=(NumaDenseBase const& other)\n      {\n        assert(chunks.size() == other.chunks.size()); // this can only be violated if the number of NUMA nodes changes...\n        rows = other.rows;\n        cols = other.cols;\n        parallelForNodes([&](int i, int n) // perform data copy on the respective\n        {                                  // NUMA node\n          chunks[i] = other.chunks[i];\n        });\n      }\n      \n      /**\n       * \\brief Assignment from scalar. \n       */\n      Self& operator=(field_type const& a)\n      {\n        for_each([&](Entry& e) { e = a; }); \n      }\n      \n      /// @}\n\n    protected:\n      /**\n       * \\brief Resizes the matrix to r x c, leaving the entries in an undefined state.\n       * \n       * On resize, all row objects and iterators are invalidated. This method adheres to the Dune::DynamicMatrix interface.\n       */\n      void resize (size_type r, size_type c)\n      {\n        // Check whether we need to change anything. Note that due to row blocking,\n        // the check rows*cols==n*m is NOT sufficient (the distribution of rows on \n        // NUMA nodes may change nevertheless).\n        if (rows==r && cols==c)\n          return;\n        \n        rows = r;\n        cols = c;\n        for (int i=0; i<chunks.size(); ++i) // TODO: parallelize\n          chunks[i].resize((uniformWeightRangeStart(i+1,chunks.size(),r)-uniformWeightRangeStart(i,chunks.size(),r))*c);\n      }\n\n    public:\n      /**\n       * \\brief Return the number of rows. \n       */\n      size_type N() const { return rows; }\n      \n    protected:\n      /**\n       * \\brief Return the number of rows. \n       */\n      size_type M() const { return cols; }\n      \n      \n      /**\n       * \\brief scalar product\n       */\n      field_type dot(Self const& other) const\n      {\n        assert(rows==other.rows && cols==other.cols);\n        std::vector<field_type> dots(chunks.size());\n        parallelForNodes([&](int i, int n) \n        {\n          assert(n==chunks.size());\n          field_type sum = 0;\n          for (size_t k=0; k<chunks[i].size(); ++k)\n            sum += NumaDenseMatrixDetail::frobenius_product(chunks[i][k],other.chunks[i][k]);\n          dots[i] = sum;\n        });\n        return std::accumulate(dots.begin(),dots.end(),0);\n      }\n      \n      /**\n       * \\brief Performs a (parallel) accumulation procedure.\n       * \n       * Note that this groups the operations in a different way than the std::accumulate, and hence \n       * gives only the same results if the operation F is associative.\n       */\n      template <class Result, class F>\n      Result accumulate(F f, Result const& init) const\n      {\n        std::vector<Result> rs(chunks.size());\n        parallelForNodes([&](int i, int n) \n        {\n          assert(n==this->chunks.size());\n          Result r = init;\n          for (auto const& e: chunks[i])\n            r = f(r,e);\n          rs[i] = r;\n        });\n        return std::accumulate(rs.begin()+1,rs.end(),rs[0],f);\n      }\n      \n      /**\n       * \\brief Applies the given functor to all matrix entries.\n       */\n      template <class F>\n      void for_each(F const& f) \n      {\n        parallelForNodes([&](int i, int n) \n        {\n          assert(n==this->chunks.size());\n          std::for_each(begin(chunks[i]),end(chunks[i]),f);\n        });\n      }\n      \n      /**\n       * \\brief Applies the given functor to pairs of corresponding matrix elements.\n       */\n      template <class F>\n      void for_each2(F const& f, Self const& other) \n      {\n        assert(rows==other.rows && cols==other.cols);\n        parallelForNodes([&](int i, int n) \n        {\n          assert(n==this->chunks.size());\n          for (size_t j=0; j<chunks[i].size(); ++j)\n            f(chunks[i][j],other.chunks[i][j]);\n        });\n      }\n      \n    private:\n      friend class NumaDenseMatrixDetail::RowIterator<Entry>;\n      friend class NumaDenseMatrixDetail::RowIterator<Entry const>;\n      friend class NumaDenseMatrixDetail::VectorIterator<Entry>;\n      friend class NumaDenseMatrixDetail::VectorIterator<Entry const>;\n      \n      size_type rows, cols;      // the matrix dimensions\n      std::vector<Chunk> chunks; // for each NUMA node a separate array to store the entries\n    };\n    \n  }\n  /**\n   * \\endcond \n   */\n  \n  //-------------------------------------------------------------------------------------------\n  \n  /**\n   * \\ingroup linalgbasic\n   * \\brief A dense matrix class tailored towards NUMA architectures.\n   * \n   * The class satisfies the Dune ISTL recursive matrix interface similar to Dune::Matrix. The data storage, however,\n   * is organized in such a way as to benefit from NUMA architectures: the rows of the matrix are distributed evenly \n   * over the nodes. This implies that a good load balancing can only be achieved for matrices with (significantly) \n   * more rows than NUMA nodes. Avoid flat, long matrices.\n   * \n   * There is no guarantee about placement or ordering of matrix elements, in particular none about the \n   * contiguity of element storage.\n   * \n   * \\tparam Entry the entry type (usually a Dune::FieldMatrix<n,m,double>)\n   * \n   * \\TODO: Currently, the implementation is mainly intended to gather a bag of coefficient vectors in one place,\n   * rather than to provide a fully-fledged matrix class.\n   */\n  template <class Entry>\n  class NumaDenseMatrix: public NumaDenseMatrixDetail::NumaDenseBase<Entry>\n  {\n    typedef NumaDenseMatrix<Entry> Self;\n    typedef NumaDenseMatrixDetail::NumaDenseBase<Entry> Base;\n    \n  public:\n    typedef size_t      size_type;\n    typedef Entry       value_type;\n    \n    /**\n     * \\brief the type of the scalar field.\n     */\n    typedef typename Dune::FieldTraits<Entry>::field_type         field_type;\n    typedef typename Dune::FieldTraits<field_type>::real_type     real_type;\n    \n    typedef NumaDenseMatrixDetail::RowIterator<Entry>       RowIterator;\n    typedef NumaDenseMatrixDetail::RowIterator<Entry const> ConstRowIterator;\n\n    typedef typename RowIterator::value_type      row_type;\n    typedef typename ConstRowIterator::value_type const_row_type;\n    \n    /**\n     * \\name Construction, assignment, and resize.\n     * @{\n     */\n    \n    /**\n     * \\brief Creates a 0 x 0 matrix.\n     */\n    NumaDenseMatrix () = default;\n\n    /**\n     * \\brief Copy constructor.\n     */\n    NumaDenseMatrix (NumaDenseMatrix const& a) = default;\n\n    /**\n     * \\brief Move constructor.\n     */\n    NumaDenseMatrix (NumaDenseMatrix&& a) = default;\n\n    /**\n     * \\brief Creates an r x c matrix with given entries.\n     */\n    NumaDenseMatrix (size_type r, size_type c, value_type v = value_type()) \n    : Base(r,c,v)\n    {}\n    \n    /**\n     * \\brief Copy assignment.\n     */\n    NumaDenseMatrix& operator=(NumaDenseMatrix const& a) = default;\n    \n    /**\n     * \\brief Assignment from scalar. \n     */\n    Self& operator=(field_type const& a)\n    {\n      Base::operator=(a);\n      return *this;\n    }\n     \n    /**\n     * \\brief Resizes the matrix to r x c, leaving the entries in an undefined state.\n     * \n     * On resize, all row objects and iterators are invalidated. This method adheres to the Dune::DynamicMatrix interface.\n     */\n    void resize (size_type r, size_type c)\n    {\n      Base::resize(r,c);\n    }\n\n    /**\n     * \\brief Resizes the matrix to r x c, leaving the entries in an undefined state.\n     * \n     * On resize, all row objects and iterators are invalidated. This method adheres to the Dune::Matrix interface.\n     */\n    void setSize (size_type r, size_type c)\n    {\n      resize(r,c);\n    }\n    \n    /// @}\n    \n    /**\n     * \\name Entry access\n     * @{\n     */\n    \n    /**\n     * \\brief Get iterator to first row. \n     */\n    RowIterator begin() { return RowIterator(*this,0); }\n    \n    /**\n     * \\brief Get iterator to one beyond last row. \n     */\n    RowIterator end() { return RowIterator(*this,this->N()); }\n    \n    /**\n     * \\brief Get const iterator to first row. \n     */\n    ConstRowIterator begin() const { return ConstRowIterator(*this,0); }\n    \n    /**\n     * \\brief Get const iterator to one beyond last row. \n     */\n    ConstRowIterator end() const { return ConstRowIterator(*this,this->N()); }\n    \n    /**\n     * \\brief The subscript operator. \n     * \n     * Rows do not exist as persistent data structures in the matrix. Hence the subscript operator\n     * returns a row object (in fact a view onto data held by the matrix) by value.\n     */\n    row_type  operator[] (size_type row) { return *RowIterator(*this,row); }\n    \n    /**\n     * \\brief The const subscript operator. \n     * \n     * Rows do not exist as persistent data structures in the matrix. Hence the subscript operator\n     * returns a row object (in fact a view onto data held by the matrix) by value.\n     */\n    const_row_type const operator[] (size_type row) const { return *ConstRowIterator(*this,row); }\n    \n    /// @}\n    \n    /**\n     * \\brief Return the number of columns. \n     */\n    size_type M() const { return Base::M(); }\n    \n    /**\n     * \\name Linear algebra operations.\n     * @{\n     */\n    \n    /**\n     * \\brief Multiplication with a scalar. \n     */\n    Self& operator*= (field_type const& a)\n    {\n      this->for_each([&](Entry& e) { e *= a; });\n      return *this;\n    }\n    \n    /**\n     * \\brief Division by a scalar.\n     */\n    Self& operator/= (field_type const& scalar)\n    {\n      return (*this) *= (1/scalar);\n    }\n    \n    /**\n     * \\brief Matrix addition.\n     * Both matrices have to have the same sizes.\n     */\n    Self& operator+= (Self const& b)\n    {\n      this->for_each2([](Entry& y, Entry const& x) { y += x; },b);\n      return *this;\n    }\n   \n    /**\n     * \\brief Matrix subtraction.\n     */\n    Self& operator-= (Self const& b)\n    {\n      this->for_each2([](Entry& y, Entry const& x) { y -= x; },b);\n      return *this;\n    }\n    \n    /// @}\n    \n    /**\n     * \\brief frobenius norm: sqrt(sum over squared frobenius norms of entries) \n     */\n    real_type frobenius_norm () const { return std::sqrt(frobenius_norm2()); }\n    \n    /**\n     * \\brief frobenius norm squared: sum over squared frobenius norms of entries\n     */\n    real_type frobenius_norm2 () const\n    {\n      return this->accumulate([](real_type s, Entry const& e) { return s+NumaDenseMatrixDetail::frobenius_norm2(e); }, real_type(0)); \n    }\n  };\n  \n  /**\n   * \\relates NumaDenseMatrix\n   */\n  template <class Entry>\n  std::ostream& operator<<(std::ostream& out, NumaDenseMatrix<Entry> const& mat)\n  {\n    for (auto ri=mat.begin(); ri!=mat.end(); ++ri)\n    {\n      std::copy(ri->begin(),ri->end(),std::ostream_iterator<Entry>(out,\" \"));\n      out << '\\n';\n    }\n    return out;\n  }\n  \n  // --------------------------------------------------------------------------\n  \n  // forward declaration\n  template <class Entry> class NumaVector;\n  \n  /**\n   * \\cond internals\n   */\n  namespace NumaDenseMatrixDetail\n  {\n    \n    template <class Entry>\n    class VectorIterator: public boost::iterator_facade<VectorIterator<Entry>,Entry,boost::random_access_traversal_tag>\n    {\n      typedef typename std::remove_const<Entry>::type NonConstEntry;\n      \n      typedef typename std::conditional<std::is_const<Entry>::value,\n                                        NumaVector<NonConstEntry> const,\n                                        NumaVector<Entry>>::type Vector;\n    public:\n      VectorIterator() = default;\n      \n      VectorIterator(Vector& vec_, typename Vector::size_type idx_)\n      : vec(&vec_), idx(idx_) {}\n      \n      size_t index() const { return idx; }\n      \n    private:\n      friend class boost::iterator_core_access;\n      \n      bool equal(VectorIterator<Entry> const& p) const\n      {\n        return idx==p.idx;\n      }\n      \n      void increment() { ++idx; }\n      void decrement() { --idx; }\n      void advance(typename VectorIterator<Entry>::difference_type n) { idx += n; }\n      template <class E>\n      typename VectorIterator<Entry>::difference_type distance_to(VectorIterator<E> const& i) const { return i.idx - idx; }\n      Entry& dereference() const \n      { \n        size_t chunk = uniformWeightRange(idx,vec->chunks.size(),vec->N());\n        size_t chunkStart = uniformWeightRangeStart(chunk,vec->chunks.size(),vec->N());\n        return vec->chunks[chunk][idx-chunkStart];\n      }\n      \n      Vector* vec;\n      typename Vector::size_type idx;\n    };\n  }\n  /**\n   * \\endcond\n   */\n  \n  /**\n   * \\ingroup linalgbasic\n   * \\brief A vector class tailored towards NUMA architectures.\n   * This vector distributes its entries in blocks of approximately equal size to the different nodes of NUMA machines\n   * in order to exploit the larger accumulated memory bandwidth for fast vector operations. This is most beneficial\n   * for large vectors exceeding the cache of the CPUs. Modern processors (2015-01-01) have up to 6MB 3rd level cache,\n   * so this is intended for vectors of more than 50,000 doubles, say.\n   * \n   * \\tparam Entry the type of vector entries (usually Dune::FieldVector<double,n>)\n   */\n  template <class Entry>\n  class NumaVector: public NumaDenseMatrixDetail::NumaDenseBase<Entry>\n  {\n    typedef NumaVector<Entry> Self;\n    typedef NumaDenseMatrixDetail::NumaDenseBase<Entry> Base;\n    \n   public:\n    typedef typename Dune::FieldTraits<Entry>::field_type         field_type;\n    typedef typename Dune::FieldTraits<field_type>::real_type     real_type;\n    typedef typename Base::size_type                              size_type;\n    typedef typename Base::value_type                             value_type;\n    typedef NumaDenseMatrixDetail::VectorIterator<Entry>          iterator;\n    typedef NumaDenseMatrixDetail::VectorIterator<Entry const>    const_iterator;\n    \n\n    /**\n     * \\name Construction, assignment, and shape changes.\n     * @{\n     */\n\n    /**\n     * \\brief Creates a 0 vector.\n     */\n    NumaVector(): Base(0,1) \n    {} \n\n    /**\n     * \\brief Copy constructor.\n     */\n    NumaVector(NumaVector const& a) = default;\n\n    /**\n     * \\brief Move constructor.\n     */\n    NumaVector (NumaVector&& a) = default;\n\n    /**\n     * \\brief Creates an r vector with given entries.\n     */\n    NumaVector (size_type r, value_type v = value_type()) :\n      Base(r,1,v)\n    {}\n    \n    /**\n     * \\brief Copy assignment.\n     */\n    NumaVector& operator=(NumaVector const& a) = default;\n    \n    /**\n     * \\brief Resizes the vector to r entries, leaving the entries in an undefined state.\n     * \n     * On resize, all iterators are invalidated. This method adheres to the Dune::BlockVector interface.\n     */\n    void resize (size_type r) { Base::resize(r,1); }\n    \n    /// @}\n    \n    /**\n     * \\name Entry access\n     * @{\n     */\n    /**\n     * \\brief iterator to first entry. \n     */\n    iterator begin() { return iterator(*this,0); }\n    \n    /**\n     * \\brief iterator to one beyond last entry. \n     */\n    iterator end() { return iterator(*this,this->N()); }\n    \n    /**\n     * \\brief const iterator to first row. \n     */\n    const_iterator begin() const { return const_iterator(*this,0); }\n    \n    /**\n     * \\brief const iterator to one beyond last entry. \n     */\n    const_iterator end() const { return const_iterator(*this,this->N()); }\n    \n    /**\n     * \\brief The subscript operator. \n     */\n    Entry&  operator[] (size_type row) { return *iterator(*this,row); }\n    \n    /**\n     * \\brief The const subscript operator. \n     */\n    Entry const& operator[] (size_type row) const { return *const_iterator(*this,row); }\n    \n    /// @}\n     \n    /**\n     * \\name Linear algebra opterations.\n     * The computations are performed in parallel on the NUMA nodes.\n     * @{\n     */\n    \n    /**\n     * \\brief \\f$ y \\leftarrow a y \\f$\n     */\n    Self& operator*= (field_type const& a)\n    {\n      this->for_each([&](Entry& e) { e *= a; });\n      return *this;\n    }\n    \n    /**\n     * \\brief \\f$ y \\leftarrow \\frac{1}{a} y \\f$\n     */\n    Self& operator/= (field_type const& a)\n    {\n      return (*this) *= (1/a);\n    }\n    \n    /**\n     * \\brief \\f$ y \\leftarrow y+x \\f$\n     * \n     * Both vectors have to have the same size.\n     */\n    Self& operator+= (Self const& x)\n    {\n      this->for_each2([](Entry& yi, Entry const& xi) { yi += xi; },x);\n      return *this;\n    }\n   \n    /**\n     * \\brief \\f$ y \\leftarrow y - x \\f$\n     * \n     * Both vectors have to have the same size.\n     */\n    Self& operator-= (Self const& x)\n    {\n      this->for_each2([](Entry& yi, Entry const& xi) { yi -= xi; },x);\n      return *this;\n    }\n\n    /**\n     * \\brief \\f$ y \\leftarrow ax + y \\f$\n     */\n    Self& axpy(field_type const& a, Self const& x)\n    {\n      this->for_each2([&](Entry& yi, Entry const& xi) { NumaDenseMatrixDetail::axpy(yi,a,xi); },x);\n      return *this;\n    }\n    \n    /// @}\n    \n    /**\n     * \\name Norms and scalar product.\n     * \n     * The computations are performed in parallel on the NUMA nodes.\n     * @{\n     */\n    \n    /**\n     * \\brief euclidean norm: sqrt(sum over squared euclidean norms of entries) \n     */\n    real_type two_norm () const { return std::sqrt(two_norm2()); }\n    \n    /**\n     * \\brief euclidean norm squared: sum over squared euclidean norms of entries\n     */\n    real_type two_norm2 () const \n    { \n      return this->accumulate([](real_type s, Entry const& e) { return s+NumaDenseMatrixDetail::frobenius_norm2(e); }, real_type(0)); \n    }\n    \n    /**\n     * \\brief one-norm: sum over absolute values of entries\n     */\n    real_type one_norm() const \n    { \n      return this->accumulate([](real_type s, Entry const& e) { return s+NumaDenseMatrixDetail::one_norm(e); }, real_type(0)); \n    }\n    \n    /**\n     * \\brief \n     */\n    field_type dot(Self const& other) const { return Base::dot(other); }\n    \n    /// @}\n  };\n  \n  /**\n   * \\relates NumaVector\n   */\n  template <class Entry>\n  std::ostream& operator<<(std::ostream& out, NumaVector<Entry> const& vec)\n  {\n    using namespace std;\n    copy(begin(vec),end(vec),ostream_iterator<Entry>(out,\" \"));\n    return out;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "1df69fc3518e2d180d7699e862587ee4c0fb7e50", "size": 29102, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/numaMatrix.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/numaMatrix.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/numaMatrix.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.8751369113, "max_line_length": 167, "alphanum_fraction": 0.5553226582, "num_tokens": 7072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.04742587317756678, "lm_q1q2_score": 0.02003765191735599}}
{"text": "#pragma once\n\n#include <cmr/config.h>\n#include <cmr/export.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"matrix_transposed.hpp\"\n#include <iomanip>\n\nnamespace tu\n{\n  namespace detail\n  {\n\n    template <typename Iterator>\n    class Range\n    {\n    public:\n      Range(Iterator begin, Iterator end)\n        : _begin(begin), _end(end)\n      {\n\n      }\n\n      Range(const Range<Iterator>& other)\n        : _begin(other._begin), _end(other._end)\n      {\n\n      }\n\n      Iterator begin()\n      {\n        return _begin;\n      }\n\n      Iterator end()\n      {\n        return _end;\n      }\n\n    private:\n      Iterator _begin;\n      Iterator _end;\n    };\n\n  } /* namespace tu::detail */\n\n  /**\n   * \\brief Base class for matrices whose entries have type \\p V.\n   */\n\n  template <typename V>\n  class Matrix\n  {\n  public:\n    typedef V Value; /// Type of entries\n    typedef std::size_t Index; /// Row/column index type\n\n    struct Nonzero\n    {\n      Index row;\n      Index column;\n      const Value& value;\n\n      Nonzero(Index r, Index c, const Value& v)\n        : row(r), column(c), value(v)\n      {\n\n      }\n    };\n  };\n\n  /**\n   * \\brief Dense matrix with entries of type \\p V.\n   */\n\n  template <typename V>\n  class DenseMatrix : public Matrix<V>\n  {\n  public:\n    typedef typename Matrix<V>::Value Value;\n    typedef typename Matrix<V>::Index Index;\n    typedef typename Matrix<V>::Nonzero Nonzero;\n\n    template <bool Row>\n    class NonzeroIterator\n    {\n    public:\n      NonzeroIterator(const DenseMatrix<V>& matrix, Index major)\n        : _matrix(matrix), _major(major), _minor(0)\n      {\n        if (Row)\n        {\n          while (_minor < _matrix.numColumns() && _matrix.get(_major, _minor) == 0)\n            ++_minor;\n        }\n        else\n        {\n          while (_minor < _matrix.numRows() && _matrix.get(_minor, _major) == 0)\n            ++_minor;\n        }\n      }\n\n      NonzeroIterator(const DenseMatrix<V>& matrix, Index major, int dummy)\n        : _matrix(matrix), _major(major)\n      {\n        if (Row)\n          _minor = _matrix.numColumns();\n        else\n          _minor = _matrix.numRows();\n      }\n\n      NonzeroIterator<Row>& operator++()\n      {\n        ++_minor;\n        if (Row)\n        {\n          while (_minor < _matrix.numColumns() && _matrix.get(_major, _minor) == 0)\n            ++_minor;\n        }\n        else\n        {\n          while (_minor < _matrix.numRows() && _matrix.get(_minor, _major) == 0)\n            ++_minor;\n        }\n      }\n\n      Nonzero operator*() const\n      {\n        if (Row)\n        {\n          assert(_major < _matrix.numRows());\n          assert(_minor < _matrix.numColumns());\n          return Nonzero(_major, _minor, _matrix.get(_major, _minor));\n        }\n        else\n        {\n          assert(_minor < _matrix.numRows());\n          assert(_major < _matrix.numColumns());\n          return Nonzero(_minor, _major, _matrix.get(_minor, _major));\n        }\n      }\n\n      bool operator!=(const NonzeroIterator<Row>& other) const\n      {\n        assert(&_matrix == &other._matrix);\n        assert(_major == other._major);\n        return _minor != other._minor;\n      }\n\n    private:\n      const DenseMatrix<V>& _matrix;\n      std::size_t _major, _minor;\n    };\n\n    typedef detail::Range<NonzeroIterator<true>> NonzeroRowRange;\n    typedef detail::Range<NonzeroIterator<false>> NonzeroColumnRange;\n\n    /**\n     * \\brief Default constructor for 0x0 matrix.\n     */\n\n    DenseMatrix()\n      : _data(nullptr), _numRows(0), _numColumns(0)\n    {\n\n    }\n\n    /**\n     * \\brief Move constructor that steals the data from \\p other.\n     */\n\n    DenseMatrix(DenseMatrix<V>&& other)\n      : _data(other._data), _numRows(other._numRows), _numColumns(other._numColumns)\n    {\n      other._data = nullptr;\n      other._numRows = 0;\n      other._numColumns = 0;\n    }\n\n    /**\n     * \\brief Copy constructor.\n     */\n\n    template <typename V2>\n    DenseMatrix(const DenseMatrix<V2>& other)\n      : _numRows(other._numRows), _numColumns(other._numColumns)\n    {\n      std::size_t size = other._numRows * other._numColumns;\n      _data = new Value[size];\n      for (std::size_t i = 0; i < size; ++i)\n        _data[i] = other._data[i];\n    }\n\n    /**\n     * \\brief Move assignment operator that steals the data from \\p other.\n     */\n\n    DenseMatrix<V>& operator=(DenseMatrix<V>&& other)\n    {\n      _data = other._data;\n      _numRows = other._numRows;\n      _numColumns = other._numColumns;\n      other._data = nullptr;\n      other._numRows = 0;\n      other._numColumns = 0;\n      return *this;\n    }\n\n    /**\n     * \\brief Assignment operator.\n     */\n\n    template <typename V2>\n    DenseMatrix<V>& operator=(const DenseMatrix<V2>& other)\n    {\n      _numRows = other._numRows;\n      _numColumns = other._numColumns;\n      std::size_t size = other._numRows * other._numColumns;\n      _data = new Value[size];\n      for (std::size_t i = 0; i < size; ++i)\n        _data[i] = other._data[i];\n      return *this;\n    }\n\n    /**\n     * \\brief Destructor.\n     */\n\n    ~DenseMatrix()\n    {\n      if (_data != nullptr)\n        delete[] _data;\n    }\n\n    /**\n     * \\brief Constructs zero matrix of given size.\n     */\n\n    DenseMatrix(Index numRows, Index numColumns)\n      : _numRows(numRows), _numColumns(numColumns)\n    {\n      std::size_t size = numRows * numColumns;\n      _data = new Value[size];\n      for (std::size_t i = 0; i < size; ++i)\n        _data[i] = 0;\n    }\n\n    /**\n     * \\brief Returns the number of rows.\n     */\n\n    Index numRows() const\n    {\n      return _numRows;\n    }\n\n    /**\n     * \\brief Returns the number of columns.\n     */\n\n    Index numColumns() const\n    {\n      return _numColumns;\n    }\n\n    /**\n     * \\brief Returns entry at \\p row, \\p column.\n     */\n\n    const Value& get(Index row, Index column) const\n    {\n      assert(row < _numRows);\n      assert(column < _numColumns);\n      return _data[_numColumns * row + column];\n    }\n\n    /**\n     * \\brief Sets entry at \\p row, \\p column to copy of \\p value.\n     */\n\n    template <typename V2>\n    void set(Index row, Index column, const V2& value)\n    {\n      assert(row < _numRows);\n      assert(column < _numColumns);\n      _data[_numColumns * row + column] = value;\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros in \\p row.\n     */\n\n    std::size_t countRowNonzeros(Index row) const\n    {\n      std::size_t begin = _numColumns * row;\n      std::size_t end = _numColumns * (row + 1);\n      std::size_t count = 0;\n      for (std::size_t i = begin; i < end; ++i)\n      {\n        if (_data[i] != 0)\n          ++count;\n      }\n      return count;\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros in \\p column.\n     */\n\n    std::size_t countColumnNonzeros(Index column) const\n    {\n      std::size_t begin = column;\n      std::size_t end = _numRows * _numColumns;\n      std::size_t count = 0;\n      for (std::size_t i = begin; i < end; i += _numColumns)\n      {\n        if (_data[i] != 0)\n          ++count;\n      }\n      return count;\n    }\n\n    /**\n     * \\brief Returns a range for iterating over the nonzeros of \\p row.\n     */\n\n    NonzeroRowRange iterateRowNonzeros(Index row) const\n    {\n      return NonzeroRowRange(NonzeroIterator<true>(*this, row),\n        NonzeroIterator<true>(*this, row, 0));\n    }\n\n    /**\n     * \\brief Returns a range for iterating over the nonzeros of \\p column.\n     */\n\n    NonzeroColumnRange iterateColumnNonzeros(Index column) const\n    {\n      return NonzeroColumnRange(NonzeroIterator<false>(*this, column),\n        NonzeroIterator<false>(*this, column, 0));\n    }\n\n    /**\n     * \\brief Checks for consistency, raising a \\ref std::runtime_error if inconsistent.\n     */\n\n    void ensureConsistency() const\n    {\n\n    }\n\n  protected:\n    Value* _data; /// Matrix entries with row-major ordering.\n    Index _numRows; /// Number of rows.\n    Index _numColumns; /// Number of columns.\n  };\n\n  /**\n   * \\brief Sparse matrix with entries of type \\p V.\n   */\n\n  template<typename V>\n  class SparseMatrix : public Matrix<V>\n  {\n  public:\n    typedef typename Matrix<V>::Value Value;\n    typedef typename Matrix<V>::Index Index;\n    typedef typename Matrix<V>::Nonzero Nonzero;\n\n    /**\n     * \\brief Matrix data, row-wise or column-wise.\n     *\n     * Matrix data, row-wise or column-wise. The term major refers to the rows if it is a row-wise\n     * view and to columns otherwise. The term minor refers to the opposite.\n     */\n\n    struct Data\n    {\n      /// Array that maps a major to its nonzero range specified by first and beyond entries.\n      std::vector<std::pair<Index, Index>> range;\n      /// Array that maps the nonzero indices to pairs of minor index and value.\n      std::vector<std::pair<Index, Value>> entries;\n      /// Whether the data is sorted by minor.\n      bool isSorted;\n\n      /**\n       * \\brief Default constructor.\n       */\n\n      Data()\n        : isSorted(true)\n      {\n\n      }\n\n      /**\n       * \\brief Move constructor.\n       */\n\n      Data(Data&& other)\n        : range(std::move(other.range)), entries(std::move(other.entries)), isSorted(other.isSorted)\n      {\n\n      }\n\n      /**\n       * \\brief Copy constructor.\n       */\n\n      Data(const Data& other)\n        : range(other.range), entries(other.entries), isSorted(other.isSorted)\n      {\n\n      }\n\n      /**\n       * \\brief Move operator.\n       */\n\n      Data& operator=(Data&& other)\n      {\n        range = std::move(other.range);\n        entries = std::move(other.entries);\n        isSorted = other.isSorted;\n        return *this;\n      }\n\n      /**\n       * \\brief Assignment operator.\n       */\n\n      Data& operator=(const Data& other)\n      {\n        range = other.range;\n        entries = other.entries;\n        isSorted = other.isSorted;\n        return *this;\n      }\n\n      /**\n       * \\brief Destructor.\n       */\n\n      ~Data() = default;\n\n      /**\n       * \\brief Computes the transpose version of \\p data. \\p numMinor is the new number of minor\n       * indices.\n       */\n\n      void constructFromTransposed(const Data& transposedData, Index numMinor)\n      {\n        // Iterate over entries and count how many in each major.\n        range.resize(numMinor);\n        for (auto& r : range)\n          r.second = 0;\n\n        for (Index i = 0; i < Index(transposedData.range.size()); ++i)\n        {\n          for (Index j = transposedData.range[i].first; j < transposedData.range[i].second; ++j)\n          {\n            ++range[transposedData.entries[j].first].second;\n          }\n        }\n\n        // Initialize start of each major. This will be incremented when copying.\n        range[0].first = 0;\n        for (Index i = 1; i < Index(range.size()); ++i)\n        {\n          range[i].first = range[i-1].first + range[i-1].second;\n          range[i-1].second = range[i].first;\n        }\n        range.back().second = transposedData.entries.size();\n\n        // Copy entries major-wise into slots indicated by first[i], incrementing the latter.\n        entries.resize(transposedData.entries.size());\n        for (Index transposedMajor = 0; transposedMajor < Index(transposedData.range.size());\n          ++transposedMajor)\n        {\n          for (Index j = transposedData.range[transposedMajor].first;\n            j < transposedData.range[transposedMajor].second; ++j)\n          {\n            auto transposedEntry = transposedData.entries[j];\n            entries[range[transposedEntry.first].first] = std::make_pair(transposedMajor,\n              transposedEntry.second);\n            ++range[transposedEntry.first].first;\n          }\n        }\n\n        // Re-initialize start of each major.\n        range[0].first = 0;\n        for (Index i = 1; i < Index(range.size()); ++i)\n          range[i].first = range[i-1].second;\n\n        isSorted = true;\n      }\n\n      /**\n       * \\brief Checks for consistency, raising a \\ref std::runtime_error if inconsistent.\n       */\n\n      void ensureConsistency(Index numMinor = std::numeric_limits<Index>::max()) const\n      {\n        for (Index i = 0; i < Index(range.size()); ++i)\n        {\n          if (range[i].first > entries.size())\n            throw std::runtime_error(\n                \"Inconsistent SparseMatrix::Data: range.first contains index out of range.\");\n          if (range[i].second > entries.size())\n            throw std::runtime_error(\n                \"Inconsistent SparseMatrix::Data: range.second contains index out of range.\");\n          if (range[i].first > range[i].second)\n            throw std::runtime_error(\n                \"Inconsistent SparseMatrix::Data: range.first > range.beyond.\");\n        }\n        for (Index i = 0; i < Index(entries.size()); ++i)\n        {\n          if (entries[i].first >= numMinor)\n            throw std::runtime_error(\"Inconsistent SparseMatrix::Data: minor entry exceeds bound.\");\n          if (entries[i].second == 0)\n            throw std::runtime_error(\"Inconsistent SparseMatrix::Data: zero entry found.\");\n        }\n        for (Index i = 0; i < Index(range.size()); ++i)\n        {\n          for (Index j = range[i].first + 1; j < range[i].second; ++j)\n          {\n            if (entries[j-1].first == entries[j].first)\n            {\n              std::stringstream ss;\n              ss << \"Inconsistent SparseMatrix::Data: minor entries of major \" << i\n                << \" contain duplicate indices \" << (j-1) << \"->\" << entries[j-1].first << \" and \"\n                << j << \"->\" << entries[j].first << \".\";\n              throw std::runtime_error(ss.str());\n            }\n            else if (entries[j-1].first > entries[j].first && isSorted)\n            {\n              std::stringstream ss;\n              ss << \"Inconsistent SparseMatrix::Data: minor entries of major \" << i\n                << \" are not sorted for indices \" << (j-1) << \"->\" << entries[j-1].first << \" and \"\n                << j << \"->\" << entries[j].first << \".\";\n              throw std::runtime_error(ss.str());\n            }\n          }\n        }\n      }\n\n      /**\n       * \\brief Swaps data with \\p other.\n       */\n\n      void swap(Data& other)\n      {\n        range.swap(other.range);\n        entries.swap(other.entries);\n        std::swap(isSorted, other.isSorted);\n      }\n\n      /**\n       * \\brief Finds entry \\p major,\\p minor.\n       * \n       * Find entry \\p major,\\p minor. If it exists, the index of the entry is returned, and\n       * \\c std::numeric_limits<std::size_t>::max() otherwise.\n       */\n\n      std::size_t find(Index major, Index minor) const\n      {\n        if (isSorted)\n        {\n          // Binary search on interval [lower, upper)\n\n          std::size_t lower = range[major].first;\n          std::size_t upper = range[major].second;\n          std::size_t mid;\n          while (lower < upper)\n          {\n            mid = (lower + upper) / 2;\n            if (entries[mid].first < minor)\n              lower = mid + 1;\n            else if (entries[mid].first > minor)\n              upper = mid;\n            else\n              return mid;\n          }\n        }\n        else\n        {\n          // Linear scan.\n\n          for (std::size_t i = range[major].first; i < range[major].second; ++i)\n          {\n            if (entries[i].first == minor)\n              return i;\n          }\n        }\n\n        return std::numeric_limits<std::size_t>::max();\n      }\n\n      /**\n       * \\brief Sort data by minor.\n       */\n\n      void sort()\n      {\n        if (!isSorted)\n          return;\n\n        for (std::size_t i = 0; i < entries.size(); ++i)\n        {\n          auto compare = [] (const std::pair<Index, Value>& a,\n            const std::pair<Index, Value>& b)\n            {\n              return a.first < b.first;\n            };\n\n          std::sort(entries.begin() + range[i].first, entries.begin() + range[i].second, compare);\n        }\n\n        isSorted = true;\n      }\n    };\n\n    /**\n     * \\brief Iterator for row- or column-wise iteration over the entries.\n     */\n\n    template <bool Row>\n    struct NonzeroIterator\n    {\n    public:\n      NonzeroIterator(const SparseMatrix<V>& matrix, Index major)\n        : _data(Row ? matrix._rowData : matrix._columnData), _major(major),\n        _index(_data.range[major].first)\n      {\n\n      }\n\n      NonzeroIterator(const SparseMatrix<V>& matrix, Index major, int dummy)\n        : _data(Row ? matrix._rowData : matrix._columnData), _major(major),\n        _index(_data.range[major].second)\n      {\n\n      }\n\n      /**\n       * \\brief Copy constructor.\n       */\n\n      NonzeroIterator(const NonzeroIterator& other)\n        : _data(other._data), _major(other._major), _index(other._index)\n      {\n\n      }\n\n      /**\n       * \\brief Returns the current entry.\n       */\n\n      inline const Nonzero operator*() const\n      {\n        // Statically known, so one branch will be optimized away.\n        if (Row)\n          return Nonzero(_major, _data.entries[_index].first, _data.entries[_index].second);\n        else\n          return Nonzero(_data.entries[_index].first, _major, _data.entries[_index].second);\n      }\n\n      /**\n       * \\brief Advances to the next entry in the same major.\n       */\n\n      inline void operator++()\n      {\n        ++_index;\n        assert(_index <= _data.range[_major].second);\n      }\n\n      /**\n       * \\brief Compares two iterators for being not equal.\n       */\n\n      inline bool operator!=(const NonzeroIterator<Row>& other) const \n      {\n        assert(&_data == &other._data);\n        return _major != other._major || _index != other._index;\n      }\n\n      private:\n        /// Reference to the matrix data.\n        const Data& _data;\n        /// Major index.\n        Index _major;\n        /// Index of the entry relative to this major.\n        Value _index;\n    };\n\n    typedef detail::Range<NonzeroIterator<true>> NonzeroRowRange;\n    typedef detail::Range<NonzeroIterator<false>> NonzeroColumnRange;\n\n    /**\n     * \\brief Constructs a 0x0 matrix.\n     */\n\n    SparseMatrix()\n      : _zero(0)\n    {\n\n    }\n\n    /**\n     * \\brief Move constructor.\n     */\n\n    SparseMatrix(SparseMatrix&& other)\n      : _rowData(std::move(other._rowData)), _columnData(std::move(other._columnData)), _zero(0)\n    {\n\n    }\n\n    /**\n     * \\brief Move assignment operator.\n     */\n\n    SparseMatrix& operator=(SparseMatrix&& other)\n    {\n      _rowData = std::move(other._rowData);\n      _columnData = std::move(other._columnData);\n      return *this;\n    }\n\n    /**\n     * \\brief Constructs a matrix.\n     *\n     * Constructs a matrix. Given entries may contain zeros, but they are filtered.\n     *\n     * \\param majorRow Indicates if data is row-wise.\n     * \\param numMajor Number of rows (resp. columns) of the matrix.\n     * \\param numMinor Number of columns (resp. rows) of the matrix.\n     * \\param numEntries Number of provided entries.\n     * \\param first Array of size \\p numMajor with first index of each row (resp. column).\n     * \\param beyond Array of size \\p numMajor with beyond index of each row (resp. column).\n     *   May be \\c NULL in which case the first-entry of the next major is considered, i.e.,\n     *   the rows (resp. columns) need to be given in an ordered way.\n     * \\param entryMinors Array of size \\p numEntries with column (resp. row) of each entry.\n     * \\param entryValues Array of size \\p numEntries with value of each entry.\n     * \\param mayContainZeros Whether we have to check for zero entries.\n     * \\param isSorted Whether the entries of each row (resp. column) are already sorted.\n     */\n\n    SparseMatrix(bool majorRow, Index numMajor, Index numMinor, Index numEntries, Index* first,\n      Index* beyond, Index* entryMinors, Value* entryValues, bool mayContainZeros = true,\n      bool isSorted = false)\n      : _zero(0)\n    {\n      set(majorRow, numMajor, numMinor, numEntries, first, beyond, entryMinors, entryValues,\n        mayContainZeros, isSorted);\n    }\n\n    /**\n     * \\brief Constructs a matrix.\n     *\n     * Constructs a matrix from a prepared data structure.\n     *\n     * \\param majorRow Indicates if data is row-wise.\n     * \\param majorIsSorted Whether the data of each major is sorted by minor.\n     * \\param data Matrix data.\n     */\n\n    SparseMatrix(bool majorRow, const Data& data, Index numMinor, bool majorIsSorted = false)\n      : _zero(0)\n    {\n      set(majorRow, data, numMinor, majorIsSorted);\n    }\n\n    /**\n     * \\brief Constructs a matrix.\n     *\n     * Constructs a matrix from a prepared data structure.\n     *\n     * \\param majorRow Indicates if data is row-wise.\n     * \\param data Matrix data.\n     */\n\n    SparseMatrix(bool majorRow, Data&& data, Index numMinor)\n      : _zero(0)\n    {\n      set(majorRow, data, numMinor);\n    }\n\n    /**\n     * \\brief Constructs a matrix.\n     *\n     * Constructs a matrix from two prepared data structures.\n     *\n     * \\param rowData Matrix row data.\n     * \\param columnData Matrix column data.\n     */\n\n    SparseMatrix(const Data& rowData, const Data& columnData)\n      : _zero(0)\n    {\n      set(rowData, columnData);\n    }\n\n    /**\n     * \\brief Constructs a matrix.\n     *\n     * Constructs a matrix from a two prepared data structures.\n     *\n     * \\param rowData Matrix row data.\n     * \\param columnData Matrix column data.\n     */\n\n    SparseMatrix(Data&& rowData, Data&& columnData)\n      : _zero(0)\n    {\n      set(std::move(rowData), std::move(columnData));\n    }\n\n    /**\n     * \\brief Sets the contents of the matrix.\n     *\n     * Sets the contents of the matrix. Given entries may contain zeros, but they are filtered.\n     *\n     * \\param majorRow Indicates if data is row-wise.\n     * \\param numMajor Number of rows (resp. columns) of the matrix.\n     * \\param numMinor Number of columns (resp. rows) of the matrix.\n     * \\param numEntries Number of provided entries.\n     * \\param first Array of size \\p numMajor with first index of each row (resp. column).\n     * \\param beyond Array of size \\p numMajor with beyond index of each row (resp. column).\n     *   May be \\c nullptr in which case the first-entry of the next major is considered, i.e.,\n     *   the rows (resp. columns) need to be ordered.\n     * \\param entryMinors Array of size \\p numEntries with column (resp. row) of each entry.\n     * \\param entryValues Array of size \\p numEntries with value of each entry.\n     * \\param mayContainZeros Whether zero entries shall be skipped.\n     * \\param isSorted Whether the entries of each major are sorted by minor.\n     */\n\n    void set(bool majorRow, Index numMajor, Index numMinor, Index numEntries, const Index* first,\n      const Index* beyond, const Index* entryMinors, const Value* entryValues,\n      bool mayContainZeros = true, bool isSorted = false)\n    {\n      if (mayContainZeros)\n      {\n        // Use first run over entries to count nonzeros in each row (resp. column).\n        _rowData.range.resize(numMajor);\n        for (auto& range : _rowData.range)\n          range.first = 0;\n        Index current = 0;\n        for (Index i = 0; i < numMajor; ++i)\n        {\n          _rowData.range[i].first = current;\n          Index b;\n          if (beyond != nullptr)\n            b = beyond[i];\n          else if (i + 1 < numMajor)\n            b = first[i+1];\n          else\n            b = numEntries;\n          for (Index j = first[i]; j < b; ++j)\n          {\n            if (entryValues[j] != 0)\n              ++current;\n          }\n          _rowData.range[i].second = current;\n        }\n\n        // Use second run to copy the nonzeros.\n        _rowData.entries.resize(current);\n        current = 0;\n        for (Index i = 0; i < numMajor; ++i)\n        {\n          Index b;\n          if (beyond != nullptr)\n            b = beyond[i];\n          else if (i + 1 < numMajor)\n            b = first[i+1];\n          else\n            b = numEntries;\n          for (Index j = first[i]; j < b; ++j)\n          {\n            if (entryValues[j] != 0)\n            {\n              _rowData.entries[current] = std::make_pair(entryMinors[j], entryValues[j]);\n              ++current;\n            }\n          }\n        }\n      }\n      else\n      {\n        // If we can trust the input then we can copy directly.\n        _rowData.range.resize(numMajor);\n        if (beyond != nullptr)\n        {\n          for (Index i = 0; i < numMajor; ++i)\n            _rowData.range[i] = std::make_pair(first[i], beyond[i]);\n        }\n        else\n        {\n          for (Index i = 0; i + 1 < numMajor; ++i)\n            _rowData.range[i] = std::make_pair(first[i], first[i+1]);\n          _rowData.range.back() = std::make_pair(first[numMajor - 1], Index(numEntries));\n        }\n        _rowData.entries.resize(numEntries);\n        for (Index i = 0; i < numEntries; ++i)\n          _rowData.entries[i] = std::make_pair(entryMinors[i], entryValues[i]);\n      }\n\n      _rowData.isSorted = isSorted;\n\n      // Construct column-wise (resp. row-wise) representation.\n      _columnData.constructFromTransposed(_rowData, numMinor);\n\n      if (!majorRow)\n        _rowData.swap(_columnData);\n\n  #if !defined(NDEBUG)\n      ensureConsistency();\n  #endif /* !NDEBUG */\n    }\n\n    /**\n     * \\brief Sets the contents of the matrix.\n     *\n     * Sets the contents of the matrix from a prepared data structure.\n     *\n     * \\param majorRow Indicates if data is row-wise.\n     * \\param data Matrix data.\n     * \\param numMinor Number of columns (resp. rows).\n     */\n\n    void set(bool majorRow, const Data& data, Index numMinor)\n    {\n      // We can trust the input and thus we can copy directly.\n      _rowData.range = data.range;\n      _rowData.entries = data.entries;\n      _rowData.isSorted = data.isSorted;\n\n      // Construct column-wise (resp. row-wise) representation.\n      _columnData.constructFromTransposed(_rowData, numMinor);\n\n      if (!majorRow)\n        _rowData.swap(_columnData);\n\n  #if !defined(NDEBUG)\n      ensureConsistency();\n  #endif /* !NDEBUG */\n    }\n\n    /**\n     * \\brief Sets the contents of the matrix.\n     *\n     * Sets the contents of the matrix from a prepared data structure.\n     *\n     * \\param majorRow Indicates if data is row-wise.\n     * \\param data Matrix data.\n     * \\param numMinor Number of columns (resp. rows).\n     */\n\n    void set(bool majorRow, Data&& data, Index numMinor)\n    {\n      _rowData = std::move(data);\n      _columnData.constructFromTransposed(_rowData, numMinor);\n      if (!majorRow)\n        _rowData.swap(_columnData);\n\n#if !defined(NDEBUG)\n      ensureConsistency();\n#endif /* !NDEBUG */\n    }\n\n    /**\n     * \\brief Sets the contents of the matrix.\n     *\n     * Sets the contents of the matrix from a prepared data structure.\n     *\n     * \\param rowData Matrix row data.\n     * \\param columnData Matrix column data.\n     */\n\n    void set(const Data& rowData, const Data& columnData)\n    {\n      _rowData.range = rowData.range;\n      _rowData.entries = rowData.entries;\n      _rowData.isSorted = rowData.isSorted;\n      _rowData.ensureConsistency();\n\n      _columnData.range = columnData.range;\n      _columnData.entries = columnData.entries;\n      _columnData.isSorted = columnData.isSorted;\n      _columnData.ensureConsistency();\n\n#if !defined(NDEBUG)\n      ensureConsistency();\n#endif /* !NDEBUG */\n    }\n\n    /**\n     * \\brief Sets the contents of the matrix.\n     *\n     * Sets the contents of the matrix from a prepared data structure.\n     *\n     * \\param rowData Matrix row data.\n     * \\param columnData Matrix column data.\n     */\n\n    void set(Data&& rowData, Data&& columnData)\n    {\n      _rowData = std::move(rowData);\n      _columnData = std::move(columnData);\n#if !defined(NDEBUG)\n      ensureConsistency();\n#endif /* !NDEBUG */\n    }\n\n    /**\n     * \\brief Destructor.\n     */\n\n    ~SparseMatrix() = default;\n\n    /**\n     * \\brief Returns the number of rows.\n     */\n\n    std::size_t numRows() const\n    {\n      return _rowData.range.size();\n    }\n\n    /**\n     * \\brief Returns the number of columns.\n     */\n\n    std::size_t numColumns() const\n    {\n      return _columnData.range.size();\n    }\n\n    /**\n     * \\brief Indicates if the row data is sorted by column.\n     */\n\n    bool hasSortedRows() const\n    {\n      return _rowData.isSorted;\n    }\n\n    /**\n     * \\brief Indicates if the column data is sorted by row.\n     */\n\n    bool hasSortedColumns() const\n    {\n      return _columnData.isSorted;\n    }\n\n    /**\n     * \\brief Returns entry at \\p row, \\p column.\n     * \n     * Returns entry at \\p row, \\p column. If the row or column data is sorted (resp. not sorted)\n     * then the time is logarithmic (resp. linear) in the number of nonzeros of the row or column.\n     */\n\n    const Value& get(Index row, Index column) const\n    {\n      assert(row < numRows());\n      assert(column < numColumns());\n\n      if (_rowData.isSorted)\n      {\n        std::size_t columnIndex = _rowData.find(row, column);\n        if (columnIndex < std::numeric_limits<std::size_t>::max())\n          return _rowData.entries[columnIndex].second;\n      }\n      else\n      {\n        std::size_t rowIndex = _columnData.find(column, row);\n        if (rowIndex < std::numeric_limits<std::size_t>::max())\n          return _columnData.entries[rowIndex].second;\n      }\n\n      return _zero;\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros.\n     */\n\n    std::size_t numNonzeros() const\n    {\n      return _rowData.entries.size();\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros in \\p row.\n     */\n\n    std::size_t countRowNonzeros(Index row) const\n    {\n      return _rowData.range[row].second - _rowData.range[row].first;\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros in \\p column.\n     */\n\n    std::size_t countColumnNonzeros(Index column) const\n    {\n      return _columnData.range[column].second - _columnData.range[column].first;\n    }\n\n    /**\n     * \\brief Returns a range for iterating over the nonzeros of \\p row.\n     */\n\n    NonzeroRowRange iterateRowNonzeros(Index row) const\n    {\n      return NonzeroRowRange(NonzeroIterator<true>(*this, row),\n        NonzeroIterator<true>(*this, row, 0));\n    }\n\n    /**\n     * \\brief Returns a range for iterating over the nonzeros of \\p column.\n     */\n\n    NonzeroColumnRange iterateColumnNonzeros(Index column) const\n    {\n      return NonzeroColumnRange(NonzeroIterator<false>(*this, column),\n        NonzeroIterator<false>(*this, column, 0));\n    }\n\n    /**\n     * \\brief Returns a copy of the matrix' transpose.\n     */\n\n    SparseMatrix transposed() const\n    {\n      return SparseMatrix(_columnData, _rowData);\n    }\n\n    /**\n     * \\brief Checks for consistency, raising a \\ref std::runtime_error if inconsistent.\n     * \n     * Checks for consistency of row- and column-data, which includes that all entries must be\n     * nonzeros and that entries are sorted and free of duplicates (if stated so).\n     */\n\n    void ensureConsistency() const\n    {\n      // First ensure individual consistency of row and column data.\n      _rowData.ensureConsistency();\n      _columnData.ensureConsistency();\n\n      // Copy of a nonzero.\n      struct NZ\n      {\n        Index row;\n        Index column;\n        Value value;\n      };\n\n      // Comparison for entries.\n      auto compare = [](const NZ& a, const NZ& b)\n      {\n        if (a.row != b.row)\n          return a.row < b.row;\n        if (a.column != b.column)\n          return a.column < b.column;\n        return a.value < b.value;\n      };\n\n      // Construct sorted vector of entries from row data.\n      std::vector<NZ> rowNonzeros;\n      for (Index i = 0; i < Index(_rowData.range.size()); ++i)\n      {\n        for (Index j = _rowData.range[i].first; j < _rowData.range[i].second; ++j)\n        {\n          NZ nz = { i, _rowData.entries[j].first, _rowData.entries[j].second };\n          rowNonzeros.push_back(nz);\n        }\n      }\n      std::sort(rowNonzeros.begin(), rowNonzeros.end(), compare);\n\n      // Construct sorted vector of entries from column data.\n      std::vector<NZ> columnNonzeros;\n      for (Index i = 0; i < Index(_columnData.range.size()); ++i)\n      {\n        for (Index j = _columnData.range[i].first; j < _columnData.range[i].second; ++j)\n        {\n          NZ nz = { _columnData.entries[j].first, i, _columnData.entries[j].second };\n          columnNonzeros.push_back(nz);\n        }\n      }\n      std::sort(columnNonzeros.begin(), columnNonzeros.end(), compare);\n\n      for (std::size_t i = 0; i < rowNonzeros.size(); ++i)\n      {\n        if (rowNonzeros[i].row != columnNonzeros[i].row\n          || rowNonzeros[i].column != columnNonzeros[i].column\n          || rowNonzeros[i].value != columnNonzeros[i].value)\n        {\n          throw std::runtime_error(\"Inconsistent Matrix: row and column data differ.\");\n        }\n      }\n    }\n\n    /**\n     * \\brief Transposes the matrix.\n     *\n     * Transposes the matrix in constant time.\n     */\n\n    void transpose()\n    {\n      _rowData.swap(_columnData);\n    }\n\n    \n    /**\n     * \\brief Sort row data (by column).\n     */\n\n    void sortRows()\n    {\n      _rowData.sort();\n    }\n\n    /**\n     * \\brief Sort column data (by row).\n     */\n\n    void sortColumns()\n    {\n      _columnData.sort();\n    }\n\n    /**\n     * \\brief Sort row and column data (by column and row, respectively).\n     */\n\n    void sort()\n    {\n      sortRows();\n      sortColumns();\n    }\n\n  private:\n    /// Data for row-wise access.\n    Data _rowData;\n    /// Data for column-wise access.\n    Data _columnData;\n    /// Zero value.\n    Value _zero;\n    /// Whether the row and column data is sorted (by columns and rows, respectively).\n    bool _isSorted;\n  };\n\n  /**\n   * \\brief Matrix proxy for the transpose of a matrix.\n   * \n   * Matrix proxy for the transpose of a matrix. It references another matrix and does not maintain\n   * matrix data by itself.\n   */\n\n  template <typename M>\n  class TransposedMatrix : public Matrix<typename M::Value>\n  {\n  public:\n    typedef typename M::Value Value;\n    typedef typename M::Index Index;\n    typedef typename M::Nonzero Nonzero;\n\n    template <bool Row>\n    class NonzeroIterator\n    {\n    public:\n      NonzeroIterator(const TransposedMatrix<M>& matrix, Index major)\n        : _matrix(matrix._matrix), _iterator(typename M::template NonzeroIterator<!Row>(matrix._matrix, major))\n      {\n\n      }\n\n      NonzeroIterator(const TransposedMatrix<M>& matrix, Index major, int dummy)\n        : _matrix(matrix._matrix), _iterator(typename M::template NonzeroIterator<!Row>(matrix._matrix, major, 0))\n      {\n\n      }\n\n      NonzeroIterator<Row>& operator++()\n      {\n        ++_iterator;\n      }\n\n      Nonzero operator*() const\n      {\n        Nonzero nz = *_iterator;\n        std::swap(nz.row, nz.column);\n        return nz;\n      }\n\n      bool operator!=(const NonzeroIterator<Row>& other) const\n      {\n        assert(&_matrix == &other._matrix);\n        return _iterator != other._iterator;\n      }\n\n    private:\n      const M& _matrix;\n      typename M::template NonzeroIterator<!Row> _iterator;\n    };\n\n    typedef detail::Range<NonzeroIterator<true>> NonzeroRowRange;\n    typedef detail::Range<NonzeroIterator<false>> NonzeroColumnRange;\n\n    /**\n     * \\brief Constructs from a matrix of type \\p M.\n     */\n\n    TransposedMatrix(M& matrix)\n      : _matrix(matrix)\n    {\n\n    }\n\n    /**\n     * \\brief Move constructor.\n     */\n\n    TransposedMatrix(TransposedMatrix&& other)\n      : _matrix(other._matrix)\n    {\n\n    }\n\n    /**\n     * \\brief Returns the number of rows.\n     */\n\n    std::size_t numRows() const\n    {\n      return _matrix.numColumns();\n    }\n\n    /**\n     * \\brief Returns the number of columns.\n     */\n\n    std::size_t numColumns() const\n    {\n      return _matrix.numRows();\n    }\n\n    /**\n     * \\brief Indicates if the row data is sorted by column.\n     */\n\n    bool hasSortedRows() const\n    {\n      return _matrix.hasSortedColumns();\n    }\n\n    /**\n     * \\brief Indicates if the column data is sorted by row.\n     */\n\n    bool hasSortedColumns() const\n    {\n      return _matrix.hasSortedRows();\n    }\n\n    /**\n     * \\brief Returns entry at \\p row, \\p column.\n     * \n     * Returns entry at \\p row, \\p column. If the row or column data is sorted (resp. not sorted)\n     * then the time is logarithmic (resp. linear) in the number of nonzeros of the row or column.\n     */\n\n    const Value& get(Index row, Index column) const\n    {\n      assert(row < numRows());\n      assert(column < numColumns());\n\n      return _matrix.get(column, row);\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros.\n     */\n\n    std::size_t numNonzeros() const\n    {\n      return _matrix.numNonzeros();\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros in \\p row.\n     */\n\n    std::size_t countRowNonzeros(Index row) const\n    {\n      return _matrix.countColumnNonzeros(row);\n    }\n\n    /**\n     * \\brief Returns the number of nonzeros in \\p column.\n     */\n\n    std::size_t countColumnNonzeros(Index column) const\n    {\n      return _matrix.countRowNonzeros(column);\n    }\n\n    /**\n     * \\brief Returns a range for iterating over the nonzeros of \\p row.\n     */\n\n    NonzeroRowRange iterateRowNonzeros(Index row) const\n    {\n      return NonzeroRowRange(NonzeroIterator<true>(_matrix, row),\n        NonzeroIterator<true>(_matrix, row, 0));\n    }\n\n    /**\n     * \\brief Returns a range for iterating over the nonzeros of \\p column.\n     */\n\n    NonzeroColumnRange iterateColumnNonzeros(Index column) const\n    {\n      return NonzeroColumnRange(NonzeroIterator<false>(_matrix, column),\n        NonzeroIterator<false>(_matrix, column, 0));\n    }\n\n    /**\n     * \\brief Checks for consistency, raising a \\ref std::runtime_error if inconsistent.\n     */\n\n    void ensureConsistency() const\n    {\n      _matrix.ensureConsistency();\n    }\n\n  protected:\n    M& _matrix;\n  };\n\n  /**\n   * \\brief Returns a \\ref TransposedMatrix for \\p matrix.\n   */\n\n  template <typename M>\n  TransposedMatrix<M> transposedMatrix(M& matrix)\n  {\n    return TransposedMatrix<M>(matrix);\n  }\n\n  /**\n   * \\brief Indexes a submatrix.\n   */\n\n  class SubmatrixIndices\n  {\n  public:\n    /**\n     * \\brief Copy constructor.\n     */\n\n    CMR_EXPORT\n    SubmatrixIndices(const SubmatrixIndices& other);\n\n    /**\n     * \\brief Move constructor.\n     */\n\n    CMR_EXPORT\n    SubmatrixIndices(SubmatrixIndices&& other);\n\n    /**\n     * \\brief Constructor from arrays \\p rows and \\p columns.\n     */\n\n    CMR_EXPORT\n    SubmatrixIndices(const std::vector<std::size_t>& rows, const std::vector<std::size_t>& columns);\n\n    /**\n     * \\brief Constructor for a 1x1 submatrix.\n     *\n     * Constructor for a 1x1 submatrix.\n     */\n\n    CMR_EXPORT\n    SubmatrixIndices(std::size_t row, std::size_t column);\n\n    /**\n     * \\brief Returns the number of row indices.\n     */\n\n    inline\n    std::size_t numRows() const\n    {\n      return _rows.size();\n    }\n\n    /**\n     * \\brief Returns the number of column indices.\n     */\n\n    inline\n    std::size_t numColumns() const\n    {\n      return _columns.size();\n    }\n\n    /**\n     * \\brief Returns the vector of row indices.\n     */\n\n    inline\n    const std::vector<std::size_t>& rows() const\n    {\n      return _rows;\n    }\n\n    /**\n     * \\brief Returns the vector of column indices.\n     */\n\n    inline\n    const std::vector<std::size_t>& columns() const\n    {\n      return _columns;\n    }\n\n  private:\n    /// Array of row indices.\n    std::vector<std::size_t> _rows;\n\n    /// Array of column indices.\n    std::vector<std::size_t> _columns;\n  };\n\n  template <typename M>\n  class Submatrix : public Matrix<typename M::Value>\n  {\n  public:\n    typedef typename M::Index Index;\n    typedef typename M::Value Value;\n    typedef typename M::Nonzero Nonzero;\n\n    /**\n     * \\brief Constructs submatrix of \\p matrix indexed by \\p indices.\n     */\n\n    Submatrix(const M& matrix, const SubmatrixIndices& indices)\n      : _matrix(matrix), _indices(indices)\n    {\n\n    }\n\n    /**\n     * \\brief Move constructor.\n     */\n\n    Submatrix(Submatrix && other)\n      : _matrix(other._matrix), _indices(other._indices)\n    {\n\n    }\n\n    /**\n     * \\brief Returns the number of rows.\n     */\n\n    std::size_t numRows() const\n    {\n      return _indices.numRows();\n    }\n\n    /**\n     * \\brief Returns the number of columns.\n     */\n\n    std::size_t numColumns() const\n    {\n      return _indices.numColumns();\n    }\n\n    /**\n     * \\brief Indicates if the row data is sorted by column.\n     */\n\n    bool hasSortedRows() const\n    {\n      return false;\n    }\n\n    /**\n     * \\brief Indicates if the column data is sorted by row.\n     */\n\n    bool hasSortedColumns() const\n    {\n      return false;\n    }\n\n    /**\n     * \\brief Returns entry at \\p row, \\p column.\n     * \n     * Returns entry at \\p row, \\p column. If the row or column data is sorted (resp. not sorted)\n     * then the time is logarithmic (resp. linear) in the number of nonzeros of the row or column.\n     */\n\n    const Value& get(Index row, Index column) const\n    {\n      assert(row < numRows());\n      assert(column < numColumns());\n\n      return _matrix.get(_indices.rows()[row], _indices.columns()[column]);\n    }\n\n    /**\n     * \\brief Checks for consistency, raising a \\ref std::runtime_error if inconsistent.\n     */\n\n    void ensureConsistency() const\n    {\n      for (auto row : _indices.rows())\n      {\n        if (row >= _matrix.numRows())\n          throw std::runtime_error(\"Inconsistent Submatrix: row index too large.\");\n      }\n      for (auto column : _indices.columns())\n      {\n        if (column >= _matrix.numColumns())\n          throw std::runtime_error(\"Inconsistent Submatrix: column index too large.\");\n      }\n      _matrix.ensureConsistency();\n    }\n\n  private:\n    const M& _matrix;\n    const SubmatrixIndices& _indices;\n  };\n\n  \n  template <typename Matrix>\n  bool find_smallest_nonzero_matrix_entry(const Matrix& matrix, size_t row_first, size_t row_beyond, size_t column_first, size_t column_beyond,\n      size_t& row, size_t& column)\n  {\n    bool result = false;\n    int current_value = 0;\n    for (size_t r = row_first; r != row_beyond; ++r)\n    {\n      for (size_t c = column_first; c != column_beyond; ++c)\n      {\n        int value = matrix(r, c);\n        if (value == 0)\n          continue;\n\n        value = value >= 0 ? value : -value;\n\n        if (!result || value < current_value)\n        {\n          result = true;\n          row = r;\n          column = c;\n          current_value = value;\n        }\n      }\n    }\n    return result;\n  }\n  \n  template <typename Matrix>\n  bool matrix_row_zero(const Matrix& matrix, size_t row, size_t column_first, size_t column_beyond)\n  {\n    for (size_t c = column_first; c != column_beyond; ++c)\n      if (matrix(row, c) != 0)\n        return false;\n    return true;\n  }\n\n  template <typename Matrix>\n  bool matrix_column_zero(const Matrix& matrix, size_t column, size_t row_first, size_t row_beyond)\n  {\n    return matrix_row_zero(make_transposed_matrix(matrix), column, row_first, row_beyond);\n  }\n\n  \n  template <typename Matrix1, typename Matrix2>\n  bool equals(const Matrix1& first, const Matrix2& second)\n  {\n    if (first.size1() != second.size1())\n      return false;\n    if (first.size2() != second.size2())\n      return false;\n    for (size_t r = 0; r < first.size1(); ++r)\n    {\n      for (size_t c = 0; c < first.size2(); ++c)\n      {\n        if (first(r, c) != second(r, c))\n          return false;\n      }\n    }\n    return true;\n  }\n\n  \n  /**\n   * Free function to permute two rows of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param index1 First index\n   * @param index2 Second index\n   */\n\n  template <typename MatrixType>\n  inline void matrix_permute1(MatrixType& matrix, size_t index1, size_t index2)\n  {\n    for (size_t index = 0; index < matrix.size2(); ++index)\n    {\n      std::swap(matrix(index1, index), matrix(index2, index));\n    }\n  }\n\n  /**\n   * Free function to permute two columns of a permuted matrix.\n   *\n   * @param matrix The permuted matrix\n   * @param index1 First index\n   * @param index2 Second index\n   */\n\n  template <typename MatrixType>\n  inline void matrix_permute2(MatrixType& matrix, size_t index1, size_t index2)\n  {\n    for (size_t index = 0; index < matrix.size1(); ++index)\n    {\n      std::swap(matrix(index, index1), matrix(index, index2));\n    }\n  }\n\n  \n} /* namespace tu */\n", "meta": {"hexsha": "3b152e4a9b1480c95f48bb44ee16d2e2a0d15672", "size": 44114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cmr/matrix.hpp", "max_stars_repo_name": "discopt/cmr", "max_stars_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-13T12:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:56:31.000Z", "max_issues_repo_path": "src/cmr/matrix.hpp", "max_issues_repo_name": "xammy/unimodularity-test", "max_issues_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T09:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T23:18:47.000Z", "max_forks_repo_path": "src/cmr/matrix.hpp", "max_forks_repo_name": "discopt/cmr", "max_forks_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_forks_repo_licenses": ["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.2368421053, "max_line_length": 143, "alphanum_fraction": 0.5739901165, "num_tokens": 10875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.045352582651065294, "lm_q1q2_score": 0.02003101149414936}}
{"text": "/**\n *  @file    mdm_AIF.cxx\n *  @brief   Implementation of mdm_AIF class\n */\n\n#ifndef MDM_API_EXPORTS\n#define MDM_API_EXPORTS\n#endif // !MDM_API_EXPORTS\n\n#include \"mdm_AIF.h\"\n\n#include <cstdio>\n#include <cassert>\n#include <iostream>\n#include <cmath>\n#include <istream>\n\n#include <madym/mdm_exception.h>\n#include <madym/mdm_ProgramLogger.h>\n#include <boost/format.hpp>\n\n//\nMDM_API mdm_AIF::mdm_AIF()\n\t:\n  AIFtype_(mdm_AIF::AIF_TYPE::AIF_UNDEFINED),\n  PIFtype_(mdm_AIF::PIF_TYPE::PIF_UNDEFINED),\n  AIFTimes_(0),\n\tbase_AIF_(0),\n\tresampled_AIF_(0),\n  base_PIF_(0),\n  resampled_PIF_(0),\n\tHct_(0.42),\n\tprebolus_(8),\n\tdose_(0.1)\n{\n\n}\n\n//\nMDM_API mdm_AIF::~mdm_AIF()\n{\n\n}\n\n//\nMDM_API void mdm_AIF::readAIF(const std::string &full_AIF_filename, const size_t nDynamics)\n{\n  try {\n    readIFFromFile(base_AIF_, full_AIF_filename, nDynamics);\n  }\n\tcatch (mdm_exception &e)\n  {\n    e.append(\"Unable to read AIF\");\n    throw;\n  }\n  setAIFType(AIF_FILE);\n}\n\n//\nMDM_API void mdm_AIF::readPIF(const std::string &full_PIF_filename, const size_t nDynamics)\n{\n  try {\n    readIFFromFile(base_PIF_, full_PIF_filename, nDynamics);\n  }\n  catch (mdm_exception &e)\n  {\n    e.append(\"Unable to read PIF\");\n    throw;\n  }\n  setPIFType(PIF_FILE);\n\n}\n\n//\nMDM_API void mdm_AIF::writeAIF(const std::string &filename)\n{\n\tif (base_AIF_.empty())\n\t\tbase_AIF_ = resampled_AIF_;\n\n  try { writeIFToFile(base_AIF_, filename); }\n  catch (mdm_exception &e)\n  {\n    e.append(\"Unable to write AIF\");\n    throw;\n  }\n}\n\n//\nMDM_API void mdm_AIF::writePIF(const std::string &filename)\n{\n\tif (base_PIF_.empty())\n\t\tbase_PIF_ = resampled_PIF_;\n\n  try { writeIFToFile(base_PIF_, filename); }\n  catch (mdm_exception &e)\n  {\n    e.append(\"Unable to write PIF\");\n    throw;\n  }\n}\n\n//\nMDM_API void mdm_AIF::setBaseAIF(const std::vector<double> &aifVals)\n{\n  if (aifVals.size() != AIFTimes_.size())\n    throw mdm_exception(__func__, boost::format(\n      \"Size of input AIF values (%1%) does not match number of times (%2%)\")\n      % aifVals.size() % AIFTimes_.size());\n  \n  base_AIF_ = aifVals;\n}\n\n//\nMDM_API const std::vector<double>& mdm_AIF::AIF() const\n{\n\treturn resampled_AIF_;\n}\n\n//\nMDM_API const std::vector<double>& mdm_AIF::PIF() const\n{\n\treturn resampled_PIF_;\n}\n\n//\nMDM_API void mdm_AIF::resample_AIF(double tOffset)\n{\n\t//Important this is only called after AIFTimes has been set\n\tconst auto nTimes = AIFTimes_.size();\n\n\tswitch (AIFtype_)\n\t{\n\tcase AIF_STD:\n\t\taifWeinman(nTimes, tOffset);\n\t\tbreak;\n\tcase AIF_FILE:\n  case AIF_MAP:\n\t\taifFromBase(nTimes, tOffset);\n\t\tbreak;\n\tcase AIF_POP:\n\t\taifPopGJMP(nTimes, tOffset);\n\t\tbreak;\n\n\tcase AIF_UNDEFINED:\n\tdefault:\n\t\t// Add warning, quit here\n    throw \"Tried to resample undefined AIF\";\n\t\tbreak;\n\t}\n}\n\n//\nMDM_API void mdm_AIF::resample_PIF(double tOffset, bool offsetAIF/* = true*/, bool resampleIRF/* = true*/)\n{\n\t//Important this is only called after AIFTimes has been set\n\tconst auto nTimes = AIFTimes_.size();\n\n\tswitch (PIFtype_)\n\t{\n\n\tcase PIF_FILE:\n\t\tpifFromBase(nTimes, tOffset);\n\t\tbreak;\n\n\tcase PIF_POP:\n\t\taifPopHepaticAB(nTimes, tOffset, offsetAIF, resampleIRF);\n\t\tbreak;\n\tcase PIF_UNDEFINED:\n\tdefault:\n\t\t// Add warning, quit here\n    throw \"Tried to resample undefined AIF\";\n\t\tbreak;\n\t}\n}\n\n//\nMDM_API bool mdm_AIF::setAIFType(AIF_TYPE value)\n{\n  bool setOK;\n\n  switch (value)\n  {\n    case AIF_STD:\n    case AIF_FILE:\n    case AIF_POP:\n    case AIF_MAP:\n      AIFtype_ = value;\n      setOK = true;\n      break;\n    default:\n      AIFtype_ = AIF_UNDEFINED;\n      setOK = false;\n      throw \"AIF type not recognised\";\n      break;\n  }\n\n  return setOK;\n}\n\n//\nMDM_API bool mdm_AIF::setPIFType(PIF_TYPE value)\n{\n\tbool setOK;\n\n\tswitch (value)\n\t{\n\tcase PIF_FILE:\n\tcase PIF_POP:\n\t\tPIFtype_ = value;\n\t\tsetOK = true;\n\t\tbreak;\n\tdefault:\n\t\tPIFtype_ = PIF_UNDEFINED;\n\t\tsetOK = false;\n    throw \"AIF type not recognised\";\n\t\tbreak;\n\t}\n\n\treturn setOK;\n}\n\n//\nMDM_API mdm_AIF::AIF_TYPE mdm_AIF::AIFType() const\n{\n  return AIFtype_;\n}\n\n//\nMDM_API mdm_AIF::PIF_TYPE mdm_AIF::PIFType() const\n{\n\treturn PIFtype_;\n}\n\n//\nMDM_API const std::vector<double>& mdm_AIF::AIFTimes() const\n{\n\treturn AIFTimes_;\n}\n\n//\nMDM_API double mdm_AIF::AIFTime(size_t i) const\n{\n  try { return AIFTimes_[i]; }\n  catch (std::out_of_range &e)\n  {\n    mdm_exception em(__func__, e.what());\n    em.append(boost::format(\n      \"Attempting to access timepoint %1% when there are only %2% times\")\n      % i % AIFTimes_.size());\n    throw em;\n  }\n}\n\n//\nMDM_API void mdm_AIF::setAIFTimes(const std::vector<double> times)\n{\n\tconst auto nTimes = times.size();\n\tAIFTimes_.resize(nTimes);\n\tfor (size_t i = 0; i < nTimes; i++)\n\t\tAIFTimes_[i] = times[i] - times[0];\n}\n\n//\nMDM_API void  mdm_AIF::setPrebolus(size_t p)\n{\n\tprebolus_ = p;\n}\n\n//\nMDM_API void  mdm_AIF::setHct(double h)\n{\n\tHct_ = h;\n}\n\n//\nMDM_API void  mdm_AIF::setDose(double d)\n{\n\tdose_ = d;\n}\n\n//\nMDM_API size_t mdm_AIF::prebolus() const\n{\n\treturn prebolus_;\n}\n\n//\nMDM_API double mdm_AIF::Hct() const\n{\n\treturn Hct_;\n}\n\n//\nMDM_API double mdm_AIF::dose() const\n{\n\treturn dose_;\n}\n\n//**************************************************************************\n// Private functions\n//**************************************************************************\n\n//\nvoid mdm_AIF::aifPopGJMP(size_t nTimes, double tOffset)\n{\n  double gaussian1, gaussian2, sigmoid;\n  std::vector<double> offsetTimes(nTimes);\n\n  // These parameters are from Parker et al MRM 56:993(2006)\n  // For gaussian1\n  const double kA1     = 5.7326;\n  const double kMu1    = 0.17046;\n  const double kSigma1 = 0.0563;\n  // For gaussian2\n  const double kA2     = 0.9974;\n  const double kMu2    = 0.365;\n  const double kSigma2 = 0.132;\n  // For sigmoid\n  const double kAlpha  = 1.050;\n  const double kBeta   = 0.1685;\n  const double kS      = 38.078;\n  const double kTau    = 0.483;\n\n  // Get AIF timing data\n  for (size_t i = 0; i < nTimes; i++)\n    offsetTimes[i] = (double) (AIFTimes_[i] - AIFTimes_[0] + tOffset);\n\n  // TODO Trying out Anita's pb - 1 instead of 2 in GJMP AIF\n\tresampled_AIF_.resize(nTimes);\n  for (int i = 0; i < nTimes; i++)\n  {\n    gaussian1 = kA1 * exp(-1.0 * ((double) AIFTimes_[i] - kMu1 - offsetTimes[(int) prebolus_ - 1])\n                               * ((double) AIFTimes_[i] - kMu1 - offsetTimes[(int) prebolus_ - 1])\n                               / (2.0 * kSigma1 * kSigma1));\n    gaussian2 = kA2 * exp(-1.0 * ((double) AIFTimes_[i] - kMu2 - offsetTimes[(int) prebolus_ - 1])\n                               * ((double) AIFTimes_[i] - kMu2 - offsetTimes[(int) prebolus_ - 1])\n                               / (2.0 * kSigma2 * kSigma2));\n    sigmoid   = kAlpha * exp(-kBeta * ((double) AIFTimes_[i] - offsetTimes[(int) prebolus_ - 1]))\n                       / (1 + exp(-kS * ((double) AIFTimes_[i] - kTau - offsetTimes[(int) prebolus_ - 1])));\n    resampled_AIF_[i] = (double) (((dose_ / 0.1) * (gaussian1 + gaussian2 + sigmoid))\n    \t\t                    / (1.0 - Hct_));\n  }\n}\n\nvoid mdm_AIF::aifPopHepaticAB(size_t nTimes, double tOffset, bool offsetAIF, bool resampleIRF)\n{\n\t//If we've got an offset, make sure AIF has been resampled\n\tif (offsetAIF || resampled_AIF_.size() != nTimes)\n\t\tresample_AIF( tOffset);\n\n\t//generate a population IRF according to Anita's model\n\tif (resampleIRF || PIF_IRF_.size() != nTimes || std::isnan(PIF_IRF_[0]))\n\t{\n\t\tPIF_IRF_.resize(nTimes);\n\t\tdouble irf_sum = 0.0;\n\t\tfor (size_t i_t = 0; i_t < nTimes; i_t++)\n\t\t{\n\t\t\tconst double &t = AIFTimes_[i_t] - tOffset;\n\t\t\tif (t < 0.08)\n        PIF_IRF_[i_t] = 0;//This might have been set to NaN, so make sure we set back to zero\n\t\t\telse if (t < 0.17)\n\t\t\t\tPIF_IRF_[i_t] = 24.16*t - 2.01;\n\t\t\telse\n\t\t\t\tPIF_IRF_[i_t] = 2.83*exp(-10.80*t) + 2.12*exp(-1.82*t);\n\n\t\t\tirf_sum += PIF_IRF_[i_t];\n\t\t}\n\t\tfor (int i_t = 0; i_t < nTimes; i_t++)\n\t\t\tPIF_IRF_[i_t] /= irf_sum;\n\t}\n\t\n\t//Convolve the AIF with the IRF to generate the PIF\n\tresampled_PIF_.resize(nTimes);\n\n\t//literal convolution operation\n\tfor (int i_t = 0; i_t < nTimes; i_t++)\n\t{\n\t\tdouble pif_sum = 0.0;\n\t\tfor (int j_t = 0, k_t = i_t; j_t <= i_t; j_t++, k_t--)\n\t\t{\n\t\t\tpif_sum += resampled_AIF_[j_t] * PIF_IRF_[k_t];\n\t\t}\n\t\tresampled_PIF_[i_t] = pif_sum;\n\t}\n}\n\n//\nvoid mdm_AIF::aifWeinman(size_t nTimes, double tOffset)\n{\n  std::vector<double> AIF(nTimes), offsetTimes(nTimes);\n  double delta_t, remainder;\n\n  /* From original paper TODO get Weinman ref */\n  const double kAlpha1 = 3.99;\n  const double kBeta1  = 0.144;\n  const double kAlpha2 = 4.78;\n  const double kBeta2  = 0.0111;\n\n  /* Get AIF timing data */\n  for (size_t i = 0; i < nTimes; i++)\n    offsetTimes[i] = (double) (AIFTimes_[i] - AIFTimes_[0] + tOffset);\n\n  AIF[0] = 0.0;\n  for (size_t i = 1; i < nTimes; i++)\n  {\n    if (i < prebolus_)\n      AIF[i] = 0.0;\n    else\n      AIF[i] = dose_ * (kAlpha1 * exp(-kBeta1 * (AIFTimes_[i - 1]))\n                             + kAlpha2 * exp(-kBeta2 * (AIFTimes_[i - 1])));\n  }\n  \n\t//Linear resample AIF to shifted time points\n  resampled_AIF_[0] = 0.0;\n  for (size_t i = 1; i < nTimes; i++)\n  {\n    if (AIFTimes_[i] <= offsetTimes[0])\n      resampled_AIF_[i] = 0.0;\n    for (size_t j = 1; j < nTimes; j++)\n      // find where in the AIF time series the current tissue time point falls\n      if (AIFTimes_[i] > offsetTimes[j - 1] && AIFTimes_[i] <= offsetTimes[j])\n      {\n        delta_t = offsetTimes[j] - offsetTimes[j - 1];\n        remainder = AIFTimes_[i] - offsetTimes[j - 1];\n        resampled_AIF_[i] = remainder / delta_t * AIF[j]\n                           + (1.0 - remainder / delta_t) * AIF[j - 1];\n      }\n  }\n}\n\n//\nvoid mdm_AIF::aifFromBase(size_t nTimes, double tOffset)\n{\n\tresampleBase(resampled_AIF_, base_AIF_,\n\t\tnTimes, tOffset);\n}\n\n//\n//Load an hepatic portal vein from file\nvoid mdm_AIF::pifFromBase(size_t nTimes, double tOffset)\n{\n\tresampleBase(resampled_PIF_, base_PIF_,\n\t\tnTimes, tOffset);\n}\n\n//Load input funtion previously loaded from file\nvoid mdm_AIF::resampleBase(std::vector<double> &resampled_if, const std::vector<double> &loaded_if,\n  size_t nTimes, double tOffset)\n{\n\tstd::vector<double> offsetTimes(nTimes);\n\tdouble delta_t, remainder;\n\n\t// Get AIF timing data\n\tfor (size_t i = 0; i < nTimes; i++)\n\t\toffsetTimes[i] = AIFTimes_[i] + tOffset;\n\n\n\t// Linear resample AIF to shifted time points\n\tresampled_if.resize(nTimes);\n\tfor (size_t i = 1; i < nTimes; i++)\n\t{\n\t\tfor (size_t j = 1; j < nTimes; j++)\n\t\t{\n\t\t\t// find where in the AIF time series the current tissue time point falls\n\t\t\tif (AIFTimes_[i] > offsetTimes[j - 1] && AIFTimes_[i] <= offsetTimes[j])\n\t\t\t{\n\t\t\t\tdelta_t = offsetTimes[j] - offsetTimes[j - 1];\n\t\t\t\tremainder = AIFTimes_[i] - offsetTimes[j - 1];\n\t\t\t\tresampled_if[i] = ((remainder / delta_t) * loaded_if[j]\n\t\t\t\t\t+ (1.0 - remainder / delta_t) * loaded_if[j - 1])\n\t\t\t\t\t/ (1.0 - Hct_);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n//Load an AIF from file\nvoid mdm_AIF::readIFFromFile(std::vector<double> &loaded_if, \n  const std::string &filename, const size_t nDynamics)\n{\n\tstd::vector<double>  timesFromFile(nDynamics, 0);\n\tloaded_if.resize(nDynamics);\n\n\tstd::ifstream aifStream(filename, std::ios::in);\n\n\tif (!aifStream.is_open())\n    throw mdm_exception(__func__,\n      boost::format( \"IF file %2% not found\") % filename);\n\n\t//Load times and values from file - MB added check we don't reach EOF\n\t//If we do this suggests the AIF file does not have sufficient time points -\n\t//most likely we've loaded a file with data organised in the wrong format\n\tfor (size_t i = 0; i < nDynamics; i++)\n\t{\n\t\tif (aifStream.eof())\n\t\t{\n      aifStream.close();\n\n      throw mdm_exception(__func__, boost::format(\n        \"IF does not contain sufficient time points. EOF reached after %1% points. \"\n        \"Expected %2% \") %  i % nDynamics);\n\t\t};\n\t\taifStream >> timesFromFile[i] >> loaded_if[i];\n\t}\n\taifStream.close();\n\n\t//Check if we have existing times, if not, use the times we've just read from the file\n\tif (AIFTimes_.size() != nDynamics)\n\t\tAIFTimes_ = timesFromFile;\n\n\tmdm_ProgramLogger::logProgramMessage(\n\t\t\"IF successfully read from \" + filename);\n\n}\n\n//\nvoid mdm_AIF::writeIFToFile(const std::vector<double> &if_to_save, const std::string &filename)\n{\n  std::ofstream aifStream(filename, std::ios::out);\n\n  if (if_to_save.size() != AIFTimes_.size())\n    throw mdm_exception(__func__, boost::format( \n      \"Size of IF values (%1%) does not match number of times (%2%)\")\n      % if_to_save.size() % AIFTimes_.size());\n\n  if (!aifStream.is_open())\n    throw mdm_exception(__func__,\n      boost::format(\"Unable to open IF file %1% for writing\") % filename);\n\n  //\n  for (size_t i = 0; i < if_to_save.size(); i++)\n    aifStream << AIFTimes_[i] << \" \" << if_to_save[i] << std::endl;\n\n\tmdm_ProgramLogger::logProgramMessage(\n\t\t\"IF successfully written to \" + filename);\n\n  return;\n}\n\n//\n\n", "meta": {"hexsha": "94d87bc309179ee82bd4d8a90544193f68b33899", "size": 12635, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "madym/mdm_AIF.cxx", "max_stars_repo_name": "michaelberks/madym_cxx", "max_stars_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T15:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T15:43:15.000Z", "max_issues_repo_path": "madym/mdm_AIF.cxx", "max_issues_repo_name": "michaelberks/madym_cxx", "max_issues_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "madym/mdm_AIF.cxx", "max_forks_repo_name": "michaelberks/madym_cxx", "max_forks_repo_head_hexsha": "647b6e59a3ef7aa6b3f3f58e16d23dc313b7dd16", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2261029412, "max_line_length": 108, "alphanum_fraction": 0.6356153542, "num_tokens": 4172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04023794679574268, "lm_q1q2_score": 0.0199617971159471}}
{"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.hpp\"\n\n#include <vector>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/format.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/counting_range.hpp>\n\n#include <core/utils/bitset_utils.hpp>\n#include <core/utils/range_utils.hpp>\n#include <classical/dd/count_solutions.hpp>\n\nusing namespace boost::assign;\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\nenum class bdd_operation {\n  _and, _or, _xor, _not, cof0, cof1, exists,\n  constrain, restrict, round_down, round_up, round\n};\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nbdd_manager::bdd_manager( unsigned nvars, unsigned log_max_objs, bool verbose )\n  : dd_manager( nvars, log_max_objs, verbose ) {}\n\nbdd_manager::~bdd_manager() {}\n\nunsigned bdd_manager::bdd_and( unsigned f, unsigned g )\n{\n  /* terminating cases */\n  if ( f == 0u ) { return 0u; }\n  if ( g == 0u ) { return 0u; }\n  if ( f == 1u ) { return g; }\n  if ( g == 1u ) { return f; }\n  if ( f == g )  { return f; }\n\n  /* commutativity */\n  if ( f > g ) { return bdd_and( g, f ); }\n\n  const auto r = cache.lookup( f, g, (unsigned)bdd_operation::_and );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( f );\n  const auto& node2 = nodes.at( g );\n  unsigned rlow, rhigh;\n  if ( node1.var < node2.var )\n  {\n    rlow = bdd_and( node1.low, g );\n    rhigh = bdd_and( node1.high, g );\n  }\n  else if ( node1.var > node2.var )\n  {\n    rlow = bdd_and( f, node2.low );\n    rhigh = bdd_and( f, node2.high );\n  }\n  else\n  {\n    rlow = bdd_and( node1.low, node2.low );\n    rhigh = bdd_and( node1.high, node2.high );\n  }\n\n  auto idx = unique_create( std::min( node1.var, node2.var ), rhigh, rlow );\n  return cache.insert( f, g, (unsigned)bdd_operation::_and, idx );\n}\n\nunsigned bdd_manager::bdd_or( unsigned f, unsigned g )\n{\n  /* terminating cases */\n  if ( f == 0u ) { return g; }\n  if ( g == 0u ) { return f; }\n  if ( f == 1u ) { return 1u; }\n  if ( g == 1u ) { return 1u; }\n  if ( f == g )  { return f; }\n\n  /* commutativity */\n  if ( f > g ) { return bdd_or( g, f ); }\n\n  const auto r = cache.lookup( f, g, (unsigned)bdd_operation::_or );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( f );\n  const auto& node2 = nodes.at( g );\n  unsigned rlow, rhigh;\n  if ( node1.var < node2.var )\n  {\n    rlow = bdd_or( node1.low, g );\n    rhigh = bdd_or( node1.high, g );\n  }\n  else if ( node1.var > node2.var )\n  {\n    rlow = bdd_or( f, node2.low );\n    rhigh = bdd_or( f, node2.high );\n  }\n  else\n  {\n    rlow = bdd_or( node1.low, node2.low );\n    rhigh = bdd_or( node1.high, node2.high );\n  }\n\n  auto idx = unique_create( std::min( node1.var, node2.var ), rhigh, rlow );\n  return cache.insert( f, g, (unsigned)bdd_operation::_or, idx );\n}\n\nunsigned bdd_manager::bdd_xor( unsigned f, unsigned g )\n{\n  /* terminating cases */\n  if ( f == 0u ) { return g; }\n  if ( g == 0u ) { return f; }\n  if ( f == g )  { return 0u; }\n\n  /* commutativity */\n  if ( f > g ) { return bdd_xor( g, f ); }\n\n  const auto r = cache.lookup( f, g, (unsigned)bdd_operation::_xor );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( f );\n  const auto& node2 = nodes.at( g );\n  unsigned rlow, rhigh;\n  if ( node1.var < node2.var )\n  {\n    rlow = bdd_xor( node1.low, g );\n    rhigh = bdd_xor( node1.high, g );\n  }\n  else if ( node1.var > node2.var )\n  {\n    rlow = bdd_xor( f, node2.low );\n    rhigh = bdd_xor( f, node2.high );\n  }\n  else\n  {\n    rlow = bdd_xor( node1.low, node2.low );\n    rhigh = bdd_xor( node1.high, node2.high );\n  }\n\n  auto idx = unique_create( std::min( node1.var, node2.var ), rhigh, rlow );\n  return cache.insert( f, g, (unsigned)bdd_operation::_xor, idx );\n}\n\nunsigned bdd_manager::bdd_not( unsigned f )\n{\n  /* terminating cases */\n  if ( f == 0u ) { return 1u; }\n  if ( f == 1u ) { return 0u; }\n\n  const auto r = cache.lookup( f, f, (unsigned)bdd_operation::_not );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node = nodes.at( f );\n\n  auto rlow = bdd_not( node.low );\n  auto rhigh = bdd_not( node.high );\n\n  auto idx = unique_create( node.var, rhigh, rlow );\n  return cache.insert( f, f, (unsigned)bdd_operation::_not, idx );\n}\n\nunsigned bdd_manager::bdd_cof0( unsigned f, unsigned v )\n{\n  /* terminating cases */\n  if ( f <= 1u ) { return f; }\n\n  const auto& node = nodes.at( f );\n  if ( node.var > v ) { return f; }\n\n  const auto r = cache.lookup( f, v, (unsigned)bdd_operation::cof0 );\n  if ( r >= 0 ) { return r; }\n\n  unsigned idx;\n  if ( node.var < v )\n  {\n    const auto rlow  = bdd_cof0( node.low, v );\n    const auto rhigh = bdd_cof0( node.high, v );\n    idx = unique_create( node.var, rhigh, rlow );\n  }\n  else\n  {\n    idx = node.low;\n  }\n  return cache.insert( f, v, (unsigned)bdd_operation::cof0, idx );\n}\n\nunsigned bdd_manager::bdd_cof1( unsigned f, unsigned v )\n{\n  /* terminating cases */\n  if ( f <= 1u ) { return f; }\n\n  const auto& node = nodes.at( f );\n  if ( node.var > v ) { return f; }\n\n  const auto r = cache.lookup( f, v, (unsigned)bdd_operation::cof1 );\n  if ( r >= 0 ) { return r; }\n\n  unsigned idx;\n  if ( node.var < v )\n  {\n    const auto rlow  = bdd_cof1( node.low, v );\n    const auto rhigh = bdd_cof1( node.high, v );\n    idx = unique_create( node.var, rhigh, rlow );\n  }\n  else\n  {\n    idx = node.high;\n  }\n  return cache.insert( f, v, (unsigned)bdd_operation::cof1, idx );\n}\n\nunsigned bdd_manager::bdd_exists( unsigned f, unsigned g )\n{\n  /* terminating cases */\n  if ( g == 1u || f <= 1u ) { return f; }\n\n  const auto& node1 = nodes.at( f );\n  const auto& node2 = nodes.at( g );\n\n  if ( node1.var > node2.var )\n  {\n    return bdd_exists( f, node2.high );\n  }\n\n  const auto r = cache.lookup( f, g, (unsigned)bdd_operation::exists );\n  if ( r >= 0 ) { return r; }\n\n  unsigned idx;\n  auto rlow  = bdd_exists( node1.low, node1.var == node2.var ? node2.high : g );\n\n  if ( rlow == 1 && node1.var == node2.var )\n  {\n    idx = 1;\n  }\n  else\n  {\n    auto rhigh = bdd_exists( node1.high, node1.var == node2.var ? node2.high : g );\n\n    if ( node1.var < node2.var )\n    {\n      idx = unique_create( node1.var, rhigh, rlow );\n    }\n    else\n    {\n      idx = bdd_or( rlow, rhigh );\n    }\n  }\n\n  return cache.insert( f, g, (unsigned)bdd_operation::exists, idx );\n}\n\nunsigned bdd_manager::bdd_constrain( unsigned f, unsigned g )\n{\n  /* terminating cases */\n  if ( g == 0u )            { return 0u; }\n  if ( g == 1u || f <= 1u ) { return f;  }\n  if ( f == g )             { return 1u; }\n\n  const auto r = cache.lookup( f, g, (unsigned)bdd_operation::constrain );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( f );\n  const auto& node2 = nodes.at( g );\n\n  unsigned idx;\n\n  do {\n    unsigned v;\n\n    if ( node1.var < node2.var )\n    {\n      v = node1.var;\n    }\n    else\n    {\n      v = node2.var;\n      if ( node2.low == 0u )\n      {\n        idx = bdd_constrain( node1.var == v ? node1.high : f, node2.high );\n        break;\n      }\n      else if ( node2.high == 0u )\n      {\n        idx = bdd_constrain( node1.var == v ? node1.low : f, node2.low );\n        break;\n      }\n    }\n\n    auto rlow = bdd_constrain( node1.var == v ? node1.low : f, node2.var == v ? node2.low : g );\n    auto rhigh = bdd_constrain( node1.var == v ? node1.high : f, node2.var == v ? node2.high : g );\n    idx = unique_create( v, rhigh, rlow );\n  } while ( false );\n\n  return cache.insert( f, g, (unsigned)bdd_operation::constrain, idx );\n}\n\nunsigned bdd_manager::bdd_restrict( unsigned f, unsigned g )\n{\n  /* terminating cases */\n  if ( g == 0u )            { return 0u; }\n  if ( g == 1u || f <= 1u ) { return f;  }\n  if ( f == g )             { return 1u; }\n\n  const auto r = cache.lookup( f, g, (unsigned)bdd_operation::restrict );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( f );\n  const auto& node2 = nodes.at( g );\n\n  unsigned idx;\n\n  do {\n    unsigned v;\n\n    if ( node1.var < node2.var )\n    {\n      v = node1.var;\n    }\n    else\n    {\n      v = node2.var;\n      if ( node2.low == 0u )\n      {\n        idx = bdd_restrict( node1.var == v ? node1.high : f, node2.high );\n        break;\n      }\n      else if ( node2.high == 0u )\n      {\n        idx = bdd_restrict( node1.var == v ? node1.low : f, node2.low );\n        break;\n      }\n    }\n\n    /* special case in RESTRICT */\n    if ( node1.low == node1.high )\n    {\n      idx = bdd_restrict( f, bdd_exists( g, v + 2u ) );\n      break;\n    }\n\n    auto rlow = bdd_restrict( node1.var == v ? node1.low : f, node2.var == v ? node2.low : g );\n    auto rhigh = bdd_restrict( node1.var == v ? node1.high : f, node2.var == v ? node2.high : g );\n    idx = unique_create( v, rhigh, rlow );\n  } while ( false );\n\n  return cache.insert( f, g, (unsigned)bdd_operation::restrict, idx );\n}\n\nunsigned bdd_manager::bdd_round_to( unsigned f, unsigned level, unsigned cop, unsigned to )\n{\n  properties::ptr settings = std::make_shared<properties>();\n  properties::ptr statistics = std::make_shared<properties>();\n\n  count_solutions( bdd( this, f ), settings, statistics );\n\n  return bdd_round_to( f, level, cop, to, statistics->get<std::map<unsigned, boost::multiprecision::uint256_t>>( \"count_map\" ) );\n}\n\nunsigned bdd_manager::bdd_round_to( unsigned f, unsigned level, unsigned cop, unsigned to, const std::map<unsigned, boost::multiprecision::uint256_t>& count_map )\n{\n  /* terminating cases */\n  if ( f <= 1u ) { return f; }\n\n  const auto r = cache.lookup( f, level, cop );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node = nodes.at( f );\n\n  auto idx = 0u;\n  if ( node.var < level )\n  {\n    auto rlow = bdd_round_to( node.low, level, cop, to, count_map );\n    auto rhigh = bdd_round_to( node.high, level, cop, to, count_map );\n\n    idx = unique_create( node.var, rhigh, rlow );\n  }\n  else\n  {\n    auto cl = count_map.at( node.low );\n    auto ch = count_map.at( node.high );\n\n    if ( cl < ch )\n    {\n      auto rhigh = bdd_round_to( node.high, level, cop, to, count_map );\n      idx = unique_create( node.var, rhigh, to );\n    }\n    else\n    {\n      auto rlow = bdd_round_to( node.low, level, cop, to, count_map );\n      idx = unique_create( node.var, to, rlow );\n    }\n  }\n  return cache.insert( f, level, cop, idx );\n}\n\nunsigned bdd_manager::bdd_round_down( unsigned f, unsigned level )\n{\n  return bdd_round_to( f, level, (unsigned)bdd_operation::round_down, 0u );\n}\n\nunsigned bdd_manager::bdd_round_up( unsigned f, unsigned level )\n{\n  return bdd_round_to( f, level, (unsigned)bdd_operation::round_up, 1u );\n}\n\nunsigned bdd_manager::bdd_round( unsigned f, unsigned level )\n{\n  /* terminating cases */\n  if ( f <= 1u ) { return f; }\n\n  const auto r = cache.lookup( f, level, (unsigned)bdd_operation::round );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node = nodes.at( f );\n\n  auto idx = 0u;\n  if ( node.var < level )\n  {\n    auto rlow = bdd_round( node.low, level );\n    auto rhigh = bdd_round( node.high, level );\n\n    idx = unique_create( node.var, rhigh, rlow );\n  }\n  else\n  {\n    auto onset = count_solutions( bdd( this, f ) ) / ( 1ull << node.var );\n    auto all   = 1ull << ( nvars - node.var );\n\n    if ( ( onset << 1u ) > all ) /* if onset / all > .5 */\n    {\n      idx = 1u;\n    }\n  }\n  return cache.insert( f, level, (unsigned)bdd_operation::round, idx );\n}\n\nbdd_manager_ptr bdd_manager::create( unsigned nvars, unsigned log_max_objs, bool verbose )\n{\n  return std::make_shared<bdd_manager>( nvars, log_max_objs, verbose );\n}\n\nunsigned bdd_manager::unique_create( unsigned var, unsigned high, unsigned low )\n{\n  if ( verbose )\n  {\n    //std::cout << boost::format( \"[i] attempt to create (%d, %d, %d)\" ) % var % high % low << std::endl;\n  }\n  assert( var < nvars );\n  assert( var < nodes[high].var );\n  assert( var < nodes[low].var );\n\n  if ( high == low ) { return high; }\n\n  return unique_lookup( var, high, low );\n}\n\nstd::ostream& operator<<( std::ostream& os, const bdd_manager& mgr )\n{\n  for ( auto i : boost::counting_range( 0u, mgr.nvars + 2u ) )\n  {\n    os << i << \": \" << mgr.nodes[i] << std::endl;\n  }\n\n  auto * q = mgr.unique;\n\n  while ( q != mgr.unique + mgr.nodes.size() )\n  {\n    if ( *q )\n    {\n      os << *q << \": \" << mgr.nodes[*q] << std::endl;\n    }\n    ++q;\n  }\n\n  return os;\n}\n\nbdd& bdd::operator=( const bdd& other )\n{\n  if ( this == &other ) { return *this; }\n  assert( !manager || manager == other.manager );\n  manager = other.manager;\n  index   = other.index;\n  return *this;\n}\n\nunsigned bdd::var() const\n{\n  return manager->get_var( index );\n}\n\nbdd bdd::high() const\n{\n  return bdd( manager, manager->get_high( index ) );\n}\n\nbdd bdd::low() const\n{\n  return bdd( manager, manager->get_low( index ) );\n}\n\nbdd bdd::operator&&( const bdd& other ) const\n{\n  assert( manager == other.manager );\n  return bdd( manager, manager->bdd_and( index, other.index ) );\n}\n\nbdd bdd::operator||( const bdd& other ) const\n{\n  assert( manager == other.manager );\n  return bdd( manager, manager->bdd_or( index, other.index ) );\n}\n\nbdd bdd::operator^( const bdd& other ) const\n{\n  assert( manager == other.manager );\n  return bdd( manager, manager->bdd_xor( index, other.index ) );\n}\n\nbdd bdd::operator!() const\n{\n  return bdd( manager, manager->bdd_not( index ) );\n}\n\nbdd bdd::cof0( unsigned v ) const\n{\n  return bdd( manager, manager->bdd_cof0( index, v ) );\n}\n\nbdd bdd::cof1( unsigned v ) const\n{\n  return bdd( manager, manager->bdd_cof1( index, v ) );\n}\n\nbdd bdd::exists( const bdd& other ) const\n{\n  assert( manager == other.manager );\n  return bdd( manager, manager->bdd_exists( index, other.index ) );\n}\n\nbdd bdd::constrain( const bdd& other ) const\n{\n  assert( manager == other.manager );\n  return bdd( manager, manager->bdd_constrain( index, other.index ) );\n}\n\nbdd bdd::restrict( const bdd& other ) const\n{\n  assert( manager == other.manager );\n  return bdd( manager, manager->bdd_restrict( index, other.index ) );\n}\n\nbdd bdd::round_down( unsigned level ) const\n{\n  return bdd( manager, manager->bdd_round_down( index, level ) );\n}\n\nbdd bdd::round_up( unsigned level ) const\n{\n  return bdd( manager, manager->bdd_round_up( index, level ) );\n}\n\nbdd bdd::round( unsigned level ) const\n{\n  return bdd( manager, manager->bdd_round( index, level ) );\n}\n\nbool bdd::equals( const bdd& other ) const\n{\n  assert( manager == other.manager );\n  return index == other.index;\n}\n\nstd::ostream &operator<<(std::ostream &stream, bdd::const_param_ref bdd)\n{\n  if ( bdd.is_bot() ) {\n    return stream << \"(zero)\";\n  }\n  else if ( bdd.is_top() ) {\n    return stream << \"(one)\";\n  }\n  else {\n    return stream << boost::format ( \"(var=%d, high=%d, low=%d)\") % bdd.var() % bdd.high() % bdd.low();\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": "e5fe5a9a934be4abd14a9bde61c4e6ce4462f1bc", "size": 16442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/dd/bdd.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/dd/bdd.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/dd/bdd.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.1399046105, "max_line_length": 162, "alphanum_fraction": 0.5809512225, "num_tokens": 4869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04023794622027691, "lm_q1q2_score": 0.019961796830462085}}
{"text": "/// @file DeconvolverFiesta.tcc\n/// @brief Class for a deconvolver based on the Fista\n/// @details This concrete class defines a deconvolver used to estimate an\n/// image from a dirty image, psf optionally using a mask and a weights image.\n/// @ingroup Deconvolver\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Tim Cornwell <tim.cornwell@csiro.au>\n///\n\n#include <string>\n\n#include <casacore/casa/aips.h>\n#include <boost/shared_ptr.hpp>\n#include <casacore/casa/Arrays/Array.h>\n#include <casacore/casa/Arrays/ArrayMath.h>\n#include <casacore/casa/BasicSL/STLIO.h>\n\n#include <fft/FFTWrapper.h>\n#include <askap/AskapLogging.h>\nASKAP_LOGGER(decfistalogger, \".deconvolution.fista\");\n\n#include <deconvolution/DeconvolverFista.h>\n#include <deconvolution/MultiScaleBasisFunction.h>\n#include <measurementequation/SynthesisParamsHelper.h>\n#include <utils/ImageUtils.h>\n\nnamespace askap {\n\n    namespace synthesis {\n\n        /// @brief Class for a deconvolver based on the Fista Clean\n        /// @details This base class defines a deconvolver used to estimate an\n        /// image from a dirty image, psf optionally using a mask and a weights image.\n        /// The template argument T is the type, and FT is the transform\n        /// e.g. DeconvolverFista<Double, DComplex>\n        /// @ingroup Deconvolver\n\n        template<class T, class FT>\n        DeconvolverFista<T, FT>::~DeconvolverFista()\n        {\n        };\n\n        template<class T, class FT>\n        DeconvolverFista<T, FT>::DeconvolverFista(Vector<Array<T> >& dirty, Vector<Array<T> >& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf)\n        {\n            if (this->itsNumberDirtyTerms > 1) {\n                throw(AskapError(\"FISTA deconvolver cannot perform multi-term deconvolutions\"));\n            }\n        };\n\n        template<class T, class FT>\n        DeconvolverFista<T, FT>::DeconvolverFista(Array<T>& dirty, Array<T>& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf)\n        {\n        };\n\n        template<class T, class FT>\n        void DeconvolverFista<T, FT>::configure(const LOFAR::ParameterSet& parset)\n        {\n            DeconvolverBase<T, FT>::configure(parset);\n\n            // Make the basis function\n            {\n                std::vector<float> defaultScales(3);\n                defaultScales[0] = 0.0;\n                defaultScales[1] = 10.0;\n                defaultScales[2] = 30.0;\n                std::vector<float> scales = parset.getFloatVector(\"scales\", defaultScales);\n\n                ASKAPLOG_INFO_STR(decfistalogger, \"Constructing Multiscale basis function with scales \" << scales);\n                const Bool orthogonal = parset.getBool(\"orthogonal\", false);\n                if (orthogonal) {\n                    ASKAPLOG_DEBUG_STR(decfistalogger, \"Multiscale basis functions will be orthogonalised\");\n                }\n\n                itsBasisFunction = BasisFunction<Float>::ShPtr(new MultiScaleBasisFunction<Float>(scales,\n                                   orthogonal));\n            }\n        }\n\n        template<class T, class FT>\n        void DeconvolverFista<T, FT>::initialise()\n        {\n            DeconvolverBase<T, FT>::initialise();\n\n            if (itsBasisFunction) {\n                this->itsBasisFunction->initialise(this->model().shape());\n                itsBasisFunctionTransform.resize(itsBasisFunction->basisFunction().shape());\n                casa::setReal(itsBasisFunctionTransform, itsBasisFunction->basisFunction().nonDegenerate());\n                scimath::fft2d(itsBasisFunctionTransform, true);\n            }\n\n            ASKAPLOG_INFO_STR(decfistalogger, \"Initialised FISTA solver\");\n        }\n\n        template<class T, class FT>\n        bool DeconvolverFista<T, FT>::deconvolve()\n        {\n            this->initialise();\n\n            bool isMasked(this->itsWeight.nelements());\n            if (!this->itsWeight(0).shape().conform(this->dirty().shape())) isMasked = false;\n\n            Array<T> X, X_old, X_temp;\n\n            X_temp.resize(this->model().shape());\n            X_temp.set(T(0.0));\n\n            X_old.resize(this->model().shape());\n            X_old.set(T(0.0));\n\n            X.resize(this->model().shape());\n            X = this->model().copy();\n\n            T absPeakVal;\n\n            ASKAPLOG_INFO_STR(decfistalogger, \"Performing Fista for \" << this->control()->targetIter() << \" iterations\");\n\n            this->updateResiduals(X);\n\n            X_temp = X.copy();\n\n            absPeakVal = max(abs(this->dirty()));\n\n            //      T effectiveLambda(absPeakVal*this->control()->fractionalThreshold()+this->control()->lambda());\n            T lambda(absPeakVal*(1.0 - this->control()->gain()));\n            ASKAPLOG_INFO_STR(decfistalogger, \"Effective lambda = \" << lambda);\n\n            T t_new = 1;\n\n            T lipschitz(10.0);\n\n            do {\n                X_old = X_temp.copy();\n                T t_old = t_new;\n\n                this->updateResiduals(X);\n                scimath::saveAsCasaImage(\"residuals.tab\", this->dirty());\n\n                X = X + this->dirty() / lipschitz;\n\n                // Transform to other (e.g. multiscale) space\n                Array<T> WX;\n                scimath::saveAsCasaImage(\"X.tab\", X);\n                this->W(WX, X);\n                scimath::saveAsCasaImage(\"W.tab\", WX);\n\n                // Now shrink the coefficients towards zero and clip those below\n                // lambda/lipschitz.\n                Array<T> shrink(WX.shape());\n\n                Array<T> truncated(abs(WX) - lambda / lipschitz);\n                shrink = truncated(truncated > T(0.0));\n                shrink = sign(WX) * shrink;\n                shrink(truncated < T(0.0)) = T(0.0);\n\n                scimath::saveAsCasaImage(\"shrink.tab\", WX);\n                // Transform back from other (e.g. wavelet) space here\n\n                this->WT(X_temp, shrink);\n                scimath::saveAsCasaImage(\"WT.tab\", X_temp);\n\n                t_new = (T(1.0) + sqrt(T(1.0) + T(4.0) * square(t_old))) / T(2.0);\n                X = X_temp + ((t_old - T(1.0)) / t_new) * (X_temp - X_old);\n                {\n                    casa::IPosition minPos;\n                    casa::IPosition maxPos;\n                    T minVal(0.0), maxVal(0.0);\n                    if (isMasked) {\n                        casa::minMaxMasked(minVal, maxVal, minPos, maxPos,\n                                           this->dirty(),\n                                           this->itsWeight(0));\n                    } else {\n                        casa::minMax(minVal, maxVal, minPos, maxPos, this->dirty());\n                    }\n\n                    ASKAPLOG_INFO_STR(decfistalogger, \"   Maximum = \" << maxVal << \" at location \" << maxPos);\n                    ASKAPLOG_INFO_STR(decfistalogger, \"   Minimum = \" << minVal << \" at location \" << minPos);\n                    if (abs(minVal) < abs(maxVal)) {\n                        absPeakVal = abs(maxVal);\n                    } else {\n                        absPeakVal = abs(minVal);\n                    }\n                }\n\n                T l1Norm = sum(abs(X_temp));\n                T fit = casa::sum(this->dirty() * this->dirty());\n                T objectiveFunction(fit + lambda*l1Norm);\n                this->state()->setPeakResidual(absPeakVal);\n                this->state()->setObjectiveFunction(objectiveFunction);\n                this->state()->setTotalFlux(sum(X_temp));\n\n                if (absPeakVal < lambda) {\n                    lambda *= 1.0 - this->control()->gain();\n                    ASKAPLOG_INFO_STR(decfistalogger, \"Setting Lagrange multiplier lambda = \" << lambda);\n                }\n                this->monitor()->monitor(*(this->state()));\n                this->state()->incIter();\n            } while (!this->control()->terminate(*(this->state())));\n            this->model() = X_temp.copy();\n            this->updateResiduals(this->model());\n\n            ASKAPLOG_INFO_STR(decfistalogger, \"Performed Fista for \" << this->state()->currentIter() << \" iterations\");\n\n            ASKAPLOG_INFO_STR(decfistalogger, this->control()->terminationString());\n\n            this->finalise();\n\n            absPeakVal = casa::max(casa::abs(this->dirty()));\n\n            this->state()->setPeakResidual(absPeakVal);\n            this->state()->setObjectiveFunction(absPeakVal);\n\n            return True;\n        }\n\n        template<class T, class FT>\n        void DeconvolverFista<T, FT>::setBasisFunction(boost::shared_ptr<BasisFunction<T> > bf)\n        {\n            itsBasisFunction = bf;\n        };\n\n        template<class T, class FT>\n        boost::shared_ptr<BasisFunction<T> > DeconvolverFista<T, FT>::basisFunction()\n        {\n            return itsBasisFunction;\n        };\n\n        // Apply the convolve operation - this is undecimated and redundant. The 2D image\n        // will be expanded along the third axis. Since the basis functions are normalised\n        // to unit volume, the values here should be roughly maintained.\n        template <class T, class FT>\n        void DeconvolverFista<T, FT>::W(Array<T>& out, const Array<T>& in)\n        {\n            if (itsBasisFunction) {\n                casa::Array<FT> inTransform(in.nonDegenerate().shape());\n                casa::Array<FT> outPlaneTransform(in.nonDegenerate().shape());\n                out.resize(itsBasisFunction->basisFunction().shape());\n                casa::Cube<T> outCube(out);\n                casa::setReal(inTransform, in.nonDegenerate());\n                scimath::fft2d(inTransform, true);\n                const uInt nPlanes(itsBasisFunction->basisFunction().shape()(2));\n                for (uInt plane = 0; plane < nPlanes; plane++) {\n                    outPlaneTransform = inTransform.nonDegenerate() * Cube<FT>(itsBasisFunctionTransform).xyPlane(plane);\n                    scimath::fft2d(outPlaneTransform, false);\n                    outCube.xyPlane(plane) = real(outPlaneTransform);\n                }\n            } else {\n                out = in.copy();\n            }\n        }\n\n        // Apply the transpose of the W operation - this is undecimated and redundant so we need\n        // to sum over the planes\n        template <class T, class FT>\n        void DeconvolverFista<T, FT>::WT(Array<T>& out, const Array<T>& in)\n        {\n            if (itsBasisFunction) {\n                const Cube<T> inCube(in);\n                casa::Array<FT> inPlaneTransform(out.nonDegenerate().shape());\n                casa::Array<FT> outTransform(out.nonDegenerate().shape());\n                outTransform.set(FT(0.0));\n\n                // To reconstruct, we filter out each basis from the cumulative sum\n                // and then add the corresponding term from the in array.\n                const uInt nPlanes(itsBasisFunction->basisFunction().shape()(2));\n\n                casa::setReal(inPlaneTransform, inCube.xyPlane(nPlanes - 1));\n                scimath::fft2d(inPlaneTransform, true);\n                outTransform = Cube<FT>(itsBasisFunctionTransform).xyPlane(nPlanes - 1) * (inPlaneTransform);\n\n                for (uInt plane = 1; plane < nPlanes; plane++) {\n                    casa::setReal(inPlaneTransform, inCube.xyPlane(nPlanes - 1 - plane));\n                    scimath::fft2d(inPlaneTransform, true);\n                    outTransform = outTransform\n                                   + Cube<FT>(itsBasisFunctionTransform).xyPlane(nPlanes - 1 - plane) * (inPlaneTransform - outTransform);\n                }\n                scimath::fft2d(outTransform, false);\n                out.nonDegenerate() = real(outTransform);\n            } else {\n                out = in.copy();\n            }\n        }\n\n    } // namespace synthesis\n\n} // namespace askap\n", "meta": {"hexsha": "609e1f16286da4f6740d47b42f5825af7e0dd216", "size": 12728, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverFista.tcc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverFista.tcc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverFista.tcc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9260450161, "max_line_length": 138, "alphanum_fraction": 0.5625392835, "num_tokens": 2989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.04023793931468827, "lm_q1q2_score": 0.01996179340464217}}
{"text": "/**\n * Copyright (C) 2016 Turi\n * All rights reserved.\n *\n * This software may be modified and distributed under the terms\n * of the BSD license. See the LICENSE file for details.\n */\n/**  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n * \\file graph_ops.hpp\n *\n * This file supports basic graph io operations to simplify reading\n * and writing adjacency structures from files.\n *\n */\n\n#ifndef GRAPHLAB_GRAPH_OPS_HPP\n#define GRAPHLAB_GRAPH_OPS_HPP\n\n\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <boost/algorithm/string/predicate.hpp>\n#include <graph/distributed_graph.hpp>\n\n#include <graphlab/macros_def.hpp>\nnamespace graphlab {\n  \n\n  namespace graph_ops {\n    \n    \n    /**\n     * builds a topological_sort of the graph returning it in topsort. \n     * \n     * \\param[out] topsort Resultant topological sort of the graph vertices.\n     *\n     * function will return false if graph is not acyclic.\n     */\n    template <typename VertexType, typename EdgeType>\n    bool topological_sort(const distributed_graph<VertexType, EdgeType>& graph, \n                          std::vector<vertex_id_type>& topsort) {\n      typedef distributed_graph<VertexType, EdgeType> graph_type;\n      topsort.clear();\n      topsort.reserve(graph.num_vertices());\n      std::vector<size_t> indeg;\n      indeg.resize(graph.num_vertices());\n      std::queue<vertex_id_type> q;\n      for (size_t i = 0;i < graph.num_vertices(); ++i) {\n        indeg[i] = graph.get_in_edges(i).size();\n        if (indeg[i] == 0) {\n          q.push(i);\n        }\n      }\n    \n      while (!q.empty()) {\n        vertex_id_type v = q.front();\n        q.pop();\n        topsort.push_back(v);\n        foreach(typename graph_type::edge_type edge, graph.get_out_edges(v)) {\n          vertex_id_type destv = edge.target();\n          --indeg[destv];\n          if (indeg[destv] == 0) {\n            q.push(destv);\n          }\n        }\n      }\n      if (q.empty() && topsort.size() != graph.num_vertices()) {\n        return false;\n      }\n      return true;\n    } // end of topological sort\n\n\n    template <typename VertexType, typename EdgeType>\n    size_t num_neighbors(const distributed_graph<VertexType, EdgeType>& graph, \n                         vertex_id_type& vid) {\n      typedef distributed_graph<VertexType, EdgeType> graph_type;\n      typename graph_type::edge_list_type in_edges =  graph.in_edges(vid); \n      typename graph_type::edge_list_type out_edges = graph.out_edges(vid);\n      typename graph_type::edge_list_type::const_iterator i = in_edges.begin();\n      typename graph_type::edge_list_type::const_iterator j = out_edges.begin();\n      size_t count = 0;      \n      for( ; i != in_edges.end() && j != out_edges.end(); ++count) {\n        if(i->source() == j->target()) { \n          ++i; ++j; \n        } else if(i->source() < j->target()) { \n          ++i; \n        } else { \n          ++j; \n        }\n      }\n      for( ; i != in_edges.end(); ++i, ++count);\n      for( ; j != out_edges.end(); ++j, ++count);\n      return count;\n    } // end of num_neighbors\n\n\n\n    template <typename VertexType, typename EdgeType>\n    void neighbors(const distributed_graph<VertexType, EdgeType>& graph, \n                   const vertex_id_type vid,   \n                   std::vector<vertex_id_type>& neighbors ) {\n      typedef distributed_graph<VertexType, EdgeType> graph_type;\n      typename graph_type::edge_list_type in_edges =  graph.in_edges(vid); \n      typename graph_type::edge_list_type out_edges = graph.out_edges(vid);\n      typename graph_type::edge_list_type::const_iterator i = in_edges.begin();\n      typename graph_type::edge_list_type::const_iterator j = out_edges.begin();\n      while(i != in_edges.end() && j != out_edges.end()) {\n        if(i->source() == j->target()) { \n          neighbors.push_back(i->source()); \n          ++i; ++j; \n        } else if(i->source() < j->target()) {\n          neighbors.push_back(i->source()); \n          ++i; \n        } else { \n          neighbors.push_back(j->target()); \n          ++j; \n        } \n      }\n      for( ; i != in_edges.end(); ++i) neighbors.push_back(i->source());\n      for( ; j != out_edges.end(); ++j) neighbors.push_back(j->target());\n    } // end of neighbors\n\n\n\n\n    \n\n\n    \n    template <typename VertexType, typename EdgeType>\n    bool save_metis_structure(const std::string& filename,\n                              const distributed_graph<VertexType, EdgeType>& graph) { \n      typedef distributed_graph<VertexType, EdgeType> graph_type;\n      typedef typename graph_type::edge_type          edge_type;\n      typedef typename graph_type::edge_list_type     edge_list_type;\n    \n      std::ofstream fout(filename.c_str());\n      if(!fout.good()) return false;\n      // Count the number of actual edges\n      size_t nedges = 0;\n      for(vertex_id_type i = 0; i < graph.num_vertices(); ++i)\n        nedges += num_neighbors(graph, i);\n      fout << graph.num_vertices() << ' ' << (nedges/2) << '\\n';\n      // Save the adjacency structure\n      std::vector<vertex_id_type> neighbor_set;\n      for(vertex_id_type i = 0; i < graph.num_vertices(); ++i) {\n        neighbors(graph, i, neighbor_set);\n        for(size_t j = 0; j < neighbor_set.size(); ++j) {\n          fout << (neighbor_set[j] + 1);\n          if(j + 1 < neighbor_set.size()) fout << ' ';\n        }\n        fout << '\\n';\n      }\n      fout.close();\n      return true;\n    } // end of save metis\n\n\n\n\n\n    template <typename VertexType, typename EdgeType>\n    bool save_edge_list_structure(const std::string& filename,\n                                  const distributed_graph<VertexType, EdgeType>& graph) { \n      typedef distributed_graph<VertexType, EdgeType> graph_type;\n      typedef typename graph_type::edge_type          edge_type;\n      typedef typename graph_type::edge_list_type     edge_list_type;\n\n      std::ofstream fout(filename.c_str());\n      if(!fout.good()) return false;\n      for(vertex_id_type i = 0; i < graph.num_vertices(); ++i) \n        foreach(edge_type edge, graph.out_edges(i)) \n          fout << edge.source() << '\\t' << edge.target() << '\\n';      \n      fout.close();\n      return true;\n    } // end of save metis\n\n\n\n\n    template <typename VertexType, typename EdgeType>\n    bool save_zoltan_hypergraph_structure(const std::string& filename,\n                                          const distributed_graph<VertexType, EdgeType>& graph) { \n      typedef distributed_graph<VertexType, EdgeType> graph_type;\n      typedef typename graph_type::edge_type          edge_type;\n      typedef typename graph_type::edge_list_type     edge_list_type;\n\n      std::ofstream fout(filename.c_str());\n      if(!fout.good()) return false;\n\n      // ok. I need to uniquely number each edge.\n      // how?\n      boost::unordered_map<std::pair<vertex_id_type, \n        vertex_id_type>, size_t> edgetoid;\n      size_t curid = 0;\n      for(vertex_id_type i = 0; i < graph.num_vertices(); ++i) {\n        foreach(const typename graph_type::edge_type& edge, graph.in_edges(i)) {\n          std::pair<vertex_id_type, vertex_id_type> e = \n            std::make_pair(edge.source(), edge.target());\n          if (e.first > e.second) std::swap(e.first, e.second);\n          if (edgetoid.find(e) == edgetoid.end()) {\n            edgetoid[e] = curid;\n            ++curid;\n          }\n        }\n        foreach(const typename graph_type::edge_type& edge, graph.out_edges(i)) {\n          std::pair<vertex_id_type, vertex_id_type> e = \n            std::make_pair(edge.source(), edge.target());\n          if (e.first > e.second) std::swap(e.first, e.second);\n          if (edgetoid.find(e) == edgetoid.end()) {\n            edgetoid[e] = curid;\n            ++curid;\n          }\n        }\n      }\n\n      size_t numedges = curid;\n      // each edge is a vertex, each vertex is an edge\n      // a pin is total adjacency of a hyper edge\n      fout << numedges << \"\\n\\n\";\n      for (size_t i = 0;i < numedges; ++i) {\n        fout << i+1 << \"\\n\";\n      }\n      fout << \"\\n\";\n      fout << graph.num_vertices() << \"\\n\\n\";\n      \n      fout << numedges * 2 << \"\\n\\n\";\n      // loop over the \"hyperedge\" and write out the edges it is adjacent to\n      for(vertex_id_type i = 0; i < graph.num_vertices(); ++i) {\n        boost::unordered_set<size_t> adjedges;\n        foreach(const typename graph_type::edge_type& edge, graph.in_edges(i)) {\n          std::pair<vertex_id_type, vertex_id_type> e = \n            std::make_pair(edge.source(), edge.target());\n          if (e.first > e.second) std::swap(e.first, e.second);\n          adjedges.insert(edgetoid[e]);\n        }\n        foreach(const typename graph_type::edge_type& edge, graph.out_edges(i)) {\n          std::pair<vertex_id_type, vertex_id_type> e = \n            std::make_pair(edge.source(), edge.target());\n          if (e.first > e.second) std::swap(e.first, e.second);\n          adjedges.insert(edgetoid[e]);\n        }\n        // write\n        std::vector<size_t> adjedgesvec;\n        std::copy(adjedges.begin(), adjedges.end(), \n                  std::inserter(adjedgesvec, adjedgesvec.end()));\n        fout << i+1 << \" \" << adjedgesvec.size() << \"\\t\";        \n        for (size_t j = 0;j < adjedgesvec.size(); ++j) {\n          fout << adjedgesvec[j] + 1;\n          if (j < adjedgesvec.size() - 1) fout << \"\\t\";\n        }\n        fout << \"\\n\";\n      }\n      fout.close();\n      return true;\n    }  // end of save_zoltan_hypergraph_structure\n\n\n\n  }; // end of graph ops\n}; // end of namespace graphlab\n#include <graphlab/macros_undef.hpp>\n\n#endif\n\n\n\n\n\n", "meta": {"hexsha": "a784956eab39579f99e5ff528c39425622c3e26d", "size": 10213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "oss_src/graph/graph_ops.hpp", "max_stars_repo_name": "venkattgg/venkey", "max_stars_repo_head_hexsha": "796b9bdfb2fa1b881d82080754643c7e68629cd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 493.0, "max_stars_repo_stars_event_min_datetime": "2016-07-11T13:35:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T13:04:29.000Z", "max_issues_repo_path": "oss_src/graph/graph_ops.hpp", "max_issues_repo_name": "venkattgg/venkey", "max_issues_repo_head_hexsha": "796b9bdfb2fa1b881d82080754643c7e68629cd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2016-07-13T20:01:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T18:55:28.000Z", "max_forks_repo_path": "oss_src/graph/graph_ops.hpp", "max_forks_repo_name": "venkattgg/venkey", "max_forks_repo_head_hexsha": "796b9bdfb2fa1b881d82080754643c7e68629cd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 229.0, "max_forks_repo_forks_event_min_datetime": "2016-07-12T10:39:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T13:04:31.000Z", "avg_line_length": 34.3872053872, "max_line_length": 98, "alphanum_fraction": 0.5948301185, "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.056652424511612155, "lm_q1q2_score": 0.019953084870323348}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////\n// This file is distributed under the University of Illinois/NCSA Open Source License.\n// See LICENSE file in top directory for details.\n//\n// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.\n//\n// File developed by: Miguel Morales, moralessilva2@llnl.gov, Lawrence Livermore National Laboratory\n//                    Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign\n//                    Cynthia Gu, zg1@ornl.gov, Oak Ridge National Laboratory\n//                    Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign\n//                    Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory\n//\n// File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign\n//////////////////////////////////////////////////////////////////////////////////////\n\n\n#include <Configuration.h>\n#include \"Message/OpenMP.h\"\n#include \"OhmmsData/AttributeSet.h\"\n#include \"RandomNumberControl.h\"\n#include \"Utilities/RandomGeneratorIO.h\"\n#include \"Utilities/Timer.h\"\n#include \"hdf/HDFVersion.h\"\n#include \"hdf/hdf_archive.h\"\n#include \"mpi/collectives.h\"\n#if defined(HAVE_LIBBOOST)\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/foreach.hpp>\n#include <string>\n#include <set>\n#include <exception>\n#include <iostream>\n#endif\n#include \"Utilities/SimpleParser.h\"\n#include \"OhmmsData/Libxml2Doc.h\"\n\nnamespace qmcplusplus\n{\n///initialize the static data members\nPrimeNumberSet<RandomGenerator_t::uint_type> RandomNumberControl::PrimeNumbers;\nstd::vector<RandomGenerator_t*> RandomNumberControl::Children;\nRandomGenerator_t::uint_type RandomNumberControl::Offset = 11u;\n\n/// constructors and destructors\nRandomNumberControl::RandomNumberControl(const char* aname)\n    : OhmmsElementBase(aname), NeverBeenInitialized(true), myCur(NULL) //, Offset(5)\n{}\n\n/// generic output\nbool RandomNumberControl::get(std::ostream& os) const\n{\n  if (omp_get_max_threads() > 1)\n  {\n    for (int ip = 0; ip < omp_get_max_threads(); ip++)\n    {\n      Children[ip]->write(os);\n      os << std::endl;\n    }\n  }\n  else\n  {\n    Random.write(os);\n  }\n  return true;\n}\n\n/// generic input\nbool RandomNumberControl::put(std::istream& is) { return true; }\n\n/// reset the generator\nvoid RandomNumberControl::reset() { make_seeds(); }\n\n/// reset the generator\nvoid RandomNumberControl::make_seeds()\n{\n  int pid         = OHMMS::Controller->rank();\n  int nprocs      = OHMMS::Controller->size();\n  uint_type iseed = static_cast<uint_type>(std::time(0)) % 1024;\n  mpi::bcast(*OHMMS::Controller, iseed);\n  //OHMMS::Controller->bcast(iseed);//broadcast the seed\n  Offset = iseed;\n  std::vector<uint_type> mySeeds;\n  RandomNumberControl::PrimeNumbers.get(Offset, nprocs * (omp_get_max_threads() + 2), mySeeds);\n  Random.init(pid, nprocs, mySeeds[pid], Offset + pid);\n  //change children as well\n  make_children();\n}\n\nvoid RandomNumberControl::make_children()\n{\n  int nthreads = omp_get_max_threads();\n  int n        = nthreads - Children.size();\n  while (n)\n  {\n    Children.push_back(new RandomGenerator_t);\n    n--;\n  }\n  int rank       = OHMMS::Controller->rank();\n  int nprocs     = OHMMS::Controller->size();\n  int baseoffset = Offset + nprocs + nthreads * rank;\n  std::vector<uint_type> myprimes;\n  PrimeNumbers.get(baseoffset, nthreads, myprimes);\n  for (int ip = 0; ip < nthreads; ip++)\n  {\n    int offset = baseoffset + ip;\n    Children[ip]->init(rank, nprocs, myprimes[ip], offset);\n  }\n}\n\nxmlNodePtr RandomNumberControl::initialize(xmlXPathContextPtr acontext)\n{\n  OhmmsXPathObject rg_request(\"//random\", acontext);\n  put(rg_request[0]);\n  return myCur;\n}\n\nvoid RandomNumberControl::test()\n{\n  /* Add random number generator tester\n  */\n  int nthreads = omp_get_max_threads();\n  std::vector<double> avg(nthreads), avg2(nthreads);\n#pragma omp parallel for\n  for (int ip = 0; ip < nthreads; ++ip)\n  {\n    const int n = 1000000;\n    double sum = 0.0, sum2 = 0.0;\n    RandomGenerator_t& myrand(*Children[ip]);\n    for (int i = 0; i < n; ++i)\n    {\n      double r = myrand.rand();\n      sum += r;\n      sum2 += r * r;\n    }\n    avg[ip]  = sum / static_cast<double>(n);\n    avg2[ip] = sum2 / static_cast<double>(n);\n  }\n  std::vector<double> avg_tot(nthreads * OHMMS::Controller->size()), avg2_tot(nthreads * OHMMS::Controller->size());\n  mpi::gather(*OHMMS::Controller, avg, avg_tot);\n  mpi::gather(*OHMMS::Controller, avg2, avg2_tot);\n  double avg_g  = 0.0;\n  double avg2_g = 0.0;\n  for (int i = 0, ii = 0; i < OHMMS::Controller->size(); ++i)\n  {\n    for (int ip = 0; ip < nthreads; ++ip, ++ii)\n    {\n      app_log() << \"RNGTest \" << std::setw(4) << i << std::setw(4) << ip << std::setw(20) << avg_tot[ii]\n                << std::setw(20) << avg2_tot[ii] - avg_tot[ii] * avg_tot[ii] << std::endl;\n      avg_g += avg_tot[ii];\n      avg2_g += avg2_tot[ii];\n    }\n  }\n  avg_g /= static_cast<double>(nthreads * OHMMS::Controller->size());\n  avg2_g /= static_cast<double>(nthreads * OHMMS::Controller->size());\n  app_log() << \"RNGTest \" << std::setw(4) << OHMMS::Controller->size() << std::setw(4) << nthreads << std::setw(20)\n            << avg_g << std::setw(20) << avg2_g - avg_g * avg_g << std::endl;\n  app_log().flush();\n}\n\nbool RandomNumberControl::put(xmlNodePtr cur)\n{\n  if (NeverBeenInitialized)\n  {\n    bool init_mpi = true;\n    int offset_in = -1; // default is to generate by Wall-clock\n    if (cur != NULL)\n    {\n      std::string pname(\"yes\");\n      OhmmsAttributeSet oAttrib;\n      oAttrib.add(pname, \"parallel\");\n      oAttrib.add(offset_in, \"seed\");\n      oAttrib.put(cur);\n      if (pname == \"0\" || pname == \"false\" || pname == \"no\")\n        init_mpi = false;\n    }\n    int nprocs = 1;\n    int pid    = 0;\n    if (init_mpi)\n    {\n      pid    = OHMMS::Controller->rank();\n      nprocs = OHMMS::Controller->size();\n    }\n\n    app_summary() << std::endl;\n    app_summary() << \" Random Number\" << std::endl;\n    app_summary() << \" -------------\" << std::endl;\n    if (offset_in < 0)\n    {\n      offset_in = static_cast<int>(static_cast<uint_type>(std::time(0)) % 1024);\n      app_summary() << \"  Offset for the random number seeds based on time: \" << offset_in << std::endl;\n      mpi::bcast(*OHMMS::Controller, offset_in);\n    }\n    else\n    {\n      offset_in %= 1024;\n      app_summary() << \"  Offset for the random number seeds from input file (mod 1024): \" << offset_in << std::endl;\n    }\n    app_summary() << std::endl;\n    Offset = offset_in;\n    std::vector<uint_type> mySeeds;\n    //allocate twice of what is required\n    PrimeNumbers.get(Offset, nprocs * (omp_get_max_threads() + 2), mySeeds);\n    Random.init(pid, nprocs, mySeeds[pid], Offset + pid);\n    app_log() << \"  Range of prime numbers to use as seeds over processors and threads = \" << mySeeds[0] << \"-\"\n              << mySeeds[nprocs * omp_get_max_threads()] << std::endl;\n    app_log() << std::endl;\n\n    make_children();\n    NeverBeenInitialized = false;\n  }\n  else\n    reset();\n  return true;\n}\n\nvoid RandomNumberControl::read_old(const std::string& fname, Communicate* comm)\n{\n  int nthreads = omp_get_max_threads();\n  std::vector<uint_type> vt_tot, vt;\n  std::vector<int> shape(2, 0), shape_now(2, 0);\n  shape_now[0] = comm->size() * nthreads;\n  shape_now[1] = Random.state_size();\n\n  if (comm->rank() == 0)\n  {\n#if defined(HAVE_LIBBOOST)\n    using boost::property_tree::ptree;\n    ptree pt;\n    std::string xname = fname + \".random.xml\";\n    read_xml(xname, pt);\n    if (!pt.empty())\n    {\n      std::string engname = pt.get<std::string>(\"random.engine\");\n      if (engname == Random.EngineName)\n      {\n        std::istringstream dims(pt.get<std::string>(\"random.dims\"));\n        dims >> shape[0] >> shape[1];\n        if (shape[0] == shape_now[0] && shape[1] == shape_now[1])\n        {\n          vt_tot.resize(shape[0] * shape[1]);\n          std::istringstream v(pt.get<std::string>(\"random.states\"));\n          for (int i = 0; i < vt_tot.size(); ++i)\n            v >> vt_tot[i];\n        }\n        else\n          shape[0] = shape[1] = 0;\n      }\n    }\n#else\n    TinyVector<hsize_t, 2> shape_t(0);\n    shape_t[1] = Random.state_size();\n    hyperslab_proxy<std::vector<uint_type>, 2> slab(vt_tot, shape_t);\n    std::string h5name = fname + \".random.h5\";\n    hdf_archive hout(comm);\n    hout.open(h5name, H5F_ACC_RDONLY);\n    hout.push(hdf::main_state);\n    hout.push(\"random\");\n    std::string engname;\n    hout.read(slab, Random.EngineName);\n    shape[0] = static_cast<int>(slab.size(0));\n    shape[1] = static_cast<int>(slab.size(1));\n#endif\n  }\n\n  mpi::bcast(*comm, shape);\n\n  if (shape[0] != shape_now[0] || shape[1] != shape_now[1])\n  {\n    app_log() << \"Mismatched random number generators.\"\n              << \"\\n  Number of streams     : old=\" << shape[0] << \" new= \" << comm->size() * nthreads\n              << \"\\n  State size per stream : old=\" << shape[1] << \" new= \" << Random.state_size()\n              << \"\\n  Using the random streams generated at the initialization.\" << std::endl;\n    return;\n  }\n\n  app_log() << \"  Restart from the random number streams from the previous configuration.\" << std::endl;\n  vt.resize(nthreads * Random.state_size());\n\n  if (comm->size() > 1)\n    mpi::scatter(*comm, vt_tot, vt);\n  else\n    copy(vt_tot.begin(), vt_tot.end(), vt.begin());\n\n  {\n    if (nthreads > 1)\n    {\n      std::vector<uint_type>::iterator vt_it(vt.begin());\n      for (int ip = 0; ip < nthreads; ip++, vt_it += shape[1])\n      {\n        std::vector<uint_type> c(vt_it, vt_it + shape[1]);\n        Children[ip]->load(c);\n      }\n    }\n    else\n      Random.load(vt);\n  }\n}\n\nvoid RandomNumberControl::write_old(const std::string& fname, Communicate* comm)\n{\n  int nthreads = omp_get_max_threads();\n  std::vector<uint_type> vt, vt_tot;\n  vt.reserve(nthreads * 1024);\n  if (nthreads > 1)\n    for (int ip = 0; ip < nthreads; ++ip)\n    {\n      std::vector<uint_type> c;\n      Children[ip]->save(c);\n      vt.insert(vt.end(), c.begin(), c.end());\n    }\n  else\n    Random.save(vt);\n  if (comm->size() > 1)\n  {\n    vt_tot.resize(vt.size() * comm->size());\n    mpi::gather(*comm, vt, vt_tot);\n  }\n  else\n    vt_tot = vt;\n\n  if (comm->rank() == 0)\n  {\n#if defined(HAVE_LIBBOOST)\n    using boost::property_tree::ptree;\n    ptree pt;\n    std::ostringstream dims, vt_o;\n    dims << comm->size() * nthreads << \" \" << Random.state_size();\n    std::vector<uint_type>::iterator v = vt_tot.begin();\n    for (int i = 0; i < comm->size() * nthreads; ++i)\n    {\n      copy(v, v + Random.state_size(), std::ostream_iterator<uint_type>(vt_o, \" \"));\n      vt_o << std::endl;\n      v += Random.state_size();\n    }\n    pt.put(\"random.engine\", Random.EngineName);\n    pt.put(\"random.dims\", dims.str());\n    pt.put(\"random.states\", vt_o.str());\n    std::string xname = fname + \".random.xml\";\n    write_xml(xname, pt);\n#else\n    std::string h5name = fname + \".random.h5\";\n    hdf_archive hout(comm);\n    hout.create(h5name);\n    hout.push(hdf::main_state);\n    hout.push(\"random\");\n    TinyVector<hsize_t, 2> shape(comm->size() * nthreads, Random.state_size());\n    hyperslab_proxy<std::vector<uint_type>, 2> slab(vt_tot, shape);\n    hout.write(slab, Random.EngineName);\n    hout.close();\n#endif\n  }\n}\n\n/*New functions past this point*/\n//switch between read functions\nvoid RandomNumberControl::read(const std::string& fname, Communicate* comm)\n{\n  std::string h5name = fname + \".random.h5\";\n  hdf_archive hin(comm, true); //attempt to read in parallel\n  hin.open(h5name, H5F_ACC_RDONLY);\n  if (hin.is_parallel())\n    read_parallel(hin, comm);\n  else\n    read_rank_0(hin, comm);\n}\n\n//switch between write functions\nvoid RandomNumberControl::write(const std::string& fname, Communicate* comm)\n{\n  std::string h5name = fname + \".random.h5\";\n  hdf_archive hout(comm, true); //attempt to write in parallel\n  hout.create(h5name);\n  if (hout.is_parallel())\n    write_parallel(hout, comm);\n  else\n    write_rank_0(hout, comm);\n}\n\n//Parallel read\nvoid RandomNumberControl::read_parallel(hdf_archive& hin, Communicate* comm)\n{\n  // cast integer to size_t\n  const size_t nthreads = static_cast<size_t>(omp_get_max_threads());\n  const size_t comm_size = static_cast<size_t>(comm->size());\n  const size_t comm_rank = static_cast<size_t>(comm->rank());\n\n  std::vector<uint_type> vt, mt;\n  TinyVector<int, 3> shape_now(comm->size(), nthreads, Random.state_size()); //cur configuration\n  TinyVector<int, 3> shape_hdf5(3, 0);                                       //configuration when file was written\n\n  //grab shape and Random.state_size() used to create hdf5 file\n  hin.push(hdf::main_state);\n  hin.read(shape_hdf5, \"nprocs_nthreads_statesize\");\n\n  //if hdf5 file's shape and the current shape don't match, abort read\n  if (shape_hdf5[0] != shape_now[0] || shape_hdf5[1] != shape_now[1] || shape_hdf5[2] != shape_now[2])\n  {\n    app_log() << \"Mismatched random number generators.\"\n              << \"\\n  Number of procs in streams : old=\" << shape_hdf5[0] << \" new= \" << shape_now[0]\n              << \"\\n  Number of threads in streams : old=\" << shape_hdf5[1] << \" new= \" << shape_now[1]\n              << \"\\n  State size per stream : old=\" << shape_hdf5[2] << \" new= \" << shape_now[2]\n              << \"\\n  Using the random streams generated at the initialization.\\n\";\n    return;\n  }\n  app_log() << \"  Restart from the random number streams from the previous configuration.\\n\";\n\n  vt.resize(nthreads * Random.state_size()); //buffer for children[ip]\n  mt.resize(Random.state_size());            //buffer for single thread Random object of random nums\n\n  std::array<size_t, 2> shape{comm_size * nthreads, Random.state_size()}; //global dims of children dataset\n  std::array<size_t, 2> counts{nthreads, Random.state_size()};               //local dimensions of dataset\n  std::array<size_t, 2> offsets{comm_rank * nthreads, 0};                 //offsets for each process to read in\n\n  hin.push(\"random\"); //group that holds children[ip] random nums\n  hyperslab_proxy<std::vector<uint_type>, 2> slab(vt, shape, counts, offsets);\n  hin.read(slab, Random.EngineName);\n\n  hin.pop();\n  hin.push(\"random_master\"); //group that holds Random_th random nums\n  shape[0]   = comm->size(); //reset shape, counts and offset for non-multiple threads\n  counts[0]  = 1;\n  offsets[0] = comm->rank();\n  hyperslab_proxy<std::vector<uint_type>, 2> slab2(mt, shape, counts, offsets);\n  hin.read(slab2, Random.EngineName);\n  hin.close();\n\n  std::vector<uint_type>::iterator vt_it(vt.begin());\n  for (int ip = 0; ip < nthreads; ip++, vt_it += shape[1])\n  {\n    std::vector<uint_type> c(vt_it, vt_it + shape[1]);\n    Children[ip]->load(c); //load random nums back to program from buffer\n  }\n  Random.load(mt); //load random nums back to prog from buffer\n}\n\n//Parallel write\nvoid RandomNumberControl::write_parallel(hdf_archive& hout, Communicate* comm)\n{\n  // cast integer to size_t\n  const size_t nthreads = static_cast<size_t>(omp_get_max_threads());\n  const size_t comm_size = static_cast<size_t>(comm->size());\n  const size_t comm_rank = static_cast<size_t>(comm->rank());\n\n  std::vector<uint_type> vt, mt;\n  TinyVector<int, 3> shape_hdf5(comm->size(), nthreads, Random.state_size()); //configuration at write time\n  vt.reserve(nthreads * Random.state_size()); //buffer for random numbers from children[ip] of each thread\n  mt.reserve(Random.state_size());            //buffer for random numbers from single Random object\n\n  for (int ip = 0; ip < nthreads; ++ip)\n  {\n    std::vector<uint_type> c;\n    Children[ip]->save(c);\n    vt.insert(vt.end(), c.begin(), c.end()); //get nums from each thread into buffer\n  }\n  Random.save(mt); //get nums for single random object (no threads)\n\n  std::array<size_t, 2> shape{comm_size * nthreads, Random.state_size()}; //global dimensions\n  std::array<size_t, 2> counts{nthreads, Random.state_size()};               //local dimensions\n  std::array<size_t, 2> offsets{comm_rank * nthreads, 0};                 //offset for the file write\n\n  hout.push(hdf::main_state);\n  hout.write(shape_hdf5, \"nprocs_nthreads_statesize\"); //save the shape of the data at write\n\n  hout.push(\"random\"); //group for children[ip]\n  hyperslab_proxy<std::vector<uint_type>, 2> slab(vt, shape, counts, offsets);\n  hout.write(slab, Random.EngineName); //write to hdf5file\n  hout.pop();\n\n  shape[0]   = comm->size(); //adjust shape, counts, offset for just one thread\n  counts[0]  = 1;\n  offsets[0] = comm->rank();\n  hout.push(\"random_master\"); //group for random object without threads\n  hyperslab_proxy<std::vector<uint_type>, 2> slab2(mt, shape, counts, offsets);\n  hout.write(slab2, Random.EngineName); //write data to hdf5 file\n  hout.close();\n}\n\n//Scatter read\nvoid RandomNumberControl::read_rank_0(hdf_archive& hin, Communicate* comm)\n{\n  // cast integer to size_t\n  const size_t nthreads = static_cast<size_t>(omp_get_max_threads());\n  const size_t comm_size = static_cast<size_t>(comm->size());\n  const size_t comm_rank = static_cast<size_t>(comm->rank());\n\n  std::vector<uint_type> vt, vt_tot, mt, mt_tot;\n  TinyVector<size_t, 3> shape_now(comm_size, nthreads, Random.state_size()); //current configuration\n  TinyVector<size_t, 3> shape_hdf5;                                             //configuration when hdf5 file was written\n  std::array<size_t, 2> shape{comm_size * nthreads, Random.state_size()};    //dimensions of children dataset\n\n  //grab configuration of threads/procs and Random.state_size() in hdf5 file\n  if (comm->rank() == 0)\n  {\n    hin.push(hdf::main_state);\n    hin.read(shape_hdf5, \"nprocs_nthreads_statesize\");\n  }\n\n  mpi::bcast(*comm, shape_hdf5);\n\n  //if hdf5 file's configuration and current configuration don't match, abort read\n  if (shape_hdf5[0] != shape_now[0] || shape_hdf5[1] != shape_now[1] || shape_hdf5[2] != shape_now[2])\n  {\n    app_log() << \"Mismatched random number generators.\"\n              << \"\\n  Number of procs in streams : old=\" << shape_hdf5[0] << \" new= \" << shape_now[0]\n              << \"\\n  Number of threads in streams : old=\" << shape_hdf5[1] << \" new= \" << shape_now[1]\n              << \"\\n  State size per stream : old=\" << shape_hdf5[2] << \" new= \" << shape_now[2]\n              << \"\\n  Using the random streams generated at the initialization.\\n\";\n    return;\n  }\n  app_log() << \"  Restart from the random number streams from the previous configuration.\\n\";\n\n  vt.resize(nthreads * Random.state_size()); //buffer for random nums in children of each thread\n  mt.resize(Random.state_size());            //buffer for random numbers from single Random object\n\n  if (comm->rank() == 0)\n  {\n    hin.push(\"random\"); //group for children[ip] (Random.object for each thread)\n    vt_tot.resize(nthreads * Random.state_size() * comm->size());\n    hin.readSlabReshaped(vt_tot, shape, Random.EngineName);\n    hin.pop();\n\n    shape[0] = comm->size(); //reset shape to one thread per process\n    mt_tot.resize(Random.state_size() * comm->size());\n    hin.push(\"random_master\"); //group for single Random object\n    hin.readSlabReshaped(mt_tot, shape, Random.EngineName);\n    hin.close();\n  }\n\n  if (comm->size() > 1)\n  {\n    mpi::scatter(*comm, vt_tot, vt); //divide big buffer into on for each proc\n    mpi::scatter(*comm, mt_tot, mt);\n  }\n  else\n  {\n    copy(vt_tot.begin(), vt_tot.end(), vt.begin());\n    copy(mt_tot.begin(), mt_tot.end(), mt.begin());\n  }\n\n  std::vector<uint_type>::iterator vt_it(vt.begin());\n  for (int i = 0; i < nthreads; i++, vt_it += shape[1])\n  {\n    std::vector<uint_type> c(vt_it, vt_it + shape[1]);\n    Children[i]->load(c); //read seeds for each thread from buffer back into object\n  }\n  Random.load(mt); //read seeds back into object\n}\n\n//scatter write\nvoid RandomNumberControl::write_rank_0(hdf_archive& hout, Communicate* comm)\n{\n  // cast integer to size_t\n  const size_t nthreads = static_cast<size_t>(omp_get_max_threads());\n  const size_t comm_size = static_cast<size_t>(comm->size());\n  const size_t comm_rank = static_cast<size_t>(comm->rank());\n\n  std::vector<uint_type> vt, vt_tot, mt, mt_tot;\n  std::array<size_t, 2> shape{comm_size * nthreads, Random.state_size()};     //dimensions of children dataset\n  TinyVector<size_t, 3> shape_hdf5(comm_size, nthreads, Random.state_size()); //configuration at write time\n  vt.reserve(nthreads * Random.state_size()); //buffer for children[ip] (Random object of seeds for each thread)\n  mt.reserve(Random.state_size()); //buffer for single Random object of seeds, one per proc regardless of thread num\n\n  for (int i = 0; i < nthreads; ++i)\n  {\n    std::vector<uint_type> c;\n    Children[i]->save(c);\n    vt.insert(vt.end(), c.begin(), c.end()); //copy children[nthreads] seeds to buffer\n  }\n  Random.save(mt); //copy random_th seeds to buffer\n\n  if (comm->size() > 1)\n  {\n    vt_tot.resize(vt.size() * comm->size());\n    mt_tot.resize(mt.size() * comm->size());\n    mpi::gather(*comm, vt, vt_tot); //gather into one big buffer for master write\n    mpi::gather(*comm, mt, mt_tot);\n  }\n  else\n  {\n    vt_tot = vt;\n    mt_tot = mt;\n  }\n\n  if (comm->rank() == 0)\n  {\n    hout.push(hdf::main_state);\n    hout.write(shape_hdf5, \"nprocs_nthreads_statesize\"); //configuration at write time to file\n\n    hout.push(\"random\"); //group for children[ip]\n    hout.writeSlabReshaped(vt_tot, shape, Random.EngineName);\n    hout.pop();\n\n    shape[0] = comm->size();    //reset dims for single thread use\n    hout.push(\"random_master\"); //group for random_th object\n    hout.writeSlabReshaped(mt_tot, shape, Random.EngineName);\n    hout.close();\n  }\n}\n} // namespace qmcplusplus\n", "meta": {"hexsha": "0f3062d2f90309b4626f268234aac8c39c65c981", "size": 21546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OhmmsApp/RandomNumberControl.cpp", "max_stars_repo_name": "eugeneswalker/qmcpack", "max_stars_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OhmmsApp/RandomNumberControl.cpp", "max_issues_repo_name": "eugeneswalker/qmcpack", "max_issues_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "src/OhmmsApp/RandomNumberControl.cpp", "max_forks_repo_name": "williamfgc/qmcpack", "max_forks_repo_head_hexsha": "732b473841e7823a21ab55ff397eed059f0f2e96", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.850249584, "max_line_length": 122, "alphanum_fraction": 0.6404437018, "num_tokens": 6032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.044018652998225924, "lm_q1q2_score": 0.0199519760051239}}
{"text": "#ifndef CFG_BOOST_GRAPH_TRAITS_HPP\n#define CFG_BOOST_GRAPH_TRAITS_HPP\n\n/*\n * Convert a CFG into a BGL (Boost Graph Library) graph\n */\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#include <crab/cfg/cfg.hpp>\n\nnamespace crab {\n  namespace cfg {\n   namespace graph  {\n        template <typename G>\n        struct mk_in_edge: \n            public std::unary_function<typename boost::graph_traits<G>::vertex_descriptor,\n                                       typename boost::graph_traits<G>::edge_descriptor> {\n          typedef typename boost::graph_traits<G>::vertex_descriptor Node;\n          typedef typename boost::graph_traits<G>::edge_descriptor   Edge;\n          \n          Node _dst;\n          mk_in_edge () {}\n          mk_in_edge (const Node &dst) : _dst (dst) {}     \n          Edge operator() (const Node &src) const { return Edge (src, _dst); }\n        };\n      \n        template <typename G> \n        struct mk_out_edge: \n         public std::unary_function<typename boost::graph_traits<G>::vertex_descriptor,\n                                    typename boost::graph_traits<G>::edge_descriptor> {\n          typedef typename boost::graph_traits<G>::vertex_descriptor Node;\n          typedef typename boost::graph_traits<G>::edge_descriptor   Edge;\n          \n          Node _src;\n          mk_out_edge () {}\n          mk_out_edge (const Node &src) : _src (src) { }\n          Edge operator() (const Node &dst) const { return Edge (_src, dst); }\n        };\n    }  // end namespace graph\n  } // end namespace cfg\n} // end namespace crab\n\n\nnamespace boost {\n\n     // cfg\n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     struct graph_traits<crab::cfg::Cfg <BasicBlockLabel, VariableName, Number> >  {\n       typedef crab::cfg::Cfg<BasicBlockLabel, VariableName, Number> graph_t;\n       typedef BasicBlockLabel vertex_descriptor;\n       typedef std::pair<vertex_descriptor, vertex_descriptor> edge_descriptor;\n       typedef std::pair<const vertex_descriptor, \n                    const vertex_descriptor> const_edge_descriptor;\n       \n       typedef disallow_parallel_edge_tag edge_parallel_category;\n       typedef bidirectional_tag directed_category;\n       struct  this_graph_tag : virtual bidirectional_graph_tag, \n                                virtual vertex_list_graph_tag {};\n       typedef this_graph_tag traversal_category;\n       \n       typedef size_t vertices_size_type;\n       typedef size_t edges_size_type;\n       typedef size_t degree_size_type;\n\n       static vertex_descriptor null_vertex() {\n\t if (std::is_pointer<vertex_descriptor>::value)\n\t   return nullptr;\n\t else {\n\t   // XXX: if vertex_descriptor is a basic type then\n\t   // null_vertex will return an undefined value, otherwise it\n\t   // will return the result of calling the default\n\t   // constructor.\n\t   vertex_descriptor n;\n\t   return n;\n\t }\n       }    \n       \n       // iterator of basic_block_label_t's\n       typedef typename graph_t::label_iterator vertex_iterator;\n       // iterator of pairs of basic_block_label_t's\n       typedef transform_iterator<crab::cfg::graph::mk_in_edge<graph_t>, \n\t\t\t\t  typename graph_t::pred_iterator> in_edge_iterator;\n       // iterator of pairs of basic_block_label_t's\n       typedef transform_iterator<crab::cfg::graph::mk_out_edge<graph_t>, \n\t\t\t\t  typename graph_t::succ_iterator> out_edge_iterator; \n     }; // end class graph_traits\n\n\n     // cfg_ref\n     template<class CFG>\n     struct graph_traits<crab::cfg::cfg_ref<CFG> >  {\n       typedef crab::cfg::cfg_ref<CFG> graph_t;\n       typedef typename graph_t::basic_block_label_t vertex_descriptor;\n       typedef std::pair<vertex_descriptor, vertex_descriptor> edge_descriptor;\n       typedef std::pair<const vertex_descriptor, \n\t\t\t const vertex_descriptor> const_edge_descriptor;\n       \n       typedef disallow_parallel_edge_tag edge_parallel_category;\n       typedef bidirectional_tag directed_category;\n       struct  this_graph_tag : virtual bidirectional_graph_tag, \n                                virtual vertex_list_graph_tag {};\n       typedef this_graph_tag traversal_category;\n       \n       typedef size_t vertices_size_type;\n       typedef size_t edges_size_type;\n       typedef size_t degree_size_type;\n\n       static vertex_descriptor null_vertex() {\n\t if (std::is_pointer<vertex_descriptor>::value)\n\t   return nullptr;\n\t else {\n\t   // XXX: if vertex_descriptor is a basic type then\n\t   // null_vertex will return an undefined value, otherwise it\n\t   // will return the result of calling the default\n\t   // constructor.\n\t   vertex_descriptor n;\n\t   return n;\n\t }\n       }    \n\n       typedef typename graph_t::label_iterator vertex_iterator;\n       typedef boost::transform_iterator<crab::cfg::graph::mk_in_edge<graph_t>, \n                                         typename graph_t::pred_iterator> in_edge_iterator;\n       typedef boost::transform_iterator<crab::cfg::graph::mk_out_edge<graph_t>, \n                                         typename graph_t::succ_iterator> out_edge_iterator; \n     }; // end class graph_traits\n\n     // cfg_rev\n     template<class CFG>\n     struct graph_traits<crab::cfg::cfg_rev<CFG> >  {\n       typedef crab::cfg::cfg_rev<CFG> graph_t;\n       typedef typename graph_t::basic_block_label_t vertex_descriptor;\n       typedef std::pair<vertex_descriptor, vertex_descriptor> edge_descriptor;\n       typedef std::pair<const vertex_descriptor, \n\t\t\t const vertex_descriptor> const_edge_descriptor;\n       \n       typedef disallow_parallel_edge_tag edge_parallel_category;\n       typedef bidirectional_tag directed_category;\n       struct  this_graph_tag : virtual bidirectional_graph_tag, \n                                virtual vertex_list_graph_tag {};\n       typedef this_graph_tag traversal_category;\n       \n       typedef size_t vertices_size_type;\n       typedef size_t edges_size_type;\n       typedef size_t degree_size_type;\n\n       static vertex_descriptor null_vertex() {\n\t if (std::is_pointer<vertex_descriptor>::value)\n\t   return nullptr;\n\t else {\n\t   // XXX: if vertex_descriptor is a basic type then\n\t   // null_vertex will return an undefined value, otherwise it\n\t   // will return the result of calling the default\n\t   // constructor.\t   \n\t   vertex_descriptor n;\n\t   return n;\n\t }\n       }    \n\n       typedef typename graph_t::label_iterator vertex_iterator;\n       typedef boost::transform_iterator<crab::cfg::graph::mk_in_edge<graph_t>, \n                                         typename graph_t::pred_iterator> in_edge_iterator;\n       typedef boost::transform_iterator<crab::cfg::graph::mk_out_edge<graph_t>, \n                                         typename graph_t::succ_iterator> out_edge_iterator; \n     }; // end class graph_traits\n\n} // end namespace\n\n\n// XXX: do not put it in the boost namespace because it won't compile\nnamespace crab {   \n   namespace cfg {   \n\n     // cfg\n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     inline std::pair<typename\n\t\t boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\t vertex_iterator, \n                 typename\n\t\t boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\t vertex_iterator > \n     vertices (Cfg<BasicBlockLabel,VariableName,Number> g) {\n       return std::make_pair (g.label_begin (), g.label_end ());\n     }\n   \n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     inline std::pair< typename\n\t\t  boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\t  out_edge_iterator, \n                  typename\n\t\t  boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\t  out_edge_iterator >\n     out_edges (typename\n\t\tboost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\tvertex_descriptor v, \n                Cfg<BasicBlockLabel,VariableName,Number> g) {\n       typedef Cfg<BasicBlockLabel,VariableName,Number> G;\n       \n       auto& node = g.get_node (v);\n       auto p = node.next_blocks ();\n       return std::make_pair (boost::make_transform_iterator\n\t\t\t      (p.first, graph::mk_out_edge<G> (v)),\n                              boost::make_transform_iterator\n\t\t\t      (p.second, graph::mk_out_edge<G> (v)));\n\t\t\t       \n     }\n   \n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     inline std::pair< typename\n\t\t  boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\t  in_edge_iterator, \n                  typename\n\t\t  boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\t  in_edge_iterator >\n     in_edges (typename\n\t       boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t       vertex_descriptor v, \n               Cfg<BasicBlockLabel,VariableName,Number> g) {\n       typedef Cfg<BasicBlockLabel,VariableName,Number> G;\n       \n       auto& node = g.get_node (v);\n       auto p = node.prev_blocks ();\n       return std::make_pair (boost::make_transform_iterator\n\t\t\t      (p.first, \n\t\t\t       graph::mk_in_edge<G> (v)),\n                              boost::make_transform_iterator\n\t\t\t      (p.second, \n\t\t\t       graph::mk_in_edge<G> (v)));\n     }\n   \n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     typename boost::graph_traits<Cfg<BasicBlockLabel,VariableName, Number> >::\n     vertices_size_type\n     num_vertices (Cfg<BasicBlockLabel,VariableName, Number> g) {\n       return std::distance (g.label_begin (), g.label_end ());\n     }\n   \n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     typename boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n     degree_size_type\n     in_degree (typename\n\t\tboost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\tvertex_descriptor v, \n                Cfg<BasicBlockLabel,VariableName,Number> g) {\n       auto preds = g.prev_nodes (v);\n       return std::distance (preds.begin (), preds.end ());\n     }\n   \n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     typename boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n     degree_size_type\n     out_degree (typename\n\t\t boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t\t vertex_descriptor v, \n                 Cfg<BasicBlockLabel,VariableName,Number> g) {\n       auto succs = g.next_nodes (v);\n       return std::distance (succs.begin (), succs.end ());\n     }\n   \n     template<typename BasicBlockLabel, typename VariableName, typename Number>\n     typename boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n     degree_size_type\n     degree (typename\n\t     boost::graph_traits<Cfg<BasicBlockLabel,VariableName,Number> >::\n\t     vertex_descriptor v, \n             Cfg<BasicBlockLabel,VariableName,Number> g) {\n       return out_degree (v, g) + in_degree (v, g);\n     }\n\n     // cfg_ref\n\n     template<class CFG>\n     inline std::pair<typename boost::graph_traits<cfg_ref<CFG> >::vertex_iterator, \n\t\t      typename boost::graph_traits<cfg_ref<CFG> >::vertex_iterator> \n     vertices (cfg_ref<CFG> g) {\n       return std::make_pair (g.label_begin (), g.label_end ());\n     }\n   \n     template<class CFG>\n     inline std::pair<typename boost::graph_traits<cfg_ref<CFG> >::out_edge_iterator, \n\t\t      typename boost::graph_traits<cfg_ref<CFG> >::out_edge_iterator>\n     out_edges (typename boost::graph_traits<cfg_ref<CFG> >::vertex_descriptor v, \n                cfg_ref<CFG> g) {\n       typedef cfg_ref<CFG> G;\n       auto &node = g.get_node (v);\n       auto p = node.next_blocks ();\n       return std::make_pair (boost::make_transform_iterator\n\t\t\t      (p.first, graph::mk_out_edge<G> (v)),\n                              boost::make_transform_iterator\n\t\t\t      (p.second, graph::mk_out_edge<G> (v)));\n\t\t\t       \n     }\n   \n     template<class CFG>\n     inline std::pair<typename boost::graph_traits<cfg_ref<CFG> >::in_edge_iterator, \n\t\t      typename boost::graph_traits<cfg_ref<CFG> >::in_edge_iterator>\n     in_edges (typename boost::graph_traits<cfg_ref<CFG> >::vertex_descriptor v, \n               cfg_ref<CFG> g) {\n       typedef cfg_ref<CFG> G;\n       auto &node = g.get_node (v);\n       auto p = node.prev_blocks ();\n       return std::make_pair (boost::make_transform_iterator\n\t\t\t      (p.first, graph::mk_in_edge<G> (v)),\n                              boost::make_transform_iterator\n\t\t\t      (p.second, graph::mk_in_edge<G> (v)));\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_ref<CFG> >::vertices_size_type\n     num_vertices (cfg_ref<CFG> g) {\n       return std::distance (g.label_begin (), g.label_end ());\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_ref<CFG> >::degree_size_type\n     in_degree (typename boost::graph_traits<cfg_ref<CFG> >::vertex_descriptor v, \n                cfg_ref<CFG> g) {\n       auto preds = g.prev_nodes (v);\n       return std::distance (preds.begin (), preds.end ());\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_ref<CFG> >::degree_size_type\n     out_degree (typename boost::graph_traits<cfg_ref<CFG> >::vertex_descriptor v, \n                 cfg_ref<CFG> g) {\n       auto succs = g.next_nodes (v);\n       return std::distance (succs.begin (), succs.end ());\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_ref<CFG> >::degree_size_type\n     degree (typename boost::graph_traits<cfg_ref<CFG> >::vertex_descriptor v, \n             cfg_ref<CFG> g) {\n       return out_degree (v, g) + in_degree (v, g);\n     }\n\n     // cfg_rev\n\n     template<class CFG>\n     inline std::pair<typename boost::graph_traits<cfg_rev<CFG> >::vertex_iterator, \n\t\t      typename boost::graph_traits<cfg_rev<CFG> >::vertex_iterator> \n     vertices (cfg_rev<CFG> g) {\n       return std::make_pair (g.label_begin (), g.label_end ());\n     }\n   \n     template<class CFG>\n     inline std::pair<typename boost::graph_traits<cfg_rev<CFG> >::out_edge_iterator, \n\t\t      typename boost::graph_traits<cfg_rev<CFG> >::out_edge_iterator>\n     out_edges (typename boost::graph_traits<cfg_rev<CFG> >::vertex_descriptor v, \n                cfg_rev<CFG> g) {\n       typedef cfg_rev<CFG> G;\n       auto &node = g.get_node (v);\n       auto p = node.next_blocks ();\n       return std::make_pair (boost::make_transform_iterator\n\t\t\t      (p.first, graph::mk_out_edge<G> (v)),\n                              boost::make_transform_iterator\n\t\t\t      (p.second, \n\t\t\t       graph::mk_out_edge<G> (v)));\n     }\n   \n     template<class CFG>\n     inline std::pair<typename boost::graph_traits<cfg_rev<CFG> >::in_edge_iterator, \n\t\t      typename boost::graph_traits<cfg_rev<CFG> >::in_edge_iterator>\n     in_edges (typename boost::graph_traits<cfg_rev<CFG> >::vertex_descriptor v, \n               cfg_rev<CFG> g) {\n       typedef cfg_rev<CFG> G;\n       auto &node = g.get_node (v);\n       auto p = node.prev_blocks ();\n       return std::make_pair (boost::make_transform_iterator\n\t\t\t      (p.first, graph::mk_in_edge<G> (v)),\n                              boost::make_transform_iterator\n\t\t\t      (p.second, graph::mk_in_edge<G> (v)));\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_rev<CFG> >::vertices_size_type\n     num_vertices (cfg_rev<CFG> g) {\n       return std::distance (g.label_begin (), g.label_end ());\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_rev<CFG> >::degree_size_type\n     in_degree (typename boost::graph_traits<cfg_rev<CFG> >::vertex_descriptor v, \n                cfg_rev<CFG> g) {\n       auto preds = g.prev_nodes (v);\n       return std::distance (preds.begin (), preds.end ());\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_rev<CFG> >::degree_size_type\n     out_degree (typename boost::graph_traits<cfg_rev<CFG> >::vertex_descriptor v, \n                 cfg_rev<CFG> g) {\n       auto succs = g.next_nodes (v);\n       return std::distance (succs.begin (), succs.end ());\n     }\n   \n     template<class CFG>\n     typename boost::graph_traits<cfg_rev<CFG> >::degree_size_type\n     degree (typename boost::graph_traits<cfg_rev<CFG> >::vertex_descriptor v, \n             cfg_rev<CFG> g) {\n       return out_degree (v, g) + in_degree (v, g);\n     }\n\n } // namespace cfg\n} // namespace crab\n\n#endif \n", "meta": {"hexsha": "c0a5d73d158318b9bfce25c6ad5a4f78cc9c75ad", "size": 16299, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/cfg/cfg_bgl.hpp", "max_stars_repo_name": "DavidFarago/crab", "max_stars_repo_head_hexsha": "c5fba9a132afea11c10f2790d232d192b2d0ae9c", "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/cfg/cfg_bgl.hpp", "max_issues_repo_name": "DavidFarago/crab", "max_issues_repo_head_hexsha": "c5fba9a132afea11c10f2790d232d192b2d0ae9c", "max_issues_repo_licenses": ["Apache-2.0"], "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/cfg/cfg_bgl.hpp", "max_forks_repo_name": "DavidFarago/crab", "max_forks_repo_head_hexsha": "c5fba9a132afea11c10f2790d232d192b2d0ae9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-01T12:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-01T12:33:53.000Z", "avg_line_length": 39.7536585366, "max_line_length": 93, "alphanum_fraction": 0.648199276, "num_tokens": 3721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.04084571722347213, "lm_q1q2_score": 0.019944285489170526}}
{"text": "/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  libDAI is licensed under the terms of the GNU General Public License version\n *  2, or (at your option) any later version. libDAI is distributed without any\n *  warranty. See the file COPYING for more details.\n *\n *  Copyright (C) 2010  Joris Mooij  [joris dot mooij at libdai dot org]\n */\n\n#include <dai/alldai.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"dai/emrun.h\"\n#include <dai/util.h>\n#include <string>\n#include <sys/stat.h>\n#include <time.h>\n\n#include <iomanip>      // std::setprecision\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <boost/lexical_cast.hpp>\nusing namespace std;\nusing namespace dai;\n\n// GA - initialization\nsize_t max_gen = 25; // no. of generations\nsize_t population_size = 20; // population size\nReal pc;// = 0.8; // crossover probability - between 0.6 an 0.9\nReal pm;// = 0.3; // mutation probability - between 1/pop.size and 1/chromosome_length\nint population_no=0; // current population id\n\n// 1. Creating initial population of EM runs \n\t\nchar* gibbsfile;// = \"/home/priya/libDAI-0.3.1/alarm/500/5.tab\";\n//const char* gibbsfile = argv[1];\nstring alarmfgloc;// = \"/home/priya/libDAI-0.3.1/alarm_learned_factor_graphs/\"; \nstring alarmlearnedfgloc;// = \"/home/priya/libDAI-0.3.1/alarm_learned_factor_graphs/\";\nconst char* networkname = \"carstarts\";\nsize_t maxIters =1000; // maximum number of iterations\n\nofstream out;\nEMRun* runname;\nvector <EMRun*> layer; \nvector <EMRun*> layer_finalval;\n//\n// Generate a random number between 0 and 1\n// return a uniform number in [0,1].\ndouble unifRand()\n{\n    return rand() / double(RAND_MAX);\n}\n// Reset the random number generator with the system clock.\nvoid seed()\n{\n\t/*Declare variable to hold seconds on clock.*/\n//\ttime_t seconds;\n\t/*Get value from system clock and place in seconds variable.*/\n//\ttime(&seconds);\n\t/*Convert seconds to a unsigned integer.*/\n     struct timeval time; \n     gettimeofday(&time,NULL);\n\n     // microsecond has 1 000 000\n     srand((time.tv_sec * 1000) + (time.tv_usec / 10));\n}\n\nstd::string& trim(std::string& s, const char* t = \" \\t\\n\\r\\f\\v\")\n{\n\ts.erase(0, s.find_first_not_of(t));\n\ts.erase(s.find_last_not_of(t) + 1);\n\treturn s;\n}\n\nvoid startEM()\n{\n\tsize_t i =0,j=0;\n\twhile(i<population_size)\n\t{\n\t string number; \n\t stringstream num; \n\t num << i; \n\t number = num.str();\n\t string dirname; \n\t stringstream p_id; \n\t p_id << population_no; \n\t dirname = p_id.str();\n\t string fgfileloc =  alarmfgloc + dirname+\"/\"+\"carstarts_\"+number+\".fg\";\n\t const char* fgfile = &fgfileloc[0];\n\n\t runname = new EMRun(networkname, i, fgfile, gibbsfile); // args are -1.network name 2.factor-graph number 3. evidencefile\n\n\t // 2. Run EM\n\t boost::thread threadid(boost::bind(&EMRun::startEM, boost::ref(runname), maxIters)); // args - max iters \n\t layer.push_back(runname); \n\t sleep(1);\n\t // 4. Next individual\n\t i=i+1;\n\t}\n\n}\n\nvoid checkEMforTermination()\n{\n         string dirname; \n\t stringstream p_id; \n\t p_id << population_no; \n\t dirname = p_id.str();\n\tstring loc =  alarmlearnedfgloc + \"learned/\"+dirname+\"/\";\n\tconst char* learnedloc = &loc[0];\n\tmkdir(learnedloc,0755);\n\twhile (true){\n\t    //cout<<\"in while loop \"<<layer.size()<<endl;\n\t    vector<EMRun*>::iterator it; \n\t    for (it=layer.begin(); it != layer.end(); ++it){    \n\t      //cout<<\"layer size \"<<layer.size()<<endl;\t\n\t      if((*it)->hasTerminated()) { //if it has terminated, set the run aside\t   \n\t\tdouble ll = (*it)->getLL();\n\t\tdouble iters = (*it)->getIters();\n\t\tdouble runid = (*it)->getRun();\n\t\tstring number; \n\t\tstringstream num; \n\t\tnum << runid; \n\t\tnumber = num.str();\n\t \tstring fglearnedfileloc =  alarmlearnedfgloc + \"learned/\"+dirname+\"/carstarts_\"+number+\".fg\";\n\t    \tconst char* fglearnedfile = &fglearnedfileloc[0];\n\t\t//cout<<\"Run number \"<<number<<\" ll = \"<<ll<<\" iters = \"<<iters<<endl;\t\n\t\t// 3. Store the learned factor graphs\n\t\tInfAlg* inf = (*it)->getInf();\n\t\tofstream learnedstream;\n\t\t//cout<<\"learned file = \"<<fglearnedfile<<endl;\n\t\tlearnedstream.open(fglearnedfile);\n\t\tlearnedstream.precision(12);\n\t\tlearnedstream << inf->fg();  \n\t\tlearnedstream.flush();\n\t\tlearnedstream.close();\n\t\tdelete inf;\n\t\tsleep(1);\n\t\t//cout<<\"Run number \"<<number<<\" has terminated\"<<endl;\n\t\tout<<pc<<\" \"<<pm<<\" \"<<gibbsfile<<\" \"<<fglearnedfile<<\" \"<<runid<<\" \"<<iters<<\" \"<<ll<<\" \"<<endl; \n\t\tlayer_finalval.push_back(*it); \n\t\tlayer.erase(it);\t\n\t\tif (layer.size() == 0){break;}\n\t\telse { it = layer.begin(); }\n\t      }\n\t      else if(((*it)->getIters()) == maxIters){ //we stop the run\n\t\tdouble ll = (*it)->getLL();\n\t\tdouble iters = (*it)->getIters();\n\t\tdouble runid = (*it)->getRun();\n\t\tstring number; \n\t\tstringstream num; \n\t\tnum << runid; \n\t\tnumber = num.str();\n\t \tstring fglearnedfileloc =  alarmlearnedfgloc + \"learned/\"+dirname+\"/carstarts_\"+number+\".fg\";\n\t    \tconst char* fglearnedfile = &fglearnedfileloc[0];\n\t\t//cout<<\"Run number \"<<number<<\" ll = \"<<ll<<\" iters = \"<<iters<<endl;\t\n\t\t//cout<<\"Run \"<<(*it)->getRun()<<\" has reached maximum iterations, so stopping the run\"<<endl;\n\t\tboost::thread thread5(boost::bind(&EMRun::stopEM, boost::ref(*it))); \n\t \t// 3. Store the learned factor graphs\n\t\tInfAlg *inf = (*it)->getInf();\n\t    \tofstream learnedstream;\n\t    \t//cout<<\"learned file = \"<<fglearnedfile<<endl;\n\t    \tlearnedstream.open(fglearnedfile);\n\t    \tlearnedstream.precision(12);\n\t    \tlearnedstream << inf->fg();  \n\t    \tlearnedstream.close();\n\t\tdelete inf;\n\t\tsleep(1);\t\t\n\t\t//cout<<\"Run number \"<<number<<\" has reached maximum iterations so stopped\"<<endl;\n\t\tout<<pc<<\" \"<<pm<<\" \"<<gibbsfile<<\" \"<<fglearnedfile<<\" \"<<runid<<\" \"<<iters<<\" \"<<ll<<\" \"<<endl; \n\t\tlayer_finalval.push_back(*it); \n\t\tlayer.erase(it);\n\t//\tif (layer.size() == 0){break;}\n\t//\telse { it = layer.begin(); }\n\t      }\n\t      //cout<<\"Going ..\"<<endl;     \n\t }\n\t if (layer.size() == 0){ //cout<<\"breaking while\"<<endl; \n\t\tbreak; }\n\t else { //cout<<\"iterating\"<<endl;\n\t\t}\n\t  sleep(1); \n\t}\n}\nstd::string doMutation(string line)\n{\t\n\tseed(); \n\tstd::vector<std::string> fields;\n\tfields = tokenizeString( line, true,\"  \");\n\tstring state_line, param_line;\n\tstringstream v;\n\tdouble val = unifRand();\n\t//  cout << fixed << setprecision(12) << val <<endl;\n\tv << fixed << setprecision(15) << val; // a random number is generated\n\tfor( size_t i = 0; i < fields.size(); ++i ) {\n\t   stringstream n;\n\t   n << fields[i]; \n\t   string s = n.str();\t\t\t\t   \n\t   if( s.find_first_not_of(\" \")!= std::string::npos){\n\t //\t//cout << \" val - \" <<s<<endl;\n\t\tif(i == 0)\n\t\tstate_line =s; // this is the index\n\t  }\n\t}\n\tline = state_line+\"   \"+v.str(); // combining the index and the random value\n\treturn line; // return the new cpt value\n}\nvoid doCrossoverandMutation()\n{\n\t// compute crossover probability\n\t seed();\n\t double pcross = unifRand(); // generates random a value between 0 and 1\t\n\t//cout<<\"Crossover probability \"<<pcross<<endl;\n\t// 4. Select 2 parents randomly\n\tconst int LOW = 0;\n\tconst int HIGH = 19;\n\t//int t =5; \n\tint t=20;\n\t// Generate the random variables to select as parents where 't' is the number of variables\n\t/*Declare variable to hold seconds on clock.*/\n\ttime_t seconds;\n\t/*Get value from system clock and place in seconds variable.*/\n\ttime(&seconds);\n\t/*Convert seconds to a unsigned integer.*/\n\tsrand(time(0));\n\tset<int> myset;\n\tset<int>::iterator it;\n\tsize_t k =0,p=0;\n\tint *arrval = new int[t];\n\tstring dirname; \n\tstringstream p_id; \n\tp_id << population_no; \n\tdirname = p_id.str();\n\tstring dirname2; \n\tstringstream p_id2; \n\tp_id2 << population_no+1; \n\tdirname2 = p_id2.str();\n\n\tstring childloc =  alarmlearnedfgloc + dirname2+\"/\";\n\tconst char* childfgloc = &childloc[0];\n\tmkdir(childfgloc,0755);\n\tfor( size_t n = 0; n < t; n++ )\n\t{ \n\t   int val = rand() % (HIGH - LOW + 1) + LOW;\n\t   it=myset.find(val);\n\t   arrval[n] = val;\n\t   if(it==myset.end()) // if the value is not in the set\n\t   {\n\t\tmyset.insert(val);\n\t\tp++;\n\t\tif(p == 2)\n\t\t{\n\t\t //cout <<\"Random value is\"<<arrval[n]<<\" and \"<< arrval[n-1]<<endl;\n\t\t string number1; \n\t\t stringstream num1; \n\t\t num1 << arrval[n]; \n\t\t number1 = num1.str();\n\t\t string parent1 =  alarmlearnedfgloc +\"learned/\"+dirname+\"/\"+ \"carstarts_\"+number1+\".fg\";\n\t\t string child1 =  childloc+ \"carstarts_\"+number1+\".fg\";\n\t\t const char* parentfgfile1 = &parent1[0];\n\t\t const char* childfgfile1 = &child1[0];\n\t\t string number2; \n\t\t stringstream num2; \n\t\t num2 << arrval[n-1]; \n\t\t number2 = num2.str();\n\t\t string parent2 = alarmlearnedfgloc +\"learned/\"+dirname+\"/\"+ \"carstarts_\"+number2+\".fg\";\n\t\t string child2 =  childloc+ \"carstarts_\"+number2+\".fg\";\n\t\t const char* parentfgfile2 = &parent2[0];\n\t\t const char* childfgfile2 = &child2[0];\t \n\t\t //cout<<\"parent files are \"<< parentfgfile1<< \" and \"<< parentfgfile2<<endl;\n\t\t //cout<<\"child files are \"<< childfgfile1<<\" and \"<<childfgfile2<<endl;\n\t \n\t\t string line1,line2;\n\t\t ifstream p1 (parentfgfile1);  ifstream p2 (parentfgfile2);\n\t\t ofstream c1 (childfgfile1);  ofstream c2 (childfgfile2);\n\t\t// 5. Do crossover and create two children\n\t\t// randomly select a crossover point\n\t\t int cr_pt = (rand() % 17) +1;\n\t\t int c = 0; // count of parameters\n\t \t int p_c1 = 0, p_c2 =0; // counter to skip the first four config lines in the cpt of the fg file\n\t\t //cout<<\"Crossover point is \"<< cr_pt<<endl;\n\t\t double pmut1=0, pmut2 =0;\n\t\t if (p1.is_open() && p2.is_open())\n\t\t {\n\t\t\t getline(p1,line1); getline(p2,line2);\n\t\t\t c1<< line1<<endl;\n\t\t\t c2<< line2<<endl;\t\t\t\t\t\n\n\t\t\t while(getline(p1,line1) && getline(p2,line2))\n\t\t\t {\n\t\t\t\t////cout<<line1 << \" \"<< line2 <<endl;\n\t\t\t\tline1 = trim(line1); line2 = trim(line2);\n\t\t\t\tif(line1.empty())\n\t\t\t\t{\n\t\t\t\t c++; p_c1=0; p_c2 = 0;\t\n\t\t\t\t seed();\n\t\t\t \t c1<< line1<<endl;\n\t\t\t\t c2<< line2<<endl;\t\n\t\t\t\t //cout<<\"empty line\"<<endl;\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t p_c1++; p_c2++;\n\t\t\t\t //cout<<\"Line number: \"<<p_c1<<\" \"<<p_c2<<endl;\n\t\t\t\t //cout<<\"Crossover point \"<<cr_pt<<\"our pt \"<<c<<\"pcross \"<<pcross<<\"pc \"<<pc<<endl;\n\t\t\t\t if(c <= cr_pt || pcross >= pc) // checking crossover probability\n\t\t\t\t {\t\t\t\t\t\n\t\t\t\t\tif(p_c1 >= 5)\n\t\t\t\t        {\n\t\t\t\t\t\tseed();\n\t\t\t\t\t\tpmut1 = unifRand(); // generates random a value between 0 and 1 for child1\t\t\t\t\t\t\n\t\t\t\t\t\t//cout<<\"Before: \"<<line1<<\"\\t\"<<\"pmut1 \"<<pmut1<<\"\\t\";\t\t\t\t\t\n\t\t\t\t\t\tif(pmut1 <= pm) // checking mutation probability for child1\n\t\t\t\t\t\t{\n\t\t\t\t\t\t //cout<<\"Mutation is done at \"<<c<<\"\\t\";\n\t\t\t\t\t\t line1 = doMutation(line1);\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t\t//cout<<\"After: \"<<line1<<endl;\t\t\t\t\n\t\t\t\t\t}\t\n\t\t\t\t\tif(p_c2 >= 5)\n\t\t\t\t        {\n\t\t\t\t\t\tseed();\n\t\t\t\t \t\tpmut2 = unifRand(); // generates random a value between 0 and 1 for child2          \n\t\t\t\t\t\t//cout<<\"Before: \"<<line2<<\"\\t\"<<\"pmut2 \"<<pmut2<<\"\\t\";\t\t\t\t\t\n\t\t\t\t\t\tif(pmut2 <= pm) // checking mutation probability for child1\n\t\t\t\t\t\t{\n\t\t\t\t\t\t //cout<<\"Mutation is done at \"<<c<<\"\\t\";\n\t\t\t\t\t\t line2 = doMutation(line2);\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t\t//cout<<\"After: \"<<line2<<endl;\t\t\t\t\t\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t \t\tc1<< line1<<endl;\n\t\t\t\t\tc2<< line2<<endl;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//cout<<\"crossover happening at \"<<c<<endl;\n\t\t\t\t\tif(p_c1 >= 5)\n\t\t\t\t        {\n\t\t\t\t\t\tseed();\n\t\t\t\t\t\tpmut1 = unifRand(); // generates random a value between 0 and 1 for child1\t\t\t\t\t\t\n\t\t\t\t\t\t//cout<<\"Before: \"<<line1<<\"\\t\"<<\"pmut1 \"<<pmut1<<\"\\t\";\t\t\t\t\t\n\t\t\t\t\t\tif(pmut1 <= pm) // checking mutation probability for child1\n\t\t\t\t\t\t{\n\t\t\t\t\t\t //cout<<\"Mutation is done at \"<<c<<\"\\t\";\n\t\t\t\t\t\t line1 = doMutation(line1);\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t\t//cout<<\"After: \"<<line1<<endl;\t\t\t\t\n\t\t\t\t\t}\t\n\t\t\t\t\tif(p_c2 >= 5)\n\t\t\t\t        {\n\t\t\t\t\t\tseed();\n\t\t\t\t \t\tpmut2 = unifRand(); // generates random a value between 0 and 1 for child2          \n\t\t\t\t\t\t//cout<<\"Before: \"<<line2<<\"\\t\"<<\"pmut2 \"<<pmut2<<\"\\t\";\t\t\t\t\t\n\t\t\t\t\t\tif(pmut2 <= pm) // checking mutation probability for child1\n\t\t\t\t\t\t{\n\t\t\t\t\t\t //cout<<\"Mutation is done at \"<<c<<\"\\t\";\n\t\t\t\t\t\t line2 = doMutation(line2);\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t\t//cout<<\"After: \"<<line2<<endl;\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t//if(pcross <= pc)\n\t\t\t\t\t{\t\t\n\t\t\t\t\tc2<< line1<<endl;\n\t\t\t\t\tc1<< line2<<endl;\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 }\n\t\t }\n\t\t p1.close(); p2.close();\n\t \t c1.close(); c2.close(); \n\t\t p=0;\t\n\t\t//break;\n\t\t}\n\n\t   }\n\t   else\n\t   {\n\t\tn=n-1;\n\t\tcontinue;\n\t   }   \n\t}\n}\nint main(int argc, char *argv[]) {\nconst char* fname =argv[2];\ngibbsfile = argv[1]; \nistringstream ss( argv[3] );\nss >> pm;\nstringstream ss1( argv[4] );\nss1 >> pc;\nstringstream ss2(argv[5]);\nalarmfgloc = ss2.str();\nalarmlearnedfgloc = ss2.str();\n\nout.open(fname);\n clock_t tStart = clock();\nwhile(population_no<max_gen)\n{\n\tcout<<\"population no\"<<population_no<<endl;\n\tstartEM();\n\tcheckEMforTermination();\n\tdoCrossoverandMutation();\n\tpopulation_no=population_no+1;\n}\ndouble t = (clock() - tStart)/CLOCKS_PER_SEC;\ncout<<\"Time taken: \"<<t<<\"s\"<<endl;\nout<<\"Time taken: \"<<t<<\"s\"<<endl;\nout.close();\n\nreturn 0;\n}\n\n", "meta": {"hexsha": "0ff052e169d0d96841e809f04202c49cff808841", "size": 12624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_Newasia_gaem.cpp", "max_stars_repo_name": "Priyaaks/libDAI_P", "max_stars_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_Newasia_gaem.cpp", "max_issues_repo_name": "Priyaaks/libDAI_P", "max_issues_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_Newasia_gaem.cpp", "max_forks_repo_name": "Priyaaks/libDAI_P", "max_forks_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3461538462, "max_line_length": 123, "alphanum_fraction": 0.6031368821, "num_tokens": 3859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.04208772881675952, "lm_q1q2_score": 0.019894173980163868}}
{"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_VECTOR_MAP_VIEW_INCLUDE\n#define MTL_VECTOR_MAP_VIEW_INCLUDE\n\n#include <utility>\n#include <boost/shared_ptr.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/utility/copy_expression_const_ref_container.hpp>\n#include <boost/numeric/mtl/operation/sfunctor.hpp>\n#include <boost/numeric/mtl/operation/tfunctor.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/real.hpp>\n#include <boost/numeric/mtl/operation/imag.hpp>\n#include <boost/numeric/mtl/operation/signum.hpp>\n#include <boost/numeric/mtl/vector/vec_expr.hpp>\n\n\nnamespace mtl { namespace vec { namespace detail {\n    // Forward declaration for friend declaration\n    template <typename, typename> struct map_value;\n}}}\n\nnamespace mtl { namespace vec {\n\ntemplate <typename Functor, typename Vector> \nstruct map_view \n  : public vec_expr< map_view<Functor, Vector> >\n{\n    typedef map_view                                   self;\n    typedef vec_expr< self >                           expr_base;\n    typedef Vector                                     other;\n\n    typedef typename Functor::result_type              value_type;\n    typedef typename Functor::result_type              const_reference;\n    typedef typename Collection<Vector>::size_type     size_type;\n\n    map_view (const Functor& functor, const other& ref) \n      : expr_base(*this), functor(functor), ref(ref) \n    {\n  ref.delay_assign();\n    }\n    \n    map_view (const Functor& functor, boost::shared_ptr<Vector> p) \n      : expr_base(*this), functor(functor), my_copy(p), ref(*p)\n    {\n  ref.delay_assign();\n    }\n\n#ifdef MTL_WITH_MOVE    \n  map_view (self&& that) : my_copy(std::move(that.my_copy)), functor(that.functor), ref(that.ref) {}\n  map_view (const self& that) : functor(that.functor), ref(that.ref) { assert(that.my_copy.use_count() == 0); }\n#endif\n\n    friend size_type inline num_rows(const self& v) { return num_rows(v.ref); }\n    friend size_type inline num_cols(const self& v) { return num_cols(v.ref); }\n\n    size_type stride() const {   return ref.stride(); }\n    const_reference operator() (size_type i) const { return functor(ref(i)); }\n    const_reference operator[] (size_type i) const { return functor(ref[i]); }\n    void delay_assign() const {}\n    \n    template <typename, typename> friend struct detail::map_value;\n\n  protected:\n    boost::shared_ptr<Vector>           my_copy;\n  public:\n    Functor           functor;\n    // ref is a const& if Vector is a true vector and a copy if it is an expression\n    typename mtl::traits::copy_expression_const_ref_container<Vector>::type ref;\n};\n\n\ntemplate <typename Functor, typename Vector> \ninline std::size_t size(const map_view<Functor, Vector>& v)\n{     return mtl::vec::size(v.ref); }\n\n// ================\n// Free functions\n// ================\n\n\n    namespace detail {\n\n  template <typename Functor, typename Vector> \n  struct map_value\n  {\n      typedef typename Vector::key_type                      key_type;\n      typedef typename vec::map_view<Functor, Vector>::value_type value_type;\n      \n      map_value(vec::map_view<Functor, Vector> const& map_vector) \n    : map_vector(map_vector), its_value(map_vector.ref) \n      {}\n\n      value_type operator() (key_type const& key) const\n      {\n    return map_vector.functor(its_value(key));\n      }\n\n    protected:\n      vec::map_view<Functor, Vector> const&   map_vector;\n      typename ::mtl::traits::const_value<Vector>::type its_value;\n        };\n\n    } // detail\n\n}} // namespace mtl::vector\n\n\n\nnamespace mtl { namespace traits {\n\n    // ================\n    // Property maps\n    // ================\n\n    template <typename Functor, typename Vector> \n    struct index<vec::map_view<Functor, Vector> >\n  : public index<Vector>\n    {};\n\n    template <typename Functor, typename Vector> \n    struct const_value<vec::map_view<Functor, Vector> >\n    {\n  typedef vec::detail::map_value<Functor, Vector>  type;\n    };\n\n\n    // ================\n    // Range generators\n    // ================\n\n    // Use range_generator of original vector\n    template <typename Tag, typename Functor, typename Vector> \n    struct range_generator<Tag, vec::map_view<Functor, Vector> >\n  : public range_generator<Tag, Vector>\n    {};\n\n}} // mtl::traits\n\nnamespace mtl { namespace vec {\n\ntemplate <typename Scaling, typename Vector>\nstruct scaled_view\n    : public map_view<tfunctor::scale<Scaling, typename Vector::value_type>, Vector>\n{\n    typedef tfunctor::scale<Scaling, typename Vector::value_type>  functor_type;\n    typedef map_view<functor_type, Vector>                         base;\n    typedef scaled_view                                            self;\n\n    explicit scaled_view(const Scaling& scaling, const Vector& vector)\n      : base(functor_type(scaling), vector)\n    {}\n    \n    explicit scaled_view(const Scaling& scaling, boost::shared_ptr<Vector> p)\n      : base(functor_type(scaling), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    scaled_view (self&& that) : base(that) {}\n    scaled_view (const self& that) : base(that) {}\n#endif\n};\n\n// added by Hui Li\ntemplate <typename Vector, typename RScaling>\nstruct rscaled_view\n  : public map_view<tfunctor::rscale<typename Vector::value_type, RScaling>, Vector>\n{\n    typedef tfunctor::rscale<typename Vector::value_type, RScaling>  functor_type;\n    typedef map_view<functor_type, Vector>                          base;\n    typedef rscaled_view                                            self;\n  \n    explicit rscaled_view(const Vector& vector, const RScaling& rscaling)\n      : base(functor_type(rscaling), vector)\n    {}\n  \n    explicit rscaled_view(boost::shared_ptr<Vector> p, const RScaling& rscaling)\n      : base(functor_type(rscaling), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    rscaled_view (self&& that) : base(that) {}\n    rscaled_view (const self& that) : base(that) {}\n#endif\n};\n  \n\n// added by Hui Li\ntemplate <typename Vector, typename Divisor>\nstruct divide_by_view\n  : public map_view<tfunctor::divide_by<typename Vector::value_type, Divisor>, Vector>\n{\n    typedef tfunctor::divide_by<typename Vector::value_type, Divisor>  functor_type;\n    typedef map_view<functor_type, Vector>                             base;\n    typedef divide_by_view                                             self;\n  \n    explicit divide_by_view(const Vector& vector, const Divisor& div)\n      : base(functor_type(div), vector)\n    {}\n  \n    explicit divide_by_view(boost::shared_ptr<Vector> p, const Divisor& div)\n      : base(functor_type(div), p)\n    {}\n  \n#ifdef MTL_WITH_MOVE    \n    divide_by_view (self&& that) : base(that) {}\n    divide_by_view (const self& that) : base(that) {}\n#endif\n};\n  \n/// View for raising vector element to power of scalar exponent\ntemplate <typename Vector, typename Exponent>\nstruct pow_by_view\n  : public map_view<tfunctor::pow_by<typename Vector::value_type, Exponent>, Vector>\n{\n    typedef tfunctor::pow_by<typename Vector::value_type, Exponent>  functor_type;\n    typedef map_view<functor_type, Vector>                           base;\n    typedef pow_by_view                                              self;\n        \n    explicit pow_by_view(const Vector& vector, const Exponent& exp)\n      : base(functor_type(exp), vector)\n    {}\n        \n    explicit pow_by_view(boost::shared_ptr<Vector> p, const Exponent& exp)\n      : base(functor_type(exp), p)\n    {}\n        \n#ifdef MTL_WITH_MOVE    \n    pow_by_view (self&& that) : base(that) {}\n    pow_by_view (const self& that) : base(that) {}\n#endif\n};\n\n\ntemplate <typename Vector>\nstruct conj_view\n  : public map_view<mtl::sfunctor::conj<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::conj<typename Vector::value_type>            functor_type;\n    typedef map_view<functor_type, Vector>                         base;\n    typedef conj_view                                                   self;\n\n    explicit conj_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit conj_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    conj_view (self&& that) : base(that) {}\n    conj_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct real_view\n  : public map_view<mtl::sfunctor::real<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::real<typename Vector::value_type>            functor_type;\n    typedef map_view<functor_type, Vector>                         base;\n  typedef real_view                                              self;\n\n    explicit real_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit real_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    real_view (self&& that) : base(that) {}\n    real_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct imag_view\n  : public map_view<mtl::sfunctor::imag<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::imag<typename Vector::value_type>            functor_type;\n    typedef map_view<functor_type, Vector>                         base;\n    typedef imag_view                                              self;\n\n    explicit imag_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit imag_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    imag_view (self&& that) : base(that) {}\n    imag_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct negate_view\n  : public map_view<mtl::sfunctor::negate<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::negate<typename Vector::value_type>            functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef negate_view                                                   self;\n\n    explicit negate_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit negate_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    negate_view (self&& that) : base(that) {}\n    negate_view (const self& that) : base(that) {}\n#endif\n};\n\n\ntemplate <typename Vector>\nstruct abs_view\n  : public map_view<mtl::sfunctor::abs<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::abs<typename Vector::value_type>               functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef abs_view                                                      self;\n\n    explicit abs_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit abs_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    abs_view (self&& that) : base(that) {}\n    abs_view (const self& that) : base(that) {}\n#endif\n};\n\n// Inverse trigonometric\n\ntemplate <typename Vector>\nstruct acos_view\n  : public map_view<mtl::sfunctor::acos<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::acos<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef acos_view                                                     self;\n\n    explicit acos_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit acos_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    acos_view (self&& that) : base(that) {}\n    acos_view (const self& that) : base(that) {}\n#endif\n};\n\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct acosh_view\n  : public map_view<mtl::sfunctor::acosh<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::acosh<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef acosh_view                                                    self;\n\n    explicit acosh_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit acosh_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    acosh_view (self&& that) : base(that) {}\n    acosh_view (const self& that) : base(that) {}\n#endif\n};\n#endif\n\ntemplate <typename Vector>\nstruct asin_view\n  : public map_view<mtl::sfunctor::asin<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::asin<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef asin_view                                                     self;\n\n    explicit asin_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit asin_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    asin_view (self&& that) : base(that) {}\n    asin_view (const self& that) : base(that) {}\n#endif\n};\n\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct asinh_view\n  : public map_view<mtl::sfunctor::asinh<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::asinh<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef asinh_view                                                    self;\n\n    explicit asinh_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit asinh_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    asinh_view (self&& that) : base(that) {}\n    asinh_view (const self& that) : base(that) {}\n#endif\n};\n#endif\n\ntemplate <typename Vector>\nstruct atan_view\n  : public map_view<mtl::sfunctor::atan<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::atan<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef atan_view                                                     self;\n\n    explicit atan_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit atan_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    atan_view (self&& that) : base(that) {}\n    atan_view (const self& that) : base(that) {}\n#endif\n};\n\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct atanh_view\n  : public map_view<mtl::sfunctor::atanh<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::atanh<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef atanh_view                                                    self;\n\n    explicit atanh_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit atanh_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    atanh_view (self&& that) : base(that) {}\n    atanh_view (const self& that) : base(that) {}\n#endif\n};\n#endif\n\n\n// Trigonometric\n\ntemplate <typename Vector>\nstruct cos_view\n  : public map_view<mtl::sfunctor::cos<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::cos<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef cos_view                                                     self;\n\n    explicit cos_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit cos_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    cos_view (self&& that) : base(that) {}\n    cos_view (const self& that) : base(that) {}\n#endif\n};\n\n\ntemplate <typename Vector>\nstruct cosh_view\n  : public map_view<mtl::sfunctor::cosh<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::cosh<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef cosh_view                                                    self;\n\n    explicit cosh_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit cosh_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    cosh_view (self&& that) : base(that) {}\n    cosh_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct sin_view\n  : public map_view<mtl::sfunctor::sin<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::sin<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef sin_view                                                     self;\n\n    explicit sin_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit sin_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    sin_view (self&& that) : base(that) {}\n    sin_view (const self& that) : base(that) {}\n#endif\n};\n\n\ntemplate <typename Vector>\nstruct sinh_view\n  : public map_view<mtl::sfunctor::sinh<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::sinh<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef sinh_view                                                    self;\n\n    explicit sinh_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit sinh_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    sinh_view (self&& that) : base(that) {}\n    sinh_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct tan_view\n  : public map_view<mtl::sfunctor::tan<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::tan<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef tan_view                                                     self;\n\n    explicit tan_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit tan_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    tan_view (self&& that) : base(that) {}\n    tan_view (const self& that) : base(that) {}\n#endif\n};\n\n\ntemplate <typename Vector>\nstruct tanh_view\n  : public map_view<mtl::sfunctor::tanh<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::tanh<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef tanh_view                                                    self;\n\n    explicit tanh_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit tanh_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    tanh_view (self&& that) : base(that) {}\n    tanh_view (const self& that) : base(that) {}\n#endif\n};\n\n// Rounding\ntemplate <typename Vector>\nstruct ceil_view\n  : public map_view<mtl::sfunctor::ceil<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::ceil<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef ceil_view                                                    self;\n\n    explicit ceil_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit ceil_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    ceil_view (self&& that) : base(that) {}\n    ceil_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct floor_view\n  : public map_view<mtl::sfunctor::floor<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::floor<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef floor_view                                                    self;\n\n    explicit floor_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit floor_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    floor_view (self&& that) : base(that) {}\n    floor_view (const self& that) : base(that) {}\n#endif\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct round_view\n  : public map_view<mtl::sfunctor::round<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::round<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef round_view                                                    self;\n\n    explicit round_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit round_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    round_view (self&& that) : base(that) {}\n    round_view (const self& that) : base(that) {}\n#endif\n};\n#endif\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct trunc_view\n  : public map_view<mtl::sfunctor::trunc<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::trunc<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef trunc_view                                                    self;\n\n    explicit trunc_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit trunc_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    trunc_view (self&& that) : base(that) {}\n    trunc_view (const self& that) : base(that) {}\n#endif\n};\n#endif\n\ntemplate <typename Vector>\nstruct log_view\n  : public map_view<mtl::sfunctor::log<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::log<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef log_view                                                    self;\n\n    explicit log_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit log_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    log_view (self&& that) : base(that) {}\n    log_view (const self& that) : base(that) {}\n#endif\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct log2_view\n  : public map_view<mtl::sfunctor::log2<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::log2<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef log2_view                                                    self;\n\n    explicit log2_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit log2_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    log2_view (self&& that) : base(that) {}\n    log2_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct log10_view\n  : public map_view<mtl::sfunctor::log10<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::log10<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef log10_view                                                    self;\n\n    explicit log10_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit log10_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    log10_view (self&& that) : base(that) {}\n    log10_view (const self& that) : base(that) {}\n#endif\n};\n# endif\n\ntemplate <typename Vector>\nstruct exp_view\n  : public map_view<mtl::sfunctor::exp<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::exp<typename Vector::value_type>               functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef exp_view                                                      self;\n\n    explicit exp_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit exp_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    exp_view (self&& that) : base(that) {}\n    exp_view (const self& that) : base(that) {}\n#endif\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct exp2_view\n  : public map_view<mtl::sfunctor::exp2<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::exp2<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef exp2_view                                                     self;\n\n    explicit exp2_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit exp2_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    exp2_view (self&& that) : base(that) {}\n    exp2_view (const self& that) : base(that) {}\n#endif\n};\n#endif\n\ntemplate <typename Vector>\nstruct exp10_view\n  : public map_view<mtl::sfunctor::exp10<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::exp10<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef exp10_view                                                    self;\n\n    explicit exp10_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit exp10_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    exp10_view (self&& that) : base(that) {}\n    exp10_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct sqrt_view\n  : public map_view<mtl::sfunctor::sqrt<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::sqrt<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef sqrt_view                                                    self;\n\n    explicit sqrt_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit sqrt_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    sqrt_view (self&& that) : base(that) {}\n    sqrt_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct rsqrt_view\n  : public map_view<mtl::sfunctor::rsqrt<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::rsqrt<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef rsqrt_view                                                    self;\n\n    explicit rsqrt_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit rsqrt_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    rsqrt_view (self&& that) : base(that) {}\n    rsqrt_view (const self& that) : base(that) {}\n#endif\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Vector>\nstruct erf_view\n  : public map_view<mtl::sfunctor::erf<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::erf<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef erf_view                                                    self;\n\n    explicit erf_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit erf_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    erf_view (self&& that) : base(that) {}\n    erf_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Vector>\nstruct erfc_view\n  : public map_view<mtl::sfunctor::erfc<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::erfc<typename Vector::value_type>             functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef erfc_view                                                    self;\n\n    explicit erfc_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit erfc_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    erfc_view (self&& that) : base(that) {}\n    erfc_view (const self& that) : base(that) {}\n#endif\n};\n# endif\n\ntemplate <typename Vector>\nstruct signum_view\n  : public map_view<mtl::sfunctor::signum<typename Vector::value_type>, Vector>\n{\n    typedef mtl::sfunctor::signum<typename Vector::value_type>              functor_type;\n    typedef map_view<functor_type, Vector>                                base;\n    typedef signum_view                                                     self;\n\n    explicit signum_view(const Vector& vector)\n      : base(functor_type(), vector)\n    {}\n    \n    explicit signum_view(boost::shared_ptr<Vector> p)\n      : base(functor_type(), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    signum_view (self&& that) : base(that) {}\n    signum_view (const self& that) : base(that) {}\n#endif\n};\n\n}} // namespace mtl::vector\n\nnamespace mtl { namespace sfunctor {\n\n\n    template <typename Vector>\n    struct conj_aux<Vector, tag::vector>\n    {\n  typedef mtl::vec::conj_view<Vector> result_type;\n\n  static inline result_type apply(const Vector& vector)\n  {\n      return result_type(vector);\n  }\n\n  result_type operator() (const Vector& vector) const\n  {\n      return apply(vector);\n  }\n    };\n\n}}\n\n\n\n\n#endif // MTL_VECTOR_MAP_VIEW_INCLUDE\n", "meta": {"hexsha": "07cbc0fe56dfb8decd0d18117aa0e213ee548743", "size": 30919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/vector/map_view.hpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/vector/map_view.hpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/vector/map_view.hpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.6432111001, "max_line_length": 111, "alphanum_fraction": 0.6067790032, "num_tokens": 7122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.052618950004997535, "lm_q1q2_score": 0.01986579357634295}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Solver class declared in the\n    swp_solver.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_solver.h\"\n#include \"local_geometry1d.h\"\n\n#include \"choose_index.hpp\"\n\n#include <stdlib.h>\n#include <cmath>\n#include \"string_functions.h\"\n#include <stdexcept>\n#include <ctime>\n#include <limits>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n\nusing namespace Sweep;\nusing namespace std;\nusing namespace Strings;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor.\nSolver::Solver(void)\n: m_splitratio(1.0e9)\n{\n//  srnd(time(0));\t\t\t//added by ms785\n//    srnd(getpid());\n #ifdef USE_MPI\n  Sweep::init_genrand(getpid());\t\t\t//added by ms785\n #endif\n\n\n}\n\n//! Copy constructor\nSolver::Solver(const Solver &sol)\n: m_splitratio(sol.m_splitratio) {}\n\n// Default destructor.\nSolver::~Solver(void)\n{\n    // Nothing special to destruct.\n}\n\n\n// RUNNING THE SOLVER.\n\n// Performs stochastic stepping algorithm up to specified stop time using\n// the given mechanism to define the stochastic processes.  Updates given\n// system accordingly.  On error returns <0, otherwise returns 0.\nint Solver::Run(double &t, double tstop, Cell &sys, const Mechanism &mech,\n                rng_type &rng)\n{\n    int err = 0;\n    double tsplit, dtg, jrate, tflow(t);\n    fvector rates(mech.TermCount(), 0.0);\n    // Global maximum time step.\n    dtg     = tstop - t;\n    double tin = t; //store start time \n\n    // Loop over time until we reach the stop time.\n    while (t < tstop)\n    {\n        if (mech.AnyDeferred() && (sys.ParticleCount() + sys.Particles().GetTotalParticleNumber() > 0))  {\n            // Get the process jump rates (and the total rate).\n            jrate = mech.CalcJumpRateTerms(t, sys, Geometry::LocalGeometry1d(), rates);\n\n            // Calculate split end time.\n            tsplit = calcSplitTime(t, std::min(t+dtg, tstop), jrate, sys.ParticleCount() + sys.Particles().GetTotalParticleNumber());\n        } else {\n            // There are no deferred processes, therefore there\n            // is no need to perform LPDA splitting steps.\n            tsplit = tstop;\n        }\n\ttin = t;\n\n        // Perform stochastic jump processes.\n        while (t < tsplit) {\n\n            // Sweep does not do transport\n            jrate = mech.CalcJumpRateTerms(t, sys, Geometry::LocalGeometry1d(), rates);\n            timeStep(t, std::min(t + dtg / 3.0, tsplit), sys, Geometry::LocalGeometry1d(),\n                     mech, rates, jrate, rng);\n\n            // Do particle transport\n            if (sys.OutflowCount() > 0 || sys.InflowCount() > 0)\n                mech.DoParticleFlow(t, t - tflow, sys, Geometry::LocalGeometry1d(), rng);\n            tflow = t;\n        }\n\n        // Perform Linear Process Deferment Algorithm to\n        // update all deferred processes.\n        mech.LPDA(t, sys, rng);\n\n        // Perform deferred processes on particle-number particles\n\tif (mech.IsHybrid() && sys.Particles().GetTotalParticleNumber() > 0)\n\t{\n\t\tsys.Particles().RecalcPNPropertySums();\n\t\tmech.UpdateSections(t, t - tin, sys, rng);\n\t}\n    }\n\n    return err;\n}\n\n\n// TIME STEPPING ROUTINES.\n\n/*!\n * Calculates the splitting end time after which all particles\n * shall be updated using LPDA.\n *\n *@param[in]\tt\t\tCurrent time\n *@param[in]\ttstop\tLatest possible end for the splitting\n *@param[in]\tjrate\tComputational jump rate\n *@param[in]\tn\t\tNumber of computational particles\n *\n *@return\tEnd time for next splitting step\n */\ndouble Solver::calcSplitTime(double t, double tstop, double jrate,\n                           unsigned int n) const\n{\n    // Calculate the splitting time step, ensuring that it is\n    // not longer than the maximum allowable time.\n    double tsplit = (n + 1) * m_splitratio / (jrate + 1.0);\n\n\t//double tsplit = m_splitratio / (jrate + 1.0);\n\n    // Now put the split end time into tsplit, again\n    // checking that it is not beyond the stop time.\n    return min(tsplit+t, tstop);\n}\n\n/*!\n * Performs a single stochastic event on the ensemble from the given\n * mechanism or move to t_stop, whichever comes first.\n *\n *@param[in,out]    t           Current time, which will be updated\n *@param[in]        t_stop      Time past which step may not go\n *@param[in,out]    sys         System in which jump will take place\n *@param[in]        geom        Specify size and neighbours of cell (use a default constructed object which will apply unit scaling when no geometry information present)\n *@param[in]        mech        Mechanism specifying the jump\n *@param[in]        rates       Vector of computational jump rates, one for each jump process\n *@param[in]        jrate       Sum of entries in rates (total jump rate)\n *@param[in,out]    rng         Random number generator\n *\n *@pre      t <= t_stop\n *@post     t <= t_stop\n */\nvoid Solver::timeStep(double &t, double t_stop, Cell &sys, const Geometry::LocalGeometry1d &geom,\n                      const Mechanism &mech, const fvector &rates, double jrate,\n                      rng_type &rng)\n{\n    // The purpose of this routine is to perform a single stochastic jump process.  This\n    // involves summing the total rate of all processes, generating a waiting time,\n    // selecting a process and performing that process.\n    double dt;\n\n    //std::cout << \"Solver::timeStep in cell \" << &sys << \" from \" << t << \" with rate \" << jrate;\n\n    // Calculate exponentially distributed time step size.\n    if (jrate > 0.0) {\n        boost::exponential_distribution<double> waitDistrib(jrate);\n        boost::variate_generator<Sweep::rng_type&, boost::exponential_distribution<double> > waitGenerator(rng, waitDistrib);\n        dt = waitGenerator();\n        //std::cout << ' ' << dt;\n    } else {\n        // Avoid divide by zero.\n        dt = std::numeric_limits<double>::max();\n    }\n\n    // Truncate if step is too long or select a process\n    // to perform.\n    if (t+dt <= t_stop) {\n        boost::uniform_01<rng_type &> uniformGenerator(rng);\n        const int i = chooseIndex(rates, uniformGenerator);\n        mech.DoProcess(i, t+dt, sys, geom, rng);\n        t += dt;\n    } else {\n        t = t_stop;\n        //std:cout << \" step truncated to end at \" << t_stop;\n    }\n    //std::cout << std::endl;\n}\n\n// Selects a process using a DIV algorithm and the process rates\n// as weights.\nint Solver::chooseProcess(const fvector &rates, double (*rand_u01)())\n{\n    // This routine implements a DIV algorithm to select a process from a\n    // discrete list of processes when each process's rate is given.\n\n    // Add together all process rates.\n    fvector::const_iterator i;\n    double sum = 0.0;\n    for (i=rates.begin(); i!=rates.end(); ++i) {\n        sum += *i;\n    }\n\n    // Generate a uniform random number.\n    double r = rand_u01() * sum ;\n\n    // Select a process using DIV algorithm.\n    int j=-1;\n    i = rates.begin();\n    while((r > 0.0) && (i != rates.end())) {\n        r -= *i;\n        ++i; ++j;\n    }\n    return j;\n};\n", "meta": {"hexsha": "b769b1f35a946f7d58ce458136957a15cc4676e5", "size": 8220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_solver.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_solver.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_solver.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 32.3622047244, "max_line_length": 169, "alphanum_fraction": 0.6437956204, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.042722194042366185, "lm_q1q2_score": 0.019861614509341517}}
{"text": "// Boost.Geometry\r\n// This file is manually converted from PROJ4\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// This file was converted to Geometry Library by Adam Wulkiewicz\r\n\r\n// Original copyright notice:\r\n\r\n// Copyright (c) 2000, Frank Warmerdam\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_SRS_PROJECTIONS_IMPL_PJ_TRANSFORM_HPP\r\n#define BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_PJ_TRANSFORM_HPP\r\n\r\n\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n\r\n#include <boost/geometry/srs/projections/impl/geocent.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/invalid_point.hpp>\r\n\r\n#include <boost/geometry/util/range.hpp>\r\n\r\n#include <cstring>\r\n#include <cmath>\r\n\r\n\r\nnamespace boost { namespace geometry { namespace projections\r\n{\r\n\r\nnamespace detail\r\n{\r\n\r\n// -----------------------------------------------------------\r\n// Boost.Geometry helpers begin\r\n// -----------------------------------------------------------\r\n\r\ntemplate\r\n<\r\n    typename Point,\r\n    bool HasCoord2 = (dimension<Point>::value > 2)\r\n>\r\nstruct z_access\r\n{\r\n    typedef typename coordinate_type<Point>::type type;\r\n    static inline type get(Point const& point)\r\n    {\r\n        return geometry::get<2>(point);\r\n    }\r\n    static inline void set(Point & point, type const& h)\r\n    {\r\n        return geometry::set<2>(point, h);\r\n    }\r\n};\r\n\r\ntemplate <typename Point>\r\nstruct z_access<Point, false>\r\n{\r\n    typedef typename coordinate_type<Point>::type type;\r\n    static inline type get(Point const& )\r\n    {\r\n        return type(0);\r\n    }\r\n    static inline void set(Point & , type const& )\r\n    {}\r\n};\r\n\r\ntemplate <typename XYorXYZ>\r\ninline typename z_access<XYorXYZ>::type\r\nget_z(XYorXYZ const& xy_or_xyz)\r\n{\r\n    return z_access<XYorXYZ>::get(xy_or_xyz);\r\n}\r\n\r\ntemplate <typename XYorXYZ>\r\ninline void set_z(XYorXYZ & xy_or_xyz,\r\n                  typename z_access<XYorXYZ>::type const& z)\r\n{\r\n    return z_access<XYorXYZ>::set(xy_or_xyz, z);\r\n}\r\n\r\ntemplate\r\n<\r\n    typename Range,\r\n    bool AddZ = (dimension<typename boost::range_value<Range>::type>::value < 3)\r\n>\r\nstruct range_wrapper\r\n{\r\n    typedef Range range_type;\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n    typedef typename coordinate_type<point_type>::type coord_t;\r\n\r\n    range_wrapper(Range & range)\r\n        : m_range(range)\r\n    {}\r\n\r\n    range_type & get_range() { return m_range; }\r\n\r\n    coord_t get_z(std::size_t i) { return detail::get_z(range::at(m_range, i)); }\r\n    void set_z(std::size_t i, coord_t const& v) { return detail::set_z(range::at(m_range, i), v); }\r\n\r\nprivate:\r\n    Range & m_range;\r\n};\r\n\r\ntemplate <typename Range>\r\nstruct range_wrapper<Range, true>\r\n{\r\n    typedef Range range_type;\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n    typedef typename coordinate_type<point_type>::type coord_t;\r\n\r\n    range_wrapper(Range & range)\r\n        : m_range(range)\r\n        , m_zs(boost::size(range), coord_t(0))\r\n    {}\r\n\r\n    range_type & get_range() { return m_range; }\r\n\r\n    coord_t get_z(std::size_t i) { return m_zs[i]; }\r\n    void set_z(std::size_t i, coord_t const& v) { m_zs[i] = v; }\r\n\r\nprivate:\r\n    Range & m_range;\r\n    std::vector<coord_t> m_zs;\r\n};\r\n\r\n// -----------------------------------------------------------\r\n// Boost.Geometry helpers end\r\n// -----------------------------------------------------------\r\n\r\n/*#ifndef SRS_WGS84_SEMIMAJOR\r\n#define SRS_WGS84_SEMIMAJOR 6378137.0\r\n#endif\r\n\r\n#ifndef SRS_WGS84_ESQUARED\r\n#define SRS_WGS84_ESQUARED 0.0066943799901413165\r\n#endif*/\r\n\r\ntemplate <typename Par>\r\ninline typename Par::type Dx_BF(Par const& defn) { return defn.datum_params[0]; }\r\ntemplate <typename Par>\r\ninline typename Par::type Dy_BF(Par const& defn) { return defn.datum_params[1]; }\r\ntemplate <typename Par>\r\ninline typename Par::type Dz_BF(Par const& defn) { return defn.datum_params[2]; }\r\ntemplate <typename Par>\r\ninline typename Par::type Rx_BF(Par const& defn) { return defn.datum_params[3]; }\r\ntemplate <typename Par>\r\ninline typename Par::type Ry_BF(Par const& defn) { return defn.datum_params[4]; }\r\ntemplate <typename Par>\r\ninline typename Par::type Rz_BF(Par const& defn) { return defn.datum_params[5]; }\r\ntemplate <typename Par>\r\ninline typename Par::type M_BF(Par const& defn) { return defn.datum_params[6]; }\r\n\r\n/*\r\n** This table is intended to indicate for any given error code in\r\n** the range 0 to -44, whether that error will occur for all locations (ie.\r\n** it is a problem with the coordinate system as a whole) in which case the\r\n** value would be 0, or if the problem is with the point being transformed\r\n** in which case the value is 1.\r\n**\r\n** At some point we might want to move this array in with the error message\r\n** list or something, but while experimenting with it this should be fine.\r\n*/\r\n\r\nstatic const int transient_error[50] = {\r\n    /*             0  1  2  3  4  5  6  7  8  9   */\r\n    /* 0 to 9 */   0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\r\n    /* 10 to 19 */ 0, 0, 0, 0, 1, 1, 0, 1, 1, 1,\r\n    /* 20 to 29 */ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0,\r\n    /* 30 to 39 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\r\n    /* 40 to 49 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 };\r\n\r\n\r\ntemplate <typename T, typename Range>\r\ninline int pj_geocentric_to_geodetic( T const& a, T const& es,\r\n                                      Range & range );\r\ntemplate <typename T, typename Range>\r\ninline int pj_geodetic_to_geocentric( T const& a, T const& es,\r\n                                      Range & range );\r\n\r\n/************************************************************************/\r\n/*                            pj_transform()                            */\r\n/*                                                                      */\r\n/*      Currently this function doesn't recognise if two projections    */\r\n/*      are identical (to short circuit reprojection) because it is     */\r\n/*      difficult to compare PJ structures (since there are some        */\r\n/*      projection specific components).                                */\r\n/************************************************************************/\r\n\r\ntemplate <typename SrcPrj, typename DstPrj2, typename Par, typename Range>\r\ninline bool pj_transform(SrcPrj const& srcprj, Par const& srcdefn,\r\n                         DstPrj2 const& dstprj, Par const& dstdefn,\r\n                         Range & range)\r\n\r\n{\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n    typedef typename coordinate_type<point_type>::type coord_t;\r\n    static const std::size_t dimension = geometry::dimension<point_type>::value;\r\n    std::size_t point_count = boost::size(range);\r\n    bool result = true;\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform unusual input coordinate axis orientation to          */\r\n/*      standard form if needed.                                        */\r\n/* -------------------------------------------------------------------- */\r\n    // Ignored\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform Z to meters if it isn't already.                      */\r\n/* -------------------------------------------------------------------- */\r\n    if( srcdefn.vto_meter != 1.0 && dimension > 2 )\r\n    {\r\n        for( std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = geometry::range::at(range, i);\r\n            set_z(point, get_z(point) * srcdefn.vto_meter);\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform geocentric source coordinates to lat/long.            */\r\n/* -------------------------------------------------------------------- */\r\n    if( srcdefn.is_geocent )\r\n    {\r\n        // Point should be cartesian 3D (ECEF)\r\n        if (dimension < 3)\r\n            BOOST_THROW_EXCEPTION( projection_exception(PJD_ERR_GEOCENTRIC) );\r\n            //return PJD_ERR_GEOCENTRIC;\r\n\r\n        if( srcdefn.to_meter != 1.0 )\r\n        {\r\n            for(std::size_t i = 0; i < point_count; i++ )\r\n            {\r\n                point_type & point = range::at(range, i);\r\n                if( ! is_invalid_point(point) )\r\n                {\r\n                    set<0>(point, get<0>(point) * srcdefn.to_meter);\r\n                    set<1>(point, get<1>(point) * srcdefn.to_meter);\r\n                }\r\n            }\r\n        }\r\n\r\n        range_wrapper<Range, false> rng(range);\r\n        int err = pj_geocentric_to_geodetic( srcdefn.a_orig, srcdefn.es_orig,\r\n                                             rng );\r\n        if( err != 0 )\r\n            BOOST_THROW_EXCEPTION( projection_exception(err) );\r\n            //return err;\r\n\r\n        // NOTE: here 3D cartesian ECEF is converted into 3D geodetic LLH\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform source points to lat/long, if they aren't             */\r\n/*      already.                                                        */\r\n/* -------------------------------------------------------------------- */\r\n    else if( !srcdefn.is_latlong )\r\n    {\r\n        // Point should be cartesian 2D or 3D (map projection)\r\n\r\n        /* Check first if projection is invertible. */\r\n        /*if( (srcdefn->inv3d == NULL) && (srcdefn->inv == NULL))\r\n        {\r\n            pj_ctx_set_errno( pj_get_ctx(srcdefn), -17 );\r\n            pj_log( pj_get_ctx(srcdefn), PJ_LOG_ERROR,\r\n                    \"pj_transform(): source projection not invertible\" );\r\n            return -17;\r\n        }*/\r\n\r\n        /* If invertible - First try inv3d if defined */\r\n        //if (srcdefn->inv3d != NULL)\r\n        //{\r\n        //    /* Three dimensions must be defined */\r\n        //    if ( z == NULL)\r\n        //    {\r\n        //        pj_ctx_set_errno( pj_get_ctx(srcdefn), PJD_ERR_GEOCENTRIC);\r\n        //        return PJD_ERR_GEOCENTRIC;\r\n        //    }\r\n\r\n        //    for (i=0; i < point_count; i++)\r\n        //    {\r\n        //        XYZ projected_loc;\r\n        //        XYZ geodetic_loc;\r\n\r\n        //        projected_loc.u = x[point_offset*i];\r\n        //        projected_loc.v = y[point_offset*i];\r\n        //        projected_loc.w = z[point_offset*i];\r\n\r\n        //        if (projected_loc.u == HUGE_VAL)\r\n        //            continue;\r\n\r\n        //        geodetic_loc = pj_inv3d(projected_loc, srcdefn);\r\n        //        if( srcdefn->ctx->last_errno != 0 )\r\n        //        {\r\n        //            if( (srcdefn->ctx->last_errno != 33 /*EDOM*/\r\n        //                 && srcdefn->ctx->last_errno != 34 /*ERANGE*/ )\r\n        //                && (srcdefn->ctx->last_errno > 0\r\n        //                    || srcdefn->ctx->last_errno < -44 || point_count == 1\r\n        //                    || transient_error[-srcdefn->ctx->last_errno] == 0 ) )\r\n        //                return srcdefn->ctx->last_errno;\r\n        //            else\r\n        //            {\r\n        //                geodetic_loc.u = HUGE_VAL;\r\n        //                geodetic_loc.v = HUGE_VAL;\r\n        //                geodetic_loc.w = HUGE_VAL;\r\n        //            }\r\n        //        }\r\n\r\n        //        x[point_offset*i] = geodetic_loc.u;\r\n        //        y[point_offset*i] = geodetic_loc.v;\r\n        //        z[point_offset*i] = geodetic_loc.w;\r\n\r\n        //    }\r\n\r\n        //}\r\n        //else\r\n        {\r\n            /* Fallback to the original PROJ.4 API 2d inversion - inv */\r\n            for( std::size_t i = 0; i < point_count; i++ )\r\n            {\r\n                point_type & point = range::at(range, i);\r\n\r\n                if( is_invalid_point(point) )\r\n                    continue;\r\n\r\n                try\r\n                {\r\n                    pj_inv(srcprj, srcdefn, point, point);\r\n                }\r\n                catch(projection_exception const& e)\r\n                {\r\n                    if( (e.code() != 33 /*EDOM*/\r\n                        && e.code() != 34 /*ERANGE*/ )\r\n                        && (e.code() > 0\r\n                            || e.code() < -44 /*|| point_count == 1*/\r\n                            || transient_error[-e.code()] == 0) ) {\r\n                        BOOST_RETHROW\r\n                    } else {\r\n                        set_invalid_point(point);\r\n                        result = false;\r\n                        if (point_count == 1)\r\n                            return result;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      But if they are already lat long, adjust for the prime          */\r\n/*      meridian if there is one in effect.                             */\r\n/* -------------------------------------------------------------------- */\r\n    if( srcdefn.from_greenwich != 0.0 )\r\n    {\r\n        for( std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = range::at(range, i);\r\n\r\n            if( ! is_invalid_point(point) )\r\n                set<0>(point, get<0>(point) + srcdefn.from_greenwich);\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Do we need to translate from geoid to ellipsoidal vertical      */\r\n/*      datum?                                                          */\r\n/* -------------------------------------------------------------------- */\r\n    /*if( srcdefn->has_geoid_vgrids && z != NULL )\r\n    {\r\n        if( pj_apply_vgridshift( srcdefn, \"sgeoidgrids\",\r\n                                 &(srcdefn->vgridlist_geoid),\r\n                                 &(srcdefn->vgridlist_geoid_count),\r\n                                 0, point_count, point_offset, x, y, z ) != 0 )\r\n            return pj_ctx_get_errno(srcdefn->ctx);\r\n    }*/\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Convert datums if needed, and possible.                         */\r\n/* -------------------------------------------------------------------- */\r\n    if ( ! pj_datum_transform( srcdefn, dstdefn, range ) )\r\n    {\r\n        result = false;\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Do we need to translate from ellipsoidal to geoid vertical      */\r\n/*      datum?                                                          */\r\n/* -------------------------------------------------------------------- */\r\n    /*if( dstdefn->has_geoid_vgrids && z != NULL )\r\n    {\r\n        if( pj_apply_vgridshift( dstdefn, \"sgeoidgrids\",\r\n                                 &(dstdefn->vgridlist_geoid),\r\n                                 &(dstdefn->vgridlist_geoid_count),\r\n                                 1, point_count, point_offset, x, y, z ) != 0 )\r\n            return dstdefn->ctx->last_errno;\r\n    }*/\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      But if they are staying lat long, adjust for the prime          */\r\n/*      meridian if there is one in effect.                             */\r\n/* -------------------------------------------------------------------- */\r\n    if( dstdefn.from_greenwich != 0.0 )\r\n    {\r\n        for( std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = range::at(range, i);\r\n\r\n            if( ! is_invalid_point(point) )\r\n                set<0>(point, get<0>(point) - dstdefn.from_greenwich);\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform destination latlong to geocentric if required.        */\r\n/* -------------------------------------------------------------------- */\r\n    if( dstdefn.is_geocent )\r\n    {\r\n        // Point should be cartesian 3D (ECEF)\r\n        if (dimension < 3)\r\n            BOOST_THROW_EXCEPTION( projection_exception(PJD_ERR_GEOCENTRIC) );\r\n            //return PJD_ERR_GEOCENTRIC;\r\n\r\n        // NOTE: In the original code the return value of the following\r\n        // function is not checked\r\n        range_wrapper<Range, false> rng(range);\r\n        int err = pj_geodetic_to_geocentric( dstdefn.a_orig, dstdefn.es_orig,\r\n                                             rng );\r\n        if( err == -14 )\r\n            result = false;\r\n        else\r\n            BOOST_THROW_EXCEPTION( projection_exception(err) );\r\n            \r\n        if( dstdefn.fr_meter != 1.0 )\r\n        {\r\n            for( std::size_t i = 0; i < point_count; i++ )\r\n            {\r\n                point_type & point = range::at(range, i);\r\n                if( ! is_invalid_point(point) )\r\n                {\r\n                    set<0>(point, get<0>(point) * dstdefn.fr_meter);\r\n                    set<1>(point, get<1>(point) * dstdefn.fr_meter);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform destination points to projection coordinates, if      */\r\n/*      desired.                                                        */\r\n/* -------------------------------------------------------------------- */\r\n    else if( !dstdefn.is_latlong )\r\n    {\r\n\r\n        //if( dstdefn->fwd3d != NULL)\r\n        //{\r\n        //    for( i = 0; i < point_count; i++ )\r\n        //    {\r\n        //        XYZ projected_loc;\r\n        //        LPZ geodetic_loc;\r\n\r\n        //        geodetic_loc.u = x[point_offset*i];\r\n        //        geodetic_loc.v = y[point_offset*i];\r\n        //        geodetic_loc.w = z[point_offset*i];\r\n\r\n        //        if (geodetic_loc.u == HUGE_VAL)\r\n        //            continue;\r\n\r\n        //        projected_loc = pj_fwd3d( geodetic_loc, dstdefn);\r\n        //        if( dstdefn->ctx->last_errno != 0 )\r\n        //        {\r\n        //            if( (dstdefn->ctx->last_errno != 33 /*EDOM*/\r\n        //                 && dstdefn->ctx->last_errno != 34 /*ERANGE*/ )\r\n        //                && (dstdefn->ctx->last_errno > 0\r\n        //                    || dstdefn->ctx->last_errno < -44 || point_count == 1\r\n        //                    || transient_error[-dstdefn->ctx->last_errno] == 0 ) )\r\n        //                return dstdefn->ctx->last_errno;\r\n        //            else\r\n        //            {\r\n        //                projected_loc.u = HUGE_VAL;\r\n        //                projected_loc.v = HUGE_VAL;\r\n        //                projected_loc.w = HUGE_VAL;\r\n        //            }\r\n        //        }\r\n\r\n        //        x[point_offset*i] = projected_loc.u;\r\n        //        y[point_offset*i] = projected_loc.v;\r\n        //        z[point_offset*i] = projected_loc.w;\r\n        //    }\r\n\r\n        //}\r\n        //else\r\n        {\r\n            for(std::size_t i = 0; i < point_count; i++ )\r\n            {\r\n                point_type & point = range::at(range, i);\r\n\r\n                if( is_invalid_point(point) )\r\n                    continue;\r\n\r\n                try {\r\n                    pj_fwd(dstprj, dstdefn, point, point);\r\n                } catch (projection_exception const& e) {\r\n\r\n                    if( (e.code() != 33 /*EDOM*/\r\n                         && e.code() != 34 /*ERANGE*/ )\r\n                        && (e.code() > 0\r\n                            || e.code() < -44 /*|| point_count == 1*/\r\n                            || transient_error[-e.code()] == 0) ) {\r\n                        BOOST_RETHROW\r\n                    } else {\r\n                        set_invalid_point(point);\r\n                        result = false;\r\n                        if (point_count == 1)\r\n                            return result;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      If a wrapping center other than 0 is provided, rewrap around    */\r\n/*      the suggested center (for latlong coordinate systems only).     */\r\n/* -------------------------------------------------------------------- */\r\n    else if( dstdefn.is_latlong && dstdefn.is_long_wrap_set )\r\n    {\r\n        for( std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = range::at(range, i);\r\n            coord_t x = get_as_radian<0>(point);\r\n            \r\n            if( is_invalid_point(point) )\r\n                continue;\r\n\r\n            // TODO - units-dependant constants could be used instead\r\n            while( x < dstdefn.long_wrap_center - math::pi<coord_t>() )\r\n                x += math::two_pi<coord_t>();\r\n            while( x > dstdefn.long_wrap_center + math::pi<coord_t>() )\r\n                x -= math::two_pi<coord_t>();\r\n\r\n            set_from_radian<0>(point, x);\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform Z from meters if needed.                              */\r\n/* -------------------------------------------------------------------- */\r\n    if( dstdefn.vto_meter != 1.0 && dimension > 2 )\r\n    {\r\n        for( std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = geometry::range::at(range, i);\r\n            set_z(point, get_z(point) * dstdefn.vfr_meter);\r\n        }\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Transform normalized axes into unusual output coordinate axis   */\r\n/*      orientation if needed.                                          */\r\n/* -------------------------------------------------------------------- */\r\n    // Ignored\r\n\r\n    return result;\r\n}\r\n\r\n/************************************************************************/\r\n/*                     pj_geodetic_to_geocentric()                      */\r\n/************************************************************************/\r\n\r\ntemplate <typename T, typename Range, bool AddZ>\r\ninline int pj_geodetic_to_geocentric( T const& a, T const& es,\r\n                                      range_wrapper<Range, AddZ> & range_wrapper )\r\n\r\n{\r\n    //typedef typename boost::range_iterator<Range>::type iterator;\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n    //typedef typename coordinate_type<point_type>::type coord_t;\r\n\r\n    Range & rng = range_wrapper.get_range();\r\n    std::size_t point_count = boost::size(rng);\r\n\r\n    int ret_errno = 0;\r\n\r\n    T const b = (es == 0.0) ? a : a * sqrt(1-es);\r\n\r\n    GeocentricInfo<T> gi;\r\n    if( pj_Set_Geocentric_Parameters( gi, a, b ) != 0 )\r\n    {\r\n        return PJD_ERR_GEOCENTRIC;\r\n    }\r\n\r\n    for( std::size_t i = 0 ; i < point_count ; ++i )\r\n    {\r\n        point_type & point = range::at(rng, i);\r\n\r\n        if( is_invalid_point(point) )\r\n            continue;\r\n\r\n        T X = 0, Y = 0, Z = 0;\r\n        if( pj_Convert_Geodetic_To_Geocentric( gi,\r\n                                               get_as_radian<0>(point),\r\n                                               get_as_radian<1>(point),\r\n                                               range_wrapper.get_z(i), // Height\r\n                                               X, Y, Z ) != 0 )\r\n        {\r\n            ret_errno = -14;\r\n            set_invalid_point(point);\r\n            /* but keep processing points! */\r\n        }\r\n        else\r\n        {\r\n            set<0>(point, X);\r\n            set<1>(point, Y);\r\n            range_wrapper.set_z(i, Z);\r\n        }\r\n    }\r\n\r\n    return ret_errno;\r\n}\r\n\r\n/************************************************************************/\r\n/*                     pj_geodetic_to_geocentric()                      */\r\n/************************************************************************/\r\n\r\ntemplate <typename T, typename Range, bool AddZ>\r\ninline int pj_geocentric_to_geodetic( T const& a, T const& es,\r\n                                      range_wrapper<Range, AddZ> & range_wrapper )\r\n\r\n{\r\n    //typedef typename boost::range_iterator<Range>::type iterator;\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n    //typedef typename coordinate_type<point_type>::type coord_t;\r\n\r\n    Range & rng = range_wrapper.get_range();\r\n    std::size_t point_count = boost::size(rng);\r\n\r\n    T const b = (es == 0.0) ? a : a * sqrt(1-es);\r\n\r\n    GeocentricInfo<T> gi;\r\n    if( pj_Set_Geocentric_Parameters( gi, a, b ) != 0 )\r\n    {\r\n        return PJD_ERR_GEOCENTRIC;\r\n    }\r\n\r\n    for( std::size_t i = 0 ; i < point_count ; ++i )\r\n    {\r\n        point_type & point = range::at(rng, i);\r\n\r\n        if( is_invalid_point(point) )\r\n            continue;\r\n\r\n        T Longitude = 0, Latitude = 0, Height = 0;\r\n        pj_Convert_Geocentric_To_Geodetic( gi,\r\n                                           get<0>(point),\r\n                                           get<1>(point),\r\n                                           range_wrapper.get_z(i), // z\r\n                                           Longitude, Latitude, Height );\r\n\r\n        set_from_radian<0>(point, Longitude);\r\n        set_from_radian<1>(point, Latitude);\r\n        range_wrapper.set_z(i, Height); // Height\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n/************************************************************************/\r\n/*                         pj_compare_datums()                          */\r\n/*                                                                      */\r\n/*      Returns TRUE if the two datums are identical, otherwise         */\r\n/*      FALSE.                                                          */\r\n/************************************************************************/\r\n\r\ntemplate <typename Par>\r\ninline bool pj_compare_datums( Par & srcdefn, Par & dstdefn )\r\n{\r\n    if( srcdefn.datum_type != dstdefn.datum_type )\r\n    {\r\n        return false;\r\n    }\r\n    else if( srcdefn.a_orig != dstdefn.a_orig\r\n             || math::abs(srcdefn.es_orig - dstdefn.es_orig) > 0.000000000050 )\r\n    {\r\n        /* the tolerance for es is to ensure that GRS80 and WGS84 are\r\n           considered identical */\r\n        return false;\r\n    }\r\n    else if( srcdefn.datum_type == PJD_3PARAM )\r\n    {\r\n        return (srcdefn.datum_params[0] == dstdefn.datum_params[0]\r\n                && srcdefn.datum_params[1] == dstdefn.datum_params[1]\r\n                && srcdefn.datum_params[2] == dstdefn.datum_params[2]);\r\n    }\r\n    else if( srcdefn.datum_type == PJD_7PARAM )\r\n    {\r\n        return (srcdefn.datum_params[0] == dstdefn.datum_params[0]\r\n                && srcdefn.datum_params[1] == dstdefn.datum_params[1]\r\n                && srcdefn.datum_params[2] == dstdefn.datum_params[2]\r\n                && srcdefn.datum_params[3] == dstdefn.datum_params[3]\r\n                && srcdefn.datum_params[4] == dstdefn.datum_params[4]\r\n                && srcdefn.datum_params[5] == dstdefn.datum_params[5]\r\n                && srcdefn.datum_params[6] == dstdefn.datum_params[6]);\r\n    }\r\n    else if( srcdefn.datum_type == PJD_GRIDSHIFT )\r\n    {\r\n        return pj_param(srcdefn.params,\"snadgrids\").s\r\n            == pj_param(dstdefn.params,\"snadgrids\").s;\r\n    }\r\n    else\r\n        return true;\r\n}\r\n\r\n/************************************************************************/\r\n/*                       pj_geocentic_to_wgs84()                        */\r\n/************************************************************************/\r\n\r\ntemplate <typename Par, typename Range, bool AddZ>\r\ninline int pj_geocentric_to_wgs84( Par const& defn,\r\n                                   range_wrapper<Range, AddZ> & range_wrapper )\r\n\r\n{\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n    typedef typename coordinate_type<point_type>::type coord_t;\r\n\r\n    Range & rng = range_wrapper.get_range();\r\n    std::size_t point_count = boost::size(rng);\r\n\r\n    if( defn.datum_type == PJD_3PARAM )\r\n    {\r\n        for(std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = range::at(rng, i);\r\n            \r\n            if( is_invalid_point(point) )\r\n                continue;\r\n\r\n            set<0>(point,                   get<0>(point) + Dx_BF(defn));\r\n            set<1>(point,                   get<1>(point) + Dy_BF(defn));\r\n            range_wrapper.set_z(i, range_wrapper.get_z(i) + Dz_BF(defn));\r\n        }\r\n    }\r\n    else if( defn.datum_type == PJD_7PARAM )\r\n    {\r\n        for(std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = range::at(rng, i);\r\n\r\n            if( is_invalid_point(point) )\r\n                continue;\r\n\r\n            coord_t x = get<0>(point);\r\n            coord_t y = get<1>(point);\r\n            coord_t z = range_wrapper.get_z(i);\r\n\r\n            coord_t x_out, y_out, z_out;\r\n\r\n            x_out = M_BF(defn)*(             x - Rz_BF(defn)*y + Ry_BF(defn)*z) + Dx_BF(defn);\r\n            y_out = M_BF(defn)*( Rz_BF(defn)*x +             y - Rx_BF(defn)*z) + Dy_BF(defn);\r\n            z_out = M_BF(defn)*(-Ry_BF(defn)*x + Rx_BF(defn)*y +             z) + Dz_BF(defn);\r\n\r\n            set<0>(point, x_out);\r\n            set<1>(point, y_out);\r\n            range_wrapper.set_z(i, z_out);\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n/************************************************************************/\r\n/*                      pj_geocentic_from_wgs84()                       */\r\n/************************************************************************/\r\n\r\ntemplate <typename Par, typename Range, bool AddZ>\r\ninline int pj_geocentric_from_wgs84( Par const& defn,\r\n                                     range_wrapper<Range, AddZ> & range_wrapper )\r\n\r\n{\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n    typedef typename coordinate_type<point_type>::type coord_t;\r\n\r\n    Range & rng = range_wrapper.get_range();\r\n    std::size_t point_count = boost::size(rng);\r\n\r\n    if( defn.datum_type == PJD_3PARAM )\r\n    {\r\n        for(std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = range::at(rng, i);\r\n\r\n            if( is_invalid_point(point) )\r\n                continue;\r\n\r\n            set<0>(point,                   get<0>(point) - Dx_BF(defn));\r\n            set<1>(point,                   get<1>(point) - Dy_BF(defn));\r\n            range_wrapper.set_z(i, range_wrapper.get_z(i) - Dz_BF(defn));\r\n        }\r\n    }\r\n    else if( defn.datum_type == PJD_7PARAM )\r\n    {\r\n        for(std::size_t i = 0; i < point_count; i++ )\r\n        {\r\n            point_type & point = range::at(rng, i);\r\n\r\n            if( is_invalid_point(point) )\r\n                continue;\r\n\r\n            coord_t x = get<0>(point);\r\n            coord_t y = get<1>(point);\r\n            coord_t z = range_wrapper.get_z(i);\r\n\r\n            coord_t x_tmp = (x - Dx_BF(defn)) / M_BF(defn);\r\n            coord_t y_tmp = (y - Dy_BF(defn)) / M_BF(defn);\r\n            coord_t z_tmp = (z - Dz_BF(defn)) / M_BF(defn);\r\n\r\n            x =              x_tmp + Rz_BF(defn)*y_tmp - Ry_BF(defn)*z_tmp;\r\n            y = -Rz_BF(defn)*x_tmp +             y_tmp + Rx_BF(defn)*z_tmp;\r\n            z =  Ry_BF(defn)*x_tmp - Rx_BF(defn)*y_tmp +             z_tmp;\r\n\r\n            set<0>(point, x);\r\n            set<1>(point, y);\r\n            range_wrapper.set_z(i, z);\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n\r\ninline bool pj_datum_check_error(int err)\r\n{\r\n    return err != 0 && (err > 0 || transient_error[-err] == 0);\r\n}\r\n\r\n/************************************************************************/\r\n/*                         pj_datum_transform()                         */\r\n/*                                                                      */\r\n/*      The input should be long/lat/z coordinates in radians in the    */\r\n/*      source datum, and the output should be long/lat/z               */\r\n/*      coordinates in radians in the destination datum.                */\r\n/************************************************************************/\r\n\r\ntemplate <typename Par, typename Range>\r\ninline bool pj_datum_transform( Par const& srcdefn, Par const& dstdefn,\r\n                                Range & range )\r\n\r\n{\r\n    typedef typename Par::type calc_t;\r\n    bool result = true;\r\n\r\n    calc_t      src_a, src_es, dst_a, dst_es;\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      We cannot do any meaningful datum transformation if either      */\r\n/*      the source or destination are of an unknown datum type          */\r\n/*      (ie. only a +ellps declaration, no +datum).  This is new        */\r\n/*      behavior for PROJ 4.6.0.                                        */\r\n/* -------------------------------------------------------------------- */\r\n    if( srcdefn.datum_type == PJD_UNKNOWN\r\n        || dstdefn.datum_type == PJD_UNKNOWN )\r\n        return result;\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Short cut if the datums are identical.                          */\r\n/* -------------------------------------------------------------------- */\r\n    if( pj_compare_datums( srcdefn, dstdefn ) )\r\n        return result;\r\n\r\n    src_a = srcdefn.a_orig;\r\n    src_es = srcdefn.es_orig;\r\n\r\n    dst_a = dstdefn.a_orig;\r\n    dst_es = dstdefn.es_orig;\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Create a temporary Z array if one is not provided.              */\r\n/* -------------------------------------------------------------------- */\r\n    \r\n    range_wrapper<Range> z_range(range);\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      If this datum requires grid shifts, then apply it to geodetic   */\r\n/*      coordinates.                                                    */\r\n/* -------------------------------------------------------------------- */\r\n    /*if( srcdefn.datum_type == PJD_GRIDSHIFT )\r\n    {\r\n        try {\r\n            pj_apply_gridshift_2( srcdefn, 0, point_count, point_offset, x, y, z );\r\n        } catch (projection_exception const& e) {\r\n            if (pj_datum_check_error(e.code())) {\r\n                BOOST_RETHROW\r\n            }\r\n        }\r\n\r\n        src_a = SRS_WGS84_SEMIMAJOR;\r\n        src_es = SRS_WGS84_ESQUARED;\r\n    }\r\n\r\n    if( dstdefn.datum_type == PJD_GRIDSHIFT )\r\n    {\r\n        dst_a = SRS_WGS84_SEMIMAJOR;\r\n        dst_es = SRS_WGS84_ESQUARED;\r\n    }*/\r\n\r\n/* ==================================================================== */\r\n/*      Do we need to go through geocentric coordinates?                */\r\n/* ==================================================================== */\r\n    if( src_es != dst_es || src_a != dst_a\r\n        || srcdefn.datum_type == PJD_3PARAM\r\n        || srcdefn.datum_type == PJD_7PARAM\r\n        || dstdefn.datum_type == PJD_3PARAM\r\n        || dstdefn.datum_type == PJD_7PARAM)\r\n    {\r\n/* -------------------------------------------------------------------- */\r\n/*      Convert to geocentric coordinates.                              */\r\n/* -------------------------------------------------------------------- */\r\n        int err = pj_geodetic_to_geocentric( src_a, src_es, z_range );\r\n        if (pj_datum_check_error(err))\r\n            BOOST_THROW_EXCEPTION( projection_exception(err) );\r\n        else if (err != 0)\r\n            result = false;\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Convert between datums.                                         */\r\n/* -------------------------------------------------------------------- */\r\n        if( srcdefn.datum_type == PJD_3PARAM\r\n            || srcdefn.datum_type == PJD_7PARAM )\r\n        {\r\n            try {\r\n                pj_geocentric_to_wgs84( srcdefn, z_range );\r\n            } catch (projection_exception const& e) {\r\n                if (pj_datum_check_error(e.code())) {\r\n                    BOOST_RETHROW\r\n                }\r\n            }\r\n        }\r\n\r\n        if( dstdefn.datum_type == PJD_3PARAM\r\n            || dstdefn.datum_type == PJD_7PARAM )\r\n        {\r\n            try {\r\n                pj_geocentric_from_wgs84( dstdefn, z_range );\r\n            } catch (projection_exception const& e) {\r\n                if (pj_datum_check_error(e.code())) {\r\n                    BOOST_RETHROW\r\n                }\r\n            }\r\n        }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Convert back to geodetic coordinates.                           */\r\n/* -------------------------------------------------------------------- */\r\n        err = pj_geocentric_to_geodetic( dst_a, dst_es, z_range );\r\n        if (pj_datum_check_error(err))\r\n            BOOST_THROW_EXCEPTION( projection_exception(err) );\r\n        else if (err != 0)\r\n            result = false;\r\n    }\r\n\r\n/* -------------------------------------------------------------------- */\r\n/*      Apply grid shift to destination if required.                    */\r\n/* -------------------------------------------------------------------- */\r\n    /*if( dstdefn.datum_type == PJD_GRIDSHIFT )\r\n    {\r\n        try {\r\n            pj_apply_gridshift_2( dstdefn, 1, point_count, point_offset, x, y, z );\r\n        } catch (projection_exception const& e) {\r\n            if (pj_datum_check_error(e.code()))\r\n                BOOST_RETHROW\r\n        }\r\n    }*/\r\n\r\n    return result;\r\n}\r\n\r\n} // namespace detail\r\n\r\n}}} // namespace boost::geometry::projections\r\n\r\n#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_PJ_TRANSFORM_HPP\r\n", "meta": {"hexsha": "a702741a19d85374850cde695973c691fb63faa8", "size": 38725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/impl/pj_transform.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_transform.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_transform.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": 38.3415841584, "max_line_length": 100, "alphanum_fraction": 0.4451387992, "num_tokens": 8459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.05749327799292466, "lm_q1q2_score": 0.01984123405450249}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include <ripley/Rectangle.h>\n#include <ripley/DefaultAssembler2D.h>\n#include <ripley/LameAssembler2D.h>\n#include <ripley/WaveAssembler2D.h>\n#include <ripley/blocktools.h>\n#include <ripley/domainhelpers.h>\n\n#include <escript/FileWriter.h>\n#include <escript/index.h>\n#include <escript/Random.h>\n\n#ifdef ESYS_HAVE_PASO\n#include <paso/SystemMatrix.h>\n#endif\n\n#ifdef ESYS_HAVE_NETCDF\n #ifdef NETCDF4\n  #include <ncVar.h>\n  #include <ncDim.h>\n  #include <escript/NCHelper.h>\n\n #else\n   #include <netcdfcpp.h>\n #endif\n#endif\n\n\n\n#ifdef ESYS_HAVE_SILO\n#include <silo.h>\n#ifdef ESYS_MPI\n#include <pmpio.h>\n#endif\n#endif\n\n#include <boost/math/special_functions/fpclassify.hpp>\t// for isnan\n#include <boost/scoped_array.hpp>\n\n#include <iomanip>\n#include <limits>\n\nnamespace bp = boost::python;\nnamespace bm = boost::math;\nusing escript::AbstractSystemMatrix;\nusing escript::FileWriter;\nusing escript::IOError;\nusing escript::NotImplementedError;\nusing escript::ValueError;\nusing std::vector;\nusing std::string;\nusing std::min;\nusing std::max;\nusing std::copy;\nusing std::ios;\nusing std::fill;\n\n#ifdef NETCDF4\nusing namespace netCDF;\n#endif\n\n\nnamespace ripley {\n\nRectangle::Rectangle(dim_t n0, dim_t n1, double x0, double y0, double x1,\n                     double y1, int d0, int d1,\n                     const vector<double>& points,\n                     const vector<int>& tags,\n                     const TagMap& tagnamestonums,\n                     escript::SubWorld_ptr w) :\n    RipleyDomain(2, w)\n{\n    if (static_cast<long>(n0 + 1) * static_cast<long>(n1 + 1)\n            > std::numeric_limits<dim_t>::max())\n        throw RipleyException(\"The number of elements has overflowed, this \"\n                \"limit may be raised in future releases.\");\n\n    if (n0 <= 0 || n1 <= 0)\n        throw ValueError(\"Number of elements in each spatial dimension \"\n                \"must be positive\");\n\n    // ignore subdivision parameters for serial run\n    if (m_mpiInfo->size == 1) {\n        d0=1;\n        d1=1;\n    }\n\n    bool warn = false;\n    vector<int> factors;\n    int ranks = m_mpiInfo->size;\n    dim_t epr[2] = {n0,n1};\n    int d[2] = {d0,d1};\n    if (d0<=0 || d1<=0) {\n        for (int i = 0; i < 2; i++) {\n            if (d[i] < 1) {\n                d[i] = 1;\n                continue;\n            }\n            epr[i] = -1; // can no longer be max\n            //remove\n            if (ranks % d[i] != 0) {\n                throw ValueError(\"Invalid number of spatial subdivisions\");\n            }\n            ranks /= d[i];\n        }\n        factorise(factors, ranks);\n        if (factors.size() != 0) {\n            warn = true;\n        }\n    }\n\n    while (factors.size() > 0) {\n        int i = epr[0] > epr[1] ? 0 : 1;\n        int f = factors.back();\n        factors.pop_back();\n        d[i] *= f;\n        epr[i] /= f;\n    }\n    d0 = d[0]; d1 = d[1];\n\n    // ensure number of subdivisions is valid and nodes can be distributed\n    // among number of ranks\n    if (d0*d1 != m_mpiInfo->size)\n        throw ValueError(\"Invalid number of spatial subdivisions\");\n\n    if (warn) {\n        std::cout << \"Warning: Automatic domain subdivision (d0=\" << d0 << \", d1=\"\n            << d1 << \"). This may not be optimal!\" << std::endl;\n    }\n\n    double l0 = x1-x0;\n    double l1 = y1-y0;\n    m_dx[0] = l0/n0;\n    m_dx[1] = l1/n1;\n\n    warn = false;\n    if ((n0+1)%d0 > 0) {\n        switch (getDecompositionPolicy()) {\n            case DECOMP_EXPAND:\n                l0 = m_dx[0]*n0; // fall through\n            case DECOMP_ADD_ELEMENTS:\n                n0 = (dim_t)round((float)(n0+1)/d0+0.5)*d0-1; // fall through\n            case DECOMP_STRICT:\n                warn = true;\n                break;\n        }\n        // reset spacing\n        m_dx[0] = l0/n0;\n    }\n    if ((n1+1)%d1 > 0) {\n        switch (getDecompositionPolicy()) {\n            case DECOMP_EXPAND:\n                l1 = m_dx[1]*n1; // fall through\n            case DECOMP_ADD_ELEMENTS:\n                n1 = (dim_t)round((float)(n1+1)/d1+0.5)*d1-1; // fall through\n            case DECOMP_STRICT:\n                warn = true;\n                break;\n        }\n        // reset spacing\n        m_dx[1] = l1/n1;\n    }\n\n    if ((d0 > 1 && (n0+1)/d0<2) || (d1 > 1 && (n1+1)/d1<2))\n        throw ValueError(\"Too few elements for the number of ranks\");\n\n    if (warn) {\n        if (getDecompositionPolicy() == DECOMP_STRICT) {\n            throw ValueError(\"Unable to decompose domain to the number of \"\n                    \"MPI ranks without adding elements and the policy \"\n                    \"is set to STRICT. Use setDecompositionPolicy() \"\n                    \"to allow adding elements.\");\n        } else {\n            std::cout << \"Warning: Domain setup has been adjusted as follows \"\n                    \"to allow decomposition into \" << m_mpiInfo->size\n                    << \" MPI ranks:\" << std::endl\n                    << \"    N0=\" << n0 << \", l0=\" << l0 << std::endl\n                    << \"    N1=\" << n1 << \", l1=\" << l1 << std::endl;\n        }\n    }\n    m_gNE[0] = n0;\n    m_gNE[1] = n1;\n    m_origin[0] = x0;\n    m_origin[1] = y0;\n    m_length[0] = l0;\n    m_length[1] = l1;\n    m_NX[0] = d0;\n    m_NX[1] = d1;\n\n    // local number of elements (with and without overlap)\n    m_NE[0] = m_ownNE[0] = (d0>1 ? (n0+1)/d0 : n0);\n    if (m_mpiInfo->rank%d0>0 && m_mpiInfo->rank%d0<d0-1)\n        m_NE[0]++;\n    else if (d0>1 && m_mpiInfo->rank%d0==d0-1)\n        m_ownNE[0]--;\n\n    m_NE[1] = m_ownNE[1] = (d1>1 ? (n1+1)/d1 : n1);\n    if (m_mpiInfo->rank/d0>0 && m_mpiInfo->rank/d0<d1-1)\n        m_NE[1]++;\n    else if (d1>1 && m_mpiInfo->rank/d0==d1-1)\n        m_ownNE[1]--;\n\n    // local number of nodes\n    m_NN[0] = m_NE[0]+1;\n    m_NN[1] = m_NE[1]+1;\n\n    // bottom-left node is at (offset0,offset1) in global mesh\n    m_offset[0] = (n0+1)/d0*(m_mpiInfo->rank%d0);\n    if (m_offset[0] > 0)\n        m_offset[0]--;\n    m_offset[1] = (n1+1)/d1*(m_mpiInfo->rank/d0);\n    if (m_offset[1] > 0)\n        m_offset[1]--;\n\n    populateSampleIds();\n\n    for (TagMap::const_iterator i = tagnamestonums.begin();\n            i != tagnamestonums.end(); i++) {\n        setTagMap(i->first, i->second);\n    }\n    addPoints(points, tags);\n}\n\nRectangle::~Rectangle()\n{\n}\n\nstring Rectangle::getDescription() const\n{\n    return \"ripley::Rectangle\";\n}\n\nbool Rectangle::operator==(const escript::AbstractDomain& other) const\n{\n    const Rectangle* o=dynamic_cast<const Rectangle*>(&other);\n    if (o) {\n        return (RipleyDomain::operator==(other) &&\n                m_gNE[0]==o->m_gNE[0] && m_gNE[1]==o->m_gNE[1]\n                && m_origin[0]==o->m_origin[0] && m_origin[1]==o->m_origin[1]\n                && m_length[0]==o->m_length[0] && m_length[1]==o->m_length[1]\n                && m_NX[0]==o->m_NX[0] && m_NX[1]==o->m_NX[1]);\n    }\n\n    return false;\n}\n\n#ifdef NETCDF4\nvoid Rectangle::readNcGrid(escript::Data& out, string filename, string varname,\n            const ReaderParameters& params) const\n{\n#ifdef ESYS_HAVE_NETCDF\n    // check destination function space\n    dim_t myN0, myN1;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NN[0];\n        myN1 = m_NN[1];\n    } else if (out.getFunctionSpace().getTypeCode() == Elements ||\n                out.getFunctionSpace().getTypeCode() == ReducedElements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n    } else\n        throw ValueError(\"readNcGrid(): invalid function space for output data object\");\n\n    if (params.first.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'first' must have 2 entries\");\n\n    if (params.numValues.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'numValues' must have 2 entries\");\n\n    if (params.multiplier.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'multiplier' must have 2 entries\");\n    for (size_t i=0; i<params.multiplier.size(); i++)\n        if (params.multiplier[i]<1)\n            throw ValueError(\"readNcGrid(): all multipliers must be positive\");\n    if (params.reverse.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'reverse' must have 2 entries\");\n\n    NcFile f;\n    if (!escript::openNcFile(f, filename))\n    {\n        throw RipleyException(\"readNcGrid(): cannot open file\");\n    }       \n    \n    NcVar var = f.getVar(varname.c_str());\n    if (var.isNull())\n        throw RipleyException(\"readNcGrid(): invalid variable name\");    \n\n    // TODO: rank>0 data support\n    const int numComp = out.getDataPointSize();\n    if (numComp > 1)\n        throw NotImplementedError(\"readNcGrid(): only scalar data supported\");\n\n    const int dims = var.getDimCount();\n    vector<long> edges(dims);\n    std::vector< NcDim > vard=var.getDims();\n    for (size_t i=0;i<vard.size();++i)\n    {\n        edges[i]=vard[i].getSize();\n    }    \n\n    // is this a slice of the data object (dims!=2)?\n    // note the expected ordering of edges (as in numpy: y,x)\n    if ( (dims==2 && (params.numValues[1] > edges[0] || params.numValues[0] > edges[1]))\n            || (dims==1 && params.numValues[1]>1) ) {\n        throw IOError(\"readNcGrid(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+params.numValues[0]*params.multiplier[0] <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+params.numValues[1]*params.multiplier[1] <= m_offset[1])\n        return;\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    // indices to first value in file (not accounting for reverse yet)\n    dim_t idx0 = max(dim_t(0), m_offset[0]-params.first[0]);\n    dim_t idx1 = max(dim_t(0), m_offset[1]-params.first[1]);\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n\n    // make sure we read the right block if going backwards through file\n    if (params.reverse[0])\n        idx0 = edges[dims-1]-num0-idx0;\n    if (dims>1 && params.reverse[1])\n        idx1 = edges[dims-2]-num1-idx1;\n\n    vector<double> values(num0*num1);\n    vector<size_t> startindex;\n    vector<size_t> counts;    \n    if (dims==2) {\n//         var->set_cur(idx1, idx0);\n//         var->get(&values[0], num1, num0);\n        startindex.push_back(idx1);\n        startindex.push_back(idx0);\n        counts.push_back(num1);\n        counts.push_back(num0);\n        var.getVar(startindex, counts, &values[0]);           \n    } else {\n//         var->set_cur(idx0);\n//         var->get(&values[0], num0);\n        startindex.push_back(idx0);\n        counts.push_back(num0);\n        var.getVar(startindex, counts, &values[0]);           \n    }\n\n    const int dpp = out.getNumDataPointsPerSample();\n    out.requireWrite();\n\n    // helpers for reversing\n    const dim_t x0 = (params.reverse[0] ? num0-1 : 0);\n    const int x_mult = (params.reverse[0] ? -1 : 1);\n    const dim_t y0 = (params.reverse[1] ? num1-1 : 0);\n    const int y_mult = (params.reverse[1] ? -1 : 1);\n\n    for (index_t y=0; y<num1; y++) {\n#pragma omp parallel for\n        for (index_t x=0; x<num0; x++) {\n            const dim_t baseIndex = first0+x*params.multiplier[0]\n                                  +(first1+y*params.multiplier[1])*myN0;\n            const dim_t srcIndex = (y0+y_mult*y)*num0+(x0+x_mult*x);\n            if (!bm::isnan(values[srcIndex])) {\n                for (index_t m1=0; m1<params.multiplier[1]; m1++) {\n                    for (index_t m0=0; m0<params.multiplier[0]; m0++) {\n                        const dim_t dataIndex = baseIndex+m0+m1*myN0;\n                        double* dest = out.getSampleDataRW(dataIndex);\n                        for (index_t q=0; q<dpp; q++) {\n                            *dest++ = values[srcIndex];\n                        }\n                    }\n                }\n            }\n        }\n    }\n#else\n    throw RipleyException(\"readNcGrid(): not compiled with netCDF support\");\n#endif\n}\n\n#else\n\nvoid Rectangle::readNcGrid(escript::Data& out, string filename, string varname,\n            const ReaderParameters& params) const\n{\n#ifdef ESYS_HAVE_NETCDF\n    // check destination function space\n    dim_t myN0, myN1;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NN[0];\n        myN1 = m_NN[1];\n    } else if (out.getFunctionSpace().getTypeCode() == Elements ||\n                out.getFunctionSpace().getTypeCode() == ReducedElements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n    } else\n        throw ValueError(\"readNcGrid(): invalid function space for output data object\");\n\n    if (params.first.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'first' must have 2 entries\");\n\n    if (params.numValues.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'numValues' must have 2 entries\");\n\n    if (params.multiplier.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'multiplier' must have 2 entries\");\n    for (size_t i=0; i<params.multiplier.size(); i++)\n        if (params.multiplier[i]<1)\n            throw ValueError(\"readNcGrid(): all multipliers must be positive\");\n    if (params.reverse.size() != 2)\n        throw ValueError(\"readNcGrid(): argument 'reverse' must have 2 entries\");\n\n    // check file existence and size\n    NcFile f(filename.c_str(), NcFile::ReadOnly);\n    if (!f.is_valid())\n        throw IOError(\"readNcGrid(): cannot open file\");\n\n    NcVar* var = f.get_var(varname.c_str());\n    if (!var)\n        throw IOError(\"readNcGrid(): invalid variable\");\n\n    // TODO: rank>0 data support\n    const int numComp = out.getDataPointSize();\n    if (numComp > 1)\n        throw NotImplementedError(\"readNcGrid(): only scalar data supported\");\n\n    const int dims = var->num_dims();\n    boost::scoped_array<long> edges(var->edges());\n\n    // is this a slice of the data object (dims!=2)?\n    // note the expected ordering of edges (as in numpy: y,x)\n    if ( (dims==2 && (params.numValues[1] > edges[0] || params.numValues[0] > edges[1]))\n            || (dims==1 && params.numValues[1]>1) ) {\n        throw IOError(\"readNcGrid(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+params.numValues[0]*params.multiplier[0] <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+params.numValues[1]*params.multiplier[1] <= m_offset[1])\n        return;\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    // indices to first value in file (not accounting for reverse yet)\n    dim_t idx0 = max(dim_t(0), m_offset[0]-params.first[0]);\n    dim_t idx1 = max(dim_t(0), m_offset[1]-params.first[1]);\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n\n    // make sure we read the right block if going backwards through file\n    if (params.reverse[0])\n        idx0 = edges[dims-1]-num0-idx0;\n    if (dims>1 && params.reverse[1])\n        idx1 = edges[dims-2]-num1-idx1;\n\n    vector<double> values(num0*num1);\n    if (dims==2) {\n        var->set_cur(idx1, idx0);\n        var->get(&values[0], num1, num0);\n    } else {\n        var->set_cur(idx0);\n        var->get(&values[0], num0);\n    }\n\n    const int dpp = out.getNumDataPointsPerSample();\n    out.requireWrite();\n\n    // helpers for reversing\n    const dim_t x0 = (params.reverse[0] ? num0-1 : 0);\n    const int x_mult = (params.reverse[0] ? -1 : 1);\n    const dim_t y0 = (params.reverse[1] ? num1-1 : 0);\n    const int y_mult = (params.reverse[1] ? -1 : 1);\n\n    for (index_t y=0; y<num1; y++) {\n#pragma omp parallel for\n        for (index_t x=0; x<num0; x++) {\n            const dim_t baseIndex = first0+x*params.multiplier[0]\n                                  +(first1+y*params.multiplier[1])*myN0;\n            const dim_t srcIndex = (y0+y_mult*y)*num0+(x0+x_mult*x);\n            if (!bm::isnan(values[srcIndex])) {\n                for (index_t m1=0; m1<params.multiplier[1]; m1++) {\n                    for (index_t m0=0; m0<params.multiplier[0]; m0++) {\n                        const dim_t dataIndex = baseIndex+m0+m1*myN0;\n                        double* dest = out.getSampleDataRW(dataIndex);\n                        for (index_t q=0; q<dpp; q++) {\n                            *dest++ = values[srcIndex];\n                        }\n                    }\n                }\n            }\n        }\n    }\n#else\n    throw RipleyException(\"readNcGrid(): not compiled with netCDF support\");\n#endif\n}\n\n#endif\n\nvoid Rectangle::readBinaryGrid(escript::Data& out, string filename,\n                               const ReaderParameters& params) const\n{\n    // the mapping is not universally correct but should work on our\n    // supported platforms\n    switch (params.dataType) {\n        case DATATYPE_INT32:\n            readBinaryGridImpl<int>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT32:\n            readBinaryGridImpl<float>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT64:\n            readBinaryGridImpl<double>(out, filename, params);\n            break;\n        default:\n            throw ValueError(\"readBinaryGrid(): invalid or unsupported datatype\");\n    }\n}\n\nvoid Rectangle::readBinaryGridFromZipped(escript::Data& out, string filename,\n                               const ReaderParameters& params) const\n{\n#ifdef ESYS_HAVE_BOOST_IO\n    // the mapping is not universally correct but should work on our\n    // supported platforms\n    switch (params.dataType) {\n        case DATATYPE_INT32:\n            readBinaryGridZippedImpl<int>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT32:\n            readBinaryGridZippedImpl<float>(out, filename, params);\n            break;\n        case DATATYPE_FLOAT64:\n            readBinaryGridZippedImpl<double>(out, filename, params);\n            break;\n        default:\n            throw ValueError(\"readBinaryGridFromZipped(): invalid or unsupported datatype\");\n    }\n#else\n    throw ValueError(\"readBinaryGridFromZipped(): not compiled with zip support\");\n#endif\n}\n\ntemplate<typename ValueType>\nvoid Rectangle::readBinaryGridImpl(escript::Data& out, const string& filename,\n                                   const ReaderParameters& params) const\n{\n    // check destination function space\n    dim_t myN0, myN1;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NN[0];\n        myN1 = m_NN[1];\n    } else if (out.getFunctionSpace().getTypeCode() == Elements ||\n                out.getFunctionSpace().getTypeCode() == ReducedElements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n    } else\n        throw ValueError(\"readBinaryGrid(): invalid function space for output data object\");\n\n    if (params.first.size() != 2)\n        throw ValueError(\"readBinaryGrid(): argument 'first' must have 2 entries\");\n\n    if (params.numValues.size() != 2)\n        throw ValueError(\"readBinaryGrid(): argument 'numValues' must have 2 entries\");\n\n    if (params.multiplier.size() != 2)\n        throw ValueError(\"readBinaryGrid(): argument 'multiplier' must have 2 entries\");\n    for (size_t i=0; i<params.multiplier.size(); i++)\n        if (params.multiplier[i]<1)\n            throw ValueError(\"readBinaryGrid(): all multipliers must be positive\");\n    if (params.reverse[0] != 0 || params.reverse[1] != 0)\n        throw NotImplementedError(\"readBinaryGrid(): reversing not supported yet\");\n\n    // check file existence and size\n    std::ifstream f(filename.c_str(), std::ifstream::binary);\n    if (f.fail()) {\n        throw IOError(\"readBinaryGrid(): cannot open file \" + filename);\n    }\n    f.seekg(0, ios::end);\n    const int numComp = out.getDataPointSize();\n    const dim_t filesize = f.tellg();\n    const dim_t reqsize = params.numValues[0]*params.numValues[1]*numComp*sizeof(ValueType);\n    if (filesize < reqsize) {\n        f.close();\n        throw IOError(\"readBinaryGrid(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+(params.numValues[0]*params.multiplier[0]) <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+(params.numValues[1]*params.multiplier[1]) <= m_offset[1]) {\n        f.close();\n        return;\n    }\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    // indices to first value in file\n    const dim_t idx0 = max(dim_t(0), (m_offset[0]/params.multiplier[0])-params.first[0]);\n    const dim_t idx1 = max(dim_t(0), (m_offset[1]/params.multiplier[1])-params.first[1]);\n    // if restX > 0 the first value in the respective dimension has been\n    // written restX times already in a previous rank so this rank only\n    // contributes (multiplier-rank) copies of that value\n    const dim_t rest0 = m_offset[0]%params.multiplier[0];\n    const dim_t rest1 = m_offset[1]%params.multiplier[1];\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n\n    out.requireWrite();\n    vector<ValueType> values(num0*numComp);\n    const int dpp = out.getNumDataPointsPerSample();\n\n    for (dim_t y=0; y<num1; y++) {\n        const dim_t fileofs = numComp*(idx0+(idx1+y)*params.numValues[0]);\n        f.seekg(fileofs*sizeof(ValueType));\n        f.read((char*)&values[0], num0*numComp*sizeof(ValueType));\n        const dim_t m1limit = (y==0 ? params.multiplier[1]-rest1 : params.multiplier[1]);\n        dim_t dataYbase = first1+y*params.multiplier[1];\n        if (y>0)\n            dataYbase -= rest1;\n        for (dim_t x=0; x<num0; x++) {\n            const dim_t m0limit = (x==0 ? params.multiplier[0]-rest0 : params.multiplier[0]);\n            dim_t dataXbase = first0+x*params.multiplier[0];\n            if (x>0)\n                dataXbase -= rest0;\n            // write a block of mult0 x mult1 identical values into Data object\n            for (dim_t m1=0; m1<m1limit; m1++) {\n                const dim_t dataY = dataYbase+m1;\n                if (dataY >= myN1)\n                    break;\n                for (dim_t m0=0; m0<m0limit; m0++) {\n                    const dim_t dataX = dataXbase+m0;\n                    if (dataX >= myN0)\n                        break;\n                    const dim_t dataIndex = dataX+dataY*myN0;\n                    double* dest = out.getSampleDataRW(dataIndex);\n                    for (int c=0; c<numComp; c++) {\n                        ValueType val = values[x*numComp+c];\n\n                        if (params.byteOrder != BYTEORDER_NATIVE) {\n                            char* cval = reinterpret_cast<char*>(&val);\n                            // this will alter val!!\n                            if (sizeof(ValueType) > 4) {\n                                byte_swap64(cval);\n                            } else {\n                                byte_swap32(cval);\n                            }\n                        }\n                        if (!bm::isnan(val)) {\n                            for (int q=0; q<dpp; q++) {\n                                *dest++ = static_cast<double>(val);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    f.close();\n}\n\n#ifdef ESYS_HAVE_BOOST_IO\ntemplate<typename ValueType>\nvoid Rectangle::readBinaryGridZippedImpl(escript::Data& out, const string& filename,\n                                   const ReaderParameters& params) const\n{\n    // check destination function space\n    dim_t myN0, myN1;\n    if (out.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NN[0];\n        myN1 = m_NN[1];\n    } else if (out.getFunctionSpace().getTypeCode() == Elements ||\n                out.getFunctionSpace().getTypeCode() == ReducedElements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n    } else\n        throw ValueError(\"readBinaryGrid(): invalid function space for output data object\");\n\n    // check file existence and size\n    std::ifstream f(filename.c_str(), std::ifstream::binary);\n    if (f.fail()) {\n        throw IOError(\"readBinaryGridFromZipped(): cannot open file\" + filename);\n    }\n    f.seekg(0, ios::end);\n    const int numComp = out.getDataPointSize();\n    dim_t filesize = f.tellg();\n    f.seekg(0, ios::beg);\n    vector<char> compressed(filesize);\n    f.read((char*)&compressed[0], filesize);\n    f.close();\n    vector<char> decompressed = unzip(compressed);\n    filesize = decompressed.size();\n    const dim_t reqsize = params.numValues[0]*params.numValues[1]*numComp*sizeof(ValueType);\n    if (filesize < reqsize) {\n        throw IOError(\"readBinaryGridFromZipped(): not enough data in file\");\n    }\n\n    // check if this rank contributes anything\n    if (params.first[0] >= m_offset[0]+myN0 ||\n            params.first[0]+params.numValues[0] <= m_offset[0] ||\n            params.first[1] >= m_offset[1]+myN1 ||\n            params.first[1]+params.numValues[1] <= m_offset[1]) {\n        f.close();\n        return;\n    }\n\n    // now determine how much this rank has to write\n\n    // first coordinates in data object to write to\n    const dim_t first0 = max(dim_t(0), params.first[0]-m_offset[0]);\n    const dim_t first1 = max(dim_t(0), params.first[1]-m_offset[1]);\n    // indices to first value in file\n    const dim_t idx0 = max(dim_t(0), m_offset[0]-params.first[0]);\n    const dim_t idx1 = max(dim_t(0), m_offset[1]-params.first[1]);\n    // number of values to read\n    const dim_t num0 = min(params.numValues[0]-idx0, myN0-first0);\n    const dim_t num1 = min(params.numValues[1]-idx1, myN1-first1);\n\n    out.requireWrite();\n    vector<ValueType> values(num0*numComp);\n    const int dpp = out.getNumDataPointsPerSample();\n\n    for (dim_t y=0; y<num1; y++) {\n        const dim_t fileofs = numComp*(idx0+(idx1+y)*params.numValues[0]);\n            memcpy((char*)&values[0], (char*)&decompressed[fileofs*sizeof(ValueType)], num0*numComp*sizeof(ValueType));\n        for (dim_t x=0; x<num0; x++) {\n            const dim_t baseIndex = first0+x*params.multiplier[0]\n                                    +(first1+y*params.multiplier[1])*myN0;\n            for (int m1=0; m1<params.multiplier[1]; m1++) {\n                for (int m0=0; m0<params.multiplier[0]; m0++) {\n                    const dim_t dataIndex = baseIndex+m0+m1*myN0;\n                    double* dest = out.getSampleDataRW(dataIndex);\n                    for (int c=0; c<numComp; c++) {\n                        ValueType val = values[x*numComp+c];\n\n                        if (params.byteOrder != BYTEORDER_NATIVE) {\n                            char* cval = reinterpret_cast<char*>(&val);\n                            // this will alter val!!\n                            byte_swap32(cval);\n                        }\n                        if (!bm::isnan(val)) {\n                            for (int q=0; q<dpp; q++) {\n                                *dest++ = static_cast<double>(val);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    f.close();\n}\n#endif\n\nvoid Rectangle::writeBinaryGrid(const escript::Data& in, string filename,\n                                int byteOrder, int dataType) const\n{\n    // the mapping is not universally correct but should work on our\n    // supported platforms\n    switch (dataType) {\n        case DATATYPE_INT32:\n            writeBinaryGridImpl<int>(in, filename, byteOrder);\n            break;\n        case DATATYPE_FLOAT32:\n            writeBinaryGridImpl<float>(in, filename, byteOrder);\n            break;\n        case DATATYPE_FLOAT64:\n            writeBinaryGridImpl<double>(in, filename, byteOrder);\n            break;\n        default:\n            throw ValueError(\"writeBinaryGrid(): invalid or unsupported datatype\");\n    }\n}\n\ntemplate<typename ValueType>\nvoid Rectangle::writeBinaryGridImpl(const escript::Data& in,\n                                    const string& filename, int byteOrder) const\n{\n    // check function space and determine number of points\n    dim_t myN0, myN1;\n    dim_t totalN0, totalN1;\n    dim_t offset0, offset1;\n    if (in.getFunctionSpace().getTypeCode() == Nodes) {\n        myN0 = m_NN[0];\n        myN1 = m_NN[1];\n        totalN0 = m_gNE[0]+1;\n        totalN1 = m_gNE[1]+1;\n        offset0 = m_offset[0];\n        offset1 = m_offset[1];\n    } else if (in.getFunctionSpace().getTypeCode() == DegreesOfFreedom ||\n            in.getFunctionSpace().getTypeCode() == ReducedDegreesOfFreedom) {\n        myN0 = (m_gNE[0]+1)/m_NX[0];\n        myN1 = (m_gNE[1]+1)/m_NX[1];\n        totalN0 = m_gNE[0]+1;\n        totalN1 = m_gNE[1]+1;\n        offset0 = (m_offset[0]>0 ? m_offset[0]+1 : 0);\n        offset1 = (m_offset[1]>0 ? m_offset[1]+1 : 0);\n    } else if (in.getFunctionSpace().getTypeCode() == Elements ||\n                in.getFunctionSpace().getTypeCode() == ReducedElements) {\n        myN0 = m_NE[0];\n        myN1 = m_NE[1];\n        totalN0 = m_gNE[0];\n        totalN1 = m_gNE[1];\n        offset0 = m_offset[0];\n        offset1 = m_offset[1];\n    } else\n        throw ValueError(\"writeBinaryGrid(): unsupported function space\");\n\n    const int numComp = in.getDataPointSize();\n    const int dpp = in.getNumDataPointsPerSample();\n\n    if (numComp > 1 || dpp > 1)\n        throw NotImplementedError(\"writeBinaryGrid(): only scalar, single-value data supported\");\n\n    const dim_t fileSize = sizeof(ValueType)*numComp*dpp*totalN0*totalN1;\n\n    // from here on we know that each sample consists of one value\n    FileWriter fw(m_mpiInfo->comm);\n    fw.openFile(filename, fileSize, true);\n    MPIBarrier();\n\n    for (index_t y=0; y<myN1; y++) {\n        const dim_t fileofs = (offset0+(offset1+y)*totalN0)*sizeof(ValueType);\n        std::ostringstream oss;\n\n        for (index_t x=0; x<myN0; x++) {\n            const double* sample = in.getSampleDataRO(y*myN0+x);\n            ValueType fvalue = static_cast<ValueType>(*sample);\n            if (byteOrder == BYTEORDER_NATIVE) {\n                oss.write((char*)&fvalue, sizeof(fvalue));\n            } else {\n                char* value = reinterpret_cast<char*>(&fvalue);\n                if (sizeof(fvalue)>4) {\n                    byte_swap64(value);\n                } else {\n                    byte_swap32(value);\n                }\n                oss.write(value, sizeof(fvalue));\n            }\n        }\n        fw.writeAt(oss, fileofs);\n    }\n    fw.close();\n}\n\nvoid Rectangle::write(const std::string& filename) const\n{\n    throw NotImplementedError(\"write: not supported\");\n}\n\nvoid Rectangle::dump(const string& fileName) const\n{\n#ifdef ESYS_HAVE_SILO\n    string fn(fileName);\n    if (fileName.length() < 6 || fileName.compare(fileName.length()-5, 5, \".silo\") != 0) {\n        fn+=\".silo\";\n    }\n\n    int driver=DB_HDF5;\n    DBfile* dbfile = NULL;\n    const char* blockDirFmt = \"/block%04d\";\n\n#ifdef ESYS_MPI\n    PMPIO_baton_t* baton = NULL;\n    const int NUM_SILO_FILES = 1;\n#endif\n\n    if (m_mpiInfo->size > 1) {\n#ifdef ESYS_MPI\n        baton = PMPIO_Init(NUM_SILO_FILES, PMPIO_WRITE, m_mpiInfo->comm,\n                    0x1337, PMPIO_DefaultCreate, PMPIO_DefaultOpen,\n                    PMPIO_DefaultClose, (void*)&driver);\n        // try the fallback driver in case of error\n        if (!baton && driver != DB_PDB) {\n            driver = DB_PDB;\n            baton = PMPIO_Init(NUM_SILO_FILES, PMPIO_WRITE, m_mpiInfo->comm,\n                        0x1338, PMPIO_DefaultCreate, PMPIO_DefaultOpen,\n                        PMPIO_DefaultClose, (void*)&driver);\n        }\n        if (baton) {\n            char siloPath[64];\n            snprintf(siloPath, 64, blockDirFmt, PMPIO_RankInGroup(baton, m_mpiInfo->rank));\n            dbfile = (DBfile*) PMPIO_WaitForBaton(baton, fn.c_str(), siloPath);\n        }\n#endif\n    } else {\n        dbfile = DBCreate(fn.c_str(), DB_CLOBBER, DB_LOCAL,\n                getDescription().c_str(), driver);\n        // try the fallback driver in case of error\n        if (!dbfile && driver != DB_PDB) {\n            driver = DB_PDB;\n            dbfile = DBCreate(fn.c_str(), DB_CLOBBER, DB_LOCAL,\n                    getDescription().c_str(), driver);\n        }\n        char siloPath[64];\n        snprintf(siloPath, 64, blockDirFmt, 0);\n        DBMkDir(dbfile, siloPath);\n        DBSetDir(dbfile, siloPath);\n    }\n\n    if (!dbfile)\n        throw IOError(\"dump: Could not create Silo file\");\n\n    /*\n    if (driver==DB_HDF5) {\n        // gzip level 1 already provides good compression with minimal\n        // performance penalty. Some tests showed that gzip levels >3 performed\n        // rather badly on escript data both in terms of time and space\n        DBSetCompression(\"ERRMODE=FALLBACK METHOD=GZIP LEVEL=1\");\n    }\n    */\n\n    const dim_t NN0 = m_NN[0];\n    const dim_t NN1 = m_NN[1];\n    boost::scoped_ptr<double> x(new double[NN0]);\n    boost::scoped_ptr<double> y(new double[NN1]);\n    double* coords[2] = { x.get(), y.get() };\n#pragma omp parallel\n    {\n#pragma omp for nowait\n        for (dim_t i0 = 0; i0 < NN0; i0++) {\n            coords[0][i0]=getLocalCoordinate(i0, 0);\n        }\n#pragma omp for nowait\n        for (dim_t i1 = 0; i1 < NN1; i1++) {\n            coords[1][i1]=getLocalCoordinate(i1, 1);\n        }\n    }\n\n    // casting to int!!\n    vector<int> dims(m_NN, m_NN+2);\n\n    // write mesh\n    DBPutQuadmesh(dbfile, \"mesh\", NULL, coords, &dims[0], 2, DB_DOUBLE,\n            DB_COLLINEAR, NULL);\n\n    // write node ids\n    DBPutQuadvar1(dbfile, \"nodeId\", \"mesh\", (void*)&m_nodeId[0], &dims[0], 2,\n            NULL, 0, DB_INT, DB_NODECENT, NULL);\n\n    // write element ids\n    dims.assign(m_NE, m_NE+2);\n    DBPutQuadvar1(dbfile, \"elementId\", \"mesh\", (void*)&m_elementId[0],\n            &dims[0], 2, NULL, 0, DB_INT, DB_ZONECENT, NULL);\n\n    // rank 0 writes multimesh and multivar\n    if (m_mpiInfo->rank == 0) {\n        vector<string> tempstrings;\n        vector<char*> names;\n        for (dim_t i=0; i<m_mpiInfo->size; i++) {\n            std::stringstream path;\n            path << \"/block\" << std::setw(4) << std::setfill('0') << std::right << i << \"/mesh\";\n            tempstrings.push_back(path.str());\n            names.push_back((char*)tempstrings.back().c_str());\n        }\n        vector<int> types(m_mpiInfo->size, DB_QUAD_RECT);\n        DBSetDir(dbfile, \"/\");\n        DBPutMultimesh(dbfile, \"multimesh\", m_mpiInfo->size, &names[0],\n               &types[0], NULL);\n        tempstrings.clear();\n        names.clear();\n        for (dim_t i=0; i<m_mpiInfo->size; i++) {\n            std::stringstream path;\n            path << \"/block\" << std::setw(4) << std::setfill('0') << std::right << i << \"/nodeId\";\n            tempstrings.push_back(path.str());\n            names.push_back((char*)tempstrings.back().c_str());\n        }\n        types.assign(m_mpiInfo->size, DB_QUADVAR);\n        DBPutMultivar(dbfile, \"nodeId\", m_mpiInfo->size, &names[0],\n               &types[0], NULL);\n        tempstrings.clear();\n        names.clear();\n        for (dim_t i=0; i<m_mpiInfo->size; i++) {\n            std::stringstream path;\n            path << \"/block\" << std::setw(4) << std::setfill('0') << std::right << i << \"/elementId\";\n            tempstrings.push_back(path.str());\n            names.push_back((char*)tempstrings.back().c_str());\n        }\n        DBPutMultivar(dbfile, \"elementId\", m_mpiInfo->size, &names[0],\n               &types[0], NULL);\n    }\n\n    if (m_mpiInfo->size > 1) {\n#ifdef ESYS_MPI\n        PMPIO_HandOffBaton(baton, dbfile);\n        PMPIO_Finish(baton);\n#endif\n    } else {\n        DBClose(dbfile);\n    }\n\n#else // ESYS_HAVE_SILO\n    throw RipleyException(\"dump: no Silo support\");\n#endif\n}\n\nconst dim_t* Rectangle::borrowSampleReferenceIDs(int fsType) const\n{\n    switch (fsType) {\n        case Nodes:\n        case ReducedNodes: // FIXME: reduced\n            return &m_nodeId[0];\n        case DegreesOfFreedom:\n        case ReducedDegreesOfFreedom: // FIXME: reduced\n            return &m_dofId[0];\n        case Elements:\n        case ReducedElements:\n            return &m_elementId[0];\n        case FaceElements:\n        case ReducedFaceElements:\n            return &m_faceId[0];\n        case Points:\n            return &m_diracPointNodeIDs[0];\n        default:\n            break;\n    }\n\n    std::stringstream msg;\n    msg << \"borrowSampleReferenceIDs: invalid function space type \" << fsType;\n    throw ValueError(msg.str());\n}\n\nbool Rectangle::ownSample(int fsType, index_t id) const\n{\n    if (getMPISize()==1)\n        return true;\n\n    switch (fsType) {\n        case Nodes:\n        case ReducedNodes: // FIXME: reduced\n            return (m_dofMap[id] < getNumDOF());\n        case DegreesOfFreedom:\n        case ReducedDegreesOfFreedom:\n            return true;\n        case Elements:\n        case ReducedElements:\n            // check ownership of element's bottom left node\n            return (m_dofMap[id%m_NE[0]+m_NN[0]*(id/m_NE[0])] < getNumDOF());\n        case FaceElements:\n        case ReducedFaceElements:\n            {\n                // determine which face the sample belongs to before\n                // checking ownership of corresponding element's first node\n                dim_t n=0;\n                for (size_t i=0; i<4; i++) {\n                    n+=m_faceCount[i];\n                    if (id<n) {\n                        index_t k;\n                        if (i==1)\n                            k=m_NN[0]-2;\n                        else if (i==3)\n                            k=m_NN[0]*(m_NN[1]-2);\n                        else\n                            k=0;\n                        // determine whether to move right or up\n                        const index_t delta=(i/2==0 ? m_NN[0] : 1);\n                        return (m_dofMap[k+(id-n+m_faceCount[i])*delta] < getNumDOF());\n                    }\n                }\n                return false;\n            }\n        default:\n            break;\n    }\n\n    std::stringstream msg;\n    msg << \"ownSample: invalid function space type \" << fsType;\n    throw ValueError(msg.str());\n}\n\nRankVector Rectangle::getOwnerVector(int fsType) const\n{\n    RankVector owner;\n    const int rank = m_mpiInfo->rank;\n\n    if (fsType == Elements || fsType == ReducedElements) {\n        owner.assign(getNumElements(), rank);\n        if (m_faceCount[0] == 0) {\n            owner[0]=(m_faceCount[2]==0 ? rank-m_NX[0]-1 : rank-1);\n            for (dim_t i=1; i<m_NE[1]; i++)\n                owner[i*m_NE[0]] = rank-1;\n        }\n        if (m_faceCount[2]==0) {\n            const int first=(m_faceCount[0]==0 ? 1 : 0);\n            for (dim_t i=first; i<m_NE[0]; i++)\n                owner[i] = rank-m_NX[0];\n        }\n\n    } else if (fsType == FaceElements || fsType == ReducedFaceElements) {\n        owner.assign(getNumFaceElements(), rank);\n        if (m_faceCount[0] == 0) {\n            if (m_faceCount[2] > 0)\n                owner[m_faceCount[1]] = rank-1;\n            if (m_faceCount[3] > 0)\n                owner[m_faceCount[1]+m_faceCount[2]] = rank-1;\n        }\n        if (m_faceCount[2] == 0) {\n            if (m_faceCount[0] > 0)\n                owner[0] = rank-m_NX[0];\n            if (m_faceCount[1] > 0)\n                owner[m_faceCount[0]] = rank-m_NX[0];\n        }\n\n    } else {\n        throw ValueError(\"getOwnerVector: only valid for element types\");\n    }\n\n    return owner;\n}\n\nvoid Rectangle::setToNormal(escript::Data& out) const\n{\n    const dim_t NE0=m_NE[0];\n    const dim_t NE1=m_NE[1];\n    if (out.getFunctionSpace().getTypeCode() == FaceElements) {\n        out.requireWrite();\n#pragma omp parallel\n        {\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    double* o = out.getSampleDataRW(m_faceOffset[0]+k1);\n                    // set vector at two quadrature points\n                    *o++ = -1.;\n                    *o++ = 0.;\n                    *o++ = -1.;\n                    *o = 0.;\n                }\n            }\n\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    double* o = out.getSampleDataRW(m_faceOffset[1]+k1);\n                    // set vector at two quadrature points\n                    *o++ = 1.;\n                    *o++ = 0.;\n                    *o++ = 1.;\n                    *o = 0.;\n                }\n            }\n\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    double* o = out.getSampleDataRW(m_faceOffset[2]+k0);\n                    // set vector at two quadrature points\n                    *o++ = 0.;\n                    *o++ = -1.;\n                    *o++ = 0.;\n                    *o = -1.;\n                }\n            }\n\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    double* o = out.getSampleDataRW(m_faceOffset[3]+k0);\n                    // set vector at two quadrature points\n                    *o++ = 0.;\n                    *o++ = 1.;\n                    *o++ = 0.;\n                    *o = 1.;\n                }\n            }\n        } // end of parallel section\n    } else if (out.getFunctionSpace().getTypeCode() == ReducedFaceElements) {\n        out.requireWrite();\n#pragma omp parallel\n        {\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    double* o = out.getSampleDataRW(m_faceOffset[0]+k1);\n                    *o++ = -1.;\n                    *o = 0.;\n                }\n            }\n\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    double* o = out.getSampleDataRW(m_faceOffset[1]+k1);\n                    *o++ = 1.;\n                    *o = 0.;\n                }\n            }\n\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    double* o = out.getSampleDataRW(m_faceOffset[2]+k0);\n                    *o++ = 0.;\n                    *o = -1.;\n                }\n            }\n\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    double* o = out.getSampleDataRW(m_faceOffset[3]+k0);\n                    *o++ = 0.;\n                    *o = 1.;\n                }\n            }\n        } // end of parallel section\n\n    } else {\n        std::stringstream msg;\n        msg << \"setToNormal: invalid function space type \"\n            << out.getFunctionSpace().getTypeCode();\n        throw ValueError(msg.str());\n    }\n}\n\nvoid Rectangle::setToSize(escript::Data& out) const\n{\n    if (out.getFunctionSpace().getTypeCode() == Elements\n            || out.getFunctionSpace().getTypeCode() == ReducedElements) {\n        out.requireWrite();\n        const dim_t numQuad = out.getNumDataPointsPerSample();\n        const dim_t numElements = getNumElements();\n        const double size=sqrt(m_dx[0]*m_dx[0]+m_dx[1]*m_dx[1]);\n#pragma omp parallel for\n        for (index_t k = 0; k < numElements; ++k) {\n            double* o = out.getSampleDataRW(k);\n            fill(o, o+numQuad, size);\n        }\n    } else if (out.getFunctionSpace().getTypeCode() == FaceElements\n            || out.getFunctionSpace().getTypeCode() == ReducedFaceElements) {\n        out.requireWrite();\n        const dim_t numQuad=out.getNumDataPointsPerSample();\n        const dim_t NE0 = m_NE[0];\n        const dim_t NE1 = m_NE[1];\n#pragma omp parallel\n        {\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    double* o = out.getSampleDataRW(m_faceOffset[0]+k1);\n                    fill(o, o+numQuad, m_dx[1]);\n                }\n            }\n\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    double* o = out.getSampleDataRW(m_faceOffset[1]+k1);\n                    fill(o, o+numQuad, m_dx[1]);\n                }\n            }\n\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    double* o = out.getSampleDataRW(m_faceOffset[2]+k0);\n                    fill(o, o+numQuad, m_dx[0]);\n                }\n            }\n\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    double* o = out.getSampleDataRW(m_faceOffset[3]+k0);\n                    fill(o, o+numQuad, m_dx[0]);\n                }\n            }\n        } // end of parallel section\n\n    } else {\n        std::stringstream msg;\n        msg << \"setToSize: invalid function space type \"\n            << out.getFunctionSpace().getTypeCode();\n        throw ValueError(msg.str());\n    }\n}\n\nvoid Rectangle::Print_Mesh_Info(const bool full) const\n{\n    RipleyDomain::Print_Mesh_Info(full);\n    if (full) {\n        std::cout << \"     Id  Coordinates\" << std::endl;\n        std::cout.precision(15);\n        std::cout.setf(ios::scientific, ios::floatfield);\n        for (index_t i=0; i < getNumNodes(); i++) {\n            std::cout << \"  \" << std::setw(5) << m_nodeId[i]\n                << \"  \" << getLocalCoordinate(i%m_NN[0], 0)\n                << \"  \" << getLocalCoordinate(i/m_NN[0], 1) << std::endl;\n        }\n    }\n}\n\n\n//protected\nvoid Rectangle::assembleCoordinates(escript::Data& arg) const\n{\n    int numDim = m_numDim;\n    if (!arg.isDataPointShapeEqual(1, &numDim))\n        throw ValueError(\"setToX: Invalid Data object shape\");\n    if (!arg.numSamplesEqual(1, getNumNodes()))\n        throw ValueError(\"setToX: Illegal number of samples in Data object\");\n\n    const dim_t NN0 = m_NN[0];\n    const dim_t NN1 = m_NN[1];\n    arg.requireWrite();\n#pragma omp parallel for\n    for (dim_t i1 = 0; i1 < NN1; i1++) {\n        for (dim_t i0 = 0; i0 < NN0; i0++) {\n            double* point = arg.getSampleDataRW(i0+NN0*i1);\n            point[0] = getLocalCoordinate(i0, 0);\n            point[1] = getLocalCoordinate(i1, 1);\n        }\n    }\n}\n\n//protected\nvoid Rectangle::assembleGradient(escript::Data& out,\n                                 const escript::Data& in) const\n{\n    if (out.isComplex() && in.isComplex())\n        assembleGradientImpl<cplx_t>(out, in);\n    else if (!out.isComplex() && !in.isComplex())\n        assembleGradientImpl<real_t>(out, in);\n    else\n        throw ValueError(\"Gradient: input & output complexity must match.\");\n}\n\n//protected\ntemplate<typename Scalar>\nvoid Rectangle::assembleGradientImpl(escript::Data& out,\n                                     const escript::Data& in) const\n{\n    const dim_t numComp = in.getDataPointSize();\n    const dim_t NE0 = m_NE[0];\n    const dim_t NE1 = m_NE[1];\n    const double cx0 = .21132486540518711775/m_dx[0];\n    const double cx1 = .78867513459481288225/m_dx[0];\n    const double cx2 = 1./m_dx[0];\n    const double cy0 = .21132486540518711775/m_dx[1];\n    const double cy1 = .78867513459481288225/m_dx[1];\n    const double cy2 = 1./m_dx[1];\n    const Scalar zero = static_cast<Scalar>(0);\n\n    if (out.getFunctionSpace().getTypeCode() == Elements) {\n        out.requireWrite();\n#pragma omp parallel\n        {\n            vector<Scalar> f_00(numComp, zero);\n            vector<Scalar> f_01(numComp, zero);\n            vector<Scalar> f_10(numComp, zero);\n            vector<Scalar> f_11(numComp, zero);\n#pragma omp for\n            for (index_t k1 = 0; k1 < NE1; ++k1) {\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(INDEX2(k0,k1,m_NE[0]), zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i]-f_00[i])*cx1 + (f_11[i]-f_01[i])*cx0;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i]-f_00[i])*cy1 + (f_11[i]-f_10[i])*cy0;\n                        o[INDEX3(i,0,1,numComp,2)] = (f_10[i]-f_00[i])*cx1 + (f_11[i]-f_01[i])*cx0;\n                        o[INDEX3(i,1,1,numComp,2)] = (f_01[i]-f_00[i])*cy0 + (f_11[i]-f_10[i])*cy1;\n                        o[INDEX3(i,0,2,numComp,2)] = (f_10[i]-f_00[i])*cx0 + (f_11[i]-f_01[i])*cx1;\n                        o[INDEX3(i,1,2,numComp,2)] = (f_01[i]-f_00[i])*cy1 + (f_11[i]-f_10[i])*cy0;\n                        o[INDEX3(i,0,3,numComp,2)] = (f_10[i]-f_00[i])*cx0 + (f_11[i]-f_01[i])*cx1;\n                        o[INDEX3(i,1,3,numComp,2)] = (f_01[i]-f_00[i])*cy0 + (f_11[i]-f_10[i])*cy1;\n                    } // end of component loop i\n                } // end of k0 loop\n            } // end of k1 loop\n        } // end of parallel section\n    } else if (out.getFunctionSpace().getTypeCode() == ReducedElements) {\n        out.requireWrite();\n#pragma omp parallel\n        {\n            vector<Scalar> f_00(numComp, zero);\n            vector<Scalar> f_01(numComp, zero);\n            vector<Scalar> f_10(numComp, zero);\n            vector<Scalar> f_11(numComp, zero);\n#pragma omp for\n            for (index_t k1 = 0; k1 < NE1; ++k1) {\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(INDEX2(k0,k1,m_NE[0]), zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i] + f_11[i] - f_00[i] - f_01[i])*cx2 * 0.5;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i] + f_11[i] - f_00[i] - f_10[i])*cy2 * 0.5;\n                    } // end of component loop i\n                } // end of k0 loop\n            } // end of k1 loop\n        } // end of parallel section\n    } else if (out.getFunctionSpace().getTypeCode() == FaceElements) {\n        out.requireWrite();\n#pragma omp parallel\n        {\n            vector<Scalar> f_00(numComp, zero);\n            vector<Scalar> f_01(numComp, zero);\n            vector<Scalar> f_10(numComp, zero);\n            vector<Scalar> f_11(numComp, zero);\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(0,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(0,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(1,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(1,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[0]+k1, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i]-f_00[i])*cx1 + (f_11[i]-f_01[i])*cx0;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i]-f_00[i])*cy2;\n                        o[INDEX3(i,0,1,numComp,2)] = (f_10[i]-f_00[i])*cx0 + (f_11[i]-f_01[i])*cx1;\n                        o[INDEX3(i,1,1,numComp,2)] = (f_01[i]-f_00[i])*cy2;\n                    } // end of component loop i\n                } // end of k1 loop\n            } // end of face 0\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(m_NN[0]-2,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(m_NN[0]-2,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[1]+k1, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i]-f_00[i])*cx1 + (f_11[i]-f_01[i])*cx0;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_11[i]-f_10[i])*cy2;\n                        o[INDEX3(i,0,1,numComp,2)] = (f_10[i]-f_00[i])*cx0 + (f_11[i]-f_01[i])*cx1;\n                        o[INDEX3(i,1,1,numComp,2)] = (f_11[i]-f_10[i])*cy2;\n                    } // end of component loop i\n                } // end of k1 loop\n            } // end of face 1\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,0, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,0, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[2]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i]-f_00[i])*cx2;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i]-f_00[i])*cy1 + (f_11[i]-f_10[i])*cy0;\n                        o[INDEX3(i,0,1,numComp,2)] = (f_10[i]-f_00[i])*cx2;\n                        o[INDEX3(i,1,1,numComp,2)] = (f_01[i]-f_00[i])*cy0 + (f_11[i]-f_10[i])*cy1;\n                    } // end of component loop i\n                } // end of k0 loop\n            } // end of face 2\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,m_NN[1]-2, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,m_NN[1]-1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,m_NN[1]-2, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,m_NN[1]-1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[3]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_11[i]-f_01[i])*cx2;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i]-f_00[i])*cy1 + (f_11[i]-f_10[i])*cy0;\n                        o[INDEX3(i,0,1,numComp,2)] = (f_11[i]-f_01[i])*cx2;\n                        o[INDEX3(i,1,1,numComp,2)] = (f_01[i]-f_00[i])*cy0 + (f_11[i]-f_10[i])*cy1;\n                    } // end of component loop i\n                } // end of k0 loop\n            } // end of face 3\n        } // end of parallel section\n\n    } else if (out.getFunctionSpace().getTypeCode() == ReducedFaceElements) {\n        out.requireWrite();\n#pragma omp parallel\n        {\n            vector<Scalar> f_00(numComp, zero);\n            vector<Scalar> f_01(numComp, zero);\n            vector<Scalar> f_10(numComp, zero);\n            vector<Scalar> f_11(numComp, zero);\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(0,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(0,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(1,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(1,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[0]+k1, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i] + f_11[i] - f_00[i] - f_01[i])*cx2 * 0.5;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i]-f_00[i])*cy2;\n                    } // end of component loop i\n                } // end of k1 loop\n            } // end of face 0\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = 0; k1 < NE1; ++k1) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(m_NN[0]-2,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(m_NN[0]-2,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1+1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[1]+k1, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i] + f_11[i] - f_00[i] - f_01[i])*cx2 * 0.5;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_11[i]-f_10[i])*cy2;\n                    } // end of component loop i\n                } // end of k1 loop\n            } // end of face 1\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,0, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,0, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[2]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_10[i]-f_00[i])*cx2;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i] + f_11[i] - f_00[i] - f_10[i])*cy2 * 0.5;\n                    } // end of component loop i\n                } // end of k0 loop\n            } // end of face 2\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = 0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,m_NN[1]-2, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,m_NN[1]-1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,m_NN[1]-2, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,m_NN[1]-1, m_NN[0]), zero), numComp*sizeof(Scalar));\n                    Scalar* o = out.getSampleDataRW(m_faceOffset[3]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        o[INDEX3(i,0,0,numComp,2)] = (f_11[i]-f_01[i])*cx2;\n                        o[INDEX3(i,1,0,numComp,2)] = (f_01[i] + f_11[i] - f_00[i] - f_10[i])*cy2 * 0.5;\n                    } // end of component loop i\n                } // end of k0 loop\n            } // end of face 3\n        } // end of parallel section\n    }\n}\n\n// instantiate our two supported versions\ntemplate\nvoid Rectangle::assembleGradientImpl<real_t>(escript::Data& out,\n                                             const escript::Data& in) const;\n\ntemplate\nvoid Rectangle::assembleGradientImpl<cplx_t>(escript::Data& out,\n                                             const escript::Data& in) const;\n\n//protected\nvoid Rectangle::assembleIntegrate(vector<real_t>& integrals,\n                                  const escript::Data& arg) const\n{\n    assembleIntegrateImpl<real_t>(integrals, arg);\n}\n\n//protected\nvoid Rectangle::assembleIntegrate(vector<cplx_t>& integrals,\n                                  const escript::Data& arg) const\n{\n    assembleIntegrateImpl<cplx_t>(integrals, arg);\n}\n\n//private\ntemplate<typename Scalar>\nvoid Rectangle::assembleIntegrateImpl(vector<Scalar>& integrals,\n                                      const escript::Data& arg) const\n{\n    const dim_t numComp = arg.getDataPointSize();\n    const index_t left = getFirstInDim(0);\n    const index_t bottom = getFirstInDim(1);\n    const int fs = arg.getFunctionSpace().getTypeCode();\n    const Scalar zero = static_cast<Scalar>(0);\n\n    if (fs == Elements && arg.actsExpanded()) {\n#pragma omp parallel\n        {\n            vector<Scalar> int_local(numComp, zero);\n            const real_t w = m_dx[0]*m_dx[1]/4.;\n#pragma omp for nowait\n            for (index_t k1 = bottom; k1 < bottom+m_ownNE[1]; ++k1) {\n                for (index_t k0 = left; k0 < left+m_ownNE[0]; ++k0) {\n                    const Scalar* f = arg.getSampleDataRO(INDEX2(k0, k1, m_NE[0]), zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        const Scalar f0 = f[INDEX2(i,0,numComp)];\n                        const Scalar f1 = f[INDEX2(i,1,numComp)];\n                        const Scalar f2 = f[INDEX2(i,2,numComp)];\n                        const Scalar f3 = f[INDEX2(i,3,numComp)];\n                        int_local[i] += (f0+f1+f2+f3)*w;\n                    }  // end of component loop i\n                } // end of k0 loop\n            } // end of k1 loop\n#pragma omp critical\n            for (index_t i=0; i<numComp; i++)\n                integrals[i] += int_local[i];\n        } // end of parallel section\n\n    } else if (fs==ReducedElements || (fs==Elements && !arg.actsExpanded())) {\n        const real_t w = m_dx[0]*m_dx[1];\n#pragma omp parallel\n        {\n            vector<Scalar> int_local(numComp, 0);\n#pragma omp for nowait\n            for (index_t k1 = bottom; k1 < bottom+m_ownNE[1]; ++k1) {\n                for (index_t k0 = left; k0 < left+m_ownNE[0]; ++k0) {\n                    const Scalar* f = arg.getSampleDataRO(INDEX2(k0, k1, m_NE[0]), zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        int_local[i] += f[i]*w;\n                    }\n                }\n            }\n#pragma omp critical\n            for (index_t i = 0; i < numComp; i++)\n                integrals[i] += int_local[i];\n        } // end of parallel section\n\n    } else if (fs == FaceElements && arg.actsExpanded()) {\n#pragma omp parallel\n        {\n            vector<Scalar> int_local(numComp, zero);\n            const real_t w0 = m_dx[0]/2.;\n            const real_t w1 = m_dx[1]/2.;\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = bottom; k1 < bottom+m_ownNE[1]; ++k1) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[0]+k1, zero);\n                    for (index_t i=0; i < numComp; ++i) {\n                        const Scalar f0 = f[INDEX2(i,0,numComp)];\n                        const Scalar f1 = f[INDEX2(i,1,numComp)];\n                        int_local[i] += (f0+f1)*w1;\n                    }  // end of component loop i\n                } // end of k1 loop\n            }\n\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = bottom; k1 < bottom+m_ownNE[1]; ++k1) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[1]+k1, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        const Scalar f0 = f[INDEX2(i,0,numComp)];\n                        const Scalar f1 = f[INDEX2(i,1,numComp)];\n                        int_local[i] += (f0+f1)*w1;\n                    }  // end of component loop i\n                } // end of k1 loop\n            }\n\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = left; k0 < left+m_ownNE[0]; ++k0) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[2]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        const Scalar f0 = f[INDEX2(i,0,numComp)];\n                        const Scalar f1 = f[INDEX2(i,1,numComp)];\n                        int_local[i] += (f0+f1)*w0;\n                    }  // end of component loop i\n                } // end of k0 loop\n            }\n\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = left; k0 < left+m_ownNE[0]; ++k0) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[3]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        const Scalar f0 = f[INDEX2(i,0,numComp)];\n                        const Scalar f1 = f[INDEX2(i,1,numComp)];\n                        int_local[i] += (f0+f1)*w0;\n                    }  // end of component loop i\n                } // end of k0 loop\n            }\n#pragma omp critical\n            for (index_t i = 0; i < numComp; i++)\n                integrals[i] += int_local[i];\n        } // end of parallel section\n\n    } else if (fs==ReducedFaceElements || (fs==FaceElements && !arg.actsExpanded())) {\n#pragma omp parallel\n        {\n            vector<Scalar> int_local(numComp, 0);\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = bottom; k1 < bottom+m_ownNE[1]; ++k1) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[0]+k1, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        int_local[i] += f[i]*m_dx[1];\n                    }\n                }\n            }\n\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1 = bottom; k1 < bottom+m_ownNE[1]; ++k1) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[1]+k1, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        int_local[i] += f[i]*m_dx[1];\n                    }\n                }\n            }\n\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = left; k0 < left+m_ownNE[0]; ++k0) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[2]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        int_local[i] += f[i]*m_dx[0];\n                    }\n                }\n            }\n\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0 = left; k0 < left+m_ownNE[0]; ++k0) {\n                    const Scalar* f = arg.getSampleDataRO(m_faceOffset[3]+k0, zero);\n                    for (index_t i = 0; i < numComp; ++i) {\n                        int_local[i] += f[i]*m_dx[0];\n                    }\n                }\n            }\n\n#pragma omp critical\n            for (index_t i = 0; i < numComp; i++)\n                integrals[i] += int_local[i];\n        } // end of parallel section\n    } // function space selector\n}\n\n//protected\nIndexVector Rectangle::getDiagonalIndices(bool upperOnly) const\n{\n    IndexVector ret;\n    // only store non-negative indices if requested\n    if (upperOnly)\n        ret.resize(5);\n    else\n        ret.resize(9);\n    const dim_t nDOF0 = getNumDOFInAxis(0);\n    size_t idx = 0;\n    for (int i1=-1; i1<2; i1++) {\n        for (int i0=-1; i0<2; i0++) {\n            const int index = i1*nDOF0 + i0;\n            if (!upperOnly || index >= 0)\n                ret[idx++] = index;\n        }\n    }\n\n    return ret;\n}\n\n//protected\nvoid Rectangle::nodesToDOF(escript::Data& out, const escript::Data& in) const\n{\n    const dim_t numComp = in.getDataPointSize();\n    out.requireWrite();\n\n    const index_t left = getFirstInDim(0);\n    const index_t bottom = getFirstInDim(1);\n    const dim_t nDOF0 = getNumDOFInAxis(0);\n    const dim_t nDOF1 = getNumDOFInAxis(1);\n#pragma omp parallel for\n    for (index_t i=0; i<nDOF1; i++) {\n        for (index_t j=0; j<nDOF0; j++) {\n            const index_t n=j+left+(i+bottom)*m_NN[0];\n            const double* src=in.getSampleDataRO(n);\n            copy(src, src+numComp, out.getSampleDataRW(j+i*nDOF0));\n        }\n    }\n}\n\n#ifdef ESYS_HAVE_TRILINOS\n//protected\nesys_trilinos::const_TrilinosGraph_ptr Rectangle::getTrilinosGraph() const\n{\n    if (m_graph.is_null()) {\n        m_graph = createTrilinosGraph(m_dofId, m_nodeId);\n    }\n    return m_graph;\n}\n#endif\n\n#ifdef ESYS_HAVE_PASO\n//protected\npaso::SystemMatrixPattern_ptr Rectangle::getPasoMatrixPattern(\n                                                    bool reducedRowOrder,\n                                                    bool reducedColOrder) const\n{\n    if (m_pattern.get())\n        return m_pattern;\n\n    // first call - create pattern, then return\n    paso::Connector_ptr conn(getPasoConnector());\n    const dim_t numDOF = getNumDOF();\n    const dim_t numShared = conn->send->numSharedComponents;\n    const dim_t numNeighbours = conn->send->neighbour.size();\n    const std::vector<index_t>& offsetInShared(conn->send->offsetInShared);\n    const index_t* sendShared = conn->send->shared;\n\n    // these are for the couple blocks\n    vector<IndexVector> colIndices(numDOF);\n    vector<IndexVector> rowIndices(numShared);\n\n    for (dim_t i=0; i<numNeighbours; i++) {\n        const dim_t start = offsetInShared[i];\n        const dim_t end = offsetInShared[i+1];\n        for (dim_t j = start; j < end; j++) {\n            if (j > start)\n                doublyLink(colIndices, rowIndices, sendShared[j-1], j);\n            doublyLink(colIndices, rowIndices, sendShared[j], j);\n            if (j < end-1)\n                doublyLink(colIndices, rowIndices, sendShared[j+1], j);\n        }\n    }\n#pragma omp parallel for\n    for (dim_t i = 0; i < numShared; i++) {\n        sort(rowIndices[i].begin(), rowIndices[i].end());\n    }\n\n    // create main and couple blocks\n    paso::Pattern_ptr mainPattern = createPasoPattern(getConnections(), numDOF);\n    paso::Pattern_ptr colPattern = createPasoPattern(colIndices, numShared);\n    paso::Pattern_ptr rowPattern = createPasoPattern(rowIndices, numDOF);\n\n    // allocate paso distribution\n    escript::Distribution_ptr distribution(new escript::Distribution(\n                                               m_mpiInfo, m_nodeDistribution));\n\n    // finally create the system matrix pattern\n    m_pattern.reset(new paso::SystemMatrixPattern(MATRIX_FORMAT_DEFAULT,\n            distribution, distribution, mainPattern, colPattern, rowPattern,\n            conn, conn));\n    return m_pattern;\n}\n#endif // ESYS_HAVE_PASO\n\n//private\nvoid Rectangle::populateSampleIds()\n{\n    // degrees of freedom are numbered from left to right, bottom to top in\n    // each rank, continuing on the next rank (ranks also go left-right,\n    // bottom-top).\n    // This means rank 0 has id 0...n0-1, rank 1 has id n0...n1-1 etc. which\n    // helps when writing out data rank after rank.\n\n    // build node distribution vector first.\n    // rank i owns m_nodeDistribution[i+1]-nodeDistribution[i] nodes which is\n    // constant for all ranks in this implementation\n    m_nodeDistribution.assign(m_mpiInfo->size+1, 0);\n    const dim_t numDOF=getNumDOF();\n    for (dim_t k=1; k<m_mpiInfo->size; k++) {\n        m_nodeDistribution[k]=k*numDOF;\n    }\n    m_nodeDistribution[m_mpiInfo->size]=getNumDataPointsGlobal();\n    try {\n        m_nodeId.resize(getNumNodes());\n        m_dofId.resize(numDOF);\n        m_elementId.resize(getNumElements());\n    } catch (const std::length_error& le) {\n        throw RipleyException(\"The system does not have sufficient memory for a domain of this size.\");\n    }\n\n    // populate face element counts\n    //left\n    if (m_offset[0]==0)\n        m_faceCount[0]=m_NE[1];\n    else\n        m_faceCount[0]=0;\n    //right\n    if (m_mpiInfo->rank%m_NX[0]==m_NX[0]-1)\n        m_faceCount[1]=m_NE[1];\n    else\n        m_faceCount[1]=0;\n    //bottom\n    if (m_offset[1]==0)\n        m_faceCount[2]=m_NE[0];\n    else\n        m_faceCount[2]=0;\n    //top\n    if (m_mpiInfo->rank/m_NX[0]==m_NX[1]-1)\n        m_faceCount[3]=m_NE[0];\n    else\n        m_faceCount[3]=0;\n\n    const dim_t NFE = getNumFaceElements();\n    m_faceId.resize(NFE);\n\n    const index_t left = getFirstInDim(0);\n    const index_t bottom = getFirstInDim(1);\n    const dim_t nDOF0 = getNumDOFInAxis(0);\n    const dim_t nDOF1 = getNumDOFInAxis(1);\n    const dim_t NE0 = m_NE[0];\n    const dim_t NE1 = m_NE[1];\n\n#define globalNodeId(x,y) \\\n    ((m_offset[0]+x)/nDOF0)*nDOF0*nDOF1+(m_offset[0]+x)%nDOF0 \\\n    + ((m_offset[1]+y)/nDOF1)*nDOF0*nDOF1*m_NX[0]+((m_offset[1]+y)%nDOF1)*nDOF0\n\n    // set corner id's outside the parallel region\n    m_nodeId[0] = globalNodeId(0, 0);\n    m_nodeId[m_NN[0]-1] = globalNodeId(m_NN[0]-1, 0);\n    m_nodeId[m_NN[0]*(m_NN[1]-1)] = globalNodeId(0, m_NN[1]-1);\n    m_nodeId[m_NN[0]*m_NN[1]-1] = globalNodeId(m_NN[0]-1,m_NN[1]-1);\n#undef globalNodeId\n\n#pragma omp parallel\n    {\n        // populate degrees of freedom and own nodes (identical id)\n#pragma omp for nowait\n        for (dim_t i=0; i<nDOF1; i++) {\n            for (dim_t j=0; j<nDOF0; j++) {\n                const index_t nodeIdx=j+left+(i+bottom)*m_NN[0];\n                const index_t dofIdx=j+i*nDOF0;\n                m_dofId[dofIdx] = m_nodeId[nodeIdx]\n                    = m_nodeDistribution[m_mpiInfo->rank]+dofIdx;\n            }\n        }\n\n        // populate the rest of the nodes (shared with other ranks)\n        if (m_faceCount[0]==0) { // left column\n#pragma omp for nowait\n            for (dim_t i=0; i<nDOF1; i++) {\n                const index_t nodeIdx=(i+bottom)*m_NN[0];\n                const index_t dofId=(i+1)*nDOF0-1;\n                m_nodeId[nodeIdx]\n                    = m_nodeDistribution[m_mpiInfo->rank-1]+dofId;\n            }\n        }\n        if (m_faceCount[1]==0) { // right column\n#pragma omp for nowait\n            for (dim_t i=0; i<nDOF1; i++) {\n                const index_t nodeIdx=(i+bottom+1)*m_NN[0]-1;\n                const index_t dofId=i*nDOF0;\n                m_nodeId[nodeIdx]\n                    = m_nodeDistribution[m_mpiInfo->rank+1]+dofId;\n            }\n        }\n        if (m_faceCount[2]==0) { // bottom row\n#pragma omp for nowait\n            for (dim_t i=0; i<nDOF0; i++) {\n                const index_t nodeIdx=i+left;\n                const index_t dofId=nDOF0*(nDOF1-1)+i;\n                m_nodeId[nodeIdx]\n                    = m_nodeDistribution[m_mpiInfo->rank-m_NX[0]]+dofId;\n            }\n        }\n        if (m_faceCount[3]==0) { // top row\n#pragma omp for nowait\n            for (dim_t i=0; i<nDOF0; i++) {\n                const index_t nodeIdx=m_NN[0]*(m_NN[1]-1)+i+left;\n                const index_t dofId=i;\n                m_nodeId[nodeIdx]\n                    = m_nodeDistribution[m_mpiInfo->rank+m_NX[0]]+dofId;\n            }\n        }\n\n        // populate element id's\n#pragma omp for nowait\n        for (dim_t i1=0; i1<NE1; i1++) {\n            for (dim_t i0=0; i0<NE0; i0++) {\n                m_elementId[i0+i1*NE0]=(m_offset[1]+i1)*m_gNE[0]+m_offset[0]+i0;\n            }\n        }\n\n        // face elements\n#pragma omp for\n        for (dim_t k=0; k<NFE; k++)\n            m_faceId[k]=k;\n    } // end parallel section\n\n    m_nodeTags.assign(getNumNodes(), 0);\n    updateTagsInUse(Nodes);\n\n    m_elementTags.assign(getNumElements(), 0);\n    updateTagsInUse(Elements);\n\n    // generate face offset vector and set face tags\n    const index_t LEFT=1, RIGHT=2, BOTTOM=10, TOP=20;\n    const index_t faceTag[] = { LEFT, RIGHT, BOTTOM, TOP };\n    m_faceOffset.assign(4, -1);\n    m_faceTags.clear();\n    index_t offset=0;\n    for (size_t i=0; i<4; i++) {\n        if (m_faceCount[i]>0) {\n            m_faceOffset[i]=offset;\n            offset+=m_faceCount[i];\n            m_faceTags.insert(m_faceTags.end(), m_faceCount[i], faceTag[i]);\n        }\n    }\n    setTagMap(\"left\", LEFT);\n    setTagMap(\"right\", RIGHT);\n    setTagMap(\"bottom\", BOTTOM);\n    setTagMap(\"top\", TOP);\n    updateTagsInUse(FaceElements);\n\n    populateDofMap();\n}\n\n//private\nvector<IndexVector> Rectangle::getConnections(bool includeShared) const\n{\n    // returns a vector v of size numDOF where v[i] is a vector with indices\n    // of DOFs connected to i (up to 9 in 2D).\n    // In other words this method returns the occupied (local) matrix columns\n    // for all (local) matrix rows.\n    // If includeShared==true then connections to non-owned DOFs are also\n    // returned (i.e. indices of the column couplings)\n    const dim_t nDOF0 = getNumDOFInAxis(0);\n    const dim_t nDOF1 = getNumDOFInAxis(1);\n    const dim_t numMatrixRows = nDOF0*nDOF1;\n    vector<IndexVector> indices(numMatrixRows);\n\n    if (includeShared) {\n        const index_t left = getFirstInDim(0);\n        const index_t bottom = getFirstInDim(1);\n        const dim_t NN0 = m_NN[0];\n        const dim_t NN1 = m_NN[1];\n#pragma omp parallel for\n        for (index_t i=0; i < numMatrixRows; i++) {\n            const index_t x = left + i % nDOF0;\n            const index_t y = bottom + i / nDOF0;\n            // loop through potential neighbours and add to index if positions\n            // are within bounds\n            for (dim_t i1=y-1; i1<y+2; i1++) {\n                for (dim_t i0=x-1; i0<x+2; i0++) {\n                    if (i0>=0 && i1>=0 && i0<NN0 && i1<NN1) {\n                        indices[i].push_back(m_dofMap[i1*NN0 + i0]);\n                    }\n                }\n            }\n            sort(indices[i].begin(), indices[i].end());\n        }\n    } else {\n#pragma omp parallel for\n        for (index_t i=0; i < numMatrixRows; i++) {\n            const index_t x = i % nDOF0;\n            const index_t y = i / nDOF0;\n            // loop through potential neighbours and add to index if positions\n            // are within bounds\n            for (dim_t i1=y-1; i1<y+2; i1++) {\n                for (dim_t i0=x-1; i0<x+2; i0++) {\n                    if (i0>=0 && i1>=0 && i0<nDOF0 && i1<nDOF1) {\n                        indices[i].push_back(i1*nDOF0 + i0);\n                    }\n                }\n            }\n        }\n    }\n    return indices;\n}\n\n//private\nvoid Rectangle::populateDofMap()\n{\n    const dim_t nDOF0 = getNumDOFInAxis(0);\n    const dim_t nDOF1 = getNumDOFInAxis(1);\n    const index_t left = getFirstInDim(0);\n    const index_t bottom = getFirstInDim(1);\n\n    // populate node->DOF mapping with own degrees of freedom.\n    // The rest is assigned in the loop further down\n    m_dofMap.assign(getNumNodes(), 0);\n#pragma omp parallel for\n    for (index_t i=bottom; i<bottom+nDOF1; i++) {\n        for (index_t j=left; j<left+nDOF0; j++) {\n            m_dofMap[i*m_NN[0]+j]=(i-bottom)*nDOF0+j-left;\n        }\n    }\n\n    // build list of shared components and neighbours by looping through\n    // all potential neighbouring ranks and checking if positions are\n    // within bounds\n    const dim_t numDOF=nDOF0*nDOF1;\n    RankVector neighbour;\n    IndexVector offsetInShared(1,0);\n    IndexVector sendShared, recvShared;\n    const int x=m_mpiInfo->rank%m_NX[0];\n    const int y=m_mpiInfo->rank/m_NX[0];\n    // numShared will contain the number of shared DOFs after the following\n    // blocks\n    dim_t numShared=0;\n    // sharing bottom edge\n    if (y > 0) {\n        neighbour.push_back((y-1)*m_NX[0] + x);\n        const dim_t num = nDOF0;\n        offsetInShared.push_back(offsetInShared.back()+num);\n        for (dim_t i=0; i<num; i++, numShared++) {\n            sendShared.push_back(i);\n            recvShared.push_back(numDOF+numShared);\n            m_dofMap[left+i]=numDOF+numShared;\n        }\n    }\n    // sharing top edge\n    if (y < m_NX[1] - 1) {\n        neighbour.push_back((y+1)*m_NX[0] + x);\n        const dim_t num = nDOF0;\n        offsetInShared.push_back(offsetInShared.back()+num);\n        for (dim_t i=0; i<num; i++, numShared++) {\n            sendShared.push_back(numDOF-num+i);\n            recvShared.push_back(numDOF+numShared);\n            m_dofMap[m_NN[0]*(m_NN[1]-1)+left+i]=numDOF+numShared;\n        }\n    }\n    // sharing left edge\n    if (x > 0) {\n        neighbour.push_back(y*m_NX[0] + x-1);\n        const dim_t num = nDOF1;\n        offsetInShared.push_back(offsetInShared.back()+num);\n        for (dim_t i=0; i<num; i++, numShared++) {\n            sendShared.push_back(i*nDOF0);\n            recvShared.push_back(numDOF+numShared);\n            m_dofMap[(bottom+i)*m_NN[0]]=numDOF+numShared;\n        }\n    }\n    // sharing right edge\n    if (x < m_NX[0] - 1) {\n        neighbour.push_back(y*m_NX[0] + x+1);\n        const dim_t num = nDOF1;\n        offsetInShared.push_back(offsetInShared.back()+num);\n        for (dim_t i=0; i<num; i++, numShared++) {\n            sendShared.push_back((i+1)*nDOF0-1);\n            recvShared.push_back(numDOF+numShared);\n            m_dofMap[(bottom+1+i)*m_NN[0]-1]=numDOF+numShared;\n        }\n    }\n    // sharing bottom-left node\n    if (x > 0 && y > 0) {\n        neighbour.push_back((y-1)*m_NX[0] + x-1);\n        // sharing a node\n        offsetInShared.push_back(offsetInShared.back()+1);\n        sendShared.push_back(0);\n        recvShared.push_back(numDOF+numShared);\n        m_dofMap[0]=numDOF+numShared;\n        ++numShared;\n    }\n    // sharing top-left node\n    if (x > 0 && y < m_NX[1]-1) {\n        neighbour.push_back((y+1)*m_NX[0] + x-1);\n        offsetInShared.push_back(offsetInShared.back()+1);\n        sendShared.push_back(numDOF-nDOF0);\n        recvShared.push_back(numDOF+numShared);\n        m_dofMap[m_NN[0]*(m_NN[1]-1)]=numDOF+numShared;\n        ++numShared;\n    }\n    // sharing bottom-right node\n    if (x < m_NX[0]-1 && y > 0) {\n        neighbour.push_back((y-1)*m_NX[0] + x+1);\n        offsetInShared.push_back(offsetInShared.back()+1);\n        sendShared.push_back(nDOF0-1);\n        recvShared.push_back(numDOF+numShared);\n        m_dofMap[m_NN[0]-1]=numDOF+numShared;\n        ++numShared;\n    }\n    // sharing top-right node\n    if (x < m_NX[0]-1 && y < m_NX[1]-1) {\n        neighbour.push_back((y+1)*m_NX[0] + x+1);\n        offsetInShared.push_back(offsetInShared.back()+1);\n        sendShared.push_back(numDOF-1);\n        recvShared.push_back(numDOF+numShared);\n        m_dofMap[m_NN[0]*m_NN[1]-1]=numDOF+numShared;\n        ++numShared;\n    }\n\n#ifdef ESYS_HAVE_PASO\n    createPasoConnector(neighbour, offsetInShared, offsetInShared, sendShared,\n                        recvShared);\n#endif\n\n    // useful debug output\n    /*\n    std::cout << \"--- rcv_shcomp ---\" << std::endl;\n    std::cout << \"numDOF=\" << numDOF << \", numNeighbors=\" << neighbour.size() << std::endl;\n    for (size_t i=0; i<neighbour.size(); i++) {\n        std::cout << \"neighbor[\" << i << \"]=\" << neighbour[i]\n            << \" offsetInShared[\" << i+1 << \"]=\" << offsetInShared[i+1] << std::endl;\n    }\n    for (size_t i=0; i<recvShared.size(); i++) {\n        std::cout << \"shared[\" << i << \"]=\" << recvShared[i] << std::endl;\n    }\n    std::cout << \"--- snd_shcomp ---\" << std::endl;\n    for (size_t i=0; i<sendShared.size(); i++) {\n        std::cout << \"shared[\" << i << \"]=\" << sendShared[i] << std::endl;\n    }\n    std::cout << \"--- dofMap ---\" << std::endl;\n    for (size_t i=0; i<m_dofMap.size(); i++) {\n        std::cout << \"m_dofMap[\" << i << \"]=\" << m_dofMap[i] << std::endl;\n    }\n    */\n}\n\n//private\ntemplate<typename Scalar>\nvoid Rectangle::addToMatrixAndRHS(AbstractSystemMatrix* S, escript::Data& F,\n         const vector<Scalar>& EM_S, const vector<Scalar>& EM_F, bool addS,\n         bool addF, index_t firstNode, int nEq, int nComp) const\n{\n    IndexVector rowIndex(4);\n    rowIndex[0] = m_dofMap[firstNode];\n    rowIndex[1] = m_dofMap[firstNode+1];\n    rowIndex[2] = m_dofMap[firstNode+m_NN[0]];\n    rowIndex[3] = m_dofMap[firstNode+m_NN[0]+1];\n    if (addF) {\n        Scalar* F_p = F.getSampleDataRW(0, static_cast<Scalar>(0));\n        for (index_t i=0; i<rowIndex.size(); i++) {\n            if (rowIndex[i]<getNumDOF()) {\n                for (int eq=0; eq<nEq; eq++) {\n                    F_p[INDEX2(eq, rowIndex[i], nEq)]+=EM_F[INDEX2(eq,i,nEq)];\n                }\n            }\n        }\n    }\n    if (addS) {\n        addToSystemMatrix<Scalar>(S, rowIndex, nEq, EM_S);\n    }\n}\n\ntemplate\nvoid Rectangle::addToMatrixAndRHS<real_t>(AbstractSystemMatrix* S, escript::Data& F,\n         const vector<real_t>& EM_S, const vector<real_t>& EM_F, bool addS,\n         bool addF, index_t firstNode, int nEq, int nComp) const;\n\ntemplate\nvoid Rectangle::addToMatrixAndRHS<cplx_t>(AbstractSystemMatrix* S, escript::Data& F,\n         const vector<cplx_t>& EM_S, const vector<cplx_t>& EM_F, bool addS,\n         bool addF, index_t firstNode, int nEq, int nComp) const;\n\n//protected\nvoid Rectangle::interpolateNodesOnElements(escript::Data& out,\n                                           const escript::Data& in,\n                                           bool reduced) const\n{\n    if (in.isComplex()!=out.isComplex())\n    {\n        throw RipleyException(\"Programmer Error: in and out parameters do not have the same complexity.\");\n    }\n    if (in.isComplex())\n    {\n        interpolateNodesOnElementsWorker(out, in, reduced, escript::DataTypes::cplx_t(0));\n    }\n    else\n    {\n        interpolateNodesOnElementsWorker(out, in, reduced, escript::DataTypes::real_t(0));      \n    }\n}\n\n//protected\nvoid Rectangle::interpolateNodesOnFaces(escript::Data& out,\n                                           const escript::Data& in,\n                                           bool reduced) const\n{\n    if (in.isComplex()!=out.isComplex())\n    {\n        throw RipleyException(\"Programmer Error: in and out parameters do not have the same complexity.\");\n    }\n    if (in.isComplex())\n    {\n        interpolateNodesOnFacesWorker(out, in, reduced, escript::DataTypes::cplx_t(0));\n    }\n    else\n    {\n        interpolateNodesOnFacesWorker(out, in, reduced, escript::DataTypes::real_t(0));      \n    }\n}\n\n// private\t \ntemplate <typename S> \nvoid Rectangle::interpolateNodesOnElementsWorker(escript::Data& out,\n                                           const escript::Data& in,\n                                           bool reduced, S sentinel) const\n{\n    const dim_t numComp = in.getDataPointSize();\n    const dim_t NE0 = m_NE[0];\n    const dim_t NE1 = m_NE[1];\n    if (reduced) {\n        out.requireWrite();\n        const S c0 = 0.25;\n#pragma omp parallel\n        {\n            vector<S> f_00(numComp);\n            vector<S> f_01(numComp);\n            vector<S> f_10(numComp);\n            vector<S> f_11(numComp);\n#pragma omp for\n            for (index_t k1=0; k1 < NE1; ++k1) {\n                for (index_t k0=0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(INDEX2(k0,k1,m_NE[0]), sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = c0*(f_00[i] + f_01[i] + f_10[i] + f_11[i]);\n                    } /* end of component loop i */\n                } /* end of k0 loop */\n            } /* end of k1 loop */\n        } /* end of parallel section */\n    } else {\n        out.requireWrite();\n        const S c0 = 0.16666666666666666667;\n        const S c1 = 0.044658198738520451079;\n        const S c2 = 0.62200846792814621559;\n#pragma omp parallel\n        {\n            vector<S> f_00(numComp);\n            vector<S> f_01(numComp);\n            vector<S> f_10(numComp);\n            vector<S> f_11(numComp);\n#pragma omp for\n            for (index_t k1=0; k1 < NE1; ++k1) {\n                for (index_t k0=0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(INDEX2(k0,k1,m_NE[0]), sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = c0*(f_01[i] + f_10[i]) + c1*f_11[i] + c2*f_00[i];\n                        o[INDEX2(i,numComp,1)] = c0*(f_00[i] + f_11[i]) + c1*f_01[i] + c2*f_10[i];\n                        o[INDEX2(i,numComp,2)] = c0*(f_00[i] + f_11[i]) + c1*f_10[i] + c2*f_01[i];\n                        o[INDEX2(i,numComp,3)] = c0*(f_01[i] + f_10[i]) + c1*f_00[i] + c2*f_11[i];\n                    } /* end of component loop i */\n                } /* end of k0 loop */\n            } /* end of k1 loop */\n        } /* end of parallel section */\n    }\n}\n\n//private\ntemplate <typename S>\nvoid Rectangle::interpolateNodesOnFacesWorker(escript::Data& out,\n                                        const escript::Data& in,\n                                        bool reduced, S sentinel) const\n{\n    const dim_t numComp = in.getDataPointSize();\n    const dim_t NE0 = m_NE[0];\n    const dim_t NE1 = m_NE[1];\n    if (reduced) {\n        out.requireWrite();\n#pragma omp parallel\n        {\n            vector<S> f_00(numComp);\n            vector<S> f_01(numComp);\n            vector<S> f_10(numComp);\n            vector<S> f_11(numComp);\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1=0; k1 < NE1; ++k1) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(0,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(0,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[0]+k1, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = (f_00[i] + f_01[i])/static_cast<S>(2);\n                    } /* end of component loop i */\n                } /* end of k1 loop */\n            } /* end of face 0 */\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1=0; k1 < NE1; ++k1) {\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[1]+k1, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = (f_10[i] + f_11[i])/static_cast<S>(2);\n                    } /* end of component loop i */\n                } /* end of k1 loop */\n            } /* end of face 1 */\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0=0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,0, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,0, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[2]+k0, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = (f_00[i] + f_10[i])/static_cast<S>(2);\n                    } /* end of component loop i */\n                } /* end of k0 loop */\n            } /* end of face 2 */\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0=0; k0 < NE0; ++k0) {\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,m_NN[1]-1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,m_NN[1]-1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[3]+k0, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = (f_01[i] + f_11[i])/static_cast<S>(2);\n                    } /* end of component loop i */\n                } /* end of k0 loop */\n            } /* end of face 3 */\n        } /* end of parallel section */\n    } else {\n        out.requireWrite();\n        const S c0 = 0.21132486540518711775;\n        const S c1 = 0.78867513459481288225;\n#pragma omp parallel\n        {\n            vector<S> f_00(numComp);\n            vector<S> f_01(numComp);\n            vector<S> f_10(numComp);\n            vector<S> f_11(numComp);\n            if (m_faceOffset[0] > -1) {\n#pragma omp for nowait\n                for (index_t k1=0; k1 < NE1; ++k1) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(0,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(0,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[0]+k1, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = c0*f_01[i] + c1*f_00[i];\n                        o[INDEX2(i,numComp,1)] = c0*f_00[i] + c1*f_01[i];\n                    } /* end of component loop i */\n                } /* end of k1 loop */\n            } /* end of face 0 */\n            if (m_faceOffset[1] > -1) {\n#pragma omp for nowait\n                for (index_t k1=0; k1 < NE1; ++k1) {\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(m_NN[0]-1,k1+1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[1]+k1, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = c1*f_10[i] + c0*f_11[i];\n                        o[INDEX2(i,numComp,1)] = c1*f_11[i] + c0*f_10[i];\n                    } /* end of component loop i */\n                } /* end of k1 loop */\n            } /* end of face 1 */\n            if (m_faceOffset[2] > -1) {\n#pragma omp for nowait\n                for (index_t k0=0; k0 < NE0; ++k0) {\n                    memcpy(&f_00[0], in.getSampleDataRO(INDEX2(k0,0, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_10[0], in.getSampleDataRO(INDEX2(k0+1,0, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[2]+k0, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = c0*f_10[i] + c1*f_00[i];\n                        o[INDEX2(i,numComp,1)] = c0*f_00[i] + c1*f_10[i];\n                    } /* end of component loop i */\n                } /* end of k0 loop */\n            } /* end of face 2 */\n            if (m_faceOffset[3] > -1) {\n#pragma omp for nowait\n                for (index_t k0=0; k0 < NE0; ++k0) {\n                    memcpy(&f_01[0], in.getSampleDataRO(INDEX2(k0,m_NN[1]-1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    memcpy(&f_11[0], in.getSampleDataRO(INDEX2(k0+1,m_NN[1]-1, m_NN[0]), sentinel), numComp*sizeof(S));\n                    S* o = out.getSampleDataRW(m_faceOffset[3]+k0, sentinel);\n                    for (index_t i=0; i < numComp; ++i) {\n                        o[INDEX2(i,numComp,0)] = c0*f_11[i] + c1*f_01[i];\n                        o[INDEX2(i,numComp,1)] = c0*f_01[i] + c1*f_11[i];\n                    } /* end of component loop i */\n                } /* end of k0 loop */\n            } /* end of face 3 */\n        } /* end of parallel section */\n    }\n}\n\n\n\nnamespace\n{\n    // Calculates a Gaussian blur convolution matrix for 2D\n    // See wiki article on the subject\n    double* get2DGauss(unsigned radius, double sigma)\n    {\n        double* arr = new double[(radius*2+1)*(radius*2+1)];\n        const double common = M_1_PI * 0.5 / (sigma*sigma);\n        const int r = static_cast<int>(radius);\n        double total = 0;\n        for (int y = -r; y <= r; ++y) {\n            for (int x = -r; x <= r; ++x) {\n                arr[(x+r)+(y+r)*(r*2+1)]=common*exp(-(x*x+y*y)/(2*sigma*sigma));\n                total+=arr[(x+r)+(y+r)*(r*2+1)];\n            }\n        }\n        const double invtotal = 1/total;\n        for (size_t p=0; p<(radius*2+1)*(radius*2+1); ++p) {\n            arr[p] *= invtotal;\n        }\n        return arr;\n    }\n\n    // applies conv to source to get a point.\n    // (xp, yp) are the coords in the source matrix not the destination matrix\n    double Convolve2D(double* conv, double* source, size_t xp, size_t yp,\n                      unsigned radius, size_t width)\n    {\n        const size_t bx = xp-radius, by=yp-radius;\n        const size_t sbase = bx+by*width;\n        double result = 0;\n        for (int y=0; y<2*radius+1; ++y) {\n            for (int x=0; x<2*radius+1; ++x) {\n                result += conv[x+y*(2*radius+1)] * source[sbase + x+y*width];\n            }\n        }\n        return result;\n    }\n}\n\n/* This is a wrapper for filtered (and non-filtered) randoms\n * For detailed doco see randomFillWorker\n */\nescript::Data Rectangle::randomFill(const escript::DataTypes::ShapeType& shape,\n                                const escript::FunctionSpace& what, long seed,\n                                const bp::tuple& filter) const\n{\n    int numvals=escript::DataTypes::noValues(shape);\n    if (len(filter) > 0 && numvals != 1)\n        throw NotImplementedError(\"Ripley only supports filters for scalar data.\");\n\n    escript::Data res = randomFillWorker(shape, seed, filter);\n    if (res.getFunctionSpace() != what) {\n        escript::Data r(res, what);\n        return r;\n    }\n    return res;\n}\n\n\n/* This routine produces a Data object filled with smoothed random data.\n * The dimensions of the rectangle being filled are internal[0] x internal[1]\n * points. A parameter radius gives the size of the stencil used for the\n * smoothing.  A point on the left hand edge for example, will still require\n * `radius` extra points to the left in order to complete the stencil.\n *\n * All local calculation is done on an array called `src`, with\n * dimensions = ext[0] * ext[1], where ext[i]= internal[i]+2*radius.\n *\n * Now for MPI there is overlap to deal with. We need to share both the\n * overlapping values themselves but also the external region.\n *\n * In a hypothetical 1-D case:\n *\n * 1234567 would be split into two ranks thus:\n * 123(4)  (4)567     [4 being a shared element]\n *\n * If the radius is 2. There will be padding elements on the outside:\n * pp123(4)  (4)567pp\n *\n * To ensure that 4 can be correctly computed on both ranks, values from the\n * other rank need to be known.\n *\n * pp123(4)56   23(4)567pp\n *\n * Now in our case, we set all the values 23456 on the left rank and send them\n * to the right hand rank.\n *\n * So the edges _may_ need to be shared at a distance `inset` from all\n * boundaries.\n *\n * inset=2*radius+1\n * This is to ensure that values at distance `radius` from the\n * shared/overlapped element that ripley has.\n */\nescript::Data Rectangle::randomFillWorker(\n                        const escript::DataTypes::ShapeType& shape, long seed,\n                        const bp::tuple& filter) const\n{\n    unsigned int radius=0;  // these are only used by gaussian\n    double sigma=0.5;\n\n    unsigned int numvals=escript::DataTypes::noValues(shape);\n\n    if (len(filter) == 0) {\n        // nothing special required here yet\n    } else if (len(filter) == 3) {\n        bp::extract<string> ex(filter[0]);\n        if (!ex.check() || (ex()!=\"gaussian\")) {\n            throw ValueError(\"Unsupported random filter\");\n        }\n        bp::extract<unsigned int> ex1(filter[1]);\n        if (!ex1.check()) {\n            throw ValueError(\"Radius of Gaussian filter must be a positive integer.\");\n        }\n        radius = ex1();\n        sigma = 0.5;\n        bp::extract<double> ex2(filter[2]);\n        if (!ex2.check() || (sigma=ex2()) <= 0) {\n            throw ValueError(\"Sigma must be a positive floating point number.\");\n        }\n    } else {\n        throw ValueError(\"Unsupported random filter for Rectangle.\");\n    }\n\n    // number of points in the internal region\n    // that is, the ones we need smoothed versions of\n    const dim_t internal[2] = { m_NN[0], m_NN[1] };\n    size_t ext[2];\n    ext[0]=(size_t)internal[0]+2*radius; // includes points we need as input\n    ext[1]=(size_t)internal[1]+2*radius; // for smoothing\n\n    // now we check to see if the radius is acceptable\n    // That is, would not cross multiple ranks in MPI\n\n    if (2*radius >= internal[0]-4) {\n        throw ValueError(\"Radius of gaussian filter is too large for X dimension of a rank\");\n    }\n    if (2*radius >= internal[1]-4) {\n        throw ValueError(\"Radius of gaussian filter is too large for Y dimension of a rank\");\n    }\n\n    double* src = new double[ext[0]*ext[1]*numvals];\n    escript::randomFillArray(seed, src, ext[0]*ext[1]*numvals);\n\n#ifdef ESYS_MPI\n    if ((internal[0] < 5) || (internal[1] < 5)) {\n        // since the dimensions are equal for all ranks, this exception\n        // will be thrown on all ranks\n        throw RipleyException(\"Random Data in Ripley requires at least five elements per side per rank.\");\n    }\n    dim_t X = m_mpiInfo->rank%m_NX[0];\n    dim_t Y = m_mpiInfo->rank/m_NX[0];\n#endif\n\n/*\n    // if we wanted to test a repeating pattern\n    size_t basex=0;\n    size_t basey=0;\n#ifdef ESYS_MPI\n    basex=X*m_gNE[0]/m_NX[0];\n    basey=Y*m_gNE[1]/m_NX[1];\n#endif\n\n    escript::patternFillArray2D(ext[0], ext[1], src, 4, basex, basey, numvals);\n*/\n\n#ifdef ESYS_MPI\n    BlockGrid2 grid(m_NX[0]-1, m_NX[1]-1);\n    // it's +2 not +1 because a whole element is shared (and hence there is\n    // an overlap of two points both of which need to have \"radius\" points on\n    // either side.\n    size_t inset=2*radius+2;\n\n    // how wide is the x-dimension between the two insets\n    size_t xmidlen=ext[0]-2*inset;\n    size_t ymidlen=ext[1]-2*inset;\n\n    Block2 block(ext[0], ext[1], inset, xmidlen, ymidlen, numvals);\n\n    // a non-tight upper bound on how many we need\n    MPI_Request reqs[40];\n    MPI_Status stats[40];\n    short rused=0;\n\n    messvec incoms;\n    messvec outcoms;\n\n    grid.generateInNeighbours(X, Y, incoms);\n    grid.generateOutNeighbours(X, Y, outcoms);\n\n    block.copyAllToBuffer(src);\n\n    int comserr = 0;\n    for (size_t i=0; i < incoms.size(); ++i) {\n        message& m = incoms[i];\n        comserr |= MPI_Irecv(block.getInBuffer(m.destbuffid),\n                             block.getBuffSize(m.destbuffid), MPI_DOUBLE,\n                             m.sourceID, m.tag, m_mpiInfo->comm,\n                             reqs+(rused++));\n        block.setUsed(m.destbuffid);\n    }\n\n    for (size_t i=0; i < outcoms.size(); ++i) {\n        message& m = outcoms[i];\n        comserr |= MPI_Isend(block.getOutBuffer(m.srcbuffid),\n                             block.getBuffSize(m.srcbuffid), MPI_DOUBLE,\n                             m.destID, m.tag, m_mpiInfo->comm, reqs+(rused++));\n    }\n\n    if (!comserr) {\n        comserr = MPI_Waitall(rused, reqs, stats);\n    }\n\n    if (comserr) {\n        // Yes this is throwing an exception as a result of an MPI error\n        // and no we don't inform the other ranks that we are doing this.\n        // However, we have no reason to believe coms work at this point anyway\n        throw RipleyException(\"Error in coms for randomFill\");\n    }\n\n    block.copyUsedFromBuffer(src);\n#endif\n\n    // the truth of either should imply the truth of the other but let's be safe\n    if (radius==0 || numvals > 1) {\n        escript::FunctionSpace fs(getPtr(), getContinuousFunctionCode());\n        escript::Data resdat(0, shape, fs, true);\n        // don't need to check for exwrite because we just made it\n        escript::DataTypes::RealVectorType& dv = resdat.getExpandedVectorReference();\n\n        // now we need to copy values over\n        for (size_t y=0; y < internal[1]; ++y) {\n            for (size_t x=0; x < internal[0]; ++x) {\n                for (unsigned int i=0; i < numvals; ++i) {\n                    dv[i+(x+y*(internal[0]))*numvals]=src[i+(x+y*ext[0])*numvals];\n                }\n            }\n        }\n        delete[] src;\n        return resdat;\n    } else { // filter enabled\n        escript::FunctionSpace fs(getPtr(), getContinuousFunctionCode());\n        escript::Data resdat(0, escript::DataTypes::scalarShape, fs, true);\n        // don't need to check for exwrite because we just made it\n        escript::DataTypes::RealVectorType& dv=resdat.getExpandedVectorReference();\n        double* convolution=get2DGauss(radius, sigma);\n        for (size_t y=0; y < internal[1]; ++y) {\n            for (size_t x=0; x < internal[0]; ++x) {\n                dv[x+y*(internal[0])] = Convolve2D(convolution, src, x+radius, y+radius, radius, ext[0]);\n            }\n        }\n        delete[] convolution;\n        delete[] src;\n        return resdat;\n    }\n}\n\ndim_t Rectangle::findNode(const double *coords) const\n{\n    const dim_t NOT_MINE = -1;\n    //is the found element even owned by this rank\n    // (inside owned or shared elements but will map to an owned element)\n    for (int dim = 0; dim < m_numDim; dim++) {\n        //allows for point outside mapping onto node\n        double min = m_origin[dim] + m_offset[dim]* m_dx[dim]\n                - m_dx[dim]/2. + escript::DataTypes::real_t_eps();\n        double max = m_origin[dim] + (m_offset[dim] + m_NE[dim])*m_dx[dim]\n                + m_dx[dim]/2. - escript::DataTypes::real_t_eps();\n        if (min > coords[dim] || max < coords[dim]) {\n            return NOT_MINE;\n        }\n    }\n    // get distance from origin\n    double x = coords[0] - m_origin[0];\n    double y = coords[1] - m_origin[1];\n\n    //check if the point is even inside the domain\n    if (x < 0 || y < 0 || x > m_length[0] || y > m_length[1])\n        return NOT_MINE;\n\n    // distance in elements\n    dim_t ex = (dim_t) floor((x + 0.01*m_dx[0]) / m_dx[0]);\n    dim_t ey = (dim_t) floor((y + 0.01*m_dx[1]) / m_dx[1]);\n    // set the min distance high enough to be outside the element plus a bit\n    dim_t closest = NOT_MINE;\n    double minDist = 1;\n    for (int dim = 0; dim < m_numDim; dim++) {\n        minDist += m_dx[dim]*m_dx[dim];\n    }\n    //find the closest node\n    for (int dx = 0; dx < 1; dx++) {\n        double xdist = (x - (ex + dx)*m_dx[0]);\n        for (int dy = 0; dy < 1; dy++) {\n            double ydist = (y - (ey + dy)*m_dx[1]);\n            double total = xdist*xdist + ydist*ydist;\n            if (total < minDist) {\n                closest = INDEX2(ex+dx-m_offset[0], ey+dy-m_offset[1], m_NN[0]);\n                minDist = total;\n            }\n        }\n    }\n    //if this happens, we've let a dirac point slip through, which is awful\n    if (closest == NOT_MINE) {\n        throw RipleyException(\"Unable to map appropriate dirac point to a node,\"\n                \" implementation problem in Rectangle::findNode()\");\n    }\n    return closest;\n}\n\nAssembler_ptr Rectangle::createAssembler(string type,\n                                         const DataMap& constants) const\n{\n    bool isComplex = false;\n    DataMap::const_iterator it;\n    for (it = constants.begin(); it != constants.end(); it++) {\n        if (!it->second.isEmpty() && it->second.isComplex()) {\n            isComplex = true;\n            break;\n        }\n    }\n\n    if (type.compare(\"DefaultAssembler\") == 0) {\n        if (isComplex) {\n            return Assembler_ptr(new DefaultAssembler2D<cplx_t>(shared_from_this(), m_dx, m_NE, m_NN));\n        } else {\n            return Assembler_ptr(new DefaultAssembler2D<real_t>(shared_from_this(), m_dx, m_NE, m_NN));\n        }\n    } else if (type.compare(\"WaveAssembler\") == 0) {\n        return Assembler_ptr(new WaveAssembler2D(shared_from_this(), m_dx, m_NE, m_NN, constants));\n    } else if (type.compare(\"LameAssembler\") == 0) {\n        return Assembler_ptr(new LameAssembler2D(shared_from_this(), m_dx, m_NE, m_NN));\n    }\n    throw NotImplementedError(\"Ripley::Rectangle does not support the\"\n                              \" requested assembler\");\n}\n\n} // end of namespace ripley\n\n", "meta": {"hexsha": "b451e712fb40e9d8fede28459662bcaa8307550b", "size": 110117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ripley/src/Rectangle.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "ripley/src/Rectangle.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "ripley/src/Rectangle.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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.0762952449, "max_line_length": 120, "alphanum_fraction": 0.5426773341, "num_tokens": 31367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.040237941616551025, "lm_q1q2_score": 0.019804637469492462}}
{"text": "/*  \n *  Copyright 2010-2011 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 <boost/foreach.hpp>\n#include <boost/progress.hpp>\n\n#ifdef _OPENMP  \n    #include <omp.h>\n#endif\n\n#include \"millingcutter.hpp\"\n#include \"point.hpp\"\n#include \"triangle.hpp\"\n#include \"batchpushcutter.hpp\"\n\nnamespace ocl\n{\n\n//********   ********************** */\n\nBatchPushCutter::BatchPushCutter() {\n    fibers = new std::vector<Fiber>();\n    nCalls = 0;\n    nthreads = 1;\n#ifdef _OPENMP\n    nthreads = omp_get_num_procs(); // figure out how many cores we have\n#endif\n    cutter = NULL;\n    bucketSize = 1;\n    root = new KDTree<Triangle>();\n}\n\nBatchPushCutter::~BatchPushCutter() {\n    delete fibers;\n    delete root;\n}\n\nvoid BatchPushCutter::setSTL(const STLSurf &s) {\n    surf = &s;\n    std::cout << \"BPC::setSTL() Building kd-tree... bucketSize=\" << bucketSize << \"..\";\n    root->setBucketSize( bucketSize );\n    if (x_direction)\n        root->setYZDimensions(); // we search for triangles in the XY plane, don't care about Z-coordinate\n    else if (y_direction)\n        root->setXZDimensions();\n    else {\n        std::cout << \" ERROR: setXDirection() or setYDirection() must be called before setSTL() \\n\";\n        assert(0);\n    }\n    std::cout << \"BPC::setSTL() root->build()...\";\n    root->build(s.tris);\n    std::cout << \"done.\\n\";\n}\n\nvoid BatchPushCutter::appendFiber(Fiber& f) {\n    fibers->push_back(f);\n}\n\nvoid BatchPushCutter::reset() {\n    fibers->clear();\n}\n\n/// very simple batch push-cutter\n/// each fiber is tested against all triangles of surface\nvoid BatchPushCutter::pushCutter1() {\n    std::cout << \"BatchPushCutter1 with \" << fibers->size() << \n              \" fibers and \" << surf->tris.size() << \" triangles...\" << std::endl;\n    nCalls = 0;\n    boost::progress_display show_progress( fibers->size() );\n    BOOST_FOREACH(Fiber& f, *fibers) {\n        BOOST_FOREACH( const Triangle& t, surf->tris) {// test against all triangles in s\n            Interval i;\n            cutter->pushCutter(f,i,t);\n            f.addInterval(i);\n            ++nCalls;\n        }\n        ++show_progress;\n    }\n    std::cout << \"BatchPushCutter done.\" << std::endl;\n    return;\n}\n\n/// push-cutter which uses KDNode2 kd-tree search to find triangles \n/// overlapping with the cutter.\nvoid BatchPushCutter::pushCutter2() {\n    std::cout << \"BatchPushCutter2 with \" << fibers->size() << \n              \" fibers and \" << surf->tris.size() << \" triangles...\" << std::endl;\n    nCalls = 0;\n    std::list<Triangle>* overlap_triangles;\n    boost::progress_display show_progress( fibers->size() );\n    BOOST_FOREACH(Fiber& f, *fibers) {\n        CLPoint cl;\n        if (x_direction) {\n            cl.x = 0;\n            cl.y = f.p1.y;\n            cl.z = f.p1.z;\n        } else if (y_direction) {\n            cl.x = f.p1.x;\n            cl.y = 0;\n            cl.z = f.p1.z;\n        } else {\n            assert(0);\n        }\n        overlap_triangles = root->search_cutter_overlap(cutter, &cl);\n        assert( overlap_triangles->size() <= surf->size() ); // can't possibly find more triangles than in the STLSurf \n        BOOST_FOREACH( const Triangle& t, *overlap_triangles) {\n            //if ( bb->overlaps( t.bb ) ) {\n                Interval i;\n                cutter->pushCutter(f,i,t);\n                f.addInterval(i);\n                ++nCalls;\n            //}\n        }\n        delete( overlap_triangles );\n        ++show_progress;\n    }\n    std::cout << \"BatchPushCutter2 done.\" << std::endl;\n    return;\n}\n\n/// use kd-tree search to find overlapping triangles\n/// use OpenMP for multi-threading\nvoid BatchPushCutter::pushCutter3() {\n    std::cout << \"BatchPushCutter3 with \" << fibers->size() << \n              \" fibers and \" << surf->tris.size() << \" triangles.\" << std::endl;\n    std::cout << \" cutter = \" << cutter->str() << \"\\n\";\n    nCalls = 0;\n    boost::progress_display show_progress( fibers->size() );\n#ifdef _OPENMP\n    omp_set_num_threads(nthreads);\n    //omp_set_nested(1);\n#endif\n    unsigned int Nmax = fibers->size();         // the number of fibers to process\n    std::list<Triangle>::iterator it,it_end;    // for looping over found triabgles\n    Interval* i;\n    std::list<Triangle>* tris;\n    std::vector<Fiber>& fiberr = *fibers;\n    unsigned int n; // loop variable\n    unsigned int calls=0;\n    \n    #pragma omp parallel for schedule(dynamic) shared(calls, fiberr) private(n,i,tris,it,it_end)\n    //#pragma omp parallel for shared( calls, fiberr) private(n,i,tris,it,it_end)\n    for (n=0; n<Nmax; ++n) { // loop through all fibers\n#ifdef _OPENMP\n        if ( n== 0 ) { // first iteration\n            if (omp_get_thread_num() == 0 ) \n                std::cout << \"Number of OpenMP threads = \"<< omp_get_num_threads() << \"\\n\";\n        }\n#endif  \n        CLPoint cl; // cl-point on the fiber\n        if ( x_direction ) {\n            cl.x=0;\n            cl.y=fiberr[n].p1.y;\n            cl.z=fiberr[n].p1.z;\n        } else if (y_direction ) {\n            cl.x=fiberr[n].p1.x;\n            cl.y=0;\n            cl.z=fiberr[n].p1.z;\n        }\n        tris = root->search_cutter_overlap(cutter, &cl);\n        it_end = tris->end();\n        for ( it=tris->begin() ; it!=it_end ; ++it) { // loop through the found overlapping triangles\n            //if ( bb->overlaps( it->bb ) ) {\n                // todo: optimization where method-calls are skipped if triangle bbox already in the fiber\n                i = new Interval();\n                cutter->pushCutter(fiberr[n],*i,*it);  \n                fiberr[n].addInterval(*i); \n                ++calls;\n                delete i;\n            //}\n        }\n        delete( tris );\n        ++show_progress;\n    } // OpenMP parallel region ends here\n    \n    this->nCalls = calls;\n    std::cout << \"\\nBatchPushCutter3 done.\" << std::endl;\n    return;\n}\n\n}// end namespace\n// end file batchpushcutter.cpp\n", "meta": {"hexsha": "e9477356b33eaf6cff496b08d67c0b27f6157183", "size": 6541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/algo/batchpushcutter.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/algo/batchpushcutter.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/algo/batchpushcutter.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": 32.8693467337, "max_line_length": 119, "alphanum_fraction": 0.5841614432, "num_tokens": 1734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.04603389847295305, "lm_q1q2_score": 0.019801360045780935}}
{"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/bind/bind.hpp>\nusing namespace boost::placeholders;\n\n\n#include \"tudat/simulation/environment_setup/createRadiationPressureInterface.h\"\n#include \"tudat/astro/basic_astro/sphericalBodyShapeModel.h\"\n#include \"tudat/astro/reference_frames/referenceFrameTransformations.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\n//! Function to obtain (by reference) the position functions and radii of occulting bodies\nvoid getOccultingBodiesInformation(\n        const SystemOfBodies& bodies, const std::vector< std::string >& occultingBodies,\n        std::vector< std::function< Eigen::Vector3d( ) > >& occultingBodyPositions,\n        std::vector< double >& occultingBodyRadii )\n{\n    // Iterate over occulring bodies and retrieve radius and position function.\n    for( unsigned int i = 0; i < occultingBodies.size( ); i++ )\n    {\n        if( bodies.count( occultingBodies[ i ] ) == 0 )\n        {\n            throw std::runtime_error( \"Error, could not find body \" + occultingBodies[ i ] +\n                                      \" in system of bodies when making occulting body settings\" );\n        }\n        else\n        {\n            std::shared_ptr< basic_astrodynamics::BodyShapeModel > shapeModel =\n                    bodies.at( occultingBodies.at( i ) )->getShapeModel( );\n            if( shapeModel == nullptr )\n            {\n                throw std::runtime_error( \"Error, no shape model for \" + occultingBodies[ i ] +\n                                          \" when making occulting body settings\" );\n            }\n            occultingBodyPositions.push_back(\n                        std::bind( &Body::getPosition, bodies.at( occultingBodies[ i ] ) ) );\n            occultingBodyRadii.push_back( shapeModel->getAverageRadius( ) );\n        }\n    }\n}\n\n\n//! Function to obtain (by reference) the position and velocity functions of the central body.\nvoid getCentralBodyInformation(\n    const SystemOfBodies& bodies, const std::string& centralBody,\n    std::function< Eigen::Vector3d( ) >& centralBodyPosition,\n    std::function< Eigen::Vector3d( ) >& centralBodyVelocity )\n{\n\n    // Check that the central body is defined.\n    if( bodies.count( centralBody ) == 0 )\n    {\n        throw std::runtime_error( \"Error, could not find body \" + centralBody +\n                                 \" in system of bodies when making central body body settings\" );\n    }\n    // Retrieve position and velocity functions.\n    else\n    {\n        centralBodyPosition = std::bind( &Body::getPosition, bodies.at( centralBody ) );\n        centralBodyVelocity = std::bind( &Body::getVelocity, bodies.at( centralBody ) );\n    }\n}\n\n\n//! Function to create a radiation pressure interface.\nstd::shared_ptr< electromagnetism::RadiationPressureInterface > createRadiationPressureInterface(\n        const std::shared_ptr< RadiationPressureInterfaceSettings > radiationPressureInterfaceSettings,\n        const std::string& bodyName, const SystemOfBodies& bodies )\n{\n    std::shared_ptr< electromagnetism::RadiationPressureInterface > radiationPressureInterface;\n\n    // Check type of radiation pressure interface\n    switch( radiationPressureInterfaceSettings->getRadiationPressureType( ) )\n    {\n    case cannon_ball_radiation_pressure_interface:\n    {\n        // Check type consistency.\n        std::shared_ptr< CannonBallRadiationPressureInterfaceSettings > cannonBallSettings =\n                std::dynamic_pointer_cast< CannonBallRadiationPressureInterfaceSettings >(\n                    radiationPressureInterfaceSettings );\n        if( cannonBallSettings == nullptr )\n        {\n            throw std::runtime_error( \"Error when making cannon ball radiation interface, type does not match object\" );\n        }\n\n        // Retrieve source body and check consistency.\n        if( bodies.count( radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\n        {\n            throw std::runtime_error( \"Error when making cannon ball radiation interface, source not found.\");\n        }\n\n        std::shared_ptr< Body > sourceBody =\n                bodies.at( radiationPressureInterfaceSettings->getSourceBody( ) );\n\n        // Get reqruied data for occulting bodies.\n        std::vector< std::string > occultingBodies = cannonBallSettings->getOccultingBodies( );\n        std::vector< std::function< Eigen::Vector3d( ) > > occultingBodyPositions;\n        std::vector< double > occultingBodyRadii;\n        getOccultingBodiesInformation(\n                    bodies, occultingBodies, occultingBodyPositions, occultingBodyRadii );\n\n        // Retrive radius of source if occultations are used.\n        double sourceRadius;\n        if( occultingBodyPositions.size( ) > 0 )\n        {\n            std::shared_ptr< basic_astrodynamics::BodyShapeModel > sourceShapeModel =\n                    sourceBody->getShapeModel( );\n\n            if( sourceShapeModel == nullptr )\n            {\n                throw std::runtime_error( \"Error when making occulted body, source body \" +\n                                          radiationPressureInterfaceSettings->getSourceBody( ) +\n                                          \" does not have a shape\" );\n            }\n            else\n            {\n                sourceRadius = sourceShapeModel->getAverageRadius( );\n            }\n        }\n        else\n        {\n            sourceRadius = 0.0;\n        }\n\n        // Create function returning radiated power.\n        std::function< double( ) > radiatedPowerFunction;\n        if( defaultRadiatedPowerValues.count(\n                    radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\n        {\n            throw std::runtime_error( \"Error, no radiated power found for \" +\n                                      radiationPressureInterfaceSettings->getSourceBody( ) );\n        }\n        else\n        {\n            radiatedPowerFunction = [ = ]( ){ return\n                        defaultRadiatedPowerValues.at(\n                            radiationPressureInterfaceSettings->getSourceBody( ) ); };\n        }\n\n        if( cannonBallSettings->getRadiationPressureCoefficient( ) !=\n                cannonBallSettings->getRadiationPressureCoefficient( ) )\n        {\n        // Create radiation pressure interface.\n        radiationPressureInterface =\n                std::make_shared< electromagnetism::RadiationPressureInterface >(\n                    radiatedPowerFunction,\n                    std::bind( &Body::getPosition, sourceBody ),\n                    std::bind( &Body::getPosition, bodies.at( bodyName ) ),\n                    cannonBallSettings->getRadiationPressureCoefficientFunction( ),\n                    cannonBallSettings->getArea( ), occultingBodyPositions, occultingBodyRadii,\n                    sourceRadius );\n        }\n        else\n        {\n            // Create radiation pressure interface.\n            radiationPressureInterface =\n                    std::make_shared< electromagnetism::RadiationPressureInterface >(\n                        radiatedPowerFunction,\n                        std::bind( &Body::getPosition, sourceBody ),\n                        std::bind( &Body::getPosition, bodies.at( bodyName ) ),\n                        cannonBallSettings->getRadiationPressureCoefficient( ),\n                        cannonBallSettings->getArea( ), occultingBodyPositions, occultingBodyRadii,\n                        sourceRadius );\n        }\n        break;\n    }\n    case panelled_radiation_pressure_interface:\n    {\n        // Check type consistency.\n        std::shared_ptr< PanelledRadiationPressureInterfaceSettings > panelledSettings =\n                std::dynamic_pointer_cast< PanelledRadiationPressureInterfaceSettings >(\n                    radiationPressureInterfaceSettings );\n        if( panelledSettings == NULL )\n        {\n            throw std::runtime_error( \"Error when making panelled radiation interface, type does not match object\" );\n        }\n\n        // Retrieve source body and check consistency.\n        if( bodies.count( radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\n        {\n            throw std::runtime_error( \"Error when making panelled radiation interface, source not found.\");\n        }\n\n        std::shared_ptr< Body > sourceBody =\n                bodies.at( radiationPressureInterfaceSettings->getSourceBody( ) );\n\n        // Get required data for occulting bodies.\n        std::vector< std::string > occultingBodies = panelledSettings->getOccultingBodies( );\n        std::vector< std::function< Eigen::Vector3d( ) > > occultingBodyPositions;\n        std::vector< double > occultingBodyRadii;\n        getOccultingBodiesInformation( bodies, occultingBodies, occultingBodyPositions, occultingBodyRadii );\n\n        // Retrieve radius of source if occultations are used.\n        double sourceRadius;\n        if( occultingBodyPositions.size( ) > 0 )\n        {\n            std::shared_ptr< basic_astrodynamics::BodyShapeModel > sourceShapeModel =\n                    sourceBody->getShapeModel( );\n\n            if( sourceShapeModel == NULL )\n            {\n                throw std::runtime_error(\n                            \"Error when making occulted body, source body \" + radiationPressureInterfaceSettings->getSourceBody( ) +\n                            \" does not have a shape\" );\n            }\n            else\n            {\n                sourceRadius = sourceShapeModel->getAverageRadius( );\n            }\n        }\n        else\n        {\n            sourceRadius = 0.0;\n        }\n\n        // Create function returning radiated power.\n        std::function< double( ) > radiatedPowerFunction;\n        if( defaultRadiatedPowerValues.count(\n                    radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\n        {\n            throw std::runtime_error( \"Error, no radiated power found for \" +\n                                      radiationPressureInterfaceSettings->getSourceBody( ) );\n        }\n        else\n        {\n            radiatedPowerFunction = [ = ]( ){ return defaultRadiatedPowerValues.at(\n                            radiationPressureInterfaceSettings->getSourceBody( ) ); };\n        }\n\n        std::vector< std::function< Eigen::Vector3d( const double ) > > localFrameSurfaceNormalFunctions = panelledSettings->getSurfaceNormalsInBodyFixedFrameFunctions();\n\n\n        // Create radiation pressure interface.\n        radiationPressureInterface =\n                std::make_shared< electromagnetism::PanelledRadiationPressureInterface >(\n                    radiatedPowerFunction,\n                    std::bind( &Body::getPosition, sourceBody ),\n                    std::bind( &Body::getPosition, bodies.at( bodyName ) ),\n                    localFrameSurfaceNormalFunctions,\n                    panelledSettings->getEmissivities( ),\n                    panelledSettings->getAreas( ),\n                    panelledSettings->getDiffusionCoefficients( ),\n                    std::bind( &Body::getCurrentRotationToGlobalFrame, bodies.at( bodyName ) ),\n                    occultingBodyPositions, occultingBodyRadii,\n                    sourceRadius );\n        break;\n    }\n    case solar_sailing_radiation_pressure_interface:\n    {\n        // Check type consistency.\n        std::shared_ptr< SolarSailRadiationInterfaceSettings > solarSailRadiationSettings =\n                std::dynamic_pointer_cast< SolarSailRadiationInterfaceSettings >( radiationPressureInterfaceSettings );\n\n        if( solarSailRadiationSettings == nullptr )\n        {\n            throw std::runtime_error( \"Error when making solar sail radiation interface, type does not match object\" );\n        }\n\n        // Retrieve source body and check consistency.\n        if( bodies.count( radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\n        {\n            throw std::runtime_error( \"Error when making solar sail radiation interface, source not found.\");\n        }\n        std::shared_ptr< Body > sourceBody = bodies.at( radiationPressureInterfaceSettings->getSourceBody( ) );\n\n\n        // Get required data for occulting bodies.\n        std::vector< std::string > occultingBodies = solarSailRadiationSettings->getOccultingBodies( );\n        std::vector< std::function< Eigen::Vector3d( ) > > occultingBodyPositions;\n        std::vector< double > occultingBodyRadii;\n        getOccultingBodiesInformation(\n            bodies, occultingBodies, occultingBodyPositions, occultingBodyRadii );\n\n        // Retrieve radius of source if occultations are used.\n        double sourceRadius;\n        if( occultingBodyPositions.size( ) > 0 )\n        {\n            std::shared_ptr< basic_astrodynamics::BodyShapeModel > sourceShapeModel =\n                sourceBody->getShapeModel( );\n\n            if( sourceShapeModel == nullptr )\n            {\n                throw std::runtime_error( \"Error when making occulted body, source body \" +\n                                         radiationPressureInterfaceSettings->getSourceBody( ) +\n                                         \" does not have a shape\" );\n            }\n            else\n            {\n                sourceRadius = sourceShapeModel->getAverageRadius( );\n            }\n        }\n        else\n        {\n            sourceRadius = 0.0;\n        }\n\n\n        // Get required data for central bodies.\n        std::string centralBody = solarSailRadiationSettings->getCentralBody();\n        std::function< Eigen::Vector3d( ) > centralBodyPosition;\n        std::function< Eigen::Vector3d( ) > centralBodyVelocity;\n        getCentralBodyInformation( bodies, centralBody, centralBodyPosition, centralBodyVelocity );\n\n        // Create function returning radiated power.\n        std::function< double( ) > radiatedPowerFunction;\n        if( defaultRadiatedPowerValues.count(\n                radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\n        {\n            throw std::runtime_error( \"Error, no radiated power found for \" +\n                                     radiationPressureInterfaceSettings->getSourceBody( ) );\n        }\n        else\n        {\n            radiatedPowerFunction = [ = ]( ){ return defaultRadiatedPowerValues.at( radiationPressureInterfaceSettings->getSourceBody( ) );};\n        }\n\n        // Create solar sailing radiation pressure interface.\n        radiationPressureInterface =\n            std::make_shared< electromagnetism::SolarSailingRadiationPressureInterface >(\n                radiatedPowerFunction,\n                std::bind( &Body::getPosition, sourceBody ),\n                std::bind( &Body::getPosition, bodies.at( bodyName ) ),\n                std::bind( &Body::getVelocity, bodies.at( bodyName ) ),\n                solarSailRadiationSettings->getArea( ),\n                solarSailRadiationSettings->getConeAngle(),\n                solarSailRadiationSettings->getClockAngle(),\n                solarSailRadiationSettings->getFrontEmissivityCoefficient(),\n                solarSailRadiationSettings->getBackEmissivityCoefficient(),\n                solarSailRadiationSettings->getFrontLambertianCoefficient(),\n                solarSailRadiationSettings->getBackLambertianCoefficient(),\n                solarSailRadiationSettings->getReflectivityCoefficient(),\n                solarSailRadiationSettings->getSpecularReflectionCoefficient(),\n                occultingBodyPositions, centralBodyVelocity,\n                occultingBodyRadii, sourceRadius);\n        break;\n    }\n    default:\n        throw std::runtime_error(\n                    \"Error, radiation pressure type\" + std::to_string(\n                        radiationPressureInterfaceSettings->getRadiationPressureType( ) ) +\n                    \"not recognized for body\" + bodyName );\n    }\n\n    return radiationPressureInterface;\n}\n\nstd::function< double( const double ) > getOccultationFunction(\n        const SystemOfBodies& bodyMap,\n        const std::string& sourceBody,\n        const std::string& occultingBody,\n        const std::string& shadowedBody )\n{\n    std::function< Eigen::Vector3d( ) > sourceBodyPositionFunction =\n            std::bind( &Body::getPosition, bodyMap.at( sourceBody ) );\n    std::function< Eigen::Vector3d( ) > occultingBodyPositionFunction =\n            std::bind( &Body::getPosition, bodyMap.at( occultingBody ) );\n    std::function< Eigen::Vector3d( ) > shadowedBodyPositionFunction =\n            std::bind( &Body::getPosition, bodyMap.at( shadowedBody ) );\n    double sourceBodyRadius = bodyMap.at( sourceBody )->getShapeModel( )->getAverageRadius( );\n    double occultingBodyRadius = bodyMap.at( occultingBody )->getShapeModel( )->getAverageRadius( );\n\n    return [=]( const double ){\n        return mission_geometry::computeShadowFunction(\n                    sourceBodyPositionFunction( ), sourceBodyRadius,\n                    occultingBodyPositionFunction( ), occultingBodyRadius,\n                    shadowedBodyPositionFunction( ) ); };\n}\n\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "877dffd7f5bf6fc1eca8f419438224bcae68273f", "size": 17279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/environment_setup/createRadiationPressureInterface.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/environment_setup/createRadiationPressureInterface.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation/environment_setup/createRadiationPressureInterface.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": 44.7642487047, "max_line_length": 170, "alphanum_fraction": 0.6188436831, "num_tokens": 3536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.040845716347790245, "lm_q1q2_score": 0.01978485152689644}}
{"text": "/*!\r\n@file\r\nDefines several `constexpr` algorithms.\r\n\r\n@copyright Louis Dionne 2013-2017\r\nDistributed under the Boost Software License, Version 1.0.\r\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#ifndef BOOST_HANA_DETAIL_ALGORITHM_HPP\r\n#define BOOST_HANA_DETAIL_ALGORITHM_HPP\r\n\r\n#include <boost/hana/functional/placeholder.hpp>\r\n\r\n#include <boost/hana/config.hpp>\r\n\r\n#include <cstddef>\r\n#include <utility>\r\n\r\n\r\nBOOST_HANA_NAMESPACE_BEGIN namespace detail {\r\n    // Do not call this swap, otherwise it can get picked up by ADL and conflict\r\n    // with std::swap (see https://github.com/boostorg/hana/issues/297).\r\n    template <typename T>\r\n    constexpr void constexpr_swap(T& x, T& y) {\r\n        auto tmp = x;\r\n        x = y;\r\n        y = std::move(tmp);\r\n    }\r\n\r\n    template <typename BidirIter>\r\n    constexpr void reverse(BidirIter first, BidirIter last) {\r\n        while (first != last) {\r\n            if (first == --last)\r\n                break;\r\n            detail::constexpr_swap(*first, *last);\r\n            ++first;\r\n        }\r\n    }\r\n\r\n    template <typename BidirIter, typename BinaryPred>\r\n    constexpr bool next_permutation(BidirIter first, BidirIter last,\r\n                                    BinaryPred pred)\r\n    {\r\n        BidirIter i = last;\r\n        if (first == last || first == --i)\r\n            return false;\r\n        while (true) {\r\n            BidirIter ip1 = i;\r\n            if (pred(*--i, *ip1)) {\r\n                BidirIter j = last;\r\n                while (!pred(*i, *--j))\r\n                    ;\r\n                detail::constexpr_swap(*i, *j);\r\n                detail::reverse(ip1, last);\r\n                return true;\r\n            }\r\n            if (i == first) {\r\n                detail::reverse(first, last);\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n\r\n    template <typename BidirIter>\r\n    constexpr bool next_permutation(BidirIter first, BidirIter last)\r\n    { return detail::next_permutation(first, last, hana::_ < hana::_); }\r\n\r\n\r\n    template <typename InputIter1, typename InputIter2, typename BinaryPred>\r\n    constexpr bool lexicographical_compare(InputIter1 first1, InputIter1 last1,\r\n                                           InputIter2 first2, InputIter2 last2,\r\n                                           BinaryPred pred)\r\n    {\r\n        for (; first2 != last2; ++first1, ++first2) {\r\n            if (first1 == last1 || pred(*first1, *first2))\r\n                return true;\r\n            else if (pred(*first2, *first1))\r\n                return false;\r\n        }\r\n        return false;\r\n    }\r\n\r\n    template <typename InputIter1, typename InputIter2>\r\n    constexpr bool lexicographical_compare(InputIter1 first1, InputIter1 last1,\r\n                                           InputIter2 first2, InputIter2 last2)\r\n    { return detail::lexicographical_compare(first1, last1, first2, last2, hana::_ < hana::_); }\r\n\r\n\r\n    template <typename InputIter1, typename InputIter2, typename BinaryPred>\r\n    constexpr bool equal(InputIter1 first1, InputIter1 last1,\r\n                         InputIter2 first2, InputIter2 last2,\r\n                         BinaryPred pred)\r\n    {\r\n        for (; first1 != last1 && first2 != last2; ++first1, ++first2)\r\n            if (!pred(*first1, *first2))\r\n                return false;\r\n        return first1 == last1 && first2 == last2;\r\n    }\r\n\r\n    template <typename InputIter1, typename InputIter2>\r\n    constexpr bool equal(InputIter1 first1, InputIter1 last1,\r\n                         InputIter2 first2, InputIter2 last2)\r\n    { return detail::equal(first1, last1, first2, last2, hana::_ == hana::_); }\r\n\r\n\r\n    template <typename BidirIter, typename BinaryPred>\r\n    constexpr void sort(BidirIter first, BidirIter last, BinaryPred pred) {\r\n        if (first == last) return;\r\n\r\n        BidirIter i = first;\r\n        for (++i; i != last; ++i) {\r\n            BidirIter j = i;\r\n            auto t = *j;\r\n            for (BidirIter k = i; k != first && pred(t,  *--k); --j)\r\n                *j = *k;\r\n            *j = t;\r\n        }\r\n    }\r\n\r\n    template <typename BidirIter>\r\n    constexpr void sort(BidirIter first, BidirIter last)\r\n    { detail::sort(first, last, hana::_ < hana::_); }\r\n\r\n\r\n    template <typename InputIter, typename T>\r\n    constexpr InputIter find(InputIter first, InputIter last, T const& value) {\r\n        for (; first != last; ++first)\r\n            if (*first == value)\r\n                return first;\r\n        return last;\r\n    }\r\n\r\n    template <typename InputIter, typename UnaryPred>\r\n    constexpr InputIter find_if(InputIter first, InputIter last, UnaryPred pred) {\r\n        for (; first != last; ++first)\r\n            if (pred(*first))\r\n                return first;\r\n        return last;\r\n    }\r\n\r\n    template <typename ForwardIter, typename T>\r\n    constexpr void iota(ForwardIter first, ForwardIter last, T value) {\r\n        while (first != last) {\r\n            *first++ = value;\r\n            ++value;\r\n        }\r\n    }\r\n\r\n    template <typename InputIt, typename T>\r\n    constexpr std::size_t\r\n    count(InputIt first, InputIt last, T const& value) {\r\n        std::size_t n = 0;\r\n        for (; first != last; ++first)\r\n            if (*first == value)\r\n                ++n;\r\n        return n;\r\n    }\r\n\r\n    template <typename InputIt, typename T, typename F>\r\n    constexpr T accumulate(InputIt first, InputIt last, T init, F f) {\r\n        for (; first != last; ++first)\r\n            init = f(init, *first);\r\n        return init;\r\n    }\r\n\r\n    template <typename InputIt, typename T>\r\n    constexpr T accumulate(InputIt first, InputIt last, T init) {\r\n        return detail::accumulate(first, last, init, hana::_ + hana::_);\r\n    }\r\n\r\n    template <typename ForwardIt>\r\n    constexpr ForwardIt min_element(ForwardIt first, ForwardIt last) {\r\n        if (first == last)\r\n            return last;\r\n\r\n        ForwardIt smallest = first;\r\n        ++first;\r\n        for (; first != last; ++first)\r\n            if (*first < *smallest)\r\n                smallest = first;\r\n        return smallest;\r\n    }\r\n} BOOST_HANA_NAMESPACE_END\r\n\r\n#endif // !BOOST_HANA_DETAIL_ALGORITHM_HPP\r\n", "meta": {"hexsha": "04171481a3b2971674d6d150dc5ad6767830f5a4", "size": 6159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/hana/detail/algorithm.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": 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": "deps/boost/include/boost/hana/detail/algorithm.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": 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": "deps/boost/include/boost/hana/detail/algorithm.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": 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": 32.935828877, "max_line_length": 97, "alphanum_fraction": 0.5509011203, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.05500528868073314, "lm_q1q2_score": 0.019766928546036296}}
{"text": "/*! file qubo.hpp\n * \n * @copyright Licensed under MIT license by hyperQ – Ewa Hendzel\n *\n */\n#include \"helpers/hash.hpp\"\n#include \"helpers/insert.hpp\"\n#include <iostream>\n#include <ostream>\n#include <string>\n#include <unordered_map>\n\n#include <boost/bind.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <iostream>\n\nnamespace qi = boost::spirit::qi;\n\n#ifndef QUBO_MODEL_HPP__\n#define QUBO_MODEL_HPP__\n\nnamespace qubo {\n\nusing boost::fusion::at_c;\nusing qi::double_;\nusing qi::int_;\nusing qi::phrase_parse;\n/**\n * @brief Storage class for linear coefficients of the QUBO model.\n * \n * @tparam NodeType integer number type used to index nodes of the QUBO model.\n * @tparam CoefType real type used to store values of the QUBO model.\n */\ntemplate <class NodeType, class CoefType>\nusing LinearCoef = std::unordered_map<NodeType, CoefType>;\n\n/**\n * @brief Storage class for quadratic coefficients of the QUBO model.\n * \n * @tparam NodeType integer number type used to index nodes of the QUBO model.\n * @tparam CoefType real type used to store values of the QUBO model.\n */\ntemplate <class NodeType, class CoefType>\nusing QuadraticCoef = std::unordered_map<std::pair<NodeType, NodeType>,\n                                         CoefType, helpers::hash_pair>;\n/**\n * @brief Container class for storage of the QUBO model.\n * \n * @tparam NodeType integer number type used to index nodes of the QUBO model.\n * @tparam CoefType real type used to store values of the QUBO model.\n */\ntemplate <class NodeType, class CoefType> class QUBOModel {\nprotected:\n /**\n  * @brief QUBO model linear coefficients store.\n  * \n  */\n  LinearCoef<NodeType, CoefType> linear;\n  /**\n   * @brief QUBO model quadratic coefficients store.\n   * \n   */\n  QuadraticCoef<NodeType, CoefType> quadratic;\n  /**\n   * @brief Number of nodes (variables) in the QUBO model.\n   * \n   */\n  ulong num_nodes = 0;\n\npublic:\n  /**\n   * @brief Construct a new QUBOModel object.\n   * \n   * @param c_linear Linear coefficients of the QUBO model.\n   * @param c_quadratic Quadratic coefficients of the QUBO model.\n   */\n  QUBOModel(LinearCoef<NodeType, CoefType> &c_linear,\n            QuadraticCoef<NodeType, CoefType> &c_quadratic);\n  \n  /**\n   * @brief Returns a textual representation of the QUBO model.\n   * \n   * @return std::string Textual representation of the stored QUBO model.\n   */\n  std::string str() const;\n\n  /**\n   * @brief Add a binary variable (node) to the QUBO model.\n   * \n   * @param vi Variable addres.\n   * @param hi Value of the variable coefficient.\n   */\n  void add_variable(const NodeType &vi, const CoefType &hi);\n\n  /**\n   * @brief Add a connection (coupling) between binaray variables.\n   * \n   * @param connection Addresses of the variables to connect (couple).\n   * @param Ji Strength of the connection (coupling).\n   */\n  void add_connection(const std::pair<NodeType, NodeType> &connection,\n                      const CoefType &Ji);\n\n  /**\n   * @brief Get the variable object.\n   * \n   * @param vi Address of the variable.\n   * @return const CoefType Variable coefficient.\n   */\n  const CoefType get_variable(const NodeType &vi) const;\n\n  /**\n   * @brief Get the connection object.\n   * \n   * @param connection Addresses of the variables.\n   * @return const CoefType Connection (coupling) strength between variables.\n   */\n  const CoefType\n  get_connection(const std::pair<NodeType, NodeType> &connection) const;\n  \n  /**\n   * @brief Set the number of nodes (variables) in the QUBO model.\n   * \n   * @param num_nodes Number of nodes to set.\n   */\n  void set_nodes(int num_nodes);\n\n  /**\n   * @brief Get number of nodes (variables) in the QUBO model.\n   * \n   * @return ulong Number of nodes.\n   */\n  ulong get_nodes() const;\n\n  /**\n   * @brief Print textual representation of the QUBO model to a stream.\n   * \n   * @param os Ouput stream reference.\n   * @param qubos QUBO model.\n   * @return std::ostream& Modified ouput stream reference.\n   */\n  friend std::ostream &operator<<(std::ostream &os,\n                                  qubo::QUBOModel<NodeType, CoefType> &qubos);\n  \n  /**\n   * @brief Create a QUBO model from the input stream.\n   * \n   * @param is Input stream reference.\n   * @param qubos QUBO model.\n   * @return std::istream& Modified input stream reference.\n   */\n  friend std::istream &operator>>(std::istream &is,\n                                  qubo::QUBOModel<NodeType, CoefType> &qubos);\n  \n  /**\n   * @brief Load a QUBO model for an input stream.\n   * \n   * @param stream Input stream refernce.\n   * @return QUBOModel<int, double> Constructed QUBO model object.\n   */\n  static QUBOModel<int, double> load(std::istream &stream);\n};\n\ntemplate <class NodeType, class CoefType>\nQUBOModel<NodeType, CoefType>::QUBOModel(\n    qubo::LinearCoef<NodeType, CoefType> &c_linear,\n    qubo::QuadraticCoef<NodeType, CoefType> &c_quadratic) {\n  linear = c_linear;\n  quadratic = c_quadratic;\n}\n\ntemplate <class NodeType, class CoefType>\nvoid QUBOModel<NodeType, CoefType>::set_nodes(int number) {\n  QUBOModel::num_nodes = number;\n}\ntemplate <class NodeType, class CoefType>\nulong QUBOModel<NodeType, CoefType>::get_nodes() const {\n  return num_nodes;\n}\n\ntemplate <class NodeType, class CoefType>\nstd::string QUBOModel<NodeType, CoefType>::str() const {\n\n  std::string s;\n\n  s.append(\"QUBO model\");\n\n  for (auto &qii : linear) {\n    s.append(\" \" + std::to_string(qii.first) + \"--\" +\n             std::to_string(qii.first) + \":\" + std::to_string(qii.second) +\n             \" \");\n  }\n\n  for (auto &qij : quadratic) {\n    s.append(std::to_string(qij.first.first) + \"--\" +\n             std::to_string(qij.first.second) + \":\" +\n             std::to_string(qij.second));\n  }\n\n  return s;\n}\n\ntemplate <class NodeType, class CoefType>\nvoid QUBOModel<NodeType, CoefType>::add_variable(const NodeType &vi,\n                                                 const CoefType &hi) {\n  helpers::insert_model(linear, vi, hi);\n}\n\ntemplate <class NodeType, class CoefType>\nvoid QUBOModel<NodeType, CoefType>::add_connection(\n    const std::pair<NodeType, NodeType> &connection, const CoefType &Ji) {\n  helpers::insert_model(quadratic, connection, Ji);\n}\n\ntemplate <class NodeType, class CoefType>\nconst CoefType QUBOModel<NodeType, CoefType>::get_connection(\n    const std::pair<NodeType, NodeType> &connection) const {\n  if (quadratic.count(connection) == 0) {\n\n    return 0;\n\n  } else {\n\n    return quadratic.at(connection);\n  }\n}\n\ntemplate <class NodeType, class CoefType>\nconst CoefType\nQUBOModel<NodeType, CoefType>::get_variable(const NodeType &vi) const {\n  if (linear.count(vi) == 0) {\n\n    return 0;\n\n  } else {\n\n    return linear.at(vi);\n  }\n}\n\n/**\n * @brief Print textual representation of the QUBO model to a stream.\n * \n * @param os Ouput stream reference.\n * @param qubos QUBO model.\n * @return std::ostream& Modified ouput stream reference.\n */\ntemplate <class NodeType, class CoefType>\nstd::ostream &operator<<(std::ostream &os,\n                         const qubo::QUBOModel<NodeType, CoefType> &qubos) {\n  os << qubos.str();\n  return os;\n}\n\n/**\n * @brief Create a QUBO model from the input stream.\n * \n * @param is Input stream reference.\n * @param qubos QUBO model.\n * @return std::istream& Modified input stream reference.\n */\ntemplate <class NodeType, class CoefType>\nstd::istream &operator>>(std::istream &is,\n                         const qubo::QUBOModel<NodeType, CoefType> &qubos) {\n  NodeType J1;\n  NodeType J2;\n  CoefType value;\n  is >> J1 >> J2 >> value;\n  if (J1 == J2) {\n    qubos.add_variable(J1, value);\n  } else {\n    qubos.add_connection(std::make_pair(J1, J2), value);\n  }\n\n  return is;\n}\n\n  /*!\n  * @brief Builder for QUBOModel.\n  */\n  struct QUBOBuilder {\n  private:\n    qubo::LinearCoef<int, double> linear_c{};\n    qubo::QuadraticCoef<int, double> quadratic_c{};\n    int num_quadratic = -1;\n    int num_linear = -1;\n    int max_nodes = -1;\n    std::set<int> used_nodes;\n\n  public:\n    /*!\n    * @brief Add new QUBO Model coefficient.\n    *\n    * Methods of this class are meant to be used in conjunction with\n    * appropriate boost spirit based parser which should call them\n    * as actions after parsing respective portions of the input file.\n    *\n    * @param element a triple (i, j, q_ij) defining coefficient to\n    *                be added. The indices pair has to be ordered such\n    *                that i <= j.\n    * @throw std::invalid_argument if i > j.\n    */\n    void add_element(boost::fusion::vector<int, int, double> element) {\n      auto i = at_c<0>(element);\n      auto j = at_c<1>(element);\n      auto coef = at_c<2>(element);\n      if (i == j) {\n        linear_c.insert({i, coef});\n      } else if (i < j) {\n        quadratic_c.insert({{i, j}, coef});\n      } else {\n        throw std::invalid_argument(\"Incorrect file, encountered coefficient \"\n                                    \"from lower triangle of QUBO matrix.\");\n      }\n      used_nodes.insert(i);\n      used_nodes.insert(j);\n    }\n\n    /*!\n    * @brief Set number of quadratic coefficients in the model.\n    *\n    * @param value number of quadratic coefficients.\n    */\n    void set_num_quadratic(int value) { num_quadratic = value; }\n\n    /*!\n    * @brief Set number of linear coefficients in the model.\n    *\n    * @param value number of linear coefficients.\n    */\n    void set_num_linear(int value) { num_linear = value; }\n\n    /*!\n    * @brief Set maximum number of nodes in the model.\n    *\n    * @param value maximm number of nodes in the model.\n    */\n    void set_max_nodes(int value) { max_nodes = value; }\n\n    /*!\n    * @brief Build QUBO Model based on information provided this far\n    *        to the builder.\n    *\n    * @throw std::invalid_argument if one of the following conditions\n    *        is met:\n    *        - number of quadratic and/or linear coefficients is different\n    *          from the declared one.\n    *        - number of quadratic/linear coefficients or maximum number\n    *          of nodes was not provided.\n    *        - there are more variables than the declard maximum number.\n    * @returns Constructed QUBO model.\n    */\n    qubo::QUBOModel<int, double> build_qubo() {\n      if (linear_c.size() == 0 && quadratic_c.size() == 0) {\n        throw std::invalid_argument(\"An empty input, no coefficients defined.\");\n      }\n      if (num_quadratic == -1 || num_linear == -1 || max_nodes == -1) {\n        throw std::invalid_argument(\n            \"No header line or header line misformatted.\");\n      }\n      if (num_linear > max_nodes) {\n        throw std::invalid_argument(\n            \"Number of linear terms is greater than num nodes.\");\n      }\n      if (quadratic_c.size() != num_quadratic) {\n        throw std::invalid_argument(\n            \"Number of quadratic terms is not equal to the declared one.\");\n      }\n      if (linear_c.size() != num_linear) {\n        throw std::invalid_argument(\n            \"Number of linear terms is not equal to the declared one.\");\n      }\n\n      qubo::QUBOModel q(linear_c, quadratic_c);\n      q.set_nodes(*used_nodes.rbegin() + 1);\n      return q;\n    }\n  };\n\n  /*!\n  * @brief Parse QUBO using boost spirit based parser.\n  *\n  * @param first Iterator to the start of the input stream containing\n  *              definition of QUBO.\n  * @param last Iterator to the end of the input stream containing\n  *              definition of QUBO.\n  * @throw std::invalid_argument if parsing failed, either from syntactic\n  *        or semantic reasons.\n  * @returns Constructed QUBO.\n  */\n  template <typename Iterator>\n  qubo::QUBOModel<int, double> parse_qubo(Iterator first, Iterator last) {\n    QUBOBuilder builder;\n    auto real = qi::lexeme[double_];\n    auto index = qi::lexeme[qi::uint_ >> \" \"];\n    auto coefficients =\n        (index >> index >>\n        real)[boost::bind(&QUBOBuilder::add_element, &builder, _1)] >>\n        (qi::eol | qi::eoi);\n    auto comment = qi::lit('c') >> *(qi::print) >> (qi::eol | qi::eoi);\n    auto header =\n        (qi::lit(\"p qubo\") >> qi::uint_ >>\n        qi::uint_[boost::bind(&QUBOBuilder::set_max_nodes, &builder, _1)] >>\n        qi::uint_[boost::bind(&QUBOBuilder::set_num_linear, &builder, _1)] >>\n        qi::uint_[boost::bind(&QUBOBuilder::set_num_quadratic, &builder, _1)] >>\n        (qi::eol | qi::eoi));\n\n    auto result = phrase_parse(first, last,\n                              (*comment >> -header >> *(comment | coefficients)),\n                              qi::blank);\n\n    if (!result || first != last) {\n      throw std::invalid_argument(\"Parsing failed. Incorrect file format.\");\n    }\n    return builder.build_qubo();\n  }\n\n  /*!\n  * @brief Load QUBO from an input stream.\n  *\n  * @param stream an input stream containing definition of QUBO.\n  * @returns A loaded instance.\n  */\n  template <class NodeType, class CoefType>\n  qubo::QUBOModel<int, double>\n  qubo::QUBOModel<NodeType, CoefType>::load(std::istream &stream) {\n    boost::spirit::istream_iterator first(stream), last;\n    return parse_qubo(first, last);\n  }\n\n}; // namespace qubo\n#endif", "meta": {"hexsha": "a6777558db3775c84183d8d8a3d50f5050b5d818", "size": 13026, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/model/qubo.hpp", "max_stars_repo_name": "gnieradk/oneSolver", "max_stars_repo_head_hexsha": "cd04c51ac3e63e7e091acb496c2f568410a0af56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T12:37:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-23T12:37:32.000Z", "max_issues_repo_path": "include/model/qubo.hpp", "max_issues_repo_name": "gnieradk/oneSolver", "max_issues_repo_head_hexsha": "cd04c51ac3e63e7e091acb496c2f568410a0af56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/model/qubo.hpp", "max_forks_repo_name": "gnieradk/oneSolver", "max_forks_repo_head_hexsha": "cd04c51ac3e63e7e091acb496c2f568410a0af56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-09T09:10:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T09:10:17.000Z", "avg_line_length": 30.0831408776, "max_line_length": 81, "alphanum_fraction": 0.6392599417, "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.359364131437828, "lm_q2_score": 0.055005290229849145, "lm_q1q2_score": 0.019766928347935385}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <boost/algorithm/string.hpp>\n#include <boost/make_shared.hpp>\n#include <map>\n#include <ored/marketdata/marketdatumparser.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n\nusing namespace std;\nusing QuantLib::WeekendsOnly;\nusing QuantLib::Currency;\n\nnamespace ore {\nnamespace data {\n\nstatic MarketDatum::InstrumentType parseInstrumentType(const string& s) {\n\n    static map<string, MarketDatum::InstrumentType> b = {\n        {\"ZERO\", MarketDatum::InstrumentType::ZERO},\n        {\"DISCOUNT\", MarketDatum::InstrumentType::DISCOUNT},\n        {\"MM\", MarketDatum::InstrumentType::MM},\n        {\"MM_FUTURE\", MarketDatum::InstrumentType::MM_FUTURE},\n        {\"FRA\", MarketDatum::InstrumentType::FRA},\n        {\"IMM_FRA\", MarketDatum::InstrumentType::IMM_FRA},\n        {\"IR_SWAP\", MarketDatum::InstrumentType::IR_SWAP},\n        {\"BASIS_SWAP\", MarketDatum::InstrumentType::BASIS_SWAP},\n        {\"CC_BASIS_SWAP\", MarketDatum::InstrumentType::CC_BASIS_SWAP},\n        {\"CC_FIX_FLOAT_SWAP\", MarketDatum::InstrumentType::CC_FIX_FLOAT_SWAP},\n        {\"BMA_SWAP\", MarketDatum::InstrumentType::BMA_SWAP},\n        {\"CDS\", MarketDatum::InstrumentType::CDS},\n        {\"CDS_INDEX\", MarketDatum::InstrumentType::CDS_INDEX},\n        {\"FX\", MarketDatum::InstrumentType::FX_SPOT},\n        {\"FX_SPOT\", MarketDatum::InstrumentType::FX_SPOT},\n        {\"FXFWD\", MarketDatum::InstrumentType::FX_FWD},\n        {\"FX_FWD\", MarketDatum::InstrumentType::FX_FWD},\n        {\"HAZARD_RATE\", MarketDatum::InstrumentType::HAZARD_RATE},\n        {\"RECOVERY_RATE\", MarketDatum::InstrumentType::RECOVERY_RATE},\n        {\"FX_FWD\", MarketDatum::InstrumentType::FX_FWD},\n        {\"SWAPTION\", MarketDatum::InstrumentType::SWAPTION},\n        {\"CAPFLOOR\", MarketDatum::InstrumentType::CAPFLOOR},\n        {\"FX_OPTION\", MarketDatum::InstrumentType::FX_OPTION},\n        {\"EQUITY\", MarketDatum::InstrumentType::EQUITY_SPOT},\n        {\"EQUITY_FWD\", MarketDatum::InstrumentType::EQUITY_FWD},\n        {\"EQUITY_DIVIDEND\", MarketDatum::InstrumentType::EQUITY_DIVIDEND},\n        {\"EQUITY_OPTION\", MarketDatum::InstrumentType::EQUITY_OPTION},\n        {\"BOND\", MarketDatum::InstrumentType::BOND},\n        {\"BOND_OPTION\", MarketDatum::InstrumentType::BOND_OPTION},\n        {\"ZC_INFLATIONSWAP\", MarketDatum::InstrumentType::ZC_INFLATIONSWAP},\n        {\"ZC_INFLATIONCAPFLOOR\", MarketDatum::InstrumentType::ZC_INFLATIONCAPFLOOR},\n        {\"YY_INFLATIONSWAP\", MarketDatum::InstrumentType::YY_INFLATIONSWAP},\n        {\"YY_INFLATIONCAPFLOOR\", MarketDatum::InstrumentType::YY_INFLATIONCAPFLOOR},\n        {\"SEASONALITY\", MarketDatum::InstrumentType::SEASONALITY},\n        {\"INDEX_CDS_OPTION\", MarketDatum::InstrumentType::INDEX_CDS_OPTION},\n        {\"COMMODITY\", MarketDatum::InstrumentType::COMMODITY_SPOT},\n        {\"COMMODITY_FWD\", MarketDatum::InstrumentType::COMMODITY_FWD},\n        {\"CORRELATION\", MarketDatum::InstrumentType::CORRELATION},\n        {\"COMMODITY_OPTION\", MarketDatum::InstrumentType::COMMODITY_OPTION},\n        {\"CPR\", MarketDatum::InstrumentType::CPR}};\n\n    auto it = b.find(s);\n    if (it != b.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Cannot convert \" << s << \" to InstrumentType\");\n    }\n}\n\nstatic MarketDatum::QuoteType parseQuoteType(const string& s) {\n    static map<string, MarketDatum::QuoteType> b = {\n        {\"BASIS_SPREAD\", MarketDatum::QuoteType::BASIS_SPREAD},\n        {\"CREDIT_SPREAD\", MarketDatum::QuoteType::CREDIT_SPREAD},\n        {\"YIELD_SPREAD\", MarketDatum::QuoteType::YIELD_SPREAD},\n        {\"RATE\", MarketDatum::QuoteType::RATE},\n        {\"RATIO\", MarketDatum::QuoteType::RATIO},\n        {\"PRICE\", MarketDatum::QuoteType::PRICE},\n        {\"RATE_LNVOL\", MarketDatum::QuoteType::RATE_LNVOL},\n        {\"RATE_GVOL\", MarketDatum::QuoteType::RATE_LNVOL}, // deprecated\n        {\"RATE_NVOL\", MarketDatum::QuoteType::RATE_NVOL},\n        {\"RATE_SLNVOL\", MarketDatum::QuoteType::RATE_SLNVOL},\n        {\"BASE_CORRELATION\", MarketDatum::QuoteType::BASE_CORRELATION},\n        {\"SHIFT\", MarketDatum::QuoteType::SHIFT},\n    };\n\n    if (s == \"RATE_GVOL\")\n        LOG(\"Use of deprecated quote type RATE_GVOL\");\n\n    auto it = b.find(s);\n    if (it != b.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Cannot convert \" << s << \" to QuoteType\");\n    }\n}\n\n// calls parseDateOrPeriod and returns a Date (either the supplied date or asof+period)\nstatic Date getDateFromDateOrPeriod(const string& token, Date asof) {\n    Period term;                                           // gets populated by parseDateOrPeriod\n    Date expiryDate;                                       // gets populated by parseDateOrPeriod\n    bool tmpIsDate;                                        // gets populated by parseDateOrPeriod\n    parseDateOrPeriod(token, expiryDate, term, tmpIsDate); // checks if the market string contains a date or a period\n    if (!tmpIsDate)\n        expiryDate =\n            WeekendsOnly().adjust(asof + term); // we have no calendar information here, so we use a generic calendar\n    return expiryDate;\n}\n\n//! Function to parse a market datum\nboost::shared_ptr<MarketDatum> parseMarketDatum(const Date& asof, const string& datumName, const Real& value) {\n\n    vector<string> tokens;\n    boost::split(tokens, datumName, boost::is_any_of(\"/\"));\n    QL_REQUIRE(tokens.size() > 2, \"more than 2 tokens expected in \" << datumName);\n\n    MarketDatum::InstrumentType instrumentType = parseInstrumentType(tokens[0]);\n    MarketDatum::QuoteType quoteType = parseQuoteType(tokens[1]);\n\n    switch (instrumentType) {\n\n    case MarketDatum::InstrumentType::ZERO: {\n        // ZERO/RATE/EUR/EUR1D/A365/1Y\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::RATE || quoteType == MarketDatum::QuoteType::YIELD_SPREAD,\n                   \"Invalid quote type for \" << datumName);\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        DayCounter dc = parseDayCounter(tokens[4]);\n        // token 5 can be a date, or tenor\n        Date date = Date();\n        Period tenor = Period();\n        bool isDate;\n        parseDateOrPeriod(tokens[5], date, tenor, isDate);\n        return boost::make_shared<ZeroQuote>(value, asof, datumName, quoteType, ccy, date, dc, tenor);\n    }\n\n    case MarketDatum::InstrumentType::DISCOUNT: {\n        // DISCOUNT/RATE/EUR/EUR1D/1Y\n        // DISCOUNT/RATE/EUR/EUR1D/2016-12-15\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        // token 4 can be a date, or tenor\n        Date date = Date();\n        Period tenor = Period();\n        bool isDate;\n        parseDateOrPeriod(tokens[4], date, tenor, isDate);\n        if (!isDate) {\n            // we can't assume any calendar here, so we do the minimal adjustment with a weekend only calendar\n            QL_REQUIRE(tenor != Period(), \"neither date nor tenor recognised\");\n            date = WeekendsOnly().adjust(asof + tenor);\n        }\n        return boost::make_shared<DiscountQuote>(value, asof, datumName, quoteType, ccy, date);\n    }\n\n    case MarketDatum::InstrumentType::MM: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        Period fwdStart = parsePeriod(tokens[3]);\n        Period term = parsePeriod(tokens[4]);\n        return boost::make_shared<MoneyMarketQuote>(value, asof, datumName, quoteType, ccy, fwdStart, term);\n    }\n\n    case MarketDatum::InstrumentType::MM_FUTURE: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        const string& expiry = tokens[3];\n        const string& contract = tokens[4];\n        Period term = parsePeriod(tokens[5]);\n        return boost::make_shared<MMFutureQuote>(value, asof, datumName, quoteType, ccy, expiry, contract, term);\n    }\n\n    case MarketDatum::InstrumentType::FRA: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        Period fwdStart = parsePeriod(tokens[3]);\n        Period term = parsePeriod(tokens[4]);\n        return boost::make_shared<FRAQuote>(value, asof, datumName, quoteType, ccy, fwdStart, term);\n    }\n\n    case MarketDatum::InstrumentType::IMM_FRA: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        string imm1 = tokens[3];\n        string imm2 = tokens[4];\n        unsigned int m1 = parseInteger(imm1);\n        unsigned int m2 = parseInteger(imm2);\n        QL_REQUIRE(m2 > m1, \"Second IMM date must be after the first in \" << datumName);\n        return boost::make_shared<ImmFraQuote>(value, asof, datumName, quoteType, ccy, m1, m2);\n    }\n\n    case MarketDatum::InstrumentType::IR_SWAP: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        Period fwdStart = parsePeriod(tokens[3]);\n        Period tenor = parsePeriod(tokens[4]);\n        Period term = parsePeriod(tokens[5]);\n        return boost::make_shared<SwapQuote>(value, asof, datumName, quoteType, ccy, fwdStart, term, tenor);\n    }\n\n    case MarketDatum::InstrumentType::BASIS_SWAP: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        Period flatTerm = parsePeriod(tokens[2]);\n        Period term = parsePeriod(tokens[3]);\n        const string& ccy = tokens[4];\n        Period maturity = parsePeriod(tokens[5]);\n        return boost::make_shared<BasisSwapQuote>(value, asof, datumName, quoteType, flatTerm, term, ccy, maturity);\n    }\n\n    case MarketDatum::InstrumentType::BMA_SWAP: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        Period term = parsePeriod(tokens[3]);\n        Period maturity = parsePeriod(tokens[4]);\n        return boost::make_shared<BMASwapQuote>(value, asof, datumName, quoteType, term, ccy, maturity);\n    }\n\n    case MarketDatum::InstrumentType::CC_BASIS_SWAP: {\n        QL_REQUIRE(tokens.size() == 7, \"7 tokens expected in \" << datumName);\n        const string& flatCcy = tokens[2];\n        Period flatTerm = parsePeriod(tokens[3]);\n        const string& ccy = tokens[4];\n        Period term = parsePeriod(tokens[5]);\n        Period maturity = parsePeriod(tokens[6]);\n        return boost::make_shared<CrossCcyBasisSwapQuote>(value, asof, datumName, quoteType, flatCcy, flatTerm, ccy,\n                                                          term, maturity);\n    }\n\n    case MarketDatum::InstrumentType::CC_FIX_FLOAT_SWAP: {\n        // CC_FIX_FLOAT_SWAP/RATE/USD/3M/TRY/1Y/5Y\n        QL_REQUIRE(tokens.size() == 7, \"7 tokens expected in \" << datumName);\n        Currency floatCurrency = parseCurrency(tokens[2]);\n        Period floatTenor = parsePeriod(tokens[3]);\n        Currency fixedCurrency = parseCurrency(tokens[4]);\n        Period fixedTenor = parsePeriod(tokens[5]);\n        Period maturity = parsePeriod(tokens[6]);\n        return boost::make_shared<CrossCcyFixFloatSwapQuote>(value, asof, datumName, quoteType, floatCurrency,\n                                                             floatTenor, fixedCurrency, fixedTenor, maturity);\n    }\n\n    case MarketDatum::InstrumentType::CDS: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& underlyingName = tokens[2];\n        const string& seniority = tokens[3];\n        const string& ccy = tokens[4];\n        Period term = parsePeriod(tokens[5]);\n        return boost::make_shared<CdsSpreadQuote>(value, asof, datumName, underlyingName, seniority, ccy, term);\n    }\n\n    case MarketDatum::InstrumentType::HAZARD_RATE: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& underlyingName = tokens[2];\n        const string& seniority = tokens[3];\n        const string& ccy = tokens[4];\n        Period term = parsePeriod(tokens[5]);\n        return boost::make_shared<HazardRateQuote>(value, asof, datumName, underlyingName, seniority, ccy, term);\n    }\n\n    case MarketDatum::InstrumentType::RECOVERY_RATE: {\n        QL_REQUIRE(tokens.size() == 3 || tokens.size() == 5, \"3 or 5 tokens expected in \" << datumName);\n        const string& underlyingName = tokens[2]; // issuer name for CDS, security ID for bond specific RRs\n        string seniority = \"\";\n        string ccy = \"\";\n        if (tokens.size() == 5) {\n            // CDS\n            seniority = tokens[3];\n            ccy = tokens[4];\n        }\n        return boost::make_shared<RecoveryRateQuote>(value, asof, datumName, underlyingName, seniority, ccy);\n    }\n\n    case MarketDatum::InstrumentType::CAPFLOOR: {\n        QL_REQUIRE(tokens.size() == 8 || tokens.size() == 4, \"Either 4 or 8 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        if (tokens.size() == 8) {\n            Period term = parsePeriod(tokens[3]);\n            Period tenor = parsePeriod(tokens[4]);\n            bool atm = parseBool(tokens[5].c_str());\n            bool relative = parseBool(tokens[6].c_str());\n            Real strike = parseReal(tokens[7]);\n            return boost::make_shared<CapFloorQuote>(value, asof, datumName, quoteType, ccy, term, tenor, atm, relative,\n                                                     strike);\n        } else {\n            Period indexTenor = parsePeriod(tokens[3]);\n            return boost::make_shared<CapFloorShiftQuote>(value, asof, datumName, quoteType, ccy, indexTenor);\n        }\n    }\n\n    case MarketDatum::InstrumentType::SWAPTION: {\n        QL_REQUIRE(tokens.size() == 4 || tokens.size() == 6 || tokens.size() == 7,\n                   \"4, 6 or 7 tokens expected in \" << datumName);\n        const string& ccy = tokens[2];\n        Period expiry = tokens.size() >= 6 ? parsePeriod(tokens[3]) : Period(0 * QuantLib::Days);\n        Period term = tokens.size() >= 6 ? parsePeriod(tokens[4]) : parsePeriod(tokens[3]);\n        if (tokens.size() >= 6) { // volatility\n            const string& dimension = tokens[5];\n            Real strike = 0.0;\n            if (dimension == \"ATM\")\n                QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in ATM quote \" << datumName);\n            else if (dimension == \"Smile\") {\n                QL_REQUIRE(tokens.size() == 7, \"7 tokens expected in Smile quote \" << datumName);\n                strike = parseReal(tokens[6]);\n            } else\n                QL_FAIL(\"Swaption vol quote dimension \" << dimension << \" not recognised\");\n            return boost::make_shared<SwaptionQuote>(value, asof, datumName, quoteType, ccy, expiry, term, dimension,\n                                                     strike);\n        } else { // SLN volatility shift\n            return boost::make_shared<SwaptionShiftQuote>(value, asof, datumName, quoteType, ccy, term);\n        }\n    }\n\n    case MarketDatum::InstrumentType::BOND_OPTION: {\n        QL_REQUIRE(tokens.size() == 4 || tokens.size() == 6, \"4 or 6 tokens expected in \" << datumName);\n        const string& qualifier = tokens[2];\n        Period expiry = tokens.size() == 6 ? parsePeriod(tokens[3]) : Period(0 * QuantLib::Days);\n        Period term = tokens.size() == 6 ? parsePeriod(tokens[4]) : parsePeriod(tokens[3]);\n        if (tokens.size() == 6) { // volatility\n            QL_REQUIRE(tokens[5] == \"ATM\", \"only ATM allowed for bond option quotes\");\n            return boost::make_shared<BondOptionQuote>(value, asof, datumName, quoteType, qualifier, expiry, term);\n        }\n        else { // SLN volatility shift\n            return boost::make_shared<BondOptionShiftQuote>(value, asof, datumName, quoteType, qualifier, term);\n        }\n    }\n\n    case MarketDatum::InstrumentType::FX_SPOT: {\n        QL_REQUIRE(tokens.size() == 4, \"4 tokens expected in \" << datumName);\n        const string& unitCcy = tokens[2];\n        const string& ccy = tokens[3];\n        return boost::make_shared<FXSpotQuote>(value, asof, datumName, quoteType, unitCcy, ccy);\n    }\n\n    case MarketDatum::InstrumentType::FX_FWD: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        const string& unitCcy = tokens[2];\n        const string& ccy = tokens[3];\n        Period term = parsePeriod(tokens[4]);\n        return boost::make_shared<FXForwardQuote>(value, asof, datumName, quoteType, unitCcy, ccy, term);\n    }\n\n    case MarketDatum::InstrumentType::FX_OPTION: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& unitCcy = tokens[2];\n        const string& ccy = tokens[3];\n        Period expiry = parsePeriod(tokens[4]);\n        const string& strike = tokens[5];\n        return boost::make_shared<FXOptionQuote>(value, asof, datumName, quoteType, unitCcy, ccy, expiry, strike);\n    }\n\n    case MarketDatum::InstrumentType::ZC_INFLATIONSWAP: {\n        QL_REQUIRE(tokens.size() == 4, \"4 tokens expected in \" << datumName);\n        const string& index = tokens[2];\n        Period term = parsePeriod(tokens[3]);\n        return boost::make_shared<ZcInflationSwapQuote>(value, asof, datumName, index, term);\n    }\n\n    case MarketDatum::InstrumentType::YY_INFLATIONSWAP: {\n        QL_REQUIRE(tokens.size() == 4, \"4 tokens expected in \" << datumName);\n        const string& index = tokens[2];\n        Period term = parsePeriod(tokens[3]);\n        return boost::make_shared<YoYInflationSwapQuote>(value, asof, datumName, index, term);\n    }\n\n    case MarketDatum::InstrumentType::ZC_INFLATIONCAPFLOOR: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& index = tokens[2];\n        Period term = parsePeriod(tokens[3]);\n        QL_REQUIRE(tokens[4] == \"C\" || tokens[4] == \"F\",\n                   \"excepted C or F for Cap or Floor at position 5 in \" << datumName);\n        bool isCap = tokens[4] == \"C\";\n        string strike = tokens[5];\n        return boost::make_shared<ZcInflationCapFloorQuote>(value, asof, datumName, quoteType, index, term, isCap,\n                                                            strike);\n    }\n\n    case MarketDatum::InstrumentType::YY_INFLATIONCAPFLOOR: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        const string& index = tokens[2];\n        Period term = parsePeriod(tokens[3]);\n        QL_REQUIRE(tokens[4] == \"C\" || tokens[4] == \"F\",\n                   \"excepted C or F for Cap or Floor at position 5 in \" << datumName);\n        bool isCap = tokens[4] == \"C\";\n        string strike = tokens[5];\n        return boost::make_shared<YyInflationCapFloorQuote>(value, asof, datumName, quoteType, index, term, isCap,\n                                                            strike);\n    }\n\n    case MarketDatum::InstrumentType::SEASONALITY: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        const string& index = tokens[3];\n        const string& type = tokens[2];\n        const string& month = tokens[4];\n        return boost::make_shared<SeasonalityQuote>(value, asof, datumName, index, type, month);\n    }\n    case MarketDatum::InstrumentType::EQUITY_SPOT: {\n        QL_REQUIRE(tokens.size() == 4, \"4 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::PRICE, \"Invalid quote type for \" << datumName);\n        const string& equityName = tokens[2];\n        const string& ccy = tokens[3];\n        return boost::make_shared<EquitySpotQuote>(value, asof, datumName, quoteType, equityName, ccy);\n    }\n\n    case MarketDatum::InstrumentType::EQUITY_FWD: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::PRICE, \"Invalid quote type for \" << datumName);\n        const string& equityName = tokens[2];\n        const string& ccy = tokens[3];\n        Date expiryDate = getDateFromDateOrPeriod(tokens[4], asof);\n        return boost::make_shared<EquityForwardQuote>(value, asof, datumName, quoteType, equityName, ccy, expiryDate);\n    }\n\n    case MarketDatum::InstrumentType::EQUITY_DIVIDEND: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::RATE, \"Invalid quote type for \" << datumName);\n        const string& equityName = tokens[2];\n        const string& ccy = tokens[3];\n        Date tenorDate = getDateFromDateOrPeriod(tokens[4], asof);\n        return boost::make_shared<EquityDividendYieldQuote>(value, asof, datumName, quoteType, equityName, ccy,\n                                                            tenorDate);\n    }\n\n    case MarketDatum::InstrumentType::EQUITY_OPTION: {\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::RATE_LNVOL, \"Invalid quote type for \" << datumName);\n        const string& equityName = tokens[2];\n        const string& ccy = tokens[3];\n        string expiryString = tokens[4];\n        const string& strike = tokens[5];\n        // note how we only store the expiry string - to ensure we can support both Periods and Dates being specified in\n        // the vol curve-config.\n        return boost::make_shared<EquityOptionQuote>(value, asof, datumName, quoteType, equityName, ccy, expiryString,\n                                                     strike);\n    }\n\n    case MarketDatum::InstrumentType::BOND: {\n        QL_REQUIRE(tokens.size() == 3, \"3 tokens expected in \" << datumName);\n        const string& securityID = tokens[2];\n        return boost::make_shared<SecuritySpreadQuote>(value, asof, datumName, securityID);\n    }\n\n    case MarketDatum::InstrumentType::CDS_INDEX: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::BASE_CORRELATION, \"Invalid quote type for \" << datumName);\n        const string& cdsIndexName = tokens[2];\n        Period term = parsePeriod(tokens[3]);\n        Real detachmentPoint = parseReal(tokens[4]);\n        return boost::make_shared<BaseCorrelationQuote>(value, asof, datumName, quoteType, cdsIndexName, term,\n                                                        detachmentPoint);\n    }\n\n    case MarketDatum::InstrumentType::INDEX_CDS_OPTION: {\n        QL_REQUIRE(tokens.size() == 4, \"4 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::RATE_LNVOL, \"Invalid quote type for \" << datumName);\n        const string& indexName = tokens[2];\n        const string& expiry = tokens[3];\n        return boost::make_shared<IndexCDSOptionQuote>(value, asof, datumName, indexName, expiry);\n    }\n\n    case MarketDatum::InstrumentType::COMMODITY_SPOT: {\n        QL_REQUIRE(tokens.size() == 4, \"4 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::PRICE, \"Invalid quote type for \" << datumName);\n\n        return boost::make_shared<CommoditySpotQuote>(value, asof, datumName, quoteType, tokens[2], tokens[3]);\n    }\n\n    case MarketDatum::InstrumentType::COMMODITY_FWD: {\n        QL_REQUIRE(tokens.size() == 5, \"5 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::PRICE, \"Invalid quote type for \" << datumName);\n\n        Date expiryDate = getDateFromDateOrPeriod(tokens[4], asof);\n        return boost::make_shared<CommodityForwardQuote>(value, asof, datumName, quoteType, tokens[2], tokens[3],\n                                                         expiryDate);\n    }\n\n    case MarketDatum::InstrumentType::COMMODITY_OPTION: {\n        // Expects the following form:\n        // COMMODITY_OPTION/RATE_LNVOL/<COMDTY_NAME>/<CCY>/<DATE/TENOR>/<STRIKE>\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::RATE_LNVOL,\n                   \"Quote type for \" << datumName << \" should be 'RATE_LNVOL'\");\n\n        return boost::make_shared<CommodityOptionQuote>(value, asof, datumName, quoteType, tokens[2], tokens[3],\n                                                        tokens[4], tokens[5]);\n    }\n\n    case MarketDatum::InstrumentType::CORRELATION: {\n        // Expects the following form:\n        // CORRELATION/RATE/<INDEX1>/<INDEX2>/<TENOR>/<STRIKE>\n        QL_REQUIRE(tokens.size() == 6, \"6 tokens expected in \" << datumName);\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::RATE || quoteType == MarketDatum::QuoteType::PRICE,\n                   \"Quote type for \" << datumName << \" should be 'CORRELATION' or 'PRICE'\");\n\n        return boost::make_shared<CorrelationQuote>(value, asof, datumName, quoteType, tokens[2], tokens[3], tokens[4],\n                                                    tokens[5]);\n    }\n\n    case MarketDatum::InstrumentType::CPR: {\n        QL_REQUIRE(tokens.size() == 3, \"3 tokens expected in \" << datumName);\n        const string& securityID = tokens[2];\n        QL_REQUIRE(quoteType == MarketDatum::QuoteType::RATE, \"Invalid quote type for \" << datumName);\n        return boost::make_shared<CPRQuote>(value, asof, datumName, securityID);\n    }\n\n    default:\n        QL_FAIL(\"Cannot convert \\\"\" << datumName << \"\\\" to MarketDatum\");\n    } // switch instrument type\n} // parseMarketDatum\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "3aca4f4b9e3b4a0c595deb0e84afd9df49147817", "size": 26074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/marketdata/marketdatumparser.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": "OREData/ored/marketdata/marketdatumparser.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": "OREData/ored/marketdata/marketdatumparser.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": 49.7595419847, "max_line_length": 120, "alphanum_fraction": 0.6307432692, "num_tokens": 6558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.04885777498672153, "lm_q1q2_score": 0.01971737853190209}}
{"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_OB_TRAN_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_HPP\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/shared_ptr.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 ob_tran_oblique {};\n    //struct ob_tran_transverse {};\n    struct ob_tran {}; // General Oblique Transformation\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail {\n\n        // fwd declaration needed below\n        template <typename T>\n        inline detail::base_v<T, parameters<T> >*\n            create_new(parameters<T> const& parameters);\n\n    } // namespace detail\n\n    namespace detail { namespace ob_tran\n    {\n\n            static const double tolerance = 1e-10;\n\n            template <typename Parameters>\n            inline Parameters o_proj_parameters(Parameters const& par)\n            {\n                /* copy existing header into new */\n                Parameters pj = par;\n\n                /* get name of projection to be translated */\n                pj.name = pj_get_param_s(par.params, \"o_proj\");\n                if (pj.name.empty())\n                    BOOST_THROW_EXCEPTION( projection_exception(error_no_rotation_proj) );\n\n                /* avoid endless recursion */\n                if( pj.name == \"ob_tran\")\n                    BOOST_THROW_EXCEPTION( projection_exception(error_failed_to_find_proj) );\n\n                /* force spherical earth */\n                pj.one_es = pj.rone_es = 1.;\n                pj.es = pj.e = 0.;\n\n                return pj;\n            }\n\n            template <typename T, typename Parameters>\n            struct par_ob_tran\n            {\n                par_ob_tran(Parameters const& par)\n                    : link(projections::detail::create_new(o_proj_parameters(par)))\n                {\n                    if (! link.get())\n                        BOOST_THROW_EXCEPTION( projection_exception(error_unknown_projection_id) );\n                }\n\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    link->fwd(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    link->inv(xy_x, xy_y, lp_lon, lp_lat);\n                }\n\n                boost::shared_ptr<base_v<T, Parameters> > link;\n                T lamp;\n                T cphip, sphip;\n            };\n\n            template <typename StaticParameters, typename T, typename Parameters>\n            struct par_ob_tran_static\n            {\n                // this metafunction handles static error handling\n                typedef typename srs::par4::detail::pick_o_proj_tag\n                    <\n                        StaticParameters\n                    >::type o_proj_tag;\n\n                /* avoid endless recursion */\n                static const bool is_o_proj_not_ob_tran = ! boost::is_same<o_proj_tag, srs::par4::ob_tran>::value;\n                BOOST_MPL_ASSERT_MSG((is_o_proj_not_ob_tran), INVALID_O_PROJ_PARAMETER, (StaticParameters));\n\n                typedef typename projections::detail::static_projection_type\n                    <\n                        o_proj_tag,\n                        srs_sphere_tag, // force spherical\n                        StaticParameters,\n                        T,\n                        Parameters\n                    >::type projection_type;\n\n                par_ob_tran_static(Parameters const& par)\n                    : link(o_proj_parameters(par))\n                {}\n\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    link.fwd(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    link.inv(xy_x, xy_y, lp_lon, lp_lat);\n                }\n\n                projection_type link;\n                T lamp;\n                T cphip, sphip;\n            };\n\n            template <typename T, typename Par>\n            inline void o_forward(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y, Par const& proj_parm)\n            {\n                T coslam, sinphi, cosphi;\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), proj_parm.sphip * cosphi * coslam +\n                    proj_parm.cphip * sinphi) + proj_parm.lamp);\n                lp_lat = aasin(proj_parm.sphip * sinphi - proj_parm.cphip * cosphi * coslam);\n\n                proj_parm.fwd(lp_lon, lp_lat, xy_x, xy_y);\n            }\n\n            template <typename T, typename Par>\n            inline void o_inverse(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat, Par const& proj_parm)\n            {\n                T coslam, sinphi, cosphi;\n\n                proj_parm.inv(xy_x, xy_y, lp_lon, lp_lat);\n                if (lp_lon != HUGE_VAL) {\n                    coslam = cos(lp_lon -= proj_parm.lamp);\n                    sinphi = sin(lp_lat);\n                    cosphi = cos(lp_lat);\n                    lp_lat = aasin(proj_parm.sphip * sinphi + proj_parm.cphip * cosphi * coslam);\n                    lp_lon = aatan2(cosphi * sin(lp_lon), proj_parm.sphip * cosphi * coslam -\n                        proj_parm.cphip * sinphi);\n                }\n            }\n\n            template <typename T, typename Par>\n            inline void t_forward(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y, Par const& proj_parm)\n            {\n                T cosphi, coslam;\n\n                cosphi = cos(lp_lat);\n                coslam = cos(lp_lon);\n                lp_lon = adjlon(aatan2(cosphi * sin(lp_lon), sin(lp_lat)) + proj_parm.lamp);\n                lp_lat = aasin(- cosphi * coslam);\n\n                proj_parm.fwd(lp_lon, lp_lat, xy_x, xy_y);\n            }\n\n            template <typename T, typename Par>\n            inline void t_inverse(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat, Par const& proj_parm)\n            {\n                T cosphi, t;\n\n                proj_parm.inv(xy_x, xy_y, lp_lon, lp_lat);\n                if (lp_lon != HUGE_VAL) {\n                    cosphi = cos(lp_lat);\n                    t = lp_lon - proj_parm.lamp;\n                    lp_lon = aatan2(cosphi * sin(t), - sin(lp_lat));\n                    lp_lat = aasin(cosphi * cos(t));\n                }\n            }\n\n            // General Oblique Transformation\n            template <typename T, typename Parameters, typename ProjParameters>\n            inline T setup_ob_tran(Parameters & par, ProjParameters& proj_parm)\n            {\n                static const T half_pi = detail::half_pi<T>();\n\n                T phip, alpha;\n\n                par.es = 0.; /* force to spherical */\n\n                // proj_parm.link should be created at this point\n\n                if (pj_param_r(par.params, \"o_alpha\", alpha)) {\n                    T lamc, phic;\n\n                    lamc    = pj_get_param_r(par.params, \"o_lon_c\");\n                    phic    = pj_get_param_r(par.params, \"o_lat_c\");\n                    //alpha   = pj_get_param_r(par.params, \"o_alpha\");\n\n                    if (fabs(fabs(phic) - half_pi) <= tolerance)\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_0_or_alpha_eq_90) );\n\n                    proj_parm.lamp = lamc + aatan2(-cos(alpha), -sin(alpha) * sin(phic));\n                    phip = aasin(cos(phic) * sin(alpha));\n                } else if (pj_param_r(par.params, \"o_lat_p\", phip)) { /* specified new pole */\n                    proj_parm.lamp = pj_get_param_r(par.params, \"o_lon_p\");\n                    //phip = pj_param_r(par.params, \"o_lat_p\");\n                } else { /* specified new \"equator\" points */\n                    T lam1, lam2, phi1, phi2, con;\n\n                    lam1 = pj_get_param_r(par.params, \"o_lon_1\");\n                    phi1 = pj_get_param_r(par.params, \"o_lat_1\");\n                    lam2 = pj_get_param_r(par.params, \"o_lon_2\");\n                    phi2 = pj_get_param_r(par.params, \"o_lat_2\");\n                    if (fabs(phi1 - phi2) <= tolerance || (con = fabs(phi1)) <= tolerance ||\n                        fabs(con - half_pi) <= tolerance || fabs(fabs(phi2) - half_pi) <= tolerance)\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_1_or_2_zero_or_90) );\n\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\n                if (fabs(phip) > tolerance) { /* oblique */\n                    proj_parm.cphip = cos(phip);\n                    proj_parm.sphip = sin(phip);\n                } else { /* transverse */\n                }\n\n                // TODO:\n                /* Support some rather speculative test cases, where the rotated projection */\n                /* is actually latlong. We do not want scaling in that case... */\n                //if (proj_parm.link...mutable_parameters().right==PJ_IO_UNITS_ANGULAR)\n                //    par.right = PJ_IO_UNITS_PROJECTED;\n\n                // return phip to choose model\n                return phip;\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_ob_tran_oblique\n                : public base_t_fi<base_ob_tran_oblique<T, Parameters>, T, Parameters>\n            {\n                par_ob_tran<T, Parameters> m_proj_parm;\n\n                inline base_ob_tran_oblique(Parameters const& par,\n                                            par_ob_tran<T, Parameters> const& proj_parm)\n                    : base_t_fi\n                        <\n                            base_ob_tran_oblique<T, Parameters>, T, Parameters\n                        >(*this, par)\n                    , m_proj_parm(proj_parm)\n                {}\n\n                // FORWARD(o_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                    o_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                }\n\n                // INVERSE(o_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                    o_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\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 T, typename Parameters>\n            struct base_ob_tran_transverse\n                : public base_t_fi<base_ob_tran_transverse<T, Parameters>, T, Parameters>\n            {\n                par_ob_tran<T, Parameters> m_proj_parm;\n\n                inline base_ob_tran_transverse(Parameters const& par,\n                                               par_ob_tran<T, Parameters> const& proj_parm)\n                    : base_t_fi\n                        <\n                            base_ob_tran_transverse<T, Parameters>, T, Parameters\n                        >(*this, par)\n                    , m_proj_parm(proj_parm)\n                {}\n\n                // FORWARD(t_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                    t_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                }\n\n                // INVERSE(t_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                    t_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ob_tran_transverse\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename StaticParameters, typename T, typename Parameters>\n            struct base_ob_tran_static\n                : public base_t_fi<base_ob_tran_static<StaticParameters, T, Parameters>, T, Parameters>\n            {\n                par_ob_tran_static<StaticParameters, T, Parameters> m_proj_parm;\n                bool m_is_oblique;\n\n                inline base_ob_tran_static(Parameters const& par)\n                    : base_t_fi<base_ob_tran_static<StaticParameters, T, Parameters>, T, Parameters>(*this, par)\n                    , m_proj_parm(par)\n                {}\n\n                // FORWARD(o_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                    if (m_is_oblique) {\n                        o_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                    } else {\n                        t_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                    }\n                }\n\n                // INVERSE(o_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                    if (m_is_oblique) {\n                        o_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\n                    } else {\n                        t_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ob_tran\";\n                }\n\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 T, typename Parameters>\n    struct ob_tran_oblique : public detail::ob_tran::base_ob_tran_oblique<T, Parameters>\n    {\n        inline ob_tran_oblique(Parameters const& par,\n                               detail::ob_tran::par_ob_tran<T, Parameters> const& proj_parm)\n            : detail::ob_tran::base_ob_tran_oblique<T, Parameters>(par, proj_parm)\n        {\n            // already done\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 T, typename Parameters>\n    struct ob_tran_transverse : public detail::ob_tran::base_ob_tran_transverse<T, Parameters>\n    {\n        inline ob_tran_transverse(Parameters const& par,\n                                  detail::ob_tran::par_ob_tran<T, Parameters> const& proj_parm)\n            : detail::ob_tran::base_ob_tran_transverse<T, Parameters>(par, proj_parm)\n        {\n            // already done\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 StaticParameters, typename T, typename Parameters>\n    struct ob_tran_static : public detail::ob_tran::base_ob_tran_static<StaticParameters, T, Parameters>\n    {\n        inline ob_tran_static(const Parameters& par)\n            : detail::ob_tran::base_ob_tran_static<StaticParameters, T, Parameters>(par)\n        {\n            T phip = detail::ob_tran::setup_ob_tran<T>(this->m_par, this->m_proj_parm);\n            this->m_is_oblique = fabs(phip) > detail::ob_tran::tolerance;\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        template <typename BGP, typename CT, typename P>\n        struct static_projection_type<srs::par4::ob_tran, srs_sphere_tag, BGP, CT, P>\n        {\n            typedef ob_tran_static<BGP, CT, P> type;\n        };\n        template <typename BGP, typename CT, typename P>\n        struct static_projection_type<srs::par4::ob_tran, srs_spheroid_tag, BGP, CT, P>\n        {\n            typedef ob_tran_static<BGP, CT, P> type;\n        };\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class ob_tran_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    Parameters params = par;\n                    detail::ob_tran::par_ob_tran<T, Parameters> proj_parm(params);\n                    T phip = detail::ob_tran::setup_ob_tran<T>(params, proj_parm);\n\n                    if (fabs(phip) > detail::ob_tran::tolerance)\n                        return new base_v_fi<ob_tran_oblique<T, Parameters>, T, Parameters>(params, proj_parm);\n                    else\n                        return new base_v_fi<ob_tran_transverse<T, Parameters>, T, Parameters>(params, proj_parm);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void ob_tran_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"ob_tran\", new ob_tran_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_OB_TRAN_HPP\n", "meta": {"hexsha": "33ff22c7671fbc60ef10a19be1988bb56946917d", "size": 22384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/proj/ob_tran.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/ob_tran.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/ob_tran.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": 39.6879432624, "max_line_length": 114, "alphanum_fraction": 0.5500357398, "num_tokens": 4924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.042722200593555464, "lm_q1q2_score": 0.01969565132277565}}
{"text": "//projection1d.cpp\n/*\n* the projection1d class impl\n* (C) 2004 olegabr. All rights reserved.\n*/\n#include \"projection1d.h\"\n#include \"ro_filtrate.h\"\n\n#include <iostream>\nusing std::cout; using std::endl;\n\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <cassert>\n\n#include <boost/lambda/lambda.hpp>\n\nprojection1d::projection1d(size1d_t size, point1d point_size)\n\t: size_(size), point_size_(point_size)\n{\n\t//cout << \"projection1d(size)\" << endl;\n\tdata_.reserve(size);\n\tstd::fill_n\n\t\t(\n\t\t\tstd::back_inserter(data_),\n\t\t\tsize,\n\t\t\t0.\n\t\t);\n\n\t//data_.resize(size_);\n\t//clear();\n}\n\nprojection1d::projection1d(const projection1d& other)\n\t: size_(other.size_), point_size_(other.point_size_)\n{\n\t//cout << \"projection1d(projection1d)\" << endl;\n\tif (&other != this)\n\t{\n\t\tif (data_.size() < other.data_.size())\n\t\t{\n\t\t\t//cout << \"projection1d(projection1d): data_.resize\\n\";\n\t\t\t\t//<< \"data_.size() = \" << data_.size() << endl\n\t\t\t\t//<< \"other.data_.size() = \" << other.data_.size() << endl;\n\t\t\tdata_.resize(size_);\n\t\t}\n\t\tstd::copy(other.data_.begin(), other.data_.end(), data_.begin());\n\t}\n}\nprojection1d& projection1d::operator =(const projection1d& other)\n{\n\t//cout << \"projection1d::operator =(const projection1d& other)\" << endl;\n\tif (&other != this)\n\t{\n\t\tpoint_size_ = other.point_size_;\n\t\tsize_ = other.size_;\n\n\t\tif (data_.size() < other.data_.size())\n\t\t{\n\t\t\t//cout << \"projection1d::operator =(projection1d): data_.resize\\n\";\n\t\t\t\t//<< \"data_.size() = \" << data_.size() << endl\n\t\t\t\t//<< \"other.data_.size() = \" << other.data_.size() << endl;\n\t\t\tdata_.resize(size_);\n\t\t}\n\t\tstd::copy(other.data_.begin(), other.data_.end(), data_.begin());\n\t}\n\treturn *this;\n}\n\n//g = f-g\nprojection1d& projection1d::assign_difference(const projection1d& f_)\n{\n\tassert(f_.point_size_ == point_size_);\n\n\tprojection1d::data_type::difference_type\n\t\tw = (f_.size_ - size_)/2;\n\tprojection1d::iterator\n\t\tp  =    data_.begin(),  e =    data_.end();\n\tprojection1d::const_iterator\n\t\tfp = f_.data_.begin(), fe = f_.data_.end();\n\tif (w > 0)      std::advance(fp,  w);\n\telse if (w < 0) std::advance( p, -w);\n\tfor(; p != e && fp != fe; ++p, ++fp) *p = *fp - *p;\n\n\treturn *this;\n}\n\nstd::ostream& operator <<(std::ostream& os, const projection1d& sh)\n{\n\tstd::copy\n\t(\n\t\tsh.data_.begin(), sh.data_.end(),\n\t\tstd::ostream_iterator<projection1d::value_type>(os, \"\\t\")\n\t);\n\treturn os;\n}\n\nvoid projection1d::clear()\n{\n\tstd::fill(data_.begin(), data_.end(), 0.0);\n}\n\nvoid projection1d::ro_filtrate()\n{\n\tutil::ro_filtrate(data_);\n\tif (point_size_ != 1)\n\t\tstd::transform\n\t\t(\n\t\t\tdata_.begin(), data_.end(),\n\t\t\tdata_.begin(),\n\t\t\tboost::lambda::_1/point_size_\n\t\t);\n}\n\npoint1d projection1d::get_point_gt(point1d l) const\n{\n\treturn get_Rmin_() + point_size_*std::ceil((l-get_Rmin_())/point_size_);\n}\n\npixel1d projection1d::point2index_(point1d R) const\n{\n\treturn static_cast<pixel1d>(util::round((R - get_Rmin_())/point_size_));\n}\n\nvoid projection1d::add_value(pixel1d i, projection1d::value_type value)\n{\n\tif (in_grid(i, size_)) data_[i] += value;\n}\n\nvoid projection1d::add_value(point1d R, projection1d::value_type value)\n{\n\tadd_value(point2index_(R), value);\n}\n\nvoid projection1d::set_value(pixel1d i, projection1d::value_type value)\n{\n\tif (in_grid(i, size_)) data_[i] = value;\n}\n\nvoid projection1d::set_value(point1d R, projection1d::value_type value)\n{\n\tset_value(point2index_(R), value);\n}\n\nprojection1d::value_type projection1d::get_value(pixel1d i) const\n{\n\tassert(in_grid(i, size_));\n\treturn data_[i];\n}\n\nprojection1d::value_type\noperator *(const projection1d& sh, const projection1d& fsh)\n{\n\tassert(sh.get_size()       == fsh.get_size()      );\n\tassert(sh.get_point_size() == fsh.get_point_size());\n\n\tprojection1d::const_iterator\n\t\tis = sh.data_.begin(), e = sh.data_.end(), ifs = fsh.data_.begin();\n\treturn\n\t\t(\n\t\t\t.5*(*is * *ifs + *sh.data_.rbegin() * *fsh.data_.rbegin()) +\n\t\t\tstd::inner_product (++is, --e, ++ifs, 0.)\n\t\t)*sh.get_point_size();\n}\n\nstd::pair<projection1d::value_type, projection1d::value_type>\nprojection1d::get_min_max_() const\n{\n\t/* named return value optimization :) */\n\tstd::pair<projection1d::value_type, projection1d::value_type>\n\t\tresult(*std::min_element(data_.begin(), data_.end()), *std::max_element(data_.begin(), data_.end()));\n\treturn result;\n}\n", "meta": {"hexsha": "6fa6f9bae8987c4ccbb3c8cf1f5cd3be1188965f", "size": 4242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libtomo3d/src/projection1d.cpp", "max_stars_repo_name": "olegabr/tomo3d", "max_stars_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-01-07T12:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T06:58:42.000Z", "max_issues_repo_path": "libtomo3d/src/projection1d.cpp", "max_issues_repo_name": "olegabr/tomo3d", "max_issues_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libtomo3d/src/projection1d.cpp", "max_forks_repo_name": "olegabr/tomo3d", "max_forks_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T10:22:13.000Z", "avg_line_length": 24.24, "max_line_length": 103, "alphanum_fraction": 0.6659594531, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.04535257571563244, "lm_q1q2_score": 0.01968217790572407}}
{"text": "\n#ifndef MTL_DIST_BLOCK_DIAGONAL2D_INCLUDE\n#define MTL_DIST_BLOCK_DIAGONAL2D_INCLUDE\n\n\n\n#include <vector>\n#include <cassert>\n#include <limits>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/bool.hpp>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/assert.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/numeric/mtl/matrix/mat_expr.hpp>\n\n\nnamespace mtl {\n\n  namespace mat {\n    \n\n/// Block diagonal matrix structure\n/** Blocks can be any existing matrix_type in mtl4. **/\ntemplate <typename Matrix>\nclass block_diagonal2D \n  : public mat_expr< block_diagonal2D<Matrix> >\n{\n  public:\n \n    typedef unsigned int\t      size_type;\n    typedef Matrix\t\t      block_type;\n    typedef std::vector<Matrix>       block_matrix_type;\n    typedef std::vector<size_type>    index_vector_type;\n    typedef block_diagonal2D<Matrix>  self;\n    typedef typename Collection<Matrix>::value_type value_type;\n\n    /// Constructor: number or rows and columns and optionally estimated number of blocks\n    explicit block_diagonal2D(size_type rows, size_type cols, size_type init_size= 0)\n      : nrows(rows), ncols(cols), nb_blocks(0), my_nnz(0),\n\tmin_ind(std::numeric_limits<size_type>::max()), max_ind(std::numeric_limits<size_type>::min()),\n\tcompact_heap(0)\n    {\n\tstart_block.reserve(init_size); \n\tend_block.reserve(init_size); \n\tblocks.reserve(init_size);\n    }\n\n    ~block_diagonal2D() { delete[] compact_heap; }\n\n    /// Returns the global number of rows\n    size_type num_rows() const {\n\treturn nrows ;\n    }\n    /// Returns the global number of coluums\n    size_type num_cols() const {\n\treturn ncols ;\n    }\n    /// Returns the global number of blocks\n    size_type num_blocks() const {\n\treturn  nb_blocks; \n    }\n\n    /// Minimal index\n    size_type min_index() const { return min_ind; }\n\n    /// Maximal index\n    size_type max_index() const { return max_ind; }\n\n\n    block_type const& block(size_type i) const\n    {\n\tMTL_CRASH_IF(is_negative(i) || i >= nb_blocks, \"Index out of range!\");\n\treturn blocks[i];\n    }\n\n    /// Insert a block from start x start to end x end\n    void insert(size_type start, size_type end, const block_type& A) \n    {\n\tMTL_CRASH_IF(start > end, \"Logic error\");\n\tMTL_CRASH_IF(is_negative(start) || end > nrows || end > ncols, \"Index out of range!\");\n\tassert(compact_heap == 0); // insertion after make_compact; might be relaxed later\n    \n\tstart_block.push_back(start);\n\tend_block.push_back(end);\n\tblocks.push_back(A); \n\tmy_nnz+= size_type(A.nnz());\n\tnb_blocks++;\n\t\n\tif (start < min_ind)\n\t    min_ind= start;\n\tif (end > max_ind)\n\t    max_ind= end;\n#if 0\n\tboost::mpi::communicator world;\n\tif (world.rank() == 0) {\n\t    std::cout << \"block_diag.insert \" << nb_blocks-1 << \"th block: start == \"\n\t\t      << start_block << \", end == \" << end_block << \"block is:\\n\"\n\t\t      << blocks.back();\n\t}\n#endif\n    } \n\n    /// Element A[i][j] by summing over all blocks, use only for debugging because it is very slow\n    value_type operator()(size_type i, size_type j) const\n    {\n\tvalue_type s= value_type(0);\n\tfor (std::size_t b= 0; b < blocks.size(); ++b) {\n\t    size_type st= start_block[b], e= end_block[b];\n\t    if (st <= i && st <= j && i < e && j < e)\n\t\ts+= blocks[b][i - st][j - st];\n\t}\n\treturn s;\n    }\n \n    /// Memory of inserted \n    void make_compact(boost::mpl::true_)\n    {\n\tassert(compact_heap == 0); // might be relaxed later\n\t\n\tsize_type entries= 0;\n\tfor (size_type i= 0; i < nb_blocks; i++)\n\t    entries+= size(blocks[i]);\n\tcompact_heap= new value_type[entries];\n\n\tsize_type pos= 0;\n\tfor (size_type i= 0; i < nb_blocks; i++) {\n\t    size_type s= end_block[i] - start_block[i];\n\t    block_type tmp(s, s, compact_heap + pos);\n\t    tmp= blocks[i];\n\t    pos+= size(blocks[i]);\n\t    swap(blocks[i], tmp);\n\t}\n\tassert(pos == entries);\n    }\n    void make_compact(boost::mpl::false_) {}\n\n    void make_compact() { make_compact(boost::is_same<typename mtl::traits::category<block_type>::type, tag::dense2D>()); }\n \n    /// Number of non-zeros (accumulated over blocks)\n    size_type nnz() const { return my_nnz; }\n\n    template <typename VectorIn, typename VectorOut>\n    void add_mult(const VectorIn& x, VectorOut& y) const \n    {\n\tmtl::vampir_trace<3062> tracer;\n\tMTL_CRASH_IF(ncols != size(x) || nrows != size(y), \"Incompatible size!\"); \n\n\t// set_to_zero(y);\n\tfor(size_type i= 0; i < nb_blocks; i++) {\n\t    mtl::irange r(start_block[i], end_block[i]);\n\t    y[r]+= blocks[i] * x[r];\n\t}\n    }\n\n    ///block_diagonal-matrix  times cvec\n    template <typename VectorIn, typename VectorOut>\n    void mult(const VectorIn& x, VectorOut& y) const \n    {\n\tmtl::vampir_trace<3062> tracer;\n\tMTL_CRASH_IF(ncols != size(x) || nrows != size(y), \"Incompatible size!\"); \n\n\tset_to_zero(y);\n\tfor(size_type i= 0; i < nb_blocks; i++) {\n\t    mtl::irange r(start_block[i], end_block[i]);\n\t    y[r]= blocks[i] * x[r];\n\t}\n    }\n\n    template <typename VectorIn>\n    struct multiplier\n      : mtl::vec::assigner<multiplier<VectorIn> >\n    {\n\texplicit multiplier(const self& P, const VectorIn& x) : P(P), x(x) {}\n\n\ttemplate <typename VectorOut>\n\tvoid assign_to(VectorOut& y) const\n\t{   P.mult(x, y); }\n\t\n\tconst self& P;\n\tconst VectorIn& x;\n    };\n  \n \n    template <typename VectorIn>\n    multiplier<VectorIn> operator*(const VectorIn& x) // const\n    {  return multiplier<VectorIn>(*this, x); }\n\n\n  private:\n    size_type           nrows, ncols, nb_blocks, my_nnz, min_ind, max_ind;\n    index_vector_type  \tstart_block, end_block;\n    block_matrix_type   blocks;\n    value_type*         compact_heap; \n};\n\n// ================\n// Free functions\n// ================\n\n\n/// Number of rows\ntemplate <typename Value>\ntypename block_diagonal2D<Value>::size_type\ninline num_rows(const block_diagonal2D<Value>& matrix)\n{\n    return matrix.num_rows();\n}\n\n/// Number of columns\ntemplate <typename Value>\ntypename block_diagonal2D<Value>::size_type\ninline num_cols(const block_diagonal2D<Value>& matrix)\n{\n    return matrix.num_cols();\n}\n\n/// Size of the matrix, i.e. the number of row times columns\ntemplate <typename Value>\ntypename block_diagonal2D<Value>::size_type\ninline size(const block_diagonal2D<Value>& matrix)\n{\n    return matrix.num_cols() * matrix.num_rows();\n}\n\n// /// Distributed Vector of start block entrys in the matrix\n// template <typename Value>\n// typename block_diagonal2D<Value>::index_type\n// inline start(const block_diagonal2D<Value>& matrix)\n// {\n//     return matrix.start();\n// }\n\n// /// Distributed Vector of en block entrys in the matrix\n// template <typename Value>\n// typename block_diagonal2D<Value>::index_type\n// inline end(const block_diagonal2D<Value>& matrix)\n// {\n//     return matrix.end();\n// }\n\n\n\n\n} // namespace matrix\n} // namespace mtl\n\n#endif // MTL_DIST_BLOCK_DIAGONAL2D_INCLUDE\n\n", "meta": {"hexsha": "cdd07e4476186f4190cccabf0ecb27d662687096", "size": 7016, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/matrix/block_diagonal2D.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/block_diagonal2D.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/block_diagonal2D.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": 27.40625, "max_line_length": 123, "alphanum_fraction": 0.6703249715, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.04742586981164345, "lm_q1q2_score": 0.019676937959530447}}
{"text": "/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n#include <boost/numeric/ublas/lu.hpp>\n#if USE_LAPACK\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/lapack/gesvd.hpp>\n#endif\n#include <boost/numeric/ublas/operation.hpp>\n#include \"solution/util/include/functor-subs.hpp\"\n#include \"solution/util/include/fdjac.hpp\" \n#include \"util/base/include/util.h\"\n#include \"solution/util/include/ublas-helpers.hpp\"\n\n#include \"solution/util/include/svd_invert_solve.hpp\"\n#include \"solution/util/include/jacobian-precondition.hpp\"\n\n#include \"util/base/include/timer.h\"\n\n#if USE_LAPACK\n#define UBMATRIX boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major>\n#else\n#define UBMATRIX boost::numeric::ublas::matrix<double>\n#endif\n#define UBVECTOR boost::numeric::ublas::vector<double> \n\n\n/* ensure that markets going into a solver that uses a jacobian start\n   off in price regimes that produce nonsingular jacobians. */\nint jacobian_precondition(UBVECTOR &x, UBVECTOR &fx, UBMATRIX &J, VecFVec<double,double> &F,\n                          std::ostream *diagnostic, bool loginputsp, double FTOL)\n{\n  const double JPCMIN = util::getVerySmallNumber(); // if max column value is less than this, the column is \"singular\".\n  const double JPCLOGINCR = 1.0;   // corresponds to an e-fold increase in price if x is a log-price.  This must always be >0\n  const double JPCLINEARFAC = 2.0; // This must always be >1.\n  const int ITMAX = 50;\n  int fail = 0;\n  int change = 0;\n  int ncol = (int) x.size();\n\n  Timer& jacPreTimer = TimerRegistry::getInstance().getTimer( TimerRegistry::JAC_PRE );\n  jacPreTimer.start();\n  UBVECTOR fxx(fx),fxdiff(fx.size()); // fxx = last distinct value of F(x)\n  \n  \n  /* We will focus on ill-conditioning that results from an entire\n     column of (nearly) zero entries.  This corresponds to a situation\n     where changing a price doesn't affect the ED of any market in the\n     calculation.  This situation comes up rather frequently when, for\n     instance, a market is below the turn-on price for its supply\n     curve, and it can often be fixed by changing the starting price.\n\n  */\n\n  for(int j=0; j<ncol; ++j) {\n    // Restrict our attention to the diagonal term.  If it's\n    // (effectively) zero, then we're in a bad part of the parameter\n    // space.\n    double diagval = fabs(J(j,j));\n\n    if(diagnostic) {\n        (*diagnostic) << \"\\tj= \" << j << \"  x[j] = \" << x[j] << \"  fx[j]= \" << fx[j] << \"  J(j,j) = \" << J(j,j)\n                      << std::endl;\n    }\n    \n    if(diagval < JPCMIN && fabs(fx[j]) > FTOL) {\n        // Tiny derivative on the diagonal, which will likely cause\n        // the Jacobian to be singular.  If fx[j] is nearly zero,\n        // ignore it (we'll deal with it later).  Otherwise, search\n        // for a price that is giving us a reasonable derivative.\n        double incr;\n        double t = x[j];          // store the original value\n        // the diagonal element is zero, so we must try to find a price that makes it nonzero\n\n        // We have to guess which way to go to get to a viable price\n        // regime. We'll use the current excess demand as our guide.\n        // If ED>0, our price is probably at the low end, so we will\n        // search upward in price.  Otherwise, we'll search downward\n        if(loginputsp) {\n          // for log inputs this additive increment will actually be a\n          // multiplicative change in the price value\n          if(fx[j] > 0)\n            incr = JPCLOGINCR;\n          else\n            incr = -JPCLOGINCR;\n        }\n        else {\n          // for linear inputs things are a little more complicated.\n          // For the most part we still want a multiplicative change,\n          // but we need to be careful when the absolute value of the\n          // price is low, and we need to make sure that the price moves\n          // in the correct direction when the price is negative.\n        \n          // You might have noticed that we make no effort to make the\n          // treatment of positive and negative values symmetric.  That\n          // is, for positive prices we multiply the price if we want to\n          // increase it, and we divide it if we want to decrease it.\n          // But for negative prices we add the same increment that we\n          // would add to a positive price of the same absolute value to\n          // increase it, and likewise for subtraction.  That's because\n          // negative prices should be unusual, and if we're seeing zero\n          // derivatives for negative prices, then we probably don't\n          // need to be in negative price territory.  Therefore, the big\n          // steps are always in the positive direction, and the small\n          // steps are always in the negative direction.\n          if(fx[j] > 0) {\n            // want to increase the price.  JPCLINEARFAC is supposed to\n            // be a multiplier, but we're going to calculate an\n            // equivalent adder here.  That way we can be certain that a\n            // positive number always corresponds to an increase.\n            incr = (JPCLINEARFAC-1.0) * std::max(fabs(x[j]), 1.0);\n          }\n          else {\n            // want to decrease the price.  Note that the first term\n            // gives us the correct sign for the increment.\n            incr = (1.0/JPCLINEARFAC - 1.0) * std::max(fabs(x[j]), 1.0);\n          }\n        }\n\n        if(diagnostic)\n          (*diagnostic) << \"Searching j= \" << j << \"  x[j] = \" << x[j] << \"  fx[j] = \" << fxx[j]\n                        << \"  J(j,j) = \" << J(j,j) << \"  incr = \" << incr << \"\\n\";\n      \n        int count = 0;\n        double deltafx=0.0;\n        do {\n          x[j] += incr;\n          \n          F(x,fx);\n          deltafx = fabs(fxx[j]-fx[j]);\n\n          if(diagnostic)\n            (*diagnostic) << \"\\txtry = \" << x[j] << \"  fxtry = \" << fx[j] << \"\\n\";\n        \n          if(deltafx > JPCMIN) {\n            change = 1;\n            // success (probably -- it's theoretically possible we\n            // jumped completely over the \"good\" range of the\n            // parameters.  We'll add checks for that (only) if it looks like\n            // it's becoming a problem.)\n            fxx = fx;\n          }\n        } while(deltafx < JPCMIN && ++count < ITMAX);\n\n        if(deltafx < JPCMIN) {\n          fail = 1;\n          x[j] = t;               // restore the old value.\n          if(diagnostic)\n            (*diagnostic) << \"jacobian_preconditioner: Unable to find a good price for j= \" << j\n                          << \"  x[j]= \" << x[j] << \"  fx[j]= \" << fx[j] << \"\\n\";\n        }\n        else if(diagnostic) {\n          (*diagnostic) << \"jacobian_preconditioner: Revised initial guess for x[\" << j << \"] = \" << x[j] << \"\\n\";\n        } \n    }\n  }\n\n  Timer& jacPreJacTimer = TimerRegistry::getInstance().getTimer( TimerRegistry::JAC_PRE_JAC );\n  jacPreJacTimer.start();\n              \n  if(change)\n    fdjac(F,x,fx,J,true); // recalculate the jacobian\n\n  jacPreJacTimer.stop();\n  jacPreTimer.stop();\n\n  return fail;\n}\n\n\nvoid broyden_singular_B_reset(UBVECTOR &x, UBVECTOR &fx, UBMATRIX &B, VecFVec<double,double> &F,\n                             std::ostream *diagnostic, double FTOL)\n{\n  const double JPCMIN = util::getVerySmallNumber(); // if diagonal value is less than this, the column is \"singular\".\n\n  /* If we get a singular matrix in the Broyden solver, we have a\n     simple solution.  Since B is just an approximate Jacobian, and\n     since we know that \"normally\" an increase a market's in price\n     reduces excess demand in that market, we just set any deficient\n     diagonal terms to -JPCMIN and keep on trucking. */\n  int nrow = B.size1(), ncol = B.size2();\n\n  for(int j=0;j<nrow;++j)\n    if(fabs(B(j,j)) < JPCMIN && fabs(fx[j]) > FTOL) {\n      if(diagnostic)\n        (*diagnostic) << \"Resetting diagonal term at j = \" << j << \"  x = \" << x[j]\n                      << \"  fx = \" << fx[j] << \"  old B = \" << B(j,j) << \"\\n\";\n      B(j,j) = -JPCMIN;\n    }\n}\n\n", "meta": {"hexsha": "905e1f562f965874c66137a8398a995c9a423735", "size": 9634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/solution/util/source/jacobian-precondition.cpp", "max_stars_repo_name": "cmcormack/gcam-core", "max_stars_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-28T04:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T04:10:11.000Z", "max_issues_repo_path": "cvs/objects/solution/util/source/jacobian-precondition.cpp", "max_issues_repo_name": "cmcormack/gcam-core", "max_issues_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-30T21:13:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-14T13:21:13.000Z", "max_forks_repo_path": "cvs/objects/solution/util/source/jacobian-precondition.cpp", "max_forks_repo_name": "cmcormack/gcam-core", "max_forks_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-26T05:56:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T10:29:30.000Z", "avg_line_length": 43.3963963964, "max_line_length": 125, "alphanum_fraction": 0.626842433, "num_tokens": 2456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388515, "lm_q2_score": 0.04401865315498991, "lm_q1q2_score": 0.019611610721355276}}
{"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_CONCEPTS_\n#define _BOOST_UBLAS_CONCEPTS_\n\n#include <boost/concept_check.hpp>\n\n// Concept checks based on ideas of Jeremy Siek\n\nnamespace boost { namespace numeric { namespace ublas {\n\n\n    template<class I>\n    struct Indexed1DIteratorConcept {\n        typedef I iterator_type;\n\n        void constraints () {\n            iterator_type it = iterator_type ();\n            // Index\n            it.index ();\n        }\n    };\n\n    template<class I>\n    struct IndexedBidirectional1DIteratorConcept {\n        typedef I iterator_type;\n\n        void constraints () {\n            function_requires< BidirectionalIteratorConcept<iterator_type> >();\n            function_requires< Indexed1DIteratorConcept<iterator_type> >();\n        }\n    };\n\n    template<class I>\n    struct Mutable_IndexedBidirectional1DIteratorConcept {\n        typedef I iterator_type;\n\n        void constraints () {\n            function_requires< Mutable_BidirectionalIteratorConcept<iterator_type> >();\n            function_requires< Indexed1DIteratorConcept<iterator_type> >();\n        }\n    };\n\n    template<class I>\n    struct IndexedRandomAccess1DIteratorConcept {\n        typedef I iterator_type;\n\n        void constraints () {\n            function_requires< RandomAccessIteratorConcept<iterator_type> >();\n            function_requires< Indexed1DIteratorConcept<iterator_type> >();\n        }\n    };\n\n    template<class I>\n    struct Mutable_IndexedRandomAccess1DIteratorConcept {\n        typedef I iterator_type;\n\n        void constraints () {\n            function_requires< Mutable_RandomAccessIteratorConcept<iterator_type> >();\n            function_requires< Indexed1DIteratorConcept<iterator_type> >();\n        }\n    };\n\n    template<class I>\n    struct Indexed2DIteratorConcept {\n        typedef I iterator_type;\n        typedef typename I::dual_iterator_type dual_iterator_type;\n        typedef typename I::dual_reverse_iterator_type dual_reverse_iterator_type;\n\n        void constraints () {\n            iterator_type it = iterator_type ();\n            // Indices\n            it.index1 ();\n            it.index2 ();\n            // Iterator begin/end\n            dual_iterator_type it_begin (it.begin ());\n            dual_iterator_type it_end (it.end ());\n            // Reverse iterator begin/end\n            dual_reverse_iterator_type it_rbegin (it.rbegin ());\n            dual_reverse_iterator_type it_rend (it.rend ());\n            ignore_unused_variable_warning (it_begin);\n            ignore_unused_variable_warning (it_end);\n            ignore_unused_variable_warning (it_rbegin);\n            ignore_unused_variable_warning (it_rend);\n        }\n    };\n\n    template<class I1, class I2>\n    struct IndexedBidirectional2DIteratorConcept {\n        typedef I1 subiterator1_type;\n        typedef I2 subiterator2_type;\n\n        void constraints () {\n            function_requires< BidirectionalIteratorConcept<subiterator1_type> >();\n            function_requires< BidirectionalIteratorConcept<subiterator2_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator1_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator2_type> >();\n        }\n    };\n\n    template<class I1, class I2>\n    struct Mutable_IndexedBidirectional2DIteratorConcept {\n        typedef I1 subiterator1_type;\n        typedef I2 subiterator2_type;\n\n        void constraints () {\n            function_requires< Mutable_BidirectionalIteratorConcept<subiterator1_type> >();\n            function_requires< Mutable_BidirectionalIteratorConcept<subiterator2_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator1_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator2_type> >();\n        }\n    };\n\n    template<class I1, class I2>\n    struct IndexedRandomAccess2DIteratorConcept {\n        typedef I1 subiterator1_type;\n        typedef I2 subiterator2_type;\n\n        void constraints () {\n            function_requires< RandomAccessIteratorConcept<subiterator1_type> >();\n            function_requires< RandomAccessIteratorConcept<subiterator2_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator1_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator2_type> >();\n        }\n    };\n\n    template<class I1, class I2>\n    struct Mutable_IndexedRandomAccess2DIteratorConcept {\n        typedef I1 subiterator1_type;\n        typedef I2 subiterator2_type;\n\n        void constraints () {\n            function_requires< Mutable_RandomAccessIteratorConcept<subiterator1_type> >();\n            function_requires< Mutable_RandomAccessIteratorConcept<subiterator2_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator1_type> >();\n            function_requires< Indexed2DIteratorConcept<subiterator2_type> >();\n        }\n    };\n\n    template<class C>\n    struct StorageArrayConcept {\n        typedef C container_type;\n        typedef typename C::size_type size_type;\n        typedef typename C::value_type value_type;\n\n        void constraints () {\n            function_requires< RandomAccessContainerConcept<container_type> >();\n            size_type n (0);\n            // Sizing constructor\n            container_type c = container_type (n);\n            // Initialised sizing constructor\n            container_type (n, value_type (5));\n            ignore_unused_variable_warning (c);\n        }\n    };\n\n    template<class C>\n    struct Mutable_StorageArrayConcept {\n        typedef C container_type;\n        typedef typename C::size_type size_type;\n        typedef typename C::value_type value_type;\n        typedef typename C::iterator iterator_type;\n\n        void constraints () {\n            function_requires< Mutable_RandomAccessContainerConcept<container_type> > ();\n            size_type n (0);\n            // Sizing constructor\n            container_type c = container_type (n);\n            // Initialised sizing constructor\n            c = container_type (n, value_type (3));\n            // Resize\n            c.resize (n, value_type (5));\n            // Resize - none preserving\n            c.resize (n);\n        }\n    };\n\n    template<class C>\n    struct StorageSparseConcept {\n        typedef C container_type;\n        typedef typename C::size_type size_type;\n\n        void constraints () {\n            function_requires< ReversibleContainerConcept<container_type> > ();\n        }\n    };\n\n    template<class C>\n    struct Mutable_StorageSparseConcept {\n        typedef C container_type;\n        typedef typename C::size_type size_type;\n        typedef typename C::value_type value_type;\n        typedef typename C::iterator iterator_type;\n\n        void constraints () {\n            // NOTE - Not Mutable_ReversibleContainerConcept\n            function_requires< ReversibleContainerConcept<container_type> >();\n            container_type c = container_type ();\n            value_type t = value_type ();\n            iterator_type it = iterator_type (), it1 = iterator_type (), it2 = iterator_type ();\n            // Insert\n            c.insert (it, t);\n            // Erase\n            c.erase (it);\n            // Range erase\n            c.erase (it1, it2);\n            // Clear\n            c.clear ();\n        }\n    };\n\n    template<class G>\n    struct IndexSetConcept {\n        typedef G generator_type;\n        typedef typename G::size_type size_type;\n        typedef typename G::value_type value_type;\n\n        void constraints () {\n            function_requires< AssignableConcept<generator_type> >();\n            function_requires< ReversibleContainerConcept<generator_type> >();\n            generator_type g = generator_type ();\n            size_type n (0);\n            value_type t;\n            // Element access\n            t = g (n);\n            ignore_unused_variable_warning (t);\n        }\n    };\n\n    /** \\brief Scalar expression concept.\n     *\n     * requirements\n     * \\li \\c SE::value_type is the type of the scalar expression\n     * \\li \\c SE must be convertable to \\c SE::value_type\n     * \\li the constant \\c SE::complexity must exist\n     *\n     * \\param SE the type of the scalar expression\n     */\n    template<class SE>\n    struct ScalarExpressionConcept {\n        typedef SE scalar_expression_type;\n        typedef typename SE::value_type value_type;\n\n        static const unsigned complexity = SE::complexity;\n\n        void constraints () {\n            scalar_expression_type *sp;\n            scalar_expression_type s = *sp;\n            value_type t;\n            // Conversion\n            t = s;\n            ignore_unused_variable_warning (t);\n        }\n    };\n\n    /** \\brief Vector expression concept.\n     *\n     * requirements\n     * \\li \\c VE::value_type is the type of the elements\n     * \\li \\c VE::const_reference The return type when accessing an element of a constant vector\n     * expression. Must be convertable to a \\c value_type.\n     * \\li \\c VE::size_type is the (unsigned) type of the indices\n     * \\li \\c VE::difference_type is the (signed) type of distances between indices\n     * \\li \\c VE::category\n     *\n     * \\li the constant \\c SE::complexity must exist\n     *\n     * \\param SE the type of the scalar expression\n     */\n    template<class VE>\n    struct VectorExpressionConcept {\n        typedef VE vector_expression_type;\n        typedef typename VE::type_category type_category;\n        typedef typename VE::size_type size_type;\n        typedef typename VE::difference_type difference_type;\n        typedef typename VE::value_type value_type;\n        typedef typename VE::const_reference const_reference;\n        typedef typename VE::const_iterator const_iterator_type;\n        typedef typename VE::const_reverse_iterator const_reverse_iterator_type;\n\n        void constraints () {\n            vector_expression_type *vp;\n            const vector_expression_type *cvp;\n            vector_expression_type v = *vp;\n            const vector_expression_type cv = *cvp;\n            size_type n (0), i (0);\n            value_type t;\n            // Find (internal?)\n            const_iterator_type cit (v.find (i));\n            // Beginning of range\n            const_iterator_type cit_begin (v.begin ());\n            // End of range\n            const_iterator_type cit_end (v.end ());\n            // Size\n            n = v.size ();\n            // Beginning of reverse range\n            const_reverse_iterator_type crit_begin (cv.rbegin ());\n            // End of reverse range\n            const_reverse_iterator_type crit_end (cv.rend ());\n            // Element access\n            t = v (i);\n            ignore_unused_variable_warning (n);\n            ignore_unused_variable_warning (cit);\n            ignore_unused_variable_warning (cit_begin);\n            ignore_unused_variable_warning (cit_end);\n            ignore_unused_variable_warning (crit_begin);\n            ignore_unused_variable_warning (crit_end);\n            ignore_unused_variable_warning (t);\n        }\n    };\n\n    template<class VE>\n    struct Mutable_VectorExpressionConcept {\n        typedef VE vector_expression_type;\n        typedef typename VE::size_type size_type;\n        typedef typename VE::value_type value_type;\n        typedef typename VE::iterator iterator_type;\n        typedef typename VE::reverse_iterator reverse_iterator_type;\n\n        void constraints () {\n            function_requires< AssignableConcept<vector_expression_type> >();\n            function_requires< VectorExpressionConcept<vector_expression_type> >();\n            vector_expression_type *vp;\n            vector_expression_type v = *vp, v1 = *vp, v2 = *vp;\n            size_type i (0);\n            value_type t = value_type ();\n            // Find (internal?)\n            iterator_type it (v.find (i));\n            // Beginning of range\n            iterator_type it_begin (v.begin ());\n            // End of range\n            iterator_type it_end (v.end ());\n            // Swap\n            v1.swap (v2);\n            // Beginning of reverse range\n            reverse_iterator_type rit_begin (v.rbegin ());\n            // End of reverse range\n            reverse_iterator_type rit_end (v.rend ());\n            // Assignments\n            v2 = v1;\n            v2.assign (v1);\n            v2 += v1;\n            v2.plus_assign (v1);\n            v2 -= v1;\n            v2.minus_assign (v1);\n            v *= t;\n            ignore_unused_variable_warning (it);\n            ignore_unused_variable_warning (it_begin);\n            ignore_unused_variable_warning (it_end);\n            ignore_unused_variable_warning (rit_begin);\n            ignore_unused_variable_warning (rit_end);\n        }\n    };\n\n    template<class ME>\n    struct MatrixExpressionConcept {\n        typedef ME matrix_expression_type;\n        typedef typename ME::type_category type_category;\n        typedef typename ME::size_type size_type;\n        typedef typename ME::value_type value_type;\n        typedef typename ME::const_iterator1 const_subiterator1_type;\n        typedef typename ME::const_iterator2 const_subiterator2_type;\n        typedef typename ME::const_reverse_iterator1 const_reverse_subiterator1_type;\n        typedef typename ME::const_reverse_iterator2 const_reverse_subiterator2_type;\n\n        void constraints () {\n            matrix_expression_type *mp;\n            const matrix_expression_type *cmp;\n            matrix_expression_type m = *mp;\n            const matrix_expression_type cm = *cmp;\n            size_type n (0), i (0), j (0);\n            value_type t;\n            // Find (internal?)\n            const_subiterator1_type cit1 (m.find1 (0, i, j));\n            const_subiterator2_type cit2 (m.find2 (0, i, j));\n            // Beginning of range\n            const_subiterator1_type cit1_begin (m.begin1 ());\n            const_subiterator2_type cit2_begin (m.begin2 ());\n            // End of range\n            const_subiterator1_type cit1_end (m.end1 ());\n            const_subiterator2_type cit2_end (m.end2 ());\n            // Size\n            n = m.size1 ();\n            n = m.size2 ();\n            // Beginning of reverse range\n            const_reverse_subiterator1_type crit1_begin (cm.rbegin1 ());\n            const_reverse_subiterator2_type crit2_begin (cm.rbegin2 ());\n            // End of reverse range\n            const_reverse_subiterator1_type crit1_end (cm.rend1 ());\n            const_reverse_subiterator2_type crit2_end (cm.rend2 ());\n            // Element access\n            t = m (i, j);\n            ignore_unused_variable_warning (n);\n            ignore_unused_variable_warning (cit1);\n            ignore_unused_variable_warning (cit2);\n            ignore_unused_variable_warning (cit1_begin);\n            ignore_unused_variable_warning (cit2_begin);\n            ignore_unused_variable_warning (cit1_end);\n            ignore_unused_variable_warning (cit2_end);\n            ignore_unused_variable_warning (crit1_begin);\n            ignore_unused_variable_warning (crit2_begin);\n            ignore_unused_variable_warning (crit1_end);\n            ignore_unused_variable_warning (crit2_end);\n            ignore_unused_variable_warning (t);\n        }\n    };\n\n    template<class ME>\n    struct Mutable_MatrixExpressionConcept {\n        typedef ME matrix_expression_type;\n        typedef typename ME::size_type size_type;\n        typedef typename ME::value_type value_type;\n        typedef typename ME::iterator1 subiterator1_type;\n        typedef typename ME::iterator2 subiterator2_type;\n        typedef typename ME::reverse_iterator1 reverse_subiterator1_type;\n        typedef typename ME::reverse_iterator2 reverse_subiterator2_type;\n\n        void constraints () {\n            function_requires< AssignableConcept<matrix_expression_type> >();\n            function_requires< MatrixExpressionConcept<matrix_expression_type> >();\n            matrix_expression_type *mp;\n            matrix_expression_type m = *mp, m1 = *mp, m2 = *mp;\n            size_type i (0), j (0);\n            value_type t = value_type ();\n            // Find (internal?)\n            subiterator1_type it1 (m.find1 (0, i, j));\n            subiterator2_type it2 (m.find2 (0, i, j));\n            // Beginning of range\n            subiterator1_type it1_begin (m.begin1 ());\n            subiterator2_type it2_begin (m.begin2 ());\n            // End of range\n            subiterator1_type it1_end (m.end1 ());\n            subiterator2_type it2_end (m.end2 ());\n            // Swap\n            m1.swap (m2);\n            // Beginning of reverse range\n            reverse_subiterator1_type rit1_begin (m.rbegin1 ());\n            reverse_subiterator2_type rit2_begin (m.rbegin2 ());\n            // End of reverse range\n            reverse_subiterator1_type rit1_end (m.rend1 ());\n            reverse_subiterator2_type rit2_end (m.rend2 ());\n            // Assignments\n            m2 = m1;\n            m2.assign (m1);\n            m2 += m1;\n            m2.plus_assign (m1);\n            m2 -= m1;\n            m2.minus_assign (m1);\n            m *= t;\n            ignore_unused_variable_warning (it1);\n            ignore_unused_variable_warning (it2);\n            ignore_unused_variable_warning (it1_begin);\n            ignore_unused_variable_warning (it2_begin);\n            ignore_unused_variable_warning (it1_end);\n            ignore_unused_variable_warning (it2_end);\n            ignore_unused_variable_warning (rit1_begin);\n            ignore_unused_variable_warning (rit2_begin);\n            ignore_unused_variable_warning (rit1_end);\n            ignore_unused_variable_warning (rit2_end);\n        }\n    };\n\n    template<class V>\n    struct VectorConcept {\n        typedef V vector_type;\n        typedef typename V::size_type size_type;\n        typedef typename V::value_type value_type;\n        typedef const value_type *const_pointer;\n\n        void constraints () {\n            function_requires< VectorExpressionConcept<vector_type> >();\n            size_type n (0);\n            size_type i (0);\n            // Sizing constructor\n            vector_type v (n);\n            // Element support\n            const_pointer p = v.find_element (i);\n\n            ignore_unused_variable_warning (p);\n        }\n    };\n\n    template<class V>\n    struct Mutable_VectorConcept {\n        typedef V vector_type;\n        typedef typename V::size_type size_type;\n        typedef typename V::value_type value_type;\n        typedef value_type *pointer;\n\n        void constraints () {\n            function_requires< VectorConcept<vector_type> >();\n            function_requires< DefaultConstructible<vector_type> >();\n            function_requires< Mutable_VectorExpressionConcept<vector_type> >();\n            size_type n (0);\n            value_type t = value_type ();\n            size_type i (0);\n            vector_type v;\n            // Element support\n            pointer p = v.find_element (i);\n            // Element assignment\n            value_type r = v.insert_element (i, t);\n            v.insert_element (i, t) = r;\n            // Zeroing\n            v.clear ();\n            // Resize\n            v.resize (n);\n\n            ignore_unused_variable_warning (p);\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class V>\n    struct SparseVectorConcept {\n        typedef V vector_type;\n        typedef typename V::size_type size_type;\n\n        void constraints () {\n            function_requires< VectorConcept<vector_type> >();\n        }\n    };\n\n    template<class V>\n    struct Mutable_SparseVectorConcept {\n        typedef V vector_type;\n        typedef typename V::size_type size_type;\n        typedef typename V::value_type value_type;\n\n        void constraints () {\n            function_requires< SparseVectorConcept<vector_type> >();\n            function_requires< Mutable_VectorConcept<vector_type> >();\n            size_type i (0);\n            vector_type v;\n            // Element erasure\n            v.erase_element (i);\n        }\n    };\n\n    template<class M>\n    struct MatrixConcept {\n        typedef M matrix_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n        typedef const value_type *const_pointer;\n\n        void constraints () {\n            function_requires< MatrixExpressionConcept<matrix_type> >();\n            size_type n (0);\n            size_type i (0), j (0);\n            // Sizing constructor\n            matrix_type m (n, n);\n            // Element support\n#ifndef SKIP_BAD\n            const_pointer p = m.find_element (i, j);\n#else\n            const_pointer p;\n            ignore_unused_variable_warning (i);\n            ignore_unused_variable_warning (j);\n#endif\n            ignore_unused_variable_warning (p);\n        }\n    };\n\n    template<class M>\n    struct Mutable_MatrixConcept {\n        typedef M matrix_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n        typedef value_type *pointer;\n\n        void constraints () {\n            function_requires< MatrixConcept<matrix_type> >();\n            function_requires< DefaultConstructible<matrix_type> >();\n            function_requires< Mutable_MatrixExpressionConcept<matrix_type> >();\n            size_type n (0);\n            value_type t = value_type ();\n            size_type i (0), j (0);\n            matrix_type m;\n            // Element support\n#ifndef SKIP_BAD\n            pointer p = m.find_element (i, j);\n            ignore_unused_variable_warning (i);\n            ignore_unused_variable_warning (j);\n#else\n            pointer p;\n#endif\n            // Element assigment\n            value_type r = m.insert_element (i, j, t);\n            m.insert_element (i, j, t) = r;\n            // Zeroing\n            m.clear ();\n            // Resize\n            m.resize (n, n);\n            m.resize (n, n, false);\n\n            ignore_unused_variable_warning (p);\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class M>\n    struct SparseMatrixConcept {\n        typedef M matrix_type;\n        typedef typename M::size_type size_type;\n\n        void constraints () {\n            function_requires< MatrixConcept<matrix_type> >();\n        }\n    };\n\n    template<class M>\n    struct Mutable_SparseMatrixConcept {\n        typedef M matrix_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n\n        void constraints () {\n            function_requires< SparseMatrixConcept<matrix_type> >();\n            function_requires< Mutable_MatrixConcept<matrix_type> >();\n            size_type i (0), j (0);\n            matrix_type m;\n            // Elemnent erasure\n            m.erase_element (i, j);\n        }\n    };\n\n    /** introduce anonymous namespace to make following functions\n     * local to the current compilation unit.\n     */\n    namespace {\n\n    // Replaced the ZeroElement and OneElement functions with the templated versions\n    // because the former where giving warnings with clang\n    template<class T>\n    T\n    ZeroElement (T) {\n        return T(0.0);\n    }\n\n    template<class T>\n    vector<T>\n    ZeroElement (vector<T>) {\n        return zero_vector<T> ();\n    }\n\n    template<class T>\n    matrix<T>\n    ZeroElement (matrix<T>) {\n        return zero_matrix<T> ();\n    }\n\n    template<class T>\n    T\n    OneElement (T) {\n        return T(0.0);\n    }\n\n    template<class T>\n    vector<T>\n    OneElement (vector<T>) {\n        return zero_vector<T> ();\n    }\n\n    template<class T>\n    matrix<T>\n    OneElement (matrix<T>) {\n        return identity_matrix<T> ();\n    }\n\n//    template<>\n//    float\n//    ZeroElement (float) {\n//        return 0.f;\n//    }\n//    template<>\n//    double\n//    ZeroElement (double) {\n//        return 0.;\n//    }\n//    template<>\n//    vector<float>\n//    ZeroElement (vector<float>) {\n//        return zero_vector<float> ();\n//    }\n//    template<>\n//    vector<double>\n//    ZeroElement (vector<double>) {\n//        return zero_vector<double> ();\n//    }\n//    template<>\n//    matrix<float>\n//    ZeroElement (matrix<float>) {\n//        return zero_matrix<float> ();\n//    }\n//    template<>\n//    matrix<double>\n//    ZeroElement (matrix<double>) {\n//        return zero_matrix<double> ();\n//    }\n//    template<>\n//    std::complex<float>\n//    ZeroElement (std::complex<float>) {\n//        return std::complex<float> (0.f);\n//    }\n//    template<>\n//    std::complex<double>\n//    ZeroElement (std::complex<double>) {\n//        return std::complex<double> (0.);\n//    }\n//    template<>\n//    vector<std::complex<float> >\n//    ZeroElement (vector<std::complex<float> >) {\n//        return zero_vector<std::complex<float> > ();\n//    }\n//    template<>\n//    vector<std::complex<double> >\n//    ZeroElement (vector<std::complex<double> >) {\n//        return zero_vector<std::complex<double> > ();\n//    }\n//    template<>\n//    matrix<std::complex<float> >\n//    ZeroElement (matrix<std::complex<float> >) {\n//        return zero_matrix<std::complex<float> > ();\n//    }\n//    template<>\n//    matrix<std::complex<double> >\n//    ZeroElement (matrix<std::complex<double> >) {\n//        return zero_matrix<std::complex<double> > ();\n//    }\n\n//    template<class T>\n//    T\n//    OneElement (T);\n//    template<>\n//    float\n//    OneElement (float) {\n//        return 1.f;\n//    }\n//    template<>\n//    double\n//    OneElement (double) {\n//        return 1.;\n//    }\n//    template<>\n//    matrix<float>\n//    OneElement (matrix<float>) {\n//        return identity_matrix<float> ();\n//    }\n//    template<>\n//    matrix<double>\n//    OneElement (matrix<double>) {\n//        return identity_matrix<double> ();\n//    }\n//    template<>\n//    std::complex<float>\n//    OneElement (std::complex<float>) {\n//        return std::complex<float> (1.f);\n//    }\n//    template<>\n//    std::complex<double>\n//    OneElement (std::complex<double>) {\n//        return std::complex<double> (1.);\n//    }\n//    template<>\n//    matrix<std::complex<float> >\n//    OneElement (matrix<std::complex<float> >) {\n//        return identity_matrix<std::complex<float> > ();\n//    }\n//    template<>\n//    matrix<std::complex<double> >\n//    OneElement (matrix<std::complex<double> >) {\n//        return identity_matrix<std::complex<double> > ();\n//    }\n\n    template<class E1, class E2>\n    bool\n    operator == (const vector_expression<E1> &e1, const vector_expression<E2> &e2) {\n        typedef typename promote_traits<typename E1::value_type,\n                                                    typename E2::value_type>::promote_type value_type;\n        typedef typename type_traits<value_type>::real_type real_type;\n        return norm_inf (e1 - e2) == real_type/*zero*/();\n    }\n    template<class E1, class E2>\n    bool\n    operator == (const matrix_expression<E1> &e1, const matrix_expression<E2> &e2) {\n        typedef typename promote_traits<typename E1::value_type,\n                                                    typename E2::value_type>::promote_type value_type;\n        typedef typename type_traits<value_type>::real_type real_type;\n        return norm_inf (e1 - e2) == real_type/*zero*/();\n    }\n\n    template<class T>\n    struct AdditiveAbelianGroupConcept {\n        typedef T value_type;\n\n        void constraints () {\n            bool r;\n            value_type a = value_type (), b = value_type (), c = value_type ();\n            r = (a + b) + c == a + (b + c);\n            r = ZeroElement (value_type ()) + a == a;\n            r = a + ZeroElement (value_type ()) == a;\n            r = a + (- a) == ZeroElement (value_type ());\n            r = (- a) + a == ZeroElement (value_type ());\n            r = a + b == b + a;\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class T>\n    struct MultiplicativeAbelianGroupConcept {\n        typedef T value_type;\n\n        void constraints () {\n            bool r;\n            value_type a = value_type (), b = value_type (), c = value_type ();\n            r = (a * b) * c == a * (b * c);\n            r = OneElement (value_type ()) * a == a;\n            r = a * OneElement (value_type ()) == a;\n            r = a * (OneElement (value_type ()) / a) == a;\n            r = (OneElement (value_type ()) / a) * a == a;\n            r = a * b == b * a;\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class T>\n    struct RingWithIdentityConcept {\n        typedef T value_type;\n\n        void constraints () {\n            function_requires< AdditiveAbelianGroupConcept<value_type> >();\n            bool r;\n            value_type a = value_type (), b = value_type (), c = value_type ();\n            r = (a * b) * c == a * (b * c);\n            r = (a + b) * c == a * c + b * c;\n            r = OneElement (value_type ()) * a == a;\n            r = a * OneElement (value_type ()) == a;\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class T>\n    struct Prod_RingWithIdentityConcept {\n        typedef T value_type;\n\n        void constraints () {\n            function_requires< AdditiveAbelianGroupConcept<value_type> >();\n            bool r;\n            value_type a = value_type (), b = value_type (), c = value_type ();\n            r = prod (T (prod (a, b)), c) == prod (a, T (prod (b, c)));\n            r = prod (a + b, c) == prod (a, c) + prod (b, c);\n            r = prod (OneElement (value_type ()), a) == a;\n            r = prod (a, OneElement (value_type ())) == a;\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class T>\n    struct CommutativeRingWithIdentityConcept {\n        typedef T value_type;\n\n        void constraints () {\n            function_requires< RingWithIdentityConcept<value_type> >();\n            bool r;\n            value_type a = value_type (), b = value_type ();\n            r = a * b == b * a;\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class T>\n    struct FieldConcept {\n        typedef T value_type;\n\n        void constraints () {\n            function_requires< CommutativeRingWithIdentityConcept<value_type> >();\n            bool r;\n            value_type a = value_type ();\n            r = a == ZeroElement (value_type ()) || a * (OneElement (value_type ()) / a) == a;\n            r = a == ZeroElement (value_type ()) || (OneElement (value_type ()) / a) * a == a;\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class T, class V>\n    struct VectorSpaceConcept {\n        typedef T value_type;\n        typedef V vector_type;\n\n        void constraints () {\n            function_requires< FieldConcept<value_type> >();\n            function_requires< AdditiveAbelianGroupConcept<vector_type> >();\n            bool r;\n            value_type alpha = value_type (), beta = value_type ();\n            vector_type a = vector_type (), b = vector_type ();\n            r = alpha * (a + b) == alpha * a + alpha * b;\n            r = (alpha + beta) * a == alpha * a + beta * a;\n            r = (alpha * beta) * a == alpha * (beta * a);\n            r = OneElement (value_type ()) * a == a;\n            ignore_unused_variable_warning (r);\n        }\n    };\n\n    template<class T, class V, class M>\n    struct LinearOperatorConcept {\n        typedef T value_type;\n        typedef V vector_type;\n        typedef M matrix_type;\n\n        void constraints () {\n            function_requires< VectorSpaceConcept<value_type, vector_type> >();\n            bool r;\n            value_type alpha = value_type (), beta = value_type ();\n            vector_type a = vector_type (), b = vector_type ();\n            matrix_type A = matrix_type ();\n            r = prod (A, alpha * a + beta * b) == alpha * prod (A, a) + beta * prod (A, b);\n            ignore_unused_variable_warning (r);\n        }\n    };\n\ninline void concept_checks () {\n\n        // Allow tests to be group to keep down compiler storage requirement\n#ifdef INTERAL\n#define INTERNAL_STORAGE\n#define INTERNAL_VECTOR\n#define INTERNAL_MATRIX\n#define INTERNAL_SPECIAL\n#define INTERNAL_SPARSE\n#define INTERNAL_EXPRESSION\n#endif\n\n        // TODO enable this for development\n        // #define VIEW_CONCEPTS\n\n        // Element value type for tests\n        typedef float T;\n\n        // Storage Array\n#if defined (INTERNAL_STORAGE) || defined (INTERNAL_STORAGE_DENSE)\n        {\n            typedef std::vector<T> container_model;\n            function_requires< Mutable_StorageArrayConcept<container_model> >();\n            function_requires< RandomAccessIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_RandomAccessIteratorConcept<container_model::iterator> >();\n        }\n\n        {\n            typedef bounded_array<T, 1> container_model;\n            function_requires< Mutable_StorageArrayConcept<container_model> >();\n            function_requires< RandomAccessIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_RandomAccessIteratorConcept<container_model::iterator> >();\n        }\n\n        {\n            typedef unbounded_array<T> container_model;\n            function_requires< Mutable_StorageArrayConcept<container_model> >();\n            function_requires< RandomAccessIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_RandomAccessIteratorConcept<container_model::iterator> >();\n        }\n\n/* FIXME array_adaptors are in progress\n        {\n            typedef array_adaptor<T> container_model;\n            function_requires< Mutable_StorageArrayConcept<container_model> >();\n            function_requires< RandomAccessIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_RandomAccessIteratorConcept<container_model::iterator> >();\n        }\n*/\n\n        {\n            typedef range container_model;\n            function_requires< IndexSetConcept<range> >();\n            function_requires< RandomAccessIteratorConcept<range::const_iterator> >();\n        }\n\n        {\n            typedef slice container_model;\n            function_requires< IndexSetConcept<range> >();\n            function_requires< RandomAccessIteratorConcept<range::const_iterator> >();\n        }\n\n        {\n            typedef indirect_array<> container_model;\n            function_requires< IndexSetConcept<range> >();\n            function_requires< RandomAccessIteratorConcept<range::const_iterator> >();\n        }\n#endif\n\n        // Storage Sparse\n#if defined (INTERNAL_STORAGE) || defined (INTERNAL_STORAGE_SPARSE)\n        {\n           typedef map_array<std::size_t, T> container_model;\n           function_requires< Mutable_StorageSparseConcept<container_model> >();\n           function_requires< RandomAccessIteratorConcept<container_model::const_iterator> >();\n           function_requires< RandomAccessIteratorConcept<container_model::iterator> >();\n        }\n\n        {\n           typedef std::map<std::size_t, T> container_model;\n           function_requires< Mutable_StorageSparseConcept<container_model > >();\n           function_requires< BidirectionalIteratorConcept<container_model::const_iterator> >();\n           function_requires< BidirectionalIteratorConcept<container_model::iterator> >();\n        }\n#endif\n\n#ifdef VIEW_CONCEPTS\n        // read only vectors\n        {\n           typedef vector_view<T> container_model;\n           function_requires< RandomAccessContainerConcept<container_model> >();\n           function_requires< VectorConcept<container_model> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n        }\n#endif\n\n        // Vector\n#if defined (INTERNAL_VECTOR) || defined (INTERNAL_VECTOR_DENSE)\n        {\n           typedef vector<T> container_model;\n           function_requires< RandomAccessContainerConcept<container_model> >();\n           function_requires< Mutable_VectorConcept<container_model> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n           typedef zero_vector<T> container_model;\n           function_requires< VectorConcept<container_model> >();\n           function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_reverse_iterator> >();\n        }\n\n        {\n           typedef unit_vector<T> container_model;\n           function_requires< VectorConcept<container_model> >();\n           function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_reverse_iterator> >();\n        }\n\n        {\n           typedef scalar_vector<T> container_model;\n           function_requires< VectorConcept<container_model> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n        }\n\n        {\n           typedef c_vector<T, 1> container_model;\n           function_requires< Mutable_VectorConcept<container_model> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n#endif\n\n        // Vector Proxies\n#if defined (INTERNAL_VECTOR) || defined (INTERNAL_VECTOR_PROXY)\n        {\n           typedef vector_range<vector<T> > container_model;\n           function_requires< Mutable_VectorExpressionConcept<container_model> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n           typedef vector_slice<vector<T> > container_model;\n           function_requires< Mutable_VectorExpressionConcept<container_model> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n           typedef vector_indirect<vector<T> > container_model;\n           function_requires< Mutable_VectorExpressionConcept<container_model> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n           function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n           function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n#endif\n\n        // Sparse Vector\n#if defined (INTERNAL_SPARSE) || defined (INTERNAL_VECTOR_SPARSE)\n        {\n            typedef mapped_vector<T> container_model;\n            function_requires< Mutable_SparseVectorConcept<container_model> >();\n            function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedBidirectional1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedBidirectional1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n            typedef compressed_vector<T> container_model;\n            function_requires< Mutable_SparseVectorConcept<container_model> >();\n            function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedBidirectional1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedBidirectional1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n            typedef coordinate_vector<T> container_model;\n            function_requires< Mutable_SparseVectorConcept<container_model> >();\n            function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedBidirectional1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedBidirectional1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedBidirectional1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n#endif\n\n        // Matrix\n#if defined (INTERNAL_MATRIX) || defined (INTERNAL_MATRIX_DENSE)\n        {\n            typedef matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<matrix<T> > >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef vector_of_vector<T> container_model;\n            function_requires< Mutable_MatrixConcept<matrix<T> > >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef zero_matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<matrix<T> > >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef identity_matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<matrix<T> > >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef scalar_matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<matrix<T> > >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef c_matrix<T, 1, 1> container_model;\n            function_requires< Mutable_MatrixConcept<matrix<T> > >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n#endif\n\n        // Matrix Proxies\n#if defined (INTERNAL_MATRIX) || defined (INTERNAL_MATRIX_PROXY)\n        {\n            typedef matrix_row<matrix<T> > container_model;\n            function_requires< Mutable_VectorExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n            typedef matrix_column<matrix<T> > container_model;\n            function_requires< Mutable_VectorExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n            typedef matrix_vector_range<matrix<T> > container_model;\n            function_requires< Mutable_VectorExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n            typedef matrix_vector_slice<matrix<T> > container_model;\n            function_requires< Mutable_VectorExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n            typedef matrix_vector_indirect<matrix<T> > container_model;\n            function_requires< Mutable_VectorExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<container_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<container_model::reverse_iterator> >();\n        }\n\n        {\n            typedef matrix_range<matrix<T> > container_model;\n            function_requires< Mutable_MatrixExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_slice<matrix<T> > container_model;\n            function_requires< Mutable_MatrixExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_indirect<matrix<T> > container_model;\n            function_requires< Mutable_MatrixExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n#endif\n\n        // Banded Matrix\n#if defined (INTERNAL_SPECIAL) || defined (INTERNAL_BANDED)\n        {\n            typedef banded_matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef banded_adaptor<matrix<T> > container_model;\n            function_requires< Mutable_MatrixExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n#endif\n\n        // Triangular Matrix\n#if defined (INTERNAL_SPECIAL) || defined (INTERNAL_TRIANGULAR)\n        {\n            typedef triangular_matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef triangular_adaptor<matrix<T> > container_model;\n            function_requires< Mutable_MatrixExpressionConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n#endif\n\n        // Symmetric Matrix\n#if defined (INTERNA_SPECIAL) || defined (INTERNAL_SYMMETRIC)\n        {\n            typedef symmetric_matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef banded_adaptor<matrix<T> > container_model;\n#ifndef SKIP_BAD\n           // const_iterator (iterator) constructor is bad\n            function_requires< Mutable_MatrixExpressionConcept<container_model> >();\n#endif\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n#endif\n\n        // Hermitian Matrix\n#if defined (INTERNAL_SPECIAL) || defined (INTERNAL_HERMITIAN)\n        {\n            typedef hermitian_matrix<T> container_model;\n            function_requires< Mutable_MatrixConcept<container_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef hermitian_adaptor<matrix<T> > container_model;\n#ifndef SKIP_BAD\n           // const_iterator (iterator) constructor is bad\n            function_requires< Mutable_MatrixExpressionConcept<container_model> >();\n#endif\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n#endif\n\n        // Sparse Matrix\n#if defined (INTERNAL_SPARSE) || defined (INTERNAL_MATRIX_SPARSE)\n        {\n            typedef mapped_matrix<T> container_model;\n            function_requires< Mutable_SparseMatrixConcept<container_model> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n        {\n            typedef mapped_vector_of_mapped_vector<T> container_model;\n            function_requires< Mutable_SparseMatrixConcept<container_model> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n        {\n            typedef compressed_matrix<T> container_model;\n            function_requires< Mutable_SparseMatrixConcept<container_model> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n        {\n            typedef coordinate_matrix<T> container_model;\n            function_requires< Mutable_SparseMatrixConcept<container_model> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n        {\n            typedef generalized_vector_of_vector<T, row_major, vector< coordinate_vector<T> > > container_model;\n            function_requires< Mutable_SparseMatrixConcept<container_model> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_iterator1, container_model::const_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::iterator1, container_model::iterator2> >();\n            function_requires< IndexedBidirectional2DIteratorConcept<container_model::const_reverse_iterator1, container_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedBidirectional2DIteratorConcept<container_model::reverse_iterator1, container_model::reverse_iterator2> >();\n        }\n\n#endif\n\n        // Scalar Expressions\n#if defined (INTERNAL_EXPRESSION) || defined (INTERNAL_VECTOR_EXPRESSION)\n        function_requires< ScalarExpressionConcept<scalar_value<T> > >();\n        function_requires< ScalarExpressionConcept<scalar_reference<T> > >();\n\n        // Vector Expressions\n        {\n            typedef vector_reference<vector<T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< Mutable_VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<expression_model::iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n            function_requires< Mutable_IndexedRandomAccess1DIteratorConcept<expression_model::reverse_iterator> >();\n        }\n\n        {\n            typedef vector_unary<vector<T>, scalar_identity<T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        {\n            typedef vector_binary<vector<T>, vector<T>, scalar_plus<T, T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        {\n            typedef vector_binary_scalar1<T, vector<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        {\n            typedef vector_binary_scalar2<vector<T>, scalar_value<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        {\n            typedef vector_binary_scalar1<scalar_value<T>, vector<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        {\n            typedef vector_binary_scalar2<vector<T>, scalar_value<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        function_requires< ScalarExpressionConcept<vector_scalar_unary<vector<T>, vector_sum<vector<T> > > > >();\n        function_requires< ScalarExpressionConcept<vector_scalar_unary<vector<T>, vector_norm_1<vector<T> > > > >();\n        function_requires< ScalarExpressionConcept<vector_scalar_unary<vector<T>, vector_norm_2<vector<T> > > > >();\n        function_requires< ScalarExpressionConcept<vector_scalar_unary<vector<T>, vector_norm_inf<vector<T> > > > >();\n\n        function_requires< ScalarExpressionConcept<vector_scalar_binary<vector<T>, vector<T>, vector_inner_prod<vector<T>, vector<T>, T> > > >();\n#endif\n\n        // Matrix Expressions\n#if defined (INTERNAL_EXPRESSION) || defined (INTERNAL_MATRIX_EXPRESSION)\n        {\n            typedef matrix_reference<matrix<T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< Mutable_MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<expression_model::iterator1, expression_model::iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n            function_requires< Mutable_IndexedRandomAccess2DIteratorConcept<expression_model::reverse_iterator1, expression_model::reverse_iterator2> >();\n        }\n\n        {\n            typedef vector_matrix_binary<vector<T>, vector<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_unary1<matrix<T>, scalar_identity<T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_unary2<matrix<T>, scalar_identity<T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_binary<matrix<T>, matrix<T>, scalar_plus<T, T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_binary_scalar1<T, matrix<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_binary_scalar2<matrix<T>, T, scalar_multiplies<T, T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_binary_scalar1<scalar_value<T>, matrix<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_binary_scalar2<matrix<T>, scalar_value<T>, scalar_multiplies<T, T> > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        {\n            typedef matrix_vector_binary1<matrix<T>, vector<T>, matrix_vector_prod1<matrix<T>, vector<T>, T> > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        {\n            typedef matrix_vector_binary2<vector<T>, matrix<T>, matrix_vector_prod2<matrix<T>, vector<T>, T > > expression_model;\n            function_requires< VectorExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_iterator> >();\n            function_requires< IndexedRandomAccess1DIteratorConcept<expression_model::const_reverse_iterator> >();\n        }\n\n        {\n            typedef matrix_matrix_binary<matrix<T>, matrix<T>, matrix_matrix_prod<matrix<T>, matrix<T>, T > > expression_model;\n            function_requires< MatrixExpressionConcept<expression_model> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_iterator1, expression_model::const_iterator2> >();\n            function_requires< IndexedRandomAccess2DIteratorConcept<expression_model::const_reverse_iterator1, expression_model::const_reverse_iterator2> >();\n        }\n\n        function_requires< ScalarExpressionConcept<matrix_scalar_unary<matrix<T>, matrix_norm_1<vector<T> > > > >();\n        function_requires< ScalarExpressionConcept<matrix_scalar_unary<matrix<T>, matrix_norm_frobenius<vector<T> > > > >();\n        function_requires< ScalarExpressionConcept<matrix_scalar_unary<matrix<T>, matrix_norm_inf<vector<T> > > > >();\n#endif\n\n#ifdef EXTERNAL\n        function_requires< AdditiveAbelianGroupConcept<T> >();\n        function_requires< CommutativeRingWithIdentityConcept<T> >();\n        function_requires< FieldConcept<T> >();\n        function_requires< VectorSpaceConcept<T, vector<T> > >();\n        function_requires< Prod_RingWithIdentityConcept<matrix<T> > >();\n        function_requires< VectorSpaceConcept<T, matrix<T> > >();\n        function_requires< LinearOperatorConcept<T, vector<T>, matrix<T> > >();\n\n        function_requires< AdditiveAbelianGroupConcept<std::complex<T> > >();\n        function_requires< CommutativeRingWithIdentityConcept<std::complex<T> > >();\n        function_requires< FieldConcept<std::complex<T> > >();\n        function_requires< VectorSpaceConcept<std::complex<T>, vector<std::complex<T> > > >();\n        function_requires< Prod_RingWithIdentityConcept<matrix<std::complex<T> > > >();\n        function_requires< VectorSpaceConcept<std::complex<T>, matrix<std::complex<T> > > >();\n        function_requires< LinearOperatorConcept<std::complex<T>, vector<std::complex<T> >, matrix<std::complex<T> > > >();\n#endif\n    }\n\n    } // end of anonymous namespace\n\n}}}\n\n#endif\n", "meta": {"hexsha": "f525d2d0838260428a51bf5bfd367b78763e3f99", "size": 73814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/detail/concepts.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/detail/concepts.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/detail/concepts.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": 46.8362944162, "max_line_length": 158, "alphanum_fraction": 0.6739507411, "num_tokens": 14954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.04813677640806833, "lm_q1q2_score": 0.019607716801549196}}
{"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_HASH_MERKLE_DAMGARD_CONSTRUCTION_HPP\n#define CRYPTO3_HASH_MERKLE_DAMGARD_CONSTRUCTION_HPP\n\n#include <boost/crypto3/hash/detail/nop_finalizer.hpp>\n\n#include <boost/crypto3/detail/static_digest.hpp>\n#include <boost/crypto3/detail/pack.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            /*!\n             * @brief\n             * @tparam DigestEndian\n             * @tparam DigestBits\n             * @tparam IV\n             * @tparam Compressor\n             * @tparam Finalizer\n             *\n             * The Merkle-Damgård construction builds a block hashes from a\n             * one-way compressor.  As this version operated on the block\n             * level, it doesn't contain any padding or other strengthening.\n             * For a Wide Pipe construction, use a digest that will\n             * truncate the internal state.\n             *\n             * @note http://www.merkle.com/papers/Thesis1979.pdf\n             */\n            template<typename Params, typename IV, typename Compressor, typename Padding,\n                     typename Finalizer = detail::nop_finalizer>\n            class merkle_damgard_construction {\n            public:\n                typedef IV iv_generator;\n                typedef Compressor compressor_functor;\n                typedef Padding padding_functor;\n                typedef Finalizer finalizer_functor;\n\n                typedef typename Params::digest_endian endian_type;\n\n                constexpr static const std::size_t word_bits = compressor_functor::word_bits;\n                typedef typename compressor_functor::word_type word_type;\n\n                constexpr static const std::size_t state_bits = compressor_functor::state_bits;\n                constexpr static const std::size_t state_words = compressor_functor::state_words;\n                typedef typename compressor_functor::state_type state_type;\n\n                constexpr static const std::size_t block_bits = compressor_functor::block_bits;\n                constexpr static const std::size_t block_words = compressor_functor::block_words;\n                typedef typename compressor_functor::block_type block_type;\n\n                constexpr static const std::size_t digest_bits = Params::digest_bits;\n                constexpr static const std::size_t digest_bytes = digest_bits / octet_bits;\n                constexpr static const std::size_t digest_words = digest_bits / word_bits;\n                typedef static_digest<digest_bits> digest_type;\n\n            protected:\n                constexpr static const std::size_t length_bits = Params::length_bits;\n                // FIXME: do something more intelligent than capping at 64\n                constexpr static const std::size_t length_type_bits =\n                    length_bits < word_bits ? word_bits : length_bits > 64 ? 64 : length_bits;\n                typedef typename boost::uint_t<length_type_bits>::least length_type;\n                constexpr static const std::size_t length_words = length_bits / word_bits;\n                BOOST_STATIC_ASSERT(!length_bits || length_bits % word_bits == 0);\n\n            public:\n                template<typename Integer = std::size_t>\n                inline merkle_damgard_construction &process_block(const block_type &block, Integer seen = Integer()) {\n                    compressor_functor::process_block(state_, block);\n                    return *this;\n                }\n\n                inline digest_type digest(const block_type &block = block_type(),\n                                          length_type total_seen = length_type()) {\n                    using namespace boost::crypto3::detail;\n\n                    block_type b = block;\n                    std::size_t block_seen = total_seen % block_bits;\n                    // Process block if block is full\n                    if (total_seen && !block_seen)\n                        process_block(b);\n\n                    // Pad last message block\n                    padding_functor padding;\n                    padding(b, block_seen);\n\n                    // Process block if total length cannot be appended\n                    if (block_seen + length_bits > block_bits) {\n                        process_block(b);\n                        std::fill(b.begin(), b.end(), 0);\n                    }\n\n                    // Append total length to the last block\n                    append_length<int>(b, total_seen);\n\n                    // Process the last block\n                    process_block(b);\n\n                    // Apply finalizer\n                    finalizer_functor()(state_);\n\n                    // Convert digest to byte representation\n                    digest_type d;\n                    pack_from<endian_type, word_bits, octet_bits>(state_.begin(), state_.end(), d.begin());\n                    return d;\n                }\n\n                merkle_damgard_construction() {\n                    reset();\n                }\n\n                inline void reset(const state_type &s) {\n                    state_ = s;\n                }\n\n                inline void reset() {\n                    iv_generator iv;\n                    reset(iv());\n                }\n\n                inline const state_type &state() const {\n                    return state_;\n                }\n\n            protected:\n                template<typename Dummy>\n                typename std::enable_if<length_bits && sizeof(Dummy)>::type append_length(block_type &block,\n                                                                                          length_type length) {\n                    using namespace boost::crypto3::detail;\n\n                    std::array<length_type, 1> length_array = {{length}};\n                    std::array<word_type, length_words> length_words_array;\n                    pack<endian_type, endian_type, length_bits, word_bits>(length_array.begin(), length_array.end(),\n                                                                           length_words_array.begin());\n                    // Append length\n                    for (std::size_t i = length_words; i; --i)\n                        block[block_words - i] = length_words_array[length_words - i];\n                }\n\n                template<typename Dummy>\n                typename std::enable_if<!(length_bits && sizeof(Dummy))>::type append_length(block_type &block,\n                                                                                             length_type length) {\n                    // No appending requested, so nothing to do\n                }\n                state_type state_;\n            };\n\n        }    // namespace hashes\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_HASH_MERKLE_DAMGARD_BLOCK_HASH_HPP\n", "meta": {"hexsha": "880af2c9cfc490853950eeb83bd4e98bf0b76412", "size": 7228, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/detail/merkle_damgard_construction.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/hash/detail/merkle_damgard_construction.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/hash/detail/merkle_damgard_construction.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 45.175, "max_line_length": 118, "alphanum_fraction": 0.5336192584, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.04146227685694369, "lm_q1q2_score": 0.019598532557347084}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\n#define BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\n\n#include <boost/units/pow.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/static_constant.hpp>\n\n#include <boost/units/systems/detail/constants.hpp>\n#include <boost/units/systems/si/amount.hpp>\n#include <boost/units/systems/si/area.hpp>\n#include <boost/units/systems/si/electric_charge.hpp>\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/systems/si/frequency.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/systems/si/power.hpp>\n#include <boost/units/systems/si/solid_angle.hpp>\n#include <boost/units/systems/si/temperature.hpp>\n\n#include <boost/units/systems/si/codata/typedefs.hpp>\n\n/// \\file\n/// CODATA recommended values of fundamental physico-chemical constants\n/// CODATA 2014 values as of 2016/04/26\n\nnamespace boost {\n\nnamespace units { \n\nnamespace si {\n                            \nnamespace constants {\n\nnamespace codata {\n\n// PHYSICO-CHEMICAL\n/// Avogadro constant\nBOOST_UNITS_PHYSICAL_CONSTANT(N_A,quantity<inverse_amount>,6.022140857e23/mole,7.4e15/mole);\n/// atomic mass constant\nBOOST_UNITS_PHYSICAL_CONSTANT(m_u,quantity<mass>,1.660539040e-27*kilograms,2.0e-35*kilograms);\n/// Faraday constant\nBOOST_UNITS_PHYSICAL_CONSTANT(F,quantity<electric_charge_over_amount>,96485.33289*coulombs/mole,5.9e-4*coulombs/mole);\n/// molar gas constant\nBOOST_UNITS_PHYSICAL_CONSTANT(R,quantity<energy_over_temperature_amount>,8.3144598*joules/kelvin/mole,4.8e-06*joules/kelvin/mole);\n/// Boltzmann constant\nBOOST_UNITS_PHYSICAL_CONSTANT(k_B,quantity<energy_over_temperature>,1.38064852e-23*joules/kelvin,7.9e-30*joules/kelvin);\n/// Stefan-Boltzmann constant\nBOOST_UNITS_PHYSICAL_CONSTANT(sigma_SB,quantity<power_over_area_temperature_4>,5.670367e-8*watts/square_meter/pow<4>(kelvin),1.3e-13*watts/square_meter/pow<4>(kelvin));\n/// first radiation constant\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1,quantity<power_area>,3.741771790e-16*watt*square_meters,4.6e-24*watt*square_meters);\n/// first radiation constant for spectral radiance\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1L,quantity<power_area_over_solid_angle>,1.191042953e-16*watt*square_meters/steradian,1.5e-24*watt*square_meters/steradian);\n/// second radiation constant\nBOOST_UNITS_PHYSICAL_CONSTANT(c_2,quantity<length_temperature>,1.43877736e-2*meter*kelvin,8.3e-9*meter*kelvin);\n/// Wien displacement law constant : lambda_max T\nBOOST_UNITS_PHYSICAL_CONSTANT(b,quantity<length_temperature>,2.8977729e-3*meter*kelvin,1.7e-9*meter*kelvin);\n/// Wien displacement law constant : nu_max/T\nBOOST_UNITS_PHYSICAL_CONSTANT(b_prime,quantity<frequency_over_temperature>,5.8789238e10*hertz/kelvin,3.4e4*hertz/kelvin);\n\n} // namespace codata\n\n} // namespace constants    \n\n} // namespace si\n\n} // namespace units\n\n} // namespace boost\n\n#endif // BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\n", "meta": {"hexsha": "e9ed035f9c5fbaabb54c7ca1fd7436931747c56a", "size": 3276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/physico-chemical_constants.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/units/systems/si/codata/physico-chemical_constants.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": 40.95, "max_line_length": 168, "alphanum_fraction": 0.7991452991, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.05184547196043441, "lm_q1q2_score": 0.019573774158097905}}
{"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_BAYES_OPT_BOPTIMIZER_HPP\n#define LIMBO_BAYES_OPT_BOPTIMIZER_HPP\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n\n#include <boost/parameter/aux_/void.hpp>\n\n#include <Eigen/Core>\n\n#include <limbo/bayes_opt/bo_base.hpp>\n#include <limbo/tools/macros.hpp>\n#include <limbo/tools/random_generator.hpp>\n\n#define USE_NLOPT\n#ifdef USE_NLOPT\n#include <limbo/opt/nlopt_no_grad.hpp>\n#elif defined USE_LIBCMAES\n#include <limbo/opt/cmaes.hpp>\n#else\n#include <limbo/opt/grid_search.hpp>\n#endif\n\nnamespace limbo {\n    namespace defaults {\n        struct bayes_opt_boptimizer {\n            BO_PARAM(int, hp_period, -1);\n        };\n    }\n\n    BOOST_PARAMETER_TEMPLATE_KEYWORD(acquiopt)\n\n    namespace bayes_opt {\n\n        using boptimizer_signature = boost::parameter::parameters<boost::parameter::optional<tag::acquiopt>,\n            boost::parameter::optional<tag::statsfun>,\n            boost::parameter::optional<tag::initfun>,\n            boost::parameter::optional<tag::acquifun>,\n            boost::parameter::optional<tag::stopcrit>,\n            boost::parameter::optional<tag::modelfun>>;\n\n        // clang-format off\n        /**\n        The classic Bayesian optimization algorithm.\n\n        \\rst\n        References: :cite:`brochu2010tutorial,Mockus2013`\n        \\endrst\n\n        This class takes the same template parameters as BoBase. It adds:\n        \\rst\n        +---------------------+------------+----------+---------------+\n        |type                 |typedef     | argument | default       |\n        +=====================+============+==========+===============+\n        |acqui. optimizer     |acquiopt_t  | acquiopt | see below     |\n        +---------------------+------------+----------+---------------+\n        \\endrst\n\n        The default value of acqui_opt_t is:\n        - ``opt::NLOptNoGrad<Params, nlopt::GN_DIRECT_L_RAND>`` if NLOpt was found in `waf configure`\n        - ``opt::Cmaes<Params>`` if libcmaes was found but NLOpt was not found\n        - ``opt::GridSearch<Params>`` otherwise (please do not use this: the algorithm will not work as expected!)\n        */\n        template <class Params,\n          class A1 = boost::parameter::void_,\n          class A2 = boost::parameter::void_,\n          class A3 = boost::parameter::void_,\n          class A4 = boost::parameter::void_,\n          class A5 = boost::parameter::void_,\n          class A6 = boost::parameter::void_>\n        // clang-format on\n        class BOptimizer : public BoBase<Params, A1, A2, A3, A4, A5, A6> {\n        public:\n            // defaults\n            struct defaults {\n#ifdef USE_NLOPT\n                using acquiopt_t = opt::NLOptNoGrad<Params, nlopt::GN_DIRECT_L_RAND>;\n#elif defined(USE_LIBCMAES)\n                using acquiopt_t = opt::Cmaes<Params>;\n#else\n#warning NO NLOpt, and NO Libcmaes: the acquisition function will be optimized by a grid search algorithm (which is usually bad). Please install at least NLOpt or libcmaes to use limbo!.\n                using acquiopt_t = opt::GridSearch<Params>;\n#endif\n            };\n            /// link to the corresponding BoBase (useful for typedefs)\n            using base_t = BoBase<Params, A1, A2, A3, A4, A5, A6>;\n            using model_t = typename base_t::model_t;\n            using acquisition_function_t = typename base_t::acquisition_function_t;\n            // extract the types\n            using args = typename boptimizer_signature::bind<A1, A2, A3, A4, A5, A6>::type;\n            using acqui_optimizer_t = typename boost::parameter::binding<args, tag::acquiopt, typename defaults::acquiopt_t>::type;\n\n            /// The main function (run the Bayesian optimization algorithm)\n            template <typename StateFunction, typename AggregatorFunction = FirstElem>\n            void optimize(const StateFunction& sfun, const AggregatorFunction& afun = AggregatorFunction(), bool reset = true)\n            {\n                this->_init(sfun, afun, reset);\n\n                if (!this->_observations.empty())\n                    _model.compute(this->_samples, this->_observations);\n                else\n                    _model = model_t(StateFunction::dim_in(), StateFunction::dim_out());\n\n                acqui_optimizer_t acqui_optimizer;\n\n                while (!this->_stop(*this, afun)) {\n                    acquisition_function_t acqui(_model, this->_current_iteration);\n\n                    auto acqui_optimization =\n                        [&](const Eigen::VectorXd& x, bool g) { return acqui(x, afun, g); };\n                    Eigen::VectorXd starting_point = tools::random_vector(StateFunction::dim_in(), Params::bayes_opt_bobase::bounded());\n                    Eigen::VectorXd new_sample = acqui_optimizer(acqui_optimization, starting_point, Params::bayes_opt_bobase::bounded());\n                    this->eval_and_add(sfun, new_sample);\n\n                    this->_update_stats(*this, afun);\n\n                    _model.add_sample(this->_samples.back(), this->_observations.back());\n\n                    if (Params::bayes_opt_boptimizer::hp_period() > 0\n                        && (this->_current_iteration + 1) % Params::bayes_opt_boptimizer::hp_period() == 0)\n                        _model.optimize_hyperparams();\n\n                    this->_current_iteration++;\n                    this->_total_iterations++;\n                }\n            }\n\n            /// return the best observation so far (i.e. max(f(x)))\n            template <typename AggregatorFunction = FirstElem>\n            const Eigen::VectorXd& best_observation(const AggregatorFunction& afun = AggregatorFunction()) const\n            {\n                auto rewards = std::vector<double>(this->_observations.size());\n                std::transform(this->_observations.begin(), this->_observations.end(), rewards.begin(), afun);\n                auto max_e = std::max_element(rewards.begin(), rewards.end());\n                return this->_observations[std::distance(rewards.begin(), max_e)];\n            }\n\n            /// return the best sample so far (i.e. the argmax(f(x)))\n            template <typename AggregatorFunction = FirstElem>\n            const Eigen::VectorXd& best_sample(const AggregatorFunction& afun = AggregatorFunction()) const\n            {\n                auto rewards = std::vector<double>(this->_observations.size());\n                std::transform(this->_observations.begin(), this->_observations.end(), rewards.begin(), afun);\n                auto max_e = std::max_element(rewards.begin(), rewards.end());\n                return this->_samples[std::distance(rewards.begin(), max_e)];\n            }\n\n            const model_t& model() const { return _model; }\n\n        protected:\n            model_t _model;\n        };\n\n        namespace _default_hp {\n            template <typename Params>\n            using model_t = model::GPOpt<Params>;\n            template <typename Params>\n            using acqui_t = acqui::UCB<Params, model_t<Params>>;\n        }\n\n        /// A shortcut for a BOptimizer with UCB + GPOpt\n        /// The acquisition function and the model CANNOT be tuned (use BOptimizer for this)\n        template <class Params,\n            class A1 = boost::parameter::void_,\n            class A2 = boost::parameter::void_,\n            class A3 = boost::parameter::void_,\n            class A4 = boost::parameter::void_>\n        using BOptimizerHPOpt = BOptimizer<Params, modelfun<_default_hp::model_t<Params>>, acquifun<_default_hp::acqui_t<Params>>, A1, A2, A3, A4>;\n    }\n}\n#endif\n", "meta": {"hexsha": "6a2ea0e11cc6c191541156bfd1109368f61a4eec", "size": 9875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/bayes_opt/boptimizer.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/bayes_opt/boptimizer.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/bayes_opt/boptimizer.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": 45.2981651376, "max_line_length": 186, "alphanum_fraction": 0.6275443038, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.04272219846061001, "lm_q1q2_score": 0.019529885539935912}}
{"text": "//    Copyright 2021 Jij Inc.\n\n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n\n//        http://www.apache.org/licenses/LICENSE-2.0\n\n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n\n\n/**\n * @file binary_quadratic_model.hpp\n * @author Fumiya Watanabe\n * @brief BinaryQuadraticModel class\n * @version 1.0.0\n * @date 2020-03-24\n * \n * @copyright Copyright (c) Jij Inc. 2020\n * \n */\n\n#ifndef BINARY_QUADRATIC_MODEL_DICT_HPP__\n#define BINARY_QUADRATIC_MODEL_DICT_HPP__\n\n#include \"disable_eigen_warning.hpp\"\n\n#include \"vartypes.hpp\"\n#include \"hash.hpp\"\n#include \"utilities.hpp\"\n#include \"json.hpp\"\n\n#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <typeinfo>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n#include <functional>\n#include <Eigen/Dense>\n\n#include \"binary_quadratic_model.hpp\"\n\nnamespace cimod\n{\n\n    struct Dict{};\n    \n    /**\n     * @brief Class for legacy binary quadratic model (dict datastructure).\n     */\n    \n    template <typename IndexType, typename FloatType>\n    class BinaryQuadraticModel<IndexType, FloatType, Dict>\n    {\n        using DataType = Dict;\n    public:\n\n        using DenseMatrix   = Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n        using SparseMatrix  = Eigen::SparseMatrix<FloatType, Eigen::RowMajor>;\n\n        /**\n         * @brief Eigen Matrix\n         */\n        using Matrix = Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    protected:\n        /**\n         * @brief Linear biases as a dictionary.\n         * \n         */\n        Linear<IndexType, FloatType> m_linear;\n    \n        /**\n         * @brief Quadratic biases as a dictionary.\n         * \n         */\n        Quadratic<IndexType, FloatType> m_quadratic;\n    \n        /**\n         * @brief The energy offset associated with the model.\n         * \n         */\n        FloatType m_offset;\n    \n        /**\n         * @brief The model's type.\n         * \n         */\n        Vartype m_vartype = Vartype::NONE;\n    \n    public:\n        /**\n         * @brief BinaryQuadraticModel constructor.\n         * \n         * @param linear\n         * @param quadratic\n         * @param offset\n         * @param vartype\n         */\n        BinaryQuadraticModel\n        (\n            const Linear<IndexType, FloatType> &linear,\n            const Quadratic<IndexType, FloatType> &quadratic,\n            const FloatType &offset,\n            const Vartype vartype\n        ):\n            m_offset(offset),\n            m_vartype(vartype)\n        {\n            add_variables_from(linear);\n            add_interactions_from(quadratic);\n        }\n\n        /**\n         * @brief BinaryQuadraticModel constructor.\n         * \n         * @param linear\n         * @param quadratic\n         * @param vartype\n         */\n        BinaryQuadraticModel\n        (\n            const Linear<IndexType, FloatType> &linear,\n            const Quadratic<IndexType, FloatType> &quadratic,\n            const Vartype vartype\n        ): BinaryQuadraticModel(linear, quadratic, 0.0, vartype){}\n\n        /**\n         * @brief BinaryQuadraticModel constructor (with matrix);\n         * This constructor is not be implemented.\n         *\n         * @param mat\n         * @param labels_vec\n         * @param offset\n         * @param vartype\n         *\n         */\n        BinaryQuadraticModel\n        (\n            const Eigen::Ref<const DenseMatrix>&,\n            const std::vector<IndexType>&,\n            const FloatType&,\n            const Vartype,\n            bool\n        )\n        {\n            throw std::runtime_error(\"Initialization from matrix is not implemented on dict-type BQM\");\n        }\n\n        /**\n         * @brief BinaryQuadraticModel constructor (with matrix);\n         * This constructor is not be implemented.\n         *\n         * @param mat\n         * @param labels_vec\n         * @param vartype\n         *\n         */\n        BinaryQuadraticModel\n        (\n            const Eigen::Ref<const DenseMatrix>&,\n            const std::vector<IndexType>&,\n            const Vartype,\n            bool\n        )\n        {\n            throw std::runtime_error(\"Initialization from matrix is not implemented on dict-type BQM\");\n        }\n\n        /**\n         * @brief BinaryQuadraticModel constructor (with sparse matrix);\n         * this constructor is for developers.\n         *\n         * @param mat\n         * @param labels_vec\n         * @param offset\n         * @param vartype\n         *\n         */\n        BinaryQuadraticModel\n        (\n            const SparseMatrix&,\n            const std::vector<IndexType>&,\n            const FloatType&,\n            const Vartype\n        )\n        {\n            throw std::runtime_error(\"Initialization from matrix is not implemented on dict-type BQM\");\n        }\n    \n        /**\n         * @brief BinaryQuadraticModel constructor (with sparse matrix);\n         * this constructor is for developers.\n         *\n         * @param mat\n         * @param labels_vec\n         * @param vartype\n         *\n         */\n        BinaryQuadraticModel\n        (\n            const SparseMatrix&,\n            const std::vector<IndexType>&,\n            const Vartype\n        )\n        {\n            throw std::runtime_error(\"Initialization from matrix is not implemented on dict-type BQM\");\n        }\n    \n        /**\n         * @brief Copy constructor of BinaryQuadraticModel\n         * \n         * @param bqm \n         */\n        BinaryQuadraticModel(const BinaryQuadraticModel&) = default;\n    \n        /**\n         * @brief generate indices\n         *\n         * @return generated indices\n         */\n        std::vector<IndexType> _generate_indices() const{\n            std::unordered_set<IndexType> index_set;\n            for(auto elem : m_linear){\n                index_set.insert(elem.first);\n            }\n    \n            for(auto elem : m_quadratic){\n                index_set.insert(elem.first.first);\n                index_set.insert(elem.first.second);\n            }\n    \n            auto ret = std::vector<IndexType>(index_set.begin(), index_set.end());\n            std::sort(ret.begin(), ret.end());\n            return ret;\n        }\n    \n        /**\n         * @brief Return the number of variables.\n         * \n         * @deprecated use get_num_variables.\n         * @return The number of variables.\n         */\n        size_t length() const\n        {\n            return get_num_variables();\n        }\n\n        /**\n         * @brief Return the number of variables.\n         * \n         * @deprecated use get_num_variables.\n         * @return The number of variables.\n         */\n        size_t get_num_variables() const{\n            return m_linear.size();\n        }\n    \n        /**\n         * @brief Return true if the variable contains v.\n         * \n         * @return Return true if the variable contains v.\n         * @param v\n         */\n        bool contains\n        (const IndexType &v) const\n        {\n            if(m_linear.count(v)!=0)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n            \n        }\n\n        /**\n         * @brief Get the element of linear object\n         *\n         * @param label_i\n         *\n         * @return \n         */\n        FloatType get_linear(IndexType label_i) const{\n            return this->m_linear.at(label_i);\n        }\n        \n        /**\n         * @brief Get the linear object\n         * \n         * @return A linear bias.\n         */\n        const Linear<IndexType, FloatType>& get_linear() const\n        {\n            return this->m_linear;\n        }\n\n        /**\n         * @brief Get the element of quadratic object\n         * \n         * @return A quadratic bias.\n         */\n        FloatType get_quadratic(IndexType label_i, IndexType label_j) const\n        {\n            return this->m_quadratic.at(std::make_pair(std::min(label_i, label_j), std::max(label_i, label_j)));\n        }\n    \n        /**\n         * @brief Get the quadratic object\n         * \n         * @return A quadratic bias.\n         */\n        const Quadratic<IndexType, FloatType>& get_quadratic() const\n        {\n            return this->m_quadratic;\n        }\n    \n        /**\n         * @brief Get the offset\n         * \n         * @return An offset.\n         */\n        const FloatType& get_offset() const\n        {\n            return this->m_offset;\n        }\n    \n        /**\n         * @brief Get the vartype object\n         * \n         * @return Type of the model.\n         */\n        const Vartype& get_vartype() const\n        {\n            return this->m_vartype;\n        }\n\n        /**\n         * @brief Get variables\n         *\n         * @return variables\n         */\n        const std::vector<IndexType> get_variables() const{\n            std::vector<IndexType> variables;\n            variables.reserve(m_linear.size());\n            for(auto&& elem : m_linear)\n            {\n                variables.push_back(elem.first);\n            }\n    \n            std::sort(variables.begin(), variables.end());\n\n            return variables;\n        }\n    \n        /**\n         * @brief Create an empty BinaryQuadraticModel\n         * \n         */\n        BinaryQuadraticModel<IndexType, FloatType, DataType> empty(Vartype vartype)\n        {\n            return BinaryQuadraticModel<IndexType, FloatType, DataType>(\n                    Linear<IndexType, FloatType>(),\n                    Quadratic<IndexType, FloatType>(),\n                    0.0,\n                    vartype\n                    );\n        }\n    \n        /* Update methods */\n    \n        /**\n         * @brief Add variable v and/or its bias to a binary quadratic model.\n         * \n         * @param v\n         * @param bias\n         */\n        void add_variable\n        (\n            const IndexType &v,\n            const FloatType &bias\n        )\n        {\n            FloatType b = bias;\n\n            Vartype vartype = this->get_vartype();\n    \n            // handle the case that a different vartype is provided\n            if((vartype!=Vartype::NONE)&&(vartype!=m_vartype))\n            {\n                if((m_vartype == Vartype::SPIN)&&(vartype == Vartype::BINARY))\n                {\n                    b /= 2;\n                    m_offset += b;\n                }\n                else if((m_vartype == Vartype::BINARY)&&(vartype == Vartype::SPIN))\n                {\n                    m_offset -= b;\n                    b *= 2;\n                }\n                else\n                {\n                    throw std::runtime_error(\"Unknown vartype\");\n                }\n            }\n    \n            // Insert or assign the bias\n            FloatType value = 0;\n            if(m_linear.count(v) != 0)\n            {\n                value = m_linear[v];\n            }\n            insert_or_assign(m_linear, v, value + b);\n        }\n    \n        /**\n         * @brief Add variables and/or linear biases to a binary quadratic model.\n         * \n         * @param linear\n         */\n        void add_variables_from\n        (\n            const Linear<IndexType, FloatType> &linear\n        )\n        {\n            for(auto &it : linear)\n            {\n                add_variable(it.first, it.second);\n            }\n        }\n    \n        /**\n         * @brief Add an interaction and/or quadratic bias to a binary quadratic model.\n         * \n         * @param arg_u\n         * @param arg_v\n         * @param bias\n         */\n        void add_interaction\n        (\n            const IndexType &arg_u,\n            const IndexType &arg_v,\n            const FloatType &bias\n        )\n        {\n            IndexType u = std::min(arg_u, arg_v);\n            IndexType v = std::max(arg_u, arg_v);\n\n            Vartype vartype = this->get_vartype();\n\n            if(u == v)\n            {\n                throw std::runtime_error(\"No self-loops allowed\");\n            }\n            else\n            {\n                //Check vartype when m_linear.empty() is true\n                if (m_linear.empty() && m_vartype == Vartype::NONE) {\n                   if (vartype != Vartype::NONE) {\n                      m_vartype = vartype;\n                   }\n                   else {\n                      throw std::runtime_error(\"Binary quadratic model is empty. Please set vartype to Vartype::SPIN or Vartype::BINARY\");\n                   }\n                }\n               \n                FloatType b = bias;\n                if((vartype!=Vartype::NONE)&&(vartype!=m_vartype))\n                {\n                    if((m_vartype == Vartype::SPIN)&&(vartype == Vartype::BINARY))\n                    {\n                        //convert from binary to spin\n                        b /= 4;\n                        add_offset(b);\n                        add_variable(u, b);\n                        add_variable(v, b);\n                    }\n                    else if((m_vartype == Vartype::BINARY)&&(vartype == Vartype::SPIN))\n                    {\n                        //convert from spin to binary\n                        add_offset(b);\n                        add_variable(u, -2 * b);\n                        add_variable(v, -2 * b);\n                        b *= 4;\n                    }\n                    else\n                    {\n                        throw std::runtime_error(\"Unknown vartype\");\n                    }\n                }\n                else\n                {\n                    if(m_linear.count(u) == 0)\n                    {\n                        add_variable(u, 0);\n                    }\n                    if(m_linear.count(v) == 0)\n                    {\n                        add_variable(v, 0);\n                    }\n                }\n                \n                FloatType value = 0;\n                std::pair<IndexType, IndexType> p1 = std::make_pair(u, v);\n                if(m_quadratic.count(p1) != 0)\n                {\n                    value = m_quadratic[p1];\n                }\n                insert_or_assign(m_quadratic, p1, value + b);\n            }\n        }\n    \n        /**\n         * @brief Add interactions and/or quadratic biases to a binary quadratic model.\n         * \n         * @param quadratic\n         */\n        void add_interactions_from\n        (\n            const Quadratic<IndexType, FloatType> &quadratic\n        )\n        {\n            for(auto &it : quadratic)\n            {\n                add_interaction(it.first.first, it.first.second, it.second);\n            }\n        }\n    \n        \n    \n        /**\n         * @brief Remove variable v and all its interactions from a binary quadratic model.\n         * \n         * @param v\n         */\n        void remove_variable\n        (\n            const IndexType &v\n        )\n        {\n            std::vector<std::pair<IndexType, IndexType>> interactions;\n            for(auto &it : m_quadratic)\n            {\n                if(it.first.first == v || it.first.second == v)\n                {\n                    interactions.push_back(it.first);\n                }         \n            }\n            remove_interactions_from(interactions);\n            m_linear.erase(v);\n        }\n    \n        /**\n         * @brief Remove specified variables and all of their interactions from a binary quadratic model.\n         * \n         * @param variables\n         */\n        void remove_variables_from\n        (\n            const std::vector<IndexType> &variables\n        )\n        {\n            for(auto &it : variables)\n            {\n                remove_variable(it);\n            }\n        }\n    \n        /**\n         * @brief Remove interaction of variables u, v from a binary quadratic model.\n         * \n         * @param arg_u\n         * @param arg_v\n         */\n        void remove_interaction\n        (\n            const IndexType &arg_u,\n            const IndexType &arg_v      \n        )\n        {\n            IndexType u = std::min(arg_u, arg_v);\n            IndexType v = std::max(arg_u, arg_v);\n            auto p = std::make_pair(u, v);\n            if(m_quadratic.count(p)!=0)\n            {\n                m_quadratic.erase(p);\n            }\n\n            bool u_flag = true;\n            for(auto &it : m_quadratic)\n            {\n                if((it.first.first == u) || (it.first.second == u)){\n                    u_flag = false;\n                    break;\n                }\n            }\n\n            if(u_flag && (m_linear[u] == 0)){ \n                remove_variable(u);\n            }\n\n            bool v_flag = true;\n            for(auto &it : m_quadratic)\n            {\n                if((it.first.first == v) || (it.first.second == v)){\n                    v_flag = false;\n                    break;\n                }\n            }\n\n            if(v_flag && (m_linear[v] == 0)){ \n                remove_variable(v);\n            }\n        }\n    \n        /**\n         * @brief Remove all specified interactions from the binary quadratic model.\n         * \n         * @param interactions\n         */\n        void remove_interactions_from\n        (\n            const std::vector<std::pair<IndexType, IndexType>> &interactions\n        )\n        {\n            for(auto &it : interactions)\n            {\n                remove_interaction(it.first, it.second);\n            }\n        }\n    \n        /**\n         * @brief Add specified value to the offset of a binary quadratic model.\n         * \n         * @param offset\n         */\n        void add_offset\n        (\n            const FloatType &offset\n        )\n        {\n            m_offset += offset;\n        }\n    \n        /**\n         * @brief Set the binary quadratic model's offset to zero.\n         */\n        void remove_offset()\n        {\n            add_offset(-m_offset);\n        }\n    \n        /**\n         * @brief Multiply by the specified scalar all the biases and offset of a binary quadratic model.\n         * \n         * @param scalar\n         * @param ignored_variables\n         * @param ignored_interactions\n         * @param ignored_offset\n         */\n        void scale\n        (\n            const FloatType &scalar,\n            const std::vector<IndexType> &ignored_variables = {},\n            const std::vector<std::pair<IndexType, IndexType>> &ignored_interactions = {},\n            const bool ignored_offset = false\n        )\n        {\n            // scaling linear\n            for(auto &it : m_linear)\n            {\n                if(std::find(ignored_variables.begin(), ignored_variables.end(), it.first) != ignored_variables.end() || ignored_variables.empty())\n                {\n                    it.second *= scalar;\n                }\n            }\n    \n            // scaling quadratic\n            for(auto &it : m_quadratic)\n            {\n                if(std::find(ignored_interactions.begin(), ignored_interactions.end(), it.first) != ignored_interactions.end() || ignored_variables.empty())\n                {\n                    it.second *= scalar;\n                }\n            }\n    \n            // scaling offset\n            if(!ignored_offset)\n            {\n                m_offset *= scalar;\n            }\n        }\n    \n        /**\n         * @brief Normalizes the biases of the binary quadratic model such that they fall in the provided range(s), and adjusts the offset appropriately.\n         * \n         * @param bias_range\n         * @param use_quadratic_range\n         * @param quadratic_range\n         * @param ignored_variables\n         * @param ignored_interactions\n         * @param ignored_offset\n         * \n         */\n        void normalize\n        (\n            const std::pair<FloatType, FloatType> &bias_range = {1.0, 1.0},\n            const bool use_quadratic_range = false,\n            const std::pair<FloatType, FloatType> &quadratic_range = {1.0, 1.0},\n            const std::vector<IndexType> &ignored_variables = {},\n            const std::vector<std::pair<IndexType, IndexType>> &ignored_interactions = {},\n            const bool ignored_offset = false\n        )\n        {\n            if (m_linear.empty()) {\n               return;\n            }\n            // parse range\n            std::pair<FloatType, FloatType> l_range = bias_range;\n            std::pair<FloatType, FloatType> q_range;\n            if(!use_quadratic_range)\n            {\n                q_range = bias_range;\n            }\n            else\n            {\n                q_range = quadratic_range;\n            }\n    \n            // calculate scaling value\n            auto comp = [](const auto &a, const auto &b) { return a.second < b.second; };\n            auto it_lin_min = std::min_element(m_linear.begin(), m_linear.end(), comp);\n            auto it_lin_max = std::max_element(m_linear.begin(), m_linear.end(), comp);\n            auto it_quad_min = std::min_element(m_quadratic.begin(), m_quadratic.end(), comp);\n            auto it_quad_max = std::max_element(m_quadratic.begin(), m_quadratic.end(), comp);\n    \n            std::vector<FloatType> v_scale =\n            {\n                it_lin_min->second / l_range.first,\n                it_lin_max->second / l_range.second,\n                it_quad_min->second / q_range.first,\n                it_quad_max->second / q_range.second\n            };\n            FloatType inv_scale = *std::max_element(v_scale.begin(), v_scale.end());\n    \n            // scaling\n            if(inv_scale != 0.0)\n            {\n                scale(1.0 / inv_scale, ignored_variables, ignored_interactions, ignored_offset);\n            }\n        }\n    \n        /**\n         * @brief Fix the value of a variable and remove it from a binary quadratic model.\n         * \n         * @param v\n         * @param value\n         */\n        void fix_variable\n        (\n            const IndexType &v,\n            const int32_t &value\n        )\n        {\n            std::vector<std::pair<IndexType, IndexType>> interactions;\n            for(auto &it : m_quadratic)\n            {\n                if(it.first.first == v)\n                {\n                    add_variable(it.first.second, value*it.second);\n                    interactions.push_back(it.first);\n                }\n                else if(it.first.second == v)\n                {\n                    add_variable(it.first.first, value*it.second);\n                    interactions.push_back(it.first);\n                }\n            }\n            remove_interactions_from(interactions);\n            add_offset(m_linear[v]*value);\n            remove_variable(v);\n        }\n    \n        /**\n         * @brief Fix the value of the variables and remove it from a binary quadratic model.\n         * \n         * @param fixed\n         */\n        void fix_variables\n        (\n            const std::vector<std::pair<IndexType, int32_t>> &fixed\n        )\n        {\n            for(auto &it : fixed)\n            {\n                fix_variable(it.first, it.second);\n            }\n        }\n    \n        /**\n         * @brief Flip variable v in a binary quadratic model.\n         * \n         * @param v\n         */\n        void flip_variable\n        (\n            const IndexType &v\n        )\n        {\n            // check variable\n            if(m_linear.count(v)==0)\n            {\n                throw std::runtime_error(\"not a variable in the binary quadratic model.\");\n            }\n    \n            if(m_vartype == Vartype::SPIN)\n            {\n                m_linear[v] *= -1.0;\n                for(auto &it : m_quadratic)\n                {\n                    if(it.first.first == v || it.first.second == v)\n                    {\n                        it.second *= -1.0;\n                    }\n                }\n            }\n            else if(m_vartype == Vartype::BINARY)\n            {\n                add_offset(m_linear[v]);\n                m_linear[v] *= -1.0;\n    \n                for(auto &it : m_quadratic)\n                {\n                    if(it.first.first == v)\n                    {\n                        m_linear[it.first.second] += it.second;\n                        it.second *= -1.0;\n                    }\n                    else if(it.first.second == v)\n                    {\n                        m_linear[it.first.first] += it.second;\n                        it.second *= -1.0;\n                    }\n                }\n            }\n        }\n    \n        /**\n         * @brief Enforce u, v being the same variable in a binary quadratic model.\n         * \n         * @param u\n         * @param v\n         */\n        void contract_variables\n        (\n            const IndexType &u,\n            const IndexType &v\n        )\n        {\n            // check variable\n            if(m_linear.count(v)==0)\n            {\n                throw std::runtime_error(\"not a variable in the binary quadratic model.\");\n            }\n            if(m_linear.count(u)==0)\n            {\n                throw std::runtime_error(\"not a variable in the binary quadratic model.\");\n            }\n    \n            auto p1 = std::make_pair(u, v);\n            auto p2 = std::make_pair(v, u);\n            if(m_quadratic.count(p1) != 0)\n            {\n                if(m_vartype == Vartype::BINARY)\n                {\n                    add_variable(u, m_quadratic[p1]);\n                }\n                else if(m_vartype == Vartype::SPIN)\n                {\n                    add_offset(m_quadratic[p1]);\n                }\n                remove_interaction(u, v);\n            }\n            if(m_quadratic.count(p2) != 0)\n            {\n                if(m_vartype == Vartype::BINARY)\n                {\n                    add_variable(u, m_quadratic[p2]);\n                }\n                else if(m_vartype == Vartype::SPIN)\n                {\n                    add_offset(m_quadratic[p2]);\n                }\n                remove_interaction(v, u);\n            }\n    \n            std::vector<std::pair<IndexType, IndexType>> interactions;\n            for(auto &it : m_quadratic)\n            {\n                if(it.first.first == v)\n                {\n                    add_interaction(u, it.first.second, it.second);\n                    interactions.push_back(it.first);\n                }\n                else if(it.first.second == v)\n                {\n                    add_interaction(it.first.first, u, it.second);\n                    interactions.push_back(it.first);\n                }\n            }\n            remove_interactions_from(interactions);\n    \n            add_variable(u, m_linear[v]);\n            remove_variable(v);\n        }\n    \n        /* Transformations */\n    \n        /**\n         * @brief Create a binary quadratic model with the specified vartype.\n         * This function does not return any object.\n         * \n         * @param vartype\n         */\n        void change_vartype\n        (\n            const Vartype &vartype\n        )\n        {\n            Linear<IndexType, FloatType> linear;\n            Quadratic<IndexType, FloatType> quadratic;\n            FloatType offset = 0.0;\n    \n            if(m_vartype == Vartype::BINARY && vartype == Vartype::SPIN) // binary -> spin\n            {\n                std::tie(linear, quadratic, offset) = binary_to_spin(m_linear, m_quadratic, m_offset);                \n            }\n            else if(m_vartype == Vartype::SPIN && vartype == Vartype::BINARY) // spin -> binary\n            {\n                std::tie(linear, quadratic, offset) = spin_to_binary(m_linear, m_quadratic, m_offset);\n            }\n            else\n            {\n                std::tie(linear, quadratic, offset) = std::tie(m_linear, m_quadratic, m_offset);\n            }\n    \n            //inplace\n            m_linear = linear;\n            m_quadratic = quadratic;\n            m_offset = offset;\n            m_vartype = vartype;\n        }\n\n        /**\n         * @brief Create a binary quadratic model with the specified vartype.\n         * \n         * @param vartype\n         * @param inplace\n         * @return A new instance of the BinaryQuadraticModel class.\n         */\n        BinaryQuadraticModel change_vartype\n        (\n            const Vartype &vartype,\n            bool inplace\n        )\n        {\n            Linear<IndexType, FloatType> linear;\n            Quadratic<IndexType, FloatType> quadratic;\n            FloatType offset = 0.0;\n    \n            if(m_vartype == Vartype::BINARY && vartype == Vartype::SPIN) // binary -> spin\n            {\n                std::tie(linear, quadratic, offset) = binary_to_spin(m_linear, m_quadratic, m_offset);                \n            }\n            else if(m_vartype == Vartype::SPIN && vartype == Vartype::BINARY) // spin -> binary\n            {\n                std::tie(linear, quadratic, offset) = spin_to_binary(m_linear, m_quadratic, m_offset);\n            }\n            else\n            {\n                std::tie(linear, quadratic, offset) = std::tie(m_linear, m_quadratic, m_offset);\n            }\n    \n            BinaryQuadraticModel bqm(linear, quadratic, offset, vartype);\n            \n            if(inplace == true)\n            {\n                //inplace\n                m_linear = bqm.get_linear();\n                m_quadratic = bqm.get_quadratic();\n                m_offset = bqm.get_offset();\n                m_vartype = bqm.get_vartype();\n            }\n    \n            return bqm;\n        }\n        \n        /* Static methods */\n        /**\n         * @brief Convert linear, quadratic, and offset from spin to binary. Does no checking of vartype. Copies all of the values into new objects.\n         * \n         * @param linear\n         * @param quadratic\n         * @param offset\n         * \n         * @return A tuple including a linear bias, a quadratic bias and an offset.\n         */\n        static std::tuple<Linear<IndexType, FloatType>, Quadratic<IndexType, FloatType>, FloatType> spin_to_binary\n        (\n            const Linear<IndexType, FloatType> &linear,\n            const Quadratic<IndexType, FloatType> &quadratic,\n            const FloatType &offset\n        )\n        {\n            Linear<IndexType, FloatType> new_linear;\n            Quadratic<IndexType, FloatType> new_quadratic;\n            FloatType new_offset = offset;\n            FloatType linear_offset = 0.0;\n            FloatType quadratic_offset = 0.0;\n    \n            for(auto &it : linear)\n            {\n                insert_or_assign(new_linear, it.first, static_cast<FloatType>(2.0 * it.second));\n                linear_offset += it.second;\n            }\n    \n            for(auto &it : quadratic)\n            {\n                insert_or_assign(new_quadratic, it.first, static_cast<FloatType>(4.0 * it.second));\n                new_linear[it.first.first] -= 2.0 * it.second;\n                new_linear[it.first.second] -= 2.0 * it.second;\n                quadratic_offset += it.second; \n            }\n    \n            new_offset += quadratic_offset - linear_offset;\n    \n            return std::make_tuple(new_linear, new_quadratic, new_offset);\n        }\n    \n        /**\n         * @brief Convert linear, quadratic and offset from binary to spin. Does no checking of vartype. Copies all of the values into new objects.\n         * \n         * @param linear\n         * @param quadratic\n         * @param offset\n         * \n         * @return A tuple including a linear bias, a quadratic bias and an offset.\n         */\n        static std::tuple<Linear<IndexType, FloatType>, Quadratic<IndexType, FloatType>, FloatType> binary_to_spin\n        (\n            const Linear<IndexType, FloatType> &linear,\n            const Quadratic<IndexType, FloatType> &quadratic,\n            const FloatType &offset\n        )\n        {\n            Linear<IndexType, FloatType> h;\n            Quadratic<IndexType, FloatType> J;\n            FloatType new_offset = offset;\n            FloatType linear_offset = 0.0;\n            FloatType quadratic_offset = 0.0;\n    \n            for(auto &it : linear)\n            {\n                insert_or_assign(h, it.first, static_cast<FloatType>(0.5 * it.second));\n                linear_offset += it.second;\n            }\n    \n            for(auto &it : quadratic)\n            {\n                insert_or_assign(J, it.first, static_cast<FloatType>(0.25 * it.second));\n                h[it.first.first] += 0.25 * it.second;\n                h[it.first.second] += 0.25 * it.second;\n                quadratic_offset += it.second;\n            }\n    \n            new_offset += 0.5 * linear_offset + 0.25 * quadratic_offset;\n    \n            return std::make_tuple(h, J, new_offset);\n        }\n    \n        /* Methods */\n    \n        /**\n         * @brief Determine the energy of the specified sample of a binary quadratic model.\n         * \n         * @param sample\n         * @return An energy with respect to the sample.\n         */\n        FloatType energy(const Sample<IndexType> &sample) const\n        {\n            FloatType en = m_offset;\n            for(auto &&it : m_linear)\n            {\n                if(check_vartype(sample.at(it.first), m_vartype))\n                {\n                    en += static_cast<FloatType>(sample.at(it.first)) * it.second;\n                }\n            }\n            for(auto &it : m_quadratic)\n            {\n                if(check_vartype(sample.at(it.first.first), m_vartype)&&check_vartype(sample.at(it.first.second), m_vartype))\n                {\n                    en += static_cast<FloatType>(sample.at(it.first.first)) * static_cast<FloatType>(sample.at(it.first.second)) * it.second;\n                }\n            }\n            return en;\n        }\n        \n        /**\n         * @brief Determine the energies of the given samples.\n         * \n         * @param samples_like\n         * @return A vector including energies with respect to the samples.\n         */\n        std::vector<FloatType> energies(const std::vector<Sample<IndexType>> &samples_like) const\n        {\n            std::vector<FloatType> en_vec;\n            for(auto &it : samples_like)\n            {\n                en_vec.push_back(energy(it));\n            }\n            return en_vec;\n        }\n        \n        /* Conversions */\n        /**\n         * @brief Convert a binary quadratic model to QUBO format.\n         * \n         * @return A tuple including a quadratic bias and an offset.\n         */\n        std::tuple<Quadratic<IndexType, FloatType>, FloatType> to_qubo()\n        {\n            // change vartype to binary\n            BinaryQuadraticModel bqm = change_vartype(Vartype::BINARY, false);\n    \n            Linear<IndexType, FloatType> linear = bqm.get_linear();\n            Quadratic<IndexType, FloatType> Q = bqm.get_quadratic();\n            FloatType offset = bqm.get_offset();\n            for(auto &it : linear)\n            {\n                insert_or_assign(Q, std::make_pair(it.first, it.first), it.second);\n            }\n            return std::make_tuple(Q, offset);\n        }\n    \n        /**\n         * @brief Create a binary quadratic model from a QUBO model.\n         *\n         * @param Q\n         * @param offset\n         *\n         * @return Binary quadratic model with vartype set to `.Vartype.BINARY`.\n         */\n        static BinaryQuadraticModel from_qubo(const Quadratic<IndexType, FloatType>& Q, FloatType offset=0.0)\n        {\n            Linear<IndexType, FloatType> linear;\n            Quadratic<IndexType, FloatType> quadratic;\n    \n            for(auto&& elem : Q){\n                const auto& key = elem.first;\n                const auto& value = elem.second;\n                if(key.first == key.second){\n                    linear[key.first] = value;\n                }\n                else{\n                    quadratic[std::make_pair(key.first, key.second)] = value;\n                }\n            }\n    \n            return BinaryQuadraticModel<IndexType, FloatType, DataType>(linear, quadratic, offset, Vartype::BINARY);\n        }\n    \n        /**\n         * @brief Convert a binary quadratic model to Ising format.\n         * \n         * @return A tuple including a linear bias, a quadratic bias and an offset.\n         */\n        std::tuple<Linear<IndexType, FloatType>, Quadratic<IndexType, FloatType>, FloatType> to_ising()\n        {\n            // change vartype to spin\n            BinaryQuadraticModel bqm = change_vartype(Vartype::SPIN, false);\n    \n            Linear<IndexType, FloatType> linear = bqm.get_linear();\n            Quadratic<IndexType, FloatType> quadratic = bqm.get_quadratic();\n            FloatType offset = bqm.get_offset();\n            return std::make_tuple(linear, quadratic, offset);\n        }\n    \n        /**\n         * @brief Create a binary quadratic model from an Ising problem.\n         *\n         * @param linear\n         * @param quadratic\n         * @param offset\n         *\n         * @return Binary quadratic model with vartype set to `.Vartype.SPIN`.\n         */\n        static BinaryQuadraticModel from_ising(const Linear<IndexType, FloatType>& linear, const Quadratic<IndexType, FloatType>& quadratic, FloatType offset=0.0)\n        {\n            return BinaryQuadraticModel<IndexType, FloatType, DataType>(linear, quadratic, offset, Vartype::SPIN);\n        }\n    \n    \n        /**\n         * @brief generate interaction matrix with given list of indices\n         * The generated matrix will be the following symmetric matrix:\n         * \\f[\n         * \\begin{pmatrix}\n         * \\tilde{J}_{0,0} & \\tilde{J}_{0,1} & \\tilde{J}_{0,2} & \\cdots \\\\\n         * \\tilde{J}_{1,0} & \\tilde{J}_{1,1} & \\tilde{J}_{1,2} & \\cdots \\\\\n         * \\tilde{J}_{2,0} & \\tilde{J}_{2,1} & \\tilde{J}_{2,2} & \\cdots \\\\\n         * \\vdots & \\vdots & \\vdots & \\ddots \\\\\n         * \\end{pmatrix}\n         * \\f]\n         *\n         * where in the Ising case,\n         * \\f[\n         * \\tilde{J}_{f(i),f(j)} = J_{ij} + J_{ji}, \\\\\n         * \\tilde{J}_{f(i),f(i)} = h_{i},\n         * \\f]\n         * and the QUBO case,\n         * \\f[\n         * \\tilde{J}_{f(i),f(j)} = Q_{ij} + Q_{ji}, \\\\\n         * \\tilde{J}_{f(i),f(i)} = Q_{ii},\n         * \\f]\n         * and the function \\f$f\\f$ denotes a mapping from index to the corresponding number specified by the argument `indices`.\n         * For instance, if `indices` is ['a', 'b', 'c'], The following equations, \\f$f(a) = 0, f(b)=1, \\mathrm{and} f(c)=2\\f$ hold.\n         *\n         * The original Hamiltonian can be rewritten with \\f$\\tilde{J_{ij}}\\f$ as\n         * \\f[\n         * E_{\\mathrm{Ising}} = \\sum_{i} \\tilde{J}_{f(i),f(i)} s_i + \\sum_{i < j} \\tilde{J}_{f(i), f(j)} s_i s_j + \\delta_{\\mathrm{Ising}},\n         * \\f]\n         * and\n         * \\f[\n         * E_{\\mathrm{QUBO}} = \\sum_{i} \\tilde{J}_{f(i), f(i)}x_i + \\sum_{i < j} \\tilde{J}_{f(i), f(j)} x_i x_j + \\delta_{\\mathrm{QUBO}}.\n         * \\f]\n         * @deprecated use interaction_matrix()\n         *\n         * @param indices\n         *\n         * @return corresponding interaction matrix (Eigen)\n         */\n        Matrix interaction_matrix(const std::vector<IndexType>& indices) const {\n            // generate matrix\n            size_t system_size = indices.size();\n            Matrix _interaction_matrix = Matrix::Zero(system_size, system_size);\n            const Linear<IndexType, FloatType>& linear = m_linear; \n            const Quadratic<IndexType, FloatType>& quadratic = m_quadratic; \n    \n            for(size_t i=0; i<indices.size(); i++){\n                const IndexType& i_index = indices[i];\n                _interaction_matrix(i, i) = (linear.find(i_index) != linear.end()) ? linear.at(i_index): 0;\n                for(size_t j=i+1; j<indices.size(); j++){\n                    const IndexType& j_index = indices[j];\n                    FloatType jval = 0.0;\n    \n                    if(quadratic.find(std::make_pair(i_index, j_index)) != quadratic.end()){\n                        jval += quadratic.at(std::make_pair(i_index, j_index));\n                    }\n                    if(quadratic.find(std::make_pair(j_index, i_index)) != quadratic.end()){\n                        jval += quadratic.at(std::make_pair(j_index, i_index));\n                    }\n    \n                    _interaction_matrix(i, j) = jval;\n                    _interaction_matrix(j, i) = jval;\n                }\n            }\n    \n            return _interaction_matrix;\n        }\n\n        /**\n         * @brief generate interaction matrix with given list of indices\n         * The generated matrix will be the following symmetric matrix:\n         * \\f[\n         * \\begin{pmatrix}\n         * J_{0,0} & J_{0,1} & \\cdots & J_{0,N-1} & h_{0}\\\\\n         * 0 & J_{1,1} & \\cdots & J_{1,N-1} & h_{1}\\\\\n         * \\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\n         * 0 & 0 & \\cdots & J_{N-1,N-1} & h_{N-1}\\\\\n         * 0 & 0 & \\cdots & 0 & 1 \\\\\n         * \\end{pmatrix}\n         * \\f]\n         *\n         */\n        Matrix interaction_matrix() const {\n            // generate matrix\n            auto indices = this->get_variables();\n            size_t system_size = this->get_num_variables();\n            Matrix _interaction_matrix = Matrix::Zero(system_size+1, system_size+1);\n            const Linear<IndexType, FloatType>& linear = m_linear; \n            const Quadratic<IndexType, FloatType>& quadratic = m_quadratic; \n    \n            for(size_t i=0; i<indices.size(); i++){\n                const IndexType& i_index = indices[i];\n                _interaction_matrix(i, system_size) = (linear.find(i_index) != linear.end()) ? linear.at(i_index): 0;\n                for(size_t j=i+1; j<indices.size(); j++){\n                    const IndexType& j_index = indices[j];\n                    FloatType jval = 0.0;\n    \n                    if(quadratic.find(std::make_pair(i_index, j_index)) != quadratic.end()){\n                        jval += quadratic.at(std::make_pair(i_index, j_index));\n                    }\n                    if(quadratic.find(std::make_pair(j_index, i_index)) != quadratic.end()){\n                        jval += quadratic.at(std::make_pair(j_index, i_index));\n                    }\n    \n                    _interaction_matrix(i, j) = jval;\n                }\n            }\n    \n            return _interaction_matrix;\n        }\n    \n    \n        using json = nlohmann::json;\n    \n        /**\n         * @brief Convert the binary quadratic model to a serializable object\n         * user_bytes is assume to be set to False\n         *\n         * @return An object that can be serialized (nlohmann::json)\n         */\n        json to_serializable() const\n        {\n            std::string schema_version = \"3.0.0\";\n            //all variables are contained in the keys of m_linear.\n            //All we need is to traverse the keys of m_linear.\n            /*\n             * output sample\n             * >>> bqm = dimod.BinaryQuadraticModel({'c': -1, 'd': 1}, {('a', 'd'): 2, ('b', 'e'): 5, ('a', 'c'): 3}, 0.0, dimod.BINARY)\n             *\n             * >>> bqm.to_serializable()\n             * {'type': 'BinaryQuadraticModel', 'version': {'bqm_schema': '3.0.0'}, 'use_bytes': False, 'index_type': 'uint16', 'bias_type': 'float32', 'num_variables': 5, 'num_interactions': 3, 'variable_labels': ['a', 'b', 'c', 'd', 'e'], 'variable_type': 'BINARY', 'offset': 0.0, 'info': {}, 'linear_biases': [0.0, 0.0, -1.0, 1.0, 0.0], 'quadratic_biases': [3.0, 2.0, 5.0], 'quadratic_head': [0, 0, 1], 'quadratic_tail': [2, 3, 4]}\n             */\n    \n            //set variables (sorted)\n            std::vector<IndexType> variables;\n            variables.reserve(m_linear.size());\n            for(auto&& elem : m_linear)\n            {\n                variables.push_back(elem.first);\n            }\n    \n            std::sort(variables.begin(), variables.end());\n    \n            size_t num_variables = variables.size();\n            \n            //set sorted linear biases\n            std::vector<FloatType> l_bias;\n            for(auto&& key : variables)\n            {\n                l_bias.push_back(m_linear.at(key));\n            }\n    \n            //set quadratic head, tail and biases\n            std::vector<size_t> q_head, q_tail;\n            std::vector<FloatType> q_bias;\n            for(auto&& elem : m_quadratic)\n            {\n                auto it_head = std::find(variables.begin(), variables.end(), elem.first.first);\n                auto it_tail = std::find(variables.begin(), variables.end(), elem.first.second);\n                size_t idx_head = std::distance(variables.begin(), it_head);\n                size_t idx_tail = std::distance(variables.begin(), it_tail);\n                q_head.push_back(idx_head);\n                q_tail.push_back(idx_tail);\n                q_bias.push_back(elem.second);\n            }\n    \n            size_t num_interactions =  m_quadratic.size();\n    \n            //set index_dtype\n            std::string index_dtype = num_variables <= 65536UL ? \"uint16\" : \"uint32\";\n    \n            //set bias_type\n            std::string bias_type;\n            if(typeid(m_offset) == typeid(float))\n            {\n                bias_type = \"float32\";\n            }\n            else if(typeid(m_offset) == typeid(double))\n            {\n                bias_type = \"float64\";\n            }\n            else\n            {\n                throw std::runtime_error(\"FloatType must be float or double.\");\n            }\n    \n            //set variable type\n            std::string variable_type;\n            if(m_vartype == Vartype::SPIN)\n            {\n                variable_type = \"SPIN\";\n            }\n            else if(m_vartype == Vartype::BINARY)\n            {\n                variable_type = \"BINARY\";\n            }\n            else\n            {\n                throw std::runtime_error(\"Variable type must be SPIN or BINARY.\");\n            }\n    \n            json output;\n            output[\"type\"] = \"BinaryQuadraticModel\";\n            output[\"version\"] = {{\"bqm_schema\", \"3.0.0\"}};\n            output[\"variable_labels\"] = variables;\n            output[\"use_bytes\"] = false;\n            output[\"index_type\"] = index_dtype;\n            output[\"bias_type\"] = bias_type;\n            output[\"num_variables\"] = num_variables;\n            output[\"num_interactions\"] = num_interactions;\n            output[\"variable_labels\"] = variables;\n            output[\"variable_type\"] = variable_type;\n            output[\"offset\"] = m_offset;\n            output[\"info\"] = \"\";\n            output[\"linear_biases\"] = l_bias;\n            output[\"quadratic_biases\"] = q_bias;\n            output[\"quadratic_head\"] = q_head;\n            output[\"quadratic_tail\"] = q_tail;\n    \n            return output;\n        }\n    \n        /**\n         * @brief Create a BinaryQuadraticModel instance from a serializable object.\n         * \n         * @tparam IndexType_serial\n         * @tparam FloatType_serial\n         * @param input\n         * @return BinaryQuadraticModel<IndexType_serial, FloatType_serial, DataType> \n         */\n        template <typename IndexType_serial = IndexType, typename FloatType_serial = FloatType>\n        static BinaryQuadraticModel<IndexType_serial, FloatType_serial, DataType> from_serializable(const json &input)\n        {\n            //extract type and version\n            std::string type = input[\"type\"];\n            if(type != \"BinaryQuadraticModel\")\n            {\n                throw std::runtime_error(\"Type must be \\\"BinaryQuadraticModel\\\".\\n\");\n            }\n            std::string version = input[\"version\"][\"bqm_schema\"];\n            if(version != \"3.0.0\")\n            {\n                throw std::runtime_error(\"bqm_schema must be 3.0.0.\\n\");\n            }\n    \n            //extract variable_type\n            Vartype vartype;\n            std::string variable_type = input[\"variable_type\"];\n            if(variable_type == \"SPIN\")\n            {\n                vartype = Vartype::SPIN;\n            }\n            else if(variable_type == \"BINARY\")\n            {\n                vartype = Vartype::BINARY;\n            }\n            else\n            {\n                throw std::runtime_error(\"variable_type must be SPIN or BINARY.\");\n            }\n    \n            //extract linear biases\n            Linear<IndexType_serial, FloatType_serial> linear;\n            std::vector<IndexType_serial> variables = input[\"variable_labels\"];\n            std::vector<FloatType_serial> l_bias = input[\"linear_biases\"];\n            for(size_t i = 0; i < variables.size(); ++i)\n            {\n                insert_or_assign(linear, variables[i], l_bias[i]);\n            }\n    \n            //extract quadratic biases\n            Quadratic<IndexType_serial, FloatType_serial> quadratic;\n            std::vector<size_t> q_head = input[\"quadratic_head\"];\n            std::vector<size_t> q_tail = input[\"quadratic_tail\"];\n            std::vector<FloatType_serial> q_bias = input[\"quadratic_biases\"];\n            for(size_t i = 0; i < q_head.size(); ++i)\n            {\n                insert_or_assign(quadratic, std::make_pair(variables[q_head[i]], variables[q_tail[i]]), q_bias[i]);\n            }\n    \n            //extract offset and info\n            FloatType_serial offset = input[\"offset\"];\n    \n            //construct a BinaryQuadraticModel instance\n            BinaryQuadraticModel<IndexType_serial, FloatType_serial, DataType> bqm(linear, quadratic, offset, vartype);\n            return bqm;\n        }\n    \n    };\n}\n#endif\n", "meta": {"hexsha": "4f0201f841b1f09a27c6abba54e8bf339cd0379a", "size": 49515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graph/cimod/src/binary_quadratic_model_dict.hpp", "max_stars_repo_name": "29rou/OpenJij", "max_stars_repo_head_hexsha": "c2579fba8710cf82b9e6761304f0042b365b595c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-01-05T13:37:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:11:08.000Z", "max_issues_repo_path": "src/graph/cimod/src/binary_quadratic_model_dict.hpp", "max_issues_repo_name": "OpenJij/OpenJij", "max_issues_repo_head_hexsha": "9ed58500ef47583bc472410d470bb2dd4bfec74a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2019-01-29T09:55:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T04:06:20.000Z", "max_forks_repo_path": "src/graph/cimod/src/binary_quadratic_model_dict.hpp", "max_forks_repo_name": "29rou/OpenJij", "max_forks_repo_head_hexsha": "c2579fba8710cf82b9e6761304f0042b365b595c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T07:55:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T14:27:23.000Z", "avg_line_length": 32.8784860558, "max_line_length": 434, "alphanum_fraction": 0.4851661113, "num_tokens": 10905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.03963883895915716, "lm_q1q2_score": 0.019509766249444404}}
{"text": "/*\n * Copyright (C) 2021, Thibaud Briand, ENS Cachan <thibaud.briand@ens-cachan.fr>\n * Copyright (C) 2021, Jonathan Vacher, ENS Cachan <jvacher@ens-cachan.fr>\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 <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include \"ps_lib.h\"\n#include \"toolbox.h\"\n#include \"Eigen/Dense\"\n#include <unsupported/Eigen/Polynomials>\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\nusing namespace std;\n\n// Allocate memory for the sample statistics\nvoid allocate_stats(statsStruct *stats, const paramsStruct params, int nz)\n{\n  int i;\n  int N_pyr = params.N_pyr;\n  int N_steer = params.N_steer;\n  int Na = params.Na;\n\n  stats->pixelStats = (float *) malloc(N_PIXELSTATS*nz*sizeof(float));\n  stats->skewLow = (float *) malloc((1+N_pyr)*nz*sizeof(float));\n  stats->kurtLow = (float *) malloc((1+N_pyr)*nz*sizeof(float));\n  stats->varHigh = (float *) malloc(nz*sizeof(float));\n  stats->magMeans = (float *) malloc(N_pyr*N_steer*nz*sizeof(float));\n  stats->autoCorLow = (float **) malloc((1+N_pyr)*sizeof(float *));\n  for(i = 0; i < 1+N_pyr; i++)\n    stats->autoCorLow[i] = (float *) malloc(Na*Na*nz*sizeof(float));\n  stats->autoCorMag = (float **) malloc(N_pyr*N_steer*sizeof(float *));\n  for(i = 0; i < N_pyr*N_steer; i++)\n    stats->autoCorMag[i] = (float *) malloc(Na*Na*nz*sizeof(float));\n  stats->cousinMagCor = (float **) malloc(N_pyr*sizeof(float *));\n  for(i = 0; i < N_pyr; i++)\n    stats->cousinMagCor[i] = (float *)\n      malloc(N_steer*N_steer*nz*nz*sizeof(float));\n  stats->parentMagCor = (float **) malloc((N_pyr-1)*sizeof(float *));\n  for(i = 0; i < N_pyr-1; i++)\n    stats->parentMagCor[i] = (float *)\n      malloc(N_steer*N_steer*nz*nz*sizeof(float));\n  stats->parentRealCor = (float **) malloc(N_pyr*sizeof(float *));\n  for(i = 0; i < N_pyr-1; i++)\n    stats->parentRealCor[i] = (float *)\n      malloc(2*N_steer*N_steer*nz*nz*sizeof(float));\n  if (nz == 3) {\n    stats->parentRealCor[N_pyr-1] = (float *)\n      malloc(N_SMALLEST*N_steer*nz*nz*sizeof(float));\n    stats->pixelStatsPCA = (float *) malloc(N_PIXELSTATSPCA*nz*sizeof(float));\n    stats->autoCorPCA = (float *) malloc(Na*Na*nz*sizeof(float));\n    stats->cousinRealCor = (float **) malloc((1+N_pyr)*sizeof(float *));\n    for(i = 0; i < N_pyr; i++)\n      stats->cousinRealCor[i] = (float *)\n        malloc(N_steer*N_steer*nz*nz*sizeof(float));\n    stats->cousinRealCor[N_pyr] = (float *)\n      malloc(N_SMALLEST*N_SMALLEST*nz*nz*sizeof(float));\n  }\n}\n\n// Free memory for the sample statistics\nvoid free_stats(statsStruct stats, const paramsStruct params, int nz)\n{\n  int i;\n  int N_pyr = params.N_pyr;\n  int N_steer = params.N_steer;\n\n  free(stats.pixelStats);\n  free(stats.skewLow);\n  free(stats.kurtLow);\n  free(stats.varHigh);\n  free(stats.magMeans);\n  for(i = 0; i < 1+N_pyr; i++) {\n    free(stats.autoCorLow[i]);\n    if (nz == 3)\n      free(stats.cousinRealCor[i]);\n  }\n  free(stats.autoCorLow);\n  for(i = 0; i < N_pyr*N_steer; i++)\n    free(stats.autoCorMag[i]);\n  free(stats.autoCorMag);\n  for(i = 0; i < N_pyr - 1; i++) {\n    free(stats.parentMagCor[i]);\n    free(stats.parentRealCor[i]);\n  }\n  if ( nz == 3)\n    free(stats.parentRealCor[N_pyr-1]);\n  for(i = 0; i < N_pyr; i++) {\n    free(stats.cousinMagCor[i]);\n  }\n  free(stats.cousinMagCor);\n  free(stats.parentMagCor);\n  free(stats.parentRealCor);\n  if( nz == 3 ) {\n    free(stats.cousinRealCor);\n    free(stats.pixelStatsPCA);\n    free(stats.autoCorPCA);\n  }\n}\n\n// Function for writing the statistics in a file\nvoid write_statistics(const statsStruct stats, const paramsStruct params, int nz)\n{\n  int i, j, l, ind;\n  int N_pyr = params.N_pyr;\n  int N_steer = params.N_steer;\n  int Na = params.Na;\n\n  // open file\n  FILE *fp = fopen(\"statistics_evolution.txt\", \"a\");\n\n  // summary statistics (i)(a)\n  for (i = 0; i < 1+N_pyr; i++) {\n    for (l = 0; l < nz; l++)\n      fprintf(fp, \" %f %f\", stats.skewLow[i + (1+N_pyr)*l],\n              stats.kurtLow[i + (1+N_pyr)*l]);\n    fprintf(fp, \",\");\n  }\n\n  // summary statistics (i)(b)\n  for(l = 0; l < nz; l++)\n    fprintf(fp, \" %f\", stats.varHigh[l]);\n  fprintf(fp, \",\");\n\n  // summary statistics (i)(c)\n  for (l = 0; l < nz; l++)\n    for (i = 0; i < 6; i++)\n      fprintf(fp, \" %f\", stats.pixelStats[i + N_PIXELSTATS*l]);\n  fprintf(fp, \",\");\n\n  // summary statistics (ii)\n  for (i = 0; i < 1+N_pyr; i++) {\n    for(l = 0; l < Na*Na*nz; l++)\n      fprintf(fp, \" %f\", stats.autoCorLow[i][l]);\n    fprintf(fp, \",\");\n  }\n\n  // summary statistics (iii)\n  for(i = 0; i < N_pyr; i++) {\n    for(j = 0; j < N_steer; j++) {\n      ind = j + i*N_steer;\n      for(l = 0; l < Na*Na*nz; l++)\n        fprintf(fp, \" %f\", stats.autoCorMag[ind][l]);\n      fprintf(fp, \",\");\n    }\n  }\n\n  // summary statistics (iv)\n  for(i = 0; i < N_pyr; i++) {\n    for(l = 0; l < N_steer*N_steer*nz*nz; l++)\n      fprintf(fp, \" %f\", stats.cousinMagCor[i][l]);\n    fprintf(fp, \",\");\n  }\n\n  // summary statistics (v)\n  for(i = 0; i < N_pyr - 1; i++) {\n    for(l = 0; l < N_steer*N_steer*nz*nz; l++)\n      fprintf(fp, \" %f\", stats.parentMagCor[i][l]);\n    fprintf(fp, \",\");\n  }\n\n  // summary statistics (vi)\n  for(i = 0; i < N_pyr - 1; i++) {\n    for(l = 0; l < 2*N_steer*N_steer*nz*nz; l++)\n      fprintf(fp, \" %f\", stats.parentRealCor[i][l]);\n    fprintf(fp, \",\");\n  }\n\n  if( nz == 3 ) {\n    // summary statistics (vii)\n    for(l = 0; l < 3; l++)\n      for(i = 0; i < 3; i++)\n        fprintf(fp, \" %f\", stats.covariancePCA[l][i]);\n    fprintf(fp, \",\");\n\n    // summary statistics (viii)\n    for(i = 0; i < Na*Na*nz; i++)\n      fprintf(fp, \" %f\", stats.autoCorPCA[i]);\n    fprintf(fp, \",\");\n\n    // summary statistics (ix)\n    for (l = 0; l < 3; l++)\n      for (i = 0; i < 2; i++)\n        fprintf(fp, \" %f\", stats.pixelStatsPCA[i + N_PIXELSTATSPCA*l]);\n    fprintf(fp, \",\");\n\n    // summary statistics (x)\n    for(i = 0; i < N_pyr; i++) {\n      for(l = 0; l < N_steer*N_steer*nz*nz; l++)\n        fprintf(fp, \" %f\", stats.cousinRealCor[i][l]);\n      fprintf(fp, \",\");\n    }\n\n    // summary statistics (xi)\n    for(l = 0; l < N_SMALLEST*N_SMALLEST*nz*nz; l++)\n      fprintf(fp, \" %f\", stats.cousinRealCor[N_pyr][l]);\n    fprintf(fp, \",\");\n\n    // summary statistics (xii)\n    for(l = 0; l < N_steer*N_SMALLEST*nz*nz; l++)\n      fprintf(fp, \" %f\", stats.parentRealCor[N_pyr-1][l]);\n    fprintf(fp, \",\");\n  }\n\n  // close file\n  fprintf(fp, \"\\n\");\n  fclose(fp);\n}\n\n// Apply an integer shift of (ofx, ofy) to an image\n// out(i,j) = in(i - ofx, j - ofy)\n// It is done using the nearest neighbor interpolation\n// with periodic boundary condition\nvoid shift(float *out, const float *in, int ofx, int ofy,\n           int nx, int ny, int nz)\n{\n  int i, j, l, i2, j2;\n  for(j = 0; j < ny; j++) {\n    j2 = (j - ofy) % ny;\n    j2 = (j2 < 0) ? j2 + ny : j2;\n    for(i = 0; i < nx; i++) {\n      i2 = (i - ofx) % nx;\n      i2 = (i2 < 0) ? i2 + nx : i2;\n      for(l = 0; l < nz; l++)\n          out[i+j*nx+l*nx*ny] = in[i2 + j2*nx + l*nx*ny];\n    }\n  }\n}\n\n/* moment part */\n\n// Compute the mean of an array\nfloat mean(const float *data, int N)\n{\n  double m = 0.0;\n\n  // sum loop\n  for(int i = 0; i < N; i++)\n    m += data[i];\n\n  // normalization\n  m /= N;\n\n  return m;\n}\n\n// Compute the moment of a given order of an array (Equation 39)\n// To save computations the mean is computed outside this function\nfloat compute_moment(const float *data, float m, int order, int N)\n{\n  double moment = 0.0;\n  double tmp, tmp2;\n\n  // sum loop\n  for(int i = 0; i < N; i++) {\n    tmp = 1.0;\n    tmp2 = data[i] - m;\n    for(int j = 0; j < order; j++)\n      tmp *= tmp2;\n    moment += tmp;\n  }\n\n  // normalization\n  moment /= N;\n\n  return moment;\n}\n\n// Compute the skewness of an array (Equation 40)\n// Set the value to 0 for a constant image\nfloat compute_skewness(const float *data_in, float m, float var, int N)\n{\n  float order_3 = compute_moment(data_in, m, 3, N);\n  float skewness = (var > 0) ? order_3/sqrt(var*var*var) : 0;\n\n  return skewness;\n}\n\n// Compute the kurtosis of an array (Equation 40)\n// Set the value to 3 for a constant image\nfloat compute_kurtosis(const float *data_in, float m, float var, int N)\n{\n  float order_4 = compute_moment(data_in, m, 4, N);\n  float kurtosis = (var > 0) ? order_4/(var*var) : 3;\n\n  return kurtosis;\n}\n\n/* range part */\n\n// Compute the min and max values of an array\nvoid min_and_max(float *m, float *M, const float *tab, int N)\n{\n  *m = *M = tab[0];\n\n  for(int i = 1; i < N; i++) {\n    if (tab[i] < *m) *m = tab[i];\n    if (tab[i] > *M) *M = tab[i];\n  }\n}\n\n// Adjust the range of an array so that it fits in [m;M] (Appendix A.1.1)\n// This corresponds to Equation 49\nvoid adjust_range(float *data, float m, float M, int N)\n{\n  // loop on the array\n  for(int i = 0; i < N; i++) {\n    // projection in [m,M]\n    if (data[i] < m)\n      data[i] = m;\n    else if (data[i] > M)\n      data[i] = M;\n  }\n}\n\n/* Modification part of marginal statistics */\n\n// Adjust the mean and the variance of an array (Appendix A.1.2)\n// This corresponds to Equation 50\nvoid adjust_mean_variance(float *data, float mean_out, float var_out, int N)\n{\n  // compute the input mean and variance\n  float m = mean(data, N);\n  float var_in = compute_moment(data, m, 2, N);\n\n  float factor = (var_in > 0) ? sqrt(var_out/var_in) : 1;\n  // loop on the array\n  for(int i = 0; i < N; i++)\n    data[i] = factor*(data[i]-m) + mean_out;\n}\n\n// Adjust the skewness of an array (Appendix A.1.3)\n// This corresponds to Algorithm 6\n// The input data is assumed to have a zero mean\nvoid adjust_skewness(float *data, float sk_out, int N)\n{\n  int i;\n\n  // computation of the moments (Line 1)\n  // this is done outside of the function compute_moment to save computations\n  double m2 = 0.0;\n  double m3 = 0.0;\n  double m4 = 0.0;\n  double m5 = 0.0;\n  double m6 = 0.0;\n  double tmp, tmp2;\n  for (i = 0; i < N; i++) {\n    tmp2 = tmp = data[i];\n\n    tmp2 *= tmp;\n    m2 += tmp2;\n\n    tmp2 *= tmp;\n    m3 += tmp2;\n\n    tmp2 *= tmp;\n    m4 += tmp2;\n\n    tmp2 *= tmp;\n    m5 += tmp2;\n\n    tmp2 *= tmp;\n    m6 += tmp2;\n  }\n  tmp = 1.0/N;\n  m2 *= tmp;\n  m3 *= tmp;\n  m4 *= tmp;\n  m5 *= tmp;\n  m6 *= tmp;\n\n  // compute skewness of the input (Line 2)\n  double std = sqrt(m2);\n  double sk_in = m3/(std*std*std);\n\n  // security check\n  double snr = 20*log10(fabs(sk_out/(sk_out-sk_in)));\n\n  // do nothing if the skewness are too close\n  if ( snr <= 60 ) {\n    // polynomial coefficients computation (Line 3)\n    // coefficients of the numerator P (Equation 56)\n    double p0 = sk_in*m2*std;\n    double p1 = 3 * ( m4 - m2 * m2 * ( 1 + sk_in*sk_in ) );\n    double p2 = 3 * ( m5 - 2*std*sk_in*m4 + m2*m2*std*sk_in*sk_in*sk_in );\n    double p3 = m6 - 3*std*sk_in*m5 + 3*m2*(sk_in*sk_in - 1)*m4\n                + m2*m2*m2*(2 + 3*sk_in*sk_in - sk_in*sk_in*sk_in*sk_in);\n    Vector4d poly_num;\n    poly_num << p0, p1, p2, p3;\n\n    // coefficients of the denominator Q (Equation 56)\n    double q0 = m2;\n    double q1 = 0;\n    double q2 = m4 - (1 + sk_in*sk_in)*m2*m2;\n    Vector3d poly_denom;\n    poly_denom << q0, q1, q2;\n\n    // coefficients of Q^3(X^2) (Equation 60)\n    double b0 = q0*q0*q0;\n    double b2 = 3*q0*q0*q2;\n    double b4 = 3*q0*q2*q2;\n    double b6 = q2*q2*q2;\n    VectorXd b_poly(4);\n    b_poly << b0, b2, b4, b6;\n\n    // derivative with respect to lambda (Equation 62)\n    double d0 = p1*b0;\n    double d1 = -p0*b2 + 2*p2*b0;\n    double d2 = 3*p3*b0;\n    double d3 = -2*p0*b4 + p2*b2;\n    double d4 = -p1*b4 + 2*p3*b2;\n    double d5 = -3*p0*b6;\n    double d6 = -2*p1*b6 + p3*b4;\n    double d7 = -p2*b6;\n    VectorXd derivative(8);\n    derivative << d0, d1, d2, d3, d4, d5, d6, d7;\n\n    // compute the roots of d (Line 4)\n    PolynomialSolver< double, 7 > dsolve( derivative );\n\n    // find the minimal and maximal skewness reachable (Line 5 and Line 6)\n    double lneg = - 1e6;\n    double lpos = 1e6;\n    double real_part;\n    for (i = 0; i < 7; i++) {\n      real_part = dsolve.roots()[i].real();\n      if ( fabs(dsolve.roots()[i].imag()/real_part)<1e-6 ) {\n        if ( real_part < 0 && real_part > lneg )\n          lneg = real_part;\n        else if ( real_part > 0 && real_part < lpos )\n          lpos = real_part;\n      }\n    }\n    double skmin = poly_eval(poly_num, lneg)/sqrt(poly_eval(b_poly, lneg*lneg));\n    double skmax = poly_eval(poly_num, lpos)/sqrt(poly_eval(b_poly, lpos*lpos));\n\n    // solve for lambda (Line 7 to 19)\n    double lambda = 0.0;\n    if ( sk_out <= skmin ) // saturating down the skewness (Line 8 and Line 9)\n      lambda = lneg;\n    else if ( sk_out >= skmax ) // saturating up the skewness (Line 10 and Line 11)\n      lambda = lpos;\n    else {\n      // define the polynomial A = P^2 - sk_out^2*Q^2 (Equation 58)\n      // This is done in Line 3\n      double sk_out2 = sk_out * sk_out;\n      double a0 = p0*p0 - sk_out2*b0;\n      double a1 = 2*p1*p0;\n      double a2 = p1*p1 + 2*p2*p0 - sk_out2*b2;\n      double a3 = 2*(p3*p0 + p1*p2);\n      double a4 = p2*p2 + 2*p3*p1 - sk_out2*b4;\n      double a5 = 2*p3*p2;\n      double a6 = p3*p3 - sk_out2*b6;\n\n      // declare the polynomials\n      VectorXd poly(7);\n      poly << a0, a1, a2, a3, a4, a5, a6;\n\n      // solve the polynomial (Line 13)\n      PolynomialSolver< double, 6 > psolve( poly );\n\n      // keep the real roots (Line 14)\n      double real_roots[6] = {0};\n      int p = 0; // number of real roots\n      for(i = 0; i < 6; i++) {\n        real_part = psolve.roots()[i].real();\n        if ( fabs(psolve.roots()[i].imag()/real_part) < 1e-6 )\n          real_roots[p++]= real_part;\n      }\n\n      if ( p == 1 ) // if only one solution left (Line 15 and Line 16)\n        lambda = real_roots[0];\n      else if ( p > 1 ) { // if several solutions left (Line 17)\n        // keep the roots giving the numerator of good sign (Line 18)\n        // if the sign is 0 it is accepted\n        int q = 0; // number of acceptable solution\n        double final_roots[6]={0};\n        int sign0 = ( fabs(sk_out)<1e-6 ) ? 0 : (sk_out>0)-(sk_out<0);\n        int sign;\n        double numerator;\n        for(i = 0; i < p; i++) {\n          numerator = poly_eval(poly_num, real_roots[i]);\n          sign = ( fabs(numerator)<1e-6 ) ? 0 : (numerator > 0)-(numerator < 0);\n          if( sign == sign0 || sign*sign0 == 0 )\n            final_roots[q++]= real_roots[i];\n        }\n\n        // get the solution with minimal modulus (Line 19)\n        if(q > 0) {\n          lambda = final_roots[0];\n          double modulus = fabs(lambda);\n          for (i = 1; i < q; i++) {\n            double modulus2 = fabs(final_roots[i]);\n            if ( modulus2 < modulus) {\n              lambda = final_roots[i];\n              modulus = modulus2;\n            }\n          }\n        }\n      }\n    }\n\n    // gradient descent (Line 20)\n    double g;\n    double stdsk = std*sk_in;\n    for(i = 0; i < N ; i++) {\n      g = data[i]*(data[i]-stdsk)-m2;\n      data[i] += lambda*g;\n    }\n\n    // adjust the mean and the variance (to insure the stability of the code)\n    adjust_mean_variance(data, 0.0, m2, N);\n  }\n}\n\n// Adjust the kurtosis of an array (Appendix A.1.4)\n// This corresponds to Algorithm 7\n// The input data is assumed to have a zero mean\nvoid adjust_kurtosis(float *data, float ku_out, int N)\n{\n  int i;\n\n  // computation of the moments (Line 1)\n  // this is done outside of compute_moment to save computations\n  double m2 = 0.0;\n  double m3 = 0.0;\n  double m4 = 0.0;\n  double m5 = 0.0;\n  double m6 = 0.0;\n  double m7 = 0.0;\n  double m8 = 0.0;\n  double m9 = 0.0;\n  double m10 = 0.0;\n  double m12 = 0.0;\n  double tmp, tmp2;\n  for (i = 0; i < N; i++) {\n    tmp2 = tmp = data[i];\n\n    tmp2 *= tmp;\n    m2 += tmp2;\n\n    tmp2 *= tmp;\n    m3 += tmp2;\n\n    tmp2 *= tmp;\n    m4 += tmp2;\n\n    tmp2 *= tmp;\n    m5 += tmp2;\n\n    tmp2 *= tmp;\n    m6 += tmp2;\n\n    tmp2 *= tmp;\n    m7 += tmp2;\n\n    tmp2 *= tmp;\n    m8 += tmp2;\n\n    tmp2 *= tmp;\n    m9 += tmp2;\n\n    tmp2 *= tmp;\n    m10 += tmp2;\n\n    tmp2 *= tmp*tmp;\n    m12 += tmp2;\n  }\n  tmp = 1.0/N;\n  m2 *= tmp;\n  m3 *= tmp;\n  m4 *= tmp;\n  m5 *= tmp;\n  m6 *= tmp;\n  m7 *= tmp;\n  m8 *= tmp;\n  m9 *= tmp;\n  m10 *= tmp;\n  m12 *= tmp;\n\n  // compute the kurtosis of the input (Line 2)\n  double ku_in = m4/(m2*m2);\n\n  // security check\n  double snr = 20*log10(fabs(ku_out/(ku_out-ku_in)));\n  if ( snr <= 60 ) { // do nothing if the kurtoses are too close\n    // polynomial coefficients computation (Line 3)\n    // auxilary useful variable\n    double alpha = m4/m2;\n\n    // define the coefficients of the numerator (Line 67)\n    double p0 = m4;\n    double p1 = 4 * ( m6 - alpha * alpha * m2 - m3 * m3 );\n    double p2 = 6 * ( m8 - 2 * alpha * m6 - 2 * m3 * m5 + alpha * alpha * m4\n      + (m2 + 2*alpha) * m3 * m3 );\n    double p3 = 4 * ( m10 - 3 * alpha * m8 - 3 * m3 * m7\n      + 3 * alpha * alpha * m6 + 6 * alpha * m3 * m5\n      + 3 * m3 * m3 * m4 - alpha * alpha * alpha * m4\n      - 3 * alpha * alpha * m3 * m3 - 3 * m4 * m3 * m3 );\n    double p4 =  m12 - 4 * alpha * m10 - 4 * m3 * m9\n      + 6 * alpha * alpha * m8 + 12 * alpha * m3 * m7 +  6 * m3 * m3 * m6\n      - 4 * alpha * alpha * alpha * m6 - 12 * alpha * alpha * m3 * m5\n      + alpha * alpha * alpha * alpha * m4 - 12 * alpha * m3 * m3 * m4\n      + 4 * alpha * alpha * alpha * m3 * m3 + 6 * alpha * alpha * m3 * m3 * m2\n      - 3 * m3 * m3 * m3 * m3;\n    VectorXd poly_num(5);\n    poly_num << p0, p1, p2, p3, p4;\n\n    // define the coefficients of the denominator (Line 67)\n    double q0 = m2;\n    double q1 = 0;\n    double q2 = p1*0.25;\n    Vector3d poly_denom;\n    poly_denom << q0, q1, q2;\n\n    // derivative with respect to lambda (Line 71)\n    double d0 = p1*q0;\n    double d1 = -4*q2*p0 + 2*p2*q0;\n    double d2 = -3*q2*p1 + 3*p3*q0;\n    double d3 = -2*p2*q2 + 4*p4*q0;\n    double d4 = -p3*q2;\n    VectorXd derivative(5);\n    derivative << d0, d1, d2, d3, d4;\n\n    // compute the roots of d (Line 4)\n    PolynomialSolver< double, 4 > dsolve( derivative );\n\n    // find the minimal and maximal kurtosis reachable (Line 5 and Line 6)\n    double lneg = - 1e6;\n    double lpos = 1e6;\n    double real_part;\n    for (i = 0; i<4; i++) {\n      real_part = dsolve.roots()[i].real();\n      if ( fabs(dsolve.roots()[i].imag()/real_part) < 1e-6 ) {\n        if ( real_part < 0 && real_part > lneg )\n          lneg = real_part;\n        else if ( real_part > 0 && real_part < lpos )\n          lpos = real_part;\n      }\n    }\n    tmp = poly_eval(poly_denom, lneg);\n    double kumin = poly_eval(poly_num, lneg)/(tmp*tmp);\n    tmp = poly_eval(poly_denom, lpos);\n    double kumax = poly_eval(poly_num, lpos)/(tmp*tmp);\n\n    // solves for lambda (Line 7 to 15)\n    double lambda = 0.0;\n    if ( ku_out <= kumin ) // saturating down the skewness (Line 8 and Line 9)\n      lambda = lneg;\n    else if ( ku_out >= kumax ) // saturating up the skewness (Line 10 and Line 11)\n      lambda = lpos;\n    else {\n      // define the polynomial (Equation 69)\n      // this is done in Line 3\n      double a4 = p4 - ku_out*q2*q2;\n      double a3 = p3;\n      double a2 = p2 - 2*ku_out*q0*q2;\n      double a1 = p1;\n      double a0 = p0 - ku_out*q0*q0;\n      VectorXd poly(5);\n      poly << a0, a1, a2, a3, a4;\n\n      // compute the roots of a (Line 13)\n      PolynomialSolver< double, 4 > psolve( poly );\n\n      // keep the real roots (Line 14)\n      double real_roots[4] = {0};\n      int p = 0; // number of real roots\n      for(i = 0; i < 4; i++) {\n        real_part = psolve.roots()[i].real();\n        if ( fabs(psolve.roots()[i].imag()/real_part) < 1e-6 )\n            real_roots[p++] = real_part;\n      }\n\n      // if acceptable solutions get the one with smallest modulus (Line 15)\n      if ( p > 0 ) {\n        lambda = real_roots[0];\n        double modulus = fabs(lambda);\n        for (i = 1; i < p; i++) {\n          double modulus2 = fabs(real_roots[i]);\n          if ( modulus2 < modulus) {\n            lambda = real_roots[i];\n            modulus = modulus2;\n          }\n        }\n      }\n    }\n\n    // gradient descent (Line 16)\n    double g;\n    for(i = 0; i < N ; i++) {\n      g = data[i] * (data[i] * data[i] - alpha ) - m3;\n      data[i] += lambda * g;\n    }\n\n    // adjust the mean and the variance\n    adjust_mean_variance(data, 0.0, m2, N);\n  }\n}\n\n/* Correlation part */\n\n// Compute the central part of the auto-correlation of an image (Equation 42)\n// Na is assumed to be an odd number smaller than nx and ny\n// The input data is assumed to have a zero mean\nvoid compute_auto_cor(float *Ac, const float *in, fftwf_complex *in_plan,\n                      fftwf_complex *out_plan, fftwf_plan plan,\n                      fftwf_plan iplan, int nx, int ny, int nz, int Na)\n{\n  int i, j, l;\n\n  // memory allocation\n  fftwf_complex *fft = (fftwf_complex *)\n    fftwf_malloc( nx*ny*nz * sizeof(fftwf_complex));\n  float *full_auto_cor = (float *) malloc(nx*ny*nz*sizeof(float));\n\n  // compute the fft\n  do_fft_plan_real(plan, out_plan, in_plan, fft, in, nx*ny, nz);\n\n  // squared modulus\n  for(i = 0; i < nx*ny*nz; i++) {\n    fft[i][0] = fft[i][0]*fft[i][0] + fft[i][1]*fft[i][1];\n    fft[i][1] = 0.0;\n  }\n\n  // compute the inverse fft\n  do_ifft_plan_real(iplan, out_plan, in_plan, full_auto_cor, fft, nx*ny, nz);\n\n  // keep the central part of size Na*Na\n  int hNa = (Na-1)/2;\n  float ifactor = 1.0/(nx*ny);\n  int ind;\n  for(i = 0; i < Na ;i++) {\n    for(j = 0; j < Na; j++) {\n      if((i < hNa) && (j < hNa))\n        ind = nx - hNa + i + (ny-hNa+j)*nx;\n      else if((i < hNa) && (j> hNa-1))\n        ind = nx - hNa + i + (j-hNa)*nx;\n      else if((i > hNa-1) && (j < hNa))\n        ind = i - hNa + (ny-hNa+j)*nx;\n      else\n        ind = i - hNa + (j-hNa)*nx;\n\n      for(l = 0; l < nz; l++)\n        Ac[i + j*Na + l*Na*Na] = full_auto_cor[ind + l*nx*ny]*ifactor;\n    }\n  }\n\n  // free memory\n  fftwf_free(fft);\n  free(full_auto_cor);\n}\n\n// Compute the pairwise cross-correlation matrix (Equation 43)\n// The input data is assumed to have a zero mean\nvoid compute_cross_cor(float *cross_cor, float **data, int N_data,\n                       int N, int nz)\n{\n  int i, j, l;\n  MatrixXf M(N_data*nz, N);\n\n  // put data in a matrix M\n  for(i = 0; i < N_data; i++)\n    for(j = 0; j < N; j++)\n      for(l = 0; l < nz; l++)\n        M(i + l*N_data,j) = data[i][j + l*N];\n\n  // compute the cross-correlation\n  MatrixXf tmp = M*(M.transpose())/N;\n\n  // put the cross-correlation in the ouput array\n  for(i = 0; i < N_data*nz; i++)\n    for(j = 0; j < N_data*nz; j++)\n      cross_cor[j + i*N_data*nz] = tmp(i,j);\n}\n\n// Compute the cross-correlation matrix (Equation 44)\n// The input data is assumed to have a zero mean\nvoid compute_cross_scale_cor(float *cross_scale_cor, float **data1,\n                             float **data2, int N_data1, int N_data2,\n                             int N, int nz)\n{\n  int i, j, l;\n  MatrixXf X(N_data1*nz, N);\n  MatrixXf Y(N_data2*nz, N);\n\n  // put data in a matrix X\n  for(i = 0; i < N_data1; i++)\n    for(j = 0; j < N; j++)\n      for(l = 0; l<nz; l++)\n        X(i + l*N_data1,j)= data1[i][j + l*N];\n\n  // put data in a matrix Y\n  for(i = 0; i < N_data2; i++)\n    for(j = 0; j < N; j++)\n      for(l = 0; l<nz; l++)\n        Y(i + l*N_data2,j) = data2[i][j + l*N];\n\n  MatrixXf tmp = X*(Y.transpose())/N;\n\n  // put the cross-correlation in the ouput array\n  for(i = 0; i < N_data1*nz; i++)\n    for(j = 0; j < N_data2*nz; j++)\n      cross_scale_cor[j + i*N_data2*nz] = tmp(i,j);\n}\n\n// Adjust the central part of the auto-correlation (Appendix A.2)\n// This corresponds to Algorithm 8\n// The input data is assumed to have a zero mean\nvoid adjust_auto_cor(float *data, const float *Ac, const float *var0,\n                  const float *vari, fftwf_complex *in_plan,\n                  fftwf_complex *out_plan, fftwf_plan plan, fftwf_plan iplan,\n                  int nx, int ny, int nz, int Na, int scale)\n{\n  int i, j, k, l, p;\n\n  // central location\n  int hNa = ((Na-1)/2);\n\n  // memory allocation\n  fftwf_complex *fft_data = (fftwf_complex *)\n    fftwf_malloc( nx*ny*nz * sizeof(fftwf_complex));\n  fftwf_complex *fft_tmp = (fftwf_complex *)\n    fftwf_malloc( nx*ny*nz * sizeof(fftwf_complex));\n  float *tmp = (float *) malloc(nx*ny*nz*sizeof(float));\n  int Na2 = 2*Na - 1;\n  float *Ac_in = (float *) malloc(Na2*Na2*nz*sizeof(float));\n\n  // compute the fft of the input (Line 1)\n  do_fft_plan_real(plan, out_plan, in_plan, fft_data, data, nx*ny, nz);\n\n  // computation of the auto-correlation image (Line 2)\n  // square the modulus of the DFT\n  for(i = 0; i<nx*ny*nz; i++) {\n    fft_tmp[i][0] = fft_data[i][0]*fft_data[i][0]\n      + fft_data[i][1]*fft_data[i][1];\n    fft_tmp[i][1] = 0.0;\n  }\n\n  // compute inverse fft\n  do_ifft_plan_real(iplan, out_plan, in_plan, tmp, fft_tmp, nx*ny, nz);\n\n  // keep the central part of size (2*Na-1)*(2*Na-1) and renormalize\n  int hNa2 = (Na2-1)/2;\n  float ifactor = 1.0/(nx*ny);\n  int ind;\n  for(i = 0; i < Na2 ; i++) {\n    for(j = 0; j < Na2; j++) {\n      if((i < hNa2) && (j < hNa2))\n        ind = nx - hNa2 + i + (ny-hNa2+j)*nx;\n      else if((i < hNa2) && (j > hNa2-1))\n        ind = nx - hNa2 + i + (j-hNa2)*nx;\n      else if((i > hNa2-1) && (j < hNa2))\n        ind = i - hNa2 + (ny-hNa2+j)*nx;\n      else\n        ind = i - hNa2 + (j-hNa2)*nx;\n\n      for(l = 0; l < nz; l++)\n        Ac_in[i + j*Na2 + l*Na2*Na2] = tmp[ind + l*nx*ny]*ifactor;\n    }\n  }\n\n  // declaration for the following computations\n  int t = ((Na*Na+1)/2);\n  MatrixXf A(t,t);\n  VectorXf B(t);\n  MatrixXf M(Na,Na);\n  MatrixXf rM(Na,Na);\n  MatrixXf auto_cor_in(Na2,Na2);\n  MatrixXf auto_cor_out(Na,Na);\n  int end_loop;\n  float factor;\n  float tol = (nz == 3) ? 1e-3 : 1e-4;\n\n  // loop over the channels\n  for(l = 0; l < nz; l++) {\n    if ( vari[l]/var0[l] > tol ) { // perform adjustment\n      // put auto-correlation arrays in matrices\n      for(i = 0; i < Na2; i++)\n        for(j = 0; j < Na2; j++)\n          auto_cor_in(j,i) = Ac_in[i + j*Na2 + l*Na2*Na2];\n      for(i = 0; i < Na; i++)\n        for(j = 0; j < Na; j++)\n          auto_cor_out(j,i) = Ac[i + j*Na + l*Na*Na];\n\n      // build the matrices involved in Equation 76\n      // A <--> R(v)\n      // B <--> R(u)\n      for(k = hNa; k < Na; k++) {\n        end_loop = (k < Na-1) ? hNa + Na : Na;\n        for(p = hNa; p<end_loop; p++) {\n          M = auto_cor_in.block(k - hNa, p - hNa, Na, Na);\n\n          for(i = 0; i < Na; i++)\n            for(j = 0; j < Na; j++)\n              rM(i,j) = M(i,j) + M(Na-1-i,Na-1-j);\n          rM(hNa, hNa) /= 2;\n          rM.resize(Na*Na,1);\n          for(i = 0; i < t; i++)\n            A((k - hNa)*Na + p - hNa,i)=rM(i,0);\n          rM.resize(Na,Na);\n          B((k - hNa)*Na + p - hNa) = auto_cor_out(k - hNa,p - hNa);\n        }\n      }\n\n      // Solve Equation 76 (Line 3)\n      // A * sol = B\n      VectorXf sol = A.colPivHouseholderQr().solve(B);\n\n      // Rearrange indices to build the center of R(h_lambda)\n      MatrixXf fullsol(2*t-1,1);\n      for(i = 0; i < t; i++) {\n        fullsol(i,0)=sol(i);\n        if(i<t-1)\n          fullsol(t + i,0) = sol(t - i -2);\n      }\n      fullsol.resize(Na,Na);\n\n      // Pad the center with zeros\n      MatrixXf hsquared0 = MatrixXf::Zero(ny,nx);\n      hsquared0.block(ny/2-hNa,nx/2-hNa, Na, Na) = fullsol;\n      MatrixXf shiftedhsquared0(ny,nx);\n      shiftedhsquared0 << hsquared0.block(ny/2,nx/2,ny/2,nx/2),\n        hsquared0.block(ny/2,0,ny/2,nx/2), hsquared0.block(0,nx/2,ny/2,nx/2),\n        hsquared0.block(0,0,ny/2,nx/2);\n\n      // store the matrix in an array before computing its DFT\n      for(j = 0; j < ny; j++)\n        for(i = 0; i < nx; i++)\n          tmp[i + j*nx + l*nx*ny] = shiftedhsquared0(j,i);\n\n      // compute the dft of the computed array (Line 4)\n      do_fft_plan_real(plan, out_plan, in_plan, fft_tmp + l*nx*ny,\n                       tmp + l*nx*ny, nx*ny, 1);\n\n      // compute the convolution in Fourier domain (Line 5 and Equation 75)\n      for(i = 0; i < nx*ny; i++) {\n        // compute the square root of the absolute value of the real part\n        factor = sqrt(fabs(fft_tmp[i + l*nx*ny][0]));\n\n        // multiplication in Fourier domain\n        fft_data[i + l*nx*ny][0] *= factor;\n        fft_data[i + l*nx*ny][1] *= factor;\n      }\n\n      // compute the inverse fft (Line 6)\n      do_ifft_plan_real(iplan, out_plan, in_plan, data + l*nx*ny,\n                        fft_data + l*nx*ny, nx*ny, 1);\n    }\n    else { // variance adjustment\n      adjust_mean_variance(data + l*nx*ny, 0.0, vari[l]/pow(16, scale), nx*ny);\n    }\n  }\n\n  // free memory\n  fftwf_free(fft_data);\n  fftwf_free(fft_tmp);\n  free(tmp);\n  free(Ac_in);\n}\n\n// Adjust the pairwise cross-correlation of a list of sub-bands (Appendix A.3)\n// This corresponds to Algorithm 9\n// Linearly adjust variables in data to have the pairwise cross-correlation cross_cor\n// The input data is assumed to have a zero mean\nvoid adjust_cross_cor(float **data, const float *cross_cor,\n                   int N_data, int N, int nz)\n{\n  int i, j, l;\n  MatrixXf V(N_data*nz, N);\n\n  // put data in a matrix V\n  for(i = 0; i < N_data; i++)\n    for(j = 0; j < N; j++)\n      for(l = 0; l < nz; l++)\n        V(i + l*N_data,j) = data[i][j + l*N];\n\n  // store the target cross-correlation in a matrix\n  MatrixXf tildeC(N_data*nz, N_data*nz);\n  for(i = 0; i < N_data*nz; i++)\n    for(j = 0; j < N_data*nz; j++)\n      tildeC(i,j) = cross_cor[j + i*N_data*nz];\n\n  // compute the input pairwise cross-correlation (Line 1)\n  MatrixXf C = V*(V.transpose())/N;\n\n  // eigen decomposition to compute the square root of matrices\n  SelfAdjointEigenSolver<MatrixXf> eigensolver_in(C);\n  SelfAdjointEigenSolver<MatrixXf> eigensolver_out(tildeC);\n  MatrixXf D_in = eigensolver_in.eigenvalues().asDiagonal();\n  MatrixXf P_in = eigensolver_in.eigenvectors();\n  MatrixXf D_out = eigensolver_out.eigenvalues().asDiagonal();\n  MatrixXf P_out = eigensolver_out.eigenvectors();\n\n  // square root and inverse square root\n  // isD_in = D_in^{-1/2}\n  // sD_out = D_out^{1/2}\n  MatrixXf isD_in = MatrixXf::Zero(N_data*nz,N_data*nz);\n  MatrixXf sD_out = MatrixXf::Zero(N_data*nz,N_data*nz);\n  int test1 = 0, test2 = 0; // to test if the matrices stay at 0 or not\n  for(i = 0; i < N_data*nz; i++) {\n    if( D_in(i,i) > 1e-12 ) {\n      isD_in(i,i) = 1.0/sqrt(D_in(i,i));\n      test1 = 1;\n    }\n    if( D_out(i,i) > 0) {\n      sD_out(i,i) = sqrt(D_out(i,i));\n      test2 = 1;\n    }\n  }\n\n  if (test1 && test2) { // if both matrices have non-zero values\n    MatrixXf Lambda = P_out*sD_out*(P_out.transpose())*P_in*isD_in*(P_in.transpose());\n\n    // update the matrix V (Line 3)\n    V = Lambda*V;\n\n    // update data\n    for(i = 0; i < N_data; i++) {\n      for(j = 0; j < N; j++)\n        for(l = 0; l < nz; l++)\n          data[i][j + l*N] = V(i + l*N_data,j);\n    }\n  }\n}\n\n// Adjust the color covariance matrix of PCA bands (Appendix A.3)\n// This corresponds to Algorithm 9\n// Linearly adjust variables in data to have the covariance matrix cov\n// The computations are similar as in adjust_cross_cor but the structure\n// of data is different\nvoid adjust_covariance_color(float *data, const float cov[3][3], int N)\n{\n  int i, j;\n  MatrixXf U(3, N);\n\n  // put data in a matrix U\n  for(i = 0; i < 3; i++)\n    for(j = 0; j < N; j++)\n      U(i,j) = data[j + i*N];\n\n  // store the target cross-correlation in a matrix\n  Matrix3f tildeC;\n  for(i = 0; i < 3; i++)\n    for(j = 0; j < 3; j++)\n      tildeC(i,j) = cov[i][j];\n\n  // compute the covariance matrix (Line 1)\n  Matrix3f C = U*(U.transpose())/N;\n\n  // eigen decomposition to compute the square root of matrices\n  SelfAdjointEigenSolver<Matrix3f> eigensolver_in(C);\n  SelfAdjointEigenSolver<Matrix3f> eigensolver_out(tildeC);\n  Matrix3f D_in = eigensolver_in.eigenvalues().asDiagonal();\n  Matrix3f P_in = eigensolver_in.eigenvectors();\n  Matrix3f D_out = eigensolver_out.eigenvalues().asDiagonal();\n  Matrix3f P_out = eigensolver_out.eigenvectors();\n\n  // square root and inverse square root\n  // isD_in = D_in^{-1/2}\n  // sD_out = D_out^{1/2}\n  Matrix3f isD_in = MatrixXf::Zero(3,3);\n  Matrix3f sD_out = MatrixXf::Zero(3,3);\n  int test1 = 0, test2 = 0; // to test if the matrices stay at 0 or not\n  for(i = 0; i < 3; i++) {\n    if( D_in(i,i) > 1e-12 ) {\n      isD_in(i,i) = 1.0/sqrt(D_in(i,i));\n      test1 = 1;\n    }\n    if( D_out(i,i) > 0 ) {\n      sD_out(i,i) = sqrt(D_out(i,i));\n      test2 = 1;\n    }\n  }\n\n  if (test1 && test2) { // if both matrices have non-zero values\n    // compute the solution matrix (Line 2)\n    MatrixXf Lambda = P_out*sD_out*(P_out.transpose())*P_in*isD_in*(P_in.transpose());\n\n    // update the matrix U (Line 3)\n    U = Lambda*U;\n\n    // update data\n    for(i = 0; i < 3; i++) {\n      for(j = 0; j < N; j++)\n        data[j + i*N] = U(i,j);\n    }\n  }\n}\n\n// Adjust the cross-correlations of a list of sub-bands given a list\n// of fixed sub-bands (Appendix A.3)\n// This corresponds to Algorithm 10\n// Linearly adjust variables in data1 to have the pairwise cross-correlation\n// cross_cor and the cross-correlation cross_scale_cor\n// The input data is assumed to have a zero mean\n// Note that data2 is not modified\nvoid adjust_cross_scale_cor(float **data1, float **data2, const float *cross_cor,\n                         const float *cross_scale_cor, int N_data1, int N_data2,\n                         int N, int nz)\n{\n  int i, j, l;\n  MatrixXf V(N_data1*nz, N);\n  MatrixXf W(N_data2*nz, N);\n\n  float tol = (nz == 3) ? 1e-3 : 1e-6;\n\n  // put data in a matrix V\n  for(i = 0; i < N_data1; i++)\n    for(j = 0; j < N; j++)\n      for(l = 0; l < nz; l++)\n        V(i + l*N_data1,j) = data1[i][j + l*N];\n\n  // put data in a matrix W\n  for(i = 0; i < N_data2; i++)\n    for(j = 0; j < N; j++)\n      for(l = 0; l < nz; l++)\n        W(i + l*N_data2,j) = data2[i][j + l*N];\n\n  // store the target pairwise cross-correlation in a matrix\n  MatrixXf tildeC(N_data1*nz, N_data1*nz);\n  for(i = 0; i < N_data1*nz; i++)\n    for(j = 0; j < N_data1*nz; j++)\n      tildeC(i,j) = cross_cor[j + i*N_data1*nz];\n\n  // store the target cross-correlation in a matrix\n  MatrixXf tildeD(N_data1*nz, N_data2*nz);\n  for(i = 0; i < N_data1*nz; i++)\n    for(j = 0; j < N_data2*nz; j++)\n      tildeD(i,j) = cross_scale_cor[j + i*N_data2*nz];\n\n  // compute the cross-correlations (Line 1)\n  MatrixXf C = V*(V.transpose())/N;\n  MatrixXf D = V*(W.transpose())/N;\n\n  // matrix computation (Line 2 and Line 3)\n  MatrixXf invE = (W*(W.transpose())/N).inverse();\n  MatrixXf F = C - D * invE *(D.transpose());\n  MatrixXf tildeF = tildeC - tildeD * invE * (tildeD.transpose());\n\n  // eigen decomposition to compute the square root of matrices\n  // F = P_in * D_in * P_in^T\n  // tildeF = P_out * D_out* P_out^T\n  // the following matrices are actually real-valued\n  SelfAdjointEigenSolver<MatrixXf> eigensolver_in(F);\n  SelfAdjointEigenSolver<MatrixXf> eigensolver_out(tildeF);\n  MatrixXcf D_in = eigensolver_in.eigenvalues().asDiagonal();\n  MatrixXcf P_in = eigensolver_in.eigenvectors();\n  MatrixXcf D_out = eigensolver_out.eigenvalues().asDiagonal();\n  MatrixXcf P_out = eigensolver_out.eigenvectors();\n\n  // square root and inverse square root\n  // isD_in = D_in^{-1/2}\n  // sD_out = D_out^{1/2}\n  MatrixXcf isD_in = MatrixXcf::Zero(N_data1*nz,N_data1*nz);\n  MatrixXcf sD_out = MatrixXcf::Zero(N_data1*nz,N_data1*nz);\n  int test = 0; // to test if the matrix stays at 0 or not\n  for(i = 0; i < N_data1*nz; i++) {\n    if( fabs(D_in.real()(i,i)) > 1e-12 ) {\n      isD_in(i,i) = ((complex<float>) 1)/sqrt((complex<float>) D_in(i,i));\n      test = 1;\n    }\n    sD_out(i,i) = sqrt((complex<float>) D_out(i,i));\n  }\n\n  if ( test ) { // if the matrix has non-zero values\n    // define new matrix Vnew = Lambda*V + Sigma*Y (Line 4 to Line 6)\n    MatrixXcf Lambda = P_out*sD_out*(P_out.transpose())*P_in*isD_in*(P_in.transpose());\n    MatrixXcf Sigma = (tildeD.cast<complex<float> >() - Lambda*D.cast<complex<float> >())\n                  * invE.cast<complex<float> >();\n    MatrixXcf Vnew = Lambda*V.cast<complex<float> >() + Sigma*W.cast<complex<float> >();\n\n    // compute variance of the real and imaginary part\n    // done outside compute_moment because of the data structure\n    for(l = 0; l < nz; l++) {\n      double mr = 0.0;\n      double mi = 0.0;\n      for(i = 0; i < N_data1; i++)\n        for(j = 0; j < N; j++) {\n          mr += Vnew.real()(i + l*N_data1,j);\n          mi += Vnew.imag()(i + l*N_data1,j);\n        }\n      mr /= (N_data1*N);\n      mi /= (N_data1*N);\n      double vr = 0.0;\n      double vi = 0.0;\n      for(i = 0; i < N_data1; i++)\n        for(j = 0; j < N; j++) {\n          vr += (Vnew.real()(i + l*N_data1,j) - mr)\n            * (Vnew.real()(i + l*N_data1,j) - mr);\n          vi += (Vnew.imag()(i + l*N_data1,j) - mi)\n            * (Vnew.imag()(i + l*N_data1,j) - mi);\n        }\n\n      // do not modify data1 if the variance of the imaginary part is too high\n      if(vi/vr < tol) {\n        for(i = 0; i < N_data1; i++)\n          for(j = 0; j < N; j++)\n            data1[i][j + l*N]= Vnew.real()(i + l*N_data1,j);\n      }\n    }\n  }\n}\n\n// Adjust the cross-correlations of an image given a list of\n// fixed sub-bands (Appendix A.3)\n// This corresponds to Algorithm 10\n// Linearly adjust variables in data1 to have the variance var\n// and the cross-correlation cross_scale_cor\n// The input data is assumed to have a zero mean\n// Note that data2 is not modified\n// The computations are similar to adjust_cross_scale_cor but the data\n// has a different structure\nvoid adjust_cross_scale_cor2(float *data1, float **data2,\n                          float var, const float *cross_scale_cor,\n                          int N_data, int N)\n{\n  int i, j, l;\n  MatrixXf V(1, N);\n  MatrixXf W(3*N_data, N);\n\n  // put data in a matrix X\n  for(j = 0; j < N; j++)\n    V(0,j) = data1[j];\n\n  // put data in a matrix Y\n  for(i = 0; i < N_data; i++)\n    for(j = 0; j < N; j++)\n      for(l = 0; l < 3; l++)\n        W(i + l*N_data,j) = data2[i][j + l*N];\n\n  // store the target pairwise cross-correlation in a matrix\n  MatrixXf tildeC(1, 1);\n  tildeC(0,0) = var;\n\n  // store the target cross-correlation in a matrix\n  MatrixXf tildeD(1, 3*N_data);\n  for(j = 0; j < 3*N_data; j++)\n    tildeD(0,j) = cross_scale_cor[j];\n\n  // compute the cross-correlations (Line 1)\n  MatrixXf C = V*(V.transpose())/N;\n  MatrixXf D = V*(W.transpose())/N;\n\n  // matrix computation (Line 2 and Line 3)\n  MatrixXf invE = (W*(W.transpose())/N).inverse();\n  MatrixXf F = C - D * invE * (D.transpose());\n  MatrixXf tildeF = tildeC - tildeD * invE * (tildeD.transpose());\n\n  // square root and inverse square root\n  // isD_in = F^{-1/2}\n  // sD_out = tildeF^{1/2}\n  MatrixXcf isD_in = MatrixXcf::Zero(1,1);\n  MatrixXcf sD_out = MatrixXcf::Zero(1,1);\n  if( fabs(F(0,0) > 1e-12) ) { // only modify if non-zero value\n    isD_in(0,0)=((complex<float>) 1)/sqrt((complex<float>) F(0,0));\n    sD_out(0,0)=sqrt((complex<float>) tildeF(0,0));\n\n    // define new matrix Vnew = Lambda*V + Sigma*Y (Line 4 to Line 6)\n    MatrixXcf Lambda = sD_out*isD_in;\n    MatrixXcf Sigma = (tildeD.cast<complex<float> >() - Lambda*D.cast<complex<float> >())\n                  * invE.cast<complex<float> >();\n    MatrixXcf Vnew = Lambda*V.cast<complex<float> >() + Sigma*W.cast<complex<float> >();\n\n    // compute variance of the real and imaginary part\n    // done outside a function because of the data structure\n    double mr = 0.0;\n    double mi = 0.0;\n    for(j=0; j<N; j++) {\n      mr += Vnew.real()(0,j);\n      mi += Vnew.imag()(0,j);\n    }\n    mr /= N;\n    mi /= N;\n    double vr = 0.0;\n    double vi = 0.0;\n    for(j=0; j<N; j++) {\n      vr += (Vnew.real()(0,j)-mr)*(Vnew.real()(0,j)-mr);\n      vi += (Vnew.imag()(0,j)-mi)*(Vnew.imag()(0,j)-mi);\n    }\n\n    // do not modify data1 if the variance of the imaginary part is too high\n    if(vi/vr < 1e-3) {\n      for(j=0; j<N; j++)\n        data1[j]= Vnew.real()(0,j);\n    }\n  }\n}\n", "meta": {"hexsha": "d3a59b589065f6b6db14bf719fc6ebb8023c541c", "size": 40091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/constraints.cpp", "max_stars_repo_name": "tbriand/portilla-simoncelli-ipol", "max_stars_repo_head_hexsha": "d867d9a22418dca23f0a2e55a6e0b49b8e33b703", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/constraints.cpp", "max_issues_repo_name": "tbriand/portilla-simoncelli-ipol", "max_issues_repo_head_hexsha": "d867d9a22418dca23f0a2e55a6e0b49b8e33b703", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/constraints.cpp", "max_forks_repo_name": "tbriand/portilla-simoncelli-ipol", "max_forks_repo_head_hexsha": "d867d9a22418dca23f0a2e55a6e0b49b8e33b703", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7210727969, "max_line_length": 89, "alphanum_fraction": 0.5719238732, "num_tokens": 13709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.044018649549418434, "lm_q1q2_score": 0.019441849251789455}}
{"text": "#include <float.h>\n#include <math.h>\n#include <sstream>\n#include <boost/any.hpp>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include \"misc/blas.h\"\n#include \"mspass/seismic/keywords.h\"\n#include \"mspass/seismic/CoreSeismogram.h\"\n#include \"mspass/utility/MsPASSError.h\"\n#include \"mspass/utility/SphericalCoordinate.h\"\n\n\nnamespace mspass::seismic\n{\nusing namespace std;\nusing namespace mspass::utility;\nnamespace py=pybind11;\n/*\n *  Start with all the constructors.\n *\n*/\n//\n// Default constructor for CoreSeismogram could be\n// done inline in seispp.h, but it is complication enough I put\n// it here\n//\nCoreSeismogram::CoreSeismogram() : BasicTimeSeries(),Metadata()\n{\n  /* mlive and tref are set in BasicTimeSeries so we don't use putters for\n  them here.   These three initialize Metadata properly for these attributes*/\n    this->set_dt(1.0);\n    this->set_t0(0.0);\n    this->set_npts(0);\n    components_are_orthogonal=true;\n    components_are_cardinal=true;\n    for(int i=0; i<3; ++i)\n        for(int j=0; j<3; ++j)\n            if(i==j)\n                tmatrix[i][i]=1.0;\n            else\n                tmatrix[i][j]=0.0;\n}\nCoreSeismogram::CoreSeismogram(const size_t nsamples)\n    : BasicTimeSeries(),Metadata()\n{\n  /* IMPORTANT:  this constructor assumes BasicTimeSeries initializes the\n  equivalent of:\n  set_dt(1.0)\n  set_t0(0.0)\n  set_tref(TimeReferenceType::Relative)\n  this->kill() - i.e. marked dead\n  */\n  this->set_npts(nsamples);  // Assume this is an allocator of the 3xnsamples matrix\n  components_are_orthogonal=true;\n  components_are_cardinal=true;\n  for(int i=0; i<3; ++i)\n    for(int j=0; j<3; ++j)\n      if(i==j)\n        tmatrix[i][i]=1.0;\n      else\n        tmatrix[i][j]=0.0;\n}\n\nCoreSeismogram::CoreSeismogram(const CoreSeismogram& t3c) :\n    BasicTimeSeries(dynamic_cast<const BasicTimeSeries&>(t3c)),\n    Metadata(dynamic_cast<const Metadata&>(t3c)),\n    u(t3c.u)\n{\n    int i,j;\n    components_are_orthogonal=t3c.components_are_orthogonal;\n    components_are_cardinal=t3c.components_are_cardinal;\n    for(i=0; i<3; ++i)\n        for(j=0; j<3; ++j) tmatrix[i][j]=t3c.tmatrix[i][j];\n}\nbool CoreSeismogram::tmatrix_is_cardinal()\n{\n    /* Test for 0 or 1 to 5 figures - safe but conservative for\n       float input although tmatrix is double */\n    double scale(10000.0);\n    int itest(10000);\n    int i,j;\n    for(i=0;i<3;++i)\n    {\n        for(j=0;j<3;++j)\n        {\n            int ival=static_cast<int>(tmatrix[i][j]*scale);\n            if(i==j)\n            {\n                if(ival!=itest) return false;\n            }\n            else\n            {\n                if(ival!=0) return false;\n            }\n        }\n    }\n    return true;\n}\nCoreSeismogram::CoreSeismogram(const Metadata& md,\n                const bool load_data) : Metadata(md)\n{\n    string dfile, dir;\n    long foff;\n    FILE *fp;\n    double *inbuffer;\n\n    components_are_orthogonal=true;\n    mlive=false;\n    try {\n        /* Names used are from mspass defintions as of Jan 2020.\n        We don't need to call the set methods for these attributes as they\n        would add the overhead of setting delta, startime, and npts to the\n        same value passed. */\n        this->mdt = this->get_double(SEISMICMD_dt);\n        this->mt0 = this->get_double(SEISMICMD_t0);\n        this->nsamp = this->get_long(SEISMICMD_npts);\n        /* Assume the data t0 is UTC. */\n        this->set_tref(TimeReferenceType::UTC);\n        /* This section is done specially to handle interaction with MongoDB.\n        We store tmatrix there as a python object so we use a get_any to fetch\n        it.   Oct 22, 2021 added a bug fix to handle tmatrix not defined.\n        We will take a null (undefined) tmatrix stored in the database to\n        imply the data are cardinal and orthogonal (i.e. stardard geographic\n        coordinates in e,n,z order.)*/\n        if(this->is_defined(\"tmatrix\"))\n        {\n          this->set_transformation_matrix\n                    (boost::any_cast<py::object>(this->get_any(\"tmatrix\")));\n          components_are_cardinal=this->tmatrix_is_cardinal();\n          if(components_are_cardinal)\n            components_are_orthogonal=true;\n          else\n            components_are_orthogonal=false;  //May be wrong but cost is tiny\n        }\n        else\n        {\n          /* this might not be needed but best be explicit*/\n          for(auto i=0;i<3;++i)\n            for(auto j=0;j<3;++j) this->tmatrix[i][j] = 0.0;\n          for(auto i=0;i<3;++i) this->tmatrix[i][i] = 1.0;\n          components_are_orthogonal = true;\n          components_are_cardinal = true;\n        }\n\n        u=dmatrix(3,nsamp);\n        if(load_data)\n        {\n            dir = this->get_string(SEISMICMD_dir);\n            dfile = this->get_string(SEISMICMD_dfile);\n            foff = this->get_long(SEISMICMD_foff);\n            string fname=dir+\"/\"+dfile;\n            if((fp=fopen(fname.c_str(),\"r\")) == NULL)\n                throw(MsPASSError(string(\"Open failure for file \")+fname,\n\t\t\t\t\t             ErrorSeverity::Invalid));\n            if (foff>0)fseek(fp,foff,SEEK_SET);\n            /* The older seispp code allowed byte swapping here.   For\n            efficiency we don't support that here and assume can do a\n            raw fread from the file and get valid data.  If support for\n            other types is needed this will need to be extended.  Here\n            we just point fread at the internal u array. */\n            inbuffer = this->u.get_address(0,0);\n            unsigned int nt=3*this->nsamp;\n            if(fread((void *)(inbuffer),sizeof(double),nt,fp)\n                    != nt )\n            {\n                throw(MsPASSError(string(\"CoreSeismogram constructor:  fread error on file \")+fname,\n                      ErrorSeverity::Invalid));\n            }\n            fclose(fp);\n\t          mlive=true;\n\t    }\n        else\n        {\n          /* Initialize the matrix in this case but leave the object marked\n          as dead */\n          this->u.zero();\n        }\n    } catch (MsPASSError& mpe) {\n        throw(mpe);\n    } catch (boost::bad_any_cast& be) {\n        throw(MsPASSError(string(\"CoreSeismogram constructor:  tmatrix type is not recognized\"),\n                ErrorSeverity::Invalid));\n    } catch (...) {\n      throw;\n    };\n}\n\nCoreSeismogram::CoreSeismogram(const vector<CoreTimeSeries>& ts,\n                       const unsigned int component_to_clone)\n    : BasicTimeSeries(dynamic_cast<const BasicTimeSeries&>(ts[component_to_clone])),\n     Metadata(dynamic_cast<const Metadata&>(ts[component_to_clone])),\n      u()\n{\n    const string base_error(\"CoreSeismogram constructor from 3 Time Series:  \");\n    int i,j;\n    /* This is needed in case nsamp does not match s.size(0) */\n    int nstest = ts[component_to_clone].s.size();\n    if(nsamp!=nstest) this->nsamp=nstest;\n    /* this method allocates u and sets the proper metadata for npts*/\n    this->CoreSeismogram::set_npts(this->nsamp);\n    /* beware irregular sample rates, but don' be too machevelian.\n           Abort only if the mismatch is large defined as accumulated time\n           over data range of this constructor is less than half a sample */\n    if( (ts[0].dt()!=ts[1].dt()) || (ts[1].dt()!=ts[2].dt()) )\n    {\n        double ddtmag1=fabs(ts[0].dt()-ts[1].dt());\n        double ddtmag2=fabs(ts[1].dt()-ts[2].dt());\n        double ddtmag;\n        if(ddtmag1>ddtmag1)\n            ddtmag=ddtmag1;\n        else\n            ddtmag=ddtmag2;\n        ddtmag1=fabs(ts[0].dt()-ts[2].dt());\n        if(ddtmag1>ddtmag)  ddtmag=ddtmag1;\n        double ddtcum=ddtmag*((double)ts[0].s.size());\n        if(ddtcum>(ts[0].dt())/2.0)\n        {\n            stringstream ss;\n            ss << base_error\n               << \"Sample intervals of components are not consistent\"<<endl;\n            for(int ie=0; ie<3; ++ie) ss << \"Component \"<<ie<<\" dt=\"<<ts[ie].dt()<<\" \";\n            ss<<endl;\n            throw MsPASSError(ss.str(),ErrorSeverity::Invalid);\n        }\n    }\n    // temporaries to hold component values\n    double t0_component[3];\n    double hang[3];\n    double vang[3];\n    // Load up these temporary arrays inside this try block and arrange to\n    // throw an exception if required metadata are missing\n    try {\n        /* WARNING hang and vang attributes in Metadata\n        are always assumed to have been read from a database where they\n        were stored in degrees.  We convert these to radians below to\n        compute the transformation matrix.\n\n        Feb 2021:  converted to use keywords.h definitions assuming these\n        came from the channel collection in MongoDB - Can be changed in\n        kewords.h for application outside mspass */\n        hang[0]=ts[0].get_double(SEISMICMD_hang);\n        hang[1]=ts[1].get_double(SEISMICMD_hang);\n        hang[2]=ts[2].get_double(SEISMICMD_hang);\n        vang[0]=ts[0].get_double(SEISMICMD_vang);\n        vang[1]=ts[1].get_double(SEISMICMD_vang);\n        vang[2]=ts[2].get_double(SEISMICMD_vang);\n    } catch (MetadataGetError& mde)\n    {\n        stringstream ss;\n        ss << base_error\n           << \"missing hang or vang variable in component TimeSeries objects received\"<<endl;\n        ss << \"Message posted by Metadata::get_double:  \"<<mde.what()<<endl;\n\tthrow MsPASSError(ss.str(),ErrorSeverity::Invalid);\n    }\n    /* We couldn't get here if hang and vang were not set on comp 0 so\n       we don't test for that condition.  We do need to clear hang and vang\n       from result here, however, as both attributes are meaningless\n       for a 3C seismogram */\n    this->erase(SEISMICMD_hang);\n    this->erase(SEISMICMD_vang);\n    // These are loaded just for convenience\n    t0_component[0]=ts[0].t0();\n    t0_component[1]=ts[1].t0();\n    t0_component[2]=ts[2].t0();\n\n    // Treat the normal case specially and avoid a bunch of work unless\n    // it is required\n    if( (ts[0].s.size()==ts[1].s.size()) && (ts[1].s.size()==ts[2].s.size())\n            && (fabs( (t0_component[0]-t0_component[1])/dt() )<1.0)\n            && (fabs( (t0_component[1]-t0_component[2])/dt() )<1.0))\n    {\n        /* Older code had this.   No longer needed with logic above that\n        calls set_npts.  that method creates and initialized the u dmatrix*/\n        //this->u=dmatrix(3,nsamp);\n        // Load data by a simple copy operation\n        /* This is a simple loop version\n        for(j=0;j<nsamp;++nsamp)\n        {\n        \tthis->u(0,j)=ts[0].s[j];\n        \tthis->u(1,j)=ts[1].s[j];\n        \tthis->u(2,j)=ts[2].s[j];\n        }\n        */\n        // This is a vector version that I'll use because it will\n        // be faster albeit infinitely more obscure and\n        // intrinsically more dangerous\n        dcopy(nsamp,&(ts[0].s[0]),1,u.get_address(0,0),3);\n        dcopy(nsamp,&(ts[1].s[0]),1,u.get_address(1,0),3);\n        dcopy(nsamp,&(ts[2].s[0]),1,u.get_address(2,0),3);\n    }\n    else\n    {\n        /*Land here if the start time or number of samples\n        is irregular.  We cut the output to latest start time to earliest end time*/\n        /* WARNING - debugging may be needed for this block. SEISPP versio of this\n        used gaps.  Here we cut the output to match an irregularities. */\n        double tsmax,temin;\n        tsmax=max(t0_component[0],t0_component[1]);\n        tsmax=max(tsmax,t0_component[2]);\n        temin=min(ts[0].endtime(),ts[1].endtime());\n        temin=min(temin,ts[2].endtime());\n        nstest=(int)round((temin-tsmax)/mdt);\n        if(nstest<=0)\n          throw MsPASSError(base_error\n                +\"Irregular time windows of components have no overlap\",\n                        ErrorSeverity::Invalid);\n        else\n          this->CoreSeismogram::set_npts(nstest);\n        // Now load the data.  Use the time and sample number methods\n        // to simplify process\n        double t;\n        t=tsmax;\n        this->set_t0(t);\n        double delta=this->dt();\n        for(int ic=0; ic<3; ++ic)\n        {\n            t=this->t0();\n            for(j=0; j<ts[ic].s.size(); ++j)\n            {\n                i=ts[ic].sample_number(t);\n                // silently do nothing if outside bounds.  This\n                // perhaps should be an error as it shouldn't really\n                // happen with the above algorithm, but safety is good\n                if( (i>=0) && (i<nsamp) ) this->u(ic,j)=ts[ic].s[i];\n                t += delta;\n            }\n        }\n    }\n    /* Finally we need to set the transformation matrix.\n     This is a direct application of conversion of routines\n    in spherical coordinate procedures.  They are procedural\n    routines, not objects so the code is procedural.\n    */\n    SphericalCoordinate scor;\n    double *nu;\n    // convert all the hang values to spherical coordinate phi\n    // (angle from postive east) from input assumed in degrees\n    // azimuth from north.  At the same time convert vang to radians.\n    for(i=0; i<3; ++i)\n    {\n        hang[i]=mspass::utility::rad(90.0-hang[i]);\n        vang[i]=mspass::utility::rad(vang[i]);\n    }\n    for(i=0; i<3; ++i)\n    {\n        scor.phi=hang[i];\n        scor.theta=vang[i];\n        nu=SphericalToUnitVector(scor);\n        for(j=0; j<3; ++j)tmatrix[i][j]=nu[j];\n        delete [] nu;\n    }\n    components_are_cardinal = this->tmatrix_is_cardinal();\n    if(components_are_cardinal)\n        components_are_orthogonal=true;\n    else\n        components_are_orthogonal=false;\n}\n// Note on usage in this group of functions.  The rotation algorithms used here\n// all key on the BLAS for speed.  That is, a transformation matrix could be done\n// by using the * operator between matrix objects.\n\nvoid CoreSeismogram::rotate_to_standard()\n{\n    if( (u.size()[1]<=0) || this->dead()) return; // do nothing in these situations\n    double *work[3];\n    int i,j;\n    if(components_are_cardinal) return;\n    /* We assume nsamp is the number of samples = number of columns in u - we don't\n    check here for efficiency */\n    for(j=0; j<3; ++j) work[j]=new double[nsamp];\n    if(components_are_orthogonal)\n    {\n        //\n        //Use a daxpy algorithm.  tmatrix stores the\n        //forward transformation used to get current\n        //Use the transpose to get back\n        //\n        for(i=0; i<3; ++i)\n        {\n            // x has a stride of 3 because we store in fortran order in x\n            dcopy(nsamp,u.get_address(0,0),3,work[i],1);\n            dscal(nsamp,tmatrix[0][i],work[i],1);\n            daxpy(nsamp,tmatrix[1][i],u.get_address(1,0),3,work[i],1);\n            daxpy(nsamp,tmatrix[2][i],u.get_address(2,0),3,work[i],1);\n        }\n        for(i=0; i<3; ++i) dcopy(nsamp,work[i],1,u.get_address(i,0),3);\n    }\n    else\n    {\n        //\n        //Enter here only when the transformation matrix is\n        //not orthogonal.  We have to construct a fortran\n        //order matrix a to use LINPACK routine in sunperf/perf\n        //This could be done with the matrix template library\n        //but the overhead ain't worth it\n        //\n        double a[9];\n        int ipivot[3];\n        int info;\n        a[0] = tmatrix[0][0];\n        a[1] = tmatrix[1][0];\n        a[2] = tmatrix[2][0];\n        a[3] = tmatrix[0][1];\n        a[4] = tmatrix[1][1];\n        a[5] = tmatrix[2][1];\n        a[6] = tmatrix[0][2];\n        a[7] = tmatrix[1][2];\n        a[8] = tmatrix[2][2];\n        //LAPACK routine with FORTRAN interface using pass by reference and pointers\n        int three(3);\n        dgetrf(three,three,a,three,ipivot,info);\n        if(info!=0)\n        {\n            for(i=0; i<3; ++i) delete [] work[i];\n            throw(MsPASSError(\n                      string(\"rotate_to_standard:  LU factorization of transformation matrix failed\")),\n                  ErrorSeverity::Invalid);\n        }\n        // inversion routine after factorization from lapack FORT$RAN interface\n        double awork[10];  //Larger than required but safety value small cost\n        int ldwork(10);\n        dgetri(three,a,three,ipivot,awork,ldwork,info);\n        // This is the openblas version\n        //info=LAPACKE_dgetri(LAPACK_COL_MAJOR,3,a,3,ipivot);\n        if(info!=0)\n        {\n            for(i=0; i<3; ++i) delete [] work[i];\n            throw(MsPASSError(\n                      string(\"rotate_to_standard:  LU factorization inversion of transformation matrix failed\")),\n                  ErrorSeverity::Invalid);\n        }\n\n        tmatrix[0][0] = a[0];\n        tmatrix[1][0] = a[1];\n        tmatrix[2][0] = a[2];\n        tmatrix[0][1] = a[3];\n        tmatrix[1][1] = a[4];\n        tmatrix[2][1] = a[5];\n        tmatrix[0][2] = a[6];\n        tmatrix[1][2] = a[7];\n        tmatrix[2][2] = a[8];\n        /* The inverse is now in tmatrix so we reverse the\n           rows and columms from above loop */\n\n        for(i=0; i<3; ++i)\n        {\n            dcopy(nsamp,u.get_address(0,0),3,work[i],1);\n            dscal(nsamp,tmatrix[i][0],work[i],1);\n            daxpy(nsamp,tmatrix[i][1],u.get_address(1,0),3,work[i],1);\n            daxpy(nsamp,tmatrix[i][2],u.get_address(2,0),3,work[i],1);\n        }\n        for(i=0; i<3; ++i) dcopy(nsamp,work[i],1,u.get_address(i,0),3);\n        components_are_orthogonal = true;\n    }\n    //\n    //Have to set the transformation matrix to an identity now\n    //\n    for(i=0; i<3; ++i)\n        for(j=0; j<3; ++j)\n            if(i==j)\n                tmatrix[i][i]=1.0;\n            else\n                tmatrix[i][j]=0.0;\n\n    components_are_cardinal=true;\n    for(i=0; i<3; ++i) delete [] work[i];\n}\n\n\n/* This routine takes a spherical coordinate vector that defines\na given direction in space and returns a transformation matrix that\nshould be viewed as a transformation to ray coordinates under an\nassumption that this vector points in the direction of P wave\nparticle motion.  If the theta angle is greater than PI/2 it\nswitches the azimuth by 180 degrees so that the direction of the\ntransformed x1 axis will be pointing upward in space.  This removes\nambiguities in the transformation that make it easier to sort out\nhandedness of the transformation.\n\nThe transformation produced for a P wave will be true ray coordinates\nwith X1 = transverse, X2 = radial, and X3 = longitudinal.\nThe best way to understand the transformation is as a pair of\nrotations:  (1) rotate North to radial about z, (2) rotate z to\ntransverse around X1 (transverse).  Note this leaves X1 (transverse)\nalways as a purely horizontal direction.  It should also work for a\nprincipal component direction determined for an S phase, but the\nappropriate the only component that will make any sense after the\ntransformation, in that case, is the X3 direction = direction of\ninferred peak particle motion.\n\nOne special case has to be dealt with.  If the direction passed into\nthe program is purely vertical (up or down), the function can only\nreturn an identity matrix because there is no way to determine a\nhorizontal rotation direction.\n\nArguments:\n\txsc - spherical coordinate structure defining unit vector used\n\t\tto define the transform (radius is ignored).  Angles\n\t\tare assumed in radians.\n\nAuthor:  Gary L. Pavlis\nWritten:  Sept. 1999\nModified:  Feb 2003\nOriginal was plain C.  Adapted to C++ for seismic processing\n*/\nvoid CoreSeismogram::rotate(SphericalCoordinate& xsc)\n{\n    if( (u.size()[1]<=0) || dead()) return; // do nothing in these situations\n\n    //Earlier version had a reset of the nsamp variable here - we need to trust\n    //that is correct here for efficiency.  We the new API it would be hard\n    //to have that happen. without a serious blunder\n    int i;\n    double theta, phi;  /* corrected angles after dealing with signs */\n    double a,b,c,d;\n\n    //\n    //Undo any previous transformations\n    //\n    this->rotate_to_standard();\n    if(xsc.theta == M_PI)\n    {\n        //This will be left handed\n        tmatrix[2][2] = -1.0;\n        dscal(nsamp,-1.0,u.get_address(2,0),3);\n        return;\n    }\n\n    if(xsc.theta < 0.0)\n    {\n        theta = -(xsc.theta);\n        phi = xsc.phi + M_PI;\n        if(phi > M_PI) phi -= (2.0*M_PI);\n    }\n    else if(xsc.theta > M_PI)\n    {\n        theta = xsc.theta - M_PI;\n        phi = xsc.phi + M_PI;\n        if(phi > M_PI) phi -= (2.0*M_PI);\n    }\n    else\n    {\n        theta = xsc.theta;\n        phi = xsc.phi;\n    }\n    /* Am using a formula here for azimuth with is pi/2 - phi*/\n    double azimuth=M_PI_2-phi;\n    a = cos(azimuth);\n    b = sin(azimuth);\n    c = cos(theta);\n    d = sin(theta);\n\n    tmatrix[0][0] = a;\n    tmatrix[1][0] = b*c;\n    tmatrix[2][0] = b*d;\n    tmatrix[0][1] = -b;\n    tmatrix[1][1] = a*c;\n    tmatrix[2][1] = a*d;\n    tmatrix[0][2] = 0.0;\n    tmatrix[1][2] = -d;\n    tmatrix[2][2] = c;\n\n    /* Now multiply the data by this transformation matrix.  */\n    double *work[3];\n    for(i=0; i<3; ++i)work[i] = new double[nsamp];\n    for(i=0; i<3; ++i)\n    {\n        dcopy(nsamp,u.get_address(0,0),3,work[i],1);\n        dscal(nsamp,tmatrix[i][0],work[i],1);\n        daxpy(nsamp,tmatrix[i][1],u.get_address(1,0),3,work[i],1);\n        daxpy(nsamp,tmatrix[i][2],u.get_address(2,0),3,work[i],1);\n    }\n    for(i=0; i<3; ++i) dcopy(nsamp,work[i],1,u.get_address(i,0),3);\n    components_are_cardinal=false;\n    for(i=0; i<3; ++i) delete [] work[i];\n}\nvoid CoreSeismogram::rotate(const double nu[3])\n{\n    if( (u.size()[1]<=0) || this->dead()) return; // do nothing in these situations\n    SphericalCoordinate xsc=UnitVectorToSpherical(nu);\n    this->rotate(xsc);\n}\n/* simplified procedure to rotate only zonal angle by phi radians.\n Similar to above but using only azimuth angle AND doing a simple\n rotation in the horizontal plane.  Efficient algorithm only\n alters 0 and 1 components. */\nvoid CoreSeismogram::rotate(double phi)\n{\n    if( (u.size()[1]<=0) || dead()) return; // do nothing in these situations\n    int i,j,k;\n    double a,b;\n    a=cos(phi);\n    b=sin(phi);\n    double tmnew[3][3];\n    tmnew[0][0] = a;\n    tmnew[1][0] = b;\n    tmnew[2][0] = 0.0;\n    tmnew[0][1] = -b;\n    tmnew[1][1] = a;\n    tmnew[2][1] = 0.0;\n    tmnew[0][2] = 0.0;\n    tmnew[1][2] = 0.0;\n    tmnew[2][2] = 1.0;\n\n    /* Now multiply the data by this transformation matrix.\n     Not trick in this i only goes to 2 because 3 component\n     is an identity.*/\n    double *work[2];\n    for(i=0; i<2; ++i)work[i] = new double[nsamp];\n    for(i=0; i<2; ++i)\n    {\n        dcopy(nsamp,u.get_address(0,0),3,work[i],1);\n        dscal(nsamp,tmnew[i][0],work[i],1);\n        daxpy(nsamp,tmnew[i][1],u.get_address(1,0),3,work[i],1);\n    }\n    for(i=0; i<2; ++i) dcopy(nsamp,work[i],1,u.get_address(i,0),3);\n    double tm_tmp[3][3];\n    double prod;\n    for(i=0; i<3; ++i)\n        for(j=0; j<3; ++j)\n        {\n            for(prod=0.0,k=0; k<3; ++k)\n                prod+=tmnew[i][k]*tmatrix[k][j];\n            tm_tmp[i][j]=prod;\n        }\n    for(i=0; i<3; ++i)\n        for(j=0; j<3; ++j)tmatrix[i][j]=tm_tmp[i][j];\n    components_are_cardinal=false;\n    for(i=0; i<2; ++i) delete [] work[i];\n}\nvoid CoreSeismogram::transform(const double a[3][3])\n{\n    if( (u.size()[1]<=0) || dead()) return; // do nothing in these situations\n    /* Older version had this - we need to trust ns is already u.columns().  */\n    //size_t ns = u.size()[1];\n    size_t i,j,k;\n    double *work[3];\n    for(i=0; i<3; ++i) work[i] = new double[nsamp];\n    for(i=0; i<3; ++i)\n    {\n        dcopy(nsamp,u.get_address(0,0),3,work[i],1);\n        dscal(nsamp,a[i][0],work[i],1);\n        daxpy(nsamp,a[i][1],u.get_address(1,0),3,work[i],1);\n        daxpy(nsamp,a[i][2],u.get_address(2,0),3,work[i],1);\n    }\n    for(i=0; i<3; ++i) dcopy(nsamp,work[i],1,u.get_address(i,0),3);\n    for(i=0; i<3; ++i) delete [] work[i];\n    /* Hand code this rather than use dmatrix or other library.\n       Probably dumb, but this is just a 3x3 system.  This\n       is simply a multiply of a*tmatrix with result replacing\n       the internal tmatrix */\n    double tmnew[3][3];\n    double prod;\n    for(i=0; i<3; ++i)\n        for(j=0; j<3; ++j)\n        {\n            for(prod=0.0,k=0; k<3; ++k)\n                prod+=a[i][k]*tmatrix[k][j];\n            tmnew[i][j]=prod;\n        }\n    for(i=0; i<3; ++i)\n        for(j=0; j<3; ++j)tmatrix[i][j]=tmnew[i][j];\n    components_are_cardinal = this->tmatrix_is_cardinal();\n    /* Assume this method does not yield cartesian coordinate directions.*/\n    if(!components_are_cardinal) components_are_orthogonal=false;\n}\n/* This function computes and applies the free surface tranformaton\nmatrix described by Kennett 1991.  The result is a ray coordinate\ntransformation with x1=transverse, x2=radial, and x3=longitudinal.\nNote this transformation is into a nonorthogonal system.\n\nAlgorithm first applies a rotation of horizontal coordinates to\nhorizonal radial and transverse, then applies free surface\ntransformation to the radial-vertical plane.\n\nThe free surface transformation code segment is a direct\ntranslation of m file from Michael Bostock.\n\nAuthor:  Gary Pavlis\n*/\nvoid CoreSeismogram::free_surface_transformation(SlownessVector uvec,\n        double a0, double b0)\n{\n    if( (u.size()[1]<=0) || dead()) return; // do nothing in these situations\n    double a02,b02,pslow,p2;\n    double qa,qb,vpz,vpr,vsr,vsz;\n    pslow=uvec.mag();\n    // silently do nothing if magnitude of the slowness vector is 0\n    // (vertical incidence)\n    if(pslow<DBL_EPSILON) return;\n    // Can't handle evanescent waves with this operator\n    double vapparent=1.0/pslow;\n    if(vapparent<a0 || vapparent<b0)\n    {\n        stringstream ss;\n        ss<<\"CoreSeismogram::free_surface_transformation method:  illegal input\"<<endl\n          << \"Apparent velocity defined by input slowness vector=\"<<vapparent<<endl\n          << \"Smaller than specified surface P velocity=\"<<a0<<\" or S velocity=\"<<b0<<endl\n          << \"That implies evanescent waves that violate the assumption of this operator\"<<endl;\n        throw MsPASSError(ss.str(),ErrorSeverity::Invalid);\n    }\n\n    // First the horizonal rotation\n    SphericalCoordinate scor;\n    //rotation angle is - azimuth to put x2 (north in standard coord)\n    //in radial direction\n    scor.phi=atan2(uvec.uy,uvec.ux);\n    scor.theta=0.0;\n    scor.radius=1.0;\n    // after this transformation x1=transverse horizontal\n    // x2=radial horizonal, and x3 is still vertical\n    this->rotate(scor);\n\n    a02=a0*a0;\n    b02=b0*b0;\n    p2=pslow*pslow;\n    qa=sqrt((1.0/a02)-p2);\n    qb=sqrt((1.0/b02)-p2);\n    vpz=-(1.0-2.0*b02*p2)/(2.0*a0*qa);\n    vpr=pslow*b02/a0;\n    vsr=(1.0-2.0*b02*p2)/(2.0*b0*qb);\n    vsz=pslow*b0;\n    /* Now construct the transformation matrix\n     This is different from Bostock's original code\n     in sign and order.  Also note this transformation\n         is not scaled to have a unit matrix norm so amplitudes\n         after the transformation are distorted.  rotate_to_standard,\n         however, should still restore original data within roundoff\n         error if called on the result. */\n    double fstran[3][3];\n    fstran[0][0]=0.5;\n    fstran[0][1]=0.0;\n    fstran[0][2]=0.0;\n    fstran[1][0]=0.0;\n    fstran[1][1]=vsr;\n    fstran[1][2]=vpr;\n    fstran[2][0]=0.0;\n    fstran[2][1]=-vsz;\n    fstran[2][2]=-vpz;\n    this->transform(fstran);\n\n    components_are_cardinal=false;\n    components_are_orthogonal=false;\n}\nbool CoreSeismogram::set_transformation_matrix(const dmatrix& A)\n{\n    for(int i=0;i<3;++i)\n        for(int j=0;j<3;++j) tmatrix[i][j]=A(i,j);\n    py::list tmatrix_l;\n    for(int i=0;i<3;++i)\n        for(int j=0;j<3;++j) tmatrix_l.append(A(i, j));\n    this->put_object(SEISMICMD_tmatrix, tmatrix_l);\n    bool cardinal;\n    cardinal=this->tmatrix_is_cardinal();\n    if(cardinal)\n    {\n        components_are_cardinal=true;\n        components_are_orthogonal=true;\n    }\n    else\n    {\n        components_are_cardinal=false;\n        /* Not necessarily true, but small overhead cost*/\n        components_are_orthogonal=false;\n    }\n    return components_are_cardinal;\n}\nbool CoreSeismogram::set_transformation_matrix(const double a[3][3])\n{\n    for(int i=0;i<3;++i)\n        for(int j=0;j<3;++j) tmatrix[i][j]=a[i][j];\n    py::list tmatrix_l;\n    for(int i=0;i<3;++i)\n        for(int j=0;j<3;++j) tmatrix_l.append(a[i][j]);\n    this->put_object(SEISMICMD_tmatrix, tmatrix_l);\n    bool cardinal;\n    cardinal=this->tmatrix_is_cardinal();\n    if(cardinal)\n    {\n        components_are_cardinal=true;\n        components_are_orthogonal=true;\n    }\n    else\n    {\n        components_are_cardinal=false;\n        /* Not necessarily true, but small overhead cost*/\n        components_are_orthogonal=false;\n    }\n    return components_are_cardinal;\n}\nbool CoreSeismogram::set_transformation_matrix(py::object tmatrix_py)\n{\n    if(py::isinstance<py::array>(tmatrix_py)) {\n        auto tmatrix_ary = tmatrix_py.cast<py::array_t<double, py::array::c_style | py::array::forcecast>>();\n        py::buffer_info info = tmatrix_ary.request();\n        if ((info.ndim == 2 && info.shape[0]*info.shape[1] == 9) ||\n            (info.ndim == 1 && info.shape[0] == 9)\n           )\n            return this->set_transformation_matrix(static_cast<double(*)[3]>(info.ptr));\n        else\n            throw(MsPASSError(string(\"set_transformation_matrix: tmatrix should be a 3x3 matrix\"),\n                    ErrorSeverity::Invalid));\n    } else if (py::isinstance<dmatrix>(tmatrix_py)) {\n        auto tmatrix_ary = tmatrix_py.cast<dmatrix>();\n        if (tmatrix_ary.rows() != 3 || tmatrix_ary.columns() != 3)\n            throw(MsPASSError(string(\"set_transformation_matrix: tmatrix should be a 3x3 matrix\"),\n                    ErrorSeverity::Invalid));\n        return this->set_transformation_matrix(tmatrix_ary);\n    } else if (py::isinstance<py::list>(tmatrix_py)) {\n        dmatrix tmatrix_ary(3,3);\n        double* ptr = tmatrix_ary.get_address(0,0);\n        if(py::len(tmatrix_py) == 9) {\n            int i = 0;\n            for (auto item : tmatrix_py) {\n                try{\n                    *(ptr+i) = item.cast<double>();\n                    i++;\n                } catch (...) {\n                    throw(MsPASSError(string(\"set_transformation_matrix: the elements of tmatrix should be float\"),\n                            ErrorSeverity::Invalid));\n                }\n            }\n        } else if(py::len(tmatrix_py) == 3) {\n            int i = 0;\n            for (auto items : tmatrix_py) {\n                if(!py::isinstance<py::list>(items))\n                    throw(MsPASSError(string(\"set_transformation_matrix: tmatrix should be a 3x3 list of list\"),\n                            ErrorSeverity::Invalid));\n                else if (py::len(items) != 3)\n                    throw(MsPASSError(string(\"set_transformation_matrix: tmatrix should be a 3x3 list of list\"),\n                            ErrorSeverity::Invalid));\n                else {\n                    for (auto item : items) {\n                        try{\n                            *(ptr+i) = item.cast<double>();\n                            i++;\n                        } catch (...) {\n                            throw(MsPASSError(string(\"set_transformation_matrix: the elements of tmatrix should be float\"),\n                                ErrorSeverity::Invalid));\n                        }\n                    }\n                }\n            }\n        } else {\n            throw(MsPASSError(string(\"set_transformation_matrix: tmatrix should be a list of 9 floats or a 3x3 list of list\"),\n                ErrorSeverity::Invalid));\n        }\n        return this->set_transformation_matrix(tr(tmatrix_ary));\n    } else {\n        throw(MsPASSError(string(\"set_transformation_matrix: tmatrix's type is not recognized\"),\n                ErrorSeverity::Invalid));\n    }\n}\nCoreSeismogram& CoreSeismogram::operator=(const CoreSeismogram& seisin)\n{\n    if(this!=&seisin)\n    {\n        this->BasicTimeSeries::operator=(seisin);\n        this->Metadata::operator=(seisin);\n        components_are_orthogonal=seisin.components_are_orthogonal;\n        components_are_cardinal=seisin.components_are_cardinal;\n        for(int i=0; i<3; ++i)\n        {\n            for(int j=0; j<3; ++j)\n            {\n                tmatrix[i][j]=seisin.tmatrix[i][j];\n            }\n        }\n        u=seisin.u;\n    }\n    return(*this);\n}\nCoreSeismogram& CoreSeismogram::operator*=(const double scale)\n{\n  /* do nothing to empty data or data marked dead*/\n  if((this->npts()==0) || (this->dead())) return(*this);\n  /* We can use this dscal blas function because dmatrix puts all the data\n  in a continguous block. Beware if there is am implementation change for\n  the matrix data*/\n  double *ptr=this->u.get_address(0,0);\n  dscal(3*this->npts(),scale,ptr,1);\n  return(*this);\n}\nCoreSeismogram& CoreSeismogram::operator+=(const CoreSeismogram& data)\n{\n    int i,iend,jend;\n    size_t j,i0,j0;\n    // Sun's compiler complains about const objects without this.\n    CoreSeismogram& d=const_cast<CoreSeismogram&>(data);\n    // Silently do nothing if d is marked dead\n    if(!d.mlive) return(*this);\n    // Silently do nothing if d does not overlap with data to contain sum\n    if( (d.endtime()<mt0)\n            || (d.mt0>(this->endtime())) ) return(*this);\n    if(d.tref!=(this->tref))\n        throw MsPASSError(\"CoreSeismogram += operator cannot handle data with inconsistent time base\\n\",\n                          ErrorSeverity::Invalid);\n    /* this defines the range of left and right hand sides to be summed */\n    i=d.sample_number(this->mt0);\n    if(i<0)\n    {\n      j0=this->sample_number(d.t0());\n      i0=0;\n    }\n    else\n    {\n      j0=0;\n      i0=i;\n    }\n    iend=d.sample_number(this->endtime());\n    jend=this->sample_number(d.endtime());\n    if(iend>=(d.npts()))\n    {\n        iend=d.npts()-1;\n    }\n    if(jend>=this->npts())\n    {\n      jend=this->npts()-1;\n    }\n    for(i=i0,j=j0; i<=iend && j<=jend; ++i,++j)\n    {\n        this->u(0,j)+=d.u(0,i);\n        this->u(1,j)+=d.u(1,i);\n        this->u(2,j)+=d.u(2,i);\n    }\n    return(*this);\n}\n/* IMPORTANT:  this code is absolutely identical to that for operator+=\nexcept the += in the last loop becomes -=.  Any changes in operator+=\nmust have exactly the same change here (other than a message with a\ntag to the function)*/\nCoreSeismogram& CoreSeismogram::operator-=(const CoreSeismogram& data)\n{\n    int i,iend,jend;\n    size_t j,i0,j0;\n    // Sun's compiler complains about const objects without this.\n    CoreSeismogram& d=const_cast<CoreSeismogram&>(data);\n    // Silently do nothing if d is marked dead\n    if(!d.mlive) return(*this);\n    // Silently do nothing if d does not overlap with data to contain sum\n    if( (d.endtime()<mt0)\n            || (d.mt0>(this->endtime())) ) return(*this);\n    if(d.tref!=(this->tref))\n        throw MsPASSError(\"CoreSeismogram += operator cannot handle data with inconsistent time base\\n\",\n                          ErrorSeverity::Invalid);\n    /* this defines the range of left and right hand sides to be summed */\n    i=d.sample_number(this->mt0);\n    if(i<0)\n    {\n      j0=this->sample_number(d.t0());\n      i0=0;\n    }\n    else\n    {\n      j0=0;\n      i0=i;\n    }\n    iend=d.sample_number(this->endtime());\n    jend=this->sample_number(d.endtime());\n    if(iend>=(d.npts()))\n    {\n        iend=d.npts()-1;\n    }\n    if(jend>=this->npts())\n    {\n      jend=this->npts()-1;\n    }\n    for(i=i0,j=j0; i<=iend && j<=jend; ++i,++j)\n    {\n        this->u(0,j)-=d.u(0,i);\n        this->u(1,j)-=d.u(1,i);\n        this->u(2,j)-=d.u(2,i);\n    }\n    return(*this);\n}\nconst CoreSeismogram CoreSeismogram::operator+(const CoreSeismogram& other) const\n{\n  CoreSeismogram result(*this);\n  result += other;\n  return result;\n}\nconst CoreSeismogram CoreSeismogram::operator-(const CoreSeismogram& other) const\n{\n  CoreSeismogram result(*this);\n  result -= other;\n  return result;\n}\nvoid CoreSeismogram::set_dt(const double sample_interval)\n{\n  this->BasicTimeSeries::set_dt(sample_interval);\n  /* This is the unique name defined in the mspass schema - we always set it. */\n  this->put(SEISMICMD_dt,sample_interval);\n  /* these are hard coded aliases for sample_interval */\n  std::set<string> aliases;\n  std::set<string>::iterator aptr;\n  /* Note these aren't set in keywords - aliases are flexible and this\n  can allow another way to make these attribute names more flexible. */\n  aliases.insert(\"dt\");\n  for(aptr=aliases.begin();aptr!=aliases.end();++aptr)\n  {\n    if(this->is_defined(*aptr))\n    {\n      this->put(*aptr,sample_interval);\n    }\n  }\n}\nvoid CoreSeismogram::set_t0(const double t0in)\n{\n  this->BasicTimeSeries::set_t0(t0in);\n  /* This is the unique name - we always set it.  Pulled from keywords.h\n  which should match the schema.  aliases are hard coded not defined as\n  keywords */\n  this->put(SEISMICMD_t0,t0in);\n  /* these are hard coded aliases for sample_interval */\n  std::set<string> aliases;\n  std::set<string>::iterator aptr;\n  aliases.insert(\"t0\");\n  aliases.insert(\"time\");\n  for(aptr=aliases.begin();aptr!=aliases.end();++aptr)\n  {\n    if(this->is_defined(*aptr))\n    {\n      this->put(*aptr,t0in);\n    }\n  }\n}\nvoid CoreSeismogram::set_npts(const size_t npts)\n{\n  this->BasicTimeSeries::set_npts(npts);\n  /* This is the unique name - we always set it.  The weird\n  cast is necessary to avoid type mismatch with unsigned.\n  We use the name defined in keywords.h which we can always assume\n  matches the schema for the unique name*/\n  this->put(SEISMICMD_npts,(long int)npts);\n  /* these are hard coded aliases for sample_interval */\n  std::set<string> aliases;\n  std::set<string>::iterator aptr;\n  aliases.insert(\"nsamp\");\n  aliases.insert(\"wfdisc.nsamp\");\n  for(aptr=aliases.begin();aptr!=aliases.end();++aptr)\n  {\n    if(this->is_defined(*aptr))\n    {\n      this->put(*aptr,(long int)npts);\n    }\n  }\n  /* this method has the further complication that npts sets the size of the\n  data matrix.   Here we resize the matrix and initialize it to 0s.*/\n  this->u=dmatrix(3,npts);\n  this->u.zero();\n}\nvoid CoreSeismogram::sync_npts()\n{\n  if(nsamp != this->u.columns()) {\n    this->BasicTimeSeries::set_npts(this->u.columns());\n    /* This is the unique name - we always set it.  The weird\n    cast is necessary to avoid type mismatch with unsigned.\n    As above converted to keywords.h const string to make\n    this easier to maintain*/\n    this->put(SEISMICMD_npts,(long int)nsamp);\n    /* these are hard coded aliases for sample_interval */\n    std::set<string> aliases;\n    std::set<string>::iterator aptr;\n    aliases.insert(\"nsamp\");\n    aliases.insert(\"wfdisc.nsamp\");\n    for(aptr=aliases.begin();aptr!=aliases.end();++aptr)\n    {\n        if(this->is_defined(*aptr))\n        {\n          this->put(*aptr,(long int)nsamp);\n        }\n    }\n  }\n}\n\nvector<double> CoreSeismogram::operator[] (const int i)const\n{\n    try {\n        vector<double> result;\n        result.reserve(3);\n        for(int k=0;k<3;++k)\n          result.push_back(this->u(k,i));\n        return result;\n    }catch(...){throw;};\n}\nvector<double> CoreSeismogram::operator[] (const double t) const\n{\n    try {\n        vector<double> result;\n        int i=this->sample_number(t);\n        /* could test for a negative i and i too large but we assume\n        the dmatrix container will throw an exception if it resolves that way*/\n        for(int k=0;k<3;++k)\n          result.push_back(this->u(k,i));\n        return result;\n    }catch(...){throw;};\n}\n} // end namespace SEISPP\n", "meta": {"hexsha": "01b693fb702a52a81147fb6e9570771abc16e33e", "size": 39153, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cxx/src/lib/seismic/CoreSeismogram.cc", "max_stars_repo_name": "mspass-team/mspass", "max_stars_repo_head_hexsha": "3fe0c52bbd6aa0c99a0f748e9711684c35d26025", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-06-30T20:30:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T17:25:25.000Z", "max_issues_repo_path": "cxx/src/lib/seismic/CoreSeismogram.cc", "max_issues_repo_name": "mspass-team/mspass", "max_issues_repo_head_hexsha": "3fe0c52bbd6aa0c99a0f748e9711684c35d26025", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2021-07-01T04:31:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:10.000Z", "max_forks_repo_path": "cxx/src/lib/seismic/CoreSeismogram.cc", "max_forks_repo_name": "mspass-team/mspass", "max_forks_repo_head_hexsha": "3fe0c52bbd6aa0c99a0f748e9711684c35d26025", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-03T18:40:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T05:59:50.000Z", "avg_line_length": 35.5936363636, "max_line_length": 126, "alphanum_fraction": 0.6017929661, "num_tokens": 11060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.041462277004998487, "lm_q1q2_score": 0.01943712681852414}}
{"text": "// Copyright 2018 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/// \\copyright Copyright 2018 the Autoware Foundation\n/// \\file\n/// \\brief Header for hungarian algorithm for optimal linear assignment\n#ifndef HUNGARIAN_ASSIGNER__HUNGARIAN_ASSIGNER_HPP_\n#define HUNGARIAN_ASSIGNER__HUNGARIAN_ASSIGNER_HPP_\n\n\n/// \\brief Ensure Eigen does not allocate memory dynamically\n#define EIGEN_NO_MALLOC\n/// \\brief Prevent Eigen from yelling at you for larged fix-sized matrices\n#define EIGEN_STACK_ALLOCATION_LIMIT 0\n\n#include <Eigen/Core>\n#include <hungarian_assigner/visibility_control.hpp>\n#include <utility>\n#include <limits>\n#include <array>\n#include \"common/types.hpp\"\n\nusing autoware::common::types::bool8_t;\nusing autoware::common::types::float32_t;\n\nnamespace autoware\n{\nnamespace fusion\n{\n/// \\brief this namespace is for all functions, structs, classes and constants in the\n///        hungarian_assigner package\nnamespace hungarian_assigner\n{\n\n/// \\brief indexing matches what matrices use\nusing index_t = Eigen::Index;\n\n/// \\brief implementation of the hungarian/kuhn-munkres/jacobi algorithm for\n/// minimum weight assignment problem in O(N^3 ) time\n/// \\tparam Capacity maximum number of things that can be matched, sets matrix size\ntemplate<uint16_t Capacity>\nclass HUNGARIAN_ASSIGNER_PUBLIC hungarian_assigner_c\n{\n  static_assert(Capacity > 0, \"Capacity must be positive\");\n  /// \\brief markers for each matrix slot, not strongly typed so it can decay to numeric type\n  enum mark_e : int8_t\n  {\n    NO_LINK = 0,   ///< no cost has been assigned, so assignment is assumed to be impossible\n    UNMARKED = 1,  ///< this location is just a normal weight\n    ZERO = 2,      ///< zero, but unmarked\n    PRIMED = 3,    ///< primed zero\n    STARRED = 4    ///< starred zero, corresponds to an assignment\n  };\n\n  /// \\brief this definition is for internal book-keeping\n  using index2_t = std::pair<index_t, index_t>;\n\n  /// \\brief This exception is for a bad edge case when the assigner tries to add a new zero\n  ///        but the only uncovered entries in the matrix are not valid links/weights\n  class HUNGARIAN_ASSIGNER_LOCAL no_uncovered_values_c : public std::runtime_error\n  {\npublic:\n    no_uncovered_values_c();\n  };  // class no_uncovered_values_c\n\npublic:\n  /// \\brief This index denotes a worker for which no job assignment was possible\n  static constexpr index_t UNASSIGNED = std::numeric_limits<index_t>::max();\n\n  /// \\brief constructor\n  hungarian_assigner_c();\n\n  /// \\brief constructor, equivalent of construct(); set_size(num_rows, num_cols)\n  /// \\param[in] num_rows number of rows/jobs\n  /// \\param[in] num_cols number of columns/workers\n  hungarian_assigner_c(const index_t num_rows, const index_t num_cols);\n\n  /// \\brief set the size of the matrix. Must be less than capacity. This should be done before\n  ///        set_weight() calls\n  /// \\param[in] num_rows number of rows/jobs\n  /// \\param[in] num_cols number of columns/workers\n  /// \\throw std::length_error if num_rows or num_cols is bigger than capacity\n  /// \\throw std::domain_error if matrix shape is skinny\n  void set_size(const index_t num_rows, const index_t num_cols);\n\n  /// \\brief set weight, update book-keeping for min in row\n  ///        This function is meant to be called asynchronously over jdx, so\n  ///        a thread should have fixed ownership over a given idx. Note that\n  ///        you can call this function again for a same index pair, but you\n  ///        will break assumptions if you set it to a higher weight.\n  /// \\param[in] weight the weight for assignment of job idx to worker jdx\n  /// \\param[in] idx the index of the job\n  /// \\param[in] jdx the index of the worker\n  /// \\throw std::out_of_range if idx or jdx are outside of range specified by set_size()\n  void set_weight(const float32_t weight, const index_t idx, const index_t jdx);\n\n  /// \\brief reset book-keeping and weight matrix, must be called after\n  ///        assign(), and before set_weight()\n  void reset();\n\n  /// \\brief reset and set_size, equivalent to reset(); set_size(num_rows, num_cols);\n  /// \\param[in] num_rows number of rows/jobs\n  /// \\param[in] num_cols number of columns/workers\n  void reset(const index_t num_rows, const index_t num_cols);\n\n  /// \\brief compute minimum cost assignment\n  /// \\return whether or not it was successful. If assignment was unsuccessful (for example, the\n  ///         case when a row has no valid assignments), then get_assignment() may return\n  ///         UNASSIGNED\n  /// \\throw std::exception if some unspecified error happens internally, should never happen\n  bool8_t assign();\n\n  // every row/job is guaranteed to have a worker\n  /// \\brief dictate what the assignment for a given row/task is, should be called after assign().\n  ///        If assign() returned true, then every job/row is guaranteed to have a worker/column.\n  ///        If assign() returned false, then a row may not have a worker/column\n  /// \\param[in] idx the index for the task, starting at 0\n  /// \\return the index for the assigned job, starting at 0\n  ///         UNASSIGNED if assign() returned false and the idx job has no possible assignments\n  /// \\throw std::range_error if idx is out of bounds\n  index_t get_assignment(const index_t idx) const;\n\n  // get unassigned workers/columns. User should know how many unassigned there will be apriori\n  /// \\brief says what jobs have been unassigned\n  /// \\param[in] idx the i'th unassigned job, starts from 0 to num_jobs - num_workers\n  /// \\return the index of the i'th unassigned job\n  /// \\throw std::range_error if idx is out of bounds (i.e. there are no unassigned rows)\n  index_t get_unassigned(const index_t idx) const;\n\nprivate:\n  /// \\brief do steps 1-3, return true if perfect assignment found\n  HUNGARIAN_ASSIGNER_LOCAL bool8_t reduce_rows_and_init_zeros_and_check_result();\n\n  /// \\brief do step 5 and 3, return true if perfect assignment found\n  HUNGARIAN_ASSIGNER_LOCAL bool8_t increment_starred_zeroes_and_check_result(index2_t loc);\n\n  /// \\brief step 4 and 6: find an uncovered zero, add it if necessary, throws exception if it can't\n  HUNGARIAN_ASSIGNER_LOCAL index2_t prime_uncovered_zero();\n\n  /// \\brief step 6: reduce matrix by smallest uncovered value, return false if no uncovered value\n  HUNGARIAN_ASSIGNER_LOCAL bool8_t add_new_zero(index2_t & loc);\n\n  /// \\brief check if assignment is complete\n  HUNGARIAN_ASSIGNER_LOCAL bool8_t are_all_columns_covered() const;\n\n  /// \\brief find a zero that is uncovered by rows or columns\n  HUNGARIAN_ASSIGNER_LOCAL bool8_t find_uncovered_zero(index2_t & loc) const;\n\n  /// \\brief find minimal value that is not covered, false if none found\n  HUNGARIAN_ASSIGNER_LOCAL bool8_t find_minimum_uncovered_value(\n    index2_t & loc,\n    float32_t & min_val) const;\n\n  /// \\brief update internal bookkeeping for which rows and columns are uncovered\n  HUNGARIAN_ASSIGNER_LOCAL void update_uncovered_rows_and_cols();\n\n  Eigen::Matrix<float32_t, Capacity, Capacity> m_weight_matrix;\n  Eigen::Matrix<int8_t, Capacity, Capacity> m_mark_matrix;\n  Eigen::Matrix<index_t, Capacity, 1> m_row_min_idx;\n  index_t m_num_rows;\n  index_t m_num_cols;\n  Eigen::Matrix<float32_t, Capacity, 1> m_row_min_weights;\n  Eigen::Matrix<index_t, Capacity, 1> m_assignments;\n  Eigen::Matrix<bool8_t, Capacity, 1> m_is_col_covered;\n  Eigen::Matrix<bool8_t, Capacity, 1> m_is_row_covered;\n  index_t m_num_uncovered_rows;\n  index_t m_num_uncovered_cols;\n  Eigen::Matrix<index_t, Capacity, 1> m_uncovered_rows;\n  Eigen::Matrix<index_t, Capacity, 1> m_uncovered_cols;\n  Eigen::Matrix<index2_t, 2 * Capacity, 1> m_augment_path;\n  Eigen::Matrix<index2_t, Capacity, 1> m_primed_zero_locs;\n  index_t m_num_primed_zeros;\n};  // class hungarian_assigner_c\n\n}  // namespace hungarian_assigner\n}  // namespace fusion\n}  // namespace autoware\n#endif  // HUNGARIAN_ASSIGNER__HUNGARIAN_ASSIGNER_HPP_\n", "meta": {"hexsha": "fec7d9e81b350ba7b66e72723ab78c47b9cd3879", "size": 8455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fusion/hungarian_assigner/include/hungarian_assigner/hungarian_assigner.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/fusion/hungarian_assigner/include/hungarian_assigner/hungarian_assigner.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/fusion/hungarian_assigner/include/hungarian_assigner/hungarian_assigner.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": 44.0364583333, "max_line_length": 100, "alphanum_fraction": 0.7412182141, "num_tokens": 2150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.04208772521219691, "lm_q1q2_score": 0.019403148149252425}}
{"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 bdd.hpp\n *\n * @brief BDD package\n *\n * @author Mathias Soeken\n * @since  2.3\n */\n#ifndef BDD_HPP\n#define BDD_HPP\n\n#include <classical/dd/dd_manager.hpp>\n#include <classical/dd/bdd_fwd.hpp>\n\n#include <boost/call_traits.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <cassert>\n#include <iostream>\n#include <map>\n#include <memory>\n\nnamespace cirkit\n{\n\nclass bdd_manager;\n\nstruct bdd\n{\n  using const_param_ref = boost::call_traits < bdd >::const_reference;\n\n  bdd() : manager( nullptr ), index( 0u ) {}\n  bdd( bdd_manager* manager, unsigned index )\n    : manager( manager ),\n      index( index ) {}\n  bdd( const bdd& other ) : manager( other.manager ), index( other.index ) {}\n\n  bdd& operator=( const bdd& other );\n\n  unsigned var() const;\n  bdd high() const;\n  bdd low() const;\n\n  inline bool is_bot() const { return index == 0u; }\n  inline bool is_top() const { return index == 1u; }\n\n  bdd operator&&( const bdd& other ) const;\n  bdd operator||( const bdd& other ) const;\n  bdd operator^( const bdd& other ) const;\n  bdd operator!() const;\n  bdd cof0( unsigned v ) const;\n  bdd cof1( unsigned v ) const;\n  bdd exists( const bdd& other ) const;\n  bdd constrain( const bdd& other ) const;\n  bdd restrict( const bdd& other ) const;\n  bdd round_down( unsigned level ) const;\n  bdd round_up( unsigned level ) const;\n  bdd round( unsigned level ) const;\n\n  bool equals( const bdd& other ) const;\n\n  bdd_manager* manager;\n  unsigned     index;\n};\n\nstd::ostream& operator<< ( std::ostream& stream, bdd::const_param_ref bdd );\n\nclass bdd_manager : public dd_manager\n{\npublic:\n  bdd_manager( unsigned nvars, unsigned log_max_objs, bool verbose = false );\n  ~bdd_manager();\n\n  bdd_manager ( const bdd_manager& other ) = delete;\n  bdd_manager& operator= ( const bdd_manager& other ) = delete;\n\n  inline bdd bdd_bot()                { return bdd( this, 0u );     }\n  inline bdd bdd_top()                { return bdd( this, 1u );     }\n  inline bdd bdd_var( unsigned i )    { assert( i < nvars ); return bdd( this, i + 2u ); }\n  inline bdd operator[]( unsigned i ) { assert( i < nvars ); return bdd( this, i + 2u ); }\n\n  unsigned bdd_and( unsigned f, unsigned g );\n  unsigned bdd_or( unsigned f, unsigned g );\n  unsigned bdd_xor( unsigned f, unsigned g );\n  unsigned bdd_not( unsigned f );\n  unsigned bdd_cof0( unsigned f, unsigned v );\n  unsigned bdd_cof1( unsigned f, unsigned v );\n  unsigned bdd_exists( unsigned f, unsigned g );\n  unsigned bdd_constrain( unsigned f, unsigned g );\n  unsigned bdd_restrict( unsigned f, unsigned g );\n  unsigned bdd_round_down( unsigned f, unsigned level );\n  unsigned bdd_round_up( unsigned f, unsigned level );\n  unsigned bdd_round( unsigned f, unsigned level );\n\n  unsigned unique_create( unsigned var, unsigned high, unsigned low );\n\n  static bdd_manager_ptr create( unsigned nvars, unsigned log_max_objs, bool verbose = false );\n\nprivate:\n  unsigned bdd_round_to( unsigned f, unsigned level, unsigned cop, unsigned to );\n  unsigned bdd_round_to( unsigned f, unsigned level, unsigned cop, unsigned to, const std::map<unsigned, boost::multiprecision::uint256_t>& count_map );\n\npublic:\n  friend std::ostream& operator<<( std::ostream& os, const bdd_manager& mgr );\n};\n\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": "3b8b24e1314397d7cae7bf6fcecc01929f30f1e0", "size": 4561, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/classical/dd/bdd.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": "src/classical/dd/bdd.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": "src/classical/dd/bdd.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": 32.1197183099, "max_line_length": 152, "alphanum_fraction": 0.7029160272, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.053403324903538434, "lm_q1q2_score": 0.01938376241234331}}
{"text": "/*\n  Author(s):      Robert I A Patterson\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2009 Robert I A Patterson.\n\n  File purpose:\n    Implementation of transition regime coagulation kernel\n\tfor hybrid particle-number/particle model\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n#include \"swp_hybrid_transcoag.h\"\n\n#include \"swp_params.h\"\n#include \"swp_cell.h\"\n#include \"swp_mechanism.h\"\n#include \"swp_PAH_primary.h\"\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nusing namespace Sweep::Processes;\n\n\n// Default constructor.\nSweep::Processes::HybridTransitionCoagulation::HybridTransitionCoagulation(const Sweep::Mechanism &mech)\n: Coagulation(mech), m_efm(mech.GetEnhancementFM())\n{\n    m_name = \"HybridTransitionRegimeCoagulation\";\n}\n\nSweep::Processes::HybridTransitionCoagulation* const Sweep::Processes::HybridTransitionCoagulation::Clone() const\n{\n\treturn new HybridTransitionCoagulation(*this);\n}\n\n// Stream-reading constructor.\nSweep::Processes::HybridTransitionCoagulation::HybridTransitionCoagulation(std::istream &in, const Sweep::Mechanism &mech)\n: Coagulation(mech), m_efm(mech.GetEnhancementFM())\n{\n    m_name = \"HybridTransitionRegimeCoagulation\";\n    Deserialize(in, mech);\n}\n\n// TOTAL RATE CALCULATION.\n\n// Returns the rate of the process for the given system.\ndouble Sweep::Processes::HybridTransitionCoagulation::Rate(double t, const Cell &sys,\n                                                          const Geometry::LocalGeometry1d &local_geom) const\n{\n    // Get the number of particles in the system.\n    unsigned int n = sys.ParticleCount() + sys.Particles().GetTotalParticleNumber();\n\n    // Check that there are at least 2 particles before calculating rate.\n    if (n > 1) {\n        // Get system properties required to calculate coagulation rate.\n        double T = sys.GasPhase().Temperature();\n        double P = sys.GasPhase().Pressure();\n\n        // Get the particle-number contributions\n        fvector props(6, 0);\n        props[0] = sys.Particles().GetTotalDiameter();\n        props[1] = sys.Particles().GetTotalDiameter2();\n        props[2] = sys.Particles().GetTotalDiameter_1();\n        props[3] = sys.Particles().GetTotalDiameter_2();\n        props[4] = sys.Particles().GetTotalMass_1_2();\n        props[5] = sys.Particles().GetTotalDiameter2_mass_1_2();\n\t\n        // Calculate the rate.\n        double rate = Rate(sys.Particles().GetSums(), (double)n, sqrt(T),\n                    T/sys.GasPhase().Viscosity(), MeanFreePathAir(T,P),\n                    sys.SampleVolume(), props);\n\n        props.clear();\n        fvector().swap(props);\n\n        return rate;\n    } else {\n        return 0.0;\n    }\n}\n\n// More efficient rate routine for coagulation only.\n// All parameters required to calculate rate passed\n// as arguments.\ndouble Sweep::Processes::HybridTransitionCoagulation::Rate(const Ensemble::particle_cache_type &data, double n, double sqrtT,\n                       double T_mu, double MFP, double vol, fvector & props) const\n{\n    // Some prerequisites.\n    double n_1 = n - 1.0;\n    double a = CSF * T_mu * A();\n    double b = a * MFP * 1.257 * A();\n    double c = CFMMAJ * m_efm * CFM * sqrtT * A();\n\n    // Summed particle properties required for coagulation rate.\n    double d       = data.Property(Sweep::iDcol);\n    double d2      = data.Property(Sweep::iD2);\n    double d_1     = data.Property(Sweep::iD_1);\n    double d_2     = data.Property(Sweep::iD_2);\n    double m_1_2   = data.Property(Sweep::iM_1_2);\n    double d2m_1_2 = data.Property(Sweep::iD2_M_1_2);\n\n    // Add particle-number contributions\n    d += props[0];\n    d2 += props[1];\n    d_1 += props[2];\n    d_2 += props[3];\n    m_1_2 += props[4];\n    d2m_1_2 += props[5];\n\n    // Get individual terms.\n    double terms[TYPE_COUNT];\n    // Slip-flow.\n    terms[0] = n * n_1 * a / vol;\n    terms[1] = ((d * d_1) - n) * a / vol;\n    terms[2] = d_1 * n_1 * b / vol;\n    terms[3] = ((d * d_2) - d_1) * b / vol;\n    // Free-molecular.\n    terms[4] = n_1 * d2m_1_2  * c / vol;\n    terms[5] = (m_1_2 * d2 - d2m_1_2) * c / vol;\n\n    // Sum up total coagulation rates for different regimes.\n    double sf = terms[0] + terms[1] + terms[2] + terms[3];\n    double fm = terms[4] + terms[5];\n\n    if ((sf>0.0) || (fm>0.0)) {\n        // There is some coagulation.\n        if (sf > fm) {\n            // Use free-mol majorant.\n            return fm;\n        } else {\n            // Use slip-flow majorant.\n            return sf;\n        }\n    }\n    return 0.0;\n}\n\n\n// RATE TERM CALCULATION.\n\n// Returns the number of rate terms for this process.\nunsigned int Sweep::Processes::HybridTransitionCoagulation::TermCount(void) const { return TYPE_COUNT; }\n\n/**\n * Calculate the terms in the sum of the majorant kernel over all particle\n * pairs, placing each term in successive positions of the sequence\n * beginning at iterm and return the sum of the terms added to that\n * vector.\n *\n * @param[in]     t          Time for which rates are requested\n * @param[in]     sys        Details of the particle population and environment\n * @param[in]     local_geom Details of spatial position and boundaries\n * @param[in,out] iterm      Pointer to start of sequence to hold the rate terms, returned as one past the end.\n *\n * @return      Sum of all rate terms for this process\n */\ndouble Sweep::Processes::HybridTransitionCoagulation::RateTerms(double t, const Cell &sys,\n                            const Geometry::LocalGeometry1d &local_geom,\n                            fvector::iterator &iterm) const\n{\n    // Get the number of particles in the system.\n    unsigned int n = sys.ParticleCount() + sys.Particles().GetTotalParticleNumber();\n\n    // Check that there are at least 2 particles before calculating rate.\n    if (n > 1) {\n        // Get system properties required to calculate coagulation rate.\n        double T = sys.GasPhase().Temperature();\n        double P = sys.GasPhase().Pressure();\n\n        // Add contributions from particle-number list\n        fvector props(6, 0);\n        props[0] = sys.Particles().GetTotalDiameter();\n        props[1] = sys.Particles().GetTotalDiameter2();\n        props[2] = sys.Particles().GetTotalDiameter_1();\n        props[3] = sys.Particles().GetTotalDiameter_2();\n        props[4] = sys.Particles().GetTotalMass_1_2();\n        props[5] = sys.Particles().GetTotalDiameter2_mass_1_2();\n\t\t\n        // Calculate the rate terms.\n        double rate = RateTerms(sys.Particles().GetSums(), (double)n, sqrt(T), T/sys.GasPhase().Viscosity(),\n                         MeanFreePathAir(T,P), sys.SampleVolume(), iterm, props);\n        props.clear();\n        fvector().swap(props);\n        return rate;\n    } else {\n        // No coagulation as there are too few particles.\n        for(unsigned int i=0; i<TYPE_COUNT; i++) *(iterm++) = 0.0;\n        return 0.0;\n    }\n}\n\n// More efficient rate routine for coagulation only.\n// All parameters required to calculate rate terms\n// passed as arguments.\ndouble Sweep::Processes::HybridTransitionCoagulation::RateTerms(const Ensemble::particle_cache_type &data, double n, double sqrtT,\n                            double T_mu, double MFP, double vol,\n                            fvector::iterator &iterm, fvector & props) const\n{\n    // Some prerequisites.\n    double n_1 = n - 1.0;\n    double a   = CSF * T_mu * A();\n    double b   = a * MFP * 1.257 * 2.0;\n    double c   = CFMMAJ * m_efm * CFM * sqrtT * A();\n\n    // Summed particle properties required for coagulation rate.\n    double d       = data.Property(Sweep::iDcol);\n    double d2      = data.Property(Sweep::iD2);\n    double d_1     = data.Property(Sweep::iD_1);\n    double d_2     = data.Property(Sweep::iD_2);\n    double m_1_2   = data.Property(Sweep::iM_1_2);\n    double d2m_1_2 = data.Property(Sweep::iD2_M_1_2);\n\n    // Add particle-number contributions\n    d       += props[0];\n    d2      += props[1];\n    d_1     += props[2];\n    d_2     += props[3];\n    m_1_2   += props[4];\n    d2m_1_2 += props[5];\n\n    fvector::iterator isf = iterm;\n    fvector::iterator ifm = iterm+4;\n\n    // Slip-flow.\n    *(iterm)   = n * n_1 * a / vol;\n    *(++iterm) = ((d * d_1) - n) * a / vol;\n    *(++iterm) = d_1 * n_1 * b / vol;\n    *(++iterm) = ((d * d_2) - d_1) * b / vol;\n    // Free-molecular.\n    *(++iterm) = n_1 * d2m_1_2  * c / vol;\n    *(++iterm) = (m_1_2 * d2 - d2m_1_2) * c / vol;\n\n    // Return iterator to next term after the coagulation terms.\n    ++iterm;\n\n    // Sum up total coagulation rates for different regimes.\n    double sf = *(isf) + *(isf+1) + *(isf+2) + *(isf+3);\n    double fm = *(ifm) + *(ifm+1);\n\n    if ((sf>0.0) || (fm>0.0)) {\n        // There is some coagulation.\n        if (sf > fm) {\n            // Use free-mol majorant.\n            *(isf) = 0.0;\n            *(isf+1) = 0.0;\n            *(isf+2) = 0.0;\n            *(isf+3) = 0.0;\n            return fm;\n        } else {\n            // Use slip-flow majorant.\n            *(ifm) = 0.0;\n            *(ifm+1) = 0.0;\n            return sf;\n        }\n    } else {\n        // Something went wrong with the rate calculation.\n        *(isf)   = 0.0;\n        *(isf+1) = 0.0;\n        *(isf+2) = 0.0;\n        *(isf+3) = 0.0;\n        *(ifm)   = 0.0;\n        *(ifm+1) = 0.0;\n        return 0.0;\n    }\n}\n\n\n// PERFORMING THE PROCESS.\n\n/*!\n * \n *\n * \\param[in]       t           Time\n * \\param[in,out]   sys         System to update\n * \\param[in]       local_geom  Details of local phsyical layout\n * \\param[in]       iterm       Process term responsible for this event\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      0 on success, otherwise negative.\n */\nint HybridTransitionCoagulation::Perform(double t, Sweep::Cell &sys, \n                                   const Geometry::LocalGeometry1d& local_geom,\n                                   unsigned int iterm,\n                                   Sweep::rng_type &rng) const\n{\n\tPartPtrVector dummy;\n\n    int ip1=-1, ip2=-1;\n    MajorantType maj;\n    TermType term = (TermType)iterm;\n\n    // Store number of particles in each particle model\n    double n_incep = sys.Particles().GetTotalParticleNumber();\n    double n_other = sys.ParticleCount();\n    double n_total = n_incep + n_other;\n    unsigned int index1 = 0, index2 = 0, n_index1 = 0; \n\n    // Hybrid particle model flags\n    bool hybrid_flag = m_mech->IsHybrid() && n_incep > 0.0; // Check if particle-number list is relevant\n    bool ip1_flag = false;      // Flag particle 1 as a particle-number particle\n    bool ip2_flag = false;      // Flag particle 2 as a particle-number particle\n    bool coag_in_place = false; // Flag for coagulation in particle-number list\n\n    // Choose and get first particle.\n    Particle *sp1 = NULL;\n    Particle *sp2 = NULL;\n\n    // Hybrid model: if < 2 SPs but incepting class >= 2, we can still act\n    if (n_total < 2)\n        return 1;\n    else\n    {\n        // Select properties by which to choose particles. \n        // Note we need to choose 2 particles.  There are six possible \n        // rate terms to choose from; 4 slip-flow and 2 free molecular.\n        boost::uniform_01<rng_type&, double> unifDistrib(rng);\n\t\n        // Get property sums for number list\t\n        double dc_incep = sys.Particles().GetTotalDiameter();\n        double dc2_incep = sys.Particles().GetTotalDiameter2();\n        double dc_1_incep = sys.Particles().GetTotalDiameter_1();\n        double dc_2_incep = sys.Particles().GetTotalDiameter_2();\n        double m_1_2_incep = sys.Particles().GetTotalMass_1_2();\n        double dc2_m_1_2_incep = sys.Particles().GetTotalDiameter2_mass_1_2();\n\n        // Get property sums for ensemble\n        double dc_other = sys.Particles().GetSum(iDcol);\n        double dc2_other = sys.Particles().GetSum(iD2);\n        double dc_1_other = sys.Particles().GetSum(iD_1);\n        double dc_2_other = sys.Particles().GetSum(iD_2);\n        double m_1_2_other = sys.Particles().GetSum(iM_1_2);\n        double dc2_m_1_2_other = sys.Particles().GetSum(iD2_M_1_2);\n\n        // Select the first particle and note the majorant type\n        double alpha1 = 0.0, alpha2 = 0.0;\n        switch (term) {\n            case SlipFlow1:\n                alpha1 = unifDistrib() * n_total;\n                if (alpha1 <= n_incep)\n                {\n                    index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1, iUniform, rng);\n                    ip1 = -2;\n                } else {\n                    ip1 = sys.Particles().Select_usingGivenRand(iUniform, alpha1 - n_incep, rng);\n                }\n                maj = SlipFlow;\n                break;\n            case SlipFlow2:\n                alpha1 = unifDistrib() * (dc_incep + dc_other);\n                if (alpha1 <= dc_incep)\n                {\n                    index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1, iDcol, rng);\n                    ip1 = -2;\n                } else {\n                    ip1 = sys.Particles().Select_usingGivenRand(iDcol, alpha1 - dc_incep, rng);\n                }\n                maj = SlipFlow;\n                break;\n            case SlipFlow3:\n                alpha1 = unifDistrib() * n_total;\n                if (alpha1 <= n_incep)\n                {\n                    index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1, iUniform, rng);\n                    ip1 = -2;\n                } else {\n                    ip1 = sys.Particles().Select_usingGivenRand(iUniform, alpha1 - n_incep, rng);\n                }\n                maj = SlipFlow;\n                break;\n            case SlipFlow4:\n                alpha1 = unifDistrib() * (dc_incep + dc_other);\n                if (alpha1 <= dc_incep)\n                {\n                    index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1, iDcol, rng);\n                    ip1 = -2;\n                } else {\n                    ip1 = sys.Particles().Select_usingGivenRand(iDcol, alpha1 - dc_incep, rng);\n                }\n                maj = SlipFlow;\n                break;\n            case FreeMol1:\n                alpha1 = unifDistrib() * n_total;\n                if (alpha1 <= n_incep)\n                {\n                    index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1, iUniform, rng);\n                    ip1 = -2;\n                } else {\n                    ip1 = sys.Particles().Select_usingGivenRand(iUniform, alpha1 - n_incep, rng);\n                }\n                maj = FreeMol;\n                break;\n            case FreeMol2:\n                alpha1 = unifDistrib() * (dc2_incep + dc2_other);\n                if (alpha1 <= dc2_incep)\n                {\n                    index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1, iD2, rng);\n                    ip1 = -2;\n                } else {\n                    ip1 = sys.Particles().Select_usingGivenRand(iD2, alpha1 - dc2_incep, rng);\n                }\n                maj = FreeMol;\n                break;\n            default:\n                alpha1 = unifDistrib() * n_total;\n                if (alpha1 <= n_incep)\n                {\n                    index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1, iUniform, rng);\n                    ip1 = -2;\n                } else {\n                    ip1 = sys.Particles().Select_usingGivenRand(iUniform, alpha1 - n_incep, rng);\n                }\n                maj = SlipFlow;\n                break;\n        }\n\n        // Is this a particle-number particle?\n        if (ip1 == -2)\n        {\n            if (index1 == 0)\n            {\n\t\t// Property sums update triggered - round-off was too severe and\n                // no suitable particle could be found. The easiest option\n                // is not to perform this coagulation event.\n\t\treturn -1;\n            }\n\t    n_index1 = sys.Particles().NumberAtIndex(index1);\n            // Flag sp1 as a particle-number particle\n            ip1_flag = true; \n            // Clone a template particle of the correct size for sp1\n            sp1 = sys.Particles().GetPNParticleAt(index1)->Clone();\n            sp1->SetTime(t); \n        } else {\n            // An ensemble particle\n            if (ip1 >= 0) {\n                sp1 = sys.Particles().At(ip1);\n            } else {\n            // Failed to choose a particle.\n            return -1;\n            }\n        }\n\n        // Choose and get unique second particle.  Note, we are allowed to do\n        // this even if the first particle was invalidated.\n        ip2 = ip1;\n        index2 = index1;\n        unsigned int guard = 0;\n        bool mustSwitch = (ip1 == -2) && (n_incep == 1); // sp1 was the only list particle\n        bool unsuitableChoice = true;\n\n        switch (term) {\n           case SlipFlow1:\n               while (unsuitableChoice && (++guard < 1000))\n                {\n                    alpha2 = unifDistrib() * n_total;\n                    if (alpha2 <= n_incep && !mustSwitch)\n                    {\n                        index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iUniform, rng);\n                        if (!(index2 == index1 && n_index1 == 1))\n                        {\n                            unsuitableChoice = false;\n                            ip2 = -2;\n                        }\n                    } else {\n                        ip2 = sys.Particles().Select_usingGivenRand(iUniform, alpha2 - n_incep, rng);\n                        if (!(ip2 == ip1))\n                            unsuitableChoice = false;\n                    }\n                }\n                break;\n            case SlipFlow2:\n                while (unsuitableChoice && (++guard < 1000))\n                {\n                    alpha2 = unifDistrib() * (dc_1_incep + dc_1_other);\n                    if (alpha2 <= dc_1_incep && !mustSwitch)\n                    {\n                        index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iD_1, rng);\n                        if (!(index2 == index1 && n_index1 == 1))\n                        {\n                            unsuitableChoice = false;\n                            ip2 = -2;\n                        }\n                    } else {\n                        ip2 = sys.Particles().Select_usingGivenRand(iD_1, alpha2 - dc_1_incep, rng);\n                        if (!(ip2 == ip1))\n                            unsuitableChoice = false;\n                    }\n                }\n                break;\n            case SlipFlow3:\n                while (unsuitableChoice && (++guard < 1000))\n                {\n                    alpha2 = unifDistrib() * (dc_1_incep + dc_1_other);\n                    if (alpha2 <= dc_1_incep && !mustSwitch)\n                    {\n                        index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iD_1, rng);\n                        if (!(index2 == index1 && n_index1 == 1))\n                        {\n                            unsuitableChoice = false;\n                            ip2 = -2;\n                        }\n                    } else {\n                        ip2 = sys.Particles().Select_usingGivenRand(iD_1, alpha2 - dc_1_incep, rng);\n                        if (!(ip2 == ip1))\n                            unsuitableChoice = false;\n                    }\n                }\n                break;\n            case SlipFlow4:\n                while (unsuitableChoice && (++guard < 1000))\n                {\n                    alpha2 = unifDistrib() * (dc_2_incep + dc_2_other);\n                    if (alpha2 <= dc_2_incep && !mustSwitch)\n                    {\n                        index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iD_2, rng);\n                        if (!(index2 == index1 && n_index1 == 1))\n                        {\n                            unsuitableChoice = false;\n                            ip2 = -2;\n                        }\n                    } else {\n                        ip2 = sys.Particles().Select_usingGivenRand(iD_2, alpha2 - dc_2_incep, rng);\n                        if (!(ip2 == ip1))\n                            unsuitableChoice = false;\n                    }\n                }\n                break;\n            case FreeMol1:\n                while (unsuitableChoice && (++guard < 1000))\n                {\n                    alpha2 = unifDistrib() * (dc2_m_1_2_incep + dc2_m_1_2_other);\n                    if (alpha2 <= dc2_m_1_2_incep && !mustSwitch)\n                    {\n                        index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iD2_M_1_2, rng);\n                        if (!(index2 == index1 && n_index1 == 1))\n                        {\n                            unsuitableChoice = false;\n                            ip2 = -2;\n                        }\n                    } else {\n                        ip2 = sys.Particles().Select_usingGivenRand(iD2_M_1_2, alpha2 - dc2_m_1_2_incep, rng);\n                        if (!(ip2 == ip1))\n                            unsuitableChoice = false;\n                    }\n                }\n                break;\n            case FreeMol2:\n                while (unsuitableChoice && (++guard < 1000))\n                {\n                    alpha2 = unifDistrib() * (m_1_2_incep + m_1_2_other);\n                    if (alpha2 <= m_1_2_incep && !mustSwitch)\n                    {\n                        index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iM_1_2, rng);\n                        if (!(index2 == index1 && n_index1 == 1))\n                        {\n                            unsuitableChoice = false;\n                            ip2 = -2;\n                        }\n                    } else {\n                        ip2 = sys.Particles().Select_usingGivenRand(iM_1_2, alpha2 - m_1_2_incep, rng);\n                        if (!(ip2 == ip1))\n                            unsuitableChoice = false;\n                        }\n                }\n                break;\n            default:\n                while (unsuitableChoice && (++guard < 1000))\n                {\n                    alpha2 = unifDistrib() * n_total;\n                    if (alpha2 <= n_incep && !mustSwitch)\n                    {\n                        index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iUniform, rng);\n                        if (!(index2 == index1 && n_index1 == 1))\n                        {\n                            unsuitableChoice = false;\n                            ip2 = -2;\n                        }\n                    } else {\n                        ip2 = sys.Particles().Select_usingGivenRand(iUniform, alpha2 - n_incep, rng);\n                        if (!(ip2 == ip1))\n                            unsuitableChoice = false;\n                    }\n                }\n                break;\n            }\n        }\n\n        // Is this a particle-number particle?\n        if (ip2 == -2)\n        {\n            // Note this could be factored into the loops above\n            // but that would require constantly checking for something\n            // that should very infrequently be a problem.\n            // Easiest option is to exit without performing the coagulation event. \n            if (index2 == 0)\n            {\n                if (ip1_flag)\n                {\n                    delete sp1;\n                    sp1 = NULL;\n                }\n                // Property sums updated\n                return -1;\n            }\n            ip2_flag = true; // Flag sp2 as a particle-number particle\n            sp2 = sys.Particles().GetPNParticleAt(index2)->Clone();\n            sp2->SetTime(t); \n        }\n        else\n        {\n            // An ensemble particle\n            if ((ip2 >= 0) && (ip2 != ip1)) {\n                sp2 = sys.Particles().At(ip2);\n            } else {\n                // Failed to select a unique particle.\n                return -1;\n            }\n        }\n\n        //Calculate the majorant rate before updating the particles\n        double majk = MajorantKernel(*sp1, *sp2, sys, maj);\n\n        //Update the particles\n        if (t > sp1->LastUpdateTime())\n            m_mech->UpdateParticle(*sp1, sys, t, ip1, rng, dummy);\n        // Check that particle is still valid.  If not,\n        // remove it and cease coagulating.\n        if (!sp1->IsValid()) {\n            if (!ip1_flag) {\n                // Must remove first particle now.\n                sys.Particles().Remove(ip1);\n            } else {\n                delete sp1;\n                sp1 = NULL;\n            }\n            // Invalidating the index tells this routine not to perform coagulation.\n            ip1 = -1;\n            return 0;\n        }\n\n        if (t > sp2->LastUpdateTime())\n            m_mech->UpdateParticle(*sp2, sys, t, ip2, rng, dummy);\n        // Check validity of particles after update.\n        if (!sp2->IsValid()) {\n            // Tell the ensemble to update particle one before we confuse things\n            // by removing particle 2\n            if (!ip1_flag)\n                sys.Particles().Update(ip1);\n            // Must remove second particle now.\n            if (!ip2_flag)\n                sys.Particles().Remove(ip2);\n            else\n            {\n                // Particle sp2 is not in the ensemble, must manually delete it\n                delete sp2;\n                sp2 = NULL;\n            }\n            // Invalidating the index tells this routine not to perform coagulation.\n            ip2 = -1;\n            return 0;\n        }\n\n        // Check that both the particles are still valid.\n        if ((ip1 != -1) && (ip2 != -1)) \n        {\n            // Must check for ficticious event now by comparing the original\n            // majorant rate and the current (after updates) true rate.\n            double truek = CoagKernel(*sp1, *sp2, sys);\n            double ceff = 0;\n            if (majk<truek)\n                std::cout << \"maj< true\" << std::endl;\n\n            //added by ms785 to include the collision efficiency in the calculation of the rate\n            if (sys.ParticleModel()->AggModel() == AggModels::PAH_KMC_ID)\n            {\n                ceff = sys.ParticleModel()->CollisionEff(sp1, sp2);\n                truek *= ceff;\n            }\n\n            //! For the purpose of checking consistency with the spherical soot\n            //! model solved using the method of moments with interpolative closure\n            //! which assumes that only pyrene (A4) is able to incept and condense.\n            else if (sys.ParticleModel()->AggModel() == AggModels::BinTree_ID || sys.ParticleModel()->AggModel() == AggModels::Spherical_ID) {\n                if (sp1->Primary()->InceptedPAH() && sp2->Primary()->InceptedPAH()) {\n                    ceff = 1;\n                }\n                else if (sp1->Primary()->InceptedPAH() && sp2->NumCarbon() > 16 || sp1->NumCarbon() > 16 && sp2->Primary()->InceptedPAH()) {\n                    ceff = 1;\n                } else {\n                    ceff = 1;\n                }\n                truek *= ceff;\n            }\n\n            if (!Fictitious(majk, truek, rng)) {\n                if (ip1_flag)\n                {\n                    // We are removing the particle from the PN model and\n                    // adding it to the ensemble\n                    sys.Particles().UpdateTotalsWithIndex(index1, -1.0);\n                    sys.Particles().UpdateNumberAtIndex(index1, -1);\n                    sys.Particles().UpdateTotalParticleNumber(-1);\n                    unsigned int index12 = index1 + index2;\n                    // Allow for coagulation in place if the combined particle is small enough\n                    if ((m_mech->CoagulateInList()) && ip2_flag && (index12 < sys.Particles().GetHybridThreshold()))\n                    {\n                        coag_in_place = true;\n                        sys.Particles().UpdateTotalsWithIndex(index12, 1.0);\n                        sys.Particles().UpdateNumberAtIndex(index12, 1);\n                        sys.Particles().UpdateTotalParticleNumber(1);\n                        if (sp1 != NULL) \n                        {\n                            delete sp1;\n                            sp1 = NULL;\n                        }\n                    } else \n                        ip1 = sys.Particles().Add(*sp1, rng, ip2, true);    \n                }\n                if (ip2_flag)\n                {\n                    // We are removing the particle from the PN model and\n                    // adding it to the ensemble\n                    sys.Particles().UpdateTotalsWithIndex(index2, -1.0);\n                    sys.Particles().UpdateNumberAtIndex(index2, -1);\n                    sys.Particles().UpdateTotalParticleNumber(-1);\n                }\n                if (!coag_in_place)\n                    JoinParticles(t, ip1, sp1, ip2, sp2, sys, rng);\n\t\t\t\n                if (ip2_flag && sp2 != NULL)                                                     // Particle sp2 is not in the ensemble, must manually delete it\n                {\n                    delete sp2;\n                    sp2 = NULL;\n                }\n            } else {\n                if (!ip1_flag)\n                    sys.Particles().Update(ip1);\n                else if (sp1 != NULL)                                                            // Particle sp1 is not in the ensemble, must manually delete it\n                {\n                    delete sp1;\n                    sp1 = NULL;\n                }\n                if (!ip2_flag)\n                    sys.Particles().Update(ip2);\n                else if (sp2 != NULL)                                                            // Particle sp2 is not in the ensemble, must manually delete it\n                {\n                    delete sp2;\n                    sp2 = NULL;\n                }\n                return 1; // Ficticious event.\n            }\n        } else {\n            // One or both particles were invalidated on update,\n            // but that's not a problem.  Information on the update\n            // of valid particles must be propagated into the binary\n            // tree\n            if (ip1 != -1)\n                if (!ip1_flag)\n                    sys.Particles().Update(ip1);\n            if (ip2 != -1)\n            {\n                if (!ip2_flag)\n                    sys.Particles().Update(ip2);\n            }\n            if (ip1_flag && sp1 != NULL)                                                         // Particle sp2 is not in the ensemble, must manually delete it\n            {\n                delete sp1;\n                sp1 = NULL;\n            }\n            if (ip2_flag && sp2 != NULL)                                                         // Particle sp2 is not in the ensemble, must manually delete it\n            {\n                delete sp2;\n                sp2 = NULL;\n            }\n    \t}\n    return 0;\n}\n\n\n// COAGULATION KERNELS.\n\n/**\n * Calculate the coagulation kernel between two particles in the given environment.\n *\n *@param[in]    sp1         First particle\n *@param[in]    sp2         Second particle\n *@param[in]    sys         Details of the environment, including temperature and pressure\n *\n *@return       Value of kernel\n */\ndouble Sweep::Processes::HybridTransitionCoagulation::CoagKernel(const Particle &sp1,\n                                                                const Particle &sp2,\n                                                                const Cell &sys) const\n{\n    const double T = sys.GasPhase().Temperature();\n    const double P = sys.GasPhase().Pressure();\n    const double fm = FreeMolKernel(sp1, sp2, T, P, false);\n    const double sf = SlipFlowKernel(sp1, sp2, T, P, sys.GasPhase().Viscosity(), false);\n    return (fm*sf)/(fm+sf);\n}\n\n/**\n * Calculate the majorant kernel between two particles in the given environment.\n *\n *@param[in]    sp1         First particle\n *@param[in]    sp2         Second particle\n *@param[in]    sys         Details of the environment, including temperature and pressure\n *@param[in]    maj         Flag to indicate which majorant kernel is required\n *\n *@return       Value of kernel\n */\ndouble Sweep::Processes::HybridTransitionCoagulation::MajorantKernel(const Particle &sp1,\n                                                                    const Particle &sp2,\n                                                                    const Cell &sys,\n                                                                    const MajorantType maj) const\n{\n    // This routine calculates the coagulation kernel for two particles.  The kernel\n    // type is chosen by the majorant type requested.\n    switch (maj) {\n        case Default:\n            // This should never happen for the transition coagulation kernel\n            assert(maj != Default);\n            break;\n        case FreeMol:\n            // Free molecular majorant.\n            return FreeMolKernel(sp1, sp2, sys.GasPhase().Temperature(),\n                    sys.GasPhase().Pressure(), true);\n        case SlipFlow:\n            // Slip-flow majorant.\n            return SlipFlowKernel(sp1, sp2, sys.GasPhase().Temperature(),\n                    sys.GasPhase().Pressure(), sys.GasPhase().Viscosity(), true);\n    }\n\n    // Invalid majorant, return zero.\n    return 0.0;\n}\n// Returns the free-molecular coagulation kernel value for the\n// two given particles.  Can return either the majorant or\n// true kernel.\ndouble Sweep::Processes::HybridTransitionCoagulation::FreeMolKernel(const Particle &sp1, const Particle &sp2,\n                                double T, double P, bool maj) const\n{\n    // This routine calculate the free molecular coagulation kernel for two particles.\n    // There are two forms of kernel; a majorant form and a non-majorant form.\n\n    // Collect the particle properties\n    const double d1 = sp1.CollDiameter();\n    const double d2 = sp2.CollDiameter();\n    const double invm1 = 1.0 / sp1.Mass();\n    const double invm2 = 1.0 / sp2.Mass();\n\n    if (maj) {\n        // The majorant form is always >= the non-majorant form.\n        return CFMMAJ * m_efm * CFM * sqrt(T) * A() *\n               (std::sqrt(invm1) + std::sqrt(invm2)) *\n               (d1 * d1 + d2 * d2);\n    } else {\n        const double dterm = d1 + d2;\n        return m_efm * CFM * A() *\n               sqrt(T * (invm1 + invm2)) *\n               dterm * dterm;\n    }\n}\n\n// Returns the slip-flow coagulation kernel value for the\n// two given particles.  Can return either the majorant or\n// true kernel.\ndouble Sweep::Processes::HybridTransitionCoagulation::SlipFlowKernel(const Particle &sp1, const Particle &sp2,\n                                 double T, double P, double mu, bool maj) const\n{\n    // Collect the particle properties\n    const double d1 = sp1.CollDiameter();\n    const double d2 = sp2.CollDiameter();\n\n    // For the slip-flow kernel the majorant and non-majorant forms are identical.\n    return ((1.257 * 2.0 * MeanFreePathAir(T,P) *\n             (1.0 / d1 / d1 + 1.0 / d2 / d2)) +\n            (1.0 / d1 + 1.0 / d2)) *\n           CSF * T * (d1 + d2)\n           * A() / mu;\n}\n\n", "meta": {"hexsha": "39558c18868a01ab05096b7267000ef2faa8b423", "size": 36001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_hybrid_transcoag.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_hybrid_transcoag.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_hybrid_transcoag.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 39.4315443593, "max_line_length": 160, "alphanum_fraction": 0.5095414016, "num_tokens": 8674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709194, "lm_q2_score": 0.03904829160793826, "lm_q1q2_score": 0.019371616518079258}}
{"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_MP_GENERIC_INTERCONVERT_HPP\n#define BOOST_MP_GENERIC_INTERCONVERT_HPP\n\n#include <boost/multiprecision/detail/default_ops.hpp>\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127 6326)\n#endif\n\nnamespace boost{ namespace multiprecision{ namespace detail{\n\ntemplate <class To, class From>\ninline To do_cast(const From & from)\n{\n   return static_cast<To>(from);\n}\ntemplate <class To, class B, ::boost::multiprecision::expression_template_option et>\ninline To do_cast(const number<B, et>& from)\n{\n   return from.template convert_to<To>();\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_floating_point>& /*to_type*/, const mpl::int_<number_kind_integer>& /*from_type*/)\n{\n   using default_ops::eval_get_sign;\n   using default_ops::eval_bitwise_and;\n   using default_ops::eval_convert_to;\n   using default_ops::eval_right_shift;\n   using default_ops::eval_ldexp;\n   using default_ops::eval_add;\n   using default_ops::eval_is_zero;\n   // smallest unsigned type handled natively by \"From\" is likely to be it's limb_type:\n   typedef typename canonical<unsigned char, From>::type   l_limb_type;\n   // get the corresponding type that we can assign to \"To\":\n   typedef typename canonical<l_limb_type, To>::type         to_type;\n   From t(from);\n   bool is_neg = eval_get_sign(t) < 0;\n   if(is_neg)\n      t.negate();\n   // Pick off the first limb:\n   l_limb_type limb;\n   l_limb_type mask = static_cast<l_limb_type>(~static_cast<l_limb_type>(0));\n   From fl;\n   eval_bitwise_and(fl, t, mask);\n   eval_convert_to(&limb, fl);\n   to = static_cast<to_type>(limb);\n   eval_right_shift(t, std::numeric_limits<l_limb_type>::digits);\n   //\n   // Then keep picking off more limbs until \"t\" is zero:\n   //\n   To l;\n   unsigned shift = std::numeric_limits<l_limb_type>::digits;\n   while(!eval_is_zero(t))\n   {\n      eval_bitwise_and(fl, t, mask);\n      eval_convert_to(&limb, fl);\n      l = static_cast<to_type>(limb);\n      eval_right_shift(t, std::numeric_limits<l_limb_type>::digits);\n      eval_ldexp(l, l, shift);\n      eval_add(to, l);\n      shift += std::numeric_limits<l_limb_type>::digits;\n   }\n   //\n   // Finish off by setting the sign:\n   //\n   if(is_neg)\n      to.negate();\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_integer>& /*to_type*/, const mpl::int_<number_kind_integer>& /*from_type*/)\n{\n   using default_ops::eval_get_sign;\n   using default_ops::eval_bitwise_and;\n   using default_ops::eval_convert_to;\n   using default_ops::eval_right_shift;\n   using default_ops::eval_left_shift;\n   using default_ops::eval_bitwise_or;\n   using default_ops::eval_is_zero;\n   // smallest unsigned type handled natively by \"From\" is likely to be it's limb_type:\n   typedef typename canonical<unsigned char, From>::type   limb_type;\n   // get the corresponding type that we can assign to \"To\":\n   typedef typename canonical<limb_type, To>::type         to_type;\n   From t(from);\n   bool is_neg = eval_get_sign(t) < 0;\n   if(is_neg)\n      t.negate();\n   // Pick off the first limb:\n   limb_type limb;\n   limb_type mask = static_cast<limb_type>(~static_cast<limb_type>(0));\n   From fl;\n   eval_bitwise_and(fl, t, mask);\n   eval_convert_to(&limb, fl);\n   to = static_cast<to_type>(limb);\n   eval_right_shift(t, std::numeric_limits<limb_type>::digits);\n   //\n   // Then keep picking off more limbs until \"t\" is zero:\n   //\n   To l;\n   unsigned shift = std::numeric_limits<limb_type>::digits;\n   while(!eval_is_zero(t))\n   {\n      eval_bitwise_and(fl, t, mask);\n      eval_convert_to(&limb, fl);\n      l = static_cast<to_type>(limb);\n      eval_right_shift(t, std::numeric_limits<limb_type>::digits);\n      eval_left_shift(l, shift);\n      eval_bitwise_or(to, l);\n      shift += std::numeric_limits<limb_type>::digits;\n   }\n   //\n   // Finish off by setting the sign:\n   //\n   if(is_neg)\n      to.negate();\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_floating_point>& /*to_type*/, const mpl::int_<number_kind_floating_point>& /*from_type*/)\n{\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127)\n#endif\n   //\n   // The code here only works when the radix of \"From\" is 2, we could try shifting by other\n   // radixes but it would complicate things.... use a string conversion when the radix is other\n   // than 2:\n   //\n   if(std::numeric_limits<number<From> >::radix != 2)\n   {\n      to = from.str(0, std::ios_base::fmtflags()).c_str();\n      return;\n   }\n\n\n   typedef typename canonical<unsigned char, To>::type ui_type;\n\n   using default_ops::eval_fpclassify;\n   using default_ops::eval_add;\n   using default_ops::eval_subtract;\n   using default_ops::eval_convert_to;\n   using default_ops::eval_get_sign;\n   using default_ops::eval_is_zero;\n\n   //\n   // First classify the input, then handle the special cases:\n   //\n   int c = eval_fpclassify(from);\n\n   if(c == (int)FP_ZERO)\n   {\n      to = ui_type(0);\n      return;\n   }\n   else if(c == (int)FP_NAN)\n   {\n      to = static_cast<const char*>(\"nan\");\n      return;\n   }\n   else if(c == (int)FP_INFINITE)\n   {\n      to = static_cast<const char*>(\"inf\");\n      if(eval_get_sign(from) < 0)\n         to.negate();\n      return;\n   }\n\n   typename From::exponent_type e;\n   From f, term;\n   to = ui_type(0);\n\n   eval_frexp(f, from, &e);\n\n   static const int shift = std::numeric_limits<boost::intmax_t>::digits - 1;\n\n   while(!eval_is_zero(f))\n   {\n      // extract int sized bits from f:\n      eval_ldexp(f, f, shift);\n      eval_floor(term, f);\n      e -= shift;\n      eval_ldexp(to, to, shift);\n      typename boost::multiprecision::detail::canonical<boost::intmax_t, To>::type ll;\n      eval_convert_to(&ll, term);\n      eval_add(to, ll);\n      eval_subtract(f, term);\n   }\n   typedef typename To::exponent_type to_exponent;\n   if((e > (std::numeric_limits<to_exponent>::max)()) || (e < (std::numeric_limits<to_exponent>::min)()))\n   {\n      to = static_cast<const char*>(\"inf\");\n      if(eval_get_sign(from) < 0)\n         to.negate();\n      return;\n   }\n   eval_ldexp(to, to, static_cast<to_exponent>(e));\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_rational>& /*to_type*/, const mpl::int_<number_kind_rational>& /*from_type*/)\n{\n   typedef typename component_type<number<To> >::type     to_component_type;\n\n   number<From> t(from);\n   to_component_type n(numerator(t)), d(denominator(t));\n   using default_ops::assign_components;\n   assign_components(to, n.backend(), d.backend());\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_rational>& /*to_type*/, const mpl::int_<number_kind_integer>& /*from_type*/)\n{\n   typedef typename component_type<number<To> >::type     to_component_type;\n\n   number<From> t(from);\n   to_component_type n(t), d(1);\n   using default_ops::assign_components;\n   assign_components(to, n.backend(), d.backend());\n}\n\ntemplate <class R, class LargeInteger>\nR safe_convert_to_float(const LargeInteger& i)\n{\n   using std::ldexp;\n   if(!i)\n      return R(0);\n   if(std::numeric_limits<R>::is_specialized && std::numeric_limits<R>::max_exponent)\n   {\n      LargeInteger val(i);\n      if(val.sign() < 0)\n         val = -val;\n      unsigned mb = msb(val);\n      if(mb >= std::numeric_limits<R>::max_exponent)\n      {\n         int scale_factor = (int)mb + 1 - std::numeric_limits<R>::max_exponent;\n         BOOST_ASSERT(scale_factor >= 1);\n         val >>= scale_factor;\n         R result = val.template convert_to<R>();\n         if(std::numeric_limits<R>::digits == 0 || std::numeric_limits<R>::digits >= std::numeric_limits<R>::max_exponent)\n         {\n            //\n            // Calculate and add on the remainder, only if there are more\n            // digits in the mantissa that the size of the exponent, in \n            // other words if we are dropping digits in the conversion\n            // otherwise:\n            //\n            LargeInteger remainder(i);\n            remainder &= (LargeInteger(1) << scale_factor) - 1;\n            result += ldexp(safe_convert_to_float<R>(remainder), -scale_factor);\n         }\n         return i.sign() < 0 ? static_cast<R>(-result) : result;\n      }\n   }\n   return i.template convert_to<R>();\n}\n\ntemplate <class To, class Integer>\ninline typename disable_if_c<is_number<To>::value || is_floating_point<To>::value>::type \n   generic_convert_rational_to_float_imp(To& result, const Integer& n, const Integer& d, const mpl::true_&)\n{\n   //\n   // If we get here, then there's something about one type or the other\n   // that prevents an exactly rounded result from being calculated\n   // (or at least it's not clear how to implement such a thing).\n   //\n   using default_ops::eval_divide;\n   number<To> fn(safe_convert_to_float<number<To> >(n)), fd(safe_convert_to_float<number<To> >(d));\n   eval_divide(result, fn.backend(), fd.backend());\n}\ntemplate <class To, class Integer>\ninline typename enable_if_c<is_number<To>::value || is_floating_point<To>::value>::type \n   generic_convert_rational_to_float_imp(To& result, const Integer& n, const Integer& d, const mpl::true_&)\n{\n   //\n   // If we get here, then there's something about one type or the other\n   // that prevents an exactly rounded result from being calculated\n   // (or at least it's not clear how to implement such a thing).\n   //\n   To fd(safe_convert_to_float<To>(d));\n   result = safe_convert_to_float<To>(n);\n   result /= fd;\n}\n\ntemplate <class To, class Integer>\ntypename enable_if_c<is_number<To>::value || is_floating_point<To>::value>::type \n   generic_convert_rational_to_float_imp(To& result, Integer& num, Integer& denom, const mpl::false_&)\n{\n   //\n   // If we get here, then the precision of type To is known, and the integer type is unbounded\n   // so we can use integer division plus manipulation of the remainder to get an exactly\n   // rounded result.\n   //\n   if(num == 0)\n   {\n      result = 0;\n      return;\n   }\n   bool s = false;\n   if(num < 0)\n   {\n      s = true;\n      num = -num;\n   }\n   int denom_bits = msb(denom);\n   int shift = std::numeric_limits<To>::digits + denom_bits - msb(num);\n   if(shift > 0)\n      num <<= shift;\n   else if(shift < 0)\n      denom <<= boost::multiprecision::detail::unsigned_abs(shift);\n   Integer q, r;\n   divide_qr(num, denom, q, r);\n   int q_bits = msb(q);\n   if(q_bits == std::numeric_limits<To>::digits - 1)\n   {\n      //\n      // Round up if 2 * r > denom:\n      //\n      r <<= 1;\n      int c = r.compare(denom);\n      if(c > 0)\n         ++q;\n      else if((c == 0) && (q & 1u))\n      {\n         ++q;\n      }\n   }\n   else\n   {\n      BOOST_ASSERT(q_bits == std::numeric_limits<To>::digits);\n      //\n      // We basically already have the rounding info:\n      //\n      if(q & 1u)\n      {\n         if(r || (q & 2u))\n            ++q;\n      }\n   }\n   using std::ldexp;\n   result = do_cast<To>(q);\n   result = ldexp(result, -shift);\n   if(s)\n      result = -result;\n}\ntemplate <class To, class Integer>\ninline typename disable_if_c<is_number<To>::value || is_floating_point<To>::value>::type\n   generic_convert_rational_to_float_imp(To& result, Integer& num, Integer& denom, const mpl::false_& tag)\n{\n   number<To> t;\n   generic_convert_rational_to_float_imp(t, num, denom, tag);\n   result = t.backend();\n}\n\ntemplate <class To, class From>\ninline void generic_convert_rational_to_float(To& result, const From& f)\n{\n   //\n   // Type From is always a Backend to number<>, or an\n   // instance of number<>, but we allow\n   // To to be either a Backend type, or a real number type,\n   // that way we can call this from generic conversions, and\n   // from specific conversions to built in types.\n   //\n   typedef typename mpl::if_c<is_number<From>::value, From, number<From> >::type actual_from_type;\n   typedef typename mpl::if_c<is_number<To>::value || is_floating_point<To>::value, To, number<To> >::type actual_to_type;\n   typedef typename component_type<actual_from_type>::type integer_type;\n   typedef mpl::bool_<!std::numeric_limits<integer_type>::is_specialized \n                      || std::numeric_limits<integer_type>::is_bounded\n                      || !std::numeric_limits<actual_to_type>::is_specialized \n                      || !std::numeric_limits<actual_to_type>::is_bounded\n                      || (std::numeric_limits<actual_to_type>::radix != 2)> dispatch_tag;\n\n   integer_type n(numerator(static_cast<actual_from_type>(f))), d(denominator(static_cast<actual_from_type>(f)));\n   generic_convert_rational_to_float_imp(result, n, d, dispatch_tag());\n}\n\ntemplate <class To, class From>\ninline void generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_floating_point>& /*to_type*/, const mpl::int_<number_kind_rational>& /*from_type*/)\n{\n   generic_convert_rational_to_float(to, from);\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert_float2rational(To& to, const From& from, const mpl::int_<2>& /*radix*/)\n{\n   typedef typename mpl::front<typename To::unsigned_types>::type ui_type;\n   static const int shift = std::numeric_limits<boost::long_long_type>::digits;\n   typename From::exponent_type e;\n   typename component_type<number<To> >::type num, denom;\n   number<From> val(from);\n   val = frexp(val, &e);\n   while(val)\n   {\n      val = ldexp(val, shift);\n      e -= shift;\n      boost::long_long_type ll = boost::math::lltrunc(val);\n      val -= ll;\n      num <<= shift;\n      num += ll;\n   }\n   denom = ui_type(1u);\n   if(e < 0)\n      denom <<= -e;\n   else if(e > 0)\n      num <<= e;\n   assign_components(to, num.backend(), denom.backend());\n}\n\ntemplate <class To, class From, int Radix>\nvoid generic_interconvert_float2rational(To& to, const From& from, const mpl::int_<Radix>& /*radix*/)\n{\n   //\n   // This is almost the same as the binary case above, but we have to use\n   // scalbn and ilogb rather than ldexp and frexp, we also only extract\n   // one Radix digit at a time which is terribly inefficient!\n   //\n   typedef typename mpl::front<typename To::unsigned_types>::type ui_type;\n   typename From::exponent_type e;\n   typename component_type<number<To> >::type num, denom;\n   number<From> val(from);\n\n   if (!val)\n   {\n      to = ui_type(0u);\n      return;\n   }\n\n   e = ilogb(val);\n   val = scalbn(val, -e);\n   while(val)\n   {\n      boost::long_long_type ll = boost::math::lltrunc(val);\n      val -= ll;\n      val = scalbn(val, 1);\n      num *= Radix;\n      num += ll;\n      --e;\n   }\n   ++e;\n   denom = ui_type(Radix);\n   denom = pow(denom, abs(e));\n   if(e > 0)\n   {\n      num *= denom;\n      denom = 1;\n   }\n   assign_components(to, num.backend(), denom.backend());\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_rational>& /*to_type*/, const mpl::int_<number_kind_floating_point>& /*from_type*/)\n{\n   generic_interconvert_float2rational(to, from, mpl::int_<std::numeric_limits<number<From> >::radix>());\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_integer>& /*to_type*/, const mpl::int_<number_kind_rational>& /*from_type*/)\n{\n   number<From> t(from);\n   number<To> result(numerator(t) / denominator(t));\n   to = result.backend();\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert_float2int(To& to, const From& from, const mpl::int_<2>& /*radix*/)\n{\n   typedef typename From::exponent_type exponent_type;\n   static const exponent_type shift = std::numeric_limits<boost::long_long_type>::digits;\n   exponent_type e;\n   number<To>   num(0u);\n   number<From> val(from);\n   val = frexp(val, &e);\n   while(e > 0)\n   {\n      int s = (std::min)(e, shift);\n      val = ldexp(val, s);\n      e -= s;\n      boost::long_long_type ll = boost::math::lltrunc(val);\n      val -= ll;\n      num <<= s;\n      num += ll;\n   }\n   to = num.backend();\n}\n\ntemplate <class To, class From, int Radix>\nvoid generic_interconvert_float2int(To& to, const From& from, const mpl::int_<Radix>& /*radix*/)\n{\n   //\n   // This is almost the same as the binary case above, but we have to use\n   // scalbn and ilogb rather than ldexp and frexp, we also only extract\n   // one Radix digit at a time which is terribly inefficient!\n   //\n   typename From::exponent_type e;\n   number<To> num(0u);\n   number<From> val(from);\n   e = ilogb(val);\n   val = scalbn(val, -e);\n   while(e >= 0)\n   {\n      boost::long_long_type ll = boost::math::lltrunc(val);\n      val -= ll;\n      val = scalbn(val, 1);\n      num *= Radix;\n      num += ll;\n      --e;\n   }\n   to = num.backend();\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_integer>& /*to_type*/, const mpl::int_<number_kind_floating_point>& /*from_type*/)\n{\n   generic_interconvert_float2int(to, from, mpl::int_<std::numeric_limits<number<From> >::radix>());\n}\n\ntemplate <class To, class From, class tag>\nvoid generic_interconvert_complex_to_scalar(To& to, const From& from, const mpl::true_&, const tag&)\n{\n   // We just want the real part, and \"to\" is the correct type already:\n   eval_real(to, from);\n\n   To im;\n   eval_imag(im, from);\n   if(!eval_is_zero(im))\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\n}\ntemplate <class To, class From>\nvoid generic_interconvert_complex_to_scalar(To& to, const From& from, const mpl::false_&, const mpl::true_&)\n{\n   typedef typename component_type<number<From> >::type component_number;\n   typedef typename component_number::backend_type component_backend;\n   //\n   // Get the real part and copy-construct the result from it:\n   //\n   component_backend r;\n   generic_interconvert_complex_to_scalar(r, from, mpl::true_(), mpl::true_());\n   to = r;\n}\ntemplate <class To, class From>\nvoid generic_interconvert_complex_to_scalar(To& to, const From& from, const mpl::false_&, const mpl::false_&)\n{\n   typedef typename component_type<number<From> >::type component_number;\n   typedef typename component_number::backend_type component_backend;\n   //\n   // Get the real part and use a generic_interconvert to type To:\n   //\n   component_backend r;\n   generic_interconvert_complex_to_scalar(r, from, mpl::true_(), mpl::true_());\n   generic_interconvert(to, r, mpl::int_<number_category<To>::value>(), mpl::int_<number_category<To>::value>());\n}\n\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_floating_point>& /*to_type*/, const mpl::int_<number_kind_complex>& /*from_type*/)\n{\n   typedef typename component_type<number<From> >::type component_number;\n   typedef typename component_number::backend_type component_backend;\n\n   generic_interconvert_complex_to_scalar(to, from, mpl::bool_<boost::is_same<component_backend, To>::value>(), mpl::bool_<boost::is_constructible<To, const component_backend&>::value>());\n}\ntemplate <class To, class From>\nvoid generic_interconvert(To& to, const From& from, const mpl::int_<number_kind_integer>& /*to_type*/, const mpl::int_<number_kind_complex>& /*from_type*/)\n{\n   typedef typename component_type<number<From> >::type component_number;\n   typedef typename component_number::backend_type component_backend;\n\n   generic_interconvert_complex_to_scalar(to, from, mpl::bool_<boost::is_same<component_backend, To>::value>(), mpl::bool_<boost::is_constructible<To, const component_backend&>::value>());\n}\n\n}\n}\n} // namespaces\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n#endif  // BOOST_MP_GENERIC_INTERCONVERT_HPP\n\n", "meta": {"hexsha": "730f45cc3a8d0591b9a1b04794c44ee75bb0c278", "size": 19914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/multiprecision/detail/generic_interconvert.hpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "deps/boost/boost/multiprecision/detail/generic_interconvert.hpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "deps/boost/boost/multiprecision/detail/generic_interconvert.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": 33.6954314721, "max_line_length": 188, "alphanum_fraction": 0.6673696897, "num_tokens": 5235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.039048289930506117, "lm_q1q2_score": 0.019371615685915528}}
{"text": "/// @file DeconvolverHogbom.tcc\n/// @brief Class for a deconvolver based on the Hogbom CLEAN\n/// @details This concrete class defines a deconvolver used to estimate an\n/// image from a dirty image, psf optionally using a mask and a weights image.\n/// @ingroup Deconvolver\n///\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Tim Cornwell <tim.cornwell@csiro.au>\n///\n\n#include <string>\n\n#include <casacore/casa/aips.h>\n#include <boost/shared_ptr.hpp>\n#include <casacore/casa/Arrays/Array.h>\n#include <askap/AskapLogging.h>\nASKAP_LOGGER(dechogbomlogger, \".deconvolution.hogbom\");\n\n#include <deconvolution/DeconvolverHogbom.h>\n\nnamespace askap {\n\n    namespace synthesis {\n\n        /// @brief Class for a deconvolver based on the Hogbom Clean\n        /// @details This base class defines a deconvolver used to estimate an\n        /// image from a dirty image, psf optionally using a mask and a weights image.\n        /// The template argument T is the type, and FT is the transform\n        /// e.g. DeconvolverHogbom<Double, DComplex>\n        /// @ingroup Deconvolver\n\n        template<class T, class FT>\n        DeconvolverHogbom<T, FT>::~DeconvolverHogbom()\n        {\n        };\n\n        template<class T, class FT>\n        DeconvolverHogbom<T, FT>::DeconvolverHogbom(Vector<Array<T> >& dirty, Vector<Array<T> >& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf)\n        {\n            if (this->itsNumberDirtyTerms > 1) {\n                throw(AskapError(\"Hogbom CLEAN cannot perform multi-term deconvolutions\"));\n            }\n        };\n\n        template<class T, class FT>\n        DeconvolverHogbom<T, FT>::DeconvolverHogbom(Array<T>& dirty, Array<T>& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf)\n        {\n        };\n\n        template<class T, class FT>\n        void DeconvolverHogbom<T, FT>::initialise()\n        {\n            DeconvolverBase<T, FT>::initialise();\n        }\n\n        template<class T, class FT>\n        bool DeconvolverHogbom<T, FT>::deconvolve()\n        {\n            this->initialise();\n\n            ASKAPLOG_INFO_STR(dechogbomlogger, \"Performing Hogbom CLEAN for \" << this->control()->targetIter() << \" iterations\");\n            do {\n                this->oneIteration();\n                this->monitor()->monitor(*(this->state()));\n                this->state()->incIter();\n            } while (!this->control()->terminate(*(this->state())));\n\n            ASKAPLOG_INFO_STR(dechogbomlogger, \"Performed Hogbom CLEAN for \" << this->state()->currentIter() << \" iterations\");\n\n            ASKAPLOG_INFO_STR(dechogbomlogger, this->control()->terminationString());\n\n            this->finalise();\n\n            return True;\n        }\n\n        template<class T, class FT>\n        void DeconvolverHogbom<T, FT>::configure(const LOFAR::ParameterSet& parset)\n        {\n            DeconvolverBase<T, FT>::configure(parset);\n        }\n\n        // This contains the heart of the Hogbom Clean algorithm\n        template<class T, class FT>\n        bool DeconvolverHogbom<T, FT>::oneIteration()\n        {\n            const bool isMasked(this->weight(0).shape().conform(this->dirty(0).shape()));\n\n            // Find peak in residual image\n            casa::IPosition minPos;\n            casa::IPosition maxPos;\n            T minVal, maxVal;\n            if (isMasked) {\n                casa::minMaxMasked(minVal, maxVal, minPos, maxPos, this->dirty(0), this->weight(0));\n                minVal = this->dirty(0)(minPos);\n                maxVal = this->dirty(0)(maxPos);\n            } else {\n                casa::minMax(minVal, maxVal, minPos, maxPos, this->dirty(0));\n            }\n            //\n            ASKAPLOG_INFO_STR(dechogbomlogger, \"Maximum = \" << maxVal << \" at location \" << maxPos);\n            ASKAPLOG_INFO_STR(dechogbomlogger, \"Minimum = \" << minVal << \" at location \" << minPos);\n\n            T absPeakVal = 0.0;\n            casa::IPosition absPeakPos;\n            if (abs(minVal) < abs(maxVal)) {\n                absPeakVal = maxVal;\n                absPeakPos = maxPos;\n            } else {\n                absPeakVal = minVal;\n                absPeakPos = minPos;\n            }\n\n            this->state()->setPeakResidual(absPeakVal);\n            this->state()->setObjectiveFunction(absPeakVal);\n            this->state()->setTotalFlux(sum(this->model()));\n\n            // Has this terminated for any reason?\n            if (this->control()->terminate(*(this->state()))) {\n                return True;\n            }\n\n            const uInt nx(this->psf(0).shape()(0));\n            const uInt ny(this->psf(0).shape()(1));\n\n            IPosition subPsfShape(this->findSubPsfShape());\n\n            // Now we adjust model and residual for this component\n            const casa::IPosition residualShape(this->dirty(0).shape().nonDegenerate());\n            const IPosition subPsfStart(2, nx / 2 - subPsfShape(0) / 2, ny / 2 - subPsfShape(1) / 2);\n            const IPosition subPsfEnd(2, nx / 2 + subPsfShape(0) / 2 - 1, ny / 2 + subPsfShape(1) / 2 - 1);\n            const IPosition subPsfStride(2, 1, 1);\n\n            Slicer subPsfSlicer(subPsfStart, subPsfEnd, subPsfStride, Slicer::endIsLast);\n\n            const casa::IPosition psfShape(2, nx, ny);\n\n            casa::IPosition residualStart(2, 0), residualEnd(2, 0), residualStride(2, 1);\n            casa::IPosition psfStart(2, 0), psfEnd(2, 0), psfStride(2, 1);\n\n            const casa::IPosition modelShape(this->model(0).shape().nonDegenerate());\n            casa::IPosition modelStart(2, 0), modelEnd(2, 0), modelStride(2, 1);\n\n            // Wrangle the start, end, and shape into consistent form.\n            for (uInt dim = 0; dim < 2; dim++) {\n                residualStart(dim) = max(0, Int(absPeakPos(dim) - psfShape(dim) / 2));\n                residualEnd(dim) = min(Int(absPeakPos(dim) + psfShape(dim) / 2 - 1), Int(residualShape(dim) - 1));\n                // Now we have to deal with the PSF. Here we want to use enough of the\n                // PSF to clean the residual image.\n                psfStart(dim) = max(0, Int(this->itsPeakPSFPos(dim) - (absPeakPos(dim) - residualStart(dim))));\n                psfEnd(dim) = min(Int(this->itsPeakPSFPos(dim) - (absPeakPos(dim) - residualEnd(dim))),\n                                  Int(psfShape(dim) - 1));\n\n                modelStart(dim) = residualStart(dim);\n                modelEnd(dim) = residualEnd(dim);\n            }\n\n            casa::Slicer psfSlicer(psfStart, psfEnd, psfStride, Slicer::endIsLast);\n            casa::Slicer residualSlicer(residualStart, residualEnd, residualStride, Slicer::endIsLast);\n            casa::Slicer modelSlicer(modelStart, modelEnd, modelStride, Slicer::endIsLast);\n\n            if (!(residualSlicer.length() == psfSlicer.length()) || !(residualSlicer.stride() == psfSlicer.stride())) {\n                ASKAPLOG_INFO_STR(dechogbomlogger, \"Peak of PSF  : \" << this->itsPeakPSFPos);\n                ASKAPLOG_INFO_STR(dechogbomlogger, \"Peak of residual: \" << absPeakPos);\n                ASKAPLOG_INFO_STR(dechogbomlogger, \"Residual start  : \" << residualStart << \" end: \" << residualEnd);\n                ASKAPLOG_INFO_STR(dechogbomlogger, \"PSF   start  : \" << psfStart << \" end: \" << psfEnd);\n                ASKAPLOG_INFO_STR(dechogbomlogger, \"Residual slicer : \" << residualSlicer);\n                ASKAPLOG_INFO_STR(dechogbomlogger, \"PSF slicer   : \" << psfSlicer);\n                throw AskapError(\"Mismatch in slicers for residual and psf images\");\n            }\n\n            // Add to model\n            this->model()(absPeakPos) = this->model()(absPeakPos) + this->control()->gain() * absPeakVal;\n\n            // Subtract entire PSF from residual image\n\n            this->dirty()(residualSlicer) = this->dirty()(residualSlicer)\n                                            - this->control()->gain() * absPeakVal * this->psf()(psfSlicer);\n\n            return True;\n        }\n\n    } // namespace synthesis\n\n} // namespace askap\n", "meta": {"hexsha": "774908b40b18cba1ca74d1cb766922f0d4e2e611", "size": 8968, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverHogbom.tcc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverHogbom.tcc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverHogbom.tcc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7047619048, "max_line_length": 129, "alphanum_fraction": 0.5941123996, "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.04885778260386222, "lm_q1q2_score": 0.019351013060708633}}
{"text": "#ifndef AIKIDO_COMMON_SPLINE_HPP_\n#define AIKIDO_COMMON_SPLINE_HPP_\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <Eigen/Sparse>\n#include <Eigen/StdVector>\n\nnamespace aikido {\nnamespace common {\n\n/// An arbitrary dimensional polynomial spline. The number of coefficients,\n/// outputs, and knot points may be specified either at compile time (via\n/// template parameters) or at runtime (if the template parameters are\n/// \\c Eigen::Dynamic). We suggest setting as many of these parameters at\n/// compile time as possible for best performance.\n///\n/// Note that this spline is not guaranteed to be continuous at knot points;\n/// this is the responsbility of the user who constructs the splines\n/// coefficients. See \\c SplineProblem for a helper class that constructs a\n/// continuous spline from a set of constraints.\n///\n/// \\tparam _Scalar floating type used to represent a scalar value\n/// \\tparam _Index integral type used to represent an index\n/// \\tparam _NumCoefficients number of polynomial coefficients, or \\c Dynamic\n/// \\tparam _NumOutputs number of outputs, or \\c Dynamic\n/// \\tparam _NumKnots number of knots, or \\c Dynamic\ntemplate <class _Scalar = double,\n          class _Index = int,\n          _Index _NumCoefficients = Eigen::Dynamic,\n          _Index _NumOutputs = Eigen::Dynamic,\n          _Index _NumKnots = Eigen::Dynamic>\nclass SplineND\n{\npublic:\n  using Scalar = _Scalar;\n  using Index = _Index;\n\n  static constexpr Index NumCoefficientsAtCompileTime = _NumCoefficients;\n  static constexpr Index NumOutputsAtCompileTime = _NumOutputs;\n  static constexpr Index NumKnotsAtCompileTime = _NumKnots;\n  static constexpr Index NumSegmentsAtCompileTime\n      = (_NumKnots != Eigen::Dynamic) ? (NumKnotsAtCompileTime - 1)\n                                      : Eigen::Dynamic;\n  static constexpr Index DimensionAtCompileTime\n      = (NumSegmentsAtCompileTime != Eigen::Dynamic\n         && _NumCoefficients != Eigen::Dynamic)\n            ? (NumSegmentsAtCompileTime * NumCoefficientsAtCompileTime)\n            : Eigen::Dynamic;\n\n  using TimeVector = Eigen::Matrix<Scalar, NumKnotsAtCompileTime, 1>;\n  using SolutionMatrix = Eigen::Matrix<Scalar,\n                                       NumOutputsAtCompileTime,\n                                       NumCoefficientsAtCompileTime>;\n  using OutputVector = Eigen::Matrix<Scalar, NumOutputsAtCompileTime, 1>;\n  using SolutionMatrices\n      = std::vector<SolutionMatrix, Eigen::aligned_allocator<SolutionMatrix> >;\n\n  /// Constructs an empty spline.\n  SplineND() = default;\n\n  /// Constructs a spline with the specified coefficients. The \\c _solution\n  /// is a vector of \\c _times.size() - 1 spline coefficients, where the\n  /// i-th matrix defines the polynomial coefficients for the segment between\n  /// knot points (i) and (i + 1). Each coefficient matrix of size\n  /// (num outputs) x (num coefficients), where element (i, j) is the\n  /// coefficient on the \\c x^j term for output \\c i.\n  ///\n  /// \\param _times times of knot points, must be monotone increasing\n  /// \\param _solution list of polynomial coefficients for each segment\n  SplineND(\n      const TimeVector& _times,\n      const std::vector<SolutionMatrix,\n                        Eigen::aligned_allocator<SolutionMatrix> >& _solution);\n\n  // Default copy and move semantics.\n  SplineND(SplineND&& _other) = default;\n  SplineND(const SplineND& _other) = default;\n  SplineND& operator=(SplineND&& _other) = default;\n  SplineND& operator=(const SplineND& _other) = default;\n\n  /// Sets the time of the \\c _index-th knot point. Times must remain monotone\n  /// after performing this operation.\n  ///\n  /// \\param _index index of a knot point\n  /// \\param _t new time for that knot point\n  void setTime(Index _index, Scalar _t);\n\n  /// Sets the times of all knot points.\n  ///\n  /// \\param _t new times, must be monotone increasing\n  void setTimes(TimeVector&& _t);\n\n  /// Sets the times of all knot points.\n  ///\n  /// \\param _t new times, must be monotone increasing\n  void setTimes(const TimeVector& _t);\n\n  /// Gets times of all knot points.\n  ///\n  /// \\return times of knot points\n  const TimeVector& getTimes() const;\n\n  /// Gets polynomial coefficients for all segments.\n  ///\n  /// \\return polynomial coefficients\n  const SolutionMatrices& getCoefficients() const;\n\n  /// Gets the number of knot points.\n  ///\n  /// \\return number of knot points\n  Index getNumKnots() const;\n\n  /// Gets the number of outputs points.\n  ///\n  /// \\return number of outputs points\n  Index getNumOutputs() const;\n\n  /// Gets an upperbound on the number of non-zero derivatives.\n  ///\n  /// \\return upper bound on the number of non-zero derivatives\n  Index getNumDerivatives() const;\n\n  /// Gets the number of polynomial coefficients in each segment.\n  ///\n  /// \\return number of polynomial coefficients\n  Index getNumCoefficients() const;\n\n  /// Gets the duration of the spline. This is the difference between the time\n  /// of the first and last knot points.\n  ///\n  /// \\return duration of the spline\n  Scalar getDuration() const;\n\n  /// Gets the index of the segment that contains time \\c _t.\n  ///\n  /// \\param _t time parameter\n  /// \\return index of the segment that contains this time\n  Index getSegmentIndex(Scalar _t) const;\n\n  /// Evaluate the \\c _derivative-th order of the spline at time \\c _t. The\n  /// zero-th order derivative is function value. All derivatives greater than\n  /// \\c getNumDerivatives() are guaranteed to be zero.\n  ///\n  /// \\param _t time parameter\n  /// \\param _derivative order of derivative to evaluate\n  /// \\return value of the specified derivative at time \\c _t\n  OutputVector evaluate(Scalar _t, Index _derivative = 0) const;\n\nprivate:\n  using CoefficientVector\n      = Eigen::Matrix<Scalar, NumCoefficientsAtCompileTime, 1>;\n  using CoefficientMatrix = Eigen::Matrix<Scalar,\n                                          NumCoefficientsAtCompileTime,\n                                          NumCoefficientsAtCompileTime>;\n\n  TimeVector mTimes;\n  SolutionMatrices mSolution;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(TimeVector::NeedsToAlign)\n};\n\n/// Utility for fitting splines given constraints on function value, derivative\n/// value, and continuity. This class is intended to be used by calling methods\n/// to add constraints to the spline, then calling \\c fit() to find spline\n/// coefficients that satisfy those constraints.\n///\n/// The number of coefficients, outputs, and knot points may be specified\n/// either at compile time (via template parameters) or at runtime (if the\n/// template parameters are \\c Eigen::Dynamic). We suggest setting as many of\n/// these parameters at compile time as possible for best performance.\n///\n/// \\tparam _Scalar floating type used to represent a scalar value\n/// \\tparam _Index integral type used to represent an index\n/// \\tparam _NumCoefficients number of polynomial coefficients, or \\c Dynamic\n/// \\tparam _NumOutputs number of outputs, or \\c Dynamic\n/// \\tparam _NumKnots number of knots, or \\c Dynamic\ntemplate <class _Scalar = double,\n          class _Index = int,\n          _Index _NumCoefficients = Eigen::Dynamic,\n          _Index _NumOutputs = Eigen::Dynamic,\n          _Index _NumKnots = Eigen::Dynamic>\nclass SplineProblem\n{\npublic:\n  using Scalar = _Scalar;\n  using Index = _Index;\n\n  static constexpr Index NumCoefficientsAtCompileTime = _NumCoefficients;\n  static constexpr Index NumOutputsAtCompileTime = _NumOutputs;\n  static constexpr Index NumKnotsAtCompileTime = _NumKnots;\n  static constexpr Index NumSegmentsAtCompileTime\n      = (_NumKnots != Eigen::Dynamic) ? (NumKnotsAtCompileTime - 1)\n                                      : Eigen::Dynamic;\n  static constexpr Index DimensionAtCompileTime\n      = (NumSegmentsAtCompileTime != Eigen::Dynamic\n         && _NumCoefficients != Eigen::Dynamic)\n            ? (NumSegmentsAtCompileTime * NumCoefficientsAtCompileTime)\n            : Eigen::Dynamic;\n\n  using TimeVector = Eigen::Matrix<Scalar, NumKnotsAtCompileTime, 1>;\n  using OutputVector = Eigen::Matrix<Scalar, NumOutputsAtCompileTime, 1>;\n  using OutputMatrix = Eigen::Matrix<Scalar,\n                                     NumCoefficientsAtCompileTime,\n                                     NumOutputsAtCompileTime>;\n  using CoefficientVector\n      = Eigen::Matrix<Scalar, NumCoefficientsAtCompileTime, 1>;\n  using CoefficientMatrix = Eigen::Matrix<Scalar,\n                                          NumCoefficientsAtCompileTime,\n                                          NumCoefficientsAtCompileTime>;\n  using ProblemMatrix = Eigen::SparseMatrix<Scalar, 0, Index>;\n  using ProblemVector\n      = Eigen::Matrix<Scalar, DimensionAtCompileTime, NumOutputsAtCompileTime>;\n  using SolutionMatrix = Eigen::Matrix<Scalar,\n                                       NumOutputsAtCompileTime,\n                                       NumCoefficientsAtCompileTime>;\n  using Spline\n      = SplineND<Scalar, Index, _NumCoefficients, _NumOutputs, _NumKnots>;\n\n  /// Constructs a spline fitting problem with the knot points at the specified\n  /// times. This overload is only supported if \\c _NumCoefficients and\n  /// \\c _NumOutputs are specified as template parameters. The length of\n  /// \\c _times must equal \\c _NumKnots if that template parameter is specified\n  ///\n  /// If \\c _NumCoefficients or \\c _NumOutputs is \\c Eigen::Dynamic, you must\n  /// use the other constructor overload.\n  ///\n  /// \\param _times list of knot point times, must be monotone increasing\n  explicit SplineProblem(const TimeVector& _times);\n\n  /// Constructs a spline fitting problem with knot points at the specified\n  /// times and the specified number of coefficients and outputs. These\n  /// parameters must match \\c _NumKnots and \\c _NumCoefficients if they are\n  /// specified at compile time. Additionally, the length of \\c _times must\n  /// match \\c _NumKnots if that template parameter is specified.\n  ///\n  /// \\param _times list of knot point times, must be monotone increasing\n  /// \\param _numCoefficients number of polynomial coefficients\n  /// \\param _numOutputs number of outputs\n  SplineProblem(\n      const TimeVector& _times, Index _numCoefficients, Index _numOutputs);\n\n  // Default copy and move semantics.\n  SplineProblem(SplineProblem&& _other) = default;\n  SplineProblem(const SplineProblem& _other) = default;\n  SplineProblem& operator=(SplineProblem&& _other) = default;\n  SplineProblem& operator=(const SplineProblem& _other) = default;\n\n  /// Creates a vector of the form [ 1, t, t^2, ... t^_n ]\n  static CoefficientVector createTimeVector(Scalar _t, Index _i, Index _n);\n\n  /// Creates the \\c _n by \\c _n matrix of derivative coefficients for a\n  /// polynomial with \\c _n coefficients. The i-th row of this matrix\n  /// corresponds to coefficients for the i-th derivative. The j-th column of\n  /// this matrix corresponds to the coefficient on x^j.\n  ///\n  /// \\param _n number of coefficients\n  /// \\return polynomial coefficient matrix\n  static CoefficientMatrix createCoefficientMatrix(Index _n);\n\n  /// Adds a constraint that the \\c _derivative-th order derivative of knot\n  /// point \\c _knot should equal \\c _value. This adds one constraint if the\n  /// knot is an end point and two constraints for interior knots. The zero-th\n  /// derivative is function value.\n  ///\n  /// \\param _knot knot index to constraint\n  /// \\param _derivative order of derivative to constraint\n  /// \\param _value desired value of that knot point's derivative\n  void addConstantConstraint(\n      Index _knot, Index _derivative, const OutputVector& _value);\n\n  /// Adds a continuity constraint on the \\c _derivative-th order derivative at\n  /// knot point \\c _knot. This operation is only defined for interior knot\n  /// points and adds one constraint.\n  ///\n  /// \\param _knot knot index to constraint\n  /// \\param _derivative order of derivative to constraint\n  void addContinuityConstraint(Index _knot, Index _derivative);\n\n  /// Fit a spline given the constraints on added to this object. The behavior\n  /// of this function is undefined if the problem is over or\n  /// under-constrained. To avoid this, be sure to only add\n  /// (num coefficients) * (num knots - 1) constraints to this class.\n  ///\n  /// \\return spline that satisfies the constraints\n  Spline fit();\n\n  /// Gets the number of knot points.\n  ///\n  /// \\return number of knot points\n  Index getNumKnots() const;\n\n  /// Gets the number of outputs points.\n  ///\n  /// \\return number of outputs points\n  Index getNumOutputs() const;\n\n  /// Gets the duration of the spline. This is the difference between the time\n  /// of the first and last knot points.\n  ///\n  /// \\return duration of the spline\n  Scalar getDuration() const;\n\nprivate:\n  Index mNumKnots;\n  Index mNumSegments;\n  Index mNumCoefficients;\n  Index mNumOutputs;\n  Index mDimension;\n\n  CoefficientMatrix mCoefficientMatrix;\n\n  Index mRowIndex;\n  TimeVector mTimes;\n  ProblemMatrix mA;\n  ProblemVector mB;\n\n  std::vector<SolutionMatrix,\n              Eigen::aligned_allocator<SolutionMatrix> >\n      mSolution; // length _NumSegments\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(\n      CoefficientMatrix::NeedsToAlign || TimeVector::NeedsToAlign\n      || ProblemMatrix::NeedsToAlign\n      || ProblemVector::NeedsToAlign)\n};\n\n} // namespace common\n} // namespace aikido\n\n#include \"detail/Spline-impl.hpp\"\n\n#endif // AIKIDO_COMMON_SPLINE_HPP_\n", "meta": {"hexsha": "eda3ecb191a5b57051104153e6335572402bd542", "size": 13426, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/aikido/common/Spline.hpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/aikido/common/Spline.hpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/aikido/common/Spline.hpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.604719764, "max_line_length": 79, "alphanum_fraction": 0.7037837033, "num_tokens": 3171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.045352584425245944, "lm_q1q2_score": 0.01933478601831536}}
{"text": "#include \"eigen-sparse.h\"\n#include <Eigen/LU>\n\n#if __cplusplus > 199711L\n  #define SMART_PTR std::unique_ptr\n#else\n  #define SMART_PTR std::auto_ptr\n#endif\n\ntemplate <class T>\nRET sparse_new(int rows, int cols, void** pr) {\n    typedef SparseMatrix<T> M;\n    *(M**)pr = new M(rows, cols);\n    return 0;\n}\nAPI(sparse_new, (int code, int rows, int cols, void** pr), (rows,cols,pr));\n\ntemplate <class T>\nRET sparse_clone(void* p, void** q) {\n    typedef SparseMatrix<T> M;\n    *(M**)q = new M(*(M*)p);\n    return 0;\n}\nAPI(sparse_clone, (int code, void* p, void** q), (p,q));\n\ntemplate <class T>\nRET sparse_fromList(int rows, int cols, void* data, int size, void** pr) {\n    typedef SparseMatrix<T> M;\n    typedef Triplet<T> E;\n    SMART_PTR<M> a(new M(rows, cols));\n    a->setFromTriplets((E*)data, (E*)data + size);\n    *(M**)pr = a.release();\n    return 0;\n}\nAPI(sparse_fromList, (int code, int rows, int cols, void* data, int size, void** pr), (rows,cols,data,size,pr));\n\ntemplate <class  T>\nRET sparse_toList(void* p, void* q, int s) {\n    int n = 0;\n    typedef SparseMatrix<T> M;\n    typedef Triplet<T> E;\n    M* m = (M*)p;\n    for (int k = 0; k < m->outerSize(); ++k) {\n        for (typename M::InnerIterator i(*m, k); i; ++i) {\n            if (n >= s)\n                return strdup(\"sparse_toList: buffer overrun detected\");\n            ((E*)q)[n++] = E(i.row(), i.col(), i.value());\n        }\n    }\n    return n < s ? strdup(\"sparse_toList: buffer underrun detected\") : 0;\n}\nAPI(sparse_toList, (int code, void* p, void* q, int s), (p,q,s));\n\ntemplate <class T>\nRET sparse_free(void* p) {\n    delete (SparseMatrix<T>*)p;\n    return 0;\n}\nAPI(sparse_free, (int code, void* p), (p));\n\n#define SPARSE_UNOP_INPLACE(name)\\\ntemplate <class T>\\\nRET sparse_##name(void* p, void** pr) {\\\n    typedef SparseMatrix<T> M;\\\n    std::unique_ptr<M> a(new M(*(M*)p));\\\n    a->name();\\\n    *(M**)pr = a.release();\\\n    return 0;\\\n}\\\nAPI(sparse_##name, (int code, void* p, void** pr), (p, pr));\n\nSPARSE_UNOP_INPLACE(makeCompressed);\nSPARSE_UNOP_INPLACE(uncompress);\n\n#define SPARSE_UNOP(name)\\\ntemplate <class T>\\\nRET sparse_##name(void* p, void** pr) {\\\n    typedef SparseMatrix<T> M;\\\n    *(M**)pr = new M(((M*)p)->name());\\\n    return 0;\\\n}\\\nAPI(sparse_##name, (int code, void* p, void** pr), (p, pr));\n\nSPARSE_UNOP(adjoint);\nSPARSE_UNOP(transpose);\n\ntemplate <class T>\nRET sparse_pruned(void* p, void** pr) {\n    typedef SparseMatrix<T> M;\n    std::unique_ptr<M> a(new M(*(M*)p));\n    a->prune(T(1));\n    *(M**)pr = a.release();\n    return 0;\n}\nAPI(sparse_pruned, (int code, void* p, void** pr), (p, pr));\n\ntemplate <class T>\nRET sparse_prunedRef(void* p, void* q, void** pr) {\n    typedef SparseMatrix<T> M;\n    std::unique_ptr<M> a(new M(*(M*)p));\n    a->prune(*(T*)q);\n    *(M**)pr = a.release();\n    return 0;\n}\nAPI(sparse_prunedRef, (int code, void* p, void* q, void** pr), (p, q, pr));\n\ntemplate <class T>\nRET sparse_scale(void* p, void* q, void** pr) {\n    typedef SparseMatrix<T> M;\n    *(M**)pr = new M(*(T*)q * *(M*)p);\n    return 0;\n}\nAPI(sparse_scale, (int code, void* p, void* q, void** pr), (p, q, pr));\n\ntemplate <class T>\nRET sparse_coeff(void* p, int row, int col, void* pr) {\n    *(T*)pr = ((SparseMatrix<T>*)p)->coeff(row, col);\n    return 0;\n}\nAPI(sparse_coeff, (int code, void* p, int row, int col, void* pr), (p, row, col, pr));\n\ntemplate <class T>\nRET sparse_coeffRef(void* p, int row, int col, void** pr) {\n    *(T**)pr = &((SparseMatrix<T>*)p)->coeffRef(row, col);\n    return 0;\n}\nAPI(sparse_coeffRef, (int code, void* p, int row, int col, void** pr), (p, row, col, pr));\n\n#define SPARSE_PROP(name,type)\\\ntemplate <class T>\\\nRET sparse_##name(void* p, void* pr) {\\\n    *(type*)pr = ((SparseMatrix<T>*)p)->name();\\\n    return 0;\\\n}\\\nAPI(sparse_##name, (int code, void* p, void* pr), (p, pr));\n\nSPARSE_PROP(cols, int);\nSPARSE_PROP(rows, int);\nSPARSE_PROP(innerSize, int);\nSPARSE_PROP(outerSize, int);\nSPARSE_PROP(nonZeros, int);\nSPARSE_PROP(isCompressed, int);\nSPARSE_PROP(norm, T);\nSPARSE_PROP(squaredNorm, T);\nSPARSE_PROP(blueNorm, T);\n\n#define SPARSE_BINOP(name,op)\\\ntemplate <class T>\\\nRET sparse_##name(void* p, void* q, void** pr) {\\\n    typedef SparseMatrix<T> M;\\\n    *(M**)pr = new M(*(M*)p op *(M*)q);\\\n    return 0;\\\n}\\\nAPI(sparse_##name, (int code, void* p, void* q, void** pr), (p, q, pr));\n\nSPARSE_BINOP(add, +);\nSPARSE_BINOP(sub, -);\nSPARSE_BINOP(mul, *);\n\ntemplate <class T>\nRET sparse_block(void* p, int row, int col, int rows, int cols, void** pr) {\n    typedef SparseMatrix<T> M;\n    *(M**)pr = new M(((M*)p)->block(row,col,rows,cols));\n    return 0;\n}\nAPI(sparse_block, (int code, void* p, int row, int col, int rows, int cols, void** pr), (p, row, col, rows, cols, pr));\n\ntemplate <class T> bool isZero(T x) { return x == 0; }\ntemplate <class T> bool isZero(std::complex<T> x) { return x.real() == 0 && x.imag() == 0; }\n\ntemplate <class T>\nRET sparse_fromMatrix(void* p, int rows, int cols, void** pq) {\n    typedef SparseMatrix<T> M;\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix src((T*)p, rows, cols);\n    std::unique_ptr<M> dst(new M(rows, cols));\n    for (int row = 0; row < rows; ++row) {\n        for (int col = 0; col < cols; ++col) {\n            T val = src.coeff(row,col);\n            if (!isZero(val))\n                dst->insert(row, col) = val;\n        }\n    }\n    dst->makeCompressed();\n    *(M**)pq = dst.release();\n    return 0;\n}\nAPI(sparse_fromMatrix, (int code, void* p, int rows, int cols, void** pq), (p,rows,cols,pq));\n\ntemplate <class T>\nRET sparse_toMatrix(void* p, void* q, int rows, int cols) {\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix((T*)q, rows, cols) = *(SparseMatrix<T>*)p;\n    return 0;\n}\nAPI(sparse_toMatrix, (int code, void* p, void* q, int rows, int cols), (p,q,rows,cols));\n\ntemplate <class T>\nRET sparse_values(void* p, int* s, void** q) {\n    SparseMatrix<T>* m = (SparseMatrix<T>*)p;\n    *s = m->outerIndexPtr()[m->outerSize()];\n    *q = m->valuePtr();\n    return 0;\n}\nAPI(sparse_values, (int code, void*p, int* s, void** q), (p,s,q));\n\ntemplate <class T>\nRET sparse_outerStarts(void* p, int* s, void** q) {\n    SparseMatrix<T>* m = (SparseMatrix<T>*)p;\n    *s = m->outerSize() + 1;\n    *q = m->outerIndexPtr();\n    return 0;\n}\nAPI(sparse_outerStarts, (int code, void*p, int* s, void** q), (p,s,q));\n\ntemplate <class T>\nRET sparse_innerIndices(void* p, int* s, void** q) {\n    SparseMatrix<T>* m = (SparseMatrix<T>*)p;\n    *s = m->outerIndexPtr()[m->outerSize()];\n    *q = m->innerIndexPtr();\n    return 0;\n}\nAPI(sparse_innerIndices, (int code, void*p, int* s, void** q), (p,s,q));\n\ntemplate <class T>\nRET sparse_innerNNZs(void* p, int* s, void** q) {\n    SparseMatrix<T>* m = (SparseMatrix<T>*)p;\n    *s = m->outerSize();\n    *q = m->innerNonZeroPtr();\n    return 0;\n}\nAPI(sparse_innerNNZs, (int code, void*p, int* s, void** q), (p,s,q));\n\n#define SPARSE_INPLACE(name,op)\\\ntemplate <class T>\\\nRET sparse_##name(void* p) {\\\n    ((SparseMatrix<T>*)p)->op();\\\n    return 0;\\\n}\\\nAPI(sparse_##name, (int code, void* p), (p));\n\nSPARSE_INPLACE(setIdentity, setIdentity);\nSPARSE_INPLACE(setZero, setZero);\nSPARSE_INPLACE(compressInplace, makeCompressed);\nSPARSE_INPLACE(uncompressInplace, uncompress);\n\ntemplate <class T>\nRET sparse_reserve(void* p, int s) {\n    ((SparseMatrix<T>*)p)->reserve(s);\n    return 0;\n}\nAPI(sparse_reserve, (int code, void* p, int s), (p,s));\n\ntemplate <class T>\nRET sparse_resize(void* p, int r, int c) {\n    ((SparseMatrix<T>*)p)->resize(r,c);\n    return 0;\n}\nAPI(sparse_resize, (int code, void* p, int r, int c), (p,r,c));\n\ntemplate <class T>\nRET sparse_conservativeResize(void* p, int r, int c) {\n    ((SparseMatrix<T>*)p)->conservativeResize(r,c);\n    return 0;\n}\nAPI(sparse_conservativeResize, (int code, void* p, int r, int c), (p,r,c));\n", "meta": {"hexsha": "d9e722844c99aa0ea6c277b0afd119d981cf7cbe", "size": 7790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cbits/eigen-sparse.cpp", "max_stars_repo_name": "nilsalex/eigen", "max_stars_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T08:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T10:27:07.000Z", "max_issues_repo_path": "cbits/eigen-sparse.cpp", "max_issues_repo_name": "nilsalex/eigen", "max_issues_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-07-17T14:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T11:37:18.000Z", "max_forks_repo_path": "cbits/eigen-sparse.cpp", "max_forks_repo_name": "nilsalex/eigen", "max_forks_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-11-22T08:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T07:40:02.000Z", "avg_line_length": 29.1760299625, "max_line_length": 119, "alphanum_fraction": 0.6083440308, "num_tokens": 2556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.04535257732852371, "lm_q1q2_score": 0.019334782992829435}}
{"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 <cstdio>\n#include <cmath>\n#include <thread>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Core/Core.h>\n#include <Core/Utility/Console.h>\n\n#define NUM_THREADS 4\n#define NUM_START 1\n#define NUM_END 10\n\nvoid simple_task()\n{\n    int n_a_rows = 2000;\n    int n_a_cols = 2000;\n    int n_b_rows = 2000;\n    int n_b_cols = 2000;\n\n    Eigen::MatrixXd a(n_a_rows, n_a_cols);\n    for (int i = 0; i < n_a_rows; ++i)\n        for (int j = 0; j < n_a_cols; ++j)\n            a(i, j) = n_a_cols * i + j;\n\n    Eigen::MatrixXd b(n_b_rows, n_b_cols);\n    for (int i = 0; i < n_b_rows; ++i)\n        for (int j = 0; j < n_b_cols; ++j)\n            b(i, j) = n_b_cols * i + j;\n\n    Eigen::MatrixXd d(n_a_rows, n_b_cols);\n    d = a * b;\n}\n\nvoid svd_task()\n{\n    int n_a_rows = 10000;\n    int n_a_cols = 200;\n    Eigen::MatrixXd a(n_a_rows, n_a_cols);\n    for (int i = 0; i < n_a_rows; ++i)\n        for (int j = 0; j < n_a_cols; ++j)\n            a(i, j) = n_a_cols * i + j;\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(a,\n            Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::MatrixXd pca = svd.matrixU().block<10000, 10>(0, 0\n            ).transpose() * a;\n}\n\nvoid TestMatrixMultiplication(int argc, char** argv)\n{\n    int i = 0, nRet = 0, nSum = 0, nStart = NUM_START, nEnd = NUM_END;\n    int nThreads = 1, nTmp = nStart + nEnd;\n    unsigned uTmp = (unsigned(nEnd - nStart + 1) * unsigned(nTmp)) / 2;\n    int nSumCalc = uTmp;\n\n    if (nTmp < 0) {\n        nSumCalc = -nSumCalc;\n    }\n\n#ifdef _OPENMP\n    printf(\"OpenMP is supported.\\n\");\n#else\n    printf(\"OpenMP is not supported.\\n\");\n#endif\n\n#ifdef _OPENMP\n    omp_set_num_threads(NUM_THREADS);\n#endif\n\n#pragma omp parallel default(none) private(i) shared(nSum, nThreads, nStart, nEnd)\n    {\n#ifdef _OPENMP\n#pragma omp master\n        nThreads = omp_get_num_threads();\n#endif\n\n#pragma omp for\n        for (i = nStart; i <= nEnd; ++i) {\n#pragma omp atomic\n            nSum += i;\n        }\n    }\n\n    if (nThreads == NUM_THREADS) {\n        printf(\"%d OpenMP threads were used.\\n\", NUM_THREADS);\n        nRet = 0;\n    } else {\n        printf(\"Expected %d OpenMP threads, but %d were used.\\n\",\n                NUM_THREADS, nThreads);\n        nRet = 1;\n    }\n\n    if (nSum != nSumCalc) {\n        printf(\"The sum of %d through %d should be %d, \"\n                \"but %d was reported!\\n\",\n                NUM_START, NUM_END, nSumCalc, nSum);\n        nRet = 1;\n    } else {\n        printf(\"The sum of %d through %d is %d\\n\",\n                NUM_START, NUM_END, nSum);\n    }\n\n    int test_thread = 256;\n    if (argc > 1) {\n        test_thread = std::stoi(argv[1]);\n    }\n    open3d::PrintInfo(\"Benchmark multithreading up to %d threads.\\n\",\n            test_thread);\n\n    for (int i = 1; i <= test_thread; i *= 2) {\n        char buff[1024];\n        sprintf(buff, \"simple task, %d tasks, %d threads\", i, i);\n        open3d::ScopeTimer t(buff);\n#ifdef _OPENMP\n        omp_set_num_threads(i);\n#endif\n#pragma omp parallel default(none) shared(nThreads)\n        {\n            simple_task();\n        }\n    }\n\n    for (int i = 1; i <= test_thread; i *= 2) {\n        char buff[1024];\n        sprintf(buff, \"simple task, %d tasks, %d threads\", i, i);\n        open3d::ScopeTimer t(buff);\n        std::vector<std::thread> threads(i);\n        for (int k = 0; k < i; k++) {\n            threads[k] = std::thread(simple_task);\n        }\n        for (int k = 0; k < i; k++) {\n            threads[k].join();\n        }\n    }\n\n    for (int i = 1; i <= test_thread; i *= 2) {\n        char buff[1024];\n        sprintf(buff, \"svd, %d tasks, %d threads\", i, i);\n        open3d::ScopeTimer t(buff);\n#ifdef _OPENMP\n        omp_set_num_threads(i);\n#endif\n#pragma omp parallel default(none) shared(nThreads)\n        {\n            svd_task();\n        }\n    }\n\n    for (int i = 1; i <= test_thread; i *= 2) {\n        char buff[1024];\n        sprintf(buff, \"svd task, %d tasks, %d threads\", i, i);\n        open3d::ScopeTimer t(buff);\n        std::vector<std::thread> threads(i);\n        for (int k = 0; k < i; k++) {\n            threads[k] = std::thread(svd_task);\n        }\n        for (int k = 0; k < i; k++) {\n            threads[k].join();\n        }\n    }\n}\n\ninline void ComputeSomething(int i, Eigen::Vector6d &A_r, double &r,\n        std::vector<Eigen::Vector3d> &data)\n{\n    const Eigen::Vector3d &vs = data[i];\n    const Eigen::Vector3d &vt = data[i];\n    const Eigen::Vector3d &nt = data[i];\n    r = (vs - vt).dot(nt);\n    //A_r.setZero();\n    A_r.block<3, 1>(0, 0).noalias() = vs.cross(nt);\n    A_r.block<3, 1>(3, 0).noalias() = nt;\n}\n\n/// Function to simulate building Jacobian matrix\n/// uses simple way of using OpenMP and std::bind\nvoid TestBindedFunction()\n{\n    // data generation\n    const int NCORR = 200000000;\n    std::vector<Eigen::Vector3d> data;\n    {\n        open3d::ScopeTimer timer1(\"Data generation\");\n        data.resize(NCORR);\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n        for (int i = 0; i < NCORR; i++) {\n            data[i] = Eigen::Vector3d::Random();\n        }\n    }\n\n    // data we want to build\n    Eigen::Matrix6d ATA;\n    Eigen::Vector6d ATb;\n\n    // to do using private ATA\n    // https://stackoverflow.com/questions/24948395/openmp-calling-global-variables-through-functions\n    auto f = std::bind(ComputeSomething, std::placeholders::_1,\n        std::placeholders::_2, std::placeholders::_3, data);\n\n    auto f_lambda = [&](int i, Eigen::Vector6d &A_r, double &r) {\n        ComputeSomething(i, A_r, r, data);\n    };\n\n    ATA.setZero();\n    ATb.setZero();\n    {\n        open3d::ScopeTimer timer(\"Calling binding function\");\n#ifdef _OPENMP\n#pragma omp parallel\n        {\n#endif\n            Eigen::Matrix6d ATA_private;\n            Eigen::Vector6d ATb_private;\n            ATA_private.setZero();\n            ATb_private.setZero();\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n            for (int i = 0; i < NCORR; i++) {\n                Eigen::Vector6d A_r;\n                double r;\n                f(i, A_r, r);\n                ATA_private.noalias() += A_r * A_r.transpose();\n                ATb_private.noalias() += A_r * r;\n            }\n#ifdef _OPENMP\n#pragma omp critical\n            {\n#endif\n                ATA += ATA_private;\n                ATb += ATb_private;\n#ifdef _OPENMP\n            }    // omp critical\n        }    // omp parallel\n#endif\n    }\n    std::cout << ATA << std::endl;\n    std::cout << ATb << std::endl;\n\n    ATA.setZero();\n    ATb.setZero();\n    {\n        open3d::ScopeTimer timer(\"Calling lambda function\");\n#ifdef _OPENMP\n#pragma omp parallel\n        {\n#endif\n            Eigen::Matrix6d ATA_private;\n            Eigen::Vector6d ATb_private;\n            ATA_private.setZero();\n            ATb_private.setZero();\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n            for (int i = 0; i < NCORR; i++) {\n                Eigen::Vector6d A_r;\n                double r;\n                f_lambda(i, A_r, r);\n                ATA_private.noalias() += A_r * A_r.transpose();\n                ATb_private.noalias() += A_r * r;\n            }\n#ifdef _OPENMP\n#pragma omp critical\n            {\n#endif\n                ATA += ATA_private;\n                ATb += ATb_private;\n#ifdef _OPENMP\n            }    // omp critical\n        }    // omp parallel\n#endif\n    }\n    std::cout << ATA << std::endl;\n    std::cout << ATb << std::endl;\n\n    ATA.setZero();\n    ATb.setZero();\n    {\n        open3d::ScopeTimer timer(\"Calling function directly\");\n#ifdef _OPENMP\n#pragma omp parallel\n        {\n#endif\n            Eigen::Matrix6d ATA_private;\n            Eigen::Vector6d ATb_private;\n            ATA_private.setZero();\n            ATb_private.setZero();\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n            for (int i = 0; i < NCORR; i++) {\n                Eigen::Vector6d A_r;\n                double r;\n                ComputeSomething(i, A_r, r, data);\n                ATA_private.noalias() += A_r * A_r.transpose();\n                ATb_private.noalias() += A_r * r;\n            }\n#ifdef _OPENMP\n#pragma omp critical\n            {\n#endif\n                ATA += ATA_private;\n                ATb += ATb_private;\n#ifdef _OPENMP\n            }    // omp critical\n        }    // omp parallel\n#endif\n    }\n    std::cout << ATA << std::endl;\n    std::cout << ATb << std::endl;\n\n    ATA.setZero();\n    ATb.setZero();\n    {\n        open3d::ScopeTimer timer(\"Direct optration\");\n#ifdef _OPENMP\n#pragma omp parallel\n        {\n#endif\n            Eigen::Matrix6d ATA_private;\n            Eigen::Vector6d ATb_private;\n            ATA_private.setZero();\n            ATb_private.setZero();\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n            for (int i = 0; i < NCORR; i++) {\n                const Eigen::Vector3d &vs = data[i];\n                const Eigen::Vector3d &vt = data[i];\n                const Eigen::Vector3d &nt = data[i];\n                double r = (vs - vt).dot(nt);\n                Eigen::Vector6d A_r;\n                A_r.block<3, 1>(0, 0).noalias() = vs.cross(nt);\n                A_r.block<3, 1>(3, 0).noalias() = nt;\n                ATA_private.noalias() += A_r * A_r.transpose();\n                ATb_private.noalias() += A_r * r;\n            }\n#ifdef _OPENMP\n#pragma omp critical\n            {\n#endif\n                ATA += ATA_private;\n                ATb += ATb_private;\n#ifdef _OPENMP\n            }    // omp critical\n        }    // omp parallel\n#endif\n    }\n    std::cout << ATA << std::endl;\n    std::cout << ATb << std::endl;\n}\n\n\nint main(int argc, char **argv)\n{\n    using namespace open3d;\n\n    if (ProgramOptionExists(argc, argv, \"--test_bind\")) {\n        TestBindedFunction();\n    }\n    else {\n        TestMatrixMultiplication(argc, argv);\n    }\n}\n", "meta": {"hexsha": "1b7fc74b94cab2859dcf60955f65ee0b85922376", "size": 11144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test/TestOpenMP.cpp", "max_stars_repo_name": "csjunxu/Open3D", "max_stars_repo_head_hexsha": "ef042a6c50e54c4bb56ccb4657a745c9b38c1b7f", "max_stars_repo_licenses": ["MIT"], "max_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/TestOpenMP.cpp", "max_issues_repo_name": "csjunxu/Open3D", "max_issues_repo_head_hexsha": "ef042a6c50e54c4bb56ccb4657a745c9b38c1b7f", "max_issues_repo_licenses": ["MIT"], "max_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/TestOpenMP.cpp", "max_forks_repo_name": "csjunxu/Open3D", "max_forks_repo_head_hexsha": "ef042a6c50e54c4bb56ccb4657a745c9b38c1b7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-31T07:02:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-31T07:02:30.000Z", "avg_line_length": 28.2126582278, "max_line_length": 101, "alphanum_fraction": 0.5421751615, "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.0433658021638845, "lm_q1q2_score": 0.019320745674693555}}
{"text": "/** \n * \n * @file functions.cpp\n * \n * @author Simone Paolo Mottadelli\n * \n */\n\n#include \"functions.hpp\"\n#include \"rbgraph.hpp\"\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/depth_first_search.hpp>\n\nstd::pair<std::list<SignedCharacter>, bool>\nrealize_character(const SignedCharacter &sc, RBGraph &g) {\n    std::list<SignedCharacter> output;\n\n    // current character vertex\n    RBVertex cv = 0;\n\n    // get the vertex in g whose name is sc.character\n    try {\n        cv = get_vertex(sc.character, g);\n    } catch (const std::out_of_range &e) {\n        // g has no vertex named sc.character\n        return std::make_pair(output, false);\n    }\n\n    RBVertexIMap i_map, c_map;\n    RBVertexIAssocMap i_assocmap(i_map), c_assocmap(c_map);\n\n    // fill vertex index map\n    RBVertexIter v, v_end;\n    std::tie(v, v_end) = vertices(g);\n    for (size_t index = 0; v != v_end; ++v, ++index) {\n        boost::put(i_assocmap, *v, index);\n    }\n\n    // build the components map\n    boost::connected_components(g, c_assocmap,\n                                boost::vertex_index_map(i_assocmap));\n\n    if (sc.state == State::gain && is_inactive(cv, g)) {\n        // c+ and c is inactive\n        if (logging::enabled) {\n            // verbosity enabled\n            //std::cout << \"Realizing \" << sc;\n        }\n        // realize the character c+:\n        // - add a red edge between c and each species in D(c) \\ N(c)\n        // - delete all black edges incident on c\n        std::tie(v, v_end) = vertices(g);\n        for (; v != v_end; ++v) {\n            if (!is_species(*v, g) || c_map.at(*v) != c_map.at(cv)) {\n                continue;\n            }\n            // for each species in the same connected component of cv\n\n            RBEdge e;\n            bool exists;\n            std::tie(e, exists) = edge(*v, cv, g);\n\n            if (exists) {\n                // there is an edge (black) between *v and cv\n                remove_edge(e, g);\n            } else {\n                // there isn't an edge between *v and cv\n                add_edge(*v, cv, Color::red, g);\n            }\n        }\n\n        if (logging::enabled) {\n            // verbosity enabled\n            //std::cout << std::endl;\n        }\n    } else if (sc.state == State::lose && is_active(cv, g)) {\n        // c- and c is active\n        if (logging::enabled) {\n            // verbosity enabled\n            //std::cout << \"Realizing \" << sc << std::endl;\n        }\n\n        // realize the character c- if it is connected through red edges to all the species of the component in which c resides. In this case:\n        // - delete all edges incident on c\n        bool connected = true;\n        std::tie(v, v_end) = vertices(g);\n        for (; v != v_end; ++v) {\n            if (!is_species(*v, g) || c_map.at(*v) != c_map.at(cv)) {\n                continue;\n            }\n\n            // if cv is not connected to the species v, which belongs to its same component, then cv is not connected to all the species of its component.\n            if (!exists(*v, cv, g)) {\n                connected = false;\n                break;\n            }\n        }\n\n        if (connected) {\n            clear_vertex(cv, g);\n        } else {\n            if (logging::enabled) {\n                // verbosity enabled\n                //std::cout << \"Could not realize \" << sc << std::endl;\n            }\n            return std::make_pair(output, false);\n        }\n    } else {\n        if (logging::enabled) {\n            // verbosity enabled\n            //std::cout << \"Could not realize \" << sc << std::endl;\n        }\n\n        // this should never happen during the algorithm, but it is handled just in\n        // case something breaks (or user input happens)\n        return std::make_pair(output, false);\n    }\n\n    output.push_back(sc);\n\n    // delete all isolated vertices\n    remove_singletons(g);\n\n    return std::make_pair(output, true);\n}\n\nstd::pair<std::list<SignedCharacter>, bool> realize_species(const RBVertex v,\n                                                            RBGraph &g) {\n    std::list<SignedCharacter> lsc;\n\n    if (!is_species(v, g)) {\n        return std::make_pair(lsc, false);\n    }\n\n    // build the list of inactive characters adjacent to v (species)\n\n    std::list<RBVertex> adjacent_chars = get_adj_vertices(v, g);\n\n    for (RBVertex c : adjacent_chars) {\n        if (is_inactive(c, g)) {\n            lsc.push_back({g[c].name, State::gain});\n        }\n    }\n\n    return realize(lsc, g);\n}\n\nstd::pair<std::list<SignedCharacter>, bool>\nrealize(const std::list<SignedCharacter> &lsc, RBGraph &g) {\n    std::list<SignedCharacter> output;\n\n    // realize the list of signed characters lsc; the algorithm stops when a\n    // non-feasible realization is encountered, setting the boolean flag to false\n    // TODO: maybe change this behaviour\n    for (const SignedCharacter i : lsc) {\n        if (std::find(output.cbegin(), output.cend(), i) != output.cend()) {\n            // the signed character i has already been realized in a previous sc\n            continue;\n        }\n\n        std::list<SignedCharacter> sc;\n        bool feasible;\n\n        std::tie(sc, feasible) = realize_character(i, g);\n\n        if (!feasible) {\n            return std::make_pair(sc, false);\n        }\n\n        output.splice(output.cend(), sc);\n    }\n\n    return std::make_pair(output, true);\n}\n\nbool is_complete(std::list<SignedCharacter> sc, const RBGraph &gm) {\n    RBVertexIter v, v_end;\n    auto scb = sc.begin();\n    auto sce = sc.end();\n    std::tie(v, v_end) = vertices(gm);\n    while (v != v_end) {\n        if (is_inactive(*v, gm)) {\n            while (scb != sce) {\n                if ((get_vertex(scb->character, gm) == *v)) {\n                    return false;\n                }\n                scb++;\n            }\n        }\n        v++;\n    }\n    return true;\n}\n\nvoid sort_by_degree(std::list<RBVertex> &list_to_sort, const RBGraph &g) {\n    // constructing a list of pairs <RBVertex, int>, where the first element is a vertex and the second element is the degree of the vertex\n    std::list<std::pair<RBVertex, int>> list_of_pairs;\n\n    for (RBVertex v : list_to_sort) {\n        list_of_pairs.push_back(std::make_pair(v, out_degree(v, g)));\n    }\n\n    auto comparator = [](const std::pair<RBVertex, int> &a,\n                         const std::pair<RBVertex, int> &b) {\n        return a.second > b.second;\n    };\n\n    list_of_pairs.sort(comparator);\n\n    list_to_sort.clear();\n\n    for (std::pair<RBVertex, int> pair : list_of_pairs) {\n        list_to_sort.push_back(pair.first);\n    }\n}\n\nstd::list<RBVertex> get_all_minimal_p_active_species(const RBGraph &g,\n                                                     bool all) {\n    std::list<RBVertex> out;\n    std::list<RBVertex> active_species = get_active_species(g);\n    sort_by_degree(active_species, g);\n\n    bool found;\n    int num_inctv_chars_v, num_inctv_chars_u;\n    for (RBVertex v : active_species) {\n        found = false;\n        // for every active species v in the sorted list of active species\n        for (int i = 1; i < num_characters(g); ++i) {\n            // index \"i\" is used after to check if vertex \"u\" has \"i\" more inactive characters than \"v\"\n\n            for (RBVertex u : get_neighbors(v, g)) {\n                if (u == v || is_character(u, g)) {\n                    continue;\n                }\n                // for every species u (neighbor of v)\n\n                if (includes_species(u, v, g)) {\n                    // if u includes all the inactive species of v, then check if u has \"i\" species more than v\n                    num_inctv_chars_v =\n                        get_adj_inactive_characters(v, g).size();\n                    num_inctv_chars_u =\n                        get_adj_inactive_characters(u, g).size();\n                    if (num_inctv_chars_u == num_inctv_chars_v + i) {\n\n                        // check if the realization of v and then of u can generate any red-sigmagraphs in g\n                        RBGraph g_copy;\n                        copy_graph(g, g_copy);\n\n                        realize_species(get_vertex(g[v].name, g_copy), g_copy);\n                        realize_species(get_vertex(g[u].name, g_copy), g_copy);\n                        if (!has_red_sigmagraph(g_copy)) {\n                            out.push_back(v);\n                            found = true;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (found) {\n                break;\n            }\n        }\n        if (found && !all) {\n            break;\n        }\n    }\n    return out;\n}\n\nRBVertex get_minimal_p_active_species(const RBGraph &g) {\n    return *get_all_minimal_p_active_species(g, false).begin();\n}\n\nRBVertex get_quasi_active_species(const RBGraph &g) {\n    for (RBVertex v : g.m_vertices) {\n        if (!is_species(v, g)) {\n            continue;\n        }\n        RBOutEdgeIter e, e_end;\n        std::tie(e, e_end) = out_edges(v, g);\n        int black_edges = 0;\n        int red_edges = 0;\n        for (; e != e_end; ++e) {\n            if (is_black(*e, g)) {\n                ++black_edges;\n            } else {\n                ++red_edges;\n            }\n        }\n        // if we are here then s is a species with some red incoming edges. So, we have to check whether its realization generates a red-sigmagraph\n        if (black_edges > 0 && red_edges > 0) {\n            RBGraph g_copy;\n            copy_graph(g, g_copy);\n            realize_species(get_vertex(g[v].name, g_copy), g_copy);\n            if (!has_red_sigmagraph(g_copy)) {\n                return v;\n            }\n        }\n    }\n    return nullptr;\n}\n\nstd::list<SignedCharacter> ppp_maximal_reducible_graphs(RBGraph &g) {\n\n    std::list<SignedCharacter> realized_chars =\n        realize_red_univ_and_univ_chars(g).first;\n    remove_duplicate_species(g);\n    std::list<SignedCharacter> tmp;\n\n    while (!is_empty(g)) {\n        std::cout << \"PRINT G \" << std::endl << g << std::endl;\n        if (get_pending_species(g).size() == 1) {\n            tmp = realize_species(*get_pending_species(g).begin(), g).first;\n        } else if (get_minimal_p_active_species(g) != 0) {\n            tmp = realize_species(get_minimal_p_active_species(g), g).first;\n        } else if (is_degenerate(g)) {\n            for (RBVertex c : get_inactive_chars(g)) {\n                tmp.splice(\n                    tmp.end(),\n                    realize_character({g[c].name, State::gain}, g).first);\n            }\n        } else if (get_active_species(g).size() == 1) {\n            tmp = realize_species(*get_active_species(g).begin(), g).first;\n        } else if (get_quasi_active_species(g) != 0\n                   && all_species_with_red_edges(g)) {\n            tmp = realize_species(get_quasi_active_species(g), g).first;\n        } else {\n            if (has_red_sigmagraph(g)) {\n                std::cout << \"[INFO] Red sigma graph generated\" << std::endl;\n            }\n            throw std::runtime_error(\n                \"[ERROR] In ppp_maximal_reducible_graphs(): could not build \"\n                \"the PPP\");\n        }\n\n        realized_chars.splice(realized_chars.end(), tmp);\n        realized_chars.splice(realized_chars.end(),\n                              realize_red_univ_and_univ_chars(g).first);\n        remove_duplicate_species(g);\n\n        if (!is_empty(g)) {\n            RBGraphVector conn_compnts = connected_components(g);\n            auto cc = conn_compnts.begin();\n            auto cc_end = conn_compnts.end();\n            for (; cc != cc_end; ++cc) {\n                RBGraph tmp_graph;\n                copy_graph(*cc->get(), tmp_graph);\n                tmp = ppp_maximal_reducible_graphs(*cc->get());\n                if (logging::enabled) {\n                    std::cout << \"[INFO] iterating in conn_compt \" << std::endl;\n                }\n                for (RBVertex v : tmp_graph.m_vertices) {\n                    remove_vertex(tmp_graph[v].name, g);\n                }\n                realized_chars.splice(realized_chars.end(), tmp);\n            }\n        }\n    }\n    return realized_chars;\n}\n\nstd::pair<std::list<SignedCharacter>, bool>\nrealize_red_univ_and_univ_chars(RBGraph &g) {\n    std::list<SignedCharacter> output;\n\n    RBVertexIter v, v_end, next;\n    std::tie(v, v_end) = vertices(g);\n\n    std::list<SignedCharacter> lsc;\n    for (next = v; v != v_end; v = next) {\n        next++;\n        if (is_red_universal(*v, g)) {\n            // if v is red_universal\n            // realize v-\n            if (logging::enabled) {\n                // verbosity enabled\n                //std::cout << \"G red-universal character \" << g[*v].name << std::endl;\n            }\n            std::tie(lsc, std::ignore) =\n                realize_character({g[*v].name, State::lose}, g);\n\n            output.splice(output.cend(), lsc);\n\n            // we have to loop again from the beginning, because if some isolate node has been deleted, the for loop is compromised\n            std::tie(v, v_end) = vertices(g);\n            next = v;\n        } else if (is_universal(*v, g)) {\n            // if v is universal\n            // realize v+\n            if (logging::enabled) {\n                // verbosity enabled\n                //std::cout << \"G universal character \" << g[*v].name << std::endl;\n            }\n\n            std::list<SignedCharacter> lsc;\n\n            std::tie(lsc, std::ignore) =\n                realize_character({g[*v].name, State::gain}, g);\n\n            output.splice(output.cend(), lsc);\n\n            // we have to loop again from the beginning, because if some isolate node has been deleted, the for loop is compromised\n            std::tie(v, v_end) = vertices(g);\n            next = v;\n        }\n    }\n\n    if (!output.empty()) {\n        return std::make_pair(output, true);\n    } else {\n        return std::make_pair(output, false);\n    }\n}\n\nRBVertex get_extension(const RBVertex &s, const RBGraph &gmax,\n                       const RBGraph &gmin) {\n    if (logging::enabled) {\n        std::cout << \"[INFO] get_extension \" << std::endl;\n    }\n\n    // ******** CASE 1 ********\n    // check whether s already exists in gmin without any additional minimal characters. If it exists, then we have already found the extension of s.\n\n    // find the characters of s\n    std::set<std::string> s_chars;\n    for (RBVertex v : get_adj_vertices(s, gmax)) {\n        s_chars.insert(gmax[v].name);\n    }\n\n    for (RBVertex v : gmin.m_vertices) {\n        if (is_species(v, gmin)) {\n            std::set<std::string> v_chars;\n            for (RBVertex u : get_adj_vertices(v, gmin)) {\n                v_chars.insert(gmin[u].name);\n            }\n\n            if (v_chars == s_chars) {\n                return v;\n            }\n        }\n    }\n\n    // ******** CASE 2 ********\n    // find all the species such that (1) they include s and (2) they do not have additional maximal characters. These species will be possible candidates\n\n    std::list<RBVertex> max_chars_of_gmin = maximal_characters(gmin);\n    std::list<RBVertex> candidates;// it contains the possible candidates\n    for (RBVertex v : gmin.m_vertices) {\n        if (is_species(v, gmin)) {\n\n            // find the characters of v\n            std::set<std::string> v_chars;\n            for (RBVertex u : get_adj_vertices(v, gmin)) {\n                v_chars.insert(gmin[u].name);\n            }\n\n            // v must include s\n            if (std::includes(v_chars.begin(), v_chars.end(), s_chars.begin(),\n                              s_chars.end())) {\n                std::cout << \"includes \" << gmin[v].name << std::endl;\n\n                // v must not have more max chars than s\n                bool more_max_chars = false;\n                for (RBVertex max_char : max_chars_of_gmin) {\n                    if (!exists(gmax[s].name, gmax[max_char].name, gmax)\n                        && exists(gmin[v].name, gmin[max_char].name, gmin)) {\n                        more_max_chars = true;\n                        break;\n                    }\n                }\n\n                if (!more_max_chars) {\n                    std::cout << \"has not more max chars than s \"\n                              << gmin[v].name << std::endl;\n                    candidates.push_back(v);\n                }\n            }\n        }\n    }\n\n    // if there is only a candidate, then return it\n    if (candidates.size() == 1) {\n        return *candidates.begin();\n    }\n\n    // if we have more candidates, we have to choose the candidate X that satisfies\n    // the following property: (1) the realization of the characters of X and of\n    // all the minimal characters that overlap with the minimal characters of s\n    // must not induce a red-sigma graph and (2) X must be minimal.\n\n    // we first sort the candidate list so that (2) is satisfied\n    sort_by_degree(candidates, gmin);\n    candidates.reverse();\n    for (RBVertex candidate : candidates) {\n\n        // this list will contain the minimal characters that overlap with the ones\n        // of s. We are going to build it by first inserting all the vertices of gmin\n        // and then reducing it progressively.\n        std::set<RBVertex> overlapping_min_chars(gmin.m_vertices.begin(),\n                                                 gmin.m_vertices.end());\n        for (RBVertex u : gmin.m_vertices) {\n            if (is_species(u, gmin)) {\n                overlapping_min_chars.erase(u);\n            }\n        }\n\n        std::list<RBVertex> candidate_chars = get_adj_vertices(candidate, gmin);\n        for (RBVertex u : candidate_chars) {\n            overlapping_min_chars.erase(u);\n        }\n\n        for (RBVertex u : max_chars_of_gmin) {\n            overlapping_min_chars.erase(u);\n        }\n\n        for (RBVertex z : overlapping_min_chars) {\n            for (RBVertex u : candidate_chars) {\n                if (!overlaps_character(z, u, gmin)) {\n                    overlapping_min_chars.erase(z);\n                }\n            }\n        }\n\n        // check for the red-sigma graph\n        RBGraph g_copy;\n        copy_graph(gmin, g_copy);\n        realize_species(get_vertex(gmin[candidate].name, g_copy), g_copy);\n        for (RBVertex u : overlapping_min_chars) {\n            if (exists(gmin[u].name, g_copy)) {\n                realize_species(get_vertex(gmin[u].name, g_copy), g_copy);\n            }\n        }\n\n        if (!has_red_sigmagraph(g_copy)) {\n            std::cout << \"Candidate does not induce red sigmagraph\"\n                      << std::endl;\n            return candidate;\n        } else {\n            std::cout << \"RED sigmagraph\" << std::endl;\n        }\n    }\n\n    return 0;// return null\n}\n\nstd::list<RBVertex> get_sources(const RBGraph &gm) {\n    std::list<RBVertex> sources = get_all_minimal_p_active_species(gm, true);\n    if (sources.empty()) {\n        std::list<RBVertex> pending_species = get_pending_species(gm);\n        if (pending_species.size() == 1) {\n            sources.push_back(*pending_species.begin());\n        }\n    }\n    return sources;\n}\n\nbool is_2_solvable(std::list<RBVertex> &sources, const RBGraph &gm) {\n    if (sources.size() == 1) {\n        if (logging::enabled) {\n            std::cout << \" [INFO] mono_solvable \" << std::endl;\n        }\n        return true;\n    } else if (sources.size() != 2) {\n        return false;\n    } else {\n        RBVertex source1 = *sources.begin();\n        RBVertex source2 = *++sources.begin();\n        if (get_adj_vertices(source1, gm).size() < 2\n            || get_adj_vertices(source2, gm).size() < 2) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool is_3_canonical(std::list<RBVertex> &sources, const RBGraph &gm) {\n    if (sources.size() != 3) {\n        return false;\n    }\n    RBVertex source1 = *sources.begin();\n    RBVertex source2 = *++sources.begin();\n    RBVertex source3 = *++++sources.begin();\n\n    if (logging::enabled) {\n        std::cout << \" [TODO]: is_3_solvable semantics \" << std::endl;\n    }\n    return true;\n}\n\nbool is_m_solvable(std::list<RBVertex> &sources, const RBGraph &gm) {\n    if (sources.size() <= 3) {\n        return false;\n    }\n    //\n\n    return true;\n}\n\nstd::list<RBVertex> closure(const RBVertex &v,\n                            const RBGraph &g)//C(S) char massimali\n{\n    //CL(s) is defined as follows: a ∈ CL(s) if and only if a is minimal in G and moreover it is\n    //included in all maximal characters of s.\n\n    // get the minimal characters as follow:\n    // cmin = vertices(g) - cmax - species(g)\n\n    std::list<RBVertex> cmax = maximal_characters(g);\n    std::list<RBVertex> cmin(g.m_vertices.begin(), g.m_vertices.end());\n    RBVertexIter b = cmin.begin(), e = cmin.end(), next;\n    for (next = b; b != e; b = next) {\n        ++next;\n        if (is_species(*b, g)) {\n            cmin.remove(*b);\n        }\n        for (RBVertex u : cmax) {\n            if (g[*b].name == g[u].name) {\n                cmin.remove(*b);\n                break;\n            }\n        }\n    }\n\n    // keep just the max chars of v\n    b = cmax.begin(), e = cmax.end();\n    for (next = b; b != e; b = next) {\n        ++next;\n        if (!exists(*b, v, g)) {\n            cmax.remove(*b);\n        }\n    }\n\n    // keep just the min chars that are included in all max chars of v\n    b = cmin.begin(), e = cmin.end();\n    for (next = b; b != e; b = next) {\n        ++next;\n        for (RBVertex u : cmax) {\n            if (!includes_characters(u, *b, g)) {\n                cmin.remove(*b);\n                break;\n            }\n        }\n    }\n\n    return cmin;\n}\n\n////////////////////////////////////////////////\n//bool type_one(RBVertex &s, RBVertex &salt) {\n//    // s source and salt source alternative source\n//}\n\n// new\nbool type_one(const RBGraph &g, const RBVertex &main_source,\n              const RBVertex &other_source, const std::list<RBVertex> &closure,\n              const std::list<RBVertex> &interjection) {\n    // TODO: check type1 algorithm and resolution\n    std::list<RBVertex> ms_chars = get_comp_vertex(main_source, g);\n    std::list<RBVertex> os_chars = get_comp_vertex(other_source, g);\n    // ms_chars - max(chars) - os_chars\n    std::list<RBVertex> max_chars = maximal_characters(g);\n\n    std::list<RBVertex> a_chars(g.m_vertices.begin(), g.m_vertices.end());\n    RBVertexIter b = a_chars.begin(), e = a_chars.end(), next;\n\n    for (next = b; b != e; b = next) {\n        bool found = false;\n        ++next;\n        if (is_species(*b, g)) {\n            a_chars.remove(*b);\n            found = true;\n            break;\n        } else {\n            for (RBVertex v : os_chars) {\n                if (g[*b].name == g[v].name & !found) {\n                    a_chars.remove(*b);\n                    found = true;\n                    break;\n                }\n            }\n            for (RBVertex v : max_chars) {\n                if (g[*b].name == g[v].name & !found) {\n                    a_chars.remove(*b);\n                    found = true;\n                    break;\n                }\n            }\n        }\n\n        // for each a - begin\n\n        // leaf-species-not-in-inverted-path\n        std::list<RBVertex> leaf_species(g.m_vertices.begin(),\n                                         g.m_vertices.end());\n        RBVertexIter b_L = leaf_species.begin(), e_L = leaf_species.end(),\n                     next_L;\n        for (next_L = b_L; b_L != e_L; b_L = next_L) {\n            bool found_L = false;\n            ++next_L;\n            if (is_character(*b_L, g)) {\n                leaf_species.remove(*b_L);\n                found_L = true;\n                break;\n            } else {\n\n                std::list<RBVertex> char_set = get_comp_vertex(*b_L, g);\n                bool pass = false;\n                for (RBVertex v : interjection) {\n                    if (contains(char_set, v)) {\n                        // not pass;\n                    } else {\n                        // add sm to leaf\n                        pass = true;\n                        break;\n                    }\n                }\n                if (!pass) {\n                    leaf_species.remove(*b_L);\n                    found_L = true;\n                    break;\n                }\n            }\n        }\n\n        // Set-B\n        std::list<RBVertex> b_chars(g.m_vertices.begin(), g.m_vertices.end());\n        RBVertexIter b_B = b_chars.begin(), e_B = b_chars.end(), next_B;\n        for (next_B = b_B; b_B != e_B; b_B = next_B) {\n            bool found_B = false;\n            ++next_B;\n            if (is_species(*b_B, g)) {\n                b_chars.remove(*b_B);\n                found_B = true;\n                break;\n            } else {\n                for (RBVertex v : max_chars) {\n                    if (g[*b_B].name == g[v].name & !found_B) {\n                        b_chars.remove(*b_B);\n                        found_B = true;\n                        break;\n                    }\n                }\n\n                for (RBVertex v : closure) {\n                    if (found_B)\n                        break;\n                    if (g[*b_B].name == g[v].name & !found_B) {\n                        b_chars.remove(*b_B);\n                        found_B = true;\n                        break;\n                    }\n                }\n\n                for (RBVertex v : os_chars) {\n                    if (found_B)\n                        break;\n                    if (g[*b_B].name == g[v].name & !found_B) {\n                        b_chars.remove(*b_B);\n                        found_B = true;\n                        break;\n                    }\n                }\n\n                if (!overlaps_character(*b_B, *b, g)) {\n                    b_chars.remove(*b_B);\n                    found_B = true;\n                    break;\n                }\n            }\n            // for-each B left\n            if (!found_B) {\n                bool pass = true;\n                for (RBVertex v : leaf_species) {\n                    if (contains(get_comp_vertex(v, g), *b_B)) {\n                        // pass FALSE\n                        pass = false;\n                        break;\n                    }\n                }\n                if (pass) {\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n}\n\nbool is_linetree(const RBGraph &g) {\n    std::list<RBVertex> vertices(g.m_vertices.begin(), g.m_vertices.end());\n    RBVertexIter b = vertices.begin(), e = vertices.end(), next;\n    ulong tmp;\n    bool found = false;\n    for (next = b; b != e; b = next) {\n        ++next;\n        // TODO: replace with degree of incident EDGES\n        if (out_degree(*b, g) > 2) {\n            std::cout << \"GUARD_IS_A_SPLIT_NODE\" << std::endl;\n            std::cout << \"NODE: \" << g[*b].name << std::endl;\n            found = true;\n        }\n    }\n\n    return !found;\n}\n\nbool test_l_source(const RBVertex &s1, const RBVertex &s2,\n                   const RBGraph &g_skeleton, const RBGraph &g) {\n\n    // given s1 species, return a list of connected chars\n    // remove from s1_max_chars, minimal chars of g\n    std::list<RBVertex> tmp;\n    // prendo le componenti di s1 in g\n    std::list<RBVertex> s1_max_chars = get_comp_vertex(s1, g);\n\n    // prendo i max char di g\n    std::list<RBVertex> cmax = maximal_characters(g);\n\n    // computo i min char di g, rimuovendo le specie e rimuovendo i char maximali dall'iterator di vertici di g\n    std::list<RBVertex> cmin(g.m_vertices.begin(), g.m_vertices.end());\n    RBVertexIter b = cmin.begin(), e = cmin.end(), next;\n\n    for (next = b; b != e; b = next) {\n        ++next;\n        if (is_species(*b,\n                       g)) {// se e' specie, rimuovila\n            cmin.remove(*b);\n        }\n        for (RBVertex u : cmax) {\n            if (g[*b].name == g[u].name) {\n                cmin.remove(*b);\n                break;\n            }\n        }\n    }\n\n    // rimuovo dalle componenti di s1, i char minimali\n    b = s1_max_chars.begin(), e = s1_max_chars.end(), next;\n    for (next = b; b != e; b = next) {\n        ++next;\n        for (RBVertex u : cmin) {\n            if (g[*b].name == g[u].name) {\n                s1_max_chars.remove(*b);\n                break;\n            }\n        }\n    }// got s1_max_chars\n\n    // riga 3 algoritmo --> per ogni a in cmin\n    bool included = true;\n    for (RBVertex a : cmin) {\n        b = cmin.begin(), e = cmin.end();\n        for (next = b; b != e; b = next) {\n            ++next;\n            for (RBVertex u : s1_max_chars) {\n                if (!includes_characters(u, *b, g)) {\n                    included = false;\n                    break;\n                } else {// se ogni u *carattere di C_s ovvero di s1_max_chars* include il char a\n                    // allora computo la closure\n                    tmp = closure(s1, g);\n                    //tmp.push_back(a);// serve??? CL(s) = {a} U CL(s)\n                }\n            }\n        }\n    }\n\n    // computo s-graph : sottografo di G indotto da C_s U CL(s)\n\n    // s1_max_chars = c_s\n    // tmp = closure di s\n    //    std::list<RBVertex> closure_ext = tmp; TODO check this value\n\n    std::cout << \"GUARD_TREE GRAPH\\n\" << g << std::endl;\n\n\n    RBGraph s_graph;\n\n    //adding tmp\n    for (RBVertex v : tmp) {\n        if (!exists(g[v].name, s_graph)) {\n            add_character(g[v].name, s_graph);\n\n            RBOutEdgeIter e, e_end;\n            std::tie(e, e_end) = out_edges(v, g);\n            for (; e != e_end; ++e) {\n                if (!exists(g[e->m_target].name, s_graph)) {\n                    add_species(g[e->m_target].name, s_graph);\n                }\n                add_edge(g[v].name, g[e->m_target].name, Color::black, s_graph);\n            }\n        }\n    }\n\n    //adding s1_max_chars\n    for (RBVertex v : s1_max_chars) {\n        if (!exists(g[v].name, s_graph)) {\n            add_character(g[v].name, s_graph);\n\n            RBOutEdgeIter e, e_end;\n            std::tie(e, e_end) = out_edges(v, g);\n            for (; e != e_end; ++e) {\n                if (!exists(g[e->m_target].name, s_graph)) {\n                    add_species(g[e->m_target].name, s_graph);\n                }\n                add_edge(g[v].name, g[e->m_target].name, Color::black, s_graph);\n            }\n        }\n    }\n    std::cout << \"GUARD_TREE S_GRAPH\\n\" << s_graph << std::endl;\n\n    //interjection\n    std::list<RBVertex> s1_chars = get_adj_inactive_characters(s1, s_graph);\n    std::list<RBVertex> s2_chars = get_adj_inactive_characters(s2, s_graph);\n    std::list<RBVertex> interjection;\n\n    for (RBVertex i : s1_chars) {\n        for (RBVertex j : s2_chars) {\n            if (s_graph[j].name == s_graph[i].name) {\n                interjection.push_back(i);\n                break;\n            }\n        }\n    }\n\n    std::cout << \"GUARD_INTERJECTION\\ninterjection\" << std::endl;\n\n    for (RBVertex p : interjection) {\n        std::cout << \"(\" << s_graph[p].name << \") \";\n    }\n    std::cout << std::endl;\n\n\n    std::cout << \"\\nMAIN Source\" << std::endl;\n    for (RBVertex s : s1_chars) {\n        std::cout << \"(\" << s_graph[s].name << \") \";\n    }\n    std::cout << \"\\nOTHER Source\" << std::endl;\n    for (RBVertex s : s2_chars) {\n        std::cout << \"(\" << s_graph[s].name << \") \";\n    }\n    std::cout << std::endl;\n\n\n    // computing G_s\n    RBGraph sub_s_graph;\n\n    //se tutta l'intersezione fa parte di una specie, salvo il set di specie\n    // e prendo il sottografo con quelle\n\n    // if comp\n\n    for (RBVertex s : s_graph.m_vertices) {\n        if (is_species(s, s_graph)) {\n            std::list<RBVertex> specie_chars = get_adj_inactive_characters(s, s_graph);\n\n\n            std::cout << \"GUARD_ADJ_vertices\" << std::endl;\n            std::cout << \"\\nadjjj\" << std::endl;\n            for (RBVertex s : specie_chars) {\n                std::cout << \"(\" << s_graph[s].name << \") \";\n            }\n            std::cout << std::endl;\n\n            bool inSpecie = true;\n            for (RBVertex v : interjection) {\n                if (!containsV2(specie_chars, v, s_graph)) {\n                    std::cout << \"GUARD_SUB_CANT_ADD\\n\" << s_graph[v].name << std::endl;\n                    inSpecie = false;\n                    break;\n                }\n            }\n\n            if (inSpecie) { // keep specie in the sub_s_graph\n                if (!exists(s_graph[s].name, sub_s_graph)) {\n                    add_species(s_graph[s].name, sub_s_graph);\n                    std::cout << \"GUARD_SUB_S_GRAPH_OK\" << std::endl;\n                    RBOutEdgeIter e, e_end;\n                    std::tie(e, e_end) = out_edges(s, s_graph);\n                    for (; e != e_end; ++e) {\n                        if (!exists(s_graph[e->m_target].name, sub_s_graph)) {\n                            add_character(s_graph[e->m_target].name, sub_s_graph);\n                        }\n                        add_edge(s_graph[s].name, s_graph[e->m_target].name,\n                                 Color::black, sub_s_graph);\n                    }\n\n\n                }\n\n            }\n        }\n//        for (RBVertex v : interjection) {\n//            bool notinspecie = false;\n//\n//            if (!exists(s_graph[v].name, sub_s_graph)) {\n//                add_character(s_graph[v].name, sub_s_graph);\n//\n//                RBOutEdgeIter e, e_end;\n//                std::tie(e, e_end) = out_edges(v, s_graph);\n//                for (; e != e_end; ++e) {\n//                    if (!exists(s_graph[e->m_target].name, sub_s_graph)) {\n//                        add_species(s_graph[e->m_target].name, sub_s_graph);\n//                    }\n//                    add_edge(s_graph[v].name, s_graph[e->m_target].name,\n//                             Color::black, sub_s_graph);\n//                }\n//            }\n//        }\n    }\n    std::cout << \"GUARD_TREE SUB_S_GRAPH\\n\" << sub_s_graph << std::endl;\n\n    if (logging::enabled)\n        std::cout << \"[INFO] Reached Linetree \" << std::endl;\n\n    if (is_linetree(sub_s_graph)) {\n        std::cout << \"GUARD_LINETREE_OK\" << std::endl;\n        if (type_one(g, s1, s2, tmp, interjection)) {\n            std::cout << \"GUARD_TYPE1_NOT\" << std::endl;\n            return false;\n        } else {\n            std::cout << \"GUARD_TYPE1\" << std::endl;\n            return true;\n        }\n    } else {\n        std::cout << \"GUARD_LINETREE_NOT\" << std::endl;\n\n        return false;\n    }\n}\n\nRBVertex source_2_solvable(const std::list<RBVertex> &sources,\n                           const RBGraph &g_skeleton, const RBGraph &g_min,\n                           const RBGraph &g) {\n    RBVertex tmp = nullptr;\n\n    if (sources.size() == 1) {\n        RBVertex source = *sources.begin();\n        RBVertex extension = get_extension(source, g_skeleton, g_min);\n        std::cout << \"GUARD_B\" << std::endl;\n        //extension\n        //tmp is the s-extension to source_2_solvable\n        if (extension != nullptr && is_species(extension, g_skeleton)) {\n            std::cout << \"GUARD_B1\" << std::endl;\n            return extension;\n        }\n        std::cout << \"GUARD_B2\" << std::endl;\n\n    } else if (sources.size() == 2) {\n        if (logging::enabled)\n            std::cout << \"[INFO] 2-sources \" << std::endl;\n\n        RBVertex source1 = *sources.begin();\n        RBVertex source2 = *++sources.begin();\n        RBVertex extension1 = get_extension(source1, g_skeleton, g_min);\n        RBVertex extension2 = get_extension(source2, g_skeleton, g_min);\n\n        if (extension1 != nullptr && extension2 != nullptr\n            && is_species(extension1, g_skeleton)\n            && is_species(extension2, g_skeleton)) {\n\n            std::cout << \"GUARD_C\" << std::endl;\n\n            if (test_l_source(extension1, extension2, g_skeleton, g)) {\n                std::cout << \"GUARD_EXT1\" << std::endl;\n                tmp = extension1;\n                //                tmp.splice(tmp.end(),\n                //                           realize_species(extension1, g_skeleton).first);\n            }\n            std::cout << \"GUARD_C1\" << std::endl;\n\n            if (test_l_source(extension2, extension1, g_skeleton, g)) {\n\n                std::cout << \"GUARD_EXT2\" << std::endl;\n                tmp = extension2;\n                //                tmp.splice(tmp.end(),\n                //                           realize_species(extension2, g_skeleton).first);\n            }\n            if (tmp != nullptr) {\n                std::cout << \"GUARD_EXT_1_2_NULL\" << std::endl;\n                return tmp;\n            }\n\n            std::cout << \"GUARD_C2\" << std::endl;\n        }\n    }\n    throw std::runtime_error(\"[ERROR] In ppr_general: could not \"\n                             \"compute persistent phylogeny\");\n}\n\n#if 0\nstd::list<SignedCharacter> source_3_canonical(std::list<RBVertex> &sources,\n                                              const RBGraph &g_skeleton) {\n    if (logging::enabled) {\n        std::cout << \"[TODO] implement source_3_canonical \" << std::endl;\n    }\n}\n\n//#if 0\nstd::list<SignedCharacter> source_m_solvable(std::list<RBVertex> &sources,\n                                             const RBGraph &g_skeleton) {\n    if (logging::enabled) {\n        std::cout << \"[TODO] implement source_m_solvable  \" << std::endl;\n    }\n}\n#endif\n\nstd::list<SignedCharacter>\nppr_general(RBGraph &g) /*, std::list<SignedCharacter> a) */\n{\n    // g-skeleton computation g->g_min->max_reducible_graph\n\n    //    if (logging::enabled) std::cout << \"[PRINT] Graph print \" << g << std::endl;\n\n    // ** found that gmin->g-max-red it's the same as computing a g-skelton (making a graph from all Inactive max char plus all active chars\n\n    if (logging::enabled) {\n        std::cout << \"[INFO] Realizing chars\" << std::endl;\n    }\n    std::list<SignedCharacter> realized_chars =\n        realize_red_univ_and_univ_chars(g).first;\n    remove_duplicate_species(g);\n    std::list<SignedCharacter> tmp;\n\n    if (logging::enabled) {\n        std::cout << \"[INFO] Running PPPH iteration \" << std::endl;\n    }\n\n    while (!is_empty(g)) {\n\n        RBGraph gm;\n        RBGraph g_max;\n        RBGraph g_min;\n        std::cout << \"GUARD_PRINT_TREE\\n\" << g <<  std::endl;\n\n\n        if (logging::enabled) {\n            std::cout << \"[INFO] Computing minimal form\" << std::endl;\n        }\n        minimal_form_graph(g, g_min);\n\n        if (logging::enabled) {\n            std::cout << \"[INFO] Computing g-skeleton\" << std::endl;\n        }\n        g_skeleton(g, gm);\n        std::cout << \"GUARD_PRINT_SKELETON\\n\" << gm <<  std::endl;\n\n        if (logging::enabled) {\n            std::cout << \"[INFO] Computing max_red_graph\" << std::endl;\n        }\n        maximal_reducible_graph(g_min, g_max, true);\n\n        // need this in advance for realizing characters, do this before the main loop\n        if (logging::enabled) {\n            std::cout << \"[INFO] Getting Sources\" << std::endl;\n        }\n        std::list<RBVertex> gm_sources = get_sources(gm);\n\n        if (is_2_solvable(gm_sources, gm)) {\n\n            tmp =\n                realize_species(source_2_solvable(gm_sources, gm, g_min, g), g)\n                    .first;\n\n            if (logging::enabled) {\n                std::cout << \"[INFO] 2-solvable \" << std::endl;\n            }\n            std::cout << \"GUARD_A 2_SOLVABLE\" << std::endl;\n\n\n            //} else if (!is_2_solvable(sources_skeleton, gm)) {\n            // return result; // skip controls,\n        } else if (is_degenerate(gm)) {\n            if (logging::enabled) {\n                std::cout << \"[INFO] is-degenerate \" << std::endl;\n            }\n            //            throw std::runtime_error(\"[ERROR] In ppr_general: could not \"\n            //                                     \"compute persistent phylogeny\");\n            break;\n        } else {\n            if (logging::enabled) {\n                std::cout << \"[INFO] no-2-solv \" << std::endl;\n            }\n            break;\n            //            throw std::runtime_error(\"[ERROR] In ppr_general: could not \"\n            //                                     \"compute persistent phylogeny\");\n            // red sigmagraph??\n        }\n\n        if (!tmp.empty()) {\n            if (logging::enabled)\n                std::cout << \"[INFO] realization not empty \" << std::endl;\n\n            // realize result in G\n            //update G and A\n            // A set of characters of r (relized chars)\n\n            realized_chars.splice(realized_chars.end(), tmp);\n            realized_chars.splice(realized_chars.end(),\n                                  realize_red_univ_and_univ_chars(g).first);\n            remove_duplicate_species(g);\n            // iterates over connected components\n            if (!is_empty(g)) {\n                if (logging::enabled)\n                    std::cout << \"[INFO] Iterating conn_cmpt \" << std::endl;\n                std::cout << \"GUARD_ITERATING_COMPT\" << std::endl;\n                RBGraphVector conn_compnts = connected_components(g);\n                auto cc = conn_compnts.begin();\n                auto cc_end = conn_compnts.end();\n                for (; cc != cc_end; ++cc) {\n                    RBGraph tmp_graph;\n                    copy_graph(*cc->get(), tmp_graph);\n                    tmp = ppr_general(*cc->get());\n                    for (RBVertex v : tmp_graph.m_vertices) {\n                        remove_vertex(tmp_graph[v].name, g);\n                    }\n                    realized_chars.splice(realized_chars.end(), tmp);\n\n                    if (logging::enabled)\n                        std::cout << \"[INFO] Realized chars \";\n                    for (SignedCharacter sc : realized_chars)\n                        std::cout << \"(\" << sc << \") \";\n                    std::cout << std::endl;\n                }\n            }\n        }\n    }\n    return realized_chars;\n}\n", "meta": {"hexsha": "6af22a3f7e4b820da61817006febbaafe4baffab", "size": 41611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/functions.cpp", "max_stars_repo_name": "illoxian/persistent-phylogeny", "max_stars_repo_head_hexsha": "b9c1743ced9e410060f6dc15c1d7e4f064ccfa80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.cpp", "max_issues_repo_name": "illoxian/persistent-phylogeny", "max_issues_repo_head_hexsha": "b9c1743ced9e410060f6dc15c1d7e4f064ccfa80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions.cpp", "max_forks_repo_name": "illoxian/persistent-phylogeny", "max_forks_repo_head_hexsha": "b9c1743ced9e410060f6dc15c1d7e4f064ccfa80", "max_forks_repo_licenses": ["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.8300813008, "max_line_length": 154, "alphanum_fraction": 0.5014058783, "num_tokens": 10032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.046033900926882594, "lm_q1q2_score": 0.019274252711492933}}
{"text": "// This file currently requires 137 MB to compile (optimizing).\r\n\r\n// Copyright (c) 2003, 2004 by Jonathan Brandmeyer and others.\r\n// See the file license.txt for complete license terms.\r\n// See the file authors.txt for a complete list of contributors.\r\n\r\n#include \"util/vector.hpp\"\r\n\r\n#include <boost/python/class.hpp>\r\n#include <boost/python/def.hpp>\r\n#include <boost/python/implicit.hpp>\r\n#include <boost/python/operators.hpp>\r\n#include <boost/python/init.hpp>\r\n#include <boost/python/overloads.hpp>\r\n#include <boost/python/return_value_policy.hpp>\r\n#include <boost/python/copy_const_reference.hpp>\r\n#include <boost/python/to_python_converter.hpp>\r\n#include <boost/python/tuple.hpp>\r\n#include <boost/python/extract.hpp>\r\n#include \"python/num_util.hpp\"\r\n\r\n\r\n\r\nnamespace cvisual {\r\nnamespace py = boost::python;\r\nusing namespace cvisual::python;\r\n\r\nusing py::numeric::array;\r\nusing py::object;\r\nusing py::extract;\r\n\r\n//AS add\r\nusing py::allow_null;\r\n\r\n// Operations on Numeric arrays\r\nnamespace {\r\n\r\nvoid\r\nvalidate_array( const array& arr)\r\n{\r\n\tstd::vector<npy_intp> dims = shape(arr);\r\n\tif (type(arr) != NPY_DOUBLE) {\r\n\t\tthrow std::invalid_argument( \"Array must be of type Float64.\");\r\n\t}\r\n\tif (!iscontiguous(arr)) {\r\n\t\tthrow std::invalid_argument( \"Array must be contiguous.\"\r\n\t\t\t\"(Did you pass a slice?)\");\r\n\t}\r\n\tif (dims.size() != 2) {\r\n\t\tif (dims.size() == 1 && dims[0] == 3)\r\n\t\t\treturn;\r\n\t\telse\r\n\t\t\tthrow std::invalid_argument( \"Array must be Nx3 in shape.\");\r\n\t}\r\n\tif (dims[1] != 3) {\r\n\t\tthrow std::invalid_argument( \"Array must be Nx3 in shape.\");\r\n\t}\r\n}\r\n\r\n// Numeric doens't support the Sequence protocol, so I have to use this hack\r\n// instead.\r\n// 2008/2/16 BAS asks, \"What is the situation with numpy?\" Should look into this.\r\ninline int\r\nlength(boost::python::object seq)\r\n{\r\n\tint ret = PySequence_Size( seq.ptr());\r\n\tif (ret == -1) {\r\n\t\tboost::python::throw_error_already_set();\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n} // !namespace anonymous\r\n\r\nvector\r\ntovector( py::object arr)\r\n{\r\n\tswitch (length(arr)) {\r\n\t\tcase 2:\r\n\t\t\treturn vector(\r\n\t\t\t\textract<double>(arr[0]),\r\n\t\t\t\textract<double>(arr[1]));\r\n\t\tcase 3:\r\n\t\t\treturn vector(\r\n\t\t\t\textract<double>(arr[0]),\r\n\t\t\t\textract<double>(arr[1]),\r\n\t\t\t\textract<double>(arr[2]));\r\n\t\tdefault:\r\n\t\t\tthrow std::invalid_argument(\"Vectors must have length 2 or 3\");\r\n\t}\r\n}\r\n\r\nobject\r\nmag_a( const array& arr)\r\n{\r\n\tvalidate_array( arr);\r\n\tstd::vector<npy_intp> dims = shape(arr);\r\n\t// Magnitude of a flat 3-length array\r\n\tif (dims.size() == 1 && dims[0] == 3) {\r\n\t\treturn object( vector(\r\n\t\t\textract<double>(arr[0]),\r\n\t\t\textract<double>(arr[1]),\r\n\t\t\textract<double>(arr[2])).mag());\r\n\t}\r\n\tstd::vector<npy_intp> rdims(1);\r\n\trdims[0] = dims[0];\r\n\tarray ret = makeNum( rdims);\r\n\tfor (int i = 0; i< rdims[0]; ++i) {\r\n\t\tret[i] = tovector(arr[i]).mag();\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nobject\r\nmag2_a( const array& arr)\r\n{\r\n\tvalidate_array( arr);\r\n\tstd::vector<npy_intp> dims = shape(arr);\r\n\tif (dims.size() == 1 && dims[0] == 3) {\r\n\t\t// Returns an object of type float.\r\n\t\treturn object( vector(\r\n\t\t\textract<double>(arr[0]),\r\n\t\t\textract<double>(arr[1]),\r\n\t\t\textract<double>(arr[2])).mag2());\r\n\t}\r\n\tstd::vector<npy_intp> rdims(1);\r\n\trdims[0] = dims[0];\r\n\tarray ret = makeNum( rdims);\r\n\tfor (int i = 0; i < rdims[0]; ++i) {\r\n\t\tret[i] = tovector(arr[i]).mag2();\r\n\t}\r\n\t// Returns an object of type Numeric.array.\r\n\treturn ret;\r\n}\r\n\r\nobject\r\nnorm_a( const array& arr)\r\n{\r\n\tvalidate_array( arr);\r\n\tstd::vector<npy_intp> dims = shape(arr);\r\n\tif (dims.size() == 1 && dims[0] == 3) {\r\n\t\t// Returns a float\r\n\t\treturn object( vector(\r\n\t\t\textract<double>(arr[0]),\r\n\t\t\textract<double>(arr[1]),\r\n\t\t\textract<double>(arr[2])).norm());\r\n\t}\r\n\tarray ret = makeNum(dims);\r\n\tfor (int i = 0; i < dims[0]; ++i) {\r\n\t\tret[i] = tovector(arr[i]).norm();\r\n\t}\r\n\t// Returns a Numeric.array\r\n\treturn ret;\r\n}\r\n\r\narray\r\ndot_a( const array& arg1, const array& arg2)\r\n{\r\n\tvalidate_array( arg1);\r\n\tvalidate_array( arg2);\r\n\tstd::vector<npy_intp> dims1 = shape(arg1);\r\n\tstd::vector<npy_intp> dims2 = shape(arg2);\r\n\tif (dims1 != dims2) {\r\n\t\tthrow std::invalid_argument( \"Array shape mismatch.\");\r\n\t}\r\n\r\n\tstd::vector<npy_intp> dims_ret(1);\r\n\tdims_ret[0] = dims1[0];\r\n\tarray ret = makeNum( dims_ret);\r\n\tconst double* arg1_i = (double*)data(arg1);\r\n\tconst double* arg2_i = (double*)data(arg2);\r\n\tfor ( int i = 0; i < dims1[0]; ++i, arg1_i +=3, arg2_i += 3) {\r\n\t\tret[i] = vector(arg1_i).dot( vector(arg2_i));\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\narray\r\ncross_a_a( const array& arg1, const array& arg2)\r\n{\r\n\tvalidate_array( arg1);\r\n\tvalidate_array( arg2);\r\n\tstd::vector<npy_intp> dims1 = shape(arg1);\r\n\tstd::vector<npy_intp> dims2 = shape(arg2);\r\n\tif (dims1 != dims2) {\r\n\t\tthrow std::invalid_argument( \"Array shape mismatch.\");\r\n\t}\r\n\r\n\tarray ret = makeNum( dims1);\r\n\tconst double* arg1_i = (double*)data(arg1);\r\n\tconst double* arg2_i = (double*)data(arg2);\r\n\tdouble* ret_i = (double*)data(ret);\r\n\tdouble* const ret_stop = ret_i + 3*dims1[0];\r\n\tfor ( ; ret_i < ret_stop; ret_i += 3, arg1_i += 3, arg2_i += 3) {\r\n\t\tvector ret = vector(arg1_i).cross( vector( arg2_i));\r\n\t\tret_i[0] = ret.get_x();\r\n\t\tret_i[1] = ret.get_y();\r\n\t\tret_i[2] = ret.get_z();\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\narray\r\ncross_a_v( const array& arg1, const vector& arg2)\r\n{\r\n\tvalidate_array( arg1);\r\n\tstd::vector<npy_intp> dims = shape( arg1);\r\n\tarray ret = makeNum( dims);\r\n\tconst double* arg1_i = (double*)data( arg1);\r\n\tdouble* ret_i = (double*)data( ret);\r\n\tdouble* const ret_stop = ret_i + 3*dims[0];\r\n\tfor ( ; ret_i < ret_stop; ret_i += 3, arg1_i += 3) {\r\n\t\tvector ret = vector( arg1_i).cross( arg2);\r\n\t\tret_i[0] = ret.get_x();\r\n\t\tret_i[1] = ret.get_y();\r\n\t\tret_i[2] = ret.get_z();\r\n\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\narray\r\ncross_v_a( const vector& arg1, const array& arg2)\r\n{\r\n\tvalidate_array( arg2);\r\n\tstd::vector<npy_intp> dims = shape( arg2);\r\n\tarray ret = makeNum( dims);\r\n\tconst double* arg2_i = (double*)data( arg2);\r\n\tdouble* ret_i = (double*)data( ret);\r\n\tdouble* const ret_stop = ret_i + 3*dims[0];\r\n\tfor ( ; ret_i < ret_stop; ret_i += 3, arg2_i += 3) {\r\n\t\tvector ret = arg1.cross( vector( arg2_i));\r\n\t\tret_i[0] = ret.get_x();\r\n\t\tret_i[1] = ret.get_y();\r\n\t\tret_i[2] = ret.get_z();\r\n\r\n\t}\r\n\treturn ret;\r\n\r\n}\r\n\r\n\r\n\r\n\r\nnamespace {\r\nusing namespace boost::python;\r\nBOOST_PYTHON_FUNCTION_OVERLOADS( free_rotate, rotate, 2, 3 )\r\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( vector_rotate, vector::rotate, 1, 2)\r\n} // !namespace anonymous\r\n\r\nstruct vector_from_seq\r\n{\r\n\tvector_from_seq()\r\n\t{\r\n\t\tpy::converter::registry::push_back(\r\n\t\t\t&convertible,\r\n\t\t\t&construct,\r\n\t\t\tpy::type_id<vector>());\r\n\t}\r\n\r\n\tstatic void* convertible( PyObject* obj)\r\n\t{\r\n\t\tusing py::handle;\r\n\t\tusing py::allow_null;\r\n\r\n\t\tobject o( handle<>( borrowed(obj) ) );\r\n\r\n\t\tint obj_size = PyObject_Length(obj);\r\n\t\tif (obj_size < 0) {\r\n\t\t\tPyErr_Clear();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tif (obj_size != 2 && obj_size != 3)\r\n\t\t\treturn 0;\r\n\t\tfor(int i=0; i<obj_size; i++)\r\n\t\t\tif (!py::extract<double>(o[i]).check())\r\n\t\t\t\treturn 0;\r\n\t\treturn obj;\r\n\t}\r\n\r\n\tstatic void construct(\r\n\t\tPyObject* _obj,\r\n\t\tpy::converter::rvalue_from_python_stage1_data* data)\r\n\t{\r\n\t\tusing namespace boost::python;\r\n\r\n\t\tobject obj = object(handle<>(borrowed(_obj)));\r\n\t\tvoid* storage = (\r\n\t\t\t(boost::python::converter::rvalue_from_python_storage<vector>*)\r\n\t\t\tdata)->storage.bytes;\r\n\t\tint obj_size = PyObject_Length(_obj);\r\n\t\tswitch (obj_size) {\r\n\t\t\tcase 1:\r\n\t\t\t\tnew (storage) vector( py::extract<double>(obj[0]));\r\n\t\t\t\tbreak;\r\n\t\t\tcase 2:\r\n\t\t\t\tnew (storage) vector(\r\n\t\t\t\t\tpy::extract<double>( obj[0]),\r\n\t\t\t\t\tpy::extract<double>( obj[1]));\r\n\t\t\t\t\tbreak;\r\n\t\t\tcase 3: default:\r\n\t\t\t\t// Will probably trigger an exception if it is the default\r\n\t\t\t\t// case.\r\n\t\t\t\tnew (storage) vector(\r\n\t\t\t\t\tpy::extract<double>( obj[0]),\r\n\t\t\t\t\tpy::extract<double>( obj[1]),\r\n\t\t\t\t\tpy::extract<double>( obj[2]));\r\n\t\t}\r\n\t\tdata->convertible = storage;\r\n\t}\r\n};\r\n\r\npy::tuple\r\nvector_as_tuple( const vector& v)\r\n{\r\n\treturn py::make_tuple( v.x, v.y, v.z);\r\n}\r\n\r\nvector\r\nvector_pos( const vector& v)\r\n{\r\n\treturn v;\r\n}\r\n\r\n\r\nvoid\r\nwrap_vector()\r\n{\r\n\t// Numeric versions for some of the above\r\n\t// TODO: round out the set.\r\n\tdef( \"mag\", mag_a);\r\n\tdef( \"dot\", dot_a);\r\n\tdef( \"cross\", cross_a_a);\r\n\tdef( \"cross\", cross_a_v);\r\n\tdef( \"cross\", cross_v_a);\r\n\tdef( \"mag2\", mag2_a);\r\n\tdef( \"norm\", norm_a);\r\n\r\n\t// Free functions for vectors\r\n\t// The following two functions have never been implemented:\r\n\t//py::def( \"det3\",a_dot_b_cross_c, \"The determinant of the matrix of 3 vectors.\");\r\n\t//py::def( \"cross3\",a_cross_b_cross_c, \"The vector triple product.\");\r\n\tpy::def( \"dot\", dot, \"The dot product between two vectors.\");\r\n\tpy::def( \"cross\", cross, \"The cross product between two vectors.\");\r\n\tpy::def( \"mag\", mag, \"The magnitude of a vector.\");\r\n\tpy::def( \"mag2\", mag2, \"A vector's magnitude squared.\");\r\n\tpy::def( \"norm\", norm, \"Returns the unit vector of its argument.\");\r\n\tpy::def( \"comp\", comp, \"The scalar projection of arg1 to arg2.\");\r\n\tpy::def( \"proj\", proj, \"The vector projection of arg1 to arg2.\");\r\n\tpy::def( \"diff_angle\", diff_angle, \"The angle between two vectors, in radians.\");\r\n\tpy::def( \"rotate\", rotate, free_rotate( args(\"vector\", \"angle\", \"axis\"),\r\n\t\t\"Rotate a vector about an axis vector through an angle.\") );\r\n\r\n\t//AS added throw()\r\n\r\n\tvector (vector::* truediv)( double) const throw()= &vector::operator/;\r\n\tconst vector& (vector::* itruediv)( double) throw() = &vector::operator/=;\r\n\r\n\t// The vector class, constructable from 0, one, two or three doubles.\r\n\tpy::class_<vector>(\"vector\", py::init< py::optional<double, double, double> >())\r\n\t\t// Explicit copy.\r\n\t\t.def( init<vector>())\r\n\t\t// member variables.\r\n\t\t.add_property( \"x\", &vector::get_x, &vector::set_x)\r\n\t\t.add_property( \"y\", &vector::get_y, &vector::set_y)\r\n\t\t.add_property( \"z\", &vector::get_z, &vector::set_z)\r\n\t\t// Member functions masquerading as properties.\r\n\t\t.add_property( \"mag\", &vector::mag, &vector::set_mag)\r\n\t\t.add_property( \"mag2\", &vector::mag2, &vector::set_mag2)\r\n\t\t// Member functions\r\n\t\t.def( \"dot\", &vector::dot, \"The dot product of this vector and another.\")\r\n\t\t.def( \"cross\", &vector::cross, \"The cross product of this vector and another.\")\r\n\t\t.def( \"norm\", &vector::norm, \"The unit vector of this vector.\")\r\n\t\t.def( \"comp\", &vector::comp, \"The scalar projection of this vector onto another.\")\r\n\t\t.def( \"proj\", &vector::proj, \"The vector projection of this vector onto another.\")\r\n\t\t.def( \"diff_angle\", &vector::diff_angle, \"The angle between this vector \"\r\n\t\t\t\"and another, in radians.\")\r\n\t\t.def( \"clear\", &vector::clear, \"Zero the state of this vector.  Potentially \"\r\n\t\t\t\"useful for reusing a temporary variable.\")\r\n\t\t.def( \"rotate\", &vector::rotate, vector_rotate( \"Rotate this vector about \"\r\n\t\t\t\"the specified axis through the specified angle, in radians\",\r\n\t\t\targs( \"angle\", \"axis\")))\r\n\t\t.def( \"__abs__\", &vector::mag, \"Return the magnitude of this vector.\")\r\n\t\t.def( \"__pos__\", vector_pos, \"Return an unmodified copy of this vector.\")\r\n\t\t// Some support for the sequence protocol.\r\n\t\t.def( \"__len__\", &vector::py_len)\r\n\t\t.def( \"__getitem__\", &vector::py_getitem)\r\n\t\t.def( \"__setitem__\", &vector::py_setitem)\r\n\t\t// Use this to quickly convert vector's to tuples.\r\n\t\t.def( \"astuple\", vector_as_tuple, \"Convert this vector to a tuple.  \"\r\n\t\t\t\"Same as tuple(vector), but much faster.\")\r\n\t\t// Member operators\r\n\t\t.def( -self)\r\n\t\t.def( self + self)\r\n\t\t.def( self += self)\r\n\t\t.def( self - self)\r\n\t\t.def( self -= self)\r\n\t\t.def( self * double())\r\n\t\t.def( self *= double())\r\n\t\t.def( self / double())\r\n\t\t.def( self /= double())\r\n\t\t.def( double() * self)\r\n\t\t.def( self == self )\r\n\t\t.def( self != self )\r\n\r\n\t\t// This doesn't work either (NPY_FLOAT not recognized as a type):\r\n\t\t//.def( other<NPY_FLOAT>() * self)\r\n\r\n\t\t// Suggestion from Jonathan Brandmeyer, which doesn't compile:\r\n\t\t//.def( \"__mul__\", &vector::operator*(double), \"Multiply vector times scalar\")\r\n\t\t//.def( \"__rmul__\", &operator*(const double&, const vector&), \"Multiply scalar times vector\")\r\n\r\n\t\t// Same as self / double, when \"from __future__ import division\" is in effect.\r\n\t\t.def( \"__itruediv__\", itruediv, return_value_policy<copy_const_reference>())\r\n\t\t// Same as self /= double, when \"from __future__ import division\" is in effect.\r\n\t\t.def( \"__truediv__\",  truediv)\r\n    \t.def( self_ns::str(self))        // Support \">>> print foo\"\r\n\t\t.def( \"__repr__\", &vector::repr) // Support \">>> foo\"\r\n\t\t;\r\n\r\n\t// Pass a sequence to some functions that expect type visual::vector.\r\n\tvector_from_seq();\r\n}\r\n\r\n} // !namespace cvisual\r\n", "meta": {"hexsha": "a4d90c259e556873aaa41b9a24479e8c2e4d019d", "size": 12403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/wrap_vector.cpp", "max_stars_repo_name": "lebarsfa/vpython-wx", "max_stars_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 68.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T05:41:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:35:24.000Z", "max_issues_repo_path": "src/python/wrap_vector.cpp", "max_issues_repo_name": "lebarsfa/vpython-wx", "max_issues_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-09T21:01:25.000Z", "max_forks_repo_path": "src/python/wrap_vector.cpp", "max_forks_repo_name": "lebarsfa/vpython-wx", "max_forks_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2015-02-04T04:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T03:24:41.000Z", "avg_line_length": 29.1150234742, "max_line_length": 96, "alphanum_fraction": 0.6346851568, "num_tokens": 3655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.046033899127334243, "lm_q1q2_score": 0.01927425129020629}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2014 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_TRSOLVE_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_GENERAL_TRSOLVE_HPP_INCLUDED\n\n#include <nt2/linalg/functions/trsolve.hpp>\n#include <nt2/core/functions/transpose.hpp>\n#include <nt2/core/functions/ctranspose.hpp>\n#include <nt2/include/functions/trsm.hpp>\n#include <nt2/include/functions/mtimes.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/core/container/dsl/size.hpp>\n#include <nt2/core/container/dsl/alias.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n#include <nt2/core/settings/locality.hpp>\n#include <nt2/sdk/memory/forward/container.hpp>\n#include <boost/dispatch/meta/terminal_of.hpp>\n#include <nt2/sdk/memory/category.hpp>\n#include <nt2/sdk/meta/as_real.hpp>\n#include <nt2/sdk/meta/size_as.hpp>\n#include <nt2/sdk/meta/value_as.hpp>\n#include <boost/proto/traits.hpp>\n#include <boost/assert.hpp>\n\nnamespace nt2 { namespace tag\n{\n  struct side\n  {\n    BOOST_FORCEINLINE static char call()\n    {\n      return 'L';\n    }\n  };\n\n  struct diag\n  {\n    BOOST_FORCEINLINE static char call()\n    {\n      return 'N';\n    }\n  };\n\n} }\n\nnamespace nt2 { namespace ext\n{\n  template<class Domain, int N, class Expr>\n  struct  size_of<tag::trsolve_,Domain,N,Expr>\n        : meta::size_as<Expr,1>\n  {};\n\n\n  template<class Domain, int N, class Expr>\n  struct  value_type<tag::trsolve_,Domain,N,Expr>\n        : meta::value_as<Expr,1>\n  {};\n\n} }\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                            )\n  {\n    typedef typename meta::option<typename A0::settings_type,nt2::tag::shape_>::type shape;\n    typedef typename A0::value_type T;\n    BOOST_DISPATCH_RETURNS(2, (A0 const& a0, A1 const& a1),\n      trsolve(a0, a1, One<T>(), tag::blas_normal_(), shape::id_value , tag::side(), tag::diag() )\n    )\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)\n                            , ((node_< A0, nt2::tag::transpose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                            )\n  {\n    typedef typename boost::proto::result_of::child_c<A0&,0>::type    child0;\n    typedef typename boost::dispatch::meta::terminal_of<typename boost::dispatch::meta::\n                     semantic_of<child0>::type>::type                in0_t;\n    typedef typename meta::option<typename in0_t::settings_type,nt2::tag::shape_>::type shape;\n    typedef typename A0::value_type T;\n    BOOST_DISPATCH_RETURNS(2, (A0 const& a0, A1 const& a1),\n      trsolve(boost::proto::child_c<0>(a0), a1, One<T>(), tag::blas_transpose_(), shape::id_value, tag::side(), tag::diag() )\n    )\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)\n                            , ((node_< A0, nt2::tag::ctranspose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                            )\n  {\n    typedef typename boost::proto::result_of::child_c<A0&,0>::type    child0;\n    typedef typename boost::dispatch::meta::terminal_of<typename boost::dispatch::meta::\n                     semantic_of<child0>::type>::type                in0_t;\n    typedef typename meta::option<typename in0_t::settings_type,nt2::tag::shape_>::type shape;\n    typedef typename A0::value_type T;\n    BOOST_DISPATCH_RETURNS(2, (A0 const& a0, A1 const& a1),\n      trsolve(boost::proto::child_c<0>(a0), a1, One<T>(), tag::blas_ctranspose_(), shape::id_value, tag::side(), tag::diag() )\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                            )\n  {\n    typedef typename meta::option<typename A0::settings_type,nt2::tag::shape_>::type shape;\n    typedef typename A0::value_type T;\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      trsolve(a0, a1, a2, tag::blas_normal_(), shape::id_value, tag::side(), tag::diag() )\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((node_< A0, nt2::tag::transpose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                            )\n  {\n    typedef typename boost::proto::result_of::child_c<A0&,0>::type    child0;\n    typedef typename boost::dispatch::meta::terminal_of<typename boost::dispatch::meta::\n                     semantic_of<child0>::type>::type                in0_t;\n    typedef typename meta::option<typename in0_t::settings_type,nt2::tag::shape_>::type shape;\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      trsolve(boost::proto::child_c<0>(a0), a1, a2, tag::blas_transpose_(), shape::id_value, tag::side(), tag::diag() )\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((node_< A0, nt2::tag::ctranspose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                            )\n  {\n    typedef typename boost::proto::result_of::child_c<A0&,0>::type    child0;\n    typedef typename boost::dispatch::meta::terminal_of<typename boost::dispatch::meta::\n                     semantic_of<child0>::type>::type                in0_t;\n    typedef typename meta::option<typename in0_t::settings_type,nt2::tag::shape_>::type shape;\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      trsolve(boost::proto::child_c<0>(a0), a1, a2, tag::blas_ctranspose_(), shape::id_value, tag::side(), tag::diag() )\n    )\n  };\n\n  // no shape for input matrix so add it as a parameter\n\n    BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< ints8_<A2> >)\n                            )\n  {\n    typedef typename meta::option<typename A0::settings_type,nt2::tag::shape_>::type shape;\n    typedef typename A0::value_type T;\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      trsolve(a0, a1, One<T>(), tag::blas_normal_(), a2 , tag::side(), tag::diag() )\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((node_< A0, nt2::tag::transpose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< ints8_<A2> >)\n                            )\n  {\n    typedef typename A0::value_type T;\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      trsolve(boost::proto::child_c<0>(a0), a1, One<T>(), tag::blas_transpose_(), a2 , tag::side(), tag::diag() )\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((node_< A0, nt2::tag::ctranspose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< ints8_<A2> >)\n                            )\n  {\n    typedef typename A0::value_type T;\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      trsolve(boost::proto::child_c<0>(a0), a1, One<T>(), tag::blas_ctranspose_(), a2 , tag::side(), tag::diag() )\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( trsolve_, tag::cpu_\n                            , (A0)(A1)(A2)(A3)(A4)(A5)(A6)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                              (unspecified_<A3>)\n                              (unspecified_<A4>)\n                              (unspecified_<A5>)\n                              (unspecified_<A6>)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS(7, (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4,A5 const& a5,A6 const& a6),\n                                 (boost::proto:: make_expr<nt2::tag::trsolve_, container::domain>\n                                    (boost::cref(a0), boost::cref(a1), boost::cref(a2), boost::cref(a3), boost::cref(a4), boost::cref(a5), boost::cref(a6))\n                                 )\n    )\n  };\n\n  // run_assign\n  BOOST_DISPATCH_IMPLEMENT  ( run_assign_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((node_< A1, nt2::tag::trsolve_, boost::mpl::long_<7> , nt2::container::domain>))\n                            )\n  {\n    typedef A0& result_type;\n    typedef typename A1::proto_child1::proto_child0::value_type T;\n    typedef typename meta::option<typename A1::proto_child1::proto_child0::settings_type\n                                 ,nt2::tag::shape_\n                                 >::type shape;\n\n    typedef typename meta::option<typename A1::proto_child1::proto_child0::settings_type\n                                 ,tag::locality_\n                                 ,typename  A1::proto_child1::proto_child0::kind_type\n                                  >::type  locality_in;\n\n    typedef typename meta::option<typename A0::settings_type\n                                 ,tag::locality_\n                                 ,typename A0::kind_type\n                                  >::type  locality_out;\n\n    typedef nt2::memory::container<tag::table_, T, nt2::settings(nt2::_2D,locality_in )> desired_semantic;\n    typedef nt2::memory::container<tag::table_, T, nt2::settings(nt2::_2D,shape,locality_out)> desired_semantic1;\n\n    result_type operator()(A0& a0, A1& a1) const\n    {\n      char side  =  boost::proto::value(boost::proto::child_c<5>(a1)).call();\n      char diag  =  boost::proto::value(boost::proto::child_c<6>(a1)).call();\n      char trans =  boost::proto::value(boost::proto::child_c<3>(a1)).call();\n      char uplo  = boost::proto::value(boost::proto::child_c<4>(a1));\n      T alpha    = boost::proto::value(boost::proto::child_c<2>(a1));\n\n      NT2_AS_TERMINAL_INOUT(desired_semantic1,result,boost::proto::child_c<1>(a1),a0);\n      NT2_AS_TERMINAL_IN(desired_semantic,in,boost::proto::child_c<0>(a1));\n\n      nt2::trsm(side, uplo, trans, diag, boost::proto::value(in)\n                                       , boost::proto::value(result) , alpha );\n\n      assign_swap(a0, result);\n\n      return a0;\n    }\n  };\n}\n}\n\n#endif\n", "meta": {"hexsha": "f58d197db4e78a73fc66b7b86b62b7c0bf49c530", "size": 11776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/general/trsolve.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/trsolve.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/trsolve.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": 43.2941176471, "max_line_length": 155, "alphanum_fraction": 0.5405061141, "num_tokens": 3095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.04401864845207065, "lm_q1q2_score": 0.019272398691563518}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Filename    : config.cpp                                                                            *\n * Project     : Planewalker - Schnorr-Euchner sphere decoder simulation for space-time lattice codes  *\n * Authors     : Pasi Pyrrö, Oliver Gnilke                                                             *\n * Version     : 1.0                                                                                   *\n * Copyright   : Aalto University ~ School of Science ~ Department of Mathematics and Systems Analysis *\n * Date        : 17.8.2017                                                                             *\n * Language    : C++ (2011 or newer standard)                                                          *\n * Description : Implements functions for handling user input and simulation configuration             *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#define ARMA_NO_DEBUG /* disable Armadillo bound checks for addiotional speed */\n\n#include <iostream>\n#include <armadillo> /* linear algebra library */\n#include <complex>\n#include <algorithm>\n#include <vector>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <regex>\n\n#include \"config.hpp\"\n#include \"misc.hpp\"\n\n#define NUM_OPTIONS 22\n\nusing namespace std;\nusing namespace arma;\n\n/* Creates a default configuration file in case one does not exist */\nvoid create_config(){\n    ofstream defconf(filenames[\"settings_default\"]);\n    // the file can contain comments similar to this line here\n    defconf << \"// configuration settings and simulation parameters for the sphere decoder program\" << endl << endl;\n    defconf << \"basis_file=bases.txt            // Text file containing the basis matrices\" << endl;\n    defconf << \"coset_file=                     // Optionally specify the coset encoding sublattice basis matrix file\" << endl;\n    defconf << \"output_file=                    // Optionally specify the output filename\" << endl;\n    defconf << \"error_file=                     // Optionally specify the file containing error requirements for the SNR simulations\" << endl;\n    defconf << \"channel_model=mimo              // Define the channel model for the simulation (either 'mimo' or 'siso')\" << endl;\n    defconf << \"x-PAM=4                         // The size of the PAM signaling set (even positive integer)\" << endl;\n    defconf << \"energy_estimation_samples=-1    // Number of samples to make the code energy estimation (-1 = sample all)\" << endl;\n    defconf << \"no_of_matrices=2                // Number of basis matrices (dimension of the data vectors)\" << endl;\n    defconf << \"matrix_coefficient=1.0          // Multiply all basis matrices by this constant\" << endl;\n    defconf << \"time_slots=2                    // Number of time slots used in the code\" << endl;\n    defconf << \"no_of_transmit_antennas=2       // Number of transmit antennas\" << endl;\n    defconf << \"no_of_receiver_antennas=2       // Number of receiver antennas\"  << endl;\n    defconf << \"snr_min=6                       // Minimum value for signal-to-noise ratio\" << endl;\n    defconf << \"snr_max=12                      // Maximum value for signal-to-noise ratio\" << endl;\n    defconf << \"snr_step=2                      // Increase SNR by this value per each iteration\" << endl;\n    defconf << \"simulation_rounds=100000        // Number of simulation rounds to run\" << endl;\n    defconf << \"required_errors=500             // Demand at minimum this many errors before the simulation ends\" << endl;\n    defconf << \"plot_results=-1                 // Draw plots? (1 = yes, -1 = no)\" << endl;\n    defconf << \"stat_display_interval=-1        // Defines after each how many rounds to display the current simulation stats (-1 = disabled)\" << endl;\n    defconf << \"spherical_shaping_max_power=-1  // Defines the maximum distance from origin for codebook elements (-1 = unbounded)\" << endl;\n    defconf << \"codebook_size_exponent=-1       // The codebook will have 2^s codewords where s is this parameter (overrides above parameter)\" << endl;\n    defconf << \"radius_search_density=-1        // Defines how accurate the codebook squared radius estimation will be\" << endl;\n    defconf.close(); \n}\n\n/* Read simulation parameters from a settings file */\nvoid configure() {\n    string filepath = filenames[\"settings\"];\n    string default_filepath = filenames[\"settings_default\"];\n\n    ifstream config_file(filepath);\n\n    if (!config_file.good() && filepath.compare(default_filepath) != 0) {\n        log_msg(\"No settings file '\" + filepath + \"' found, using the default one...\", \"Alert\");\n        config_file = ifstream(default_filepath);\n    } \n\n    if (!config_file.good()) {\n        log_msg(\"No default settings file found, creating a new one with default settings...\");\n        create_config();\n        log_msg(\"Make your changes to the settings file and rerun this program.\");\n        log_msg(\"Exiting...\");\n        exit(0);\n    }\n\n    /* List special (not integer) parameter names that should be handled differently */\n    vector<string> sparam_names = {\"channel_model\"};\n    vector<string> dparam_names = {\"spherical_shaping_max_power\", \"matrix_coefficient\"};\n    vector<string> accept_empty_names = {\"output_file\", \"error_file\", \"coset_file\"};\n    \n    string line;\n    char *endptr; /* used for parsing error checking */\n    int lines = 0;\n    while (getline(config_file, line))\n    {\n        istringstream iss(line);\n        string key;\n        if(getline(iss, key, '=') )\n        {\n            if (key.find(\"//\", 0) != string::npos)\n                continue;\n            lines++;\n            // cout << lines << endl;\n            string value;\n            getline(iss, value);\n            clean_input(value); \n            if (!value.empty()) { /* Valid key-value pair found */\n                /* kinda messy checking but works */\n                if (key.compare(\"basis_file\") == 0) { \n                    filenames[\"bases\"] = \"bases/\" + value;\n                } else if (key.compare(\"coset_file\") == 0) {\n                    filenames[\"cosets\"] = \"bases/\" + value;\n                } else if (key.compare(\"output_file\") == 0) {\n                    filenames[\"output\"] = \"output/\" + value;\n                } else if (key.compare(\"error_file\") == 0) {\n                    filenames[\"error\"] = \"settings/\" + value;\n                } else if (find(dparam_names.begin(), dparam_names.end(), key) != dparam_names.end()) {\n                    dparams[key] = strtod(value.c_str(), &endptr);\n                    if (*endptr != 0) {\n                        log_msg(\"Invalid value for option '\" + key + \"'\", \"Error\");\n                        exit(1);\n                    }\n                } else if (find(sparam_names.begin(), sparam_names.end(), key) != sparam_names.end()) {\n                    sparams[key] = value;\n                } else {\n                    params[key] = strtol(value.c_str(), &endptr, 10); \n                    if (*endptr != 0) {\n                        log_msg(\"Invalid value for option '\" + key + \"'\", \"Error\");\n                        exit(1);\n                    }\n                }\n            } else if (find(accept_empty_names.begin(), accept_empty_names.end(), key) == accept_empty_names.end()){\n                log_msg(\"[Error] Value for option '\" + key + \"' not spesified!\");\n                exit(1);\n            }\n        }\n    }\n    if (lines < NUM_OPTIONS){\n        log_msg(\"Too few options spesified in the '\" + filepath + \"'!\", \"Error\");\n        log_msg(\"Consider deleting the default settings file which will reset the program settings.\");\n        exit(1);\n    } \n    if ((params[\"x-PAM\"] <= 0) || (params[\"x-PAM\"] % 2 == 1)){\n        log_msg(\"Invalid x-PAM signal set spesified!\", \"Error\");\n        log_msg(\"x-PAM option accepts positive even integers.\");\n        exit(1);\n    }\n\n    // helper variable (size of the codebook) calculated from the input parameters\n    dparams[\"codebook_size\"] = pow(params[\"x-PAM\"], params[\"no_of_matrices\"]);\n}\n\n/* reads k (m x t) matrices from the spesified basis_file */\nvector<cx_mat> read_matrices(const string &filepath){\n\n    /* - uses regular expression pattern to search \n     *   matrix elements in almost any known format (eg. Mathematica, Matlab (with commas))\n     * - ignores most white spaces and supports asterisk in front of 'I'\n     * - pattern is also case insensitive\n     * - Caveats: elements can't be separated by spaces alone like in Matlab, \n     *            only one sign (x/-) is to be inserted between real and imag part of a complex number\n     */\n\n    /* Some supported formats for the matrix elements:\n     * 1) \"re ,\"\n     * 2) \"re + im *I,\"\n     * 3) \"re - im *I,\"\n     * 4) \"im *I,\" \n     */\n\n    /* The regex pattern */\n    regex elem_regex(\n        \"(\"                                                                                      // three basic types for matrix element\n            \"([+-]?\\\\s*[^\\\\d\\\\.]+[Ii]{1})\"                                                       // 1. plain letter 'i' with sign\n            \"|\" \n            \"(([+-]?\\\\s*\\\\d*\\\\.?\\\\d+|[+-]?\\\\s*\\\\d+\\\\.?\\\\d*)\\\\s*\\\\*?[Ii]?)\"                       // 2. pure real or complex number\n            \"|\"\n             \"([+-]?\\\\s*\\\\d*\\\\.?\\\\d+|[+-]?\\\\s*\\\\d+\\\\.?\\\\d*)\"                                     // 3. both real part\n            \"\\\\s*\"                                                                               \n            \"(([+-]?\\\\s*\\\\d*\\\\.?\\\\d+|[+-]?\\\\s*\\\\d+\\\\.?\\\\d*|[+-]?\\\\s*[^\\\\d\\\\.]+)\\\\s*\\\\*?[Ii]{1})\" // and imaginary part\n        \")\" \n        \"\\\\s*[,)};\\\\]\\n]{1}\"       // element ends in comma, semicolon, newline or closing bracket (WHITE SPACE SEPARATION NOT SUPPORTED)\n    );\n\n    int m = params[\"no_of_transmit_antennas\"];\n    int t = params[\"time_slots\"];\n    int k = params[\"no_of_matrices\"];\n    int idx = 0;\n\n    ifstream matrix_file(filepath);\n    vector<cx_mat> output;\n    smatch match; /* regex match object, contains capture groups */\n    vector< complex<double> > numbers; /* store the parsed elements in here */\n    \n    string content((istreambuf_iterator<char>(matrix_file)), \n        istreambuf_iterator<char>());\n\n    /* capture group substrings */\n    string  m2,  // plain i\n            m3,  // real or pure complex number\n            m5,  // real part\n            m6,  // imaginary part with i\n            m7;  // imaginary part without i\n    \n    /* Search the configured basis_file for basis matrix elements */\n    while(regex_search(content, match, elem_regex)){\n\n        /***** print all capture groups for debugging! *****/\n        // for (auto i = 0u; i < match.size(); ++i)\n        //     cout << i << \": \" << match[i].str() << endl;\n        // cout << endl;\n\n        /* assign and clean the helper substrings */\n        m2 = match[2].str();\n        m3 = match[3].str();\n        m5 = match[5].str();\n        m6 = match[6].str();\n        m7 = match[7].str();\n\n        clean_input(m2);\n        clean_input(m3);\n        clean_input(m5);\n        clean_input(m6);\n        clean_input(m7);\n\n        /* both real and imaginary part are present */\n        if (!m5.empty() && !m6.empty()) {\n            if (isdigit(m7.back()) || (m7.back() == '.')) \n                numbers.push_back(complex<double>(stod(m5), stod(m7)));\n            else { /* imag element is of type +-i */\n                numbers.push_back(complex<double>(stod(m5), stod(m7 + string(\"1.0\"))));\n            }\n        } \n        /* plain +-i element found */\n        else if (!m2.empty()) {\n            remove_from_string(m2, 'i');\n            remove_from_string(m2, 'I');\n            numbers.push_back(complex<double>(0.0, stod(m2 + string(\"1.0\"))));\n        }\n        /* pure real or imag element found */\n        else {\n            if (isdigit(m3.back()) || (m3.back() == '.')) {\n                numbers.push_back(complex<double>(stod(m3), 0.0)); \n            } else {\n                numbers.push_back(complex<double>(0.0, stod(m3)));\n            }\n        }\n        /* iterate the content, i.e. remove the part of the string we examined already */\n        content = match.suffix().str();\n        idx++;\n    }\n\n    /* Sanity check */\n    if (m*t*k != (int)numbers.size()){\n        log_msg(\"Failed to read the \" + to_string(m*t*k) + \" matrix elements (found \" + to_string(numbers.size()) + \\\n            \") configured in '\" + filepath + \"'!\", \"Error\");\n        exit(1);\n    }\n\n    /* store the read matrix elements in a complex matrix datatype from Armadillo library */\n    idx = 0;\n    cx_mat X(m, t);\n    for (int i = 0; i < k; i++){    \n        for (int j = 0; j < m; j++){\n            for (int s = 0; s < t; s++){\n                X(j,s) = numbers[idx];\n                idx++;\n            }\n        }\n        output.push_back(dparams[\"matrix_coefficient\"]*X);\n        X.zeros();\n    }\n    \n    return output;\n}\n\n/* Reads the user spesified error requirements for each SNR simulation from a csv file \n * Example: 'settings/errors.csv' file contains two lines:\n * --------------------\n * 10,12,14,16,18\n * 1000,800,600,400,200\n * --------------------\n * first line has SNR values separated by commas and \n * second line has the corresponding error requirement for each SNR value\n * this means that SNR 16 simulation will be run until we hit 400 errors etc.\n */\nunordered_map<int, int> read_error_requirements(const string &filepath){\n    unordered_map<int, int> snr_to_error;\n    vector<int> snrs, errors;\n    int line_num = 1;\n    ifstream error_file(filepath);\n    string line;\n    string value;\n\n    if (!error_file.good()) {\n        log_msg(\"No error requirements file '\" + filepath + \"' found!\", \"Error\");\n        exit(1);\n    }\n\n    while(getline(error_file, line)){\n        clean_input(line);\n        if (line.empty()) continue;\n        istringstream iss(line);\n        while(getline(iss, value, ',')){\n            // clean_input(value);\n            if (line_num == 1){\n                snrs.push_back(strtol(value.c_str(), NULL, 10));\n            } else if (line_num == 2){\n                errors.push_back(strtol(value.c_str(), NULL, 10));\n            } else break;\n        }\n        line_num++;\n    }\n\n    /* assert error requirements validity... */\n    /* especially make sure that the data here matches with the data in the settings file */\n\n    if (snrs.empty()){\n        log_msg(\"Error requirements file '\" + filepath + \"' is empty!\", \"Error\");\n        exit(1);\n    }\n\n    int min = params[\"snr_min\"];\n    int max = params[\"snr_max\"];\n    int step = params[\"snr_step\"];\n    unsigned required_size = (max-min)/step + 1;\n\n    if (snrs.size() != required_size){\n        log_msg(\"Error requirements file '\" + filepath + \"' has an incorrect amount of SNR values!\", \"Error\");\n        exit(1);\n    }\n\n    if (snrs.size() != errors.size()){\n        log_msg(\"Error requirements file '\" + filepath + \"' has an incorrect amount of error values!\", \"Error\");\n        exit(1);\n    }\n\n    for (auto i = 0u; i < snrs.size(); i++){\n        if (min + (int)i*step != snrs[i]){\n            log_msg(\"Error requirements file '\" + filepath + \"' has unspesified SNR value at column \" + to_string(i+1) + \"!\", \"Error\");\n            exit(1);\n        }\n        snr_to_error[snrs[i]] = errors[i];\n    }\n\n    /* All good! */\n\n    return snr_to_error;\n}", "meta": {"hexsha": "159ca7925dc2a3e6ad4d3ed384486466ee63ffab", "size": 15393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/config.cpp", "max_stars_repo_name": "Hyper5phere/sphere-decoder", "max_stars_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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/config.cpp", "max_issues_repo_name": "Hyper5phere/sphere-decoder", "max_issues_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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/config.cpp", "max_forks_repo_name": "Hyper5phere/sphere-decoder", "max_forks_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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.4884393064, "max_line_length": 151, "alphanum_fraction": 0.5296563373, "num_tokens": 3647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.04401864829530668, "lm_q1q2_score": 0.01927239862292857}}
{"text": "//*****************************************************************************\n// Copyright 2017-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#pragma once\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <omp.h>\n#include <utility>\n\n#include \"ngraph/runtime/reference/broadcast.hpp\"\n#include \"ngraph/shape_util.hpp\"\n#include \"ngraph/util.hpp\"\n\nnamespace ngraph\n{\n    namespace runtime\n    {\n        namespace gcpu\n        {\n            namespace kernel\n            {\n#ifdef PARALLEL\n                static std::tuple<size_t, size_t> get_start_finish(size_t size)\n                {\n                    const size_t nthreads = omp_get_num_threads();\n                    const size_t ithread = omp_get_thread_num();\n                    const size_t start = ithread * size / nthreads;\n                    const size_t finish = (ithread + 1) * size / nthreads;\n                    return std::make_tuple(start, finish);\n                }\n#endif\n                template <typename T>\n                void broadcast_2d(const T* in,\n                                  T* out,\n                                  const Shape& in_shape,\n                                  const Shape& out_shape,\n                                  const AxisSet& broadcast_axes)\n                {\n                    size_t index[2];\n                    size_t* out_index =\n                        (broadcast_axes.find(0) == broadcast_axes.end() ? &index[0] : &index[1]);\n                    for (index[0] = 0; index[0] < out_shape[0]; ++index[0])\n                    {\n                        for (index[1] = 0; index[1] < out_shape[1]; ++index[1])\n                        {\n                            out[index[0] * out_shape[1] + index[1]] = in[*out_index];\n                        }\n                    }\n                }\n\n                // #define PARALLEL\n                template <typename T>\n                void broadcast_3d(const T* in,\n                                  T* out,\n                                  const Shape& in_shape,\n                                  const Shape& out_shape,\n                                  const AxisSet& broadcast_axes)\n                {\n#ifdef PARALLEL\n#pragma omp parallel\n#endif\n                    {\n                        size_t start;\n                        size_t finish;\n#ifdef PARALLEL\n                        std::tie(start, finish) = get_start_finish(out_shape[0]);\n#else\n                        start = 0;\n                        finish = out_shape[0];\n#endif\n                        size_t index[3];\n                        size_t* out_index = 0;\n                        for (size_t i = 0; i < 3; i++)\n                        {\n                            if (broadcast_axes.count(i) == 0)\n                            {\n                                out_index = &index[i];\n                                break;\n                            }\n                        }\n                        for (index[0] = start; index[0] < finish; ++index[0])\n                        {\n                            for (index[1] = 0; index[1] < out_shape[1]; ++index[1])\n                            {\n                                for (index[2] = 0; index[2] < out_shape[2]; ++index[2])\n                                {\n                                    out[index[0] * out_shape[1] * out_shape[2] +\n                                        index[1] * out_shape[2] + index[2]] = in[*out_index];\n                                }\n                            }\n                        }\n                    }\n                }\n\n                template <typename T>\n                void broadcast_4d(const T* in,\n                                  T* out,\n                                  const Shape& in_shape,\n                                  const Shape& out_shape,\n                                  const AxisSet& broadcast_axes)\n                {\n                    size_t index[4];\n                    size_t* out_index = 0;\n                    for (size_t i = 0; i < 4; i++)\n                    {\n                        if (broadcast_axes.count(i) == 0)\n                        {\n                            out_index = &index[i];\n                            break;\n                        }\n                    }\n                    for (index[0] = 0; index[0] < out_shape[0]; ++index[0])\n                    {\n                        for (index[1] = 0; index[1] < out_shape[1]; ++index[1])\n                        {\n                            for (index[2] = 0; index[2] < out_shape[2]; ++index[2])\n                            {\n                                for (index[3] = 0; index[3] < out_shape[3]; ++index[3])\n                                {\n                                    out[index[0] * out_shape[1] * out_shape[2] * out_shape[3] +\n                                        index[1] * out_shape[2] * out_shape[3] +\n                                        index[2] * out_shape[3] + index[3]] = in[*out_index];\n                                }\n                            }\n                        }\n                    }\n                }\n\n                template <typename T>\n                void broadcast_5d(const T* in,\n                                  T* out,\n                                  const Shape& in_shape,\n                                  const Shape& out_shape,\n                                  const AxisSet& broadcast_axes)\n                {\n                    size_t index[5];\n                    size_t* out_index = 0;\n                    for (size_t i = 0; i < 5; i++)\n                    {\n                        if (broadcast_axes.count(i) == 0)\n                        {\n                            out_index = &index[i];\n                            break;\n                        }\n                    }\n                    for (index[0] = 0; index[0] < out_shape[0]; ++index[0])\n                    {\n                        for (index[1] = 0; index[1] < out_shape[1]; ++index[1])\n                        {\n                            for (index[2] = 0; index[2] < out_shape[2]; ++index[2])\n                            {\n                                for (index[3] = 0; index[3] < out_shape[3]; ++index[3])\n                                {\n                                    for (index[4] = 0; index[4] < out_shape[4]; ++index[4])\n                                    {\n                                        out[index[0] * out_shape[1] * out_shape[2] * out_shape[3] *\n                                                out_shape[4] +\n                                            index[1] * out_shape[2] * out_shape[3] * out_shape[4] +\n                                            index[2] * out_shape[3] * out_shape[4] +\n                                            index[3] * out_shape[4] + index[4]] = in[*out_index];\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n\n                template <typename T>\n                void broadcast_6d(const T* in,\n                                  T* out,\n                                  const Shape& in_shape,\n                                  const Shape& out_shape,\n                                  const AxisSet& broadcast_axes)\n                {\n                    size_t index[6];\n                    size_t* out_index = 0;\n                    for (size_t i = 0; i < 6; i++)\n                    {\n                        if (broadcast_axes.count(i) == 0)\n                        {\n                            out_index = &index[i];\n                            break;\n                        }\n                    }\n                    for (index[0] = 0; index[0] < out_shape[0]; ++index[0])\n                    {\n                        for (index[1] = 0; index[1] < out_shape[1]; ++index[1])\n                        {\n                            for (index[2] = 0; index[2] < out_shape[2]; ++index[2])\n                            {\n                                for (index[3] = 0; index[3] < out_shape[3]; ++index[3])\n                                {\n                                    for (index[4] = 0; index[4] < out_shape[4]; ++index[4])\n                                    {\n                                        for (index[5] = 0; index[5] < out_shape[5]; ++index[5])\n                                        {\n                                            out[index[0] * out_shape[1] * out_shape[2] *\n                                                    out_shape[3] * out_shape[4] * out_shape[5] +\n                                                index[1] * out_shape[2] * out_shape[3] *\n                                                    out_shape[4] * out_shape[5] +\n                                                index[2] * out_shape[3] * out_shape[4] *\n                                                    out_shape[5] +\n                                                index[3] * out_shape[4] * out_shape[5] +\n                                                index[4] * out_shape[5] + index[5]] =\n                                                in[*out_index];\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n\n                template <typename T>\n                void broadcast(const T* in,\n                               T* out,\n                               const Shape& in_shape,\n                               const Shape& out_shape,\n                               const AxisSet& broadcast_axes)\n                {\n                    if (in_shape.size() == 0)\n                    {\n                        for (size_t i = 0; i < shape_size(out_shape); ++i)\n                        {\n                            out[i] = in[0];\n                        }\n                    }\n                    else if (in_shape.size() == 1)\n                    {\n                        switch (out_shape.size())\n                        {\n                        case 2:\n                            broadcast_2d<T>(in, out, in_shape, out_shape, broadcast_axes);\n                            break;\n                        case 3:\n                            broadcast_3d<T>(in, out, in_shape, out_shape, broadcast_axes);\n                            break;\n                        case 4:\n                            broadcast_4d<T>(in, out, in_shape, out_shape, broadcast_axes);\n                            break;\n                        case 5:\n                            broadcast_5d<T>(in, out, in_shape, out_shape, broadcast_axes);\n                            break;\n                        case 6:\n                            broadcast_6d<T>(in, out, in_shape, out_shape, broadcast_axes);\n                            break;\n                        default:\n                            runtime::reference::broadcast<T>(\n                                in, out, in_shape, out_shape, broadcast_axes);\n                            break;\n                        }\n                    }\n                    else\n                    {\n                        runtime::reference::broadcast<T>(\n                            in, out, in_shape, out_shape, broadcast_axes);\n                    }\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "f3d4b8e047f5f6b955546fc16ce946145ac7bf00", "size": 11974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ngraph/runtime/generic_cpu/kernel/broadcast.hpp", "max_stars_repo_name": "magrawal128/ngraph", "max_stars_repo_head_hexsha": "ca911487d1eadfe6ec66dbe3da6f05cee3645b24", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T21:55:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T21:55:19.000Z", "max_issues_repo_path": "src/ngraph/runtime/generic_cpu/kernel/broadcast.hpp", "max_issues_repo_name": "biswajitcsecu/ngraph", "max_issues_repo_head_hexsha": "d6bff37d7968922ef81f3bed63379e849fcf3b45", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-20T20:56:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-22T20:10:28.000Z", "max_forks_repo_path": "src/ngraph/runtime/generic_cpu/kernel/broadcast.hpp", "max_forks_repo_name": "biswajitcsecu/ngraph", "max_forks_repo_head_hexsha": "d6bff37d7968922ef81f3bed63379e849fcf3b45", "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.2274368231, "max_line_length": 99, "alphanum_fraction": 0.3199432103, "num_tokens": 2191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.044018645316791415, "lm_q1q2_score": 0.01927239731886459}}
{"text": "/**\n * @file constrained_ik.cpp\n * @brief Constrained Inverse Kinematic Solver\n *\n * @author dsolomon\n * @date Sep 15, 2013\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2013, 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#include <constrained_ik/constrained_ik.h>\n#include \"constrained_ik/constraint_group.h\"\n#include <boost/make_shared.hpp>\n#include <constrained_ik/constraint_results.h>\n#include <ros/ros.h>\n\nconst std::vector<std::string> SUPPORTED_COLLISION_DETECTORS = {\"IndustrialFCL\", \"CollisionDetectionOpenVDB\"}; /**< Supported collision detector */\n\nnamespace constrained_ik\n{\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::Affine3d;\n\nConstrained_IK::Constrained_IK():nh_(\"~\")\n{\n  initialized_ = false;\n\n  loadDefaultSolverConfiguration();\n}\n\nvoid Constrained_IK::addConstraintsFromParamServer(const std::string &parameter_name)\n{\n  XmlRpc::XmlRpcValue constraints_xml;\n  boost::shared_ptr<pluginlib::ClassLoader<constrained_ik::Constraint> > constraint_loader;\n\n  constraint_loader.reset(new pluginlib::ClassLoader<constrained_ik::Constraint>(\"constrained_ik\", \"constrained_ik::Constraint\"));\n\n  if (!nh_.getParam(parameter_name, constraints_xml))\n  {\n    ROS_ERROR(\"Unable to find ros parameter: %s\", parameter_name.c_str());\n    ROS_BREAK();\n    return;\n  }\n\n  if(constraints_xml.getType() != XmlRpc::XmlRpcValue::TypeArray)\n  {\n    ROS_ERROR(\"ROS parameter %s must be an array\", parameter_name.c_str());\n    ROS_BREAK();\n    return;\n  }\n\n  for (int i=0; i<constraints_xml.size(); ++i)\n  {\n    XmlRpc::XmlRpcValue constraint_xml = constraints_xml[i];\n\n    if (constraint_xml.hasMember(\"class\") &&\n              constraint_xml[\"class\"].getType() == XmlRpc::XmlRpcValue::TypeString &&\n              constraint_xml.hasMember(\"primary\") &&\n              constraint_xml[\"primary\"].getType() == XmlRpc::XmlRpcValue::TypeBoolean)\n    {\n      std::string class_name = constraint_xml[\"class\"];\n      bool is_primary = constraint_xml[\"primary\"];\n\n      Constraint *constraint;\n      try\n      {\n        constraint = constraint_loader->createUnmanagedInstance(class_name);\n\n        constraint->loadParameters(constraint_xml);\n        if (is_primary)\n          addConstraint(constraint, constraint_types::Primary);\n        else\n          addConstraint(constraint, constraint_types::Auxiliary);\n\n      }\n      catch (pluginlib::PluginlibException& ex)\n      {\n        ROS_ERROR(\"Couldn't load constraint named %s.\\n Error: %s\", class_name.c_str(), ex.what());\n        ROS_BREAK();\n      }\n    }\n    else\n    {\n      ROS_ERROR(\"Constraint must have class(string) and primary(boolean) members\");\n    }\n  }\n}\n\nvoid Constrained_IK::loadDefaultSolverConfiguration()\n{\n  ConstrainedIKConfiguration config;\n  config.debug_mode = false;\n  config.allow_joint_convergence = false;\n  config.allow_primary_normalization = true;\n  config.allow_auxiliary_nomalization = true;\n  config.limit_primary_motion = false;\n  config.limit_auxiliary_motion = false;\n  config.limit_auxiliary_interations = false;\n  config.solver_max_iterations = 500;\n  config.solver_min_iterations = 0;\n  config.auxiliary_max_iterations = 5;\n  config.primary_max_motion = 2.0;\n  config.auxiliary_max_motion = 0.2;\n  config.primary_norm = 1.0;\n  config.auxiliary_norm = 0.2;\n  config.primary_gain = 1.0;\n  config.auxiliary_gain = 1.0;\n  config.joint_convergence_tol = 0.0001;\n\n  setSolverConfiguration(config);\n}\n\nvoid Constrained_IK::setSolverConfiguration(const ConstrainedIKConfiguration &config)\n{\n  config_ = config;\n  validateConstrainedIKConfiguration<ConstrainedIKConfiguration>(config_);\n}\n\nconstrained_ik::ConstraintResults Constrained_IK::evalConstraint(constraint_types::ConstraintTypes constraint_type, const constrained_ik::SolverState &state) const\n{\n  switch(constraint_type)\n  {\n    case constraint_types::Primary:\n      return primary_constraints_.evalConstraint(state);\n    case constraint_types::Auxiliary:\n      return auxiliary_constraints_.evalConstraint(state);\n  }\n}\n\nEigen::MatrixXd Constrained_IK::calcNullspaceProjection(const Eigen::MatrixXd &J) const\n{\n  MatrixXd J_pinv = calcDampedPseudoinverse(J);\n  MatrixXd JplusJ = J_pinv * J;\n  int mn = JplusJ.rows();\n  MatrixXd P = MatrixXd::Identity(mn,mn)-JplusJ;\n  return (P);\n}\n\nEigen::MatrixXd Constrained_IK::calcNullspaceProjectionTheRightWay(const Eigen::MatrixXd &A) const\n{\n  Eigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeFullV);\n  MatrixXd V(svd.matrixV());\n\n  // determine rank using same algorithym as latest Eigen\n  // TODO replace next 10 lines of code with rnk = svd.rank(); once eigen3 is updated\n  int rnk = 0;\n  if(svd.singularValues().size()==0)\n  {\n    rnk = 0;\n  }\n  else\n  {\n    double threshold = std::min(A.rows(),A.cols())*Eigen::NumTraits<double>::epsilon();\n    double premultiplied_threshold = svd.singularValues().coeff(0) * threshold;\n    rnk = svd.nonzeroSingularValues()-1;\n    while(rnk>=0 && svd.singularValues().coeff(rnk) < premultiplied_threshold) --rnk;\n    rnk++;\n  }\n\n  // zero singular vectors in the range of A\n  for(int i=0; i<rnk; ++i)\n  {\n    for(int j=0; j<A.cols(); j++) V(j,i) = 0;\n  }\n\n  MatrixXd P = V *  V.transpose();\n  return(P);\n}\n\nEigen::MatrixXd Constrained_IK::calcDampedPseudoinverse(const Eigen::MatrixXd &J) const\n{\n  MatrixXd J_pinv;\n\n  if (basic_kin::BasicKin::dampedPInv(J,J_pinv))\n  {\n    return J_pinv;\n  }\n  else\n  {\n    ROS_ERROR_STREAM(\"Not able to calculate damped pseudoinverse!\");\n    throw std::runtime_error(\"Not able to calculate damped pseudoinverse!  IK solution may be invalid.\");\n  }\n}\n\nbool Constrained_IK::calcInvKin(const Eigen::Affine3d &goal,\n                                const Eigen::VectorXd &joint_seed,\n                                Eigen::VectorXd &joint_angles) const\n{\n  return calcInvKin(goal,joint_seed, planning_scene::PlanningSceneConstPtr(), joint_angles);\n}\n\nbool Constrained_IK::calcInvKin(const Eigen::Affine3d &goal,\n                                const Eigen::VectorXd &joint_seed,\n                                const planning_scene::PlanningSceneConstPtr planning_scene,\n                                Eigen::VectorXd &joint_angles) const\n{\n  double dJoint_norm;\n  SolverStatus status;\n\n    // initialize state\n  joint_angles = joint_seed;  // initialize result to seed value\n  constrained_ik::SolverState state = getState(goal, joint_seed); // create state vars for this IK solve\n  state.condition = checkInitialized();\n  state.planning_scene = planning_scene;\n  state.group_name = kin_.getJointModelGroup()->getName();\n\n  //TODO: Does this still belong here?\n  if(planning_scene)\n  {\n    state.robot_state = robot_state::RobotStatePtr(new moveit::core::RobotState(planning_scene->getCurrentState()));\n\n    //Check and make sure the correct collision detector is loaded.\n    auto pos = std::find(SUPPORTED_COLLISION_DETECTORS.begin(),SUPPORTED_COLLISION_DETECTORS.end(),\n                         planning_scene->getActiveCollisionDetectorName());\n    if (pos == SUPPORTED_COLLISION_DETECTORS.end())\n    {\n      std::stringstream error_message;\n      error_message<<\" Constrained IK requires the use of collision detectors: \";\n      for(auto& d : SUPPORTED_COLLISION_DETECTORS)\n      {\n        error_message<<\"'\"<< d<<\"' \";\n      }\n      error_message<<\".\\nSet or add the 'collision_detector' parameter to an allowed collision detector in the move_group.launch file\"<<std::endl;\n      throw std::runtime_error(error_message.str());\n    }\n\n    state.collision_robot = boost::dynamic_pointer_cast<const collision_detection::CollisionRobotIndustrial>(planning_scene->getCollisionRobot());\n    state.collision_world = boost::dynamic_pointer_cast<const collision_detection::CollisionWorldIndustrial>(planning_scene->getCollisionWorld());\n  }\n\n  if (state.condition == initialization_state::NothingInitialized || state.condition == initialization_state::AuxiliaryOnly)\n    throw std::runtime_error(\"Must call init() before using Constrained_IK and have a primary constraint.\");\n\n  //Cache the joint angles to return if max iteration is reached.\n  Eigen::VectorXd cached_joint_angles = joint_seed;\n\n  // iterate until solution converges (or aborted)\n  while (true)\n  {\n    // re-update internal state variables\n    updateState(state, joint_angles);\n\n    // calculate a Jacobian (relating joint-space updates/deltas to cartesian-space errors/deltas)\n    // and the associated cartesian-space error/delta vector\n    // Primary Constraints\n    constrained_ik::ConstraintResults primary = evalConstraint(constraint_types::Primary, state);\n    // TODO since we already have J_p = USV, use that to get null-projection too.\n    // otherwise, we are repeating the expensive calculation of the SVD\n\n    VectorXd dJoint_p;\n    dJoint_p.setZero(joint_seed.size());\n    if (!primary.isEmpty()) // This is required because not all constraints always return data.\n    {\n      MatrixXd Ji_p = calcDampedPseudoinverse(primary.jacobian);\n      dJoint_p = config_.primary_gain*(Ji_p*primary.error);\n      dJoint_norm = dJoint_p.norm();\n      if(config_.allow_primary_normalization && dJoint_norm > config_.primary_norm)// limit maximum update radian/meter\n      {\n        dJoint_p = config_.primary_norm * (dJoint_p/dJoint_norm);\n        dJoint_norm = dJoint_p.norm();\n      }\n      state.primary_sum += dJoint_norm;\n    }\n\n    // Auxiliary Constraints\n    VectorXd dJoint_a;\n    constrained_ik::ConstraintResults auxiliary;\n    dJoint_a.setZero(dJoint_p.size());\n    if (state.condition == initialization_state::PrimaryAndAuxiliary)\n    {\n      if (!((config_.limit_auxiliary_motion && state.auxiliary_sum >= config_.auxiliary_max_motion) ||\n          (config_.limit_auxiliary_interations && state.iter > config_.auxiliary_max_iterations)))\n      {\n        auxiliary = evalConstraint(constraint_types::Auxiliary, state);\n        if (!auxiliary.isEmpty()) // This is required because not all constraints always return data.\n        {\n          MatrixXd N_p = calcNullspaceProjectionTheRightWay(primary.jacobian);\n          MatrixXd Jnull_a = calcDampedPseudoinverse(auxiliary.jacobian*N_p);\n          dJoint_a = config_.auxiliary_gain*Jnull_a*(auxiliary.error-auxiliary.jacobian*dJoint_p);\n          dJoint_norm = dJoint_a.norm();\n          if(config_.allow_auxiliary_nomalization && dJoint_norm > config_.auxiliary_norm)// limit maximum update radian/meter\n          {\n            dJoint_a = config_.auxiliary_norm * (dJoint_a/dJoint_norm);\n            dJoint_norm = dJoint_a.norm();\n          }\n          state.auxiliary_sum += dJoint_norm;\n        }\n      }\n      else\n      {\n        state.auxiliary_at_limit = true;\n      }\n    }\n\n    status = checkStatus(state, primary, auxiliary);\n    \n    \n    if (status == Converged)\n    {\n      ROS_DEBUG_STREAM(\"Found IK solution in \" << state.iter << \" iterations: \" << joint_angles.transpose());\n      return true;\n    }\n    else if (status == NotConverged)\n    {\n      // update joint solution by the calculated update (or a partial fraction)\n      joint_angles += (dJoint_p + dJoint_a);\n      clipToJointLimits(joint_angles);\n    }\n    else if (status == Failed)\n    {\n      joint_angles = cached_joint_angles;\n      return false;\n    }\n  }\n}\n\nSolverStatus Constrained_IK::checkStatus(const constrained_ik::SolverState &state, const constrained_ik::ConstraintResults &primary, const constrained_ik::ConstraintResults &auxiliary) const\n{\n  // Check the status of convergence\n  if(state.condition == initialization_state::PrimaryAndAuxiliary)\n  {\n    bool status = (primary.status && auxiliary.status);\n\n    if (state.iter > config_.solver_min_iterations)\n    {\n      if (!status && primary.status && state.auxiliary_at_limit)\n      {\n        ROS_DEBUG(\"Auxiliary motion or iteration limit reached!\");\n        return Converged;\n      }\n      else if(status)\n      {\n        return Converged;\n      }\n    }\n  }\n  \n  if(state.condition == initialization_state::PrimaryOnly)\n  {   \n    if (primary.status && state.iter > config_.solver_min_iterations)\n    {\n      return Converged;\n    }\n  }\n\n  // check for joint convergence\n  //   - this is an error: joints stabilize, but goal pose not reached\n  if (config_.allow_joint_convergence)\n  {\n    if (state.joints_delta.cwiseAbs().maxCoeff() < config_.joint_convergence_tol)\n    {\n      if (state.iter > config_.solver_min_iterations)\n      {\n        ROS_DEBUG_STREAM(\"Joint convergence reached \" << state.iter << \" / \" << config_.solver_max_iterations << \" iterations before convergence.\");\n        return Converged;\n      }\n    }\n  }\n  \n  if (state.iter > config_.solver_max_iterations || (config_.limit_primary_motion && state.primary_sum >= config_.primary_max_motion))\n  {\n    if (!primary.status)\n    {\n      if (config_.limit_primary_motion && state.primary_sum >= config_.primary_max_motion)\n      {\n        ROS_WARN_STREAM(\"Primary reached max allowed motion, no solution returned.\");\n      }\n      else\n      {\n        ROS_WARN_STREAM(\"Solver reached max allowed iteration, no solution returned.\");\n      }\n      return Failed;\n    }\n    else if (state.condition == initialization_state::PrimaryAndAuxiliary)\n    {\n      ROS_WARN_STREAM(\"Maximum iterations reached but primary converged so returning solution.\");\n      return Converged;\n    }\n  }\n\n  return NotConverged;\n}\n\nvoid Constrained_IK::clearConstraintList()\n{\n  primary_constraints_.clear();\n  auxiliary_constraints_.clear();\n}\n\nvoid Constrained_IK::clipToJointLimits(Eigen::VectorXd &joints) const\n{\n  const MatrixXd limits = kin_.getLimits();\n  const VectorXd orig_joints(joints);\n\n  if (joints.size() != limits.rows())\n    throw std::invalid_argument(\"clipToJointLimits: Unexpected number of joints\");\n\n  for (size_t i=0; i<limits.rows(); ++i)\n  {\n    joints[i] = std::max(limits(i,0), std::min(limits(i,1), joints[i]));\n  }\n  if (config_.debug_mode && !joints.isApprox(orig_joints))\n      ROS_WARN(\"Joints have been clipped\");\n}\n\nvoid Constrained_IK::init(const basic_kin::BasicKin &kin)\n{\n  if (!kin.checkInitialized())\n    throw std::invalid_argument(\"Input argument 'BasicKin' must be initialized\");\n\n  kin_ = kin;\n  initialized_ = true;\n  primary_constraints_.init(this);\n  auxiliary_constraints_.init(this);\n\n}\n\ndouble Constrained_IK::rangedAngle(double angle)\n{\n    angle = copysign(fmod(fabs(angle),2.0*M_PI), angle);\n    if (angle < -M_PI) return angle+2.*M_PI;\n    if (angle > M_PI)  return angle-2.*M_PI;\n    return angle;\n}\n\nconstrained_ik::SolverState Constrained_IK::getState(const Eigen::Affine3d &goal, const Eigen::VectorXd &joint_seed) const\n{\n  if (!kin_.checkJoints(joint_seed))\n    throw std::invalid_argument(\"Seed doesn't match kinematic model\");\n\n  if (!goal.matrix().block(0,0,3,3).isUnitary(1e-6))\n        throw std::invalid_argument(\"Goal pose not proper affine\");\n\n  return constrained_ik::SolverState(goal, joint_seed);\n}\n\nvoid Constrained_IK::updateState(constrained_ik::SolverState &state, const Eigen::VectorXd &joints) const\n{\n  // update maximum iterations\n  state.iter++;\n\n  // update joint convergence\n  state.joints_delta = joints - state.joints;\n  state.joints = joints;\n  kin_.calcFwdKin(joints, state.pose_estimate);\n\n  if(state.planning_scene && state.robot_state)\n  {\n    state.robot_state->setJointGroupPositions(kin_.getJointModelGroup()->getName(), joints);\n    state.robot_state->update();\n  }\n\n  if (config_.debug_mode)\n    state.iteration_path.push_back(joints);\n\n}\n\n} // namespace constrained_ik\n\n", "meta": {"hexsha": "d78a73eaefc7c912fb5aaa2aa9dcfbade8b69253", "size": 15979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "constrained_ik/src/constrained_ik.cpp", "max_stars_repo_name": "jrgnicho/industrial_moveit", "max_stars_repo_head_hexsha": "a077a32608aca7e976b51669ed33e0f2af328b55", "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": "constrained_ik/src/constrained_ik.cpp", "max_issues_repo_name": "jrgnicho/industrial_moveit", "max_issues_repo_head_hexsha": "a077a32608aca7e976b51669ed33e0f2af328b55", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-04T16:51:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-04T16:51:03.000Z", "max_forks_repo_path": "constrained_ik/src/constrained_ik.cpp", "max_forks_repo_name": "jrgnicho/industrial_moveit", "max_forks_repo_head_hexsha": "a077a32608aca7e976b51669ed33e0f2af328b55", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-28T14:19:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T17:12:14.000Z", "avg_line_length": 33.5693277311, "max_line_length": 190, "alphanum_fraction": 0.7024845109, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.04813677009248645, "lm_q1q2_score": 0.0192456410305913}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_KROVAK_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_KROVAK_HPP\r\n\r\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\r\n// This file is automatically generated. DO NOT EDIT.\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 4.9.1\r\n\r\n// Original copyright notice:\r\n\r\n// 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#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 {};\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            template <typename T>\r\n            struct par_krovak\r\n            {\r\n                T    C_x;\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 CalculationType, typename Parameters>\r\n            struct base_krovak_ellipsoid : public base_t_fi<base_krovak_ellipsoid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>\r\n            {\r\n\r\n                typedef CalculationType geographic_type;\r\n                typedef CalculationType cartesian_type;\r\n\r\n                par_krovak<CalculationType> m_proj_parm;\r\n\r\n                inline base_krovak_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_krovak_ellipsoid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(e_forward)  ellipsoid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                /* calculate xy from lat/lon */\r\n\r\n                /* Constants, identical to inverse transform function */\r\n                    CalculationType s45, s90, e2, e, alfa, uq, u0, g, k, k1, n0, ro0, ad, a, s0, n;\r\n                    CalculationType gfi, u, fi0, deltav, s, d, eps, ro;\r\n\r\n\r\n                    s45 = 0.785398163397448;    /* 45 DEG */\r\n                    s90 = 2 * s45;\r\n                    fi0 = this->m_par.phi0;    /* Latitude of projection centre 49 DEG 30' */\r\n\r\n                   /* Ellipsoid is used as Parameter in for.c and inv.c, therefore a must\r\n                      be set to 1 here.\r\n                      Ellipsoid Bessel 1841 a = 6377397.155m 1/f = 299.1528128,\r\n                      e2=0.006674372230614;\r\n                   */\r\n                    a =  1; /* 6377397.155; */\r\n                    /* e2 = this->m_par.es;*/       /* 0.006674372230614; */\r\n                    e2 = 0.006674372230614;\r\n                    e = sqrt(e2);\r\n\r\n                    alfa = sqrt(1. + (e2 * pow(cos(fi0), 4)) / (1. - e2));\r\n\r\n                    uq = 1.04216856380474;      /* DU(2, 59, 42, 42.69689) */\r\n                    u0 = asin(sin(fi0) / alfa);\r\n                    g = pow(   (1. + e * sin(fi0)) / (1. - e * sin(fi0)) , alfa * e / 2.  );\r\n\r\n                    k = tan( u0 / 2. + s45) / pow  (tan(fi0 / 2. + s45) , alfa) * g;\r\n\r\n                    k1 = this->m_par.k0;\r\n                    n0 = a * sqrt(1. - e2) / (1. - e2 * pow(sin(fi0), 2));\r\n                    s0 = 1.37008346281555;       /* Latitude of pseudo standard parallel 78 DEG 30'00\" N */\r\n                    n = sin(s0);\r\n                    ro0 = k1 * n0 / tan(s0);\r\n                    ad = s90 - uq;\r\n\r\n                /* Transformation */\r\n\r\n                    gfi =pow ( ((1. + e * sin(lp_lat)) /\r\n                               (1. - e * sin(lp_lat))) , (alfa * e / 2.));\r\n\r\n                    u= 2. * (atan(k * pow( tan(lp_lat / 2. + s45), alfa) / gfi)-s45);\r\n\r\n                    deltav = - lp_lon * alfa;\r\n\r\n                    s = asin(cos(ad) * sin(u) + sin(ad) * cos(u) * cos(deltav));\r\n                    d = asin(cos(u) * sin(deltav) / cos(s));\r\n                    eps = n * d;\r\n                    ro = ro0 * pow(tan(s0 / 2. + s45) , n) / pow(tan(s / 2. + s45) , n)   ;\r\n\r\n                   /* x and y are reverted! */\r\n                    xy_y = ro * cos(eps) / a;\r\n                    xy_x = ro * sin(eps) / a;\r\n\r\n                        if( !pj_param(this->m_par.params, \"tczech\").i )\r\n                      {\r\n                        xy_y *= -1.0;\r\n                        xy_x *= -1.0;\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(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    /* calculate lat/lon from xy */\r\n\r\n                /* Constants, identisch wie in der Umkehrfunktion */\r\n                    CalculationType s45, s90, fi0, e2, e, alfa, uq, u0, g, k, k1, n0, ro0, ad, a, s0, n;\r\n                    CalculationType u, deltav, s, d, eps, ro, fi1, xy0;\r\n                    int ok;\r\n\r\n                    s45 = 0.785398163397448;    /* 45 DEG */\r\n                    s90 = 2 * s45;\r\n                    fi0 = this->m_par.phi0;    /* Latitude of projection centre 49 DEG 30' */\r\n\r\n\r\n                   /* Ellipsoid is used as Parameter in for.c and inv.c, therefore a must\r\n                      be set to 1 here.\r\n                      Ellipsoid Bessel 1841 a = 6377397.155m 1/f = 299.1528128,\r\n                      e2=0.006674372230614;\r\n                   */\r\n                    a = 1; /* 6377397.155; */\r\n                    /* e2 = this->m_par.es; */      /* 0.006674372230614; */\r\n                    e2 = 0.006674372230614;\r\n                    e = sqrt(e2);\r\n\r\n                    alfa = sqrt(1. + (e2 * pow(cos(fi0), 4)) / (1. - e2));\r\n                    uq = 1.04216856380474;      /* DU(2, 59, 42, 42.69689) */\r\n                    u0 = asin(sin(fi0) / alfa);\r\n                    g = pow(   (1. + e * sin(fi0)) / (1. - e * sin(fi0)) , alfa * e / 2.  );\r\n\r\n                    k = tan( u0 / 2. + s45) / pow  (tan(fi0 / 2. + s45) , alfa) * g;\r\n\r\n                    k1 = this->m_par.k0;\r\n                    n0 = a * sqrt(1. - e2) / (1. - e2 * pow(sin(fi0), 2));\r\n                    s0 = 1.37008346281555;       /* Latitude of pseudo standard parallel 78 DEG 30'00\" N */\r\n                    n = sin(s0);\r\n                    ro0 = k1 * n0 / tan(s0);\r\n                    ad = s90 - uq;\r\n\r\n\r\n                /* Transformation */\r\n                   /* revert y, x*/\r\n                    xy0=xy_x;\r\n                    xy_x=xy_y;\r\n                    xy_y=xy0;\r\n\r\n                        if( !pj_param(this->m_par.params, \"tczech\").i )\r\n                      {\r\n                        xy_x *= -1.0;\r\n                        xy_y *= -1.0;\r\n                      }\r\n\r\n                    ro = sqrt(xy_x * xy_x + xy_y * xy_y);\r\n                    eps = atan2(xy_y, xy_x);\r\n                    d = eps / sin(s0);\r\n                    s = 2. * (atan(  pow(ro0 / ro, 1. / n) * tan(s0 / 2. + s45)) - s45);\r\n\r\n                    u = asin(cos(ad) * sin(s) - sin(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 / alfa;\r\n\r\n                /* ITERATION FOR lp_lat */\r\n                   fi1 = u;\r\n\r\n                   ok = 0;\r\n                   do\r\n                   {\r\n                       lp_lat = 2. * ( atan( pow( k, -1. / alfa)  *\r\n                                            pow( tan(u / 2. + s45) , 1. / alfa)  *\r\n                                            pow( (1. + e * sin(fi1)) / (1. - e * sin(fi1)) , e / 2.)\r\n                                           )  - s45);\r\n\r\n                      if (fabs(fi1 - lp_lat) < 0.000000000000001) ok=1;\r\n                      fi1 = lp_lat;\r\n\r\n                   }\r\n                   while (ok==0);\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 ts;\r\n                /* read some Parameters,\r\n                 * here Latitude Truescale */\r\n\r\n                ts = pj_param(par.params, \"rlat_ts\").f;\r\n                proj_parm.C_x = ts;\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(par.params, \"tlat_0\").i)\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(par.params, \"tlon_0\").i)\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(par.params, \"tk\").i)\r\n                        par.k0 = 0.9999;\r\n\r\n                /* always the same */\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 CalculationType, typename Parameters>\r\n    struct krovak_ellipsoid : public detail::krovak::base_krovak_ellipsoid<CalculationType, Parameters>\r\n    {\r\n        inline krovak_ellipsoid(const Parameters& par) : detail::krovak::base_krovak_ellipsoid<CalculationType, 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 CalculationType, typename Parameters>\r\n        class krovak_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                    return new base_v_fi<krovak_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void krovak_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"krovak\", new krovak_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_KROVAK_HPP\r\n\r\n", "meta": {"hexsha": "28e3c4cfde8b63cb18dd6cfc3c038e4c5e179bed", "size": 14877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/krovak.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/krovak.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/krovak.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": 41.2105263158, "max_line_length": 132, "alphanum_fraction": 0.5097801976, "num_tokens": 3637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.042087727615238615, "lm_q1q2_score": 0.019239845620760067}}
{"text": "/*\n\nRPBA - Robust Parallel Bundle Adjustment\n\nFile rpba.cpp\n\nDescription: Input controlled by file \"parameters\", call of parallel bundle adjustment and output\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#include <cstdio>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\n#include \"rpba.h\"\n#include \"system.h\"\n#include <iomanip>      // std::setprecision\n#include <fstream>      // std::ofstream\n\n\n\nusing std::string;\nusing std::ifstream;\nusing std::ofstream;\nusing namespace Eigen;\n\n\n\nvoid ComputeRotationMatrixfromRodriguesAngle(const double a, const double b, const double c,\n\t\t\t\t\t     PMat &Rabc);\nvoid ComputeRodriguesAnglefromRotationMatrix(double &a, double &b, double &c,\n\t\tconst PMat &Rabc);\n\n\nint main(int argc, char** argv) {\n\t// load parameters from parameter file\n\tif( argc > 1 ) {\n\t\tstd::cout << \"Parameter file not used\\n\";\n\t\treturn 1;\n\t}\n\n\n\tboost::property_tree::ptree pt;\n\tboost::property_tree::ini_parser::read_ini(\"parameters\", pt);\n\n\tstd::string ID = pt.get<std::string>(\"InputDir\");\n\tstd::string File = pt.get<std::string>(\"File\");\n\tstd::string rf = pt.get<std::string>(\"Robust\");\n\tstd::string ee = pt.get<std::string>(\"Exteval\");\n\tstd::string k2i = pt.get<std::string>(\"k2\");\n\tstd::string k4i = pt.get<std::string>(\"k4\");\n\tstd::string fl = pt.get<std::string>(\"f\");\n\tstd::string k24outi = pt.get<std::string>(\"k24out\");\n\tstd::string mti = pt.get<std::string>(\"Threads\");\n\n\tint mt = 0;\n\tbool k2f, k4f, flf, extevalflag, robustflag, k24outflag;\n\n\tstd::stringstream ees(ee), rfs(rf), k2s(k2i), k4s(k4i), fls(fl), k24outs(k24outi), mts(mti), inputfiles, outputfiles;\n\n\tees >> extevalflag;\n\trfs >> robustflag;\n\n\tk2s >> k2f;\n\tk4s >> k4f;\n\tfls >> flf;\n\n\tk24outs >> k24outflag;\n\n\tmts >> mt;\n\n\tinputfiles << ID << \"/\" << File;\n\tstd::string inputfile = inputfiles.str();\n\n\tstd::cout << \"Inputfile: \" << inputfile << std::endl << std::endl;\n\tstd::cout << \"Robustflag: \" << robustflag << std::endl << std::endl;\n\n\tif (mt < 1)\n\t\tmt = System::threadCount();\n\n\tstd::cout << \"Threads: \" << mt << std::endl << std::endl;\n\n\n\tstd::cout << \"K2: \" << k2f << std::endl;\n\tstd::cout << \"K4: \" << k4f << std::endl;\n\tstd::cout << \"Focal length: \" << flf << std::endl << std::endl;\n\tstd::cout << \"K24out: \" << k24outflag << std::endl << std::endl;\n\n\n\tstd::vector<bool> addflags(7,false);\n\taddflags[0] = k2f; // k2 - second order coefficient for radial distortion\n\taddflags[1] = k4f; // k4 - fourth order coefficient for radial distortion\n\taddflags[2] = flf; // f - focal length or photogrammetric camera constant\n\n\tint nraddpar = 0;\n\tfor (int i = 0; i < 3; ++i)\n\t\tif (addflags[i])\n\t\t\t++nraddpar;\n\n\tMatrixXf XX;\n\tstd::vector< Eigen::MatrixXf > xg;\n\tstd::vector<std::vector<float> > wx, wy, wxy;\n\tstd::vector<std::vector<IMAPNR> > pointXXv;\n\tstd::vector< Eigen::Matrix<float, 3, 4> > PMatrices;\n\tstd::vector<Camera> cameras;\n\tstd::vector<int> iwidth, iheight;\n\n\tInputBlock(inputfile, nraddpar, XX, xg,\n\t\t\twx, wy, wxy,\n\t\t\tpointXXv, PMatrices, cameras,\n\t\t\tiwidth, iheight,\n\t\t\tk24outflag);\n\n\n\n\tstd::ostringstream os;\n\tconst System::Time start = System::getTickCount();\n\n\tCalcPLSA(XX, xg,\n\t\t\twx, wy, wxy,\n\t\t\tpointXXv, PMatrices, cameras,\n\t\t\tiwidth, iheight,\n\t\t\trobustflag,\n\t\t\taddflags,\n\t\t\tos, mt, extevalflag);\n\n\tif ((int) PMatrices.size() < 50 || mt == 1)\n\t\tstd::cout << os.str();\n\n\tstd::cout << \"\\n\\nBundle adjustment runtime: \" << (float) (System::getTickCount()-start) / 1000.f << \"s\\n\\n\";\n\n\n\n/*\tif (!extevalflag) {\n\t\toutputfiles << ID << \"/out-\" << File;\n\t\tstd::string outputfile = outputfiles.str();\n\n\t\tOutputBlock(outputfile, XX, xg, pointXXv, PMatrices,\n\t\t\t\tcameras, k24outflag);\n\t} // if extevalflag */\n\n\t\n\t\n/*\n\t// Output of text file with 3D coordinates\n\tstd::stringstream cloudfiles;\n\tcloudfiles << ID << \"/\" << \"cloud.txt\";\n\tstd::string cloudfile = cloudfiles.str();\n\tstd::cout << \"Outputfile: \" << cloudfile << std::endl;\n\tofstream foutc(cloudfile);\n\tfoutc << std::setprecision(8);\n\tint counter = 0;\n\tfor (int i = 0; i < XX.cols(); ++i) {\n\t\tif (pointXXv[i].size() > 0)\n\t\t\tfoutc << XX(0,i) << ' ' << XX(1,i) << ' ' << XX(2,i) << '\\n';\n\t\telse\n\t\t\t++counter;\n\t}\n\tfoutc.close();\n\n\t// Counter gives number of 3D points which have been deleted during (robust) bundle adjustment\n\tstd::cout << \"Counter: \" << counter << std::endl;\n*/\n\n\treturn 0;\n}\n\n\n\nvoid InputBlock(const std::string &inputfile, const int nraddpar,\n\t\tEigen::MatrixXf &XX,\n\t\tstd::vector<Eigen::MatrixXf> &xg,\n\t\tstd::vector<std::vector<float> > &wx, std::vector<std::vector<float> > &wy,\n\t\tstd::vector<std::vector<float> > &wxy,\n\t\tstd::vector<std::vector<IMAPNR> > &pointXXv,\n\t\tstd::vector<PMat> &PMatrices,\n\t\tstd::vector<Camera> &cameras,\n\t\tstd::vector<int> &iwidth, std::vector<int> &iheight,\n\t\tconst bool k24outflag)\n{\n\tifstream fin(inputfile);\n\n\tint nrcameras,nrpoints,nrobs;\n\n\tfin >> nrcameras;\n\tfin >> nrpoints;\n\tfin >> nrobs;\n\n\tstd::cout << \"Cameras: \" << nrcameras << \"  Points: \" << nrpoints << \" Observations \" << nrobs << std::endl;\n\n\tint nrobs2 = nrobs * 2;\n\tint nrparimages = (nrcameras - 2) * 6 + 5 + nrcameras * nraddpar;\n\tint nrunknowns = 3 * nrpoints + nrparimages;\n\tint redundancy = nrobs2 - nrunknowns;\n\tstd::cout << \"Unknowns \" << nrunknowns << \"  Redundancy \" << redundancy << std::endl;\n\n\tstd::vector<std::vector<float> > xin(nrcameras),yin(nrcameras);\n\n\twx.resize(nrcameras);\n\twy.resize(nrcameras);\n\twxy.resize(nrcameras);\n\n\tpointXXv.resize(nrpoints);\n\n\tstd::vector<float> minx(nrcameras,1.e20f),miny(nrcameras,1.e20f),maxx(nrcameras,-1.e20f),maxy(nrcameras,-1.e20f);\n\tint nrcam,nrpoint;\n\tfloat x,y;\n\tIMAPNR point;\n\tfor (int i = 0; i < nrobs; ++i) {\n\t\tfin >> nrcam >> nrpoint >> x >> y;\n\t\tif (x < minx[nrcam])\n\t\t\tminx[nrcam] = x;\n\t\tif (y < miny[nrcam])\n\t\t\tminy[nrcam] = y;\n\t\tif (x > maxx[nrcam])\n\t\t\tmaxx[nrcam] = x;\n\t\tif (y > maxy[nrcam])\n\t\t\tmaxy[nrcam] = y;\n\t\txin[nrcam].push_back(x);\n\t\tyin[nrcam].push_back(y);\n\t\t// set weight to unit matrix\n\t\twx[nrcam].push_back(1.f);\n\t\twy[nrcam].push_back(1.f);\n\t\twxy[nrcam].push_back(0.f);\n\t\tpoint.image = nrcam;\n\t\tpoint.pointnr = (int) xin[nrcam].size() - 1;\n\t\tpointXXv[nrpoint].push_back(point);\n\t}\n\n\tPMatrices.resize(nrcameras);\n\tcameras.resize(nrcameras);\n\txg.resize(nrcameras);\n\tiwidth.resize(nrcameras);\n\tiheight.resize(nrcameras);\n\n\tdouble a, b, c;\n\tfloat f, k2, k4;\n\tfor (int i = 0; i < nrcameras; ++i) {\n\t\tcameras[i] = Camera();\n\t\tcameras[i].K.setZero();\n\t\tfin >> a >> b >> c >> PMatrices[i](0,3) >> PMatrices[i](1,3) >> PMatrices[i](2,3) >> f >> k2 >> k4;\n\t\tComputeRotationMatrixfromRodriguesAngle(a,b,c,PMatrices[i]);\n\t\tcameras[i].K(1,1) = cameras[i].K(0,0) = f;\n\t\tcameras[i].K(2,2) = 1.f;\n\t\tif (k24outflag) {\n\t\t\tcameras[i].distpara[0] = k2;\n\t\t\tcameras[i].distpara[1] = k4;\n\t\t} // if\n\t\telse {\n\t\t\tcameras[i].distpara[0] = k2 * f * f;\n\t\t\tcameras[i].distpara[1] = k4 * f * f * f * f;\n\t\t} // else\n\n\t\tiwidth[i] = 1;\n\t\tiheight[i] = 1;\n\n\t\txg[i].resize(3,(int) xin[i].size());\n\t\tfor (int j = 0; j < (int) xin[i].size(); ++j) {\n\t\t\txg[i](0,j) = -xin[i][j];\n\t\t\txg[i](1,j) = -yin[i][j];\n\t\t\txg[i](2,j) = 1.f;\n\t\t} // for j\n\t} // for i\n\n\tXX.resize(4,nrpoints);\n\tfor (int i = 0; i < nrpoints; ++i) {\n\t\tfin >> XX(0,i) >> XX(1,i) >> XX(2,i);\n\t\tXX(3,i) = 1.f;\n\t} // for i\n\n\tfin.close();\n\n\treturn;\n}\n\n\n\nvoid OutputBlock(const std::string &outputfile,\n\t\tEigen::MatrixXf &XX,\n\t\tstd::vector<Eigen::MatrixXf> &xg,\n\t\tstd::vector<std::vector<IMAPNR> > &pointXXv,\n\t\tstd::vector<PMat> &PMatrices,\n\t\tstd::vector<Camera> &cameras,\n\t\tconst bool k24outflag)\n{\n\tofstream fout(outputfile);\n\n\tint nrobs = 0;\n\n\tfor (int i = 0; i < (int) pointXXv.size(); ++i)\n\t\tnrobs += (int) pointXXv[i].size();\n\n\tfout << (int) PMatrices.size() << ' ';\n\tfout << (int) XX.cols() << ' ';\n\tfout << nrobs << '\\n';\n\n\tSBI sortbimage;\n\n\tfout << std::setprecision(8);\n\tfor (int i = 0; i < (int) pointXXv.size(); ++i) {\n\t\tsort(pointXXv[i].begin(), pointXXv[i].end(), sortbimage);\n\t\tfor (int j = 0; j < (int) pointXXv[i].size(); ++j) {\n\t\t\tIMAPNR &point = pointXXv[i][j];\n\t\t\tfout << point.image << ' ' << i << ' ' << -xg[point.image](0,point.pointnr) << ' ' << -xg[point.image](1,point.pointnr) << '\\n';\n\t\t} // for j\n\t} // for i\n\n\tdouble a, b, c;\n\tfor (int i = 0; i < (int) PMatrices.size(); ++i) {\n\t\tComputeRodriguesAnglefromRotationMatrix(a, b, c, PMatrices[i]);\n\t\tfout << a << ' ' << b << ' ' << c << ' ' << PMatrices[i](0,3) << ' ' << PMatrices[i](1,3) << ' ' << PMatrices[i](2,3) << ' ';\n\t\tfout << cameras[i].K(0,0) << ' ';\n\t\tif (k24outflag)\n\t\t\tfout << cameras[i].distpara[0] << ' ' << cameras[i].distpara[1] << '\\n';\n\t\telse {\n\t\t\tconst double f = cameras[i].K(0,0);\n\t\t\tconst double f2 = 1./ (f * f);\n\t\t\tfout << cameras[i].distpara[0] * f2 << ' ' << cameras[i].distpara[1] * f2 * f2 << '\\n';\n\t\t}\n\t} // for i\n\n\tfor (int i = 0; i < XX.cols(); ++i)\n\t\tfout << XX(0,i) << ' ' << XX(1,i) << ' ' << XX(2,i) << '\\n';\n\n\tfout.close();\n\n\treturn;\n} // OutputBlock\n\n\n\n// inspired by PBA\nvoid ComputeRotationMatrixfromRodriguesAngle(const double a, const double b, const double c,\n\t\tPMat &Rabc){\n\n\tif (boost::math::isnan(a) || boost::math::isnan(b) || boost::math::isnan(c))\n\t\tstd::cout << \"NANRabc: \" << a << ' ' << b << ' ' << c << '\\n';\n\n\tconst double a2 = a * a, b2 = b * b, c2 = c * c;\n\tconst double ab = a * b, ac = a * c, bc = b * c;\n\n\tconst double aa = sqrt(a2 + b2 + c2);\n\tconst double ct = aa == 0.?0.5:(1. - cos(aa)) / (aa * aa);\n\tconst double st = aa == 0.?1:sin(aa) / aa;\n\tRabc(0,0) = (float) (1. - (b2 + c2) * ct);\n\tRabc(0,1) = (float) (ab * ct - c * st);\n\tRabc(0,2) = (float) (ac * ct + b * st);\n\tRabc(1,0) = (float) (ab * ct + c * st);\n\tRabc(1,1) = (float) (1. - (c2 + a2) * ct);\n\tRabc(1,2) = (float) (bc * ct - a * st);\n\tRabc(2,0) = (float) (ac * ct - b * st);\n\tRabc(2,1) = (float) (bc * ct + a * st);\n\tRabc(2,2) = (float) (1. - (a2 + b2) * ct);\n\n\treturn;\n} // ComputeRotationMatrixfromRodriguesAngle\n\n\n\n// inspired by PBA\nvoid ComputeRodriguesAnglefromRotationMatrix(double &a, double &b, double &c,\n\t\tconst PMat &Rabc)\n{\n    const double epsilon0 = 0.01;\n    const double epsilon1 = 0.1;\n    const double pi = 3.14159265358979323846;\n\n    double trace1 = (Rabc(0,0) + Rabc(1,1) + Rabc(2,2) - 1.) * 0.5;\n    if (fabs(Rabc(0,1) - Rabc(1,0)) < epsilon0 &&\n    \t\tfabs(Rabc(1,2) - Rabc(2,1)) < epsilon0 &&\n\t\tfabs(Rabc(0,2) - Rabc(2,0)) < epsilon0 ) {\n    \t \t if (fabs(Rabc(0,1) + Rabc(1,0)) < epsilon1 &&\n    \t \t\tfabs(Rabc(1,2) + Rabc(2,1)) < epsilon1 &&\n\t\t\tfabs(Rabc(0,2) + Rabc(2,0)) < epsilon1 && trace1 > 0.9) {\n    \t \t\t a = b = c = 0.;\n    \t \t\t return;\n    \t \t }\n\n    \t \t const double xx12 = (Rabc(0,0) + 1.) * 0.5;\n    \t \t const double yy12 = (Rabc(1,1) + 1.) * 0.5;\n    \t \t const double zz12 = (Rabc(2,2) + 1.) * 0.5;\n    \t \t const double xy4 = (Rabc(0,1) + Rabc(1,0)) * 0.25;\n    \t \t const double xz4 = (Rabc(0,2) + Rabc(2,0)) * 0.25;\n    \t \t const double yz4 = (Rabc(1,2) + Rabc(2,1)) * 0.25;\n\n    \t \t if ((xx12 > yy12) && (xx12 > zz12)) {\n    \t \t\t if (xx12 < epsilon0) {\n    \t \t\t\t a = 0.;\n    \t \t\t\t b = c = sqrt(0.5) * pi;\n    \t \t\t\t return;\n    \t \t\t } // if xx\n    \t \t\t const double t = sqrt(xx12);\n    \t \t\t a = t * pi;\n    \t \t\t b = xy4 / t * pi;\n    \t \t\t c = xz4 / t * pi;\n    \t \t\t return;\n    \t \t } // if xx\n    \t \t if (yy12 > zz12) {\n    \t \t\t if (yy12 < epsilon0) {\n    \t \t\t\t a = c = sqrt(0.5) * pi;\n    \t \t\t\t b = 0.;\n    \t \t\t\t return;\n    \t \t\t } // if yy\n    \t \t\t const double t = sqrt(yy12);\n    \t \t\t a = xy4 / t * pi;\n    \t \t\t b = t * pi;\n    \t \t\t c = yz4 / t * pi;\n    \t \t\t return;\n    \t \t } // if\n    \t \t if (zz12 < epsilon0) {\n    \t \t\t a = b = sqrt(0.5) * pi;\n    \t \t\t c = 0.;\n    \t \t\t return;\n    \t \t } // if zz\n    \t \t const double t  = sqrt(zz12);\n    \t \t a = xz4 / t * pi;\n    \t \t b = yz4 / t * pi;\n    \t \t c = t * pi;\n    \t \t return;\n    } // if fabs\n\n    const double aa = acos(trace1);\n    const double bb = 0.5 * aa / sin(aa);\n    a = bb * (Rabc(2,1) - Rabc(1,2));\n    b = bb * (Rabc(0,2) - Rabc(2,0));\n    c = bb * (Rabc(1,0) - Rabc(0,1));\n\n    return;\n} // ComputeRodriguesAnglefromRotationMatrix\n", "meta": {"hexsha": "a3c8f68efb72bed651f04130ded912ec5eff421b", "size": 12914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rpba.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": "rpba.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": "rpba.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.35, "max_line_length": 460, "alphanum_fraction": 0.5919931857, "num_tokens": 4592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.044680865661299037, "lm_q1q2_score": 0.019219355896728012}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"timer.h\"\n\n#include <boost/bimap.hpp>\n#include <boost/foreach.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nnamespace {\n    class Etat {\n    public:\n        Etat() {}\n\n        std::deque<unsigned short> memoire_larry;\n        std::deque<unsigned short> memoire_robin;\n\n        short suivant(const unsigned short tirage) {\n            short score = 0;\n            // Larry's strategy is to remove the number that hasn't been called \n            // in the longest time.\n            auto it = std::find(memoire_larry.begin(), memoire_larry.end(), tirage);\n            if (it != memoire_larry.end()) {\n                ++score;\n                memoire_larry.erase(it);\n                memoire_larry.push_front(tirage);\n            } else {\n                memoire_larry.push_front(tirage);\n                if (memoire_larry.size() > 5)\n                    memoire_larry.pop_back();\n            }\n\n            // Robin's strategy is to remove the number that's been in the memory \n            // the longest time.\n            it = std::find(memoire_robin.begin(), memoire_robin.end(), tirage);\n            if (it != memoire_robin.end()) {\n                --score;\n            } else {\n                memoire_robin.push_front(tirage);\n                if (memoire_robin.size() > 5)\n                    memoire_robin.pop_back();\n            }\n\n            std::map<unsigned short, unsigned short> echange;\n            unsigned short compteur = 0;\n            for (auto &n: memoire_robin) {\n                if (echange.find(n) == echange.end())\n                    echange[n] = ++compteur;\n\n                n = echange[n];\n            }\n\n            for (auto &n: memoire_larry) {\n                if (echange.find(n) == echange.end())\n                    echange[n] = ++compteur;\n\n                n = echange[n];\n            }\n\n            return score;\n        }\n\n        bool operator<(const Etat &e) const {\n            if (memoire_larry != e.memoire_larry)\n                return memoire_larry < e.memoire_larry;\n\n            return memoire_robin < e.memoire_robin;\n        }\n    };\n\n    // std::ostream & operator<<(std::ostream & os, const Etat & e)\n    // {\n    //     os << \"Larry \" << e.memoire_larry << \", Robin \" << e.memoire_robin;\n    //     return os;\n    // }\n}\n\nENREGISTRER_PROBLEME(298, \"Selective Amnesia\") {\n    // Larry and Robin play a memory game involving of a sequence of random numbers between 1 and 10, inclusive, that\n    // are called out one at a time.\n    // Each player can remember up to 5 previous numbers. When the called number is in a player's memory, that player is\n    // awarded a point. If it's not, the player adds the called number to his memory, removing another number if his\n    // memory is full.\n    //  \n    // Both players start with empty memories. Both players always add new missed numbers to their memory but use a\n    // different strategy in deciding which number to remove:\n    //      - Larry's strategy is to remove the number that hasn't been called in the longest time.\n    //      - Robin's strategy is to remove the number that's been in the memory the longest time.\n    //\n    // Example game:\n    // \n    //      Turn\tCalled \t    Larry's Larry's     Robin's Robin's\n    //              number      memory  score       memory  score\n    //         1\t     1\t          1\t      0\t          1\t      0\n    //         2\t     2\t        1,2\t      0\t        1,2\t      0\n    //         3\t     4\t      1,2,4\t      0\t      1,2,4\t      0\n    //         4\t     6\t    1,2,4,6\t      0\t    1,2,4,6\t      0\n    //         5\t     1\t    1,2,4,6\t      1\t    1,2,4,6\t      1\n    //         6\t     8\t  1,2,4,6,8\t      1\t  1,2,4,6,8\t      1\n    //         7\t    10\t 1,4,6,8,10\t      1\t 2,4,6,8,10\t      1\n    //         8\t     2\t 1,2,6,8,10\t      1\t 2,4,6,8,10\t      2 \n    //         9\t     4\t 1,2,4,8,10\t      1\t 2,4,6,8,10\t      3\n    //        10\t     1\t 1,2,4,8,10\t      2\t 1,4,6,8,10\t      3\n    //\n    // Denoting Larry's score by L and Robin's score by R, what is the expected value of |L-R| after 50 turns? Give your\n    // answer rounded to eight decimal places using the format x.xxxxxxxx.\n    typedef boost::bimap<Etat, unsigned short> bimap_t;\n    typedef std::tuple<unsigned short/*etat*/, short/*score*/, long double/*probabilite*/> tuple_t;\n\n    std::map<unsigned short/*etat*/, std::deque<tuple_t>> graphe;\n\n    unsigned short compteur = 0;\n    bimap_t relation;\n    relation.insert(bimap_t::value_type(Etat(), compteur++));\n\n    std::set<Etat> a_voir{Etat()};\n    while (!a_voir.empty()) {\n        const auto it = a_voir.begin();\n        const unsigned short origine = relation.left.find(*it)->second;\n\n        std::deque<tuple_t> suivants;\n\n        for (unsigned short tirage = 0; tirage < 10; ++tirage) {\n            Etat nouvel_etat = *it;\n            short score = nouvel_etat.suivant(tirage);\n\n            unsigned short suivant = 0;\n\n\n            if (auto it2 = relation.left.find(nouvel_etat);it2 != relation.left.end()) {\n                suivant = it2->second;\n            } else {\n                suivant = compteur;\n                relation.insert(bimap_t::value_type(nouvel_etat, compteur++));\n                a_voir.insert(nouvel_etat);\n            }\n\n            bool found = false;\n            for (auto&[etat, s, probabilite]: suivants) {\n                if (etat == suivant && s == score) {\n                    probabilite += 0.1L;\n                    found = true;\n                }\n            }\n\n            if (!found) {\n                suivants.emplace_back(suivant, score, 0.1);\n            }\n        }\n\n        graphe.emplace(origine, suivants);\n        a_voir.erase(it);\n    }\n\n    std::deque<std::map<short/*score*/, long double/*probabilite*/>> dp(compteur);\n    dp.front().emplace(0, 1.0);\n\n    for (unsigned short tour = 0; tour < 50; ++tour) {\n        std::deque<std::map<short/*score*/, long double/*probabilite*/>> suivant(compteur);\n        for (unsigned short etat = 0; etat < compteur; ++etat) {\n            const auto &etats = graphe[etat];\n            for (auto[score, probabilite]: dp[etat]) {\n                for (const auto &[e/*etat*/, s/*score*/, p/*probabilite*/]: etats) {\n                    suivant[e][score + s] += p * probabilite;\n                }\n            }\n        }\n        std::swap(suivant, dp);\n    }\n\n    long double resultat = 0.0L;\n    for (const auto &p: dp)\n        for (const auto &[score, probabilite]: p) {\n            resultat += static_cast<long double>(std::abs(score)) * probabilite;\n        }\n\n    return std::to_fixed(resultat, 8);\n}\n", "meta": {"hexsha": "6a83a373f6a915de692d4854afe6d1ab0e80b10e", "size": 6644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme2xx/probleme298.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme2xx/probleme298.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme2xx/probleme298.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9111111111, "max_line_length": 120, "alphanum_fraction": 0.5164057797, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.046724954311889194, "lm_q1q2_score": 0.01920913590774328}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/Core/Log.h>\n#include <vw/Camera/CAHVORModel.h>\n#include <fstream>\n#include <boost/foreach.hpp>\n\nusing namespace vw;\n\n// Overloaded constructor - this one reads in the file name\n// where the CAVHOR camera model is saved.\ncamera::CAHVORModel::CAHVORModel(std::string const& filename) {\n\n  try {\n    std::ifstream input(filename.c_str(), std::ifstream::in);\n    input.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n    vw_out(InfoMessage, \"camera\") << \"Reading CAHVOR file: \"\n                                  << filename << \".\\n\";\n\n    char r1,r2;\n\n    while (true) {\n      input.ignore(1024, 'C');\n      input >> r1;\n      if (r1 == '=')\n        break;\n    }\n\n    input >> C(0) >> C(1) >> C(2);\n\n    input >> r1 >> r2;\n    if (r1 != 'A' || r2 != '=')\n      vw_throw( IOErr() << \"CAHVORModel: Could not read A vector\\n\" );\n    input >> A(0) >> A(1) >> A(2);\n\n    input >> r1 >> r2;\n    if (r1 != 'H' || r2 != '=')\n      vw_throw( IOErr() << \"CAHVORModel: Could not read H vector\\n\" );\n    input >> H(0) >> H(1) >> H(2);\n\n    input >> r1 >> r2;\n    if (r1 != 'V' || r2 != '=')\n      vw_throw( IOErr() << \"CAHVORModel: Could not read V vector\\n\" );\n    input >> V(0) >> V(1) >> V(2);\n\n    input >> r1 >> r2;\n    if (r1 != 'O' || r2 != '=')\n      vw_throw( IOErr() << \"CAHVORModel: Could not read O vector\\n\" );\n    input >> O(0) >> O(1) >> O(2);\n\n    input >> r1 >> r2;\n    if (r1 != 'R' || r2 != '=')\n      vw_throw( IOErr() << \"CAHVORModel: Could not read R vector\\n\" );\n    input >> R(0) >> R(1) >> R(2);\n\n  } catch (const std::ifstream::failure& e) {\n    vw_throw( IOErr() << \"CAHVORModel: Could not read file: \" << filename << \" (\" << e.what() << \")\" );\n  }\n}\n\n// Write CAHVOR model to file.\nvoid camera::CAHVORModel::write(std::string const& filename) {\n\n  try {\n    std::ofstream output(filename.c_str(), std::ofstream::out);\n    output.exceptions(std::ofstream::failbit | std::ofstream::badbit);\n    output.precision(20);\n\n    vw_out(InfoMessage, \"camera\") << \"Writing CAHVOR file: \" << filename << \"\\n\";\n\n    output << \"C = \" << C(0) << \" \" << C(1) << \" \" << C(2) << \"\\n\"\n           << \"A = \" << A(0) << \" \" << A(1) << \" \" << A(2) << \"\\n\"\n           << \"H = \" << H(0) << \" \" << H(1) << \" \" << H(2) << \"\\n\"\n           << \"V = \" << V(0) << \" \" << V(1) << \" \" << V(2) << \"\\n\"\n           << \"O = \" << O(0) << \" \" << O(1) << \" \" << O(2) << \"\\n\"\n           << \"R = \" << R(0) << \" \" << R(1) << \" \" << R(2) << \"\\n\";\n\n  } catch (const std::ofstream::failure& e) {\n    vw_throw( IOErr() << \"CAHVORModel: Could not write file: \" << filename << \" (\" << e.what() << \")\" );\n  }\n}\n\n// Set iteration and convergence constants\n#define VW_CAHVOR_MAXITER  20     // maximum number of iterations allowed\n#define VW_CAHVOR_CONV   1.0e-6   // covergence tolerance - check adequacy for application\n\n// CAHVOR pixel_to_vector with partial_derivative output\nVector3 camera::CAHVORModel::pixel_to_vector(Vector2 const& pix,\n                                             Matrix<double> &partial_derivatives) const {\n\n  // Note, vec is actually the output vector\n  // Based on JPL_CMOD_CAHVOR_2D_TO_3D\n  Vector3 vec;\n  int i, j;\n  double omega, omega_2, tau, mu, u, u_2, du, k1, k3, k5, poly, deriv;\n\n  Vector3 f, g, rr, pp, wo, lambda;\n\n  Matrix3x3 m33, n33;\n  double sgn, magv, magi;\n  Vector3 t, w, v3, u3;\n  Matrix3x3 irrt;\n\n  double dudt;\n  Vector3 drpdx, drpdy;\n  Matrix3x3 dldr;\n\n  Vector3 drdx, drdy;\n  Matrix3x3 drpdr, drpdri;\n\n  //  The projection point is merely the C of the camera model.\n  //  vec = C; This isn't needed, only vec is returned for our\n  //  usage.\n\n  // Calculate the projection ray assuming normal vector directions,\n  // neglecting distortion.\n\n  f = pix.y() * A; // pos2[1] in JPL code is our y, and pos2[0] is x...\n  f = V - f;\n\n  g = pix.x() * A;\n  g = H - g;\n  rr = cross_prod(f,g);\n  magi = 1.0/norm_2(rr);\n  rr = magi * rr;\n\n  // Check and optionally correct for vector directions.\n  sgn = 1;\n  t = cross_prod(V,H);\n\n  if (dot_prod(t, A) < 0) {\n    rr = -1.0 * rr;\n    sgn = -1;\n  }\n\n  // Optionally compute partial for non-linear part of the model\n  irrt.set_identity();\n\n  for (i=0; i<3; i++) {\n    for (j=0; j<3; j++) {\n      irrt(i,j) -= (rr(i) * rr(j));\n      // used to be A.as_ref() in vxl\n      t = cross_prod(f, A);\n      w = irrt * t;\n      drpdx(0) = partial_derivatives(0,0) = -sgn * w(0) * magi;\n      drpdx(1) = partial_derivatives(1,0) = -sgn * w(1) * magi;\n      drpdx(2) = partial_derivatives(2,0) = -sgn * w(2) * magi;\n\n      // used to be A.as_ref() in vxl\n      t = cross_prod(g, A);\n      w = irrt * t;\n      drpdy(0) = partial_derivatives(0,1) = sgn * w(0) * magi;\n      drpdy(1) = partial_derivatives(1,1) = sgn * w(1) * magi;\n      drpdy(2) = partial_derivatives(2,1) = sgn * w(2) * magi;\n    }\n  }\n\n  // Remove the radial lens distortion.  Preliminary values of\n  // omega, lambda, and tau are computed from the rr vector\n  // including distortion, in order to obtain the coefficients of\n  // the equation k5*u^5 + k3*u^3 + k1*u = 1, which is solved for u\n  // by means of Newton's method.  This value is used to compute the\n  // corrected rr.\n  omega = dot_prod(rr, O);\n  omega_2 = omega * omega;\n  wo = omega * O;\n  lambda = rr - wo;\n  tau = dot_prod(lambda, lambda) / omega_2;\n\n  k1 = 1 + R(0);                //  1 + rho0\n  k3 = R(1) * tau;              //  rho1*tau\n  k5 = R(2) * tau*tau;  //  rho2*tau^2\n\n  mu = R(0) + k3 + k5;\n  u = 1.0 - mu; // initial approximation for iterations\n\n  for (i=0; i<VW_CAHVOR_MAXITER; i++) {\n    u_2 = u*u;\n    poly  =  ((k5*u_2  +  k3)*u_2 + k1)*u - 1;\n    deriv = (5*k5*u_2 + 3*k3)*u_2 + k1;\n\n    if (deriv <= 0) {\n      vw_out(InfoMessage, \"camera\") << \"CAHVORModel.pixel_to_vector(): Distortion is too negative\\n\";\n      break;\n    } else {\n      du = poly/deriv;\n      u -= du;\n      if (fabs(du) < VW_CAHVOR_CONV)\n        break;\n    }\n  }\n\n  if (i >= VW_CAHVOR_MAXITER) {\n    vw_out(InfoMessage, \"camera\") << \"CAHVORModel.pixel_to_vector(): Too many iterations (\" << i << \")\\n\";\n  }\n\n  mu = 1 - u;\n  pp = mu * lambda;\n  vec = rr - pp;\n  magv = norm_2(vec);\n  vec = 1.0/magv * vec;\n\n  // Note:  If partial derivatives are to be computed, corrected values\n  // of omega, lambda, tau, and mu must be computed.\n\n  // Recompute omega, lambda, tau, and mu\n  omega = dot_prod(vec, O);\n  omega_2 = omega * omega;\n  wo = omega * O;\n  lambda = vec - wo;\n  tau = dot_prod(lambda, lambda) / omega_2;\n  mu = R(0) + R(1)*tau + R(2)*tau*tau;\n\n  // Compute the partial derivatives for distortion\n  dldr.set_identity();\n\n  Matrix<double, 3, 1> Ocol;\n  Matrix<double, 1, 3> Orow;\n\n  select_col(Ocol, 0) = O;\n  select_row(Orow, 0) = O;\n\n  m33 = Ocol*Orow; // outer product, hopefully\n  dldr = dldr - m33;\n\n  dudt = R(1) + (2 * R(2) * tau);\n\n\n  v3 = transpose(transpose(lambda) * dldr);\n  v3 = (2/omega_2) * v3;\n  u3 = (2 * tau / omega) * O;\n  v3 = v3 - u3;\n\n  Matrix<double, 3, 1> lambdacol;\n  Matrix<double, 1, 3> v3row;\n\n  select_col(lambdacol,0) = lambda;\n  select_row(v3row,0) = v3;\n\n  m33 = lambdacol * v3row; // outer product, hopefully\n  m33 = dudt * m33;\n  n33 = mu * dldr;\n  drpdr = m33 + n33;\n\n  m33.set_identity();\n  drpdr = m33 + drpdr;\n  drpdr = magv * drpdr;\n\n  // Apply these partials to get the final result\n  drpdri = inverse(drpdr);\n  drdx = drpdri * drpdx;\n  drdy = drpdri * drpdy;\n\n  partial_derivatives(0,0) = drdx(0);\n  partial_derivatives(1,0) = drdx(1);\n  partial_derivatives(2,0) = drdx(2);\n  partial_derivatives(0,1) = drdy(0);\n  partial_derivatives(1,1) = drdy(1);\n  partial_derivatives(2,1) = drdy(2);\n\n  return vec;\n}\n\n\n// pixel_to_vector (no returned partial matrix)\nVector3 camera::CAHVORModel::pixel_to_vector(Vector2 const& pix) const {\n  // Based on JPL_CMOD_CAHVOR_2D_TO_3D\n\n  // Calculate the projection ray assuming normal vector directions,\n  // neglecting distortion.\n  Vector3 rr = normalize(cross_prod(V - pix.y() * A,\n                                    H - pix.x() * A));\n\n  // Check and optionally correct for vector directions.\n  if (dot_prod(cross_prod(V,H), A) < 0)\n    rr = -1.0 * rr;\n\n  // Remove the radial lens distortion.  Preliminary values of\n  // omega, lambda, and tau are computed from the rr vector\n  // including distortion, in order to obtain the coefficients of\n  // the equation k5*u^5 + k3*u^3 + k1*u = 1, which is solved for u\n  // by means of Newton's method.  This value is used to compute the\n  // corrected rr.\n  double omega = dot_prod(rr, O);\n  Vector3 lambda = rr - omega * O;\n  const double tau = dot_prod(lambda, lambda) / (omega*omega);\n\n  const double k1 = 1 + R(0);        //  1 + rho0\n  const double k3 = R(1) * tau;      //  rho1*tau\n  const double k5 = R(2) * tau*tau;  //  rho2*tau^2\n\n  double u = 1.0 - (R(0) + k3 + k5); // initial approximation for iterations\n\n  double du, poly, deriv;\n  for (int32 i=0;; i++) {\n    if (i >= VW_CAHVOR_MAXITER) {\n      vw_out(InfoMessage, \"camera\") << \"CAHVORModel.pixel_to_vector(): Too many iterations (\" << i << \")\\n\";\n      break;\n    }\n\n    double u_2 = u*u;\n    poly  =  ((k5*u_2  +  k3)*u_2 + k1)*u - 1;\n    deriv = (5*k5*u_2 + 3*k3)*u_2 + k1;\n\n    if (deriv <= 0) {\n      vw_out(InfoMessage, \"camera\") << \"CAHVORModel.pixel_to_vector(): Distortion is too negative\\n\";\n      break;\n    } else {\n      du = poly/deriv;\n      u -= du;\n      if (fabs(du) < VW_CAHVOR_CONV)\n        break;\n    }\n  }\n\n  return normalize(rr - (1 - u)*lambda);\n}\n\n\n// vector_to_pixel with partial_derivatives\nVector2 camera::CAHVORModel::point_to_pixel(Vector3 const& point,\n                                            Matrix<double> &partial_derivatives) const {\n\n  Vector3 vec = point - C;\n  // Based on JPL 3D to 2D POINT (not the 3D to 2D function alone).\n  Vector2 pix;\n  double alpha, beta, gamma, xh, yh;\n  double omega, omega_2, tau, mu;\n  Vector3 pp_c, wo, lambda;\n  Matrix3x3 dldp, dppdp, m33, n33;\n  Vector3 dxhdpp, dyhdpp, v3, u3;\n  double dudt;\n\n  // Calculate necessary quantities\n  omega = dot_prod(vec,O);\n  omega_2 = omega * omega;\n  wo = omega * O;\n  lambda = vec - wo;\n  tau = dot_prod(lambda, lambda) / omega_2;\n  mu = R(0) + (R(1) * tau) + (R(2) * tau * tau);\n  pp_c = mu * lambda;\n  pp_c = vec + pp_c;\n\n  // Calculate alpha, beta, gamma,\n  // dotted with a, h, v, respectively\n  alpha = dot_prod(pp_c, A);\n  beta = dot_prod(pp_c, H);\n  gamma = dot_prod(pp_c, V);\n\n  // Calculate the projection\n  pix.x() = xh = beta / alpha;\n  pix.y() = yh = gamma /alpha;\n\n  // Calculate the approximate partial derivatives\n  v3 = xh * A;\n  v3 = H - v3;\n  dxhdpp = 1/alpha * v3;\n  v3 = yh * A;\n  v3 = V - v3;\n  dyhdpp = 1/alpha * v3;\n\n  // Complete the calculations for accuracy\n  dldp.set_identity();\n\n  Matrix<double, 3, 1> Ocol;\n  Matrix<double, 1, 3> Orow;\n\n  select_col(Ocol, 0) = O;\n  select_row(Orow, 0) = O;\n\n  m33 = Ocol*Orow; // outer product, hopefully\n\n  dldp = dldp - m33;\n  dudt = R(1) + (2 * R(2) * tau);\n  lambda = dldp * v3;\n  v3 = 2/omega_2 * v3;\n  u3 = (2 * tau/omega) * O;\n  v3 = v3 - u3;\n\n  Matrix<double, 3, 1> lambdacol;\n  Matrix<double, 1, 3> v3row;\n\n  select_col(lambdacol,0) = lambda;\n  select_row(v3row,0) = v3;\n\n  m33 = lambdacol * v3row; // outer product, hopefully\n\n  m33 = dudt * m33;\n  n33 = mu * dldp;\n  dppdp = m33 + n33;\n  m33.set_identity();\n  dppdp = dppdp + m33;\n  select_row(partial_derivatives,0) = transpose(transpose(dxhdpp) * dppdp);\n  select_row(partial_derivatives,1) = transpose(transpose(dyhdpp) * dppdp);\n  return pix;\n}\n\n// vector_to_pixel without partial_derivatives\nVector2 camera::CAHVORModel::point_to_pixel(Vector3 const& point) const {\n\n  // Convert to directional\n  Vector3 vec = point - C;\n\n  // Calculate necessary quantities\n  double omega = dot_prod(vec,O);\n  Vector3 lambda = vec - omega * O;\n  double tau = dot_prod(lambda,lambda) / (omega*omega);\n  double mu = R(0) + (R(1) * tau) + (R(2) * tau * tau);\n  Vector3 pp_c = vec + mu * lambda;\n\n  double alpha = dot_prod(pp_c, A);\n\n  // Calculate the projection\n  return Vector2( dot_prod(pp_c,H) / alpha,\n                  dot_prod(pp_c,V) / alpha );\n}\n\n// linearize_camera\n//\n// Takes CAHVOR camera --> CAHV camera\n// Requires knowledge of size of image from CAHVOR camera\n//\n// This function warps a camera model so that it is purely\n// linear. The parameter C will not change. The parameters O\n// (identical to A) and R (all terms zero) will not be output. Note\n// that image warping will be necessary in order to use the new\n// models.\ncamera::CAHVModel camera::linearize_camera( camera::CAHVORModel const& camera_model,\n                                            Vector2i const& cahvor_image_size,\n                                            Vector2i const& cahv_image_size ) {\n\n  CAHVModel output_camera;\n  output_camera.C = camera_model.C;\n\n  static const bool minfov = true; // set to 0 if you do not want to\n                                   // minimize to a common field of\n                                   // view\n\n  // Record the landmark 2D coordinates around the perimeter of the image\n  Vector2 hpts[6], vpts[6];\n  hpts[0] = Vector2();\n  hpts[1] = Vector2(0,(cahvor_image_size[1]-1)/2.0);\n  hpts[2] = Vector2(0,cahvor_image_size[1]-1);\n  hpts[3] = Vector2(cahvor_image_size[0]-1,0);\n  hpts[4] = Vector2(cahvor_image_size[0]-1,(cahvor_image_size[1]-1)/2.0);\n  hpts[5] = cahvor_image_size - Vector2(1,1);\n  vpts[0] = Vector2();\n  vpts[1] = Vector2((cahvor_image_size[0]-1)/2.0,0);\n  vpts[2] = Vector2(cahvor_image_size[0]-1,0);\n  vpts[3] = Vector2(0,cahvor_image_size[1]-1);\n  vpts[4] = Vector2((cahvor_image_size[0]-1)/2,cahvor_image_size[1]-1);\n  vpts[5] = cahvor_image_size - Vector2(1,1);\n\n  BOOST_FOREACH( Vector2 const& local, vpts ) {\n    output_camera.A += camera_model.pixel_to_vector(local);\n  }\n  BOOST_FOREACH( Vector2 const& local, hpts ) {\n    output_camera.A += camera_model.pixel_to_vector(local);\n  }\n  output_camera.A = normalize(output_camera.A);\n\n  // Compute the original right and down vectors\n  Vector3 dn = cross_prod(camera_model.A, camera_model.H); // down vector\n  Vector3 rt = normalize(cross_prod(dn, camera_model.A)); // right vector\n  dn = normalize(dn);\n\n  // Adjust the right and down vectors to be orthogonal to new axis\n  rt = cross_prod(dn, output_camera.A);\n  dn = normalize(cross_prod(output_camera.A, rt));\n  rt = normalize(rt);\n\n  // Find horizontal and vertical fields of view\n\n  // Horizontal\n  double hmin = 1, hmax = -1;\n  BOOST_FOREACH( Vector2 const& loop, hpts ) {\n    Vector3 u3 = camera_model.pixel_to_vector(loop);\n    double sn = norm_2(cross_prod(output_camera.A,\n                           normalize(u3 - dot_prod(dn, u3) * dn)));\n    if (hmin > sn) hmin = sn;\n    if (hmax < sn) hmax = sn;\n  }\n\n  // Vertical\n  double vmin = 1, vmax = -1;\n  BOOST_FOREACH( Vector2 const& loop, vpts ) {\n    Vector3 u3 = camera_model.pixel_to_vector(loop);\n    double sn = norm_2(cross_prod(output_camera.A,\n                           normalize(u3 - dot_prod(rt, u3) * rt) ) );\n    if (vmin > sn) vmin = sn;\n    if (vmax < sn) vmax = sn;\n  }\n\n  // Compute the all-encompassing scale factors\n  Vector2 scale_factors;\n  Vector2 image_center = (cahv_image_size-Vector2(1,1))/2.0;\n  Vector2 image_center_2 = elem_prod(image_center,image_center);\n  if ( minfov ) {\n    // Use min value\n    scale_factors =\n      sqrt( elem_quot(image_center_2,\n                      Vector2(hmin*hmin,vmin*vmin)) - image_center_2 );\n  } else {\n    // Use max value\n    scale_factors =\n      sqrt( elem_quot(image_center_2,\n                      Vector2(hmax*hmax,vmax*vmax)) - image_center_2 );\n  }\n\n  // Assign idealized image centers and coordinate angles\n  output_camera.H = scale_factors[0] * rt + image_center[0] * output_camera.A;\n  output_camera.V = scale_factors[1] * dn + image_center[1] * output_camera.A;\n\n  return output_camera;\n}\n\ncamera::CAHVModel camera::linearize_camera( CAHVORModel const& camera_model,\n                                            int32 ix, int32 iy, int32 ox, int32 oy ) {\n  return camera::linearize_camera( camera_model,\n                                   Vector2i( ix, iy), Vector2i(ox, oy) );\n}\n\n// Note: the second derivatives with respect to motion of the point are the\n// same as the second derivatives with respect to motion of the camera, and\n// the first derivatives are opposite.\nvoid camera::CAHVORModel::get_point_derivatives( Vector3 const& P, double& u, double& v,\n                                                 Vector3& grad_u, Vector3& grad_v,\n                                                 Matrix3x3& hess_u, Matrix3x3& hess_v ) const {\n  // Compute the image plane position\n  double xi = dot_prod(P-C,O);\n  Vector3 lambda = P-C-xi*O;\n  double tau = dot_prod(lambda,lambda)/(xi*xi);\n  double mu = R[0]+tau*(R[1]+tau*R[2]);\n  Vector3 PP = P + mu*lambda;\n  Vector3 PPC = PP - C;\n  double denom = dot_prod(PPC,A);\n  u = dot_prod(PPC,H)/denom;\n  v = dot_prod(PPC,V)/denom;\n\n  // Compute the gradients\n  Vector3 grad_tau = 2*(lambda-tau*xi*O)/(xi*xi);\n  Vector3 grad_mu = 2*(R[1]+2*R[2]*tau)*(lambda/xi-tau*O)/xi;\n  Vector3 HuA = H - u*A;\n  Vector3 VvA = V - v*A;\n  grad_u = ( (1+mu)*HuA - mu*dot_prod(O,HuA)*O + dot_prod(lambda,HuA)*grad_mu ) / denom;\n  grad_v = ( (1+mu)*VvA - mu*dot_prod(O,VvA)*O + dot_prod(lambda,VvA)*grad_mu ) / denom;\n\n  // Compute the Hessians\n  Matrix3x3 I; I.set_identity();\n  Matrix3x3 hess_tau = 2/(xi*xi) * ( I + (3*tau-1)*outer_prod(O,O)\n                                     - 2*(outer_prod(O,lambda)+outer_prod(lambda,O))/xi );\n  Matrix3x3 hess_mu = (R[1]+2*R[2]*tau)*hess_tau + 2*R[2]*outer_prod(grad_tau,grad_tau);\n  Matrix3x3 tmp_u = outer_prod( grad_mu, HuA - dot_prod(O,HuA)*O )\n    + outer_prod( grad_u, mu*dot_prod(O,A)*O - dot_prod(lambda,A)*grad_mu - (1+mu)*A );\n  hess_u = ( tmp_u + transpose(tmp_u) + dot_prod(lambda,HuA)*hess_mu ) / denom;\n  Matrix3x3 tmp_v = outer_prod( grad_mu, VvA - dot_prod(O,VvA)*O )\n    + outer_prod( grad_v, mu*dot_prod(O,A)*O - dot_prod(lambda,A)*grad_mu - (1+mu)*A );\n  hess_v = ( tmp_v + transpose(tmp_v) + dot_prod(lambda,VvA)*hess_mu ) / denom;\n}\n", "meta": {"hexsha": "e13f7793227d3ad811652cacbae8c186f13d51bc", "size": 18119, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Camera/CAHVORModel.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Camera/CAHVORModel.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Camera/CAHVORModel.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 32.0123674912, "max_line_length": 108, "alphanum_fraction": 0.5988741101, "num_tokens": 6024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.04272219937472948, "lm_q1q2_score": 0.01919904172713839}}
{"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_GENERATION_HH\n#define GRAPH_GENERATION_HH\n\n#include <tuple>\n#include <boost/functional/hash.hpp>\n#include <map>\n#include <set>\n#include <iostream>\n\n#include \"graph_util.hh\"\n#include \"random.hh\"\n#include \"hash_map_wrap.hh\"\n\nnamespace graph_tool\n{\nusing namespace std;\nusing namespace boost;\n\n// desired vertex type, with desired j,k values and the index in the real graph\nstruct dvertex_t\n{\n    dvertex_t(): in_degree(0), out_degree(0) {}\n    dvertex_t(size_t in, size_t out): in_degree(in), out_degree(out) {}\n    dvertex_t(const pair<size_t,size_t>& deg): in_degree(deg.first),\n                                               out_degree(deg.second) {}\n    size_t index, in_degree, out_degree;\n    bool operator==(const dvertex_t& other) const {return other.index == index;}\n};\n\nsize_t hash_value(const dvertex_t& v)\n{\n    return v.index;\n}\n\n\n// used for verbose display\nvoid print_progress(size_t current, size_t total, stringstream& str)\n{\n    size_t atom = (total > 200) ? total/100 : 1;\n    if ( ( (current+1) % atom == 0) || (current + 1) == total)\n    {\n        for (size_t j = 0; j < str.str().length(); ++j)\n            cout << \"\\b\";\n        str.str(\"\");\n        str << current+1 << \" of \" << total << \" (\"\n            << (current+1)*100 / total << \"%)\";\n        cout << str.str() << flush;\n    }\n}\n\nvoid print_update(size_t current, stringstream& str)\n{\n    for (size_t j = 0; j < str.str().length(); ++j)\n        cout << \"\\b\";\n    for (size_t j = 0; j < str.str().length(); ++j)\n        cout << \" \";\n    for (size_t j = 0; j < str.str().length(); ++j)\n        cout << \"\\b\";\n    str.str(\"\");\n    str << current;\n    cout << str.str() << flush;\n}\n\n\n//\n// Generation strategies\n// =====================\n//\n// Directed and undirected graphs have different generation strategies, which\n// are defined in the classes below.\n\n//\n// Directed graph generation strategy\n//\n\nclass DirectedStrat\n{\npublic:\n    typedef pair<size_t, size_t> deg_t; // degree type\n\n    DirectedStrat(size_t N, bool no_parallel, bool no_self_loops)\n        : _N(N), _no_parallel(no_parallel), _no_self_loops(no_self_loops)\n    {\n        if (_no_parallel)\n            _max_deg = _no_self_loops ? _N - 1 : N;\n        else\n            _max_deg = numeric_limits<size_t>::max();\n    }\n\n    // check whether a degree sequence is graphical\n    template <class DegSequence>\n    bool is_graphical(DegSequence& d)\n    {\n        size_t one = _no_self_loops ? 1 : 0;\n\n        size_t sum_out_deg = 0;\n        size_t j = 0;\n        for(auto di = d.begin(); di != d.end(); ++di)\n        {\n            size_t out_deg = di->first.second;\n            size_t count = di->second;\n\n            j += count;\n            sum_out_deg += out_deg * count;\n\n            size_t sum_in_deg = 0;\n            auto dj_end = di; ++dj_end;\n            for(auto dj = d.begin(); dj != dj_end; ++dj)\n                sum_in_deg += min(dj->first.first, j - one) * dj->second;\n\n            size_t sum_rest = 0;\n            auto dj = di;\n            for(++dj; dj != d.end(); ++dj)\n                sum_rest += min(dj->first.first, j)*dj->second;\n\n            if (sum_out_deg > sum_in_deg + sum_rest)\n                return false;\n        }\n        return true;\n    }\n\n    // check whether a degree sequence is graphical, when parallel loops are\n    // allowed but self-loops are not\n    template <class DegSequence>\n    bool is_graphical_parallel(DegSequence& d)\n    {\n        size_t sum_in_deg = 0;\n        for(auto di = d.begin(); di != d.end(); ++di)\n            sum_in_deg += di->first.first * di->second;\n        for(auto di = d.begin(); di != d.end(); ++di)\n        {\n            if (di->first.second > sum_in_deg - di->first.first)\n                return false;\n        }\n        return true;\n    }\n\n    // sample the degrees of all the vertices\n    template <class DegSample>\n    size_t SampleDegrees(vector<dvertex_t>& vertices, DegSample& deg_sample,\n                         rng_t& rng, bool verbose)\n    {\n        stringstream str;\n        size_t sum_j=0, sum_k=0;\n        for(size_t i = 0; i < _N; ++i)\n        {\n            if (verbose)\n                print_progress(i, _N, str);\n            dvertex_t& v = vertices[i];\n            do\n            {\n                tie(v.in_degree, v.out_degree) = deg_sample(i);\n            }\n            while (_no_parallel &&\n                   (v.in_degree > _max_deg || v.out_degree > _max_deg));\n            sum_j += v.in_degree;\n            sum_k += v.out_degree;\n            if (_no_parallel || _no_self_loops)\n                _deg_seq[make_pair(v.in_degree, v.out_degree)]++;\n        }\n\n        if (verbose)\n        {\n            cout << \"\\nfixing average degrees. Total degree difference: \"\n                 << flush;\n                str.str(\"\");\n        }\n\n        // Sequence must be graphical. Re-sample random pairs until this holds\n        uniform_int_distribution<size_t> vertex_sample(0, _N-1);\n        size_t count = 0;\n        while(sum_j != sum_k || (_no_parallel && !is_graphical(_deg_seq)) ||\n              (_no_self_loops && !_no_parallel &&\n               !is_graphical_parallel(_deg_seq)))\n        {\n            size_t i = vertex_sample(rng);\n            dvertex_t& v = vertices[i];\n            if (_no_parallel || _no_self_loops)\n            {\n                auto iter = _deg_seq.find(make_pair(v.in_degree, v.out_degree));\n                iter->second--;\n                if (iter->second == 0)\n                    _deg_seq.erase(iter);\n            }\n\n            sum_j -= v.in_degree;\n            sum_k -= v.out_degree;\n            do\n            {\n                tie(v.in_degree, v.out_degree) = deg_sample(i);\n            }\n            while (_no_parallel &&\n                   (v.in_degree > _max_deg || v.out_degree > _max_deg));\n            sum_j += v.in_degree;\n            sum_k += v.out_degree;\n            if (_no_parallel || _no_self_loops)\n                _deg_seq[make_pair(v.in_degree, v.out_degree)]++;\n            if (verbose && (count % 100 == 0 || sum_j == sum_k))\n                print_update(min(sum_j-sum_k, sum_k-sum_j), str);\n            count++;\n        }\n        return sum_k;\n    }\n\n    struct deg_cmp\n    {\n        bool operator()(const deg_t& d1, const deg_t& d2) const\n        {\n            if (d1.second == d2.second)\n                return d1.first > d2.first;\n            return d1.second > d2.second;\n        }\n    };\n\nprivate:\n    size_t _N;\n    bool _no_parallel;\n    bool _no_self_loops;\n    size_t _max_deg;\n    map<deg_t, size_t, deg_cmp> _deg_seq;\n};\n\n//\n// Undirected graph generation strategy\n//\n\nclass UndirectedStrat\n{\npublic:\n    typedef size_t deg_t; // degree type\n\n    UndirectedStrat(size_t N, bool no_parallel, bool no_self_loops)\n        : _N(N), _no_parallel(no_parallel), _no_self_loops(no_self_loops)\n    {\n        if (_no_parallel)\n            _max_deg = (_no_self_loops) ? _N - 1 : N;\n        else\n            _max_deg = numeric_limits<size_t>::max();\n    }\n\n    // check whether a degree sequence is graphical\n    template <class DegSequence>\n    bool is_graphical(DegSequence& d)\n    {\n        size_t one = (_no_self_loops) ? 1 : 0;\n        size_t sum_deg = 0;\n        size_t j = 0;\n        for(auto di = d.begin(); di != d.end(); ++di)\n        {\n            j += di->second;\n            sum_deg += di->first * di->second;\n            size_t sum_rest = 0;\n            auto dj = di;\n            for(++dj; dj != d.end(); ++dj)\n                sum_rest += min(dj->first, j)*dj->second;\n            if (sum_deg > j*(j-one) + sum_rest)\n                return false;\n        }\n        return true;\n    }\n\n    // check whether a degree sequence is graphical, when parallel loops are\n    // allowed but self-loops are not\n    template <class DegSequence>\n    bool is_graphical_parallel(DegSequence& d)\n    {\n        size_t sum_deg = 0;\n        for(auto& di : d)\n            sum_deg += di.first * di.second;\n        for(auto& di : d)\n        {\n            if (di.first > sum_deg - di.first)\n                return false;\n        }\n        return true;\n    }\n\n    // samples the degress of all vertices\n    template <class DegSample>\n    size_t SampleDegrees(vector<dvertex_t>& vertices, DegSample& deg_sample,\n                         rng_t& rng, bool verbose)\n    {\n        stringstream str;\n        size_t sum_k=0;\n        sum_k = 0;\n        for(size_t i = 0; i < _N; ++i)\n        {\n            if (verbose)\n                print_progress(i, _N, str);\n            dvertex_t& v = vertices[i];\n            do\n            {\n                v.out_degree = deg_sample(i, true);\n            }\n            while (_no_parallel && v.out_degree > _max_deg);\n            sum_k += v.out_degree;\n            _deg_seq[v.out_degree]++;\n        }\n\n        if (verbose)\n        {\n            cout << \"\\nFixing degree sequence: \"\n                 << flush;\n            str.str(\"\");\n        }\n\n        // sum_k must be an even number (2*num_edges), and degree sequence must\n        // be graphical, if multiple edges are not allowed. Re-sample degrees\n        // until this holds.\n        uniform_int_distribution<size_t> vertex_sample(0, _N-1);\n        size_t count = 0;\n        while (sum_k % 2 != 0 || (_no_parallel && !is_graphical(_deg_seq)) ||\n               (_no_self_loops && !_no_parallel &&\n                !is_graphical_parallel(_deg_seq)))\n        {\n            size_t i = vertex_sample(rng);\n            dvertex_t& v = vertices[i];\n            if (_no_parallel || _no_self_loops)\n            {\n                auto iter = _deg_seq.find(v.out_degree);\n                iter->second--;\n                if(iter->second == 0)\n                    _deg_seq.erase(iter);\n            }\n            sum_k -= v.out_degree;\n            do\n            {\n                v.out_degree = deg_sample(i, true);\n            }\n            while (_no_parallel && (v.out_degree > _max_deg));\n            sum_k +=  v.out_degree;\n            if (_no_parallel || _no_self_loops)\n                _deg_seq[v.out_degree]++;\n            if (verbose && (count % 100 || sum_k % 2 == 0))\n                print_update(sum_k, str);\n            count++;\n        }\n        return sum_k/2;\n    }\n\nprivate:\n    size_t _N;\n    bool _no_parallel;\n    bool _no_self_loops;\n    size_t _max_deg;\n    map<size_t, size_t, greater<size_t> > _deg_seq;\n};\n\n//\n// Main Algorithm\n// ==============\n//\n// generates a directed or undirected graph with given degree distribution\n\ntemplate <class Cmp>\nstruct cmp_in\n{\n    bool operator()(const pair<size_t,size_t>& v1,\n                    const pair<size_t,size_t>& v2) const\n    {\n        if (v1.first == v2.first)\n            return cmp(v1.second, v2.second);\n        return cmp(v1.first, v2.first);\n    }\n    Cmp cmp;\n};\n\ntemplate <class Cmp>\nstruct cmp_out\n{\n    bool operator()(const pair<size_t,size_t>& v1,\n                    const pair<size_t,size_t>& v2) const\n    {\n        if (v1.second == v2.second)\n            return cmp(v1.first, v2.first);\n        return cmp(v1.second, v2.second);\n    }\n    Cmp cmp;\n};\n\ntemplate <class Graph>\npair<size_t, size_t> get_deg(dvertex_t& v, Graph& g)\n{\n    return make_pair(v.in_degree - in_degreeS()(vertex(v.index, g), g),\n                     v.out_degree - out_degree(vertex(v.index, g), g));\n}\n\ntemplate <class Graph>\nbool is_source(const pair<size_t, size_t>& deg)\n{\n    return deg.second > 0;\n}\n\ntemplate <class Graph>\nbool is_target(const pair<size_t, size_t>& deg)\n{\n    if (is_directed_::apply<Graph>::type::value)\n        return deg.first > 0;\n    else\n        return is_source<Graph>(deg);\n}\n\n\ntemplate <class Vset, class Targets, class Sources, class Graph>\nbool update_deg(size_t t_i, const pair<size_t, size_t>& deg, Vset& vset,\n                Targets& targets, Sources& sources, Graph&)\n{\n    if (is_source<Graph>(deg))\n        sources.insert(deg);\n    if (is_target<Graph>(deg))\n        targets.insert(deg);\n    vset[deg].push_back(t_i);\n    return true;\n}\n\nstruct gen_graph\n{\n    template <class Graph, class DegSample>\n    void operator()(Graph& g, size_t N, DegSample& deg_sample, bool no_parallel,\n                    bool no_self_loops, rng_t& rng, bool verbose, bool verify)\n        const\n    {\n        typename property_map<Graph,vertex_index_t>::type vertex_index =\n            get(vertex_index_t(), g);\n\n        // figure out the necessary strategy\n        typedef typename mpl::if_<typename is_directed_::apply<Graph>::type,\n                                  DirectedStrat,\n                                  UndirectedStrat>::type gen_strat_t;\n\n        gen_strat_t gen_strat(N, no_parallel, no_self_loops);\n        stringstream str; // used for verbose status\n\n        if (verbose)\n            cout << \"adding vertices: \" << flush;\n\n        vector<dvertex_t> vertices(N);\n        for(size_t i = 0; i < N; ++i)\n            vertices[i].index = vertex_index[add_vertex(g)];\n\n        // sample the N (j,k) pairs\n        size_t E = gen_strat.SampleDegrees(vertices, deg_sample, rng, verbose);\n\n        // source and target degree lists\n        typedef pair<size_t, size_t> deg_t;\n        set<deg_t, cmp_out<greater<size_t> > > sources;\n        set<deg_t, cmp_in<greater<size_t> > > targets;\n\n        // vertices with a given degree\n        unordered_map<deg_t, vector<size_t>> vset; // can't use gt_hash_map, as\n                                                   // internal pointers are\n                                                   // invalidated after insert\n\n        size_t num_e = 0;\n        for (size_t i = 0; i < vertices.size();  ++i)\n        {\n            deg_t deg = get_deg(vertices[i], g);\n\n            if (is_source<Graph>(deg))\n                sources.insert(deg);\n            if (is_target<Graph>(deg))\n                targets.insert(deg);\n            if (is_target<Graph>(deg) || is_source<Graph>(deg))\n                vset[deg].push_back(i);\n        }\n\n        if (verbose)\n        {\n            cout << endl << \"adding edges: \" << flush;\n            str.str(\"\");\n        }\n\n        vector<size_t> skip;\n\n        // connect edges: from sources with the largest in-degree to the ones\n        // with largest out-degree\n        while (!sources.empty())\n        {\n            // find source. The out-degree must be non-zero, and there must be a\n            // vertex with the chosen degree.\n            deg_t s_deg = *sources.begin();\n            auto sv_iter = vset.find(s_deg);\n            if (s_deg.second == 0 || sv_iter == vset.end() ||\n                sv_iter->second.empty())\n            {\n                sources.erase(sources.begin());\n                continue;\n            }\n\n            vector<size_t>& s_list = sv_iter->second;\n            size_t s_i = s_list.front();\n            typename graph_traits<Graph>::vertex_descriptor s =\n                vertex(vertices[s_i].index, g);\n\n            deg_t ns_deg = get_deg(vertices[s_i], g);\n            if (ns_deg != s_deg)\n            {\n                swap(s_list.back(), s_list.front());\n                s_list.pop_back();\n                update_deg(s_i, ns_deg, vset, targets, sources, g);\n                continue;\n            }\n\n            // find the targets.\n            // we will keep an iterator to the current target degree\n            auto t_iter = targets.begin();\n            auto v_iter = vset.find(*t_iter);\n            while (v_iter == vset.end() || v_iter->second.empty())\n            {\n                targets.erase(t_iter);\n                t_iter = targets.begin();\n                v_iter = vset.find(*t_iter);\n            }\n\n            skip.clear();\n            skip.push_back(s_i);\n\n            if (no_self_loops)\n            {\n                swap(s_list.back(), s_list.front());\n                s_list.pop_back();\n            }\n\n            while (s_deg.second > 0)\n            {\n                // assert(!targets.empty());\n                // assert(t_iter != targets.end());\n                while (v_iter == vset.end() || v_iter->second.empty())\n                {\n                    ++t_iter;\n                    v_iter = vset.find(*t_iter);\n                }\n\n                deg_t t_deg = *t_iter;\n\n                vector<size_t>& v_list = v_iter->second;\n\n                size_t t_i = v_list.front();\n\n                deg_t nt_deg = get_deg(vertices[t_i], g);\n                if (nt_deg != t_deg)\n                {\n                    swap(v_list.back(), v_list.front());\n                    v_list.pop_back();\n                    update_deg(t_i, nt_deg, vset, targets, sources, g);\n                    t_iter = targets.begin();\n                    v_iter = vset.find(*t_iter);\n                    continue;\n                }\n\n                // remove target from vertex list, and get new t_i\n                skip.push_back(t_i);\n\n                swap(v_list.back(), v_list.front());\n                v_list.pop_back();\n\n                typename graph_traits<Graph>::vertex_descriptor t =\n                    vertex(vertices[t_i].index, g);\n\n                if ((s == t) && (!graph_tool::is_directed(g) &&\n                                 s_deg.second < 2))\n                    continue;\n\n                add_edge(s, t, g);\n                s_deg = get_deg(vertices[s_i], g);\n\n                // if parallel edges are allowed, we should update the target\n                // list right away\n                if (!no_parallel)\n                {\n                    for (size_t i = 0; i < skip.size(); ++i)\n                    {\n                        if (no_self_loops && skip[i] == s_i)\n                            continue;\n                        update_deg(skip[i],\n                                   get_deg(vertices[skip[i]], g), vset,\n                                   targets, sources, g);\n                        t_iter = targets.begin();\n                        v_iter = vset.find(*t_iter);\n                    }\n                    skip.clear();\n                    if (no_self_loops)\n                        skip.push_back(s_i);\n                }\n                if (verbose)\n                    print_progress(num_e++, E, str);\n            }\n\n            if (!s_list.empty() && s_list.front() == s_i)\n            {\n                swap(s_list.back(), s_list.front());\n                s_list.pop_back();\n            }\n\n            // update modified degrees\n            for (size_t i = 0; i < skip.size(); ++i)\n                update_deg(skip[i],\n                           get_deg(vertices[skip[i]], g),\n                           vset, targets, sources, g);\n        }\n        if (verbose)\n            cout << endl;\n\n        if (verify)\n        {\n            for (size_t i = 0; i < vertices.size(); ++i)\n            {\n                deg_t dseq = make_pair(vertices[i].in_degree,\n                                       vertices[i].out_degree);\n                deg_t deg = make_pair(in_degreeS()(vertex(i, g), g),\n                                      out_degree(vertex(i, g), g));\n                if (deg != dseq)\n                    throw GraphException(\"Graph does not match the desired \"\n                                         \"sequence! Vertex \" +\n                                         lexical_cast<string>(i) +\n                                         \", wanted: \" +\n                                         lexical_cast<string>(dseq.first) +\n                                         \" \" +\n                                         lexical_cast<string>(dseq.second) +\n                                         \", got: \" +\n                                         lexical_cast<string>(deg.first) +\n                                         \" \" +\n                                         lexical_cast<string>(deg.second) +\n                                         \" This is a bug.\");\n            }\n        }\n    }\n};\n\n} // graph_tool namespace\n\n#endif // GRAPH_GENERATION_HH\n", "meta": {"hexsha": "43a751cc357508581c11e679d74c9092afa04f0d", "size": 20523, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/generation/graph_generation.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_generation.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_generation.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": 31.5738461538, "max_line_length": 80, "alphanum_fraction": 0.5030940896, "num_tokens": 4714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.042722197698843806, "lm_q1q2_score": 0.01919904160409636}}
{"text": "// Copyright © 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#include <fstream>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <vinecopulib/misc/tools_stl.hpp>\n#include <iostream>\n\nnamespace vinecopulib {\n\nnamespace tools_eigen {\n\n//! remove rows of a matrix which contain nan values\n//! @param x the matrix.\ninline void remove_nans(Eigen::MatrixXd &x)\n{\n    // if a row has nan, move it to the end\n    size_t last = x.rows() - 1;\n    for (size_t i = 0; i < last + 1; i++) {\n        if (x.row(i).array().isNaN().any())\n            x.row(i--).swap(x.row(last--));\n    }\n    // remove nan rows\n    x.conservativeResize(last + 1, x.cols());\n}\n\n//! remove rows of a matrix which contain nan values or have zero weight\n//! @param x the matrix.\n//! @param a vector of weights that is either empty or whose size is equal to\n//!   the number of columns of x.\ninline void remove_nans(Eigen::MatrixXd &x, Eigen::VectorXd &weights)\n{\n    if ((weights.size() > 0) & (weights.size() != x.rows()))\n        throw std::runtime_error(\"sizes of x and weights don't match.\");\n\n    // if a row has nan or weight is zero, move it to the end\n    size_t last = x.rows() - 1;\n    for (size_t i = 0; i < last + 1; i++) {\n        bool row_has_nan = x.row(i).array().isNaN().any();\n        if (weights.size() > 0) {\n            row_has_nan = row_has_nan | (boost::math::isnan)(weights(i));\n            row_has_nan = row_has_nan | (weights(i) == 0.0);\n        }\n        if (row_has_nan) {\n            if (weights.size() > 0)\n                std::swap(weights(i), weights(last));\n            x.row(i--).swap(x.row(last--));\n        }\n    }\n\n    // remove nan rows\n    x.conservativeResize(last + 1, x.cols());\n    if (weights.size() > 0)\n        weights.conservativeResize(last + 1);\n}\n\n//! check if all elements are contained in the unit cube.\n//! @param u copula data.\n//! @return `true` if all data lie in the unit cube; throws an error otherwise.\ninline bool check_if_in_unit_cube(const Eigen::MatrixXd &u)\n{\n    bool any_outside = (u.array() < 0.0).any() | (u.array() > 1.0).any();\n    if (any_outside) {\n        throw std::runtime_error(\"all data must be contained in [0, 1]^d.\");\n    }\n    return !any_outside;\n}\n\n\n//! swap the columns of a two-column matrix\n//! @param u the matrix.\n//! @return a new matrix v with `v.col(0) = u.col(1)`, `v.col(1) = u.col(0)`.\ninline Eigen::Matrix<double, Eigen::Dynamic, 2> swap_cols(\n    Eigen::Matrix<double, Eigen::Dynamic, 2> u)\n{\n    u.col(0).swap(u.col(1));\n    return u;\n}\n\n//! computes the inverse \\f$ f^{-1} \\f$ of a function \\f$ f \\f$ by the\n//! bisection method.\n//!\n//! @param x evaluation points.\n//! @param f the function to invert.\n//! @param lb lower bound.\n//! @param ub upper bound.\n//! @param n_iter the number of iterations for the bisection (defaults to 35,\n//! guaranteeing an accuracy of 0.5^35 ~= 6e-11).\n//!\n//! @return \\f$ f^{-1}(x) \\f$.\ninline Eigen::VectorXd invert_f(\n    const Eigen::VectorXd &x,\n    std::function<Eigen::VectorXd(const Eigen::VectorXd &)> f,\n    const double lb,\n    const double ub,\n    int n_iter)\n{\n    Eigen::VectorXd xl = Eigen::VectorXd::Constant(x.size(), lb);\n    Eigen::VectorXd xh = Eigen::VectorXd::Constant(x.size(), ub);\n    Eigen::VectorXd x_tmp = x;\n    Eigen::VectorXd fm(x.size());\n    for (int iter = 0; iter < n_iter; ++iter) {\n        x_tmp = (xh + xl) / 2.0;\n        fm = f(x_tmp) - x;\n        xl = (fm.array() < 0).select(x_tmp, xl);\n        xh = (fm.array() < 0).select(xh, x_tmp);\n    }\n    if (fm.array().isNaN().any()) {\n        size_t n = x.size();\n        for (size_t j = 0; j < n; j++) {\n            if ((boost::math::isnan)(fm(j))) {\n                x_tmp(j) = std::numeric_limits<double>::quiet_NaN();\n            }\n        }\n    }\n\n    return x_tmp;\n}\n\n//! expand a vector into a matrix with two columns where each row\n//! contains one combination of the vector elements\n//!\n//! @param grid_points the vector to expand.\ninline Eigen::Matrix<double, Eigen::Dynamic, 2> expand_grid(\n    const Eigen::VectorXd &grid_points)\n{\n    ptrdiff_t m = grid_points.size();\n    Eigen::Matrix<double, Eigen::Dynamic, 2> grid_2d(m * m, 2);\n    ptrdiff_t k = 0;\n    for (ptrdiff_t i = 0; i < m; ++i) {\n        for (ptrdiff_t j = 0; j < m; ++j) {\n            grid_2d(k, 0) = grid_points(i);\n            grid_2d(k, 1) = grid_points(j);\n            ++k;\n        }\n    }\n    return grid_2d;\n}\n\n//! reads data from a file to an Eigen matrix of integers.\n//!\n//! The function is currently **not safe** and may cause crashes when the\n//! arguments are specified incorrectly.\n//!\n//! @param filename the name of the file to read from.\n//! @param max_buffer_size the maximal buffer size.\ninline Eigen::Matrix <size_t, Eigen::Dynamic, Eigen::Dynamic> read_matxs(\n    const char *filename, int max_buffer_size)\n{\n    Eigen::MatrixXd temp = read_matxd(filename, max_buffer_size);\n    Eigen::Matrix <size_t, Eigen::Dynamic, Eigen::Dynamic> output = temp.cast<size_t>();\n    return output;\n}\n\n//! reads data from a file to an Eigen matrix of doubles.\n//!\n//! The function is currently **not safe** and may cause crashes when the\n//! arguments are specified incorrectly.\n//!\n//! @param filename the name of the file to read from.\n//! @param max_buffer_size the maximal buffer size.\ninline Eigen::MatrixXd read_matxd(const char *filename, int max_buffer_size)\n{\n    using namespace std;\n\n    int cols = 0, rows = 0;\n    double *buff = new double[max_buffer_size];\n\n    // Read numbers from file into buffer.\n    ifstream infile;\n    infile.open(filename);\n    while (!infile.eof()) {\n        string line;\n        getline(infile, line);\n\n        int temp_cols = 0;\n        stringstream stream(line);\n        while (!stream.eof()) {\n            stream >> buff[cols * rows + temp_cols++];\n        }\n        if (temp_cols == 0) {\n            continue;\n        }\n        if (cols == 0) {\n            cols = temp_cols;\n        }\n        rows++;\n    }\n\n    infile.close();\n\n    rows--;\n\n    // Populate matrix with numbers.\n    Eigen::MatrixXd result(rows, cols);\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++) {\n            result(i, j) = buff[cols * i + j];\n        }\n    }\n\n    delete[] buff;\n    return result;\n}\n\n//! @}\n}\n\n}\n", "meta": {"hexsha": "d82f29b8b2afec35148cc14c9c6936a3092a5ef9", "size": 6453, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/implementation/tools_eigen.ipp", "max_stars_repo_name": "covit2019/analysis_codes", "max_stars_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/implementation/tools_eigen.ipp", "max_issues_repo_name": "covit2019/analysis_codes", "max_issues_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/implementation/tools_eigen.ipp", "max_forks_repo_name": "covit2019/analysis_codes", "max_forks_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T12:59:17.000Z", "avg_line_length": 30.2957746479, "max_line_length": 88, "alphanum_fraction": 0.5991011932, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.05340333356619822, "lm_q1q2_score": 0.019191243315716602}}
{"text": "// (C) Copyright Renaud Detry   2007-2015.\n// Distributed under the GNU General Public License and under the\n// BSD 3-Clause License (See accompanying file LICENSE.txt).\n\n/** @file */\n\n#include <iostream>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/thread.hpp>\n\n#include <nuklei/Random.h>\n#include <nuklei/Common.h>\n#include <nuklei/Log.h>\n\n#include <boost/random.hpp>\n\nnamespace nuklei {\n\n// Either use GSL random gen, or Boost random gen\n//#define NUKLEI_USE_BOOST_RANDOM_GEN\n\n// Sync before accessing random gen?\n// -> NUKLEI_RANDOM_SYNC_OMP: use OMP exclusive access\n//    This one is obsolete, because when OMP is enabled, omp_get_thread_num\n//    allows Random methods to access thread-specific random gens.\n// -> NUKLEI_RANDOM_SYNC_MUTEX: use posix mutex\n//    This makes Nuklei much slower\n// -> NUKLEI_RANDOM_SYNC_NONE: default, use this on single-thread, or with OMP.\n  \n#define NUKLEI_RANDOM_SYNC_NONE\n\n#ifdef _OPENMP\n#include <omp.h>\n  static inline int nuklei_thread_num()\n  {\n    return omp_get_thread_num();\n  }\n  static inline int nuklei_max_threads()\n  {\n    // I had issues with omp_get_max_threads(), returning 1 while spawning\n    // more than one thread.\n    // I had this with static executables.\n    // I guess it could be a race condition.\n    // Let's just return a large number instead (who would have more than 1000\n    // procs anyway?)\n    //return omp_get_max_threads();\n    return 1024;\n  }\n#else\n  static inline int nuklei_thread_num()\n  {\n    return 0;\n  }\n  static inline int nuklei_max_threads()\n  {\n    return 1;\n  }\n#endif\n\n  \n  // bRandGens must be a pointer. If not, its construtor may be called after\n  // init() is called, which will destroy the bRandGens setup in init().\n  static std::vector<boost::mt19937>* bRandGens;\n  // Same holds for these:\n  static std::vector<gsl_rng*>* gRandGens;\n  static std::vector<boost::shared_ptr<boost::mutex> >* mutexes;\n  // Keep in mind that it's unsafe to store pointers in std::vectors because\n  // they could be discarted without being deallocated. Here it's fine as we\n  // won't be resizing or deleting the vector before the end if the program.\n  \n  bool Random::initialized_ = Random::init();\n  \n  bool Random::init()\n  {\n    unsigned seed = 0;\n\n    const char * envValPara = getenv(\"NUKLEI_PARALLELIZATION\");\n    if (envValPara != NULL)\n    {\n      std::string para(envValPara);\n      if (para == \"single\" || para == \"openmp\")\n      {\n        // all ok\n      }\n      else if (para == \"pthread\")\n      {\n#if defined(NUKLEI_RANDOM_SYNC_OMP) || defined(NUKLEI_RANDOM_SYNC_NONE) || !defined(NUKLEI_RANDOM_SYNC_MUTEX)\n        std::cout << \"NUKLEI_PARALLELIZATION is set to pthread. \"\n        \"You should manually undefine all NUKLEI_RANDOM_SYNC_* in Random.cpp, \"\n        \"and define NUKLEI_RANDOM_SYNC_MUTEX instead. Note that multithreading \"\n        \"will be slower than with OpenMP. \"\n        \"See http://renaud-detry.net/nuklei/group__faq.html\" << std::endl;\n        std::terminate();\n#endif\n      }\n      else\n      {\n        std::cout << \"Unknown value '\" << para << \"' for NUKLEI_PARALLELIZATION\"\n        \" env variable.\" << std::endl;\n        std::terminate();\n      }\n    }\n    \n    const char * envVal = getenv(\"NUKLEI_RANDOM_SEED\");\n    if (envVal != NULL)\n    {\n      const char * log = getenv(\"NUKLEI_LOG_LEVEL\");\n      if (log != NULL && numify<unsigned>(log) >= Log::INFO)\n        std::cout << \"export \" << \"NUKLEI_RANDOM_SEED\" << \"=\"\n        << numify<int>(envVal)\n        << \"\\n\";\n      double seed_d = numify<double>(envVal);\n      if (seed_d >= 0)\n        seed = numify<unsigned>(envVal);\n      else\n        seed = time(NULL)*getpid(); // Unsigned don't overflow, they wrap around\n    }\n    \n    bRandGens = new std::vector<boost::mt19937>(nuklei_max_threads());\n    gRandGens = new std::vector<gsl_rng*>(nuklei_max_threads(), NULL);\n    for (int i = 0; i < nuklei_max_threads(); i++)\n      gRandGens->at(i) = gsl_rng_alloc(gsl_rng_mt19937);\n    \n    mutexes = new std::vector<boost::shared_ptr<boost::mutex> >();\n    for (int i = 0; i < nuklei_max_threads(); i++)\n      mutexes->push_back(boost::shared_ptr<boost::mutex>(new boost::mutex()));\n    \n    Random::seed(seed);\n    return true;\n  }\n  \n  void Random::seed(unsigned s)\n  {\n    if (getenv(\"NUKLEI_RANDOM_SEED\") != NULL)\n    {\n      // Libraries Nuklei depends on may make use of random numbers.\n      // Let's make sure we seed those randomly as well.\n      ::srandom(s);\n      //BSD implementation of rand differs from random.\n      ::srand(s);\n    }\n    \n    for (int i = 0; i < bRandGens->size(); ++i)\n    {\n      bRandGens->at(i).seed(s+i);\n    }\n    for (int i = 0; i < gRandGens->size(); ++i)\n    {\n      gsl_rng_set(gRandGens->at(i), s+i+1); // +1 because GSL complains when seed == 0\n    }\n  }\n  \n  //This function returns a double precision floating point number\n  //uniformly distributed in the range [0,1). The range includes 0.0 but\n  //excludes 1.0.\n  double Random::uniform()\n  {\n    double r;\n#if defined(NUKLEI_RANDOM_SYNC_OMP)\n#  pragma omp critical(nuklei_randomRng)\n#elif defined(NUKLEI_RANDOM_SYNC_MUTEX)\n    boost::unique_lock<boost::mutex> lock(*mutexes->at(nuklei_thread_num()));\n#elif defined(NUKLEI_RANDOM_SYNC_NONE)\n#else\n#  error Undefined random sync method\n#endif\n#ifdef NUKLEI_USE_BOOST_RANDOM_GEN\n    {\n      boost::uniform_01<> dist;\n      boost::variate_generator<boost::mt19937&, boost::uniform_01<> >\n      die(bRandGens->at(nuklei_thread_num()), dist);\n      r = die();\n    }\n#else\n    r = gsl_rng_uniform(gRandGens->at(nuklei_thread_num()));\n#endif\n    return r;\n  }\n  \n  //This function returns a double precision floating point number\n  //uniformly distributed in the range [a,b). The range includes a but\n  //excludes b.\n  double Random::uniform(double a, double b)\n  {\n    NUKLEI_FAST_ASSERT(a < b);\n    return a + uniform()*(b-a);\n  }\n  \n  //This function returns a random integer from 0 to n-1 inclusive by\n  //scaling down and/or discarding samples from the generator r. All\n  //integers in the range [0,n-1] are produced with equal probability.\n  unsigned long int Random::uniformInt(unsigned long int n)\n  {\n    unsigned long int r;\n    // GSL has trouble with concurrent random number generation:\n    //   - if a single generator is used, it must be mutexed.\n    //   - using one random generator per thread is somehow very slow\n    // Random::uniformInt is used *a lot*, everytime a KernelCollection is\n    // iterated in random order. Using a mutex here entirely breaks\n    // multithreading (n threads on n cpus takes as much time as the same work\n    // on a single cpu).  Multithreading will only be fast if done through\n    // OpenMP. This is because it is hard to map pthreads to a\n    // number. boost::thread::id could be used to implement nuklei_thread_num()\n    // (todo?), but random generators could not be cleaned when a thread exits.\n#if defined(NUKLEI_RANDOM_SYNC_OMP)\n#  pragma omp critical(nuklei_randomRng)\n#elif defined(NUKLEI_RANDOM_SYNC_MUTEX)\n    boost::unique_lock<boost::mutex> lock(*mutexes->at(nuklei_thread_num()));\n#elif defined(NUKLEI_RANDOM_SYNC_NONE)\n#else\n#  error Undefined random sync method\n#endif\n#ifdef NUKLEI_USE_BOOST_RANDOM_GEN\n    {\n      boost::uniform_int<unsigned long> dist(0, n-1);\n      boost::variate_generator<boost::mt19937&, boost::uniform_int<unsigned long> >\n      die(bRandGens->at(nuklei_thread_num()), dist);\n      r = die();\n    }\n#else\n    r = gsl_rng_uniform_int(gRandGens->at(nuklei_thread_num()), n);\n#endif\n    return r;\n  }\n  \n  double Random::triangle(double b)\n  {\n    double r;\n#if defined(NUKLEI_RANDOM_SYNC_OMP)\n#  pragma omp critical(nuklei_randomRng)\n#elif defined(NUKLEI_RANDOM_SYNC_MUTEX)\n    boost::unique_lock<boost::mutex> lock(*mutexes->at(nuklei_thread_num()));\n#elif defined(NUKLEI_RANDOM_SYNC_NONE)\n#else\n#  error Undefined random sync method\n#endif\n    {\n      boost::triangle_distribution<> dist(-b/2, 0, b/2);\n      boost::variate_generator<boost::mt19937&, boost::triangle_distribution<> >\n      die(bRandGens->at(nuklei_thread_num()), dist);\n      r = die();\n    }\n    return r;\n  }\n  \n  //This function returns a Gaussian random variate, with mean zero and\n  //standard deviation sigma. Use the transformation z = \\mu + x on the\n  //numbers returned by gsl_ran_gaussian to obtain a Gaussian distribution\n  //with mean \\mu.\n  double Random::gaussian(double sigma)\n  {\n    double r;\n#if defined(NUKLEI_RANDOM_SYNC_OMP)\n#  pragma omp critical(nuklei_randomRng)\n#elif defined(NUKLEI_RANDOM_SYNC_MUTEX)\n    boost::unique_lock<boost::mutex> lock(*mutexes->at(nuklei_thread_num()));\n#elif defined(NUKLEI_RANDOM_SYNC_NONE)\n#else\n#  error Undefined random sync method\n#endif\n#ifdef NUKLEI_USE_BOOST_RANDOM_GEN\n    {\n      boost::normal_distribution<> dist(0, sigma);\n      boost::variate_generator<boost::mt19937&, boost::normal_distribution<> >\n      die(bRandGens->at(nuklei_thread_num()), dist);\n      r = die();\n    }\n#else\n    r = gsl_ran_gaussian(gRandGens->at(nuklei_thread_num()), sigma);\n#endif\n    return r;\n  }\n  \n  double Random::beta(double a, double b)\n  {\n    double r;\n#if defined(NUKLEI_RANDOM_SYNC_OMP)\n#  pragma omp critical(nuklei_randomRng)\n#elif defined(NUKLEI_RANDOM_SYNC_MUTEX)\n    boost::unique_lock<boost::mutex> lock(*mutexes->at(nuklei_thread_num()));\n#elif defined(NUKLEI_RANDOM_SYNC_NONE)\n#else\n#  error Undefined random sync method\n#endif\n    r = gsl_ran_beta(gRandGens->at(nuklei_thread_num()), a, b);\n    return r;\n  }\n  \n  Vector2 Random::uniformDirection2d()\n  {\n    Vector2 dir;\n#if defined(NUKLEI_RANDOM_SYNC_OMP)\n#  pragma omp critical(nuklei_randomRng)\n#elif defined(NUKLEI_RANDOM_SYNC_MUTEX)\n    boost::unique_lock<boost::mutex> lock(*mutexes->at(nuklei_thread_num()));\n#elif defined(NUKLEI_RANDOM_SYNC_NONE)\n#else\n#  error Undefined random sync method\n#endif\n#ifdef NUKLEI_USE_BOOST_RANDOM_GEN\n    {\n      const int dim = 2;\n      typedef boost::uniform_on_sphere<double, std::vector<double> > dist_t;\n      dist_t dist(dim);\n      boost::variate_generator<boost::mt19937&, dist_t >\n      die(bRandGens->at(nuklei_thread_num()), dist);\n      std::vector<double> r = die();\n      dir.X() = r.at(0);\n      dir.Y() = r.at(1);\n    }\n#else\n    gsl_ran_dir_2d(gRandGens->at(nuklei_thread_num()), &dir.X(), &dir.Y());\n#endif\n    return dir;\n  }\n  \n  Vector3 Random::uniformDirection3d()\n  {\n    Vector3 dir;\n#if defined(NUKLEI_RANDOM_SYNC_OMP)\n#  pragma omp critical(nuklei_randomRng)\n#elif defined(NUKLEI_RANDOM_SYNC_MUTEX)\n    boost::unique_lock<boost::mutex> lock(*mutexes->at(nuklei_thread_num()));\n#elif defined(NUKLEI_RANDOM_SYNC_NONE)\n#else\n#  error Undefined random sync method\n#endif\n#ifdef NUKLEI_USE_BOOST_RANDOM_GEN\n    const int dim = 3;\n    typedef boost::uniform_on_sphere<double, std::vector<double> > dist_t;\n    dist_t dist(dim);\n    boost::variate_generator<boost::mt19937&, dist_t >\n    die(bRandGens->at(nuklei_thread_num()), dist);\n    std::vector<double> r = die();\n    dir.X() = r.at(0);\n    dir.Y() = r.at(1);\n    dir.Z() = r.at(2);\n#else\n    gsl_ran_dir_3d(gRandGens->at(nuklei_thread_num()), &dir.X(), &dir.Y(), &dir.Z());\n#endif\n    return dir;\n  }\n  \n  Quaternion Random::uniformQuaternion()\n  {\n    // See Kuffner 2004 and Shoemake 1992.\n    // A supposably \"slightly faster\" way could be read from\n    // http://planning.cs.uiuc.edu/node198.html and Arvo 1992, but\n    // would need to be tested.\n    // Also, how would gsl_ran_dir_nd perform?\n    \n#if defined(NUKLEI_RANDOM_QUATERNION_MARSAGLIA_1972)\n    coord_t x1, y1, s1, x2, y2, s2;\n    for (;;)\n    {\n      x1 = uniform(-1, 1);\n      y1 = uniform(-1, 1);\n      s1 = x1*x1 + y1*y1;\n      if (s1 < 1) break;\n    }\n    for (;;)\n    {\n      x2 = uniform(-1, 1);\n      y2 = uniform(-1, 1);\n      s2 = x2*x2 + y2*y2;\n      if (s2 < 1) break;\n    }\n    coord_t root = std::sqrt( (1-s1)/s2 );\n    Quaternion u(x1,\n                 y1,\n                 x2 * root,\n                 y2 * root);\n    return q;\n#elif defined(NUKLEI_RANDOM_QUATERNION_GAUSSIAN_PROJ)\n    // comparable to gsl_ran_dir_nd\n    Quaternion u(gaussian(1),\n                 gaussian(1),\n                 gaussian(1),\n                 gaussian(1));\n    u.Normalize();\n    return u;\n#else // Fastest method (although MARSAGLIA is comparable)\n    coord_t s = static_cast<coord_t>(uniform());\n    //assert(s <= 1 && s >= 0);\n    coord_t s1 = std::sqrt(1-s);\n    coord_t s2 = std::sqrt(s);\n    coord_t t1 = 2 * M_PI * static_cast<coord_t>(uniform());\n    coord_t t2 = 2 * M_PI * static_cast<coord_t>(uniform());\n    Quaternion u(std::cos(t2) * s2,\n                 std::sin(t1) * s1,\n                 std::cos(t1) * s1,\n                 std::sin(t2) * s2);\n    //assert(nuklei_wmf::Math<coord_t>::FAbs(u.Length()-1) < 1e-6);\n    return u;\n#endif\n  }\n  \n  void Random::printRandomState()\n  {\n    NUKLEI_INFO(\"Random state: \" <<\n                NUKLEI_NVP(random()) <<\n                \"\\n              \" << NUKLEI_NVP(rand()) <<\n                \"\\n              \" << NUKLEI_NVP(Random::uniformInt(1000000)) <<\n                \"\\n              \" << NUKLEI_NVP(Random::uniform()));\n  }\n  \n}\n", "meta": {"hexsha": "4dc6f20c679a66b5284ccce7a9d7ed20c2521fb5", "size": 13116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libnuklei/base/Random.cpp", "max_stars_repo_name": "renauddetry/nuklei", "max_stars_repo_head_hexsha": "5c23b527904bcee66cc0602b45f9f3e3b9743584", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libnuklei/base/Random.cpp", "max_issues_repo_name": "renauddetry/nuklei", "max_issues_repo_head_hexsha": "5c23b527904bcee66cc0602b45f9f3e3b9743584", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libnuklei/base/Random.cpp", "max_forks_repo_name": "renauddetry/nuklei", "max_forks_repo_head_hexsha": "5c23b527904bcee66cc0602b45f9f3e3b9743584", "max_forks_repo_licenses": ["BSD-3-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.9124087591, "max_line_length": 109, "alphanum_fraction": 0.6540866118, "num_tokens": 3729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.05033063259747689, "lm_q1q2_score": 0.019187022635867135}}
{"text": "#pragma once\n#include <simcem/enum.hpp>\n#include <simcem/config.hpp>\n#include <boost/algorithm/string.hpp>\n#include <stator/symbolic/symbolic.hpp>\n#include <algorithm>\n\nnamespace simcem {\n  struct Reference_t : Enum<Reference_t> {\n    using Enum<Reference_t>::Enum;\n    enum { Elements298, Elements273, Elements, Self };\n    static const constexpr char* const strings[] = {\"Elements298\", \"Elements273\", \"Elements\", \"Self\"};\n  };\n\n  struct Property_t : Enum<Property_t> {\n    using Enum<Property_t>::Enum;\n    enum { vc, pc, AcentricFactor, Tc};\n    static const constexpr char* const strings[] = {\"vc\", \"pc\", \"AcentricFactor\", \"Tc\"};\n  };\n  \n  struct Objective_t : Enum<Objective_t> {\n    using Enum<Objective_t>::Enum;\n    enum { G, H, negS, S, U, A, p, V, T, Cp, Cv, dynvisc, thermcond, density};\n    static const constexpr char* const strings[] = {\"G\", \"H\", \"negS\", \"S\", \"U\", \"A\", \"p\", \"V\", \"T\", \"Cp\", \"Cv\", \"dynvisc\", \"thermcond\", \"density\"};\n  };\n\n  struct T_unit_t : Enum<T_unit_t> {\n    using Enum<T_unit_t>::Enum;\n    enum { K, C, F, R };\n    static const constexpr char* const strings[] = {\"K\", \"C\", \"F\", \"R\"};\n    inline double scale() const {\n      static constexpr double data[] = {1.0, 1.0, 5.0/9.0, 5.0/9.0};\n      return data[_value];\n    }\n    inline double origin() const {\n      static constexpr double data[] = {0, 273.15, 273.15 - 32.0 * 5.0 / 9.0, 0};\n      return data[_value];\n    }\n  };\n\n  struct Q_unit_t : Enum<Q_unit_t> {\n    using Enum<Q_unit_t>::Enum;\n    enum { mol, kmol, g, kg, lb};\n    static const constexpr char* const strings[] = {\"mol\", \"kmol\", \"g\", \"kg\", \"lb\"};\n    inline double scale() const {\n      static constexpr double data[] = {1.0, 1000.0, 1e-3, 1, 0.45359237};\n      return data[_value];\n    }\n  };\n\n  struct E_unit_t : Enum<E_unit_t> {\n    using Enum<E_unit_t>::Enum;\n    enum { J, kJ, cal, kcal };\n    static const constexpr char* const strings[] = {\"J\", \"kJ\", \"cal\", \"kcal\"};\n    inline double scale() const {\n      static constexpr double data[] = {1.0, 1000.0, 4.184, 4184.0};\n      return data[_value];\n    }\n  };\n\n  struct P_unit_t : Enum<P_unit_t> {\n    using Enum<P_unit_t>::Enum;\n    enum { Pa, bar, at, atm, torr, psi };\n    static const constexpr char* const strings[] = {\"Pa\", \"bar\", \"at\", \"atm\", \"torr\", \"psi\"};\n    inline double scale() const {\n      static constexpr double data[] = {1.0, 1e5, 9.80665e4, 1.01325e5, 101325.0/760, 6.8948e3 };\n      return data[_value];\n    }\n  };\n\n  struct L_unit_t : Enum<L_unit_t> {\n    using Enum<L_unit_t>::Enum;\n    enum { m, cm, mm, ft, inches};\n    static const constexpr char* const strings[] = {\"m\", \"cm\", \"mm\", \"ft\", \"inches\"};\n    inline double scale() const {\n      static constexpr double data[] = {1.0, 0.01, 0.001, 0.3048, 0.3048/12};\n      return data[_value];\n    }\n  };\n  \n  struct Data {\n    Data():\n      _T(\"K\"),\n      _Q(\"mol\"),\n      _E(\"J\"),\n      _P(\"Pa\"),\n      _L(\"m\"),\n      _mass(0)\n    {}\n    \n    void xml(stator::xml::Node node) const {      \n      if (!_source.empty())\n\tnode.add_attribute(\"Source\", _source);\n      if (_T != T_unit_t::K)\n\tnode.add_attribute(\"TUnit\", std::string(_T));\n      if (_Q != Q_unit_t::mol)\n\tnode.add_attribute(\"QUnit\", std::string(_Q));\n      if (_E != E_unit_t::J)\n\tnode.add_attribute(\"EUnit\", std::string(_E));\n      if (_P != P_unit_t::Pa)\n\tnode.add_attribute(\"PUnit\", std::string(_P));\n      if (_L != L_unit_t::m)\n\tnode.add_attribute(\"LUnit\", std::string(_L));\n\n      for (const auto& comment : _comments) {\n\t//Don't output empty comments\n\tif (stator::strip(comment._text).empty() &&\n\t    (stator::strip(comment._src).empty() || (stator::strip(comment._src) == stator::strip(_source))))\n\t    continue;\n\tauto comnode = node.add_node(\"Comment\");\n\tif (!comment._src.empty())\n\t  comnode.add_attribute(\"Source\", comment._src);\n\tcomnode = comment._text;\n      }\n    }\n\n    Data(stator::xml::Node node):\n      _T(\"K\"),\n      _Q(\"mol\"),\n      _E(\"J\"),\n      _P(\"Pa\"),\n      _L(\"m\"),\n      _mass(0)\n    {\n      //Only load values if present\n      for (stator::xml::Node comnode = node.findNode(\"Comment\"); comnode.valid(); ++comnode) {\n\tstd::string src;\n\tif (comnode.hasAttribute(\"Source\"))\n\t  src = comnode.getAttribute(\"Source\").as<std::string>();\n\t_comments.emplace_back(src, comnode);\n      }\n      \n      if (node.hasAttribute(\"Source\"))\n\t_source = node.getAttribute(\"Source\").as<std::string>();\n\n      if (node.hasAttribute(\"TUnit\"))\n\t_T = T_unit_t(node.getAttribute(\"TUnit\"));\n      if (node.hasAttribute(\"QUnit\"))\n\t_Q = Q_unit_t(node.getAttribute(\"QUnit\"));\n      if (node.hasAttribute(\"EUnit\"))\n\t_E = E_unit_t(node.getAttribute(\"EUnit\"));\n      if (node.hasAttribute(\"PUnit\"))\n\t_P = P_unit_t(node.getAttribute(\"PUnit\"));\n      if (node.hasAttribute(\"LUnit\"))\n\t_L = L_unit_t(node.getAttribute(\"LUnit\"));\n    }\n\n    Data(std::string comment, std::string source,\n\t T_unit_t Tunit, Q_unit_t Qunit, E_unit_t Eunit, P_unit_t Punit, L_unit_t Lunit):\n      _comments({{std::string(\"\"),comment}}),\n      _source(source),\n      _T(Tunit), _Q(Qunit), _E(Eunit), _P(Punit), _L(Lunit),\n      _mass(0)\n    {}\n\n    double normalise_units(Objective_t variable, double value) const {\n      const double origin = (variable == Objective_t::T) ? _T.origin() : 0.0;\n      return value * scale(variable) + origin;\n    }\n\n    double restore_units(Objective_t variable, double value) const {\n      const double origin = (variable == Objective_t::T) ? _T.origin() : 0.0;\n      return (value - origin) / scale(variable);\n    }\n    \n    double scale(Objective_t variable) const {\n      double scale = 1;\n\n      double inv_qscale = 1.0 / _Q.scale();\n      if ((_Q == Q_unit_t::g) || (_Q == Q_unit_t::kg) || (_Q == Q_unit_t::lb)) {\n\tif (_mass == 0)\n\t  stator_throw() << \"Cannot use Isobars with mass units without first registering them to a phase.\";\n\tinv_qscale *= _mass;\n      }\n      \n      switch (variable) {\n      case Objective_t::G:\n      case Objective_t::H:\n      case Objective_t::U:\n      case Objective_t::A:\n\treturn _E.scale() * inv_qscale;\n      case Objective_t::negS:\n      case Objective_t::S:\n      case Objective_t::Cp:\n      case Objective_t::Cv:\n\treturn _E.scale() * inv_qscale / _T.scale();\n      case Objective_t::T:\n\treturn _T.scale();\n      case Objective_t::p:\n\treturn _P.scale(); \n      case Objective_t::V:\n\treturn std::pow(_L.scale(), 3) * inv_qscale;\n      case Objective_t::dynvisc:\n\treturn _P.scale(); //i.e. Pa s, but the time scale is always seconds!\n      case Objective_t::thermcond:\n\treturn _E.scale() / _L.scale() / _T.scale();\n      case Objective_t::density:\n\treturn 1.0 / (inv_qscale * std::pow(_L.scale(), 3));\n      default:\n\tstator_throw() << \"Can't handle units for this yet \" + std::string(variable);\n      };\n      \n      return scale;\n    }\n\n    std::string LaTeX_units(Objective_t variable) const {\n      auto wrapunit = [](std::string u) { return \"\\\\mathrm{\"+u+\"}\"; };\n      switch (variable) {\n      case Objective_t::G:\n      case Objective_t::H:\n      case Objective_t::U:\n      case Objective_t::A:\n\treturn wrapunit(_E) + \"\\\\,\" + wrapunit(_Q)+\"^{-1}\";\n      case Objective_t::negS:\n      case Objective_t::S:\n      case Objective_t::Cp:\n      case Objective_t::Cv:\n\treturn wrapunit(_E) + \"\\\\,\" + wrapunit(_Q)+\"^{-1}\" + \"\\\\,\" + wrapunit(_T)+\"^{-1}\";\n      case Objective_t::T:\n\treturn wrapunit(_T);\n      case Objective_t::p:\n\treturn wrapunit(_P); \n      case Objective_t::V:\n\treturn wrapunit(_L)+\"^3\" + \"\\\\,\" + wrapunit(_Q)+\"^{-1}\";\n      case Objective_t::dynvisc:\n\treturn wrapunit(_P)+\"\\\\,\"+wrapunit(\"s\");\n      case Objective_t::thermcond:\n\treturn wrapunit(_E)+\"\\\\,\"+wrapunit(_L)+\"^{-1}\\\\,\"+wrapunit(_T)+\"^{-1}\";\n      case Objective_t::density:\n\treturn wrapunit(_Q)+\"\\\\,\"+wrapunit(_L)+\"^{-3}\";\n      default:\n\tstator_throw() << \"Can't handle units for this yet \" + std::string(variable);\n      }\n    }\n    \n    double normalise_units(Property_t variable, double value) const {\n      const double origin = (variable == Property_t::Tc) ? _T.origin() : 0.0;\n      return value * scale(variable) + origin;\n    }\n\n    double restore_units(Property_t variable, double value) const {\n      const double origin = (variable == Property_t::Tc) ? _T.origin() : 0.0;\n      return (value - origin) / scale(variable);\n    }\n    \n    double scale(Property_t variable) const {\n      switch (variable) {\n      case Property_t::vc:\n\treturn std::pow(_L.scale(), 3) / _Q.scale();\t\n      case Property_t::Tc:\n\treturn _T.scale();\n      case Property_t::AcentricFactor:\n\treturn 1.0;\n      case Property_t::pc:\n\treturn _P.scale();\n      default:\n\tstator_throw() << \"Can't handle units for this yet \" + std::string(variable);\n      };\n    }\n\n    std::string LaTeX_units(Property_t variable) const {\n      auto wrapunit = [](std::string u) { return \"\\\\mathrm{\"+u+\"}\"; };\n      switch (variable) {\n      case Property_t::vc:\n\treturn wrapunit(_L)+\"^3\\\\,\"+wrapunit(_Q)+\"^{-1}\";\n      case Property_t::Tc:\n\treturn wrapunit(_T);\n      case Property_t::AcentricFactor:\n\treturn \"\";\n      case Property_t::pc:\n\treturn wrapunit(_P);\n      default:\n\tstator_throw() << \"Can't handle units for this yet \" + std::string(variable);\n      }\n    }\n\n    void setMass(double mass) { _mass = mass; }\n\n    std::string getSource() { return _source; }\n\n    bool operator==(const Data& d) const {\n      return (_comments == d._comments)\n\t&& (_source == d._source)\n\t&& (_T == d._T)\n\t&& (_Q == d._Q)\n\t&& (_E == d._E)\n\t&& (_P == d._P)\n\t&& (_L == d._L)\n\t&& (_mass == d._mass)\n\t;\n    }\n\n    struct Comment {\n      Comment() {}\n      \n      Comment(std::string src, std::string text):\n\t_src(src), _text(text)\n      {}\n      \n      std::string _src;\n      std::string _text;\n      bool operator==(const Comment& b) const {\n\treturn (_src == b._src) && (_text == b._text);\n      }\n    };\n    \n    std::vector<Comment> _comments;\n    std::string _source;\n    T_unit_t _T;\n    Q_unit_t _Q;\n    E_unit_t _E;\n    P_unit_t _P;\n    L_unit_t _L;\n    double _mass;\n  };\n\n  /*! \\brief Data structure for a phase of a particular molecule. */\n  struct Curve : Data {\n    Curve(std::string comment, std::string source, Objective_t variable, Reference_t reference, Objective_t xvar,\n\t  T_unit_t Tunit, Q_unit_t Qunit, E_unit_t Eunit, P_unit_t Punit, L_unit_t Lunit):\n      Data(comment, source, Tunit, Qunit, Eunit, Punit, Lunit),\n      _xvar(xvar),\n      _variable(variable),\n      _reference(reference)\n    {}\n      \n    Curve(Node xml, Objective_t xvar):\n      Data(xml),\n      _xvar(xvar),\n      _variable(xml.getAttribute(\"Variable\")),\n      _reference(xml.getAttribute(\"Reference\"))\n    {\n      if (xml.hasAttribute(\"Error\"))\n\t_error = xml.getAttribute(\"Error\");\n    }\n\n    virtual ~Curve() {}\n\t  \n    void xml(stator::xml::Node node) const {\n      node.add_attribute(\"Variable\", std::string(_variable));\n\n      if (!_error.empty())\n\tnode.add_attribute(\"Error\", _error);\n      \n      Data::xml(node);\n\n      node.add_attribute(\"Reference\", std::string(_reference));\n      xml_extended(node);\n    }\n    \n    bool inRange(double x) const {\n      return (x >= xmin()) && (x <= xmax());\n    }\n\n    virtual double xmin() const = 0;\n    virtual double xmax() const = 0;\n    \n    virtual sym::Expr getFunction() const = 0;\n    \n    virtual void xml_extended(Node) const = 0;\n\n    Objective_t _xvar;\n    Objective_t _variable;\n    Reference_t _reference;\n    double _mass;\n    std::string _error;\n\n    Objective_t getVariable() const { return _variable; }\n    \n    static shared_ptr<Curve> load(Node, Objective_t);\n  };\n\n      \n  struct FunctionCurve: public Curve {\n    struct ShomateTerm {\n      ShomateTerm(double c, double p): C(c), power(p) {}\n      bool operator==(const ShomateTerm&c) const { return (c.C == C) && (power == c.power); }\n      double C; double power; };\n    \n    static std::string Shomate(const std::vector<ShomateTerm>& terms, double HConst = 0, double SConst = 0) {\n      std::string input;\n      \n      static auto signwrap = [](std::string a) { return (((a[0] != '-') && (a[0] != '+')) ? \"+\" : \"\") + a;  };\n      \n      for (const auto& t : terms) {\n\tstd::string coeff = signwrap(stator::repr(t.C));\n\tif (t.power == -1)\n\t  input = input + coeff + \"*(ln(T)+1)\";\n\telse if (t.power == 0)\n\t  input = input + coeff + \"*T*(1-ln(T))\";\n\telse\n\t  input = input + signwrap(stator::repr(-t.C / (t.power * (t.power + 1))))+\"*T^\"+stator::repr(t.power+1);\n      }\n\n      if (HConst)\n\tinput = input + \"+\" + stator::repr(HConst);\n\n      if (SConst)\n\tinput = input + \"-T*\" + stator::repr(SConst);\n\n      return input;\n    }\n    \n    \n    static std::string parseOldXML(Node xml) {\n      if (xml.getAttribute(\"Type\").as<std::string>() == \"Shomate\") {\n\tstd::vector<ShomateTerm> terms;\n\t\n\tfor (Node tnode = xml.findNode(\"Term\"); tnode.valid(); ++tnode) {\n\t  const std::string type = tnode.getAttribute(\"Type\");\n\t  if (type.substr(1,1) != \"^\") stator_throw() << \"Shomate only supports polynomial terms\";\n\t  double C = tnode.getAttribute(\"C\").as<double>();\n\t  double power = boost::lexical_cast<double>(tnode.getAttribute(\"Type\").as<std::string>().substr(2));\n\t  terms.push_back(ShomateTerm{C, power});\n\t}\n\n\tdouble HConst = 0, SConst = 0;\n\tif (xml.hasNode(\"HConst\"))\n\t  HConst = xml.getNode(\"HConst\").getAttribute(\"Value\").as<double>();\n\tif (xml.hasNode(\"SConst\"))\n\t  SConst = xml.getNode(\"SConst\").getAttribute(\"Value\").as<double>();\n\n\treturn Shomate(terms, HConst, SConst);\n      }\n      \n      static auto signwrap = [](std::string a) { return (((a[0] != '-') && (a[0] != '+')) ? \"+\" : \"\") + a;  };\n      \n      std::string input = \"\";\n      if (xml.hasNode(\"Function\"))\n\tinput = stator::strip(xml.getNode(\"Function\").getValue());\n      \n      for (Node tnode = xml.findNode(\"Term\"); tnode.valid(); ++tnode) {\n\tconst std::string type = tnode.getAttribute(\"Type\");\n\tstd::string s_C = tnode.getAttribute(\"C\").as<std::string>();\n\ts_C = signwrap(s_C);\n\t\n\tif (type.substr(1,1) == \"^\") {\n\t  std::string s_power = tnode.getAttribute(\"Type\").as<std::string>().substr(2);\n\t  input = input + s_C + \"*T^\" + s_power;\n\t} else if (type == \"lnx\") {\n\t  input = input + s_C +\"*ln(T)\";\n\t} else if (type == \"xlnx\") {\n\t  input = input + s_C + \"*T*ln(T)\";\n\t} else if (type == \"exp\") {\n\t  input = input + s_C + \"*exp(\"+parseOldXML(tnode)+\")\";\n\t} else\n\t  stator_throw() << \"Unknown term type\";\n      }\n      \n      return input;\n    }\n    \n    FunctionCurve(Node xml, Objective_t xvar):\n      Curve(xml, xvar),\n      _x_min(xml.getAttribute(\"xMin\").as<double>()),\n      _x_max(xml.getAttribute(\"xMax\").as<double>())\n    {\n      sym::Var<sym::vidx<'T'>> T;\n      \n      _f = sym::Expr(parseOldXML(xml));\n      auto df = sym::simplify(sym::derivative(_f, T));\n\n      if (xml.getAttribute(\"Type\").as<std::string>() == \"Shomate\") {\n\tdouble Tref = 298.15;\n\tif (xml.hasNode(\"TRef\"))\n\t  Tref = xml.getNode(\"TRef\").getAttribute(\"Value\").as<double>();\n\t\n\tif (xml.hasNode(\"HRef\") && xml.hasNode(\"SRef\")) {\n\t  auto H_Ref = xml.getNode(\"HRef\").getAttribute(\"Value\").as<double>();\n\t  auto S_Ref = xml.getNode(\"SRef\").getAttribute(\"Value\").as<double>();\n\n\t  auto G_Shift = sym::sub(_f, T = Tref);\n\t  auto S_Shift = sym::sub(df, T = Tref);\n\n\t  _f = _f + H_Ref - G_Shift + Tref * S_Shift - T * (S_Shift + S_Ref);\n\t}\n      }\n    }\n\n    virtual double xmin() const {\n      return normalise_units(_xvar, _x_min);\n    }\n    \n    virtual double xmax() const {\n      return normalise_units(_xvar, _x_max);\n    }\n\t\n    FunctionCurve(double xmin, double xmax, std::string comment, std::string source, Objective_t variable, Reference_t reference,\n\t\t  Objective_t xvar,\n\t\t  T_unit_t Tunit, Q_unit_t Qunit, E_unit_t Eunit, P_unit_t Punit, L_unit_t Lunit, sym::Expr f\n\t\t  ):\n      Curve(comment, source, variable, reference, xvar, Tunit, Qunit, Eunit, Punit, Lunit),\n      _x_min(xmin), _x_max(xmax), _f(f)\n    {}\n\n    virtual void xml_extended(Node xml) const {\n      xml.add_attribute(\"Type\", \"Function\");\n      xml.add_attribute(\"xMin\", _x_min);\n      xml.add_attribute(\"xMax\", _x_max);\n      xml.add_node(\"Function\") = stator::repr(_f);\n    }\n\n    virtual sym::Expr getFunction() const {\n      sym::Var<sym::vidx<'T'>> T;\n      //Standardise the units of the function\n      return scale(_variable) * sym::sub(_f , T = (T - _T.origin()) * (1 / scale(Objective_t(Objective_t::T))));\n    }\n    \n    virtual std::array<std::string,3> LaTeX() const {\n      sym::Expr df = sym::simplify(sym::derivative(_f, sym::VarRT('T')));\n      sym::Expr ddf = sym::simplify(sym::derivative(df, sym::VarRT('T')));\n    \n      return {{stator::repr<stator::ReprConfig<stator::Latex_output> >(_f),\n\t    stator::repr<stator::ReprConfig<stator::Latex_output> >(df),\n\t    stator::repr<stator::ReprConfig<stator::Latex_output> >(ddf)\n\t    }};\n    }\n    \n    double _x_min;\n    double _x_max;\n    sym::Expr _f;\n  };\n\n\n  struct TabulatedCurve: public Curve {\n    TabulatedCurve(std::string comment, std::string source, Objective_t variable, Reference_t reference, Objective_t xvar,\n\t\t   T_unit_t Tunit, Q_unit_t Qunit, E_unit_t Eunit, P_unit_t Punit, L_unit_t Lunit):\n      Curve(comment, source, variable, reference, xvar, Tunit, Qunit, Eunit, Punit, Lunit)\n    {}\n\n    TabulatedCurve(Node xml, Objective_t xvar):\n      Curve(xml, xvar)\n    {\n      std::string input = xml.getNode(\"Data\");\n      std::vector<std::string> lines;\n      boost::split(lines, input, boost::is_any_of(\"\\n\"), boost::token_compress_on);\n\n      for (size_t line(0); line < lines.size(); ++line) {\n\tstd::vector<std::string> values;\n\tboost::trim_right(lines[line]);\n\tboost::trim_left(lines[line]);\n\tboost::split(values, lines[line], boost::is_any_of(\"\\t \"), boost::token_compress_on);\n\tif (lines[line] == \"\")\n\t  continue;\n\tif (values.size() == 0)\n\t  continue;\n\tif (values[0][0] == '!')\n\t  continue;\n\tif ((values.size() != 2) && (values.size() != 3)) {\n\t  std::ostringstream os;\n\t  for (const auto & split: values)\n\t    os << \"\\\"\" << split << \"\\\",\";\n\t  \n\t  stator_throw() << \"Tabulated Curve has bad formatting on line \" << line+1 << \", xml path \" << xml.getPath() << \"\\nLine content is :\\\"\" << lines[line] << \"\\\"\" << \"\\n\" << \"string was split as follows \" << os.str()\n\t\t\t << \"\\nXML:\\n\" << xml.print();\n\t  \n\t}\n\tif (values.size() == 2)\n\t  add_point(boost::lexical_cast<double>(values[0]), boost::lexical_cast<double>(values[1]));\n\tif (values.size() == 3)\n\t  add_point(boost::lexical_cast<double>(values[0]), boost::lexical_cast<double>(values[1]), boost::lexical_cast<double>(values[2]));\n      }\n      if  (_values.empty())\n\tstator_throw() << \"Loaded an empty Tabulated Curve? xml path \" << xml.getPath() \n\t\t       << \"\\nXML:\\n\" << xml.print();\n    }\n\n    virtual double xmin() const {\n      if (_values.empty())\n\treturn +HUGE_VAL;\n      return normalise_units(_xvar, _values.front().x);\n    }\n    \n    virtual double xmax() const {\n      if (_values.empty())\n\treturn -HUGE_VAL;\n      return normalise_units(_xvar, _values.back().x);\n    }\n\n    virtual void xml_extended(Node xml) const {\n      xml.add_attribute(\"Type\", \"Tabulated\");\n\n      std::string data;\n      for (const auto& datum : _values) {      \n\tdata += \"\\n\" + boost::lexical_cast<std::string>(datum.x) + \" \" + boost::lexical_cast<std::string>(datum.val);\n\tif (datum.error != 0)\n\t  data += \" \" + boost::lexical_cast<std::string>(datum.error);\n      }\n\n      xml.add_node(\"Data\") = data;\n    }\n\n    virtual sym::Expr getFunction() const {\n      stator_throw() << \"Not implemented yet\";\n      //See commented code below for ideas\n    }\n    \n    //virtual DataPoint eval_worker(double x) const {\n    //  for (size_t i(0); i < _values.size() - 1; ++i)\n    //\tif ((x >= _values[i].x) && (x <= _values[i+1].x)) {\n    //\t  const double dfdx  = (_values[i+1].val - _values[i].val) / (_values[i+1].x - _values[i].x);\n    //\t  const double val = _values[i].val + dfdx * (x - _values[i].x);\n    //\t  return DataPoint{x, val, dfdx, 0.0};\n    //\t}\n    //  \n    //  if (x == _values.back().x) {\n    //\tdouble dfdx = 0;\n    //\tif (_values.size() - 1)\n    //\t  dfdx = (_values[_values.size() - 1].val - _values[_values.size() - 2].val)\n    //\t    / (_values[_values.size() - 1].x - _values[_values.size() - 2].x);\n    //\treturn DataPoint{x, _values.back().val, dfdx, 0.0};\n    //  }\n    //  \n    //  stator_throw() << \"Out of range access for Tabulated Curve\";\n    //}\n\n    void add_point(double x, double val, double error = 0.0) {\n      Datum v{x, val, error};\n      _values.insert(std::upper_bound(_values.begin(), _values.end(), v), v);\n    }\n    \n    struct Datum {\n      bool operator<(const Datum& d) const { return x < d.x; }\n      double x;\n      double val;\n      double error;\n    };\n    std::vector<Datum> _values;\n  };\n\n  inline\n  shared_ptr<Curve> Curve::load(Node xml, Objective_t xvar) {\n    try {\n      std::string type = xml.getAttribute(\"Type\").as<std::string>();\n      if ((type == \"Function\") || (type == \"Shomate\"))\n\treturn make_shared<FunctionCurve>(xml, xvar);\n      else if (type == \"Tabulated\")\n\treturn make_shared<TabulatedCurve>(xml, xvar);\n      else\n\tstator_throw() << \"Unknown Curve type \" << type;\n    } catch (const stator::Exception& e) {\n      stator_throw() << \"Failed parsing Curve\\n\" << xml.getPath() << \"\\n\" << e.what();\n    }\n  }\n}\n", "meta": {"hexsha": "37329323a06d91eb6a1babf80555eb6b6522ea01", "size": 21042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simcem/simcem/curve.hpp", "max_stars_repo_name": "toastedcrumpets/SimCem", "max_stars_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T17:29:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T14:53:37.000Z", "max_issues_repo_path": "src/simcem/simcem/curve.hpp", "max_issues_repo_name": "toastedcrumpets/SimCem", "max_issues_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simcem/simcem/curve.hpp", "max_forks_repo_name": "toastedcrumpets/SimCem", "max_forks_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "max_forks_repo_licenses": ["BSD-3-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.572755418, "max_line_length": 214, "alphanum_fraction": 0.5943826632, "num_tokens": 6131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.050330631707179815, "lm_q1q2_score": 0.019187021588809118}}
{"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#include \"galois/Galois.h\"\n#include \"galois/Reduction.h\"\n#include \"galois/Bag.h\"\n#include \"galois/Timer.h\"\n#include \"galois/graphs/LCGraph.h\"\n#include \"galois/ParallelSTL.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"Lonestar/BoilerPlate.h\"\n\n#include \"galois/graphs/Graph.h\"\n#include \"galois/runtime/Profile.h\"\n\n#include <boost/iterator/transform_iterator.hpp>\n\n#include <utility>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\n//#define DEBUG 0\n\nconst char* name = \"K-Cliques\";\nconst char* desc = \"Counts the number of K-Cliques in a graph for any given K\";\nconst char* url  = 0;\n\nnamespace cll = llvm::cl;\nstatic cll::opt<std::string>\n    inputFilename(cll::Positional, cll::desc(\"<input file>\"), cll::Required);\n\nstatic cll::opt<unsigned int>\n    clique_size(\"k\", // not uint64_t due to a bug in llvm cl\n                cll::desc(\"Clique Size\"), cll::init(3));\n\ntypedef galois::graphs::LC_CSR_Graph<uint32_t, void>::with_numa_alloc<\n    true>::type ::with_no_lockable<true>::type Graph;\n\n// typedef galois::graphs::MorphGraph<int,int,true,false,false,true> DAG;\ntypedef galois::graphs::MorphGraph<int, int, true> DAG;\n\ntypedef Graph::GraphNode GNode;\ntypedef DAG::GraphNode DAGNode;\n\nstruct WorkItem {\n  std::vector<DAGNode> clique;    // set of graph nodes that form a clique\n  std::vector<DAGNode> neighbors; // set of neighbors of the clique\n};\n\n/**\n * Compares the given two graph nodes n1 and n2.\n * It returns true if\n * \t\t(1) degree(n1) < degree(n2) (or)\n * \t\t(2) (degree(n1) = degree(n2)) and (node id of n1 < node id of n2)\n *\n * \\param g is the input graph g\n * \\param n1 is the first input node\n * \\param n2 is the second input node\n * \\return True if n1 < n2 else False.\n */\n\nbool lessThan(Graph& g, const GNode& n1, const GNode& n2) {\n  int n1_degree = std::distance(g.edge_begin(n1), g.edge_end(n1));\n  int n2_degree = std::distance(g.edge_begin(n2), g.edge_end(n2));\n\n  if (n1_degree < n2_degree) {\n    return true;\n  } else if ((n1_degree == n2_degree) && (g.getData(n1) < g.getData(n2))) {\n    return true;\n  } else {\n    return false;\n  }\n}\n\n/**\n * Extracts neighbors of a given node of directed acyclic graph (DAG)\n *\n * \\param n is the node of a DAG\n * \\param neighbors is the output vector that contains the neighbors of node n\n * \\param dag is the input DAG\n */\n\nvoid getNeighbors(DAGNode& n, std::vector<DAGNode>& neighbors, DAG& dag) {\n  int i = 0;\n  for (auto jj : dag.edges(n)) {\n    DAGNode dst  = dag.getEdgeDst(jj);\n    neighbors[i] = dst;\n    i++;\n  }\n}\n\n/**\n * Gives the intersection two neighbor vector. It requires the vectors be sorted\n * according to the node ids.\n *\n * \\param jointNeighbors is the output neighbor vector\n * \\param srcNeighbors is the first input neighbor vector\n * \\param dstNeighbors is the second input neighbor vector\n */\n\nsize_t intersect(std::vector<DAGNode>& jointNeighbors,\n                 std::vector<DAGNode>& srcNeighbors,\n                 std::vector<DAGNode>& dstNeighbors) {\n  std::vector<DAGNode>::iterator srcItr = srcNeighbors.begin();\n  std::vector<DAGNode>::iterator dstItr = dstNeighbors.begin();\n  size_t size                           = 0;\n\n  while (srcItr != srcNeighbors.end() && dstItr != dstNeighbors.end()) {\n    if (*srcItr < *dstItr) {\n      ++srcItr;\n    } else if (*dstItr < *srcItr) {\n      ++dstItr;\n    } else {\n      jointNeighbors[size] = (*srcItr);\n      size++;\n      ++srcItr;\n      ++dstItr;\n    }\n  }\n  return size;\n}\n\n/**\n * Prints edges of a DAG\n *\n * \\param dag is the input directed acyclic graph\n */\n\nvoid printDAG(DAG& dag) {\n  std::cout << \"DAG: \"\n            << \"\\n\";\n  for (DAG::iterator ii = dag.begin(); ii != dag.end(); ++ii) {\n    DAGNode src = *ii;\n    for (DAG::edge_iterator jj = dag.edge_begin(src); jj != dag.edge_end(src);\n         ++jj) {\n      DAGNode dst = dag.getEdgeDst(jj);\n      std::cout << \"(\" << dag.getData(src) << \",\" << dag.getData(dst) << \")\\n\";\n    }\n  }\n}\n\n/**\n * Prints the details of a work item.\n *\n * \\param w is the input work item\n * \\param dag is a directed acyclic graph\n */\n\nvoid print_workitem(WorkItem& w, DAG& dag) {\n  std::cout << \"\\n-------------------------------------------------------- \\n\";\n  std::cout << \"Clique: \";\n  for (std::vector<DAGNode>::iterator v = w.clique.begin(); v != w.clique.end();\n       ++v) {\n    std::cout << dag.getData(*v) << \" \";\n  }\n\n  std::cout << \"Neighborhood:\";\n  for (std::vector<DAGNode>::iterator nitr = w.neighbors.begin();\n       nitr != w.neighbors.end(); ++nitr) {\n    std::cout << dag.getData(*nitr) << \" \";\n  }\n  std::cout << \"\\n-------------------------------------------------------- \\n\";\n}\n\n/**\n * Prints the vertices of a clique\n *\n * \\param w is the input work item which contains a clique\n * \\param dag is a directed acyclic graph\n */\n\nvoid print_clique(WorkItem& w, DAG& dag) {\n\n  std::cout << \"Clique: \";\n  for (std::vector<DAGNode>::iterator v = w.clique.begin(); v != w.clique.end();\n       ++v) {\n    std::cout << dag.getData(*v) << \" \";\n  }\n  std::cout << \"\\n\\n\";\n}\n\n/**\n * Prints the vertices that are present in the neighbors\n *\n * \\param neighbors is the input vector whose vertices need to be printed\n * \\param dag is a directed acyclic graph\n * \\param size the number of vertices in the neighbors to be printed\n */\n\nvoid print_neighbors(std::vector<DAGNode> neighbors, DAG& dag, int size) {\n\n  int i = 0;\n  std::cout << \"Neighbors \";\n  for (std::vector<DAGNode>::iterator nitr = neighbors.begin();\n       nitr != neighbors.end() && (i < size); ++nitr, ++i) {\n    std::cout << dag.getData(*nitr) << \" \";\n  }\n  std::cout << \"\\n\";\n}\n\n/**\n * This procedure computes the number of k-cliques of a given graph.\n *\n * \\param k is the clique size\n * \\param dag is a directed acyclic graph, which is obtained using an input\n * graph.\n */\n\nvoid compute_kcliques(unsigned int k, DAG& dag) {\n\n  galois::InsertBag<WorkItem>\n      items; // worklist that monitors the cliques and their neighborhood\n  galois::GAccumulator<size_t> num_kcliques; // maintains the number k cliques\n\n  // Initialize the worklist. Each work item contains a single vertex, and all\n  // its neighbors.\n\n  galois::StatTimer TWorkInit(\"Work list initialization\");\n  galois::StatTimer Tsort(\"Sorting\");\n  galois::StatTimer TCliqueResize(\"Clique Resize\");\n  galois::StatTimer TNeighborResize(\"Neighbor Resize\");\n  galois::StatTimer TProcessWorkItem(\"Processing work item\");\n  galois::StatTimer TProcessEdge(\"Processing Edges\");\n  galois::StatTimer TIntersect(\"Neighbor Intersection\");\n  galois::StatTimer TGetNeighbor(\"Get Neighbors\");\n\n  TWorkInit.start();\n  galois::do_all(\n      galois::iterate(dag),\n      [&](DAGNode n) {\n        WorkItem w;\n\n        TCliqueResize.start();\n        w.clique.resize(1);\n        TCliqueResize.stop();\n\n        w.clique[0]    = n;\n        int neigh_size = std::distance(dag.edge_begin(n), dag.edge_end(n));\n\n        TNeighborResize.start();\n        w.neighbors.resize(neigh_size);\n        TNeighborResize.stop();\n        getNeighbors(n, w.neighbors, dag);\n\n        Tsort.start();\n        std::sort(w.neighbors.begin(), w.neighbors.end());\n        Tsort.stop();\n        items.push(w);\n\n#ifdef DEBUG\n        print_workitem(w, dag);\n#endif\n      },\n      galois::loopname(\"Initialize\"));\n  TWorkInit.stop();\n\n  // Process a work item w containing a clique C and neighbood N.\n  auto processClique = [&](WorkItem& w, auto& ctx) {\n    TProcessWorkItem.start();\n\n    if (w.clique.size() == k) {\n      // If the clique size is k, increment number of k-cliques by 1. No new\n      // work item is generated here.\n      num_kcliques += 1;\n\n#ifdef DEBUG\n      print_clique(w, dag);\n#endif\n    } else if (w.clique.size() == k - 1) {\n      /**\n       * Clique size is k-1, so form a new clique of size k by adding a vertex\n       * from the neighborhood. So, for a neighborhood for size N, new N\n       * K-cliques are formed.\n       */\n\n#ifdef DEBUG\n      std::cout << \"Processing Work Item:\";\n      print_workitem(w, dag);\n#endif\n\n      for (std::vector<DAGNode>::iterator neighitr = w.neighbors.begin();\n           neighitr != w.neighbors.end(); ++neighitr) {\n        WorkItem nextItem;\n\n        TCliqueResize.start();\n        nextItem.clique.resize(w.clique.size() + 1);\n        TCliqueResize.stop();\n\n        int i = 0;\n        for (std::vector<DAGNode>::iterator v = w.clique.begin();\n             v != w.clique.end(); ++v) {\n          nextItem.clique[i] = (*v);\n          i++;\n        }\n        nextItem.clique[i] = *neighitr;\n\n#ifdef DEBUG\n        print_clique(nextItem, dag);\n#endif\n\n        num_kcliques += 1;\n      }\n    } else {\n      /**\n       * For each edge u->v present in N, construct a new work W with (C', N')\n       * and insert it into the work list where C' = C U {u,v} and N' =\n       * intersection{N, neighbors of u, neighbors of v)\n       */\n\n      for (std::vector<DAGNode>::iterator src = w.neighbors.begin();\n           src != w.neighbors.end(); ++src) {\n        for (std::vector<DAGNode>::iterator dst = w.neighbors.begin();\n             dst != w.neighbors.end(); ++dst) {\n          if ((dag.getData(*src) != dag.getData(*dst)) &&\n              (dag.findEdge(*src, *dst) !=\n               dag.edge_end(*src, galois::MethodFlag::UNPROTECTED))) {\n\n            TProcessEdge.start();\n#ifdef DEBUG\n            std::cout << \"Processing Work Item:\";\n            print_workitem(w, dag);\n#endif\n\n            WorkItem nextItem;\n\n            TCliqueResize.start();\n            nextItem.clique.resize(w.clique.size() + 2);\n            TCliqueResize.stop();\n\n            int i = 0;\n\n            for (std::vector<DAGNode>::iterator itr = w.clique.begin();\n                 itr != w.clique.end(); ++itr) {\n              nextItem.clique[i] = (*itr);\n              i++;\n            }\n            nextItem.clique[i]     = *src;\n            nextItem.clique[i + 1] = *dst;\n\n            TGetNeighbor.start();\n            std::vector<DAGNode> srcNeighbors;\n            std::vector<DAGNode> dstNeighbors;\n            std::vector<DAGNode> jointNeighbors;\n            std::vector<DAGNode> tmpNeighbors;\n\n            size_t srcDegree =\n                std::distance(dag.edge_begin(*src), dag.edge_end(*src));\n            size_t dstDegree =\n                std::distance(dag.edge_begin(*dst), dag.edge_end(*dst));\n\n            TGetNeighbor.stop();\n\n            TNeighborResize.start();\n            srcNeighbors.resize(srcDegree);\n            dstNeighbors.resize(dstDegree);\n            tmpNeighbors.resize(std::min(srcDegree, w.neighbors.size()));\n            TNeighborResize.stop();\n\n            TGetNeighbor.start();\n            getNeighbors(*src, srcNeighbors, dag);\n            TGetNeighbor.stop();\n\n            Tsort.start();\n            std::sort(srcNeighbors.begin(), srcNeighbors.end());\n            Tsort.stop();\n\n            getNeighbors(*dst, dstNeighbors, dag);\n\n            Tsort.start();\n            std::sort(dstNeighbors.begin(), dstNeighbors.end());\n            Tsort.stop();\n\n            TIntersect.start();\n            size_t tmp_neighborsize =\n                intersect(tmpNeighbors, srcNeighbors, w.neighbors);\n            TIntersect.stop();\n\n            nextItem.neighbors.resize(tmp_neighborsize);\n\n            TIntersect.start();\n            size_t nextItem_neighborsize =\n                intersect(nextItem.neighbors, dstNeighbors, tmpNeighbors);\n            TIntersect.stop();\n\n            TNeighborResize.start();\n            nextItem.neighbors.resize(nextItem_neighborsize);\n            TNeighborResize.stop();\n\n            ctx.push(nextItem);\n\n#ifdef DEBUG\n            std::cout << \"Processing an edge with Source : \"\n                      << dag.getData(*src)\n                      << \" Destination : \" << dag.getData(*dst) << \"\\n\";\n            std::cout << \"Source Neighborhood: \";\n            print_neighbors(srcNeighbors, dag, srcNeighbors.size());\n            std::cout << \"Temporary Neighborhood: Intersection of Source \"\n                         \"Neighborhood and WorkItem Neighborhood: \";\n            print_neighbors(tmpNeighbors, dag, tmp_neighborsize);\n            std::cout << \"Destination Neighborhood: \";\n            print_neighbors(dstNeighbors, dag, dstNeighbors.size());\n            std::cout << \"NextItem Neighborhood: Intersection of Temporary \"\n                         \"Neighborhood and Destination Neighborhood: \";\n            print_neighbors(nextItem.neighbors, dag, nextItem_neighborsize);\n#endif\n\n            TProcessEdge.stop();\n          }\n        }\n      }\n    }\n    TProcessWorkItem.stop();\n  };\n\n  // parallel loop that processes work list until it is empty.\n  galois::for_each(\n      galois::iterate(items), // initial range using initializer list\n      processClique,          // operator\n      galois::loopname(\"process clique\"), galois::steal());\n\n  std::cout << \"Number of K-Cliques: \" << num_kcliques.reduce() << \"\\n\";\n}\n\n/*\n * For a given graph (G), it constructs a directed acyclic graph (DAG)\n * corresponding to it. The graph DAG represents a total order among the\n * vertices of the graph G. Procedure: V (DAG) = V(G) An edge u->v is present in\n * DAG if (1) (u,v) is in E(G) and (2) (degree(u) < degree(v)) or (degree(u) =\n * degree(v) and u < v)\n *\n * \\param graph is the input graph\n * \\param dag is the output directed acyclic graph\n */\nvoid constructDAG(Graph& graph, DAG& dag) {\n\n  std::vector<DAGNode> nodes;\n  nodes.resize(graph.size());\n\n  // Creating the DAG vertices\n  galois::do_all(galois::iterate(graph),\n                 [&graph, &dag, &nodes](GNode N) {\n                   int index    = graph.getData(N);\n                   nodes[index] = dag.createNode(index);\n                   dag.addNode(nodes[index]);\n                 } // operator as lambda expression\n  );\n\n  // Adding the edges depending on the degree of source and destination.\n  galois::do_all(galois::iterate(graph),\n                 [&graph, &dag, &nodes](GNode N) {\n                   for (Graph::edge_iterator edge :\n                        graph.out_edges(N, galois::MethodFlag::UNPROTECTED)) {\n                     GNode dst = graph.getEdgeDst(edge);\n                     if (lessThan(graph, N, dst)) {\n                       DAGNode srcNode = nodes[graph.getData(N)];\n                       DAGNode dstNode = nodes[graph.getData(dst)];\n                       dag.addEdge(srcNode, dstNode);\n                     }\n                   }\n                 } // operator as lambda expression\n  );\n\n#ifdef DEBUG\n  printDAG(dag);\n#endif\n}\n\n/**\n * Read a graph from the given input file (inputFileName)\n *\n * \\param graph is the output graph\n */\nvoid readGraph(Graph& graph) {\n\n  galois::graphs::readGraph(graph, inputFilename);\n  size_t index = 0;\n  for (GNode n : graph) {\n    graph.getData(n) = index++;\n  }\n}\n\n/**\n * This is an implementation for computing number of k-cliques in a given graph.\n * It uses the edge parallel algorithm described in Danisch et al. WWW 2018\n * (https://dl.acm.org/citation.cfm?id=3186125). It is implemented using Galois\n * framework.\n */\n\nint main(int argc, char** argv) {\n  galois::SharedMemSys G;\n  LonestarStart(argc, argv, name, desc, url);\n\n  Graph graph;\n  DAG dag;\n\n  // Read the input Graph\n  galois::StatTimer Tinitial(\"GraphReadingTime\");\n  Tinitial.start();\n  readGraph(graph);\n  Tinitial.stop();\n\n  // Constructing a DAG from the original graph\n  galois::StatTimer Tdag(\"DAG Construction Time\");\n  Tdag.start();\n  constructDAG(graph, dag);\n  Tdag.stop();\n\n  galois::preAlloc(numThreads + 16 * (graph.size() + graph.sizeEdges()) /\n                                    galois::runtime::pagePoolSize());\n  galois::reportPageAlloc(\"MeminfoPre\");\n\n  galois::StatTimer T;\n  T.start();\n  // the main procedure that computes k-cliques\n  compute_kcliques(clique_size, dag);\n\n  T.stop();\n\n  galois::reportPageAlloc(\"MeminfoPost\");\n  return 0;\n}\n", "meta": {"hexsha": "115b0c7d72bc0fa5d52f56824948406ce99046ac", "size": 16887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/k-cliques/k-cliques.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/k-cliques/k-cliques.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/k-cliques/k-cliques.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": 31.2722222222, "max_line_length": 80, "alphanum_fraction": 0.6085154261, "num_tokens": 4259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864512179822543, "lm_q2_score": 0.05500528751889617, "lm_q1q2_score": 0.019177325166571963}}
{"text": "\n#ifndef MTL_COORDINATE2D_INCLUDE\n#define MTL_COORDINATE2D_INCLUDE\n\n#include <vector>\n#include <cassert>\n#include <boost/mpl/bool.hpp>\n\n\n#include <boost/numeric/mtl/operation/is_negative.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/operation/sort.hpp>\n#include <boost/numeric/mtl/operation/iota.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n\nnamespace mtl {  namespace mat {\n    \n  \n/// Sparse matrix structure in coordinate format\ntemplate <typename Value, typename Parameters = mat::parameters<> >\nclass coordinate2D \n  : public base_matrix<Value, Parameters>,\n    public const_crtp_base_matrix< coordinate2D<Value, Parameters>, Value, typename Parameters::size_type >,\n    public crtp_matrix_assign< coordinate2D<Value, Parameters>, Value, typename Parameters::size_type >,\n    public mat_expr< coordinate2D<Value, Parameters> >\n{\n  public:\n    typedef Value                                                       value_type;\n    typedef Value&                                                      reference;\n    typedef Value const&                                                const_reference;\n    typedef typename Parameters::size_type\t\t\t\t  size_type;\n    typedef typename Parameters::dimensions                             dim_type;\n    typedef typename Parameters::orientation                            orientation;      \n\n    typedef coordinate2D                                                self;\n    typedef base_matrix<Value, Parameters>                              super;\n    typedef crtp_matrix_assign<self, Value, size_type>                  assign_base;\n\n    typedef std::vector< size_type >                                    row_index_array_type ;\n    typedef std::vector< size_type >                                    column_index_array_type ;\n    typedef std::vector< value_type >                                   value_array_type ;\n\n    /// Common constructor\n    explicit coordinate2D(size_type nrows, size_type ncols, size_type expected= 0)\n      : super(dim_type(nrows, ncols))\n    {\n\tif (expected > 0) {\n\t    rows.reserve(expected);\n\t    cols.reserve(expected);\n\t    values.reserve(expected);\n\t}\n\tmy_is_sorted= true; \n    } \n    \n    using assign_base::operator=;    \n  \n    size_type nnz() const { return rows.size(); } ///< Number of non-zeros\n\n    value_array_type const& value_array() const { return values; } ///< Array of values (const)\n    value_array_type& value_array() { return values; }             ///< Array of values (mutable)\n\n    row_index_array_type const& row_index_array() const { return rows; }       ///< Array of rows  (const)\n    column_index_array_type const& column_index_array() const {\treturn cols; } ///< Array of columns (const)\n  \n    row_index_array_type& row_index_array() { return rows; }       ///< Array of rows   (mutable)\n    column_index_array_type& column_index_array() { return cols; } ///< Array of columns  (mutable)\n\n    /// Drop all entries\n    void make_empty()\n    {\n        rows.resize(0); cols.resize(0); values.resize(0);\n        my_is_sorted= true; // haha\n    }\n    \n    /// Insert an entry at the end of the row-,col- and value-array \n    void push_back(size_type r, size_type c, const_reference v) \n    {\n\trows.push_back(r); cols.push_back(c); values.push_back(v); my_is_sorted= false;\n    } \n  \n    /// Insert an entry at the end of the row-,col- and value-array, like push_back\n    void insert(size_type r, size_type c, const_reference v) {\tpush_back(r, c, v); }\n  \n    /// Whether the entries are sorted\n    bool is_sorted() const { return my_is_sorted; }\n\n    /// sorting standard by rows\n    void sort() \n    { \n\tif (nnz() > 0) \n\t    sort(mtl::traits::is_row_major<Parameters>());  \n\tmy_is_sorted= true;\n    }\n\n  private:\n    // sorting by rows\n    void sort(boost::mpl::true_)\n    {  \n\tmtl::vec::sort_xy(rows, cols, values);\n    }\n\n    // sorting by columns\n    void sort(boost::mpl::false_)\n    {\n\tmtl::vec::sort_xy(cols, rows, values);\n    }\n  \n    template <typename OStream, typename Vector>\n    void print_stl_vector(OStream& os, const Vector& v) const\n    {\n\tos << \"[\";\n\tfor (unsigned i= 0; i < v.size(); i++)\n\t    os << v[i] << (i+1 < v.size() ? \",\" : \"\");\n\tos << \"]\\n\";\n    }\n\n  public:\n    template <typename OStream>\n    void print_internal(OStream& os) const\n    {\n       \tos << \"rows   = \"; print_stl_vector(os, rows);\n\tos << \"cols   = \"; print_stl_vector(os, cols);\n\tos << \"values = \"; print_stl_vector(os, values);\n    }\n\n    void print_internal() const { print(std::cout); }\n\n    ///operator * for  vector= coordinaten-matrix * vector\n    template <typename Vector >\n    Vector operator*(const Vector& x)\n    {\n\t\n\tVector res(this->num_rows());\n\tres= 0;\n\tfor (size_type i= 0; i < nnz(); i++)\n\t    res[rows[i]]+=  values[i] * x[cols[i]];\n\treturn res;\n    }\n  \n    value_type operator() (const size_type r, const size_type c) const\n    {\n\tMTL_CRASH_IF(is_negative(r) || r >= this->num_rows() \n\t\t  || is_negative(c) || c >= this->num_cols(), \"Index out of range!\");\n\n#if 0\n\tif (my_is_sorted)\n\t    return find(r, c, mtl::traits::is_row_major<Parameters>());\n#endif\n\n\tfor (size_type i= 0; i < nnz(); i++) \n\t    if (rows[i] == r && cols[i] == c)\n\t\treturn values[i];\n\treturn value_type(0);\n    }\n\n    template <typename Updater>\n    void compress(Updater up)\n    {\n\tif (!my_is_sorted)\n\t    sort();\n\n\tsize_type i= 0, j= 1, end= rows.size();\n\tfor (; j < end; ++j) \n\t    if (rows[i] == rows[j] && cols[i] == cols[j]) {\n\t\tup(values[i], values[j]);\n\t    } else {\n\t\ti++;\n\t\tif (i != j) {\n\t\t    rows[i]= rows[j];\n\t\t    cols[i]= cols[j];\n\t\t    values[i]= values[j];\n\t\t}\n\t    }\n\tif (end > 0) i++;\n\trows.resize(i);\n\tcols.resize(i);\n\tvalues.resize(i);\n   }\n\n    template <typename Matrix, typename Updater> friend struct coordinate2D_inserter;\n\n  private:\n    row_index_array_type      rows;\n    column_index_array_type   cols;\n    value_array_type          values;\n    bool                      my_is_sorted;\n};\n\n// ================\n// Free functions\n// ================\n\n\n/// Number of rows\ntemplate <typename Value, typename Parameters>\ntypename coordinate2D<Value, Parameters>::size_type\ninline num_rows(const coordinate2D<Value, Parameters>& matrix)\n{\n    return matrix.num_rows();\n}\n\n/// Number of columns\ntemplate <typename Value, typename Parameters>\ntypename coordinate2D<Value, Parameters>::size_type\ninline num_cols(const coordinate2D<Value, Parameters>& matrix)\n{\n    return matrix.num_cols();\n}\n\n/// Size of the matrix, i.e. the number of row times columns\ntemplate <typename Value, typename Parameters>\ntypename coordinate2D<Value, Parameters>::size_type\ninline size(const coordinate2D<Value, Parameters>& matrix)\n{\n    return matrix.num_cols() * matrix.num_rows();\n}\n\n/// Number of NoZeros of the matrix\ntemplate <typename Value, typename Parameters>\ntypename coordinate2D<Value, Parameters>::size_type\ninline nnz(const coordinate2D<Value, Parameters>& matrix)\n{\n    return matrix.nnz();\n}\n\n\ntemplate <typename Matrix, \n\t  typename Updater = mtl::operations::update_store<typename Matrix::value_type> >\nstruct coordinate2D_inserter\n{\n    typedef coordinate2D_inserter                       self;\n    typedef Matrix                                      matrix_type;\n    typedef typename matrix_type::size_type             size_type;\n    typedef typename matrix_type::value_type            value_type;\n    typedef operations::update_proxy<self, size_type>   proxy_type;\n    \n    // We only support storing so far !!!\n    // STATIC_ASSERT((boost::is_same<Updater, mtl::operations::update_store<value_type> >::value), \"We only support storing so far\");\n\n    coordinate2D_inserter(matrix_type& matrix, size_type slot_size= 1) \n      : matrix(matrix) \n    {\n\tstd::size_t ns= slot_size * matrix.dim1();\n\tif (ns > matrix.nnz()) {\n\t    matrix.rows.reserve(ns);\n\t    matrix.cols.reserve(ns);\n\t    matrix.values.reserve(ns);\n\t}\n    }\n\n    ~coordinate2D_inserter() { matrix.compress(Updater()); }\n    \n private:\n\n    struct update_proxy\n    {\n\t// self is type of inserter not update_proxy !!!\n\tupdate_proxy(self& ref, size_type row, size_type col) : ref(ref), row(row), col(col) {}\n\n\ttemplate <typename Value>\n\tupdate_proxy& operator<< (Value const& val)\n\t{\n\t    ref.matrix.push_back(row, col, val);\n\t    return *this;\n\t}\n\tself& ref;\n\tsize_type row, col;\n    };\n    \n    proxy_type operator() (size_type row, size_type col)\n    {\n\treturn proxy_type(*this, row, col);\n    }\n\n    \n    struct bracket_proxy\n    {\n\tbracket_proxy(self& ref, size_type row) : ref(ref), row(row) {}\n\t\n\tproxy_type operator[](size_type col)\n\t{\n\t    return proxy_type(ref, row, col);\n\t}\n\n\tself&      ref;\n\tsize_type  row;\n    };\n\n  public:\n\n    bracket_proxy operator[] (size_type row)\n    {\n\treturn bracket_proxy(*this, row);\n    }\n\n    template <typename Value>\n    void update(size_type row, size_type col, Value val)\n    {\n\tmatrix.push_back(row, col, val);\n    }\n\n    template <typename Modifier, typename Value>\n    void modify(size_type row, size_type col, Value val)\n    {\n\tmatrix.push_back(row, col, val);\n    }\n\n    template <typename EMatrix, typename Rows, typename Cols>\n    self& operator<< (const mat::element_matrix_t<EMatrix, Rows, Cols>& elements)\n    {\n\tusing mtl::size;\n\tfor (unsigned ri= 0; ri < size(elements.rows); ri++)\n\t    for (unsigned ci= 0; ci < size(elements.cols); ci++)\n\t\tupdate (elements.rows[ri], elements.cols[ci], elements.matrix(ri, ci));\n\treturn *this;\n    }\n\n    template <typename EMatrix, typename Rows, typename Cols>\n    self& operator<< (const mat::element_array_t<EMatrix, Rows, Cols>& elements)\n    {\n\tusing mtl::size;\n\tfor (unsigned ri= 0; ri < size(elements.rows); ri++)\n\t    for (unsigned ci= 0; ci < size(elements.cols); ci++)\n\t\tupdate (elements.rows[ri], elements.cols[ci], elements.array[ri][ci]);\n\treturn *this;\n    }\n\n  protected:\n    matrix_type&         matrix;\n};\n\nstruct coordinate_key\n{\n    typedef std::size_t                               size_t;\n\n    explicit coordinate_key(size_t offset) : offset(offset) {}\n\n    bool operator== (coordinate_key const& other) const { return offset == other.offset; }\n    bool operator!= (coordinate_key const& other) const { return offset != other.offset; }\n    \n    size_t offset;    \n};\n\n\n// Cursor over every element\ntemplate <typename Value, typename Parameters>\nstruct coordinate_minor_cursor \n : public coordinate_key \n{\n    typedef coordinate_minor_cursor<Value, Parameters>   self;\n    typedef typename Parameters::size_type               size_type;\n    typedef const coordinate2D<Value, Parameters>&       matrix_ref_type;\n    static const int                                     level= 2;\n\n    coordinate_minor_cursor(matrix_ref_type ref, size_type offset) \n      : coordinate_key(offset), ref(ref)  {}\n\n    bool operator!=(const self& that) const\n    {\n\tassert(&ref == &that.ref);\n\treturn this->offset != that.offset;\n    }\n\n    self& operator++() { this->offset++; return *this; }\n    coordinate_key operator*() const { return *this; }\n\n    matrix_ref_type ref;\n};\n\n\ntemplate <typename Value, typename Parameters>\nstruct coordinate_major_cursor \n{\n    typedef coordinate_major_cursor<Value, Parameters>   self;\n    typedef typename Parameters::size_type               size_type;\n    typedef const coordinate2D<Value, Parameters>&       matrix_ref_type;\n    typedef coordinate_minor_cursor<Value, Parameters>   inner_cursor;\n    static const int                                     level= 2;\n\n    void find_next_offset(boost::mpl::true_)\n    {\n\tsize_type i= offset;\n\tfor ( ; i < nnz(ref) && ref.row_index_array()[i] <= major; i++) ;\n\tnext_offset= i;\n    }\n\n    void find_next_offset(boost::mpl::false_)\n    {\n\tsize_type i= offset;\n\tfor ( ; i < nnz(ref) && ref.col_index_array()[i] <= major; i++) ;\n\tnext_offset= i;\n    }\n\n    void find_next_offset() { find_next_offset(mtl::traits::is_row_major<Parameters>()); }\n\n    coordinate_major_cursor(matrix_ref_type ref, size_type major, size_type offset) \n      : ref(ref), major(major), offset(offset)\n    {\n\tfind_next_offset();\n    }\n\n    bool operator!=(const self& that) const\n    {\n\tassert(&ref == &that.ref);\n\treturn this->offset != that.offset;\n    }\n\n    self& operator++() \n    { \n\toffset= next_offset; \n\tmajor++;\n\tfind_next_offset();\n\treturn *this; \n    }\n\n    matrix_ref_type ref;\n    size_type       major, offset, next_offset;\n};\n\ntemplate <typename Value, typename Parameters>\nstruct coordinate_minor_range_generator\n{\n    typedef coordinate_major_cursor<Value, Parameters>   outer_cursor_type;\n    typedef coordinate_minor_cursor<Value, Parameters>   type;\n    static const int                                     level= 2;\n\n    type begin(outer_cursor_type c) const { return type(c.ref, c.offset); }\n    type end(outer_cursor_type c) const { return type(c.ref, c.next_offset); }\n};\n\ntemplate <typename Value, typename Parameters>\nstruct coordinate_row_range_generator\n{\n    typedef const coordinate2D<Value, Parameters>&       matrix_ref_type;\n    typedef coordinate_major_cursor<Value, Parameters>   type;\n    typedef complexity_classes::linear_cached            complexity;\n    static const int                                     level= 1;\n\n    type begin(matrix_ref_type A) const { return type(A, 0, 0); }\n    type end(matrix_ref_type A) const { return type(A, num_rows(A), nnz(A)); }\n};\n\ntemplate <typename Value, typename Parameters>\nstruct coordinate_col_range_generator\n{\n    typedef const coordinate2D<Value, Parameters>&       matrix_ref_type;\n    typedef coordinate_major_cursor<Value, Parameters>   type;\n    typedef complexity_classes::linear_cached            complexity;\n    static const int                                     level= 1;\n\n    type begin(matrix_ref_type A) const { return type(A, 0, 0); }\n    type end(matrix_ref_type A) const { return type(A, num_cols(A), nnz(A)); }\n};\n\n\n}} // namespace mtl::matrix\n\n\nnamespace mtl { namespace traits {\n\t\n    // Cursor over all rows\n    // Supported if row major matrix\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::row, mat::coordinate2D<Value, Parameters> >\n      : boost::mpl::if_<\n\t    boost::is_same<typename Parameters::orientation, row_major>\n\t  , mat::coordinate_row_range_generator<Value, Parameters>\n \t  , range_generator<tag::unsupported, mat::coordinate2D<Value, Parameters> >\n        >::type {};\t\n\n    template <typename Value, typename Parameters>\n    struct range_generator<glas::tag::col, mat::coordinate2D<Value, Parameters> >\n      : boost::mpl::if_<\n\t    boost::is_same<typename Parameters::orientation, col_major>\n\t  , mat::coordinate_col_range_generator<Value, Parameters>\n \t  , range_generator<tag::unsupported, mat::coordinate2D<Value, Parameters> >\n        >::type {};\t\n\n    template <class Value, class Parameters>\n    struct range_generator<glas::tag::nz, mat::coordinate_major_cursor<Value, Parameters> >\n      : mat::coordinate_minor_range_generator<Value, Parameters>\n    {};\n\n\n}} // namespace mtl::traits\n\nnamespace mtl {\n\tusing mat::coordinate2D;\n}\n\n#endif // MTL_COORDINATE2D_INCLUDE\n\n", "meta": {"hexsha": "4357adcd591b5ef33138ec8f940fe72f8e05fa0b", "size": 15154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/matrix/coordinate2D.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/coordinate2D.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/coordinate2D.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": 30.5524193548, "max_line_length": 133, "alphanum_fraction": 0.6422066781, "num_tokens": 3574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.04535258555427004, "lm_q1q2_score": 0.019161678257057984}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n#define CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n\n#include <stdexcept>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"crocoddyl/core/fwd.hpp\"\n#include \"crocoddyl/core/state-base.hpp\"\n#include \"crocoddyl/core/utils/to-string.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief This class DifferentialActionModelAbstract represents a first-order\n * ODE, i.e.\n * \\f[\n * \\mathbf{\\dot{v}} = \\mathbf{f}(\\mathbf{q}, \\mathbf{v}, \\boldsymbol{\\tau})\n * \\f]\n * where \\f$ xout = \\mathbf{\\dot{v}} \\f$ and represents the  acceleration of the\n * system. Note that Jacobians Fx and Fu in the\n * DifferentialActionDataAbstract are in \\f$ \\mathbb{R}^{nv\\times ndx} \\f$ and\n * \\f$ \\mathbb{R}^{nv\\times nu} \\f$, respectively.\n *\n * Then we use the acceleration to integrate the system, and as consequence we\n * obtain:\n * \\f[\n * \\mathbf{\\dot{x}} = (\\mathbf{v}, \\mathbf{\\dot{v}}) = \\mathbf{f}(\\mathbf{x},\\mathbf{u})\n * \\f]\n * where this \\f$ f \\f$ function is different to the other one.\n * So \\f$ xout \\f$ is interpreted here as \\f$ vdout \\f$ or \\f$ aout \\f$.\n */\n\ntemplate <typename _Scalar>\nclass DifferentialActionModelAbstractTpl {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef DifferentialActionDataAbstractTpl<Scalar> DifferentialActionDataAbstract;\n  typedef StateAbstractTpl<Scalar> StateAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  DifferentialActionModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t& nu,\n                                     const std::size_t& nr = 0);\n  virtual ~DifferentialActionModelAbstractTpl();\n\n  virtual void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                    const Eigen::Ref<const VectorXs>& u) = 0;\n  virtual void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data,\n                        const Eigen::Ref<const VectorXs>& x, const Eigen::Ref<const VectorXs>& u) = 0;\n  virtual boost::shared_ptr<DifferentialActionDataAbstract> createData();\n\n  void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n  void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  const std::size_t& get_nu() const;\n  const std::size_t& get_nr() const;\n  const boost::shared_ptr<StateAbstract>& get_state() const;\n\n  const VectorXs& get_u_lb() const;\n  const VectorXs& get_u_ub() const;\n  bool const& get_has_control_limits() const;\n\n  void set_u_lb(const VectorXs& u_lb);\n  void set_u_ub(const VectorXs& u_ub);\n\n protected:\n  std::size_t nu_;                          //!< Control dimension\n  std::size_t nr_;                          //!< Dimension of the cost residual\n  boost::shared_ptr<StateAbstract> state_;  //!< Model of the state\n  VectorXs unone_;                          //!< Neutral state\n  VectorXs u_lb_;                           //!< Lower control limits\n  VectorXs u_ub_;                           //!< Upper control limits\n  bool has_control_limits_;                 //!< Indicates whether any of the control limits is finite\n\n  void update_has_control_limits();\n};\n\ntemplate <typename _Scalar>\nstruct DifferentialActionDataAbstractTpl {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  template <template <typename Scalar> class Model>\n  explicit DifferentialActionDataAbstractTpl(Model<Scalar>* const model)\n      : cost(0.),\n        xout(model->get_state()->get_nv()),\n        Fx(model->get_state()->get_nv(), model->get_state()->get_ndx()),\n        Fu(model->get_state()->get_nv(), model->get_nu()),\n        r(model->get_nr()),\n        Lx(model->get_state()->get_ndx()),\n        Lu(model->get_nu()),\n        Lxx(model->get_state()->get_ndx(), model->get_state()->get_ndx()),\n        Lxu(model->get_state()->get_ndx(), model->get_nu()),\n        Luu(model->get_nu(), model->get_nu()) {\n    xout.setZero();\n    r.setZero();\n    Fx.setZero();\n    Fu.setZero();\n    Lx.setZero();\n    Lu.setZero();\n    Lxx.setZero();\n    Lxu.setZero();\n    Luu.setZero();\n  }\n  virtual ~DifferentialActionDataAbstractTpl() {}\n\n  Scalar cost;\n  VectorXs xout;\n  MatrixXs Fx;\n  MatrixXs Fu;\n  VectorXs r;\n  VectorXs Lx;\n  VectorXs Lu;\n  MatrixXs Lxx;\n  MatrixXs Lxu;\n  MatrixXs Luu;\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/diff-action-base.hxx\"\n\n#endif  // CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n", "meta": {"hexsha": "c72a45a11ec0d55c3806bc6367de6d870de33aec", "size": 5279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/diff-action-base.hpp", "max_stars_repo_name": "paLeziart/crocoddyl", "max_stars_repo_head_hexsha": "c31a27432f9f2b365faec31b5e7cb37d90b7abb0", "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/diff-action-base.hpp", "max_issues_repo_name": "paLeziart/crocoddyl", "max_issues_repo_head_hexsha": "c31a27432f9f2b365faec31b5e7cb37d90b7abb0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/diff-action-base.hpp", "max_forks_repo_name": "paLeziart/crocoddyl", "max_forks_repo_head_hexsha": "c31a27432f9f2b365faec31b5e7cb37d90b7abb0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9160839161, "max_line_length": 119, "alphanum_fraction": 0.6368630422, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.047425875702009436, "lm_q1q2_score": 0.0191395114427049}}
{"text": "/**\n * @file uninformed_bidirectional_pruning.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 Licence\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_GRAPH_PRUNING_ALGORITHMS_HPP\n#define BOOST_GRAPH_PRUNING_ALGORITHMS_HPP\n\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <arlib/details/arlib_utils.hpp>\n#include <arlib/routing_kernels/bidirectional_dijkstra.hpp>\n#include <arlib/routing_kernels/visitor.hpp>\n#include <arlib/type_traits.hpp>\n\n#include <arlib/details/ubp_impl.hpp>\n\n#include <limits>\n#include <unordered_set>\n#include <vector>\n\n/**\n * An Alternative-Routing library for Boost.Graph\n */\nnamespace arlib {\ntemplate <typename Graph>\nusing PrunedGraph =\n    boost::filtered_graph<Graph, details::pruned_edges<edge_of_t<Graph>>>;\n/**\n * An implementation of Uninformed Bidirectional Pruning for Boost::Graph.\n *\n * This implementation refers to the following publication:\n *\n * Andreas Paraskevopoulos, Christos Zaroliagis. Improved Alternative Route\n * Planning. Daniele Frigioni and Sebastian Stiller. ATMOS - 13th Workshop on\n * Algorithmic Approaches for Transportation Modelling, Optimization, and\n * Systems - 2013, Sep 2013, Sophia Antipolis, France. Schloss\n * Dagstuhl–Leibniz-Zentrum fuer Informatik, 33, pp.108–122, 2013, OpenAccess\n * Series in Informatics (OASIcs).\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 RevWeightMap Same as `WeightMap`, but for\n *         `boost::reverse_graph<Graph>`\n * @param G The input graph.\n * @param weight_f The weight map of `G`.\n * @param rev_G A `boost::reverse_graph` of `G`\n * @param weight_b The weight map of `rev_G`.\n * @param s The source node.\n * @param t The target node.\n * @param tau The pruning factor.\n * @return A pruned copy of `G`.\n */\ntemplate <typename Graph, typename WeightMap, typename RevWeightMap,\n          typename Vertex = vertex_of_t<Graph>>\nPrunedGraph<Graph>\nuninformed_bidirectional_pruner(const Graph &G, WeightMap const &weight_f,\n                                boost::reverse_graph<Graph> const &rev_G,\n                                RevWeightMap const &weight_b, Vertex s,\n                                Vertex t, double tau) {\n  using namespace boost;\n  using Length = typename boost::property_traits<WeightMap>::value_type;\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n  using RevEdge =\n      typename graph_traits<boost::reverse_graph<Graph>>::edge_descriptor;\n\n  BOOST_CONCEPT_ASSERT((VertexAndEdgeListGraphConcept<Graph>));\n  BOOST_CONCEPT_ASSERT(\n      (VertexAndEdgeListGraphConcept<boost::reverse_graph<Graph>>));\n  BOOST_CONCEPT_ASSERT((LvaluePropertyMapConcept<WeightMap, Edge>));\n  BOOST_CONCEPT_ASSERT((LvaluePropertyMapConcept<RevWeightMap, RevEdge>));\n\n  // Instantiate data structures\n  auto distance_f_vec = std::vector<Length>(num_vertices(G), 6);\n  auto predecessor_f_vec =\n      std::vector<Vertex>(vertices(G).first, vertices(G).second);\n  auto vertex_id = get(vertex_index, G);\n  auto distance_f =\n      make_iterator_property_map(std::begin(distance_f_vec), vertex_id);\n  auto predecessor_f =\n      make_iterator_property_map(std::begin(predecessor_f_vec), vertex_id);\n\n  // Reverse tree\n  auto vertex_id_b = get(vertex_index, G);\n  auto distance_b_vec = std::vector<Length>(num_vertices(rev_G));\n  auto predecessor_b_vec =\n      std::vector<Vertex>(vertices(rev_G).first, vertices(rev_G).second);\n  auto predecessor_b =\n      make_iterator_property_map(std::begin(predecessor_b_vec), vertex_id_b);\n\n  auto distance_b =\n      make_iterator_property_map(std::begin(distance_b_vec), vertex_id_b);\n\n  // Pruning visitor\n  auto pruning_visitor = UninformedBiPrunerVisitor<Vertex>{tau};\n\n  bidirectional_dijkstra(G, s, t, predecessor_f, distance_f, weight_f, rev_G,\n                         predecessor_b, distance_b, weight_b, pruning_visitor);\n\n  // auto pruned_G = Graph{G};\n  auto prd_edges = std::unordered_set<Edge, boost::hash<Edge>>{};\n\n  auto sp = details::build_edge_list_from_dijkstra(G, s, t, predecessor_f);\n  auto final_distance =\n      details::compute_length_from_edges(sp.begin(), sp.end(), weight_f);\n  for (auto [v_it, v_end] = pruning_visitor.get_pruned_vertices();\n       v_it != v_end; ++v_it) {\n    bool should_prune =\n        details::pruning_policy(s, t, *v_it, predecessor_f, predecessor_b,\n                                distance_f, distance_b, tau, final_distance);\n    if (should_prune) {\n      for (auto [adj_it, adj_end] = adjacent_vertices(*v_it, G);\n           adj_it != adj_end; ++adj_it) {\n        auto u = *adj_it;\n        auto v = *v_it;\n\n        auto [uv_e, uv_exists] = edge(u, v, G);\n        if (uv_exists) {\n          prd_edges.insert(uv_e);\n        }\n\n        auto [vu_e, vu_exists] = edge(v, u, G);\n        if (vu_exists) {\n          prd_edges.insert(vu_e);\n        }\n      }\n    }\n  }\n\n  const auto pruned_G =\n      filtered_graph(G, details::pruned_edges{std::move(prd_edges)});\n  return pruned_G;\n}\n\n/**\n * An implementation of Uninformed Bidirectional Pruning for 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 uninformed_bidirectional_pruner(const Graph &G, WeightMap const\n *                                      &weight_f, boost::reverse_graph<Graph>\n *                                      const &rev_G, RevWeightMap const\n *                                      &weight_b, Vertex s, Vertex t, double\n *                                      tau)\n *\n * @tparam PropertyGraph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n *\n * @return A pruned copy of `G`.\n */\ntemplate <typename PropertyGraph, typename Vertex = vertex_of_t<PropertyGraph>>\nPrunedGraph<PropertyGraph>\nuninformed_bidirectional_pruner(const PropertyGraph &G, Vertex s, Vertex t,\n                                double tau) {\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  auto rev = make_reverse_graph(G);\n  auto weight_b = get(edge_weight, rev);\n  return uninformed_bidirectional_pruner(G, weight, rev, weight_b, s, t, tau);\n}\n} // namespace arlib\n\n#endif\n", "meta": {"hexsha": "b7e145ad1ae3ffe01a89784cc2d76f46f5c41078", "size": 8231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/uninformed_bidirectional_pruning.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/uninformed_bidirectional_pruning.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/uninformed_bidirectional_pruning.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": 39.7632850242, "max_line_length": 80, "alphanum_fraction": 0.703924189, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.044018646727667046, "lm_q1q2_score": 0.019103277430051906}}
{"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 \"SiconosMatrixSetBlock.hpp\"\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include \"SiconosMatrix.hpp\"\n#include \"SiconosException.hpp\"\n\nvoid setBlock(SPC::SiconosMatrix  input_matrix, SP::SiconosMatrix output_matrix, const Index& dim, const Index& start)\n{\n  // To copy a subBlock of input_matrix into a subBlock of output_matrix.\n  // dim[0], dim[1]: number of rows and columns of the sub-block\n  // start[0], start[1]: position (row, column) of the first element of the subBlock in input_matrix\n  // start[2], start[3]: position (row, column) of the first element of the subBlock in output_matrix\n\n  if(input_matrix == output_matrix)  // useless op => nothing to be done.\n    return;\n\n  Siconos::UBLAS_TYPE numIn = input_matrix->num();\n  Siconos::UBLAS_TYPE numOut = output_matrix->num();\n\n  if(numOut == Siconos::ZERO || numOut == Siconos::IDENTITY)  // if output_matrix = 0 or Identity => read-only\n    THROW_EXCEPTION(\"output_matrix is read-only (zero or identity matrix?).\");\n\n  // Check dimension\n  Index MDim(4); // dim. of matrices input_matrix and output_matrix.\n  MDim[0] = input_matrix->size(0);\n  MDim[1] = input_matrix->size(1);\n  MDim[2] = output_matrix->size(0);\n  MDim[3] = output_matrix->size(1);\n\n  for(unsigned int i = 0; i < 4 ; ++i)\n    if(start[i] >= MDim[i])\n      THROW_EXCEPTION(\"matrices, setBlock(input_matrix, ...): sub-block indices are out of range.\");\n\n  // index position of the last element in subBlock ...\n  Index end(4);\n  end[0] = dim[0] + start[0];\n  end[1] = dim[1] + start[1];\n  end[2] = dim[0] + start[2];\n  end[3] = dim[1] + start[3];\n\n  for(unsigned int i = 0; i < 4 ; ++i)\n    if(end[i] > MDim[i])\n      THROW_EXCEPTION(\"sub-block last indices are out of range.\");\n\n  // Elements from row/col start[i] to row/col (end[i]-1) will be copied.\n\n  // If both matrices input_matrix and output_matrix are block, exception.\n  if(numIn == Siconos::BLOCK && numOut == Siconos::BLOCK)\n    THROW_EXCEPTION(\"not yet implemented for input_matrix and output_matrix both BlockMatrix. Try to use setBlock on the sub-matrices?\");\n\n  if(numOut == Siconos::BLOCK)  // if output_matrix is a BlockMatrix.\n  {\n\n    // Steps:\n    // A - Find the blocks of output_matrix that \"own\" indices start[2] and end[2] ie\n    //     the first and last sub-block to be set in a block-column\n    //         --> numbers blockStart0 and blockEnd0\n    // B - Find the  Block of output_matrix that \"owns\" index start[3] and end[3] ie\n    //     the first sub-block to be set in a block-row\n    //         --> numbers blockStart1 and blockEnd1\n    //\n    //        => The blocks concerned in output_matrix, are those between (block) rows blockStart0 and blockEnd0\n    //           and (block) columns blockStart1 and blockEnd1.\n    //\n    // C - Loop through the concerned blocks (name = currentBlock) of output_matrix and call setBlock(input_matrix, currentBlock, subSize, currentPos).\n    //     subSize: dim. of the considered sub-block of currentBlock to be set\n    //     currentPos: same as \"start\" vector but for currentBlock\n    //\n\n    // A - Block-Row position: we look for the block of output_matrix that include index start[2] and end[2].\n    //\n    unsigned int blockStart0 = 0;\n    SPC::Index tab = output_matrix->tabRow();\n    while(start[2] >= (*tab)[blockStart0] && blockStart0 < tab->size())\n      blockStart0 ++;\n    // Relative position in the block blockStart0 of the first element to be set.\n    unsigned int posOut0 = start[2];\n    if(blockStart0 != 0)\n      posOut0 -= (*tab)[blockStart0 - 1];\n\n    unsigned int blockEnd0 = blockStart0;\n    while(end[2] > (*tab)[blockEnd0] && blockEnd0 < tab->size())\n      blockEnd0 ++;\n\n    // Size of the last sub-block in the column of block\n    unsigned int lastBlockSize0 = end[2];\n    if(blockEnd0 != 0)\n      lastBlockSize0 -= (*tab)[blockEnd0 - 1];\n\n    // B - Block-Col position: we look for the block of output_matrix that include index start[3] and end[3].\n    unsigned int blockStart1 = 0;\n    tab = output_matrix->tabCol();\n    while(start[3] >= (*tab)[blockStart1] && blockStart1 < tab->size())\n      blockStart1 ++;\n    // Relative position in the block blockStart1 of the first element to be set.\n    unsigned int posOut1 = start[3];\n    if(blockStart1 != 0)\n      posOut1 -= (*tab)[blockStart1 - 1];\n\n    unsigned int blockEnd1 = blockStart1;\n    while(end[3] > (*tab)[blockEnd1] && blockEnd1 < tab->size())\n      blockEnd1 ++;\n\n    // Size of the last sub-block in the row of block\n    unsigned int lastBlockSize1 = end[3];\n    if(blockEnd1 != 0)\n      lastBlockSize1 -= (*tab)[blockEnd1 - 1];\n\n    //C - Next, 3 steps for each row:\n    // - set first sub-block in the row (number blockStart1)\n    // - set all other blocks in the row except the last one\n    // - set last block (number blockEnd1)\n    // Same process for other rows ...\n\n    // The current considered block\n    SP::SiconosMatrix   currentBlock = output_matrix->block(blockStart0, blockStart1);\n\n    // dim of the subBlock of currentBlock to be set.\n    Index subSize(2);\n    // indices of the first element of input_matrix (resp. currentBlock) to be read (resp. set)  (same as start for input_matrix and output_matrix).\n    Index currentPos(4);\n\n    // currentBlock position in output_matrix.\n    unsigned int numRow = blockStart0;\n    unsigned int numCol = blockStart1;\n\n    // Init currentPos\n    // row and col position for first element to be read in input_matrix,\n    currentPos[0] = start[0];\n    currentPos[1] = start[1];\n    // row and col position for first element in sub-block of Mout (namely currentBlock).\n    currentPos[2] = posOut0;\n    currentPos[3] = posOut1;\n\n    while(numRow != blockEnd0 + 1)\n    {\n\n      while(numCol != blockEnd1 + 1)\n      {\n        // Get the block of output_matrix from which a sub-block will be set ...\n        currentBlock = output_matrix->block(numRow, numCol);\n\n        // Set subSize[0], dim (rows) and subSize[1], dim (columns) of the sub-block.\n        // subSize[0] is only required for the first block in the row, after it remains constant.\n        subSize[1] = currentBlock->size(1);\n\n        // Warning: test \"a\" must be done before test \"b\"\n        if(numCol == blockEnd1)  // if last column of blocks -> test \"a\"\n          subSize[1] = lastBlockSize1;\n\n        if(numCol == blockStart1)  // -> test \"b\"\n        {\n          subSize[1] -= posOut1;\n          subSize[0] = currentBlock->size(0);\n          if(numRow == blockEnd0)  // if last row of blocks\n            subSize[0] = lastBlockSize0;\n          if(numRow == blockStart0)  // if first row of blocks\n            subSize[0] -= posOut0;\n        }\n\n        // Set sub-block\n        setBlock(input_matrix, currentBlock, subSize, currentPos);\n\n        // Update currentPos:\n        // col position for first element to be read in input_matrix,\n        currentPos[1] += subSize[1] ;\n        // col position for first element to be set in sub-block.\n        currentPos[3] = 0;\n        numCol++;\n      }\n\n      numCol = blockStart1;\n      numRow++;\n\n      // Update currentPos:\n      // row position for first element to be read in input_matrix,\n      currentPos[0] += subSize[0] ;\n      // col position for first element to be read in input_matrix,\n      currentPos[1] = start[1] ;\n      // row position for first element to be set in sub-block.\n      currentPos[2] = 0;\n      // col position for first element to be set in sub-block.\n      currentPos[3] = posOut1;\n\n    }\n\n  }\n  else if(numIn == Siconos::BLOCK)  // If input_matrix is a BlockMatrix.\n  {\n\n    // Same process as for numOut == 0\n\n    unsigned int blockStart0 = 0;\n    SPC::Index tab = input_matrix->tabRow();\n    while(start[0] >= (*tab)[blockStart0] && blockStart0 < tab->size())\n      blockStart0 ++;\n    // Relative position in the block blockStart0 of the first element to be set.\n    unsigned int posOut0 = start[0];\n    if(blockStart0 != 0)\n      posOut0 -= (*tab)[blockStart0 - 1];\n\n    unsigned int blockEnd0 = blockStart0;\n    while(end[0] > (*tab)[blockEnd0] && blockEnd0 < tab->size())\n      blockEnd0 ++;\n\n    // Size of the last sub-block in the column of block\n    unsigned int lastBlockSize0 = end[0];\n    if(blockEnd0 != 0)\n      lastBlockSize0 -= (*tab)[blockEnd0 - 1];\n\n    // B - Block-Col position: we look for the block of output_matrix that include index start[3] and end[3].\n    unsigned int blockStart1 = 0;\n    tab = input_matrix->tabCol();\n    while(start[1] >= (*tab)[blockStart1] && blockStart1 < tab->size())\n      blockStart1 ++;\n    // Relative position in the block blockStart1 of the first element to be set.\n    unsigned int posOut1 = start[1];\n    if(blockStart1 != 0)\n      posOut1 -= (*tab)[blockStart1 - 1];\n\n    unsigned int blockEnd1 = blockStart1;\n    while(end[1] > (*tab)[blockEnd1] && blockEnd1 < tab->size())\n      blockEnd1 ++;\n\n    // Size of the last sub-block in the row of block\n    unsigned int lastBlockSize1 = end[1];\n    if(blockEnd1 != 0)\n      lastBlockSize1 -= (*tab)[blockEnd1 - 1];\n\n    //C - Next, 3 steps for each row:\n    // - set first sub-block in the row (number blockStart1)\n    // - set all other blocks in the row except the last one\n    // - set last block (number blockEnd1)\n    // Same process for other rows ...\n\n    // The current considered block\n    SPC::SiconosMatrix  currentBlock = input_matrix->block(blockStart0, blockStart1);\n\n    // dim of the subBlock of currentBlock to be set.\n    Index subSize(2);\n    // indices of the first element of input_matrix (resp. currentBlock) to be read (resp. set)  (same as start for input_matrix and output_matrix).\n    Index currentPos(4);\n\n    // currentBlock position in output_matrix.\n    unsigned int numRow = blockStart0;\n    unsigned int numCol = blockStart1;\n\n    // Init currentPos\n    // row and col position for first element to be read in input_matrix,\n    currentPos[0] = posOut0;\n    currentPos[1] = posOut1;\n    // row and col position for first element in sub-block of Mout (namely currentBlock).\n    currentPos[2] = start[2];\n    currentPos[3] = start[3];\n\n    while(numRow != blockEnd0 + 1)\n    {\n\n      while(numCol != blockEnd1 + 1)\n      {\n        // Get the block of output_matrix from which a sub-block will be set ...\n        currentBlock = input_matrix->block(numRow, numCol);\n\n        // Set subSize[0], dim (rows) and subSize[1], dim (columns) of the sub-block.\n        // subSize[0] is only required for the first block in the row, after it remains constant.\n        subSize[1] = currentBlock->size(1);\n        // Warning: test \"a\" must be done before test \"b\"\n        if(numCol == blockEnd1)  // if last column of blocks -> test \"a\"\n          subSize[1] = lastBlockSize1;\n\n        if(numCol == blockStart1)  // -> test \"b\"\n        {\n          subSize[1] -= posOut1;\n          subSize[0] = currentBlock->size(0);\n          if(numRow == blockEnd0)  // if last row of blocks\n            subSize[0] = lastBlockSize0;\n          if(numRow == blockStart0)  // if first row of blocks\n            subSize[0] -= posOut0;\n        }\n\n        // Set sub-block\n        setBlock(currentBlock, output_matrix, subSize, currentPos);\n\n        // Update currentPos:\n        // col position for first element to be read in input_matrix,\n        currentPos[1] = 0 ;\n        // col position for first element to be set in sub-block.\n        currentPos[3] += subSize[1];\n        numCol++;\n      }\n\n      numCol = blockStart1;\n      numRow++;\n\n      // Update currentPos:\n      // row position for first element to be read in input_matrix,\n      currentPos[0] = 0;\n      // col position for first element to be read in input_matrix,\n      currentPos[1] = posOut1;\n      // row position for first element to be set in sub-block.\n      currentPos[2] += subSize[0] ;\n      // col position for first element to be set in sub-block.\n      currentPos[3] = start[3];\n\n    }\n    output_matrix->resetFactorizationFlags();\n\n  }\n  else // neither input_matrix nor output_matrix is a BlockMatrix.\n  {\n    if(numOut == Siconos::DENSE)\n    {\n      ublas::matrix_range<DenseMat> out_range(*output_matrix->dense(),\n                                              ublas::range(start[2],end[2]),\n                                              ublas::range(start[3], end[3]));\n      if(numIn == Siconos::DENSE)\n      {\n        ublas::matrix_range<DenseMat> in_range(*input_matrix->dense(),\n                                               ublas::range(start[0],end[0]),\n                                               ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::SYMMETRIC)\n      {\n        ublas::matrix_range<SymMat> in_range(*input_matrix->sym(),\n                                             ublas::range(start[0],end[0]),\n                                             ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::SPARSE)\n      {\n        ublas::matrix_range<SparseMat> in_range(*input_matrix->sparse(),\n                                                ublas::range(start[0],end[0]),\n                                                ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::IDENTITY)\n      {\n        ublas::matrix_range<IdentityMat> in_range(*input_matrix->identity(),\n                                                  ublas::range(start[0],end[0]),\n                                                  ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::ZERO)\n        out_range *= 0.;\n      else\n        THROW_EXCEPTION(\"unconsistent types between input_matrix and output_matrix.\");\n    }\n    else if(numOut == Siconos::SPARSE)\n    {\n      ublas::matrix_range<SparseMat> out_range(*output_matrix->sparse(),\n                                               ublas::range(start[2],end[2]),\n                                               ublas::range(start[3], end[3]));\n      if(numIn == Siconos::DENSE)\n      {\n        ublas::matrix_range<DenseMat> in_range(*input_matrix->dense(),\n                                               ublas::range(start[0],end[0]),\n                                               ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::SYMMETRIC)\n      {\n        ublas::matrix_range<SymMat> in_range(*input_matrix->sym(),\n                                             ublas::range(start[0],end[0]),\n                                             ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::SPARSE)\n      {\n        ublas::matrix_range<SparseMat> in_range(*input_matrix->sparse(),\n                                                ublas::range(start[0],end[0]),\n                                                ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::IDENTITY)\n      {\n        ublas::matrix_range<IdentityMat> in_range(*input_matrix->identity(),\n                                                  ublas::range(start[0],end[0]),\n                                                  ublas::range(start[1], end[1]));\n        noalias(out_range) = in_range;\n      }\n      else if(numIn == Siconos::ZERO)\n        out_range *= 0.;\n      else\n        THROW_EXCEPTION(\"unconsistent types between input_matrix and output_matrix.\");\n    }\n\n    output_matrix->resetFactorizationFlags();\n  }\n}\n", "meta": {"hexsha": "8a12bf36a86f8a1af3bc21b71ec8cf05f83737e8", "size": 16348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosMatrixSetBlock.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/SiconosMatrixSetBlock.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/SiconosMatrixSetBlock.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": 39.6796116505, "max_line_length": 151, "alphanum_fraction": 0.6023978468, "num_tokens": 4259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988313272769, "lm_q2_score": 0.046033897654976556, "lm_q1q2_score": 0.019099410338489244}}
{"text": "/*\n * Copyright (C) 2015 INRA\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 *    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 *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n * OR 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 SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef ORG_VLEPROJECT_KERNEL_DEVS_QSS1_HPP\n#define ORG_VLEPROJECT_KERNEL_DEVS_QSS1_HPP\n\n#include <vle/devs/devs.hpp>\n#include <vle/qss-common.hpp>\n#include <boost/math/special_functions/sign.hpp>\n\nnamespace vle {\nnamespace devs {\nnamespace qss {\n\ninline static constexpr double nan() noexcept\n{\n    return std::numeric_limits <double>::quiet_NaN();\n}\n\nstruct QssInputPort {\n    QssInputPort(std::size_t size) noexcept\n        : m_value(size, nan())\n        , m_dirac(false)\n    {}\n\n    const double &operator[](std::size_t i) const noexcept\n    {\n        return m_value[i];\n    }\n\n    double &operator[](std::size_t i) noexcept\n    {\n        return m_value[i];\n    }\n\n    void dirac() noexcept\n    {\n        m_dirac = true;\n    }\n\n    void clear() noexcept\n    {\n        std::fill(m_value.begin(), m_value.end(), nan());\n        m_dirac = false;\n    }\n\n    std::size_t size() const noexcept\n    {\n        return m_value.size();\n    }\n\n    bool empty() const noexcept\n    {\n        if (m_dirac)\n            return false;\n\n        for (auto val : m_value)\n            if (not std::isnan(val))\n                return false;\n\n        return true;\n    }\n\n    std::vector <double> m_value;\n    bool m_dirac;\n};\n\nstruct QssOutputPort {\n    constexpr QssOutputPort(double) noexcept\n        : m_value(nan())\n    {}\n\n    constexpr const double &operator[](std::size_t) const noexcept\n    {\n        return m_value;\n    }\n\n    constexpr double &operator[](std::size_t) noexcept\n    {\n        return m_value;\n    }\n\n    constexpr std::size_t size() const noexcept\n    {\n        return 1u;\n    }\n\n    constexpr void clear() noexcept\n    {\n        m_value = nan();\n    }\n\n    bool empty() const noexcept\n    {\n        return std::isnan(m_value);\n    }\n\n    double m_value;\n};\n\ntemplate <typename Time, typename Container>\nclass StaticFunction : public AtomicModel <Time, QssInputPort, QssOutputPort>\n{\npublic:\n    using parent_type = AtomicModel <Time, QssInputPort, QssOutputPort>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n    using inputport_type = typename parent_type::inputport_type;\n    using outputport_type = typename parent_type::inputport_type;\n\n    StaticFunction(const Context &ctx, std::size_t system_size,\n                   Function <Time, Container> function_)\n        : parent_type(ctx, system_size, nan())\n        , m_integrate_function(function_)\n        , m_variable(system_size)\n        , m_sigma(Time::infinity())\n        , m_time(Time::null())\n    {\n        if (system_size == 0ul)\n            throw std::invalid_argument(\n                \"vle::dsde::qss1::StaticFunction: bad system size\");\n    }\n\n    virtual time_type ta() const\n    {\n        return m_sigma;\n    }\n\n    virtual void lambda() const\n    {\n        parent_type::y[0] = m_integrate_function(m_variable, m_time);\n    }\n\n    virtual void internal()\n    {\n        m_sigma = Time::infinity();\n    }\n\n    virtual void external(const time_type &e)\n    {\n        m_time += e;\n        m_sigma = Time::infinity();\n\n        for (std::size_t i = 0ul, end = parent_type::x.size(); i != end; ++i) {\n            if (not std::isnan(parent_type::x[i])) {\n                m_variable[i] = parent_type::x[i];\n                m_sigma = Time::null();\n            }\n        }\n    }\n\nprivate:\n    Function <Time, Container> m_integrate_function;\n    Container m_variable;\n    time_type m_sigma;\n    time_type m_time;\n};\n\ntemplate <typename Time>\nclass Integrator : public AtomicModel <Time, QssInputPort, QssOutputPort>\n{\npublic:\n    using parent_type = AtomicModel <Time, QssInputPort, QssOutputPort>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n\n    Integrator(const Context &ctx, double dq, double epsilon, double x)\n        : parent_type(ctx, 1u, nan())\n        , m_sigma(Time::null())\n        , m_dq(dq)\n        , m_epsilon(epsilon)\n        , m_X(x)\n        , m_dX(0.0)\n        , m_q(std::floor(x / dq) * dq)\n    {}\n\n    virtual time_type ta() const\n    {\n        return m_sigma;\n    }\n\n    virtual void lambda() const\n    {\n        parent_type::y[0] = m_q + m_dq * boost::math::sign(m_dX);\n    }\n\n    virtual void internal()\n    {\n        m_X += (m_sigma * m_dX);\n\n        if (m_dX > 0.0) {\n            m_sigma = m_dq / m_dX;\n            m_q = m_q + m_dq;\n        } else if (m_dX < 0.0) {\n            m_sigma = - m_dq / m_dX;\n            m_q = m_q - m_dq;\n        } else {\n            m_sigma = Time::infinity();\n        }\n    }\n\n    virtual void external(const time_type &e)\n    {\n        auto xv = parent_type::x[0];\n        m_X += (e * m_dX);\n\n        if (xv > 0.0) {\n            m_sigma = (m_q + m_dq - m_X) / xv;\n        } else if (xv < 0.0) {\n            m_sigma = (m_q - m_epsilon - m_X) / xv;\n        } else {\n            m_sigma = Time::infinity();\n        }\n\n        m_dX = xv;\n    }\n\n    constexpr inline double value() const noexcept\n    {\n        return m_X;\n    }\n\nprivate:\n    time_type m_sigma;\n    double m_dq;\n    double m_epsilon;\n    double m_X;\n    double m_dX;\n    double m_q;\n};\n\ntemplate <typename Time, typename Container>\nclass EquationBlock : public CoupledModel <\n    Time, QssInputPort, QssOutputPort,\n    QssInputPort, QssOutputPort >\n{\npublic:\n    using parent_type = CoupledModel <Time, QssInputPort, QssOutputPort,\n          QssInputPort, QssOutputPort>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n    using child_type = typename parent_type::child_type;\n\n    using UpdatedPort = typename parent_type::UpdatedPort;\n\n    EquationBlock(const vle::Context &ctx,\n                  double dq,\n                  double epsilon,\n                  double x,\n                  std::size_t system_size,\n                  std::size_t id,\n                  Function <Time, Container> function_)\n        : parent_type(ctx, system_size, nan())\n        , m_integrator(ctx, dq, epsilon, x)\n        , m_staticfunction(ctx, system_size, function_)\n        , m_id(id)\n    {\n        if (id >= system_size)\n            throw std::invalid_argument(\n                \"vle::dsde::qss1::EquationBlock: bad id or system size\");\n    }\n\n    virtual typename parent_type::children_t\n    children() override final\n    {\n        return { &m_integrator, &m_staticfunction };\n    }\n\n    virtual void post(const child_type *out, UpdatedPort &in) const override\n    {\n        if (!out) {\n            for (std::size_t i = 0ul, end = parent_type::x.size(); i != end;\n                ++i) {\n                if (!std::isnan(parent_type::x[i])) {\n                    m_staticfunction.x[i] = parent_type::x[i];\n                    in.emplace(&m_staticfunction);\n                }\n            }\n        } else if (out == &m_integrator) {\n            if (not m_integrator.y.empty()) {\n                m_staticfunction.x[m_id] = m_integrator.y[0];\n                parent_type::y[0] = m_integrator.y[0];\n                in.emplace(&m_staticfunction);\n            }\n        } else if (out == &m_staticfunction) {\n            if (not m_staticfunction.y.empty()) {\n                m_integrator.x[0] = m_staticfunction.y[0];\n                in.emplace(&m_integrator);\n            }\n        }\n    }\n\n    virtual std::size_t select(const std::vector <child_type *> &) const override\n    {\n        return 0u;\n    }\n\n    constexpr inline double value() const noexcept\n    {\n        return m_integrator.value();\n    }\n\nprivate:\n    Integrator <Time> m_integrator;\n    StaticFunction <Time, Container> m_staticfunction;\n    std::size_t m_id;\n};\n\ntemplate <typename Time, typename Container>\nclass Equation : public AtomicModel <Time, QssInputPort, QssOutputPort>\n{\npublic:\n    using parent_type = AtomicModel <Time, QssInputPort, QssOutputPort>;\n    using time_format = typename parent_type::time_format;\n    using time_type = typename parent_type::time_type;\n\n    Equation(const Context &ctx,\n             double dq,\n             double epsilon,\n             double x,\n             std::size_t system_size,\n             std::size_t id,\n             Function <Time, Container> function)\n        : parent_type(ctx, system_size, nan())\n        , m_integrate_function(function)\n        , m_variables(system_size)\n        , m_sigma(Time::null())\n        , m_time(Time::null())\n        , m_dq(dq)\n        , m_epsilon(epsilon)\n        , m_X(x)\n        , m_dX(0.0)\n        , m_q(std::floor(x / dq) * dq)\n        , m_id(id)\n    {\n        if (system_size == 0ul)\n            throw std::invalid_argument(\n                \"vle::dsde::qss1::Equation: bad system size\");\n\n        if (id >= system_size)\n            throw std::invalid_argument(\n                \"vle::dsde::qss1::Equation: bad id or system size\");\n\n        m_variables[m_id] = m_q;\n    }\n\n    virtual time_type ta() const\n    {\n        return m_sigma;\n    }\n\n    virtual void lambda() const override final\n    {\n        parent_type::y[0] = m_q + m_dq * boost::math::sign(m_dX);\n    }\n\n    virtual void internal()\n    {\n        m_time += m_sigma;\n        m_X += (m_sigma * m_dX);\n\n        if (m_dX > 0.0) {\n            m_sigma = m_dq / m_dX;\n            m_q = m_q + m_dq;\n        } else if (m_dX < 0.0) {\n            m_sigma = - m_dq / m_dX;\n            m_q = m_q - m_dq;\n        } else {\n            m_sigma = Time::infinity();\n        }\n    }\n\n    virtual void external(const time_type &e)\n    {\n        m_time += e;\n\n        for (std::size_t i = 0, end = parent_type::x.size(); i != end; ++i)\n            if (not std::isnan(parent_type::x[i]))\n                m_variables[i] = parent_type::x[i];\n\n        m_variables[m_id] = m_q + m_dq * boost::math::sign(m_dX);\n        auto xv = m_integrate_function(m_variables, m_time);\n        m_X += (e * m_dX);\n\n        if (xv > 0.0) {\n            m_sigma = (m_q + m_dq - m_X) / xv;\n        } else if (xv < 0.0) {\n            m_sigma = (m_q - m_epsilon - m_X) / xv;\n        } else {\n            m_sigma = Time::infinity();\n        }\n\n        m_dX = xv;\n    }\n\n    constexpr inline double value() const noexcept\n    {\n        return m_X;\n    }\n\nprivate:\n    Function <Time, Container> m_integrate_function;\n    Container m_variables;\n    time_type m_sigma;\n    time_type m_time;\n    double m_dq;\n    double m_epsilon;\n    double m_X;\n    double m_dX;\n    double m_q;\n    std::size_t m_id;\n};\n\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "490f14f4b699445ea93d2a66d174eada42790aa3", "size": 11685, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vle/devs/qss1.hpp", "max_stars_repo_name": "quesnel/Echll", "max_stars_repo_head_hexsha": "e14a588f065d734ba8971576f407a89a4e5af9dd", "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": "vle/devs/qss1.hpp", "max_issues_repo_name": "quesnel/Echll", "max_issues_repo_head_hexsha": "e14a588f065d734ba8971576f407a89a4e5af9dd", "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": "vle/devs/qss1.hpp", "max_forks_repo_name": "quesnel/Echll", "max_forks_repo_head_hexsha": "e14a588f065d734ba8971576f407a89a4e5af9dd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4366515837, "max_line_length": 81, "alphanum_fraction": 0.583055199, "num_tokens": 2946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.04958902193059524, "lm_q1q2_score": 0.01908741677416622}}
{"text": "/**\n * @file LatticeModelFactory.cpp\n * @author Finn Lasse Buessen\n * @brief Create lattice representations from a lattice unit cell and specification of spin interactions. \n * \n * @copyright Copyright (c) 2020\n */\n\n#include \"LatticeModelFactory.hpp\"\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/regex.hpp>\n#include <boost/format.hpp>\n#include \"lib/Geometry.hpp\"\n#include \"lib/InputParser.hpp\"\n#include \"lib/Exception.hpp\"\n#include \"lib/Log.hpp\"\n\n#define __EPSILON 0.00001\n#define PI 3.14159265358979323846\n\nnamespace LatticeModelFactory\n{\n\t#pragma region LatticeSite definition\n\tLatticeSite::LatticeSite()\n\t{\n\t\ta0 = 0;\n\t\ta1 = 0;\n\t\ta2 = 0;\n\t\tb = 0;\n\t}\n\n\tLatticeSite::LatticeSite(const int a0, const int a1, const int a2, const int b) : LatticeSite()\n\t{\n\t\tthis->a0 = a0;\n\t\tthis->a1 = a1;\n\t\tthis->a2 = a2;\n\t\tthis->b = b;\n\t}\n\n\tbool LatticeSite::operator==(const LatticeSite& rhs) const\n\t{\n\t\tif (a0 == rhs.a0 && a1 == rhs.a1 && a2 == rhs.a2 && b == rhs.b) return true;\n\t\telse return false;\n\t}\n\n\tbool LatticeSite::operator!=(const LatticeSite& rhs) const\n\t{\n\t\treturn !operator==(rhs);\n\t}\n\t#pragma endregion\n\n\t#pragma region LatticeBond definition\n\tLatticeBond::LatticeBond(const int fromB, const int toB, const int da0, const int da1, const int da2)\n\t{\n\t\tthis->fromB = fromB;\n\t\tthis->toB = toB;\n\t\tthis->da0 = da0;\n\t\tthis->da1 = da1;\n\t\tthis->da2 = da2;\n\t}\n\n\tbool LatticeBond::isAttachedToSite(const LatticeSite& site) const\n\t{\n\t\tif (fromB == site.b || toB == site.b) return true;\n\t\telse return false;\n\t}\n\n\tbool LatticeBond::isConnectingSites(const LatticeSite& site1, const LatticeSite& site2) const\n\t{\n\t\tif (isConnectingFromTo(site1, site2)) return true;\n\t\telse if (isConnectingFromTo(site2, site1)) return true;\n\t\telse return false;\n\t}\n\n\tbool LatticeBond::isConnectingFromTo(const LatticeSite& siteFrom, const LatticeSite& siteTo) const\n\t{\n\t\tif (da0 == (siteTo.a0 - siteFrom.a0) && da1 == (siteTo.a1 - siteFrom.a1) && da2 == (siteTo.a2 - siteFrom.a2) && fromB == siteFrom.b && toB == siteTo.b) return true;\n\t\telse return false;\n\t}\n\n\tstd::vector<LatticeSite> LatticeBond::getOtherEnd(const LatticeSite& site) const\n\t{\n\t\tif (isAttachedToSite(site))\n\t\t{\n\t\t\tif (fromB == site.b)\n\t\t\t{\n\t\t\t\tif (fromB == toB) return std::vector<LatticeSite>({ LatticeSite(site.a0 + da0, site.a1 + da1, site.a2 + da2, toB), LatticeSite(site.a0 - da0, site.a1 - da1, site.a2 - da2, fromB) });\n\t\t\t\telse return std::vector<LatticeSite>({ LatticeSite(site.a0 + da0, site.a1 + da1, site.a2 + da2, toB) });\n\t\t\t}\n\t\t\telse return std::vector<LatticeSite>({ LatticeSite(site.a0 - da0, site.a1 - da1, site.a2 - da2, fromB) });\n\t\t}\n\t\telse throw Exception(Exception::Type::ArgumentError, \"Lattice bond is not attached to specified site\");\n\t}\n\t#pragma endregion\n\n\t#pragma region LatticeUniteCell definition\n\tLatticeUnitCell::LatticeUnitCell() {}\n\n\tLatticeUnitCell::LatticeUnitCell(const std::string &latticeName, const std::string &bundle)\n\t{\n\t\tif (!_initFromResBundle(latticeName, bundle)) throw Exception(Exception::Type::InitializationError, \"Invalid lattice unit cell definition.\");\n\t}\n\n\tbool LatticeUnitCell::_initFromResBundle(const std::string &latticeName, const std::string &bundle)\n\t{\n\t\tboost::filesystem::directory_iterator end;\n\t\tfor (boost::filesystem::directory_iterator it(bundle); it != end; ++it)\n\t\t{\n\t\t\tif (boost::filesystem::is_regular_file(it->path()) && it->path().extension() == \".xml\")\n\t\t\t{\n\t\t\t\tboost::property_tree::ptree latticeDefinition;\n\t\t\t\tboost::property_tree::xml_parser::read_xml(it->path().string(), latticeDefinition);\n\n\t\t\t\tfor (auto u : latticeDefinition)\n\t\t\t\t{\n\t\t\t\t\tif (u.first != \"unitcell\") continue;\n\t\t\t\t\tauto uc = u.second;\n\t\t\t\t\tif (!uc.get_optional<std::string>(\"<xmlattr>.name\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell. Unit cell name is undefined.\");\n\n\t\t\t\t\tif (uc.get<std::string>(\"<xmlattr>.name\") == latticeName)\n\t\t\t\t\t{\n\t\t\t\t\t\t//read unit cell\n\t\t\t\t\t\tif (uc.count(\"primitive\") != 3) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell. Unit cell must define three primitive vectors.\");\n\t\t\t\t\t\tif (uc.count(\"site\") == 0) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell. Unit cell must contain at least one lattice site.\");\n\t\t\t\t\t\tif (uc.count(\"bond\") == 0) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell. Unit cell must contain at least one lattice bond.\");\n\n\t\t\t\t\t\tfor (auto p : uc)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//lattice vector\n\t\t\t\t\t\t\tif (p.first == \"primitive\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.x\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell primitive. x attribute missing.\");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.y\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell primitive. y attribute missing.\");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.z\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell primitive. z attribute missing.\");\n\n\t\t\t\t\t\t\t\tlatticeVectors.push_back(geometry::Vec3<double>(\n\t\t\t\t\t\t\t\t\tInputParser::stringToDouble(p.second.get<std::string>(\"<xmlattr>.x\")),\n\t\t\t\t\t\t\t\t\tInputParser::stringToDouble(p.second.get<std::string>(\"<xmlattr>.y\")),\n\t\t\t\t\t\t\t\t\tInputParser::stringToDouble(p.second.get<std::string>(\"<xmlattr>.z\"))\n\t\t\t\t\t\t\t\t\t));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//basis site\n\t\t\t\t\t\t\telse if (p.first == \"site\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.x\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell site. x attribute missing.\");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.y\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell site. y attribute missing.\");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.z\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell site. z attribute missing.\");\n\n\t\t\t\t\t\t\t\tbasisSites.push_back(geometry::Vec3<double>(\n\t\t\t\t\t\t\t\t\tInputParser::stringToDouble(p.second.get<std::string>(\"<xmlattr>.x\")),\n\t\t\t\t\t\t\t\t\tInputParser::stringToDouble(p.second.get<std::string>(\"<xmlattr>.y\")),\n\t\t\t\t\t\t\t\t\tInputParser::stringToDouble(p.second.get<std::string>(\"<xmlattr>.z\"))\n\t\t\t\t\t\t\t\t\t));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//bond\n\t\t\t\t\t\t\telse if (p.first == \"bond\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.from\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell bond. 'from' attribute missing. \");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.to\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell bond. 'to' attribute missing. \");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.da0\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell bond. 'da0' attribute missing. \");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.da1\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell bond. 'da1' attribute missing. \");\n\t\t\t\t\t\t\t\tif (!p.second.get_optional<std::string>(\"<xmlattr>.da2\")) throw Exception(Exception::Type::InitializationError, \"Invalid unit cell bond. 'da2' attribute missing. \");\n\n\t\t\t\t\t\t\t\tint from = std::stoi(p.second.get<std::string>(\"<xmlattr>.from\"));\n\t\t\t\t\t\t\t\tint to = std::stoi(p.second.get<std::string>(\"<xmlattr>.to\"));\n\t\t\t\t\t\t\t\tint da0 = std::stoi(p.second.get<std::string>(\"<xmlattr>.da0\"));\n\t\t\t\t\t\t\t\tint da1 = std::stoi(p.second.get<std::string>(\"<xmlattr>.da1\"));\n\t\t\t\t\t\t\t\tint da2 = std::stoi(p.second.get<std::string>(\"<xmlattr>.da2\"));\n\t\t\t\t\t\t\t\tthis->latticeBonds.push_back(LatticeBond(from, to, da0, da1, da2));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t#pragma endregion\n\n\t#pragma region SpinInteraction definition\n\tSpinInteraction::SpinInteraction()\n\t{\n\t\tmemset(&interactionStrength[0][0], 0, 9 * sizeof(float));\n\t};\n\n\tSpinInteraction::SpinInteraction(const LatticeSite& from, const LatticeSite& to) : from(from), to(to)\n\t{\n\t\tmemset(&interactionStrength[0][0], 0, 9 * sizeof(float));\n\t};\n\n\tbool SpinInteraction::isConnectingFromTo(const LatticeSite& siteFrom, const LatticeSite& siteTo) const\n\t{\n\t\tif ((to.a0 - from.a0) == (siteTo.a0 - siteFrom.a0) && (to.a1 - from.a1) == (siteTo.a1 - siteFrom.a1) && (to.a2 - from.a2) == (siteTo.a2 - siteFrom.a2) && from.b == siteFrom.b && to.b == siteTo.b) return true;\n\t\telse return false;\n\t}\n\n\tint SpinInteraction::isConnectingSites(const LatticeSite& site1, const LatticeSite& site2) const\n\t{\n\t\tif (isConnectingFromTo(site1, site2)) return 1;\n\t\telse if (isConnectingFromTo(site2, site1)) return -1;\n\t\telse return 0;\n\t}\n\n\tSpinInteraction& SpinInteraction::operator+=(const SpinInteraction& rhs)\n\t{\n\t\tif (from == rhs.from && to == rhs.to)\n\t\t{\n\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t{\n\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2)\n\t\t\t\t{\n\t\t\t\t\tinteractionStrength[s1][s2] += rhs.interactionStrength[s1][s2];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (from == rhs.to && to == rhs.from)\n\t\t{\n\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t{\n\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2)\n\t\t\t\t{\n\t\t\t\t\tinteractionStrength[s1][s2] += rhs.interactionStrength[s2][s1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse throw Exception(Exception::Type::ArgumentError, \"Cannnot combine incompatible spin interactions.\");\n\n\t\treturn *this;\n\t}\n\t#pragma endregion\n\n\t#pragma region SpinModelUnitCell definition\n\tSpinModelUnitCell::SpinModelUnitCell() {}\n\n\tSpinModelUnitCell::SpinModelUnitCell(const std::string &modelName, const std::string &bundle, const std::map<std::string, std::string> &modelOptions)\n\t{\n\t\tif (!_initFromResBundle(modelName, bundle, modelOptions)) throw Exception(Exception::Type::InitializationError, \"Invalid spin model definition.\");\n\t}\n\n\tbool SpinModelUnitCell::_initFromResBundle(const std::string &res, const std::string &bundle, const std::map<std::string, std::string> &modelOptions)\n\t{\n\t\t//read spin model\n\t\tboost::filesystem::directory_iterator end;\n\t\tfor (boost::filesystem::directory_iterator it(bundle); it != end; ++it)\n\t\t{\n\t\t\tif (boost::filesystem::is_regular_file(it->path()) && it->path().extension() == \".xml\")\n\t\t\t{\n\t\t\t\tboost::property_tree::ptree modelDefinition;\n\t\t\t\tboost::property_tree::xml_parser::read_xml(it->path().string(), modelDefinition);\n\n\t\t\t\tfor (auto m : modelDefinition)\n\t\t\t\t{\n\t\t\t\t\tif (m.first != \"model\") continue;\n\t\t\t\t\tauto model = m.second;\n\t\t\t\t\tif (!model.get_optional<std::string>(\"<xmlattr>.name\")) throw Exception(Exception::Type::InitializationError, \"Invalid spin model. Model name is undefined.\");\n\n\t\t\t\t\tif (model.get<std::string>(\"<xmlattr>.name\") == res)\n\t\t\t\t\t{\n\t\t\t\t\t\t//read model\n\t\t\t\t\t\tif (model.count(\"interaction\") == 0) throw Exception(Exception::Type::InitializationError, \"Invalid spin model. Spin model must define at least one interaction.\");\n\n\t\t\t\t\t\tfor (auto i : model)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (i.first != \"interaction\") continue;\n\n\t\t\t\t\t\t\tif (!i.second.get_optional<std::string>(\"<xmlattr>.parameter\")) throw Exception(Exception::Type::InitializationError, \"Invalid interaction. Parameter name not specified. \");\n\t\t\t\t\t\t\tif (!i.second.get_optional<std::string>(\"<xmlattr>.type\")) throw Exception(Exception::Type::InitializationError, \"Invalid interaction. Interaction type not specified. \");\n\t\t\t\t\t\t\tif (!i.second.get_optional<std::string>(\"<xmlattr>.from\")) throw Exception(Exception::Type::InitializationError, \"Invalid interaction. No target sites specified. \");\n\t\t\t\t\t\t\tif (!i.second.get_optional<std::string>(\"<xmlattr>.to\")) throw Exception(Exception::Type::InitializationError, \"Invalid interaction. No target sites specified. \");\n\n\t\t\t\t\t\t\tstd::string parameter = i.second.get<std::string>(\"<xmlattr>.parameter\");\n\t\t\t\t\t\t\tstd::string from = i.second.get<std::string>(\"<xmlattr>.from\");\n\t\t\t\t\t\t\tstd::string to = i.second.get<std::string>(\"<xmlattr>.to\");\n\t\t\t\t\t\t\tstd::string type = i.second.get<std::string>(\"<xmlattr>.type\");\n\n\t\t\t\t\t\t\t//parse lattice sites\n\t\t\t\t\t\t\tboost::regex pattern(\"(-{0,1}\\\\d+)[, ](-{0,1}\\\\d+)[, ](-{0,1}\\\\d+)[, ](\\\\d+)\");\n\t\t\t\t\t\t\tboost::smatch matchSite1;\n\t\t\t\t\t\t\tboost::smatch matchSite2;\n\t\t\t\t\t\t\tif (!boost::regex_match(from, matchSite1, pattern)) throw Exception(Exception::Type::InitializationError, \"Invalid spin model. Site '\" + from + \"' is ill-defined. \");\n\t\t\t\t\t\t\tif (!boost::regex_match(to, matchSite2, pattern)) throw Exception(Exception::Type::InitializationError, \"Invalid spin model. Site '\" + to + \"' is ill-defined. \");\n\n\t\t\t\t\t\t\t//parse coupling strength\n\t\t\t\t\t\t\tfloat interactionStrength;\n\t\t\t\t\t\t\tif (modelOptions.count(parameter)) interactionStrength = InputParser::stringToFloat(modelOptions.at(parameter));\n\t\t\t\t\t\t\telse throw Exception(Exception::Type::InitializationError, \"Interaction parameter '\" + parameter + \"' is not defined in the taskfile\");\n\n\t\t\t\t\t\t\t//generate interaction\n\t\t\t\t\t\t\tSpinInteraction interaction(LatticeSite(std::stoi(matchSite1[1].str()), std::stoi(matchSite1[2].str()), std::stoi(matchSite1[3].str()), std::stoi(matchSite1[4].str())), LatticeSite(std::stoi(matchSite2[1].str()), std::stoi(matchSite2[2].str()), std::stoi(matchSite2[3].str()), std::stoi(matchSite2[4].str())));\n\t\t\t\t\t\t\tif (type == \"heisenberg\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[0][0] += interactionStrength;\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[1][1] += interactionStrength;\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[2][2] += interactionStrength;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (type == \"xxyy\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[0][0] += interactionStrength;\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[1][1] += interactionStrength;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (type == \"gx\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[1][2] += interactionStrength;\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[2][1] += interactionStrength;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (type == \"gy\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[2][0] += interactionStrength;\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[0][2] += interactionStrength;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (type == \"gz\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[0][1] += interactionStrength;\n\t\t\t\t\t\t\t\tinteraction.interactionStrength[1][0] += interactionStrength;\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\tboost::regex pattern(\"(-?)([xyz])([xyz])\");\n\t\t\t\t\t\t\t\tboost::smatch match;\n\t\t\t\t\t\t\t\tif (boost::regex_match(type, match, pattern))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfloat sign = (match[1] == \"-\") ? -1.0f : 1.0f;\n\t\t\t\t\t\t\t\t\tint s1 = 0;\n\t\t\t\t\t\t\t\t\tint s2 = 0;\n\t\t\t\t\t\t\t\t\tif (match[2] == \"x\") s1 = 0;\n\t\t\t\t\t\t\t\t\telse if (match[2] == \"y\") s1 = 1;\n\t\t\t\t\t\t\t\t\telse if (match[2] == \"z\") s1 = 2;\n\t\t\t\t\t\t\t\t\tif (match[3] == \"x\") s2 = 0;\n\t\t\t\t\t\t\t\t\telse if (match[3] == \"y\") s2 = 1;\n\t\t\t\t\t\t\t\t\telse if (match[3] == \"z\") s2 = 2;\n\n\t\t\t\t\t\t\t\t\tinteraction.interactionStrength[s1][s2] += sign * interactionStrength;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse throw Exception(Exception::Type::InitializationError, \"Invalid spin model. Unknown interaction type '\" + type + \"'.\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//add interaction to spin model\n\t\t\t\t\t\t\tauto addInteraction = [&](const SpinInteraction &i)->void\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (auto j = interactions.begin(); j != interactions.end(); ++j)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (j->isConnectingSites(i.from, i.to) != 0)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t(*j) += i;\n\t\t\t\t\t\t\t\t\t\treturn;\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\tinteractions.push_back(i);\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\taddInteraction(interaction);\n\n\t\t\t\t\t\t\t//add required interaction parameter\n\t\t\t\t\t\t\tinteractionParameters.insert(parameter);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t};\n\t#pragma endregion\n\n\t#pragma region private interface\n\tstruct SpinPermutation\n\t{\n\tpublic:\n\t\tSpinPermutation()\n\t\t{\n\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t}\n\n\t\tSpinPermutation(SpinComponent transformedX, SpinComponent transformedY, SpinComponent transformedZ)\n\t\t{\n\t\t\ttransformedComponent[0] = transformedX;\n\t\t\ttransformedComponent[1] = transformedY;\n\t\t\ttransformedComponent[2] = transformedZ;\n\t\t}\n\n\t\tSpinPermutation(const int n)\n\t\t{\n\t\t\tswitch (n)\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 9:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 10:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 11:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 12:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 13:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 14:\n\t\t\t\ttransformedComponent[0] = SpinComponent::X;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 15:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 16:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 17:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 18:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 19:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 20:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Z;\n\t\t\t\tbreak;\n\t\t\tcase 21:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 22:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 23:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusZ;\n\t\t\t\tbreak;\n\t\t\tcase 24:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 25:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 26:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 27:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tcase 28:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 29:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tcase 30:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tcase 31:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tcase 32:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 33:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 34:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 35:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 36:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::Y;\n\t\t\t\tbreak;\n\t\t\tcase 37:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::X;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 38:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 39:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusX;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusY;\n\t\t\t\tbreak;\n\t\t\tcase 40:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 41:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 42:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 43:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tcase 44:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::X;\n\t\t\t\tbreak;\n\t\t\tcase 45:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::Y;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tcase 46:\n\t\t\t\ttransformedComponent[0] = SpinComponent::Z;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tcase 47:\n\t\t\t\ttransformedComponent[0] = SpinComponent::MinusZ;\n\t\t\t\ttransformedComponent[1] = SpinComponent::MinusY;\n\t\t\t\ttransformedComponent[2] = SpinComponent::MinusX;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow Exception(Exception::Type::ArgumentError, \"Specified spin permutation does not exist\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tstatic SpinPermutation identity()\n\t\t{\n\t\t\treturn SpinPermutation(SpinComponent::X, SpinComponent::Y, SpinComponent::Z);\n\t\t}\n\n\t\tstatic SpinPermutation inverse(const SpinPermutation& rhs)\n\t\t{\n\t\t\tSpinPermutation p;\n\t\t\tif (rhs.transformedComponent[0] == SpinComponent::X) p.transformedComponent[0] = SpinComponent::X;\n\t\t\telse if (rhs.transformedComponent[0] == SpinComponent::Y) p.transformedComponent[1] = SpinComponent::X;\n\t\t\telse if (rhs.transformedComponent[0] == SpinComponent::Z) p.transformedComponent[2] = SpinComponent::X;\n\n\t\t\tif (rhs.transformedComponent[1] == SpinComponent::X) p.transformedComponent[0] = SpinComponent::Y;\n\t\t\telse if (rhs.transformedComponent[1] == SpinComponent::Y) p.transformedComponent[1] = SpinComponent::Y;\n\t\t\telse if (rhs.transformedComponent[1] == SpinComponent::Z) p.transformedComponent[2] = SpinComponent::Y;\n\n\t\t\tif (rhs.transformedComponent[2] == SpinComponent::X) p.transformedComponent[0] = SpinComponent::Z;\n\t\t\telse if (rhs.transformedComponent[2] == SpinComponent::Y) p.transformedComponent[1] = SpinComponent::Z;\n\t\t\telse if (rhs.transformedComponent[2] == SpinComponent::Z) p.transformedComponent[2] = SpinComponent::Z;\n\n\t\t\treturn p;\n\t\t}\n\n\t\tbool operator==(const SpinPermutation& rhs) const\n\t\t{\n\t\t\treturn transformedComponent[0] == rhs.transformedComponent[0] && transformedComponent[1] == rhs.transformedComponent[1] && transformedComponent[2] == rhs.transformedComponent[2];\n\t\t}\n\n\t\tSpinComponent transformedComponent[3];\n\t};\n\n\t//return a list of all nearest neighbors of given lattice site\n\tstd::vector<LatticeSite> getNeighbors(const LatticeUnitCell& uc, const LatticeSite& site)\n\t{\n\t\tstd::vector<LatticeSite> neighbors;\n\n\t\tfor (auto bond : uc.latticeBonds)\n\t\t{\n\t\t\tif (bond.isAttachedToSite(site))\n\t\t\t{\n\t\t\t\tstd::vector<LatticeSite> newNeighbors = bond.getOtherEnd(site);\n\t\t\t\tneighbors.insert(neighbors.end(), newNeighbors.begin(), newNeighbors.end());\n\t\t\t}\n\t\t}\n\t\treturn neighbors;\n\t}\n\n\t//return a list of all neighbors of given lattice site within a specified range\n\tstd::vector<LatticeSite> constructRangeAroundSite(const LatticeUnitCell& uc, const LatticeSite& site, int range)\n\t{\n\t\tstd::vector<LatticeSite> sites({ site });\n\t\tfor (int i = 0; i < range; ++i)\n\t\t{\n\t\t\t//for each site of the set, add all neighbors\n\t\t\tstd::vector<LatticeSite> neighbors;\n\t\t\tfor (auto site : sites)\n\t\t\t{\n\t\t\t\tstd::vector<LatticeSite> ns = getNeighbors(uc, site);\n\t\t\t\tfor (auto n : ns) if (std::find(neighbors.begin(), neighbors.end(), n) == neighbors.end()) neighbors.push_back(n);\n\t\t\t}\n\t\t\tfor (auto n : neighbors) if (std::find(sites.begin(), sites.end(), n) == sites.end()) sites.push_back(n);\n\t\t}\n\t\treturn sites;\n\t}\n\n\t//return the coordinates of given lattice site\n\tgeometry::Vec3<double> getSitePosition(const LatticeUnitCell& uc, const LatticeSite& site)\n\t{\n\t\treturn double(site.a0) * uc.latticeVectors[0] + double(site.a1) * uc.latticeVectors[1] + double(site.a2) * uc.latticeVectors[2] + uc.basisSites[site.b];\n\t}\n\n\t//return true and write result to LatticeSite &site if a lattice site exists at the specified coordinates, otherwise return false\n\tbool siteAtPosition(const LatticeUnitCell& uc, const geometry::Vec3<double>& position, LatticeSite& site)\n\t{\n\t\tfor (int b = 0; b < int(uc.basisSites.size()); ++b)\n\t\t{\n\t\t\tgeometry::Vec3<double> n = geometry::Mat3<double>(uc.latticeVectors[0], uc.latticeVectors[1], uc.latticeVectors[2]).inverse() * (position - uc.basisSites[b]);\n\t\t\tif (fabs(n.x - std::round(n.x)) < __EPSILON && fabs(n.y - std::round(n.y)) < __EPSILON && fabs(n.z - std::round(n.z)) < __EPSILON)\n\t\t\t{\n\t\t\t\tsite.a0 = std::lround(n.x);\n\t\t\t\tsite.a1 = std::lround(n.y);\n\t\t\t\tsite.a2 = std::lround(n.z);\n\t\t\t\tsite.b = b;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t};\n\n\t//searches lattice automorphisms f_i that map site2 onto (0,0,0,0). Return f_i(site1). If reducedSearch==true, return after the first f_i has been found. \n\tstd::vector<std::pair<LatticeSite, SpinPermutation>> symmetryReduce(const LatticeUnitCell& uc, const SpinModelUnitCell& spinModel, const LatticeSite& site1, const LatticeSite& site2, bool reducedSearch = false)\n\t{\n\t\t//define reference site ref\n\t\tLatticeSite ref = LatticeSite(0, 0, 0, 0);\n\n\t\t//collect minimal set of lattice sites which needs to be considered in order to verify symmetry transformations\n\t\tstd::vector<LatticeSite> preImageSites;\n\t\tfor (unsigned int b = 0; b < uc.basisSites.size(); ++b)\n\t\t{\n\t\t\tLatticeSite site(0, 0, 0, b);\n\t\t\tif (std::find(preImageSites.begin(), preImageSites.end(), site) == preImageSites.end()) preImageSites.push_back(site);\n\t\t}\n\t\tfor (auto bond : uc.latticeBonds)\n\t\t{\n\t\t\tLatticeSite site(bond.da0, bond.da1, bond.da2, bond.toB);\n\t\t\tif (std::find(preImageSites.begin(), preImageSites.end(), site) == preImageSites.end()) preImageSites.push_back(site);\n\t\t}\n\n\t\t//collect minimal set of spin interactions which need to be considered in order to verify symmetry transformations\n\t\tstd::vector<SpinInteraction> preImageInteractions = spinModel.interactions; //TODO select only those that are within neighborhood[site2.b]\n\n\t\t//choose two neighbors (n1, n2) of site2 such that the sites are non-collinear\n\t\tLatticeSite n1, n2;\n\t\tstd::vector<LatticeSite> neighbors = getNeighbors(uc, site2);\n\t\tif (neighbors.size() < 3) throw Exception(Exception::Type::InitializationError, \"Could not build lattice. Too few neighbors. \");\n\t\tn1 = neighbors[0];\n\t\tfor (unsigned int i = 1; i < neighbors.size(); ++i)\n\t\t{\n\t\t\tif (geometry::cross(getSitePosition(uc, n1) - getSitePosition(uc, site2), getSitePosition(uc, neighbors[i]) - getSitePosition(uc, site2)).norm() > __EPSILON)\n\t\t\t{\n\t\t\t\tn2 = neighbors[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (i == neighbors.size() - 1) throw Exception(Exception::Type::InitializationError, \"Could not build lattice. Unfavorable lattice geometry. \");\n\t\t}\n\n\t\t//container to store all valid transformations f_i\n\t\tstd::vector<std::pair<geometry::Mat4<double>, SpinPermutation>> validTransformations;\n\n\t\t//try to match (site2, n1, n2) with any combination of neighbors (ref, c1, c2) where c1 and c2 are neighbors of ref\n\t\tstd::vector<LatticeSite> refNeighbors = getNeighbors(uc, ref);\n\t\tfor (auto c1 : refNeighbors)\n\t\t{\n\t\t\tfor (auto c2 : refNeighbors)\n\t\t\t{\n\t\t\t\t//skip if (c1, c2, ref) collinear\n\t\t\t\tif (cross(getSitePosition(uc, c1) - getSitePosition(uc, ref), getSitePosition(uc, c2) - getSitePosition(uc, ref)).norm() < __EPSILON) continue;\n\n\t\t\t\tfor (int inversion = 0; inversion <= 1; ++inversion)\n\t\t\t\t{\n\t\t\t\t\tif (reducedSearch && validTransformations.size() > 0) break;\n\n\t\t\t\t\t//init transformation\n\t\t\t\t\tgeometry::Mat4<double> transformation = (inversion) ? geometry::Mat4<double>::inversion() : geometry::Mat4<double>::identity();\n\t\t\t\t\tSpinPermutation spinTransformation;\n\n\t\t\t\t\t//move site2 to ref\n\t\t\t\t\ttransformation = geometry::Mat4<double>::translation(getSitePosition(uc, ref) - transformation * getSitePosition(uc, site2)) * transformation;\n\n\t\t\t\t\t//rotate n1 onto c1\n\t\t\t\t\tgeometry::Vec3<double> a = (transformation * getSitePosition(uc, n1) - getSitePosition(uc, ref)).normalize();\n\t\t\t\t\tgeometry::Vec3<double> b = (getSitePosition(uc, c1) - getSitePosition(uc, ref)).normalize();\n\t\t\t\t\tgeometry::Vec3<double> axis = cross(a, b);\n\t\t\t\t\tdouble angle = acos(dot(a, b));\n\t\t\t\t\tif (axis.norm() < __EPSILON)\n\t\t\t\t\t{\n\t\t\t\t\t\t//a and b are already antiparallel or parallel. If they are antiparallel, rotate them. Otherwise do nothing. \n\t\t\t\t\t\tif (dot(a, b) < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\taxis = (a.x != 0) ? geometry::Vec3<double>(-a.y, a.x, 0) : geometry::Vec3<double>(0, -a.z, a.y);\n\t\t\t\t\t\t\tangle = PI;\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\taxis = geometry::Vec3<double>(1, 0, 0);\n\t\t\t\t\t\t\tangle = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttransformation = geometry::Mat4<double>::rotation(axis, getSitePosition(uc, ref), angle) * transformation;\n\n\t\t\t\t\t//try to rotate n2 onto c2\n\t\t\t\t\tgeometry::Vec3<double> x = (transformation * getSitePosition(uc, n2) - getSitePosition(uc, ref) - dot(transformation * getSitePosition(uc, n2) - getSitePosition(uc, ref), (getSitePosition(uc, c1) - getSitePosition(uc, ref)).normalize()) * (getSitePosition(uc, c1) - getSitePosition(uc, ref)).normalize()).normalize();\n\t\t\t\t\tgeometry::Vec3<double> y = (getSitePosition(uc, c2) - getSitePosition(uc, ref) - dot(getSitePosition(uc, c2) - getSitePosition(uc, ref), (getSitePosition(uc, c1) - getSitePosition(uc, ref)).normalize()) * (getSitePosition(uc, c1) - getSitePosition(uc, ref)).normalize()).normalize();\n\t\t\t\t\taxis = cross(x, y);\n\t\t\t\t\tangle = acos(dot(x, y));\n\t\t\t\t\tif (axis.norm() < __EPSILON)\n\t\t\t\t\t{\n\t\t\t\t\t\taxis = b;\n\t\t\t\t\t\tangle = (dot(x, y) < 0) ? PI : 0.0;\n\t\t\t\t\t}\n\t\t\t\t\ttransformation = geometry::Mat4<double>::rotation(axis, getSitePosition(uc, ref), angle) * transformation;\n\n\t\t\t\t\t//perform sanity checks on the basic transformation properties\n\t\t\t\t\t//T(site2) should match ref\n\t\t\t\t\tdouble e = (transformation * getSitePosition(uc, site2) - getSitePosition(uc, ref)).norm();\n\t\t\t\t\tif (e > __EPSILON) throw Exception(Exception::Type::InternalError, \"Lattice symmetry calculation has failed. (Deviation of symmetry transformed site [s2] from target [ref] is \" + std::to_string(e) + \", should be zero)\");\n\n\t\t\t\t\t//T(n1) should match of c1\n\t\t\t\t\te = (transformation * getSitePosition(uc, n1) - getSitePosition(uc, c1)).norm();\n\t\t\t\t\tif (e > __EPSILON) throw Exception(Exception::Type::InternalError, \"Lattice symmetry calculation has failed. (Deviation of symmetry transformed site [n1] from target [c1] is \" + std::to_string(e) + \", should be zero)\");\n\n\t\t\t\t\t//T(n2) should be coplanar with c1-ref and c2-ref\n\t\t\t\t\te = dot(transformation * getSitePosition(uc, n2) - getSitePosition(uc, ref), cross(getSitePosition(uc, c1) - getSitePosition(uc, ref), getSitePosition(uc, c2) - getSitePosition(uc, ref)));\n\t\t\t\t\tif (fabs(e) > __EPSILON) throw Exception(Exception::Type::InternalError, \"Lattice symmetry calculation has failed. (Symmetry transformed site [n2] is not coplanar with [c1-ref] and [c2-ref]. Deviation is \" + std::to_string(e) + \", should be zero)\");\n\n\t\t\t\t\t//check if the transformation is valid\n\t\t\t\t\tbool validTransformation = true;\n\n\t\t\t\t\t//check if lattice sites are invariant under transformation\n\t\t\t\t\tLatticeSite imageSite;\n\t\t\t\t\tfor (auto p : preImageSites)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!siteAtPosition(uc, transformation * getSitePosition(uc, p), imageSite))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvalidTransformation = false;\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 (!validTransformation) continue;\n\n\t\t\t\t\t//check if spin couplings are invariant under transformation up to a global permutation of spin components\n\t\t\t\t\tbool spinTransformationExists = false;\n\t\t\t\t\tfor (int i = 0; i < 48; ++i)  // Extend this to all 48 permutations.\n\t\t\t\t\t{\n\t\t\t\t\t\tSpinPermutation permutation(i);\n\t\t\t\t\t\tbool validPermutation = true;\n\n\t\t\t\t\t\t//check whether permutation is compatible with all interactions in the model\n\t\t\t\t\t\tfor (auto interaction : preImageInteractions)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//determine transformed interaction\n\t\t\t\t\t\t\tLatticeSite fromTransformed;\n\t\t\t\t\t\t\tsiteAtPosition(uc, transformation * getSitePosition(uc, interaction.from), fromTransformed);\n\t\t\t\t\t\t\tLatticeSite toTransformed;\n\t\t\t\t\t\t\tsiteAtPosition(uc, transformation * getSitePosition(uc, interaction.to), toTransformed);\n\n\t\t\t\t\t\t\tfloat targetInteractionStrength[3][3];\n\t\t\t\t\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttargetInteractionStrength[s1][s2] = 0.0f;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (auto i : spinModel.interactions)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint connection = i.isConnectingSites(fromTransformed, toTransformed);\n\n\t\t\t\t\t\t\t\tif (connection == 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttargetInteractionStrength[s1][s2] = i.interactionStrength[s1][s2];\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\telse if (connection == -1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttargetInteractionStrength[s1][s2] = i.interactionStrength[s2][s1];\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\n\t\t\t\t\t\t\t//verify transformation\n\t\t\t\t\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2)\n\t\t\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\t\t\tSpinComponent transformedComponent1 = permutation.transformedComponent[s1];\n\t\t\t\t\t\t\t\t\tSpinComponent transformedComponent2 = permutation.transformedComponent[s2];\n\t\t\t\t\t\t\t\t\t// Spincomponets  can be X,Y,Z ,and MinusX,MinusY, MinusZ.\n\n\t\t\t\t\t\t\t\t\t// Now we need to perform the mapping from MinusX->X,etc.\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t \tfloat sign =1.0f;\n\t\t\t\t\t\t\t\t\tif(transformedComponent1 == SpinComponent::MinusX)    \n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttransformedComponent1  = SpinComponent::X;\n\t\t\t\t\t\t\t\t\t\tsign =-sign;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(transformedComponent1  == SpinComponent::MinusY)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttransformedComponent1  = SpinComponent::Y;\n\t\t\t\t\t\t\t\t\t\tsign=-sign;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(transformedComponent1  == SpinComponent::MinusZ)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttransformedComponent1  == SpinComponent::Z;\n\t\t\t\t\t\t\t\t\t\tsign = -sign;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif(transformedComponent2 == SpinComponent::MinusX)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttransformedComponent2 = SpinComponent::X;\n\t\t\t\t\t\t\t\t\t\tsign =-sign;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(transformedComponent2 == SpinComponent::MinusY)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttransformedComponent2 = SpinComponent::Y;\n\t\t\t\t\t\t\t\t\t\tsign=-sign;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(transformedComponent2 == SpinComponent::MinusZ)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttransformedComponent2 = SpinComponent::Z;\n\t\t\t\t\t\t\t\t\t\tsign = -sign;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// here the transformed components must be X,Y,Z\n\n\t\t\t\t\t\t\t\t\tif (interaction.interactionStrength[s1][s2] != sign*targetInteractionStrength[static_cast<int>(transformedComponent1)][static_cast<int>(transformedComponent2)]) validPermutation = false;\n\t\t\t\t\t\t\t\t\t//if (interaction.interactionStrength[s1][s2] != targetInteractionStrength[static_cast<int>(permutation.transformedComponent[s1])][static_cast<int>(permutation.transformedComponent[s2])]) validPermutation = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (validPermutation)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tspinTransformationExists = true;\n\t\t\t\t\t\t\tspinTransformation = permutation;\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 (!spinTransformationExists) validTransformation = false;\n\n\t\t\t\t\tif (!validTransformation) continue;\n\t\t\t\t\telse validTransformations.push_back(std::pair<geometry::Mat4<double>, SpinPermutation>(transformation, spinTransformation));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//compute f_i(site1) and return\n\t\tstd::vector<std::pair<LatticeSite, SpinPermutation>> fsite1;\n\t\tif (validTransformations.size() > 0)\n\t\t{\n\t\t\tfsite1.reserve(validTransformations.size());\n\n\t\t\t//build equivalence class from all transformed sites\n\t\t\tfor (auto t : validTransformations)\n\t\t\t{\n\t\t\t\tLatticeSite ts1;\n\t\t\t\tif (!siteAtPosition(uc, t.first * getSitePosition(uc, site1), ts1)) throw Exception(Exception::Type::InternalError, \"Lattice symmetry calculation has failed. (Internal error. Unexpected outcome of an allegedly valid symmetry)\");\n\t\t\t\tstd::pair<LatticeSite, SpinPermutation> transformation(ts1, t.second);\n\n\t\t\t\tif (std::find(fsite1.begin(), fsite1.end(), transformation) == fsite1.end()) fsite1.push_back(transformation);\n\t\t\t}\n\t\t}\n\t\telse throw Exception(Exception::Type::InternalError, \"Lattice symmetry calculation has failed. (Internal error. Could not establish identity as a valid symmetry operation)\");\n\t\treturn fsite1;\n\t}\n\t#pragma endregion\n\n\tstd::pair<Lattice *, SpinModel *> newLatticeModel(const LatticeUnitCell &uc, const SpinModelUnitCell &spinModelDefinition, const int latticeRange, const std::string &ldfPath)\n\t{\n\t\tLog::log << Log::LogLevel::Info << \"Building lattice spin model...\" << Log::endl;\n\n\t\t//generate empty lattice \n\t\tLattice *lattice = new Lattice;\n\n\t\t//construct neighborhoods around basis sites\n\t\tstd::vector<std::vector<LatticeSite> > neighborhoods;\n\t\tfor (int b = 0; b < int(uc.basisSites.size()); ++b) neighborhoods.push_back(constructRangeAroundSite(uc, LatticeSite(0, 0, 0, b), latticeRange));\n\n\t\t//set lattice->_bravaisLattice\n\t\tlattice->_bravaisLattice = uc.latticeVectors;\n\n\t\t//set lattice->_basis\n\t\tlattice->_basis = uc.basisSites;\n\n\t\t//construct lattice parametrization\n\t\tLog::log << Log::LogLevel::Info << \"\\t...finding lattice parametrization\" << Log::endl;\n\t\tstd::vector<std::pair<int, SpinPermutation>> equivalenceClasses;\n\t\tequivalenceClasses.resize(neighborhoods[0].size());\n\t\tfor (int i = 0; i < int(equivalenceClasses.size()); ++i) equivalenceClasses[i] = std::pair<int, SpinPermutation>(-1, SpinPermutation());\n\t\tint rid = 0;\n\t\tfor (int i = 0; i < int(equivalenceClasses.size()); ++i)\n\t\t{\n\t\t\t//skip if the equivalence class of this site has already been defined\n\t\t\tif (equivalenceClasses[i].first != -1) continue;\n\n\t\t\t//compute symmetry related sites\n\t\t\tauto equiv = symmetryReduce(uc, spinModelDefinition, neighborhoods[0][i], LatticeSite(0, 0, 0, 0));\n\n\t\t\t//define trivial representative of the group\n\t\t\tequivalenceClasses[i].first = rid;\n\t\t\tequivalenceClasses[i].second = SpinPermutation::identity();\n\n\t\t\t//assign the same representative id (rid) to all equivalent sites\n\t\t\tfor (auto e : equiv)\n\t\t\t{\n\t\t\t\t//determine symmetry related partner, skip if it has been addressed before\n\t\t\t\tint j = int(std::find(neighborhoods[0].begin(), neighborhoods[0].end(), e.first) - neighborhoods[0].begin());\n\t\t\t\tif (equivalenceClasses[j].first != -1) continue;\n\n\t\t\t\t//e contains a symmetry transformation of site(i) to site(j), i.e. we need to store the inverse transformation for site(j)\n\t\t\t\tequivalenceClasses[j].first = rid;\n\t\t\t\tequivalenceClasses[j].second = SpinPermutation::inverse(e.second);\n\t\t\t}\n\t\t\t++rid;\n\t\t}\n\t\t//sort lattice parametrization to store the trivial representative of each equivalence class upfront\n\t\tfor (int r = 0; r < rid; ++r)\n\t\t{\n\t\t\tfor (int i = 0; i < int(equivalenceClasses.size()); ++i)\n\t\t\t{\n\t\t\t\tif (equivalenceClasses[i].first == r && equivalenceClasses[i].second == SpinPermutation::identity())\n\t\t\t\t{\n\t\t\t\t\tstd::swap(equivalenceClasses[r], equivalenceClasses[i]);\n\t\t\t\t\tstd::swap(neighborhoods[0][r], neighborhoods[0][i]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//set lattice->size\n\t\tlattice->size = rid;\n\n\t\t//generate lattice sites\n\t\tstd::vector<LatticeSite> sites = neighborhoods[0];\n\t\tfor (int b = 0; b < int(uc.basisSites.size()); ++b)\n\t\t{\n\t\t\tfor (auto n : neighborhoods[b]) if (std::find(sites.begin(), sites.end(), n) == sites.end()) sites.push_back(n);\n\t\t}\n\n\t\t//set lattice->_geometryTable\n\t\tLog::log << Log::LogLevel::Info << \"\\t...initializing lattice geometry buffers\" << Log::endl;\n\t\tlattice->_geometryTable.resize(sites.size());\n\t\tfor (int i = 0; i < int(sites.size()); ++i) lattice->_geometryTable[i] = std::tuple<int, int, int, int>(sites[i].a0, sites[i].a1, sites[i].a2, sites[i].b);\n\n\t\t//set lattice->_dataSize\n\t\tlattice->_dataSize = int(sites.size());\n\n\t\t//set lattice->_bufferBasis\n\t\tlattice->_bufferBasis = new int[uc.basisSites.size() + 1];\n\t\tfor (int b = 0; b < int(uc.basisSites.size()); ++b)\n\t\t{\n\t\t\tfor (int i = 0; i < int(sites.size()); ++i) if (sites[i] == LatticeSite(0, 0, 0, b)) lattice->_bufferBasis[b] = i;\n\t\t}\n\t\tlattice->_bufferBasis[uc.basisSites.size()] = int(sites.size());\n\n\t\t//set lattice->_bufferLatticeRange\n\t\tlattice->_bufferLatticeRange = new int*[uc.basisSites.size()];\n\t\tfor (int b = 0; b < int(uc.basisSites.size()); ++b)\n\t\t{\n\t\t\tlattice->_bufferLatticeRange[b] = new int[neighborhoods[b].size() + 1];\n\t\t\tfor (int n = 0; n < int(neighborhoods[b].size()); ++n)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < int(sites.size()); ++i) if (neighborhoods[b][n] == sites[i]) lattice->_bufferLatticeRange[b][n] = i;\n\t\t\t}\n\t\t\tlattice->_bufferLatticeRange[b][neighborhoods[b].size()] = int(sites.size());\n\t\t}\n\n\t\t//generate lattice->_symmetryTable\n\t\tLog::log << Log::LogLevel::Info << \"\\t...calculating lattice symmetries\" << Log::endl;\n\t\tlattice->_symmetryTable = new LatticeSiteDescriptor[sites.size() * sites.size()];\n\t\tfor (int i = 0; i < int(sites.size() * sites.size()); ++i)\n\t\t{\n\t\t\tlattice->_symmetryTable[i].rid = -1;\n\t\t\tlattice->_symmetryTable[i].spinPermutation[0] = SpinComponent::X;\n\t\t\tlattice->_symmetryTable[i].spinPermutation[1] = SpinComponent::Y;\n\t\t\tlattice->_symmetryTable[i].spinPermutation[2] = SpinComponent::Z;\n\t\t}\n\t\t//init entries related to lattice parametrization (transformations with site1=LatticeSite(0,0,0,0))\n\t\tfor (int n = 0; n < int(neighborhoods[0].size()); ++n)\n\t\t{\n\t\t\tlattice->_symmetryTable[0 * sites.size() + n].rid = equivalenceClasses[n].first;\n\t\t\tlattice->_symmetryTable[0 * sites.size() + n].spinPermutation[0] = equivalenceClasses[n].second.transformedComponent[0];\n\t\t\tlattice->_symmetryTable[0 * sites.size() + n].spinPermutation[1] = equivalenceClasses[n].second.transformedComponent[1];\n\t\t\tlattice->_symmetryTable[0 * sites.size() + n].spinPermutation[2] = equivalenceClasses[n].second.transformedComponent[2];\n\t\t}\n\t\t//init entries related to fundamental transformations with site1=LatticeSite(0,0,0,b) for b non-zero)\n\t\tfor (int b = 1; b < int(uc.basisSites.size()); ++b)\n\t\t{\n\t\t\tfor (auto n : neighborhoods[b])\n\t\t\t{\n\t\t\t\tauto equiv = symmetryReduce(uc, spinModelDefinition, n, LatticeSite(0, 0, 0, b), true);\n\t\t\t\tif (equiv.size() == 0) throw Exception(Exception::Type::InitializationError, \"Could not build lattice. Could not find enough symmetries\");\n\t\t\t\tint bid = int(std::find(sites.begin(), sites.end(), LatticeSite(0, 0, 0, b)) - sites.begin());\n\t\t\t\tint nid = int(std::find(sites.begin(), sites.end(), n) - sites.begin());\n\t\t\t\tint eid = int(std::find(sites.begin(), sites.end(), equiv[0].first) - sites.begin());\n\n\t\t\t\tlattice->_symmetryTable[bid * sites.size() + nid].rid = lattice->_symmetryTable[0 * sites.size() + eid].rid;\n\t\t\t\tlattice->_symmetryTable[bid * sites.size() + nid].spinPermutation[0] = equivalenceClasses[eid].second.transformedComponent[static_cast<int>(equiv[0].second.transformedComponent[static_cast<int>(SpinComponent::X)])];\n\t\t\t\tlattice->_symmetryTable[bid * sites.size() + nid].spinPermutation[1] = equivalenceClasses[eid].second.transformedComponent[static_cast<int>(equiv[0].second.transformedComponent[static_cast<int>(SpinComponent::Y)])];\n\t\t\t\tlattice->_symmetryTable[bid * sites.size() + nid].spinPermutation[2] = equivalenceClasses[eid].second.transformedComponent[static_cast<int>(equiv[0].second.transformedComponent[static_cast<int>(SpinComponent::Z)])];\n\t\t\t}\n\t\t}\n\t\t//init remaining entries of all overlapping pairs of sites\n\t\tfor (int s1 = 0; s1 < int(sites.size()); ++s1)\n\t\t{\n\t\t\tfor (int s2 = 0; s2 < int(sites.size()); ++s2)\n\t\t\t{\n\t\t\t\tLatticeSite s1p(0, 0, 0, sites[s1].b);\n\t\t\t\tLatticeSite s2p(sites[s2].a0 - sites[s1].a0, sites[s2].a1 - sites[s1].a1, sites[s2].a2 - sites[s1].a2, sites[s2].b);\n\t\t\t\tif (std::find(neighborhoods[s1p.b].begin(), neighborhoods[s1p.b].end(), s2p) == neighborhoods[s1p.b].end()) continue;\n\n\t\t\t\tint s1pid = int(std::find(sites.begin(), sites.end(), s1p) - sites.begin());\n\t\t\t\tint s2pid = int(std::find(sites.begin(), sites.end(), s2p) - sites.begin());\n\t\t\t\tlattice->_symmetryTable[s1 * sites.size() + s2] = lattice->_symmetryTable[s1pid * sites.size() + s2pid];\n\t\t\t}\n\t\t}\n\n\t\t//generate lattice->_bufferSites\n\t\tlattice->_bufferSites = new LatticeSiteDescriptor[lattice->size];\n\t\tfor (int i = 0; i < lattice->size; ++i)\n\t\t{\n\t\t\tlattice->_bufferSites[i] = lattice->_symmetryTable[0 * sites.size() + i];\n\t\t}\n\n\t\t//generate lattice->_bufferInvertedSites\n\t\tlattice->_bufferInvertedSites = new LatticeSiteDescriptor[lattice->size];\n\t\tfor (int i = 0; i < lattice->size; ++i)\n\t\t{\n\t\t\tlattice->_bufferInvertedSites[i] = lattice->_symmetryTable[i * sites.size() + 0];\n\t\t}\n\n\t\t//generate lattice->_bufferOverlapMatrices\n\t\tauto bufferNewOverlapTable = [&](int rid)\n\t\t{\n\t\t\t//overlap table buffer\n\t\t\tstd::vector<int> overlapRid1;\n\t\t\tstd::vector<int> overlapRid2;\n\t\t\tstd::vector<SpinComponent> overlapTX1;\n\t\t\tstd::vector<SpinComponent> overlapTY1;\n\t\t\tstd::vector<SpinComponent> overlapTZ1;\n\t\t\tstd::vector<SpinComponent> overlapTX2;\n\t\t\tstd::vector<SpinComponent> overlapTY2;\n\t\t\tstd::vector<SpinComponent> overlapTZ2;\n\n\t\t\t//generate overlap buffer\n\t\t\tLatticeSite i1 = sites[0];\n\t\t\tLatticeSite i2 = sites[rid];\n\n\t\t\tfor (int j = 0; j < int(sites.size()); ++j)\n\t\t\t{\n\t\t\t\t//verify that j is in range of i1\n\t\t\t\tif (std::find(neighborhoods[i1.b].begin(), neighborhoods[i1.b].end(), sites[j]) == neighborhoods[i1.b].end()) continue;\n\n\t\t\t\t//verify that j is in range of i2\n\t\t\t\tif (std::find(neighborhoods[i2.b].begin(), neighborhoods[i2.b].end(), LatticeSite(sites[j].a0 - i2.a0, sites[j].a1 - i2.a1, sites[j].a2 - i2.a2, sites[j].b)) == neighborhoods[i2.b].end()) continue;\n\n\t\t\t\t//symmetry transform the pair (0,j) to obtain rid1 and (j,rid) to obtain rid2\n\t\t\t\tLatticeSiteDescriptor t1 = lattice->_symmetryTable[0 * sites.size() + j];\n\t\t\t\tLatticeSiteDescriptor t2 = lattice->_symmetryTable[j * sites.size() + rid];\n\n\t\t\t\toverlapRid1.push_back(t1.rid);\n\t\t\t\toverlapTX1.push_back(t1.spinPermutation[0]);\n\t\t\t\toverlapTY1.push_back(t1.spinPermutation[1]);\n\t\t\t\toverlapTZ1.push_back(t1.spinPermutation[2]);\n\t\t\t\toverlapRid2.push_back(t2.rid);\n\t\t\t\toverlapTX2.push_back(t2.spinPermutation[0]);\n\t\t\t\toverlapTY2.push_back(t2.spinPermutation[1]);\n\t\t\t\toverlapTZ2.push_back(t2.spinPermutation[2]);\n\t\t\t}\n\n\t\t\tLatticeOverlap overlap(int(overlapRid1.size()));\n\t\t\tmemcpy(overlap.rid1, overlapRid1.data(), overlapRid1.size() * sizeof(int));\n\t\t\tmemcpy(overlap.rid2, overlapRid2.data(), overlapRid2.size() * sizeof(int));\n\t\t\tmemcpy(overlap.transformedX1, overlapTX1.data(), overlapTX1.size() * sizeof(SpinComponent));\n\t\t\tmemcpy(overlap.transformedY1, overlapTY1.data(), overlapTY1.size() * sizeof(SpinComponent));\n\t\t\tmemcpy(overlap.transformedZ1, overlapTZ1.data(), overlapTZ1.size() * sizeof(SpinComponent));\n\t\t\tmemcpy(overlap.transformedX2, overlapTX2.data(), overlapTX2.size() * sizeof(SpinComponent));\n\t\t\tmemcpy(overlap.transformedY2, overlapTY2.data(), overlapTY2.size() * sizeof(SpinComponent));\n\t\t\tmemcpy(overlap.transformedZ2, overlapTZ2.data(), overlapTZ2.size() * sizeof(SpinComponent));\n\n\t\t\treturn overlap;\n\t\t};\n\t\tlattice->_bufferOverlapMatrices = new LatticeOverlap[lattice->size];\n\t\tfor (int rid = 0; rid < lattice->size; ++rid) lattice->_bufferOverlapMatrices[rid] = bufferNewOverlapTable(rid);\n\n\t\t//init SpinModel\n\t\tSpinModel* spinModel = new SpinModel();\n\n\t\t//add interaction parameters\n\t\tspinModel->interactionParameters.insert(spinModel->interactionParameters.begin(), spinModelDefinition.interactionParameters.begin(), spinModelDefinition.interactionParameters.end());\n\n\t\t//add interaction strengths\n\t\tfor (int rid = 0; rid < lattice->size; ++rid)\n\t\t{\n\t\t\tauto i1 = lattice->getSiteParameters(lattice->fromParametrization(rid));\n\n\t\t\tfor (auto interaction : spinModelDefinition.interactions)\n\t\t\t{\n\t\t\t\tint connection = interaction.isConnectingSites(LatticeSite(0, 0, 0, 0), LatticeSite(std::get<0>(i1), std::get<1>(i1), std::get<2>(i1), std::get<3>(i1)));\n\n\t\t\t\tif (connection == 1)\n\t\t\t\t{\n\t\t\t\t\tSpinModel::SpinInteraction i;\n\t\t\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2) i.interactionStrength[s1][s2] = interaction.interactionStrength[s1][s2];\n\t\t\t\t\t}\n\t\t\t\t\tspinModel->interactions.push_back(std::pair<LatticeIterator, SpinModel::SpinInteraction>(lattice->fromParametrization(rid), i));\n\t\t\t\t}\n\t\t\t\telse if (connection == -1)\n\t\t\t\t{\n\t\t\t\t\tSpinModel::SpinInteraction i;\n\t\t\t\t\tfor (int s1 = 0; s1 < 3; ++s1)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int s2 = 0; s2 < 3; ++s2) i.interactionStrength[s1][s2] = interaction.interactionStrength[s2][s1];\n\t\t\t\t\t}\n\t\t\t\t\tspinModel->interactions.push_back(std::pair<LatticeIterator, SpinModel::SpinInteraction>(lattice->fromParametrization(rid), i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//print ldf file\n\t\tif (ldfPath != \"\")\n\t\t{\n\t\t\t//open file file\n\t\t\tstd::ofstream ldfFile(ldfPath, std::ios::out);\n\t\t\tif (!ldfFile.is_open()) throw Exception(Exception::Type::IOError, \"Could not write lattice debug information to file. \");\n\t\t\tldfFile << \"<lattice>\" << std::endl;\n\n\t\t\t//write sites\n\t\t\tfor (auto i1 = lattice->getRange(0); i1 != lattice->end(); ++i1)\n\t\t\t{\n\t\t\t\tgeometry::Vec3<double> p = lattice->getSitePosition(i1);\n\t\t\t\tstd::string parametrized = (i1 - lattice->begin() < lattice->size) ? \"true\" : \"false\";\n\t\t\t\tldfFile << boost::format(\"\\t<site id=\\\"%d\\\" x=\\\"%f\\\" y=\\\"%f\\\" z=\\\"%f\\\" parametrized=\\\"%s\\\"/>\") % (i1 - lattice->begin()) % p.x % p.y % p.z % parametrized << std::endl;\n\t\t\t}\n\n\t\t\t//write bonds\n\t\t\tfor (auto i1 = lattice->getRange(0); i1 != lattice->end(); ++i1)\n\t\t\t{\n\t\t\t\tfor (auto i2 = lattice->getRange(0); i2 != lattice->end(); ++i2)\n\t\t\t\t{\n\t\t\t\t\tauto s1Parm = lattice->getSiteParameters(i1);\n\t\t\t\t\tauto s2Parm = lattice->getSiteParameters(i2);\n\t\t\t\t\tLatticeSite s1 = LatticeSite(std::get<0>(s1Parm), std::get<1>(s1Parm), std::get<2>(s1Parm), std::get<3>(s1Parm));\n\t\t\t\t\tLatticeSite s2 = LatticeSite(std::get<0>(s2Parm), std::get<1>(s2Parm), std::get<2>(s2Parm), std::get<3>(s2Parm));\n\n\t\t\t\t\tfor (auto bond : uc.latticeBonds)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (bond.isConnectingFromTo(s1, s2)) ldfFile << boost::format(\"\\t<bond from=\\\"%d\\\" to=\\\"%d\\\" />\") % (i1 - lattice->begin()) % (i2 - lattice->begin()) << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//write interactions\n\t\t\tfor (auto i1 = lattice->getRange(0); i1 != lattice->end(); ++i1)\n\t\t\t{\n\t\t\t\tfor (auto i2 = lattice->getRange(0); i2 != lattice->end(); ++i2)\n\t\t\t\t{\n\t\t\t\t\tauto s1Parm = lattice->getSiteParameters(i1);\n\t\t\t\t\tauto s2Parm = lattice->getSiteParameters(i2);\n\t\t\t\t\tLatticeSite s1 = LatticeSite(std::get<0>(s1Parm), std::get<1>(s1Parm), std::get<2>(s1Parm), std::get<3>(s1Parm));\n\t\t\t\t\tLatticeSite s2 = LatticeSite(std::get<0>(s2Parm), std::get<1>(s2Parm), std::get<2>(s2Parm), std::get<3>(s2Parm));\n\n\t\t\t\t\tfor (auto i : spinModelDefinition.interactions)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (i.isConnectingFromTo(s1, s2))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tldfFile << boost::format(\"\\t<interaction from=\\\"%d\\\" to=\\\"%d\\\" value=\\\"[[%f,%f,%f],[%f,%f,%f],[%f,%f,%f]]\\\" />\") % (i1 - lattice->begin()) % (i2 - lattice->begin()) % i.interactionStrength[0][0] % i.interactionStrength[0][1] % i.interactionStrength[0][2] % i.interactionStrength[1][0] % i.interactionStrength[1][1] % i.interactionStrength[1][2] % i.interactionStrength[2][0] % i.interactionStrength[2][1] % i.interactionStrength[2][2] << std::endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//finalize file\n\t\t\tldfFile << \"</lattice>\" << std::endl;\n\t\t\tldfFile.close();\n\t\t}\n\n\t\t//return lattice\n\t\treturn std::pair<Lattice*, SpinModel*>(lattice, spinModel);\n\t}\n}", "meta": {"hexsha": "2cd5bb1e25f1c1a46ba82b53c0c145fd7b402100", "size": 54442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LatticeModelFactory.cpp", "max_stars_repo_name": "Sourin-chatterjee/SpinParser", "max_stars_repo_head_hexsha": "23fa90c327b8a4543e5afac1b64d18df40975182", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LatticeModelFactory.cpp", "max_issues_repo_name": "Sourin-chatterjee/SpinParser", "max_issues_repo_head_hexsha": "23fa90c327b8a4543e5afac1b64d18df40975182", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LatticeModelFactory.cpp", "max_forks_repo_name": "Sourin-chatterjee/SpinParser", "max_forks_repo_head_hexsha": "23fa90c327b8a4543e5afac1b64d18df40975182", "max_forks_repo_licenses": ["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.8784615385, "max_line_length": 455, "alphanum_fraction": 0.6718526138, "num_tokens": 15550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.03846619243168113, "lm_q1q2_score": 0.019082840708597993}}
{"text": "//=======================================================================\n// Copyright 2015 - 2020 Jeff Linahan\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include \"lipton-tarjan.h\"\n#include \"theorem4.h\"\n#include \"lemmas.h\"\n#include \"strutil.h\"\n#include \"BFSVert.h\"\n#include \"BFSVisitorData.h\"\n#include \"BFSVisitor.h\"\n#include \"EmbedStruct.h\"\n#include \"ScanVisitor.h\"\n#include \"graphutil.h\"\n#include <boost/lexical_cast.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp> \n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/range/irange.hpp> \n#include <boost/bimap.hpp>\n#include <boost/config.hpp>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <csignal>\n#include <iterator>\nusing namespace std;\nusing namespace boost; \n\n// Step 10: construct_vertex_partition\n// Time:    O(n)\n//\n// Use the fundamental cycle found in Step 9 and the levels found in Step 4 (l1_and_k) to construct a satisfactory vertex partition as described in the proof of Lemma 3\n// Extend this partition from the connected component chosen in Step 2 to the entire graph as described in the proof of Theorem 4.\nPartition construct_vertex_partition(GraphCR g_orig, Graph& g_shrunk, vector<uint> const& L, uint l[3], BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_shrunken, vector<vertex_t> const& fundamental_cycle)\n{\n        vertex_map idx; \n        associative_property_map<vertex_map> vertid_to_component(idx);\n        uint num_components = connected_components(g_orig, vertid_to_component);\n        //BOOST_ASSERT(1 == num_components);\n\n        uint n = num_vertices(g_orig);\n        uint n_biggest_comp = vis_data_orig.verts.size(); // if num_components > 1 then num_vertices(g_orig) will not be what we want\n        //cout << \"n_biggest: \" << n_biggest_comp << '\\n';\n\n        cout  << \"\\n------------ 10  - Construct Vertex Partition --------------\\n\";\n        cout << \"g_orig:\\n\";\n        print_graph(g_orig);\n        cout << \"l0: \" << l[0] << '\\n';\n        cout << \"l1: \" << l[1] << '\\n';\n        cout << \"l2: \" << l[2] << '\\n';\n\n        uint r = vis_data_orig.num_levels;\n        cout << \"r max distance: \" << r << '\\n';\n\n        Partition biggest_comp_p = lemma3(g_orig, L, l[1], l[2], r, vis_data_orig, vis_data_shrunken, fundamental_cycle, &g_shrunk);\n        biggest_comp_p.verify_edges(g_orig);\n        biggest_comp_p.verify_sizes_lemma3(L, l[1], l[2]);\n        if( 1 == num_components ){\n\n                if( biggest_comp_p.verify_sizes(g_orig) && biggest_comp_p.verify_edges(g_orig) ) return biggest_comp_p;\n\n                return theorem4_connected(g_orig, L, l, r, &g_shrunk, &vis_data_shrunken);\n        }\n\n        //associative_property_map<vertex_map> const& vertid_to_component, vector<uint> const& num_verts_per_component)\n        vector<uint> num_verts_per_component(num_components, 0);\n        VertIter vit, vjt;\n        for( tie(vit, vjt) = vertices(g_orig); vit != vjt; ++vit ){\n\t       \t++num_verts_per_component[vertid_to_component[*vit]];\n\t}\n\n        // somehow the two Partitions need to be stiched together\n\n        cout << \"biggest comp p:\\n\";\n        biggest_comp_p.print(&g_orig);\n\n        Partition extended_p = theorem4_disconnected(g_orig, n, num_components, vertid_to_component, num_verts_per_component, biggest_comp_p);\n\n        return extended_p; // TODO replace this with extended_p\n}\n\n\n// Locate the triangle (vi, y, wi) which has (vi, wi) as a boundary edge and lies inside the (vi, wi) cycle.  \n// one of the vertices in the set neighbors_vw is y.  Maybe it's .begin(), so we use is_edge_inside_outside_or_on_cycle to test if it is.j\nvertex_t findy(vertex_t vi, set<vertex_t> const& neighbors_vw, vector<vertex_t> const& cycle, GraphCR g_shrunk, EmbedStruct const& em,  decltype(get(vertex_index, const_cast<Graph&>(g_shrunk))) prop_map)\n{\n\tfor( vertex_t y_candidate : neighbors_vw ){\n                pair<edge_t, bool> vi_cy = edge(vi, y_candidate, g_shrunk);\n                BOOST_ASSERT(vi_cy.second);\n                edge_t e = vi_cy.first;\n                InsideOutOn insideout = is_edge_inside_outside_or_on_cycle(e, vi, cycle, g_shrunk, em.em);\n                if( INSIDE == insideout ){\n                        return y_candidate;\n                }\n\t}\n\t/*pair<edge_t, bool> maybe_y = edge(vi, *neighbors_vw.begin(), g_shrunk);\n\tBOOST_ASSERT(maybe_y.second); // I'm assuming the bool means that the edge_t exists?  Boost Graph docs don't say\n\tcout << \"maybe_y: \" << to_string(maybe_y.first, g_shrunk) << '\\n';\n\n\tcout << \"cycle:\\n\";\n\tprint_cycle(cycle, g_shrunk);\n\n\tvertex_t common_vert_on_cycle = find(STLALL(cycle), *neighbors_vw.begin()) == cycle.end() ?\n\t\t\t\t\t*neighbors_vw.rbegin() :\n\t\t\t\t\t*neighbors_vw.begin() ;\n\tcout << \"common vert on cycle: \" << prop_map[common_vert_on_cycle] << '\\n';\n\tBOOST_ASSERT(find(STLALL(cycle), common_vert_on_cycle) != cycle.end());\n\n\tInsideOutOn insideout = is_edge_inside_outside_or_on_cycle(maybe_y.first, common_vert_on_cycle, cycle, g_shrunk, em.em);\n\tBOOST_ASSERT(insideout != ON);\n\tvertex_t y = (insideout == INSIDE) ? *neighbors_vw.begin() : *neighbors_vw.rbegin();*/\n\t// We now have the (vi, y, wi) triangle\n        BOOST_ASSERT(0);\n}\n\n// Step 9: Improve Separator\n// Time:   O(n)\n//\n// Let (vi, wi) be the nontree edge whose cycle is the current candidate to complete the separator.\n// If the cost inside the cycle exceeds 2/3, find a better cycle by the following method.\n// \tLocate the triangle (vi, y, wi) which has (vi, wi) as a boundary edge and lies inside the (vi, wi) cycle.\n//      If either (vi, y) or (y, wi) is a tree edge, let (vi+1, wi+1) be the nontree edge among (vi, y) and (y, wi).\n//      Compute the cost inside the (vi+1, wi+1) cycle from the cost inside the (vi, wi) cycle and the cost of vi, y and wi.\n// \tIf neither (vi, y) nor (y, wi) is a tree edge, determine the tree path from y to the (vi, wi) cycle by following parent pointers from y.\n//      Let z be the vertex on the (vi, wi) cycle reached during this search.  Compute the total cost of all vertices except z on this tree path.\n//      Scan the tree edges inside the (y, wi) cycle, alternately scanning an edge in one cycle and an edge in the other cycle.\n//      Stop scanning when all edges inside one of the cycles have been scanned.  Compute the cost inside this cycle by summing the associated costs of all scanned edges.\n//      Use this cost, the cost inside the (vi, wi) cycle, and the cost on the tree path from y to z to compute the cost inside the other cycle.\n//      Let (vi+1, wi+1) be the edge among (vi, y) and (y, wi) whose cycle has more cost inside it.\n// \tRepeat Step 9 until finding a cycle whose inside has cost not exceeding 2/3.\nPartition improve_separator(GraphCR g_orig, Graph& g_shrunk, CycleCost& cc, edge_t completer_candidate_edge, BFSVisitorData const& vis_data_orig,\n                            BFSVisitorData const& vis_data_shrunken, vector<vertex_t> cycle, EmbedStruct const& em, bool cost_swapped, vector<uint> const& L, uint l[3])\n{\n        cout << \"---------------------------- 9 - Improve Separator -----------\\n\";\n        print_graph(g_shrunk);\n\n        auto prop_map = get(vertex_index, g_shrunk); // writing to this property map has side effects in the graph\n\n        cout << \"cycle: \";\n        for( uint i = 0; i < cycle.size(); ++i ) cout << prop_map[cycle[i]] << ' ';\n        cout << '\\n';\n\n        uint n_orig = num_vertices(g_orig);\n        uint n = num_vertices(g_shrunk);\n        cout << \"n_orig: \" << n_orig << \", n: \" << n << '\\n';\n\n        while( cc.inside > 2.*n/3 ){\n                cout << \"nontree completer candidate edge: \" << to_string(completer_candidate_edge, g_shrunk) << '\\n';\n                cout << \"cost inside: \" << cc.inside  << '\\n';\n                cout << \"cost outide: \" << cc.outside << '\\n';\n                cout << \"looking for a better cycle\\n\";\n\n\t\t// Let (vi, wi) be the nontree edge whose cycle is the current candidate to complete the separator\n                vertex_t vi = source(completer_candidate_edge, g_shrunk);\n                vertex_t wi = target(completer_candidate_edge, g_shrunk); \n                BOOST_ASSERT(!vis_data_shrunken.is_tree_edge(completer_candidate_edge));\n                cout << \"   vi: \" << prop_map[vi] << '\\n';\n                cout << \"   wi: \" << prop_map[wi] << '\\n';\n\n                set<vertex_t> neighbors_of_v = get_neighbors(vi, g_shrunk);\n                set<vertex_t> neighbors_of_w = get_neighbors(wi, g_shrunk); \n                set<vertex_t> neighbors_vw = get_intersection(neighbors_of_v, neighbors_of_w);\n                for( auto& ne : neighbors_vw ){ \n                        cout << \"neighbor: \" << ne << \" prop_map: \" << prop_map[ne] << '\\n';\n                }\n                cout << \"   neighbors_vw_begin : \" << prop_map[*neighbors_vw.begin()] << '\\n';\n                cout << \"   neighbors_vw_rbegin: \" << prop_map[*neighbors_vw.rbegin()] << '\\n';\n\n\t\tvertex_t y = findy(vi, neighbors_vw, cycle, g_shrunk, em, prop_map);\n\n                cout << \"   y: \" << prop_map[y] << '\\n';\n                pair<edge_t, bool> viy_e = edge(vi, y, g_shrunk); BOOST_ASSERT(viy_e.second); edge_t viy = viy_e.first;\n                pair<edge_t, bool> ywi_e = edge(y, wi, g_shrunk); BOOST_ASSERT(ywi_e.second); edge_t ywi = ywi_e.first; \n                edge_t next_edge;\n\n\t\t// if either (vi, y) or (y, wi) is a tree edge, \n                if ( vis_data_shrunken.is_tree_edge(viy) || vis_data_shrunken.is_tree_edge(ywi) ){\n\t\t\t// determine the tree path from y to the (vi, wi) cycle by following parent pointers from y.\n                        cout << \"   at least one tree edge\\n\";\n                        next_edge = vis_data_shrunken.is_tree_edge(viy) ? ywi : viy;\n                        BOOST_ASSERT(!vis_data_shrunken.is_tree_edge(next_edge));\n\n                        // Compute the cost inside the (vi+1 wi+1) cycle from the cost inside the (vi, wi) cycle and the cost of vi, y, and wi.  See Fig 4.\n                        uint cost[4] = {vis_data_shrunken.verts.find(vi)->second.descendant_cost,\n\t\t\t\t\tvis_data_shrunken.verts.find(y )->second.descendant_cost,\n\t\t\t\t\tvis_data_shrunken.verts.find(wi)->second.descendant_cost,\n\t\t\t\t\tcc.inside};\n                        vector<vertex_t> new_cycle = vis_data_shrunken.get_cycle(source(next_edge, g_shrunk), target(next_edge, g_shrunk));\n                        cc = compute_cycle_cost(new_cycle, g_shrunk, vis_data_shrunken, em); // !! CHEATED !!\n                        if( cost_swapped ) swap(cc.outside, cc.inside);\n                } else {\n                        // Determine the tree path from y to the (vi, wi) cycle by following parents of y.\n                        cout << \"   neither are tree edges\\n\";\n                        vector<vertex_t> y_parents = vis_data_shrunken.ancestors(y);\n\n                        for( vertex_t vp : y_parents ){\n                                cout << \"y parent: \" << prop_map[vp] << '\\n';\n                        }\n\n                        uint i = 0;\n                        while( !on_cycle(y_parents.at(i), cycle, g_shrunk) ){\n                                cout << \"yparents[\" << i << \"]: \" << y_parents[i] << \" propmap: \" << prop_map[y_parents[i]] << '\\n';\n                                ++i;\n                        }\n                        cout << \"yparents[\" << i << \"]: \" << y_parents.at(i) << \" propmap: \" << prop_map[y_parents[i]] << '\\n';\n\n                        // Let z be the vertex on the (vi, wi) cycle reached during the search.\n\t\t\tcout << \"i: \" << i << '\\n';\n                        vertex_t z = y_parents.at(i);\n\t\t\tcout << \"z: \" << prop_map[z] << '\\n';\n                        BOOST_ASSERT(on_cycle(z, cycle, g_shrunk));\n                        cout << \"    z: \" << prop_map[z] << '\\n';\n                        y_parents.erase(y_parents.begin()+i, y_parents.end());\n                        BOOST_ASSERT(y_parents.size() == i);\n\n                        // Compute the total cost af all vertices except z on this tree path.\n                        uint path_cost = y_parents.size() - 1;\n                        cout << \"    y-to-z-minus-z cost: \" << path_cost << '\\n';\n\n                        // Scan the tree edges inside the (y, wi) cycle, alternately scanning an edge in one cycle and an edge in the other cycle.\n                        // Stop scanning when all edges inside one of the cycles have been scanned.  Compute the cost inside this cycle by summing the associated costs of all scanned edges.\n                        // Use this cost, the cost inside the (vi, wi) cycle, and the cost on the tree path from y to z to compute the cost inside the other cycle.\n                        vector<vertex_t> cycle1 = vis_data_shrunken.get_cycle(vi, y);\n                        vector<vertex_t> cycle2 = vis_data_shrunken.get_cycle(y, wi);\n                        CycleCost cost1 = compute_cycle_cost(cycle1, g_shrunk, vis_data_shrunken, em);\n                        CycleCost cost2 = compute_cycle_cost(cycle2, g_shrunk, vis_data_shrunken, em);\n                        if( cost_swapped ){\n                                swap(cost1.inside, cost1.outside);\n                                swap(cost2.inside, cost2.outside);\n                        }\n\n                        // Let (vi+1, wi+1) be the edge among (vi, y) and (i, wi) whose cycle has more cost inside it.\n                        if( cost1.inside > cost2.inside ){ next_edge = edge(vi, y, g_shrunk).first; cc = cost1; cycle = cycle1;}\n                        else                             { next_edge = edge(y, wi, g_shrunk).first; cc = cost2; cycle = cycle2;}\n                } \n                completer_candidate_edge = next_edge;\n        }\n        cout << \"found fundamental cycle with inside cost \" << cc.inside << \" which is less than 2/3\\n\";\n        print_cycle(cycle, g_shrunk);\n\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n        //BOOST_ASSERT(vis_data_orig.assert_data());\n        //BOOST_ASSERT(vis_data_shrunken.assert_data());\n\n\treturn construct_vertex_partition(g_orig, g_shrunk, L, l, vis_data_orig, vis_data_shrunken, cycle); // step 10\n}\n\n\n// Step 8: locate_cycle\n// Time: O(n)\n//\n// Choose any nontree edge (v1, w1).\n// Locate the corresponding cycle by following parent pointers from v1 and w1.\n// Compute the cost on each side of this cycle by scanning the tree edges incident on either side of the cycle and summing their associated costs.\n// If (v, w) is a tree edge with v on the cycle and w not on the cycle, the cost associated with (v,w) is the descendant cost of w if v is the parent of w,\n// and the cost of all vertices minus the descendant cost of v if w is the parent of v.\n// Determine which side of the cycle has greater cost and call it the \"inside\"\nPartition locate_cycle(GraphCR g_orig, Graph& g_shrunk, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_shrunken, vector<uint> const& L, uint l[3])\n{\n        //BOOST_ASSERT(vis_data_orig.assert_data()); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n        //BOOST_ASSERT(vis_data_shrunken.assert_data()); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n\n        uint n = num_vertices(g_orig);\n        cout  << \"----------------------- 8 - Locate Cycle -----------------\\n\"; \n        print_graph(g_shrunk);\n        edge_t completer_candidate_edge;\n        \n        try {\n                completer_candidate_edge = vis_data_shrunken.arbitrary_nontree_edge(g_shrunk);\n        } catch (NoNontreeEdgeException const& e){\n                vector<vertex_t> cycle;\n                CycleCost cc;\n                cc.inside = 0;\n                cc.outside = n; // force Step 9 to exit without going through any iterations\n                bool cost_swapped = false;\n                EmbedStruct em(&g_shrunk);\n                return improve_separator(g_orig, g_shrunk, cc, completer_candidate_edge, vis_data_orig, vis_data_shrunken, cycle, em, cost_swapped, L, l); // step 9 \n        }\n        vertex_t v1 = source(completer_candidate_edge, g_shrunk);\n        vertex_t w1 = target(completer_candidate_edge, g_shrunk); \n        cout << \"ancestors v1...\\n\";\n        vector<vertex_t> parents_v   = vis_data_shrunken.ancestors(v1);\n        cout << \"ancestors v2...\\n\";\n        vector<vertex_t> parents_w   = vis_data_shrunken.ancestors(w1); \n        vertex_t common_ancestor    = get_common_ancestor(parents_v, parents_w);\n        cout << \"common ancestor: \" << common_ancestor << '\\n'; \n        vector<vertex_t> cycle = vis_data_shrunken.get_cycle(v1, w1, common_ancestor);\n\n        EmbedStruct em(&g_shrunk);\n        CycleCost cc = compute_cycle_cost(cycle, g_shrunk, vis_data_shrunken, em); \n\tbool cost_swapped;\n        if( cc.outside > cc.inside ){\n                swap(cc.outside, cc.inside);\n                cost_swapped = true;\n                cout << \"!!!!!! cost swapped !!!!!!!!\\n\";\n        } else cost_swapped = false;\n        cout << \"total inside cost:  \" << cc.inside  << '\\n'; \n        cout << \"total outside cost: \" << cc.outside << '\\n';\n\n\treturn improve_separator(g_orig, g_shrunk, cc, completer_candidate_edge, vis_data_orig, vis_data_shrunken, cycle, em, cost_swapped, L, l); // step 9\n}\n\n// Step 7: new_bfs_and_make_max_planar\n// Time:   O(n)\n// \n// Construct a breadth-first spanning tree rooted at x in the new (shrunken) graph.\n// (This can be done by modifying the breadth-first spanning tree constructed in Step 3 bfs_and_levels.)\n// Record, for each vertex v, the parent of v in the tree, and the total cost of all descendants of v includiing v itself.\n// Make all faces of the new graph into triangles by scanning the boundary of each face and adding (nontree) edges as necessary.\nPartition new_bfs_and_make_max_planar(GraphCR g_orig, Graph& g_shrunk, BFSVisitorData const& vis_data_orig, vertex_t x, vector<uint> const& L, uint l[3])\n{\n        cout  << \"-------------------- 7 - New BFS and Make Max Planar -----\\n\";\n        cout << \"g_orig:\\n\";\n        print_graph(g_orig);\n        print_graph_addresses(g_orig);\n        cout << \"g_shrunk:\\n\";\n        print_graph(g_shrunk);\n        print_graph_addresses(g_shrunk);\n        //reset_vertex_indices(g_shrunk);\n        //reset_edge_index(g_shrunk);\n        BFSVisitorData shrunken_vis_data(&g_shrunk, x);\n\n        //vis_data.reset(&g_shrunk);\n        shrunken_vis_data.root = x;\n        ++shrunken_vis_data.verts[shrunken_vis_data.root].descendant_cost;\n\n        uint n = num_vertices(g_shrunk);\n        cout << \"n:    \" << n << '\\n'; \n        cout << \"null vertex: \" << Graph::null_vertex() << '\\n';\n\n        BFSVisitor visit = BFSVisitor(shrunken_vis_data);\n\n        auto bvs = boost::visitor(visit);\n\n        cout << \"g_shrunk:\\n\";\n        print_graph(g_shrunk);\n\n        // workaround for https://github.com/boostorg/graph/issues/195 \n        VertIter vit, vjt;\n        tie(vit, vjt) = vertices(g_shrunk);\n        for( VertIter next = vit; vit != vjt; ++vit){\n                if( 0 == in_degree(*vit, g_shrunk) + out_degree(*vit, g_shrunk) ){\n                        add_edge(*vit, *vit, g_shrunk);\n                }\n        }\n\n        cout << \"g_shrunk with workaround:\\n\";\n        print_graph(g_shrunk);\n\n        BOOST_ASSERT(vertex_exists(shrunken_vis_data.root, g_shrunk));\n\n        breadth_first_search(g_shrunk, shrunken_vis_data.root, bvs);\n\n        make_max_planar(g_shrunk);\n        //reset_vertex_indices(g_shrunk);\n        reset_edge_index(g_shrunk);\n\n        print_graph(g_shrunk);\n\n\treturn locate_cycle(g_orig, g_shrunk, vis_data_orig, shrunken_vis_data, L, l);  // step 8\n}\n\n// Step 6: Shrinktree\n// Time:   big-theta(n)\n//\n// Delete all vertices on level l2 and above.\n// Construct a new vertex x to represent all vertices on levels 0 through l0.\n// Construct a boolean table with one entry per vertex.\n// Initialize to true the entry for each vertex on levels 0 through l0 and\n// initialize to false the entry for each vertex on levels l0 + 1 through l2 - 1.\n// The vertices on levels 0 through l0 correspond to a subtree of the breadth-first spanning tree\n// generated in Step 3 (bfs_and_levels).\n// Scan the edges incident to this tree clockwise around the tree.\n// When scanning an edge(v, w) with v in the tree, check the table entry for w.\n// If it is true, delete edge(v, w).\n// If it is false, change it to true, construct an edge(x,w) and delete edge(v,w).\n// The result of this step is a planar representation of the shrunken graph to which Lemma 2 is to be applied.\n\n//const uint X_VERT_UINT = 9999;\n\nvector<vertex_t> shrinktree_deletel2andabove(Graph& g, uint l[3], BFSVisitorData const& vis_data_copy, vertex_t x)\n{\n        cout << \"l[0]: \" << l[0] << '\\n';\n        cout << \"l[1]: \" << l[1] << '\\n';\n        cout << \"l[2]: \" << l[2] << '\\n';\n\n        vector<vertex_t> replaced_verts;\n\tVertIter vit, vjt;\n        tie(vit, vjt) = vertices(g); \n        for( VertIter next = vit; vit != vjt; vit = next ){\n                ++next;\n                if( *vit == x ) continue; // don't delete x\n                if( !vis_data_copy.verts.contains(*vit) ) continue; // *vit is in a different connected component\n\n                uint level = vis_data_copy.verts.find(*vit)->second.level;\n\n                if( level >= l[2] ){\n                        kill_vertex(*vit, g); \n                }\n                if( level <= l[0] ){\n                        replaced_verts.push_back(*vit);\n                }\n        }\n        return replaced_verts;\n}\n\nPartition shrinktree(GraphCR g_orig, Graph& g_copy, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_copy, vector<uint> const& L, uint l[3])\n{\n        Graph& g_shrunk = g_copy;\n        cout << \"---------------------------- 6 - Shrinktree -------------\\n\";\n        print_graph(g_copy);\n        cout << \"n: \" << num_vertices(g_shrunk) << '\\n';\n\n        // delete all vertices on level l2 and above\n        vertex_t x = add_vertex(g_shrunk);\n        BFSVisitorData vis_data_addx(vis_data_copy);\n        vis_data_addx.root = x;\n        vis_data_addx.verts[x].level = 0;\n        vis_data_addx.verts[x].parent = Graph::null_vertex();\n        vis_data_addx.verts[x].descendant_cost = -1;\n        BOOST_ASSERT(vertex_exists(x, g_shrunk));\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n        vector<vertex_t> replaced_verts = shrinktree_deletel2andabove(g_shrunk, l, vis_data_addx, x);\n\n        BOOST_ASSERT(vertex_exists(x, g_shrunk));\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n        //prop_map[x] = X_VERT_UINT;\n\n        map<vertex_t, bool> table; // x will not be in this table\n\tVertIter vit, vjt;\n        for( tie(vit, vjt) = vertices(g_shrunk); vit != vjt; ++vit ){\n                if( *vit == x ) continue; // the new x isn't in visdata, std::map::find() will fail\n                if( !vis_data_addx.verts.contains(*vit) ) continue; // *vit may be in a different connected component\n                uint level = vis_data_addx.verts.find(*vit)->second.level;\n                table[*vit] = level <= l[0];\n        }\n\n        BOOST_ASSERT(vertex_exists(x, g_shrunk)); \n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n\n        cout << \"g_shrunk:\\n\";\n        print_graph(g_shrunk);\n        reset_vertex_indices(g_shrunk);\n\n        //reset_vertex_indices(g_shrunk);\n        //reset_edge_index(g_shrunk);\n        EmbedStruct em = ctor_workaround(&g_shrunk);\n        BOOST_ASSERT(test_planar_workaround(em.em, &g_shrunk));\n\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n\n        VertIter vei, vend;\n        for( tie(vei, vend) = vertices(g_orig); vei != vend; ++vei ){ \n                vertex_t v = *vei;\n                if( !vis_data_orig.verts.contains(v) ){\n                        cerr << \"lipton-tarjan.cpp: ignoring bad vertex : \" << v << '\\n';\n                        continue; \n                }\n        }\n\n        ScanVisitor svis(&table, &g_shrunk, x, l[0]);\n        svis.scan_nonsubtree_edges_clockwise(*vertices(g_shrunk).first, g_shrunk, em.em, vis_data_addx);\n        svis.finish();\n\n        BOOST_ASSERT(vertex_exists(x, g_shrunk));\n\n        cout << \"deleting all vertices x has replaced\\n\"; for( vertex_t& v : replaced_verts ) {cout << \"killing \" << v << '\\n'; kill_vertex(v, g_shrunk); }// delete all vertices x has replaced\n\n        reset_vertex_indices(g_shrunk);\n\n        BOOST_ASSERT(vertex_exists(x, g_shrunk));\n\n        cout << \"g_shrunk:\\n\";\n        print_graph(g_shrunk);\n\n        uint n2 = num_vertices(g_shrunk);\n        cout << \"shrunken size: \" << n2 << '\\n';\n\n        auto prop_map = get(vertex_index, g_shrunk);\n        cout << \"x prop_map: \" << prop_map[x] << '\\n';\n        cout << \"x : \" << x << '\\n';\n\n\treturn new_bfs_and_make_max_planar(g_orig, g_shrunk, vis_data_orig, x, L, l); // step 7\n}\n\n// Step 5: find_more_levels\n// Time:   O(n)\n//\n// Find the highest level l0 <= l1 such that L(l0) + 2(l1 - l0) <= 2*sqrt(k).\n// Find the lowest level l2 >= l1 + 1 such that L(l2) + 2(l2-l1-1) <= 2*sqrt(n-k)\nPartition find_more_levels(GraphCR g_orig, Graph& g_copy, uint k, uint l[3], vector<uint> const& L, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_copy)\n{\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n\n        cout  << \"---------------------------- 5 - Find More Levels -------\\n\";\n        //print_graph(g_copy);\n        float sq  = 2 * sqrt(k); \n        float snk = 2 * sqrt(num_vertices(g_copy) - k); \n        cout << \"sq:     \" << sq << '\\n';\n        cout << \"snk:    \" << snk << '\\n';\n        cout << \"L size: \" << L.size() << '\\n';\n\n        l[0] = l[1];\n        cout << \"l[0]:   \" << l[0] << '\\n';\n        while( l[0] < L.size() ){\n                float val = L.at(l[0]) + 2*(l[1] - l[0]);\n                if( val <= sq ) break;\n                --l[0];\n        }\n        cout << \"l0: \" << l[0] << \"     highest level <= l1\\n\";\n\n        l[2] = l[1] + 1;\n        cout << \"l[2]\" << l[2] << '\\n';\n        while( l[2] < L.size() ){\n                float val = L.at(l[2]) + 2*(l[2] - l[1] - 1);\n                if( val <= snk ) break;\n                ++l[2];\n        }\n        cout << \"l2: \" << l[2] << \"     lowest  level >= l1 + 1\\n\";\n\n\treturn shrinktree(g_orig, g_copy, vis_data_orig, vis_data_copy, L, l); // step 6\n}\n\n// Step 4: l1_and_k\n// Time:   O(n)\n//\n// Find the level l1 such that the total cost of levels 0 through l1 - 1 does not exceed 1/2,\n// but the total cost of levels 0 through l1 does exceed 1/2.\n// Let k be the number of vertices in levels 0 through l1\nPartition l1_and_k(GraphCR g_orig, Graph& g_copy, vector<uint> const& L, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_copy)\n{\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components\n\n        cout  << \"---------------------------- 4 - l1 and k  ------------\\n\";\n        uint k = L[0]; \n        uint l[3];\n        uint n = num_vertices(g_copy);\n        l[1] = 0;\n        while( k <= n/2 ){\n                uint indx = ++l[1];\n                uint lsize = L.size();\n                if( indx >= lsize ) break;\n\t       \tk += L.at(indx);\n\t}\n\n        cout << \"k:  \" << k    << \"      # of verts in levels 0 thru l1\\n\";\n        cout << \"l1: \" << l[1] << \"      total cost of levels 0 thru l1 barely exceeds 1/2\\n\";\n\tBOOST_ASSERT(k <= n); \n\treturn find_more_levels(g_orig, g_copy, k, l, L, vis_data_orig, vis_data_copy); // step 5\n}\n\n// Step 3: bfs_and_levels\n// Time:   O(n)\n//\n// Find a breadth-first spanning tree of the most costly component.\n// Compute the level of each vertex and the number of vertices L(l) in each level l.\nPartition bfs_and_levels(GraphCR g_orig, Graph& g_copy)\n{\n        cout << \"---------------------------- 3 - BFS and Levels ------------\\n\";\n        BFSVisitorData vis_data_copy(&g_copy, *vertices(g_copy).first);\n        breadth_first_search(g_copy, vis_data_copy.root, boost::visitor(BFSVisitor(vis_data_copy)));\n        BFSVisitorData vis_data_orig(&g_orig, *vertices(g_orig).first);\n        breadth_first_search(g_orig, vis_data_orig.root, boost::visitor(BFSVisitor(vis_data_orig)));\n\n        // disabled because they don't support multiple connected components\n        //BOOST_ASSERT(assert_verts(g_orig, vis_data_orig));\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy));\n\n        vector<uint> L(vis_data_copy.num_levels + 1, 0);\n\tcout << \"L levels: \" << L.size() << '\\n';\n        for( auto& d : vis_data_copy.verts ){\n                cout << \"level: \" << d.second.level << '\\n';\n\t       \t++L[d.second.level];\n\t}\n\n\tVertIter vit, vjt;\n        for( tie(vit, vjt) = vertices(g_copy); vit != vjt; ++vit ){\n                if( vis_data_copy.verts.contains(*vit) ) cout << \"level/cost of vert \" << *vit << \": \" << vis_data_copy.verts[*vit].level << '\\n';\n\t}\n        for( uint i = 0; i < L.size(); ++i ){\n\t\tcout << \"L[\" << i << \"]: \" << L[i] << '\\n';\n\t}\n\n\treturn l1_and_k(g_orig, g_copy, L, vis_data_orig, vis_data_copy); // step 4\n}\n\n// Step 2: find_connected_components\n// Time:   O(n)\n//\n// Find the connected components of G and determine the cost of each one.\n// If none has cost exceeding 2/3, construct the partition as described in the proof of Theorem 4.\n// If some component has cost exceeding 2/3, go to Step 3.\nPartition find_connected_components(GraphCR g_orig, Graph& g_copy)\n{\n\tuint n = num_vertices(g_copy);\n        //cout << \"---------------------------- 2 - Find Connected Components --------\\n\";\n        vertex_map idx; \n        associative_property_map<vertex_map> vertid_to_component(idx);\n        VertIter vit, vjt;\n        tie(vit, vjt) = vertices(g_copy);\n        for( uint i = 0; vit != vjt; ++vit, ++i ){\n\t\t//cout << \"checking vertex number: \" << i << ' ' << *vit << '\\n';\n\t       \tput(vertid_to_component, *vit, i);\n\t}\n        uint num_components = connected_components(g_copy, vertid_to_component);\n\n        //cout << \"# of connected components: \" << num_components << '\\n';\n        vector<uint> num_verts_per_component(num_components, 0);\n        for( tie(vit, vjt) = vertices(g_copy); vit != vjt; ++vit ){\n\t       \t++num_verts_per_component[vertid_to_component[*vit]];\n\t}\n        uint biggest_component_index = 0;\n        uint biggest_size            = 0;\n        bool bigger_than_two_thirds  = false;\n        for( uint i = 0; i < num_components; ++i ){\n                if( 3*num_verts_per_component[i] > 2*num_vertices(g_copy) ){\n                        //cout << \"component \" << i << \" is bigger than two thirds of the entire graph\\n\";\n                        bigger_than_two_thirds = true;\n                }\n                if( num_verts_per_component[i] > biggest_size ){\n                        biggest_size = num_verts_per_component[i];\n                        biggest_component_index = i;\n                }\n        }\n\n        if( !bigger_than_two_thirds ){\n\t\tcout << \"exiting early through theorem 4 - no component has cost exceeding two thirds\\n\";\n\t\t// connected graphs can never get here because they would have a single component with total cost > 2/3\n                Partition defp;\n\t\treturn theorem4_disconnected(g_copy, n, num_components, vertid_to_component, num_verts_per_component, defp);\n        }\n        cout << \"index of biggest component: \" << biggest_component_index << '\\n';\n\n\treturn bfs_and_levels(g_orig, g_copy); // step 3\n}\n\n// Step 1: check_planarity\n// Time:   big-theta(n)\n//\n// Find a planar embedding of G and construct a representation for it of the kind described above.\nPartition lipton_tarjan_separator(GraphCR g_orig)\n{\n\tGraph g_copy(g_orig);\n\n\t//cout << \"@#$original g:\\n\";\n\tprint_graph(g_orig);\n\t//cout << \"@#$g_copy:\\n\";\n\t//print_graph2(g_copy);\n\n        /*auto prop_map = get(vertex_index, g_copy);\n        VertIter vi, vend;\n        for( tie(vi, vend) = vertices(g_copy); vi != vend; ++vi ){\n                cout << \"vert#: \" << prop_map[*vi] << '\\n';\n        }*/\n\n\t/*cout << \"---------------------------- 0 - Printing Edges -------------------\\n\";\n\tcout << \"edges of g:\\n\";*/\n\t//cout << \"edges of g_copy:\\n\" << std::endl;\n\n        cout << \"---------------------------- 1 - Check Planarity  ------------\\n\";\n        EmbedStruct em(&g_copy);\n        if( !em.test_planar() ) throw NotPlanarException();\n\n\treturn find_connected_components(g_orig, g_copy);\n}\n", "meta": {"hexsha": "2a0f6d0725d97dc1332a8ce9872eb32a43402f73", "size": 33384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lipton-tarjan.cpp", "max_stars_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_stars_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-05-20T11:20:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T15:50:33.000Z", "max_issues_repo_path": "lipton-tarjan.cpp", "max_issues_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_issues_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-12-02T06:35:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T19:58:56.000Z", "max_forks_repo_path": "lipton-tarjan.cpp", "max_forks_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_forks_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-04-19T16:37:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T04:29:33.000Z", "avg_line_length": 49.3116691285, "max_line_length": 224, "alphanum_fraction": 0.6036724179, "num_tokens": 8682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.038466187746970484, "lm_q1q2_score": 0.019082838384541948}}
{"text": "//\n// CPPINTS: A C++ Program to Generate Analytical Integrals Based on Gaussian\n// Form Primitive Functions\n//\n// Copyright (C) 2015 The State University of New York at Buffalo\n// This softare uses the MIT license as below:\n//\n//\tPermission is hereby granted, free of charge, to any person obtaining \n//\ta copy of this software and associated documentation files (the \"Software\"), \n//\tto deal in the Software without restriction, including without limitation \n//\tthe rights to use, copy, modify, merge, publish, distribute, sublicense, \n//\tand/or sell copies of the Software, and to permit persons to whom the Software \n//\tis 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//\t\t\t\t\t\t    \n//\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, \n//\tINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR \n//\tPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE \n//\tFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, \n//\tARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n//\n#include \"basisutil.h\"\n#include \"shellsymbol.h\"\n#include <boost/algorithm/string.hpp> \nusing namespace basisutil;\nusing namespace boost;\n\nvoid BasisUtil::getLMNVal(const int& L, const int& index,\n\t\tint& l, int& m, int& n) const \n{\n\tif (L<=MAX_L) {\n\t\tint ii = L*(L+1)*(L+2)/6 + index;\n\t\tl = LIBINT_BASIS_SET_ORDER[3*ii  ];\n\t\tm = LIBINT_BASIS_SET_ORDER[3*ii+1];\n\t\tn = LIBINT_BASIS_SET_ORDER[3*ii+2];\n\t}else{\n\t\t// now we have to use the libint order to generate th l m n\n\t\tint nx = -1;\n\t\tint ny = -1;\n\t\tint nz = -1;\n\t\tint count = 0;\n\t\tfor(int x=0; x<=L; x++) {\n\t\t\tnx = L - x;\n\t\t\tfor(int y=0; y<=x; y++) {\n\t\t\t\tny = x-y; \n\t\t\t\tnz = y;   \n\t\t\t\tif (count == index) {\n\t\t\t\t\tl = nx;\n\t\t\t\t\tm = ny;\n\t\t\t\t\tn = nz;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint BasisUtil::getLocalBasisSetIndex(const int& l, const int& m,\n\t\tconst int& n) const \n{\n\t// actually we note that since here we calculate the local index\n\t// within the shell, therefore we only need the m and n value actually\n\t// however, we still pass in the l,m,n in full since we do not want \n\t// to mistake about whether it's l,m passed or m,n passed\n\tint index = -1;\n\tint x =  m + n;\n\tindex = (x*(x+1))/2 + n;\n\treturn index;\n}\n\n", "meta": {"hexsha": "882db716dea7252c605707ed3f60a27380566795", "size": 2498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basisutil.cpp", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basisutil.cpp", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basisutil.cpp", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3066666667, "max_line_length": 104, "alphanum_fraction": 0.6809447558, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.04468087218079564, "lm_q1q2_score": 0.019048420584527655}}
{"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/BoundingVolume.h\"\n\n#include <Eigen/Eigenvalues>\n#include <numeric>\n\n#include \"open3d/geometry/PointCloud.h\"\n#include \"open3d/geometry/Qhull.h\"\n#include \"open3d/geometry/TriangleMesh.h\"\n#include \"open3d/utility/Console.h\"\n\nnamespace open3d {\nnamespace geometry {\n\nOrientedBoundingBox& OrientedBoundingBox::Clear() {\n    center_.setZero();\n    extent_.setZero();\n    R_ = Eigen::Matrix3d::Identity();\n    color_.setZero();\n    return *this;\n}\n\nbool OrientedBoundingBox::IsEmpty() const { return Volume() <= 0; }\n\nEigen::Vector3d OrientedBoundingBox::GetMinBound() const {\n    auto points = GetBoxPoints();\n    return ComputeMinBound(points);\n}\n\nEigen::Vector3d OrientedBoundingBox::GetMaxBound() const {\n    auto points = GetBoxPoints();\n    return ComputeMaxBound(points);\n}\n\nEigen::Vector3d OrientedBoundingBox::GetCenter() const { return center_; }\n\nAxisAlignedBoundingBox OrientedBoundingBox::GetAxisAlignedBoundingBox() const {\n    return AxisAlignedBoundingBox::CreateFromPoints(GetBoxPoints());\n}\n\nOrientedBoundingBox OrientedBoundingBox::GetOrientedBoundingBox() const {\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Transform(\n        const Eigen::Matrix4d& transformation) {\n    utility::LogError(\n            \"A general transform of an OrientedBoundingBox is not implemented. \"\n            \"Call Translate, Scale, and Rotate.\");\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Translate(\n        const Eigen::Vector3d& translation, bool relative) {\n    if (relative) {\n        center_ += translation;\n    } else {\n        center_ = translation;\n    }\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Scale(const double scale,\n                                                const Eigen::Vector3d& center) {\n    extent_ *= scale;\n    center_ = scale * (center_ - center) + center;\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Rotate(\n        const Eigen::Matrix3d& R, const Eigen::Vector3d& center) {\n    R_ = R * R_;\n    center_ = R * (center_ - center) + center;\n    return *this;\n}\n\ndouble OrientedBoundingBox::Volume() const {\n    return extent_(0) * extent_(1) * extent_(2);\n}\n\nstd::vector<Eigen::Vector3d> OrientedBoundingBox::GetBoxPoints() const {\n    Eigen::Vector3d x_axis = R_ * Eigen::Vector3d(extent_(0) / 2, 0, 0);\n    Eigen::Vector3d y_axis = R_ * Eigen::Vector3d(0, extent_(1) / 2, 0);\n    Eigen::Vector3d z_axis = R_ * Eigen::Vector3d(0, 0, extent_(2) / 2);\n    std::vector<Eigen::Vector3d> points(8);\n    points[0] = center_ - x_axis - y_axis - z_axis;\n    points[1] = center_ + x_axis - y_axis - z_axis;\n    points[2] = center_ - x_axis + y_axis - z_axis;\n    points[3] = center_ - x_axis - y_axis + z_axis;\n    points[4] = center_ + x_axis + y_axis + z_axis;\n    points[5] = center_ - x_axis + y_axis + z_axis;\n    points[6] = center_ + x_axis - y_axis + z_axis;\n    points[7] = center_ + x_axis + y_axis - z_axis;\n    return points;\n}\n\nstd::vector<size_t> OrientedBoundingBox::GetPointIndicesWithinBoundingBox(\n        const std::vector<Eigen::Vector3d>& points) const {\n    std::vector<size_t> indices;\n    Eigen::Vector3d dx = R_ * Eigen::Vector3d(1, 0, 0);\n    Eigen::Vector3d dy = R_ * Eigen::Vector3d(0, 1, 0);\n    Eigen::Vector3d dz = R_ * Eigen::Vector3d(0, 0, 1);\n    for (size_t idx = 0; idx < points.size(); idx++) {\n        Eigen::Vector3d d = points[idx] - center_;\n        if (std::abs(d.dot(dx)) <= extent_(0) / 2 &&\n            std::abs(d.dot(dy)) <= extent_(1) / 2 &&\n            std::abs(d.dot(dz)) <= extent_(2) / 2) {\n            indices.push_back(idx);\n        }\n    }\n    return indices;\n}\n\nOrientedBoundingBox OrientedBoundingBox::CreateFromAxisAlignedBoundingBox(\n        const AxisAlignedBoundingBox& aabox) {\n    OrientedBoundingBox obox;\n    obox.center_ = aabox.GetCenter();\n    obox.extent_ = aabox.GetExtent();\n    obox.R_ = Eigen::Matrix3d::Identity();\n    return obox;\n}\n\nOrientedBoundingBox OrientedBoundingBox::CreateFromPoints(\n        const std::vector<Eigen::Vector3d>& points) {\n    PointCloud hull_pcd;\n    hull_pcd.points_ = std::get<0>(Qhull::ComputeConvexHull(points))->vertices_;\n\n    Eigen::Vector3d mean;\n    Eigen::Matrix3d cov;\n    std::tie(mean, cov) = hull_pcd.ComputeMeanAndCovariance();\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(cov);\n    Eigen::Vector3d evals = es.eigenvalues();\n    Eigen::Matrix3d R = es.eigenvectors();\n    R.col(0) /= R.col(0).norm();\n    R.col(1) /= R.col(1).norm();\n    R.col(2) /= R.col(2).norm();\n\n    if (evals(1) > evals(0)) {\n        std::swap(evals(1), evals(0));\n        Eigen::Vector3d tmp = R.col(1);\n        R.col(1) = R.col(0);\n        R.col(0) = tmp;\n    }\n    if (evals(2) > evals(0)) {\n        std::swap(evals(2), evals(0));\n        Eigen::Vector3d tmp = R.col(2);\n        R.col(2) = R.col(0);\n        R.col(0) = tmp;\n    }\n    if (evals(2) > evals(1)) {\n        std::swap(evals(2), evals(1));\n        Eigen::Vector3d tmp = R.col(2);\n        R.col(2) = R.col(1);\n        R.col(1) = tmp;\n    }\n\n    for (auto& pt : hull_pcd.points_) {\n        pt = R.transpose() * (pt - mean);\n    }\n    const auto aabox = hull_pcd.GetAxisAlignedBoundingBox();\n\n    OrientedBoundingBox obox;\n    obox.center_ = R * aabox.GetCenter() + mean;\n    obox.R_ = R;\n    obox.extent_ = aabox.GetExtent();\n\n    return obox;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Clear() {\n    min_bound_.setZero();\n    max_bound_.setZero();\n    return *this;\n}\n\nbool AxisAlignedBoundingBox::IsEmpty() const { return Volume() <= 0; }\n\nEigen::Vector3d AxisAlignedBoundingBox::GetMinBound() const {\n    return min_bound_;\n}\n\nEigen::Vector3d AxisAlignedBoundingBox::GetMaxBound() const {\n    return max_bound_;\n}\n\nEigen::Vector3d AxisAlignedBoundingBox::GetCenter() const {\n    return (min_bound_ + max_bound_) * 0.5;\n}\n\nAxisAlignedBoundingBox AxisAlignedBoundingBox::GetAxisAlignedBoundingBox()\n        const {\n    return *this;\n}\n\nOrientedBoundingBox AxisAlignedBoundingBox::GetOrientedBoundingBox() const {\n    return OrientedBoundingBox::CreateFromAxisAlignedBoundingBox(*this);\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Transform(\n        const Eigen::Matrix4d& transformation) {\n    utility::LogError(\n            \"A general transform of a AxisAlignedBoundingBox would not be axis \"\n            \"aligned anymore, convert it to a OrientedBoundingBox first\");\n    return *this;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Translate(\n        const Eigen::Vector3d& translation, bool relative) {\n    if (relative) {\n        min_bound_ += translation;\n        max_bound_ += translation;\n    } else {\n        const Eigen::Vector3d half_extent = GetHalfExtent();\n        min_bound_ = translation - half_extent;\n        max_bound_ = translation + half_extent;\n    }\n    return *this;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Scale(\n        const double scale, const Eigen::Vector3d& center) {\n    min_bound_ = center + scale * (min_bound_ - center);\n    max_bound_ = center + scale * (max_bound_ - center);\n    return *this;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Rotate(\n        const Eigen::Matrix3d& rotation, const Eigen::Vector3d& center) {\n    utility::LogError(\n            \"A rotation of a AxisAlignedBoundingBox would not be axis aligned \"\n            \"anymore, convert it to an OrientedBoundingBox first\");\n    return *this;\n}\n\nstd::string AxisAlignedBoundingBox::GetPrintInfo() const {\n    return fmt::format(\"[({:.4f}, {:.4f}, {:.4f}) - ({:.4f}, {:.4f}, {:.4f})]\",\n                       min_bound_(0), min_bound_(1), min_bound_(2),\n                       max_bound_(0), max_bound_(1), max_bound_(2));\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::operator+=(\n        const AxisAlignedBoundingBox& other) {\n    if (IsEmpty()) {\n        min_bound_ = other.min_bound_;\n        max_bound_ = other.max_bound_;\n    } else if (!other.IsEmpty()) {\n        min_bound_ = min_bound_.array().min(other.min_bound_.array()).matrix();\n        max_bound_ = max_bound_.array().max(other.max_bound_.array()).matrix();\n    }\n    return *this;\n}\n\nAxisAlignedBoundingBox AxisAlignedBoundingBox::CreateFromPoints(\n        const std::vector<Eigen::Vector3d>& points) {\n    AxisAlignedBoundingBox box;\n    if (points.empty()) {\n        box.min_bound_ = Eigen::Vector3d(0.0, 0.0, 0.0);\n        box.max_bound_ = Eigen::Vector3d(0.0, 0.0, 0.0);\n    } else {\n        box.min_bound_ = std::accumulate(\n                points.begin(), points.end(), points[0],\n                [](const Eigen::Vector3d& a, const Eigen::Vector3d& b) {\n                    return a.array().min(b.array()).matrix();\n                });\n        box.max_bound_ = std::accumulate(\n                points.begin(), points.end(), points[0],\n                [](const Eigen::Vector3d& a, const Eigen::Vector3d& b) {\n                    return a.array().max(b.array()).matrix();\n                });\n    }\n    return box;\n}\n\ndouble AxisAlignedBoundingBox::Volume() const { return GetExtent().prod(); }\n\nstd::vector<Eigen::Vector3d> AxisAlignedBoundingBox::GetBoxPoints() const {\n    std::vector<Eigen::Vector3d> points(8);\n    Eigen::Vector3d extent = GetExtent();\n    points[0] = min_bound_;\n    points[1] = min_bound_ + Eigen::Vector3d(extent(0), 0, 0);\n    points[2] = min_bound_ + Eigen::Vector3d(0, extent(1), 0);\n    points[3] = min_bound_ + Eigen::Vector3d(0, 0, extent(2));\n    points[4] = max_bound_;\n    points[5] = max_bound_ - Eigen::Vector3d(extent(0), 0, 0);\n    points[6] = max_bound_ - Eigen::Vector3d(0, extent(1), 0);\n    points[7] = max_bound_ - Eigen::Vector3d(0, 0, extent(2));\n    return points;\n}\n\nstd::vector<size_t> AxisAlignedBoundingBox::GetPointIndicesWithinBoundingBox(\n        const std::vector<Eigen::Vector3d>& points) const {\n    std::vector<size_t> indices;\n    for (size_t idx = 0; idx < points.size(); idx++) {\n        const auto& point = points[idx];\n        if (point(0) >= min_bound_(0) && point(0) <= max_bound_(0) &&\n            point(1) >= min_bound_(1) && point(1) <= max_bound_(1) &&\n            point(2) >= min_bound_(2) && point(2) <= max_bound_(2)) {\n            indices.push_back(idx);\n        }\n    }\n    return indices;\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "ba12a9001d96afb7dd62f70985ebbd5f4551e2ad", "size": 11659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/geometry/BoundingVolume.cpp", "max_stars_repo_name": "xkaraman/Open3D", "max_stars_repo_head_hexsha": "a1d65eca537a2b099fc3b6d08edb26e45b717e40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T14:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:35:27.000Z", "max_issues_repo_path": "cpp/open3d/geometry/BoundingVolume.cpp", "max_issues_repo_name": "moonwonlee/Open3D", "max_issues_repo_head_hexsha": "dda9b3a0129fa6c60f913672a70ff02483dcd0f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T09:22:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T01:32:31.000Z", "max_forks_repo_path": "cpp/open3d/geometry/BoundingVolume.cpp", "max_forks_repo_name": "moonwonlee/Open3D", "max_forks_repo_head_hexsha": "dda9b3a0129fa6c60f913672a70ff02483dcd0f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T18:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T10:48:34.000Z", "avg_line_length": 35.1174698795, "max_line_length": 80, "alphanum_fraction": 0.633416245, "num_tokens": 3079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03963884080272446, "lm_q1q2_score": 0.019045617828244488}}
{"text": "#ifndef D_MOSAIC_GEOCUTS_IMPL_HPP\r\n#define D_MOSAIC_GEOCUTS_IMPL_HPP\r\n\r\n#include <time.h>\r\n\r\n#include <boost/config.hpp>\r\n// for boost::tie\r\n#include <boost/utility.hpp>\r\n// for boost::graph_traits\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n\r\n#include <boost/version.hpp>\r\n#if BOOST_VERSION >= 104700\r\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\r\n#elif BOOST_VERSION >= 103500\r\n#include <boost/graph/kolmogorov_max_flow.hpp>\r\n#endif\r\n\r\n#include <vector>\r\n\r\nstatic int debugOn = false;\r\n\r\n#define SMIL_ENTER_FUNCTION(a)                                                 \\\r\n  {                                                                            \\\r\n    if (debugOn)                                                               \\\r\n      cout << \"Entering function \" << __func__ << \" \" << (a) << endl;          \\\r\n  }\r\n\r\n#define SMIL_REGISTER_ERROR(a)\r\n\r\nnamespace smil\r\n{\r\n  /*\r\n   * Some useful tools\r\n   */\r\n  /* This function selects points from an Structuring element\r\n   * generating a positive offset\r\n   */\r\n  inline vector<IntPoint> filterStrElt(StrElt se)\r\n  {\r\n    vector<IntPoint> pts(0);\r\n\r\n    vector<IntPoint>::iterator it, itStart, itEnd;\r\n    itStart = se.points.begin();\r\n    itEnd   = se.points.end();\r\n\r\n    for (it = itStart; it != itEnd; it++) {\r\n      bool ok = (4 * it->z + 2 * it->y + it->x) > 0;\r\n      if (ok)\r\n        pts.push_back(*it);\r\n\r\n      if (debugOn) {\r\n        std::cout << (ok ? \"GOOD \" : \"BAD  \") << std::right << \" \"\r\n                  << std::setw(6) << it->x << \" \" << std::setw(6) << it->y\r\n                  << \" \" << std::setw(6) << it->z << endl;\r\n      }\r\n    }\r\n    return pts;\r\n  }\r\n\r\n  /*\r\n   *\r\n   */\r\n  using namespace boost;\r\n\r\n  // needed for max flow: capacit map, rev_capacity map, etc.\r\n  typedef adjacency_list_traits<vecS, vecS, directedS> Traits_T;\r\n\r\n  typedef adjacency_list<\r\n      vecS, vecS, directedS, property<vertex_name_t, std::string>,\r\n      property<edge_capacity_t, double,\r\n               property<edge_residual_capacity_t, double,\r\n                        property<edge_reverse_t, Traits_T::edge_descriptor>>>>\r\n      GraphVV_T;\r\n\r\n  // edge capacity\r\n  typedef property_map<GraphVV_T, edge_capacity_t>::type EdgeCapVV_T;\r\n  // edge reverse\r\n  typedef property_map<GraphVV_T, edge_reverse_t>::type EdgeRevCapVV_T;\r\n  // edge residual capacity\r\n  typedef property_map<GraphVV_T, edge_residual_capacity_t>::type EdgeResCapVV_T;\r\n  //\r\n  typedef property_map<GraphVV_T, vertex_index_t>::type VertexIndexVV_T;\r\n  \r\n  typedef adjacency_list<\r\n      listS, vecS, directedS, property<vertex_name_t, std::string>,\r\n      property<edge_capacity_t, double,\r\n               property<edge_residual_capacity_t, double,\r\n                        property<edge_reverse_t, Traits_T::edge_descriptor>>>>\r\n      GraphLV_T;\r\n\r\n  // edge capacity\r\n  typedef property_map<GraphLV_T, edge_capacity_t>::type EdgeCapLV_T;\r\n  // edge reverse\r\n  typedef property_map<GraphLV_T, edge_reverse_t>::type EdgeRevCapLV_T;\r\n  // edge residual capacity\r\n  typedef property_map<GraphLV_T, edge_residual_capacity_t>::type EdgeResCapLV_T;\r\n  //\r\n  typedef property_map<GraphLV_T, vertex_index_t>::type VertexIndexLV_T;\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n  template <class T>\r\n  RES_T geoCutsMinSurfaces(const Image<T> &imIn, const Image<T> &imGrad,\r\n                            const Image<T> &imMarker, const StrElt &nl,\r\n                            Image<T> &imOut)\r\n  {\r\n    SMIL_ENTER_FUNCTION(\"\");\r\n\r\n    ASSERT_ALLOCATED(&imIn, &imGrad, &imMarker, &imOut);\r\n    ASSERT_SAME_SIZE(&imIn, &imGrad, &imMarker, &imOut);\r\n\r\n    typename Image<T>::lineType bufIn     = imIn.getPixels();\r\n    typename Image<T>::lineType bufOut    = imOut.getPixels();\r\n    typename Image<T>::lineType bufMarker = imMarker.getPixels();\r\n    typename Image<T>::lineType bufGrad   = imGrad.getPixels();\r\n\r\n    GraphVV_T g;\r\n    EdgeCapVV_T capacity = boost::get(boost::edge_capacity, g);\r\n    EdgeRevCapVV_T rev   = boost::get(boost::edge_reverse, g);\r\n    EdgeResCapVV_T residual_capacity =\r\n        boost::get(boost::edge_residual_capacity, g);\r\n\r\n    GraphVV_T::edge_descriptor e1, e2, e3, e4, e5;\r\n    GraphVV_T::vertex_descriptor vSource, vSink;\r\n\r\n    int numVertex = maxVal(imIn);\r\n    int numEdges  = 0;\r\n\r\n    std::cout << \"build Region Adjacency Graph\" << std::endl;\r\n    std::cout << \"build Region Adjacency Graph Vertices\" << std::endl;\r\n\r\n    clock_t t1 = clock();\r\n\r\n    std::cout << \"number of Vertices : \" << numVertex << std::endl;\r\n\r\n    for (int i = 1; i <= numVertex; i++) {\r\n      boost::add_vertex(g);\r\n    }\r\n\r\n    vSource = boost::add_vertex(g);\r\n    vSink   = boost::add_vertex(g);\r\n\r\n    clock_t tt_marker2 = 0, tt_marker3 = 0, tt_new_edge = 0, tt_old_edge = 0;\r\n    clock_t t2 = clock();\r\n    std::cout << \"Nodes creation time : \" << double(t2 - t1) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n\r\n    std::cout << \"Building Region Adjacency Graph Edges\" << std::endl;\r\n    t1 = clock();\r\n\r\n    // iterators on the Structuring Element\r\n    vector<IntPoint> pts = filterStrElt(nl);\r\n    vector<IntPoint>::iterator itBegin, itEnd;\r\n    itBegin = pts.begin();\r\n    itEnd   = pts.end();\r\n\r\n    int width  = imIn.getWidth();\r\n    int height = imIn.getHeight();\r\n    int depth  = imIn.getDepth();\r\n\r\n    off_t strideY = width;\r\n    off_t strideZ = width * height;\r\n    for (int z = 0; z < depth; z++) {\r\n      off_t p0Z = z * strideZ;\r\n      for (int y = 0; y < height; y++) {\r\n        off_t p0Y = y * strideY;\r\n        for (int x = 0; x < width; x++) {\r\n          off_t o1 = p0Z + p0Y + x;\r\n\r\n          int val1        = (int) bufIn[o1];\r\n          int marker      = (int) bufMarker[o1];\r\n          int val_prec    = 0;\r\n          int marker_prec = 0;\r\n\r\n          if (val1 <= 0)\r\n            continue;\r\n\r\n          // do the following only for val1 > 0\r\n          if (marker == 2 && marker_prec != marker && val_prec != val1) {\r\n            clock_t temps_marker2 = clock();\r\n\r\n            bool hasEdge;\r\n            boost::tie(e4, hasEdge) = boost::edge(vSource, val1, g);\r\n            if (!hasEdge) {\r\n              // std::cout<<\"Add new edge marker 2\"<<std::endl;\r\n              boost::tie(e4, hasEdge) = boost::add_edge(vSource, val1, g);\r\n              boost::tie(e3, hasEdge) = boost::add_edge(val1, vSource, g);\r\n              capacity[e4]            = (std::numeric_limits<double>::max)();\r\n              capacity[e3]            = (std::numeric_limits<double>::max)();\r\n              rev[e4]                 = e3;\r\n              rev[e3]                 = e4;\r\n            }\r\n            tt_marker2 += clock() - temps_marker2;\r\n          } else {\r\n            if (marker == 3 && marker_prec != marker && val_prec != val1) {\r\n              clock_t temps_marker3 = clock();\r\n              bool hasEdge;\r\n              boost::tie(e3, hasEdge) = boost::edge(vSink, val1, g);\r\n              if (!hasEdge) {\r\n                // std::cout<<\"Add new edge marker 3\"<<std::endl;\r\n                boost::tie(e4, hasEdge) = boost::add_edge(val1, vSink, g);\r\n                boost::tie(e3, hasEdge) = boost::add_edge(vSink, val1, g);\r\n                capacity[e4]            = (std::numeric_limits<double>::max)();\r\n                capacity[e3]            = (std::numeric_limits<double>::max)();\r\n                rev[e4]                 = e3;\r\n                rev[e3]                 = e4;\r\n              }\r\n              tt_marker3 += clock() - temps_marker3;\r\n            }\r\n          }\r\n\r\n          double val_grad_o1 = (double) bufGrad[o1];\r\n          // val de val2 precedente\r\n          int val2_prec = val1;\r\n\r\n          // iterators on the Structuring Element\r\n          vector<IntPoint> pts = filterStrElt(nl);\r\n          vector<IntPoint>::iterator itBegin, itEnd, it;\r\n          itBegin = pts.begin();\r\n          itEnd   = pts.end();\r\n \r\n          for (it = itBegin; it != itEnd; it++) {\r\n            if (x + it->x > width - 1 || x + it->x < 0)\r\n              continue;\r\n            if (y + it->y > height - 1 || y + it->y < 0)\r\n              continue;\r\n            if (z + it->z > depth - 1 || z + it->z < 0)\r\n              continue;\r\n\r\n            off_t o2 = o1 + it->z * strideZ + it->y * strideY + it->x;\r\n            if (o2 <= o1)\r\n              continue;\r\n\r\n            int val2 = bufIn[o2];\r\n            if (val1 == val2)\r\n              continue;\r\n              \r\n            double val_grad_o2 = bufGrad[o2];\r\n            double maxi        = std::max(val_grad_o1, val_grad_o2);\r\n            double cost        = 10000.0 / (1.0 + std::pow(maxi, 4));\r\n\r\n            if (val2_prec == val2) {\r\n              // same val2 means same edge (thus, keep e3 and e4)\r\n              capacity[e4] = capacity[e4] + cost;\r\n              capacity[e3] = capacity[e3] + cost;\r\n            } else {\r\n              bool hasEdge;\r\n              \r\n              boost::tie(e5, hasEdge) = boost::edge(val1, val2, g);\r\n              if (hasEdge == 0) {\r\n                clock_t temps_new_edge = clock();\r\n                // std::cout<<\"Add new edge \"<< val1<<\" --\r\n                // \"<<val2<<std::endl;\r\n                numEdges++;\r\n                boost::tie(e4, hasEdge) = boost::add_edge(val1, val2, g);\r\n                boost::tie(e3, hasEdge) = boost::add_edge(val2, val1, g);\r\n                capacity[e4]            = cost;\r\n                capacity[e3]            = cost;\r\n                rev[e4]                 = e3;\r\n                rev[e3]                 = e4;\r\n                tt_new_edge += clock() - temps_new_edge;                \r\n              } else {\r\n                clock_t temps_old_edge = clock();\r\n                // std::cout<<\"existing edge\"<<std::endl;\r\n                boost::tie(e4, hasEdge) = boost::edge(val1, val2, g);\r\n                boost::tie(e3, hasEdge) = boost::edge(val2, val1, g);\r\n                capacity[e4]            = capacity[e4] + cost;\r\n                capacity[e3]            = capacity[e3] + cost;\r\n                tt_old_edge += clock() - temps_old_edge;\r\n              }\r\n              val2_prec = val2;\r\n            }\r\n          }\r\n          val_prec    = val1;\r\n          marker_prec = marker;\r\n        }\r\n      }\r\n    }\r\n\r\n    std::cout << \"Number of edges : \" << numEdges << std::endl;\r\n    t2 = clock();\r\n    std::cout << \"Edges creation time : \" << double(t2 - t1) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n    std::cout << \"Marker2   : \" << double(tt_marker2) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n    std::cout << \"Marker3   : \" << double(tt_marker3) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n    std::cout << \"New edges : \" << double(tt_new_edge) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n    std::cout << \"Old edges : \" << double(tt_old_edge) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n\r\n    boost::property_map<GraphVV_T, boost::vertex_index_t>::type indexmap =\r\n        boost::get(boost::vertex_index, g);\r\n    std::vector<boost::default_color_type> color(boost::num_vertices(g));\r\n\r\n    std::cout << \"Compute Max flow\" << std::endl;\r\n    t1 = clock();\r\n#if BOOST_VERSION >= 104700\r\n      // XXX - JOE - Check against this function prototype :\r\n      // boykov_kolmogorov_max_flow(\r\n      //     Graph& g,\r\n      //     CapacityEdgeMap cap,\r\n      //     ResidualCapacityEdgeMap res_cap,\r\n      //     ReverseEdgeMap rev_map,\r\n      //     PredecessorMap pre_map,\r\n      //     ColorMap color,\r\n      //     DistanceMap dist,\r\n      //     IndexMap idx,\r\n      //     typename graph_traits<Graph>::vertex_descriptor src,\r\n      //     typename graph_traits<Graph>::vertex_descriptor sink)\r\n    double flow =\r\n        boykov_kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                   &color[0], indexmap, vSource, vSink);\r\n#else\r\n    double flow = kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                      &color[0], indexmap, vSource, vSink);\r\n#endif\r\n    std::cout << \"c  The total flow:\" << std::endl;\r\n    std::cout << \"s \" << flow << std::endl << std::endl;\r\n    t2 = clock();\r\n    std::cout << \"Flow computation time : \" << double(t2 - t1) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n\r\n    t1                = clock();\r\n    size_t pixelCount = imIn.getPixelCount();\r\n    for (off_t o1 = 0; o1 < (off_t) pixelCount; o1++) {\r\n      int val = (T) bufIn[o1];\r\n\r\n      if (val == 0) {\r\n        bufOut[o1] = 0;\r\n      } else {\r\n        if (color[val] == color[vSource])\r\n          bufOut[o1] = 2;\r\n        else if (color[val] == color[vSink])\r\n          bufOut[o1] = 3;\r\n        else\r\n          bufOut[o1] = 4;\r\n      }\r\n    }\r\n\r\n    t2 = clock();\r\n    std::cout << \"Computing imOut took : \" << double(t2 - t1) / CLOCKS_PER_SEC\r\n              << \" seconds\\n\";\r\n\r\n    return RES_OK;\r\n  }\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageGrad, class ImageMarker, class SE,\r\n            class ImageOut>\r\n  RES_T geoCutsMinSurfaces_with_Line(\r\n      const ImageIn &imIn, const ImageGrad &imGrad, const ImageMarker &imMarker,\r\n      const SE &nl, ImageOut &imOut)\r\n\r\n  }\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  // ImageLabel and ImageMarker should be unsigned integers\r\n  template <class ImageLabel, class ImageVal, class ImageMarker, class SE,\r\n            class ImageOut>\r\n  RES_T geoCutsMinSurfaces_with_steps(\r\n      const ImageLabel &imLabel, const ImageVal &imVal,\r\n      const ImageMarker &imMarker, const SE &nl, F_SIMPLE step_x,\r\n      F_SIMPLE step_y, F_SIMPLE step_z, ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  // ImageLabel and ImageMarker should be unsigned integers\r\n  template <class ImageLabel, class ImageVal, class ImageMarker, class SE,\r\n            class ImageOut>\r\n  RES_T geoCutsMinSurfaces_with_steps_vGradient(\r\n      const ImageLabel &imLabel, const ImageVal &imVal,\r\n      const ImageMarker &imMarker, const SE &nl, F_SIMPLE step_x,\r\n      F_SIMPLE step_y, F_SIMPLE step_z, ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageGrad, class ImageMarker, class SE,\r\n            class ImageOut>\r\n  RES_T geoCutsMinSurfaces_with_steps_old(\r\n      const ImageIn &imIn, const ImageGrad &imGrad, const ImageMarker &imMarker,\r\n      const SE &nl, F_SIMPLE step_x, F_SIMPLE step_y, F_SIMPLE step_z,\r\n      ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n  template <class T>\r\n  RES_T geoCutsMultiWay_MinSurfaces(const Image<T> &imIn,\r\n                                     const Image<T> &imGrad,\r\n                                     const Image<T> &imMarker, const StrElt &nl,\r\n                                     Image<T> &imOut)\r\n  {\r\n    SMIL_ENTER_FUNCTION(\"\");\r\n\r\n    ASSERT_ALLOCATED(&imIn, &imGrad, &imMarker, &imOut);\r\n    ASSERT_SAME_SIZE(&imIn, &imGrad, &imMarker, &imOut);\r\n\r\n    typename Image<T>::lineType bufIn     = imIn.getPixels();\r\n    typename Image<T>::lineType bufOut    = imOut.getPixels();\r\n    typename Image<T>::lineType bufMarker = imMarker.getPixels();\r\n    typename Image<T>::lineType bufGrad   = imGrad.getPixels();\r\n\r\n    std::cout << \"build Region Adjacency Graph\" << std::endl;\r\n\r\n    GraphLV_T g;\r\n    EdgeCapLV_T capacity = boost::get(boost::edge_capacity, g);\r\n    EdgeRevCapLV_T rev   = boost::get(boost::edge_reverse, g);\r\n    EdgeResCapLV_T residual_capacity =\r\n        boost::get(boost::edge_residual_capacity, g);\r\n\r\n    GraphLV_T::edge_descriptor e1, e2, e3, e4;\r\n    GraphLV_T::vertex_descriptor vSource, vSink;\r\n\r\n    int numVertex = maxVal(imIn);\r\n    int numLabels = maxVal(imMarker);\r\n\r\n    size_t pixelCount = imIn.getPixelCount();\r\n\r\n    std::cout << \"number of labels :\" << numLabels << std::endl;\r\n\r\n    std::cout << \"build Region Adjacency Graph Vertices\" << std::endl;\r\n\r\n    for (int i = 0; i <= numVertex; i++) {\r\n      boost::add_vertex(g);\r\n    }\r\n\r\n    vSource = boost::add_vertex(g);\r\n    vSink   = boost::add_vertex(g);\r\n\r\n    std::vector<boost::default_color_type> color(boost::num_vertices(g));\r\n    VertexIndexLV_T indexmap = boost::get(boost::vertex_index, g);\r\n\r\n    std::cout << \"build Region Adjacency Graph Edges\" << std::endl;\r\n\r\n    int width  = imIn.getWidth();\r\n    int height = imIn.getHeight();\r\n    int depth  = imIn.getDepth();\r\n\r\n    off_t strideY = width;\r\n    off_t strideZ = width * height;\r\n    for (int z = 0; z < depth; z++) {\r\n      off_t p0Z = z * strideZ;\r\n      for (int y = 0; y < height; y++) {\r\n        off_t p0Y = y * strideY;\r\n        for (int x = 0; x < width; x++) {\r\n          off_t o1 = p0Z + p0Y + x;\r\n          int val1 = (int) bufIn[o1];\r\n          // int marker = (int) bufMarker[o1]; // XXX unused ???\r\n\r\n          // iterators on the Structuring Element\r\n          vector<IntPoint> pts = filterStrElt(nl);\r\n          vector<IntPoint>::iterator itBegin, itEnd, it;\r\n          itBegin = pts.begin();\r\n          itEnd   = pts.end();\r\n\r\n          for (it = itBegin; it != itEnd; it++) {\r\n            if (x + it->x > width - 1 || x + it->x < 0)\r\n              continue;\r\n            if (y + it->y > height - 1 || y + it->y < 0)\r\n              continue;\r\n            if (z + it->z > depth - 1 || z + it->z < 0)\r\n              continue;\r\n\r\n            off_t o2 = o1 + it->z * strideZ + it->y * strideY + it->x;\r\n            if (o2 <= o1)\r\n              continue;\r\n\r\n            int val2 = bufIn[o2];\r\n            if (val1 == val2)\r\n              continue;\r\n\r\n            bool hasEdge;\r\n            boost::tie(e3, hasEdge) = boost::edge(val1, val2, g);\r\n            // std::cout<<hasEdge<<std::endl;\r\n            // std::cout<<\"Compute Gradient\"<<std::endl;\r\n            double val3 = (double) bufGrad[o1];\r\n            double val4 = (double) bufGrad[o2];\r\n            double maxi = std::max(val3, val4);\r\n            double cost = 10000.0 / (1.0 + std::pow(maxi, 4));\r\n\r\n            if (!hasEdge) {\r\n              // std::cout<<\"Add new edge\"<<std::endl;\r\n              boost::tie(e4, hasEdge) = boost::add_edge(val1, val2, g);\r\n              boost::tie(e3, hasEdge) = boost::add_edge(val2, val1, g);\r\n              capacity[e4]            = cost;\r\n              capacity[e3]            = cost;\r\n              rev[e4]                 = e3;\r\n              rev[e3]                 = e4;\r\n            } else {\r\n              // std::cout<<\"existing edge\"<<std::endl;\r\n              boost::tie(e4, hasEdge) = boost::edge(val1, val2, g);\r\n              boost::tie(e3, hasEdge) = boost::edge(val2, val1, g);\r\n              capacity[e4]            = capacity[e4] + cost;\r\n              capacity[e3]            = capacity[e3] + cost;\r\n            }\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    for (int nbk = 2; nbk <= numLabels; nbk++) {\r\n      // for all pixels in imIn create a vertex\r\n      for (off_t o0 = 0; o0 < (off_t) pixelCount; o0++) {\r\n        int val1 = (int) bufMarker[o0];\r\n        int val2 = (int) bufIn[o0];\r\n\r\n        bool hasEdge;\r\n        if (val1 == nbk) {\r\n          boost::tie(e4, hasEdge) = boost::edge(vSource, val2, g);\r\n          if (!hasEdge) {\r\n            boost::tie(e4, hasEdge) = boost::add_edge(vSource, val2, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(val2, vSource, g);\r\n            capacity[e4]            = (std::numeric_limits<double>::max)();\r\n            capacity[e3]            = (std::numeric_limits<double>::max)();\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          }\r\n        } else if (val1 > 1 && val1 != nbk) {\r\n          boost::tie(e4, hasEdge) = boost::edge(val2, vSink, g);\r\n          if (!hasEdge) {\r\n            boost::tie(e4, hasEdge) = boost::add_edge(val2, vSink, g);\r\n            boost::tie(e3, hasEdge) = boost::add_edge(vSink, val2, g);\r\n            capacity[e4]            = (std::numeric_limits<double>::max)();\r\n            capacity[e3]            = (std::numeric_limits<double>::max)();\r\n            rev[e4]                 = e3;\r\n            rev[e3]                 = e4;\r\n          }\r\n        }\r\n      }\r\n\r\n      std::cout << \"Compute Max flow\" << nbk << std::endl;\r\n#if BOOST_VERSION >= 104700\r\n      // XXX - JOE - Check against this function prototype :\r\n      // boykov_kolmogorov_max_flow(\r\n      //     Graph& g,\r\n      //     CapacityEdgeMap cap,\r\n      //     ResidualCapacityEdgeMap res_cap,\r\n      //     ReverseEdgeMap rev_map,\r\n      //     PredecessorMap pre_map,\r\n      //     ColorMap color,\r\n      //     DistanceMap dist,\r\n      //     IndexMap idx,\r\n      //     typename graph_traits<Graph>::vertex_descriptor src,\r\n      //     typename graph_traits<Graph>::vertex_descriptor sink)\r\n      double flow =\r\n          boykov_kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                     &color[0], indexmap, vSource, vSink);\r\n#else\r\n      double flow = kolmogorov_max_flow(g, capacity, residual_capacity, rev,\r\n                                        &color[0], indexmap, vSource, vSink);\r\n#endif\r\n\r\n      std::cout << \"c  The total flow:\" << std::endl;\r\n      std::cout << \"s \" << flow << std::endl << std::endl;\r\n\r\n      // for all pixels in imIn create a vertex and an edge\r\n      for (off_t o1 = 0; o1 < (off_t) pixelCount; o1++) {\r\n        int val1 = (int) bufIn[o1];\r\n        int val2 = (int) bufOut[o1];\r\n        int val3 = (int) bufMarker[o1];\r\n\r\n        if (val2 == 1) {\r\n          if (color[val1] == color[vSource])\r\n            bufOut[o1] = (T) nbk;\r\n        }\r\n\r\n        bool hasEdge;\r\n        if (val3 == nbk) {\r\n          boost::tie(e4, hasEdge) = boost::edge(vSource, val1, g);\r\n          if (hasEdge) {\r\n            boost::remove_edge(vSource, val1, g);\r\n            boost::remove_edge(val1, vSource, g);\r\n          }\r\n        } else if (val3 > 1) {\r\n          boost::tie(e4, hasEdge) = boost::edge(val1, vSink, g);\r\n          if (hasEdge) {\r\n            boost::remove_edge(val1, vSink, g);\r\n            boost::remove_edge(vSink, val1, g);\r\n          }\r\n        }\r\n      }\r\n    }\r\n\r\n    return RES_OK;\r\n  }\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageGrad, class ImageMosaic,\r\n            class ImageMarker, class SE, class ImageOut>\r\n  RES_T geoCutsOptimize_Mosaic(\r\n      const ImageIn &imIn, const ImageGrad &imGrad, const ImageMosaic &imMosaic,\r\n      const ImageMarker &imMarker, const SE &nl, ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageGrad, class ImageCurvature,\r\n            class ImageMarker, typename _Beta, class SE, class ImageOut>\r\n  RES_T geoCutsRegularized_MinSurfaces(\r\n      const ImageIn &imIn, const ImageGrad &imGrad,\r\n      const ImageCurvature &imCurvature, const ImageMarker &imMarker,\r\n      const _Beta Beta, const SE &nl, ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageMosaic, class ImageMarker, class SE,\r\n            class ImageOut>\r\n  RES_T geoCutsSegment_Graph(const ImageIn &imIn, const ImageMosaic &imMosaic,\r\n                              const ImageMarker &imMarker, const SE &nl,\r\n                              ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageMosaic, class ImageMarker, typename _Beta,\r\n            typename _Sigma, class SE, class ImageOut>\r\n  RES_T MAP_MRF_edge_preserving(\r\n      const ImageIn &imIn, const ImageMosaic &imMosaic,\r\n      const ImageMarker &imMarker, const _Beta Beta, const _Sigma Sigma,\r\n      const SE &nl, ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageMosaic, class ImageMarker, typename _Beta,\r\n            typename _Sigma, class SE, class ImageOut>\r\n  RES_T MAP_MRF_Ising(const ImageIn &imIn, const ImageMosaic &imMosaic,\r\n                      const ImageMarker &imMarker, const _Beta Beta,\r\n                      const _Sigma Sigma, const SE &nl, ImageOut &imOut)\r\n#endif\r\n\r\n  /*\r\n   *\r\n   *\r\n   *\r\n   *\r\n   */\r\n#if 0\r\n  template <class ImageIn, class ImageMosaic, class ImageMarker, typename _Beta,\r\n            typename _Sigma, class SE, class ImageOut>\r\n  RES_T MAP_MRF_Potts(const ImageIn &imIn, const ImageMosaic &imMosaic,\r\n                      const ImageMarker &imMarker, const _Beta Beta,\r\n                      const _Sigma Sigma, const SE &nl, ImageOut &imOut)\r\n#endif\r\n\r\n/*\r\n *\r\n *\r\n *\r\n *\r\n */\r\n#define indent \"   \"\r\n\r\n  inline void printSE(StrElt ss)\r\n  {\r\n    cout << indent << \"Structuring Element\" << endl;\r\n    cout << indent << \"Type: \" << ss.seT << endl;\r\n    cout << indent << \"Size: \" << ss.size << endl;\r\n    size_t ptNbr = ss.points.size();\r\n    cout << indent << \"Point Nbr: \" << ptNbr << endl;\r\n    if (ptNbr == 0)\r\n      return;\r\n\r\n    vector<IntPoint>::iterator itStart = ss.points.begin();\r\n    vector<IntPoint>::iterator it, itEnd;\r\n    itEnd = ss.points.end();\r\n\r\n    vector<IntPoint> z(0);\r\n    z       = filterStrElt(ss);\r\n    itStart = z.begin();\r\n    itEnd   = z.end();\r\n    for (it = itStart; it != itEnd; it++) {\r\n      // cout << \"z      \" << \"* \" << it->x << \" \" << it->y << \" \" << it->z <<\r\n      // endl;\r\n    }\r\n    cout << \" =================== \" << endl;\r\n  }\r\n\r\n  template <class T> void testHandleSE(const Image<T> &img, StrElt se)\r\n  {\r\n    StrElt sx = se;\r\n    // sx = CubeSE(2);\r\n    printSE(sx);\r\n    sx = sx.noCenter();\r\n    printSE(sx);\r\n    int sz = sx.getSize();\r\n    sx     = sx.homothety(sz);\r\n    printSE(sx);\r\n\r\n#if 1\r\n    img.printSelf();\r\n    cout << \"* width \" << img.getWidth() << endl;\r\n    cout << \"* height \" << img.getHeight() << endl;\r\n    cout << \"* depth \" << img.getDepth() << endl;\r\n#endif\r\n  }\r\n\r\n} // namespace smil\r\n\r\n#endif // D_MOSAIC_GEOCUTS_IMPL_HPP\r\n", "meta": {"hexsha": "bd04598b145654911ef50e3aca6d3eba203fbc14", "size": 25636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Addons/GraphCuts/include/private/MosaicGeoCuts/Mosaic_GeoCuts.hpp", "max_stars_repo_name": "basileMarchand/smil", "max_stars_repo_head_hexsha": "84e4825e813b6cdd757290ff769e7bcc43d2ac08", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T12:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T08:33:52.000Z", "max_issues_repo_path": "Addons/GraphCuts/include/private/MosaicGeoCuts/Mosaic_GeoCuts.hpp", "max_issues_repo_name": "basileMarchand/smil", "max_issues_repo_head_hexsha": "84e4825e813b6cdd757290ff769e7bcc43d2ac08", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/GraphCuts/include/private/MosaicGeoCuts/Mosaic_GeoCuts.hpp", "max_forks_repo_name": "basileMarchand/smil", "max_forks_repo_head_hexsha": "84e4825e813b6cdd757290ff769e7bcc43d2ac08", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-19T07:45:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T07:59:12.000Z", "avg_line_length": 33.5111111111, "max_line_length": 82, "alphanum_fraction": 0.519698861, "num_tokens": 6824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.04272220089826196, "lm_q1q2_score": 0.019034002931124897}}
{"text": "//=======================================================================\r\n// Copyright 2002 Indiana University.\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\r\n#ifndef BOOST_GRAPH_DAG_SHORTEST_PATHS_HPP\r\n#define BOOST_GRAPH_DAG_SHORTEST_PATHS_HPP\r\n\r\n#include <boost/graph/topological_sort.hpp>\r\n#include <boost/graph/dijkstra_shortest_paths.hpp>\r\n\r\n// single-source shortest paths for a Directed Acyclic Graph (DAG)\r\n\r\nnamespace boost\r\n{\r\n\r\n// Initalize distances and call depth first search\r\ntemplate < class VertexListGraph, class DijkstraVisitor, class DistanceMap,\r\n    class WeightMap, class ColorMap, class PredecessorMap, class Compare,\r\n    class Combine, class DistInf, class DistZero >\r\ninline void dag_shortest_paths(const VertexListGraph& g,\r\n    typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n    DistanceMap distance, WeightMap weight, ColorMap color, PredecessorMap pred,\r\n    DijkstraVisitor vis, Compare compare, Combine combine, DistInf inf,\r\n    DistZero zero)\r\n{\r\n    typedef typename graph_traits< VertexListGraph >::vertex_descriptor Vertex;\r\n    std::vector< Vertex > rev_topo_order;\r\n    rev_topo_order.reserve(num_vertices(g));\r\n\r\n    // Call 'depth_first_visit', not 'topological_sort', because we don't\r\n    // want to traverse the entire graph, only vertices reachable from 's',\r\n    // and 'topological_sort' will traverse everything. The logic below\r\n    // is the same as for 'topological_sort', only we call 'depth_first_visit'\r\n    // and 'topological_sort' calls 'depth_first_search'.\r\n    topo_sort_visitor< std::back_insert_iterator< std::vector< Vertex > > >\r\n        topo_visitor(std::back_inserter(rev_topo_order));\r\n    depth_first_visit(g, s, topo_visitor, color);\r\n\r\n    typename graph_traits< VertexListGraph >::vertex_iterator ui, ui_end;\r\n    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)\r\n    {\r\n        put(distance, *ui, inf);\r\n        put(pred, *ui, *ui);\r\n    }\r\n\r\n    put(distance, s, zero);\r\n    vis.discover_vertex(s, g);\r\n    typename std::vector< Vertex >::reverse_iterator i;\r\n    for (i = rev_topo_order.rbegin(); i != rev_topo_order.rend(); ++i)\r\n    {\r\n        Vertex u = *i;\r\n        vis.examine_vertex(u, g);\r\n        typename graph_traits< VertexListGraph >::out_edge_iterator e, e_end;\r\n        for (boost::tie(e, e_end) = out_edges(u, g); e != e_end; ++e)\r\n        {\r\n            vis.discover_vertex(target(*e, g), g);\r\n            bool decreased\r\n                = relax(*e, g, weight, pred, distance, combine, compare);\r\n            if (decreased)\r\n                vis.edge_relaxed(*e, g);\r\n            else\r\n                vis.edge_not_relaxed(*e, g);\r\n        }\r\n        vis.finish_vertex(u, g);\r\n    }\r\n}\r\n\r\nnamespace detail\r\n{\r\n\r\n    // Defaults are the same as Dijkstra's algorithm\r\n\r\n    // Handle Distance Compare, Combine, Inf and Zero defaults\r\n    template < class VertexListGraph, class DijkstraVisitor, class DistanceMap,\r\n        class WeightMap, class ColorMap, class IndexMap, class Params >\r\n    inline void dag_sp_dispatch2(const VertexListGraph& g,\r\n        typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n        DistanceMap distance, WeightMap weight, ColorMap color, IndexMap /*id*/,\r\n        DijkstraVisitor vis, const Params& params)\r\n    {\r\n        typedef typename property_traits< DistanceMap >::value_type D;\r\n        dummy_property_map p_map;\r\n        D inf = choose_param(get_param(params, distance_inf_t()),\r\n            (std::numeric_limits< D >::max)());\r\n        dag_shortest_paths(g, s, distance, weight, color,\r\n            choose_param(get_param(params, vertex_predecessor), p_map), vis,\r\n            choose_param(\r\n                get_param(params, distance_compare_t()), std::less< D >()),\r\n            choose_param(\r\n                get_param(params, distance_combine_t()), closed_plus< D >(inf)),\r\n            inf, choose_param(get_param(params, distance_zero_t()), D()));\r\n    }\r\n\r\n    // Handle DistanceMap and ColorMap defaults\r\n    template < class VertexListGraph, class DijkstraVisitor, class DistanceMap,\r\n        class WeightMap, class ColorMap, class IndexMap, class Params >\r\n    inline void dag_sp_dispatch1(const VertexListGraph& g,\r\n        typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n        DistanceMap distance, WeightMap weight, ColorMap color, IndexMap id,\r\n        DijkstraVisitor vis, const Params& params)\r\n    {\r\n        typedef typename property_traits< WeightMap >::value_type T;\r\n        typename std::vector< T >::size_type n;\r\n        n = is_default_param(distance) ? num_vertices(g) : 1;\r\n        std::vector< T > distance_map(n);\r\n        n = is_default_param(color) ? num_vertices(g) : 1;\r\n        std::vector< default_color_type > color_map(n);\r\n\r\n        dag_sp_dispatch2(g, s,\r\n            choose_param(distance,\r\n                make_iterator_property_map(\r\n                    distance_map.begin(), id, distance_map[0])),\r\n            weight,\r\n            choose_param(color,\r\n                make_iterator_property_map(\r\n                    color_map.begin(), id, color_map[0])),\r\n            id, vis, params);\r\n    }\r\n\r\n} // namespace detail\r\n\r\ntemplate < class VertexListGraph, class Param, class Tag, class Rest >\r\ninline void dag_shortest_paths(const VertexListGraph& g,\r\n    typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n    const bgl_named_params< Param, Tag, Rest >& params)\r\n{\r\n    // assert that the graph is directed...\r\n    null_visitor null_vis;\r\n    detail::dag_sp_dispatch1(g, s, get_param(params, vertex_distance),\r\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\r\n        get_param(params, vertex_color),\r\n        choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n        choose_param(\r\n            get_param(params, graph_visitor), make_dijkstra_visitor(null_vis)),\r\n        params);\r\n}\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_DAG_SHORTEST_PATHS_HPP\r\n", "meta": {"hexsha": "b99cd3fdffa061d0376adda38226c51159c4813b", "size": 6209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/dag_shortest_paths.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/dag_shortest_paths.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/dag_shortest_paths.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": 42.5273972603, "max_line_length": 81, "alphanum_fraction": 0.6443871799, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.042722194347072646, "lm_q1q2_score": 0.019033999383321537}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstdlib>\n#include <iterator>\n#include <limits>\n#include <memory>\n#include <pup.h>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tags.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/OrientationMap.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodType.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/Literals.hpp\"\n#include \"Utilities/Numeric.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace Limiters::Minmod_detail {\n\n// This function combines the evaluation of the troubled-cell indicator with the\n// computation of the post-limiter reduced slopes. The returned bool indicates\n// whether the slopes are to be reduced. The slopes themselves are returned by\n// pointer.\n//\n// Note: This function is only made available in this header file to facilitate\n// testing.\ntemplate <size_t VolumeDim>\nbool minmod_limited_slopes(\n    gsl::not_null<DataVector*> u_lin_buffer,\n    gsl::not_null<BufferWrapper<VolumeDim>*> buffer,\n    gsl::not_null<double*> u_mean,\n    gsl::not_null<std::array<double, VolumeDim>*> u_limited_slopes,\n    Limiters::MinmodType minmod_type, double tvb_constant, const DataVector& u,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const DirectionMap<VolumeDim, double>& effective_neighbor_means,\n    const DirectionMap<VolumeDim, double>& effective_neighbor_sizes) noexcept;\n\n// Implements the minmod limiter for one Tensor<DataVector> at a time.\ntemplate <size_t VolumeDim, typename Tag, typename PackagedData>\nbool minmod_impl(\n    const gsl::not_null<DataVector*> u_lin_buffer,\n    const gsl::not_null<BufferWrapper<VolumeDim>*> buffer,\n    const gsl::not_null<typename Tag::type*> tensor,\n    const Limiters::MinmodType minmod_type, const double tvb_constant,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const tnsr::I<DataVector, VolumeDim, Frame::Logical>& logical_coords,\n    const std::array<double, VolumeDim>& element_size,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) noexcept {\n  // True if the mesh is linear-order in every direction\n  const bool mesh_is_linear = (mesh.extents() == Index<VolumeDim>(2));\n  const bool minmod_type_is_linear =\n      (minmod_type != Limiters::MinmodType::LambdaPiN);\n  const bool using_linear_limiter_on_non_linear_mesh =\n      minmod_type_is_linear and not mesh_is_linear;\n\n  // In each direction, average the size of all different neighbors in that\n  // direction. Note that only the component of neighor_size that is normal\n  // to the face is needed (and, therefore, computed). Note that this average\n  // does not depend on the solution on the neighboring elements, so could be\n  // precomputed outside of `limit_one_tensor`. Changing the code to\n  // precompute the average may or may not be a measurable optimization.\n  const auto effective_neighbor_sizes =\n      compute_effective_neighbor_sizes(element, neighbor_data);\n\n  bool some_component_was_limited = false;\n  for (size_t i = 0; i < tensor->size(); ++i) {\n    // In each direction, average the mean of the i'th tensor component over\n    // all different neighbors in that direction. This produces one effective\n    // neighbor per direction.\n    const auto effective_neighbor_means =\n        compute_effective_neighbor_means<Tag>(i, element, neighbor_data);\n\n    DataVector& u = (*tensor)[i];\n    double u_mean = std::numeric_limits<double>::signaling_NaN();\n    std::array<double, VolumeDim> u_limited_slopes{};\n    const bool reduce_slopes = minmod_limited_slopes(\n        u_lin_buffer, buffer, make_not_null(&u_mean),\n        make_not_null(&u_limited_slopes), minmod_type, tvb_constant, u, mesh,\n        element, element_size, effective_neighbor_means,\n        effective_neighbor_sizes);\n\n    if (reduce_slopes or using_linear_limiter_on_non_linear_mesh) {\n      u = u_mean;\n      for (size_t d = 0; d < VolumeDim; ++d) {\n        u += logical_coords.get(d) * gsl::at(u_limited_slopes, d);\n      }\n      some_component_was_limited = true;\n    }\n  }  // end for loop over tensor components\n\n  return some_component_was_limited;\n}\n\n}  // namespace Limiters::Minmod_detail\n", "meta": {"hexsha": "8ac169b9f1967cf9842b552ebd8fe3a7a7e6314c", "size": 4941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/MinmodImpl.hpp", "max_stars_repo_name": "trami18/spectre", "max_stars_repo_head_hexsha": "6b1f6497bf2e26d1474bfadf143b3321942c40b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-11T04:07:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T05:07:54.000Z", "max_issues_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/MinmodImpl.hpp", "max_issues_repo_name": "trami18/spectre", "max_issues_repo_head_hexsha": "6b1f6497bf2e26d1474bfadf143b3321942c40b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/MinmodImpl.hpp", "max_forks_repo_name": "trami18/spectre", "max_forks_repo_head_hexsha": "6b1f6497bf2e26d1474bfadf143b3321942c40b4", "max_forks_repo_licenses": ["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.5948275862, "max_line_length": 80, "alphanum_fraction": 0.752276867, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.040237941904283876, "lm_q1q2_score": 0.019019810271367902}}
{"text": "// Copyright (c) 2008-2016 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 UUID_47B1D1217B411E08424FA0ADFD72085\n#define UUID_47B1D1217B411E08424FA0ADFD72085\n\n#include <boost/qvm/enable_if.hpp>\n#include <boost/qvm/inline.hpp>\n#include <boost/qvm/mat_traits.hpp>\n#include <boost/qvm/static_assert.hpp>\n\nnamespace boost {\nnamespace qvm {\n////////////////////////////////////////////////\n\ntemplate <int R, int C, class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A(M const &a) {\n  BOOST_STATIC_ASSERT(R >= 0);\n  BOOST_STATIC_ASSERT(R < mat_traits<M>::rows);\n  BOOST_STATIC_ASSERT(C >= 0);\n  BOOST_STATIC_ASSERT(C < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<R, C>(a);\n}\n\ntemplate <int R, int C, class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A(M &a) {\n  BOOST_STATIC_ASSERT(R >= 0);\n  BOOST_STATIC_ASSERT(R < mat_traits<M>::rows);\n  BOOST_STATIC_ASSERT(C >= 0);\n  BOOST_STATIC_ASSERT(C < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<R, C>(a);\n}\n\n////////////////////////////////////////////////\n\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A00(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A01(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A02(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A03(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A04(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A05(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A06(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A07(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A08(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A09(M const &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<0, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A10(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A11(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A12(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A13(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A14(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A15(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A16(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A17(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A18(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A19(M const &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<1, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A20(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A21(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A22(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A23(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A24(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A25(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A26(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A27(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A28(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A29(M const &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<2, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A30(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A31(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A32(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A33(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A34(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A35(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A36(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A37(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A38(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A39(M const &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<3, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A40(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A41(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A42(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A43(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A44(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A45(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A46(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A47(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A48(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A49(M const &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<4, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A50(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A51(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A52(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A53(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A54(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A55(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A56(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A57(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A58(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A59(M const &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<5, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A60(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A61(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A62(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A63(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A64(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A65(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A66(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A67(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A68(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A69(M const &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<6, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A70(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A71(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A72(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A73(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A74(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A75(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A76(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A77(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A78(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A79(M const &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<7, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A80(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A81(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A82(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A83(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A84(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A85(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A86(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A87(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A88(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A89(M const &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<8, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A90(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A91(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A92(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A93(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A94(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A95(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A96(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A97(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A98(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type>::type\n    A99(M const &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template read_element<9, 9>(a);\n}\n\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A00(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A01(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A02(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A03(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A04(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A05(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A06(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A07(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A08(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A09(M &a) {\n  BOOST_STATIC_ASSERT(0 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<0, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A10(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A11(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A12(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A13(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A14(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A15(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A16(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A17(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A18(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A19(M &a) {\n  BOOST_STATIC_ASSERT(1 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<1, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A20(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A21(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A22(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A23(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A24(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A25(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A26(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A27(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A28(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A29(M &a) {\n  BOOST_STATIC_ASSERT(2 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<2, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A30(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A31(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A32(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A33(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A34(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A35(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A36(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A37(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A38(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A39(M &a) {\n  BOOST_STATIC_ASSERT(3 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<3, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A40(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A41(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A42(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A43(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A44(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A45(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A46(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A47(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A48(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A49(M &a) {\n  BOOST_STATIC_ASSERT(4 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<4, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A50(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A51(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A52(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A53(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A54(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A55(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A56(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A57(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A58(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A59(M &a) {\n  BOOST_STATIC_ASSERT(5 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<5, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A60(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A61(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A62(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A63(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A64(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A65(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A66(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A67(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A68(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A69(M &a) {\n  BOOST_STATIC_ASSERT(6 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<6, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A70(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A71(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A72(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A73(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A74(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A75(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A76(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A77(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A78(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A79(M &a) {\n  BOOST_STATIC_ASSERT(7 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<7, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A80(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A81(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A82(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A83(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A84(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A85(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A86(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A87(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A88(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A89(M &a) {\n  BOOST_STATIC_ASSERT(8 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<8, 9>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A90(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 0 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 0>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A91(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 1 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 1>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A92(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 2 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 2>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A93(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 3 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 3>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A94(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 4 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 4>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A95(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 5 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 5>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A96(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 6 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 6>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A97(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 7 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 7>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A98(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 8 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 8>(a);\n}\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_mat<M>::value,\n                         typename mat_traits<M>::scalar_type &>::type\n    A99(M &a) {\n  BOOST_STATIC_ASSERT(9 < mat_traits<M>::rows && 9 < mat_traits<M>::cols);\n  return mat_traits<M>::template write_element<9, 9>(a);\n}\n\n////////////////////////////////////////////////\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "62c305e5a20c1fa8fd71ed4478f816e2e827408f", "size": 63200, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/mat_access.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/mat_access.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/mat_access.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": 38.2798304058, "max_line_length": 79, "alphanum_fraction": 0.654414557, "num_tokens": 17385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.04023794060948605, "lm_q1q2_score": 0.019019809659338367}}
{"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) 2004, 2005, 2006 Ferdinando Ametrano\n Copyright (C) 2006 Katiuscia Manzoni\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/time/imm.hpp>\n#include \"ql_settings.hpp\"\n#include \"ql_utilities_dataparsers.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/algorithm/string/case_conv.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n//using boost::algorithm::to_upper_copy;\n//using std::string;\n\nnamespace QuantLib {\n    template <class ExtDate> inline\n    bool IMM<ExtDate>::isIMMdate(const ExtDate& dat, bool mainCycle) {\n        auto date = to_DateLike(dat);\n        auto s = date.serialNumber();\n        if (date.weekday(s)!=Wednesday)\n            return false;\n\n        Day d = date.dayOfMonth(s);\n        if (d<15 || d>21)\n            return false;\n\n        if (!mainCycle) return true;\n\n        switch (date.month(s)) {\n          case March:\n          case June:\n          case September:\n          case December:\n            return true;\n          default:\n            return false;\n        }\n    }\n    template <class ExtDate>    inline\n    bool IMM<ExtDate>::isIMMcode(const std::string& in, bool mainCycle) {\n        if (in.length() != 2)\n            return false;\n\n        std::string str1(\"0123456789\");\n        std::string::size_type loc = str1.find(in.substr(1,1), 0);\n        if (loc == std::string::npos)\n            return false;\n\n        if (mainCycle) str1 = \"hmzuHMZU\";\n        else           str1 = \"fghjkmnquvxzFGHJKMNQUVXZ\";\n        loc = str1.find(in.substr(0,1), 0);\n        return loc != std::string::npos;\n    }\n    template <class ExtDate>    inline\n    std::string IMM<ExtDate>::code(const ExtDate& date) {\n        QL_REQUIRE(isIMMdate(date, false),\n                   \"{} is not an IMM date\",date);\n\n        std::ostringstream IMMcode;\n        auto d = to_DateLike(date);\n        auto s = d.serialNumber();\n        unsigned int y = d.year(s) % 10;\n        switch(d.month(s)) {\n          case January:\n            IMMcode << 'F' << y;\n            break;\n          case February:\n            IMMcode << 'G' << y;\n            break;\n          case March:\n            IMMcode << 'H' << y;\n            break;\n          case April:\n            IMMcode << 'J' << y;\n            break;\n          case May:\n            IMMcode << 'K' << y;\n            break;\n          case June:\n            IMMcode << 'M' << y;\n            break;\n          case July:\n            IMMcode << 'N' << y;\n            break;\n          case August:\n            IMMcode << 'Q' << y;\n            break;\n          case September:\n            IMMcode << 'U' << y;\n            break;\n          case October:\n            IMMcode << 'V' << y;\n            break;\n          case November:\n            IMMcode << 'X' << y;\n            break;\n          case December:\n            IMMcode << 'Z' << y;\n            break;\n          default:\n            QL_FAIL(\"not an IMM month (and it should have been)\");\n        }\n\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_ENSURE(isIMMcode(IMMcode.str(), false),\n                  \"the result {} is an invalid IMM code\",IMMcode.str());\n        #endif\n        return IMMcode.str();\n    }\n    template <class ExtDate>    inline\n    ExtDate IMM<ExtDate>::date(const std::string& immCode, const ExtDate& refDate) {\n        QL_REQUIRE(isIMMcode(immCode, false), \"{} is not a valid IMM code\"\n            , immCode);\n\n        DateLike<ExtDate> referenceDate{\n            to_DateLike(refDate) != ExtDate() ?\n                to_DateLike(refDate) :\n                DateLike<ExtDate>{Settings<ExtDate>::instance().evaluationDate()}};\n        auto to_upper_copy = [](const std::string& s) { std::string res; for (auto i:s) res.push_back(std::toupper(i)); return res;};\n        std::string code = to_upper_copy(immCode);\n        std::string ms = code.substr(0,1);\n        QuantLib::Month m;\n        if (ms==\"F\")      m = January;\n        else if (ms==\"G\") m = February;\n        else if (ms==\"H\") m = March;\n        else if (ms==\"J\") m = April;\n        else if (ms==\"K\") m = May;\n        else if (ms==\"M\") m = June;\n        else if (ms==\"N\") m = July;\n        else if (ms==\"Q\") m = August;\n        else if (ms==\"U\") m = September;\n        else if (ms==\"V\") m = October;\n        else if (ms==\"X\") m = November;\n        else if (ms==\"Z\") m = December;\n        else QL_FAIL(\"invalid IMM month letter\");\n\n//        Year y = boost::lexical_cast<Year>(); // lexical_cast causes compilation errors with x64\n\n        Year y= io::to_integer(code.substr(1,1));\n        /* year<1900 are not valid QuantLib years: to avoid a run-time\n           exception few lines below we need to add 10 years right away */\n        auto s = referenceDate.serialNumber();\n        if (y==0 && referenceDate.year(s)<=1909) y+=10;\n        Year referenceYear = (referenceDate.year(s) % 10);\n        y += referenceDate.year(s) - referenceYear;\n        ExtDate result = IMM<ExtDate>::nextDate(DateAdaptor<ExtDate>::Date(1, m, y), false);\n        if (result<referenceDate)\n            return IMM<ExtDate>::nextDate(DateAdaptor<ExtDate>::Date(1, m, y + 10), false);\n\n        return result;\n    }\n    template <class ExtDate>    inline\n    ExtDate IMM<ExtDate>::nextDate(const ExtDate& date, bool mainCycle) {\n        DateLike<ExtDate> refDate{(to_DateLike(date) == ExtDate() ?\n                                       ExtDate(Settings<ExtDate>::instance().evaluationDate()) :\n                                       date)};\n        auto s = refDate.serialNumber();\n        Year y = refDate.year(s);\n        QuantLib::Month m = refDate.month(s);\n\n        Size offset = mainCycle ? 3 : 1;\n        Size skipMonths = offset-(m%offset);\n        if (skipMonths != offset || refDate.dayOfMonth(s) > 21) {\n            skipMonths += Size(m);\n            if (skipMonths<=12) {\n                m = QuantLib::Month(skipMonths);\n            } else {\n                m = QuantLib::Month(skipMonths-12);\n                y += 1;\n            }\n        }\n\n        ExtDate result = DateLike<ExtDate>::nthWeekday(3, Wednesday, m, y);\n        if (result<=refDate)\n            result = nextDate(DateAdaptor<ExtDate>::Date(22, m, y), mainCycle);\n        return result;\n    }\n    template <class ExtDate>    inline\n    ExtDate IMM<ExtDate>::nextDate(const std::string& IMMcode,\n                       bool mainCycle,\n                       const ExtDate& referenceDate)  {\n        ExtDate immDate = date(IMMcode, referenceDate);\n        return nextDate(immDate+1, mainCycle);\n    }\n    template <class ExtDate>    inline\n    std::string IMM<ExtDate>::nextCode(const ExtDate& d,\n                              bool mainCycle) {\n        ExtDate date = nextDate(d, mainCycle);\n        return code(date);\n    }\n    template <class ExtDate>    inline\n    std::string IMM<ExtDate>::nextCode(const std::string& immCode,\n                              bool mainCycle,\n                              const ExtDate& referenceDate) {\n        ExtDate date = nextDate(immCode, mainCycle, referenceDate);\n        return code(date);\n    }\n\n}\n", "meta": {"hexsha": "5553cda4aeeb0e7cf15880411de86425ebd9f0fc", "size": 8069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/time/imm.cpp", "max_stars_repo_name": "reder2000/QuantLib", "max_stars_repo_head_hexsha": "1d58c3859a0872722aa570283c6571aeb64f6f39", "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/time/imm.cpp", "max_issues_repo_name": "reder2000/QuantLib", "max_issues_repo_head_hexsha": "1d58c3859a0872722aa570283c6571aeb64f6f39", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T06:52:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:41:08.000Z", "max_forks_repo_path": "ql/time/imm.cpp", "max_forks_repo_name": "reder2000/QuantLib", "max_forks_repo_head_hexsha": "1d58c3859a0872722aa570283c6571aeb64f6f39", "max_forks_repo_licenses": ["BSD-3-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.1838565022, "max_line_length": 133, "alphanum_fraction": 0.5557070269, "num_tokens": 2052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.053403325280175794, "lm_q1q2_score": 0.018999563094388872}}
{"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @file geometry_core.hpp\n * @author Ondrej Prochazka <ondrej.prochazka@citationtech.net>\n * @author Vaclav Blazek <vaclav.blazek@citationtech.net>\n *\n * Basic structures for geometric modeling\n */\n\n#ifndef MATH_GEOMETRY_CORE_HPP\n#define MATH_GEOMETRY_CORE_HPP\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/qi_match.hpp>\n#include <boost/spirit/include/qi_match_auto.hpp>\n#include <boost/spirit/include/qi_alternative.hpp>\n\n#include <boost/rational.hpp>\n\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <stdexcept>\n#include <limits>\n\n#ifdef MATH_HAS_OPENCV\n#include <opencv2/core/core.hpp>\n#endif\n\n#include \"utility/streams.hpp\"\n\nnamespace math {\n\nnamespace ublas = boost::numeric::ublas;\n\nstruct GeometryError : std::runtime_error {\n    GeometryError(const std::string &msg) : std::runtime_error(msg) {}\n};\n\nstruct NoIntersectError : GeometryError {\n    NoIntersectError(const std::string &msg) : GeometryError(msg) {}\n};\n\n/* sizes */\n\ntemplate <class T>\nstruct Size2_ {\n    typedef T value_type;\n\n    Size2_() : width( 0 ), height( 0 ) {};\n\n    Size2_( const T & width, const T & height )\n        : width( width ), height( height ) {};\n\n    T width, height;\n\n    template <typename U>\n    explicit Size2_(const Size2_<U> &s)\n        : width(s.width), height(s.height)\n    {}\n\n    template <typename U>\n    explicit Size2_(const Size2_<boost::rational<U> > &s)\n        : width(boost::rational_cast<T>(s.width))\n        , height(boost::rational_cast<T>(s.height))\n    {}\n\n    bool operator== (const Size2_<T>& s) const {\n        return width == s.width && height == s.height;\n    }\n    bool operator!= (const Size2_<T>& s) const {\n        return !operator==(s);\n    }\n};\n\n\ntypedef Size2_<int> Size2i;\ntypedef Size2_<long long> Size2ll;\ntypedef Size2_<double> Size2f;\ntypedef Size2i Size2;\ntypedef Size2_<boost::rational<long long> > Size2r;\n\nnamespace detail {\n\n/** Area type. Must be wide enough to hold result of (width * height).\n *\n *  Defaults to long long (should hold any sane area of integral sizes.\n *\n *  Floating types have identical area type.\n */\ntemplate <typename T> struct AreaType { typedef long long type; };\ntemplate<> struct AreaType<float> { typedef float type; };\ntemplate<> struct AreaType<double> { typedef double type; };\ntemplate<> struct AreaType<long double> { typedef long double type; };\n\n} // namespace detail\n\ntemplate <typename T>\ntypename detail::AreaType<T>::type area(const Size2_<T> &size)\n{\n    return ((typename detail::AreaType<T>::type)(size.width) * size.height);\n}\n\ntemplate <typename T>\nbool empty(const Size2_<T> &size)\n{\n    return (size.width <= 0) || (size.height <= 0);\n}\n\ntemplate <typename T> struct Size2SimpleReader { math::Size2_<T> *value; };\n\n/** Used to safely read Size2_<T> in format WxH or A (equivalent to AxA) from\n *  input stream.\n */\ntemplate <typename T>\nSize2SimpleReader<T> size2SimpleReader(math::Size2_<T> &value);\n\ntemplate <class T>\nstruct Size3_ {\n    typedef T value_type;\n\n    Size3_() : width( 0 ), height( 0 ), depth( 0 ) {};\n\n    Size3_( const T & width, const T & height, const T & depth)\n        : width( width ), height( height ), depth(depth) {};\n\n    T width, height, depth;\n\n    template <typename U>\n    explicit Size3_(const Size3_<U> &s)\n        : width(s.width), height(s.height), depth(s.depth)\n    {}\n\n    template <typename U>\n    explicit Size3_(const Size3_<boost::rational<U> > &s)\n        : width(boost::rational_cast<T>(s.width))\n        , height(boost::rational_cast<T>(s.height))\n        , depth(boost::rational_cast<T>(s.depth))\n    {}\n\n    bool operator== (const Size3_<T>& s) const {\n        return width == s.width && height == s.height && depth == s.depth;\n    }\n    bool operator!= (const Size3_<T>& s) const {\n        return !operator==(s);\n    }\n\n    T & operator()(int idx) {\n        switch(idx) {\n            case 0 : return width;\n            case 1 : return height;\n            case 2 : return depth;\n            default :\n                throw GeometryError(\"Bad index to Size3.\");\n        }\n    }\n\n    const T & operator()(int idx) const {\n        switch(idx) {\n            case 0 : return width;\n            case 1 : return height;\n            case 2 : return depth;\n            default :\n                throw GeometryError(\"Bad index to Size3.\");\n        }\n    }\n};\n\ntypedef Size3_<int> Size3i;\ntypedef Size3_<long long> Size3ll;\ntypedef Size3_<double> Size3f;\ntypedef Size3i Size3;\ntypedef Size3_<boost::rational<long long> > Size3r;\n\ntemplate <typename T> struct Size3SimpleReader { math::Size3_<T> *value; };\n\n/** Used to safely read Size3_<T> in format WxHxD or WxA (equivalent WxAxA) or A\n *  (equivalent to AxAxA) from input stream.\n */\ntemplate <typename T>\nSize3SimpleReader<T> size3SimpleReader(math::Size3_<T> &value);\n\n/* viewports */\n\ntemplate <typename T>\nstruct Viewport2_ {\n    typedef T value_type;\n    typedef Size2_<T> size_type;\n\n    value_type width;\n    value_type height;\n    value_type x;\n    value_type y;\n\n    Viewport2_() : width(1000), height(1000), x(0), y(0) {}\n\n    Viewport2_(value_type width, value_type height\n               , value_type x = 0, value_type y = 0)\n        : width(width), height(height), x(x), y(y) {};\n\n    Viewport2_(const size_type &size, value_type x = 0, value_type y = 0)\n        : width( size.width ), height( size.height ), x( x ), y( y ) {};\n\n    size_type size() const { return math::Size2i(width, height); }\n\n    template <typename U>\n    explicit Viewport2_(const Viewport2_<U> &v)\n        : width(v.width), height(v.height), x(v.x), y(v.y)\n    {}\n};\n\ntypedef Viewport2_<int> Viewport2i;\ntypedef Viewport2_<double> Viewport2f;\ntypedef Viewport2i Viewport2;\n\ntemplate <class T> class Point2_;\n\ntemplate <typename T1, typename T2>\ninline bool inside(const Viewport2_<T1> &v, const Point2_<T2> &p)\n{\n    return ((p(0) >= v.x) && (p(0) <= (v.x + v.width))\n            && (p(1) >= v.y) && (p(1) <= (v.y + v.height)));\n}\n\ntemplate <typename T1, typename T2>\ninline bool inside(const Viewport2_<T1> &v, T2 x, T2 y)\n{\n    return ((x >= v.x) && (x <= (v.x + v.width))\n            && (y >= v.y) && (y <= (v.y + v.height)));\n}\n\n/* points and point vectors */\n\ntemplate <class T>\nclass Point2_ : public ublas::fixed_vector<T, 2>  {\n    using Base = ublas::fixed_vector<T, 2>;\npublic:\n    Point2_( const T & x = 0.0, const T & y = 0.0 )\n        : Base() {\n        (*this)(0) = x; (*this)(1) = y;\n    }\n\n    template <class AE>\n    Point2_( const ublas::vector_expression<AE> & op )\n        : Base() {\n        ublas::vector_assign<ublas::scalar_assign>(*this, op );\n    }\n\n    Point2_( const ublas::vector<T> & op )\n        : Base() {\n        ublas::vector_assign<ublas::scalar_assign>( *this, op );\n    }\n\n#ifdef MATH_HAS_OPENCV\n    Point2_( const cv::Point_<T> & op )\n        : Base() {\n        (*this)(0) = op.x; (*this)(1) = op.y;\n    }\n\n    Point2_(const cv::Vec<T,2>& op)\n        : Base() {\n        (*this)(0) = op[0]; (*this)(1) = op[1];\n    }\n#endif\n\n\n#if 0\n    // quite dangerous, imho, should be phased out, use euclidian instead\n    Point2_( const cv::Point3_<T> & op ) {\n        (*this)(0) = op.x / op.z; (*this)(1) = op.y / op.z;\n    }\n#endif\n\n    template <typename U>\n    explicit Point2_(const Point2_<U> &op)\n        : Base()\n    {\n        (*this)(0) = op(0); (*this)(1) = op(1);\n    }\n\n    bool operator== (const Point2_<T>& p) const {\n        return (*this)(0) == p(0) && (*this)(1) == p(1);\n    }\n    bool operator!= (const Point2_<T>& p) const {\n        return !operator==(p);\n    }\n};\n\ntemplate <class T>\nclass Point3_ : public ublas::fixed_vector<T, 3> {\n    using Base = ublas::fixed_vector<T, 3>;\npublic:\n    Point3_( const T & x = 0.0, const T & y = 0.0, const T & z = 0.0 )\n        : Base() {\n        (*this)(0) = x; (*this)(1) = y; (*this)(2) = z;\n    }\n\n    template <class AE>\n    Point3_( const ublas::vector_expression<AE> & op )\n        : Base() {\n        ublas::vector_assign<ublas::scalar_assign>( *this, op );\n    }\n\n    Point3_( const ublas::vector<T> & op )\n        : Base() {\n        ublas::vector_assign<ublas::scalar_assign>( *this, op );\n    }\n\n#ifdef MATH_HAS_OPENCV\n    // convieniece for reading points from 3-channel OpenCV matrices\n    Point3_(const cv::Vec<T,3>& op)\n        : Base() {\n        (*this)(0) = op[0]; (*this)(1) = op[1]; (*this)(2) = op[2];\n    }\n\n    Point3_(const cv::Point3_<T>& op)\n        : Base() {\n        (*this)(0) = op.x; (*this)(1) = op.y; (*this)(2) = op.z;\n    }\n#endif\n\n    Point3_(const Point3_<T> &) = default;\n    Point3_ & operator=(const Point3_<T> &) = default;\n\n    // make point movable\n    Point3_( Point3_<T> && op )\n        : Base() {\n        ublas::vector_assign<ublas::scalar_assign>( *this, op );\n    }\n\n    Point3_ & operator=(Point3_<T> &&op) {\n        ublas::vector_assign<ublas::scalar_assign>( *this, op );\n        return *this;\n    }\n\n    template <typename U>\n    explicit Point3_(const Point3_<U> &op)\n        : Base()\n    {\n        (*this)(0) = op(0); (*this)(1) = op(1); (*this)(2) = op(2);\n    }\n\n    bool operator== (const Point3_<T>& p) const {\n        return (*this)(0) == p(0) && (*this)(1) == p(1) && (*this)(2) == p(2);\n    }\n    bool operator!= (const Point3_<T>& p) const {\n        return !operator==(p);\n    }\n};\n\ntemplate <class T>\nclass Point4_ : public ublas::fixed_vector<T, 4> {\n    using Base = ublas::fixed_vector<T, 4>;\npublic:\n    Point4_( const T & x = 0.0, const T & y = 0.0\n           , const T & z = 0.0, const T & w = 0.0 )\n        : Base() {\n        (*this)(0) = x; (*this)(1) = y; (*this)(2) = z; (*this)(3) = w;\n    }\n\n    template <class AE>\n    Point4_( const ublas::vector_expression<AE> & op )\n        : Base() {\n        ublas::vector_assign<ublas::scalar_assign>( *this, op );\n    }\n\n    Point4_( const ublas::vector<T> & op )\n        : Base() {\n        ublas::vector_assign<ublas::scalar_assign>( *this, op );\n    }\n\n    bool operator== (const Point4_<T>& p) const {\n        return (*this)(0) == p(0) && (*this)(1) == p(1) &&\n               (*this)(2) == p(2) && (*this)(3) == p(3);\n    }\n    bool operator!= (const Point4_<T>& p) const {\n        return !operator==(p);\n    }\n};\n\ntypedef Point2_<int> Point2i;\ntypedef Point2_<long long> Point2ll;\ntypedef Point2_<float> Point2f;\ntypedef Point2_<double> Point2d;\ntypedef Point2d Point2;\n\ntypedef Point3_<int> Point3i;\ntypedef Point3_<long long> Point3ll;\ntypedef Point3_<float> Point3f;\ntypedef Point3_<double> Point3d;\ntypedef Point3d Point3;\n\ntypedef Point4_<int> Point4i;\ntypedef Point4_<long long> Point4ll;\ntypedef Point4_<float> Point4f;\ntypedef Point4_<double> Point4d;\ntypedef Point4d Point4;\n\ntypedef std::vector<Point2_<int> > Points2i;\ntypedef std::vector<Point2_<long long> > Points2ll;\ntypedef std::vector<Point2_<float> > Points2f;\ntypedef std::vector<Point2_<double> > Points2d;\ntypedef std::vector<Point2> Points2;\n\ntypedef std::vector<Point3_<int> > Points3i;\ntypedef std::vector<Point3_<long long> > Points3ll;\ntypedef std::vector<Point3_<float> > Points3f;\ntypedef std::vector<Point3_<double> > Points3d;\ntypedef std::vector<Point3> Points3;\n\ntypedef ublas::matrix<double,ublas::row_major,\n                      ublas::bounded_array<double, 4> > Matrix2;\ntypedef ublas::matrix<double,ublas::row_major,\n                      ublas::bounded_array<double, 9> > Matrix3;\ntypedef ublas::matrix<double,ublas::row_major,\n                      ublas::bounded_array<double, 16> > Matrix4;\n\n\n// handy point->size conversion\ntemplate<typename T>\ninline Size2_<T> size(const Point2_<T> &p) {\n    return { p(0), p(1) };\n}\n\n// handy size->point conversion\ntemplate<typename T>\ninline Point2_<T> point(const Size2_<T> &s) {\n    return { s.width, s.height };\n}\n\n// handy point->size conversion for point3\ntemplate<typename T>\ninline Size3_<T> size(const Point3_<T> &p) {\n    return { p(0), p(1), p(2) };\n}\n\n// handy size->point conversion\ntemplate<typename T>\ninline Point3_<T> point(const Size3_<T> &s) {\n    return { s.width, s.height, s.depth };\n}\n\n/** Helper tag struct for invalid value extents instantiation.\n */\nstruct InvalidExtents {};\n\n/** Helper tag struct for creating infinite extents\n */\nstruct InfiniteExtents {};\n\n/** Helper tag struct for inclusive size computation:\n *\n *  size(Extents<integral>(x, y, x, y)) is (0, 0)\n *  size(Extents<integral>(x, y, x, y), Inclusive{}) is (1, 1)\n */\nstruct Inclusive {};\n\ntemplate <typename T>\nstruct Extents2_ {\n    typedef T value_type;\n    typedef Point2_<T> point_type;\n\n    point_type ll;\n    point_type ur;\n\n    Extents2_() : ll(), ur() {}\n\n    explicit Extents2_(InvalidExtents)\n        : ll(std::numeric_limits<T>::max()\n             , std::numeric_limits<T>::max())\n        , ur(std::numeric_limits<T>::lowest()\n             , std::numeric_limits<T>::lowest())\n    {}\n\n    explicit Extents2_(InfiniteExtents)\n        : ll(std::numeric_limits<T>::lowest()\n             , std::numeric_limits<T>::lowest())\n        , ur(std::numeric_limits<T>::max()\n             , std::numeric_limits<T>::max())\n    {}\n\n    explicit Extents2_(const point_type &p)\n        : ll(p), ur(p)\n    {}\n\n    Extents2_(const point_type &ll, const point_type &ur)\n        : ll(ll), ur(ur)\n    {}\n\n    Extents2_(const value_type &xll, const value_type &yll\n              , const value_type &xur, const value_type &yur)\n        : ll(xll, yll), ur(xur, yur)\n    {}\n\n    template <typename U>\n    explicit Extents2_(const Extents2_<U> &e)\n        : ll(e.ll), ur(e.ur)\n    {}\n\n    Extents2_<T>& operator=(InvalidExtents) {\n        ll(0) = std::numeric_limits<T>::max();\n        ll(1) = std::numeric_limits<T>::max();\n        ur(0) = std::numeric_limits<T>::lowest();\n        ur(1) = std::numeric_limits<T>::lowest();\n        return *this;\n    }\n\n    T area() const {\n        if ( ur[1] < ll[1] || ur[0] < ll[0] ) return 0;\n        return ( ur[1] - ll[1] ) * ( ur[0] - ll[0] ); }\n\n    T size() const {\n        return std::max(ur[0] - ll[0], ur[1] - ll[1]);\n    }\n};\n\ntypedef Extents2_<int> Extents2i;\ntypedef Extents2_<long long> Extents2ll;\ntypedef Extents2_<double> Extents2f;\ntypedef Extents2f Extents2;\n\ntemplate <typename T1, typename T2>\ninline bool inside(const Extents2_<T1> &e, const T2 &p0, const T2 &p1)\n{\n    return ((p0 >= e.ll(0)) && (p0 <= e.ur(0))\n            && (p1 >= e.ll(1)) && (p1 <= e.ur(1)));\n}\n\ntemplate <typename T1, typename T2>\ninline bool inside(const Extents2_<T1> &e, const Point2_<T2> &p)\n{\n    return ((p(0) >= e.ll(0)) && (p(0) <= e.ur(0))\n            && (p(1) >= e.ll(1)) && (p(1) <= e.ur(1)));\n}\n\n/** Checks only for x and y components of Point3\n */\ntemplate <typename T1, typename T2>\ninline bool inside(const Extents2_<T1> &e, const Point3_<T2> &p)\n{\n    return ((p(0) >= e.ll(0)) && (p(0) <= e.ur(0))\n            && (p(1) >= e.ll(1)) && (p(1) <= e.ur(1)));\n}\n\ntemplate <typename T1, typename T2>\ninline Extents2_<T1> operator+(const Extents2_<T1> &e, const T2 &diff)\n{\n    return Extents2_<T1>\n        (e.ll(0) - diff, e.ll(1) - diff\n         , e.ur(0) + diff, e.ur(1) + diff);\n}\n\ntemplate <typename T1, typename T2>\ninline Extents2_<T1> operator+(const Extents2_<T1> &e, const Size2_<T2> &diff)\n{\n    return Extents2_<T1>\n        (e.ll(0) - diff.width, e.ll(1) - diff.height\n         , e.ur(0) + diff.width, e.ur(1) + diff.height);\n}\n\ntemplate <typename T>\nViewport2_<T> viewport(const Extents2_<T> &e)\n{\n    return Viewport2_<T>(e.ur(0) - e.ll(0), e.ur(1) - e.ll(1)\n                         , e.ll(0), e.ll(1));\n}\n\ntemplate <typename T>\nExtents2_<T> extents(const Viewport2_<T> &v)\n{\n    return Extents2_<T>(v.x, v.y, v.x + v.width, v.y + v.height);\n}\n\ntemplate <typename T>\nconst typename Extents2_<T>::point_type& ll(const Extents2_<T> &e) {\n    return e.ll;\n}\n\ntemplate <typename T>\nconst typename Extents2_<T>::point_type& ur(const Extents2_<T> &e) {\n    return e.ur;\n}\n\ntemplate <typename T>\ntypename Extents2_<T>::point_type ul(const Extents2_<T> &e) {\n    return typename Extents2_<T>::point_type(e.ll(0), e.ur(1));\n}\n\ntemplate <typename T>\ntypename Extents2_<T>::point_type lr(const Extents2_<T> &e) {\n    return typename Extents2_<T>::point_type(e.ur(0), e.ll(1));\n}\n\ntemplate<typename T>\ninline Point2_<T> clip(const Extents2_<T> &e, const Point2_<T> &p) {\n    return Point2_<T>(std::max(e.ll(0), std::min(e.ur(0), p(0)))\n                      , std::max(e.ll(1), std::min(e.ur(1), p(1))));\n}\n\ntemplate<typename T>\ninline Point2_<T> center(const Extents2_<T> &e) {\n    return (e.ur + e.ll) / 2;\n}\n\ntemplate<typename T>\ninline Size2_<T> size(const Extents2_<T> &e) {\n    return Size2_<T>(e.ur(0) - e.ll(0), e.ur(1) - e.ll(1));\n}\n\ntemplate<typename T>\ninline Size2_<T> size(const Extents2_<T> &e, const Inclusive&) {\n    return Size2_<T>(e.ur(0) - e.ll(0) + T(1), e.ur(1) - e.ll(1) + T(1));\n}\n\ntemplate<typename T>\ninline T area(const Extents2_<T> &e) {\n    return ((e.ur[1] < e.ll[1]) || (e.ur[0] < e.ll[0]))\n        ? 0\n        : (e.ur[1] - e.ll[1]) * (e.ur[0] - e.ll[0]);\n}\n\ntemplate<typename T>\ninline bool empty(const Extents2_<T> &e) {\n    return !area(e);\n}\n\ntemplate<typename T>\ninline bool valid(const Extents2_<T> &e) {\n    return (e.ll(0) <= e.ur(0)) && (e.ll(1) <= e.ur(1));\n}\n\ntemplate <typename T>\ninline Extents2_<T> unite( const Extents2_<T> &a, const Extents2_<T> &b ) {\n\n    return Extents2_<T>(\n        typename Extents2_<T>::point_type (\n            std::min( a.ll[0], b.ll[0] ),\n            std::min( a.ll[1], b.ll[1] ) ),\n        typename Extents2_<T>::point_type (\n            std::max( a.ur[0], b.ur[0] ),\n            std::max( a.ur[1], b.ur[1] ) ) );\n}\n\ntemplate <typename T1, typename T2>\ninline bool overlaps(const Extents2_<T1> &a, const Extents2_<T2> &b)\n{\n    return ((a.ll(0) < b.ur(0)) && (b.ll(0) < a.ur(0))\n             && (a.ll(1) < b.ur(1)) && (b.ll(1) < a.ur(1)));\n}\n\ntemplate <typename T>\ninline Extents2_<T> intersect( const Extents2_<T> &a, const Extents2_<T> &b ) {\n    if (!overlaps(a, b)) {\n        throw NoIntersectError\n            (\"Extents do not overlap, cannot compute intersection\");\n    }\n\n    return Extents2_<T>(\n        typename Extents2_<T>::point_type (\n            std::max( a.ll[0], b.ll[0] ),\n            std::max( a.ll[1], b.ll[1] ) ),\n        typename Extents2_<T>::point_type (\n            std::min( a.ur[0], b.ur[0] ),\n            std::min( a.ur[1], b.ur[1] ) ) );\n}\n\n\ntemplate <typename T>\ninline double overlap( const Extents2_<T> & a, const Extents2_<T> & b ) {\n    try {\n        return ( intersect( a, b ).area() / unite( a, b ).area() );\n    } catch (const NoIntersectError &) {\n        return .0;\n    }\n}\n\ntemplate <typename T>\ninline void update(Extents2_<T> &e, const T &x, const T &y) {\n    e.ll(0) = std::min(e.ll(0), x);\n    e.ll(1) = std::min(e.ll(1), y);\n\n    e.ur(0) = std::max(e.ur(0), x);\n    e.ur(1) = std::max(e.ur(1), y);\n}\n\ntemplate <typename T>\ninline void update(Extents2_<T> &e, const Point2_<T> &p) {\n    e.ll(0) = std::min(e.ll(0), p(0));\n    e.ll(1) = std::min(e.ll(1), p(1));\n\n    e.ur(0) = std::max(e.ur(0), p(0));\n    e.ur(1) = std::max(e.ur(1), p(1));\n}\n\ntemplate <typename T>\ninline void update(Extents2_<T> &e, const Point3_<T> &p) {\n    e.ll(0) = std::min(e.ll(0), p(0));\n    e.ll(1) = std::min(e.ll(1), p(1));\n\n    e.ur(0) = std::max(e.ur(0), p(0));\n    e.ur(1) = std::max(e.ur(1), p(1));\n}\n\ntemplate <typename T>\ninline void update(Extents2_<T> &e, const Extents2_<T> &other) {\n    update(e, other.ll);\n    update(e, other.ur);\n}\n\ntemplate <typename P, typename R, typename T>\ninline P snapToGrid(const P & point, const P & origin, T step, R roundFcn) {\n    P res;\n\n    for (std::size_t i(0); i < res.size(); ++i) {\n        res(i) = roundFcn((point(i) - origin(i))/step) * step + origin(i);\n    }\n\n    return res;\n}\n\ntemplate <typename E, typename T>\ninline E snapToGrid( const E &ext, const typename E::point_type &origin\n                   , T step, bool inscribe = false)\n{\n    typedef typename E::value_type VT;\n    if (inscribe) {\n        return { snapToGrid(ext.ll, origin, step\n                            , [](VT value) { return std::ceil(value); })\n                , snapToGrid(ext.ur, origin, step\n                             , [](VT value) { return std::floor(value); }) };\n    }\n\n    return { snapToGrid(ext.ll, origin, step\n                        , [](VT value) { return std::floor(value); })\n            , snapToGrid(ext.ur, origin, step\n                         , [](VT value) { return std::ceil(value); }) };\n}\n\ntemplate <typename T>\nstruct Extents3_ {\n    typedef T value_type;\n    typedef Point3_<T> point_type;\n\n    point_type ll;\n    point_type ur;\n\n    Extents3_() : ll(), ur() {}\n\n    explicit Extents3_(InvalidExtents)\n        : ll(std::numeric_limits<T>::max(), std::numeric_limits<T>::max()\n             , std::numeric_limits<T>::max())\n        , ur(std::numeric_limits<T>::lowest(), std::numeric_limits<T>::lowest()\n             , std::numeric_limits<T>::lowest())\n    {}\n\n    explicit Extents3_(const point_type &p)\n        : ll(p), ur(p)\n    {}\n\n    Extents3_(const point_type &ll, const point_type &ur)\n        : ll(ll), ur(ur)\n    {}\n\n    Extents3_(const value_type &xll, const value_type &yll\n              , const value_type &zll\n              , const value_type &xur, const value_type yur\n              , const value_type &zur)\n        : ll(xll, yll, zll), ur(xur, yur, zur)\n    {}\n\n    template <typename U>\n    explicit Extents3_(const Extents3_<U> &e)\n        : ll(e.ll), ur(e.ur)\n    {}\n\n    Extents3_<T>& operator=(InvalidExtents) {\n        ll(0) = std::numeric_limits<T>::max();\n        ll(1) = std::numeric_limits<T>::max();\n        ll(2) = std::numeric_limits<T>::max();\n        ur(0) = std::numeric_limits<T>::lowest();\n        ur(1) = std::numeric_limits<T>::lowest();\n        ur(2) = std::numeric_limits<T>::lowest();\n        return *this;\n    }\n};\n\ntypedef Extents3_<int> Extents3i;\ntypedef Extents3_<long long> Extents3ll;\ntypedef Extents3_<double> Extents3f;\ntypedef Extents3f Extents3;\n\ntemplate<typename T>\ninline Point3_<T> center(const Extents3_<T> &e) {\n    return (e.ur + e.ll) / 2;\n}\n\ntemplate<typename T>\ninline Point3_<T> clip(const Extents3_<T> &e, const Point3_<T> &p) {\n    return Point3_<T>(std::max(e.ll(0), std::min(e.ur(0), p(0)))\n                      , std::max(e.ll(1), std::min(e.ur(1), p(1)))\n                      , std::max(e.ll(2), std::min(e.ur(2), p(2))));\n}\n\ntemplate<typename T>\ninline Size3_<T> size(const Extents3_<T> &e) {\n    return Size3_<T>(e.ur(0) - e.ll(0), e.ur(1) - e.ll(1), e.ur(2) - e.ll(2));\n}\n\ntemplate<typename T>\ninline Size3_<T> size(const Extents3_<T> &e, const Inclusive&) {\n    return Size3_<T>(e.ur(0) - e.ll(0) + T(1)\n                     , e.ur(1) - e.ll(1) + T(1)\n                     , e.ur(2) - e.ll(2) + T(1));\n}\n\ntemplate<typename T>\ninline Size2_<T> size2(const Extents3_<T> &e) {\n    return Size2_<T>(e.ur(0) - e.ll(0), e.ur(1) - e.ll(1));\n}\n\ntemplate<typename T>\ninline Size2_<T> size2(const Extents3_<T> &e, const Inclusive&) {\n    return Size2_<T>(e.ur(0) - e.ll(0) + T(1)\n                     , e.ur(1) - e.ll(1) + T(1));\n}\n\ntemplate<typename T>\ninline T volume(const Extents3_<T> &e) {\n    return ((e.ur[2] < e.ll[2]) || (e.ur[1] < e.ll[1]) || (e.ur[0] < e.ll[0]))\n        ? 0\n        : (e.ur[2] - e.ll[2]) * (e.ur[1] - e.ll[1]) * (e.ur[0] - e.ll[0]);\n}\n\ntemplate<typename T>\ninline bool empty(const Extents3_<T> &e) {\n    return !volume(e);\n}\n\ntemplate<typename T>\ninline bool valid(const Extents3_<T> &e) {\n    return ((e.ll(0) <= e.ur(0))\n            && (e.ll(1) <= e.ur(1))\n            && (e.ll(2) <= e.ur(2)));\n}\n\ntemplate <typename T>\ninline void update(Extents3_<T> &e, const Point3_<T> &p) {\n    e.ll(0) = std::min(e.ll(0), p(0));\n    e.ll(1) = std::min(e.ll(1), p(1));\n    e.ll(2) = std::min(e.ll(2), p(2));\n\n    e.ur(0) = std::max(e.ur(0), p(0));\n    e.ur(1) = std::max(e.ur(1), p(1));\n    e.ur(2) = std::max(e.ur(2), p(2));\n}\n\n\ntemplate <typename T>\ninline void update(Extents3_<T> &e, const Extents3_<T> &other) {\n    update(e, other.ll);\n    update(e, other.ur);\n}\n\ntemplate <typename T>\ninline Extents3_<T> unite(const Extents3_<T> &a, const Extents3_<T> &b ) {\n    Extents3_<T> res(a);\n    update(res, b.ll);\n    update(res, b.ur);\n    return res;\n}\n\ntemplate <typename T1, typename T3>\ninline bool overlaps(const Extents3_<T1> &a, const Extents3_<T3> &b)\n{\n    return ((a.ll(0) < b.ur(0)) && (b.ll(0) < a.ur(0))\n             && (a.ll(1) < b.ur(1)) && (b.ll(1) < a.ur(1))\n             && (a.ll(2) < b.ur(2)) && (b.ll(2) < a.ur(2)));\n}\n\ntemplate <typename T>\ninline Extents3_<T> intersect( const Extents3_<T> &a, const Extents3_<T> &b ) {\n    if (!overlaps(a, b)) {\n        throw NoIntersectError\n            (\"Extents do not overlap, cannot compute intersection\");\n    }\n\n    typedef Extents3_<T> E3;\n    typedef typename E3::point_type point_type;\n    return Extents3(point_type(std::max(a.ll[0], b.ll[0])\n                               , std::max(a.ll[1], b.ll[1])\n                               , std::max(a.ll[2], b.ll[2]))\n                    , point_type(std::min(a.ur[0], b.ur[0])\n                                 , std::min(a.ur[1], b.ur[1])\n                                 , std::min(a.ur[2], b.ur[2])));\n}\n\ntemplate <typename T>\ninline double overlap(const Extents3_<T> & a, const Extents3_<T> & b) {\n    try {\n        return (volume(intersect(a, b)) / volume(unite(a, b)));\n    } catch (const NoIntersectError&) {\n        return .0;\n    }\n}\n\ntemplate<typename CharT, typename Traits, typename T>\ninline std::basic_ostream<CharT, Traits>&\noperator<<(std::basic_ostream<CharT, Traits> &os, const Viewport2_<T> &v)\n{\n    std::ios::fmtflags flags(os.flags());\n    os << v.width << \"x\" << v.height << std::showpos << v.x << v.y;\n    os.flags(flags);\n    return os;\n}\n\ntemplate<typename CharT, typename Traits, typename T>\ninline std::basic_istream<CharT, Traits>&\noperator>>(std::basic_istream<CharT, Traits> &is, Viewport2_<T> &v)\n{\n    using boost::spirit::qi::auto_;\n    using boost::spirit::qi::char_;\n    using boost::spirit::qi::omit;\n    using boost::spirit::qi::match;\n\n    char sign1, sign2;\n\n    is >> match((auto_ >> omit['x'] >> auto_\n                 >> (char_('+') | char_('-')) >> auto_\n                 >> (char_('+') | char_('-')) >> auto_)\n                , v.width, v.height, sign1, v.x, sign2, v.y);\n\n    if (sign1 == '-') { v.x = -v.x; }\n    if (sign2 == '-') { v.y = -v.y; }\n    return is;\n}\n\n#if 0\n// original unsafe code\ntemplate <class UblasContainer>\ninline bool operator < (\n    const UblasContainer & op1, const UblasContainer & op2 ) {\n\n    return std::lexicographical_compare(\n                op1.data().begin(), op1.data().end(),\n                op2.data().begin(), op2.data().end() );\n}\n\n#else\n\ninline bool operator < (\n    const Matrix4 & op1, const Matrix4 & op2 ) {\n    return std::lexicographical_compare(\n                op1.data().begin(), op1.data().end(),\n                op2.data().begin(), op2.data().end() );\n}\n\ntemplate <typename T1, typename T2>\ninline bool operator < (\n    const Point3_<T1> & op1, const Point3_<T2> & op2 ) {\n\n    return std::lexicographical_compare(\n                op1.data().begin(), op1.data().end(),\n                op2.data().begin(), op2.data().end() );\n}\n\ntemplate <typename T1, typename T2>\ninline bool operator < (\n    const Point2_<T1> & op1, const Point2_<T2> & op2 ) {\n\n    return std::lexicographical_compare(\n                op1.data().begin(), op1.data().end(),\n                op2.data().begin(), op2.data().end() );\n}\n\n#endif\n\ntemplate<typename CharT, typename Traits, typename T>\ninline std::basic_ostream<CharT, Traits>&\noperator<<(std::basic_ostream<CharT, Traits> &os, const Extents2_<T> &e)\n{\n    os << e.ll(0) << ',' << e.ll(1) << ':' << e.ur(0) << ',' << e.ur(1);\n    return os;\n}\n\ntemplate<typename CharT, typename Traits, typename T>\ninline std::basic_istream<CharT, Traits>&\noperator>>(std::basic_istream<CharT, Traits> &is, Extents2_<T> &e)\n{\n    using boost::spirit::qi::auto_;\n    using boost::spirit::qi::char_;\n    using boost::spirit::qi::omit;\n    using boost::spirit::qi::match;\n\n    is >> match((auto_ >> omit[','] >> auto_ >> omit[':']\n                 >> auto_ >> omit[','] >> auto_)\n                , e.ll(0), e.ll(1), e.ur(0), e.ur(1));\n\n    return is;\n}\n\ntemplate<typename CharT, typename Traits, typename T>\ninline std::basic_ostream<CharT, Traits>&\noperator<<(std::basic_ostream<CharT, Traits> &os, const Extents3_<T> &e)\n{\n    os << e.ll(0) << ',' << e.ll(1) << ',' << e.ll(2) << ':'\n       << e.ur(0) << ',' << e.ur(1) << ',' << e.ur(2);\n    return os;\n}\n\ntemplate<typename CharT, typename Traits, typename T>\ninline std::basic_istream<CharT, Traits>&\noperator>>(std::basic_istream<CharT, Traits> &is, Extents3_<T> &e)\n{\n    using boost::spirit::qi::auto_;\n    using boost::spirit::qi::char_;\n    using boost::spirit::qi::omit;\n    using boost::spirit::qi::match;\n\n    is >> match((auto_ >> omit[','] >> auto_ >> omit[','] >> auto_ >> omit[':']\n                 >> auto_ >> omit[','] >> auto_ >> omit[','] >> auto_)\n                , e.ll(0), e.ll(1), e.ll(2), e.ur(0), e.ur(1), e.ur(2));\n\n    return is;\n}\n\ntemplate <typename T1, typename T2>\ninline bool inside(const Extents3_<T1> &e, const T2 &p0, const T2 &p1\n                   , const T2 &p2)\n{\n    return ((p0 >= e.ll(0)) && (p0 <= e.ur(0))\n            && (p1 >= e.ll(1)) && (p1 <= e.ur(1))\n            && (p2 >= e.ll(2)) && (p2 <= e.ur(2)));\n}\n\ntemplate <typename T1, typename T2>\ninline bool inside(const Extents3_<T1> &e, const Point3_<T2> &p)\n{\n    return ((p(0) >= e.ll(0)) && (p(0) <= e.ur(0))\n            && (p(1) >= e.ll(1)) && (p(1) <= e.ur(1))\n            && (p(2) >= e.ll(2)) && (p(2) <= e.ur(2)));\n}\n\ntemplate <typename T1, typename T2>\ninline Extents3_<T1> operator+(const Extents3_<T1> &e, const T2 &diff)\n{\n    return Extents3_<T1>\n        (e.ll(0) - diff, e.ll(1) - diff, e.ll(2) - diff\n        , e.ur(0) + diff, e.ur(1) + diff, e.ur(2) + diff);\n}\n\ntemplate <typename T1, typename T2>\ninline Extents3_<T1> operator+(const Extents3_<T1> &e, const Size3_<T2> &diff)\n{\n    return Extents3_<T1>\n        (e.ll(0) - diff.width, e.ll(1) - diff.height\n         , e.ll(2) - diff.depth\n         , e.ur(0) + diff.width, e.ur(1) + diff.height\n         , e.ur(2) + diff.depth);\n}\n\ntemplate <typename T>\nconst typename Extents3_<T>::point_type& bll(const Extents3_<T> &e) {\n    return e.ll;\n}\n\ntemplate <typename T>\ntypename Extents3_<T>::point_type bul(const Extents3_<T> &e) {\n    return typename Extents3_<T>::point_type(e.ll(0), e.ur(1), e.ll(2));\n}\n\ntemplate <typename T>\ntypename Extents3_<T>::point_type bur(const Extents3_<T> &e) {\n    return typename Extents3_<T>::point_type(e.ur(0), e.ur(1), e.ll(2));\n}\n\ntemplate <typename T>\ntypename Extents3_<T>::point_type blr(const Extents3_<T> &e) {\n    return typename Extents3_<T>::point_type(e.ur(0), e.ll(1), e.ll(2));\n}\n\ntemplate <typename T>\nconst typename Extents3_<T>::point_type tll(const Extents3_<T> &e) {\n    return typename Extents3_<T>::point_type(e.ll(0), e.ll(1), e.ur(2));\n}\n\ntemplate <typename T>\ntypename Extents3_<T>::point_type tul(const Extents3_<T> &e) {\n    return typename Extents3_<T>::point_type(e.ll(0), e.ur(1), e.ur(2));\n}\n\ntemplate <typename T>\nconst typename Extents3_<T>::point_type& tur(const Extents3_<T> &e) {\n    return e.ur;\n}\n\ntemplate <typename T>\ntypename Extents3_<T>::point_type tlr(const Extents3_<T> &e) {\n    return typename Extents3_<T>::point_type(e.ur(0), e.ll(1), e.ur(2));\n}\n\n/** Get all 4 vertices from Extents2 as a vector of points.\n */\ntemplate <typename T>\nconst std::vector<typename Extents2_<T>::point_type>\nvertices(const Extents2_<T> &e)\n{\n    return { ll(e), ul(e), ur(e), lr(e) };\n}\n\n/** Get all 8 vertices from Extents3 as a vector of points.\n */\ntemplate <typename T>\nconst std::vector<typename Extents3_<T>::point_type>\nvertices(const Extents3_<T> &e)\n{\n    return { bll(e), bul(e), bur(e), blr(e), tll(e), tul(e), tur(e), tlr(e) };\n}\n\n/** Helper functions to convert between 2d and 3d entities\n */\n\n// Size2_ <-> Size3_\n\ntemplate <typename T>\nSize2_<T> size2(const Size3_<T> &s)\n{\n    return Size2_<T>(s.width, s.height);\n}\n\ntemplate <typename T>\nconst Size2_<T>& size2(const Size2_<T> &s) { return s; }\n\ntemplate <typename T>\nSize3_<T> size3(const Size2_<T> &s)\n{\n    return Size3_<T>(s.width, s.height, T(0));\n}\n\ntemplate <typename T>\nconst Size3_<T>& size3(const Size3_<T> &s) { return s; }\n\n// Extents2_ <-> Extents3_\n\ntemplate <typename T>\nExtents2_<T> extents2(const Extents3_<T> &e)\n{\n    return Extents2_<T>(e.ll(0), e.ll(1), e.ur(0), e.ur(1));\n}\n\ntemplate <typename T>\nconst Extents2_<T>& extents2(const Extents2_<T> &e) { return e; }\n\ntemplate <typename T>\nExtents3_<T> extents3(const Extents2_<T> &e)\n{\n    return Extents3_<T>(e.ll(0), e.ll(1), T(0), e.ur(0), e.ur(1), T(0));\n}\n\ntemplate <typename T>\nconst Extents3_<T>& extents3(const Extents3_<T> &e) { return e; }\n\n// Point2_ <-> Point3_\n\ntemplate <typename T>\nPoint2_<T> point2(const Point3_<T> &p)\n{\n    return Point2_<T>(p(0), p(1));\n}\n\ntemplate <typename T>\nconst Point2_<T>& point2(const Point2_<T> &p) { return p; }\n\ntemplate <typename T>\nPoint3_<T> point3(const Point2_<T> &p)\n{\n    return Point3_<T>(p(0), p(1), T(0));\n}\n\ntemplate <typename T>\nconst Point3_<T>& point3(const Point3_<T> &p) { return p; }\n\n\n#define MATH_GEOMETRY_CORE_HPP_INLINES_\n#include \"detail/point.inline.hpp\"\n#include \"detail/size2.inline.hpp\"\n#include \"detail/size3.inline.hpp\"\n#include \"detail/extents2.inline.hpp\"\n#undef MATH_GEOMETRY_CORE_HPP_INLINES_\n\n} // namespace math\n\n#endif // MATH_GEOMETRY_CORE_HPP\n\n", "meta": {"hexsha": "fe19493fb853ce42ce668f789a0bf06fd617bb38", "size": 34847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/geometry_core.hpp", "max_stars_repo_name": "melowntech/libmath", "max_stars_repo_head_hexsha": "7a473801a93ba5e244d96e773b412a3abed4a400", "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": "math/geometry_core.hpp", "max_issues_repo_name": "melowntech/libmath", "max_issues_repo_head_hexsha": "7a473801a93ba5e244d96e773b412a3abed4a400", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-09T12:06:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T08:15:04.000Z", "max_forks_repo_path": "math/geometry_core.hpp", "max_forks_repo_name": "melowntech/libmath", "max_forks_repo_head_hexsha": "7a473801a93ba5e244d96e773b412a3abed4a400", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:20:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:20:17.000Z", "avg_line_length": 28.4930498774, "max_line_length": 80, "alphanum_fraction": 0.5921887106, "num_tokens": 10913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.04742586812868187, "lm_q1q2_score": 0.01896141415003745}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_PairProductionPhotoatomicReaction.hpp\n//! \\author Alex Robinson\n//! \\brief  The pair production photoatomic reaction class decl.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_PAIR_PRODUCTION_PHOTOATOMIC_REACTION_HPP\n#define MONTE_CARLO_PAIR_PRODUCTION_PHOTOATOMIC_REACTION_HPP\n\n// Boost Includes\n#include <boost/function.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_StandardReactionBaseImpl.hpp\"\n#include \"MonteCarlo_PhotoatomicReaction.hpp\"\n#include \"Utility_InterpolatedFullyTabularBasicBivariateDistribution.hpp\"\n\nnamespace MonteCarlo{\n\n//! The pair production photoatomic reaction class\ntemplate<typename InterpPolicy, bool processed_cross_section = true>\nclass PairProductionPhotoatomicReaction : public StandardReactionBaseImpl<PhotoatomicReaction,InterpPolicy,processed_cross_section>\n{\n  // Typedef for the base class type\n  typedef StandardReactionBaseImpl<PhotoatomicReaction,InterpPolicy,processed_cross_section> BaseType;\n\npublic:\n\n  //! Basic constructor\n  PairProductionPhotoatomicReaction(\n       const std::shared_ptr<const std::vector<double> >& incoming_energy_grid,\n       const std::shared_ptr<const std::vector<double> >& cross_section,\n       const size_t threshold_energy_index,\n       const bool use_detailed_electron_emission_physics = true );\n\n  //! Constructor\n  PairProductionPhotoatomicReaction(\n    const std::shared_ptr<const std::vector<double> >& incoming_energy_grid,\n    const std::shared_ptr<const std::vector<double> >& cross_section,\n    const size_t threshold_energy_index,\n    const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >&\n    grid_searcher,\n    const bool use_detailed_electron_emission_physics = true );\n\n  //! Destructor\n  ~PairProductionPhotoatomicReaction()\n  { /* ... */ }\n\n  //! Return the number of photons emitted from the rxn at the given energy\n  unsigned getNumberOfEmittedPhotons( const double energy ) const override;\n\n  //! Return the number of electrons emitted from the rxn at the given energy\n  unsigned getNumberOfEmittedElectrons( const double energy ) const override;\n\n  //! Return the number of positrons emitted from the rxn at the given energy\n  unsigned getNumberOfEmittedPositrons( const double energy ) const override;\n\n  //! Return the reaction type\n  PhotoatomicReactionType getReactionType() const override;\n\n  //! Simulate the reaction\n  void react( PhotonState& photon,\n\t      ParticleBank& bank,\n\t      Data::SubshellType& shell_of_interaction ) const override;\n\nprotected:\n\n  //! The basic pair production model\n  static void basicInteraction( PhotonState& photon,\n                                ParticleBank& bank );\n\n  //! The detailed pair production model\n  static void detailedInteraction( PhotonState& photon,\n                                   ParticleBank& bank );\n\nprivate:\n\n  // Sample the polar angle of the emitted electron/positron\n  static double sampleEmittedPolarAngle( const double energy );\n\n  // Create the secondary energy distribution\n  static Utility::FullyTabularBasicBivariateDistribution*\n  initializeSecondaryEnergyDistribution();\n\n  // Initialize interaction models\n  void initializeInteractionModels(\n                           const bool use_detailed_electron_emission_physics );\n\n  // The pair production secondary energy distribution (in a ratio form)\n  static std::unique_ptr<const Utility::FullyTabularBasicBivariateDistribution>\n  s_secondary_energy_distribution;\n\n  // Check if a detailed model is being used\n  bool d_detailed_electron_emission_model;\n\n  // The pair production model\n  boost::function<void (PhotonState&,ParticleBank&)> d_interaction_model;\n\n  // pair production secondary energy distribution (in a ratio form)\n  std::shared_ptr<Utility::FullyTabularBasicBivariateDistribution> d_secondary_energy_distribution;\n};\n\n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes.\n//---------------------------------------------------------------------------//\n\n#include \"MonteCarlo_PairProductionPhotoatomicReaction_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end MONTE_CARLO_PAIR_PRODUCTION_PHOTOATOMIC_REACTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_PairProductionPhotoatomicReaction.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "f79bcad3f1abd35cb53c0bf218e764c30a89f9cf", "size": 4578, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_PairProductionPhotoatomicReaction.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_PairProductionPhotoatomicReaction.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_PairProductionPhotoatomicReaction.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 38.15, "max_line_length": 131, "alphanum_fraction": 0.6823940585, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03789242391337982, "lm_q1q2_score": 0.01894621195668991}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *\n *     This file is part of PCMSolver.\n *\n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *\n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *\n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *\n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"Input.hpp\"\n\n#include <iostream>\n#include <map>\n#include <vector>\n#include <string>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n#include \"utils/getkw/Getkw.h\"\n\n#include <boost/algorithm/string.hpp>\n\n#include \"cavity/CavityData.hpp\"\n#include \"green/GreenData.hpp\"\n#include \"solver/SolverData.hpp\"\n#include \"PCMInput.h\"\n#include \"utils/Solvent.hpp\"\n#include \"utils/Sphere.hpp\"\n\nusing boost::algorithm::to_upper_copy;\nusing boost::algorithm::trim;\n\nInput::Input(const std::string & filename)\n{\n    reader(filename);\n    semanticCheck();\n}\n\nInput::Input(const PCMInput & host_input)\n{\n    reader(host_input);\n    semanticCheck();\n}\n\nvoid Input::reader(const std::string & filename)\n{\n    Getkw input_ = Getkw(filename, false, true);\n    units_      = input_.getStr(\"UNITS\");\n    CODATAyear_ = input_.getInt(\"CODATA\");\n    initBohrToAngstrom(bohrToAngstrom, CODATAyear_);\n\n    const Section & cavity = input_.getSect(\"CAVITY\");\n\n    type_ = cavity.getStr(\"TYPE\");\n    area_ = cavity.getDbl(\"AREA\");\n    patchLevel_ = cavity.getInt(\"PATCHLEVEL\");\n    coarsity_ = cavity.getDbl(\"COARSITY\");\n    minDistance_ = cavity.getDbl(\"MINDISTANCE\");\n    derOrder_ = cavity.getInt(\"DERORDER\");\n    if (type_ == \"RESTART\") {\n        cavFilename_ = cavity.getStr(\"NPZFILE\");\n    }\n    dyadicFilename_ = cavity.getStr(\"DYADICFILE\");\n\n    scaling_ = cavity.getBool(\"SCALING\");\n    radiiSet_ = to_upper_copy(cavity.getStr(\"RADIISET\"));\n    minimalRadius_ = cavity.getDbl(\"MINRADIUS\");\n    mode_ = to_upper_copy(cavity.getStr(\"MODE\"));\n    if (mode_ == \"EXPLICIT\") {\n        std::vector<double> spheresInput = cavity.getDblVec(\"SPHERES\");\n        int j = 0;\n        int nAtoms = int(spheresInput.size() / 4);\n        for (int i = 0; i < nAtoms; ++i) {\n            Eigen::Vector3d center;\n            center << spheresInput[j], spheresInput[j+1], spheresInput[j+2];\n            Sphere sph(center, spheresInput[j+3]);\n            spheres_.push_back(sph);\n            j += 4;\n        }\n        // Initialize molecule from spheres only when molecule section is absent\n        if (!input_.getSect(\"MOLECULE\").isDefined()) molecule_ = Molecule(spheres_);\n    } else if (mode_ == \"ATOMS\") {\n        atoms_ = cavity.getIntVec(\"ATOMS\");\n        radii_ = cavity.getDblVec(\"RADII\");\n    }\n\n    // Get the contents of the Medium section\n    const Section & medium = input_.getSect(\"MEDIUM\");\n    // Get the name of the solvent\n    std::string name = medium.getStr(\"SOLVENT\");\n    if (name == \"EXPLICIT\") {\n        hasSolvent_ = false;\n        // Get the probe radius\n        probeRadius_ = medium.getDbl(\"PROBERADIUS\");\n        // Get the contents of the Green<inside> section...\n        const Section & inside = medium.getSect(\"GREEN<INSIDE>\");\n        // ...and initialize the data members\n        greenInsideType_ = inside.getStr(\"TYPE\");\n        derivativeInsideType_ = derivativeTraits(inside.getStr(\"DER\"));\n        epsilonInside_ = inside.getDbl(\"EPS\");\n        // Get the contents of the Green<outside> section...\n        const Section & outside = medium.getSect(\"GREEN<OUTSIDE>\");\n        // ...and initialize the data members\n        greenOutsideType_ = outside.getStr(\"TYPE\");\n        derivativeOutsideType_ = derivativeTraits(outside.getStr(\"DER\"));\n        epsilonStaticOutside_ = outside.getDbl(\"EPS\");\n        epsilonDynamicOutside_ = outside.getDbl(\"EPSDYN\");\n        // This will be needed for the metal sphere only\n        if (greenOutsideType_ == \"METALSPHERE\") {\n            epsilonReal_ = outside.getDbl(\"EPSRE\");\n            epsilonImaginary_ = outside.getDbl(\"EPSIMG\");\n            spherePosition_ = outside.getDblVec(\"SPHEREPOSITION\");\n            sphereRadius_ = outside.getDbl(\"SPHERERADIUS\");\n        }\n        epsilonStatic1_ = outside.getDbl(\"EPS1\");\n        epsilonDynamic1_ = outside.getDbl(\"EPSDYN1\");\n        epsilonStatic2_ = outside.getDbl(\"EPS2\");\n        epsilonDynamic2_ = outside.getDbl(\"EPSDYN2\");\n        center_ = outside.getDbl(\"CENTER\");\n        width_ = outside.getDbl(\"WIDTH\");\n        origin_ = outside.getDblVec(\"INTERFACEORIGIN\");\n        profileType_ = profilePolicy(outside.getStr(\"PROFILE\"));\n        maxL_ = outside.getInt(\"MAXL\");\n    } else { // This part must be reviewed!! Some data members are not initialized...\n        // Just initialize the solvent object in this class\n        hasSolvent_ = true;\n        if (solvents().find(name) == solvents().end()) {\n            PCMSOLVER_ERROR(\"Solvent \" + name + \" NOT found!\", BOOST_CURRENT_FUNCTION);\n        } else {\n            solvent_ = solvents()[name];\n        }\n        probeRadius_ = solvent_.probeRadius * angstromToBohr();\n        // Specification of the solvent by name means isotropic PCM\n        // We have to initialize the Green's functions data here, Solvent class\n        // is an helper class and should not be used in the core classes.\n        greenInsideType_ = \"VACUUM\";\n        derivativeInsideType_ = derivativeTraits(\"DERIVATIVE\");\n        epsilonInside_ = 1.0;\n        greenOutsideType_ = \"UNIFORMDIELECTRIC\";\n        derivativeOutsideType_ = derivativeTraits(\"DERIVATIVE\");\n        epsilonStaticOutside_ = solvent_.epsStatic;\n        epsilonDynamicOutside_ = solvent_.epsDynamic;\n    }\n    integratorType_ = integratorPolicy(medium.getStr(\"DIAGONALINTEGRATOR\"));\n    integratorScaling_ = medium.getDbl(\"DIAGONALSCALING\");\n\n    solverType_ = medium.getStr(\"SOLVERTYPE\");\n    equationType_ = integralEquation(medium.getStr(\"EQUATIONTYPE\"));\n    correction_ = medium.getDbl(\"CORRECTION\");\n    hermitivitize_ = medium.getBool(\"MATRIXSYMM\");\n    isDynamic_ = medium.getBool(\"NONEQUILIBRIUM\");\n\n    if (input_.getSect(\"MOLECULE\").isDefined()) {\n      TIMER_ON(\"Initializing molecule\");\n      geometry_ = input_.getSect(\"MOLECULE\").getDblVec(\"GEOMETRY\");\n      initMolecule();\n      TIMER_OFF(\"Initializing molecule\");\n    }\n\n    providedBy_ = std::string(\"API-side\");\n}\n\nstd::string trim(const char * src)\n{\n    std::string tmp(src);\n    trim(tmp);\n    return tmp;\n}\n\nstd::string trim_and_upper(const char * src)\n{\n    return to_upper_copy(trim(src));\n}\n\nvoid Input::reader(const PCMInput & host_input)\n{\n    CODATAyear_ = 2010;\n    initBohrToAngstrom(bohrToAngstrom, CODATAyear_);\n\n    type_ = trim_and_upper(host_input.cavity_type);\n    area_ = host_input.area * angstrom2ToBohr2();\n    patchLevel_ = host_input.patch_level;\n    coarsity_ = host_input.coarsity * angstromToBohr();\n    minDistance_ = host_input.min_distance * angstromToBohr();\n    derOrder_ = host_input.der_order;\n    if (type_ == \"RESTART\") {\n        cavFilename_ = trim(host_input.restart_name); // No case conversion here!\n    }\n\n    scaling_ = host_input.scaling;\n    radiiSet_ = trim_and_upper(host_input.radii_set);\n    minimalRadius_ = host_input.min_radius * angstromToBohr();\n    mode_ = std::string(\"IMPLICIT\");\n\n    std::string name = trim_and_upper(host_input.solvent);\n    if (name.empty()) {\n        hasSolvent_ = false;\n        // Get the probe radius\n        probeRadius_ = host_input.probe_radius * angstromToBohr();\n        // Get the contents of the Green<inside> section...\n        // ...and initialize the data members\n        greenInsideType_ = trim_and_upper(host_input.inside_type);\n        derivativeInsideType_ = derivativeTraits(\"DERIVATIVE\");\n        epsilonInside_ = 1.0;\n        // Get the contents of the Green<outside> section...\n        // ...and initialize the data members\n        greenOutsideType_ = trim_and_upper(host_input.outside_type);\n        derivativeOutsideType_ = derivativeTraits(\"DERIVATIVE\");\n        epsilonStaticOutside_ = host_input.outside_epsilon;\n        epsilonDynamicOutside_ = host_input.outside_epsilon;\n    } else { // This part must be reviewed!! Some data members are not initialized...\n        // Just initialize the solvent object in this class\n        hasSolvent_ = true;\n        solvent_ = solvents()[name];\n        probeRadius_ = solvent_.probeRadius* angstromToBohr();\n        // Specification of the solvent by name means isotropic PCM\n        // We have to initialize the Green's functions data here, Solvent class\n        // is an helper class and should not be used in the core classes.\n        greenInsideType_ = std::string(\"VACUUM\");\n        derivativeInsideType_ = derivativeTraits(\"DERIVATIVE\");\n        epsilonInside_ = 1.0;\n        greenOutsideType_ = std::string(\"UNIFORMDIELECTRIC\");\n        derivativeOutsideType_ = derivativeTraits(\"DERIVATIVE\");\n        epsilonStaticOutside_ = solvent_.epsStatic;\n        epsilonDynamicOutside_ = solvent_.epsDynamic;\n    }\n    integratorType_ = integratorPolicy(\"COLLOCATION\");\n    integratorScaling_ = 1.07;\n\n    solverType_ = trim_and_upper(host_input.solver_type);\n    std::string inteq = trim_and_upper(host_input.equation_type);\n    equationType_ = integralEquation(inteq);\n    correction_ = host_input.correction;\n    hermitivitize_ = true;\n    isDynamic_ = false;\n\n    providedBy_ = std::string(\"host-side\");\n}\n\nvoid Input::semanticCheck()\n{\n}\n\nvoid Input::initMolecule()\n{\n  // Gather information necessary to build molecule_\n  // 1. number of atomic centers\n  int nuclei = int(geometry_.size() / 4);\n  // 2. position and charges of atomic centers\n  Eigen::Matrix3Xd centers = Eigen::Matrix3Xd::Zero(3, nuclei);\n  Eigen::VectorXd charges  = Eigen::VectorXd::Zero(nuclei);\n  int j = 0;\n  for (int i = 0; i < nuclei; ++i) {\n    centers.col(i) << geometry_[j], geometry_[j+1], geometry_[j+2];\n    charges(i) = geometry_[j+3];\n    j += 4;\n  }\n  // 3. list of atoms and list of spheres\n  double factor = angstromToBohr();\n  std::vector<Atom> radiiSet;\n  std::vector<Atom> atoms;\n  if ( radiiSet_ == \"UFF\" ) {\n    radiiSet = initUFF();\n    radiiSetName_ = \"UFF\";\n  } else if ( radiiSet_ == \"BONDI\" ) {\n    radiiSet = initBondi();\n    radiiSetName_ = \"Bondi-Mantina\";\n  } else {\n    radiiSet = initAllinger();\n    radiiSetName_ = \"Allinger's MM3\";\n  }\n  for (int i = 0; i < charges.size(); ++i) {\n    int index = int(charges(i)) - 1;\n    atoms.push_back(radiiSet[index]);\n    if (scaling_) atoms[index].radiusScaling = 1.2;\n  }\n  // Based on the creation mode (Implicit or Atoms)\n  // the spheres list might need postprocessing\n  if ( mode_ == \"IMPLICIT\" || mode_ == \"ATOMS\") {\n    for (int i = 0; i < charges.size(); ++i) {\n      int index = int(charges(i)) - 1;\n      double radius = radiiSet[index].radius * factor;\n      if (scaling_) radius *= 1.2;\n      spheres_.push_back(Sphere(centers.col(i), radius));\n    }\n    if (mode_ == \"ATOMS\") {\n      // Loop over the atomsInput array to get which atoms will have a user-given radius\n      for (size_t i = 0; i < atoms_.size(); ++i) {\n        int index = atoms_[i] - 1; // -1 to go from human readable to machine readable\n        // Put the new Sphere in place of the implicit-generated one\n        spheres_[index] = Sphere(centers.col(index), radii_[i]);\n      }\n    }\n  }\n\n  // 4. masses\n  Eigen::VectorXd masses = Eigen::VectorXd::Zero(nuclei);\n  for (int i = 0; i < masses.size(); ++i) {\n    masses(i) = atoms[i].mass;\n  }\n  // 5. molecular point group\n  // FIXME currently hardcoded to C1\n\n  // OK, now get molecule_\n  molecule_ = Molecule(nuclei, charges, masses, centers, atoms, spheres_);\n  // Check that all atoms have a radius attached\n  std::vector<Atom>::const_iterator res =\n    std::find_if(atoms.begin(), atoms.end(), invalid);\n  if (res != atoms.end()) {\n    std::cout << molecule_ << std::endl;\n    PCMSOLVER_ERROR(\"Some atoms do not have a radius attached. Please specify a radius for all atoms (see http://pcmsolver.readthedocs.org/en/latest/users/input.html)!\", BOOST_CURRENT_FUNCTION);\n  }\n}\n\ncavityData Input::cavityParams()\n{\n    if (cavData_.empty) {\n        cavData_ = cavityData(molecule_, area_, probeRadius_, minDistance_, derOrder_, minimalRadius_,\n                        patchLevel_, coarsity_, cavFilename_, dyadicFilename_);\n    }\n    return cavData_;\n}\n\ngreenData Input::insideGreenParams()\n{\n    if (insideGreenData_.empty) {\n        int profile = profilePolicy(\"UNIFORM\");\n        insideGreenData_ = greenData(derivativeInsideType_, integratorType_, profile, epsilonInside_, integratorScaling_);\n    }\n    return insideGreenData_;\n}\n\ngreenData Input::outsideStaticGreenParams()\n{\n    if (outsideStaticGreenData_.empty) {\n        int profile = profilePolicy(\"UNIFORM\");\n        outsideStaticGreenData_ = greenData(derivativeOutsideType_,\n                                            integratorType_, profile,  epsilonStaticOutside_, integratorScaling_);\n        if (not hasSolvent_) {\n           outsideStaticGreenData_.howProfile = profileType_;\n           outsideStaticGreenData_.epsilon1 = epsilonStatic1_;\n           outsideStaticGreenData_.epsilon2 = epsilonStatic2_;\n           outsideStaticGreenData_.center   = center_;\n           outsideStaticGreenData_.width    = width_;\n           outsideStaticGreenData_.origin   << origin_[0], origin_[1], origin_[2];\n           outsideStaticGreenData_.maxL = maxL_;\n        }\n    }\n    return outsideStaticGreenData_;\n}\n\ngreenData Input::outsideDynamicGreenParams()\n{\n    if (outsideDynamicGreenData_.empty) {\n        int profile = profilePolicy(\"UNIFORM\");\n        outsideDynamicGreenData_ = greenData(derivativeOutsideType_,\n                                             integratorType_, profile, epsilonDynamicOutside_, integratorScaling_);\n        if (not hasSolvent_) {\n           outsideDynamicGreenData_.howProfile  = profileType_;\n           outsideDynamicGreenData_.epsilon1 = epsilonDynamic1_;\n           outsideDynamicGreenData_.epsilon2 = epsilonDynamic2_;\n           outsideDynamicGreenData_.center   = center_;\n           outsideDynamicGreenData_.width    = width_;\n           outsideDynamicGreenData_.origin   << origin_[0], origin_[1], origin_[2];\n           outsideDynamicGreenData_.maxL = maxL_;\n        }\n    }\n    return outsideDynamicGreenData_;\n}\n\nsolverData Input::solverParams()\n{\n    if (solverData_.empty) {\n        solverData_ = solverData(correction_, equationType_, hermitivitize_);\n    }\n    return solverData_;\n}\n\nint derivativeTraits(const std::string & name)\n{\n    static std::map<std::string, int> mapStringToInt;\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"NUMERICAL\", 0));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"DERIVATIVE\", 1));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"GRADIENT\", 2));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"HESSIAN\", 3));\n\n    return mapStringToInt.find(name)->second;\n}\n\nint integratorPolicy(const std::string & name)\n{\n    static std::map<std::string, int> mapStringToInt;\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"COLLOCATION\", 0));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"NUMERICAL\", 1));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"PURISIMA\", 2));\n\n    return mapStringToInt.find(name)->second;\n}\n\nint profilePolicy(const std::string & name)\n{\n    static std::map<std::string, int> mapStringToInt;\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"TANH\", 0));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"ERF\", 1));\n\n    return mapStringToInt.find(name)->second;\n}\n\nint integralEquation(const std::string & name)\n{\n    static std::map<std::string, int> mapStringToInt;\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"FIRSTKIND\",0));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"SECONDKIND\", 1));\n    mapStringToInt.insert(std::map<std::string, int>::value_type(\"FULL\", 2));\n\n    return mapStringToInt.find(name)->second;\n}\n", "meta": {"hexsha": "e1867e3c9b0c44a1a95b25c0c0f706bf4fd195dd", "size": 16640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/interface/Input.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/interface/Input.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/interface/Input.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2528735632, "max_line_length": 194, "alphanum_fraction": 0.6662259615, "num_tokens": 4225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.039048297199379224, "lm_q1q2_score": 0.01891421748830804}}
{"text": "/*\n * Copyright (c) 2017, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *    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// Defines the InvertedPendulumState struct.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef RL_ENVIRONMENT_INVERTED_PENDULUM_STATE_H\n#define RL_ENVIRONMENT_INVERTED_PENDULUM_STATE_H\n\n#include \"../util/types.hpp\"\n\n#include <glog/logging.h>\n#include <boost/functional/hash.hpp>\n#include <stddef.h>\n#include <math.h>\n#include <random>\n\n#ifdef SYSTEM_OSX\n#include <GLUT/glut.h>\n#endif\n\n#ifdef SYSTEM_LINUX\n#include <GL/glut.h>\n#endif\n\nnamespace rl {\n\n  struct InvertedPendulumState {\n    // Angle from the positive x-axis, and its derivative.\n    double theta_;\n    double omega_;\n\n    // Random number generator for initialization.\n    static std::random_device rd_;\n    static std::default_random_engine rng_;\n\n    // Constructor/destructor.\n    ~InvertedPendulumState() {}\n    InvertedPendulumState(double theta, double omega)\n      : theta_(theta), omega_(omega) {}\n    InvertedPendulumState()\n      : theta_(M_PI_2), omega_(0.0) {\n      // Reset randomly.\n      std::uniform_real_distribution<double> unif_theta(0.1 * M_PI, 0.9 * M_PI);\n      std::uniform_real_distribution<double> unif_omega(-0.25, 0.25);\n\n      theta_ = unif_theta(rng_);\n      omega_ = unif_omega(rng_);\n    }\n\n    // Static number of dimensions.\n    static constexpr size_t FeatureDimension() { return 2; }\n\n    // Get a feature vector for this state.\n    void Features(VectorXd& features) const {\n      CHECK_EQ(features.size(), FeatureDimension());\n\n      features(0) = theta_;\n      features(1) = omega_;\n    }\n\n    // (In)equality operators. Note that these are not exactly transitive,\n    // but rather are intended to simplify routine comparisons.\n    bool operator==(const InvertedPendulumState& rhs) const {\n      return (std::abs(theta_ - rhs.theta_) < 1e-8 &&\n              std::abs(omega_ - rhs.omega_) < 1e-8);\n    }\n\n    bool operator!=(const InvertedPendulumState& rhs) const {\n      return (std::abs(theta_ - rhs.theta_) >= 1e-8 ||\n              std::abs(omega_ - rhs.omega_) >= 1e-8);\n    }\n\n    // OpenGL visualization. Must provide pendulum arm length and ball radius.\n    void Visualize(double arm_length, double ball_radius) const {\n      const size_t kNumVertices = 100;\n\n      // Extract current position on xy plane.\n      const GLfloat current_x = arm_length * std::cos(theta_);\n      const GLfloat current_y = arm_length * std::sin(theta_);\n\n      // Draw the arm first. Arm will be drawn as a narrow rectangle from the\n      // origin to the center of the ball.\n      const GLfloat arm_width = 0.25 * ball_radius;\n      glBegin(GL_POLYGON);\n      glColor4f(0.3, 0.3, 0.3, 0.5);\n      // Bottom left, bottom right, top right, top left.\n      glVertex2f(-0.5 * arm_width * std::sin(theta_),\n                 0.5 * arm_width * std::cos(theta_));\n      glVertex2f(0.5 * arm_width * std::sin(theta_),\n                 -0.5 * arm_width * std::cos(theta_));\n      glVertex2f(current_x + 0.5 * arm_width * std::sin(theta_),\n                 current_y - 0.5 * arm_width * std::cos(theta_));\n      glVertex2f(current_x - 0.5 * arm_width * std::sin(theta_),\n                 current_y + 0.5 * arm_width * std::cos(theta_));\n      glEnd();\n\n      // Now draw the ball.\n      glBegin(GL_POLYGON);\n      glColor4f(0.0, 0.8, 0.2, 0.5);\n      for (size_t ii = 0; ii < kNumVertices; ii++) {\n        const GLfloat angle = 2.0 * M_PI *\n          static_cast<GLfloat>(ii) / static_cast<GLfloat>(kNumVertices);\n        glVertex2f(current_x + ball_radius * std::cos(angle),\n                   current_y + ball_radius * std::sin(angle));\n      }\n      glEnd();\n    }\n\n    // Hash functor. Should not really ever need to hash a pendulum state,\n    // but we provide this functor just in case.\n    struct Hash {\n      size_t operator()(const InvertedPendulumState& state) const {\n        size_t seed = 0;\n        boost::hash_combine(seed, boost::hash_value(state.theta_));\n        boost::hash_combine(seed, boost::hash_value(state.omega_));\n\n        return seed;\n      }\n    }; //\\struct Hash\n  }; //\\struct InvertedPendulumState\n}  //\\namespace rl\n\n#endif\n", "meta": {"hexsha": "85ff51f2339b81400b28627f3bdf54c71cad964c", "size": 5958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/environment/inverted_pendulum_state.hpp", "max_stars_repo_name": "dfridovi/rl", "max_stars_repo_head_hexsha": "41684df8d55d1e64947f9b9273e19d19b5de8110", "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/environment/inverted_pendulum_state.hpp", "max_issues_repo_name": "dfridovi/rl", "max_issues_repo_head_hexsha": "41684df8d55d1e64947f9b9273e19d19b5de8110", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T23:34:46.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-24T15:20:54.000Z", "max_forks_repo_path": "include/environment/inverted_pendulum_state.hpp", "max_forks_repo_name": "dfridovi/rl", "max_forks_repo_head_hexsha": "41684df8d55d1e64947f9b9273e19d19b5de8110", "max_forks_repo_licenses": ["BSD-3-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.0062111801, "max_line_length": 80, "alphanum_fraction": 0.6550855992, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.040845716639684206, "lm_q1q2_score": 0.018830560733930683}}
{"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_MORTON_DENSE_INCLUDE\n#define MTL_MORTON_DENSE_INCLUDE\n\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <boost/numeric/mtl/utility/common_include.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/matrix/crtp_base_matrix.hpp>\n#include <boost/numeric/mtl/matrix/base_sub_matrix.hpp>\n#include <boost/numeric/mtl/detail/contiguous_memory_block.hpp>\n#include <boost/numeric/mtl/detail/dilated_int.hpp>\n#include <boost/numeric/mtl/utility/iterator_adaptor.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/matrix/mat_expr.hpp>\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/operation/compute_factors.hpp>\n#include <boost/numeric/mtl/operation/clone.hpp>\n\n#ifdef MTL_WITH_INITLIST\n# include <initializer_list>\n#endif\n\n\nnamespace mtl { namespace matrix {\n\n// Helper type\nstruct morton_dense_sub_ctor {};\n\ntemplate <std::size_t BitMask>\nstruct morton_dense_key\n{\n    typedef std::size_t                               size_type;\n    typedef dilated_int<std::size_t, BitMask, true>   dilated_row_t;\n    typedef dilated_int<std::size_t, ~BitMask, true>  dilated_col_t; \n    typedef morton_dense_key                          self;\n\n    morton_dense_key(size_type my_row, size_type my_col) \n\t: my_row(my_row), my_col(my_col), dilated_row(my_row), dilated_col(my_col)\n    {}\n\n    bool operator== (self const& x) const\n    {\n\treturn my_row == x.my_row && my_col == x.my_col;\n    }\n\n    bool operator!= (self const& x)\n    {\n\treturn !(*this == x);\n    }\n\n    size_type row() const\n    {\n\treturn my_row;\n    }\n\n    size_type col() const\n    {\n\treturn my_col;\n    }\n\n    self& advance_row(int row_inc)\n    {\n\tdilated_row.advance(row_inc);\n\t// potential addition of signed and unsigned\n\tmy_row+= row_inc;\n\treturn *this;\n    }\n\n    self& advance_col(int col_inc)\n    {\n\tdilated_col.advance(col_inc);\n\t// potential addition of signed and unsigned\n\tmy_col+= col_inc;\n\treturn *this;\n    }\n\n    self& advance(int row_inc, int col_inc)\n    {\n\tadvance_row(row_inc);\n\tadvance_col(col_inc);\n\treturn *this;\n    }\n\npublic:\n    size_type                    my_row, my_col;   \n    dilated_row_t                dilated_row;\n    dilated_col_t                dilated_col; \n};\n\ntemplate <std::size_t BitMask>\nstruct morton_dense_el_cursor \n  : public morton_dense_key<BitMask>\n{\n    typedef std::size_t                               size_type;\n    typedef dilated_int<std::size_t, ~BitMask, true>  dilated_col_t; \n    typedef morton_dense_el_cursor                    self;\n    typedef morton_dense_key<BitMask>                 base;\n    typedef base                                      key_type;\n\n    morton_dense_el_cursor(size_type my_row, size_type my_col, size_type num_cols) \n\t: base(my_row, my_col), num_cols(num_cols) \n    {}\n\n    self& operator++ ()\n    {\n\t++this->my_col; ++this->dilated_col;\n\tif (this->my_col == num_cols) {\n\t    this->my_col= 0; this->dilated_col= dilated_col_t(0);\n\t    ++this->my_row; ++this->dilated_row;\n\t}\n\treturn *this;\n    }\n\n    base& operator* ()\n    {\n\treturn *this;\n    }\n\n    const base& operator* () const\n    {\n\treturn *this;\n    }\n\nprotected:\n    size_t                       num_cols;\n};\n\ntemplate <std::size_t BitMask>\nstruct morton_dense_row_cursor \n    : public morton_dense_key<BitMask>\n{\n    typedef std::size_t                               size_type;\n    typedef morton_dense_row_cursor                   self;\n    typedef morton_dense_key<BitMask>                 base;\n    typedef base                                      key_type;\n\n    morton_dense_row_cursor(size_type my_row, size_type my_col) \n\t: base(my_row, my_col)\n    {}\n\n    self& operator++ ()\n    {\n\t++this->my_row; ++this->dilated_row;\n\treturn *this;\n    }\n\n    self& operator+=(int inc) \n    {\n\tthis->advance_row(inc);\n\treturn *this;\n    }\n\n    self& operator-- ()\n    {\n\t--this->my_row; --this->dilated_row;\n\treturn *this;\n    }\n\n    self& operator-=(int dec) \n    {\n\tthis->advance_row(-dec);\n\treturn *this;\n    }\n\n    self operator+ (int inc) const\n    {\n\tself tmp(*this);\n\ttmp.advance_row(inc);\n\treturn tmp;\n    }\n\n    base& operator* ()\n    {\n\treturn *this;\n    }\n\n    const base& operator* () const\n    {\n\treturn *this;\n    }\n};\n\ntemplate <std::size_t BitMask>\nstruct morton_dense_col_cursor \n    : public morton_dense_key<BitMask>\n{\n    typedef std::size_t                               size_type;\n    typedef morton_dense_col_cursor                   self;\n    typedef morton_dense_key<BitMask>                 base;\n    typedef base                                      key_type;\n\n    morton_dense_col_cursor(size_type my_row, size_type my_col) \n\t: base(my_row, my_col)\n    {}\n\n    self& operator++ ()\n    {\n\t++this->my_col; ++this->dilated_col;\n\treturn *this;\n    }\n\n    self& operator+=(int inc) \n    {\n\tthis->advance_col(inc);\n\treturn *this;\n    }\n\n    self& operator-- ()\n    {\n\t--this->my_col; --this->dilated_col;\n\treturn *this;\n    }\n\n    self& operator-=(int dec) \n    {\n\tthis->advance_col(-dec);\n\treturn *this;\n    }\n\n    self operator+ (int inc) const\n    {\n\tself tmp(*this);\n\ttmp.advance_col(inc);\n\treturn tmp;\n    }\n\n    base& operator* ()\n    {\n\treturn *this;\n    }\n\n    const base& operator* () const\n    {\n\treturn *this;\n    }\n};\n\n\ntemplate <typename Matrix>\nstruct morton_dense_row_const_iterator\n    : utilities::const_iterator_adaptor<typename mtl::traits::const_value<Matrix>::type, morton_dense_row_cursor<Matrix::mask>,\n\t\t\t\t\ttypename Matrix::value_type>\n{\n    static const std::size_t                          mask= Matrix::mask;\n    typedef morton_dense_row_cursor<mask>               cursor_type;\n    typedef typename mtl::traits::const_value<Matrix>::type  map_type;\n    typedef typename Matrix::value_type                 value_type;\n    typedef typename Matrix::size_type                  size_type;\n    typedef utilities::const_iterator_adaptor<map_type, cursor_type, value_type> base;\n    \n    morton_dense_row_const_iterator(const Matrix& matrix, size_type row, size_type col)\n\t: base(map_type(matrix), cursor_type(row, col))\n    {}\n};\n\n\ntemplate <typename Matrix>\nstruct morton_dense_row_iterator\n    : utilities::iterator_adaptor<typename mtl::traits::value<Matrix>::type, morton_dense_row_cursor<Matrix::mask>,\n\t\t\t\t  typename Matrix::value_type>\n{\n    static const std::size_t                          mask= Matrix::mask;\n    typedef morton_dense_row_cursor<mask>               cursor_type;\n    typedef typename mtl::traits::value<Matrix>::type   map_type;\n    typedef typename Matrix::value_type                 value_type;\n    typedef typename Matrix::size_type                  size_type;\n    typedef utilities::iterator_adaptor<map_type, cursor_type, value_type> base;\n    \n    morton_dense_row_iterator(Matrix& matrix, size_type row, size_type col)\n\t:  base(map_type(matrix), cursor_type(row, col))\n    {}\n};\n\n\ntemplate <typename Matrix>\nstruct morton_dense_col_const_iterator\n    : utilities::const_iterator_adaptor<typename mtl::traits::const_value<Matrix>::type, morton_dense_col_cursor<Matrix::mask>,\n\t\t\t\t\ttypename Matrix::value_type>\n{\n    static const std::size_t                          mask= Matrix::mask;\n    typedef morton_dense_col_cursor<mask>               cursor_type;\n    typedef typename mtl::traits::const_value<Matrix>::type  map_type;\n    typedef typename Matrix::value_type                 value_type;\n    typedef typename Matrix::size_type                  size_type;\n    typedef utilities::const_iterator_adaptor<map_type, cursor_type, value_type> base;\n    \n    morton_dense_col_const_iterator(const Matrix& matrix, size_type row, size_type col)\n\t: base(map_type(matrix), cursor_type(row, col))\n    {}\n};\n\n\ntemplate <typename Matrix>\nstruct morton_dense_col_iterator\n    : utilities::iterator_adaptor<typename mtl::traits::value<Matrix>::type, morton_dense_col_cursor<Matrix::mask>,\n\t\t\t\t  typename Matrix::value_type>\n{\n    static const std::size_t                          mask= Matrix::mask;\n    typedef morton_dense_col_cursor<mask>               cursor_type;\n    typedef typename mtl::traits::value<Matrix>::type   map_type;\n    typedef typename Matrix::value_type                 value_type;\n    typedef typename Matrix::size_type                  size_type;\n    typedef utilities::iterator_adaptor<map_type, cursor_type, value_type> base;\n    \n    morton_dense_col_iterator(Matrix& matrix, size_type row, size_type col)\n      : base(map_type(matrix), cursor_type(row, col))  {}    \n};\n\n\n\n/// Dense Morton-order matrix \ntemplate <typename Elt, std::size_t BitMask, typename Parameters = mtl::matrix::parameters<> >\nclass morton_dense \n  : public base_sub_matrix<Elt, Parameters>, \n    public mtl::detail::contiguous_memory_block<Elt, false>,\n    public crtp_base_matrix< morton_dense<Elt, BitMask, Parameters>, Elt, std::size_t >,\n    public mat_expr< morton_dense<Elt, BitMask, Parameters> >\n{\n    typedef morton_dense                                               self;\n    typedef base_sub_matrix<Elt, Parameters>                           super;\n    typedef mtl::detail::contiguous_memory_block<Elt, false>           memory_base;\n    typedef crtp_matrix_assign< self, Elt, std::size_t >               assign_base;\n    typedef mat_expr< morton_dense<Elt, BitMask, Parameters> >         expr_base;\n\n  public:\n\n    typedef Parameters                        parameters;\n    typedef typename Parameters::orientation  orientation;\n    typedef typename Parameters::index        index_type;\n    typedef typename Parameters::dimensions   dim_type;\n    typedef Elt                               value_type;\n    typedef const value_type&                 const_reference;\n    typedef value_type&                       reference;\n    typedef typename parameters::size_type    size_type;\n    const static std::size_t                  mask= BitMask;\n\n    //  implement cursor for morton matrix, somewhere\n    //  also, morton indexer?\n\n    typedef morton_dense_key<BitMask>          key_type;\n    typedef morton_dense_el_cursor<BitMask>    el_cursor_type; \n    \n    typedef dilated_int<std::size_t, BitMask, true>   dilated_row_t;\n    typedef dilated_int<std::size_t, ~BitMask, true>  dilated_col_t; \n\n  protected:\n    \n    // ranges of rows and columns\n    dilated_row_t            my_begin_row, my_end_row;\n    dilated_col_t            my_begin_col, my_end_col;\n\n    // Set ranges from begin_r to end_r and begin_c to end_c\n    void set_ranges(size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n    {\n\tsuper::set_ranges(begin_r, end_r, begin_c, end_c);\n\tmy_begin_row= begin_r; my_end_row= end_r;\n\tmy_begin_col= begin_c; my_end_col= end_c;\n\tset_nnz();\n    }\n\n    // Set ranges to a num_row x num_col matrix, keeps indexing\n    void set_ranges(size_type num_rows, size_type num_cols)\n    {\n\tset_ranges(this->begin_row(), this->begin_row() + num_rows, \n\t\t   this->begin_col(), this->begin_col() + num_cols);\n    }\n\n    void init(size_type num_rows, size_type num_cols)\n    {\n\tset_ranges(num_rows, num_cols);\n\t// set_to_zero(*this);\n    }\n\n  public:\n    /// Default constructor\n    /** If compile time matrix size allocate memory. **/\n    morton_dense() : memory_base(memory_need(dim_type().num_rows(), dim_type().num_cols()))\n    {\n\tinit(dim_type().num_rows(), dim_type().num_cols());\n    }\n\n    /// Construction from run-time dimension type\n    explicit morton_dense(mtl::non_fixed::dimensions d) \n\t: memory_base(memory_need(d.num_rows(), d.num_cols()))\n    {\n\tinit(d.num_rows(), d.num_cols());\n    }\n\n    /// Construction of matrix of dimension \\p num_rows by \\p num_cols\n    morton_dense(size_type num_rows, size_type num_cols) \n\t: memory_base(memory_need(num_rows, num_cols))\n    {\n\tinit(num_rows, num_cols);\n    }\n\n    /// Construction of matrix with dimension \\p d using pointer \\p a to external data\n    explicit morton_dense(mtl::non_fixed::dimensions d, value_type* a) \n      : memory_base(a, memory_need(d.num_rows(), d.num_cols()))\n    { \n\tset_ranges(d.num_rows(), d.num_cols());\n    }\n\n    /// Construction of \\p num_rows by \\p num_cols matrix with pointer \\p a to external data\n    explicit morton_dense(size_type num_rows, size_type num_cols, value_type* a) \n      : memory_base(a, memory_need(num_rows, num_cols))\n    { \n\tset_ranges(num_rows, num_cols);\n    }\n\n    /// Construction of matrix with static dimension using pointer \\p a to external data\n    explicit morton_dense(value_type* a) \n\t: memory_base(a, memory_need(dim_type().num_rows(), dim_type().num_cols()))\n    { \n\tBOOST_ASSERT((dim_type::is_static));\n\tset_ranges(dim_type().num_rows(), dim_type().num_cols());\n    }\n\n    /// Copy constructor\n    morton_dense(const self& m) \n      : super(m), memory_base(m)\n    {\n\tset_ranges(m.num_rows(), m.num_cols());\n    }\n\n    /// Clone constructor\n    explicit morton_dense(const self& m, clone_ctor) \n      : memory_base(m, clone_ctor())\n    {\n\tinit(m.num_rows(), m.num_cols());\n\t*this= m;\n    }\n\n    /// Templated copy constructor\n    template <typename MatrixSrc>\n    explicit morton_dense(const MatrixSrc& src) \n      : memory_base(memory_need(dim_type().num_rows(), dim_type().num_cols()))\n    {\n\tinit(dim_type().num_rows(), dim_type().num_cols());\n\t*this= src;\n    }\n\n#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n    /// Constructor for initializer list \\p values \n    template <typename Value2>\n    morton_dense(std::initializer_list<std::initializer_list<Value2> > values)\n      : super(mtl::non_fixed::dimensions(values.size(), values.size()? values.begin()->size() : 0)),\n    \tmemory_base(this->num_rows() * this->num_cols()) \n    {\n    \tinit(this->num_rows(), this->num_cols());\n\t*this= values;\n    }\n#endif\n\n\n    /// Construct a sub-matrix as a view\n    explicit morton_dense(self& matrix, morton_dense_sub_ctor,\n\t\t\t  size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n      : memory_base(matrix.data, memory_need(end_r - begin_r, end_c - begin_c), true) // View constructor\n    {\n\tmatrix.check_ranges(begin_r, end_r, begin_c, end_c);\n\t\n\tif (begin_r >= end_r || begin_c >= end_c) {\n\t    set_ranges(0, 0);\n\t    return;\n\t}\n\t\n\t// Check whether sub-matrix is contigous memory block\n\t// by comparing the address of the last and the first element in the entire and the sub-matrix\n\tMTL_DEBUG_THROW_IF(&matrix[end_r-1][end_c-1] - &matrix[begin_r][begin_c] \n\t\t\t   != &matrix[end_r-begin_r-1][end_c-begin_c-1] - &matrix[0][0],\n\t\t\t   range_error(\"This sub-matrix cannot be used because it is split in memory\"));\n\t// Check with David if this is a sufficient condition (it is a necessary at least)\n\t\n\tdilated_row_t  dilated_row(begin_r);\n\tdilated_col_t  dilated_col(begin_c);\n\n\t// Set new start address within masked matrix\n\tthis->data += dilated_row.dilated_value() + dilated_col.dilated_value();\n\tset_ranges(end_r - begin_r, end_c - begin_c);\n    }\n\n    /// Change dimension to \\p num_rows by \\p num_cols\n    void change_dim(size_type num_rows, size_type num_cols)\n    {\n\tset_ranges(num_rows, num_cols);\n\tthis->realloc(memory_need(num_rows, num_cols));\n    }\n\n\n#if 0\n    // Move assignment (emulation)\n    self& operator=(self src)\n    {\n\t// Self-copy would be an indication of an error\n\tassert(this != &src);\n\n\tthis->check_dim(src.num_rows(), src.num_cols());\n\tif (this->category == memory_base::view || src.category == memory_base::view)\n\t    matrix_copy(src, *this);\n\telse\n\t    memory_base::move_assignment(src);\n\treturn *this;\n    }\n#endif\n\n\n#ifdef MTL_WITH_MOVE\n    /// Move Assignment\n    self& operator=(self&& src)\n    {\n\tthis->checked_change_dim(src.num_rows(), src.num_cols());\n\tif (this->category == memory_base::view || src.category == memory_base::view)\n\t    matrix_copy(src, *this);\n\telse\n\t    memory_base::move_assignment(src);\n\tstd::cout << \"In dense2D::move_assignment\\n\";\n\treturn *this;\n    }\n\n    /// Copy Assignment\n    self& operator=(const self& src)\n    {\n\tthis->checked_change_dim(src.num_rows(), src.num_cols());\n\t// this->check_dim(src.num_rows(), src.num_cols());\n\tmatrix_copy(src, *this);\n\treturn *this;\n    }\n#else\n    /// Copy assignment (with move emulation)\n    self& operator=(self src)\n    {\n\t// Self-copy would be an indication of an error\n\tassert(this != &src);\n\n\tthis->check_dim(src.num_rows(), src.num_cols());\n\tif (this->category == memory_base::view || src.category == memory_base::view)\n\t    matrix_copy(src, *this);\n\telse\n\t    memory_base::move_assignment(src);\n\treturn *this;\n    }\n#endif\n    \n    using assign_base::operator=;\n\n\n    value_type operator() (key_type const& key) const\n    {\n\treturn this->data[key.dilated_row.dilated_value() + key.dilated_col.dilated_value()];\n    }\n\n    void operator()(key_type const& key, value_type const& value)\n    {\n\tthis->data[key.dilated_row.dilated_value() + key.dilated_col.dilated_value()]= value;\n    }\n\n    /// Constant reference to A[row][col]\n    const_reference operator() (size_type row, size_type col) const\n    {\n\tMTL_DEBUG_THROW_IF(is_negative(row) || row >= this->num_rows() || is_negative(col) || col >= this->num_cols(), index_out_of_range());\n\treturn this->data[dilated_row_t(row).dilated_value() + dilated_col_t(col).dilated_value()];\n    }\n\n    /// Mutable reference to A[row][col]\n    value_type& operator() (size_type row, size_type col)\n    {\n\tMTL_DEBUG_THROW_IF(is_negative(row) || row >= this->num_rows() || is_negative(col) || col >= this->num_cols(), index_out_of_range());\n\treturn this->data[dilated_row_t(row).dilated_value() + dilated_col_t(col).dilated_value()];\n    }\n\n    void crop() {} ///< Delete structural zeros, only dummy here\n\n  protected:\n    void set_nnz()\n    {\n      this->my_nnz = this->num_rows() * this->num_cols();\n    }\n    \n    size_type memory_need(size_type rows, size_type cols)\n    {\n        dilated_row_t n_rows(rows - 1);\n        dilated_col_t n_cols(cols - 1);\n        return (n_rows.dilated_value() + n_cols.dilated_value() + 1);\n    }\n\n    /// Swap matrices\n    friend void swap(self& matrix1, self& matrix2)\n    {\n\tswap(static_cast<memory_base&>(matrix1), static_cast<memory_base&>(matrix2));\n\tswap(static_cast<super&>(matrix1), static_cast<super&>(matrix2));\n    }\n\n    template <typename> friend struct sub_matrix_t;    \n};\n\n\n// ================\n// Free functions\n// ================\n\n/// Number of rows\ntemplate <typename Value, std::size_t Mask, typename Parameters>\ntypename morton_dense<Value, Mask, Parameters>::size_type\ninline num_rows(const morton_dense<Value, Mask, Parameters>& matrix)\n{\n    return matrix.num_rows();\n}\n\n/// Number of columns\ntemplate <typename Value, std::size_t Mask, typename Parameters>\ntypename morton_dense<Value, Mask, Parameters>::size_type\ninline num_cols(const morton_dense<Value, Mask, Parameters>& matrix)\n{\n    return matrix.num_cols();\n}\n\n/// Matrix size, i.e. number of rows times columns\ntemplate <typename Value, std::size_t Mask, typename Parameters>\ntypename morton_dense<Value, Mask, Parameters>::size_type\ninline size(const morton_dense<Value, Mask, Parameters>& matrix)\n{\n    return matrix.num_cols() * matrix.num_rows();\n}\n\n}} // namespace mtl::matrix\n\n\n\n\n// ================\n// Range generators\n// ================\n\nnamespace mtl { namespace traits {\n\n    // VC 8.0 finds ambiguity with mtl::tag::morton_dense (I wonder why)\n    using mtl::matrix::morton_dense;\n    using mtl::matrix::morton_dense_el_cursor;\n    using mtl::matrix::morton_dense_col_cursor;\n    using mtl::matrix::morton_dense_row_cursor;\n    using mtl::matrix::morton_dense_col_const_iterator;\n    using mtl::matrix::morton_dense_row_const_iterator;\n    using mtl::matrix::morton_dense_col_iterator;\n    using mtl::matrix::morton_dense_row_iterator;\n\n    // ===========\n    // For cursors\n    // ===========\n\n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::all, morton_dense<Elt, BitMask, Parameters> >\n    {\n\ttypedef morton_dense<Elt, BitMask, Parameters>        Matrix;\n\ttypedef complexity_classes::linear_cached             complexity;\n\tstatic int const                                      level = 1;\n\ttypedef morton_dense_el_cursor<BitMask>  type;\n\ttype begin(Matrix const& matrix)\n\t{\n\t    return type(matrix.begin_row(), matrix.begin_col(), matrix.num_cols());\n\t}\n\ttype end(Matrix const& matrix)\n\t{\n\t    return type(matrix.end_row(), matrix.begin_col(), matrix.num_cols());\n\t}\n    };\n\n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::nz, morton_dense<Elt, BitMask, Parameters> >\n\t: range_generator<glas::tag::all, morton_dense<Elt, BitMask, Parameters> >\n    {};\n\n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::row, morton_dense<Elt, BitMask, Parameters> >\n\t: detail::all_rows_range_generator<morton_dense<Elt, BitMask, Parameters>, complexity_classes::linear_cached> \n    {};\n\n    // For a cursor pointing to some row give the range of elements in this row \n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::nz, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Elt, BitMask, Parameters>, glas::tag::row, 2> >\n    {\n\ttypedef morton_dense<Elt, BitMask, Parameters>                   matrix;\n\ttypedef typename Collection<matrix>::size_type                   size_type;\n\ttypedef detail::sub_matrix_cursor<matrix, glas::tag::row, 2>     cursor;\n\ttypedef complexity_classes::linear_cached                        complexity;\n\tstatic int const                                                 level = 1;\n\ttypedef morton_dense_col_cursor<BitMask>                         type;\n\t\n\ttype begin(cursor const& c) const\n\t{\n\t    return type(c.key, c.ref.begin_col());\n\t}\n\ttype end(cursor const& c) const\n\t{\n\t    return type(c.key, c.ref.end_col());\n\t}\n\ttype lower_bound(cursor const& c, size_type position) const\n\t{\n\t    return type(c.key, std::min(c.ref.end_col(), position));\n\t}\n    };\n\n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::all, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Elt, BitMask, Parameters>, glas::tag::row, 2> >\n        : range_generator<glas::tag::nz, \n\t\t\t  detail::sub_matrix_cursor<morton_dense<Elt, BitMask, Parameters>, glas::tag::row, 2> >\n    {};\n\n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::col, morton_dense<Elt, BitMask, Parameters> >\n\t: detail::all_cols_range_generator<morton_dense<Elt, BitMask, Parameters>, complexity_classes::linear_cached> \n    {};\n\n    // For a cursor pointing to some row give the range of elements in this row \n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::nz, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Elt, BitMask, Parameters>, glas::tag::col, 2> >\n    {\n\ttypedef morton_dense<Elt, BitMask, Parameters>                   matrix;\n\ttypedef typename Collection<matrix>::size_type                   size_type;\n\ttypedef detail::sub_matrix_cursor<matrix, glas::tag::col, 2>     cursor;\n\ttypedef complexity_classes::linear_cached                        complexity;\n\tstatic int const                                                 level = 1;\n\ttypedef morton_dense_row_cursor<BitMask>                         type;\n\t\n\ttype begin(cursor const& c)\n\t{\n\t    return type(c.ref.begin_row(), c.key);\n\t}\n\ttype end(cursor const& c)\n\t{\n\t    return type(c.ref.end_row(), c.key);\n\t}\n\ttype lower_bound(cursor const& c, size_type position) const\n\t{\n\t    return type(std::min(c.ref.end_row(), position), c.key);\n\t}\n    };\n\n    template <class Elt, std::size_t BitMask, class Parameters>\n    struct range_generator<glas::tag::all, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Elt, BitMask, Parameters>, glas::tag::col, 2> >\n        : range_generator<glas::tag::nz, \n\t\t\t  detail::sub_matrix_cursor<morton_dense<Elt, BitMask, Parameters>, glas::tag::col, 2> >\n    {};\n\n\n// =============\n// For iterators\n// =============\n\n    namespace detail {\n\n        template <typename OuterTag, typename Matrix, bool is_const>\n        struct morton_dense_iterator_range_generator\n        {\n\t    typedef Matrix                                                                matrix_type;\n\t    typedef typename matrix_type::size_type                                       size_type;\n\t    typedef typename matrix_type::value_type                                      value_type;\n\t    typedef typename matrix_type::parameters                                      parameters;\n\t    typedef detail::sub_matrix_cursor<matrix_type, OuterTag, 2>                   cursor;\n\n\t    typedef complexity_classes::linear_cached                                     complexity;\n\t    static int const                                                              level = 1;\n\n\t    typedef typename boost::mpl::if_<\n\t\tboost::is_same<OuterTag, glas::tag::row>\n\t      , typename boost::mpl::if_c<\n    \t            is_const \n\t\t  , morton_dense_col_const_iterator<Matrix>\n\t\t  , morton_dense_col_iterator<Matrix>\n\t\t>::type\n\t      , typename boost::mpl::if_c<\n    \t            is_const \n\t\t  , morton_dense_row_const_iterator<Matrix>\n\t\t  , morton_dense_row_iterator<Matrix>\n\t\t>::type\n\t    >::type type;  \n\n        private:\n\n\t    typedef typename boost::mpl::if_c<is_const, const Matrix&, Matrix&>::type    mref_type; \n\n\t    type begin_dispatch(cursor const& c, glas::tag::row)\n\t    {\n\t\treturn type(const_cast<mref_type>(c.ref), c.key, c.ref.begin_col());\n\t    }\n\t    \n\t    type end_dispatch(cursor const& c, glas::tag::row)\n\t    {\n\t\treturn type(const_cast<mref_type>(c.ref), c.key, c.ref.end_col());\n\t    }\n\n\t    type begin_dispatch(cursor const& c, glas::tag::col)\n\t    {\n\t\treturn type(const_cast<mref_type>(c.ref), c.ref.begin_row(), c.key);\n\t    }\n\n\t    type end_dispatch(cursor const& c, glas::tag::col)\n\t    {\n\t\treturn type(const_cast<mref_type>(c.ref), c.ref.end_row(), c.key);\n\t    }\n\n        public:\n\n\t    type begin(cursor const& c)\n\t    {\n\t\treturn begin_dispatch(c, OuterTag());\n\t    }\n\n\t    type end(cursor const& c)\n\t    {\n\t\treturn end_dispatch(c, OuterTag());\n\t    }\t\n        };\n\n    } // namespace detail\n\n        \n    template <typename Value, std::size_t BitMask, typename Parameters, typename OuterTag>\n    struct range_generator<tag::iter::nz, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Value, BitMask, Parameters>, OuterTag, 2> >\n      : public detail::morton_dense_iterator_range_generator<OuterTag, morton_dense<Value, BitMask, Parameters>, false>\n    {};\n\n    template <typename Value, std::size_t BitMask, typename Parameters, typename OuterTag>\n    struct range_generator<tag::iter::all, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Value, BitMask, Parameters>, OuterTag, 2> >\n      : public detail::morton_dense_iterator_range_generator<OuterTag, morton_dense<Value, BitMask, Parameters>, false>\n    {};\n\n    template <typename Value, std::size_t BitMask, typename Parameters, typename OuterTag>\n    struct range_generator<tag::const_iter::nz, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Value, BitMask, Parameters>, OuterTag, 2> >\n      : public detail::morton_dense_iterator_range_generator<OuterTag, morton_dense<Value, BitMask, Parameters>, true>\n    {};\n\n    template <typename Value, std::size_t BitMask, typename Parameters, typename OuterTag>\n    struct range_generator<tag::const_iter::all, \n\t\t\t   detail::sub_matrix_cursor<morton_dense<Value, BitMask, Parameters>, OuterTag, 2> >\n      : public detail::morton_dense_iterator_range_generator<OuterTag, morton_dense<Value, BitMask, Parameters>, true>\n    {};\n\n\n}} // namespace mtl::traits\n\n\nnamespace mtl { namespace matrix {\n\n    // ==========\n    // Sub matrix\n    // ==========\n\n    template <typename Value, std::size_t BitMask, typename Parameters>\n    struct sub_matrix_t<morton_dense<Value, BitMask, Parameters> >\n    {\n        typedef morton_dense<Value, BitMask, Parameters>    matrix_type;\n        typedef matrix_type                     sub_matrix_type;\n        typedef matrix_type const               const_sub_matrix_type;\n        typedef typename matrix_type::size_type size_type;\n        \n        sub_matrix_type operator()(matrix_type& matrix, size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n        {\n    \treturn sub_matrix_type(matrix, morton_dense_sub_ctor(), begin_r, end_r, begin_c, end_c);\n        }\n\n        const_sub_matrix_type\n        operator()(matrix_type const& matrix, size_type begin_r, size_type end_r, size_type begin_c, size_type end_c)\n        {\n    \t// To minimize code duplication, we use the non-const version\n    \tsub_matrix_type tmp((*this)(const_cast<matrix_type&>(matrix), begin_r, end_r, begin_c, end_c));\n    \treturn tmp;\n        }\t\n    };\n       \n}} // mtl::matrix\n\nnamespace mtl {\n\n\tusing matrix::morton_dense;\n\n    // Enable cloning of dense matrices\n    template <typename Value, std::size_t BitMask, typename Parameters>\n    struct is_clonable< matrix::morton_dense<Value, BitMask, Parameters> > : boost::mpl::true_ {};\n        \n} // namespace mtl\n\n#endif // MTL_MORTON_DENSE_INCLUDE\n", "meta": {"hexsha": "f65a876a98a7fa53ad92df86bf45efea110b5429", "size": 29513, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/matrix/morton_dense.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/matrix/morton_dense.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/matrix/morton_dense.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6110497238, "max_line_length": 134, "alphanum_fraction": 0.6572357944, "num_tokens": 7165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.04084571386669168, "lm_q1q2_score": 0.018830559455534603}}
{"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_PROBLEMS_ORS2016_HH\n#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_ORS2016_HH\n\n#include <iostream>\n#include <vector>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/stuff/functions/checkerboard.hh>\n#include <dune/stuff/playground/functions/indicator.hh>\n\n#include <dune/pymor/functions/default.hh>\n\n#include \"default.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Problems {\nnamespace internal {\n\n\ntemplate< class E, class D, class R >\nclass BatteryGeometry\n{\n  typedef Problems::Default< E, D, 3, R, 1 >                   ProblemType;\n  typedef typename ProblemType::DomainType                     DomainType;\n  typedef Stuff::LocalizableFunctionInterface< E, D, 3, R, 1 > NonparametricFunctionType;\n  typedef typename ProblemType::DiffusionFactorType            DiffusionFactorType;\n\npublic:\n  BatteryGeometry(const std::string& filename,\n                  const DomainType& lower_left,\n                  const DomainType& upper_right,\n                  const Stuff::Common::FieldVector< size_t, 3 >& num_elements,\n                  const std::string& separator_domain,\n                  const std::string& name)\n  {\n    // Interpretation of the data as int:\n    //    enum Subdomain\n    //    {\n    //      ANODE,      // 0\n    //      CATHODE,    // 1\n    //      CC_ANODE,   // 2\n    //      CC_CATHODE, // 3\n    //      ELECTROLYTE // 4\n    //    };\n    static_assert(sizeof(int) == 4, \"This is not the correct architecture, sizeof(int) should be 4!\");\n\n    size_t num_entries = 1;\n    for (size_t ii = 0; ii < 3; ++ii)\n      num_entries *= num_elements[ii];\n    std::vector< int > raw_data(num_entries);\n\n    std::ifstream file(filename, std::ifstream::binary);\n    if (!file)\n      DUNE_THROW(IOError, \"Could not open '\" << filename << \"'!\");\n    // check for the amount of data present in the file\n    file.seekg(0, file.end);\n    const auto length = file.tellg();\n    if (length != boost::numeric_cast< decltype(length) >(raw_data.size()*sizeof(int)))\n      DUNE_THROW(IOError,\n                 \"Given file '\" << filename << \"' has wrong size (should be \" << raw_data.size()*sizeof(int) << \", is \"\n                 << length << \")!\");\n    // read the actual data\n    file.seekg(0, file.beg);\n    file.read((char *)(raw_data.data()), length);\n    // check for the amount of read data\n    const auto read_data = file.gcount();\n    if (read_data != boost::numeric_cast< decltype(read_data) >(raw_data.size()*sizeof(int)))\n      DUNE_THROW(IOError,\n                 \"Could not read the correct amount from given file '\" << filename << \"' (we would like to read \"\n                 << raw_data.size()*sizeof(int) << \" and the file reported this many entries, but we could only read \"\n                 << read_data << \"data)!\");\n    if (!file)\n      DUNE_THROW(IOError, \"Failed to read from file '\" << filename << \"'!\");\n    file.close();\n\n    // create all but separator\n    typedef Stuff::Functions::Checkerboard< E, D, 3, R, 1, 1 > PiecewiseConstantFunctionType;\n    std::vector< typename PiecewiseConstantFunctionType::RangeType > data(num_entries);\n    for (size_t ii = 0; ii < num_entries; ++ii)\n      data[ii] = raw_data[ii];\n    auto battery_function = std::make_shared< PiecewiseConstantFunctionType >(lower_left, upper_right, num_elements, data, name);\n\n    // create separator\n    separator_ = std::shared_ptr< Stuff::Functions::DomainIndicator< E, D, 3, R, 1 > >(\n          Stuff::Functions::DomainIndicator< E, D, 3, R, 1 >::create(DSC::Configuration({\"0.domain\",        \"0.value\", \"name\"},\n                                                                                        {separator_domain,  \"1\",       \"SEPARATOR\"})));\n    // create one component per battery part\n    typedef Stuff::Functions::Constant< E, D, 3, R, 1, 1 >    ConstantFunctionType;\n    typedef Stuff::Functions::LevelIndicator< E, D, 3, R, 1 > LevelIndicator;\n    anode_      = std::make_shared< LevelIndicator >(battery_function, 0., 0., 1., \"ANODE\");\n    cathode_    = std::make_shared< LevelIndicator >(battery_function, 1., 1., 1., \"CATHODE\");\n    cc_anode_   = std::make_shared< LevelIndicator >(battery_function, 2., 2., 1., \"CC_ANODE\");\n    cc_cathode_ = std::make_shared< LevelIndicator >(battery_function, 3., 3., 1., \"CC_CATHODE\");\n    //   for the electrolyte, substract the seperator\n    electrolyte_ = std::make_shared< LevelIndicator >(\n                     Stuff::Functions::make_difference(battery_function,\n                                                       Stuff::Functions::make_product(std::make_shared< ConstantFunctionType >(4.),\n                                                                                      separator_)),\n                     4., 4., 1., \"ELECTROLYTE\");\n    // create parametric diffusion factor\n    battery_geometry_ = std::make_shared< Pymor::Functions::AffinelyDecomposableDefault< E, D, 3, R, 1 > >();\n//    battery_geometry_->register_component(anode_,       new Pymor::ParameterFunctional(\"ANODE\",       1, \"ANODE[0]\"));\n//    battery_geometry_->register_component(cathode_,     new Pymor::ParameterFunctional(\"CATHODE\",     1, \"CATHODE[0]\"));\n//    battery_geometry_->register_component(cc_anode_,    new Pymor::ParameterFunctional(\"CC_ANODE\",    1, \"CC_ANODE[0]\"));\n//    battery_geometry_->register_component(cc_cathode_,  new Pymor::ParameterFunctional(\"CC_CATHODE\",  1, \"CC_CATHODE[0]\"));\n    battery_geometry_->register_component(electrolyte_, new Pymor::ParameterFunctional(\"ELECTROLYTE\", 1, \"ELECTROLYTE[0]\"));\n//    battery_geometry_->register_component(separator_,   new Pymor::ParameterFunctional(\"SEPARATOR\",   1, \"SEPARATOR[0]\"));\n    battery_geometry_->register_affine_part(\n          Stuff::Functions::make_sum(Stuff::Functions::make_product(std::make_shared< ConstantFunctionType >(1.04),   anode_),\n          Stuff::Functions::make_sum(Stuff::Functions::make_product(std::make_shared< ConstantFunctionType >(1.58),   cathode_),\n          Stuff::Functions::make_sum(Stuff::Functions::make_product(std::make_shared< ConstantFunctionType >(238.),   cc_anode_),\n          Stuff::Functions::make_sum(Stuff::Functions::make_product(std::make_shared< ConstantFunctionType >(398.),   cc_cathode_),\n                                     Stuff::Functions::make_product(std::make_shared< ConstantFunctionType >(0.3344), separator_)))),\n                                     \"NON_ELECTROLYTE\"));\n  } // BatteryGeometry(...)\n\nprotected:\n  std::shared_ptr< NonparametricFunctionType > anode_;\n  std::shared_ptr< NonparametricFunctionType > cathode_;\n  std::shared_ptr< NonparametricFunctionType > cc_anode_;\n  std::shared_ptr< NonparametricFunctionType > cc_cathode_;\n  std::shared_ptr< NonparametricFunctionType > electrolyte_;\n  std::shared_ptr< NonparametricFunctionType > separator_;\n  std::shared_ptr< Pymor::Functions::AffinelyDecomposableDefault< E, D, 3, R, 1 > > battery_geometry_;\n}; // class BatteryGeometry\n\n\n} // namespace internal\n\n\ntemplate< class E, class D, int d, class R, int r = 1 >\nclass ORS2016\n  : public ProblemInterface< E, D, d, R, r >\n{\n  ORS2016() { static_assert(AlwaysFalse< E >::value, \"Not available for these dimensions!\"); }\n};\n\n\ntemplate< class E, class D, class R >\nclass ORS2016< E, D, 3, R, 1 >\n  : internal::BatteryGeometry< E, D, R >\n  , public Problems::Default< E, D, 3, R, 1 >\n{\n  typedef internal::BatteryGeometry< E, D, R > DataType;\n  typedef Problems::Default< E, D, 3, R, 1 > BaseType;\n  typedef ORS2016< E, D, 3, R, 1 >           ThisType;\npublic:\n  typedef typename BaseType::EntityType      EntityType;\n  typedef typename BaseType::DomainFieldType DomainFieldType;\n  static const unsigned int                  dimDomain = BaseType::dimDomain;\n  typedef typename BaseType::DomainType      DomainType;\n  typedef typename BaseType::RangeFieldType  RangeFieldType;\n  static const unsigned int                  dimRange = BaseType::dimRange;\n  using typename BaseType::FunctionType;\n  using typename BaseType::DiffusionFactorType;\n  using typename BaseType::DiffusionTensorType;\n\n  static const bool available = true;\n\n  static std::string static_id()\n  {\n    return BaseType::BaseType::static_id() + \".ORS2016\";\n  }\n\n  static Stuff::Common::Configuration default_config(const std::string sub_name = \"\")\n  {\n    Stuff::Common::Configuration config;\n    for (auto sub : {\"diffusion_tensor\", \"dirichlet\", \"neumann\"})\n      config.add(BaseType::default_config().sub(sub), sub);\n    config[\"type\"] = static_id();\n    config[\"diffusion_factor.filename\"]    = \"geometry\";\n    config[\"diffusion_factor.lower_left\"]  = \"[0.0 0.0 0.0]\";\n    config[\"diffusion_factor.upper_right\"] = \"[0.0184 0.008 0.008]\";\n    config[\"diffusion_factor.num_elements\"] = \"[46 20 20]\";\n    config[\"diffusion_factor.name\"] = \"battery_geometry\";\n    config[\"diffusion_factor.separator\"] = \"[0.0084 0.01; 0 0.008; 0 0.008]\";\n    config[\"force.value\"] = \"1\";\n    if (sub_name.empty())\n      return config;\n    else {\n      Stuff::Common::Configuration tmp;\n      tmp.add(config, sub_name);\n      return tmp;\n    }\n  } // ... default_config(...)\n\n  static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),\n                                            const std::string sub_name = static_id())\n  {\n    const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n    const Stuff::Common::Configuration def_cfg = default_config();\n    return DSC::make_unique< ThisType >(cfg.get(\"diffusion_factor.filename\", def_cfg.get<std::string>(\"diffusion_factor.filename\")),\n                                        cfg.get(\"diffusion_factor.lower_left\",\n                                                def_cfg.get<DomainType>(\"diffusion_factor.lower_left\")),\n                                        cfg.get(\"diffusion_factor.upper_right\",\n                                                def_cfg.get<DomainType>(\"diffusion_factor.upper_right\")),\n                                        cfg.get(\"diffusion_factor.num_elements\",\n                                                def_cfg.get<Stuff::Common::FieldVector< size_t, 3 >>(\"diffusion_factor.num_elements\")),\n                                        cfg.get(\"diffusion_factor.separator\",\n                                                def_cfg.get<std::string>(\"diffusion_factor.separator\")),\n                                        cfg.get(\"diffusion_factor.name\",\n                                                def_cfg.get<std::string>(\"diffusion_factor.name\")),\n                                        cfg.get(\"force.value\",\n                                                def_cfg.get<RangeFieldType>(\"force.value\")),\n                                        BaseType::create_matrix_function(\"diffusion_tensor\", cfg),\n                                        BaseType::create_vector_function(\"dirichlet\", cfg),\n                                        BaseType::create_vector_function(\"neumann\", cfg));\n  } // ... create(...)\n\n  ORS2016(const std::string& filename,\n          const DomainType& lower_left,\n          const DomainType& upper_right,\n          const Stuff::Common::FieldVector< size_t, 3 >& num_elements,\n          const std::string& separator,\n          const std::string& name,\n          const RangeFieldType& force_value,\n          const std::shared_ptr< const DiffusionTensorType >& diff_ten,\n          const std::shared_ptr< const FunctionType >& dir,\n          const std::shared_ptr< const FunctionType >& neum)\n    : DataType(filename, lower_left, upper_right, num_elements, separator, name)\n    , BaseType(DataType::battery_geometry_,\n               diff_ten,\n               std::make_shared< Pymor::Functions::AffinelyDecomposableDefault< E, D, 3, R, 1 > >(\n                  Stuff::Functions::make_product(std::make_shared< Stuff::Functions::Constant< E, D, 3, R, 1 > >(force_value),\n                                                 Stuff::Functions::make_sum(DataType::anode_, DataType::cathode_),\n                                                 \"force\")),\n               dir,\n               neum)\n  {}\n}; // class ORS2016< ..., 3, ... 1 >\n\n\n} // namespace Problems\n} // namespace LinearElliptic\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH\n", "meta": {"hexsha": "d9a7840d1a6db4e976df419e1d12e734a87c4e93", "size": 12482, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/problems/ORS2016.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/problems/ORS2016.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/problems/ORS2016.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": 50.5344129555, "max_line_length": 135, "alphanum_fraction": 0.6159269348, "num_tokens": 2997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.051845469946048134, "lm_q1q2_score": 0.01881830903610826}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\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 ecb.hpp\n    \\brief European Central Bank reserve maintenance date functions\n*/\n\n#ifndef quantlib_ecb_hpp\n#define quantlib_ecb_hpp\n\n#include <ql/time/date.hpp>\n#include <set>\n#include <vector>\n\nnamespace QuantLib {\n\n    //! European Central Bank reserve maintenance dates\n    struct ECB {\n\n        static const std::set<Date>& knownDates();\n        static void addDate(const Date& d);\n        static void removeDate(const Date& d);\n\n        //! maintenance period start date in the given month/year\n        static Date date(Month m,\n                         Year y) { return nextDate(Date(1, m, y) - 1); }\n\n        /*! returns the ECB date for the given ECB code\n            (e.g. March xxth, 2013 for MAR10).\n\n            \\warning It raises an exception if the input\n                     string is not an ECB code\n        */\n        static Date date(const std::string& ecbCode,\n                         const Date& referenceDate = Date());\n\n        /*! returns the ECB code for the given date\n            (e.g. MAR10 for March xxth, 2010).\n\n            \\warning It raises an exception if the input\n                     date is not an ECB date\n        */\n        static std::string code(const Date& ecbDate);\n\n        //! next maintenance period start date following the given date\n        static Date nextDate(const Date& d = Date());\n\n        //! next maintenance period start date following the given ECB code\n        static Date nextDate(const std::string& ecbCode,\n                             const Date& referenceDate = Date()) {\n            return nextDate(date(ecbCode, referenceDate));\n        }\n\n        //! next maintenance period start dates following the given date\n        static std::vector<Date> nextDates(const Date& d = Date());\n\n        //! next maintenance period start dates following the given code\n        static std::vector<Date> nextDates(const std::string& ecbCode,\n                                           const Date& referenceDate = Date()) {\n            return nextDates(date(ecbCode, referenceDate));\n        }\n\n        /*! returns whether or not the given date is\n            a maintenance period start date */\n        static bool isECBdate(const Date& d) {\n            Date date = nextDate(d-1);\n            return d==date;\n        }\n\n        //! returns whether or not the given string is an ECB code\n        static bool isECBcode(const std::string& in);\n\n        //! next ECB code following the given date\n        static std::string nextCode(const Date& d = Date()) {\n            return code(nextDate(d));\n        }\n\n        //! next ECB code following the given code\n        static std::string nextCode(const std::string& ecbCode);\n\n    };\n\n}\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2009, 2011 Ferdinando Ametrano\n Copyright (C) 2015 Paolo Mazzocchi\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/settings.hpp>\n#include <ql/utilities/dataparsers.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/algorithm/string/case_conv.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n#include <algorithm>\n\nusing boost::algorithm::to_upper_copy;\nusing std::string;\n\nnamespace QuantLib {\n\n    static std::set<Date> knownDateSet;\n\n    inline const std::set<Date>& ECB::knownDates() {\n\n        // one-off inizialization\n        static const Date::serial_type knownDatesArray[] = {\n              38371, 38391, 38420, 38455, 38483, 38511, 38546, 38574, 38602, 38637, 38665, 38692 // 2005\n            , 38735, 38756, 38784, 38819, 38847, 38883, 38910, 38938, 38966, 39001, 39029, 39064 // 2006\n            , 39099, 39127, 39155, 39190, 39217, 39246, 39274, 39302, 39337, 39365, 39400, 39428 // 2007\n            , 39463, 39491, 39519, 39554, 39582, 39610, 39638, 39673, 39701, 39729, 39764, 39792 // 2008\n            , 39834, 39855, 39883, 39911, 39946, 39974, 40002, 40037, 40065, 40100, 40128, 40155 // 2009\n            , 40198, 40219, 40247, 40282, 40310, 40345, 40373, 40401, 40429, 40464, 40492, 40520 // 2010\n            , 40562, 40583, 40611, 40646, 40674, 40709, 40737, 40765, 40800, 40828, 40856, 40891 // 2011\n            // http://www.ecb.europa.eu/press/pr/date/2011/html/pr110520.en.html\n            , 40926, 40954, 40982, 41010, 41038, 41073, 41101, 41129, 41164, 41192, 41227, 41255 // 2012\n            , 41290, 41318, 41346, 41374, 41402, 41437, 41465, 41493, 41528, 41556, 41591, 41619 // 2013\n            // http://www.ecb.europa.eu/press/pr/date/2013/html/pr130610.en.html\n            , 41654, 41682, 41710, 41738, 41773, 41801, 41829, 41864, 41892, 41920, 41955, 41983 // 2014\n            // http://www.ecb.europa.eu/press/pr/date/2014/html/pr140717_1.en.html\n            , 42032, 42074, 42116, 42165, 42207, 42256, 42305, 42347// 2015\n            // https://www.ecb.europa.eu/press/pr/date/2015/html/pr150622.en.html\n            , 42396, 42445, 42487, 42529, 42578, 42627, 42669, 42718 // 2016\n            // https://www.ecb.europa.eu/press/calendars/reserve/html/index.en.html\n            , 42760, 42809, 42858, 42900, 42942, 42991, 43040, 43089 //2017\n        };\n        if (knownDateSet.empty()) {\n            Size n = sizeof(knownDatesArray)/sizeof(Date::serial_type);\n            for (Size i=0; i<n; ++i)\n                knownDateSet.insert(Date(knownDatesArray[i]));\n        }\n\n        return knownDateSet;\n    }\n\n    inline void ECB::addDate(const Date& d) {\n        knownDates(); // just to ensure inizialization\n        knownDateSet.insert(d);\n    }\n\n    inline void ECB::removeDate(const Date& d) {\n        knownDates(); // just to ensure inizialization\n        knownDateSet.erase(d);\n    }\n\n    inline Date ECB::date(const string& ecbCode,\n                   const Date& refDate) {\n\n        QL_REQUIRE(isECBcode(ecbCode),\n                   ecbCode << \" is not a valid ECB code\");\n\n        string code = to_upper_copy(ecbCode);\n        string monthString = code.substr(0, 3);\n        Month m;\n        if (monthString==\"JAN\")      m = January;\n        else if (monthString==\"FEB\") m = February;\n        else if (monthString==\"MAR\") m = March;\n        else if (monthString==\"APR\") m = April;\n        else if (monthString==\"MAY\") m = May;\n        else if (monthString==\"JUN\") m = June;\n        else if (monthString==\"JUL\") m = July;\n        else if (monthString==\"AUG\") m = August;\n        else if (monthString==\"SEP\") m = September;\n        else if (monthString==\"OCT\") m = October;\n        else if (monthString==\"NOV\") m = November;\n        else if (monthString==\"DEC\") m = December;\n        else QL_FAIL(\"not an ECB month (and it should have been)\");\n\n        // lexical_cast causes compilation errors with x64\n        //Year y = boost::lexical_cast<Year>(code.substr(3, 2));\n\n        Year y = io::to_integer(code.substr(3, 2));\n        Date referenceDate = (refDate != Date() ?\n                              refDate :\n                              Date(Settings::instance().evaluationDate()));\n        Year referenceYear = (referenceDate.year() % 100);\n        y += referenceDate.year() - referenceYear;\n        if (y<Date::minDate().year())\n            return ECB::nextDate(Date::minDate());\n\n        return ECB::nextDate(Date(1, m, y) - 1);\n    }\n\n    inline string ECB::code(const Date& ecbDate) {\n\n        QL_REQUIRE(isECBdate(ecbDate),\n                   ecbDate << \" is not a valid ECB date\");\n\n        std::ostringstream ECBcode;\n        unsigned int y = ecbDate.year() % 100;\n        string padding;\n        if (y < 10)\n            padding = \"0\";\n        switch(ecbDate.month()) {\n          case January:\n            ECBcode << \"JAN\" << padding << y;\n            break;\n          case February:\n            ECBcode << \"FEB\" << padding << y;\n            break;\n          case March:\n            ECBcode << \"MAR\" << padding << y;\n            break;\n          case April:\n            ECBcode << \"APR\" << padding << y;\n            break;\n          case May:\n            ECBcode << \"MAY\" << padding << y;\n            break;\n          case June:\n            ECBcode << \"JUN\" << padding << y;\n            break;\n          case July:\n            ECBcode << \"JUL\" << padding << y;\n            break;\n          case August:\n            ECBcode << \"AUG\" << padding << y;\n            break;\n          case September:\n            ECBcode << \"SEP\" << padding << y;\n            break;\n          case October:\n            ECBcode << \"OCT\" << padding << y;\n            break;\n          case November:\n            ECBcode << \"NOV\" << padding << y;\n            break;\n          case December:\n            ECBcode << \"DEC\" << padding << y;\n            break;\n          default:\n            QL_FAIL(\"not an ECB month (and it should have been)\");\n        }\n\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_ENSURE(isECBcode(ECBcode.str()),\n                  \"the result \" << ECBcode.str() <<\n                  \" is an invalid ECB code\");\n        #endif\n        return ECBcode.str();\n    }\n\n\n\n    inline Date ECB::nextDate(const Date& date) {\n        Date d = (date == Date() ?\n                  Settings::instance().evaluationDate() :\n                  date);\n\n        std::set<Date>::const_iterator i =\n            std::upper_bound(knownDates().begin(), knownDates().end(), d);\n\n        QL_REQUIRE(i!=knownDates().end(),\n                   \"ECB dates after \" << *(--knownDates().end()) << \" are unknown\");\n        return Date(*i);\n    }\n\n    inline std::vector<Date> ECB::nextDates(const Date& date) {\n        Date d = (date == Date() ?\n                  Settings::instance().evaluationDate() :\n                  date);\n\n        std::set<Date>::const_iterator i =\n            std::upper_bound(knownDates().begin(), knownDates().end(), d);\n\n        QL_REQUIRE(i!=knownDates().end(),\n                   \"ECB dates after \" << *knownDates().end() << \" are unknown\");\n        return std::vector<Date>(i, knownDates().end());\n    }\n\n\n    inline bool ECB::isECBcode(const std::string& ecbCode) {\n\n        if (ecbCode.length() != 5)\n            return false;\n\n        string code = to_upper_copy(ecbCode);\n\n        string str1(\"0123456789\");\n        string::size_type loc = str1.find(code.substr(3, 1), 0);\n        if (loc == string::npos)\n            return false;\n        loc = str1.find(code.substr(4, 1), 0);\n        if (loc == string::npos)\n            return false;\n\n        string monthString = code.substr(0, 3);\n        if (monthString==\"JAN\")      return true;\n        else if (monthString==\"FEB\") return true;\n        else if (monthString==\"MAR\") return true;\n        else if (monthString==\"APR\") return true;\n        else if (monthString==\"MAY\") return true;\n        else if (monthString==\"JUN\") return true;\n        else if (monthString==\"JUL\") return true;\n        else if (monthString==\"AUG\") return true;\n        else if (monthString==\"SEP\") return true;\n        else if (monthString==\"OCT\") return true;\n        else if (monthString==\"NOV\") return true;\n        else if (monthString==\"DEC\") return true;\n        else return false;\n    }\n\n    inline string ECB::nextCode(const std::string& ecbCode) {\n        QL_REQUIRE(isECBcode(ecbCode),\n                   ecbCode << \" is not a valid ECB code\");\n\n        string code = to_upper_copy(ecbCode);\n        std::ostringstream result;\n\n        string monthString = code.substr(0, 3);\n        if (monthString==\"JAN\")      result << \"FEB\" << code.substr(3, 2);\n        else if (monthString==\"FEB\") result << \"MAR\" << code.substr(3, 2);\n        else if (monthString==\"MAR\") result << \"APR\" << code.substr(3, 2);\n        else if (monthString==\"APR\") result << \"MAY\" << code.substr(3, 2);\n        else if (monthString==\"MAY\") result << \"JUN\" << code.substr(3, 2);\n        else if (monthString==\"JUN\") result << \"JUL\" << code.substr(3, 2);\n        else if (monthString==\"JUL\") result << \"AUG\" << code.substr(3, 2);\n        else if (monthString==\"AUG\") result << \"SEP\" << code.substr(3, 2);\n        else if (monthString==\"SEP\") result << \"OCT\" << code.substr(3, 2);\n        else if (monthString==\"OCT\") result << \"NOV\" << code.substr(3, 2);\n        else if (monthString==\"NOV\") result << \"DEC\" << code.substr(3, 2);\n        else if (monthString==\"DEC\") {\n            // lexical_cast causes compilation errors with x64\n            //Year y = boost::lexical_cast<Year>(code.substr(3, 2));\n            unsigned int y = (io::to_integer(code.substr(3, 2)) + 1) % 100;\n            string padding;\n            if (y < 10)\n                padding = \"0\";\n\n            result << \"JAN\" << padding << y;\n        } else QL_FAIL(\"not an ECB month (and it should have been)\");\n\n\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_ENSURE(isECBcode(result.str()),\n                  \"the result \" << result.str() <<\n                  \" is an invalid ECB code\");\n        #endif\n        return result.str();\n    }\n\n}\n\n\n#endif\n", "meta": {"hexsha": "b42d23a8a58ea442a240ee4c202ac4a0a16fb163", "size": 14454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/time/ecb.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/time/ecb.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/time/ecb.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 37.7389033943, "max_line_length": 104, "alphanum_fraction": 0.5760343158, "num_tokens": 3857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961687, "lm_q2_score": 0.05184546133912578, "lm_q1q2_score": 0.018818305912060497}}
{"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/affine_matrix_layer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\nnamespace caffe\n{\nnamespace ultinous\n{\n\ntemplate<typename Dtype>\nvoid AffineMatrixLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype> *> &bottom,\n                                          const vector<Blob<Dtype> *> &top)\n{\n\n  CHECK(bottom[0]->channels() == 7);\n\n  m_base_sx = this->layer_param_.affine_matrix_param().base_sx();\n  m_base_sy = this->layer_param_.affine_matrix_param().base_sy();\n\n  m_min_sx = this->layer_param_.affine_matrix_param().min_sx();\n  m_max_sx = this->layer_param_.affine_matrix_param().max_sx();\n  m_min_sy = this->layer_param_.affine_matrix_param().min_sy();\n  m_max_sy = this->layer_param_.affine_matrix_param().max_sy();\n  m_min_hx = this->layer_param_.affine_matrix_param().min_hx();\n  m_max_hx = this->layer_param_.affine_matrix_param().max_hx();\n  m_min_hy = this->layer_param_.affine_matrix_param().min_hy();\n  m_max_hy = this->layer_param_.affine_matrix_param().max_hy();\n  m_min_tx = this->layer_param_.affine_matrix_param().min_tx();\n  m_max_tx = this->layer_param_.affine_matrix_param().max_tx();\n  m_min_ty = this->layer_param_.affine_matrix_param().min_ty();\n  m_max_ty = this->layer_param_.affine_matrix_param().max_ty();\n  m_min_alpha = this->layer_param_.affine_matrix_param().min_alpha();\n  m_max_alpha = this->layer_param_.affine_matrix_param().max_alpha();\n\n  m_bias = this->layer_param_.affine_matrix_param().bias();\n\n  m_max_diff = this->layer_param_.affine_matrix_param().max_diff();\n  m_normalize_params = this->layer_param_.affine_matrix_param().normalize_params();\n  m_moving_average_fraction = 0.9999;\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  } else\n  {\n    if( m_normalize_params || m_bias )\n    {\n      int blobNum = (m_bias && m_normalize_params)?2:1;\n\n      this->blobs_.resize(blobNum);\n      vector<int> sz;\n      sz.push_back(bottom[0]->channels());\n\n      for( int i = 0; i < blobNum; ++i )\n      {\n\tthis->blobs_[i].reset(new Blob<Dtype>(sz));\n\tcaffe_set(this->blobs_[i]->count(), Dtype(0),\n\t\t  this->blobs_[i]->mutable_cpu_data());\n      }\n    }\n  }\n\n  std::vector<int> top_shape(2);\n  top_shape[0] = bottom[0]->num();\n  top_shape[1] = 6;\n  top[0]->Reshape(top_shape);\n}\n\ntemplate<typename Dtype>\nvoid AffineMatrixLayer<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] = 6;\n  top[0]->Reshape(top_shape);\n}\n\ntemplate<typename Dtype>\nvoid AffineMatrixLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype> *> &bottom,\n                                           const vector<Blob<Dtype> *> &top)\n{\n  ++m_iter;\n\n  std::vector<Dtype> batch_averages(7, 0);\n  Dtype const *averages = batch_averages.data();\n\n  if (m_normalize_params)\n  {\n\n    if (this->phase_ == TRAIN)\n    {\n      // Update running averages\n      Dtype *saved_averages = this->blobs_[0]->mutable_cpu_data();\n      for (int n = 0; n < bottom[0]->num(); ++n)\n      {\n        Dtype const *bottom_data = bottom[0]->cpu_data() + 7 * n;\n\n        for (int c = 0; c < 7; ++c)\n          saved_averages[c] = m_moving_average_fraction * saved_averages[c]\n                              + (1.0 - m_moving_average_fraction) * bottom_data[c];\n      }\n\n      if ((m_iter % 100) == 0)\n      {\n        std::cout << \"Moving averages:\";\n        for (int c = 0; c < 7; ++c)\n          std::cout << \" \" << saved_averages[c];\n        std::cout << std::endl;\n      }\n\n      // Compute batch averages\n      for (int n = 0; n < bottom[0]->num(); ++n)\n      {\n        Dtype const *bottom_data = bottom[0]->cpu_data() + 7 * n;\n\n        for (int c = 0; c < 7; ++c)\n          batch_averages[c] += bottom_data[c];\n      }\n      for (int c = 0; c < 7; ++c)\n        batch_averages[c] /= bottom[0]->num();\n\n      if ((m_iter % 100) == 0)\n      {\n        std::cout << \"Batch averages: \";\n        for (int c = 0; c < 7; ++c)\n          std::cout << \" \" << batch_averages[c];\n        std::cout << std::endl;\n      }\n    } else\n    {\n      averages = this->blobs_[0]->cpu_data();\n    }\n  }\n\n\n  if(this->phase_ == TRAIN && (m_iter % 100) == 0)\n  {\n    Dtype const * bias = this->blobs_[m_normalize_params?1:0]->cpu_data();\n    std::cout << \"Bias:\";\n    for (int c = 0; c < 7; ++c)\n      std::cout << \" \" << bias[c];\n    std::cout << std::endl;\n  }\n\n  for (int n = 0; n < bottom[0]->num(); ++n)\n  {\n    Dtype const *bottom_data = bottom[0]->cpu_data() + 7 * n;\n\n    Dtype sx = m_base_sx + bottom_data[0]; // scale param\n    Dtype sy = m_base_sy + bottom_data[1]; // scale param\n    Dtype hx = bottom_data[2] - averages[2]; // shear param\n    Dtype hy = bottom_data[3] - averages[3]; // shear param\n    Dtype tx = bottom_data[4] - averages[4];             // translate param\n    Dtype ty = bottom_data[5] - averages[5]; // translate param\n    Dtype al = bottom_data[6] - averages[6]; // alpha - rotatio angle;\n\n    if( m_bias )\n    {\n      Dtype const * bias = this->blobs_[m_normalize_params?1:0]->cpu_data();\n      sx += bias[0];\n      sy += bias[1];\n      hx += bias[2];\n      hy += bias[3];\n      tx += bias[4];\n      ty += bias[5];\n      al += bias[6];\n    }\n\n    Dtype ca = std::cos(al);\n    Dtype sa = std::sin(al);\n\n    Dtype *top_data = top[0]->mutable_cpu_data() + 6 * n;\n    top_data[0] = sx * ca - hy * sy * sa;\n    top_data[1] = hx * sx * ca - sy * sa;\n    top_data[2] = tx;\n    top_data[3] = sx * sa + hy * sy * ca;\n    top_data[4] = hx * sx * sa + sy * ca;\n    top_data[5] = ty;\n  }\n\n}\n\ntemplate<typename Dtype>\nvoid AffineMatrixLayer<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  std::vector<Dtype> batch_averages(7, 0);\n  Dtype const *averages = batch_averages.data();\n\n  if (m_normalize_params)\n  {\n    if (this->phase_ == TRAIN)\n    {\n      for (int n = 0; n < bottom[0]->num(); ++n)\n      {\n        Dtype const *bottom_data = bottom[0]->cpu_data() + 7 * n;\n\n        for (int c = 0; c < 7; ++c)\n          batch_averages[c] += bottom_data[c];\n      }\n      for (int c = 0; c < 7; ++c)\n        batch_averages[c] /= bottom[0]->channels();\n    } else\n    {\n      averages = this->blobs_[0]->cpu_data();\n    }\n  }\n\n  for (int n = 0; n < bottom[0]->num(); ++n)\n  {\n    Dtype const *bottom_data = bottom[0]->cpu_data() + 7 * n;\n\n    Dtype sx = m_base_sx + bottom_data[0]; // scale param\n    Dtype sy = m_base_sy + bottom_data[1]; // scale param\n    Dtype hx = bottom_data[2] - averages[2]; // shear param\n    Dtype hy = bottom_data[3] - averages[3]; // shear param\n    Dtype tx = bottom_data[4] - averages[4]; // translate param\n    Dtype ty = bottom_data[5] - averages[5]; // translate param\n    Dtype al = bottom_data[6] - averages[6]; // alpha - rotatio angle;\n\n    if( m_bias )\n    {\n      Dtype const * bias = this->blobs_[m_normalize_params?1:0]->cpu_data();\n      sx += bias[0];\n      sy += bias[1];\n      hx += bias[2];\n      hy += bias[3];\n      tx += bias[4];\n      ty += bias[5];\n      al += bias[6];\n    }\n\n    Dtype ca = std::cos(al);\n    Dtype sa = std::sin(al);\n\n    Dtype *bottom_diff = bottom[0]->mutable_cpu_diff() + 7 * n;\n    Dtype const *top_diff = top[0]->cpu_diff() + 6 * n;\n\n    if (sx < m_min_sx)\n      bottom_diff[0] = (sx - m_min_sx) * m_boundary_violation_step;\n    else if (sx > m_max_sx)\n      bottom_diff[0] = (sx - m_max_sx) * m_boundary_violation_step;\n    else\n      bottom_diff[0] =\n      (top_diff[0] * ca) + (top_diff[1] * hx * ca) + (top_diff[3] * sa) + (top_diff[4] * hx * sa);  // sx\n\n    if (sy < m_min_sy)\n      bottom_diff[1] = (sy - m_min_sy) * m_boundary_violation_step;\n    else if (sy > m_max_sy)\n      bottom_diff[1] = (sy - m_max_sy) * m_boundary_violation_step;\n    else\n      bottom_diff[1] =\n      (top_diff[0] * -hy * sa) + (top_diff[1] * -sa) + (top_diff[3] * hy * ca) + (top_diff[4] * ca);  // sy\n\n    if (hx < m_min_hx)\n      bottom_diff[2] = (hx - m_min_hx) * m_boundary_violation_step;\n    else if (hx > m_max_hx)\n      bottom_diff[2] = (hx - m_max_hx) * m_boundary_violation_step;\n    else\n      bottom_diff[2] = (top_diff[1] * sx * ca) + (top_diff[4] * sx * sa);  // hx\n\n    if (hy < m_min_hy)\n      bottom_diff[3] = (hy - m_min_hy) * m_boundary_violation_step;\n    else if (hy > m_max_hy)\n      bottom_diff[3] = (hy - m_max_hy) * m_boundary_violation_step;\n    else\n      bottom_diff[3] = (top_diff[0] * -sy * sa) + (top_diff[3] * sy * ca);  // hy\n\n    if (tx < m_min_tx)\n      bottom_diff[4] = (tx - m_min_tx) * m_boundary_violation_step;\n    else if (tx > m_max_tx)\n      bottom_diff[4] = (tx - m_max_tx) * m_boundary_violation_step;\n    else\n      bottom_diff[4] = top_diff[2]; // tx\n\n    if (ty < m_min_ty)\n      bottom_diff[5] = (ty - m_min_ty) * m_boundary_violation_step;\n    else if (ty > m_max_ty)\n      bottom_diff[5] = (ty - m_max_ty) * m_boundary_violation_step;\n    else\n      bottom_diff[5] = top_diff[5]; // ty\n\n    if (al < m_min_alpha)\n      bottom_diff[6] = (al - m_min_alpha) * m_boundary_violation_step;\n    else if (al > m_max_alpha)\n      bottom_diff[6] = (al - m_max_alpha) * m_boundary_violation_step;\n    else\n      bottom_diff[6] = top_diff[0] * (sx * -sa - hy * sy * ca)\n                       + top_diff[1] * (hx * sx * -sa - sy * ca)\n                       + top_diff[3] * (sx * ca + hy * sy * -sa)\n                       + top_diff[4] * (hx * sx * ca + sy * -sa);\n\n    if( m_max_diff != 0 )\n      for (int i = 0; i < 7; 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    if( m_bias )\n    {\n      Dtype * bias_diff = this->blobs_[m_normalize_params?1:0]->mutable_cpu_diff();\n      bias_diff[0] += bottom_diff[0]; // sx\n      bias_diff[1] += bottom_diff[1]; // sy\n      bias_diff[4] += bottom_diff[4]; // tx\n//      bias_diff[5] += bottom_diff[5]; // ty\n    }\n\n\n  }\n}\n\n#ifdef CPU_ONLY\n//STUB_GPU(AffineMatrixLayer);\n#endif\n\nINSTANTIATE_CLASS(AffineMatrixLayer);\n\nREGISTER_LAYER_CLASS(AffineMatrix);\n\n}  // namespace ultinous\n}  // namespace caffe\n", "meta": {"hexsha": "75912e0d449458a654baa42850ceee266b649fd2", "size": 10466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/ultinous/affine_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/affine_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/affine_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": 30.9644970414, "max_line_length": 107, "alphanum_fraction": 0.5818841964, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.03789242635798463, "lm_q1q2_score": 0.018798198899877404}}
{"text": "/**\n * @file esx_impl.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_EDGE_SUBSET_EXCLUSION_IMPL_HPP\n#define BOOST_EDGE_SUBSET_EXCLUSION_IMPL_HPP\n\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <arlib/details/arlib_utils.hpp>\n#include <arlib/routing_kernels/bidirectional_dijkstra.hpp>\n#include <arlib/routing_kernels/types.hpp>\n#include <arlib/terminators.hpp>\n#include <arlib/type_traits.hpp>\n\n#include <limits>\n#include <unordered_set>\n#include <utility>\n\n/**\n * An Alternative-Routing library for Boost.Graph\n */\nnamespace arlib {\n/**\n * Implementations details of kSPwLO algorithms\n */\nnamespace details {\n\n//===----------------------------------------------------------------------===//\n//                      ESX algorithm support classes\n//===----------------------------------------------------------------------===//\n\n/**\n * Comparator for edges priority queue.\n *\n * Given two edges @c e1 and @c e2, if <tt>prio(e1) > prio(e2)</tt> then @c e1\n * must be popped before @c e2.\n *\n * @tparam Edge A Boost::Graph edge descriptor.\n */\ntemplate <typename Edge> struct EdgePriorityComparator {\n  /**\n   * The priority of Edge\n   */\n  using Priority = std::pair<Edge, int>;\n  /**\n   * Given two edges @c e1 and @c e2, if <tt>prio(e1) > prio(e2)</tt>\n   * then @c e1 must be popped before @c e2.\n   *\n   * @param lhs first edge and its priority.\n   * @param rhs second edge and its priority.\n   * @return true if @p lhs has lower priority then @p rhs\n   * @return false otherwise.\n   */\n  bool operator()(Priority lhs, Priority rhs) const {\n    return lhs.second < rhs.second;\n  }\n};\n\n/**\n * A filter functor for Boost::filtered_graph to hide edges deleted by\n * ESX.\n *\n * @tparam Edge A Boost::Graph edge descriptor\n */\ntemplate <typename Edge> class edge_deleted_filter {\npublic:\n  /**\n   * The deleted edges map.\n   */\n  using DeletedEdgeMap = std::unordered_set<Edge, boost::hash<Edge>>;\n  /**\n   * Empty constructor, required by Boost::Graph\n   */\n  edge_deleted_filter() : deleted_edge_map{nullptr} {}\n  /**\n   * Construct a new edge_deleted_filter object filtering edges contained\n   * in @p deleted_edge_map.\n   *\n   * @param deleted_edge_map The set of deleted edges.\n   */\n  edge_deleted_filter(const DeletedEdgeMap &deleted_edge_map)\n      : deleted_edge_map{std::addressof(deleted_edge_map)} {}\n  /**\n   * @param e Edge to check.\n   * @return true if @p e is marked as deleted\n   * @return false otherwise.\n   */\n  bool operator()(const Edge &e) const {\n    return deleted_edge_map->find(e) == std::end(*deleted_edge_map);\n  }\n\nprivate:\n  const DeletedEdgeMap *deleted_edge_map;\n};\n\ntemplate <typename PMap, class Graph> class reverse_weight_functor {\npublic:\n  using Edge = typename boost::graph_traits<\n      boost::reverse_graph<Graph>>::edge_descriptor;\n  using Length = typename boost::property_traits<PMap>::value_type;\n\n  reverse_weight_functor(PMap &pmap, Graph const &G,\n                         const boost::reverse_graph<Graph> &rev_G)\n      : inner_weight{pmap}, G{G}, rev_G{rev_G} {}\n\n  reverse_weight_functor(reverse_weight_functor const &other)\n      : inner_weight{other.inner_weight}, G{other.G}, rev_G{other.rev_G} {}\n\n  const Length &operator()(const Edge &e) const {\n    auto forward_edge = get_forward_edge(e);\n\n    return inner_weight[forward_edge];\n  }\n\n  Length &operator[](const Edge &e) {\n    auto forward_edge = get_forward_edge(e);\n\n    return inner_weight[forward_edge];\n  }\n\n  const Length &operator[](const Edge &e) const {\n    auto forward_edge = get_forward_edge(e);\n\n    return inner_weight[forward_edge];\n  }\n\nprivate:\n  auto get_forward_edge(const Edge &e) const {\n    using namespace boost;\n    auto u = source(e, rev_G);\n    auto v = target(e, rev_G);\n\n    auto [forward_edge, is_valid] = edge(v, u, G);\n    assert(is_valid);\n    return forward_edge;\n  }\n\n  PMap &inner_weight;\n  const Graph &G;\n  const boost::reverse_graph<Graph> &rev_G;\n};\n\n//===----------------------------------------------------------------------===//\n//                          ESX algorithm routines\n//===----------------------------------------------------------------------===//\n/**\n * Checks whether the path from @p s to @p t contains edge @p e or not.\n *\n * @pre @p predecessor is the PredecessorMap filled by a Boost::Graph\n * shortest path algorithm such that <tt>predecessor[s] == s</tt>\n *\n * @tparam Graph A Boost::EdgeList graph\n * @tparam PredMap A Boost::PredecessorMap\n * @param s The source vertex\n * @param t The target vertex\n * @param e The edge we want to check if present in <tt>path(s -> t)</tt>\n * @param G The graph containing edge @p e\n * @param predecessor The predecessor map\n * @return true If @p e is in the computed path from @p s to @p t\n * @return false otherwise.\n */\ntemplate <typename Graph, typename PredMap,\n          typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>>\nbool shortest_path_contains_edge(Vertex s, Vertex t, Edge e, const Graph &G,\n                                 const PredMap &predecessor) {\n  auto e_s = boost::source(e, G);\n  auto e_t = boost::target(e, G);\n\n  auto v = t;\n  auto u = predecessor[v];\n  while (u != s) {\n    if (u == e_s && v == e_t) {\n      return true;\n    }\n    v = u;\n    u = predecessor[v];\n  }\n  return false;\n}\n\ntemplate <typename Graph, typename WeightMap, typename DeletedEdgeMap,\n          typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>>\nstd::optional<std::vector<Edge>>\ndijkstra_shortest_path(const Graph &G, Vertex s, Vertex t,\n                       const WeightMap &weight,\n                       DeletedEdgeMap &deleted_edge_map) {\n  using namespace boost;\n\n  // Get a graph with deleted edges filtered out\n  auto filter = edge_deleted_filter{deleted_edge_map};\n  auto filtered_G = filtered_graph(G, filter);\n\n  auto predecessor = std::vector<Vertex>(num_vertices(filtered_G), s);\n  auto vertex_id = get(vertex_index, filtered_G);\n\n  try {\n    dijkstra_shortest_paths(\n        filtered_G, s,\n        weight_map(weight)\n            .predecessor_map(make_iterator_property_map(std::begin(predecessor),\n                                                        vertex_id, s))\n            .visitor(make_dijkstra_visitor(\n                make_target_visitor(t, on_examine_vertex{}))));\n  } catch (target_found &) {\n    auto edge_list = build_edge_list_from_dijkstra(G, s, t, predecessor);\n    return std::make_optional(edge_list);\n  }\n\n  // In case t could not be found from astar_search and target_found is not\n  // thrown, return empty optional\n  return std::optional<std::vector<Edge>>{};\n}\n\n/**\n * Compute a shortest path between two vertices on a filtered graph using\n * an A* approach, provided the set of edges to filter and the heuristic.\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n * @tparam AStarHeuristic\n * @tparam DeletedEdgeMap an edge_deleted_filter::DeletedEdgeMap\n * @param G The graph\n * @param s The source vertex\n * @param t The target vertex\n * @param heuristic The A* heuristic.\n * @param deleted_edge_map The set of edges to filter from @p G\n * @return A std::optional of the list of edges from @p s to @p t if a path\n * could be found. An empty optional otherwise.\n */\ntemplate <typename Graph, typename WeightMap, typename AStarHeuristic,\n          typename DeletedEdgeMap, typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>>\nstd::optional<std::vector<Edge>>\nastar_shortest_path(const Graph &G, Vertex s, Vertex t, const WeightMap &weight,\n                    const AStarHeuristic &heuristic,\n                    DeletedEdgeMap &deleted_edge_map) {\n  using namespace boost;\n\n  // Get a graph with deleted edges filtered out\n  auto filter = edge_deleted_filter{deleted_edge_map};\n  auto filtered_G = filtered_graph(G, filter);\n\n  auto predecessor = std::vector<Vertex>(num_vertices(G), s);\n  auto vertex_id = get(vertex_index, filtered_G);\n\n  try {\n    astar_search(filtered_G, s, heuristic,\n                 predecessor_map(make_iterator_property_map(\n                                     std::begin(predecessor), vertex_id, s))\n                     .visitor(astar_target_visitor{t})\n                     .weight_map(weight));\n  } catch (target_found &) {\n    auto edge_list = build_edge_list_from_dijkstra(G, s, t, predecessor);\n    return std::make_optional(edge_list);\n  }\n  // In case t could not be found from astar_search and target_found is not\n  // thrown, return empty optional\n  return std::optional<std::vector<Edge>>{};\n}\n\ntemplate <typename Graph, typename WeightMap, typename DeletedEdgeMap,\n          typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>,\n          typename Length = length_of_t<Graph>>\nstd::optional<std::vector<Edge>>\nbidirectional_dijkstra_shortest_path(const Graph &G, Vertex s, Vertex t,\n                                     const WeightMap &weight,\n                                     DeletedEdgeMap &deleted_edge_map) {\n  using namespace boost;\n\n  // Get a graph with deleted edges filtered out\n  using FilteredGraph = boost::filtered_graph<Graph, edge_deleted_filter<Edge>>;\n  auto filter = edge_deleted_filter{deleted_edge_map};\n  const auto filtered_G = filtered_graph(G, filter);\n\n  auto index = get(vertex_index, filtered_G);\n  auto predecessor_vec = std::vector<Vertex>(num_vertices(G), s);\n  auto predecessor = make_iterator_property_map(predecessor_vec.begin(), index);\n  auto distance_vec = std::vector<Length>(num_vertices(G));\n  auto distance = make_iterator_property_map(distance_vec.begin(), index);\n\n  auto rev_G = make_reverse_graph(filtered_G);\n  using RevEdge =\n      typename graph_traits<reverse_graph<FilteredGraph>>::edge_descriptor;\n  auto rev_weight = make_function_property_map<RevEdge, Length>(\n      reverse_weight_functor{weight, filtered_G, rev_G});\n  auto rev_index = get(vertex_index, rev_G);\n\n  try {\n    bidirectional_dijkstra(filtered_G, s, t, predecessor, distance, weight,\n                           rev_G, rev_weight, rev_index);\n  } catch (target_not_found &) {\n    // In case t could not be found return empty optional\n    return std::optional<std::vector<Edge>>{};\n  }\n\n  auto edge_list = build_edge_list_from_dijkstra(G, s, t, predecessor);\n  return std::make_optional(edge_list);\n}\n\ntemplate <typename Graph, typename WeightMap, typename AStarHeuristic,\n          typename DeletedEdgeMap, typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>>\nconstexpr std::function<std::optional<std::vector<Edge>>(\n    const Graph &, Vertex, Vertex, const WeightMap &, DeletedEdgeMap &)>\nbuild_shortest_path_fn(routing_kernels algorithm, const Graph &, Vertex, Vertex,\n                       const WeightMap &, const AStarHeuristic &heuristic,\n                       DeletedEdgeMap &) {\n  switch (algorithm) {\n  case routing_kernels::astar:\n    return [&heuristic](const auto &G, auto s, auto t, const auto &weight,\n                        auto &deleted_edge_map) {\n      return astar_shortest_path(G, s, t, weight, heuristic, deleted_edge_map);\n    };\n  default:\n    throw std::invalid_argument{\"Invalid algorithm. Only [astar] \"\n                                \"allowed.\"};\n  }\n}\n\ntemplate <typename Graph, typename WeightMap, typename DeletedEdgeMap,\n          typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>>\nconstexpr std::function<std::optional<std::vector<Edge>>(\n    const Graph &, Vertex, Vertex, const WeightMap &, DeletedEdgeMap &)>\nbuild_shortest_path_fn(routing_kernels algorithm, const Graph &, Vertex, Vertex,\n                       const WeightMap &, DeletedEdgeMap &) {\n  switch (algorithm) {\n  case routing_kernels::dijkstra:\n    return [](const auto &G, auto s, auto t, const auto &weight,\n              auto &deleted_edge_map) {\n      return dijkstra_shortest_path(G, s, t, weight, deleted_edge_map);\n    };\n  case routing_kernels::bidirectional_dijkstra:\n    return [](const auto &G, auto s, auto t, const auto &weight,\n              auto &deleted_edge_map) {\n      return bidirectional_dijkstra_shortest_path(G, s, t, weight,\n                                                  deleted_edge_map);\n    };\n  default:\n    throw std::invalid_argument{\n        \"Invalid algorithm. Only [dijkstra|bidirectional_dijkstra] \"\n        \"allowed.\"};\n  }\n}\n\n/**\n * Computes the ESX priority of an edge. Quoting the reference paper:\n *\n * <blockquote>Given an edge e(a, b) on some alternative path p, let E_inc(a) be\n * the set of all incoming edges e(n_i, a) to a from some node n_i in N\\{b} and\n * E_out(b) be the set of all outgoing edges e(b, n_j) from b to some node n_j\n * in N\\{a}. First, ESX computes the set P_s which contains the shortest paths\n * from every node n_i in E_inc(a) to every node n_j in E_out(b). Then, ESX\n * defines the set P'_s which contains all paths p in P'_s that cross edge e.\n * Finally, ESX assigns a priority to edge e, denoted by prio(e), which is set\n * to cardinality of P'_s.</blockquote>\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n * @tparam AStarHeuristic\n * @tparam DeletedEdgeMap  an edge_deleted_filter::DeletedEdgeMap\n * @param G The graph\n * @param e An edge of @p G\n * @param heuristic An A* heuristic to use in performing shortest paths search.\n * @param deleted_edge_map The set of edges to filter from @p G\n * @return The priority of @p e.\n */\ntemplate <typename Graph, typename WeightMap, typename DeletedEdgeMap,\n          typename Edge = edge_of_t<Graph>,\n          typename Length = length_of_t<Graph>>\nint compute_priority(const Graph &G, const Edge &e, WeightMap &weight,\n                     const DeletedEdgeMap &deleted_edge_map) {\n  using namespace boost;\n  using Vertex = typename graph_traits<Graph>::vertex_descriptor;\n  int priority = 0;\n  auto sources = std::vector<Vertex>{};\n  auto targets = std::vector<Vertex>{};\n\n  auto a = source(e, G);\n  auto b = target(e, G);\n\n  // Compute all the n_i nodes s.t. (n_i, a) is an incoming edge of a, with n_i\n  // != b\n  for (auto in_it = in_edges(a, G).first; in_it != in_edges(a, G).second;\n       ++in_it) {\n    auto n_i = source(*in_it, G);\n    if (n_i != b) {\n      sources.push_back(n_i);\n    }\n  }\n\n  // Compute all the n_j nodes s.t. (b, n_j) is an outgoing edge of b, with n_j\n  // != a\n  for (auto out_it = out_edges(b, G).first; out_it != out_edges(b, G).second;\n       ++out_it) {\n    auto n_j = target(*out_it, G);\n    if (n_j != a) {\n      targets.push_back(n_j);\n    }\n  }\n\n  // Get a graph with deleted edges filtered out\n  auto filter = edge_deleted_filter{deleted_edge_map};\n  const auto filtered_G = filtered_graph(G, filter);\n\n  for (auto s_i : sources) {\n    for (auto t_i : targets) {\n      // Compute the shortest path from s_i to t_i\n      auto index = get(vertex_index, filtered_G);\n      auto predecessor_vec = std::vector<Vertex>(num_vertices(G), s_i);\n      auto predecessor =\n          make_iterator_property_map(predecessor_vec.begin(), index);\n      auto distance_vec = std::vector<Length>(num_vertices(G));\n      auto distance = make_iterator_property_map(distance_vec.begin(), index);\n\n      auto rev_G = make_reverse_graph(filtered_G);\n      using RevEdge =\n          typename graph_traits<reverse_graph<Graph>>::edge_descriptor;\n      auto rev_weight = make_function_property_map<RevEdge>(\n          reverse_weight_functor{weight, filtered_G, rev_G});\n      auto rev_index = get(vertex_index, rev_G);\n\n      try {\n        bidirectional_dijkstra(filtered_G, s_i, t_i, predecessor, distance,\n                               weight, rev_G, rev_weight, rev_index);\n        if (shortest_path_contains_edge(s_i, t_i, e, filtered_G, predecessor)) {\n          ++priority;\n        }\n      } catch (target_not_found &ex) {\n        // In case t could not be found do nothing\n        std::cout << \"Caught exception: \" << ex.what() << \"\\n\";\n      }\n    }\n  }\n\n  return priority;\n}\n\n/**\n * Computes the edge priorities of an alternative path.\n *\n * @pre @p edge_priorities is a vector of std::priority_queue of size al least\n * @p alt_index + 1.\n *\n * @post @c edge_priorities[alt_index] queue is filled with pairs <tt>(e,\n * priority(e))</tt>\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n * @tparam PrioritiesVector a std::vector<std::priority_queue<std::pair<Edge,\n * Priority>>>\n * @tparam AStarHeuristic\n * @tparam EdgeMap an edge_deleted_filter::DeletedEdgeMap\n * @param alternative The alternative path\n * @param edge_priorities The edge priorities vector\n * @param alt_index The index of @p edge_priorities where to store priorities\n * at.\n * @param G The graph\n * @param heuristic An A* heuristic to use in performing shortest paths search.\n * @param deleted_edges The set of edges to filter from @p G\n */\ntemplate <typename Graph, typename PrioritiesVector, typename WeightMap,\n          typename EdgeMap,\n          typename Index = typename PrioritiesVector::size_type>\nvoid init_edge_priorities(const Graph &alternative,\n                          PrioritiesVector &edge_priorities, Index alt_index,\n                          const Graph &G, const WeightMap &weight,\n                          const EdgeMap &deleted_edges) {\n  using namespace boost;\n  for (auto it = edges(alternative).first; it != edges(alternative).second;\n       ++it) {\n    // Get a reference to (u, v) in G\n    auto u = source(*it, alternative);\n    auto v = target(*it, alternative);\n    auto edge_in_G = edge(u, v, G);\n    assert(edge_in_G.second); // (u, v) must exist in G\n    auto prio_e_i = compute_priority(G, edge_in_G.first, weight, deleted_edges);\n    edge_priorities[alt_index].push(std::make_pair(edge_in_G.first, prio_e_i));\n  }\n}\n\n/**\n * Computes the edge priorities of an alternative path.\n *\n * @pre @p edge_priorities is a vector of std::priority_queue of size al least\n * @p alt_index + 1.\n *\n * @post @c edge_priorities[alt_index] queue is filled with pairs <tt>(e,\n * priority(e))</tt>\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n * @tparam PrioritiesVector a std::vector<std::priority_queue<std::pair<Edge,\n * Priority>>>\n * @tparam AStarHeuristic\n * @tparam EdgeMap an edge_deleted_filter::DeletedEdgeMap\n * @param alternative The alternative path\n * @param edge_priorities The edge priorities vector\n * @param alt_index The index of @p edge_priorities where to store priorities\n * at.\n * @param G The graph\n * @param heuristic An A* heuristic to use in performing shortest paths search.\n * @param deleted_edges The set of edges to filter from @p G\n */\ntemplate <typename PrioritiesVector, typename Graph, typename WeightMap,\n          typename EdgeMap, typename Edge = edge_of_t<Graph>,\n          typename Index = typename PrioritiesVector::size_type>\nvoid init_edge_priorities(const std::vector<Edge> &alternative,\n                          PrioritiesVector &edge_priorities, Index alt_index,\n                          const Graph &G, const WeightMap &weight,\n                          const EdgeMap &deleted_edges) {\n  for (const auto &e : alternative) {\n    auto prio_e_i = compute_priority(G, e, weight, deleted_edges);\n    edge_priorities[alt_index].push(std::make_pair(e, prio_e_i));\n  }\n}\n\n/**\n * Checks whether another alternative path can be found by ESX.\n *\n * @param overlaps The vector of overlapping factors between @c path_tmp and the\n * alternative paths.\n * @return true if a solution can still be found.\n * @return false otherwise.\n */\nbool check_feasibility(const std::vector<double> &overlaps);\n\n/**\n * Checks whether a candidate path satisfies the condition to add it the\n * the alternative paths set. That is: @f$Sim(candidate, p_i) < \\theta, \\forall\n * p_i \\in AlternativePaths@f$\n *\n * @tparam Graph A Boost::PropertyGraph having at least one edge\n *         property with tag boost::edge_weight_t.\n * @param candidate The candidate path.\n * @param alternatives The list of alternative paths.\n * @param theta The similarity threshold.\n * @return true If @p candidate is sufficiently dissimilar to all the other\n * alternative paths.\n * @return false Otherwise.\n */\ntemplate <typename Edge, typename WeightMap>\nbool check_candidate_validity(\n    const std::vector<Edge> &candidate,\n    const std::vector<std::unordered_set<Edge, boost::hash<Edge>>>\n        &alternatives,\n    WeightMap const &weight, double theta) {\n  bool candidate_is_valid = true;\n  for (const auto &alt_path : alternatives) {\n    if (compute_similarity(candidate, alt_path, weight) > theta) {\n      candidate_is_valid = false;\n      break;\n    }\n  }\n  return candidate_is_valid;\n}\n\ntemplate <typename Edge>\nvoid move_to_dnr(Edge e,\n                 std::unordered_set<Edge, boost::hash<Edge>> &deleted_edges,\n                 std::unordered_set<Edge, boost::hash<Edge>> &dnr_edges) {\n#ifndef NDEBUG\n  auto old_size = deleted_edges.size();\n#endif\n  deleted_edges.erase(e); // Reinsert e_tmp into G\n#ifndef NDEBUG\n  assert(deleted_edges.size() + 1 == old_size);\n#endif\n  dnr_edges.insert(e); // Mark e_tmp as do_not_remove\n}\n\n//===----------------------------------------------------------------------===//\n//                             ESX implementation\n//===----------------------------------------------------------------------===//\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename PriorityFunc, typename RoutingKernel, typename Terminator,\n          typename Vertex = vertex_of_t<Graph>>\nvoid esx(const Graph &G, WeightMap const &weight,\n         MultiPredecessorMap &predecessors, Vertex s, Vertex t, int k,\n         double theta, PriorityFunc &&priority_fn,\n         RoutingKernel &routing_kernel, Terminator &&terminator) {\n  using namespace boost;\n  using Edge = typename graph_traits<Graph>::edge_descriptor;\n\n  BOOST_CONCEPT_ASSERT((VertexAndEdgeListGraphConcept<Graph>));\n  BOOST_CONCEPT_ASSERT((LvaluePropertyMapConcept<WeightMap, Edge>));\n\n  // P_LO set of k paths\n  auto resPathsEdges = std::vector<std::vector<Edge>>{};\n  auto resEdges = std::vector<std::unordered_set<Edge, boost::hash<Edge>>>{};\n\n  BOOST_CONCEPT_ASSERT((VertexAndEdgeListGraphConcept<Graph>));\n  BOOST_CONCEPT_ASSERT((LvaluePropertyMapConcept<WeightMap, Edge>));\n\n  // P_LO set of k paths\n  auto resPaths = std::vector<Path<Graph>>{};\n  // Compute shortest path from s to t\n  auto sp = details::compute_shortest_path(G, weight, s, t);\n  if (!sp) {\n    auto oss = std::ostringstream{};\n    oss << \"Vertex \" << t << \" is unreachable from \" << s;\n    throw details::target_not_found{oss.str()};\n  }\n\n  // P_LO <-- {shortest path p_0(s, t)};\n  resPathsEdges.push_back(*sp);\n  resEdges.emplace_back(sp->begin(), sp->end());\n\n  // If we need the shortest path only\n  if (k == 1) {\n    fill_multi_predecessor(resPathsEdges.begin(), resPathsEdges.end(), G,\n                           predecessors);\n    return;\n  }\n\n  // Every max-heap H_i is associated with p_i\n  using Priority = std::pair<Edge, int>;\n  using EdgePriorityQueue =\n      std::priority_queue<Priority, std::vector<Priority>,\n                          details::EdgePriorityComparator<Edge>>;\n  auto edge_priorities = std::vector<EdgePriorityQueue>(k);\n\n  // We keep a set of non-removable edges\n  auto dnr_edges = std::unordered_set<Edge, boost::hash<Edge>>{};\n\n  // We keep a set of deleted-edges\n  auto deleted_edges = std::unordered_set<Edge, boost::hash<Edge>>{};\n\n  // Compute lower bounds for AStar\n  // auto heuristic = details::distance_heuristic<Graph, Length>(G, t);\n\n  // Initialize max-heap H_0 with the priority of each edge of the shortest path\n  priority_fn(*sp, edge_priorities, 0, G, weight, deleted_edges);\n\n  auto overlaps = std::vector<double>(k, 0.0);\n  overlaps[0] = 1.0; // Set p_c overlap with sp (itself) to 1\n\n  bool still_feasible = true;\n  while (resPathsEdges.size() < static_cast<std::size_t>(k) && still_feasible) {\n    std::ptrdiff_t p_max_idx = 0;\n    double overlap_ratio = 1.0;\n\n    while (overlap_ratio >= theta) {\n      // Get the max overlapping path\n      auto max_it = std::max_element(std::begin(overlaps), std::end(overlaps));\n      p_max_idx = max_it - std::begin(overlaps);\n      overlap_ratio = *max_it;\n\n      // Check if finding a result is feasible\n      still_feasible = details::check_feasibility(overlaps);\n      if (!still_feasible) {\n        break; // Stop the algorithm\n      }\n\n      // Get e_tmp with higher priority from H_{p_max_idx}\n      auto e_tmp = edge_priorities[p_max_idx].top().first;\n\n      // If edge is in DO-NOT-REMOVE edges set, continue\n      if (dnr_edges.find(e_tmp) != std::end(dnr_edges)) {\n        edge_priorities[p_max_idx].pop();\n        // Also, if H_{p_max_idx} queue is empty set its overlapping value to 0\n        if (edge_priorities[p_max_idx].empty()) {\n          overlaps[p_max_idx] = 0;\n        }\n        continue;\n      } else {\n        // Otherwise, add e_tmp to deleted edges\n        deleted_edges.insert(e_tmp);\n      }\n\n      // The remainder code is the hot part of the algorithm. So we check here\n      // if the algorithm should terminate\n      if (terminator.should_stop()) {\n        throw terminator_stop_error{\n            \"ESX terminated before completing due to a Terminator. Please \"\n            \"discard partial output.\"};\n      }\n\n      // Compute p_tmp shortest path\n      auto p_tmp = routing_kernel(G, s, t, weight, deleted_edges);\n\n      // If shortest path did not find a path\n      if (!p_tmp) {\n        move_to_dnr(e_tmp, deleted_edges, dnr_edges);\n        continue;\n      }\n\n      // Remove e_tmp from H_{p_max_idx}\n      edge_priorities[p_max_idx].pop();\n\n      // in cases there are no more edges to remove we set overlap to zero to\n      // avoid choosing from the same path again. A path the overlap of which is\n      // zero can never be chosen to remove its edges.\n      if (edge_priorities[p_max_idx].empty()) {\n        overlaps[p_max_idx] = 0;\n      } else {\n        const auto &alt_path = resEdges[p_max_idx];\n        overlaps[p_max_idx] = compute_similarity(*p_tmp, alt_path, weight);\n      }\n\n      // Checking if the resulting path is valid\n      bool candidate_is_valid =\n          check_candidate_validity(*p_tmp, resEdges, weight, theta);\n      if (candidate_is_valid) {\n        // Add p_tmp to P_LO\n        resPathsEdges.emplace_back(*p_tmp);\n        resEdges.emplace_back(p_tmp->begin(), p_tmp->end());\n\n        // Set p_c overlap with itself to 1\n        std::ptrdiff_t p_c_idx = resPathsEdges.size() - 1;\n        overlaps[p_c_idx] = 1.0;\n\n        // Initialize max-heap H_i with the priority of each edge of new\n        // alternative path\n        priority_fn(*p_tmp, edge_priorities, p_c_idx, G, weight, deleted_edges);\n        break; // From inner while loop\n      }\n    }\n  }\n\n  // Beforer returning, populate predecessors map\n  fill_multi_predecessor(resPathsEdges.begin(), resPathsEdges.end(), G,\n                         predecessors);\n}\n\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename PriorityFunc, typename Terminator,\n          typename Vertex = vertex_of_t<Graph>>\nvoid esx_dispatch2(const Graph &G, WeightMap const &weight,\n                   MultiPredecessorMap &predecessors, Vertex s, Vertex t, int k,\n                   double theta, PriorityFunc &&priority_fn,\n                   routing_kernels algorithm, Terminator &&terminator) {\n  using Edge = edge_of_t<Graph>;\n  using Length = length_of_t<Graph>;\n\n  auto deleted_edges = std::unordered_set<Edge, boost::hash<Edge>>{};\n  if (algorithm == routing_kernels::astar) {\n    auto heuristic = details::distance_heuristic<Graph, Length>(G, t);\n    auto routing_kernel = details::build_shortest_path_fn(\n        algorithm, G, s, t, weight, heuristic, deleted_edges);\n    esx(G, weight, predecessors, s, t, k, theta,\n        std::forward<PriorityFunc>(priority_fn), routing_kernel,\n        std::forward<Terminator>(terminator));\n  } else {\n    auto routing_kernel = details::build_shortest_path_fn(\n        algorithm, G, s, t, weight, deleted_edges);\n    esx(G, weight, predecessors, s, t, k, theta,\n        std::forward<PriorityFunc>(priority_fn), routing_kernel,\n        std::forward<Terminator>(terminator));\n  }\n}\n\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename Terminator, typename Vertex = vertex_of_t<Graph>>\nvoid esx_dispatch(const Graph &G, WeightMap const &weight,\n                  MultiPredecessorMap &predecessors, Vertex s, Vertex t, int k,\n                  double theta, routing_kernels algorithm,\n                  Terminator &&terminator) {\n  auto priority_fn = [](auto const &alternative, auto &edge_priorities,\n                        auto alt_index, auto const &G, auto const &weight,\n                        auto const &deleted_edges) {\n    init_edge_priorities(alternative, edge_priorities, alt_index, G, weight,\n                         deleted_edges);\n  };\n  esx_dispatch2(G, weight, predecessors, s, t, k, theta, std::move(priority_fn),\n                algorithm, std::forward<Terminator>(terminator));\n}\n\ntemplate <typename Graph, typename WeightMap, typename MultiPredecessorMap,\n          typename EdgeCentralityMap, typename Terminator,\n          typename Vertex = vertex_of_t<Graph>>\nvoid esx_dispatch(const Graph &G, WeightMap const &weight,\n                  MultiPredecessorMap &predecessors,\n                  EdgeCentralityMap const &edge_centrality, Vertex s, Vertex t,\n                  int k, double theta, routing_kernels algorithm,\n                  Terminator &&terminator) {\n  auto priority_fn = [&edge_centrality](auto const &alternative,\n                                        auto &edge_priorities, auto alt_index,\n                                        auto const &, auto const &,\n                                        auto const &) {\n    for (const auto &e : alternative) {\n      auto prio_e_i = get(edge_centrality, e);\n      edge_priorities[alt_index].push(std::make_pair(e, prio_e_i));\n    }\n  };\n\n  esx_dispatch2(G, weight, predecessors, s, t, k, theta, std::move(priority_fn),\n                algorithm, std::forward<Terminator>(terminator));\n}\n} // namespace details\n} // namespace arlib\n#endif\n", "meta": {"hexsha": "52757258e35dcab5b657886213fddf7c95b07cce", "size": 31673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/details/esx_impl.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/details/esx_impl.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/details/esx_impl.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": 38.2524154589, "max_line_length": 80, "alphanum_fraction": 0.6629621444, "num_tokens": 7532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.0440186473547229, "lm_q1q2_score": 0.018766099842051836}}
{"text": "\n#include <NTL/vec_GF2.h>\n\n#include <NTL/new.h>\n#include <stdio.h>\n\nNTL_START_IMPL\n\nvoid vec_GF2::SetLength(long n)\n{\n   long len = length();\n\n   if (n == len) return;\n\n   if (n < 0) Error(\"negative length in vec_GF2::SetLength\");\n\n   if (NTL_OVERFLOW(n, 1, 0))\n      Error(\"vec_GF2::SetLength: excessive length\");\n\n   if (fixed()) Error(\"SetLength: can't change this vector's length\");\n\n   long wdlen = (n+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;\n\n   if (n < len) {\n      // have to clear bits n..len-1\n\n      long q = n/NTL_BITS_PER_LONG;\n      long p = n - q*NTL_BITS_PER_LONG;\n\n      _ntl_ulong *x = rep.elts();\n\n      x[q] &= (1UL << p) - 1UL;\n\n      long q1 = (len-1)/NTL_BITS_PER_LONG;\n      long i;\n\n      for (i = q+1; i <= q1; i++)\n         x[i] = 0;\n\n      _len = n;\n\n      rep.QuickSetLength(wdlen);\n\n      return;\n   }\n\n   long maxlen = MaxLength();\n\n   if (n <= maxlen) {\n      _len = n;\n      rep.QuickSetLength(wdlen);\n      return;\n   }\n\n   long alloc = rep.MaxLength();\n\n   if (wdlen <= alloc) {\n      _len = n;\n      _maxlen = (n << 1);\n      rep.QuickSetLength(wdlen);\n      return;\n   }\n\n   // have to grow vector and initialize to zero\n\n   rep.SetLength(wdlen);\n\n   wdlen = rep.MaxLength(); // careful! rep.MaxLength() may exceed the\n                            // old value of wdlen...this is due to \n                            // the awkward semantics of WordVector.\n\n   _ntl_ulong *x = rep.elts();\n\n   long i;\n   for (i = alloc; i < wdlen; i++)\n      x[i] = 0;\n\n   _len = n;\n   _maxlen = (n << 1);\n\n}\n\n\nvec_GF2& vec_GF2::operator=(const vec_GF2& a)\n{\n   if (this == &a) return *this;\n\n   long n = a.length();\n\n   SetLength(n);\n\n   long wdlen = (n+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;\n\n   _ntl_ulong *x = rep.elts();\n   const _ntl_ulong *y = a.rep.elts();\n\n   long i;\n   for (i = 0; i < wdlen; i++)\n      x[i] = y[i];\n\n   return *this;\n}\n\nvoid vec_GF2::kill()\n{\n   if (fixed()) Error(\"can't kill this vec_GF2\");\n   rep.kill();\n   _len = _maxlen = 0;\n}\n\n\nvoid vec_GF2::SetMaxLength(long n)\n{\n   long oldlen = length();\n   if (n > oldlen) {\n      SetLength(n);\n      SetLength(oldlen);\n   }\n}\n\nvoid vec_GF2::FixLength(long n)\n{\n   if (MaxLength() > 0 || fixed()) Error(\"can't fix this vector\");\n\n   SetLength(n);\n   _maxlen |= 1;\n}\n\nconst GF2 vec_GF2::get(long i) const\n{\n   const vec_GF2& v = *this;\n\n   if (i < 0 || i >= v.length()) \n      Error(\"vec_GF2: subscript out of range\");\n\n   long q = i/NTL_BITS_PER_LONG;\n   long p = i - q*NTL_BITS_PER_LONG;\n\n   if (v.rep[q] & (1UL << p))\n      return to_GF2(1);\n   else\n      return to_GF2(0);\n}\n\nref_GF2 vec_GF2::operator[](long i)\n{\n   vec_GF2& v = *this;\n\n   if (i < 0 || i >= v.length()) \n      Error(\"vec_GF2: subscript out of range\");\n\n   long q = i/NTL_BITS_PER_LONG;\n   long p =  i - q*NTL_BITS_PER_LONG;\n   return ref_GF2(INIT_LOOP_HOLE, &v.rep[q], p);\n}\n\n\n\nstatic\nvoid SetBit(vec_GF2& v, long i)\n{\n   if (i < 0 || i >= v.length())\n      Error(\"vec_GF2: subscript out of range\");\n\n   long q = i/NTL_BITS_PER_LONG;\n   long p = i - q*NTL_BITS_PER_LONG;\n\n   v.rep[q] |= (1UL << p);\n}\n\nstatic\nvoid ClearBit(vec_GF2& v, long i)\n{\n   if (i < 0 || i >= v.length())\n      Error(\"vec_GF2: subscript out of range\");\n\n   long q = i/NTL_BITS_PER_LONG;\n   long p = i - q*NTL_BITS_PER_LONG;\n\n   v.rep[q] &= ~(1UL << p);\n}\n\nvoid vec_GF2::put(long i, GF2 a)\n{\n   if (a == 1)\n      SetBit(*this, i);\n   else\n      ClearBit(*this, i);\n}\n\nvoid swap(vec_GF2& x, vec_GF2& y)\n{\n   long xf = x.fixed();\n   long yf = y.fixed();\n\n   if (xf != yf || (xf && x.length() != y.length()))\n      Error(\"swap: can't swap these vec_GF2s\");\n\n   swap(x.rep, y.rep);\n   swap(x._len, y._len);\n   swap(x._maxlen, y._maxlen);\n}\n\n\nvoid append(vec_GF2& v, const GF2& a)\n{\n   long n = v.length();\n   v.SetLength(n+1);\n   v.put(n, a);\n}\n\nvoid append(vec_GF2& x, const vec_GF2& a)\n{\n   long a_len = a.length();\n   long x_len = x.length();\n\n   if (a_len == 0) return;\n   if (x_len == 0) {\n      x = a;\n      return;\n   }\n\n\n   x.SetLength(x_len + a_len);\n   // new bits are guaranteed zero\n\n\n   ShiftAdd(x.rep.elts(), a.rep.elts(), a.rep.length(), x_len);\n}\n\n\nlong operator==(const vec_GF2& a, const vec_GF2& b)\n{\n   return a.length() == b.length() && a.rep == b.rep;\n}\n\n\n\n\n\nistream & operator>>(istream& s, vec_GF2& a) \n{   \n   static ZZ ival;\n\n   long c;   \n   if (!s) Error(\"bad vec_GF2 input\"); \n   \n   c = s.peek();  \n   while (IsWhiteSpace(c)) {  \n      s.get();  \n      c = s.peek();  \n   }  \n\n   if (c != '[') {  \n      Error(\"bad vec_GF2 input\");  \n   }  \n\n   vec_GF2 ibuf;  \n   \n   ibuf.SetLength(0);\n      \n   s.get();  \n   c = s.peek();  \n   while (IsWhiteSpace(c)) {  \n      s.get();  \n      c = s.peek();  \n   }  \n\n   while (c != ']' && c != EOF) {   \n      if (!(s >> ival)) Error(\"bad vec_GF2 input\");\n      append(ibuf, to_GF2(ival));\n\n      c = s.peek();  \n\n      while (IsWhiteSpace(c)) {  \n         s.get();  \n         c = s.peek();  \n      }  \n   }   \n\n   if (c == EOF) Error(\"bad vec_GF2 input\");  \n   s.get(); \n   \n   a = ibuf; \n   return s;   \n}    \n\n\nostream& operator<<(ostream& s, const vec_GF2& a)   \n{   \n   long i, n;\n   GF2 c;\n  \n   n = a.length();\n   \n   s << '[';   \n   \n   for (i = 0; i < n; i++) {   \n      c = a.get(i);\n      if (c == 0)\n         s << \"0\";\n      else\n         s << \"1\";\n      if (i < n-1) s << \" \";   \n   }   \n   \n   s << ']';   \n      \n   return s;   \n}   \n\n// math operations:\n\nvoid mul(vec_GF2& x, const vec_GF2& a, GF2 b)\n{\n   x = a;\n   if (b == 0)\n      clear(x);\n}\n\nvoid add(vec_GF2& x, const vec_GF2& a, const vec_GF2& b)\n{\n   long blen = a.length();\n\n   if (b.length() != blen) Error(\"vec_GF2 add: length mismatch\");\n\n   x.SetLength(blen);\n\n   long wlen = a.rep.length();\n   long i;\n\n   _ntl_ulong *xp = x.rep.elts();\n   const _ntl_ulong *ap = a.rep.elts();\n   const _ntl_ulong *bp = b.rep.elts();\n\n   for (i = 0; i < wlen; i++)\n      xp[i] = ap[i] ^ bp[i];\n}\n\nvoid clear(vec_GF2& x)\n{\n   long wlen = x.rep.length();\n   long i;\n   _ntl_ulong *xp = x.rep.elts();\n\n   for (i = 0; i < wlen; i++)\n      xp[i] = 0;\n}\n\n\nlong IsZero(const vec_GF2& x)\n{\n   long wlen = x.rep.length();\n   long i;\n   const _ntl_ulong *xp = x.rep.elts();\n\n   for (i = 0; i < wlen; i++)\n      if (xp[i] != 0) return 0;\n\n   return 1;\n}\n\nvec_GF2 operator+(const vec_GF2& a, const vec_GF2& b)\n{\n   vec_GF2 res;\n   add(res, a, b);\n   NTL_OPT_RETURN(vec_GF2, res);\n}\n\n\nvec_GF2 operator-(const vec_GF2& a, const vec_GF2& b)\n{\n   vec_GF2 res;\n   add(res, a, b);\n   NTL_OPT_RETURN(vec_GF2, res);\n}\n\nstatic\nvoid ShiftToHigh(vec_GF2& x, const vec_GF2& a, long n)\n// assumes 0 <= n < a.length()\n\n{\n   long l = a.length();\n\n   x.SetLength(l);\n\n   _ntl_ulong *xp = x.rep.elts();\n   const _ntl_ulong *ap = a.rep.elts();\n\n   long wn = n/NTL_BITS_PER_LONG;\n   long bn = n - wn*NTL_BITS_PER_LONG;\n\n   long sa = a.rep.length();\n\n   long i;\n\n   if (bn == 0) {\n      for (i = sa-1; i >= wn; i--)\n         xp[i] = ap[i-wn];\n      for (i = wn-1; i >= 0; i--)\n         xp[i] = 0; \n   }\n   else {\n      for (i = sa-1; i >= wn+1; i--)\n         xp[i] = (ap[i-wn] << bn) | (ap[i-wn-1] >> (NTL_BITS_PER_LONG-bn));\n      xp[wn] = ap[0] << bn;\n      for (i = wn-1; i >= 0; i--)\n         xp[i] = 0;\n   }\n\n   long p = l % NTL_BITS_PER_LONG;\n\n   if (p != 0)\n      xp[sa-1] &= (1UL << p) - 1UL;\n   \n}\n\nstatic\nvoid ShiftToLow(vec_GF2& x, const vec_GF2& a, long n)\n// assumes 0 <= n < a.length()\n\n{\n   long l = a.length();\n\n   x.SetLength(l);\n\n   _ntl_ulong *xp = x.rep.elts();\n   const _ntl_ulong *ap = a.rep.elts();\n\n   long wn = n/NTL_BITS_PER_LONG;\n   long bn = n - wn*NTL_BITS_PER_LONG;\n\n   long sa = a.rep.length();\n\n   long i;\n\n   if (bn == 0) {\n      for (i = 0; i < sa-wn; i++)\n         xp[i] = ap[i+wn];\n   }\n   else {\n      for (i = 0; i < sa-wn-1; i++)\n         xp[i] = (ap[i+wn] >> bn) | (ap[i+wn+1] << (NTL_BITS_PER_LONG - bn));\n\n      xp[sa-wn-1] = ap[sa-1] >> bn;\n   }\n\n   for (i = sa-wn; i < sa; i++)\n      xp[i] = 0;\n}\n\n\n\nvoid shift(vec_GF2& x, const vec_GF2& a, long n)\n{\n   long l = a.length();\n\n   if (n >= l || n <= -l) {\n      x.SetLength(l);\n      clear(x);\n   }\n   else if (n < 0) \n      ShiftToLow(x, a, -n); // |n| < l, so -n won't overflow!\n   else\n      ShiftToHigh(x, a, n);\n}\n\n\n\n\n\n// This code is simply canibalized from GF2X.c...\n// so much for \"code re-use\" and \"modularity\"\n\nstatic _ntl_ulong revtab[256] = {\n\n0UL, 128UL, 64UL, 192UL, 32UL, 160UL, 96UL, 224UL, 16UL, 144UL, \n80UL, 208UL, 48UL, 176UL, 112UL, 240UL, 8UL, 136UL, 72UL, 200UL, \n40UL, 168UL, 104UL, 232UL, 24UL, 152UL, 88UL, 216UL, 56UL, 184UL, \n120UL, 248UL, 4UL, 132UL, 68UL, 196UL, 36UL, 164UL, 100UL, 228UL, \n20UL, 148UL, 84UL, 212UL, 52UL, 180UL, 116UL, 244UL, 12UL, 140UL, \n76UL, 204UL, 44UL, 172UL, 108UL, 236UL, 28UL, 156UL, 92UL, 220UL, \n60UL, 188UL, 124UL, 252UL, 2UL, 130UL, 66UL, 194UL, 34UL, 162UL, \n98UL, 226UL, 18UL, 146UL, 82UL, 210UL, 50UL, 178UL, 114UL, 242UL, \n10UL, 138UL, 74UL, 202UL, 42UL, 170UL, 106UL, 234UL, 26UL, 154UL, \n90UL, 218UL, 58UL, 186UL, 122UL, 250UL, 6UL, 134UL, 70UL, 198UL, \n38UL, 166UL, 102UL, 230UL, 22UL, 150UL, 86UL, 214UL, 54UL, 182UL, \n118UL, 246UL, 14UL, 142UL, 78UL, 206UL, 46UL, 174UL, 110UL, 238UL, \n30UL, 158UL, 94UL, 222UL, 62UL, 190UL, 126UL, 254UL, 1UL, 129UL, \n65UL, 193UL, 33UL, 161UL, 97UL, 225UL, 17UL, 145UL, 81UL, 209UL, \n49UL, 177UL, 113UL, 241UL, 9UL, 137UL, 73UL, 201UL, 41UL, 169UL, \n105UL, 233UL, 25UL, 153UL, 89UL, 217UL, 57UL, 185UL, 121UL, 249UL, \n5UL, 133UL, 69UL, 197UL, 37UL, 165UL, 101UL, 229UL, 21UL, 149UL, \n85UL, 213UL, 53UL, 181UL, 117UL, 245UL, 13UL, 141UL, 77UL, 205UL, \n45UL, 173UL, 109UL, 237UL, 29UL, 157UL, 93UL, 221UL, 61UL, 189UL, \n125UL, 253UL, 3UL, 131UL, 67UL, 195UL, 35UL, 163UL, 99UL, 227UL, \n19UL, 147UL, 83UL, 211UL, 51UL, 179UL, 115UL, 243UL, 11UL, 139UL, \n75UL, 203UL, 43UL, 171UL, 107UL, 235UL, 27UL, 155UL, 91UL, 219UL, \n59UL, 187UL, 123UL, 251UL, 7UL, 135UL, 71UL, 199UL, 39UL, 167UL, \n103UL, 231UL, 23UL, 151UL, 87UL, 215UL, 55UL, 183UL, 119UL, 247UL, \n15UL, 143UL, 79UL, 207UL, 47UL, 175UL, 111UL, 239UL, 31UL, 159UL, \n95UL, 223UL, 63UL, 191UL, 127UL, 255UL  }; \n\nstatic inline \n_ntl_ulong rev1(_ntl_ulong a)\n{\n   return NTL_BB_REV_CODE;\n}\n\n\n\nvoid reverse(vec_GF2& c, const vec_GF2& a)\n// c = reverse of a\n\n{\n   long n = a.length();\n\n   c = a;\n\n   if (n <= 0) {\n      return;\n   }\n\n   long wn = n/NTL_BITS_PER_LONG;\n   long bn = n - wn*NTL_BITS_PER_LONG;\n\n   if (bn != 0) {\n      wn++;\n      bn = NTL_BITS_PER_LONG - bn;\n   }\n\n   _ntl_ulong *cp = c.rep.elts();\n\n   long i;\n\n   if (bn != 0) {\n      for (i = wn-1; i >= 1; i--)\n         cp[i] = (cp[i] << bn) | (cp[i-1] >> (NTL_BITS_PER_LONG-bn));\n      cp[0] = cp[0] << bn;\n   }\n\n   for (i = 0; i < wn/2; i++) {\n      _ntl_ulong t; t = cp[i]; cp[i] = cp[wn-1-i]; cp[wn-1-i] = t;\n   }\n\n   for (i = 0; i < wn; i++)\n      cp[i] = rev1(cp[i]);\n}\n\nstatic \nlong weight1(_ntl_ulong a)\n{\n   long res = 0;\n   while (a) {\n      if (a & 1) res ++;\n      a >>= 1;\n   }\n   return res;\n}\n\nlong weight(const vec_GF2& a)\n{\n   long wlen = a.rep.length();\n   long res = 0;\n   long i;\n   for (i = 0; i < wlen; i++)\n      res += weight1(a.rep[i]);\n\n   return res;\n}\n\nvoid random(vec_GF2& x, long n)\n{\n   if (n < 0) Error(\"random: bad arg\");\n\n   x.SetLength(n);\n\n   long wl = x.rep.length();\n   long i;\n\n   for (i = 0; i < wl-1; i++) {\n      x.rep[i] = RandomWord();\n   }\n\n   if (n > 0) {\n      long pos = n % NTL_BITS_PER_LONG;\n      if (pos == 0) pos = NTL_BITS_PER_LONG;\n      x.rep[wl-1] = RandomBits_ulong(pos);\n   }\n}\n\n\n\nvoid VectorCopy(vec_GF2& x, const vec_GF2& a, long n)\n{\n   if (n < 0) Error(\"VectorCopy: negative length\");\n   if (NTL_OVERFLOW(n, 1, 0)) Error(\"overflow in VectorCopy\");\n\n   long m = min(n, a.length());\n\n   x.SetLength(n);\n\n   long wn = (n + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n   long wm = (m + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n\n   _ntl_ulong *xp = x.rep.elts();\n   const _ntl_ulong *ap = a.rep.elts();\n\n   long i;\n\n   for (i = 0; i < wm; i++)\n      xp[i] = ap[i];\n\n   for (i = wm; i < wn; i++)\n      xp[i] = 0;\n\n   long p = n % NTL_BITS_PER_LONG;\n   if (p != 0) {\n      xp[wn-1] &= ((1UL << p) - 1UL);\n   }\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "abeed363c998b8702d8f7a7857b6adec44db42f7", "size": 12021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ntl/vec_GF2.cpp", "max_stars_repo_name": "av-elier/fast-exponentiation-algs", "max_stars_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "src/ntl/vec_GF2.cpp", "max_issues_repo_name": "av-elier/fast-exponentiation-algs", "max_issues_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ntl/vec_GF2.cpp", "max_forks_repo_name": "av-elier/fast-exponentiation-algs", "max_forks_repo_head_hexsha": "1d6393021583686372564a7ca52b09dc7013fb38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2336, "max_line_length": 77, "alphanum_fraction": 0.5371433325, "num_tokens": 4645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056074291439, "lm_q2_score": 0.06656918989642605, "lm_q1q2_score": 0.0187329433188698}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// @project        Open Space Toolkit ▸ Core\n/// @file           OpenSpaceToolkit/Core/Types/Real.cpp\n/// @author         Lucas Brémond <lucas@loftorbital.com>\n/// @license        Apache License 2.0\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <OpenSpaceToolkit/Core/Types/Real.hpp>\n#include <OpenSpaceToolkit/Core/Error.hpp>\n\n#include <boost/lexical_cast.hpp>\n\n#include <limits>\n#include <iomanip>\n#include <iostream>\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nnamespace ostk\n{\nnamespace core\n{\nnamespace types\n{\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n                                Real::Real                                  (           Real::ValueType             aReal                                       )\n                                :   type_(Real::Type::Defined),\n                                    value_(aReal)\n{\n\n}\n\nReal&                           Real::operator =                            (           Real::ValueType             aReal                                       )\n{\n\n    type_ = Real::Type::Defined ;\n    value_ = aReal ;\n\n    return *this ;\n\n}\n\nbool                            Real::operator ==                           (   const   Real&                       aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (aReal.type_ == Real::Type::Defined) && (value_ == aReal.value_) ;\n}\n\nbool                            Real::operator !=                           (   const   Real&                       aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (aReal.type_ == Real::Type::Defined) && (value_ != aReal.value_) ;\n}\n\nbool                            Real::operator <                            (   const   Real&                       aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (aReal.type_ == Real::Type::Defined) && (value_ < aReal.value_) ;\n}\n\nbool                            Real::operator <=                           (   const   Real&                       aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (aReal.type_ == Real::Type::Defined) && (value_ <= aReal.value_) ;\n}\n\nbool                            Real::operator >                            (   const   Real&                       aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (aReal.type_ == Real::Type::Defined) && (value_ > aReal.value_) ;\n}\n\nbool                            Real::operator >=                           (   const   Real&                       aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (aReal.type_ == Real::Type::Defined) && (value_ >= aReal.value_) ;\n}\n\nbool                            Real::operator ==                           (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (value_ == aReal) ;\n}\n\nbool                            Real::operator !=                           (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (value_ != aReal) ;\n}\n\nbool                            Real::operator <                            (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (value_ < aReal) ;\n}\n\nbool                            Real::operator <=                           (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (value_ <= aReal) ;\n}\n\nbool                            Real::operator >                            (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (value_ > aReal) ;\n}\n\nbool                            Real::operator >=                           (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (type_ == Real::Type::Defined) && (value_ >= aReal) ;\n}\n\nReal                            Real::operator +                            (   const   Real&                       aReal                                       ) const\n{\n\n    if ((type_ != Real::Type::Undefined) && (aReal.type_ != Real::Type::Undefined))\n    {\n\n        if ((type_ == Real::Type::PositiveInfinity) && (aReal.type_ == Real::Type::PositiveInfinity))\n        {\n            return Real::PositiveInfinity() ;\n        }\n        else if ((type_ == Real::Type::NegativeInfinity) && (aReal.type_ == Real::Type::NegativeInfinity))\n        {\n            return Real::NegativeInfinity() ;\n        }\n        else if ((type_ == Real::Type::Defined) || (aReal.type_ == Real::Type::Defined))\n        {\n\n            if (type_ != Real::Type::Defined)\n            {\n                return *this ;\n            }\n            else if (aReal.type_ != Real::Type::Defined)\n            {\n                return aReal ;\n            }\n\n            // [TBC] Use __builtin_add_overflow instead?\n\n            if ((aReal.value_ > 0.0) && (value_ >= (std::numeric_limits<Real::ValueType>::max() - aReal.value_))) // Addition would overflow\n            {\n                return (value_ != 0.0) ? Real::PositiveInfinity() : aReal ;\n            }\n\n            if ((aReal.value_ < 0.0) && (value_ <= (std::numeric_limits<Real::ValueType>::lowest() - aReal.value_))) // Addition would underflow\n            {\n                return (value_ != 0.0) ? Real::NegativeInfinity() : aReal ;\n            }\n\n            return Real(value_ + aReal.value_) ;\n\n        }\n\n    }\n\n    return Real::Undefined() ;\n\n}\n\nReal                            Real::operator -                            (   const   Real&                       aReal                                       ) const\n{\n\n    if ((type_ != Real::Type::Undefined) && (aReal.type_ != Real::Type::Undefined))\n    {\n\n        if ((type_ == Real::Type::PositiveInfinity) && (aReal.type_ == Real::Type::NegativeInfinity))\n        {\n            return Real::PositiveInfinity() ;\n        }\n        else if ((type_ == Real::Type::NegativeInfinity) && (aReal.type_ == Real::Type::PositiveInfinity))\n        {\n            return Real::NegativeInfinity() ;\n        }\n        else if ((type_ == Real::Type::Defined) || (aReal.type_ == Real::Type::Defined))\n        {\n\n            if (type_ != Real::Type::Defined)\n            {\n                return *this ;\n            }\n            else if (aReal.type_ != Real::Type::Defined)\n            {\n\n                if (aReal.type_ == Real::Type::PositiveInfinity)\n                {\n                    return Real::NegativeInfinity() ;\n                }\n\n                return Real::PositiveInfinity() ;\n\n            }\n\n            if ((aReal.value_ < 0.0) && (value_ >= (std::numeric_limits<Real::ValueType>::max() + aReal.value_))) // Subtraction would overflow\n            {\n                return (value_ != 0.0) ? Real::PositiveInfinity() : -aReal ;\n            }\n\n            if ((aReal.value_ > 0.0) && (value_ <= (std::numeric_limits<Real::ValueType>::lowest() + aReal.value_))) // Subtraction would underflow\n            {\n                return (value_ != 0.0) ? Real::NegativeInfinity() : -aReal ;\n            }\n\n            return Real(value_ - aReal.value_) ;\n\n        }\n\n    }\n\n    return Real::Undefined() ;\n\n}\n\nReal                            Real::operator *                            (   const   Real&                       aReal                                       ) const\n{\n\n    if ((type_ != Real::Type::Undefined) && (aReal.type_ != Real::Type::Undefined))\n    {\n\n        if (type_ == Real::Type::PositiveInfinity)\n        {\n\n            if (aReal.isStrictlyPositive())\n            {\n                return Real::PositiveInfinity() ;\n            }\n            else if (aReal.isStrictlyNegative())\n            {\n                return Real::NegativeInfinity() ;\n            }\n\n            return Real::Undefined() ;\n\n        }\n        else if (type_ == Real::Type::NegativeInfinity)\n        {\n\n            if (aReal.isStrictlyPositive())\n            {\n                return Real::NegativeInfinity() ;\n            }\n            else if (aReal.isStrictlyNegative())\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            return Real::Undefined() ;\n\n        }\n        else if (aReal.type_ == Real::Type::PositiveInfinity)\n        {\n\n            if (this->isStrictlyPositive())\n            {\n                return Real::PositiveInfinity() ;\n            }\n            else if (this->isStrictlyNegative())\n            {\n                return Real::NegativeInfinity() ;\n            }\n\n            return Real::Undefined() ;\n\n        }\n        else if (aReal.type_ == Real::Type::NegativeInfinity)\n        {\n\n            if (this->isStrictlyPositive())\n            {\n                return Real::NegativeInfinity() ;\n            }\n            else if (this->isStrictlyNegative())\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            return Real::Undefined() ;\n\n        }\n        else\n        {\n\n            if (this->isZero() || aReal.isZero())\n            {\n                return Real::Zero() ;\n            }\n\n            // Check for -1 for two's complement machines\n\n            if ((value_ < 0.0) && (aReal.value_ == std::numeric_limits<Real::ValueType>::lowest())) // Multiplication can overflow\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            if ((aReal.value_ < 0.0) && (value_ == std::numeric_limits<Real::ValueType>::lowest())) // Multiplication can overflow\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            if ((this->getSign() == aReal.getSign()) && (std::abs(value_) > (std::numeric_limits<Real::ValueType>::max() / std::abs(aReal.value_)))) // Multiplication would overflow\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            if ((value_ == +1) && (aReal.value_ == std::numeric_limits<Real::ValueType>::lowest()))\n            {\n                return Real(std::numeric_limits<Real::ValueType>::lowest()) ;\n            }\n\n            if ((value_ == -1) && (aReal.value_ == std::numeric_limits<Real::ValueType>::lowest()))\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            if ((aReal.value_ != -1) && (this->getSign() != aReal.getSign()) && ((-std::abs(value_)) < (std::numeric_limits<Real::ValueType>::lowest() / std::abs(aReal.value_)))) // Multiplication would underflow\n            {\n                return Real::NegativeInfinity() ;\n            }\n\n            return Real(value_ * aReal.value_) ;\n\n        }\n\n    }\n\n    return Real::Undefined() ;\n\n}\n\nReal                            Real::operator /                            (   const   Real&                       aReal                                       ) const\n{\n\n    if (aReal.isZero())\n    {\n        return Real::Undefined() ;\n    }\n\n    if ((type_ != Real::Type::Undefined) && (aReal.type_ != Real::Type::Undefined))\n    {\n\n        if (type_ == Real::Type::PositiveInfinity)\n        {\n\n            if (aReal.isInfinity())\n            {\n                return Real::Undefined() ;\n            }\n            else if (aReal.isStrictlyPositive())\n            {\n                return Real::PositiveInfinity() ;\n            }\n            else if (aReal.isStrictlyNegative())\n            {\n                return Real::NegativeInfinity() ;\n            }\n\n            return Real::Undefined() ;\n\n        }\n        else if (type_ == Real::Type::NegativeInfinity)\n        {\n\n            if (aReal.isInfinity())\n            {\n                return Real::Undefined() ;\n            }\n            else if (aReal.isStrictlyPositive())\n            {\n                return Real::NegativeInfinity() ;\n            }\n            else if (aReal.isStrictlyNegative())\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            return Real::Undefined() ;\n\n        }\n        else\n        {\n\n            if (this->isZero() || aReal.isInfinity())\n            {\n                return Real::Zero() ;\n            }\n            else\n            {\n\n                if ((value_ == std::numeric_limits<Real::ValueType>::lowest()) && (aReal.value_ == -1))\n                {\n                    return Real::PositiveInfinity() ;\n                }\n\n                return Real(value_ / aReal.value_) ;\n\n            }\n\n        }\n\n    }\n\n    return Real::Undefined() ;\n\n}\n\nReal                            Real::operator +                            (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (*this) + Real(aReal) ;\n}\n\nReal                            Real::operator -                            (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (*this) - Real(aReal) ;\n}\n\nReal                            Real::operator *                            (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (*this) * Real(aReal) ;\n}\n\nReal                            Real::operator /                            (   const   Real::ValueType&            aReal                                       ) const\n{\n    return (*this) / Real(aReal) ;\n}\n\nReal&                           Real::operator +=                           (   const   Real&                       aReal                                       )\n{\n\n    (*this) = (*this) + aReal ;\n\n    return *this ;\n\n}\n\nReal&                           Real::operator -=                           (   const   Real&                       aReal                                       )\n    {\n\n    (*this) = (*this) - aReal ;\n\n    return *this ;\n\n}\n\nReal&                           Real::operator *=                           (   const   Real&                       aReal                                       )\n    {\n\n    (*this) = (*this) * aReal ;\n\n    return *this ;\n\n}\n\nReal&                           Real::operator /=                           (   const   Real&                       aReal                                       )\n    {\n\n    (*this) = (*this) / aReal ;\n\n    return *this ;\n\n}\n\nReal&                           Real::operator +=                           (   const   Real::ValueType&            aReal                                       )\n{\n\n    (*this) = (*this) + Real(aReal) ;\n\n    return *this ;\n\n}\n\nReal&                           Real::operator -=                           (   const   Real::ValueType&            aReal                                       )\n{\n\n    (*this) = (*this) - Real(aReal) ;\n\n    return *this ;\n\n}\n\nReal&                           Real::operator *=                           (   const   Real::ValueType&            aReal                                       )\n{\n\n    (*this) = (*this) * Real(aReal) ;\n\n    return *this ;\n\n}\n\nReal&                           Real::operator /=                           (   const   Real::ValueType&            aReal                                       )\n{\n\n    (*this) = (*this) / Real(aReal) ;\n\n    return *this ;\n\n}\n\nReal                            operator +                                  (   const   Real::ValueType&            anInt,\n                                                                                const   Real&                       aReal                                       )\n{\n    return Real(anInt) + aReal ;\n}\n\nReal                            operator -                                  (   const   Real::ValueType&            anInt,\n                                                                                const   Real&                       aReal                                       )\n{\n    return Real(anInt) - aReal ;\n}\n\nReal                            operator *                                  (   const   Real::ValueType&            anInt,\n                                                                                const   Real&                       aReal                                       )\n{\n    return Real(anInt) * aReal ;\n}\n\nReal                            operator /                                  (   const   Real::ValueType&            anInt,\n                                                                                const   Real&                       aReal                                       )\n{\n    return Real(anInt) / aReal ;\n}\n\nReal                            Real::operator +                            ( ) const\n{\n    return *this ;\n}\n\nReal                            Real::operator -                            ( ) const\n{\n\n    switch (type_)\n    {\n\n        case Real::Type::Defined:\n        {\n\n            if (value_ == std::numeric_limits<Real::ValueType>::lowest())\n            {\n                return Real::PositiveInfinity() ;\n            }\n\n            return Real(-value_) ;\n\n        }\n\n        case Real::Type::Undefined:\n            return Real::Undefined() ;\n\n        case Real::Type::PositiveInfinity:\n            return Real::NegativeInfinity() ;\n\n        case Real::Type::NegativeInfinity:\n            return Real::PositiveInfinity() ;\n\n        default:\n            break ;\n\n    }\n\n    return Real::Undefined() ;\n\n}\n\n                                Real::operator Real::ValueType        ( ) const\n{\n\n    if (type_ != Real::Type::Defined)\n    {\n        throw ostk::core::error::runtime::Undefined(\"Real\") ;\n    }\n\n    return value_ ;\n\n}\n\nstd::ostream&                   operator <<                                 (           std::ostream&               anOutputStream,\n                                                                                const   Real&                       aReal                                       )\n{\n\n    (void) aReal ;\n\n    switch (aReal.type_)\n    {\n\n        case Real::Type::Undefined:\n            anOutputStream << \"Undefined\" ;\n            break ;\n\n        case Real::Type::Defined:\n            anOutputStream << aReal.value_ ;\n            break ;\n\n        case Real::Type::PositiveInfinity:\n            anOutputStream << \"+Inf\" ;\n            break ;\n\n        case Real::Type::NegativeInfinity:\n            anOutputStream << \"-Inf\" ;\n            break ;\n\n    }\n\n    // ostk::core::utilities::Output::Header(anOutputStream, \"Real\") ;\n\n    // ostk::core::utilities::Output::Line(anOutputStream) << \"Type:\" << aReal.type_ ;\n    // ostk::core::utilities::Output::Line(anOutputStream) << \"Value:\" << aReal.value_ ;\n\n    // ostk::core::utilities::Output::Footer(anOutputStream) ;\n\n    return anOutputStream ;\n\n}\n\nbool                            Real::isDefined                             ( ) const\n{\n    return type_ != Real::Type::Undefined ;\n}\n\nbool                            Real::isZero                                ( ) const\n{\n    return (type_ == Real::Type::Defined) && (value_ == 0.0) ;\n}\n\nbool                            Real::isPositive                            ( ) const\n{\n    return ((type_ == Real::Type::Defined) && (value_ >= 0.0)) || this->isPositiveInfinity() ;\n}\n\nbool                            Real::isNegative                            ( ) const\n{\n    return ((type_ == Real::Type::Defined) && (value_ <= 0.0)) || this->isNegativeInfinity() ;\n}\n\nbool                            Real::isStrictlyPositive                    ( ) const\n{\n    return ((type_ == Real::Type::Defined) && (value_ > 0.0)) || this->isPositiveInfinity() ;\n}\n\nbool                            Real::isStrictlyNegative                    ( ) const\n{\n    return ((type_ == Real::Type::Defined) && (value_ < 0.0)) || this->isNegativeInfinity() ;\n}\n\nbool                            Real::isInfinity                            ( ) const\n{\n    return this->isPositiveInfinity() || this->isNegativeInfinity() ;\n}\n\nbool                            Real::isPositiveInfinity                    ( ) const\n{\n    return type_ == Real::Type::PositiveInfinity ;\n}\n\nbool                            Real::isNegativeInfinity                    ( ) const\n{\n    return type_ == Real::Type::NegativeInfinity ;\n}\n\nbool                            Real::isInteger                             ( ) const\n{\n\n    if (this->isFinite())\n    {\n\n        double intpart ;\n\n        return std::modf(value_, &intpart) == 0.0 ;\n\n    }\n\n    return false ;\n\n}\n\nbool                            Real::isFinite                              ( ) const\n{\n    return type_ == Real::Type::Defined ;\n}\n\nbool                            Real::isNear                                (   const   Real&                       aValue,\n                                                                                const   Real&                       aTolerance                                  ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Real\") ;\n    }\n\n    if (!aValue.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Real\") ;\n    }\n\n    if (!aTolerance.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Tolerance\") ;\n    }\n\n    if ((!this->isFinite()) || (!aValue.isFinite()))\n    {\n        return false ;\n    }\n\n    return ((*this) - aValue).abs() <= aTolerance ;\n\n}\n\ntypes::Sign                     Real::getSign                               ( ) const\n{\n\n    switch (type_)\n    {\n\n        case Real::Type::Undefined:\n            return types::Sign::Undefined ;\n\n        case Real::Type::Defined:\n        {\n\n            if (value_ > 0.0)\n            {\n                return types::Sign::Positive ;\n            }\n            else if (value_ < 0.0)\n            {\n                return types::Sign::Negative ;\n            }\n\n            return types::Sign::None ;\n\n        }\n\n        case Real::Type::PositiveInfinity:\n            return types::Sign::Positive ;\n\n        case Real::Type::NegativeInfinity:\n            return types::Sign::Negative ;\n\n        default:\n           return types::Sign::Undefined ;\n\n    }\n\n    return types::Sign::Undefined ;\n\n}\n\ntypes::String                   Real::toString                              (   const   types::Integer&             aPrecision                                  ) const\n{\n\n    switch (type_)\n    {\n\n        case Real::Type::Undefined:\n            return \"Undefined\" ;\n\n        case Real::Type::Defined:\n        {\n\n            if (!aPrecision.isDefined())\n            {\n\n                if (this->isInteger())\n                {\n\n                    types::String realString = boost::lexical_cast<std::string>(value_) ;\n\n                    if (realString.find('e') == std::string::npos)\n                    {\n                        realString += \".0\" ;\n                    }\n\n                    return realString ;\n\n                }\n\n                // types::String realString = std::to_string(value_) ;\n                types::String realString = boost::lexical_cast<std::string>(value_) ;\n\n                // std::ostringstream stringStream ;\n\n                // stringStream.precision(14) ;\n\n                // stringStream << std::fixed << value_ ;\n\n                // types::String realString = stringStream.str() ;\n\n                if (realString.find('e') == std::string::npos)\n                {\n                    realString.erase(realString.find_last_not_of('0') + 1, std::string::npos) ; // Remove trailing zeros if any\n                }\n\n                return realString ;\n\n                // return boost::lexical_cast<std::string>(value_) ;\n                // return std::to_string(value_) ;\n\n            }\n\n            std::ostringstream stringStream ;\n\n            stringStream.precision(aPrecision) ;\n\n            stringStream << std::fixed << value_ ;\n\n            return stringStream.str() ;\n\n        }\n\n        case Real::Type::PositiveInfinity:\n            return \"+Inf\" ;\n\n        case Real::Type::NegativeInfinity:\n            return \"-Inf\" ;\n\n    }\n\n    return types::String::Empty() ;\n\n}\n\ntypes::Integer                  Real::toInteger                         ( ) const\n{\n\n    if (this->isInteger())\n    {\n        return types::Integer(static_cast<types::Integer::ValueType>(value_)) ;\n    }\n\n    throw ostk::core::error::RuntimeError(\"Real is not integer.\") ;\n\n    return types::Integer::Undefined() ;\n\n}\n\nReal                            Real::abs                                   ( ) const\n{\n\n    switch (type_)\n    {\n\n        case Real::Type::Undefined:\n            return Real::Undefined() ;\n\n        case Real::Type::Defined:\n            return Real(Real::Type::Defined, std::abs(value_)) ;\n\n        case Real::Type::PositiveInfinity:\n        case Real::Type::NegativeInfinity:\n            return Real::PositiveInfinity() ;\n\n        default:\n            throw ostk::core::error::runtime::Undefined(\"Type\") ;\n            break ;\n\n    }\n\n    return Real::Undefined() ;\n\n}\n\ntypes::Integer                  Real::floor                                 ( ) const\n{\n\n    switch (type_)\n    {\n\n        case Real::Type::Undefined:\n            return types::Integer::Undefined() ;\n\n        case Real::Type::Defined:\n            return types::Integer(static_cast<types::Integer::ValueType>(std::floor(value_))) ;\n\n        case Real::Type::PositiveInfinity:\n        case Real::Type::NegativeInfinity:\n            return types::Integer::Undefined() ;\n\n        default:\n            throw ostk::core::error::runtime::Undefined(\"Type\") ;\n            break ;\n\n    }\n\n    return types::Integer::Undefined() ;\n\n}\n\nReal                            Real::sqrt                                  ( ) const\n{\n\n    switch (type_)\n    {\n\n        case Real::Type::Undefined:\n            return Real::Undefined() ;\n\n        case Real::Type::Defined:\n        {\n\n            if (this->isStrictlyNegative())\n            {\n                return Real::Undefined() ;\n            }\n\n            return Real(Real::Type::Defined, std::sqrt(value_)) ;\n\n        }\n\n        case Real::Type::PositiveInfinity:\n            return Real::PositiveInfinity() ;\n\n        case Real::Type::NegativeInfinity:\n            return Real::Undefined() ;\n\n        default:\n            throw ostk::core::error::runtime::Undefined(\"Type\") ;\n            break ;\n\n    }\n\n    return Real::Undefined() ;\n\n}\n\nReal                            Real::Undefined                             ( )\n{\n    return Real(Real::Type::Undefined, 0.0) ;\n}\n\nReal                            Real::Zero                                  ( )\n{\n    return Real(Real::Type::Defined, 0.0) ;\n}\n\nReal                            Real::Pi                                    ( )\n{\n    return Real(Real::Type::Defined, M_PI) ;\n}\n\nReal                            Real::HalfPi                                ( )\n{\n    return Real(Real::Type::Defined, M_PI / 2.0) ;\n}\n\nReal                            Real::TwoPi                                 ( )\n{\n    return Real(Real::Type::Defined, 2.0 * M_PI) ;\n}\n\nReal                            Real::Epsilon                               ( )\n{\n    return Real(Real::Type::Defined, 1e-15) ;\n}\n\nReal                            Real::PositiveInfinity                      ( )\n{\n    return Real(Real::Type::PositiveInfinity, std::numeric_limits<Real::ValueType>::max()) ;\n}\n\nReal                            Real::NegativeInfinity                      ( )\n{\n    return Real(Real::Type::NegativeInfinity, std::numeric_limits<Real::ValueType>::lowest()) ;\n}\n\nReal                            Real::Integer                               (   const   types::Integer&             anInteger                                   )\n{\n\n    if (anInteger.isDefined())\n    {\n        return Real(Real::Type::Defined, anInteger) ;\n    }\n\n    return Real::Undefined() ;\n\n}\n\nReal                            Real::CanParse                              (   const   types::String&              aString                                     )\n{\n\n    if (aString.isEmpty())\n    {\n        return false ;\n    }\n\n    if ((aString == \"Undefined\") || (aString == \"NaN\") || (aString == \"Inf\") || (aString == \"+Inf\") || (aString == \"-Inf\"))\n    {\n        return true ;\n    }\n\n    Real::ValueType real ;\n\n    return boost::conversion::try_lexical_convert<Real::ValueType>(aString, real) ;\n\n}\n\nReal                            Real::Parse                                 (   const   types::String&              aString                                     )\n{\n\n    if (aString.isEmpty())\n    {\n        throw ostk::core::error::runtime::Undefined(\"String\") ;\n    }\n\n    if ((aString == \"Undefined\") || (aString == \"NaN\"))\n    {\n        return Real::Undefined() ;\n    }\n\n    if ((aString == \"Inf\") || (aString == \"+Inf\"))\n    {\n        return Real::PositiveInfinity() ;\n    }\n\n    if (aString == \"-Inf\")\n    {\n        return Real::NegativeInfinity() ;\n    }\n\n    try\n    {\n\n        const Real::ValueType value = boost::lexical_cast<Real::ValueType>(aString) ;\n\n        if (value != value)\n        {\n            throw ostk::core::error::RuntimeError(\"Cannot cast string [\" + aString + \"] to Real.\") ;\n        }\n\n        return Real(value) ;\n\n    }\n    catch (const boost::bad_lexical_cast&)\n    {\n        throw ostk::core::error::RuntimeError(\"Cannot cast string [\" + aString + \"] to Real.\") ;\n    }\n\n    return Real::Undefined() ;\n\n}\n\n// Real                             Real::Object                             (   const   ctnr::Object&               anObject                                   )\n// {\n\n// }\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n                                Real::Real                                  (   const   Real::Type&                 aType,\n                                                                                const   Real::ValueType&            aReal                                       )\n                                :   type_(aType),\n                                    value_(aReal)\n{\n\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n}\n}\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "d2c3228e25d6049e55690567cb6d84498c88e8f4", "size": 30893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OpenSpaceToolkit/Core/Types/Real.cpp", "max_stars_repo_name": "open-space-collective/library-core", "max_stars_repo_head_hexsha": "0b031edb403e2d657d02761b07dd4b35680fcafc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T06:50:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T03:36:50.000Z", "max_issues_repo_path": "src/OpenSpaceToolkit/Core/Types/Real.cpp", "max_issues_repo_name": "open-space-collective/library-core", "max_issues_repo_head_hexsha": "0b031edb403e2d657d02761b07dd4b35680fcafc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-06-12T07:42:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-05T01:13:27.000Z", "max_forks_repo_path": "src/OpenSpaceToolkit/Core/Types/Real.cpp", "max_forks_repo_name": "open-space-collective/library-core", "max_forks_repo_head_hexsha": "0b031edb403e2d657d02761b07dd4b35680fcafc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T18:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T18:18:24.000Z", "avg_line_length": 29.2547348485, "max_line_length": 212, "alphanum_fraction": 0.3882432914, "num_tokens": 5895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.052618955204778425, "lm_q1q2_score": 0.018720503903623554}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n#include <votca/xtp/aomatrix.h>\n#include <votca/xtp/dftcoupling.h>\n\n#include <votca/tools/constants.h>\n#include <boost/format.hpp>\n#include <boost/progress.hpp>\n\n\nnamespace votca { namespace xtp {\n\n\nusing std::flush;\nusing boost::format;\n\nvoid DFTcoupling::Initialize(tools::Property& options){\n  \n  std::string key=\"\";\n  _degeneracy=options.ifExistsReturnElseReturnDefault<bool>(key+\"degeneracy\",0.0);\n  _numberofstatesA=options.ifExistsReturnElseReturnDefault<int>(key+\"levA\",1);\n  _numberofstatesB=options.ifExistsReturnElseReturnDefault<int>(key+\"levB\",1);\n\n}\n\nvoid DFTcoupling::WriteToProperty(tools::Property& type_summary, const Orbitals& orbitalsA,\n                                  const Orbitals& orbitalsB, int a, int b){\n  double J = getCouplingElement(a,b, orbitalsA, orbitalsB);\n  tools::Property& coupling = type_summary.add(\"coupling\",\"\");\n  double energyA = orbitalsA.getEnergy(a);\n  double energyB = orbitalsB.getEnergy(b);\n  coupling.setAttribute(\"levelA\", a);\n  coupling.setAttribute(\"levelB\", b);\n  coupling.setAttribute(\"j\",(format(\"%1$1.6e\") % J).str());\n  coupling.setAttribute(\"eA\",(format(\"%1$1.6e\") % energyA).str());\n  coupling.setAttribute(\"eB\",(format(\"%1$1.6e\") % energyB).str());\n}\n\n void DFTcoupling::Addoutput(tools::Property & type_summary,const Orbitals& orbitalsA, \n                               const Orbitals& orbitalsB){\n  tools::Property& dftcoupling= type_summary.add(Identify(),\"\");\n  dftcoupling.setAttribute(\"homoA\",orbitalsA.getHomo());\n  dftcoupling.setAttribute(\"homoB\",orbitalsB.getHomo());\n   tools::Property &hole_summary = dftcoupling.add(\"hole\",\"\");\n   //hole hole\n   for (int a=Range_orbA.first;a<=orbitalsA.getHomo();++a){\n     for (int b=Range_orbB.first;b<=orbitalsB.getHomo();++b){\n          WriteToProperty(hole_summary, orbitalsA, orbitalsB, a, b);\n    }\n   }\n   tools::Property &electron_summary = dftcoupling.add(\"electron\",\"\");\n   //electron-//electron\n   for (int a=orbitalsA.getLumo();a<=Range_orbA.first+Range_orbA.second;++a){\n     for (int b=orbitalsB.getLumo();b<=Range_orbB.first+Range_orbB.second;++b){\n          WriteToProperty(electron_summary, orbitalsA, orbitalsB, a, b);\n    }\n   }\n   return;\n }\n\n\n\nstd::pair<int,int> DFTcoupling::DetermineRangeOfStates(const Orbitals& orbital, int numberofstates)const{\n  const Eigen::VectorXd& MOEnergies=orbital.MOEnergies();\n  if(std::abs(MOEnergies(orbital.getHomo())-MOEnergies(orbital.getLumo()))<_degeneracy){\n    throw std::runtime_error(\"Homo Lumo Gap is smaller than degeneracy. \"\n            \"Either your degeneracy is too large or your Homo and Lumo are degenerate\");\n  }\n  \n  int minimal=orbital.getHomo()-numberofstates+1;\n  int maximal=orbital.getLumo()+numberofstates-1;\n  \n  std::vector<int> deg_min=orbital.CheckDegeneracy(minimal,_degeneracy);\n  for(int i:deg_min){\n    if (i<minimal){\n      minimal=i;\n    }\n  }\n  \n  std::vector<int> deg_max=orbital.CheckDegeneracy(maximal,_degeneracy);\n  for(int i:deg_max){\n    if (i>maximal){\n      maximal=i;\n    }\n  }\n  \n  std::pair<int,int> result;\n  result.first=minimal;//start\n  result.second=maximal-minimal+1;//size\n  \n  return result;\n}\n\n\ndouble DFTcoupling::getCouplingElement( int levelA, int levelB, const Orbitals&orbitalsA,\n    const Orbitals& orbitalsB)const {\n\n    \n    int levelsA =Range_orbA.second;\n    \n    if (_degeneracy != 0) {\n        std::vector<int> list_levelsA = orbitalsA.CheckDegeneracy(levelA,_degeneracy);\n        std::vector<int> list_levelsB = orbitalsA.CheckDegeneracy(levelB,_degeneracy);\n\n        double JAB_sq = 0;\n\n        for (int iA : list_levelsA) {\n          for (int iB : list_levelsB) {\n            double JAB_one_level = JAB(iA - 1, iB - 1 + levelsA);\n            JAB_sq += JAB_one_level*JAB_one_level;\n          }\n        }\n        return std::sqrt(JAB_sq / (list_levelsA.size() * list_levelsB.size())) * tools::conv::hrt2ev;\n      } else {\n        return JAB(levelA - 1, levelB - 1 + levelsA) * tools::conv::hrt2ev;\n      }\n}\n\n\n\n/**\n * \\brief evaluates electronic couplings  \n * @param _orbitalsA molecular orbitals of molecule A\n * @param _orbitalsB molecular orbitals of molecule B\n * @param _orbitalsAB molecular orbitals of the dimer AB\n */\nvoid DFTcoupling::CalculateCouplings(const Orbitals& orbitalsA, const Orbitals& orbitalsB, \n    Orbitals& orbitalsAB) {\n\n    CTP_LOG(ctp::logDEBUG,*_pLog) << \"Calculating electronic couplings\" << flush;\n    \n    CheckAtomCoordinates(orbitalsA, orbitalsB, orbitalsAB);\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       throw std::runtime_error( \"Basis set size is not stored in monomers\");\n    }\n    \n    Range_orbA=DetermineRangeOfStates(orbitalsA,_numberofstatesA);\n    Range_orbB=DetermineRangeOfStates(orbitalsB,_numberofstatesB);\n    \n    int levelsA = Range_orbA.second;\n    int levelsB = Range_orbB.second;\n    \n    CTP_LOG(ctp::logDEBUG,*_pLog) << \"Levels:Basis A[\" << levelsA << \":\" << basisA << \"]\"\n                                     << \" B[\" << levelsB << \":\" << basisB << \"]\" << flush;\n    \n    if ( ( levelsA == 0 ) || (levelsB == 0) ) {\n         throw std::runtime_error(\"No information about number of occupied/unoccupied levels is stored\");\n    } \n    \n    //       | Orbitals_A          0 |      | Overlap_A |     \n    //       | 0          Orbitals_B |.T  X   | Overlap_B |  X  ( Orbitals_AB )\n \n    \n    Eigen::MatrixXd psi_AxB=Eigen::MatrixXd::Zero( basisA + basisB, levelsA + levelsB  );\n    \n      CTP_LOG(ctp::logDEBUG,*_pLog) << \"Constructing direct product AxB [\" \n            << psi_AxB.rows() << \"x\" \n            << psi_AxB.cols() << \"]\" << flush;    \n    \n    // constructing merged orbitals\n    psi_AxB.block(0,0, basisA,levelsA) = orbitalsA.MOCoefficients().block(0,Range_orbA.first,basisA,Range_orbA.second);\n    psi_AxB.block(basisA,levelsA, basisB,levelsB) =orbitalsB.MOCoefficients().block(0,Range_orbB.first,basisB,Range_orbB.second);\n   \n    Eigen::MatrixXd overlap;\n    if ( orbitalsAB.hasAOOverlap() ) {\n            CTP_LOG(ctp::logDEBUG,*_pLog) << \"Reading overlap matrix from orbitals\" << flush; \n           overlap= orbitalsAB.AOOverlap();\n    }else{\n        CTP_LOG(ctp::logDEBUG,*_pLog) << \"Calculating overlap matrix for basisset: \"<< orbitalsAB.getDFTbasis()<< flush; \n        overlap=CalculateOverlapMatrix(orbitalsAB);\n    }\n     CTP_LOG(ctp::logDEBUG,*_pLog) << \"Projecting dimer onto monomer orbitals\" << flush; \n    Eigen::MatrixXd psi_AxB_dimer_basis =psi_AxB.transpose()*overlap*orbitalsAB.MOCoefficients(); \n\n    unsigned int LevelsA = levelsA;\n    for (unsigned i=0;i<psi_AxB_dimer_basis.rows();i++){\n        double mag=psi_AxB_dimer_basis.row(i).squaredNorm();\n        if (mag<0.95){\n            int monomer = 0;\n            int level = 0;\n            if ( i < LevelsA ) {\n                monomer = 1;\n                level   = i;\n            } else {\n                monomer = 2;\n                level   = i -levelsA;\n                \n            }\n            CTP_LOG(ctp::logERROR,*_pLog) << \"\\nWarning: \" << i << \" Projection of orbital \" << level \n                    << \" of monomer \" << monomer << \" on dimer is insufficient,mag=\"<<mag\n                    <<\" maybe the orbital order is screwed up, otherwise increase dimer basis.\\n\"<<flush;\n        }\n    }\n    CTP_LOG(ctp::logDEBUG,*_pLog) << \"Projecting the Fock matrix onto the dimer basis\" << flush;         \n    Eigen::MatrixXd JAB_dimer = psi_AxB_dimer_basis*orbitalsAB.MOEnergies().asDiagonal()*psi_AxB_dimer_basis.transpose();  \n    CTP_LOG(ctp::logDEBUG,*_pLog) << \"Constructing Overlap matrix\" << flush;    \n    Eigen::MatrixXd S_AxB = psi_AxB_dimer_basis*psi_AxB_dimer_basis.transpose();    \n   Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(S_AxB);\n   Eigen::MatrixXd Sm1=es.operatorInverseSqrt();\n   CTP_LOG(ctp::logDEBUG,*_pLog) << \"Smallest eigenvalue of overlap matrix is \"<<es.eigenvalues()(0)<< flush;    \n   JAB = Sm1*JAB_dimer*Sm1;\n    CTP_LOG(ctp::logDEBUG,*_pLog) << \"Done with electronic couplings\" << flush;\n\n}\n\n\n    \n}}\n", "meta": {"hexsha": "117c9a5e0f768cbe0eb4ac9458bfe784628b711d", "size": 8777, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/dftcoupling.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/dftcoupling.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/dftcoupling.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8318965517, "max_line_length": 129, "alphanum_fraction": 0.6488549618, "num_tokens": 2483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.044680870908698676, "lm_q1q2_score": 0.01870774320498523}}
{"text": "#include <memory>\n#include <cstdio>\n#include <boost/program_options.hpp>\n#include \"THYAnalysis.h\"\n#include \"TICBjTest.h\"\n#include \"TRNavier3DBj.h\"\n#include \"TDomain3D.h\"\n#include \"TGrid3D.h\"\n#include \"THydro3DBj.h\"\n#include \"TIC3D.h\"\n\nusing namespace std ;\n\n//! Purpose:\n//!\n//! To simulate second order hydro for a boost invariant expansion, and \n//! to produce output that can be compared to the full hydro evolution.\n//!\n//! Usage\n//!\n//! test_icbj [--no-entropy-rewite] nametag\n//!\n//! Inputs:\n//!\n//! * The nametag. The program reads nametag.ini and generates the output Of\n//! course the input file should be setup with the initial conditions\n//! TICBjTest, so that the hydro solution will correspond to a (infinite in\n//! transverse extent bjorken solution.\n//!\n//! * If the command line option is specified. Then the evolution is \n//! done without multiplying by the entropy and using ideal EOM.\n//!\n//! Outputs:\n//!\n//! On output the program produces a data file with the variables as a function of time. See the fprintf statement below for the variable list.\n//!\n//! The filename is nametage_icbj_srewrite.out if the entropy rewrite is used,\n//! and nametag_icbj_nosrewrite.out if the entropy rewrite is not used.\n//!\nint main(int argc, char **argv) \n{\n   bool use_entropy_rewrite = true ;\n   std::string nametag;\n   if (argc == 2) {\n      nametag = argv[1] ;\n   } else if (argc ==3) {\n      use_entropy_rewrite = false ;\n      std::string s = argv[1] ;\n      if (s != \"--no-entropy-rewrite\") {\n         cout << \"Usage is test_icbj [--no-entropy-rewrite] nametag. \" << endl;\n      }\n      nametag = argv[2] ;\n   } else {\n      cout << \"Usage is test_icbj [--no-entropy-rewrite] nametag. \" << endl;\n   }\n\n   TRNavier3DBj rn(nametag.c_str(), make_eos_gammalaw) ;\n   THydro3DBj hy(&rn, make_ic_icbjtest) ;\n   THModel3D *hm = rn.getHModel3D() ;\n\n   // Extract the parameters from the class\n   TICBjTest *ic = dynamic_cast<TICBjTest *>(hy.getIC()) ;\n   double s0 = ic->getS0() ;\n   double t0 = ic->getTau0() ;\n   double novers = ic->getNOverS() ;\n   double pioverpins = ic->getPiOverPiNS() ;\n   double c1 = ic->getCutoffC1() ;\n\n   // Set the time equal to the initial time\n   double t = t0 ;\n\n   // determine initial conditions for e and n and other thermo variables\n   double s = s0/t;\n   double n = novers*s ;\n   double e = hm->getEOS()->eofs(s, n) ;\n   double p, cs ;\n   hm->getEOS()->eos(e, n, p, cs) ;\n   double temper, mu ;\n   hm->getEOS()->stmu(e, n, s, temper, mu) ;\n\n\n   // Determine the viscosities needed\n   double sigma_overs, kappaT_overs, eta_overs ; \n   hm->getEOS()->viscosity(e, n, sigma_overs, kappaT_overs, eta_overs) ;\n   double eta = eta_overs*s ;\n   double tpi_over_etast, l1, l2 ;\n   //l1 and l2 are lambda_1/(eta*tau*pi) and lambda_2/(eta*tau_pi)\n   hm->getEOS()->getBRSSSParams(e,n, tpi_over_etast, l1, l2)  ;\n   double tpi = tpi_over_etast * eta/(s*temper) ;\n\n\n   //Determine the initial conditions for pi.\n   double pins = -4./3.*eta/t ; //navier stokes value\n   double pi   = pioverpins * pins;\n   double tr = 3./2.*pi*pi ;    //tr(piij*piij) \n   pi = pi/(1. + c1 * tr/(p*p)) ; // regulator used\n   double spi = s * pi * t;\n\n   // determine the nonlinear coupling\n   double sig = 4./3./t ;\n   tr = 3./2.*pi*sig ;\n   double pi_sig = 0.5*pi*sig + 0.5*pi*sig - 1./3.*tr ; \n\n   // Set time stepping parameters\n   double dt = 0.001 ;\n   double tmax =  3. ;\n   int nsteps = (tmax - hy.getTime())/dt ; \n\n   // TODO \n   // Determine the integration constant c0ns for the analytic\n   // solution of first order viscous hydro. For speed of sound^2=1/3.\n   // Also set the (analytic) expectations. Add the analytic\n   // solution to the printout\n\n   // Open the output file\n   std::string name ;\n   if (use_entropy_rewrite) {\n      name = rn.getNametag() + \"_srewrite\" + \"_icbj.out\";\n   } else {\n      name = rn.getNametag() + \"_nosrewrite\" + \"_icbj.out\";\n   }\n   FILE *fp = fopen(name.c_str(), \"w\") ;\n\n   // Forward euler\n   for (int itime = 0 ;  itime < nsteps ; itime++) {\n      // Print out the results and navier stokes expectation for ideal gas.\n      fprintf(fp, \n              \"%15.5e %15.5e %15.5e %15.5e \"\n              \"%15.5e %15.5e %15.5e %15.5e \\n\", \n            t, e, n, p,\n            s, temper, pins, pi) ;\n\n      // Take a step\n      e +=  -dt * (e + p + pi)/t ;\n\n      n +=  -dt  * n / t ;\n\n      pi += dt * (- 1./tpi*pi  + pins/tpi - 4./3.*pi/t - l1*pi_sig);\n\n      spi +=  -dt * t * s * (1./tpi*pi  - pins/tpi + 4./3.*pi/t + l1*pi_sig);\n\n      t += dt ;\n\n      // determine parameters for next time step\n      hm->getEOS()->eos(e, n, p, cs) ;\n      hm->getEOS()->stmu(e, n, s, temper, mu) ;\n      hm->getEOS()->viscosity(e, n, sigma_overs, kappaT_overs, eta_overs) ;\n      eta = eta_overs*s ;\n      hm->getEOS()->getBRSSSParams(e, n, tpi_over_etast, l1, l2) ; \n      tpi = tpi_over_etast * eta/(s*temper) ;\n      pins = -4./3.*eta/t ; \n      sig = 4./3./t ;\n      tr = 3./2.*pi*sig ;\n      pi_sig = 0.5*pi*sig + 0.5*pi*sig - 1./3.*tr ; \n\n      // set spi or pi. Depending on which equations we want to solve\n      if (use_entropy_rewrite) {\n         pi = spi/(s*t);  // pi is determined by spi\n      } else{\n         spi = pi*s*t;  // spi is determined by pi\n      }\n   }\n   fclose(fp) ;\n   \n}\n", "meta": {"hexsha": "3701bed5389a211e7a6bb0bc9433c0bdcba83829", "size": 5237, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/test_core/test_icbj.cxx", "max_stars_repo_name": "rnavier/rnavier", "max_stars_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-08-04T14:02:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T15:03:33.000Z", "max_issues_repo_path": "src/test_core/test_icbj.cxx", "max_issues_repo_name": "rnavier/rnavier", "max_issues_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_issues_repo_licenses": ["MIT"], "max_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_core/test_icbj.cxx", "max_forks_repo_name": "rnavier/rnavier", "max_forks_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_forks_repo_licenses": ["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.5481927711, "max_line_length": 143, "alphanum_fraction": 0.6039717395, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.04023794636414335, "lm_q1q2_score": 0.018706684493528365}}
{"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_CASS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_CASS_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/pj_mlfn.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace cass\n    {\n\n            //static const double epsilon10 = 1e-10;\n            //static const double C1 = .16666666666666666666;\n            //static const double C2 = .00833333333333333333;\n            //static const double C3 = .04166666666666666666;\n            //static const double C4 = .33333333333333333333;\n            //static const double C5 = .06666666666666666666;\n\n            template <typename T>\n            inline T C1() { return .16666666666666666666666666666666666666; }\n            template <typename T>\n            inline T C2() { return .00833333333333333333333333333333333333; }\n            template <typename T>\n            inline T C3() { return .04166666666666666666666666666666666666; }\n            template <typename T>\n            inline T C4() { return .33333333333333333333333333333333333333; }\n            template <typename T>\n            inline T C5() { return .06666666666666666666666666666666666666; }\n\n            template <typename T>\n            struct par_cass\n            {\n                T m0;\n                detail::en<T> en;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_cass_ellipsoid\n                : public base_t_fi<base_cass_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_cass<T> m_proj_parm;\n\n                inline base_cass_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_cass_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                    static const T C1 = cass::C1<T>();\n                    static const T C2 = cass::C2<T>();\n                    static const T C3 = cass::C3<T>();\n\n                    T n = sin(lp_lat);\n                    T c = cos(lp_lat);\n                    xy_y = pj_mlfn(lp_lat, n, c, this->m_proj_parm.en);\n                    n = 1./sqrt(1. - this->m_par.es * n * n);\n                    T tn = tan(lp_lat);\n                    T t = tn * tn;\n                    T a1 = lp_lon * c;\n                    c *= this->m_par.es * c / (1 - this->m_par.es);\n                    T a2 = a1 * a1;\n                    xy_x = n * a1 * (1. - a2 * t *\n                        (C1 - (8. - t + 8. * c) * a2 * C2));\n                    xy_y -= this->m_proj_parm.m0 - n * tn * a2 *\n                        (.5 + (5. - t + 6. * c) * a2 * C3);\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 C3 = cass::C3<T>();\n                    static const T C4 = cass::C4<T>();\n                    static const T C5 = cass::C5<T>();\n\n                    T ph1;\n\n                    ph1 = pj_inv_mlfn(this->m_proj_parm.m0 + xy_y, this->m_par.es, this->m_proj_parm.en);\n                    T tn = tan(ph1); T t = tn * tn;\n                    T n = sin(ph1);\n                    T r = 1. / (1. - this->m_par.es * n * n);\n                    n = sqrt(r);\n                    r *= (1. - this->m_par.es) * n;\n                    T dd = xy_x / n;\n                    T d2 = dd * dd;\n                    lp_lat = ph1 - (n * tn / r) * d2 *\n                        (.5 - (1. + 3. * t) * d2 * C3);\n                    lp_lon = dd * (1. + t * d2 *\n                        (-C4 + (1. + 3. * t) * d2 * C5)) / cos(ph1);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"cass_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_cass_spheroid\n                : public base_t_fi<base_cass_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_cass<T> m_proj_parm;\n\n                inline base_cass_spheroid(const Parameters& par)\n                    : base_t_fi<base_cass_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    xy_x = asin(cos(lp_lat) * sin(lp_lon));\n                    xy_y = atan2(tan(lp_lat) , cos(lp_lon)) - this->m_par.phi0;\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    T dd = xy_y + this->m_par.phi0;\n                    lp_lat = asin(sin(dd) * cos(xy_x));\n                    lp_lon = atan2(tan(xy_x), cos(dd));\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"cass_spheroid\";\n                }\n\n            };\n\n            // Cassini\n            template <typename Parameters, typename T>\n            inline void setup_cass(Parameters& par, par_cass<T>& proj_parm)\n            {\n                if (par.es) {\n                    proj_parm.en = pj_enfn<T>(par.es);\n                    proj_parm.m0 = pj_mlfn(par.phi0, sin(par.phi0), cos(par.phi0), proj_parm.en);\n                } else {\n                }\n            }\n\n    }} // namespace detail::cass\n    #endif // doxygen\n\n    /*!\n        \\brief Cassini projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_cass.gif\n    */\n    template <typename T, typename Parameters>\n    struct cass_ellipsoid : public detail::cass::base_cass_ellipsoid<T, Parameters>\n    {\n        template <typename Params>\n        inline cass_ellipsoid(Params const& , Parameters const& par)\n            : detail::cass::base_cass_ellipsoid<T, Parameters>(par)\n        {\n            detail::cass::setup_cass(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Cassini projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n        \\par Example\n        \\image html ex_cass.gif\n    */\n    template <typename T, typename Parameters>\n    struct cass_spheroid : public detail::cass::base_cass_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline cass_spheroid(Params const& , Parameters const& par)\n            : detail::cass::base_cass_spheroid<T, Parameters>(par)\n        {\n            detail::cass::setup_cass(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_cass, cass_spheroid, cass_ellipsoid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI2(cass_entry, cass_spheroid, cass_ellipsoid)\n\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(cass_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(cass, cass_entry);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_CASS_HPP\n\n", "meta": {"hexsha": "4f68cd01bb7b72801f8d509c8ae4973d6966da84", "size": 10459, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/cass.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/cass.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/cass.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 38.737037037, "max_line_length": 112, "alphanum_fraction": 0.5687924276, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.03789242907421237, "lm_q1q2_score": 0.01865020402396906}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include <niftkConversionUtils.h>\n#include <niftkCommandLineParser.h>\n\n#include <itkImage.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkNifTKImageIOFactory.h>\n\n#include <itkTransformFileWriter.h>\n#include <itkTransformFactory.h>\n\n#include <itkGE5000_TomosynthesisGeometry.h>\n#include <itkGE6000_TomosynthesisGeometry.h>\n#include <itkSiemensMammomat_TomosynthesisGeometry.h>\n#include <itkIsocentricConeBeamRotationGeometry.h>\n\n#include <itkImageReconstructionMetric.h>\n\n#include <itkConjugateGradientMaxIterOptimizer.h>\n#include <itkConjugateGradientOptimizer.h>\n#include <itkRegularStepGradientDescentOptimizer.h>\n#include <itkLBFGSOptimizer.h>\n\n#include <itkImageReconstructionMethod.h>\n\n#include <itkCastImageFilter.h>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#ifndef HZ\n  #if defined(__APPLE__)\n    #define HZ __DARWIN_CLK_TCK\n  #endif\n#endif\n\n\n/* -----------------------------------------------------------------------\n   The Command Line Structure\n   ----------------------------------------------------------------------- */\n\nstruct niftk::CommandLineArgumentDescription clArgList[] = {\n\n  {OPT_SWITCH, \"v\", NULL,   \"Output verbose info\"},\n  {OPT_SWITCH, \"dbg\", NULL, \"Output debugging info\"},\n\n  {OPT_INT, \"niters\", \"n\", \"Set the maximum number of iterations (set to zero to turn off) [10]\"},\n\n  {OPT_INT,  \"opt\", \"n\", \"The optimizer to use. Options are:\\n\"\n                         \"           0    Conjugate gradient with max iterations [default],\\n\"\n                         \"           1    Limited Memory BFGS,\\n\"\n                         \"           2    Regular step gradient descent,\\n\"\n                         \"           3    Conjugate gradient.\"},\n\n  {OPT_STRING,  \"est\", \"filename\", \"Input current estimate of the 3D volume\"},\n\n  {OPT_INTx3,   \"s3D\", \"nx,ny,nz\", \"The size of the reconstructed volume [100 x 100 x 100]\"},\n  {OPT_FLOATx3, \"r3D\", \"rx,ry,rz\", \"The resolution of the reconstructed volume [1mm x 1mm x 1mm]\"},\n  {OPT_FLOATx3, \"o3D\", \"ox,oy,oz\", \"The origin of the reconstructed volume [0mm x 0mm x 0mm]\"},\n\n  {OPT_DOUBLE, \"FirstAngle\", \"theta\",   \"ISOCENTRIC: The angle of the first projection in the sequence [-89]\"},\n  {OPT_DOUBLE, \"AngRange\", \"range\",     \"ISOCENTRIC: The full angular range of the sequence [180]\"},\n  {OPT_DOUBLE, \"FocalLength\", \"length\", \"ISOCENTRIC: The focal length of the projection [660]\"},\n  {OPT_INT,    \"axis\", \"number\",        \"ISOCENTRIC: The axis about which to rotate, 1:'x', 2:'y', 3:'z' [2:'y']\"},\n\t    \n  {OPT_DOUBLE,  \"transX\", \"angle\", \"ISOCENTRIC: Add an additional translation in 'x' [none]\"},\n  {OPT_DOUBLE,  \"transY\", \"angle\", \"ISOCENTRIC: Add an additional translation in 'y' [none]\"},\n  {OPT_DOUBLE,  \"transZ\", \"angle\", \"ISOCENTRIC: Add an additional translation in 'z' [none]\"},\n  \n  {OPT_SWITCH,  \"GE5000\", 0, \"Use the 'old' GE-5000, 11 projection geometry [21 projection]\"},\n  {OPT_SWITCH,  \"GE6000\", 0, \"Use the 'new' GE-6000, 15 projection geometry [21 projection]\"},\n  \n  {OPT_SWITCH,  \"Mammomat\", 0, \"Use the Siemens Mammomat Inspiration 25 projection geometry [21 projection]\"},\n  \n  {OPT_DOUBLE,  \"thetaX\", \"angle\", \"Add an additional rotation in 'x' [none]\"},\n  {OPT_DOUBLE,  \"thetaY\", \"angle\", \"Add an additional rotation in 'y' [none]\"},\n  {OPT_DOUBLE,  \"thetaZ\", \"angle\", \"Add an additional rotation in 'z' [none]\"},\n\t    \n  {OPT_STRING,  \"oCurrEstFile\", \"filestem\", \"Write the current reconstruction estimate to a file (i.e. filestem_04d%.suffix)\"},\n  {OPT_STRING,  \"oCurrEstSuffix\", \"suffix\", \"Write the current reconstruction estimate to a file (i.e. filestem_04d%.suffix) [nii]\"},\n\n  {OPT_STRING,  \"oGeom\", \"filestem\", \"Write out the affine and projection geometries to a set of files\"},\n  {OPT_STRING,  \"oTime\", \"filename\", \"Time execution and save value to a file\"},\n\n  {OPT_STRING|OPT_REQ,  \"o\", \"filename\", \"Output 3D reconstructed volume\"},\n\n  {OPT_STRING|OPT_REQ,  \"projs\", \"filename\", \"Input volume of 2D projection images\"},\n\n  {OPT_DONE, NULL, NULL, \n   \"Compute a reconstructed volume from a set of projection images and an initial estimate (or zero).\\n\"\n  }\n};\n\nenum {\n  O_VERBOSE = 0,\n  O_DEBUG,\n\n  O_NITERS,\n\n  O_OPTIMISER,\n\n  O_FILE_ESTIMATE,\n\n  O_RECONSTRUCTION_SIZE,\n  O_RECONSTRUCTION_RES,\n  O_RECONSTRUCTION_ORIGIN,\n\n  O_FIRST_ANGLE,\n  O_ANGULAR_RANGE,\n  O_FOCAL_LENGTH,\n  O_AXIS_NUMBER,\n\n  O_TRANSX,\n  O_TRANSY,\n  O_TRANSZ,\n\n  O_GE5000,\n  O_GE6000,\n\n  O_MAMMOMAT,\n\n  O_THETAX,\n  O_THETAY,\n  O_THETAZ,\n\n  O_CURRENT_RECON_FILESTEM,\n  O_CURRENT_RECON_SUFFIX,\n\n  O_OUTPUT_GEOMETRY,\n  O_TIME,\n\n  O_OUTPUT_RECONSTRUCTION,\n\n  O_INPUT_PROJECTIONS\n};\n \n\n/* -----------------------------------------------------------------------\n   Optimizer types\n   ----------------------------------------------------------------------- */\n\ntypedef enum {\n  OPTIMIZER_CONJUGATE_GRADIENT_MAXITER,\n  OPTIMIZER_LIMITED_MEMORY_BFGS,\n  OPTIMIZER_REGULAR_STEP_GRADIENT_DESCENT,\n  OPTIMIZER_CONJUGATE_GRADIENT,\n  OPTIMIZER_UNSET\n} enumOptimizerType;\n\nconst char *nameOptimizer[5] = {\n  \"Conjugate Gradient (Maximum Iterations)\",\n  \"LBFGS Optimizer\",\n  \"Regular Step Gradient Descent\",\n  \"Conjugate Gradient\",\n  \"Unset\"\n};\n\n\n\n\n/* -----------------------------------------------------------------------\n   main()\n   ----------------------------------------------------------------------- */\n\nint main(int argc, char** argv)\n{\n  itk::NifTKImageIOFactory::Initialize();\n\n  bool flgDebug = false;\n\n  bool flgFirstAngleSet = false; // Has the user set the first angle\n\n  bool flgGE_5000 = false;\t// Use the GE 5000 11 projection geometry\n  bool flgGE_6000 = false;\t// Use the GE 6000 15 projection geometry\n  bool flgMammomat = false;\t// Use the Siemens Mammomat Inspiration 25 projection geometry\n\n  bool flgTransX = false;\t// Translation in 'x' has been set\n  bool flgTransY = false;\t// Translation in 'y' has been set\n  bool flgTransZ = false;\t// Translation in 'z' has been set\n\n  char filename[256];\n\n  unsigned int nProjections = 0; // The number of projections in the sequence\n\n  int axis  = 0;\t\t// The axis about which to rotate\n  int clo_optimiser = 0;\n  int nIterations = 10;\t\t// The maximum number of iterations\n\n  int *clo_size = 0;\t\t// The size of the reconstructed volume\n\n  float *clo_res = 0;\t\t// The resolution of the reconstructed volume\n  float *clo_origin = 0;\t\t// The origin of the reconstructed volume\n\n  double firstAngle = 0;         // The angle of the first projection in the sequence\n  double angularRange = 0;       // The full angular range of the sequence\n  double focalLength = 0;        // The focal length of the projection\n\n  double thetaX = 0;\t\t // An additional rotation in 'x'\n  double thetaY = 0;\t\t // An additional rotation in 'y'\n  double thetaZ = 0;\t\t // An additional rotation in 'z'\n\n  double transX = 0;\t\t // An additional translation in 'x'\n  double transY = 0;\t\t // An additional translation in 'y'\n  double transZ = 0;\t\t // An additional translation in 'z'\n\n  enumOptimizerType enumOptimizer =  OPTIMIZER_CONJUGATE_GRADIENT_MAXITER;\n\n  typedef double IntensityType;\n  typedef itk::ImageReconstructionMethod<IntensityType> ImageReconstructionMethodType;\n\n  typedef ImageReconstructionMethodType::ReconstructionType        ReconstructionType;\n\n  typedef ImageReconstructionMethodType::InputProjectionVolumeType InputProjectionType;\n  typedef ImageReconstructionMethodType::ReconstructionType        ReconstructionType;\n\n  typedef itk::ImageFileReader< ReconstructionType >  ReconEstimateReaderType;\n  typedef itk::ImageFileReader< InputProjectionType > InputProjectionReaderType;\n\n  typedef itk::ProjectionGeometry< IntensityType > ProjectionGeometryType;\n\n\n  std::string fileOutputGeometry;\n\n  std::string fileOutputCurrentEstimate;\n  std::string suffixOutputCurrentEstimate;\n\n  std::string fileInputProjectionVolume;\n  std::string fileInputCurrentEstimate;\n  std::string fileOutputReconstruction;\n  std::string fileOutputExecutionTime;\n\n  bool flgInputImage3D_SizeSet = false;\t// Has the user specified the 3D image size?\n  bool flgInputImage3D_ResSet = false;\t// Has the user specified the 3D image resolution?\n\n  ImageReconstructionMethodType::ReconstructionSizeType    nVoxels3D; // The dimensions in voxels of the reconstruction\n  ImageReconstructionMethodType::ReconstructionSpacingType spacing3D; // The resolution in mm of the reconstruction\n  ImageReconstructionMethodType::ReconstructionPointType   origin3D;  // The origin in mm of the reconstruction\n\n  // Create the command line parser, passing the\n  // 'CommandLineArgumentDescription' structure. The final boolean\n  // parameter indicates whether the command line options should be\n  // printed out as they are parsed.\n\n  niftk::CommandLineParser CommandLineOptions(argc, argv, clArgList, false);\n  \n  CommandLineOptions.GetArgument(O_NITERS, nIterations);\n\n  if (CommandLineOptions.GetArgument(O_OPTIMISER, clo_optimiser))\n    enumOptimizer = (enumOptimizerType) clo_optimiser;\n\n  CommandLineOptions.GetArgument(O_FILE_ESTIMATE, fileInputCurrentEstimate);\n\n  if (CommandLineOptions.GetArgument(O_RECONSTRUCTION_SIZE, clo_size)) {\n    nVoxels3D[0] = clo_size[0];\n    nVoxels3D[1] = clo_size[1];\n    nVoxels3D[2] = clo_size[2];\n  }\n  else {\n    nVoxels3D[0] = 100;\n    nVoxels3D[1] = 100;\n    nVoxels3D[2] = 100;\n  }\n\n  if (CommandLineOptions.GetArgument(O_RECONSTRUCTION_RES, clo_res)) {\n    spacing3D[0] = clo_res[0];\n    spacing3D[1] = clo_res[1];\n    spacing3D[2] = clo_res[2];\n  }\n  else {\n    spacing3D[0] = 1.;\n    spacing3D[1] = 1.;\n    spacing3D[2] = 1.;\n  }\n\n  if (CommandLineOptions.GetArgument(O_RECONSTRUCTION_ORIGIN, clo_origin)) {\n    origin3D[0] = clo_origin[0];\n    origin3D[1] = clo_origin[1];\n    origin3D[2] = clo_origin[2];\n  }\n  else {\n    origin3D[0] = 0.;\n    origin3D[1] = 0.;\n    origin3D[2] = 0.;\n  }\n\n  flgFirstAngleSet = CommandLineOptions.GetArgument(O_FIRST_ANGLE, firstAngle);\n\n  CommandLineOptions.GetArgument(O_ANGULAR_RANGE, angularRange);\n  CommandLineOptions.GetArgument(O_FOCAL_LENGTH, focalLength);\n  CommandLineOptions.GetArgument(O_AXIS_NUMBER, axis);\n\n  CommandLineOptions.GetArgument(O_GE5000, flgGE_5000);\n  CommandLineOptions.GetArgument(O_GE6000, flgGE_6000);\n\n  CommandLineOptions.GetArgument(O_MAMMOMAT, flgMammomat);\n\n  CommandLineOptions.GetArgument(O_THETAX, thetaX);\n  CommandLineOptions.GetArgument(O_THETAY, thetaY);\n  CommandLineOptions.GetArgument(O_THETAZ, thetaZ);\n\n  flgTransX = CommandLineOptions.GetArgument(O_TRANSX, transX);\n  flgTransY = CommandLineOptions.GetArgument(O_TRANSY, transY);\n  flgTransZ = CommandLineOptions.GetArgument(O_TRANSZ, transZ);\n\n  CommandLineOptions.GetArgument(O_CURRENT_RECON_FILESTEM, fileOutputCurrentEstimate);\n  CommandLineOptions.GetArgument(O_CURRENT_RECON_SUFFIX, suffixOutputCurrentEstimate);\n\n  CommandLineOptions.GetArgument(O_OUTPUT_GEOMETRY, fileOutputGeometry);\n  CommandLineOptions.GetArgument(O_TIME, fileOutputExecutionTime);\n\n  CommandLineOptions.GetArgument(O_OUTPUT_RECONSTRUCTION, fileOutputReconstruction);\n\n  CommandLineOptions.GetArgument(O_INPUT_PROJECTIONS, fileInputProjectionVolume);\n\n\n  // Validate command line args\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~\n  \n\n  if ( fileInputProjectionVolume.length() == 0 || fileOutputReconstruction.length() == 0 ) {\n\n    CommandLineOptions.PrintUsage();\n    return EXIT_FAILURE;\n  }\n\n  if ( fileInputCurrentEstimate.length() != 0 && \n       ((flgInputImage3D_SizeSet == true) || (flgInputImage3D_ResSet == true)) ) {\n\n    std::cerr << \"Command line options '-est' and '-s3D' or '-r3D' are exclusive.\";\n\n    CommandLineOptions.PrintUsage();\n    return EXIT_FAILURE;\n  }\n\n  if ( ( flgGE_5000  && flgGE_6000 ) ||\n       ( flgGE_5000  && flgMammomat ) ||\n       ( flgMammomat && flgGE_6000 ) ) {\n\n    std::cerr << \"Command line options '-GE5000', '-GE6000'and '-Mammomat' are exclusive.\" \n              << std::endl;\n\n    CommandLineOptions.PrintUsage();\n    return EXIT_FAILURE;\n  }\n\n  if ( (flgGE_5000 || flgGE_6000 || flgMammomat) && \n       (flgFirstAngleSet || angularRange || focalLength || axis) ) {\n\n    std::cerr << \"Command line options '-GE5000' or '-GE6000' and \"\n              << \"'-1stAngle' or '-AngRange' or '-FocalLength' or '-axis' are exclusive.\";\n\n    return EXIT_FAILURE;\n  }\n\n  if ( (flgGE_5000 || flgGE_6000 || flgMammomat) && (flgTransX || flgTransY || flgTransZ) ) {\n\n    std::cerr <<\"Command line options '-transX|Y|Z' can only be used with isocentric geometry.\";\n\n    return EXIT_FAILURE;\n  }\n\n\n  // Create the reconstructor\n  // ~~~~~~~~~~~~~~~~~~~~~~~~\n\n  ImageReconstructionMethodType::Pointer imReconstructor = ImageReconstructionMethodType::New();\n\n\n  // Load the volume of 2D projection images\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  InputProjectionReaderType::Pointer inputProjectionReader  = InputProjectionReaderType::New();\n\n  inputProjectionReader->SetFileName( fileInputProjectionVolume );\n\n  try {\n    std::cout << \"Reading input volume of 2D projection images: \" << fileInputProjectionVolume << std::endl;\n    inputProjectionReader->Update();\n  }\n  catch( itk::ExceptionObject & err ) {\n    std::cerr << \"ERROR: Failed to load input projection volume: \" << fileInputProjectionVolume << \"; \" << err << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  nProjections = inputProjectionReader->GetOutput()->GetLargestPossibleRegion().GetSize()[2];\n\n  std::cout << \"Number of projections: \" << niftk::ConvertToString((int) nProjections) << std::endl;\n\n  imReconstructor->SetInputProjectionVolume( inputProjectionReader->GetOutput() );\n\n\n  // Load the current estimate (or create it)\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  if ( fileInputCurrentEstimate.length() != 0 ) {\n\n    ReconEstimateReaderType::Pointer inputEstimateReader  = ReconEstimateReaderType::New();\n\n    inputEstimateReader->SetFileName( fileInputCurrentEstimate );\n\n    try {\n      std::cout << \"Reading input 3D estimate: \" << fileInputCurrentEstimate << std::endl;\n      inputEstimateReader->Update();\n    }\n    catch( itk::ExceptionObject & err ) {\n      std::cerr << \"ERROR: Failed to load reconstruction estimate: \" << fileInputCurrentEstimate << \"; \" << err << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    nVoxels3D = inputEstimateReader->GetOutput()->GetLargestPossibleRegion().GetSize();\n    spacing3D = inputEstimateReader->GetOutput()->GetSpacing();\n    origin3D  = inputEstimateReader->GetOutput()->GetOrigin();\n\n    imReconstructor->SetReconEstimate(inputEstimateReader->GetOutput());\n  }\n\n  imReconstructor->SetReconstructedVolumeSize( nVoxels3D );\n  imReconstructor->SetReconstructedVolumeSpacing( spacing3D );\n  imReconstructor->SetReconstructedVolumeOrigin( origin3D );\n\n\n\n  // Create the tomosynthesis geometry\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  ProjectionGeometryType::Pointer geometry;\n\n  // Create the GE-5000 11 projection geometry\n\n  if (flgGE_5000) {\n\n    if (nProjections != 11) {\n      std::cerr << \"ERROR: Number of projections in input volume (\" << nProjections << \") must equal 11 for GE-5000 geometry\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    typedef itk::GE5000_TomosynthesisGeometry< IntensityType > GE5000_TomosynthesisGeometryType;\n    geometry = GE5000_TomosynthesisGeometryType::New();\n     \n  }\n\n  // Create the GE-6000 15 projection geometry\n\n  else if (flgGE_6000) {\n\n    if (nProjections != 15) {\n      std::cerr << \"ERROR: Number of projections in input volume (\" << nProjections << \") must equal 15 for GE-6000 geometry\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    typedef itk::GE6000_TomosynthesisGeometry< IntensityType > GE6000_TomosynthesisGeometryType;\n    geometry = GE6000_TomosynthesisGeometryType::New();\n  }\n\n  // Siemens Mammomat Inspiration 25 projection geometry\n\n  else if (flgMammomat) {\n\n    if (nProjections != 25) {\n      std::cerr << \"ERROR: Number of projections in input volume (\" << nProjections << \") must equal 25 for Siemens Mammomat geometry\" << std::endl;\n      return EXIT_FAILURE;\n    }\n    \n    typedef itk::SiemensMammomat_TomosynthesisGeometry< IntensityType > SiemensMammomat_TomosynthesisGeometryType;\n    geometry = SiemensMammomat_TomosynthesisGeometryType::New();\n  }\n\n  // Create an isocentric cone bean rotation geometry\n\n  else {\n\n    if (! flgFirstAngleSet) firstAngle = -89.;\n    if (! angularRange) angularRange = 180.;\n    if (! focalLength) focalLength = 660.;\n\n    typedef itk::IsocentricConeBeamRotationGeometry< IntensityType > IsocentricConeBeamRotationGeometryType;\n\n    IsocentricConeBeamRotationGeometryType::Pointer isoGeometry = IsocentricConeBeamRotationGeometryType::New();\n\n    isoGeometry->SetNumberOfProjections(nProjections);\n    isoGeometry->SetFirstAngle(firstAngle);\n    isoGeometry->SetAngularRange(angularRange);\n    isoGeometry->SetFocalLength(focalLength);\n\n    isoGeometry->SetTranslation(transX, transY, transZ);\n\n    if (axis) {\n\n      switch (axis) \n\t{\n\n\tcase 1: {\n\t  isoGeometry->SetRotationAxis(itk::ISOCENTRIC_CONE_BEAM_ROTATION_IN_X);\n\t  break;\n\t}\n\n\tcase 2: {\n\t  isoGeometry->SetRotationAxis(itk::ISOCENTRIC_CONE_BEAM_ROTATION_IN_Y);\n\t  break;\n\t}\n\n\tcase 3: {\n\t  isoGeometry->SetRotationAxis(itk::ISOCENTRIC_CONE_BEAM_ROTATION_IN_Z);\n\t  break;\n\t}\n\n\tdefault: {\n\t  std::cerr << \"Command line option '-axis' must be: 1, 2 or 3.\";\n\t  \n\t  CommandLineOptions.PrintUsage();\n\t  return EXIT_FAILURE;\n\t}\n\t}\n    }\n\n    geometry = isoGeometry;\n  }\n\n  if (thetaX) geometry->SetRotationInX(thetaX);\n  if (thetaY) geometry->SetRotationInY(thetaY);\n  if (thetaZ) geometry->SetRotationInZ(thetaZ);\n\n  std::cout << \"Projection geometry:\" << std::endl;\n  geometry->Print(std::cout);\n\n  imReconstructor->SetProjectionGeometry( geometry );\n\n\n  // Create the optimizer\n  // ~~~~~~~~~~~~~~~~~~~~\n\n  std::cout << \"Optimiser: \" << nameOptimizer[enumOptimizer] << std::endl;\n\n  switch (enumOptimizer)\n    {\n\n    case OPTIMIZER_CONJUGATE_GRADIENT_MAXITER: {\n\n      typedef itk::ConjugateGradientMaxIterOptimizer OptimizerType;\n      OptimizerType::Pointer optimizer = OptimizerType::New();\n\n      if (nIterations)\n\toptimizer->SetMaximumNumberOfFunctionEvaluations(nIterations);\n\n      std::cout << \"Maximum number of iterations set to: \" << niftk::ConvertToString((int) nIterations) << std::endl;\n\n      imReconstructor->SetOptimizer( optimizer );\n      break;\n    }\n\n    case OPTIMIZER_LIMITED_MEMORY_BFGS: {\n\n      typedef itk::LBFGSOptimizer OptimizerType;\n      OptimizerType::Pointer optimizer = OptimizerType::New();\n\n      if (nIterations)\n\toptimizer->SetMaximumNumberOfFunctionEvaluations(nIterations);\n\n      std::cout << \"Maximum number of iterations set to: \" << niftk::ConvertToString((int) nIterations) << std::endl;\n\n      imReconstructor->SetOptimizer( optimizer );\n      break;\n    }\n\n    case OPTIMIZER_REGULAR_STEP_GRADIENT_DESCENT: {\n\n      typedef itk::RegularStepGradientDescentOptimizer OptimizerType;\n      OptimizerType::Pointer optimizer = OptimizerType::New();\n\n      imReconstructor->SetOptimizer( optimizer );\n      break;\n    }\n\n    case OPTIMIZER_CONJUGATE_GRADIENT: {\n\n      typedef itk::ConjugateGradientOptimizer OptimizerType;\n      OptimizerType::Pointer optimizer = OptimizerType::New();\n\n      imReconstructor->SetOptimizer( optimizer );\n      break;\n    }\n\n    default: {\n      std::cerr << argv[0]\n\t\t\t\t     << \"Optimizer type: '\"\n\t\t\t\t     << niftk::ConvertToString(nameOptimizer[enumOptimizer])\n\t\t\t\t     << \"' not recognised.\";\n      return -1;\n    }\n    }\n\n\n  // Create the metric\n  // ~~~~~~~~~~~~~~~~~\n\n  typedef itk::ImageReconstructionMetric< IntensityType > ImageReconstructionMetricType;\n  ImageReconstructionMetricType::Pointer metric = ImageReconstructionMetricType::New();\n\n  if ( fileOutputCurrentEstimate.length() > 0 )\n    metric->SetIterativeReconEstimateFile( fileOutputCurrentEstimate );\n  \n  if ( suffixOutputCurrentEstimate.length() > 0 )\n    metric->SetIterativeReconEstimateSuffix( suffixOutputCurrentEstimate );\n  \n  imReconstructor->SetMetric( metric );\n\n\n  // Initialise the start time\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  boost::posix_time::ptime startTime = boost::posix_time::second_clock::local_time();\n\n\n  // Perform the reconstruction\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  try {\n    std::cout << \"Starting reconstruction...\" << std::endl;\n\n    if (flgDebug)\n      std::cout << \"ImageReconstructionMethod: \" << imReconstructor << std::endl;\n\n    imReconstructor->Update();\n    std::cout << \"Reconstruction complete\" << std::endl;\n  }\n  catch( itk::ExceptionObject & err ) {\n    std::cerr << \"ERROR: Failed to calculate the reconstruction; \" << err << std::endl;\n    return EXIT_FAILURE;\n  }\n\n\n  // Calculate the execution time\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  boost::posix_time::ptime endTime = boost::posix_time::second_clock::local_time();\n  boost::posix_time::time_duration duration = endTime - startTime;\n\n  std::cout << \"Execution time: \" << boost::posix_time::to_simple_string(duration) << std::endl;\n\n  if (fileOutputExecutionTime.length() != 0) {\n    std::ofstream fout(fileOutputExecutionTime.c_str());\n\n    if ((! fout) || fout.bad()) {\n      std::cerr << \"ERROR: Could not open file: \" << fileOutputExecutionTime << std::endl;\n      return 1;\n    }\n\n    fout << \"Execution time: \" << boost::posix_time::to_simple_string(duration) << std::endl;\n\n    fout.close();\n  }\n\n\n  // Write the output reconstruction to a file\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  // First cast the image from double to float\n\n  typedef float OutputReconstructionType;\n  typedef itk::Image< OutputReconstructionType, 3 > OutputImageType;\n  typedef itk::CastImageFilter< ReconstructionType, OutputImageType > CastFilterType;\n\n  CastFilterType::Pointer  caster =  CastFilterType::New();\n\n  caster->SetInput( imReconstructor->GetOutput() );\n\n\n  // Then write the image\n\n  typedef itk::ImageFileWriter< OutputImageType > OutputImageWriterType;\n\n  OutputImageWriterType::Pointer writer = OutputImageWriterType::New();\n\n  writer->SetFileName( fileOutputReconstruction );\n  writer->SetInput( caster->GetOutput() );\n\n  try {\n    std::cout << \"Writing output to file: \" << fileOutputReconstruction << std::endl;\n    writer->Update();\n  }\n  catch( itk::ExceptionObject & err ) {\n    std::cerr << \"ERROR: Failed to write output to file: \" << fileOutputReconstruction << \"; \" << err << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  std::cout << \"Done\" << std::endl;\n  \n  \n  // Write out the affine and projection geometries to a set of files\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  if ( fileOutputGeometry.length() > 0 ) {\n\n    geometry->Print(std::cout);\n\n    ProjectionGeometryType::EulerAffineTransformPointerType pAffineTransform;\n    ProjectionGeometryType::PerspectiveProjectionTransformPointerType pPerspectiveTransform;\n\n    itk::TransformFactory< ProjectionGeometryType::PerspectiveProjectionTransformType >::RegisterTransform();\n    itk::TransformFactory< ProjectionGeometryType::EulerAffineTransformType >::RegisterTransform();\n\n    typedef itk::TransformFileWriter TransformFileWriterType;\n    TransformFileWriterType::Pointer transformFileWriter = TransformFileWriterType::New();\n\n    unsigned int iProjection;\n\n    for (iProjection=0; iProjection<geometry->GetNumberOfProjections(); iProjection++) {\n  \n\n      // Get and write the perspective transform\n\n      try {\n\tpPerspectiveTransform = geometry->GetPerspectiveTransform(iProjection);\n      }\n\n      catch( itk::ExceptionObject & err ) { \n\tstd::cerr << \"Failed: \" << err << std::endl; \n\treturn EXIT_FAILURE;\n      }                \n\n      sprintf(filename, \"%s_%02d.tPerspective\", fileOutputGeometry.c_str(), iProjection);\n\n      transformFileWriter->SetInput( pPerspectiveTransform );\n      transformFileWriter->SetFileName(filename);\n      transformFileWriter->Update();         \n\n      std::cout << \"Writing perspective transform: \" << filename << std::endl;\n\n      // Get and write the affine transform\n\n      try {\n\tpAffineTransform = geometry->GetAffineTransform(iProjection);\n\tpAffineTransform->SetFullAffine(); \n      }\n\n      catch( itk::ExceptionObject & err ) { \n\tstd::cerr << \"Failed: \" << err << std::endl; \n\treturn EXIT_FAILURE;\n      }                \n\n      sprintf(filename, \"%s_%02d.tAffine\", fileOutputGeometry.c_str(), iProjection);\n\n      transformFileWriter->SetInput( pAffineTransform );\n      transformFileWriter->SetFileName(filename);\n      transformFileWriter->Update();         \n    \n      std::cout << \"Writing affine transform: \" << filename << std::endl;\n    }\n  }\n\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e57615dbc3792aa47d14d15ddac150a3b2d56ad0", "size": 24875, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Applications/ImageReconstruction/niftkImageReconstruction.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "Applications/ImageReconstruction/niftkImageReconstruction.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Applications/ImageReconstruction/niftkImageReconstruction.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 32.4738903394, "max_line_length": 148, "alphanum_fraction": 0.6806432161, "num_tokens": 6433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.037892426222173245, "lm_q1q2_score": 0.018650202620229237}}
{"text": "/*\n * This file is part of the Geneva library collection.\n *\n * This code is based on a number of examples shipped with the\n * Boost.Spirit library, particularly \"calc6.cpp\" from Boost 1.54.\n * It is consequently covered by the Boost license v.1.0, as quoted below.\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 * The following license applies to the code IN THIS FILE:\n *\n * ***************************************************************************\n *\n * Boost Software License - Version 1.0 - August 17th, 2003\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 * NOTE THAT THE BOOST-LICENSE DOES NOT APPLY TO ANY OTHER FILES OF THE\n * GENEVA LIBRARY, UNLESS THIS IS EXPLICITLY STATED IN THE CORRESPONDING FILE!\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 headers go here\n#include <iostream>\n#include <string>\n#include <stack>\n#include <map>\n#include <cmath>\n#include <type_traits>\n\n// Boost headers go here\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi_operator.hpp>\n#include <boost/spirit/include/qi_char.hpp>\n#include <boost/spirit/include/qi_string.hpp>\n#include <boost/spirit/include/qi_numeric.hpp>\n#include <boost/spirit/include/qi_auxiliary.hpp>\n#include <boost/spirit/include/qi_nonterminal.hpp>\n#include <boost/spirit/include/qi_action.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_object.hpp>\n#include <boost/spirit/include/phoenix_bind.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/optional.hpp>\n#include <boost/xpressive/xpressive.hpp>\n#include <boost/variant.hpp>\n#include <boost/utility.hpp>\n#include <boost/variant/recursive_variant.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp> // Compare http://stackoverflow.com/questions/18158376/getting-boostspiritqi-to-use-stl-containers\n\n// Geneva headers go here\n#include \"common/GExceptions.hpp\"\n#include \"common/GLogger.hpp\"\n#include \"common/GErrorStreamer.hpp\"\n#include \"common/GCommonHelperFunctionsT.hpp\"\n#include \"common/GCommonMathHelperFunctions.hpp\"\n\nnamespace Gem {\nnamespace Common {\n\n/******************************************************************************/\n// Exceptions for some error conditions\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * An exception to be thrown in case of mathematical errors,\n * such as division by 0\n */\nclass math_logic_error : public gemfony_exception {\npublic:\n\t/** @brief The default constructor: Intentionally deleted */\n\tG_API_COMMON math_logic_error() = delete;\n\t/** @brief The standard constructor */\n\texplicit G_API_COMMON math_logic_error(std::string const&) noexcept;\n\n\t/**************************************************************************/\n\t// Defaulted functions, constructors and destructor; rule of five\n\n\tG_API_COMMON math_logic_error(math_logic_error const&) = default;\n\tG_API_COMMON math_logic_error(math_logic_error &&) noexcept = default;\n\tG_API_COMMON ~math_logic_error() noexcept override = default;\n\n\tG_API_COMMON math_logic_error& operator=(math_logic_error const&) = default;\n\tG_API_COMMON math_logic_error& operator=(math_logic_error &&) noexcept = default;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * An exception indicating a division by 0\n */\nclass division_by_0 : public math_logic_error {\npublic:\n\t/** @brief The default constructor */\n\tG_API_COMMON division_by_0() noexcept;\n\n\t/**************************************************************************/\n\t// Defaulted functions, constructors and destructor; rule of five\n\n\tG_API_COMMON division_by_0(division_by_0 const&) = default;\n\tG_API_COMMON division_by_0(division_by_0 &&) noexcept = default;\n\tG_API_COMMON ~division_by_0() noexcept override = default;\n\n\tG_API_COMMON division_by_0& operator=(division_by_0 const&) = default;\n\tG_API_COMMON division_by_0& operator=(division_by_0 &&) noexcept = default;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * An exception indicating a range outside [-1:1] in acos\n */\ntemplate<typename fp_type>\nclass acos_invalid_range : public math_logic_error {\npublic:\n\t/** @brief The default constructor: Intentionally deleted */\n\tacos_invalid_range() = delete;\n\n\t/** @brief The standard constructor */\n\texplicit acos_invalid_range(const fp_type &val) noexcept\n\t\t: math_logic_error(std::string(\"acos: Value \") + Gem::Common::to_string(val) +\n\t\t\t\t\t\t\t\t std::string(\" out of valid range [-1:1] in GFormulaParserT\"))\n\t{ /* nothing */ }\n\n\t/**************************************************************************/\n\t// Defaulted functions, constructors and destructor; rule of five\n\n\tG_API_COMMON acos_invalid_range(acos_invalid_range const&) = default;\n\tG_API_COMMON acos_invalid_range(acos_invalid_range &&) noexcept = default;\n\tG_API_COMMON ~acos_invalid_range() noexcept override = default;\n\n\tG_API_COMMON acos_invalid_range& operator=(acos_invalid_range const&) = default;\n\tG_API_COMMON acos_invalid_range& operator=(acos_invalid_range &&) noexcept = default;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * An exception indicating a range outside [-1:1] in acos\n */\ntemplate<typename fp_type>\nclass asin_invalid_range : public math_logic_error {\npublic:\n\t/** @brief The default constructor: Intentionally deleted */\n\tasin_invalid_range() = delete;\n\t/** @brief The standard constructor */\n\texplicit asin_invalid_range(const fp_type &val) noexcept\n\t\t: math_logic_error(std::string(\"asin: Value \") + Gem::Common::to_string(val) +\n\t\t\t\t\t\t\t\t std::string(\" out of valid range [-1:1] in GFormulaParserT\")) { /* nothing */ }\n\n\t/**************************************************************************/\n\t// Defaulted functions, constructors and destructor; rule of five\n\n\tG_API_COMMON asin_invalid_range(asin_invalid_range const&) = default;\n\tG_API_COMMON asin_invalid_range(asin_invalid_range &&) noexcept = default;\n\tG_API_COMMON ~asin_invalid_range() noexcept override = default;\n\n\tG_API_COMMON asin_invalid_range& operator=(asin_invalid_range const&) = default;\n\tG_API_COMMON asin_invalid_range& operator=(asin_invalid_range &&) noexcept = default;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * An exception indicating a value <= 0\n */\n\ntemplate<typename fp_type>\nclass log_negative_value : public math_logic_error {\npublic:\n\t/** @brief The default constructor: Intentionally deleted */\n\tlog_negative_value() = delete;\n\t/** @brief The standard constructor */\n\texplicit log_negative_value(const fp_type &val) noexcept\n\t\t: math_logic_error(std::string(\"log: Value \") + Gem::Common::to_string(val) +\n\t\t\t\t\t\t\t\t std::string(\" <= 0 in GFormulaParserT\"))\n\t{ /* nothing */ }\n\n\t/**************************************************************************/\n\t// Defaulted functions, constructors and destructor; rule of five\n\n\tG_API_COMMON log_negative_value(log_negative_value const&) = default;\n\tG_API_COMMON log_negative_value(log_negative_value &&) noexcept = default;\n\tG_API_COMMON ~log_negative_value() noexcept override = default;\n\n\tG_API_COMMON log_negative_value& operator=(log_negative_value const&) = default;\n\tG_API_COMMON log_negative_value& operator=(log_negative_value &&) noexcept = default;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * An exception indicating a value <= 0\n */\ntemplate<typename fp_type>\nclass log10_negative_value : public math_logic_error {\npublic:\n\t/** @brief The default constructor: Intentionally deleted */\n\tlog10_negative_value() = delete;\n\t/** @brief The standard constructor */\n\texplicit log10_negative_value(const fp_type &val) noexcept\n\t\t: math_logic_error(std::string(\"log10: Value \") + Gem::Common::to_string(val) +\n\t\t\t\t\t\t\t\t std::string(\" <= 0  in GFormulaParserT\"))\n\t{ /* nothing */ }\n\n\t/**************************************************************************/\n\t// Defaulted functions, constructors and destructor; rule of five\n\n\tG_API_COMMON log10_negative_value(log10_negative_value const&) = default;\n\tG_API_COMMON log10_negative_value(log10_negative_value &&) noexcept = default;\n\tG_API_COMMON ~log10_negative_value() noexcept override = default;\n\n\tG_API_COMMON log10_negative_value& operator=(log10_negative_value const&) = default;\n\tG_API_COMMON log10_negative_value& operator=(log10_negative_value &&) noexcept = default;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n/**\n * An exception indicating a value <= 0\n */\ntemplate<typename fp_type>\nclass sqrt_negative_value : public math_logic_error {\npublic:\n\t/** @brief The default constructor: Intentionally deleted */\n\tsqrt_negative_value() = delete;\n\t/** @brief The standard constructor */\n\texplicit sqrt_negative_value(const fp_type &val) noexcept\n\t\t: math_logic_error(std::string(\"sqrt: Value \") + Gem::Common::to_string(val) +\n\t\t\t\t\t\t\t\t std::string(\" < 0  in GFormulaParserT\")) { /* nothing */ }\n\n\t/**************************************************************************/\n\t// Defaulted functions, constructors and destructor; rule of five\n\n\tG_API_COMMON sqrt_negative_value(sqrt_negative_value const&) = default;\n\tG_API_COMMON sqrt_negative_value(sqrt_negative_value &&) noexcept = default;\n\tG_API_COMMON ~sqrt_negative_value() noexcept override = default;\n\n\tG_API_COMMON sqrt_negative_value& operator=(sqrt_negative_value const&) = default;\n\tG_API_COMMON sqrt_negative_value& operator=(sqrt_negative_value &&) noexcept = default;\n};\n\n/******************************************************************************/\n////////////////////////////////////////////////////////////////////////////////\n/******************************************************************************/\n// The Abstract Syntax Tree + access functions\n\n// Forward declarations\nstruct nil;\nstruct signed_;\nstruct unary_function_;\nstruct binary_function_;\nstruct ast_expression;\n\nusing operand =\nboost::variant<\n\tnil\n\t, float\n\t, double\n\t, boost::recursive_wrapper<signed_>\n\t, boost::recursive_wrapper<unary_function_>\n\t, boost::recursive_wrapper<binary_function_>\n\t, boost::recursive_wrapper<ast_expression>\n>;\n\nstruct nil {\n\tvoid swap(nil &);\n};\n\nstruct signed_ {\n\tchar sign;\n\toperand operand_;\n\n\tvoid swap(signed_ &);\n};\n\nstruct operation {\n\tchar operator_;\n\toperand operand_;\n\n\tvoid swap(operation &);\n};\n\nstruct unary_function_ {\n\tstd::string fname_;\n\toperand operand_;\n\n\tvoid swap(unary_function_ &);\n};\n\nstruct binary_function_ {\n\tstd::string fname_;\n\toperand operand1_;\n\toperand operand2_;\n\n\tvoid swap(binary_function_ &);\n};\n\nstruct ast_expression {\n\toperand first;\n\tstd::list<operation> rest;\n\n\tvoid swap(ast_expression &);\n};\n\n/** @brief print function for debugging */\ninline std::ostream &operator<<(std::ostream &out, nil) {\n\tout << \"nil\";\n\treturn out;\n}\n\n} /* namespace Common */\n} /* namespace Gem */\n\nBOOST_FUSION_ADAPT_STRUCT(\n\tGem::Common::signed_,\n\t(char, sign)\n\t\t(Gem::Common::operand, operand_)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n\tGem::Common::operation,\n\t(char, operator_)\n\t\t(Gem::Common::operand, operand_)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n\tGem::Common::unary_function_,\n\t(std::string, fname_)\n\t\t(Gem::Common::operand, operand_)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n\tGem::Common::binary_function_,\n\t(std::string, fname_)\n\t\t(Gem::Common::operand, operand1_)\n\t\t(Gem::Common::operand, operand2_)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n\tGem::Common::ast_expression,\n\t(Gem::Common::operand, first)\n\t\t(std::list<Gem::Common::operation>, rest)\n)\n\nnamespace Gem {\nnamespace Common {\n\n/******************************************************************************/\n/**\n * This class allows to parse and evaluate simple mathematical formulas of the\n * type \"(sin(3.)*sqrt(5.) - (2*pi))^2\". Formulas may optionally contain place\n * holders for variables, e.g. \"(sin({{var1}})*sqrt({{var2}}) - ({{var3}}*pi))^2\".\n * Formulas are provided in string form to the constructor. The evaluate()\n * function will then replace the place-holders with the corresponding entries of\n * a std::map<std::string, std::vector<fp_type>>. For simple variable names such\n * as \"var2\" only the first value of the std::vector is used -- a notation such as\n * \"var3{2]\" is also possible -- in this case the third value of the vector will be\n * used. An exception will be thrown, if the vector doesn't have enough entries.\n * An object of this class may deal with a single formula only, which is\n * given to it through the constructor. When a formula cannot be parsed,\n * an exception will be thrown. Likewise, exceptions derived from \"Gem::Common::math_logic_error\"\n * will be thrown for common mathematical errors, such as division by 0 or sqrt(-1).\n * Note that the class currently only handles floating point values (float and double).\n * The class is based on a number of examples taken from the Boost.Spirit code base,\n * particularly calc6.cpp from Boost version 1.54.\n */\n/*****************************************************************************/\n/**\n * The actual formula parser\n */\ntemplate<typename fp_type>\nclass GFormulaParserT\n\t: public boost::spirit::qi::grammar<std::string::const_iterator, ast_expression(), boost::spirit::ascii::space_type> {\n\t// Make sure, fp_type is a floating point value\n\tstatic_assert(std::is_floating_point<fp_type>::value, \"fp_type should ne a floating point type\");\n\npublic:\n\t/*****************************************************************************/\n\t/**\n\t * Specifies the operations the parser must know about\n\t */\n\tenum class byte_code : Gem::Common::ENUMBASETYPE {\n\t\top_trap = 0,      // triggers an exception --> boost::variant<int,fp_type>() == 0\n\t\top_neg = 1,      // negate the top stack entry\n\t\top_add = 2,      // add top two stack entries\n\t\top_sub = 3,      // subtract top two stack entries\n\t\top_mul = 4,      // multiply top two stack entries\n\t\top_div = 5,      // divide top two stack entries\n\t\top_acos = 7,      // Calculates the acos value of the top-most stack-entry\n\t\top_asin = 8,      // Calculates the asin value of the top-most stack-entry\n\t\top_atan = 9,      // Calculates the atan value of the top-most stack-entry\n\t\top_ceil = 10,     // Calculates the ceil value of the top-most stack-entry\n\t\top_cos = 11,     // Calculates the cos value of the top-most stack-entry\n\t\top_cosh = 12,     // Calculates the cosh value of the top-most stack-entry\n\t\top_exp = 13,     // Calculates the exp value of the top-most stack-entry\n\t\top_fabs = 14,     // Calculates the fabs value of the top-most stack-entry\n\t\top_floor = 15,     // Calculates the floor value of the top-most stack-entry\n\t\top_log = 16,     // Calculates the log value of the top-most stack-entry\n\t\top_log10 = 17,     // Calculates the log10 value of the top-most stack-entry\n\t\top_sin = 18,     // Calculates the sin value of the top-most stack-entry\n\t\top_sinh = 19,     // Calculates the sinh value of the top-most stack-entry\n\t\top_sqrt = 20,     // Calculates the sqrt value of the top-most stack-entry\n\t\top_tan = 21,     // Calculates the tan value of the top-most stack-entry\n\t\top_tanh = 22,     // Calculates the tanh value of the top-most stack-entry\n\t\top_pow = 23,     // Calculates the pow value of the two top-most stack-entries\n\t\top_hypot = 24,     // Calculates the hypot value of the two top-most stack-entries\n\t\top_min = 25,     // Calculates the min value of the two top-most stack-entries\n\t\top_max = 26,     // Calculates the max value of the two top-most stack-entries\n\t\top_fp = 27,     // Pushes a fp_type onto the stack\n\t};\n\n\tusing result_type = void; // Needed for the operator() and apply_visitor\n\tusing codeEntry = boost::variant<byte_code, fp_type>;\n\tusing parameter_map = std::map<std::string, std::vector<fp_type>>;\n\tusing constants_map = std::map<std::string, fp_type>;\n\n\t/***************************************************************************/\n\t/** @brief The default constructor -- intentionally deleted */\n\tGFormulaParserT() = delete;\n\n\t/***************************************************************************/\n\t/**\n\t * The standard constructor\n\t */\n\texplicit GFormulaParserT(\n\t\tconst std::string &formula\n\t\t, const constants_map &user_constants = constants_map()\n\t)\n\t\t: GFormulaParserT::base_type(expression_rule_)\n\t\t, raw_formula_(formula)\n\t\t, stack_(4096)\n\t\t, stack_ptr_(stack_.begin())\n\t\t, printCode_(false)\n\t{\n\t\tboost::spirit::qi::char_type char_;\n\t\tboost::spirit::qi::string_type string_;\n\n\t\tusing boost::spirit::qi::on_error;\n\t\tusing boost::spirit::qi::fail;\n\n\t\t//---------------------------------------------------------------------------\n\t\t// Define a number of mathematical constants\n\t\tconstants_.add\n\t\t\t(\"e\", boost::math::constants::e<fp_type>())\n\t\t\t(\"pi\", boost::math::constants::pi<fp_type>());\n\n\t\t// Add user-defined constants\n\t\ttypename constants_map::const_iterator cit;\n\t\tfor (cit = user_constants.begin(); cit != user_constants.end(); ++cit) {\n\t\t\tconstants_.add(cit->first, cit->second);\n\t\t}\n\n\t\t//---------------------------------------------------------------------------\n\t\t// Define the actual grammar\n\t\texpression_rule_ =\n\t\t\tterm_rule_ >> *((char_('+') > term_rule_) | (char_('-') > term_rule_));\n\n\t\tterm_rule_ =\n\t\t\tfactor_rule_ >> *((char_('*') > factor_rule_) | (char_('/') > factor_rule_));\n\n\t\tunary_function_rule_ =\n\t\t\t(string_(\"acos\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"asin\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"atan\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"ceil\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"cosh\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"cos\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"exp\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"fabs\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"floor\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"log10\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"log\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"sinh\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"sin\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"sqrt\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"tanh\") > '(' > expression_rule_ > ')')\n\t\t\t| (string_(\"tan\") > '(' > expression_rule_ > ')');\n\n\t\tbinary_function_rule_ =\n\t\t\t(string_(\"min\") > '(' > expression_rule_ > ',' > expression_rule_ > ')')\n\t\t\t| (string_(\"max\") > '(' > expression_rule_ > ',' > expression_rule_ > ')')\n\t\t\t| (string_(\"pow\") > '(' > expression_rule_ > ',' > expression_rule_ > ')')\n\t\t\t| (string_(\"hypot\") > '(' > expression_rule_ > ',' > expression_rule_ > ')');\n\n\t\tfactor_rule_ =\n\t\t\treal\n\t\t\t| ('(' > expression_rule_ > ')')\n\t\t\t| (char_('-') > factor_rule_)\n\t\t\t| (char_('+') > factor_rule_)\n\t\t\t| unary_function_rule_\n\t\t\t| binary_function_rule_\n\t\t\t| constants_;\n\n\t\t//---------------------------------------------------------------------------\n\t\t// Debugging and error handling and reporting support.\n\t\tBOOST_SPIRIT_DEBUG_NODES(\n\t\t\t(expression_rule_)\n\t\t\t\t(term_rule_)\n\t\t\t\t(unary_function_rule_)\n\t\t\t\t(binary_function_rule_)\n\t\t\t\t(factor_rule_)\n\t\t);\n\n\t\t// Error handling\n\t\t{\n\t\t\tnamespace qi = boost::spirit::qi;\n\t\t\tnamespace ascii = boost::spirit::ascii;\n\t\t\tnamespace phoenix = boost::phoenix;\n\n\t\t\tusing qi::eps;\n\t\t\tusing qi::lit;\n\t\t\tusing qi::_val;\n\t\t\tusing qi::_2;\n\t\t\tusing qi::_3;\n\t\t\tusing qi::_4;\n\t\t\tusing ascii::char_;\n\t\t\tusing qi::on_error;\n\t\t\tusing qi::fail;\n\t\t\tusing phoenix::construct;\n\t\t\tusing phoenix::val;\n\n\t\t\ton_error<fail>\n\t\t\t\t(\n\t\t\t\t\t// start\n\t\t\t\t\texpression_rule_, phoenix::ref(std::cout)\n\t\t\t\t\t\t\t\t\t\t\t<< \"Error! Was expecting \" << qi::_4\n\t\t\t\t\t\t\t\t\t\t\t<< \" here: '\" << phoenix::construct<std::string>(qi::_3, qi::_2) << \"'\\n\"\n\t\t\t\t);\n\t\t}\n\t}\n\n\t/***************************************************************************/\n\t// Deleted copy and assignment / rule of five\n\n\tGFormulaParserT(GFormulaParserT<fp_type> const&) = delete;\n\tGFormulaParserT(GFormulaParserT<fp_type> &&) = delete;\n\n\tGFormulaParserT<fp_type>& operator=(GFormulaParserT<fp_type> const&) = delete;\n\tGFormulaParserT<fp_type>& operator=(GFormulaParserT<fp_type> &&) = delete;\n\n\t/***************************************************************************/\n\t/**\n\t * When set to true, the code-vector will be printed prior to the evaluation\n\t */\n\tvoid setPrintCode(bool printCode) {\n\t\tprintCode_ = printCode;\n\t}\n\n\t/***************************************************************************/\n\t/**\n\t * Retrieves the processed formula (after replacement of place-holders)\n\t *\n\t * @param placeHolders A list of place-holders for variable values\n\t * @return A string containing the processed formula\n\t */\n\tstd::string getFormula(const parameter_map &vm) const {\n\t\treturn this->replacePlaceHolders(vm);\n\t}\n\n\t/***************************************************************************/\n\t/**\n\t * Evaluates a formula after replacing place holders with values\n\t */\n\tfp_type evaluate(const parameter_map &vm = parameter_map()) const {\n\t\t// Clear local data structures\n\t\tcode_.clear();\n\t\tstack_ptr_ = stack_.begin();\n\n\t\tast_expression ast; ///< The abstract syntax tree\n\n\t\t// Replace place holders with values taken from the map\n\t\tstd::string formula = this->replacePlaceHolders(vm);\n\n\t\t// Do the actual parsing of the formula\n\t\tstd::string::const_iterator iter = formula.begin();\n\t\tstd::string::const_iterator end = formula.end();\n\t\tboost::spirit::ascii::space_type space;\n\t\tbool r = boost::spirit::qi::phrase_parse(iter, end, *this, space, ast);\n\n\t\tif (r && iter == end) {\n\t\t\tthis->compile(ast);\n\t\t\tthis->execute();\n\t\t} else {\n\t\t\tstd::string rest(iter, end);\n\n\t\t\tthrow gemfony_exception(\n\t\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t\t<< \"In GFormulaParserT<>::evaluate(): Error!\" << std::endl\n\t\t\t\t\t<< \"Parsing of formula \" << formula << \" failed at \" << rest << std::endl\n\t\t\t);\n\t\t}\n\n\t\treturn stack_.at(0);\n\t}\n\n\t/*****************************************************************************/\n\t/**\n\t * Ease of access to the evaluate function\n\t */\n\tfp_type operator()(const parameter_map &vm = parameter_map()) const {\n\t\treturn this->evaluate(vm);\n\t}\n\n\t/*****************************************************************************/\n\t// Code for the compilation of the AST\n\tvoid operator()(nil) const { BOOST_ASSERT(0); }\n\n\tvoid operator()(const fp_type &fp_val) const {\n\t\tcode_.push_back(codeEntry(byte_code::op_fp));\n\t\tcode_.push_back(codeEntry(fp_val));\n\t}\n\n\tvoid operator()(const operation &x) const {\n\t\tboost::apply_visitor(*this, x.operand_);\n\n\t\tif (x.operator_ == '+') code_.push_back(codeEntry(byte_code::op_add));\n\t\telse if (x.operator_ == '-') code_.push_back(codeEntry(byte_code::op_sub));\n\t\telse if (x.operator_ == '*') code_.push_back(codeEntry(byte_code::op_mul));\n\t\telse if (x.operator_ == '/')\n\t\t\tcode_.push_back(codeEntry(byte_code::op_div));  // division by 0 throws Gem::Common::division_by_0 exception\n\t\telse\n\t\t\tBOOST_ASSERT(0);\n\t}\n\n\tvoid operator()(const unary_function_ &f) const {\n\t\tboost::apply_visitor(*this, f.operand_);\n\n\t\tif (f.fname_ == \"acos\")\n\t\t\tcode_.push_back(codeEntry(byte_code::op_acos)); // Value out of valid range [-1,1] throws Gem::Common::acos_invalid_range\n\t\telse if (f.fname_ == \"asin\")\n\t\t\tcode_.push_back(codeEntry(byte_code::op_asin)); // Value out of valid range [-1,1] throws Gem::Common::asin_invalid_range\n\t\telse if (f.fname_ == \"atan\") code_.push_back(codeEntry(byte_code::op_atan));\n\t\telse if (f.fname_ == \"ceil\") code_.push_back(codeEntry(byte_code::op_ceil));\n\t\telse if (f.fname_ == \"cos\") code_.push_back(codeEntry(byte_code::op_cos));\n\t\telse if (f.fname_ == \"cosh\") code_.push_back(codeEntry(byte_code::op_cosh));\n\t\telse if (f.fname_ == \"exp\") code_.push_back(codeEntry(byte_code::op_exp));\n\t\telse if (f.fname_ == \"fabs\") code_.push_back(codeEntry(byte_code::op_fabs));\n\t\telse if (f.fname_ == \"floor\") code_.push_back(codeEntry(byte_code::op_floor));\n\t\telse if (f.fname_ == \"log\")\n\t\t\tcode_.push_back(codeEntry(byte_code::op_log)); // Value <= 0 throws Gem::Common::log_negative_value\n\t\telse if (f.fname_ == \"log10\")\n\t\t\tcode_.push_back(codeEntry(byte_code::op_log10)); // Value <= 0 throws Gem::Common::log10_negative_value\n\t\telse if (f.fname_ == \"sin\") code_.push_back(codeEntry(byte_code::op_sin));\n\t\telse if (f.fname_ == \"sinh\") code_.push_back(codeEntry(byte_code::op_sinh));\n\t\telse if (f.fname_ == \"sqrt\")\n\t\t\tcode_.push_back(codeEntry(byte_code::op_sqrt)); // Value < 0 throws Gem::Common::sqrt_negative_value\n\t\telse if (f.fname_ == \"tan\") code_.push_back(codeEntry(byte_code::op_tan));\n\t\telse if (f.fname_ == \"tanh\") code_.push_back(codeEntry(byte_code::op_tanh));\n\t\telse\n\t\t\tBOOST_ASSERT(0);\n\t}\n\n\tvoid operator()(const binary_function_ &f) const {\n\t\tboost::apply_visitor(*this, f.operand1_);\n\t\tboost::apply_visitor(*this, f.operand2_);\n\n\t\tif (f.fname_ == \"min\") code_.push_back(codeEntry(byte_code::op_min));\n\t\telse if (f.fname_ == \"max\") code_.push_back(codeEntry(byte_code::op_max));\n\t\telse if (f.fname_ == \"pow\") code_.push_back(codeEntry(byte_code::op_pow));\n\t\telse if (f.fname_ == \"hypot\") code_.push_back(codeEntry(byte_code::op_hypot));\n\t\telse\n\t\t\tBOOST_ASSERT(0);\n\t}\n\n\tvoid operator()(const signed_ &x) const {\n\t\tboost::apply_visitor(*this, x.operand_);\n\t\tif (x.sign == '-') code_.push_back(codeEntry(byte_code::op_neg));\n\t\telse if (x.sign == '+') { /* nothing */ }\n\t\telse\n\t\t\tBOOST_ASSERT(0);\n\t}\n\n\tvoid operator()(const ast_expression &x) const {\n\t\tboost::apply_visitor(*this, x.first);\n\t\tfor(const auto& oper: x.rest) {\n\t\t\t(*this)(oper);\n\t\t}\n\t}\n\nprivate:\n\t/***************************************************************************/\n\t/**\n\t * Replaces place holders with corresponding parameter values\n\t *\n\t * @param vm A std::map of name-value pairs, holding place-holders to be replaced with values\n\t */\n\tstd::string replacePlaceHolders(const parameter_map &vm) const {\n\t\tstd::string formula = raw_formula_;\n\t\tstd::string key, value;\n\t\tboost::xpressive::sregex re;\n\n\t\ttypename parameter_map::const_iterator cit;\n\t\tfor (cit = vm.begin(); cit != vm.end(); ++cit) {\n\t\t\tkey = cit->first;\n\n\t\t\tif (1 == (cit->second).size()) { // Try just the key\n\t\t\t\tvalue = Gem::Common::to_string((cit->second).at(0));\n\t\t\t\tre = boost::xpressive::as_xpr(\"{{\" + key + \"}}\");\n\t\t\t\tformula = boost::xpressive::regex_replace(formula, re, value);\n\n\t\t\t} else if ((cit->second).size() > 1) { // Try key[0], key[1] --> you may use formulas with place holders sin({{x[2]}})\n\t\t\t\tstd::size_t cnt = 0;\n\t\t\t\ttypename std::vector<fp_type>::const_iterator v_cit;\n\t\t\t\tfor (v_cit = (cit->second).begin(); v_cit != (cit->second).end(); ++v_cit) {\n\t\t\t\t\tvalue = Gem::Common::to_string(*v_cit);\n\t\t\t\t\tre = boost::xpressive::as_xpr(\"{{\" + key + \"[\" + Gem::Common::to_string(cnt++) + \"]\" + \"}}\");\n\t\t\t\t\tformula = boost::xpressive::regex_replace(formula, re, value);\n\t\t\t\t}\n\t\t\t} else { // The vector is empty\n\t\t\t\tthrow gemfony_exception(\n\t\t\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t\t\t<< \"In GFormulaParserT::replacePlaceHolders(): Error!\" << std::endl\n\t\t\t\t\t\t<< \"Vector is empty!\" << std::endl\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn formula;\n\t}\n\n\t/***************************************************************************/\n\t/**\n\t * Compiles the AST into byte code\n\t */\n\tvoid compile(const ast_expression &x) const {\n\t\t(*this)(x);\n\t}\n\n\t/***************************************************************************/\n\t/**\n\t * The actual calculations\n\t */\n\tvoid execute() const {\n\t\t// Position pointers for stack and code\n\t\ttypename std::vector<codeEntry>::const_iterator code_ptr = code_.begin();\n\t\tstack_ptr_ = stack_.begin();\n\n\t\t// When requested by the user, print a copy of the code-vector\n\t\tif (printCode_) printCode();\n\n\t\twhile (code_ptr != code_.end()) {\n\t\t\t// Note: *code_ptr is a boost::variabt, boost::get has nothing to do with a boost::tuple here\n\t\t\tswitch (boost::get<byte_code>(*code_ptr++)) { // Read out code_ptr, then switch it to the next position\n\t\t\t\tcase byte_code::op_trap: {\n\t\t\t\t\tthrow gemfony_exception(\n\t\t\t\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t\t\t\t<< \"In GFormulaParserT<fp_type>::execute(): Error!\" << std::endl\n\t\t\t\t\t\t\t<< \"byte_code::op_trap encountered\" << std::endl\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_neg:\n\t\t\t\t\tstack_ptr_[-1] = -stack_ptr_[-1];\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_add:\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tstack_ptr_[-1] += stack_ptr_[0];\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_sub:\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tstack_ptr_[-1] -= stack_ptr_[0];\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_mul:\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tstack_ptr_[-1] *= stack_ptr_[0];\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_div: {\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tif (0 == stack_ptr_[0]) {\n\t\t\t\t\t\tthrow Gem::Common::division_by_0();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstack_ptr_[-1] /= stack_ptr_[0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_min:\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tstack_ptr_[-1] = Gem::Common::gmin(stack_ptr_[-1], stack_ptr_[0]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_max:\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tstack_ptr_[-1] = Gem::Common::gmax(stack_ptr_[-1], stack_ptr_[0]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_pow:\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tstack_ptr_[-1] = std::pow(stack_ptr_[-1], stack_ptr_[0]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_hypot:\n\t\t\t\t\t--stack_ptr_;\n\t\t\t\t\tstack_ptr_[-1] = hypot(stack_ptr_[-1], stack_ptr_[0]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_acos: {\n\t\t\t\t\tif (stack_ptr_[-1] < -1. || stack_ptr_[-1] > 1.) {\n\t\t\t\t\t\tthrow Gem::Common::acos_invalid_range<fp_type>(stack_ptr_[-1]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstack_ptr_[-1] = std::acos(stack_ptr_[-1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_asin: {\n\t\t\t\t\tif (stack_ptr_[-1] < -1. || stack_ptr_[-1] > 1.) {\n\t\t\t\t\t\tthrow Gem::Common::asin_invalid_range<fp_type>(stack_ptr_[-1]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstack_ptr_[-1] = std::asin(stack_ptr_[-1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_atan:\n\t\t\t\t\tstack_ptr_[-1] = std::atan(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_ceil:\n\t\t\t\t\tstack_ptr_[-1] = std::ceil(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_cos:\n\t\t\t\t\tstack_ptr_[-1] = std::cos(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_cosh:\n\t\t\t\t\tstack_ptr_[-1] = std::cosh(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_exp:\n\t\t\t\t\tstack_ptr_[-1] = std::exp(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_fabs:\n\t\t\t\t\tstack_ptr_[-1] = std::fabs(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_floor:\n\t\t\t\t\tstack_ptr_[-1] = std::floor(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_log: {\n\t\t\t\t\tif (stack_ptr_[-1] <= 0.) {\n\t\t\t\t\t\tthrow Gem::Common::log_negative_value<fp_type>(stack_ptr_[-1]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstack_ptr_[-1] = std::log(stack_ptr_[-1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_log10: {\n\t\t\t\t\tif (stack_ptr_[-1] <= 0.) {\n\t\t\t\t\t\tthrow Gem::Common::log10_negative_value<fp_type>(stack_ptr_[-1]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstack_ptr_[-1] = std::log10(stack_ptr_[-1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_sin:\n\t\t\t\t\tstack_ptr_[-1] = std::sin(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_sinh:\n\t\t\t\t\tstack_ptr_[-1] = std::sinh(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_sqrt: {\n\t\t\t\t\tif (stack_ptr_[-1] < 0.) {\n\t\t\t\t\t\tthrow Gem::Common::sqrt_negative_value<fp_type>(stack_ptr_[-1]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstack_ptr_[-1] = std::sqrt(stack_ptr_[-1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_tan:\n\t\t\t\t\tstack_ptr_[-1] = std::tan(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_tanh:\n\t\t\t\t\tstack_ptr_[-1] = std::tanh(stack_ptr_[-1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase byte_code::op_fp:\n\t\t\t\t\t*stack_ptr_++ = boost::get<fp_type>(*code_ptr++);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault: {\n\t\t\t\t\tthrow gemfony_exception(\n\t\t\t\t\t\tg_error_streamer(DO_LOG, time_and_place)\n\t\t\t\t\t\t\t<< \"In GFormulaParserT<fp_type>::execute(): Error!\" << std::endl\n\t\t\t\t\t\t\t<< \"Invalid instruction \" << static_cast<std::size_t>(boost::get<byte_code>(*code_ptr--)) << std::endl\n\t\t\t\t\t);\n\t\t\t\t\t// Note that the static cast is required here as strongly-typed enums cannot be\n\t\t\t\t\t// cast implicitly to integers types.\n\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/***************************************************************************/\n\t/**\n\t * Prints the stack until it encounters a 0 entry or the end of the list\n\t */\n\tvoid printStack() const {\n\t\tif (stack_.empty()) {\n\t\t\tstd::cout << \"Stack is empty!\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\ttypename std::vector<fp_type>::const_iterator it = stack_.begin();\n\t\tstd::cout << \"Stack: \";\n\t\twhile (it != stack_.end() && *it != 0.) {\n\t\t\tstd::cout << *it << \" \" << std::flush;\n\t\t\t++it;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\t/***************************************************************************/\n\t/**\n\t * Prints the code\n\t */\n\tvoid printCode() const {\n\t\tif (code_.empty()) {\n\t\t\tstd::cout << \"Code is empty!\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tstd::cout << \"Code: \";\n\t\tfor (auto it: code_) {\n\t\t\tstd::cout << static_cast<std::size_t>(boost::get<byte_code>(it)) << \" \" << std::flush;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\t/***************************************************************************/\n\t// Local data and empty functions\n\n\tstd::string raw_formula_; ///< Holds the formula with place holders\n\n\tboost::spirit::qi::rule<std::string::const_iterator, ast_expression(), boost::spirit::ascii::space_type> expression_rule_;\n\tboost::spirit::qi::rule<std::string::const_iterator, ast_expression(), boost::spirit::ascii::space_type> term_rule_;\n\tboost::spirit::qi::rule<std::string::const_iterator, unary_function_(), boost::spirit::ascii::space_type> unary_function_rule_;\n\tboost::spirit::qi::rule<std::string::const_iterator, binary_function_(), boost::spirit::ascii::space_type> binary_function_rule_;\n\tboost::spirit::qi::rule<std::string::const_iterator, operand(), boost::spirit::ascii::space_type> factor_rule_;\n\n\tboost::spirit::qi::real_parser<fp_type, boost::spirit::qi::real_policies<fp_type>> real;\n\n\tboost::spirit::qi::symbols<std::iterator_traits<std::string::const_iterator>::value_type, fp_type> constants_; ///< Holds mathematical- and user-defined constants\n\n\tmutable std::vector<fp_type> stack_; ///< Holds the data needed as input for each operation\n\tmutable std::vector<codeEntry> code_; ///< Holds the \"compiled\" code\n\n\tmutable typename std::vector<fp_type>::iterator stack_ptr_;\n\n\tbool printCode_; ///< When set, the code will be printed prior to the evaluation\n};\n\n/******************************************************************************/\n\n} /* namespace Common */\n} /* namespace Gem */\n\n// Needed for rules to work. Follows http://boost.2283326.n4.nabble.com/hold-multi-pass-backtracking-swap-compliant-ast-td4664679.html\nnamespace boost {\nnamespace spirit {\n\nG_API_COMMON void swap(Gem::Common::nil &, Gem::Common::nil &);\nG_API_COMMON void swap(Gem::Common::signed_ &, Gem::Common::signed_ &);\nG_API_COMMON void swap(Gem::Common::operation &, Gem::Common::operation &);\nG_API_COMMON void swap(Gem::Common::unary_function_ &, Gem::Common::unary_function_ &);\nG_API_COMMON void swap(Gem::Common::binary_function_ &, Gem::Common::binary_function_ &);\nG_API_COMMON void swap(Gem::Common::ast_expression &, Gem::Common::ast_expression &);\n\n} /* namespace spirit */\n} /* namespace boost */\n", "meta": {"hexsha": "4d3f69695df2948d03071fdd8e48b66cbe8dc0e0", "size": 37551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/GFormulaParserT.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/common/GFormulaParserT.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/common/GFormulaParserT.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": 36.5994152047, "max_line_length": 163, "alphanum_fraction": 0.6098106575, "num_tokens": 8888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.045352577167234585, "lm_q1q2_score": 0.018644937421140786}}
{"text": "/* RevKit: A Toolkit for Reversible Circuit Design (www.revkit.org)\n * Copyright (C) 2009-2011  The RevKit Developers <revkit@informatik.uni-bremen.de>\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 * @file truth_table.hpp\n *\n * @brief Class for truth table representation\n */\n\n#ifndef TRUTH_TABLE_HPP\n#define TRUTH_TABLE_HPP\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/permutation_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/optional.hpp>\n\n#include <core/circuit.hpp>\n\nnamespace revkit\n{\n\n  /** @cond */\n  template<typename T>\n  struct transform_cube;\n  /** @endcond */\n\n  /**\n   * @brief Represents a  truth table\n   *\n   * This class helps mapping input assignments\n   * to their corresponding output assignments.\n   *\n   * Assignments are thereby cubes (type truth_table<T>::cube_type)\n   * are vectors of values T, which type is given as\n   * template parameter to the class.\n   *\n   * For the tristate value 1, 0, and don't care the\n   * type \\ref binary_truth_table is predefined with\n   * T = boost::optional<bool>.\n   *\n   * You can use read_specification(binary_truth_table&, const std::string&, std::string*)\n   * for reading a RevLib specification file into a truth_table.\n   *\n   * @section sec_example_iterate_through_truth_table Example\n   * This example shows how to iterate through the values of a \\ref binary_truth_table, which is not that convenient on the first sight.\n   * This code works also for a generic \\ref truth_table.\n   * @code\n   * binary_truth_table tt = // obtained from somewhere\n   *\n   * for ( binary_truth_table::const_iterator it = tt.begin(); it != tt.end(); ++it )\n   * {\n   *   // iterate through input cube (bit by bit)\n   *   foreach ( const binary_truth_table::value_type& in_bit, it->first )\n   *   {\n   *     // do something with in_bit\n   *   }\n   *\n   *   // iterate through output cube (bit by bit)\n   *   foreach ( const binary_truth_table::value_type& out_bit, it->second )\n   *   {\n   *     // do something with out_bit\n   *   }\n   * }\n   * @endcode\n   *\n   * @author RevKit\n   * @since  1.0\n   */\n  template<typename T>\n  class truth_table\n  {\n  public:\n    /**\n     * @brief Typedef reference to the given template type\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    typedef T                                     value_type;\n\n    /**\n     * @brief Type representing a cube\n     *\n     * Implemented as a vector over the basic type T\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    typedef std::vector<T>                        cube_type;\n\n    /**\n     * @brief Represents a map from input to output cube\n     *\n     * Implemented as a tuple\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    typedef std::map<cube_type, cube_type> cube_vector;\n\n    /**\n     * @brief Constant Iterator of input cubes\n     *\n     * Default constant iterator is used.\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    typedef typename cube_type::const_iterator in_const_iterator;\n\n    /**\n     * @brief Constant Iterator of output cubes\n     *\n     * A permutation iterator from Boost.Iterators is used which makes use of the truth table's permutation.\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    typedef boost::permutation_iterator<typename cube_type::const_iterator, std::vector<unsigned>::const_iterator> out_const_iterator;\n\n    /**\n     * @brief Truth Table's constant iterator\n     *\n     * A transform iterator which transforms the cube_tuple objects to a pair of iterator pairs of each input and output cube.\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    typedef boost::transform_iterator<transform_cube<T>, typename cube_vector::const_iterator> const_iterator;\n\n    /**\n     * @brief Returns the number of inputs\n     *\n     * If the truth table contains no cube tuple,\n     * then 0 is returned, otherwise the length of the\n     * first input assignment is returned.\n     *\n     * @return Number of inputs\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    unsigned num_inputs() const\n    {\n      if ( _cubes.size() )\n      {\n        return _cubes.begin()->first.size();\n      }\n      else\n      {\n        return 0;\n      }\n    }\n\n    /**\n     * @brief Returns the number of outputs\n     *\n     * If the truth table contains no cube tuple,\n     * then 0 is returned, otherwise the length of the\n     * first output assignment is returned.\n     *\n     * @return Number of outputs\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    unsigned num_outputs() const\n    {\n      if ( _cubes.size() )\n      {\n        return _cubes.begin()->second.size();\n      }\n      else\n      {\n        return 0;\n      }\n    }\n\n    /**\n     * @brief Returns constant begin iterator of the cube list\n     *\n     * @return Constant begin iterator of the cube list\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    const_iterator begin() const\n    {\n      return boost::make_transform_iterator( _cubes.begin(), transform_cube<T>( _permutation ) );\n    }\n\n    /**\n     * @brief Returns constant end iterator of the cube list\n     *\n     * @return Constant end iterator of the cube list\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    const_iterator end() const\n    {\n      return boost::make_transform_iterator( _cubes.end(), transform_cube<T>( _permutation ) );\n    }\n\n    /**\n     * @brief Adds a new entry to the truth table\n     *\n     * With adding the first entry the dimension of inputs\n     * and outputs is set. When adding further entries\n     * it has to make sure that the dimensions fit, else\n     * an assertion is thrown and false is returned.\n     *\n     * @param input Input assignment\n     * @param output Output assignment\n     * @return Returns whether the assignment could be added or not\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    bool add_entry( const cube_type& input, const cube_type& output )\n    {\n      if ( _cubes.size() &&\n           ( input.size() != _cubes.begin()->first.size() ||\n             output.size() != _cubes.begin()->second.size() ) )\n      {\n        assert( false );\n        return false;\n      }\n\n      if ( !_cubes.size() )\n      {\n        /* first entry -> create permutation */\n        std::copy( boost::counting_iterator<unsigned>( 0 ),\n                   boost::counting_iterator<unsigned>( output.size() ),\n                   std::back_inserter( _permutation ) );\n\n        _constants.resize( input.size(), constant() );\n        _garbage.resize( output.size(), false );\n      }\n\n      _cubes.insert( std::make_pair( input, output ) );\n      return true;\n    }\n\n    /**\n     * @brief Clears the truth table\n     *\n     * Clears the truth table, as well as the current permutation and constant\n     * and garbage information.\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    void clear()\n    {\n      _cubes.clear();\n      _permutation.clear();\n      _constants.clear();\n      _garbage.clear();\n    }\n\n    /**\n     * @brief Returns current permutation\n     *\n     * The permutation is initializes when the first entry is added\n     * to the truth table and is initially the sequence from 0 to \\e n - 1,\n     * where \\e n is the size of the output cubes.\n     *\n     * @return Current permutation\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    const std::vector<unsigned>& permutation() const\n    {\n      return _permutation;\n    }\n\n    /**\n     * @brief Sets the permutation\n     *\n     * This method can set a specific permutation. This method should not be used\n     * in combination with permute which provides a dynamic change of the permutation.\n     *\n     * @param perm New permutation\n     * @return True, if successful. It can be unsuccessful, when the size of perm is not suitable.\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    bool set_permutation( const std::vector<unsigned>& perm )\n    {\n      if ( perm.size() == _permutation.size() )\n      {\n        std::copy( perm.begin(), perm.end(), _permutation.begin() );\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    }\n\n    /**\n     * @brief Permutes the current permutation\n     *\n     * This methods calls <tt>std::next_permutation</tt> on the current permutation.\n     * It returns false, when all permutations were considered.\n     *\n     * @return False, when all permutations were considered, true otherwise.\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    bool permute()\n    {\n      return std::next_permutation( _permutation.begin(), _permutation.end() );\n    }\n\n    /**\n     * @brief Sets the inputs of the specification\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @param ins Vector of input names\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    void set_inputs( const std::vector<std::string>& ins )\n    {\n      _inputs = ins;\n    }\n\n    /**\n     * @brief Returns the inputs of the specification\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @return Vector of input names\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    const std::vector<std::string>& inputs() const\n    {\n      return _inputs;\n    }\n\n    /**\n     * @brief Sets the outputs of the specification\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @param outs Vector of output names\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    void set_outputs( const std::vector<std::string>& outs )\n    {\n      _outputs = outs;\n    }\n\n    /**\n     * @brief Returns the outputs of the specification\n     *\n     * The outputs are permuted in respect to the current permutation.\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @return Vector of output names\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    std::vector<std::string> outputs() const\n    {\n      if ( _outputs.size() == _permutation.size() )\n      {\n        // permute outputs first\n        return std::vector<std::string>( boost::make_permutation_iterator( _outputs.begin(), _permutation.begin() ), boost::make_permutation_iterator( _outputs.begin(), _permutation.end() ) );\n      }\n      else\n      {\n        return _outputs;\n      }\n    }\n\n    /**\n     * @brief Sets the constant lines of the specification\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @param constants Vector of constant values\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    void set_constants( const std::vector<constant>& constants )\n    {\n      _constants = constants;\n      _constants.resize( num_inputs(), constant() );\n    }\n\n    /**\n     * @brief Returns the constant line information of the specification\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @return Vector of constant line information\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    const std::vector<constant>& constants() const\n    {\n      return _constants;\n    }\n\n    /**\n     * @brief Sets the garbage lines of the specification\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @param garbage Vector of garbage values\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    void set_garbage( const std::vector<bool>& garbage )\n    {\n      _garbage = garbage;\n      _garbage.resize( num_outputs(), false );\n    }\n\n    /**\n     * @brief Returns the garbage line information of the specification\n     *\n     * The garbage line information is permuted in respect to the current permutation.\n     *\n     * Use \\ref copy_metadata to assign specification meta-data to a circuit.\n     *\n     * @return Vector of garbage line information\n     *\n     * @author RevKit\n     * @since  1.0\n     */\n    std::vector<bool> garbage() const\n    {\n      if ( _garbage.size() == _permutation.size() )\n      {\n        // permute outputs first\n        return std::vector<bool>( boost::make_permutation_iterator( _garbage.begin(), _permutation.begin() ), boost::make_permutation_iterator( _garbage.begin(), _permutation.end() ) );\n      }\n      else\n      {\n        return _garbage;\n      }\n    }\n\n  private:\n    /** @cond */\n    cube_vector _cubes;\n    std::vector<unsigned> _permutation;\n    std::vector<std::string> _inputs;\n    std::vector<std::string> _outputs;\n    std::vector<constant> _constants;\n    std::vector<bool> _garbage;\n    /** @endcond */\n  };\n\n  /** @cond */\n  template<typename T>\n  struct transform_cube\n  {\n    explicit transform_cube( const std::vector<unsigned>& permutation ) : permutation( permutation ) {}\n\n    typedef std::pair<typename truth_table<T>::in_const_iterator, typename truth_table<T>::in_const_iterator> in_const_iterator_pair;\n    typedef std::pair<typename truth_table<T>::out_const_iterator, typename truth_table<T>::out_const_iterator> out_const_iterator_pair;\n    typedef std::pair<in_const_iterator_pair, out_const_iterator_pair> result_type;\n\n    result_type operator()( const typename truth_table<T>::cube_vector::value_type& ct ) const\n    {\n      return std::make_pair(\n               std::make_pair( ct.first.begin(), ct.first.end() ),\n               std::make_pair(\n                 boost::make_permutation_iterator( ct.second.begin(), permutation.begin() ),\n                 boost::make_permutation_iterator( ct.second.end(), permutation.end() )\n               )\n             );\n    }\n\n  private:\n    const std::vector<unsigned>& permutation;\n  };\n  /** @endcond */\n\n  /**\n   * @brief A predefined truth table for specifications using binary values as in specifications for reversible circuits\n   *\n   * As template type boost::optional<bool> is used, which\n   * represents 0, 1, and a don't care value.\n   *\n   * * <table border=\"0\">\n     *   <tr>\n     *     <td class=\"indexkey\">Description</th>\n     *     <td class=\"indexkey\">Char representation</th>\n     *     <td class=\"indexkey\">Typed value</th>\n     *   </tr>\n     *   <tr>\n     *     <td class=\"indexvalue\">No constant input line</td>\n     *     <td align=\"center\" class=\"indexvalue\">'-'</td>\n     *     <td class=\"indexvalue\">@code boost::optional<bool>() @endcode</td>\n     *   </tr>\n     *   <tr>\n     *     <td class=\"indexvalue\">Constant input line with value 0</td>\n     *     <td align=\"center\" class=\"indexvalue\">'0'</td>\n     *     <td class=\"indexvalue\">@code boost::optional<bool>( 0 ) @endcode</td>\n     *   </tr>\n     *   <tr>\n     *     <td class=\"indexvalue\">Constant input line with value 1</td>\n     *     <td align=\"center\" class=\"indexvalue\">'1'</td>\n     *     <td class=\"indexvalue\">@code boost::optional<bool>( 1 ) @endcode</td>\n     *   </tr>\n     * </table>\n   */\n  typedef truth_table<boost::optional<bool> > binary_truth_table;\n\n  /**\n   * @brief Outputs a truth table\n   *\n   * Prints the input and output cubes of a binary truth table\n   *\n   * @param os The output stream\n   * @param spec The truth table\n   * @return The output stream \\p os\n   *\n   * @author RevKit\n   * @since  1.0\n   */\n  std::ostream& operator<<( std::ostream& os, const binary_truth_table& spec );\n\n  /**\n   * @brief Converts a truth table cube to a number\n   *\n   * The first element in the cube (at index 0) is thereby the most significant bit.\n   *\n   * @param cube The cube to be converted\n   * @return The \\p cube in numerical representation\n   *\n   * @author RevKit\n   * @since  1.0\n   */\n  unsigned truth_table_cube_to_number( const binary_truth_table::cube_type& cube );\n\n  /**\n   * @brief Converts a number to a cube of a fixed bitwidth\n   *\n   * The first element in the cube (at index 0) is thereby the most significant bit.\n   *\n   * @param number Number to be converted as a cube\n   * @param bw Bit-width of the cube\n   * @return The number as cube\n   *\n   * @author RevKit\n   * @since  1.0\n   */\n  binary_truth_table::cube_type number_to_truth_table_cube( unsigned number, unsigned bw );\n\n}\n\n#endif /* TRUTH_TABLE_HPP */\n", "meta": {"hexsha": "42216ff3a0183d29d5e3d7afb3049a11a0e9c0a6", "size": 16709, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rkqc/src/core/truth_table.hpp", "max_stars_repo_name": "clairechingching/ScaffCC", "max_stars_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 158.0, "max_stars_repo_stars_event_min_datetime": "2016-07-21T10:45:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T00:56:20.000Z", "max_issues_repo_path": "rkqc/src/core/truth_table.hpp", "max_issues_repo_name": "clairechingching/ScaffCC", "max_issues_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2016-07-25T01:23:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T16:05:50.000Z", "max_forks_repo_path": "rkqc/src/core/truth_table.hpp", "max_forks_repo_name": "clairechingching/ScaffCC", "max_forks_repo_head_hexsha": "737ae90f85d9fe79819d66219747d27efa4fa5b9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2016-08-29T17:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T17:55:58.000Z", "avg_line_length": 28.1770657673, "max_line_length": 192, "alphanum_fraction": 0.6095517386, "num_tokens": 4153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.050330630460763956, "lm_q1q2_score": 0.018633677421919726}}
{"text": "/*!\n * \\file   swp_PAH_primary.cpp\n * \\author Markus Sander\n *\n * \\brief  Particle Model that stores the individual PAHs of a soot particle\n */\n/*\n  Author(s):      Markus Sander (ms785)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2008 Markus Sander.\n\n  File purpose:\n    Implementation of the PAHPrimary class declared in the\n    swp_PAH_primary.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#define _USE_MATH_DEFINES //!< First define.\n#include <math.h>         //!< Then include so that the pi constant (M_PI) can be used.\n\n#include \"swp_primary.h\"\n#include \"swp_PAH_primary.h\"\n#include \"swp_aggmodel_type.h\"\n#include \"swp_model_factory.h\"\n#include \"swp_particle_image.h\"\n#include \"swp_cell.h\"\n#include \"swp_kmc_pah_process.h\"\n#include \"swp_kmc_pah_structure.h\"\n#include \"swp_PAH.h\"\n#include \"swp_ensemble.h\"\n#include \"swp_particle_model.h\"\n\n#include <stdexcept>\n#include <cassert>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/bind.hpp>\n#include <boost/bind/placeholders.hpp>\n\n#include \"string_functions.h\"\n\nint uniquePAHCounter = 0;\n\nusing namespace Sweep;\nusing namespace Sweep::AggModels;\nusing namespace Sweep::KMC_ARS;\n\nusing namespace std;\nusing namespace Strings;\n\n//used for debugging, testing clone function for PAHStructure.\nstatic unsigned int ID=0; \nstatic bool m_clone=false;\n/*\ndouble PAHPrimary::pow(double a, double b) {\n    int tmp = (*(1 + (int *)&a));\n    int tmp2 = (int)(b * (tmp - 1072632447) + 1072632447);\n    double p = 0.0;\n    *(1 + (int * )&p) = tmp2;\n    return p;\n}\n*/\n\n// CONSTRUCTORS AND DESTRUCTORS.\nPAHPrimary::PAHPrimary() : Primary(),\n    m_numcarbon(0),\n    m_numH(0),\n\tm_numCH3(0),\n    m_numOfEdgeC(0),\n    m_numOfRings(0),\n\tm_numOfLoneRings5(0),\n\tm_numOfEmbeddedRings5(0),\n\tm_PAHmass(0),\n\tm_PAHCollDiameter(0),\n    m_numPAH(0),\n    m_numprimary(0),\n    m_primarydiam(0.0),\n\tm_primaryvol(0.0),\n    m_children_radius(0),\n    m_children_vol(0),\n\tm_children_surf(0),\n    m_leftparticle_vol_old(0),\n    m_rightparticle_vol_old(0),\n    m_rightparticle_numPAH(0),\n    m_leftparticle_numPAH(0),\n    m_children_roundingLevel(0),\n\tm_children_sintering(0.0),\n\tm_children_sumCap(0.0), //used to calculate geometric volume of a particle\n\tm_sum_cap(0.0), //used to calculate geometric volume of a particle\n\tm_sph_prim_vol(0.0), //used to calculate geometric volume of a particle\n    m_distance_centreToCentre(0.0),\n    m_Rg(0),\n    m_fdim(0),\n    m_sqrtLW(0),\n    m_LdivW(0),\n    m_avg_coalesc(0), //if primary coordinates are not tracked\n\tm_avg_sinter(0.0), //if primary coordinates are tracked\n    m_sint_time(0.0),\n\tm_sint_rate(0.0),\n    m_leftchild(NULL),\n    m_rightchild(NULL),\n    m_parent(NULL),\n    m_leftparticle(NULL),\n    m_rightparticle(NULL),\n\tm_free_surf(0.0),\n\tm_sum_necks(0.0),\n\tm_r(0.0),\n\tm_r2(0.0),\n\tm_r3(0.0)\n{\n\tm_cen_bsph[0] = 0.0;\n\tm_cen_bsph[1] = 0.0;\n\tm_cen_bsph[2] = 0.0;\n\n\tm_cen_mass[0] = 0.0;\n\tm_cen_mass[1] = 0.0;\n\tm_cen_mass[2] = 0.0;\n}\n\n/*!\n * @param[in]       time        Time at which particle is being created\n * @param[in]       model       Model which defines the meaning of the primary\n * @param[in]       k       \tType of PAH used as primary particle\n *\n */\nPAHPrimary::PAHPrimary(const double time, const Sweep::ParticleModel &model, int k)\n\t: Primary(time, model),\n\tm_numcarbon(0),\n\tm_numH(0),\n\tm_numCH3(0),\n\tm_numOfEdgeC(0),\n\tm_numOfRings(0),\n\tm_numOfLoneRings5(0),\n\tm_numOfEmbeddedRings5(0),\n\tm_PAHmass(0),\n\tm_PAHCollDiameter(0),\n\tm_numPAH(0),\n\tm_numprimary(0),\n\tm_primarydiam(0.0),\n\tm_primaryvol(0.0),\n\tm_children_radius(0),\n\tm_children_vol(0),\n\tm_children_surf(0),\n\tm_leftparticle_vol_old(0),\n\tm_rightparticle_vol_old(0),\n\tm_rightparticle_numPAH(0),\n\tm_leftparticle_numPAH(0),\n\tm_children_roundingLevel(0),\n\tm_children_sintering(0.0),\n\tm_children_sumCap(0.0),\n\tm_sum_cap(0.0),\n\tm_sph_prim_vol(0.0),\n\tm_distance_centreToCentre(0.0),\n\tm_Rg(0),\n\tm_fdim(0),\n\tm_sqrtLW(0),\n\tm_LdivW(0),\n\tm_avg_coalesc(0),\n\tm_avg_sinter(0.0),\n\tm_sint_time(0.0),\n\tm_sint_rate(0.0),\n\tm_leftchild(NULL),\n\tm_rightchild(NULL),\n\tm_parent(NULL),\n\tm_leftparticle(NULL),\n\tm_rightparticle(NULL),\n\tm_free_surf(0.0),\n\tm_sum_necks(0.0),\n\tm_r(0.0),\n\tm_r2(0.0),\n\tm_r3(0.0)\n{\n\tm_cen_bsph[0] = 0.0;\n\tm_cen_bsph[1] = 0.0;\n\tm_cen_bsph[2] = 0.0;\n\n\tm_cen_mass[0] = 0.0;\n\tm_cen_mass[1] = 0.0;\n\tm_cen_mass[2] = 0.0;\n\n\t// Other parts of the code check for a non-zero composition\n\tm_comp[0] = 1;\n\n\tAddPAH(time, model, k);\n\n\t//Update the other properties\n\tUpdateCache();\n}\n\n/*!\n * @param[in]       time        Time at which particle is being created\n * @param[in]       position    Position at which particle is being created\n * @param[in]       model       Model which defines the meaning of the primary\n *\n */\nPAHPrimary::PAHPrimary(const double time, const double position,\n\tconst Sweep::ParticleModel &model)\n\t: Primary(time, model),\n\tm_numcarbon(0),\n\tm_numH(0),\n\tm_numCH3(0),\n\tm_numOfEdgeC(0),\n\tm_numOfRings(0),\n\tm_numOfLoneRings5(0),\n\tm_numOfEmbeddedRings5(0),\n\tm_numOfLoneRings7(0),\n\tm_numOfEmbeddedRings7(0),\n\tm_PAHmass(0),\n\tm_PAHCollDiameter(0),\n\tm_numPAH(0),\n\tm_numprimary(0),\n\tm_primarydiam(0.0),\n\tm_primaryvol(0.0),\n\tm_children_radius(0),\n\tm_children_vol(0),\n\tm_children_surf(0),\n\tm_leftparticle_vol_old(0),\n\tm_rightparticle_vol_old(0),\n\tm_rightparticle_numPAH(0),\n\tm_leftparticle_numPAH(0),\n\tm_children_roundingLevel(0),\n\tm_children_sintering(0.0),\n\tm_children_sumCap(0.0),\n\tm_sum_cap(0.0), \n\tm_sph_prim_vol(0.0), \n\tm_distance_centreToCentre(0.0),\n\tm_Rg(0),\n\tm_fdim(0),\n\tm_sqrtLW(0),\n\tm_LdivW(0),\n\tm_avg_coalesc(0),\n\tm_avg_sinter(0.0),\n\tm_sint_time(0.0),\n\tm_sint_rate(0.0), \n\tm_leftchild(NULL),\n\tm_rightchild(NULL),\n\tm_parent(NULL),\n\tm_leftparticle(NULL),\n\tm_rightparticle(NULL),\n\tm_free_surf(0.0),\n\tm_sum_necks(0.0), \n\tm_r(0.0),\n\tm_r2(0.0),\n\tm_r3(0.0)\n{\n\tm_cen_bsph[0] = 0.0; \n\tm_cen_bsph[1] = 0.0; \n\tm_cen_bsph[2] = 0.0; \n\n\tm_cen_mass[0] = 0.0; \n\tm_cen_mass[1] = 0.0; \n\tm_cen_mass[2] = 0.0; \n\t// Other parts of the code check for a non-zero composition\n\tm_comp[0] = 1;\n\n\tAddPAH(time, model, 0);\n\t//This passes the first PAH in the inception list. Not tested. gl413\n\n\t//Update the other properties\n\tUpdateCache();\n}\n\n\n// Initialising constructor.\nPAHPrimary::PAHPrimary(double time, const Sweep::ParticleModel &model, bool noPAH)\n\t: Primary(time, model),\n\tm_numcarbon(0),\n\tm_numH(0),\n\tm_numCH3(0),\n\tm_numOfEdgeC(0),\n\tm_numOfRings(0),\n\tm_numOfLoneRings5(0),\n\tm_numOfEmbeddedRings5(0),\n\tm_numOfLoneRings7(0),\n\tm_numOfEmbeddedRings7(0),\n\tm_PAHmass(0),\n\tm_PAHCollDiameter(0),\n\tm_numPAH(0),\n\tm_numprimary(0),\n\tm_primarydiam(0.0),\n\tm_primaryvol(0.0),\n\tm_children_radius(0),\n\tm_children_vol(0),\n\tm_children_surf(0),\n\tm_leftparticle_vol_old(0),\n\tm_rightparticle_vol_old(0),\n\tm_rightparticle_numPAH(0),\n\tm_leftparticle_numPAH(0),\n\tm_children_roundingLevel(0),\n\tm_children_sintering(0.0),\n\tm_children_sumCap(0.0), \n\tm_sum_cap(0.0),\n\tm_sph_prim_vol(0.0),\n\tm_distance_centreToCentre(0.0),\n\tm_Rg(0),\n\tm_fdim(0),\n\tm_sqrtLW(0),\n\tm_LdivW(0),\n\tm_avg_coalesc(0),\n\tm_avg_sinter(0.0),\n\tm_sint_time(0.0),\n\tm_sint_rate(0.0), \n\tm_leftchild(NULL),\n\tm_rightchild(NULL),\n\tm_parent(NULL),\n\tm_leftparticle(NULL),\n\tm_rightparticle(NULL),\n\tm_free_surf(0.0), \n\tm_sum_necks(0.0), \n\tm_r(0.0), \n\tm_r2(0.0), \n\tm_r3(0.0)\n{\n\tm_cen_bsph[0] = 0.0; \n\tm_cen_bsph[1] = 0.0; \n\tm_cen_bsph[2] = 0.0; \n\n\tm_cen_mass[0] = 0.0; \n\tm_cen_mass[1] = 0.0; \n\tm_cen_mass[2] = 0.0; \n\n\tm_comp[0] = 1;\n}\n\n\n/*double PAHPrimary::Fdim() const\n{\n    return m_fdim;\n}*/\n\n\n/*!\n * Add a PAH to the primary particle\n *\n * @param[in]   time        create time of the PAH\n * @param[in]   model       Particle model containing molecule database\n * @param[in]   k        \tType of PAH used as primary particle\n*/\nvoid PAHPrimary::AddPAH(double time,const Sweep::ParticleModel &model, int k)\n{\n\tconst std::vector<ParticleModel::PostProcessStartingStr> Incepted_PAH_list = model.InceptedPAH();\n\tParticleModel::PostProcessStartingStr Primary_PAH = Incepted_PAH_list[k];\n\tboost::shared_ptr<PAH> new_PAH (new PAH(time, Primary_PAH));\n    //boost::shared_ptr<PAH> new_PAH (new PAH(time, model.InceptedPAH()));\n    new_PAH->PAH_ID=ID;\n    m_PAH.push_back(new_PAH);\n    ID++;\n    // Set the particle mass, diameter etc\n    UpdatePrimary();\n}\n\n// Copy constructor.\nPAHPrimary::PAHPrimary(const PAHPrimary &copy)\n{\n    *this = copy;\n    if (copy.m_leftchild!=NULL)\n    {\n        CopyTree(&copy);\n    }\n\t//m_clone=false;\n}\n\n\n// Default destructor.\nPAHPrimary::~PAHPrimary()\n{\n    delete m_leftchild;\n    delete m_rightchild;\n    // it is not necessary to delete m_leftparticle because\n    // this is also m_leftchild somewhere down the tree\n    if (m_PAH.size()!=0) m_PAH.clear();\n    // delete the PAH list\n    releaseMem();\n    m_clone=false;\n}\n\n\n// Copy constructor.\nstd::vector<boost::shared_ptr<PAH> > PAHPrimary::GetPAHVector() const\n{\n\treturn m_PAH;\n}\n\n/*!\n * Recursively copy the tree for non-leaf nodes.\n *\n * @param[in] source Pointer to the primary to be copied\n*/\nvoid PAHPrimary::CopyTree( const PAHPrimary *source)\n{\n    //create the new left and right children with nothing in them\n    m_leftchild = new PAHPrimary(source->CreateTime(),*m_pmodel,false);\n    m_rightchild = new PAHPrimary(source->CreateTime(),*m_pmodel,false);\n\n    // copy the properties such as the volume, surface area and list of\n\t// constituent PAH molecules\n\tm_leftchild->CopyParts(source->m_leftchild);\n\tm_rightchild->CopyParts(source->m_rightchild);\n\n    //set the pointers to the parent\n\tm_leftchild->m_parent=this;\n\tm_rightchild->m_parent=this;\n\n    // the left and right particle are set further down in UpdateAllPointers\n\t// These are the pointers that specify which primary particles touch each\n\t// other in the aggregat structure.\n\tm_leftparticle=NULL;\n\tm_rightparticle=NULL;\n\n    //recurse to copy the subtrees\n\tif (source->m_leftchild->m_leftchild!=NULL)\n        m_leftchild->CopyTree(source->m_leftchild);\n\n\tif (source->m_rightchild->m_leftchild!=NULL)\n        m_rightchild->CopyTree(source->m_rightchild);\n\n    //set the leftparticle and rightparticle\n\tUpdateAllPointers(source);\n}\n\nPAHPrimary &PAHPrimary::operator=(const Primary &rhs)\n{\n    if (this != &rhs) {\n        const AggModels::PAHPrimary *pahprimary = NULL;\n        pahprimary = dynamic_cast<const AggModels::PAHPrimary*>(&rhs);\n        UpdateAllPointers(pahprimary);\n    }\n    return *this;\n}\n\n/*\n * @brief Stream-reading constructor\n *\n * @param[in,out]\t in\t\t       Input binary stream  \n * @param[in]        model\t       Particle model defining interpretation of particle data\n * @param[in,out]    duplicates    Addresses of PAHs for use when reading primary particles\n */ \nPAHPrimary::PAHPrimary(std::istream &in, const Sweep::ParticleModel &model, PahDeserialisationMap &pah_duplicates)\n{\n    Deserialize(in, model, pah_duplicates);\n}\n\n\n/*!\n * This function is like a limited assignment operator, except that the\n * children are not copied and the pointers to the particles may need\n * adjusting after this method has finished.\n *\n * @param[in] source Pointer to the primary to be copied\n */\nvoid PAHPrimary::CopyParts(const PAHPrimary *source)\n{\n    SetCollDiameter(source->CollDiameter());\n    SetMobDiameter(source->MobDiameter());\n    SetSphDiameter(source->SphDiameter());\n\n\tSetSurfaceArea(source->SurfaceArea());\n\tSetMass(source->Mass());\n\n\tm_values = source->m_values;\n\tm_comp = source->m_comp;\n\tm_time = source->m_time;\n\n\tm_sint_time = source->m_sint_time;\n\tm_sint_rate = source->m_sint_rate;\n\tm_numcarbon = source->m_numcarbon;\n\tm_numH = source->m_numH;\n\tm_numCH3 = source->m_numCH3;\n\tm_numOfEdgeC = source->m_numOfEdgeC;\n\tm_numOfRings = source->m_numOfRings;\n\tm_numOfLoneRings5 = source->m_numOfLoneRings5;\n\tm_numOfEmbeddedRings5 = source->m_numOfEmbeddedRings5;\n\tm_numOfLoneRings7 = source->m_numOfLoneRings7;\n\tm_numOfEmbeddedRings7 = source->m_numOfEmbeddedRings7;\n\tm_numPAH = source->m_numPAH;\n\tm_numprimary = source->m_numprimary;\n\tm_primarydiam = source->m_primarydiam;\n\tm_primaryvol = source->m_primaryvol;\n    m_PAHCollDiameter=source->m_PAHCollDiameter;\n    m_PAHmass=source->m_PAHmass;\n    \n    m_surf=source->m_surf;\n    m_vol=source->m_vol;\n\tm_free_surf = source->m_free_surf;\n    m_distance_centreToCentre = source->m_distance_centreToCentre;\n\t\n\tm_cen_bsph = source->m_cen_bsph;\n\tm_cen_mass = source->m_cen_mass;\n\tm_r = source->m_r;\n\tm_r2 = source->m_r2;\n\tm_r3 = source->m_r3;\n    m_children_vol=source->m_children_vol;\n    m_children_radius=source->m_children_radius;\n\tm_children_surf = source->m_children_surf;\n\tm_children_sintering = source->m_children_sintering;\n\tm_children_roundingLevel = source->m_children_roundingLevel;\n\tm_children_sumCap = source->m_children_sumCap;\n\tm_sum_cap = source->m_sum_cap;\n\tm_sph_prim_vol = source->m_sph_prim_vol;\n\tm_sum_necks = source->m_sum_necks;\n\n    m_rightparticle_numPAH=source->m_rightparticle_numPAH;\n    m_leftparticle_numPAH=source->m_leftparticle_numPAH;\n    m_leftparticle_vol_old=source->m_leftparticle_vol_old;\n    m_rightparticle_vol_old=source->m_rightparticle_vol_old;\n\n    m_fdim=source->m_fdim;\n    m_Rg=source->m_Rg;\n\tm_sqrtLW = source->m_sqrtLW;\n\tm_LdivW = source->m_LdivW;\n\tm_pmodel = source->m_pmodel;\n    m_avg_coalesc=source->m_avg_coalesc;\n\tm_avg_sinter = source->m_avg_sinter;\n\n\t//! Set particles.\n\tm_parent = source->m_parent;\n\tm_leftchild = source->m_leftchild;\n\tm_rightchild = source->m_rightchild;\n\tm_leftparticle = source->m_leftparticle; \n\tm_rightparticle = source->m_rightparticle;\n\n    //! Replace the PAHs with those from the source.\n    if (m_clone==true) {\n\t    m_PAH.resize(source->m_PAH.size());\n        m_PAH.clear();\n        const int sharedPointers = m_pmodel->Components(0)->SharedPointers();\n        for (size_t i=0; i!=source->m_PAH.size();++i) {\n\t\t    //! Each time a PAH is cloned 100000 is added to its ID so that we can easily calculate how many times this pah has been cloned.\n            if(sharedPointers) {\n                //! Create a copy of the shared pointers for PAHs in particles.\n\t\t        if (source->m_PAH.size() > 1) {\n                    boost::shared_ptr<PAH> new_m_PAH = source->m_PAH[i];\n                    new_m_PAH->PAH_ID=source->m_PAH[i]->PAH_ID+100000;\n                    m_PAH.push_back(new_m_PAH);\n                }\n                //! Always create new shared pointers for single PAHs.\n                else {\n                    boost::shared_ptr<PAH> new_m_PAH (source->m_PAH[i]->Clone());\n                    new_m_PAH->PAH_ID=source->m_PAH[i]->PAH_ID+100000;\n                    m_PAH.push_back(new_m_PAH);\n                }\n            }\n            else {\n                //! Create new shared pointers for single PAHs or PAHs in particles.\n                boost::shared_ptr<PAH> new_m_PAH (source->m_PAH[i]->Clone());\n                //m_PAH[i]=source->m_PAH[i]->Clone();\n                // Commented out to keep different PAH_ID numbers.\n\t\t\t\t//new_m_PAH->PAH_ID=source->m_PAH[i]->PAH_ID+100000;\n\t\t\t\t\n\t\t\t\t/*if (source->m_PAH[i]->PAH_ID != 0){\n\t\t\t\t\tnew_m_PAH->PAH_ID=source->m_PAH[i]->PAH_ID; //This keeps the same PAH_ID numbers after reading a file.\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tnew_m_PAH->PAH_ID=ID; //Added to keep different PAH_ID numbers.\n\t\t\t\t}*/\n\t\t\t\tnew_m_PAH->PAH_ID=ID; //Added to keep different PAH_ID numbers.\n\t\t\t\tID++; //Added to keep different PAH_ID numbers.\n                m_PAH.push_back(new_m_PAH);\n            }\n        }\n    }\n\telse {\n\t\tm_PAH.assign(source->m_PAH.begin(), source->m_PAH.end());\n\t}\n}\n\t\n\n/*!\n * Select a primary uniformly at random from this particle\n * and descend the aggregate tree to find the primary.\n * Note that most PAHPrimarys are nodes in a tree representing\n * connectivity within an aggregate, so it is necessary to\n * descend the tree to find a primary that really is a\n * primary.\n *\n * @param[in,out]   rng     Random number generator\n *\n * @return      Pointer to an object representing a phsyical primary\n */\nPAHPrimary *PAHPrimary::SelectRandomSubparticle(rng_type &rng)\n{\n    // We want to choose an integer uniformly on the range [0, m_numprimary - 1]\n    typedef boost::uniform_smallint<int> uniform_integer;\n    uniform_integer uniformDistrib(0, m_numprimary - 1);\n\n    // Now build an object that can generate a sample and use it\n    boost::variate_generator<rng_type&, uniform_integer> uniformGenerator(rng, uniformDistrib);\n    return SelectRandomSubparticleLoop(uniformGenerator());\n\n}\n/*!\n * @param[in] target The primary to be selected\n *\n * @return      Pointer to the next node down the tree on the path to target primary\n*/\nPAHPrimary *PAHPrimary::SelectRandomSubparticleLoop(int target)\n{\n\tif (m_leftchild==NULL) return this;\n\tif (target < m_leftchild->m_numprimary)\n\t{\n\t\treturn m_leftchild->SelectRandomSubparticleLoop(target);\n\t}\n\telse\n\t{\n\t\treturn m_rightchild->SelectRandomSubparticleLoop(target-(m_leftchild->m_numprimary));\n\t}\n}\n\n\n/*!\n * Each node contains two pointers (m_leftparticle and m_rightparticle)\n * to primary particles that are connected by this node\n * This function is used when the entire particle tree is duplicated.\n * It sets the pointers in the copied node (this), that the connectivity\n * of the primary particles in this node is the same as in the original node.\n *\n * A large number of asserts are provided to check that the pointer network\n * describing the aggregate structure is valid.  This can be re-enabled if\n * there is suspicion of a bug,\n *\n *\n *@todo give this method a more accurate name\n *\n * @param[in] original    Pointer to the primary to be copied\n*/\nvoid PAHPrimary::UpdateAllPointers( const PAHPrimary *original)\n{\n    //the primary has no children => there are no left and right particles\n    if (original->m_leftchild == NULL) {\n        // Check that both children are missing in the original and the copy\n        //assert(original->m_rightchild == NULL);\n        //assert(m_leftchild == NULL);\n        //assert(m_rightchild == NULL);\n\n        // Check the original really does not have left and right particles\n        // since it should be representing a physical primary, not a connection\n        // inside an aggregate unit.\n        //assert(original->m_leftparticle == NULL);\n        //assert(original->m_rightparticle == NULL);\n\n        // Since this is not a connecting node it does not have left and\n        // right particles.\n\t\tm_leftparticle=NULL;\n\t\tm_rightparticle=NULL;\n    } else {\n//        assert(original->m_rightchild != NULL);\n//        assert(m_leftchild != NULL);\n//        assert(m_rightchild != NULL);\n\n        // Check the original really does have left and right particles\n        // since it should be representing a connection\n        // inside an aggregate unit.\n//        assert(original->m_leftparticle != NULL);\n//        assert(original->m_rightparticle != NULL);\n\n        // m_leftparticle should be a leaf node so assert that it does not have children\n//        assert(original->m_leftparticle->m_leftchild == NULL);\n//        assert(original->m_leftparticle->m_rightchild == NULL);\n\n        // Find the route to m_leftparticle in the original tree\n        std::stack<bool> route = recordPath(original->m_leftparticle, original);\n\n        // Now follow the same route down the new tree to find the new left particle\n        m_leftparticle = descendPath(this, route);\n\n        // the new m_leftparticle should be a leaf node so assert\n        // that it does not have children\n//        assert(m_leftparticle->m_leftchild == NULL);\n//        assert(m_leftparticle->m_rightchild == NULL);\n\n        // m_rightparticle should be a leaf node so assert that it does not have children\n//        assert(original->m_rightparticle->m_leftchild == NULL);\n//        assert(original->m_rightparticle->m_rightchild == NULL);\n\n        // Find the route to m_rightparticle in the original tree\n        route = recordPath(original->m_rightparticle, original);\n\n        // Now follow the same route down the new tree to find the new right particle\n        m_rightparticle = descendPath(this, route);\n\n        // the new m_rightparticle should be a leaf node so assert\n        // that it does not have children\n//        assert(m_rightparticle->m_leftchild == NULL);\n//        assert(m_rightparticle->m_rightchild == NULL);\n\t}\n}\n//void PAHPrimary::ReleasePAH(Primary &rhs)\n//{\n//    PAHPrimary *rhsparticle = NULL;\n//    rhsparticle = dynamic_cast<AggModels::PAHPrimary*>(&rhs);\n//    rhsparticle->m_PAH.clear();\n//}\n\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nPAHPrimary &PAHPrimary::Coagulate(const Primary &rhs, rng_type &rng)\n{\n\tvector<PAH>::const_iterator j;\n\tconst PAHPrimary *rhsparticle = NULL;\n\trhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(&rhs);\n\tdouble vol_old = 0.0;\n\t////only one PAH in rhs or this particle -> condensation or inception process.\n\tif ((rhsparticle->m_numPAH == 1) || (m_numPAH == 1))\n\t{\n\t\tif (rhsparticle->Numprimary() > 1)\n\t\t{\n\t\t\t//rhsparticle is a soot particle but this paricle repesents a PAH\n\t\t\t//this paricle will condense on this rhsparticle\n\t\t\t//Get a copy of the rhs ready to add to the current particle\n\t\t\tPAHPrimary copy_rhs(*rhsparticle);\n\t\t\tPAHPrimary *target = copy_rhs.SelectRandomSubparticle(rng);\n\t\t\tvol_old = target->m_vol; //volume before condensation\n\t\t\ttarget->m_PAH.insert(target->m_PAH.end(), m_PAH.begin(), m_PAH.end());\n\t\t\ttarget->UpdatePrimary();\n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\t\t\ttarget -> Adjust(vol_old); //treat condensation similar to surface growth\n\n\t\t\tCopyParts(&copy_rhs);\n\t\t\tCopyTree(&copy_rhs);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//this paricle is a soot particle but rhsparticle repesents a PAH\n\t\t\t//rhsparticle will condense on this particle\n\t\t\t//particle has more then one primary select the primary where\n\t\t\t//the PAH condenses to and add it to the list\n\t\t\tif (m_leftchild != NULL)\n\t\t\t{\n\t\t\t\tPAHPrimary *target = SelectRandomSubparticle(rng);\n\t\t\t\tvol_old = target->m_vol; //volume before condensation\n\t\t\t\ttarget->m_PAH.insert(target->m_PAH.end(), rhsparticle->m_PAH.begin(), rhsparticle->m_PAH.end());\n\t\t\t\ttarget->UpdatePrimary();\n\t\t\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\t\t\t\ttarget->Adjust(vol_old); //treat condensation similar to surface growth\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//! rhsparticle is a gas-phase PAH but the this pointer may be\n\t\t\t\t//! pointing to a gas-phase PAH in which case this would be an\n\t\t\t\t//! inception event, or a single primary particle in which case\n\t\t\t\t//! it would be a condensation event.\n\t\t\t\tvol_old = m_vol; //volume before condensation\n\t\t\t\tm_PAH.insert(m_PAH.end(), rhsparticle->m_PAH.begin(), rhsparticle->m_PAH.end());\n\t\t\t\tUpdatePrimary();\n\t\t\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\t\t\t\tAdjust(vol_old); //treat condensation similar to surface growth\n\t\t\t}\n\t\t}\n\t\tUpdateCache();\n\n\t\t//Check the coalescence ratio\n\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\t\tCheckSintering();\n\t\telse\n\t\t\tCheckRounding();\n\n\t}\n\n\telse\n\t{ //comment inception and condensation to test PAH_KMC model and bintree model\n\t\t//coagulation process\n\t\t//PAHPrimary *newleft = new PAHPrimary(m_time, *m_pmodel);\n\t\t//PAHPrimary *newright = new PAHPrimary(m_time, *m_pmodel);\n\t\tPAHPrimary *newleft = new PAHPrimary;\n\t\tPAHPrimary *newright = new PAHPrimary;\n\t\tPAHPrimary copy_rhs(*rhsparticle);\n\t\t//rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(&rhs);\n\n\t\t// bool print=false;\n\t\t// if (this->m_numprimary>2 && notconstpah->m_numprimary>2)\n\t\t// {\n\t\t//    PrintTree(\"before1\");\n\t\t//     notconstpah->PrintTree(\"before2\");\n\t\t//   print=true;\n\t\t//  cout << \"printing tree\"<<endl;\n\t\t//}\n\n\t\t//select where to add the second particle\n\t\tboost::bernoulli_distribution<> bernoulliDistrib;\n\t\tboost::variate_generator<rng_type &, boost::bernoulli_distribution<> > leftRightChooser(rng, bernoulliDistrib);\n\t\tif (leftRightChooser())\n\t\t{\n\t\t\tnewleft->CopyParts(this);\n\t\t\tnewright->CopyParts(&copy_rhs);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnewright->CopyParts(this);\n\t\t\tnewleft->CopyParts(&copy_rhs);\n\t\t}\n\t\t//set the pointers\n\t\tm_leftchild = newleft;\n\t\tm_rightchild = newright;\n\t\tnewright->m_parent = this;\n\t\tnewleft->m_parent = this;\n\n\t\tthis->m_leftparticle = NULL;//leftparticle has not been determined yet\n\t\tthis->m_rightparticle = NULL;//rightparticle has not been determined yet\n\n\t\t//set the pointers to the parent node\n\t\tif (newleft->m_leftchild != NULL)\n\t\t{\n\t\t\tnewleft->m_leftchild->m_parent = newleft;\n\t\t\tnewleft->m_rightchild->m_parent = newleft;\n\t\t}\n\t\tif (newright->m_leftchild != NULL)\n\t\t{\n\t\t\tnewright->m_leftchild->m_parent = newright;\n\t\t\tnewright->m_rightchild->m_parent = newright;\n\t\t}\n\n\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\t\tm_children_sintering = 0; //track coordinates\n\t\telse\n\t\t\tm_children_roundingLevel = 0; //no track\n\n\t\tUpdateCache();\n\n\t\t//! It is assumed that primary pi from particle Pq and primary pj from\n\t\t//! particle Pq are in point contact and by default pi and pj are\n\t\t//! uniformly selected. If we track the coordinates of the primaries in\n\t\t//! a particle, we can do a smarter selection where pi and pj are\n\t\t//! determined by ballistic cluster-cluster aggregation (BCCA):\n\t\t//! R. Jullien, Transparency effects in cluster-cluster aggregation with\n\t\t//! linear trajectories, J. Phys. A 17 (1984) L771-L776.\n\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation()) {\n\t\t\tboost::uniform_01<rng_type&, double> uniformGenerator(rng);\n\n\t\t\t//! Implementation of Arvo's algorithm, Fast Random Rotation Matrices,\n\t\t\t//! Chapter III.4 in Graphic Gems III edited by David Kirk to generate\n\t\t\t//! a transformation matrix for randomly rotating a particle.\n\t\t\tdouble theta1 = 2 * PI * uniformGenerator(); //!< Pick a rotation about the pole.\n\t\t\tdouble phi1 = 2 * PI * uniformGenerator();   //!< Pick a direction to deflect the pole.\n\t\t\tdouble z1 = uniformGenerator();              //!< Pick the amount of pole deflection.\n\n\t\t\t//! Construct a vector for performing the reflection.\n\t\t\tfvector V1;\n\t\t\tV1.push_back(cos(phi1) * sqrt(z1));\n\t\t\tV1.push_back(sin(phi1) * sqrt(z1));\n\t\t\tV1.push_back(sqrt(1 - z1));\n\n\t\t\t//! Rotate centre-of-mass.\n\t\t\tm_leftchild->rotateCOM(theta1, V1);\n\n\t\t\t//! Implementation of Arvo's algorithm, Fast Random Rotation Matrices,\n\t\t\t//! Chapter III.4 in Graphic Gems III edited by David Kirk to generate\n\t\t\t//! a transformation matrix for randomly rotating a particle.\n\t\t\tdouble theta2 = 2 * PI * uniformGenerator(); //!< Pick a rotation about the pole.\n\t\t\tdouble phi2 = 2 * PI * uniformGenerator();   //!< Pick a direction to deflect the pole.\n\t\t\tdouble z2 = uniformGenerator();              //!< Pick the amount of pole deflection.\n\n\t\t\t//! Construct a vector for performing the reflection.\n\t\t\tfvector V2;\n\t\t\tV2.push_back(cos(phi2) * sqrt(z2));\n\t\t\tV2.push_back(sin(phi2) * sqrt(z2));\n\t\t\tV2.push_back(sqrt(1 - z2));\n\n\t\t\t//! Rotate centre-of-mass.\n\t\t\tm_rightchild->rotateCOM(theta2, V2);\n\n\t\t\tm_leftchild->centreBoundSph();\n\t\t\tm_rightchild->centreBoundSph();\n\n\t\t\tbool Overlap = false;\n\n\t\t\t//! Incremental translation.\n\t\t\twhile (!Overlap) {\n\t\t\t\t//! Sphere point picking. This is the random direction step of\n\t\t\t\t//! Jullien's BCCA algorithm. It is incorrect to select spherical\n\t\t\t\t//! coordinates theta (polar angle) and phi (azimuthal angle) from\n\t\t\t\t//! uniform distributions theta E [0, 2 * pi) and phi E [0, pi] as\n\t\t\t\t//! points picked in this way will be 'bunched' near the poles:\n\t\t\t\t//! http://mathworld.wolfram.com/SpherePointPicking.html\n\t\t\t\tdouble theta = 2.0 * PI * uniformGenerator();\n\t\t\t\tdouble phi = acos(2.0 * uniformGenerator() - 1.0);\n\n\t\t\t\t//! In terms of Cartesian coordinates.\n\t\t\t\tdouble x = cos(theta) * sin(phi);\n\t\t\t\tdouble y = sin(theta) * sin(phi);\n\t\t\t\tdouble z = cos(phi);\n\n\t\t\t\t//! We want to find the rotation matrix which rotates an\n\t\t\t\t//! arbitrarily chosen unit vector to the randomly chosen unit\n\t\t\t\t//! vector selected above. Not sure where the formula is from but I\n\t\t\t\t//! have checked that it works:\n\t\t\t\t//! https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d\n\t\t\t\tdouble bx = 0.0;\n\t\t\t\tdouble by = 0.0;\n\t\t\t\tdouble bz = -1.0;\n\n\t\t\t\t//! Cross product of the two vectors.\n\t\t\t\tdouble vx = by * z - bz * y;\n\t\t\t\tdouble vy = bz * x - bx * z;\n\t\t\t\tdouble vz = bx * y - by * x;\n\n\t\t\t\t//! Skew-symmetric cross-product matrix of vector v.\n\t\t\t\tdouble v[3][3] = { 0 };\n\n\t\t\t\tv[0][0] = 0.0;\n\t\t\t\tv[0][1] = -vz;\n\t\t\t\tv[0][2] = vy;\n\t\t\t\tv[1][0] = vz;\n\t\t\t\tv[1][1] = 0.0;\n\t\t\t\tv[1][2] = -vx;\n\t\t\t\tv[2][0] = -vy;\n\t\t\t\tv[2][1] = vx;\n\t\t\t\tv[2][2] = 0.0;\n\n\t\t\t\t//! Identity.\n\t\t\t\tdouble I[3][3] = { 0 };\n\n\t\t\t\tI[0][0] = 1.0;\n\t\t\t\tI[0][1] = 0.0;\n\t\t\t\tI[0][2] = 0.0;\n\t\t\t\tI[1][0] = 0.0;\n\t\t\t\tI[1][1] = 1.0;\n\t\t\t\tI[1][2] = 0.0;\n\t\t\t\tI[2][0] = 0.0;\n\t\t\t\tI[2][1] = 0.0;\n\t\t\t\tI[2][2] = 1.0;\n\n\t\t\t\t//! Rotation matrix.\n\t\t\t\tdouble R[3][3] = { 0 };\n\t\t\t\tdouble Mult = 1.0 / (1.0 + bx * x + by * y + bz * z); //!< Dot product of the two unit vectors.\n\n\t\t\t\t//! Square of the matrix v.\n\t\t\t\tR[0][0] = Mult * (-vy * vy - vz * vz);\n\t\t\t\tR[0][1] = Mult * (vx * vy);\n\t\t\t\tR[0][2] = Mult * (vx * vz);\n\t\t\t\tR[1][0] = Mult * (vx * vy);\n\t\t\t\tR[1][1] = Mult * (-vx * vx - vz * vz);\n\t\t\t\tR[2][2] = Mult * (vy * vz);\n\t\t\t\tR[2][0] = Mult * (vx * vz);\n\t\t\t\tR[2][1] = Mult * (-vy * vz);\n\t\t\t\tR[2][2] = Mult * (-vx * vx - vy * vy);\n\n\t\t\t\tR[0][0] = 1.0 + R[0][0];\n\t\t\t\tR[0][1] = -vz + R[0][1];\n\t\t\t\tR[0][2] = vy + R[0][2];\n\t\t\t\tR[1][0] = vz + R[1][0];\n\t\t\t\tR[1][1] = 1.0 + R[1][1];\n\t\t\t\tR[1][2] = -vx + R[1][2];\n\t\t\t\tR[2][0] = -vy + R[2][0];\n\t\t\t\tR[2][1] = vx + R[2][1];\n\t\t\t\tR[2][2] = 1.0 + R[2][2];\n\n\t\t\t\t//! Disk point picking. This is the random impact step of Jullien's\n\t\t\t\t//! BCCA algorithm. We first randomly select a point in the x-y\n\t\t\t\t//! plane over a disk of diameter and at a distance equal to the\n\t\t\t\t//! sum of the primary particle radii as this is the maximum\n\t\t\t\t//! distance they can be apart. Then we apply the rotation matrix\n\t\t\t\t//! obtained above to the point:\n\t\t\t\t//http://mathworld.wolfram.com/DiskPointPicking.html\n\t\t\t\tdouble r = uniformGenerator();\n\t\t\t\ttheta = 2.0 * PI * uniformGenerator();\n\n\t\t\t\tdouble sumr = m_leftchild->Radius() + m_rightchild->Radius();\n\n\t\t\t\tdouble x3 = (sumr / 2.0) * sqrt(r) * cos(theta);\n\t\t\t\tdouble y3 = (sumr / 2.0) * sqrt(r) * sin(theta);\n\t\t\t\tdouble z3 = -sumr;\n\n\t\t\t\tdouble x4 = R[0][0] * x3 + R[0][1] * y3 + R[0][2] * z3;\n\t\t\t\tdouble y4 = R[1][0] * x3 + R[1][1] * y3 + R[1][2] * z3;\n\t\t\t\tdouble z4 = R[2][0] * x3 + R[2][1] * y3 + R[2][2] * z3;\n\n\t\t\t\tthis->m_leftchild->Translate(x4, y4, z4);\n\n\t\t\t\t//! The two particles are initially at the origin. Keep doubling\n\t\t\t\t//! the distance between them so that they do not overlap. This is\n\t\t\t\t//! more efficient than picking an arbitrarily large distance.\n\t\t\t\tint numberOfOverlaps = 0;\n\t\t\t\tint factorApart = 1;\n\t\t\t\tdouble Separation = 0.0;\n\n\t\t\t\twhile (this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation)) {\n\t\t\t\t\tthis->m_leftchild->Translate(-factorApart * R[0][2] * sumr, -factorApart * R[1][2] * sumr, -factorApart * R[2][2] * sumr);\n\t\t\t\t\tfactorApart *= 2;\n\t\t\t\t}\n\n\t\t\t\tnumberOfOverlaps = 0;\n\n\t\t\t\twhile (!Overlap) {\n\t\t\t\t\tdouble dx = this->m_leftchild->m_cen_bsph[0];\n\t\t\t\t\tdouble dy = this->m_leftchild->m_cen_bsph[1];\n\t\t\t\t\tdouble dz = this->m_leftchild->m_cen_bsph[2];\n\n\t\t\t\t\tdouble oldDistance = dx * dx + dy * dy + dz * dz;\n\n\t\t\t\t\t//! Translate particle in 1% increments.\n\t\t\t\t\tthis->m_leftchild->Translate(-0.01 * x * sumr, -0.01 * y * sumr, -0.01 * z * sumr);\n\n\t\t\t\t\tOverlap = this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation);\n\n\t\t\t\t\tdx = this->m_leftchild->m_cen_bsph[0];\n\t\t\t\t\tdy = this->m_leftchild->m_cen_bsph[1];\n\t\t\t\t\tdz = this->m_leftchild->m_cen_bsph[2];\n\n\t\t\t\t\tdouble newDistance = dx * dx + dy * dy + dz * dz;\n\n\t\t\t\t\t//! If the left particle has failed to collide with the\n\t\t\t\t\t//! particle at the origin (first condition) or if there are\n\t\t\t\t\t//! multiple points of overlap (second condition), the trial is\n\t\t\t\t\t//! abandoned and another trajectory is chosen.\n\t\t\t\t\tif ((newDistance > oldDistance && newDistance > sumr * sumr) || (numberOfOverlaps > 1)) {\n\t\t\t\t\t\tthis->m_leftchild->centreBoundSph();\n\t\t\t\t\t\tthis->m_leftchild->centreCOM();\n\t\t\t\t\t\tnumberOfOverlaps = 0;\n\t\t\t\t\t\tOverlap = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//! Newton bisection method to speed up translation.\n\t\t\t\t//! Needs to be tested.\n\t\t\t\t//double a = 0.0;\n\t\t\t\t//double b = 0.0;\n\t\t\t\t//double c = 0.0;\n\n\t\t\t\t//b = this->m_leftchild->m_cen_bsph[2];\n\t\t\t\t//double Translation = - (b - (a + b) / 2.0);\n\n\t\t\t\t//numberOfOverlaps = 0;\n\n\t\t\t\t//while (!(abs(Separation - 1) < 0.01 && numberOfOverlaps == 1)) {\n\t\t\t\t//    this->m_leftchild->Translate(0, 0, Translation);\n\n\t\t\t\t//    numberOfOverlaps = 0;\n\n\t\t\t\t//    if (this->checkForOverlap(*m_leftchild, *m_rightchild, numberOfOverlaps, Separation)) {\n\t\t\t\t//        a = this->m_leftchild->m_cen_bsph[2];\n\t\t\t\t//        Translation = (a + b) / 2.0 - a;\n\t\t\t\t//    } else {\n\t\t\t\t//        b = this->m_leftchild->m_cen_bsph[2];\n\t\t\t\t//        Translation = - (b - (a + b) / 2.0);\n\t\t\t\t//    }\n\t\t\t\t//}\n\t\t\t}\n\n\t\t\tdouble deltax = m_rightparticle->m_cen_bsph[0] - m_leftparticle->m_cen_bsph[0];\n\t\t\tdouble deltay = m_rightparticle->m_cen_bsph[1] - m_leftparticle->m_cen_bsph[1];\n\t\t\tdouble deltaz = m_rightparticle->m_cen_bsph[2] - m_leftparticle->m_cen_bsph[2];\n\n\t\t\tm_distance_centreToCentre = sqrt(deltax * deltax + deltay * deltay + deltaz * deltaz);\n\n\t\t\t//! Calculate properties of this particle.\n\t\t\tthis->calcBoundSph();\n\t\t\tthis->calcCOM();\n\n\t\t\t//! If particle contains PAH to be traced write POV-Ray translation\n\t\t\t//! of particle\n\t\t\tthis->centreBoundSph();\n\n\t\t\t//! Particle is centred about its bounding sphere for the purpose\n\t\t\t//! generating its structure. Now that it is complete centre it\n\t\t\t//! about its centre-of-mass.\n\t\t\tthis->centreCOM();\n\n\t\t}\n\t\telse {\n\t\t\t//! Randomly select the primaries that are touching.\n\t\t\tthis->m_leftparticle = m_leftchild->SelectRandomSubparticle(rng);\n\t\t\tthis->m_rightparticle = m_rightchild->SelectRandomSubparticle(rng);\n\t\t}\n\n\t\t//set the sintertime for the new created primary particle\n\t\tSetSinteringTime(std::max(this->m_sint_time, rhsparticle->m_sint_time));\n\t\tm_createt = max(m_createt, rhsparticle->m_createt);\n\t\t//initialise the variables used to calculate the coalesence ratio\n\t\tm_children_vol = m_leftparticle->m_vol + m_rightparticle->m_vol;\n\t\tm_children_surf = (m_leftparticle->m_surf + m_rightparticle->m_surf);\n\n\t\tm_leftparticle_vol_old = m_leftparticle->m_vol;\n\t\tm_rightparticle_vol_old = m_rightparticle->m_vol;\n\t\tm_leftparticle_numPAH = m_leftparticle->m_numPAH;\n\t\tm_rightparticle_numPAH = m_rightparticle->m_numPAH;\n\n\t\tm_children_radius = pow(3.0 / (4.0*PI)*(m_children_vol), (ONE_THIRD));\n\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())\n\t\t\tm_children_sintering = SinteringLevel();\n\t\telse\n\t\t\tm_children_roundingLevel = CoalescenceLevel();\n\n\t\tm_distance_centreToCentre = m_leftparticle->m_primarydiam / 2.0 + m_rightparticle->m_primarydiam / 2.0;\n\n\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\tdouble x1 = m_leftparticle->m_cen_bsph[0];\n\t\t\tdouble y1 = m_leftparticle->m_cen_bsph[1];\n\t\t\tdouble z1 = m_leftparticle->m_cen_bsph[2];\n\n\t\t\tdouble x2 = m_rightparticle->m_cen_bsph[0];\n\t\t\tdouble y2 = m_rightparticle->m_cen_bsph[1];\n\t\t\tdouble z2 = m_rightparticle->m_cen_bsph[2];\n\n\t\t\tm_distance_centreToCentre = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1));\n\t\t}\n\t\telse if (m_pmodel->getTrackPrimarySeparation()) {\n\t\t\tm_distance_centreToCentre = m_leftparticle->m_primarydiam / 2.0 + m_rightparticle->m_primarydiam / 2.0;\n\t\t}\n\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())\n\t\t\tCheckSintering();\n\t\telse\n\t\t\tCheckRounding();\n\n\t\t//must set all the pointer to NULL otherwise the delete function\n\t\t//will also delete the children\n\t\tcopy_rhs.m_leftchild = NULL;\n\t\tcopy_rhs.m_rightchild = NULL;\n\t\tcopy_rhs.m_parent = NULL;\n\t\tcopy_rhs.m_leftparticle = NULL;\n\t\tcopy_rhs.m_rightparticle = NULL;\n\t\t//\trhsparticle->Clear();\n\t\t//    if (fabs(surfacebeforerhs+surfacebefore-m_surf)/m_surf > 1e-6)\n\t\t//    {\n\t\t//        cout << \"error\" << surfacebeforerhs<<' ' <<surfacebefore << ' '<<m_surf<<endl;\n\t\t////         PrintTree(\"after\");\n\t\t//    }\n\t\t// if (print)\n\t\t//     PrintTree(\"after\");\n\n\t}\n\treturn *this;\n}\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nPAHPrimary &PAHPrimary::Fragment(const Primary &rhs, rng_type &rng)\n{\n    vector<PAH>::const_iterator j;\n    const PAHPrimary *rhsparticle = NULL;\n    rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(&rhs);\n\n    //only one PAH in rhs or this particle -> condensation or inception process.\n    if ( (rhsparticle->m_numPAH==1) || (m_numPAH==1 ))\n    {\n        if (rhsparticle->Numprimary()>1)\n        {\n            // rhsparticle is a soot particle but this paricle repesents a PAH\n            // this paricle will condense on this rhsparticle\n            // Get a copy of the rhs ready to add to the current particle\n            PAHPrimary copy_rhs(*rhsparticle);\n            PAHPrimary *target = copy_rhs.SelectRandomSubparticle(rng);\n\n            target->m_PAH.insert(target->m_PAH.end(),m_PAH.begin(),m_PAH.end());\n\t\t\ttarget->UpdatePrimary();\n            CopyParts(&copy_rhs);\n            CopyTree(&copy_rhs);\n        }\n        else\n        {\n            // this paricle is a soot particle but rhsparticle repesents a PAH\n            // rhsparticle will condense on this particle\n            // particle has more then one primary select the primary where\n            // the PAH condenses to and add it to the list\n            if (m_leftchild!=NULL)\n            {\n                PAHPrimary *target = SelectRandomSubparticle(rng);\n\n                target->m_PAH.insert(target->m_PAH.end(),rhsparticle->m_PAH.begin(),rhsparticle->m_PAH.end());\n                target->UpdatePrimary();\n\n            }\n            else\n            {\n                //this particle and rhsparticle are both PAHs, this process should be inception\n                m_PAH.insert(m_PAH.end(),rhsparticle->m_PAH.begin(),rhsparticle->m_PAH.end());\n                UpdatePrimary();\n            }\n        }\n\t\tUpdateCache();\n        //Check the coalescence ratio\n        CheckSintering();\n\n\t}\n\n    else\n    {\n            //coagulation process\n            PAHPrimary *newleft = new PAHPrimary;\n\t\t    PAHPrimary *newright = new PAHPrimary;\n            PAHPrimary copy_rhs(*rhsparticle);\n\t\t    //rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(&rhs);\n\n           // bool print=false;\n           // if (this->m_numprimary>2 && notconstpah->m_numprimary>2)\n           // {\n            //    PrintTree(\"before1\");\n           //     notconstpah->PrintTree(\"before2\");\n             //   print=true;\n              //  cout << \"printing tree\"<<endl;\n            //}\n\n            //select where to add the second particle\n            boost::bernoulli_distribution<> bernoulliDistrib;\n            boost::variate_generator<rng_type &, boost::bernoulli_distribution<> > leftRightChooser(rng, bernoulliDistrib);\n\t\t    if (leftRightChooser())\n\t\t    {\n\t\t\t    newleft->CopyParts(this);\n\t\t\t    newright->CopyParts(&copy_rhs);\n\t\t    }\n\t\t    else\n\t\t    {\n\t\t\t    newright->CopyParts(this);\n\t\t\t    newleft->CopyParts(&copy_rhs);\n\t\t    }\n            //set the pointers\n\t\t    m_leftchild=newleft;\n\t\t    m_rightchild=newright;\n\t\t    newright->m_parent=this;\n\t\t    newleft->m_parent=this;\n            //set the pointers to the parent node\n\t\t    if (newleft->m_leftchild!=NULL)\n\t\t    {\n\t\t\t    newleft->m_leftchild->m_parent=newleft;\n\t\t\t    newleft->m_rightchild->m_parent=newleft;\n\t\t    }\n\t\t    if (newright->m_leftchild!=NULL)\n\t\t    {\n\t\t\t    newright->m_leftchild->m_parent=newright;\n\t\t\t    newright->m_rightchild->m_parent=newright;\n\t\t    }\n            m_children_roundingLevel=0;\n\t\t    UpdateCache();\n            //select the primaries that are touching\n\t\t    this->m_leftparticle=m_leftchild->SelectRandomSubparticle(rng);\n\t\t    this->m_rightparticle=m_rightchild->SelectRandomSubparticle(rng);\n\n            //set the sintertime for the new created primary particle\n            SetSinteringTime(std::max(this->m_sint_time, rhsparticle->m_sint_time));\n            //initialise the variables used to calculate the coalesence ratio\n            m_children_vol=m_leftparticle->m_vol+m_rightparticle->m_vol;\n            m_children_surf=(m_leftparticle->m_surf+m_rightparticle->m_surf);\n            m_leftparticle_vol_old=m_leftparticle->m_vol;\n            m_rightparticle_vol_old=m_rightparticle->m_vol;\n            m_leftparticle_numPAH=m_leftparticle->m_numPAH;\n            m_rightparticle_numPAH=m_rightparticle->m_numPAH;\n            m_children_radius=pow(3.0/(4.0*PI)*(m_children_vol),(ONE_THIRD));\n            m_children_roundingLevel=CoalescenceLevel();\n            CheckSintering();\n            //must set all the pointer to NULL otherwise the delete function\n            //will also delete the children\n\t        copy_rhs.m_leftchild=NULL;\n\t        copy_rhs.m_rightchild=NULL;\n\t        copy_rhs.m_parent=NULL;\n            copy_rhs.m_leftparticle=NULL;\n            copy_rhs.m_rightparticle=NULL;\n\t\t//\trhsparticle->Clear();\n        //    if (fabs(surfacebeforerhs+surfacebefore-m_surf)/m_surf > 1e-6)\n        //    {\n        //        cout << \"error\" << surfacebeforerhs<<' ' <<surfacebefore << ' '<<m_surf<<endl;\n        ////         PrintTree(\"after\");\n        //    }\n        // if (print)\n    //     PrintTree(\"after\");\n\n\t}\n    return *this;\n}\n\n//from bintree model//\n//! Check for the overlap of primary particles.\n/*!\n* @brief       Copy state-space and derived properties from source *\n*  @return Whether there is the overlap of primary particles.\n*/\nbool PAHPrimary::checkForOverlap(PAHPrimary &target, PAHPrimary &bullet, int &numberOfOverlaps, double &Separation)\n{\n\tbool Overlap = false;\n\n\tif (target.isLeaf()) {\n\t\t//! Target is a leaf.\n\t\tif (bullet.isLeaf()) {\n\t\t\tOverlap = particlesOverlap(target.boundSphCentre(), target.Radius(), bullet.boundSphCentre(), bullet.Radius(), Separation);\n\n\t\t\t//! Keep a running total of the number of overlaps, and the left\n\t\t\t//! and right particles should not be assigned unless there is\n\t\t\t//! overlap.\n\t\t\tif (Overlap) {\n\t\t\t\tnumberOfOverlaps += 1;\n\n\t\t\t\t//! Bullet is a leaf (both leaves).\n\t\t\t\tthis->m_leftparticle = &target;\n\t\t\t\tthis->m_rightparticle = &bullet;\n\t\t\t}\n\n\t\t\treturn Overlap;\n\t\t}\n\t\telse {\n\t\t\t//! Bullet is not a leaf, call sub-nodes.\n\t\t\tOverlap = checkForOverlap(target, *bullet.m_leftchild, numberOfOverlaps, Separation);\n\t\t\tOverlap = checkForOverlap(target, *bullet.m_rightchild, numberOfOverlaps, Separation) || Overlap;\n\n\t\t\treturn Overlap;\n\t\t}\n\t}\n\telse {\n\t\t//! Target is not a leaf.\n\t\tif (bullet.isLeaf()) {\n\t\t\t//! Bullet is a leaf, call target sub-nodes.\n\t\t\tOverlap = checkForOverlap(*target.m_leftchild, bullet, numberOfOverlaps, Separation);\n\t\t\tOverlap = checkForOverlap(*target.m_rightchild, bullet, numberOfOverlaps, Separation) || Overlap;\n\n\t\t\treturn Overlap;\n\t\t}\n\t\telse {\n\t\t\t//! Bullet is not a leaf (neither is a leaf), check all left/right\n\t\t\t//! collision combinations.\n\t\t\t//! Target left and bullet left.\n\t\t\tOverlap = checkForOverlap(*target.m_leftchild, *bullet.m_leftchild, numberOfOverlaps, Separation);\n\n\t\t\t//! Target left and bullet right.\n\t\t\tOverlap = checkForOverlap(*target.m_leftchild, *bullet.m_rightchild, numberOfOverlaps, Separation) || Overlap;\n\n\t\t\t//! Target right and bullet left.\n\t\t\tOverlap = checkForOverlap(*target.m_rightchild, *bullet.m_leftchild, numberOfOverlaps, Separation) || Overlap;\n\n\t\t\t//! Target right and bullet right.\n\t\t\tOverlap = checkForOverlap(*target.m_rightchild, *bullet.m_rightchild, numberOfOverlaps, Separation) || Overlap;\n\n\t\t\treturn Overlap;\n\t\t}\n\t}\n}\n\n//from bintree model.//\n//! Determine whether the particles overlap.\n/*!\n*  @param[in]  p1         Coordinates of sphere 1.\n*  @param[in]  r1         Radius of sphere 1.\n*  @param[in]  p2         Coordinates of sphere 2.\n*  @param[in]  r2         Radius of sphere 2.\n*  @param[out] Separation Separation between the centres of the primary\n*                         particles for use with the Newton bisection\n*                         method.\n*\n*  @return Do the particles overlap?\n*/\nbool PAHPrimary::particlesOverlap(const Coords::Vector &p1, double r1,\n\tconst Coords::Vector &p2, double r2, double &Separation)\n{\n\tdouble sumrsqr;\n\n\tsumrsqr = r1 + r2;\n\n\t//! Calculate the square of the sum of the radii.\n\tsumrsqr *= sumrsqr;\n\n\t//! Calculate dx, dy and dz.\n\tdouble xdev = p2[0] - p1[0];\n\tdouble ydev = p2[1] - p1[1];\n\tdouble zdev = p2[2] - p1[2];\n\n\t//! Calculate dx, dy and dz squared.\n\tdouble dxsqr = xdev * xdev;\n\tdouble dysqr = ydev * ydev;\n\tdouble dzsqr = zdev * zdev;\n\n\t//! The particles overlap if the centre-to-centre distance is less than the\n\t//! sum of the primary radii.\n\tif (sumrsqr < dxsqr + dysqr + dzsqr) {\n\t\tSeparation = 0.0;\n\t\treturn false;\n\t}\n\telse {\n\t\tSeparation = sqrt(dxsqr + dysqr + dzsqr);\n\t\treturn true;\n\t}\n}\n\n//from bintree model//\n//! Calculates the radius of gyration of a particle.\ndouble PAHPrimary::GetRadiusOfGyration() const\n{\n\tdouble sum = 0;\n\tdouble mass;\n\tdouble totalmass = 0;\n\tdouble r2;\n\tdouble Rg;\n\tdouble rix, riy, riz, rjx, rjy, rjz, drx, dry, drz;\n\tvector<fvector> coords;\n\n\tif (m_numprimary == 1) {\n\t\t//if single primary return the primary radius\t\n\t\tRg = m_primarydiam / 2.0;\n\n\t}else{\n\n\t\tthis->GetPriCoords(coords);\n\n\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t//! Calculation is based on Eq. (1) in R. Jullien, Transparency effects\n\t\t\t//! in cluster-cluster aggregation with linear trajectories, J. Phys. A\n\t\t\t//! 17 (1984) L771-L776. \n\t\t\tfor (int i = 0; i != coords.size(); ++i) {\n\t\t\t\tfor (int j = 0; j != coords.size(); ++j) {\n\t\t\t\t\trix = coords[i][0];\n\t\t\t\t\triy = coords[i][1];\n\t\t\t\t\triz = coords[i][2];\n\n\t\t\t\t\trjx = coords[j][0];\n\t\t\t\t\trjy = coords[j][1];\n\t\t\t\t\trjz = coords[j][2];\n\n\t\t\t\t\t//! Expansion of (r_i - r_j)^2 term. Dot product of r vectors.\n\t\t\t\t\tsum += rix * rix + riy * riy + riz * riz +\n\t\t\t\t\t\trjx * rjx + rjy * rjy + rjz * rjz -\n\t\t\t\t\t\t2 * (rix * rjx + riy * rjy + riz * rjz);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tRg = sqrt(sum / 2 / coords.size() / coords.size());\n\t\t}\n\t\telse {\n\t\t\tfor (unsigned int i = 0; i != coords.size(); ++i) {\n\t\t\t\t//! Mass is proportional to the cube of the radius.\n\t\t\t\tmass = coords[i][3] * coords[i][3] * coords[i][3];\n\t\t\t\tr2 = coords[i][0] * coords[i][0] + coords[i][1] * coords[i][1] + coords[i][2] * coords[i][2];\n\t\t\t\tsum += mass * r2;\n\t\t\t\ttotalmass += mass;\n\t\t\t}\n\n\t\t\tRg = sqrt(sum / totalmass);\n\t\t}\t\n\t}\n\n\treturn Rg;\n}\n\n//from bintree model//\n//! Returns a vector of primary coordinates and radius (4D).\n/*!\n*  @param[in] coords The first three returned values are the cartesian x, y, z\n*                    coordinates, the final value is the radius.\n*/\nvoid PAHPrimary::GetPriCoords(std::vector<fvector> &coords) const\n{\n\tif (isLeaf()) {\n\t\tfvector c(4);\n\t\tc[0] = m_cen_mass[0];\n\t\tc[1] = m_cen_mass[1];\n\t\tc[2] = m_cen_mass[2];\n\t\tc[3] = m_r;\n\t\tcoords.push_back(c);\n\t}\n\telse {\n\t\tm_leftchild->GetPriCoords(coords);\n\t\tm_rightchild->GetPriCoords(coords);\n\t}\n}\n\n//returns the CoalescenceLevel of the two primaries that are connected by this node\n//only for coordinates are not tracked\ndouble PAHPrimary::CoalescenceLevel()\n{\n\tif (m_leftparticle != NULL)\n\t{\n\n\t\tdouble dV = 0;\n\n\n\t\t//make sure that the volume growth does not arise from a former coalescence event\n\t\t//(number of PAHs must remain const, or increase by 1 in case of a condensation\n\t\t// event\n\t\t// if the volume changes due to a coalescence event the chilren surface is changed in\n\t\t// PAHPrimary::ChangePointer(PAHPrimary *source, PAHPrimary *target)\n\n\t\t// m_leftparticle->m_numPAH is the actual number of PAHs in the left one of the two\n\t\t// touching primary particles.\n\n\t\t// m_leftparticle_numPAH is the the number of PAHs in the left one of the two touching\n\t\t// particles last time this method was called.\n\n\t\t// The following test checks that at most one PAH has been added to the left one\n\t\t// of the two touching primaries since this method was last called.\n\t\tif (m_leftparticle->m_numPAH - m_leftparticle_numPAH < 2)\n\t\t{\n\t\t\t//calculate the volume change of the left particle in the last timestep\n\t\t\tdV += m_leftparticle->m_vol - m_leftparticle_vol_old;\n\t\t}\n\n\t\t//adjust the number of PAHs and vol for the next step\n\t\tm_leftparticle_numPAH = m_leftparticle->m_numPAH;\n\t\tm_leftparticle_vol_old = m_leftparticle->m_vol;\n\n\t\t//make sure that the volume growth does not arise from a coalescence event\n\t\t//(number of PAHs must remain const, or increase by1 in case of a condensation\n\t\t// event\n\t\tif (m_rightparticle->m_numPAH - m_rightparticle_numPAH < 2)\n\t\t{\n\t\t\t//calculate the volume change of the right particle in the last timestep\n\t\t\tdV += m_rightparticle->m_vol - m_rightparticle_vol_old;\n\t\t}\n\n\t\t//adjust the number of PAHs and vol for the next step\n\t\tm_rightparticle_numPAH = m_rightparticle->m_numPAH;\n\t\tm_rightparticle_vol_old = m_rightparticle->m_vol;\n\n\t\t//update the children volume, this value is used to calculate dV n the next timestep\n\t\tm_children_vol = m_rightparticle->m_vol + m_leftparticle->m_vol;\n\t\t//calculate dS, at the moment it is assumed that the particles always grow\n\t\tdouble ct = m_pmodel->Components(0)->CoalescThresh();\n\t\tconst double dS = dV*ct / m_children_radius;\n\t\t//update the radius for the next event\n\t\tm_children_radius = pow(3.0 / (4.0*PI)*(m_children_vol), (ONE_THIRD));\n\t\tm_children_surf += dS;\n\n\t\t// const double spherical_surface=4*PI*m_children_radius*m_children_radius;\n\t\t//// double two_1_3=pow(2,-1*ONE_THIRD);\n\t\t// const double two_1_3=0.79370052231642452;\n\t\t// double clevel= ((spherical_surface/m_children_surf)-two_1_3)/(1-two_1_3);\n\t\t// if (clevel<0)\n\t\t//     return 0;\n\t\t// else\n\t\t//     return clevel;\n\t\treturn RoundingLevel();\n\t}\n\telse\n\t\treturn 0;\n}\n\n//calculates the fractal dimension of the particle and stores it in m_fdim\n//void PAHPrimary::CalcFractalDimension()\n//{\n//\tSweep::Imaging::ParticleImage img;\n//    // construct the particle by colliding the primary particles\n//\timg.constructSubParttree(this);\n//\tdouble L,W;\n//    // calculate the length and the width of the particle\n//    img.LengthWidth(L,W);\n//    // calculate the radius of gyration\n//    m_Rg=img.RadiusofGyration();\n//\tm_sqrtLW=sqrt(L*W);\n//\tm_LdivW=L/W;\n//    m_Rg=m_Rg*1e-9;\n//    m_fdim=log((double)m_numprimary)/log(2*m_Rg/(m_primarydiam/m_numprimary));\n//  /*  if (m_fdim>0 && m_fdim<3)\n//    {\n//       string filename;\n//       filename=cstr(m_fdim)+\".3d\";\n//       ofstream out;\n//       out.open(filename.c_str());\n//       img.Write3dout(out,0,0,0);\n//       out.close();\n//    }*/\n//\n//}\n\n// sets all the childrenproperties to zero, this function is used after the children are coalesced\nvoid PAHPrimary::ResetChildrenProperties()\n{\n            m_children_roundingLevel=0.0;\n            m_children_surf=0.0;\n            m_children_vol=0.0;\n            m_distance_centreToCentre=0.0;\n            m_rightparticle_vol_old=0.0;\n            m_leftparticle_vol_old=0.0;\n            m_leftparticle_numPAH=0;\n            m_rightparticle_numPAH=0;\n            m_avg_coalesc=0; //no track\n\n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\t\t{\n\t\t\t\tm_children_sintering = 0.0;\n\t\t\t\tm_children_radius = 0.0; \n\t\t\t\tm_avg_sinter = 0;\n\t\t\t\tm_sint_rate = 0.0;\n\t\t\t\tm_children_sumCap = 0.0; //used to calculate geometric volume of a particle\n\t\t\t}\n}\n\n//merges the left and the right primary particle to one primary particle\nPAHPrimary &PAHPrimary::Merge()\n{\n\t//    if(this->m_numprimary>5)\n\t//       cout<<\"tset\";\n\t//      PrintTree(\"before.inp\");\n\t//! Declare pointers for coordinate/separation tracking model\n\n\tPAHPrimary *small_prim; //!< smaller of the merging primaries\n\tPAHPrimary *big_prim;\t//!< larger of the merging primaries\n\tPAHPrimary *new_prim;\t//!< new (merged) primary\n\n\t//initialise parameters\n\tdouble r_big, r_small, d_ij, x_ij;\n\n\tvector<PAH>::const_iterator j;\n\n\t//make sure this primary has children to merge\n\tif (m_leftchild != NULL)\n\t{\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\n\t\t\td_ij = m_distance_centreToCentre;\n\n\t\t\t//! Update primaries\n\t\t\tm_leftparticle->UpdatePrimary();\n\t\t\tm_rightparticle->UpdatePrimary();\n\n\t\t\t//! If the centre to centre distance is tracked we need to know which is the smaller primary of the merging pair\n\t\t\tif (m_leftparticle->m_primarydiam > m_rightparticle->m_primarydiam){\n\t\t\t\tsmall_prim = m_rightparticle;\n\t\t\t\tbig_prim = m_leftparticle;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tsmall_prim = m_leftparticle;\n\t\t\t\tbig_prim = m_rightparticle;\n\t\t\t}\n\n\t\t\tr_big = big_prim->m_primarydiam / 2.0;\n\t\t\tr_small = small_prim->m_primarydiam / 2.0;\n\t\t\tx_ij = min((d_ij*d_ij - r_small*r_small + r_big*r_big) / (2.0*d_ij), r_big); //!<distance from neck to centre of larger primary (x_ij < r_i)\n\n\t\t\tdouble V_prim = small_prim->m_primaryvol; //!< Volume of smaller primary\n\t\t\t\n\t\t\t//! If there is a cap (i.e. the smaller primary isn't completely enclosed)\n\t\t\tif (d_ij + r_small > r_big){\n\t\t\t\t//! calculate cap volume of larger primary\n\t\t\t\tdouble V_cap = 2.0*M_PI*r_big*r_big*r_big / 3.0 + M_PI*x_ij*x_ij*x_ij / 3.0 - M_PI*r_big*r_big*x_ij;\n\t\t\t\t//! Subtract cap volume from the merging primary's volume\n\t\t\t\tdouble dV = max(V_prim - V_cap, 0.0);\n\n\t\t\t\t//! Adjust larger primary to incorporate excess volume\n\t\t\t\tif (dV > 0.0)\n\t\t\t\t\tbig_prim->AdjustPrimary(dV, d_ij, small_prim);\n\t\t\t}\n\t\t}\n\n\t\tif (m_leftchild == m_leftparticle && m_rightchild == m_rightparticle)\n\t\t{\n\t\t\t//this node has only two primaries in its subtree\n\t\t\t//it is possible that this node is not the root node and belongs to a bigger particle\n\t\t\t//copy the PAHs of both children to the parent node\n\t\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())\n\t\t\t{\n\n\t\t\t\tnew_prim = this; //!< new primary\n\n\t\t\t\tnew_prim->m_primarydiam = big_prim->m_primarydiam;\n\t\t\t}\n\n\t\t\t//m_PAH is empty, therefore no need to append\n\t\t\tm_PAH = m_rightparticle->m_PAH;\n\n\t\t\tm_PAH.insert(this->m_PAH.end(), m_leftparticle->m_PAH.begin(), m_leftparticle->m_PAH.end());\n\n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\t\tnew_prim->m_cen_bsph = big_prim->m_cen_bsph;\n\t\t\t\tnew_prim->m_cen_mass = big_prim->m_cen_mass;\n\t\t\t}\n\n\t\t\t//! Update the pointers that pointed to the two former children\n\t\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\tChangePointer(m_leftchild, this);\n\t\t\t\tChangePointer(m_rightchild, this);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//! If coordinates/separation are tracked the pointer to the larger primary is changed first\n\t\t\t\t//! so that primary properties are correctly calculated when adding neighbours\n\t\t\t\tChangePointer(big_prim, this, small_prim, this);\n\t\t\t\tChangePointer(small_prim, this, small_prim, this);\n\t\t\t}\n\n\t\t\t//delete the children (destructor is recursive for this class)\n\t\t\tdelete m_leftchild;\n\t\t\tdelete m_rightchild;\n\t\t\tm_leftchild = NULL;\n\t\t\tm_rightchild = NULL;\n\t\t\tm_leftparticle = NULL;\n\t\t\tm_rightparticle = NULL;\n\n\t\t\t//set the children properties to zero, this node has no more children\n\t\t\tResetChildrenProperties();\n\t\t\tUpdatePrimary();\n\n\t\t\t// Only update the cache on m_parent if the sintering level of\n\t\t\t// m_parent if the sintering level won't call a merge on the\n\t\t\t// parent node. Otherwise, the *this* memory address could be\n\t\t\t// removed from the tree and segmentation faults will result!\n\t\t\t//if (m_parent != NULL) {\n\t\t\t//\tif (!m_parent->MergeCondition()) {\n\t\t\t//\t\tm_parent->UpdateCache();\n\t\t\t//\t}\n\t\t\t//}\n\n\t\t}\n\n\t\telse //******m_leftchild != m_leftparticle or m_rightchild != m_rightparticle******//\n\t\t{\n\t\t\t//! If primary coordinates or primary separations are not tracked then \n\t\t\t//! select subtree to keep the tree balanced\n\t\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\n\t\t\t\tif (m_leftchild->m_numprimary < m_rightchild->m_numprimary)\n\t\t\t\t{\n\t\t\t\t\t//append to left subtree because there are fewer primaries\n\t\t\t\t\t//this is only to keep the tree balanced\n\t\t\t\t\tPAHPrimary *oldleftparticle = m_leftparticle;\n\n\t\t\t\t\t//copy the PAHs\n\n\t\t\t\t\t//for (j=oldleftparticle->m_PAH.begin(); j!=oldleftparticle->m_PAH.end(); ++j) {\n\t\t\t\t\t//\tm_rightparticle->m_PAH.insert(m_rightparticle->m_PAH.end(),PAH(*j));\n\t\t\t\t\t//}\n\n\t\t\t\t\tm_rightparticle->m_PAH.insert(m_rightparticle->m_PAH.end(), oldleftparticle->m_PAH.begin(), oldleftparticle->m_PAH.end());\n\t\t\t\t\tm_rightparticle->UpdatePrimary();\n\t\t\t\t\t//set the pointers from the leftprimary to the rightprimary\n\t\t\t\t\t//this will be the new bigger primary\n\t\t\t\t\toldleftparticle->ChangePointer(oldleftparticle, m_rightparticle);\n\t\t\t\t\tm_rightparticle->ChangePointer(m_rightparticle, m_rightparticle);\n\n\t\t\t\t\t//set the pointer to the parent node\n\t\t\t\t\tif (oldleftparticle->m_parent->m_leftchild == oldleftparticle)\n\t\t\t\t\t{\n\t\t\t\t\t\toldleftparticle->m_parent->m_leftchild = m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\toldleftparticle->m_parent->m_rightchild = m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_rightchild->m_parent = oldleftparticle->m_parent;\n\n\n\t\t\t\t\tPAHPrimary *oldleftchild = m_leftchild;\n\t\t\t\t\tPAHPrimary *oldparent = m_parent;\n\n\t\t\t\t\t//copy the properties of the former leftchild to this node\n\t\t\t\t\t// so that it can be removed from the aggregate tree structure\n\t\t\t\t\tCopyParts(oldleftchild);\n\n\t\t\t\t\t// Now break the links to the tree structure in oldleftchild and free it\n\t\t\t\t\toldleftchild->m_leftchild = NULL;\n\t\t\t\t\toldleftchild->m_rightchild = NULL;\n\t\t\t\t\tdelete oldleftchild;\n\n\t\t\t\t\tm_parent = oldparent;\n\t\t\t\t\tif (m_leftchild != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_rightchild->m_parent = this;\n\t\t\t\t\t\tm_leftchild->m_parent = this;\n\t\t\t\t\t}\n\n\t\t\t\t\tdelete oldleftparticle;\n\n\t\t\t\t}\n\n\t\t\t\telse //******m_leftchild->m_numprimary > m_rightchild->m_numprimary******//\n\t\t\t\t{\n\t\t\t\t\t//append to right subtree\n\t\t\t\t\tPAHPrimary *oldrightparticle = m_rightparticle;\n\n\t\t\t\t\t//\tfor (j=oldrightparticle->m_PAH.begin(); j!=oldrightparticle->m_PAH.end(); ++j) {\n\t\t\t\t\t//\t\tm_leftparticle->m_PAH.insert(m_leftparticle->m_PAH.end(),PAH(*j));\n\t\t\t\t\t//\t}\n\n\t\t\t\t\tm_leftparticle->m_PAH.insert(m_leftparticle->m_PAH.end(), oldrightparticle->m_PAH.begin(), oldrightparticle->m_PAH.end());\n\t\t\t\t\tm_leftparticle->UpdatePrimary();\n\n\t\t\t\t\toldrightparticle->ChangePointer(oldrightparticle, m_leftparticle);\n\t\t\t\t\tm_leftparticle->ChangePointer(m_leftparticle, m_leftparticle);\n\n\t\t\t\t\tif (oldrightparticle->m_parent->m_leftchild == oldrightparticle)\n\t\t\t\t\t{\n\t\t\t\t\t\toldrightparticle->m_parent->m_leftchild = m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\toldrightparticle->m_parent->m_rightchild = m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_leftchild->m_parent = oldrightparticle->m_parent;\n\n\t\t\t\t\t//ReleaseMem(oldrightparticle);\n\t\t\t\t\tPAHPrimary *oldrightchild = m_rightchild;\n\t\t\t\t\tPAHPrimary *oldparent = m_parent;\n\n\t\t\t\t\t//copy the properties of the former leftchild to this node\n\t\t\t\t\t// so that it can be removed from the aggregate tree structure\n\t\t\t\t\tCopyParts(oldrightchild);\n\n\t\t\t\t\t// Now break the links to the tree structure in oldrightchild and free it\n\t\t\t\t\toldrightchild->m_leftchild = NULL;\n\t\t\t\t\toldrightchild->m_rightchild = NULL;\n\t\t\t\t\tdelete oldrightchild;\n\n\t\t\t\t\tm_parent = oldparent;\n\t\t\t\t\tif (m_leftchild != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_rightchild->m_parent = this;\n\t\t\t\t\t\tm_leftchild->m_parent = this;\n\t\t\t\t\t}\n\t\t\t\t\tdelete oldrightparticle;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//! If the coordinates/separations are tracked then the larger primary becomes the new primary\n\n\t\t\t\t//! the new (merged) primary\n\t\t\t\tnew_prim = big_prim;\n\n\t\t\t\t//! left/right flag\n\t\t\t\tbool newleft;\n\t\t\t\tif (new_prim == m_leftparticle){\n\t\t\t\t\tnewleft = true;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tnewleft = false;\n\t\t\t\t}\n\n\t\t\t\tPAHPrimary *oldparticle = small_prim;\n\t\t\t\t//! update composition\n\t\t\t\tif (newleft)\n\t\t\t\t{\n\t\t\t\t\tnew_prim->m_PAH = m_leftparticle->m_PAH;\n\t\t\t\t\tnew_prim->m_PAH.insert(m_leftparticle->m_PAH.end(), m_rightparticle->m_PAH.begin(), m_rightparticle->m_PAH.end());\n\t\t\t\t\t//new_prim->UpdatePrimary();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tnew_prim->m_PAH = m_rightparticle->m_PAH;\n\t\t\t\t\tnew_prim->m_PAH.insert(m_rightparticle->m_PAH.end(), m_leftparticle->m_PAH.begin(), m_leftparticle->m_PAH.end());\n\t\t\t\t\t//new_prim->UpdatePrimary();\n\t\t\t\t}\n\n\t\t\t\t//! update pointers to neighbours\n\t\t\t\tnew_prim->ChangePointer(new_prim, new_prim, small_prim, this);\n\t\t\t\toldparticle->ChangePointer(oldparticle, new_prim, small_prim, this);\n\n\t\t\t\t// Set the pointer to the parent node\n\t\t\t\tPAHPrimary *oldchild = NULL;\n\n\t\t\t\tif (newleft){\n\t\t\t\t\tif (oldparticle->m_parent->m_leftchild == oldparticle) {\n\t\t\t\t\t\toldparticle->m_parent->m_leftchild = m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toldparticle->m_parent->m_rightchild = m_leftchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_leftchild->m_parent = oldparticle->m_parent;\n\n\t\t\t\t\toldchild = m_rightchild;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif (oldparticle->m_parent->m_leftchild == oldparticle) {\n\t\t\t\t\t\toldparticle->m_parent->m_leftchild = m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toldparticle->m_parent->m_rightchild = m_rightchild;\n\t\t\t\t\t}\n\t\t\t\t\tm_rightchild->m_parent = oldparticle->m_parent;\n\n\t\t\t\t\toldchild = m_leftchild;\n\t\t\t\t}\n\n\t\t\t\tPAHPrimary *oldparent = m_parent;\n\n\t\t\t\t// Copy the properties of the former leftchild to this node\n\t\t\t\t// so that it can be removed from the aggregate tree structure\n\t\t\t\tCopyParts(oldchild);\n\n\t\t\t\t// Now break the links to the tree structure in oldleftchild\n\t\t\t\t// in order to free it\n\t\t\t\toldchild->m_leftchild = NULL;\n\t\t\t\toldchild->m_rightchild = NULL;\n\t\t\t\tdelete oldchild;\n\n\t\t\t\tm_parent = oldparent;\n\n\t\t\t\tif (m_leftchild != NULL) {\n\t\t\t\t\tm_rightchild->m_parent = this;\n\t\t\t\t\tm_leftchild->m_parent = this;\n\t\t\t\t}\n\n\t\t\t\tdelete oldparticle;\n\n\t\t\t}\n\t\t}\n\n\t\t//if coordinates are tracked then update the tracked radii\n\t\tif (m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\tnew_prim->setRadius(new_prim->m_primarydiam / 2.0);\n\t\t}\n\n\t\tUpdateCache();\n\t\t//      PrintTree(\"after.inp\");\n\t}\n\n\treturn *this;\n}\n\n////from bintree model//\n//void PAHPrimary::SumNeighbours(PAHPrimary *prim, double &sumterm) {\n//\n//\tdouble d_ij = m_parent->m_distance_centreToCentre;\n//\tdouble r_i = prim->m_primarydiam / 2.0;\n//\tdouble r_j = 0.0;\n//\tdouble x_ij = 0.0;\n//\n//\t//check if a neighbour of prim\n//\tif (m_parent->m_leftparticle == prim) {\n//\t\t//right particle is a neighbour\n//\t\tr_j = m_parent->m_rightparticle->m_primarydiam / 2.0;\n//\t}\n//\telse if (m_parent->m_rightparticle == prim) {\n//\t\t//left particle is a neighbour\n//\t\tr_j = m_parent->m_leftparticle->m_primarydiam / 2.0;\n//\t}\n//\telse {\n//\t\t//not a neighbour\n//\t\tr_j = 0.0;\n//\t}\n//\n//\t//if the node connects a neighbourt then calculate the summation term\n//\tif (r_j > 0.0){\n//\t\t//the volumes and radii of neighbours remain unchanged\n//\t\t//the centre to centre separations increase to allow growth of the primary\n//\t\tx_ij = (pow(d_ij, 2.0) - pow(r_j, 2.0) + pow(r_i, 2.0)) / (2.0*d_ij);\n//\t\tsumterm += x_ij - 2.0*r_i + pow(r_i, 2.0) / x_ij;\n//\t}\n//\n//\t//continue working up the binary tree\n//\tif (m_parent->m_parent != NULL){\n//\t\tm_parent->SumNeighbours(prim, sumterm);\n//\t}\n//}\n\n//! From bintree model.\n/*!\n* @brief       Identify neighbours and update centre to centre separation ignoring specified neighbour\n*\n* Works up the binary tree identifying the neighbours of the adjusted primary\n* and updates the centre to centre separation. Also sums the contribution from\n* neighbours to the free surface area.\n*\n* @param[in]   prim\t\t\tPointer to the primary being adjusted\n* @param[in]   delta_r\t\t\tChange in radius of prim\n* @param[in]   sumterm\t\t\tSum of contributions from neighbours to the free surface area of prim\n* @param[in]   prim_ignore\t\tPointer to the primary to be ignored\n*/\nvoid PAHPrimary::UpdateConnectivity(PAHPrimary *prim, double delta_r, PAHPrimary *prim_ignore){\n\n\tdouble d_ij = m_parent->m_distance_centreToCentre;\n\tdouble r_i = prim->m_primarydiam / 2.0;\n\tdouble r_j = 0.0;\n\tdouble x_ij = 0.0;\n\tPAHPrimary *neighbour = NULL;\n\n\t//! check if a neighbour of prim\n\tif (m_parent->m_leftparticle == prim && m_parent->m_rightparticle != prim_ignore) {\n\t\t//! right particle is a neighbour\n\t\tneighbour = m_parent->m_rightparticle;\n\t\tr_j = neighbour->m_primarydiam / 2.0;\n\t}\n\telse if (m_parent->m_rightparticle == prim &&  m_parent->m_leftparticle != prim_ignore) {\n\t\t//! left particle is a neighbour\n\t\tneighbour = m_parent->m_leftparticle;\n\t\tr_j = neighbour->m_primarydiam / 2.0;\n\t}\n\telse {\n\t\t//! not a neighbour\n\t\tr_j = 0.0;\n\t}\n\n\tif (r_j > 0.0){\n\n\t\tdouble d_ij_old = d_ij;\n\t\tx_ij = (pow(d_ij, 2.0) - pow(r_j, 2.0) + pow(r_i, 2.0)) / (2.0*d_ij);\n\t\t//! update centre to centre separation\n\t\t//making sure centre to centre separation remains smaller than the sum of the radii\n\t\td_ij = min(d_ij + r_i * delta_r / x_ij, r_i + r_j + delta_r);\n\t\tm_parent->m_distance_centreToCentre = d_ij;\n\n\t\t//! if primary coordinates are tracked then we need to update the coordinates of the neighbour \n\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t//! get (unit) vector separating prim and neighbour\n\t\t\tCoords::Vector u = UnitVector(prim->boundSphCentre(), neighbour->boundSphCentre());\n\t\t\tdouble delta_d = d_ij - d_ij_old; //!< change in separation (magnitude)\n\t\t\t//! translate the neighbour \n\t\t\tneighbour->TranslatePrimary(u, delta_d);\n\t\t\t//! translate all neighbours of the neighbour except prim\n\t\t\tneighbour->TranslateNeighbours(neighbour, u, delta_d, prim);\n\t\t}\n\t}\n\n\t//continue working up the binary tree\n\tif (m_parent->m_parent != NULL){\n\t\tm_parent->UpdateConnectivity(prim, delta_r, prim_ignore);\n\t}\n}\n\n//! From bintree model.\n//! Returns true if this node is a leaf (has no children).\nbool PAHPrimary::isLeaf(void) const\n{\n\treturn (m_leftchild == NULL) && (m_rightchild == NULL);\n}\n\n//! From bintree model.\n//! Returns the bounding-sphere centre.\nconst Coords::Vector &PAHPrimary::boundSphCentre(void) const\n{\n\treturn m_cen_bsph;\n}\n\n//! From bintree model.\n//! Calculates the bounding sphere position and radius using\n//! the left and right child node values.\nvoid PAHPrimary::calcBoundSph(void)\n{\n\tif ((m_leftchild != NULL) && (m_rightchild != NULL)) {\n\t\t// Calculate bounding spheres of children.\n\t\tm_leftchild->calcBoundSph();\n\t\tm_rightchild->calcBoundSph();\n\n\t\t// Calculate translation between left and right spheres.\n\t\tdouble dx = m_rightchild->m_cen_bsph[0] - m_leftchild->m_cen_bsph[0];\n\t\tdouble dy = m_rightchild->m_cen_bsph[1] - m_leftchild->m_cen_bsph[1];\n\t\tdouble dz = m_rightchild->m_cen_bsph[2] - m_leftchild->m_cen_bsph[2];\n\n\t\t// Calculate bounding sphere centre.\n\t\tm_cen_bsph[0] = m_leftchild->m_cen_bsph[0] + (0.5 * dx);\n\t\tm_cen_bsph[1] = m_leftchild->m_cen_bsph[1] + (0.5 * dy);\n\t\tm_cen_bsph[2] = m_leftchild->m_cen_bsph[2] + (0.5 * dz);\n\n\t\t// Calculate bounding sphere radius.\n\t\tsetRadius(sqrt((dx*dx) + (dy*dy) + (dz*dz)));\n\t}\n}\n\n//! From bintree model.\n//! Calculates the centre-of-mass using the left and right child node values.\nvoid PAHPrimary::calcCOM(void)\n{\n\tif ((m_leftchild != NULL) && (m_rightchild != NULL)) {\n\t\t//! Calculate centres-of-mass of left and right children.\n\t\tm_leftchild->calcCOM();\n\t\tm_rightchild->calcCOM();\n\n\t\t//! Calculate inverse total mass of left and right children.\n\t\tm_mass = m_leftchild->m_mass + m_rightchild->m_mass;\n\t\tdouble invtotmass = 1.0 / m_mass;\n\n\t\t//! Now calculate centre-of-mass.\n\t\tfor (unsigned int i = 0; i != 3; ++i) {\n\t\t\tm_cen_mass[i] = m_leftchild->m_cen_mass[i] * m_leftchild->m_mass;\n\t\t\tm_cen_mass[i] += m_rightchild->m_cen_mass[i] * m_rightchild->m_mass;\n\t\t\tm_cen_mass[i] *= invtotmass;\n\t\t}\n\t}\n\telse {\n\t\t//! If there are no children, then the centre-of-mass and bounding-\n\t\t//! sphere centre are the same.\n\t\tm_cen_mass[0] = m_cen_bsph[0];\n\t\tm_cen_mass[1] = m_cen_bsph[1];\n\t\tm_cen_mass[2] = m_cen_bsph[2];\n\t}\n}\n\n//! From bintree model.\n//! Put the bounding-sphere at the origin.\nvoid PAHPrimary::centreBoundSph(void)\n{\n\tTranslate(-m_cen_bsph[0], -m_cen_bsph[1], -m_cen_bsph[2]);\n}\n\n//! From bintree model.\n//! Put the centre-of-mass at the origin.\nvoid PAHPrimary::centreCOM(void)\n{\n\tTranslate(-m_cen_mass[0], -m_cen_mass[1], -m_cen_mass[2]);\n}\n\n//! From bintree model.\n/*!\n*  Randomly rotates the aggregate node and child structure about its centre of\n*  mass.\n*\n*  @param[in]    theta    Rotation about the pole.\n*  @param[in]    V        Vector for performing the reflection.\n*/\nvoid PAHPrimary::rotateCOM(double theta, fvector V)\n{\n\t//! Move the aggregate so that its centre-of-mass is at the origin. Store\n\t//! the coordinates, so that they can be restored afterwards.\n\tCoords::Vector D(m_cen_mass);\n\tTranslate(-D.X(), -D.Y(), -D.Z());\n\n\t//! Create transformation matrix.\n\tCoords::Matrix M;\n\t//M.SetIdentity();\n\tM.rotateArvo(theta, V);\n\n\t//! Rotate child nodes.\n\tif (m_leftchild != NULL) m_leftchild->transform(M);\n\tif (m_rightchild != NULL) m_rightchild->transform(M);\n\n\t//! Rotate bounding-sphere coordinates.\n\tm_cen_bsph = M.Mult(m_cen_bsph);\n\n\t//! Restore centre-of-mass coordinates.\n\tTranslate(D.X(), D.Y(), D.Z());\n}\n\n//! From bintree model.\n/*!\n*  @brief Sets the radius of the bounding sphere.\n*\n*  @param[in]    r    Radius of bounding sphere.\n*/\nvoid PAHPrimary::setRadius(double r)\n{\n\tm_r = r;\n\tm_r2 = r * r;\n\tm_r3 = m_r2 * m_r;\n}\n\n\n//! From bintree model.\n//! Returns the bounding sphere radius.\ndouble PAHPrimary::Radius(void) const\n{\n\treturn m_r;\n}\n\n//! From bintree model.\n/*!\n*  Transform the primary particle coordinates using the transformation matrix\n*  so as to rotate it.\n*\n*  @param[in]    mat               Transformation matrix.\n*  @param[in]    PAHTracerMatch    Flag used to indicate whether the particle\n*                                  contains the PAH to be traced.\n*/\nvoid PAHPrimary::transform(const Coords::Matrix &mat)\n{\n\t//! Descend binary tree to the leaf nodes, i.e. single primary particles.\n\tif (m_leftchild != NULL)\n\t\tm_leftchild->transform(mat);\n\tif (m_rightchild != NULL)\n\t\tm_rightchild->transform(mat);\n\n\t//! Rotate centre-of-mass and bounding sphere coordinates.\n\tm_cen_mass = mat.Mult(m_cen_mass);\n\tm_cen_bsph = mat.Mult(m_cen_bsph);\n}\n\n//! From bintree model.\n/*!\n*  Translates (moves) the aggregate node and child structure by the given\n*  amounts along the cartesian axes.\n*\n*  @param[in]    dx    Distance to translate in the x-axis.\n*  @param[in]    dy    Distance to translate in the y-axis.\n*  @param[in]    dz    Distance to translate in the z-axis.\n*/\nvoid PAHPrimary::Translate(double dx, double dy, double dz)\n{\n\t//! Translate child branches.\n\tif (m_leftchild != NULL) m_leftchild->Translate(dx, dy, dz);\n\tif (m_rightchild != NULL) m_rightchild->Translate(dx, dy, dz);\n\n\t//! Translate bounding sphere centre.\n\tm_cen_bsph.Translate(dx, dy, dz);\n\n\t//! Translate centre-of-mass.\n\tm_cen_mass.Translate(dx, dy, dz);\n}\n\n//! From bintree model.\n//! Write the coordinates of the primaries in the particle pointed to by the\n//! this pointer. Units of nm.\nvoid PAHPrimary::writePrimaryCoordinatesRadius(void)\n{\n\tif (m_leftchild != NULL)\n\t\tm_leftchild->writePrimaryCoordinatesRadius();\n\n\tif (m_rightchild != NULL)\n\t\tm_rightchild->writePrimaryCoordinatesRadius();\n\n\tstd::ofstream outfile;\n\n\tdouble r = Radius() * 1.0e9;\n\tdouble a = m_cen_mass[0] * 1.0e9;\n\tdouble b = m_cen_mass[1] * 1.0e9;\n\tdouble c = m_cen_mass[2] * 1.0e9;\n\n\t//! There is a need for these two conditions as upon exit of the function\n\t//! the aggregate node will pass through this part of the code but are only\n\t//! we are only interested in the coordinates of the primaries.\n\tif (isLeaf()) {\n\t\toutfile.open(\"Spheres.m\", std::ios_base::app);\n\t\toutfile << \"surf(x*\" << r << \"+\" << a << \",y*\" << r << \"+\" << b << \",z*\" << r << \"+\" << c << \");\\n\";\n\t\toutfile.close();\n\t}\n}\n\nvoid PAHPrimary::ReleaseMem()\n{ \n    m_PAH.clear();\n}\n\n//! Overload function. If coordinates are not tracked.\n/*!//add explanation\n * @param[in] source Pointer to the original particle\n * @param[in,out] target Pointer to the new particle\n*/\nvoid PAHPrimary::ChangePointer(PAHPrimary *source, PAHPrimary *target)\n{\n\t\tif(m_rightparticle==source){\n\t\t\tm_rightparticle=target;\n            double sphericalsurface=\n                4*PI*pow(3*(m_leftparticle->Volume()+m_rightparticle->Volume())/(4*PI),TWO_THIRDS);\n\t\t\tm_children_surf = sphericalsurface / (m_children_roundingLevel*0.2063 + 0.7937);    //sphericalsurface/(m_children_roundingLevel*(1-2^(-1/3))+2^(-1/3))\n\t\t}\n\t\tif(m_leftparticle==source){\n\t\t\tm_leftparticle=target;\n            double sphericalsurface=\n                4*PI*pow(3*(m_leftparticle->Volume()+m_rightparticle->Volume())/(4*PI),TWO_THIRDS);\n\t\t\tm_children_surf = sphericalsurface / (m_children_roundingLevel*0.2063 + 0.7937);    //sphericalsurface/(m_children_roundingLevel*(1-2^(-1/3))+2^(-1/3))\n\n\t\t}\n\n    // Update the tree above this sub-particle.\n    if (m_parent != NULL) {\n        m_parent->ChangePointer(source,target);\n    }\n\n}\n\n//! Overload function. Used if primary coordinates are not tracked.\n/*!\n * The actual interval over which the update is carried out on a PAH is from\n * lastupdated to t.\n *\n * @param[in]        t        Time up to which to update.\n * @param[in]        model    Particle model defining interpretation of particle data.\n * @param[in]        sys      Cell containing particle and providing gas phase.\n * @param[in,out]    rng      Random number generator.\n *\n */\nvoid PAHPrimary::UpdatePAHs(const double t, const double dt, const Sweep::ParticleModel &model, Cell &sys, int statweight, \n\tint ind, rng_type &rng, PartPtrVector &overflow)\n{\n    // Either the primary has two children or it is a leaf of the\n    // tree\n    if (m_leftchild!=NULL)\n    {\n        // Recurse down to the leaves\n\t\tm_leftchild->UpdatePAHs(t, dt, model, sys, statweight, ind, rng, overflow);\n\t\tm_rightchild->UpdatePAHs(t, dt, model, sys, statweight, ind, rng, overflow);\n    }\n    else\n    {\n        // There are PAHs in this primary so update them, if needed\n        // Flag to show if any PAH has been changed\n        // this flag store the condition of this cluster(primary particle)\n        bool m_PAHclusterchanged = false;\n        // this flag store the condition of a particular PAH within this cluster\n        bool m_InvalidPAH = false;\n        // check whether this updated primary particle is a inceptedPAH, used later to track the num of InceptedPAH in the ensemble\n        //const int m_InceptedPAH = InceptedPAH();\n\n        //! Loop over each PAH in this primary.\n        const std::vector<boost::shared_ptr<PAH> >::iterator itEnd = m_PAH.end();\n        for (std::vector<boost::shared_ptr<PAH> >::iterator it = m_PAH.begin(); it != itEnd; ++it) {\n            \n\t\t\tbool m_PAHchanged = false;\n\n            //! Model parameter.\n\t\t\t/*!\n\t\t\t * If a jump process reduces the total number of 6-member rings\n\t\t\t * (excludes 5-member rings) in a PAH (in a particle) below this\n\t\t\t * threshold it is removed.\n             */\n\t\t\tconst int thresholdOxidation = model.Components(0)->ThresholdOxidation();\n\n            //! PAH removal.\n\t\t\t/*!\n\t\t\t * Allow for the removal of PAHs in particles (2 or more PAHs) when\n\t\t\t * the total number of 6-member rings (excludes 5-member rings) in\n\t\t\t * the PAH has fallen below, for example, the minimum number of\n\t\t\t * rings in a PAH for inception. Particularly relevant when\n\t\t\t * oxidation is strong.\n             */\n            if((*it)->m_pahstruct->numofC() == 5){\n                m_PAHclusterchanged = true; \n\t\t\t\tm_PAHchanged = true;\n                m_InvalidPAH = CheckInvalidPAHs(*it);\n                continue;\n\t\t\t}\t\t\t\n\n            //! Model parameter.\n\t\t\t/*!\n             * Defines when primary particles contain too many PAHs for them all \n\t\t\t * to have full access to the surrounding gas phase.  Once a primary\n\t\t\t * contains more than minPAH PAHs the growth rate of each PAH is\n\t\t\t * reduced according to the growth factor.\n             */\n\t\t\tconst double minPAH = model.Components(0)->MinPAH();\n\t\t\tdouble growthfact = 1.0;\n\n\t\t\tif (m_numPAH>=minPAH)\n\t\t\t{\n\t\t\t\tgrowthfact = model.Components(0)->GrowthFact();\n\t\t\t\t//double density = model.Components(0)->Density();\n\t\t\t\t////! PP mass (kg).\n\t\t\t\t//double m_mass = m_numcarbon*1.9945e-26 + m_numH*1.6621e-27;\n\n\t\t\t\t////! Spherical diameter (nm).\n\t\t\t\t//double diameter = pow(6.0 * m_mass / density / PI, ONE_THIRD);\n\t\t\t\t//diameter = diameter * 1.0e9;\n\t\t\t\t//growthfact = 1.950 / diameter ;\n\t\t\t\t//if (growthfact > 1.0)\n\t\t\t\t//{\n\t\t\t\t//\tgrowthfact = 1.0;\n\t\t\t\t//}\n\t\t\t}\n\n\t\t\t//! Time for one particular PAH to grow.\n\t\t\tdouble growtime = t - (*it)->lastupdated;\n\t\t\t//assert(growtime >= 0.0);\n\t\t\tdouble statweightold = statweight;\n\t\t\tint numloops = 0;\n\t\t\tbool calcrates = true;\n\t\t\tdouble ratefactor = 1.0;\n\t\t\tconst int oldNumCarbon = (*it)->m_pahstruct->numofC(); \n\t\t\tconst int oldNumH = (*it)->m_pahstruct->numofH();\n\n\t\t\tdouble updatetime;\n\n\t\t\t//if this is a particle with a single PAH, it may be weighted. \n\t\t\t//If it is weighted and IWDSA is being used, we do not want to update the PAH, but rather update a clone of \n\t\t\t//that PAH and create a new particle\n\t\t\tif (m_PAH.size() == 1 && statweight > 1.0 && ParticleModel()->Components(0)->WeightedPAHs()){ \n\t\t\t\tPartPtrVector overflowtemp; \n\n\t\t\t\twhile (growtime > 0.0 && statweight > 1.0){\n\n\t\t\t\t\tboost::shared_ptr<PAH> new_m_PAH((*it)->Clone());\n\n\t\t\t\t\tnew_m_PAH->PAH_ID = ID;\n\t\t\t\t\tID++;\n\n\t\t\t\t\tif (numloops > 0){\n\t\t\t\t\t\tcalcrates = false;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcalcrates = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tupdatetime = sys.Particles().Simulator()->updatePAH(new_m_PAH->m_pahstruct, (*it)->lastupdated, growtime, 1, 1,\n\t\t\t\t\t\t rng, growthfact*statweight, new_m_PAH->PAH_ID, calcrates, ratefactor);\n\n\t\t\t\t\t/*updatetime = sys.Particles().Simulator()->updatePAH(new_m_PAH->m_pahstruct, (*it)->lastupdated, growtime, 1, 1,\n\t\t\t\t\t\trng, growthfact*statweight, new_m_PAH->PAH_ID, true, 1.0);*/\n\n\t\t\t\t\tnew_m_PAH->lastupdated = updatetime;\n\t\t\t\t\t(*it)->lastupdated = updatetime;\n\n\t\t\t\t\tgrowtime = t - (*it)->lastupdated;\n\t\t\t\t\tnumloops++;\n\n\t\t\t\t\t//! Invalidate PAH.\n\t\t\t\t\t/*!\n\t\t\t\t\t* A PAH is made invalid by setting the number of carbons to 5. The\n\t\t\t\t\t* reason for only applying this to particles is that we would not\n\t\t\t\t\t* want to remove single PAHs in the gas-phase which fall below the\n\t\t\t\t\t* minimum number of rings for nception but are still growing.\n\t\t\t\t\t*/\n\t\t\t\t\tif (new_m_PAH->m_pahstruct->numofRings() < thresholdOxidation ){\n\t\t\t\t\t\tstatweight--;\n\t\t\t\t\t\t(*sys.Particles().At(ind)).setStatisticalWeight(statweight);\n\t\t\t\t\t\tnew_m_PAH.reset();\n\t\t\t\t\t\tID--;\n\t\t\t\t\t}\n\n\t\t\t\t\t//! See if anything changed, as this will required a call to UpdatePrimary() below.\n\t\t\t\t\t//This will also dictate if the new PAH is used to create a new particle, or if it is just destroyed\n\t\t\t\t\telse if (growtime > 0.0)\n\t\t\t\t\t//else\n\t\t\t\t\t{\n\t\t\t\t\t\t//Reduce statistical weight of the particle being updated\n\t\t\t\t\t\tstatweight--;\n\t\t\t\t\t\t(*sys.Particles().At(ind)).setStatisticalWeight(statweight);\n\n\t\t\t\t\t\tParticle *sp = NULL;\n\t\t\t\t\t\tsp = model.CreateParticle(updatetime, 0);\n\t\t\t\t\t\t//Creating the first type of primary particle. Not tested. gl413\n\t\t\t\t\t\tAggModels::PAHPrimary *pri =\n\t\t\t\t\t\t\tdynamic_cast<AggModels::PAHPrimary*>((*sp).Primary());\n\t\t\t\t\t\tpri->m_PAH.clear();\n\t\t\t\t\t\tpri->m_PAH.push_back(new_m_PAH);\n\t\t\t\t\t\tsp->SetTime(updatetime);\n\t\t\t\t\t\t//Update the primary and the cache\n\t\t\t\t\t\tpri->UpdatePrimary();\n\t\t\t\t\t\tsp->UpdateCache();\n\n\t\t\t\t\t\toverflowtemp.push_back(sp);\n\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tassert(growtime == 0);\n\t\t\t\t\t\tnew_m_PAH.reset();\n\t\t\t\t\t\tID--;\n\t\t\t\t\t}\n\n\t\t\t\t\tratefactor = statweight / statweightold;\n\t\t\t\t}\n\t\t\t\t//Final update after statistical weight reaches 1\n\t\t\t\t//Now update the PAH one last time\n\t\t\t\tif (growtime > 0.0){\n\n\t\t\t\t\tupdatetime = sys.Particles().Simulator()->updatePAH((*it)->m_pahstruct, (*it)->lastupdated, growtime, 1, 0,\n\t\t\t\t\t\trng, growthfact, (*it)->PAH_ID, true, 1.0);\n\n\t\t\t\t\t(*it)->lastupdated = t;\n\n\t\t\t\t\t//! Invalidate PAH.\n\t\t\t\t\t/*!\n\t\t\t\t\t* A PAH is made invalid by setting the number of carbons to 5. The\n\t\t\t\t\t* reason for only applying this to particles is that we would not\n\t\t\t\t\t* want to remove single PAHs in the gas-phase which fall below the\n\t\t\t\t\t* minimum number of rings for inception but are still growing.\n\t\t\t\t\t*/\n\t\t\t\t\tif ((*it)->m_pahstruct->numofRings() < thresholdOxidation){\n\t\t\t\t\t\t(*it)->m_pahstruct->setnumofC(5);\n\t\t\t\t\t}\n\n\n\t\t\t\t\t//! See if anything changed, as this will required a call to UpdatePrimary() below.\n\t\t\t\t\tif (oldNumCarbon != (*it)->m_pahstruct->numofC() || oldNumH != (*it)->m_pahstruct->numofH())\n\t\t\t\t\t{\n\t\t\t\t\t\tm_PAHclusterchanged = true;\n\t\t\t\t\t\tm_PAHchanged = true;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t//Now, update all created particles that were added to overflowtemp\n\t\t\t\tPartPtrVector::iterator it1;\n\t\t\t\tfor (it1 = overflowtemp.begin(); it1 != overflowtemp.end(); ++it1){\n\t\t\t\t\tAggModels::PAHPrimary *pri =\n\t\t\t\t\t\tdynamic_cast<AggModels::PAHPrimary*>((*(*it1)).Primary());\n\t\t\t\t\t//This new particle must also be updated to time t\n\t\t\t\t\tconst int oldNumCarbon1 = pri->m_PAH[0]->m_pahstruct->numofC();\n\t\t\t\t\tconst int oldNumH1 = pri->m_PAH[0]->m_pahstruct->numofH();\n\t\t\t\t\tpri->UpdatePAHs(t, t - (*it1)->LastUpdateTime(), model, sys, 1, -1, rng, overflow);\n\t\t\t\t\t(*it1)->SetTime(t);\n\n\t\t\t\t\t//Update the primary and the cache if the PAH structure has changed.\n\t\t\t\t\t//Place the particle (which is a single PAH) in the overflow vector if it is still a valid PAH\n\t\t\t\t\tif (pri->GetPAHVector()[0]->m_pahstruct->numofC() != oldNumCarbon1 &&\n\t\t\t\t\t\tpri->GetPAHVector()[0]->m_pahstruct->numofH() != oldNumH1){\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (pri->m_PAH[0]->m_pahstruct->numofRings() >= thresholdOxidation){\n\t\t\t\t\t\t\tpri->UpdatePrimary();\n\t\t\t\t\t\t\t(*it1)->UpdateCache();\n\t\t\t\t\t\t\toverflow.push_back(*it1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tdelete *it1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{ //If nothing changed, but it is still a valid PAH, place it in overflow vector\n\t\t\t\t\t\toverflow.push_back(*it1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse{\n\t\t\t\tupdatetime = sys.Particles().Simulator()->updatePAH((*it)->m_pahstruct, (*it)->lastupdated, growtime, 1, 0,\n\t\t\t\t\trng, growthfact, (*it)->PAH_ID, true, 1.0);\n\n\t\t\t\t(*it)->lastupdated = t;\n\n\t\t\t\t//! Invalidate PAH.\n\t\t\t\t/*!\n\t\t\t\t* A PAH is made invalid by setting the number of carbons to 5. The\n\t\t\t\t* reason for only applying this to particles is that we would not\n\t\t\t\t* want to remove single PAHs in the gas-phase which fall below the\n\t\t\t\t* minimum number of rings for inception but are still growing.\n\t\t\t\t*/\n\t\t\t\tif ((*it)->m_pahstruct->numofRings() < thresholdOxidation && m_numPAH >= minPAH && ind != -1){\n\t\t\t\t\t(*it)->m_pahstruct->setnumofC(5);\n\t\t\t\t}\n\n\n\t\t\t\t//! See if anything changed, as this will required a call to UpdatePrimary() below.\n\t\t\t\tif ((oldNumCarbon != (*it)->m_pahstruct->numofC() || oldNumH != (*it)->m_pahstruct->numofH()) && ind != -1)\n\t\t\t\t{\n\t\t\t\t\tm_PAHclusterchanged = true;\n\t\t\t\t\tm_PAHchanged = true;\n\t\t\t\t}\n\n\t\t\t}\n\n\n\t\t\t/*!\n             * The second condition ensures that the m_InvalidPAH is modified in the correct way\n\t\t\t * consider 2 PAH, the first is invalid, the other is valid. If not using the\n             * second condition, the m_InvalidPAH will be false enventually, but it should be true.\n\t\t\t */ \n\t\t\tif (m_PAHchanged && !m_InvalidPAH && ind != -1)\n\t\t\t\tm_InvalidPAH = CheckInvalidPAHs(*it);\n\n        } //end of loop for PAHs in a primary\n        if (m_InvalidPAH)\n        {\n            RemoveInvalidPAHs();\n        }\n\n        //sys.Particles().Add();\n        //this->ParticleModel()->Mode();\n        /*!\n         * Calculate derived quantities such as collision diameter and surface\n         * area by iterating through all the PAHs.  This call is rather expensive.\n         */\n        if(m_PAHclusterchanged)\n            UpdatePrimary();\n            // if (m_InceptedPAH!=0) {\n            //        sys.Particles().SetNumOfInceptedPAH(-1);\n            //        //sys.Particles().NumOfInceptedPAH();\n            // }\n            //else if (m_InceptedPAH == 0 && InceptedPAH()==1){\n            //        sys.Particles().SetNumOfInceptedPAH(1);\n            //        //sys.Particles().NumOfInceptedPAH();\n            //}\n        //! otherwise there is no need to update.\n    }\n}\n\n//! Overload function. Used if primary coordinates are tracked, then particle free surface area can be used to \n// calculate a free_surf_factor to describe surface growth.\n/*!\n* The actual interval over which the update is carried out on a PAH is from\n* lastupdated to t.\n*\n* @param[in]        t        Time up to which to update.\n* @param[in]        model    Particle model defining interpretation of particle data.\n* @param[in]        sys      Cell containing particle and providing gas phase.\n* @param[in]        fs       Free surface area of the particle.\n* @param[in,out]    rng      Random number generator.\n*\n*/\nvoid PAHPrimary::UpdatePAHs(const double t, const double dt, const Sweep::ParticleModel &model, Cell &sys, int statweight,\n\tint ind, rng_type &rng, PartPtrVector &overflow, const double fs)\n{\n\t// Either the primary has two children or it is a leaf of the\n\t// tree\n\tif (m_leftchild != NULL)\n\t{\n\t\t// Recurse down to the leaves\n\t\tm_leftchild->UpdatePAHs(t, dt, model, sys, statweight, ind, rng, overflow, fs);\n\t\tm_rightchild->UpdatePAHs(t, dt, model, sys, statweight, ind, rng, overflow, fs);\n\t}\n\telse\n\t{\n\t\t// There are PAHs in this primary so update them, if needed\n\t\t// Flag to show if any PAH has been changed\n\t\t// this flag store the condition of this cluster(primary particle)\n\t\tbool m_PAHclusterchanged = false;\n\t\t// this flag store the condition of a particular PAH within this cluster\n\t\tbool m_InvalidPAH = false;\n\t\t// check whether this updated primary particle is a inceptedPAH, used later to track the num of InceptedPAH in the ensemble\n\t\t//const int m_InceptedPAH = InceptedPAH();\n\n\t\tdouble m_vol_old = m_vol; //volume before PAH growth; used for adjust primary after surface growth\n\n\t\tdouble free_surf_factor = m_free_surf / fs; //if the free surface area of a primary particle is too small, there are less chance for PAHs in it to grow\n\n\t\t//assert(free_surf_factor <= 1.0); //test by hdy\n\n\t\t//! Loop over each PAH in this primary.\n\t\tconst std::vector<boost::shared_ptr<PAH> >::iterator itEnd = m_PAH.end();\n\t\tfor (std::vector<boost::shared_ptr<PAH> >::iterator it = m_PAH.begin(); it != itEnd; ++it) {\n\n\t\t\tbool m_PAHchanged = false;\n\n\t\t\t//! Model parameter.\n\t\t\t/*!\n\t\t\t* If a jump process reduces the total number of 6-member rings\n\t\t\t* (excludes 5-member rings) in a PAH (in a particle) below this\n\t\t\t* threshold it is removed.\n\t\t\t*/\n\t\t\tconst int thresholdOxidation = model.Components(0)->ThresholdOxidation();\n\n\t\t\t//! PAH removal.\n\t\t\t/*!\n\t\t\t* Allow for the removal of PAHs in particles (2 or more PAHs) when\n\t\t\t* the total number of 6-member rings (excludes 5-member rings) in\n\t\t\t* the PAH has fallen below, for example, the minimum number of\n\t\t\t* rings in a PAH for inception. Particularly relevant when\n\t\t\t* oxidation is strong.\n\t\t\t*/\n\t\t\tif ((*it)->m_pahstruct->numofC() == 5){\n\t\t\t\tm_PAHclusterchanged = true;\n\t\t\t\tm_PAHchanged = true;\n\t\t\t\tm_InvalidPAH = CheckInvalidPAHs(*it);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t//! Model parameter.\n\t\t\t/*!\n\t\t\t* Defines when primary particles contain too many PAHs for them all\n\t\t\t* to have full access to the surrounding gas phase.  Once a primary\n\t\t\t* contains more than minPAH PAHs the growth rate of each PAH is\n\t\t\t* reduced according to the growth factor.\n\t\t\t*/\n\t\t\tconst double minPAH = model.Components(0)->MinPAH();\n\t\t\tdouble growthfact = 1.0;\n\t\t\tgrowthfact = growthfact * free_surf_factor; \n\n\t\t\tif (m_numPAH >= minPAH)\n\t\t\t{\n\t\t\t\tgrowthfact = model.Components(0)->GrowthFact();\n\t\t\t\tgrowthfact = growthfact * free_surf_factor; \n\t\t\t\t//double density = model.Components(0)->Density();\n\t\t\t\t////! PP mass (kg).\n\t\t\t\t//double m_mass = m_numcarbon*1.9945e-26 + m_numH*1.6621e-27;\n\n\t\t\t\t////! Spherical diameter (nm).\n\t\t\t\t//double diameter = pow(6.0 * m_mass / density / PI, ONE_THIRD);\n\t\t\t\t//diameter = diameter * 1.0e9;\n\t\t\t\t//growthfact = 1.950 / diameter ;\n\t\t\t\t//if (growthfact > 1.0)\n\t\t\t\t//{\n\t\t\t\t//\tgrowthfact = 1.0;\n\t\t\t\t//}\n\t\t\t}\n\n\t\t\t//! Time for one particular PAH to grow.\n\t\t\tdouble growtime = t - (*it)->lastupdated;\n\t\t\tassert(growtime >= 0.0);\n\t\t\tdouble statweightold = statweight;\n\t\t\tint numloops = 0;\n\t\t\tbool calcrates = true;\n\t\t\tdouble ratefactor = 1.0;\n\t\t\tconst int oldNumCarbon = (*it)->m_pahstruct->numofC();\n\t\t\tconst int oldNumH = (*it)->m_pahstruct->numofH();\n\n\t\t\tdouble updatetime;\n\n\t\t\t//if this is a particle with a single PAH, it may be weighted. \n\t\t\t//If it is weighted and IWDSA is being used, we do not want to update the PAH, but rather update a clone of \n\t\t\t//that PAH and create a new particle\n\t\t\tif (m_PAH.size() == 1 && statweight > 1.0 && ParticleModel()->Components(0)->WeightedPAHs()){\n\t\t\t\tPartPtrVector overflowtemp; \n\n\t\t\t\twhile (growtime > 0.0 && statweight > 1.0){\n\n\t\t\t\t\tboost::shared_ptr<PAH> new_m_PAH((*it)->Clone());\n\n\t\t\t\t\tnew_m_PAH->PAH_ID = ID;\n\t\t\t\t\tID++;\n\n\t\t\t\t\tif (numloops > 0){\n\t\t\t\t\t\tcalcrates = false;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcalcrates = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tupdatetime = sys.Particles().Simulator()->updatePAH(new_m_PAH->m_pahstruct, (*it)->lastupdated, growtime, 1, 1,\n\t\t\t\t\t\trng, growthfact*statweight, new_m_PAH->PAH_ID, calcrates, ratefactor);\n\n\t\t\t\t\t/*updatetime = sys.Particles().Simulator()->updatePAH(new_m_PAH->m_pahstruct, (*it)->lastupdated, growtime, 1, 1,\n\t\t\t\t\trng, growthfact*statweight, new_m_PAH->PAH_ID, true, 1.0);*/\n\n\t\t\t\t\tnew_m_PAH->lastupdated = updatetime;\n\t\t\t\t\t(*it)->lastupdated = updatetime;\n\n\t\t\t\t\tgrowtime = t - (*it)->lastupdated;\n\t\t\t\t\tnumloops++;\n\n\t\t\t\t\t//! Invalidate PAH.\n\t\t\t\t\t/*!\n\t\t\t\t\t* A PAH is made invalid by setting the number of carbons to 5. The\n\t\t\t\t\t* reason for only applying this to particles is that we would not\n\t\t\t\t\t* want to remove single PAHs in the gas-phase which fall below the\n\t\t\t\t\t* minimum number of rings for nception but are still growing.\n\t\t\t\t\t*/\n\t\t\t\t\tif (new_m_PAH->m_pahstruct->numofRings() < thresholdOxidation){\n\t\t\t\t\t\tstatweight--;\n\t\t\t\t\t\t(*sys.Particles().At(ind)).setStatisticalWeight(statweight);\n\t\t\t\t\t\tnew_m_PAH.reset();\n\t\t\t\t\t\tID--;\n\t\t\t\t\t}\n\n\t\t\t\t\t//! See if anything changed, as this will required a call to UpdatePrimary() below.\n\t\t\t\t\t//This will also dictate if the new PAH is used to create a new particle, or if it is just destroyed\n\t\t\t\t\telse if (growtime > 0.0)\n\t\t\t\t\t\t//else\n\t\t\t\t\t{\n\t\t\t\t\t\t//Reduce statistical weight of the particle being updated\n\t\t\t\t\t\tstatweight--;\n\t\t\t\t\t\t(*sys.Particles().At(ind)).setStatisticalWeight(statweight);\n\n\t\t\t\t\t\tParticle *sp = NULL;\n\t\t\t\t\t\tsp = model.CreateParticle(updatetime, 0);\n\t\t\t\t\t\t//Creating the first type of primary particle. Not tested. gl413\n\t\t\t\t\t\tAggModels::PAHPrimary *pri =\n\t\t\t\t\t\t\tdynamic_cast<AggModels::PAHPrimary*>((*sp).Primary());\n\t\t\t\t\t\tpri->m_PAH.clear();\n\t\t\t\t\t\tpri->m_PAH.push_back(new_m_PAH);\n\t\t\t\t\t\tsp->SetTime(updatetime);\n\t\t\t\t\t\t//Update the primary and the cache\n\t\t\t\t\t\tpri->UpdatePrimary();\n\t\t\t\t\t\tsp->UpdateCache();\n\n\t\t\t\t\t\toverflowtemp.push_back(sp);\n\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tassert(growtime == 0);\n\t\t\t\t\t\tnew_m_PAH.reset();\n\t\t\t\t\t\tID--;\n\t\t\t\t\t}\n\n\t\t\t\t\tratefactor = statweight / statweightold;\n\t\t\t\t}\n\t\t\t\t//Final update after statistical weight reaches 1\n\t\t\t\t//Now update the PAH one last time\n\t\t\t\tif (growtime > 0.0){\n\n\t\t\t\t\tupdatetime = sys.Particles().Simulator()->updatePAH((*it)->m_pahstruct, (*it)->lastupdated, growtime, 1, 0,\n\t\t\t\t\t\trng, growthfact, (*it)->PAH_ID, true, 1.0);\n\n\t\t\t\t\t(*it)->lastupdated = t;\n\n\t\t\t\t\t//! Invalidate PAH.\n\t\t\t\t\t/*!\n\t\t\t\t\t* A PAH is made invalid by setting the number of carbons to 5. The\n\t\t\t\t\t* reason for only applying this to particles is that we would not\n\t\t\t\t\t* want to remove single PAHs in the gas-phase which fall below the\n\t\t\t\t\t* minimum number of rings for inception but are still growing.\n\t\t\t\t\t*/\n\t\t\t\t\tif ((*it)->m_pahstruct->numofRings() < thresholdOxidation){\n\t\t\t\t\t\t(*it)->m_pahstruct->setnumofC(5);\n\t\t\t\t\t}\n\n\n\t\t\t\t\t//! See if anything changed, as this will required a call to UpdatePrimary() below.\n\t\t\t\t\tif (oldNumCarbon != (*it)->m_pahstruct->numofC() || oldNumH != (*it)->m_pahstruct->numofH())\n\t\t\t\t\t{\n\t\t\t\t\t\tm_PAHclusterchanged = true;\n\t\t\t\t\t\tm_PAHchanged = true;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t//Now, update all created particles that were added to overflowtemp\n\t\t\t\tPartPtrVector::iterator it1;\n\t\t\t\tfor (it1 = overflowtemp.begin(); it1 != overflowtemp.end(); ++it1){\n\t\t\t\t\tAggModels::PAHPrimary *pri =\n\t\t\t\t\t\tdynamic_cast<AggModels::PAHPrimary*>((*(*it1)).Primary());\n\t\t\t\t\t//This new particle must also be updated to time t\n\t\t\t\t\tpri->UpdatePAHs(t, t - (*it1)->LastUpdateTime(), model, sys, 1, -1, rng, overflow, fs);\n\t\t\t\t\t(*it1)->SetTime(t);\n\n\t\t\t\t\t//Update the primary and the cache\n\t\t\t\t\tpri->UpdatePrimary();\n\t\t\t\t\t(*it1)->UpdateCache();\n\n\t\t\t\t\t//Check if the PAH is still valid after being updated\n\t\t\t\t\tif (pri->m_PAH[0]->m_pahstruct->numofRings() >= thresholdOxidation){\n\t\t\t\t\t\toverflow.push_back(*it1);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdelete *it1;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse{\n\t\t\t\tupdatetime = sys.Particles().Simulator()->updatePAH((*it)->m_pahstruct, (*it)->lastupdated, growtime, 1, 0,\n\t\t\t\t\trng, growthfact, (*it)->PAH_ID, true, 1.0);\n\n\t\t\t\t(*it)->lastupdated = t;\n\n\t\t\t\t//! Invalidate PAH.\n\t\t\t\t/*!\n\t\t\t\t* A PAH is made invalid by setting the number of carbons to 5. The\n\t\t\t\t* reason for only applying this to particles is that we would not\n\t\t\t\t* want to remove single PAHs in the gas-phase which fall below the\n\t\t\t\t* minimum number of rings for inception but are still growing.\n\t\t\t\t*/\n\t\t\t\tif ((*it)->m_pahstruct->numofRings() < thresholdOxidation && m_numPAH >= minPAH && ind != -1){\n\t\t\t\t\t(*it)->m_pahstruct->setnumofC(5);\n\t\t\t\t}\n\n\n\t\t\t\t//! See if anything changed, as this will required a call to UpdatePrimary() below.\n\t\t\t\tif (oldNumCarbon != (*it)->m_pahstruct->numofC() || oldNumH != (*it)->m_pahstruct->numofH() && ind != -1)\n\t\t\t\t{\n\t\t\t\t\tm_PAHclusterchanged = true;\n\t\t\t\t\tm_PAHchanged = true;\n\t\t\t\t}\n\n\t\t\t}\n\n\n\t\t\t/*!\n\t\t\t* The second condition ensures that the m_InvalidPAH is modified in the correct way\n\t\t\t* consider 2 PAH, the first is invalid, the other is valid. If not using the\n\t\t\t* second condition, the m_InvalidPAH will be false enventually, but it should be true.\n\t\t\t*/\n\t\t\tif (m_PAHchanged && !m_InvalidPAH && ind != -1)\n\t\t\t\tm_InvalidPAH = CheckInvalidPAHs(*it);\n\n\t\t} //end of loop for PAHs in a primary\n\t\tif (m_InvalidPAH)\n\t\t{\n\t\t\tRemoveInvalidPAHs();\n\t\t}\n\n\t\t//sys.Particles().Add();\n\t\t//this->ParticleModel()->Mode();\n\t\t/*!\n\t\t* Calculate derived quantities such as collision diameter and surface\n\t\t* area by iterating through all the PAHs.  This call is rather expensive.\n\t\t*/\n\t\tif (m_PAHclusterchanged) {\n\t\t\tUpdatePrimary();\n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\t\t\tAdjust(m_vol_old);\n\t\t\t// if (m_InceptedPAH!=0) {\n\t\t\t//        sys.Particles().SetNumOfInceptedPAH(-1);\n\t\t\t//        //sys.Particles().NumOfInceptedPAH();\n\t\t\t// }\n\t\t\t//else if (m_InceptedPAH == 0 && InceptedPAH()==1){\n\t\t\t//        sys.Particles().SetNumOfInceptedPAH(1);\n\t\t\t//        //sys.Particles().NumOfInceptedPAH();\n\t\t\t//}\n\t\t}\n\t\t//! otherwise there is no need to update.\n\t}\n}\n\n\n// currently, only A1,A2 and A4 can be specified as InceptedPAH due to the underlying KMC code\nbool PAHPrimary::CheckInvalidPAHs(const boost::shared_ptr<PAH> & it) const\n{\n\tstd::vector<ParticleModel::PostProcessStartingStr> str_list = this->ParticleModel()->InceptedPAH();\n\tfor (std::vector<int>::size_type ii = 0; ii!=str_list.size(); ii++){\n\t\tParticleModel::PostProcessStartingStr str = str_list[ii];\n\t\tint m_control;\n\t\tstd::ifstream src(\"InceptedPAH.inx\");\n\t\tstd:string token;\n\t\tswitch (str){\n\t\tcase ParticleModel::A1:\n\t\t\tm_control=Sweep::KMC_ARS::BENZENE_C;\n\t\t\tbreak;\n\t\tcase ParticleModel::A1CH3:\n\t\t\tm_control=Sweep::KMC_ARS::TOLUENE_C;\n\t\t\tbreak;\n\t\tcase ParticleModel::A2:\n\t\t\tm_control=10;\n\t\t\tbreak;\n\t\tcase ParticleModel::A4:\n\t\t\tm_control=Sweep::KMC_ARS::PYRENE_C;\n\t\t\tbreak;\n\t\tcase ParticleModel::A4CH3:\n\t\t\tm_control=Sweep::KMC_ARS::METHYLPYRENE_C;\n\t\t\tbreak;\n\t\tcase ParticleModel::R5A3:\n\t\t\tm_control=Sweep::KMC_ARS::MPHENANTHRENER_C;\n\t\t\tbreak;\n\t\tcase ParticleModel::A5:\n\t\t\tm_control=Sweep::KMC_ARS::BENZOPYRENE_C;\n\t\t\tbreak;\n\t\tcase ParticleModel::A7:\n\t\t\tm_control=Sweep::KMC_ARS::CORONENE_C;\n\t\t\tbreak;\n\t\tcase ParticleModel::FromFile:\n\t\t\tif (src.is_open()){\n\t\t\t\t//Read the first line and split it with spaces\n\t\t\t\tstd::getline(src,token,' ');\n\t\t\t}\n\t\t\tsrc.close();\n\t\t\tm_control=std::stoi(token);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"no information about the incepted PAH is available (Sweep::PAHPrimary::CheckInvalidPAHs())\");\n\t\t}\n\t\t// if the PAH in the cluster is as the same size as the incepted PAH, it will be released but the current implementation is directly removed which causes mass loss, for a fully coupled model this part should be redesigned.\n\t\t//return (it->m_pahstruct->numofC() < m_control || (it->m_pahstruct->numofC() <= m_control && NumPAH() != 1));\n\t\treturn (it->m_pahstruct->numofC() < 6 || (it->m_pahstruct->numofC() <= 6 && NumPAH() != 1)); //Forced benzene as the smaller available PAH.\n\t}\n}\n\n//struct compare_class\n//{\n//    bool operator () (const boost::shared_ptr<PAH>  & it) const\n//    {\n//        if (m_pyreneInception) \n//        {\n//            if (it->Structure()->numofC() < Sweep::KMC_ARS::PYRENE_C)\n//                return true;\n//        }\n//        else \n//        {\n//            if (it->Structure()->numofC() < Sweep::KMC_ARS::BENZENE_C)\n//                return true;\n//        }\n//        return false;\n//    }\n//};\n\nvoid PAHPrimary::RemoveInvalidPAHs()\n{\n    // if the num of PAH in this primary particle is smaller than 2 after removing the InvalidPAHs,\n    // FakeRounding() will return true and it will be merged with other part of the aggregate.\n    // TODO: thinking suitable solution for moving the InvalidPAH back to gasphase when coupling with the gasphase chemistry.\n    // current implementation is only suitable for post-pocessing due to mass loss.\n    //remove_if(m_PAH.begin(),m_PAH.end(),compare_class());\n    std::vector<boost::shared_ptr<PAH> >::iterator NewEnd = remove_if(m_PAH.begin(),m_PAH.end(),boost::bind(&PAHPrimary::CheckInvalidPAHs, this,_1));\n    m_PAH.resize(NewEnd-m_PAH.begin());\n}\n\n// Find Xmer (monomer, dimer or trimer) and record its mass which will be used to create mass spectra\n// however, this function currently is only implenmented in PAHPrimary class\n// this means it is limited to PAH-PP model. \nvoid PAHPrimary::FindXmer(std::vector<double> &out, int m_xmer) const\n{\n    if (m_leftchild!=NULL)\n        m_leftchild->FindXmer(out, m_xmer);\n\n\t// dimer: a partilce with one primary containing 2 PAHs\n\tif (this->NumPAH()==m_xmer)\n\t\tout.push_back(this->MassforXmer());\n}\n\n// Find particular primary particle with target number of PAHs ( this can be a range, details please see the implementation) \n// and record num of C and H for each PAH, also push_back a divider (0,0,ID) at end to distinguish \nvoid PAHPrimary::FindXmer(std::vector<std::vector<double> > &out, int target_num_PAH) const\n{\n\tif (m_leftchild != NULL)\n\t\tm_leftchild->FindXmer(out,target_num_PAH);\n\tif (m_rightchild != NULL)\n\t\tm_rightchild->FindXmer(out,target_num_PAH);\n    if (target_num_PAH-10<=0) std::cout<<\"Warning: (target_num_PAH-10) return 0 or negative value in PAHPrimary::FindXmer()\"<<std::endl;\n\tif (m_PAH.size() <= size_t(target_num_PAH+10) && m_PAH.size() >= size_t(target_num_PAH-10))\n\t\tmass_PAH(out);\n}\n\n//calculate the mass of Xmer including C and H\ndouble PAHPrimary::MassforXmer() const\n{ \n\tint sum = 0;\n\tfor (size_t i = 0; i != m_PAH.size(); ++i)\n\t{\n\t\tsum+=m_PAH[i]->m_pahstruct->numofH();\n\t    sum+=12 * m_PAH[i]->m_pahstruct->numofC();\n\t}\n\treturn sum;\t\n}\n\n/*\n * Checks if PAH selected is an inception PAH.\n * @param[in]        k                 Type of PAH checked.\n */\nint PAHPrimary::InceptedPAH(const int k) const\n{\n    // m_parent == NULL is to check whether this primary particle is part of an aggregate.\n    if (m_parent == NULL && Numprimary() == 1 && NumPAH() == 1){\n        //currently only Num of C and H is used to identify the Pyrene, Naphthalene and benzene\n        std::vector<ParticleModel::PostProcessStartingStr> str_list = ParticleModel()->InceptedPAH();\n\t\t//std::vector<ParticleModel::PostProcessStartingStr>::iterator it;\n\t\tParticleModel::PostProcessStartingStr str = str_list[k];\n\t\tstd::ifstream src(\"InceptedPAH.inx\");\n\t\tstd:string token;\n\t\tint carbon_number, hydrogen_number;\n\t\t//ParticleModel::PostProcessStartingStr str = (*it);\n\t\tswitch (str){\n\t\tcase ParticleModel::A1:\n\t\t\tif (NumCarbon() == BENZENE_C && NumHydrogen() == BENZENE_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::A1CH3:\n\t\t\tif (NumCarbon() == TOLUENE_C && NumHydrogen() == TOLUENE_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::A2:\n\t\t\tif (NumCarbon() == NAPHTHALENE_C && NumHydrogen() == NAPHTHALENE_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::A4:\n\t\t\tif (NumCarbon() == PYRENE_C && NumHydrogen() == PYRENE_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::A4CH3:\n\t\t\tif (NumCarbon() == METHYLPYRENE_C && NumHydrogen() == METHYLPYRENE_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::R5A3:\n\t\t\tif (NumCarbon() == MPHENANTHRENER_C && NumHydrogen() == MPHENANTHRENER_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::A5:\n\t\t\tif (NumCarbon() == BENZOPYRENE_C && NumHydrogen() == BENZOPYRENE_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::A7:\n\t\t\tif (NumCarbon() == CORONENE_C && NumHydrogen() == CORONENE_H)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tcase ParticleModel::FromFile:\n\t\t\tif (src.is_open()){\n\t\t\t\t//Read the first line and split it with spaces\n\t\t\t\tstd::getline (src,token,' ');\n\t\t\t\tcarbon_number = std::stoi(token);\n\t\t\t\tstd::getline (src,token,' ');\n\t\t\t\thydrogen_number = std::stoi(token);\n\t\t\t}\n\t\t\tsrc.close();\n\t\t\tif (NumCarbon() == carbon_number && NumHydrogen() == hydrogen_number)\n\t\t\t\treturn 1;\n\t\t\telse return 0;\n\t\t\tbreak;\n\t\tdefault: return 0;\n\t\t}\n\t}\n\telse return 0;\n}\n\n// dump information of this Xmer to a vector<vector<double> > \n void PAHPrimary::mass_PAH(std::vector<std::vector<double> > &out) const\n {\n    std::vector<double> temp;\n    std::vector<double> divider(2,0);\n    for (size_t i = 0; i != m_PAH.size(); ++i)\n    {\n        temp.push_back(m_PAH[i]->m_pahstruct->numofC());\n        temp.push_back(m_PAH[i]->m_pahstruct->numofH());\n        m_PAH[i]->saveDOTperLoop((int)ID,(int)i);\n        out.push_back(temp);\n        temp.clear();\n    }\n    divider.push_back(ID);\n    out.push_back(divider);\n    ID++;\n}\n\n//! SaveXYZ files for every PAH in a primary particle.\nvoid PAHPrimary::saveXYZ(const std::string &filename, bool optimise) const{\n\tfor (size_t i = 0; i != m_PAH.size(); ++i)\n\t{\n\t\tstd::string filename_pah = filename;\n\t\tfilename_pah.append(\"_\");\n\t\tfilename_pah.append(std::to_string(i));\n\t\tm_PAH[i]->saveXYZ(filename_pah, optimise);\n\t}\n}\n\n // only for num of Primary == 1, carbon only\ndouble PAHPrimary::ReducedMass() const\n{\n    double val=0;\n    for (size_t i = 0; i != m_PAH.size(); ++i)\n    {\n        int num_C=0;\n        num_C=m_PAH[i]->m_pahstruct->numofC();\n        val+=1/num_C;\n    }\n    if (val==0) return 1;\n    else \n    return 1/val;\n}\nbool IsSticked(double val)\n{\n    return val<2*(32*12+14);\n}\nbool NotValid(double val)\n{\n    return val==0;\n}\n\nvoid PAHPrimary::Fragtest(std::vector<double> &out, const int k, std::string mode, double threshold) const\n{\n    //test8 start\n    //int thres=0;\n    //if (mode ==\"MIN\"||mode==\"MAX\")\n    //    thres = threshold/2;\n    //else if (mode ==\"COMBINED\")\n    //    thres = threshold/4;\n    //else if (mode ==\"REDUCED\")\n    //    thres = threshold;\n    //if (m_leftchild!=NULL)\n    //m_leftchild->Fragtest(out, k, mode, threshold);\n\n    //std::vector<double> temp;\n\n    ////if (k==0 && ReducedMass()<=thres) {\n    ////    for (size_t i = 0; i != m_PAH.size(); i+=1)\n    ////        {\n    ////            int num_C=0;\n    ////            int num_H=0;\n    ////            int val=0;\n    ////            int val1=0;\n    ////            num_C=m_PAH[i]->m_pahstruct->numofC();\n    ////            num_H=m_PAH[i]->m_pahstruct->numofH();\n    ////            // PAH mass (u)\n    ////            val = 12*num_C + num_H;\n    ////            temp.push_back(val);\n    ////        }\n    ////}\n    ////else if (k==1 && ReducedMass()>thres) {\n    \n    //if (k==1 && NumPAH()<=10) {\n    //    for (size_t i = 0; i != m_PAH.size(); i+=2)\n    //    {\n    //        if (i+1>=m_PAH.size())\n    //            break;\n    //        int num_C=0;\n    //        int num_H=0;\n    //        int val=0;\n    //        int val1=0;\n    //        num_C=m_PAH[i]->m_pahstruct->numofC();\n    //        num_H=m_PAH[i]->m_pahstruct->numofH();\n    //        // PAH mass (u)\n    //        val = 12*num_C + num_H;\n    //        num_C=m_PAH[i+1]->m_pahstruct->numofC();\n    //        num_H=m_PAH[i+1]->m_pahstruct->numofH();\n    //        // PAH mass (u)\n    //        val1 = 12*num_C + num_H;\n    //        val+=val1;\n    //        temp.push_back(val);\n    //    }\n    //}\n    //if (temp.size()!=0) {\n    //    std::vector<double>::iterator NewEnd = remove_if(temp.begin(),temp.end(),IsSticked);\n    //    temp.resize(NewEnd-temp.begin());\n    //    out.insert(out.end(),temp.begin(),temp.end());\n    //}\n    //test8 end\n    //test9 start\n    std::vector<double> temp;\n    if (k==1 && NumPAH()<=5) {\n        mass_PAH(temp);\n    }\n    if (temp.size()!=0)\n    {\n        for (size_t i = 0; i != static_cast<size_t>(NumPAH()); ++i){\n            //c32h14\n            if (temp[i]<=398)\n                temp[i]=0;\n        }\n        std::vector<double>::iterator NewEnd = remove_if(temp.begin(),temp.end(),NotValid);\n        temp.resize(NewEnd-temp.begin());\n        for (size_t i = 0; i !=temp.size(); i+=2) {\n            if (i+1>=temp.size()) {\n                temp[i]=0;\n                break;\n            }\n            temp[i]=temp[i]+temp[i+1];\n            temp[i+1]=0;\n        }\n        NewEnd = remove_if(temp.begin(),temp.end(),NotValid);\n        temp.resize(NewEnd-temp.begin());\n        out.insert(out.end(),temp.begin(),temp.end());\n    }\n    //test9 end\n\n}\n\n/*!\n * @brief Create contents pertaining to PAH specific information to be written to a csv file. \n *\n * @param[in,out]    out                   Vector (different PAHs) of vectors (different pieces of information about the PAH).\n * @param[in]        index                 Index assigned to particle.\n * @param[in]        density               Density of soot.\n * @param[in,out]    pahUniqueAddresses    Keep a record of which PAHs have been stored in \"out\" to avoid storing the same memory location twice.\n * @param[in,out]    Mapping               Map of PAH memory locations to PAH in \"out\".\n * @param[in]        timeStep              Index assigned to time step.\n */ \nvoid PAHPrimary::OutputPAHPSL(std::vector<std::vector<double> > &out, const int index, const double density, std::set<void*> &pahUniqueAddresses, std::vector<std::string> &Mapping, const double timeStep) const\n{\n    if (m_leftchild!=NULL)\n        m_leftchild->OutputPAHPSL(out, index, density, pahUniqueAddresses, Mapping, timeStep);\n    if (m_rightchild!=NULL) m_rightchild->OutputPAHPSL(out, index, density, pahUniqueAddresses, Mapping, timeStep);\n\n\tstd::stringstream memoryLocation;\n\n    std::vector<double> temp;\n\n    for (size_t i = 0; i != m_PAH.size(); ++i)\n    {\n        //! Reduce the number of redundant entries.\n        /*!\n\t\t * First retrieve the memory location of this PAH. If the memory\n\t\t * location is not in the list of unique memory locations, store the\n\t\t * information for this PAH in \"out\". Otherwise, we can simply\n\t\t * increment the frequency of the PAH in \"out\" which shares the same\n\t\t * memory location as this PAH.\n\t\t */\n        void *ptr = m_PAH[i].get();\n        if(pahUniqueAddresses.find(m_PAH[i].get()) == pahUniqueAddresses.end()) {\n            \n            //! Initialization of variables.\n\t\t\tint num_C=0;\n\t\t\tint num_H=0;\n\t\t\tint num_CH3=0;\n\t\t\tdouble val=0.0;\n\t\t\tdouble m_mass=0.0;\n\t\t\tdouble PAHCollDiameter=0.0;\n\t\t\tdouble diameter=0.0;\n\n            //! If this particle is a single primary with a single PAH it is assigned an index of -1 to distinguish it from PAHs in particles.\n\t\t\tif (this->NumPAH() == 1 && this->Numprimary() == 1) {\n\t\t\t\ttemp.push_back(-1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttemp.push_back(index);\n\t\t\t}\n\t\t\t\t\n            //! Number of carbon atoms.\n\t\t\tnum_C=m_PAH[i]->m_pahstruct->numofC();\n\t\t\ttemp.push_back(num_C);\n\n            //! Number of hydrogen atoms.\n\t\t\tnum_H=m_PAH[i]->m_pahstruct->numofH();\n\t\t\ttemp.push_back(num_H);\n\t\t\t\n\t\t\t//! Number of methyl groups.\n\t\t\tnum_CH3=m_PAH[i]->m_pahstruct->numofCH3();\n\t\t\ttemp.push_back(num_CH3);\n\n            //! Number of 6-member rings.\n\t\t\ttemp.push_back(m_PAH[i]->m_pahstruct->numofRings());\n            \n            //! Number of lone 5-member rings.\n\t\t\ttemp.push_back(m_PAH[i]->m_pahstruct->numofLoneRings5());\n\n\t\t\t//! Number of embedded 5-member rings.\n\t\t\ttemp.push_back(m_PAH[i]->m_pahstruct->numofEmbeddedRings5());\n\t\t\t\n\t\t\t//! Number of lone 5-member rings.\n\t\t\ttemp.push_back(m_PAH[i]->m_pahstruct->numofLoneRings7());\n\n\t\t\t//! Number of embedded 5-member rings.\n\t\t\ttemp.push_back(m_PAH[i]->m_pahstruct->numofEmbeddedRings7());\n\t\t\t\n            //! Number of carbon atoms on the edge of the PAH.\n            temp.push_back(m_PAH[i]->m_pahstruct->numofEdgeC());\n\n\t\t\t//! PAH mass (u).\n\t\t\tval = 12*num_C + num_H;\n\t\t\ttemp.push_back(val);\n\n\t\t\t//! PAH mass (kg).\n\t\t\tm_mass = num_C*1.9945e-26 + num_H*1.6621e-27;\n\t\t\ttemp.push_back(m_mass);\n\n\t\t\t//! PAH collision diameter (m).\n\t\t\tPAHCollDiameter = sqrt(num_C*2.0/3.);\n\t\t\tPAHCollDiameter *= 2.4162*1e-10;    //! convert from Angstrom to m.\n\t\t\ttemp.push_back(PAHCollDiameter);\n\n\t\t\t//! PAH density (kg/m3).\n\t\t\ttemp.push_back(density);\n\n\t\t\t//! PAH volume (m3).\n\t\t\tval = m_mass / density;\n\t\t\ttemp.push_back(val);\n\n\t\t\t//! Spherical diameter (m).\n\t\t\tdiameter = pow(6.0 * val / PI, ONE_THIRD);\n\t\t\ttemp.push_back(diameter);\n\n\t\t\t//! Larger of the spherical or collison diameter (m).\n\t\t\tval = max(diameter, PAHCollDiameter);\n\t\t\ttemp.push_back(val);\n\n\t\t\t//! Time created (s).\n\t\t\tval = m_PAH[i]->time_created;\n\t\t\ttemp.push_back(val);\n\n\t\t\t//! Index of PAH.\n\t\t\tval = m_PAH[i]->PAH_ID;\n\t\t\ttemp.push_back(val);\n\n            //! Uncomment the call to saveDOTperLoop to print out the structure of each PAH.\n\t\t\t//m_PAH[i]->saveDOTperLoop(timeStep,uniquePAHCounter);\n\n\t\t\tuniquePAHCounter = uniquePAHCounter + 1;\n\n\t\t\t//! Number of PAHs pointing to the same memory location.\n\t\t\ttemp.push_back(1);\n\n\t\t\tout.push_back(temp);\n\n\t\t\ttemp.clear();\n\n\t\t\tpahUniqueAddresses.insert(m_PAH[i].get());\n\n\t\t\tmemoryLocation << m_PAH[i].get() << std::endl;\n\n\t\t\tMapping.push_back(memoryLocation.str());\n\n\t\t\tmemoryLocation.str(\"\");\n        }\n        else {\n\t\t\tmemoryLocation << m_PAH[i].get() << std::endl;\n\n\t\t\tint pos = find(Mapping.begin(), Mapping.end(), memoryLocation.str()) - Mapping.begin();\n\n\t\t\tmemoryLocation.str(\"\");\n\n\t\t\tout[pos].back() = out[pos].back() + 1;\n        }\n    }\n}\n\n/*!\n* @brief Create contents pertaining to primary particle specific information to be written to a csv file.\n*\n* @param[in,out]    out                   Vector (different PAHs) of vectors (different pieces of information about the PAH).\n* @param[in]        index                 Index assigned to particle.\n* @param[in]        density               Density of soot.\n* @param[in,out]    pahUniqueAddresses    Keep a record of which PAHs have been stored in \"out\" to avoid storing the same memory location twice.\n* @param[in,out]    Mapping               Map of PAH memory locations to PAH in \"out\".\n* @param[in]        timeStep              Index assigned to time step.\n*/\nvoid PAHPrimary::OutputPPPSL(std::vector<std::vector<double> > &out, const int index, const double density, const double timeStep) const\n{\n\tif (m_leftchild != NULL)\n\t\tm_leftchild->OutputPPPSL(out, index, density, timeStep);\n\tif (m_rightchild != NULL) m_rightchild->OutputPPPSL(out, index, density, timeStep);\n\n\tstd::vector<double> temp;\n\n\t//! Initialization of variables.\n\tdouble val;\n\tdouble m_mass = 0.0;\n\tdouble PPCollDiameter = 0.0;\n\tdouble diameter = 0.0;\n\n\t//! If this particle is a single primary with a single PAH it is assigned an index of -1 to distinguish it from PAHs in particles.\n\tif (this->NumPAH() == 1 && this->Numprimary() == 1) {\n\t\ttemp.push_back(-1);\n\t}\n\telse {\n\t\ttemp.push_back(index);\n\t}\n\n\t//! Number of carbon atoms.\n\ttemp.push_back(m_numcarbon);\n\n\t//! Number of hydrogen atoms.\n\ttemp.push_back(m_numH);\n\t\n\t//! Number of methyl atoms.\n\ttemp.push_back(m_numCH3);\n\n\t//! Number of 6-member rings.\n\ttemp.push_back(m_numOfRings);\n\n\t//! Number of 5-member rings.\n\ttemp.push_back(m_numOfLoneRings5);\n\t\n\t//! Number of 5-member rings.\n\ttemp.push_back(m_numOfEmbeddedRings5);\n\t\n\t//! Number of 5-member rings.\n\ttemp.push_back(m_numOfLoneRings7);\n\t\n\t//! Number of 5-member rings.\n\ttemp.push_back(m_numOfEmbeddedRings7);\n\n\t//! Number of PAHs\n\ttemp.push_back(m_numPAH);\n\n\t//! PP mass (kg).\n\tm_mass = m_numcarbon*1.9945e-26 + m_numH*1.6621e-27;\n\ttemp.push_back(m_mass);\n\n\t//! PP volume (m3).\n\tval = m_mass / density;\n\ttemp.push_back(m_mass / density);\n\n\t//! Spherical diameter (nm).\n\tdiameter = pow(6.0 * val / PI, ONE_THIRD);\n\ttemp.push_back(diameter*1.0e9);\n\n\tout.push_back(temp);\n\n\ttemp.clear();\n}\n\n// this function is only used to create a vector containing all the mass of individual PAH within this soot particle\nvoid PAHPrimary::mass_PAH(std::vector<double> &out) const\n{\n    if (m_leftchild != NULL)\n        m_leftchild->mass_PAH(out);\n    if (m_rightchild != NULL)\n        m_rightchild->mass_PAH(out);\n\n    double temp_mass=0.0;\n    for (size_t i = 0; i != m_PAH.size(); ++i)\n    {\n        temp_mass = 12*m_PAH[i]->m_pahstruct->numofC() + m_PAH[i]->m_pahstruct->numofH();\n        out.push_back(temp_mass);\n    }\n}\nvoid PAHPrimary::UpdateCache(void)\n{\n    UpdateCache(this);\n}\n\nbool PAHPrimary::FakeRounding()\n{\n    // there are two conditions that it should perform FakeRounding, no PAH or only one PAH in this primary particle, thus it should be merged with other primary particle.\n    if (m_leftparticle!=NULL)\n    {\n        if (m_leftparticle->m_numPAH==1||(m_leftparticle->m_numPAH==0&&m_leftparticle->m_numcarbon==0))\n            return true;\n        else if (m_rightparticle->m_numPAH==1||(m_rightparticle->m_numPAH==0&&m_rightparticle->m_numcarbon==0))\n            return true;\n        else return false;\n    }\n    else return false;\n}\n\nbool PAHPrimary::CheckRounding()\n{\n    bool hascoalesced = false;\n    bool Condition;\n    \n    //! The condition for whether a particle has coalesced depends on whether\n    //! the distance between the centres of primary particles is tracked. If\n    //! tracked, a particle has coalesced if the distance is 0. If not, the\n    //! condition depends on whether the rounding level exceeds an arbitrarily\n    //! high threshold.\n\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n        Condition = (m_children_roundingLevel > 0.95);\n    } else {\n        Condition = (m_distance_centreToCentre == 0.0);\n    }\n\n    if ((Condition && m_leftparticle != NULL) || FakeRounding()) {\n\t\t//if ((Condition && m_leftparticle != NULL)) {\n        // PrintTree(\"before.inp\");\n        // cout <<\"merging\"<<m_children_roundingLevel<<endl;\n        Merge();\n        // PrintTree(\"after.inp\");\n\n        hascoalesced = true;\n\n        //! Check again because this node has changed.\n        CheckRounding();\n    }\n\n    if (m_leftchild != NULL) {\n        hascoalesced = m_leftchild->CheckRounding();\n        hascoalesced = m_rightchild->CheckRounding();\n    }\n\n    UpdateCache();\n\n    return hascoalesced;\n}\n\n\n//! Update primary particle.\nvoid PAHPrimary::UpdatePrimary(void)\n{\n\t//! If the vector of boost shared pointers to PAHs (m_PAH) is empty, the\n\t//! primary particle is invalid and the following member variables should\n\t//! be set to 0.\n\tif (m_PAH.empty())\n\t{\n\t\tm_mass = 0.0;\n\t\tm_numcarbon = 0;\n\t\tm_numH = 0;\n\t\tm_numCH3 = 0;\n\t\tm_numOfEdgeC = 0;\n\t\tm_numOfRings = 0;\n\t\tm_numOfLoneRings5 = 0;\n\t\tm_numOfEmbeddedRings5 = 0;\n\t\tm_numOfLoneRings7 = 0;\n\t\tm_numOfEmbeddedRings7 = 0;\n\t\tm_numPAH = m_PAH.size();\n\t\tm_PAHmass = 0.0;\n\t\tm_PAHCollDiameter = 0.0;\n\t}\n\telse\n\t{\n\t\tm_numcarbon = 0;\n\t\tm_numH = 0;\n\t\tm_numCH3 = 0;\n\t\tm_numOfEdgeC = 0;\n\t\tm_numOfRings = 0;\n\t\tm_numOfLoneRings5 = 0;\n\t\tm_numOfEmbeddedRings5 = 0;\n\t\tm_numOfLoneRings7 = 0;\n\t\tm_numOfEmbeddedRings7 = 0;\n\t\tm_numPAH = m_PAH.size();\n\t\tm_PAHmass = 0.0;\n\t\tm_PAHCollDiameter = 0.0;\n\n\t\t//! Initialisation of variables to adjust the primary diameter if the\n\t\t//! distance between the centres of primary particles is tracked.\n\t\tdouble d_ij = 0.0;               //!< Distance between the centres of primary particles i and j.\n\t\tdouble r_i = 0.0;                //!< Radius of primary particle i.\n\t\tdouble r_j = 0.0;                //!< Radius of primary particle j.\n\t\tdouble x_i = 0.0;                //!< The distance from the centre of primary particle i to the neck level.\n\t\tdouble A_n = 0.0;                //!< Cross-sectional neck area.\n\t\tdouble A_i = 0.0;                //!< Free surface area of primary particle i.\n\n\t\t//! Initialisation of variables but this is only relevant to particles\n\t\t//! with more than one primary.\n\t\t//d_ij = m_parent->m_distance_centreToCentre;\n\t\t//r_i = m_primarydiam / 2.0;\n\n\t\t//if (m_parent->m_leftparticle == this) {\n\t\t//    r_j = m_parent->m_rightparticle->m_primarydiam / 2.0;\n\t\t//} else {\n\t\t//    r_j = m_parent->m_leftparticle->m_primarydiam / 2.0;\n\t\t//}\n\n\t\t//x_i = (pow(d_ij, 2.0) - pow(r_j, 2.0) + pow(r_i, 2.0)) / 2.0 / d_ij; //!< Eq. (3b) of Langmuir 27:6358 (2011).\n\t\t//A_n = M_PI * (pow(r_i, 2.0) - pow(x_i, 2.0));                        //!< Eq. (4).\n\t\t//A_i = 2.0 * M_PI * (pow(r_i, 2.0) + r_i * x_i);                      //!< Eq. (6).\n\t\t//m_primary_diam_old = m_primarydiam;\n\t\t//m_vol_old = m_vol;\n\t\t//}\n\n\t\tint maxcarbon = 0;\n\n\t\tfor (vector<boost::shared_ptr<PAH> >::iterator i = m_PAH.begin(); i != m_PAH.end(); ++i) {\n\t\t\tm_numcarbon += (*i)->m_pahstruct->numofC();\n\t\t\tm_numH += (*i)->m_pahstruct->numofH();\n\t\t\tm_numCH3 += (*i)->m_pahstruct->numofCH3();\n\t\t\tm_numOfEdgeC += (*i)->m_pahstruct->numofEdgeC();\n\t\t\tm_numOfRings += (*i)->m_pahstruct->numofRings();\n\t\t\tm_numOfLoneRings5 += (*i)->m_pahstruct->numofLoneRings5();\n\t\t\tm_numOfEmbeddedRings5 += (*i)->m_pahstruct->numofEmbeddedRings5();\n\t\t\tm_numOfLoneRings7 += (*i)->m_pahstruct->numofLoneRings7();\n\t\t\tm_numOfEmbeddedRings7 += (*i)->m_pahstruct->numofEmbeddedRings7();\n\t\t\tmaxcarbon = max(maxcarbon, (*i)->m_pahstruct->numofC()); //!< Search for the largest PAH-in terms of the number of carbon atoms-in the primary.\n\t\t}\n\t\tm_numOf6Rings = m_numOfRings;\n\n\t\tm_PAHmass = m_numcarbon * 1.9945e-23 + m_numH * 1.6621e-24;  //!< Units of g.\n\t\tm_PAHmass *= 1.0e-3;                                         //!< Units of kg.\n\n\t\t//! Eq. (10.19) in M. Frenklach, H. Wang, Detailed mechanism and\n\t\t//! modeling of soot particle formation, in: H. Bockhorn (Ed.), Soot\n\t\t//! Formation in Combustion-Mechanisms and Models, Springer, Berlin,\n\t\t//! 1994, pp. 165-190.\n\t\t//! Note that m_i in Eq. (10.19) refers to the number of carbon atoms.\n\t\tm_PAHCollDiameter = 1.395 * sqrt(3.0) * sqrt(maxcarbon * 2.0 / 3.0); //!< Units of Angstroms.\n\t\tm_PAHCollDiameter *= 1.0e-10;                             //!< Units of m.\n\n\t\t//! At the moment we have only one component: soot.\n\t\tif (m_pmodel->ComponentCount() != 1) {\n\t\t\tthrow std::runtime_error(\"Model contains more then one component. Only soot is supported. (PAHPrimary::UpdatePrimary)\");\n\t\t}\n\n\t\tm_vol = m_PAHmass / m_pmodel->Components(0)->Density(); //!< Units of m^3.\n\t\tm_mass = m_PAHmass;\n\t\tm_diam = pow(6.0 * m_vol / PI, ONE_THIRD);\n\t\tm_dmob = m_diam;\n\t\tm_dcol = max(m_diam, m_PAHCollDiameter); \n\t\t//m_dcol = m_diam; //to test bintree model and PAH-KMC model\n\t\tm_surf = PI * m_diam * m_diam;\n\n\t\t//! If the distance between the centres of primary particles is\n\t\t//! tracked, the rate of change in the primary diameter is determined\n\t\t//! by its neighbour. Therefore, the particle should be made up of more\n\t\t//! than one primary.\n\t\t//if ((!m_pmodel->getTrackPrimarySeparation()) || (!m_pmodel->getTrackPrimaryCoordinates()) || (m_pmodel->getTrackPrimarySeparation() && m_numprimary == 1) || m_parent == NULL) {\n\t\t//m_primarydiam = m_diam; \n\t\t//} //else { \n\t\t//! Differentiating Eq. (3b) with respect to time, and assuming\n\t\t//! that r_j and d_ij do not change, the rate of change in x_i with\n\t\t//! respect to time can be obtained.\n\t\t//! Substituting Eqs. (4) and (6) and the above result into\n\t\t//! Eq. (2), the rate of change in r_i with respect to time can be\n\t\t//! obtained.\n\t\t//! References to equations are to Langmuir 27:6358 (2011).\n\t\t//!\n\t\t//! @todo Remove derivation and replace with reference to preprint\n\t\t//!       or paper if results do get published.\n\t\t//m_primarydiam = m_primary_diam_old + 2 * (m_vol - m_vol_old) / (A_i + A_n * r_j / d_ij);\n\t\t//} \n\n\t\t//learn from bintree model//\n\t\tif (!(m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()) || m_parent == NULL){\n\t\t\tm_primarydiam = m_diam;\n\t\t\tm_free_surf = m_surf;\n\t\t\tm_primaryvol = m_vol;\n\t\t\tm_sum_necks = 0.0;\t\n\t\t\tm_sum_cap = 0.0; //used to calculate geometric volume of a particle.\n\n\t\t}\n\t\telse{\n\t\t\t//! Update overlapping primary model\n\t\t\tUpdateOverlappingPrimary();\n\t\t}\n\n\t\tm_sph_prim_vol = (1.0 / 6.0) * M_PI * pow(m_primarydiam, 3.0); // used to calculate geometric volume of a particle.\n\t\t//m_numprimary = 1;\n\t\tm_avg_coalesc = 0.0;\n\n\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\tsetRadius(m_primarydiam / 2.0);\n\t\t}\n\t}\n}\n\nvoid PAHPrimary::Reset()\n{\n\tm_numcarbon = 0;\n\tm_numH = 0;\n\tm_numCH3 = 0;\n\tm_numOfEdgeC = 0;\n\tm_numOfRings = 0;\n\tm_primarydiam = 0.0;\n\tm_surf = 0;\n\tm_vol = 0;\n\tm_PAH.clear();\n\tif (m_pmodel->getTrackPrimaryCoordinates() || m_pmodel->getTrackPrimarySeparation())\n\t\tm_avg_sinter = 0;\n\telse\n\t\tm_avg_coalesc = 0;\n}\n\n//! From bintree model//\n/*!\n* @brief       Checks the sintering level of the particle\n*\n* If the sintering level is above 95%, Merge is called and the cache\n* is updated.\n*\n* @return      Boolean telling if the particle has sintered\n*/\nbool PAHPrimary::CheckSintering()\n{\n\tbool hassintered = false;\n\n\tif (m_leftparticle != NULL) {\n\n\t\t// check whether condition for merger is met\n\t\tif (MergeCondition() || FakeRounding()) { //add FakeRounding() by hdy\n\t\t//if (MergeCondition()) { //used to test bintree model and PAH-KMC model\n\t\t\tMerge();\n\t\t\tUpdateCache();\n\t\t\thassintered = true;\n\n\t\t\t// Check again because this node has changed\n\t\t\tCheckSintering();\n\t\t}\n\t}\n\tif (m_leftchild != NULL) {\n\t\thassintered = m_leftchild->CheckSintering();\n\t\thassintered = m_rightchild->CheckSintering();\n\t}\n\n\treturn hassintered;\n}\n\n/*!\n * @param[in] root The root node of this particle\n */\nvoid PAHPrimary::UpdateCache(PAHPrimary *root)\n{\n\t//Update the children\n\tif (m_leftchild != NULL)\n\t{\n\t\tm_leftchild->UpdateCache(root);\n\t\tm_rightchild->UpdateCache(root);\n\t\tm_numprimary = m_leftchild->m_numprimary + m_rightchild->m_numprimary;\n\t}\n\t//this is a primary and the number of primaries below this node is one (this node and no children)\n\telse\n\t{\n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates())\n\t\t\tm_avg_coalesc = 0;\n\n\t\telse{\n\n\t\t\tif (m_parent == NULL) m_avg_sinter = 1.0;\n\t\t\telse m_avg_sinter = 0.0;\n\n\t\t\tm_sum_cap = 0.0; //used to calculate geometric volume of a particle.\n\t\t\tUpdatePrimary(); //only update if primary coordinates are tracked; learned from bintree model.\n\t\t}\n\n\t\tm_numprimary = 1;\n\n\t\t// Check that the primary is begin kept up to date\n\t\t//            const double oldNumCarbons = m_numcarbon;\n\t\t//            UpdatePrimary();\n\t\t//            if(m_numcarbon != oldNumCarbons)\n\t\t//                std::cerr << \"UpdatePrimary has changed num carbons inside UpdateCache\\n\";\n\n\t}\n\n\t//this is not a primary, sum up the properties\n\tif (m_leftchild != NULL)\n\t{\n\t\t// remove the PAHs from this node to free memory\n\t\tReset();\n\t\tm_surf = m_leftchild->m_surf + m_rightchild->m_surf;\n\t\tm_primarydiam = (m_leftchild->m_primarydiam + m_rightchild->m_primarydiam);\n\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())\n\t\t{\n\t\t\tm_free_surf = m_leftchild->m_free_surf + m_rightchild->m_free_surf;\n\t\t\tm_primaryvol = m_leftchild->m_primaryvol + m_rightchild->m_primaryvol;\n\t\t\tm_sph_prim_vol = m_leftchild->m_sph_prim_vol + m_rightchild->m_sph_prim_vol; //used to calculate geometric volume of a particle.\n\t\t}\n\t\tm_vol = m_leftchild->m_vol + m_rightchild->m_vol;\n\t\tm_numPAH = m_leftchild->m_numPAH + m_rightchild->m_numPAH;\n\t\tm_mass = (m_leftchild->m_mass + m_rightchild->m_mass);\n\t\tm_PAHCollDiameter = max(m_leftchild->m_PAHCollDiameter, m_rightchild->m_PAHCollDiameter);\n\n\t\tm_numcarbon = m_leftchild->m_numcarbon + m_rightchild->m_numcarbon;\n\t\tm_numH = m_leftchild->m_numH + m_rightchild->m_numH;\n\t\tm_numCH3 = m_leftchild->m_numCH3 + m_rightchild->m_numCH3;\n\n\t\tm_numOfEdgeC = m_leftchild->m_numOfEdgeC + m_rightchild->m_numOfEdgeC;\n\t\tm_numOfRings = m_leftchild->m_numOfRings + m_rightchild->m_numOfRings;\n\t\tm_numOfLoneRings5 = m_leftchild->m_numOfLoneRings5 + m_rightchild->m_numOfLoneRings5;\n\t\tm_numOfEmbeddedRings5 = m_leftchild->m_numOfEmbeddedRings5 + m_rightchild->m_numOfEmbeddedRings5;\n\t\tm_numOfLoneRings7 = m_leftchild->m_numOfLoneRings7 + m_rightchild->m_numOfLoneRings7;\n\t\tm_numOfEmbeddedRings7 = m_leftchild->m_numOfEmbeddedRings7 + m_rightchild->m_numOfEmbeddedRings7;\n\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())\n\t\t{\n\t\t\tm_children_sumCap = CalcChildrenSumCap();//used to calculate geometric volume of a particle.\n\t\t\tif ((m_leftchild != NULL) && (m_rightchild != NULL))\n\t\t\t{\n\t\t\t\tm_sum_cap = m_children_sumCap +\n\t\t\t\t\tm_leftchild->m_sum_cap + m_rightchild->m_sum_cap;\n\t\t\t}\n\t\t\t//else m_sum_cap = m_children_sumCap;\n\t\t}\n\n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates())\n\t\t{\n\t\t\t// calculate the coalescence level of the two primaries connected by this node\n\t\t\tm_children_roundingLevel = CoalescenceLevel();\n\t\t\t//sum up the avg coal level\n\t\t\tm_avg_coalesc = m_children_roundingLevel + m_leftchild->m_avg_coalesc + m_rightchild->m_avg_coalesc;\n\t\t}\n\t\telse{\n\n\t\t\t//calculate bounding sphere\n\t\t\tcalcBoundSph();\n\t\t\t\n\t\t\t// calculate the coalescence level of the two primaries connected by this node\n\t\t\tm_children_sintering = SinteringLevel();\n\n\t\t\tif (MergeCondition()) CheckSintering();\n\n\t\t\t// Sum up the avg sintering level (now that sintering is done)\n\t\t\tif ((m_leftchild != NULL) && (m_rightchild != NULL)) {\n\t\t\t\tm_avg_sinter = m_children_sintering +\n\t\t\t\t\tm_leftchild->m_avg_sinter + m_rightchild->m_avg_sinter;\t\t\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// This should only occur if CheckSintering has merged\n\t\t\t\tm_avg_sinter = m_children_sintering;\n\t\t\t}\n\n\t\t}\n\n\t\t// calculate the different diameters only for the root node because this goes into the\n\t\t// particle tree and gets used by the coagulation kernel\n\t\tif (this == root)\n\t\t{\n\t\t\t//spherical eqiv radius\n\t\t\tdouble spherical_radius = pow(3 * m_vol / (4 * PI), ONE_THIRD);\n\t\t\tm_diam = 2 * spherical_radius;\n\n\t\t\t// there are m_numprimary-1 connections between the primary particles\n\t\t\tif (m_numprimary > 1 && !(m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()))\n\t\t\t\t// there are m_numprimary-1 connections between the primary particles\n\t\t\t\tm_avg_coalesc = m_avg_coalesc / (m_numprimary - 1);\n\n\t\t\telse\n\t\t\t\tm_avg_sinter = m_avg_sinter / (m_numprimary - 1);\n\n\t\t\t//approxmiate the surface of the particle\n\n\t\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\t// Approxmiate the surface of the particle\n\t\t\t\t// (same as in ChangePointer)\n\t\t\t\tconst double numprim_1_3 = pow(m_numprimary, -1.0 * ONE_THIRD);\n\n\t\t\t\tm_surf = 4 * PI*spherical_radius*spherical_radius /\n\t\t\t\t\t(m_avg_coalesc*(1 - numprim_1_3) + numprim_1_3);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t// if the centre to centre distance is tracked then this is the free surface area\n\t\t\t\tm_surf = m_free_surf;\n\t\t\t}\n\n\t\t\t//calculate the surface equivalent radius\n\t\t\t// const double radius_surf=sqrt(m_surf/(4*PI));\n\t\t\t// the average between the surface and voluem equiv diameter\n\t\t\t//const double meandiam=spherical_radius+radius_surf;            //2*0.5*(radius(vol)+radius(sphere))\n\t\t\tconst double aggcolldiam = (6 * m_vol / m_surf)*\n\t\t\t\tpow(pow(m_surf, 3) / (36 * PI*m_vol*m_vol), (1.0 / 1.8));\n\t\t\t// the maximum of the largest PAH diameter and\n\t\t\t// the average between the surface and voluem equiv diameter\n\t\t\tconst double cdiam = max(aggcolldiam, m_PAHCollDiameter);\n\t\t\t//const double cdiam = aggcolldiam; //used to test bintree model and PAH-KMC model\n\t\t\tm_dmob = aggcolldiam;\n\t\t\tSetCollDiameter(cdiam);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_diam = 0;\n\t\t\tm_dmob = 0;\n\n\t\t}\n\n\t\t//test the difference between geometric volume (geom_vol) and mass-density based volume (m_vol)\n\t\t//geom_vol should be very close to m_primaryvol\n\t\t//there is some problem to test the geom_vol and m_vol here, maybe because in the function UpdatePAHs, all the primary particles are updated first,\n\t\t//then UpdateCache() was called to update the whole particle\n\t\t//anyway, geom_vol and m_vol can pass the mass conservation test by post processing the data printed by PrintPrimary() using matlab script.\n\t\t//if (this == root && this->m_leftparticle != NULL && this->m_rightparticle != NULL)\n\t\t//{\n\t\t//\tdouble geom_vol = 0.0;\n\t\t//\tgeom_vol = m_sph_prim_vol - m_sum_cap;\n\n\t\t//\t//if (m_primaryvol > 0.0){\n\t\t//\t//\tif (abs((geom_vol - m_primaryvol) / m_primaryvol) > 0.01)\n\t\t//\t//\t{\n\t\t//\t//\t\tstd::cout << \"Something wrong with this particle!\" << endl;\n\t\t//\t//\t\tstd::cout << \"Geometry volume = \" << geom_vol << endl;\n\t\t//\t//\t\tstd::cout << \"Primary volume = \" << m_primaryvol << endl;\n\t\t//\t//\t}\n\t\t//\t//}\n\n\t\t//\tif (abs((geom_vol - m_vol) / m_vol) > 0.01)\n\t\t//\t{\n\t\t//\t\tstd::cout << \"Something wrong with this particle!\" << endl;\n\t\t//\t\tstd::cout << \"Geometry volume = \" << geom_vol << endl;\n\t\t//\t\tstd::cout << \"Mass and density volume = \" << m_vol << endl;\n\t\t//\t\tstd::cout << \"Num of primary = \" << m_numprimary << endl;\n\t\t//\t}\n\n\t\t//\t//assert(abs((geom_vol - m_vol) / m_vol) < 0.01);\n\t\t//\t//assert(abs((geom_vol - m_primaryvol) / m_primaryvol) < 0.01);\n\t\t//}\n\n\t}\n\t\n}\n\n/*!\n * @param[in] filename Output filename\n*/\nvoid PAHPrimary::PrintTree(string filename)\n{\n  ofstream out;\n  out.open(filename.c_str());\n  out << \"digraph unix {\"<<endl;\n  out <<\"graph [rankdir = \\\"LR\\\"];\"<<endl;\n  PrintTreeLoop(out);\n  out << \"}\"<<endl;\n  out.close();\n}\n\n/*!\n * @param[in] out Output stream\n*/\nvoid PAHPrimary::PrintTreeLoop(std::ostream &out)\n{\n  if (m_leftchild!=NULL)\n  { //out<<\"leftchild \"<<10E8*m_leftchild->SphDiameter()<<endl;\n\t//out<<\"rightchild \"<<10E8*m_rightchild->SphDiameter()<<endl;\n      out<<\"\\\" \"<<this<<\"\\\" \"<<\" [shape = \\\"record\\\" label = \\\"surf=\"<<this->m_surf<<\"|m_children_surf=\"<<this->m_children_surf<<\"|m_vol=\"<<this->m_vol<<\"|\"<<this->m_children_sintering<<\"|\"<<this<<\"\\\"];\"<<endl;\n\tout<<\"\\\" \"<<this->m_leftchild<<\"\\\" \"<<\" [shape = \\\"record\\\" label = \\\"surf=\"<<this->m_surf<<\"|m_children_surf=\"<<this->m_children_surf<<\"|m_vol=\"<<this->m_vol<<\"|\"<<this->m_children_sintering<<\"|\"<<this<<\"\\\"];\"<<endl;\n\tout<<\"\\\" \"<<this->m_rightchild<<\"\\\" \"<<\" [shape = \\\"record\\\" label = \\\"surf=\"<<this->m_surf<<\"|m_children_surf=\"<<this->m_children_surf<<\"|m_vol=\"<<this->m_vol<<\"|\"<<this->m_children_sintering<<\"|\"<<this<<\"\\\"];\"<<endl;\n\tout<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_leftchild<<\"\\\"; \"<<endl;\n\tout<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_rightchild<<\"\\\"; \"<<endl;\n\tout<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_leftparticle<<\"\\\"[label=\\\"\"<<this<<\"\\\",color=\\\"blue\\\"]; \"<<endl;\n\tout<<\"\\\" \"<<this<<\"\\\" \"<<\"->\"<<\"\\\" \"<<this->m_rightparticle<<\"\\\"[label=\\\"\"<<this<<\"\\\",color=\\\"blue\\\"]; \"<<endl;\n\tm_leftchild->PrintTreeLoop(out);\n    m_rightchild->PrintTreeLoop(out);\n  }\n\n  else\n  {\n      //out<<\"\\\" \"<<this<<\"\\\" \"<<\" [label = \\\"\"<<2*pow((this->vol_sinter)*3/(4*PI),ONE_THIRD)<<\"\\\"];\"<<endl;\n      out<<\"\\\" \"<<this<<\"\\\" \"<<\" [shape = \\\"record\\\" label = \\\"surf=\"<<this->m_surf<<\"|m_children_surf=\"<<this->m_children_surf<<\"|m_vol=\"<<this->m_vol<<\"|\"<<this->m_children_sintering<<\"|\"<<this<<\"\\\"];\"<<endl;\n  }\n}\n\n\nconst PAHPrimary *PAHPrimary::RightChild() const\n{\n    return m_rightchild;\n}\n\n const PAHPrimary *PAHPrimary::LeftChild() const\n{\n    return m_leftchild;\n}\n\ndouble PAHPrimary::PAHCollDiameter() const\n{\n    return m_PAHCollDiameter;\n}\n\ndouble PAHPrimary::Rg() const\n{\n    return m_Rg;\n}\n\ndouble PAHPrimary::Fdim() const\n{\n    return m_fdim;\n}\n\ndouble PAHPrimary::PrimaryDiam() const\n{\n    return m_primarydiam;\n}\n\ndouble PAHPrimary::LdivW() const\n{\n    return m_LdivW;\n}\n\nint PAHPrimary::Numprimary() const\n{\n    return m_numprimary;\n}\n\nint PAHPrimary::NumCarbon() const\n{\n    return m_numcarbon;\n}\n\nint PAHPrimary::NumHydrogen() const\n{\n    return m_numH;\n}\n\nint PAHPrimary::NumMethyl() const\n{\n    return m_numCH3;\n}\n\nint PAHPrimary::NumEdgeC() const\n{\n    return m_numOfEdgeC;\n}\n\nint PAHPrimary::NumRings() const\n{\n    return m_numOfRings;\n}\n\nint PAHPrimary::NumLoneRings5() const\n{\n\treturn m_numOfLoneRings5;\n}\n\nint PAHPrimary::NumEmbeddedRings5() const\n{\n\treturn m_numOfEmbeddedRings5;\n}\n\nint PAHPrimary::NumLoneRings7() const\n{\n\treturn m_numOfLoneRings7;\n}\n\nint PAHPrimary::NumEmbeddedRings7() const\n{\n\treturn m_numOfEmbeddedRings7;\n}\n\nint PAHPrimary::NumPAH() const\n{\n    return m_numPAH;\n}\n\ndouble PAHPrimary::sqrtLW() const\n{\n    return m_sqrtLW;\n}\n\ndouble PAHPrimary::AvgCoalesc() const\n{\n    return m_avg_coalesc;\n}\n\ndouble PAHPrimary::AvgSinter() const\n{\n\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())\n\t\treturn m_avg_sinter;\n\telse\n\t\treturn m_avg_coalesc;\n}\n\n//! Return distance between the centres of primary particles.\ndouble PAHPrimary::Distance() const\n{\n    return m_distance_centreToCentre;\n}\n\n//! Return free surface area of primary particles.\ndouble PAHPrimary::GetFreeSurfArea() const\n{\n\treturn m_free_surf;\n}\n\n// READ/WRITE/COPY.\n\n// Returns a copy of the model data.\nPAHPrimary *const PAHPrimary::Clone(void) const\n{\n    m_clone=true;\n\tPAHPrimary* newPAHPrimary=new PAHPrimary();\n\tnewPAHPrimary->CopyParts(this);\n\tif (this->m_leftchild!=NULL)\n\tnewPAHPrimary->CopyTree(this);\n\tm_clone=false;\n\treturn newPAHPrimary;\n}\n\n\n// AGGREGATION MODEL.\n\n// Returns the aggregation model which this primary describes.\nAggModels::AggModelType PAHPrimary::AggID(void) const {return AggModels::PAH_KMC_ID;}\n\n/*\n * @brief Writes a object to a binary stream\n *\n * @param[in,out]    out                 Output binary stream\n * @param[in,out]    duplicates          Addresses of PAHs that have already been serialised\n *\n * @exception\t\t invalid_argument    Stream not ready\n */\nvoid PAHPrimary::Serialize(std::ostream &out, void *duplicates) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        if (m_pmodel->WriteBinaryTrees()) {\n            // Call the binary tree serialiser...\n            BinTreeSerializer <PAHPrimary> tree;\n            tree.Serialize(out, this, duplicates);\n        } else {\n            // Just serialise the root node.\n            SerializePrimary(out, duplicates);\n        }\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, PAHPrimary::Serialize).\");\n    }\n}\n\n/*!\n * @brief Writes an individual primary to a binary stream\n *\n * @param[in,out]    out                 Output binary stream\n * @param[in,out]    duplicates          Addresses of PAHs that have already been serialised\n *\n * @exception\t\t invalid_argument    Stream not ready\n */\nvoid PAHPrimary::SerializePrimary(std::ostream &out, void *duplicates) const\n{\n\tif (out.good()) {\n\n\t\tint  val_int(0);\n\t\tdouble val(0.0);\n\t\t// Serialise state space\n\t\tval_int = m_numcarbon;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval_int = m_numH;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval_int = m_numCH3;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\t\t\n\t\tval_int = m_numOfEdgeC;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval_int = m_numOfRings;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\t\t\n\t\tval_int = m_numOfLoneRings5;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\t\t\n\t\tval_int = m_numOfEmbeddedRings5;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\t\t\n\t\tval_int = m_numOfLoneRings7;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\t\t\n\t\tval_int = m_numOfEmbeddedRings7;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval_int = m_numPAH;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval_int = m_numprimary;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval = m_PAHmass;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_PAHCollDiameter;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_primarydiam;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_children_radius;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_children_vol;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_leftparticle_vol_old;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_rightparticle_vol_old;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval_int = m_rightparticle_numPAH;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval_int = m_leftparticle_numPAH;\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\tval = m_children_surf;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_free_surf;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_sum_necks;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_primaryvol;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_children_roundingLevel;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_distance_centreToCentre;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_cen_bsph[0];\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_cen_bsph[1];\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_cen_bsph[2];\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_cen_mass[0];\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_cen_mass[1];\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_cen_mass[2];\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_r;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_r2;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_r3;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_children_sintering;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_avg_sinter;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\t/*Imaging properties\n\t\tval = (double)m_Rg;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = (double)m_fdim;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = (double)m_sqrtLW;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = (double)m_LdivW;\n\t\tout.write((char*)&val, sizeof(val));*/\n\n\t\tval = m_avg_coalesc;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval = m_sint_time;\n\t\tout.write((char*)&val, sizeof(val));\n\n\t\tval_int = (int)m_PAH.size();\n\t\tout.write((char*)&val_int, sizeof(val_int));\n\n\t\t// write the PAH stack (m_PAH)\n\t\tPahSerialisationMap *pahDuplicates = reinterpret_cast<PahSerialisationMap*>(duplicates);\n\t\toutputPAHs(out, *pahDuplicates);\n\n\t\t// Output base class.\n\t\tPrimary::Serialize(out);\n\n\t}\n\telse {\n\t\tthrow invalid_argument(\"Output stream not ready \"\n\t\t\t\"(Sweep, PAHPrimary::SerializePrimary).\");\n\t}\n}\n\n/*\n * @brief Writes individual PAHs to a binary stream \n *\n * @param[in]        out               Output binary stream\n * @param[in,out]    pah_duplicates    Addresses of PAHs that have already been serialised\n */\nvoid PAHPrimary::outputPAHs(std::ostream &out, PahSerialisationMap &pah_duplicates) const\n{\n    if (m_PAH.size() != 0) {\n        //count the number of PAH should be serialized\n        unsigned count = 0;\n\t\tint PAHSize= m_PAH.size();\n        \n        // Keep a record of which PAHs have been serialised to avoid serialising the same\n        // memory location twice.\n        //PahSerialisationMap pahUniqueAdresses;\n\n        while (count != m_PAH.size())\n        {\n            // Serialise the raw memory locations of the PAHs, so that we\n            // can recognise PAHs that are referenced multiple times on\n            // deserialisation.\n            void *ptr = m_PAH[count].get();\n            out.write(reinterpret_cast<char*>(&ptr), sizeof(ptr));\n            //if(pahUniqueAdresses.find(m_PAH[count].get()) == pahUniqueAdresses.end()) {\n            //    m_PAH[count]->Serialize(out);\n            //    pahUniqueAdresses.insert(m_PAH[count].get());\n            //}\n            //else {\n            //    std::cout << \"PAH at \" << m_PAH[count].get() << \" has already been serialised\\n\";\n            //}\n\t\t\tif(pah_duplicates.find(m_PAH[count].get()) == pah_duplicates.end()){\n\t\t\t\tm_PAH[count]->Serialize(out);\n\t\t\t\tpah_duplicates.insert(m_PAH[count].get());\n\t\t\t}\n\t\t\telse {\n                //std::cout << \"PAH at \" << m_PAH[count].get() << \" has already been serialised\\n\";\n            }\n            ++count;\n        }\n    }\n}\n\n/* \n * @brief Reads the object from a binary stream.\n *\n * @param[in,out]\t in\t\t             Stream from which to read\n * @param[in]        model\t             Particle model defining interpretation of particle data\n * @param[in,out]    duplicates          Addresses of PAHs for use when reading primary particles\n *\n * @exception\t\t invalid_argument    Stream not ready\n */\nvoid PAHPrimary::Deserialize(std::istream &in, const Sweep::ParticleModel &model, PahDeserialisationMap &pah_duplicates)\n{\n\tif (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        if (model.WriteBinaryTrees()) {\n            // Call the binary tree serialiser...\n            BinTreeSerializer <PAHPrimary> tree;\n            tree.Deserialize(in, this, model, &pah_duplicates);\n        } else {\n            // Just deserialise the root node.\n            DeserializePrimary(in, model, &pah_duplicates);\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, PAHPrimary::Deserialize).\");\n    }\n}\n\n/*\n * @brief Reads an individual primary from the binary stream\n *\n * @param[in,out]\t in\t\t             Input binary stream\n * @param[in]        model\t             Particle model defining interpretation of particle data\n * @param[in,out]    duplicates          Addresses of PAHs for use when reading primary particles\n *\n * @exception\t\t invalid_argument    Stream not ready\n */\nvoid PAHPrimary::DeserializePrimary(std::istream &in, const Sweep::ParticleModel &model, void *duplicates)\n{\n\tif (in.good()) {\n\n\t\tint  val_int(0);\n\t\tdouble val(0.0);\n\n\t\t// Serialise state space\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numcarbon = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numH = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numCH3 = val_int;\n\t\t\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numOfEdgeC = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numOfRings = val_int;\n\t\t\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numOfLoneRings5 = val_int;\n\t\t\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numOfEmbeddedRings5 = val_int;\n\t\t\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numOfLoneRings7 = val_int;\n\t\t\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numOfEmbeddedRings7 = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numPAH = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_numprimary = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_PAHmass = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_PAHCollDiameter = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_primarydiam = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_children_radius = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_children_vol = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_leftparticle_vol_old = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_rightparticle_vol_old = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_rightparticle_numPAH = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\tm_leftparticle_numPAH = val_int;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_children_surf = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_free_surf = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_sum_necks = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_primaryvol = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_children_roundingLevel = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_distance_centreToCentre = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_cen_bsph[0] = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_cen_bsph[1] = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_cen_bsph[2] = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_cen_mass[0] = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_cen_mass[1] = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_cen_mass[2] = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_r = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_r2 = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_r3 = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_children_sintering = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_avg_sinter = val;\n\n\t\t/* imaging properies\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_Rg = val;\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_fdim = val;\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_sqrtLW = val;\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_LdivW = val;*/\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_avg_coalesc = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val), sizeof(val));\n\t\tm_sint_time = val;\n\n\t\tin.read(reinterpret_cast<char*>(&val_int), sizeof(val_int));\n\t\t// the size of m_PAH\n\t\tconst int PAHcount = val_int;\n\t\t// read the PAH stack (m_PAH)\n\t\tPahDeserialisationMap *pahDuplicates = reinterpret_cast<PahDeserialisationMap*>(duplicates);\n\t\tif (PAHcount != 0)\n\t\t\tinputPAHs(in, model, PAHcount, *pahDuplicates);\n\n\t\tm_leftchild = NULL;\n\t\tm_rightchild = NULL;\n\t\tm_leftparticle = NULL;\n\t\tm_rightparticle = NULL;\n\t\tm_parent = NULL;\n\t\t// Output base class.\n\t\tPrimary::Deserialize(in, model);\n\n\t}\n\telse {\n\t\tthrow invalid_argument(\"Input stream not ready \"\n\t\t\t\"(Sweep, PAHPrimary::DeserializePrimary).\");\n\t}\n}\n\n/*\n * @brief Reads individual PAHs from the binary stream \n *\n * @param[in]        in                Input binary stream\n * @param[in]        model\t           Particle model defining interpretation of particle data\n * @param[in]        PAHcount          Number of PAHs in the particle\n * @param[in,out]    pah_duplicates    Addresses of PAHs for use when reading primary particles\n */\nvoid PAHPrimary::inputPAHs(std::istream &in, const Sweep::ParticleModel &model, const int PAHcount, PahDeserialisationMap &pah_duplicates)\n{\n    int m_count=0;\n    \n    //PahDeserialisationMap pahPointerMappings;\n    while (m_count != PAHcount)\n    {\n        // Raw memory location of PAH prior to serialisation.\n        void* preSerializePointer;\n        in.read(reinterpret_cast<char*>(&preSerializePointer), sizeof(preSerializePointer));\n        //cout << preSerializePointer;\n\n        // See if this PAH has already been deserialised\n        //PahDeserialisationMap::iterator searchResult = pahPointerMappings.find(preSerializePointer);\n        //if(searchResult != pahPointerMappings.end())\n        //{\n        //    // Found PAH in list that has already been deserialised\n        //    m_PAH.push_back(searchResult->second);\n        //}\n        //else {\n        //    // create a new PAH to load in its details\n        //    boost::shared_ptr<PAH> new_PAH (new PAH());\n        //    new_PAH->Deserialize(in);\n        //    m_PAH.push_back(new_PAH);\n        //    pahPointerMappings.insert(std::make_pair(preSerializePointer, new_PAH));\n        //}\n        PahDeserialisationMap::iterator searchResult = pah_duplicates.find(preSerializePointer);\n        if(searchResult != pah_duplicates.end())\n        {\n            // Found PAH in list that has already been deserialised\n            m_PAH.push_back(searchResult->second);\n        }\n        else {\n            // create a new PAH to load in its details\n            boost::shared_ptr<PAH> new_PAH (new PAH());\n            new_PAH->Deserialize(in);\n            m_PAH.push_back(new_PAH);\n            pah_duplicates.insert(std::make_pair(preSerializePointer, new_PAH));\n        }\n        ++m_count;\n    }\n}\n\n/*!\n * This is a helper function for ???????\n * It climbs up the tree from bottom to top recording a route\n * suitable for use in call to @see descendPath.\n *\n *@param[in]    bottom      Tree node from which to start climbing\n *@param[in]    top         Tree node at which to stop climbing\n *\n *@pre      top must be above bottom in a tree\n *\n *@return   Stack that can be used to descend the same path by moving to the\n *          left child each time the top of the stack is true.\n */\nstd::stack<bool> PAHPrimary::recordPath(const PAHPrimary* bottom,\n                                        const PAHPrimary* const top) {\n    std::stack<bool> wasLeftChild;\n\n    while(bottom != top) {\n        // check whether bottom was a left child of its parent\n        wasLeftChild.push(bottom == bottom->m_parent->m_leftchild);\n\n        // Climb one level up the tree\n        bottom = bottom->m_parent;\n    }\n    return wasLeftChild;\n}\n\n/*!\n *@param[in]        here            Point in tree from which to start descent\n *@param[in,out]    takeLeftBranch  Instructions for which child to move to at each level\n *\n *@return   The node at the bottom of the path\n *\n *@pre  here must be a node of tree in which takeLeftBranch is a valid path\n *@post takeLeftBranch.empty() == true\n */\nPAHPrimary* PAHPrimary::descendPath(PAHPrimary *here,\n                                    std::stack<bool> &takeLeftBranch) {\n    while(!takeLeftBranch.empty()) {\n        // Move one step down the tree in the instructed direction\n        if(takeLeftBranch.top())\n            here = here->m_leftchild;\n        else\n            here = here->m_rightchild;\n\n        // This instuction has now been processed\n        takeLeftBranch.pop();\n    }\n\n    return here;\n}\n\n/*!\n *  @brief Sinters particles for time dt.\n *\n *  This function only operates on non-leaf nodes. It begins at the root node,\n *  which sinters for time dt. It then descends the tree to sinter nodes below\n *  the root. If the sintering level rises above 95%, or if the distance\n *  between the centres of primary particles is 0 (if tracked), Merge is called\n *  and the particles are combined. \n *\n *  @param[in] dt    Time for which to sinter.\n *  @param[in] sys   Environment for particles.\n *  @param[in] model Sintering model to apply.\n *  @param[in] rng   Random number generator.\n *  @param[in] wt    Statistical weight.\n */\nvoid PAHPrimary::SinterNode(double dt, Cell &sys, const Processes::SinteringModel &model, rng_type &rng, double wt)\n{\n\t//! Declare sintering rate.\n\tdouble r = 0.0;\n\t// Declare time step variables.\n\tdouble t1 = 0.0, delt = 0.0, tstop = dt;\n\n\t// The scale parameter discretises the delta-S when using\n\t// the Poisson distribution.  This allows a smoother change\n\t// (smaller scale = higher precision).\n\tdouble scale = 0.01;\n\n\t////! Only update the time on the root node.\n\t//if (m_parent == NULL) {\n\t//\tm_sint_time += dt;\n\t//\tSetSinteringTime(m_sint_time);\n\t//}\n\n\t//! Do only if there is a particle to sinter.\n\tif (m_leftparticle != NULL)\n\t{\n\t\t//bool Condition;                          //! Declare variable for condition for complete sintering.\n\n\t\t//! The sintering model depends on whether the distance between the\n\t\t//! centres of primary particles is tracked. If tracked, sintering\n\t\t//! results in a decrease in the distance between the primaries and an\n\t\t//! increase in their diameters. If not, sintering results in a\n\t\t//! decrease in the common surface between the primaries.\n\t\tif (!(m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())) {\n\t\t\t//! Store the old surface area of particles.\n\t\t\t// double surf_old = m_children_surf;\n\n\t\t\t//! Calculate the spherical surface.\n\t\t\tconst double spherical_surface = 4 * PI * m_children_radius * m_children_radius;\n\n\t\t\t//! Define the maximum allowed change in surface area in one\n\t\t\t//! internal time step (10% of spherical surface).\n\t\t\tdouble dAmax = 0.1 * spherical_surface;\n\n\t\t\t//! Perform integration loop.\n\t\t\twhile (t1 < tstop) {\n\t\t\t\t//! Calculate sintering rate.\n\t\t\t\tr = model.Rate(m_time + t1, sys, *this);\n\n\t\t\t\tif (r > 0) {\n\t\t\t\t\t//! Calculate next time-step end point so that the\n\t\t\t\t\t//! surface area changes by no more than dAmax.\n\t\t\t\t\tdelt = dAmax / max(r, 1.0e-300);\n\n\t\t\t\t\t//! Approximate sintering by a poisson process.  Calculate\n\t\t\t\t\t//! number of poisson events.\n\t\t\t\t\tdouble mean;\n\n\t\t\t\t\tif (tstop > (t1 + delt)) {\n\t\t\t\t\t\t//! A sub-step, we have changed surface by dAmax, on average.\n\t\t\t\t\t\tmean = 1.0 / scale;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//! Step until end. Calculate degree of sintering explicitly.\n\t\t\t\t\t\tmean = r * (tstop - t1) / (scale * dAmax);\n\t\t\t\t\t}\n\n\t\t\t\t\tboost::random::poisson_distribution<unsigned, double> repeatDistribution(mean);\n\t\t\t\t\tconst unsigned n = repeatDistribution(rng);\n\n\t\t\t\t\t//! Adjust the surface area.\n\t\t\t\t\tif (n > 0) {\n\t\t\t\t\t\tm_children_surf -= (double)n * scale * dAmax;\n\n\t\t\t\t\t\t//! Check that primary is not completely sintered.\n\t\t\t\t\t\tif (m_children_surf <= spherical_surface) {\n\t\t\t\t\t\t\tm_children_surf = spherical_surface;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t//! Set t1 for next time step.\n\t\t\t\t\tt1 += delt;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tt1 = tstop;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t//! From bintree model\n\t\t\t//! Declare characteristic sintering time.\n\n\t\t\tm_leftparticle->UpdatePrimary(); \n\t\t\tm_rightparticle->UpdatePrimary(); \n\n\t\t\t//! Define the maximum allowed change (1%) in the distance between the\n\t\t\t//! centres of primary particles in one internal time step. In the case\n\t\t\t//! of pure sintering it was found that if the allowed change is too\n\t\t\t//! large (~10%) a significant error is incurred in the final spherical\n\t\t\t//! volume determined through comparisons with the mass-derived volume.\n\t\t\t//! Note that the smaller the distance is, the smaller the changes are.\n\t\t\tdouble dd_ij_Max = m_distance_centreToCentre / 100.0;\n\n\t\t\twhile (t1 < tstop) {\n\n\t\t\t\t//! Definition of variables\n\t\t\t\tdouble r_i = this->m_leftparticle->m_primarydiam / 2.0;\n\t\t\t\tdouble r_j = this->m_rightparticle->m_primarydiam / 2.0;\n\t\t\t\tdouble d_ij = m_distance_centreToCentre;\n\n\t\t\t\tdouble d_ij2 = pow(d_ij, 2.0);\n\t\t\t\tdouble r_i2 = pow(r_i, 2.0);\n\t\t\t\tdouble r_j2 = pow(r_j, 2.0);\n\t\t\t\tdouble r_i4 = pow(r_i, 4.0);\n\t\t\t\tdouble r_j4 = pow(r_j, 4.0);\n\n\t\t\t\t//! Continue if primaries have not coalesced\n\t\t\t\tif (!MergeCondition() && !FakeRounding()) { // add FakeRounding() by hdy\n\t\t\t\t//if (!MergeCondition()) { //used to test bintrtee model and PAH_KMC model\n\n\t\t\t\t\t//! Due to rounding, x_i and x_j are sometimes calculated to be larger \n\t\t\t\t\t//! than the respective primary radii resulting in a negative neck area.\n\t\t\t\t\t//! Therefore we take the smaller of x_i and r_i.\n\t\t\t\t\tdouble x_i = min((d_ij2 - r_j2 + r_i2) / (2.0 * d_ij), r_i); //!< Eq. (3b).\n\t\t\t\t\tdouble x_j = min((d_ij2 - r_i2 + r_j2) / (2.0 * d_ij), r_j); //!< Eq. (3b).\n\t\t\t\t\tdouble A_n = M_PI * (r_i2 - pow(x_i, 2.0));        //!< Eq. (4).\n\n\t\t\t\t\t//declare more variables\n\t\t\t\t\tdouble dd_ij_dt = 0.0;\n\t\t\t\t\tdouble R_n = 0.0;\n\t\t\t\t\tdouble r4_tau = 0.0;\n\t\t\t\t\tdouble tau = 0.0;\n\t\t\t\t\tdouble gamma_eta = 0.0;\n\n\t\t\t\t\t//! In Section 3.1.2 of Langmuir 27:6358 (2011), it is argued that\n\t\t\t\t\t//! the smaller particle dominates the sintering process.\n\n\t\t\t\t\tif (r_i <= r_j) {\n\t\t\t\t\t\ttau = model.SintTime(sys, *this->m_leftparticle); //!< The left particle is smaller than the right. \n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\ttau = model.SintTime(sys, *this->m_rightparticle); //!< The right particle is smaller than the left.\n\t\t\t\t\t}\n\n\t\t\t\t\t//! Gamma is the surface tension and eta is the viscosity, and the\n\t\t\t\t\t//! ratio (gamma/eta) can be related to tau.\n\t\t\t\t\t//! J. Colloid Interface Sci. 140:419 (1990).\n\t\t\t\t\tgamma_eta = min(r_i, r_j) / tau;\n\n\t\t\t\t\t///////////////////////////////////////////////////////\n\t\t\t\t\t/// References to equations in Langmuir 27:6358 (2011).\n\t\t\t\t\t///////////////////////////////////////////////////////\n\n\t\t\t\t\t//! Eq. (14a).\n\t\t\t\t\tdd_ij_dt = 4.0 * r_i * r_j * d_ij2 * (r_i + r_j) * gamma_eta /\n\t\t\t\t\t\t((r_i + r_j + d_ij) * (r_i4 + r_j4 - 2.0 * r_i2 * r_j2 + 4.0 * d_ij * r_i * r_j *(r_i + r_j) - d_ij2 * (r_i2 + r_j2)));\n\n\t\t\t\t\t//! Get surface area and subtract mutual contribution\n\t\t\t\t\tdouble A_i = m_leftparticle->m_free_surf + m_leftparticle->m_sum_necks - M_PI*(r_i*r_i - x_i*x_i)*r_i / x_i;\n\t\t\t\t\tdouble A_j = m_rightparticle->m_free_surf + m_rightparticle->m_sum_necks - M_PI*(r_j*r_j - x_j*x_j)*r_j / x_j;\n\n\t\t\t\t\t//! @todo Remove derivation and replace with reference to preprint\n\t\t\t\t\t//!       or paper if results do get published.\n\t\t\t\t\tdouble B_i = (-r_j*A_n*A_n - x_j*A_j*A_n) / (A_i*A_j*d_ij + r_i*A_j*A_n + r_j*A_i*A_n);\n\t\t\t\t\tdouble B_j = (-r_i*A_n*A_n - x_i*A_i*A_n) / (A_j*A_i*d_ij + r_j*A_i*A_n + r_i*A_j*A_n);\n\n\t\t\t\t\tdelt = dd_ij_Max / max(dd_ij_dt, 1.0e-300);\n\t\t\t\t\tdouble mean;\n\n\t\t\t\t\tif (tstop > (t1 + delt)) {\n\t\t\t\t\t\tmean = 1.0 / scale;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tmean = dd_ij_dt * (tstop - t1) / (scale * dd_ij_Max);\n\t\t\t\t\t}\n\n\t\t\t\t\t//! Sinter primaries\n\t\t\t\t\tboost::random::poisson_distribution<unsigned, double> repeatDistribution(mean);\n\t\t\t\t\tconst unsigned n = repeatDistribution(rng);\n\n\t\t\t\t\tdouble delta_dij = -(double)n * scale * dd_ij_Max; //!< Sintering decreases d_ij hence the negative sign.\n\t\t\t\t\tm_distance_centreToCentre += delta_dij;\n\n\t\t\t\t\t//! if coordinates are tracked then we will translate one side of the particle by the change in separation\n\t\t\t\t\t//! this is faster than translating both sides by half the change\n\t\t\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\t\t\t//! get direction of translation (left particle to right particle)\n\t\t\t\t\t\tCoords::Vector vector_change = UnitVector(m_leftparticle->boundSphCentre(), m_rightparticle->boundSphCentre());\n\t\t\t\t\t\t//! translate the leftparticle\n\t\t\t\t\t\tm_leftparticle->TranslatePrimary(vector_change, -delta_dij);\n\t\t\t\t\t\t//! translate all neighbours of the left particle except the right particle\n\t\t\t\t\t\tm_leftparticle->TranslateNeighbours(m_leftparticle, vector_change, -delta_dij, m_rightparticle);\n\t\t\t\t\t}\n\n\t\t\t\t\t//! Change in primary radii\n\t\t\t\t\tdouble delta_r_i = -(double)n * scale * B_i * dd_ij_Max;  //!< Eq. (8).\n\t\t\t\t\tdouble delta_r_j = -(double)n * scale * B_j * dd_ij_Max;  //!< Eq. (8).\n\n\t\t\t\t\t//! Adjust separation of neighbours that are not currently sintering\n\t\t\t\t\tm_leftparticle->UpdateConnectivity(m_leftparticle, delta_r_i, m_rightparticle);\n\t\t\t\t\tm_rightparticle->UpdateConnectivity(m_rightparticle, delta_r_j, m_leftparticle);\n\n\t\t\t\t\t//! Adjust primary radii\n\t\t\t\t\tthis->m_leftparticle->m_primarydiam += 2.0 * delta_r_i;\n\t\t\t\t\tthis->m_rightparticle->m_primarydiam += 2.0 * delta_r_j;\n\n\t\t\t\t\t//! update primaries\n\t\t\t\t\tm_leftparticle->UpdateOverlappingPrimary();\n\t\t\t\t\tm_rightparticle->UpdateOverlappingPrimary();\n\n\t\t\t\t\tt1 += delt;\n\n\t\t\t\t\t//! Return some sintering rate\n\t\t\t\t\tr = dd_ij_dt;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbreak; //!do not continue to sinter.\n\t\t\t\t}\n\t\t\t}\n\t\t\t//! If coordinates are tracked update tracking radius \n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\tm_leftparticle->setRadius(m_leftparticle->m_primarydiam / 2.0);\n\t\t\t\tm_rightparticle->setRadius(m_rightparticle->m_primarydiam / 2.0);\n\t\t\t}\n\n\t\t}\n\n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates())\n\t\t\tm_children_roundingLevel = RoundingLevel();\n\t\telse m_children_sintering = SinteringLevel();\n\t\t\n\t\t//m_sint_rate = r;\n\n\t}\n}\n\nvoid PAHPrimary::SetSinteringTime(double time) \n{\n    m_sint_time = time;\n    // Update children\n    if (m_leftchild != NULL) {\n        m_leftchild->SetSinteringTime(time);\n        m_rightchild->SetSinteringTime(time);\n    }\n    // Update particles\n    if (m_leftparticle != NULL) {\n        m_leftparticle->SetSinteringTime(time);\n        m_rightparticle->SetSinteringTime(time);\n    }\n}\n\n//returns the CoalescenceLevel of the two primaries that are connected by this node\n//used for when primary coordinates are not tracked\ndouble PAHPrimary::RoundingLevel()\n{\n    if (m_leftparticle!=NULL) {\n        // Calculate the spherical surface\n        const double spherical_surface=4*PI*m_children_radius*m_children_radius;\n        const double two_1_3=0.79370052231642452;\n        double slevel;\n\n        if (m_children_surf <= spherical_surface) {\n            m_children_surf = spherical_surface;\n            return 1.0;\n        }\n\n        if (m_children_surf == 0.0) {\n            slevel = 0.0;\n        } else {\n            slevel= ((spherical_surface/m_children_surf)-two_1_3)/(1-two_1_3);\n        }\n\n        if (slevel < 0.0) {\n            return 0.0;\n        } else if (slevel > 1.0) {\n            cout << \"sweep: PAHPrimary::CoalescenceLevel() > 1.0\";\n            return 1.0;\n        } else {\n            return slevel;\n        }\n    } else {\n        // Particle is a primary, should have 0 as default properties\n        m_children_surf = 0.0;\n        m_children_radius = 0.0;\n        m_children_vol = 0.0;\n        return 0.0;\n    }\n}\n\n//from bintree model\n/*!\n* @brief       Identify neighbours and sum their cap areas and volumes\n*\n* Works up the binary tree identifying the neighbours of the adjusted primary\n* and sums the contribution from neighbours to the free surface area.\n* All neighbours of the primary being adjusted are left/rightparticles of nodes directly\n* above it.\n*\n* @param[in]   prim\t\tPointer to the primary being adjusted\n* @param[in]   CapAreas\tSum of cap areas\n* @param[in]   CapVolumes\tSum of cap volumes\n*/\nvoid PAHPrimary::SumCaps(PAHPrimary *prim, double &CapAreas, double &CapVolumes, double &SumNecks){\n\n\tdouble d_ij = m_parent->m_distance_centreToCentre;\n\tdouble r_i = prim->m_primarydiam / 2.0;\n\tdouble r_j = 0.0;\n\tdouble x_ij = 0.0;\n\n\t//! Check if a neighbour of prim\n\tif (m_parent->m_leftparticle == prim) {\n\n\t\t//! Right primary is a neighbour\n\t\tr_j = m_parent->m_rightparticle->m_primarydiam / 2.0;\n\t\tx_ij = min((pow(d_ij, 2.0) - pow(r_j, 2.0) + pow(r_i, 2.0)) / (2.0*d_ij), r_i); //ensure -r_i <= x_ij <= r_i\n\t\tx_ij = max(x_ij, -r_i);\n\n\t\t//! Calculate cap area and add to sum\n\t\tCapAreas += 2 * M_PI*(r_i*r_i - r_i*x_ij);\n\n\t\t//! Calculate cap volume and add to sum\n\t\tCapVolumes += M_PI * (2 * pow(r_i, 3.0) + pow(x_ij, 3.0) - 3.0*pow(r_i, 2.0)*x_ij) / 3.0;\n\n\t\t//! Neck area * r_i / x_ij\n\t\tSumNecks += abs(M_PI*(r_i*r_i - x_ij*x_ij) * r_i / x_ij);\n\n\t}\n\telse if (m_parent->m_rightparticle == prim) {\n\n\t\t//! Left primary is a neighbour\n\t\tr_j = m_parent->m_leftparticle->m_primarydiam / 2.0;\n\t\tx_ij = min((pow(d_ij, 2.0) - pow(r_j, 2.0) + pow(r_i, 2.0)) / (2.0*d_ij), r_i);\t//ensure -r_i <= x_ij <= r_i\n\t\tx_ij = max(x_ij, -r_i);\n\n\t\t//! Calculate cap area and add to sum\n\t\tCapAreas += 2 * M_PI*(r_i*r_i - r_i*x_ij);\n\n\t\t//! Calculate cap volume and add to sum\n\t\tCapVolumes += M_PI * (2 * pow(r_i, 3.0) + pow(x_ij, 3.0) - 3.0*pow(r_i, 2.0)*x_ij) / 3.0;\n\n\t\t//! Neck area * r_i / x_ij\n\t\tSumNecks += abs(M_PI*(r_i*r_i - x_ij*x_ij) * r_i / x_ij);\n\t}\n\n\t//! Continue working up the binary tree\n\tif (m_parent->m_parent != NULL){\n\t\tm_parent->SumCaps(prim, CapAreas, CapVolumes, SumNecks);\n\t}\n}\n\n//! From bintree model\n/*! Updates primary free surface area and volume\n*\n* @param[in]   this\t\tPrimary to update\n*/\nvoid PAHPrimary::UpdateOverlappingPrimary(){\n\n\t//! Get sum of cap areas and volumes\n\tdouble CapAreas = 0.0;\t\t\t//!< Contribution from neighbours to free surface area\n\tdouble CapVolumes = 0.0;\t\t//!< Contribution from neighbours to volume\n\tdouble SumNecks = 0.0;\t\t\t//!< Sum of necks * r_i / x_ij\n\tSumCaps(this, CapAreas, CapVolumes, SumNecks);\n\n\t//! Update free surface area\n\t//if the calculated area is negative (too many overlaps) then set m_free_surf = 0.0\n\tm_free_surf = max(M_PI*m_primarydiam*m_primarydiam - CapAreas, 0.0);\n\n\t//! Update primary volume\n\t//if calculated volume is negative (too many overlaps) then set m_primaryvol = 0.0\n\tm_primaryvol = max(M_PI*pow(m_primarydiam, 3.0) / 6.0 - CapVolumes, 0.0);\n\n\t//! Update sum of necks \n\tm_sum_necks = max(SumNecks, 0.0);\n}\n\n//! From bintree model\n/*!\n* @brief       Checks if condition for merger is met\n*\n* @return      Boolean telling if the merger condition is met\n*/\nbool PAHPrimary::MergeCondition()\n{\n\tbool condition = false;\n\n\tif (m_leftparticle != NULL) {\n\t\t//! The condition for whether a particle has coalesced depends on whether\n\t\t//! the distance between the centres of primary particles is tracked. \n\t\t//! If not, the condition depends on whether the rounding \n\t\t//! level exceeds an arbitrarily high threshold.\n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\tcondition = (m_children_roundingLevel > 0.95);\n\t\t}\n\t\telse {\n\t\t\t//! If tracked, a particle has coalesced when the neck reaches the centre \n\t\t\t//! of one of the primaries. Condition: min(x_ij,x_ji) <= 0\n\t\t\t//  (If the neck were allowed to move beyond this point and reside outside \n\t\t\t//  the region between the primary centres any (growth) adjustments would \n\t\t\t//  fail.) \n\t\t\tdouble r_i = m_leftparticle->m_primarydiam / 2.0;\n\t\t\tdouble r_j = m_rightparticle->m_primarydiam / 2.0;\n\t\t\tdouble d_ij = m_distance_centreToCentre;\n\n\t\t\tif (d_ij <= 0.0 ){\n\t\t\t//if (d_ij <= 0.0 || d_ij < 0.5*(r_i + r_j)){\n\t\t\t\t//ensures that particles are merged if the sintering step overshoots\n\t\t\t\tcondition = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//! Primaries are merged when the neck radius is 95% of the smaller primary radius.\n\t\t\t\t//! The second condition ensures that primaries are merged even if sintering overshoots\n\t\t\t\t//! i.e. the neck crosses the centre of smaller primary\n\t\t\t\tdouble x_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i) / (2.0*d_ij);\n\t\t\t\tdouble x_ji = (d_ij*d_ij - r_i*r_i + r_j*r_j) / (2.0*d_ij);\n\t\t\t\tdouble R_ij = sqrt(r_i*r_i - x_ij*x_ij);\t//!neck radius\n\t\t\t\tcondition = R_ij / min(r_i, r_j) >= 0.95 || ((pow(d_ij, 2.0) - pow(max(r_i, r_j), 2.0) + pow(min(r_i, r_j), 2.0)) / (2.0*d_ij)) <= 0.0;\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\treturn condition;\n}\n\n//! From bintree model\n/*!\n*  Calculates unit vector between two set coordinates\n*\n*  @param[in]    x_i\tCoordinates\n*  @param[in]    x_j\tCoordinates\n*  @param[out]   unit vector\n*/\nCoords::Vector PAHPrimary::UnitVector(Coords::Vector x_i, Coords::Vector x_j)\n{\n\tCoords::Vector delta_x;\n\tdouble len_delta_x;\n\n\t//! Calculate difference x_j - x_i\n\tdelta_x[0] = x_j[0] - x_i[0];\n\tdelta_x[1] = x_j[1] - x_i[1];\n\tdelta_x[2] = x_j[2] - x_i[2];\n\n\t//! Calculate the length of the vector\n\tlen_delta_x = sqrt(delta_x[0] * delta_x[0] + delta_x[1] * delta_x[1] + delta_x[2] * delta_x[2]);\n\n\t//! Create unit vector\n\tdelta_x[0] /= len_delta_x;\n\tdelta_x[1] /= len_delta_x;\n\tdelta_x[2] /= len_delta_x;\n\n\treturn delta_x;\n}\n\n// !From bintree model\n/*!\n*  Translates a primary particle along a unit vector\n*\n*  @param[in]    u\t\t\tUnit vector (direction)\n*  @param[in]    delta_d\tDistance to translate\n*/\nvoid PAHPrimary::TranslatePrimary(Coords::Vector u, double delta_d)\n{\n\t//! Bounding sphere coordinates\n\tm_cen_bsph[0] += delta_d * u[0];\n\tm_cen_bsph[1] += delta_d * u[1];\n\tm_cen_bsph[2] += delta_d * u[2];\n\t//! Centre of mass coordinates\n\tm_cen_mass[0] += delta_d * u[0];\n\tm_cen_mass[1] += delta_d * u[1];\n\tm_cen_mass[2] += delta_d * u[2];\n}\n\n//! From bintree model\n/*!\n*  Translates neighbours of a primary particle along a unit vector\n*\n*  @param[in]    prim\t\t\tPrimary\n*  @param[in]    u\t\t\t\tUnit vector direction of translation\n*  @param[in]    delta_d\t\tMagnitude of translation\n*  @param[in]    prim_ignore\tPrimary to ignore\n*/\nvoid PAHPrimary::TranslateNeighbours(PAHPrimary *prim, Coords::Vector u, double delta_d, PAHPrimary *prim_ignore)\n{\n\tPAHPrimary *neighbour = NULL;\n\t//! Check if a neighbour of prim but not prim_ignore\n\tif (m_parent->m_leftparticle == prim && m_parent->m_rightparticle != prim_ignore) {\n\t\t//! right particle is a neighbour\n\t\tneighbour = m_parent->m_rightparticle;\n\t\t//! adjust its coordinates\n\t\tneighbour->TranslatePrimary(u, delta_d);\n\t\t//! adjust its neighbours except for prim\n\t\tneighbour->TranslateNeighbours(neighbour, u, delta_d, prim);\n\t}\n\telse if (m_parent->m_rightparticle == prim &&  m_parent->m_leftparticle != prim_ignore) {\n\t\t//! left particle is a neighbour\n\t\tneighbour = m_parent->m_leftparticle;\n\t\t//! adjust its coordinates\n\t\tneighbour->TranslatePrimary(u, delta_d);\n\t\t//! adjust its neighbours except for prim\n\t\tneighbour->TranslateNeighbours(neighbour, u, delta_d, prim);\n\t}\n\n\t//! continue working up the binary tree\n\tif (m_parent->m_parent != NULL){\n\t\tm_parent->TranslateNeighbours(prim, u, delta_d, prim_ignore);\n\t}\n}\n\n//! From bintree model\n/*!\n* @brief    Calculates the sintering level for particles connected by node.\n*\n* Unlike the original SilicaPrimary model; this model assumes that a single\n* primary particle (no tree structure) has a sintering level of 1.0. In the\n* case where it is part of a tree, 0.0 is returned so as to not cause\n* erroneous calculation of m_children_sintering.\n*\n* @return   Sintering level\n*/\ndouble PAHPrimary::SinteringLevel()\n{\n\tif (m_leftchild != NULL && m_rightchild != NULL) {\n\n\t\tdouble slevel(0.0);\n\n\t\t//! If the centre-centre separation is not tracked the sintering level is calculated \n\t\t//! as per Shekar et al. (2012)\n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t// Calculate the spherical surface\n\t\t\tconst double spherical_surface =\n\t\t\t\t4 * PI * m_children_radius * m_children_radius;\n\n\t\t\tif (m_children_surf == 0.0) {\n\t\t\t\tslevel = 0.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tslevel = ((spherical_surface / m_children_surf) - TWO_ONE_THIRD)\n\t\t\t\t\t/ (1 - TWO_ONE_THIRD);\n\t\t\t}\n\n\t\t\t//! if centre-centre separation is tracked the sintering level is calculated as\n\t\t\t//! s = R_ij / min(r_i,r_j)\n\t\t\t//! 0 <= s <= 1 is consistent with the merger condition\n\t\t\t//To do: paper reference here\n\t\t}\n\t\telse{\n\t\t\tif (m_leftparticle != NULL && m_rightparticle != NULL) {\n\n\t\t\t\tdouble r_i = m_leftparticle->m_primarydiam / 2.0;\n\t\t\t\tdouble r_j = m_rightparticle->m_primarydiam / 2.0;\n\t\t\t\tdouble d_ij = m_distance_centreToCentre;\n\t\t\t\tdouble x_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i) / (2.0*d_ij);\n\t\t\t\tdouble R_ij = sqrt(r_i*r_i - x_ij*x_ij);\n\n\t\t\t\tslevel = R_ij / min(r_i, r_j);\n\t\t\t}\n\t\t}\n\n\t\tif (slevel < 0.0) {\n\t\t\treturn 0.0;\n\t\t}\n\t\telse if (slevel > 1.0) {\n\t\t\treturn 1.0;\n\t\t}\n\t\telse return slevel;\n\n\t}\n\telse {\n\t\t// Particle is a primary\n\t\tm_children_surf = 0.0;\n\t\tm_children_radius = 0.0;\n\t\tm_children_vol = 0.0;\n\t\tif (m_parent == NULL) return 1.0;        // Single primary case\n\t\telse return 0.0;                         // Part of a tree\n\t}\n}\n\n//! From bintree model//\n/*!\n* @brief       Adjust primary radius after volume addition due to merger.\n*\t\t\t\tAdjustment is performed in a similar manner to sintering,\n*\t\t\t\tassuming that the neck radii are unchanged; hence,\n*\t\t\t\tthe neighbours are translated outwwards.\n*\n* @param[in] V1\t\t\tVolume to be added\n* @param[in] d_ij\t\t\tSeparation of merging primaries\n* @param[in] prim_ignore\tPrimary to be ignored in adjustments\n*/\nvoid PAHPrimary::AdjustPrimary(double V1, double d_ij, PAHPrimary *prim_ignore)\n{\n\tdouble V0 = 0.0;\t\t\t\t\t\t\t\t//!< Variable to track added volume\n\tdouble r_i = m_primarydiam / 2.0;\t\t\t\t//!< Radius of primary particle i\n\tdouble r_j = prim_ignore->m_primarydiam / 2.0;\t//!< Radius of primary particle j\n\tdouble x_i = (d_ij*d_ij - r_j*r_j + r_i*r_i) / (2.0*d_ij);\t//!< Distance to merging neck\n\tdouble dr_max = 0.01*r_i;\t\t\t\t\t\t//!< Maximum change in primary radius during internal step (1% of primary radius)\n\tdouble dr_i = 0.0;\t\t\t\t\t\t\t\t//!< Change in radius of i\n\n\twhile (V0 <= V1){\n\n\t\tr_i = m_primarydiam / 2.0;\n\n\t\t//! change in volume (exclude contribution from merging neck)\n\t\tdouble dV = dr_max * (m_free_surf + 2.0*M_PI*(r_i*r_i - r_i*x_i) + max(m_sum_necks - abs(M_PI*(r_i*r_i - x_i*x_i)*r_i / x_i), 0.0));\n\n\t\tassert(dV > 0.0);\n\n\t\t//! change in radius\n\t\tif (V0 + dV > V1){\n\t\t\tdr_i = (V1 - V0)*dr_max / dV;\n\t\t}\n\t\telse{\n\t\t\tdr_i = dr_max;\n\t\t}\n\n\t\tassert(dr_i > 0.0);\n\t\tassert(dr_i <= 1.1*dr_max);\n\n\t\t//! Update the particle separations ignoring the smaller primary\n\t\tif (m_parent != NULL) UpdateConnectivity(this, dr_i, prim_ignore);\n\n\t\t//! Update primary diameter\n\t\tm_primarydiam = 2.0* (r_i + dr_i);\n\n\t\t//! Update primary properties\n\t\tthis->UpdateOverlappingPrimary();\n\n\t\tV0 += dV;\n\t}\n}\n\n//! From bintree model.//\n//! Overload function. Used when primary coordinates are tracked.//\n/*!\n* @brief       Changes pointer from source to target when centre-centre separation is tracked\n*\n* If a primary neighbours the smaller of the merging pair the centre to centre separation is\n* re-estmated as the smaller of the sum of the separation or the sum of primary radii.\n*\n* @param[in] source\t\tPointer to the original particle\n* @param[in] target\t\tPointer to the new particle\n* @param[in] small_prim\tSmaller of merging primaries\n* @param[in] node\t\t\tPointer to merging neck (non-leaf node)\n*/\nvoid PAHPrimary::ChangePointer(PAHPrimary *source, PAHPrimary *target, PAHPrimary *small_prim, PAHPrimary *node)\n{\n\n\tif (m_rightparticle == source) {\n\t\t//! if the neighbour is the smaller of the merging primaries then add new neighbour\n\t\tif (this != node){\n\t\t\tif (source == small_prim){\n\n\t\t\t\tdouble r_j = m_rightparticle->m_primarydiam / 2.0;\t//!< radius of smaller merging primary\n\t\t\t\tdouble r_k = m_leftparticle->m_primarydiam / 2.0;\t//!< radius of neighbour of merging primary\n\t\t\t\tdouble d_kj = m_distance_centreToCentre;\t\t\t//!< primary separation\n\t\t\t\tdouble x_kj = (d_kj*d_kj - r_j*r_j + r_k*r_k) / 2.0 / d_kj;\t//!< distance form centre of neighbour to neck with smaller merging primary\n\t\t\t\tdouble A_n_k = M_PI*(r_k*r_k - x_kj*x_kj);\t\t\t\t//!< neck radius\n\n\t\t\t\tif (A_n_k > 0.0){\n\t\t\t\t\t//! add the neighbouring primary of smaller merging primary as a neighbour of the new merged primary\n\t\t\t\t\tdouble x_ik = target->AddNeighbour(A_n_k, small_prim, node);\n\t\t\t\t\tm_distance_centreToCentre = min(x_ik + x_kj, m_rightparticle->m_primarydiam / 2.0 + m_leftparticle->m_primarydiam / 2.0);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t//! primaries in point contact\n\t\t\t\t\tm_distance_centreToCentre = m_rightparticle->m_primarydiam / 2.0 + m_leftparticle->m_primarydiam / 2.0;\n\t\t\t\t}\n\n\t\t\t\t//! adjust coordinates of new neighbour and all its neighbour\n\t\t\t\t//! this translates the branch along old separation vector d_ik to appropriate separation\n\t\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()){\n\n\t\t\t\t\tCoords::Vector u_ik = UnitVector(m_leftparticle->boundSphCentre(), target->boundSphCentre());\t//!< old separation unit vector\n\t\t\t\t\tdouble d_ik = Separation(m_leftparticle->boundSphCentre(), target->boundSphCentre());\t\t\t//!< old separation distance \n\t\t\t\t\t//! Translate the neighbour \n\t\t\t\t\tm_leftparticle->TranslatePrimary(u_ik, d_ik - m_distance_centreToCentre);\n\t\t\t\t\t//! Translate all neighbours of the neighbour except the old small_prim\n\t\t\t\t\tm_leftparticle->TranslateNeighbours(m_leftparticle, u_ik, d_ik - m_distance_centreToCentre, small_prim);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_rightparticle = target;\n\n\t\t\tif (m_distance_centreToCentre < 0.0) m_distance_centreToCentre = -m_distance_centreToCentre; //! this is a length \n\n\t\t}\n\t\telse{\n\t\t\tm_rightparticle = NULL;\n\t\t}\n\n\t}\n\n\tif (m_leftparticle == source){\n\t\t//! if the neighbour is the smaller of the merging primaries then add new neighbour\n\t\tif (this != node){\n\t\t\tif (source == small_prim){\n\n\t\t\t\tdouble r_j = m_leftparticle->m_primarydiam / 2.0;\t//!< radius of smaller merging primary\n\t\t\t\tdouble r_k = m_rightparticle->m_primarydiam / 2.0;\t//!< radius of neighbour of merging primary\n\t\t\t\tdouble d_kj = m_distance_centreToCentre;\t\t\t//!< primary separation\n\t\t\t\tdouble x_kj = (d_kj*d_kj - r_j*r_j + r_k*r_k) / 2.0 / d_kj;\t//!< distance form centre of neighbour to neck with smaller merging primary\n\t\t\t\tdouble A_n_k = M_PI*(r_k*r_k - x_kj*x_kj);\t\t\t\t//!< neck radius\n\n\t\t\t\tif (A_n_k > 0.0){\n\t\t\t\t\t//! add the neighbouring primary of smaller merging primary as a neighbour of the new merged primary\n\t\t\t\t\tdouble x_ik = target->AddNeighbour(A_n_k, small_prim, node);\n\t\t\t\t\tm_distance_centreToCentre = min(x_ik + x_kj, m_rightparticle->m_primarydiam / 2.0 + m_leftparticle->m_primarydiam / 2.0);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t//! primaries in point contact\n\t\t\t\t\tm_distance_centreToCentre = m_rightparticle->m_primarydiam / 2.0 + m_leftparticle->m_primarydiam / 2.0;\n\t\t\t\t}\n\n\t\t\t\t//! adjust coordinates of new neighbour and all its neighbour\n\t\t\t\t//! this translates the branch along old separation vector d_ik to appropriate separation\n\t\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()){\n\n\t\t\t\t\tCoords::Vector vector_d_ik = UnitVector(m_rightparticle->boundSphCentre(), target->boundSphCentre());\t//!< old separation unit vector\n\t\t\t\t\tdouble d_ik = Separation(m_rightparticle->boundSphCentre(), target->boundSphCentre());\t\t\t\t\t//!< old separation distance \n\t\t\t\t\t//! Translate the neighbour \n\t\t\t\t\tm_rightparticle->TranslatePrimary(vector_d_ik, d_ik - m_distance_centreToCentre);\n\t\t\t\t\t//! Translate all neighbours of the neighbour except the old small_prim\n\t\t\t\t\tm_rightparticle->TranslateNeighbours(m_rightparticle, vector_d_ik, d_ik - m_distance_centreToCentre, small_prim);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_leftparticle = target;\n\n\t\t\tif (m_distance_centreToCentre < 0.0) m_distance_centreToCentre = -m_distance_centreToCentre; //! this is a length \n\n\t\t}\n\t\telse{\n\t\t\tm_leftparticle = NULL;\n\t\t}\n\t}\n\n\t// Update the tree above this sub-particle.\n\tif (m_parent != NULL) {\n\t\tm_parent->ChangePointer(source, target, small_prim, node);\n\t}\n\n}\n\n//! From bintree model//\n/*!\n* @brief       Create neck for new neighbours added during merger event\n*\n* Neighbours of merging primary are added to the new merged primary\n* (the larger of the merging pair). The new merged primary is 'sintered'\n* to preserve the neck size of the neighbour being added\n*\n* @param[in]\tA_n_k\t\tNeck area of neighbour being added\n* @param[in]\tsmall_prim\tSmall merging primary\n* @param[in]\tthis\t\tNew merged primary\n* @param[out] centre to neck distance of new merged primary\n*/\ndouble PAHPrimary::AddNeighbour(double A_n_k, PAHPrimary *small_prim, PAHPrimary *node)\n{\n\n\tdouble dr_i = 0.0;\t\t\t\t\t//!< Change in radius\n\tdouble r_i = m_primarydiam / 2.0;\t\t//!< Radius of new (merged) primary\n\tdouble dx_max = -0.1*r_i;\t\t\t//!< Maximum step change in x_ik\n\tdouble dx_i = 0.0;\t\t\t\t\t//!< Change in primary centre to neck distance\n\tdouble x_ik = 0.999*r_i;\t\t\t//!< Initialise primary centre to neck distance as 0.999*r_i\n\tdouble A_n_i = M_PI*(r_i*r_i - x_ik*x_ik);\t\t//!< initial neck radius\n\n\t//! \"Sinter\" new primary until the neck is the same size as the \n\t//! neck on the old neighbour of the old particle.\n\t//! Loop while the merged primary neck area is less than the desired area A_n_k\n\twhile (A_n_i < A_n_k){\n\n\t\t//! variables for updating surface areas\n\t\tdouble NodeCapAreas = 0.0;\n\t\tdouble NodeCapVolumes = 0.0;\n\t\tdouble NodeSumNecks = 0.0;\n\t\tdouble SmallCapAreas = 0.0;\n\t\tdouble SmallCapVolumes = 0.0;\n\t\tdouble SmallSumNecks = 0.0;\n\t\tdouble CapAreas = 0.0;\n\t\tdouble CapVolumes = 0.0;\n\t\tdouble SumNecks = 0.0;\n\n\t\t//!Update surface areas\n\t\t//UpdateOverlappingPrimary ascends from the primary and misses some neighbours\n\t\t//becasue they are not on this path during the change pointer update.\n\t\t//(The tree is only rearranged after the update.)\n\t\t//To include the missed necks we sum the contribution ascending from the \n\t\t//small primary and from the large primary and subtract the contribution \n\t\t//ascending from node to avoid double counting.\n\t\tthis->SumCaps(this, CapAreas, CapVolumes, SumNecks);\n\t\tsmall_prim->SumCaps(this, SmallCapAreas, SmallCapVolumes, SmallSumNecks);\n\t\tif (node->m_parent != NULL) node->SumCaps(this, NodeCapAreas, NodeCapVolumes, NodeSumNecks);\n\n\t\t//! Update free surface area\n\t\t//if the calculated area is negative (too many overlaps) then set m_free_surf = 0.0\n\t\tm_free_surf = max(M_PI*m_primarydiam*m_primarydiam - CapAreas - SmallCapAreas + NodeCapAreas, 0.0);\n\n\t\t//! Update sum of necks \n\t\tm_sum_necks = max(SumNecks + SmallSumNecks - NodeSumNecks, 0.0);\n\n\t\tr_i = m_primarydiam / 2.0;\t\t//!< Radius of new (merged) primary\n\n\t\t//Add reference to preprint/paper here.\n\t\t//Surface areas exclude the contribution from the new neck being added \n\t\t//we must add the contribution to the free surface area,\n\t\t//this is to be excluded from the sum over necks anyway.\n\t\tdouble B_ik = -A_n_i / (m_free_surf + m_sum_necks - 2 * M_PI*(r_i*r_i - r_i*x_ik));\n\n\t\t//! Change in radius\n\t\tdr_i = B_ik * dx_max;\n\t\t//! Save old neck size\n\t\tdouble A_n_i_old = A_n_i;\n\t\t//! New neck size\n\t\tA_n_i = M_PI*((r_i + dr_i)*(r_i + dr_i) - (x_ik + dx_max)*(x_ik + dx_max));\n\n\t\t//! If desired neck size is exceeded then solve the quadratic for dx\n\t\t//! A_n_i = M_PI*((r_i+dr_i)*(r_i+dr_i) - (x_ik+dx)*(x_ik+dx));\n\t\tif (A_n_i > A_n_k) {\n\t\t\t//coefficients\n\t\t\tdouble a = B_ik*B_ik - 1;\n\t\t\tdouble b = 2.0*r_i*B_ik - 2.0*x_ik;\n\t\t\tdouble c = r_i*r_i - x_ik*x_ik - A_n_k / M_PI;\n\n\t\t\t//! dx should be negative\n\t\t\tdx_i = min((-b - sqrt(b*b - 4 * a*c)) / 2.0 / a, (-b + sqrt(b*b - 4 * a*c)) / 2.0 / a);\n\n\t\t\t//! re-calculate change in radis\n\t\t\tdr_i = B_ik * dx_i;\n\n\t\t\tassert(dx_i <= 0.0);\n\t\t\tassert(dr_i >= 0.0);\n\t\t}\n\t\telse{\n\t\t\tdx_i = dx_max;\n\t\t}\n\n\t\t//! update connectivity ignoring small (merged) primary\n\t\tif (m_parent != NULL) UpdateConnectivity(this, dr_i, small_prim);\n\n\t\t//! update radius and x_ik\n\t\tr_i += dr_i;\n\t\tm_primarydiam += 2.0*dr_i;\n\t\tx_ik += dx_i;\n\n\t\t// if(x_ik <=0.0) break; //break if neck reaches maximum //csl37- necesssary?\n\n\t}\n\n\treturn x_ik;\n}\n\n//! From bintree model//\n/*!\n*  Calculates distance between two points\n*\n*  @param[in]    x_i\tCoordinates\n*  @param[in]    x_j\tCoordinates\n*  @param[out]   Separation\n*/\ndouble PAHPrimary::Separation(Coords::Vector x_i, Coords::Vector x_j)\n{\n\tCoords::Vector delta_x;\n\tdouble len_delta_x;\n\n\t//calculate difference x_j - x_i\n\tdelta_x[0] = x_j[0] - x_i[0];\n\tdelta_x[1] = x_j[1] - x_i[1];\n\tdelta_x[2] = x_j[2] - x_i[2];\n\n\t//calculate the length of the vector\n\tlen_delta_x = sqrt(delta_x[0] * delta_x[0] + delta_x[1] * delta_x[1] + delta_x[2] * delta_x[2]);\n\n\treturn len_delta_x;\n}\n\n//! From bintree model//\n/*!\n* @brief       Sinters particles for time dt\n*\n* This function only operates on non-leaf nodes. It begins at the root\n* node, which sinters for time dt. It then descends the tree to sinter\n* nodes below the root. If the sintering level rises above 95%, Merge\n* is called and the particles are combined.\n*\n* @param[in]   dt      Time for which to sinter\n* @param[in]   sys     Environment for particles\n* @param[in]   model   Sintering model to apply\n* @param[in]   rng     Random number generator\n* @param[in]   wt      Statistical weight\n*/\nvoid PAHPrimary::Sinter(double dt, Cell &sys,\n\tconst Processes::SinteringModel &model,\n\trng_type &rng,\n\tdouble wt)\n{\n\t// Only update the time on the root node\n\tif (m_parent == NULL) {\n\t\tm_sint_time += dt;\n\t\tSetSinteringTime(m_sint_time);\n\t}\n\n\t// Do only if there is a particle to sinter\n\tif (m_leftparticle != NULL && m_rightparticle != NULL) {\n\n\t\tSinterNode(dt, sys, model, rng, wt);\n\n\t\t// Check if the sintering level is above the threshold, and merge\n\t\tif (!m_pmodel->getTrackPrimarySeparation() && !m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\tbool Condition;\n\t\t\tCondition = (m_children_roundingLevel > 0.95);\n\t\t\tif (Condition) {\n\t\t\t\tCheckRounding();\n\t\t\t\tUpdateCache();\n\n\t\t\t\tif (m_leftchild != NULL && m_rightchild != NULL) {\n\t\t\t\t\tm_leftchild->Sinter(dt, sys, model, rng, wt);\n\t\t\t\t\tm_rightchild->Sinter(dt, sys, model, rng, wt);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tm_leftchild->Sinter(dt, sys, model, rng, wt);\n\t\t\t\tm_rightchild->Sinter(dt, sys, model, rng, wt);\n\t\t\t}\n\t\t}\n\t\telse{ //track\n\n\t\t\tif (MergeCondition()) {\n\t\t\t\tCheckSintering();\n\t\t\t}\n\n\t\t\tif (m_leftchild != NULL && m_rightchild != NULL) {\n\t\t\t\tm_leftchild->Sinter(dt, sys, model, rng, wt);\n\t\t\t\tm_rightchild->Sinter(dt, sys, model, rng, wt);\n\t\t\t}\n\t\t}\n\n\t\tUpdateCache();\n\n\t\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates())\n\t\t\tm_children_sintering = SinteringLevel();\n\t\telse\n\t\t\tm_children_roundingLevel = RoundingLevel();\n\n\t}\n\n}\n\n//! Learn from bintree model.\n/*!\n* @brief       Adjusts one primary of a particle after all PAHs in it has been updated by KMC-ARS code.\n*\n* Analogous to the implementation in Adjust() in bintree model. However, since only one primary is updated\n* here, not the whole particle, so there is no need to climb or descend the tree.\n*\n* @param[in]   old_vol   Volume of the primary before surface growth.\n*/\nvoid PAHPrimary::Adjust(const double old_vol)\n{\n\tdouble dV(0.0);\n\tdouble m_vol_old = old_vol;\n\n\t//! If the distance between the centres of primary particles or the\n\t//! primary coordinates is tracked, the rate of change in the\n\t//! primary diameter is affected by its neighbours.\n\tif (m_pmodel->getTrackPrimarySeparation() || m_pmodel->getTrackPrimaryCoordinates()) {\n\n\t\t//! Particle with more than one primary.\n\t\tif (m_parent != NULL) {\n\n\t\t\twhile (m_vol_old <= m_vol){\n\n\t\t\t\t//! Initialisation of variables to adjust the primary diameter if the\n\t\t\t\t//! distance between the centres of primary particles is tracked.\n\t\t\t\tdouble r_i = m_primarydiam / 2.0;\t//!< Radius of primary particle i.\n\t\t\t\tdouble dr_max = 0.01*r_i;\t\t\t//!< Maximum change in primary radius during internal step (1% of primary radius)\n\t\t\t\tdouble dr = 0.0;\t\t\t\t\t//!< Change in radius of i\n\n\t\t\t\t//Calculate change in volume\n\t\t\t\tdV = dr_max * m_free_surf;\n\n\t\t\t\t//Calculate change in radius\n\t\t\t\tif (m_vol_old + dV > m_vol){\n\t\t\t\t\tdr = (m_vol - m_vol_old)*dr_max / dV;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tdr = dr_max;\n\t\t\t\t}\n\n\t\t\t\t//Update primary diameter\n\t\t\t\tm_primarydiam = 2.0* (r_i + dr);\n\n\t\t\t\t//! Update free surface area\n\t\t\t\tthis->UpdateOverlappingPrimary();\n\n\t\t\t\tm_vol_old += dV;\n\t\t\t}\n\n\t\t\t//if coordinates are tracked then update coordinate tracking properties\n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()){\n\t\t\t\tsetRadius(m_primarydiam / 2.0);\n\t\t\t\tthis->calcBoundSph();\n\t\t\t\tthis->calcCOM();\n\t\t\t}\n\n\t\t}\n\t\t//! Single primary case: the primary diameter equals the\n\t\t//! spherical diameter                \n\t\telse {\n\t\t\tm_primarydiam = m_diam;\n\n\t\t\tif (m_pmodel->getTrackPrimaryCoordinates()) {\n\t\t\t\tsetRadius(m_primarydiam / 2.0);\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n\n//! From bintree model.\n/*!\n*  Print primary particle details and connectivity\n*\n*  @param[in]    surface\t\t\tPrimary connectivity\n*  @param[in]    primary_diameter\tPrimary details\n*  @param[in]    k\t\t\t\t\tParticle counter\n*/\nvoid PAHPrimary::PrintPrimary(vector<fvector> &surface, vector<fvector> &primary_diameter, int k) const\n{\n\tfvector node(10);\n\tfvector primary(10);\n\n\tif ((m_leftchild == NULL) && (m_rightchild == NULL)){\n\t\t//if leaf then print diameter\n\t\tprimary[0] = k + 1;\n\t\tprimary[1] = m_primarydiam;\n\t\tprimary[2] = m_diam;\n\t\tprimary[3] = m_primaryvol;\n\t\tprimary[4] = m_vol;\n\t\tprimary[5] = m_free_surf;\n\t\tvector<fvector> coords;\n\t\tthis->GetPriCoords(coords);\n\t\tprimary[6] = coords[0][0];\n\t\tprimary[7] = coords[0][1];\n\t\tprimary[8] = coords[0][2];\n\t\tprimary[9] = coords[0][3];\n\n\t\tprimary_diameter.push_back(primary);\n\n\t\tif (m_parent == NULL){\t//single particle case\n\t\t\tnode[0] = k + 1;\n\t\t\tnode[1] = m_numprimary;\n\t\t\tnode[2] = 0.0;\n\t\t\tnode[3] = 1.0;\n\t\t\tnode[4] = 0.0;\n\t\t\tnode[5] = 0.0;\n\t\t\tnode[6] = m_primarydiam / 2.0;\n\t\t\tnode[7] = 0.0;\n\t\t\tnode[8] = reinterpret_cast<uintptr_t>(this);\t//print pointer\n\t\t\tnode[9] = 0.0;\n\n\t\t\tsurface.push_back(node);\n\t\t}\n\t}\n\telse {\n\n\t\tdouble r_i = m_leftparticle->m_primarydiam / 2.0;\n\t\tdouble r_j = m_rightparticle->m_primarydiam / 2.0;\n\t\tdouble d_ij = m_distance_centreToCentre;\n\n\t\tdouble x_ij = (d_ij*d_ij - r_j*r_j + r_i*r_i) / (2.0*d_ij);\n\t\tdouble R_ij = sqrt(r_i*r_i - x_ij*x_ij);\t//!neck radius\n\n\t\t//if non-leaf node then print node and continue down the tree\n\t\tnode[0] = k + 1;\n\t\tnode[1] = m_numprimary;\n\t\tnode[2] = m_children_surf;\n\t\tnode[3] = m_children_sintering;\n\t\tnode[4] = d_ij;\n\t\tnode[5] = R_ij;\n\t\tnode[6] = r_i;\n\t\tnode[7] = r_j;\n\t\tnode[8] = reinterpret_cast<uintptr_t>(m_leftparticle);\t//print pointer\n\t\tnode[9] = reinterpret_cast<uintptr_t>(m_rightparticle);\t//print pointer\n\n\t\tsurface.push_back(node);\n\n\t\tm_leftchild->PrintPrimary(surface, primary_diameter, k);\n\t\tm_rightchild->PrintPrimary(surface, primary_diameter, k);\n\t}\n}\n\n//! Used to calculate the geometric volume of a particle if primary coordinates are tracked.\n//! Returns the cap volume of two connected primary parti\ndouble PAHPrimary::CalcChildrenSumCap()\n{\n\tif (m_leftchild != NULL && m_rightchild != NULL) {\n\n\t\tif (m_leftparticle != NULL && m_rightparticle != NULL) {\n\n\t\t\tdouble r_i = m_leftparticle->m_primarydiam / 2.0;\n\t\t\tdouble r_j = m_rightparticle->m_primarydiam / 2.0;\n\t\t\tdouble d_ij = m_distance_centreToCentre;\n\t\t\tdouble x_ij = (pow(d_ij, 2.0) - pow(r_j, 2.0) + pow(r_i, 2.0)) / (2.0*d_ij);\n\t\t\tdouble x_ji = (pow(d_ij, 2.0) - pow(r_i, 2.0) + pow(r_j, 2.0)) / (2.0*d_ij);\n\t\t\tdouble V_cap = 0.0;\n\t\t\tV_cap = V_cap + M_PI*(2 * pow(r_i, 3.0) + pow(x_ij, 3.0) - 3 * r_i*r_i*x_ij) / 3;\n\t\t\tV_cap = V_cap + M_PI*(2 * pow(r_j, 3.0) + pow(x_ji, 3.0) - 3 * r_j*r_j*x_ji) / 3;\n\n\t\t\treturn V_cap;\n\t\t}\n\t\telse{\n\t\t\treturn 0.0;\n\t\t}\n\n\t}\n\telse{ //this is a single primary\n\t\t\n\t\treturn 0.0;\n\n\t}\n\n}", "meta": {"hexsha": "775475451762e77a368dc35dfeb76a93b9951879", "size": 189863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_PAH_primary.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_PAH_primary.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_PAH_primary.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 32.9680500087, "max_line_length": 224, "alphanum_fraction": 0.6598494704, "num_tokens": 55770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.04146227670888889, "lm_q1q2_score": 0.018632841761114422}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n\nclass MatrixReplacement;\ntemplate<typename Rhs> class MatrixReplacement_ProductReturnType;\n\nnamespace Eigen {\nnamespace internal {\n  template<>\n  struct traits<MatrixReplacement> :  Eigen::internal::traits<Eigen::SparseMatrix<double> >\n  {};\n\n  template <typename Rhs>\n  struct traits<MatrixReplacement_ProductReturnType<Rhs> > {\n    // The equivalent plain objet type of the product. This type is used if the product needs to be evaluated into a temporary.\n    typedef Eigen::Matrix<typename Rhs::Scalar, Eigen::Dynamic, Rhs::ColsAtCompileTime> ReturnType;\n  };\n}\n}\n\n// Inheriting EigenBase should not be needed in the future.\nclass MatrixReplacement : public Eigen::EigenBase<MatrixReplacement> {\npublic:\n  // Expose some compile-time information to Eigen:\n  typedef double Scalar;\n  typedef double RealScalar;\n  enum {\n    ColsAtCompileTime = Eigen::Dynamic,\n    RowsAtCompileTime = Eigen::Dynamic,\n    MaxColsAtCompileTime = Eigen::Dynamic,\n    MaxRowsAtCompileTime = Eigen::Dynamic\n  };\n\n  Index rows() const { return 4; }\n  Index cols() const { return 4; }\n\n  void resize(Index a_rows, Index a_cols)\n  {\n    // This method should not be needed in the future.\n    assert(a_rows==0 && a_cols==0 || a_rows==rows() && a_cols==cols());\n  }\n\n  // In the future, the return type should be Eigen::Product<MatrixReplacement,Rhs>\n  template<typename Rhs>\n  MatrixReplacement_ProductReturnType<Rhs> operator*(const Eigen::MatrixBase<Rhs>& x) const {\n    return MatrixReplacement_ProductReturnType<Rhs>(*this, x.derived());\n  }\n\n};\n\n// The proxy class representing the product of a MatrixReplacement with a MatrixBase<>\ntemplate<typename Rhs>\nclass MatrixReplacement_ProductReturnType : public Eigen::ReturnByValue<MatrixReplacement_ProductReturnType<Rhs> > {\npublic:\n  typedef MatrixReplacement::Index Index;\n  \n  // The ctor store references to the matrix and right-hand-side object (usually a vector).\n  MatrixReplacement_ProductReturnType(const MatrixReplacement& matrix, const Rhs& rhs)\n    : m_matrix(matrix), m_rhs(rhs)\n  {}\n  \n  Index rows() const { return m_matrix.rows(); }\n  Index cols() const { return m_rhs.cols(); }\n\n  // This function is automatically called by Eigen. It must evaluate the product of matrix * rhs into y.\n  template<typename Dest>\n  void evalTo(Dest& y) const\n  {\n    y.setZero(4);\n\n    y(0) += 2 * m_rhs(0); y(1) += 1 * m_rhs(0);\n    y(0) += 1 * m_rhs(1); y(1) += 2 * m_rhs(1); y(2) += 1 * m_rhs(1);\n    y(1) += 1 * m_rhs(2); y(2) += 2 * m_rhs(2); y(3) += 1 * m_rhs(2);\n    y(2) += 1 * m_rhs(3); y(3) += 2 * m_rhs(3);\n  }\n\nprotected:\n  const MatrixReplacement& m_matrix;\n  typename Rhs::Nested m_rhs;\n};\n\n\n/*****/\n\n// This class simply warp a diagonal matrix as a Jacobi preconditioner.\n// In the future such simple and generic wrapper should be shipped within Eigen itsel.\ntemplate <typename _Scalar>\nclass MyJacobiPreconditioner\n{\n    typedef _Scalar Scalar;\n    typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1> Vector;\n    typedef typename Vector::Index Index;\n\n  public:\n    // this typedef is only to export the scalar type and compile-time dimensions to solve_retval\n    typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MatrixType;\n\n    MyJacobiPreconditioner() : m_isInitialized(false) {}\n\n    void setInvDiag(const Eigen::VectorXd &invdiag) {\n      m_invdiag=invdiag;\n      m_isInitialized=true;\n    }\n\n    Index rows() const { return m_invdiag.size(); }\n    Index cols() const { return m_invdiag.size(); }\n    \n    template<typename MatType>\n    MyJacobiPreconditioner& analyzePattern(const MatType& ) { return *this; }\n    \n    template<typename MatType>\n    MyJacobiPreconditioner& factorize(const MatType& mat) { return *this; }\n    \n    template<typename MatType>\n    MyJacobiPreconditioner& compute(const MatType& mat) { return *this; }\n\n    template<typename Rhs, typename Dest>\n    void _solve(const Rhs& b, Dest& x) const\n    {\n      x = m_invdiag.array() * b.array() ;\n    }\n\n    template<typename Rhs> inline const Eigen::internal::solve_retval<MyJacobiPreconditioner, Rhs>\n    solve(const Eigen::MatrixBase<Rhs>& b) const\n    {\n      eigen_assert(m_isInitialized && \"MyJacobiPreconditioner is not initialized.\");\n      eigen_assert(m_invdiag.size()==b.rows()\n                && \"MyJacobiPreconditioner::solve(): invalid number of rows of the right hand side matrix b\");\n      return Eigen::internal::solve_retval<MyJacobiPreconditioner, Rhs>(*this, b.derived());\n    }\n\n  protected:\n    Vector m_invdiag;\n    bool m_isInitialized;\n};\n\nnamespace Eigen {\nnamespace internal {\n\ntemplate<typename _MatrixType, typename Rhs>\nstruct solve_retval<MyJacobiPreconditioner<_MatrixType>, Rhs>\n  : solve_retval_base<MyJacobiPreconditioner<_MatrixType>, Rhs>\n{\n  typedef MyJacobiPreconditioner<_MatrixType> Dec;\n  EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)\n\n  template<typename Dest> void evalTo(Dest& dst) const\n  {\n    dec()._solve(rhs(),dst);\n  }\n};\n\n}\n}\n\n\n/*****/\n\n\nint main()\n{\n  MatrixReplacement A;\n  Eigen::VectorXd b(4), x;\n  b << 1, 1, 1, 1;\n\n  // solve Ax = b using CG with matrix-free version:\n  Eigen::ConjugateGradient < MatrixReplacement, Eigen::Lower|Eigen::Upper, MyJacobiPreconditioner<double> > cg;\n\n  Eigen::VectorXd invdiag(4);\n  invdiag << 1./3., 1./4., 1./4., 1./3.;\n\n  cg.preconditioner().setInvDiag(invdiag);\n  cg.compute(A);\n  x = cg.solve(b);\n\n  std::cout << \"#iterations: \" << cg.iterations() << std::endl;\n  std::cout << \"estimated error: \" << cg.error() << std::endl;\n}\n", "meta": {"hexsha": "f0631c3a31654bd6376c8457ded78f6d838dd1cf", "size": 5540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/doc/examples/matrixfree_cg.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/doc/examples/matrixfree_cg.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "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": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/doc/examples/matrixfree_cg.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 30.6077348066, "max_line_length": 127, "alphanum_fraction": 0.6994584838, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.03904828979072011, "lm_q1q2_score": 0.018609620323094687}}
{"text": "//////////////////////////////////////////////////////////////////////\n// This file is distributed under the University of Illinois/NCSA Open Source\n// License.  See LICENSE file in top directory for details.\n//\n// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.\n//\n// File developed by:\n// Miguel A. Morales, moralessilva2@llnl.gov \n//    Lawrence Livermore National Laboratory \n//\n// File created by:\n// Miguel A. Morales, moralessilva2@llnl.gov \n//    Lawrence Livermore National Laboratory \n////////////////////////////////////////////////////////////////////////////////\n\n#ifndef QMCPLUSPLUS_AFQMC_EXCITATIONS_HPP\n#define QMCPLUSPLUS_AFQMC_EXCITATIONS_HPP\n\n#include <boost/iterator/iterator_facade.hpp>\n#include <map>\n#include \"AFQMC/config.h\"\n#include \"AFQMC/Matrix/array_of_sequences.hpp\"\n\nnamespace qmcplusplus\n{\n\nnamespace afqmc\n{\n\n// CHEAT!!! \ntemplate<class TP, class integer>\nsize_t get_index(TP const& tp_, integer loc)\n{\n  if(loc == 0) return size_t(std::get<0>(tp_));\n  else if(loc == 1) return size_t(std::get<1>(tp_));\n  else throw std::runtime_error(\" Error in qmcplusplus::afqmc::get_index<TP,integer>(). \\n\");\n}\n\ntemplate<class Vector>\nvoid push_excitation(Vector const& abij, Vector& v)\n{\n  if(abij.size()==0) return; \n  assert(v.size()%abij.size()==0);\n  size_t n = abij.size();\n  for(typename Vector::iterator it=v.begin(); it<v.end(); it+=n) \n    if( std::equal(abij.begin(),abij.end(),it) ) return;\n  v.insert(v.end(),abij.begin(),abij.end());\n}\n\ntemplate<class Vector>\nsize_t find_excitation(Vector const& abij, Vector& v)\n{\n  if(abij.size()==0) return 0;  // this assumes that the reference is 0 \n  assert(v.size()%abij.size()==0);\n  size_t n = abij.size();\n  size_t loc=0;\n  for(typename Vector::iterator it=v.begin(); it<v.end(); it+=n, loc++) \n    if( std::equal(abij.begin(),abij.end(),it) ) return loc;\n  APP_ABORT(\"Error: Sequence not found in find_excitation.\\n\");\n  return 0;\n}\n\ntemplate<class excitations>\nstd::map<int,int> find_active_space(bool single_list, excitations const& abij, int NMO, int NAEA, int NAEB)\n{\n  std::map<int,int> mo2active;\n  for(int i=0; i<2*NMO; i++) mo2active[i]=-1;\n  std::vector<size_t> count(2*NMO);\n  // reference first\n  auto refc = abij.reference_configuration();\n  for(int i=0; i<NAEA+NAEB; i++, ++refc) ++count[*refc];\n  auto nex = abij.maximum_excitation_number();\n  for(int n=1; n<nex[0]; ++n) {\n    auto it = abij.alpha_begin(n);\n    auto itend = abij.alpha_end(n);\n    for(; it<itend; ++it) {\n      auto exct = *it+n; // skip locations\n      for(int ak=0; ak<n; ++ak, ++exct)\n        ++count[*exct];\n    }\n  }\n  for(int n=1; n<nex[1]; ++n) {\n    auto it = abij.beta_begin(n);\n    auto itend = abij.beta_end(n);\n    for(; it<itend; ++it) {\n      auto exct = *it+n; // skip locations\n      for(int ak=0; ak<n; ++ak, ++exct)\n        ++count[*exct];\n    }\n  }\n  if(not single_list) {\n    int ik=0;\n    for(int i=0; i<NMO; ++i)\n      if(count[i]>0 || count[i+NMO]>0) {\n        if(count[i]>0) mo2active[i] = ik;\n        if(count[i+NMO]>0) mo2active[i+NMO] = ik;\n        ++ik;\n      }\n  } else {  \n    int ik=0;\n    for(int i=0; i<NMO; ++i)\n      if(count[i]>0) mo2active[i] = ik++;\n    ik=0;\n    for(int i=NMO; i<2*NMO; ++i)\n      if(count[i]>0) mo2active[i] = ik++;\n  }\n  return mo2active;\n}\n\n/*\n * - exct stores, for each electron excitaion, the location of the orbital in the reference \n *    being excited and the index of the excited orbital.\n */\ntemplate<class Vector, class T>\nint get_excitation_number(bool getIndx, Vector& refc, Vector& confg, Vector& exct, T& ci, Vector& Iwork) {\n  int NE = refc.size();\n  exct.clear();\n  int cnt=0;\n  if(getIndx) std::copy(refc.begin(),refc.end(),Iwork.begin());\n  auto it = refc.data();\n  assert(Iwork.size() >= refc.size());  \n  for(int i=0; i<NE; i++,it++)\n    if(!std::binary_search(confg.begin(),confg.end(),*it)) {\n      if(getIndx) {\n        // store the location, NOT the index!!!\n        //exct.emplace_back(*it);\n        exct.emplace_back(i);\n      }\n      cnt++;\n    }\n  if(!getIndx)\n    return cnt;\n  it = confg.data();\n  int cnt2=0;\n  for(int i=0; i<NE; i++,it++)\n    if(!std::binary_search(refc.begin(),refc.end(),*it)) {\n      exct.emplace_back(*it);\n      Iwork[exct[cnt2]]=*it;\n      cnt2++;\n    }\n  assert(cnt==cnt2);\n  // sort Iwork and count number of exchanges to determine permutation sign\n  // sooo slow but sooo simple too\n  for(int i=0; i<NE; i++)\n    for(int j=i+1; j<NE; j++)\n    {\n      if(Iwork[j] < Iwork[i])\n      {\n        ci *= T(-1.0);\n        std::swap(Iwork[i],Iwork[j]);\n      }\n    }\n  return cnt;\n}\n\ntemplate<typename intT, class csr>\ninline std::vector<size_t> get_nnz(csr const& PsiT_MO, intT* refc, size_t N, size_t shift)\n{\n  std::vector<size_t> res(N);\n  for(size_t i=0; i<N; i++)\n    res[i] = PsiT_MO.num_non_zero_elements(*(refc+i)-shift);\n  return res;\n}\n\n\n// try putting this in shared memory later on\ntemplate<class I = int,\n\t class VType = std::complex<double>,\t\n         class Alloc = shared_allocator<I>,\n         class is_root = ma::sparse::is_root>\nstruct ph_excitations\n{\n  public:\n  using integer_type = I;\n  using configuration_type = std::tuple<int,int,VType>;\n\n  private:\n  using IAllocator = Alloc;\n  using CAllocator = typename Alloc::template rebind<configuration_type>::other;\n  using confg_aos = ma::sparse::array_of_sequences<configuration_type,int,CAllocator,is_root>;\n  using index_aos = ma::sparse::array_of_sequences<integer_type,int,IAllocator,is_root>;\n\n  IAllocator i_allocator_;\n  CAllocator c_allocator_;\n\n  template< typename Integer>\n  class Iterator: public boost::iterator_facade< Iterator<Integer>,\n                                               Integer*,\n                                               std::random_access_iterator_tag,\n                                               Integer*,\n                                               std::ptrdiff_t\n                                             >\n  { \n    public: \n      using difference_type = std::ptrdiff_t;\n      using reference = Integer *;\n      using const_reference = Integer const*;\n      using value_tupe = Integer*;\n    \n      Iterator(Integer* index, size_t d_) : p_index(index),D(d_) {}\n        \n        // What we implement is determined by the boost::forward_traversal_tag\n    private: \n      friend class boost::iterator_core_access;\n    \n      void increment() { p_index+=2*D; }\n    \n      bool equal(Iterator const& other) const\n      {   \n        return this->p_index == other.p_index;\n      }\n    \n      reference dereference() const\n      {   \n        return reference(p_index);\n      }\n    \n      void decrement() { p_index-=2*D; }\n    \n      void advance(int n) { p_index+=2*D*n; }\n    \n      difference_type distance_to(Iterator const& z) const { return ((z.p_index-p_index)/2/D); }\n  \n    private:\n      Integer* p_index;\n      size_t D;\n  };\n\n  template< typename Integer>\n  class Iterator_const: public boost::iterator_facade< Iterator_const<Integer>,\n                                               Integer const*,\n                                               std::random_access_iterator_tag,\n                                               Integer const*,\n                                               std::ptrdiff_t\n                                             >\n  {\n    public:\n      using difference_type = std::ptrdiff_t;\n      using reference = Integer const*;\n      using const_reference = Integer const*;\n      using value_tupe = Integer*;\n\n      Iterator_const(Integer * index, size_t d_) : p_index(index),D(d_) {}\n      Iterator_const(Integer const* index, size_t d_) : p_index(index),D(d_) {}\n\n        // What we implement is determined by the boost::forward_traversal_tag\n    private:\n      friend class boost::iterator_core_access;\n\n      void increment() { p_index+=2*D; }\n\n      bool equal(Iterator_const const& other) const\n      {\n        return this->p_index == other.p_index;\n      }\n\n      reference dereference() const\n      {\n        return reference(p_index);\n      }\n\n      void decrement() { p_index-=2*D; }\n\n      void advance(int n) { p_index+=2*D*n; }\n\n      difference_type distance_to(Iterator_const const& z) const { return ((z.p_index-p_index)/2/D); }\n\n    private:\n      Integer* p_index;\n      size_t D;\n  };\n\n  public:\n\n  using Excitation_Iterator = Iterator<integer_type>;\n  using Excitation_const_Iterator = Iterator_const<integer_type>;\n\n  ph_excitations() = delete;\n\n  // Note: terms_per_excitation[0] has special meaning, the number of electrons in the calculation.\n  // coefficients[0] will store the reference configuration itself.\n  ph_excitations(size_t number_of_configurations,\n                 int na_, int nb_,\n                 std::vector<size_t>& unique_alpha_counts, \n                 std::vector<size_t>& unique_beta_counts, \n                 Alloc alloc_ = Alloc{}):\n                 i_allocator_(alloc_),\n                 c_allocator_(alloc_),\n                 NAEA(na_),NAEB(nb_),\n                 configurations(1,number_of_configurations,c_allocator_),\n                 reference(1,NAEA+NAEB,i_allocator_),\n                 unique_alpha(unique_alpha_counts.size(),unique_alpha_counts,i_allocator_),\n                 unique_beta(unique_beta_counts.size(),unique_beta_counts,i_allocator_)\n  { \n    size_t emax = std::max(unique_alpha_counts.size(),unique_beta_counts.size());\n    sum_of_exct.resize(emax+1);\n    sum_of_exct[0] = {0,0};\n    sum_of_exct[1] = {1,1};\n    for(size_t n=1; n<unique_alpha.size(); ++n) \n      sum_of_exct[n+1][0] = sum_of_exct[n][0]+unique_alpha_counts[n]/size_t(2)/n;\n    for(size_t n=unique_alpha.size()+1; n<=emax; n++)\n      sum_of_exct[n][0]=sum_of_exct[n-1][0];\n    for(size_t n=1; n<unique_beta.size(); ++n)\n      sum_of_exct[n+1][1] = sum_of_exct[n][1]+unique_beta_counts[n]/size_t(2)/n;\n    for(size_t n=unique_beta.size()+1; n<=emax; n++)\n      sum_of_exct[n][1]=sum_of_exct[n-1][1];\n  }\n\n  ph_excitations(ph_excitations const& other) = delete;\n  //ph_excitations(ph_excitations && other) = default;\n  ph_excitations(ph_excitations && other):\n                 i_allocator_(other.i_allocator_),\n                 c_allocator_(other.c_allocator_),\n                 NAEA(other.NAEA),NAEB(other.NAEB),\n                 configurations(std::move(other.configurations)),\n                 reference(std::move(other.reference)),\n                 unique_alpha(std::move(other.unique_alpha)),\n                 unique_beta(std::move(other.unique_beta)),\n                 sum_of_exct(std::move(other.sum_of_exct)) \n  {}\n\n  ph_excitations& operator=(ph_excitations const& other) = delete;\n  ph_excitations& operator=(ph_excitations && other) = default;\n\n  std::array<size_t,2> maximum_excitation_number() const\n  { return {unique_alpha.size(),unique_beta.size()}; } \n  size_t number_of_unique_alpha_excitations(int n) const\n  { \n    if(n==0) return 1;\n    return unique_alpha.num_elements(n)/2/n;\n  }\n  size_t number_of_unique_beta_excitations(int n) const\n  { \n    if(n==0) return 1;\n    return unique_beta.num_elements(n)/2/n;\n  }\n  std::array<size_t,2> number_of_unique_excitations(int n) const\n  { \n    if(n==0) return {1,1};\n    std::array<size_t,2> res{0,0};\n    if(n < unique_alpha.size()) res[0] = unique_alpha.num_elements(n)/2/n;\n    if(n < unique_beta.size()) res[1] = unique_beta.num_elements(n)/2/n;\n    return res; \n  } \n  std::array<size_t,2> number_of_unique_excitations() const\n  { \n    return sum_of_exct.back();\n  } \n\n  size_t number_of_configurations() const { return configurations.num_elements(0); }\n  \n  // returns the number of unique excitations with particle number less than n\n  std::array<size_t,2> number_of_unique_smaller_than(int n) const { return sum_of_exct[n]; }\n\n  template<class intIt>\n  void add_alpha(size_t n, intIt indx) {\n    assert(n<unique_alpha.size());\n    assert(n>0);\n    for(int i=0; i<2*n; i++, ++indx)\t\n      unique_alpha.emplace_back(n,static_cast<integer_type>(*indx));\t\n  }\n\n  template<class intIt>\n  void add_beta(size_t n, intIt indx) {\n    assert(n<unique_beta.size());\n    assert(n>0);\n    for(int i=0; i<2*n; i++, ++indx)\n      unique_beta.emplace_back(n,static_cast<integer_type>(*indx));\n  }\n\n  template<class Vector>\n  void add_reference(Vector& refa, Vector& refb) {\n    for(auto k: refa)\n      reference.emplace_back(0,static_cast<integer_type>(k));  \n    for(auto k: refb)\n      reference.emplace_back(0,static_cast<integer_type>(k));  \n  }\n \n  // index=0 is reserved for the reference!!! \n  template<typename integer, typename value>\n  void add_configuration(integer alpha_indx, integer beta_index, value ci) {\n    configurations.emplace_back(0,configuration_type{alpha_indx,beta_index,ci});\n  }\n\n  typename Excitation_Iterator::const_reference reference_configuration(int spin=0) const{\n    return to_address(reference.values(0)) + (spin==0?0:NAEA);\n  }\n\n  typename Excitation_Iterator::reference reference_configuration(int spin=0) {\n    return to_address(reference.values(0)) + (spin==0?0:NAEA);\n  }\n\n  configuration_type const* configurations_begin() const {\n    return to_address(configurations.values(0));\n  }\n\n  configuration_type const* configurations_end() const {\n    return to_address(configurations.values()) + (*configurations.pointers_end(0));\n  }\n\n  configuration_type const* configuration(int i) const {\n    return to_address(configurations.values()) + i; \n  }\n\n  Excitation_Iterator alpha_begin(int n) {\n    assert(n>0);\n    if(n<unique_alpha.size()) {\n      return Excitation_Iterator(to_address(unique_alpha.values(n)),n); \n    } else\n      return alpha_end(n); \n  }\n\n  Excitation_Iterator alpha_end(int n) {\n    assert(n>0);\n    if(n<unique_alpha.size())\n      return Excitation_Iterator(to_address(unique_alpha.values())\n                                    +(*unique_alpha.pointers_end(n)),n);\n    else\n      return Excitation_Iterator(to_address(unique_alpha.values())\n                                    +(*unique_alpha.pointers_end(unique_alpha.size()-1)),1);\n  }\n\n  Excitation_const_Iterator alpha_begin(int n) const {\n    assert(n>0);\n    if(n<unique_alpha.size()) {\n      return Excitation_const_Iterator(to_address(unique_alpha.values(n)),n);\n    } else\n      return alpha_end(n);\n  }\n\n  Excitation_const_Iterator alpha_end(int n) const {\n    assert(n>0);\n    if(n<unique_alpha.size())\n      return Excitation_const_Iterator(to_address(unique_alpha.values())\n                                    +(*unique_alpha.pointers_end(n)),n);\n    else\n      return Excitation_const_Iterator(to_address(unique_alpha.values())\n                                    +(*unique_alpha.pointers_end(unique_alpha.size()-1)),1);\n  }\n\n  Excitation_Iterator beta_begin(int n) {\n    assert(n>0);\n    if(n<unique_beta.size())\n      return Excitation_Iterator(to_address(unique_beta.values(n)),n);\n    else\n      return beta_end(n);\n  }\n\n  Excitation_Iterator beta_end(int n) {\n    assert(n>0);\n    if(n<unique_beta.size())\n      return Excitation_Iterator(to_address(unique_beta.values())\n                                    +(*unique_beta.pointers_end(n)),n);\n    else\n      return Excitation_Iterator(to_address(unique_beta.values())\n                                    +(*unique_beta.pointers_end(unique_beta.size()-1)),1);\n  }\n\n  Excitation_const_Iterator beta_begin(int n) const {\n    assert(n>0);\n    if(n<unique_beta.size())\n      return Excitation_const_Iterator(to_address(unique_beta.values(n)),n);\n    else\n      return beta_end(n);\n  }\n\n  Excitation_const_Iterator beta_end(int n) const {\n    assert(n>0);\n    if(n<unique_beta.size())\n      return Excitation_const_Iterator(to_address(unique_beta.values())\n                                    +(*unique_beta.pointers_end(n)),n);\n    else\n      return Excitation_const_Iterator(to_address(unique_beta.values())\n                                    +(*unique_beta.pointers_end(unique_beta.size()-1)),1);\n  }\n\n  // for generic access\n  std::array<Excitation_Iterator,2> unique_begin(int n) \n  {  return std::array<Excitation_Iterator,2>{alpha_begin(n),beta_begin(n)}; }\n  std::array<Excitation_Iterator,2> unique_end(int n) \n  {  return std::array<Excitation_Iterator,2>{alpha_end(n),beta_end(n)}; }\n  std::array<Excitation_const_Iterator,2> unique_begin(int n) const\n  {  return std::array<Excitation_const_Iterator,2>{alpha_begin(n),beta_begin(n)}; }\n  std::array<Excitation_const_Iterator,2> unique_end(int n) const\n  {  return std::array<Excitation_const_Iterator,2>{alpha_end(n),beta_end(n)}; }\n\n  template<class Vector>\n  void get_alpha_configuration(size_t index, Vector& confg) const{\n    assert(confg.size() >= NAEA); \n    std::copy_n(to_address(reference.values(0)),NAEA,confg.data());\n    if(index==0) return;\n    // could use lower bound \n    for(int i=1; i<unique_alpha.size(); i++) {\n      if(index >= sum_of_exct[i][0] && index < sum_of_exct[i+1][0]) {\n        size_t dn = index-sum_of_exct[i][0];\n        auto exct = unique_alpha.values(i) + 2*i*dn;\n        for(int n=0; n<i; n++)\n          confg[ exct[n] ] = exct[n+i];      \n        return;\n      }\n    } \n    APP_ABORT(\" Error in ph_excitations::get_alpha_configuration() \\n\");\n  }\n\n  template<class Vector>\n  void get_beta_configuration(size_t index, Vector& confg) const{\n    assert(confg.size() >= NAEB); \n    std::copy_n(to_address(reference.values(0))+NAEA,NAEB,confg.data());\n    if(index==0) return;\n    // could use lower bound \n    for(int i=1; i<unique_beta.size(); i++) {\n      if(index >= sum_of_exct[i][1] && index < sum_of_exct[i+1][1]) {\n        size_t dn = index-sum_of_exct[i][1];\n        auto exct = unique_beta.values(i) + 2*i*dn;\n        for(int n=0; n<i; n++)\n          confg[ exct[n] ] = exct[n+i];\n        return;\n      }\n    }\n    APP_ABORT(\" Error in ph_excitations::get_beta_configuration() \\n\");\n  } \n\n  template<class Vector>\n  void get_configuration(int spin, size_t index, Vector& confg) const{\n    if(spin==0)\n      get_alpha_configuration(index,confg);  \n    else\n      get_beta_configuration(index,confg);  \n  }\n\n  private:\n\n  // using array_of_seq until I switch to Boost.Multi to be able to use shared_allocator\n  int NAEA, NAEB;\n  confg_aos configurations;\n  index_aos reference; \n  index_aos unique_alpha; \n  index_aos unique_beta; \n  std::vector<std::array<size_t,2>> sum_of_exct;\n\n};\n\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "dcbabcfcaed279504b550a69307db0e7c4930c45", "size": 18191, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/AFQMC/Wavefunctions/Excitations.hpp", "max_stars_repo_name": "kayahans/qmcpack", "max_stars_repo_head_hexsha": "c25d77702e36363ff7368ded783bf31c1b1c5f17", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AFQMC/Wavefunctions/Excitations.hpp", "max_issues_repo_name": "kayahans/qmcpack", "max_issues_repo_head_hexsha": "c25d77702e36363ff7368ded783bf31c1b1c5f17", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AFQMC/Wavefunctions/Excitations.hpp", "max_forks_repo_name": "kayahans/qmcpack", "max_forks_repo_head_hexsha": "c25d77702e36363ff7368ded783bf31c1b1c5f17", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1952554745, "max_line_length": 107, "alphanum_fraction": 0.6244846353, "num_tokens": 4822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.04468087297585627, "lm_q1q2_score": 0.018538042626874803}}
{"text": "// Copyright (c) 2016 The UUV Simulator Authors.\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, 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// This source code is from rotors_simulator\n//   (https://github.com/ethz-asl/rotors_simulator)\n// * Copyright 2015 Fadri Furrer, ASL, ETH Zurich, Switzerland\n// * Copyright 2015 Michael Burri, ASL, ETH Zurich, Switzerland\n// * Copyright 2015 Mina Kamel, ASL, ETH Zurich, Switzerland\n// * Copyright 2015 Janosch Nikolic, ASL, ETH Zurich, Switzerland\n// * Copyright 2015 Markus Achtelik, ASL, ETH Zurich, Switzerland\n// This source code is licensed under the Apache-2.0 license found in the\n// open_source_licenses.txt file in the root directory of this source tree.\n//\n// The original code was modified by the UUV Simulator Authors to adhere to\n// Gazebo's coding standards.\n\n#ifndef UUV_SENSOR_PLUGINS_COMMON_H_\n#define UUV_SENSOR_PLUGINS_COMMON_H_\n\n#include <string>\n#include <Eigen/Dense>\n#include <gazebo/gazebo.hh>\n\nnamespace gazebo {\n\n/**\n * \\brief Obtains a parameter from sdf.\n * \\param[in] sdf Pointer to the sdf object.\n * \\param[in] name Name of the parameter.\n * \\param[out] param Param Variable to write the parameter to.\n * \\param[in] default_value Default value, if the parameter not available.\n * \\param[in] verbose If true, gzerror if the parameter is not available.\n */\ntemplate<class T>\nbool getSdfParam(sdf::ElementPtr sdf, const std::string& name, T& param,\n                 const T& default_value, const bool& verbose = false)\n{\n  if (sdf->HasElement(name))\n  {\n    param = sdf->GetElement(name)->Get<T>();\n    return true;\n  }\n  else\n  {\n    param = default_value;\n    if (verbose)\n      gzerr << \"[uuv_sensor_plugins] Please specify a value for parameter \\\"\"\n            << name << \"\\\".\\n\";\n  }\n  return false;\n}\n}  // namespace gazebo\n\ntemplate <typename T>\nclass FirstOrderFilter {\n/*\nThis class can be used to apply a first order filter on a signal.\nIt allows different acceleration and deceleration time constants.\n\nShort reveiw of discrete time implementation of firest order system:\nLaplace:\n    X(s)/U(s) = 1/(tau*s + 1)\ncontinous time system:\n    dx(t) = (-1/tau)*x(t) + (1/tau)*u(t)\ndiscretized system (ZoH):\n    x(k+1) = exp(samplingTime*(-1/tau))*x(k) + (1 - exp(samplingTime*(-1/tau))) * u(k)\n*/\n\n  public:\n    FirstOrderFilter(double timeConstantUp, double timeConstantDown,\n                     T initialState):\n      timeConstantUp_(timeConstantUp),\n      timeConstantDown_(timeConstantDown),\n      previousState_(initialState) {}\n\n    T updateFilter(T inputState, double samplingTime)\n    {\n      /*\n      This method will apply a first order filter on the inputState.\n      */\n      T outputState;\n      if (inputState > previousState_)\n      {\n        // Calcuate the outputState if accelerating.\n        double alphaUp = exp(- samplingTime / timeConstantUp_);\n        // x(k+1) = Ad*x(k) + Bd*u(k)\n        outputState = alphaUp * previousState_ + (1 - alphaUp) * inputState;\n      }\n      else\n      {\n        // Calculate the outputState if decelerating.\n        double alphaDown = exp(- samplingTime / timeConstantDown_);\n        outputState = alphaDown * previousState_ + (1 - alphaDown) * inputState;\n      }\n      previousState_ = outputState;\n      return outputState;\n    }\n    ~FirstOrderFilter() {}\n\n  protected:\n    double timeConstantUp_;\n    double timeConstantDown_;\n    T previousState_;\n};\n\n\n\n/// Computes a quaternion from the 3-element small angle approximation theta.\ntemplate<class Derived>\nEigen::Quaternion<typename Derived::Scalar> QuaternionFromSmallAngle(\n        const Eigen::MatrixBase<Derived> & theta)\n{\n  typedef typename Derived::Scalar Scalar;\n  EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived);\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);\n  const Scalar q_squared = theta.squaredNorm() / 4.0;\n\n  if (q_squared < 1)\n  {\n    return Eigen::Quaternion<Scalar>(sqrt(1 - q_squared), theta[0] * 0.5,\n            theta[1] * 0.5, theta[2] * 0.5);\n  }\n  else\n  {\n    const Scalar w = 1.0 / sqrt(1 + q_squared);\n    const Scalar f = w * 0.5;\n    return Eigen::Quaternion<Scalar>(w, theta[0] * f, theta[1] * f,\n            theta[2] * f);\n  }\n}\n\ntemplate<class In, class Out>\nvoid copyPosition(const In& in, Out* out)\n{\n  out->x = in.x;\n  out->y = in.y;\n  out->z = in.z;\n}\n\n#endif  // UUV_SENSOR_PLUGINS_COMMON_H_\n", "meta": {"hexsha": "c0b1d3ac7e599c6fb2af14bcd0141cfcab69b98f", "size": 4812, "ext": "hh", "lang": "C++", "max_stars_repo_path": "uuv_simulator/uuv_sensor_plugins/uuv_sensor_plugins/src/Common.hh", "max_stars_repo_name": "laughlinbarker/underice_ekf", "max_stars_repo_head_hexsha": "d74a83b2d02cef986fc904cf588a408382d728a6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-03T05:56:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T06:29:34.000Z", "max_issues_repo_path": "uuv_simulator/uuv_sensor_plugins/uuv_sensor_plugins/src/Common.hh", "max_issues_repo_name": "laughlinbarker/underice_ekf", "max_issues_repo_head_hexsha": "d74a83b2d02cef986fc904cf588a408382d728a6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-13T10:58:38.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T14:09:05.000Z", "max_forks_repo_path": "uuv_simulator/uuv_sensor_plugins/uuv_sensor_plugins/src/Common.hh", "max_forks_repo_name": "laughlinbarker/underice_ekf", "max_forks_repo_head_hexsha": "d74a83b2d02cef986fc904cf588a408382d728a6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T15:02:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-02T15:14:58.000Z", "avg_line_length": 31.4509803922, "max_line_length": 86, "alphanum_fraction": 0.6820448878, "num_tokens": 1256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.04468086693339587, "lm_q1q2_score": 0.01853804011986496}}
{"text": "\n// The quad_float module is derived from the doubledouble\n// library originally developed by Keith Briggs:\n//    http://keithbriggs.info/doubledouble.html\n// I attach the original copyright notice.\n\n\n/*\n\nCopyright (C) 1997 Keith Martin Briggs\n\nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n*/\n\n#if (defined(__GNUC__) && __FAST_MATH__)\n#error \"do not compile quad_float.cpp with -ffast-math!!\"\n#endif\n\n\n#ifdef __INTEL_COMPILER\n#pragma float_control(precise,on)\n#endif\n\n// NOTE: the above will force the Intel compiler to adhere to\n// language standards, which it does not do by default\n\n#include <NTL/quad_float.h>\n#include <NTL/RR.h>\n\n#include <cfloat>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n#if (NTL_EXT_DOUBLE && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))\n\n#if (!defined(NTL_X86_FIX) && !defined(NTL_NO_X86_FIX))\n\n#define NTL_X86_FIX\n\n#endif\n\n#endif\n\n\n#if (NTL_EXT_DOUBLE && !defined(NTL_X86_FIX))\n\n#define DOUBLE volatile double\n\n#else\n\n#define DOUBLE double\n\n#endif\n\n\n#ifdef NTL_X86_FIX\n\n\n#define START_FIX \\\n  volatile unsigned short __old_cw, __new_cw; \\\n  asm volatile (\"fnstcw %0\":\"=m\" (__old_cw)); \\\n  __new_cw = (__old_cw & ~0x300) | 0x200; \\\n  asm volatile (\"fldcw %0\": :\"m\" (__new_cw));\n\n\n#define END_FIX  asm volatile (\"fldcw %0\": :\"m\" (__old_cw));\n\n#else\n\n#define START_FIX\n#define END_FIX\n\n#endif\n\n\nstatic \nvoid normalize(quad_float& z, const double& xhi, const double& xlo)\n{\nSTART_FIX\n   DOUBLE u, v;\n\n   u = xhi + xlo; \n   v = xhi - u;    \n   v = v + xlo;    \n\n   z.hi = u;\n   z.lo = v;\nEND_FIX\n}\n\n\n\n#if (NTL_BITS_PER_LONG >= NTL_DOUBLE_PRECISION)\n\n\nquad_float to_quad_float(long n)\n{\n   DOUBLE xhi, xlo;\n\n   xhi = TrueDouble(n);\n\n   // Because we are assuming 2's compliment integer\n   // arithmetic, the following prevents long(xhi) from overflowing.\n\n   if (n > 0)\n      xlo = TrueDouble(n+long(-xhi));\n   else\n      xlo = TrueDouble(n-long(xhi));\n\n   // renormalize...just to be safe\n\n   quad_float z;\n   normalize(z, xhi, xlo);\n   return z;\n}\n\nquad_float to_quad_float(unsigned long n)\n{\n   DOUBLE xhi, xlo, t;\n\n   const double bnd = double(1L << (NTL_BITS_PER_LONG-2))*4.0;\n\n   xhi = TrueDouble(n);\n   \n   if (xhi >= bnd)\n      t = xhi - bnd;\n   else\n      t = xhi;\n\n   // we use the \"to_long\" function here to be as portable as possible.\n   long llo = to_long(n - (unsigned long)(t));\n   xlo = TrueDouble(llo);\n\n   quad_float z;\n   normalize(z, xhi, xlo);\n   return z;\n}\n#endif\n\n\nNTL_CHEAP_THREAD_LOCAL\nlong quad_float::oprec = 10;\n\nvoid quad_float::SetOutputPrecision(long p)\n{\n   if (p < 1) p = 1;\n\n   if (NTL_OVERFLOW(p, 1, 0)) \n      ResourceError(\"quad_float: output precision too big\");\n\n   oprec = p;\n}\n\n\nquad_float operator +(const quad_float& x, const quad_float& y ) {\nSTART_FIX\n        DOUBLE    H, h, T, t, S, s, e, f;\n        DOUBLE    t1;\n\n        S = x.hi + y.hi;\n        T = x.lo + y.lo;\n        e = S - x.hi;\n        f = T - x.lo;\n\n        t1 = S-e;\n        t1 = x.hi-t1;\n        s = y.hi-e;\n        s = s + t1;\n        \n        t1 = T-f;\n        t1 = x.lo-t1;\n        t = y.lo-f;\n        t = t + t1;\n\n\n        s = s + T;\n        H = S + s;\n        h = S - H;\n        h = h + s;\n\n        h = h + t;\n        e = H + h; \n        f = H - e;\n        f = f + h;\nEND_FIX\n        return quad_float(e, f);\n}\n\nquad_float& operator +=(quad_float& x, const quad_float& y ) {\nSTART_FIX\n        DOUBLE    H, h, T, t, S, s, e, f;\n        DOUBLE    t1;\n\n        S = x.hi + y.hi;\n        T = x.lo + y.lo;\n        e = S - x.hi;\n        f = T - x.lo;\n\n        t1 = S-e;\n        t1 = x.hi-t1;\n        s = y.hi-e;\n        s = s + t1;\n        \n        t1 = T-f;\n        t1 = x.lo-t1;\n        t = y.lo-f;\n        t = t + t1;\n\n\n        s = s + T;\n        H = S + s;\n        h = S - H;\n        h = h + s;\n\n        h = h + t;\n        e = H + h; \n        f = H - e;\n        f = f + h;\n\n        x.hi = e;\n        x.lo = f;\nEND_FIX\n        return x;\n}\n\nquad_float operator -(const quad_float& x, const quad_float& y ) {\nSTART_FIX\n        DOUBLE    H, h, T, t, S, s, e, f;\n        DOUBLE    t1, yhi, ylo;\n\n        yhi = -y.hi;\n        ylo = -y.lo;\n\n        S = x.hi + yhi;\n        T = x.lo + ylo;\n        e = S - x.hi;\n        f = T - x.lo;\n\n        t1 = S-e;\n        t1 = x.hi-t1;\n        s = yhi-e;\n        s = s + t1;\n        \n        t1 = T-f;\n        t1 = x.lo-t1;\n        t = ylo-f;\n        t = t + t1;\n\n\n        s = s + T;\n        H = S + s;\n        h = S - H;\n        h = h + s;\n\n        h = h + t;\n        e = H + h; \n        f = H - e;\n        f = f + h;\n\nEND_FIX\n        return quad_float(e, f);\n}\n\nquad_float& operator -=(quad_float& x, const quad_float& y ) {\nSTART_FIX\n        DOUBLE    H, h, T, t, S, s, e, f;\n        DOUBLE    t1, yhi, ylo;\n\n        yhi = -y.hi;\n        ylo = -y.lo;\n\n        S = x.hi + yhi;\n        T = x.lo + ylo;\n        e = S - x.hi;\n        f = T - x.lo;\n\n        t1 = S-e;\n        t1 = x.hi-t1;\n        s = yhi-e;\n        s = s + t1;\n        \n        t1 = T-f;\n        t1 = x.lo-t1;\n        t = ylo-f;\n        t = t + t1;\n\n\n        s = s + T;\n        H = S + s;\n        h = S - H;\n        h = h + s;\n\n        h = h + t;\n        e = H + h; \n        f = H - e;\n        f = f + h;\n\n        x.hi = e;\n        x.lo = f;\nEND_FIX\n        return x;\n}\n\nquad_float operator -(const quad_float& x)\n{\nSTART_FIX\n   DOUBLE xhi, xlo, u, v;\n\n   xhi = -x.hi;\n   xlo = -x.lo;\n\n   // it is a good idea to renormalize here, just in case\n   // the rounding rule depends on sign, and thus we will\n   // maintain the \"normal form\" for quad_float's.\n  \n   u = xhi + xlo;\n   v = xhi - u;\n   v = v + xlo;\n\nEND_FIX\n   return quad_float(u, v);\n}\n\n\n\n#if (NTL_FMA_DETECTED)\n\ndouble quad_float_zero = 0;\n\nstatic inline\ndouble Protect(double x) { return x + quad_float_zero; }\n\n#else\n\n\nstatic inline\ndouble Protect(double x) { return x; }\n\n\n#endif\n\n// NOTE: this is really sick: some compilers will issue FMA\n// (fused mul add) instructions which will break correctness.\n// C99 standard is supposed to prevent this across separate\n// statements, but C++ standard doesn't guarantee much at all.\n// In any case, gcc does not even implement the C99 standard\n// correctly.  One could disable this by compiling with\n// an appropriate flag: -mno-fma works for gcc, while -no-fma works\n// for icc.  icc and MSVC++ also support pragmas to do this:\n// #pragma fp_contract(off).  There is also a compiler flag for\n// gcc: -ffp-contract=off, but -mno-fma seems more widely supported.\n// These flags work for clang, as well.\n//\n// But in any case, I'd rather not mess with getting these flags right.\n// By calling Protect(a*b), this has the effect of forcing the\n// compiler to compute a*b + 0.  Assuming the compiler otherwise\n// does not perform any re-association, this should do the trick.\n// There is a small performance penalty, but it should be reasonable.\n\n\n\nquad_float operator *(const quad_float& x,const quad_float& y ) {\nSTART_FIX\n  DOUBLE hx, tx, hy, ty, C, c;\n  DOUBLE t1, t2;\n\n  C = Protect(NTL_QUAD_FLOAT_SPLIT*x.hi);\n  hx = C-x.hi;\n  c = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);\n  hx = C-hx;\n  tx = x.hi-hx;\n  hy = c-y.hi;\n  C = Protect(x.hi*y.hi);\n  hy = c-hy;\n  ty = y.hi-hy;\n\n  // c = ((((hx*hy-C)+hx*ty)+tx*hy)+tx*ty)+(x.hi*y.lo+x.lo*y.hi);\n  \n  t1 = Protect(hx*hy);\n  t1 = t1-C;\n  t2 = Protect(hx*ty);\n  t1 = t1+t2;\n  t2 = Protect(tx*hy);\n  t1 = t1+t2;\n  t2 = Protect(tx*ty);\n  c = t1+t2;\n  t1 = Protect(x.hi*y.lo);\n  t2 = Protect(x.lo*y.hi);\n  t1 = t1+t2;\n  c = c + t1;\n\n\n  hx = C+c;\n  tx = C-hx;\n  tx = tx+c;\n\nEND_FIX\n  return quad_float(hx, tx);\n}\n\nquad_float& operator *=(quad_float& x,const quad_float& y ) {\nSTART_FIX\n  DOUBLE hx, tx, hy, ty, C, c;\n  DOUBLE t1, t2;\n\n  C = Protect(NTL_QUAD_FLOAT_SPLIT*x.hi);\n  hx = C-x.hi;\n  c = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);\n  hx = C-hx;\n  tx = x.hi-hx;\n  hy = c-y.hi;\n  C = Protect(x.hi*y.hi);\n  hy = c-hy;\n  ty = y.hi-hy;\n\n  // c = ((((hx*hy-C)+hx*ty)+tx*hy)+tx*ty)+(x.hi*y.lo+x.lo*y.hi);\n  \n  t1 = Protect(hx*hy);\n  t1 = t1-C;\n  t2 = Protect(hx*ty);\n  t1 = t1+t2;\n  t2 = Protect(tx*hy);\n  t1 = t1+t2;\n  t2 = Protect(tx*ty);\n  c = t1+t2;\n  t1 = Protect(x.hi*y.lo);\n  t2 = Protect(x.lo*y.hi);\n  t1 = t1+t2;\n  c = c + t1;\n\n\n  hx = C+c;\n  tx = C-hx;\n  tx = tx+c;\n\n  x.hi = hx;\n  x.lo = tx;\nEND_FIX\n  return x;\n}\n\nquad_float operator /(const quad_float& x, const quad_float& y ) {\nSTART_FIX\n  DOUBLE hc, tc, hy, ty, C, c, U, u;\n  DOUBLE t1;\n\n  C = x.hi/y.hi;\n  c = Protect(NTL_QUAD_FLOAT_SPLIT*C);\n  hc = c-C;\n  u = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);\n  hc = c-hc;\n  tc = C-hc;\n  hy = u-y.hi;\n  U = Protect(C * y.hi);\n  hy = u-hy;\n  ty = y.hi-hy;\n\n  // u = (((hc*hy-U)+hc*ty)+tc*hy)+tc*ty;\n\n  u = Protect(hc*hy);\n  u = u-U;\n  t1 = Protect(hc*ty);\n  u = u+t1;\n  t1 = Protect(tc*hy);\n  u = u+t1;\n  t1 = Protect(tc*ty);\n  u = u+t1;\n\n  // c = ((((x.hi-U)-u)+x.lo)-C*y.lo)/y.hi;\n\n  c = x.hi-U;\n  c = c-u;\n  c = c+x.lo;\n  t1 = Protect(C*y.lo);\n  c = c - t1;\n  c = c/y.hi;\n  \n  hy = C+c;\n  ty = C-hy;\n  ty = ty+c;\n\nEND_FIX\n  return quad_float(hy, ty);\n}\n\nquad_float& operator /=(quad_float& x, const quad_float& y ) {\nSTART_FIX\n  DOUBLE hc, tc, hy, ty, C, c, U, u;\n  DOUBLE t1;\n\n  C = x.hi/y.hi;\n  c = Protect(NTL_QUAD_FLOAT_SPLIT*C);\n  hc = c-C;\n  u = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);\n  hc = c-hc;\n  tc = C-hc;\n  hy = u-y.hi;\n  U = Protect(C * y.hi);\n  hy = u-hy;\n  ty = y.hi-hy;\n\n  // u = (((hc*hy-U)+hc*ty)+tc*hy)+tc*ty;\n\n  u = Protect(hc*hy);\n  u = u-U;\n  t1 = Protect(hc*ty);\n  u = u+t1;\n  t1 = Protect(tc*hy);\n  u = u+t1;\n  t1 = Protect(tc*ty);\n  u = u+t1;\n\n  // c = ((((x.hi-U)-u)+x.lo)-C*y.lo)/y.hi;\n\n  c = x.hi-U;\n  c = c-u;\n  c = c+x.lo;\n  t1 = Protect(C*y.lo);\n  c = c - t1;\n  c = c/y.hi;\n  \n  hy = C+c;\n  ty = C-hy;\n  ty = ty+c;\n\n  x.hi = hy;\n  x.lo = ty;\nEND_FIX\n  return x;\n}\n\n\nquad_float sqrt(const quad_float& y) {\n  if (y.hi < 0.0) \n    ArithmeticError(\"quad_float: square root of negative number\");\n  if (y.hi == 0.0) return quad_float(0.0,0.0);\n\n  double c;\n  c = sqrt(y.hi);\n  ForceToMem(&c);  // This is fairly paranoid, but it doesn't cost too much.\n\nSTART_FIX\n\n  DOUBLE p,q,hx,tx,u,uu,cc;\n  DOUBLE t1;\n\n  p = Protect(NTL_QUAD_FLOAT_SPLIT*c); \n  hx = (c-p); \n  hx = hx+p; \n  tx = c-hx;\n  p = Protect(hx*hx);\n  q = Protect(hx*tx);\n  q = q+q;\n\n  u = p+q;\n  uu = p-u;\n  uu = uu+q;\n  t1 = Protect(tx*tx);\n  uu = uu+t1;\n\n\n  cc = y.hi-u;\n  cc = cc-uu;\n  cc = cc+y.lo;\n  t1 = c+c;\n  cc = cc/t1;\n\n  hx = c+cc;\n  tx = c-hx;\n  tx = tx+cc;\nEND_FIX\n  return quad_float(hx, tx);\n}\n\n\n\nvoid power(quad_float& z, const quad_float& a, long e)\n{\n   quad_float res, u;\n   unsigned long k;\n\n   if (e < 0)\n      k = -((unsigned long) e);\n   else\n      k = e;\n\n   res = 1.0;\n   u = a;\n\n   while (k) {\n      if (k & 1)\n         res = res * u;\n\n      k = k >> 1;\n      if (k)\n         u = u * u;\n   }\n\n   if (e < 0)\n      z = 1.0/res;\n   else\n      z = res;\n}\n\n\nvoid power2(quad_float& z, long e)\n{\n   z.hi = _ntl_ldexp(1.0, e);\n   z.lo = 0;\n}\n\n\nlong to_long(const quad_float& x)\n{\n   double fhi, flo;\n\n   fhi = floor(x.hi);\n\n   if (fhi == x.hi) \n      flo = floor(x.lo);\n   else\n      flo = 0;\n\n   // the following code helps to prevent unnecessary integer overflow,\n   // and guarantees that to_long(to_quad_float(a)) == a, for all long a,\n   // provided long's are not too wide.\n\n   if (fhi > 0)\n      return long(flo) - long(-fhi);\n   else\n      return long(fhi) + long(flo);\n}\n\n\n\n// This version of ZZ to quad_float coversion relies on the\n// precise rounding rules implemented by the ZZ to double conversion.\n\n\nvoid conv(quad_float& z, const ZZ& a)\n{\n   double xhi, xlo;\n\n   conv(xhi, a);\n\n   if (!IsFinite(&xhi)) {\n      z.hi = xhi;\n      z.lo = 0;\n      return;\n   }\n\n   NTL_ZZRegister(t);\n\n   conv(t, xhi);\n   sub(t, a, t);\n\n   conv(xlo, t);\n\n   normalize(z, xhi, xlo);\n\n   // The following is just paranoia.\n   if (fabs(z.hi) < NTL_FDOUBLE_PRECISION && z.lo != 0)\n      LogicError(\"internal error: ZZ to quad_float conversion\");\n} \n\nvoid conv(ZZ& z, const quad_float& x)\n{ \n   NTL_ZZRegister(t1);\n   NTL_ZZRegister(t2);\n   NTL_ZZRegister(t3);\n\n   double fhi, flo;\n\n   fhi = floor(x.hi);\n\n   if (fhi == x.hi) {\n      flo = floor(x.lo);\n\n      conv(t1, fhi);\n      conv(t2, flo);\n\n      add(z, t1, t2);\n   }\n   else\n      conv(z, fhi);\n}\n\n\n\nostream& operator<<(ostream& s, const quad_float& a)\n{\n   quad_float aa = a;\n\n   if (!IsFinite(&aa)) {\n      s << \"NaN\";\n      return s;\n   }\n\n   RRPush push;\n   RROutputPush opush;\n\n   RR::SetPrecision(long(3.33*quad_float::oprec) + 10);\n   RR::SetOutputPrecision(quad_float::oprec);\n\n   NTL_TLS_LOCAL(RR, t);\n\n   conv(t, a);\n   s << t;\n\n   return s;\n}\n\nistream& operator>>(istream& s, quad_float& x)\n{\n   RRPush push;\n   RR::SetPrecision(4*NTL_DOUBLE_PRECISION);\n\n   NTL_TLS_LOCAL(RR, t);\n   NTL_INPUT_CHECK_RET(s, s >> t);\n   conv(x, t);\n\n   return s;\n}\n\nvoid random(quad_float& x)\n{\n   RRPush push;\n   RR::SetPrecision(4*NTL_DOUBLE_PRECISION);\n\n   NTL_TLS_LOCAL(RR, t);\n   random(t);\n   conv(x, t);\n}\n\nquad_float random_quad_float()\n{\n   quad_float x;\n   random(x);\n   return x;\n}\n      \nlong IsFinite(quad_float *x)\n{\n   return IsFinite(&x->hi) && IsFinite(&x->lo);\n}\n\n\nlong PrecisionOK()\n{\nSTART_FIX\n   long k;\n   DOUBLE l1 = (double)1;\n   DOUBLE lh = 1/(double)2;\n   DOUBLE epsilon;\n   DOUBLE fudge, oldfudge;\n\n   epsilon = l1;\n   fudge = l1+l1;\n\n   k = 0;\n\n   do {\n      k++;\n      epsilon = epsilon * lh;\n      oldfudge = fudge;\n      fudge = l1 + epsilon;\n   } while (fudge > l1 && fudge < oldfudge);\n\nEND_FIX\n   return k == NTL_DOUBLE_PRECISION;\n}\n\nquad_float floor(const quad_float& x)\n{\n   double fhi = floor(x.hi);\n\n   if (fhi != x.hi)\n      return quad_float(fhi, 0.0);\n   else {\n      double flo = floor(x.lo);\n      quad_float z;\n      normalize(z, fhi, flo);\n      return z;\n   }\n}\n\n\nquad_float ceil(const quad_float& x) { \n  return -floor(-x);\n}\n\nquad_float trunc(const quad_float& x) { \n  if (x>=0.0) return floor(x); else return -floor(-x);\n}\n\n\n\nlong compare(const quad_float& x, const quad_float& y)\n{\n   if (x.hi > y.hi) \n      return 1;\n   else if (x.hi < y.hi)\n      return -1;\n   else if (x.lo > y.lo)\n      return 1;\n   else if (x.lo < y.lo) \n      return -1;\n   else\n      return 0;\n}\n\n\nquad_float fabs(const quad_float& x) \n{ if (x.hi>=0.0) return x; else return -x; }\n\n\nquad_float ldexp(const quad_float& x, long exp) { // x*2^exp\n   double xhi, xlo;\n   quad_float z;\n\n   xhi = _ntl_ldexp(x.hi, exp);\n   xlo = _ntl_ldexp(x.lo, exp);\n\n   normalize(z, xhi, xlo);\n   return z;\n}\n\n\nquad_float exp(const quad_float& x) { // New version 97 Aug 05\n/*\n!  Calculate a quadruple-precision exponential\n!  Method:\n!   x    x.log2(e)    nint[x.log2(e)] + frac[x.log2(e)]\n!  e  = 2          = 2\n!\n!                     iy    fy\n!                  = 2   . 2\n!  Then\n!   fy    y.loge(2)\n!  2   = e\n!\n!  Now y.loge(2) will be less than 0.3466 in absolute value.\n!  This is halved and a Pade aproximation is used to approximate e^x over\n!  the region (-0.1733, +0.1733).   This approximation is then squared.\n*/\n  if (x.hi<DBL_MIN_10_EXP*2.302585092994045684017991) \n    return to_quad_float(0.0);\n  if (x.hi>DBL_MAX_10_EXP*2.302585092994045684017991) {\n    ResourceError(\"exp(quad_float): overflow\");\n  }\n\n  static const quad_float Log2 = to_quad_float(\"0.6931471805599453094172321214581765680755\");\n  // GLOBAL (assumes C++11 thread-safe init)\n\n  quad_float y,temp,ysq,sum1,sum2;\n  long iy;\n  y=x/Log2;\n  temp = floor(y+0.5);\n  iy = to_long(temp);\n  y=(y-temp)*Log2;\n  y=ldexp(y,-1L);\n  ysq=y*y;\n  sum1=y*((((ysq+3960.0)*ysq+2162160.0)*ysq+302702400.0)*ysq+8821612800.0);\n  sum2=(((90.0*ysq+110880.0)*ysq+30270240.0)*ysq+2075673600.0)*ysq+17643225600.0;\n/*\n!                     sum2 + sum1         2.sum1\n! Now approximation = ----------- = 1 + ----------- = 1 + 2.temp\n!                     sum2 - sum1       sum2 - sum1\n!\n! Then (1 + 2.temp)^2 = 4.temp.(1 + temp) + 1\n*/\n  temp=sum1/(sum2-sum1);\n  y=temp*(temp+1);\n  y=ldexp(y,2L);\n  return ldexp(y+1,iy);\n}\n\nquad_float log(const quad_float& t) { // Newton method. See Bailey, MPFUN\n  if (t.hi <= 0.0) {\n    ArithmeticError(\"log(quad_float): argument must be positive\");\n  }\n  double s1 = log(t.hi);\n  ForceToMem(&s1);  // Again, this is fairly paranoid.\n  quad_float s;\n  s = s1;\n  quad_float e;\n  e=exp(s);\n  return s+(t-e)/e;  // Newton step\n}\n\nlong operator> (const quad_float& x, const quad_float& y) {\n   return (x.hi> y.hi) || (x.hi==y.hi && x.lo> y.lo); }\nlong operator>=(const quad_float& x, const quad_float& y) {\n   return (x.hi>y.hi) || (x.hi==y.hi && x.lo>=y.lo); }\nlong operator< (const quad_float& x, const quad_float& y) {\n   return (x.hi< y.hi) || (x.hi==y.hi && x.lo< y.lo); }\nlong operator<=(const quad_float& x, const quad_float& y) {\n   return (x.hi<y.hi) || (x.hi==y.hi && x.lo<=y.lo); }\nlong operator==(const quad_float& x, const quad_float& y)\n   { return x.hi==y.hi && x.lo==y.lo; }\nlong operator!=(const quad_float& x, const quad_float& y)\n   { return x.hi!=y.hi || x.lo!=y.lo; }\n\n\nNTL_END_IMPL\n\n", "meta": {"hexsha": "d018752e59b77aa6b523cb698c3a7e47aa89f18e", "size": 17484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "android/jni/ntl/src/quad_float.cpp", "max_stars_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_stars_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "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": "android/jni/ntl/src/quad_float.cpp", "max_issues_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_issues_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "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": "android/jni/ntl/src/quad_float.cpp", "max_forks_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_forks_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-24T13:38:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T13:38:28.000Z", "avg_line_length": 18.9631236443, "max_line_length": 93, "alphanum_fraction": 0.5610272249, "num_tokens": 6100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.04813677487184564, "lm_q1q2_score": 0.018528429244462425}}
{"text": "// Copyright (c) by respective owners including Yahoo!, Microsoft, and\n// individual contributors. All rights reserved. Released under a BSD (revised)\n// license as described in the file LICENSE.\n#ifdef _WIN32\n#  pragma warning(disable : 4996)  // generated by inner_product use\n#endif\n#include <fstream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include \"correctedMath.h\"\n#include \"vw_versions.h\"\n#include \"vw.h\"\n#include \"mwt.h\"\n\n#include <cstring>\n#include <cstdio>\n#include <cassert>\n#include \"no_label.h\"\n#include \"gd.h\"\n#include \"rand48.h\"\n#include \"reductions.h\"\n#include \"array_parameters.h\"\n#include \"vw_exception.h\"\n\n#include \"io/logger.h\"\n#include \"shared_data.h\"\n\n#include <boost/version.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n#if BOOST_VERSION >= 105600\n#  include <boost/align/is_aligned.hpp>\n#endif\n\nusing namespace VW::config;\n\nnamespace logger = VW::io::logger;\n\nenum lda_math_mode\n{\n  USE_SIMD,\n  USE_PRECISE,\n  USE_FAST_APPROX\n};\n\nclass index_feature\n{\npublic:\n  uint32_t document;\n  feature f;\n  bool operator<(const index_feature b) const { return f.weight_index < b.f.weight_index; }\n};\n\nstruct lda\n{\n  size_t topics;\n  float lda_alpha;\n  float lda_rho;\n  float lda_D;\n  float lda_epsilon;\n  size_t minibatch;\n  lda_math_mode mmode;\n\n  size_t finish_example_count;\n\n  v_array<float> Elogtheta;\n  v_array<float> decay_levels;\n  v_array<float> total_new;\n  v_array<example *> examples;\n  v_array<float> total_lambda;\n  v_array<int> doc_lengths;\n  v_array<float> digammas;\n  v_array<float> v;\n  std::vector<index_feature> sorted_features;\n\n  bool compute_coherence_metrics;\n\n  // size by 1 << bits\n  std::vector<uint32_t> feature_counts;\n  std::vector<std::vector<size_t>> feature_to_example_map;\n\n  bool total_lambda_init;\n\n  double example_t;\n  vw *all;  // regressor, lda\n\n  static constexpr float underflow_threshold = 1.0e-10f;\n  inline float digamma(float x);\n  inline float lgamma(float x);\n  inline float powf(float x, float p);\n  inline void expdigammify(vw &all, float *gamma);\n  inline void expdigammify_2(vw &all, float *gamma, float *norm);\n};\n\n// #define VW_NO_INLINE_SIMD\n\nnamespace\n{\ninline bool is_aligned16(void *ptr)\n{\n#if BOOST_VERSION >= 105600\n  return boost::alignment::is_aligned(16, ptr);\n#else\n  return ((reinterpret_cast<uintptr_t>(ptr) & 0x0f) == 0);\n#endif\n}\n}  // namespace\n\nnamespace ldamath\n{\ninline float fastlog2(float x)\n{\n  uint32_t mx;\n  memcpy(&mx, &x, sizeof(uint32_t));\n  mx = (mx & 0x007FFFFF) | (0x7e << 23);\n\n  float mx_f;\n  memcpy(&mx_f, &mx, sizeof(float));\n\n  uint32_t vx;\n  memcpy(&vx, &x, sizeof(uint32_t));\n\n  float y = static_cast<float>(vx);\n  y *= 1.0f / (float)(1 << 23);\n\n  return y - 124.22544637f - 1.498030302f * mx_f - 1.72587999f / (0.3520887068f + mx_f);\n}\n\ninline float fastlog(float x) { return 0.69314718f * fastlog2(x); }\n\ninline float fastpow2(float p)\n{\n  float offset = (p < 0) * 1.0f;\n  float clipp = (p < -126.0) ? -126.0f : p;\n  int w = (int)clipp;\n  float z = clipp - w + offset;\n  uint32_t approx = (uint32_t)((1 << 23) * (clipp + 121.2740838f + 27.7280233f / (4.84252568f - z) - 1.49012907f * z));\n\n  float v;\n  memcpy(&v, &approx, sizeof(uint32_t));\n  return v;\n}\n\ninline float fastexp(float p) { return fastpow2(1.442695040f * p); }\n\ninline float fastpow(float x, float p) { return fastpow2(p * fastlog2(x)); }\n\ninline float fastlgamma(float x)\n{\n  float logterm = fastlog(x * (1.0f + x) * (2.0f + x));\n  float xp3 = 3.0f + x;\n\n  return -2.081061466f - x + 0.0833333f / xp3 - logterm + (2.5f + x) * fastlog(xp3);\n}\n\ninline float fastdigamma(float x)\n{\n  float twopx = 2.0f + x;\n  float logterm = fastlog(twopx);\n\n  return -(1.0f + 2.0f * x) / (x * (1.0f + x)) - (13.0f + 6.0f * x) / (12.0f * twopx * twopx) + logterm;\n}\n\n#if !defined(VW_NO_INLINE_SIMD)\n\n#  if defined(__SSE2__) || defined(__SSE3__) || defined(__SSE4_1__)\n\n// Include headers for the various SSE versions:\n#    if defined(__SSE2__)\n#      include <emmintrin.h>\n#    endif\n#    if defined(__SSE3__)\n#      include <tmmintrin.h>\n#    endif\n#    if defined(__SSE4_1__)\n#      include <smmintrin.h>\n#    endif\n\n#    define HAVE_SIMD_MATHMODE\n\ntypedef __m128 v4sf;\ntypedef __m128i v4si;\n\ninline v4sf v4si_to_v4sf(v4si x) { return _mm_cvtepi32_ps(x); }\n\ninline v4si v4sf_to_v4si(v4sf x) { return _mm_cvttps_epi32(x); }\n\n// Extract v[idx]\ntemplate <const int idx>\nfloat v4sf_index(const v4sf x)\n{\n#    if defined(__SSE4_1__)\n  float ret;\n  uint32_t val;\n\n  val = _mm_extract_ps(x, idx);\n  // Portably convert uint32_t bit pattern to float. Optimizers will generally\n  // make this disappear.\n  memcpy(&ret, &val, sizeof(uint32_t));\n  return ret;\n#    else\n  return _mm_cvtss_f32(_mm_shuffle_ps(x, x, _MM_SHUFFLE(idx, idx, idx, idx)));\n#    endif\n}\n\n// Specialization for the 0'th element\ntemplate <>\nfloat v4sf_index<0>(const v4sf x)\n{\n  return _mm_cvtss_f32(x);\n}\n\ninline v4sf v4sfl(const float x) { return _mm_set1_ps(x); }\n\ninline v4si v4sil(const uint32_t x) { return _mm_set1_epi32(x); }\n\n#    ifdef _WIN32\n\ninline __m128 operator+(const __m128 a, const __m128 b) { return _mm_add_ps(a, b); }\n\ninline __m128 operator-(const __m128 a, const __m128 b) { return _mm_sub_ps(a, b); }\n\ninline __m128 operator*(const __m128 a, const __m128 b) { return _mm_mul_ps(a, b); }\n\ninline __m128 operator/(const __m128 a, const __m128 b) { return _mm_div_ps(a, b); }\n\n#    endif\n\ninline v4sf vfastpow2(const v4sf p)\n{\n  v4sf ltzero = _mm_cmplt_ps(p, v4sfl(0.0f));\n  v4sf offset = _mm_and_ps(ltzero, v4sfl(1.0f));\n  v4sf lt126 = _mm_cmplt_ps(p, v4sfl(-126.0f));\n  v4sf clipp = _mm_andnot_ps(lt126, p) + _mm_and_ps(lt126, v4sfl(-126.0f));\n  v4si w = v4sf_to_v4si(clipp);\n  v4sf z = clipp - v4si_to_v4sf(w) + offset;\n\n  const v4sf c_121_2740838 = v4sfl(121.2740838f);\n  const v4sf c_27_7280233 = v4sfl(27.7280233f);\n  const v4sf c_4_84252568 = v4sfl(4.84252568f);\n  const v4sf c_1_49012907 = v4sfl(1.49012907f);\n\n  v4sf v = v4sfl(1 << 23) * (clipp + c_121_2740838 + c_27_7280233 / (c_4_84252568 - z) - c_1_49012907 * z);\n\n  return _mm_castsi128_ps(v4sf_to_v4si(v));\n}\n\ninline v4sf vfastexp(const v4sf p)\n{\n  const v4sf c_invlog_2 = v4sfl(1.442695040f);\n\n  return vfastpow2(c_invlog_2 * p);\n}\n\ninline v4sf vfastlog2(v4sf x)\n{\n  v4si vx_i = _mm_castps_si128(x);\n  v4sf mx_f = _mm_castsi128_ps(_mm_or_si128(_mm_and_si128(vx_i, v4sil(0x007FFFFF)), v4sil(0x3f000000)));\n  v4sf y = v4si_to_v4sf(vx_i) * v4sfl(1.1920928955078125e-7f);\n\n  const v4sf c_124_22551499 = v4sfl(124.22551499f);\n  const v4sf c_1_498030302 = v4sfl(1.498030302f);\n  const v4sf c_1_725877999 = v4sfl(1.72587999f);\n  const v4sf c_0_3520087068 = v4sfl(0.3520887068f);\n\n  return y - c_124_22551499 - c_1_498030302 * mx_f - c_1_725877999 / (c_0_3520087068 + mx_f);\n}\n\ninline v4sf vfastlog(v4sf x)\n{\n  const v4sf c_0_69314718 = v4sfl(0.69314718f);\n\n  return c_0_69314718 * vfastlog2(x);\n}\n\ninline v4sf vfastdigamma(v4sf x)\n{\n  v4sf twopx = v4sfl(2.0f) + x;\n  v4sf logterm = vfastlog(twopx);\n\n  return (v4sfl(-48.0f) + x * (v4sfl(-157.0f) + x * (v4sfl(-127.0f) - v4sfl(30.0f) * x))) /\n      (v4sfl(12.0f) * x * (v4sfl(1.0f) + x) * twopx * twopx) +\n      logterm;\n}\n\nvoid vexpdigammify(vw &all, float *gamma, const float underflow_threshold)\n{\n  float extra_sum = 0.0f;\n  v4sf sum = v4sfl(0.0f);\n  float *fp;\n  const float *fpend = gamma + all.lda;\n\n  // Iterate through the initial part of the array that isn't 128-bit SIMD\n  // aligned.\n  for (fp = gamma; fp < fpend && !is_aligned16(fp); ++fp)\n  {\n    extra_sum += *fp;\n    *fp = fastdigamma(*fp);\n  }\n\n  // Rip through the aligned portion...\n  for (; is_aligned16(fp) && fp + 4 < fpend; fp += 4)\n  {\n    v4sf arg = _mm_load_ps(fp);\n    sum = sum + arg;\n    arg = vfastdigamma(arg);\n    _mm_store_ps(fp, arg);\n  }\n\n  for (; fp < fpend; ++fp)\n  {\n    extra_sum += *fp;\n    *fp = fastdigamma(*fp);\n  }\n\n#    if defined(__SSE3__) || defined(__SSE4_1__)\n  // Do two horizontal adds on sum, extract the total from the 0 element:\n  sum = _mm_hadd_ps(sum, sum);\n  sum = _mm_hadd_ps(sum, sum);\n  extra_sum += v4sf_index<0>(sum);\n#    else\n  extra_sum += v4sf_index<0>(sum) + v4sf_index<1>(sum) + v4sf_index<2>(sum) + v4sf_index<3>(sum);\n#    endif\n\n  extra_sum = fastdigamma(extra_sum);\n  sum = v4sfl(extra_sum);\n\n  for (fp = gamma; fp < fpend && !is_aligned16(fp); ++fp) { *fp = fmax(underflow_threshold, fastexp(*fp - extra_sum)); }\n\n  for (; is_aligned16(fp) && fp + 4 < fpend; fp += 4)\n  {\n    v4sf arg = _mm_load_ps(fp);\n    arg = arg - sum;\n    arg = vfastexp(arg);\n    arg = _mm_max_ps(v4sfl(underflow_threshold), arg);\n    _mm_store_ps(fp, arg);\n  }\n\n  for (; fp < fpend; ++fp) { *fp = fmax(underflow_threshold, fastexp(*fp - extra_sum)); }\n}\n\nvoid vexpdigammify_2(vw &all, float *gamma, const float *norm, const float underflow_threshold)\n{\n  float *fp = gamma;\n  const float *np;\n  const float *fpend = gamma + all.lda;\n\n  for (np = norm; fp < fpend && !is_aligned16(fp); ++fp, ++np)\n    *fp = fmax(underflow_threshold, fastexp(fastdigamma(*fp) - *np));\n\n  for (; is_aligned16(fp) && fp + 4 < fpend; fp += 4, np += 4)\n  {\n    v4sf arg = _mm_load_ps(fp);\n    arg = vfastdigamma(arg);\n    v4sf vnorm = _mm_loadu_ps(np);\n    arg = arg - vnorm;\n    arg = vfastexp(arg);\n    arg = _mm_max_ps(v4sfl(underflow_threshold), arg);\n    _mm_store_ps(fp, arg);\n  }\n\n  for (; fp < fpend; ++fp, ++np) *fp = fmax(underflow_threshold, fastexp(fastdigamma(*fp) - *np));\n}\n\n#  else\n// PLACEHOLDER for future ARM NEON code\n// Also remember to define HAVE_SIMD_MATHMODE\n#  endif\n\n#endif  // !VW_NO_INLINE_SIMD\n\n// Templates for common code shared between the three math modes (SIMD, fast approximations\n// and accurate).\n//\n// The generic template takes a type and a specialization flag, mtype.\n//\n// mtype == USE_PRECISE: Use the accurate computation for lgamma, digamma.\n// mtype == USE_FAST_APPROX: Use the fast approximations for lgamma, digamma.\n// mtype == USE_SIMD: Use CPU SIMD instruction\n//\n// The generic template is specialized for the particular accuracy setting.\n\n// Log gamma:\ntemplate <typename T, const lda_math_mode mtype>\ninline T lgamma(T /* x */)\n{\n  BOOST_STATIC_ASSERT_MSG(true, \"ldamath::lgamma is not defined for this type and math mode.\");\n}\n\n// Digamma:\ntemplate <typename T, const lda_math_mode mtype>\ninline T digamma(T /* x */)\n{\n  BOOST_STATIC_ASSERT_MSG(true, \"ldamath::digamma is not defined for this type and math mode.\");\n}\n\n// Exponential\ntemplate <typename T, lda_math_mode mtype>\ninline T exponential(T /* x */)\n{\n  BOOST_STATIC_ASSERT_MSG(true, \"ldamath::exponential is not defined for this type and math mode.\");\n}\n\n// Powf\ntemplate <typename T, lda_math_mode mtype>\ninline T powf(T /* x */, T /* p */)\n{\n  BOOST_STATIC_ASSERT_MSG(true, \"ldamath::powf is not defined for this type and math mode.\");\n}\n\n// High accuracy float specializations:\n\ntemplate <>\ninline float lgamma<float, USE_PRECISE>(float x)\n{\n  return boost::math::lgamma(x);\n}\ntemplate <>\ninline float digamma<float, USE_PRECISE>(float x)\n{\n  return boost::math::digamma(x);\n}\ntemplate <>\ninline float exponential<float, USE_PRECISE>(float x)\n{\n  return correctedExp(x);\n}\ntemplate <>\ninline float powf<float, USE_PRECISE>(float x, float p)\n{\n  return std::pow(x, p);\n}\n\n// Fast approximation float specializations:\n\ntemplate <>\ninline float lgamma<float, USE_FAST_APPROX>(float x)\n{\n  return fastlgamma(x);\n}\ntemplate <>\ninline float digamma<float, USE_FAST_APPROX>(float x)\n{\n  return fastdigamma(x);\n}\ntemplate <>\ninline float exponential<float, USE_FAST_APPROX>(float x)\n{\n  return fastexp(x);\n}\ntemplate <>\ninline float powf<float, USE_FAST_APPROX>(float x, float p)\n{\n  return fastpow(x, p);\n}\n\n// SIMD specializations:\n\ntemplate <>\ninline float lgamma<float, USE_SIMD>(float x)\n{\n  return lgamma<float, USE_FAST_APPROX>(x);\n}\ntemplate <>\ninline float digamma<float, USE_SIMD>(float x)\n{\n  return digamma<float, USE_FAST_APPROX>(x);\n}\ntemplate <>\ninline float exponential<float, USE_SIMD>(float x)\n{\n  return exponential<float, USE_FAST_APPROX>(x);\n}\ntemplate <>\ninline float powf<float, USE_SIMD>(float x, float p)\n{\n  return powf<float, USE_FAST_APPROX>(x, p);\n}\n\ntemplate <typename T, const lda_math_mode mtype>\ninline void expdigammify(vw &all, T *gamma, T threshold, T initial)\n{\n  T sum = digamma<T, mtype>(std::accumulate(gamma, gamma + all.lda, initial));\n\n  std::transform(gamma, gamma + all.lda, gamma,\n      [sum, threshold](T g) { return fmax(threshold, exponential<T, mtype>(digamma<T, mtype>(g) - sum)); });\n}\ntemplate <>\ninline void expdigammify<float, USE_SIMD>(vw &all, float *gamma, float threshold, float)\n{\n#if defined(HAVE_SIMD_MATHMODE)\n  vexpdigammify(all, gamma, threshold);\n#else\n  // Do something sensible if SIMD math isn't available:\n  expdigammify<float, USE_FAST_APPROX>(all, gamma, threshold, 0.0);\n#endif\n}\n\ntemplate <typename T, const lda_math_mode mtype>\ninline void expdigammify_2(vw &all, float *gamma, T *norm, const T threshold)\n{\n  std::transform(gamma, gamma + all.lda, norm, gamma,\n      [threshold](float g, float n) { return fmax(threshold, exponential<T, mtype>(digamma<T, mtype>(g) - n)); });\n}\ntemplate <>\ninline void expdigammify_2<float, USE_SIMD>(vw &all, float *gamma, float *norm, const float threshold)\n{\n#if defined(HAVE_SIMD_MATHMODE)\n  vexpdigammify_2(all, gamma, norm, threshold);\n#else\n  // Do something sensible if SIMD math isn't available:\n  expdigammify_2<float, USE_FAST_APPROX>(all, gamma, norm, threshold);\n#endif\n}\n\n}  // namespace ldamath\n\nfloat lda::digamma(float x)\n{\n  switch (mmode)\n  {\n    case USE_FAST_APPROX:\n      return ldamath::digamma<float, USE_FAST_APPROX>(x);\n    case USE_PRECISE:\n      return ldamath::digamma<float, USE_PRECISE>(x);\n    case USE_SIMD:\n      return ldamath::digamma<float, USE_SIMD>(x);\n    default:\n      // Should not happen.\n      logger::errlog_critical(\"lda::digamma: Trampled or invalid math mode, aborting\");\n      abort();\n      return 0.0f;\n  }\n}\n\nfloat lda::lgamma(float x)\n{\n  switch (mmode)\n  {\n    case USE_FAST_APPROX:\n      return ldamath::lgamma<float, USE_FAST_APPROX>(x);\n    case USE_PRECISE:\n      return ldamath::lgamma<float, USE_PRECISE>(x);\n    case USE_SIMD:\n      return ldamath::lgamma<float, USE_SIMD>(x);\n    default:\n      logger::errlog_critical(\"lda::lgamma: Trampled or invalid math mode, aborting\");\n      abort();\n      return 0.0f;\n  }\n}\n\nfloat lda::powf(float x, float p)\n{\n  switch (mmode)\n  {\n    case USE_FAST_APPROX:\n      return ldamath::powf<float, USE_FAST_APPROX>(x, p);\n    case USE_PRECISE:\n      return ldamath::powf<float, USE_PRECISE>(x, p);\n    case USE_SIMD:\n      return ldamath::powf<float, USE_SIMD>(x, p);\n    default:\n      logger::errlog_critical(\"lda::powf: Trampled or invalid math mode, aborting\");\n      abort();\n      return 0.0f;\n  }\n}\n\nvoid lda::expdigammify(vw &all_, float *gamma)\n{\n  switch (mmode)\n  {\n    case USE_FAST_APPROX:\n      ldamath::expdigammify<float, USE_FAST_APPROX>(all_, gamma, underflow_threshold, 0.0f);\n      break;\n    case USE_PRECISE:\n      ldamath::expdigammify<float, USE_PRECISE>(all_, gamma, underflow_threshold, 0.0f);\n      break;\n    case USE_SIMD:\n      ldamath::expdigammify<float, USE_SIMD>(all_, gamma, underflow_threshold, 0.0f);\n      break;\n    default:\n      logger::errlog_critical(\"lda::expdigammify: Trampled or invalid math mode, aborting\");\n      abort();\n  }\n}\n\nvoid lda::expdigammify_2(vw &all_, float *gamma, float *norm)\n{\n  switch (mmode)\n  {\n    case USE_FAST_APPROX:\n      ldamath::expdigammify_2<float, USE_FAST_APPROX>(all_, gamma, norm, underflow_threshold);\n      break;\n    case USE_PRECISE:\n      ldamath::expdigammify_2<float, USE_PRECISE>(all_, gamma, norm, underflow_threshold);\n      break;\n    case USE_SIMD:\n      ldamath::expdigammify_2<float, USE_SIMD>(all_, gamma, norm, underflow_threshold);\n      break;\n    default:\n      logger::errlog_critical(\"lda::expdigammify_2: Trampled or invalid math mode, aborting\");\n      abort();\n  }\n}\n\nstatic inline float average_diff(vw &all, float *oldgamma, float *newgamma)\n{\n  float sum;\n  float normalizer;\n\n  // This warps the normal sense of \"inner product\", but it accomplishes the same\n  // thing as the \"plain old\" for loop. clang does a good job of reducing the\n  // common subexpressions.\n  sum = std::inner_product(\n      oldgamma, oldgamma + all.lda, newgamma, 0.0f, [](float accum, float absdiff) { return accum + absdiff; },\n      [](float old_g, float new_g) { return std::abs(old_g - new_g); });\n\n  normalizer = std::accumulate(newgamma, newgamma + all.lda, 0.0f);\n  return sum / normalizer;\n}\n\n// Returns E_q[log p(\\theta)] - E_q[log q(\\theta)].\nfloat theta_kl(lda &l, v_array<float> &Elogtheta, float *gamma)\n{\n  float gammasum = 0;\n  Elogtheta.clear();\n  for (size_t k = 0; k < l.topics; k++)\n  {\n    Elogtheta.push_back(l.digamma(gamma[k]));\n    gammasum += gamma[k];\n  }\n  float digammasum = l.digamma(gammasum);\n  gammasum = l.lgamma(gammasum);\n  float kl = -(l.topics * l.lgamma(l.lda_alpha));\n  kl += l.lgamma(l.lda_alpha * l.topics) - gammasum;\n  for (size_t k = 0; k < l.topics; k++)\n  {\n    Elogtheta[k] -= digammasum;\n    kl += (l.lda_alpha - gamma[k]) * Elogtheta[k];\n    kl += l.lgamma(gamma[k]);\n  }\n\n  return kl;\n}\n\nstatic inline float find_cw(lda &l, float *u_for_w, float *v)\n{\n  return 1.0f / std::inner_product(u_for_w, u_for_w + l.topics, v, 0.0f);\n}\n\nnamespace\n{\n// Effectively, these are static and not visible outside the compilation unit.\nv_array<float> new_gamma = v_init<float>();\nv_array<float> old_gamma = v_init<float>();\n}  // namespace\n\n// Returns an estimate of the part of the variational bound that\n// doesn't have to do with beta for the entire corpus for the current\n// setting of lambda based on the document passed in. The value is\n// divided by the total number of words in the document This can be\n// used as a (possibly very noisy) estimate of held-out likelihood.\nfloat lda_loop(lda &l, v_array<float> &Elogtheta, float *v, example *ec, float)\n{\n  parameters &weights = l.all->weights;\n  new_gamma.clear();\n  old_gamma.clear();\n\n  for (size_t i = 0; i < l.topics; i++)\n  {\n    new_gamma.push_back(1.f);\n    old_gamma.push_back(0.f);\n  }\n  size_t num_words = 0;\n  for (features &fs : *ec) num_words += fs.size();\n\n  float xc_w = 0;\n  float score = 0;\n  float doc_length = 0;\n  do\n  {\n    memcpy(v, new_gamma.begin(), sizeof(float) * l.topics);\n    l.expdigammify(*l.all, v);\n\n    memcpy(old_gamma.begin(), new_gamma.begin(), sizeof(float) * l.topics);\n    memset(new_gamma.begin(), 0, sizeof(float) * l.topics);\n\n    score = 0;\n    size_t word_count = 0;\n    doc_length = 0;\n    for (features &fs : *ec)\n    {\n      for (features::iterator &f : fs)\n      {\n        float *u_for_w = &(weights[f.index()]) + l.topics + 1;\n        float c_w = find_cw(l, u_for_w, v);\n        xc_w = c_w * f.value();\n        score += -f.value() * log(c_w);\n        size_t max_k = l.topics;\n        for (size_t k = 0; k < max_k; k++, ++u_for_w) new_gamma[k] += xc_w * *u_for_w;\n        word_count++;\n        doc_length += f.value();\n      }\n    }\n    for (size_t k = 0; k < l.topics; k++) new_gamma[k] = new_gamma[k] * v[k] + l.lda_alpha;\n  } while (average_diff(*l.all, old_gamma.begin(), new_gamma.begin()) > l.lda_epsilon);\n\n  ec->pred.scalars.clear();\n  ec->pred.scalars.resize_but_with_stl_behavior(l.topics);\n  memcpy(ec->pred.scalars.begin(), new_gamma.begin(), l.topics * sizeof(float));\n\n  score += theta_kl(l, Elogtheta, new_gamma.begin());\n\n  return score / doc_length;\n}\n\nsize_t next_pow2(size_t x)\n{\n  int i = 0;\n  x = x > 0 ? x - 1 : 0;\n  while (x > 0)\n  {\n    x >>= 1;\n    i++;\n  }\n  return ((size_t)1) << i;\n}\n\nstruct initial_weights\n{\n  weight _initial;\n  weight _initial_random;\n  bool _random;\n  uint32_t _lda;\n  uint32_t _stride;\n};\n\nvoid save_load(lda &l, io_buf &model_file, bool read, bool text)\n{\n  vw &all = *(l.all);\n  uint64_t length = (uint64_t)1 << all.num_bits;\n  if (read)\n  {\n    initialize_regressor(all);\n    initial_weights init{all.initial_t, static_cast<float>(l.lda_D / all.lda / all.length() * 200.f),\n        all.random_weights, all.lda, all.weights.stride()};\n\n    auto initial_lda_weight_initializer = [init](weight *weights, uint64_t index) {\n      uint32_t lda = init._lda;\n      weight initial_random = init._initial_random;\n      if (init._random)\n      {\n        for (size_t i = 0; i != lda; ++i, ++index)\n        { weights[i] = static_cast<float>(-std::log(merand48(index) + 1e-6) + 1.0f) * initial_random; }\n      }\n      weights[lda] = init._initial;\n    };\n\n    all.weights.set_default(initial_lda_weight_initializer);\n  }\n  if (model_file.num_files() != 0)\n  {\n    uint64_t i = 0;\n    std::stringstream msg;\n    size_t brw = 1;\n\n    do\n    {\n      brw = 0;\n      size_t K = all.lda;\n      if (!read && text) msg << i << \" \";\n\n      if (!read || all.model_file_ver >= VERSION_FILE_WITH_HEADER_ID)\n        brw += bin_text_read_write_fixed(model_file, (char *)&i, sizeof(i), \"\", read, msg, text);\n      else\n      {\n        // support 32bit build models\n        uint32_t j;\n        brw += bin_text_read_write_fixed(model_file, (char *)&j, sizeof(j), \"\", read, msg, text);\n        i = j;\n      }\n\n      if (brw != 0)\n      {\n        weight *w = &(all.weights.strided_index(i));\n        for (uint64_t k = 0; k < K; k++)\n        {\n          weight *v = w + k;\n          if (!read && text) msg << *v + l.lda_rho << \" \";\n          brw += bin_text_read_write_fixed(model_file, (char *)v, sizeof(*v), \"\", read, msg, text);\n        }\n      }\n      if (text)\n      {\n        if (!read) msg << \"\\n\";\n        brw += bin_text_read_write_fixed(model_file, nullptr, 0, \"\", read, msg, text);\n      }\n      if (!read) ++i;\n    } while ((!read && i < length) || (read && brw > 0));\n  }\n}\n\nvoid return_example(vw &all, example &ec)\n{\n  all.sd->update(ec.test_only, true, ec.loss, ec.weight, ec.num_features);\n  for (auto &sink : all.final_prediction_sink) { MWT::print_scalars(sink.get(), ec.pred.scalars, ec.tag); }\n\n  if (all.sd->weighted_examples() >= all.sd->dump_interval && !all.logger.quiet)\n    all.sd->print_update(*all.trace_message, all.holdout_set_off, all.current_pass, \"none\", 0, ec.num_features,\n        all.progress_add, all.progress_arg);\n  VW::finish_example(all, ec);\n}\n\nvoid learn_batch(lda &l)\n{\n  parameters &weights = l.all->weights;\n\n  assert(l.finish_example_count == (l.examples.size() - 1));\n\n  if (l.sorted_features.empty())  // FAST-PASS for real \"true\"\n  {\n    // This can happen when the socket connection is dropped by the client.\n    // If l.sorted_features is empty, then l.sorted_features[0] does not\n    // exist, so we should not try to take its address in the beginning of\n    // the for loops down there. Since it seems that there's not much to\n    // do in this case, we just return.\n    for (size_t d = 0; d < l.examples.size(); d++)\n    {\n      l.examples[d]->pred.scalars.clear();\n      l.examples[d]->pred.scalars.resize_but_with_stl_behavior(l.topics);\n      memset(l.examples[d]->pred.scalars.begin(), 0, l.topics * sizeof(float));\n\n      l.examples[d]->pred.scalars.clear();\n\n      if (l.finish_example_count > 0)\n      {\n        return_example(*l.all, *l.examples[d]);\n        l.finish_example_count--;\n      }\n    }\n    l.examples.clear();\n    return;\n  }\n\n  float eta = -1;\n  float minuseta = -1;\n\n  if (l.total_lambda.empty())\n  {\n    for (size_t k = 0; k < l.all->lda; k++) l.total_lambda.push_back(0.f);\n    // This part does not work with sparse parameters\n    size_t stride = weights.stride();\n    for (size_t i = 0; i <= weights.mask(); i += stride)\n    {\n      weight *w = &(weights[i]);\n      for (size_t k = 0; k < l.all->lda; k++) l.total_lambda[k] += w[k];\n    }\n  }\n\n  l.example_t++;\n  l.total_new.clear();\n  for (size_t k = 0; k < l.all->lda; k++) l.total_new.push_back(0.f);\n\n  size_t batch_size = l.examples.size();\n\n  sort(l.sorted_features.begin(), l.sorted_features.end());\n\n  eta = l.all->eta * l.powf((float)l.example_t, -l.all->power_t);\n  minuseta = 1.0f - eta;\n  eta *= l.lda_D / batch_size;\n  l.decay_levels.push_back(l.decay_levels.back() + log(minuseta));\n\n  l.digammas.clear();\n  float additional = (float)(l.all->length()) * l.lda_rho;\n  for (size_t i = 0; i < l.all->lda; i++) l.digammas.push_back(l.digamma(l.total_lambda[i] + additional));\n\n  auto last_weight_index = std::numeric_limits<uint64_t>::max();\n  for (index_feature *s = &l.sorted_features[0]; s <= &l.sorted_features.back(); s++)\n  {\n    if (last_weight_index == s->f.weight_index) continue;\n    last_weight_index = s->f.weight_index;\n    // float *weights_for_w = &(weights[s->f.weight_index]);\n    float *weights_for_w = &(weights[s->f.weight_index & weights.mask()]);\n    float decay_component =\n        l.decay_levels.end()[-2] - l.decay_levels.end()[(int)(-1 - l.example_t + *(weights_for_w + l.all->lda))];\n    float decay = fmin(1.0f, correctedExp(decay_component));\n    float *u_for_w = weights_for_w + l.all->lda + 1;\n\n    *(weights_for_w + l.all->lda) = (float)l.example_t;\n    for (size_t k = 0; k < l.all->lda; k++)\n    {\n      weights_for_w[k] *= decay;\n      u_for_w[k] = weights_for_w[k] + l.lda_rho;\n    }\n\n    l.expdigammify_2(*l.all, u_for_w, l.digammas.begin());\n  }\n\n  for (size_t d = 0; d < batch_size; d++)\n  {\n    float score = lda_loop(l, l.Elogtheta, &(l.v[d * l.all->lda]), l.examples[d], l.all->power_t);\n    if (l.all->audit) GD::print_audit_features(*l.all, *l.examples[d]);\n    // If the doc is empty, give it loss of 0.\n    if (l.doc_lengths[d] > 0)\n    {\n      l.all->sd->sum_loss -= score;\n      l.all->sd->sum_loss_since_last_dump -= score;\n    }\n\n    if (l.finish_example_count > 0)\n    {\n      return_example(*l.all, *l.examples[d]);\n      l.finish_example_count--;\n    }\n  }\n\n  // -t there's no need to update weights (especially since it's a noop)\n  if (eta != 0)\n  {\n    for (index_feature *s = &l.sorted_features[0]; s <= &l.sorted_features.back();)\n    {\n      index_feature *next = s + 1;\n      while (next <= &l.sorted_features.back() && next->f.weight_index == s->f.weight_index) next++;\n\n      float *word_weights = &(weights[s->f.weight_index]);\n      for (size_t k = 0; k < l.all->lda; k++, ++word_weights)\n      {\n        float new_value = minuseta * *word_weights;\n        *word_weights = new_value;\n      }\n\n      for (; s != next; s++)\n      {\n        float *v_s = &(l.v[s->document * l.all->lda]);\n        float *u_for_w = &(weights[s->f.weight_index]) + l.all->lda + 1;\n        float c_w = eta * find_cw(l, u_for_w, v_s) * s->f.x;\n        word_weights = &(weights[s->f.weight_index]);\n        for (size_t k = 0; k < l.all->lda; k++, ++u_for_w, ++word_weights)\n        {\n          float new_value = *u_for_w * v_s[k] * c_w;\n          l.total_new[k] += new_value;\n          *word_weights += new_value;\n        }\n      }\n    }\n\n    for (size_t k = 0; k < l.all->lda; k++)\n    {\n      l.total_lambda[k] *= minuseta;\n      l.total_lambda[k] += l.total_new[k];\n    }\n  }\n  l.sorted_features.resize(0);\n\n  l.examples.clear();\n  l.doc_lengths.clear();\n}\n\nvoid learn(lda &l, VW::LEARNER::single_learner &, example &ec)\n{\n  uint32_t num_ex = (uint32_t)l.examples.size();\n  l.examples.push_back(&ec);\n  l.doc_lengths.push_back(0);\n  for (features &fs : ec)\n  {\n    for (features::iterator &f : fs)\n    {\n      index_feature temp = {num_ex, feature(f.value(), f.index())};\n      l.sorted_features.push_back(temp);\n      l.doc_lengths[num_ex] += (int)f.value();\n    }\n  }\n  if (++num_ex == l.minibatch) learn_batch(l);\n}\n\nvoid learn_with_metrics(lda &l, VW::LEARNER::single_learner &base, example &ec)\n{\n  if (l.all->passes_complete == 0)\n  {\n    // build feature to example map\n    uint64_t stride_shift = l.all->weights.stride_shift();\n    uint64_t weight_mask = l.all->weights.mask();\n\n    for (features &fs : ec)\n    {\n      for (features::iterator &f : fs)\n      {\n        uint64_t idx = (f.index() & weight_mask) >> stride_shift;\n        l.feature_counts[idx] += (uint32_t)f.value();\n        l.feature_to_example_map[idx].push_back(ec.example_counter);\n      }\n    }\n  }\n\n  learn(l, base, ec);\n}\n\n// placeholder\nvoid predict(lda &l, VW::LEARNER::single_learner &base, example &ec) { learn(l, base, ec); }\nvoid predict_with_metrics(lda &l, VW::LEARNER::single_learner &base, example &ec) { learn_with_metrics(l, base, ec); }\n\nstruct word_doc_frequency\n{\n  // feature/word index\n  uint64_t idx;\n  // document count\n  uint32_t count;\n};\n\n// cooccurence of 2 features/words\nstruct feature_pair\n{\n  // feature/word 1\n  uint64_t f1;\n  // feature/word 2\n  uint64_t f2;\n\n  feature_pair(uint64_t _f1, uint64_t _f2) : f1(_f1), f2(_f2) {}\n};\n\ntemplate <class T>\nvoid get_top_weights(vw *all, int top_words_count, int topic, std::vector<feature> &output, T &weights)\n{\n  uint64_t length = (uint64_t)1 << all->num_bits;\n\n  // get top features for this topic\n  auto cmp = [](feature left, feature right) { return left.x > right.x; };\n  std::priority_queue<feature, std::vector<feature>, decltype(cmp)> top_features(cmp);\n  typename T::iterator iter = weights.begin();\n\n  for (uint64_t i = 0; i < std::min(static_cast<uint64_t>(top_words_count), length); i++, ++iter)\n    top_features.push({(&(*iter))[topic], iter.index()});\n\n  for (uint64_t i = top_words_count; i < length; i++, ++iter)\n  {\n    weight v = (&(*iter))[topic];\n    if (v > top_features.top().x)\n    {\n      top_features.pop();\n      top_features.push({v, i});\n    }\n  }\n\n  // extract idx and sort descending\n  output.resize(top_features.size());\n  for (int i = (int)top_features.size() - 1; i >= 0; i--)\n  {\n    output[i] = top_features.top();\n    top_features.pop();\n  }\n}\n\nvoid get_top_weights(vw *all, int top_words_count, int topic, std::vector<feature> &output)\n{\n  if (all->weights.sparse)\n    get_top_weights(all, top_words_count, topic, output, all->weights.sparse_weights);\n  else\n    get_top_weights(all, top_words_count, topic, output, all->weights.dense_weights);\n}\n\ntemplate <class T>\nvoid compute_coherence_metrics(lda &l, T &weights)\n{\n  uint64_t length = (uint64_t)1 << l.all->num_bits;\n\n  std::vector<std::vector<feature_pair>> topics_word_pairs;\n  topics_word_pairs.resize(l.topics);\n\n  int top_words_count = 10;  // parameterize and check\n\n  for (size_t topic = 0; topic < l.topics; topic++)\n  {\n    // get top features for this topic\n    auto cmp = [](feature &left, feature &right) { return left.x > right.x; };\n    std::priority_queue<feature, std::vector<feature>, decltype(cmp)> top_features(cmp);\n    typename T::iterator iter = weights.begin();\n    for (uint64_t i = 0; i < std::min(static_cast<uint64_t>(top_words_count), length); i++, ++iter)\n      top_features.push(feature((&(*iter))[topic], iter.index()));\n\n    for (typename T::iterator v = weights.begin(); v != weights.end(); ++v)\n      if ((&(*v))[topic] > top_features.top().x)\n      {\n        top_features.pop();\n        top_features.push(feature((&(*v))[topic], v.index()));\n      }\n\n    // extract idx and sort descending\n    std::vector<uint64_t> top_features_idx;\n    top_features_idx.resize(top_features.size());\n    for (int i = (int)top_features.size() - 1; i >= 0; i--)\n    {\n      top_features_idx[i] = top_features.top().weight_index;\n      top_features.pop();\n    }\n\n    auto &word_pairs = topics_word_pairs[topic];\n    for (size_t i = 0; i < top_features_idx.size(); i++)\n      for (size_t j = i + 1; j < top_features_idx.size(); j++)\n        word_pairs.emplace_back(top_features_idx[i], top_features_idx[j]);\n  }\n\n  // compress word pairs and create record for storing frequency\n  std::map<uint64_t, std::vector<word_doc_frequency>> coWordsDFSet;\n  for (auto &vec : topics_word_pairs)\n  {\n    for (auto &wp : vec)\n    {\n      auto f1 = wp.f1;\n      auto f2 = wp.f2;\n      auto wdf = coWordsDFSet.find(f1);\n\n      if (wdf != coWordsDFSet.end())\n      {\n        // http://stackoverflow.com/questions/5377434/does-stdmapiterator-return-a-copy-of-value-or-a-value-itself\n        // if (wdf->second.find(f2) == wdf->second.end())\n\n        if (std::find_if(wdf->second.begin(), wdf->second.end(),\n                [&f2](const word_doc_frequency &v) { return v.idx == f2; }) != wdf->second.end())\n        {\n          wdf->second.push_back({f2, 0});\n          // printf(\" add %d %d\\n\", f1, f2);\n        }\n      }\n      else\n      {\n        std::vector<word_doc_frequency> tmp_vec = {{f2, 0}};\n        coWordsDFSet.insert(std::make_pair(f1, tmp_vec));\n      }\n    }\n  }\n\n  // this.GetWordPairsDocumentFrequency(coWordsDFSet);\n  for (auto &pair : coWordsDFSet)\n  {\n    auto &examples_for_f1 = l.feature_to_example_map[pair.first];\n    for (auto &wdf : pair.second)\n    {\n      auto &examples_for_f2 = l.feature_to_example_map[wdf.idx];\n\n      // assumes examples_for_f1 and examples_for_f2 are orderd\n      size_t i = 0;\n      size_t j = 0;\n      while (i < examples_for_f1.size() && j < examples_for_f2.size())\n      {\n        if (examples_for_f1[i] == examples_for_f2[j])\n        {\n          wdf.count++;\n          i++;\n          j++;\n        }\n        else if (examples_for_f2[j] < examples_for_f1[i])\n          j++;\n        else\n          i++;\n      }\n    }\n  }\n\n  float epsilon = 1e-6f;  // TODO\n  float avg_coherence = 0;\n  for (size_t topic = 0; topic < l.topics; topic++)\n  {\n    float coherence = 0;\n\n    for (auto &pairs : topics_word_pairs[topic])\n    {\n      auto f1 = pairs.f1;\n      if (l.feature_counts[f1] == 0) continue;\n\n      auto f2 = pairs.f2;\n      auto &co_feature = coWordsDFSet[f1];\n      auto co_feature_df = std::find_if(\n          co_feature.begin(), co_feature.end(), [&f2](const word_doc_frequency &v) { return v.idx == f2; });\n\n      if (co_feature_df != co_feature.end())\n      {\n        // printf(\"(%d:%d + eps)/(%d:%d)\\n\", f2, co_feature_df->count, f1, l.feature_counts[f1]);\n        coherence += logf((co_feature_df->count + epsilon) / l.feature_counts[f1]);\n      }\n    }\n\n    printf(\"Topic %3d coherence: %f\\n\", (int)topic, coherence);\n\n    // TODO: expose per topic coherence\n\n    // TODO: good vs. bad topics\n    avg_coherence += coherence;\n  }\n\n  avg_coherence /= l.topics;\n\n  printf(\"Avg topic coherence: %f\\n\", avg_coherence);\n}\n\nvoid compute_coherence_metrics(lda &l)\n{\n  if (l.all->weights.sparse)\n    compute_coherence_metrics(l, l.all->weights.sparse_weights);\n  else\n    compute_coherence_metrics(l, l.all->weights.dense_weights);\n}\n\nvoid end_pass(lda &l)\n{\n  if (!l.examples.empty()) learn_batch(l);\n\n  if (l.compute_coherence_metrics && l.all->passes_complete == l.all->numpasses)\n  {\n    compute_coherence_metrics(l);\n    // FASTPASS return;\n  }\n}\n\ntemplate <class T>\nvoid end_examples(lda &l, T &weights)\n{\n  for (typename T::iterator iter = weights.begin(); iter != weights.end(); ++iter)\n  {\n    float decay_component =\n        l.decay_levels.back() - l.decay_levels.end()[(int)(-1 - l.example_t + (&(*iter))[l.all->lda])];\n    float decay = fmin(1.f, correctedExp(decay_component));\n\n    weight *wp = &(*iter);\n    for (size_t i = 0; i < l.all->lda; ++i) wp[i] *= decay;\n  }\n}\n\nvoid end_examples(lda &l)\n{\n  if (l.all->weights.sparse)\n    end_examples(l, l.all->weights.sparse_weights);\n  else\n    end_examples(l, l.all->weights.dense_weights);\n}\n\nvoid finish_example(vw &all, lda &l, example &e)\n{\n  if (l.minibatch <= 1) { return return_example(all, e); }\n\n  if (l.examples.size() > 0)\n  {\n    // if there's still examples to be queued, inc only to finish later\n    l.finish_example_count++;\n  }\n  else\n  {\n    // return now since it has been processed (example size = 0)\n    return_example(all, e);\n  }\n\n  assert(l.finish_example_count <= l.minibatch);\n}\n\nstd::istream &operator>>(std::istream &in, lda_math_mode &mmode)\n{\n  std::string token;\n  in >> token;\n  if (token == \"simd\")\n    mmode = USE_SIMD;\n  else if (token == \"accuracy\" || token == \"precise\")\n    mmode = USE_PRECISE;\n  else if (token == \"fast-approx\" || token == \"approx\")\n    mmode = USE_FAST_APPROX;\n  else\n    THROW_EX(VW::vw_unrecognised_option_exception, token);\n  return in;\n}\n\nVW::LEARNER::base_learner *lda_setup(options_i &options, vw &all)\n{\n  auto ld = scoped_calloc_or_throw<lda>();\n  option_group_definition new_options(\"Latent Dirichlet Allocation\");\n  int math_mode;\n  new_options.add(make_option(\"lda\", ld->topics).keep().necessary().help(\"Run lda with <int> topics\"))\n      .add(make_option(\"lda_alpha\", ld->lda_alpha)\n               .keep()\n               .default_value(0.1f)\n               .help(\"Prior on sparsity of per-document topic weights\"))\n      .add(make_option(\"lda_rho\", ld->lda_rho)\n               .keep()\n               .default_value(0.1f)\n               .help(\"Prior on sparsity of topic distributions\"))\n      .add(make_option(\"lda_D\", ld->lda_D).default_value(10000.0f).help(\"Number of documents\"))\n      .add(make_option(\"lda_epsilon\", ld->lda_epsilon).default_value(0.001f).help(\"Loop convergence threshold\"))\n      .add(make_option(\"minibatch\", ld->minibatch).default_value(1).help(\"Minibatch size, for LDA\"))\n      .add(make_option(\"math-mode\", math_mode).default_value(USE_SIMD).help(\"Math mode: simd, accuracy, fast-approx\"))\n      .add(make_option(\"metrics\", ld->compute_coherence_metrics).help(\"Compute metrics\"));\n\n  if (!options.add_parse_and_check_necessary(new_options)) return nullptr;\n\n  // Convert from int to corresponding enum value.\n  ld->mmode = static_cast<lda_math_mode>(math_mode);\n\n  ld->finish_example_count = 0;\n\n  all.lda = (uint32_t)ld->topics;\n  ld->sorted_features = std::vector<index_feature>();\n  ld->total_lambda_init = false;\n  ld->all = &all;\n  ld->example_t = all.initial_t;\n  if (ld->compute_coherence_metrics)\n  {\n    ld->feature_counts.resize((uint32_t)(UINT64_ONE << all.num_bits));\n    ld->feature_to_example_map.resize((uint32_t)(UINT64_ONE << all.num_bits));\n  }\n\n  float temp = ceilf(logf((float)(all.lda * 2 + 1)) / logf(2.f));\n\n  all.weights.stride_shift((size_t)temp);\n  all.random_weights = true;\n  all.add_constant = false;\n\n  if (all.eta > 1.)\n  {\n    logger::errlog_warn(\"your learning rate is too high, setting it to 1\");\n    all.eta = std::min(all.eta, 1.f);\n  }\n\n  size_t minibatch2 = next_pow2(ld->minibatch);\n\n  //should num_parse_threads be specifiable or just 1? tell user this? write in the wiki page you make?\n  int num_parse_threads = 1;\n  if (minibatch2 > all.example_parser->ring_size)\n  {\n    bool previous_strict_parse = all.example_parser->strict_parse;\n    delete all.example_parser;\n    all.example_parser = new parser{minibatch2, previous_strict_parse, num_parse_threads};\n    all.example_parser->_shared_data = all.sd;\n  }\n\n  ld->v.resize_but_with_stl_behavior(all.lda * ld->minibatch);\n\n  ld->decay_levels.push_back(0.f);\n\n  all.example_parser->lbl_parser = no_label::no_label_parser;\n\n  VW::LEARNER::learner<lda, example> &l = init_learner(ld, ld->compute_coherence_metrics ? learn_with_metrics : learn,\n      ld->compute_coherence_metrics ? predict_with_metrics : predict, UINT64_ONE << all.weights.stride_shift(),\n      prediction_type_t::scalars, all.get_setupfn_name(lda_setup), true);\n\n  l.set_save_load(save_load);\n  l.set_finish_example(finish_example);\n  l.set_end_examples(end_examples);\n  l.set_end_pass(end_pass);\n\n  return make_base(l);\n}\n", "meta": {"hexsha": "742b9ed238dde093ba88902db55ca327d87e0c3f", "size": 39009, "ext": "cc", "lang": "C++", "max_stars_repo_path": "vowpalwabbit/lda_core.cc", "max_stars_repo_name": "nishantkr18/vowpal_wabb", "max_stars_repo_head_hexsha": "0a4e15f45cc71d88775cf4bdf36a4c56e0993a8b", "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": "vowpalwabbit/lda_core.cc", "max_issues_repo_name": "nishantkr18/vowpal_wabb", "max_issues_repo_head_hexsha": "0a4e15f45cc71d88775cf4bdf36a4c56e0993a8b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-05-27T11:17:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-18T17:41:31.000Z", "max_forks_repo_path": "vowpalwabbit/lda_core.cc", "max_forks_repo_name": "nishantkr18/vowpal_wabbit", "max_forks_repo_head_hexsha": "0a4e15f45cc71d88775cf4bdf36a4c56e0993a8b", "max_forks_repo_licenses": ["BSD-3-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.8101920236, "max_line_length": 120, "alphanum_fraction": 0.6500807506, "num_tokens": 11972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.03732688988752763, "lm_q1q2_score": 0.01851763974654292}}
{"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/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  Copyright (c) 2006-2011, The libDAI authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license that can be found\n * in the LICENSE file.\n */\n\n#include <algorithm>\n#include <cmath>\n#include <boost/dynamic_bitset.hpp>\n#include <dai/regiongraph.h>\n#include <dai/factorgraph.h>\n#include <dai/clustergraph.h>\n\nnamespace dai {\n\nusing namespace std;\n\nvoid RegionGraph::construct(\n    const FactorGraph& fg, const std::vector<VarSet>& ors,\n    const std::vector<Region>& irs,\n    const std::vector<std::pair<size_t, size_t>>& edges) {\n  // Copy factor graph structure\n  FactorGraph::operator=(fg);\n\n  // Copy inner regions\n  _IRs = irs;\n\n  // Construct outer regions (giving them counting number 1.0)\n  _ORs.clear();\n  _ORs.reserve(ors.size());\n  diaforeach(const VarSet& alpha, ors)\n      _ORs.push_back(FRegion(Factor(alpha, 1.0), 1.0));\n\n  // For each factor, find an outer region that subsumes that factor.\n  // Then, multiply the outer region with that factor.\n  _fac2OR.clear();\n  _fac2OR.reserve(nrFactors());\n  for (size_t I = 0; I < nrFactors(); I++) {\n    size_t alpha;\n    for (alpha = 0; alpha < nrORs(); alpha++)\n      if (OR(alpha).vars() >> factor(I).vars()) {\n        _fac2OR.push_back(alpha);\n        break;\n      }\n    DAI_ASSERT(alpha != nrORs());\n  }\n  recomputeORs();\n\n  // Create bipartite graph\n  _G.construct(nrORs(), nrIRs(), edges.begin(), edges.end());\n}\n\nvoid RegionGraph::constructCVM(const FactorGraph& fg,\n                               const std::vector<VarSet>& cl, size_t verbose) {\n  if (verbose)\n    cerr << \"constructCVM called (\" << fg.nrVars() << \" vars, \"\n         << fg.nrFactors() << \" facs, \" << cl.size() << \" clusters)\" << endl;\n\n  // Retain only maximal clusters\n  if (verbose)\n    cerr << \"  Constructing ClusterGraph\" << endl;\n  ClusterGraph cg(cl);\n  if (verbose)\n    cerr << \"  Erasing non-maximal clusters\" << endl;\n  cg.eraseNonMaximal();\n\n  // Create inner regions - first pass\n  if (verbose)\n    cerr << \"  Creating inner regions (first pass)\" << endl;\n  set<VarSet> betas;\n  for (size_t alpha = 0; alpha < cg.nrClusters(); alpha++)\n    for (size_t alpha2 = alpha; (++alpha2) != cg.nrClusters();) {\n      VarSet intersection = cg.cluster(alpha) & cg.cluster(alpha2);\n      if (intersection.size() > 0)\n        betas.insert(intersection);\n    }\n\n  // Create inner regions - subsequent passes\n  if (verbose)\n    cerr << \"  Creating inner regions (next passes)\" << endl;\n  set<VarSet> new_betas;\n  do {\n    new_betas.clear();\n    for (set<VarSet>::const_iterator gamma = betas.begin();\n         gamma != betas.end(); gamma++)\n      for (set<VarSet>::const_iterator gamma2 = gamma;\n           (++gamma2) != betas.end();) {\n        VarSet intersection = (*gamma) & (*gamma2);\n        if ((intersection.size() > 0) && (betas.count(intersection) == 0))\n          new_betas.insert(intersection);\n      }\n    betas.insert(new_betas.begin(), new_betas.end());\n  } while (new_betas.size());\n\n  // Create inner regions - final phase\n  if (verbose)\n    cerr << \"  Creating inner regions (final phase)\" << endl;\n  vector<Region> irs;\n  irs.reserve(betas.size());\n  for (set<VarSet>::const_iterator beta = betas.begin(); beta != betas.end();\n       beta++)\n    irs.push_back(Region(*beta, 0.0));\n\n  // Create edges\n  if (verbose)\n    cerr << \"  Creating edges\" << endl;\n  vector<pair<size_t, size_t>> edges;\n  for (size_t beta = 0; beta < irs.size(); beta++)\n    for (size_t alpha = 0; alpha < cg.nrClusters(); alpha++)\n      if (cg.cluster(alpha) >> irs[beta])\n        edges.push_back(pair<size_t, size_t>(alpha, beta));\n\n  // Construct region graph\n  if (verbose)\n    cerr << \"  Constructing region graph\" << endl;\n  construct(fg, cg.clusters(), irs, edges);\n\n  // Calculate counting numbers\n  if (verbose)\n    cerr << \"  Calculating counting numbers\" << endl;\n  calcCVMCountingNumbers();\n\n  if (verbose)\n    cerr << \"Done.\" << endl;\n}\n\nvoid RegionGraph::calcCVMCountingNumbers() {\n  // Calculates counting numbers of inner regions based upon counting numbers of\n  // outer regions\n\n  vector<vector<size_t>> ancestors(nrIRs());\n  boost::dynamic_bitset<> assigned(nrIRs());\n  for (size_t beta = 0; beta < nrIRs(); beta++) {\n    IR(beta).c() = 0.0;\n    for (size_t beta2 = 0; beta2 < nrIRs(); beta2++)\n      if ((beta2 != beta) && IR(beta2) >> IR(beta))\n        ancestors[beta].push_back(beta2);\n  }\n\n  bool new_counting;\n  do {\n    new_counting = false;\n    for (size_t beta = 0; beta < nrIRs(); beta++) {\n      if (!assigned[beta]) {\n        bool has_unassigned_ancestor = false;\n        for (vector<size_t>::const_iterator beta2 = ancestors[beta].begin();\n             (beta2 != ancestors[beta].end()) && !has_unassigned_ancestor;\n             beta2++)\n          if (!assigned[*beta2])\n            has_unassigned_ancestor = true;\n        if (!has_unassigned_ancestor) {\n          Real c = 1.0;\n          diaforeach(const Neighbor& alpha, nbIR(beta)) c -= OR(alpha).c();\n          for (vector<size_t>::const_iterator beta2 = ancestors[beta].begin();\n               beta2 != ancestors[beta].end(); beta2++)\n            c -= IR(*beta2).c();\n          IR(beta).c() = c;\n          assigned.set(beta, true);\n          new_counting = true;\n        }\n      }\n    }\n  } while (new_counting);\n}\n\nbool RegionGraph::checkCountingNumbers() const {\n  // Checks whether the counting numbers satisfy the fundamental relation\n\n  bool all_valid = true;\n  for (vector<Var>::const_iterator n = vars().begin(); n != vars().end(); n++) {\n    Real c_n = 0.0;\n    for (size_t alpha = 0; alpha < nrORs(); alpha++)\n      if (OR(alpha).vars().contains(*n))\n        c_n += OR(alpha).c();\n    for (size_t beta = 0; beta < nrIRs(); beta++)\n      if (IR(beta).contains(*n))\n        c_n += IR(beta).c();\n    if (fabs(c_n - 1.0) > 1e-15) {\n      all_valid = false;\n      cerr << \"WARNING: counting numbers do not satisfy relation for \" << *n\n           << \"(c_n = \" << c_n << \").\" << endl;\n    }\n  }\n\n  return all_valid;\n}\n\nvoid RegionGraph::recomputeORs() {\n  for (size_t alpha = 0; alpha < nrORs(); alpha++)\n    OR(alpha).fill(1.0);\n  for (size_t I = 0; I < nrFactors(); I++)\n    if (fac2OR(I) != -1U)\n      OR(fac2OR(I)) *= factor(I);\n}\n\nvoid RegionGraph::recomputeORs(const VarSet& ns) {\n  for (size_t alpha = 0; alpha < nrORs(); alpha++)\n    if (OR(alpha).vars().intersects(ns))\n      OR(alpha).fill(1.0);\n  for (size_t I = 0; I < nrFactors(); I++)\n    if (fac2OR(I) != -1U)\n      if (OR(fac2OR(I)).vars().intersects(ns))\n        OR(fac2OR(I)) *= factor(I);\n}\n\nvoid RegionGraph::recomputeOR(size_t I) {\n  DAI_ASSERT(I < nrFactors());\n  if (fac2OR(I) != -1U) {\n    size_t alpha = fac2OR(I);\n    OR(alpha).fill(1.0);\n    for (size_t J = 0; J < nrFactors(); J++)\n      if (fac2OR(J) == alpha)\n        OR(alpha) *= factor(J);\n  }\n}\n\n/// Send RegionGraph to output stream\nostream& operator<<(ostream& os, const RegionGraph& rg) {\n  os << \"digraph RegionGraph {\" << endl;\n  os << \"node[shape=box];\" << endl;\n  for (size_t alpha = 0; alpha < rg.nrORs(); alpha++)\n    os << \"\\ta\" << alpha << \" [label=\\\"a\" << alpha << \": \"\n       << rg.OR(alpha).vars() << \", c=\" << rg.OR(alpha).c() << \"\\\"];\" << endl;\n  os << \"node[shape=ellipse];\" << endl;\n  for (size_t beta = 0; beta < rg.nrIRs(); beta++)\n    os << \"\\tb\" << beta << \" [label=\\\"b\" << beta << \": \" << (VarSet)rg.IR(beta)\n       << \", c=\" << rg.IR(beta).c() << \"\\\"];\" << endl;\n  for (size_t alpha = 0; alpha < rg.nrORs(); alpha++)\n    diaforeach(const Neighbor& beta, rg.nbOR(alpha)) os\n        << \"\\ta\" << alpha << \" -> b\" << beta << \";\" << endl;\n  os << \"}\" << endl;\n  return os;\n}\n\n} // end of namespace dai\n", "meta": {"hexsha": "03fbb115fb634a9d608c1c201f0bb4314637c235", "size": 8796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/bp/libdai/src/regiongraph.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/bp/libdai/src/regiongraph.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/bp/libdai/src/regiongraph.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": 34.2256809339, "max_line_length": 80, "alphanum_fraction": 0.6126648477, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.04084571182343415, "lm_q1q2_score": 0.018513802824593667}}
{"text": "\r\n\r\n#include <Rcpp.h>\r\n#include <boost/multi_array.hpp> // 多次元配列用\r\n\r\nusing namespace Rcpp;\r\n\r\n// [[Rcpp::plugins(\"cpp11\")]]\r\n// [[Rcpp::depends(BH)]]\r\n//'Estimation of population distribution via EM algorithm.\r\n//'\r\n//'This function is new version of \\code{MML_EM_dist}\r\n//'@param x Item response matrix.\r\n//'@param para item parameter data.frame estimated by \\code{\\link{estip}}\r\n//'@param N the number of nodes in integration.\r\n//'@param fc0 a column of first item response.\r\n//'@param ng the number of groups\r\n//'@param gc0 a column of group. the element must be integer and the minimum number must be 1.\r\n//'@param eMLL a convergence criteria(CC) for marginal log likelihood.\r\n//'@param eDIST a CC for population distribution.\r\n//'@param D factor constant.\r\n//'@param fix Don't use. If 1, fix population distribution mean and sigma each EM cycle.\r\n//'@param print How much information you want to display? from 1 to 3. The larger, more information is displayed.\r\n//'@param max maximum value of theta in integration.\r\n//'@param min minimum value of theta in integration.\r\n//'@param maxiter_em maximum iteration time for EM cycle.\r\n//'@param rm_list a vector of item U want to remove for estimation. NOT list.\r\n//'@export\r\n// [[Rcpp::export]]\r\n\r\n\r\nList estdist(DataFrame x, DataFrame para, const int N = 31, const double eMLL = 1e-6, const double eDIST = 1e-4,\r\n             int fc0 = 2,int ng = 1, int gc0 = 2, const double D = 1.702, const int fix = 1, const int print = 0,\r\n             const double max = 4.0, const double min = -4.0, const int maxiter_em = 200,\r\n             CharacterVector rm_list = CharacterVector::create(\"NONE\")\r\n){\r\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n  // Update Information\r\n  //\r\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n  struct LocalFunc{ // R function define\r\n\r\n    static NumericVector colSums_cpp(NumericMatrix mat){ // R::colSums\r\n      Function f(\"colSums\");\r\n      return f(mat, _[\"na.rm\"] = true);\r\n    }\r\n\r\n    static NumericVector rowSums_cpp(NumericMatrix mat){ // R::rowSums\r\n      Function f(\"rowSums\");\r\n      return f(mat, _[\"na.rm\"] = true);\r\n    }\r\n\r\n    static NumericVector cor_cpp(NumericVector vec, NumericMatrix mat){ //R::cor\r\n      Function f(\"cor\");\r\n      return f(vec, _[\"y\"] = mat, _[\"use\"] = \"pairwise.complete.obs\");\r\n    }\r\n\r\n    static NumericVector colMeans_cpp(NumericMatrix mat){ // R::colMeans\r\n      Function f(\"colMeans\");\r\n      return f(mat, _[\"na.rm\"] = true);\r\n    }\r\n  };\r\n\r\n  const int lc = x.length();// item n\r\n  const int fc = fc0 -1;// Rcpp上では0から要素数がカウントされるので，数値を調整する。\r\n\r\n  // 入力データの確認\r\n  const int nj = lc - fc;\r\n  const int ni = x.nrows(); // subject n\r\n  int rm_n = 0;\r\n  if(rm_list[0] != \"NONE\") rm_n = rm_list.length();  // 削除項目\r\n\r\n  const int gc = gc0 -1;\r\n\r\n  IntegerVector group (ni,1);\r\n  if(ng != 1) group = x[gc];\r\n  //NumericVector group = x[gc];\r\n\r\n  group = group -1; // 集団変数を，C++の要素数に適合するように，-1する。\r\n\r\n  NumericMatrix xall (ni, nj);\r\n  CharacterVector Item_temp = x.names();\r\n  CharacterVector Item (nj);\r\n  for (int j=0; j<nj; j++){ // もとのデータフレームから項目反応パタンだけを抜き出し，行列として保存\r\n    int jj = j + fc;\r\n    NumericVector kk = x[jj];\r\n    Item[j] = Item_temp[jj];\r\n    for(int i=0; i<ni; i++){\r\n      double k = kk[i];\r\n      xall(i,j) = k;\r\n    }\r\n  }\r\n  // 削除した項目の列番号（データフレーム）を取得\r\n  IntegerVector rm_id(1,9999);\r\n\r\n  if(rm_list[0] != \"NONE\"){\r\n    Rcout<<\"You select Item; \"<<rm_list<<\"as not use.\\n\";\r\n    rm_id = IntegerVector(rm_n); // result\r\n    for(int l=0; l<rm_n; l++){\r\n      String r = rm_list[l];\r\n      rm_id[l] = x.findName(r)-(fc-1);\r\n    }\r\n  } else {\r\n\r\n  }\r\n\r\n\r\n  // 欠測値がある箇所を0，そうではない箇所を1とした行列を作成\r\n  NumericMatrix resp (ni,nj);\r\n  for(int i=0; i<ni; i++){\r\n    for(int j=0; j<nj; j++){\r\n      if(NumericVector::is_na(xall(i,j))) resp(i,j) = 0; // NAならば0を\r\n      else resp(i,j) = 1; // NA以外（0か1）ならば1を\r\n    }\r\n  }\r\n\r\n\r\n  NumericMatrix ind (ng,nj); // 当該集団が，項目に回答したか否か\r\n  for(int g=0; g<ng; g++){\r\n    // 集団が受検した項目を確認\r\n    for(int i=0; i<ni; i++){\r\n      if(group[i] != g) continue;\r\n      for(int j=0; j<nj; j++){\r\n        int q = ind(g,j);\r\n        ind(g,j)= q + resp(i,j);\r\n      }\r\n    }\r\n\r\n    for( int j=0; j<nj; j++){\r\n      int q = ind(g,j);\r\n      if(q != 0) ind(g,j) = 1; // 誰か一人でも回答していたら1，集団内が全員無回答なら0\r\n    }\r\n  }\r\n\r\n\r\n  Rcout << \"The number of subject is \" << ni << \".\\nThe number of item is \" << nj-rm_n <<\".\\nThe number of remove item is \"<<rm_n<<\".\\n\";\r\n\r\n\r\n  // initial values\r\n  NumericMatrix t0(nj,3);\r\n  NumericVector a0 = para[\"a\"];\r\n  NumericVector b0 = para[\"b\"];\r\n  NumericVector c0 = para[\"c\"];\r\n  // NumericVector a0 = para[0];\r\n  // NumericVector b0 = para[1];\r\n  // NumericVector c0 = para[2];\r\n  for(int j=0; j<nj; j++){\r\n    t0(j,0) = a0[j];\r\n    t0(j,1) = b0[j];\r\n    t0(j,2) = c0[j];\r\n  }\r\n\r\n  // prior distribution\r\n  double seq = (max - min)/(N-1); // 分点の間隔。これは全母集団で固定。\r\n  NumericVector Xm (N);\r\n  Xm[0] = min;\r\n  for(int m=1; m<N; m++){\r\n    double pre = Xm[m-1];\r\n    Xm[m] = pre + seq;\r\n  }\r\n\r\n\r\n  // 母集団分布の初期値を決定。\r\n  NumericMatrix Um (N,ng); // 推定母集団分布計算用\r\n  NumericMatrix dist (0);\r\n\r\n\r\n  // 結果代入用の行列，ベクトルを準備　＝　こうしないと，最終的にスコープできない。\r\n  boost::multi_array <double, 3> Gim (boost::extents[ng][ni][N]);\r\n  boost::multi_array <double, 3> Lim (boost::extents[ng][ni][N]);\r\n  boost::multi_array <double, 3> Nm (boost::extents[ng][nj][N]);\r\n  boost::multi_array <double, 3> rjm (boost::extents[ng][nj][N]);\r\n  NumericMatrix skip_para (nj,3); // 推定に失敗した項目番号の代入用\r\n\r\n  /////////////////////////\r\n  // EM step starts here //\r\n  /////////////////////////\r\n  // 推定母集団分布の計算\r\n  // 初期値に一様分布をもちいた場合，Easy Estimationの計算結果とおおむね一致するはず。\r\n\r\n  Rprintf(\"Start calculating estimated population distribution.\\n\");\r\n\r\n  // result\r\n  NumericVector mean_pop(ng);\r\n  NumericVector sd_pop(ng);\r\n  double diff2 = 0;\r\n  NumericVector MLL2 (0);\r\n\r\n  // 一様分布を初期値に設定する。\r\n  NumericMatrix unif_dist (0);\r\n  double NN = Um.nrow();\r\n  for(int i=0; i<N; i++){\r\n    for(int j=0; j<ng; j++){\r\n      Um(i,j) = 1/NN;\r\n    }\r\n  }\r\n\r\n\r\n  // start loop\r\n  int count3 =0;\r\n  int conv3 = 0;\r\n  LogicalVector conv0(ng);\r\n\r\n  while(conv3 == 0){\r\n    count3 += 1;\r\n\r\n    // calculate Lim\r\n    double a,b,c,t,xx,tt,u;\r\n    int g,i,m,j;\r\n    for(g=0; g<ng; g++){\r\n      for(i=0; i<ni; i++){\r\n        if(group[i] != g) continue; // 集団に属さない受験者の部分はスキップ\r\n        for(m=0; m<N; m++){\r\n          t = 1;\r\n          xx = Xm[m];\r\n          tt = 0;\r\n          for(j=0; j<nj; j++){\r\n            //if(resp(i,j)==0) continue; // NAの反応パタンのところは計算ループから外れる。\r\n            a = t0(j,0);\r\n            if(a==0)continue;\r\n            b = t0(j,1);\r\n            c = t0(j,2);\r\n            u = xall(i,j);\r\n            if(u == 1){ // 正答した場合の尤度\r\n              tt = c+(1.0-c)/(1.0+exp(-D*a*(xx-b)));\r\n            } else if (u == 0) { // 誤答した場合の尤度\r\n              tt = 1.0-(c+(1.0-c)/(1.0+exp(-D*a*(xx-b))));\r\n            } else { // 欠測値の場合は尤度を計算しないので，1\r\n              tt = 1;\r\n            }\r\n            t = t * tt; // sum\r\n          }\r\n          //boost::multi_array<double, 3>::index idx = {{g,i,m}};\r\n          Lim[g][i][m] = t;\r\n        }\r\n      }\r\n    }\r\n\r\n\r\n    //Rcout<<\"marginal log likelihood calculation.\\n\";\r\n    // Calculation marginal log likelihood\r\n\r\n    double f = 0; // 周辺対数尤度代入用\r\n    double ff,fff,l,w;\r\n\r\n    for(int g=0; g<ng; g++){\r\n      for(int i=0; i<ni; i++){\r\n        if(group[i] != g) continue; // 集団に属さない受験者の部分はスキップ\r\n        ff = 0; // 受検者iの周辺対数尤度代入用\r\n        for(int m=0; m<N; m++){\r\n          l = Lim[g][i][m];\r\n          w = Um(m,g);\r\n          fff =  l*w ;\r\n          ff = ff + fff;\r\n        }\r\n        f = f + log(ff);\r\n      }\r\n    }\r\n\r\n    MLL2.push_back(f);\r\n    diff2 = fabs(MLL2[count3-1] - MLL2[count3]); // 周辺対数尤度の差\r\n\r\n    //Rcout << \"-2 Marginal Log Likelihood is \" << -2 * f <<\"\\r\";\r\n    Rprintf(\"%d times -2 Marginal Log Likelihood is %f \\r\",count3,-2*f); // 小数点形式の出力に対応\r\n\r\n\r\n    // calculate Gim\r\n    double uu;\r\n    for(int g=0; g<ng; g++){\r\n      for(int i=0; i<ni; i++){\r\n        if(group[i] != g) continue; // 集団に属さない受験者の部分はスキップ\r\n        u = 0;\r\n        for(int m=0; m<N; m++){ // 総和を1にするための分母の計算 // sum\r\n          l = Lim[g][i][m];\r\n          w = Um(m,g);\r\n          uu = l*w;\r\n          u = u + uu;\r\n        }\r\n        for(int m=0; m<N; m++){\r\n          l = Lim[g][i][m];\r\n          w = Um(m,g);\r\n          Gim[g][i][m] =  l * w / u;\r\n        }\r\n      }\r\n    }\r\n\r\n    // calculate Nm\r\n\r\n    //Rcout<<\"expected frequency of subjects in each nodes calculation.\\n\";\r\n    double k,kk;\r\n    for(int g=0; g<ng; g++){\r\n      for(int j=0; j<nj; j++){ // 各分点の期待度数\r\n        if(ind(g,j) == 0) continue;\r\n        for(int m=0; m<N; m++){\r\n          k = 0;\r\n          for(int i=0; i<ni; i++){ // 欠測値がある場合，項目ごとに受検者数が異なる。\r\n            if(resp(i,j)==0) continue;\r\n            //double d = resp(i,j);\r\n            kk = Gim[g][i][m];\r\n            k = k + kk; //* d;\r\n          }\r\n          Nm[g][j][m] = k;\r\n        }\r\n      }\r\n    }\r\n\r\n    // 一様分布の確率密度をリセット\r\n    for(int m=0; m<N; m++){\r\n      for(int g=0; g<ng; g++){\r\n        Um(m,g) = 0;\r\n      }\r\n    }\r\n\r\n    // 母集団ごとの平均と標準偏差を計算\r\n    for(int g=0; g<ng; g++){\r\n      // probability\r\n      double mean_g = 0;\r\n      double sd_g = 0;\r\n      //int counti = 0; // 母集団の受検した項目数カウント用\r\n      for(int j=0; j<nj; j++){\r\n        // 集団内のだれも回答をしていなかったら，次の項目のループへスキップ。\r\n        if(ind(g,j) == 0) continue;\r\n\r\n        //counti = counti + 1;\r\n        double mean_j = 0;\r\n        double sNjm = 0; // 項目ごとの分点の受験者の期待度数の総和代入用\r\n        for(int m=0; m<N; m++){  // sum\r\n          double Njm = Nm[g][j][m];\r\n          sNjm = sNjm + Njm;\r\n        }\r\n\r\n        for(int m=0; m<N; m++){ // sum\r\n          double Njm = Nm[g][j][m];\r\n          double xm = Xm[m];\r\n          double tempM = xm * Njm/sNjm; // E(X) = \\Sigma(x_i * prob_i)\r\n          Um(m,g) += Njm/sNjm;\r\n          mean_j += tempM; //\r\n        } // end of m\r\n        mean_g = mean_g + mean_j; // 項目ごとの母集団平均を足し上げたもの\r\n\r\n        // sd\r\n\r\n        double var_j = 0;\r\n        double sd_j = 0;\r\n        for(int m=0; m<N; m++){\r\n          double Njm = Nm[g][j][m];\r\n          double xm = Xm[m];\r\n          double tempV = (xm -mean_j)*(xm -mean_j)*Njm/sNjm; // V(X) = Sigma(x_i-E(X))^2*prob_i\r\n          var_j = var_j + tempV;\r\n        }// end of m\r\n        sd_j = std::sqrt(var_j); // 項目ごとに計算した標準偏差\r\n        sd_g = sd_g + sd_j; // 項目ごとの母集団標準偏差を足し上げたもの\r\n\r\n      } // end of j\r\n\r\n      int counti = sum(ind(g,_));\r\n      // 収束判定用\r\n      if(fabs(mean_pop[g] - mean_g/counti)<eDIST && fabs(sd_pop[g] - sd_g/counti)<eDIST ) conv0[g] = 1;\r\n\r\n      mean_pop[g] = mean_g/counti; // 全項目における母集団平均の，平均\r\n      sd_pop[g] = sd_g/counti; // 全項目における母集団標準偏差の，平均\r\n      if(print >= 1) Rcout << \"mean: \"<< mean_pop[g]<<\", sd: \"<<sd_pop[g]<<\"\\n\";\r\n\r\n      for(int m=0; m<N; m++){\r\n        Um(m,g) /= counti;\r\n      }\r\n\r\n    } // end of g\r\n\r\n    if(diff2 < eMLL || is_true(all(conv0)) ) conv3 = 1;\r\n    //break;\r\n  }\r\n\r\n  unif_dist = cbind(Xm,Um);\r\n\r\n  List res = List::create(_[\"population_dist\"] = unif_dist, _[\"population_mean\"] = mean_pop, _[\"population_sd\"] = sd_pop,\r\n                          _[\"MLL\"] = MLL2, _[\"conv\"] = conv3, _[\"count\"] = count3,\r\n                          _[\"skip_para\"] = skip_para, _[\"rm_n\"] = rm_n, _[\"rm_id\"] = rm_id\r\n  );\r\n\r\n  return res;\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "b1774aa69b09a629d5d29e77a2271fc30357cef6", "size": 11355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MML-EM_dist.cpp", "max_stars_repo_name": "takuizum/irtfun2", "max_stars_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MML-EM_dist.cpp", "max_issues_repo_name": "takuizum/irtfun2", "max_issues_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MML-EM_dist.cpp", "max_forks_repo_name": "takuizum/irtfun2", "max_forks_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_forks_repo_licenses": ["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.4170984456, "max_line_length": 152, "alphanum_fraction": 0.4971378247, "num_tokens": 4217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.040845711677487184, "lm_q1q2_score": 0.01851380275844148}}
{"text": "/*! @file wavelet_filter_bank.cc\n *  @brief Wavelet filter bank tree (mid level).\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/primitives/wavelet_filter_bank.h\"\n#include <cassert>\n#include <cstring>\n#include <algorithm>\n#include <list>\n#include <memory>\n#include <string>\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n#include <boost/regex.hpp>  // NOLINT(build/include_order)\n#pragma GCC diagnostic pop\n#include <simd/wavelet.h>\n#include \"src/stoi_function.h\"\n\nnamespace sound_feature_extraction {\n\nTreeFingerprint Parse(const std::string& str, identity<TreeFingerprint>) {\n  static const boost::regex all_regex(\"^\\\\s*(\\\\d+\\\\s*(\\\\s|$))+\");\n  static const boost::regex int_regex(\"(\\\\d+\\\\s*(\\\\s|$))\");\n\n  boost::smatch match;\n  if (!boost::regex_match(str, match, all_regex)) {\n    throw WaveletTreeDescriptionParseException(str);\n  }\n\n  TreeFingerprint res;\n  try {\n    std::transform(boost::sregex_token_iterator(str.begin(), str.end(),\n                                                int_regex,\n                                                1),\n                   boost::sregex_token_iterator(),\n                   std::back_inserter(res),\n                   std::stoi_function);\n  }\n  catch(const std::invalid_argument& e) {\n    throw WaveletTreeDescriptionParseException(str);\n  }\n  if (res.empty()) {\n    throw WaveletTreeDescriptionParseException(str);\n  }\n  return res;\n}\n\nWaveletType Parse(const std::string& value, identity<WaveletType>) {\n  static const std::unordered_map<std::string, WaveletType> map = {\n    { WAVELET_TYPE_DAUBECHIES_STR, WAVELET_TYPE_DAUBECHIES },\n    { WAVELET_TYPE_COIFLET_STR, WAVELET_TYPE_COIFLET },\n    { WAVELET_TYPE_SYMLET_STR, WAVELET_TYPE_SYMLET }\n  };\n  auto it = map.find(value);\n  if (it == map.end()) {\n    throw WaveletTreeWaveletTypeParseException(value);\n  }\n  return it->second;\n}\n\nnamespace primitives {\n\nWaveletFilterBank::WaveletFilterBank(WaveletType type, int order,\n                                     const TreeFingerprint& treeDescription)\n    : type_(type),\n      order_(order),\n      tree_(treeDescription) {\n\n  ValidateDescription(treeDescription);\n}\n\nWaveletFilterBank::WaveletFilterBank(WaveletType type, int order,\n                                     TreeFingerprint&& treeDescription)\n    : type_(type),\n      order_(order),\n      tree_(treeDescription) {\n  ValidateDescription(treeDescription);\n}\n\nvoid WaveletFilterBank::ValidateWavelet(WaveletType type,\n                                      int order) {\n  if (!wavelet_validate_order(type, order)) {\n    throw WaveletTreeInvalidOrderException(type, order);\n  }\n}\n\nvoid WaveletFilterBank::ValidateDescription(\n    const TreeFingerprint& treeDescription) {\n  if (treeDescription.size() < 2) {\n    throw WaveletTreeInvalidDescriptionException(treeDescription);\n  }\n  std::list<int> tree(treeDescription.begin(), treeDescription.end());\n  while (!tree.empty()) {\n    // Reduce the tree using a simple grammar:\n    // (n) (n) -> (n - 1)\n    bool reduced = false;\n    for (auto it = tree.begin(); it != tree.end(); it++) {\n       auto next = it;\n       next++;\n       if (next != tree.end() && *it == *next) {\n         if (*it == 1 && tree.size() == 2) {\n           tree.erase(it, tree.end());\n         } else {\n           *it = *it - 1;\n           tree.erase(next);\n         }\n         reduced = true;\n         break;\n       }\n    }\n    if (!reduced) {\n      throw WaveletTreeInvalidDescriptionException(treeDescription);\n    }\n  }\n}\n\nvoid WaveletFilterBank::ValidateLength(\n    const TreeFingerprint& tree, size_t length) {\n  int max = *std::max_element(tree.begin(), tree.end());\n  // length / 2^max >= 1\n  if (length == 0 || length % (1 << max) != 0) {\n    throw WaveletTreeInvalidSourceLengthException(tree, length);\n  }\n}\n\nvoid WaveletFilterBank::Apply(const float* source, size_t length,\n                              float *result) noexcept {\n  assert(source && result);\n  ValidateLength(tree_, length);\n\n  // Support zero-copy\n  auto lsrc =\n#ifndef __AVX__\n      (source == result)? result :\n#endif\n      wavelet_prepare_array(order_, source, length);\n  ApplyInternal(lsrc, length, result);\n#ifndef __AVX__\n  if (source != result) {\n#endif\n  free(lsrc);\n#ifndef __AVX__\n  }\n#endif\n}\n\nvoid WaveletFilterBank::ApplyInternal(float* source, size_t length,\n                                      float *result) noexcept {\n  assert(source && result);\n  ValidateLength(tree_, length);\n\n  TreeFingerprint tree(tree_);\n  std::reverse(tree.begin(), tree.end());\n  TreeFingerprint workingTree;\n  workingTree.reserve(tree.size());\n\n  auto ldesthi = std::unique_ptr<float, decltype(&std::free)>(\n      wavelet_allocate_destination(order_, length), free);\n  auto ldestlo = std::unique_ptr<float, decltype(&std::free)>(\n      wavelet_allocate_destination(order_, length), free);\n  wavelet_apply(type_, order_, EXTENSION_TYPE_PERIODIC, source, length,\n                ldesthi.get(), ldestlo.get());\n  float *desthihi, *desthilo, *destlohi, *destlolo;\n  wavelet_recycle_source(order_, source, length,\n                         &desthihi, &desthilo,\n                         &destlohi, &destlolo);\n  workingTree.push_back(1);\n  workingTree.push_back(1);\n\n  while (!tree.empty()) {\n    RecursivelyIterate(type_, order_, length / 2, &tree, &workingTree,\n                       ldesthi.get(), desthihi, desthilo, &result);\n    RecursivelyIterate(type_, order_, length / 2, &tree, &workingTree,\n                       ldestlo.get(), destlohi, destlolo, &result);\n  }\n}\n\nvoid WaveletFilterBank::RecursivelyIterate(\n    WaveletType type, int order, size_t length,\n    TreeFingerprint *tree, TreeFingerprint* workingTree, float* source,\n    float* desthi, float* destlo, float** result) noexcept {\n  if (tree->back() != workingTree->back()) {\n    wavelet_apply(type, order, EXTENSION_TYPE_PERIODIC, source, length, desthi,\n                  destlo);\n    float *desthihi, *desthilo, *destlohi, *destlolo;\n    wavelet_recycle_source(order, source, length,\n                           &desthihi, &desthilo,\n                           &destlohi, &destlolo);\n    int next = workingTree->back() + 1;\n    workingTree->pop_back();\n    workingTree->push_back(next);\n    workingTree->push_back(next);\n    RecursivelyIterate(type, order, length / 2, tree, workingTree,\n                       desthi, desthihi, desthilo, result);\n    RecursivelyIterate(type, order, length / 2, tree, workingTree,\n                       destlo, destlohi, destlolo, result);\n  } else {\n    memcpy(*result, source, length * sizeof(source[0]));\n    *result += length;\n    tree->pop_back();\n    workingTree->pop_back();\n  }\n}\n\n}  // namespace primitives\n}  // namespace sound_feature_extraction\n", "meta": {"hexsha": "aaebf190479ae8ae6159955a99f7c3eaa5c55d8d", "size": 7809, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/primitives/wavelet_filter_bank.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/primitives/wavelet_filter_bank.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/primitives/wavelet_filter_bank.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": 33.5150214592, "max_line_length": 136, "alphanum_fraction": 0.6483544628, "num_tokens": 1924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.04672496211064144, "lm_q1q2_score": 0.018506270728558673}}
{"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/// @author Vitaliy Ogarko <vogarko@gmail.com>\n///\n#ifdef HAVE_MPI\n#include <mpi.h>\n#endif\n\n#include <fitting/LinearSolver.h>\n#include <fitting/GenericNormalEquations.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#include <casacore/casa/OS/Timer.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n\n#include <lsqr_solver/GlobalTypedefs.h>\n#include <lsqr_solver/SparseMatrix.h>\n#include <lsqr_solver/LSQRSolver.h>\n#include <lsqr_solver/ModelDamping.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           itsWorkersComm(NULL),\n           itsMajorLoopIterationNumber(0)\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    \n    // this has been added to the subset, so delete it\n    names.erase(names.begin());\n\n    // for each name in subset (which grows as matches are found), check all remaining names for associates.\n    for (std::vector<std::string>::const_iterator ciRes = resultNames.begin(); ciRes != resultNames.end(); ++ciRes) {\n\n        // keep a temporary list of added names to erase from the main list\n        std::vector<std::string> toErase;\n        toErase.reserve(names.size());\n\n        for (std::vector<std::string>::const_iterator ci = names.begin(); ci != names.end(); ++ci) {\n            const casa::Matrix<double>& nm1 = normalEquations().normalMatrix(*ci, *ciRes);\n            const casa::Matrix<double>& nm2 = normalEquations().normalMatrix(*ciRes, *ci);\n\n            if (!allMatrixElementsAreZeros(nm1,tolerance) || !allMatrixElementsAreZeros(nm2,tolerance)) {\n                // this parameter (iterated in the inner loop) belongs to the subset\n                resultNames.push_back(*ci);\n                // also add it to the temporary list of added names to erased\n                toErase.push_back(*ci);\n            } \n        }\n\n        // erase all of the names that have just been added from the main list\n        for (std::vector<std::string>::iterator it0 = toErase.begin(); it0 != toErase.end(); ++it0) {\n            std::vector<std::string>::iterator it = std::find(names.begin(), names.end(), *it0);\n            if (it != names.end()) names.erase(it);\n        }\n\n    } \n    return resultNames;\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    bool algorithmLSQR = (algorithm() == \"LSQR\");\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    std::map<string, size_t> indicesMap;\n\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            ASKAPDEBUGASSERT(it != indices.end());\n            it->second = nParameters;\n            it->first = *cit;\n\n            indicesMap[it->first] = (size_t)(it->second);\n\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    gsl_matrix * A = 0;\n    gsl_vector * B = 0;\n    gsl_vector * X = 0;\n\n    if (!algorithmLSQR) {\n        // Containers to convert the normal equations to gsl format.\n        A = gsl_matrix_alloc (nParameters, nParameters);\n        B = gsl_vector_alloc (nParameters);\n        X = gsl_vector_alloc (nParameters);\n    }\n\n    const GenericNormalEquations& gne = dynamic_cast<const GenericNormalEquations&>(normalEquations());\n    size_t nElements = gne.getNumberElements();\n\n    ASKAPLOG_INFO_STR(logger, \"Linear solver nParameters = \" << nParameters << \", nElements = \" << nElements);\n\n    //------------------------------------------------------------------------------\n    // Define LSQR solver sparse matrix.\n    //------------------------------------------------------------------------------\n    void* comm = NULL;\n    size_t nrows = 0;\n    size_t nnz = 0;\n    bool addSmoothnessConstraints = false;\n\n    if (algorithmLSQR) {\n\n#ifdef HAVE_MPI\n        MPI_Comm comm_world = MPI_COMM_WORLD;\n        comm = (void *)&comm_world;\n#endif\n\n        // Define approximate number of nonzero elements.\n        // Note: nElements may contain elements which are not currently being solved for.\n        if (nElements <= nParameters * nParameters) {\n            nnz = nElements;\n        } else {\n            nnz = nParameters * nParameters;\n        }\n\n        nrows = nParameters;\n        if (parameters().count(\"smoothing\") > 0\n            && parameters().at(\"smoothing\") == \"true\") {\n            addSmoothnessConstraints = true;\n        }\n\n        if (addSmoothnessConstraints) {\n            nrows += nParameters;\n            nnz += 2 * nParameters;\n        }\n    }\n    lsqr::SparseMatrix matrix(nrows, nnz, comm);\n\n    //--------------------------------------------------------------------------------------------\n    // Copy matrix elements from normal matrix (map of map of matrixes) to the solver matrix:\n    //      - to gsl NxN matrix, for the SVD solver;\n    //      - to sparse matrix (CSR format), for the LSQR solver.\n    //--------------------------------------------------------------------------------------------\n\n    // Loop over matrix rows.\n    for (std::vector<std::pair<string, int> >::const_iterator indit1 = indices.begin();\n            indit1 != indices.end(); ++indit1) {\n\n        const std::map<string, casa::Matrix<double> >::const_iterator colItBeg = gne.getNormalMatrixRowBegin(indit1->first);\n        const std::map<string, casa::Matrix<double> >::const_iterator colItEnd = gne.getNormalMatrixRowEnd(indit1->first);\n\n        ASKAPCHECK(colItBeg != colItEnd, \"Normal matrix has no elements for row = \" << indit1->first << \", this shouldn't happen!\");\n\n        const casa::uInt nrow = colItBeg->second.nrow();\n\n        for (size_t row = 0; row < nrow; ++row) {\n\n            if (algorithmLSQR) {\n                matrix.NewRow();\n            }\n\n            // Loop over column elements.\n            for (std::map<string, casa::Matrix<double> >::const_iterator colIt = colItBeg;\n                    colIt != colItEnd; ++colIt) {\n\n                const std::map<string, size_t>::const_iterator indicesMapIt = indicesMap.find(colIt->first);\n                if (indicesMapIt != indicesMap.end()) {\n                // It is a parameter to solve for, adding it to the matrix.\n\n                    const size_t colIndex = indicesMapIt->second;\n                    const casa::Matrix<double>& nm = colIt->second;\n\n                    ASKAPCHECK(nrow == nm.nrow(), \"Not consistent normal matrix element element dimension!\");\n\n                    const size_t ncolumn = nm.ncolumn();\n                    for (size_t col = 0; col < 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 happen!\");\n\n                         if (algorithmLSQR) {\n                             matrix.Add(elem, col + colIndex);\n\n                         } else {\n                             gsl_matrix_set(A, row + (indit1->second), col + colIndex, elem);\n                         }\n                    }\n                }\n            }\n        }\n    }\n\n    if (algorithmLSQR) {\n        size_t nonzeros = matrix.GetNumberElements();\n        ASKAPLOG_INFO_STR(logger, \"Linear solver Jacobian nonzeros = \" << nonzeros);\n        ASKAPLOG_INFO_STR(logger, \"Linear solver Jacobian sparsity = \" << (double)(nonzeros) / (double)(nParameters * nParameters));\n    }\n\n    if (!algorithmLSQR) {\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 happen!\");\n                 gsl_vector_set(B, row+(indit1->second), elem);\n            }\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        ASKAPLOG_INFO_STR(logger, \"Solving normal equations using the SVD solver\");\n\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        gsl_error_handler_t *oldhandler=gsl_set_error_handler_off();\n        ASKAPLOG_DEBUG_STR(logger, \"Running SV decomp\");\n        const int status = gsl_linalg_SV_decomp (A, V, S, work);\n        // ASKAPCHECK(status == 0, \"gsl_linalg_SV_decomp failed, status = \"<<status);\n        gsl_set_error_handler(oldhandler);\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         if (status != 0) {\n             ASKAPLOG_WARN_STR(logger, \"Solution is considered invalid due to gsl_linalg_SV_decomp failure, main matrix is effectively rank zero\");\n             quality.setRank(0);\n             quality.setCond(0.);\n             quality.setInfo(\"SVD decomposition rank deficient\");\n         } else {\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\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//                 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    }\n    else if (algorithmLSQR) {\n        ASKAPLOG_INFO_STR(logger, \"Solving normal equations using the LSQR solver\");\n\n        int myrank = 0;\n        int nbproc = 1;\n\n        lsqr::Vector b_RHS(nrows, 0.);\n\n        // Define the right-hand side (the data misfit part).\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 happen!\");\n                 //gsl_vector_set(B, row+(indit1->second), elem);\n                 b_RHS[row+(indit1->second)] = elem;\n            }\n        }\n\n        if (addSmoothnessConstraints) {\n        //-----------------------------------------------\n        // Adding smoothness constraints.\n        //-----------------------------------------------\n            // Setting the smoothing weight.\n            double smoothingWeight = 0.;\n            if (addSmoothnessConstraints) {\n                double smoothingMinWeight = 0.;\n                if (parameters().count(\"smoothingMinWeight\") > 0) {\n                    smoothingMinWeight = std::atof(parameters().at(\"smoothingMinWeight\").c_str());\n                }\n\n                double smoothingMaxWeight = 3.e+6;\n                if (parameters().count(\"smoothingMaxWeight\") > 0) {\n                    smoothingMaxWeight = std::atof(parameters().at(\"smoothingMaxWeight\").c_str());\n                }\n\n                size_t nsteps = 10;\n                if (parameters().count(\"smoothingNsteps\") > 0) {\n                    nsteps = std::atoi(parameters().at(\"smoothingNsteps\").c_str());\n                }\n\n                if (itsMajorLoopIterationNumber < nsteps) {\n                    if (smoothingMinWeight == smoothingMaxWeight) {\n                        smoothingWeight = smoothingMaxWeight;\n                    } else {\n                        double span = smoothingMaxWeight - smoothingMinWeight;\n                        ASKAPCHECK(span > 0, \"Wrong smoothing weight!\");\n\n                        // Logarithmic sweep (between the min and max weights).\n                        smoothingWeight = smoothingMinWeight + std::pow(10., log10(span) / (double)(nsteps) * (double)(itsMajorLoopIterationNumber));\n                    }\n                } else {\n                    // Relaxation with constant weight.\n                    smoothingWeight = smoothingMaxWeight;\n                }\n            }\n            ASKAPLOG_INFO_STR(logger, \"Adding smoothness constraints, with weight = \" << smoothingWeight);\n\n            // Reading the number of channels.\n            size_t nChannels = 0;\n            if (parameters().count(\"nChan\") > 0) {\n                nChannels = std::atoi(parameters().at(\"nChan\").c_str());\n            }\n            ASKAPCHECK(nChannels > 1, \"Wrong number of channels for smoothness constraints!\");\n\n            // Extract the solution at the current major iteration (before the update).\n            std::vector<double> x0(nParameters);\n            int counter = 0;\n            for (std::vector<std::pair<string, int> >::const_iterator indit = indices.begin();\n                             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                    x0[indit->second + i] = value(i);\n                    counter++;\n                }\n            }\n            ASKAPCHECK(counter == nParameters, \"Wrong number of parameters!\");\n\n            // Build indexes maps (needed to add smoothness constraints to the matrix).\n            std::map<std::pair<casa::uInt, std::string>, size_t> gainIndexesReal;\n            std::map<std::pair<casa::uInt, std::string>, size_t> gainIndexesImag;\n            for (std::vector<std::pair<string, int> >::const_iterator indit = indices.begin();\n                 indit != indices.end(); ++indit) {\n                // Make sure there are two unknowns per parameter: real and imaginary parts of the complex gain value.\n                ASKAPCHECK(params.value(indit->first).nelements() == 2, \"Number of unknowns per parameter name is not correct!\");\n\n                // Extracting channel and parameter name.\n                std::pair<casa::uInt, std::string> paramInfo = extractChannelInfo(indit->first);\n\n                gainIndexesReal.insert(make_pair(paramInfo, indit->second));     // real part\n                gainIndexesImag.insert(make_pair(paramInfo, indit->second + 1)); // imaginary part\n            }\n\n            double cost = 0.;\n            for (std::vector<std::pair<string, int> >::const_iterator indit = indices.begin();\n                             indit != indices.end(); ++indit) {\n                // Extracting channel and parameter name.\n                std::pair<casa::uInt, std::string> paramInfo = extractChannelInfo(indit->first);\n                size_t channel = paramInfo.first;\n\n                bool lastChannel = (channel == nChannels - 1);\n                if (!lastChannel) {\n\n                    std::string name = paramInfo.second;\n\n                    size_t currIndex[2];\n                    size_t nextIndex[2];\n\n                    // Extracting parameter indexes for the current channel.\n                    currIndex[0] = gainIndexesReal[make_pair(channel, name)];\n                    currIndex[1] = gainIndexesImag[make_pair(channel, name)];\n\n                    ASKAPCHECK((int)currIndex[0] == indit->second, \"Wrong index (real)!\");\n                    ASKAPCHECK((int)currIndex[1] == indit->second + 1, \"Wrong index (imag)!\");\n\n                    // Extracting parameter indexes for the next channel.\n                    nextIndex[0] = gainIndexesReal[make_pair(channel + 1, name)];\n                    nextIndex[1] = gainIndexesImag[make_pair(channel + 1, name)];\n\n                    for (size_t i = 0; i < 2; ++i) {\n                        matrix.NewRow();\n\n                        // Applying forward difference grad(f) = f[i+1] - f[i].\n                        matrix.Add(- smoothingWeight, currIndex[i]);\n                        matrix.Add(+ smoothingWeight, nextIndex[i]);\n\n                        double b_RHS_value = - smoothingWeight * (x0[nextIndex[i]] - x0[currIndex[i]]);\n\n                        size_t b_index = matrix.GetCurrentNumberRows() - 1;\n                        b_RHS[b_index] = b_RHS_value;\n\n                        cost += b_RHS_value * b_RHS_value;\n                    }\n                } else\n                {   // No constraints explicitly added for the last channel (it is coupled with previous one by forward difference).\n                    // Two rows: for real & imaginary parts.\n                    matrix.NewRow();\n                    matrix.NewRow();\n                }\n            }\n            ASKAPLOG_INFO_STR(logger, \"Smoothness constraints cost (weighted) = \" << cost);\n            ASKAPLOG_INFO_STR(logger, \"Smoothness constraints cost = \" << cost / (smoothingWeight * smoothingWeight));\n        }\n        size_t ncolumms = nParameters;\n\n        // Completed the matrix building.\n        matrix.Finalize(ncolumms);\n\n        // A simple approximation for the upper bound of the rank of the  A'A matrix.\n        size_t rank_approx = matrix.GetNumberNonemptyRows();\n\n        //-----------------------------------------------\n        // Adding damping.\n        //-----------------------------------------------\n        // Setting damping parameters.\n        double alpha = 0.01;\n        if (parameters().count(\"alpha\") > 0) {\n            alpha = std::atof(parameters().at(\"alpha\").c_str());\n        }\n\n        double norm = 2.0;\n        if (parameters().count(\"norm\") > 0) {\n            norm = std::atof(parameters().at(\"norm\").c_str());\n        }\n\n        ASKAPLOG_INFO_STR(logger, \"Adding model damping, with alpha = \" << alpha);\n\n        lsqr::ModelDamping damping(ncolumms);\n        damping.Add(alpha, norm, matrix, b_RHS, NULL, NULL, NULL, myrank, nbproc);\n\n        //-----------------------------------------------\n        // Calculating the total cost.\n        //-----------------------------------------------\n        double total_cost = 0.;\n        for (size_t i = 0; i < b_RHS.size(); ++i) {\n            total_cost += b_RHS[i] * b_RHS[i];\n        }\n        ASKAPLOG_INFO_STR(logger, \"Total cost = \" << total_cost);\n\n        //-----------------------------------------------\n        // Setting solver parameters.\n        //-----------------------------------------------\n        int niter = 100;\n        if (parameters().count(\"niter\") > 0) {\n            niter = std::atoi(parameters().at(\"niter\").c_str());\n        }\n\n        double rmin = 1.e-13;\n        if (parameters().count(\"rmin\") > 0) {\n            rmin = std::atof(parameters().at(\"rmin\").c_str());\n        }\n\n        bool suppress_output = true;\n        if (parameters().count(\"verbose\") > 0\n            && parameters().at(\"verbose\") == \"true\") {\n            suppress_output = false;\n        }\n\n        //-----------------------------------------------\n        // Solving the matrix system.\n        //-----------------------------------------------\n        casa::Timer timer;\n        timer.mark();\n\n        lsqr::Vector x(ncolumms, 0.0);\n        lsqr::LSQRSolver solver(matrix.GetCurrentNumberRows(), ncolumms);\n\n        solver.Solve(niter, rmin, matrix, b_RHS, x, myrank, nbproc, suppress_output);\n\n        ASKAPLOG_INFO_STR(logger, \"Completed LSQR in \" << timer.real() << \" seconds\");\n\n        //------------------------------------------------------------------------\n        // Update the parameters for the calculated changes.\n        // Exploit reference semantics of casa::Array.\n        //------------------------------------------------------------------------\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                const double adjustment = 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\n         //------------------------------------------------------------------------\n         // Set approximate solution quality.\n         quality.setDOF(nParameters);\n         quality.setRank(rank_approx);\n    }\n    else if (algorithm() == \"Chol\") {\n        // TODO: It seems this branch is never actually used. Need to remove it?\n        ASKAPLOG_INFO_STR(logger, \"Solving normal equations using the Cholesky decomposition solver\");\n\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    else {\n        ASKAPTHROW(AskapError, \"Unknown calibration solver type: \" << algorithm());\n    }\n\n    if (!algorithmLSQR) {\n        // Free up gsl storage.\n        gsl_matrix_free(A);\n        gsl_vector_free(B);\n        gsl_vector_free(X);\n    }\n\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        // 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 // No need to extract independent blocks if number of unknowns is small.\n            || algorithm() == \"LSQR\") {\n            solveSubsetOfNormalEquations(params, quality, names);\n        } else {\n            while (names.size() > 0) {\n                const std::vector<std::string> subsetNames = getIndependentSubset(names,1e-6);\n                solveSubsetOfNormalEquations(params, quality, subsetNames);\n            }\n        }\n        return true;\n    };\n\n    Solver::ShPtr LinearSolver::clone() const\n    {\n      return Solver::ShPtr(new LinearSolver(*this));\n    }\n\n    void LinearSolver::SetWorkersCommunicator(void *comm)\n    {\n        itsWorkersComm = comm;\n    }\n\n    void LinearSolver::SetMajorLoopIterationNumber(size_t it)\n    {\n        itsMajorLoopIterationNumber = it;\n    }\n\n    // NOTE: Copied from \"calibaccess/CalParamNameHelper.h\", as currently accessors depends of scimath.\n    /// @brief extract coded channel and parameter name\n    /// @details This is a reverse operation to codeInChannel. Note, no checks are done that the name passed\n    /// has coded channel present.\n    /// @param[in] name full name of the parameter\n    /// @return a pair with extracted channel and the base parameter name\n    std::pair<casa::uInt, std::string> LinearSolver::extractChannelInfo(const std::string &name)\n    {\n      size_t pos = name.rfind(\".\");\n      ASKAPCHECK(pos != std::string::npos, \"Expect dot in the parameter name passed to extractChannelInfo, name=\"<<name);\n      ASKAPCHECK(pos + 1 != name.size(), \"Parameter name=\"<<name<<\" ends with a dot\");\n      return std::pair<casa::uInt, std::string>(utility::fromString<casa::uInt>(name.substr(pos+1)),name.substr(0,pos));\n    }\n\n  }\n}\n", "meta": {"hexsha": "9a20e8dafa36ea4a9efa25c46644b14865c64803", "size": 33346, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/Base/scimath/current/fitting/LinearSolver.cc", "max_stars_repo_name": "ATNF/askapsoft", "max_stars_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Base/scimath/current/fitting/LinearSolver.cc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Base/scimath/current/fitting/LinearSolver.cc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0504413619, "max_line_length": 207, "alphanum_fraction": 0.5690637558, "num_tokens": 7665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.03789242486405945, "lm_q1q2_score": 0.018502241868615255}}
{"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_2C807EC599D5E980B2EAC9CC53BF67D6\n#define BOOST_QVM_2C807EC599D5E980B2EAC9CC53BF67D6\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_assign3.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 == 3 &&\n                                  vec_traits<B>::dim == 3,\n                              deduce_vec2<A, B, 3>>::type\n    operator+(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, 3>::type R;\n  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 3);\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  vec_traits<R>::template write_element<2>(r) =\n      vec_traits<A>::template read_element<2>(a) +\n      vec_traits<B>::template read_element<2>(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<3> { 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 == 3 &&\n                                  vec_traits<B>::dim == 3,\n                              deduce_vec2<A, B, 3>>::type\n    operator-(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, 3>::type R;\n  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 3);\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  vec_traits<R>::template write_element<2>(r) =\n      vec_traits<A>::template read_element<2>(a) -\n      vec_traits<B>::template read_element<2>(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<3> { 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 == 3 && vec_traits<B>::dim == 3,\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  vec_traits<A>::template write_element<2>(a) +=\n      vec_traits<B>::template read_element<2>(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<3> { 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 == 3 && vec_traits<B>::dim == 3,\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  vec_traits<A>::template write_element<2>(a) -=\n      vec_traits<B>::template read_element<2>(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<3> { 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 == 3 && 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  vec_traits<R>::template write_element<2>(r) =\n      vec_traits<A>::template read_element<2>(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<3> { 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 == 3,\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  vec_traits<R>::template write_element<2>(r) =\n      a * vec_traits<B>::template read_element<2>(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<3> { 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 == 3 && 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  vec_traits<A>::template write_element<2>(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<3> { 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 == 3 && 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  vec_traits<R>::template write_element<2>(r) =\n      vec_traits<A>::template read_element<2>(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<3> { 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 == 3 && 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  vec_traits<A>::template write_element<2>(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<3> { 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 == 3 &&\n                             vec_traits<A>::dim == 3,\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  vec_traits<R>::template write_element<2>(r) =\n      vec_traits<A>::template read_element<2>(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<3> { 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 == 3 && vec_traits<B>::dim == 3,\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         vec_traits<A>::template read_element<2>(a) ==\n             vec_traits<B>::template read_element<2>(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<3> { 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 == 3 && vec_traits<B>::dim == 3,\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         !(vec_traits<A>::template read_element<2>(a) ==\n           vec_traits<B>::template read_element<2>(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<3> { 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 == 3, 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  vec_traits<R>::template write_element<2>(r) =\n      -vec_traits<A>::template read_element<2>(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<3> { 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 == 3,\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 a2 = vec_traits<A>::template read_element<2>(a);\n  T const m2 = a0 * a0 + a1 * a1 + a2 * a2;\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<3> { 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 == 3,\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 a2 = vec_traits<A>::template read_element<2>(a);\n  T const m2 = a0 * a0 + a1 * a1 + a2 * a2;\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<3> { 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 == 3, 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 a2 = vec_traits<A>::template read_element<2>(a);\n  T const m2 = a0 * a0 + a1 * a1 + a2 * a2;\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  vec_traits<R>::template write_element<2>(r) = a2 * 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 == 3, 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 a2 = vec_traits<A>::template read_element<2>(a);\n  T const m2 = a0 * a0 + a1 * a1 + a2 * a2;\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  vec_traits<A>::template write_element<2>(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<3> { 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 == 3 && vec_traits<B>::dim == 3,\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  Ta const a2 = vec_traits<A>::template read_element<2>(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  Tb const b2 = vec_traits<B>::template read_element<2>(b);\n  Tr const dot = a0 * b0 + a1 * b1 + a2 * b2;\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<3> { static bool const value = true; };\n} // namespace qvm_detail\n\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "c9b43b802d6dac172f49fbb63e30aec2d0a2c6b2", "size": 15406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/gen/vec_operations3.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_operations3.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_operations3.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": 32.1628392484, "max_line_length": 79, "alphanum_fraction": 0.6714267169, "num_tokens": 4311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478692926354, "lm_q2_score": 0.038466188022541675, "lm_q1q2_score": 0.018482183742930196}}
{"text": "#ifndef SETTINGS_COMMON_HPP\n#define SETTINGS_COMMON_HPP\n\n#include <mpi.h>\n#include <boost/lexical_cast.hpp>\n#include <clstatphys/physics/toda_lax_form.hpp>\n#include <clstatphys/lattice/chain.hpp>\n\nusing Lattice = lattice::Chain;\n\nstruct SettingsCommon{\n  int num_iterations = 32; \n  int Ns = 10; // lenght of chain\n  int N_loop = 1; //loop number\n  int Ns_observe = Ns; //observed particle \n  int N_mc = 10; //numer of time step\n  int order = 0;\n  int num_particles = 10; //nummer of particles\n  int N_mpi_parallel = 2; // number of mpi parallel\n  int N_each = 10;// number of each parallel\n  int N_adj = 2;// number of adjacent spins\n  int N_total_data = 10; // number of data\n  int process_id = 1;\n  int name_length;\n  int num_threads;\n  int mpi_error = 1;\n  int mpi_error_end = 1;\n  char processor_name[MPI_MAX_PROCESSOR_NAME];\n  std::string condition_dat{\"condi.dat\"};\n  std::string result_directory{\"./\"};\n\n\n  SettingsCommon(int argc, char **argv, int & input_counter){\n    if(mpi_error > 0){\n      mpi_error = MPI_Init(&argc, &argv);\n      MPI_Comm_size(MPI_COMM_WORLD, &N_mpi_parallel);\n      MPI_Comm_rank(MPI_COMM_WORLD, &process_id);\n      MPI_Get_processor_name(processor_name, &name_length);\n    }\n    set(argc, argv, input_counter);\n  }\n  SettingsCommon() = default;\n\n  inline void set(int argc, char **argv, int & input_counter){\n    if (argc > input_counter) result_directory = boost::lexical_cast<std::string>(argv[input_counter]); ++input_counter;\n    if (argc > input_counter) Ns =               boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) Ns_observe =       boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (Ns < Ns_observe){\n      std::cerr << \"Ns_observe should be lower than Ns\" << std::endl;\n      std::exit(1);\n    }\n    if (argc > input_counter) N_mc =             boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) N_loop =           boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) num_iterations =   boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n\n    num_particles = Lattice::set_num_particles(Ns); //nummer of particles\n    Lattice lattice_t(Ns);\n    N_adj = lattice_t.number_adjacent();\n\n    N_each = N_loop / N_mpi_parallel; // number of each parallel\n    condition_dat = result_directory + condition_dat;\n\n    N_total_data = N_mc;\n  }\n\n  template <class Dataput>\n  inline void declare(Dataput & dataput){\n    dataput << \"<<Common Settings>>\" << std::endl \n            << \"  Sampling GGE of Toda lattice by Monte Carlo\" << std::endl\n            <<  \"  \" << Lattice::name() << std::endl\n\n            << \"  Number of patricles : num_particles = \" << num_particles << std::endl\n            << \"  Length of whole system : Ns = \" << Ns << std::endl\n            << \"  Length of observe system : Ns_observe = \" << Ns_observe << std::endl\n            << \"  Number of result data (time step): N_total_data = \" << N_total_data << std::endl\n            << \"  Number of monte carlo steps : N_mc = \" << N_mc << std::endl\n            << \"  Number of MPI parallelization : N_mpi_parallel =\" << N_mpi_parallel << std::endl\n            << \"  Number of loop : N_loop =\" << N_loop << std::endl\n            << \"  Each thread loop : N_each = \" << N_each << std::endl \n            << \"  Number of iteration for action variables : num_iterations = \" << num_iterations << std::endl\n            << \"  Result directory : \" << result_directory << std::endl;\n  }\n\n  integrable::TodaLaxForm toda_lax_form(){\n    Lattice lattice_t(Ns);\n    std::vector<std::vector<int> > pair_table(\n                                              num_particles,\n                                              std::vector<int>(N_adj)\n                                              );\n    lattice_t.create_table(pair_table);\n    return integrable::TodaLaxForm(num_particles,1.0,1.0,\"periodic\");\n  }\n\n  inline void finalize(){mpi_error = MPI_Finalize();};\n\n}; // end struct define\n\n#endif\n", "meta": {"hexsha": "6d9f8bd3309af1b8ded557113e4e4c31bcd80828", "size": 4040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toda-lattice-action-angle-sampling/include/common/settings_common.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toda-lattice-action-angle-sampling/include/common/settings_common.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "toda-lattice-action-angle-sampling/include/common/settings_common.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 40.8080808081, "max_line_length": 120, "alphanum_fraction": 0.6304455446, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.04535257748981284, "lm_q1q2_score": 0.018473619589771985}}
{"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 VectorValues.cpp\n * @brief Implementations for VectorValues\n * @author Richard Roberts\n * @author Alex Cunningham\n */\n\n#include <gtsam/linear/VectorValues.h>\n\n#include <boost/bind.hpp>\n#include <boost/range/combine.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/adaptor/map.hpp>\n\nusing namespace std;\n\nnamespace gtsam {\n\n  using boost::combine;\n  using boost::adaptors::transformed;\n  using boost::adaptors::map_values;\n  using boost::accumulate;\n\n  /* ************************************************************************* */\n  VectorValues::VectorValues(const VectorValues& first, const VectorValues& second)\n  {\n    // Merge using predicate for comparing first of pair\n    merge(first.begin(), first.end(), second.begin(), second.end(), inserter(values_, values_.end()),\n      boost::bind(&less<Key>::operator(), less<Key>(), boost::bind(&KeyValuePair::first, _1), boost::bind(&KeyValuePair::first, _2)));\n    if(size() != first.size() + second.size())\n      throw invalid_argument(\"Requested to merge two VectorValues that have one or more variables in common.\");\n  }\n\n  /* ************************************************************************* */\n  VectorValues::VectorValues(const Vector& x, const Dims& dims) {\n    typedef pair<Key, size_t> Pair;\n    size_t j = 0;\n    for (const Pair& v : dims) {\n      Key key;\n      size_t n;\n      boost::tie(key, n) = v;\n      values_.emplace(key, x.segment(j, n));\n      j += n;\n    }\n  }\n\n  /* ************************************************************************* */\n  VectorValues::VectorValues(const Vector& x, const Scatter& scatter) {\n    size_t j = 0;\n    for (const SlotEntry& v : scatter) {\n      values_.emplace(v.key, x.segment(j, v.dimension));\n      j += v.dimension;\n    }\n  }\n\n  /* ************************************************************************* */\n  VectorValues VectorValues::Zero(const VectorValues& other)\n  {\n    VectorValues result;\n    for(const KeyValuePair& v: other)\n      result.values_.emplace(v.first, Vector::Zero(v.second.size()));\n    return result;\n  }\n\n  /* ************************************************************************* */\n  VectorValues::iterator VectorValues::insert(const std::pair<Key, Vector>& key_value) {\n    std::pair<iterator, bool> result = values_.insert(key_value);\n    if(!result.second)\n      throw std::invalid_argument(\n      \"Requested to insert variable '\" + DefaultKeyFormatter(key_value.first)\n      + \"' already in this VectorValues.\");\n    return result.first;\n  }\n\n  /* ************************************************************************* */\n  VectorValues::iterator VectorValues::emplace(Key j, const Vector& value) {\n    std::pair<iterator, bool> result = values_.emplace(j, value);\n    if(!result.second)\n      throw std::invalid_argument(\n      \"Requested to emplace variable '\" + DefaultKeyFormatter(j)\n      + \"' already in this VectorValues.\");\n    return result.first;\n  }\n\n  /* ************************************************************************* */\n  void VectorValues::update(const VectorValues& values)\n  {\n    iterator hint = begin();\n    for(const KeyValuePair& key_value: values)\n    {\n      // Use this trick to find the value using a hint, since we are inserting from another sorted map\n      size_t oldSize = values_.size();\n      hint = values_.insert(hint, key_value);\n      if(values_.size() > oldSize) {\n        values_.unsafe_erase(hint);\n        throw out_of_range(\"Requested to update a VectorValues with another VectorValues that contains keys not present in the first.\");\n      } else {\n        hint->second = key_value.second;\n      }\n    }\n  }\n\n  /* ************************************************************************* */\n  void VectorValues::insert(const VectorValues& values)\n  {\n    size_t originalSize = size();\n    values_.insert(values.begin(), values.end());\n    if(size() != originalSize + values.size())\n      throw invalid_argument(\"Requested to insert a VectorValues into another VectorValues that already contains one or more of its keys.\");\n  }\n\n  /* ************************************************************************* */\n  void VectorValues::setZero()\n  {\n    for(Vector& v: values_ | map_values)\n      v.setZero();\n  }\n\n  /* ************************************************************************* */\n  ostream& operator<<(ostream& os, const VectorValues& v) {\n    // Change print depending on whether we are using TBB\n#ifdef GTSAM_USE_TBB\n    map<Key, Vector> sorted;\n    for (const auto& key_value : v) {\n      sorted.emplace(key_value.first, key_value.second);\n    }\n    for (const auto& key_value : sorted)\n#else\n    for (const auto& key_value : v)\n#endif\n    {\n      os << \"  \" << StreamedKey(key_value.first) << \": \" << key_value.second.transpose()\n         << \"\\n\";\n    }\n    return os;\n  }\n\n  /* ************************************************************************* */\n  void VectorValues::print(const string& str,\n                           const KeyFormatter& formatter) const {\n    cout << str << \": \" << size() << \" elements\\n\";\n    cout << key_formatter(formatter) << *this;\n    cout.flush();\n}\n\n  /* ************************************************************************* */\n  bool VectorValues::equals(const VectorValues& x, double tol) const {\n    if(this->size() != x.size())\n      return false;\n    for(const auto& values: boost::combine(*this, x)) {\n      if(values.get<0>().first != values.get<1>().first ||\n        !equal_with_abs_tol(values.get<0>().second, values.get<1>().second, tol))\n        return false;\n    }\n    return true;\n  }\n\n  /* ************************************************************************* */\n  Vector VectorValues::vector() const {\n    // Count dimensions\n    DenseIndex totalDim = 0;\n    for (const Vector& v : *this | map_values) totalDim += v.size();\n\n    // Copy vectors\n    Vector result(totalDim);\n    DenseIndex pos = 0;\n    for (const Vector& v : *this | map_values) {\n      result.segment(pos, v.size()) = v;\n      pos += v.size();\n    }\n\n    return result;\n  }\n\n  /* ************************************************************************* */\n  Vector VectorValues::vector(const Dims& keys) const\n  {\n    // Count dimensions\n    DenseIndex totalDim = 0;\n    for(size_t dim: keys | map_values)\n      totalDim += dim;\n    Vector result(totalDim);\n    size_t j = 0;\n    for(const Dims::value_type& it: keys) {\n      result.segment(j,it.second) = at(it.first);\n      j += it.second;\n    }\n    return result;\n  }\n\n  /* ************************************************************************* */\n  void VectorValues::swap(VectorValues& other) {\n    this->values_.swap(other.values_);\n  }\n\n  /* ************************************************************************* */\n  namespace internal\n  {\n    bool structureCompareOp(const boost::tuple<VectorValues::value_type,\n      VectorValues::value_type>& vv)\n    {\n      return vv.get<0>().first == vv.get<1>().first\n        && vv.get<0>().second.size() == vv.get<1>().second.size();\n    }\n  }\n\n  /* ************************************************************************* */\n  bool VectorValues::hasSameStructure(const VectorValues other) const\n  {\n    return accumulate(combine(*this, other)\n      | transformed(internal::structureCompareOp), true, logical_and<bool>());\n  }\n\n  /* ************************************************************************* */\n  double VectorValues::dot(const VectorValues& v) const\n  {\n    if(this->size() != v.size())\n      throw invalid_argument(\"VectorValues::dot called with a VectorValues of different structure\");\n    double result = 0.0;\n    typedef boost::tuple<value_type, value_type> ValuePair;\n    using boost::adaptors::map_values;\n    for(const ValuePair& values: boost::combine(*this, v)) {\n      assert_throw(values.get<0>().first == values.get<1>().first,\n        invalid_argument(\"VectorValues::dot called with a VectorValues of different structure\"));\n      assert_throw(values.get<0>().second.size() == values.get<1>().second.size(),\n        invalid_argument(\"VectorValues::dot called with a VectorValues of different structure\"));\n      result += values.get<0>().second.dot(values.get<1>().second);\n    }\n    return result;\n  }\n\n  /* ************************************************************************* */\n  double VectorValues::norm() const {\n    return std::sqrt(this->squaredNorm());\n  }\n\n  /* ************************************************************************* */\n  double VectorValues::squaredNorm() const {\n    double sumSquares = 0.0;\n    using boost::adaptors::map_values;\n    for(const Vector& v: *this | map_values)\n      sumSquares += v.squaredNorm();\n    return sumSquares;\n  }\n\n  /* ************************************************************************* */\n  VectorValues VectorValues::operator+(const VectorValues& c) const\n  {\n    if(this->size() != c.size())\n      throw invalid_argument(\"VectorValues::operator+ called with different vector sizes\");\n    assert_throw(hasSameStructure(c),\n      invalid_argument(\"VectorValues::operator+ called with different vector sizes\"));\n\n    VectorValues result;\n    // The result.end() hint here should result in constant-time inserts\n    for(const_iterator j1 = begin(), j2 = c.begin(); j1 != end(); ++j1, ++j2)\n      result.values_.emplace(j1->first, j1->second + j2->second);\n\n    return result;\n  }\n\n  /* ************************************************************************* */\n  VectorValues VectorValues::add(const VectorValues& c) const\n  {\n    return *this + c;\n  }\n\n  /* ************************************************************************* */\n  VectorValues& VectorValues::operator+=(const VectorValues& c)\n  {\n    if(this->size() != c.size())\n      throw invalid_argument(\"VectorValues::operator+= called with different vector sizes\");\n    assert_throw(hasSameStructure(c),\n      invalid_argument(\"VectorValues::operator+= called with different vector sizes\"));\n\n    iterator j1 = begin();\n    const_iterator j2 = c.begin();\n    // The result.end() hint here should result in constant-time inserts\n    for(; j1 != end(); ++j1, ++j2)\n      j1->second += j2->second;\n\n    return *this;\n  }\n\n  /* ************************************************************************* */\n  VectorValues& VectorValues::addInPlace(const VectorValues& c)\n  {\n    return *this += c;\n  }\n\n  /* ************************************************************************* */\n  VectorValues& VectorValues::addInPlace_(const VectorValues& c)\n  {\n    for(const_iterator j2 = c.begin(); j2 != c.end(); ++j2) {\n      pair<VectorValues::iterator, bool> xi = tryInsert(j2->first, Vector());\n      if(xi.second)\n        xi.first->second = j2->second;\n      else\n        xi.first->second += j2->second;\n    }\n    return *this;\n  }\n\n  /* ************************************************************************* */\n  VectorValues VectorValues::operator-(const VectorValues& c) const\n  {\n    if(this->size() != c.size())\n      throw invalid_argument(\"VectorValues::operator- called with different vector sizes\");\n    assert_throw(hasSameStructure(c),\n      invalid_argument(\"VectorValues::operator- called with different vector sizes\"));\n\n    VectorValues result;\n    // The result.end() hint here should result in constant-time inserts\n    for(const_iterator j1 = begin(), j2 = c.begin(); j1 != end(); ++j1, ++j2)\n      result.values_.emplace(j1->first, j1->second - j2->second);\n\n    return result;\n  }\n\n  /* ************************************************************************* */\n  VectorValues VectorValues::subtract(const VectorValues& c) const\n  {\n    return *this - c;\n  }\n\n  /* ************************************************************************* */\n  VectorValues operator*(const double a, const VectorValues &v)\n  {\n    VectorValues result;\n    for(const VectorValues::KeyValuePair& key_v: v)\n      result.values_.emplace(key_v.first, a * key_v.second);\n    return result;\n  }\n\n  /* ************************************************************************* */\n  VectorValues VectorValues::scale(const double a) const\n  {\n    return a * *this;\n  }\n\n  /* ************************************************************************* */\n  VectorValues& VectorValues::operator*=(double alpha)\n  {\n    for(Vector& v: *this | map_values)\n      v *= alpha;\n    return *this;\n  }\n\n  /* ************************************************************************* */\n  VectorValues& VectorValues::scaleInPlace(double alpha)\n  {\n    return *this *= alpha;\n  }\n\n  /* ************************************************************************* */\n\n} // \\namespace gtsam\n", "meta": {"hexsha": "cd3ae815b761177323bfcb9150bd9675b4c3bbd7", "size": 13054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/VectorValues.cpp", "max_stars_repo_name": "DEVESHTARASIA/gtsam", "max_stars_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T14:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T14:19:34.000Z", "max_issues_repo_path": "gtsam/linear/VectorValues.cpp", "max_issues_repo_name": "DEVESHTARASIA/gtsam", "max_issues_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam/linear/VectorValues.cpp", "max_forks_repo_name": "DEVESHTARASIA/gtsam", "max_forks_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-18T19:27:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-18T19:27:18.000Z", "avg_line_length": 35.2810810811, "max_line_length": 140, "alphanum_fraction": 0.5153975793, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.04146227315557397, "lm_q1q2_score": 0.01847266728068663}}
{"text": "#include <boost/algorithm/string.hpp>\n#include <iostream>\nusing namespace std;\n\nconst string alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst int alphabet_length = (int) alphabet.length();\n\nstring get_keyphrase(const string& text, const string& keyword)\n{\n  /* Returns the Vigenere keyword of appropriate length (in all caps) for a\n   * given text (either plaintext or ciphertext) and keyword.\n   */\n  string keyphrase = \"\";\n  string caps_keyword = boost::algorithm::to_upper_copy<string>(keyword);\n\n  size_t keyword_length = keyword.length();\n  size_t text_length = text.length();\n\n  for (int i = 0; i < text_length; i++)\n  {\n    keyphrase += caps_keyword[i % keyword_length];\n  }\n\n  return keyphrase;\n}\n\n\nstring encrypt(const string& plaintext, const string& keyword)\n{\n  /* Returns the ciphertext produced by encrypting the plaintext using the\n   * given keyword and the Vigenere Cipher\n   * (http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher).\n   */\n\n  string ciphertext = \"\";\n  string caps_plaintext = boost::algorithm::to_upper_copy<string>(plaintext);\n  string keyphrase = get_keyphrase(plaintext, keyword);\n\n  for (int i = 0; i < plaintext.length(); i++)\n  {\n    int plaintext_index = (int) alphabet.find(caps_plaintext[i]);\n    int advance_by = (int) alphabet.find(keyphrase[i]);\n    int ciphertext_index = (plaintext_index + advance_by) % alphabet_length;\n\n    ciphertext += alphabet[ciphertext_index];\n  }\n\n  return ciphertext;\n}\n\nstring decrypt(const string& ciphertext, const string& keyword)\n{\n  /* Returns the plaintext produced by decrypting the ciphertext using the\n   * given keyword and the Vigenere Cipher\n   * (http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher).\n   */\n  string plaintext = \"\";\n  string caps_ciphertext = boost::algorithm::to_upper_copy<string>(ciphertext);\n  string keyphrase = get_keyphrase(ciphertext, keyword);\n\n  for (int i = 0; i < ciphertext.length(); i++)\n  {\n    int ciphertext_index = (int) alphabet.find(caps_ciphertext[i]);\n    int reverse_by = (int) alphabet.find(keyphrase[i]);\n    int plaintext_index = (ciphertext_index - reverse_by) % alphabet_length;\n\n    cout << ciphertext_index << endl;\n    cout << reverse_by << endl;\n    cout << plaintext_index << endl;\n    cout << endl;\n\n    plaintext += alphabet[plaintext_index];\n  }\n\n  return plaintext;\n}\n", "meta": {"hexsha": "775fe5dc580bc078d680c91f7c9814db906e029c", "size": 2302, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vigenere.hpp", "max_stars_repo_name": "DasAllFolks/Vigenere", "max_stars_repo_head_hexsha": "ba9144a44bfc663b68167327cd967059feff195c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vigenere.hpp", "max_issues_repo_name": "DasAllFolks/Vigenere", "max_issues_repo_head_hexsha": "ba9144a44bfc663b68167327cd967059feff195c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vigenere.hpp", "max_forks_repo_name": "DasAllFolks/Vigenere", "max_forks_repo_head_hexsha": "ba9144a44bfc663b68167327cd967059feff195c", "max_forks_repo_licenses": ["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.8961038961, "max_line_length": 79, "alphanum_fraction": 0.7093831451, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.041462273155573964, "lm_q1q2_score": 0.01847266728068663}}
{"text": "/**\n *  This file is part of dvo.\n *\n *  Copyright 2012 Christian Kerl <christian.kerl@in.tum.de> (Technical University of Munich)\n *  For more information see <http://vision.in.tum.de/data/software/dvo>.\n *\n *  dvo 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 *  dvo 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 dvo.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <dvo/dense_tracking.h>\n\n#include <assert.h>\n#include <sophus/se3.h>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include <dvo/core/datatypes.h>\n#include <dvo/util/revertable.h>\n#include <dvo/util/stopwatch.h>\n#include <dvo/visualization/visualizer.h>\n\n#include <tbb/task_scheduler_init.h>\n#include <tbb/parallel_reduce.h>\n#include <tbb/blocked_range.h>\n\nnamespace dvo\n{\n\nusing namespace dvo::core;\nusing namespace dvo::util;\n\nstatic inline bool isfinite(const float& v)\n{\n  return std::isfinite(v);\n}\n\nconst DenseTracker::Config& DenseTracker::getDefaultConfig()\n{\n  static Config defaultConfig;\n\n  return defaultConfig;\n}\n\nstatic const Eigen::IOFormat YamlArrayFmt(Eigen::FullPrecision, Eigen::DontAlignCols, \",\", \",\", \"\", \"\", \"[\", \"]\");\n\nDenseTracker::DenseTracker(IntrinsicMatrix& intrinsics, const Config& cfg) :\n    cfg(cfg),\n    weight_calculation_(),\n    itctx_(cfg)\n{\n  intrinsics_.push_back(intrinsics);\n\n  configure();\n}\n\nvoid DenseTracker::configure()\n{\n  assert(cfg.IsSane());\n\n  IntrinsicMatrix current = intrinsics_.back();\n\n  for(size_t idx = intrinsics_.size(); idx <= cfg.FirstLevel; ++idx)\n  {\n    current.scale(0.5f);\n\n    intrinsics_.push_back(current);\n  }\n\n  if(cfg.UseWeighting)\n  {\n    weight_calculation_\n      .scaleEstimator(ScaleEstimators::get(cfg.ScaleEstimatorType))\n      .scaleEstimator()->configure(cfg.ScaleEstimatorParam);\n\n    weight_calculation_\n      .influenceFunction(InfluenceFunctions::get(cfg.InfluenceFuntionType))\n      .influenceFunction()->configure(cfg.InfluenceFunctionParam);\n  }\n  else\n  {\n    weight_calculation_\n      .scaleEstimator(ScaleEstimators::get(ScaleEstimators::Unit))\n      .influenceFunction(InfluenceFunctions::get(InfluenceFunctions::Unit));\n  }\n}\n\nconst IntrinsicMatrix& DenseTracker::intrinsics(size_t level)\n{\n  return intrinsics_.at(level);\n}\n\nvoid DenseTracker::updateLastTransform(Eigen::Affine3d& last_transformation)\n{\n  last_xi_ = Sophus::SE3(last_transformation.rotation(), last_transformation.translation());\n}\n\nvoid DenseTracker::getCovarianceEstimate(Eigen::Matrix<double, 6, 6>& covariance) const\n{\n  covariance = last_a_.cast<double>().lu().inverse();\n}\n\nbool DenseTracker::match(RgbdImagePyramid& reference, RgbdImagePyramid& current, Eigen::Affine3d& transformation)\n{\n  reference.compute(cfg.getNumLevels());\n  current.compute(cfg.getNumLevels());\n\n  bool success = true;\n\n  if(!cfg.UseInitialEstimate)\n  {\n    transformation.setIdentity();\n  }\n\n  // our first increment is the given guess\n  Sophus::SE3 inc(transformation.rotation(), transformation.translation());\n\n  Revertable<Sophus::SE3> old(last_xi_);\n  Revertable<Sophus::SE3> initial(inc);\n  Revertable<AffineTransform> estimate(AffineTransform::Identity());\n\n  bool accept = true;\n\n  static stopwatch_collection sw_level(5, \"l\", 100);\n  static stopwatch_collection sw_it(5, \"it@l\", 500);\n\n  for(itctx_.Level = cfg.FirstLevel; itctx_.Level >= cfg.LastLevel; --itctx_.Level)\n  {\n    // reset error after every pyramid level? yes because errors from different levels are not comparable\n    itctx_.Iteration = 0;\n    itctx_.Error = 1;\n\n    RgbdImage& ref = reference.level(itctx_.Level);\n    RgbdImage& cur = current.level(itctx_.Level);\n    const IntrinsicMatrix& intrinsics = intrinsics_[itctx_.Level];\n\n    NormalEquationsLeastSquares ls;\n    Vector6 x;\n\n    Vector6 last_x;\n    sw_level[itctx_.Level].start();\n    do\n    {\n      sw_it[itctx_.Level].start();\n      estimate.update() = inc.matrix().cast<NumType>() * estimate().matrix();\n\n      if(cfg.UseTemporalSmoothing())\n      {\n        old.update() = inc.inverse() * old();\n      }\n\n      if(cfg.UseEstimateSmoothing())\n      {\n        initial.update() = inc.inverse() * initial();\n      }\n\n      computeLeastSquaresEquationsInverseCompositional(ref, cur, intrinsics, estimate(), ls);\n\n      itctx_.LastError = itctx_.Error;\n      itctx_.Error = ls.error + 0.5 * cfg.Lambda * old().log().squaredNorm() + 0.5 * cfg.Mu * initial().log().squaredNorm();\n\n      // accept the last increment?\n      accept = itctx_.ErrorDiff() > 0.0;\n\n      //ROS_DEBUG_STREAM_COND(!accept, itctx_);\n\n      // if we get a worse result, we revert the increment and try our luck on the next pyramid level\n      if(!accept)\n      {\n        old.revert();\n        initial.revert();\n        estimate.revert();\n        inc = Sophus::SE3::exp(Vector6::Zero().cast<double>());\n\n        break;\n      }\n\n      // calculate new increment\n      Matrix6x6 A_diagonal = Matrix6x6::Identity();\n\n      if(cfg.UseTemporalSmoothing())\n      {\n        ls.A += cfg.Lambda * A_diagonal;\n        ls.b += cfg.Lambda * old().log().cast<NumType>();\n      }\n\n      if(cfg.UseEstimateSmoothing())\n      {\n        ls.A += cfg.Mu * A_diagonal;\n        ls.b += cfg.Mu * initial().log().cast<NumType>();\n      }\n\n      // first estimate rotation on lowest level\n      //if(itctx_.IsFirstLevel())\n      //{\n      //  Eigen::Vector3f rot = ls.A.bottomRightCorner(3, 3).ldlt().solve(ls.b.tail(3));\n      //  x.setZero();\n      //  x.tail<3>() = rot;\n      //}\n      //else\n      //{\n      //  ls.solve(x);\n      //}\n\n      ls.solve(x);\n      if(itctx_.IsLastLevel())\n      {\n        // TODO: should only be used if we also accept the solution\n        last_a_ = ls.A;\n      }\n\n      //ROS_DEBUG_STREAM_COND(accept, itctx_ << \", Increment: \" << x.format(YamlArrayFmt));\n\n      inc = Sophus::SE3::exp(x.cast<double>());\n\n      itctx_.Iteration++;\n      itctx_.NumConstraints = ls.num_constraints;\n\n      sw_it[itctx_.Level].stopAndPrint();\n    }\n    while(accept && itctx_.ErrorDiff() > cfg.Precision && !itctx_.IterationsExceeded());\n\n    sw_level[itctx_.Level].stopAndPrint();\n  }\n\n  // if last increment wasn't incorporated because of iterations exceeded, incorporate it\n  if(itctx_.IterationsExceeded())\n  {\n    estimate.update() = inc.matrix().cast<NumType>() * estimate().matrix();\n  }\n\n  // log reason for termination on last level\n  //ROS_DEBUG_STREAM_COND_NAMED(!itctx_.IterationsExceeded() && itctx_.ErrorDiff() > 0.0 && itctx_.ErrorDiff() <= cfg.Precision, \"abort\", \"error_precision\");\n  //ROS_DEBUG_STREAM_COND_NAMED(!itctx_.IterationsExceeded() && itctx_.ErrorDiff() < 0.0, \"abort\", \"error_increase\");\n  //ROS_DEBUG_STREAM_COND_NAMED(itctx_.IterationsExceeded(), \"abort\", \"iteration_exceeded\");\n\n  if(success)\n  {\n    last_xi_ = Sophus::SE3(estimate().rotation().cast<double>(), estimate().translation().cast<double>());\n  }\n\n  transformation = estimate().inverse().cast<double>();\n\n  return success;\n}\n\nvoid DenseTracker::computeLeastSquaresEquationsForwardAdditive(dvo::core::RgbdImage& ref, dvo::core::RgbdImage& cur, const dvo::core::IntrinsicMatrix& intrinsics, const dvo::core::AffineTransform& transformation, dvo::core::LeastSquaresInterface& ls)\n{\n  RgbdImage cur_warped;\n  RgbdImage::PointCloud ref_transformed;\n  cv::Mat residuals, cur_dx, cur_dy;\n\n  ref.buildPointCloud(intrinsics);\n  cur.warpIntensitySse(transformation, ref.pointcloud, intrinsics, cur_warped, ref_transformed);\n\n  // compute I_{2,x} and I_{2,y}\n  cur_warped.calculateIntensityDerivatives();\n  cur_dx = cur_warped.intensity_dx * intrinsics.fx();\n  cur_dy = cur_warped.intensity_dy * intrinsics.fy();\n\n  // compute residuals\n  residuals = cur_warped.intensity - ref.intensity;\n\n  computeLeastSquaresEquationsGeneric(residuals, cur_dx, cur_dy, ref_transformed, ls);\n}\n\nvoid DenseTracker::computeLeastSquaresEquationsForwardCompositional(dvo::core::RgbdImage& ref, dvo::core::RgbdImage& cur, const dvo::core::IntrinsicMatrix& intrinsics, const dvo::core::AffineTransform& transformation, dvo::core::LeastSquaresInterface& ls)\n{\n  RgbdImage cur_warped;\n  cv::Mat residuals, cur_dx, cur_dy;\n\n  ref.buildPointCloud(intrinsics);\n  cur.warpIntensitySse(transformation, ref.pointcloud, intrinsics, cur_warped);\n\n  // compute I_{2,x} and I_{2,y}\n  cur_warped.calculateIntensityDerivatives();\n  cur_dx = cur_warped.intensity_dx * intrinsics.fx();\n  cur_dy = cur_warped.intensity_dy * intrinsics.fy();\n\n  // compute residuals\n  residuals = cur_warped.intensity - ref.intensity;\n\n  computeLeastSquaresEquationsGeneric(residuals, cur_dx, cur_dy, ref.pointcloud, ls);\n}\n\nvoid DenseTracker::computeLeastSquaresEquationsForwardCompositionalESM(dvo::core::RgbdImage& ref, dvo::core::RgbdImage& cur, const dvo::core::IntrinsicMatrix& intrinsics, const dvo::core::AffineTransform& transformation, dvo::core::LeastSquaresInterface& ls)\n{\n  //static stopwatch_collection sw_warp(5, \"warp@l\"), sw_eqs(5, \"eqs@l\"), sw_total(5, \"total@l\");\n  //sw_total[itctx_.Level].start();\n  RgbdImage cur_warped;\n  cv::Mat residuals, dx, dy;\n\n  ref.buildPointCloud(intrinsics);\n  //sw_warp[itctx_.Level].start();\n  cur.warpIntensitySse(transformation, ref.pointcloud, intrinsics, cur_warped);\n  //sw_warp[itctx_.Level].stopAndPrint();\n\n  // compute I_{1,x} and I_{1,y}\n  ref.calculateIntensityDerivatives();\n  // compute I_{2,x} and I_{2,y}\n  cur_warped.calculateIntensityDerivatives();\n\n  dx = (ref.intensity_dx + cur_warped.intensity_dx) * 0.5f * intrinsics.fx();\n  dy = (ref.intensity_dy + cur_warped.intensity_dy) * 0.5f * intrinsics.fy();\n\n  // compute residuals\n  residuals = cur_warped.intensity - ref.intensity;\n\n  //sw_eqs[itctx_.Level].start();\n  computeLeastSquaresEquationsGeneric(residuals, dx, dy, ref.pointcloud, ls);\n  //sw_eqs[itctx_.Level].stopAndPrint();\n  //sw_total[itctx_.Level].stopAndPrint();\n}\n\nvoid DenseTracker::computeLeastSquaresEquationsInverseCompositional(dvo::core::RgbdImage& ref, dvo::core::RgbdImage& cur, const dvo::core::IntrinsicMatrix& intrinsics, const dvo::core::AffineTransform& transformation, dvo::core::LeastSquaresInterface& ls)\n{\n  RgbdImage cur_warped;\n  cv::Mat residuals, ref_dx, ref_dy;\n\n  ref.buildPointCloud(intrinsics);\n  cur.warpIntensitySse(transformation, ref.pointcloud, intrinsics, cur_warped);\n\n  // compute I_{1,x} and I_{1,y}\n  ref.calculateIntensityDerivatives();\n  ref_dx = ref.intensity_dx * intrinsics.fx();\n  ref_dy = ref.intensity_dy * intrinsics.fy();\n\n  // compute residuals\n  residuals = cur_warped.intensity - ref.intensity;\n\n  computeLeastSquaresEquationsGeneric(residuals, ref_dx, ref_dy, ref.pointcloud, ls);\n}\n\nstruct LeastSquaresEquationsReduction\n{\n  dvo::core::NormalEquationsLeastSquares* ls;\n  const cv::Mat& residuals/*, weights*/, Jix, Jiy;\n  const dvo::core::RgbdImage::PointCloud& points;\n  const dvo::core::WeightCalculation& weights;\n  LeastSquaresEquationsReduction(const cv::Mat& residuals,const dvo::core::WeightCalculation& weights, const cv::Mat& Jix, const cv::Mat& Jiy, const dvo::core::RgbdImage::PointCloud& points) :\n    ls(new dvo::core::NormalEquationsLeastSquares()),\n    residuals(residuals),\n    weights(weights),\n    Jix(Jix),\n    Jiy(Jiy),\n    points(points)\n  {\n    ls->initialize(1);\n  }\n\n  LeastSquaresEquationsReduction(LeastSquaresEquationsReduction& other, tbb::split) :\n    ls(new dvo::core::NormalEquationsLeastSquares()),\n    residuals(other.residuals),\n    weights(other.weights),\n    Jix(other.Jix),\n    Jiy(other.Jiy),\n    points(other.points)\n  {\n    ls->initialize(1);\n  }\n\n  ~LeastSquaresEquationsReduction()\n  {\n    delete ls;\n  }\n\n  void operator()(const tbb::blocked_range<size_t>& r)\n  {\n    const float *jix_ptr = Jix.ptr<float>() + r.begin(), *jiy_ptr = Jiy.ptr<float>() + r.begin(), *residual_ptr = residuals.ptr<float>() + r.begin();//, *weights_ptr = weights.ptr<float>() + r.begin();\n    Matrix1x2 Ji;\n    Matrix2x6 Jw;\n\n    dvo::core::NormalEquationsLeastSquares* tmp = ls;//new dvo::core::NormalEquationsLeastSquares();\n\n    for (size_t idx = r.begin(); idx != r.end(); ++idx, ++jix_ptr, ++jiy_ptr, ++residual_ptr)//, ++weights_ptr)\n    {\n      if(!isfinite(*jix_ptr) || !isfinite(*jiy_ptr) || !isfinite(*residual_ptr)) continue;\n\n      Ji << *jix_ptr, *jiy_ptr;\n\n      const Vector4& p3d = points.col(idx).cast<NumType>();\n      DenseTracker::computeJacobianOfProjectionAndTransformation(p3d, Jw);\n\n      tmp->update(Ji * Jw, *residual_ptr, weights.calculateWeight(*residual_ptr));\n    }\n\n    ls = tmp;\n  }\n\n  void join(LeastSquaresEquationsReduction& other)\n  {\n    ls->combine(*other.ls);\n  }\n};\n\ninline void DenseTracker::computeLeastSquaresEquationsGeneric(const cv::Mat& residuals, const cv::Mat& Jix, const cv::Mat& Jiy, const dvo::core::RgbdImage::PointCloud& points, dvo::core::LeastSquaresInterface& ls)\n{\n  //static stopwatch_collection sw_weights(5, \"weights@l\"), sw_reduce(5, \"reduce@l\");\n\n  cv::Mat weights;\n\n  // compute weights\n  //sw_weights[itctx_.Level].start();\n  computeWeights(residuals, weights);\n  //sw_weights[itctx_.Level].stopAndPrint();\n  LeastSquaresEquationsReduction body(residuals, weight_calculation_, Jix, Jiy, points);\n\n  //sw_reduce[itctx_.Level].start();\n  tbb::parallel_reduce(tbb::blocked_range<size_t>(0, residuals.size().area()), body);\n  //sw_reduce[itctx_.Level].stopAndPrint();\n\n  NormalEquationsLeastSquares& xls = (NormalEquationsLeastSquares&)ls;\n  xls = *body.ls;\n  xls.finish();\n}\n\ninline void DenseTracker::computeWeights(const cv::Mat& residuals, cv::Mat& weights)\n{\n  if(itctx_.IsFirstLevel() || itctx_.IsFirstIterationOnLevel())\n  {\n    weight_calculation_.calculateScale(residuals);\n  }\n}\n\n// jacobian computation\ninline void DenseTracker::computeJacobianOfProjectionAndTransformation(const Vector4& p, Matrix2x6& j)\n{\n  NumType z = 1.0f / p(2);\n  NumType z_sqr = 1.0f / (p(2) * p(2));\n\n  j(0, 0) =  z;\n  j(0, 1) =  0.0f;\n  j(0, 2) = -p(0) * z_sqr;\n  j(0, 3) = j(0, 2) * p(1);//j(0, 3) = -p(0) * p(1) * z_sqr;\n  j(0, 4) = 1.0f - j(0, 2) * p(0);//j(0, 4) =  (1.0 + p(0) * p(0) * z_sqr);\n  j(0, 5) = -p(1) * z;\n\n  j(1, 0) =  0.0f;\n  j(1, 1) =  z;\n  j(1, 2) = -p(1) * z_sqr;\n  j(1, 3) = -1.0f + j(1, 2) * p(1); //j(1, 3) = -(1.0 + p(1) * p(1) * z_sqr);\n  j(1, 4) = -j(0, 3); //j(1, 4) =  p(0) * p(1) * z_sqr;\n  j(1, 5) =  p(0) * z;\n}\n\nvoid DenseTracker::compute3rdRowOfJacobianOfTransformation(Vector4& p, Vector6& j)\n{\n  j(0) = 0.0;\n  j(1) = 0.0;\n  j(2) = 1.0;\n  j(3) = p(1);\n  j(4) = -p(0);\n  j(5) = 0.0;\n}\n\n} /* namespace dvo */\n", "meta": {"hexsha": "730c15f860fde349fef75e698fc7de313f8b8802", "size": 14768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dvo_core/src/dense_tracking.cpp", "max_stars_repo_name": "jesusbriales/dvo", "max_stars_repo_head_hexsha": "bd21a70ce76d882a354de7b89d2429f974b8814c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 124.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T20:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:39:17.000Z", "max_issues_repo_path": "dvo_core/src/dense_tracking.cpp", "max_issues_repo_name": "jesusbriales/dvo", "max_issues_repo_head_hexsha": "bd21a70ce76d882a354de7b89d2429f974b8814c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T12:30:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-12T15:11:50.000Z", "max_forks_repo_path": "dvo_core/src/dense_tracking.cpp", "max_forks_repo_name": "jesusbriales/dvo", "max_forks_repo_head_hexsha": "bd21a70ce76d882a354de7b89d2429f974b8814c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 78.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T14:12:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T14:33:14.000Z", "avg_line_length": 31.5555555556, "max_line_length": 258, "alphanum_fraction": 0.6880417118, "num_tokens": 4305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.03904829454344467, "lm_q1q2_score": 0.018457483620894104}}
{"text": "/*\n  Tencent is pleased to support the open source community by making\n  Plato available.\n  Copyright (C) 2019 THL A29 Limited, a Tencent company.\n  All rights reserved.\n\n  Licensed under the BSD 3-Clause License (the \"License\"); you may\n  not use this file except in compliance with the License. You may\n  obtain a copy of the License at\n\n  https://opensource.org/licenses/BSD-3-Clause\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" basis,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n  implied. See the License for the specific language governing\n  permissions and limitations under the License.\n\n  See the AUTHORS file for names of contributors.\n*/\n\n#ifndef __PLATO_ALGO_FAST_UNFOLDING_LOUVAIN_DENSITY_HPP__\n#define __PLATO_ALGO_FAST_UNFOLDING_LOUVAIN_DENSITY_HPP__\n\n#include <cstdint>\n#include <cstdlib>\n#include <unordered_map>\n#include <algorithm>\n#include <utility>\n#include <vector>\n#include <cmath>\n#include <unordered_set>\n#include <boost/format.hpp>\n#include <boost/lockfree/queue.hpp>\n\n#include \"glog/logging.h\"\n\n#include \"plato/util/perf.hpp\"\n#include \"plato/util/atomic.hpp\"\n#include \"plato/graph/graph.hpp\"\n#include \"plato/engine/dualmode.hpp\"\n#include \"plato/algo/fast_unfolding/louvain.hpp\"\n\nnamespace plato { namespace algo {\n\ntemplate<typename GRAPH>\nclass louvain_density_epoch_t {\npublic:\n  using partition_t = typename GRAPH::partition_t;\n  using edge_value_t = typename GRAPH::edata_t;\n  using louvain_value_t = plato::dense_state_t<edge_value_t, partition_t>;\n  using adj_unit_list_spec_t = typename GRAPH::adj_unit_list_spec_t;\n  struct epoch_msg_type_t {\n    vid_t v_i;\n    vid_t from;\n    vid_t to;\n    edge_value_t ki;\n    edge_value_t ki_in_from;\n    edge_value_t ki_in_to;\n    uint32_t in_from_edges;\n    uint32_t in_to_edges;\n  };\n\n  struct sync_val_msg_type_t{\n    vid_t v_i;\n    edge_value_t val;\n    uint32_t edges;\n    edge_value_t in_sum;\n  };\n\n\npublic:\n  /**\n   * @brief\n   * @param graph\n   * @param graph_info\n   * @param m\n   * @param opts\n   */\n  explicit louvain_density_epoch_t(\n    std::shared_ptr<GRAPH> graph, const graph_info_t& graph_info, double m,\n    const louvain_opts_t& opts = louvain_opts_t());\n\n  /**\n   * @brief\n   */\n  ~louvain_density_epoch_t();\n\n  /**\n   * @brief\n   */\n  void compute();\n\n  /**\n   * @brief getter\n   * @return\n   */\n  std::shared_ptr<GRAPH> graph() { return graph_; };\n\n  /**\n   * @brief getter\n   * @return\n   */\n  std::vector<vid_t>& labels() { return labels_; };\n\nprivate:\n  std::shared_ptr<GRAPH> graph_;\n  graph_info_t graph_info_;\n  louvain_value_t ki_;\n  std::vector<vid_t> labels_;\n  std::vector<edge_value_t> sigma_tot_;\n  bitmap_t<> local_bit_;\n  double m_;\n  std::vector<edge_value_t> sigma_in_;\n  std::vector<uint32_t>  c_vertices_;\n  std::vector<uint32_t>  c_edges_;\n  louvain_opts_t opts_;\n};\n\ntemplate <typename GRAPH>\nlouvain_density_epoch_t<GRAPH>::louvain_density_epoch_t(\n  std::shared_ptr<GRAPH> graph,\n  const graph_info_t& graph_info, double m, const louvain_opts_t& opts) :\n  graph_(graph), graph_info_(graph_info), ki_(graph_info.max_v_i_, graph->partitioner()),\n  labels_(graph_info.max_v_i_ + 1), sigma_tot_(graph_info.max_v_i_ + 1, 0),\n  local_bit_(graph_info.max_v_i_ + 1), m_(2 * m), sigma_in_(graph_info.max_v_i_ + 1, 0),\n  c_vertices_(graph_info.max_v_i_ + 1, 1),c_edges_(graph_info.max_v_i_ + 1, 0),opts_(opts) {\n\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  plato::stop_watch_t watch;\n\n  {// init labels\n    watch.mark(\"t0\");\n#pragma omp parallel for num_threads(cluster_info.threads_)\n    for (vid_t v_i = 0; v_i <= graph_info.max_v_i_; ++v_i) {\n      labels_[v_i] = v_i;\n    }\n    LOG(INFO) << \"epoch init labels: \" << watch.show(\"t0\") / 1000.0;\n  }\n\n  {//calc ki_ and sync sigma_tot_\n    int cnt =0;\n    bitmap_t<> active_all(graph_info.max_v_i_ + 1);\n    active_all.fill();\n    auto active_view_all = plato::create_active_v_view(graph->partitioner()->self_v_view(), active_all);\n    watch.mark(\"t0\");\n    edge_value_t max_ki = 0;\n    using push_context_t = plato::template mepa_bc_context_t<sync_val_msg_type_t>;\n    plato::broadcast_message<sync_val_msg_type_t, vid_t>(\n      active_view_all,\n      [&](const push_context_t& context, vid_t v_i) {\n        edge_value_t local_sum = 0;\n        edge_value_t self_sum =0;\n        uint32_t self_num =0;\n        auto neighbours = graph->neighbours(v_i);\n        for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n          local_sum += it->edata_;\n          if(it->neighbour_ == v_i) {\n            self_num++;\n            self_sum += it->edata_;\n          }\n        }\n        if (neighbours.begin_ != neighbours.end_) {\n          ki_[v_i] = local_sum;\n          local_bit_.set_bit(v_i);\n          plato::write_max(&max_ki, local_sum);\n          context.send(sync_val_msg_type_t{ v_i, local_sum, self_num, self_sum});\n        }\n      },\n      [&](int p_i, sync_val_msg_type_t& msg) {\n        sigma_tot_[msg.v_i] = msg.val;\n        sigma_in_[msg.v_i]  = msg.in_sum;\n        c_edges_[msg.v_i]   = msg.edges;\n        return 0;\n      }\n    );\n    LOG(INFO) << \"epoch sync sigma_tot\" << watch.show(\"t0\") / 1000.0;\n    MPI_Allreduce(MPI_IN_PLACE, &max_ki, 1, get_mpi_data_type<edge_value_t>(), MPI_MAX, MPI_COMM_WORLD);\n    LOG(INFO) << \"max-ki is: \" << max_ki;\n  }\n}\n\ntemplate <typename GRAPH>\nlouvain_density_epoch_t<GRAPH>::~louvain_density_epoch_t() {\n}\n\ntemplate <typename GRAPH>\nvoid louvain_density_epoch_t<GRAPH>::compute() {\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  uint32_t graph_vertices= graph_info_.vertices_;\n  double p_all = 1.0;\n  if(graph_vertices > 1) { p_all = graph_info_.edges_*2.0 / ((graph_vertices - 1) * graph_vertices); }\n\n  auto try_change =\n    [&](vid_t v_i, vid_t from, vid_t to, edge_value_t ki_in_from, edge_value_t ki_in_to, int32_t in_from_edges,  int32_t in_to_edges) {\n      //p = 2mc / nc(nc -1) - M*2 / N(N - 1)\n      //Q = [p*in/2m + p^2 * tot^2 / 4m^2 ]\n\n      double p_from = 1.0 - p_all, p_to = 1.0 - p_all, p_from_change = 1.0 - p_all, p_to_change = 1.0 - p_all;\n      if(c_vertices_[from] > 1) {\n        p_from = c_edges_[from]*2.0 / (c_vertices_[from] * (c_vertices_[from] - 1)) - p_all;\n        if(c_vertices_[from] > 2) { p_from_change= (c_edges_[from] - in_from_edges) * 2.0 / ((c_vertices_[from] - 1) * (c_vertices_[from] - 2)) - p_all;}\n      }\n      if(c_vertices_[to] > 1) {\n        p_to = c_edges_[to] * 2.0 / (c_vertices_[to] * (c_vertices_[to] - 1)) - p_all;\n      }\n      p_to_change = (c_edges_[to] + in_to_edges) * 2.0 / (c_vertices_[to] * (c_vertices_[to] + 1)) - p_all;\n\n      double x1 = (p_from_change - p_from) * sigma_in_[from] - p_from_change * ki_in_from + (p_to_change - p_to) * sigma_in_[to] + p_to_change * ki_in_to;\n\n      p_from_change *= p_from_change;\n      p_from *= p_from;\n      p_to_change  *= p_to_change;\n      p_to *= p_to;\n\n      double x2 = p_from_change * (sigma_tot_[from] * sigma_tot_[from] - 2 * ki_[v_i] * sigma_tot_[from] + ki_[v_i] * ki_[v_i]) - p_from * sigma_tot_[from] * sigma_tot_[from];\n      x2 += p_to_change * (sigma_tot_[to] * sigma_tot_[to] + 2 * ki_[v_i] * sigma_tot_[to] + ki_[v_i] * ki_[v_i]) - p_to * sigma_tot_[to] * sigma_tot_[to];\n      return x1 - x2 / m_ ;\n    };\n\n  auto do_change =\n    [&](epoch_msg_type_t& msg) {\n      labels_[msg.v_i] = msg.to;\n      plato::write_add(&sigma_tot_[msg.from], -msg.ki);\n      plato::write_add(&sigma_tot_[msg.to], msg.ki);\n\n      plato::write_add(&sigma_in_[msg.from], -msg.ki_in_from);\n      plato::write_add(&sigma_in_[msg.to], msg.ki_in_to);\n      plato::write_add(&c_vertices_[msg.from], (uint32_t)-1);\n      plato::write_add(&c_vertices_[msg.to], (uint32_t)1);\n      plato::write_add(&c_edges_[msg.from],-msg.in_from_edges);\n      plato::write_add(&c_edges_[msg.to],msg.in_to_edges);\n    };\n\n  auto active_view = plato::create_active_v_view(graph_->partitioner()->self_v_view(), local_bit_);\n  plato::stop_watch_t watch;\n  using push_context_t = plato::template mepa_bc_context_t<epoch_msg_type_t>;\n  for (int try_time = 0; try_time < opts_.inner_iteration_; ++try_time){\n    watch.mark(\"t0\");\n    auto exec_once =\n      [&](std::function<bool(vid_t, vid_t)> condition) {\n        plato::broadcast_message<epoch_msg_type_t, vid_t>(\n          active_view,\n          [&](const push_context_t& context, plato::vid_t v_i) {\n            vid_t target = (vid_t)-1;\n            vid_t from = labels_[v_i];\n            edge_value_t ki_in_from = 0;\n            std::unordered_map<vid_t, edge_value_t> ki_in_map;\n            std::unordered_map<vid_t, uint32_t>  ki_in_edges;\n            auto neighbours = graph_->neighbours(v_i);\n            edge_value_t self_cycle = 0;\n            uint32_t self_cycle_edges = 0;\n            for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n              vid_t to = labels_[it->neighbour_];\n              if (condition(from, to)) {\n                ki_in_map[to] += it->edata_;\n                ki_in_edges[to]++;\n              } else if (to == from) {\n                ki_in_from += it->edata_;\n                ki_in_edges[from]++;\n              }\n              if (it->neighbour_ == v_i) {\n                self_cycle_edges++;\n                self_cycle = it->edata_;\n              }\n            }\n            edge_value_t cur_kto,cur_kfrom;\n            double best_delta = 0;\n            for (auto& it: ki_in_map) {\n              double delta = try_change(v_i, from, it.first, ki_in_from, it.second + self_cycle, ki_in_edges[from], ki_in_edges[it.first] + self_cycle_edges);\n              if (delta > best_delta) {\n                target = it.first;\n                best_delta = delta;\n                cur_kfrom = ki_in_from;\n                cur_kto   = it.second + self_cycle;\n              }\n            }\n\n            if (target != (vid_t)-1) {\n\n              epoch_msg_type_t msg = epoch_msg_type_t{ v_i, from, target, ki_[v_i],cur_kfrom,cur_kto,ki_in_edges[from],ki_in_edges[target] + self_cycle_edges};\n              context.send(msg);\n              do_change(msg);\n            }\n          },\n          [&](int p_i, epoch_msg_type_t& msg) {\n            if (p_i != cluster_info.partition_id_) {\n              do_change(msg);\n            }\n            return 0;\n          }\n        );\n      };\n\n    exec_once(\n      [&](vid_t from, vid_t to){\n      if (from < to) return true;\n      return false;\n    });\n    exec_once(\n      [&](vid_t from, vid_t to){\n      if (from > to) return true;\n      return false;\n    });\n    LOG(INFO) << \"try_time: \"  << try_time << \" cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n}\n\ntemplate<typename GRAPH>\nclass louvain_density_fast_unfolding_t {\npublic:\n  using partition_t = typename GRAPH::partition_t;\n  using edge_value_t = typename GRAPH::edata_t;\n  using adj_unit_list_spec_t = plato::adj_unit_list_t<edge_value_t>;\n  using louvain_value_t = plato::dense_state_t<vid_t, partition_t>;\n\n  struct edge_sync_msg_type_t {\n    vid_t src;\n    vid_t dst;\n    edge_value_t data;\n  };\n\n  struct degree_sync_msg_type_t {\n    vid_t src;\n    vid_t degree;\n  };\n\npublic:\n  /**\n   * @brief\n   * @param graph\n   * @param graph_info\n   * @param opts\n   */\n  explicit louvain_density_fast_unfolding_t(\n    std::shared_ptr<GRAPH> graph, const graph_info_t& graph_info,\n    const louvain_opts_t& opts = louvain_opts_t());\n\n  ~louvain_density_fast_unfolding_t();\n\n  /**\n   * @brief\n   */\n  void compute();\n\n  /**\n   * @brief\n   * @tparam Callback\n   * @param callback\n   */\n  template <typename Callback>\n  void save(Callback&& callback);\n\nprivate:\n  /**\n   * @brief\n   * @param graph\n   * @param labels\n   * @return\n   */\n  std::shared_ptr<GRAPH> rebuild(std::shared_ptr<GRAPH> graph, std::vector<vid_t>& labels);\n\n  /**\n   * @brief\n   * @param labels\n   */\n  void update_local_label(std::vector<vid_t>& labels);\nprivate:\n  std::shared_ptr<GRAPH> graph_;\n  graph_info_t graph_info_;\n  graph_info_t cur_graph_info_;\n  louvain_value_t local_label_;\n  louvain_value_t local_comm_size_;\n  louvain_opts_t opts_;\n};\n\ntemplate<typename GRAPH>\nlouvain_density_fast_unfolding_t<GRAPH>::louvain_density_fast_unfolding_t(\n  std::shared_ptr<GRAPH> graph, const graph_info_t& graph_info,\n  const louvain_opts_t& opts)\n  : graph_(graph), graph_info_(graph_info), cur_graph_info_(graph_info),\n    local_label_(graph_info.max_v_i_, graph->partitioner()),\n    local_comm_size_(graph_info.max_v_i_, graph->partitioner()), opts_(opts) {\n}\n\ntemplate<typename GRAPH>\nlouvain_density_fast_unfolding_t<GRAPH>::~louvain_density_fast_unfolding_t() {\n}\n\ntemplate<typename GRAPH>\nvoid louvain_density_fast_unfolding_t<GRAPH>::compute() {\n  //first calc m and init label\n  plato::stop_watch_t watch;\n  watch.mark(\"t0\");\n  double m = local_label_.template foreach<double> (\n    [&](vid_t v_i, vid_t* pval) {\n      *pval = v_i;\n      double local_sum = 0;\n      auto neighbours = graph_->neighbours(v_i);\n      for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n        local_sum += it->edata_;\n      }\n      return local_sum;\n    }\n  );\n  m /= 2; //undirected\n  LOG(INFO) << \"calc m: \" << m << \" cost: \" << watch.show(\"t0\") / 1000.0;\n\n  //epoch\n  louvain_density_epoch_t<GRAPH>* cur = new louvain_density_epoch_t<GRAPH>(graph_, cur_graph_info_, m, opts_);\n  for (int epoch = 0; epoch < opts_.outer_iteration_; epoch++) {\n    LOG(INFO) << \"epoch \" << epoch << \" begin!\";\n    watch.mark(\"compute\");\n    cur->compute();\n    LOG(INFO) << \"compute cost: \" << watch.show(\"compute\") / 1000.0;\n    update_local_label(cur->labels());\n    if (epoch == opts_.outer_iteration_ - 1) {\n      delete cur;\n      break;\n    }\n    //rebuild from current graph\n    watch.mark(\"rebuild\");\n    graph_info_t graph_info_next(cur_graph_info_);\n    graph_info_next.is_directed_ = true;\n    auto graph_next = rebuild(cur->graph(), cur->labels());\n    louvain_density_epoch_t<GRAPH>* nxt = new louvain_density_epoch_t<GRAPH>(graph_next, graph_info_next, m, opts_);\n    LOG(INFO) << \"rebuild cost: \" << watch.show(\"rebuild\") / 1000.0;\n    delete cur;\n    cur = nxt;\n  }\n}\n\ntemplate<typename GRAPH>\nstd::shared_ptr<GRAPH> louvain_density_fast_unfolding_t<GRAPH>::rebuild(std::shared_ptr<GRAPH> graph, std::vector<vid_t>& labels) {\n  plato::stop_watch_t watch;\n  watch.mark(\"t0\");\n  eid_t total_edge = local_label_.template foreach<eid_t> (\n    [&](vid_t v_i, vid_t* pval) {\n      auto neighbours = graph->neighbours(v_i);\n      return (eid_t)(neighbours.end_ - neighbours.begin_);\n    }\n  );\n  LOG(INFO) << \"rebuild before total edge: \" << total_edge << \" cost: \" << watch.show(\"t0\") / 1000.0;\n\n  watch.mark(\"t0\");\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  vid_t v_begin = graph->partitioner()->offset_[cluster_info.partition_id_];\n  vid_t v_end = graph->partitioner()->offset_[cluster_info.partition_id_ + 1];\n  std::vector<eid_t> edge_idx(v_end - v_begin + 1, 0);\n  std::vector<eid_t> tmp_idx(v_end - v_begin + 1, 0);\n\n  bitmap_t<> active_all(graph_info_.max_v_i_ + 1);\n  active_all.fill();\n  auto active_view_all = plato::create_active_v_view(graph->partitioner()->self_v_view(), active_all);\n\n  {\n    //first, calc degree\n    using push_context_t = plato::template mepa_sd_context_t<degree_sync_msg_type_t>;\n    plato::spread_message<degree_sync_msg_type_t, vid_t>(\n      active_view_all,\n      [&](const push_context_t& context, vid_t v_i) {\n        auto neighbours = graph->neighbours(v_i);\n        if (neighbours.begin_ == neighbours.end_) return;\n        vid_t src = labels[v_i];\n        auto send_to = graph->partitioner()->get_partition_id(src);\n        context.send(send_to, degree_sync_msg_type_t { src, (vid_t)(neighbours.end_ - neighbours.begin_) } );\n      },\n      [&](degree_sync_msg_type_t& msg) {\n        vid_t pos = msg.src - v_begin + 1;\n        plato::write_add(&edge_idx[pos], (eid_t)msg.degree);\n        return 0;\n      }\n    );\n\n    for (int i = 1; i < (int)edge_idx.size(); ++i) {\n      edge_idx[i] = edge_idx[i - 1] + edge_idx[i];\n      tmp_idx[i] = edge_idx[i];\n    }\n\n    LOG(INFO) << \"rebuild calc degree cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n  eid_t total_local_edge = edge_idx[edge_idx.size() - 1];\n  std::vector<std::pair<vid_t, edge_value_t> > edges(total_local_edge);\n  LOG(INFO) << \"rebuild local edge: \" << edges.size();\n  watch.mark(\"t0\");\n  {\n    //second, transfer edge\n    using push_context_t = plato::template mepa_sd_context_t<edge_sync_msg_type_t>;\n    plato::spread_message<edge_sync_msg_type_t, vid_t>(\n      active_view_all,\n      [&](const push_context_t& context, vid_t v_i) {\n        auto neighbours = graph->neighbours(v_i);\n        if (neighbours.begin_ == neighbours.end_) return;\n        vid_t src = labels[v_i];\n        auto send_to = graph->partitioner()->get_partition_id(src);\n        for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n          vid_t dst = labels[it->neighbour_];\n          context.send(send_to, edge_sync_msg_type_t{ src, dst, it->edata_ });\n        }\n      },\n      [&](edge_sync_msg_type_t& msg) {\n        vid_t pos = msg.src - v_begin;\n        vid_t idx = __sync_fetch_and_add(&tmp_idx[pos], (eid_t)1);\n        edges[idx].first = msg.dst;\n        edges[idx].second = msg.data;\n        return 0;\n      }\n    );\n    LOG(INFO) << \"rebuild transfer edge cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n\n  watch.mark(\"t0\");\n  bitmap_t<> v_bitmap(std::numeric_limits<vid_t>::max());\n  edge_cache_t<edge_value_t> edge_cache;\n  {\n    //third, sort and aggregate\n#pragma omp parallel for num_threads(cluster_info.threads_)\n    for (vid_t v_i = v_begin; v_i < v_end; ++v_i) {\n      vid_t pos = v_i - v_begin;\n      eid_t e_start = edge_idx[pos];\n      eid_t e_end = edge_idx[pos + 1];\n      if (e_start == e_end) continue;\n      std::sort(edges.begin() + e_start, edges.begin() + e_end);\n      vid_t pre = (vid_t)-1;\n      edge_value_t local_sum = 0;\n      for (eid_t e = e_start; e < e_end; ++e) {\n        if (pre != edges[e].first) {\n          if (pre != (vid_t)-1) {\n            v_bitmap.set_bit(v_i);v_bitmap.set_bit(pre);\n            edge_cache.push_back(edge_unit_t<edge_value_t> { v_i, pre, local_sum });\n          }\n          pre = edges[e].first;\n          local_sum = 0;\n        }\n        local_sum += edges[e].second;\n      }\n      if (pre != (vid_t)-1) {\n        v_bitmap.set_bit(v_i);v_bitmap.set_bit(pre);\n        edge_cache.push_back(edge_unit_t<edge_value_t> { v_i, pre, local_sum });\n      }\n    }\n\n    eid_t edge_num_new = edge_cache.size();\n    MPI_Allreduce(MPI_IN_PLACE, &edge_num_new, 1, get_mpi_data_type<eid_t>(), MPI_SUM, MPI_COMM_WORLD);\n    LOG(INFO) << \"rebuild new edge num: \" << edge_num_new;\n    cur_graph_info_.edges_ = edge_num_new;\n    LOG(INFO) << \"rebuild aggregate edge cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n\n  watch.mark(\"t0\");\n  graph_info_t graph_info_next(graph_info_);\n  graph_info_next.is_directed_ = true;\n  std::shared_ptr<GRAPH> pgraph(new GRAPH(graph->partitioner()));\n  pgraph->load_from_cache(graph_info_next, edge_cache);\n  LOG(INFO) << \"rebuild load cache cost is: \" << watch.show(\"t0\") / 1000.0;\n\n  cur_graph_info_.vertices_ = v_bitmap.count();\n  return pgraph;\n}\n\ntemplate<typename GRAPH>\nvoid louvain_density_fast_unfolding_t<GRAPH>::update_local_label(std::vector<vid_t>& labels) {\n  local_label_.template foreach<int> (\n    [&] (vid_t v_i, vid_t* pval) {\n      if (labels[*pval] != *pval) {\n        *pval = labels[*pval];\n      }\n      return 0;\n    }\n  );\n}\n\ntemplate<typename GRAPH>\ntemplate<typename Callback>\nvoid louvain_density_fast_unfolding_t<GRAPH>::save(Callback&& callback) {\n  // traverse\n  local_label_.template foreach<int> (\n    [&] (vid_t v_i, vid_t* pval) {\n      callback(v_i, *pval);\n      return 0;\n    }\n  );\n}\n\n}  // namespace plato\n}  // namespace algo\n#endif\n", "meta": {"hexsha": "516b9b04f91297594c5a0cc06fdf135c552f34bd", "size": 19720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "plato/algo/fast_unfolding/louvain_density.hpp", "max_stars_repo_name": "ustcyu/plato", "max_stars_repo_head_hexsha": "e4b3ae644f74acb4b57e3150b6f3b50546dce9da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1845.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T10:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:33:53.000Z", "max_issues_repo_path": "plato/algo/fast_unfolding/louvain_density.hpp", "max_issues_repo_name": "ustcyu/plato", "max_issues_repo_head_hexsha": "e4b3ae644f74acb4b57e3150b6f3b50546dce9da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 142.0, "max_issues_repo_issues_event_min_datetime": "2019-11-14T16:10:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:57:48.000Z", "max_forks_repo_path": "plato/algo/fast_unfolding/louvain_density.hpp", "max_forks_repo_name": "ustcyu/plato", "max_forks_repo_head_hexsha": "e4b3ae644f74acb4b57e3150b6f3b50546dce9da", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 314.0, "max_forks_repo_forks_event_min_datetime": "2019-11-13T12:06:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:52:52.000Z", "avg_line_length": 33.537414966, "max_line_length": 175, "alphanum_fraction": 0.6432048682, "num_tokens": 5657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.03963883612289993, "lm_q1q2_score": 0.01842815778870254}}
{"text": "// SPDX-License-Identifier: NASA-1.3\n/*******************************************************************************\n *\n * Implementation of bignums based on GMP, the Gnu Multiple Precision Arithmetic\n * Library (http://gmplib.org).\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n *\n * Contributors: Jorge A. Navas (jorge.navas@sri.com)\n *\n * Notices:\n *\n * Copyright (c) 2011-2014 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 <climits>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <boost/functional/hash.hpp>\n#include <utility>\n\n#include <gmpxx.h>\n\n#include \"debug.hpp\"\n\nnamespace crab {\n\n// GMP can convert directly from/to signed/unsigned long and\n// signed/unsigned int. However, the C++11 standard only guarantees:\n//\n//  - unsigned/signed int  >= 16 bits.\n//  - unsigned/signed long >= 32 bits.\n//\n\n// TODO/FIXME:\n//\n// We don't have a conversion from GMP numbers to 64-bit integers,\n// because GMP cannot convert directly from/to int64_t or\n// uint64_t. For that, we need to use mpz_export and mpz_import but\n// they are significantly more expensive.\n//\n// Note that the actual size of **long** integer varies depending on\n// the architecture and OS (see e.g.,\n// https://en.cppreference.com/w/cpp/language/types). For instance,\n// both Linux and mac OS on an Intel 64, the size of long integers is\n// 8 bytes. But for Windows on Intel 64, the size is 4 bytes.\n\nclass z_number final {\n  private:\n    mpz_class _n{0};\n\n  public:\n    z_number() = default;\n    explicit z_number(mpz_class n) : _n(std::move(n)) {}\n\n    z_number(signed long long int n) : _n((signed long int)n) {\n        if (n > LONG_MAX) {\n            CRAB_ERROR(n, \" cannot fit into a signed long int: use another mpz_class constructor\");\n        }\n    }\n\n    explicit z_number(const std::string& s) {\n        try {\n            _n = s;\n        } catch (std::invalid_argument& e) {\n            CRAB_ERROR(\"z_number: invalid string in constructor\", s);\n        }\n    }\n\n    // overloaded typecast operators\n    explicit operator long() const {\n        if (_n.fits_slong_p()) {\n            return _n.get_si();\n        } else {\n            CRAB_ERROR(\"mpz_class \", _n.get_str(), \" does not fit into a signed long integer\");\n        }\n    }\n\n    explicit operator int() const {\n        if (_n.fits_sint_p()) {\n            // get_si returns a signed long so we cast it to int\n            return (int)_n.get_si();\n        } else {\n            CRAB_ERROR(\"mpz_class \", _n.get_str(), \" does not fit into a signed integer\");\n        }\n    }\n\n    explicit operator mpz_class() const { return _n; }\n\n    [[nodiscard]] std::size_t hash() const {\n        boost::hash<std::string> hasher;\n        return hasher(_n.get_str());\n    }\n\n    [[nodiscard]] bool fits_sint() const { return _n.fits_sint_p(); }\n\n    [[nodiscard]] bool fits_slong() const { return _n.fits_slong_p(); }\n\n    z_number operator+(const z_number& x) const {\n        mpz_class r = _n + x._n;\n        return z_number(r);\n    }\n\n    z_number operator+(int x) const { return operator+(z_number(x)); }\n\n    z_number operator*(const z_number& x) const {\n        mpz_class r = _n * x._n;\n        return z_number(r);\n    }\n\n    z_number operator*(int x) const { return operator*(z_number(x)); }\n\n    z_number operator-(const z_number& x) const {\n        mpz_class r = _n - x._n;\n        return z_number(r);\n    }\n\n    z_number operator-(int x) const { return operator-(z_number(x)); }\n\n    z_number operator-() const {\n        mpz_class r = -_n;\n        return z_number(r);\n    }\n\n    z_number operator/(const z_number& x) const {\n        if (x._n == 0) {\n            CRAB_ERROR(\"z_number: division by zero [1]\");\n        } else {\n            mpz_class r = _n / x._n;\n            return z_number(r);\n        }\n    }\n\n    z_number operator/(int x) const { return operator/(z_number(x)); }\n\n    z_number operator%(const z_number& x) const {\n        if (x._n == 0) {\n            CRAB_ERROR(\"z_number: division by zero [2]\");\n        } else {\n            mpz_class r = _n % x._n;\n            return z_number(r);\n        }\n    }\n\n    z_number operator%(int x) const { return operator%(z_number(x)); }\n\n    z_number& operator+=(const z_number& x) {\n        _n += x._n;\n        return *this;\n    }\n\n    z_number& operator+=(int x) { return operator+=(z_number(x)); }\n\n    z_number& operator*=(const z_number& x) {\n        _n *= x._n;\n        return *this;\n    }\n\n    z_number& operator*=(int x) { return operator*=(z_number(x)); }\n\n    z_number& operator-=(const z_number& x) {\n        _n -= x._n;\n        return *this;\n    }\n\n    z_number& operator-=(int x) { return operator-=(z_number(x)); }\n\n    z_number& operator/=(const z_number& x) {\n        if (x._n == 0) {\n            CRAB_ERROR(\"z_number: division by zero [3]\");\n        } else {\n            _n /= x._n;\n            return *this;\n        }\n    }\n\n    z_number& operator/=(int x) { return operator/=(z_number(x)); }\n\n    z_number& operator%=(const z_number& x) {\n        if (x._n == 0) {\n            CRAB_ERROR(\"z_number: division by zero [4]\");\n        } else {\n            _n %= x._n;\n            return *this;\n        }\n    }\n\n    z_number& operator%=(int x) { return operator%=(z_number(x)); }\n\n    z_number& operator--() & {\n        --(_n);\n        return *this;\n    }\n\n    z_number& operator++() & {\n        ++(_n);\n        return *this;\n    }\n\n    z_number operator++(int) & {\n        z_number r(*this);\n        ++(*this);\n        return r;\n    }\n\n    z_number operator--(int) & {\n        z_number r(*this);\n        --(*this);\n        return r;\n    }\n\n    bool operator==(const z_number& x) const { return _n == x._n; }\n    bool operator==(int x) const { return operator==(z_number(x)); }\n\n    bool operator!=(const z_number& x) const { return _n != x._n; }\n    bool operator!=(int x) const { return operator!=(z_number(x)); }\n\n    bool operator<(const z_number& x) const { return _n < x._n; }\n\n    bool operator<(int x) const { return operator<(z_number(x)); }\n\n    bool operator<=(const z_number& x) const { return _n <= x._n; }\n    bool operator<=(int x) const { return operator<=(z_number(x)); }\n\n    bool operator>(const z_number& x) const { return _n > x._n; }\n    bool operator>(int x) const { return operator>(z_number(x)); }\n\n    bool operator>=(const z_number& x) const { return _n >= x._n; }\n    bool operator>=(int x) const { return operator>=(z_number(x)); }\n\n    z_number operator&(const z_number& x) const { return z_number(_n & x._n); }\n    z_number operator&(int x) const { return operator&(z_number(x)); }\n\n    z_number operator|(const z_number& x) const { return z_number(_n | x._n); }\n    z_number operator|(int x) const { return operator|(z_number(x)); }\n\n    z_number operator^(const z_number& x) const { return z_number(_n ^ x._n); }\n    z_number operator^(int x) const { return operator^(z_number(x)); }\n\n    z_number operator<<(z_number x) const {\n        mpz_t tmp;\n        mpz_init(tmp);\n        mpz_mul_2exp(tmp, _n.get_mpz_t(), mpz_get_ui(x._n.get_mpz_t()));\n        mpz_class result(tmp);\n        return z_number(result);\n    }\n\n    z_number operator<<(int x) const { return operator<<(z_number(x)); }\n\n    z_number operator>>(z_number x) const {\n        mpz_class tmp(_n);\n        return z_number(tmp.operator>>=(mpz_get_ui(x._n.get_mpz_t())));\n    }\n    z_number operator>>(int x) const { return operator>>(z_number(x)); }\n\n    [[nodiscard]] z_number fill_ones() const {\n        assert(_n >= 0);\n        if (_n == 0) {\n            return z_number(0);\n        }\n\n        mpz_class result;\n        for (result = 1; result < _n; result = 2 * result + 1)\n            ;\n        return z_number(result);\n    }\n\n    friend std::ostream& operator<<(std::ostream& o, const z_number& z) { return o << z._n.get_str(); }\n\n}; // class z_number\n\nusing number_t = z_number;\n\ninline std::size_t hash_value(const z_number& z) { return z.hash(); }\n\n} // namespace crab\n", "meta": {"hexsha": "d27e55710f6d4c37804f9ed84ea1c0ca909cbe1f", "size": 9779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crab_utils/bignums_gmp.hpp", "max_stars_repo_name": "poornagmsft/ebpf-verifier", "max_stars_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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": "src/crab_utils/bignums_gmp.hpp", "max_issues_repo_name": "poornagmsft/ebpf-verifier", "max_issues_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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": "src/crab_utils/bignums_gmp.hpp", "max_forks_repo_name": "poornagmsft/ebpf-verifier", "max_forks_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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.5451612903, "max_line_length": 103, "alphanum_fraction": 0.6113099499, "num_tokens": 2561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.046033905998337385, "lm_q1q2_score": 0.01840489148685676}}
{"text": "#ifndef STAN_VARIATIONAL_ADVI_HPP\n#define STAN_VARIATIONAL_ADVI_HPP\n\n#include <stan/math.hpp>\n#include <stan/callbacks/logger.hpp>\n#include <stan/callbacks/writer.hpp>\n#include <stan/callbacks/stream_writer.hpp>\n#include <stan/io/dump.hpp>\n#include <stan/services/error_codes.hpp>\n#include <stan/variational/print_progress.hpp>\n#include <stan/variational/families/normal_fullrank.hpp>\n#include <stan/variational/families/normal_meanfield.hpp>\n#include <boost/circular_buffer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <algorithm>\n#include <limits>\n#include <numeric>\n#include <ostream>\n#include <vector>\n#include <queue>\n#include <string>\n\nnamespace stan {\n\nnamespace variational {\n\n/**\n * Automatic Differentiation Variational Inference\n *\n * Implements \"black box\" variational inference using stochastic gradient\n * ascent to maximize the Evidence Lower Bound for a given model\n * and variational family.\n *\n * @tparam Model class of model\n * @tparam Q class of variational distribution\n * @tparam BaseRNG class of random number generator\n */\ntemplate <class Model, class Q, class BaseRNG>\nclass advi {\n public:\n  /**\n   * Constructor\n   *\n   * @param[in] m stan model\n   * @param[in] cont_params initialization of continuous parameters\n   * @param[in,out] rng random number generator\n   * @param[in] n_monte_carlo_grad number of samples for gradient computation\n   * @param[in] n_monte_carlo_elbo number of samples for ELBO computation\n   * @param[in] eval_elbo evaluate ELBO at every \"eval_elbo\" iters\n   * @param[in] n_posterior_samples number of samples to draw from posterior\n   * @throw std::runtime_error if n_monte_carlo_grad is not positive\n   * @throw std::runtime_error if n_monte_carlo_elbo is not positive\n   * @throw std::runtime_error if eval_elbo is not positive\n   * @throw std::runtime_error if n_posterior_samples is not positive\n   */\n  advi(Model& m, Eigen::VectorXd& cont_params, BaseRNG& rng,\n       int n_monte_carlo_grad, int n_monte_carlo_elbo, int eval_elbo,\n       int n_posterior_samples)\n      : model_(m),\n        cont_params_(cont_params),\n        rng_(rng),\n        n_monte_carlo_grad_(n_monte_carlo_grad),\n        n_monte_carlo_elbo_(n_monte_carlo_elbo),\n        eval_elbo_(eval_elbo),\n        n_posterior_samples_(n_posterior_samples) {\n    static const char* function = \"stan::variational::advi\";\n    math::check_positive(function,\n                         \"Number of Monte Carlo samples for gradients\",\n                         n_monte_carlo_grad_);\n    math::check_positive(function, \"Number of Monte Carlo samples for ELBO\",\n                         n_monte_carlo_elbo_);\n    math::check_positive(function, \"Evaluate ELBO at every eval_elbo iteration\",\n                         eval_elbo_);\n    math::check_positive(function, \"Number of posterior samples for output\",\n                         n_posterior_samples_);\n  }\n\n  /**\n   * Calculates the Evidence Lower BOund (ELBO) by sampling from\n   * the variational distribution and then evaluating the log joint,\n   * adjusted by the entropy term of the variational distribution.\n   *\n   * @param[in] variational variational approximation at which to evaluate\n   * the ELBO.\n   * @param logger logger for messages\n   * @return the evidence lower bound.\n   * @throw std::domain_error If, after n_monte_carlo_elbo_ number of draws\n   * from the variational distribution all give non-finite log joint\n   * evaluations. This means that the model is severly ill conditioned or\n   * that the variational distribution has somehow collapsed.\n   */\n  double calc_ELBO(const Q& variational, callbacks::logger& logger) const {\n    static const char* function = \"stan::variational::advi::calc_ELBO\";\n\n    double elbo = 0.0;\n    int dim = variational.dimension();\n    Eigen::VectorXd zeta(dim);\n\n    int n_dropped_evaluations = 0;\n    for (int i = 0; i < n_monte_carlo_elbo_;) {\n      variational.sample(rng_, zeta);\n      try {\n        std::stringstream ss;\n        double log_prob = model_.template log_prob<false, true>(zeta, &ss);\n        if (ss.str().length() > 0)\n          logger.info(ss);\n        stan::math::check_finite(function, \"log_prob\", log_prob);\n        elbo += log_prob;\n        ++i;\n      } catch (const std::domain_error& e) {\n        ++n_dropped_evaluations;\n        if (n_dropped_evaluations >= n_monte_carlo_elbo_) {\n          const char* name = \"The number of dropped evaluations\";\n          const char* msg1 = \"has reached its maximum amount (\";\n          const char* msg2\n              = \"). Your model may be either severely \"\n                \"ill-conditioned or misspecified.\";\n          stan::math::domain_error(function, name, n_monte_carlo_elbo_, msg1,\n                                   msg2);\n        }\n      }\n    }\n    elbo /= n_monte_carlo_elbo_;\n    elbo += variational.entropy();\n    return elbo;\n  }\n\n  /**\n   * Calculates the \"black box\" gradient of the ELBO.\n   *\n   * @param[in] variational variational approximation at which to evaluate\n   * the ELBO.\n   * @param[out] elbo_grad gradient of ELBO with respect to variational\n   * approximation.\n   * @param logger logger for messages\n   */\n  void calc_ELBO_grad(const Q& variational, Q& elbo_grad,\n                      callbacks::logger& logger) const {\n    static const char* function = \"stan::variational::advi::calc_ELBO_grad\";\n\n    stan::math::check_size_match(\n        function, \"Dimension of elbo_grad\", elbo_grad.dimension(),\n        \"Dimension of variational q\", variational.dimension());\n    stan::math::check_size_match(\n        function, \"Dimension of variational q\", variational.dimension(),\n        \"Dimension of variables in model\", cont_params_.size());\n\n    variational.calc_grad(elbo_grad, model_, cont_params_, n_monte_carlo_grad_,\n                          rng_, logger);\n  }\n\n  /**\n   * Heuristic grid search to adapt eta to the scale of the problem.\n   *\n   * @param[in] variational initial variational distribution.\n   * @param[in] adapt_iterations number of iterations to spend doing stochastic\n   * gradient ascent at each proposed eta value.\n   * @param[in,out] logger logger for messages\n   * @return adapted (tuned) value of eta via heuristic grid search\n   * @throw std::domain_error If either (a) the initial ELBO cannot be\n   * computed at the initial variational distribution, (b) all step-size\n   * proposals in eta_sequence fail.\n   */\n  double adapt_eta(Q& variational, int adapt_iterations,\n                   callbacks::logger& logger) const {\n    static const char* function = \"stan::variational::advi::adapt_eta\";\n\n    stan::math::check_positive(function, \"Number of adaptation iterations\",\n                               adapt_iterations);\n\n    logger.info(\"Begin eta adaptation.\");\n\n    // Sequence of eta values to try during adaptation\n    const int eta_sequence_size = 5;\n    double eta_sequence[eta_sequence_size] = {100, 10, 1, 0.1, 0.01};\n\n    // Initialize ELBO tracking variables\n    double elbo = -std::numeric_limits<double>::max();\n    double elbo_best = -std::numeric_limits<double>::max();\n    double elbo_init;\n    try {\n      elbo_init = calc_ELBO(variational, logger);\n    } catch (const std::domain_error& e) {\n      const char* name\n          = \"Cannot compute ELBO using the initial \"\n            \"variational distribution.\";\n      const char* msg1\n          = \"Your model may be either \"\n            \"severely ill-conditioned or misspecified.\";\n      stan::math::domain_error(function, name, \"\", msg1);\n    }\n\n    // Variational family to store gradients\n    Q elbo_grad = Q(model_.num_params_r());\n\n    // Adaptive step-size sequence\n    Q history_grad_squared = Q(model_.num_params_r());\n    double tau = 1.0;\n    double pre_factor = 0.9;\n    double post_factor = 0.1;\n\n    double eta_best = 0.0;\n    double eta;\n    double eta_scaled;\n\n    bool do_more_tuning = true;\n    int eta_sequence_index = 0;\n    while (do_more_tuning) {\n      // Try next eta\n      eta = eta_sequence[eta_sequence_index];\n\n      int print_progress_m;\n      for (int iter_tune = 1; iter_tune <= adapt_iterations; ++iter_tune) {\n        print_progress_m = eta_sequence_index * adapt_iterations + iter_tune;\n        variational ::print_progress(print_progress_m, 0,\n                                     adapt_iterations * eta_sequence_size,\n                                     adapt_iterations, true, \"\", \"\", logger);\n\n        // (ROBUST) Compute gradient of ELBO. It's OK if it diverges.\n        // We'll try a smaller eta.\n        try {\n          calc_ELBO_grad(variational, elbo_grad, logger);\n        } catch (const std::domain_error& e) {\n          elbo_grad.set_to_zero();\n        }\n\n        // Update step-size\n        if (iter_tune == 1) {\n          history_grad_squared += elbo_grad.square();\n        } else {\n          history_grad_squared = pre_factor * history_grad_squared\n                                 + post_factor * elbo_grad.square();\n        }\n        eta_scaled = eta / sqrt(static_cast<double>(iter_tune));\n        // Stochastic gradient update\n        variational\n            += eta_scaled * elbo_grad / (tau + history_grad_squared.sqrt());\n      }\n\n      // (ROBUST) Compute ELBO. It's OK if it has diverged.\n      try {\n        elbo = calc_ELBO(variational, logger);\n      } catch (const std::domain_error& e) {\n        elbo = -std::numeric_limits<double>::max();\n      }\n\n      // Check if:\n      // (1) ELBO at current eta is worse than the best ELBO\n      // (2) the best ELBO hasn't gotten worse than the initial ELBO\n      if (elbo < elbo_best && elbo_best > elbo_init) {\n        std::stringstream ss;\n        ss << \"Success!\"\n           << \" Found best value [eta = \" << eta_best << \"]\";\n        if (eta_sequence_index < eta_sequence_size - 1)\n          ss << (\" earlier than expected.\");\n        else\n          ss << \".\";\n        logger.info(ss);\n        logger.info(\"\");\n        do_more_tuning = false;\n      } else {\n        if (eta_sequence_index < eta_sequence_size - 1) {\n          // Reset\n          elbo_best = elbo;\n          eta_best = eta;\n        } else {\n          // No more eta values to try, so use current eta if it\n          // didn't diverge or fail if it did diverge\n          if (elbo > elbo_init) {\n            std::stringstream ss;\n            ss << \"Success!\"\n               << \" Found best value [eta = \" << eta_best << \"].\";\n            logger.info(ss);\n            logger.info(\"\");\n            eta_best = eta;\n            do_more_tuning = false;\n          } else {\n            const char* name = \"All proposed step-sizes\";\n            const char* msg1\n                = \"failed. Your model may be either \"\n                  \"severely ill-conditioned or misspecified.\";\n            stan::math::domain_error(function, name, \"\", msg1);\n          }\n        }\n        // Reset\n        history_grad_squared.set_to_zero();\n      }\n      ++eta_sequence_index;\n      variational = Q(cont_params_);\n    }\n    return eta_best;\n  }\n\n  /**\n   * Runs stochastic gradient ascent with an adaptive stepsize sequence.\n   *\n   * @param[in,out] variational initia variational distribution\n   * @param[in] eta stepsize scaling parameter\n   * @param[in] tol_rel_obj relative tolerance parameter for convergence\n   * @param[in] max_iterations max number of iterations to run algorithm\n   * @param[in,out] logger logger for messages\n   * @param[in,out] diagnostic_writer writer for diagnostic information\n   * @throw std::domain_error If the ELBO or its gradient is ever\n   * non-finite, at any iteration\n   */\n  void stochastic_gradient_ascent(Q& variational, double eta,\n                                  double tol_rel_obj, int max_iterations,\n                                  callbacks::logger& logger,\n                                  callbacks::writer& diagnostic_writer) const {\n    static const char* function\n        = \"stan::variational::advi::stochastic_gradient_ascent\";\n\n    stan::math::check_positive(function, \"Eta stepsize\", eta);\n    stan::math::check_positive(\n        function, \"Relative objective function tolerance\", tol_rel_obj);\n    stan::math::check_positive(function, \"Maximum iterations\", max_iterations);\n\n    // Gradient parameters\n    Q elbo_grad = Q(model_.num_params_r());\n\n    // Stepsize sequence parameters\n    Q history_grad_squared = Q(model_.num_params_r());\n    double tau = 1.0;\n    double pre_factor = 0.9;\n    double post_factor = 0.1;\n    double eta_scaled;\n\n    // Initialize ELBO and convergence tracking variables\n    double elbo(0.0);\n    double elbo_best = -std::numeric_limits<double>::max();\n    double elbo_prev = -std::numeric_limits<double>::max();\n    double delta_elbo = std::numeric_limits<double>::max();\n    double delta_elbo_ave = std::numeric_limits<double>::max();\n    double delta_elbo_med = std::numeric_limits<double>::max();\n\n    // Heuristic to estimate how far to look back in rolling window\n    int cb_size\n        = static_cast<int>(std::max(0.1 * max_iterations / eval_elbo_, 2.0));\n    boost::circular_buffer<double> elbo_diff(cb_size);\n\n    logger.info(\"Begin stochastic gradient ascent.\");\n    logger.info(\n        \"  iter\"\n        \"             ELBO\"\n        \"   delta_ELBO_mean\"\n        \"   delta_ELBO_med\"\n        \"   notes \");\n\n    // Timing variables\n    clock_t start = clock();\n    clock_t end;\n    double delta_t;\n\n    // Main loop\n    bool do_more_iterations = true;\n    for (int iter_counter = 1; do_more_iterations; ++iter_counter) {\n      // Compute gradient using Monte Carlo integration\n      calc_ELBO_grad(variational, elbo_grad, logger);\n\n      // Update step-size\n      if (iter_counter == 1) {\n        history_grad_squared += elbo_grad.square();\n      } else {\n        history_grad_squared = pre_factor * history_grad_squared\n                               + post_factor * elbo_grad.square();\n      }\n      eta_scaled = eta / sqrt(static_cast<double>(iter_counter));\n\n      // Stochastic gradient update\n      variational\n          += eta_scaled * elbo_grad / (tau + history_grad_squared.sqrt());\n\n      // Check for convergence every \"eval_elbo_\"th iteration\n      if (iter_counter % eval_elbo_ == 0) {\n        elbo_prev = elbo;\n        elbo = calc_ELBO(variational, logger);\n        if (elbo > elbo_best)\n          elbo_best = elbo;\n        delta_elbo = rel_difference(elbo, elbo_prev);\n        elbo_diff.push_back(delta_elbo);\n        delta_elbo_ave\n            = std::accumulate(elbo_diff.begin(), elbo_diff.end(), 0.0)\n              / static_cast<double>(elbo_diff.size());\n        delta_elbo_med = circ_buff_median(elbo_diff);\n        std::stringstream ss;\n        ss << \"  \" << std::setw(4) << iter_counter << \"  \" << std::setw(15)\n           << std::fixed << std::setprecision(3) << elbo << \"  \"\n           << std::setw(16) << std::fixed << std::setprecision(3)\n           << delta_elbo_ave << \"  \" << std::setw(15) << std::fixed\n           << std::setprecision(3) << delta_elbo_med;\n\n        end = clock();\n        delta_t = static_cast<double>(end - start) / CLOCKS_PER_SEC;\n\n        std::vector<double> print_vector;\n        print_vector.clear();\n        print_vector.push_back(iter_counter);\n        print_vector.push_back(delta_t);\n        print_vector.push_back(elbo);\n        diagnostic_writer(print_vector);\n\n        if (delta_elbo_ave < tol_rel_obj) {\n          ss << \"   MEAN ELBO CONVERGED\";\n          do_more_iterations = false;\n        }\n\n        if (delta_elbo_med < tol_rel_obj) {\n          ss << \"   MEDIAN ELBO CONVERGED\";\n          do_more_iterations = false;\n        }\n\n        if (iter_counter > 10 * eval_elbo_) {\n          if (delta_elbo_med > 0.5 || delta_elbo_ave > 0.5) {\n            ss << \"   MAY BE DIVERGING... INSPECT ELBO\";\n          }\n        }\n\n        logger.info(ss);\n\n        if (do_more_iterations == false\n            && rel_difference(elbo, elbo_best) > 0.05) {\n          logger.info(\n              \"Informational Message: The ELBO at a previous \"\n              \"iteration is larger than the ELBO upon \"\n              \"convergence!\");\n          logger.info(\n              \"This variational approximation may not \"\n              \"have converged to a good optimum.\");\n        }\n      }\n\n      if (iter_counter == max_iterations) {\n        logger.info(\n            \"Informational Message: The maximum number of \"\n            \"iterations is reached! The algorithm may not have \"\n            \"converged.\");\n        logger.info(\n            \"This variational approximation is not \"\n            \"guaranteed to be meaningful.\");\n        do_more_iterations = false;\n      }\n    }\n  }\n\n  /**\n   * Runs ADVI and writes to output.\n   *\n   * @param[in] eta eta parameter of stepsize sequence\n   * @param[in] adapt_engaged boolean flag for eta adaptation\n   * @param[in] adapt_iterations number of iterations for eta adaptation\n   * @param[in] tol_rel_obj relative tolerance parameter for convergence\n   * @param[in] max_iterations max number of iterations to run algorithm\n   * @param[in,out] logger logger for messages\n   * @param[in,out] parameter_writer writer for parameters\n   *   (typically to file)\n   * @param[in,out] diagnostic_writer writer for diagnostic information\n   */\n  int run(double eta, bool adapt_engaged, int adapt_iterations,\n          double tol_rel_obj, int max_iterations, callbacks::logger& logger,\n          callbacks::writer& parameter_writer,\n          callbacks::writer& diagnostic_writer) const {\n    diagnostic_writer(\"iter,time_in_seconds,ELBO\");\n\n    // Initialize variational approximation\n    Q variational = Q(cont_params_);\n\n    if (adapt_engaged) {\n      eta = adapt_eta(variational, adapt_iterations, logger);\n      parameter_writer(\"Stepsize adaptation complete.\");\n      std::stringstream ss;\n      ss << \"eta = \" << eta;\n      parameter_writer(ss.str());\n    }\n\n    stochastic_gradient_ascent(variational, eta, tol_rel_obj, max_iterations,\n                               logger, diagnostic_writer);\n\n    // Write posterior mean of variational approximations.\n    cont_params_ = variational.mean();\n    std::vector<double> cont_vector(cont_params_.size());\n    for (int i = 0; i < cont_params_.size(); ++i)\n      cont_vector.at(i) = cont_params_(i);\n    std::vector<int> disc_vector;\n    std::vector<double> values;\n\n    std::stringstream msg;\n    model_.write_array(rng_, cont_vector, disc_vector, values, true, true,\n                       &msg);\n    if (msg.str().length() > 0)\n      logger.info(msg);\n\n    // The first row of lp_, log_p, and log_g.\n    values.insert(values.begin(), {0, 0, 0});\n    parameter_writer(values);\n\n    // Draw more from posterior and write on subsequent lines\n    logger.info(\"\");\n    std::stringstream ss;\n    ss << \"Drawing a sample of size \" << n_posterior_samples_\n       << \" from the approximate posterior... \";\n    logger.info(ss);\n    double log_p = 0;\n    double log_g = 0;\n    // Draw posterior sample. log_g is the log normal densities.\n    for (int n = 0; n < n_posterior_samples_; ++n) {\n      variational.sample_log_g(rng_, cont_params_, log_g);\n      for (int i = 0; i < cont_params_.size(); ++i) {\n        cont_vector.at(i) = cont_params_(i);\n      }\n      std::stringstream msg2;\n      model_.write_array(rng_, cont_vector, disc_vector, values, true, true,\n                         &msg2);\n      //  log_p: Log probability in the unconstrained space\n      log_p = model_.template log_prob<false, true>(cont_params_, &msg2);\n      if (msg2.str().length() > 0)\n        logger.info(msg2);\n      // Write lp__, log_p, and log_g.\n      values.insert(values.begin(), {0, log_p, log_g});\n      parameter_writer(values);\n    }\n    logger.info(\"COMPLETED.\");\n    return stan::services::error_codes::OK;\n  }\n\n  // TODO(akucukelbir): move these things to stan math and test there\n\n  /**\n   * Compute the median of a circular buffer.\n   *\n   * @param[in] cb circular buffer with some number of values in it.\n   * @return median of values in circular buffer.\n   */\n  double circ_buff_median(const boost::circular_buffer<double>& cb) const {\n    // FIXME: naive implementation; creates a copy as a vector\n    std::vector<double> v;\n    for (boost::circular_buffer<double>::const_iterator i = cb.begin();\n         i != cb.end(); ++i) {\n      v.push_back(*i);\n    }\n\n    size_t n = v.size() / 2;\n    std::nth_element(v.begin(), v.begin() + n, v.end());\n    return v[n];\n  }\n\n  /**\n   * Compute the relative difference between two double values.\n   *\n   * @param[in] prev previous value\n   * @param[in] curr current value\n   * @return  absolutely value of relative difference\n   */\n  double rel_difference(double prev, double curr) const {\n    return std::fabs((curr - prev) / prev);\n  }\n\n protected:\n  Model& model_;\n  Eigen::VectorXd& cont_params_;\n  BaseRNG& rng_;\n  int n_monte_carlo_grad_;\n  int n_monte_carlo_elbo_;\n  int eval_elbo_;\n  int n_posterior_samples_;\n};\n}  // namespace variational\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "ca1eb4cc8596136c84ccfe462f5ab78f7db62ce6", "size": 20772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/variational/advi.hpp", "max_stars_repo_name": "Dr-G/stan", "max_stars_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "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/variational/advi.hpp", "max_issues_repo_name": "Dr-G/stan", "max_issues_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/variational/advi.hpp", "max_forks_repo_name": "Dr-G/stan", "max_forks_repo_head_hexsha": "c2dfa08f30d3bd5db936fcc4327cd056cfc1dcbb", "max_forks_repo_licenses": ["BSD-3-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.5061511424, "max_line_length": 80, "alphanum_fraction": 0.6320527633, "num_tokens": 4980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584297, "lm_q2_score": 0.04272219602295819, "lm_q1q2_score": 0.01837683934504011}}
{"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 <experimental_data.hh>\n#include <utils.hh>\n\n#include <deal.II/arborx/bvh.h>\n#include <deal.II/base/symmetric_tensor.h>\n#include <deal.II/base/tensor.h>\n#include <deal.II/dofs/dof_handler.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/grid/reference_cell.h>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n\n#include <Kokkos_HostSpace.hpp>\n\n#include <cstdlib>\n#include <fstream>\n#include <limits>\n#include <optional>\n#include <regex>\n#include <sstream>\n\n#include <ArborX_Ray.hpp>\n\nnamespace adamantine\n{\n/**\n * This class implements a predicate for the intersection of Ray and\n * BoundingBox\n */\nclass RayIntersectPredicate\n{\npublic:\n  /**\n   * Constructor. @p points is a list of points which we are interested in\n   * knowing if they intersect ArborXWrappers::BVH bounding boxes.\n   */\n  RayIntersectPredicate(std::vector<Ray<3>> const &rays) : _rays(rays) {}\n\n  /**\n   * Number of rays stored in the structure.\n   */\n  std::size_t size() const { return _rays.size(); }\n\n  /**\n   * Return the `i`th Ray stored in the object.\n   */\n  Ray<3> const &get(unsigned int i) const { return _rays[i]; }\n\nprivate:\n  std::vector<Ray<3>> _rays;\n};\n} // namespace adamantine\n\nnamespace ArborX\n{\ntemplate <>\nstruct AccessTraits<adamantine::RayIntersectPredicate, PredicatesTag>\n{\n  using memory_space = Kokkos::HostSpace;\n\n  static std::size_t\n  size(adamantine::RayIntersectPredicate const &ray_intersect)\n  {\n    return ray_intersect.size();\n  }\n\n  static auto get(adamantine::RayIntersectPredicate const &ray_intersect,\n                  std::size_t i)\n  {\n    auto const &ray = ray_intersect.get(i);\n    auto const &origin = ray.origin;\n    auto const &direction = ray.direction;\n    ArborX::Experimental::Ray arborx_ray = {\n        ArborX::Point{(float)origin[0], (float)origin[1], (float)origin[2]},\n        ArborX::Experimental::Ray::Vector{\n            (float)direction[0], (float)direction[1], (float)direction[2]}};\n    return intersects(arborx_ray);\n  }\n};\n} // namespace ArborX\n\nnamespace adamantine\n{\ntemplate <int dim>\nstd::vector<PointsValues<dim>> read_experimental_data_point_cloud(\n    MPI_Comm const &communicator,\n    boost::property_tree::ptree const &experiment_database)\n{\n  // Format of the file names: the format is pretty arbitrary, #frame and\n  // #camera are replaced by the frame and the camera number.\n  // PropertyTreeInput experiment.file\n  std::string data_filename = experiment_database.get<std::string>(\"file\");\n  // PropertyTreeInput experiment.first_frame\n  unsigned int first_frame = experiment_database.get(\"first_frame\", 0);\n  // PropertyTreeInput experiment.last_frame\n  unsigned int last_frame = experiment_database.get<unsigned int>(\"last_frame\");\n  // PropertyTreeInput experiment.first_camera_id\n  unsigned int first_camera_id =\n      experiment_database.get<unsigned int>(\"first_camera_id\");\n  // PropertyTreeInput experiment.last_camera_id\n  unsigned int last_camera_id = experiment_database.get<int>(\"last_camera_id\");\n  // PropertyTreeInput experiment.data_columns\n  std::string data_columns =\n      experiment_database.get<std::string>(\"data_columns\");\n\n  std::vector<PointsValues<dim>> points_values_all_frames(last_frame + 1 -\n                                                          first_frame);\n  for (unsigned int frame = first_frame; frame < last_frame + 1; ++frame)\n  {\n    PointsValues<dim> points_values;\n    for (unsigned int camera_id = first_camera_id;\n         camera_id < last_camera_id + 1; ++camera_id)\n    {\n      // Use regex to get the next file to read\n      std::regex camera_regex(\"#camera\");\n      std::regex frame_regex(\"#frame\");\n      auto regex_filename =\n          std::regex_replace((std::regex_replace(data_filename, camera_regex,\n                                                 std::to_string(camera_id))),\n                             frame_regex, std::to_string(frame));\n      ASSERT(boost::filesystem::exists(regex_filename),\n             \"The file \" + regex_filename + \" does not exist.\");\n      std::string filename(\"data_\" + std::to_string(frame) + \"_\" +\n                           std::to_string(camera_id) + \".csv\");\n\n      // Use bash to create a new file that only contains the columns that we\n      // care about. For large files this divides by four the time to parse the\n      // files. It also simplifies reading the files. Only rank zero renames\n      // the file.\n      if (dealii::Utilities::MPI::this_mpi_process(communicator) == 0)\n      {\n        std::string cut_command(\"cut -d, -f\" + data_columns + \" \" +\n                                regex_filename + \" > \" + filename);\n        std::system(cut_command.c_str());\n      }\n\n      // Wait for rank zero before reading the file.\n      MPI_Barrier(communicator);\n\n      // Read and parse the file\n      std::ifstream file;\n      file.open(filename);\n      std::string line;\n      std::getline(file, line);\n      while (std::getline(file, line))\n      {\n        std::size_t pos = 0;\n        std::size_t last_pos = 0;\n        std::size_t line_length = line.length();\n        unsigned int i = 0;\n        dealii::Point<dim> point;\n        double value = 0.;\n        while (last_pos < line_length + 1)\n        {\n          pos = line.find_first_of(\",\", last_pos);\n          // If no comma was found that we read until the end of the file\n          if (pos == std::string::npos)\n          {\n            pos = line_length;\n          }\n\n          if (pos != last_pos)\n          {\n            char *end = line.data() + pos;\n            if (i < dim)\n            {\n              point[i] = std::strtod(line.data() + last_pos, &end);\n            }\n            else\n            {\n              value = std::strtod(line.data() + last_pos, &end);\n            }\n\n            ++i;\n          }\n\n          last_pos = pos + 1;\n        }\n\n        points_values.points.push_back(point);\n        points_values.values.push_back(value);\n      }\n\n      // Wait for every rank to be done reading the temporary stripped file and\n      // then remove it.\n      MPI_Barrier(communicator);\n      if (dealii::Utilities::MPI::this_mpi_process(communicator) == 0)\n      {\n        std::string rm_command(\"rm \" + filename);\n        std::system(rm_command.c_str());\n      }\n    }\n    points_values_all_frames[frame - first_frame] = points_values;\n  }\n\n  return points_values_all_frames;\n}\n\ntemplate <int dim>\nstd::pair<std::vector<int>, std::vector<int>> set_with_experimental_data(\n    PointsValues<dim> const &points_values,\n    dealii::DoFHandler<dim> const &dof_handler,\n    dealii::LinearAlgebra::distributed::Vector<double> &temperature)\n{\n  // First we need to get all the supports points and the associated dof\n  // indices\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 something that can be used by ArborX\n  std::vector<dealii::types::global_dof_index> dof_indices(\n      indices_points.size());\n  std::vector<dealii::Point<dim>> support_points(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    support_points[pos] = map_it->second;\n  }\n\n  // Perform the search\n  dealii::ArborXWrappers::BVH bvh(support_points);\n  dealii::ArborXWrappers::PointNearestPredicate pt_nearest(points_values.points,\n                                                           1);\n  auto [indices, offset] = bvh.query(pt_nearest);\n\n  // Fill in the temperature\n  unsigned int const n_queries = points_values.points.size();\n  for (unsigned int i = 0; i < n_queries; ++i)\n  {\n    for (int j = offset[i]; j < offset[i + 1]; ++j)\n    {\n      temperature[dof_indices[indices[j]]] = points_values.values[i];\n    }\n  }\n\n  temperature.compress(dealii::VectorOperation::insert);\n\n  return {indices, offset};\n}\n\nstd::vector<std::vector<double>>\nread_frame_timestamps(boost::property_tree::ptree const &experiment_database)\n{\n  // PropertyTreeInput experiment.log_filename\n  std::string log_filename =\n      experiment_database.get<std::string>(\"log_filename\");\n\n  ASSERT(boost::filesystem::exists(log_filename),\n         \"The file \" + log_filename + \" does not exist.\");\n\n  // PropertyTreeInput experiment.first_frame_temporal_offset\n  double first_frame_offset =\n      experiment_database.get(\"first_frame_temporal_offset\", 0.0);\n\n  // PropertyTreeInput experiment.first_frame\n  unsigned int first_frame =\n      experiment_database.get<unsigned int>(\"first_frame\", 0);\n  // PropertyTreeInput experiment.last_frame\n  unsigned int last_frame = experiment_database.get<unsigned int>(\"last_frame\");\n\n  // PropertyTreeInput experiment.first_camera_id\n  unsigned int first_camera_id =\n      experiment_database.get<unsigned int>(\"first_camera_id\");\n  // PropertyTreeInput experiment.last_camera_id\n  unsigned int last_camera_id =\n      experiment_database.get<unsigned int>(\"last_camera_id\");\n\n  unsigned int num_cameras = last_camera_id - first_camera_id + 1;\n  std::vector<std::vector<double>> time_stamps(num_cameras);\n\n  std::vector<double> first_frame_value(num_cameras);\n\n  // Read and parse the file\n  std::ifstream file;\n  file.open(log_filename);\n  std::string line;\n  std::getline(file, line);\n  while (std::getline(file, line))\n  {\n    unsigned int entry_index = 0;\n    std::stringstream s_stream(line);\n    bool frame_of_interest = false;\n    unsigned int frame = std::numeric_limits<unsigned int>::max();\n    while (s_stream.good())\n    {\n      std::string substring;\n      std::getline(s_stream, substring, ',');\n      boost::trim(substring);\n\n      if (entry_index == 0)\n      {\n        ASSERT(std::stoi(substring) - frame == 1 ||\n                   frame == std::numeric_limits<unsigned int>::max(),\n               \"The file \" + log_filename +\n                   \" does not have consecutive frame indices.\");\n        frame = std::stoi(substring);\n        if (frame >= first_frame && frame <= last_frame)\n          frame_of_interest = true;\n      }\n      else\n      {\n        if (frame == first_frame && substring.size() > 0)\n          first_frame_value[entry_index - 1] = std::stod(substring);\n\n        if (frame_of_interest && substring.size() > 0)\n          time_stamps[entry_index - 1].push_back(\n              std::stod(substring) - first_frame_value[entry_index - 1] +\n              first_frame_offset);\n      }\n      entry_index++;\n    }\n  }\n  return time_stamps;\n}\n\nRayTracing::RayTracing(boost::property_tree::ptree const &experiment_database)\n{\n\n  // Format of the file names: the format is pretty arbitrary, #frame and\n  // #camera are replaced by the frame and the camera number.\n  // PropertyTreeInput experiment.file\n  std::string data_filename = experiment_database.get<std::string>(\"file\");\n  // PropertyTreeInput experiment.first_frame\n  unsigned int first_frame = experiment_database.get(\"first_frame\", 0);\n  // PropertyTreeInput experiment.last_frame\n  unsigned int last_frame = experiment_database.get<unsigned int>(\"last_frame\");\n  // PropertyTreeInput experiment.first_camera_id\n  unsigned int first_camera_id =\n      experiment_database.get<unsigned int>(\"first_camera_id\");\n  // PropertyTreeInput experiment.last_camera_id\n  unsigned int last_camera_id = experiment_database.get<int>(\"last_camera_id\");\n\n  _rays_all_frames.resize(last_frame + 1 - first_frame);\n  _values_all_frames.resize(last_frame + 1 - first_frame);\n  for (unsigned int frame = first_frame; frame < last_frame + 1; ++frame)\n  {\n    std::vector<Ray<dim>> rays_one_frame;\n    std::vector<double> values_one_frame;\n    for (unsigned int camera_id = first_camera_id;\n         camera_id < last_camera_id + 1; ++camera_id)\n    {\n      // Use regex to get the next file to read\n      std::regex camera_regex(\"#camera\");\n      std::regex frame_regex(\"#frame\");\n      auto filename =\n          std::regex_replace((std::regex_replace(data_filename, camera_regex,\n                                                 std::to_string(camera_id))),\n                             frame_regex, std::to_string(frame));\n      ASSERT(boost::filesystem::exists(filename),\n             \"The file \" + filename + \" does not exist.\");\n\n      // Read and parse the file\n      std::ifstream file;\n      file.open(filename);\n      std::string line;\n      while (std::getline(file, line))\n      {\n        std::size_t pos = 0;\n        std::size_t last_pos = 0;\n        std::size_t line_length = line.length();\n        unsigned int i = 0;\n        dealii::Point<dim> point;\n        dealii::Tensor<1, dim> direction;\n        double value = 0.;\n        while (last_pos < line_length + 1)\n        {\n          pos = line.find_first_of(\",\", last_pos);\n          // If no comma was found that we read until the end of the file\n          if (pos == std::string::npos)\n          {\n            pos = line_length;\n          }\n\n          if (pos != last_pos)\n          {\n            char *end = line.data() + pos;\n            if (i < dim)\n            {\n              point[i] = std::strtod(line.data() + last_pos, &end);\n            }\n            else if (i < 2 * dim)\n            {\n              direction[i - dim] = std::strtod(line.data() + last_pos, &end);\n            }\n            else\n            {\n              value = std::strtod(line.data() + last_pos, &end);\n            }\n\n            ++i;\n          }\n\n          last_pos = pos + 1;\n        }\n\n        Ray<dim> ray{point, direction};\n        rays_one_frame.push_back(ray);\n        values_one_frame.push_back(value);\n      }\n    }\n    _rays_all_frames[frame - first_frame] = rays_one_frame;\n    _values_all_frames[frame - first_frame] = values_one_frame;\n  }\n}\n\nPointsValues<3>\nRayTracing::get_intersection(dealii::DoFHandler<3> const &dof_handler,\n                             unsigned int frame)\n{\n  PointsValues<dim> points_values;\n\n  // Perform the ray tracing to get the cells that are intersected by rays\n\n  // Create the bounding boxes associated to the locally owned cells with FE\n  // index = 0\n  std::vector<dealii::BoundingBox<dim>> bounding_boxes;\n  std::vector<typename dealii::DoFHandler<dim>::active_cell_iterator>\n      cell_iterators;\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    bounding_boxes.push_back(cell->bounding_box());\n    cell_iterators.push_back(cell);\n  }\n\n  dealii::ArborXWrappers::BVH bvh(bounding_boxes);\n  RayIntersectPredicate ray_intersect(_rays_all_frames[frame]);\n  auto [indices, offset] = bvh.query(ray_intersect);\n\n  // Find the exact intersections points\n  // See https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection\n  // NOTE that we assume that the faces are flat. If the faces are curved,\n  // this is wrong.\n  unsigned int const n_rays = _rays_all_frames[frame].size();\n  unsigned int n_intersections = 0;\n  for (unsigned int i = 0; i < n_rays; ++i)\n  {\n    if (offset[i] != offset[i + 1])\n    {\n      ++n_intersections;\n    }\n  }\n  std::vector<double> distances(n_intersections,\n                                std::numeric_limits<double>::max());\n  points_values.points.resize(n_intersections);\n  points_values.values.resize(n_intersections);\n  auto constexpr reference_cell = dealii::ReferenceCells::get_hypercube<dim>();\n  double constexpr tolerance = 1e-12;\n  unsigned int ii = 0;\n  for (unsigned int i = 0; i < n_rays; ++i)\n  {\n    points_values.values[ii] = _values_all_frames[frame][i];\n    for (int j = offset[i]; j < offset[i + 1]; ++j)\n    {\n      auto const &cell = cell_iterators[indices[j]];\n      // We know that the ray intersects the bounding box but we don't know\n      // where it intersects the cells. We need to check the intersection of\n      // the ray with each face of the cell.\n      for (unsigned int f = 0; f < reference_cell.n_faces(); ++f)\n      {\n        // First we check if the ray is parallel to the face. If this is the\n        // case, either the ray misses the face or the ray hits the edge of\n        // the face. In that last case, the ray is also orthogonal to another\n        // face and it is safe to discard all rays parallel to a face.\n        auto const point_0 = cell->face(f)->vertex(0);\n        auto const point_1 = cell->face(f)->vertex(1);\n        auto const point_2 = cell->face(f)->vertex(2);\n        dealii::Tensor<1, dim> edge_01({point_1[0] - point_0[0],\n                                        point_1[1] - point_0[1],\n                                        point_1[2] - point_0[2]});\n        dealii::Tensor<1, dim> edge_02({point_2[0] - point_0[0],\n                                        point_2[1] - point_0[1],\n                                        point_2[2] - point_0[2]});\n        auto const &ray_direction = _rays_all_frames[frame][i].direction;\n        dealii::Tensor<2, dim> matrix(\n            {{-ray_direction[0], -ray_direction[1], -ray_direction[2]},\n             {edge_01[0], edge_01[1], edge_01[2]},\n             {edge_02[0], edge_02[1], edge_02[2]}});\n        double det = dealii::determinant(matrix);\n        // If determinant is close to zero, the ray is parallel to the face\n        // and we go to the next face.\n        if (std::abs(det) < tolerance)\n          continue;\n        // Compute the distance along the ray direction between the origin of\n        // the ray and the intersection point.\n        auto const cross_product = dealii::cross_product_3d(edge_01, edge_02);\n        auto const &ray_origin = _rays_all_frames[frame][i].origin;\n        dealii::Tensor<1, dim> p0_ray({ray_origin[0] - point_0[0],\n                                       ray_origin[1] - point_0[1],\n                                       ray_origin[2] - point_0[2]});\n        double d = cross_product * p0_ray / det;\n        // We can finally compute the intersection point. It is possible that\n        // a ray intersects multiple faces. For instance if the mesh is a cube\n        // the ray will get into the cube from one face and it will get out of\n        // the cube by the opposite face. The correct intersection point is\n        // the one with the smallest distance.\n        if (d < distances[ii])\n        {\n          // The point intersects the plane of the face but maybe not the face\n          // itself. Check that the point is on the face.\n          // NOTE: We assume that the face is an axis-aligned rectangle.\n          dealii::Point<dim> intersection = ray_origin + d * ray_direction;\n          std::vector<double> min(dim, std::numeric_limits<double>::max());\n          std::vector<double> max(dim, std::numeric_limits<double>::lowest());\n          for (unsigned int coord = 0; coord < dim; ++coord)\n          {\n            if (point_0[coord] < min[coord])\n              min[coord] = point_0[coord];\n            if (point_0[coord] > max[coord])\n              max[coord] = point_0[coord];\n\n            if (point_1[coord] < min[coord])\n              min[coord] = point_1[coord];\n            if (point_1[coord] > max[coord])\n              max[coord] = point_1[coord];\n\n            if (point_2[coord] < min[coord])\n              min[coord] = point_2[coord];\n            if (point_2[coord] > max[coord])\n              max[coord] = point_2[coord];\n          }\n\n          bool on_the_face = true;\n          for (unsigned int coord = 0; coord < 3; ++coord)\n          {\n            // NOTE: We could add a tolerance if the intersection point is on\n            // the edge. Currently, we may lose some rays but I don't think it\n            // matters. The mesh does not match exactly the real object\n            // anyway.\n            if ((intersection[coord] < min[coord]) ||\n                (intersection[coord] > max[coord]))\n            {\n              on_the_face = false;\n              break;\n            }\n          }\n\n          if (on_the_face)\n          {\n            points_values.points[ii] = intersection;\n            distances[ii] = d;\n          }\n        }\n      }\n    }\n    if (offset[i] != offset[i + 1])\n      ++ii;\n  }\n\n  return points_values;\n}\n\n} // namespace adamantine\n\n//-------------------- Explicit Instantiations --------------------//\nnamespace adamantine\n{\ntemplate std::vector<PointsValues<2>> read_experimental_data_point_cloud(\n    MPI_Comm const &communicator,\n    boost::property_tree::ptree const &experiment_database);\ntemplate std::vector<PointsValues<3>> read_experimental_data_point_cloud(\n    MPI_Comm const &communicator,\n    boost::property_tree::ptree const &experiment_database);\n\ntemplate std::pair<std::vector<int>, std::vector<int>>\nset_with_experimental_data(\n    PointsValues<2> const &points_values,\n    dealii::DoFHandler<2> const &dof_handler,\n    dealii::LinearAlgebra::distributed::Vector<double> &temperature);\ntemplate std::pair<std::vector<int>, std::vector<int>>\nset_with_experimental_data(\n    PointsValues<3> const &points_values,\n    dealii::DoFHandler<3> const &dof_handler,\n    dealii::LinearAlgebra::distributed::Vector<double> &temperature);\n} // namespace adamantine\n", "meta": {"hexsha": "e151425ff952fc9ef86e04e42639c9aae355f266", "size": 21449, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/experimental_data.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/experimental_data.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/experimental_data.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": 36.3542372881, "max_line_length": 80, "alphanum_fraction": 0.627908061, "num_tokens": 5131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.044680865820311146, "lm_q1q2_score": 0.01836878958543398}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_CORE_POINT_ORDER_HPP\r\n#define BOOST_GEOMETRY_CORE_POINT_ORDER_HPP\r\n\r\n\r\n#include <boost/mpl/assert.hpp>\r\n#include <boost/range.hpp>\r\n#include <boost/type_traits/remove_const.hpp>\r\n\r\n#include <boost/geometry/core/ring_type.hpp>\r\n#include <boost/geometry/core/tag.hpp>\r\n#include <boost/geometry/core/tags.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n/*!\r\n\\brief Enumerates options for the order of points within polygons\r\n\\ingroup enum\r\n\\details The enumeration order_selector describes options for the order of \r\n    points within a polygon. Polygons can be ordered either clockwise or \r\n    counterclockwise. The specific order of a polygon type is defined by the \r\n    point_order metafunction. The point_order metafunction defines a value, \r\n    which is one of the values enumerated in the order_selector\r\n\r\n\\qbk{\r\n[heading See also]\r\n[link geometry.reference.core.point_order The point_order metafunction]\r\n}\r\n*/\r\nenum order_selector\r\n{\r\n    /// Points are ordered clockwise\r\n    clockwise = 1,\r\n    /// Points are ordered counter clockwise\r\n    counterclockwise = 2,\r\n    /// Points might be stored in any order, algorithms will determine it on the\r\n    /// fly (not yet supported)\r\n    order_undetermined = 0\r\n};\r\n\r\nnamespace traits\r\n{\r\n\r\n/*!\r\n\\brief Traits class indicating the order of contained points within a\r\n    ring or (multi)polygon, clockwise, counter clockwise or not known.\r\n\\ingroup traits\r\n\\tparam Ring ring\r\n*/\r\ntemplate <typename Ring>\r\nstruct point_order\r\n{\r\n    static const order_selector value = clockwise;\r\n};\r\n\r\n\r\n} // namespace traits\r\n\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace point_order\r\n{\r\n\r\nstruct clockwise\r\n{\r\n    static const order_selector value = geometry::clockwise;\r\n};\r\n\r\n\r\n}} // namespace detail::point_order\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n\r\n\r\n#ifndef DOXYGEN_NO_DISPATCH\r\nnamespace core_dispatch\r\n{\r\n\r\ntemplate <typename Tag, typename Geometry>\r\nstruct point_order\r\n{\r\n    BOOST_MPL_ASSERT_MSG\r\n        (\r\n            false, NOT_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE\r\n            , (types<Geometry>)\r\n        );\r\n};\r\n\r\ntemplate <typename Point>\r\nstruct point_order<point_tag, Point>\r\n    : public detail::point_order::clockwise {};\r\n\r\ntemplate <typename Segment>\r\nstruct point_order<segment_tag, Segment>\r\n    : public detail::point_order::clockwise {};\r\n\r\n\r\ntemplate <typename Box>\r\nstruct point_order<box_tag, Box>\r\n    : public detail::point_order::clockwise {};\r\n\r\ntemplate <typename LineString>\r\nstruct point_order<linestring_tag, LineString>\r\n    : public detail::point_order::clockwise {};\r\n\r\n\r\ntemplate <typename Ring>\r\nstruct point_order<ring_tag, Ring>\r\n{\r\n    static const order_selector value \r\n        = geometry::traits::point_order<Ring>::value;\r\n};\r\n\r\n// Specialization for polygon: the order is the order of its rings\r\ntemplate <typename Polygon>\r\nstruct point_order<polygon_tag, Polygon>\r\n{\r\n    static const order_selector value = core_dispatch::point_order\r\n        <\r\n            ring_tag,\r\n            typename ring_type<polygon_tag, Polygon>::type\r\n        >::value ;\r\n};\r\n\r\n} // namespace core_dispatch\r\n#endif // DOXYGEN_NO_DISPATCH\r\n\r\n\r\n/*!\r\n\\brief \\brief_meta{value, point order (clockwise\\, counterclockwise), \r\n    \\meta_geometry_type}\r\n\\tparam Geometry \\tparam_geometry\r\n\\ingroup core\r\n\r\n\\qbk{[include reference/core/point_order.qbk]}\r\n*/\r\ntemplate <typename Geometry>\r\nstruct point_order\r\n{\r\n    static const order_selector value = core_dispatch::point_order\r\n        <\r\n            typename tag<Geometry>::type,\r\n            typename boost::remove_const<Geometry>::type\r\n        >::value;\r\n};\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_CORE_POINT_ORDER_HPP\r\n", "meta": {"hexsha": "babbec21d5a9a5fc7903ff4e58d3833731884c05", "size": 4291, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependencies/boost_geometry/boost/geometry/core/point_order.hpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-30T18:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T18:41:39.000Z", "max_issues_repo_path": "dependencies/boost_geometry/boost/geometry/core/point_order.hpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dependencies/boost_geometry/boost/geometry/core/point_order.hpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3251533742, "max_line_length": 81, "alphanum_fraction": 0.7103239338, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.056652423715250484, "lm_q1q2_score": 0.018368721946420596}}
{"text": "/*  \n *  Copyright 2010-2011 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 <boost/foreach.hpp>\n\n#include \"fiber.hpp\"\n\nnamespace ocl\n{\n\nFiber::Fiber(const Point &p1in, const Point &p2in) {\n    p1=p1in;\n    p2=p2in;\n    calcDir();\n}\n\nvoid Fiber::calcDir() {\n    dir = p2 - p1;\n    assert( dir.z == 0.0 );\n    dir.normalize();\n}\n\nbool Fiber::contains(Interval& i) const {\n    BOOST_FOREACH( Interval fi, ints) {\n        if ( i.inside( fi ) )\n            return true;\n    }\n    return false;\n}\n\nbool Fiber::missing(Interval& i) const {\n    bool result = true;\n    BOOST_FOREACH( Interval fi, ints) {\n        if ( !i.outside( fi ) ) // all existing ints must be non-overlapping\n            result = false; \n    }\n    return result;\n}\n\nvoid Fiber::addInterval(Interval& i) {\n    if (i.empty())\n        return; // do nothing.\n    \n    if (ints.empty()) { // empty fiber case\n        ints.push_back(i); \n        return;\n    } else if ( this->contains(i)  ) { // if fiber already contains i  \n        return; // do nothing\n    } else if ( this->missing(i) ) { // if fiber doesn't contain i \n        ints.push_back(i);\n        return;\n    } else {\n        // this is the messier general case with partial overlap\n        std::vector<Interval>::iterator itr;\n        itr = ints.begin();\n        std::vector<Interval> overlaps;\n        while (itr!=ints.end()) { // loop through all intervals\n            if ( ! (itr->outside( i )) ) {\n                overlaps.push_back(*itr); // add overlaps here\n                itr = ints.erase(itr); // erase overlaps from ints\n            } else {\n                ++itr;\n            }\n        }\n        overlaps.push_back(i);\n        // now build a new interval from i and the overlaps\n        Interval sumint;        \n        BOOST_FOREACH(Interval intr, overlaps) {\n            sumint.updateLower( intr.lower, intr.lower_cc );\n            sumint.updateUpper( intr.upper, intr.upper_cc );\n        }\n        ints.push_back(sumint); // add the sum-interval to ints\n        return;\n    }\n}\n\ndouble Fiber::tval(Point& p) const {\n    // fiber is  f = p1 + t * (p2-p1)\n    // t = (f-p1).dot(p2-p1) / (p2-p1).dot(p2-p1)\n    return  (p-p1).dot(p2-p1) / (p2-p1).dot(p2-p1);\n}\n\nPoint Fiber::point(double t) const {\n    Point p = p1 + t*(p2-p1);\n    return p;\n}\n\nvoid Fiber::printInts() const {\n    int n=0;\n    BOOST_FOREACH( Interval i, ints) {\n        std::cout << n << \": [ \" << i.lower << \" , \" << i.upper << \" ]\" << \"\\n\";\n        ++n;\n    }\n}\n\nstd::ostream& operator<<(std::ostream &stream, const Fiber& f) {\n  stream << \" fiber dir=\" << f.dir << \" and \" << f.ints.size() << \" intervals\\n\"; \n  stream << \" fiber.p1=\" << f.p1 << \" fiber.p2 \" << f.p2 ; \n  return stream;\n}\n\n\n} // end namespace\n// end file fiber.cpp\n", "meta": {"hexsha": "db1017148d6cebe1dee26c2ce4ee326f0398c8fe", "size": 3447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/algo/fiber.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/algo/fiber.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/algo/fiber.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": 28.4876033058, "max_line_length": 82, "alphanum_fraction": 0.5781839281, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.03789243056813771, "lm_q1q2_score": 0.018354338712054323}}
{"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. Identified multiple warnings.\n *      110207    D. Dirkx          Fixed warning problems by extending cerr comments.\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 *      Craidon, C.B. A Desription of the Langley Wireframe Geometry Standard (LaWGS) format, NASA\n *          TECHNICAL MEMORANDUM 85767.\n *\n *    Notes\n *\n */\n\n#include <boost/shared_ptr.hpp>\n\n#include \"Tudat/Mathematics/GeometricShapes/lawgsPartGeometry.h\"\n\nnamespace tudat\n{\nnamespace geometric_shapes\n{\n\n//! Constructor from surface geometry (i.e., geometry type conversion).\nvoid LawgsPartGeometry::setMesh( boost::shared_ptr< SingleSurfaceGeometry > originalSurface,\n                                 int numberOfLinesIn, int numberOfPointsIn )\n{\n    // Set (temporary name) of part.\n    name_ = \"copied surface\";\n\n    // Set size of mesh.\n    numberOfLines_ = numberOfLinesIn;\n    numberOfPoints_ = numberOfPointsIn;\n\n    // Allocate mesh points.\n    meshPoints_.resize( boost::extents[ numberOfLines_ ][ numberOfPoints_ ] );\n\n    // Set grid sizes from requested number of sample points.\n    double independentVariableGridSize1 =\n            ( originalSurface->getMaximumIndependentVariable( 1 ) -\n              originalSurface->getMinimumIndependentVariable( 1 ) ) /\n            ( static_cast< double >( numberOfLines_ - 1 ) );\n\n    double independentVariableGridSize2 =\n            ( originalSurface->getMaximumIndependentVariable( 2 ) -\n              originalSurface->getMinimumIndependentVariable( 2 ) ) /\n            ( static_cast< double >( numberOfPoints_ - 1 ) );\n\n    // Declare sample point variables.\n    double variable1, variable2;\n\n    // Declare and set minimum values of independent variables.\n    double minimumIndependentVariable1 = originalSurface->getMinimumIndependentVariable( 1 );\n    double minimumIndependentVariable2 = originalSurface->getMinimumIndependentVariable( 2 );\n\n    // Loop through the number of lines and points specified and sample\n    // geometry at fixed intervals.\n    for ( int i = 0; i < numberOfLines_; i++ )\n    {\n        for ( int j = 0; j < numberOfPoints_; j++ )\n        {\n            // Set sampling point of original geometry.\n            variable1 = minimumIndependentVariable1 + i * independentVariableGridSize1;\n            variable2 = minimumIndependentVariable2 + j * independentVariableGridSize2;\n\n            // Set new mesh point.\n            meshPoints_[ i ][ j ] = originalSurface->getSurfacePoint( variable1, variable2 );\n        }\n    }\n\n    // Perform panel calculations for mesh.\n    performPanelCalculations( );\n}\n\n//! Copy constructor.\nLawgsPartGeometry::LawgsPartGeometry( const LawgsPartGeometry& partToCopy )\n    : QuadrilateralMeshedSurfaceGeometry( )\n{\n    // Copy all properties of partToCopy to new part.\n    name_ = partToCopy.name_;\n    reversalOperator_ = partToCopy.reversalOperator_;\n    numberOfLines_ = partToCopy.numberOfLines_;\n    numberOfPoints_ = partToCopy.numberOfPoints_;\n    rotationMatrix_= partToCopy.rotationMatrix_;\n    scalingMatrix_ = partToCopy.scalingMatrix_;\n    offset_= partToCopy.offset_;\n\n    // Copy surface points array.\n    meshPoints_ = partToCopy.meshPoints_;\n}\n\n//! Get surface point.\nEigen::VectorXd LawgsPartGeometry::getSurfacePoint( const double independentVariable1,\n                                                    const double independentVariable2 )\n{\n    // Declare local variables denoting 'start' of panel.\n    int pointIndex, lineIndex;\n\n    // Declare local variable denoting surface point.\n    Eigen::VectorXd point = Eigen::VectorXd( 3 );\n\n    // Set local variables.\n    pointIndex = static_cast< int > ( floor( independentVariable2 ) );\n    lineIndex = static_cast< int > ( floor( independentVariable1 ) );\n\n    // Start with panel centroid.\n    point = panelCentroids_[ lineIndex ][ pointIndex ];\n\n    // Move back to panel corner.\n    point -= 0.5 *( meshPoints_[ lineIndex + 1 ][ pointIndex + 1 ] -\n                    meshPoints_[ lineIndex ][ pointIndex ]);\n\n    // Add contribution of 1st independent variable on panel.\n    point += ( independentVariable1 - lineIndex ) *\n             ( meshPoints_[ lineIndex + 1 ][ pointIndex ]\n               - meshPoints_[ lineIndex ][ pointIndex ] );\n\n    // Add contribution of 2nd independent variable on panel.\n    point += ( independentVariable2 - pointIndex ) *\n             ( meshPoints_[ lineIndex ][ pointIndex + 1 ] -\n               meshPoints_[ lineIndex ][ pointIndex ] );\n\n    return point;\n}\n\n//! Get surface derivative (currently not implemented).\nEigen::VectorXd LawgsPartGeometry::getSurfaceDerivative( const double u, const double v,\n                                                         const int uDerivative,\n                                                         const int vDerivative )\n{\n    std::cerr << \"Surface derivative function not implemented in \"\n              << \"LawgsPartGeometry class. Not able to return the \"\n              << uDerivative << \", \" << vDerivative << \"th derivative at point,\"\n              << u << \", \" << v << \". Returning zero vector.\" << std::endl;\n\n    return Eigen::Vector3d( 0.0, 0.0, 0.0 );\n}\n\n//! Get parameter.\ndouble LawgsPartGeometry::getParameter( const int parameterIndex )\n{\n    std::cerr << \"Get parameter function not implemented in LawgsPartGeometry\"\n              << \"class, unable to retrieve parameter \"<< parameterIndex\n              << \". Returning zero.\" << std::endl;\n\n    return 0.0;\n}\n\n//! Set parameter.\nvoid LawgsPartGeometry::setParameter( const int parameterIndex, const double value )\n{\n    std::cerr << \"Set parameter function not implemented in LawgsPartGeometry\"\n              << \"class. Unable to set value of \" << value << \" at parameter index \"\n              << parameterIndex << std::endl;\n}\n\n//! Overload ostream to print class information.\nstd::ostream& operator<<( std::ostream& stream, LawgsPartGeometry& lawgsPartGeometry )\n{\n    stream << \"This is a Langley Wireframe Geometry Standard surface geometry\"\n           << \" of a single part.\" << std::endl;\n    stream << \"The number of lines ( contours ) is: \"\n           << lawgsPartGeometry.numberOfLines_ << std::endl;\n    stream << \"The number of points per line is: \"\n           << lawgsPartGeometry.numberOfPoints_ << std::endl;\n    stream << \"The part name is: \" << lawgsPartGeometry.name_ << std::endl;\n\n    // Return stream.\n    return stream;\n}\n\n} // namespace geometric_shapes\n} // namespace tudat\n", "meta": {"hexsha": "21c9c16aa649ab3b4afd9deb3d01c4bb2d4a8d44", "size": 8589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/GeometricShapes/lawgsPartGeometry.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/lawgsPartGeometry.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/lawgsPartGeometry.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": 42.5198019802, "max_line_length": 99, "alphanum_fraction": 0.6620095471, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.03789242337013432, "lm_q1q2_score": 0.018354335225484835}}
{"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#include <limits>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cstring>\n#include <sstream>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#include \"galois/Galois.h\"\n#include \"galois/Atomic.h\"\n#include \"galois/CilkInit.h\"\n#include \"galois/Timer.h\"\n#include \"galois/runtime/DoAllCoupled.h\"\n#include \"galois/runtime/Profile.h\"\n#include \"galois/substrate/CompilerSpecific.h\"\n\n#include \"llvm/Support/CommandLine.h\"\n#include \"Lonestar/BoilerPlate.h\"\n\n#include \"Config.h\"\n#include \"Point.h\"\n#include \"Octree.h\"\n#include \"BoundingBox.h\"\n#include \"TreeBuildSumm.h\"\n#include \"ForceComputation.h\"\n\nnamespace bh {\nconst char* name = \"Barnshut N-Body Simulator\";\nconst char* desc =\n    \"Simulates the gravitational forces in a galactic cluster using the \"\n    \"Barnes-Hut n-body algorithm\";\nconst char* url = \"barneshut\";\n\nnamespace cll = llvm::cl;\n\nstatic cll::opt<int> nbodies(\"n\", cll::desc(\"Number of bodies\"),\n                             cll::init(10000));\nstatic cll::opt<int> ntimesteps(\"steps\", cll::desc(\"Number of steps\"),\n                                cll::init(1));\nstatic cll::opt<int> seed(\"seed\", cll::desc(\"Random seed\"), cll::init(7));\n\nenum TreeSummMethod {\n  SERIAL,\n  SERIAL_TREE,\n  GALOIS_TREE,\n  CILK_TREE,\n  KDG_HAND,\n  LEVEL_EXEC,\n  SPEC,\n  TWO_PHASE,\n  DATA_DAG,\n  RSUMM_SERIAL,\n  RSUMM_CILK,\n  RSUMM_GALOIS,\n};\n\ncll::opt<TreeSummMethod> treeSummOpt(\n    cll::desc(\"Tree Summarization Method:\"),\n    cll::values(\n        clEnumVal(SERIAL, \"Serial recursive\"),\n        clEnumVal(SERIAL_TREE, \"using data dependence DAG version of KDG\"),\n        clEnumVal(GALOIS_TREE, \"using data dependence DAG version of KDG\"),\n        clEnumVal(CILK_TREE, \"using cilk executor\"),\n        clEnumVal(KDG_HAND, \"KDG based hand-implemented\"),\n        clEnumVal(LEVEL_EXEC, \"using level-by-level executor\"),\n        clEnumVal(SPEC, \"using speculative ordered executor\"),\n        clEnumVal(TWO_PHASE, \"using two phase window ordered executor\"),\n        clEnumVal(DATA_DAG, \"Generate DAG using data dependences\"),\n        clEnumVal(RSUMM_SERIAL, \"Build Lock Free, Summarize Recursive Serial\"),\n        clEnumVal(RSUMM_CILK, \"Build Lock Free, Summarize Recursive Cilk\"),\n        clEnumVal(RSUMM_GALOIS, \"Build Lock Free, Summarize Recursive Galois\"),\n        clEnumValEnd),\n    cll::init(SERIAL));\n\ndouble nextDouble() { return rand() / (double)RAND_MAX; }\n\n/**\n * Generates random input according to the Plummer model, which is more\n * realistic but perhaps not so much so according to astrophysicists\n */\ntemplate <typename BodyCont>\nvoid generateInput(BodyCont& bodies, int nbodies, int seed) {\n  typedef\n      typename std::remove_pointer<typename BodyCont::value_type>::type Body_ty;\n\n  double v, sq, scale;\n  Point p;\n  double PI = boost::math::constants::pi<double>();\n\n  srand(seed);\n\n  double rsc = (3 * PI) / 16;\n  double vsc = sqrt(1.0 / rsc);\n\n  for (int body = 0; body < nbodies; body++) {\n    double r = 1.0 / sqrt(pow(nextDouble() * 0.999, -2.0 / 3.0) - 1);\n    do {\n      for (int i = 0; i < 3; i++)\n        p[i] = nextDouble() * 2.0 - 1.0;\n      sq = p.x * p.x + p.y * p.y + p.z * p.z;\n    } while (sq > 1.0);\n    scale = rsc * r / sqrt(sq);\n\n    Body_ty* b = new Body_ty();\n    b->mass    = 1.0 / nbodies;\n    for (int i = 0; i < 3; i++)\n      b->pos[i] = p[i] * scale;\n\n    do {\n      p.x = nextDouble();\n      p.y = nextDouble() * 0.1;\n    } while (p.y > p.x * p.x * pow(1 - p.x * p.x, 3.5));\n    v = p.x * sqrt(2.0 / sqrt(1 + r * r));\n    do {\n      for (int i = 0; i < 3; i++)\n        p[i] = nextDouble() * 2.0 - 1.0;\n      sq = p.x * p.x + p.y * p.y + p.z * p.z;\n    } while (sq > 1.0);\n    scale = vsc * v / sqrt(sq);\n    for (int i = 0; i < 3; i++)\n      b->vel[i] = p[i] * scale;\n\n    bodies.push_back(b);\n  }\n}\n\ntemplate <bool IsOn>\nstruct ToggleTime : public galois::StatTimer {\n  ToggleTime(const char* name) : galois::StatTimer(name) {}\n};\n\ntemplate <>\nstruct ToggleTime<false> {\n  ToggleTime(const char* name) {}\n  void start() {}\n  void stop() {}\n};\n\ntemplate <bool TrackTime, typename TB>\nPoint run(int nbodies, int ntimesteps, int seed, const TB& treeBuilder) {\n  typedef typename TB::Base_ty B;\n  typedef galois::gdeque<Body<B>*> Bodies;\n  typedef galois::FixedSizeAllocator<OctreeInternal<B>> TreeAlloc;\n\n  Config config;\n  Bodies bodies;\n  TreeAlloc treeAlloc;\n\n  ToggleTime<TrackTime> t_input_gen(\"Time taken by input generation: \");\n\n  t_input_gen.start();\n  generateInput(bodies, nbodies, seed);\n  t_input_gen.stop();\n\n  Point ret;\n  for (int step = 0; step < ntimesteps; step++) {\n    typedef galois::worklists::PerSocketChunkLIFO<256> WL;\n\n    ReducibleBox bbox;\n    ToggleTime<TrackTime> t_bbox(\"Time taken by Bounding Box computation: \");\n\n    // TODO: use parallel reducer here\n    struct GetPos {\n      typedef const Point& result_type;\n\n      result_type operator()(const Body<B>* b) const { return b->pos; }\n    };\n    auto beg = boost::make_transform_iterator(bodies.begin(), GetPos());\n    auto end = boost::make_transform_iterator(bodies.end(), GetPos());\n\n    t_bbox.start();\n    galois::do_all(beg, end, ReduceBoxes(bbox), galois::steal());\n    t_bbox.stop();\n\n    BoundingBox box(bbox.reduce());\n\n    // OctreeInternal<B>* top = new OctreeInternal<B>(box);\n    ToggleTime<TrackTime> t_tree_build(\n        \"Time taken by Octree building and summarization: \");\n\n    t_tree_build.start();\n    OctreeInternal<B>* top =\n        treeBuilder(box, bodies.begin(), bodies.end(), treeAlloc);\n    t_tree_build.stop();\n\n    if (!skipVerify) {\n      std::cout << \"WARNING: Comparing against serially built & summarized \"\n                   \"tree..., timing may be off\"\n                << std::endl;\n      BuildSummarizeSeparate<BuildTreeSerial, SummarizeTreeSerial<B>>\n          serialBuilder;\n      OctreeInternal<B>* stop =\n          serialBuilder(box, bodies.begin(), bodies.end(), treeAlloc);\n\n      compareTrees(stop, top);\n    }\n\n    // BuildOctreeSerial<B> build;\n    //\n    // OctreeInternal<B>* top = build (box, bodies.begin (), bodies.end ());\n    //\n    // // galois::for_each(bodies.begin(), bodies.end(),\n    // // BuildOctree<B>(top, box.radius()), galois::wl<WL> ());\n    //\n    // // reset the number of threads\n    // galois::setActiveThreads(numThreads);\n    //\n    // ToggleTime<TrackTime> t_tree_summ (\"Time taken by Tree Summarization: \");\n    //\n    // t_tree_summ.start ();\n    // summMethod (top, bodies.begin (), bodies.end ());\n    // t_tree_summ.stop ();\n\n    if (false) { // disabling remaining phases\n      ToggleTime<TrackTime> T_parallel(\"ParallelTime\");\n      T_parallel.start();\n\n      galois::for_each(bodies.begin(), bodies.end(),\n                       ComputeForces<B>(config, top, box.diameter()),\n                       galois::wl<WL>());\n      galois::for_each(bodies.begin(), bodies.end(), AdvanceBodies<B>(config),\n                       galois::wl<WL>());\n      T_parallel.stop();\n    }\n\n    ret = top->pos;\n\n    std::cout << \"Timestep \" << step << \", Root's Center of Mass = \" << top->pos\n              << std::endl;\n\n    // TODO: delete using TreeAlloc\n    // delete top;\n    destroyTree(top, treeAlloc);\n\n    for (auto i = bodies.begin(), endi = bodies.end(); i != endi; ++i) {\n      delete *i;\n      *i = nullptr;\n    }\n  }\n\n  return ret;\n}\n\n} // end namespace bh\n\nint main(int argc, char** argv) {\n  galois::StatManager sm;\n  LonestarStart(argc, argv, bh::name, bh::desc, bh::url);\n\n  std::cout.setf(std::ios::right | std::ios::scientific | std::ios::showpoint);\n\n  std::cout << \"configuration: \" << bh::nbodies << \" bodies, \" << bh::ntimesteps\n            << \" time steps\" << std::endl\n            << std::endl;\n  std::cout << \"Num. of threads: \" << numThreads << std::endl;\n\n  bh::Point pos;\n  galois::StatTimer T(\"total time:\");\n\n  T.start();\n  switch (bh::treeSummOpt) {\n  case bh::SERIAL:\n    // TODO: fix template argument mistmatch between build and summarize\n    pos =\n        bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                      bh::BuildSummarizeSeparate<bh::BuildTreeSerial,\n                                                 bh::SummarizeTreeSerial<>>());\n    break;\n\n  case bh::SERIAL_TREE:\n    pos =\n        bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                      bh::BuildSummarizeRecursive<bh::recursive::USE_SERIAL>());\n    break;\n\n  case bh::GALOIS_TREE:\n    pos =\n        bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                      bh::BuildSummarizeRecursive<bh::recursive::USE_GALOIS>());\n    break;\n\n  case bh::CILK_TREE:\n    // FIXME:      galois::CilkInit ();\n    pos = bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                        bh::BuildSummarizeRecursive<bh::recursive::USE_CILK>());\n    break;\n\n  case bh::LEVEL_EXEC:\n    pos =\n        bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                      bh::BuildSummarizeSeparate<bh::BuildTreeLockFree,\n                                                 bh::TreeSummarizeLevelExec>());\n    break;\n\n  case bh::KDG_HAND:\n    pos = bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                        bh::BuildSummarizeSeparate<bh::BuildTreeLockFree,\n                                                   bh::TreeSummarizeKDGhand>());\n    break;\n\n  case bh::SPEC:\n    pos = bh::run<true>(\n        bh::nbodies, bh::ntimesteps, bh::seed,\n        bh::BuildSummarizeSeparate<bh::BuildTreeLockFree,\n                                   bh::TreeSummarizeSpeculative>());\n    break;\n\n  case bh::TWO_PHASE:\n    pos =\n        bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                      bh::BuildSummarizeSeparate<bh::BuildTreeLockFree,\n                                                 bh::TreeSummarizeTwoPhase>());\n    break;\n\n  case bh::DATA_DAG:\n    pos = bh::run<true>(bh::nbodies, bh::ntimesteps, bh::seed,\n                        bh::BuildSummarizeSeparate<bh::BuildTreeLockFree,\n                                                   bh::TreeSummarizeDataDAG>());\n    break;\n\n  case bh::RSUMM_SERIAL:\n    pos = bh::run<true>(\n        bh::nbodies, bh::ntimesteps, bh::seed,\n        bh::BuildLockFreeSummarizeRecursive<bh::recursive::USE_SERIAL>());\n    break;\n\n  case bh::RSUMM_CILK:\n    // FIXME:      galois::CilkInit ();\n    pos = bh::run<true>(\n        bh::nbodies, bh::ntimesteps, bh::seed,\n        bh::BuildLockFreeSummarizeRecursive<bh::recursive::USE_CILK>());\n    break;\n\n  case bh::RSUMM_GALOIS:\n    pos = bh::run<true>(\n        bh::nbodies, bh::ntimesteps, bh::seed,\n        bh::BuildLockFreeSummarizeRecursive<bh::recursive::USE_GALOIS>());\n    break;\n\n  default:\n    abort();\n  }\n  T.stop();\n\n  // if (!skipVerify) {\n  // std::cout << \"Running serial tree summarization for verification\" <<\n  // std::endl; bh::Point serPos = bh::run<false> (bh::nbodies, bh::ntimesteps,\n  // bh::seed, bh::SummarizeTreeSerial ());\n  //\n  // double EPS = 1e-9;\n  // bool equal = true;\n  // for (unsigned i = 0; i < 3; ++i) {\n  // if (fabs (pos[i] - serPos[i]) > EPS) {\n  // equal = false;\n  // break;\n  // }\n  // }\n  //\n  // if (!equal) {\n  // std::cerr << \"!!!BAD: Results don't match with serial!!!\" << std::endl;\n  // abort ();\n  //\n  // } else {\n  // std::cout << \">>> OK, results verified\" << std::endl;\n  // }\n  //\n  // }\n}\n", "meta": {"hexsha": "5003c60bde0930fd2b5347ddd166165812651073", "size": 12378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/ordered/bh_odg/BarneshutODG.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/bh_odg/BarneshutODG.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/bh_odg/BarneshutODG.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": 31.7384615385, "max_line_length": 80, "alphanum_fraction": 0.6103570852, "num_tokens": 3440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.04336579799118459, "lm_q1q2_score": 0.018322251274368935}}
{"text": "﻿#include <Eigen/StdVector>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Jacobi>\n#include <Eigen/SVD>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <iostream>\n#include <map>\n#include <vector>\n#include <functional>\n#include <type_traits>\n\n#ifndef EIGEN_HELPERS_HPP\n#define EIGEN_HELPERS_HPP\n\nnamespace std\n{\n    // http://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x\n    template <class T>\n    inline void hash_combine(std::size_t& seed, const T& v)\n    {\n        std::hash<T> hasher;\n        seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n    }\n\n    template <typename T>\n    struct hash<std::complex<T>>\n    {\n        std::size_t operator()(const std::complex<T>& val) const\n        {\n            return (std::hash<T>()(val.real()) ^ ((std::hash<T>()(val.imag()) << 1) >> 1));\n        }\n    };\n\n    template <>\n    struct hash<Eigen::Vector3d>\n    {\n        std::size_t operator()(const Eigen::Vector3d& vector) const\n        {\n            return (std::hash<double>()(vector.x()) ^ ((std::hash<double>()(vector.y()) << 1) >> 1) ^ (std::hash<double>()(vector.z()) << 1));\n        }\n    };\n\n    // Hash function for Eigen vector.\n    // Based on here: https://wjngkoh.wordpress.com/2015/03/04/c-hash-function-for-eigen-matrix-and-vector/\n    template<typename _Scalar, int _Rows>\n    struct hash<Eigen::Matrix<_Scalar, _Rows, 1>>\n    {\n        std::size_t operator() (const Eigen::Matrix<_Scalar, _Rows, 1>& vector) const\n        {\n            std::size_t hash = 0;\n            for (ssize_t idx = 0; idx < vector.size(); idx++)\n            {\n                std::hash_combine(hash, vector(idx));\n            }\n            return hash;\n        }\n    };\n\n    template <typename T1, typename T2>\n    struct hash<std::pair<T1, T2>>\n    {\n        std::size_t operator()(const std::pair<T1, T2>& val) const\n        {\n            std::size_t seed = 0;\n            std::hash_combine(seed, val.first);\n            std::hash_combine(seed, val.second);\n            return seed;\n        }\n    };\n\n}\n\nnamespace EigenHelpers\n{\n    ////////////////////////////////////////////////////////////////////////////\n    // Typedefs for aligned STL containers using Eigen types\n    ////////////////////////////////////////////////////////////////////////////\n\n    typedef std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VectorVector2d;\n    typedef std::vector<Eigen::Vector3f, Eigen::aligned_allocator<Eigen::Vector3f>> VectorVector3f;\n    typedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VectorVector3d;\n    typedef std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f>> VectorVector4f;\n    typedef std::vector<Eigen::Vector4d, Eigen::aligned_allocator<Eigen::Vector4d>> VectorVector4d;\n    typedef std::vector<Eigen::Quaternionf, Eigen::aligned_allocator<Eigen::Quaternionf>> VectorQuaternionf;\n    typedef std::vector<Eigen::Quaterniond, Eigen::aligned_allocator<Eigen::Quaterniond>> VectorQuaterniond;\n    typedef std::vector<Eigen::Isometry3f, Eigen::aligned_allocator<Eigen::Isometry3f>> VectorIsometry3f;\n    typedef std::vector<Eigen::Isometry3d, Eigen::aligned_allocator<Eigen::Isometry3d>> VectorIsometry3d;\n    typedef std::map<std::string, Eigen::Vector3f, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector3f>>> MapStringVector3f;\n    typedef std::map<std::string, Eigen::Vector3d, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector3d>>> MapStringVector3d;\n    typedef std::map<std::string, Eigen::Vector4f, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector4f>>> MapStringVector4f;\n    typedef std::map<std::string, Eigen::Vector4d, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector4d>>> MapStringVector4d;\n    typedef std::map<std::string, Eigen::Quaternionf, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Quaternionf>>> MapStringQuaternionf;\n    typedef std::map<std::string, Eigen::Quaterniond, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Quaterniond>>> MapStringQuaterniond;\n    typedef std::map<std::string, Eigen::Isometry3f, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Isometry3f>>> MapStringIsometry3f;\n    typedef std::map<std::string, Eigen::Isometry3d, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Isometry3d>>> MapStringIsometry3d;\n\n    inline bool Equal(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n    {\n        if ((v1.x() == v2.x()) && (v1.y() == v2.y()) && (v1.z() == v2.z()))\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n    inline bool CloseEnough(const double p1, const double p2, const double threshold)\n    {\n        const double real_threshold = std::abs(threshold);\n        const double abs_delta = std::abs(p2 - p1);\n        if (abs_delta <= real_threshold)\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n    inline bool CloseEnough(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const double threshold)\n    {\n        double real_threshold = std::fabs(threshold);\n        if (std::fabs(v1.x() - v2.x()) > real_threshold)\n        {\n            return false;\n        }\n        if (std::fabs(v1.y() - v2.y()) > real_threshold)\n        {\n            return false;\n        }\n        if (std::fabs(v1.z() - v2.z()) > real_threshold)\n        {\n            return false;\n        }\n        return true;\n    }\n\n    template <typename EigenType, typename Allocator=Eigen::aligned_allocator<EigenType>>\n    inline bool CloseEnough(const std::vector<EigenType, Allocator>& a, const std::vector<EigenType, Allocator>& b, const double threshold)\n    {\n        if (a.size() != b.size())\n        {\n            return false;\n        }\n        for (size_t idx = 0; idx < a.size(); idx++)\n        {\n            if (!CloseEnough(a[idx], b[idx], threshold))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    // Inspired by Eigen's \"isApprox\" function\n    inline bool IsApprox(const double p1, const double p2, const double precision)\n    {\n        const double smallest_element = std::min(std::abs(p1), std::abs(p2));\n        const double threshold = precision * smallest_element;\n        return CloseEnough(p1, p2, threshold);\n    }\n\n    template <typename EigenType, typename Allocator=Eigen::aligned_allocator<EigenType>>\n    inline bool IsApprox(const std::vector<EigenType, Allocator>& a, const std::vector<EigenType, Allocator>& b,\n                         const typename EigenType::Scalar& precision = Eigen::NumTraits<typename EigenType::Scalar>::dummy_precision())\n    {\n        if (a.size() != b.size())\n        {\n            return false;\n        }\n        for (size_t idx = 0; idx < a.size(); idx++)\n        {\n            if (!a[idx].isApprox(b[idx], precision))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    template <typename Derived>\n    inline Eigen::MatrixXd ClampNorm(const Eigen::MatrixBase<Derived>& item_to_clamp, const double max_norm)\n    {\n        assert(max_norm >= 0 && \"You must pass a maximum norm that is positive\");\n        const double current_norm = item_to_clamp.norm();\n        if (current_norm > max_norm)\n        {\n            return item_to_clamp * (max_norm / current_norm);\n        }\n        return item_to_clamp;\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Kinematics functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    inline Eigen::Vector3d RotateVector(const Eigen::Quaterniond& quat, const Eigen::Vector3d& vec)\n    {\n        const Eigen::Quaterniond temp(0.0, vec.x(), vec.y(), vec.z());\n        const Eigen::Quaterniond res = quat * (temp * quat.inverse());\n        return Eigen::Vector3d(res.x(), res.y(), res.z());\n    }\n\n    inline Eigen::Vector3d RotateVectorReverse(const Eigen::Quaterniond& quat, const Eigen::Vector3d& vec)\n    {\n        const Eigen::Quaterniond temp(0.0, vec.x(), vec.y(), vec.z());\n        const Eigen::Quaterniond res = quat.inverse() * (temp * quat);\n        return Eigen::Vector3d(res.x(), res.y(), res.z());\n    }\n\n    inline double EnforceContinuousRevoluteBounds(const double value)\n    {\n        if ((value <= -M_PI) || (value > M_PI))\n        {\n            const double remainder = fmod(value, 2.0 * M_PI);\n            if (remainder <= -M_PI)\n            {\n                return (remainder + (2.0 * M_PI));\n            }\n            else if (remainder > M_PI)\n            {\n                return (remainder - (2.0 * M_PI));\n            }\n            else\n            {\n                return remainder;\n            }\n        }\n        else\n        {\n            return value;\n        }\n    }\n\n    inline Eigen::VectorXd SafeNormal(const Eigen::VectorXd& vec)\n    {\n        const double norm = vec.norm();\n        if (norm > std::numeric_limits<double>::epsilon())\n        {\n            return vec / norm;\n        }\n        else\n        {\n            return vec;\n        }\n    }\n\n    inline double SquaredNorm(const std::vector<double>& vec)\n    {\n        double squared_norm = 0.0;\n        for (size_t idx = 0; idx < vec.size(); idx++)\n        {\n            const double element = vec[idx];\n            squared_norm += (element * element);\n        }\n        return squared_norm;\n    }\n\n    inline double Norm(const std::vector<double>& vec)\n    {\n        return std::sqrt(SquaredNorm(vec));\n    }\n\n    inline std::vector<double> Abs(const std::vector<double>& vec)\n    {\n        std::vector<double> absed(vec.size(), 0.0);\n        for (size_t idx = 0; idx < absed.size(); idx++)\n        {\n            absed[idx] = std::abs(vec[idx]);\n        }\n        return absed;\n    }\n\n    inline std::vector<double> Multiply(const std::vector<double>& vec, const double scalar)\n    {\n        std::vector<double> multiplied(vec.size(), 0.0);\n        for (size_t idx = 0; idx < multiplied.size(); idx++)\n        {\n            const double element = vec[idx];\n            multiplied[idx] = element * scalar;\n        }\n        return multiplied;\n    }\n\n    inline std::vector<double> Multiply(const std::vector<double>& vec1, const std::vector<double>& vec2)\n    {\n        if (vec1.size() == vec2.size())\n        {\n            std::vector<double> multiplied(vec1.size(), 0.0);\n            for (size_t idx = 0; idx < multiplied.size(); idx++)\n            {\n                const double element1 = vec1[idx];\n                const double element2 = vec2[idx];\n                multiplied[idx] = element1 * element2;\n            }\n            return multiplied;\n        }\n        else\n        {\n            return std::vector<double>();\n        }\n    }\n\n    inline std::vector<double> Divide(const std::vector<double>& vec, const double scalar)\n    {\n        const double inv_scalar = 1.0 / scalar;\n        return Multiply(vec, inv_scalar);\n    }\n\n    inline std::vector<double> Divide(const std::vector<double>& vec1, const std::vector<double>& vec2)\n    {\n        if (vec1.size() == vec2.size())\n        {\n            std::vector<double> divided(vec1.size(), 0.0);\n            for (size_t idx = 0; idx < divided.size(); idx++)\n            {\n                const double element1 = vec1[idx];\n                const double element2 = vec2[idx];\n                divided[idx] = element1 / element2;\n            }\n            return divided;\n        }\n        else\n        {\n            return std::vector<double>();\n        }\n    }\n\n    inline std::vector<double> Add(const std::vector<double>& vec, const double scalar)\n    {\n        std::vector<double> added(vec.size(), 0.0);\n        for (size_t idx = 0; idx < added.size(); idx++)\n        {\n            added[idx] = vec[idx] + scalar;\n        }\n        return added;\n    }\n\n    inline std::vector<double> Add(const std::vector<double>& vec1, const std::vector<double>& vec2)\n    {\n        if (vec1.size() == vec2.size())\n        {\n            std::vector<double> added(vec1.size(), 0.0);\n            for (size_t idx = 0; idx < added.size(); idx++)\n            {\n                const double element1 = vec1[idx];\n                const double element2 = vec2[idx];\n                added[idx] = element1 + element2;\n            }\n            return added;\n        }\n        else\n        {\n            return std::vector<double>();\n        }\n    }\n\n    inline std::vector<double> Sub(const std::vector<double>& vec, const double scalar)\n    {\n        std::vector<double> subed(vec.size(), 0.0);\n        for (size_t idx = 0; idx < subed.size(); idx++)\n        {\n            subed[idx] = vec[idx] - scalar;\n        }\n        return subed;\n    }\n\n    inline std::vector<double> Sub(const std::vector<double>& vec1, const std::vector<double>& vec2)\n    {\n        if (vec1.size() == vec2.size())\n        {\n            std::vector<double> subed(vec1.size(), 0.0);\n            for (size_t idx = 0; idx < subed.size(); idx++)\n            {\n                const double element1 = vec1[idx];\n                const double element2 = vec2[idx];\n                subed[idx] = element1 - element2;\n            }\n            return subed;\n        }\n        else\n        {\n            return std::vector<double>();\n        }\n    }\n\n    inline Eigen::Matrix3d Skew(const Eigen::Vector3d& vector)\n    {\n        Eigen::Matrix3d skewed;\n        skewed << 0.0, -vector.z(), vector.y(),\n                  vector.z(), 0.0, -vector.x(),\n                  -vector.y(), vector.x(), 0.0;\n        return skewed;\n    }\n\n    inline Eigen::Vector3d Unskew(const Eigen::Matrix3d& matrix)\n    {\n        const Eigen::Matrix3d matrix_symetric = (matrix - matrix.transpose()) / 2.0;\n        const Eigen::Vector3d unskewed(matrix_symetric(2, 1), matrix_symetric(0, 2), matrix_symetric(1, 0));\n        return unskewed;\n    }\n\n    inline Eigen::Matrix4d TwistHat(const Eigen::Matrix<double, 6, 1>& twist)\n    {\n        const Eigen::Vector3d trans_velocity = twist.segment<3>(0);\n        const Eigen::Matrix3d hatted_rot_velocity = Skew(twist.segment<3>(3));\n        Eigen::Matrix4d hatted_twist = Eigen::Matrix4d::Zero();\n        hatted_twist.block<3, 3>(0, 0) = hatted_rot_velocity;\n        hatted_twist.block<3, 1>(0, 3) = trans_velocity;\n        return hatted_twist;\n    }\n\n    inline Eigen::Matrix<double, 6, 1> TwistUnhat(const Eigen::Matrix4d& hatted_twist)\n    {\n         const Eigen::Vector3d trans_velocity = hatted_twist.block<3, 1>(0, 3);\n         const Eigen::Vector3d rot_velocity = Unskew(hatted_twist.block<3, 3>(0, 0));\n         Eigen::Matrix<double, 6, 1> twist;\n         twist.segment<3>(0) = trans_velocity;\n         twist.segment<3>(3) = rot_velocity;\n         return twist;\n    }\n\n    inline Eigen::Matrix<double, 6, 6> AdjointFromTransform(const Eigen::Isometry3d& transform)\n    {\n        const Eigen::Matrix3d rotation = transform.matrix().block<3, 3>(0, 0);\n        const Eigen::Vector3d translation = transform.matrix().block<3, 1>(0, 3);\n        const Eigen::Matrix3d translation_hat = Skew(translation);\n        // Assemble the adjoint matrix\n        Eigen::Matrix<double, 6, 6> adjoint;\n        adjoint.block<3, 3>(0, 0) = rotation;\n        adjoint.block<3, 3>(0, 3) = translation_hat * rotation;\n        adjoint.block<3, 3>(3, 0) = Eigen::Matrix3d::Zero();\n        adjoint.block<3, 3>(3, 3) = rotation;\n        return adjoint;\n    }\n\n    inline Eigen::Matrix<double, 6, 1> TransformTwist(const Eigen::Isometry3d& transform, const Eigen::Matrix<double, 6, 1>& initial_twist)\n    {\n        return (Eigen::Matrix<double, 6, 1>)(EigenHelpers::AdjointFromTransform(transform) * initial_twist);\n    }\n\n    inline Eigen::Matrix<double, 6, 1> TwistBetweenTransforms(const Eigen::Isometry3d& start, const Eigen::Isometry3d& end)\n    {\n        const Eigen::Isometry3d t_diff = start.inverse() * end;\n        return TwistUnhat(t_diff.matrix().log());\n    }\n\n    inline Eigen::Matrix3d ExpMatrixExact(const Eigen::Matrix3d& hatted_rot_velocity, const double delta_t)\n    {\n        assert(std::fabs(Unskew(hatted_rot_velocity).norm() - 1.0) < 1e-10);\n        const Eigen::Matrix3d exp_matrix = Eigen::Matrix3d::Identity() + (hatted_rot_velocity * sin(delta_t)) + (hatted_rot_velocity * hatted_rot_velocity * (1.0 - cos(delta_t)));\n        return exp_matrix;\n    }\n\n    inline Eigen::Isometry3d ExpTwist(const Eigen::Matrix<double, 6, 1>& twist, const double delta_t)\n    {\n        const Eigen::Vector3d trans_velocity = twist.segment<3>(0);\n        const Eigen::Vector3d rot_velocity = twist.segment<3>(3);\n        const double trans_velocity_norm = trans_velocity.norm();\n        const double rot_velocity_norm = rot_velocity.norm();\n        Eigen::Matrix4d raw_transform = Eigen::Matrix4d::Identity();\n        if (rot_velocity_norm >= 1e-100)\n        {\n            const double scaled_delta_t = delta_t * rot_velocity_norm;\n            const Eigen::Vector3d scaled_trans_velocity = trans_velocity / rot_velocity_norm;\n            const Eigen::Vector3d scaled_rot_velocity = rot_velocity / rot_velocity_norm;\n            const Eigen::Matrix3d rotation_displacement = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n            const Eigen::Vector3d translation_displacement = ((Eigen::Matrix3d::Identity() - rotation_displacement) * scaled_rot_velocity.cross(scaled_trans_velocity)) + (scaled_rot_velocity * scaled_rot_velocity.transpose() * scaled_trans_velocity * scaled_delta_t);\n            raw_transform.block<3, 3>(0, 0) = rotation_displacement;\n            raw_transform.block<3, 1>(0, 3) = translation_displacement;\n        }\n        else\n        {\n            if ((trans_velocity_norm >= 1e-100) || (rot_velocity_norm == 0.0))\n            {\n                raw_transform.block<3, 1>(0, 3) = trans_velocity * delta_t;\n            }\n            else\n            {\n                std::cerr << \"*** WARNING - YOU MAY ENCOUNTER NUMERICAL INSTABILITY IN EXPTWIST(...) WITH TRANS & ROT VELOCITY NORM < 1e-100 ***\" << std::endl;\n                const double scaled_delta_t = delta_t * rot_velocity_norm;\n                const Eigen::Vector3d scaled_trans_velocity = trans_velocity / rot_velocity_norm;\n                const Eigen::Vector3d scaled_rot_velocity = rot_velocity / rot_velocity_norm;\n                const Eigen::Matrix3d rotation_displacement = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n                const Eigen::Vector3d translation_displacement = ((Eigen::Matrix3d::Identity() - rotation_displacement) * scaled_rot_velocity.cross(scaled_trans_velocity)) + (scaled_rot_velocity * scaled_rot_velocity.transpose() * scaled_trans_velocity * scaled_delta_t);\n                raw_transform.block<3, 3>(0, 0) = rotation_displacement;\n                raw_transform.block<3, 1>(0, 3) = translation_displacement;\n            }\n        }\n        Eigen::Isometry3d transform;\n        transform = raw_transform;\n        return transform;\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Interpolation functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    inline double Interpolate(const double p1, const double p2, const double ratio)\n    {\n        // Safety check ratio\n        double real_ratio = ratio;\n        if (real_ratio < 0.0)\n        {\n            real_ratio = 0.0;\n            std::cerr << \"Interpolation ratio < 0.0, set to 0.0\" << std::endl;\n        }\n        else if (real_ratio > 1.0)\n        {\n            real_ratio = 1.0;\n            std::cerr << \"Interpolation ratio > 1.0, set to 1.0\" << std::endl;\n        }\n        // Interpolate\n        // This is the numerically stable version, rather than  (p1 + (p2 - p1) * real_ratio)\n        return ((p1 * (1.0 - real_ratio)) + (p2 * real_ratio));\n    }\n\n    inline double InterpolateContinuousRevolute(const double p1, const double p2, const double ratio)\n    {\n        // Safety check ratio\n        double real_ratio = ratio;\n        if (real_ratio < 0.0)\n        {\n            real_ratio = 0.0;\n            std::cerr << \"Interpolation ratio < 0.0, set to 0.0\" << std::endl;\n        }\n        else if (real_ratio > 1.0)\n        {\n            real_ratio = 1.0;\n            std::cerr << \"Interpolation ratio > 1.0, set to 1.0\" << std::endl;\n        }\n        // Safety check args\n        const double real_p1 = EnforceContinuousRevoluteBounds(p1);\n        const double real_p2 = EnforceContinuousRevoluteBounds(p2);\n        // Interpolate\n        double interpolated = 0.0;\n        double diff = real_p2 - real_p1;\n        if (std::fabs(diff) <= M_PI)\n        {\n            interpolated = real_p1 + diff * real_ratio;\n        }\n        else\n        {\n            if (diff > 0.0)\n            {\n                diff = 2.0 * M_PI - diff;\n            }\n            else\n            {\n                diff = -2.0 * M_PI - diff;\n            }\n            interpolated = real_p1 - diff * real_ratio;\n            // Input states are within bounds, so the following check is sufficient\n            if (interpolated > M_PI)\n            {\n                interpolated -= 2.0 * M_PI;\n            }\n            else\n            {\n                if (interpolated < -M_PI)\n                {\n                    interpolated += 2.0 * M_PI;\n                }\n            }\n        }\n        return interpolated;\n    }\n\n    inline std::vector<double> Interpolate(const std::vector<double>& v1, const std::vector<double>& v2, const double ratio)\n    {\n        // Safety check ratio\n        double real_ratio = ratio;\n        if (real_ratio < 0.0)\n        {\n            real_ratio = 0.0;\n            std::cerr << \"Interpolation ratio < 0.0, set to 0.0\" << std::endl;\n        }\n        else if (real_ratio > 1.0)\n        {\n            real_ratio = 1.0;\n            std::cerr << \"Interpolation ratio > 1.0, set to 1.0\" << std::endl;\n        }\n        // Safety check inputs\n        const size_t len = v1.size();\n        if (len != v2.size())\n        {\n            std::cerr << \"Vectors to interpolate are different sizes (\" << v1.size() << \" versus \" << v2.size() << \")\" << std::endl;\n            return std::vector<double>();\n        }\n        // Interpolate\n        // This is the numerically stable version, rather than  (p1 + (p2 - p1) * real_ratio)\n        std::vector<double> interped(len, 0);\n        for (size_t idx = 0; idx < len; idx++)\n        {\n            interped[idx] = ((v1[idx] * (1.0 - real_ratio)) + (v2[idx] * real_ratio));\n        }\n        return interped;\n    }\n\n    inline Eigen::Quaterniond Interpolate(const Eigen::Quaterniond& q1, const Eigen::Quaterniond& q2, const double ratio)\n    {\n        // Safety check ratio\n        double real_ratio = ratio;\n        if (real_ratio < 0.0)\n        {\n            real_ratio = 0.0;\n            std::cerr << \"Interpolation ratio < 0.0, set to 0.0\" << std::endl;\n        }\n        else if (real_ratio > 1.0)\n        {\n            real_ratio = 1.0;\n            std::cerr << \"Interpolation ratio > 1.0, set to 1.0\" << std::endl;\n        }\n        // Interpolate\n        return q1.slerp(real_ratio, q2);\n    }\n\n    inline Eigen::Vector3d Interpolate(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const double ratio)\n    {\n        // Safety check ratio\n        double real_ratio = ratio;\n        if (real_ratio < 0.0)\n        {\n            real_ratio = 0.0;\n            std::cerr << \"Interpolation ratio < 0.0, set to 0.0\" << std::endl;\n        }\n        else if (real_ratio > 1.0)\n        {\n            real_ratio = 1.0;\n            std::cerr << \"Interpolation ratio > 1.0, set to 1.0\" << std::endl;\n        }\n        // Interpolate\n        // This is the numerically stable version, rather than  (p1 + (p2 - p1) * real_ratio)\n        return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n    }\n\n    inline Eigen::Isometry3d Interpolate(const Eigen::Isometry3d& t1, const Eigen::Isometry3d& t2, const double ratio)\n    {\n        // Safety check ratio\n        double real_ratio = ratio;\n        if (real_ratio < 0.0)\n        {\n            real_ratio = 0.0;\n            std::cerr << \"Interpolation ratio < 0.0, set to 0.0\" << std::endl;\n        }\n        else if (real_ratio > 1.0)\n        {\n            real_ratio = 1.0;\n            std::cerr << \"Interpolation ratio > 1.0, set to 1.0\" << std::endl;\n        }\n        // Interpolate\n        const Eigen::Vector3d v1 = t1.translation();\n        const Eigen::Quaterniond q1(t1.rotation());\n        const Eigen::Vector3d v2 = t2.translation();\n        const Eigen::Quaterniond q2(t2.rotation());\n        const Eigen::Vector3d vint = Interpolate(v1, v2, real_ratio);\n        const Eigen::Quaterniond qint = Interpolate(q1, q2, real_ratio);\n        const Eigen::Isometry3d tint = ((Eigen::Translation3d)vint) * qint;\n        return tint;\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Distance functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    inline double SquaredDistance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2)\n    {\n        const double xd = v2.x() - v1.x();\n        const double yd = v2.y() - v1.y();\n        return ((xd * xd) + (yd * yd));\n    }\n\n    inline double Distance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2)\n    {\n        return sqrt(SquaredDistance(v1, v2));\n    }\n\n    inline double SquaredDistance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n    {\n        const double xd = v2.x() - v1.x();\n        const double yd = v2.y() - v1.y();\n        const double zd = v2.z() - v1.z();\n        return ((xd * xd) + (yd * yd) + (zd * zd));\n    }\n\n    inline double Distance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n    {\n        return sqrt(SquaredDistance(v1, v2));\n    }\n\n    inline double SquaredDistance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)\n    {\n        assert(v1.size() == v2.size());\n        return (v2 - v1).squaredNorm();\n    }\n\n    inline double Distance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)\n    {\n        return (v2 - v1).norm();\n    }\n\n    inline double Distance(const Eigen::Quaterniond& q1, const Eigen::Quaterniond& q2)\n    {\n        const double dq = std::fabs((q1.w() * q2.w()) + (q1.x() * q2.x()) + (q1.y() * q2.y()) + (q1.z() * q2.z()));\n        if (dq < (1.0 - std::numeric_limits<double>::epsilon()))\n        {\n            return acos(2.0 * (dq * dq) - 1.0);\n        }\n        else\n        {\n            return 0.0;\n        }\n    }\n\n    inline double Distance(const Eigen::Isometry3d& t1, const Eigen::Isometry3d& t2, const double alpha = 0.5)\n    {\n        assert(alpha >= 0.0);\n        assert(alpha <= 1.0);\n        const Eigen::Vector3d v1 = t1.translation();\n        const Eigen::Quaterniond q1(t1.rotation());\n        const Eigen::Vector3d v2 = t2.translation();\n        const Eigen::Quaterniond q2(t2.rotation());\n        const double vdist = Distance(v1, v2) * (1.0 - alpha);\n        const double qdist = Distance(q1, q2) * (alpha);\n        return vdist + qdist;\n    }\n\n    inline double SquaredDistance(const std::vector<double>& p1, const std::vector<double>& p2)\n    {\n        if (p1.size() == p2.size())\n        {\n            double distance = 0.0;\n            for (size_t idx = 0; idx < p1.size(); idx++)\n            {\n                distance += (p2[idx] - p1[idx]) * (p2[idx] - p1[idx]);\n            }\n            return distance;\n        }\n        else\n        {\n            return INFINITY;\n        }\n    }\n\n    inline double Distance(const std::vector<double>& p1, const std::vector<double>& p2)\n    {\n        if (p1.size() == p2.size())\n        {\n            return sqrt(SquaredDistance(p1, p2));\n        }\n        else\n        {\n            return INFINITY;\n        }\n    }\n\n    inline double ContinuousRevoluteSignedDistance(const double p1, const double p2)\n    {\n        // Safety check args\n        const double real_p1 = EnforceContinuousRevoluteBounds(p1);\n        const double real_p2 = EnforceContinuousRevoluteBounds(p2);\n        const double raw_distance = real_p2 - real_p1;\n        if ((raw_distance <= -M_PI) || (raw_distance > M_PI))\n        {\n            if (raw_distance <= -M_PI)\n            {\n                return (-(2.0 * M_PI) - raw_distance);\n            }\n            else if (raw_distance > M_PI)\n            {\n                return ((2.0 * M_PI) - raw_distance);\n            }\n            else\n            {\n                return raw_distance;\n            }\n        }\n        else\n        {\n            return raw_distance;\n        }\n    }\n\n    inline double ContinuousRevoluteDistance(const double p1, const double p2)\n    {\n        return std::fabs(ContinuousRevoluteSignedDistance(p1, p2));\n    }\n\n    inline double AddContinuousRevoluteValues(const double start, const double change)\n    {\n        return EnforceContinuousRevoluteBounds(start + change);\n    }\n\n    inline double GetContinuousRevoluteRange(const double start, const double end)\n    {\n        const double raw_range = ContinuousRevoluteSignedDistance(start, end);\n        if (raw_range >= 0.0)\n        {\n            return raw_range;\n        }\n        else\n        {\n            return (2.0 * M_PI) + raw_range;\n        }\n    }\n\n    inline bool CheckInContinuousRevoluteRange(const double start, const double range, const double val)\n    {\n        const double real_val = EnforceContinuousRevoluteBounds(val);\n        const double real_start = EnforceContinuousRevoluteBounds(start);\n        const double delta = ContinuousRevoluteSignedDistance(real_start, real_val);\n        if (delta >= 0.0)\n        {\n            if (delta <= range)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n        else\n        {\n            const double real_delta = (2.0 * M_PI) + delta;\n            if (real_delta <= range)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n    }\n\n    inline bool CheckInContinuousRevoluteBounds(const double start, const double end, const double val)\n    {\n        const double range = GetContinuousRevoluteRange(start, end);\n        return CheckInContinuousRevoluteRange(start, range, val);\n    }\n\n    // DistanceFn must match the following interface: std::function<double(const T&, const T&)>\n    template<typename T, class DistanceFn, typename Alloc = std::allocator<T>>\n    inline double CalculateTotalDistance(const std::vector<T, Alloc>& path, const DistanceFn& distance_fn)\n    {\n        double total_dist = 0;\n        for (size_t path_idx = 0; path_idx + 1 < path.size(); path_idx++)\n        {\n            const double delta = distance_fn(path[path_idx], path[path_idx + 1]);\n            total_dist += delta;\n        }\n        return total_dist;\n    }\n\n    inline double CalculateTotalDistance(const EigenHelpers::VectorVector3d& points)\n    {\n        double distance = 0;\n\n        for (size_t idx = 1; idx < points.size(); ++idx)\n        {\n            const double delta = (points[idx] - points[idx - 1]).norm();\n            distance += delta;\n        }\n\n        return distance;\n    }\n\n    inline std::vector<double> CalculateIndividualDistances(const EigenHelpers::VectorVector3d& points)\n    {\n        std::vector<double> distances(points.size());\n\n        if (points.size() > 0)\n        {\n            distances[0] = 0.0;\n            for (size_t idx = 1; idx < points.size(); ++idx)\n            {\n                distances[idx] = (points[idx] - points[idx - 1]).norm();\n            }\n        }\n\n        return distances;\n    }\n\n    inline std::vector<double> CalculateCumulativeDistances(const EigenHelpers::VectorVector3d& points)\n    {\n        std::vector<double> distances(points.size());\n\n        if (points.size() > 0)\n        {\n            distances[0] = 0.0;\n            for (size_t idx = 1; idx < points.size(); ++idx)\n            {\n                const double delta = (points[idx] - points[idx - 1]).norm();\n                distances[idx] = distances[idx - 1] + delta;\n            }\n        }\n\n        return distances;\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Conversion functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    inline Eigen::Quaterniond QuaternionFromRPY(const double R, const double P, const double Y)\n    {\n        const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n        const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n        const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n        const Eigen::Quaterniond quat(roll * pitch * yaw);\n        return quat;\n    }\n\n    /* URDF RPY IS ACTUALLY APPLIED Y*P*R */\n    inline Eigen::Quaterniond QuaternionFromUrdfRPY(const double R, const double P, const double Y)\n    {\n        const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n        const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n        const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n        const Eigen::Quaterniond quat(yaw * pitch * roll);\n        return quat;\n    }\n\n    // Returns XYZ Euler angles\n    inline Eigen::Vector3d EulerAnglesFromRotationMatrix(const Eigen::Matrix3d& rot_matrix)\n    {\n        const Eigen::Vector3d euler_angles = rot_matrix.eulerAngles(0, 1, 2); // Use XYZ angles\n        return euler_angles;\n    }\n\n    // Returns XYZ Euler angles\n    inline Eigen::Vector3d EulerAnglesFromQuaternion(const Eigen::Quaterniond& quat)\n    {\n        return EulerAnglesFromRotationMatrix(quat.toRotationMatrix());\n    }\n\n    // Returns XYZ Euler angles\n    inline Eigen::Vector3d EulerAnglesFromIsometry3d(const Eigen::Isometry3d& trans)\n    {\n        return EulerAnglesFromRotationMatrix(trans.rotation());\n    }\n\n    inline Eigen::Isometry3d TransformFromRPY(const double x, const double y, const double z, const double roll, const double pitch, const double yaw)\n    {\n        const Eigen::Isometry3d transform = Eigen::Translation3d(x, y, z) * QuaternionFromRPY(roll, pitch, yaw);\n        return transform;\n    }\n\n    inline Eigen::Isometry3d TransformFromRPY(const Eigen::Vector3d& translation, const Eigen::Vector3d& rotation)\n    {\n        const Eigen::Isometry3d transform = (Eigen::Translation3d)translation * QuaternionFromRPY(rotation.x(), rotation.y(), rotation.z());\n        return transform;\n    }\n\n    inline Eigen::Isometry3d TransformFromRPY(const Eigen::VectorXd& components)\n    {\n        assert(components.size() == 6);\n        const Eigen::Isometry3d transform = Eigen::Translation3d(components(0), components(1), components(2)) * QuaternionFromRPY(components(3), components(4), components(5));\n        return transform;\n    }\n\n    inline Eigen::VectorXd TransformToRPY(const Eigen::Isometry3d& transform)\n    {\n        Eigen::VectorXd components = Eigen::VectorXd::Zero(6);\n        const Eigen::Vector3d translation = transform.translation();\n        const Eigen::Vector3d rotation = EulerAnglesFromRotationMatrix(transform.rotation());\n        components << translation, rotation;\n        return components;\n    }\n\n    inline Eigen::Vector3d StdVectorDoubleToEigenVector3d(const std::vector<double>& vector)\n    {\n        assert(vector.size() == 3 && \"std::vector<double> source vector is not 3 elements in size\");\n        return Eigen::Vector3d(vector[0], vector[1], vector[2]);\n    }\n\n    inline Eigen::VectorXd StdVectorDoubleToEigenVectorXd(const std::vector<double>& vector)\n    {\n        Eigen::VectorXd eigen_vector(vector.size());\n        for (size_t idx = 0; idx < vector.size(); idx++)\n        {\n            const double val = vector[idx];\n            eigen_vector((ssize_t)idx) = val;\n        }\n        return eigen_vector;\n    }\n\n    inline std::vector<double> EigenVector3dToStdVectorDouble(const Eigen::Vector3d& point)\n    {\n        return std::vector<double>{point.x(), point.y(), point.z()};\n    }\n\n    inline std::vector<double> EigenVectorXdToStdVectorDouble(const Eigen::VectorXd& eigen_vector)\n    {\n        std::vector<double> vector((size_t)eigen_vector.size());\n        for (size_t idx = 0; idx < (size_t)eigen_vector.size(); idx++)\n        {\n            const double val = eigen_vector[(ssize_t)idx];\n            vector[idx] = val;\n        }\n        return vector;\n    }\n\n    // Takes <x, y, z, w> as is the ROS custom!\n    inline Eigen::Quaterniond StdVectorDoubleToEigenQuaterniond(const std::vector<double>& vector)\n    {\n        if (vector.size() != 4)\n        {\n            std::cerr << \"Quaterniond source vector is not 4 elements in size\" << std::endl;\n            assert(false);\n        }\n        Eigen::Quaterniond eigen_quaternion(vector[3], vector[0], vector[1], vector[2]);\n        return eigen_quaternion;\n    }\n\n    // Returns <x, y, z, w> as is the ROS custom!\n    inline std::vector<double> EigenQuaterniondToStdVectorDouble(const Eigen::Quaterniond& quat)\n    {\n        return std::vector<double>{quat.x(), quat.y(), quat.z(), quat.w()};\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Averaging functions\n    // Numerically more stable averages taken from http://people.ds.cam.ac.uk/fanf2/hermes/doc/antiforgery/stats.pdf\n    ////////////////////////////////////////////////////////////////////////////\n\n    inline double AverageStdVectorDouble(\n            const std::vector<double>& values,\n            const std::vector<double>& weights = std::vector<double>())\n    {\n        // Get the weights\n        assert(values.size() > 0);\n        assert((weights.size() == values.size()) || (weights.size() == 0));\n        const bool use_weights = (weights.size() != 0);\n        // Find the first element with non-zero weight\n        size_t starting_idx = 0;\n        while (starting_idx < weights.size() && weights[starting_idx] == 0.0)\n        {\n            starting_idx++;\n        }\n        // If all weights are zero, result is undefined\n        assert(starting_idx < values.size());\n        // Start the recursive definition with the base case\n        double average = values[starting_idx];\n        const double starting_weight = use_weights ? std::abs(weights[starting_idx]) : 1.0;\n        assert(starting_weight > 0.0);\n        double weights_running_sum = starting_weight;\n        // Do the weighted averaging on the rest of the vectors\n        for (size_t idx = starting_idx + 1; idx < values.size(); idx++)\n        {\n            const double weight = use_weights ? std::abs(weights[idx]) : 1.0;\n            weights_running_sum += weight;\n            const double effective_weight = weight / weights_running_sum;\n            const double prev_average = average;\n            const double current = values[idx];\n            average = prev_average + (effective_weight * (current - prev_average));\n        }\n        return average;\n    }\n\n    inline double ComputeStdDevStdVectorDouble(const std::vector<double>& values, const double mean)\n    {\n        assert(values.size() > 0);\n        if (values.size() == 1)\n        {\n            return 0.0;\n        }\n        else\n        {\n            const double inv_n_minus_1 = 1.0 / (double)(values.size() - 1);\n            double stddev_sum = 0.0;\n            for (size_t idx = 0; idx < values.size(); idx++)\n            {\n                const double delta = values[idx] - mean;\n                stddev_sum += (delta * delta);\n            }\n            return std::sqrt(stddev_sum * inv_n_minus_1);\n        }\n    }\n\n    inline double ComputeStdDevStdVectorDouble(const std::vector<double>& values)\n    {\n        const double mean = AverageStdVectorDouble(values);\n        return ComputeStdDevStdVectorDouble(values, mean);\n    }\n\n    /*\n     * This function does not actually deal with the continuous revolute space correctly,\n     * it just assumes a normal real Euclidean space\n     */\n    inline double AverageContinuousRevolute(\n            const std::vector<double>& angles,\n            const std::vector<double>& weights = std::vector<double>())\n    {\n        return AverageStdVectorDouble(angles, weights);\n    }\n\n    /**\n     * This function is really only going to work well for \"approximately continuous\"\n     *  types, i.e. floats and doubles, due to the implementation\n     */\n    template<typename ScalarType, int Rows, typename Allocator = std::allocator<Eigen::Matrix<ScalarType, Rows, 1>>>\n    inline Eigen::Matrix<ScalarType, Rows, 1> AverageEigenVector(\n            const std::vector<Eigen::Matrix<ScalarType, Rows, 1>, Allocator>& vectors,\n            const std::vector<double>& weights = std::vector<double>())\n    {\n        // Get the weights\n        assert(vectors.size() > 0);\n        assert((weights.size() == vectors.size()) || (weights.size() == 0));\n        const bool use_weights = (weights.size() != 0);\n        // Find the first element with non-zero weight\n        size_t starting_idx = 0;\n        while (starting_idx < weights.size() && weights[starting_idx] == 0.0)\n        {\n            starting_idx++;\n        }\n        // If all weights are zero, result is undefined\n        assert(starting_idx < vectors.size());\n        // Start the recursive definition with the base case\n        Eigen::Matrix<ScalarType, Rows, 1> avg_vector = vectors[starting_idx];\n        const double starting_weight = use_weights ? std::abs(weights[starting_idx]) : 1.0;\n        assert(starting_weight > 0.0);\n        double weights_running_sum = starting_weight;\n        // Do the weighted averaging on the rest of the vectors\n        for (size_t idx = starting_idx + 1; idx < vectors.size(); ++idx)\n        {\n            const double weight = use_weights ? std::abs(weights[idx]) : 1.0;\n            weights_running_sum += weight;\n            const double effective_weight = weight / weights_running_sum;\n            const Eigen::Matrix<ScalarType, Rows, 1> prev_avg_vector = avg_vector;\n            const Eigen::Matrix<ScalarType, Rows, 1>& current = vectors[idx];\n            avg_vector = prev_avg_vector + (effective_weight * (current - prev_avg_vector));\n        }\n        return avg_vector;\n    }\n\n    inline Eigen::Vector3d AverageEigenVector3d(\n            const EigenHelpers::VectorVector3d& vectors,\n            const std::vector<double>& weights = std::vector<double>())\n    {\n        return AverageEigenVector(vectors, weights);\n    }\n\n    inline Eigen::VectorXd AverageEigenVectorXd(\n            const std::vector<Eigen::VectorXd>& vectors,\n            const std::vector<double>& weights = std::vector<double>())\n    {\n        return AverageEigenVector(vectors, weights);\n    }\n\n    /**\n     * Implementation of method described in (http://stackoverflow.com/a/27410865)\n     * See paper at (http://www.acsu.buffalo.edu/~johnc/ave_quat07.pdf) for full explanation\n     */\n    inline Eigen::Quaterniond AverageEigenQuaterniond(\n            const EigenHelpers::VectorQuaterniond& quaternions,\n            const std::vector<double>& weights = std::vector<double>())\n    {\n        // Get the weights\n        const bool use_weights = weights.size() == quaternions.size() ? true : false;\n        assert(quaternions.size() > 0);\n        assert((weights.size() == quaternions.size()) || (weights.size() == 0));\n        // Shortcut the process if there is only 1 quaternion\n        if (quaternions.size() == 1)\n        {\n            assert(weights.size() == 0 || weights[0] != 0.0);\n            return quaternions[0];\n        }\n        // Build the averaging matrix\n        Eigen::MatrixXd q_matrix(4, quaternions.size());\n        for (size_t idx = 0; idx < quaternions.size(); idx++)\n        {\n            const double weight = use_weights ? std::abs(weights[idx]) : 1.0;\n            const Eigen::Quaterniond& q = quaternions[idx];\n            q_matrix.col((ssize_t)idx) << weight * q.w(), weight * q.x(), weight * q.y(), weight * q.z();\n        }\n        // Make the matrix square\n        const Eigen::Matrix<double, 4, 4> qqtranspose_matrix = q_matrix * q_matrix.transpose();\n        // Compute the eigenvectors and eigenvalues of the qqtranspose matrix\n        const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>> solver(qqtranspose_matrix);\n        const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>>::EigenvalueType eigen_values = solver.eigenvalues();\n        const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>>::EigenvectorsType eigen_vectors = solver.eigenvectors();\n        // Extract the eigenvector corresponding to the largest eigenvalue\n        double max_eigenvalue = -INFINITY;\n        int64_t max_eigenvector_index = -1;\n        for (size_t idx = 0; idx < 4; idx++)\n        {\n            const double current_eigenvalue = eigen_values((long)idx).real();\n            if (current_eigenvalue > max_eigenvalue)\n            {\n                max_eigenvalue = current_eigenvalue;\n                max_eigenvector_index = (int64_t)idx;\n            }\n        }\n        assert(max_eigenvector_index >= 0);\n        // Note that these are already normalized!\n        const Eigen::Vector4cd best_eigenvector = eigen_vectors.col((long)max_eigenvector_index);\n        // Convert back into a quaternion\n        const Eigen::Quaterniond average_q(best_eigenvector(0).real(), best_eigenvector(1).real(), best_eigenvector(2).real(), best_eigenvector(3).real());\n        return average_q;\n    }\n\n    inline Eigen::Isometry3d AverageEigenIsometry3d(\n            const EigenHelpers::VectorIsometry3d& transforms,\n            const std::vector<double>& weights = std::vector<double>())\n    {\n        assert(transforms.size() > 0);\n        assert((weights.size() == transforms.size()) || (weights.size() == 0));\n        // Shortcut the process if there is only 1 transform\n        if (transforms.size() == 1)\n        {\n            assert(weights.size() == 0 || weights[0] != 0.0);\n            return transforms[0];\n        }\n        // Extract components\n        EigenHelpers::VectorVector3d translations(transforms.size());\n        EigenHelpers::VectorQuaterniond rotations(transforms.size());\n        for (size_t idx = 0; idx < transforms.size(); idx++)\n        {\n            translations[idx] = transforms[idx].translation();\n            rotations[idx] = Eigen::Quaterniond(transforms[idx].rotation());\n        }\n        // Average\n        const Eigen::Vector3d average_translation = AverageEigenVector(translations, weights);\n        const Eigen::Quaterniond average_rotation = AverageEigenQuaterniond(rotations, weights);\n        // Make the average transform\n        const Eigen::Isometry3d average_transform = (Eigen::Translation3d)average_translation * average_rotation;\n        return average_transform;\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Geometry functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    /**\n     * @brief DistanceToLine\n     * Math taken from http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html\n     * x = x0\n     * point_on_line = x1\n     * unit_vector = x2 - x1 / |x2 - x1|\n     * @param point_on_line\n     * @param unit_vector\n     * @param x\n     * @return The distance to the line, and the displacement along the line\n     */\n    inline std::pair<double, double> DistanceToLine(\n            const Eigen::Vector3d& point_on_line,\n            const Eigen::Vector3d& unit_vector,\n            const Eigen::Vector3d x)\n    {\n        // Ensure that our input data is valid\n        const auto real_unit_vector = unit_vector.normalized();\n        if (!CloseEnough(unit_vector.norm(), 1.0, 1e-13))\n        {\n            std::cerr << \"[Distance to line]: unit vector was not normalized: \"\n                      << unit_vector.transpose() << \" Norm: \" << unit_vector.norm() << std::endl;\n        }\n\n        const auto delta = x - point_on_line;\n        const double displacement_along_line = real_unit_vector.dot(delta);\n        const auto x_projected_onto_line = point_on_line + real_unit_vector * displacement_along_line;\n        const double distance_to_line = (x_projected_onto_line - x).norm();\n\n        // A simple neccescary (but not sufficient) check to look for math errors\n        assert(IsApprox(distance_to_line * distance_to_line +\n                        displacement_along_line * displacement_along_line, delta.squaredNorm(), 1e-10));\n\n        return std::make_pair(distance_to_line, displacement_along_line);\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Projection/Rejection functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    // Projects vector_to_project onto base_vector and returns the portion that is parallel to base_vector\n    template <typename DerivedB, typename DerivedV>\n    inline Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1> VectorProjection(\n            const Eigen::MatrixBase<DerivedB>& base_vector,\n            const Eigen::MatrixBase<DerivedV>& vector_to_project)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(DerivedB);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(DerivedV);\n        EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(DerivedB, DerivedV)\n        static_assert(std::is_same<typename DerivedB::Scalar, typename DerivedV::Scalar>::value,\n                      \"base_vector and vector_to_project must have the same data type\");\n        // Perform projection\n        const typename DerivedB::Scalar b_squared_norm = base_vector.squaredNorm();\n        if (b_squared_norm > 0)\n        {\n            return (base_vector.dot(vector_to_project) / b_squared_norm) * base_vector;\n        }\n        else\n        {\n            return Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1>::Zero(base_vector.rows());\n        }\n    }\n\n    // Projects vector_to_project onto base_vector and returns the portion that is perpendicular to base_vector\n    template <typename DerivedB, typename DerivedV>\n    inline Eigen::Matrix<typename DerivedB::Scalar, Eigen::Dynamic, 1> VectorRejection(\n            const Eigen::MatrixBase<DerivedB>& base_vector,\n            const Eigen::MatrixBase<DerivedV>& vector_to_project)\n    {\n        // Rejection is defined in relation to projection\n        return vector_to_project - VectorProjection(base_vector, vector_to_project);\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // (Weighted) dot product, norm, and angle functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    // Returns the (non-negative) angle defined by the vectors (b - a), and (b - c)\n    template <typename DerivedA, typename DerivedB, typename DerivedC>\n    inline double AngleDefinedByPoints(const Eigen::MatrixBase<DerivedA>& a, const Eigen::MatrixBase<DerivedB>& b, const Eigen::MatrixBase<DerivedC>& c)\n    {\n        // Check for potential numerical problems\n        if (a.isApprox(b) || (b.isApprox(c)))\n        {\n            std::cerr << \"Warning: Potential numerical stability problems in AngleDefinedByPoints\\n\";\n        }\n\n        // Do the actual math here\n        const auto vec1 = (a - b).normalized();\n        const auto vec2 = (c - b).normalized();\n        const double cosine_raw = vec1.dot(vec2);\n        const double cosine = std::max(-1.0, std::min(cosine_raw, 1.0));\n        return std::acos(cosine);\n    }\n\n    inline double WeightedDotProduct(const Eigen::VectorXd& vec1, const Eigen::VectorXd& vec2, const Eigen::VectorXd& weights)\n    {\n        return vec1.cwiseProduct(weights).dot(vec2);\n    }\n\n    inline double WeightedSquaredNorm(const Eigen::VectorXd& vec, const Eigen::VectorXd weights)\n    {\n        return WeightedDotProduct(vec, vec, weights);\n    }\n\n    inline double WeightedNorm(const Eigen::VectorXd& vec, const Eigen::VectorXd& weights)\n    {\n        return std::sqrt(WeightedSquaredNorm(vec, weights));\n    }\n\n    inline double WeightedCosineAngleBetweenVectors(const Eigen::VectorXd& vec1, const Eigen::VectorXd& vec2, const Eigen::VectorXd& weights)\n    {\n        const double vec1_norm = WeightedNorm(vec1, weights);\n        const double vec2_norm = WeightedNorm(vec2, weights);\n        assert(vec1_norm > 0 && vec2_norm > 0);\n        const double result = WeightedDotProduct(vec1, vec2, weights) / (vec1_norm * vec2_norm);\n        return std::max(-1.0, std::min(result, 1.0));\n    }\n\n    inline double WeightedAngleBetweenVectors(const Eigen::VectorXd& vec1, const Eigen::VectorXd& vec2, const Eigen::VectorXd& weights)\n    {\n        return std::acos(WeightedCosineAngleBetweenVectors(vec1, vec2, weights));\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Other auxiliary functions\n    ////////////////////////////////////////////////////////////////////////////\n\n    class Hyperplane\n    {\n    protected:\n\n        Eigen::VectorXd plane_origin_;\n        Eigen::VectorXd plane_normal_;\n\n    public:\n\n        Hyperplane(const Eigen::VectorXd& origin, const Eigen::VectorXd& normal)\n        {\n            assert(origin.size() == normal.size());\n            plane_origin_ = origin;\n            plane_normal_ = normal;\n        }\n\n        Hyperplane() {}\n\n        const Eigen::VectorXd& GetOrigin() const\n        {\n            return plane_origin_;\n        }\n\n        const Eigen::VectorXd& GetNormal() const\n        {\n            return plane_normal_;\n        }\n\n        double GetNormedDotProduct(const Eigen::VectorXd& point) const\n        {\n            assert(point.size() == plane_origin_.size());\n            const Eigen::VectorXd check_vector = point - plane_origin_;\n            const Eigen::VectorXd check_vector_normed = EigenHelpers::SafeNormal(check_vector);\n            const double dot_product = check_vector_normed.dot(plane_normal_);\n            return dot_product;\n        }\n\n        double GetRawDotProduct(const Eigen::VectorXd& point) const\n        {\n            assert(point.size() == plane_origin_.size());\n            const Eigen::VectorXd check_vector = point - plane_origin_;\n            const double dot_product = check_vector.dot(plane_normal_);\n            return dot_product;\n        }\n\n        Eigen::VectorXd RejectVectorOntoPlane(const Eigen::VectorXd& vector) const\n        {\n            return VectorProjection(plane_normal_, vector);\n        }\n\n        double GetSquaredDistanceToPlane(const Eigen::VectorXd& point) const\n        {\n            const Eigen::VectorXd origin_to_point_vector = point - plane_origin_;\n            return VectorProjection(plane_normal_, origin_to_point_vector).squaredNorm();\n        }\n\n        double GetDistanceToPlane(const Eigen::VectorXd& point) const\n        {\n            const Eigen::VectorXd origin_to_point_vector = point - plane_origin_;\n            return VectorProjection(plane_normal_, origin_to_point_vector).norm();\n        }\n\n        Eigen::VectorXd ProjectVectorOntoPlane(const Eigen::VectorXd& vector) const\n        {\n            return VectorRejection(plane_normal_, vector);\n        }\n\n        Eigen::VectorXd ProjectPointOntoPlane(const Eigen::VectorXd& point) const\n        {\n            const Eigen::VectorXd origin_to_point_vector = point - plane_origin_;\n            const Eigen::VectorXd projected_to_point_vector = VectorRejection(plane_normal_, origin_to_point_vector);\n            const Eigen::VectorXd projected_point = plane_origin_ + projected_to_point_vector;\n            return projected_point;\n        }\n    };\n\n    /*\n     * Returns a pair of <centroid point, normal vector> defining the plane\n     */\n    inline Hyperplane FitPlaneToPoints(const std::vector<Eigen::VectorXd>& points)\n    {\n        // Subtract out the centroid\n        const Eigen::VectorXd centroid = EigenHelpers::AverageEigenVectorXd(points);\n        Eigen::MatrixXd centered_points(centroid.size(), points.size());\n        for (size_t idx = 0; idx < points.size(); idx++)\n        {\n            const Eigen::VectorXd& current_point = points[idx];\n            centered_points.block(0, (ssize_t)idx, centroid.size(), 1) = (current_point - centroid);\n        }\n        // Compute SVD of the centered points\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(centered_points, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        // Get results of SVD\n        const Eigen::JacobiSVD<Eigen::MatrixXd>::SingularValuesType& singular_values = svd.singularValues();\n        const Eigen::JacobiSVD<Eigen::MatrixXd>::MatrixUType& u_matrix = svd.matrixU();\n        // Get the left singular vector corresponding to the minimum singular value\n        double minimum_singular_value = INFINITY;\n        ssize_t best_singular_value_index = -1;\n        for (ssize_t idx = 0; idx < singular_values.size(); idx++)\n        {\n            const std::complex<double> current_singular_value = singular_values(idx);\n            if (current_singular_value.real() < minimum_singular_value)\n            {\n                minimum_singular_value = current_singular_value.real();\n                best_singular_value_index = idx;\n            }\n        }\n        assert(best_singular_value_index >= 0);\n        // The corresponding left singular vector is the normal vector of the best-fit plane\n        const Eigen::VectorXd best_left_singular_vector = u_matrix.col(best_singular_value_index);\n        const Eigen::VectorXd normal_vector = EigenHelpers::SafeNormal(best_left_singular_vector);\n        return Hyperplane(centroid, normal_vector);\n    }\n\n    inline double SuggestedRcond()\n    {\n        return 0.001;\n    }\n\n    // Derived from code by Yohann Solaro ( http://listengine.tuxfamily.org/lists.tuxfamily.org/eigen/2010/01/msg00187.html )\n    // see : http://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#The_general_case_and_the_SVD_method\n    inline Eigen::MatrixXd Pinv(const Eigen::MatrixXd& b, const double rcond, const bool enable_flip=true)\n    {\n        bool flip = false;\n        Eigen::MatrixXd a;\n        if (enable_flip && (b.rows() < b.cols()))\n        {\n            a = b.transpose();\n            flip = true;\n        }\n        else\n        {\n            a = b;\n        }\n        // SVD\n        Eigen::JacobiSVD<Eigen::MatrixXd> svdA;\n        svdA.compute(a, Eigen::ComputeFullU | Eigen::ComputeThinV);\n        Eigen::JacobiSVD<Eigen::MatrixXd>::SingularValuesType vSingular = svdA.singularValues();\n        // Build a diagonal matrix with the Inverted Singular values\n        // The pseudo inverted singular matrix is easy to compute :\n        // is formed by replacing every nonzero entry by its reciprocal (inversing).\n        Eigen::VectorXd vPseudoInvertedSingular(svdA.matrixV().cols());\n        for (int iRow = 0; iRow < vSingular.rows(); iRow++)\n        {\n            if (std::fabs(vSingular(iRow)) <= rcond) // Todo : Put epsilon in parameter\n            {\n                vPseudoInvertedSingular(iRow)= 0.0;\n            }\n            else\n            {\n                vPseudoInvertedSingular(iRow) = 1.0 / vSingular(iRow);\n            }\n        }\n        // A little optimization here\n        const Eigen::MatrixXd mAdjointU = svdA.matrixU().adjoint().block(0, 0, vSingular.rows(), svdA.matrixU().adjoint().cols());\n        // Yes, this is ugly. This is to suppress a warning on type conversion related to Eigen operations\n        #pragma GCC diagnostic push\n        #pragma GCC diagnostic ignored \"-Wconversion\"\n        // Pseudo-Inversion : V * S * U'\n        const Eigen::MatrixXd a_pinv = (svdA.matrixV() * vPseudoInvertedSingular.asDiagonal()) * mAdjointU;\n        #pragma GCC diagnostic pop\n        // Flip back if need be\n        if (flip)\n        {\n            return a_pinv.transpose();\n        }\n        else\n        {\n            return a_pinv;\n        }\n    }\n\n    /**\n     * @brief WeightedLeastSquaresSolver Solves the minimization problem min || Ax - b ||^2 for x, using weights w in the norm\n     *                                   If the problem is ill-conditioned, adds in a damping factor. This is equivalent to\n     *                                   solving A^T * diag(W) * A * x = A^T * diag(W) * b for x.\n     * @param A size M x N with M > N\n     * @param b size M x 1\n     * @param w size M x 1\n     * @param damping_threshold The smallest singular value we allow in A^T * W * A before we apply damping\n     * @param damping_value The damping value we apply to the main diagonal of A^T * W * A if we exceed the threshold\n     * @return size N x 1\n     */\n    inline Eigen::VectorXd WeightedLeastSquaresSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::VectorXd& w, const double damping_threshold, const double damping_value)\n    {\n        // Yes, this is ugly. This is to suppress a warning on type conversion related to Eigen operations\n        #pragma GCC diagnostic push\n        #pragma GCC diagnostic ignored \"-Wconversion\"\n        Eigen::MatrixXd left_side = A.transpose() * w.asDiagonal() * A;\n        #pragma GCC diagnostic pop\n        const double minimum_singular_value = left_side.jacobiSvd().singularValues().minCoeff();\n\n        if (minimum_singular_value < damping_threshold)\n        {\n            left_side += damping_value * Eigen::MatrixXd::Identity(left_side.rows(), left_side.cols());\n        }\n\n        // With the damping we can assume that the left side is positive definite, so use LLT to solve this\n        return left_side.llt().solve(A.transpose() * w.cwiseProduct(b));\n    }\n}\n\n#endif // EIGEN_HELPERS_HPP\n", "meta": {"hexsha": "b4e4595afb9bef8d15dca9895db7fb02fd1358de", "size": 61464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/eigen_helpers.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/eigen_helpers.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/eigen_helpers.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": 39.149044586, "max_line_length": 271, "alphanum_fraction": 0.5812670832, "num_tokens": 14606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.03904829705959318, "lm_q1q2_score": 0.018305475647254398}}
{"text": "/**\n * @file EmbedPDBQTMols.cpp\n * @author Louai KASSA BAGHDOUCHE\n * @brief A C++ code to generate conformers and their USRCAT Features from multiple pdbqt files, by fetching the SMILES and ID \n * from PDBQT and generate SMI files\n * @date 2022-03-29\n * \n * @copyright Copyright (c) 2022\n * \n */\n\n#include <iostream>\n#include <string>\n#include <thread>\n#include <array>\n#include <vector>\n#include <mutex>\n#include <GraphMol/FileParsers/MolSupplier.h>\n#include <GraphMol/DistGeomHelpers/Embedder.h>\n#include <GraphMol/FileParsers/MolWriters.h>\n#include <GraphMol/SmilesParse/SmilesParse.h>\n#include <GraphMol/Descriptors/MolDescriptors.h>\n#include <GraphMol/Substruct/SubstructMatch.h>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/filesystem/operations.hpp>\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace RDGeom;\nusing namespace RDKit;\nusing namespace RDKit::MolOps;\nusing namespace RDKit::DGeomHelpers;\nusing namespace RDKit::Descriptors;\nusing namespace boost::filesystem;\nusing boost_ifstream = boost::filesystem::ifstream;\nusing boost_ofstream = boost::filesystem::ofstream;\n\nstatic const size_t s_Num_references = 4;\nstatic const size_t s_Num_subsets = 5;\nstatic const array<string, s_Num_subsets> s_SubsetSMARTS\n{{\n  \"[!#1]\", // heavy\n  \"[#6+0!$(*~[#7,#8,F]),SH0+0v2,s+0,S^3,Cl+0,Br+0,I+0]\", // hydrophobic\n  \"[a]\", // aromatic\n  \"[$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N&v3;H1,H2]-[!$(*=[O,N,P,S])]),$([N;v3;H0]),$([n,o,s;+0]),F]\", // acceptor\n  \"[N!H0v3,N!H0+v4,OH+0,SH+0,nH+0]\", // donor\n}};\n\nstatic array<unique_ptr<ROMol>, s_Num_subsets> SubsetMols;\nstatic array<vector<int>, s_Num_subsets> subsets;\nstatic array<Point3D, s_Num_references> references;\nstatic array<vector<float>, s_Num_references> dista;\n\n// Compute the Euclidien distance\ntemplate<typename T>\nstatic inline float dist2(const T& p0, const T& p1)\n{\n\tconst auto d0 = p0[0] - p1[0];\n\tconst auto d1 = p0[1] - p1[1];\n\tconst auto d2 = p0[2] - p1[2];\n\treturn d0 * d0 + d1 * d1 + d2 * d2;\n}\n\nstatic array<float, 60> usrcat_features(ROMol& mol, int index)\n{\n  array<float, 60> features;\n  // Wrap SMARTS strings to ROMol objects.\n  for (size_t k = 0; k < s_Num_subsets; ++k)\n  {\n    SubsetMols[k].reset(reinterpret_cast<ROMol*>(SmartsToMol(s_SubsetSMARTS[k])));\n  }\n  const auto num_points = mol.getNumHeavyAtoms();\n  const auto& conformer = mol.getConformer(index);\n  for (size_t k = 0; k < s_Num_subsets; ++k)\n  {\n    vector<vector<pair<int, int>>> matchVect;\n    SubstructMatch(mol, *SubsetMols[k], matchVect);\n    const auto num_matches = matchVect.size();\n    auto& subset = subsets[k];\n    subset.resize(num_matches);\n    for (size_t j = 0; j < num_matches; ++j)\n    {\n      subset[j] = matchVect[j].front().second;\n    }\n  }\n  const auto& subset0 = subsets.front();\n  // assert(subset0.size() == num_points);\n\n  for (auto& ref : references)\n  {\n    ref.x = ref.y = ref.z = 0;\n  }\n  auto& ctd = references[0];\n  auto& cst = references[1];\n  auto& fct = references[2];\n  auto& ftf = references[3];\n  for (const auto sub : subset0)\n  {\n    const auto& a = conformer.getAtomPos(sub);\n    ctd += a;\n  }\n  ctd /= num_points;\n  float cst_dist = numeric_limits<float>::max();\n  float fct_dist = numeric_limits<float>::lowest();\n  float ftf_dist = numeric_limits<float>::lowest();\n  for (const auto sub : subset0)\n  {\n    const auto& a = conformer.getAtomPos(sub);\n    const auto this_dist = dist2(a, ctd);\n    if (this_dist < cst_dist)\n    {\n      cst = a;\n      cst_dist = this_dist;\n    }\n    if (this_dist > fct_dist)\n    {\n      fct = a;\n      fct_dist = this_dist;\n    }\n  }\n  for (const auto sub : subset0)\n  {\n    const auto& a = conformer.getAtomPos(sub);\n    const auto this_dist = dist2(a, fct);\n    if (this_dist > ftf_dist)\n    {\n      ftf = a;\n      ftf_dist = this_dist;\n    }\n  }\n  // Precalculate the distances of heavy atoms to the reference points, given that subsets[1 to 4] are subsets of subsets[0].\n  for (size_t ref = 0; ref < s_Num_references; ++ref)\n  {\n    const auto& reference = references[ref];\n    auto& distp = dista[ref];\n    distp.resize(num_points);\n    for (size_t p = 0; p < num_points; ++p)\n    {\n      distp[subset0[p]] = sqrt(dist2(conformer.getAtomPos(subset0[p]), reference));\n    }\n  }\n  // loop over pharmacophoric subsets and reference points.\n  size_t qo = 0;\n  for (const auto& subset : subsets)\n  {\n    const auto n = subset.size();\n    for (size_t ref = 0; ref < s_Num_references; ++ref)\n    {\n      // Load distances from precalculated ones\n      const auto& distp = dista[ref];\n      vector<float> dists(n);\n      for (size_t a = 0; a < n; ++a)\n      {\n        dists[a] = distp[subset[a]];\n      }\n      // Compute moments\n      array<float, 3> m{};\n      if (n > 2)\n      {\n        const auto v = 1.0 / n;\n        for (size_t j = 0; j < n; ++j)\n        {\n          const auto d = dists[j];\n          m[0] += d;\n        }\n        m[0] *= v;\n        for (size_t j = 0; j < n; ++j)\n        {\n          const auto d = dists[j] - m[0];\n          m[1] += d * d;\n        }\n        m[1] = sqrt(m[1] * v);\n        for (size_t j = 0; j < n; ++j)\n        {\n          const auto d = dists[j] - m[0];\n          m[2] += d * d * d;\n        }\n        m[2] = cbrt(m[2] * v);\n      }\n      else if (n == 2)\n      {\n        m[0] = 0.5 * (dists[0] + dists[1]);\n        m[1] = 0.5 * fabs(dists[0] - dists[1]);\n      }\n      else if (n == 1)\n      {\n        m[0] = dists[0];\n      }\n      for (const auto e : m)\n      {\n        features[qo++] = e;\n      }\n    }\n  }\n  return features;\n}\n\n// function to remove whitespaces\nstatic inline auto stripWhiteSpaces(string& str)\n{\n  str.erase(remove(str.begin(), str.end(), ' '), str.end());\n}\n\nstatic mutex s_Mu;\n\ntemplate<typename T>\nstatic inline void write_to_binary(T& buf, boost_ofstream& ofs)\n{\n  // pass the ofstream object by reference, to avoid declaring it each time\n  lock_guard<mutex> lock(s_Mu);\n  const size_t num_bytes = sizeof(buf);\n  ofs.write(reinterpret_cast<char*>(buf.data()), num_bytes);\n}\n\nint main(int argc, char* argv[])\n{\n  if (argc != 4)\n  {\n    cerr << \"Usage: ./EmbedAllAndGenerateSMIL [PDBQT FOLDER] [CONFORMERS SDF] [OUTPUT SMI]\" << endl;\n    return 1;\n  }\n\n  // Obtain the files from the CLI argument\n  const auto pdbqt_folder = argv[1];\n  const auto conformers_file = argv[2];\n  const auto smi_file = argv[3];\n\n  // generate smiles.txt and realid.txt and properties\n  int p = string(smi_file).find('.');\n  const path only_smiles_txt = string(smi_file).substr(0, p) + \"_only_smiles.txt\";\n  const path only_id_txt = string(smi_file).substr(0, p) + \"_only_id.txt\";\n  p = string(conformers_file).find('.');\n  const path rfprop_file = string(conformers_file).substr(0, p) + \"_4properties.f32\";\n  const path riprop_file = string(conformers_file).substr(0, p) + \"_5properties.i16\";\n  const path usrcatf64_file = string(conformers_file).substr(0, p) + \"_usrcat.f64\";\n\n  // Inialize the output files\n  boost_ofstream conf_file(conformers_file, ios::app);\n  boost_ofstream smifile(smi_file, ios::app);\n  boost_ofstream smilesfile(only_smiles_txt, ios::app);\n  boost_ofstream id_file(only_id_txt, ios::app);\n  boost_ofstream rfprop(rfprop_file, ios::binary | ios::app);\n  boost_ofstream riprop(riprop_file, ios::binary | ios::app);\n  boost_ofstream usrcatf64(usrcatf64_file, ios::binary | ios::app);\n\n  // Initalize constants\n  const string pdbqt_extension = \".pdbqt\";\n\n  // Initialize variables\n  string line, compound, smiles, next_line;\n  int pos;\n  vector<thread> thread_pool; \n  thread_pool.reserve(3); // thread pool with 3 threads\n  array<float, 60> features;\n  array<float, 4> realfprop;\n  array<int16_t, 5> realiprop;\n  size_t processed_ligand = 0;\n  size_t all_ligands = 0;\n  EmbedParameters params(srETKDGv3);\n  params.randomSeed = 209;\n  params.numThreads = 8;\n  params.useRandomCoords = true; // this parameter is used to make the process faster\n  params.maxIterations = 3; // max iterations to 1\n  SDWriter writer(&conf_file);\n\n  // Search for pdbqt files into the pdbqt folder\n  for (const auto& entry : recursive_directory_iterator(pdbqt_folder))\n  {\n    if (entry.path().extension() == pdbqt_extension)\n    {\n      std::cout << \"Processing molecule Number° \" << processed_ligand << '/' << all_ligands << endl;\n      std::cout << \"Path of the molecule \" << entry.path() << endl;\n      boost_ifstream ifs(entry.path());\n      while (getline(ifs, line))\n      {\n        if (line.find(\"Compound:\") != string::npos)\n        {\n          pos = line.find(':');\n          compound = line.substr(pos + 1);\n          stripWhiteSpaces(compound);\n        }\n        if (line.find(\"SMILES:\") != string::npos)\n        {\n          /**\n           * @brief Some compounds of the REAL library strangely contain a 'q' and 'r' characters in their \n           * SMILES, and other compounds have a splitted SMILES in two lines. These problems cause a Segfault error raised from the RDKit API.\n           * Here is a check of the goodness of the SMILES molecule, to avoid the Segfault error\n           */\n          pos = line.find(':');\n          smiles = line.substr(pos + 1);\n          stripWhiteSpaces(smiles);\n          if (getline(ifs, next_line))\n          {\n            if (next_line.find(\"REMARK\") != string::npos)\n            {\n              std::cout << \"No problem with the SMILES!\" << endl;\n            }\n            else\n            {\n              cerr << \"The SMILES is splited, trying to fix the SMILES\" << endl;\n              smiles = smiles + next_line;\n              std::cout << \"The fixed SMILES: \" << smiles << endl;\n            }\n          }\n          if (smiles.find('q') != string::npos || smiles.find('r') != string::npos || smiles.find('s') != string::npos)\n          {\n            cerr << \"Incorrect format of the SMILES\" << endl;\n            break;\n          }\n          else\n          {\n            try\n            {\n              const unique_ptr<ROMol> smi_ptr(SmilesToMol(smiles));\n              const unique_ptr<ROMol> mol_ptr(addHs(*smi_ptr));\n              auto& mol = *mol_ptr;\n              mol.setProp(\"_Name\", compound);\n              // generate conformers\n              const auto confIds = EmbedMultipleConfs(mol, 4, params);\n              if (confIds.empty())\n              {\n                cerr << \"Error, in parsing molecule. Conformers not generated!\" << endl;\n                break;\n              }\n              // Check if the molecule has 4 conformers\n              if (confIds.size() == 4)\n              {\n                // generate 4 chemical properties for the molecules\n                realfprop[0] = calcExactMW(mol);\n                realfprop[1] = calcClogP(mol);\n                realfprop[2] = calcTPSA(mol);\n                realfprop[3] = calcLabuteASA(mol);\n                // add this task to the thread inside the threads vector\n                thread_pool.emplace_back([&]() { \n                  write_to_binary<array<float, 4>>(realfprop, rfprop);\n                }); // emplace_back to avoid copying, so that we can pass the parameters directly\n                //write_to_binary<array<float, 4>>(realfprop, rfprop_file);\n\n                // generate 5 chemical properties for the molecules\n                realiprop[0] = mol.getNumHeavyAtoms();\n                realiprop[1] = calcNumHBD(mol);\n                realiprop[2] = calcNumHBA(mol);\n                realiprop[3] = calcNumRotatableBonds(mol);\n                realiprop[4] = calcNumRings(mol);\n                // add this task to the thread inside the threads vector\n                thread_pool.emplace_back([&]() {\n         \t  write_to_binary<array<int16_t, 5>>(realiprop, riprop);\n                });\n\n                std::cout << confIds.size() << \" Conformers of \" << compound << '\\t' << smiles << \" are succefully generated!\" << endl;\n                id_file << compound << '\\n';\n                smilesfile << smiles << '\\n';\n                smifile << compound << '\\t' << smiles << '\\n';\n                // Writing conformers in the output SDF\n                for (const auto confId : confIds)\n                {\n                  writer.write(mol, confId);\n                }\n\n                // generate the USRCAT features for each conformer\n                thread_pool.emplace_back([&]() {\n                  for (int i = 0; i < 4; i++)\n                  {\n                    features = usrcat_features(mol, i);\n                    write_to_binary<array<float, 60>>(features, usrcatf64);\n                  }\n                });\n\n                /*for (int i = 0; i < 4; i++)\n                {\n                  features = usrcat_features(mol, i);\n                  write_to_binary<array<float, 60>>(features, usrcatf64);\n                }*/\n                processed_ligand++;\n                break;\n              }\n              else\n              {\n                std::cout << \"Molecule doesn't have 4 conformers!\" << endl;\n                break;\n              }\n            }\n            catch (const MolSanitizeException& e)\n            {\n              cerr << \"Kekulization problem!\" << endl;\n              break;\n            }\n          }\n        }\n      }\n      // join the threads\n      for (thread& th : thread_pool)\n      {\n        th.join();\n      }\n      thread_pool.clear();\n      all_ligands++;\n    }\n  }\n  std::cout << \"Process completed! for \" << all_ligands << \" compounds\" << endl;\n}\n", "meta": {"hexsha": "2ca9f4c9c9b41a6f92790fd8c95df53c3c031c9c", "size": 13342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EmbedAllAndGenerateSMI.cpp", "max_stars_repo_name": "sawsimeon/USR_VS_UTILITIES", "max_stars_repo_head_hexsha": "c3cdbf390d96e26e164186a0e46b8d11a1c74c60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EmbedAllAndGenerateSMI.cpp", "max_issues_repo_name": "sawsimeon/USR_VS_UTILITIES", "max_issues_repo_head_hexsha": "c3cdbf390d96e26e164186a0e46b8d11a1c74c60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-30T13:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:46:53.000Z", "max_forks_repo_path": "EmbedAllAndGenerateSMI.cpp", "max_forks_repo_name": "LouaiKB/USR_VS_UTILITIES", "max_forks_repo_head_hexsha": "683b44a25d6f0f8866ff18ea9e0d6b1740c07123", "max_forks_repo_licenses": ["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.1890547264, "max_line_length": 142, "alphanum_fraction": 0.574501574, "num_tokens": 3710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.03904829146815224, "lm_q1q2_score": 0.018305473026039295}}
{"text": "#include <sstream>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <boost/serialization/export.hpp>\n\n#include \"Epsilon.hxx\"\nBOOST_CLASS_EXPORT(Epsilon)\n#include \"eval.hxx\"\n\nEpsilon::Epsilon(char const i1, char const i2, char const i3, char const i4) : i1(i1), i2(i2), i3(i3), i4(i4) {}\n\ntemplate<class Archive>\nvoid Epsilon::serialize (Archive & ar, unsigned int const) {\n  ar & boost::serialization::base_object<Node>(*this);\n  ar & i1;\n  ar & i2;\n  ar & i3;\n  ar & i4;\n}\n\nvoid Epsilon::exchangeTensorIndices (std::map<char, char> const & exchange_map) {\n  auto it = exchange_map.find(i1);\n  if (it != exchange_map.end()) {\n    i1 = it->second;\n  }\n  it = exchange_map.find(i2);\n  if (it != exchange_map.end()) {\n    i2 = it->second;\n  }\n  it = exchange_map.find(i3);\n  if (it != exchange_map.end()) {\n    i3 = it->second;\n  }\n  it = exchange_map.find(i4);\n  if (it != exchange_map.end()) {\n    i4 = it->second;\n  }\n}\n\nint Epsilon::sortIndices() {\n  int ret = 1;\n  bool swapped = true;\n  do {\n    swapped = false;\n    if (i1 == i2) {\n      ret = 0;\n    } else if (i1 > i2) {\n      std::swap (i1, i2);\n      swapped = true;\n      ret *= -1;\n    }\n    if (i2 == i3) {\n      ret = 0;\n    } else if (i2 > i3) {\n      std::swap (i2, i3);\n      swapped = true;\n      ret *= -1;\n    }\n    if (i3 == i4) {\n      ret = 0;\n    } else if (i3 > i4) {\n      std::swap (i3, i4);\n      swapped = true;\n      ret *= -1;\n    }\n  } while (swapped);\n\n  return ret;\n}\n\nchar Epsilon::order () const { return 0; }\n\nstd::string Epsilon::print () const {\n  std::stringstream ss;\n  ss << \"Epsilon {\" << i1 << i2 << i3 << i4 << \"}\";\n\n  return ss.str();\n}\n\nstd::string Epsilon::printMaple () const {\n  std::stringstream ss;\n  ss << \"LeviCivita[~\" << i1 << \", ~\" << i2 << \", ~\" << i3 << \", ~\" << i4 << \"]\";\n\n  return ss.str();\n}\n\nint Epsilon::evaluate(std::map <char, char> const & eval_map) const {\n  return (- 1 * epsilon_eval.at(64 * eval_map.at(i1)\n                       + 16 * eval_map.at(i2)\n                       +  4 * eval_map.at(i3)\n                       +      eval_map.at(i4)));\n}\n\nmpq_class Epsilon::symmetrize() {\n  return sortIndices();\n}\n\nbool Epsilon::containsIndex (char i) const {\n  return (i == i1 || i == i2 || i == i3 || i == i4);\n}\n\nint Epsilon::applyTensorSymmetries (int parity) {\n  int epsilon_parity = sortIndices();\n  return (parity * epsilon_parity);\n}\n\nbool Epsilon::lessThan(Node const * other) const {\n  auto other_eps = static_cast<Epsilon const *>(other);\n  if (i1 < other_eps->i1) {\n    return true;\n  } else if (i1 > other_eps->i1) {\n    return false;\n  } else if (i2 < other_eps->i2) {\n    return true;\n  } else if (i2 > other_eps->i2) {\n    return false;\n  } else if (i3 < other_eps->i3) {\n    return true;\n  } else if (i3 > other_eps->i3) {\n    return false;\n  } else if (i4 < other_eps->i4) {\n    return true;\n  } else {\n    return false;\n  }\n}\n\nbool Epsilon::equals(Node const * other) const {\n  if (other == nullptr) {\n    return false;\n  } else if (typeid(*this) != typeid(*other)) {\n    return false;\n  } else {\n    auto other_eps = static_cast<Epsilon const *> (other);\n    return (i1 == other_eps->i1 && i2 == other_eps->i2 && i3 == other_eps->i3 && i4 == other_eps->i4);\n  }\n}\n\nstd::unique_ptr<Node> Epsilon::clone () const {\n  return std::unique_ptr<Node>(new Epsilon(*this));\n}\n\nstd::tuple<int, char, std::map<char, char>> Epsilon::multiplyWithOther3 (char j1, char j2, char j3) const {\n  assert (j1 != j2 && j1 != j3 && j2 != j3);\n  bool const is_contained_j1 = containsIndex (j1);\n  bool const is_contained_j2 = containsIndex (j2);\n  bool const is_contained_j3 = containsIndex (j3);\n  std::vector<char> contained;\n  if (is_contained_j1) { contained.push_back (j1); }\n  if (is_contained_j2) { contained.push_back (j2); }\n  if (is_contained_j3) { contained.push_back (j3); }\n\n  if (contained.size() == 0) {\n    return {-24, i1, {{j1, i2}, {j2, i3}, {j3, i4}}};\n  } else if (contained.size() == 3) {\n    std::vector<char> i_vec {i1, i2, i3, i4};\n    int parity = 1;\n    if (std::find (contained.cbegin(), contained.cend(), i_vec[0]) == contained.cend()) {\n      // do nothing\n    } else if (std::find (contained.cbegin(), contained.cend(), i_vec[1]) == contained.cend()) {\n      std::iter_swap (i_vec.begin(), i_vec.begin() + 1);\n      parity *= -1;\n    } else if (std::find (contained.cbegin(), contained.cend(), i_vec[2]) == contained.cend()) {\n      std::iter_swap (i_vec.begin(), i_vec.begin() + 2);\n      parity *= -1;\n    } else {\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[3]) == contained.cend());\n      std::iter_swap (i_vec.begin(), i_vec.begin() + 3);\n      parity *= -1;\n    }\n    if ( (i_vec[1] == j1 && i_vec[2] == j2 && i_vec[3] == j3) ||\n         (i_vec[2] == j1 && i_vec[3] == j2 && i_vec[1] == j3) ||\n         (i_vec[3] == j1 && i_vec[1] == j2 && i_vec[2] == j3) ) {\n      // sorted\n    } else {\n      // unsorted\n      assert ( (i_vec[1] == j1 && i_vec[3] == j2 && i_vec[2] == j3) ||\n               (i_vec[3] == j1 && i_vec[2] == j2 && i_vec[1] == j3) ||\n               (i_vec[2] == j1 && i_vec[1] == j2 && i_vec[3] == j3));\n      parity *= -1;\n    }\n    return {-6 * parity, i_vec[0], { }};\n  } else if (contained.size() == 2) {\n    std::vector<char> i_vec {i1, i2, i3, i4};\n    std::vector<char> j_vec {j1, j2, j3};\n    int parity = 1;\n    if (!is_contained_j1) {\n      // nothing\n    } else if (!is_contained_j2) {\n      j_vec = {j2, j1, j3};\n      parity *= -1;\n    } else {\n      assert (!is_contained_j3);\n      j_vec = {j3, j1, j2};\n    }\n    if (std::find (contained.cbegin(), contained.cend(), i_vec[0]) == contained.cend()) {\n      if (std::find (contained.cbegin(), contained.cend(), i_vec[1]) == contained.cend()) {\n        // do nothing\n      } else if (std::find (contained.cbegin(), contained.cend(), i_vec[2]) == contained.cend()) {\n        std::iter_swap (i_vec.begin() + 1, i_vec.begin() + 2);\n        parity *= -1;\n      } else {\n        assert (std::find (contained.cbegin(), contained.cend(), i_vec[3]) == contained.cend());\n        std::iter_swap (i_vec.begin() + 1, i_vec.begin() + 3);\n        parity *= -1;\n      }\n    } else if (std::find (contained.cbegin(), contained.cend(), i_vec[1]) == contained.cend()) {\n      std::iter_swap (i_vec.begin(), i_vec.begin() + 1);\n      parity *= -1;\n      if (std::find (contained.cbegin(), contained.cend(), i_vec[2]) == contained.cend()) {\n        std::iter_swap (i_vec.begin() + 1, i_vec.begin() + 2);\n        parity *= -1;\n      } else {\n        assert (std::find (contained.cbegin(), contained.cend(), i_vec[3]) == contained.cend());\n        std::iter_swap (i_vec.begin() + 1, i_vec.begin() + 3);\n        parity *= -1;\n      }\n    } else {\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[2]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[3]) == contained.cend());\n      std::iter_swap (i_vec.begin(), i_vec.begin() + 2);\n      std::iter_swap (i_vec.begin() + 1, i_vec.begin() + 3);\n    }\n    if (i_vec[2] == contained[0]) {\n      // sorted\n    } else {\n      assert (i_vec[2] == contained[1]);\n      parity *= -1;\n    }\n    return { -4 * parity, i_vec[0], {{j_vec[0], i_vec[1]}} };\n  } else if (contained.size() == 1) {\n    std::vector<char> i_vec {i1, i2, i3, i4};\n    std::vector<char> j_vec {j1, j2, j3};\n    int parity = 1;\n    if (!is_contained_j1) {\n      if (!is_contained_j2) {\n        // nothing\n      } else {\n        assert (!is_contained_j3);\n        j_vec = {j1, j3, j2};\n        parity *= -1;\n      }\n    } else {\n      assert (!is_contained_j2);\n      assert (!is_contained_j3);\n      j_vec = {j2, j3, j1};\n    }\n    if (std::find (contained.cbegin(), contained.cend(), i_vec[0]) != contained.cend()) {\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[1]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[2]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[3]) == contained.cend());\n      std::iter_swap (i_vec.begin(), i_vec.begin() + 1);\n      std::iter_swap (i_vec.begin() + 1, i_vec.begin() + 2);\n      std::iter_swap (i_vec.begin() + 2, i_vec.begin() + 3);\n      parity *= -1;\n    } else if (std::find (contained.cbegin(), contained.cend(), i_vec[1]) != contained.cend()) {\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[0]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[2]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[3]) == contained.cend());\n      std::iter_swap (i_vec.begin() + 1, i_vec.begin() + 2);\n      std::iter_swap (i_vec.begin() + 2, i_vec.begin() + 3);\n    } else if (std::find (contained.cbegin(), contained.cend(), i_vec[2]) != contained.cend()) {\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[0]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[1]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[3]) == contained.cend());\n      std::iter_swap (i_vec.begin() + 2, i_vec.begin() + 3);\n      parity *= -1;\n    } else if (std::find (contained.cbegin(), contained.cend(), i_vec[3]) != contained.cend()) {\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[0]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[1]) == contained.cend());\n      assert (std::find (contained.cbegin(), contained.cend(), i_vec[2]) == contained.cend());\n      // nothing\n    }\n    return { -6 * parity, i_vec[0], {{j_vec[0], i_vec[1]}, {j_vec[1], i_vec[2]}} };\n  } else {\n    assert (false);\n    return {0, 0, {}};\n  }\n}\n", "meta": {"hexsha": "00f9ecf30b8adb2c1e5901749567c0cdc9b08852", "size": 9815, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/Epsilon.cxx", "max_stars_repo_name": "nilsalex/tensor-trees", "max_stars_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Epsilon.cxx", "max_issues_repo_name": "nilsalex/tensor-trees", "max_issues_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Epsilon.cxx", "max_forks_repo_name": "nilsalex/tensor-trees", "max_forks_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9288256228, "max_line_length": 112, "alphanum_fraction": 0.560774325, "num_tokens": 3135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.039638836690151356, "lm_q1q2_score": 0.018274168826580436}}
{"text": "/*  Sirikata\n *  MeshSimplifier.cpp\n *\n *  Copyright (c) 2010, Tahir Azim.\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\n *    the documentation and/or other materials provided with the\n *    distribution.\n *  * Neither the name of Sirikata nor the names of its contributors may\n *    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\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 OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <sirikata/mesh/MeshSimplifier.hpp>\n\n#include <boost/functional/hash.hpp>\n\n#include <sirikata/core/util/Timer.hpp>\n#ifdef _WIN32\n#include <float.h>\n#else\n#include <cmath>\n#endif\n#include <math.h>\n#include <iomanip>\n#define SIMPLIFY_LOG(lvl, msg) SILOG(simplify, lvl, msg)\n\nnamespace Sirikata {\n\nnamespace Mesh {\n\n#define SIMPLIFIER_INVALID_VECTOR Vector3f(-1000000,-1000000,-1000000)\n\nclass IndexedFaceContainer {\npublic:\n\n  bool valid;\n  uint32 idx1;\n  uint32 idx2;\n  uint32 idx3;\n\n  IndexedFaceContainer(uint32 i, uint32 j, uint32 k) :\n    valid(true), idx1(i), idx2(j), idx3(k)\n  {\n  }\n\n  size_t hash() const {\n      size_t seed = 0;\n\n      std::vector<uint32> sortedIndices;\n      sortedIndices.push_back(idx1);\n      sortedIndices.push_back(idx2);\n      sortedIndices.push_back(idx3);\n      std::sort(sortedIndices.begin(), sortedIndices.end());\n\n      seed = 0;\n      boost::hash_combine(seed, sortedIndices[0]);\n      boost::hash_combine(seed, sortedIndices[1]);\n      boost::hash_combine(seed, sortedIndices[2]);\n\n      return seed;\n  }\n\n  bool operator==(const IndexedFaceContainer&other) const {\n    std::vector<uint32> sortedIndices;\n    sortedIndices.push_back(idx1);\n    sortedIndices.push_back(idx2);\n    sortedIndices.push_back(idx3);\n    std::sort(sortedIndices.begin(), sortedIndices.end());\n\n    std::vector<uint32> sortedIndices2;\n    sortedIndices2.push_back(other.idx1);\n    sortedIndices2.push_back(other.idx2);\n    sortedIndices2.push_back(other.idx3);\n    std::sort(sortedIndices2.begin(), sortedIndices2.end());\n\n    return (sortedIndices[0] == sortedIndices2[0]\n            && sortedIndices[1] == sortedIndices2[1]\n            && sortedIndices[2] == sortedIndices2[2] );\n  }\n\n  class Hasher{\n  public:\n        size_t operator() (const IndexedFaceContainer& g) const {\n            return g.hash();\n        }\n  };\n\n\n};\n\nclass FaceContainer {\npublic:\n  Vector3f v1;\n  Vector3f v2;\n  Vector3f v3;\n\n  FaceContainer(Vector3f& v1, Vector3f& v2, Vector3f& v3) {\n    this->v1 = v1;\n    this->v2 = v2;\n    this->v3 = v3;\n  }\n\n  FaceContainer() {\n  }\n\n  size_t hash() const {\n      size_t seed = 0;\n\n      size_t pos1Hash = v1.hash();\n      size_t pos2Hash = v2.hash();\n      size_t pos3Hash = v3.hash();\n\n      std::vector<size_t> facevecs;      \n      facevecs.push_back(pos1Hash);facevecs.push_back(pos2Hash);facevecs.push_back(pos3Hash);\n      sort(facevecs.begin(), facevecs.end());      \n\n      seed = 0;\n      boost::hash_combine(seed, facevecs[0]);\n      boost::hash_combine(seed, facevecs[1]);\n      boost::hash_combine(seed, facevecs[2]);\n\n      return seed;\n  }\n\n  bool operator==(const FaceContainer&other)const {\n    if (v1+v2+v3 != other.v1+other.v2+other.v3) return false;\n\n    //There is a more elegant way to do this, but this is\n    //easier to code and faster.\n    if (v1 == other.v1) {\n       if ((v2==other.v2 && v3==other.v3) ||\n           (v2==other.v3 && v3==other.v2))\n          return true;\n    }\n\n    if (v1 == other.v2) {\n      if ((v2==other.v1 && v3==other.v3) ||\n          (v2==other.v3 && v3==other.v1))\n        return true;\n    }\n\n    if (v1 == other.v3) {\n     if ((v2==other.v1 && v3==other.v2) ||\n         (v2==other.v2 && v3==other.v1))\n       return true;\n    }\n\n    return false;\n  }\n\n  class Hasher{\n  public:\n        size_t operator() (const FaceContainer& g) const {\n            return g.hash();\n        }\n  };\n\n};\n\n\nclass GeomContainer {\npublic:\n  uint32 geomIdx;\n  uint32 vertexIdx;\n\n  GeomContainer(int g, int v) {\n    geomIdx = g;\n    vertexIdx = v;\n  }\n\n  GeomContainer() {\n    geomIdx = vertexIdx = 0;\n  }\n\n  size_t hash() const {\n      size_t seed = 0;\n      boost::hash_combine(seed, geomIdx);\n      boost::hash_combine(seed, vertexIdx);\n\n      return seed;\n  }\n\n  bool operator==(const GeomContainer&other)const {\n        return geomIdx==other.geomIdx && vertexIdx==other.vertexIdx;\n  }\n\n  class Hasher{\n  public:\n        size_t operator() (const GeomContainer& g) const {\n            return g.hash();\n        }\n  };\n\n};\n\nclass GeomPairContainer {\npublic:\n  uint32 mGeomIdx;\n  uint32 mVertexIdx1;\n  uint32 mVertexIdx2;\n  float64 mCost;\n  Vector3f mReplacementVector;\n\n  void init(uint32 g, uint32 v1, uint32 v2) {\n    mGeomIdx = g;\n    mVertexIdx1 = v1;\n    mVertexIdx2 = v2;\n\n    if (mVertexIdx1 > mVertexIdx2) {\n      uint32 temp = mVertexIdx1;\n      mVertexIdx1 = mVertexIdx2;\n      mVertexIdx2 = temp;\n    }\n\n    mCost = 0;\n  }\n\n  GeomPairContainer(uint32 g, uint32 v1, uint32 v2) {\n    init(g,v1,v2);\n  }\n\n  GeomPairContainer(uint32 g, uint32 v1, uint32 v2, float64 cost)  {\n    init(g,v1,v2);\n    mCost = cost;\n  }\n\n  GeomPairContainer() {\n    mGeomIdx = mVertexIdx1 = mVertexIdx2 = 0;\n    mCost = 0;\n  }\n\n  size_t hash() const {\n      size_t seed = 0;\n      boost::hash_combine(seed, mGeomIdx);\n      boost::hash_combine(seed, mVertexIdx1);\n      boost::hash_combine(seed, mVertexIdx2);\n\n      return seed;\n  }\n\n  bool operator==(const GeomPairContainer&other)const {\n    return mGeomIdx==other.mGeomIdx && mVertexIdx1==other.mVertexIdx1 && mVertexIdx2==other.mVertexIdx2;\n  }\n\n  bool operator<(const GeomPairContainer&other) const {\n\n    if (*this == other) return false;\n\n    if (mCost == other.mCost) {\n      if (mGeomIdx == other.mGeomIdx) {\n        if (mVertexIdx1 == other.mVertexIdx1) {\n          assert(mVertexIdx2 != other.mVertexIdx2);\n          return mVertexIdx2 < other.mVertexIdx2;\n        }\n\n        return mVertexIdx1 < other.mVertexIdx1;\n      }\n\n      return mGeomIdx < other.mGeomIdx;\n    }\n\n    return mCost < other.mCost;\n  }\n\n  class Hasher{\n  public:\n        size_t operator() (const GeomPairContainer& g) const {\n            return g.hash();\n        }\n  };\n\n};\nbool custom_isnan (double data) {\n#ifdef _WIN32\n    return _isnan(data);\n#else\n    return std::isnan(data);\n#endif\n}\n\nbool optimize(Matrix4x4d& Q, const Vector3f& v11, const Vector3f& v21, Vector3f& best) {\n    Vector3d v1(v11.x,v11.y,v11.z);\n    Vector3d v2(v21.x,v21.y,v21.z);\n\n    ///First compute cost of contracting to endpoint\n    Vector4d vbar4f (v1.x, v1.y, v1.z, 1);\n    float64 cost1 = vbar4f[0]*vbar4f[0]*Q(0,0) + 2*vbar4f[0]*vbar4f[1]*Q(0,1) + 2*vbar4f[0]*vbar4f[2]*Q(0,2) + 2*vbar4f[0]*Q(0,3)\n      + vbar4f[1]*vbar4f[1]*Q(1,1) + 2*vbar4f[1]*vbar4f[2]*Q(1,2) + 2*vbar4f[1]*Q(1,3)\n      + vbar4f[2]*vbar4f[2]*Q(2,2) + 2*vbar4f[2]*Q(2,3)\n      + Q(3,3);\n    cost1 = (cost1 < 0.0) ? -cost1 : cost1;\n\n    vbar4f = Vector4d (v2.x, v2.y, v2.z, 1);\n    float64 cost2 = vbar4f[0]*vbar4f[0]*Q(0,0) + 2*vbar4f[0]*vbar4f[1]*Q(0,1) + 2*vbar4f[0]*vbar4f[2]*Q(0,2) + 2*vbar4f[0]*Q(0,3)\n      + vbar4f[1]*vbar4f[1]*Q(1,1) + 2*vbar4f[1]*vbar4f[2]*Q(1,2) + 2*vbar4f[1]*Q(1,3)\n      + vbar4f[2]*vbar4f[2]*Q(2,2) + 2*vbar4f[2]*Q(2,3)\n      + Q(3,3);\n    cost2 = (cost2 < 0.0) ? -cost2 : cost2;\n\n    //Now find cost of contracting to an \"optimal\" vertex\n    Vector3d d = v1 - v2;\n    Matrix3x3d A(Vector3d(Q(0,0), Q(0,1), Q(0,2)),\n                 Vector3d(Q(0,1), Q(1,1), Q(1,2)),\n                 Vector3d(Q(0,2), Q(1,2), Q(2,2)),\n                 ROWS());       //tensor of Q;\n\n    Vector3d Av2 = A*v2;\n    Vector3d Ad  = A*d;\n\n    float64 denom = 2.0*(d.dot(Ad));\n    if (   denom <= 1e-12 ) {\n      if (cost2 < cost1) best = v21;\n      else best = v11;\n\n      return false;\n    }\n\n    Vector3d vec(Q(3,0),Q(3,1),Q(3,2))  ;\n    double a =  ( -2.0*(vec.dot(d)) - (d.dot(Av2)) - (v2.dot(Ad)) ) / ( 2.0*(d.dot(Ad)) );\n\n    if( a<0.0 ) a=0.0; else if( a>1.0 ) a=1.0;\n\n    Vector3d best64 = a*d + v2;\n    best.x = best64.x; best.y = best64.y; best.z = best64.z;\n\n    //Optimal found: now find cost of contracting to it\n    vbar4f = Vector4d (best.x, best.y, best.z, 1);\n    float64 cost3 = vbar4f[0]*vbar4f[0]*Q(0,0) + 2*vbar4f[0]*vbar4f[1]*Q(0,1) + 2*vbar4f[0]*vbar4f[2]*Q(0,2) + 2*vbar4f[0]*Q(0,3)\n      + vbar4f[1]*vbar4f[1]*Q(1,1) + 2*vbar4f[1]*vbar4f[2]*Q(1,2) + 2*vbar4f[1]*Q(1,3)\n      + vbar4f[2]*vbar4f[2]*Q(2,2) + 2*vbar4f[2]*Q(2,3)\n      + Q(3,3);\n    \n    if (cost1<cost2 && cost1<cost3){\n      best = v11;\n    }\n    else if (cost2<cost1 && cost2<cost3){\n      best = v21;\n    }\n\n    return true;\n}\n\nvoid computeCosts(Mesh::MeshdataPtr agg_mesh,\n                  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, Matrix4x4d> >& submeshPositionQs,\n                  std::set<GeomPairContainer>& vertexPairs,\n                  std::tr1::unordered_map<GeomPairContainer, float64, GeomPairContainer::Hasher>& pairPriorities,\n                  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, std::tr1::unordered_set<uint32> > >& submeshNeighborVertices,\n                  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, std::vector<uint32> > >& vertexToFacesMap,\n                  std::tr1::unordered_map<GeomPairContainer, uint32, GeomPairContainer::Hasher>& pairFrequency,\n                  std::tr1::unordered_map<GeomContainer, uint8, GeomContainer::Hasher>& pairNonCollapsible\n                 )\n{\n\n  for (uint32 i = 0;  i < agg_mesh->geometry.size(); i++) {\n\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n    std::tr1::unordered_map<uint32, Matrix4x4d>& positionQs = submeshPositionQs[i];\n    std::tr1::unordered_map<uint32, std::tr1::unordered_set<uint32> >& neighborVertices = submeshNeighborVertices[i];\n    std::tr1::unordered_map<uint32, std::vector<uint32> >& submeshVertexToFacesMap = vertexToFacesMap[i];\n\n    for (uint32 j = 0; j < curGeometry.positions.size(); j++) {\n      \n      if (neighborVertices.find(j) == neighborVertices.end()) continue;\n\n      bool j_edgeVertex = (submeshVertexToFacesMap[j].size() == 1);\n\n      const Vector3f& position = curGeometry.positions[j];\n\n      Matrix4x4d Q = positionQs[j];\n\n      std::tr1::unordered_set<uint32>& neighbors = neighborVertices[j];\n\n      for (std::tr1::unordered_set<uint32>::iterator neighbor_it = neighbors.begin(); neighbor_it != neighbors.end(); neighbor_it++) {\n        uint32 neighbor = *neighbor_it;\n\n        bool neighbor_edgeVertex = (submeshVertexToFacesMap[neighbor].size() == 1);\n\n        Vector3f best;\n        \n        const Vector3f& neighborPosition = curGeometry.positions[neighbor];\n        Matrix4x4d Q = positionQs[j] + positionQs[neighbor];\n\n        optimize(Q, position, neighborPosition, best);\n        \n        Vector4d vbar4f (best.x, best.y, best.z, 1);\n\n        float64 cost = vbar4f[0]*vbar4f[0]*Q(0,0) + 2*vbar4f[0]*vbar4f[1]*Q(0,1) + 2*vbar4f[0]*vbar4f[2]*Q(0,2) + 2*vbar4f[0]*Q(0,3)\n          + vbar4f[1]*vbar4f[1]*Q(1,1) + 2*vbar4f[1]*vbar4f[2]*Q(1,2) + 2*vbar4f[1]*Q(1,3)\n          + vbar4f[2]*vbar4f[2]*Q(2,2) + 2*vbar4f[2]*Q(2,3)\n          + Q(3,3);\n        cost = (cost < 0.0) ? -cost : cost;\n        \n        uint32 idx1 = j, idx2 = neighbor;\n        if (best == position) {\n          uint32 temp = idx1;\n          idx1 = idx2;\n          idx2 = temp;\n        }\n\n        GeomPairContainer gpc(i, idx1, idx2);\n\n        //Insert this cost as the cost of the edge if the edge hasnt been inserted \n        //before or if this cost is less than the previously computed cost.\n        if (pairPriorities[gpc] == -1 || (pairPriorities[gpc] != -1 && cost < pairPriorities[gpc]) ) { \n          gpc.mCost = pairPriorities[gpc];\n          vertexPairs.erase(gpc);\n\n          gpc.mReplacementVector = best;\n\n          gpc.mCost = cost;\n          pairPriorities[gpc] = gpc.mCost;\n          vertexPairs.insert(gpc);\n        }\n      }\n    }\n  }\n}\n\ninline uint32 findMappedVertex(std::tr1::unordered_map<int, int>& vertexMapping, uint32 idx) {\n  uint32 startIdx = idx;\n\n  int countIter = 0;\n  while (vertexMapping.find(idx) != vertexMapping.end()) {\n    countIter++;\n    if ((int)idx == vertexMapping[idx]) {\n      break;\n    }\n    idx = vertexMapping[idx];\n  }\n\n  if (countIter > 1) {\n    vertexMapping[startIdx] = idx;\n  }\n\n  return idx;\n}\n\nvoid computeCosts(Mesh::MeshdataPtr agg_mesh, uint32 geomIdx, uint32 sourcePositionIdx, uint32 targetPositionIdx,\n                  std::tr1::unordered_map<int, int>& vertexMapping,\n                  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, Matrix4x4d> >& submeshPositionQs,\n                  std::set<GeomPairContainer>& vertexPairs,\n                  std::tr1::unordered_map<GeomPairContainer, float64, GeomPairContainer::Hasher>& pairPriorities,\n                  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, std::tr1::unordered_set<uint32> > >& submeshNeighborVertices,\n                  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, std::vector<uint32> > >& vertexToFacesMap,\n                  std::tr1::unordered_map<GeomPairContainer, uint32, GeomPairContainer::Hasher>& pairFrequency,\n                  std::tr1::unordered_map<GeomContainer, uint8, GeomContainer::Hasher>& pairNonCollapsible\n                  )\n{\n  \n  SubMeshGeometry& curGeometry = agg_mesh->geometry[geomIdx];\n  std::tr1::unordered_map<uint32, Matrix4x4d>& positionQs = submeshPositionQs[geomIdx];\n  std::tr1::unordered_map<uint32, std::tr1::unordered_set<uint32> >& neighborVertices = submeshNeighborVertices[geomIdx];\n  std::tr1::unordered_map<uint32, std::vector<uint32> >& submeshVertexToFacesMap = vertexToFacesMap[geomIdx];\n\n  targetPositionIdx = findMappedVertex(vertexMapping, targetPositionIdx);\n\n  const Vector3f& position = curGeometry.positions[targetPositionIdx];\n\n  std::tr1::unordered_set<uint32>& neighbors = neighborVertices[targetPositionIdx];\n\n\n  for (std::tr1::unordered_set<uint32>::iterator neighbor_it = neighbors.begin(); neighbor_it != neighbors.end(); neighbor_it++) {   \n    uint32 neighborIdx = *neighbor_it;\n\n    neighborIdx = findMappedVertex(vertexMapping, neighborIdx);\n\n    if (neighborIdx == targetPositionIdx) continue;\n\n    uint32 idx1 = targetPositionIdx;\n    uint32 idx2 = neighborIdx;\n\n    float64 cost = 0;        \n    const Vector3f& neighborPosition = curGeometry.positions[neighborIdx];\n    Matrix4x4d Q = positionQs[targetPositionIdx] + positionQs[neighborIdx];\n\n    Vector3f best;\n    optimize(Q, position, neighborPosition, best);\n\n    Vector4d vbar4f (best.x, best.y, best.z, 1);\n    cost = vbar4f[0]*vbar4f[0]*Q(0,0) + 2*vbar4f[0]*vbar4f[1]*Q(0,1) + 2*vbar4f[0]*vbar4f[2]*Q(0,2) + 2*vbar4f[0]*Q(0,3)\n            + vbar4f[1]*vbar4f[1]*Q(1,1) + 2*vbar4f[1]*vbar4f[2]*Q(1,2) + 2*vbar4f[1]*Q(1,3)\n            + vbar4f[2]*vbar4f[2]*Q(2,2) + 2*vbar4f[2]*Q(2,3)\n            + Q(3,3);\n    cost = (cost < 0.0) ? -cost : cost;\n\n    if (best == position) {\n      uint32 temp = idx1;\n      idx1 = idx2;\n      idx2 = temp;\n    }\n\n    //Remove the previous vertex pair that existed before one vertex collapsed.\n    GeomPairContainer gpc(geomIdx, sourcePositionIdx, neighborIdx);\n    gpc.mCost = pairPriorities[gpc];\n    vertexPairs.erase(gpc);\n    gpc = GeomPairContainer(geomIdx, neighborIdx, sourcePositionIdx);\n    gpc.mCost = pairPriorities[gpc];\n    vertexPairs.erase(gpc);\n    \n    //Insert this vertex pair with the new cost, but first remove this pair if it already exists, then re-insert it.\n    gpc = GeomPairContainer(geomIdx, idx1, idx2);\n    gpc.mCost = pairPriorities[gpc];\n    vertexPairs.erase(gpc);\n    gpc = GeomPairContainer(geomIdx, idx2, idx1);\n    gpc.mCost = pairPriorities[gpc];\n    vertexPairs.erase(gpc);        \n\n    gpc = GeomPairContainer(geomIdx, idx1, idx2);\n    gpc.mCost = pairPriorities[gpc];\n\n    gpc.mCost = cost;\n    gpc.mReplacementVector = best;\n    pairPriorities[gpc] = gpc.mCost;\n\n    vertexPairs.insert(gpc); \n  }\n}\n\nbool MeshSimplifier::okToApplyStochastic(float totalInstances, \n\t\t\t\t\t std::tr1::unordered_map<uint32, uint32>& submeshInstanceCount,  \n\t\t\t\t\t std::map<int, BoundingBox3f>& instanceToBBoxMap)\n{\n  if (instanceToBBoxMap.size() == 0) return false;\n\n  bool canApplyStochastic = false;\n  for (std::tr1::unordered_map<uint32, uint32>::iterator it = submeshInstanceCount.begin();\n         it != submeshInstanceCount.end(); it++)\n  {\n      uint32 submeshIdx = it->first;\n      float freq = it->second;\n\n      if (freq/totalInstances >= 0.05 && freq >= 1000) {\n        canApplyStochastic = true;\n        break;\n      }\n  }\n\n  return canApplyStochastic;\n}\n\nbool MeshSimplifier::applyStochastic(float totalInstances, \n\t\t\t\t   Mesh::MeshdataPtr agg_mesh,\n\t\t\t\t   int32 targetFaces,\n\t\t\t\t   std::tr1::unordered_map<uint32, uint32>& submeshInstanceCount,\n\t\t\t\t   std::tr1::unordered_map<int, std::tr1::unordered_map<int,int> >& vertexMapping1,\n              \t\t\t   std::map<int, BoundingBox3f>& instanceToBBoxMap\n\t\t\t\t   )\n{\n    //if it gets in here, I think it's ok to assume that\n    //all submeshes have 4 or fewer triangles.\n\n    std::set<uint32> nodesToRemove;\n    for (std::tr1::unordered_map<uint32, uint32>::iterator it = submeshInstanceCount.begin(); \n         it != submeshInstanceCount.end(); it++)\n    {\n      uint32 submeshIdx = it->first;\n      float freq = it->second;\n\n      //Assuming 3 triangles per submesh, targetFaces/3.0 is the number of targetInstances.\n      //So for the current submesh, # of faces included should be that number times\n      //the ratio of instances of the current submesh.\n      float numberIncluded = freq/totalInstances * (targetFaces/3.0);\n      float percentIncluded = numberIncluded / freq * 100;\n\n      //if this submesh is referenced by less than 5% of the total instances in the mesh\n      //and it has fewer than 1000 instances, then just keep it.\n      if (freq/totalInstances < 0.05 && freq < 1000) {\n        continue;\n      }\n\n      //First determine which instances can be immediately eliminated because\n      //they cannot be inflated, or otherwise, go outside bounding box.\n      std::set<uint32> nodesTooBig;\n      for (uint32 i = 0; i < agg_mesh->nodes.size(); i++) {\n        const GeometryInstance& geomInstance = agg_mesh->instances[i];\n        int geomIdx = geomInstance.geometryIndex;\n\n        if (geomIdx == submeshIdx) {\n\n          Node& node = agg_mesh->nodes[i];\n          SubMeshGeometry& curGeometry = agg_mesh->geometry[geomIdx];\n          std::tr1::unordered_map<int, int>& vertexMapping = vertexMapping1[geomIdx];\n          assert( instanceToBBoxMap.find(i) != instanceToBBoxMap.end());\n          BoundingBox3f& bbox = instanceToBBoxMap[i];\n\n          float currentScale = sqrtf(100.0/percentIncluded);\n          Matrix4x4f transform = node.transform * Matrix4x4f::scale(currentScale);\n          bool transformOK = true;\n\n\t  for (uint32 j = 0; j < curGeometry.primitives.size() && transformOK; j++) {\n              if (curGeometry.primitives[j].primitiveType != SubMeshGeometry::Primitive::TRIANGLES) continue;\n\n              for (uint32 k = 0; k+2 < curGeometry.primitives[j].indices.size() && transformOK; k+=3) {\n                unsigned short idx = curGeometry.primitives[j].indices[k];\n                unsigned short idx2 = curGeometry.primitives[j].indices[k+1];\n                unsigned short idx3 = curGeometry.primitives[j].indices[k+2];\n\n                idx = findMappedVertex(vertexMapping, idx);\n                idx2 = findMappedVertex(vertexMapping, idx2);\n                idx3 = findMappedVertex(vertexMapping, idx3);\n\n                Vector3f pos1 = curGeometry.positions[idx];\n                Vector3f pos2 = curGeometry.positions[idx2];\n                Vector3f pos3 = curGeometry.positions[idx3];\n\n                Vector4f npos1 = node.transform * Vector4f(pos1.x, pos1.y, pos1.z, 1);\n                Vector4f npos2 = node.transform * Vector4f(pos2.x, pos2.y, pos2.z, 1);\n                Vector4f npos3 = node.transform * Vector4f(pos3.x, pos3.y, pos3.z, 1);\n\n                pos1.x = npos1.x; pos1.y = npos1.y; pos1.z = npos1.z;\n                pos2.x = npos2.x; pos2.y = npos2.y; pos2.z = npos2.z;\n                pos3.x = npos3.x; pos3.y = npos3.y; pos3.z = npos3.z;\n\n                if (!bbox.contains(pos1) ) {\n                  bbox.mergeIn(pos1);\n                }\n                if (!bbox.contains(pos2) ) {\n                  bbox.mergeIn(pos2);\n                }\n                if (!bbox.contains(pos3) ) {\n                  bbox.mergeIn(pos3);\n                }\n                pos1 = curGeometry.positions[idx];\n                pos2 = curGeometry.positions[idx2];\n                pos3 = curGeometry.positions[idx3];\n\n                Vector4f tpos1 = transform * Vector4f(pos1.x, pos1.y, pos1.z, 1);\n                Vector4f tpos2 = transform * Vector4f(pos2.x, pos2.y, pos2.z, 1);\n                Vector4f tpos3 = transform * Vector4f(pos3.x, pos3.y, pos3.z, 1);\n\n                pos1.x = tpos1.x; pos1.y = tpos1.y; pos1.z = tpos1.z;\n                pos2.x = tpos2.x; pos2.y = tpos2.y; pos2.z = tpos2.z;\n                pos3.x = tpos3.x; pos3.y = tpos3.y; pos3.z = tpos3.z;\n\n                if (pos1 != pos2 && pos2 != pos3 && pos1 != pos3) {\n                  //std::cout << pos1 << \" \" << pos2 <<\" \"<< pos3 << \"  \" <<  bbox <<\" \" << currentScale  << \"\\n\";\n                  if (!bbox.contains(pos1, 0.1)  || !bbox.contains(pos2, 0.1) || !bbox.contains(pos3, 0.1)) {\n                    transformOK = false;\n                    nodesTooBig.insert(i);\n                  }\n                }\n              }\n          }\n        }\n      }\n        \n      if (nodesTooBig.size() >= freq - numberIncluded && nodesTooBig.size() > 0) {\n        std::deque<int> mydeque;\n        for (std::set<uint32>::iterator it = nodesTooBig.begin(); it != nodesTooBig.end(); it++) {\n          mydeque.push_back(*it);\n        }\n        while (nodesTooBig.size() >= freq - numberIncluded && nodesTooBig.size() > 0) {\n          int rand_pos = rand() % nodesTooBig.size();\n          nodesTooBig.erase(mydeque[rand_pos]);\n          mydeque.erase(mydeque.begin() + rand_pos);\n        }\n      }\n\n      //nodesTooBig.clear();\n      float newPercentIncluded = numberIncluded/(freq - nodesTooBig.size()) * 100.0;\n      //std::cout << newPercentIncluded << \" : \" << percentIncluded << \" \" << nodesTooBig.size() << \" \" << numberIncluded << \"  \" << freq <<  \" pcincl\\n\";\n                \n      for (uint32 i = 0; i < agg_mesh->nodes.size(); i++) {\n        const GeometryInstance& geomInstance = agg_mesh->instances[i];\n        int geomIdx = geomInstance.geometryIndex;\n        \n        if (geomIdx == submeshIdx) {\n          if (nodesTooBig.find(i) != nodesTooBig.end()) {\n            nodesToRemove.insert(i);\n            continue;\n          }\n\n          if (rand() % 100 >= newPercentIncluded) {\n            nodesToRemove.insert(i);\n            continue;\n          }\n      \n          Node& node = agg_mesh->nodes[i];\n          SubMeshGeometry& curGeometry = agg_mesh->geometry[geomIdx];\n          std::tr1::unordered_map<int, int>& vertexMapping = vertexMapping1[geomIdx];\n          assert( instanceToBBoxMap.find(i) != instanceToBBoxMap.end());\n          BoundingBox3f& bbox = instanceToBBoxMap[i];\n\n          float currentScale = sqrtf(100.0/percentIncluded);\n          Matrix4x4f transform = node.transform * Matrix4x4f::scale(currentScale);\n          bool transformOK = false;\n\t    \n          while (!transformOK) { \n            transformOK = true;  break;\n            if (currentScale < 1) {\n              currentScale = 1;\n              transform = node.transform;\n              break;\n            }\n\t    \n\t    for (uint32 j = 0; j < curGeometry.primitives.size() && transformOK; j++) {\n\t      if (curGeometry.primitives[j].primitiveType != SubMeshGeometry::Primitive::TRIANGLES) continue;\n\t      \n\t      for (uint32 k = 0; k+2 < curGeometry.primitives[j].indices.size(); k+=3) {\n\t\tunsigned short idx = curGeometry.primitives[j].indices[k];\n\t\tunsigned short idx2 = curGeometry.primitives[j].indices[k+1];\n\t\tunsigned short idx3 = curGeometry.primitives[j].indices[k+2];\n\t\t\n\t\tidx = findMappedVertex(vertexMapping, idx);\n\t\tidx2 = findMappedVertex(vertexMapping, idx2);\n\t\tidx3 = findMappedVertex(vertexMapping, idx3);\n\t\t\n\t\tVector3f pos1 = curGeometry.positions[idx];\n\t\tVector3f pos2 = curGeometry.positions[idx2];\n\t\tVector3f pos3 = curGeometry.positions[idx3];\n\n                Vector4f npos1 = node.transform * Vector4f(pos1.x, pos1.y, pos1.z, 1);\n                Vector4f npos2 = node.transform * Vector4f(pos2.x, pos2.y, pos2.z, 1);\n                Vector4f npos3 = node.transform * Vector4f(pos3.x, pos3.y, pos3.z, 1);\n\n                pos1.x = npos1.x; pos1.y = npos1.y; pos1.z = npos1.z;\n                pos2.x = npos2.x; pos2.y = npos2.y; pos2.z = npos2.z;\n                pos3.x = npos3.x; pos3.y = npos3.y; pos3.z = npos3.z;\n\n                if (!bbox.contains(pos1) ) {\n                  bbox.mergeIn(pos1);\n                }\n                if (!bbox.contains(pos2) ) {\n                  bbox.mergeIn(pos2);\n                }\n                if (!bbox.contains(pos3) ) {\n                  bbox.mergeIn(pos3);\n                }\n\n                pos1 = curGeometry.positions[idx];\n                pos2 = curGeometry.positions[idx2];\n                pos3 = curGeometry.positions[idx3];\n\n                Vector4f tpos1 = transform * Vector4f(pos1.x, pos1.y, pos1.z, 1);\n                Vector4f tpos2 = transform * Vector4f(pos2.x, pos2.y, pos2.z, 1);\n                Vector4f tpos3 = transform * Vector4f(pos3.x, pos3.y, pos3.z, 1);\n  \n                pos1.x = tpos1.x; pos1.y = tpos1.y; pos1.z = tpos1.z;\n                pos2.x = tpos2.x; pos2.y = tpos2.y; pos2.z = tpos2.z;\n                pos3.x = tpos3.x; pos3.y = tpos3.y; pos3.z = tpos3.z;\n\n\t\tif (pos1 != pos2 && pos2 != pos3 && pos1 != pos3) {\n                  //std::cout << pos1 << \" \" << pos2 <<\" \"<< pos3 << \"  \" <<  bbox <<\" \" << currentScale  << \"\\n\";\n\n\t\t  if (!bbox.contains(pos1, 0.1)  || !bbox.contains(pos2, 0.1) || !bbox.contains(pos3, 0.1)) {\n                    transformOK = false;\n                    //std::cout << \"Not contains\\n\";\n                    break;\n                  }\n                  //std::cout << \"Contains\\n\";\n\t\t}\n\t      } \n\t    }\n            if (!transformOK) {\n              std::cout << \"currentScale reducing from \" << currentScale << \" to \" << currentScale/1.5 << \"\\n\";\n              currentScale = currentScale / 1.50;\n              transform = node.transform * Matrix4x4f::scale(currentScale);\n            }\n          }\n          node.transform = transform;\n          std::cout << currentScale << \" : currentScale\\n\";\n        }\n      }\n    }\n\n    NodeList newNodeList;\n    NodeIndexList newRootNodesList;\n    GeometryInstanceList newInstanceList;\n\n    NodeList& nodes = agg_mesh->nodes;\n    NodeIndexList& rootNodes = agg_mesh->rootNodes;\n    GeometryInstanceList& instanceList = agg_mesh->instances;\n    for (uint32 i = 0; i < nodes.size(); i++) {\n      if (nodesToRemove.find(i) == nodesToRemove.end() ) \n      {\n\tNodeIndex geom_node_idx = newNodeList.size();\n\tnewNodeList.push_back(nodes[i]);\n\tnewRootNodesList.push_back(geom_node_idx);\n\tGeometryInstance geomInstance = instanceList[i];\n\tgeomInstance.parentNode = geom_node_idx;\n\tnewInstanceList.push_back(geomInstance);\n      }\n    }\n    agg_mesh->nodes = newNodeList;\n    agg_mesh->rootNodes = newRootNodesList;\n    agg_mesh->instances = newInstanceList;\n}\n\nvoid MeshSimplifier::simplify(Mesh::MeshdataPtr agg_mesh, int32 numFacesLeft) {\n  std::map<int, BoundingBox3f> emptyMap;\n  return simplify(agg_mesh, numFacesLeft, emptyMap );\n}\n\nvoid MeshSimplifier::simplify(Mesh::MeshdataPtr agg_mesh, \n\t\t\t      int32 targetFaces, \n\t\t\t      std::map<int, BoundingBox3f>& instanceToBBoxMap) \n{\n  std::tr1::unordered_map<uint32, uint32> submeshInstanceCount;\n\n  int countFaces = 0;\n\n  uint32 geoinst_idx;\n  Matrix4x4f geoinst_pos_xform;\n  Meshdata::GeometryInstanceIterator geoinst_it = agg_mesh->getGeometryInstanceIterator();\n\n  std::set<GeomPairContainer> vertexPairs;\n  std::tr1::unordered_map<GeomPairContainer, float64, GeomPairContainer::Hasher> pairPriorities;\n  std::tr1::unordered_map<GeomPairContainer, uint32, GeomPairContainer::Hasher> pairFrequency; \n\n  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, Matrix4x4d> > submeshPositionQs;\n\n  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, std::tr1::unordered_set<uint32> > > submeshNeighborVertices;\n\n  bool meshChangedDuringPreprocess = false;\n\n  //variables for stochastic simplification\n  std::tr1::unordered_map<uint32, uint32> numTrianglesInSubmesh;\n  float totalInstances = 0;\n  std::map<uint32, BoundingBox3f> submeshBBoxAreas;\n  std::map<uint32, double> submeshTriangleAreas;\n\n\n  /* Make every index in prims specification point to the earliest occurrence of the corresponding position vector */\n  for (uint32 i = 0; i < agg_mesh->geometry.size(); i++) {\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n\n    std::tr1::unordered_map<Vector3f, uint32, Vector3f::Hasher> firstPositionMap;\n\n    std::tr1::unordered_set<uint32> deletedIndices;\n    for (uint32 j = 0; j < curGeometry.primitives.size(); j++) {\n      SubMeshGeometry::Primitive& primitive = curGeometry.primitives[j];\n\n      for (uint32 k = 0; k+2 < primitive.indices.size(); k+=3) {\n        unsigned short idx = primitive.indices[k];\n        unsigned short idx2 = primitive.indices[k+1];\n        unsigned short idx3 = primitive.indices[k+2];\n\n        Vector3f& pos1 = curGeometry.positions[idx];\n        Vector3f& pos2 = curGeometry.positions[idx2];\n        Vector3f& pos3 = curGeometry.positions[idx3];       \n\n        if (firstPositionMap.find(pos1) == firstPositionMap.end()) {\n          firstPositionMap[pos1] = idx;\n        }\n        else {\n          if (idx != firstPositionMap[pos1]) {\n            primitive.indices[k] = firstPositionMap[pos1];\n            deletedIndices.insert(idx);\n          }\n        }\n\n        if (firstPositionMap.find(pos2) == firstPositionMap.end()) {\n          firstPositionMap[pos2] = idx2;\n        }\n        else {\n           if (idx2 != firstPositionMap[pos2]) {\n             primitive.indices[k+1] = firstPositionMap[pos2];\n             deletedIndices.insert(idx2);\n           }\n        }\n\n        if (firstPositionMap.find(pos3) == firstPositionMap.end()) {\n          firstPositionMap[pos3] = idx3;\n        }\n        else {\n          if (idx3 != firstPositionMap[pos3]) {\n            primitive.indices[k+2] = firstPositionMap[pos3];\n            deletedIndices.insert(idx3);\n          }\n        }\n      }\n    }\n\n    for (std::tr1::unordered_set<uint32>::iterator it = deletedIndices.begin();\n          it != deletedIndices.end(); it++)\n    {      \n      curGeometry.positions[*it] = SIMPLIFIER_INVALID_VECTOR;      \n    }\n\t\t\n    if (deletedIndices.size() > 0) {\n      meshChangedDuringPreprocess = true;\n    }\n  }\n\n  std::tr1::unordered_map<uint32, std::vector<IndexedFaceContainer> > geomFacesList;\n  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, std::vector<uint32> > > vertexToFacesMap;\n\n  /* Identify the non-unique faces in the geometry. Insert the vertex pairs */\n  for (uint32 i = 0; i < agg_mesh->geometry.size(); i++) {\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n\n    std::tr1::unordered_map<uint32, std::tr1::unordered_set<uint32> >& neighborVertices = submeshNeighborVertices[i];\n    std::tr1::unordered_map<uint32, std::vector<uint32> >& geomsVertexToFacesMap = vertexToFacesMap[i];\n    std::vector<IndexedFaceContainer>& facesList = geomFacesList[i];\n\n    std::tr1::unordered_map<uint32, Matrix4x4d>& positionQs = submeshPositionQs[i];\n\n    std::tr1::unordered_set<IndexedFaceContainer, IndexedFaceContainer::Hasher> duplicateFaces;\n    for (uint32 j = 0; j < curGeometry.primitives.size(); j++) {\n        SubMeshGeometry::Primitive& primitive = curGeometry.primitives[j];\n\n        for (uint32 k = 0; k+2 < primitive.indices.size(); k+=3) {\n          unsigned short idx = primitive.indices[k];\n          unsigned short idx2 = primitive.indices[k+1];\n          unsigned short idx3 = primitive.indices[k+2];\n\n          if (idx == idx2 || idx == idx3 || idx2 == idx3)\n            continue;\n\n          Vector3f& pos1 = curGeometry.positions[idx];\n          Vector3f& pos2 = curGeometry.positions[idx2];\n          Vector3f& pos3 = curGeometry.positions[idx3];\n\n          IndexedFaceContainer origface(idx, idx2, idx3);\n\n          if (duplicateFaces.find(origface) != duplicateFaces.end()) {\n            primitive.indices[k] = USHRT_MAX;\n            primitive.indices[k+1] = USHRT_MAX;\n            primitive.indices[k+2] = USHRT_MAX;\n            meshChangedDuringPreprocess = true;\n\n            continue;\n          }\n\n          GeomPairContainer gpc1(i, idx, idx2, -1);\n          GeomPairContainer gpc2(i, idx2, idx3, -1);\n          GeomPairContainer gpc3(i, idx, idx3, -1);\n\n          neighborVertices[idx].insert(idx2);\n          neighborVertices[idx].insert(idx3);\n          neighborVertices[idx2].insert(idx);\n          neighborVertices[idx2].insert(idx3);\n          neighborVertices[idx3].insert(idx);\n          neighborVertices[idx3].insert(idx2);\n\n          vertexPairs.insert(gpc1);\n          pairPriorities[gpc1] = -1;\n          pairFrequency[gpc1]++;\n\n          vertexPairs.insert(gpc2);\n          pairPriorities[gpc2] = -1;\n          pairFrequency[gpc2]++;\n\n          vertexPairs.insert(gpc3);\n          pairPriorities[gpc3] = -1;\n          pairFrequency[gpc3]++;\n\n          duplicateFaces.insert(origface);\n\n          IndexedFaceContainer ifc(idx, idx2, idx3);\n          uint32 faceIndex = facesList.size();\n          facesList.push_back(ifc);\n\n          geomsVertexToFacesMap[idx].push_back(faceIndex);\n          geomsVertexToFacesMap[idx2].push_back(faceIndex);\n          geomsVertexToFacesMap[idx3].push_back(faceIndex);\n        }\n    }\n  }\n\n  std::tr1::unordered_map<GeomContainer, uint8, GeomContainer::Hasher> pairNonCollapsible;\n  for (uint32 i = 0; i < agg_mesh->geometry.size(); i++) {\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n\n    for (uint32 j = 0; j < curGeometry.primitives.size(); j++) {\n      SubMeshGeometry::Primitive& primitive = curGeometry.primitives[j];\n\n      for (uint32 k = 0; k+2 < primitive.indices.size(); k+=3) {\n        unsigned short idx = primitive.indices[k];\n        unsigned short idx2 = primitive.indices[k+1];\n        unsigned short idx3 = primitive.indices[k+2];\n\n        if (idx == USHRT_MAX && idx2 == USHRT_MAX && idx3 == USHRT_MAX) {          \n          continue;\n        }\n\n        if (idx == idx2 || idx == idx3 || idx2 == idx3)          continue;\n\n        Vector3f& pos1 = curGeometry.positions[idx];\n        Vector3f& pos2 = curGeometry.positions[idx2];\n        Vector3f& pos3 = curGeometry.positions[idx3];\n\n        GeomPairContainer gpc1(i, idx, idx2, -1);\n        GeomPairContainer gpc2(i, idx2, idx3, -1);\n        GeomPairContainer gpc3(i, idx, idx3, -1);\n\n        if (pairFrequency[gpc1]==1 || pairFrequency[gpc2]==1 || pairFrequency[gpc3]==1) {\n          pairNonCollapsible[GeomContainer(i,idx)] = 1;\n          pairNonCollapsible[GeomContainer(i,idx2)] = 1;\n          pairNonCollapsible[GeomContainer(i,idx3)] = 1;\n        }\n      }\n    }\n  }\n\n\n  //Find the list of instances associated with each submesh\n  countFaces = 0;\n  \n  while( geoinst_it.next(&geoinst_idx, &geoinst_pos_xform) ) {\n    const GeometryInstance& geomInstance = agg_mesh->instances[geoinst_idx];\n    Matrix4x4f geoinst_pos_xform_transpose = geoinst_pos_xform.transpose();\n    Matrix4x4d transform;\n    for (int row=0; row<4; row++) {\n      for (int col=0; col<4; col++) {\n        transform(row,col) = geoinst_pos_xform(row,col);        \n      }\n    } \n    \n    \n    int geomIdx = geomInstance.geometryIndex;\n    submeshInstanceCount[geomIdx]++;\n    totalInstances++;\n\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[geomIdx];\n    std::tr1::unordered_map<uint32, Matrix4x4d>& positionQs = submeshPositionQs[geomIdx];\n\n    numTrianglesInSubmesh[geomIdx] = 0;\n    for (uint32 j = 0; j < curGeometry.primitives.size(); j++) {\n      SubMeshGeometry::Primitive& primitive = curGeometry.primitives[j];\n\n      for (uint32 k = 0; k+2 < primitive.indices.size(); k+=3) {\n        unsigned short idx = primitive.indices[k];\n        unsigned short idx2 = primitive.indices[k+1];\n        unsigned short idx3 = primitive.indices[k+2];\n\n\n        if (idx == USHRT_MAX && idx2 == USHRT_MAX && idx3 == USHRT_MAX) {\n          continue;\n        }\n\n        if (idx == idx2 || idx == idx3 || idx2 == idx3) continue;\n\n        countFaces++;\n        numTrianglesInSubmesh[geomIdx]++;\n\n        Vector3d orig_pos1 (curGeometry.positions[idx].x, curGeometry.positions[idx].y,\n                           curGeometry.positions[idx].z);\n        Vector3d orig_pos2 (curGeometry.positions[idx2].x, curGeometry.positions[idx2].y,\n                            curGeometry.positions[idx2].z);\n        Vector3d orig_pos3 (curGeometry.positions[idx3].x, curGeometry.positions[idx3].y,\n                            curGeometry.positions[idx3].z);                \n\n        Vector3d pos1 = transform * orig_pos1;\n        Vector3d pos2 = transform * orig_pos2;\n        Vector3d pos3 = transform * orig_pos3;\n        \n        Vector3d normal = (pos2 - pos1).cross(pos3-pos1);\n        normal = normal.normal();\n        float64 A = normal[0];\n        float64 B = normal[1];\n        float64 C = normal[2];\n        float64 D = -(normal.dot(pos1));\n\n        Matrix4x4d Qmat ( Vector4d(A*A, A*B, A*C, A*D),\n                          Vector4d(A*B, B*B, B*C, B*D),\n                          Vector4d(A*C, B*C, C*C, C*D),\n                          Vector4d(A*D, B*D, C*D, D*D), Matrix4x4d::ROWS() );\n        \n        Qmat = transform.transpose() * Qmat * transform;\n\n        float64 face_area = (pos1-pos2).cross(pos1-pos3).length() * ((double)0.5);\n        Qmat *= face_area;\n\n        positionQs[idx] += Qmat;\n        positionQs[idx2] += Qmat;\n        positionQs[idx3] += Qmat;\n\n        GeomPairContainer gpc1(geomIdx, idx, idx2, -1);\n        GeomPairContainer gpc2(geomIdx, idx3, idx2, -1);\n        GeomPairContainer gpc3(geomIdx, idx, idx3, -1);\n\n        //Handle boundary edges adding the perpendicular constraint plane.\n        //Implementation could be much much better though.\n        if (pairFrequency[gpc1] == 1) {\n          Vector3d org = pos1, dest = pos2;\n          Vector3d e = dest - org;\n          Vector3d constraint = e.cross(normal);\n          constraint = constraint.normal();\n\n          float64 A = constraint[0];\n          float64 B = constraint[1];\n          float64 C = constraint[2];\n          float64 D = -(constraint.dot(org));\n\n          Matrix4x4d Qmat ( Vector4d(A*A, A*B, A*C, A*D),\n                          Vector4d(A*B, B*B, B*C, B*D),\n                          Vector4d(A*C, B*C, C*C, C*D),\n                          Vector4d(A*D, B*D, C*D, D*D), Matrix4x4d::ROWS() );\n          //Qmat*=100.0;\n          Qmat*=e.lengthSquared();\n\n          Qmat=transform.transpose()*Qmat*transform; \n          positionQs[idx]+=Qmat;\n          positionQs[idx2]+=Qmat;\n        }\n        if (pairFrequency[gpc2] == 1) {\n          Vector3d org = pos3, dest = pos2;\n          Vector3d e = dest - org;\n          Vector3d constraint = e.cross(normal);\n          constraint = constraint.normal();\n\n          float64 A = constraint[0];\n          float64 B = constraint[1];\n          float64 C = constraint[2];\n          float64 D = -(constraint.dot(org));\n\n          Matrix4x4d Qmat ( Vector4d(A*A, A*B, A*C, A*D),\n                          Vector4d(A*B, B*B, B*C, B*D),\n                          Vector4d(A*C, B*C, C*C, C*D),\n                          Vector4d(A*D, B*D, C*D, D*D), Matrix4x4d::ROWS() );\n          //Qmat*=100.0;\n          Qmat*=e.lengthSquared();\n\n          Qmat=transform.transpose()*Qmat*transform;\n          positionQs[idx3]+=Qmat;\n          positionQs[idx2]+=Qmat;\n\n        }\n        if (pairFrequency[gpc3] == 1) {\n          Vector3d org = pos1, dest = pos3;\n          Vector3d e = dest - org;\n          Vector3d constraint = e.cross(normal);\n          constraint = constraint.normal();\n\n          float64 A = constraint[0];\n          float64 B = constraint[1];\n          float64 C = constraint[2];\n          float64 D = -(constraint.dot(org));\n\n          Matrix4x4d Qmat ( Vector4d(A*A, A*B, A*C, A*D),\n                          Vector4d(A*B, B*B, B*C, B*D),\n                          Vector4d(A*C, B*C, C*C, C*D),\n                          Vector4d(A*D, B*D, C*D, D*D), Matrix4x4d::ROWS() );\n          //Qmat*=100.0;\n          Qmat*=e.lengthSquared();\n\n          Qmat=transform.transpose()*Qmat*transform;\n          positionQs[idx]+=Qmat;\n          positionQs[idx3]+=Qmat;\n        }\n        \n      }\n    }\n  }\n\n  targetFaces = countFaces / 5.0;\n  SIMPLIFY_LOG(warn, \"countFaces = \" << countFaces);\n  SIMPLIFY_LOG(warn, \"targetFaces = \" << targetFaces);\n  if (targetFaces < countFaces) {\n      SIMPLIFY_LOG(warn, \"targetFaces < countFaces: Simplification needed\");\n      computeCosts(agg_mesh, submeshPositionQs, vertexPairs, pairPriorities, submeshNeighborVertices, vertexToFacesMap, pairFrequency, pairNonCollapsible);\n  }\n  else if (!meshChangedDuringPreprocess) {\n    return;\n  }\n\n  \n  bool canApplyStochastic = okToApplyStochastic(totalInstances, submeshInstanceCount, instanceToBBoxMap);\n\n  std::tr1::unordered_map<int, std::tr1::unordered_map<int,int>  > vertexMapping1;\n  //Do the actual edge collapses.\n  while (countFaces > targetFaces && vertexPairs.size() > 0) {\n    GeomPairContainer top = *(vertexPairs.begin());   \n\n    int i = top.mGeomIdx;\n\n    //Don't simplify if number of triangles in submesh <= 4.\n    if (canApplyStochastic && numTrianglesInSubmesh[i] <= 4) {\n      vertexPairs.erase(top);\n      pairPriorities.erase(top);\n      continue;\n    }\n\n    uint32 targetIdx = top.mVertexIdx1;\n    uint32 sourceIdx = top.mVertexIdx2;\n\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n    std::tr1::unordered_map<int, int>& vertexMapping = vertexMapping1[i];\n\n    targetIdx = findMappedVertex(vertexMapping, targetIdx);\n    sourceIdx = findMappedVertex(vertexMapping, sourceIdx);\n\n    Vector3f& targetPos = curGeometry.positions[targetIdx];\n    Vector3f& sourcePos = curGeometry.positions[sourceIdx];\n\n    //Collapse vertex at sourceIdx into targetIdx.\n    if (targetIdx != sourceIdx && targetPos != sourcePos) {\n      vertexMapping[sourceIdx] = targetIdx;\n      \n      std::tr1::unordered_map<uint32, std::vector<uint32> >& geomsVertexToFacesMap = vertexToFacesMap[i];\n      std::vector<uint32>& ifcVector = geomsVertexToFacesMap[sourceIdx];\n      std::vector<IndexedFaceContainer>& facesList = geomFacesList[i];\n\n      //count how many faces get invalidated and degenerate because of this edge collapse.\n      for (uint32 ifcVectorIdx = 0; ifcVectorIdx < ifcVector.size(); ifcVectorIdx++) {\n        uint32 faceIndex = ifcVector[ifcVectorIdx];\n        IndexedFaceContainer& ifc = facesList[faceIndex];\n\n        if (!ifc.valid) continue;\n\n        unsigned short vidx = ifc.idx1;\n        unsigned short vidx2 = ifc.idx2;\n        unsigned short vidx3 = ifc.idx3;\n\n        vidx = findMappedVertex(vertexMapping, vidx);\n        vidx2 = findMappedVertex(vertexMapping, vidx2);\n        vidx3 = findMappedVertex(vertexMapping, vidx3);\n\n        if (vidx == vidx2 || vidx2 == vidx3 || vidx == vidx3) {\n          //degenerate face; invalidate it.\n          countFaces -= submeshInstanceCount[i];\n          ifc.valid = false;\n        }\n        else {\n          //add this face to the neighbors of the target vertex.\n          geomsVertexToFacesMap[targetIdx].push_back(faceIndex);\n        }\n      }\n      //done invalidating degenerate faces.\n\n      //Now update the neighbors of the target vertex and its quadric matrix.\n      std::tr1::unordered_set<uint32>& sourceNeighborVertices =  submeshNeighborVertices[i][sourceIdx];\n      std::tr1::unordered_set<uint32>& targetNeighborVertices =  submeshNeighborVertices[i][targetIdx];\n      std::tr1::unordered_map<uint32, Matrix4x4d>& positionQs = submeshPositionQs[i];\n      for (std::tr1::unordered_set<uint32>::iterator neighbor_it = sourceNeighborVertices.begin();\n           neighbor_it != sourceNeighborVertices.end(); neighbor_it++)\n      {\n        uint32 neighborIdx = *neighbor_it;\n\n        if (neighborIdx != targetIdx) {\n          targetNeighborVertices.insert(neighborIdx);\n        }\n      }\n\n      positionQs[ targetIdx ] += positionQs[sourceIdx];\n\n      curGeometry.positions[targetIdx] = top.mReplacementVector;\n      //Finally recompute the costs of the neighbors.\n      computeCosts(agg_mesh, i, sourceIdx, targetIdx, vertexMapping,\n                   submeshPositionQs, vertexPairs, pairPriorities, submeshNeighborVertices,\n                   vertexToFacesMap, pairFrequency, pairNonCollapsible);  \n    }\n\n    vertexPairs.erase(top);\n    pairPriorities.erase(top);\n  }\n\n  if (canApplyStochastic && \n      countFaces > targetFaces * 1.1 && \n      countFaces > targetFaces + 10 ) \n  {\n    applyStochastic(totalInstances, agg_mesh, targetFaces, \n\t\t    submeshInstanceCount, vertexMapping1, instanceToBBoxMap);\n  }\n\n  //remove unused vertices; get new mapping from previous vertex indices to new vertex indices in vertexMapping2;\n  std::tr1::unordered_map<int, std::tr1::unordered_map<int,int> > vertexMapping2;\n  \n  //Remove vertices no longer used in the simplified mesh.\n  for (uint32 i = 0; i < agg_mesh->geometry.size(); i++) {\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n    std::tr1::unordered_map<int, int>& vertexMapping = vertexMapping1[i];\n    std::tr1::unordered_map<int, int>& oldToNewMap = vertexMapping2[i];\n\n    std::vector<Sirikata::Vector3f> positions;\n    std::vector<Sirikata::Vector3f> normals;\n    std::vector<SubMeshGeometry::TextureSet>texUVs;\n\n    for (uint32 j = 0; j < curGeometry.texUVs.size(); j++) {\n      SubMeshGeometry::TextureSet ts;\n      ts.stride = curGeometry.texUVs[j].stride;\n      texUVs.push_back(ts);\n    }\n\n    std::tr1::unordered_map<Vector3f, uint32, Vector3f::Hasher> vector3fSet;\n\n    for (uint32 j = 0 ; j < curGeometry.positions.size() ; j++) {\n      if (vertexMapping.find(j) == vertexMapping.end()) {\n\n        if (curGeometry.positions[j] == SIMPLIFIER_INVALID_VECTOR) {\n          continue;\n        }\n\n        if (vector3fSet.find(curGeometry.positions[j]) != vector3fSet.end()) {\n          oldToNewMap[j] = vector3fSet[ curGeometry.positions[j] ];\n          continue;\n        }\n\n        oldToNewMap[j] = positions.size();\n\n        vector3fSet[ curGeometry.positions[j] ] = positions.size();\n\n        positions.push_back(curGeometry.positions[j]);\n\n        if (j < curGeometry.normals.size())\n          normals.push_back(curGeometry.normals[j]);\n\n        for (uint32 k = 0; k < curGeometry.texUVs.size(); k++) {\n          unsigned int stride = curGeometry.texUVs[k].stride;\n          if (stride*j < curGeometry.texUVs[k].uvs.size()) {\n            uint32 idx = stride * j;\n            while ( idx < stride*j+stride){\n              texUVs[k].uvs.push_back(curGeometry.texUVs[k].uvs[idx]);\n              idx++;\n            }\n          }\n        }\n      }      \n    }\n\n    curGeometry.positions = positions;\n    curGeometry.normals = normals;\n    curGeometry.texUVs = texUVs;\n  }\n\n  //Now adjust the primitives to point to the new indexes of the submesh geometry vertices.\n  std::tr1::unordered_map<uint32, std::tr1::unordered_map<uint32, std::vector<unsigned short> > > newIndices;\n\n  //First create new indices from all the non-degenerate faces.\n  for (uint32 i = 0; i < agg_mesh->geometry.size(); i++) {\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n\n    std::tr1::unordered_map<int, int>& vertexMapping = vertexMapping1[i];\n    std::tr1::unordered_map<int, int>& oldToNewMap = vertexMapping2[i];\n\n    for (uint32 j = 0; j < curGeometry.primitives.size(); j++) {\n      if (curGeometry.primitives[j].primitiveType != SubMeshGeometry::Primitive::TRIANGLES) continue;\n\n      std::vector<unsigned short>& indices = newIndices[i][j];\n\n      for (uint32 k = 0; k+2 < curGeometry.primitives[j].indices.size(); k+=3) {\n\n        unsigned short idx = curGeometry.primitives[j].indices[k];\n        unsigned short idx2 = curGeometry.primitives[j].indices[k+1];\n        unsigned short idx3 = curGeometry.primitives[j].indices[k+2];\n\n        if (idx == USHRT_MAX && idx2 == USHRT_MAX && idx3 == USHRT_MAX) {          \n          continue;\n        }\n\n        unsigned short midx = findMappedVertex(vertexMapping, idx);\n        unsigned short midx2 = findMappedVertex(vertexMapping, idx2);\n        unsigned short midx3 = findMappedVertex(vertexMapping, idx3);\n\n        idx = findMappedVertex(vertexMapping, idx);\n        idx2 = findMappedVertex(vertexMapping, idx2);\n        idx3 = findMappedVertex(vertexMapping, idx3);\n\n        if (idx != idx2 && idx2 != idx3 && idx != idx3) {\n          indices.push_back(oldToNewMap[idx]);\n          indices.push_back(oldToNewMap[idx2]);\n          indices.push_back(oldToNewMap[idx3]);\n        }\n      }\n    }\n  }\n\n  //Now set the new indices.\n  for (uint32 i = 0; i < agg_mesh->geometry.size(); i++) {\n    SubMeshGeometry& curGeometry = agg_mesh->geometry[i];\n\n    for (uint32 j = 0 ; j < curGeometry.primitives.size() ; j++) {\n      curGeometry.primitives[j].indices = newIndices[i][j];\n    }\n  }\n}\n\n}\n\n}\n\n", "meta": {"hexsha": "3e5bba76c6cd2f87020951e374d07d45cc745023", "size": 50357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libmesh/src/MeshSimplifier.cpp", "max_stars_repo_name": "sirikata/sirikata", "max_stars_repo_head_hexsha": "3a0d54a8c4778ad6e25ef031d461b2bc3e264860", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-01-28T17:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T08:30:37.000Z", "max_issues_repo_path": "libmesh/src/MeshSimplifier.cpp", "max_issues_repo_name": "sirikata/sirikata", "max_issues_repo_head_hexsha": "3a0d54a8c4778ad6e25ef031d461b2bc3e264860", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libmesh/src/MeshSimplifier.cpp", "max_forks_repo_name": "sirikata/sirikata", "max_forks_repo_head_hexsha": "3a0d54a8c4778ad6e25ef031d461b2bc3e264860", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-02T18:39:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T10:32:30.000Z", "avg_line_length": 36.1500358938, "max_line_length": 155, "alphanum_fraction": 0.6143137995, "num_tokens": 14138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.036769465811718006, "lm_q1q2_score": 0.018241105102135235}}
{"text": "// Copyright (c) 2018, 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 \"base/homography_matrix.h\"\n\n#include <array>\n\n#include <Eigen/Dense>\n\n#include \"base/pose.h\"\n#include \"util/logging.h\"\n#include \"util/math.h\"\n\nnamespace colmap {\nnamespace {\n\ndouble ComputeOppositeOfMinor(const Eigen::Matrix3d& matrix, const size_t row,\n                              const size_t col) {\n  const size_t col1 = col == 0 ? 1 : 0;\n  const size_t col2 = col == 2 ? 1 : 2;\n  const size_t row1 = row == 0 ? 1 : 0;\n  const size_t row2 = row == 2 ? 1 : 2;\n  return (matrix(row1, col2) * matrix(row2, col1) -\n          matrix(row1, col1) * matrix(row2, col2));\n}\n\nEigen::Matrix3d ComputeHomographyRotation(const Eigen::Matrix3d& H_normalized,\n                                          const Eigen::Vector3d& tstar,\n                                          const Eigen::Vector3d& n,\n                                          const double v) {\n  return H_normalized *\n         (Eigen::Matrix3d::Identity() - (2.0 / v) * tstar * n.transpose());\n}\n\n}  // namespace\n\nvoid DecomposeHomographyMatrix(const Eigen::Matrix3d& H,\n                               const Eigen::Matrix3d& K1,\n                               const Eigen::Matrix3d& K2,\n                               std::vector<Eigen::Matrix3d>* R,\n                               std::vector<Eigen::Vector3d>* t,\n                               std::vector<Eigen::Vector3d>* n) {\n  // Remove calibration from homography.\n  Eigen::Matrix3d H_normalized = K2.inverse() * H * K1;\n\n  // Remove scale from normalized homography.\n  Eigen::JacobiSVD<Eigen::Matrix3d> hmatrix_norm_svd(H_normalized);\n  H_normalized.array() /= hmatrix_norm_svd.singularValues()[1];\n\n  // Ensure that we always return rotations, and never reflections.\n  //\n  // It's enough to take det(H_normalized) > 0.\n  //\n  // To see this:\n  // - In the paper: R := H_normalized * (Id + x y^t)^{-1} (page 32).\n  // - Can check that this implies that R is orthogonal: RR^t = Id.\n  // - To return a rotation, we also need det(R) > 0.\n  // - By Sylvester's idenitity: det(Id + x y^t) = (1 + x^t y), which\n  //   is positive by choice of x and y (page 24).\n  // - So det(R) and det(H_normalized) have the same sign.\n  if (H_normalized.determinant() < 0) {\n    H_normalized.array() *= -1.0;\n  }\n\n  const Eigen::Matrix3d S =\n      H_normalized.transpose() * H_normalized - Eigen::Matrix3d::Identity();\n\n  // Check if H is rotation matrix.\n  const double kMinInfinityNorm = 1e-3;\n  if (S.lpNorm<Eigen::Infinity>() < kMinInfinityNorm) {\n    *R = {H_normalized};\n    *t = {Eigen::Vector3d::Zero()};\n    *n = {Eigen::Vector3d::Zero()};\n    return;\n  }\n\n  const double M00 = ComputeOppositeOfMinor(S, 0, 0);\n  const double M11 = ComputeOppositeOfMinor(S, 1, 1);\n  const double M22 = ComputeOppositeOfMinor(S, 2, 2);\n\n  const double rtM00 = std::sqrt(M00);\n  const double rtM11 = std::sqrt(M11);\n  const double rtM22 = std::sqrt(M22);\n\n  const double M01 = ComputeOppositeOfMinor(S, 0, 1);\n  const double M12 = ComputeOppositeOfMinor(S, 1, 2);\n  const double M02 = ComputeOppositeOfMinor(S, 0, 2);\n\n  const int e12 = SignOfNumber(M12);\n  const int e02 = SignOfNumber(M02);\n  const int e01 = SignOfNumber(M01);\n\n  const double nS00 = std::abs(S(0, 0));\n  const double nS11 = std::abs(S(1, 1));\n  const double nS22 = std::abs(S(2, 2));\n\n  const std::array<double, 3> nS{{nS00, nS11, nS22}};\n  const size_t idx =\n      std::distance(nS.begin(), std::max_element(nS.begin(), nS.end()));\n\n  Eigen::Vector3d np1;\n  Eigen::Vector3d np2;\n  if (idx == 0) {\n    np1[0] = S(0, 0);\n    np2[0] = S(0, 0);\n    np1[1] = S(0, 1) + rtM22;\n    np2[1] = S(0, 1) - rtM22;\n    np1[2] = S(0, 2) + e12 * rtM11;\n    np2[2] = S(0, 2) - e12 * rtM11;\n  } else if (idx == 1) {\n    np1[0] = S(0, 1) + rtM22;\n    np2[0] = S(0, 1) - rtM22;\n    np1[1] = S(1, 1);\n    np2[1] = S(1, 1);\n    np1[2] = S(1, 2) - e02 * rtM00;\n    np2[2] = S(1, 2) + e02 * rtM00;\n  } else if (idx == 2) {\n    np1[0] = S(0, 2) + e01 * rtM11;\n    np2[0] = S(0, 2) - e01 * rtM11;\n    np1[1] = S(1, 2) + rtM00;\n    np2[1] = S(1, 2) - rtM00;\n    np1[2] = S(2, 2);\n    np2[2] = S(2, 2);\n  }\n\n  const double traceS = S.trace();\n  const double v = 2.0 * std::sqrt(1.0 + traceS - M00 - M11 - M22);\n\n  const double ESii = SignOfNumber(S(idx, idx));\n  const double r_2 = 2 + traceS + v;\n  const double nt_2 = 2 + traceS - v;\n\n  const double r = std::sqrt(r_2);\n  const double n_t = std::sqrt(nt_2);\n\n  const Eigen::Vector3d n1 = np1.normalized();\n  const Eigen::Vector3d n2 = np2.normalized();\n\n  const double half_nt = 0.5 * n_t;\n  const double esii_t_r = ESii * r;\n\n  const Eigen::Vector3d t1_star = half_nt * (esii_t_r * n2 - n_t * n1);\n  const Eigen::Vector3d t2_star = half_nt * (esii_t_r * n1 - n_t * n2);\n\n  const Eigen::Matrix3d R1 =\n      ComputeHomographyRotation(H_normalized, t1_star, n1, v);\n  const Eigen::Vector3d t1 = R1 * t1_star;\n\n  const Eigen::Matrix3d R2 =\n      ComputeHomographyRotation(H_normalized, t2_star, n2, v);\n  const Eigen::Vector3d t2 = R2 * t2_star;\n\n  *R = {R1, R1, R2, R2};\n  *t = {t1, -t1, t2, -t2};\n  *n = {-n1, n1, -n2, n2};\n}\n\nvoid PoseFromHomographyMatrix(const Eigen::Matrix3d& H,\n                              const Eigen::Matrix3d& K1,\n                              const Eigen::Matrix3d& K2,\n                              const std::vector<Eigen::Vector2d>& points1,\n                              const std::vector<Eigen::Vector2d>& points2,\n                              Eigen::Matrix3d* R, Eigen::Vector3d* t,\n                              Eigen::Vector3d* n,\n                              std::vector<Eigen::Vector3d>* points3D) {\n  CHECK_EQ(points1.size(), points2.size());\n\n  std::vector<Eigen::Matrix3d> R_cmbs;\n  std::vector<Eigen::Vector3d> t_cmbs;\n  std::vector<Eigen::Vector3d> n_cmbs;\n  DecomposeHomographyMatrix(H, K1, K2, &R_cmbs, &t_cmbs, &n_cmbs);\n\n  points3D->clear();\n  for (size_t i = 0; i < R_cmbs.size(); ++i) {\n    std::vector<Eigen::Vector3d> points3D_cmb;\n    CheckCheirality(R_cmbs[i], t_cmbs[i], points1, points2, &points3D_cmb);\n    if (points3D_cmb.size() >= points3D->size()) {\n      *R = R_cmbs[i];\n      *t = t_cmbs[i];\n      *n = n_cmbs[i];\n      *points3D = points3D_cmb;\n    }\n  }\n}\n\nEigen::Matrix3d HomographyMatrixFromPose(const Eigen::Matrix3d& K1,\n                                         const Eigen::Matrix3d& K2,\n                                         const Eigen::Matrix3d& R,\n                                         const Eigen::Vector3d& t,\n                                         const Eigen::Vector3d& n,\n                                         const double d) {\n  CHECK_GT(d, 0);\n  return K2 * (R - t * n.normalized().transpose() / d) * K1.inverse();\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "15a8e1dac7fb97d8a7a0de51a44efc615b6cee70", "size": 8316, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/base/homography_matrix.cc", "max_stars_repo_name": "UncleGene/colmap", "max_stars_repo_head_hexsha": "a2a85b4efb77ea6da0edff94e3802c7ef2588f92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T07:43:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:37:28.000Z", "max_issues_repo_path": "src/base/homography_matrix.cc", "max_issues_repo_name": "Pascal-So/colmap", "max_issues_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/homography_matrix.cc", "max_forks_repo_name": "Pascal-So/colmap", "max_forks_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-12-15T01:39:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:19:57.000Z", "avg_line_length": 36.96, "max_line_length": 78, "alphanum_fraction": 0.5999278499, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.03676946554783728, "lm_q1q2_score": 0.018241104971225636}}
{"text": "/**\n* @file: MyUtility.hpp\n* @brief:\n* @author: Changjiang Cai, caicj5351@gmail.com\n* @version: 0.0.1\n* @creation date: 17-12-2015\n* @last modified: Thu 10 Mar 2016 09:32:02 AM EST\n*/\n\n#ifndef __HEADER__CROWD_SOURCING_PROJECT_UTILITY_H_\n#define __HEADER__CROWD_SOURCING_PROJECT_UTILITY_H_\n#include <iostream>\n#include <fstream> // std::fstream\n#include <vector>\n#include <string>\n#include <map> /*ordered map*/\n#include <unordered_map> /*unordered map*/\n#include <set>\n#include <algorithm> /*Permutation*/\n#include <functional>\n#include <array> /* array */\n#include <cmath> /*pow etc*/\n#include <cstdio>/*printf*/\n#include <string>\n#include <stdlib.h>     /* srand, rand */\n#include <time.h>       /* time */\n#include <limits.h>\n#include <cstring> /* memset */\n#include <queue>\n#include <set>\n#include <vector>\n#include <random>  /*std::uniform_int_distribution*/\n#include <Eigen/Dense>\n//#include \"CrowdBT.h\" // Crowd_BT\n#include <boost/math/special_functions/digamma.hpp>\n\ntypedef unsigned long ulong;\ntypedef unsigned long long ullong;\nullong factorial(unsigned int n);\nullong factorial(int n);\nvoid printTiePath(const int & v, // vertex number;\n\tconst std::vector<int> & v_tiePath, // tie-paths;\n\tconst std::string  & fn); // output file name;\n\nstd::string toString(const std::vector<int> &p);\n\nvoid printFactorial(std::ofstream  & of, const int & n);\n\n\nstd::vector<std::vector<double> > add(const std::vector<std::vector<double> >& lhs, const std::vector<std::vector<double> >& rhs);\n\nstd::vector<std::vector<int>> add(const std::vector<std::vector<int> >& lhs, const std::vector<std::vector<int> >& rhs);\n\nstd::vector<std::vector<double> > multiply(const std::vector<std::vector<double> >& lhs, const std::vector<std::vector<double> >& rhs);\nstd::vector<std::vector<double> > multiplyEigen(const std::vector<std::vector<double> >& lhs, const std::vector<std::vector<double> >& rhs);\n\nvoid unify_BT_D(Eigen::MatrixXd & M, const int & n);/*direct use of voting results*/\nvoid unify_BT_D(std::vector<std::vector<double> >& M);/*direct use of voting results*/\nvoid unify_BT_E(std::vector<std::vector<double> >& M);/*using the exponentials of voting results*/\nvoid unify_BT_L(std::vector<std::vector<double> >& M, const double & alpha = 1.0);/*Laplace smoothing*/\n\n\nvoid\noutput_matrix(std::vector<std::vector<int> > &matrix);\n\nvoid\noutput_matrix(std::vector<std::vector<double> > &matrix);\n\ntemplate<typename T>\nvoid output_matrix(std::vector<std::vector<T> > &matrix, std::ofstream & of1){\n\tfor (int i = 0; i < matrix.size(); ++i){\n\t\tfor (int j = 0; j < matrix[i].size(); ++j){\n\t\t\tof1 << matrix[i][j];\n\t\t\tif (matrix[i].size() - 1 == j)\n\t\t\t\tof1 << \"\\n\";\n\t\t\telse of1 << \",\";\n\t\t}\n\t}\n}\n\n// print boundary;\ntemplate<typename T>\nvoid printBoundary(const T & val, const int & vertexNum, std::ofstream & of_csv){\n\tfor (auto i = 0; i < vertexNum; ++i)\n\t\tof_csv << val << \",\";\n\tof_csv << endl;\n}\n\ntemplate <typename T, typename T2>\nbool isHP(T ** tc, T2 * v, const int & size){\r\n\r\n\t\tfor (int i = 0; i < size - 1; i++)\r\n\t\t{\r\n\t\t\tif (tc[v[i]][v[i + 1]] == 0){\r\n\t\t\t\t/*std::cout << \" (\" << v[i] << \", \" << v[i + 1] <<\r\n\t\t\t\t\t\") = 0, \";*/\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n}\r\n\n\n\n\n#endif\n", "meta": {"hexsha": "905d20013736147d935ce5984cfefff48fb8744e", "size": 3185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MyUtility.hpp", "max_stars_repo_name": "ccj5351/crowdsourcing", "max_stars_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyUtility.hpp", "max_issues_repo_name": "ccj5351/crowdsourcing", "max_issues_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MyUtility.hpp", "max_forks_repo_name": "ccj5351/crowdsourcing", "max_forks_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7663551402, "max_line_length": 140, "alphanum_fraction": 0.6571428571, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.04603390141766852, "lm_q1q2_score": 0.018232562920935978}}
{"text": "/*!\n * @file    swp_silicon_inception.cpp\n * @author  William J Menz\n * @brief   Implementation of the SiliconInception class.\n *\n *   Author(s):      William J Menz\n *   Project:        sweepc (population balance solver)\n *   Copyright (C) 2012 William J Menz\n *\n *   File purpose:\n *      Based on swp_dimer_inception by Robert Patterson, Markus Sander\n *      and Matthew Celnik.\n *\n *      Implementation of the SiliconInception class.\n *\n *   Licence:\n *      This file is part of \"sweepc\".\n *\n *      sweepc is free software; you can redistribute it and/or\n *      modify it under the terms of the GNU Lesser 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 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 program; if not, write to the Free Software\n *      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n *      02111-1307, USA.\n *\n *   Contact:\n *      Prof Markus Kraft\n *      Dept of Chemical Engineering\n *      University of Cambridge\n *      New Museums Site\n *      Pembroke Street\n *      Cambridge\n *      CB2 3RA, UK\n *\n *      Email:       mk306@cam.ac.uk\n *      Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_silicon_inception.h\"\n#include \"swp_mechanism.h\"\n#include \"swp_params.h\"\n#include \"swp_primary.h\"\n#include \"swp_sprog_idealgas_wrapper.h\"\n\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::Processes;\nusing namespace std;\n\n// Mass of a silicon monomer, kg\nconst double SiliconInception::m_m1  = 4.664e-26;\n// Vol of a silicon atom, m3\nconst double SiliconInception::m_v1  = 2.003e-29;\n// Spherical diameter of a bulk silicon atom, m\nconst double SiliconInception::m_d1  = 3.369e-10;\n\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n//! Default constructor (protected).\nSiliconInception::SiliconInception(void)\n: Inception(), m_kfm(0.0), m_ksf1(0.0), m_ksf2(0.0),\n  m_efm(2.2),\n  m_itype(iCollisional), m_vi(0.0), m_di(0.0),\n  m_sidata(0), m_reacs(0), m_concs(0)\n{\n    m_name = \"SiliconInception\";\n}\n\n//! Initialising constructor.\nSiliconInception::SiliconInception(const Sweep::Mechanism &mech)\n: Inception(mech), m_kfm(0.0), m_ksf1(0.0), m_ksf2(0.0),\n  m_efm(mech.GetEnhancementFM()),\n  m_itype(iCollisional), m_vi(0.0), m_di(0.0),\n  m_sidata(0), m_reacs(0), m_concs(0)\n{\n    m_name = \"SiliconInception\";\n}\n\n//! Copy constructor.\nSiliconInception::SiliconInception(const SiliconInception &copy)\n: m_efm(copy.m_efm)\n{\n    *this = copy;\n}\n\n//! Stream-reading constructor.\nSiliconInception::SiliconInception(std::istream &in, const Sweep::Mechanism &mech)\n: m_efm(mech.GetEnhancementFM())\n{\n    Deserialize(in, mech);\n}\n\n//! Default destructor.\nSiliconInception::~SiliconInception(void)\n{\n}\n\n// OPERATOR OVERLOADS.\n\n/*!\n * @brief           Assignment operator\n *\n * @param rhs       Pointer to right hand side object\n * @return          Pointer to object\n */\nSiliconInception &SiliconInception::operator =(const SiliconInception &rhs)\n{\n    if (this != &rhs) {\n        Inception::operator =(rhs);\n        m_kfm  = rhs.m_kfm;\n        m_ksf1 = rhs.m_ksf1;\n        m_ksf2 = rhs.m_ksf2;\n        m_itype = rhs.m_itype;\n        m_vi   = rhs.m_vi;\n        m_di   = rhs.m_di;\n\n        m_sidata = rhs.m_sidata;\n        m_reacs  = rhs.m_reacs;\n        m_concs  = rhs.m_concs;\n    }\n    return *this;\n}\n\n\n/*!\n * Create a new particle and add it to the ensemble with position uniformly\n * distributed over the grid cell.\n *\n * The iterm parameter is included because it will be needed for many process\n * types and this function is meant to have a general signature.\n *\n * \\param[in]       t               Time\n * \\param[in]       local_geom      Details of geometry around current location\n * \\param[in,out]   sys             System to update\n * \\param[in]       iterm           Process term responsible for this event\n * \\param[in,out]   rng             Random number generator\n *\n * \\return      0 on success, otherwise negative.\n */\nint SiliconInception::Perform(const double t, Cell &sys,\n                            const Geometry::LocalGeometry1d &local_geom,\n                            const unsigned int iterm,\n                            rng_type &rng) const {\n\n    // This routine performs the inception on the given chemical system.\n\n    // Create a new particle of the type specified\n    // by the system ensemble.\n    Particle *sp = m_mech->CreateParticle(t);\n\n    // Get the cell vertices\n    fvector vertices = local_geom.cellVertices();\n\n    // Sample a uniformly distributed position, note that this method\n    // works whether the vertices come in increasing or decreasing order,\n    // but 1d is assumed for now.\n    double posn = vertices.front();\n\n    const double width = vertices.back() - posn;\n    boost::uniform_01<rng_type&, double> uniformGenerator(rng);\n    posn += width * uniformGenerator();\n\n    sp->setPositionAndTime(posn, t);\n\n    if (m_itype == iCollisional) {\n\n        // If the normal collisional-type rate is used, create the particle\n        // and adjust the gas-phase as in normal Inception\n\n        // Initialise the new particle.\n        sp->Primary()->SetComposition(ParticleComp());\n        sp->Primary()->SetValues(ParticleTrackers());\n        sp->UpdateCache();\n\n        // Add particle to system's ensemble.\n        sys.Particles().Add(*sp, rng);\n\n        // Update gas-phase chemistry of system.\n        adjustGas(sys, sp->getStatisticalWeight());\n\n    } else {\n\n        // Otherwise, use information from m_sidata to select a gas-phase\n        // species to transform into a new particle\n        const SiliconData* species = ChooseData(sys, rng);\n        if (species != NULL) {\n            sp->Primary()->SetComposition(species->_track);\n            sp->Primary()->SetValues(ParticleTrackers());\n            sp->UpdateCache();\n\n            // Add particle to system's ensemble.\n            sys.Particles().Add(*sp, rng);\n\n            // Update gas-phase chemistry of system.\n            adjustGasPhase(sys, (*species), sp->getStatisticalWeight());\n        } else {\n            std::cout << \"Warning: silicon inception chosen with no precursor.\"\n                    << endl;\n        }\n    }\n\n    return 0;\n}\n\n\n// INCEPTION KERNEL.\n\n/*!\n * The inception rate is based on a transition coagulation kernel that\n * is calculated using a molecule diameter and mass.  These values do not\n * have to correspond the the physical properties of the molecule, but they\n * are fed into the transition regime kernel.\n *\n * @param[in]    m1    mass of first molecule\n * @param[in]    m2    mass of second molecule\n * @param[in]    d1    diameter of first molecule\n * @param[in]    d2    diameter of second molecule\n */\nvoid SiliconInception::SetInceptingSpecies(double m1, double m2, double d1, double d2)\n{\n    // The free mol part can be handled by the free mol specific method\n    SetInceptingSpeciesFreeMol(m1, m2, d1, d2);\n\n    // Now the slip flow part\n    double invd1=1.0/d1, invd2=1.0/d2;\n    m_ksf1 = CSF * (d1+d2);\n    m_ksf2 = 2.0 * 1.257 * m_ksf1 * ((invd1*invd1) + (invd2*invd2));\n    m_ksf1 = m_ksf1 * (invd1+invd2);\n}\n\n/*!\n * The inception rate is based on a free molecular coagulation kernel only,\n * contrast \\ref SetInceptingSpecies that\n * is calculated using a molecule diameter and mass.  These values do not\n * have to correspond the the physical properties of the molecule, but they\n * are fed into the transition regime kernel.\n *\n * @param[in]    m1    mass of first molecule\n * @param[in]    m2    mass of second molecule\n * @param[in]    d1    diameter of first molecule\n * @param[in]    d2    diameter of second molecule\n */\nvoid SiliconInception::SetInceptingSpeciesFreeMol(double m1, double m2, double d1, double d2)\n{\n    // This routine sets the free-mol and slip flow kernel parameters given\n    // the mass and diameter of the incepting species.\n    m_kfm  = m_efm * CFM * sqrt((1.0/m1) + (1.0/m2)) * (d1+d2) * (d1+d2);\n    m_ksf1 = 0.0;\n    m_ksf2 = 0.0;\n}\n\n/*!\n * @brief           Sets the incepting volume\n *\n * The volume of the incepting particle is determined upon initialisation,\n * based on the density of molwt of each component.\n *\n * @param mech      Particle mechanism\n */\nvoid SiliconInception::SetInceptingVolume(const Sweep::Mechanism &mech)\n{\n    double v1(0.0);\n    CompPtrVector comp = mech.Components();\n    for (unsigned int i=0; i!=comp.size(); i++) {\n        // returns in m3, due to Density()\n        v1 += 1.0 * mech.Components(i)->MolWt() /\n                (Sweep::NA * mech.Components(i)->Density());\n    }\n\n    m_vi = v1;\n}\n\n/*!\n * @brief       Calculates the diameter of an incepting particle\n *\n * Pre-calculates the incepting diameter of a particle (when a collisional\n * inception process is used) for this inception reaction. This is done\n * using the molwt, density and initial number of each component in\n * the new particle.\n *\n * @param mech  Particle mechanism\n */\nvoid SiliconInception::SetInceptingDiameter(const Sweep::Mechanism &mech)\n{\n    if (m_itype != iCollisional) {\n        double dmin(1.0);\n        for (unsigned int i=0; i!=m_sidata.size(); i++) {\n            if (m_sidata[i]._diam < dmin) dmin = m_sidata[i]._diam;\n        }\n        m_di = dmin;\n    } else {\n        //Pre-define volume and diameters\n        double v(0.0), d(0.0);\n\n        // Loop over list of components in incepting particle to find initial vol\n        for (unsigned int i=0; i!=ParticleComp().size(); i++) {\n\n            // returns in m3, due to Density()\n            v += ParticleComp()[i] * mech.Components(i)->MolWt() /\n                    (Sweep::NA * mech.Components(i)->Density());\n        }\n\n        // Now calculate the equivalent spherical diameter\n        d = pow(6 * v / Sweep::PI, Sweep::ONE_THIRD);\n        m_di = d;\n    }\n}\n\n/*!\n * @brief           Generates the silicon species data\n *\n * The silicon species data hold information on each species such as name,\n * diameter and the incepting particle composition.\n *\n * @param mech      Particle mechanism\n */\nvoid SiliconInception::GenerateSpeciesData(const Sweep::Mechanism &mech)\n{\n    // First scan the species to determine possible candidates for inception\n    // Loop over all gas-phase species\n    const Sprog::SpeciesPtrVector *spec = mech.Species();\n    for (unsigned int i=0; i!=spec->size(); i++) {\n\n        string name = spec->at(i)->Name();\n        CompPtrVector comp = mech.Components();\n\n        if (IsCandidate(name)) {\n            SiliconData *data;\n            data = new SiliconData();\n            data->_fracIndex = i;\n            data->_name      = name;\n\n            // Create a new component vector for storing new particle comp\n            data->_track.resize(comp.size(), 0.0);\n\n            // Initialise variable for volume\n            double v(0.0);\n\n            // Loop over particle components to work out how many the\n            // gas-phase species of interest will  contribute\n            for (unsigned int j=0; j!=comp.size(); j++) {\n\n                if (comp[j]->Name() == \"silicon\") {\n                    data->_track[j] = spec->at(i)->AtomCount(\"SI\");\n                    v += data->_track[j] * comp[j]->MolWt() /\n                            (NA * comp[j]->Density());\n                } else if (comp[j]->Name() == \"hydrogen\") {\n                    data->_track[j] = spec->at(i)->AtomCount(\"H\");\n                    v += data->_track[j] * comp[j]->MolWt() /\n                            (NA * comp[j]->Density());\n                } else {\n                    std::cout << \"Warning! Unrecognised component name!\" << std::endl;\n                }\n            }\n            data->_diam = pow(6.0 * v / Sweep::PI, Sweep::ONE_THIRD);\n            printSiliconData(*data);\n            m_sidata.push_back(*data);\n        }\n\n    }\n\n\n    // Now generate other data\n    SetInceptingDiameter(mech);\n    SetInceptingVolume(mech);\n\n    // Resize the counter vectors\n    m_reacs.resize(spec->size(), 0);\n    m_concs.resize(spec->size(), 0.0);\n}\n\nconst SiliconInception::SiliconData* SiliconInception::ChooseData(const Sweep::Cell &sys,\n        rng_type &rng) const\n{\n    // Choose a species which is ABOVE THE CRITICAL DIAMETER and\n    // weight the choice based on mole fractions.\n    const SiliconData* ans(NULL);\n\n    double dcrit = GetCriticalNucleus(sys);\n\n    // Hold fractions of available species in vector\n    fvector availFracs;\n    std::vector<const SiliconData*> availSpecies;\n    double sum(0.0);\n    double frac(0.0);\n\n    // Loop over candidate species\n    for (unsigned int i=0; i != m_sidata.size(); i++) {\n        if (m_sidata[i]._diam >= dcrit) {\n            frac = sys.GasPhase().SpeciesConcentration(m_sidata[i]._fracIndex) /\n                    sys.GasPhase().MolarDensity();\n            sum += frac;\n            availFracs.push_back(frac);\n            availSpecies.push_back(&(m_sidata[i]));\n        }\n    }\n\n    // Scale these to be probabilities\n    if (sum > 0.0) {\n        for (unsigned int i=0; i != availFracs.size(); i++) {\n            availFracs[i] /= sum;\n        }\n\n        // Select an index based on its mole fraction\n        boost::random::discrete_distribution<> dist(availFracs);\n        unsigned int j = dist(rng);\n        ans = availSpecies[j];\n    }\n    return ans;\n}\n\n/*!\n * Adjust the gas phase for the effects of this process.\n *\n *@param[in]    sys         Cell in which the process is taking place\n *@param[in]    species     Silicon hydride species to be incepted\n *@param[in]    wt          Statistical weight of particle\n *\n *@pre      The gas phase in sys must be of type SprogIdealGasWrapper\n *\n *@exception    std::runtime_error      Could not cast gas phase to SprogIdealGasWrapper\n */\nvoid SiliconInception::adjustGasPhase(Sweep::Cell &sys,\n        const SiliconInception::SiliconData &species,\n        double wt) const\n{\n    if(!sys.FixedChem()) {\n    // This method requires write access to the gas phase, which is not\n    // standard in sweep.  This means it cannot use the generic gas\n    // phase interface\n    SprogIdealGasWrapper *gasWrapper = dynamic_cast<SprogIdealGasWrapper*>(&sys.GasPhase());\n    if(gasWrapper == NULL)\n        throw std::runtime_error(\"Could not cast gas phase to SprogIdealGasWrapper in SiliconInception::adjustGasPhase\");\n\n    // If excecution reaches here, the cast must have been successful\n    Sprog::Thermo::IdealGas *gas = gasWrapper->Implementation();\n\n    // Get the existing concentrations\n    fvector newConcs;\n    gas->GetConcs(newConcs);\n\n    double n_NAvol = wt / (NA * sys.SampleVolume());\n\n    // Update the internal counters\n    m_reacs[species._fracIndex] += 1;\n    m_concs[species._fracIndex] += n_NAvol;\n\n    // Use the fracindex to calculate the amount of precursor to be\n    // removed.\n    newConcs[species._fracIndex] -= 1.0 * n_NAvol;\n\n    // Now adjust the gas-phase!\n    gas->SetConcs(newConcs);\n    }\n}\n\n/*!\n * @brief       Does this species contribute to inception?\n *\n * @param name  Species name\n * @return      True/false\n */\nbool SiliconInception::IsCandidate(std::string name) const\n{\n    bool ans(false);\n    // Permit silylenes to incept\n    if (std::string::npos != name.find(\"B\")\n            && std::string::npos != name.find(\"SI\")) {\n        ans = true;\n    } else if (std::string::npos != name.find(\"A\")\n            && std::string::npos != name.find(\"SI\")) {\n        ans = true;\n    } else if (name == \"SI2H2\") {\n        ans = true;\n    } else if (name == \"SIH2\") {\n        ans = true;\n    } else if (name == \"SIH\") {\n        ans = true;\n    } else if (name == \"SI\") {\n        ans = true;\n    }\n    return ans;\n}\n\n\n/*!\n * @brief       Calculates the mole fraction of precursor\n *\n * @param sys   System for analysis\n * @return      Mole fraction of precursor\n */\ndouble SiliconInception::GetPrecursorFraction(const Sweep::Cell &sys) const\n{\n    // Initialise the fraction\n    double frac(0.0);\n\n    // Loop over all gas-phase species\n    for (unsigned int i=0; i!=m_sidata.size(); i++) {\n        frac += sys.GasPhase().SpeciesConcentration(m_sidata[i]._fracIndex) /\n                sys.GasPhase().MolarDensity();\n    }\n\n    if (frac > 1.0) {\n        throw runtime_error(\"Mole fraction greater than 1.0! \"\n                            \"(Sweep, SiliconInception::GetPrecursorFraction).\");\n    }\n    return frac;\n}\n\n/*!\n * @brief       Returns the supersaturation\n *\n * Supersaturation for this system is defined by the ratio of the\n * monomer pressure to the saturation vapour pressure.\n *\n * @param sys   System for which to calculate\n * @return      Supersaturation (-)\n */\ndouble SiliconInception::GetSupersaturation(const Sweep::Cell &sys) const\n{\n    double s(1.0);\n\n    // First get the silicon pressure\n    s *= (GetPrecursorFraction(sys) * sys.GasPhase().Pressure());\n\n    // Now divide by the saturation vapour pressure\n    s /= GetSatVapourPressure(sys.GasPhase().Temperature());\n\n    return s;\n\n}\n\n/*!\n * @brief       Returns the surface energy of silicon\n *\n * Koermer et al (2010) J. Aerosol Sci, 41, 1007-\n *\n * @param T     Temperature (K)\n * @return      Surface energy (N/m)\n */\ndouble SiliconInception::GetSurfaceEnergy(double T) const\n{\n    return 1.152 - 1.574e-4 * T;\n}\n\n/*!\n * @brief       Returns the saturation vapour pressure of silicon\n *\n * Koermer et al (2010) J. Aerosol Sci, 41, 1007-\n *\n * @param T     Temperature (K)\n * @return      Saturation vapour pressure (Pa)\n */\ndouble SiliconInception::GetSatVapourPressure(double T) const\n{\n    return 101325.0 * pow(10, 7.534 - (23399 / T));\n}\n\n\n/*!\n * @brief       Returns the saturated monomer number concentration\n *\n * Estimates the number concentration from the saturation vapour pressure\n *\n * @param T     Temperature (K)\n * @return      Sat. monomer number concentration (#/m3)\n */\ndouble SiliconInception::GetMonomerConc(double T) const\n{\n    double psat = GetSatVapourPressure(T);\n    psat *= (NA / (T * R));\n    return psat;\n}\n\n\n/*!\n * @brief       Calculates the critical nucleus size\n *\n * Uses the Kelvin equation to calculate the critical nucleus size. This\n * is given by:\n * d* = 4 gamma v1 / (kB T ln(S))\n * where:\n *  gamma is the surface energy (N/m)\n *  v1 is the volume of a monomer (m)\n *  kB is Boltzmann's constant\n *  S is the supersaturation\n *\n * @param sys   System for analysis\n * @return      Critical diameter, in metres\n */\ndouble SiliconInception::GetCriticalNucleus(const Sweep::Cell &sys) const\n{\n    double d = 4.0/Sweep::KB;\n    double s = GetSupersaturation(sys);\n\n    // Get chemical conditions\n    double T = sys.GasPhase().Temperature();      // in K\n\n    // Set d to an arbitrarily high value if psi = 0 (i.e. no precursor)\n    if (s <= 1.0) {\n        d = 1.0;                            // in m\n    } else {\n        d *= (GetSurfaceEnergy(T) * m_v1 / (T * log(s)));      // in m\n    }\n\n    return d;\n}\n\n\nbool SiliconInception::IsInceptionAllowed(const Sweep::Cell &sys) const\n{\n    bool val(false);\n    // Only allow inception if d_incep >= d_crit\n    if (m_di >= GetCriticalNucleus(sys)) {\n        val = true;\n    } else{\n        val = false;\n    }\n    return val;\n}\n\n// TOTAL RATE CALCULATIONS.\n\n// Returns rate of the process for the given system.\ndouble SiliconInception::Rate(double t, const Cell &sys, const Geometry::LocalGeometry1d &local_geom) const\n{\n    // Get the current chemical conditions.\n    double T = sys.GasPhase().Temperature();\n    double P = sys.GasPhase().Pressure();\n\n    // Calculate the rate.\n    return Rate(sys.GasPhase(), sqrt(T),\n                T/sys.GasPhase().Viscosity(), MeanFreePathAir(T,P),\n                sys.SampleVolume(), sys);\n}\n\n\n\n/*!\n * Calculate inception rate using a the transition coagulation kernel\n * with the values provided by the user.  The result is this value\n * multiplied by the square of the number concentration of the gas\n * phase species.\n *\n * @param[in]    gas      interface to gas mixture\n * @param[in]    sqrtT    square root of temperature\n * @param[in]    T_mu     temperature divided by air viscosity\n * @param[in]    MFP      mean free path in gas\n * @param[in]    vol      sample volume\n *\n * @return    Inception rate for a cell of size vol. (\\f$ \\mathrm{s}^{-1}\\f$)\n */\ndouble SiliconInception::Rate(const EnvironmentInterface &gas, double sqrtT,\n                     double T_mu, double MFP, double vol, const Cell &sys) const\n{\n    double rate(1.0);\n    double fm(0.0);\n    double sf(0.0);\n    double n(0.0);\n    double s(0.0);\n    double y(0.0);\n    double Theta(0.0);\n    double T = sys.GasPhase().Temperature();\n\n    // Check if the rate is > 0 as found by homogeneous nucleation\n    if (IsInceptionAllowed(sys)) {\n        switch (m_itype) {\n        case iCollisional:\n            // Use the 'normal' MOPS collisional rate\n            rate = A() * vol * chemRatePart(gas);\n\n            fm   = sqrtT * m_kfm;\n            if((m_ksf1 > 0) || (m_ksf2 > 0))  {\n                // Transition regime\n                sf   = T_mu  * (m_ksf1 + (MFP*m_ksf2));\n                rate *= ((fm*sf) / (fm+sf));\n            }\n            else {\n                // Free mol regime only\n                rate *= fm;\n            }\n\n            break;\n        case iVBDZ:\n            // Wu et al (1987) Langmuir 3:266-271\n            rate = A() * vol;\n\n            s = GetSupersaturation(sys);\n            y = GetSurfaceEnergy(T);\n            n = GetMonomerConc(T);\n\n            rate *= (s * s * m_v1 * n * n);\n            rate *= sqrt(2.0 * y / (PI * m_m1));\n            rate *= exp(-16.0 * PI * y * y * y * m_v1 * m_v1 * m_v1\n                    / (3.0 * KB * KB * KB * T * T * T * log(s) * log(s)));\n\n            break;\n        case iGirshick:\n            // Girshick & Chiu (1990) J. Chem. Phys. 93:1273-1277\n            rate = A() * vol;\n\n            s = GetSupersaturation(sys);\n            y = GetSurfaceEnergy(T);\n            n = GetMonomerConc(T);\n\n            Theta = PI * m_d1 * m_d1 * y / (KB * T);\n\n            rate *= (s  * m_v1 * n * n);\n            rate *= sqrt(2.0 * y / (PI * m_m1));\n            rate *= exp(Theta - (4.0 * Theta * Theta * Theta / (27.0 * log(s) * log(s))));\n\n            break;\n        }\n    } else {\n        // We have d < d_crit, return 0.\n        rate = 0.0;\n    }\n\n    return rate;\n}\n\n/*!\n * Calculates the gas-phase chemistry contribution to the rate\n * expression.  This is overloaded as Avogadro's number must be\n * included in the terms for inception processes.\n *\n * @param[in]    gas      interface to gas mixture\n */\ndouble SiliconInception::chemRatePart(const EnvironmentInterface &gas) const\n{\n    // Factor of 0.5 adjusts for doubling counting of pairs of molecules in the number\n    // of possible collisions.\n    double rate = 0.5;\n\n    Sprog::StoichMap::const_iterator i;\n    for (i=m_reac.begin(); i!=m_reac.end(); ++i) {\n        //std::cerr << \"Mole frac to use \" << fracs[i->first] << std::endl;\n        double conc = gas.SpeciesConcentration(i->first);\n        for (int j=0; j!=i->second; ++j) {\n            rate *= (NA * conc);\n        }\n    }\n\n    return rate;\n}\n\n\n// RATE TERM CALCULATIONS.\n\n// Returns the number of rate terms for this process (one).\nunsigned int SiliconInception::TermCount(void) const {return 1;}\n\n// Calculates the rate terms given an iterator to a double vector. The\n// iterator is advanced to the position after the last term for this\n// process.  Returns the sum of all terms.\ndouble SiliconInception::RateTerms(const double t, const Cell &sys,\n                               const Geometry::LocalGeometry1d &local_geom,\n                               fvector::iterator &iterm) const\n{\n    // Get the current chemical conditions.\n    double T = sys.GasPhase().Temperature();\n    double P = sys.GasPhase().Pressure();\n\n    // Calculate the single rate term and advance iterator.\n    *iterm = Rate(sys.GasPhase(), sqrt(T),\n                  T/sys.GasPhase().Viscosity(), MeanFreePathAir(T,P),\n                  sys.SampleVolume(), sys);\n    return *(iterm++);\n}\n\n\n// READ/WRITE/COPY.\n\n// Creates a copy of the inception.\nSiliconInception *const SiliconInception::Clone(void) const {return new SiliconInception(*this);}\n\n// Returns the process type.  Used to identify different\n// processes and for serialisation.\nProcessType SiliconInception::ID(void) const {return Silicon_Inception_ID;}\n\n// Writes the object to a binary stream.\nvoid SiliconInception::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Serialize base class.\n        Inception::Serialize(out);\n\n        // Write free-mol parameter.\n        double v = (double)m_kfm;\n        out.write((char*)&v, sizeof(v));\n\n        // Write slip-flow parameters.\n        v = (double)m_ksf1;\n        out.write((char*)&v, sizeof(v));\n        v = (double)m_ksf2;\n        out.write((char*)&v, sizeof(v));\n\n        // Write HNT parameters\n        unsigned int num = (unsigned int)m_itype;\n        out.write((char*)&num, sizeof(num));\n        v = (double)m_vi;\n        out.write((char*)&v, sizeof(v));\n        v = (double)m_di;\n        out.write((char*)&v, sizeof(v));\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, SiliconInception::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid SiliconInception::Deserialize(std::istream &in, const Sweep::Mechanism &mech)\n{\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        double val = 0.0;\n        unsigned int num(0);\n\n        switch (version) {\n            case 0:\n                // Deserialize base class.\n                Inception::Deserialize(in, mech);\n\n                // Read free-mol parameter.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_kfm = (double)val;\n\n                // Read slip-flow parameters.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_ksf1 = (double)val;\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_ksf2 = (double)val;\n\n                // Read HNT parameters\n                in.read(reinterpret_cast<char*>(&num), sizeof(num));\n                m_itype = (InceptionType)num;\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_vi = (double)val;\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_di = (double)val;\n\n                break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, SiliconInception::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, SiliconInception::Deserialize).\");\n    }\n}\n", "meta": {"hexsha": "9e9e413ff9f96add3f915634cc32b7378b153916", "size": 27411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_silicon_inception.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_silicon_inception.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_silicon_inception.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 31.3986254296, "max_line_length": 121, "alphanum_fraction": 0.6048301777, "num_tokens": 7092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.0427221951088388, "lm_q1q2_score": 0.018213394255924758}}
{"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_VECTOR_PROXY_\r\n#define _BOOST_UBLAS_VECTOR_PROXY_\r\n\r\n#include <boost/numeric/ublas/vector_expression.hpp>\r\n#include <boost/numeric/ublas/detail/vector_assign.hpp>\r\n#include <boost/numeric/ublas/detail/temporary.hpp>\r\n\r\n// Iterators based on ideas of Jeremy Siek\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    // Vector based range class\r\n    template<class V>\r\n    class vector_range:\r\n        public vector_expression<vector_range<V> > {\r\n\r\n        typedef vector_range<V> self_type;\r\n    public:\r\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\r\n        using vector_expression<self_type>::operator ();\r\n#endif\r\n        typedef const V const_vector_type;\r\n        typedef V vector_type;\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typedef typename V::value_type value_type;\r\n        typedef typename V::const_reference const_reference;\r\n        typedef typename boost::mpl::if_<boost::is_const<V>,\r\n                                          typename V::const_reference,\r\n                                          typename V::reference>::type reference;\r\n        typedef typename boost::mpl::if_<boost::is_const<V>,\r\n                                          typename V::const_closure_type,\r\n                                          typename V::closure_type>::type vector_closure_type;\r\n        typedef basic_range<size_type, difference_type> range_type;\r\n        typedef const self_type const_closure_type;\r\n        typedef self_type closure_type;\r\n        typedef typename storage_restrict_traits<typename V::storage_category,\r\n                                                 dense_proxy_tag>::storage_category storage_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        vector_range (vector_type &data, const range_type &r):\r\n            data_ (data), r_ (r.preprocess (data.size ())) {\r\n            // Early checking of preconditions here.\r\n            // BOOST_UBLAS_CHECK (r_.start () <= data_.size () &&\r\n            //                   r_.start () + r_.size () <= data_.size (), bad_index ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_range (const vector_closure_type &data, const range_type &r, bool):\r\n            data_ (data), r_ (r.preprocess (data.size ())) {\r\n            // Early checking of preconditions here.\r\n            // BOOST_UBLAS_CHECK (r_.start () <= data_.size () &&\r\n            //                    r_.start () + r_.size () <= data_.size (), bad_index ());\r\n        }\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type start () const {\r\n            return r_.start ();\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return r_.size ();\r\n        }\r\n\r\n        // Storage accessors\r\n        BOOST_UBLAS_INLINE\r\n        const vector_closure_type &data () const {\r\n            return data_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_closure_type &data () {\r\n            return data_;\r\n        }\r\n\r\n        // Element access\r\n#ifndef BOOST_UBLAS_PROXY_CONST_MEMBER\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type i) const {\r\n            return data_ (r_ (i));\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) {\r\n            return data_ (r_ (i));\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) {\r\n            return (*this) (i);\r\n        }\r\n#else\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) const {\r\n            return data_ (r_ (i));\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n#endif\r\n\r\n        // ISSUE can this be done in free project function?\r\n        // Although a const function can create a non-const proxy to a non-const object\r\n        // Critical is that vector_type and data_ (vector_closure_type) are const correct\r\n        BOOST_UBLAS_INLINE\r\n        vector_range<vector_type> project (const range_type &r) const {\r\n            return vector_range<vector_type> (data_, r_.compose (r.preprocess (data_.size ())), false);\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &operator = (const vector_range &vr) {\r\n            // ISSUE need a temporary, proxy can be overlaping alias\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (vr));\r\n            return *this;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &assign_temporary (vector_range &vr) {\r\n            // assign elements, proxied container remains the same\r\n            vector_assign<scalar_assign> (*this, vr);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &operator = (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &operator += (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (*this + ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &plus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_plus_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &operator -= (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (*this - ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &minus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_minus_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &operator *= (const AT &at) {\r\n            vector_assign_scalar<scalar_multiplies_assign> (*this, at);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector_range &operator /= (const AT &at) {\r\n            vector_assign_scalar<scalar_divides_assign> (*this, at);\r\n            return *this;\r\n        }\r\n\r\n        // Closure comparison\r\n        BOOST_UBLAS_INLINE\r\n        bool same_closure (const vector_range &vr) const {\r\n            return (*this).data_.same_closure (vr.data_);\r\n        }\r\n\r\n        // Comparison\r\n        BOOST_UBLAS_INLINE\r\n        bool operator == (const vector_range &vr) const {\r\n            return (*this).data_ == vr.data_ && r_ == vr.r_;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (vector_range vr) {\r\n            if (this != &vr) {\r\n                BOOST_UBLAS_CHECK (size () == vr.size (), bad_size ());\r\n                // Sparse ranges may be nonconformant now.\r\n                // std::swap_ranges (begin (), end (), vr.begin ());\r\n                vector_swap<scalar_swap> (*this, vr);\r\n            }\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (vector_range vr1, vector_range vr2) {\r\n            vr1.swap (vr2);\r\n        }\r\n\r\n        // Iterator types\r\n    private:\r\n        typedef typename V::const_iterator const_subiterator_type;\r\n        typedef typename boost::mpl::if_<boost::is_const<V>,\r\n                                          typename V::const_iterator,\r\n                                          typename V::iterator>::type subiterator_type;\r\n\r\n    public:\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        typedef indexed_iterator<vector_range<vector_type>,\r\n                                 typename subiterator_type::iterator_category> iterator;\r\n        typedef indexed_const_iterator<vector_range<vector_type>,\r\n                                       typename const_subiterator_type::iterator_category> const_iterator;\r\n#else\r\n        class const_iterator;\r\n        class iterator;\r\n#endif\r\n\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n            const_subiterator_type it (data_.find (start () + i));\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return const_iterator (*this, it.index ());\r\n#else\r\n            return const_iterator (*this, it);\r\n#endif\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator find (size_type i) {\r\n            subiterator_type it (data_.find (start () + i));\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return iterator (*this, it.index ());\r\n#else\r\n            return iterator (*this, it);\r\n#endif\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class const_iterator:\r\n            public container_const_reference<vector_range>,\r\n            public iterator_base_traits<typename const_subiterator_type::iterator_category>::template\r\n                        iterator_base<const_iterator, value_type>::type {\r\n        public:\r\n            typedef typename const_subiterator_type::difference_type difference_type;\r\n            typedef typename const_subiterator_type::value_type value_type;\r\n            typedef typename const_subiterator_type::reference reference;\r\n            typedef typename const_subiterator_type::pointer pointer;\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const self_type &vr, const const_subiterator_type &it):\r\n                container_const_reference<self_type> (vr), it_ (it) {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const typename self_type::iterator &it):  // ISSUE self_type:: stops VC8 using std::iterator here\r\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\r\n                return *it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator [] (difference_type n) const {\r\n                return *(*this + n);\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                return it_.index () - (*this) ().start ();\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            const_subiterator_type it_;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (size ());\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class iterator:\r\n            public container_reference<vector_range>,\r\n            public iterator_base_traits<typename subiterator_type::iterator_category>::template\r\n                        iterator_base<iterator, value_type>::type {\r\n        public:\r\n            typedef typename subiterator_type::difference_type difference_type;\r\n            typedef typename subiterator_type::value_type value_type;\r\n            typedef typename subiterator_type::reference reference;\r\n            typedef typename subiterator_type::pointer pointer;\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            iterator ():\r\n                container_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            iterator (self_type &vr, const subiterator_type &it):\r\n                container_reference<self_type> (vr), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            reference operator * () const {\r\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\r\n                return *it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            reference operator [] (difference_type n) const {\r\n                return *(*this + n);\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                return it_.index () - (*this) ().start ();\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator = (const iterator &it) {\r\n                container_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            subiterator_type it_;\r\n\r\n            friend class const_iterator;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        iterator begin () {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator end () {\r\n            return find (size ());\r\n        }\r\n\r\n        // Reverse iterator\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n        typedef reverse_iterator_base<iterator> reverse_iterator;\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rbegin () {\r\n            return reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rend () {\r\n            return reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        vector_closure_type data_;\r\n        range_type r_;\r\n    };\r\n\r\n    // Simple Projections\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_range<V> subrange (V &data, typename V::size_type start, typename V::size_type stop) {\r\n        typedef basic_range<typename V::size_type, typename V::difference_type> range_type;\r\n        return vector_range<V> (data, range_type (start, stop));\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_range<const V> subrange (const V &data, typename V::size_type start, typename V::size_type stop) {\r\n        typedef basic_range<typename V::size_type, typename V::difference_type> range_type;\r\n        return vector_range<const V> (data, range_type (start, stop));\r\n    }\r\n\r\n    // Generic Projections\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_range<V> project (V &data, typename vector_range<V>::range_type const &r) {\r\n        return vector_range<V> (data, r);\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_range<const V> project (const V &data, typename vector_range<V>::range_type const &r) {\r\n        // ISSUE was: return vector_range<V> (const_cast<V &> (data), r);\r\n        return vector_range<const V> (data, r);\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_range<V> project (vector_range<V> &data, const typename vector_range<V>::range_type &r) {\r\n        return data.project (r);\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_range<V> project (const vector_range<V> &data, const typename vector_range<V>::range_type &r) {\r\n        return data.project (r);\r\n    }\r\n\r\n    // Specialization of temporary_traits\r\n    template <class V>\r\n    struct vector_temporary_traits< vector_range<V> >\r\n    : vector_temporary_traits< V > {} ;\r\n    template <class V>\r\n    struct vector_temporary_traits< const vector_range<V> >\r\n    : vector_temporary_traits< V > {} ;\r\n\r\n\r\n    // Vector based slice class\r\n    template<class V>\r\n    class vector_slice:\r\n        public vector_expression<vector_slice<V> > {\r\n\r\n        typedef vector_slice<V> self_type;\r\n    public:\r\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\r\n        using vector_expression<self_type>::operator ();\r\n#endif\r\n        typedef const V const_vector_type;\r\n        typedef V vector_type;\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typedef typename V::value_type value_type;\r\n        typedef typename V::const_reference const_reference;\r\n        typedef typename boost::mpl::if_<boost::is_const<V>,\r\n                                          typename V::const_reference,\r\n                                          typename V::reference>::type reference;\r\n        typedef typename boost::mpl::if_<boost::is_const<V>,\r\n                                          typename V::const_closure_type,\r\n                                          typename V::closure_type>::type vector_closure_type;\r\n        typedef basic_range<size_type, difference_type> range_type;\r\n        typedef basic_slice<size_type, difference_type> slice_type;\r\n        typedef const self_type const_closure_type;\r\n        typedef self_type closure_type;\r\n        typedef typename storage_restrict_traits<typename V::storage_category,\r\n                                                 dense_proxy_tag>::storage_category storage_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice (vector_type &data, const slice_type &s):\r\n            data_ (data), s_ (s.preprocess (data.size ())) {\r\n            // Early checking of preconditions here.\r\n            // BOOST_UBLAS_CHECK (s_.start () <= data_.size () &&\r\n            //                    s_.start () + s_.stride () * (s_.size () - (s_.size () > 0)) <= data_.size (), bad_index ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice (const vector_closure_type &data, const slice_type &s, int):\r\n            data_ (data), s_ (s.preprocess (data.size ())) {\r\n            // Early checking of preconditions here.\r\n            // BOOST_UBLAS_CHECK (s_.start () <= data_.size () &&\r\n            //                    s_.start () + s_.stride () * (s_.size () - (s_.size () > 0)) <= data_.size (), bad_index ());\r\n        }\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type start () const {\r\n            return s_.start ();\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        difference_type stride () const {\r\n            return s_.stride ();\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return s_.size ();\r\n        }\r\n\r\n        // Storage accessors\r\n        BOOST_UBLAS_INLINE\r\n        const vector_closure_type &data () const {\r\n            return data_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_closure_type &data () {\r\n            return data_;\r\n        }\r\n\r\n        // Element access\r\n#ifndef BOOST_UBLAS_PROXY_CONST_MEMBER\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type i) const {\r\n            return data_ (s_ (i));\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) {\r\n            return data_ (s_ (i));\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) {\r\n            return (*this) (i);\r\n        }\r\n#else\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) const {\r\n            return data_ (s_ (i));\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n#endif\r\n\r\n        // ISSUE can this be done in free project function?\r\n        // Although a const function can create a non-const proxy to a non-const object\r\n        // Critical is that vector_type and data_ (vector_closure_type) are const correct\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice<vector_type> project (const range_type &r) const {\r\n            return vector_slice<vector_type>  (data_, s_.compose (r.preprocess (data_.size ())), false);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice<vector_type> project (const slice_type &s) const {\r\n            return vector_slice<vector_type>  (data_, s_.compose (s.preprocess (data_.size ())), false);\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &operator = (const vector_slice &vs) {\r\n            // ISSUE need a temporary, proxy can be overlaping alias\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (vs));\r\n            return *this;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &assign_temporary (vector_slice &vs) {\r\n            // assign elements, proxied container remains the same\r\n            vector_assign<scalar_assign> (*this, vs);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &operator = (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &operator += (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (*this + ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &plus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_plus_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &operator -= (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (*this - ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &minus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_minus_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &operator *= (const AT &at) {\r\n            vector_assign_scalar<scalar_multiplies_assign> (*this, at);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector_slice &operator /= (const AT &at) {\r\n            vector_assign_scalar<scalar_divides_assign> (*this, at);\r\n            return *this;\r\n        }\r\n\r\n        // Closure comparison\r\n        BOOST_UBLAS_INLINE\r\n        bool same_closure (const vector_slice &vr) const {\r\n            return (*this).data_.same_closure (vr.data_);\r\n        }\r\n\r\n        // Comparison\r\n        BOOST_UBLAS_INLINE\r\n        bool operator == (const vector_slice &vs) const {\r\n            return (*this).data_ == vs.data_ && s_ == vs.s_;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (vector_slice vs) {\r\n            if (this != &vs) {\r\n                BOOST_UBLAS_CHECK (size () == vs.size (), bad_size ());\r\n                // Sparse ranges may be nonconformant now.\r\n                // std::swap_ranges (begin (), end (), vs.begin ());\r\n                vector_swap<scalar_swap> (*this, vs);\r\n            }\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (vector_slice vs1, vector_slice vs2) {\r\n            vs1.swap (vs2);\r\n        }\r\n\r\n        // Iterator types\r\n    private:\r\n        // Use slice as an index - FIXME this fails for packed assignment\r\n        typedef typename slice_type::const_iterator const_subiterator_type;\r\n        typedef typename slice_type::const_iterator subiterator_type;\r\n\r\n    public:\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        typedef indexed_iterator<vector_slice<vector_type>,\r\n                                 typename vector_type::iterator::iterator_category> iterator;\r\n        typedef indexed_const_iterator<vector_slice<vector_type>,\r\n                                       typename vector_type::const_iterator::iterator_category> const_iterator;\r\n#else\r\n        class const_iterator;\r\n        class iterator;\r\n#endif\r\n\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return const_iterator (*this, i);\r\n#else\r\n            return const_iterator (*this, s_.begin () + i);\r\n#endif\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator find (size_type i) {\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return iterator (*this, i);\r\n#else\r\n            return iterator (*this, s_.begin () + i);\r\n#endif\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class const_iterator:\r\n            public container_const_reference<vector_slice>,\r\n            public iterator_base_traits<typename V::const_iterator::iterator_category>::template\r\n                        iterator_base<const_iterator, value_type>::type {\r\n        public:\r\n            typedef typename V::const_iterator::difference_type difference_type;\r\n            typedef typename V::const_iterator::value_type value_type;\r\n            typedef typename V::const_reference reference;    //FIXME due to indexing access\r\n            typedef typename V::const_iterator::pointer pointer;\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const self_type &vs, const const_subiterator_type &it):\r\n                container_const_reference<self_type> (vs), it_ (it) {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const typename self_type::iterator &it):  // ISSUE self_type:: stops VC8 using std::iterator here\r\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                // FIXME replace find with at_element\r\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\r\n                return (*this) ().data_ (*it_);\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator [] (difference_type n) const {\r\n                return *(*this + n);\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                return it_.index ();\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            const_subiterator_type it_;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (size ());\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class iterator:\r\n            public container_reference<vector_slice>,\r\n            public iterator_base_traits<typename V::iterator::iterator_category>::template\r\n                        iterator_base<iterator, value_type>::type {\r\n        public:\r\n            typedef typename V::iterator::difference_type difference_type;\r\n            typedef typename V::iterator::value_type value_type;\r\n            typedef typename V::reference reference;    //FIXME due to indexing access\r\n            typedef typename V::iterator::pointer pointer;\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            iterator ():\r\n                container_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            iterator (self_type &vs, const subiterator_type &it):\r\n                container_reference<self_type> (vs), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            reference operator * () const {\r\n                // FIXME replace find with at_element\r\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\r\n                return (*this) ().data_ (*it_);\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            reference operator [] (difference_type n) const {\r\n                return *(*this + n);\r\n            }\r\n\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                return it_.index ();\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator = (const iterator &it) {\r\n                container_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            subiterator_type it_;\r\n\r\n            friend class const_iterator;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        iterator begin () {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator end () {\r\n            return find (size ());\r\n        }\r\n\r\n        // Reverse iterator\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n        typedef reverse_iterator_base<iterator> reverse_iterator;\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rbegin () {\r\n            return reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rend () {\r\n            return reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        vector_closure_type data_;\r\n        slice_type s_;\r\n    };\r\n\r\n    // Simple Projections\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_slice<V> subslice (V &data, typename V::size_type start, typename V::difference_type stride, typename V::size_type size) {\r\n        typedef basic_slice<typename V::size_type, typename V::difference_type> slice_type;\r\n        return vector_slice<V> (data, slice_type (start, stride, size));\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_slice<const V> subslice (const V &data, typename V::size_type start, typename V::difference_type stride, typename V::size_type size)  {\r\n        typedef basic_slice<typename V::size_type, typename V::difference_type> slice_type;\r\n        return vector_slice<const V> (data, slice_type (start, stride, size));\r\n    }\r\n\r\n    // Generic Projections\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_slice<V> project (V &data, const typename vector_slice<V>::slice_type &s) {\r\n        return vector_slice<V> (data, s);\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_slice<const V> project (const V &data, const typename vector_slice<V>::slice_type &s) {\r\n        // ISSUE was: return vector_slice<V> (const_cast<V &> (data), s);\r\n        return vector_slice<const V> (data, s);\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_slice<V> project (vector_slice<V> &data, const typename vector_slice<V>::slice_type &s) {\r\n        return data.project (s);\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_slice<V> project (const vector_slice<V> &data, const typename vector_slice<V>::slice_type &s) {\r\n        return data.project (s);\r\n    }\r\n    // ISSUE in the following two functions it would be logical to use vector_slice<V>::range_type but this confuses VC7.1 and 8.0\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    vector_slice<V> project (vector_slice<V> &data, const typename vector_range<V>::range_type &r) {\r\n        return data.project (r);\r\n    }\r\n    template<class V>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_slice<V> project (const vector_slice<V> &data, const typename vector_range<V>::range_type &r) {\r\n        return data.project (r);\r\n    }\r\n\r\n    // Specialization of temporary_traits\r\n    template <class V>\r\n    struct vector_temporary_traits< vector_slice<V> >\r\n    : vector_temporary_traits< V > {} ;\r\n    template <class V>\r\n    struct vector_temporary_traits< const vector_slice<V> >\r\n    : vector_temporary_traits< V > {} ;\r\n\r\n\r\n    // Vector based indirection class\r\n    // Contributed by Toon Knapen.\r\n    // Extended and optimized by Kresimir Fresl.\r\n    template<class V, class IA>\r\n    class vector_indirect:\r\n        public vector_expression<vector_indirect<V, IA> > {\r\n\r\n        typedef vector_indirect<V, IA> self_type;\r\n    public:\r\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\r\n        using vector_expression<self_type>::operator ();\r\n#endif\r\n        typedef const V const_vector_type;\r\n        typedef V vector_type;\r\n        typedef const IA const_indirect_array_type;\r\n        typedef IA indirect_array_type;\r\n        typedef typename V::size_type size_type;\r\n        typedef typename V::difference_type difference_type;\r\n        typedef typename V::value_type value_type;\r\n        typedef typename V::const_reference const_reference;\r\n        typedef typename boost::mpl::if_<boost::is_const<V>,\r\n                                          typename V::const_reference,\r\n                                          typename V::reference>::type reference;\r\n        typedef typename boost::mpl::if_<boost::is_const<V>,\r\n                                          typename V::const_closure_type,\r\n                                          typename V::closure_type>::type vector_closure_type;\r\n        typedef basic_range<size_type, difference_type> range_type;\r\n        typedef basic_slice<size_type, difference_type> slice_type;\r\n        typedef const self_type const_closure_type;\r\n        typedef self_type closure_type;\r\n        typedef typename storage_restrict_traits<typename V::storage_category,\r\n                                                 dense_proxy_tag>::storage_category storage_category;\r\n\r\n        // Construction and destruction\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect (vector_type &data, size_type size):\r\n            data_ (data), ia_ (size) {}\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect (vector_type &data, const indirect_array_type &ia):\r\n            data_ (data), ia_ (ia.preprocess (data.size ())) {}\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect (const vector_closure_type &data, const indirect_array_type &ia, int):\r\n            data_ (data), ia_ (ia.preprocess (data.size ())) {}\r\n\r\n        // Accessors\r\n        BOOST_UBLAS_INLINE\r\n        size_type size () const {\r\n            return ia_.size ();\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_indirect_array_type &indirect () const {\r\n            return ia_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        indirect_array_type &indirect () {\r\n            return ia_;\r\n        }\r\n\r\n        // Storage accessors\r\n        BOOST_UBLAS_INLINE\r\n        const vector_closure_type &data () const {\r\n            return data_;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_closure_type &data () {\r\n            return data_;\r\n        }\r\n\r\n        // Element access\r\n#ifndef BOOST_UBLAS_PROXY_CONST_MEMBER\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator () (size_type i) const {\r\n            return data_ (ia_ (i));\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) {\r\n            return data_ (ia_ (i));\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) {\r\n            return (*this) (i);\r\n        }\r\n#else\r\n        BOOST_UBLAS_INLINE\r\n        reference operator () (size_type i) const {\r\n            return data_ (ia_ (i));\r\n        }\r\n\r\n        BOOST_UBLAS_INLINE\r\n        reference operator [] (size_type i) const {\r\n            return (*this) (i);\r\n        }\r\n#endif\r\n\r\n        // ISSUE can this be done in free project function?\r\n        // Although a const function can create a non-const proxy to a non-const object\r\n        // Critical is that vector_type and data_ (vector_closure_type) are const correct\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect<vector_type, indirect_array_type> project (const range_type &r) const {\r\n            return vector_indirect<vector_type, indirect_array_type> (data_, ia_.compose (r.preprocess (data_.size ())), 0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect<vector_type, indirect_array_type> project (const slice_type &s) const {\r\n            return vector_indirect<vector_type, indirect_array_type> (data_, ia_.compose (s.preprocess (data_.size ())), 0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect<vector_type, indirect_array_type> project (const indirect_array_type &ia) const {\r\n            return vector_indirect<vector_type, indirect_array_type> (data_, ia_.compose (ia.preprocess (data_.size ())), 0);\r\n        }\r\n\r\n        // Assignment\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &operator = (const vector_indirect &vi) {\r\n            // ISSUE need a temporary, proxy can be overlaping alias\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (vi));\r\n            return *this;\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &assign_temporary (vector_indirect &vi) {\r\n            // assign elements, proxied container remains the same\r\n            vector_assign<scalar_assign> (*this, vi);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &operator = (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &operator += (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (*this + ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &plus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_plus_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &operator -= (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_assign> (*this, typename vector_temporary_traits<V>::type (*this - ae));\r\n            return *this;\r\n        }\r\n        template<class AE>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &minus_assign (const vector_expression<AE> &ae) {\r\n            vector_assign<scalar_minus_assign> (*this, ae);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &operator *= (const AT &at) {\r\n            vector_assign_scalar<scalar_multiplies_assign> (*this, at);\r\n            return *this;\r\n        }\r\n        template<class AT>\r\n        BOOST_UBLAS_INLINE\r\n        vector_indirect &operator /= (const AT &at) {\r\n            vector_assign_scalar<scalar_divides_assign> (*this, at);\r\n            return *this;\r\n        }\r\n\r\n        // Closure comparison\r\n        BOOST_UBLAS_INLINE\r\n        bool same_closure (const vector_indirect &vr) const {\r\nreturn true;\r\n        }\r\n\r\n        // Comparison\r\n        BOOST_UBLAS_INLINE\r\n        bool operator == (const vector_indirect &vi) const {\r\n            return (*this).data_ == vi.data_ && ia_ == vi.ia_;\r\n        }\r\n\r\n        // Swapping\r\n        BOOST_UBLAS_INLINE\r\n        void swap (vector_indirect vi) {\r\n            if (this != &vi) {\r\n                BOOST_UBLAS_CHECK (size () == vi.size (), bad_size ());\r\n                // Sparse ranges may be nonconformant now.\r\n                // std::swap_ranges (begin (), end (), vi.begin ());\r\n                vector_swap<scalar_swap> (*this, vi);\r\n            }\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        friend void swap (vector_indirect vi1, vector_indirect vi2) {\r\n            vi1.swap (vi2);\r\n        }\r\n\r\n        // Iterator types\r\n    private:\r\n        // Use indirect array as an index - FIXME this fails for packed assignment\r\n        typedef typename IA::const_iterator const_subiterator_type;\r\n        typedef typename IA::const_iterator subiterator_type;\r\n\r\n    public:\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        typedef indexed_iterator<vector_indirect<vector_type, indirect_array_type>,\r\n                                 typename vector_type::iterator::iterator_category> iterator;\r\n        typedef indexed_const_iterator<vector_indirect<vector_type, indirect_array_type>,\r\n                                       typename vector_type::const_iterator::iterator_category> const_iterator;\r\n#else\r\n        class const_iterator;\r\n        class iterator;\r\n#endif\r\n        // Element lookup\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator find (size_type i) const {\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return const_iterator (*this, i);\r\n#else\r\n            return const_iterator (*this, ia_.begin () + i);\r\n#endif\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator find (size_type i) {\r\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n            return iterator (*this, i);\r\n#else\r\n            return iterator (*this, ia_.begin () + i);\r\n#endif\r\n        }\r\n\r\n        // Iterators simply are indices.\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class const_iterator:\r\n            public container_const_reference<vector_indirect>,\r\n            public iterator_base_traits<typename V::const_iterator::iterator_category>::template\r\n                        iterator_base<const_iterator, value_type>::type {\r\n        public:\r\n            typedef typename V::const_iterator::difference_type difference_type;\r\n            typedef typename V::const_iterator::value_type value_type;\r\n            typedef typename V::const_reference reference;    //FIXME due to indexing access\r\n            typedef typename V::const_iterator::pointer pointer;\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator ():\r\n                container_const_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const self_type &vi, const const_subiterator_type &it):\r\n                container_const_reference<self_type> (vi), it_ (it) {}\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator (const typename self_type::iterator &it):  // ISSUE self_type:: stops VC8 using std::iterator here\r\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator * () const {\r\n                // FIXME replace find with at_element\r\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\r\n                return (*this) ().data_ (*it_);\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            const_reference operator [] (difference_type n) const {\r\n                return *(*this + n);\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                return it_.index ();\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            const_iterator &operator = (const const_iterator &it) {\r\n                container_const_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const const_iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            const_subiterator_type it_;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator begin () const {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_iterator end () const {\r\n            return find (size ());\r\n        }\r\n\r\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\r\n        class iterator:\r\n            public container_reference<vector_indirect>,\r\n            public iterator_base_traits<typename V::iterator::iterator_category>::template\r\n                        iterator_base<iterator, value_type>::type {\r\n        public:\r\n            typedef typename V::iterator::difference_type difference_type;\r\n            typedef typename V::iterator::value_type value_type;\r\n            typedef typename V::reference reference;    //FIXME due to indexing access\r\n            typedef typename V::iterator::pointer pointer;\r\n\r\n            // Construction and destruction\r\n            BOOST_UBLAS_INLINE\r\n            iterator ():\r\n                container_reference<self_type> (), it_ () {}\r\n            BOOST_UBLAS_INLINE\r\n            iterator (self_type &vi, const subiterator_type &it):\r\n                container_reference<self_type> (vi), it_ (it) {}\r\n\r\n            // Arithmetic\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator ++ () {\r\n                ++ it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -- () {\r\n                -- it_;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator += (difference_type n) {\r\n                it_ += n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator -= (difference_type n) {\r\n                it_ -= n;\r\n                return *this;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            difference_type operator - (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ - it.it_;\r\n            }\r\n\r\n            // Dereference\r\n            BOOST_UBLAS_INLINE\r\n            reference operator * () const {\r\n                // FIXME replace find with at_element\r\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\r\n                return (*this) ().data_ (*it_);\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            reference operator [] (difference_type n) const {\r\n                return *(*this + n);\r\n            }\r\n\r\n            // Index\r\n            BOOST_UBLAS_INLINE\r\n            size_type index () const {\r\n                return it_.index ();\r\n            }\r\n\r\n            // Assignment\r\n            BOOST_UBLAS_INLINE\r\n            iterator &operator = (const iterator &it) {\r\n                container_reference<self_type>::assign (&it ());\r\n                it_ = it.it_;\r\n                return *this;\r\n            }\r\n\r\n            // Comparison\r\n            BOOST_UBLAS_INLINE\r\n            bool operator == (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ == it.it_;\r\n            }\r\n            BOOST_UBLAS_INLINE\r\n            bool operator < (const iterator &it) const {\r\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\r\n                return it_ < it.it_;\r\n            }\r\n\r\n        private:\r\n            subiterator_type it_;\r\n\r\n            friend class const_iterator;\r\n        };\r\n#endif\r\n\r\n        BOOST_UBLAS_INLINE\r\n        iterator begin () {\r\n            return find (0);\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        iterator end () {\r\n            return find (size ());\r\n        }\r\n\r\n        // Reverse iterator\r\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\r\n        typedef reverse_iterator_base<iterator> reverse_iterator;\r\n\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rbegin () const {\r\n            return const_reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        const_reverse_iterator rend () const {\r\n            return const_reverse_iterator (begin ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rbegin () {\r\n            return reverse_iterator (end ());\r\n        }\r\n        BOOST_UBLAS_INLINE\r\n        reverse_iterator rend () {\r\n            return reverse_iterator (begin ());\r\n        }\r\n\r\n    private:\r\n        vector_closure_type data_;\r\n        indirect_array_type ia_;\r\n    };\r\n\r\n    // Projections\r\n    template<class V, class A>\r\n    BOOST_UBLAS_INLINE\r\n    vector_indirect<V, indirect_array<A> > project (V &data, const indirect_array<A> &ia) {\r\n        return vector_indirect<V, indirect_array<A> > (data, ia);\r\n    }\r\n    template<class V, class A>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_indirect<const V, indirect_array<A> > project (const V &data, const indirect_array<A> &ia) {\r\n        // ISSUE was: return vector_indirect<V, indirect_array<A> > (const_cast<V &> (data), ia)\r\n        return vector_indirect<const V, indirect_array<A> > (data, ia);\r\n    }\r\n    template<class V, class IA>\r\n    BOOST_UBLAS_INLINE\r\n    vector_indirect<V, IA> project (vector_indirect<V, IA> &data, const typename vector_indirect<V, IA>::range_type &r) {\r\n        return data.project (r);\r\n    }\r\n    template<class V, class IA>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_indirect<V, IA> project (const vector_indirect<V, IA> &data, const typename vector_indirect<V, IA>::range_type &r) {\r\n        return data.project (r);\r\n    }\r\n    template<class V, class IA>\r\n    BOOST_UBLAS_INLINE\r\n    vector_indirect<V, IA> project (vector_indirect<V, IA> &data, const typename vector_indirect<V, IA>::slice_type &s) {\r\n        return data.project (s);\r\n    }\r\n    template<class V, class IA>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_indirect<V, IA> project (const vector_indirect<V, IA> &data, const typename vector_indirect<V, IA>::slice_type &s) {\r\n        return data.project (s);\r\n    }\r\n    template<class V, class A>\r\n    BOOST_UBLAS_INLINE\r\n    vector_indirect<V, indirect_array<A> > project (vector_indirect<V, indirect_array<A> > &data, const indirect_array<A> &ia) {\r\n        return data.project (ia);\r\n    }\r\n    template<class V, class A>\r\n    BOOST_UBLAS_INLINE\r\n    const vector_indirect<V, indirect_array<A> > project (const vector_indirect<V, indirect_array<A> > &data, const indirect_array<A> &ia) {\r\n        return data.project (ia);\r\n    }\r\n\r\n    // Specialization of temporary_traits\r\n    template <class V>\r\n    struct vector_temporary_traits< vector_indirect<V> >\r\n    : vector_temporary_traits< V > {} ;\r\n    template <class V>\r\n    struct vector_temporary_traits< const vector_indirect<V> >\r\n    : vector_temporary_traits< V > {} ;\r\n\r\n}}}\r\n\r\n#endif\r\n", "meta": {"hexsha": "73cf5c4c31744f50697ae785665806a5932c0de0", "size": 59416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/numeric/ublas/vector_proxy.hpp", "max_stars_repo_name": "dstrigl/mcotf", "max_stars_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "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/numeric/ublas/vector_proxy.hpp", "max_issues_repo_name": "dstrigl/mcotf", "max_issues_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "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/numeric/ublas/vector_proxy.hpp", "max_forks_repo_name": "dstrigl/mcotf", "max_forks_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.820496499, "max_line_length": 147, "alphanum_fraction": 0.5606570621, "num_tokens": 12196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197264277872, "lm_q2_score": 0.05500528751889616, "lm_q1q2_score": 0.018213335755338674}}
{"text": "#define  __declspec(dllexport)\r\n\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n\r\n#include \"geodesic_mesh.h\"\r\n#include \"geodesic_algorithm_dijkstra_alternative.h\"\r\n#include \"geodesic_algorithm_dijkstra.h\"\r\n#include \"geodesic_algorithm_subdivision.h\"\r\n#include \"geodesic_algorithm_exact.h\"\r\n#include \"geodesic_matlab_api.h\"\r\n\r\ntypedef boost::shared_ptr<geodesic::Mesh> mesh_shared_pointer;\r\nstd::vector<mesh_shared_pointer> meshes;\r\n\r\ntypedef boost::shared_ptr<geodesic::GeodesicAlgorithmBase> algorithm_shared_pointer;\r\nstd::vector<algorithm_shared_pointer> algorithms;\r\n\r\nstd::vector<geodesic::SurfacePoint> output_path;\r\ngeodesic::OutputBuffer output_buffer, output_buffer1;\r\n\r\n\r\nstd::size_t find_mesh_id(geodesic::Mesh* mesh)\r\n{\r\n\tfor(std::size_t i=0; i<meshes.size(); ++i)\r\n\t{\r\n\t\tif(meshes[i].get() == mesh)\r\n\t\t{\r\n\t\t\treturn i;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n long distance_and_source(long algorithm_id,\t\t//quickly find what source this point belongs to and what is the distance to this source\r\n\t\t\t\t\t\t\t\t\t\t\t double* destination,\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t double* best_source_distance)\r\n{\r\n\tgeodesic::SurfacePoint point;\r\n\tgeodesic::GeodesicAlgorithmBase* algorithm = algorithms[algorithm_id].get();\r\n\tstd::size_t mesh_id = find_mesh_id(algorithm->mesh());\r\n\tgeodesic::fill_surface_point_structure(&point, \r\n\t\t\t\t\t\t\t\t\t\t   destination, \r\n\t\t\t\t\t\t\t\t\t\t   algorithm->mesh());\r\n\r\n\tstd::size_t best_source = algorithm->best_source(point,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t *best_source_distance);\r\n\treturn best_source;\r\n}\r\n\r\n long distance_and_source_for_all_vertices(long algorithm_id,\t//same idea as in the previous function\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  double** distances,\t//list distance/source info for all vertices of the mesh\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  long** sources)\r\n{\r\n\r\n\tgeodesic::GeodesicAlgorithmBase* algorithm = algorithms[algorithm_id].get();\r\n\tgeodesic::Mesh* mesh = algorithm->mesh();\r\n\r\n\toutput_buffer.allocate<double>(mesh->vertices().size());\t//allocate space for distances\r\n\t*distances = output_buffer.get<double>();\r\n\r\n\toutput_buffer1.allocate<long>(mesh->vertices().size());\t\t//allocate space for sources\r\n\t*sources = output_buffer1.get<long>();\r\n\r\n\r\n\tfor(std::size_t i = 0; i < mesh->vertices().size(); ++i)\r\n\t{\r\n\t\tgeodesic::SurfacePoint point(&mesh->vertices()[i]);\r\n\t\tdouble* distace_location = *distances + i;\r\n\t\t(*sources)[i] = algorithm->best_source(point, *distace_location);\r\n\t}\r\n\r\n\treturn mesh->vertices().size();\r\n}\r\n\r\n\r\n long trace_back(long algorithm_id,\r\n\t\t\t\t\t\t\t\t\tdouble* destination,\r\n\t\t\t\t\t\t\t\t\tdouble** path)\r\n{\r\n\tgeodesic::SurfacePoint point;\r\n\tgeodesic::GeodesicAlgorithmBase* algorithm = algorithms[algorithm_id].get();\r\n\tgeodesic::fill_surface_point_structure(&point, \r\n\t\t\t\t\t\t\t\t\t\t   destination, \r\n\t\t\t\t\t\t\t\t\t\t   algorithm->mesh());\r\n\r\n\talgorithm->trace_back(point,\r\n\t\t\t\t\t\t  output_path);\r\n\r\n\tstd::size_t mesh_id = find_mesh_id(algorithm->mesh());\r\n\toutput_buffer.allocate<double>(output_path.size()*5);\r\n\tfor(std::size_t i=0; i<output_path.size(); ++i)\r\n\t{\r\n\t\tgeodesic::fill_surface_point_double(&output_path[i], \r\n\t\t\t\t\t\t\t\t\t\t\toutput_buffer.get<double>() + 5*i, \r\n\t\t\t\t\t\t\t\t\t\t\tmesh_id);\r\n\t}\r\n\r\n\t*path = output_buffer.get<double>();\r\n\r\n\treturn output_path.size();\r\n}\r\n\r\n void propagate(long algorithm_id,\r\n\t\t\t\t\t\t\t\t\tdouble* source_points,\t\r\n\t\t\t\t\t\t\t\t\tlong num_sources,\r\n\t\t\t\t\t\t\t\t\tdouble* stop_points,\t\r\n\t\t\t\t\t\t\t\t\tlong num_stop_points,\r\n\t\t\t\t\t\t\t\t\tdouble max_propagation_distance)\r\n{\r\n\tstd::vector<geodesic::SurfacePoint> sources(num_sources);\r\n\r\n\tgeodesic::Mesh* mesh = algorithms[algorithm_id]->mesh();\r\n\tfor(std::size_t i=0; i<num_sources; ++i)\r\n\t{\r\n\t\tgeodesic::fill_surface_point_structure(&sources[i], \r\n\t\t\t\t\t\t\t\t\t\t\t\tsource_points + 5*i, \r\n\t\t\t\t\t\t\t\t\t\t\t\tmesh);\r\n\t}\r\n\r\n\tstd::vector<geodesic::SurfacePoint> stop(num_stop_points);\r\n\tfor(std::size_t i=0; i<num_stop_points; ++i)\r\n\t{\r\n\t\tgeodesic::fill_surface_point_structure(&stop[i], \r\n\t\t\t\t\t\t\t\t\t\t\t\tstop_points + 5*i, \r\n\t\t\t\t\t\t\t\t\t\t\t\tmesh);\r\n\t}\r\n\r\n\talgorithms[algorithm_id]->propagate(sources, \r\n\t\t\t\t\t\t\t\t\t\tmax_propagation_distance,\r\n\t\t\t\t\t\t\t\t\t\t&stop);\r\n}\r\n\r\n\r\n long new_mesh(long num_points,\r\n\t\t\t\t\t\t\t\t  double* points,\t\r\n\t\t\t\t\t\t\t\t  long num_triangles,\r\n\t\t\t\t\t\t\t\t  long* triangles, \r\n\t\t\t\t\t\t\t\t  long* num_edges, \r\n\t\t\t\t\t\t\t\t  double** edges)\r\n{\r\n\tmesh_shared_pointer new_mesh = mesh_shared_pointer(new geodesic::Mesh);\r\n\tmeshes.push_back(new_mesh);\r\n\r\n\tnew_mesh->initialize_mesh_data(num_points,\r\n\t\t\t\t\t\t\t\t   points,\t\r\n\t\t\t\t\t\t\t\t   num_triangles,\r\n\t\t\t\t\t\t\t\t   triangles);\r\n\r\n\t*num_edges = new_mesh->edges().size();\r\n\r\n\toutput_buffer.allocate<double>(*num_edges * 4);\r\n\t*edges = output_buffer.get<double>();\r\n\t\r\n\tfor(std::size_t i=0; i<*num_edges; ++i)\r\n\t{\r\n\t\tgeodesic::Edge& edge = new_mesh->edges()[i];\r\n\t\tdouble* buffer = *edges + 4*i;\r\n\r\n\t\tbuffer[0] = edge.adjacent_vertices()[0]->id();\r\n\t\tbuffer[1] = edge.adjacent_vertices()[1]->id();\r\n\t\tbuffer[2] = edge.adjacent_faces()[0]->id();\r\n\t\tbuffer[3] = edge.adjacent_faces().size() == 2 ? \r\n\t\t\t\t\tedge.adjacent_faces()[1]->id() : \r\n\t\t\t\t\t-1.0; \r\n\t}\r\n\r\n\treturn meshes.size() - 1;\r\n}\r\n\r\n long new_algorithm(long mesh_id,\r\n\t\t\t\t\t\t               long type,\r\n\t\t\t\t\t\t\t\t\t   long subdivision)\r\n{\r\n\tif(subdivision == 0 && type == 1)//SUBDIVISION)\r\n\t{\r\n\t\ttype = 2;\t\t//DIJKSTRA;\r\n\t}\r\n\r\n\tgeodesic::Mesh* mesh = meshes[mesh_id].get();\r\n\tgeodesic::GeodesicAlgorithmBase* algorithm;\r\n\tswitch(type)\r\n\t{\r\n\t\tcase 2: //DIJKSTRA\r\n\t\t{\r\n\t\t\talgorithm = new geodesic::GeodesicAlgorithmDijkstra(mesh);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase 1: //SUBDIVISION:\r\n\t\t{\r\n\t\t\talgorithm = new geodesic::GeodesicAlgorithmSubdivision(mesh, subdivision);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase 0://EXACT:\r\n\t\tdefault:\r\n\t\t{\r\n\t\t\talgorithm = new geodesic::GeodesicAlgorithmExact(mesh);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\talgorithms.push_back(algorithm_shared_pointer(algorithm));\r\n\r\n\treturn algorithms.size() - 1;\r\n}\r\n\r\n void delete_mesh(long id)\t\t//delete mesh and all related algorithms\r\n{\r\n\tassert(id < meshes.size());\r\n\r\n\tgeodesic::Mesh* mesh = meshes[id].get();\r\n\tfor(std::size_t i=0; i<algorithms.size(); ++i)\r\n\t{\r\n\t\tgeodesic::GeodesicAlgorithmBase* algorithm = algorithms[i].get();\r\n\t\tif(algorithm && algorithm->mesh() == mesh)\r\n\t\t{\r\n\t\t\talgorithms[i] = algorithm_shared_pointer();\r\n\t\t}\r\n\t}\r\n\r\n\tmeshes[id] = mesh_shared_pointer();\r\n}\r\n\r\n void delete_algorithm(long id)\r\n{\r\n\tif(id < algorithms.size())\r\n\t{\r\n\t\talgorithms[id] = algorithm_shared_pointer();\r\n\t}\r\n}\r\n", "meta": {"hexsha": "b4af5c137277f94ed44b48a6f65b62bcc13ee243", "size": 6271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geoc/geodesic_matlab_api.cpp", "max_stars_repo_name": "MCanales87/Toolbox-Fast-Marching-Unix", "max_stars_repo_head_hexsha": "86ba65224639c22d1c7f275d9b32871d14f2bce7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T02:33:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T02:33:06.000Z", "max_issues_repo_path": "geoc/geodesic_matlab_api.cpp", "max_issues_repo_name": "MCanales87/Toolbox-Fast-Marching-Unix", "max_issues_repo_head_hexsha": "86ba65224639c22d1c7f275d9b32871d14f2bce7", "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": "geoc/geodesic_matlab_api.cpp", "max_forks_repo_name": "MCanales87/Toolbox-Fast-Marching-Unix", "max_forks_repo_head_hexsha": "86ba65224639c22d1c7f275d9b32871d14f2bce7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-01T05:01:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T05:01:39.000Z", "avg_line_length": 26.9141630901, "max_line_length": 135, "alphanum_fraction": 0.6523680434, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.04468086804648062, "lm_q1q2_score": 0.018200009898376508}}
{"text": "/*  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n *\n */\n\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <algorithm>\n\n\n#include <stdint.h>\n#include <vector>\n#include <map>\n\n#include <boost/program_options.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n\n#include <graphlab.hpp>\n\n\n#include <graphlab/macros_def.hpp>\n\ntypedef uint32_t word_id_type;\ntypedef uint32_t doc_id_type;\ntypedef uint16_t topic_id_type;\ntypedef uint32_t count_type;\n#define NULL_TOPIC topic_id_type(-1)\n\nstruct token_type {\n  word_id_type word;\n  doc_id_type doc;\n  token_type(const word_id_type& word = 0, const doc_id_type& doc = 0) : \n    word(word), doc(doc) { }\n};\nstd::ostream& operator<<(std::ostream& out, const token_type& tok) {\n  return out << \"(\" << tok.word << \", \" << tok.doc << \")\";\n}\n\n\nstruct corpus_type {\n  size_t nwords, ndocs, ntokens;\n  std::vector< token_type > tokens;\n  std::vector<std::string> dictionary;\n  std::vector< word_id_type > ntokens_in_doc;\n  \n  corpus_type(const std::string& dictionary_fname, \n              const std::string& counts_fname ) : \n    nwords(0), ndocs(0), ntokens(0) {\n    dictionary.reserve(20000);\n    ntokens_in_doc.reserve(5000);\n    tokens.reserve(100000);\n    load_dictionary(dictionary_fname);\n    load_counts(counts_fname);\n  }\n  void load_dictionary(const std::string& fname) {\n    std::ifstream fin(fname.c_str());\n    std::string str;\n    while(fin.good()) {\n      std::getline(fin, str);\n      if(fin.good()) { dictionary.push_back(str); nwords++; }\n    }\n    fin.close();\n  }\n\n  void load_counts(const std::string& fname)  {\n    std::ifstream fin(fname.c_str());    \n    while(fin.good()) {\n      // Read a collection of tokens\n      const size_t NULL_VALUE(-1);\n      size_t word = NULL_VALUE, doc = NULL_VALUE, count = NULL_VALUE;\n      fin >> doc >> word >> count;\n      if(fin.good()) {\n        assert(word != NULL_VALUE && doc != NULL_VALUE && count != NULL_VALUE);\n        // update the doc counter\n        ndocs = std::max(ndocs, doc + 1);\n        // Assert valid word\n        assert(word < nwords);\n        // Update the words in document counter\n        if(doc >= ntokens_in_doc.size())\n          ntokens_in_doc.resize(doc+1, 0);\n        ntokens_in_doc[doc] += count;\n        // Add all the tokens\n        token_type tok; tok.word = word; tok.doc = doc;\n        for(size_t i = 0; i < count; ++i) tokens.push_back(tok);\n      }\n    }\n    fin.close();\n    ntokens = tokens.size();\n  } // end of load counts\n\n  void shuffle_tokens() { graphlab::random::shuffle(tokens); }\n}; // end of corpus\n\n\n\ntemplate<typename T>\nclass matrix {\nprivate:\n  size_t _rows, _cols;\n  std::vector<T> data;\n\n  const size_t linear_index(const size_t& i, const size_t& j) const {\n    assert(i < _rows && j < _cols);\n    return i + j * _rows;\n  }\n\npublic:\n  matrix(const size_t& rows, const size_t& cols, const T& zero = T(0)) :\n    _rows(rows), _cols(cols), data(rows*cols, zero) { };\n  const T& operator()(const size_t& i, const size_t& j) const {\n    return data[linear_index(i,j)];\n  }\n  size_t rows() const { return _rows; }\n  size_t cols() const { return _cols; }\n  T& operator()(const size_t& i, const size_t& j) {\n    return data[linear_index(i,j)];\n  }\n  const T& operator()(const size_t& i) const {\n    assert(i < data.size());\n    return data[i];\n  }\n  T& operator()(const size_t& i) {\n    assert(i < data.size());\n    return data[i];\n  }\n  void zeros() {\n    std::fill(data.begin(), data.end(), T(0));\n  }\n  void operator+=(const matrix& other) {\n    assert(_rows == other._rows);\n    assert(_cols == other._cols);\n    for(size_t i = 0; i < data.size(); ++i) data[i] += other.data[i];\n  }\n  T sum() const {\n    T z(0);\n    for(size_t i = 0; i < data.size(); ++i) z += data[i];\n    return z;\n  }\n}; // end of matrix \ntypedef matrix<count_type> mat_type;\n\n\nclass collapsed_gibbs {\npublic:\n  const corpus_type* corpus_ptr;\n  const size_t ntopics;\n  const double alpha, beta;\n \n  std::vector< topic_id_type > topics;\n  //! n_td(t,d) Number of occurences of topic t in document d\n  mat_type n_td;\n  //! n_wt(w,t) Number of occurences of word w in topic t\n  mat_type n_wt;\n  //! n_t(t) The total number of words assigned to topic t\n  mat_type n_t;\n  //! number of times a token was assigned to a new topic\n  size_t nchanges;\n\n  collapsed_gibbs(const corpus_type& corpus, \n                  const size_t& ntopics,\n                  const double& alpha,\n                  const double& beta) : \n    corpus_ptr(&corpus), ntopics(ntopics), alpha(alpha),\n    beta(beta), topics(corpus.ntokens, NULL_TOPIC),\n    n_td(ntopics, corpus.ndocs, 0),\n    n_wt(corpus.nwords, ntopics, 0),\n    n_t(ntopics, 1, 0),\n    nchanges(0) { }\n  \n  \n  void iterate() {\n    assert(corpus_ptr != NULL);\n    const corpus_type& corpus = *corpus_ptr;\n    // Reset the number of changes\n    nchanges = 0;\n    std::vector<double> conditional(ntopics);\n\n    // Loop over all the tokens\n    for(size_t i = 0; i < corpus.ntokens; ++i) {\n      // Get the word and document for the ith token\n      const word_id_type w = corpus.tokens[i].word;\n      const doc_id_type d = corpus.tokens[i].doc;\n      const topic_id_type old_topic = topics[i];\n\n      // Remove the word from the current counters\n      if(old_topic != NULL_TOPIC) {\n        --n_td(old_topic, d); --n_wt(w, old_topic), --n_t(old_topic);\n      }\n\n      // Construct the conditional\n      double normalizer = 0;\n      for(size_t t = 0; t < ntopics; ++t) {\n        conditional[t] = (alpha + n_td(t,d)) * (beta + n_wt(w,t)) /\n          (beta * corpus.nwords + n_t(t)); \n        normalizer += conditional[t];\n      }\n      assert(normalizer > 0);\n\n      // Draw a new value\n      topic_id_type new_topic = 0;\n      // normalize and then sample\n      for(size_t t = 0; t < ntopics; ++t) conditional[t] /= normalizer;\n      new_topic = graphlab::random::multinomial(conditional);\n\n      // Update the topic assignment and counters\n      topics[i] = new_topic;\n      if(new_topic != old_topic) nchanges++;\n      ++n_td(new_topic, d); ++n_wt(w, new_topic), ++n_t(new_topic);\n    } // end of loop over tokens\n\n    const size_t n_td_sum = n_td.sum();\n    const size_t n_wt_sum = n_wt.sum();\n    const size_t n_t_sum = n_t.sum();\n    assert(n_td_sum == corpus.ntokens);\n    assert(n_wt_sum == corpus.ntokens);\n    assert(n_t_sum == corpus.ntokens);\n  }\n};\n\n\ndouble log_likelihood(const double& alpha, const double& beta,\n                      const mat_type& n_td, const mat_type& n_wt) {\n  using boost::math::lgamma;\n  const size_t ndocs  = n_td.cols();\n  const size_t ntopics = n_td.rows();\n  const size_t nwords = n_wt.rows();\n\n  mat_type n_t(ntopics,1, 0);\n  for(size_t t = 0; t < n_wt.cols(); ++t) \n    for(size_t w = 0; w < n_wt.rows(); ++w) n_t(t) += n_wt(w,t);\n      \n  \n  // Matlab Functions:\n  //\n  //  llik_w_given_z = ...\n  //    ntopics * (gammaln(nwords * beta) - nwords * gammaln(beta)) + ...\n  //    sum((sum(gammaln(n_wt + beta)) - gammaln( sum(n_wt) + nwords*beta)));\n  //\n  //  llik_z = ...\n  //    ndocs * (gammaln(ntopics * alpha) - ntopics * gammaln(alpha)) + ...\n  //    sum(sum(gammaln(n_td + alpha)) - gammaln(sum(n_td) + ntopics * alpha));\n\n  double llik_words_given_topics = \n    ntopics * (lgamma(nwords * beta) - nwords * lgamma(beta));\n  for(size_t t = 0; t < ntopics; ++t) {\n    for(size_t w = 0; w < nwords; ++w) {\n      llik_words_given_topics += lgamma(n_wt(w,t) + beta);\n    }\n    llik_words_given_topics -= lgamma(n_t(t) + nwords * beta);\n  }\n  double llik_topics = ndocs * (lgamma(ntopics * alpha) - ntopics * lgamma(alpha));\n  for(size_t d = 0; d < ndocs; ++d) {\n    size_t ntokens_in_doc = 0;\n    for(size_t t = 0; t < ntopics; ++t) {\n      llik_topics += lgamma(n_td(t,d) + alpha);\n      ntokens_in_doc += n_td(t,d); \n    }\n    llik_topics -= lgamma(ntokens_in_doc + ntopics * alpha);\n  }\n  return llik_words_given_topics + llik_topics;\n} // end of log_likelihood\n\n\nvoid display_top(const corpus_type& corpus,\n                 const mat_type& n_wt,\n                 const size_t& ntop) {\n  assert(ntop > 0);\n  const size_t nwords = n_wt.rows();\n  const size_t ntopics = n_wt.cols();\n  typedef std::pair<size_t, word_id_type> cw_pair_type;\n  for(size_t t = 0; t < ntopics; ++t) {\n    std::set< cw_pair_type > top_words;\n    for(size_t w = 0; w < nwords; ++w) {\n      if(top_words.size() < ntop || n_wt(w,t) > top_words.begin()->first) {\n        top_words.insert(std::make_pair(n_wt(w,t), w));\n        if(top_words.size() > ntop) top_words.erase(top_words.begin());\n      }\n    }\n    std::cout << std::endl;\n    rev_foreach(const cw_pair_type& pair, top_words) {\n      std::cout << corpus.dictionary.at(pair.second) << \", \";\n    }\n    std::cout << std::endl;\n  }\n} // end of display top\n\n\n\n\n\n\n\n\nint main(int argc, char** argv) {\n\n  std::string dictionary_fname(\"dictionary.txt\");\n  std::string counts_fname(\"counts.tsv\");\n  size_t ntopics(50);\n  size_t nburnin(50);\n  size_t nsamples(10);\n  double alpha(50.0/double(ntopics));\n  double beta(0.1);\n  size_t topk(20);\n  std::string llik_fname(\"llik.txt\");\n  std::string doctop_fname(\"doctop.txt\");\n  std::string wordtop_fname(\"wordtop.txt\");\n\n\n  // Parse command line options\n  namespace po = boost::program_options;\n  po::options_description desc(\"LDA sampler code\");\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"dictionary\", po::value<std::string>(&dictionary_fname)->\n     default_value(dictionary_fname), \"Dictionary file\")\n    (\"counts\", po::value<std::string>(&counts_fname)->\n     default_value(counts_fname), \"Counts file\")\n    (\"ntopics\", po::value<size_t>(&ntopics)->\n     default_value(ntopics), \"Number of topics\")\n    (\"nburnin\", po::value<size_t>(&nburnin)->\n     default_value(nburnin), \"Number of iterations\")\n    (\"nsamples\", po::value<size_t>(&nsamples)->\n     default_value(nsamples), \"Number of iterations\")\n    (\"alpha\", po::value<double>(&alpha)->\n     default_value(alpha), \"Alpha prior\")\n    (\"beta\", po::value<double>(&beta)->\n     default_value(beta), \"Beta prior\")\n    (\"doctop_fname\", po::value<std::string>(&doctop_fname)->\n     default_value(doctop_fname), \"doctop_fname\")\n    (\"wordtop_fname\", po::value<std::string>(&wordtop_fname)->\n     default_value(wordtop_fname), \"wordtop_fname\")\n    (\"topk\", po::value<size_t>(&topk)->\n     default_value(topk), \"number of top k to show\");\n  \n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);    \n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    return EXIT_FAILURE;\n  }\n\n  if (dictionary_fname.length() == 0 || counts_fname.length() == 0) {\n    std::cout << \"Both counts and dictionary must be specified\" << std::endl;\n    std::cout << desc << \"\\n\";\n    return EXIT_FAILURE; \n  }\n  \n  std::cout << \"Loading the corpus.\" << std::endl;\n  corpus_type corpus(dictionary_fname, counts_fname);\n\n  std::cout << \"Number of words:   \" << corpus.nwords << std::endl\n            << \"Number of docs:    \" << corpus.ndocs << std::endl\n            << \"Number of tokens:  \" << corpus.ntokens << std::endl\n            << \"Ntopics:           \" << ntopics << std::endl\n            << \"Alpha:             \" << alpha   << std::endl\n            << \"Beta:              \" << beta    << std::endl;\n\n  std::cout << \"Seeding Generator: \" << std::endl;\n  graphlab::random::nondet_seed();\n  std::cout << \"Shuffling corpus: \" << std::endl;\n  corpus.shuffle_tokens();\n\n\n  std::cout << \"Constructing Gibbs Sampler: \" << std::endl;\n  collapsed_gibbs gibbs(corpus, ntopics, alpha, beta);\n  \n  \n  std::ofstream llik_fout(llik_fname.c_str());\n  llik_fout.precision(16);\n\n  std::cout << \"Starting Burnin\" << std::endl;\n  for(size_t i = 0; i < nburnin; ++i) {\n    std::cout << \"Burnin iteration: \" << i << std::endl;\n    gibbs.iterate();\n    std::cout << \"Computing top \" << topk << \" of each topic\" << std::endl;\n    display_top(corpus, gibbs.n_wt, topk);\n    std::cout << \"Number of changes: \" << gibbs.nchanges << std::endl\n              << \"Prop. Changes:     \" \n              << double(gibbs.nchanges)/ corpus.ntokens << std::endl;\n    double llik = log_likelihood(gibbs.alpha, gibbs.beta, gibbs.n_td, gibbs.n_wt);\n    std::cout << \"Log-likelihood:    \" // std::setprecision(8) <<\n              <<  llik << std::endl;\n    llik_fout << llik << '\\t' << gibbs.nchanges << std::endl;\n\n  }\n  std::cout << \"Finished burnin.  Preparing final sample set.\" << std::endl;\n \n  mat_type n_td(ntopics, corpus.ndocs, 0);\n  mat_type n_wt(corpus.nwords, ntopics, 0);\n  mat_type n_t(ntopics, 1, 0);\n\n  for(size_t i = 0; i < nsamples; ++i) {\n    std::cout << \"Sampling iteration: \" << i << std::endl;\n    gibbs.iterate();\n    std::cout << \"Number of changes: \" << gibbs.nchanges << std::endl\n              << \"Prop. Changes:     \" \n              << double(gibbs.nchanges)/ corpus.ntokens << std::endl;\n    std::cout << \"Accumulating sample\" << std::endl;\n    n_td += gibbs.n_td;\n    n_wt += gibbs.n_wt;\n    n_t  += gibbs.n_t;\n\n    std::cout << \"Computing top \" << topk << \" of each topic\" << std::endl;\n    display_top(corpus, n_wt, topk);    \n    std::cout << \"Number of changes: \" << gibbs.nchanges << std::endl\n              << \"Prop. Changes:     \" \n              << double(gibbs.nchanges)/ corpus.ntokens << std::endl;\n    double llik = log_likelihood(gibbs.alpha, gibbs.beta, gibbs.n_td, gibbs.n_wt);\n    std::cout << \"Log-likelihood:    \" // std::setprecision(8) <<\n              <<  llik << std::endl;\n    llik_fout << llik << '\\t' << gibbs.nchanges << std::endl;\n\n  }\n  llik_fout.close();\n\n  std::cout << \"Saving doctop: \" << doctop_fname << std::endl;\n  std::ofstream doctop_fout(doctop_fname.c_str());\n  for(size_t d = 0; d < corpus.ndocs; ++d) {\n    double normalizer = ntopics * alpha; \n    for(size_t t = 0; t < ntopics; ++t) \n      normalizer += double(n_td(t,d)) / double(nsamples);\n    for(size_t t = 0; t < ntopics; ++t) {\n      const double value = \n        (double(n_td(t,d))/double(nsamples) + alpha) / normalizer;\n      doctop_fout << value << ((t+1 < ntopics)? '\\t' : '\\n');\n    }\n  }\n  doctop_fout.close();\n  \n  std::cout << \"Saving wordtop: \" << wordtop_fname << std::endl;\n\n\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4ba081df8c81ddf1de03a551bf676b68fc4987d7", "size": 14692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/topic_modeling/lda_sequential_cgs.cpp", "max_stars_repo_name": "RealM10/package", "max_stars_repo_head_hexsha": "3bcec9b677226ee0395e82e908f542aba0ecaad7", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 333.0, "max_stars_repo_stars_event_min_datetime": "2016-07-29T19:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:40:34.000Z", "max_issues_repo_path": "toolkits/topic_modeling/lda_sequential_cgs.cpp", "max_issues_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_issues_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2016-09-15T00:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T07:51:07.000Z", "max_forks_repo_path": "toolkits/topic_modeling/lda_sequential_cgs.cpp", "max_forks_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_forks_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 163.0, "max_forks_repo_forks_event_min_datetime": "2016-07-29T19:22:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:15:24.000Z", "avg_line_length": 32.3612334802, "max_line_length": 83, "alphanum_fraction": 0.6116253744, "num_tokens": 4253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.038466194222894164, "lm_q1q2_score": 0.018182333846154305}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_UNITS_CODATA_HELION_CONSTANTS_HPP\r\n#define BOOST_UNITS_CODATA_HELION_CONSTANTS_HPP\r\n\r\n#include <boost/units/quantity.hpp>\r\n#include <boost/units/static_constant.hpp>\r\n\r\n#include <boost/units/systems/detail/constants.hpp>\r\n#include <boost/units/systems/si/amount.hpp>\r\n#include <boost/units/systems/si/area.hpp>\r\n#include <boost/units/systems/si/electric_charge.hpp>\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/frequency.hpp>\r\n#include <boost/units/systems/si/length.hpp>\r\n#include <boost/units/systems/si/mass.hpp>\r\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\r\n#include <boost/units/systems/si/time.hpp>\r\n#include <boost/units/systems/si/wavenumber.hpp>\r\n\r\n#include <boost/units/systems/si/codata/typedefs.hpp>\r\n\r\n/// \\file\r\n/// CODATA recommended values of fundamental atomic and nuclear constants\r\n/// CODATA 2006 values as of 2007/03/30\r\n\r\nnamespace boost {\r\n\r\nnamespace units { \r\n\r\nnamespace si {\r\n                            \r\nnamespace constants {\r\n\r\nnamespace codata {\r\n\r\n/// CODATA recommended values of the fundamental physical constants: NIST SP 961\r\n\r\n/// helion mass\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_h,quantity<mass>,5.00641192e-27*kilograms,2.5e-34*kilograms);\r\n/// helion-electron mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_h_over_m_e,quantity<dimensionless>,5495.8852765*dimensionless(),5.2e-6*dimensionless());\r\n/// helion-proton mass ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(m_h_over_m_p,quantity<dimensionless>,2.9931526713*dimensionless(),2.6e-9*dimensionless());\r\n/// helion molar mass\r\nBOOST_UNITS_PHYSICAL_CONSTANT(M_h,quantity<mass_over_amount>,3.0149322473e-3*kilograms/mole,2.6e-12*kilograms/mole);\r\n/// helion shielded magnetic moment\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_h_prime,quantity<energy_over_magnetic_flux_density>,-1.074552982e-26*joules/tesla,3.0e-34*joules/tesla);\r\n/// shielded helion-Bohr magneton ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_h_prime_over_mu_B,quantity<dimensionless>,-1.158671471e-3*dimensionless(),1.4e-11*dimensionless());\r\n/// shielded helion-nuclear magneton ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_h_prime_over_mu_N,quantity<dimensionless>,-2.127497718*dimensionless(),2.5e-8*dimensionless());\r\n/// shielded helion-proton magnetic moment ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_h_prime_over_mu_p,quantity<dimensionless>,-0.761766558*dimensionless(),1.1e-8*dimensionless());\r\n/// shielded helion-shielded proton magnetic moment ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_h_prime_over_mu_p_prime,quantity<dimensionless>,-0.7617861313*dimensionless(),3.3e-8*dimensionless());\r\n/// shielded helion gyromagnetic ratio\r\nBOOST_UNITS_PHYSICAL_CONSTANT(gamma_h_prime,quantity<frequency_over_magnetic_flux_density>,2.037894730e8/second/tesla,5.6e-0/second/tesla);\r\n\r\n} // namespace codata\r\n\r\n} // namespace constants    \r\n\r\n} // namespace si\r\n\r\n} // namespace units\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_UNITS_CODATA_HELION_CONSTANTS_HPP\r\n", "meta": {"hexsha": "0e06938cec972a4751e1b26b093d17b3e1b029d7", "size": 3334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/helion_constants.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/helion_constants.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/helion_constants.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 42.2025316456, "max_line_length": 140, "alphanum_fraction": 0.7792441512, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.04813677316493159, "lm_q1q2_score": 0.01817358886020606}}
{"text": "\n\n/*\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/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <stdexcept>\n#include <votca/tools/constants.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/basisset.h\"\n#include \"votca/xtp/bse.h\"\n#include \"votca/xtp/ecpbasisset.h\"\n#include \"votca/xtp/gwbse.h\"\n#include \"votca/xtp/logger.h\"\n#include \"votca/xtp/openmp_cuda.h\"\n#include \"votca/xtp/orbitals.h\"\n#include \"votca/xtp/vxc_grid.h\"\n#include \"votca/xtp/vxc_potential.h\"\n\nusing boost::format;\nusing namespace boost::filesystem;\nusing std::flush;\nnamespace votca {\nnamespace xtp {\n\nIndex GWBSE::CountCoreLevels() {\n  Index ignored_corelevels = 0;\n  if (!orbitals_.hasECPName()) {\n    ECPBasisSet basis;\n    basis.Load(\"corelevels\");\n    Index coreElectrons = 0;\n    for (const auto& atom : orbitals_.QMAtoms()) {\n      coreElectrons += basis.getElement(atom.getElement()).getNcore();\n    }\n    ignored_corelevels = coreElectrons / 2;\n  }\n  return ignored_corelevels;\n}\n\nvoid GWBSE::Initialize(tools::Property& options) {\n\n  // getting level ranges\n  Index rpamax = 0;\n  Index rpamin = 0;  // never changes\n  Index qpmin = 0;\n  Index qpmax = 0;\n  Index bse_vmin = 0;\n  Index bse_cmax = 0;\n\n  Index homo = orbitals_.getHomo();  // indexed from 0\n  Index num_of_levels = orbitals_.getBasisSetSize();\n  Index num_of_occlevels = orbitals_.getNumberOfAlphaElectrons();\n\n  std::string ranges = options.get(\".ranges\").as<std::string>();\n\n  // now check validity, and get rpa, qp, and bse level ranges accordingly\n\n  if (ranges == \"factor\") {\n\n    double rpamaxfactor = options.get(\".rpamax\").as<double>();\n    rpamax = Index(rpamaxfactor * double(num_of_levels)) -\n             1;  // total number of levels\n\n    double qpminfactor = options.get(\".qpmin\").as<double>();\n    qpmin =\n        num_of_occlevels - Index(qpminfactor * double(num_of_occlevels)) - 1;\n\n    double qpmaxfactor = options.get(\".qpmax\").as<double>();\n    qpmax =\n        num_of_occlevels + Index(qpmaxfactor * double(num_of_occlevels)) - 1;\n\n    double bseminfactor = options.get(\".bsemin\").as<double>();\n    bse_vmin =\n        num_of_occlevels - Index(bseminfactor * double(num_of_occlevels)) - 1;\n\n    double bsemaxfactor = options.get(\".bsemax\").as<double>();\n    bse_cmax =\n        num_of_occlevels + Index(bsemaxfactor * double(num_of_occlevels)) - 1;\n\n  } else if (ranges == \"explicit\") {\n    // get explicit numbers\n    rpamax = options.get(\".rpamax\").as<Index>();\n    qpmin = options.get(\".qpmin\").as<Index>();\n    qpmax = options.get(\".qpmax\").as<Index>();\n    bse_vmin = options.get(\".bsemin\").as<Index>();\n    bse_cmax = options.get(\".bsemax\").as<Index>();\n  } else if (ranges == \"default\") {\n    rpamax = num_of_levels - 1;\n    qpmin = 0;\n    qpmax = 3 * homo + 1;\n    bse_vmin = 0;\n    bse_cmax = 3 * homo + 1;\n  } else if (ranges == \"full\") {\n    rpamax = num_of_levels - 1;\n    qpmin = 0;\n    qpmax = num_of_levels - 1;\n    bse_vmin = 0;\n    bse_cmax = num_of_levels - 1;\n  }\n  std::string ignore_corelevels =\n      options.get(\".ignore_corelevels\").as<std::string>();\n\n  if (ignore_corelevels == \"RPA\" || ignore_corelevels == \"GW\" ||\n      ignore_corelevels == \"BSE\") {\n    Index ignored_corelevels = CountCoreLevels();\n    if (ignore_corelevels == \"RPA\") {\n      rpamin = ignored_corelevels;\n    }\n    if (ignore_corelevels == \"GW\" || ignore_corelevels == \"RPA\") {\n      if (qpmin < ignored_corelevels) {\n        qpmin = ignored_corelevels;\n      }\n    }\n    if (ignore_corelevels == \"GW\" || ignore_corelevels == \"RPA\" ||\n        ignore_corelevels == \"BSE\") {\n      if (bse_vmin < ignored_corelevels) {\n        bse_vmin = ignored_corelevels;\n      }\n    }\n\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Ignoring \" << ignored_corelevels\n        << \" core levels for \" << ignore_corelevels << \" and beyond.\" << flush;\n  }\n\n  // check maximum and minimum sizes\n  if (rpamax > num_of_levels) {\n    rpamax = num_of_levels - 1;\n  }\n  if (qpmax > num_of_levels) {\n    qpmax = num_of_levels - 1;\n  }\n  if (bse_cmax > num_of_levels) {\n    bse_cmax = num_of_levels - 1;\n  }\n  if (bse_vmin < 0) {\n    bse_vmin = 0;\n  }\n  if (qpmin < 0) {\n    qpmin = 0;\n  }\n\n  gwopt_.homo = homo;\n  gwopt_.qpmin = qpmin;\n  gwopt_.qpmax = qpmax;\n  gwopt_.rpamin = rpamin;\n  gwopt_.rpamax = rpamax;\n\n  bseopt_.vmin = bse_vmin;\n  bseopt_.cmax = bse_cmax;\n  bseopt_.homo = homo;\n  bseopt_.qpmin = qpmin;\n  bseopt_.qpmax = qpmax;\n  bseopt_.rpamin = rpamin;\n  bseopt_.rpamax = rpamax;\n\n  orbitals_.setRPAindices(rpamin, rpamax);\n  orbitals_.setGWindices(qpmin, qpmax);\n  orbitals_.setBSEindices(bse_vmin, bse_cmax);\n  orbitals_.SetFlagUseHqpOffdiag(bseopt_.use_Hqp_offdiag);\n\n  Index bse_vmax = homo;\n  Index bse_cmin = homo + 1;\n  Index bse_vtotal = bse_vmax - bse_vmin + 1;\n  Index bse_ctotal = bse_cmax - bse_cmin + 1;\n  Index bse_size = bse_vtotal * bse_ctotal;\n\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" RPA level range [\" << rpamin\n                              << \":\" << rpamax << \"]\" << flush;\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" GW  level range [\" << qpmin\n                              << \":\" << qpmax << \"]\" << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" BSE level range occ[\" << bse_vmin << \":\" << bse_vmax\n      << \"]  virt[\" << bse_cmin << \":\" << bse_cmax << \"]\" << flush;\n\n  gwopt_.reset_3c = options.get(\".gw.rebuild_3c_freq\").as<Index>();\n\n  bseopt_.nmax = options.get(\".bse.exctotal\").as<Index>();\n  if (bseopt_.nmax > bse_size || bseopt_.nmax < 0) {\n    bseopt_.nmax = bse_size;\n  }\n\n  bseopt_.davidson_correction =\n      options.get(\"bse.davidson.correction\").as<std::string>();\n\n  bseopt_.davidson_tolerance =\n      options.get(\"bse.davidson.tolerance\").as<std::string>();\n\n  bseopt_.davidson_update =\n      options.get(\"bse.davidson.update\").as<std::string>();\n\n  bseopt_.davidson_maxiter = options.get(\"bse.davidson.maxiter\").as<Index>();\n\n  bseopt_.useTDA = options.get(\"bse.useTDA\").as<bool>();\n  orbitals_.setTDAApprox(bseopt_.useTDA);\n  if (!bseopt_.useTDA) {\n    XTP_LOG(Log::error, *pLog_) << \" BSE type: full\" << flush;\n  } else {\n    XTP_LOG(Log::error, *pLog_) << \" BSE type: TDA\" << flush;\n  }\n\n  Index full_bse_size = (bseopt_.useTDA) ? bse_size : 2 * bse_size;\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" BSE Hamiltonian has size \"\n                              << full_bse_size << \"x\" << full_bse_size << flush;\n\n  bseopt_.use_Hqp_offdiag = options.get(\"bse.use_Hqp_offdiag\").as<bool>();\n\n  if (!bseopt_.use_Hqp_offdiag) {\n    XTP_LOG(Log::error, *pLog_)\n        << \" BSE without Hqp offdiagonal elements\" << flush;\n  } else {\n    XTP_LOG(Log::error, *pLog_)\n        << \" BSE with Hqp offdiagonal elements\" << flush;\n  }\n\n  bseopt_.max_dyn_iter = options.get(\"bse.dyn_screen_max_iter\").as<Index>();\n  bseopt_.dyn_tolerance = options.get(\"bse.dyn_screen_tol\").as<double>();\n  if (bseopt_.max_dyn_iter > 0) {\n    do_dynamical_screening_bse_ = true;\n  }\n\n  functional_ = orbitals_.getXCFunctionalName();\n  grid_ = orbitals_.getXCGrid();\n\n  dftbasis_name_ = orbitals_.getDFTbasisName();\n  if (orbitals_.hasAuxbasisName()) {\n    auxbasis_name_ = orbitals_.getAuxbasisName();\n  } else if (options.exists(\".auxbasisset\")) {\n    auxbasis_name_ = options.get(\".auxbasisset\").as<std::string>();\n  } else {\n    auxbasis_name_ = \"aux-\" + dftbasis_name_;\n    try {\n      BasisSet b;\n      b.Load(auxbasis_name_);\n    } catch (std::runtime_error&) {\n      std::runtime_error(\n          \"There is no auxbasis from the dftcalculation nor did you specify an \"\n          \"auxbasisset for the gwbse calculation. Also no auxiliary basisset \"\n          \"for basisset \" +\n          dftbasis_name_ + \" could be found!\");\n    }\n    XTP_LOG(Log::error, *pLog_)\n        << \" Could not find an auxbasisset using \" << auxbasis_name_ << flush;\n  }\n\n  std::string mode = options.get(\"gw.mode\").as<std::string>();\n  if (mode == \"G0W0\") {\n    gwopt_.gw_sc_max_iterations = 1;\n  } else if (mode == \"evGW\") {\n    gwopt_.g_sc_limit = 0.1 * gwopt_.gw_sc_limit;\n    gwopt_.eta = 0.1;\n  }\n\n  XTP_LOG(Log::error, *pLog_) << \" Running GW as: \" << mode << flush;\n  gwopt_.ScaHFX = orbitals_.getScaHFX();\n\n  gwopt_.shift = options.get(\"gw.scissor_shift\").as<double>();\n  gwopt_.g_sc_limit =\n      options.get(\"gw.qp_sc_limit\").as<double>();  // convergence criteria\n                                                   // for qp iteration\n                                                   // [Hartree]]\n  gwopt_.g_sc_max_iterations =\n      options.get(\"gw.qp_sc_max_iter\").as<Index>();  // convergence\n                                                     // criteria for qp\n                                                     // iteration\n                                                     // [Hartree]]\n\n  if (mode == \"evGW\") {\n    gwopt_.gw_sc_max_iterations = options.get(\"gw.sc_max_iter\").as<Index>();\n  }\n\n  gwopt_.gw_sc_limit =\n      options.get(\"gw.sc_limit\").as<double>();  // convergence criteria\n                                                // for shift it\n  XTP_LOG(Log::error, *pLog_)\n      << \" qp_sc_limit [Hartree]: \" << gwopt_.g_sc_limit << flush;\n  if (gwopt_.gw_sc_max_iterations > 1) {\n    XTP_LOG(Log::error, *pLog_)\n        << \" gw_sc_limit [Hartree]: \" << gwopt_.gw_sc_limit << flush;\n  }\n  bseopt_.min_print_weight = options.get(\"bse.print_weight\").as<double>();\n  // print exciton WF composition weight larger than minimum\n\n  // possible tasks\n  std::string tasks_string = options.get(\".tasks\").as<std::string>();\n  boost::algorithm::to_lower(tasks_string);\n  if (tasks_string.find(\"all\") != std::string::npos) {\n    do_gw_ = true;\n    do_bse_singlets_ = true;\n    do_bse_triplets_ = true;\n  }\n  if (tasks_string.find(\"gw\") != std::string::npos) {\n    do_gw_ = true;\n  }\n  if (tasks_string.find(\"singlets\") != std::string::npos) {\n    do_bse_singlets_ = true;\n  }\n  if (tasks_string.find(\"triplets\") != std::string::npos) {\n    do_bse_triplets_ = true;\n  }\n\n  XTP_LOG(Log::error, *pLog_) << \" Tasks: \" << flush;\n  if (do_gw_) {\n    XTP_LOG(Log::error, *pLog_) << \" GW \" << flush;\n  }\n  if (do_bse_singlets_) {\n    XTP_LOG(Log::error, *pLog_) << \" singlets \" << flush;\n  }\n  if (do_bse_triplets_) {\n    XTP_LOG(Log::error, *pLog_) << \" triplets \" << flush;\n  }\n  XTP_LOG(Log::error, *pLog_) << \" Store: \" << flush;\n  if (do_gw_) {\n    XTP_LOG(Log::error, *pLog_) << \" GW \" << flush;\n  }\n\n  if (options.exists(\"bse.fragments\")) {\n    std::vector<tools::Property*> prop_region =\n        options.Select(\"bse.fragments.fragment\");\n    Index index = 0;\n    for (tools::Property* prop : prop_region) {\n      std::string indices = prop->get(\"indices\").as<std::string>();\n      fragments_.push_back(QMFragment<BSE_Population>(index, indices));\n      index++;\n    }\n  }\n\n  gwopt_.sigma_integration =\n      options.get(\"gw.sigma_integrator\").as<std::string>();\n  XTP_LOG(Log::error, *pLog_)\n      << \" Sigma integration: \" << gwopt_.sigma_integration << flush;\n  gwopt_.eta = options.get(\"gw.eta\").as<double>();\n  XTP_LOG(Log::error, *pLog_) << \" eta: \" << gwopt_.eta << flush;\n  if (gwopt_.sigma_integration == \"exact\") {\n    XTP_LOG(Log::error, *pLog_)\n        << \" RPA Hamiltonian size: \" << (homo + 1 - rpamin) * (rpamax - homo)\n        << flush;\n  }\n  if (gwopt_.sigma_integration == \"cda\") {\n    gwopt_.order = options.get(\"gw.quadrature_order\").as<Index>();\n    XTP_LOG(Log::error, *pLog_)\n        << \" Quadrature integration order : \" << gwopt_.order << flush;\n    gwopt_.quadrature_scheme =\n        options.get(\".quadrature_scheme\").as<std::string>();\n    XTP_LOG(Log::error, *pLog_)\n        << \" Quadrature integration scheme : \" << gwopt_.quadrature_scheme\n        << flush;\n    gwopt_.alpha = options.get(\"gw.alpha\").as<double>();\n    XTP_LOG(Log::error, *pLog_)\n        << \" Alpha smoothing parameter : \" << gwopt_.alpha << flush;\n  }\n  gwopt_.qp_solver = options.get(\"gw.qp_solver\").as<std::string>();\n\n  XTP_LOG(Log::error, *pLog_) << \" QP solver: \" << gwopt_.qp_solver << flush;\n  if (gwopt_.qp_solver == \"grid\") {\n    gwopt_.qp_grid_steps = options.get(\"gw.qp_grid_steps\").as<Index>();\n    gwopt_.qp_grid_spacing = options.get(\"gw.qp_grid_spacing\").as<double>();\n    XTP_LOG(Log::error, *pLog_)\n        << \" QP grid steps: \" << gwopt_.qp_grid_steps << flush;\n    XTP_LOG(Log::error, *pLog_)\n        << \" QP grid spacing: \" << gwopt_.qp_grid_spacing << flush;\n  }\n  gwopt_.gw_mixing_order =\n      options.get(\"gw.mixing_order\").as<Index>();  // max history in\n                                                   // mixing (0: plain,\n                                                   // 1: linear, >1\n                                                   // Anderson)\n\n  gwopt_.gw_mixing_alpha = options.get(\"gw.mixing_alpha\").as<double>();\n\n  if (mode == \"evGW\") {\n    if (gwopt_.gw_mixing_order == 0) {\n      XTP_LOG(Log::error, *pLog_) << \" evGW with plain update \" << std::flush;\n    } else if (gwopt_.gw_mixing_order == 1) {\n      XTP_LOG(Log::error, *pLog_) << \" evGW with linear update using alpha \"\n                                  << gwopt_.gw_mixing_alpha << std::flush;\n    } else {\n      XTP_LOG(Log::error, *pLog_) << \" evGW with Anderson update with history \"\n                                  << gwopt_.gw_mixing_order << \" using alpha \"\n                                  << gwopt_.gw_mixing_alpha << std::flush;\n    }\n  }\n\n  if (options.exists(\".sigma_plot\")) {\n    sigma_plot_states_ = options.get(\".sigma_plot.states\").as<std::string>();\n    sigma_plot_steps_ = options.get(\".sigma_plot.steps\").as<Index>();\n    sigma_plot_spacing_ = options.get(\".sigma_plot.spacing\").as<double>();\n    sigma_plot_filename_ =\n        options.get(\".sigma_plot.filename\").as<std::string>();\n\n    XTP_LOG(Log::error, *pLog_)\n        << \" Sigma plot states: \" << sigma_plot_states_ << flush;\n    XTP_LOG(Log::error, *pLog_)\n        << \" Sigma plot steps: \" << sigma_plot_steps_ << flush;\n    XTP_LOG(Log::error, *pLog_)\n        << \" Sigma plot spacing: \" << sigma_plot_spacing_ << flush;\n    XTP_LOG(Log::error, *pLog_)\n        << \" Sigma plot filename: \" << sigma_plot_filename_ << flush;\n  }\n}\n\nvoid GWBSE::addoutput(tools::Property& summary) {\n\n  const double hrt2ev = tools::conv::hrt2ev;\n  tools::Property& gwbse_summary = summary.add(\"GWBSE\", \"\");\n  if (do_gw_) {\n    gwbse_summary.setAttribute(\"units\", \"eV\");\n    gwbse_summary.setAttribute(\n        \"DFTEnergy\",\n        (format(\"%1$+1.6f \") % (orbitals_.getDFTTotalEnergy() * hrt2ev)).str());\n\n    tools::Property& dft_summary = gwbse_summary.add(\"dft\", \"\");\n    dft_summary.setAttribute(\"HOMO\", gwopt_.homo);\n    dft_summary.setAttribute(\"LUMO\", gwopt_.homo + 1);\n\n    for (Index state = 0; state < gwopt_.qpmax + 1 - gwopt_.qpmin; state++) {\n      tools::Property& level_summary = dft_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + gwopt_.qpmin);\n      level_summary.add(\n          \"dft_energy\",\n          (format(\"%1$+1.6f \") %\n           (orbitals_.MOs().eigenvalues()(state + gwopt_.qpmin) * hrt2ev))\n              .str());\n      level_summary.add(\n          \"gw_energy\",\n          (format(\"%1$+1.6f \") % (orbitals_.QPpertEnergies()(state) * hrt2ev))\n              .str());\n\n      level_summary.add(\"qp_energy\",\n                        (format(\"%1$+1.6f \") %\n                         (orbitals_.QPdiag().eigenvalues()(state) * hrt2ev))\n                            .str());\n    }\n  }\n  if (do_bse_singlets_) {\n    tools::Property& singlet_summary = gwbse_summary.add(\"singlets\", \"\");\n    for (Index state = 0; state < bseopt_.nmax; ++state) {\n      tools::Property& level_summary = singlet_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + 1);\n      level_summary.add(\n          \"omega\", (format(\"%1$+1.6f \") %\n                    (orbitals_.BSESinglets().eigenvalues()(state) * hrt2ev))\n                       .str());\n      if (orbitals_.hasTransitionDipoles()) {\n\n        const Eigen::Vector3d& dipoles = (orbitals_.TransitionDipoles())[state];\n        double f = 2 * dipoles.squaredNorm() *\n                   orbitals_.BSESinglets().eigenvalues()(state) / 3.0;\n\n        level_summary.add(\"f\", (format(\"%1$+1.6f \") % f).str());\n        tools::Property& dipol_summary = level_summary.add(\n            \"Trdipole\", (format(\"%1$+1.4f %2$+1.4f %3$+1.4f\") % dipoles.x() %\n                         dipoles.y() % dipoles.z())\n                            .str());\n        dipol_summary.setAttribute(\"unit\", \"e*bohr\");\n        dipol_summary.setAttribute(\"gauge\", \"length\");\n      }\n    }\n  }\n  if (do_bse_triplets_) {\n    tools::Property& triplet_summary = gwbse_summary.add(\"triplets\", \"\");\n    for (Index state = 0; state < bseopt_.nmax; ++state) {\n      tools::Property& level_summary = triplet_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + 1);\n      level_summary.add(\n          \"omega\", (format(\"%1$+1.6f \") %\n                    (orbitals_.BSETriplets().eigenvalues()(state) * hrt2ev))\n                       .str());\n    }\n  }\n  return;\n}\n\n/*\n *    Many-body Green's fuctions theory implementation\n *\n *  data required from orbitals file\n *  - atomic coordinates\n *  - DFT molecular orbitals (energies and coeffcients)\n *  - DFT exchange-correlation potential matrix in atomic orbitals\n *  - number of electrons, number of levels\n */\n\nEigen::MatrixXd GWBSE::CalculateVXC(const AOBasis& dftbasis) {\n  if (orbitals_.getXCFunctionalName().empty()) {\n    orbitals_.setXCFunctionalName(functional_);\n  } else {\n    if (!(functional_ == orbitals_.getXCFunctionalName())) {\n      throw std::runtime_error(\"Functionals from DFT \" +\n                               orbitals_.getXCFunctionalName() + \" GWBSE \" +\n                               functional_ + \" differ!\");\n    }\n  }\n\n  Vxc_Grid grid;\n  grid.GridSetup(grid_, orbitals_.QMAtoms(), dftbasis);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Setup grid for integration with gridsize: \" << grid_\n      << \" with \" << grid.getGridSize() << \" points, divided into \"\n      << grid.getBoxesSize() << \" boxes\" << flush;\n  Vxc_Potential<Vxc_Grid> vxcpotential(grid);\n  vxcpotential.setXCfunctional(functional_);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Integrating Vxc with functional \" << functional_\n      << flush;\n  Eigen::MatrixXd DMAT = orbitals_.DensityMatrixGroundState();\n  Mat_p_Energy e_vxc_ao = vxcpotential.IntegrateVXC(DMAT);\n  XTP_LOG(Log::info, *pLog_) << TimeStamp() << \" Calculated Vxc\" << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Set hybrid exchange factor: \" << orbitals_.getScaHFX()\n      << flush;\n  Index qptotal = gwopt_.qpmax - gwopt_.qpmin + 1;\n  Eigen::MatrixXd mos =\n      orbitals_.MOs().eigenvectors().middleCols(gwopt_.qpmin, qptotal);\n\n  Eigen::MatrixXd vxc = mos.transpose() * e_vxc_ao.matrix() * mos;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Calculated exchange-correlation expectation values \"\n      << flush;\n\n  return vxc;\n}\n\nbool GWBSE::Evaluate() {\n\n  // set the parallelization\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Using \"\n                              << OPENMP::getMaxThreads() << \" threads\" << flush;\n\n  if (XTP_HAS_MKL_OVERLOAD()) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Using MKL overload for Eigen \" << flush;\n  } else {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp()\n        << \" Using native Eigen implementation, no BLAS overload \" << flush;\n  }\n  Index nogpus = OpenMP_CUDA::UsingGPUs();\n  if (nogpus > 0) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Using CUDA support for tensor multiplication with \"\n        << nogpus << \" GPUs.\" << flush;\n  }\n\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Molecule Coordinates [A] \" << flush;\n  for (QMAtom& atom : orbitals_.QMAtoms()) {\n    std::string output = (boost::format(\"%5d\"\n                                        \"%5s\"\n                                        \"   %1.4f %1.4f %1.4f\") %\n                          atom.getId() % atom.getElement() %\n                          (atom.getPos().x() * tools::conv::bohr2ang) %\n                          (atom.getPos().y() * tools::conv::bohr2ang) %\n                          (atom.getPos().z() * tools::conv::bohr2ang))\n                             .str();\n\n    XTP_LOG(Log::error, *pLog_) << output << flush;\n  }\n\n  std::string dft_package = orbitals_.getQMpackage();\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" DFT data was created by \" << dft_package << flush;\n\n  BasisSet dftbs;\n  dftbs.Load(dftbasis_name_);\n\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Loaded DFT Basis Set \" << dftbasis_name_ << flush;\n\n  // fill DFT AO basis by going through all atoms\n  AOBasis dftbasis;\n  dftbasis.Fill(dftbs, orbitals_.QMAtoms());\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Filled DFT Basis of size \"\n                              << dftbasis.AOBasisSize() << flush;\n\n  // load auxiliary basis set (element-wise information) from xml file\n  BasisSet auxbs;\n  auxbs.Load(auxbasis_name_);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Loaded Auxbasis Set \" << auxbasis_name_ << flush;\n\n  // fill auxiliary AO basis by going through all atoms\n  AOBasis auxbasis;\n  auxbasis.Fill(auxbs, orbitals_.QMAtoms());\n  orbitals_.setAuxbasisName(auxbasis_name_);\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Filled Auxbasis of size \"\n                              << auxbasis.AOBasisSize() << flush;\n\n  if ((do_bse_singlets_ || do_bse_triplets_) && fragments_.size() > 0) {\n    for (const auto& frag : fragments_) {\n      XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Fragment \" << frag.getId()\n                                  << \" size:\" << frag.size() << flush;\n    }\n  }\n\n  if (!do_gw_ && !orbitals_.hasQPdiag()) {\n    throw std::runtime_error(\n        \"You want no GW calculation but the orb file has no QPcoefficients for \"\n        \"BSE\");\n  }\n  TCMatrix_gwbse Mmn;\n  // rpamin here, because RPA needs till rpamin\n  Index max_3c = std::max(bseopt_.cmax, gwopt_.qpmax);\n  Mmn.Initialize(auxbasis.AOBasisSize(), gwopt_.rpamin, max_3c, gwopt_.rpamin,\n                 gwopt_.rpamax);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp()\n      << \" Calculating Mmn_beta (3-center-repulsion x orbitals)  \" << flush;\n  Mmn.Fill(auxbasis, dftbasis, orbitals_.MOs().eigenvectors());\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Removed \" << Mmn.Removedfunctions()\n      << \" functions from Aux Coulomb matrix to avoid near linear dependencies\"\n      << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Calculated Mmn_beta (3-center-repulsion x orbitals)  \"\n      << flush;\n\n  Eigen::MatrixXd Hqp;\n  if (do_gw_) {\n\n    std::chrono::time_point<std::chrono::system_clock> start =\n        std::chrono::system_clock::now();\n    Eigen::MatrixXd vxc = CalculateVXC(dftbasis);\n    GW gw = GW(*pLog_, Mmn, vxc, orbitals_.MOs().eigenvalues());\n    gw.configure(gwopt_);\n    gw.CalculateGWPerturbation();\n\n    if (!sigma_plot_states_.empty()) {\n      gw.PlotSigma(sigma_plot_filename_, sigma_plot_steps_, sigma_plot_spacing_,\n                   sigma_plot_states_);\n    }\n\n    // store perturbative QP energy data in orbitals object (DFT, S_x,S_c, V_xc,\n    // E_qp)\n    orbitals_.QPpertEnergies() = gw.getGWAResults();\n    orbitals_.RPAInputEnergies() = gw.RPAInputEnergies();\n\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << \" Calculating offdiagonal part of Sigma  \" << flush;\n    gw.CalculateHQP();\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Calculated offdiagonal part of Sigma  \" << flush;\n\n    Hqp = gw.getHQP();\n\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =\n        gw.DiagonalizeQPHamiltonian();\n    if (es.info() == Eigen::ComputationInfo::Success) {\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" Diagonalized QP Hamiltonian  \" << flush;\n    }\n\n    orbitals_.QPdiag().eigenvectors() = es.eigenvectors();\n    orbitals_.QPdiag().eigenvalues() = es.eigenvalues();\n    std::chrono::duration<double> elapsed_time =\n        std::chrono::system_clock::now() - start;\n    XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" GW calculation took \"\n                                << elapsed_time.count() << \" seconds.\" << flush;\n\n  } else {\n    if (orbitals_.getGWAmax() != gwopt_.qpmax ||\n        orbitals_.getGWAmin() != gwopt_.qpmin ||\n        orbitals_.getRPAmax() != gwopt_.rpamax ||\n        orbitals_.getRPAmin() != gwopt_.rpamin) {\n      throw std::runtime_error(\n          \"The ranges for GW and RPA do not agree with the ranges from the \"\n          \".orb file, rerun your GW calculation\");\n    }\n    const Eigen::MatrixXd& qpcoeff = orbitals_.QPdiag().eigenvectors();\n\n    Hqp = qpcoeff * orbitals_.QPdiag().eigenvalues().asDiagonal() *\n          qpcoeff.transpose();\n  }\n\n  // proceed only if BSE requested\n  if (do_bse_singlets_ || do_bse_triplets_) {\n\n    std::chrono::time_point<std::chrono::system_clock> start =\n        std::chrono::system_clock::now();\n\n    BSE bse = BSE(*pLog_, Mmn);\n    bse.configure(bseopt_, orbitals_.RPAInputEnergies(), Hqp);\n\n    // store the direct contribution to the static BSE results\n    Eigen::VectorXd Hd_static_contrib_triplet;\n    Eigen::VectorXd Hd_static_contrib_singlet;\n\n    if (do_bse_triplets_) {\n      bse.Solve_triplets(orbitals_);\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" Solved BSE for triplets \" << flush;\n      bse.Analyze_triplets(fragments_, orbitals_);\n    }\n\n    if (do_bse_singlets_) {\n      bse.Solve_singlets(orbitals_);\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" Solved BSE for singlets \" << flush;\n      bse.Analyze_singlets(fragments_, orbitals_);\n    }\n\n    // do perturbative dynamical screening in BSE\n    if (do_dynamical_screening_bse_) {\n\n      if (do_bse_triplets_) {\n        bse.Perturbative_DynamicalScreening(QMStateType(QMStateType::Triplet),\n                                            orbitals_);\n      }\n\n      if (do_bse_singlets_) {\n        bse.Perturbative_DynamicalScreening(QMStateType(QMStateType::Singlet),\n                                            orbitals_);\n      }\n    }\n\n    std::chrono::duration<double> elapsed_time =\n        std::chrono::system_clock::now() - start;\n    XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" BSE calculation took \"\n                                << elapsed_time.count() << \" seconds.\" << flush;\n  }\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" GWBSE calculation finished \" << flush;\n  return true;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "dc952481a2cc7d4b45562b5039c0eb82d0b732e0", "size": 27145, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/gwbse.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/gwbse/gwbse.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/gwbse/gwbse.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1933333333, "max_line_length": 80, "alphanum_fraction": 0.6036839197, "num_tokens": 7883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.04146227359973832, "lm_q1q2_score": 0.01815315770866783}}
{"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#ifndef TCHECKER_REFDBM_HH\n#define TCHECKER_REFDBM_HH\n\n#include <boost/dynamic_bitset/dynamic_bitset.hpp>\n\n#include \"tchecker/basictypes.hh\"\n#include \"tchecker/dbm/db.hh\"\n#include \"tchecker/dbm/dbm.hh\"\n#include \"tchecker/variables/clocks.hh\"\n\n/*!\n \\file refdbm.hh\n \\brief Functions on DBMs with reference clocks\n \\note A DBM with reference clocks is a DBM where the first refcount variables\n are reference variables, and the other variables are clock (or offset)\n variables. Each clock variable has a corresponding reference variable. The\n correspondance is defined according to an instance r of\n tchecker::reference_clock_variables_t. It associates to each clock variable X\n its reference clock r(X). Each reference clock is mapped to itself.\n\n The value of system clock x is represented as the value of X-r(X), the\n difference between the corresponding clock variable X and its reference clock\n r(X). Reference DBMs generalise standard DBMs which have a single reference\n clock, usually denoted 0.\n\n Reference DBMs have been introduced as \"offset DBMs\" in \"Partial Order\n Reduction for Timed Systems\", J. Bengtsson, B. Jonsson, J. Lilis and Wang Yi,\n CONCUR, 1998.\n */\n\nnamespace tchecker {\n\nnamespace refdbm {\n\n/*!\n \\brief Universal DBM with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is a DBM over reference clocks r\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n \\post dbm is the universal DBM over reference clocks r\n rdbm is tight and consistent.\n */\nvoid universal(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Positive universal DBM with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n \\post rdbm is the universal positive DBM over reference clocks r\n dbm is tight and consistent\n */\nvoid universal_positive(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Empty DBM with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n \\post rdbm represents the empty DBM over reference clocks r (is_empty_0() returns\n true on dbm)\n rdbm IS NOT TIGHT (empty DBMs cannot be tight), NOR CONSISTENT\n */\nvoid empty(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Initialize DBM with reference clocks to zero\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n \\post rdbm represents the zone where all variables are equal to each other over\n reference variables r.\n dbm is tight and consistent.\n */\nvoid zero(tchecker::dbm::db_t * dbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Fast emptiness predicate on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is either non-empty and tight, or it is empty\n rdbm is a DBM over reference clocks r\n \\return true if rdbm has a negative difference bound on (0,0), false otherwise\n \\note this function only checks the (0,0) entry of rdbm. Hence, this function\n returns false for empty DBMs which have no negative bound on (0,0).\n However, all other functions on DBMs with reference clocks set (0,0) to a value\n less-than <=0 when they generate an empty zone. So this function can be used as\n a safe and efficient emptiness check if rdbm has been generated by calls to\n functions over DBMs with reference variables defined in this file.\n */\nbool is_empty_0(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Universality predicate on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\return true if rdbm is universal, false otherwise\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n */\nbool is_universal(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Positivity predicate on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\return true if all clocks in rdbm have a value greater-than or equal-to their\n reference clock, false otherwise\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n */\nbool is_positive(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Positive universality predicate on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\return true if rdbm is universal positive (the only constraints in rdbm are\n positivity constraints: each clock is greater-than or equal-to its reference\n clock), false otherwise.\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n */\nbool is_universal_positive(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Checks if a DBM with reference clocks is open up (time-elapsed)\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\return true if rdbm is open up (it is closed under time successors), false\n otherwise\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is tight (checked by assertion)\n rdbm is consistent (checked by assertion)\n rdbm is a DBM over reference clocks r\n */\nbool is_open_up(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Tightness predicate on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks fr rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is a DBM over reference clocks r\n \\return true if dbm is tight, false otherwise\n */\nbool is_tight(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Tighten a  DBM with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is a DBM over reference clocks r\n rdbm is consistent (checked by assertion)\n \\post rdbm is tight if it is not empty.\n if rdbm is empty, then the difference bound in (0,0) is less-than <=0\n (tchecker::refdbm::is_empty_0() returns true)\n \\return EMPTY if rdbm is empty, NON_EMPTY otherwise\n \\note Applies Floyd-Warshall algorithm on rdbm seen as a weighted graph.\n */\nenum tchecker::dbm::status_t tighten(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Consistency of DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is a DBM over reference clocks r\n \\return true if rdbm is consistent (no negative value on the diagonal), false\n otherwise\n*/\nbool is_consistent(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Synchronized predicate on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n \\return true if reference clocks are equal to each other in rdbm, false otherwise\n */\nbool is_synchronized(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Synchronized predicate on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param sync_ref_clocks : synchronized reference clocks\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n the size of sync_ref_clocks is the number of reference clocks in r (checked by\n assertion)\n \\return true if all reference clocks in sync_ref_clocks are equal in rdbm,\n false otherwise\n */\nbool is_synchronized(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r,\n                     boost::dynamic_bitset<> const & sync_ref_clocks);\n\n/*!\n \\brief Check if a DBM with reference clocks contains a synchronized valuation\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n \\return true dbm contains a synchronized valuation, false otherwise\n */\nbool is_synchronizable(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Equality predicate on DBMs with reference clocks\n \\param rdbm1 : a first DBM\n \\param rdbm2 : a second DBM\n \\param r : reference clocks for rdbm1 and rdbm2\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n rdbm1 and rdbm2 are DBMs over reference clocks r\n \\return true if rdbm1 and rdbm2 are equal, false otherwise\n */\nbool is_equal(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n              tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Inclusion predicate on DBMs with reference clocks\n \\param rdbm1 : a first DBM\n \\param rdbm2 : a second DBM\n \\param r : reference clocks for rdbm1 and rdbm2\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n rdbm1 and rdbm2 are DBMs over reference clocks r\n \\return true if rdbm1 is included into rdbm2, false otherwise\n */\nbool is_le(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n           tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Checks inclusion w.r.t. abstraction aLU* (i.e. aLU over reference DBMs)\n \\param rdbm1 : a first dbm\n \\param rdbm2 : a second dbm\n \\param r : reference clocks for rdbm1 and rdbm2\n \\param l : clock lower bounds for offset clocks, l[0] is the bound for offset\n clock 1 and so on\n \\param u : clock upper bounds for offset clocks, u[0] is the bound for offset\n clock 1 and so on\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are positive (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n l and u are arrays of size r.size()-r.refcount()\n l[i], u[i] < tchecker::dbm::INF_VALUE for all offset clock i>=0 (checked by\n assertion)\n \\return true if rdbm1 <= aLU*(rdbm2), false otherwise\n \\note set l[i]/u[i] to tchecker::clockbounds::NO_BOUND if clock i has no\n lower/upper bound\n */\nbool is_alu_star_le(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n                    tchecker::reference_clock_variables_t const & r, tchecker::integer_t const * l,\n                    tchecker::integer_t const * u);\n\n/*!\n \\brief Checks inclusion w.r.t. abstraction aM* (i.e. aM over reference DBMs)\n \\param rdbm1 : a first dbm\n \\param rdbm2 : a second dbm\n \\param r : reference clocks for rdbm1 and rdbm2\n \\param m : clock bounds for offset clocks, m[0] is the bound for offset clock 1\n and so on\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are positive (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n m is an array of size r.size()-r.refcount()\n m[i] < tchecker::dbm::INF_VALUE for all offset clock i>=0 (checked by\n assertion)\n \\return true if rdbm1 <= aM*(rdbm2), false otherwise\n \\note set m[i] to tchecker::clockbounds::NO_BOUND if clock i has no lower/upper\n bound\n */\nbool is_am_star_le(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n                   tchecker::reference_clock_variables_t const & r, tchecker::integer_t const * m);\n\n/*!\n \\brief Checks inclusion w.r.t. abstraction aLU* (i.e. aLU over reference DBMs)\n combined with time elapse\n \\param rdbm1 : a first dbm\n \\param rdbm2 : a second dbm\n \\param r : reference clocks for rdbm1 and rdbm2\n \\param l : clock lower bounds for offset clocks, l[0] is the bound for offset\n clock 1 and so on\n \\param u : clock upper bounds for offset clocks, u[0] is the bound for offset\n clock 1 and so on\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are positive (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n l and u are arrays of size r.size()-r.refcount()\n l[i], u[i] < tchecker::dbm::INF_VALUE for all offset clock i>=0 (checked by\n assertion)\n \\return true if time-elapse(rdbm1) <= aLU*(time-elapse(rdbm2)), false otherwise\n \\note set l[i]/u[i] to tchecker::clockbounds::NO_BOUND if clock i has no\n lower/upper bound\n \\note time-elapsed(dbm1) and time-elapsed(dbm2) are not computed but the\n algorithm for aLU* is adapted to behave as if rdbm1 and rdbm2 were time-elapsed\n */\nbool is_time_elapse_alu_star_le(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n                                tchecker::reference_clock_variables_t const & r, tchecker::integer_t const * l,\n                                tchecker::integer_t const * u);\n\n/*!\n \\brief Checks inclusion w.r.t. abstraction aM* (i.e. aM over reference DBMs)\n combined with time elapse\n \\param rdbm1 : a first dbm\n \\param rdbm2 : a second dbm\n \\param r : reference clocks for rdbm1 and rdbm2\n \\param m : clock bounds for offset clocks, m[0] is the bound for offset clock 1\n and so on\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are positive (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n m is an array of size r.size()-r.refcount()\n m[i] < tchecker::dbm::INF_VALUE for all offset clock i>=0 (checked by\n assertion)\n \\return true if time-elapse(rdbm1) <= aM*(time-elapse(rdbm2)), false otherwise\n \\note set m[i] to tchecker::clockbounds::NO_BOUND if clock i has no lower/upper\n bound\n \\note time-elapsed(dbm1) and time-elapsed(dbm2) are not computed but the\n algorithm for aLU* is adapted to behave as if rdbm1 and rdbm2 were time-elapsed\n */\nbool is_time_elapse_am_star_le(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n                               tchecker::reference_clock_variables_t const & r, tchecker::integer_t const * m);\n\n/*!\n \\brief Checks inclusion w.r.t. abstraction aLU over synchronized valuations\n \\param rdbm1 : a first dbm\n \\param rdbm2 : a second dbm\n \\param r : reference clocks for rdbm1 and rdbm2\n \\param l : clock lower bounds for offset clocks, l[0] is the bound for offset\n clock 1 and so on\n \\param u : clock upper bounds for offset clocks, u[0] is the bound for offset\n clock 1 and so on\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are positive (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n l and u are arrays of size r.size()-r.refcount()\n l[i], u[i] < tchecker::dbm::INF_VALUE for all offset clock i>=0 (checked by\n assertion)\n \\return true if sync(local_time_elapse(rdbm1)) <=\n aLU(sync(local_time_elapse(rdbm2))), false otherwise\n \\note set l[i]/u[i] to tchecker::clockbounds::NO_BOUND if clock i has no\n lower/upper bound\n */\nbool is_sync_alu_le(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n                    tchecker::reference_clock_variables_t const & r, tchecker::integer_t const * l,\n                    tchecker::integer_t const * u);\n\n/*!\n \\brief Checks inclusion w.r.t. abstraction aM over synchronized valuations\n \\param rdbm1 : a first dbm\n \\param rdbm2 : a second dbm\n \\param r : reference clocks for rdbm1 and rdbm2\n \\param m : clock bounds for offset clocks, m[0] is the bound for offset clock 1\n and so on\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 and rdbm2 are r.size()*r.size() arrays of difference bounds\n rdbm1 and rdbm2 are consistent (checked by assertion)\n rdbm1 and rdbm2 are positive (checked by assertion)\n rdbm1 and rdbm2 are tight (checked by assertion)\n m is an array of size r.size()-r.refcount()\n m[i] < tchecker::dbm::INF_VALUE for all offset clock i>=0 (checked by\n assertion)\n \\return true if sync(rdbm1) <= aM(sync(rdbm2)), false otherwise\n \\note set m[i] to tchecker::clockbounds::NO_BOUND if clock i has no bound\n */\nbool is_sync_am_le(tchecker::dbm::db_t const * rdbm1, tchecker::dbm::db_t const * rdbm2,\n                   tchecker::reference_clock_variables_t const & r, tchecker::integer_t const * m);\n\n/*!\n \\brief Hash function on DBMs with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\return hash value for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is a DBM over reference clocks r\n \\note if rdbm is not tight, the returned hash code may differ from the hash\n code of its corresponding tight DBM\n */\nstd::size_t hash(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Constrain a DBM with reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param x : index of first clock\n \\param y : index of second clock\n \\param cmp : constraint comparator\n \\param value : constraint value\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n 0 <= x < r.size() (checked by assertion)\n 0 <= y < r.size() (checked by assertion)\n \\post rdbm has been intersected with constraint `x - y # value` where # is < if\n cmp is LT, and # is <= if cmp is LE\n rdbm is tight if it is not empty.\n if rdbm is empty, then its difference bound in (0,0) is less-than <=0\n (tchecker::refdbm::is_empty_0() returns true)\n \\return EMPTY if rdbm is empty, NON_EMPTY otherwise\n \\throw std::invalid_argument : if `cmp value` cannot be represented as a\n tchecker::dbm::db_t (only if compilation flag DBM_UNSAFE is not set)\n */\nenum tchecker::dbm::status_t constrain(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                       tchecker::clock_id_t x, tchecker::clock_id_t y, tchecker::dbm::comparator_t cmp,\n                                       tchecker::integer_t value);\n\n/*!\n \\brief Constrain a DBM with reference clocks with a clock constraint\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param c : clock constraint\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n clocks IDs in c are systems clocks, i.e. the first clock has index 0, and the\n last clock has index r.size() - r.refcount() - 1\n \\post rdbm has been intersected with constraint c (translated w.r.t. r clocks)\n rdbm is tight if it is not empty.\n if rdbm is empty, then its difference bound in (0,0) is less-than <=0\n (tchecker::refdbm::is_empty_0() returns true)\n \\return EMPTY if rdbm is empty, NON_EMPTY otherwise\n */\nenum tchecker::dbm::status_t constrain(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                       tchecker::clock_constraint_t const & c);\n/*!\n \\brief Constrain a DBM with reference clocks with a collection of clock constraints\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param cc : collection of clock constraints\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n clocks IDs in c are systems clocks, i.e. the first clock has index 0, and the\n last clock has index r.size() - r.refcount() - 1\n \\post rdbm has been intersected with clock constraints in cc (translated w.r.t.\n r clocks))\n rdbm is tight if it is not empty.\n if rdbm is empty, then its difference bound in (0,0) is less-than <=0\n (tchecker::refdbm::is_empty_0() returns true)\n \\return EMPTY if rdbm is empty, NON_EMPTY otherwise\n */\nenum tchecker::dbm::status_t constrain(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                       tchecker::clock_constraint_container_t const & cc);\n\n/*!\n \\brief Restriction to synchronized valuations\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n \\post rdbm has been restricted to its subset of synchronized valuations\n \\return tchecker::dbm::EMPTY if synchronized dbm is empty,\n tchecker::dbm::NON_EMPTY otherwise\n */\nenum tchecker::dbm::status_t synchronize(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Restriction to synchronized valuations over specified set of reference\n clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param sync_ref_clocks : set of reference clocks to synchronize\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n the size of sync_ref_clocks is the number of reference clocks in r (checked by\n assertion)\n \\post rdbm has been restricted to its subset of valuations that are\n synchronized over all reference clocks in sync_ref_clocks\n \\return tchecker::dbm::EMPTY if synchronized dbm is empty,\n tchecker::dbm::NON_EMPTY otherwise\n */\nenum tchecker::dbm::status_t synchronize(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                         boost::dynamic_bitset<> const & sync_ref_clocks);\n\n/*!\n \\brief Unbounded spread\n*/\nextern tchecker::integer_t const UNBOUNDED_SPREAD;\n\n/*!\n \\brief Bound the spread between reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param spread : expected spread between reference clocks\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n \\post rdbm is unchanged if spread is tchecker::refdbm::UNBOUNDED_SPREAD.\n rdbm has been restricted to its subset of valuations such that the spread\n between all reference clocks is bounded by spread otherwise, if not empty.\n if rdbm is empty, then its difference bound in (0,0) is less-than <=0\n (tchecker::refdbm::is_empty_0() returns true)\n \\return tchecker::dbm::EMPTY is the spread-bounded dbm is empty,\n tchecker::dbm::NON_EMPTY otherwise\n */\nenum tchecker::dbm::status_t bound_spread(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                          tchecker::integer_t spread);\n\n/*!\n \\brief Bound the spread between reference clocks\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param spread : expected spread between reference clocks\n \\param ref_clocks : reference clocks to bound\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n the size of ref_clocks is the number of reference clocks in r (checked by\n assertion)\n \\post rdbm is unchanged if spread is tchecker::refdbm::UNBOUNDED_SPREAD.\n rdbm has been restricted to its subset of valuations such that the spread\n between all reference clocks in ref_clocks is bounded by spread otherwise, if\n not empty.\n if rdbm is empty, then its difference bound in (0,0) is less-than <=0\n (tchecker::refdbm::is_empty_0() returns true)\n \\return tchecker::dbm::EMPTY is the spread-bounded dbm is empty,\n tchecker::dbm::NON_EMPTY otherwise\n */\nenum tchecker::dbm::status_t bound_spread(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                          tchecker::integer_t spread, boost::dynamic_bitset<> const & ref_clocks);\n\n/*!\n \\brief Reset a clock to its reference clock\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param x : clock identifier\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n x < r.size() (checked by assertion)\n \\post clock x has been updated to value r.refmap()[x] in dbm. All other\n variables are unchanged\n rdbm is tight\n */\nvoid reset_to_reference_clock(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                              tchecker::clock_id_t x);\n\n/*!\n \\brief Reset a DBM with reference clocks w.r.t. a clock reset\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param reset : clock reset\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n all clock IDs in reset are system clock IDs\n reset should be a reset to reference clock: the right id of reset is\n tchecker::REFCLOCK_ID, and the value in reset is 0 (checked by assertion)\n \\post the left clock in reset is equal to its reference clock. All other\n variables are unchanged.\n rdbm is tight\n */\nvoid reset(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r, tchecker::clock_reset_t const & reset);\n\n/*!\n \\brief Reset a DBM with reference clocks w.r.t. a clock reset\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param rc : clock reset collection\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n all clock IDs in rc are system clock IDs\n all resets in rc must be resets to reference clock: the right id is\n tchecker::REFCLOCK_ID, and the value  is 0 (checked by assertion)\n \\post the left clock in each reset in cr is equal to its reference clock. All\n other variables are unchanged.\n rdbm is tight\n */\nvoid reset(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n           tchecker::clock_reset_container_t const & rc);\n\n/*!\n \\brief Asynchronous open-up (delay)\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n \\post upper bounds on reference clocks and constraints relating reference\n clocks have been removed from rdbm (i.e. they have been set to (<,inf)).\n rdbm is tight and consistent.\n */\nvoid asynchronous_open_up(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Asynchronous open-up (delay) with clock stopping\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\param delay_allowed : reference clocks allowed to delay\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n rdbm is a DBM over reference clocks r\n delay_allowed has size r.refcount() (checked by assertion)\n \\post reference clocks in rdbm with delay_allowed are unbounded (i.e. x-t<inf\n for every reference clock t and any variable x, including x being another\n reference clock).\n reference clocks in rdbm without delay_allowed are unchanged\n rdbm is tight and consistent.\n */\nvoid asynchronous_open_up(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                          boost::dynamic_bitset<> const & delay_allowed);\n\n/*!\n \\brief Extract a standard DBM from a DBM with reference clocks\n \\param rdbm : a DBM with reference clocks\n \\param r : reference clocks for rdbm\n \\param dbm : a DBM\n \\param dim : dimension of dbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is an r.size()*r.size() array of difference bounds (checked by assertion)\n rdbm is not empty.\n rdbm is consistent (checked by assertion)\n rdbm is tight (checked by assertion)\n rdbm is synchronized (checked by assertion)\n rdbm is a DBM over reference clocks r\n dbm is not nullptr (checked by assertion)\n dbm is a dim*dim array of difference bounds\n dim is equal to r.size() - r.refcount() + 1 (checked by assertion)\n \\post dbm is the zone extracted from rdbm by identifying the reference clocks\n in rdbm to the zero clock in dbm.\n dbm is tight and consistent.\n */\nvoid to_dbm(tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r, tchecker::dbm::db_t * dbm,\n            tchecker::clock_id_t dim);\n\n/*!\n \\brief Output a DBM with reference clocks as a matrix\n \\param os : output stream\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is a DBM over reference clocks r\n \\post rdbm has been output to os as a matrix\n \\return os after output\n */\nstd::ostream & output_matrix(std::ostream & os, tchecker::dbm::db_t const * rdbm,\n                             tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Output a DBM with reference clocks as a conjunction of constraints\n \\param os : output stream\n \\param rdbm : a DBM\n \\param r : reference clocks for rdbm\n \\pre rdbm is not nullptr (checked by assertion)\n rdbm is a r.size()*r.size() array of difference bounds\n rdbm is a DBM over reference clocks r\n \\post the relevant constraints in rdbm have been output to os. Relevant\n constraints are those that differ from the universal DBM.\n \\return os after output\n */\nstd::ostream & output(std::ostream & os, tchecker::dbm::db_t const * rdbm, tchecker::reference_clock_variables_t const & r);\n\n/*!\n \\brief Lexical ordering over DBMs with reference clocks\n \\param rdbm1 : first DBM\n \\param r1 : reference clocks for rdbm1\n \\param rdbm2 : second DBM\n \\param r2 : reference clocks for rdbm2\n \\pre rdbm1 and rdbm2 are not nullptr (checked by assertion)\n rdbm1 is a r1.size()*r1.size() array of difference bounds\n rdbm2 is a r2.size()*r2.size() array of difference bounds\n rdbm1 is a DBM over reference clocks r1\n rdbm2 is a DBM over reference clocks r2\n \\return 0 if rdbm1 and rdbm2 are equal, a negative value if rdbm1 is smaller\n than rdbm2 w.r.t. lexical ordering, and a positive value otherwise\n */\nint lexical_cmp(tchecker::dbm::db_t const * rdbm1, tchecker::reference_clock_variables_t const & r1,\n                tchecker::dbm::db_t const * rdbm2, tchecker::reference_clock_variables_t const & r2);\n\n} // end of namespace refdbm\n\n} // end of namespace tchecker\n\n#endif // TCHECKER_REFDBM_HH\n", "meta": {"hexsha": "74187423a153393aeb2e81cb8bcba8e60ba127b7", "size": 32512, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/tchecker/dbm/refdbm.hh", "max_stars_repo_name": "schlepil/tchecker", "max_stars_repo_head_hexsha": "3ab68fe150d16e3db77db8380c47e02026c7815f", "max_stars_repo_licenses": ["MIT"], "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/tchecker/dbm/refdbm.hh", "max_issues_repo_name": "schlepil/tchecker", "max_issues_repo_head_hexsha": "3ab68fe150d16e3db77db8380c47e02026c7815f", "max_issues_repo_licenses": ["MIT"], "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/tchecker/dbm/refdbm.hh", "max_forks_repo_name": "schlepil/tchecker", "max_forks_repo_head_hexsha": "3ab68fe150d16e3db77db8380c47e02026c7815f", "max_forks_repo_licenses": ["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.6402684564, "max_line_length": 127, "alphanum_fraction": 0.7368971457, "num_tokens": 8978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.045352578457547636, "lm_q1q2_score": 0.0181324881562205}}
{"text": "#pragma once\n\n// deal.II includes ----------------------------------------\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/grid/tria.h>\n\n// system  includes ----------------------------------------\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <vector>\n\n\nnamespace boltzmann {\n\n/**y\n * @brief Provides mapping between periodic and non periodic indexing on a\n *        given grid in the *physical* domain.\n *\n * @param dh\n */\nclass DoFMapperPeriodic\n{\n private:\n  typedef unsigned int index_t;\n  typedef std::set<index_t> index_set_t;\n  typedef std::map<index_t, index_t> map_t;\n\n public:\n  void init(const dealii::DoFHandler<2>& dh);\n\n  /**\n   * @brief full grid -> periodic enumeration\n   *\n   * @param unrestricted_idx (full grid id)\n   *\n   * @return restricted grid id\n   */\n  index_t operator[](const index_t unrestricted_idx) const;\n\n  /**\n   * @brief restriced -> full\n   *\n   * @param restricted_idx\n   *\n   * @return full_idx\n   */\n  index_t lookup(const index_t restricted_idx) const;\n\n  const std::vector<index_t>& get_mapping() const { return mapping; }\n\n  unsigned int size() const { return size_; }\n\n  const map_t& dof_map() const { return dof_map_; }\n\n private:\n  unsigned int size_;\n  /// full -> periodic renumbering\n  std::vector<index_t> mapping;\n  ///\n  std::vector<index_t> inverse;\n  /// maps boundary DoFs to their master DoF\n  /// no entry means this DoF is original\n  map_t dof_map_;\n};\n\n// ------------------------------------------------------------\n/**\n * @brief periodic -> non-periodic\n *\n * @param restricted_idx\n *\n * @return\n */\nDoFMapperPeriodic::index_t\nDoFMapperPeriodic::lookup(const index_t restricted_idx) const\n{\n  return this->inverse[restricted_idx];\n}\n\n// ------------------------------------------------------------\n/**\n * @brief go from non-periodic dof-idx to periodic indexing\n *\n * @param unrestricted_idx  non-periodic dof-idx\n *\n * @return\n */\nDoFMapperPeriodic::index_t DoFMapperPeriodic::operator[](const index_t unrestricted_idx) const\n{\n  return mapping[unrestricted_idx];\n}\n\n// ------------------------------------------------------------\nvoid\nDoFMapperPeriodic::init(const dealii::DoFHandler<2>& dh)\n{\n  typedef std::map<index_t, double> map_t;\n  map_t dof_locations_y;\n  map_t dof_locations_x;\n\n  for (dealii::DoFHandler<2>::active_cell_iterator cell = dh.begin_active(); cell != dh.end();\n       ++cell) {\n    auto collect_vertices = [&](map_t& dof_locations, const int face_id, const int c_id) {\n      if (cell->at_boundary() && cell->face(face_id)->at_boundary()) {\n        dof_locations[cell->face(face_id)->vertex_dof_index(0, 0)] =\n            cell->face(face_id)->vertex(0)[c_id];\n        dof_locations[cell->face(face_id)->vertex_dof_index(1, 0)] =\n            cell->face(face_id)->vertex(1)[c_id];\n      }\n    };\n    collect_vertices(dof_locations_y, 1, 1);\n    collect_vertices(dof_locations_x, 3, 0);\n  }\n\n  typedef std::pair<index_t, index_t> index_pair_t;\n  typedef std::set<index_pair_t> index_pair_set_t;\n\n  index_pair_set_t edges;\n  // contains all dof indices located on the boundary\n  std::set<index_t> indices;\n  // build edges\n  for (dealii::DoFHandler<2>::active_cell_iterator cell = dh.begin_active(); cell != dh.end();\n       ++cell) {\n    // left and right boundary\n    int face_id = 0;\n    // coordinate id\n    int c_id = 1;\n    if (cell->at_boundary() && cell->face(face_id)->at_boundary()) {\n      for (index_t face_vertex = 0; face_vertex < 2; ++face_vertex) {\n        map_t::const_iterator p = dof_locations_y.begin();\n        for (; p != dof_locations_y.end(); ++p) {\n          if (std::fabs(p->second - cell->face(face_id)->vertex(face_vertex)[c_id]) < 1e-8) {\n            const index_t ix1 = cell->face(face_id)->vertex_dof_index(face_vertex, 0);\n            const index_t ix2 = p->first;\n            if (ix1 < ix2) {\n              edges.insert(std::make_pair(ix1, ix2));\n              indices.insert(ix1);\n            } else {\n              edges.insert(std::make_pair(ix2, ix1));\n              indices.insert(ix2);\n            }\n            break;\n          }\n        }\n        if (p == dof_locations_y.end()) {\n          std::cerr << \"No corresponding degree of freedom was found!\"\n                    << \"At coordinate y = \" << p->second << std::endl;\n          exit(-1);\n        }\n        // Assert( p != dof_locations_y.end(),\n        //         dealii::ExcMessage( \"No corresponding degree of freedom was found!\"));\n      }\n    }\n    face_id = 2;\n    c_id = 0;\n    if (cell->at_boundary() && cell->face(face_id)->at_boundary()) {\n      for (index_t face_vertex = 0; face_vertex < 2; ++face_vertex) {\n        map_t::const_iterator p = dof_locations_x.begin();\n        for (; p != dof_locations_x.end(); ++p) {\n          if (std::fabs(p->second - cell->face(face_id)->vertex(face_vertex)[c_id]) < 1e-8) {\n            const index_t ix1 = cell->face(face_id)->vertex_dof_index(face_vertex, 0);\n            const index_t ix2 = p->first;\n            if (ix1 < ix2) {\n              edges.insert(std::make_pair(ix1, ix2));\n              indices.insert(ix1);\n            } else {\n              edges.insert(std::make_pair(ix2, ix1));\n              indices.insert(ix2);\n            }\n            break;\n          }\n        }\n        if (p == dof_locations_x.end()) {\n          std::cerr << \"No corresponding degree of freedom was found!\"\n                    << \"At coordinate x = \" << p->second << std::endl;\n          exit(-1);\n        }\n        // Assert( p != dof_locations_x.end(),\n        //         dealii::ExcMessage( \"No corresponding degree of freedom was found!\"));\n      }\n    }\n  }\n  // build cluster\n  typedef std::set<index_t> index_set_t;\n  std::function<void(index_t, index_set_t & neighbors)> find_clones = [&](index_t ix,\n                                                                          index_set_t& clones) {\n    index_pair_set_t::iterator it = edges.begin();\n    while (true) {\n      // finished?\n      if (!(it != edges.end())) break;\n      if (it->first == ix) {\n        // add this edge to\n        index_t next = it->second;\n        edges.erase(it++);\n        // recursion\n        find_clones(next, clones);\n        clones.insert(next);\n        // remove this edge from the set and go to the next element\n      } else {\n        ++it;\n      }\n    }\n  };\n\n  std::map<index_t, index_set_t> clones_map;\n  // iterate over boundary vertices and cluster them\n  for (index_t ix : indices) {\n    index_set_t& clones = clones_map[ix];\n    // recursively traverse the graph add to\n    // neighbors and delete the edges after they have been visited\n    find_clones(ix, clones);\n    // create a map\n    for (index_t i : clones) {\n      dof_map_[i] = ix;\n    }\n  }\n\n  // mapping for periodic boundary condition has been constructed,\n  // now renumber the dofs\n  struct DOF\n  {\n    // helper class\n    DOF(const index_t ix_)\n        : ix(ix_)\n    {\n    }\n    index_t ix;\n  };\n\n  std::nullptr_t nullp;\n\n  typedef std::shared_ptr<DOF> ptr_DOF;\n  std::vector<ptr_DOF> mapping_ptr(dh.n_dofs(), NULL);\n\n  unsigned int index_counter = 0;\n  for (unsigned int i = 0; i < dh.n_dofs(); ++i) {\n    // slave node? (one that is remapped to another?)\n    auto it = dof_map_.find(i);\n    if (it != dof_map_.end()) {\n      index_t master = it->second;\n      // does it point to another DOF which is already initialized?\n      if (mapping_ptr[master] != nullp) {\n        mapping_ptr[i] = mapping_ptr[master];\n      } else {\n        // create this dof\n        mapping_ptr[master] = ptr_DOF(new DOF(index_counter++));\n      }\n    } else {\n      // it is a master node\n      // initialize it if required\n      if (mapping_ptr[i] == nullp) {\n        mapping_ptr[i] = ptr_DOF(new DOF(index_counter++));\n      }\n    }\n  }\n  mapping.resize(dh.n_dofs());\n  // store renumber into mapping\n  for (unsigned int i = 0; i < dh.n_dofs(); ++i) {\n    mapping[i] = mapping_ptr[i]->ix;\n  }\n\n  this->size_ = index_counter;\n\n  // inverse mapping\n  inverse.resize(this->size_);\n  for (unsigned int i = 0; i < dh.n_dofs(); ++i) {\n    inverse[mapping[i]] = i;\n  }\n}\n} // end namespace boltzmann\n", "meta": {"hexsha": "bdb79f8cd2b06d3fca894b7df0dd03f9e7df4f62", "size": 8158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/grid/dof_mapper_periodic.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/grid/dof_mapper_periodic.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/grid/dof_mapper_periodic.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": 29.7737226277, "max_line_length": 96, "alphanum_fraction": 0.5786957588, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.05834583651821275, "lm_q1q2_score": 0.018127723690163307}}
{"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 <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\n#include \"galois/Galois.h\"\n#include \"galois/AtomicHelpers.h\"\n#include \"galois/FlatMap.h\"\n#include \"galois/Reduction.h\"\n#include \"galois/PriorityQueue.h\"\n#include \"galois/Timer.h\"\n#include \"galois/gstl.h\"\n#include \"galois/Timer.h\"\n#include \"galois/graphs/LCGraph.h\"\n#include \"galois/graphs/TypeTraits.h\"\n#include \"llvm/Support/CommandLine.h\"\n\n#include \"Lonestar/BoilerPlate.h\"\n#include \"Lonestar/BFS_SSSP.h\"\n\n#include <iostream>\n#include <chrono>\n#include <iomanip>\n#include <unordered_set>\n#include <fstream>\n#include \"stack_vector.h\"\n\n\n#ifndef STACK_BITVECTOR_SIZE\n#define STACK_BITVECTOR_SIZE 23947347\n#endif\n\nnamespace cll = llvm::cl;\nusing namespace std::chrono; \nnamespace acc = boost::accumulators;\n\nstatic const char* name = \"Single Source Shortest Path\";\nstatic const char* desc =\n    \"Computes the shortest path from a source node to all nodes in a directed \"\n    \"graph using a modified chaotic iteration algorithm\";\nstatic const char* url = \"single_source_shortest_path\";\n\nstatic cll::opt<std::string>\n    filename(cll::Positional, cll::desc(\"<input graph>\"), cll::Required);\n\nstatic cll::opt<unsigned int>\n    startNode(\"startNode\",\n              cll::desc(\"Node to start search from (default value 0)\"),\n              cll::init(0));\nstatic cll::opt<unsigned int>\n    reportNode(\"reportNode\",\n               cll::desc(\"Node to report distance to(default value 1)\"),\n               cll::init(1));\nstatic cll::opt<unsigned int>\n    stepShift(\"delta\",\n              cll::desc(\"Shift value for the deltastep (default value 13)\"),\n              cll::init(13));\n\nenum Algo {\n  deltaTile = 0,\n  deltaStep,\n  serDeltaTile,\n  serDelta,\n  dijkstraTile,\n  dijkstra,\n  topo,\n  topoTile,\n  serSP1,\n  serSP2,\n  parSP1,\n  parSP2\n};\n\nconst char* const ALGO_NAMES[] = {\"deltaTile\", \"deltaStep\",    \"serDeltaTile\",\n                                  \"serDelta\",  \"dijkstraTile\", \"dijkstra\",\n                                  \"topo\", \"topoTile\", \"serSP1\", \"serSP2\", \"parSP1\", \"parSP2\"};\n\nstatic cll::opt<Algo>\n    algo(\"algo\", cll::desc(\"Choose an algorithm:\"),\n         cll::values(clEnumVal(deltaTile, \"deltaTile\"),\n                     clEnumVal(deltaStep, \"deltaStep\"),\n                     clEnumVal(serDeltaTile, \"serDeltaTile\"),\n                     clEnumVal(serDelta, \"serDelta\"),\n                     clEnumVal(dijkstraTile, \"dijkstraTile\"),\n                     clEnumVal(dijkstra, \"dijkstra\"), clEnumVal(topo, \"topo\"),\n                     clEnumVal(topoTile, \"topoTile\"),\n                     clEnumVal(serSP1, \"serSP1\"),\n                     clEnumVal(serSP2, \"serSP2\"),\n                     clEnumVal(parSP1, \"parSP1\"),\n                     clEnumVal(parSP2, \"parSP2\"),\n                     clEnumValEnd),\n         cll::init(deltaTile));\n\nconstexpr static const bool TRACK_WORK          = false;\nconstexpr static const unsigned CHUNK_SIZE      = 64u;\nconstexpr static const ptrdiff_t EDGE_TILE_SIZE = 512;\n\nhigh_resolution_clock::time_point start;\n\ntemplate<typename GraphTypes>\nstruct SerNodeData {\n  typename GraphTypes::SerGraphType::GraphNode node;\n  int pred;\n  uint32_t dist;\n  bool fixed;\n  high_resolution_clock::time_point fixed_ts;\n  uint32_t min_in_weight;\n  SerNodeData(): node(-1), pred(0), dist(0), fixed(false) {}\n};\n\ntemplate<typename GraphTypes>\nstruct ParNodeData {\n  typename GraphTypes::ParGraphType::GraphNode node;\n  std::atomic<int> pred;\n  std::atomic<uint32_t> dist;\n  std::atomic<bool> fixed;\n  high_resolution_clock::time_point fixed_ts;\n  uint32_t min_in_weight;\n  ParNodeData(): node(-1), pred(0), dist(0), fixed(false) {}\n};\n\nstruct GraphTypes {\n  typedef SerNodeData<GraphTypes> SerNodeDataType;\n  typedef galois::graphs::LC_CSR_Graph<typename GraphTypes::SerNodeDataType, uint32_t>::\n  with_no_lockable<true>::type ::with_numa_alloc<true>::type SerGraphType;\n  typedef ParNodeData<GraphTypes> ParNodeDataType;\n  typedef galois::graphs::LC_CSR_Graph<typename GraphTypes::ParNodeDataType, uint32_t>::\n  with_no_lockable<true>::type ::with_numa_alloc<true>::type ParGraphType;\n};\n\nstd::vector<uint32_t> total_pred;\n\ntemplate<typename GType>\nstruct GraphTypeTraits {\n  typedef BFS_SSSP<GType, uint32_t, true, EDGE_TILE_SIZE> SSSP;\n  typedef typename SSSP::Dist Dist;\n  typedef typename SSSP::UpdateRequest UpdateRequest;\n  typedef typename SSSP::UpdateRequestIndexer UpdateRequestIndexer;\n  typedef typename SSSP::SrcEdgeTile SrcEdgeTile;\n  typedef typename SSSP::SrcEdgeTileMaker SrcEdgeTileMaker;\n  typedef typename SSSP::SrcEdgeTilePushWrap SrcEdgeTilePushWrap;\n  typedef typename SSSP::ReqPushWrap ReqPushWrap;\n  typedef typename SSSP::OutEdgeRangeFn OutEdgeRangeFn;\n  typedef typename SSSP::TileRangeFn TileRangeFn;\n};\n\ntemplate<typename GType>\nstruct GraphType {\n  typedef GType Graph;\n  typedef typename GType::GraphNode GNode;\n  typedef GraphTypeTraits<GType> Traits;\n};\n\ntemplate <typename GType,\n          typename T,\n          typename P,\n          typename R,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename Traits = typename GType::Traits>\nvoid deltaStepAlgo(Graph& graph,\n                   GNode source,\n                   const P& pushWrap,\n                   const R& edgeRange) {\n\n  using Dist                 = typename Traits::Dist;\n  using UpdateRequestIndexer = typename Traits::UpdateRequestIndexer;\n\n  //! [reducible for self-defined stats]\n  galois::GAccumulator<size_t> BadWork;\n  //! [reducible for self-defined stats]\n  galois::GAccumulator<size_t> WLEmptyWork;\n\n  namespace gwl = galois::worklists;\n\n  using PSchunk = gwl::PerSocketChunkFIFO<CHUNK_SIZE>;\n  using OBIM = galois::worklists::OrderedByIntegerMetric<UpdateRequestIndexer, PSchunk>;\n\n  graph.getData(source).dist = 0;\n\n  galois::InsertBag<T> initBag;\n  pushWrap(initBag, source, 0, \"parallel\");\n\n  galois::for_each(galois::iterate(initBag),\n                   [&](const T& item, auto& ctx) {\n                     constexpr galois::MethodFlag flag =\n                         galois::MethodFlag::UNPROTECTED;\n                     const auto& sdata = graph.getData(item.src, flag);\n\n                     if (sdata.dist < item.dist) {\n                       if (TRACK_WORK)\n                         WLEmptyWork += 1;\n                       return;\n                     }\n\n                     for (auto ii : edgeRange(item)) {\n\n                       GNode dst          = graph.getEdgeDst(ii);\n                       auto& ddist        = graph.getData(dst, flag);\n                       Dist ew            = graph.getEdgeData(ii, flag);\n                       const Dist newDist = sdata.dist + ew;\n\n\n                       while (true) {\n                         Dist oldDist = ddist.dist;\n\n                         if (oldDist <= newDist) {\n                           break;\n                         }\n\n                         if (ddist.dist.compare_exchange_weak(\n                                 oldDist, newDist, std::memory_order_relaxed)) {\n\n                           ddist.fixed = true;\n                           ddist.fixed_ts = high_resolution_clock::now();\n                           \n                           if (TRACK_WORK) {\n                             //! [per-thread contribution of self-defined stats]\n                             if (oldDist != GType::Traits::SSSP::DIST_INFINITY) {\n                               BadWork += 1;\n                             }\n                             //! [per-thread contribution of self-defined stats]\n                           }\n\n                           pushWrap(ctx, dst, newDist);\n                           break;\n                         }\n                       }\n                     }\n                   },\n                   galois::wl<OBIM>(UpdateRequestIndexer{stepShift}),\n                   galois::no_conflicts(), galois::loopname(\"SSSP\"));\n\n  if (TRACK_WORK) {\n    //! [report self-defined stats]\n    galois::runtime::reportStat_Single(\"SSSP\", \"BadWork\", BadWork.reduce());\n    //! [report self-defined stats]\n    galois::runtime::reportStat_Single(\"SSSP\", \"WLEmptyWork\",\n                                       WLEmptyWork.reduce());\n  }\n}\n\ntemplate <typename GType,\n          typename T,\n          typename P,\n          typename R,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename Traits = typename GType::Traits>\nvoid serDeltaAlgo(Graph& graph, const GNode& source,\n                  const P& pushWrap, const R& edgeRange) {\n\n  using UpdateRequestIndexer = typename Traits::UpdateRequestIndexer;\n\n  SerialBucketWL<T, UpdateRequestIndexer> wl(UpdateRequestIndexer{stepShift});\n  graph.getData(source).dist = 0;\n\n  pushWrap(wl, source, 0);\n\n  size_t iter = 0ul;\n  while (!wl.empty()) {\n\n    auto& curr = wl.minBucket();\n\n    while (!curr.empty()) {\n      ++iter;\n      auto item = curr.front();\n      curr.pop_front();\n\n      if (graph.getData(item.src).dist < item.dist) {\n        // empty work\n        continue;\n      }\n\n      for (auto e : edgeRange(item)) {\n\n        GNode dst   = graph.getEdgeDst(e);\n        auto& ddata = graph.getData(dst);\n\n        const auto newDist = item.dist + graph.getEdgeData(e);\n\n        if (newDist < ddata.dist) {\n          ddata.dist = newDist;\n          pushWrap(wl, dst, newDist);\n        }\n      }\n    }\n\n    wl.goToNextBucket();\n  }\n\n  if (!wl.allEmpty()) {\n    std::abort();\n  }\n  galois::runtime::reportStat_Single(\"SSSP-Serial-Delta\", \"Iterations\", iter);\n}\n\ntemplate <typename GType,\n          typename T,\n          typename P,\n          typename R,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename Traits = typename GType::Traits>\nvoid dijkstraAlgo(Graph& graph, const GNode& source, const P& pushWrap,\n                  const R& edgeRange) {\n\n  using WL = galois::MinHeap<T>;\n\n  graph.getData(source).dist = 0;\n\n  WL wl;\n  pushWrap(wl, source, 0);\n\n  while (!wl.empty()) {\n\n    T item = wl.pop();\n\n    if (graph.getData(item.src).dist < item.dist) {\n      continue;\n    }\n\n    auto& nd = graph.getData(item.src);\n    nd.fixed = true;\n    nd.fixed_ts = high_resolution_clock::now();\n\n    for (auto e : edgeRange(item)) {\n\n      GNode dst   = graph.getEdgeDst(e);\n      auto& ddata = graph.getData(dst);\n\n      const auto newDist = item.dist + graph.getEdgeData(e);\n\n      if (newDist < ddata.dist) {\n        ddata.dist = newDist;\n        pushWrap(wl, dst, newDist);\n      }\n    }\n  }\n}\n\ntemplate<typename Graph, typename R>\nvoid calc_graph_predecessors(Graph& graph, R& edgeRange) {\n  // Fill the pred array\n  for (auto vertex : graph) {\n    for (auto edge : edgeRange(vertex)) {\n      auto& k_data = graph.getData(graph.getEdgeDst(edge));\n      k_data.pred++;\n      total_pred[k_data.node]++;\n      k_data.min_in_weight = std::min(k_data.min_in_weight, graph.getEdgeData(edge));\n    }\n  }\n}\n\n#ifdef DEBUG\n#define D(x) x\n#else\n#define D(x)\n#endif\n\n#define LIKELY(condition) __builtin_expect(static_cast<bool>(condition), 1)\n#define UNLIKELY(condition) __builtin_expect(static_cast<bool>(condition), 0)\n\ntemplate <typename GType,\n          typename T,\n          typename P,\n          typename R,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename GNodeData = typename GType::Graph::node_data_type,\n          typename Traits = typename GType::Traits,\n\t  typename Cmp = std::less<typename Traits::Dist>>\nvoid serSP1Algo(Graph& graph, const GNode& source,\n                const P& pushWrap, const R& edgeRange) {\n\n  using Heap = galois::MinHeap<T>;\n  using Dist = typename Traits::Dist;\n\n  bool changed;\n\n  Heap heap;\n  pushWrap(heap, source, 0);\n\n  galois::gstl::Vector<GNodeData*> r_set;\n  r_set.reserve(100);\n\n  GNodeData* min = nullptr;\n  Cmp cmp;\n\n  // While the heap is not empty\n  while (!heap.empty() || !r_set.empty()) {\n\n    while (LIKELY(!heap.empty())) {\n      T item = heap.top();\n      GNodeData* item_data = &graph.getData(item.src);\n\n      if (item_data->fixed || item_data->dist < item.dist) {\n        // If we got a min, go do some work.\n        heap.pop();\n        if (!r_set.empty()) break;\n        continue;\n      }\n      heap.pop();\n      min = item_data;\n      min->fixed = true;\n      min->fixed_ts = high_resolution_clock::now();\n      r_set.push_back(min);\n\n      if (!(UNLIKELY(!heap.empty()) && heap.top().dist == min->dist)) break;\n    }\n\n    // Inner loop, go through the all the elements in R\n    while(r_set.size() > 0) {\n      GNodeData* z = r_set.back();\n      r_set.pop_back();\n\n      // Get all the vertices that have edges from z\n      for (auto e : edgeRange(z->node)) {\n        // If k vertex is not fixed, process the edge between z and k.\n        auto k = &graph.getData(graph.getEdgeDst(e));\n        if (k->fixed) continue;\n\n        Dist z_k_dist = graph.getEdgeData(e);\n\n        changed = false;\n        if(z->dist + z_k_dist < k->dist) {\n          k->dist = z->dist + z_k_dist;\n          changed = true;\n          if (k->dist < min->dist) min = k;\n        }\n        if (--k->pred <= 0) {\n          k->fixed = true;\n          k->fixed_ts = high_resolution_clock::now();\n          r_set.push_back(k);\n        } else if (changed) {\n          pushWrap(heap,k->node,k->dist);\n        }\n      }\n\n      if (r_set.empty() && !min->fixed && cmp(min->dist, heap.top().dist)){\n        // We're done, but before we break, let's just check whether we have the new min in the q set\n        // That is, if the heap is not empty and the current min is higher than the min in the q\n        // set no point in pushing back to the heap, where it would have to bubble up.\n        min->fixed = true;\n        min->fixed_ts = high_resolution_clock::now();\n        r_set.push_back(min);\n      }\n    }\n  }\n}\n\n// template <typename GType,\n//           typename T,\n//           typename P,\n//           typename R,\n//           typename Graph = typename GType::Graph,\n//           typename GNode = typename GType::GNode,\n//           typename GNodeData = typename GType::Graph::node_data_type,\n//           typename Traits = typename GType::Traits,\n// \t  typename Cmp = std::less<typename Traits::Dist>>\n// void serSP2Algo(Graph& graph, const GNode& source,\n//                 const P& pushWrap, const R& edgeRange) {\n\n//   using Heap = galois::MinHeap<T>;\n//   using Dist = typename Traits::Dist;\n\n//   bool changed;\n\n//   Heap heap;\n//   pushWrap(heap, source, 0);\n\n//   galois::gstl::Vector<GNodeData*> r_set;\n//   r_set.reserve(100);\n\n//   GNodeData* min = nullptr;\n//   Cmp cmp;\n\n//   // While the heap is not empty\n//   while (!heap.empty() || !r_set.empty()) {\n\n//     while (LIKELY(!heap.empty())) {\n//       T item = heap.top();\n//       GNodeData* item_data = &graph.getData(item.src);\n\n//       if (item_data->fixed || item_data->dist < item.dist) {\n//         // If we got a min, go do some work.\n//         heap.pop();\n//         if (!r_set.empty()) break;\n//         continue;\n//       }\n//       heap.pop();\n//       min = item_data;\n//       min->fixed = true;\n//       min->fixed_ts = high_resolution_clock::now();\n//       r_set.push_back(min);\n\n//       if (heap.empty() || heap.top().dist != min->dist) break;\n//     }\n\n//     galois::gstl::Vector<GNodeData*> q_set1;\n//     galois::gstl::Vector<GNodeData*> q_set2;\n//     galois::gstl::Vector<GNodeData*>* q_set_current = &q_set1;\n//     galois::gstl::Vector<GNodeData*>* q_set_aux = &q_set2;\n//     // Inner loop, go through the all the elements in R\n//     while(r_set.size() > 0) {\n//       GNodeData* z = r_set.back();\n//       r_set.pop_back();\n\n//       // Get all the vertices that have edges from z\n//       for (auto e : edgeRange(z->node)) {\n//         auto k = &graph.getData(graph.getEdgeDst(e));\n//         Dist z_k_dist = graph.getEdgeData(e);\n//         // If k vertex is not fixed, process the edge between z and k.\n//         if (k->fixed) continue;\n\n\n//         changed = false;\n//         if(z->dist + z_k_dist < k->dist) {\n//           //std::cout << \"Trying to relax to \" <<  (z->dist + z_k_dist) << std::endl;\n//           k->dist = z->dist + z_k_dist;\n//           changed = true;\n//           if (k->dist < min->dist) min = k;\n//         }\n//         if (--k->pred == 0 || k->dist <= (min->dist + k->min_in_weight)) {         \n//           k->fixed = true;\n//           k->fixed_ts = high_resolution_clock::now();\n//           r_set.push_back(k);\n//         } else if (changed) {\n//           q_set_current->push_back(k);\n//         }\n//       }\n\n//       if (r_set.empty()) {        \n//         if (!min->fixed && min->dist <= heap.top().dist) {\n//           // We're done, but before we break, let's just check whether we have the new min in the q set\n//           // That is, if the heap is not empty and the current min is higher than the min in the q\n//           // set no point in pushing back to the heap, where it would have to bubble up.\n//           min->fixed = true;\n//           min->fixed_ts = high_resolution_clock::now();\n//           r_set.push_back(min);\n//         }\n//         for (auto& q : *q_set_current) {\n//           if (q->fixed) {\n//             r_set.push_back(q);\n//           } else {\n//             q_set_aux->push_back(q);\n//           }\n//         }\n//         if (r_set.empty()) {\n//           for (auto& q: *q_set_aux) {\n//             pushWrap(heap, q->node, q->dist);\n//           }\n//         } else {\n//           q_set_current->clear();\n//           auto temp =  q_set_current;\n//           q_set_current = q_set_aux;\n//           q_set_aux = temp;          \n//         }\n//       }\n//     }\n//   }\n// }\n\ntemplate <typename GType,\n          typename T,\n          typename P,\n          typename R,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename GNodeData = typename GType::Graph::node_data_type,\n          typename Traits = typename GType::Traits,\n\t  typename Cmp = std::less<typename Traits::Dist>>\nvoid serSP2Algo(Graph& graph, const GNode& source,\n                const P& pushWrap, const R& edgeRange) {\n\n  using Heap = galois::MinHeap<T>;\n  using Dist = typename Traits::Dist;\n\n  bool changed;\n\n  Heap heap;\n  pushWrap(heap, source, 0);\n\n  galois::gstl::Vector<GNodeData*> r_set;\n  r_set.reserve(100);\n\n  GNodeData* min = nullptr;\n  Cmp cmp;\n\n  // While the heap is not empty\n  while (!heap.empty() || !r_set.empty()) {\n\n    while (LIKELY(!heap.empty())) {\n      T item = heap.top();\n      GNodeData* item_data = &graph.getData(item.src);\n\n       heap.pop();\n      if (item_data->fixed || item_data->dist < item.dist) {\n        // If we got a min, go do some work.\n        if (!r_set.empty()) break;\n        continue;\n      }\n      min = item_data;\n      min->fixed = true;\n      min->fixed_ts = high_resolution_clock::now();\n      r_set.push_back(min);\n\n      if (heap.empty() || heap.top().dist != min->dist) break;\n    }\n\n    // Inner loop, go through the all the elements in R\n    while(r_set.size() > 0) {\n      GNodeData* z = r_set.back();\n      //std::cout << \"Processing node \" << z->node << std::endl;\n      r_set.pop_back();\n\n      // Get all the vertices that have edges from z\n      for (auto e : edgeRange(z->node)) {\n        auto k = &graph.getData(graph.getEdgeDst(e));\n        Dist z_k_dist = graph.getEdgeData(e);\n        // If k vertex is not fixed, process the edge between z and k.\n        if (k->fixed) continue;\n\n\n        changed = false;\n        if(z->dist + z_k_dist < k->dist) {\n          k->dist = z->dist + z_k_dist;\n          changed = true;\n          if (k->dist < min->dist) min = k;\n        }\n        if (--k->pred == 0 || k->dist <= (min->dist + k->min_in_weight)) {         \n          k->fixed = true;\n          k->fixed_ts = high_resolution_clock::now();\n          r_set.push_back(k);\n        } else if (changed) {\n          pushWrap(heap,k->node,k->dist);\n        }\n      }\n\n      if (r_set.empty() && !min->fixed && cmp(min->dist, heap.top().dist)){\n        // We're done, but before we break, let's just check whether we have the new min in the q set\n        // That is, if the heap is not empty and the current min is higher than the min in the q\n        // set no point in pushing back to the heap, where it would have to bubble up.\n        min->fixed = true;\n        min->fixed_ts = high_resolution_clock::now();\n        r_set.push_back(min);\n      }\n    }\n  }\n}\n\ntemplate<typename GNode,\n         typename Graph,\n         typename Container,\n         typename R>\ninline int push_back_edges_of_node(const GNode& node,\n                                   Graph& graph,\n                                   Container& c,\n                                   const R& edgeRange) {\n  int edges_pushed = 0;\n  for (auto& edge : edgeRange(node)) {\n    c.push_back(std::make_pair(node, *edge));\n    edges_pushed++;\n  }\n  return edges_pushed;\n}\n\ntemplate <typename GType,\n          typename T,\n          typename P,\n          typename R,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename GEdge = typename GType::Graph::edge_iterator::value_type,\n          typename GNodeData = typename GType::Graph::node_data_type,\n          typename Traits = typename GType::Traits>\nvoid parSP1VerticesAlgo(Graph& graph,\n                        const GNode& source,\n                        const P& pushWrap,\n                        const R& edgeRange) {\n\n  using Heap = galois::ThreadSafeMinHeap<T>;\n  using WorkItem = T;\n  using PSchunk = galois::worklists::PerSocketChunkFIFO<CHUNK_SIZE>;\n  using Dist = typename Traits::Dist;\n\n  constexpr galois::MethodFlag flag = galois::MethodFlag::UNPROTECTED;\n\n  Heap heap;\n  std::atomic<uint32_t> last_heap_pop_dist(0);\n  std::atomic<int> r_set_counter(1);\n  std::mutex mutex;\n  auto& source_data = graph.getData(source);\n  source_data.fixed = true;\n  source_data.fixed_ts = high_resolution_clock::now();\n\n  galois::for_each(galois::iterate({T{source, 0}}),\n                   [&](WorkItem z_item, auto& ctx) {\n\n                     const auto& z_data = graph.getData(z_item.src, flag);\n                     //std::cout << \"Processing node \" << z_data.node << std::endl;\n\n                     for (auto& z_edge : edgeRange(z_item.src)) {\n                       auto k = graph.getEdgeDst(z_edge);\n                       auto& k_data = graph.getData(k, flag);\n\n                       //std::cout << \"Processing edge \" << *z_edge << \" from \" << z_item.src << \" to dst : \" << k_data.node << \" Current dist: \" << k_dist << \" New dist: \" << new_dist << std::endl;\n                       if (k_data.fixed) continue;\n\n                       auto z_k_dist = graph.getEdgeData(z_edge, flag);\n                       auto new_dist = z_data.dist + z_k_dist;\n                       unsigned int k_dist = k_data.dist;;\n                       bool changed = false;\n\n                       \n                       while (new_dist < k_dist) {\n                         //std::cout << \"Trying to relax to \" << new_dist << std::endl;\n                         if (k_data.dist.compare_exchange_weak(k_dist, new_dist, std::memory_order_relaxed)) {\n                           changed = true;\n                           break;\n                         }\n                         k_dist = k_data.dist;\n                         new_dist = z_data.dist + z_k_dist;                         \n                       }                      \n\n                       // If the k vertex is now fixed, push the edges to the r set, otherwise push k\n                       // to the heap.\n                       if (--k_data.pred == 0) {\n                         k_data.fixed = true;\n                         k_data.fixed_ts = high_resolution_clock::now();                         \n                         //std::cout << \"Fixed \" << k_data.node << \" to \" << k_data.dist << \" at: \" << duration_cast<microseconds>(k_data.fixed_ts - start).count() << std::endl;\n                         //std::cout << \"SP1 cond \" << k_data.pred << \" SP2 cond\" << (last_heap_pop_dist.load() + k_data.min_in_weight) << std::endl;\n                         pushWrap(ctx, k, k_data.dist);\n                         ++r_set_counter;\n                       } else if (changed){\n                         pushWrap(heap, k, k_data.dist);\n                       }\n                     }\n\n                     \n                     if (--r_set_counter == 0) {\n\n                       uint32_t min_dist = 0;\n                       uint32_t items_pushed = 0;\n                       while(!heap.empty()) {\n                         auto j = heap.top();\n                         auto& j_data = graph.getData(j.src, flag);\n\n                         if (j_data.fixed || j_data.dist < j.dist) {\n                           heap.pop();\n                           if (r_set_counter.load() > 0) break;\n                           continue;\n                         }\n\n                         heap.pop();\n                         last_heap_pop_dist = (unsigned int)j_data.dist;\n                         min_dist = j_data.dist;\n                         j_data.fixed = true;\n\t\t\t j_data.fixed_ts = high_resolution_clock::now();\n                         ++r_set_counter;\n                         pushWrap(ctx, j.src, j.dist);\n                         items_pushed++;\n\n                         if (!(UNLIKELY(!heap.empty()) && heap.top().dist == min_dist)) break;\n                       }\n                     }\n                   },\n                   galois::wl<PSchunk>(),\n                   galois::no_conflicts(),\n                   galois::loopname(\"sssp_parsp2_inner\"));\n}\n\ntemplate <typename GType,\n          typename T,\n          typename P,\n          typename R,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename GEdge = typename GType::Graph::edge_iterator::value_type,\n          typename GNodeData = typename GType::Graph::node_data_type,\n          typename Traits = typename GType::Traits>\nvoid parSP2VerticesAlgo(Graph& graph,\n                        const GNode& source,\n                        const P& pushWrap,\n                        const R& edgeRange) {\n\n  using Heap = galois::ThreadSafeMinHeap<T>;\n  using WorkItem = T;\n  using PSchunk = galois::worklists::PerSocketChunkFIFO<CHUNK_SIZE>;\n  using Dist = typename Traits::Dist;\n\n  constexpr galois::MethodFlag flag = galois::MethodFlag::UNPROTECTED;\n\n  Heap heap;\n  std::atomic<uint32_t> min_dist(0);\n  std::atomic<int> r_set_counter(1);\n  std::mutex mutex;\n  auto& source_data = graph.getData(source);\n  source_data.fixed = true;\n  source_data.fixed_ts = high_resolution_clock::now();\n\n  galois::for_each(galois::iterate({T{source, 0}}),\n                   [&](WorkItem z_item, auto& ctx) {\n\n                     const auto& z_data = graph.getData(z_item.src, flag);\n                     //std::cout << \"Processing node \" << z_data.node << std::endl;\n\n                     for (auto& z_edge : edgeRange(z_item.src)) {\n                       auto k = graph.getEdgeDst(z_edge);\n                       auto& k_data = graph.getData(k, flag);\n\n                       //std::cout << \"Processing edge \" << *z_edge << \" from \" << z_item.src << \" to dst : \" << k_data.node << \" Current dist: \" << k_dist << \" New dist: \" << new_dist << std::endl;\n                       if (k_data.fixed) continue;\n\n                       auto z_k_dist = graph.getEdgeData(z_edge, flag);\n                       auto new_dist = z_data.dist + z_k_dist;\n                       unsigned int k_dist = k_data.dist;;\n                       bool changed = false;\n                       \n                       while (new_dist < k_dist) {\n                         //std::cout << \"Trying to relax to \" << new_dist << std::endl;\n                         if (k_data.dist.compare_exchange_weak(k_dist, new_dist, std::memory_order_relaxed)) {\n                           changed = true;\n                           break;\n                         }\n                         k_dist = k_data.dist;\n                         new_dist = z_data.dist + z_k_dist;                         \n                       }                      \n\n                       // If the k vertex is now fixed, push the edges to the r set, otherwise push k\n                       // to the heap.\n                       --k_data.pred;\n                       if (k_dist <= min_dist + k_data.min_in_weight || k_data.pred <= 0) {\n                         k_data.fixed = true;\n                         k_data.fixed_ts = high_resolution_clock::now();                         \n                         //std::cout << \"Fixed \" << k_data.node << \" to \" << k_data.dist << \" at: \" << duration_cast<microseconds>(k_data.fixed_ts - start).count() << std::endl;\n                         //std::cout << \"SP1 cond \" << k_data.pred << \" SP2 cond\" << (last_heap_pop_dist.load() + k_data.min_in_weight) << std::endl;\n                         ++r_set_counter;\n                         pushWrap(ctx, k, k_data.dist);\n                       } else if (changed){\n                         pushWrap(heap, k, k_data.dist);\n                       }\n                     }\n\n                     \n                     if (--r_set_counter == 0) {\n                       while(!heap.empty()) {\n                         auto j = heap.top();\n                         auto& j_data = graph.getData(j.src, flag);\n                         heap.pop();\n                         if (j_data.fixed || j_data.dist < j.dist) {\n                           if (r_set_counter.load() > 0) break;\n                           continue;\n                         }\n\n                         min_dist = (unsigned int)j_data.dist;\n                         j_data.fixed = true;\n\t\t\t j_data.fixed_ts = high_resolution_clock::now();\n                         ++r_set_counter;\n                         pushWrap(ctx, j.src, j.dist);\n\n                         if (heap.empty() || heap.top().dist != min_dist) break;\n                       }\n                     }\n                   },\n                   galois::wl<PSchunk>(),\n                   galois::no_conflicts(),\n                   galois::loopname(\"sssp_parsp2_inner\"));\n}\n\ntemplate <typename GType,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename Traits = typename GType::Traits>\nvoid topoAlgo(Graph& graph, const GNode& source) {\n  using SSSP                 = typename Traits::SSSP;\n  using Dist                 = typename Traits::Dist;\n\n  galois::LargeArray<Dist> oldDist;\n  oldDist.allocateInterleaved(graph.size());\n\n  constexpr Dist INFTY = SSSP::DIST_INFINITY;\n  galois::do_all(galois::iterate(0ul, graph.size()),\n                 [&](size_t i) { oldDist.constructAt(i, INFTY); },\n                 galois::no_stats(), galois::loopname(\"initDistArray\"));\n\n  graph.getData(source).dist = 0;\n\n  galois::GReduceLogicalOR changed;\n  size_t rounds = 0;\n\n  do {\n\n    ++rounds;\n    changed.reset();\n\n    galois::do_all(galois::iterate(graph),\n                   [&](const GNode& n) {\n                     const auto& sdata = graph.getData(n);\n\n                     if (oldDist[n] > sdata.dist) {\n\n                       oldDist[n] = sdata.dist;\n                       changed.update(true);\n\n                       for (auto e : graph.edges(n)) {\n                         const auto newDist = sdata.dist + graph.getEdgeData(e);\n                         auto dst           = graph.getEdgeDst(e);\n                         auto& ddata        = graph.getData(dst);\n                         galois::atomicMin(ddata.dist, newDist);\n                       }\n                     }\n                   },\n                   galois::steal(), galois::loopname(\"Update\"));\n\n  } while (changed.reduce());\n\n  galois::runtime::reportStat_Single(\"SSSP-topo\", \"rounds\", rounds);\n}\n\ntemplate <typename GType,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename Traits = typename GType::Traits>\nvoid topoTileAlgo(Graph& graph, const GNode& source) {\n\n  using SSSP                 = typename Traits::SSSP;\n  using SrcEdgeTile          = typename Traits::SrcEdgeTile;\n  using SrcEdgeTileMaker     = typename Traits::SrcEdgeTileMaker;\n\n  galois::InsertBag<SrcEdgeTile> tiles;\n\n  graph.getData(source).dist = 0;\n\n  galois::do_all(galois::iterate(graph),\n                 [&](const GNode& n) {\n                   SSSP::pushEdgeTiles(\n                       tiles, graph, n,\n                       SrcEdgeTileMaker{n, SSSP::DIST_INFINITY});\n                 },\n                 galois::steal(), galois::loopname(\"MakeTiles\"));\n\n  galois::GReduceLogicalOR changed;\n  size_t rounds = 0;\n\n  do {\n    ++rounds;\n    changed.reset();\n\n    galois::do_all(galois::iterate(tiles),\n                   [&](SrcEdgeTile& t) {\n                     const auto& sdata = graph.getData(t.src);\n\n                     if (t.dist > sdata.dist) {\n\n                       t.dist = sdata.dist;\n                       changed.update(true);\n\n                       for (auto e = t.beg; e != t.end; ++e) {\n                         const auto newDist = sdata.dist + graph.getEdgeData(e);\n                         auto dst           = graph.getEdgeDst(e);\n                         auto& ddata        = graph.getData(dst);\n                         galois::atomicMin(ddata.dist, newDist);\n                       }\n                     }\n                   },\n                   galois::steal(), galois::loopname(\"Update\"));\n\n  } while (changed.reduce());\n\n  galois::runtime::reportStat_Single(\"SSSP-topo\", \"rounds\", rounds);\n}\n\ntemplate <typename GType,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode>\nvoid reset_graph(Graph& graph, GNode& source){\n\n  using SSSP = typename GType::Traits::SSSP;\n\n  galois::do_all(galois::iterate(graph),\n                 [&graph](GNode n) {\n                   auto& data = graph.getData(n);\n                   data.dist = SSSP::DIST_INFINITY;\n\t\t   data.pred = total_pred[data.node];\n\t\t   data.fixed = false;\n                 });\n\n  graph.getData(source).dist = 0;\n}\n\ntemplate <typename GType,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename Traits = typename GType::Traits>\nvoid init_graph(Graph& graph, GNode& source, GNode& report) {\n\n  using SSSP = typename Traits::SSSP;\n  using Dist = typename Traits::Dist;\n  std::cout << \"Reading from file: \" << filename << std::endl;\n  galois::graphs::readGraph(graph, filename);\n  std::cout << \"Read \" << graph.size() << \" nodes, \" << graph.sizeEdges()\n            << \" edges\" << std::endl;\n\n  if (startNode >= graph.size() || reportNode >= graph.size()) {\n    std::cerr << \"failed to set report: \" << reportNode\n              << \" or failed to set source: \" << startNode << \"\\n\";\n    assert(0);\n    abort();\n  }\n\n  auto it = graph.begin();\n  std::advance(it, startNode);\n  source = *it;\n  it     = graph.begin();\n  std::advance(it, reportNode);\n  report = *it;\n\n  size_t approxNodeData = graph.size() * 64;\n  // size_t approxEdgeData = graph.sizeEdges() * sizeof(typename\n  // Graph::edge_data_type) * 2;\n  galois::preAlloc(numThreads +\n                   approxNodeData / galois::runtime::pagePoolSize());\n  galois::reportPageAlloc(\"MeminfoPre\");\n\n  if (algo == deltaStep || algo == deltaTile || algo == serDelta ||\n      algo == serDeltaTile) {\n    std::cout << \"INFO: Using delta-step of \" << (1 << stepShift) << \"\\n\";\n    std::cout\n        << \"WARNING: Performance varies considerably due to delta parameter.\\n\";\n    std::cout\n        << \"WARNING: Do not expect the default to be good for your graph.\\n\";\n  }\n\n   auto edgeRange = typename GType::Traits::OutEdgeRangeFn{graph};\n\n   struct edgeComp {\n     bool operator()( const Dist& lhs, const Dist& rhs ) const {\n       return lhs < rhs;      \n     }\n   };\n\n  galois::do_all(galois::iterate(graph),\n                 [&](GNode n) {\n                   auto& data = graph.getData(n);\n                   data.dist = SSSP::DIST_INFINITY;\n                   data.min_in_weight = SSSP::DIST_INFINITY;\n                   data.node = n;\n                   //graph.sortEdgesByEdgeData(n, edgeComp());\n                   //                   for (auto& e : edgeRange(n)) {\n                   //  std::cout << \"Node: \" << n << \" Edge: \" << *e << \" dist: \" << graph.getEdgeData(e) << std::endl;\n                   //}\n                 });\n\n  graph.getData(source).dist = 0;\n  total_pred.resize(graph.size());\n}\n\nstruct MatchPathSeparator {\n  bool operator()( char ch ) const {\n    return ch == '/';\n  }\n};\n\nstd::string basename( std::string const& pathname ) {\n    return std::string(\n        std::find_if( pathname.rbegin(), pathname.rend(),\n                      MatchPathSeparator() ).base(),\n        pathname.end() );\n}\n\nstd::string removeExtension( std::string const& filename ) {\n    std::string::const_reverse_iterator\n                        pivot\n            = std::find( filename.rbegin(), filename.rend(), '.' );\n    return pivot == filename.rend()\n        ? filename\n        : std::string( filename.begin(), pivot.base() - 1 );\n}\n\ntemplate <typename GType,\n          typename Graph = typename GType::Graph,\n          typename GNode = typename GType::GNode,\n          typename Traits = typename GType::Traits>\nvoid verify_and_report(Graph& graph, GNode& source, GNode& report, unsigned long exec_time) {\n  galois::reportPageAlloc(\"MeminfoPost\");\n\n  std::cout << \"Node \" << reportNode << \" has distance \"\n            << graph.getData(report).dist << \"\\n\";\n\n  if (!skipVerify) {\n    if (Traits::SSSP::verify(graph, source)) {\n      std::cout << \"Verification successful.\\n\";\n    } else {\n      GALOIS_DIE(\"Verification failed\");\n    }\n  }\n\n  acc::accumulator_set<double, acc::stats<acc::tag::count,\n                                          acc::tag::mean,\n                                          acc::tag::variance,\n                                          acc::tag::max,\n                                          acc::tag::min,\n                                          acc::tag::median>> stats;\n\n  for (auto& node : graph) {\n    auto& node_data = graph.getData(node);\n    if (node_data.fixed) stats(duration_cast<microseconds>(node_data.fixed_ts - start).count());\n  }\n\n  auto count =  acc::count(stats);\n  auto mean =  acc::mean(stats);\n  auto median = acc::median(stats);\n  auto max =  acc::max(stats);\n  auto min = acc::min(stats);\n  auto variance =  acc::variance(stats);\n\n  std::cout << std::setprecision(16)\n            << \"count:    \" << count    << '\\n'\n            << \"mean:     \" << mean     << '\\n'\n            << \"median:   \" << median   << '\\n'\n            << \"max:      \" << max      << '\\n' \n            << \"min:      \" << min      << '\\n'\n            << \"variance: \" << variance << '\\n';\n\n    //Auxiliary code for stat collection to CSV file\n  std::string resultfile_name = \"results.csv\";\n  std::string graph_name = removeExtension(basename(filename));\n  std::ifstream in_data_stream(resultfile_name);\n  bool print_header = false;\n  if(in_data_stream.peek() == std::ifstream::traits_type::eof())\n    print_header = true;\n  in_data_stream.close();\n  std::ofstream data_stream;\n  data_stream.open(resultfile_name, std::ofstream::out | std::ofstream::app);\n  if(print_header)\n    data_stream << \"Algo;Graph_name;Main_time;Count;Mean;Median;max;min;variance;\";\n  data_stream << std::endl << ALGO_NAMES[algo] << ';' << graph_name << ';' << exec_time << ';' << count << ';' << mean << ';' << median << ';' << max << ';' << min << ';' << variance; \n  data_stream.close();\n\n}\n\nint main(int argc, char** argv) {\n  using ParGType = GraphType<GraphTypes::ParGraphType>;\n  using SerGType = GraphType<GraphTypes::SerGraphType>;\n\n  galois::SharedMemSys G;\n  LonestarStart(argc, argv, name, desc, url);\n\n  //skipVerify = true;\n  std::cout << \"Running \" << ALGO_NAMES[algo] << \" algorithm\" << std::endl;\n  galois::StatTimer Tinit;\n  galois::StatTimer Tmain;\n  unsigned long Init_Time, Main_Time;\n\n  switch (algo) {\n    case deltaTile: {\n      ParGType::Graph graph;\n      ParGType::GNode source, report;\n      init_graph<ParGType>(graph, source, report);\n      auto edgeRange = ParGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n      \n      Tmain.start();\n      deltaStepAlgo<ParGType, ParGType::Traits::SrcEdgeTile>(\n          graph, source,\n          ParGType::Traits::SrcEdgeTilePushWrap{graph},\n          ParGType::Traits::TileRangeFn());\n      Tmain.stop();\n\n      verify_and_report<ParGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case deltaStep: {\n      ParGType::Graph graph;\n      ParGType::GNode source, report;\n      init_graph<ParGType>(graph, source, report);\n      auto edgeRange = ParGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      deltaStepAlgo<ParGType, ParGType::Traits::UpdateRequest>(\n          graph, source,\n          ParGType::Traits::ReqPushWrap(),\n          ParGType::Traits::OutEdgeRangeFn{graph});\n      Tmain.stop();\n\n      verify_and_report<ParGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case serDeltaTile: {\n      SerGType::Graph graph;\n      SerGType::GNode source, report;\n      init_graph<SerGType>(graph, source, report);\n      auto edgeRange = SerGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n      \n      Tmain.start();\n      serDeltaAlgo<SerGType, SerGType::Traits::SrcEdgeTile>(\n          graph, source,\n          SerGType::Traits::SrcEdgeTilePushWrap{graph},\n          SerGType::Traits::TileRangeFn());\n      Tmain.stop();\n\n      verify_and_report<SerGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case serDelta: {\n      SerGType::Graph graph;\n      SerGType::GNode source, report;\n      init_graph<SerGType>(graph, source, report);\n      auto edgeRange = SerGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n      \n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      serDeltaAlgo<SerGType, SerGType::Traits::UpdateRequest>(\n          graph, source,\n          SerGType::Traits::ReqPushWrap(),\n          SerGType::Traits::OutEdgeRangeFn{graph});\n      Tmain.stop();\n\n      verify_and_report<SerGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case dijkstraTile: {\n      SerGType::Graph graph;\n      SerGType::GNode source, report;\n      init_graph<SerGType>(graph, source, report);\n      auto edgeRange = SerGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      dijkstraAlgo<SerGType, SerGType::Traits::SrcEdgeTile>(\n          graph, source,\n          SerGType::Traits::SrcEdgeTilePushWrap{graph},\n          SerGType::Traits::TileRangeFn());\n      Tmain.stop();\n\n      verify_and_report<SerGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case dijkstra: {\n      SerGType::Graph graph;\n      SerGType::GNode source, report;\n      init_graph<SerGType>(graph, source, report);\n      auto edgeRange = SerGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      dijkstraAlgo<SerGType, SerGType::Traits::UpdateRequest>(\n          graph, source,\n          SerGType::Traits::ReqPushWrap(),\n          SerGType::Traits::OutEdgeRangeFn{graph});\n      Tmain.stop();\n\n      verify_and_report<SerGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case topo: {\n      ParGType::Graph graph;\n      ParGType::GNode source, report;\n      init_graph<ParGType>(graph, source, report);\n      auto edgeRange = ParGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      topoAlgo<ParGType>(graph, source);\n      Tmain.stop();\n\n      verify_and_report<ParGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case topoTile: {\n      ParGType::Graph graph;\n      ParGType::GNode source, report;\n      init_graph<ParGType>(graph, source, report);\n      auto edgeRange = ParGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      topoTileAlgo<ParGType>(graph, source);\n      Tmain.stop();\n\n      verify_and_report<ParGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case serSP1: {\n      SerGType::Graph graph;\n      SerGType::GNode source, report;\n      init_graph<SerGType>(graph, source, report);\n      auto edgeRange = SerGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      serSP1Algo<SerGType, SerGType::Traits::UpdateRequest>(\n          graph, source,\n          SerGType::Traits::ReqPushWrap(),\n          edgeRange);\n      Tmain.stop();\n\n      verify_and_report<SerGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case serSP2: {\n      SerGType::Graph graph;\n      SerGType::GNode source, report;\n      init_graph<SerGType>(graph, source, report);\n      auto edgeRange = SerGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();\n\n      Tmain.start();\n      serSP2Algo<SerGType, SerGType::Traits::UpdateRequest>(\n          graph, source,\n          SerGType::Traits::ReqPushWrap(),\n          edgeRange);\n      Tmain.stop();\n\n      verify_and_report<SerGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case parSP1: {\n      ParGType::Graph graph;\n      ParGType::GNode source, report;\n      init_graph<ParGType>(graph, source, report);\n      auto edgeRange = ParGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();      \n      \n      Tmain.start();\n      parSP1VerticesAlgo<ParGType, ParGType::Traits::UpdateRequest>(\n          graph, source,\n          ParGType::Traits::ReqPushWrap(),\n          edgeRange);\n      Tmain.stop();\n\n      verify_and_report<ParGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    case parSP2: {\n      ParGType::Graph graph;\n      ParGType::GNode source, report;\n      init_graph<ParGType>(graph, source, report);\n      auto edgeRange = ParGType::Traits::OutEdgeRangeFn{graph};\n      calc_graph_predecessors(graph, edgeRange);\n\n      start = high_resolution_clock::now();      \n\n      Tmain.start();\n      parSP2VerticesAlgo<ParGType, ParGType::Traits::UpdateRequest>(\n          graph, source,\n          ParGType::Traits::ReqPushWrap(),\n          edgeRange);\n      Tmain.stop();\n\n      //skipVerify = true;\n      verify_and_report<ParGType>(graph, source, report, Tmain.get());\n      break;\n    }\n    default:\n      std::abort();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "18fc51379cff10f901526bb54f91f5e0dc4b98f5", "size": 48678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/sssp/SSSP.cpp", "max_stars_repo_name": "dralves/sp1-sp2-galois", "max_stars_repo_head_hexsha": "1597f1f510cc1aa75f5595f0d42f5701dfc34a91", "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/sssp/SSSP.cpp", "max_issues_repo_name": "dralves/sp1-sp2-galois", "max_issues_repo_head_hexsha": "1597f1f510cc1aa75f5595f0d42f5701dfc34a91", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/sssp/SSSP.cpp", "max_forks_repo_name": "dralves/sp1-sp2-galois", "max_forks_repo_head_hexsha": "1597f1f510cc1aa75f5595f0d42f5701dfc34a91", "max_forks_repo_licenses": ["BSD-3-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.5234042553, "max_line_length": 198, "alphanum_fraction": 0.5594519085, "num_tokens": 11813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.055823144668888804, "lm_q1q2_score": 0.018099838855050426}}
{"text": "// \n//  This file is part of the FFEA simulation package\n//  \n//  Copyright (c) by the Theory and Development FFEA teams,\n//  as they appear in the README.md file. \n// \n//  FFEA 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//  FFEA 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 FFEA.  If not, see <http://www.gnu.org/licenses/>.\n// \n//  To help us fund FFEA development, we humbly ask that you cite \n//  the research papers on the package.\n//\n\n#include <cstring>\n#include <iostream>\n#include \"dimensions.h\"\n#include \"mat_vec_types.h\"\n#include \"mat_vec_fns_II.h\"\n#include \"FFEA_return_codes.h\"\n#include \"BlobLite.h\"\n#include \"VolumeIntersection.h\"\n#include <Eigen/Geometry>\n\n\nint skipnlines(FILE *iFile, int n);\nFILE *set_up_trajfile(const char *traj_filename);\nvoid storeCoordsEigen(BlobLite &blob, Eigen::MatrixXd &coords); \ndouble getRotationAngle(Eigen::MatrixXd &m1, Eigen::MatrixXd &m2); \n\nFILE *set_up_trajfile(const char *traj_filename){\n  \n   FILE *trj; \n   char c;\n   if ((trj = fopen(traj_filename, \"r\")) == NULL) {\n      cout << \"Failed to open: \" << traj_filename << endl; \n      return NULL; \n   }\n \n   while(c != '*') {\n     c = fgetc(trj);\n   }  \n\n   skipnlines(trj, 2); \n\n   return trj;\n\n}\n\nint skipnlines(FILE *iFile, int n) {\n\n   int i=0;\n   char *ignore;\n   int len_crap = 256;\n   char crap[len_crap];\n   for (i=0; i<n; i++){\n     ignore = fgets(crap, len_crap, iFile);\n     //printf(\"crap: %s\", crap); \n   }\n   return 0;\n\n}\n\nvoid storeCoordsEigen(BlobLite &blob, Eigen::MatrixXd &coords){ \n    \n   for (int i=0; i<blob.num_nodes; i++){\n      coords(0,i) = blob.coord[3*i  ];\n      coords(1,i) = blob.coord[3*i+1];\n      coords(2,i) = blob.coord[3*i+2];\n   }\n \n}\n\ndouble getRotationAngle(Eigen::MatrixXd &m1, Eigen::MatrixXd &m2) {\n\n   Eigen::Matrix<double,4,4> t = Eigen::umeyama(m1,m2); \n   Eigen::Matrix<double,3,3> r = t.block<3,3>(0,0);\n   Eigen::AngleAxisd t_angleAxis(r);\n\n   return t_angleAxis.angle(); \n}\n \n\nint main(int argc, char** argv) { \n \n   // usage:\n   // ./find_intersections scale1 nodes_file1 topology_file1 scale2 nodes_file2 topology_file2 traj_file num_steps\n   cout << \"argc = \" << argc << endl;\n   for(int i = 0; i < argc; i++)\n      cout << \"argv[\" << i << \"] = \" << argv[i] << endl;\n\n   int num_steps = atoi(argv[8]);\n \n   // initialise the blobs:\n   BlobLite b1, b2;\n   b1.load_nodes(argv[2], atof(argv[1])); \n   b1.load_topology(argv[3]); \n   b2.load_nodes(argv[5], atof(argv[4]));\n   b2.load_topology(argv[6]); \n\n   // initialise the bouncing condition:\n   bool bouncing = false;\n  \n   // initialise two arrays with the starting coordinates:\n   Eigen::MatrixXd b1_ini(3,b1.num_nodes), b1_end(3,b1.num_nodes); \n   Eigen::MatrixXd b2_ini(3,b2.num_nodes), b2_end(3,b2.num_nodes); \n   // and the corresponding tolerance:\n   scalar tol = 3; // degrees\n   \n\n   // initialise the trajectory file:\n   FILE *trj = set_up_trajfile(argv[7]);\n   if (trj == NULL) return 1;\n\n   int checks = 0;\n   int i_vol = 0;\n   int i_cms = 0;\n   arr3 cm1, cm2, aux; \n   scalar d0 = 1000; \n   scalar d = 10*d0;\n   // for every time step:\n   for (int t=0; t<num_steps; t++) {\n     // load the coordinates of this time step:\n     if (b1.read_nodes_from_file(trj)) break; \n     skipnlines(trj,1);\n     if (b2.read_nodes_from_file(trj)) break; \n     skipnlines(trj,6);\n\n     // 1st Check - Nodes only move on the x axis.\n     // we store these coordinates because the system has to be put into box.\n     if (t == 0) {\n       storeCoordsEigen(b1, b1_ini);\n       storeCoordsEigen(b2, b2_ini);\n     } else if (t == num_steps - 2) { \n       storeCoordsEigen(b1, b1_end);\n       storeCoordsEigen(b2, b2_end);\n     }\n   \n     // 2nd Check - Eventually the CMs change direction: \n     b1.center_of_coord(cm1);\n     b2.center_of_coord(cm2);\n     d = arr3arr3Distance<scalar,arr3>(cm2, cm1);\n     if (d >= d0) bouncing = true;  \n     d0 = d;\n\n     // 3rd Check - Calculate if there is any tetrahedra intersecting:\n     checks = 0;\n     i_vol = 0; \n     scalar tet1[4][3], tet2[4][3];\n     for (int i=0; i<b1.num_elements; i++){ \n       // set up tetrahedron 1:\n       for (int nn = 0; nn<4; nn++) {\n         for (int nc = 0; nc<3; nc++) {\n           tet1[nn][nc] = b1.coord[ b1.elem[ i*NUM_NODES_QUADRATIC_TET + nn ]*3 + nc ];\n         }\n       }\n       for (int j=0; j<b2.num_elements; j++){\n         // set up tetrahedron 2:\n         for (int nn = 0; nn<4; nn++) {\n           for (int nc = 0; nc<3; nc++) {\n             tet2[nn][nc] = b2.coord[ b2.elem[ j*NUM_NODES_QUADRATIC_TET + nn ]*3 + nc ];\n           }\n         }\n         checks += 1;\n         if (volumeIntersection<scalar,arr3>(tet1, tet2, false, aux)){\n           // cout << \" ivol \" << endl;\n           i_vol += 1;\n         }\n       }   // elements in b2 \n     }     // elements in b1\n   }       // num_steps\n   fclose(trj);\n\n   cout << \"There were vol:\" << i_vol << \" in \" << checks << \" checkings\" << endl; \n   if (( ((float) i_vol) / checks ) > 0.00500 ) {\n     cout << \" There were too many intersections: \" << (( (float) i_vol) / checks ) << endl; \n     return 1;\n   } \n\n   if (!bouncing) {\n     cout << \" The blobs did not bounce back: the trajectory could be too short, or the steric repulsion not taken into account\" << endl; \n     return 1; \n   } else cout << \" The blobs did bounce back \" << endl; \n  \n\n   // check the rotation angle:\n   double b1_angle = getRotationAngle(b1_ini, b1_end); \n   double b2_angle = getRotationAngle(b2_ini, b2_end); \n   if (b1_angle > tol) {\n     cout << \" Blob 1 ended up with a too large rotation: \" << b1_angle << endl; \n     return 1;\n   } \n   if (b2_angle > tol) {\n     cout << \" Blob 2 ended up with a too large rotation: \" << b2_angle << endl; \n     return 1;\n   } \n\n   cout << \"b1 suffered a rotation of angle: \" << b1_angle << endl;\n   cout << \"b2 suffered a rotation of angle: \" << b2_angle << endl;\n   \n\n   return 0; \n\n} \n\n\n \n     // scalar *tet3[4], tet4[4][3];\n         // tet3[nn] = &b1.coord[ b1.elem[ i*NUM_NODES_QUADRATIC_TET + nn ]*3];\n       /*for (int nn = 0; nn<4; nn++) {\n         cout << \"tet1: n\" << nn << \": \" << tet1[nn][0] << \" \" << tet1[nn][1] << \" \" << tet1[nn][2] << endl; \n         cout << \"tet3: n\" << nn << \": \" << tet3[nn][0] << \" \" << tet3[nn][1] << \" \" << tet3[nn][2] << endl; \n       }*/\n", "meta": {"hexsha": "b19c0fc1ec4f71d65236dd36ca1ac0ab7f6db38d", "size": 6713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/physics/squidgy_steric/checkSquidgySpheres.cpp", "max_stars_repo_name": "zzalscv2/FFEA", "max_stars_repo_head_hexsha": "da8a09dadb1b3978a3d230dc79d9b163d7889242", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/physics/squidgy_steric/checkSquidgySpheres.cpp", "max_issues_repo_name": "zzalscv2/FFEA", "max_issues_repo_head_hexsha": "da8a09dadb1b3978a3d230dc79d9b163d7889242", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/physics/squidgy_steric/checkSquidgySpheres.cpp", "max_forks_repo_name": "zzalscv2/FFEA", "max_forks_repo_head_hexsha": "da8a09dadb1b3978a3d230dc79d9b163d7889242", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-03T16:08:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T16:08:21.000Z", "avg_line_length": 30.1031390135, "max_line_length": 138, "alphanum_fraction": 0.5906450171, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.05033063188523923, "lm_q1q2_score": 0.018087024502806765}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2018 Sylko Olzscher\n *\n */\n\n#include <smf/sml/scaler.h>\n#include <boost/assert.hpp>\n\nnamespace node\n{\n\tnamespace sml\n\t{\n\t\tstd::string scale_value(std::int64_t value, std::int8_t scaler)\n\t\t{\n\t\t\t//\tWorking with a string operation prevents us of losing precision.\n\t\t\tstd::string str_value = std::to_string(value);\n\n\t\t\t//\ttreat 0 as special value\n\t\t\tif (value == 0)\treturn str_value;\n\n\t\t\t//\tshould at least contain a \"0\"\n\t\t\tBOOST_ASSERT_MSG(!str_value.empty(), \"no number\");\n\t\t\tif (str_value.empty())\treturn \"0.0\";\t//\temergency exit\n\n\t\t\tif (scaler < 0)\n\t\t\t{\n\n\t\t\t\t//\tnegative\n\t\t\t\twhile ((std::size_t)std::abs(scaler - 1) > str_value.size())\n\t\t\t\t{\n\t\t\t\t\t//\tpad missing zeros\n\t\t\t\t\tstr_value.insert(0, \"0\");\n\t\t\t\t}\n\n\t\t\t\t//\tfinish\n\t\t\t\tif (str_value.size() > (std::size_t)std::abs(scaler))\n\t\t\t\t{\n\t\t\t\t\tconst std::size_t pos = str_value.size() + scaler;\n\t\t\t\t\tstr_value.insert(pos, \".\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//\tsimulating: result = value * pow10(scaler)\n\t\t\t\twhile (scaler-- > 0)\n\t\t\t\t{\n\t\t\t\t\t//\tappend missing zeros\n\t\t\t\t\tstr_value.append(\"0\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn str_value;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "20519af9e32cb74f24b57867917beeda251b2803", "size": 1125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/sml/protocol/src/scaler.cpp", "max_stars_repo_name": "solosTec/node", "max_stars_repo_head_hexsha": "e35e127867a4f66129477b780cbd09c5231fc7da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T12:40:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-06T06:20:19.000Z", "max_issues_repo_path": "lib/sml/protocol/src/scaler.cpp", "max_issues_repo_name": "solosTec/node", "max_issues_repo_head_hexsha": "e35e127867a4f66129477b780cbd09c5231fc7da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-01-14T20:38:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T09:52:07.000Z", "max_forks_repo_path": "lib/sml/protocol/src/scaler.cpp", "max_forks_repo_name": "solosTec/node", "max_forks_repo_head_hexsha": "e35e127867a4f66129477b780cbd09c5231fc7da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-09T09:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-03T12:40:30.000Z", "avg_line_length": 19.3965517241, "max_line_length": 70, "alphanum_fraction": 0.5955555556, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.03789242269107747, "lm_q1q2_score": 0.018058757584071015}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_PARTITION_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_PARTITION_HPP\r\n\r\n#include <vector>\r\n#include <boost/geometry/algorithms/assign.hpp>\r\n#include <boost/range/algorithm/copy.hpp>\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\nnamespace detail { namespace partition\r\n{\r\n\r\ntypedef std::vector<std::size_t> index_vector_type;\r\n\r\ntemplate <int Dimension, typename Box>\r\ninline void divide_box(Box const& box, Box& lower_box, Box& upper_box)\r\n{\r\n    typedef typename coordinate_type<Box>::type ctype;\r\n\r\n    // Divide input box into two parts, e.g. left/right\r\n    ctype two = 2;\r\n    ctype mid = (geometry::get<min_corner, Dimension>(box)\r\n            + geometry::get<max_corner, Dimension>(box)) / two;\r\n\r\n    lower_box = box;\r\n    upper_box = box;\r\n    geometry::set<max_corner, Dimension>(lower_box, mid);\r\n    geometry::set<min_corner, Dimension>(upper_box, mid);\r\n}\r\n\r\n// Divide collection into three subsets: lower, upper and oversized (not-fitting)\r\n// (lower == left or bottom, upper == right or top)\r\ntemplate <typename OverlapsPolicy, typename InputCollection, typename Box>\r\nstatic inline void divide_into_subsets(Box const& lower_box, Box const& upper_box,\r\n        InputCollection const& collection,\r\n        index_vector_type const& input,\r\n        index_vector_type& lower,\r\n        index_vector_type& upper,\r\n        index_vector_type& exceeding)\r\n{\r\n    typedef boost::range_iterator<index_vector_type const>::type index_iterator_type;\r\n\r\n    for(index_iterator_type it = boost::begin(input);\r\n        it != boost::end(input);\r\n        ++it)\r\n    {\r\n        bool const lower_overlapping = OverlapsPolicy::apply(lower_box, collection[*it]);\r\n        bool const upper_overlapping = OverlapsPolicy::apply(upper_box, collection[*it]);\r\n\r\n        if (lower_overlapping && upper_overlapping)\r\n        {\r\n            exceeding.push_back(*it);\r\n        }\r\n        else if (lower_overlapping)\r\n        {\r\n            lower.push_back(*it);\r\n        }\r\n        else if (upper_overlapping)\r\n        {\r\n            upper.push_back(*it);\r\n        }\r\n        else\r\n        {\r\n            // Is nowhere! Should not occur!\r\n            BOOST_ASSERT(true);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n// Match collection with itself\r\ntemplate <typename InputCollection, typename Policy>\r\nstatic inline void handle_one(InputCollection const& collection,\r\n        index_vector_type const& input,\r\n        Policy& policy)\r\n{\r\n    typedef boost::range_iterator<index_vector_type const>::type index_iterator_type;\r\n    // Quadratic behaviour at lowest level (lowest quad, or all exceeding)\r\n    for(index_iterator_type it1 = boost::begin(input); it1 != boost::end(input); ++it1)\r\n    {\r\n        index_iterator_type it2 = it1;\r\n        for(++it2; it2 != boost::end(input); ++it2)\r\n        {\r\n            policy.apply(collection[*it1], collection[*it2]);\r\n        }\r\n    }\r\n}\r\n\r\n// Match collection 1 with collection 2\r\ntemplate <typename InputCollection, typename Policy>\r\nstatic inline void handle_two(\r\n        InputCollection const& collection1, index_vector_type const& input1,\r\n        InputCollection const& collection2, index_vector_type const& input2,\r\n        Policy& policy)\r\n{\r\n    typedef boost::range_iterator<index_vector_type const>::type index_iterator_type;\r\n    for(index_iterator_type it1 = boost::begin(input1); it1 != boost::end(input1); ++it1)\r\n    {\r\n        for(index_iterator_type it2 = boost::begin(input2); it2 != boost::end(input2); ++it2)\r\n        {\r\n            policy.apply(collection1[*it1], collection2[*it2]);\r\n        }\r\n    }\r\n}\r\n\r\n\r\ntemplate\r\n<\r\n    int Dimension,\r\n    typename Box,\r\n    typename OverlapsPolicy,\r\n    typename VisitBoxPolicy\r\n>\r\nclass partition_one_collection\r\n{\r\n    typedef std::vector<std::size_t> index_vector_type;\r\n    typedef typename coordinate_type<Box>::type ctype;\r\n    typedef partition_one_collection\r\n            <\r\n                1 - Dimension,\r\n                Box,\r\n                OverlapsPolicy,\r\n                VisitBoxPolicy\r\n            > sub_divide;\r\n\r\n    template <typename InputCollection, typename Policy>\r\n    static inline void next_level(Box const& box,\r\n            InputCollection const& collection,\r\n            index_vector_type const& input,\r\n            int level, int min_elements,\r\n            Policy& policy, VisitBoxPolicy& box_policy)\r\n    {\r\n        if (boost::size(input) > 0)\r\n        {\r\n            if (boost::size(input) > min_elements && level < 100)\r\n            {\r\n                sub_divide::apply(box, collection, input, level + 1, min_elements, policy, box_policy);\r\n            }\r\n            else\r\n            {\r\n                handle_one(collection, input, policy);\r\n            }\r\n        }\r\n    }\r\n\r\npublic :\r\n    template <typename InputCollection, typename Policy>\r\n    static inline void apply(Box const& box,\r\n            InputCollection const& collection,\r\n            index_vector_type const& input,\r\n            int level,\r\n            int min_elements,\r\n            Policy& policy, VisitBoxPolicy& box_policy)\r\n    {\r\n        box_policy.apply(box, level);\r\n\r\n        Box lower_box, upper_box;\r\n        divide_box<Dimension>(box, lower_box, upper_box);\r\n\r\n        index_vector_type lower, upper, exceeding;\r\n        divide_into_subsets<OverlapsPolicy>(lower_box, upper_box, collection, input, lower, upper, exceeding);\r\n\r\n        if (boost::size(exceeding) > 0)\r\n        {\r\n            // All what is not fitting a partition should be combined\r\n            // with each other, and with all which is fitting.\r\n            handle_one(collection, exceeding, policy);\r\n            handle_two(collection, exceeding, collection, lower, policy);\r\n            handle_two(collection, exceeding, collection, upper, policy);\r\n        }\r\n\r\n        // Recursively call operation both parts\r\n        next_level(lower_box, collection, lower, level, min_elements, policy, box_policy);\r\n        next_level(upper_box, collection, upper, level, min_elements, policy, box_policy);\r\n    }\r\n};\r\n\r\n\r\ntemplate\r\n<\r\n    int Dimension,\r\n    typename Box,\r\n    typename OverlapsPolicy,\r\n    typename VisitBoxPolicy\r\n>\r\nclass partition_two_collections\r\n{\r\n    typedef std::vector<std::size_t> index_vector_type;\r\n    typedef typename coordinate_type<Box>::type ctype;\r\n    typedef partition_two_collections\r\n            <\r\n                1 - Dimension,\r\n                Box,\r\n                OverlapsPolicy,\r\n                VisitBoxPolicy\r\n            > sub_divide;\r\n\r\n    template <typename InputCollection, typename Policy>\r\n    static inline void next_level(Box const& box,\r\n            InputCollection const& collection1, index_vector_type const& input1,\r\n            InputCollection const& collection2, index_vector_type const& input2,\r\n            int level, int min_elements,\r\n            Policy& policy, VisitBoxPolicy& box_policy)\r\n    {\r\n        if (boost::size(input1) > 0 && boost::size(input2) > 0)\r\n        {\r\n            if (boost::size(input1) > min_elements\r\n                && boost::size(input2) > min_elements\r\n                && level < 100)\r\n            {\r\n                sub_divide::apply(box, collection1, input1, collection2, input2, level + 1, min_elements, policy, box_policy);\r\n            }\r\n            else\r\n            {\r\n                box_policy.apply(box, level + 1);\r\n                handle_two(collection1, input1, collection2, input2, policy);\r\n            }\r\n        }\r\n    }\r\n\r\npublic :\r\n    template <typename InputCollection, typename Policy>\r\n    static inline void apply(Box const& box,\r\n            InputCollection const& collection1, index_vector_type const& input1,\r\n            InputCollection const& collection2, index_vector_type const& input2,\r\n            int level,\r\n            int min_elements,\r\n            Policy& policy, VisitBoxPolicy& box_policy)\r\n    {\r\n        box_policy.apply(box, level);\r\n\r\n        Box lower_box, upper_box;\r\n        divide_box<Dimension>(box, lower_box, upper_box);\r\n\r\n        index_vector_type lower1, upper1, exceeding1;\r\n        index_vector_type lower2, upper2, exceeding2;\r\n        divide_into_subsets<OverlapsPolicy>(lower_box, upper_box, collection1, input1, lower1, upper1, exceeding1);\r\n        divide_into_subsets<OverlapsPolicy>(lower_box, upper_box, collection2, input2, lower2, upper2, exceeding2);\r\n\r\n        if (boost::size(exceeding1) > 0)\r\n        {\r\n            // All exceeding from 1 with 2:\r\n            handle_two(collection1, exceeding1, collection2, exceeding2, policy);\r\n\r\n            // All exceeding from 1 with lower and upper of 2:\r\n            handle_two(collection1, exceeding1, collection2, lower2, policy);\r\n            handle_two(collection1, exceeding1, collection2, upper2, policy);\r\n        }\r\n        if (boost::size(exceeding2) > 0)\r\n        {\r\n            // All exceeding from 2 with lower and upper of 1:\r\n            handle_two(collection1, lower1, collection2, exceeding2, policy);\r\n            handle_two(collection1, upper1, collection2, exceeding2, policy);\r\n        }\r\n\r\n        next_level(lower_box, collection1, lower1, collection2, lower2, level, min_elements, policy, box_policy);\r\n        next_level(upper_box, collection1, upper1, collection2, upper2, level, min_elements, policy, box_policy);\r\n    }\r\n};\r\n\r\n\r\n\r\n}} // namespace detail::partition\r\n\r\nstruct visit_no_policy\r\n{\r\n    template <typename Box>\r\n    static inline void apply(Box const&, int )\r\n    {}\r\n};\r\n\r\n\r\ntemplate\r\n<\r\n    typename Box,\r\n    typename ExpandPolicy,\r\n    typename OverlapsPolicy,\r\n    typename VisitBoxPolicy = visit_no_policy\r\n>\r\nclass partition\r\n{\r\n    typedef std::vector<std::size_t> index_vector_type;\r\n\r\n    template <typename InputCollection>\r\n    static inline void expand_to_collection(InputCollection const& collection, Box& total, index_vector_type& index_vector)\r\n    {\r\n        std::size_t index = 0;\r\n        for(typename boost::range_iterator<InputCollection const>::type it\r\n            = boost::begin(collection);\r\n            it != boost::end(collection);\r\n            ++it, ++index)\r\n        {\r\n            ExpandPolicy::apply(total, *it);\r\n            index_vector.push_back(index);\r\n        }\r\n    }\r\n\r\n\r\npublic :\r\n    template <typename InputCollection, typename VisitPolicy>\r\n    static inline void apply(InputCollection const& collection,\r\n            VisitPolicy& visitor,\r\n            int min_elements = 16,\r\n            VisitBoxPolicy box_visitor = visit_no_policy()\r\n            )\r\n    {\r\n        if (boost::size(collection) > min_elements)\r\n        {\r\n            index_vector_type index_vector;\r\n            Box total;\r\n            assign_inverse(total);\r\n            expand_to_collection(collection, total, index_vector);\r\n\r\n            detail::partition::partition_one_collection\r\n                <\r\n                    0, Box,\r\n                    OverlapsPolicy,\r\n                    VisitBoxPolicy\r\n                >::apply(total, collection, index_vector, 0, min_elements, visitor, box_visitor);\r\n        }\r\n        else\r\n        {\r\n            typedef typename boost::range_iterator<InputCollection const>::type iterator_type;\r\n            for(iterator_type it1 = boost::begin(collection); it1 != boost::end(collection); ++it1)\r\n            {\r\n                iterator_type it2 = it1;\r\n                for(++it2; it2 != boost::end(collection); ++it2)\r\n                {\r\n                    visitor.apply(*it1, *it2);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    template <typename InputCollection, typename VisitPolicy>\r\n    static inline void apply(InputCollection const& collection1,\r\n                InputCollection const& collection2,\r\n                VisitPolicy& visitor,\r\n                int min_elements = 16,\r\n                VisitBoxPolicy box_visitor = visit_no_policy()\r\n                )\r\n    {\r\n        if (boost::size(collection1) > min_elements && boost::size(collection2) > min_elements)\r\n        {\r\n            index_vector_type index_vector1, index_vector2;\r\n            Box total;\r\n            assign_inverse(total);\r\n            expand_to_collection(collection1, total, index_vector1);\r\n            expand_to_collection(collection2, total, index_vector2);\r\n\r\n            detail::partition::partition_two_collections\r\n                <\r\n                    0, Box, OverlapsPolicy, VisitBoxPolicy\r\n                >::apply(total,\r\n                    collection1, index_vector1,\r\n                    collection2, index_vector2,\r\n                    0, min_elements, visitor, box_visitor);\r\n        }\r\n        else\r\n        {\r\n            typedef typename boost::range_iterator<InputCollection const>::type iterator_type;\r\n            for(iterator_type it1 = boost::begin(collection1); it1 != boost::end(collection1); ++it1)\r\n            {\r\n                for(iterator_type it2 = boost::begin(collection2); it2 != boost::end(collection2); ++it2)\r\n                {\r\n                    visitor.apply(*it1, *it2);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n};\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RING_IDENTIFIER_HPP\r\n", "meta": {"hexsha": "eb8accc3bcedb79e5f2d341f54f166c699247e36", "size": 13447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependencies/boost_geometry/boost/geometry/algorithms/detail/partition.hpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-30T18:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T18:41:39.000Z", "max_issues_repo_path": "dependencies/boost_geometry/boost/geometry/algorithms/detail/partition.hpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dependencies/boost_geometry/boost/geometry/algorithms/detail/partition.hpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4794871795, "max_line_length": 127, "alphanum_fraction": 0.6060831412, "num_tokens": 2806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.038466194911822287, "lm_q1q2_score": 0.018032591616640396}}
{"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 AMIRAMESHREADER_HH\n#define AMIRAMESHREADER_HH\n\n#include <algorithm>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n#include <cassert>\n#include <stdexcept>\n\n#include <boost/timer/timer.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <dune/common/fvector.hh>\n\n#include <amiramesh/AmiraMesh.h>\n#include \"fem/lagrangespace.hh\"\n#include \"io/ioTools.hh\"\n#include \"io/vtk.hh\"\n\n// forward declaration\ntemplate <> class std::complex<float>;\n\nnamespace Kaskade\n{\n  /// Reader for Amira meshes.\n  /**\n   * Note that the Amira mesh file must be in ASCII format. Currently UG and ALUSimplex grids are supported.\n   *\n   */\n  namespace AmiraMeshReader\n  {\n    namespace ImplementationDetails{\n\n      /**\n       * \\cond internals\n       */\n      template <class value_type> struct TypeId{};\n\n      template <> struct TypeId<unsigned char>        { static int const id = HxBYTE; };\n      template <> struct TypeId<int>                  { static int const id = HxINT32; };\n      template <> struct TypeId<float>                { static int const id = HxFLOAT; };\n      template <> struct TypeId<double>               { static int const id = HxDOUBLE; };\n      template <> struct TypeId<std::complex<float> > { static int const id = HxCOMPLEX; };\n      /**\n       * \\endcond\n       */\n\n\n      std::string exceptionMessage(std::string const& function, std::string const& gridfile, int line)\n      {\n        return std::string(\"In AmiraMeshReader::\") + function + \", line \" + boost::lexical_cast<std::string>(line) + \": Error reading \" + gridfile + \"\\n\";\n      }\n\n      std::string exceptionMessage(std::string const& function, std::string const& location, std::string const& component, int line)\n      {\n        return std::string(\"In AmiraMeshReader::\") + function + \", line \" + boost::lexical_cast<std::string>(line)  + std::string(\": Error reading \") + component + \" of \" + location + \"\\n\";\n      }\n\n\n      template <class value_type, int components>\n      void extractData(AmiraMesh::Data* dataObj, std::vector<Dune::FieldVector<value_type,components> >& data)\n      {\n        size_t const n= dataObj->location()->nNodes();\n        std::cout << n << \" entries...\";\n        data.clear();\n        data.reserve(n);\n        data.insert(data.begin(),n,Dune::FieldVector<value_type,components>(0));\n\n        value_type const* dataPtr = static_cast<value_type const*>(dataObj->dataPtr());\n        for (size_t i=0; i<n; ++i)\n          for (int j=0; j<components; ++j)\n            data[i][j] = dataPtr[i*components+j];\n\n      }\n\n      template <class value_type, int components>\n      bool readData(AmiraMesh& am, char const* location, char const* name, std::vector<Dune::FieldVector<value_type,components> >& data)\n      {\n        std::string pname=name;\n        std::cout << \"trying to read \" << pname << \" of \" << location << \": \" << std::flush;\n        int const id = ImplementationDetails::TypeId<value_type>::id;\n        AmiraMesh::Data* dataObj = am.findData(location,id,components,name);\n        if (!dataObj){\n          std::cout << \"empty.\" << std::endl << std::flush;\n          return false;\n        }\n\n        extractData(dataObj,data);\n        std::cout << \"done.\" << std::endl << std::flush;\n        return true;\n      }\n\n\n    } // End of ImplementationDetails\n\n\n    /// function reading an Amira mesh file in ASCII format.\n    /**\n     * This function reads vertices, tetrahedra and, if defined, boundary triangles\n     * of an Amira mesh file into a grid and returns this grid.\n     *\n     * \\param Scalar scalar type of the vertex coordinates\n     * \\param gridfile the name of the Amira mesh file\n     * \\param initialGridSize optional parameter for reserving memory for the grid\n     * \\return pointer on the created grid\n     */\n    template<class Grid, class Scalar>\n    std::unique_ptr<Grid> readGrid(std::string const& gridfile, int initialGridSize = 0, bool measureTime = false){\n      int const dim = Grid::dimension;\n      std::vector<Dune::FieldVector<Scalar,dim> >    vertices;\n      std::vector<Dune::FieldVector<int,dim+1> >     cells;\n      std::vector<Dune::FieldVector<int,dim> >       boundary;\n\n      // open grid file.\n      std::cout << \"Reading amira mesh\\n\";\n      std::cout << \"opening \" << gridfile << '\\n';\n      AmiraMesh* am = AmiraMesh::read(gridfile.c_str());\n      if(!am){\n        std::string const mes = ImplementationDetails::exceptionMessage(\"readGrid(std::string const&, int)\", gridfile, __LINE__);\n        throw std::runtime_error(mes);\n      }\n\n\n      // read vertices\n      bool exists = ImplementationDetails::readData(*am,\"Nodes\",\"Coordinates\",vertices);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readGrid(std::string const&, int)\", \"Nodes\", \"Coordinates\", __LINE__));\n      }\n      // read cells\n      std::string cellName;\n      if(dim == 2) cellName = \"Triangles\";\n      if(dim == 3) cellName = \"Tetrahedra\";\n      if(dim != 2 && dim != 3){\n        delete(am);\n        throw std::runtime_error(\"Sorry!\\nOnly 2D and 3D grids are supported.\");\n      }\n      exists = ImplementationDetails::readData(*am,cellName.c_str(),\"Nodes\",cells);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readGrid(std::string const&, int)\", cellName, \"Nodes\", __LINE__));\n      }\n      // read boundary segments if defined\n      bool boundaryExists = ImplementationDetails::readData(*am,\"BoundaryTriangles\",\"Nodes\",boundary);\n\n      // close grid file\n      delete(am);\n\n      // We use start indices 0. Amira uses 1. Correct indices.\n      for (size_t i=0; i<cells.size(); ++i) {\n        for (int j=0; j<dim+1; ++j) {\n          cells[i][j] -= 1;\n          if (cells[i][j]>=vertices.size()){\n            std::string message = std::string(\"In \") + __FILE__ + \" line \" + boost::lexical_cast<std::string>(__LINE__) + \": cell node \" + boost::lexical_cast<std::string>(i) + \"[\" + boost::lexical_cast<std::string>(j) + \"]=\" + boost::lexical_cast<std::string>(cells[i][j]) + \" exceeds vertex numbers!\\n\";\n            throw std::runtime_error(message);\n          }\n        }\n      }\n\n      if(boundaryExists)\n        for (size_t i=0; i<boundary.size(); ++i)\n          for (int j=0; j<dim; ++j)\n            boundary[i][j] -= 1;\n\n\n      // Create grid.\n      std::cout << std::endl;\n      std::cout << \"preparing grid creation\\n\";\n\n      Dune::GridFactory<Grid> factory = IOTools::FactoryGenerator<dim,Grid>::createFactory(initialGridSize);\n      std::cout << \"inserting vertices...\";\n      for (size_t i=0; i<vertices.size(); ++i) {\n        Dune::FieldVector<double,dim> pos;\n        for(int j=0; j<dim; ++j)\n          pos[j] = (double)vertices[i][j];\n        factory.insertVertex(pos);\n      }\n      std::cout << \"done.\" << std::endl;\n\n      if(boundaryExists){\n        std::cout << \"inserting boundary segments...\";\n        for(size_t i=0; i<boundary.size(); ++i){\n          std::vector<unsigned int> tmp(dim);\n          for(size_t j=0; j<dim; ++j){\n            assert(boundary[i][j]>=0 && boundary[i][j]<vertices.size());\n            tmp[j] = boundary[i][j];\n          }\n          factory.insertBoundarySegment(tmp);\n        }\n        std::cout << \"done.\" << std::endl;\n      }\n\n      std::cout << \"inserting elements...\";\n      for (size_t i=0; i<cells.size(); ++i) {\n        std::vector<unsigned int> tmp(dim+1);\n        for (int j=0; j<dim+1; ++j) {\n          assert(cells[i][j]>=0 && cells[i][j]<vertices.size());\n          tmp[j] = cells[i][j];\n        }\n        factory.insertElement(Dune::GeometryType(Dune::GeometryType::simplex,dim),tmp);\n      }\n      std::cout << \"done.\" << std::endl;\n\n      boost::timer::cpu_timer timer;\n      std::unique_ptr<Grid> result(factory.createGrid());\n      std::cout << \"grid creation finished in \" << boost::timer::format(timer.elapsed()) << std::endl;\n      std::cout << std::endl;\n\n      return result;\n    }\n\n\n    /// function reading an Amira mesh file in ASCII format.\n    /**\n     * This function reads vertices, tetrahedra and, if defined, boundary triangles\n     * of an Amira mesh file into a grid and returns this grid.\n     *\n     * \\param Scalar scalar type of the vertex coordinates\n     * \\param gridfile the name of the Amira mesh file\n     * \\param initialGridSize optional parameter for reserving memory for the grid\n     * \\return pointer on the created grid\n     */\n    template<class Grid, class Scalar>\n    std::unique_ptr<Grid> readGrid(std::string const& gridfile, std::vector<int>& boundaryIds, int initialGridSize = 0){\n      int const dim = Grid::dimension;\n      std::vector<Dune::FieldVector<Scalar,dim> >    vertices;\n      std::vector<Dune::FieldVector<int,dim+1> >     cells;\n      std::vector<Dune::FieldVector<int,dim> >       boundary;\n\n      // open grid file.\n      std::cout << \"Reading amira mesh\\n\";\n      std::cout << \"opening \" << gridfile << '\\n';\n      AmiraMesh* am = AmiraMesh::read(gridfile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readGrid(std::string const&, std::vector<int>&, int)\", gridfile, __LINE__));\n\n      // read vertices\n      bool exists = ImplementationDetails::readData(*am,\"Nodes\",\"Coordinates\",vertices);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readGrid(std::string const&, std::vector<int>&, int)\", \"Nodes\", \"Coordinates\", __LINE__));\n      }\n      // read cells\n      std::string cellName;\n      if(dim == 2) cellName = \"Triangles\";\n      if(dim == 3) cellName = \"Tetrahedra\";\n      if(dim != 2 && dim != 3){\n        delete(am);\n        throw std::runtime_error(\"Sorry!\\nOnly 2D and 3D grids are supported.\");\n      }\n      exists = ImplementationDetails::readData(*am,cellName.c_str(),\"Nodes\",cells);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readGrid(std::string const&, std::vector<int>&, int)\", cellName, \"Nodes\", __LINE__));\n      }\n      // read boundary segments if defined\n      exists = ImplementationDetails::readData(*am,\"BoundaryTriangles\",\"Nodes\",boundary);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readGrid(std::string const&, std::vector<int>&, int)\", \"BoundaryTriangles\", \"Nodes\", __LINE__));\n      }\n\n      typedef std::vector<Dune::FieldVector<unsigned char, 1> > TmpIdVector;\n      TmpIdVector boundaryID;\n      ImplementationDetails::readData(*am,\"BoundaryTriangles\",\"Id\",boundaryID);\n\n      // close grid file\n      delete(am);\n\n      // We use start indices 0. Amira uses 1. Correct indices.\n      for (size_t i=0; i<cells.size(); ++i) {\n        for (int j=0; j<dim+1; ++j) {\n          cells[i][j] -= 1;\n          if (cells[i][j]>=vertices.size()){\n            std::string message = std::string(\"In \") + __FILE__ + \" line \" + boost::lexical_cast<std::string>(__LINE__) + \": cell node \" + boost::lexical_cast<std::string>(i) + \"[\" + boost::lexical_cast<std::string>(j) + \"]=\" + boost::lexical_cast<std::string>(cells[i][j]) + \" exceeds vertex numbers!\\n\";\n            throw std::runtime_error(message);\n          }\n        }\n      }\n\n      for (size_t i=0; i<boundary.size(); ++i)\n        for (int j=0; j<dim; ++j)\n          boundary[i][j] -= 1;\n\n\n      // Create grid.\n      std::cout << std::endl;\n      std::cout << \"preparing grid creation\\n\";\n\n      Dune::GridFactory<Grid> factory = IOTools::FactoryGenerator<dim,Grid>::createFactory(initialGridSize);\n      std::cout << \"inserting vertices...\";\n      for (size_t i=0; i<vertices.size(); ++i) {\n        Dune::FieldVector<double,dim> pos;\n        for(int j=0; j<dim; ++j)\n          pos[j] = (double)vertices[i][j];\n        factory.insertVertex(pos);\n      }\n      std::cout << \"done.\" << std::endl;\n\n      std::cout << \"inserting boundary segments...\";\n      for(size_t i=0; i<boundary.size(); ++i){\n        std::vector<unsigned int> tmp(dim);\n        for(size_t j=0; j<dim; ++j){\n          assert(boundary[i][j]>=0 && boundary[i][j]<vertices.size());\n          tmp[j] = boundary[i][j];\n        }\n        factory.insertBoundarySegment(tmp);\n      }\n      std::cout << \"done.\" << std::endl;\n\n      std::cout << \"inserting elements...\";\n      for (size_t i=0; i<cells.size(); ++i) {\n        std::vector<unsigned int> tmp(dim+1);\n        for (int j=0; j<dim+1; ++j) {\n          assert(cells[i][j]>=0 && cells[i][j]<vertices.size());\n          tmp[j] = cells[i][j];\n        }\n        factory.insertElement(Dune::GeometryType(Dune::GeometryType::simplex,dim),tmp);\n      }\n      std::cout << \"done.\" << std::endl;\n\n      boost::timer::cpu_timer timer;\n      std::unique_ptr<Grid> grid(factory.createGrid());\n      std::cout << \"grid creation finished in \" << boost::timer::format(timer.elapsed()) << std::endl;\n\n      // get boundary segment indices\n      std::cout << \"sorting boundary ids...\";\n      IOTools::BoundarySegmentIndexWrapper<dim, Grid>::readBoundarySegmentIndices(*grid, factory, vertices, boundary, boundaryID, boundaryIds);\n      std::cout << \"done.\" << std::endl;\n\n      return grid;\n    }\n\n    /// function reading additional data from an Amira mesh file in ASCII format.\n    /**\n     * \\param Scalar scalar type of the data in the Amira mesh file\n     * \\param FunctionSpaceElement type of FE-Function to store the additional data in\n     * \\param datafile the name of the Amira mesh file containing additional data\n     * \\param dataname the name of the data in the Amira mesh file\n     * \\param componentname the name of the data's components in the Amira mesh file\n     * \\param data fe-function object for storing the additional data\n     */\n    template<class Scalar, class FunctionSpaceElement>\n    void readData(std::string const& datafile, std::string const& dataname, std::string const& componentname, FunctionSpaceElement &data){\n      constexpr int numberOfComponents = FunctionSpaceElement::StorageValueType::dimension;\n      // FunctionSpaceElement::StorageValueType in general uses floating point precision.\n      // Thus, in order to read integer values or characters, the DataVector is defined manually.\n      // When reading the information into the function space element the data is\n      // casted to the desired type.\n      typedef std::vector<Dune::FieldVector<Scalar, numberOfComponents> > DataVector;\n      DataVector dataVector;\n\n      // open data file\n      std::cout << std::endl;\n      std::cout << \"Reading additional data\" << std::endl;\n      std::cout << \"opening \" << datafile << std::endl;\n      AmiraMesh* am = AmiraMesh::read(datafile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readData(std::string const&, std::string const&, std::string const&, FunctionSpaceElement&)\", datafile, __LINE__));\n\n\n      bool exists = ImplementationDetails::readData(*am, dataname.c_str(), componentname.c_str(), dataVector);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error( ImplementationDetails::exceptionMessage(\"readData(std::string const&, std::string const&, std::string const&, FunctionSpaceElement&)\", dataname, componentname, __LINE__) );\n      }\n\n      // close data file\n      delete(am);\n\n      std::cout << \"number of entries: \" << dataVector.size() << std::endl;\n      std::cout << \"number of components: \" << numberOfComponents << std::endl;\n      std::cout << \"data object: \" << data.coefficients().size() << \"x\" << data.coefficients()[0].size() << std::endl;\n\n      // reading prescribed data into function space element\n      for(size_t i=0; i<dataVector.size(); ++i)\n        for(size_t j=0; j<numberOfComponents; ++j)\n          data.coefficients()[i][j] = (typename FunctionSpaceElement::Scalar) dataVector[i][j];\n\n    }\n\n    /// function reading additional data for each vertex from an Amira mesh file in ASCII format.\n    /**\n     * \\param Scalar scalar type of the data in the Amira mesh file\n     * \\param numberOfComponents number of components of each entry of the data\n     * \\param datafile the name of the Amira mesh file containing additional node data\n     * \\param dataname the name of the data in the Amira mesh file\n     * \\param componentname the name of the data's components in the Amira mesh file\n     * \\param data vector containing the data\n     */\n    template<class Scalar, int numberOfComponents>\n    void readData(std::string const& datafile, std::string const& dataname, std::string const& componentname,\n        std::vector<Dune::FieldVector<Scalar,numberOfComponents> > &data){\n      // open data file\n      std::cout << std::endl;\n      std::cout << \"Reading additional vertex data\" << std::endl;\n      std::cout << \"opening \" << datafile << std::endl;\n      AmiraMesh* am = AmiraMesh::read(datafile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readData(std::string const&, std::string const&, std::string const&, std::vector<Dune::FieldVector>&)\", datafile, __LINE__));\n\n      bool exists = ImplementationDetails::readData(*am, dataname.c_str(), componentname.c_str(), data);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readData(std::string const&, std::string const&, std::string const&, std::vector<Dune::FieldVector>&)\", dataname, componentname, __LINE__));\n      }\n\n      // close data file\n      delete(am);\n    }\n\n    /// function reading return a FE-function describing the deformation.\n    /**\n     * Function reading a deformed and an undeformed geometry from Amira mesh files\n     * in ASCII format. These geometries must possess the same number of nodes. For each\n     * vertex the difference between the geometries is calculated. This difference is stored\n     * into the FE-function at index 0 of the variable set data.\n     *\n     * \\param datafile the name of the Amira mesh file containing the deformed geometry\n     * \\param gridfile the name of the Amira mesh file containing the undeformed geometry\n     * \\param data fe-function object for storing the deformation of type VariableSet::VariableSet\n     */\n    template <class VarSetDesc>\n    void readDeformationIntoVariableSetRepresentation(std::string const& gridfile, std::string const& datafile, \n\t\t\t\t\t\t      typename VarSetDesc::VariableSet& data){\n      using namespace boost::fusion;\n      int const numberOfComponents = result_of::at_c<typename VarSetDesc::VariableSet::Functions, 0>::type::Components;\n      typedef std::vector<Dune::FieldVector<float,numberOfComponents> > DataVector;\n      std::vector<Dune::FieldVector<float,numberOfComponents> > vertices;\n      DataVector nodeData;\n\n      // open grid file.\n      std::cout << \"Reading undeformed geometry\\n\";\n      std::cout << \"opening \" << gridfile << '\\n';\n      AmiraMesh* am = AmiraMesh::read(gridfile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformationIntoVariableSetRepresentation(std::string const&, std::string const&,  VariableSet::VariableSet&)\", gridfile, __LINE__));\n\n      // read vertices\n      bool exists = ImplementationDetails::readData(*am,\"Nodes\",\"Coordinates\",vertices);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformationIntoVariableSetRepresentation(std::string const&, std::string const&,  VariableSet::VariableSet&)\",\"Nodes\",\"Coordinates\",__LINE__));\n      }\n\n      // close grid file\n      delete(am);\n\n      // open data file\n      std::cout << std::endl;\n      std::cout << \"Reading deformed geometry\" << std::endl;\n      std::cout << \"opening \" << datafile << std::endl;\n      am = AmiraMesh::read(datafile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformationIntoVariableSetRepresentation(std::string const&, std::string const&,  VariableSet::VariableSet&)\", datafile, __LINE__));\n\n      exists = ImplementationDetails::readData(*am,\"Nodes\",\"Coordinates\",nodeData);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(\"readDeformationIntoVariableSetRepresentation(std::string const&, std::string const&,  VariableSet::VariableSet&)\", \"Nodes\", \"Coordinates\", __LINE__);\n      }\n\n      // close data file\n      delete(am);\n\n      // check for correct sizes\n      assert(nodeData.size()==vertices.size());\n\n      // get deformation\n      for(size_t i=0; i<nodeData.size(); ++i)\n        nodeData[i]=nodeData[i]-vertices[i];\n\n      // reading prescribed data into function space\n      std::vector<double> tmpVec(nodeData.size()*numberOfComponents);\n      for(size_t i=0; i<nodeData.size(); ++i)\n        for(size_t j=0; j<numberOfComponents; ++j)\n          tmpVec[numberOfComponents*i+j] = (double)nodeData[i][j];\n\n      data.read(tmpVec.begin());\n    }\n\n    /// function reading return a fe-function describing the deformation.\n    /**\n     * Function reading a deformed and a undeformed geometry from Amira mesh files\n     * in ASCII format. These geometry must possess the same number of nodes. For each\n     * vertex the difference between the geometries is calculated. This difference is read\n     * into the fe-function object data.\n     *\n     * \\param datafile the name of the Amira mesh file containing the deformed geometry\n     * \\param gridfile the name of the Amira mesh file containing the undeformed geometry\n     * \\param data fe-function object for storing the deformation\n     */\n    template<class FunctionSpaceElement, class FileScalar=float>\n    void readDeformation(std::string const& gridfile, std::string const& datafile, FunctionSpaceElement &data) {\n      int const numberOfComponents = FunctionSpaceElement::Components;\n      typedef std::vector<Dune::FieldVector<FileScalar,numberOfComponents> > DataVector;\n      typedef typename FunctionSpaceElement::Scalar Scalar;\n      std::vector<Dune::FieldVector<FileScalar,numberOfComponents> > vertices;\n      DataVector nodeData;\n\n      // open grid file.\n      std::cout << \"Reading undeformed geometry\\n\";\n      std::cout << \"opening \" << gridfile << '\\n';\n      AmiraMesh* am = AmiraMesh::read(gridfile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformation(std::string const&, std::string const&, FunctionSpaceElement&)\", gridfile, __LINE__));\n\n      // read vertices\n      bool exists = ImplementationDetails::readData(*am,\"Nodes\",\"Coordinates\",vertices);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformation(std::string const&, std::string const&, FunctionSpaceElement&)\", \"Nodes\", \"Coordinates\", __LINE__));\n      }\n\n      // close grid file\n      delete(am);\n\n      // open data file\n      std::cout << std::endl;\n      std::cout << \"Reading deformed geometry\" << std::endl;\n      std::cout << \"opening \" << datafile << std::endl;\n      am = AmiraMesh::read(datafile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformation(std::string const&, std::string const&, FunctionSpaceElement&)\", datafile, __LINE__));\n\n      exists = ImplementationDetails::readData(*am,\"Nodes\",\"Coordinates\",nodeData);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformation(std::string const&, std::string const&, FunctionSpaceElement&)\", \"Nodes\", \"Coordinates\", __LINE__));\n      }\n\n      // close data file\n      delete(am);\n\n      // check for correct sizes\n      assert(nodeData.size()==vertices.size());\n\n      // get deformation\n      for(size_t i=0; i<nodeData.size(); ++i)\n        nodeData[i]=nodeData[i]-vertices[i];\n\n      // reading prescribed data into function space\n      std::vector<Scalar> tmpVec(nodeData.size()*numberOfComponents);\n      for(size_t i=0; i<nodeData.size(); ++i)\n        for(size_t j=0; j<FunctionSpaceElement::Components; ++j)\n          data.coefficients()[i][j] = (Scalar) nodeData[i][j];\n    }\n\n\n    template<class GridView, class FunctionSpaceElement, class FileScalar=float>\n    void readDeformation2(GridView const& gridView, std::string const& datafile, FunctionSpaceElement &data){\n      int const numberOfComponents = FunctionSpaceElement::Components;\n      typedef std::vector<Dune::FieldVector<FileScalar,numberOfComponents> > DataVector;\n      typedef typename FunctionSpaceElement::Scalar Scalar;\n      std::vector<Dune::FieldVector<FileScalar,numberOfComponents> > vertices;\n      DataVector nodeData;\n\n      // open data file\n      std::cout << \"Reading deformed geometry\" << std::endl;\n      std::cout << \"opening \" << datafile << std::endl;\n      AmiraMesh *am = AmiraMesh::read(datafile.c_str());\n      if(!am) throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformation(std::string const&, std::string const&, FunctionSpaceElement&)\", datafile, __LINE__));\n\n      bool exists = ImplementationDetails::readData(*am,\"Nodes\",\"Coordinates\",nodeData);\n      if(!exists){\n        delete(am);\n        throw std::runtime_error(ImplementationDetails::exceptionMessage(\"readDeformation(std::string const&, std::string const&, FunctionSpaceElement&)\", \"Nodes\", \"Coordinates\", __LINE__));\n      }\n\n      // close data file\n      delete(am);\n\n      // check for correct sizes\n      assert(nodeData.size()==vertices.size());\n\n      // get deformation\n      auto vIter = gridView.template begin<GridView::dimension>();\n      auto vend = gridView.template end<GridView::dimension>();\n      size_t i=0;\n      for(;vIter!=vend;++vIter)\n      {\n        nodeData[i] -= vIter->geometry().corner(0);\n        ++i;\n      }\n      //      for(size_t i=0; i<nodeData.size(); ++i)\n//        nodeData[i]=nodeData[i]-vertices[i];\n\n      // reading prescribed data into function space\n      std::vector<Scalar> tmpVec(nodeData.size()*numberOfComponents);\n      for(size_t i=0; i<nodeData.size(); ++i)\n        for(size_t j=0; j<FunctionSpaceElement::Components; ++j)\n          data.coefficients()[i][j] = (Scalar) nodeData[i][j];\n    }\n\n\n    /// Read boundary indices and save as scalar field in .vtu-file\n    /**\n     * \\param gridfile name of the Amira mesh file\n     * \\param savefilename name of the output file (optional), default: \"boundaryConditions.vtu\"\n     * \\param initialGridSize initial grid size in mb(only for UGGrid)\n     */\n    template <class Grid>\n    void boundaryConditionsToScalarField(std::string const& gridfile, std::string const& savefilename=std::string(\"boundaryConditions\"), int initialGridSize = 0) {\n\n      int const dim = Grid::dimension;\n      // read grid\n      typedef typename Grid::LeafGridView LeafView;\n      std::vector<int> boundaryIndices;\n      std::unique_ptr<Grid> grid = readGrid<Grid,float>(gridfile, boundaryIndices);\n      GridManager<Grid> gridManager(grid);\n\n      // create variable set\n      typedef FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> > Space;\n      Space space(gridManager, gridManager.grid().leafView(), 1);\n      typedef boost::fusion::vector<Space const*> Spaces;\n      Spaces spaces(&space);\n      typedef boost::fusion::vector< VariableDescription<0,1,0> > VariableDescriptions;\n      typedef VariableSetDescription<Spaces,VariableDescriptions> VarSetDesc;\n      std::string name[1] = { \"boundary ids\" };\n      VarSetDesc varSetDesc(spaces, name);\n      typename VarSetDesc::VariableSet indices(varSetDesc);\n\n      // read boundary indices\n      std::vector<Dune::FieldVector<int,dim> > boundaryVertices;\n\n      std::string const comp_name(\"BoundaryTriangles\");\n      std::string const node_name(\"Nodes\");\n\n      ImplementationDetails::readData<int,dim>(gridfile, comp_name, node_name, boundaryVertices);\n      std::vector<double> tmp(gridManager.grid().size(dim),0);\n      for(int i=0; i<boundaryIndices.size(); ++i){\n        tmp[boundaryVertices[i][0]-1] = boundaryIndices[i];\n        tmp[boundaryVertices[i][1]-1] = boundaryIndices[i];\n        tmp[boundaryVertices[i][2]-1] = boundaryIndices[i];\n      }\n      indices.read(tmp.begin());\n\n      // write file\n      IoOptions options;\n      options.outputType = IoOptions::ascii;\n      writeVTKFile(gridManager.grid().leafView(), varSetDesc, indices, savefilename,options);\n    }\n  }\n} // namespace Kaskade\n#endif\n", "meta": {"hexsha": "a3a15ba72d622b2658926925c6cd1ebb4de20e4c", "size": 29131, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/io/amirameshreader.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/io/amirameshreader.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/io/amirameshreader.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": 44.6110260337, "max_line_length": 305, "alphanum_fraction": 0.6314235694, "num_tokens": 7071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.05921024991122574, "lm_q1q2_score": 0.01800238355819694}}
{"text": "/* Greg Anderson\n *\n * Definition of a bounded powerset domain for some underlying domain in the\n * ELINA abstract interpretation library.\n */\n\n#include <zonotope.h>\n#include <elina_box_internal.h>\n\n#include <cstdlib>\n#include <iostream>\n#include <Eigen/Dense>\n#include <elina_box_internal.h>\n\n#include \"powerset.hpp\"\n\nAbstract0::Abstract0(elina_manager_t* m, elina_abstract0_t* a):\n  man{m}, value{a}, center_computed{false} {}\n\nAbstract0::Abstract0(const Abstract0& other):\n  man{other.man}, value{elina_abstract0_copy(other.man, other.value)},\n  center{other.center}, center_computed{other.center_computed} {}\n\nAbstract0::Abstract0(Abstract0&& other):\n  man{other.man}, value{other.value}, center{other.center},\n  center_computed{other.center_computed} {\n  other.value = nullptr;\n}\n\nAbstract0::~Abstract0() {\n  if (value != nullptr) {\n    elina_abstract0_free(man, value);\n  }\n}\n\nAbstract0& Abstract0::operator=(const Abstract0& other) {\n  this->man = other.man;\n  this->value = elina_abstract0_copy(other.man, other.value);\n  this->center = other.center;\n  this->center_computed = other.center_computed;\n  return *this;\n}\n\nAbstract0& Abstract0::operator=(Abstract0&& other) {\n  this->man = other.man;\n  this->value = other.value;\n  other.value = nullptr;\n  this->center = other.center;\n  this->center_computed = other.center_computed;\n  return *this;\n}\n\nEigen::VectorXd compute_center(elina_manager_t* man, elina_abstract0_t* abs) {\n  elina_interval_t** itv;\n  itv = elina_abstract0_to_box(man, abs);\n  int dims = elina_abstract0_dimension(man, abs).realdim;\n  Eigen::VectorXd center(dims);\n  for (int i = 0; i < dims; i++) {\n    double l, u;\n    elina_double_set_scalar(&l, itv[i]->inf, MPFR_RNDN);\n    elina_double_set_scalar(&u, itv[i]->sup, MPFR_RNDN);\n    center(i) = (l + u) / 2.0;\n  }\n  return center;\n}\n\nPowerset::Powerset(const Powerset& other) {\n  disjuncts = other.disjuncts;\n  size = other.size;\n}\n\nPowerset::Powerset(elina_manager_t* m, elina_abstract0_t* a, int s) {\n  size = s;\n  disjuncts = std::vector<std::shared_ptr<Abstract0>>();\n  disjuncts.push_back(std::make_shared<Abstract0>(m, a));\n}\n\nPowerset::Powerset(std::vector<std::shared_ptr<Abstract0>>& ds, int s) {\n  size = s;\n  disjuncts = ds;\n}\n\nPowerset::Powerset(std::vector<std::shared_ptr<Abstract0>>& ds,\n    std::vector<Eigen::VectorXd>& cs, int s) {\n  size = s;\n  disjuncts = std::vector<std::shared_ptr<Abstract0>>(ds);\n}\n\nPowerset Powerset::assign_linexpr_array(elina_dim_t* dims,\n    elina_linexpr0_t** update, unsigned int size, unsigned int s) const {\n  std::vector<std::shared_ptr<Abstract0>> ds;\n  for (std::shared_ptr<Abstract0> it : this->disjuncts) {\n    elina_abstract0_t* it_dim;\n    size_t num_dims = elina_abstract0_dimension(it->man, it->value).realdim;\n    if (s > num_dims) {\n      // If the output size is greater than the input size, then we need to\n      // add dimensions to the input abstract value.\n      elina_dimchange_t* dc = elina_dimchange_alloc(0, s - num_dims);\n      for (unsigned int i = 0; i < s - num_dims; i++) {\n        dc->dim[i] = num_dims;\n      }\n      it_dim = elina_abstract0_add_dimensions(it->man, false, it->value, dc, false);\n      elina_dimchange_free(dc);\n    } else {\n      it_dim = elina_abstract0_copy(it->man, it->value);\n    }\n\n    elina_abstract0_t* abs = elina_abstract0_assign_linexpr_array(\n        it->man, false, it_dim, dims, update, size, NULL);\n    elina_abstract0_free(it->man, it_dim);\n    bool bot = elina_abstract0_is_bottom(it->man, abs);\n    if (bot) {\n      // If this value is bottom we don't need to add it back to the powerset.\n      elina_abstract0_free(it->man, abs);\n      continue;\n    }\n\n    if (num_dims > s) {\n      // If the input size is greater than the output size, then we need to\n      // remove excess dimensions here.\n      elina_dimchange_t* dc = elina_dimchange_alloc(0, num_dims - s);\n      for (unsigned int i = 0; i < num_dims - s; i++) {\n        dc->dim[i] = s + i;\n      }\n      elina_abstract0_t* abs2 = elina_abstract0_remove_dimensions(it->man, false, abs, dc);\n      elina_abstract0_free(it->man, abs);\n      abs = abs2;\n      elina_dimchange_free(dc);\n    }\n\n    ds.push_back(std::make_shared<Abstract0>(it->man, abs));\n  }\n\n  return Powerset(ds, this->size);\n}\n\nPowerset Powerset::meet_lincons_array(elina_lincons0_array_t* cons) const {\n  std::vector<std::shared_ptr<Abstract0>> ds;\n  for (std::shared_ptr<Abstract0> it : this->disjuncts) {\n    elina_abstract0_t* abs = elina_abstract0_meet_lincons_array(\n        it->man, false, it->value, cons);\n    bool bot = elina_abstract0_is_bottom(it->man, abs);\n    // If this value is bottom it doesn't affect the powerset.\n    if (!bot) {\n      ds.push_back(std::make_shared<Abstract0>(it->man, abs));\n    } else {\n      elina_abstract0_free(it->man, abs);\n    }\n  }\n  return Powerset(ds, this->size);\n}\n\nPowerset Powerset::permute_dimensions(elina_dimperm_t* dp) const {\n  std::vector<std::shared_ptr<Abstract0>> ds;\n  for (std::shared_ptr<Abstract0> it : this->disjuncts) {\n    elina_abstract0_t* abs = elina_abstract0_permute_dimensions(\n        it->man, false, it->value, dp);\n    ds.push_back(std::make_shared<Abstract0>(it->man, abs));\n  }\n  Powerset p(ds, this->size);\n  // Permute the centers as well so we don't need to recompute them.\n  if (disjuncts.size() > 0) {\n    int dims = elina_abstract0_dimension(disjuncts[0]->man, disjuncts[0]->value).realdim;\n    Eigen::VectorXi perm(dims);\n    for (int i = 0; i < dims; i++) {\n      perm(i) = dp->dim[i];\n    }\n    Eigen::PermutationMatrix<Eigen::Dynamic> pm(perm);\n    for (unsigned int i = 0; i < disjuncts.size(); i++) {\n      if (disjuncts[i]->center_computed) {\n        p.disjuncts[i]->center_computed = true;\n        p.disjuncts[i]->center = pm * disjuncts[i]->center;\n      }\n    }\n  }\n  return p;\n}\n\nPowerset Powerset::remove_dimensions(elina_dimchange_t* dc) const {\n  std::vector<std::shared_ptr<Abstract0>> ds;\n  for (std::shared_ptr<Abstract0> it : this->disjuncts) {\n    elina_abstract0_t* abs = elina_abstract0_remove_dimensions(\n        it->man, false, it->value, dc);\n    bool bot = elina_abstract0_is_bottom(it->man, abs);\n    // bottom elements don't need to be added to this powerset.\n    if (!bot) {\n      ds.push_back(std::make_shared<Abstract0>(it->man, abs));\n    } else {\n      elina_abstract0_free(it->man, abs);\n    }\n  }\n  Powerset p(ds, this->size);\n  // Update centers\n  if (disjuncts.size() > 0) {\n    unsigned int dims = elina_abstract0_dimension(\n        disjuncts[0]->man, disjuncts[0]->value).realdim;\n    unsigned int out_dims = dims - dc->realdim;\n    for (unsigned int i = 0; i < disjuncts.size(); i++) {\n      if (disjuncts[i]->center_computed) {\n        p.disjuncts[i]->center_computed = true;\n        Eigen::VectorXd c(out_dims);\n        int dc_ind = 0;\n        int c_ind = 0;\n        for (unsigned int j = 0; j < dims; j++) {\n          if (dc->dim[dc_ind] == j) {\n            dc_ind++;\n            continue;\n          }\n          c(c_ind) = disjuncts[i]->center(j);\n          c_ind++;\n        }\n      }\n    }\n  }\n  return p;\n}\n\nPowerset Powerset::affine(const Eigen::MatrixXd& m, const Eigen::VectorXd& b) const {\n  int in_size = m.cols();\n  int out_size = m.rows();\n\n  // Create an elina linexpr array representing this update\n  elina_dim_t* dims = (elina_dim_t*) malloc(out_size * sizeof(elina_dim_t));\n  elina_linexpr0_t** update = (elina_linexpr0_t**) malloc(out_size *\n      sizeof(elina_linexpr0_t*));\n  for (int j = 0; j < out_size; j++) {\n    dims[j] = j;\n    update[j] = elina_linexpr0_alloc(ELINA_LINEXPR_DENSE, in_size);\n    for (int k = 0; k < in_size; k++) {\n      elina_linexpr0_set_coeff_scalar_double(update[j], k, m(j,k));\n    }\n    elina_linexpr0_set_cst_scalar_double(update[j], b(j));\n  }\n\n  Powerset z = assign_linexpr_array(dims, update, out_size, out_size);\n\n  free(dims);\n  for (int j = 0; j < out_size; j++) {\n    elina_linexpr0_free(update[j]);\n  }\n  free(update);\n\n  return z;\n}\n\nPowerset Powerset::relu() const {\n  Powerset z = *this;\n  size_t num_dims = elina_abstract0_dimension(\n      disjuncts[0]->man, disjuncts[0]->value).realdim;\n  for (unsigned int i = 0; i < num_dims; i++) {\n    // Create two linear constraints, so that we can meet z with\n    // x_i <= 0 and x_i >= 0.\n    elina_linexpr0_t* lt0_le = elina_linexpr0_alloc(ELINA_LINEXPR_SPARSE, 1);\n    elina_linexpr0_t* gt0_le = elina_linexpr0_alloc(ELINA_LINEXPR_SPARSE, 1);\n    elina_linexpr0_set_coeff_scalar_double(lt0_le, i, -1.0);\n    elina_linexpr0_set_coeff_scalar_double(gt0_le, i, 1.0);\n\n    elina_lincons0_array_t lt0 = elina_lincons0_array_make(1);\n    elina_lincons0_array_t gt0 = elina_lincons0_array_make(1);\n    lt0.p[0].constyp = ELINA_CONS_SUPEQ;\n    lt0.p[0].linexpr0 = lt0_le;\n    gt0.p[0].constyp = ELINA_CONS_SUP;\n    gt0.p[0].linexpr0 = gt0_le;\n\n    // zlt = z `meet` x_i <= 0\n    Powerset zlt = z.meet_lincons_array(&lt0);\n    // z = z `meet` x_i >= 0\n    z = z.meet_lincons_array(&gt0);\n\n    // Assign x_i = 0 in zlt\n    elina_linexpr0_t* zero = elina_linexpr0_alloc(ELINA_LINEXPR_SPARSE, 0);\n    elina_linexpr0_set_cst_scalar_double(zero, 0.0);\n    elina_dim_t dim = i;\n    zlt = zlt.assign_linexpr_array(&dim, &zero, 1, num_dims);\n\n    // Join z with the modified zlt\n    z = z.join(zlt);\n\n    elina_linexpr0_free(zero);\n    elina_lincons0_array_clear(&lt0);\n    elina_lincons0_array_clear(&gt0);\n  }\n\n  return z;\n}\n\nPowerset Powerset::join(const Powerset& other) const {\n  if (this->disjuncts.size() == 0) {\n    return other;\n  } else if (other.disjuncts.size() == 0) {\n    return *this;\n  }\n  std::vector<std::shared_ptr<Abstract0>> ds(disjuncts);\n  ds.insert(ds.end(), other.disjuncts.begin(), other.disjuncts.end());\n  // ds now holds all of the disjuncts from both powersets\n  unsigned int s = std::max(size, other.size);\n  while (ds.size() > s) {\n    // Find the two disjuncts whose centers are closes to each other\n    int best_i = 0, best_j = 1;\n    if (s > 1) {\n      if (!ds[0]->center_computed) {\n        ds[0]->center = compute_center(ds[0]->man, ds[0]->value);\n      }\n      if (!ds[1]->center_computed) {\n        ds[1]->center = compute_center(ds[1]->man, ds[1]->value);\n      }\n      double best_dist = (ds[0]->center - ds[1]->center).norm();\n      for (unsigned int i = 0; i < ds.size() - 1; i++) {\n        if (!ds[i]->center_computed) {\n          ds[i]->center = compute_center(ds[i]->man, ds[i]->value);\n        }\n        for (unsigned int j = i+1; j < ds.size(); j++) {\n          if (!ds[j]->center_computed) {\n            ds[j]->center = compute_center(ds[j]->man, ds[j]->value);\n          }\n          double dist = (ds[i]->center - ds[j]->center).lpNorm<Eigen::Infinity>();\n          if (dist < best_dist) {\n            best_i = i;\n            best_j = j;\n            best_dist = dist;\n          }\n        }\n      }\n    }\n    // Join those two disjuncts\n    elina_abstract0_t* n = elina_abstract0_join(ds[best_i]->man, false,\n        ds[best_i]->value, ds[best_j]->value);\n    // j > i so we don't need to worry about messing up indices if we erase\n    // j first\n    ds.erase(ds.begin() + best_j);\n    ds.erase(ds.begin() + best_i);\n    ds.push_back(std::make_shared<Abstract0>(ds[best_i]->man, n));\n  }\n\n  return Powerset(ds, s);\n}\n\nbool Powerset::is_bottom() const {\n  bool bottom = true;\n  for (std::shared_ptr<Abstract0> it : this->disjuncts) {\n    if (!elina_abstract0_is_bottom(it->man, it->value)) {\n      bottom = false;\n      break;\n    }\n  }\n  // Note that if disjuncts is empty then this powerset is bottom.\n\n  return bottom;\n}\n\nssize_t Powerset::dims() const {\n  if (this->disjuncts.size() > 0)\n    return elina_abstract0_dimension(\n        this->disjuncts[0]->man, this->disjuncts[0]->value).realdim;\n  return 0;\n}\n\nelina_interval_t** Powerset::bounding_box() const {\n  elina_interval_t** itvs[disjuncts.size()];\n  for (unsigned int i = 0; i < disjuncts.size(); i++) {\n    itvs[i] = elina_abstract0_to_box(disjuncts[i]->man, disjuncts[i]->value);\n  }\n  size_t dims = elina_abstract0_dimension(disjuncts[0]->man, disjuncts[0]->value).realdim;\n  elina_interval_t** ret = (elina_interval_t**) malloc(dims * sizeof(elina_interval_t*));\n  for (unsigned int i = 0; i < dims; i++) {\n    ret[i] = elina_interval_alloc();\n    double lowest = std::numeric_limits<double>::max();\n    double highest = -std::numeric_limits<double>::max();\n    for (unsigned int j = 0; j < disjuncts.size(); j++) {\n      double l, u;\n      elina_double_set_scalar(&l, itvs[j][i]->inf, MPFR_RNDN);\n      elina_double_set_scalar(&u, itvs[j][i]->sup, MPFR_RNDN);\n      if (l < lowest) {\n        lowest = l;\n      }\n      if (u > highest) {\n        highest = u;\n      }\n    }\n    elina_interval_set_double(ret[i], lowest, highest);\n  }\n  for (unsigned int i = 0; i < disjuncts.size(); i++) {\n    for (unsigned int j = 0; j < dims; j++) {\n      elina_interval_free(itvs[i][j]);\n    }\n    free(itvs[i]);\n  }\n  return ret;\n}\n\nvoid Powerset::print_bounding_box() const {\n  std::cout.precision(std::numeric_limits<double>::max_digits10);\n  elina_interval_t** box = bounding_box();\n  for (int i = 0; i < dims(); i++) {\n    double l, u;\n    elina_double_set_scalar(&l, box[i]->inf, MPFR_RNDN);\n    elina_double_set_scalar(&u, box[i]->sup, MPFR_RNDN);\n    std::cout << \"[\" << l << \", \" << u << \"]\" << std::endl;\n    elina_interval_free(box[i]);\n  }\n  free(box);\n}\n\nPowerset& Powerset::operator=(const Powerset& other) {\n  this->size = other.size;\n  disjuncts = other.disjuncts;\n  return *this;\n}\n\n", "meta": {"hexsha": "2befe85dfa1f21277d14a8c6a8ba6ee225483415", "size": 13430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/powerset.cpp", "max_stars_repo_name": "gavlegoat/charon", "max_stars_repo_head_hexsha": "287303ab4eac90ab8f0bfc7cbf145efc9767469c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-07-11T18:48:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T07:20:28.000Z", "max_issues_repo_path": "src/powerset.cpp", "max_issues_repo_name": "gavlegoat/charon", "max_issues_repo_head_hexsha": "287303ab4eac90ab8f0bfc7cbf145efc9767469c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/powerset.cpp", "max_forks_repo_name": "gavlegoat/charon", "max_forks_repo_head_hexsha": "287303ab4eac90ab8f0bfc7cbf145efc9767469c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T00:53:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T07:39:25.000Z", "avg_line_length": 32.756097561, "max_line_length": 91, "alphanum_fraction": 0.6425912137, "num_tokens": 4148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.03904829048965016, "lm_q1q2_score": 0.01800191711919025}}
{"text": "#pragma once\r\n//=====================================================================//\r\n/*!\t@file\r\n\t@brief\t各種頂点の定義 @n\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps://github.com/hirakuni45/glfw_app/blob/master/LICENSE\r\n*/\r\n//=====================================================================//\r\n#include <vector>\r\n#include <boost/unordered_set.hpp>\r\n#include <boost/unordered_map.hpp>\r\n#include <cmath>\r\n#include <cfloat>\r\n#include <cstdint>\r\n\r\nnamespace vtx {\r\n\r\n// note: 通常のマシンでは、float 型より double 型の方が高速だが、リソースが限られた\r\n//       マシンでは、その傾向は逆転する。\r\n//       RXv2 コアでは、float 型は高速だが double 型は遅い。\r\n//       RXv2 コアには、「fsqrt」（float 型専用の平方根命令がある）\r\n#if defined(SIG_RX24T) || defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N)\r\n\tinline float fsqrt(float x)\r\n\t{\r\n\t\t__asm __volatile(\r\n\t\t\t\"fsqrt %0, %0\\n\" \\\r\n\t\t\t: \"+r\"(x) \\\r\n\t\t);\r\n\t\treturn x;\r\n\t}\r\n#else\r\n\tinline float fsqrt(float x) { return std::sqrt(x); }\r\n#endif\r\n\r\n\ttemplate <typename T>\r\n\tT get_pi() { return static_cast<T>(3.1415926535897932384626433832795); }\r\n\r\n\tconst float  deg2rad_f_ = get_pi<float>() / 180.0f;\t\t///< DEG -> RAD の変換定数(float)\r\n\tconst float  radian_f_  = 2.0f * get_pi<float>();\t\t///< RADIAN のπ変換定数(float)\r\n\tconst double deg2rad_d_ = get_pi<double>() / 180.0;\t\t///< DEG -> RAD の変換定数(double)\r\n\tconst double radian_d_  = 2.0 * get_pi<double>();\t\t///< RADIAN のπ変換定数(double)\r\n\r\n\tinline void min_level(int8_t& min) { min = 1; }\r\n\tinline void min_level(int16_t& min) { min = 1; }\r\n\tinline void min_level(int32_t& min) { min = 1; }\r\n\tinline void min_level(float& min) { min = FLT_MIN; }\r\n\tinline void min_level(double& min) { min = DBL_MIN; }\r\n\r\n\tinline void max_level(int8_t& min) { min = 0x7f; }\r\n\tinline void max_level(int16_t& min) { min = 0x7fff; }\r\n\tinline void max_level(int32_t& min) { min = 0x7fffffff; }\r\n\tinline void max_level(float& max) { max = FLT_MAX; }\r\n\tinline void max_level(double& max) { max = DBL_MAX; }\r\n\r\n\ttemplate <typename T>\r\n\tT min_value() {\r\n\t\tT min;\r\n\t\tmin_level(min);\r\n\t\treturn min;\r\n\t}\r\n\r\n\ttemplate <typename T>\r\n\tT max_value() {\r\n\t\tT max;\r\n\t\tmax_level(max);\r\n\t\treturn max;\r\n\t}\r\n\r\n\ttemplate <typename T> struct vertex2;\r\n\ttemplate <typename T> struct vertex3;\r\n\ttemplate <typename T> struct vertex4;\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t8 ビット整数、二次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex2<int8_t>\tbpos;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t16 ビット整数、二次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex2<int16_t> spos;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t32 ビット整数、二次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex2<int32_t> ipos;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t32 ビット浮動小数点、二次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex2<float>\tfpos;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t64 ビット倍精度浮動小数点、二次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex2<double>\tdpos;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t8 ビット整数、三次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex3<int8_t> bvtx;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t16 ビット整数、三次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex3<int16_t> svtx;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t32 ビット整数、三次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex3<int32_t> ivtx;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t32 ビット浮動小数点、三次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex3<float> fvtx;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t64 ビット倍精度浮動小数点、三次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex3<double> dvtx;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t8 ビット整数、四次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex4<int8_t> bvtx4;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t16 ビット整数、四次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex4<int16_t> svtx4;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t32 ビット整数、四次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex4<int32_t> ivtx4;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t32 ビット浮動小数点、四次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex4<float> fvtx4;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t64 ビット倍精度浮動小数点、四次元、位置情報\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttypedef vertex4<double> dvtx4;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t次元テンプレート共通クラス\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <typename T, int NUM>\r\n\tstruct vertex_base {\r\n\t\ttypedef T   value_type;\r\n\r\n\t\tinline uint32_t dim() const { return NUM; }\r\n\t\tinline uint32_t size() const { return sizeof(T) * NUM; }\r\n\t\tstatic inline T get_min() { T v; min_level(v); return v; }\r\n\t\tstatic inline T get_max() { T v; max_level(v); return v; }\r\n\t};\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t二次元テンプレート\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <typename T>\r\n\tstruct vertex2 : public vertex_base<T, 2> {\r\n\t\tT\tx;\r\n\t\tT\ty;\r\n\r\n\t\tvertex2() { }\r\n\t\tconstexpr vertex2(const spos& v) : x(v.x), y(v.y) { }\r\n\t\tconstexpr vertex2(const ipos& v) : x(v.x), y(v.y) { }\r\n\t\tconstexpr vertex2(const fpos& v) : x(v.x), y(v.y) { }\r\n\t\tconstexpr vertex2(const dpos& v) : x(v.x), y(v.y) { }\r\n\t\texplicit constexpr vertex2(T c) : x(c), y(c) { }\r\n\t\tconstexpr vertex2(T xx, T yy) : x(xx), y(yy) { }\r\n\r\n\t\tconst T* getXY() const { return &x; }\r\n\r\n\t\tT sqrX() const { return x * x; }\r\n\t\tT sqrY() const { return y * y; }\r\n\t\tT sqr() const { return sqrX() + sqrY(); }\r\n\t\tT len() const { return fsqrt(sqr()); }\r\n\r\n\t\tT min() const { return x < y ? x : y; }\r\n\t\tT max() const { return x > y ? x : y; }\r\n\r\n\t\tvoid set(T c) { x = y = c; }\r\n\t\tvoid set(T xx, T yy) { x = xx; y = yy; }\r\n\t\tvoid set(const vertex2& v) { x = v.x; y = v.y; }\r\n\r\n\t\tvoid add(T c) { x += c; y += c; }\r\n\t\tvoid add(T xx, T yy) { x += xx; y += yy; }\r\n\t\tvoid add(const vertex2<T>& v) { x += v.x; y += v.y; }\r\n\t\tvoid sub(T c) { x -= c; y -= c; }\r\n\t\tvoid sub(T xx, T yy) { x -= xx; y -= yy; }\r\n\t\tvoid sub(const vertex2<T>& v) { x -= v.x; y -= v.y; }\r\n\t\tvoid mul(T c) { x *= c; y *= c; }\r\n\t\tvoid mul(T xx, T yy) { x *= xx; y *= yy; }\r\n\t\tvoid mul(const vertex2<T>& v) { x *= v.x; y *= v.y; }\r\n\t\tvoid div(T c) { x /= c; y /= c; }\r\n\t\tvoid div(T xx, T yy) { x /= xx; y /= yy; }\r\n\t\tvoid div(const vertex2<T>& v) { x /= v.x; y /= v.y; }\r\n\r\n\t\tstatic T dot(const vertex2& a, const vertex2& b) { return a.x * b.x + a.y * b.y; }\r\n\t\tstatic T cross(const vertex2& a, const vertex2& b) { return a.x * b.y - a.y * b.x; }\r\n\r\n\t\t// Method necessary for using「boost/unordered_map」\r\n\t\tbool operator == (const vertex2<T>& v) const {\r\n\t\t\tif(x == v.x && y == v.y) return true;\r\n\t\t\telse return false;\r\n\t\t}\r\n\r\n\t\tbool operator != (const vertex2<T>& v) const {\r\n\t\t\tif(x == v.x && y == v.y) return false;\r\n\t\t\telse return true;\r\n\t\t}\r\n\r\n\t\tsize_t hash() const {\r\n\t\t\tsize_t h = 0;\r\n\t\t\tboost::hash_combine(h, x);\r\n\t\t\tboost::hash_combine(h, y);\r\n\t\t\treturn h;\r\n\t\t}\r\n\r\n\t\tvertex2& operator = (T c) { set(c); return *this; }\r\n\r\n\t\tvertex2& operator = (const spos& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y)); return *this;\r\n\t\t}\r\n\t\tvertex2& operator = (const ipos& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y)); return *this;\r\n\t\t}\r\n\t\tvertex2& operator = (const fpos& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y)); return *this;\r\n\t\t}\r\n\t\tvertex2& operator = (const dpos& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y)); return *this;\r\n\t\t}\r\n\r\n\t\tvertex2& operator += (const vertex2& v) { add(v); return *this; }\r\n\t\tvertex2& operator += (T c) { add(c); return *this; }\r\n\t\tvertex2 operator + (T c) const {\r\n\t\t\tvertex2 t(x + c, y + c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tvertex2 operator + (const vertex2& v) const {\r\n\t\t\tvertex2\tt(x + v.x, y + v.y);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tvertex2& operator -= (const vertex2& v) { sub(v); return *this; }\r\n\t\tvertex2& operator -= (T c) { sub(c); return *this; }\r\n\t\tvertex2 operator - (T c) const {\r\n\t\t\tvertex2\tt(x - c, y - c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tvertex2 operator - (const vertex2& v) const {\r\n\t\t\tvertex2 t(x, y);\r\n\t\t\tt.sub(v);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tvertex2& operator *= (T c) { mul(c); return *this; }\r\n\t\tvertex2& operator *= (const vertex2& v) { mul(v);  return *this; }\r\n\t\tvertex2 operator * (const vertex2& v) const {\r\n\t\t\tvertex2\tt(x * v.x, y * v.y);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tvertex2 operator * (T c) const {\r\n\t\t\tvertex2\tt(x * c, y * c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tvertex2& operator /= (T c) { div(c); return *this; }\r\n\t\tvertex2& operator /= (const vertex2& v) { div(v); return *this; }\r\n\t\tvertex2 operator / (T c) const {\r\n\t\t\tvertex2\tt(x / c, y / c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tvertex2 operator / (const vertex2& v) const {\r\n\t\t\tvertex2\tt(x / v.x, y / v.y);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t};\r\n\r\n\ttypedef std::vector<bpos>\t\t\t\t\tbposs;\r\n\ttypedef std::vector<bpos>::iterator\t\t\tbposs_it;\r\n\ttypedef std::vector<bpos>::const_iterator\tbposs_cit;\r\n\r\n\ttypedef std::vector<spos>\t\t\t\t\tsposs;\r\n\ttypedef std::vector<spos>::iterator\t\t\tsposs_it;\r\n\ttypedef std::vector<spos>::const_iterator\tsposs_cit;\r\n\r\n\ttypedef std::vector<ipos>\t\t\t\t\tiposs;\r\n\ttypedef std::vector<ipos>::iterator\t\t\tiposs_it;\r\n\ttypedef std::vector<ipos>::const_iterator\tiposs_cit;\r\n\r\n\ttypedef std::vector<fpos>\t\t\t\t\tfposs;\r\n\ttypedef std::vector<fpos>::iterator\t\t\tfposs_it;\r\n\ttypedef std::vector<fpos>::const_iterator\tfposs_cit;\r\n\r\n\ttypedef std::vector<dpos>\t\t\t\t\tdposs;\r\n\ttypedef std::vector<dpos>::iterator\t\t\tdposs_it;\r\n\ttypedef std::vector<dpos>::const_iterator\tdposs_cit;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t三次元、位置情報テンプレート\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <typename T>\r\n\tstruct vertex3 : public vertex_base<T, 3> {\r\n\t\tT\tx;\r\n\t\tT\ty;\r\n\t\tT\tz;\r\n\r\n\t\tinline vertex3() { }\r\n\t\tinline vertex3(const svtx& v) : x(v.x), y(v.y), z(v.z) { }\r\n\t\tinline vertex3(const ivtx& v) : x(v.x), y(v.y), z(v.z) { }\r\n\t\tinline vertex3(const fvtx& v) : x(v.x), y(v.y), z(v.z) { }\r\n\t\tinline vertex3(const dvtx& v) : x(v.x), y(v.y), z(v.z) { }\r\n\t\texplicit inline vertex3(T c) : x(c), y(c), z(c) { }\r\n\t\texplicit inline vertex3(T xx, T yy, T zz = static_cast<T>(0)) : x(xx), y(yy), z(zz) { }\r\n\r\n\t\tinline const T* getXYZ() const { return &x; }\r\n\r\n\t\tinline T sqrX() const { return x * x; }\r\n\t\tinline T sqrY() const { return y * y; }\r\n\t\tinline T sqrZ() const { return z * z; }\r\n\t\tinline T sqr() const { return sqrX() + sqrY() + sqrZ(); }\r\n\t\tinline T len() const { return fsqrt(sqr()); }\r\n\r\n\t\tinline T min() const {\r\n\t\t\tif(x < y) {\r\n\t\t\t\tif(x < z) return x;\r\n\t\t\t} else {\r\n\t\t\t\tif(y < z) return y;\r\n\t\t\t}\r\n\t\t\treturn z;\r\n\t\t}\r\n\t\tinline T max() const {\r\n\t\t\tif(x > y) {\r\n\t\t\t\tif(x > z) return x;\r\n\t\t\t} else {\r\n\t\t\t\tif(y > z) return y;\r\n\t\t\t}\r\n\t\t\treturn z;\r\n\t\t}\r\n\r\n\t\tinline void set(T c) { x = y = z = c; }\r\n\t\tinline void set(T xx, T yy, T zz = static_cast<T>(0)) { x = xx; y = yy; z = zz; }\r\n\t\tinline void set(const vertex2<T>& v) { x = v.x; y = v.y; z = static_cast<T>(0); }\r\n\t\tinline void set(const vertex3<T>& v) { x = v.x; y = v.y; z = v.z; }\r\n\r\n\t\tinline void add(T c) { x += c; y += c; z += c; }\r\n\t\tinline void add(T xx, T yy, T zz) { x += xx; y += yy; z += zz; }\r\n\t\tinline void add(const vertex3& v) { x += v.x; y += v.y; z += v.z; }\r\n\t\tinline void sub(T c) { x -= c; y -= c; z -= c; }\r\n\t\tinline void sub(T xx, T yy, T zz) { x -= xx; y -= yy; z -= zz; }\r\n\t\tinline void sub(const vertex3& v) { x -= v.x; y -= v.y; z -= v.z; }\r\n\t\tinline void mul(T c) { x *= c; y *= c; z *= c; }\r\n\t\tinline void mul(T xx, T yy, T zz) { x *= xx; y *= yy; z *= zz; }\r\n\t\tinline void mul(const vertex3& v) { x *= v.x; y *= v.y; z *= v.z; }\r\n\t\tinline void div(T c) { x /= c; y /= c; z /= c; }\r\n\t\tinline void div(T xx, T yy, T zz) { x /= xx; y /= yy; z /= zz; }\r\n\t\tinline void div(const vertex3& v) { x /= v.x; y /= v.y; z /= v.z; }\r\n\r\n\t\tstatic inline T dot(const vertex3& a, const vertex3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; }\r\n\t\tstatic inline void cross(const vertex3& a, const vertex3& b, vertex3& out) {\r\n\t\t\tout.x = a.y * b.z - a.z * b.y;\r\n\t\t\tout.y = a.z * b.x - a.x * b.z;\r\n\t\t\tout.z = a.x * b.y - a.y * b.x;\r\n\t\t}\r\n\r\n\t\t// Method necessary for using「boost/unordered_map」\r\n\t\tinline bool operator == (const vertex3& v) const {\r\n\t\t\tif(x == v.x && y == v.y && z == v.z) return true;\r\n\t\t\telse return false;\r\n\t\t}\r\n\r\n\t\tinline bool operator != (const vertex3& v) const {\r\n\t\t\tif(x == v.x && y == v.y && z == v.z) return false;\r\n\t\t\telse return true;\r\n\t\t}\r\n\r\n\t\tinline size_t hash() const {\r\n\t\t\tsize_t h = 0;\r\n\t\t\tboost::hash_combine(h, x);\r\n\t\t\tboost::hash_combine(h, y);\r\n\t\t\tboost::hash_combine(h, z);\r\n\t\t\treturn h;\r\n\t\t}\r\n\r\n\t\tinline vertex3& operator = (T c) { set(c); return *this; }\r\n\t\tinline vertex3& operator = (const vertex2<T>& v) { set(v); return *this; }\r\n\r\n\t\tvertex3& operator = (const svtx& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y), static_cast<T>(v.z));\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t\tvertex3& operator = (const ivtx& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y), static_cast<T>(v.z));\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t\tvertex3& operator = (const fvtx& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y), static_cast<T>(v.z));\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t\tvertex3& operator = (const dvtx& v) {\r\n\t\t\tset(static_cast<T>(v.x), static_cast<T>(v.y), static_cast<T>(v.z));\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tinline vertex3& operator += (T c) { add(c); return *this; }\r\n\t\tinline vertex3& operator += (const vertex3& v) { add(v); return *this; }\r\n\t\tinline vertex3 operator + (T c) const {\r\n\t\t\tvertex3\tt(x + c, y + c, z + c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex3 operator + (const vertex3& v) const {\r\n\t\t\tvertex3\tt(x + v.x, y + v.y, z + v.z);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tinline vertex3& operator -= (T c) { sub(c); return *this; }\r\n\t\tinline vertex3& operator -= (const vertex3& v) { sub(v); return *this; }\r\n\t\tinline vertex3 operator - (T c) const {\r\n\t\t\tvertex3\tt(x - c, y - c, z - c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex3 operator - (const vertex3& v) const {\r\n\t\t\tvertex3\tt(x - v.x, y - v.y, z - v.z);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tinline vertex3& operator *= (T c) { mul(c); return *this; }\r\n\t\tinline vertex3& operator *= (const vertex3& v) { mul(v); return *this; }\r\n\t\tinline vertex3 operator * (T c) const {\r\n\t\t\tvertex3\tt(x * c, y * c, z * c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex3 operator * (const vertex3& v) const {\r\n\t\t\tvertex3\tt(x * v.x, y * v.y, z * v.z);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tinline vertex3& operator /= (T c) { div(c); return *this; }\r\n\t\tinline vertex3& operator /= (const vertex3& v) { div(v); return *this; }\r\n\t\tinline vertex3 operator / (T c) const {\r\n\t\t\tvertex3\tt(x / c, y / c, z / c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex3 operator / (const vertex3& v) const {\r\n\t\t\tvertex3\tt(x / v.x, y / v.y, z / v.z);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t};\r\n\r\n\ttypedef std::vector<bvtx>\t\t\t\t\tbvtxs;\r\n\ttypedef std::vector<bvtx>::iterator\t\t\tbvtxs_it;\r\n\ttypedef std::vector<bvtx>::const_iterator\tbvtxs_cit;\r\n\r\n\ttypedef std::vector<svtx>\t\t\t\t\tsvtxs;\r\n\ttypedef std::vector<svtx>::iterator\t\t\tsvtxs_it;\r\n\ttypedef std::vector<svtx>::const_iterator\tsvtxs_cit;\r\n\r\n\ttypedef std::vector<ivtx>\t\t\t\t\tivtxs;\r\n\ttypedef std::vector<ivtx>::iterator\t\t\tivtxs_it;\r\n\ttypedef std::vector<ivtx>::const_iterator\tivtxs_cit;\r\n\r\n\ttypedef std::vector<fvtx>\t\t\t\t\tfvtxs;\r\n\ttypedef std::vector<fvtx>::iterator\t\t\tfvtxs_it;\r\n\ttypedef std::vector<fvtx>::const_iterator\tfvtxs_cit;\r\n\r\n\ttypedef std::vector<dvtx>\t\t\t\t\tdvtxs;\r\n\ttypedef std::vector<dvtx>::iterator\t\t\tdvtxs_it;\r\n\ttypedef std::vector<dvtx>::const_iterator\tdvtxs_cit;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t四次元、位置情報テンプレート\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <typename T>\r\n\tstruct vertex4 : public vertex_base<T, 4> {\r\n\t\tT\tx;\r\n\t\tT\ty;\r\n\t\tT\tz;\r\n\t\tT\tw;\r\n\r\n\t\tinline vertex4() { }\r\n\t\texplicit inline vertex4(T c) : x(c), y(c), z(c), w(c) { }\r\n\t\texplicit inline vertex4(T xx, T yy, T zz, T ww = static_cast<T>(1)) : x(xx), y(yy), z(zz), w(ww) { }\r\n\t\tinline vertex4(const vertex3<T>& v) : x(v.x), y(v.y), z(v.z), w(static_cast<T>(1)) { }\r\n\t\tinline vertex4(const vertex4& v) : x(v.x), y(v.y), z(v.z), w(v.w) { }\r\n\r\n\t\tinline const T* getXYZW() const { return &x; }\r\n\r\n\t\tinline T sqrX() const { return x * x; }\r\n\t\tinline T sqrY() const { return y * y; }\r\n\t\tinline T sqrZ() const { return z * z; }\r\n\t\tinline T sqrW() const { return w * w; }\r\n\t\tinline T sqr() const { return (sqrX() + sqrY() + sqrZ() + sqrW()); }\r\n\t\tinline T len() const { return fsqrt(sqrX() + sqrY() + sqrZ() + sqrW()); }\r\n\r\n\t\tinline T min() const {\r\n\t\t\tif(x < y) {\r\n\t\t\t\tif(x < z) {\r\n\t\t\t\t\tif(x < w) return x;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(z < w) return z;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif(y < z) {\r\n\t\t\t\t\tif(y < w) return y;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(z < w) return z;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn w;\r\n\t\t}\r\n\t\tinline T max() const {\r\n\t\t\tif(x > y) {\r\n\t\t\t\tif(x > z) {\r\n\t\t\t\t\tif(x > w) return x;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(z > w) return z;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif(y > z) {\r\n\t\t\t\t\tif(y > w) return y;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif(z > w) return z;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn w;\r\n\t\t}\r\n\r\n\t\tinline void set(T c) { x = y = z = w = c; }\r\n\t\tinline void set(T xx, T yy, T zz, T ww = static_cast<T>(1)) { x = xx; y = yy; z = zz; w = ww; }\r\n\t\tinline void set(const vertex2<T>& v) { x = v.x; y = v.y; z = static_cast<T>(0); w = static_cast<T>(1); }\r\n\t\tinline void set(const vertex3<T>& v) { x = v.x; y = v.y; z = v.z; w = static_cast<T>(1); }\r\n\t\tinline void set(const vertex4<T>& v) { x = v.x; y = v.y; z = v.z; w = v.w;}\r\n\r\n\t\tinline void add(T xx, T yy, T zz, T ww = static_cast<T>(1)) { x += xx; y += yy; z += zz; w += ww; }\r\n\t\tinline void sub(T xx, T yy, T zz, T ww = static_cast<T>(1)) { x -= xx; y -= yy; z -= zz; w -= ww; }\r\n\t\tinline void mul(T xx, T yy, T zz, T ww = static_cast<T>(1)) { x *= xx; y *= yy; z *= zz; w *= ww; }\r\n\t\tinline void div(T xx, T yy, T zz, T ww = static_cast<T>(1)) { x /= xx; y /= yy; z /= zz; w /= ww; }\r\n\r\n\t\tinline bool operator == (const vertex4& v) const {\r\n\t\t\tif(x == v.x && y == v.y && z == v.z && w == v.w) return true;\r\n\t\t\telse return false;\r\n\t\t}\r\n\r\n\t\tinline bool operator != (const vertex4& v) const {\r\n\t\t\tif(x == v.x && y == v.y && z == v.z && w == v.w) return false;\r\n\t\t\telse return true;\r\n\t\t}\r\n\r\n\t\t// Method necessary for using「boost/unordered_map」\r\n\t\tinline size_t hash() const {\r\n\t\t\tsize_t h = 0;\r\n\t\t\tboost::hash_combine(h, x);\r\n\t\t\tboost::hash_combine(h, y);\r\n\t\t\tboost::hash_combine(h, z);\r\n\t\t\tboost::hash_combine(h, w);\r\n\t\t\treturn h;\r\n\t\t}\r\n\r\n\t\tinline vertex4& operator = (T c) { set(c); return *this; }\r\n\t\tinline vertex4& operator = (const vertex2<T>& v) { set(v); return *this; }\r\n\t\tinline vertex4& operator = (const vertex3<T>& v) { set(v); return *this; }\r\n\t\tinline vertex4& operator = (const vertex4<T>& v) { set(v); return *this; }\r\n\r\n\t\tinline vertex4& operator += (T c) { add(c); return *this; }\r\n\t\tinline vertex4& operator += (const vertex4& v) { add(v); return *this; }\r\n\t\tinline vertex4 operator + (T c) const {\r\n\t\t\tvertex4\tt(x + c, y + c, z + c, w + c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex4 operator + (const vertex4& v) const {\r\n\t\t\tvertex4 t(x + v.x, y + v.y, z + v.z, w + v.w);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tinline vertex4& operator -= (T c) { sub(c); return *this; }\r\n\t\tinline vertex4& operator -= (const vertex4& v) { sub(v); return *this; }\r\n\t\tinline vertex4 operator - (T c) const {\r\n\t\t\tvertex4 t(x - c, y - c, z - c, w - c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex4<T> operator - (const vertex4<T>& v) const {\r\n\t\t\tvertex4<T> t(x - v.x, y - v.y, z - v.z, w - v.w);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tinline vertex4<T>& operator *= (T c) { mul(c); return *this; }\r\n\t\tinline vertex4<T>& operator *= (const vertex4& v) { mul(v); return *this; }\r\n\t\tinline vertex4<T> operator * (T c) const {\r\n\t\t\tvertex4<T> t(x * c, y * c, z * c, w * c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex4<T> operator * (const vertex4<T>& v) const {\r\n\t\t\tvertex4<T> t(x * v.x, y * v.y, z * v.z, w * v.w);\r\n\t\t\treturn t;\r\n\t\t}\r\n\r\n\t\tinline vertex4<T>& operator /= (T c) { div(c); return *this; }\r\n\t\tinline vertex4<T>& operator /= (const vertex4<T>& v) { div(v); return *this; }\r\n\t\tinline vertex4<T> operator / (T c) const {\r\n\t\t\tvertex4<T> t(x / c, y / c, z / c, w / c);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\tinline vertex4<T> operator / (const vertex4<T>& v) const {\r\n\t\t\tvertex4<T> t(x / v.x, y / v.y, z / v.z, w / v.w);\r\n\t\t\treturn t;\r\n\t\t}\r\n\t};\r\n\r\n\ttypedef std::vector<bvtx4>\t\t\t\t\tbvtxs4;\r\n\ttypedef std::vector<bvtx4>::iterator\t\tbvtxs4_it;\r\n\ttypedef std::vector<bvtx4>::const_iterator\tbvtxs4_cit;\r\n\r\n\ttypedef std::vector<svtx4>\t\t\t\t\tsvtxs4;\r\n\ttypedef std::vector<svtx4>::iterator\t\tsvtxs4_it;\r\n\ttypedef std::vector<svtx4>::const_iterator\tsvtxs4_cit;\r\n\r\n\ttypedef std::vector<ivtx4>\t\t\t\t\tivtxs4;\r\n\ttypedef std::vector<ivtx4>::iterator\t\tivtxs4_it;\r\n\ttypedef std::vector<ivtx4>::const_iterator\tivtxs4_cit;\r\n\r\n\ttypedef std::vector<fvtx4>\t\t\t\t\tfvtxs4;\r\n\ttypedef std::vector<fvtx4>::iterator\t\tfvtxs4_it;\r\n\ttypedef std::vector<fvtx4>::const_iterator\tfvtxs4_cit;\r\n\r\n\ttypedef std::vector<dvtx4>\t\t\t\t\tdvtxs4;\r\n\ttypedef std::vector<dvtx4>::iterator\t\tdvtxs4_it;\r\n\ttypedef std::vector<dvtx4>::const_iterator\tdvtxs4_cit;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t「boost/unordered_set, unordered_map」用ハッシュ値計算\r\n\t\t@param[in]\tv\tハッシュ・ソース座標\r\n\t\t@return\t\tハッシュ値を返す\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tinline size_t hash_value(const T& v) { return v.hash(); }\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tベクトルの距離を求める\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@return\tベクトルの距離\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tinline typename T::value_type distance(const T& a, const T& b) {\r\n\t\tT d = b - a;\r\n\t\treturn d.len();\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tベクトルの内積\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@return\t内積結果\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tinline typename T::value_type dot(const T& a, const T& b)\r\n\t{\r\n\t\treturn T::dot(a, b);\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t二次元ベクトルの外積\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@return 外積結果（スカラー）\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tinline typename T::value_type cross(const T& a, const T& b)\r\n\t{\r\n\t\treturn T::cross(a, b);\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t三次元ベクトルの外積\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@param[out]\tout\t外積結果を受け取るベクトル（正規化されていない）\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tinline void cross(const T& a, const T& b, T& out)\r\n\t{\r\n\t\tT::cross(a, b, out);\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tベクトルの内積、正規化\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@return\t内積結果（COS θ)\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tinline typename T::value_type inner_product(const T& a, const T& b)\r\n\t{\r\n\t\ttypename T::value_type c = a.len() * b.len();\r\n\t\tif(c <= T::get_min()) return T::get_max();\r\n\t\treturn T::dot(a, b) / c;\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tベクトルの外積、正規化\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@param[out]\tn\t外積結果を受け取るベクトル\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tvoid outer_product(const T& a, const T& b, T& n)\r\n\t{\r\n\t\tT t;\r\n\t\tT::cross(a, b, t);\r\n\t\ttypename T::value_type l = t.len();\r\n\t\tif(l <= T::get_min()) {\r\n\t\t\tn = static_cast<T>(0);\r\n\t\t} else {\r\n\t\t\tn = t / l;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t二次元ベクトルの回転(CW: 時計廻り)@n\r\n\t\t\t\tX' =  X COS(s) + Y SIN(s)@n\r\n\t\t\t\tY' =  Y COS(s) - X SIN(s)\r\n\t\t@param[in]\tsrc\tソース・ベクトル\r\n\t\t@param[in]\tsi\tサイン\r\n\t\t@param[in]\tco\tコサイン\r\n\t\t@param[in]\tdst\t出力・ベクトル\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tvoid rotate_cw(const T& src, typename T::value_type si, typename T::value_type co, T& dst)\r\n\t{\r\n\t\tdst.set(src.x * co + src.y * si, src.y * co - src.x * si);\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t二次元ベクトルの回転(CCW: 反時計廻り)@n\r\n\t\t\t\tX' =  X COS(s) - Y SIN(s)@n\r\n\t\t\t\tY' =  Y COS(s) + X SIN(s)\r\n\t\t@param[in]\tsrc\tソース・ベクトル\r\n\t\t@param[in]\tsi\tサイン\r\n\t\t@param[in]\tco\tコサイン\r\n\t\t@param[in]\tdst\t出力・ベクトル\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <class T>\r\n\tvoid rotate_ccw(const T& src, typename T::value_type si, typename T::value_type co, T& dst)\r\n\t{\r\n\t\tdst.set(src.x * co - src.y * si, src.y * co + src.x * si);\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tライン（対の値を扱う）\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <typename T>\r\n\tclass line {\r\n\tpublic:\r\n\t\tT\ts;\r\n\t\tT\tt;\r\n\r\n\t\tline() { }\r\n\t\tline(const T& ss, const T& tt) { s = ss; t = tt; }\r\n\t\tvoid set(const T& ss, const T& tt) { s = ss; t = tt; }\r\n\t\tvoid first(const T& ss) { s = ss; }\r\n\t\tvoid second(const T& tt) { t = tt; }\r\n\t\tT center() const { return (s + t) / static_cast<T>(2); }\r\n\t\tstatic T center(const T& ss, const T& tt) { return (ss + tt) / static_cast<T>(2); }\r\n\t};\r\n\r\n\ttypedef line<fpos>\tfpos_line;\r\n\ttypedef line<dpos>\tdpos_line;\r\n\r\n\ttypedef line<fvtx>\tfvtx_line;\r\n\ttypedef line<dvtx>\tdvtx_line;\r\n\r\n\ttypedef std::vector<fpos_line>\t\t\t\tfpos_lines;\r\n\ttypedef std::vector<fpos_line>::iterator\tfpos_lines_it;\r\n\ttypedef std::vector<dpos_line>\t\t\t\tdpos_lines;\r\n\ttypedef std::vector<dpos_line>::iterator\tdpos_lines_it;\r\n\r\n\ttypedef std::vector<fvtx_line>\t\t\t\tfvtx_lines;\r\n\ttypedef std::vector<fvtx_line>::iterator\tfvtx_lines_it;\r\n\ttypedef std::vector<dvtx_line>\t\t\t\tdvtx_lines;\r\n\ttypedef std::vector<dvtx_line>::iterator\tdvtx_lines_it;\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tvertex を正規化するテンプレート\r\n\t\t@param[in]\tsrc\tソース座標列\r\n\t\t@param[out]\tdst\t生成座標列\r\n\t\t@return\t失敗した場合に「false」を返す\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\ttemplate <class T>\r\n\tbool normalize(const T& src, T& dst) {\r\n\t\ttypename T::value_type a = src.len();\r\n\t\tif(a < src.get_min()) return false;\r\n\t\tdst = src / a;\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tvertex を正規化するテンプレート\r\n\t\t@param[in]\tsrc\tソース座標列\r\n\t\t@return\t正規化されたベクトル\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\ttemplate <class T>\r\n\tT normalize(const T& src) {\r\n\t\tT dst;\r\n\t\tif(normalize(src, dst)) {\r\n\t\t\treturn dst;\r\n\t\t} else {\r\n\t\t\treturn src;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tortho_normalize\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@param[out]\tdst\t結果を受け取るベクトル\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n    template <typename T>\r\n    inline void ortho_normalize(const vertex3<T>& a, const vertex3<T>& b, vertex3<T>& dst)\r\n\t{\r\n\t\tnormalize(a - b * dot(b, a), dst);\r\n    }\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\t二次元領域テンプレート・クラス\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <typename T>\r\n\tclass rectangle {\r\n\tpublic:\r\n\t\ttypedef T\tvalue_type;\r\n\r\n\t\tvertex2<T>\t\torg;\t///< 開始点\r\n\t\tvertex2<T>\t\tsize;\t///< サイズ\r\n\r\n\t\trectangle() { }\r\n\t\tconstexpr rectangle(T v) : org(v), size(v) { }\r\n\t\tconstexpr rectangle(T x, T y, T w, T h) : org(x, y), size(w, h) { }\r\n\t\tconstexpr rectangle(const vertex2<T>& org_, const vertex2<T>& size_) : org(org_), size(size_) { }\r\n\t\tconstexpr rectangle(const rectangle<T>& r) : org(r.org), size(r.size) { }\r\n\r\n\t\tvoid set(T x, T y, T w, T h) { org.set(x, y); size.set(w, h); }\r\n\t\tvoid set(const vertex2<T>& org_, const vertex2<T>& size_) { org = org_; size = size_; }\r\n\r\n\t\tbool is_focus(const vertex2<T>& p) const {\r\n\t\t\tif(size.x <= 0 || size.y <= 0) return false;\r\n\t\t\tif(org.x <= p.x && p.x < (org.x + size.x) && org.y <= p.y && p.y < (org.y + size.y)) {\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n \r\n\t\tvoid center(vertex2<T>& c) const { c = (org + size) / static_cast<T>(2); }\r\n\t\tvertex2<T> center() const { return (org + size) / static_cast<T>(2); }\r\n\t\tvoid end(vertex2<T>& e) const { e = org + size; }\r\n\t\tvertex2<T> end() const { return org + size; }\r\n\r\n\t\tT center_x() const { return org.x + size.x / 2; }\r\n\t\tT center_y() const { return org.y + size.y / 2; }\r\n\t\tT end_x() const { return org.x + size.x; }\r\n\t\tT end_y() const { return org.y + size.y; }\r\n\r\n\t\t// クリップ領域の構築\r\n\t\tbool clip(const rectangle& r) {\r\n\t\t\tvertex2<T> e = end();\r\n\t\t\tvertex2<T> re = r.end();\r\n\t\t\tif(r.org.x <= org.x && org.x < re.x) {\r\n\t\t\t\tif(re.x < e.x) {\r\n\t\t\t\t\tsize.x = re.x - org.x;\r\n\t\t\t\t} \r\n\t\t\t} else if(re.x <= org.x) {\r\n\t\t\t\tsize.x = 0;\r\n\t\t\t\treturn false;\r\n\t\t\t} else if(org.x < r.org.x) {\r\n\t\t\t\tif(e.x < r.org.x) {\r\n\t\t\t\t\tsize.x = 0;\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t} else {\r\n\t\t\t\t\torg.x = r.org.x;\r\n\t\t\t\t\tif(re.x < e.x) {\r\n\t\t\t\t\t\tsize.x = re.x - org.x;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif(r.org.y <= org.y && org.y < re.y) {\r\n\t\t\t\tif(re.y < e.y) {\r\n\t\t\t\t\tsize.y = re.y - org.y;\r\n\t\t\t\t} \r\n\t\t\t} else if(re.y <= org.y) {\r\n\t\t\t\tsize.y = 0;\r\n\t\t\t\treturn false;\r\n\t\t\t} else if(org.y < r.org.y) {\r\n\t\t\t\tif(e.y < r.org.y) {\r\n\t\t\t\t\tsize.y = 0;\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t} else {\r\n\t\t\t\t\torg.y = r.org.y;\r\n\t\t\t\t\tif(re.y < e.y) {\r\n\t\t\t\t\t\tsize.y = re.y - org.y;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n\r\n\ttypedef rectangle<int16_t> srect;\r\n\ttypedef rectangle<int32_t> irect;\r\n\ttypedef rectangle<float>   frect;\r\n\ttypedef rectangle<double>  drect;\r\n\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tサークル\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\ttemplate <typename T>\r\n\tclass circle {\r\n\t\tT\t\t\t\tradius_;\r\n\t\tT\t\t\t\tradius_sqr_;\r\n\tpublic:\r\n\t\tvertex2<T>\t\tcenter;\r\n\t\tcircle() { }\r\n\t\tcircle(const vertex2<T>& cen, T r) : center(cen), radius_(r), radius_sqr_(r * r) { }\r\n\t\tcircle(T x, T y, T r) : center(x, y), radius_(r), radius_sqr_(r * r) { }\r\n\r\n\t\tT get_radius() const { return radius_; }\r\n\t\tvoid set_radius(T r) { radius_ = r; radius_sqr_ = r * r; }\r\n\r\n\t\tbool is_focus(const vertex2<T>& p) {\r\n\t\t\tvertex2<T> d = center - p;\r\n\t\t\tif((d.x * d.x + d.y * d.y) <= radius_sqr_) return true;\r\n\t\t\telse return false;\r\n\t\t}\r\n\t};\r\n\r\n\ttypedef circle<int>\t\ticircle;\r\n\ttypedef circle<float>\tfcircle;\r\n\ttypedef circle<double>\tdcircle;\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tクランプした B-Spline の生成\r\n\t\t@param[in]\tsrc\tソース座標列\r\n\t\t@param[in]\tlod\t分割数\r\n\t\t@param[out]\tdst\t生成座標列\r\n\t\t@return\t失敗した場合に「false」を返す\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tbool clumped_bspline(const fvtxs& src, int lod, fvtxs& dst);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t分割したベクトル列の生成\r\n\t\t@param[in]\tsrc\tソース座標列\r\n\t\t@param[in]\tlod\t分割数\r\n\t\t@param[out]\tdst\t生成座標列\r\n\t\t@return\t失敗した場合に「false」を返す\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tbool division_lines(const fvtxs& src, int lod, fvtxs& dst);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t直線の交点を求める(float)\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@param[out]\tpos\t交点\r\n\t\t@return\t「解」が無い場合、「false」が返る。\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tbool intersection_line(const fpos_line& a, const fpos_line& b, fpos& pos);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t直線の交点を求める(double)\r\n\t\t@param[in]\ta\tベクトル A\r\n\t\t@param[in]\tb\tベクトル B\r\n\t\t@param[out]\tpos\t交点\r\n\t\t@return\t「解」が無い場合、「false」が返る。\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tbool intersection_line(const dpos_line& a, const dpos_line& b, dpos& pos);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t最小値を設定\r\n\t\t@param[in]\tsrc\t\tソース\r\n\t\t@param[out]\tmin\t\t最小値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid set_min(const fvtx& src, fvtx& min);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t最大値を設定\r\n\t\t@param[in]\tsrc\t\tソース\r\n\t\t@param[out]\tmax\t\t最大値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid set_max(const fvtx& src, fvtx& max);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t最小値と最大値を設定\r\n\t\t@param[in]\tsrc\t\tソース\r\n\t\t@param[out]\tmin\t\t最小値\r\n\t\t@param[out]\tmax\t\t最大値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid set_min_max(const fvtx& src, fvtx& min, fvtx& max);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t最小値と最大値を探す (fpos)\r\n\t\t@param[in]\tsrc\t\tソース列\r\n\t\t@param[out]\tmin\t\t最小値\r\n\t\t@param[out]\tmax\t\t最大値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid scan_min_max(const fposs& src, fpos& min, fpos& max);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t最小値と最大値を探す (dpos)\r\n\t\t@param[in]\tsrc\t\tソース列\r\n\t\t@param[out]\tmin\t\t最小値\r\n\t\t@param[out]\tmax\t\t最大値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid scan_min_max(const dposs& src, dpos& min, dpos& max);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t最小値と最大値を探す (fvtx)\r\n\t\t@param[in]\tsrc\t\tソース列\r\n\t\t@param[out]\tmin\t\t最小値\r\n\t\t@param[out]\tmax\t\t最大値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid scan_min_max(const fvtxs& src, fvtx& min, fvtx& max);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t最小値と最大値を探す (dvtx)\r\n\t\t@param[in]\tsrc\t\tソース列\r\n\t\t@param[out]\tmin\t\t最小値\r\n\t\t@param[out]\tmax\t\t最大値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tvoid scan_min_max(const dvtxs& src, dvtx& min, dvtx& max);\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tベクトルの中心位置（fpos)\r\n\t\t@param[in]\ta\ta 点\r\n\t\t@param[in]\tb\tb 点\r\n\t\t@param[out]\tcen\t中心位置\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tinline void center_line(const fpos& a, const fpos& b, fpos& out) {\r\n\t\tout = fpos_line::center(a, b);\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tベクトルの中心位置（dpos)\r\n\t\t@param[in]\ta\ta 点\r\n\t\t@param[in]\tb\tb 点\r\n\t\t@param[out]\tcen\t中心位置\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tinline void center_line(const dpos& a, const dpos& b, dpos& out) {\r\n\t\tout = dpos_line::center(a, b);\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tベクトルの中心位置（fvtx)\r\n\t\t@param[in]\ta\ta 点\r\n\t\t@param[in]\tb\tb 点\r\n\t\t@param[out]\tcen\t中心位置\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tinline void center_line(const fvtx& a, const fvtx& b, fvtx& out) {\r\n\t\tout = fvtx_line::center(a, b);\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tベクトルの中心位置（dvtx)\r\n\t\t@param[in]\ta\ta 点\r\n\t\t@param[in]\tb\tb 点\r\n\t\t@param[out]\tcen\t中心位置\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tinline void center_line(const dvtx& a, const dvtx& b, dvtx& out) {\r\n\t\tout = dvtx_line::center(a, b);\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tベクター比（fvtx)\r\n\t\t@param[in]\ta\t\ta 点\r\n\t\t@param[in]\tfactor\t比率\r\n\t\t@param[in]\tb\t\tb 点\r\n\t\t@param[out]\tout\t\t答え\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tinline void factor_line(const fvtx& a, float factor, const fvtx& b, fvtx& out) {\r\n\t\tout = a + (b - a) * factor;\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tベクトル列の平均（fpos)\r\n\t\t@param[in]\tlist\tベクトル列\r\n\t\t@param[out]\tout\t\t平均値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tinline void average(const fposs& list, fpos& out) {\r\n\t\tout.set(0.0f, 0.0f);\r\n\t\tfor(fposs_cit cit = list.begin(); cit != list.end(); ++cit) {\r\n\t\t\tout += *cit;\r\n\t\t}\r\n\t\tout *= 1.0f / static_cast<float>(list.size());\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\tベクトル列の平均（fvtx)\r\n\t\t@param[in]\tlist\tベクトル列\r\n\t\t@param[out]\tout\t\t平均値\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tinline void average(const fvtxs& list, fvtx& out) {\r\n\t\tout.set(0.0f, 0.0f, 0.0f);\r\n\t\tfor(fvtxs_cit cit = list.begin(); cit != list.end(); ++cit) {\r\n\t\t\tout += *cit;\r\n\t\t}\r\n\t\tout *= 1.0f / static_cast<float>(list.size());\r\n\t}\r\n\r\n\r\n\t//-----------------------------------------------------------------//\r\n\t/*!\r\n\t\t@brief\t二つの頂点配列(std::vector)から、共有「する」、@n\r\n\t\t\t\t「しない」頂点配列(std::vector)を生成\r\n\t\t@param[in]\tsrc_a\t配列 A\r\n\t\t@param[in]\tsrc_b\t配列 B\r\n\t\t@param[out]\tdst\t\t共有配列\r\n\t\t@param[in]\tshare\t「false」なら共有しない頂点を生成\r\n\t\t@return 共有する頂点が無い場合「false」\r\n\t*/\r\n\t//-----------------------------------------------------------------//\r\n\tbool make_share_vertex(const fvtxs& src_a, const fvtxs& src_b, fvtxs& dst, bool share = true);\r\n\r\n\ttypedef boost::unordered_set<fvtx>\t\t\t\t\tfvtx_set;\r\n\ttypedef boost::unordered_set<fvtx>::iterator\t\tfvtx_set_it;\r\n\ttypedef boost::unordered_set<fvtx>::const_iterator\tfvtx_set_cit;\r\n\r\n\ttypedef boost::unordered_set<dvtx>\t\t\t\t\tdvtx_set;\r\n\ttypedef boost::unordered_set<dvtx>::iterator\t\tdvtx_set_it;\r\n\ttypedef boost::unordered_set<dvtx>::const_iterator\tdvtx_set_cit;\r\n\r\n}\t// namespace vtx\r\n", "meta": {"hexsha": "1b8766be9991e3321efd3c7ca30f35d1eb0c0337", "size": 39420, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "glfw3_app/rx_gui_emu/RX/common/vtx.hpp", "max_stars_repo_name": "hirakuni45/glfw3_app", "max_stars_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-09-22T21:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T09:16:53.000Z", "max_issues_repo_path": "glfw3_app/rx_gui_emu/RX/common/vtx.hpp", "max_issues_repo_name": "hirakuni45/glfw3_app", "max_issues_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glfw3_app/rx_gui_emu/RX/common/vtx.hpp", "max_forks_repo_name": "hirakuni45/glfw3_app", "max_forks_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T04:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T17:24:32.000Z", "avg_line_length": 30.4401544402, "max_line_length": 177, "alphanum_fraction": 0.4536022324, "num_tokens": 12316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.04813677401838861, "lm_q1q2_score": 0.01799717599170027}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2020 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include <debug.h>\n\n#include \"Bullet2d3DR.hpp\"\n#include <RigidBody2dDS.hpp>\n#include <Interaction.hpp>\n\n#if defined(__clang__)\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunreachable-code\"\n#pragma clang diagnostic ignored \"-Woverloaded-virtual\"\n#elif !(__INTEL_COMPILER || __APPLE__ )\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Woverloaded-virtual\"\n#endif\n\n#include <BulletCollision/NarrowPhaseCollision/btManifoldPoint.h>\n#include <BulletCollision/CollisionDispatch/btCollisionObject.h>\n\n#include <btBulletCollisionCommon.h>\n\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#elif !(__INTEL_COMPILER || __APPLE__ )\n#pragma GCC diagnostic pop\n#endif\n\n#include <boost/math/quaternion.hpp>\n\n//static\n//void copyQuatRot2d(boost::math::quaternion<double>& from, SiconosVector& to)\n//{\n//  double angle = 2.0 * acos(from.R_component_1());\n//  to(2) = angle;\n//}\n\nstatic\nvoid copyQuatRot2d(const SiconosVector& from, boost::math::quaternion<double>& to)\n{\n  double half_angle = from(2)/2.0;\n\n  to = boost::math::quaternion<double>(cos(half_angle), 0.0, 0.0, sin(half_angle));\n}\n\nstatic\nvoid copyQuatPos2d(const boost::math::quaternion<double>& from, SiconosVector& to)\n{\n  to(0) = from.R_component_2();\n  to(1) = from.R_component_3();\n}\n\nstatic\nvoid copyQuatPos2d(const SiconosVector& from, boost::math::quaternion<double>& to)\n{\n  to = boost::math::quaternion<double>(0, from(0), from(1), 0.0);\n}\n\nstatic\nvoid copyQuatPos2d(const btVector3& from, boost::math::quaternion<double>& to)\n{\n  to = boost::math::quaternion<double>(0, from.x(), from.y(), 0.0);\n}\n\nstatic void copyBtVector32d(const btVector3 &from, SiconosVector& to)\n{\n  to(0) = from.x();\n  to(1) = from.y();\n}\n\nBullet2d3DR::Bullet2d3DR()\n  : Contact2d3DR()\n{\n}\n\n#ifdef DEBUG_MESSAGES\nstatic\nvoid display_quat(boost::math::quaternion<double>& quat)\n{\n  std::cout << \"q_0: \" << quat.R_component_1()\n            << \" q_1: \" << quat.R_component_2()\n            << \" q_2: \" << quat.R_component_3()\n            << \" q_3: \" << quat.R_component_4() << std::endl;\n}\n#endif\n\nvoid Bullet2d3DR::updateContactPointsFromManifoldPoint(const btPersistentManifold& manifold,\n    const btManifoldPoint& point,\n    bool flip, double scaling,\n    SP::RigidBody2dDS ds1,\n    SP::RigidBody2dDS ds2)\n{\n  DEBUG_BEGIN(\"Bullet2d3DR::updateContactPointsFromManifoldPoint(...)\\n\");\n  // Get new world positions of contact points and calculate relative\n  // to ds1 and ds2\n\n  DEBUG_PRINTF(\"point.getPositionWorldOnA().x() = %8.5e\\t\", point.getPositionWorldOnA().x());\n  DEBUG_PRINTF(\"point.getPositionWorldOnA().y() = %8.5e\\t\", point.getPositionWorldOnA().y());\n  DEBUG_PRINTF(\"point.getPositionWorldOnA().z() = %8.5e\\n\", point.getPositionWorldOnA().z());\n\n  DEBUG_PRINTF(\"point.getPositionWorldOnB().x() = %8.5e\\t\", point.getPositionWorldOnB().x());\n  DEBUG_PRINTF(\"point.getPositionWorldOnB().y() = %8.5e\\t\", point.getPositionWorldOnB().y());\n  DEBUG_PRINTF(\"point.getPositionWorldOnB().z() = %8.5e\\n\", point.getPositionWorldOnB().z());\n\n  DEBUG_PRINTF(\"point.m_normalWorldOnB.x() = %8.5e\\t\", point.m_normalWorldOnB.x());\n  DEBUG_PRINTF(\"point.m_normalWorldOnB.y() = %8.5e\\t\", point.m_normalWorldOnB.y());\n  DEBUG_PRINTF(\"point.m_normalWorldOnB.z() = %8.5e\\n\", point.m_normalWorldOnB.z());\n\n\n  ::boost::math::quaternion<double> rq1, rq2, posa;\n  ::boost::math::quaternion<double> pq1, pq2, posb;\n\n\n  /* Compute quaternion representation of the position of ds1 and the rotation */\n  DEBUG_EXPR(ds1->q()->display(););\n  copyQuatPos2d(*ds1->q(), pq1);\n\n  copyQuatRot2d(*ds1->q(), rq1);\n  DEBUG_EXPR(display_quat(pq1););\n  DEBUG_EXPR(display_quat(rq1););\n\n\n  if(ds2)\n  {\n    DEBUG_EXPR(ds2->q()->display(););\n    copyQuatPos2d(*ds2->q(), pq2);\n    copyQuatRot2d(*ds2->q(), rq2);\n  }\n\n\n  /* Compute a quaternion representation of the position of the contact points\n   * to prepare rotations\n   * posa : global position of the contact point A on ds1 if flip =0\n   * posb : global position of the contact point B on ds2 if flip =0\n   */\n  copyQuatPos2d(point.getPositionWorldOnA() / scaling, posa);\n  copyQuatPos2d(point.getPositionWorldOnB() / scaling, posb);\n\n\n  if(flip)\n  {\n    ::boost::math::quaternion<double> tmp = posa;\n    posa = posb;\n    posb = tmp;\n  }\n\n  /* after flips :\n   * posa : global position of the contact point A on ds1\n   * posb : global position of the contact point B on ds2\n   */\n  DEBUG_EXPR(display_quat(posa););\n  DEBUG_EXPR(display_quat(posb););\n\n\n  SiconosVector va(2), vb(2);\n  if(flip)\n  {\n    /* Rotate the relatice position of the contact point */\n    copyQuatPos2d((1.0/rq1) * (posa - pq1) * rq1, va);\n\n    if(ds2)\n      copyQuatPos2d((1.0/rq2) * (posb - pq2) * rq2, vb);\n    else\n    {\n      // If no body2, position is relative to 0,0,0\n      copyBtVector32d(point.getPositionWorldOnA() / scaling, vb);\n    }\n  }\n  else\n  {\n    copyQuatPos2d((1.0/rq1) * (posa - pq1) * rq1, va);\n    if(ds2)\n      copyQuatPos2d((1.0/rq2) * (posb - pq2) * rq2, vb);\n    else\n    {\n      // If no body2, position is relative to 0,0,0\n      copyBtVector32d(point.getPositionWorldOnB() / scaling, vb);\n    }\n  }\n\n\n\n  SiconosVector vn(3);\n  // Get new normal\n  if(ds2)\n  {\n    btQuaternion qn(point.m_normalWorldOnB.x(),\n                    point.m_normalWorldOnB.y(),\n                    point.m_normalWorldOnB.z(), 0);\n    btQuaternion qb1 = manifold.getBody1()->getWorldTransform().getRotation();\n    // un-rotate normal into body1 frame\n    qn = qb1.inverse() * qn * qb1;\n    vn(0) = qn.x();\n    vn(1) = qn.y();\n    vn(2) = qn.z();\n    vn = vn/vn.norm2();\n  }\n  else\n    copyBtVector32d(point.m_normalWorldOnB, vn);\n\n  vn.resize(2);\n  DEBUG_EXPR(va.display(););\n  DEBUG_EXPR(vb.display(););\n  DEBUG_EXPR(vn.display(););\n  Contact2d3DR::updateContactPoints(va, vb, vn*(flip?-1:1));\n  DEBUG_END(\"Bullet2d3DR::updateContactPointsFromManifoldPoint(...)\\n\");\n}\n", "meta": {"hexsha": "eb0215dfd9774c97adcb4ee1e9a98d643597d3be", "size": 6585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mechanics/src/collision/bullet/Bullet2d3DR.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mechanics/src/collision/bullet/Bullet2d3DR.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mechanics/src/collision/bullet/Bullet2d3DR.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0088105727, "max_line_length": 93, "alphanum_fraction": 0.6804859529, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716967, "lm_q2_score": 0.04813676582520185, "lm_q1q2_score": 0.01799717292846583}}
{"text": "// Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.\n\n// Boost Software License - Version 1.0 - August 17th, 2003\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//  Authors: Thejaka Kanewala\n//           Marcin Zalewski\n//           Andrew Lumsdaine\n\n//======== Maximal Independent Set Algortihms================//\n// Driver for MIS family of algorithms.\n//===========================================================//\n\n\n#include <iostream>\n#include \"common/synthetic_generator.hpp\"\n#include \"common/parser.hpp\"\n#include \"common/executor.hpp\"\n#include \"common/vertex_permutations.hpp\"\n#include <boost/graph/distributed/mis_delta.hpp>\n#include <boost/graph/distributed/mis.hpp>\n#include <boost/graph/distributed/luby_mis.hpp>\n#include <boost/graph/distributed/thread_pq_def.hpp>\n\n\nenum mis_algorithm {\n  fix,\n  fix_bucket,\n  luby_a,\n  luby_av1,\n  luby_av2,\n  luby_b\n};\n\n\nclass mis_instance_params {\n\npublic:\n  mis_algorithm algorithm;\n  id_distribution_t id_distribution;\n  bool verify;\n  mis_instance_params(mis_algorithm& alg,\n\t\t      id_distribution_t& idd,\n\t\t      bool v):\n    algorithm(alg), id_distribution(idd), verify(v){}\n\n  void print() {\n      std::cout << \"Algorithm -- \";\n      if (algorithm == fix) \n\tstd::cout << \"FIX\";\n      else if(algorithm == fix_bucket)\n\tstd::cout << \"FIX-Bucket\";\n      else if(algorithm == luby_a)\n\tstd::cout << \"Luby A\";\n      else if(algorithm == luby_av1)\n\tstd::cout << \"Luby AV1\";\n      else if(algorithm == luby_av2)\n\tstd::cout << \"Luby AV2\";\n      else if(algorithm == luby_b)\n\tstd::cout << \"Luby B\";\n      else\n\tstd::cerr << \"Invalid !\" << std::endl;\n\n      std::cout << std::endl;\n\n\n    if (id_distribution == vertical)\n      std::cout << \"id distribution : vertical\" << std::endl;\n\n    if (id_distribution == horizontal)\n      std::cout << \"id distribution : horizontal\" << std::endl;\n    \n    std::cout << \"verify : \" << verify << std::endl;\n  }\n\n  std::string get_algorithm() {\n    if (algorithm == fix) \n      return \"FIX\";\n    else if(algorithm == fix_bucket)\n      return \"FIX-Bucket\";\n    else if(algorithm == luby_a)\n      return \"Luby A\";\n    else if(algorithm == luby_av1)\n      return \"Luby AV1\";\n    else if(algorithm == luby_av2)\n      return \"Luby AV2\";\n    else if(algorithm == luby_b)\n      return \"Luby B\";\n    else\n      return \"Invalid !\";\n  }\n\n};\n\n\nclass mis_params {\n\nprivate:\n  std::vector<mis_instance_params> instance_params;\n  std::vector<mis_algorithm> algorithms;\n  id_distribution_t id_distribution = horizontal; // default\n  bool verify = false;\n\npublic:\n  bool parse(int argc, char* argv[]){\n    for (int i = 1; i < argc; ++i) {\n      mis_algorithm algorithm;\n      std::string arg = argv[i];\n      if (arg == \"--run_fix_mis\") {\n\talgorithm = fix;\n\talgorithms.push_back(algorithm);\n      }\n\n      if (arg == \"--run_bucket_mis\") {\n\talgorithm = fix_bucket;\n\talgorithms.push_back(algorithm);\n      }\n\n      if (arg == \"--id-distribution\") {\n\tif (strcmp(argv[i+1],\"vertical\") == 0)\n\t  id_distribution = vertical;\n\telse if (strcmp(argv[i+1],\"horizontal\") == 0)\n\t  id_distribution = horizontal;\n\telse {\n\t  std::cout << \"Invalid id distribution type. Available types are vertical and horizontal\" \n\t\t    << std::endl;\n\t  return false;\n\t}\n      }\n\n      if (arg == \"--verify\") {\n\tverify = true;\n      }\n\n      if (arg == \"--luby_algorithms\") {\n\tstd::vector<std::string> luby_algorithms;\n\tluby_algorithms = extract_params<std::string> ( argv[i+1] );\n\tBOOST_FOREACH(std::string al, luby_algorithms) {\n\t  if (al == \"A\") \n\t    algorithm = luby_a;\n\t  else if (al == \"AV1\")\n\t    algorithm = luby_av1;\n\t  else if (al == \"AV2\")\n\t    algorithm = luby_av2;\n\t  else if (al == \"B\")\n\t    algorithm = luby_b;\n\t  else {\n\t    std::cerr << \"Invalid Luby algorithm. Available algorithms --\"\n\t\t      << \"A, AV1, AV2, B\" << std::endl;\n\t    return false;\n\t  }\n\n\t  algorithms.push_back(algorithm);\n\t}\n      }\n    }\n  }\n\n  void print() {\n    BOOST_FOREACH(mis_algorithm alg, algorithms) {\n      std::cout << \"Algorithm -- \";\n      if (alg == fix) \n\tstd::cout << \"FIX\";\n      else if(alg == fix_bucket)\n\tstd::cout << \"FIX-Bucket\";\n      else if(alg == luby_a)\n\tstd::cout << \"Luby A\";\n      else if(alg == luby_av1)\n\tstd::cout << \"Luby AV1\";\n      else if(alg == luby_av2)\n\tstd::cout << \"Luby AV2\";\n      else if(alg == luby_b)\n\tstd::cout << \"Luby B\";\n      else\n\tstd::cerr << \"Invalid !\" << std::endl;\n\n      std::cout << std::endl;\n    }\n\n    if (id_distribution == vertical)\n      std::cout << \"id distribution : vertical\" << std::endl;\n\n    if (id_distribution == horizontal)\n      std::cout << \"id distribution : horizontal\" << std::endl;\n    \n    std::cout << \"verify : \" << verify << std::endl;\n  }\n\n  const std::vector<mis_instance_params>&\n  get_instance_params() {\n    if (instance_params.empty()) {\n      BOOST_FOREACH(mis_algorithm alg, algorithms) {\n\tinstance_params.push_back(mis_instance_params(alg, id_distribution, verify));\n      }\n    }\n\n    return instance_params;\n  }\n  \n};\n\nclass MISExecutor {\nprivate:\n\n  template <typename Graph, typename MISMap>\n  bool verify_mis(amplusplus::transport& trans,  Graph& g, MISMap& mis) {\n    typedef typename boost::property_map<Graph, boost::vertex_owner_t>::const_type OwnerMap;\n    OwnerMap owner(get(boost::vertex_owner, g));\n\n    mis.set_consistency_model(boost::parallel::cm_forward || boost::parallel::cm_backward);\n    mis.set_max_ghost_cells(0);\n\n    if (trans.rank() == 0) std::cout<<\"Verifying MIS results......\";\n\n    {\n      amplusplus::scoped_epoch epoch(g.transport());\n\t  \n      BGL_FORALL_VERTICES_T(v, g, Graph) {\n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t  get(mis, target(e, g));\n\t}\n      }\n    }\n\t    \n    bool result = true;\n    int found_mis = 0;\n#ifdef PRINT_DEBUG\n    std::cout << \"MIS = {\";\n#endif\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      if (get(mis, v) ==  MIS_FIX1) {// v in mis, none of the neigbours should be in mis\n#ifdef PRINT_DEBUG\n\tif (v == 35) {\n\t  std::cout << \"Printing all neighbors of \" << v\n\t\t    << \" -- [\";\n\n\t  BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t    std::cout << target(e, g) << \", \";\n\t  }\n\t  std::cout << \"]\" << std::endl;\n\t}\n\n\tstd::cout << v << \"-[\";\n#endif\n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n#ifdef PRINT_DEBUG\n\t  std::cout << target(e, g) << \", \";\n#endif\n\t  if (v == target(e, g))\n\t    continue;\n\n\t  if (get(mis, target(e, g)) == MIS_FIX1) {\n\t    std::cout << \"[FAIL] Vertex : \" << v << \" and its neigbour \" << target(e, g)\n\t\t      << \" are both in MIS.\" \n\t\t      << \" Vertex value : \" << get(mis, v)\n\t\t      << \" neighbor value : \" << get(mis, target(e, g)) \n\t\t      << std::endl;\n\t    std::cout << \"Neighbors of \" << v << \"- {\";\n\t    BGL_FORALL_ADJ_T(v, u1, g, Graph) {\n\t      std::cout << \"(\" << u1 << \", \" << get(mis, u1) << \")\";\n\t    }\n\t    std::cout << \"}\" << std::endl;\n\n\t    auto k = target(e, g);\n\t    if (get(owner, k) == g.transport().rank()) {\n\t      std::cout << \"Neighbors of \" << k << \"- {\";\n\t      BGL_FORALL_ADJ_T(k, u2, g, Graph) {\n\t\tstd::cout << \"(\" << u2 << \", \" << get(mis, u2) << \")\";\n\t      }\n\t      std::cout << \"}\" << std::endl;\n\t    }\n\n\t    result = false;\n\t  } else {\n#ifdef PRINT_DEBUG\n\t    if (get(mis, target(e, g)) != MIS_FIX0) {\n\t      std::cout << \"vertex : \" \n\t\t\t<< target(e, g) \n\t\t\t<< \", is in \" \n\t\t\t<< get(mis, target(e, g))\n\t\t\t<< std::endl;\n\t    }\n#endif\n\n\t    // cannot be MIS_UNFIX\n\t    assert(get(mis, target(e, g)) == MIS_FIX0);\n\t    found_mis = 1;\n\t  }\n\t}\n#ifdef PRINT_DEBUG\n\tstd::cout << \"], \";\n#endif\n      } else {\n\t// if v is not in mis, at least one of its neighbors must\n\t// be in mis\n\tif (get(mis, v) != MIS_FIX0) {\n\t  std::cout << \"[ERROR] Vertex - \" << v << \" is in \" << get(mis, v)\n\t\t    << std::endl;\n\t}\n\n\tif (get(mis, v) != MIS_FIX0) {\n\t  std::cout << \"Error : \" << v << \" is not in MIS_FIX0. But in \" << get(mis, v)\n\t\t    << \", owner of \" << v << \":\" << get(owner, v)\n\t\t    << \", current rank : \" << _RANK << std::endl;\n\t  BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t    auto k = target(e, g);\n\t    std::cout << \"neigbor : \" << k << \" mis : \" << get(mis, k)\n\t\t      << std::endl;\n\t  }\n\t}\n\tassert(get(mis, v) == MIS_FIX0);\n\n\tbool inmis = false;\n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t  if (v == target(e, g))\n\t    continue;\n\n\t  if (get(mis, target(e, g)) == MIS_FIX1) {\n\t    inmis = true;\n\t    break;\n\t  }\n\t}\n      \n\tif (!inmis) {\n\t  std::cout << \"Vertex : \" << v << \" and none of its neighbors is in MIS\" << std::endl;\n\t  assert(false);\n\t}\n      }\n    }\n#ifdef PRINT_DEBUG\n    std::cout << \"}\" << std::endl;\n#endif\n\n    // Run a reduction on found mis.\n    // We cannot expect every rank will have found_mis true.\n    // E.g:- rank0 - {0,1}, rank1 - {281474976710656, 281474976710657}\n    // If every vertex is connect to each other, a vertex (Lets say 0) will\n    // be in one rank. In the second rank all vertices are out of mis.\n    int or_found_mis = 0;\n    MPI_Allreduce(&found_mis, &or_found_mis, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n    if (or_found_mis == 0) {\n      std::cout << \"Did not find any MIS\" <<std::endl;\n      result = false;\n    }\n\n    return result;\n  }\n\n\n  // Luby Algorithms\n  template <typename SelectGenerator, typename Graph, \n\t    typename graph_create_params,\n\t    typename MessageGenerator>\n  time_type\n  run_luby_maximal_is(amplusplus::transport& trans, \n\t\t    amplusplus::transport& barrier_trans, \n\t\t    Graph& g,  \n\t\t    MessageGenerator msg_gen, \n\t\t    graph_create_params& gparams,\n\t\t    instance_params& runtime_params,\n\t\t    mis_instance_params& mis_params) {\n\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename boost::graph_traits<Graph>::vertices_size_type vertices_size_type;\n\n    typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMap;\n    typedef boost::iterator_property_map<typename std::vector<random_t>::iterator, VertexIndexMap>  RandomMap;\n\n    std::vector<state_t> misvec(num_vertices(g), MIS_UNFIX);\n    typedef boost::iterator_property_map<typename std::vector<state_t>::iterator, VertexIndexMap>  MISMap;\n    MISMap mis(misvec.begin(), get(boost::vertex_index, g));\n\n\n    // create a property map\n    std::vector<random_t> pivec(num_vertices(g), 0);\n    RandomMap rmap(pivec.begin(), get(boost::vertex_index, g)); // TODO remove copying\n\n    if (trans.rank() == 0)\n      std::cout << \"Initializing mis map ...\" << std::endl;\n\n    BGL_FORALL_VERTICES_T(v, g, Graph) \n      { put(mis, v, MIS_UNFIX); }\n\n    // TODO find why we need this ?\n    trans.set_nthreads(runtime_params.threads);\n\n    if (trans.rank() == 0)\n      std::cout << \"Creating algorithm instance ...\" << std::endl;\n\n    boost::graph::distributed::luby_mis<Graph, MISMap, RandomMap, \n\t\t\t\t\tSelectGenerator,\n\t\t\t\t\tMessageGenerator>\n      D(g, mis, rmap, gparams.n, trans, sched_getcpu(), msg_gen);\n    \n    trans.set_nthreads(1);\n\n    { amplusplus::scoped_epoch epoch(barrier_trans); }\n\n    // Many threads now\n    trans.set_nthreads(runtime_params.threads);\n\n    if (trans.rank() == 0)\n      std::cout << \"Invoking algorithm ...\" << std::endl;\n\n    boost::scoped_array<boost::thread> threads(new boost::thread[runtime_params.threads - 1]);\n    for (int i = 0; i < runtime_params.threads - 1; ++i) {\n      boost::thread thr(boost::ref(D), i + 1);\n      threads[i].swap(thr);\n    }\n\t  \n    D(0);\n    \n    for (int i = 0; i < runtime_params.threads - 1; ++i)\n      threads[i].join();\n\t  \n    time_type end = get_time();\n\n    if (trans.rank() == 0)\n      std::cout << \"Algorithm done ...\" << std::endl;\n\n#ifdef MIS_STATS\n    D.print_stats();\n#endif\n\n    time_type start = D.get_start_time();\n\n    // Back to one thread\n    trans.set_nthreads(1);\n    clear_thread_core_data();\n\n    if (mis_params.verify) {\n      if (trans.rank()==0)\n\tstd::cout << \"Verifying mis ...\" << std::endl;\n\n      if (!verify_mis(trans, g, mis)) {\n\tstd::cout << \"MIS Verification Failed\" << std::endl;\n\tassert(false);\n\treturn 0;\n      }\n    }\n\n    vertices_size_type visited = 0;\n    BGL_FORALL_VERTICES_T(v, g, Graph) { \n      if (get(mis, v) != MIS_UNFIX)\n\t++visited; \n    }\n\t  \n    boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > \n      r(trans, std::plus<vertices_size_type>());\n    vertices_size_type total = r(visited);\n\t  \n    if (mis_params.verify)\n      if (trans.rank() == 0)\n\tstd::cout << \"Visited \" << total << \" vertices of \" << gparams.n << \" in \" << print_time(end - start) \n\t\t  << std::endl;\n\n\t  \n    return end - start;\n  }\n\n\n  // FIX algorithms\n  template <typename Graph, typename IdDistribution, typename MessageGenerator, \n\t    typename graph_create_params,\n\t    typename PriorityQueueGenerator = boost::graph::distributed::thread_priority_queue_gen>\n  time_type\n  run_fix_mis(amplusplus::transport& trans, \n\t      amplusplus::transport& barrier_trans, \n\t      Graph& g,  \n\t      const IdDistribution& idd,\n\t      MessageGenerator msg_gen, \n\t      graph_create_params& gparams,\n\t      instance_params& runtime_params,\n\t      mis_instance_params& mis_params) { \n\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename boost::graph_traits<Graph>::vertices_size_type vertices_size_type;\n\n#ifdef MIS_DISTANCE_ORDERING\n    std::cout << \"Running with distance ordering ...\" << std::endl;\n#endif\n\n    if (trans.rank() == 0)\n      std::cout << \"Initializing mis map ...\" << std::endl;\n\n    std::vector<state_t> misvec(num_vertices(g), MIS_UNFIX);\n    typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMap;\n    typedef boost::iterator_property_map<typename std::vector<state_t>::iterator, VertexIndexMap>  MISMap;\n    MISMap mis(misvec.begin(), get(boost::vertex_index, g));\n\n    BGL_FORALL_VERTICES_T(v, g, Graph) \n      { put(mis, v, MIS_UNFIX); }\n\n    trans.set_nthreads(runtime_params.threads);\n\n    if (trans.rank() == 0)\n      std::cout << \"Creating algorithm instance ...\" << std::endl;\n\n    boost::graph::distributed::maximal_independent_set<Graph, MISMap, IdDistribution,\n\t\t\t\t\t\t       PriorityQueueGenerator, MessageGenerator>\n      D(g, mis, trans, idd, runtime_params.threads, sched_getcpu(), msg_gen);\n    \n    trans.set_nthreads(1);\n\n    { amplusplus::scoped_epoch epoch(barrier_trans); }\n\n    // Many threads now\n    trans.set_nthreads(runtime_params.threads);\n\n    if (trans.rank() == 0)\n      std::cout << \"Invoking algorithm ...\" << std::endl;\n\n    boost::scoped_array<boost::thread> threads(new boost::thread[runtime_params.threads - 1]);\n    for (int i = 0; i < runtime_params.threads - 1; ++i) {\n      boost::thread thr(boost::ref(D), i + 1);\n      threads[i].swap(thr);\n    }\n\t  \n    D(0);\n    \n    for (int i = 0; i < runtime_params.threads - 1; ++i)\n      threads[i].join();\n\t  \n    time_type end = get_time();\n\n    if (trans.rank() == 0)\n      std::cout << \"Algorithm done ...\" << std::endl;\n\n    time_type start = D.get_start_time();\n\n    // Back to one thread\n    trans.set_nthreads(1);\n    clear_thread_core_data();\n\n#ifdef MIS_PRIORITY\n#ifdef MIS_STATS\n    D.print_pq_sizes();\n#endif\n#endif\n\n#ifdef MIS_STATS\n    D.print_stats();\n#endif\n\n    if (mis_params.verify) {\n      if (trans.rank()==0)\n\tstd::cout << \"Verifying mis ...\" << std::endl;\n\n      if (!verify_mis(trans, g, mis)) {\n\tstd::cout << \"MIS Verification Failed\" << std::endl;\n\tassert(false);\n\treturn 0;\n      }\n    }\n\n    vertices_size_type visited = 0;\n    BGL_FORALL_VERTICES_T(v, g, Graph) { \n      if (get(mis, v) != MIS_UNFIX)\n\t++visited; \n    }\n\t  \n    boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > \n      r(trans, std::plus<vertices_size_type>());\n    vertices_size_type total = r(visited);\n\t  \n    if (mis_params.verify)\n      if (trans.rank() == 0)\n\tstd::cout << \"Visited \" << total << \" vertices of \" << gparams.n << \" in \" << print_time(end - start) \n\t\t  << std::endl;\n\n    //if (total < 100) return -1.;\n\t  \n    return end - start;\n  }\n\n\n  // FIX-Bucket algorithm\n  template <typename Graph, typename IdDistribution,\n\t    typename graph_create_params,\n\t    typename MessageGenerator>\n  time_type\n  run_fix_mis_bucket(amplusplus::transport& trans, \n\t\t     amplusplus::transport& barrier_trans, \n\t\t     Graph& g,  \n\t\t     const IdDistribution& idd,\n\t\t     MessageGenerator msg_gen, \n\t\t     graph_create_params& gparams,\n\t\t     instance_params& runtime_params,\n\t\t     mis_instance_params& mis_params) {\n\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename boost::graph_traits<Graph>::vertices_size_type vertices_size_type;\n\n    std::vector<state_t> misvec(num_vertices(g), MIS_UNFIX);\n    typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMap;\n    typedef boost::iterator_property_map<typename std::vector<state_t>::iterator, VertexIndexMap>  MISMap;\n    MISMap mis(misvec.begin(), get(boost::vertex_index, g));\n\n    if (trans.rank() == 0)\n      std::cout << \"Initializing mis-delta map ...\" << std::endl;\n\n    BGL_FORALL_VERTICES_T(v, g, Graph) \n      { put(mis, v, MIS_UNFIX); }\n\n    trans.set_nthreads(runtime_params.threads);\n\n    if (trans.rank() == 0)\n      std::cout << \"Creating algorithm instance ...\" << std::endl;\n\n    boost::graph::distributed::maximal_independent_set_delta<Graph, MISMap, IdDistribution,\n\t\t\t\t\t\t\t     append_buffer<Vertex, 10u>, MessageGenerator> \n      D(g, mis, trans, idd, runtime_params.flush, sched_getcpu(), msg_gen);\n    \n    trans.set_nthreads(1);\n\n    { amplusplus::scoped_epoch epoch(barrier_trans); }\n\n    \n    // Many threads now\n    trans.set_nthreads(runtime_params.threads);\n\n    if (trans.rank() == 0)\n      std::cout << \"Invoking algorithm ...\" << std::endl;\n\n    boost::scoped_array<boost::thread> threads(new boost::thread[runtime_params.threads - 1]);\n    for (int i = 0; i < runtime_params.threads - 1; ++i) {\n      boost::thread thr(boost::ref(D), i + 1);\n      threads[i].swap(thr);\n    }\n\t  \n    D(0);\n    \n    for (int i = 0; i < runtime_params.threads - 1; ++i)\n      threads[i].join();\n\t  \n    time_type end = get_time();\n\n    if (trans.rank() == 0)\n      std::cout << \"Algorithm done ...\" << std::endl;\n\n    time_type start = D.get_start_time();\n\n#ifdef MIS_STATS\n    D.print_stats();\n#endif\n\n    // Back to one thread\n    trans.set_nthreads(1);\n    clear_thread_core_data();\n\n    if (mis_params.verify) {\n      if (trans.rank()==0)\n\tstd::cout << \"Verifying delta mis ...\" << std::endl;\n\n      if (!verify_mis(trans, g, mis)) {\n\tstd::cout << \"Bucket-MIS Verification Failed\" << std::endl;\n\tassert(false);\n\treturn 0;\n      }\n    }\n\n    vertices_size_type visited = 0;\n    BGL_FORALL_VERTICES_T(v, g, Graph) { \n      if (get(mis, v) != MIS_UNFIX)\n\t++visited; \n    }\n\t  \n    boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > \n      r(trans, std::plus<vertices_size_type>());\n    vertices_size_type total = r(visited);\n\t  \n    if (mis_params.verify)\n      if (trans.rank() == 0)\n\tstd::cout << \"Visited \" << total << \" vertices of \" << gparams.n << \" in \" << print_time(end - start) \n\t\t  << std::endl;\n\n    return end - start;\n  }\n\n\npublic:\n  template <typename Graph, typename MessageGenerator,\n\t    typename graph_create_params>\n  time_type operator()(const Graph& g, \n\t\t       amplusplus::transport& trans, \n\t\t       MessageGenerator& msg_gen,\n\t\t       graph_create_params& gparams,\n\t\t       instance_params& runtime_params,\n\t\t       mis_instance_params& mis_params) { // remove\n\n    if (mis_params.algorithm == fix_bucket) {\n      amplusplus::transport barrier_trans = trans.clone();\n      if (mis_params.id_distribution == vertical) {\n\treturn run_fix_mis_bucket(trans,\n\t\t\t\t  barrier_trans,\n\t\t\t\t  g,\n\t\t\t\t  block_id_distribution<Graph>(g, gparams.n),\n\t\t\t\t  msg_gen,\n\t\t\t\t  gparams,\n\t\t\t\t  runtime_params,\n\t\t\t\t  mis_params); \n      } else if (mis_params.id_distribution == horizontal) {\n\treturn run_fix_mis_bucket(trans,\n\t\t\t\t  barrier_trans,\n\t\t\t\t  g,\n\t\t\t\t  row_id_distribution<Graph>(g, trans.size()),\n\t\t\t\t  msg_gen,\n\t\t\t\t  gparams,\n\t\t\t\t  runtime_params,\n\t\t\t\t  mis_params); \n\n      } else {\n\tstd::cerr << \"Invalid id distribution ! \" << std::endl;\n\tassert(false);\n      }\n\t\t\t\t   \n\n    }\n\n    if (mis_params.algorithm == fix) {\n      amplusplus::transport barrier_trans = trans.clone();\n\n      if (mis_params.id_distribution == vertical) {\n\treturn run_fix_mis(trans,\n\t\t\t   barrier_trans,\n\t\t\t   g,\n\t\t\t   block_id_distribution<Graph>(g, gparams.n),\n\t\t\t   msg_gen,\n\t\t\t   gparams,\n\t\t\t   runtime_params,\n\t\t\t   mis_params); //remove\n      } else if (mis_params.id_distribution == horizontal) {\n\treturn run_fix_mis(trans,\n\t\t\t   barrier_trans,\n\t\t\t   g,\n\t\t\t   row_id_distribution<Graph>(g, trans.size()),\n\t\t\t   msg_gen,\n\t\t\t   gparams,\n\t\t\t   runtime_params,\n\t\t\t   mis_params); //remove\n\n      } else {\n\tstd::cerr << \"Invalid id distribution ! \" << std::endl;\n\tassert(false);\n      }\n    }\n\n\n    if (mis_params.algorithm == luby_a) {\n      amplusplus::transport barrier_trans = trans.clone();\n      return run_luby_maximal_is<boost::graph::distributed::select_a_functor_gen>(trans,\n\t\t\t\t\t\t\t\t\t\t  barrier_trans,\n\t\t\t\t\t\t\t\t\t\t  g,\n\t\t\t\t\t\t\t\t\t\t  msg_gen,\n\t\t\t\t\t\t\t\t\t\t  gparams,\n\t\t\t\t\t\t\t\t\t\t  runtime_params,\n\t\t\t\t\t\t\t\t\t\t  mis_params);\n\n    }\n\n    if (mis_params.algorithm == luby_av1) {\n      amplusplus::transport barrier_trans = trans.clone();\n      return run_luby_maximal_is<boost::graph::distributed::select_a_vertex_functor_gen>(trans,\n\t\t\t\t\t\t\t\t\t\t  barrier_trans,\n\t\t\t\t\t\t\t\t\t\t  g,\n\t\t\t\t\t\t\t\t\t\t  msg_gen,\n\t\t\t\t\t\t\t\t\t\t  gparams,\n\t\t\t\t\t\t\t\t\t\t  runtime_params,\n\t\t\t\t\t\t\t\t\t\t  mis_params);\n\n    }\n\n\n    if (mis_params.algorithm == luby_av2) {\n      amplusplus::transport barrier_trans = trans.clone();\n      return run_luby_maximal_is<boost::graph::distributed::select_a_v2_functor_gen>(trans,\n\t\t\t\t\t\t\t\t\t\t  barrier_trans,\n\t\t\t\t\t\t\t\t\t\t  g,\n\t\t\t\t\t\t\t\t\t\t  msg_gen,\n\t\t\t\t\t\t\t\t\t\t  gparams,\n\t\t\t\t\t\t\t\t\t\t  runtime_params,\n\t\t\t\t\t\t\t\t\t\t  mis_params);\n\n    }\n\n    if (mis_params.algorithm == luby_b) {\n      amplusplus::transport barrier_trans = trans.clone();\n      return run_luby_maximal_is<boost::graph::distributed::select_b_functor_gen>(trans,\n\t\t\t\t\t\t\t\t\t\t  barrier_trans,\n\t\t\t\t\t\t\t\t\t\t  g,\n\t\t\t\t\t\t\t\t\t\t  msg_gen,\n\t\t\t\t\t\t\t\t\t\t  gparams,\n\t\t\t\t\t\t\t\t\t\t  runtime_params,\n\t\t\t\t\t\t\t\t\t\t  mis_params);\n\n    }\n\n\n\n\n    \n  }\n\n};\n\n\nint main(int argc, char* argv[]) {\n  std::cout << \"printing core id for process ...\" << std::endl;\n  print_core_id();\n\n  executor<MISExecutor, mis_params, mis_instance_params> mis_executor;\n  mis_executor.execute(argc, argv);  \n  \n}\n", "meta": {"hexsha": "55728fe86fe44d8bf3ff277602754fd0f3ab14eb", "size": 23601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph_parallel/drivers/mis_family.cpp", "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": "libs/graph_parallel/drivers/mis_family.cpp", "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": "libs/graph_parallel/drivers/mis_family.cpp", "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": 28.1971326165, "max_line_length": 110, "alphanum_fraction": 0.6196771323, "num_tokens": 6282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082131381216084, "lm_q2_score": 0.055823137207643155, "lm_q1q2_score": 0.017909252220072596}}
{"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/*\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\nnamespace boost {\n\n  template <class Visitor, class Graph>\n  struct BellmanFordVisitorConcept {\n    void constraints() {\n      function_requires< 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    function_requires<EdgeListGraphConcept<EdgeListGraph> >();\n    typedef graph_traits<EdgeListGraph> GTraits;\n    typedef typename GTraits::edge_descriptor Edge;\n    typedef typename GTraits::vertex_descriptor Vertex;\n    function_requires<ReadWritePropertyMapConcept<DistanceMap, Vertex> >();\n    function_requires<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 (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 (tie(i, end) = edges(g); i != end; ++i)\n      if (compare(combine(get(distance, source(*i, g)), \n                          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 <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      typedef typename property_traits<DistanceMap>::value_type D;\n      bellman_visitor<> null_vis;\n      dummy_property_map dummy_pred;\n      return bellman_ford_shortest_paths\n        (g, N, weight, \n         choose_param(get_param(params, vertex_predecessor), dummy_pred),\n         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  } // 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} // namespace boost\n\n#endif // BOOST_GRAPH_BELLMAN_FORD_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "174f38b81279bad8122726ffa60701f80eeaa5fa", "size": 7051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rd party/boost/boost/graph/bellman_ford_shortest_paths.hpp", "max_stars_repo_name": "OLR-xray/OLR-3.0", "max_stars_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/bellman_ford_shortest_paths.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/graph/bellman_ford_shortest_paths.hpp", "max_forks_repo_name": "Imperator-Knoedel/Sunset", "max_forks_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 35.255, "max_line_length": 75, "alphanum_fraction": 0.6482768402, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.05033063117300158, "lm_q1q2_score": 0.01790637494604844}}
{"text": "//----------------------------------*-C++-*----------------------------------//\n/**\n *  @file   Material.hh\n *  @author Jeremy Roberts\n *  @brief  Material class definition.\n */\n//---------------------------------------------------------------------------//\n\n#ifndef detran_material_MATERIAL_HH_\n#define detran_material_MATERIAL_HH_\n\n#include \"material/material_export.hh\"\n#include \"utilities/Definitions.hh\"\n#include \"utilities/SP.hh\"\n#include <string>\n#ifdef DETRAN_ENABLE_BOOST\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/serialization/vector.hpp>\n#endif\n\nnamespace detran_material\n{\n\n//---------------------------------------------------------------------------//\n/**\n *  @class Material\n *  @brief Simple cross section container.\n *\n *  All data is stored with the material index changing fastest.  This\n *  appears to be the best storage scheme with respect to memory access.\n */\n//---------------------------------------------------------------------------//\nclass MATERIAL_EXPORT Material\n{\n\npublic:\n\n  //-------------------------------------------------------------------------//\n  // TYPEDEFS\n  //-------------------------------------------------------------------------//\n\n  typedef detran_utilities::SP<Material> SP_material;\n  typedef detran_utilities::vec_dbl      vec_dbl;\n  typedef detran_utilities::vec2_dbl     vec2_dbl;\n  typedef detran_utilities::vec3_dbl     vec3_dbl;\n  typedef detran_utilities::vec_int      vec_int;\n  typedef detran_utilities::vec2_int     vec2_int;\n  typedef detran_utilities::vec_size_t   vec_size_t;\n  typedef detran_utilities::vec2_size_t  vec2_size_t;\n  typedef detran_utilities::size_t       size_t;\n\n  //-------------------------------------------------------------------------//\n  // PUBLIC INTERFACE\n  //-------------------------------------------------------------------------//\n\n  /**\n   *  @brief Constructor.\n   *  @param    number_materials    Number of materials.\n   *  @param    number_groups       Number of energy groups.\n   *  @param    downscatter         Switch on to use only downscatter.\n   */\n  Material(const size_t number_materials,\n           const size_t number_groups,\n           std::string  name = \"no name given\");\n\n  /// Virtual destructor\n  virtual ~Material(){}\n\n  /// SP constructor\n  static SP_material Create(const size_t number_materials,\n                            const size_t number_groups,\n                            std::string  name = \"no name given\");\n\n  //--------------------------------------------------------------------------//\n  // Setters\n  //--------------------------------------------------------------------------//\n\n  /**\n   *  @brief Explicitly turn on downscatter-only\n   */\n  void set_downscatter(bool v, bool tran = false)\n  {\n    if (tran) d_downscatter[1] = v;\n    d_downscatter[0] = v;\n    if (d_finalized) finalize();\n  }\n\n  void set_sigma_t(size_t m, size_t g, double v);\n  void set_sigma_a(size_t m, size_t g, double v);\n  void set_nu_sigma_f(size_t m, size_t g, double v);\n  void set_sigma_f(size_t m, size_t g, double v);\n  void set_nu(size_t m, size_t g, double v);\n  void set_chi(size_t m, size_t g, double v);\n  void set_sigma_s(size_t m, size_t g, size_t gp, double v);\n  void set_diff_coef(size_t m, size_t g, double v);\n\n  // Vectorized setters\n\n  void set_sigma_t(size_t m, vec_dbl &v);\n  void set_sigma_a(size_t m, vec_dbl &v);\n  void set_nu_sigma_f(size_t m, vec_dbl &v);\n  void set_sigma_f(size_t m, vec_dbl &v);\n  void set_nu(size_t m, vec_dbl &v);\n  void set_chi(size_t m, vec_dbl &v);\n  void set_sigma_s(size_t m, size_t g, vec_dbl &v);\n  void set_diff_coef(size_t m, vec_dbl &v);\n\n  //------------------------------------------------------------------------//\n  // Getters\n  //------------------------------------------------------------------------//\n\n  virtual double sigma_t(size_t m, size_t g) const;\n  virtual double sigma_a(size_t m, size_t g) const;\n  virtual double nu_sigma_f(size_t m, size_t g) const;\n  virtual double sigma_f(size_t m, size_t g) const;\n  virtual double nu(size_t m, size_t g) const;\n  virtual double chi(size_t m, size_t g) const;\n  virtual double sigma_s(size_t m, size_t g, size_t gp) const;\n  virtual double diff_coef(size_t m, size_t g) const;\n\n  // Vectorized getters\n\n  virtual vec_dbl sigma_t(size_t m) const;\n  virtual vec_dbl sigma_a(size_t m) const;\n  virtual vec_dbl nu_sigma_f(size_t m) const;\n  virtual vec_dbl sigma_f(size_t m) const;\n  virtual vec_dbl nu(size_t m) const;\n  virtual vec_dbl chi(size_t m) const;\n  virtual vec2_dbl sigma_s(size_t m) const;\n  virtual vec_dbl diff_coef(size_t m) const;\n\n  //------------------------------------------------------------------------//\n  // OTHER ACCESSORS\n  //------------------------------------------------------------------------//\n\n  size_t number_groups() const\n  {\n    return d_number_groups;\n  }\n\n  size_t number_materials() const\n  {\n    return d_number_materials;\n  }\n\n  /**\n   *  @brief Lower scatter group bound.\n   *\n   *  This is the *lowest* index (highest energy) \\f$ g' \\f$\n   *  that leads to downscatter for a given outgoing group \\f$ g \\f$.\n   *\n   *  @param g        Row of the scattering matrix\n   *  @param tran     Flag for accessing transpose of S\n   */\n  size_t lower(size_t g, bool tran = false) const;\n\n  /**\n   *  @brief Upper scatter group bound.\n   *\n   *  This is the *highest* index (lowest energy) \\f$ g' \\f$\n   *  that upscatters size_to the outgoing group \\f$ g \\f$.\n   *\n   *  @param g        Row of the scattering matrix\n   *  @param tran     Flag for accessing transpose of S\n   */\n  size_t upper(size_t g, bool tran = false) const;\n\n  /// Do we do only downscatter?\n  bool downscatter(bool tran = false) const;\n\n  /**\n   *  @brief Index below which upscatter doesn't occur for any material.\n   *\n   *  For adjoint problems, this is the group above which\n   */\n  size_t upscatter_cutoff(bool tran = false) const;\n\n  /**\n   *  @brief Compute the absorption cross section from total and scattering.\n   *  @note this overwrites any data for \\f$ \\Sigma_a \\f$ already stored.\n   */\n  void compute_sigma_a();\n\n  /**\n   *  @brief Compute the diffusion coefficient from \\f$ \\Sigma_t \\f$.\n   *\n   *  Assuming isotropic scattering in the LAB, the diffusion\n   *  coefficient is simply \\f$ D = 1/3\\Sigma_t \\f$.\n   *\n   *  @todo Update diffusion definition if anisotropic scattering\n   *        is added.\n   *  @note This overwrites any data for \\f$ D \\f$ already stored.\n   */\n  void compute_diff_coef();\n\n  /// Computes scattering bounds and absorption cross section.\n  void finalize();\n\n  /// Pretty print the material database.\n  virtual void display();\n\nprotected:\n\n  //-------------------------------------------------------------------------//\n  // DATA\n  //-------------------------------------------------------------------------//\n\n  /// Material name\n  std::string d_name;\n  /// Number of groups\n  size_t d_number_groups;\n  /// Number of materials\n  size_t d_number_materials;\n  /// Downscatter switch (when true, upscatter ignored)\n  bool d_downscatter[2];\n  /// Total cross section [material, group]\n  vec2_dbl d_sigma_t;\n  /// Absorption cross section [material, group]\n  vec2_dbl d_sigma_a;\n  /// nu * Fission [material, group]\n  vec2_dbl d_nu_sigma_f;\n  /// Fission [material, group]\n  vec2_dbl d_sigma_f;\n  /// nu [material, group]\n  vec2_dbl d_nu;\n  /// Fission spectrum [material, group]\n  vec2_dbl d_chi;\n  /// Scatter [material, group<-, group']\n  vec3_dbl d_sigma_s;\n  /// Diffusion coefficient [material, group]\n  vec2_dbl d_diff_coef;\n  /// Scatter bounds applied to all materials [group, 2]\n  vec2_size_t d_scatter_bounds;\n  /// Groups equal to or above cutoff are subject to upscatter iterations\n  size_t d_upscatter_cutoff[2];\n  /// Are we ready to be used?\n  bool d_finalized;\n\n  //-------------------------------------------------------------------------//\n  // IMPLEMENTATION\n  //-------------------------------------------------------------------------//\n\n  void material_display();\n\n#ifdef DETRAN_ENABLE_BOOST\n\n  /// Default constructor needed for serialization\n  Material(){}\n\n  friend class boost::serialization::access;\n\n  template<class Archive>\n  void serialize(Archive & ar, const unsigned int version)\n  {\n    ar & d_number_groups;\n    ar & d_number_materials;\n    ar & d_downscatter;\n    ar & d_sigma_t;\n    ar & d_sigma_a;\n    ar & d_nu_sigma_f;\n    ar & d_sigma_f;\n    ar & d_nu;\n    ar & d_chi;\n    ar & d_sigma_s;\n    ar & d_diff_coef;\n    ar & d_scatter_bounds;\n    ar & d_upscatter_cutoff;\n    ar & d_finalized;\n  }\n\n#endif\n\n};\n\nMATERIAL_TEMPLATE_EXPORT(detran_utilities::SP<Material>)\n\n} // end namespace detran_material\n\n//---------------------------------------------------------------------------//\n// INLINE FUNCTIONS\n//---------------------------------------------------------------------------//\n\n#include \"Material.i.hh\"\n\n#endif /* detran_material_MATERIAL_HH_ */\n", "meta": {"hexsha": "e91828d43df5049e8086a77f4e5f5ae8fe428131", "size": 9008, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/material/Material.hh", "max_stars_repo_name": "baklanovp/libdetran", "max_stars_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T16:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-10T13:40:16.000Z", "max_issues_repo_path": "src/material/Material.hh", "max_issues_repo_name": "baklanovp/libdetran", "max_issues_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T21:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T00:56:44.000Z", "max_forks_repo_path": "src/material/Material.hh", "max_forks_repo_name": "baklanovp/libdetran", "max_forks_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-03-07T16:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T00:14:23.000Z", "avg_line_length": 31.169550173, "max_line_length": 80, "alphanum_fraction": 0.5684946714, "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.047425871999493587, "lm_q1q2_score": 0.01790519543302405}}
{"text": "//============================================================================\n// Name        : Application.cpp\n// Author      : Rian van Gijlswijk\n// Description : Main application file.\n//============================================================================\n\n#include \"Application.h\"\n#include <string>\n#include <regex>\n#include <boost/log/core.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/expressions.hpp>\n#include <boost/log/utility/setup/file.hpp>\n#include \"Timer.cpp\"\n#include \"CommandLine.h\"\n#include \"../math/Matrix3d.h\"\n#include \"../exporter/JsonExporter.h\"\n#include \"../exporter/MatlabExporter.h\"\n#include \"../radio/AntennaFactory.h\"\n#include \"../radio/IsotropicAntenna.h\"\n\nnamespace raytracer {\nnamespace core {\n\n\tusing namespace std;\n\tusing namespace tracer;\n\tusing namespace exporter;\n\tusing namespace math;\n\tusing namespace threading;\n\tusing namespace radio;\n\n\tboost::mutex datasetMutex;\n\tboost::mutex tracingIncMutex;\n\n\tboost::threadpool::pool tp;\n\n\tvoid Application::init(int argc, char * argv[]) {\n\n\t\tBOOST_LOG_TRIVIAL(debug) << \"Init application\";\n\n\t\tAntennaFactory::printMappedTypes();\n\n\t\tparseCommandLineArgs(argc, argv);\n\t\tstart();\n\t\trun();\n\t}\n\n\tvoid Application::parseCommandLineArgs(int argc, char * argv[]) {\n\n\t\tBOOST_LOG_TRIVIAL(debug) << \"parseCommandLineArgs\";\n\n\t\tfor (int i = 0; i < argc; i++) {\n\n\t\t\tif (strcmp(argv[i], \"-h\") == 0) {\n\t\t\t\tstd::cout \t<< \"Ionospheric Ray Tracer\\n\\n\"\n\t\t\t\t\t\t\t<< \"Synopsis:\\n\"\n\t\t\t\t\t\t\t<< \"\\tirt [-opts] scenarioConfig\\n\\n\"\n\t\t\t\t\t\t\t<< \"Description: \\n\"\n\t\t\t\t\t\t\t<< \"\\tPerform ionospheric ray tracing on a celestial object described by the _celestialConfig json file. \"\n\t\t\t\t\t\t\t<< \"If no config file is supplied, use a default scenario.\\n\\n\"\n\t\t\t\t\t\t\t<< \"Options:\\n\"\n\t\t\t\t\t\t\t<< \"\\t-c | --config\\t Application config file\\n\"\n\t\t\t\t\t\t\t<< \"\\t-i | --iterations\\t The number of consecutive times every ray option should be run.\\n\"\n\t\t\t\t\t\t\t<< \"\\t-h | --help\\t This help.\\n\"\n\t\t\t\t\t\t\t<< \"\\t-o | --output\\t Path where output file should be stored.\\n\"\n\t\t\t\t\t\t\t<< \"\\t-p | --parallelism\\t Multithreading indicator.\\n\"\n\t\t\t\t\t\t\t<< \"\\t-v | --verbose\\t Verbose, display log output\\n\"\n\t\t\t\t\t\t\t<< \"\\t-vv \\t\\t Very verbose, display log and debug output\\n\";\n\t\t\t\tstd::exit(0);\n\n\t\t\t} else if (strcmp(argv[i], \"-s\") == 0 || strcmp(argv[i], \"--scenario\") == 0) {\n\t\t\t\t_celestialConfigFile = argv[i+1];\n\n\t\t\t} else if (strcmp(argv[i], \"-c\") == 0 || strcmp(argv[i], \"--config\") == 0) {\n\t\t\t\t_applicationConfigFile = argv[i+1];\n\n\t\t\t} else if (strcmp(argv[i], \"-p\") == 0 || strcmp(argv[i], \"--parallelism\") == 0) {\n\t\t\t\t_parallelism = atoi(argv[i+1]);\n\n\t\t\t} else if (strcmp(argv[i], \"-o\") == 0 || strcmp(argv[i], \"--output\") == 0) {\n\t\t\t\t_outputFile = argv[i+1];\n\n\t\t\t} else if (strcmp(argv[i], \"-i\") == 0 || strcmp(argv[i], \"--iterations\") == 0) {\n\t\t\t\t_iterations = atoi(argv[i+1]);\n\n\t\t\t} else if (strcmp(argv[i], \"-v\") == 0 || strcmp(argv[i], \"--verbose\") == 0) {\n\t\t\t\t_verbosity = boost::log::trivial::info;\n\n\t\t\t} else if (strcmp(argv[i], \"-vv\") == 0) {\n\t\t\t\t_verbosity = boost::log::trivial::debug;\n\n\t\t\t} else if (strcmp(argv[i], \"-fmin\") == 0) {\n\t\t\t\t_fmin = atoi(argv[i+1]);\n\n\t\t\t} else if (strcmp(argv[i], \"-fstep\") == 0) {\n\t\t\t\t_fstep = atoi(argv[i+1]);\n\n\t\t\t} else if (strcmp(argv[i], \"-fmax\") == 0) {\n\t\t\t\t_fmax = atoi(argv[i+1]);\n\n\t\t\t}\n\t\t}\n\n\t\t// load scenario config file. Must be given.\n\t\tif (!std::regex_match (argv[argc-1], std::regex(\"[A-Za-z0-9_/]+\\.json\") )) {\n\t\t\tBOOST_LOG_TRIVIAL(fatal) << \"No scenario file given! Exiting.\";\n\t\t\tstd::exit(0);\n\t\t}\n\t\t_celestialConfigFile = argv[argc-1];\n\t}\n\n\tvoid Application::start() {\n\n\t\tBOOST_LOG_TRIVIAL(debug) << \"Start application\";\n\n\t\t_isRunning = true;\n\n\t\t_applicationConfig = Config(_applicationConfigFile);\n\t\t_celestialConfig = Config(_celestialConfigFile);\n\n\t\tif (_parallelism < 1) {\n\t\t\t_parallelism = _applicationConfig.getInt(\"parallelism\");\n\t\t}\n\t\tif (_iterations < 1) {\n\t\t\t_iterations = _applicationConfig.getInt(\"iterations\");\n\t\t}\n\t\tif (_fmin < 1) {\n\t\t\t_fmin = _applicationConfig.getObject(\"frequencies\")[\"min\"].asInt();\n\t\t}\n\t\tif (_fstep < 1) {\n\t\t\t_fstep = _applicationConfig.getObject(\"frequencies\")[\"step\"].asInt();\n\t\t}\n\t\tif (_fmax < 1) {\n\t\t\t_fmax = _applicationConfig.getObject(\"frequencies\")[\"max\"].asInt();\n\t\t}\n\n//\t\tboost::log::add_file_log(\"log/sample.log\");\n\n\t\tboost::log::core::get()->set_filter(\n\t\t\t\tboost::log::trivial::severity >= _verbosity);\n\n\t\ttp = boost::threadpool::pool(_parallelism);\n\n\t\tBOOST_LOG_TRIVIAL(debug) << \"applicationConfig: \" << _applicationConfigFile << endl\n\t\t\t\t<< _applicationConfig << endl\n\t\t\t\t<< \"celestialConfig:\" << _celestialConfigFile << endl\n\t\t\t\t<< _celestialConfig;\n\n\t\t_me = new MatlabExporter(_outputFile);\n\t}\n\n\tvoid Application::run() {\n\n\t\tBOOST_LOG_TRIVIAL(debug) << \"Run application\";\n\n\t\tTimer tmr;\n\t\tint radius = _celestialConfig.getInt(\"radius\");\n\n\t\tBOOST_LOG_TRIVIAL(info) << \"Parallelism is \" << _applicationConfig.getInt(\"parallelism\");\n\t\tif (_verbosity > boost::log::trivial::info) {\n\t\t\tstd::ostringstream stringStream;\n\t\t\tstringStream << \"Parallelism is \" << _applicationConfig.getInt(\"parallelism\");\n\t\t\tCommandLine::getInstance().addToHeader(stringStream.str().c_str());\n\t\t}\n\t\tBOOST_LOG_TRIVIAL(info) << _applicationConfig.getInt(\"iterations\") << \" iterations\";\n\n\t\t// load config values\n\t\tdouble SZAmin = _applicationConfig.getObject(\"SZA\")[\"min\"].asDouble();\n\t\tdouble SZAstep = _applicationConfig.getObject(\"SZA\")[\"step\"].asDouble();\n\t\tdouble SZAmax = _applicationConfig.getObject(\"SZA\")[\"max\"].asDouble();\n\t\tdouble azimuthMin = _applicationConfig.getObject(\"azimuth\")[\"min\"].asDouble();\n\t\tdouble azimuthStep = _applicationConfig.getObject(\"azimuth\")[\"step\"].asDouble();\n\t\tdouble azimuthMax = _applicationConfig.getObject(\"azimuth\")[\"max\"].asDouble();\n\t\tconst Json::Value beacons = _applicationConfig.getArray(\"beacons\");\n\n\t\t// trace a ray\n\t\tint rayCounter = 0;\n\t\tfor (int iteration = 0; iteration < _applicationConfig.getInt(\"iterations\"); iteration++) {\n\n\t\t\tBOOST_LOG_TRIVIAL(info) << \"Iteration \" << (iteration+1) << \" of \" << _applicationConfig.getInt(\"iterations\");\n\n\t\t\tcreateScene();\n\n\t\t\tBOOST_LOG_TRIVIAL(info) << \"Simulating \" << beacons.size() << \" beacons\";\n\t\t\tBOOST_LOG_TRIVIAL(info) << \"Scanning frequencies \" << _fmin << \" Hz to \" << _fmax << \"Hz with steps of \" << _fstep << \"Hz\";\n\t\t\tBOOST_LOG_TRIVIAL(info) << \"Scanning SZA \" << SZAmin << \" deg to \" << SZAmax << \" deg with steps of \" << SZAstep << \" deg\";\n\t\t\tBOOST_LOG_TRIVIAL(info) << \"Scanning azimuth \" << azimuthMin << \" deg to \" << azimuthMax << \" deg with steps of \" << azimuthStep << \" deg\";\n\n\t\t\tif (_verbosity > boost::log::trivial::info) {\n\t\t\t\tstd::ostringstream stringStream;\n\t\t\t\tstringStream << \"Simulating \" << beacons.size() << \" beacons\\n\" << \"Scanning frequencies \" << _fmin << \" Hz to \" << _fmax\n\t\t\t\t\t\t<< \"Hz with steps of \" << _fstep << \"Hz\\n\" << \"Scanning SZA \" << SZAmin << \" deg to \"\n\t\t\t\t\t\t<< SZAmax << \" deg with steps of \" << SZAstep << \" deg\\n\"\n\t\t\t\t\t\t<< \"Scanning azimuth \" << azimuthMin << \" deg to \" << azimuthMax << \" deg with steps of \" << azimuthStep << \" deg\";\n\t\t\t\t\t\tCommandLine::getInstance().addToHeader(stringStream.str().c_str());\n\t\t\t}\n\n\t\t\tfor(int b = 0; b < beacons.size(); b++) {\n\n\t\t\t\tdouble latitudeOffset = beacons[b].get(\"latitudeOffset\", \"\").asDouble() * Constants::PI / 180.0;\n\t\t\t\tdouble longitudeOffset = beacons[b].get(\"longitudeOffset\", \"\").asDouble() * Constants::PI / 180.0;\n\t\t\t\tconst Json::Value antenna = beacons[b].get(\"antenna\", \"\");\n\t\t\t\t//IAntenna* ant = AntennaFactory::createInstance(antenna.get(\"type\", \"\").asString());\n\t\t\t\tIAntenna* ant = new IsotropicAntenna();\n\t\t\t\tant->setConfig(antenna);\n\n\t\t\t\tMatrix3d latitude = Matrix3d::createRotationMatrix(latitudeOffset, Matrix3d::ROTATION_X);\n\t\t\t\tMatrix3d longitude = Matrix3d::createRotationMatrix(longitudeOffset, Matrix3d::ROTATION_Z);\n\t\t\t\tMatrix3d rotationMatrix = latitude * longitude;\n\n\t\t\t\tVector3d startPosition = rotationMatrix * Vector3d(0, (radius+2), 0);\n\t\t\t\tBOOST_LOG_TRIVIAL(debug) << startPosition;\n\n\t\t\t\tfor(double azimuth = azimuthMin; azimuth <= azimuthMax; azimuth += azimuthStep) {\n\n\t\t\t\t\tMatrix3d azimuthRotation = Matrix3d::createRotationMatrix(azimuth * Constants::PI / 180, Matrix3d::ROTATION_Y);\n\n\t\t\t\t\tfor (int freq = _fmin; freq <= _fmax; freq += _fstep) {\n\t\t\t\t\t\tfor (double elevation = SZAmin; elevation <= SZAmax; elevation += SZAstep) {\n\n\t\t\t\t\t\t\tRay r;\n\t\t\t\t\t\t\tr.rayNumber = ++rayCounter;\n\t\t\t\t\t\t\tr.frequency = (double)freq;\n\t\t\t\t\t\t\tr.signalPower = ant->getSignalPowerAt(azimuth, elevation);\n\t\t\t\t\t\t\tr.o = startPosition;\n\t\t\t\t\t\t\tr.originalAngle = elevation * Constants::PI / 180.0;\n\t\t\t\t\t\t\tr.originBeaconId = b+1;\n\t\t\t\t\t\t\tr.originalAzimuth = azimuth * Constants::PI / 180.0;\n\t\t\t\t\t\t\tVector3d direction = Vector3d(cos(Constants::PI/2.0 - r.originalAngle),\n\t\t\t\t\t\t\t\t\tsin(Constants::PI/2.0 - r.originalAngle),\n\t\t\t\t\t\t\t\t\t0).norm();\n\t\t\t\t\t\t\tr.d = azimuthRotation * direction;\n\n\t\t\t\t\t\t\tWorker w;\n\t\t\t\t\t\t\tw.schedule(&tp, r);\n\n\t\t\t\t\t\t\tnumWorkers++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tBOOST_LOG_TRIVIAL(info) << numWorkers << \" workers queued\";\n\t\t\tif (_verbosity > boost::log::trivial::info) {\n\t\t\t\tstd::ostringstream stringStream;\n\t\t\t\tstringStream << numWorkers << \" workers queued\";\n\t\t\t\tCommandLine::getInstance().addToHeader(stringStream.str().c_str());\n\t\t\t}\n\n\t\t\ttp.wait();\n\n\t\t\tflushScene();\n\t\t}\n\n\t\tstop();\n\n\t\tdouble t = tmr.elapsed();\n\t\tdouble tracingsPerSec = _numTracings / t;\n\t\tchar buffer[80];\n\t\tCommandLine::getInstance().updateBody(\"\\n\");\n\t    sprintf(buffer, \"Elapsed: %5.2f sec. %d tracings done. %5.2f tracings/sec\",\n\t    \t\tt, _numTracings, tracingsPerSec);\n\t    BOOST_LOG_TRIVIAL(warning) << buffer;\n\n\t\t//CsvExporter ce;\n\t\t//ce.dump(\"Debug/data.csv\", dataSet);\n\t\t_me->dump(_outputFile, dataSet);\n\n\t    BOOST_LOG_TRIVIAL(warning) << \"Results stored at: \" << _outputFile;\n\t}\n\n\tvoid Application::stop() {\n\n\t\t_isRunning = false;\n\t}\n\n\t/**\n\t * Add geometries to the scenemanager\n\t */\n\tvoid Application::createScene() {\n\n\t\t_scm = SceneManager();\n\t\t_scm.loadStaticEnvironment();\n\n\t\tint numSceneObjectsCreated = 0;\n\t\tdouble R = _celestialConfig.getInt(\"radius\");\n\t\tdouble angularStepSize = _applicationConfig.getDouble(\"angularStepSize\");\n\n\t\tfor (double latitude = 0 * Constants::PI; latitude <= 0.3 * Constants::PI; latitude += angularStepSize) {\n\t\t\tfor (double longitude = 0 * Constants::PI; longitude <= 2 * Constants::PI; longitude += angularStepSize) {\n\n\t\t\t\tMatrix3d latitudeM = Matrix3d::createRotationMatrix(latitude, Matrix3d::ROTATION_X);\n\t\t\t\tMatrix3d longitudeM = Matrix3d::createRotationMatrix(longitude, Matrix3d::ROTATION_Z);\n\t\t\t\tMatrix3d rotationMatrix = latitudeM * longitudeM;\n\n\t\t\t\tVector3d startPosition = rotationMatrix * Vector3d(0, R, 0);\n\n\t\t\t\tPlane3d mesh = Plane3d(startPosition.norm(), startPosition);\n\t\t\t\tmesh.size = angularStepSize * R;\n\t\t\t\tTerrain* tr = new Terrain(mesh);\n\n\t\t\t\tnumSceneObjectsCreated++;\n\t\t\t\t_scm.addToScene(tr);\n\t\t\t}\n\t\t}\n\n\t\tif (numSceneObjectsCreated > 1e9)\n\t\t\tBOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e9 << \"G scene objects created\";\n\t\telse if (numSceneObjectsCreated > 1e6)\n\t\t\tBOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e6 << \"M scene objects created\";\n\t\telse if (numSceneObjectsCreated > 1e3)\n\t\t\tBOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e3 << \"K scene objects created\";\n\t\telse\n\t\t\tBOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated << \" scene objects created\";\n\t}\n\n\t/**\n\t * Flush the scene by clearing the list of scene objects\n\t */\n\tvoid Application::flushScene() {\n\n\t\t_scm.removeAllFromScene();\n\t}\n\n\tvoid Application::addToDataset(Data dat) {\n\n\t\tdatasetMutex.lock();\n\t\tdataSet.push_back(dat);\n\t\tif (dataSet.size() > Data::MAX_DATASET_SIZE) {\n\t\t\t_me->dump(_outputFile, dataSet);\n\t\t\tdataSet.clear();\n\t\t}\n\t\tdatasetMutex.unlock();\n\t}\n\n\tvoid Application::incrementTracing() {\n\n\t\ttracingIncMutex.lock();\n\t\t_numTracings++;\n\t\ttracingIncMutex.unlock();\n\t}\n\n\tSceneManager Application::getSceneManager() {\n\n\t\treturn _scm;\n\t}\n\n\tConfig Application::getApplicationConfig() {\n\n\t\treturn _applicationConfig;\n\t}\n\n\tConfig Application::getCelestialConfig() {\n\n\t\treturn _celestialConfig;\n\t}\n\n\tvoid Application::setCelestialConfig(Config conf) {\n\n\t\t_celestialConfig = conf;\n\t}\n\n\tvoid Application::setApplicationConfig(Config conf) {\n\n\t\t_applicationConfig = conf;\n\t}\n\n\tint Application::getVerbosity() {\n\n\t\treturn _verbosity;\n\t}\n\n} /* namespace core */\n} /* namespace raytracer */\n", "meta": {"hexsha": "74138140c13806406fa95a7b17a2a64e4f13cd4d", "size": 12314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/Application.cpp", "max_stars_repo_name": "rvangijlswijk/ionospheric-ray-tracer", "max_stars_repo_head_hexsha": "cff7594485a5b21354ad2bd140abbaaa6e894654", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-12-13T12:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T14:13:32.000Z", "max_issues_repo_path": "src/core/Application.cpp", "max_issues_repo_name": "Selena1/ionospheric-ray-tracer", "max_issues_repo_head_hexsha": "cff7594485a5b21354ad2bd140abbaaa6e894654", "max_issues_repo_licenses": ["MIT"], "max_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/Application.cpp", "max_forks_repo_name": "Selena1/ionospheric-ray-tracer", "max_forks_repo_head_hexsha": "cff7594485a5b21354ad2bd140abbaaa6e894654", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T12:16:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T13:14:32.000Z", "avg_line_length": 32.8373333333, "max_line_length": 142, "alphanum_fraction": 0.6501542959, "num_tokens": 3413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.04742587082142043, "lm_q1q2_score": 0.017905194323944516}}
{"text": "#include \"../include/Multigraph.hpp\"\n#include <limits>\n#include <queue>\n#include <iostream>\n#include <iomanip>\n#include <stack>\n#include <algorithm>\n#include <fstream>\n#include <string>\n#include <numeric>\n\nusing namespace std;\n\nconst uint16_t Multigraph::INFINITY = numeric_limits<uint16_t>::max() / 4;\n\nMultigraph::Multigraph(/* args */)\n{\n}\n\nMultigraph::Multigraph(uint16_t n)\n{\n    adjacencyMatrix.resize(n);\n    for (uint16_t i = 0; i < n; i++)\n    {\n        Vertex_t v;\n        v.id = i;\n        vertices.push_back(v);\n        adjacencyMatrix[i].resize(n, Multigraph::INFINITY);\n        adjacencyMatrix[i][i] = 0.0;\n    }\n\n    neighbors.resize(n);\n}\n\nMultigraph::~Multigraph()\n{\n}\n\nvoid Multigraph::addVertex(Vertex_t &vertex)\n{\n    //add vertex to vertices list\n    vertices.push_back(vertex);\n\n    //resize adjacencyMatrix due to new vertex\n    uint16_t last = adjacencyMatrix.size();\n    uint16_t newSize = adjacencyMatrix.size() + 1;\n    adjacencyMatrix.resize(newSize);\n\n    for (uint16_t i = 0; i < last; i++)\n        adjacencyMatrix[i].push_back(Multigraph::INFINITY);\n\n    //resizing and putting infinity value in the last line\n    adjacencyMatrix[last].resize(newSize, Multigraph::INFINITY);\n    adjacencyMatrix[last][last] = 0;\n\n    //resize neighbors matrix due to new vertex\n    neighbors.resize(newSize);\n}\n\nvoid Multigraph::addEdge(Edge_t &edge)\n{   \n    //updates weight in edges\n    adjacencyMatrix[edge.from][edge.to] = edge.weight;\n    adjacencyMatrix[edge.to][edge.from] = edge.weight;\n    //add neighbors\n    neighbors[edge.from].insert(edge.to);\n    neighbors[edge.to].insert(edge.from);\n}\n\nvoid Multigraph::addEdge(uint16_t from, uint16_t to)\n{\n    //just add a neighbor. used to duplicate edges\n    neighbors[from].insert(to);\n    neighbors[to].insert(from);\n}\n\nvoid Multigraph::addEdge(uint16_t from, uint16_t to, uint16_t weight)\n{\n    //updates weight in edges\n    adjacencyMatrix[from][to] = weight;\n    adjacencyMatrix[to][from] = weight;\n    //add neighbors\n    neighbors[from].insert(to);\n    neighbors[to].insert(from);\n}\n\nvoid Multigraph::addVertices(vector<Vertex_t> &newVertices)\n{\n    //add vertex to vertices list\n    for (auto &v : newVertices)\n        vertices.push_back(v);\n\n    //resize adjacencyMatrix due to new vertex\n    uint16_t last = adjacencyMatrix.size();\n    uint16_t newSize = adjacencyMatrix.size() + newVertices.size();\n    adjacencyMatrix.resize(newSize);\n\n    //set infinity in new coluns\n    for (uint16_t i = 0; i < last; i++)\n        adjacencyMatrix[i].resize(newSize, Multigraph::INFINITY);\n\n    //set infinity in new lines\n    for (uint16_t i = last; i < newSize; i++)\n    {\n        adjacencyMatrix[i].resize(newSize, Multigraph::INFINITY);\n        adjacencyMatrix[i][i] = 0.0;\n    }\n\n    //resize neighbors matrix due to new vertex\n    neighbors.resize(newSize);\n}\n\nvoid Multigraph::addEdges(vector<Edge_t> &edges)\n{\n    for (auto &edge : edges)\n    {\n        //update weight in edges\n        adjacencyMatrix[edge.from][edge.to] = edge.weight;\n        adjacencyMatrix[edge.to][edge.from] = edge.weight;\n        //add neighbors\n        neighbors[edge.from].insert(edge.to);\n        neighbors[edge.to].insert(edge.from);\n    }\n}\n\nvector<vector<uint16_t>> *Multigraph::getAdjacencyMatrix()\n{\n    return &adjacencyMatrix;\n}\n\nvector<unordered_multiset<uint16_t>> *Multigraph::getNeighbors()\n{\n    return &neighbors;\n}\n\nbool Multigraph::isEulerian(vector<uint16_t> &oddVertices)\n{\n    bool tst = true;\n    for (uint16_t i = 0; i < neighbors.size(); i++)\n    {\n        //if the vertex has neighbors and the number of neighbors is odd\n        //add to the list of odd vertices\n        if ((neighbors[i].size() > 0) && !(neighbors[i].size() % 2 == 0))\n        {\n            tst = false;\n            oddVertices.push_back(i);\n        }\n    }\n    return tst;\n}\n\n//first is cost, second is id vertex\ntypedef pair<uint16_t, uint16_t> pq_pair;\nbool Multigraph::dijkstra(uint16_t start, uint16_t end, list<uint16_t> &outputPath, uint16_t &totalDistance)\n{\n    priority_queue<pq_pair, vector<pq_pair>, greater<pq_pair>> pq;\n\n    vector<uint16_t> distance(vertices.size(), Multigraph::INFINITY);\n    vector<int32_t> ancester(vertices.size(), -1);\n    vector<bool> visited(vertices.size(), false);\n\n    distance[start] = 0;\n\n    pq.push(make_pair(0, start));\n\n    while (!pq.empty())\n    {\n        pq_pair best;\n        best = pq.top();\n        pq.pop();\n        visited[best.second] = true;\n\n        //when usgin stl, if the best the the priority queue) has value diferent of the vector of distances it is out of date\n        //therefore just pop it\n        if (best.first == distance[best.second])\n        {\n            //if found the end can stop\n            if (best.second == end)\n            {\n                uint16_t curr = end;\n                totalDistance = 0;\n                //geting path e distance in the path\n                while (curr != start)\n                {\n                    outputPath.push_front(curr);\n                    totalDistance += adjacencyMatrix[curr][ancester[curr]];\n                    curr = ancester[curr];\n                }\n                outputPath.push_front(start);\n                return true;\n            }\n\n            for (auto n : neighbors[best.second])\n            {\n                if (!visited[n])\n                {\n                    uint16_t tempDist = distance[best.second] + adjacencyMatrix[best.second][n];\n\n                    if (tempDist < distance[n])\n                    {\n                        distance[n] = tempDist;\n                        ancester[n] = best.second;\n                        pq.push(make_pair(tempDist, n));\n                    }\n                }\n            }\n        }\n    }\n    return false;\n}\n\n//structures to use fibonacci_heap\n//the heap are ordered by distance\n#include <boost/heap/fibonacci_heap.hpp>\nstruct node_heap\n{\n    uint16_t distance;\n    uint16_t vertex;\n    node_heap(uint16_t distance, uint16_t vertex) : distance(distance), vertex(vertex) {}\n    node_heap() {}\n};\n\nstruct compare_node\n{\n    bool operator()(const node_heap &n1, const node_heap &n2) const\n    {\n        return n1.distance > n2.distance;\n    }\n};\ntypedef boost::heap::fibonacci_heap<node_heap, boost::heap::compare<compare_node>> fibonacci_heap_t;\ntypedef fibonacci_heap_t::handle_type handle_t;\nbool Multigraph::dijkstra_boost(uint16_t start, uint16_t end, list<uint16_t> &outputPath, uint16_t &totalDistance)\n{\n    fibonacci_heap_t fh;\n    vector<uint16_t> distance(vertices.size(), Multigraph::INFINITY);\n    vector<int32_t> ancester(vertices.size(), -1);\n    vector<bool> visited(vertices.size(), false);\n    //variable used to update vertices in the priority queue\n    vector<handle_t> nodeHandle;\n\n    for (uint16_t i = 0; i < vertices.size(); i++)\n    {\n        node_heap nh(Multigraph::INFINITY, vertices[i].id);\n        //if (vertices[i].id == start)\n        //    nh.distance = 0;\n        nodeHandle.push_back(fh.push(nh));\n    }\n\n    fh.update(nodeHandle[start], node_heap(0, start));\n\n    distance[start] = 0;\n\n    while (!fh.empty())\n    {\n        node_heap best = fh.top();\n        fh.pop();\n        visited[best.vertex] = true;\n\n        //if reach the end vertex the algorithm can stop\n        if (best.vertex == end)\n        {\n            uint16_t curr = end;\n            totalDistance = 0;\n            //geting path e distance in the path\n            while (curr != start)\n            {\n                outputPath.push_front(curr);\n                totalDistance += adjacencyMatrix[curr][ancester[curr]];\n                curr = ancester[curr];\n            }\n            outputPath.push_front(start);\n            return true;\n        }\n\n        for (auto n : neighbors[best.vertex])\n        {\n            if (!visited[n])\n            {\n                uint16_t tempDist = distance[best.vertex] + adjacencyMatrix[best.vertex][n];\n                if (tempDist < distance[n])\n                {\n                    distance[n] = tempDist;\n                    ancester[n] = best.vertex;\n                    nodeHandle[n].node_->value.distance = tempDist;\n                    fh.update(nodeHandle[n]);\n                    //fh.update(nodeHandle[n], node_heap(tempDist, n));\n                }\n            }\n        }\n    }\n    return false;\n}\n\nbool Multigraph::hierholzer(uint16_t start, list<uint16_t> &outputPath, uint16_t &totalDistance)\n{\n    vector<unordered_multiset<uint16_t>> n(neighbors);\n\n    stack<uint16_t> tempEulerPath;\n\n    tempEulerPath.push(start);\n    totalDistance = 0;\n    while (!tempEulerPath.empty())\n    {\n        uint16_t u = tempEulerPath.top();\n\n        if (n[u].size() == 0)\n        {\n            tempEulerPath.pop();\n            outputPath.push_front(u);\n        }\n        else\n        {\n            uint16_t v = *n[u].begin();\n            totalDistance += adjacencyMatrix[u][v];\n            tempEulerPath.push(v);\n            n[u].erase(n[u].begin());\n            n[v].erase(n[v].find(u));\n        }\n    }\n    return true;\n}\n\nvoid Multigraph::print()\n{\n    cout << \"========================================\\n\";\n    cout << \"\\nVertices: \\n\";\n    for (auto &v : vertices)\n    {\n        cout << v.id << \"\\t\";\n    }\n    cout << \"\\n\";\n\n    cout << \"\\nNeighbors: \\n\";\n    for (uint16_t i = 0; i < neighbors.size(); i++)\n    {\n        cout << \"[\" << i << \"]: \";\n        for (auto &e : neighbors[i])\n        {\n            cout << e << \" \";\n        }\n        cout << \"\\n\";\n    }\n\n    cout << \"\\nAdjacency Matrix: \\n\";\n    for (auto &line : adjacencyMatrix)\n    {\n        for (auto &e : line)\n        {\n            if (e != Multigraph::INFINITY)\n                cout << std::setw(10) << e << \" \";\n            else\n                cout << std::setw(10) << \"inf\"\n                     << \" \";\n        }\n        cout << \"\\n\";\n    }\n\n    cout << \"\\n========================================\" << endl;\n}\n\nvoid gotoLine(std::ifstream &ifs, uint16_t num)\n{\n    ifs.seekg(std::ios::beg);\n    for (uint16_t i = 0; i < num - 1; i++)\n        ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n}\n\nvoid Multigraph::readGraphFromFile(string file)\n{\n    ifstream ifs;\n    ifs.open(file, ifstream::in);\n\n    //Read number of vertices\n    string line;\n    getline(ifs, line);\n    stringstream linestream(line);\n    getline(linestream, line, ' ');\n    getline(linestream, line, ' ');\n\n    uint16_t num_ver = stol(line);\n    vertices.resize(num_ver);\n    adjacencyMatrix.resize(num_ver);\n    for (uint16_t i = 0; i < num_ver; i++)\n    {\n        adjacencyMatrix[i].resize(num_ver, Multigraph::INFINITY);\n        adjacencyMatrix[i][i] = 0.0;\n    }\n\n    neighbors.resize(num_ver);\n\n    //Go to line, start of Edges\n    gotoLine(ifs, num_ver + 3);\n\n    while (ifs.good())\n    {\n        string line;\n        getline(ifs, line);\n        stringstream linestream(line);\n\n        Edge_t e;\n        e.weight = 1;\n\n        getline(linestream, line, ' ');\n        e.from = stoi(line) - 1;\n        getline(linestream, line, ' ');\n        e.to = stoi(line) - 1;\n\n        addEdge(e);\n    }\n}\n\nvoid Multigraph::generateGraph(uint16_t n, uint16_t p)\n{\n    //4 even vertices + number of odd vertices\n    uint16_t nv = 4 + 4 + 6 * n + 2 * p;\n\n    adjacencyMatrix.resize(nv);\n    for (uint16_t i = 0; i < nv; i++)\n    {\n        Vertex_t v;\n        v.id = i;\n        vertices.push_back(v);\n        adjacencyMatrix[i].resize(nv, Multigraph::INFINITY);\n        adjacencyMatrix[i][i] = 0.0;\n    }\n\n    neighbors.resize(nv);\n\n    //first part\n    addEdge(0, 5, 1);\n    addEdge(0, 1, 1);\n    addEdge(1, 3, 1);\n    addEdge(1, 2, 1);\n    addEdge(3, 4, 1);\n    addEdge(2, 4, 1);\n    addEdge(2, 6, 1);\n    addEdge(4, 7, 1);\n    addEdge(6, 5, 1);\n    addEdge(6, 7, 1);\n\n    for (uint16_t i = 8; i < nv - 2 * p; i = i + 6)\n    {\n        addEdge(i, i - 5, 1);\n        addEdge(i + 4, i - 1, 1);\n        addEdge(i, i + 1, 1);\n        addEdge(i, i + 2, 1);\n        addEdge(i + 1, i + 3, 1);\n        addEdge(i + 2, i + 3, 1);\n        addEdge(i + 2, i + 4, 1);\n        addEdge(i + 3, i + 5, 1);\n        addEdge(i + 4, i + 5, 1);\n    }\n\n    if (p > 0)\n    {\n        uint16_t first_v = nv - 2 * p;\n        addEdge(0, first_v, 1);\n        addEdge(5, first_v + 1, 1);\n        addEdge(first_v, first_v + 1, 1);\n\n        for (uint16_t i = first_v; i < nv - 2; i += 2)\n        {\n            addEdge(i, i + 2, 1);\n            addEdge(i + 1, i + 3, 1);\n            addEdge(i + 2, i + 3, 1);\n        }\n    }\n}", "meta": {"hexsha": "455fb4b9b3bde6881d8aafb0c76ead4cedd31ac0", "size": 12402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/src/Multigraph.cpp", "max_stars_repo_name": "alankc/ChinesePostmanProblem", "max_stars_repo_head_hexsha": "344c143c4fb9d8b249821b406b49909ea0b25230", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common/src/Multigraph.cpp", "max_issues_repo_name": "alankc/ChinesePostmanProblem", "max_issues_repo_head_hexsha": "344c143c4fb9d8b249821b406b49909ea0b25230", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/src/Multigraph.cpp", "max_forks_repo_name": "alankc/ChinesePostmanProblem", "max_forks_repo_head_hexsha": "344c143c4fb9d8b249821b406b49909ea0b25230", "max_forks_repo_licenses": ["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.5, "max_line_length": 125, "alphanum_fraction": 0.5540235446, "num_tokens": 3242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.040845716201843275, "lm_q1q2_score": 0.017883214990553335}}
{"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 \"mig_rewriting.hpp\"\n\n#include <functional>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/format.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <core/graph/depth.hpp>\n#include <core/utils/timer.hpp>\n#include <classical/mig/mig_utils.hpp>\n\nusing namespace boost::assign;\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\nusing mig_function_vec_t = std::vector<mig_function>;\n\nstruct children_pair_t\n{\n  unsigned left_a;\n  unsigned left_b;\n  unsigned right_a;\n  unsigned right_b;\n};\n\ninline std::pair<unsigned, unsigned> three_without( unsigned x )\n{\n  return std::make_pair( x == 0u ? 1u : 0u, x == 2u ? 1u : 2u );\n}\n\nclass mig_rewriting_manager\n{\npublic:\n  mig_rewriting_manager( const mig_graph& mig, bool verbose );\n\n  void swap_current( const std::string& method );\n  inline unsigned depth() const { return max_depth; }\n\n  void run_distributivity_rtl();\n  void run_associativity();\n  void run_compl_associativity();\n  void run_push_up();\n  void run_relevance();\n  void run_memristor_optimization();\n  void run_memristor_inverter();\n\n  mig_function distributivity_rtl( const mig_node& f );\n  mig_function distributivity_ltr( const mig_node& f );\n  mig_function associativity( const mig_node& f );\n  mig_function compl_associativity( const mig_node& f );\n  mig_function relevance( const mig_node& f, std::map<mig_function, mig_function> replacements );\n\n  mig_function push_up( const mig_node& f );\n  mig_function memristor_optimization( const mig_node& f );\n  mig_function memristor_inverter( const mig_node& f );\n\nprivate:\n  inline mig_function distributivity_rtl_apply( const children_pair_t& pair,\n                                                const mig_function_vec_t& children_a,\n                                                const mig_function_vec_t& children_b,\n                                                const mig_function& other )\n  {\n    assert( children_a[pair.left_a] == children_b[pair.right_a] );\n    assert( children_a[pair.left_b] == children_b[pair.right_b] );\n\n    const auto x = pair.left_a;\n    const auto y = pair.left_b;\n    const auto u = 3u - pair.left_a - pair.left_b;\n    const auto v = 3u - pair.right_a - pair.right_b;\n\n    if ( verbose )\n    {\n      std::cout << boost::format( \"[i] x: %d, y: %d, u: %d, v: %d\") % x % y % u % v << std::endl;\n    }\n\n    return mig_create_maj( mig_current,\n                           make_function( distributivity_rtl( children_a[x].node ), children_a[x].complemented ),\n                           make_function( distributivity_rtl( children_a[y].node ), children_a[y].complemented ),\n                           mig_create_maj(\n                                          mig_current,\n                                          make_function( distributivity_rtl( children_a[u].node ), children_a[u].complemented ),\n                                          make_function( distributivity_rtl( children_b[v].node ), children_b[v].complemented ),\n                                          make_function( distributivity_rtl( other.node ), other.complemented ) ) );\n  }\n\n  inline mig_function associativity_apply( const mig_function_vec_t& grand_children,\n                                           const mig_function& common,\n                                           const mig_function& extra )\n  {\n    const auto common_f = make_function( associativity( common.node ), common.complemented );\n    return mig_create_maj( mig_current,\n                           make_function( associativity( grand_children[0u].node ), grand_children[0u].complemented ),\n                           common_f,\n                           mig_create_maj( mig_current,\n                                           make_function( associativity( grand_children[1u].node ), grand_children[1u].complemented ),\n                                           common_f,\n                                           make_function( associativity( extra.node ), extra.complemented ) ) );\n  }\n\n  inline mig_function compl_associativity_apply( const mig_function_vec_t& grand_children,\n                                                 const mig_function& common,\n                                                 const mig_function& extra )\n  {\n    const auto extra_f = make_function( compl_associativity( extra.node ), extra.complemented );\n    return mig_create_maj( mig_current,\n                           extra_f,\n                           make_function( compl_associativity( common.node ), common.complemented ),\n                           mig_create_maj( mig_current,\n                                           make_function( compl_associativity( grand_children[0u].node ), grand_children[0u].complemented ),\n                                           extra_f,\n                                           make_function( compl_associativity( grand_children[1u].node ), grand_children[1u].complemented ) ) );\n  }\n\n  /**\n   * @return (a,b) where z = node[a][b]\n   */\n  boost::optional<std::pair<unsigned, unsigned>> find_depth_distributivity_candidate( const mig_node& node ) const;\n\n  /**\n   * @return (a,b,c) where x = node[a] and z = node[b][c]\n   */\n  boost::optional<std::tuple<unsigned, unsigned, unsigned>> find_depth_associativity_candidate( const mig_node& node ) const;\n\n  /**\n   * @return (a,b) where x = node[a] and u = node[b]\n   */\n  boost::optional<std::pair<unsigned, unsigned>> find_depth_compl_associativity_candidate( const mig_node& node ) const;\n\n  /**\n   * @return (a,b,c) where x = node[a], y = node[b], and z = node[c]\n   */\n  boost::optional<std::tuple<mig_function, mig_function, mig_function>> find_depth_relevance_candidate( const mig_node& node ) const;\n\npublic:\n  mig_graph                        mig_old;\n  mig_graph                        mig_current;\n  std::map<mig_node, mig_function> old_to_new;\n  bool                             verbose;\n  std::vector<unsigned>            indegree;\n  std::vector<unsigned>            depths;\n  unsigned                         max_depth;\n\n  bool                             use_distributivity       = true;\n  bool                             use_associativity        = true;\n  bool                             use_compl_associativity  = true;\n\n  /* statistics */\n  unsigned                         distributivity_count       = 0u;\n  unsigned                         associativity_count        = 0u;\n  unsigned                         compl_associativity_count  = 0u;\n};\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\ninline bool is_terminal( const mig_graph& mig, const mig_function& f )\n{\n  return out_degree( f.node, mig ) == 0u;\n}\n\ninline bool is_regular_nonterminal( const mig_graph& mig, const mig_function& f )\n{\n  return !f.complemented && out_degree( f.node, mig );\n}\n\nboost::dynamic_bitset<> get_pair_pattern( const mig_function_vec_t& c1,\n                                          const mig_function_vec_t& c2 )\n{\n  boost::dynamic_bitset<> equals( 9u );\n\n  equals.set( 0u, c1[0u] == c2[0u] );\n  equals.set( 1u, c1[0u] == c2[1u] );\n  equals.set( 2u, c1[0u] == c2[2u] );\n  equals.set( 3u, c1[1u] == c2[0u] );\n  equals.set( 4u, c1[1u] == c2[1u] );\n  equals.set( 5u, c1[1u] == c2[2u] );\n  equals.set( 6u, c1[2u] == c2[0u] );\n  equals.set( 7u, c1[2u] == c2[1u] );\n  equals.set( 8u, c1[2u] == c2[2u] );\n\n  return equals;\n}\n\nstd::vector<children_pair_t> get_children_pairs( const mig_function_vec_t& c1,\n                                                 const mig_function_vec_t& c2 )\n{\n  std::vector<children_pair_t> pairs;\n\n  const auto pattern = get_pair_pattern( c1, c2 );\n\n  auto pos_a = pattern.find_first();\n\n  while ( pos_a != boost::dynamic_bitset<>::npos )\n  {\n    auto pos_b = pattern.find_next( pos_a );\n    while ( pos_b != boost::dynamic_bitset<>::npos )\n    {\n      pairs.push_back({(unsigned)pos_a / 3u,\n                       (unsigned)pos_b / 3u,\n                       (unsigned)pos_a % 3u,\n                       (unsigned)pos_b % 3u} );\n      pos_b = pattern.find_next( pos_b );\n    }\n    pos_a = pattern.find_next( pos_a );\n  }\n\n  return pairs;\n}\n\nmig_rewriting_manager::mig_rewriting_manager( const mig_graph& mig, bool verbose )\n  : mig_current( mig ),\n    verbose( verbose )\n{\n}\n\nvoid mig_rewriting_manager::swap_current( const std::string& method )\n{\n  mig_old = mig_current;\n  mig_current = mig_graph();\n\n  const auto& info_old = mig_info( mig_old );\n  mig_initialize( mig_current, info_old.model_name );\n\n  auto& info_current = mig_info( mig_current );\n  info_current.constant_used = info_old.constant_used;\n\n  /* node to node mapping from old to new mig */\n  old_to_new.clear();\n  old_to_new.insert( {info_old.constant, {info_current.constant, false}} );\n\n  for ( const auto& input : info_old.inputs )\n  {\n    old_to_new.insert( {input, mig_create_pi( mig_current, info_old.node_names.at( input ) )} );\n  }\n\n  /* indegrees */\n  indegree = precompute_in_degrees( mig_old );\n\n  /* depth */\n  std::vector<mig_node> outputs;\n  for ( const auto& output : info_old.outputs )\n  {\n    outputs += output.first.node;\n  }\n\n  max_depth = compute_depth( mig_old, outputs, depths );\n\n  if ( verbose )\n  {\n    std::cout << \"[i] current depth: \" << max_depth << \", run \" << method << std::endl;\n  }\n}\n\nvoid mig_rewriting_manager::run_distributivity_rtl()\n{\n  swap_current( \"D_RTL\" );\n\n  for ( const auto& output : mig_info( mig_old ).outputs )\n  {\n    mig_create_po( mig_current, make_function( distributivity_rtl( output.first.node ), output.first.complemented ), output.second );\n  }\n}\n\nvoid mig_rewriting_manager::run_associativity()\n{\n  swap_current( \"A\" );\n\n  for ( const auto& output : mig_info( mig_old ).outputs )\n  {\n    mig_create_po( mig_current, make_function( associativity( output.first.node ), output.first.complemented ), output.second );\n  }\n}\n\nvoid mig_rewriting_manager::run_compl_associativity()\n{\n  swap_current( \"C\" );\n\n  for ( const auto& output : mig_info( mig_old ).outputs )\n  {\n    mig_create_po( mig_current, make_function( compl_associativity( output.first.node ), output.first.complemented ), output.second );\n  }\n}\n\nvoid mig_rewriting_manager::run_push_up()\n{\n  swap_current( \"PU\" );\n\n  for ( const auto& output : mig_info( mig_old ).outputs )\n  {\n    mig_create_po( mig_current, make_function( push_up( output.first.node ), output.first.complemented ), output.second );\n  }\n}\n\nvoid mig_rewriting_manager::run_relevance()\n{\n  swap_current( \"R\" );\n\n  for ( const auto& output : mig_info( mig_old ).outputs )\n  {\n    std::map<mig_function, mig_function> replacements;\n    mig_create_po( mig_current, make_function( relevance( output.first.node, replacements ), output.first.complemented ), output.second );\n  }\n}\n\nvoid mig_rewriting_manager::run_memristor_optimization()\n{\n  /* mig_old is removed\n     mig_old = mig_current\n     mig_current is empty */\n  swap_current( \"MO\" );\n\n  for ( const auto& output : mig_info( mig_old ).outputs )\n  {\n    mig_create_po( mig_current, make_function( memristor_optimization( output.first.node ), output.first.complemented ), output.second );\n  }\n}\n\nvoid mig_rewriting_manager::run_memristor_inverter()\n{\n  /* mig_old is removed\n     mig_old = mig_current\n     mig_current is empty */\n  swap_current( \"MO_INV\" );\n\n  for ( const auto& output : mig_info( mig_old ).outputs )\n  {\n    mig_create_po( mig_current, make_function( memristor_optimization( output.first.node ), output.first.complemented ), output.second );\n  }\n}\n\n\n/**\n * 〈〈xyu〉〈xyv〉z〉↦〈xy〈uvz〉〉\n */\nmig_function mig_rewriting_manager::distributivity_rtl( const mig_node& node )\n{\n  /* node is terminal */\n  const auto it = old_to_new.find( node );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  const auto children = get_children( mig_old, node );\n  mig_function_vec_t children_a, children_b, children_c;\n  mig_function res;\n\n  if ( is_regular_nonterminal( mig_old, children[0u] ) && indegree[children[0u].node] == 1u )\n  {\n    /* first child is not terminal */\n    children_a = get_children( mig_old, children[0u].node );\n\n    /* check (0,1) */\n    if ( is_regular_nonterminal( mig_old, children[1u] ) && indegree[children[1u].node] == 1u )\n    {\n      children_b = get_children( mig_old, children[1u].node );\n\n      const auto pairs = get_children_pairs( children_a, children_b );\n\n      if ( !pairs.empty() )\n      {\n        res = distributivity_rtl_apply( pairs.front(), children_a, children_b, children[2u] );\n        goto cache_and_return;\n      }\n    }\n\n    /* check (0,2) */\n    if ( is_regular_nonterminal( mig_old, children[2u] ) && indegree[children[2u].node] == 1u )\n    {\n      children_c = get_children( mig_old, children[2u].node );\n\n      const auto pairs = get_children_pairs( children_a, children_c );\n\n      if ( !pairs.empty() )\n      {\n        res = distributivity_rtl_apply( pairs.front(), children_a, children_c, children[1u] );\n        goto cache_and_return;\n      }\n    }\n  }\n\n  /* check (1,2) */\n  if ( is_regular_nonterminal( mig_old, children[1u] ) && is_regular_nonterminal( mig_old, children[2u] ) &&\n       indegree[children[1u].node] == 1u && indegree[children[2u].node] == 1u )\n  {\n    if ( children_b.empty() ) { children_b = get_children( mig_old, children[1u].node ); }\n    if ( children_c.empty() ) { children_c = get_children( mig_old, children[2u].node ); }\n\n    const auto pairs = get_children_pairs( children_b, children_c );\n\n    if ( !pairs.empty() )\n    {\n      res = distributivity_rtl_apply( pairs.front(), children_b, children_c, children[0u] );\n      goto cache_and_return;\n    }\n  }\n\n  /* recur */\n  res = mig_create_maj( mig_current,\n                        make_function( distributivity_rtl( children[0u].node ), children[0u].complemented ),\n                        make_function( distributivity_rtl( children[1u].node ), children[1u].complemented ),\n                        make_function( distributivity_rtl( children[2u].node ), children[2u].complemented ) );\n\ncache_and_return:\n  old_to_new.insert( {node, res} );\n  return res;\n}\n\n/**\n * 〈xy〈uvz〉〉↦〈〈xyu〉〈xyv〉z〉\n */\nmig_function mig_rewriting_manager::distributivity_ltr( const mig_node& node )\n{\n  /* node is terminal */\n  const auto it = old_to_new.find( node );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  assert( false );\n\n  return mig_function();\n}\n\nboost::optional<std::pair<unsigned, unsigned>> mig_rewriting_manager::find_depth_distributivity_candidate( const mig_node& node ) const\n{\n  const auto children = get_children( mig_old, node );\n\n  for ( auto i = 0u; i < 3u; ++i )\n  {\n    if ( is_regular_nonterminal( mig_old, children[i] ) )\n    {\n      auto grand_children = get_children( mig_old, children[i].node );\n\n      for ( auto j = 0u; j < 3u; ++j )\n      {\n        auto valid = true;\n\n        for ( auto k = 0u; k < 3u; ++k )\n        {\n          if ( i == k ) { continue; }\n\n          int diff = (int)depths[grand_children[j].node] - (int)depths[children[k].node];\n\n          if ( diff < 2 ) { valid = false; break; }\n        }\n\n        if ( !valid ) { continue; }\n\n        /* WE HAVE A CANDIDATE: z = ( i -> j ) */\n        return std::make_pair( i, j );\n      }\n    }\n  }\n\n  return boost::none;\n}\n\nboost::optional<std::tuple<unsigned, unsigned, unsigned>> mig_rewriting_manager::find_depth_associativity_candidate( const mig_node& node ) const\n{\n  const auto children = get_children( mig_old, node );\n\n  /* i iterates to find grand children (which contain z) */\n  for ( auto i = 0u; i < 3u; ++i )\n  {\n    if ( !is_regular_nonterminal( mig_old, children[i] ) ) { continue; }\n\n    const auto grand_children = get_children( mig_old, children[i].node );\n\n    /* j iterates to find u */\n    for ( auto j = 0u; j < 3u; ++j )\n    {\n      if ( i == j ) { continue; }\n\n      /* if u ( = children[j] ) can be found in the grand_children */\n      if ( boost::find( grand_children, children[j] ) != grand_children.end() )\n      {\n        for ( auto k = 0u; k < 3u; ++k )\n        {\n          if ( grand_children[k] == children[j] ) { continue; }\n\n          int diff = (int)depths[grand_children[k].node] - (int)depths[children[3u - j - i].node];\n\n          if ( diff >= 2 )\n          {\n            return std::make_tuple( 3u - j - i, i, k );\n          }\n        }\n      }\n    }\n  }\n\n  return boost::none;\n}\n\nboost::optional<std::pair<unsigned, unsigned>> mig_rewriting_manager::find_depth_compl_associativity_candidate( const mig_node& node ) const\n{\n  const auto children = get_children( mig_old, node );\n\n  /* i iterates to find grand children (which contain z) */\n  for ( auto i = 0u; i < 3u; ++i )\n  {\n    if ( !is_regular_nonterminal( mig_old, children[i] ) ) { continue; }\n\n    const auto grand_children = get_children( mig_old, children[i].node );\n\n    /* j iterates to find u */\n    for ( auto j = 0u; j < 3u; ++j )\n    {\n      if ( i == j ) { continue; }\n\n      /* if u ( = children[j] ) can be found in the grand_children */\n      if ( boost::find( grand_children, !children[j] ) != grand_children.end() )\n      {\n        int diff = (int)depths[children[j].node] - (int)depths[children[3u - j - i].node];\n\n        if ( diff >= 2 )\n        {\n          return std::make_pair( 3u - j - i, j );\n        }\n      }\n    }\n  }\n\n  return boost::none;\n}\n\nboost::optional<std::tuple<mig_function, mig_function, mig_function>> mig_rewriting_manager::find_depth_relevance_candidate( const mig_node& node ) const\n{\n  auto children = get_children( mig_old, node );\n\n  boost::sort( children, [this]( const mig_function& a, const mig_function& b ) { return depths.at( a.node ) > depths.at( b.node ); } );\n\n  if ( indegree[children[1u].node] > 1u )\n  {\n    return std::make_tuple( children[0u], children[2u], children[1u] );\n  }\n  else if ( indegree[children[2u].node] > 1u )\n  {\n    return std::make_tuple( children[0u], children[1u], children[2u] );\n  }\n  else if ( indegree[children[0u].node] > 1u )\n  {\n    return std::make_tuple( children[1u], children[2u], children[0u] );\n  }\n\n  return boost::none;\n}\n\n/**\n * 〈xu〈yuz〉〉↦〈zu〈yux〉〉\n */\nmig_function mig_rewriting_manager::associativity( const mig_node& node )\n{\n  /* node is terminal */\n  const auto it = old_to_new.find( node );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  const auto children = get_children( mig_old, node );\n  mig_function res;\n\n  for ( auto i = 0u; i < 3u; ++i )\n  {\n    if ( is_regular_nonterminal( mig_old, children[i] ) && indegree[children[i].node] == 1u )\n    {\n      for ( auto j = 0u; j < 3u; ++j )\n      {\n        if ( i == j ) { continue; }\n\n        auto grand_children = get_children( mig_old, children[i].node );\n\n        const auto it = boost::find( grand_children, children[j] );\n        if ( it != grand_children.end() )\n        {\n          grand_children.erase( it );\n          res = associativity_apply( grand_children, children[j], children[3u - j - i] );\n          goto cache_and_return;\n        }\n      }\n    }\n  }\n\n  /* recur */\n  res = mig_create_maj( mig_current,\n                        make_function( associativity( children[0u].node ), children[0u].complemented ),\n                        make_function( associativity( children[1u].node ), children[1u].complemented ),\n                        make_function( associativity( children[2u].node ), children[2u].complemented ) );\n\ncache_and_return:\n  old_to_new.insert( {node, res} );\n  return res;\n}\n\n/**\n * 〈xu〈yu'z〉〉↦〈xu〈yxz〉〉\n */\nmig_function mig_rewriting_manager::compl_associativity( const mig_node& node )\n{\n  /* node is terminal */\n  const auto it = old_to_new.find( node );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  const auto children = get_children( mig_old, node );\n  mig_function res;\n\n  for ( auto i = 0u; i < 3u; ++i )\n  {\n    if ( is_regular_nonterminal( mig_old, children[i] ) && indegree[children[i].node] == 1u )\n    {\n      for ( auto j = 0u; j < 3u; ++j )\n      {\n        if ( i == j ) { continue; }\n\n        auto grand_children = get_children( mig_old, children[i].node );\n\n        const auto it = boost::find( grand_children, !children[j] );\n        if ( it != grand_children.end() )\n        {\n          grand_children.erase( it );\n          res = compl_associativity_apply( grand_children, children[j], children[3u - j - i] );\n          goto cache_and_return;\n        }\n      }\n    }\n  }\n\n  /* recur */\n  res = mig_create_maj( mig_current,\n                        make_function( compl_associativity( children[0u].node ), children[0u].complemented ),\n                        make_function( compl_associativity( children[1u].node ), children[1u].complemented ),\n                        make_function( compl_associativity( children[2u].node ), children[2u].complemented ) );\n\ncache_and_return:\n  old_to_new.insert( {node, res} );\n  return res;\n}\n\n/**\n * 〈xyz〉↦〈xyz_{x/y'}〉\n */\nmig_function mig_rewriting_manager::relevance( const mig_node& f, std::map<mig_function, mig_function> replacements )\n{\n  /* node should be replaced? */\n  auto it_replace = replacements.find( {f, false} );\n  if ( it_replace != replacements.end() ) { return it_replace->second; }\n\n  it_replace = replacements.find( {f, true} );\n  if ( it_replace != replacements.end() ) { return !it_replace->second; }\n\n  /* node is terminal */\n  const auto it = old_to_new.find( f );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  mig_function res;\n\n  const auto cand = find_depth_relevance_candidate( f );\n\n  if ( cand != boost::none )\n  {\n    const auto zcand = *cand;\n\n    const auto x = std::get<0>( zcand );\n    const auto y = std::get<1>( zcand );\n    const auto z = std::get<2>( zcand );\n\n    assert( !( x == y ) );\n    assert( !( x == z ) );\n    assert( !( y == z ) );\n\n    const auto xf = make_function( relevance( x.node, replacements ), x.complemented );\n    const auto yf = make_function( relevance( y.node, replacements ), y.complemented );\n\n    if ( xf.node != 0u && yf.node != 0u )\n    {\n      replacements.insert( {xf, !yf} );\n    }\n    const auto zf = make_function( relevance( z.node, replacements ), z.complemented );\n\n    res = mig_create_maj( mig_current, xf, yf, zf );\n  }\n  else\n  {\n    const auto children = get_children( mig_old, f );\n\n    /* recur */\n    res = mig_create_maj( mig_current,\n                          make_function( relevance( children[0u].node, replacements ), children[0u].complemented ),\n                          make_function( relevance( children[1u].node, replacements ), children[1u].complemented ),\n                          make_function( relevance( children[2u].node, replacements ), children[2u].complemented ) );\n  }\n\n  old_to_new.insert( {f, res} );\n  return res;\n}\n\nmig_function mig_rewriting_manager::push_up( const mig_node& f )\n{\n  /* node is terminal */\n  const auto it = old_to_new.find( f );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  mig_function res;\n\n  const auto children = get_children( mig_old, f );\n\n  /* distributivity */\n    if ( use_distributivity )\n  {\n    const auto cand_dist = find_depth_distributivity_candidate( f );\n\n    if ( cand_dist != boost::none )\n    {\n      const auto zcand = *cand_dist;\n\n      const auto grand_children = get_children( mig_old, children[zcand.first].node );\n\n      const auto xy = three_without( zcand.first );\n      const auto uv = three_without( zcand.second );\n\n      const auto x = children[xy.first];\n      const auto y = children[xy.second];\n      const auto u = grand_children[uv.first];\n      const auto v = grand_children[uv.second];\n      const auto z = grand_children[zcand.second];\n\n      const auto xf = make_function( push_up( x.node ), x.complemented );\n      const auto yf = make_function( push_up( y.node ), y.complemented );\n      const auto uf = make_function( push_up( u.node ), u.complemented ^ children[zcand.first].complemented );\n      const auto vf = make_function( push_up( v.node ), v.complemented ^ children[zcand.first].complemented );\n      const auto zf = make_function( push_up( z.node ), z.complemented ^ children[zcand.first].complemented );\n\n      res = mig_create_maj( mig_current,\n                            mig_create_maj( mig_current, xf, yf, uf ),\n                            mig_create_maj( mig_current, xf, yf, vf ),\n                            zf );\n\n      ++distributivity_count;\n      goto cache_and_return;\n    }\n  }\n\n  /* associativity */\n  if ( use_associativity )\n  {\n    const auto cand_assoc = find_depth_associativity_candidate( f );\n\n    if ( cand_assoc != boost::none )\n    {\n      const auto zcand = *cand_assoc;\n\n      const auto grand_children = get_children( mig_old, children[std::get<1>( zcand )].node );\n\n      assert( !children[std::get<1>( zcand )].complemented );\n\n      const auto yu = three_without( std::get<2>( zcand ) );\n\n      const auto x = children[std::get<0>( zcand )];\n      const auto u = children[3u - std::get<0>( zcand ) - std::get<1>( zcand )];\n      const auto z = grand_children[std::get<2>( zcand )];\n      const auto y = ( u == grand_children[yu.first] ) ? grand_children[yu.second] : grand_children[yu.first];\n\n      assert( grand_children[yu.first] == u || grand_children[yu.second] == u );\n\n      const auto xf = make_function( push_up( x.node ), x.complemented );\n      const auto uf = make_function( push_up( u.node ), u.complemented );\n      const auto zf = make_function( push_up( z.node ), z.complemented );\n      const auto yf = make_function( push_up( y.node ), y.complemented );\n\n      res = mig_create_maj( mig_current,\n                            zf,\n                            uf,\n                            mig_create_maj( mig_current, yf, uf, xf ) );\n\n      ++associativity_count;\n      goto cache_and_return;\n    }\n  }\n\n  /* complementary associativity */\n  if ( use_compl_associativity )\n  {\n    const auto cand = find_depth_compl_associativity_candidate( f );\n\n    if ( cand != boost::none )\n    {\n      const auto zcand = *cand;\n\n      const auto grand_children = get_children( mig_old, children[3u - zcand.first - zcand.second].node );\n\n      const auto x = children[zcand.first];\n      const auto u = children[zcand.second];\n\n      const auto ui = std::distance( grand_children.begin(), boost::find( grand_children, !u ) );\n      const auto yz = three_without( ui );\n\n      const auto y = grand_children[yz.first];\n      const auto z = grand_children[yz.second];\n\n      const auto xf = make_function( push_up( x.node ), x.complemented );\n      const auto uf = make_function( push_up( u.node ), u.complemented );\n      const auto zf = make_function( push_up( z.node ), z.complemented );\n      const auto yf = make_function( push_up( y.node ), y.complemented );\n\n      res = mig_create_maj( mig_current,\n                            xf,\n                            uf,\n                            mig_create_maj( mig_current, yf, xf, zf ) );\n\n      ++compl_associativity_count;\n      goto cache_and_return;\n    }\n  }\n\n  /* recur */\n  res = mig_create_maj( mig_current,\n                        make_function( push_up( children[0u].node ), children[0u].complemented ),\n                        make_function( push_up( children[1u].node ), children[1u].complemented ),\n                        make_function( push_up( children[2u].node ), children[2u].complemented ) );\n\ncache_and_return:\n  old_to_new.insert( {f, res} );\n  return res;\n}\n\nmig_function mig_rewriting_manager::memristor_optimization( const mig_node& f )\n{\n  /* node is terminal */\n  const auto it = old_to_new.find( f );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  mig_function res;\n\n  const auto children = get_children( mig_old, f );\n\n  /* if at least two children are complemented */\n  if ( ( static_cast<int>( children[0u].complemented ) + static_cast<int>( children[1u].complemented ) + static_cast<int>( children[2u].complemented ) >= 2 ) ) //&& indegree[f] == 1u )\n  {\n    res = !mig_create_maj( mig_current,\n                           make_function( memristor_optimization( children[0u].node ), !children[0u].complemented ),\n                           make_function( memristor_optimization( children[1u].node ), !children[1u].complemented ),\n                           make_function( memristor_optimization( children[2u].node ), !children[2u].complemented ) );\n  }\n  else\n  {\n    res = mig_create_maj( mig_current,\n                          make_function( memristor_optimization( children[0u].node ), children[0u].complemented ),\n                          make_function( memristor_optimization( children[1u].node ), children[1u].complemented ),\n                          make_function( memristor_optimization( children[2u].node ), children[2u].complemented ) );\n  }\n\n  old_to_new.insert( {f, res} );\n  return res;\n}\n\n\n\nmig_function mig_rewriting_manager::memristor_inverter( const mig_node& f )\n{\n  /* node is terminal */\n  const auto it = old_to_new.find( f );\n  if ( it != old_to_new.end() ) { return it->second; }\n\n  mig_function res;\n\n  const auto children = get_children( mig_old, f );\n\n  /* if at least two children are complemented */\n  if ( ( static_cast<int>( children[0u].complemented ) + static_cast<int>( children[1u].complemented ) + static_cast<int>( children[2u].complemented ) == 3u ) && indegree[f] == 1u )\n  {\n    res = !mig_create_maj( mig_current,\n                           make_function( memristor_optimization( children[0u].node ), !children[0u].complemented ),\n                           make_function( memristor_optimization( children[1u].node ), !children[1u].complemented ),\n                           make_function( memristor_optimization( children[2u].node ), !children[2u].complemented ) );\n  }\n  else\n  {\n    res = mig_create_maj( mig_current,\n                          make_function( memristor_optimization( children[0u].node ), children[0u].complemented ),\n                          make_function( memristor_optimization( children[1u].node ), children[1u].complemented ),\n                          make_function( memristor_optimization( children[2u].node ), children[2u].complemented ) );\n  }\n\n  old_to_new.insert( {f, res} );\n  return res;\n}\n\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nmig_graph mig_area_rewriting( const mig_graph& mig,\n                              const properties::ptr& settings,\n                              const properties::ptr& statistics )\n{\n  /* settings */\n  const auto effort  = get( settings, \"effort\",  1u );\n  const auto verbose = get( settings, \"verbose\", false );\n\n  /* timer */\n  properties_timer t( statistics );\n\n  mig_rewriting_manager mgr( mig, verbose );\n\n  for ( auto k = 0u; k < effort; ++k )\n  {\n    mgr.run_distributivity_rtl();\n    mgr.run_associativity();\n    mgr.run_compl_associativity();\n    mgr.run_distributivity_rtl();\n  }\n\n  set( statistics, \"distributivity_count\",       mgr.distributivity_count );\n  set( statistics, \"associativity_count\",        mgr.associativity_count );\n  set( statistics, \"compl_associativity_count\",  mgr.compl_associativity_count );\n\n  return mgr.mig_current;\n}\n\nmig_graph mig_depth_rewriting( const mig_graph& mig,\n                               const properties::ptr& settings,\n                               const properties::ptr& statistics )\n{\n  /* settings */\n  const auto effort                   = get( settings, \"effort\",  1u );\n  const auto use_distributivity       = get( settings, \"use_distributivity\", true );\n  const auto use_associativity        = get( settings, \"use_associativity\", true );\n  const auto use_compl_associativity  = get( settings, \"use_compl_associativity\", true );\n  const auto verbose                  = get( settings, \"verbose\", false );\n\n  /* timer */\n  properties_timer t( statistics );\n\n  mig_rewriting_manager mgr( mig, verbose );\n  mgr.use_distributivity = use_distributivity;\n  mgr.use_associativity  = use_associativity;\n  mgr.use_compl_associativity = use_compl_associativity;\n\n  for ( auto k = 0u; k < effort; ++k )\n  {\n    mgr.run_push_up();\n    mgr.run_relevance();\n    mgr.run_push_up();\n  }\n\n  set( statistics, \"distributivity_count\",       mgr.distributivity_count );\n  set( statistics, \"associativity_count\",        mgr.associativity_count );\n  set( statistics, \"compl_associativity_count\",  mgr.compl_associativity_count );\n\n  return mgr.mig_current;\n}\n\nmig_graph mig_memristor_rewriting( const mig_graph& mig,\n                                   const properties::ptr& settings,\n                                   const properties::ptr& statistics )\n{\n  /* settings */\n  const auto effort   = get( settings, \"effort\",  1u );\n  const auto verbose  = get( settings, \"verbose\", false );\n  const auto strategy = get( settings, \"strategy\", 0u ); /* 0u: multi-objective, 1u: RRAM step, 2u: PLiM */\n\n  /* timer */\n  properties_timer t( statistics );\n\n  mig_rewriting_manager mgr( mig, verbose );\n  mgr.use_distributivity = true;\n  mgr.use_associativity  = true;\n  mgr.use_compl_associativity = true;\n\n  for ( auto k = 0u; k < effort; ++k )\n  {\n    switch ( strategy )\n    {\n    case 0u:\n      mgr.run_push_up();\n      mgr.run_memristor_optimization();\n      mgr.run_push_up();\n      mgr.run_associativity();\n      mgr.run_distributivity_rtl();\n      break;\n    case 1u:\n      mgr.run_push_up();\n      mgr.run_memristor_inverter();\n      mgr.run_memristor_optimization();\n      mgr.run_push_up();\n      break;\n    case 2u:\n      mgr.run_distributivity_rtl();\n      mgr.run_associativity();\n      mgr.run_compl_associativity();\n      mgr.run_distributivity_rtl();\n      mgr.run_memristor_optimization();\n      mgr.run_memristor_inverter();\n      break;\n    case 3u:\n      mgr.run_memristor_optimization();\n      mgr.run_memristor_inverter();\n      break;\n    }\n  }\n\n  set( statistics, \"distributivity_count\",       mgr.distributivity_count );\n  set( statistics, \"associativity_count\",        mgr.associativity_count );\n  set( statistics, \"compl_associativity_count\",  mgr.compl_associativity_count );\n\n  return mgr.mig_current;\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": "6b8d0b698bf33a53a756a90bdf23b64d9431302b", "size": 35526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/mig/mig_rewriting.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/mig/mig_rewriting.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/mig/mig_rewriting.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.9961722488, "max_line_length": 184, "alphanum_fraction": 0.609947644, "num_tokens": 9032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.044680871544747154, "lm_q1q2_score": 0.01786393256198938}}
{"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 \"BlockVector.hpp\"\n\n#include <boost/numeric/ublas/vector_proxy.hpp>  // for project\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <vector>\n\n#include \"SiconosVector.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n#include \"SiconosAlgebraTools.hpp\" // for isComparableTo\n#include \"Tools.hpp\"\n//#define DEBUG_STDOUT\n//#define DEBUG_MESSAGES\n#include \"siconos_debug.h\"\n#include \"SiconosException.hpp\"\n\n\nusing Siconos::Algebra::isComparableTo;\n\n// =================================================\n//                CONSTRUCTORS\n// =================================================\nBlockVector::BlockVector()\n{\n  _tabIndex.reset(new Index());\n}\n\nBlockVector::BlockVector(const BlockVector &v)\n{\n  Index::size_type nbBlocks = v.numberOfBlocks();\n  _tabIndex.reset(new Index());\n  _tabIndex->reserve(nbBlocks);\n  _vect.reserve(nbBlocks);\n  VectorOfVectors::const_iterator it;\n  for(it = v.begin(); it != v.end(); ++it)\n  {\n    _vect.push_back(std::shared_ptr<SiconosVector>(new SiconosVector(**it))) ;\n    _sizeV += (*it)->size();\n    _tabIndex->push_back(_sizeV);\n  }\n}\n\nBlockVector::BlockVector(SP::SiconosVector v1, SP::SiconosVector v2)\n{\n  // Insert the two vectors in the container\n  // NO COPY !!\n  if(! v1  && ! v2)\n    THROW_EXCEPTION(\"both vectors are nullptr.\");\n\n  _tabIndex.reset(new Index());\n\n  _tabIndex->reserve(2);\n  _vect.reserve(2);\n\n  if(v1)\n  {\n    _vect.push_back(v1);\n    _sizeV = v1->size();\n    _tabIndex->push_back(_sizeV);\n\n  }\n  else\n    // If first parameter is a nullptr pointer, then set this(1) to a SiconosVector of the same size as v2, and equal to 0.\n  {\n    // This case is usefull to set xDot in LagrangianDS.\n    _sizeV = v2->size();\n\n    _vect.push_back(std::shared_ptr<SiconosVector>(new SiconosVector(_sizeV)));\n    _tabIndex->push_back(_sizeV);\n\n  }\n  if(v2)\n  {\n    _vect.push_back(v2);\n    _sizeV += v2->size();\n    _tabIndex->push_back(_sizeV);\n\n  }\n  else // If second parameter is a nullptr pointer, then set this(2) to a SiconosVector of the same size as v1, and equal to 0.\n  {\n    // This case is usefull to set xDot in LagrangianDS.\n\n    _vect.push_back(std::shared_ptr<SiconosVector>(new SiconosVector(v1->size())));\n    _sizeV += v1->size();\n    _tabIndex->push_back(_sizeV);\n  }\n}\n\nBlockVector::BlockVector(unsigned int numberOfBlocks, unsigned int dim)\n{\n  _tabIndex.reset(new Index());\n  _tabIndex->reserve(numberOfBlocks);\n  _vect.reserve(numberOfBlocks);\n  for(unsigned int i = 0; i < numberOfBlocks; ++i)\n  {\n    _vect.push_back(std::shared_ptr<SiconosVector>(new SiconosVector(dim)));\n    _tabIndex->push_back(dim * (i + 1));\n  }\n  _sizeV = dim * numberOfBlocks;\n}\n\nBlockVector::BlockVector(unsigned int numberOfBlocks)\n{\n  _tabIndex.reset(new Index());\n  _tabIndex->resize(numberOfBlocks);\n  _vect.resize(numberOfBlocks);\n}\n\n// ===========================\n//      private method\n// ===========================\n\nvoid BlockVector::_update()\n{\n  _sizeV=0;\n  _tabIndex.reset(new Index());\n\n  VectorOfVectors::iterator it;\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n  {\n    if(*it)\n    {\n      _sizeV += (*it)->size();\n    }\n    _tabIndex->push_back(_sizeV);\n  }\n}\n\n// ===========================\n//       fill vector\n// ===========================\n\nbool BlockVector::isDense() const\n{\n  return std::find_if(_vect.begin(), _vect.end(), TestDense()) != _vect.end();\n}\n\nvoid BlockVector::zero()\n{\n  VectorOfVectors::iterator it;\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n    (*it)->zero();\n}\n\nvoid BlockVector::fill(double value)\n{\n  VectorOfVectors::iterator it;\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n    if((*it))(*it)->fill(value);\n}\n\n//=====================\n// screen display\n//=====================\n\nvoid BlockVector::display() const\n{\n  VectorOfVectors::const_iterator it;\n  std::cout << \"=======> Block Vector Display (\" << _tabIndex->size() << \" block(s)): \" << std::endl;\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n  {\n    DEBUG_EXPR(std::cout <<\"(*it)\" << (*it) << std::endl;);\n    if(*it)\n      (*it)->display();\n    else\n      std::cout << \"(*it)-> nullptr\" <<std::endl;\n  }\n}\n\n//=====================\n// convert to a string\n//=====================\n\nstd::string BlockVector::toString() const\n{\n  return ::toString(*this);\n}\n\n//=====================\n// convert to an ostream\n//=====================\n\nstd::ostream& operator<<(std::ostream& os, const BlockVector& bv)\n{\n  VectorOfVectors::const_iterator it;\n  os << \"[\" << bv._vect.size() << \"](\";\n  for(it = bv._vect.begin(); it != bv._vect.end(); ++it)\n  {\n    if(it != bv._vect.begin()) os << \",\";\n    if(*it) os << **it;\n    else os << \"(nil)\";\n  }\n  os << \")\";\n  return os;\n}\n\n//=============================\n// Elements access (get or set)\n//=============================\n\ndouble BlockVector::getValue(unsigned int pos) const\n{\n  unsigned int blockNum = 0;\n\n  while(pos >= (*_tabIndex)[blockNum] && blockNum < _tabIndex->size())\n    blockNum ++;\n\n  unsigned int relativePos = pos;\n\n  if(blockNum != 0)\n    relativePos -= (*_tabIndex)[blockNum - 1];\n\n  return (*_vect[blockNum])(relativePos);\n}\n\nvoid BlockVector::setValue(unsigned int pos, double value)\n{\n  unsigned int blockNum = 0;\n\n  while(pos >= (*_tabIndex)[blockNum] && blockNum < _tabIndex->size())\n    blockNum ++;\n\n  unsigned int relativePos = pos;\n\n  if(blockNum != 0)\n    relativePos -= (*_tabIndex)[blockNum - 1];\n\n  (*_vect[blockNum])(relativePos) = value;\n}\n\ndouble& BlockVector::operator()(unsigned int pos)\n{\n  unsigned int blockNum = 0;\n\n  while(pos >= (*_tabIndex)[blockNum] && blockNum < _tabIndex->size())\n    blockNum ++;\n\n  unsigned int relativePos = pos;\n\n  if(blockNum != 0)\n    relativePos -= (*_tabIndex)[blockNum - 1];\n\n  return (*_vect[blockNum])(relativePos);\n}\n\ndouble BlockVector::operator()(unsigned int pos) const\n{\n  return getValue(pos);\n}\n\n//============================================\n// Access (get or set) to blocks of elements\n//============================================\n\n\nvoid BlockVector::setVector(unsigned int pos, const SiconosVector& v)\n{\n  assert(pos < _vect.size() && \"insertion out of vector size\");\n  if(! _vect[pos])\n    THROW_EXCEPTION(\"this[pos] == nullptr pointer.\");\n  *_vect[pos] = v ;\n}\n\nvoid BlockVector::setVectorPtr(unsigned int pos, SP::SiconosVector v)\n{\n  assert(pos < _vect.size() && \"insertion out of vector size\");\n  _vect[pos] = v;\n  _update();\n}\n\nvoid BlockVector::setAllVect(VectorOfVectors& v)\n{\n  _vect = v;\n  _update();\n}\n\n// SP::SiconosVector BlockVector::operator [](unsigned int pos)\n// {\n//   return  _vect[pos];\n// }\n\n// SPC::SiconosVector BlockVector::operator [](unsigned int pos) const\n// {\n//   return  _vect[pos];\n// }\n\nunsigned int BlockVector::getNumVectorAtPos(unsigned int pos) const\n{\n  unsigned int blockNum = 0;\n\n  while(pos >= (*_tabIndex)[blockNum] && blockNum < _tabIndex->size() - 1)\n    blockNum ++;\n  return blockNum;\n}\n\n\nBlockVector& BlockVector::operator = (const BlockVector& vIn)\n{\n  if(&vIn == this) return *this;\n  else\n  {\n    if(isComparableTo(*this, vIn))  // if vIn and this are \"block-consistent\"\n    {\n      VectorOfVectors::iterator it1;\n      VectorOfVectors::const_iterator it2 = vIn.begin();\n\n      for(it1 = _vect.begin(); it1 != _vect.end(); ++it1)\n      {\n        (**it1) = (**it2);\n        it2++;\n      }\n    }\n    else\n    {\n      for(unsigned int i = 0; i < _sizeV; ++i)\n        (*this)(i) = vIn(i);\n    }\n    return *this;\n  }\n}\n\nBlockVector& BlockVector::operator = (const double* data)\n{\n  VectorOfVectors::iterator it1;\n  unsigned indxPos = 0;\n\n  for(it1 = _vect.begin(); it1 != _vect.end(); ++it1)\n  {\n    SiconosVector& v = **it1;\n    v = &data[indxPos];\n    indxPos += v.size();\n  }\n  return *this;\n}\n\n\nBlockVector& BlockVector::operator -= (const BlockVector& vIn)\n{\n  if(isComparableTo(*this, vIn))  // if vIn and this are \"block-consistent\"\n  {\n    unsigned int i = 0;\n    VectorOfVectors::iterator it1;\n\n    for(it1 = _vect.begin(); it1 != _vect.end(); ++it1)\n      **it1 -= *(vIn.vector(i++));\n  }\n  else // use of a temporary SimpleVector... bad way, to be improved. But this case happens rarely ...\n  {\n    for(unsigned int i = 0; i < _sizeV; ++i)\n      (*this)(i) -= vIn(i);\n  }\n  return *this;\n}\n\nBlockVector& BlockVector::operator -= (const SiconosVector& vIn)\n{\n  unsigned int dim = vIn.size(); // size of the block to be added.\n  if(dim > _sizeV) THROW_EXCEPTION(\"invalid ranges\");\n\n  VectorOfVectors::const_iterator it;\n  Siconos::UBLAS_TYPE numVIn = vIn.num();\n  unsigned int currentSize;\n  Siconos::UBLAS_TYPE currentNum;\n  unsigned int index = 0;\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n  {\n    currentSize = (*it)->size();\n    currentNum = (*it)->num();\n    if(numVIn != currentNum)\n      THROW_EXCEPTION(\"inconsistent types.\");\n    if(numVIn == Siconos::DENSE)\n      noalias(*(*it)->dense()) -=  ublas::subrange(*vIn.dense(), index, index + currentSize) ;\n    else\n      noalias(*(*it)->sparse()) -=  ublas::subrange(*vIn.sparse(), index, index + currentSize) ;\n    index += currentSize;\n  }\n  return *this;\n}\n\nBlockVector& BlockVector::operator += (const BlockVector& vIn)\n{\n  if(isComparableTo(*this, vIn))  // if vIn and this are \"block-consistent\"\n  {\n    unsigned int i = 0;\n    VectorOfVectors::iterator it1;\n\n    for(it1 = _vect.begin(); it1 != _vect.end(); ++it1)\n      **it1 += *(vIn.vector(i++));\n  }\n  else // use of a temporary SimpleVector... bad way, to be improved. But this case happens rarely ...\n  {\n    for(unsigned int i = 0; i < _sizeV; ++i)\n      (*this)(i) += vIn(i);\n  }\n  return *this;\n}\n\nBlockVector& BlockVector::operator += (const SiconosVector& vIn)\n{\n  // Add a part of vIn (starting from index) to the current vector.\n  // vIn must be a SimpleVector.\n\n  // At the end of the present function, index is equal to index + the dim. of the added sub-vector.\n\n  unsigned int dim = vIn.size(); // size of the block to be added.\n  if(dim > _sizeV) THROW_EXCEPTION(\"invalid ranges\");\n\n  VectorOfVectors::const_iterator it;\n  Siconos::UBLAS_TYPE numVIn = vIn.num(), currentNum;\n  unsigned int currentSize;\n  unsigned int index = 0;\n\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n  {\n    currentSize = (*it)->size();\n    currentNum = (*it)->num();\n    if(numVIn != currentNum) THROW_EXCEPTION(\"inconsistent types.\");\n    if(numVIn == Siconos::DENSE)\n      noalias(*(*it)->dense()) += ublas::subrange(*vIn.dense(), index, index + currentSize) ;\n    else\n      noalias(*(*it)->sparse()) += ublas::subrange(*vIn.sparse(), index, index + currentSize) ;\n    index += currentSize;\n  }\n  return *this;\n}\n\n// void BlockVector::insert(const  SiconosVector& v)\n// {\n//   _sizeV += v.size();\n\n//   _vect.push_back(std::shared_ptr<SiconosVector>(new SiconosVector(v))); // Copy\n\n//   _tabIndex->push_back(_sizeV);\n// }\n\nvoid BlockVector::insertPtr(SP::SiconosVector v)\n{\n  if(!v)\n    THROW_EXCEPTION(\"v is a nullptr vector.\");\n\n  _sizeV += v->size();\n  _vect.push_back(v);\n  _tabIndex->push_back(_sizeV);\n}\n\nvoid BlockVector::setBlock(const SiconosVector& vIn, unsigned int sizeB, unsigned int startIn, unsigned int startOut)\n{\n  // Check dim ...\n  unsigned int endOut = startOut + sizeB;\n\n  assert(startIn < vIn.size());\n  assert(startOut < size());\n  assert((startIn + sizeB) <= vIn.size());\n  assert(endOut <= size());\n\n  // We look for the block of vOut that include index startOut\n  unsigned int blockOutStart = 0;\n  while(startOut >= (*_tabIndex)[blockOutStart] && blockOutStart < _tabIndex->size())\n    blockOutStart++;\n  // Relative position in the block blockOutStart.\n  unsigned int posOut = startOut;\n  if(blockOutStart != 0)\n    posOut -= (*_tabIndex)[blockOutStart - 1];\n\n  // We look for the block of vOut that include index endOut\n  unsigned int blockOutEnd = blockOutStart;\n  while(endOut > (*_tabIndex)[blockOutEnd] && blockOutEnd < _tabIndex->size())\n    blockOutEnd ++;\n\n  // => the block to be set runs from block number blockOutStart to block number blockOutEnd.\n\n  if(blockOutEnd == blockOutStart)  //\n  {\n    vIn.toBlock(*_vect[blockOutStart], sizeB, startIn, posOut);\n  }\n  else // More that one block of vOut are concerned\n  {\n\n    // The current considered block ...\n    SP::SiconosVector currentBlock = _vect[blockOutStart];\n\n    // Size of the subBlock of vOut to be set.\n    size_t subSizeB = currentBlock->size() - posOut;\n    unsigned int posIn = startIn;\n\n    // Set first sub-block (currentBlock) values, between index posOut and posOut+subSizeB,\n    // with vIn values from posIn to posIn+subSizeB.\n    vIn.toBlock(*currentBlock, subSizeB, posIn, posOut);\n\n    // Other blocks, except number blockOutEnd.\n    unsigned int currentBlockNum = blockOutStart + 1;\n    while(currentBlockNum != blockOutEnd)\n    {\n      posIn += subSizeB;\n      currentBlock = _vect[currentBlockNum];\n      subSizeB = currentBlock->size();\n      vIn.toBlock(*currentBlock, subSizeB, posIn, 0);\n      currentBlockNum++;\n    }\n    // set last subBlock ...\n    currentBlock = _vect[blockOutEnd];\n\n    posIn += subSizeB;\n\n    // Size of the considered sub-block\n    subSizeB = endOut - (*_tabIndex)[blockOutEnd - 1];\n\n    vIn.toBlock(*currentBlock, subSizeB, posIn, 0);\n  }\n\n}\n\ndouble BlockVector::norm2() const\n{\n  double d = 0;\n  VectorOfVectors::const_iterator it;\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n  {\n    assert(*it);\n    d += pow((*it)->norm2(), 2);\n  }\n  return sqrt(d);\n}\n\ndouble BlockVector::normInf() const\n{\n  double d = 0;\n  VectorOfVectors::const_iterator it;\n  for(it = _vect.begin(); it != _vect.end(); ++it)\n  {\n    assert(*it);\n    d = fmax((*it)->normInf(), d);\n  }\n  return d;\n}\n\n\n\nSP::SiconosVector BlockVector::prepareVectorForPlugin() const\n{\n  {\n    if(_tabIndex->size()> 1)\n    {\n      SP::SiconosVector copy(new SiconosVector(*this));\n      return copy;\n    }\n    else\n    {\n      // No copy, just a ref.\n      return _vect[0];\n    }\n  }\n}\n\n\n\n\nBlockVector& BlockVector::operator =(const SiconosVector& vIn)\n{\n  setBlock(vIn, _sizeV, 0, 0);\n  return *this;\n}\n\nBlockVector& BlockVector::operator *= (double s)\n{\n  VectorOfVectors::iterator it;\n  for(it = begin(); it != end(); ++it)\n    (**it) *= s;\n  return *this;\n}\n\nBlockVector& BlockVector::operator /= (double s)\n{\n  VectorOfVectors::iterator it;\n  for(it = begin(); it != end(); ++it)\n    (**it) /= s;\n  return *this;\n}\n", "meta": {"hexsha": "e164a2661d24098500c5d690914068d461d3c215", "size": 14894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/BlockVector.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/BlockVector.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/BlockVector.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": 24.9480737018, "max_line_length": 127, "alphanum_fraction": 0.6210554586, "num_tokens": 4206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.05749328122276937, "lm_q1q2_score": 0.017862839548489225}}
{"text": "// Copyright (c) 2009, Hikaru Inoue, Akihiro Yamasaki,\r\n// All rights reserved.\r\n//\r\n// Redistribution and use in source and binary forms, with or without\r\n// modification, are permitted provided that the following conditions are\r\n// met:\r\n//\r\n//    * Redistributions of source code must retain the above copyright\r\n//      notice, this list of conditions and the following disclaimer.\r\n//    * Redistributions in binary form must reproduce the above\r\n//      copyright notice, this list of conditions and the following\r\n//      disclaimer in the documentation and/or other materials provided\r\n//      with the distribution.\r\n//    * The names of the contributors may not be used to endorse or promote\r\n//      products derived from this software without specific prior written\r\n//      permission.\r\n//\r\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <boost/bind.hpp>\r\n#include <boost/spirit.hpp>\r\n#include \"jitasm.h\"\r\n\r\n\r\nclass RenderExpr : public jitasm::function<void, RenderExpr, void *, size_t, void *, size_t, void *, size_t, int, int>\r\n{\r\nprivate:\r\n\tstruct Calculator : public boost::spirit::grammar<Calculator>\r\n\t{\r\n\t\tRenderExpr& renderExpr_;\r\n\t\tCalculator(RenderExpr& renderExpr) : renderExpr_(renderExpr) {}\r\n\r\n\t\ttemplate <typename ScannerT>\r\n\t\tstruct definition\r\n\t\t{\r\n\t\t\tdefinition(Calculator const& self)\r\n\t\t\t{\r\n\t\t\t\tusing namespace boost;\r\n\t\t\t\tusing namespace boost::spirit;\r\n\t\t\t\texpression\r\n\t\t\t\t\t=\tterm\r\n\t\t\t\t\t\t>> *(   (L'+' >> term)[boost::bind(&do_add, ref(self.renderExpr_), _1, _2)]\r\n\t\t\t\t\t\t\t|\t(L'-' >> term)[boost::bind(&do_sub, ref(self.renderExpr_), _1, _2)]\r\n\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\tterm\r\n\t\t\t\t\t=   factor\r\n\t\t\t\t\t\t>> *(   (L'*' >> factor)[boost::bind(&do_mul, ref(self.renderExpr_), _1, _2)]\r\n\t\t\t\t\t\t\t|   (L'/' >> factor)[boost::bind(&do_div, ref(self.renderExpr_), _1, _2)]\r\n\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\tfactor\r\n\t\t\t\t\t=   real_p[boost::bind(&do_real, ref(self.renderExpr_), _1)]\r\n\t\t\t\t\t|\tchseq_p(L\"src1\")[boost::bind(&do_src1, ref(self.renderExpr_), _1, _2)]\r\n\t\t\t\t\t|\tchseq_p(L\"src2\")[boost::bind(&do_src2, ref(self.renderExpr_), _1, _2)]\r\n\t\t\t\t\t|   L'(' >> expression >> L')'\r\n\t\t\t\t\t|   (L'-' >> factor)[boost::bind(&do_neg, ref(self.renderExpr_), _1, _2)]\r\n\t\t\t\t\t|   (L'+' >> factor);\r\n\t\t\t}\r\n\r\n\t\t\tboost::spirit::rule<ScannerT> expression, term, factor;\r\n\r\n\t\t\tboost::spirit::rule<ScannerT> const& start() const { return expression; }\r\n\t\t};\r\n\t};\r\n\r\n\tvoid do_add(const wchar_t *, const wchar_t *)\r\n\t{\r\n\t\tXmmReg reg1 = variableStack_.back();\r\n\t\tvariableStack_.pop_back();\r\n\t\tXmmReg reg2 = variableStack_.back();\r\n\t\taddps(reg2, reg1);\r\n\t}\r\n\r\n\tvoid do_sub(const wchar_t *, const wchar_t *)\r\n\t{\r\n\t\tXmmReg reg1 = variableStack_.back();\r\n\t\tvariableStack_.pop_back();\r\n\t\tXmmReg reg2 = variableStack_.back();\r\n\t\tsubps(reg2, reg1);\r\n\t}\r\n\r\n\tvoid do_mul(const wchar_t *, const wchar_t *)\r\n\t{\r\n\t\tXmmReg reg1 = variableStack_.back();\r\n\t\tvariableStack_.pop_back();\r\n\t\tXmmReg reg2 = variableStack_.back();\r\n\t\tmulps(reg2, reg1);\r\n\t}\r\n\r\n\tvoid do_div(const wchar_t *, const wchar_t *)\r\n\t{\r\n\t\tXmmReg reg1 = variableStack_.back();\r\n\t\tvariableStack_.pop_back();\r\n\t\tXmmReg reg2 = variableStack_.back();\r\n\t\tdivps(reg2, reg1);\r\n\t}\r\n\r\n\tvoid do_real(double val)\r\n\t{\r\n\t\tfloat fval = static_cast<float>(val);\r\n\t\tmov(eax, *(unsigned int*)&fval);\r\n\t\tXmmReg var;\r\n\t\tmovd(var, eax);\r\n\t\tshufps(var, var, 0);\r\n\t\tvariableStack_.push_back(var);\r\n\t}\r\n\r\n\tvoid do_src(int i)\r\n\t{\r\n\t\t__declspec(align(16)) const static float factor8bpp[4] = {1.0f/255.0f, 1.0f/255.0f, 1.0f/255.0f, 1.0f/255.0f};\r\n\t\tXmmReg src;\r\n\t\tmovd(src, dword_ptr[i == 0 ? zsi : zbx]);\r\n\t\tpunpcklbw(src, zero_);\r\n\t\tpunpcklwd(src, zero_);\r\n\t\tcvtdq2ps(src, src);\r\n\t\tmov(zax, (uintptr_t)factor8bpp);\r\n\t\tmulps(src, xmmword_ptr[zax]);\r\n\t\tvariableStack_.push_back(src);\r\n\t}\r\n\r\n\tvoid do_src1(const wchar_t *, const wchar_t *)\r\n\t{\r\n\t\tdo_src(0);\r\n\t}\r\n\r\n\tvoid do_src2(const wchar_t *, const wchar_t *)\r\n\t{\r\n\t\tdo_src(1);\r\n\t}\r\n\r\n\tvoid do_neg(const wchar_t *, const wchar_t *)\r\n\t{\r\n\t\tXmmReg var = variableStack_.back();\r\n\t\tXmmReg tmp;\r\n\t\txorps(tmp, tmp);\r\n\t\tsubps(tmp, var);\r\n\t\tmovaps(var, tmp);\r\n\t}\r\n\r\npublic:\r\n\tRenderExpr(wchar_t *expr) : expr_(expr) {}\r\n\r\n\tvoid main(Addr dst, Addr dstSkip, Addr src1, Addr src1Skip, Addr src2, Addr src2Skip, Addr width, Addr height)\r\n\t{\r\n\t\tmov(zsi, ptr[src1]);\r\n\t\tmov(zbx, ptr[src2]);\r\n\t\tmov(zdi, ptr[dst]);\r\n\t\txorps(zero_, zero_);\r\n\r\n\t\tL(\"LoopY\");\r\n\t\t{\r\n\t\t\tmov(ecx, dword_ptr[width]);\r\n\r\n\t\t\tL(\"LoopX\");\r\n\t\t\t{\r\n\t\t\t\tCalculator calc(*this);\r\n\t\t\t\tboost::spirit::parse_info<const wchar_t *> info = boost::spirit::parse(expr_, calc, boost::spirit::space_p);\r\n\t\t\t\tif (!info.full)\r\n\t\t\t\t\tthrow info;\r\n\r\n\t\t\t\t__declspec(align(16)) const static float factor8bpp[4] = {255.0f, 255.0f, 255.0f, 255.0f};\r\n\t\t\t\tmov(zax, (uintptr_t)factor8bpp);\r\n\t\t\t\tXmmReg dstReg = variableStack_.back();\r\n\t\t\t\tmulps(dstReg, xmmword_ptr[zax]);\r\n\t\t\t\tcvtps2dq(dstReg, dstReg);\r\n\t\t\t\tpackssdw(dstReg, dstReg);\r\n\t\t\t\tpackuswb(dstReg, dstReg);\r\n\t\t\t\tmovd(eax, dstReg);\r\n\t\t\t\tmovnti(dword_ptr[zdi], eax);\r\n\r\n\t\t\t\tadd(zsi, 4);\r\n\t\t\t\tadd(zbx, 4);\r\n\t\t\t\tadd(zdi, 4);\r\n\t\t\t\tdec(ecx);\r\n\t\t\t\tjnz(\"LoopX\");\r\n\t\t\t}\r\n\r\n\t\t\tadd(zsi, ptr[src1Skip]);\r\n\t\t\tadd(zbx, ptr[src2Skip]);\r\n\t\t\tadd(zdi, ptr[dstSkip]);\r\n\t\t\tdec(dword_ptr[height]);\r\n\t\t\tjnz(\"LoopY\");\r\n\t\t}\r\n\t}\r\n\r\nprivate:\r\n\twchar_t *expr_;\r\n\tstd::vector<XmmReg> variableStack_;\r\n\tXmmReg zero_;\r\n};\r\n\r\nbool RenderJIT(wchar_t *expr, void *dst, size_t dstStride, void *src1, size_t src1Stride, void *src2, size_t src2Stride, int width, int height)\r\n{\r\n\ttry {\r\n\t\tRenderExpr renderExpr(expr);\r\n\t\trenderExpr(dst, dstStride - width * 4, src1, src1Stride - width * 4, src2, src2Stride - width * 4, width, height);\r\n\r\n\t\t//FILE *file = fopen(\"render.dmp\", \"wb\");\r\n\t\t//fwrite(renderExpr.GetCode(), 1, renderExpr.GetCodeSize(), file);\r\n\t\t//fclose(file);\r\n\r\n\t\treturn true;\r\n\t}\r\n\tcatch (...) {\r\n\t\treturn false;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "5b601c1123ad727f94a0b92bd17fc4c84ede2780", "size": 6540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jitasm/samples/pixel_calc/pixel_calc_jit.cpp", "max_stars_repo_name": "Traderain/ProjectNovigrad", "max_stars_repo_head_hexsha": "cc4b0286612a950cba37c0140db0409c3aa22c50", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T19:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T11:33:03.000Z", "max_issues_repo_path": "jitasm/samples/pixel_calc/pixel_calc_jit.cpp", "max_issues_repo_name": "Traderain/ProjectNovigrad", "max_issues_repo_head_hexsha": "cc4b0286612a950cba37c0140db0409c3aa22c50", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jitasm/samples/pixel_calc/pixel_calc_jit.cpp", "max_forks_repo_name": "Traderain/ProjectNovigrad", "max_forks_repo_head_hexsha": "cc4b0286612a950cba37c0140db0409c3aa22c50", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-25T22:28:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-25T22:28:49.000Z", "avg_line_length": 29.592760181, "max_line_length": 144, "alphanum_fraction": 0.644648318, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.035678552800292834, "lm_q1q2_score": 0.017839276400146417}}
{"text": "/*\n * This file is part of the Visual Computing Library (VCL) release under the\n * MIT license.\n *\n * Copyright (c) 2015 Basil Fierz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n#include <vcl/graphics/frustum.h>\n\n// Eigen library\n#include <Eigen/Eigenvalues>\n\n// VCL\n#include <vcl/core/contract.h>\n#include <vcl/graphics/matrixfactory.h>\n#include <vcl/graphics/camera.h>\n#include <vcl/math/math.h>\n\nnamespace Vcl { namespace Graphics\n{\n\ttemplate<typename Scalar>\n\tPerspectiveViewFrustum<Scalar>::PerspectiveViewFrustum()\n\t: PerspectiveViewFrustum(0, 0, (float) (M_PI / 4.0), 0.01, 100, {0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 0, 0})\n\t{\n\t}\n\n\ttemplate<typename Scalar>\n\tPerspectiveViewFrustum<Scalar>::PerspectiveViewFrustum\n\t(\n\t\treal_t width, real_t height, real_t fov, real_t near_plane, real_t far_plane,\n\t\tvector3_t pos, vector3_t dir, vector3_t up, vector3_t right\n\t)\n\t:\t_x(width), _y(height), _fov(fov), _near(near_plane), _far(far_plane),\n\t\t_position(pos), _direction(dir), _up(up), _right(right)\n\t{\n\t\tcomputePlanes();\n\t}\n\n\ttemplate<typename Scalar>\n\tPerspectiveViewFrustum<Scalar>::PerspectiveViewFrustum(const Vcl::Graphics::Camera* cam)\n\t: PerspectiveViewFrustum\n\t  (\n\t\tcam->viewportWidth(), cam->viewportHeight(), cam->fieldOfView(), cam->nearPlane(), cam->farPlane(),\n\t\tcam->position().cast<Scalar>(),\n\t\tcam->direction().cast<Scalar>(),\n\t\tcam->direction().cross(cam->up().cross(cam->direction()).normalized()).normalized().cast<Scalar>(),\n\t\tcam->up().cross(cam->direction()).normalized().cast<Scalar>()\n\t  )\n\t{\n\t}\n\n\ttemplate<typename Scalar>\n\tPerspectiveViewFrustum<Scalar>::PerspectiveViewFrustum(const PerspectiveViewFrustum<real_t>& rhs)\n\t{\n\t\t_x = rhs._x;\n\t\t_y = rhs._y;\n\t\t_fov = rhs._fov;\n\t\t_near = rhs._near;\n\t\t_far = rhs._far;\n\t\t_position = rhs._position;\n\t\t_direction = rhs._direction;\n\t\t_up = rhs._up;\n\t\t_right = rhs._right;\n\n\t\t_corners = rhs._corners;\n\t\t_planes = rhs._planes;\n\t}\n\n\ttemplate<typename Scalar>\n\tconst typename PerspectiveViewFrustum<Scalar>::vector3_t& PerspectiveViewFrustum<Scalar>::position() const\n\t{\n\t\treturn _position;\n\t}\n\t\t\t\t\t\n\t\t\n\ttemplate<typename Scalar>\n\tconst typename PerspectiveViewFrustum<Scalar>::vector3_t& PerspectiveViewFrustum<Scalar>::direction() const\n\t{\n\t\treturn _direction;\n\t}\n\t\t\n\ttemplate<typename Scalar>\n\tconst typename PerspectiveViewFrustum<Scalar>::vector3_t& PerspectiveViewFrustum<Scalar>::up() const\n\t{\n\t\treturn _up;\n\t}\t\n\t\t\n\ttemplate<typename Scalar>\n\tconst typename PerspectiveViewFrustum<Scalar>::vector3_t& PerspectiveViewFrustum<Scalar>::right() const\n\t{\n\t\treturn _right;\n\t}\n\n\ttemplate<typename Scalar>\n\ttypename PerspectiveViewFrustum<Scalar>::real_t PerspectiveViewFrustum<Scalar>::width() const\n\t{\n\t\treturn _x;\n\t}\n\t\n\ttemplate<typename Scalar>\n\ttypename PerspectiveViewFrustum<Scalar>::real_t PerspectiveViewFrustum<Scalar>::height() const\n\t{\n\t\treturn _y;\n\t}\n\n\ttemplate<typename Scalar>\n\ttypename PerspectiveViewFrustum<Scalar>::real_t PerspectiveViewFrustum<Scalar>::fieldOfView() const\n\t{\n\t\treturn _fov;\n\t}\n\t\n\ttemplate<typename Scalar>\n\ttypename PerspectiveViewFrustum<Scalar>::real_t PerspectiveViewFrustum<Scalar>::nearPlane() const\n\t{\n\t\treturn _near;\n\t}\n\t\t\n\ttemplate<typename Scalar>\n\ttypename PerspectiveViewFrustum<Scalar>::real_t PerspectiveViewFrustum<Scalar>::farPlane() const\n\t{\n\t\treturn _far;\n\t}\n\n\ttemplate<typename Scalar>\n\tbool PerspectiveViewFrustum<Scalar>::isInside(vector3_t p)\n\t{\n\t\tfor (int i = 0; i < 6; i++)\n\t\t\tif (_planes[i].signedDistance(p) < 0)\n\t\t\t\treturn false; \n\n\t\treturn true;\n\t}\n\n\ttemplate<typename Scalar>\n\tconst typename PerspectiveViewFrustum<Scalar>::vector3_t& PerspectiveViewFrustum<Scalar>::corner(unsigned int i) const\n\t{\n\t\tRequire(i < 8, \"Index is valid.\");\n\n\t\treturn _corners[i];\n\t}\n\n\ttemplate<typename Scalar>\n\tvoid PerspectiveViewFrustum<Scalar>::computePlanes()\n\t{\n\t\tusing Vcl::Mathematics::equal;\n\n\t\tRequire(equal(_direction.norm(), 1, (Scalar) 1e-6), \"Direction is unit length.\", \"Length: %f\", _direction.norm());\n\t\tRequire(equal(_up.norm(), 1, (Scalar) 1e-6), \"Up is unit length.\", \"Length: %f\", _up.norm());\n\t\tRequire(equal(_right.norm(), 1, (Scalar) 1e-6), \"Right is unit length.\", \"Length: %f\", _right.norm());\n\t\t\t\n\t\treal_t ratio = _x / _y;\n\n\t\treal_t near_height = real_t(2) * std::tan(real_t(0.5) * _fov) * _near;\n\t\treal_t near_width = near_height * ratio;\n\t\t\t\n\t\treal_t far_height = real_t(2) * std::tan(real_t(0.5) * _fov) * _far;\n\t\treal_t far_width = far_height * ratio;\n\n\t\t// Far plane center\n\t\tvector3_t fc = _position + _direction * _far;\n\n\t\t// Far plane (top, left/top, right/bottom, left/top, left)\n\t\tvector3_t ftl = fc + (_up * far_height*real_t(0.5)) - (_right * far_width*real_t(0.5));\n\t\tvector3_t ftr = fc + (_up * far_height*real_t(0.5)) + (_right * far_width*real_t(0.5));\n\t\tvector3_t fbl = fc - (_up * far_height*real_t(0.5)) - (_right * far_width*real_t(0.5));\n\t\tvector3_t fbr = fc - (_up * far_height*real_t(0.5)) + (_right * far_width*real_t(0.5));\n\t\t\t\n\t\t// Near plane center\n\t\tvector3_t nc = _position + _direction * _near;\n\t\t\t\n\t\t// Near plane (top, left/top, right/bottom, left/top, left)\n\t\tvector3_t ntl = nc + (_up * near_height*real_t(0.5)) - (_right * near_width*real_t(0.5));\n\t\tvector3_t ntr = nc + (_up * near_height*real_t(0.5)) + (_right * near_width*real_t(0.5));\n\t\tvector3_t nbl = nc - (_up * near_height*real_t(0.5)) - (_right * near_width*real_t(0.5));\n\t\tvector3_t nbr = nc - (_up * near_height*real_t(0.5)) + (_right * near_width*real_t(0.5));\n\t\t\t\n\t\t// Store the corners\n\t\t_corners[0] = nbl;\n\t\t_corners[1] = nbr;\n\t\t_corners[2] = ntr;\n\t\t_corners[3] = ntl;\n\n\t\t_corners[4] = fbl;\n\t\t_corners[5] = fbr;\n\t\t_corners[6] = ftr;\n\t\t_corners[7] = ftl;\n\n\t\t// Compute the bounding planes\n\t\t//vector3_t aux, normal;\n\t\t//\n\t\t//aux = (nc + _y*near_height) - _position;\n\t\t//aux.normalize();\n\t\t//normal = aux * _x;\n\t\t//_planes[Top] = Eigen::Hyperplane<real_t, 3>(normal, nc+_up*near_height);\n\t\t//\n\t\t//aux = (nc - _y*near_height) - _position;\n\t\t//aux.normalize();\n\t\t//normal = _x * aux;\n\t\t//_planes[Bottom] = Eigen::Hyperplane<real_t, 3>(normal, nc-_y*near_height);\n\t\t//\n\t\t//aux = (nc - _x*far_width) - _position;\n\t\t//aux.normalize();\n\t\t//normal = aux * _y;\n\t\t//_planes[Left] = Eigen::Hyperplane<real_t, 3>(normal, nc-_right*near_width);\n\t\t//\n\t\t//aux = (nc + _x*far_width) - _position;\n\t\t//aux.normalize();\n\t\t//normal = _y * aux;\n\t\t//_planes[Right] = Eigen::Hyperplane<real_t, 3>(normal, nc+_right*near_width);\n\t\t//\n\t\t//_planes[Near] = Eigen::Hyperplane<real_t, 3>(-_direction, nc);\n\t\t//_planes[Far] = Eigen::Hyperplane<real_t, 3>(_direction, fc);\n\t}\n\n\ttemplate<typename Scalar>\n\tOrthographicViewFrustum<Scalar>::OrthographicViewFrustum()\n\t: _x(0)\n\t, _y(0)\n\t, _near(0.01)\n\t, _far(100)\n\t, _position(0, 0, 0)\n\t, _direction(0, 0, 1)\n\t, _up(0, 1, 0)\n\t, _right(1, 0, 0)\n\t{\n\t\tcomputePlanes();\n\t}\n\n\ttemplate<typename Scalar>\n\tOrthographicViewFrustum<Scalar>::OrthographicViewFrustum\n\t(\n\t\treal_t width, real_t height, real_t near_plane, real_t far_plane, vector3_t pos, vector3_t dir, vector3_t up, vector3_t right\n\t)\n\t: _x(width)\n\t, _y(height)\n\t, _near(near_plane)\n\t, _far(far_plane)\n\t, _position(pos)\n\t, _direction(dir)\n\t, _up(up)\n\t, _right(right)\n\t{\n\t\tcomputePlanes();\n\t}\n\n\ttemplate<typename Scalar>\n\tOrthographicViewFrustum<Scalar>::OrthographicViewFrustum\n\t(\n\t\tconst OrthographicViewFrustum<real_t>& rhs\n\t)\n\t{\n\t\t_x = rhs._x;\n\t\t_y = rhs._y;\n\t\t_near = rhs._near;\n\t\t_far = rhs._far;\n\t\t_position = rhs._position;\n\t\t_direction = rhs._direction;\n\t\t_up = rhs._up;\n\t\t_right = rhs._right;\n\n\t\t_corners = rhs._corners;\n\t\t_planes = rhs._planes;\n\t}\n\n\ttemplate<typename Scalar>\n\tconst typename OrthographicViewFrustum<Scalar>::vector3_t& OrthographicViewFrustum<Scalar>::position() const\n\t{\n\t\treturn _position;\n\t}\n\t\t\t\t\t\n\ttemplate<typename Scalar>\n\tconst typename OrthographicViewFrustum<Scalar>::vector3_t& OrthographicViewFrustum<Scalar>::direction() const\n\t{\n\t\treturn _direction;\n\t}\n\t\t\n\ttemplate<typename Scalar>\n\tconst typename OrthographicViewFrustum<Scalar>::vector3_t& OrthographicViewFrustum<Scalar>::up() const\n\t{\n\t\treturn _up;\n\t}\n\t\t\n\ttemplate<typename Scalar>\n\tconst typename OrthographicViewFrustum<Scalar>::vector3_t& OrthographicViewFrustum<Scalar>::right() const\n\t{\n\t\treturn _right;\n\t}\n\t\t\t\n\t\t\n\ttemplate<typename Scalar>\n\ttypename OrthographicViewFrustum<Scalar>::real_t OrthographicViewFrustum<Scalar>::nearPlane() const\n\t{\n\t\treturn _near;\n\t}\n\t\t\n\ttemplate<typename Scalar>\n\ttypename OrthographicViewFrustum<Scalar>::real_t OrthographicViewFrustum<Scalar>::farPlane() const\n\t{\n\t\treturn _far;\n\t}\n\t\t\t\t\t\n\ttemplate<typename Scalar>\n\ttypename OrthographicViewFrustum<Scalar>::real_t OrthographicViewFrustum<Scalar>::width() const\n\t{\n\t\treturn _x;\n\t}\n\t\t\t\t\t\n\ttemplate<typename Scalar>\n\ttypename OrthographicViewFrustum<Scalar>::real_t OrthographicViewFrustum<Scalar>::height() const\n\t{\n\t\treturn _y;\n\t}\n\n\ttemplate<typename Scalar>\n\tbool OrthographicViewFrustum<Scalar>::isInside(vector3_t p)\n\t{\n\t\tfor (int i = 0; i < 6; i++)\n\t\t\tif (_planes[i].signedDistance(p) < 0)\n\t\t\t\treturn false; \n\n\t\treturn true;\n\t}\n\n\ttemplate<typename Scalar>\n\tconst typename OrthographicViewFrustum<Scalar>::vector3_t& OrthographicViewFrustum<Scalar>::corner(unsigned int i) const\n\t{\n\t\tRequire(i < 8, \"Index is valid.\");\n\n\t\treturn _corners[i];\n\t}\n\n\ttemplate<typename Scalar>\n\tEigen::Matrix<Scalar, 4, 4> OrthographicViewFrustum<Scalar>::computeViewMatrix(const MatrixFactory& factory) const\n\t{\n\t\tusing Vcl::Mathematics::equal;\n\t\t\t\n\t\tRequire(equal(_direction.cross(_up).dot(_right), 1, (Scalar) 1e-4), \"Frame is orthogonal.\", \"Angle: %f\", _direction.cross(_up).dot(_right));\n\n\t\treturn factory.createLookAt(_position.template cast<float>(), _direction.template cast<float>(), _up.template cast<float>(), Handedness::RightHanded).template cast<Scalar>();\n\t}\n\n\ttemplate<typename Scalar>\n\tEigen::Matrix<Scalar, 4, 4> OrthographicViewFrustum<Scalar>::computeProjectionMatrix(const MatrixFactory& factory) const\n\t{\t\t\n\t\tRequire(_x > 0, \"Width is valid\");\n\t\tRequire(_y > 0, \"Height is valid\");\n\t\tRequire(_near > 0, \"Near plane is valid\");\n\t\tRequire(_far > 0, \"Far plane is valid\");\n\t\t\n\t\treturn factory.createOrtho((float) _x, (float) _y, (float) nearPlane(), (float) farPlane(), Handedness::RightHanded).cast<Scalar>();\n\t}\n\t\n\ttemplate<typename Scalar>\n\tOrthographicViewFrustum<Scalar> OrthographicViewFrustum<Scalar>::enclose(const PerspectiveViewFrustum<real_t>& frustum, const vector3_t& orthographic_direction)\n\t{\n\t\tusing Vcl::Mathematics::equal;\n\n\t\tvector3_t dir = -orthographic_direction.normalized();\n\n\t\t// OBB positions & normals\n\t\tstd::array<vector3_t, 6> p; p.fill(frustum.corner(0));\n\t\tstd::array<vector3_t, 6> n;\n\t\tstd::array<int, 6> idx;     idx.fill(0);\n\n\t\t// Near/Far plane\n\t\tn[0] =  dir;\n\t\tn[1] = -dir;\n\t\tfor (int i = 1; i < 8; i++)\n\t\t{\n\t\t\treal_t d0 = n[0].dot(frustum.corner(i) - p[0]);\n\t\t\treal_t d1 = n[1].dot(frustum.corner(i) - p[1]);\n\t\t\tif (d0 > 0) { p[0] = frustum.corner(i); idx[0] = i; }\n\t\t\tif (d1 > 0) { p[1] = frustum.corner(i); idx[1] = i; }\n\t\t}\n\n\t\t// Project points on near plane\n\t\tstd::array<vector3_t, 8> proj_points;\n\t\tfor (int i = 0; i < 8; i++)\n\t\t{\n\t\t\treal_t d = dir.dot(frustum.corner(i) - p[0]);\n\t\t\tproj_points[i] = frustum.corner(i) - d * dir;\n\t\t\tCheck(equal(dir.dot(proj_points[i] - p[0]), 0, (Scalar) 1e-3), \"Projected point is on plane\", \"d = %f\", dir.dot(proj_points[i] - p[0]));\n\t\t}\n\n\t\t// Compute center of projected points\n\t\tvector3_t m = vector3_t::Zero();\n\t\tfor (int i = 0; i < 8; i++)\n\t\t\tm += proj_points[i];\n\t\tm /= 8;\n\n\t\t// Compute projected center point\n\t\t//vector3_t c = \n\t\t//\treal_t(0.5)*(frustum.position() + frustum.nearPlane()*frustum.direction()) + \n\t\t//\treal_t(0.5)*(frustum.position() +  frustum.farPlane()*frustum.direction())  ;\n\t\t//real_t dc = dir.dot(c - p[0]);\n\t\t//c -= dc * dir;\n\n\t\t// Compute PCA of projected points\n\t\tEigen::Matrix<real_t, 3, 8> Y;\n\t\tfor (int i = 0; i < 8; i++)\n\t\t\tY.col(i) = proj_points[i] - m;\n\n\t\tEigen::Matrix<real_t, 3, 3> S = Y*Y.transpose();\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix<real_t, 3, 3>> eig(S);\n\n\t\t// Compute planes orthogonal to the main directions\n\t\tn[2] =  eig.eigenvectors().col(2).normalized();\n\t\tn[3] = -eig.eigenvectors().col(2).normalized();\n\t\tn[4] =  eig.eigenvectors().col(1).normalized();\n\t\tn[5] = -eig.eigenvectors().col(1).normalized();\n\n\t\t// Check if frame is orthogonal, else change it\n\t\tif (-dir.cross(n[5]).dot(n[3]) < 0)\n\t\t\tstd::swap(n[4], n[5]);\n\t\t\t\n\t\tfor (int i = 1; i < 8; i++)\n\t\t{\n\t\t\treal_t d2 = n[2].dot(frustum.corner(i) - p[2]);\n\t\t\treal_t d3 = n[3].dot(frustum.corner(i) - p[3]);\n\t\t\treal_t d4 = n[4].dot(frustum.corner(i) - p[4]);\n\t\t\treal_t d5 = n[5].dot(frustum.corner(i) - p[5]);\n\t\t\tif (d2 > 0) { p[2] = frustum.corner(i); idx[2] = i; }\n\t\t\tif (d3 > 0) { p[3] = frustum.corner(i); idx[3] = i; }\n\t\t\tif (d4 > 0) { p[4] = frustum.corner(i); idx[4] = i; }\n\t\t\tif (d5 > 0) { p[5] = frustum.corner(i); idx[5] = i; }\n\t\t}\n\n\t\t// Compute frustum parameters\n\t\treal_t near_to_far   = n[1].dot(p[1] - p[0]);\n\t\treal_t left_to_right = n[3].dot(p[3] - p[2]);\n\t\treal_t bottom_to_top = n[5].dot(p[5] - p[4]);\n\n\t\t// Compute frustum center on near plane\n\t\t// - Project m on to left plane, displace by left_to_right/2 -> t\n\t\t// - Project t on to bottom plane, displace by bottom_to_top/2 -> nc\n\t\treal_t dt = -n[3].dot(m - p[3]) - left_to_right/2;\n\t\tvector3_t t = m + dt * n[3];\n\t\treal_t dnc = -n[5].dot(t - p[5]) - bottom_to_top/2;\n\t\tvector3_t nc = t + dnc * n[5];\n\n\t\tAssertBlock\n\t\t{\n\t\t\tvector3_t pos = nc + dir*near_to_far;\n\t\t\treal_t d0 = n[0].dot(pos - p[0]);\n\t\t\treal_t d1 = n[1].dot(pos - p[1]);\n\n\t\t\treal_t dm0 = n[0].dot(nc - p[0]);\n\t\t\treal_t dm1 = n[1].dot(nc - p[1]);\n\t\t\treal_t dm2 = n[2].dot(nc - p[2]);\n\t\t\treal_t dm3 = n[3].dot(nc - p[3]);\n\t\t\treal_t dm4 = n[4].dot(nc - p[4]);\n\t\t\treal_t dm5 = n[5].dot(nc - p[5]);\n\n\t\t\tCheck(equal(abs(d0),   near_to_far, (Scalar) 1e-3), \"Frustum position is correct.\");\n\t\t\tCheck(equal(abs(d1), 2*near_to_far, (Scalar) 1e-3), \"Frustum position is correct.\");\n\t\t\t\t\n\t\t\tCheck(equal(abs(dm0),           0, (Scalar) 1e-3), \"Frustum depth is correct.\");\n\t\t\tCheck(equal(abs(dm1), near_to_far, (Scalar) 1e-3), \"Frustum depth is correct.\");\n\t\t\tCheck(equal(abs(dm2), left_to_right/2, (Scalar) 1e-3), \"Frustum width is correct.\");\n\t\t\tCheck(equal(abs(dm3), left_to_right/2, (Scalar) 1e-3), \"Frustum width is correct.\");\n\t\t\tCheck(equal(abs(dm4), bottom_to_top/2, (Scalar) 1e-3), \"Frustum height is correct.\");\n\t\t\tCheck(equal(abs(dm5), bottom_to_top/2, (Scalar) 1e-3), \"Frustum height is correct.\");\n\n\t\t\tCheck(equal(-dir.cross(n[5]).dot(n[3]), 1, (Scalar) 1e-4), \"Frame is orthogonal.\", \"Angle: %f\", -dir.cross(n[5]).dot(n[3]));\n\t\t}\n\n\t\tOrthographicViewFrustum<real_t> ortho\n\t\t(\n\t\t\tleft_to_right, bottom_to_top, near_to_far, 2*near_to_far, nc + dir*near_to_far, -dir, n[5], n[3]\n\t\t);\n\t\treturn ortho;\n\t}\n\t\n\ttemplate<typename Scalar>\n\tvoid OrthographicViewFrustum<Scalar>::computePlanes()\n\t{\n\t\tusing Vcl::Mathematics::equal;\n\n\t\tRequire(equal(_direction.squaredNorm(), 1, (Scalar) 1e-6), \"Direction is unit length.\");\n\t\tRequire(equal(_up.squaredNorm(), 1, (Scalar) 1e-6), \"Up is unit length.\");\n\t\tRequire(equal(_right.squaredNorm(), 1, (Scalar) 1e-6), \"Right is unit length.\");\n\t\t\t\n\t\treal_t ratio = _x / _y;\n\n\t\treal_t height = _y;\n\t\treal_t width  = _x;\n\n\t\t// Far plane center\n\t\tvector3_t fc = _position + _direction * _far;\n\n\t\t// Far plane (top, left/top, right/bottom, left/top, left)\n\t\tvector3_t ftl = fc + (_up * height*real_t(0.5)) - (_right * width*real_t(0.5));\n\t\tvector3_t ftr = fc + (_up * height*real_t(0.5)) + (_right * width*real_t(0.5));\n\t\tvector3_t fbl = fc - (_up * height*real_t(0.5)) - (_right * width*real_t(0.5));\n\t\tvector3_t fbr = fc - (_up * height*real_t(0.5)) + (_right * width*real_t(0.5));\n\t\t\t\n\t\t// Near plane center\n\t\tvector3_t nc = _position + _direction * _near;\n\t\t\t\n\t\t// Near plane (top, left/top, right/bottom, left/top, left)\n\t\tvector3_t ntl = nc + (_up * height*real_t(0.5)) - (_right * width*real_t(0.5));\n\t\tvector3_t ntr = nc + (_up * height*real_t(0.5)) + (_right * width*real_t(0.5));\n\t\tvector3_t nbl = nc - (_up * height*real_t(0.5)) - (_right * width*real_t(0.5));\n\t\tvector3_t nbr = nc - (_up * height*real_t(0.5)) + (_right * width*real_t(0.5));\n\t\t\t\n\t\t// Store the corners\n\t\t_corners[0] = nbl;\n\t\t_corners[1] = nbr;\n\t\t_corners[2] = ntr;\n\t\t_corners[3] = ntl;\n\n\t\t_corners[4] = fbl;\n\t\t_corners[5] = fbr;\n\t\t_corners[6] = ftr;\n\t\t_corners[7] = ftl;\n\n\t\t// Compute the bounding planes\n\t\t//vector3_t aux, normal;\n\t\t//\n\t\t//aux = (nc + _y*near_height) - _position;\n\t\t//aux.normalize();\n\t\t//normal = aux * _x;\n\t\t//_planes[Top] = Eigen::Hyperplane<real_t, 3>(normal, nc+_up*near_height);\n\t\t//\n\t\t//aux = (nc - _y*near_height) - _position;\n\t\t//aux.normalize();\n\t\t//normal = _x * aux;\n\t\t//_planes[Bottom] = Eigen::Hyperplane<real_t, 3>(normal, nc-_y*near_height);\n\t\t//\n\t\t//aux = (nc - _x*far_width) - _position;\n\t\t//aux.normalize();\n\t\t//normal = aux * _y;\n\t\t//_planes[Left] = Eigen::Hyperplane<real_t, 3>(normal, nc-_right*near_width);\n\t\t//\n\t\t//aux = (nc + _x*far_width) - _position;\n\t\t//aux.normalize();\n\t\t//normal = _y * aux;\n\t\t//_planes[Right] = Eigen::Hyperplane<real_t, 3>(normal, nc+_right*near_width);\n\t\t//\n\t\t//_planes[Near] = Eigen::Hyperplane<real_t, 3>(-_direction, nc);\n\t\t//_planes[Far] = Eigen::Hyperplane<real_t, 3>(_direction, fc);\n\t}\n\n\ttemplate class PerspectiveViewFrustum<float>;\n\ttemplate class PerspectiveViewFrustum<double>;\n\n\ttemplate class OrthographicViewFrustum<float>;\n\ttemplate class OrthographicViewFrustum<double>;\n}}\n", "meta": {"hexsha": "bb1355d674771d931835e25dce30b5673ec5fc25", "size": 18305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/vcl.graphics/vcl/graphics/frustum.cpp", "max_stars_repo_name": "bschindler/vcl", "max_stars_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/vcl.graphics/vcl/graphics/frustum.cpp", "max_issues_repo_name": "bschindler/vcl", "max_issues_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/vcl.graphics/vcl/graphics/frustum.cpp", "max_forks_repo_name": "bschindler/vcl", "max_forks_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2839506173, "max_line_length": 176, "alphanum_fraction": 0.6724392243, "num_tokens": 5970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.0356785472889478, "lm_q1q2_score": 0.0178392736444739}}
{"text": "/*\n * serial.hpp\n *\n *  Created on: 10 Jul 2018\n *      Author: scsjd\n */\n\n#ifndef _SERIAL_HPP_\n#define _SERIAL_HPP_\n\n#include <sstream>\n#include <string>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/string.hpp>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <NTL/ZZX.h>\n#include <NTL/vec_ZZ.h>\n\nnamespace boost {\n\tnamespace serialization {\n\t\ttemplate<class Archive>\n\t\tvoid save(Archive & ar, const NTL::ZZ& p, const unsigned int version) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << p;\n\t\t\tar << oss.str();\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid load(Archive & ar, NTL::ZZ& p, const unsigned int version) {\n\t\t\tstd::string s;\n\t\t\tar >> s;\n\t\t\tstd::istringstream iss(s);\n\t\t\tiss >> p;\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid serialize(Archive & ar, NTL::ZZ& p, const unsigned int version) {\n\t\t\tboost::serialization::split_free(ar, p, version);\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid save(Archive & ar, const NTL::ZZ_p& p, const unsigned int version) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << p;\n\t\t\tar << oss.str();\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid load(Archive & ar, NTL::ZZ_p& p, const unsigned int version) {\n\t\t\tstd::string s;\n\t\t\tar >> s;\n\t\t\tstd::istringstream iss(s);\n\t\t\tiss >> p;\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid serialize(Archive & ar, NTL::ZZ_p& p, const unsigned int version) {\n\t\t\tboost::serialization::split_free(ar, p, version);\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid save(Archive & ar, const NTL::ZZX& p, const unsigned int version) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << p;\n\t\t\tar << oss.str();\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid load(Archive & ar, NTL::ZZX& p, const unsigned int version) {\n\t\t\tstd::string s;\n\t\t\tar >> s;\n\t\t\tstd::istringstream iss(s);\n\t\t\tiss >> p;\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid serialize(Archive & ar, NTL::ZZX& p, const unsigned int version) {\n\t\t\tboost::serialization::split_free(ar, p, version);\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid save(Archive & ar, const NTL::vec_ZZ& p, const unsigned int version) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << p;\n\t\t\tar << oss.str();\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid load(Archive & ar, NTL::vec_ZZ& p, const unsigned int version) {\n\t\t\tstd::string s;\n\t\t\tar >> s;\n\t\t\tstd::istringstream iss(s);\n\t\t\tiss >> p;\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid serialize(Archive & ar, NTL::vec_ZZ& p, const unsigned int version) {\n\t\t\tboost::serialization::split_free(ar, p, version);\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid save(Archive & ar, const NTL::vec_ZZ_p& p, const unsigned int version) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << p;\n\t\t\tar << oss.str();\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid load(Archive & ar, NTL::vec_ZZ_p& p, const unsigned int version) {\n\t\t\tstd::string s;\n\t\t\tar >> s;\n\t\t\tstd::istringstream iss(s);\n\t\t\tiss >> p;\n\t\t}\n\n\t\ttemplate<class Archive>\n\t\tvoid serialize(Archive & ar, NTL::vec_ZZ_p& p, const unsigned int version) {\n\t\t\tboost::serialization::split_free(ar, p, version);\n\t\t}\n\t}\n}\n\n#endif /* _SERIAL_HPP_ */\n", "meta": {"hexsha": "96dffd13e4edf93f7dc221ef8a70a8c1ea298387", "size": 3004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/src/serial.hpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/serial.hpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/serial.hpp", "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": 23.6535433071, "max_line_length": 79, "alphanum_fraction": 0.654460719, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584297, "lm_q2_score": 0.0414622721191905, "lm_q1q2_score": 0.017834886418414513}}
{"text": "//\n// Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.\n// Copyright (c) 2015-2017, University of Bremen\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// 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#ifndef __MAPS_BRESENHAM_LINE__\n#define __MAPS_BRESENHAM_LINE__\n\n#include <Eigen/Core>\n\nnamespace maps { namespace tools\n{\n\n\n/**\n * This class use useful for calculation\n * straight lines in grid. The Bresenham Algorithm\n * is a fast but inaccurate way to do this. \n * Inaccurate means, that the result will have\n * aliasing artifacts.\n * \n * The implementation of the core algorithm was taken from an wikipedia article.\n * */\nclass Bresenham {\npublic:\n    typedef Eigen::Vector2i Point;\n    Bresenham(const Point& start, const Point& end);\n\n    /**\n     * Inits the algorithm.\n     * The method may be used to 'reinit' the class\n     * after a line was already interpolated.\n     * */\n    void init(const Point& start, const Point& end);\n    void init(int startX, int startY, int endX, int endY);\n\n    /**\n     * Calculates the next point in the line\n     * and returns it over the given parameters.\n     *\n     * returns false if the end point is reached an\n     *              no further point can be calculated.\n     *\n     * */\n    bool getNextPoint(Point& next);\n\nprivate:\n    bool hasP;\n    int x0,y0, x1, y1, dx, sx, dy, sy, err;\n};\n\n\n}}  // namespace maps\n\n\n#endif\n", "meta": {"hexsha": "4a548a996925bd233c978b5ffeb8cdb2e0cff6f2", "size": 2642, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tools/BresenhamLine.hpp", "max_stars_repo_name": "JanWehrmann/slam-maps", "max_stars_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T05:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T02:34:18.000Z", "max_issues_repo_path": "src/tools/BresenhamLine.hpp", "max_issues_repo_name": "JanWehrmann/slam-maps", "max_issues_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T18:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T15:20:31.000Z", "max_forks_repo_path": "src/tools/BresenhamLine.hpp", "max_forks_repo_name": "JanWehrmann/slam-maps", "max_forks_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-03-10T10:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T05:50:10.000Z", "avg_line_length": 33.8717948718, "max_line_length": 88, "alphanum_fraction": 0.7221801665, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.043365797836640164, "lm_q1q2_score": 0.017828150217790113}}
{"text": "/*\n fcs.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 <iostream>\n#include <string>\n#include <cmath>\n#include \"../external/combination.hpp\"\n#include <boost/lexical_cast.hpp>\n#include \"files.h\"\n#include \"interaction.h\"\n#include \"error.h\"\n#include \"memory.h\"\n#include \"fcs.h\"\n#include \"symmetry.h\"\n#include \"system.h\"\n#include \"timer.h\"\n#include \"constants.h\"\n\nusing namespace ALM_NS;\n\nFcs::Fcs(ALM *alm) : Pointers(alm){};\nFcs::~Fcs() {};\n\nvoid Fcs::init(){\n\n    int i;\n    int maxorder = interaction->maxorder;\n\n    std::cout << \" FORCE CONSTANT\" << std::endl;\n    std::cout << \" ==============\" << std::endl << std::endl;\n\n    memory->allocate(nints, maxorder);\n    memory->allocate(nzero, maxorder);\n    memory->allocate(fc_set, maxorder);\n    memory->allocate(ndup, maxorder);\n\n    for (i = 0; i < maxorder; ++i) nzero[i] = 0;\n    generate_fclists(maxorder);\n\n    std::cout << std::endl;\n    for (i = 0; i < maxorder; ++i) {\n        std::cout << \"  Number of \" << std::setw(9) << interaction->str_order[i] << \" FCs : \" << ndup[i].size();\n\tstd::cout << std::endl;\n    }\n    std::cout << std::endl;\n\n    // sort fc_set\n\n    for (int order = 0; order < maxorder; ++order) {\n        if (ndup[order].size() > 0) {\n            std::sort(fc_set[order].begin(), fc_set[order].begin() + ndup[order][0]);\n            int nbegin = ndup[order][0];\n            int nend;\n            for (unsigned int mm = 1; mm < ndup[order].size(); ++mm) {\n                nend  = nbegin + ndup[order][mm];\n                std::sort(fc_set[order].begin() + nbegin, fc_set[order].begin() + nend);\n                nbegin += ndup[order][mm];\n            }\n        }\n    }\n\n    memory->deallocate(nints);\n    memory->deallocate(nzero);\n    timer->print_elapsed();\n    std::cout << \" --------------------------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n}\n\n\nvoid Fcs::generate_fclists(int maxorder)\n{\n    int i, j;\n    int i1, i2;\n    int order;\n    int i_prim;\n    int *atmn, *atmn_mapped;\n    int *ind, *ind_mapped;\n    int *ind_tmp, *ind_mapped_tmp;\n    int nxyz;\n    unsigned int isym;\n\n    double c_tmp;\n\n    int **xyzcomponent;\n\n    int nmother;\n    int nat = system->nat;\n\n    bool is_zero;\n    bool *is_searched;\n\n    std::cout << \"  Finding symmetrically-independent force constants ...\" << std::endl;\n\n    memory->allocate(atmn, maxorder + 1);\n    memory->allocate(atmn_mapped, maxorder + 1);\n    memory->allocate(ind, maxorder + 1);\n    memory->allocate(ind_mapped, maxorder + 1);\n    memory->allocate(ind_tmp, maxorder - 1);\n    memory->allocate(ind_mapped_tmp, maxorder + 1);\n    memory->allocate(is_searched, 3 * nat);\n\n    for (order = 0; order < maxorder; ++order) {\n\n        std::cout << \"   \" << std::setw(8) << interaction->str_order[order] << \" ...\";\n\n        fc_set[order].clear();\n        ndup[order].clear();\n        nmother = 0;\n\n        nxyz = static_cast<int>(std::pow(3.0, order + 2));\n\n        memory->allocate(xyzcomponent, nxyz, order + 2);\n        get_xyzcomponent(order + 2, xyzcomponent);\n\n        std::set<IntList> list_found;\n\n        for (std::set<IntList>::iterator iter = interaction->pairs[order].begin(); iter != interaction->pairs[order].end(); ++iter) {\n\n            for (i = 0; i < order + 2; ++i) atmn[i] = (*iter).iarray[i];\n\n            for (i1 = 0; i1 < nxyz; ++i1) {\n                for (i = 0; i < order + 2; ++i) ind[i] = 3 * atmn[i] + xyzcomponent[i1][i];\n\n                if (!is_ascending(order + 2, ind)) continue;\n\n                i_prim = min_inprim(order + 2, ind);\n                std::swap(ind[0], ind[i_prim]);\n                sort_tail(order + 2, ind);\n\n                is_zero = false;\n\n                if (list_found.find(IntList(order + 2, ind)) != list_found.end()) continue; // Already exits!\n\n                // Search symmetrically-dependent parameter set\n\n                int ndeps = 0;\n\n                for (isym = 0; isym < symmetry->nsym; ++isym) {\n\n                    if (!symmetry->sym_available[isym]) continue;\n\n                    for (i = 0; i < order + 2; ++i) atmn_mapped[i] = symmetry->map_sym[atmn[i]][isym];\n\n                    if (!is_inprim(order + 2, atmn_mapped)) continue;\n\n                    for (i2 = 0; i2 < nxyz; ++i2) {\n                        c_tmp = coef_sym(order + 2, isym, xyzcomponent[i1], xyzcomponent[i2]);\n                        if (std::abs(c_tmp) > eps12) {\n                            for (i = 0; i < order + 2; ++i) ind_mapped[i] = 3 * atmn_mapped[i] + xyzcomponent[i2][i];\n\n                            i_prim = min_inprim(order + 2, ind_mapped);\n                            std::swap(ind_mapped[0], ind_mapped[i_prim]);\n                            sort_tail(order + 2, ind_mapped);\n\n                            if (!is_zero) {\n                                bool zeroflag = true;\n                                for (i = 0; i < order + 2; ++i) {\n                                    zeroflag = zeroflag & (ind[i] == ind_mapped[i]);\n                                }\n                                zeroflag = zeroflag & (std::abs(c_tmp + 1.0) < eps8);\n                                is_zero = zeroflag;\n                            }\n\n                            // Add to found list (set) and fcset (vector) if the created is new one.\n\n                            if (list_found.find(IntList(order + 2, ind_mapped)) == list_found.end()) {\n                                list_found.insert(IntList(order + 2, ind_mapped));\n\n                                fc_set[order].push_back(FcProperty(order + 2, c_tmp, ind_mapped, nmother));\n                                ++ndeps;\n\n                                // Add equivalent interaction list (permutation) if there are two or more indices\n                                // which belong to the primitive cell.\n                                // This procedure is necessary for fitting.\n\n                                for (i = 0; i < 3 * nat; ++i) is_searched[i] = false;\n                                is_searched[ind_mapped[0]] = true;\n                                for (i = 1; i < order + 2; ++i) {\n                                    if ((!is_searched[ind_mapped[i]]) && is_inprim(ind_mapped[i])) {\n\n                                        for (j = 0; j < order + 2; ++j) ind_mapped_tmp[j] = ind_mapped[j];\n                                        std::swap(ind_mapped_tmp[0], ind_mapped_tmp[i]);\n                                        sort_tail(order + 2, ind_mapped_tmp);\n                                        fc_set[order].push_back(FcProperty(order + 2, c_tmp, ind_mapped_tmp, nmother));\n\n                                        ++ndeps;\n\n                                        is_searched[ind_mapped[i]] = true;\n                                    }\n                                }\n\n\n                            }\n                        }\n                    }\n                } // close symmetry loop\n\n                if (is_zero) {\n                    for (i = 0; i < ndeps; ++i) fc_set[order].pop_back();\n                    ++nzero[order];\n                } else {\n                    ndup[order].push_back(ndeps);\n                    ++nmother;\n                }\n\n            } // close xyz component loop\n        } // close atom number loop (iterator)\n\n        memory->deallocate(xyzcomponent);\n        list_found.clear();\n        std::cout << \" done. \" << std::endl;\n    } //close order loop\n\n    memory->deallocate(atmn);\n    memory->deallocate(atmn_mapped);\n    memory->deallocate(ind);\n    memory->deallocate(ind_mapped);\n    memory->deallocate(ind_tmp);\n    memory->deallocate(ind_mapped_tmp);\n    memory->deallocate(is_searched);\n\n    std::cout << \"  Finished!\" << std::endl;\n}\n\ndouble Fcs::coef_sym(const int n, const int symnum, const int *arr1, const int *arr2)\n{\n    double tmp = 1.0;\n    int i;\n\n    for (i = 0; i < n; ++i) {\n        tmp *= symmetry->symrel[symnum][arr2[i]][arr1[i]];\n    }\n    return tmp;\n}\n\nbool Fcs::is_ascending(const int n, const int *arr)\n{\n    int i;\n    for (i = 0; i < n - 1; ++i) {\n        if (arr[i] > arr[i+1]) return false;\n    }\n    return true;\n}\n\nint Fcs::min_inprim(const int n, const int *arr)\n{\n    int i, j, atmnum;\n    int natmin = symmetry->natmin;\n    int minloc;\n    int *ind;\n\n    memory->allocate(ind, n);\n\n    for (i = 0; i < n; ++i) {\n\n        ind[i] = 3 * system->nat;\n        atmnum = arr[i] / 3;\n\n        for (j = 0; j < natmin; ++j) {\n            if (symmetry->map_p2s[j][0] == atmnum) {\n                ind[i] = arr[i];\n                continue;\n            }\n        }\n    }\n\n    int minval = ind[0];\n    minloc = 0;\n\n    for (i = 0; i < n; ++i) {\n        if (ind[i] < minval) {\n            minval = ind[i];\n            minloc = i;\n        }\n    }\n\n    memory->deallocate(ind);\n    return minloc;\n}\n\nbool Fcs::is_inprim(const int n, const int *arr)\n{\n    int i, j;\n    int natmin = symmetry->natmin;\n\n    for (i = 0; i < n; ++i) {\n        for (j = 0; j < natmin; ++j) {\n            if (symmetry->map_p2s[j][0] == arr[i]) return true;\n        }\n    }\n    return false;\n}\n\nbool Fcs::is_inprim(const int n)\n{\n    int i, atmn;\n    int natmin = symmetry->natmin;\n\n    atmn = n / 3;\n\n    for (i = 0; i < natmin; ++i) {\n        if (symmetry->map_p2s[i][0] == atmn) return true;\n    }\n\n    return false;\n}\n\nvoid Fcs::get_xyzcomponent(int n, int **xyz)\n{\n    // Return xyz component for the given order using boost algorithm library\n\n    std::vector<int> v;\n    int i;\n\n    for (i = 0; i < n; ++i) {\n        v.push_back(0);\n        v.push_back(1);\n        v.push_back(2);\n    }\n\n    std::sort(v.begin(), v.end());\n\n    int m = 0;\n\n    do {\n        xyz[m][0] = v[0];\n        for (i = 1; i < n; ++i) xyz[m][i] = v[i];\n        ++m;\n    } while(boost::next_partial_permutation(v.begin(), v.begin() + n, v.end()));\n}\n\nvoid Fcs::sort_tail(const int n, int *arr)\n{\n    int i, m;\n\n    m = n - 1;\n    int *ind_tmp;\n\n    memory->allocate(ind_tmp, m);\n\n    for (i = 0; i < m; ++i) {\n        ind_tmp[i] = arr[i + 1];\n    }\n\n    interaction->insort(m, ind_tmp);\n\n    for (i = 0; i < m; ++i) {\n        arr[i + 1] = ind_tmp[i];\n    }\n\n    memory->deallocate(ind_tmp);\n}\n\nstd::string Fcs::easyvizint(const int n)\n{\n    int atmn;\n    int crdn;\n    atmn = n / 3 + 1;\n    crdn = n % 3;\n    std::string str_crd[3] = {\"x\", \"y\", \"z\"};\n    std::string str_tmp;\n\n    str_tmp = boost::lexical_cast<std::string>(atmn);\n    str_tmp += str_crd[crdn];\n\n    return  str_tmp;\n}\n", "meta": {"hexsha": "6c106ca01b690fc53db62a0b14a614b8bdbea0b3", "size": 10598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "alm/fcs.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/fcs.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/fcs.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": 28.2613333333, "max_line_length": 133, "alphanum_fraction": 0.4848084544, "num_tokens": 2904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.03622005560488866, "lm_q1q2_score": 0.017827081643873702}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007, 2008, 2009, 2010 Ferdinando Ametrano\n Copyright (C) 2007 Chiara Fornarola\n Copyright (C) 2009 StatPro Italia srl\n Copyright (C) 2009 Nathan Abbott\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 bondfunctions.hpp\n    \\brief bond functions\n*/\n\n#ifndef quantlib_bond_functions_hpp\n#define quantlib_bond_functions_hpp\n\n#include <ql/cashflows/duration.hpp>\n#include <ql/cashflow.hpp>\n#include <ql/interestrate.hpp>\n#include <boost/shared_ptr.hpp>\n\nnamespace QuantLib {\n\n    // forward declarations\n    class Bond;\n    class DayCounter;\n    class YieldTermStructure;\n\n    //! Bond adapters of CashFlows functions\n    /*! See CashFlows for functions' documentation.\n\n        These adapters calls into CashFlows functions passing as input the\n        Bond cashflows, the dirty price (i.e. npv) calculated from clean\n        price, the bond settlement date (unless another date is given), zero\n        ex-dividend days, and excluding any cashflow on the settlement date.\n\n        Prices are always clean, as per market convention.\n    */\n    struct BondFunctions {\n        //! \\name Date inspectors\n        //@{\n        static Date startDate(const Bond& bond);\n        static Date maturityDate(const Bond& bond);\n        static bool isTradable(const Bond& bond,\n                               Date settlementDate = Date());\n        //@}\n\n        //! \\name CashFlow inspectors\n        //@{\n        static Leg::const_reverse_iterator\n        previousCashFlow(const Bond& bond,\n                         Date refDate = Date());\n        static Leg::const_iterator nextCashFlow(const Bond& bond,\n                                                Date refDate = Date());\n        static Date previousCashFlowDate(const Bond& bond,\n                                         Date refDate = Date());\n        static Date nextCashFlowDate(const Bond& bond,\n                                     Date refDate = Date());\n        static Real previousCashFlowAmount(const Bond& bond,\n                                           Date refDate = Date());\n        static Real nextCashFlowAmount(const Bond& bond,\n                                       Date refDate = Date());\n        //@}\n\n        //! \\name Coupon inspectors\n        //@{\n        static Rate previousCouponRate(const Bond& bond,\n                                       Date settlementDate = Date());\n        static Rate nextCouponRate(const Bond& bond,\n                                   Date settlementDate = Date());\n        static Date accrualStartDate(const Bond& bond,\n                                     Date settlementDate = Date());\n        static Date accrualEndDate(const Bond& bond,\n                                   Date settlementDate = Date());\n        static Date referencePeriodStart(const Bond& bond,\n                                         Date settlementDate = Date());\n        static Date referencePeriodEnd(const Bond& bond,\n                                       Date settlementDate = Date());\n        static Time accrualPeriod(const Bond& bond,\n                                  Date settlementDate = Date());\n        static BigInteger accrualDays(const Bond& bond,\n                                      Date settlementDate = Date());\n        static Time accruedPeriod(const Bond& bond,\n                                  Date settlementDate = Date());\n        static BigInteger accruedDays(const Bond& bond,\n                                      Date settlementDate = Date());\n        static Real accruedAmount(const Bond& bond,\n                                  Date settlementDate = Date());\n        //@}\n\n        //! \\name YieldTermStructure functions\n        //@{\n        static Real cleanPrice(const Bond& bond,\n                               const YieldTermStructure& discountCurve,\n                               Date settlementDate = Date());\n        static Real bps(const Bond& bond,\n                        const YieldTermStructure& discountCurve,\n                        Date settlementDate = Date());\n        static Rate atmRate(const Bond& bond,\n                            const YieldTermStructure& discountCurve,\n                            Date settlementDate = Date(),\n                            Real cleanPrice = Null<Real>());\n        //@}\n\n        //! \\name Yield (a.k.a. Internal Rate of Return, i.e. IRR) functions\n        //@{\n        static Real cleanPrice(const Bond& bond,\n                               const InterestRate& yield,\n                               Date settlementDate = Date());\n        static Real cleanPrice(const Bond& bond,\n                               Rate yield,\n                               const DayCounter& dayCounter,\n                               Compounding compounding,\n                               Frequency frequency,\n                               Date settlementDate = Date());\n        static Real dirtyPrice(const Bond& bond,\n                               const InterestRate& yield,\n                               Date settlementDate = Date());\n        static Real dirtyPrice(const Bond& bond,\n                               Rate yield,\n                               const DayCounter& dayCounter,\n                               Compounding compounding,\n                               Frequency frequency,\n                               Date settlementDate = Date());\n        static Real bps(const Bond& bond,\n                        const InterestRate& yield,\n                        Date settlementDate = Date());\n        static Real bps(const Bond& bond,\n                        Rate yield,\n                        const DayCounter& dayCounter,\n                        Compounding compounding,\n                        Frequency frequency,\n                        Date settlementDate = Date());\n        static Rate yield(const Bond& bond,\n                          Real cleanPrice,\n                          const DayCounter& dayCounter,\n                          Compounding compounding,\n                          Frequency frequency,\n                          Date settlementDate = Date(),\n                          Real accuracy = 1.0e-10,\n                          Size maxIterations = 100,\n                          Rate guess = 0.05);\n        static Time duration(const Bond& bond,\n                             const InterestRate& yield,\n                             Duration::Type type = Duration::Modified,\n                             Date settlementDate = Date() );\n        static Time duration(const Bond& bond,\n                             Rate yield,\n                             const DayCounter& dayCounter,\n                             Compounding compounding,\n                             Frequency frequency,\n                             Duration::Type type = Duration::Modified,\n                             Date settlementDate = Date() );\n        static Real convexity(const Bond& bond,\n                              const InterestRate& yield,\n                              Date settlementDate = Date());\n        static Real convexity(const Bond& bond,\n                              Rate yield,\n                              const DayCounter& dayCounter,\n                              Compounding compounding,\n                              Frequency frequency,\n                              Date settlementDate = Date());\n        static Real basisPointValue(const Bond& bond,\n                                    const InterestRate& yield,\n                                    Date settlementDate = Date());\n        static Real basisPointValue(const Bond& bond,\n                                    Rate yield,\n                                    const DayCounter& dayCounter,\n                                    Compounding compounding,\n                                    Frequency frequency,\n                                    Date settlementDate = Date());\n        static Real yieldValueBasisPoint(const Bond& bond,\n                                         const InterestRate& yield,\n                                         Date settlementDate = Date());\n        static Real yieldValueBasisPoint(const Bond& bond,\n                                         Rate yield,\n                                         const DayCounter& dayCounter,\n                                         Compounding compounding,\n                                         Frequency frequency,\n                                         Date settlementDate = Date());\n        //@}\n\n        //! \\name Z-spread functions\n        //@{\n        static Real cleanPrice(const Bond& bond,\n                               const boost::shared_ptr<YieldTermStructure>& discount,\n                               Spread zSpread,\n                               const DayCounter& dayCounter,\n                               Compounding compounding,\n                               Frequency frequency,\n                               Date settlementDate = Date());\n        static Spread zSpread(const Bond& bond,\n                              Real cleanPrice,\n                              const boost::shared_ptr<YieldTermStructure>&,\n                              const DayCounter& dayCounter,\n                              Compounding compounding,\n                              Frequency frequency,\n                              Date settlementDate = Date(),\n                              Real accuracy = 1.0e-10,\n                              Size maxIterations = 100,\n                              Rate guess = 0.0);\n        //@}\n\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "a3c1395ed508afc718088d28e477cbd31c9530ce", "size": 10203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/bond/bondfunctions.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "ql/pricingengines/bond/bondfunctions.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/pricingengines/bond/bondfunctions.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 45.9594594595, "max_line_length": 85, "alphanum_fraction": 0.4930902676, "num_tokens": 1641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.036220053394157015, "lm_q1q2_score": 0.017827080555777815}}
{"text": "/*\n* Level_8 Exercise 3:\n* Source file for Visitor Class\n*\n* variant visitor that moves the shapes\n*\n* @file Visitor.cpp\n* @author Chunyu Yuan\n* @version 1.0 02/22/2021\n*\n*/\n\n\n#include<iostream> // Standard Input / Output Streams Library\n#include <boost/variant/static_visitor.hpp>\n#include \"Point.hpp\" //header file for Array class\n#include \"Line.hpp\"  // header file for Line class\n#include \"Circle.hpp\" // header file for circle class\n#include \"Visitor.hpp\"\n\nusing namespace Chunyu::CAD;//namespace declaration for using Chunyu::CAD\n\n\n// Default constructor\nVisitor::Visitor(): boost::static_visitor<void>(),m_dx(0), m_dy(0) //colon syntax\n{\n\n}\n\n// Copy constructor\nVisitor::Visitor(const Visitor& source): boost::static_visitor<void>(),m_dx(source.m_dx), m_dy(source.m_dy)\n{\n\n}\n\n// Constructor with x- and y-coordinates argument\nVisitor::Visitor(double new_x, double new_y):boost::static_visitor<void>(), m_dx(new_x), m_dy(new_y)\n{\n\n}\n\n// Destructor\nVisitor::~Visitor()\n{\n\n}\n\n// Assignment operator\nVisitor& Visitor::operator = (const Visitor& source)\n{\n\tif (this == &source)  //check if the address is the same\n\t\treturn *this;     //if same, return itself \n\t//copy source x coordinate and assign this visitor\n\tm_dx = source.m_dx;\n\t//copy source y coordinate and assign this visitor\n\tm_dy = source.m_dy;\n\n\treturn *this; //return this visitor\n}\n\n// () operator for Point,visit a point\nvoid Visitor::operator () (Point& p) const\n{\n\tp.X(p.X() + m_dx); //move the point's x coordinate m_dx\n\tp.Y(p.Y() + m_dy); // move the point's y coordinate m_dy\n}\n\n// () operator for Line, visit a line\nvoid Visitor::operator () (Line& l) const\n{\n\t//get line's start point and assign to tempory point p1\n\tPoint p1 = l.startP();\n\t//get line's end point and assign to tempory point p2\n\tPoint p2 = l.endP();\n\n\t//move the point p1's x coordinate m_dx\n\tp1.X(p1.X() + m_dx);\n\t//move the point p1's y coordinate m_dy\n\tp1.Y(p1.Y() + m_dy);\n\t//move the point p2's x coordinate m_dx\n\tp2.X(p2.X() + m_dx);\n\t//move the point p2's y coordinate m_dy\n\tp2.Y(p2.Y() + m_dy);\n\n\t//set line's start point to p1\n\tl.startP(p1);\n\t//set line's end point to p2\n\tl.endP(p2);\n}\n\n// () operator for Circle, visit a circle\nvoid Visitor::operator () (Circle& c) const\n{\n\t//get circle's centre point and assign to tempory point p1\n\tPoint p1 = c.CentrePoint();\n\n\t//move the point p1's x coordinate m_dx\n\tp1.X(p1.X() + m_dx);\n\t//move the point p1's y coordinate m_dy\n\tp1.Y(p1.Y() + m_dy);\n\n\t//set ircle centre point\n\tc.CentrePoint(p1);\n}\n\n\n\n\n\n", "meta": {"hexsha": "5d2bc15cd8b219e362c48f050d53476d03e3378b", "size": 2496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level8/Level8/Level8/Exercise 3/Visitor.cpp", "max_stars_repo_name": "chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering", "max_stars_repo_head_hexsha": "478b414714edbea1ebdc2f565baad6f04f54bc70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-12T08:15:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T08:15:57.000Z", "max_issues_repo_path": "Level8/Level8/Level8/Exercise 3/Visitor.cpp", "max_issues_repo_name": "chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering", "max_issues_repo_head_hexsha": "478b414714edbea1ebdc2f565baad6f04f54bc70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Level8/Level8/Level8/Exercise 3/Visitor.cpp", "max_forks_repo_name": "chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering", "max_forks_repo_head_hexsha": "478b414714edbea1ebdc2f565baad6f04f54bc70", "max_forks_repo_licenses": ["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.6909090909, "max_line_length": 107, "alphanum_fraction": 0.6887019231, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074556640652345, "lm_q2_score": 0.05921024700601515, "lm_q1q2_score": 0.017807219272894186}}
{"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/main/LICENSE\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\n *       copyright notice, this list of conditions and the following\n *       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\n *       provided with the distribution.\n *     * Neither the name of the Georgia Tech Research Corporation nor\n *       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 GEORGIA TECH RESEARCH CORPORATION ''AS\n * 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 GEORGIA\n * TECH RESEARCH CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n/**\n * @file RRT.h\n * @author Tobias Kunz, Can Erdogan\n * @date Jan 31, 2013\n * @brief The generic RRT implementation. It can be inherited for modifications\n * to collision checking, sampling and etc.\n */\n\n#ifndef DART_PLANNING_RRT_HPP_\n#define DART_PLANNING_RRT_HPP_\n\n#include <list>\n#include <vector>\n#include <Eigen/Core>\n\n#include \"dart/dynamics/SmartPointer.hpp\"\n#include \"dart/simulation/World.hpp\"\n\nnamespace flann {\ntemplate <class A>\nclass L2;\ntemplate <class A>\nclass Index;\n} // namespace flann\n\nnamespace dart {\n\nnamespace simulation {\nclass World;\n}\nnamespace dynamics {\nclass Skeleton;\n}\n\nnamespace planning {\n\n/// The rapidly-expanding random tree implementation\nclass RRT\n{\npublic:\n  /// To get byte-aligned Eigen vectors\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /// The result of attempting to create a new node to reach a target node\n  typedef enum\n  {\n    STEP_COLLISION, // Collided with obstacle. No node added.\n    STEP_REACHED,   // The target node is closer than step size (so reached). No\n                    // node added.\n    STEP_PROGRESS   // One node added.\n  } StepResult;\n\npublic:\n  // Initialization constants and search variables\n\n  const int\n      ndim; ///< Number of dof we can manipulate (may be less than robot's)\n  const double stepSize; ///< Step size at each node creation\n\n  int activeNode; ///< Last added node or the nearest node found after a search\n  std::vector<int> parentVector; ///< The ith node in configVector has parent\n                                 ///< with index pV[i]\n\n  /// All visited configs\n  // NOTE We are using pointers for the VectorXd's because flann copies the\n  // pointers for the data points and we give it the copies made in the heap\n  std::vector<const Eigen::VectorXd*> configVector;\n\npublic:\n  //// Constructor with a single root\n  RRT(dart::simulation::WorldPtr world,\n      dart::dynamics::SkeletonPtr robot,\n      const std::vector<std::size_t>& dofs,\n      const Eigen::VectorXd& root,\n      double stepSize = 0.02);\n\n  /// Constructor with multiple roots (so, multiple trees)\n  RRT(simulation::WorldPtr world,\n      dynamics::SkeletonPtr robot,\n      const std::vector<std::size_t>& dofs,\n      const std::vector<Eigen::VectorXd>& roots,\n      double stepSize = 0.02);\n\n  /// Destructor\n  virtual ~RRT()\n  {\n  }\n\n  /// Reach for a random node by repeatedly extending nodes from the nearest\n  /// neighbor in the tree. Stop if there is a collision.\n  bool connect();\n\n  /// Reach for a target by repeatedly extending nodes from the nearest\n  /// neighbor. Stop if collide.\n  bool connect(const Eigen::VectorXd& target);\n\n  /// Try a single step with the given \"stepSize\" to a random configuration.\n  /// Fail if collide.\n  StepResult tryStep();\n\n  /// Try a single step with the given \"stepSize\" to the given configuration.\n  /// Fail if collide.\n  StepResult tryStep(const Eigen::VectorXd& qtry);\n\n  /// Tries to extend tree towards provided sample\n  virtual StepResult tryStepFromNode(const Eigen::VectorXd& qtry, int NNidx);\n\n  /// Checks if the given new configuration is in collision with an obstacle.\n  /// Moreover, it is a an opportunity for child classes to change the new\n  /// configuration if there is a need. For instance, task constrained planners\n  /// might want to sample around this point and replace it with a better (less\n  /// erroroneous due to constraint) node.\n  virtual bool newConfig(\n      std::list<Eigen::VectorXd>& intermediatePoints,\n      Eigen::VectorXd& qnew,\n      const Eigen::VectorXd& qnear,\n      const Eigen::VectorXd& qtarget);\n\n  /// Returns the distance between the current active node and the given node.\n  /// TODO This might mislead the users to thinking returning the distance\n  /// between the given target and the nearest neighbor.\n  double getGap(const Eigen::VectorXd& target);\n\n  /// Traces the path from some node to the initConfig node - useful in creating\n  /// the full path after the goal is reached.\n  void tracePath(\n      int node, std::list<Eigen::VectorXd>& path, bool reverse = false);\n\n  /// Returns the number of nodes in the tree.\n  std::size_t getSize();\n\n  /// Implementation-specific function for checking collisions\n  virtual bool checkCollisions(const Eigen::VectorXd& c);\n\n  /// Returns a random configuration with the specified node IDs\n  virtual Eigen::VectorXd getRandomConfig();\n\nprotected:\n  simulation::WorldPtr world; ///< The world that the robot is in\n  dynamics::SkeletonPtr\n      robot; ///< The ID of the robot for which a plan is generated\n  std::vector<std::size_t>\n      dofs; ///< The dofs of the robot the planner can manipulate\n\n  /// The underlying flann data structure for fast nearest neighbor searches\n  flann::Index<flann::L2<double> >* index;\n\n  /// Returns a random value between the given minimum and maximum value\n  double randomInRange(double min, double max);\n\n  /// Returns the nearest neighbor to query point\n  virtual int getNearestNeighbor(const Eigen::VectorXd& qsamp);\n\n  /// Adds a new node to the tree\n  virtual int addNode(const Eigen::VectorXd& qnew, int parentId);\n};\n\n} // namespace planning\n} // namespace dart\n\n#endif // DART_PLANNING_RRT_HPP_\n", "meta": {"hexsha": "7409cc61237e777956ee4a660303660ae0a82b94", "size": 6916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/planning/RRT.hpp", "max_stars_repo_name": "lakshmipathyarjun6/dart", "max_stars_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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/RRT.hpp", "max_issues_repo_name": "lakshmipathyarjun6/dart", "max_issues_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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/RRT.hpp", "max_forks_repo_name": "lakshmipathyarjun6/dart", "max_forks_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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.58, "max_line_length": 80, "alphanum_fraction": 0.7168883748, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.045352585392980885, "lm_q1q2_score": 0.01779348959296522}}
{"text": "/////////////////////////////////////////////////////////////\n//                                                         //\n// Copyright (c) 2003-2017 by The University of Queensland //\n// Centre for Geoscience Computing                         //\n// http://earth.uq.edu.au/centre-geoscience-computing      //\n//                                                         //\n// Primary Business: Brisbane, Queensland, Australia       //\n// Licensed under the Open Software License version 3.0    //\n// http://www.apache.org/licenses/LICENSE-2.0              //\n//                                                         //\n/////////////////////////////////////////////////////////////\n\n#include <boost/version.hpp>\n#include <iostream>\n#include <sstream>\n#include \"Python/esys/lsm/util/QuaternionPy.h\"\n#include \"Python/esys/lsm/util/Vec3Py.h\"\n#include \"Foundation/StringUtil.h\"\n#include \"Python/BoostPythonUtil/Util.h\"\n\nusing namespace boost::python;\nusing namespace esys::lsm;\n\nnamespace esys\n{\n  namespace lsm\n  {\n    QuaternionPy::QuaternionPy() : Quaternion()\n    {\n    }\n\n    QuaternionPy::QuaternionPy(\n      double q0,\n      double q1,\n      double q2,\n      double q3\n    ) : Quaternion(q0, Vec3(q1, q2, q3))\n    {\n    }\n\n    QuaternionPy::QuaternionPy(const Vec3Py &v)\n      : Quaternion(\n          cos(v.norm()/2.0),\n          v*(sin(v.norm()/2.0)/v.norm())\n        )\n    {\n    }\n\n    QuaternionPy::QuaternionPy(const QuaternionPy &q) : Quaternion(q)\n    {\n    }\n\n    QuaternionPy::QuaternionPy(const Quaternion &q) : Quaternion(q)\n    {\n    }\n\n    QuaternionPy::QuaternionPy(const boost::python::object &pyOb)\n    {\n      if (esys::lsm::bpu::len(pyOb) == 4)\n      {\n        *this = \n          QuaternionPy(\n            boost::python::extract<double>(pyOb[0]),\n            boost::python::extract<double>(pyOb[1]),\n            boost::python::extract<double>(pyOb[2]),\n            boost::python::extract<double>(pyOb[3])\n          );\n      }\n      else\n      {\n        std::stringstream msg;\n        msg \n          << \"Could not extract (q0,q1,q2,q3) elements from: \"\n          << boost::python::extract<std::string>(boost::python::str(pyOb))();\n        throw runtime_error(msg.str());\n      }\n    }\n    \n    int QuaternionPy::len() const\n    {\n      return 4;\n    }\n\n    int QuaternionPy::getIndex(int i) const\n    {\n      const int origI = i;\n      if (i < 0)\n      {\n          i += len();\n      }\n      if ((i >= len()) || i < 0)\n      {\n        std::stringstream msg;\n        msg << \"Index \" << origI << \" out of range [0,4)\";\n        PyErr_SetString(PyExc_IndexError, msg.str().c_str());\n        throw_error_already_set();\n      }\n      return i;\n    }\n    \n    double QuaternionPy::getItem(int i) const\n    {\n      return ((i=getIndex(i)) == 0) ? return_sca() : return_vec()[i-1];\n    }\n\n    void QuaternionPy::setItem(int i, double val)\n    {\n      i = getIndex(i);\n      if (i == 0)\n      {\n        set_scalar(val);\n      }\n      else\n      {\n        Vec3 v = return_vec();\n        v[i-1] = val;\n        set_vector(v);\n      }\n    }\n\n    std::string QuaternionPy::toString() const\n    {\n      return StringUtil::toString(*this);\n    }\n\n    boost::python::list QuaternionPy::toList() const\n    {\n      boost::python::list l;\n      l.append(getItem(0));\n      l.append(getItem(1));\n      l.append(getItem(2));\n      l.append(getItem(3));\n      return l;\n    }\n\n    boost::python::tuple QuaternionPy::toTuple() const\n    {\n      return boost::python::tuple(toList());\n    }\n\n    boost::python::tuple\n    QuaternionPy::PickleSuite::getinitargs(QuaternionPy const& q)\n    {\n      return q.toTuple();\n    }\n\n    Vec3Py QuaternionPy::asAngleAxis() const\n    {\n      return Vec3Py(Quaternion::asAngleAxis());\n    }\n\n    boost::python::tuple QuaternionPy::asAngleAxisPair() const\n    {\n      Quaternion::AngleAxisPair p = Quaternion::asAngleAxisPair();\n      return boost::python::make_tuple(p.first, Vec3Py(p.second));\n    }\n\n    using boost::python::arg;\n    void exportQuaternion()\n    {\n      // Disable autogeneration of C++ signatures (Boost 1.34.0 and higher)\n      // for Epydoc which stumbles over indentation in the automatically generated strings.\n      boost::python::docstring_options no_autogen(true,false);\n\n      class_<esys::lsm::QuaternionPy>(\n        \"Quaternion\",\n        \"A quaternion.\",\n        init<>()\n      )\n      .def(init<const object &>())\n      .def(init<const Vec3Py &>())\n      .def(init<const QuaternionPy &>())\n      .def(\n        init<double,double,double,double>(\n          (arg(\"q0\"), arg(\"q1\"), arg(\"q2\"), arg(\"q3\") ),\n          \"Constructs quaternion with specifed component values.\\n\"\n          \"@type q0: float\\n\"\n          \"@kwarg q0: Scalar part, index 0.\\n\"\n          \"@type q1: float\\n\"\n          \"@kwarg q1: index 1\\n\"\n          \"@type q2: float\\n\"\n          \"@kwarg q2: index 2\\n\"\n          \"@type q3: float\\n\"\n          \"@kwarg q3: index 3\\n\"\n        )\n      )\n      .def(\n        \"normalise\",\n        &QuaternionPy::normalize,\n        \"Normalises this quaternion.\\n\"\n      )\n      .def(\n        \"normalize\",\n        &QuaternionPy::normalize,\n        \"Normalizes this quaternion.\\n\"\n      )\n      .def(\n        \"asAngleAxis\",\n        &QuaternionPy::asAngleAxis,\n        \"Returns angle and axis rotation representation, where\"\n        \" angle is the magnitude of the returned \"\n        \" L{Vec3<esys.lsm.util.Vec3>} object.\\n\"\n        \"@rtype: L{Vec3<esys.lsm.util.Vec3>}\\n\"\n        \"@return: angle and axis rotation representation.\"\n      )\n      .def(\n        \"asAngleAxisPair\",\n        &QuaternionPy::asAngleAxis,\n        \"Returns angle and axis rotation representation as a\"\n        \" two element tuple, the first element is the\"\n        \" angle and the second element is the\"\n        \" L{Vec3<esys.lsm.util.Vec3>} axis.\\n\"\n        \"@rtype: (float, L{Vec3<esys.lsm.util.Vec3>})\\n\"\n        \"@return: angle and axis rotation tuple-pair.\"\n      )\n      .def(self_ns::str(self))\n      .def(boost::python::self == boost::python::self)\n      .def(\"__len__\", &QuaternionPy::len)\n      .def(\"__getitem__\", &QuaternionPy::getItem)\n      .def(\"__setitem__\", &QuaternionPy::setItem)\n      .def(\n        \"toList\",\n        &QuaternionPy::toList,\n        \"Returns a python list of 4 elements.\\n\"\n        \"@rtype: list of four floats\\n\"\n        \"@return: C{[self[0],self[1],self[2],self[3]]}\"\n      )\n      .def(\n        \"toTuple\",\n        &QuaternionPy::toTuple,\n        \"Returns a python tuple of 4 elements.\\n\"\n        \"@rtype: tuple of four floats\\n\"\n        \"@return: C{(self[0],self[1],self[2],self[3])}\"\n      )\n      .def_pickle(QuaternionPy::PickleSuite())\n      ;\n    }\n  }\n}\n\nstd::ostream &operator<<(std::ostream &oStream, const esys::lsm::QuaternionPy &quat)\n{\n  oStream\n    << quat.return_sca() << \" \"\n    << quat.return_vec()[0] << \" \"\n    << quat.return_vec()[1] << \" \"\n    << quat.return_vec()[2];\n  return oStream;\n}\n", "meta": {"hexsha": "ff83e792d2de92e598c6503909318e393d10d712", "size": 6874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Python/esys/lsm/util/QuaternionPy.cpp", "max_stars_repo_name": "danielfrascarelli/esys-particle", "max_stars_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "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": "Python/esys/lsm/util/QuaternionPy.cpp", "max_issues_repo_name": "danielfrascarelli/esys-particle", "max_issues_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "max_issues_repo_licenses": ["Apache-2.0"], "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/esys/lsm/util/QuaternionPy.cpp", "max_forks_repo_name": "danielfrascarelli/esys-particle", "max_forks_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "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.496, "max_line_length": 91, "alphanum_fraction": 0.5314227524, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462564, "lm_q2_score": 0.040237944781612515, "lm_q1q2_score": 0.01777201401346204}}
{"text": "/*\n * Copyright 2014-2015 Arne Johanson\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 MESH_PERIODIC_HPP_\n#define MESH_PERIODIC_HPP_\n\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <cstdlib>\n#include <limits>\n#include <forward_list>\n#include <boost/iterator/iterator_facade.hpp>\n#include \"config.hpp\"\n#include \"util.hpp\"\n#include \"interval.hpp\"\n#include \"numa.hpp\"\n#include \"mesh_rect.hpp\"\n\n\n\n\ntemplate <unsigned int Dim>\nclass FEMMeshRectP1Periodic {\npublic:\n\tconstexpr static index_t noNeighbor       = INDEX_T_NO_NEIGHBOR;\n\tconstexpr static index_t maxValidNeighbor = INDEX_T_MAX_VALID;\n\n\tconstexpr static unsigned int nDimensions() {\n\t\treturn Dim;\n\t}\n\tconstexpr static unsigned int nDoFPerElement() {\n\t\treturn twoToThePowerOfN(Dim);\n\t}\n\tconstexpr static unsigned int nHypersufacesPerElement() {\n\t\treturn 2*Dim;\n\t}\nprivate:\n\tstruct ElementData {\n\t\tshort_index_t multiIndex[Dim];\n\t\tindex_t dofIndices[nDoFPerElement()];\n\t\tindex_t neighborIndices[nHypersufacesPerElement()];\n\n\t\tvoid print(index_t j) const {\n\t\t\tstd::cout << \"Element \" << j << \" mit Multiindex ( \";\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tstd::cout << multiIndex[i] << \" \";\n\t\t\t}\n\t\t\tstd::cout << \") und Freiheitsgraden \";\n\t\t\tfor(uint i=0; i<nDoFPerElement(); ++i) {\n\t\t\t\tstd::cout << dofIndices[i] << \" \";\n\t\t\t}\n//\t\t\tstd::cout << \" und Nachbarn \";\n//\t\t\tfor(uint i=0; i<nHypersufacesPerElement(); ++i) {\n//\t\t\t\tstd::cout << neighborIndices[i] << \" \";\n//\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t};\n\tstruct DoFData {\n\t\tshort_index_t multiIndex[Dim];\n\n\t\tvoid print(index_t j) const {\n\t\t\tstd::cout << \"DoF \" << j << \" mit Multiindex ( \";\n\t\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\t\tstd::cout << multiIndex[i] << \" \";\n\t\t\t}\n\t\t\tstd::cout << \")\" << std::endl;\n\t\t}\n\t};\n\n\tnuma_vector<ElementData> _elementData;\n\tstd::vector<bool> _elementHasDomainBorder;\n\tstd::vector<index_t> _elementsWithDomainBorder;\n\tnuma_vector<DoFData> _dofData;\n\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\tstd::vector<std::forward_list<index_t>> _elementsOfDoF;\n\tstd::vector<numa_vector<index_t>> _independentElementDecomposition;\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\n\tconstexpr static unsigned int twoToThePowerOfN(unsigned int n) {\n\t\treturn (n>0 ? 2*twoToThePowerOfN(n-1) : 1);\n\t}\n\n\tindex_t multiIndexToElementIndexInFullyPopulatedMesh(short_index_t multiIndex[Dim]) {\n\t\tindex_t result = multiIndex[0];\n\t\tfor(uint i=1; i<Dim; ++i) {\n\t\t\tresult *= dimensions[i].nElements;\n\t\t\tresult += multiIndex[i];\n\t\t}\n\t\treturn result;\n\t}\n\n\tvoid findElementsWithDomainBorder() {\n\t\t_elementsWithDomainBorder.resize(0);\n\t\t_elementHasDomainBorder.resize(_elementData.size());\n\t\tfor(index_t i=0; i<_elementData.size(); ++i) {\n\t\t\t_elementHasDomainBorder[i] = false;\n\t\t}\n\t}\n\n\tvoid createElementsOfDoF(index_t numDoF, std::vector<ElementData> const& elemData) {\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\t\t_elementsOfDoF.resize(numDoF);\n\n\t\tfor(index_t i=0; i<numDoF; ++i) {\n\t\t\t_elementsOfDoF[i].clear();\n\t\t}\n\n\t\tfor(index_t i=0; i<elemData.size(); ++i) {\n\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\t_elementsOfDoF[elemData[i].dofIndices[k]].push_front(i);\n\t\t\t}\n\t\t}\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\t}\n\n\tvoid createMaximalIndependentElementSets(std::vector<ElementData> const& elemData) {\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\t\tstatic constexpr uint noColor = std::numeric_limits<uint>::max();\n\t\t//static constexpr uint noColor = UINT_MAX; // For Intel compiler bug\n\t\tstd::vector<uint> elementColor(elemData.size(), noColor);\n\t\tindex_t nUncolored = elemData.size();\n\t\tuint nColors = 0;\n\n\t\tfor(uint currentColor=0; nUncolored>0; ++currentColor) {\n\t\t\tfor(index_t i=0; i<elemData.size(); ++i) {\n\t\t\t\tif(elementColor[i] != noColor) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbool hasNeighbourOfCurrentColor = false;\n\t\t\t\tfor(uint k=0; k<nDoFPerElement() && !hasNeighbourOfCurrentColor; ++k) {\n\t\t\t\t\tconst index_t dof = elemData[i].dofIndices[k];\n\t\t\t\t\tfor(auto it=_elementsOfDoF[dof].cbegin(); it!=_elementsOfDoF[dof].cend(); ++it) {\n\t\t\t\t\t\tif(elementColor[*it] == currentColor) {\n\t\t\t\t\t\t\thasNeighbourOfCurrentColor = 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\tif(!hasNeighbourOfCurrentColor) {\n\t\t\t\t\telementColor[i] = currentColor;\n\t\t\t\t\tnUncolored -= 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnColors += 1;\n\t\t}\n\n\t\tstd::vector<std::vector<index_t>> independentElementDecompositionTemp(nColors);\n\t\tfor(uint color=0; color<nColors; ++color) {\n\t\t\tindependentElementDecompositionTemp[color].clear();\n\t\t}\n\t\tfor(index_t i=0; i<elemData.size(); ++i) {\n\t\t\tindependentElementDecompositionTemp[elementColor[i]].push_back(i);\n\t\t}\n\n\t\t_independentElementDecomposition.resize(nColors);\n\t\tfor(uint color=0; color<nColors; ++color) {\n\t\t\t_independentElementDecomposition[color].resize(independentElementDecompositionTemp[color].size());\n\t\t\tforeach_omp_index(i, _independentElementDecomposition[color].size(), shared(color,independentElementDecompositionTemp), {\n\t\t\t\t\t_independentElementDecomposition[color][i] = independentElementDecompositionTemp[color][i];\n\t\t\t})\n\t\t}\n\n\n\t\t// Debug output\n\t\t//for(index_t i=0; i<nElements(); ++i) {\n\t\t//\tstd::cout << \"Element \" << i << \" hat Farbe \" << elementColor[i] << std::endl;\n\t\t//}\n\t\t//std::cout << std::endl;\n\t\t//for(uint color=0; color<nColors; ++color) {\n\t\t//\tstd::cout << \"Farbe \" << color << \" haben die Elemente:\";\n\t\t//\tfor(index_t i=0; i<_independentElementDecomposition[color].size(); ++i) {\n\t\t//\t\tstd::cout << \" \" << _independentElementDecomposition[color][i];\n\t\t//\t}\n\t\t//\tstd::cout << std::endl;\n\t\t//}\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\t}\n\npublic:\n\tRectMeshDimension dimensions[Dim];\n\n\tFEMMeshRectP1Periodic() {}\n\n\tFEMMeshRectP1Periodic(std::vector<RectMeshDimension> const& dimensions_in) :\n\t\tFEMMeshRectP1Periodic(&dimensions_in[0]) {}\n\n\tFEMMeshRectP1Periodic(RectMeshDimension const * const dimensions_in) {\n\t\tindex_t totalElements = 1;\n\t\tindex_t totalDoF = 1;\n\t\tfor(uint i=0; i<Dim; ++i) {\n\t\t\tdimensions[i] = dimensions_in[i];\n\t\t\ttotalElements *= dimensions[i].nElements;\n\t\t\ttotalDoF *= dimensions[i].nNodes-1;\n\t\t}\n\n\t\tstd::vector<ElementData> elementDataTemp(totalElements);\n\t\t_dofData.resize(totalDoF);\n\n\t\tfor(index_t index=0; index<totalElements; ++index) {\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t// *** multiIndex\n\t\t\t\tindex_t divideAway = index;\n\t\t\t\tfor(uint j=Dim-1; j>k; --j) {\n\t\t\t\t\tdivideAway /= dimensions[j].nElements;\n\t\t\t\t}\n\t\t\t\telementDataTemp[index].multiIndex[k] = divideAway % dimensions[k].nElements;\n\t\t\t}\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t// *** neighborIndices\n\n\t\t\t\t// find left neighbor\n\t\t\t\tshort_index_t leftNeighborIndex[Dim];\n\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\tleftNeighborIndex[j] = elementDataTemp[index].multiIndex[j];\n\t\t\t\t}\n\t\t\t\tif(leftNeighborIndex[k] == 0) {\n\t\t\t\t\tleftNeighborIndex[k] = dimensions[k].nElements-1;\n\t\t\t\t} else {\n\t\t\t\t\tleftNeighborIndex[k] -= 1;\n\t\t\t\t}\n\t\t\t\telementDataTemp[index].neighborIndices[2*k  ] = multiIndexToElementIndexInFullyPopulatedMesh(leftNeighborIndex);\n\n\t\t\t\t// find right neighbor\n\t\t\t\tshort_index_t rightNeighborIndex[Dim];\n\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\trightNeighborIndex[j] = elementDataTemp[index].multiIndex[j];\n\t\t\t\t}\n\t\t\t\tif(rightNeighborIndex[k] == dimensions[k].nElements-1) {\n\t\t\t\t\trightNeighborIndex[k] = 0;\n\t\t\t\t} else {\n\t\t\t\t\trightNeighborIndex[k] += 1;\n\t\t\t\t}\n\t\t\t\telementDataTemp[index].neighborIndices[2*k+1] = multiIndexToElementIndexInFullyPopulatedMesh(rightNeighborIndex);\n\t\t\t}\n\t\t\tfor(uint k=0; k<nDoFPerElement(); ++k) {\n\t\t\t\t// *** dofIndices\n\t\t\t\tuint dofPosition[Dim];\n\t\t\t\tuint divideAway = k;\n\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\tdofPosition[Dim-1-j] = divideAway%2;\n\t\t\t\t\tdivideAway /= 2;\n\t\t\t\t}\n\t\t\t\tindex_t dofIndex = 0;\n\t\t\t\tfor(uint j=0; j<Dim; ++j) {\n\t\t\t\t\tdofIndex *= dimensions[j].nNodes-1;\n\t\t\t\t\tif(!(elementDataTemp[index].multiIndex[j] == dimensions[j].nElements-1 && dofPosition[j] == 1)) {\n\t\t\t\t\t\tdofIndex += elementDataTemp[index].multiIndex[j] + dofPosition[j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telementDataTemp[index].dofIndices[k] = dofIndex;\n\t\t\t}\n\t\t}\n\n\n\t\tcreateElementsOfDoF(totalDoF, elementDataTemp);\n\t\tcreateMaximalIndependentElementSets(elementDataTemp);\n\n\t\t_elementData.resize(elementDataTemp.size());\n\t\tforeachElementIndependently(auto tau, *this, shared(elementDataTemp), {\n\t\t\t\t_elementData[tau] = elementDataTemp[tau];\n\t\t})\n\t\telementDataTemp.clear();\n\n\t\tfindElementsWithDomainBorder();\n\n\t\t//std::cout << \"There are \" << _elementData.size() << \" elements in the master mesh.\" << std::endl;\n\n\n\t\tforeach_omp_index(index, totalDoF, , {\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\tindex_t divideAway = index;\n\t\t\t\tfor(uint j=Dim-1; j>k; --j) {\n\t\t\t\t\tdivideAway /= (dimensions[j].nNodes-1);\n\t\t\t\t}\n\t\t\t\t_dofData[index].multiIndex[k] = divideAway % (dimensions[k].nNodes-1);\n\t\t\t}\n\t\t})\n\n//\t\tfor(uint i=0; i<_elementData.size(); ++i) {\n//\t\t\t_elementData[i].print(i);\n//\t\t}\n//\t\tfor(uint i=0; i<_dofData.size(); ++i) {\n//\t\t\t_dofData[i].print(i);\n//\t\t}\n\t}\n\n\n#ifdef SPRAT_BUILD_WITH_OPENMP\n\tstd::vector<numa_vector<index_t>> const& getIndependentElementDecomposition() const {\n\t\treturn _independentElementDecomposition;\n\t}\n#endif //#ifdef SPRAT_BUILD_WITH_OPENMP\n\n\tindex_t nElements() const {\n\t\treturn _elementData.size();\n\t}\n\tindex_t nLocalElements() const {\n\t\treturn nElements();\n\t}\n\tindex_t nElementsWithDomainBorder() const {\n\t\treturn _elementsWithDomainBorder.size();\n\t}\n\tindex_t nDoF() const {\n\t\treturn _dofData.size();\n\t}\n\tindex_t nSpatialDoF() const {\n\t\treturn _dofData.size() / dimensions[Dim-1].nNodes;\n\t}\n\tindex_t nLocalDoF() const {\n\t\treturn nDoF();\n\t}\n\n\n\tclass ElementT {\n\tpublic:\n\t\tconstexpr static unsigned int nDoFPerElement() {\n\t\t\treturn FEMMeshRectP1Periodic<Dim>::twoToThePowerOfN(Dim);\n\t\t}\n\tprivate:\n\n\t\tFEMMeshRectP1Periodic<Dim> const& _femMesh;\n\t\tconst index_t _index;\n\n\t\t// WARNING: Initially, end must be vec.size()\n\t\tindex_t binarySearchInSortedIndexVector(std::vector<index_t> const& vec, index_t begin, index_t end, index_t value) const {\n\t\t\tconst index_t mid = (begin+end)/2;\n\t\t\tconst index_t mid_value = vec[mid];\n\t\t\tif(mid_value == value) {\n\t\t\t\treturn mid;\n\t\t\t}\n\t\t\telse if(value < mid_value) {\n\t\t\t\treturn binarySearchInSortedIndexVector(vec, begin, mid, value);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn binarySearchInSortedIndexVector(vec, mid, end, value);\n\t\t\t}\n\t\t}\n\n\tpublic:\n\t\tElementT(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t index) : _femMesh(femMesh), _index(index) {}\n\n\t\toperator index_t() const {\n\t\t\treturn _index;\n\t\t}\n\t\tindex_t index() const {\n\t\t\treturn _index;\n\t\t}\n\n\t\tuint indexInDimension(uint dimension) const {\n\t\t\treturn _femMesh._elementData[_index].multiIndex[dimension];\n\t\t}\n\n\t\treal diamInDimension(uint dimension) const {\n\t\t\treturn _femMesh.dimensions[dimension].elementDiameter[indexInDimension(dimension)];\n\t\t}\n\n\t\tindex_t globalDoFIndex(uint localDoFIndex) const {\n\t\t\treturn _femMesh._elementData[_index].dofIndices[localDoFIndex];\n\t\t}\n\n\t\tindex_t const * globalDoFIndices() const {\n\t\t\treturn _femMesh._elementData[_index].dofIndices;\n\t\t}\n\n\t\tFEMMeshRectP1Periodic<Dim> const& getMesh() const {\n\t\t\treturn _femMesh;\n\t\t}\n\n\n\t\t/*\n\t\t * Returns - \\sum_{k=1}^d \\int_\\tau \\frac{\\partial}{\\partial x_k} \\prod_{l} \\phi_i_l (x_l)  *  \\frac{\\partial}{\\partial x_k} \\prod_{m} \\phi_i_m (x_m)  dx\n\t\t * Assertion: i and j are *local* DoF Indices (\\in {0,1,2, ..., nDofPerElement()})\n\t\t */\n\t\treal integratePartIntLaplace(uint i, uint j) const {\n\t\t\tuint iMultiIndex[Dim];\n\t\t\tuint jMultiIndex[Dim];\n\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\tiMultiIndex[Dim-1-k] = i%2;\n\t\t\t\ti /= 2;\n\t\t\t\tjMultiIndex[Dim-1-k] = j%2;\n\t\t\t\tj /= 2;\n\t\t\t}\n\n\t\t\tconst real intValue[4] = {1.0/3.0, 1.0/6.0, 1.0/6.0, 1.0/3.0}; // (i_x/y, j_x/y): (0,0), (0,1), (1,0), (1,1)\n\t\t\tconst real diffValue[4] = {1.0, -1.0, -1.0, 1.0}; // (i_x/y, j_x/y): (0,0), (0,1), (1,0), (1,1)\n\t\t\treal result = 0.0;\n\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\treal dimResult = 1.0;\n\t\t\t\tfor(uint l=0; l<Dim; ++l) {\n\t\t\t\t\tif(l != k) {\n\t\t\t\t\t\tdimResult *= diamInDimension(l) * intValue[2*iMultiIndex[l] + jMultiIndex[l]];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdimResult *= diffValue[2*iMultiIndex[l] + jMultiIndex[l]] / diamInDimension(l);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult += dimResult;\n\t\t\t}\n\t\t\treturn -1.0 * result;\n\t\t}\n\n\n\t\tbool hasDomainBorder() const {\n\t\t\treturn _femMesh._elementHasDomainBorder[_index];\n\t\t}\n\n\t\tindex_t iAmTheNThElementWithDomainBorder() const {\n\t\t\t//const index_t result = std::find(_femMesh._elementsWithDomainBorder.begin(), _femMesh._elementsWithDomainBorder.end(), _index) - _femMesh._elementsWithDomainBorder.begin();\n\t\t\t//if(result >= _femMesh._elementsWithDomainBorder.size()) {\n\t\t\t//\tstd::cout << \"IAmTheNThElementWithDomainBorder: This should NOT happen!\" << std::endl;\n\t\t\t//}\n\n\t\t\treturn binarySearchInSortedIndexVector(_femMesh._elementsWithDomainBorder, 0, _femMesh._elementsWithDomainBorder.size(), _index);\n\t\t}\n\t\tuint nDomainBorderHypesurfaces() const {\n\t\t\tuint result = 0;\n\t\t\tfor(uint i=0; i<nHypersufacesPerElement(); ++i) {\n\t\t\t\tif(neighborElementIndices()[i] == noNeighbor) {\n\t\t\t\t\tresult += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tindex_t neighborElementIndex(short_index_t index) const {\n\t\t\treturn _femMesh._elementData[_index].neighborIndices[index];\n\t\t}\n\t\tindex_t const * neighborElementIndices() const {\n\t\t\treturn _femMesh._elementData[_index].neighborIndices;\n\t\t}\n\n\t\t/*\n\t\t * Terminology:\n\t\t * (Global) DoF -- all DoF accessible by this compute node\n\t\t * LocalDoF     -- DoF genuinely belonging to this compute node\n\t\t * ElementDoF   -- DoF belonging to one element\n\t\t */\n\t\tclass ElementDoFT {\n\t\tprivate:\n\t\t\tuint _localIndex;\n\t\t\tindex_t _globalIndex;\n\n\t\tpublic:\n\t\t\tElementDoFT(uint localIndex, index_t globalIndex) : _localIndex(localIndex), _globalIndex(globalIndex) {\n\t\t\t\t//std::cout << \"Constructing ElementDoFT with localIndex \" << _localIndex << \" and global index \" << _globalIndex << std::endl;\n\t\t\t}\n\n\t\t\toperator uint() const {\n\t\t\t\treturn _localIndex;\n\t\t\t}\n\t\t\tuint index() const {\n\t\t\t\treturn _localIndex;\n\t\t\t}\n\t\t\tuint localIndex() const {\n\t\t\t\treturn _localIndex;\n\t\t\t}\n\n\t\t\tindex_t globalIndex() const {\n\t\t\t\treturn _globalIndex;\n\t\t\t}\n\n\t\t\tbool operator==(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex == other._localIndex;\n\t\t\t}\n\t\t\tbool operator!=(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex != other._localIndex;\n\t\t\t}\n\t\t\tbool operator<(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex < other._localIndex;\n\t\t\t}\n\t\t\tbool operator<=(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex <= other._localIndex;\n\t\t\t}\n\t\t\tbool operator>(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex > other._localIndex;\n\t\t\t}\n\t\t\tbool operator>=(ElementDoFT const& other) const {\n\t\t\t\treturn _localIndex >= other._localIndex;\n\t\t\t}\n\t\t};\n\n\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::ElementDoFT elementDoF(uint localIndex) const {\n\t\t\treturn typename FEMMeshRectP1Periodic<Dim>::ElementT::ElementDoFT(localIndex, globalDoFIndex(localIndex));\n\t\t}\n\n\t\tclass IterateElementDoF {\n\t\tprivate:\n\t\t\tindex_t const*const _globalDoF;\n\n\t\tpublic:\n\t\t\tIterateElementDoF(typename FEMMeshRectP1Periodic<Dim>::ElementT element) :\n\t\t\t\t_globalDoF(element.globalDoFIndices()) {}\n\n\n\t\t\tclass const_iterator : public boost::iterator_facade<\n\t\t\tconst_iterator\n\t\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT::ElementDoFT const\n\t\t\t, boost::random_access_traversal_tag\n\t\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT::ElementDoFT const\n\t\t\t, signed_short_index_t> {\n\t\t\tpublic:\n\t\t\t\t//const_iterator() : _element(0), _elementDoFIndex(0) {}\n\t\t\t\texplicit const_iterator(index_t const* globalDoF) : _globalDoF(globalDoF), _localIndex(0) {}\n\t\t\t\tconst_iterator(index_t const* globalDoF, short_index_t localIndex) : _globalDoF(globalDoF), _localIndex(localIndex) {}\n\n\t\t\tprivate:\n\t\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\t\tvoid increment() { ++_localIndex; }\n\t\t\t\tvoid decrement() { --_localIndex; }\n\t\t\t\tvoid advance(signed_short_index_t n) { _localIndex+=n; }\n\t\t\t\tsigned_short_index_t distance_to(const_iterator const& other) const { return other._localIndex - this->_localIndex; }\n\n\t\t\t\tbool equal(const_iterator const& other) const {\treturn this->_localIndex == other._localIndex; }\n\n\t\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::ElementDoFT const dereference() const {\n\t\t\t\t\treturn typename FEMMeshRectP1Periodic<Dim>::ElementT::ElementDoFT(_localIndex, _globalDoF[_localIndex]);\n\t\t\t\t}\n\n\t\t\t\tindex_t const* _globalDoF;\n\t\t\t\tsigned_short_index_t _localIndex;\n\t\t\t};\n\t\t\ttypedef const_iterator iterator;\n\n\t\t\titerator begin() const { return iterator(_globalDoF); }\n\t\t\titerator end() const { return iterator(_globalDoF, FEMMeshRectP1Periodic<Dim>::nDoFPerElement()); }\n\t\t\tconst_iterator cbegin() const { return const_iterator(_globalDoF); }\n\t\t\tconst_iterator cend() const { return const_iterator(_globalDoF, FEMMeshRectP1Periodic<Dim>::nDoFPerElement()); }\n\t\t};\n\n\t\tclass HypersurfaceT {\n\t\tpublic:\n\t\t\tconstexpr static unsigned int nDoFPerHypersurface() {\n\t\t\t\treturn Dim;\n\t\t\t}\n\t\tprivate:\n\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT const& _element;\n\t\t\tshort_index_t _surfaceIndex;\n\t\tpublic:\n\t\t\tHypersurfaceT(typename FEMMeshRectP1Periodic<Dim>::ElementT const& element, uint localIndex) :\n\t\t\t\t_element(element),\n\t\t\t\t_surfaceIndex(localIndex)\n\t\t\t{}\n\n\t\t\toperator short_index_t() const {\n\t\t\t\treturn _surfaceIndex;\n\t\t\t}\n\t\t\tshort_index_t index() const {\n\t\t\t\treturn _surfaceIndex;\n\t\t\t}\n\n\t\t\tuint elementDoFIndex(uint hypersurfaceDoFIndex) const {\n\t\t\t\tconst uint normalDimension = _surfaceIndex/2;\n\t\t\t\tconst uint normalEntry = _surfaceIndex%2;\n\t\t\t\tconst uint allOnes = ~(0U);\n\t\t\t\tconst uint maskLowerPart = ~(allOnes << (Dim-1-normalDimension));\n\t\t\t\tconst uint maskHigherPart = allOnes << (Dim-1-normalDimension);\n\t\t\t\tconst uint result = (normalEntry<<(Dim-1-normalDimension))    |\n\t\t\t\t                    (hypersurfaceDoFIndex & maskLowerPart)    |\n\t\t\t\t                    ((hypersurfaceDoFIndex & maskHigherPart)<<1);\n\t\t\t\t//std::cout << \"Für hypersurfaceDoFIndex=\" << hypersurfaceDoFIndex << \" von Hypersurface \" << _surfaceIndex <<\n\t\t\t\t//\t\t\" ist elementDoFIndex=\" << result << std::endl;\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tclass HypersurfaceDoFT {\n\t\t\tprivate:\n\t\t\t\tuint _hypersurfaceIndex;\n\t\t\t\tuint _elementIndex;\n\n\t\t\tpublic:\n\t\t\t\tHypersurfaceDoFT(uint hypersurfaceIndex, index_t elementIndex) : _hypersurfaceIndex(hypersurfaceIndex), _elementIndex(elementIndex) {}\n\n\t\t\t\toperator uint() const {\n\t\t\t\t\treturn _hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tuint index() const {\n\t\t\t\t\treturn _hypersurfaceIndex;\n\t\t\t\t}\n\n\t\t\t\tuint elementDoFIndex() const {\n\t\t\t\t\treturn _elementIndex;\n\t\t\t\t}\n\n\t\t\t\tbool operator==(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex == other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator!=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex != other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator<(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex < other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator<=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex <= other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator>(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex > other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator>=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex >= other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT hypersurfaceDoF(uint hypersurfaceDoFIndex) const {\n\t\t\t\treturn typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT(hypersurfaceDoFIndex, elementDoFIndex(hypersurfaceDoFIndex));\n\t\t\t}\n\n\t\t\treal surfaceIntegral(HypersurfaceDoFT const& i, HypersurfaceDoFT const& j, uint dimension) {\n\t\t\t\tuint i_elem = i.elementDoFIndex();\n\t\t\t\tuint j_elem = j.elementDoFIndex();\n\n\t\t\t\tconst uint normalDimension = _surfaceIndex/2;\n\t\t\t\tif(normalDimension != dimension) {\n\t\t\t\t\treturn 0.0;\n\t\t\t\t}\n\n\t\t\t\tuint iMultiIndex[Dim];\n\t\t\t\tuint jMultiIndex[Dim];\n\n\t\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t\tiMultiIndex[Dim-1-k] = i_elem%2;\n\t\t\t\t\ti_elem /= 2;\n\t\t\t\t\tjMultiIndex[Dim-1-k] = j_elem%2;\n\t\t\t\t\tj_elem /= 2;\n\t\t\t\t}\n\n\n\t\t\t\tconst real intValue[2] = {1.0/3.0, 1.0/6.0};\n\n\t\t\t\tconst bool isLeftSurface = (_surfaceIndex%2 == 0);\n\t\t\t\treal result = (isLeftSurface ? -1.0 : 1.0);\n\t\t\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\t\t\tif(k != normalDimension) {\n\t\t\t\t\t\tresult *= intValue[(iMultiIndex[k]!=jMultiIndex[k] ? 1 : 0)] * _element.diamInDimension(k);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tclass IterateHypersurfaceDoF {\n\t\t\tprivate:\n\t\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const& _hypersurface;\n\n\t\t\tpublic:\n\t\t\t\tIterateHypersurfaceDoF(typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const& hypersurface) :\n\t\t\t\t\t_hypersurface(hypersurface) {\n\t\t\t\t\t//std::cout << \"IterateHypersurfaceDoF(hypersurface), hypersurface = \" << &hypersurface << std::endl;\n\t\t\t\t}\n\n\n\t\t\t\tclass const_iterator : public boost::iterator_facade<\n\t\t\t\tconst_iterator\n\t\t\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT const\n\t\t\t\t, boost::random_access_traversal_tag\n\t\t\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT const\n\t\t\t\t, signed_short_index_t> {\n\t\t\t\tpublic:\n\t\t\t\t\t//const_iterator() : _element(0), _elementDoFIndex(0) {}\n\t\t\t\t\texplicit const_iterator(typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const& hypersurface) : _hypersurface(hypersurface), _localIndex(0) {\n\t\t\t\t\t\t//std::cout << \"IterateHypersurfaceDoF::const_iterator(hypersurface), hypersurface = \" << &hypersurface << std::endl;\n\t\t\t\t\t}\n\t\t\t\t\tconst_iterator(typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const& hypersurface, short_index_t localIndex) : _hypersurface(hypersurface), _localIndex(localIndex) {\n\t\t\t\t\t\t//std::cout << \"IterateHypersurfaceDoF::const_iterator(hypersurface, index), hypersurface = \" << &hypersurface << std::endl;\n\t\t\t\t\t}\n\n\t\t\t\tprivate:\n\t\t\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\t\t\tvoid increment() { ++_localIndex; }\n\t\t\t\t\tvoid decrement() { --_localIndex; }\n\t\t\t\t\tvoid advance(signed_short_index_t n) { _localIndex+=n; }\n\t\t\t\t\tsigned_short_index_t distance_to(const_iterator const& other) const { return other._localIndex - this->_localIndex; }\n\n\t\t\t\t\tbool equal(const_iterator const& other) const {\treturn this->_localIndex == other._localIndex; }\n\n\t\t\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT::HypersurfaceDoFT const dereference() const {\n\t\t\t\t\t\treturn _hypersurface.hypersurfaceDoF(_localIndex);\n\t\t\t\t\t}\n\n\t\t\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const& _hypersurface;\n\t\t\t\t\tsigned_short_index_t _localIndex;\n\t\t\t\t};\n\t\t\t\ttypedef const_iterator iterator;\n\n\t\t\t\titerator begin() const { return iterator(_hypersurface); }\n\t\t\t\titerator end() const { return iterator(_hypersurface, FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT::nDoFPerHypersurface()); }\n\t\t\t\tconst_iterator cbegin() const { return const_iterator(_hypersurface); }\n\t\t\t\tconst_iterator cend() const { return const_iterator(_hypersurface, FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT::nDoFPerHypersurface()); }\n\t\t\t};\n\t\t};\n\n\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT hypersurface(uint surfaceIndex) const {\n\t\t\treturn typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT(*this, surfaceIndex);\n\t\t}\n\n\t\tclass IterateElementDomainBoundaryHypersurfaces {\n\t\tprivate:\n\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT const& _element;\n\t\t\tconst uint _nDomainBoundaryHypersurfaces;\n\t\tpublic:\n\t\t\tIterateElementDomainBoundaryHypersurfaces(typename FEMMeshRectP1Periodic<Dim>::ElementT const& element) :\n\t\t\t\t_element(element),\n\t\t\t\t_nDomainBoundaryHypersurfaces(element.nDomainBorderHypesurfaces()){}\n\n\t\t\tclass const_iterator : public boost::iterator_facade<\n\t\t\tconst_iterator\n\t\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const\n\t\t\t, boost::random_access_traversal_tag\n\t\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const\n\t\t\t, int> {\n\t\t\tpublic:\n\t\t\t\tconst_iterator() : _element(0), _hypersurfaceIndex(0) {}\n\t\t\t\t//explicit const_iterator(FEMMeshRectP1<Dim> const& femMesh) : _femMesh(femMesh), _elementIndex(0) {}\n\t\t\t\texplicit const_iterator(typename FEMMeshRectP1Periodic<Dim>::ElementT const& element) : _element(&element), _hypersurfaceIndex(0) {}\n\t\t\t\tconst_iterator(typename FEMMeshRectP1Periodic<Dim>::ElementT const& element, int hypersurfaceIndex) : _element(&element), _hypersurfaceIndex(hypersurfaceIndex) {}\n\n\t\t\tprivate:\n\t\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\t\tvoid increment() { ++_hypersurfaceIndex; }\n\t\t\t\tvoid decrement() { --_hypersurfaceIndex; }\n\t\t\t\tvoid advance(int n) { _hypersurfaceIndex+=n; }\n\t\t\t\tint distance_to(const_iterator const& other) const { return  other._hypersurfaceIndex - this->_hypersurfaceIndex; }\n\n\t\t\t\tbool equal(const_iterator const& other) const {\treturn this->_hypersurfaceIndex == other._hypersurfaceIndex; }\n\n\t\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT::HypersurfaceT const dereference() const {\n\t\t\t\t\tuint nBorderSurface = 0;\n\t\t\t\t\tfor(int i=0; i<nHypersufacesPerElement(); ++i) {\n\t\t\t\t\t\tif(_element->neighborElementIndex(i) == noNeighbor) {\n\t\t\t\t\t\t\tif(nBorderSurface == _hypersurfaceIndex) {\n\t\t\t\t\t\t\t\tnBorderSurface = i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnBorderSurface += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn _element->hypersurface(nBorderSurface);\n\t\t\t\t}\n\n\t\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT const* _element;\n\t\t\t\tint _hypersurfaceIndex;\n\t\t\t};\n\t\t\ttypedef const_iterator iterator;\n\n\t\t\titerator begin() const { return iterator(_element); }\n\t\t\titerator end() const { return iterator(_element, _nDomainBoundaryHypersurfaces); }\n\t\t\tconst_iterator cbegin() const { return const_iterator(_element); }\n\t\t\tconst_iterator cend() const { return const_iterator(_element, _nDomainBoundaryHypersurfaces); }\n\t\t};\n\t};\n\n\tElementT const element(index_t index) const {\n\t\treturn ElementT(*this, index);\n\t}\n\n\tclass DoFT {\n\tprivate:\n\t\tFEMMeshRectP1Periodic<Dim> const& _femMesh;\n\t\tconst index_t _index;\n\n\tpublic:\n\t\tDoFT(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t index) : _femMesh(femMesh), _index(index) {}\n\n\t\toperator index_t() const {\n\t\t\treturn _index;\n\t\t}\n\t\tindex_t index() const {\n\t\t\treturn _index;\n\t\t}\n\n\t\tuint indexInDimension(uint dimension) const {\n\t\t\treturn _femMesh._dofData[_index].multiIndex[dimension];\n\t\t}\n\n\t\treal positionInDimension(uint dimension) const {\n\t\t\treturn _femMesh.dimensions[dimension].nodes[indexInDimension(dimension)];\n\t\t}\n\n\t\treal spatialDistance(DoFT const& other) const {\n\t\t\treal result = 0.0;\n\n\t\t\tfor(uint i=0; i<Dim-1; ++i) {\n\t\t\t\tconst real otherPos = other.positionInDimension(i);\n\t\t\t\tconst real thisPos = positionInDimension(i);\n\t\t\t\tconst real a = _femMesh.dimensions[i].nodes.front();\n\t\t\t\tconst real b = _femMesh.dimensions[i].nodes.back();\n\n\t\t\t\tconst real diffNormal = fabs(otherPos - thisPos);\n\t\t\t\tconst real diffWrappedA =\n\t\t\t\t\t\totherPos - a +\n\t\t\t\t\t\tb - thisPos;\n\t\t\t\tconst real diffWrappedB =\n\t\t\t\t\t\tthisPos - a +\n\t\t\t\t\t\tb - otherPos;\n\n\t\t\t\tconst real diff = min(diffNormal, diffWrappedA, diffWrappedB);\n\t\t\t\tresult += diff*diff;\n\t\t\t}\n\n\t\t\treturn sqrt(result);\n\t\t}\n\t};\n\n\tDoFT dof(index_t index) const {\n\t\treturn DoFT(*this, index);\n\t}\n\n\n\t/*\n\t * Iterations\n\t */\n\n\tclass IterateMeshElements {\n\tprivate:\n\t\tFEMMeshRectP1Periodic<Dim> const& _femMesh;\n\t\tconst index_t _beginIndex;\n\t\tconst index_t _endIndex;\n\n\tpublic:\n\t\tIterateMeshElements(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t beginIndex, index_t endIndex) :\n\t\t\t_femMesh(femMesh), _beginIndex(beginIndex), _endIndex(endIndex) {}\n\n\n\t\tclass const_iterator : public boost::iterator_facade<\n\t\tconst_iterator\n\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT const\n\t\t, boost::random_access_traversal_tag\n\t\t, typename FEMMeshRectP1Periodic<Dim>::ElementT const\n\t\t, signed_index_t> {\n\t\tpublic:\n\t\t\tconst_iterator() : _femMesh(0), _elementIndex(0) {}\n\t\t\t//explicit const_iterator(FEMMeshRectP1<Dim> const& femMesh) : _femMesh(femMesh), _elementIndex(0) {}\n\t\t\tconst_iterator(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t elementIndex) : _femMesh(&femMesh), _elementIndex(elementIndex) {}\n\n\t\tprivate:\n\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\tvoid increment() { ++_elementIndex; }\n\t\t\tvoid decrement() { --_elementIndex; }\n\t\t\tvoid advance(signed_index_t n) { _elementIndex+=n; }\n\t\t\tsigned_index_t distance_to(const_iterator const& other) const { return  other._elementIndex - this->_elementIndex; }\n\n\t\t\tbool equal(const_iterator const& other) const {\treturn this->_elementIndex == other._elementIndex; }\n\n\t\t\ttypename FEMMeshRectP1Periodic<Dim>::ElementT const dereference() const {\n\t\t\t\treturn _femMesh->element(_elementIndex);\n\t\t\t}\n\n\t\t\tFEMMeshRectP1Periodic<Dim> const * _femMesh;\n\t\t\tsigned_index_t _elementIndex;\n\t\t};\n\t\ttypedef const_iterator iterator;\n\n\t\titerator begin() const { return iterator(_femMesh, _beginIndex); }\n\t\titerator end() const { return iterator(_femMesh, _endIndex); }\n\t\tconst_iterator cbegin() const { return const_iterator(_femMesh, _beginIndex); }\n\t\tconst_iterator cend() const { return const_iterator(_femMesh, _endIndex); }\n\t};\n\n\tclass IterateDoF {\n\tprivate:\n\t\tFEMMeshRectP1Periodic<Dim> const& _femMesh;\n\t\tconst index_t _beginIndex;\n\t\tconst index_t _endIndex;\n\tpublic:\n\t\tIterateDoF(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t beginIndex, index_t endIndex) :\n\t\t\t_femMesh(femMesh), _beginIndex(beginIndex), _endIndex(endIndex) {}\n\n\n\t\tclass const_iterator : public boost::iterator_facade<\n\t\tconst_iterator\n\t\t, typename FEMMeshRectP1Periodic<Dim>::DoFT const\n\t\t, boost::random_access_traversal_tag\n\t\t, typename FEMMeshRectP1Periodic<Dim>::DoFT const\n\t\t, signed_index_t> {\n\t\tpublic:\n\t\t\t//const_iterator() : _element(0), _elementDoFIndex(0) {}\n\t\t\t//explicit const_iterator(Mesh_2DRect const& mesh) : _mesh(mesh), _dofIndex(0) {}\n\t\t\tconst_iterator(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t dofIndex) : _femMesh(&femMesh), _dofIndex(dofIndex) {}\n\n\t\tprivate:\n\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\tvoid increment() { ++_dofIndex; }\n\t\t\tvoid decrement() { --_dofIndex; }\n\t\t\tvoid advance(signed_index_t n) { _dofIndex+=n; }\n\t\t\tsigned_index_t distance_to(const_iterator const& other) const { return other._dofIndex - this->_dofIndex; }\n\n\t\t\tbool equal(const_iterator const& other) const {\treturn this->_dofIndex == other._dofIndex; }\n\n\t\t\ttypename FEMMeshRectP1Periodic<Dim>::DoFT const dereference() const {\n\t\t\t\treturn _femMesh->dof(_dofIndex);\n\t\t\t}\n\n\t\t\tFEMMeshRectP1Periodic<Dim> const* _femMesh;\n\t\t\tsigned_index_t _dofIndex;\n\t\t};\n\t\ttypedef const_iterator iterator;\n\n\t\titerator begin() const { return iterator(_femMesh, _beginIndex); }\n\t\titerator end() const { return iterator(_femMesh, _endIndex); }\n\t\tconst_iterator cbegin() const { return const_iterator(_femMesh, _beginIndex); }\n\t\tconst_iterator cend() const { return const_iterator(_femMesh, _endIndex); }\n\t};\n\tclass IterateDoFStrided {\n\tprivate:\n\t\tFEMMeshRectP1Periodic<Dim> const& _femMesh;\n\t\tconst index_t _beginIndex;\n\t\tconst index_t _endIndex;\n\t\tconst index_t _stride;\n\tpublic:\n\t\tIterateDoFStrided(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t beginIndex, index_t endIndex, index_t stride) :\n\t\t\t_femMesh(femMesh), _beginIndex(beginIndex), _endIndex(endIndex), _stride(stride) {}\n\n\n\t\tclass const_iterator : public boost::iterator_facade<\n\t\tconst_iterator\n\t\t, typename FEMMeshRectP1Periodic<Dim>::DoFT const\n\t\t, boost::random_access_traversal_tag\n\t\t, typename FEMMeshRectP1Periodic<Dim>::DoFT const\n\t\t, signed_index_t> {\n\t\tpublic:\n\t\t\t//const_iterator() : _element(0), _elementDoFIndex(0) {}\n\t\t\t//explicit const_iterator(Mesh_2DRect const& mesh) : _mesh(mesh), _dofIndex(0) {}\n\t\t\tconst_iterator(FEMMeshRectP1Periodic<Dim> const& femMesh, index_t dofIndex, index_t stride) : _femMesh(&femMesh), _dofBaseIndex(dofIndex/stride), _stride(stride) {}\n\n\t\tprivate:\n\t\t\tfriend class boost::iterator_core_access;\n\n\t\t\tvoid increment() { ++_dofBaseIndex; }\n\t\t\tvoid decrement() { --_dofBaseIndex; }\n\t\t\tvoid advance(signed_index_t n) { _dofBaseIndex+=n; }\n\t\t\tsigned_index_t distance_to(const_iterator const& other) const { return other._dofBaseIndex - this->_dofBaseIndex; }\n\n\t\t\tbool equal(const_iterator const& other) const {\treturn this->_dofBaseIndex == other._dofBaseIndex; }\n\n\t\t\ttypename FEMMeshRectP1Periodic<Dim>::DoFT const dereference() const {\n\t\t\t\treturn _femMesh->dof(_dofBaseIndex*_stride);\n\t\t\t}\n\n\t\t\tFEMMeshRectP1Periodic<Dim> const* _femMesh;\n\t\t\tsigned_index_t _dofBaseIndex;\n\t\t\tsigned_index_t _stride;\n\t\t};\n\t\ttypedef const_iterator iterator;\n\n\t\titerator begin() const { return iterator(_femMesh, _beginIndex, _stride); }\n\t\titerator end() const { return iterator(_femMesh, _endIndex, _stride); }\n\t\tconst_iterator cbegin() const { return const_iterator(_femMesh, _beginIndex, _stride); }\n\t\tconst_iterator cend() const { return const_iterator(_femMesh, _endIndex, _stride); }\n\t};\n\n\n\t/*\n\t * Returns \\prod_{k=1}^n  \\int_0^1 \\tilde{\\phi}_i_k (x_k) * \\tilde{\\phi}_j_k (x_k) dx_k\n\t * Assertion: i and j are *local* DoF Indices (\\in {0,1,2, ..., nDofPerElement()})\n\t */\n\tstatic real integrateReferenceElement(uint i, uint j) {\n\t\tuint iMultiIndex[Dim];\n\t\tuint jMultiIndex[Dim];\n\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tiMultiIndex[Dim-1-k] = i%2;\n\t\t\ti /= 2;\n\t\t\tjMultiIndex[Dim-1-k] = j%2;\n\t\t\tj /= 2;\n\t\t}\n\n\t\tconst real intValue[4] = {1.0/3.0, 1.0/6.0, 1.0/6.0, 1.0/3.0}; // (i_x/y, j_x/y): (0,0), (0,1), (1,0), (1,1)\n\t\treal result = 1.0;\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tresult *= intValue[2*iMultiIndex[k] + jMultiIndex[k]];\n\t\t}\n\t\treturn result;\n\t}\n\n\t/*\n\t * Returns \\prod_{k=1,k!=l}^n  \\int_0^1 \\tilde{\\phi}_i_k (x_k) * \\tilde{\\phi}_j_k (x_k) dx_k *\n\t *         \\int_0^1 (d/dx_l \\tilde{\\phi}_i_l (x_l)) * \\tilde{\\phi}_j_l (x_l) dx\n\t * Assertion: i and j are *local* DoF Indices (\\in {0,1,2, ..., nDofPerElement()})\n\t */\n\tstatic real integratePartIntDerivativeReferenceElement(uint i, uint j, uint derivativeDimension) {\n\t\tuint iMultiIndex[Dim];\n\t\tuint jMultiIndex[Dim];\n\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tiMultiIndex[Dim-1-k] = i%2;\n\t\t\ti /= 2;\n\t\t\tjMultiIndex[Dim-1-k] = j%2;\n\t\t\tj /= 2;\n\t\t}\n\n\t\tconst real intValue[4] = {1.0/3.0, 1.0/6.0, 1.0/6.0, 1.0/3.0}; // (i_x/y, j_x/y): (0,0), (0,1), (1,0), (1,1)\n\t\tconst real intDerivativeXValue[4] = {-0.5, -0.5, 0.5, 0.5}; // (i_x, j_x): (0,0), (0,1), (1,0), (1,1)\n\t\treal result = 1.0;\n\t\tfor(uint k=0; k<Dim; ++k) {\n\t\t\tif(k == derivativeDimension) {\n\t\t\t\tresult *= intDerivativeXValue[2*iMultiIndex[k] + jMultiIndex[k]];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tresult *= intValue[2*iMultiIndex[k] + jMultiIndex[k]];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n};\n\n\n\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1Periodic<Dim>::IterateMeshElements Elements(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1Periodic<Dim>::IterateMeshElements(femMesh, 0, femMesh.nElements());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1Periodic<Dim>::IterateMeshElements LocalElements(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1Periodic<Dim>::IterateMeshElements(femMesh, 0, femMesh.nLocalElements());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1Periodic<Dim>::IterateMeshElements NeighborElements(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1Periodic<Dim>::IterateMeshElements(femMesh, femMesh.nLocalElements(), femMesh.nElements());\n}\n\ntemplate <unsigned int Dim>\nstatic inline UIntRange ElementDoFIndices(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn UIntRange(0, FEMMeshRectP1Periodic<Dim>::nDoFPerElement());\n}\n//template <typename ElemT>\n//static inline typename ElemT::IterateElementDoF ElementDoF(ElemT const& element) {\n//\treturn typename ElemT::IterateElementDoF(element);\n//}\n//template <typename ElemT>\n//static inline typename ElemT::IterateElementDomainBoundaryHypersurfaces DomainBoundaryHypersurfaces(ElemT const& element) {\n//\treturn typename ElemT::IterateElementDomainBoundaryHypersurfaces(element);\n//}\n//template <typename HSurfaceT>\n//static inline typename HSurfaceT::IterateHypersurfaceDoF HypersurfaceDoF(HSurfaceT const& hypersurface) {\n//\treturn typename HSurfaceT::IterateHypersurfaceDoF(hypersurface);\n//}\n\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1Periodic<Dim>::IterateDoF DoF(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1Periodic<Dim>::IterateDoF(femMesh, 0, femMesh.nDoF());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1Periodic<Dim>::IterateDoF LocalDoF(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1Periodic<Dim>::IterateDoF(femMesh, 0, femMesh.nLocalDoF());\n}\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1Periodic<Dim>::IterateDoF GhostDoF(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1Periodic<Dim>::IterateDoF(femMesh, femMesh.nLocalDoF(), femMesh.nDoF());\n}\n\ntemplate <unsigned int Dim>\nstatic inline typename FEMMeshRectP1Periodic<Dim>::IterateDoFStrided BaseLevelDoF(FEMMeshRectP1Periodic<Dim> const& femMesh) {\n\treturn typename FEMMeshRectP1Periodic<Dim>::IterateDoFStrided(femMesh, 0, femMesh.nDoF(), femMesh.dimensions[Dim-1].nNodes);\n}\n\n\n\n\n#endif /* MESH_PERIODIC_HPP_ */\n", "meta": {"hexsha": "1c8ef9c75560361b8e4f6d736524f59fb669fdf1", "size": 37174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pdedsl/mesh_periodic.hpp", "max_stars_repo_name": "cau-se/sprat-pde-dsl", "max_stars_repo_head_hexsha": "15621aaf8b3e78f67f39a7c3c5ae30e02ee7c9ee", "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": "pdedsl/mesh_periodic.hpp", "max_issues_repo_name": "cau-se/sprat-pde-dsl", "max_issues_repo_head_hexsha": "15621aaf8b3e78f67f39a7c3c5ae30e02ee7c9ee", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdedsl/mesh_periodic.hpp", "max_forks_repo_name": "cau-se/sprat-pde-dsl", "max_forks_repo_head_hexsha": "15621aaf8b3e78f67f39a7c3c5ae30e02ee7c9ee", "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.3567467652, "max_line_length": 184, "alphanum_fraction": 0.7088556518, "num_tokens": 11217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.04023794118495175, "lm_q1q2_score": 0.017772012424914066}}
{"text": "/*    Copyright (c) 2010-2018, 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#include <boost/bind.hpp>\r\n\r\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createRadiationPressureInterface.h\"\r\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/sphericalBodyShapeModel.h\"\r\n#include \"Tudat/Astrodynamics/ReferenceFrames/referenceFrameTransformations.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace simulation_setup\r\n{\r\n\r\n//! Function to obtain (by reference) the position functions and radii of occulting bodies\r\nvoid getOccultingBodiesInformation(\r\n        const NamedBodyMap& bodyMap, const std::vector< std::string >& occultingBodies,\r\n        std::vector< std::function< Eigen::Vector3d( ) > >& occultingBodyPositions,\r\n        std::vector< double >& occultingBodyRadii )\r\n{\r\n    // Iterate over occulring bodies and retrieve radius and position function.\r\n    for( unsigned int i = 0; i < occultingBodies.size( ); i++ )\r\n    {\r\n        if( bodyMap.count( occultingBodies[ i ] ) == 0 )\r\n        {\r\n           throw std::runtime_error( \"Error, could not find body \" + occultingBodies[ i ] +\r\n                                     \" in body map when making occulting body settings\" );\r\n        }\r\n        else\r\n        {\r\n            std::shared_ptr< basic_astrodynamics::BodyShapeModel > shapeModel =\r\n                    bodyMap.at( occultingBodies.at( i ) )->getShapeModel( );\r\n            if( shapeModel == nullptr )\r\n            {\r\n                throw std::runtime_error( \"Error, no shape model for \" + occultingBodies[ i ] +\r\n                                          \" when making occulting body settings\" );\r\n            }\r\n            occultingBodyPositions.push_back(\r\n                        std::bind( &Body::getPosition, bodyMap.at( occultingBodies[ i ] ) ) );\r\n            occultingBodyRadii.push_back( shapeModel->getAverageRadius( ) );\r\n        }\r\n    }\r\n}\r\n\r\n//! Function to create a radiation pressure interface.\r\nstd::shared_ptr< electro_magnetism::RadiationPressureInterface > createRadiationPressureInterface(\r\n        const std::shared_ptr< RadiationPressureInterfaceSettings > radiationPressureInterfaceSettings,\r\n        const std::string& bodyName, const NamedBodyMap& bodyMap )\r\n{\r\n    std::shared_ptr< electro_magnetism::RadiationPressureInterface > radiationPressureInterface;\r\n\r\n    // Check type of radiation pressure interface\r\n    switch( radiationPressureInterfaceSettings->getRadiationPressureType( ) )\r\n    {\r\n    case cannon_ball:\r\n    {\r\n        // Check type consistency.\r\n        std::shared_ptr< CannonBallRadiationPressureInterfaceSettings > cannonBallSettings =\r\n                std::dynamic_pointer_cast< CannonBallRadiationPressureInterfaceSettings >(\r\n                    radiationPressureInterfaceSettings );\r\n        if( cannonBallSettings == nullptr )\r\n        {\r\n            throw std::runtime_error( \"Error when making cannon ball radiation interface, type does not match object\" );\r\n        }\r\n\r\n        // Retrieve source body and check consistency.\r\n        if( bodyMap.count( radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\r\n        {\r\n            throw std::runtime_error( \"Error when making cannon ball radiation interface, source not found.\");\r\n        }\r\n\r\n        std::shared_ptr< Body > sourceBody =\r\n                bodyMap.at( radiationPressureInterfaceSettings->getSourceBody( ) );\r\n\r\n        // Get reqruied data for occulting bodies.\r\n        std::vector< std::string > occultingBodies = cannonBallSettings->getOccultingBodies( );\r\n        std::vector< std::function< Eigen::Vector3d( ) > > occultingBodyPositions;\r\n        std::vector< double > occultingBodyRadii;\r\n        getOccultingBodiesInformation(\r\n                    bodyMap, occultingBodies, occultingBodyPositions, occultingBodyRadii );\r\n\r\n        // Retrive radius of source if occultations are used.\r\n        double sourceRadius;\r\n        if( occultingBodyPositions.size( ) > 0 )\r\n        {\r\n            std::shared_ptr< basic_astrodynamics::BodyShapeModel > sourceShapeModel =\r\n                    sourceBody->getShapeModel( );\r\n\r\n            if( sourceShapeModel == nullptr )\r\n            {\r\n                throw std::runtime_error( \"Error when making occulted body, source body \" +\r\n                                          radiationPressureInterfaceSettings->getSourceBody( ) +\r\n                                          \" does not have a shape\" );\r\n            }\r\n            else\r\n            {\r\n                sourceRadius = sourceShapeModel->getAverageRadius( );\r\n            }\r\n        }\r\n        else\r\n        {\r\n            sourceRadius = 0.0;\r\n        }\r\n\r\n        // Create function returning radiated power.\r\n        std::function< double( ) > radiatedPowerFunction;\r\n        if( defaultRadiatedPowerValues.count(\r\n                    radiationPressureInterfaceSettings->getSourceBody( ) ) == 0 )\r\n        {\r\n            throw std::runtime_error( \"Error, no radiated power found for \" +\r\n                                      radiationPressureInterfaceSettings->getSourceBody( ) );\r\n        }\r\n        else\r\n        {\r\n            radiatedPowerFunction = [ = ]( ){ return\r\n                        defaultRadiatedPowerValues.at(\r\n                            radiationPressureInterfaceSettings->getSourceBody( ) ); };\r\n        }\r\n\r\n        // Create radiation pressure interface.\r\n        radiationPressureInterface =\r\n                std::make_shared< electro_magnetism::RadiationPressureInterface >(\r\n                    radiatedPowerFunction,\r\n                    std::bind( &Body::getPosition, sourceBody ),\r\n                    std::bind( &Body::getPosition, bodyMap.at( bodyName ) ),\r\n                    cannonBallSettings->getRadiationPressureCoefficient( ),\r\n                    cannonBallSettings->getArea( ), occultingBodyPositions, occultingBodyRadii,\r\n                    sourceRadius );\r\n        break;\r\n\r\n    }\r\n    default:\r\n        throw std::runtime_error(\r\n                    \"Error, radiation pressure type\" + std::to_string(\r\n                        radiationPressureInterfaceSettings->getRadiationPressureType( ) ) +\r\n                    \"not recognized for body\" + bodyName );\r\n    }\r\n\r\n    return radiationPressureInterface;\r\n}\r\n\r\n} // namespace simulation_setup\r\n\r\n} // namespace tudat\r\n", "meta": {"hexsha": "e7b5dbd18406697ae841a83b492307cf5843f6e6", "size": 6623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createRadiationPressureInterface.cpp", "max_stars_repo_name": "different91988/tudat", "max_stars_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "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/createRadiationPressureInterface.cpp", "max_issues_repo_name": "different91988/tudat", "max_issues_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/createRadiationPressureInterface.cpp", "max_forks_repo_name": "different91988/tudat", "max_forks_repo_head_hexsha": "97b287fe759979cf2028c9180f0abafa2487dde4", "max_forks_repo_licenses": ["BSD-3-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.2875816993, "max_line_length": 121, "alphanum_fraction": 0.6059187679, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.044018654722629766, "lm_q1q2_score": 0.017764469360545276}}
{"text": "#ifndef LUNAR_TYPE_HPP\n#define LUNAR_TYPE_HPP\n\n#include \"lunar_common.hpp\"\n#include \"lunar_parser.hpp\"\n\n#include <assert.h>\n\n#include <map>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/bimap/bimap.hpp>\n#include <boost/bimap/unordered_set_of.hpp>\n\n#include <boost/multi_index/hashed_index.hpp>\n#include <boost/multi_index/member.hpp>\n#include <boost/multi_index/random_access_index.hpp>\n#include <boost/multi_index_container.hpp>\n\nnamespace lunar {\n\nstruct type_id {\n    std::string m_path;\n    std::string m_id;\n\n    void print() const {\n        std::cout << \"{\\\"path\\\":\\\"\" << m_path << \"\\\",\\\"id\\\":\\\"\" << m_id\n                  << \"\\\"}\";\n    }\n\n    bool operator==(const type_id &rhs) const {\n        return m_path == rhs.m_path && m_id == rhs.m_id;\n    }\n\n    bool operator!=(const type_id &rhs) const { return !(*this == rhs); }\n};\n\n} // namespace lunar\n\nnamespace std {\n\ntemplate <> struct std::hash<lunar::type_id> {\n  public:\n    size_t operator()(const lunar::type_id &data) const {\n        std::size_t seed = 0;\n        boost::hash_combine(seed, data.m_path);\n        boost::hash_combine(seed, data.m_id);\n        return seed;\n    }\n};\n\n} // namespace std\n\nnamespace lunar {\n\nstruct ast;\nstruct ast_kind;\nstruct ast_type;\nstruct ast_class;\nstruct ast_instance;\nstruct ast_pred;\nstruct ast_defun;\nstruct ast_interface;\nstruct ast_expr;\nstruct ast_expr_id;\nstruct ast_binexpr;\nstruct ast_userdef;\nclass module;\nclass parser;\nclass pred;\nclass defun;\n\nclass substitution;\n\n// a kind is the type of a type constructor or a higher order type operator\n// e.g.\n//   *\n//   * -> *\n//   * -> (* -> *)\nclass kind {\n  public:\n    kind() {}\n    virtual ~kind(){};\n\n    static uint16_t num_args(const ast_kind *ptr);\n\n    virtual void print() = 0;\n    virtual std::string to_str() = 0;\n\n    bool m_is_star;\n};\n\ntypedef std::shared_ptr<kind> shared_kind;\n\n// normal type\nclass star : public kind {\n  public:\n    star() { m_is_star = true; }\n    virtual ~star() {}\n    virtual void print() { std::cout << \"*\"; }\n    virtual std::string to_str() { return \"*\"; }\n};\n\ntypedef std::shared_ptr<star> shared_star;\n\n// higher order type\nclass kfun : public kind {\n  public:\n    kfun() { m_is_star = false; }\n    virtual ~kfun() {}\n\n    virtual void print() {\n        m_left->print();\n        std::cout << \" -> \";\n        m_right->print();\n    }\n\n    virtual std::string to_str() {\n        auto left = m_left->to_str();\n        auto right = m_right->to_str();\n        return left + \" -> \" + right;\n    }\n\n    shared_kind m_left;\n    shared_kind m_right;\n};\n\ntypedef std::shared_ptr<kfun> shared_kfun;\n\nint cmp_kind(const kind *lhs, const kind *rhs);\n\n// type\nclass type {\n  public:\n    type() {}\n    virtual ~type(){};\n\n    virtual void print() = 0;\n    virtual std::string to_str() = 0;\n\n    enum subtype {\n        TYPE_CONST, // constant type\n        TYPE_VAR,   // type variable\n        TYPE_APP,   // higher order type application\n    };\n\n    subtype m_subtype;\n\n    static std::shared_ptr<type> make(const module *ptr_mod,\n                                      const ast_type *ptr);\n\n    virtual shared_kind get_kind() const = 0;\n};\n\ntypedef std::shared_ptr<type> shared_type;\n\nbool eq_type(type *lhs, type *rhs);\n\n// constant type\n// e.g.\n//   num : *\n//   vec : * -> *\nclass type_const : public type {\n  public:\n    virtual ~type_const() {}\n    virtual void print();\n    virtual std::string to_str();\n\n    bool operator==(const type_const &lhs) const {\n        return m_id == lhs.m_id &&\n               cmp_kind(m_kind.get(), lhs.m_kind.get()) == 0;\n    }\n\n    bool operator!=(const type_const &lhs) const { return !(*this == lhs); }\n\n    virtual shared_kind get_kind() const { return m_kind; }\n    const type_id &get_id() { return m_id; }\n\n    // id: type name\n    // numtargs: the number of type arguments\n    static shared_type make(const type_id &id, unsigned int numtargs);\n\n  protected:\n    type_const() { m_subtype = TYPE_CONST; }\n    type_id m_id; // identifier of type (e.g. num, bool)\n    shared_kind m_kind;\n};\n\ntypedef std::shared_ptr<type_const> shared_type_const;\n\n// type variable\nclass type_var : public type {\n  public:\n    type_var(const std::string &id, shared_kind k) : m_id(id), m_kind(k) {\n        m_subtype = TYPE_VAR;\n    }\n    virtual ~type_var() {}\n\n    bool operator==(const type_var &lhs) const {\n        return m_id == lhs.m_id &&\n               cmp_kind(m_kind.get(), lhs.m_kind.get()) == 0;\n    }\n\n    bool operator!=(const type_var &lhs) const { return !(*this == lhs); }\n\n    bool operator<(const type_var &lhs) const {\n        int ret = m_id.compare(lhs.m_id);\n        if (ret == 0)\n            ret = cmp_kind(m_kind.get(), lhs.m_kind.get());\n        return ret > 0 ? true : false;\n    }\n\n    virtual shared_kind get_kind() const { return m_kind; }\n    const std::string &get_id() const { return m_id; }\n    void set_id(const std::string &s) { m_id = s; }\n\n    // id: type variable name\n    static shared_type make(const std::string &id, unsigned int numtargs);\n\n    // id: type variable name, k: kind\n    static shared_type make(const std::string &id, shared_kind k) {\n        auto ret = std::shared_ptr<type_var>(new type_var);\n        ret->m_id = id;\n        ret->m_kind = k;\n        return ret;\n    }\n\n    virtual void print();\n    virtual std::string to_str();\n\n  private:\n    type_var() { m_subtype = TYPE_VAR; }\n    std::string m_id; // type variable name\n    shared_kind m_kind;\n};\n\ntypedef std::shared_ptr<type_var> shared_type_var;\n\n// application of higher order type\n// e.g. (1)\n//   struct dict<T1, T2> {...} is denoted as * -> (* -> *)\n//   dict<int> is denoted as\n//     tapp1.left  = * -> (* -> *)\n//     tapp1.right = *\n//   dict<int, bool> is denoted as\n//     tapp2.left  = tapp1\n//     type2.right = *\n//\n// e.g. (2)\n//   struct somedata<T1, T2, T3> {...}\n//   somedata<int>\n//     tapp1.left  = * -> (* -> (* -> *))\n//     tapp1.right = *\n//   somedata<int, int>\n//     tapp2.left  = tapp1\n//     tapp2.right = *\n//   somedata<int, int, int>\n//     tapp3.left  = tapp2\n//     tapp3.right = *\nclass type_app : public type {\n  public:\n    virtual ~type_app() {}\n\n    bool operator==(const type_app &lhs) const {\n        return eq_type(m_left.get(), m_right.get()) &&\n               eq_type(lhs.m_left.get(), lhs.m_right.get());\n    }\n\n    // e.g.\n    // if\n    //   left:  * -> (* -> *)\n    //   right: *\n    // then output\n    //   * -> *\n    virtual shared_kind get_kind() const {\n        auto k = m_left->get_kind();\n        assert(!k->m_is_star);\n\n        auto kf = std::static_pointer_cast<kfun>(k);\n\n        return kf->m_right;\n    }\n    static shared_type make(shared_type lhs, shared_type rhs);\n\n    // require\n    //   m_left->get_kind()->m_left == m_right->get_kind()\n    //   m_right->get_kind() == *\n    shared_type m_left;\n    shared_type m_right;\n\n    virtual void print();\n    virtual std::string to_str();\n    std::string to_str(bool is_top);\n\n  private:\n    type_app() { m_subtype = TYPE_APP; }\n};\n\ntypedef std::unique_ptr<pred> uniq_pred;\n\n// substitution from (id, kind) to type\n// type variable -> type\n// e.g.\n//   substitution:\n//     {(`a : *) -> int}\n//   apply:\n//     {(`a : *) -> int} `a : * -> int\n//   composition:\n//     {`b : * -> int} {(`a : *) -> vec (`b : *)} -> {(`a : *) -> vec int}\nclass substitution {\n  public:\n    substitution() {}\n    virtual ~substitution() {}\n\n    // substitute type variables in the argument\n    shared_type apply(shared_type type);\n    uniq_pred apply(pred *p);\n\n    std::map<type_var, shared_type> m_subst;\n};\n\ntypedef std::unique_ptr<substitution> uniq_subst;\n\n// a predicate asserts that m_types are members of a class named m_id\n// e.g.\n//   num<`a>: class name = num, m_args = [`a]\n//   ClassA<`a, `b>: class name = ClassA, m_args = [`a, `b]\nclass pred {\n  public:\n    pred() {}\n    virtual ~pred() {}\n\n    void print();\n    std::string to_str() { return m_id.m_id + \"<\" + m_arg->to_str() + \">\"; }\n\n    static uniq_pred make(const module *ptr_mod, const ast_pred *ptr);\n\n    bool operator==(const pred &rhs) const {\n        if (m_id != rhs.m_id)\n            return false;\n\n        return eq_type(m_arg.get(), rhs.m_arg.get());\n    }\n\n    bool in_hnf() { return hnf(m_arg.get()); }\n\n    bool is_head_var(const std::string &arg) {\n        return head_var(m_arg.get(), arg);\n    }\n\n    type_id m_id; // class name_id\n    shared_type m_arg;\n\n  private:\n    static bool hnf(type *p) {\n        switch (p->m_subtype) {\n        case type::TYPE_VAR:\n            return true;\n        case type::TYPE_APP: {\n            auto ap = (type_app *)p;\n            return hnf(ap->m_left.get());\n        }\n        case type::TYPE_CONST:\n            return false;\n        }\n    }\n\n    static bool head_var(type *p, const std::string &arg) {\n        switch (p->m_subtype) {\n        case type::TYPE_VAR: {\n            auto tv = (type_var *)p;\n            if (arg == tv->get_id())\n                return true;\n            else\n                return false;\n        }\n        case type::TYPE_APP: {\n            auto ap = (type_app *)p;\n            return head_var(ap->m_left.get(), arg);\n        }\n        case type::TYPE_CONST:\n            return false;\n        }\n    }\n};\n\ntypedef boost::bimaps::bimap<boost::bimaps::unordered_set_of<std::string>,\n                             boost::bimaps::unordered_set_of<std::string>>\n    bimap_ss;\n\n// qualified type\n// e.g.\n//   qualified class declaration:\n//     class ord<`a> require eq<`a>\n//   qualified class instance:\n//     inst ord<either `a> require ord<'a>\n//   qualified type declaration:\n//     fn myfun (x : `a, y : `b) : `a require num<`a>, bool<`b>\n//     struct data<`a, `b> require num<`a>, bool<`b>\nclass qual {\n  public:\n    qual() : m_parent(nullptr) {}\n    virtual ~qual() {}\n\n    void print_preds();\n\n    std::vector<uniq_pred> m_preds; // require\n\n    // de Bruijn index <-> original type variable\n    bimap_ss m_idx_tvar;\n\n    const ast *m_ast;\n    const module *m_module;\n    const qual *m_parent;\n\n    std::vector<shared_type> m_tvar_constraint; // type variable constraint\n\n    bool check_kind_constraint(const std::string &id, kind *k, bool &found);\n    bool add_constraints(pred *p);\n    bool add_constraints(type *p);\n    std::string\n\n    // find oritinal type variable from de Bruijn index\n    // id: de Bruijn index\n    // if found this returns original type variable name,\n    // otherwise returns \"\"\n    find_tvar_idx(const std::string &id) const;\n};\n\n// qualified type\n// function, struct, or union types are denoted by this class\nclass qual_type : public qual {\n  public:\n    qual_type() {}\n    virtual ~qual_type() {}\n\n    shared_type m_type;\n};\n\ntypedef std::unique_ptr<qual_type> ptr_qual_type;\n\n// class declaration\nclass typeclass : public qual {\n  public:\n    enum ASYCLIC {\n        ASYCLIC_NONE,\n        ASYCLIC_YES,\n        ASYCLIC_NO,\n    };\n    typeclass() : m_is_asyclic(ASYCLIC_NONE) {}\n    virtual ~typeclass() {}\n\n    void print();\n\n    type_id m_id; // class name\n\n    std::string m_arg;                                  // arguments\n    std::unordered_map<type_id, ptr_qual_type> m_funcs; // interfaces\n\n    ASYCLIC m_is_asyclic;\n\n    bool apply_super(shared_type arg, std::vector<uniq_pred> &ret,\n                     const module *ptr_mod, const ast *ptr_ast);\n    bool add_interface(const module *ptr_mod, const std::string &id,\n                       ast_interface *ptr_ast);\n\n  private:\n    shared_type make_funtype(const module *ptr_mod, ast_interface *ptr_ast);\n};\n\ntypedef std::unique_ptr<typeclass> uniq_typeclass;\n\nclass defun : public qual {\n  public:\n    defun() {}\n    virtual ~defun() {}\n\n    void print();\n\n    static std::unique_ptr<defun>\n    make(const module *ptr_mod, const qual *parent, const ast_defun *ast);\n\n    shared_type m_type;\n    std::vector<std::pair<std::string, shared_type>> m_args;\n    shared_type m_ret;\n    std::unordered_map<std::string, shared_type> m_assump;\n};\n\ntypedef std::unique_ptr<defun> ptr_defun;\n\n// class instance declaration\nclass inst : public qual {\n  public:\n    inst() {}\n    virtual ~inst() {}\n\n    void print();\n\n    pred m_pred;\n    std::unordered_map<std::string, ptr_defun> m_funcs; // interfaces\n};\n\ntypedef std::unique_ptr<inst> uniq_inst;\n\nclass classenv {\n  public:\n    classenv() {}\n    virtual ~classenv() {}\n\n    static std::unique_ptr<classenv> make(const parser &ps);\n\n    void print();\n\n  private:\n    struct env {\n        uniq_typeclass m_class; // class declaration\n\n        // multiply defined instances are prohibited\n        // 0 <= i, j < m_insts.size()\n        // s: substitution (mgu)\n        // ∀i ∀j ∃s (s m_insts[i].m_args = s m_insts[j].m_args) -> error\n        std::vector<uniq_inst> m_insts; // instance declarations\n    };\n\n    typedef std::unique_ptr<env> ptr_env;\n\n    // class name -> (class declarations, class instance declarations)\n    std::unordered_map<type_id, ptr_env> m_env;\n\n    // function name -> class name\n    std::unordered_map<type_id, std::string> m_func2class;\n\n    bool add_class(const module *ptr_mod, const ast_class *ptr);\n    bool add_instance(const module *ptr_mod, const ast_instance *ptr_ast);\n    bool is_inherit_instance(const pred &p, const module *ptr_mod,\n                             const ast *ptr_ast);\n    inst *overlap(pred &ptr);\n    bool is_asyclic();\n    bool is_asyclic(const module *ptr_mod, typeclass *ptr,\n                    std::unordered_set<type_id> &visited);\n\n    bool by_super(pred *pd, std::vector<uniq_pred> &ret);\n    void by_inst(pred *pd, std::vector<uniq_pred> &ret);\n    TRIVAL entail(std::vector<uniq_pred> &ps, pred *pd);\n    bool to_hnfs(std::vector<uniq_pred> &ps, std::vector<uniq_pred> &ret,\n                 int &idx);\n    bool to_hnf(uniq_pred pd, std::vector<uniq_pred> &ret);\n    bool simplify(std::vector<uniq_pred> &ps);\n    bool reduce(std::vector<uniq_pred> &ps, int &idx);\n    bool check_ifs_type(); // check type of interfaces\n    uniq_subst mgu_if_type(typeclass *cls, inst *in, const std::string &id,\n                           defun *qt);\n};\n\nclass funcenv {\n  public:\n    funcenv() {}\n    virtual ~funcenv() {}\n\n    void print();\n\n    static std::unique_ptr<funcenv> make(const parser &ps);\n\n    friend class type_infer;\n    friend bool typing(classenv &cenv, funcenv &fenv);\n\n  private:\n    std::unordered_map<type_id, ptr_defun> m_defuns;\n};\n\nnamespace mi = boost::multi_index;\n\nclass typeenv {\n  public:\n    typeenv() {}\n    virtual ~typeenv() {}\n\n    void print();\n\n    static std::unique_ptr<typeenv> make(const parser &ps);\n\n    friend class type_infer;\n    friend bool typing(classenv &cenv, funcenv &fenv);\n\n    struct memv {\n        std::string m_id;\n        mutable shared_type m_type;\n\n        memv(const std::string &id, shared_type t) : m_id(id), m_type(t) {}\n    };\n\n  private:\n    struct hashmap {};\n    struct seq {};\n\n    typedef mi::multi_index_container<\n        memv, mi::indexed_by<\n                  mi::hashed_unique<mi::tag<hashmap>,\n                                    mi::member<memv, std::string, &memv::m_id>>,\n                  mi::random_access<mi::tag<seq>>>>\n        dict_mem;\n\n    struct typeinfo {\n        qual_type m_type;\n        std::vector<shared_type> m_args;\n        dict_mem m_members;\n        bool m_is_struct;\n        const ast_type *m_ast;\n        const module *m_module;\n    };\n\n    static bool check_tvar(type *ptr,\n                           const std::unordered_set<std::string> &tvars);\n    static std::shared_ptr<typeinfo> make_typeinfo(const module *ptr_mod,\n                                                   const ast_userdef *ptr_ast);\n\n    // return true if info is not recursively defined\n    bool check_recursive(const typeinfo &info,\n                         std::unordered_set<type_id> &used);\n\n    // return true if ptr was checked whether it is not defined recursively\n    bool is_rec_checked(const type_id &id, shared_type ptr);\n\n    std::unordered_map<type_id, std::shared_ptr<typeinfo>> m_types;\n    std::unordered_multimap<type_id, shared_type> m_rec_checked;\n};\n\nclass type_infer {\n  public:\n    type_infer(defun &fun, classenv &cenv, funcenv &fenv);\n    virtual ~type_infer() {}\n\n    bool typing();\n\n  private:\n    defun &m_defun;\n    classenv &m_classenv;\n    funcenv &m_funcenv;\n    shared_type m_type;\n    shared_type m_ret;\n    std::vector<uniq_pred> m_preds;\n    uniq_subst m_sbst;\n    ast_defun *m_ast;\n    uint64_t m_de_bruijn_idx;\n\n    // assumpsion: variable names to types\n    std::unordered_map<std::string, std::vector<shared_type>> m_assump;\n\n    // constraints of kind\n    std::unordered_map<std::string, shared_kind> m_tvar_constraint;\n\n    // variable names in function\n    // storead variable name as de Bruijn index\n    std::vector<std::vector<std::string>> m_block_ids;\n\n    // variable names in current scope\n    // storead variable name as de Bruijn index\n    std::vector<std::vector<std::string>>::reverse_iterator m_ids;\n\n    // de Bruijn index to original variable name\n    std::unordered_map<std::string, std::string> m_idx2name;\n\n    // original variable name to de Bruijn index\n    std::unordered_map<std::string, std::vector<std::string>> m_name2idx;\n\n    shared_type typing(ast_expr *expr);\n    shared_type typing_id(ast_expr_id *expr);\n    shared_type typing_dotexpr(ast_binexpr *expr);\n    shared_type typing_dotexpr(ast_expr *expr, std::list<std::string> &ids);\n\n    // generate de Bruijn index for var, and returned the generated index\n    std::string gensym_for(const std::string &var);\n\n    // return de Bruijn index of var\n    // if no variable name is found, return \"\"\n    std::string name2idx(const std::string &var);\n\n    void pop_variables();\n};\n\nbool typing(classenv &cenv, funcenv &fenv);\n\n} // namespace lunar\n\n#endif // LUNAR_TYPE_HPP", "meta": {"hexsha": "c284c1f8154492ba1bf853424d8fdd124ee33023", "size": 17741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lunar_type.hpp", "max_stars_repo_name": "ytakano/lunarlang", "max_stars_repo_head_hexsha": "22ed8399678ba8414d14fa4c189276c5424644ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-26T06:10:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-26T06:10:53.000Z", "max_issues_repo_path": "src/lunar_type.hpp", "max_issues_repo_name": "ytakano/lunarlang", "max_issues_repo_head_hexsha": "22ed8399678ba8414d14fa4c189276c5424644ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lunar_type.hpp", "max_forks_repo_name": "ytakano/lunarlang", "max_forks_repo_head_hexsha": "22ed8399678ba8414d14fa4c189276c5424644ab", "max_forks_repo_licenses": ["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.7863372093, "max_line_length": 80, "alphanum_fraction": 0.6118031678, "num_tokens": 4676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.04401864782501478, "lm_q1q2_score": 0.017764467208426702}}
{"text": "/**\n *  This file is part of dvo.\n *\n *  Copyright 2012 Christian Kerl <christian.kerl@in.tum.de> (Technical University of Munich)\n *  For more information see <http://vision.in.tum.de/data/software/dvo>.\n *\n *  dvo 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 *  dvo 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 dvo.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <dvo/core/rgbd_image.h>\n\n#include <assert.h>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include <dvo/core/interpolation.h>\n\n//#include \"../util.h\"\n//#include \"../stopwatch.h\"\n\nnamespace dvo\n{\nnamespace core\n{\n\ntemplate<typename T>\nstatic void pyrDownMeanSmooth(const cv::Mat& in, cv::Mat& out)\n{\n  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());\n\n  for(int y = 0; y < out.rows; ++y)\n  {\n    for(int x = 0; x < out.cols; ++x)\n    {\n      int x0 = x * 2;\n      int x1 = x0 + 1;\n      int y0 = y * 2;\n      int y1 = y0 + 1;\n\n      out.at<T>(y, x) = (T) ( (in.at<T>(y0, x0) + in.at<T>(y0, x1) + in.at<T>(y1, x0) + in.at<T>(y1, x1)) / 4.0f );\n    }\n  }\n}\n\ntemplate<typename T>\nstatic void pyrDownMeanSmoothIgnoreInvalid(const cv::Mat& in, cv::Mat& out)\n{\n  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());\n\n  for(int y = 0; y < out.rows; ++y)\n  {\n    for(int x = 0; x < out.cols; ++x)\n    {\n      int x0 = x * 2;\n      int x1 = x0 + 1;\n      int y0 = y * 2;\n      int y1 = y0 + 1;\n\n      T total = 0;\n      int cnt = 0;\n\n      if(std::isfinite(in.at<T>(y0, x0)))\n      {\n        total += in.at<T>(y0, x0);\n        cnt++;\n      }\n\n      if(std::isfinite(in.at<T>(y0, x1)))\n      {\n        total += in.at<T>(y0, x1);\n        cnt++;\n      }\n\n      if(std::isfinite(in.at<T>(y1, x0)))\n      {\n        total += in.at<T>(y1, x0);\n        cnt++;\n      }\n\n      if(std::isfinite(in.at<T>(y1, x1)))\n      {\n        total += in.at<T>(y1, x1);\n        cnt++;\n      }\n\n      if(cnt > 0)\n      {\n        out.at<T>(y, x) = (T) ( total / cnt );\n      }\n      else\n      {\n        out.at<T>(y, x) = InvalidDepth;\n      }\n    }\n  }\n}\n\ntemplate<typename T>\nstatic void pyrDownMedianSmooth(const cv::Mat& in, cv::Mat& out)\n{\n  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());\n\n  cv::Mat in_smoothed;\n  cv::medianBlur(in, in_smoothed, 3);\n\n  for(int y = 0; y < out.rows; ++y)\n  {\n    for(int x = 0; x < out.cols; ++x)\n    {\n      out.at<T>(y, x) = in_smoothed.at<T>(y * 2, x * 2);\n    }\n  }\n}\n\ntemplate<typename T>\nstatic void pyrDownSubsample(const cv::Mat& in, cv::Mat& out)\n{\n  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());\n\n  for(int y = 0; y < out.rows; ++y)\n  {\n    for(int x = 0; x < out.cols; ++x)\n    {\n      out.at<T>(y, x) = in.at<T>(y * 2, x * 2);\n    }\n  }\n}\n\nRgbdImagePyramid::RgbdImagePyramid(RgbdCameraPyramid& camera, const cv::Mat& intensity, const cv::Mat& depth) :\n    camera_(camera)\n{\n  levels_.push_back(camera_.level(0).create(intensity, depth));\n}\n\nRgbdImagePyramid::~RgbdImagePyramid()\n{\n}\n\nvoid RgbdImagePyramid::compute(const size_t num_levels)\n{\n  build(num_levels);\n}\n\nvoid RgbdImagePyramid::build(const size_t num_levels)\n{\n  if(levels_.size() >= num_levels) return;\n\n  // if we already have some levels, we just need to compute the coarser levels\n  size_t first = levels_.size();\n\n  for(size_t idx = first; idx < num_levels; ++idx)\n  {\n    levels_.push_back(camera_.level(idx).create());\n\n    pyrDownMeanSmooth<IntensityType>(levels_[idx - 1]->intensity, levels_[idx]->intensity);\n    //pyrDownMeanSmoothIgnoreInvalid<float>(levels[idx - 1].depth, levels[idx].depth);\n    pyrDownSubsample<float>(levels_[idx - 1]->depth, levels_[idx]->depth);\n    levels_[idx]->initialize();\n  }\n}\n\nRgbdImage& RgbdImagePyramid::level(size_t idx)\n{\n  assert(idx < levels_.size());\n\n  return *levels_[idx];\n}\n\ndouble RgbdImagePyramid::timestamp() const\n{\n  return !levels_.empty() ? levels_[0]->timestamp: 0.0;\n}\n\nRgbdCamera::RgbdCamera(size_t width, size_t height, const IntrinsicMatrix& intrinsics) :\n    width_(width),\n    height_(height),\n    intrinsics_(intrinsics)\n{\n  pointcloud_template_.resize(Eigen::NoChange, width_ * height_);\n  int idx = 0;\n\n  for(size_t y = 0; y < height_; ++y)\n  {\n    for(size_t x = 0; x < width_; ++x, ++idx)\n    {\n      pointcloud_template_(0, idx) = (x - intrinsics_.ox()) / intrinsics_.fx();\n      pointcloud_template_(1, idx) = (y - intrinsics_.oy()) / intrinsics_.fy();\n      pointcloud_template_(2, idx) = 1.0;\n      pointcloud_template_(3, idx) = 0.0;\n    }\n  }\n}\n\nRgbdCamera::~RgbdCamera()\n{\n}\n\nsize_t RgbdCamera::width() const\n{\n  return width_;\n}\n\nsize_t RgbdCamera::height() const\n{\n  return height_;\n}\n\nconst dvo::core::IntrinsicMatrix& RgbdCamera::intrinsics() const\n{\n  return intrinsics_;\n}\n\nRgbdImagePtr RgbdCamera::create(const cv::Mat& intensity, const cv::Mat& depth) const\n{\n  RgbdImagePtr result(new RgbdImage(*this));\n  result->intensity = intensity;\n  result->depth = depth;\n  result->initialize();\n\n  return result;\n}\n\nRgbdImagePtr RgbdCamera::create() const\n{\n  return boost::make_shared<RgbdImage>(*this);\n}\n\nbool RgbdCamera::hasSameSize(const cv::Mat& img) const\n{\n  return img.cols == width_ && img.rows == height_;\n}\n\nvoid RgbdCamera::buildPointCloud(const cv::Mat &depth, PointCloud& pointcloud) const\n{\n  assert(hasSameSize(depth));\n\n  pointcloud.resize(Eigen::NoChange, width_ * height_);\n\n  const float* depth_ptr = depth.ptr<float>();\n  int idx = 0;\n\n  for(size_t y = 0; y < height_; ++y)\n  {\n    for(size_t x = 0; x < width_; ++x, ++depth_ptr, ++idx)\n    {\n      pointcloud.col(idx) = pointcloud_template_.col(idx) * (*depth_ptr);\n      pointcloud(3, idx) = 1.0;\n    }\n  }\n}\n\nRgbdCameraPyramid::RgbdCameraPyramid(const RgbdCamera& base)\n{\n  levels_.push_back(boost::make_shared<RgbdCamera>(base));\n}\n\nRgbdCameraPyramid::RgbdCameraPyramid(size_t base_width, size_t base_height, const dvo::core::IntrinsicMatrix& base_intrinsics)\n{\n  levels_.push_back(boost::make_shared<RgbdCamera>(base_width, base_height, base_intrinsics));\n}\n\nRgbdCameraPyramid::~RgbdCameraPyramid()\n{\n}\n\nRgbdImagePyramidPtr RgbdCameraPyramid::create(const cv::Mat& base_intensity, const cv::Mat& base_depth)\n{\n  return RgbdImagePyramidPtr(new RgbdImagePyramid(*this, base_intensity, base_depth));\n}\n\nvoid RgbdCameraPyramid::build(size_t levels)\n{\n  size_t start = levels_.size();\n\n  for(size_t idx = start; idx < levels; ++idx)\n  {\n    RgbdCameraPtr& previous = levels_[idx - 1];\n\n    dvo::core::IntrinsicMatrix intrinsics(previous->intrinsics());\n    intrinsics.scale(0.5f);\n\n    levels_.push_back(boost::make_shared<RgbdCamera>(previous->width() / 2, previous->height() / 2, intrinsics));\n  }\n}\n\nconst RgbdCamera& RgbdCameraPyramid::level(size_t level)\n{\n  build(level + 1);\n\n  return *levels_[level];\n}\n\nconst RgbdCamera& RgbdCameraPyramid::level(size_t level) const\n{\n  return *levels_[level];\n}\n/*\nRgbdImage::RgbdImage() :\n  camera_(0),\n  intensity_requires_calculation_(true),\n  depth_requires_calculation_(true),\n  pointcloud_requires_build_(true),\n  width(0),\n  height(0)\n{\n}\n*/\nRgbdImage::RgbdImage(const RgbdCamera& camera) :\n  camera_(camera),\n  intensity_requires_calculation_(true),\n  depth_requires_calculation_(true),\n  pointcloud_requires_build_(true),\n  width(0),\n  height(0)\n{\n}\n\nRgbdImage::~RgbdImage()\n{\n}\n\nconst RgbdCamera& RgbdImage::camera() const\n{\n  return camera_;\n}\n\nvoid RgbdImage::initialize()\n{\n  assert(hasIntensity() || hasDepth());\n\n  if(hasIntensity() && hasDepth())\n  {\n    assert(intensity.size() == depth.size());\n  }\n\n  if(hasIntensity())\n  {\n    assert(intensity.type() == cv::DataType<IntensityType>::type && intensity.channels() == 1);\n    width = intensity.cols;\n    height = intensity.rows;\n  }\n  if(hasDepth())\n  {\n    assert(depth.type() == cv::DataType<DepthType>::type && depth.channels() == 1);\n    width = depth.cols;\n    height = depth.rows;\n  }\n\n  intensity_requires_calculation_ = true;\n  depth_requires_calculation_ = true;\n  pointcloud_requires_build_ = true;\n}\n\nbool RgbdImage::hasIntensity() const\n{\n  return !intensity.empty();\n}\n\nbool RgbdImage::hasRgb() const\n{\n  return !rgb.empty();\n}\n\nbool RgbdImage::hasDepth() const\n{\n  return !depth.empty();\n}\n\nvoid RgbdImage::calculateDerivatives()\n{\n  calculateIntensityDerivatives();\n  calculateDepthDerivatives();\n}\n\nbool RgbdImage::calculateIntensityDerivatives()\n{\n  if(!intensity_requires_calculation_) return false;\n\n  assert(hasIntensity());\n\n  calculateDerivativeX<IntensityType>(intensity, intensity_dx);\n  //calculateDerivativeY<IntensityType>(intensity, intensity_dy);\n  calculateDerivativeYSseFloat(intensity, intensity_dy);\n  /*\n  cv::Mat dy_ref, diff;\n  calculateDerivativeY<IntensityType>(intensity, dy_ref);\n  cv::absdiff(dy_ref, intensity_dy, diff);\n  tracker::util::show(\"diff\", diff);\n  cv::waitKey(0);\n   */\n  intensity_requires_calculation_ = false;\n  return true;\n}\n\nvoid RgbdImage::calculateDepthDerivatives()\n{\n  if(!depth_requires_calculation_) return;\n\n  assert(hasDepth());\n\n  calculateDerivativeX<DepthType>(depth, depth_dx);\n  calculateDerivativeY<DepthType>(depth, depth_dy);\n\n  depth_requires_calculation_ = false;\n}\n\ntemplate<typename T>\nvoid RgbdImage::calculateDerivativeX(const cv::Mat& img, cv::Mat& result)\n{\n  result.create(img.size(), img.type());\n\n  for(int y = 0; y < img.rows; ++y)\n  {\n    for(int x = 0; x < img.cols; ++x)\n    {\n      int prev = std::max(x - 1, 0);\n      int next = std::min(x + 1, img.cols - 1);\n\n      result.at<T>(y, x) = (T) (img.at<T>(y, next) - img.at<T>(y, prev)) * 0.5f;\n    }\n  }\n\n  //cv::Sobel(img, result, -1, 1, 0, 3, 1.0f / 4.0f, 0, cv::BORDER_REPLICATE);\n\n  // compiler auto-vectorization\n  /*\n  const float* img_ptr = img.ptr<float>();\n  float* result_ptr = result.ptr<float>();\n\n  for(int y = 0; y < img.rows; ++y)\n  {\n    *result_ptr++ = img_ptr[1] - img_ptr[0];\n\n    for(int x = 1; x < img.cols - 1; ++x, ++img_ptr)\n    {\n      *result_ptr++ = img_ptr[2] - img_ptr[0];\n    }\n\n    *result_ptr++ = img_ptr[1] - img_ptr[0];\n\n    img_ptr++;\n  }\n   */\n}\n\ntemplate<typename T>\nvoid RgbdImage::calculateDerivativeY(const cv::Mat& img, cv::Mat& result)\n{\n  result.create(img.size(), img.type());\n\n  for(int y = 0; y < img.rows; ++y)\n  {\n    for(int x = 0; x < img.cols; ++x)\n    {\n      int prev = std::max(y - 1, 0);\n      int next = std::min(y + 1, img.rows - 1);\n\n      result.at<T>(y, x) = (T) (img.at<T>(next, x) - img.at<T>(prev, x)) * 0.5f;\n    }\n  }\n  //cv::Sobel(img, result, -1, 0, 1, 3, 1.0f / 4.0f, 0, cv::BORDER_REPLICATE);\n\n  // compiler auto-vectorization\n  /*\n  for(int y = 0; y < img.rows; ++y)\n  {\n    const float* prev_row = img.ptr<float>(std::max(y - 1, 0), 0);\n    const float* next_row = img.ptr<float>(std::min(y + 1, img.rows - 1), 0);\n    float* cur_row = result.ptr<float>(y, 0);\n\n    for(int x = 0; x < img.cols; ++x)\n    {\n      *cur_row++ = *next_row++ - *prev_row++;\n    }\n  }\n   */\n}\n\nvoid RgbdImage::buildPointCloud()\n{\n  if(!pointcloud_requires_build_) return;\n\n  assert(hasDepth());\n\n  camera_.buildPointCloud(depth, pointcloud);\n\n  pointcloud_requires_build_ = false;\n}\n\nvoid RgbdImage::calculateNormals()\n{\n  if(angles.total() == 0)\n  {\n    normals = cv::Mat::zeros(depth.size(), CV_32FC4);\n    angles.create(depth.size(), CV_32FC1);\n\n    float *angle_ptr = angles.ptr<float>();\n    cv::Vec4f *normal_ptr = normals.ptr<cv::Vec4f>();\n\n    int x_max = depth.cols - 1;\n    int y_max = depth.rows - 1;\n\n    for(int y = 0; y < depth.rows; ++y)\n    {\n      for(int x = 0; x < depth.cols; ++x, ++angle_ptr, ++normal_ptr)\n      {\n        int idx1 = y * depth.cols + std::max(x-1, 0);\n        int idx2 = y * depth.cols + std::min(x+1, x_max);\n        int idx3 = std::max(y-1, 0) * depth.cols + x;\n        int idx4 = std::min(y+1, y_max) * depth.cols + x;\n\n        Eigen::Vector4f::AlignedMapType n(normal_ptr->val);\n        n = (pointcloud.col(idx2) - pointcloud.col(idx1)).cross3(pointcloud.col(idx4) - pointcloud.col(idx3));\n        n.normalize();\n\n        *angle_ptr = std::abs(n(2));\n      }\n    }\n  }\n}\n\nvoid RgbdImage::buildAccelerationStructure()\n{\n  if(acceleration.total() == 0)\n  {\n    calculateDerivatives();\n    cv::Mat zeros = cv::Mat::zeros(intensity.size(), intensity.type());\n    cv::Mat channels[8] = { intensity, depth, intensity_dx, intensity_dy, depth_dx, depth_dy, zeros, zeros};\n    cv::merge(channels, 8, acceleration);\n  }\n}\n\nvoid RgbdImage::warpIntensity(const AffineTransform& transformationd, const PointCloud& reference_pointcloud, const IntrinsicMatrix& intrinsics, RgbdImage& result, PointCloud& transformed_pointcloud)\n{\n  Eigen::Affine3f transformation = transformationd.cast<float>();\n\n  cv::Mat warped_image(intensity.size(), intensity.type());\n  cv::Mat warped_depth(depth.size(), depth.type());\n\n  float ox = intrinsics.ox();\n  float oy = intrinsics.oy();\n\n  float* warped_intensity_ptr = warped_image.ptr<IntensityType>();\n  float* warped_depth_ptr = warped_depth.ptr<DepthType>();\n\n  int outliers = 0;\n  int total = 0;\n  int idx = 0;\n\n  transformed_pointcloud = transformation * reference_pointcloud;\n\n  for(size_t y = 0; y < height; ++y)\n  {\n    for(size_t x = 0; x < width; ++x, ++idx, ++warped_intensity_ptr, ++warped_depth_ptr)\n    {\n\n      const Eigen::Vector4f& p3d = transformed_pointcloud.col(idx);\n\n      if(!std::isfinite(p3d(2)))\n      {\n        *warped_intensity_ptr = Invalid;\n        *warped_depth_ptr = InvalidDepth;\n        continue;\n      }\n\n      float x_projected = (float) (p3d(0) * intrinsics.fx() / p3d(2) + ox);\n      float y_projected = (float) (p3d(1) * intrinsics.fy() / p3d(2) + oy);\n\n      if(inImage(x_projected, y_projected))\n      {\n        float z = (float) p3d(2);\n\n        *warped_intensity_ptr = Interpolation::bilinearWithDepthBuffer(this->intensity, this->depth, x_projected, y_projected, z);\n        *warped_depth_ptr = z;\n      }\n      else\n      {\n        *warped_intensity_ptr = Invalid;\n        *warped_depth_ptr = InvalidDepth;\n        //outliers++;\n      }\n\n      //total++;\n    }\n  }\n\n  result.intensity = warped_image;\n  result.depth = warped_depth;\n  result.initialize();\n}\n\nvoid RgbdImage::warpDepthForward(const AffineTransform& transformationx, const IntrinsicMatrix& intrinsics, RgbdImage& result, cv::Mat_<cv::Vec3d>& cloud)\n{\n  Eigen::Affine3d transformation = transformationx.cast<double>();\n\n  cloud = cv::Mat_<cv::Vec3d>(depth.size(), cv::Vec3d(0, 0, 0));\n  cv::Mat warped_depth = cv::Mat::zeros(depth.size(), depth.type());\n  warped_depth.setTo(InvalidDepth);\n\n  float ox = intrinsics.ox();\n  float oy = intrinsics.oy();\n\n  const float* depth_ptr = depth.ptr<float>();\n  int outliers = 0;\n  int total = 0;\n\n  for(size_t y = 0; y < height; ++y)\n  {\n    for(size_t x = 0; x < width; ++x, ++depth_ptr)\n    {\n      if(!std::isfinite(*depth_ptr))\n      {\n        continue;\n      }\n\n      float depth = *depth_ptr;\n      Eigen::Vector3d p3d((x - ox) * depth / intrinsics.fx(), (y - oy) * depth / intrinsics.fy(), depth);\n      Eigen::Vector3d p3d_transformed = transformation * p3d;\n\n      float x_projected = (float) (p3d_transformed(0) * intrinsics.fx() / p3d_transformed(2) + ox);\n      float y_projected = (float) (p3d_transformed(1) * intrinsics.fy() / p3d_transformed(2) + oy);\n\n      if(inImage(x_projected, y_projected))\n      {\n        int yi = (int) y_projected, xi = (int) x_projected;\n\n        if(!std::isfinite(warped_depth.at<DepthType>(yi, xi)) || (warped_depth.at<DepthType>(yi, xi) - 0.05) > depth)\n          warped_depth.at<DepthType>(yi, xi) = depth;\n      }\n\n      p3d = p3d_transformed;\n\n      total++;\n      cloud(y, x) = cv::Vec3d(p3d(0), p3d(1), p3d(2));\n    }\n  }\n\n  result.depth = warped_depth;\n  result.initialize();\n}\n\nvoid RgbdImage::warpIntensityForward(const AffineTransform& transformationx, const IntrinsicMatrix& intrinsics, RgbdImage& result, cv::Mat_<cv::Vec3d>& cloud)\n{\n  Eigen::Affine3d transformation = transformationx.cast<double>();\n\n  bool identity = transformation.affine().isIdentity(1e-6);\n\n  cloud = cv::Mat_<cv::Vec3d>(intensity.size(), cv::Vec3d(0, 0, 0));\n  cv::Mat warped_image = cv::Mat::zeros(intensity.size(), intensity.type());\n\n  float ox = intrinsics.ox();\n  float oy = intrinsics.oy();\n\n  const float* depth_ptr = depth.ptr<float>();\n  int outliers = 0;\n  int total = 0;\n\n  for(size_t y = 0; y < height; ++y)\n  {\n    for(size_t x = 0; x < width; ++x, ++depth_ptr)\n    {\n      if(*depth_ptr <= 1e-6f) continue;\n\n      float depth = *depth_ptr;\n      Eigen::Vector3d p3d((x - ox) * depth / intrinsics.fx(), (y - oy) * depth / intrinsics.fy(), depth);\n\n      if(!identity)\n      {\n        Eigen::Vector3d p3d_transformed = transformation * p3d;\n\n        float x_projected = (float) (p3d_transformed(0) * intrinsics.fx() / p3d_transformed(2) + ox);\n        float y_projected = (float) (p3d_transformed(1) * intrinsics.fy() / p3d_transformed(2) + oy);\n\n        if(inImage(x_projected, y_projected))\n        {\n          int xp, yp;\n          xp = (int) std::floor(x_projected);\n          yp = (int) std::floor(y_projected);\n\n          warped_image.at<IntensityType>(yp, xp) = intensity.at<IntensityType>(y, x);\n        }\n        else\n        {\n          outliers++;\n        }\n\n        p3d = p3d_transformed;\n      }\n\n      total++;\n      cloud(y, x) = cv::Vec3d(p3d(0), p3d(1), p3d(2));\n    }\n  }\n\n  //std::cerr << \"warp out: \" << outliers << \" total: \" << total << std::endl;\n\n  if(identity)\n  {\n    warped_image = intensity;\n  }\n  else\n  {\n    //std::cerr << \"did warp\" << std::endl;\n  }\n\n  result.intensity = warped_image;\n  result.depth = depth;\n  result.initialize();\n}\n\nvoid RgbdImage::warpDepthForwardAdvanced(const AffineTransform& transformation, const IntrinsicMatrix& intrinsics, RgbdImage& result)\n{\n  assert(hasDepth());\n\n  this->buildPointCloud();\n\n  PointCloud transformed_pointcloud = transformation.cast<float>() * pointcloud;\n\n  cv::Mat warped_depth(depth.size(), depth.type());\n  warped_depth.setTo(InvalidDepth);\n\n  float z_factor1 = transformation.rotation()(0, 0) + transformation.rotation()(0, 1) * (intrinsics.fx() / intrinsics.fy());\n  float x_factor1 = -transformation.rotation()(2, 0) - transformation.rotation()(2, 1) * (intrinsics.fx() / intrinsics.fy());\n\n  float z_factor2 = transformation.rotation()(1, 1) + transformation.rotation()(1, 0) * (intrinsics.fy() / intrinsics.fx());\n  float y_factor2 = -transformation.rotation()(2, 1) - transformation.rotation()(2, 0) * (intrinsics.fy() / intrinsics.fx());\n\n  for(int idx = 0; idx < height * width; ++idx)\n  {\n    Vector4 p3d = pointcloud.col(idx);\n    NumType z = p3d(2);\n\n    if(!std::isfinite(z)) continue;\n\n    int x_length = (int) std::ceil(z_factor1 + x_factor1 * p3d(0) / z) + 1; // magic +1\n    int y_length = (int) std::ceil(z_factor2 + y_factor2 * p3d(1) / z) + 1; // magic +1\n\n    Vector4 p3d_transformed = transformed_pointcloud.col(idx);\n    NumType z_transformed = p3d_transformed(2);\n\n    int x_projected = (int) std::floor(p3d_transformed(0) * intrinsics.fx() / z_transformed + intrinsics.ox());\n    int y_projected = (int) std::floor(p3d_transformed(1) * intrinsics.fy() / z_transformed + intrinsics.oy());\n\n    // TODO: replace inImage(...) checks, with max(..., 0) on initial value of x_, y_ and  min(..., width/height) for their respective upper bound\n    //for (int y_ = y_projected; y_ < y_projected + y_length; y_++)\n    //  for (int x_ = x_projected; x_ < x_projected + x_length; x_++)\n\n    int x_begin = std::max(x_projected, 0);\n    int y_begin = std::max(y_projected, 0);\n    int x_end = std::min(x_projected + x_length, (int) width);\n    int y_end = std::min(y_projected + y_length, (int) height);\n\n    for (int y = y_begin; y < y_end; ++y)\n    {\n      DepthType* v = warped_depth.ptr<DepthType>(y, x_begin);\n\n      for (int x = x_begin; x < x_end; ++x, ++v)\n      {\n        if(!std::isfinite(*v) || (*v) > z_transformed)\n        {\n          (*v) = (DepthType) z_transformed;\n        }\n      }\n    }\n  }\n\n  result.depth = warped_depth;\n  result.initialize();\n}\n\nbool RgbdImage::inImage(const float& x, const float& y) const\n{\n  return x >= 0 && x < width && y >= 0 && y < height;\n}\n\n} /* namespace core */\n} /* namespace dvo */\n", "meta": {"hexsha": "951f3f80847c95abde3d85135bb82508f0276c24", "size": 20490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dvo_core/src/core/rgbd_image.cpp", "max_stars_repo_name": "aginika/dvo_slam", "max_stars_repo_head_hexsha": "d25b65bff58860bb5a3a39a742459db3ba98eaa6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 566.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:34:55.000Z", "max_issues_repo_path": "dvo_core/src/core/rgbd_image.cpp", "max_issues_repo_name": "aginika/dvo_slam", "max_issues_repo_head_hexsha": "d25b65bff58860bb5a3a39a742459db3ba98eaa6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T08:03:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T16:14:35.000Z", "max_forks_repo_path": "dvo_core/src/core/rgbd_image.cpp", "max_forks_repo_name": "aginika/dvo_slam", "max_forks_repo_head_hexsha": "d25b65bff58860bb5a3a39a742459db3ba98eaa6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 291.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T23:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T13:26:17.000Z", "avg_line_length": 25.9367088608, "max_line_length": 199, "alphanum_fraction": 0.6300634456, "num_tokens": 6313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.04885777412113744, "lm_q1q2_score": 0.017733868129561}}
{"text": "// Copyright (c) 2012 Andre Martins\n// All Rights Reserved.\n//\n// This file is part of AD3 2.1.\n//\n// AD3 2.1 is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// AD3 2.1 is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public License\n// along with AD3 2.1.  If not, see <http://www.gnu.org/licenses/>.\n\n#include <cmath>\n#include \"GenericFactor.h\"\n#include \"Utils.h\"\n#define EIGEN\n#ifdef EIGEN\n#include <Eigen/Eigenvalues>\n#else\n#include \"lapacke/lapacke.h\"\n#endif\n#include <limits>\n\nnamespace AD3 {\n\n#ifdef PRINT_INVERSION_STATS\nstatic int num_inversions_from_scratch = 0;\nstatic int num_inversions_incremental = 0;\nstatic int num_eigenvalue_computations = 0;\n#endif\n\nvoid\nGenericFactor::ClearActiveSet()\n{\n    for (size_t j = 0; j < active_set_.size(); ++j) {\n        DeleteConfiguration(active_set_[j]);\n    }\n    active_set_.clear();\n}\n\nvoid\nGenericFactor::InitActiveSet(Configuration configuration)\n{\n    init_configuration_ = configuration;\n}\n\nvoid\nGenericFactor::InitActiveSetFromScores(\n    const vector<double>& variable_log_potentials,\n    const vector<double>& additional_log_potentials)\n{\n    Configuration configuration = CreateConfiguration();\n\n    double value;\n    Maximize(variable_log_potentials,\n             additional_log_potentials,\n             configuration,\n             &value);\n    InitActiveSet(configuration);\n}\n\nbool\nGenericFactor::InvertAfterInsertion(const vector<Configuration>& active_set,\n                                    const Configuration& inserted_element)\n{\n#ifdef PRINT_INVERSION_STATS\n    ++num_inversions_incremental;\n    if (0 == num_inversions_incremental % 10000) {\n        cout << \"Number of incremental inversions: \"\n             << num_inversions_incremental << endl;\n        cout << \"Number of standard inversions: \" << num_inversions_from_scratch\n             << endl;\n        cout << \"Number of eigenvalue computations: \"\n             << num_eigenvalue_computations << endl;\n    }\n#endif\n\n    vector<double> inverse_A = inverse_A_;\n    int size_A = active_set.size() + 1;\n    vector<double> r(size_A);\n\n    r[0] = 1.0;\n    for (size_t i = 0; i < active_set.size(); ++i) {\n        // Count how many variable values the new assignment\n        // have in common with the i-th assignment.\n        r[i + 1] = CountCommonValuesAdapt(active_set[i], inserted_element);\n    }\n\n    double r0 = CountCommonValuesAdapt(inserted_element, inserted_element);\n    double s = r0;\n    for (int i = 0; i < size_A; ++i) {\n        if (r[i] == 0.0)\n            continue;\n        s -= r[i] * r[i] * inverse_A[i * size_A + i];\n        for (int j = i + 1; j < size_A; ++j) {\n            if (r[j] == 0.0)\n                continue;\n            s -= 2 * r[i] * r[j] * inverse_A[i * size_A + j];\n        }\n    }\n\n    if (NEARLY_ZERO_TOL(s, 1e-9)) {\n        if (verbosity_ > 2) {\n            cout\n              << \"Warning: updated matrix will become singular after insertion.\"\n              << endl;\n        }\n        return false;\n    }\n\n    double invs = 1.0 / s;\n    vector<double> d(size_A, 0.0);\n    for (int i = 0; i < size_A; ++i) {\n        if (r[i] == 0.0)\n            continue;\n        for (int j = 0; j < size_A; ++j) {\n            d[j] += inverse_A[i * size_A + j] * r[i];\n        }\n    }\n\n    int size_A_after = size_A + 1;\n    inverse_A_.resize(size_A_after * size_A_after);\n    for (int i = 0; i < size_A; ++i) {\n        for (int j = 0; j < size_A; ++j) {\n            inverse_A_[i * size_A_after + j] =\n              inverse_A[i * size_A + j] + invs * d[i] * d[j];\n        }\n        inverse_A_[i * size_A_after + size_A] = -invs * d[i];\n        inverse_A_[size_A * size_A_after + i] = -invs * d[i];\n    }\n    inverse_A_[size_A * size_A_after + size_A] = invs;\n\n    return true;\n}\n\nvoid\nGenericFactor::InvertAfterRemoval(const vector<Configuration>& active_set,\n                                  int removed_index)\n{\n#ifdef PRINT_INVERSION_STATS\n    ++num_inversions_incremental;\n    if (0 == num_inversions_incremental % 10000) {\n        cout << \"Number of incremental inversions: \"\n             << num_inversions_incremental << endl;\n        cout << \"Number of standard inversions: \" << num_inversions_from_scratch\n             << endl;\n        cout << \"Number of eigenvalue computations: \"\n             << num_eigenvalue_computations << endl;\n    }\n#endif\n\n    vector<double> inverse_A = inverse_A_;\n    int size_A = active_set.size() + 1;\n    vector<double> r(size_A);\n\n    ++removed_index; // Index in A has an offset of 1.\n    double invs = inverse_A[removed_index * size_A + removed_index];\n    assert(!NEARLY_ZERO_TOL(\n      invs,\n      1e-12)); // TODO: Make this tolerance depend on the scale of the data.\n    double s = 1.0 / invs;\n    vector<double> d(size_A - 1, 0.0);\n    int k = 0;\n    for (int i = 0; i < size_A; ++i) {\n        if (i == removed_index)\n            continue;\n        d[k] = -s * inverse_A[removed_index * size_A + i];\n        ++k;\n    }\n\n    int size_A_after = size_A - 1;\n    inverse_A_.resize(size_A_after * size_A_after);\n    k = 0;\n    for (int i = 0; i < size_A; ++i) {\n        if (i == removed_index)\n            continue;\n        int l = 0;\n        for (int j = 0; j < size_A; ++j) {\n            if (j == removed_index)\n                continue;\n            inverse_A_[k * size_A_after + l] =\n              inverse_A[i * size_A + j] - invs * d[k] * d[l];\n            ++l;\n        }\n        ++k;\n    }\n}\n\n// Compute Mnz'*Mnz\nvoid\nGenericFactor::ComputeActiveSetSimilarities(\n  const vector<Configuration>& active_set,\n  vector<double>* similarities)\n{\n    size_t size = active_set.size();\n\n    // Compute similarity matrix.\n    similarities->resize(size * size);\n    (*similarities)[0] = 0.0;\n    for (size_t i = 0; i < size; ++i) {\n        (*similarities)[i * size + i] =\n          CountCommonValuesAdapt(active_set[i], active_set[i]);\n        for (size_t j = i + 1; j < size; ++j) {\n            // Count how many variable values the i-th and j-th\n            // assignments have in common.\n            double num_common_values =\n              CountCommonValuesAdapt(active_set[i], active_set[j]);\n            (*similarities)[i * size + j] = num_common_values;\n            (*similarities)[j * size + i] = num_common_values;\n        }\n    }\n}\n\n// Compute eigendecomposition of M'*M.\n// Remark: overwrite similarities with the eigenvectors.\nvoid\nGenericFactor::EigenDecompose(vector<double>* similarities,\n                              vector<double>* eigenvalues)\n{\n#ifdef PRINT_INVERSION_STATS\n    ++num_eigenvalue_computations;\n    if (0 == num_eigenvalue_computations % 10000) {\n        cout << \"Number of incremental inversions: \"\n             << num_inversions_incremental << endl;\n        cout << \"Number of standard inversions: \" << num_inversions_from_scratch\n             << endl;\n        cout << \"Number of eigenvalue computations: \"\n             << num_eigenvalue_computations << endl;\n    }\n#endif\n\n    int size =\n      static_cast<int>(sqrt(static_cast<double>(similarities->size())));\n#ifdef EIGEN\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;\n    Eigen::MatrixXd sim(size, size);\n    int t = 0;\n    for (int i = 0; i < size; ++i) {\n        for (int j = 0; j < size; ++j) {\n            sim(i, j) = (*similarities)[t];\n            ++t;\n        }\n    }\n    es.compute(sim);\n    const Eigen::VectorXd& eigvals = es.eigenvalues();\n    eigenvalues->resize(size);\n    for (int i = 0; i < size; ++i) {\n        (*eigenvalues)[i] = eigvals[i];\n    }\n    const Eigen::MatrixXd& eigvectors = es.eigenvectors().transpose();\n    t = 0;\n    for (int i = 0; i < size; ++i) {\n        for (int j = 0; j < size; ++j) {\n            (*similarities)[t] = eigvectors(i, j);\n            ++t;\n        }\n    }\n#else\n    lapack_int info;\n    eigenvalues->resize(size);\n    info = LAPACKE_dsyev(LAPACK_COL_MAJOR,\n                         'V',\n                         'U',\n                         size,\n                         &(*similarities)[0],\n                         size,\n                         &(*eigenvalues)[0]);\n#endif\n}\n\n// Compute inverse of A from scratch.\n// Uses eigendecomposition of M'*M.\nvoid\nGenericFactor::Invert(const vector<double>& eigenvalues,\n                      const vector<double>& eigenvectors)\n{\n#ifdef PRINT_INVERSION_STATS\n    ++num_inversions_from_scratch;\n    if (0 == num_inversions_from_scratch % 10000) {\n        cout << \"Number of incremental inversions: \"\n             << num_inversions_incremental << endl;\n        cout << \"Number of standard inversions: \" << num_inversions_from_scratch\n             << endl;\n        cout << \"Number of eigenvalue computations: \"\n             << num_eigenvalue_computations << endl;\n    }\n#endif\n    int size = eigenvalues.size();\n    int size_A = size + 1;\n    inverse_A_.assign(size_A * size_A, 0.0);\n    for (int i = 0; i < size; ++i) {\n        double s = 1.0 / eigenvalues[i];\n        const double* v = &eigenvectors[0] + i * size;\n        for (int j = 0; j < size; ++j) {\n            for (int k = j; k < size; ++k) {\n                inverse_A_[(1 + j) * size_A + (1 + k)] += s * v[j] * v[k];\n            }\n        }\n    }\n    double s = 0.0;\n    vector<double> d(size, 0.0);\n    for (int j = 1; j <= size; ++j) {\n        s -= inverse_A_[j * size_A + j];\n        d[j - 1] += inverse_A_[j * size_A + j];\n        for (int k = j + 1; k <= size; ++k) {\n            inverse_A_[k * size_A + j] = inverse_A_[j * size_A + k];\n            s -= 2 * inverse_A_[j * size_A + k];\n            d[j - 1] += inverse_A_[j * size_A + k];\n            d[k - 1] += inverse_A_[j * size_A + k];\n        }\n    }\n\n    double invs = 1.0 / s;\n    inverse_A_[0] = invs;\n    for (int j = 1; j <= size; ++j) {\n        inverse_A_[j * size_A] = -invs * d[j - 1];\n        inverse_A_[j] = inverse_A_[j * size_A];\n        inverse_A_[j * size_A + j] += invs * d[j - 1] * d[j - 1];\n        for (int k = j + 1; k <= size; ++k) {\n            inverse_A_[j * size_A + k] += invs * d[j - 1] * d[k - 1];\n            inverse_A_[k * size_A + j] = inverse_A_[j * size_A + k];\n        }\n    }\n}\n\n// Checks if M'*M is singular.\n// If so, asserts that the null space is 1-dimensional\n// and returns a basis of the null space.\nbool\nGenericFactor::IsSingular(vector<double>& eigenvalues,\n                          vector<double>& eigenvectors,\n                          vector<double>* null_space_basis)\n{\n    int size = eigenvalues.size();\n    int zero_eigenvalue = -1;\n    for (int i = 0; i < size; ++i) {\n        if (eigenvalues[i] < 1e-12) {\n            if (zero_eigenvalue >= 0) {\n                cout << eigenvalues[i] << \" \" << eigenvalues[zero_eigenvalue]\n                     << endl;\n                assert(false);\n            }\n            zero_eigenvalue = i;\n        }\n    }\n    if (zero_eigenvalue < 0)\n        return false;\n    if (null_space_basis) {\n        null_space_basis->assign(eigenvectors.begin() + zero_eigenvalue * size,\n                                 eigenvectors.begin() +\n                                   (1 + zero_eigenvalue) * size);\n    }\n    return true;\n}\n\nvoid\nGenericFactor::SolveQP(const vector<double>& variable_log_potentials,\n                       const vector<double>& additional_log_potentials,\n                       vector<double>* variable_posteriors,\n                       vector<double>* additional_posteriors)\n{\n    if (verbosity_ > 5)\n        cout << \"Solving QP...\" << endl;\n    size_t dim = variable_log_potentials.size();\n\n    vector<double> variable_log_potentials_adj = variable_log_potentials;\n    if (adjust_degrees_) {\n        for (size_t j = 0; j < dim; ++j)\n            variable_log_potentials_adj[j] /= sqrt_degrees_[j];\n    }\n\n    // Initialize the active set.\n    if (active_set_.size() == 0) {\n        variable_posteriors->resize(variable_log_potentials.size());\n        additional_posteriors->resize(additional_log_potentials.size());\n        distribution_.clear();\n\n        // Initialize the active set with one vertex.\n        // For best convergence, it's good to use the MAP.\n        // However you may specify a custom initializer.\n       Configuration configuration = init_configuration_;\n\n        if (configuration == nullptr)\n        {\n            // Initialize by solving the LP, discarding the quadratic term.\n            configuration = CreateConfiguration();\n\n            double value;\n            Maximize(variable_log_potentials_adj,\n                     additional_log_potentials,\n                     configuration,\n                     &value);\n        }\n\n        active_set_.push_back(configuration);\n        distribution_.push_back(1.0);\n\n        // Initialize inv(A) as [-M,1;1,0].\n        double nrm = CountCommonValuesAdapt(configuration, configuration);\n        inverse_A_ = { -nrm, 1, 1, 0 };\n    }\n    if (verbosity_ > 5)\n    {\n        cout << \"Distribution at beginning of active set: \";\n        for (auto val : distribution_)\n            cout << val << \" \";\n        cout << endl;\n    }\n\n    bool changed_active_set = true;\n    vector<double> z;\n    int num_max_iterations = num_max_iterations_QP_;\n    double tau = 0;\n    for (int iter = 0; iter < num_max_iterations; ++iter) {\n\n        if (verbosity_ > 6)\n            cout << \"active set iter \" << iter << endl;\n\n        bool same_as_before = true;\n        bool unbounded = false;\n        if (changed_active_set) {\n            // Recompute vector b.\n            vector<double> b(active_set_.size() + 1, 0.0);\n            b[0] = 1.0;\n            for (size_t i = 0; i < active_set_.size(); ++i) {\n                const Configuration& configuration = active_set_[i];\n                double score;\n                Evaluate(variable_log_potentials_adj,\n                         additional_log_potentials,\n                         configuration,\n                         &score);\n                b[i + 1] = score;\n            }\n\n            // Solve the system Az = b.\n            z.resize(active_set_.size());\n            size_t size_A = active_set_.size() + 1;\n            for (size_t i = 0; i < active_set_.size(); ++i) {\n                z[i] = 0.0;\n                for (size_t j = 0; j < size_A; ++j) {\n                    z[i] += inverse_A_[(i + 1) * size_A + j] * b[j];\n                }\n            }\n            tau = 0.0;\n            for (size_t j = 0; j < size_A; ++j) {\n                tau += inverse_A_[j] * b[j];\n            }\n\n            same_as_before = false;\n        }\n\n        if (same_as_before) {\n            // Compute the variable marginals from the full distribution\n            // stored in z.\n            ComputeMarginalsFromSparseDistribution(\n              active_set_, z, variable_posteriors, additional_posteriors);\n            if (adjust_degrees_) {\n                for (size_t j = 0; j < dim; ++j)\n                    (*variable_posteriors)[j] /= sqrt_degrees_[j];\n            }\n\n            // Get the most violated constraint\n            // (by calling the black box that computes the MAP).\n            vector<double> scores = variable_log_potentials_adj;\n            for (size_t i = 0; i < scores.size(); ++i) {\n                scores[i] -= (*variable_posteriors)[i];\n            }\n            Configuration configuration = CreateConfiguration();\n            double value;\n            Maximize(scores, additional_log_potentials, configuration, &value);\n\n            double very_small_threshold = 1e-9;\n            if (value <= tau + very_small_threshold) { // value <= tau.\n                // We have found the solution;\n                // the distribution, active set, and inv(A) are cached for the\n                // next round.\n                if (verbosity_ > 2) {\n                    cout << \"Converged.\" << endl;\n                }\n                DeleteConfiguration(configuration);\n                return;\n            } else {\n                for (size_t k = 0; k < active_set_.size(); ++k) {\n                    // This is expensive and should just be a sanity check.\n                    // However, in practice, numerical issues force an already\n                    // existing configuration to try to be added. Therefore, we\n                    // always check if a configuration already exists before\n                    // inserting it. If it does, that means the active set\n                    // method converged to a solution (but numerical issues had\n                    // prevented us to see it.)\n                    if (SameConfiguration(active_set_[k], configuration)) {\n                        if (verbosity_ > 0) {\n                            cout << \"Warning: value - tau = \" << value - tau\n                                 << \" \" << value << \" \" << tau << endl;\n                        }\n                        // We have found the solution;\n                        // the distribution, active set, and inv(A)\n                        // are cached for the next round.\n                        DeleteConfiguration(configuration);\n\n                        // Just in case, clean the cache.\n                        // This may prevent eventual numerical problems in the\n                        // future.\n                        if (clear_cache_) {\n                            for (size_t j = 0; j < active_set_.size(); ++j) {\n                                if (j == k)\n                                    continue; // This configuration was deleted\n                                              // already.\n                                DeleteConfiguration(active_set_[j]);\n                            }\n                            active_set_.clear();\n                            inverse_A_.clear();\n                            distribution_.clear();\n                        }\n\n                        // Return.\n                        return;\n                    }\n                }\n                z.push_back(0.0);\n                distribution_ = z;\n\n                // Update inv(A).\n                bool singular =\n                  !InvertAfterInsertion(active_set_, configuration);\n                if (singular) {\n                    // If adding a new configuration causes the matrix to be\n                    // singular, don't just add it. Instead, look for a\n                    // configuration in the null space and remove it before\n                    // inserting the new one. Right now, if more than one such\n                    // configuration exists, we just remove the first one we\n                    // find. There's a chance this could cause some cyclic\n                    // behaviour. If that is the case, we should randomize this\n                    // choice. Note: This step is expensive and requires an\n                    // eigendecomposition.\n                    // TODO: I think there is a graph interpretation for this\n                    // problem. Maybe some specialized graph algorithm is\n                    // cheaper than doing the eigendecomposition.\n                    vector<double> similarities(active_set_.size() *\n                                                active_set_.size());\n                    ComputeActiveSetSimilarities(active_set_, &similarities);\n                    vector<double> padded_similarities(\n                      (active_set_.size() + 2) * (active_set_.size() + 2), 1.0);\n                    for (size_t i = 0; i < active_set_.size(); ++i) {\n                        for (size_t j = 0; j < active_set_.size(); ++j) {\n                            padded_similarities[(i + 1) *\n                                                  (active_set_.size() + 2) +\n                                                (j + 1)] =\n                              similarities[i * active_set_.size() + j];\n                        }\n                    }\n                    padded_similarities[0] = 0.0;\n                    for (size_t i = 0; i < active_set_.size(); ++i) {\n                        double value =\n                          CountCommonValuesAdapt(configuration, active_set_[i]);\n                        padded_similarities[(i + 1) * (active_set_.size() + 2) +\n                                            (active_set_.size() + 1)] = value;\n                        padded_similarities[(active_set_.size() + 1) *\n                                              (active_set_.size() + 2) +\n                                            (i + 1)] = value;\n                    }\n                    double value =\n                      CountCommonValuesAdapt(configuration, configuration);\n                    padded_similarities[(active_set_.size() + 1) *\n                                          (active_set_.size() + 2) +\n                                        (active_set_.size() + 1)] = value;\n\n                    vector<double> eigenvalues(active_set_.size() + 2);\n                    EigenDecompose(&padded_similarities, &eigenvalues);\n                    int zero_eigenvalue = -1;\n                    for (size_t i = 0; i < active_set_.size() + 2; ++i) {\n                        if (NEARLY_EQ_TOL(eigenvalues[i], 0.0, 1e-9)) {\n                            if (zero_eigenvalue >= 0) {\n                                // If this happens, something failed. Maybe a\n                                // numerical problem may cause this. In that\n                                // case, just give up, clean the cache and\n                                // return. Hopefully the next iteration will fix\n                                // it.\n                                cout << \"Multiple zero eigenvalues: \"\n                                     << eigenvalues[zero_eigenvalue] << \" and \"\n                                     << eigenvalues[i] << endl;\n                                cout << \"Warning: Giving up.\" << endl;\n                                // Clean the cache.\n                                for (size_t j = 0; j < active_set_.size(); ++j) {\n                                    DeleteConfiguration(active_set_[j]);\n                                }\n                                active_set_.clear();\n                                inverse_A_.clear();\n                                distribution_.clear();\n                                return;\n                            }\n                            zero_eigenvalue = i;\n                        }\n                    }\n                    assert(zero_eigenvalue >= 0);\n                    vector<int> configurations_to_remove;\n                    for (size_t j = 1; j < active_set_.size() + 1; ++j) {\n                        double value =\n                          padded_similarities[zero_eigenvalue *\n                                                (active_set_.size() + 2) +\n                                              j];\n                        if (!NEARLY_EQ_TOL(value, 0.0, 1e-9)) {\n                            configurations_to_remove.push_back(j - 1);\n                        }\n                    }\n                    if (verbosity_ > 2) {\n                        cout << \"Pick a configuration to remove (\"\n                             << configurations_to_remove.size() << \" out of \"\n                             << active_set_.size() << \").\" << endl;\n                    }\n\n                    assert(configurations_to_remove.size() >= 1);\n                    int j = configurations_to_remove[0];\n\n                    // Update inv(A).\n                    InvertAfterRemoval(active_set_, j);\n\n                    // Remove blocking constraint from the active set.\n                    DeleteConfiguration(\n                      active_set_[j]); // Delete configutation.\n                    active_set_.erase(active_set_.begin() + j);\n\n                    singular =\n                      !InvertAfterInsertion(active_set_, configuration);\n                    assert(!singular);\n                }\n\n                // Insert configuration to active set.\n                if (verbosity_ > 2) {\n                    cout << \"Inserted one element to the active set (iteration \"\n                         << iter << \").\" << endl;\n                }\n                active_set_.push_back(configuration);\n                changed_active_set = true;\n            }\n        } else {\n            // Solution has changed from the previous iteration.\n            // Look for blocking constraints.\n            int blocking = -1;\n            bool exist_blocking = false;\n            double alpha = 1.0;\n            for (size_t i = 0; i < active_set_.size(); ++i) {\n\n                // Incorrect factors can make this fail.\n                assert(distribution_[i] >= -1e-12);\n\n                if (z[i] >= distribution_[i])\n                    continue;\n                if (z[i] < 0)\n                    exist_blocking = true;\n                double tmp = distribution_[i] / (distribution_[i] - z[i]);\n                if (blocking < 0 || tmp < alpha) {\n                    alpha = tmp;\n                    blocking = i;\n                }\n            }\n\n            if (!exist_blocking) {\n                // No blocking constraints.\n                assert(!unbounded);\n                distribution_ = z;\n                alpha = 1.0;\n                changed_active_set = false;\n            } else {\n                if (alpha > 1.0 && !unbounded)\n                    alpha = 1.0;\n                // Interpolate between factor_posteriors_[i] and z.\n                if (alpha == 1.0) {\n                    distribution_ = z;\n                } else {\n                    for (size_t i = 0; i < active_set_.size(); ++i) {\n                        z[i] = (1 - alpha) * distribution_[i] + alpha * z[i];\n                        distribution_[i] = z[i];\n                        if (distribution_[i] < 0.0) {\n                            if (verbosity_ > 2) {\n                                cout << \"Truncating distribution variable: \"\n                                     << distribution_[i] << endl;\n                            }\n                            distribution_[i] = 0.0;\n                        }\n                    }\n                }\n\n                // Update inv(A).\n                InvertAfterRemoval(active_set_, blocking);\n\n                // Remove blocking constraint from the active set.\n                if (verbosity_ > 2) {\n                    cout << \"Removed one element to the active set (iteration \"\n                         << iter << \").\" << endl;\n                }\n\n                DeleteConfiguration(\n                  active_set_[blocking]); // Delete configutation.\n                active_set_.erase(active_set_.begin() + blocking);\n\n                z.erase(z.begin() + blocking);\n                distribution_.erase(distribution_.begin() + blocking);\n                changed_active_set = true;\n                for (size_t i = 0; i < distribution_.size(); ++i) {\n                    assert(distribution_[i] > -1e-16);\n                }\n            }\n        }\n    }\n\n    if (verbosity_ > 2) {\n        cout << \"Maximum number of iterations reached.\" << endl;\n    }\n\n    // Maximum number of iterations reached.\n    // Return the best existing solution by computing the variable marginals\n    // from the full distribution stored in z.\n    // assert(false);\n    ComputeMarginalsFromSparseDistribution(\n      active_set_, z, variable_posteriors, additional_posteriors);\n    if (adjust_degrees_) {\n        for (size_t j = 0; j < dim; ++j)\n            (*variable_posteriors)[j] /= sqrt_degrees_[j];\n    }\n}\n\n/* Get the correspondence between configurations & variable/additionals */\nvoid\nGenericFactor::GetCorrespondence(vector<double>* M, vector<double>* N)\n{\n\n    size_t n_active = active_set_.size();\n    size_t n_vars = Degree();\n    size_t n_add = GetAdditionalLogPotentials().size();\n\n    M->reserve(n_vars * n_active);\n    N->reserve(n_add * n_active);\n\n    vector<double> m_row(n_vars), n_row(n_add);\n\n    for (size_t i = 0; i < n_active; ++i) {\n\n        m_row.assign(n_vars, 0);\n        n_row.assign(n_add, 0);\n\n        UpdateMarginalsFromConfiguration(active_set_[i], 1.0, &m_row, &n_row);\n        if (adjust_degrees_)\n            for (size_t j = 0; j < n_vars; ++j)\n                m_row[j] /= sqrt_degrees_[j];\n\n        M->insert(M->end(), m_row.begin(), m_row.end());\n\n        N->insert(N->end(), n_row.begin(), n_row.end());\n    }\n}\n\n// multiply by the lower-right corner of inverse_A_, which is our Q\nvoid\nGenericFactor::QVec(const double* v, double* out)\n{\n    size_t nnz = active_set_.size();\n    for (size_t i = 0; i < nnz; ++i)\n        for (size_t j = 0; j < nnz; ++j)\n            out[i] += inverse_A_[(1 + nnz) * (i + 1) + (j + 1)] * v[j];\n}\n\nvoid\nGenericFactor::JacobianVec(const vector<double>& v,\n                           vector<double>& out,\n                           vector<double>& out_add)\n{\n    size_t nnz = active_set_.size();\n    out_add.assign(additional_log_potentials_.size(), 0.0);\n\n    // 1. Multiply v by M.t, save in buf\n    vector<double> Mtv(nnz); // TODO avoid the allocation\n    vector<double> QMtv(nnz, 0);\n    for (size_t i = 0; i < nnz; ++i) {\n        Evaluate(v, out_add, active_set_[i], &Mtv[i]);\n    }\n\n    // 2. Apply jac-vector to buf\n    QVec(Mtv.data(), QMtv.data());\n\n    // 3. Multiply result by M, store in out and out_add.\n    ComputeMarginalsFromSparseDistribution(active_set_, QMtv, &out, &out_add);\n}\n\nvoid\nGenericFactor::DistJacobianVec(const vector<double>& v,\n                               vector<double>& out,\n                               vector<double>& out_add)\n{\n    // Gradient wrt the posterior probabilties on the support.\n    size_t nnz = active_set_.size();\n    out_add.assign(GetNumAdditionals(), 0.0);\n\n    vector<double> Qv(nnz, 0);\n\n    // 2. Apply jac-vector to input vector v\n    QVec(v.data(), Qv.data());\n\n    // 3. Multiply result by M, store in out and out_add.\n    ComputeMarginalsFromSparseDistribution(active_set_, Qv, &out, &out_add);\n}\n\n} // namespace AD3\n", "meta": {"hexsha": "d4177e4e53d24629ea363990053cd437ec2ce2dd", "size": 30147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ad3qp/ad3/GenericFactor.cpp", "max_stars_repo_name": "andre-martins/lp-sparsemap", "max_stars_repo_head_hexsha": "5df0c2f25290881a0ecd4270a9fbbc488d9055ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-02-04T04:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T12:08:04.000Z", "max_issues_repo_path": "ad3qp/ad3/GenericFactor.cpp", "max_issues_repo_name": "andre-martins/lp-sparsemap", "max_issues_repo_head_hexsha": "5df0c2f25290881a0ecd4270a9fbbc488d9055ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-02-04T05:19:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T08:54:24.000Z", "max_forks_repo_path": "ad3qp/ad3/GenericFactor.cpp", "max_forks_repo_name": "andre-martins/lp-sparsemap", "max_forks_repo_head_hexsha": "5df0c2f25290881a0ecd4270a9fbbc488d9055ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-03-07T10:35:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T11:04:43.000Z", "avg_line_length": 37.2185185185, "max_line_length": 81, "alphanum_fraction": 0.5015092712, "num_tokens": 6969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609384437117127, "lm_q2_score": 0.03567855010870562, "lm_q1q2_score": 0.01769990908501724}}
{"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_IO_MATRIX_MARKET_INCLUDE\n#define MTL_IO_MATRIX_MARKET_INCLUDE\n\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <locale>\n#include <complex>\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/type_traits/is_integral.hpp>\n// #include <boost/algorithm/string/case_conv.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <boost/numeric/mtl/io/matrix_file.hpp>\n#include <boost/numeric/mtl/io/read_filter.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/exception.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/string_to_enum.hpp>\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n\nnamespace mtl { namespace io {\n\n\n/// Input file stream for files in matrix market format\nclass matrix_market_istream\n{\n    class pattern_type {};\n    typedef matrix_market_istream        self;\n    void check_stream(const std::string& file_name= std::string()) // not const to delete new_stream\n    {\n\tif (!my_stream.good()) {\n\t    std::string message(\"matrix_market_istream: Error in input stream!\\n\");\n\t    if (file_name != std::string())\n\t\tmessage+= \"Probably file \" + file_name + \" not found.\\n\";\n\t    std::cerr << message;\n\t    if (new_stream)\n\t\tdelete new_stream, new_stream= 0; // To get valgrind quite\n\t    throw(file_not_found(message.c_str()));\n\t}\n    }\n\n  public:\n    explicit matrix_market_istream(const char* p) : new_stream(new std::ifstream(p)), my_stream(*new_stream) { check_stream(p); }\n    explicit matrix_market_istream(const std::string& s) : new_stream(new std::ifstream(s.c_str())), my_stream(*new_stream) { check_stream(s); }\n    explicit matrix_market_istream(std::istream& s= std::cin) : new_stream(0), my_stream(s) { check_stream(); }\n\n    ~matrix_market_istream() \n    { \tif (new_stream) delete new_stream;    }\n\n    template <typename Coll>\n    self& operator>>(Coll& c) \n    { \treturn read(c, typename mtl::traits::category<Coll>::type());    }\n\n    /// Close only my own file, i.e. if filename and not stream is passed in constructor\n    void close() { if (new_stream) new_stream->close(); }\n\n  protected:\n    template <typename Matrix> self& read(Matrix& A, tag::matrix);\n\n    void to_lower(std::string& s) const\n    {\n\tusing namespace std;\n\tfor (unsigned i= 0; i < s.size(); i++)\n\t    s[i]= tolower(s[i]);\n    }\n\n    void set_symmetry(std::string& symmetry_text)\n    {\n\tto_lower(symmetry_text); \n\tconst char* symmetry_options[]= {\"general\", \"symmetric\", \"skew-symmetric\", \"hermitian\"};\n\tmy_symmetry= string_to_enum(symmetry_text, symmetry_options, symmetry());\n    }\n\n    void set_sparsity(std::string& sparsity_text)\n    {\n\tto_lower(sparsity_text); \n\tconst char* sparsity_options[]= {\"coordinate\", \"array\"};\n\tmy_sparsity= string_to_enum(sparsity_text, sparsity_options, sparsity());\n    }\n\n    template <typename Inserter, typename Value>\n    void read_matrix(Inserter& ins, Value)\n    {\n\ttypedef typename Collection<typename Inserter::matrix_type>::size_type size_type;\n\tread_filter<Inserter> filter(ins);\n\tif (my_sparsity == coordinate) // sparse\n\t    // while (my_stream) { // sometimes does an extra erroneous loop\n\t    for (std::size_t i= 0; i < nnz; i++) {\n\t\tsize_type r, c;\n\t\tmy_stream >> r >> c;\n\t\tif (!my_stream) break; // in case while(my_stream) caught an empty line at the end\n\t\tinsert_value(ins, r-1, c-1, filter, Value());\n\t    }\n\telse // dense \n\t    for (std::size_t c= 0; c < ncols; c++) \n\t\tfor (std::size_t r= 0; r < nrows; r++)\n\t\t    insert_value(ins, r, c, filter, Value());\n    }\n\n    template <typename Inserter, typename Filter, typename Value>\n    void insert_value(Inserter& ins, std::size_t r, std::size_t c, const Filter& filter, Value) \n    {\n\tusing mtl::conj;\n\ttypedef typename Collection<typename Inserter::matrix_type>::value_type mvt;\n\tValue v;\n\tread_value(v);\n\t// std::cout << \"Going to insert at [\" << r << \"][\" << c << \"] value \" << which_value(v, mvt()) << \"\\n\";\n\tif (filter(r, c))\n\t    ins[r][c] << which_value(v, mvt());\n\tif (r != c && filter(c, r)) \n\t    switch(my_symmetry) {\n\t      case symmetric:      ins[c][r] << which_value(v, mvt()); break;\n\t      case skew:           ins[c][r] << -which_value(v, mvt()); break;\n\t      case Hermitian:      ins[c][r] << conj(which_value(v, mvt())); break;\n\t      default:             ; // do nothing\n\t    }\n    }\n\n    void read_value(pattern_type) {}\n    void read_value(double& v) { my_stream >> v;}\n    void read_value(long& v) { my_stream >> v;}\n    void read_value(std::complex<double>& v) \n    { \n\tdouble r, i; my_stream >> r >> i; v= std::complex<double>(r, i);\n    }\n\n    // Which value to be inserted? Itself if exist and 0 for pattern; complex are \n    template <typename Value, typename MValue> MValue which_value(Value v, MValue) { return boost::numeric_cast<MValue>(v); }\n    template <typename MValue> MValue which_value(pattern_type, MValue) { return boost::numeric_cast<MValue>(0.0); }\n    template <typename MValue> MValue which_value(std::complex<double>, MValue) { MTL_THROW(runtime_error(\"Cannot convert complex value in real\\n\")); return 1; }\n    std::complex<long double> which_value(std::complex<double> v, std::complex<long double>) { return boost::numeric_cast<std::complex<long double> >(v); }\n    std::complex<double> which_value(std::complex<double> v, std::complex<double>) { return v; }\n    std::complex<float> which_value(std::complex<double> v, std::complex<float>) { return std::complex<float>(float(real(v)), float(imag(v))); }\n\n    std::ifstream      *new_stream;\n    std::istream       &my_stream;\n    enum symmetry {general, symmetric, skew, Hermitian} my_symmetry;\n    enum sparsity {coordinate, array} my_sparsity;\n    std::size_t nrows, ncols, nnz;\n};\n\n\n\n// Matrix version\ntemplate <typename Matrix>\nmatrix_market_istream& matrix_market_istream::read(Matrix& A, tag::matrix)\n{\n    std::string marker, type, sparsity_text, value_format, symmetry_text;\n    my_stream >> marker >> type >> sparsity_text >> value_format >> symmetry_text;\n#if 0    \n    std::cout << marker << \", \" << type << \", \" << sparsity_text << \", \" \n\t      << value_format << \", \" << symmetry_text << \"\\n\";\n#endif\n    MTL_THROW_IF(marker != std::string(\"%%MatrixMarket\"), \n\t\t runtime_error(\"File not in Matrix Market format\"));\n    MTL_THROW_IF(type != std::string(\"matrix\"), \n\t\t runtime_error(\"Try to read matrix from non-matrix file\"));\n\n    set_symmetry(symmetry_text);\n    set_sparsity(sparsity_text);\n\n    char first, comment[80];\n    do {\n\tmy_stream >> first;\n\tif (first == '%') // comments start with % -> ignore them\n\t    my_stream.getline(comment, 80, '\\n'); // read rest of line\n\telse\n\t    my_stream.putback(first); // if not commment we still need it\n    } while (first == '%');\n\n    my_stream >> nrows >> ncols;\n    // std::cout << nrows << \"x\" << ncols << \", \" << nnz << \" non-zeros\\n\";\t\n    A.change_dim(nrows, ncols);\n    set_to_zero(A);\n\n    std::size_t slot_size;\n    if (sparsity_text == std::string(\"coordinate\")) {\n\tmy_stream >> nnz; slot_size= std::max(std::size_t(double(nnz) / double(A.dim1()) * 1.25), std::size_t(1));\n    } else\n\tslot_size= A.dim2(); // maximal value (if A is dense it does not matter anyway)\n\n    // Create enough space in sparse matrices\n    mat::inserter<Matrix> ins(A, slot_size);\n\n    if (value_format == std::string(\"real\"))\n\tread_matrix(ins, double());\n    else if (value_format == std::string(\"integer\"))\n\tread_matrix(ins, long());\n    else if (value_format == std::string(\"complex\"))\n\tread_matrix(ins, std::complex<double>());\n    else if (value_format == std::string(\"pattern\"))\n\tread_matrix(ins, pattern_type());\n    else\n\tMTL_THROW(runtime_error(\"Unknown tag for matrix value type in file\"));\n\n    return *this;\n}\n\n\nclass matrix_market_ostream \n{\n    typedef matrix_market_ostream        self;\npublic:\n    explicit matrix_market_ostream(const char* p) : new_stream(new std::ofstream(p)), my_stream(*new_stream) {}\n    explicit matrix_market_ostream(const std::string& s) : new_stream(new std::ofstream(s.c_str())), my_stream(*new_stream) {}\n    explicit matrix_market_ostream(std::ostream& s= std::cout) : new_stream(0), my_stream(s) {}\n\n    ~matrix_market_ostream() { if (new_stream) delete new_stream; }\n\n    template <typename Coll>\n    self& operator<<(const Coll& c) \n    { \n\treturn write(c, typename mtl::traits::category<Coll>::type());\n    }\n\n    /// Close only my own file, i.e. if filename and not stream is passed in constructor\n    void close() { if (new_stream) new_stream->close(); }\n\nprivate:\n    template <typename Matrix> self& write(const Matrix& A, tag::matrix)\n    {\n\tmatrix_status_line(A);\n\tif (sparsity(A) == std::string(\"coordinate \"))\n\t    return write_sparse_matrix(A);\n\telse\n\t    return write_dense_matrix(A);\n    }\n\n    template <typename Matrix> self& write_sparse_matrix(const Matrix& A)\n    {\n\tmy_stream << num_rows(A) << \" \" << num_cols(A) << \" \" << A.nnz() << \"\\n\";\n\t\n\ttypename mtl::traits::row<Matrix>::type             row(A); \n\ttypename mtl::traits::col<Matrix>::type             col(A); \n\ttypename mtl::traits::const_value<Matrix>::type     value(A); \n\ttypedef typename mtl::traits::range_generator<tag::major, Matrix>::type  cursor_type;\n\ttypedef typename mtl::traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\n\tfor (cursor_type cursor = begin<tag::major>(A), cend = end<tag::major>(A); cursor != cend; ++cursor)\n\t    for (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor)\n\t\tmy_stream << row(*icursor)+1 << \" \" << col(*icursor)+1 << \" \", write_value(value(*icursor)), my_stream << \"\\n\";\n\treturn *this;\n    }\n\n    template <typename Matrix> self& write_dense_matrix(const Matrix& A)\n    {\n\tmy_stream << num_rows(A) << \" \" << num_cols(A) << \"\\n\";\n\tfor (std::size_t c = 0; c < num_cols(A); ++c)\n\t    for (std::size_t r = 0; r < num_rows(A); ++r) {\n\t\twrite_value(A[r][c]), my_stream << \" \";\n\t    my_stream << \"\\n\";\n\t}\n\treturn *this;\n    }\n\n    template <typename Value>\n    typename boost::enable_if<boost::is_integral<Value> >::type\n    write_value(const Value& v) { my_stream << v; }\n\n    template <typename Value>\n    typename boost::enable_if<boost::is_floating_point<Value> >::type\n    write_value(const Value& v) \n    { \n\tmy_stream.precision(std::numeric_limits<Value>::digits10 + 1);\n\tmy_stream.setf(std::ios::scientific); \n\tmy_stream << v; \n\tmy_stream.unsetf(std::ios::scientific); \n    }\n\n    template <typename Value>\n    void write_value(const std::complex<Value>& v) \n    { \n\tmy_stream.precision(std::numeric_limits<Value>::digits10 + 1);\n\tmy_stream.setf(std::ios::scientific); \n\tmy_stream << real(v) << \" \" << imag(v); \n\tmy_stream.unsetf(std::ios::scientific); \n    }\n\n    // Will be generalized via traits::is_symmetric and alike\n    template <typename Matrix>\n    std::string symmetry(const Matrix&) const { return std::string(\"general\\n\"); }\n\n    template <typename Matrix>\n    std::string sparsity(const Matrix&) const \n    {\n\treturn std::string( mtl::traits::is_sparse<Matrix>::value ? \"coordinate \" : \"array \" );\n    }\n\n    template <typename Value>\n    typename boost::enable_if<boost::is_integral<Value>, std::string>::type\n    value(const Value&) const { return std::string(\"integer \"); }\n\n    template <typename Value>\n    typename boost::enable_if<boost::is_floating_point<Value>, std::string>::type\n    value(const Value&) const { return std::string(\"real \"); }\n\n    template <typename Value>\n    std::string value(const std::complex<Value>&) const { return std::string(\"complex \"); }\n\n    template <typename Matrix>\n    void matrix_status_line(const Matrix& A) const\n    {\n\ttypedef typename Collection<Matrix>::value_type value_type;\n\tstd::string st(std::string(\"%%MatrixMarket  matrix \") + sparsity(A) + value(value_type()) + symmetry(A));\n\tmy_stream << st;\n    }\n\nprotected:\n    std::ofstream      *new_stream;\n    std::ostream       &my_stream;\n};\n\n\n}} // namespace mtl::io\n\n#endif // MTL_IO_MATRIX_MARKET_INCLUDE\n", "meta": {"hexsha": "847f6245a1d934ef332a8f17593e2199b6d3e6ae", "size": 12600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/io/matrix_market.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/mtl/io/matrix_market.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/mtl/io/matrix_market.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5, "max_line_length": 161, "alphanum_fraction": 0.666984127, "num_tokens": 3290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.05340333318956081, "lm_q1q2_score": 0.017682897781047653}}
{"text": "#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <thread>\n#include <string>\n#include <cmath>\n#include <map>\n#include <utility>\n#include <unordered_map>\n\n//#include <inttypes.h>\n\n#include <boost/tr1/random.hpp>\n\n#include \"utils.h\"\n#include \"utils/hdf5.h\"\n#include \"utils/string.h\"\n\n//#include \"WordEmbed.h\"\n\n\nconst int exp_table_size = 1000;\nconst int max_exp = 6;\nconst int max_sentence_length = 1000;\nconst int64_t table_size = 100000000;\n\nusing namespace util::io;\n\n///// Data Structure\nnamespace word2vec{\nnamespace type{\n  \nusing int_t = int64_t;\nusing float_t = float;\nusing char_t = char;\n\nusing hashmap_t = std::unordered_map<std::string, int_t>;\n}//namespace word2vec::type\n}//namespace word2vec\n\nnamespace word2vec{\n\nstruct TokenizedFile{\n    TokenizedFile(std::string train_file) {\n        val.open(train_file, std::ifstream::in);\n\n        if(val.fail()) {\n            std::cout << \"ERROR: training data file not found!\\n\";\n            exit(1);\n        }\n    }\n    std::ifstream val; \n};\n\n//CAUTION!! Do not include a following line in a header.\nusing namespace word2vec::type;\n    \nvoid VocabLearn(TokenizedFile & file, hashmap_t &word_count, std::vector<std::pair<int64_t,std::string>> &word_position, int64_t &pos){\n    std::string line;\n    while (std::getline(file.val, line)){  \n        std::istringstream iss{line};\n        auto words = util::string::split(line);\n        for(auto x : words) {\n            word_position.push_back(std::make_pair(pos,x));\n            pos++;\n            auto isin = word_count.find(x);\n            if(isin != word_count.end()) {\n                word_count[x]+=1;\n            } else {\n                word_count[x]= 1;\n            }\n        }\n    }\n    /*\n    hashmap_t word_count_temp;\n    word_count_temp = word_count;\n    for(auto x : word_count_temp) {\n        if(x.second < 5) {\n            word_count.erase(x.first);\n        }\n        }*/\n    pos--; // to have last index of pos as pos_max\n}\n\n    \nvoid PrintWordCount(hashmap_t const &word_count){\n    for(auto x : word_count){\n        std::cout << x.first << \" \" <<x.second<< std::endl;\n    }\n}\n\nvoid InsertSpecialTag(hashmap_t &word_count){\n    auto word2vec_sentence_delim = \"</s>\";\n    word_count[word2vec_sentence_delim]=1;\n}\n\nauto MapValues(hashmap_t const &map){\n    std::vector<hashmap_t::mapped_type> values;\n    for(auto x : map){\n        values.push_back(x.second);\n    }\n    return values;\n}\nauto MapKeys(hashmap_t const &map){\n    std::vector<hashmap_t::key_type> values;\n    for(auto x : map){\n        values.push_back(x.first);\n    }\n    return values;\n}\n\nauto Concat(std::vector<std::string> const &words){\n    std::vector<char> vec;\n    for(auto const &x:words){\n        std::copy(x.cbegin(),x.cend(),std::back_inserter(vec));\n        vec.push_back('\\0');\n    }\n    return vec;\n}\nauto ToStrings(std::vector<char> const &concat_words){\n    std::vector<std::string> words;\n    auto it =concat_words.cbegin();\n    auto end=concat_words.cend();\n    while(it!=end){\n        words.push_back(std::string{&(*it)});\n        //std::cout<<std::string{&(*it)}<<std::endl;\n        it=std::find(it, end, '\\0');\n        ++it;\n    }\n    return words;\n}\n}//namespace word2vec\n\n///// Data Structure\n\nbool VCompare(int64_t i, int64_t j) { return (i>j); }\n\n// main function arguments\n\nusing namespace word2vec;\n\nclass Word2Vec {\nprivate:\n    int layer1_size;\n    int window;\n    int num_threads;\n    int iter;\n    int hs, negative;\n    int cbow;\n\n    int min_reduce;\n    int min_count;\n    int64_t vocab_size;\n    int64_t train_words;\n    int64_t word_count_actual;\n    int64_t pos_max;\n\n    float sample;\n    float alpha, starting_alpha;\n    \n    std::string train_file, output_file;\n    std::string save_vocab_file, read_vocab_file;\n\n    std::array<float, exp_table_size> expTable;\n    std::array<int, table_size> table;\n\n    clock_t start;\n\n    std::vector<hashmap_t::key_type> vocab;\n    std::vector<hashmap_t::mapped_type> vocabcn;\n\n    hashmap_t word_cn;\n    std::vector<std::pair<int64_t,std::string>> word_pos;\n    hashmap_t word_idx;\n    \n    std::vector<float> syn0, syn1, syn1neg;\n\npublic:\n    Word2Vec (             \n        std::string train_file, //Use text data from <file> to train the model\n        std::string output_file, //Use <file> to save the resulting word vectors / word clusters\n        unsigned int min_count, //This will discard words that appear less than <int> times; default is 5\n        std::string save_vocab_file, //The vocabulary will be saved to <file>\n        std::string read_vocab_file, //The vocabulary will be read from <file>, not constructed from the training data\n        int layer1_size, //Set size of word vectors; default is 100\n        int window, //Set max skip length between words; default is 5\n        float sample, //Set threshold for occurrence of words. default is 1e-3, useful range is (0, 1e-5) \n        int hs, //Use Hierarchical Softmax; default is 0 (not used)\n        int negative, //Number of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n        int num_threads, //Use <int> threads (default 12)\n        int iter, //Run more training iterations (default 5)\n        float alpha, //Set the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n        int cbow = 0 //Use the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n        ):\n        train_file (train_file),\n        output_file (output_file),\n        save_vocab_file (save_vocab_file),\n        read_vocab_file (read_vocab_file),\n        min_count (min_count),\n        layer1_size (layer1_size),\n        window (window),\n        sample (sample),\n        hs (hs),\n        negative (negative),\n        num_threads (num_threads),\n        iter (iter),\n        alpha (alpha),\n        cbow (cbow)\n    {\n        min_reduce = 1;\n        vocab_size = 0;\n        train_words = 0;\n        word_count_actual = 0;\n        pos_max = 0;\n        \n        //infile = TokenizedFile sinfile{train_file};\n        //auto word_count = WordCount(infile);\n            \n        //auto word_count_values = MapValues(word_count);\n        //auto word_count_keys = MapKeys(word_count);\n\n    };\n    void LearnVocab();\n    //void CreateBinaryTree();\n    void InitUnigramTable();\n    void testFunction();\n    void InitNet();\n    void TrainModelThread(int tid);\n    void TrainModel();\n};\n\nvoid Word2Vec::LearnVocab(){\n\n    std::cout << \"I'm here!\\n\";\n    TokenizedFile infile{train_file};\n    VocabLearn(infile, word_cn, word_pos, pos_max);\n\n    hashmap_t::iterator it = word_cn.begin();\n    while(it != word_cn.end()){\n        if(it -> second < 5){\n            it = word_cn.erase(it);\n        } else {\n            ++it;\n        }\n    }\n    \n    std::cout << \"Vocab Learning is complete.\\n\";\n    vocab = MapKeys(word_cn);\n    vocabcn = MapValues(word_cn);\n\n    std::vector<std::pair<std::string,int64_t>> v;\n    for(int i = 0; i < vocab.size(); i++){\n        v.push_back(std::make_pair(vocab[i],vocabcn[i]));\n    }\n    //std::sort(vocabcn.begin(), vocabcn.end(), VCompare);\n    //std::cout << vocabcn[0] << \" \" << vocabcn[1] << \" \" << vocabcn[2] << std::endl;\n\n    vocab_size = vocabcn.size();\n\n    std::sort(v.begin(), v.end(), [](auto &left, auto &right) {\n    return left.second > right.second;\n    });\n\n    std::cout << v[0].first << std::endl;\n    std::cout << v[0].second << std::endl;\n    \n    int64_t idx = 0;\n    for(auto x : v){\n        word_idx[x.first] = idx;\n        idx++;\n    }\n    std::cout << \"Indexing words is complete.\\n\";\n}\n\nvoid Word2Vec::InitUnigramTable() {\n    unsigned int i;\n    float train_words_pow = 0;\n    float d1;\n    float power = 0.75;\n\n    for(auto w : vocabcn) train_words_pow += pow(w, power);\n    i = 0;\n    d1 = pow(vocabcn[0], power)/train_words_pow;\n    for(unsigned int a = 0; a < table_size; a++){\n        table[a] = i;\n        if(a / (float)table_size > d1){\n            i++;\n            d1 += pow(vocabcn[i],power)/train_words_pow;\n        }\n        if(i >= vocab_size) i = vocab_size -1;\n    }\n\n}  \n\nvoid Word2Vec::testFunction(){\n    //    for(auto x : vocab) std::cout << x << std::endl;\n    for(auto x : word_pos) std::cout << x.first << \"  \" << x.second << std::endl;\n    std::cout << pos_max << std::endl;\n}\n\nvoid Word2Vec::InitNet() {\n\n    unsigned int a, b;\n    \n    boost::mt19937 rand_engine_double;  // rand engine\n    boost::uniform_real<> rand_double(0.0, 1.0);\n    boost::variate_generator<boost::mt19937, boost::uniform_real<>> rand_gen_double(rand_engine_double, rand_double);\n\n    for (int i = 0; i <= exp_table_size; i++) {\n        expTable[i] = exp((i / (double)exp_table_size * 2 - 1) * max_exp);\n        expTable[i] = expTable[i] / (expTable[i] + 1);\n    }\n    \n    syn0.resize(vocab_size * layer1_size);\n    for(auto &x : syn0) x= (rand_gen_double() - 0.5) / layer1_size;\n\n    if(hs) {\n        syn1.resize(vocab_size * layer1_size);\n        for(auto &x : syn1) x=0;\n    }\n    if(negative > 0) {\n        syn1neg.resize(vocab_size * layer1_size);\n        for(auto &x : syn1neg) x=0;\n    }\n\n    //CreateBinaryTree();\n}\n\n\nvoid Word2Vec::TrainModelThread(int tid){\n    int64_t a, b, d, word, last_word, sentence_length = 0, sentence_position = 0;\n    int64_t word_count = 0, last_word_count = 0;\n    std::vector<int64_t> sen(max_sentence_length+1,int64_t{0});//[max_sentence_length + 1];\n    int64_t l1, l2, c, target, label, local_iter = iter;\n    int64_t next_random;\n    float f, g;\n    clock_t now;\n    int64_t pos= 0; // Should be reset.\n    int64_t starting_pos;\n    int64_t cnt;\n\n\n    next_random = 1;\n    //sen.resize(max_sentence_length+1);\n    //std::cout << \"sen = \" << sen.at(max_sentence_length+3) << std::endl;\n    boost::mt19937 rand_engine_int;    // rand engine\n    //boost::uniform_int : min,max is inclusive\n    boost::uniform_int<> rand_int_in_vocab(1,vocab_size-1);\n    boost::variate_generator<boost::mt19937, boost::uniform_int<>> sample_in_vocab(rand_engine_int, rand_int_in_vocab);\n    boost::uniform_int<> rand_int_in_table(0,table_size-1);\n    boost::variate_generator<boost::mt19937, boost::uniform_int<>> sample_in_table(rand_engine_int, rand_int_in_table);\n    boost::uniform_int<> rand_int_in_window(0,window-1);\n    boost::variate_generator<boost::mt19937, boost::uniform_int<>> sample_in_window(rand_engine_int, rand_int_in_window);\n\n    \n\n    \n    boost::mt19937 rand_engine_double;  // rand engine\n    boost::uniform_real<> rand_double(0.0, 1.0);\n    boost::variate_generator<boost::mt19937, boost::uniform_real<>> rand_gen_double(rand_engine_double, rand_double);\n    \n    std::vector<float> neu1;\n    std::vector<float> neu1e;\n\n    neu1.resize(layer1_size);\n    neu1e.resize(layer1_size);\n\n    //inFile.seekg(file_size / (int64_t)num_threads * (int64_t)tid);\n    starting_pos = pos_max / (int64_t)num_threads * (int64_t)tid;\n    pos = starting_pos;\n    std::cout << pos << std::endl;fflush(stdout);\n    while(1) {\n        \n        if(word_count - last_word_count > 10000) {\n            word_count_actual += word_count - last_word_count;\n            last_word_count = word_count;\n            \n            now = clock();\n            printf(\"%cAlpha: %f  Progress: %.2f%%  Words/thread/sec: %.2fk   \", 13, alpha,\n                    word_count_actual / (double)(iter * pos_max + 1) * 100,\n                    word_count_actual / ((double)(now - start + 1) / (double)CLOCKS_PER_SEC * 1000));\n            fflush(stdout);\n            \n            alpha = starting_alpha * (1 - word_count_actual / (double)(iter * pos_max + 1));\n            if(alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;\n        }\n        \n        if(sentence_length == 0) { \n            while(1) {\n                if(pos>=pos_max) break;\n\n                if(word_idx.find(word_pos[pos].second) == word_idx.end()){\n                    pos++;\n                    continue;\n                }\n                word_count++;\n                //if(word == 0) break;\n                cnt = word_cn.find(word_pos[pos].second) -> second; // log(n)\n                 // The subsampling randomly discards frequent words while keeping the ranking same\n                if(sample > 0) {\n                    double ran = (sqrt(cnt / (sample * pos_max)) + 1) * (sample * pos_max) / cnt;\n                    if(ran < rand_gen_double()) {\n                        pos++;\n                        continue;\n                    }\n                }\n                    \n                sen[sentence_length] = word_idx.find(word_pos[pos].second) -> second;//word_cn.find(word_pos[pos].second);\n                pos++;\n                sentence_length++;\n                if(sentence_length >= max_sentence_length) break;\n            }\n            sentence_position = 0;\n        }\n    \n    \n    \n        \n        if((pos>=pos_max) || (word_count > pos_max / (int64_t)num_threads )) {\n            word_count_actual += word_count - last_word_count;\n            local_iter--;\n            if(local_iter == 0) break;\n            word_count = 0;\n            last_word_count = 0;\n            sentence_length = 0;\n            pos = starting_pos;\n            continue;\n        }\n        \n        word = sen[sentence_position];\n        //if(word == -1) continue;\n        // Network Initialization\n        for(auto &x:neu1) x = 0;\n        for(auto &x:neu1e) x = 0;\n\n        b = sample_in_window();\n        for(a = b; a < window * 2 + 1 - b; a++) if(a != window) {\n                c = sentence_position - window + a;\n                if(c < 0) continue;\n                if(c >= sentence_length) continue;\n                last_word = sen[c];\n                if(last_word == -1) continue;\n                l1 = last_word * layer1_size;\n                // Hierarchical Softmax\n                /*if(hs) for(d = 0; d < vocab[word].codelen; d++) {\n                    f = 0;\n                    l2 = vocab[word].point[d] * layer1_size;\n                    // Propagate hidden -> output\n                    for(c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2];\n                    if(f <= -MAX_EXP) continue;\n                    else if(f >= MAX_EXP) continue;\n                    else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];\n                    // g is the gradient multiplied by the learning rate\n                    g = (1 - vocab[word].code[d] - f) * alpha;\n                    // Backpropagate errors output -> hidden\n                    for(c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];\n                    // Learn weights hidden -> output\n                    for(c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c +l1];\n                    }*/\n                // Negative Sampling\n                if(negative > 0) for (d = 0; d < negative + 1 ; d++) {\n                        if(d == 0) {\n                            target = word;\n                            label = 1;\n                        } else {\n                            //next_random = sample_in_table();\n                            //target = table[next_random];\n                            //if(target == 0) target = next_random % (vocab_size - 1) + 1;\n                            target = table[sample_in_table()];\n                            //if(target == 0) target = sample_in_vocab();\n                            if(target == word) continue;\n                            target = sample_in_vocab();\n                            label = 0;\n                        }\n\n                        l2 = target * layer1_size;\n                        f = 0;\n\n                        for(c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];\n                        \n                        if(f > max_exp) g = (label - 1) * alpha;\n                        else if(f < - max_exp) g = (label - 0) * alpha;\n                        else g = (label - expTable[(int)((f + max_exp) * (exp_table_size / max_exp / 2))]) * alpha;\n\n                        for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];\n                        for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];\n                    }\n                // Learn weights input -> hidden\n                for(c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];\n            }\n        sentence_position++;\n        if(sentence_position >= sentence_length) {\n            sentence_length = 0;\n            continue;\n        }\n        \n    }\n}\n\n\n\nvoid Word2Vec::TrainModel() {\n    std::ofstream outFile;\n\n    std::vector<std::thread> th;\n    starting_alpha = alpha;\n\n    std::cout << \"Starting training using file \" << train_file << std::endl;\n    if(output_file[0] == 0) return;\n\n    // Initialization\n    InitNet();\n    if(negative > 0)\n        InitUnigramTable();\n\n    start = clock(); // start to measure time\n\n    for(int i = 0; i < num_threads; i++) {\n      th.push_back(std::thread(&Word2Vec::TrainModelThread, this, i));\n    }\n\n    for(auto &t : th) {\n      t.join();\n    }\n\n    //TrainModelThread(); // For the single thread\n\n    outFile.open(output_file, std::ofstream::out);\n    outFile << vocab_size << \" \" << layer1_size << std::endl;\n    for(auto x : word_idx) {\n        outFile << x.first << \" \";\n        for(unsigned int b = 0; b < layer1_size; b++) outFile << syn0[x.second * layer1_size + b] << \" \";\n        outFile << std::endl;\n    }\n    \n    auto word_concat = Concat(MapKeys(word_idx));\n    //syn0: beg=syn0[idx*dim], end=syn0[(idx+1)*dim];\n    H5file file{H5name{\"data.h5\"}, hdf5::FileMode::replace};\n    file.writeRawData(H5name{std::string{\"foo.vec\" }}, syn0); \n    //TODO: check if syn0 and word_concat has consistantly ordered.\n    file.writeRawData(H5name{std::string{\"foo.word\"}}, word_concat);//it was vocab, which was the cause of compile error.  \n}\n\n// End of Learning Net\n\n\n\n\nvoid printHelp() {\n    std::cout << \"c++ word2vector implementation \\n\\n\";\n    std::cout << \"Options:\\n\";\n    std::cout << \"Parameters for training:\\n\";\n    std::cout << \"\\t-train <file>\\n\";\n    std::cout << \"\\t\\tUse text data from <file> to train the model\\n\";\n    std::cout << \"\\t-output <file>\\n\";\n    std::cout << \"\\t\\tUse <file> to save the resulting word vectors / word clusters\\n\";\n    std::cout << \"\\t-size <int>\\n\";\n    std::cout << \"\\t\\tSet size of word vectors; default is 100\\n\";\n    std::cout << \"\\t-window <int>\\n\";\n    std::cout << \"\\t\\tSet max skip length between words; default is 5\\n\";\n    std::cout << \"\\t-sample <float>\\n\";\n    std::cout << \"\\t\\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\\n\";\n    std::cout << \"\\t\\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\\n\";\n    std::cout << \"\\t-hs <int>\\n\";\n    std::cout << \"\\t\\tUse Hierarchical Softmax; default is 0 (not used)\\n\";\n    std::cout << \"\\t-negative <int>\\n\";\n    std::cout << \"\\t\\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\\n\";\n    std::cout << \"\\t-threads <int>\\n\";\n    std::cout << \"\\t\\tUse <int> threads (default 12)\\n\";\n    std::cout << \"\\t-iter <int>\\n\";\n    std::cout << \"\\t\\tRun more training iterations (default 5)\\n\";\n    std::cout << \"\\t-min-count <int>\\n\";\n    std::cout << \"\\t\\tThis will discard words that appear less than <int> times; default is 5\\n\";\n    std::cout << \"\\t-alpha <float>\\n\";\n    std::cout << \"\\t\\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\\n\";\n    std::cout << \"\\t-save-vocab <file>\\n\";\n    std::cout << \"\\t\\tThe vocabulary will be saved to <file>\\n\";\n    std::cout << \"\\t-read-vocab <file>\\n\";\n    std::cout << \"\\t\\tThe vocabulary will be read from <file>, not constructed from the training data\\n\";\n    std::cout << \"\\t-cbow <int>\\n\";\n    std::cout << \"\\t\\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\\n\";\n    std::cout << \"\\nExamples:\\n\";\n    std::cout << \"./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\\n\\n\";\n\n}\n\nint argpos(const char *str, int argc, char **argv) {\n    std::string s_str(str);\n    std::vector<std::string> s_argv(argv,argv+argc);\n\n    int i=0;\n    while (i<argc) {\n        if(s_str == s_argv[i]) break;\n        i++;\n    }\n    if(i == argc) i=0;\n\n    return i;\n}\n\nWord2Vec *arg_to_w2v(int argc, char **argv) {\n\n    int i;\n    int layer1_size = 100;\n    std::string train_file =\"\", save_vocab_file = \"\", read_vocab_file = \"\";\n    int debug_mode =2, binary = 0, cbow = 0;\n    float alpha = 0.05;\n    std::string output_file = \"\";\n    int window = 5;\n    float sample = 1e-3;\n    int hs = 0, negative = 5, num_threads = 12;\n    int64_t iter = 5;\n    int min_count = 5;\n    int64_t classes = 0;\n    std::string wordvector_file = \"\";\n    \n    \n    if ((i = argpos(\"-size\", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);\n    if ((i = argpos(\"-train\", argc, argv)) > 0) train_file = argv[i + 1];\n    if ((i = argpos(\"-save-vocab\", argc, argv)) > 0) save_vocab_file = argv[i + 1];\n    if ((i = argpos(\"-read-vocab\", argc, argv)) > 0) read_vocab_file = argv[i + 1];\n    if ((i = argpos(\"-cbow\", argc, argv)) > 0) cbow = atoi(argv[i + 1]);\n    if (cbow) alpha = 0.05; else alpha = 0.025;\n    if ((i = argpos(\"-alpha\", argc, argv)) > 0) alpha = atof(argv[i + 1]);\n    if ((i = argpos(\"-output\", argc, argv)) > 0) output_file = argv[i + 1];\n    if ((i = argpos(\"-window\", argc, argv)) > 0) window = atoi(argv[i + 1]);\n    if ((i = argpos(\"-sample\", argc, argv)) > 0) sample = atof(argv[i + 1]);\n    if ((i = argpos(\"-hs\", argc, argv)) > 0) hs = atoi(argv[i + 1]);\n    if ((i = argpos(\"-negative\", argc, argv)) > 0) negative = atoi(argv[i + 1]);\n    if ((i = argpos(\"-threads\", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);\n    if ((i = argpos(\"-iter\", argc, argv)) > 0) iter = atoi(argv[i + 1]);\n    if ((i = argpos(\"-min-count\", argc, argv)) > 0) min_count = atoi(argv[i + 1]);\n\n    Word2Vec *w2v = new Word2Vec (             \n                train_file, \n                output_file, \n                min_count, \n                save_vocab_file, \n                read_vocab_file, \n                layer1_size, \n                window, \n                sample, \n                hs, \n                negative, \n                num_threads, \n                iter, \n                alpha,\n                cbow );\n\n    return w2v;\n}\n\nint main(int argc, char **argv) {\n\n\n    \n    //std::vector<char> concat_words = Concat(word_count_keys);\n    \n    //PrintWordCount(word_count);\n\n    \n    //H5file file{H5name{\"data.h5\"}, hdf5::FileMode::read_exist};\n    //file.writeRawData(H5name{\"bar.word_count\"},word_count_values);\n    //file.writeRawData(H5name{\"bar.word_key\"},concat_words);\n    \n    //concat_read = file.readRawData(H5name{\"bar.word_key\"},concat_words); \n    //auto words = ToStrings(concat_read);\n    //assert(words=word_count_keys);\n    \n    Word2Vec *w2v;\n    \n    if(argc < 2) { printHelp(); return 1; }\n    else {\n        w2v = arg_to_w2v(argc, argv);\n    }\n    w2v -> LearnVocab();\n    //w2v -> testFunction();\n    w2v->TrainModel();\n\n    return 0;\n}\n", "meta": {"hexsha": "9241ce4c8fffda8262506de8603765632d0f5cf1", "size": 22989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "word2vec/app/wordvec_trainer.cpp", "max_stars_repo_name": "uphere-co/nlp-prototype", "max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "word2vec/app/wordvec_trainer.cpp", "max_issues_repo_name": "uphere-co/nlp-prototype", "max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "word2vec/app/wordvec_trainer.cpp", "max_forks_repo_name": "uphere-co/nlp-prototype", "max_forks_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7082111437, "max_line_length": 143, "alphanum_fraction": 0.5578755057, "num_tokens": 6280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.041462274191957464, "lm_q1q2_score": 0.017676262159735695}}
{"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_HASH_HAIFA_CONSTRUCTION_HPP\n#define CRYPTO3_HASH_HAIFA_CONSTRUCTION_HPP\n\n#include <boost/crypto3/hash/detail/nop_finalizer.hpp>\n\n#include <boost/crypto3/detail/static_digest.hpp>\n#include <boost/crypto3/detail/pack.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            /*!\n             * @brief\n             * @tparam DigestEndian\n             * @tparam DigestBits\n             * @tparam IV\n             * @tparam Compressor\n             * @tparam Finalizer\n             *\n             * The HAIFA construction builds a block hashes from a\n             * one-way compressor.  As this version operated on the block\n             * level, it doesn't contain any padding or other strengthening.\n             * For a Wide Pipe construction, use a digest that will\n             * truncate the internal state.\n             *\n             * @note https://eprint.iacr.org/2007/278.pdf\n             */\n            template<typename Params, typename IV, typename Compressor, typename Padding,\n                     typename Finalizer = detail::nop_finalizer>\n            class haifa_construction {\n            public:\n                typedef Compressor compressor_functor;\n                typedef Padding padding_functor;\n                typedef Finalizer finalizer_functor;\n\n                typedef typename Params::digest_endian endian_type;\n\n                constexpr static const std::size_t salt_bits = compressor_functor::salt_bits;\n                typedef typename compressor_functor::salt_type salt_type;\n                constexpr static const salt_type salt_value = compressor_functor::salt_value;\n\n                typedef typename compressor_functor::iv_generator iv_generator;\n\n                constexpr static const std::size_t word_bits = compressor_functor::word_bits;\n                typedef typename compressor_functor::word_type word_type;\n\n                constexpr static const std::size_t state_bits = compressor_functor::state_bits;\n                constexpr static const std::size_t state_words = compressor_functor::state_words;\n                typedef typename compressor_functor::state_type state_type;\n\n                constexpr static const std::size_t block_bits = compressor_functor::block_bits;\n                constexpr static const std::size_t block_words = compressor_functor::block_words;\n                typedef typename compressor_functor::block_type block_type;\n\n                constexpr static const std::size_t digest_bits = Params::digest_bits;\n                constexpr static const std::size_t digest_bytes = digest_bits / octet_bits;\n                constexpr static const std::size_t digest_words =\n                    digest_bits / word_bits + ((digest_bits % word_bits) ? 1 : 0);\n                typedef static_digest<digest_bits> digest_type;\n\n            protected:\n                constexpr static const std::size_t length_bits = Params::length_bits;\n                // FIXME: do something more intelligent than capping at 64\n                constexpr static const std::size_t length_type_bits =\n                    length_bits < word_bits ? word_bits : length_bits > 64 ? 64 : length_bits;\n                typedef typename boost::uint_t<length_type_bits>::least length_type;\n                constexpr static const std::size_t length_words = length_bits / word_bits;\n                BOOST_STATIC_ASSERT(!length_bits || length_bits % word_bits == 0);\n\n            public:\n                template<typename Integer = std::size_t>\n                inline haifa_construction &process_block(const block_type &block, Integer seen,\n                                                         Integer finalization = 0) {\n                    compressor_functor::process_block(state_, block, seen, finalization);\n                    return *this;\n                }\n\n                inline digest_type digest(const block_type &block = block_type(),\n                                          std::size_t total_seen = length_type()) {\n                    using namespace boost::crypto3::detail;\n\n                    block_type b = block;\n                    // Process block if it is full\n                    if (total_seen && !(total_seen % block_bits))\n                        process_block(b, total_seen);\n\n                    // Pad last message block\n                    padding_functor padding;\n                    padding(b, total_seen);\n\n                    // Process last block\n                    process_block(b, total_seen, salt_value);\n\n                    // Apply finalizer\n                    finalizer_functor()(state_);\n\n                    // Convert digest to byte representation\n                    std::array<octet_type, state_bits / octet_bits> d_full;\n                    pack_from<endian_type, word_bits, octet_bits>(state_.begin(), state_.end(), d_full.begin());\n                    digest_type d;\n                    std::copy(d_full.begin(), d_full.begin() + digest_bytes, d.begin());\n\n                    return d;\n                }\n\n                haifa_construction() {\n                    reset();\n                }\n\n                void reset(const state_type &s) {\n                    state_ = s;\n                    state_[0] ^= 0x01010000U ^ (digest_bits / CHAR_BIT);\n                }\n\n                void reset() {\n                    iv_generator iv;\n                    reset(iv());\n                }\n\n                state_type const &state() const {\n                    return state_;\n                }\n\n            private:\n                state_type state_;\n            };\n\n        }    // namespace hashes\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_HASH_HAIFA_CONSTRUCTION_HPP\n", "meta": {"hexsha": "446d8cc707752bf9669b6e0f348b12906dc2259c", "size": 6180, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/detail/haifa_construction.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/hash/detail/haifa_construction.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/hash/detail/haifa_construction.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 43.5211267606, "max_line_length": 112, "alphanum_fraction": 0.5566343042, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790695, "lm_q2_score": 0.03676946660336021, "lm_q1q2_score": 0.01766694470610918}}
{"text": "//   -----------------------------------------------------------------------------------------------\n//    Copyright 2015 André Bergner. Distributed under the Boost Software License, Version 1.0.\n//     (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//      --------------------------------------------------------------------------------------------\n\n#include <iostream>\n#include <array>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/min_max.hpp>\n#include <boost/typeof/typeof.hpp>\n#include <boost/proto/core.hpp>\n#include <boost/proto/context.hpp>\n#include <boost/proto/transform.hpp>\n#include <boost/proto/debug.hpp>\n\n#include <boost/algorithm/string/erase.hpp>\n\n#include \"callable_decltype.hpp\"\n#include \"tuple_tools.hpp\"\n#include \"demangle.h\"\n\n\nnamespace mpl = boost::mpl;\nnamespace proto = boost::proto;\n\n\ntemplate< typename S >\nvoid print_state( S const & s)\n{\n   auto s_name = type_name(s);\n   boost::erase_all( s_name, \"std::__1::\" );\n   boost::erase_all( s_name, \"mpl_::\" );\n   std::cout << s_name << std::endl;\n}\n\n\nnamespace building_blocks\n{\n   using namespace proto;\n\n   //  ---------------------------------------------------------------------------------------------\n   // definition of the building blocks of the language\n   //  ---------------------------------------------------------------------------------------------\n\n   template < typename I >  struct placeholder       { using arity = I; };\n   template < typename T >  struct placeholder_arity { using type = typename T::arity; };\n\n   template < typename idx = _ >\n   using delayed_placeholder = subscript< terminal<placeholder<idx>> , terminal<placeholder<_>> >;\n\n   //  ---------------------------------------------------------------------------------------------\n   // block composition operators -- TODO needs correct grammar as arguments\n\n   using channel_operator  = comma              < _ , _ >;\n   using parallel_operator = bitwise_or         < _ , _ >;\n   using sequence_operator = bitwise_or_assign  < _ , _ >;\n   using feedback_operator = complement         < _ >;\n}\n\nusing building_blocks :: placeholder;\nusing building_blocks :: placeholder_arity;\nusing building_blocks :: delayed_placeholder;\n\nusing building_blocks :: channel_operator;\nusing building_blocks :: sequence_operator;\nusing building_blocks :: parallel_operator;\nusing building_blocks :: feedback_operator;\n\n\nBOOST_PROTO_DEFINE_ENV_VAR( current_input_t, current_input );\nBOOST_PROTO_DEFINE_ENV_VAR( delayed_input_t, delayed_input );\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// very simple delay_line operation on std::array --> TODO should be own type static_delay_line !\n\nstruct no_state {};\n\nstruct\n{\n    template< typename T , size_t N , typename Y >\n    void operator()( std::array<T,N>& xs , Y y ) const\n    {\n        for ( size_t n = 1 ; n < xs.size() ; ++n )  xs[n-1] = xs[n];\n        xs.back() = y;\n    }\n\n    template< typename T , typename Y >\n    void operator()( std::array<T,0>& , Y ) const { }\n\n    template< typename T , typename Y >\n    void operator()( no_state , Y ) const { }\n\n    template< typename T , typename Y >   // if input is not an array, e.g. for not fully\n    void operator()( T& , Y ) const { }   // unpacked state while traversing the tree (tuple o'tuples)\n}\nrotate_push_back;\n\n\n\nnamespace transforms\n{\n   using namespace proto;\n\n   //  ---------------------------------------------------------------------------------------------\n   // static analysis transforms  --  helpers that inspect structure of expression\n   //  ---------------------------------------------------------------------------------------------\n\n   struct output_arity;\n\n   struct input_arity : or_\n   <  when\n      <  delayed_placeholder<>\n      ,  placeholder_arity<_value(_left)>()\n      >\n   ,  when\n      <  terminal< placeholder<_> >\n      ,  placeholder_arity<_value>()\n      >\n   ,  when\n      <  terminal<_>\n      ,  mpl::int_<0>()\n      >\n   ,  when\n      <  feedback_operator\n      ,  mpl::max\n         <  mpl::int_<0>\n         ,  mpl::minus< input_arity(_child) , output_arity(_child) >\n         >()\n      >\n   ,  when\n      <  parallel_operator\n      ,  mpl::plus< input_arity(_left) , input_arity(_right) >()\n      >\n   ,  when\n      <  sequence_operator\n      ,  mpl::plus\n         <  input_arity(_left)\n         ,  mpl::max\n            <  mpl::int_<0>\n            ,  mpl::minus< input_arity(_right) , output_arity(_left) >\n            >\n         >()\n      >\n   ,  when\n      <  nary_expr<_, vararg<_>>\n      ,  fold<_, mpl::int_<0>(), mpl::max<input_arity, _state>()>\n      >\n   >\n   {};\n\n\n   struct output_arity : or_\n   <  when\n      <  channel_operator\n      ,  mpl::plus< output_arity(_left) , output_arity(_right) >()\n      >\n   ,  when\n      <  feedback_operator\n      ,  output_arity(_child)\n      >\n   ,  when\n      <  parallel_operator\n      ,  mpl::plus< output_arity(_left) , output_arity(_right) >()\n      >\n   ,  when\n      <  sequence_operator\n      ,  mpl::plus\n         <  output_arity(_right)\n         ,  mpl::max\n            <  mpl::int_<0>\n            ,  mpl::minus< output_arity(_left) , input_arity(_right) >\n            >\n         >()\n      >\n   ,  otherwise< mpl::int_<1>() >\n   >\n   {};\n\n\n   template < typename Expr >\n   using input_arity_t = typename boost::result_of<input_arity(Expr)>::type;\n\n   template < typename Expr >\n   using output_arity_t = typename boost::result_of<output_arity(Expr)>::type;\n\n\n\n\n   // -------------------------------------------------------------------------------------------\n   // state and wire related tuple tools\n   // -------------------------------------------------------------------------------------------\n\n   template < typename arity , typename delay = mpl::int_<0> >\n   struct make_arity_impl\n   {\n      using type = tuple_cat_t< repeat_t< arity::value-1ul, mpl::int_<0> >\n                              , std::tuple<delay>\n                              >;\n   };\n\n   template < typename delay >\n   struct make_arity_impl<mpl::int_<0>, delay>\n   {\n      using type = std::tuple<>;\n   };\n\n   template < typename arity , typename delay = mpl::int_<0> >\n   using make_arity = typename make_arity_impl<arity,delay>::type;\n\n\n   struct delay_per_wire : callable_decltype\n   {\n      using default_t = placeholder<mpl::int_<0>>;\n\n      template < typename Placeholder = default_t , typename Delay = default_t>\n      auto operator()( Placeholder const & = default_t{}, Delay const & = default_t{} ) const\n      {\n         return make_arity<typename Placeholder::arity, typename Delay::arity>{};\n      }\n   };\n\n   struct tuple_cat_fn : callable_decltype\n   {\n      template < typename... Tuples >\n      auto operator()( Tuples&&... ts ) const\n      {\n         return std::tuple_cat( std::forward<Tuples>(ts)... );\n      }\n   };\n\n   struct make_tuple_fn : callable_decltype\n   {\n      template < typename... Ts >\n      auto operator()( Ts&&... ts ) const\n      {\n         return std::make_tuple( std::forward<Ts>(ts)... );\n      }\n   };\n\n   // -------------------------------------------------------------------------------------------\n   // max-zip tuple\n   // -------------------------------------------------------------------------------------------\n\n   template < typename Tuple1, typename Tuple2, std::size_t... Ns >\n   auto zip_with_max( Tuple1&& t1, Tuple2&& t2, std::index_sequence<Ns...> )\n   {\n      using namespace std;\n      return tuple< typename mpl::max< decay_t<decltype(get<Ns>(t1))> , decay_t<decltype(get<Ns>(t2))> >::type... >{};\n   }\n\n   template < typename Tuple1, typename Tuple2 >\n   auto zip_with_max( Tuple1&&, Tuple2&&, std::index_sequence<> )\n   {\n      return std::tuple<>{};\n   }\n\n   struct max_delay_of_wires : callable_decltype\n   {\n      template < typename Tuple_l , typename Tuple_r >\n      auto operator()( Tuple_l&& tl, Tuple_r&& tr ) const\n      {\n         using tuple_tl = std::decay_t<Tuple_l>;\n         using tuple_tr = std::decay_t<Tuple_r>;\n         using min_size = typename mpl::min< mpl::int_<std::tuple_size<tuple_tl>::value>\n                                           , mpl::int_<std::tuple_size<tuple_tr>::value>\n                                           >::type;\n         return  std::tuple_cat(  zip_with_max(tl,tr,std::make_index_sequence<min_size::value>{})\n                               ,  tuple_drop<min_size::value>( std::forward<Tuple_l>(tl) )\n                               ,  tuple_drop<min_size::value>( std::forward<Tuple_r>(tr) )\n                               );\n      }\n   };\n\n   struct tuple_take_ : callable_decltype\n   {\n      template< typename Drop , typename Tuple >\n      decltype(auto) operator()( Drop , Tuple const & t ) const\n      {\n         return tuple_take<Drop::value>(t);\n      }\n   };\n\n   struct tuple_drop_ : callable_decltype\n   {\n      template< typename Drop , typename Tuple >\n      decltype(auto) operator()( Drop , Tuple const & t ) const\n      {\n         return tuple_drop<Drop::value>(t);\n      }\n   };\n\n   struct input_delays : or_\n   <  when\n      <  delayed_placeholder<>\n      ,  delay_per_wire( _value(_left),_value(_right))\n      >\n   ,  when\n      <  terminal< placeholder<_> >\n      ,  delay_per_wire( _value() )\n      >\n   ,  when\n      <  terminal<_>\n      ,  std::tuple<>()//delay_per_wire()\n      >\n   ,  when\n      <  feedback_operator\n      ,  tuple_drop_\n         (  output_arity(_child)\n         ,  input_delays(_child)\n         )\n      >\n   ,  when\n      <  parallel_operator\n      ,  tuple_cat_fn( input_delays(_left) , input_delays(_right) )\n      >\n   ,  when\n      <  sequence_operator\n      ,  tuple_cat_fn\n         (  input_delays(_left)\n         ,  tuple_drop_\n            (  output_arity(_left)\n            ,  input_delays(_right)\n            )\n         )\n      >\n   ,  when\n      <  nary_expr<_, vararg<_>>\n      ,  fold<_, std::tuple<>(), max_delay_of_wires(input_delays, _state) >\n      >\n   >\n   {};\n\n\n   struct identity : callable_decltype\n   {\n      template < typename X >\n      auto operator()( X&& x ) { return std::forward<X>(x); }\n   };\n\n   template < typename StateCtor >\n   struct build_state_impl\n   {\n      struct apply : or_\n      <  when\n         <  feedback_operator\n         ,  make_tuple_fn\n            (  StateCtor\n               (  tuple_take_\n                  ( output_arity(_child)\n                  , input_delays(_child)\n                  )\n               )\n            ,  apply( _child  )\n            )\n         >\n      ,  when\n         <  sequence_operator\n         ,  make_tuple_fn\n            (  StateCtor(input_delays( _right  ))\n            ,  apply( _left  )\n            ,  apply( _right )\n            )\n         >\n      ,  when\n         <  parallel_operator\n         ,  make_tuple_fn\n            (  apply( _left  )\n            ,  apply( _right )\n            )\n         >\n      ,  otherwise< std::tuple<>() >\n      >\n      {};\n   };\n\n   template < typename StateCtor = identity >\n   using build_state = typename build_state_impl<StateCtor>::apply;\n\n\n   //  ---------------------------------------------------------------------------------------------\n   // Evaluators -- transforms that work together for the evaluation of flowz-expressions\n   //  ---------------------------------------------------------------------------------------------\n\n   struct place_the_holder;\n   struct place_delay;\n   struct sequence;\n   struct feedback;\n   struct parallel;\n\n\n   struct eval_it : or_\n   <  when\n      <  delayed_placeholder<>\n      ,  place_delay( _value(_left) , _value(_right) , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  terminal< placeholder<_> >\n      ,  place_the_holder( _value , _env_var<current_input_t> )\n      >\n   ,  when\n      <  feedback_operator\n      ,  feedback( _child , _env_var<current_input_t> , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  sequence_operator\n      ,  sequence( _left , _right , _env_var<current_input_t> , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  parallel_operator\n      ,  parallel( _left , _right , _env_var<current_input_t> , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  channel_operator    //  grammar rule: only allowed after sequence or recursion at top of sub-tree\n      ,  make_tuple_fn( eval_it(_left), eval_it(_right) )\n      >\n   ,  when\n      <  _\n      ,  _default< eval_it >\n      >\n   >\n   {};\n\n\n   //-----------------------------------------------------------------------------------------------\n\n\n   template < typename T >\n   using in_t = T const &;\n   //using in_t = T;\n\n   struct place_the_holder : callable_decltype\n   {\n      template < typename I , typename Tuple >\n      auto operator()( placeholder<I> const & , Tuple const & args ) const\n      {\n         return std::get<I::value-1>( args );\n      }\n   };\n\n   struct place_delay : callable_decltype\n   {\n      template < typename I , typename J , typename Delayed_input >\n      auto operator()( placeholder<I> , placeholder<J> , in_t<Delayed_input> del_in ) const\n      {\n         auto const & s = std::get<I::value-1>(std::get<0>(del_in));\n         return s[s.size()-J::value];\n      }\n   };\n\n   struct sequence : callable_decltype\n   {\n      template < typename LeftExpr , typename RightExpr , typename Input , typename State >\n      auto operator()( in_t<LeftExpr> l , in_t<RightExpr> r , in_t<Input> input , State state ) const\n      {\n         eval_it  e;\n\n         auto in_state    = std::get<0>(state);\n         auto node_state  = std::get<0>(std::get<1>(state));\n         auto& left_state  = std::get<1>(std::get<1>(state));\n         auto& right_state = std::get<2>(std::get<1>(state));\n\n         auto left_result =\n            flatten_tuple( std::make_tuple(\n               e( l, 0, ( current_input = tuple_take<input_arity_t<LeftExpr>::value>(input) , delayed_input = std::tie(in_state,left_state) ))\n            ));\n\n         using left_size = std::tuple_size<decltype(left_result)>;\n         auto right_input = tuple_cat( left_result, tuple_drop<left_size::value>(input) );\n\n         auto right_result =\n            flatten_tuple( std::make_tuple(\n               e( r, 0, ( current_input = right_input , delayed_input = std::tie(node_state,right_state) ))\n            ));\n\n         tuple_for_each( rotate_push_back, node_state, left_result );\n         using right_size = std::tuple_size<decltype(right_result)>;\n         return tuple_cat( right_result, tuple_drop<right_size::value>(std::move(left_result)) );\n      }\n   };\n\n\n   struct bottom_type {};\n\n   struct feedback : callable_decltype\n   {\n      template < typename Expr , typename Input , typename State >\n      auto operator()( in_t<Expr> x , in_t<Input> input , State state ) const\n      {\n         eval_it  e;\n\n         auto in_state    = deep_tie(std::get<0>(state));\n         auto node_state  = deep_tie(std::get<0>(std::get<1>(state)));\n         auto child_state = deep_tie(std::get<1>(std::get<1>(state)));\n         auto next_state  = std::tuple_cat( node_state, in_state );\n\n         auto aligned_input = std::tuple_cat( repeat_t<output_arity_t<Expr>::value, bottom_type>{} , input );\n         auto result =\n            flatten_tuple( std::make_tuple(\n               e( x, 0, ( current_input = aligned_input , delayed_input = std::tie(next_state,child_state) ))\n            ));\n\n\n         tuple_for_each( rotate_push_back, node_state, std::tuple_cat( result, input) );\n         using size = std::tuple_size<decltype(result)>;\n         return tuple_cat( result, tuple_drop<size::value>(input) );\n      }\n   };\n\n\n   struct parallel : callable_decltype\n   {\n      template < typename LeftExpr , typename RightExpr , typename Input , typename State >\n      auto operator()( in_t<LeftExpr> l , in_t<RightExpr> r , in_t<Input> input , State state ) const\n      {\n         eval_it  e;\n\n         auto in_state    = deep_tie(std::get<0>(state));\n         auto left_state  = deep_tie(std::get<0>(std::get<1>(state)));\n         auto right_state = deep_tie(std::get<1>(std::get<1>(state)));\n\n         auto in_state_l = tuple_take<input_arity_t<LeftExpr>::value>(in_state);\n         auto left_state_  = ( current_input = tuple_take<input_arity_t<LeftExpr>::value>(input)\n                             , delayed_input = std::tie(in_state_l,left_state)\n                             );\n\n         auto in_state_r = tuple_drop<input_arity_t<LeftExpr>::value>(in_state);\n         auto right_state_ = ( current_input = tuple_drop<input_arity_t<LeftExpr>::value>(input)\n                             , delayed_input = std::tie(in_state_r,right_state)\n                             );\n         return std::make_tuple\n                (  e( l, 0, left_state_ )\n                ,  e( r, 0, right_state_ )\n                );\n      }\n   };\n\n}\n\n\nusing  transforms :: input_arity;\nusing  transforms :: input_delays;\nusing  transforms :: build_state;\nusing  transforms :: input_arity_t;\nusing  transforms :: output_arity;\nusing  transforms :: eval_it;\n\n\n//  ------------------------------------------------------------------------------------------------\n// supporting state tools\n//  ------------------------------------------------------------------------------------------------\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// lift_into_tuple  --  lifts a meta-function into a tuple,\n//                      i.e. applies it on each type in tuple, returns tuple of new types\n\ntemplate< typename F , typename Tuple >\nstruct lift_into_tuple;\n\ntemplate< typename F , typename... Ts >\nstruct lift_into_tuple< F , std::tuple<Ts...> >\n{\n    using type = std::tuple< typename F::template apply_t<Ts>... >;\n};\n\ntemplate< typename F , typename Tuple >\nusing lift_into_tuple_t = typename lift_into_tuple<F,Tuple>::type;\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// to_array  --  meta-function that maps mpl::int_<N> to array<T,N>\n\ntemplate< typename T , typename Int >\nstruct to_array_impl\n{\n   using type = std::array< T , std::decay_t<Int>::value >;\n};\n\ntemplate< typename T >\nstruct to_array_impl< T, mpl::int_<0> >\n{\n   using type = no_state;     // array<T,N> prevents empty base class optimization to kick in.\n};\n\n\ntemplate< typename T >\nstruct to_array\n{\n   template< typename Int >\n   using apply_t = typename to_array_impl<T,Int>::type;\n};\n\ntemplate < typename T >\nstruct to_array_tuple\n{\n   struct apply : proto::callable_decltype\n   {\n       template< typename Tuple >\n       auto operator()( Tuple ) { return lift_into_tuple_t< to_array<T>, Tuple > {}; }\n   };\n};\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// compile  --  main function of framework\n//              • takes an expression\n//              • returns clojure\n//  ------------------------------------------------------------------------------------------------\n\ntemplate\n<  typename Expression\n,  typename State\n,  size_t   arity\n>\nstruct stateful_lambda\n{\nprivate:\n\n   Expression  expr_;\n   State       state_;\n\n   template < typename... Args >\n   auto call_impl( mpl::int_<0> , Args const &... args ) -> decltype(auto)\n   {\n      std::tuple<> in_state;\n      auto in_tuple = std::tie(in_state,state_);\n      auto result = eval_it{}( expr_, 0, ( current_input = std::make_tuple(args...)\n                                         , delayed_input = boost::ref(in_tuple) ) );\n      return flatten_tuple( std::make_tuple( result ));\n   }\n\n   template < int arg_diff , typename... Args >\n   auto call_impl( mpl::int_<arg_diff> , Args const &... args )\n   {\n      return [ args...\n             , expr = *this ]           // TODO should not be a lambda, but a type that is\n      ( auto const &... missing_args ) mutable  //      aware of the # of args (enable_if them)\n      {\n         return expr( args..., missing_args... );\n      };\n   }\n\npublic:\n\n   stateful_lambda( Expression expr ) : expr_( expr )\n   {\n      //std::cout << \"• size expr:  \" << sizeof(expr_)  << std::endl;\n      //std::cout << \"• size state: \" << sizeof(state_) << std::endl;\n      //std::cout << \"• state: \" << type_name(state_) << std::endl;\n   }\n\n   template < typename... Args , typename = std::enable_if_t< sizeof...(Args) <= arity > >\n   auto operator()( Args const &... args ) -> decltype(auto)\n   {\n      return call_impl( mpl::int_< arity - sizeof...(Args) >{} , args... );\n   }\n};\n\n\n// TODO template input type determinse state type (float)\nauto compile = []( auto expr_ )        // TODO need to define value_type for state\n{\n   auto expr = proto::deep_copy(expr_);\n   using expr_t = decltype(expr);\n   using arity_t = input_arity_t<expr_t>;\n\n   auto builder = build_state< to_array_tuple<float>::apply >{};\n   using state_t = decltype( builder(expr) );\n\n   return stateful_lambda< expr_t, state_t, arity_t::value>{ expr };\n};\n\n\n\nconst proto::terminal< placeholder< mpl::int_<1> >>::type   _1  = {{}};\nconst proto::terminal< placeholder< mpl::int_<2> >>::type   _2  = {{}};\nconst proto::terminal< placeholder< mpl::int_<3> >>::type   _3  = {{}};\nconst proto::terminal< placeholder< mpl::int_<4> >>::type   _4  = {{}};\nconst proto::terminal< placeholder< mpl::int_<5> >>::type   _5  = {{}};\nconst proto::terminal< placeholder< mpl::int_<6> >>::type   _6  = {{}};\n\n\n\n\n\nauto print_ins_and_outs = []( auto const & expr )\n{\n    std::cout << \"-------------------------\" << std::endl;\n    //proto::display_expr( expr );\n    std::cout << \"#ins:  \" << input_arity{} (expr) << std::endl;\n    std::cout << \"#outs: \" << output_arity{}(expr) << std::endl;\n    std::cout << std::endl;\n};\n\n\n\nauto one_quad = []\n{\n   return compile( proto::deep_copy( ~(0.9f*_1[_1] - 0.8f*_1[_2] + _2 ) ));\n};\n\nauto one_quad_chain = []\n{\n   return compile( proto::deep_copy(\n      ~(0.9f*_1[_1] - 0.8f*_1[_2] + _2)\n   |= ~(0.9f*_1[_1] - 0.8f*_1[_2] + _2)\n   //|= ~(0.9f*_1[_1] - 0.8f*_1[_2] + _2)\n   //|= ~(0.9f*_1[_1] - 0.8f*_1[_2] + _2)\n   ));\n};\n\nauto cross_wire = []\n{\n   return compile( proto::deep_copy(\n      ~( (_2[_1],_3,_1[_1])  |=  (.9f*_1 + _2) | (.2f*_1) )\n   ));\n};\n\n\nauto test_wire_around_box = []\n{\n   /*\n   auto wire_around_prev_box = (_1 |= _2);\n   print_ins_and_outs( wire_around_prev_box );\n   auto wp = compile( wire_around_prev_box );\n   std::cout << wp(2,1337) << std::endl;\n\n   auto wire_around_succ_box = ( (_1,_1) |= _1);\n   print_ins_and_outs( wire_around_succ_box );\n   auto ws = compile( wire_around_succ_box );\n   std::cout << ws(1337) << std::endl;\n   */\n};\n\n\nauto sum_dirac = []( auto& proc )\n{\n   auto sum = std::get<0>(proc(1.f));\n   for ( size_t n = 0; n < 100; ++n )\n      sum += std::get<0>(proc(.0f));\n   return sum;\n};\n\nauto make_simple_asm_inspectable_code = []( auto proc )\n{\n   asm volatile(\"nop\");\n   auto sum = std::get<0>(proc(1.f));\n   for ( size_t n = 0; n < 100; ++n )  sum += std::get<0>(proc(.0f));\n   asm volatile(\"nop\");\n   std::cout << sum << std::endl;\n};\n\nauto feed_dirac = []( auto proc )\n{\n   std::cout << proc(1.f) << std::endl;\n   for ( size_t n = 0; n < 100; ++n )\n      std::cout << proc(0.f) << std::endl;\n};\n\n\n\nauto x_wire = [ u1 = 0.f , u2 = 0.f ](float x) mutable\n{\n   auto u1_ = .9f * u2 + x;\n   auto u2_ = .2f * u1;\n   u1 = u1_;\n   u2 = u2_;\n   return std::make_tuple(u1,u2);\n};\n\n\n\n\n#include <benchmark/benchmark.h>\n\n\ninline void escape(void* p) { asm volatile( \"\" :: \"g\"(p) : \"memory\" ); }\n\n\nstatic void BM_cross_wire(benchmark::State& state)\n{\n   float x;\n   auto f = cross_wire();\n   while (state.KeepRunning())\n   {\n      escape(&x);\n      asm volatile(\"nop\");\n      x = sum_dirac(f);\n      asm volatile(\"nop\");\n   }\n}\nBENCHMARK(BM_cross_wire);\n\n\nstatic void BM_x_wire(benchmark::State& state)\n{\n   float x;\n   auto f = x_wire;\n   while (state.KeepRunning())\n   {\n      escape(&x);\n      asm volatile(\"nop\");\n      asm volatile(\"nop\");\n      x = sum_dirac(f);\n      asm volatile(\"nop\");\n   }\n}\nBENCHMARK(BM_x_wire);\n\n\n//BENCHMARK_MAIN();\n\n\n\n\n\nint main()\n{\n   make_simple_asm_inspectable_code( cross_wire() );\n   print_range( cross_wire() );\n\n\n   input_delays  d;\n   build_state<> b;\n\n   //auto e = (_1 |= _1[_1]) |= (_1 |= _1[_1]);\n   auto e = (_1,_1) |= (_1[_1]|_1) |= _1+_2*0;\n   auto id = compile( e );\n   std::cout << \" ------ e ------\" << std::endl;\n   std::cout << id(1337) << std::endl;\n   std::cout << id(42) << std::endl;\n   std::cout << id(1) << std::endl;\n   std::cout << id(1) << std::endl;\n   std::cout << id(1) << std::endl;\n\n   std::cout << d(e) << std::endl;\n   std::cout << b(e) << std::endl;\n   print_state( b( e ));\n\n   //print_state( b( cross_wire() ));\n   //compile( cross_wire() )(1.f,1.f);\n\n\n//   std::cout << \"--------------\" << std::endl;\n//\n//   // TODO build state only for used wires in feedback!\n//\n//   std::cout << b( ~(_1[_1] + _2[_1] + _3[_3]) ) << std::endl;\n//   std::cout << d( ~(_1[_1] + _2[_1] + _3[_3]) ) << std::endl;\n\n\n   // TODO does not work yet\n   auto fb = compile( ~~(_1[_1] + _2[_1] + _3) );\n   //std::cout << d( ~~(_1[_1] + _2[_1] + _3) ) << std::endl;\n   //std::cout << b( ~~(_1[_1] + _2[_1] + _3) ) << std::endl;\n   std::cout << fb(2) << std::endl;\n   std::cout << fb(1) << std::endl;\n   std::cout << fb(0) << std::endl;\n\n}\n", "meta": {"hexsha": "b969751330aa64d419d4e0819d3f39e6ac26940f", "size": 25126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental_steps/multi_wires_feedback.cpp", "max_stars_repo_name": "andre-bergner/zignal", "max_stars_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2016-02-04T20:56:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T15:51:17.000Z", "max_issues_repo_path": "experimental_steps/multi_wires_feedback.cpp", "max_issues_repo_name": "andre-bergner/zignal", "max_issues_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-02-05T14:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-05T14:46:11.000Z", "max_forks_repo_path": "experimental_steps/multi_wires_feedback.cpp", "max_forks_repo_name": "andre-bergner/zignal", "max_forks_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-20T15:27:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-09T16:34:04.000Z", "avg_line_length": 28.9803921569, "max_line_length": 142, "alphanum_fraction": 0.5292127677, "num_tokens": 6370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.03846619491182228, "lm_q1q2_score": 0.017584310050836924}}
{"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#                           robert.wueest@fhnw.ch                              #\n********************************************************************************\n*     Licensed under MIT License. Read the file LICENSE for more information   *\n*******************************************************************************/\n\n//-------------------------------------------------------\n// NOTE: this tool will be renamed to ogPostprocess soon\n//-------------------------------------------------------\n\n#include \"ogprocess.h\"\n#include \"errors.h\"\n#include <boost/asio.hpp>\n#include \"app/ProcessingSettings.h\"\n#include \"geo/MercatorQuadtree.h\"\n#include \"geo/CoordinateTransformation.h\"\n#include \"geo/ElevationLayerSettings.h\"\n#include \"string/FilenameUtils.h\"\n#include \"string/StringUtils.h\"\n#include \"geo/ImageLayerSettings.h\"\n#include \"io/FileSystem.h\"\n#include \"image/ImageLoader.h\"\n#include \"image/ImageWriter.h\"\n#include \"app/Logger.h\"\n#include \"math/mathutils.h\"\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <sstream>\n#include <omp.h>\n#include <app/QueueManager.h>\n#include \"hillshading.h\"\n#include <math/vec3.h>\n\nnamespace po = boost::program_options;\n\n//-------------------------------------------------------------------\n// Job-Struct\nstruct SJob\n{\n   int xx;\n   int yy;\n   int lod;\n};\n\n// -------------------------------------------------------------------\n// -- Global variables\n   bool bError = false;\n   std::string sLayerPath;\n   std::string sJobQueueFile;\n   int iLayerMaxZoom = 0;\n   int iLayerMinZoom = 0;\n   std::string sAlgorithm;\n   std::string sProcessHostName;\n   bool bVerbose = false;\n   bool bGenerateJobs = false;\n   bool bOverrideQueue = false;\n   bool bOverrideTiles = true;\n   bool bLockEnabled = false;\n   bool bNormalMaps = false;\n   bool bBorders = false;\n   bool bSlope = false;\n   bool bColored = false;\n   bool bTextured = false;\n   bool bNoData = false;\n   int iAmount = 256;\n   int inputX = 768;\n   int inputY = 768;\n   int outputX = 256;\n   int outputY = 256;\n   double z_depth = 1.0;\n   double azimut = 315;\n   double altitude = 45;\n   double sscale = 1;\n   double slopeScale = 1;\n   bool bJPEG = false;\n   int iX = 0;\n   int iY = 0;\n   std::string sTempTileDir;\n   std::string sTileDir;\n   boost::shared_ptr<MercatorQuadtree> qQuadtree;\n   int64 layerTileX0, layerTileY0, layerTileX1, layerTileY1;\n   QueueManager _QueueManager = QueueManager();\n   boost::shared_array<ImageObject> pTextures;\n// -------------------------------------------------------------------\n\n//  Job function (called every thread/compute node)\nvoid ProcessJob(const SJob& job, int layerLod)\n{\n   //std::cout << sCurrentQuadcode << \"\\n\";\n   HSProcessChunk pData;\n   pData.layerLod = layerLod;\n   pData.dfXMax = -1e20;\n   pData.dfYMax = -1e20;\n   pData.dfXMin = 1e20;\n   pData.dfYMin = 1e20;\n   pData.data.AllocateImage(inputX, inputY, -9999.0f);\n   std::string sParentQuad = qQuadtree->TileCoordToQuadkey(job.xx,job.yy,job.lod);\n   sParentQuad = StringUtils::Left(sParentQuad,layerLod);\n   int64 parentX,parentY;\n   int parentLod;\n   MercatorQuadtree::QuadKeyToTileCoord(sParentQuad,parentX, parentY,parentLod);\n   for (int ty=-1;ty<=1;ty++)\n   {\n      for (int tx=-1;tx<=1;tx++)\n      {\n         //std::string sQuadcode = qQuadtree->TileCoordToQuadkey(job.xx+tx,job.yy+ty,job.lod);\n         std::string sQuadcode = qQuadtree->TileCoordToQuadkey(parentX+tx, parentY+ty,parentLod);\n         std::string sTilefile = ProcessingUtils::GetTilePath(sTempTileDir, \".raw\" , parentLod, parentX+tx, parentY+ty);\n                  \n         double sx0, sy1, sx1, sy0;\n         qQuadtree->QuadKeyToMercatorCoord(sQuadcode, sx0, sy1, sx1, sy0);\n               \n         pData.dfXMax = math::Max<double>(pData.dfXMax, sx1);\n         pData.dfYMax = math::Max<double>(pData.dfYMax, sy1);\n         pData.dfXMin = math::Min<double>(pData.dfXMin, sx0);\n         pData.dfYMin = math::Min<double>(pData.dfYMin, sy0);\n\n         assert(sx0 < sx1);\n         assert(sy0 < sy1);\n\n         //std::cout << \"   \" << sTilefile << \"\\n\";\n\n         std::ifstream fin;\n         fin.open(sTilefile.c_str(), std::ios::binary);\n         int posX = (tx+1)*(inputX/3);\n         int posY = (ty+1)*(inputY/3);\n         int offX = 0;\n         int offY = 0;\n         if (fin.good())\n         {\n            while (!fin.eof())\n            {    \n               float value;\n               fin.read((char*)&(value), sizeof(float));\n               if (!fin.eof())\n               {\n                  pData.data.SetValue(posX+offX, posY+offY, value);\n               }\n               offX++;\n               if(offX % 256 == 0)\n               {\n                  offX = 0;\n                  offY++;\n               }\n\n            }\n         }\n         fin.close();\n      }\n   }\n   // Generate tile\n   process_hillshading(sTileDir, pData, qQuadtree, job.xx, job.yy, job.lod, z_depth, azimut, altitude,sscale,slopeScale, bSlope, bNormalMaps, outputX, outputY, bOverrideTiles, bLockEnabled, bNoData, bJPEG, bColored, bTextured, pTextures);\n}\n\n//------------------------------------------------------------------------------------\n\nvoid ConvertJobs(std::vector<QJob>& input, std::vector<SJob>& output)\n{\n   output.clear();\n   for (size_t i=0;i<input.size();i++)\n   {  \n      SJob job2;\n      memcpy(&job2, input[i].data.get(), sizeof(SJob));\n      output.push_back(job2);\n   }\n}\n\n//------------------------------------------------------------------------------------\n\nint main(int argc, char *argv[])\n{\n\t   //---------------------------------------------------------------------------\n   // init options:\n\n   boost::shared_ptr<ProcessingSettings> qSettings =  ProcessingUtils::LoadAppSettings();\n\n   if (!qSettings)\n   {\n      std::cout << \"[\" << sProcessHostName<< \"] \" << \"Error in configuration! Check setup.xml\\n\";\n      return ERROR_CONFIG;\n   }\n\n   sProcessHostName = boost::asio::ip::host_name();\n   po::options_description desc(\"Program-Options\");\n   desc.add_options()\n      (\"layername\", po::value<std::string>(), \"name of layer to generate data\")\n      (\"maxlod\", po::value<int>(), \"maximum lod which has to be generated previously using ogAddData\")\n      (\"minlod\", po::value<int>(), \"minimum lod which has to be generated previously using ogAddData\")\n      (\"generatejobs\",\"[optional] create a jobqueue which can be used in every process\")\n      (\"overridejobqueue\",\"[optional] overrides existing queue file if exist (only when generatejobs is set!)\")\n      (\"normalmaps\", \"[optional] generate normal maps\")\n      (\"slope\", \"[optional] integrate slope to map\")\n      (\"slopescale\", po::value<double>(),\"[optional] define slope scale default 1\")\n      (\"numthreads\", po::value<int>(), \"[optional] force number of threads\")\n      (\"amount\", po::value<int>(), \"[opional] define amount of jobs to be read for one process at the time\")\n      (\"zdepth\", po::value<double>(), \"[opional] hillshading z factor\")\n      (\"azimut\", po::value<double>(), \"[opional] hillshading azimut\")\n      (\"altitude\", po::value<double>(), \"[opional] hillshading altitude\")\n      (\"scale\", po::value<double>(), \"[opional] hillshading scale\")\n      (\"nooverride\", \"[opional] overriding existing tiles disabled\")\n      (\"enablelocking\", \"[opional] lock files to prevent concurrency on parallel processes\")\n      (\"verbose\", \"[optional] verbose output\")\n      (\"processborders\", \"[optional] process border tiles\")\n      (\"nodata\", \"[optional] include nodata values\")\n\t   (\"colored\", \"[optional] color the heigths\")\n\t   (\"textured\", \"[optional] generic textured heights\")\n      (\"jpg\", \"[optional] save files in compressed JPEG quality(78) instead of PNG\")\n      ;\n\n   po::variables_map vm;\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      bError = true;\n   }\n\n   if(vm.count(\"layername\"))\n   {\n\t  std::string sLayerName = vm[\"layername\"].as<std::string>();\n\t  sLayerPath = FilenameUtils::DelimitPath(qSettings->GetPath()) + sLayerName;\n      /*sLayerPath = vm[\"layerpath\"].as<std::string>();\n      if(!(sLayerPath.at(sLayerPath.length()-1) == '\\\\' || sLayerPath.at(sLayerPath.length()-1) == '/'))\n         sLayerPath = sLayerPath + \"/\";*/\n   }\n   else\n      bError = true;\n   if(vm.count(\"maxlod\"))\n      iLayerMaxZoom = vm[\"maxlod\"].as<int>();\n   else\n      bError = true;\n   if(vm.count(\"minlod\"))\n      iLayerMinZoom = vm[\"minlod\"].as<int>();\n   else\n      bError = true;\n   int numThreads = 1;\n   if(vm.count(\"numthreads\"))\n   {\n      int n = vm[\"numthreads\"].as<int>();\n      if (n>0 && n<65)\n      {\n         std::cout << \"[\" << sProcessHostName<< \"] \" << \"Forcing number of threads to \" << n << \"\\n\";\n         omp_set_num_threads(n);\n         numThreads = n;\n      }\n   }\n   if(vm.count(\"amount\"))\n      iAmount = vm[\"amount\"].as<int>();\n   if(vm.count(\"zdepth\"))\n      z_depth = vm[\"zdepth\"].as<double>();\n   if(vm.count(\"azimut\"))\n      azimut = vm[\"azimut\"].as<double>();\n   if(vm.count(\"altitude\"))\n      altitude = vm[\"altitude\"].as<double>();\n   if(vm.count(\"scale\"))\n      sscale = vm[\"scale\"].as<double>();\n   if(vm.count(\"verbose\"))\n      bVerbose = true;\n   if(vm.count(\"generatejobs\"))\n      bGenerateJobs = true;\n    if(vm.count(\"normalmaps\"))\n      bNormalMaps = true;\n    if(vm.count(\"slopescale\"))\n      slopeScale = vm[\"slopescale\"].as<double>();\n    if(vm.count(\"slope\"))\n      bSlope = true;\n    if(vm.count(\"nodata\"))\n      bNoData = true;\n   if(vm.count(\"overridejobqueue\"))\n      bOverrideQueue = true;\n   if(vm.count(\"nooverride\"))\n      bOverrideTiles = false;\n    if(vm.count(\"enablelocking\"))\n      bLockEnabled = true;\n\tif(vm.count(\"colored\"))\n      bColored = true;\n   if(vm.count(\"processborders\"))\n      bBorders = true;\n   if(vm.count(\"jpg\"))\n      bJPEG = true;\n\tif(vm.count(\"textured\"))\n   {\n      bTextured = true;\n         // Coloring textures\n      pTextures = boost::shared_array<ImageObject>(new ImageObject[6]);\n      ImageLoader::LoadFromDisk(Img::Format_PNG, \"data/ground.png\", Img::PixelFormat_RGBA, pTextures[0]);\n      ImageLoader::LoadFromDisk(Img::Format_PNG, \"data/grass.png\", Img::PixelFormat_RGBA, pTextures[1]);\n      ImageLoader::LoadFromDisk(Img::Format_PNG, \"data/snow.png\", Img::PixelFormat_RGBA, pTextures[2]);\n      ImageLoader::LoadFromDisk(Img::Format_PNG, \"data/rock.png\", Img::PixelFormat_RGBA, pTextures[3]);\n      ImageLoader::LoadFromDisk(Img::Format_PNG, \"data/desert.png\", Img::PixelFormat_RGBA, pTextures[4]);\n      ImageLoader::LoadFromDisk(Img::Format_PNG, \"data/water.png\", Img::PixelFormat_RGBA, pTextures[5]);\n   }\n\n\t   if(bError)\n   {\n      std::cout << \"[\" << sProcessHostName<< \"] \" << \"Wrong parameters!\\n\";\n      std::cout << desc << \"\\n\";\n      return ERROR_PARAMS;\n   }\n   //---------------------------------------------------------------------------\n   // -- Beginn process\n   sTempTileDir = sLayerPath + \"/temp/tiles/\";\n   sTileDir = sLayerPath + \"/tiles/\";\n\n   boost::shared_ptr<ImageLayerSettings> qImageLayerSettings = ImageLayerSettings::Load(sLayerPath);\n\n   if (!qImageLayerSettings)\n   {\n      std::cout << \"[\" << sProcessHostName<< \"] \" << \"Failed retrieving image layer settings! Make sure to create it using 'createlayer'.\\n\"<< std::flush;\n      return ERROR_IMAGELAYERSETTINGS;\n   }\n   int layermaxlod = qImageLayerSettings->GetMaxLod();\n   \n   qImageLayerSettings->GetTileExtent(layerTileX0, layerTileY0, layerTileX1, layerTileY1);\n   if (bVerbose)\n   {\n      std::cout << \"\\n\" << \"[\" << sProcessHostName<< \"] \" << \"Raw Image Layer:\\n\";\n      std::cout << \"   name = \" << qImageLayerSettings->GetLayerName() << \"\\n\";\n      std::cout << \"   maxlod = \" << layermaxlod << \"\\n\";\n      std::cout << \"   extent = \" << layerTileX0 << \", \" << layerTileY0 << \", \" << layerTileX1 << \", \" << layerTileY1 << \"\\n\" << std::flush;\n   }\n   //---------------------------------------------------------------------------\n   // -- performance measurement\n   int tileCount = 0;\n   clock_t t_0, t_1;\n   t_0 = clock();\n\n  \n   //---------------------------------------------------------------------------\n   // -- Generate job queue\n   qQuadtree = boost::shared_ptr<MercatorQuadtree>(new MercatorQuadtree());\n   sJobQueueFile = sTileDir + \"jobqueue.jobs\";\n   if(bGenerateJobs)\n   {\n      if(iLayerMaxZoom > layermaxlod)\n      {\n         for(size_t ll = layermaxlod; ll <iLayerMaxZoom; ll++)\n         {\n            layerTileX0 = layerTileX0*2;\n            layerTileX1 = layerTileX1*2;\n            layerTileY0 = layerTileY0*2;\n            layerTileY1 = layerTileY1*2;\n         }\n      }\n\t  else if(iLayerMaxZoom < layermaxlod)\n      {\n         for(size_t ll = layermaxlod; ll > iLayerMaxZoom; ll--)\n         {\n            layerTileX0 = math::Floor(layerTileX0/2.0);\n            layerTileX1 = math::Floor(layerTileX1/2.0);\n            layerTileY0 = math::Floor(layerTileY0/2.0);\n            layerTileY1 = math::Floor(layerTileY1/2.0);\n         }\n      }\n      else\n      {\n         iLayerMaxZoom = layermaxlod;\n         \n      }\n      if(iLayerMinZoom == 0)\n      {\n         iLayerMinZoom = layermaxlod;\n      }\n      for(size_t lod = iLayerMaxZoom; lod >= iLayerMinZoom; lod--)\n      {\n\n         if(lod < iLayerMaxZoom)\n         {\n            // update tile extents\n            layerTileX0 = math::Floor(layerTileX0/2.0);\n            layerTileX1 = math::Floor(layerTileX1/2.0);\n            layerTileY0 = math::Floor(layerTileY0/2.0);\n            layerTileY1 = math::Floor(layerTileY1/2.0);\n         }\n         int64 width = layerTileX1-layerTileX0+1;\n         int64 height = layerTileY1-layerTileY0+1;\n         if ((width<3 || height<3) && !bBorders)\n         {\n            std::cout << \"Extent is too small for hillshading processing skipping current and following LOD levels\\n\";\n            return ERROR_ELVLAYERSETTINGS;\n         }\n\n         // Retrieve dataset extent in mercator coord:\n         \n         double xmin, ymin, xmax, ymax;\n         std::string qc0 = qQuadtree->TileCoordToQuadkey(layerTileX0,layerTileY0,lod);\n         std::string qc1 = qQuadtree->TileCoordToQuadkey(layerTileX1,layerTileY1,lod);\n\n         double x00, y00, x10, y10;\n         double x01, y01, x11, y11;\n         qQuadtree->QuadKeyToMercatorCoord(qc0, x00,y00,x10,y10);\n         qQuadtree->QuadKeyToMercatorCoord(qc1, x01,y01,x11,y11);\n\n         xmin = x00;\n         ymin = y11;\n         xmax = x11;\n         ymax = y00;\n         if (bVerbose)\n         {\n            std::cout << \"\\n[\" << sProcessHostName<< \"] \" << \"Extent mercator:\";\n            std::cout << \"   extent = \" << xmin << \", \" << ymin << \", \" << xmax << \", \" << ymax << \"\\n\"<< std::flush;\n         }\n\n         if (!ProcessingUtils::init_gdal())\n         {\n            std::cout << \"[\" << sProcessHostName<< \"] \" << \"Warning: gdal-data directory not found. Ouput may be wrong!\\n\"<< std::flush;\n            return 1;\n         }   \n      \n         int idx = 0;\n         std::cout << \"[\" << sProcessHostName<< \"] \" << \" Generating jobs starting from (z, x, y) \" << \"(\" << lod << \", \" << layerTileX0+(bBorders ? 0 : 1) << \", \" << layerTileY0+(bBorders ? 0 : 1) << \")\\n\"<< std::flush;\n         for (int64 xx = layerTileX0+(bBorders ? 0 : 1); xx < layerTileX1+(bBorders ? 1 : 0); ++xx)\n         {\n            for (int64 yy = layerTileY0+(bBorders ? 0 : 1); yy < layerTileY1+(bBorders ? 1 : 0); ++yy)\n            {\n               QJob job;\n               SJob sJob;\n               sJob.lod = lod;\n               sJob.xx = xx;\n               sJob.yy = yy;\n               job.data = boost::shared_array<char>(new char[sizeof(SJob)]);\n               memcpy(job.data.get(), &sJob, sizeof(SJob));\n               job.size = sizeof(SJob);\n               _QueueManager.AddToJobQueue(sJobQueueFile, job, (bOverrideQueue && idx == 0)? false : true);\n               idx++;\n               iX = xx;\n               iY = yy;\n            }\n         }\n         _QueueManager.CommitJobQueue(sJobQueueFile);\n         std::cout << \"[\" << sProcessHostName<< \"] \" << \" Generated \" << idx << \" jobs ending with (z, x, y) \" << \"(\" << lod << \", \" << iX << \", \" << iY << \")!\\n\"<< std::flush;\n      }\n   }\n   //---------------------------------------------------------------------------\n   // -- Process Jobs Queue\n   else\n   {\n      if(!FileSystem::FileExists(sJobQueueFile))\n      {\n         std::cout << \"[\" << sProcessHostName<< \"] \" << \"ERROR: Jobqueue file not found: \" << sJobQueueFile << \" use --generatejobs first...\\n\"<< std::flush;\n         return ERROR_PARAMS;\n      }\n      std::vector<SJob> vecConverted;\n      std::vector<QJob> jobs;\n      std::cout << \"[\" << sProcessHostName<< \"] >>>\" << \"start processing...\\n\"<< std::flush;\n      do\n      {\n         jobs.clear();\n         vecConverted.clear();\n         jobs = _QueueManager.FetchJobList(sJobQueueFile, sizeof(SJob), iAmount,bVerbose);\n         if(jobs.size() > 0)\n         {\n         ConvertJobs(jobs, vecConverted);\n         SJob first, last;\n         first = vecConverted[0];\n         last = vecConverted[vecConverted.size()-1];\n         clock_t subT0 = clock();\n         clock_t subT1;\n         std::cout << \"--[\" << sProcessHostName<< \"] \" << \"  processing \" << vecConverted.size() << \" jobs\\n       starting from (z, x, y) \" << \"(\" << first.lod << \", \" << first.xx << \", \" << first.yy << \")\\n\"<< std::flush;\n#ifndef _DEBUG\n         std::cout << \"..Processing parallel using \" << numThreads << \"\\n\";\n               #pragma omp parallel shared(vecConverted, sTempTileDir, sTileDir, inputX, inputY, outputX, outputY)\n               {\n                  #pragma omp for \n#endif\n                  for(int index = 0; index < vecConverted.size(); index++)\n                  {\n                     ProcessJob(vecConverted[index],layermaxlod);\n                     tileCount++;\n                  }\n#ifndef _DEBUG\n               }\n#endif\n            subT1 = clock();\n            double subTime=(double(subT1-subT0)/double(CLOCKS_PER_SEC));\n            double subTps = vecConverted.size()/subTime;\n            std::cout << \"--[\" << sProcessHostName<< \"] \" << \"  processing average \" << subTps << \" tiles per second.\\n\";\n            std::cout << \"--[\" << sProcessHostName<< \"] \" << \"  processed \" << vecConverted.size() << \" jobs\\n       terminating with (z, x, y) \" << \"(\" << last.lod << \", \" << last.xx << \", \" << last.yy << \")\\n\"<< std::flush;\n         }\n      }while(jobs.size() >= iAmount); \n   }\n   t_1 = clock();\n         double time=(double(t_1-t_0)/double(CLOCKS_PER_SEC));\n         double tps = tileCount/time;\n         std::cout << \"[\" << sProcessHostName<< \"] <<<\" << \"finished processing \"<< tileCount << \" jobs at \" << tps << \" tiles pers second working for \" << time << \" seconds.\\n\"<< std::flush;\n   return 0;\n}", "meta": {"hexsha": "aedb9e8764e5e985b7ca4c4f248dc85678faf9e6", "size": 19672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/apps/hillshading/main_hpc.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/hillshading/main_hpc.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/hillshading/main_hpc.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": 39.187250996, "max_line_length": 238, "alphanum_fraction": 0.52450183, "num_tokens": 5119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.038466191053825004, "lm_q1q2_score": 0.017584308287204715}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  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#define BOOST_MPL_LIMIT_STRING_SIZE 64\n#define BOOST_METAPARSE_LIMIT_STRING_SIZE BOOST_MPL_LIMIT_STRING_SIZE\n\n#include <boost/metaparse/grammar.hpp>\n\n#include <boost/metaparse/string.hpp>\n#include <boost/metaparse/build_parser.hpp>\n#include <boost/metaparse/token.hpp>\n#include <boost/metaparse/entire_input.hpp>\n#include <boost/metaparse/int_.hpp>\n#include <boost/metaparse/transform.hpp>\n\n#include <boost/mpl/apply_wrap.hpp>\n#include <boost/mpl/front.hpp>\n#include <boost/mpl/back.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/fold.hpp>\n\nusing boost::mpl::apply_wrap1;\nusing boost::mpl::front;\nusing boost::mpl::back;\nusing boost::mpl::if_;\nusing boost::mpl::bool_;\n\nusing boost::metaparse::build_parser;\nusing boost::metaparse::token;\nusing boost::metaparse::entire_input;\nusing boost::metaparse::int_;\nusing boost::metaparse::grammar;\nusing boost::metaparse::transform;\n\n#if BOOST_METAPARSE_STD < 2011\nint main()\n{\n  std::cout << \"Please use a compiler that supports constexpr\" << std::endl;\n}\n#else\n\n#ifdef _STR\n#  error _STR already defined\n#endif\n#define _STR BOOST_METAPARSE_STRING\n\ntemplate <class T, char C>\nstruct is_c : bool_<T::type::value == C> {};\n\nstruct build_plus_impl\n{\n  template <class A, class B>\n  class _plus\n  {\n  public:\n    typedef _plus type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) + _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class A, class B>\n  class _minus\n  {\n  public:\n    typedef _minus type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) - _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class State, class C>\n  struct apply :\n    if_<\n      typename is_c<front<C>, '+'>::type,\n      _plus<State, typename back<C>::type>,\n      _minus<State, typename back<C>::type>\n    >\n  {};\n};\n\nstruct build_plus\n{\n  typedef build_plus type;\n\n  template <class Seq>\n  struct apply :\n    boost::mpl::fold<\n      typename back<Seq>::type,\n      typename front<Seq>::type,\n      build_plus_impl\n    >\n  {};\n};\n\nstruct build_mult_impl\n{\n  template <class A, class B>\n  class _mult\n  {\n  public:\n    typedef _mult type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) * _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class A, class B>\n  class _div\n  {\n  public:\n    typedef _div type;\n\n    template <class T>\n    T operator()(T t) const\n    {\n      return _left(t) / _right(t);\n    }\n  private:\n    typename A::type _left;\n    typename B::type _right;\n  };\n\n  template <class State, class C>\n  struct apply :\n    if_<\n      typename is_c<front<C>, '*'>::type,\n      _mult<State, typename back<C>::type>,\n      _div<State, typename back<C>::type>\n    >\n  {};\n};\n\nstruct build_mult\n{\n  typedef build_mult type;\n\n  template <class Seq>\n  struct apply :\n    boost::mpl::fold<\n      typename back<Seq>::type,\n      typename front<Seq>::type,\n      build_mult_impl\n    >\n  {};\n};\n\nstruct build_value\n{\n  typedef build_value type;\n\n  template <class V>\n  struct apply\n  {\n    typedef apply type;\n\n    template <class T>\n    int operator()(T) const\n    {\n      return V::type::value;\n    }\n  };\n};\n\nstruct build_arg\n{\n  typedef build_arg type;\n\n  template <class>\n  struct apply\n  {\n    typedef apply type;\n  \n    template <class T>\n    T operator()(T t) const\n    {\n      return t;\n    }\n  };\n};\n\nstruct keep_front\n{\n  typedef keep_front type;\n\n  template <class Seq>\n  struct apply : front<Seq> {};\n};\n\ntypedef\n  grammar<_STR(\"plus_exp\")>\n    ::import<_STR(\"int_token\"), token<transform<int_, build_value>>>::type\n\n    ::rule<_STR(\"ws ::= (' ' | '\\n' | '\\r' | '\\t')*\")>::type\n    ::rule<_STR(\"plus_token ::= '+' ws\"), keep_front>::type\n    ::rule<_STR(\"minus_token ::= '-' ws\"), keep_front>::type\n    ::rule<_STR(\"mult_token ::= '*' ws\"), keep_front>::type\n    ::rule<_STR(\"div_token ::= '/' ws\"), keep_front>::type\n    ::rule<_STR(\"arg_token ::= '_' ws\"), keep_front>::type\n\n    ::rule<_STR(\"plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*\"), build_plus>::type\n    ::rule<_STR(\"prod_exp ::= value_exp ((mult_token | div_token) value_exp)*\"), build_mult>::type\n    ::rule<_STR(\"value_exp ::= int_token | arg_exp\")>::type\n    ::rule<_STR(\"arg_exp ::= arg_token\"), build_arg>::type\n  g;\n\ntypedef build_parser<entire_input<g>> function_parser;\n\n#ifdef LAMBDA\n  #error LAMBDA already defined\n#endif\n#define LAMBDA(exp) apply_wrap1<function_parser, _STR(#exp)>::type\n\nLAMBDA(13) f1;\nLAMBDA(2 + 3) f2;\nLAMBDA(2 * 3) f3;\nLAMBDA(1+ 2*4-6/2) f4;\nLAMBDA(2 * _) f5;\n\nint main()\n{\n  using std::cout;\n  using std::endl;\n\n  cout\n    << f1(11) << endl\n    << f2(11) << endl\n    << f3(11) << endl\n    << f4(11) << endl\n    << f5(11) << endl\n    << f5(1.1) << endl\n    ;\n}\n\n#endif\n\n\n", "meta": {"hexsha": "44254983558de6a0f0cf7dd105aa4e09e40ca12c", "size": 5129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/metaparse/example/meta_metaparse/main.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/metaparse/example/meta_metaparse/main.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/metaparse/example/meta_metaparse/main.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 19.8030888031, "max_line_length": 98, "alphanum_fraction": 0.6346266329, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.035144844505941936, "lm_q1q2_score": 0.017572422252970968}}
{"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\n#include \"Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.h\"\n\n#include <iostream>\n#include <boost/make_shared.hpp>\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n\nnamespace tudat\n{\n\nnamespace aerodynamics\n{\n\nusing namespace interpolators;\n\n//! Check uniqueness of input.\ntemplate< typename VariableType >\nvoid checkVariableUniqueness( std::vector< VariableType > variables )\n{\n    // Sort variables\n    std::sort( variables.begin( ), variables.end( ) );\n\n    // Check uniqueness\n    unsigned int numberOfUniqueElements = std::distance( variables.begin( ),\n                                                         std::unique( variables.begin( ), variables.end( ) ) );\n\n    // Give error in case of non-unique variables\n    if ( numberOfUniqueElements != variables.size( ) )\n    {\n        throw std::runtime_error( \"Error, in tabulated atmosphere. Duplicate entry in (in)dependent variables.\" );\n    }\n}\n\n//! Function to create the interpolators based on the tabulated atmosphere files.\nvoid TabulatedAtmosphere::createAtmosphereInterpolators( )\n{\n    // Check uniqueness\n    checkVariableUniqueness< AtmosphereDependentVariables >( dependentVariables_ );\n    checkVariableUniqueness< AtmosphereIndependentVariables >( independentVariables_ );\n\n    // Retrieve number of dependent variables from user.\n    unsigned int numberOfDependentVariables = dependentVariables_.size( );\n\n    // Check that number of dependent variables does not exceed limit\n    if ( numberOfDependentVariables > dependentVariablesDependency_.size( ) )\n    {\n        throw std::runtime_error( \"Error, in tabulated atmosphere. Number of dependent variables exceeds current limit.\" );\n    }\n\n    // Check input consistency\n    if ( independentVariables_.size( ) != 1 )\n    {\n        if ( atmosphereTableFile_.size( ) != numberOfDependentVariables )\n        {\n            throw std::runtime_error( \"Error when creating tabulated atmosphere from file, \"\n                                      \"number of specified dependent variables differs from file.\" );\n        }\n\n        // Retrieve number of independent variables from file.\n        numberOfIndependentVariables_ = input_output::getNumberOfIndependentVariablesInCoefficientFile(\n                    atmosphereTableFile_.at( 0 ) );\n\n        // Check that number of independent variables does not exceed limit\n        if ( ( numberOfIndependentVariables_ < 1 ) || ( numberOfIndependentVariables_ > 4 ) )\n        {\n            throw std::runtime_error( \"Error when reading tabulated atmosphere from file, found \" +\n                                      std::to_string( numberOfIndependentVariables_ ) +\n                                      \" independent variables, up to 4 currently supported.\" );\n        }\n\n        // Check input consistency\n        if ( independentVariables_.size( ) != numberOfIndependentVariables_ )\n        {\n            throw std::runtime_error( \"Error when creating tabulated atmosphere from file, \"\n                                      \"number of specified independent variables differs from file.\" );\n        }\n    }\n    else\n    {\n        numberOfIndependentVariables_ = 1; // if only one independent variable is specified, only one file will\n                                           // be provided, and it cannot be opened with the same function\n    }\n\n    // Get order of dependent variables\n    for ( unsigned int i = 0; i < numberOfDependentVariables; i++ )\n    {\n        dependentVariablesDependency_.at( dependentVariables_.at( i ) ) = true;\n        dependentVariableIndices_.at( dependentVariables_.at( i ) ) = i;\n    }\n\n    // Check that density, pressure and temperature are present\n    if ( !( dependentVariablesDependency_.at( 0 ) || dependentVariablesDependency_.at( 1 ) ||\n            dependentVariablesDependency_.at( 2 ) ) )\n    {\n        throw std::runtime_error( \"Error, tabulated atmosphere must be initialized with at least \"\n                                  \"density, pressure and temperature.\" );\n    }\n\n    // Assign values to default boundary handling methods\n    if ( boundaryHandling_.empty( ) )\n    {\n        boundaryHandling_ = std::vector< BoundaryInterpolationType >( numberOfIndependentVariables_,\n                                                                      use_boundary_value );\n    }\n    else\n    {\n        if ( boundaryHandling_.size( ) != numberOfIndependentVariables_ )\n        {\n            throw std::runtime_error( \"Error, in tabulated atmosphere. Number of boundary handling methods provided does \"\n                                      \"not match number of independent variables.\" );\n        }\n    }\n\n    // Assign values to default extrapolation values\n    if ( defaultExtrapolationValue_.empty( ) )\n    {\n        defaultExtrapolationValue_ = std::vector< std::vector< std::pair< double, double > > >(\n                    numberOfDependentVariables, std::vector< std::pair< double, double > >(\n                        numberOfIndependentVariables_, std::make_pair(\n                            IdentityElement::getAdditionIdentity< double >( ),\n                            IdentityElement::getAdditionIdentity< double >( ) ) ) );\n    }\n    else\n    {\n        if ( defaultExtrapolationValue_.size( ) != numberOfDependentVariables )\n        {\n            throw std::runtime_error( \"Error, in tabulated atmosphere. Number of default extrapolation values provided \"\n                                      \"does not match number of dependent variables.\" );\n        }\n    }\n\n    // Create interpolators for variables requested by users, depending on the number of variables\n    switch ( numberOfIndependentVariables_ )\n    {\n    case 1:\n    {\n        // Call approriate file reading function for 1 independent variables\n        Eigen::MatrixXd tabulatedAtmosphereData = input_output::readMatrixFromFile( atmosphereTableFile_.at( 0 ), \" \\t\", \"%\" );\n\n        // Extract information on file size\n        unsigned int numberOfColumnsInFile = tabulatedAtmosphereData.cols( );\n        unsigned int numberOfRowsInFile = tabulatedAtmosphereData.rows( );\n\n\n        // Check whether data is present in the file.\n        if ( numberOfRowsInFile < 1 || numberOfColumnsInFile < 1 )\n        {\n            std::string errorMessage = \"Error, in tabulated atmosphere. The atmosphere table file \" +\n                    atmosphereTableFile_.at( 0 ) + \" is empty\";\n            throw std::runtime_error( errorMessage );\n        }\n\n        // Check whether number of dependent variables matches number of columns\n        if ( numberOfDependentVariables != ( numberOfColumnsInFile - 1 ) )\n        {\n            throw std::runtime_error( \"Error, in tabulated atmosphere. \"\n                                      \"Number of specified dependent variables does not match file.\" );\n        }\n\n        // Assign sizes to vectors\n        independentVariablesData_.resize( numberOfIndependentVariables_ );\n        std::vector< std::vector< double > > dependentVariablesData;\n        dependentVariablesData.resize( numberOfDependentVariables );\n\n        // Extract variables from file\n        for ( unsigned int i = 0; i < numberOfRowsInFile; i++ )\n        {\n            independentVariablesData_.at( 0 ).push_back( tabulatedAtmosphereData( i, 0 ) );\n            for ( unsigned int j = 0; j < dependentVariablesDependency_.size( ); j++ )\n            {\n                if ( dependentVariablesDependency_.at( j ) )\n                {\n                    dependentVariablesData.at( dependentVariableIndices_.at( j ) ).push_back(\n                                tabulatedAtmosphereData( i, dependentVariableIndices_.at( j ) + 1 ) );\n                }\n            }\n        }\n\n        // Create interpolators for density, pressure and temperature\n        interpolatorForDensity_ = std::make_shared< CubicSplineInterpolatorDouble >(\n                    independentVariablesData_.at( 0 ), dependentVariablesData.at( dependentVariableIndices_.at( 0 ) ),\n                    huntingAlgorithm, boundaryHandling_.at( 0 ), defaultExtrapolationValue_.at( dependentVariableIndices_.at( 0 ) ).at( 0 ) );\n        interpolatorForPressure_ = std::make_shared< CubicSplineInterpolatorDouble >(\n                    independentVariablesData_.at( 0 ), dependentVariablesData.at( dependentVariableIndices_.at( 1 ) ),\n                    huntingAlgorithm, boundaryHandling_.at( 0 ), defaultExtrapolationValue_.at( dependentVariableIndices_.at( 1 ) ).at( 0 ) );\n        interpolatorForTemperature_ = std::make_shared< CubicSplineInterpolatorDouble >(\n                    independentVariablesData_.at( 0 ), dependentVariablesData.at( dependentVariableIndices_.at( 2 ) ),\n                    huntingAlgorithm, boundaryHandling_.at( 0 ), defaultExtrapolationValue_.at( dependentVariableIndices_.at( 2 ) ).at( 0 ) );\n\n        // Create remaining interpolators, if requested by user\n        if ( dependentVariablesDependency_.at( 3 ) )\n        {\n            interpolatorForGasConstant_ = std::make_shared< CubicSplineInterpolatorDouble >(\n                        independentVariablesData_.at( 0 ), dependentVariablesData.at( dependentVariableIndices_.at( 3 ) ),\n                        huntingAlgorithm, boundaryHandling_.at( 0 ), defaultExtrapolationValue_.at( dependentVariableIndices_.at( 3 ) ).at( 0 ) );\n        }\n        if ( dependentVariablesDependency_.at( 4 ) )\n        {\n            interpolatorForSpecificHeatRatio_ = std::make_shared< CubicSplineInterpolatorDouble >(\n                        independentVariablesData_.at( 0 ), dependentVariablesData.at( dependentVariableIndices_.at( 4 ) ),\n                        huntingAlgorithm, boundaryHandling_.at( 0 ), defaultExtrapolationValue_.at( dependentVariableIndices_.at( 4 ) ).at( 0 ) );\n        }\n        if ( dependentVariablesDependency_.at( 5 ) )\n        {\n            interpolatorForMolarMass_ = std::make_shared< CubicSplineInterpolatorDouble >(\n                        independentVariablesData_.at( 0 ), dependentVariablesData.at( dependentVariableIndices_.at( 5 ) ),\n                        huntingAlgorithm, boundaryHandling_.at( 0 ), defaultExtrapolationValue_.at( dependentVariableIndices_.at( 5 ) ).at( 0 ) );\n        }\n        break;\n    }\n    case 2:\n    {\n        createMultiDimensionalAtmosphereInterpolators< 2 >( );\n        break;\n    }\n    case 3:\n    {\n        createMultiDimensionalAtmosphereInterpolators< 3 >( );\n        break;\n    }\n    case 4:\n    {\n        createMultiDimensionalAtmosphereInterpolators< 4 >( );\n        break;\n    }\n    default:\n        throw std::runtime_error( \"Error, multi-dimensional atmosphere with N>4 not yet implemented\" );\n    }\n}\n\n//! Create interpolators for specified dependent variables, taking into consideration the number\n//! of independent variables (which is greater than one).\ntemplate< unsigned int NumberOfIndependentVariables >\nvoid TabulatedAtmosphere::createMultiDimensionalAtmosphereInterpolators( )\n{\n    // Call approriate file reading function for N independent variables\n    std::pair< std::vector< boost::multi_array< double, static_cast< size_t >( NumberOfIndependentVariables ) > >,\n            std::vector< std::vector< double > > > tabulatedAtmosphereData;\n\n    // Extract data\n    tabulatedAtmosphereData = input_output::readTabulatedAtmosphere< NumberOfIndependentVariables >( atmosphereTableFile_ );\n\n    // Assign independent variables\n    independentVariablesData_ = tabulatedAtmosphereData.second;\n\n    // Create interpolators for density, pressure and temperature\n    interpolatorForDensity_ =\n            std::make_shared< MultiLinearInterpolator< double, double, NumberOfIndependentVariables > >(\n                independentVariablesData_, tabulatedAtmosphereData.first.at( dependentVariableIndices_.at( 0 ) ),\n                huntingAlgorithm, boundaryHandling_, defaultExtrapolationValue_.at( dependentVariableIndices_.at( 0 ) ) );\n    interpolatorForPressure_ =\n            std::make_shared< MultiLinearInterpolator< double, double, NumberOfIndependentVariables > >(\n                independentVariablesData_, tabulatedAtmosphereData.first.at( dependentVariableIndices_.at( 1 ) ),\n                huntingAlgorithm, boundaryHandling_, defaultExtrapolationValue_.at( dependentVariableIndices_.at( 1 ) ) );\n    interpolatorForTemperature_ =\n            std::make_shared< MultiLinearInterpolator< double, double, NumberOfIndependentVariables > >(\n                independentVariablesData_, tabulatedAtmosphereData.first.at( dependentVariableIndices_.at( 2 ) ),\n                huntingAlgorithm, boundaryHandling_, defaultExtrapolationValue_.at( dependentVariableIndices_.at( 2 ) ) );\n\n    // Create remaining interpolators, if requested by user\n    if ( dependentVariablesDependency_.at( 3 ) )\n    {\n        interpolatorForGasConstant_ =\n                std::make_shared< MultiLinearInterpolator< double, double, NumberOfIndependentVariables > >(\n                    independentVariablesData_, tabulatedAtmosphereData.first.at( dependentVariableIndices_.at( 3 ) ),\n                    huntingAlgorithm, boundaryHandling_, defaultExtrapolationValue_.at( dependentVariableIndices_.at( 3 ) ) );\n    }\n    if ( dependentVariablesDependency_.at( 4 ) )\n    {\n        interpolatorForSpecificHeatRatio_ =\n                std::make_shared< MultiLinearInterpolator< double, double, NumberOfIndependentVariables > >(\n                    independentVariablesData_, tabulatedAtmosphereData.first.at( dependentVariableIndices_.at( 4 ) ),\n                    huntingAlgorithm, boundaryHandling_, defaultExtrapolationValue_.at( dependentVariableIndices_.at( 4 ) ) );\n    }\n    if ( dependentVariablesDependency_.at( 5 ) )\n    {\n        interpolatorForMolarMass_ =\n                std::make_shared< MultiLinearInterpolator< double, double, NumberOfIndependentVariables > >(\n                    independentVariablesData_, tabulatedAtmosphereData.first.at( dependentVariableIndices_.at( 5 ) ),\n                    huntingAlgorithm, boundaryHandling_, defaultExtrapolationValue_.at( dependentVariableIndices_.at( 5 ) ) );\n    }\n}\n\n} // namespace aerodynamics\n\n} // namespace tudat\n", "meta": {"hexsha": "b43608bc73d89428e5ddcb9cf6f643f694dfe76d", "size": 14591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.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": 48.4750830565, "max_line_length": 146, "alphanum_fraction": 0.6560893702, "num_tokens": 3083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.04272219495648556, "lm_q1q2_score": 0.017563558704066926}}
{"text": "/************************************************************************/\n/*                                                                      */\n/*               Copyright 2007-2019 by Hans Meine                      */\n/*                                                                      */\n/*    Permission is hereby granted, free of charge, to any person       */\n/*    obtaining a copy of this software and associated documentation    */\n/*    files (the \"Software\"), to deal in the Software without           */\n/*    restriction, including without limitation the rights to use,      */\n/*    copy, modify, merge, publish, distribute, sublicense, and/or      */\n/*    sell copies of the Software, and to permit persons to whom the    */\n/*    Software is furnished to do so, subject to the following          */\n/*    conditions:                                                       */\n/*                                                                      */\n/*    The above copyright notice and this permission notice shall be    */\n/*    included in all copies or substantial portions of the             */\n/*    Software.                                                         */\n/*                                                                      */\n/*    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND    */\n/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   */\n/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          */\n/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       */\n/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      */\n/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      */\n/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     */\n/*    OTHER DEALINGS IN THE SOFTWARE.                                   */\n/*                                                                      */\n/************************************************************************/\n\n#ifndef VIGRA_CPPMAP_HXX\n#define VIGRA_CPPMAP_HXX\n\n#include \"filteriterator.hxx\"\n#include \"labellut.hxx\"\n#include \"vigra/map2d.hxx\"\n#include \"polygon.hxx\"\n#include <vector>\n#include <list>\n#include <vigra/multi_array.hxx>\n\n#include <boost/signals2/signal.hpp>\n#include <boost/utility.hpp> // boost::noncopyable\n#include <boost/math/special_functions/fpclassify.hpp> // boost::math::isnan (for Mac/Win!)\n\n#include <cfloat>\n\n// The define USE_INSECURE_CELL_PTRS can be used to switch between\n// \"safe\" cell handling e.g. for Python and a possibly faster C++ way.\n\n#ifdef USE_INSECURE_CELL_PTRS\n#  define CELL_PTR(Type) Type *\n#  define NULL_PTR(Type) (Type *)NULL\n#  define RESET_PTR(ptr) delete ptr; ptr = NULL\n#else\n#  include <boost/shared_ptr.hpp>\n#  define CELL_PTR(Type) boost::shared_ptr<Type>\n#  define NULL_PTR(Type) boost::shared_ptr<Type>()\n#  define RESET_PTR(ptr) ptr.reset()\n#endif\n\ntypedef unsigned int CellLabel;\ntypedef unsigned int CellFlags;\n\n// functor for FilterIterator to skip NULL cells\ntemplate<class POINTER>\nstruct NotNull\n{\n    bool operator()(const POINTER &p) const\n    {\n        return static_cast<bool>(p);\n    }\n};\n\ntypedef vigra::TinyVector<double, 2>       Vector2;\ntypedef vigra::PointArray<Vector2>         Vector2Array;\ntypedef vigra::BBoxPolygon<Vector2>        Vector2Polygon;\n\ntypedef vigra::PointArray<vigra::Point2D> PixelList;\n\n// \"accumulator\" for boost::signals, which calls pre-operation\n// callbacks in order but cancels whenever a callback returns false\nstruct interruptable_accumulator\n{\n    typedef bool result_type;\n\n    template<typename T_iterator>\n    result_type operator()(T_iterator first, T_iterator last) const\n    {\n        for(; first != last; ++first)\n            if(!*first)\n                return false;\n        return true;\n    }\n};\n\nnamespace detail {\n\ntypedef vigra::MultiArray<2, int>::difference_type IVector2;\n\ninline IVector2 intVPos(const Vector2 &p)\n{\n    return IVector2((int)floor(p[0]+0.5), (int)floor(p[1]+0.5));\n}\n\nclass PlannedSplits;\n\n} // namespace detail\n\n/********************************************************************/\n/*                                                                  */\n/*                              GeoMap                              */\n/*                                                                  */\n/********************************************************************/\n\nclass GeoMap\n{\n  public:\n    class Node;\n    class Edge;\n    class Face;\n    class Dart;\n    class SigmaAnchor;\n\n    typedef CELL_PTR(Node) NodePtr;\n    typedef CELL_PTR(Edge) EdgePtr;\n    typedef CELL_PTR(Face) FacePtr;\n    typedef CELL_PTR(const Node) ConstNodePtr;\n    typedef CELL_PTR(const Edge) ConstEdgePtr;\n    typedef CELL_PTR(const Face) ConstFacePtr;\n\n    typedef std::vector<NodePtr> Nodes;\n    typedef std::vector<EdgePtr> Edges;\n    typedef std::vector<FacePtr> Faces;\n\n    typedef vigra::SafeFilterIterator<Nodes::iterator, NotNull<NodePtr> >\n        NodeIterator;\n    typedef vigra::SafeFilterIterator<Edges::iterator, NotNull<EdgePtr> >\n        EdgeIterator;\n    typedef vigra::SafeFilterIterator<Faces::iterator, NotNull<FacePtr> >\n        FaceIterator;\n    typedef vigra::SafeFilterIterator<Nodes::const_iterator, NotNull<NodePtr> >\n        ConstNodeIterator;\n    typedef vigra::SafeFilterIterator<Edges::const_iterator, NotNull<EdgePtr> >\n        ConstEdgeIterator;\n    typedef vigra::SafeFilterIterator<Faces::const_iterator, NotNull<FacePtr> >\n        ConstFaceIterator;\n\n    typedef std::vector<int> SigmaMapping;\n    typedef std::vector<double> EdgePreferences;\n\n    typedef vigra::ConstImageIterator<int> LabelImageIterator;\n    struct LabelImageAccessor {\n        typedef int value_type;\n\n        template<class Iterator>\n        value_type operator()(Iterator it) const\n        {\n            int label = *it;\n            if(label >= 0)\n                label = faceLabelLUT_[label];\n            return label;\n        }\n\n        template<class Iterator>\n        value_type operator()(Iterator it,\n                              typename Iterator::difference_type diff) const\n        {\n            int label = it[diff];\n            if(label >= 0)\n                label = faceLabelLUT_[label];\n            return label;\n        }\n\n      protected:\n        friend class GeoMap;\n\n        LabelImageAccessor(LabelLUT const &faceLabelLUT)\n        : faceLabelLUT_(faceLabelLUT)\n        {}\n\n        LabelLUT const &faceLabelLUT_;\n    };\n\n  protected:\n    SigmaMapping\n        sigmaMappingArray_,\n        sigmaInverseMappingArray_;\n    SigmaMapping::iterator\n        sigmaMapping_,\n        sigmaInverseMapping_;\n\n    Nodes nodes_;\n    Edges edges_;\n    Faces faces_;\n\n    unsigned int nodeCount_;\n    unsigned int edgeCount_;\n    unsigned int faceCount_;\n\n    typedef vigra::PositionedObject<Vector2, CellLabel> PositionedNodeLabel;\n    typedef vigra::Map2D<PositionedNodeLabel> NodeMap;\n    NodeMap nodeMap_;\n\n    typedef vigra::MultiArray<2, int> LabelImage;\n\n    vigra::Size2D imageSize_;\n    LabelImage   *labelImage_;\n    LabelLUT      faceLabelLUT_;\n\n    bool edgesSorted_;\n    std::auto_ptr<detail::PlannedSplits> splitInfo_;\n    std::auto_ptr<EdgePreferences> edgePreferences_;\n\n  public:\n    GeoMap(vigra::Size2D imageSize);\n    GeoMap(const GeoMap &other);\n    ~GeoMap();\n\n    NodeIterator nodesBegin()\n        { return NodeIterator(nodes_.begin(), nodes_.end()); }\n    NodeIterator nodesEnd()\n        { return NodeIterator(nodes_.end(), nodes_.end()); }\n    NodePtr node(CellLabel label)\n    {\n        vigra_precondition(label < nodes_.size(), \"invalid node label!\");\n        return nodes_[label];\n    }\n    ConstNodeIterator nodesBegin() const\n        { return ConstNodeIterator(nodes_.begin(), nodes_.end()); }\n    ConstNodeIterator nodesEnd() const\n        { return ConstNodeIterator(nodes_.end(), nodes_.end()); }\n    ConstNodePtr node(CellLabel label) const\n    {\n        vigra_precondition(label < nodes_.size(), \"invalid node label!\");\n        return nodes_[label];\n    }\n\n    EdgeIterator edgesBegin()\n        { return EdgeIterator(edges_.begin(), edges_.end()); }\n    EdgeIterator edgesEnd()\n        { return EdgeIterator(edges_.end(), edges_.end()); }\n    EdgePtr edge(CellLabel label)\n    {\n        vigra_precondition(label < edges_.size(), \"invalid edge label!\");\n        return edges_[label];\n    }\n    ConstEdgeIterator edgesBegin() const\n        { return ConstEdgeIterator(edges_.begin(), edges_.end()); }\n    ConstEdgeIterator edgesEnd() const\n        { return ConstEdgeIterator(edges_.end(), edges_.end()); }\n    ConstEdgePtr edge(CellLabel label) const\n    {\n        vigra_precondition(label < edges_.size(), \"invalid edge label!\");\n        return edges_[label];\n    }\n\n    FaceIterator facesBegin()\n        { return FaceIterator(faces_.begin(), faces_.end()); }\n    FaceIterator finiteFacesBegin()\n        { return ++facesBegin(); }\n    FaceIterator facesEnd()\n        { return FaceIterator(faces_.end(), faces_.end()); }\n    FacePtr face(CellLabel label)\n    {\n        vigra_precondition(label < faces_.size(), \"invalid face label!\");\n        return faces_[label];\n    }\n    ConstFaceIterator facesBegin() const\n        { return ConstFaceIterator(faces_.begin(), faces_.end()); }\n    ConstFaceIterator finiteFacesBegin() const\n        { return ++facesBegin(); }\n    ConstFaceIterator facesEnd() const\n        { return ConstFaceIterator(faces_.end(), faces_.end()); }\n    ConstFacePtr face(CellLabel label) const\n    {\n        vigra_precondition(label < faces_.size(), \"invalid face label!\");\n        return faces_[label];\n    }\n\n    inline Dart dart(int label);\n    FacePtr faceAt(const Vector2 &position);\n    ConstFacePtr faceAt(const Vector2 &position) const;\n\n    CellLabel nodeCount() const { return nodeCount_; }\n    CellLabel maxNodeLabel() const { return nodes_.size(); }\n    CellLabel edgeCount() const { return edgeCount_; }\n    CellLabel maxEdgeLabel() const { return edges_.size(); }\n    CellLabel faceCount() const { return faceCount_; }\n    CellLabel maxFaceLabel() const { return faces_.size(); }\n\n    const vigra::Size2D &imageSize() const\n    {\n        return imageSize_;\n    }\n\n    NodePtr addNode(const Vector2 &position);\n    NodePtr addNode(const Vector2 &position, CellLabel label);\n    EdgePtr addEdge(const SigmaAnchor &startNeighbor,\n                           const SigmaAnchor &endNeighbor,\n                           const Vector2Array &points, CellLabel label = 0);\n    // will always return NULL if !mapInitialized():\n    FacePtr removeEdge(const Dart &dart);\n\n    void sortEdgesDirectly();\n\n    typedef std::list<std::list<int> > UnsortableGroups;\n    void sortEdgesEventually(double stepDist, double minDist,\n                             UnsortableGroups &unsortable,\n                             bool splitEdges);\n    void setEdgePreferences(std::auto_ptr<EdgePreferences> edgePreferences)\n    {\n        vigra_precondition(\n            splitInfo_.get() != NULL,\n            \"setting edge preferences futile - splitting impossible\");\n        edgePreferences_ = edgePreferences;\n    }\n    void splitParallelEdges();\n        // for debugging / paper writing only:\n    detail::PlannedSplits *internalSplitInfo()\n        { return splitInfo_.get(); }\n\n    void setSigmaMapping(SigmaMapping const &sigmaMapping, bool sorted = true);\n    const SigmaMapping &sigmaMapping()\n        { return sigmaMappingArray_; }\n\n    bool edgesSorted() const { return edgesSorted_; }\n\n    void initializeMap(bool initLabelImage = true);\n    bool mapInitialized() const  { return faces_.size() > 0; }\n    bool hasLabelImage() const { return labelImage_ != NULL; }\n    void setHasLabelImage(bool onoff);\n    const LabelLUT &faceLabelLUT() const { return faceLabelLUT_; }\n\n    LabelImageIterator labelsUpperLeft() const\n    {\n        return LabelImageIterator(labelImage_->data(), labelImage_->shape(0));\n    }\n    LabelImageIterator labelsLowerRight() const\n    {\n        return labelsUpperLeft() + imageSize_;\n    }\n    LabelImageAccessor labelAccessor() const\n    {\n        return LabelImageAccessor(faceLabelLUT_);\n    }\n\n    vigra::triple<LabelImageIterator, LabelImageIterator, LabelImageAccessor>\n    srcLabelRange() const\n    {\n        vigra_precondition(\n            hasLabelImage(), \"trying to access labelImage of GeoMap w/o label image!\");\n        return srcIterRange(labelsUpperLeft(),\n                            labelsLowerRight(),\n                            labelAccessor());\n    }\n\n        // maxFaceLabel is to be +1 here, too:\n    void changeFaceLabels(const std::vector<CellLabel> &newFaceLabels,\n                          CellLabel maxFaceLabel);\n\n  protected:\n    void initContours();\n    void embedFaces(bool initLabelImage);\n    void resizeSigmaMapping(SigmaMapping::size_type newSize);\n    void insertSigmaPredecessor(int successor, int newPredecessor);\n    void detachDart(int dartLabel);\n\n  public:\n    NodePtr nearestNode(\n        const Vector2 &position,\n        double maxSquaredDist = vigra::NumericTraits<double>::max());\n\n    bool checkConsistency();\n\n  protected:\n    void associatePixels(Face &face, const PixelList &pixels);\n\n  public:\n    bool removeIsolatedNode(Node &node);\n    EdgePtr mergeEdges(const Dart &dart);\n    EdgePtr splitEdge(Edge &edge, unsigned int segmentIndex);\n    EdgePtr splitEdge(Edge &edge, unsigned int segmentIndex,\n                             const Vector2 &newPoint,\n                             bool insertPoint = true);\n    FacePtr removeBridge(const Dart &dart);\n    FacePtr mergeFaces(const Dart &dart);\n\n    // callbacks using boost::signals:\n#ifndef BOOST_NO_VARIADIC_TEMPLATES\n    boost::signals2::signal<bool(Node &), interruptable_accumulator>\n        removeNodeHook;\n    boost::signals2::signal<bool(const Dart &), interruptable_accumulator>\n        preMergeEdgesHook;\n    boost::signals2::signal<void(Edge &)>\n        postMergeEdgesHook;\n    boost::signals2::signal<void(Edge &, unsigned int, Vector2 const &, bool)>\n        preSplitEdgeHook;\n    boost::signals2::signal<void(Edge &, Edge &)>\n        postSplitEdgeHook;\n    boost::signals2::signal<bool(const Dart &), interruptable_accumulator>\n        preRemoveBridgeHook;\n    boost::signals2::signal<void(Face &)>\n        postRemoveBridgeHook;\n    boost::signals2::signal<bool(const Dart &), interruptable_accumulator>\n        preMergeFacesHook;\n    boost::signals2::signal<void(Face &)>\n        postMergeFacesHook;\n    boost::signals2::signal<void(const Face &, const PixelList &)>\n        associatePixelsHook;\n#else\n    boost::signals2::signal1\n      <bool, Node &, interruptable_accumulator>\n        removeNodeHook;\n    boost::signals2::signal1<bool, const Dart &, interruptable_accumulator>\n        preMergeEdgesHook;\n    boost::signals2::signal1<void, Edge &>\n        postMergeEdgesHook;\n    boost::signals2::signal4<void, Edge &, unsigned int, Vector2 const &, bool>\n        preSplitEdgeHook;\n    boost::signals2::signal2<void, Edge &, Edge &>\n        postSplitEdgeHook;\n    boost::signals2::signal1<bool, const Dart &, interruptable_accumulator>\n        preRemoveBridgeHook;\n    boost::signals2::signal1<void, Face &>\n        postRemoveBridgeHook;\n    boost::signals2::signal1<bool, const Dart &, interruptable_accumulator>\n        preMergeFacesHook;\n    boost::signals2::signal1<void, Face &>\n        postMergeFacesHook;\n    boost::signals2::signal2<void, const Face &, const PixelList &>\n        associatePixelsHook;\n#endif\n};\n\n/********************************************************************/\n/*                                                                  */\n/*                           GeoMap::Node                           */\n/*                                                                  */\n/********************************************************************/\n\nclass GeoMap::Node : boost::noncopyable\n{\n  protected:\n    GeoMap        *map_;\n    CellLabel      label_;\n    Vector2 position_;\n    int            anchor_;\n\n    friend class GeoMap; // give access to anchor_ (add edge, sort edges, Euler..)\n    friend class SigmaAnchor; // give access to anchor_\n\n    inline void uninitialize();\n\n    Node(GeoMap *map, const Vector2 &position)\n    : map_(map),\n      label_(map->nodes_.size()),\n      position_(position),\n      anchor_(0)\n    {\n        map_->nodes_.push_back(GeoMap::NodePtr(this));\n        ++map_->nodeCount_;\n        map_->nodeMap_.insert(PositionedNodeLabel(position_, label_));\n    }\n\n        // copy constructor for copying GeoMaps\n    Node(GeoMap *map, const Node &other)\n    : map_(map),\n      label_(other.label_),\n      position_(other.position_),\n      anchor_(other.anchor_)\n    {\n        map_->nodeMap_.insert(PositionedNodeLabel(position_, label_));\n    }\n\n  public:\n    bool initialized() const\n    {\n        return map_ != NULL;\n    }\n\n    CellLabel label() const\n    {\n        return label_;\n    }\n\n    const Vector2 &position() const\n    {\n        return position_;\n    }\n\n    void setPosition(const Vector2 &p);\n\n    inline Dart anchor() const;\n\n    bool isIsolated() const\n    {\n        return !anchor_;\n    }\n\n    inline unsigned int degree() const;\n\n    inline bool hasMinDegree(unsigned int minDegree) const;\n\n    inline bool hasDegree(unsigned int exactDegree) const;\n\n    bool operator==(const GeoMap::Node &other)\n    {\n        return label() == other.label();\n    }\n\n    bool operator!=(const GeoMap::Node &other)\n    {\n        return !operator==(other);\n    }\n\n    GeoMap *map() const\n    {\n        return map_;\n    }\n};\n\n/********************************************************************/\n/*                                                                  */\n/*                           GeoMap::Edge                           */\n/*                                                                  */\n/********************************************************************/\n\nconst CellLabel UNINITIALIZED_CELL_LABEL =\n    vigra::NumericTraits<CellLabel>::max();\n\nclass GeoMap::Edge\n  : public Vector2Polygon, boost::noncopyable\n{\n  public:\n    typedef vigra::BBoxPolygon<Vector2> Base;\n\n    enum {\n        BORDER_PROTECTION = 1,\n        ALL_PROTECTION = 0xff,\n        REMOVE_BRIDGE = 0x80000000,\n    };\n\n  protected:\n    GeoMap      *map_;\n    CellLabel    label_;\n    CellLabel    startNodeLabel_, endNodeLabel_;\n    CellLabel    leftFaceLabel_, rightFaceLabel_;\n    CellFlags    flags_;\n\n    mutable std::auto_ptr<vigra::Scanlines> scanLines_;\n\n    friend class Dart; // allow setLeftFaceLabel\n    friend class GeoMap;\n\n    inline void uninitialize();\n\n    void concatenate(Edge &other, bool atEnd, bool reverse);\n\n    template<class POINTS>\n    Edge(GeoMap *map, CellLabel startNodeLabel, CellLabel endNodeLabel,\n         const POINTS &p)\n    : Base(p),\n      map_(map),\n      label_(map->edges_.size()),\n      startNodeLabel_(startNodeLabel),\n      endNodeLabel_(endNodeLabel),\n      leftFaceLabel_(UNINITIALIZED_CELL_LABEL),\n      rightFaceLabel_(UNINITIALIZED_CELL_LABEL),\n      flags_(0)\n    {\n        map_->edges_.push_back(GeoMap::EdgePtr(this));\n        ++map_->edgeCount_;\n    }\n\n        // copy constructor for copying GeoMaps\n    Edge(GeoMap *map, const Edge &other)\n    : Base(static_cast<const Base &>(other)),\n      map_(map),\n      label_(other.label_),\n      startNodeLabel_(other.startNodeLabel_),\n      endNodeLabel_(other.endNodeLabel_),\n      leftFaceLabel_(other.leftFaceLabel_),\n      rightFaceLabel_(other.rightFaceLabel_),\n      flags_(other.flags_)\n    {\n    }\n\n  public:\n    bool initialized() const\n    {\n        return map_ != NULL;\n    }\n\n    CellLabel label() const\n    {\n        return label_;\n    }\n\n    inline Dart dart() const;\n\n    CellLabel startNodeLabel() const\n    {\n        return startNodeLabel_;\n    }\n\n    GeoMap::NodePtr startNode() const\n    {\n        vigra_precondition(initialized(), \"startNode() of uninitialized edge!\");\n        return map_->node(startNodeLabel_);\n    }\n\n    CellLabel endNodeLabel() const\n    {\n        return endNodeLabel_;\n    }\n\n    GeoMap::NodePtr endNode() const\n    {\n        vigra_precondition(initialized(), \"endNode() of uninitialized edge!\");\n        return map_->node(endNodeLabel_);\n    }\n\n    CellLabel leftFaceLabel() const\n    {\n        return leftFaceLabel_;\n    }\n\n    GeoMap::FacePtr leftFace() const\n    {\n        vigra_precondition(initialized(), \"leftFace() of uninitialized edge!\");\n        return map_->face(leftFaceLabel());\n    }\n\n    CellLabel rightFaceLabel() const\n    {\n        return rightFaceLabel_;\n    }\n\n    GeoMap::FacePtr rightFace() const\n    {\n        vigra_precondition(initialized(), \"rightFace() of uninitialized edge!\");\n        return map_->face(rightFaceLabel());\n    }\n\n    bool isBridge() const\n    {\n        return leftFaceLabel() == rightFaceLabel();\n    }\n\n    bool isLoop() const\n    {\n        return startNodeLabel_ == endNodeLabel_;\n    }\n\n    bool operator==(const GeoMap::Edge &other)\n    {\n        return label() == other.label();\n    }\n\n    bool operator!=(const GeoMap::Edge &other)\n    {\n        return !operator==(other);\n    }\n\n    CellFlags flags() const\n    {\n        return flags_;\n    }\n\n    CellFlags flag(CellFlags which) const\n    {\n        return flags_ & which;\n    }\n\n    void setFlag(CellFlags flag, bool onoff = true)\n    {\n        if(onoff)\n            flags_ |= flag;\n        else\n            flags_ &= ~flag;\n    }\n\n    GeoMap *map() const\n    {\n        return map_;\n    }\n\n    const vigra::Scanlines &scanLines() const\n    {\n        if(!scanLines_.get())\n            scanLines_ = scanPoly(*this);\n        return *scanLines_;\n    }\n};\n\nstd::string description(GeoMap::Edge const &edge);\n\nclass DartPointIter\n{\n    GeoMap::EdgePtr edge_;\n    int index_, inc_, end_;\n\n  public:\n        /** the iterator's value type\n        */\n    typedef GeoMap::Edge::value_type value_type;\n\n        /** the iterator's reference type (return type of <tt>*iter</tt>)\n        */\n    typedef value_type & reference;\n\n        /** the iterator's pointer type (return type of <tt>operator-></tt>)\n        */\n    typedef value_type * pointer;\n\n        /** the iterator tag (forward_iterator_tag)\n        */\n    typedef std::forward_iterator_tag iterator_category;\n\n    DartPointIter(GeoMap::Dart const &dart);\n\n    DartPointIter & operator++()\n    {\n        index_ += inc_;\n        return *this;\n    }\n\n    DartPointIter operator++(int)\n    {\n        DartPointIter ret(*this);\n        operator++();\n        return ret;\n    }\n\n        /**\n         * Change the direction of traversal, without changing the\n         * current position.  (Thus, atEnd()/inRange() will also not\n         * change.)\n         */\n    void reverse()\n    {\n        if(inc_ < 0)\n        {\n            inc_ = 1;\n            end_ = edge_->size();\n        }\n        else\n        {\n            inc_ = -1;\n            end_ = -1;\n        }\n    }\n\n        /**\n         * the opposite of inRange(); true if this iterator is behind the\n         * range and should not be dereferenced any more\n         */\n    bool atEnd() const\n    {\n        return index_ == end_;\n    }\n\n        /**\n         * the opposite of atEnd(); true if this iterator is dereferencable\n         */\n    bool inRange() const\n    {\n        return index_ != end_;\n    }\n\n    reference operator*() const\n    {\n        return (*edge_)[index_];\n    }\n\n    pointer operator->() const\n    {\n        return &(operator*());\n    }\n};\n\nclass GeoMap::Dart\n{\n  protected:\n    GeoMap *map_;\n    int     label_;\n\n    CellLabel &internalLeftFaceLabel()\n    {\n        if(label_ > 0)\n            return guaranteedEdge()->leftFaceLabel_;\n        else\n            return guaranteedEdge()->rightFaceLabel_;\n    }\n\n    friend class Face; // allow internalLeftFaceLabel in Face constructor\n    friend GeoMap::FacePtr GeoMap::mergeFaces(const Dart &);\n\n  public:\n    Dart(GeoMap *map, int label)\n    : map_(map),\n      label_(label)\n    {}\n\n    Dart clone() const\n    {\n        return Dart(map_, label_);\n    }\n\n    int label() const\n    {\n        return label_;\n    }\n\n    GeoMap *map() const\n    {\n        return map_;\n    }\n\n    CellLabel edgeLabel() const\n    {\n        return abs(label_);\n    }\n\n    CellLabel startNodeLabel() const\n    {\n        if(label_ > 0)\n            return guaranteedEdge()->startNodeLabel();\n        else\n            return guaranteedEdge()->endNodeLabel();\n    }\n\n    CellLabel endNodeLabel() const\n    {\n        if(label_ > 0)\n            return guaranteedEdge()->endNodeLabel();\n        else\n            return guaranteedEdge()->startNodeLabel();\n    }\n\n//         def _setStartNode(self, node):\n//             \"\"\"changes corresponding start/end node of this dart's\n//             edge and the first/last point of its' polygon, too\"\"\"\n//             if self._label > 0:\n//                 self.edge()._startNodeLabel = node._label\n//                 self.edge()[0] = node.position()\n//                 #self.edge().invalidateProperties()\n//             else:\n//                 self.edge()._endNodeLabel = node._label\n//                 self.edge()[-1] = node.position()\n//                 #self.edge().invalidateProperties()\n\n    CellLabel leftFaceLabel() const\n    {\n        if(label_ > 0)\n            return guaranteedEdge()->leftFaceLabel();\n        else\n            return guaranteedEdge()->rightFaceLabel();\n    }\n\n    CellLabel rightFaceLabel() const\n    {\n        if(label_ > 0)\n            return guaranteedEdge()->rightFaceLabel();\n        else\n            return guaranteedEdge()->leftFaceLabel();\n    }\n\n    GeoMap::EdgePtr edge() const\n    {\n        return map_->edge(edgeLabel());\n    }\n\n    GeoMap::EdgePtr guaranteedEdge() const\n    {\n        GeoMap::EdgePtr result(edge());\n        if(!result)\n        {\n            std::stringstream s;\n            s << \"Cannot operate on invalid dart \" << label()\n              << \" belonging to removed edge!\";\n            vigra_precondition(static_cast<bool>(result), s.str());\n        }\n        return result;\n    }\n\n    GeoMap::NodePtr startNode() const\n    {\n        return map_->node(startNodeLabel());\n    }\n\n    GeoMap::NodePtr endNode() const\n    {\n        return map_->node(endNodeLabel());\n    }\n\n    GeoMap::FacePtr leftFace() const\n    {\n        return map_->face(leftFaceLabel());\n    }\n\n    GeoMap::FacePtr rightFace() const\n    {\n        return map_->face(rightFaceLabel());\n    }\n\n    double partialArea() const\n    {\n        if(label_ > 0)\n            return guaranteedEdge()->partialArea();\n        else\n            return -guaranteedEdge()->partialArea();\n    }\n\n    DartPointIter pointIter() const\n    {\n        return DartPointIter(*this);\n    }\n\n    typedef GeoMap::Edge::value_type value_type;\n\n    const value_type &operator[](int index) const\n    {\n        if(label_ > 0)\n            return (*guaranteedEdge())[index];\n        else\n            return (*guaranteedEdge())[size()-1-index];\n    }\n\n    GeoMap::Edge::size_type size() const\n    {\n        return guaranteedEdge()->size();\n    }\n\n    Dart &nextAlpha()\n    {\n        label_ = -label_;\n        return *this;\n    }\n\n    Dart &nextSigma()\n    {\n        label_ = map_->sigmaMapping_[label_];\n        return *this;\n    }\n\n    Dart &prevSigma()\n    {\n        label_ = map_->sigmaInverseMapping_[label_];\n        return *this;\n    }\n\n    Dart &nextPhi()\n    {\n        return nextAlpha().prevSigma();\n    }\n\n    Dart &prevPhi()\n    {\n        return nextSigma().nextAlpha();\n    }\n\n    bool operator==(const Dart &other) const\n    {\n        return label_ == other.label_;\n    }\n\n    bool operator!=(const Dart &other) const\n    {\n        return label_ != other.label_;\n    }\n};\n\n/*\n * Note: This code is based on the assumption that a dart must always\n * have a least two points!\n */\nclass ContourPointIter\n{\n    DartPointIter dpi_;\n    GeoMap::Dart dart_, end_;\n\n  public:\n        /** the iterator's value type\n        */\n    typedef GeoMap::Edge::value_type value_type;\n\n        /** the iterator's reference type (return type of <tt>*iter</tt>)\n        */\n    typedef value_type & reference;\n\n        /** the iterator's pointer type (return type of <tt>operator-></tt>)\n        */\n    typedef value_type * pointer;\n\n        /** the iterator tag (forward_iterator_tag)\n        */\n    typedef std::forward_iterator_tag iterator_category;\n\n    ContourPointIter(GeoMap::Dart const &dart, bool firstTwice = false)\n    : dpi_(dart),\n      dart_(dart),\n      end_(dart)\n    {\n        if(!firstTwice)\n            ++dpi_;\n    }\n\n    ContourPointIter & operator++()\n    {\n        ++dpi_;\n        if(dpi_.atEnd())\n        {\n            if(dart_.nextPhi() != end_)\n            {\n                dpi_ = DartPointIter(dart_);\n                ++dpi_;\n            }\n        }\n        return *this;\n    }\n\n    ContourPointIter operator++(int)\n    {\n        ContourPointIter ret(*this);\n        operator++();\n        return ret;\n    }\n\n    /**\n     * the opposite of inRange(); true if this iterator is behind the\n     * range and should not be dereferenced any more\n     */\n    bool atEnd() const\n    {\n        return dpi_.atEnd();\n    }\n\n    /**\n     * the opposite of atEnd(); true if this iterator is dereferencable\n     */\n    bool inRange() const\n    {\n        return dpi_.inRange();\n    }\n\n    reference operator*() const\n    {\n        return *dpi_;\n    }\n\n    pointer operator->() const\n    {\n        return &(operator*());\n    }\n};\n\ndouble angleTheta(double dy, double dx);\ndouble contourArea(const GeoMap::Dart &dart);\ndouble contourLength(const GeoMap::Dart &dart);\ndouble isoperimetricQuotient(const GeoMap::Dart &dart);\nVector2Polygon contourPoly(const GeoMap::Dart &dart);\n\n/********************************************************************/\n/*                                                                  */\n/*                           GeoMap::Face                           */\n/*                                                                  */\n/********************************************************************/\n\nclass GeoMap::Face : boost::noncopyable\n{\n  public:\n    typedef Edge::BoundingBox BoundingBox;\n    // Interestingly, std::vector seems to be faster than\n    // std::list here, although we frequently need\n    // erase/concatenation (cf. splice in cppmap.cxx):\n    typedef std::vector<Dart> Contours;\n    typedef Contours::const_iterator ContourIterator;\n\n  protected:\n    GeoMap              *map_;\n    CellLabel            label_;\n    Contours             anchors_;\n    mutable CellFlags    flags_;\n    mutable BoundingBox  boundingBox_;\n    mutable double       area_;\n    unsigned int         pixelArea_;\n\n    enum {\n        BOUNDING_BOX_VALID = 0x80000000U,\n        AREA_VALID         = 0x40000000U,\n        INTERNAL_FLAGS     = 0xf0000000U,\n    };\n\n    friend class GeoMap; // give access to pixelArea_ and anchors_ (Euler ops...)\n\n    inline void uninitialize();\n    typedef Contours::iterator AnchorIterator; // non-const ContourIterator\n    AnchorIterator findComponentAnchor(const GeoMap::Dart &dart);\n\n    Face(GeoMap *map, Dart anchor)\n    : map_(map),\n      label_(map->faces_.size()),\n      flags_(0),\n      pixelArea_(0)\n    {\n        map_->faces_.push_back(GeoMap::FacePtr(this));\n        ++map_->faceCount_;\n\n        if(label_)\n        {\n            anchors_.push_back(anchor);\n\n            for(; anchor.internalLeftFaceLabel() == UNINITIALIZED_CELL_LABEL;\n                anchor.nextPhi())\n            {\n                anchor.internalLeftFaceLabel() = label_;\n\n                // don't calculate area on-the-fly here; we want to\n                // exclude bridges from the area!\n            }\n        }\n    }\n\n        // copy constructor for copying GeoMaps\n    Face(GeoMap *map, const Face &other)\n    : map_(map),\n      label_(other.label_),\n      flags_(other.flags_),\n      boundingBox_(other.boundingBox_),\n      area_(other.area_),\n      pixelArea_(other.pixelArea_)\n    {\n        for(unsigned int i = 0; i < other.anchors_.size(); ++i)\n            anchors_.push_back(Dart(map, other.anchors_[i].label()));\n    }\n\n  public:\n    bool initialized() const\n    {\n        return map_ != NULL;\n    }\n\n    CellLabel label() const\n    {\n        return label_;\n    }\n\n    const BoundingBox &boundingBox() const\n    {\n        vigra_precondition(label_, \"infinite face has no boundingBox()!\");\n\n        if(!flag(BOUNDING_BOX_VALID))\n        {\n            boundingBox_ = BoundingBox();\n            Dart anchor(*anchors_.begin()), dart(anchor);\n            do\n            {\n                boundingBox_ |= dart.edge()->boundingBox();\n            }\n            while(dart.nextPhi() != anchor);\n            flags_ |= BOUNDING_BOX_VALID;\n        }\n        return boundingBox_;\n    }\n\n    bool contains(const Vector2 &point) const\n    {\n        vigra_precondition(initialized(), \"contains() of uninitialized face!\");\n        if(map_->labelImage_)\n        {\n            detail::IVector2 iPos(detail::intVPos(point));\n            if(map_->labelImage_->isInside(iPos))\n            {\n                int l = (*map_->labelImage_)[iPos];\n                if(l > 0)\n                    return map_->faceLabelLUT_[l] == label_;\n            }\n        }\n        ContourIterator it = contoursBegin();\n        if(label_)\n        {\n            if(!boundingBox().contains(point))\n                return false;\n            if(!contourPoly(*it).contains(point))\n                return false;\n            ++it;\n        }\n        for(; it != contoursEnd(); ++it)\n            if(contourPoly(*it).contains(point))\n                return false;\n        return true;\n    }\n\n    double area() const\n    {\n        if(!flag(AREA_VALID))\n        {\n            area_ = 0.0;\n            for(ContourIterator it = contoursBegin();\n                it != contoursEnd(); ++it)\n            {\n                area_ += contourArea(*it);\n            }\n            flags_ |= AREA_VALID;\n        }\n        return area_;\n    }\n\n    std::auto_ptr<vigra::Scanlines> scanLines() const\n    {\n        int startIndex = (int)floor(boundingBox().begin()[1] + 0.5);\n        int endIndex = (int)floor(boundingBox_.end()[1] + 0.5);\n\n        std::auto_ptr<vigra::Scanlines> result(\n            new vigra::Scanlines(startIndex, endIndex - startIndex + 1));\n\n        Dart anchor(*anchors_.begin()), dart(anchor);\n        do\n        {\n            if(dart.label() > 0)\n            {\n                result->merge(dart.edge()->scanLines());\n            }\n            else\n            {\n                vigra::Scanlines sl(dart.edge()->scanLines());\n                sl.reverse();\n                result->merge(sl);\n            }\n        }\n        while(dart.nextPhi() != anchor);\n\n        result->normalize();\n\n        return result;\n    }\n\n    unsigned int pixelArea() const\n    {\n        return pixelArea_;\n    }\n\n    const Dart &contour()\n    {\n        return *contoursBegin();\n    }\n\n    ContourIterator contoursBegin() const\n    {\n        return anchors_.begin();\n    }\n\n    ContourIterator contoursEnd() const\n    {\n        return anchors_.end();\n    }\n\n    ContourIterator holesBegin() const\n    {\n        ContourIterator result(anchors_.begin());\n        if(label())\n            ++result;\n        return result;\n    }\n\n    unsigned int holeCount() const\n    {\n        return anchors_.size() - (label() ? 1 : 0);\n    }\n\n    void embedContour(const Dart &anchor);\n\n    bool operator==(const GeoMap::Face &other)\n    {\n        return label() == other.label();\n    }\n\n    bool operator!=(const GeoMap::Face &other)\n    {\n        return !operator==(other);\n    }\n\n    CellFlags flags() const\n    {\n        return flags_;\n    }\n\n    CellFlags flag(CellFlags which) const\n    {\n        return flags_ & which;\n    }\n\n    void setFlag(CellFlags flag, bool onoff = true)\n    {\n        if(onoff)\n            flags_ |= flag;\n        else\n            flags_ &= ~flag;\n    }\n\n    GeoMap *map() const\n    {\n        return map_;\n    }\n};\n\n/********************************************************************/\n\ninline GeoMap::Dart GeoMap::dart(int label)\n{\n    return GeoMap::Dart(this, label);\n}\n\ninline void GeoMap::Node::uninitialize()\n{\n    GeoMap *map = map_;\n    map_ = NULL; // DON'T MESS WITH THIS!\n    --map->nodeCount_;\n    map->nodeMap_.erase(\n        map->nodeMap_.nearest(PositionedNodeLabel(position_, label_),\n                              vigra::NumericTraits<double>::epsilon()));\n    RESET_PTR(map->nodes_[label_]); // may have effect like \"delete this;\"!\n}\n\ninline void GeoMap::Edge::uninitialize()\n{\n    GeoMap *map = map_;\n    map_ = NULL;\n    --map->edgeCount_;\n    RESET_PTR(map->edges_[label_]);\n}\n\ninline void GeoMap::Face::uninitialize()\n{\n    GeoMap *map = map_;\n    map_ = NULL;\n    --map->faceCount_;\n    RESET_PTR(map->faces_[label_]);\n}\n\ninline GeoMap::Dart GeoMap::Node::anchor() const\n{\n    vigra_precondition(initialized(), \"anchor() of uninitialized node!\");\n    vigra_precondition(anchor_ != 0, \"anchor() of degree 0 node!\");\n    return Dart(map_, anchor_);\n}\n\ninline unsigned int GeoMap::Node::degree() const\n{\n    if(!anchor_)\n        return 0;\n\n    int result = 0;\n    GeoMap::Dart d(map_, anchor_);\n    do\n    {\n        ++result;\n    }\n    while(d.nextSigma().label() != anchor_);\n\n    return result;\n}\n\ninline bool GeoMap::Node::hasMinDegree(unsigned int minDegree) const\n{\n    if(!anchor_)\n        return minDegree == 0;\n\n    if(!minDegree)\n        return true;\n\n    GeoMap::Dart d(map_, anchor_);\n    do\n    {\n        if(--minDegree == 0)\n            return true;\n    }\n    while(d.nextSigma().label() != anchor_);\n\n    return false;\n}\n\ninline bool GeoMap::Node::hasDegree(unsigned int exactDegree) const\n{\n    if(!anchor_)\n        return exactDegree == 0;\n\n    if(!exactDegree)\n        return false;\n\n    GeoMap::Dart d(map_, anchor_);\n    do\n    {\n        if(d.nextSigma().label() == anchor_)\n            return exactDegree == 1;\n    }\n    while(--exactDegree);\n    return false;\n}\n\ninline GeoMap::Dart GeoMap::Edge::dart() const\n{\n    return map_->dart(label());\n}\n\n/********************************************************************/\n\nclass GeoMap::SigmaAnchor\n{\n  public:\n    SigmaAnchor(const GeoMap::Node &node)\n    : isSingular_(node.isIsolated()),\n      dartLabel_(node.anchor_),\n      nodeLabel_(node.label()),\n      map_(node.map())\n    {\n        vigra_precondition(isSingular_ || !node.map()->edgesSorted(),\n            \"sigma position of sorted GeoMap not fully specified\");\n    }\n\n    SigmaAnchor(const GeoMap::Dart &dart)\n    : isSingular_(false),\n      dartLabel_(dart.label()),\n      nodeLabel_(dart.startNodeLabel()),\n      map_(dart.map())\n    {\n    }\n\n    bool isSingular() const\n    {\n        return isSingular_;\n    }\n\n    int dartLabel() const\n    {\n        return dartLabel_;\n    }\n\n    CellLabel nodeLabel() const\n    {\n        return nodeLabel_;\n    }\n\n    bool operator==(const GeoMap::SigmaAnchor &other) const\n    {\n        if(isSingular() != other.isSingular())\n            return false;\n        if(isSingular())\n            return nodeLabel_ == other.nodeLabel_;\n        else\n            return dartLabel_ == other.dartLabel_;\n    }\n\n  private:\n    bool isSingular_;\n    int dartLabel_;\n    CellLabel nodeLabel_;\n    GeoMap *map_;\n};\n\n/********************************************************************/\n\n#include <iostream> // FIXME: not here, please!\n\n/**\n * A DartPosition object represents a (variable) position on a (fixed)\n * dart.\n *\n * The exact current position can be queried with dp() (where dp\n * denotes a DartPosition object), and always lies on the Dart's\n * polygon.  It may not be identical to any of the Dart's support\n * points though, but may lie on the polyline segment between to\n * support points.  This segment is then called the \"current segment\",\n * and segmentIndex() gives its index between 0 and N-2, where N is\n * the number of points in the Dart.\n */\nclass DartPosition\n{\n  public:\n    DartPosition(const GeoMap::Dart &dart)\n    : dart_(dart),\n      pointIter_(dart),\n      segmentIndex_(0),\n      arcLength_(0.0),\n      partialArcLength_(0.0),\n      position_(*pointIter_)\n    {\n        p1_ = *pointIter_;\n        p2_ = *++pointIter_;\n    }\n\n    bool atEnd() const\n    {\n        return pointIter_.atEnd();\n    }\n\n    const Vector2 &operator()() const\n    {\n        return position_;\n    }\n\n    GeoMap::Dart dart() const\n    {\n        return dart_;\n    }\n\n    int dartLabel() const\n    {\n        return dart_.label();\n    }\n\n    unsigned int segmentIndex() const\n    {\n        return segmentIndex_;\n    }\n\n    double arcLength() const\n    {\n        return arcLength_ + partialArcLength_;\n    }\n\n    const Vector2 &segmentStart() const\n    {\n        return p1_;\n    }\n\n    const Vector2 &segmentEnd() const\n    {\n        return p2_;\n    }\n\n    double segmentLength() const\n    {\n        return (p2_ - p1_).magnitude();\n    }\n\n        /// Try to go to the exact given arcLength (forward or backward).\n        /// Returns false iff not possible (i.e. arcLength out of range).\n    bool gotoArcLength(double arcLength)\n    {\n        while(arcLength < arcLength_)\n            if(!prevSegmentInternal())\n                return false;\n        do\n        {\n            double rest = arcLength - arcLength_;\n            Vector2 diff(p2_ - p1_);\n            if(diff.squaredMagnitude() > rest*rest)\n            {\n                position_ = p1_ + diff*rest/diff.magnitude();\n                partialArcLength_ = rest;\n                return true;\n            }\n        }\n        while(nextSegmentInternal());\n\n        // hit end\n        position_ = p1_;\n        partialArcLength_ = 0.0;\n        return false;\n    }\n\n        // Go to the beginning of the next segment if possible\n        // (i.e. segmentIndex() will increase).  Otherwise, return\n        // false.\n    bool gotoNextSegment()\n    {\n        bool result = nextSegmentInternal();\n        position_ = p1_;\n        partialArcLength_ = 0.0;\n        return result;\n    }\n\n    bool gotoPrevSegment()\n    {\n        bool result = prevSegmentInternal();\n        position_ = p1_;\n        partialArcLength_ = 0.0;\n        return result;\n    }\n\n    bool leaveCircle(const Vector2 &center, double radius2)\n    {\n        while((p2_ - center).squaredMagnitude() < radius2)\n            if(!nextSegmentInternal())\n                break;\n\n        position_ = p2_;\n        partialArcLength_ = (p2_ - p1_).magnitude();\n        return !atEnd();\n    }\n\n    bool intersectCircle(const Vector2 &center, double radius2)\n    {\n        // unfortunately, this prevents larger steps:\n//         if((p1_ - center).squaredMagnitude() >= radius2)\n//         {\n//             std::cerr << \"intersectCircle: we are already outside!\\n\";\n//             position_ = p1_;\n//             return;\n//         }\n        while((p2_ - center).squaredMagnitude() < radius2)\n        {\n            if(!nextSegmentInternal())\n            {\n                position_ = p2_;\n                return false;\n            }\n        }\n\n        Vector2 diff(p2_ - p1_);\n        double dist2 = diff.squaredMagnitude();\n        double lambda = (\n            (std::sqrt(radius2 * dist2\n                       - vigra::sq(p2_[0]*p1_[1] - p1_[0]*p2_[1]\n                                   + center[0]*diff[1] - diff[0]*center[1]))\n             - dot(diff, p1_ - center))\n            / dist2);\n        if(!boost::math::isnan(lambda))\n            diff *= lambda;\n        else\n        {\n            std::cerr << \"intersectCircle: error interpolating between \" << p1_ << \" and \" << p2_ << \" to a squared distance of \" << radius2 << \" from \" << center << \"!\\n\";\n        }\n        position_ = p1_ + diff;\n        partialArcLength_ = diff.magnitude();\n        return true;\n    }\n\n  protected:\n    bool nextSegmentInternal()\n    {\n        if(atEnd())\n            return false;\n        arcLength_ += (p2_ - p1_).magnitude();\n        p1_ = p2_;\n        ++pointIter_;\n        if(pointIter_.atEnd())\n            return false;\n        p2_ = *pointIter_;\n        ++segmentIndex_;\n        return true;\n    }\n\n    bool prevSegmentInternal()\n    {\n        if(!segmentIndex_)\n            return false;\n        // now I assume that pointIter_ can step backwards and still\n        // is inRange():\n        pointIter_.reverse();\n        p2_ = p1_;\n        ++pointIter_;\n        pointIter_.reverse();\n        p1_ = *pointIter_;\n        arcLength_ -= (p2_ - p1_).magnitude();\n        --segmentIndex_;\n        return true;\n    }\n\n    GeoMap::Dart dart_;\n    DartPointIter pointIter_;\n    unsigned int segmentIndex_;\n    double arcLength_, partialArcLength_;\n    Vector2 p1_, p2_, position_;\n};\n\n/********************************************************************/\n\nnamespace detail {\n\nstruct DartPositionAngle\n{\n    struct EdgePosition\n    {\n        unsigned int segmentIndex;\n        double arcLength;\n        Vector2 position;\n    };\n\n    struct CommonPos : public EdgePosition\n    {\n        CommonPos()\n        : isSet(false)\n        {}\n\n        const Vector2 &set(const DartPosition &dp)\n        {\n            position = dp();\n            segmentIndex = dp.segmentIndex();\n            arcLength = dp.arcLength();\n            isSet = true;\n            return position;\n        }\n\n        bool isSet;\n    };\n\n    DartPosition dp;\n    double absAngle, angle;\n    CommonPos commonPos;\n\n    DartPositionAngle(const GeoMap::Dart &dart)\n    : dp(dart)\n    {}\n\n    bool operator<(const DartPositionAngle &other) const\n    {\n        return angle < other.angle;\n    }\n\n    struct SplitPos : public EdgePosition\n    {\n        int dartLabel, sigmaPos;\n        unsigned int splitGroup;\n\n        SplitPos(const EdgePosition &ep, int dl, unsigned int sg)\n        : EdgePosition(ep),\n          dartLabel(dl),\n          splitGroup(sg)\n        {}\n\n        bool operator<(const SplitPos &other) const\n        {\n            return arcLength > other.arcLength;\n        }\n    };\n\n    SplitPos splitPos(unsigned int group) const\n    {\n        vigra_precondition(\n            commonPos.isSet, \"splitPos() called with uninitialized commonPos\");\n        SplitPos result(commonPos, dp.dartLabel(), group);\n        if(dp.dartLabel() < 0)\n        {\n            GeoMap::Edge &edge(*dp.dart().edge());\n            result.segmentIndex = edge.size()-2 - result.segmentIndex;\n            result.arcLength = edge.length() - result.arcLength;\n        }\n        return result;\n    }\n};\n\nclass PlannedSplits : public std::vector<DartPositionAngle::SplitPos>\n{\n  public:\n    PlannedSplits()\n    : splitGroupCount(0)\n    {}\n\n    unsigned int splitGroupCount;\n};\n\n} // namespace detail\n\n#endif // VIGRA_CPPMAP_HXX\n", "meta": {"hexsha": "337c426a0d63ae2c16e93945de75162aba7b543a", "size": 46385, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/geomap/cppmap.hxx", "max_stars_repo_name": "hmeine/geomap", "max_stars_repo_head_hexsha": "66463aaad5ff9132b017cd019cc428a910590334", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-11-29T03:13:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T03:11:19.000Z", "max_issues_repo_path": "src/geomap/cppmap.hxx", "max_issues_repo_name": "hmeine/geomap", "max_issues_repo_head_hexsha": "66463aaad5ff9132b017cd019cc428a910590334", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-15T14:26:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-27T10:03:15.000Z", "max_forks_repo_path": "src/geomap/cppmap.hxx", "max_forks_repo_name": "hmeine/geomap", "max_forks_repo_head_hexsha": "66463aaad5ff9132b017cd019cc428a910590334", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-27T12:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T12:45:03.000Z", "avg_line_length": 26.4001138304, "max_line_length": 172, "alphanum_fraction": 0.5630915167, "num_tokens": 10531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.046033904362384165, "lm_q1q2_score": 0.01754902505410518}}
{"text": "// This autogenerated skeleton file illustrates how to build a server.\n// You should copy it to another filename to avoid overwriting it.\n\n#include \"../../gen-cpp/Word2Vec.h\"\n#include <thrift/protocol/TBinaryProtocol.h>\n#include <thrift/server/TSimpleServer.h>\n#include <thrift/transport/TServerSocket.h>\n#include <thrift/transport/TBufferTransports.h>\n\nusing namespace std;\nusing namespace ::apache::thrift;\nusing namespace ::apache::thrift::concurrency;\nusing namespace ::apache::thrift::protocol;\nusing namespace ::apache::thrift::transport;\nusing namespace ::apache::thrift::server;\n\n//#include <google/dense_hash_map>\n#include <thrift/concurrency/ThreadManager.h>\n#include <thrift/concurrency/PosixThreadFactory.h>\n#include <thrift/protocol/TBinaryProtocol.h>\n#include <thrift/server/TNonblockingServer.h>\n#include <thrift/server/TSimpleServer.h>\n#include <thrift/server/TThreadPoolServer.h>\n#include <thrift/server/TThreadedServer.h>\n#include <thrift/transport/TServerSocket.h>\n#include <thrift/transport/TTransportUtils.h>\n#include <thrift/TToString.h>\n\n#include <fstream>\n#include <iostream>\n#include <math.h>\n#include <stdexcept>\n#include <sstream>\n\n#include <boost/numeric/ublas/vector_sparse.hpp>\n\nconst long long max_size = 2000;         // max length of strings\nconst long long N = 40;                  // number of closest words that will be shown\nconst long long max_w = 50;              // max length of vocabulary entries\n\nusing namespace boost::numeric::ublas;\nusing boost::shared_ptr;\n\nclass Word2VecHandler : virtual public Word2VecIf {\n\nprotected:\n  \n  float *M;\n  long long words;\n  long long size;\n\n  char st1[max_size];\n\n  char *vocab;\n\n  /* null vector */\n  boost::numeric::ublas::zero_vector<float> zero;\n\n  /* word to position map */\n  //  google::dense_hash_map<string,long long> word_to_position;\n\npublic:\n  Word2VecHandler( string file_name ) {\n\n    //word_to_position.set_empty_key( \"[[__EMPTRY_KEY__]]\" );\n\n    // Load word2vec model\n    char st[100][max_size];\n\n    float len;\n    long long a, c, d, bi[100];\n    char ch;\n\n    //ifstream f;\n    FILE *f;\n\n    cout << \"Loading vector space from: \" << file_name << endl;\n    //f.open( file_name.c_str() , ios::in | ios::binary );\n    f = fopen( file_name.c_str() , \"rb\" );\n\n    //if ( ! f.is_open() ) {\n    if ( f == NULL ) {\n      throw(\"Invalid model file ...\");\n    }\n\n    //f >> words;\n    /* note: we introduce n_read_words only to suppress unused-result warnings */\n    int n_read_words = fscanf(f, \"%lld\", &words);\n    cout << \"number of words : \" << words << endl;\n\n    //f >> size;\n    /* note: we introduce n_read_size only to suppress unused-result warnings */\n    int n_read_size = fscanf(f, \"%lld\", &size);\n    cout << \"size : \" << size << endl;\n\n    /* initialize null vector */\n    zero = boost::numeric::ublas::zero_vector<float>( size );\n\n    //    vocab = (char *)malloc((long long)words * max_w * sizeof(char));\n    vocab = new char[ ((long long)words * max_w * sizeof(char)) ];\n\n    // M = (float *)malloc((long long)words * (long long)size * sizeof(float));\n    M = new float[ ((long long)words * (long long)size * sizeof(float)) ];\n\n    if (M == NULL) {\n      throw (\"Cannot allocate memory: %lld MB    %lld  %lld\\n\", (long long)words * size * sizeof(float) / 1048576, words, size);\n    }\n    for (long long b = 0; b < words; b++) {\n      a = 0;\n\n      while ( 1 ) {\n\tlong long vocab_index = b * max_w + a;\n\n\t//f.get( vocab + vocab_index , 1 );\n\tvocab[ vocab_index ] = fgetc(f);\n\n\t//if (f.eof() || (vocab[ vocab_index ] == ' ')) break;\n\tif ( feof(f) || ( vocab[ vocab_index ] == ' ' ) ) break;\n\n\tif ((a < max_w) && (vocab[ vocab_index ] != '\\n')) a++;\n      }\n      vocab[b * max_w + a] = 0;\n\n      /* TODO : reinterpret_cast seems to be a terrible idea */\n      /* http://stackoverflow.com/questions/2473628/c-cant-static-cast-from-double-to-int */\n      //for (a = 0; a < size; a++) f.read( reinterpret_cast<char*>( &M[a + b * size] ), sizeof(float) );\n      for (a = 0; a < size; a++)\n\t/* note: we introduce n_read only to suppress unused-result warnings */\n\tint n_read = fread( &M[a + b * size] , sizeof(float) , 1 , f );\n\n      len = 0;\n      for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size];\n      len = sqrt(len);\n      for (a = 0; a < size; a++) M[a + b * size] /= len;\n\n      /* CURRENT : is this even necessary ? check vocab_index above */\n      /* store word position */\n      //word_to_position[ word ] = b;\n\n    }\n\n    //f.close();\n    fclose( f );\n    \n  }\n\n  long long _get_vocabulary_position( string word ) {\n\n    long long b;\n\n    // TODO : implement some for of binary search here ?\n    for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], word.c_str())) break;\n\n    cout << endl << \"Word: \" << word << \" \";\n\n    // TODO : print status via shared string => reduce code duplication\n    if (b == words) {\n      cout << \"[out of vocabulary]\";\n      b = -1;\n    }\n    else {\n      cout << \"Position in vocabulary: \" << b;\n    }\n\n    cout << endl;\n\n    return b;\n\n  }\n\n  const std::vector<ScoredString> _get_nearest_vocabulary( const boost::numeric::ublas::vector<float> vec , long n_requested , std::vector<long long> exclude ) {\n\n    long long a, c;\n    float dist;\n\n    std::vector<long long>::const_iterator exclude_iter;\n\n    /* we look for more locations than actually requested , accounting for locations that may match the exclude list */\n    long n_adjusted = n_requested + exclude.size();\n    float bestd[n_adjusted];\n    long long besti[n_adjusted];\n    char bestw[n_adjusted][max_size];\n\n    for (a = 0; a < n_adjusted; a++) bestd[a] = 0;\n    for (a = 0; a < n_adjusted; a++) bestw[a][0] = 0;\n    for (c = 0; c < words; c++) {\n\n      /* Note : this totally looks redundant with what's coming just before ... remove ?\n\t a = 0;\n\t for (b = 0; b < 3; b++) if (bi[b] == c) a = 1;\n\t if (a == 1) continue;\n      */\n      \n      /* compute distance with the current word */\n      /* Note : is there a way to optimize / speed this up ? */\n      dist = 0;\n      for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size];\n      for (a = 0; a < n_adjusted; a++) {\n        if (dist > bestd[a]) {\n          for (long long d = n_adjusted - 1; d > a; d--) {\n            bestd[d] = bestd[d - 1];\n\t    besti[d] = besti[d - 1];\n            strcpy(bestw[d], bestw[d - 1]);\n          }\n          bestd[a] = dist;\n\t  besti[a] = c;\n          strcpy(bestw[a], &vocab[c * max_w]);\n          break;\n        }\n      }\n\n    }\n\n    std::vector<ScoredString> results;\n\n    cout << endl << \"                                              Word              Distance\\n------------------------------------------------------------------------\" << endl;\n    for (a = 0; a < n_adjusted; a++) {\n\n      /* TODO : keep track of vocabulary position */\n      bool do_exclude = false;\n      exclude_iter = exclude.begin();\n      while( exclude_iter != exclude.end() ) {\n\tif ( besti[ a ] == *exclude_iter++ ) {\n\t  do_exclude = true;\n\t  break;\n\t}\n      }\n\n      if ( do_exclude ) {\n\tcontinue;\n      }\n\n      cout << bestw[ a ] << \"\\t\\t\" << bestd[ a ] << endl;\n\n      ScoredString word_entry;\n      word_entry.word = bestw[ a ];\n      word_entry.score = bestd[ a ];\n      results.push_back( word_entry );\n    }\n\n    return results;\n\n  }\n\n  void ping() { cout << \"ping()\" << endl; }\n\n  /**\n   * Prints 'testList(\"{%s}\")' where thing has been formatted into a string of  values\n   *  separated by commas and new lines\n   * @param list<i32> thing - the list<i32> to print\n   * @return list<i32> - returns the list<i32> 'thing'\n   * \n   * @param word1\n   * @param word2\n   * @param word3\n   */\n  void analogy(std::vector<ScoredString> & _return, const std::string& word1, const std::string& word2, const std::string& word3) {\n\n    cout << \"analogy(\" << word1 << \", \" << word2 << \", \" << word3 << \")\" << endl;\n\n    long long a;\n    std::vector<long long> bi( 3 );\n\n    boost::numeric::ublas::vector<float> vec1 = get_coordinates( word1 );\n    boost::numeric::ublas::vector<float> vec2 = get_coordinates( word2 );\n    boost::numeric::ublas::vector<float> vec3 = get_coordinates( word3 );\n\n    /* TODO : we should be throwing exceptions instead */\n    bool can_proceed = ( ! boost::numeric::ublas::norm_1( vec1 ) ||\n\t\t\t ! boost::numeric::ublas::norm_1( vec2 ) ||\n\t\t\t ! boost::numeric::ublas::norm_1( vec3 ) );\n    if ( ! can_proceed ) {\n      return;\n    }\n\n    /* vector computation - specific to the analogy problem */\n    boost::numeric::ublas::vector<float> vec = vec2 - vec1 + vec3;\n    vec /= boost::numeric::ublas::norm_2( vec );\n\n    _return = _get_nearest_vocabulary( vec , N , bi );\n\n  }\n\n  /**\n   * Returns the distance between two words\n   * @param string word1 - the first word\n   * @param string word2 - the second word\n   * @return float - distance between word1 and word2\n   * \n   * @param word1\n   * @param word2\n   */\n  double distance(const std::string& word1, const std::string& word2) {\n\n    /* 1 - get coordinates for word1 */\n    boost::numeric::ublas::vector<float> vec1 = get_coordinates( word1 );\n\n    /* 2 - get coordinates for word2 */\n    boost::numeric::ublas::vector<float> vec2 = get_coordinates( word2 );\n\n    /* 3 - compute distance */\n    double distance = boost::numeric::ublas::norm_2( vec1 - vec2 );\n\n    return distance;\n\n  }\n\n  /**\n   * Returns the cosine similarity between two words\n   * @param string word1 - the first word\n   * @param string word2 - the second word\n   * @param double rescale - how much to rescale vectors for cosine computation\n   * @return float - cosine similarity between word1 and word2\n   * \n   * @param word1\n   * @param word2\n   */\n  double cosine_similarity(const std::string& word1, const std::string& word2 ) {\n\n    /* 1 - get coordinates for word1 */\n    boost::numeric::ublas::vector<float> vec1 = get_coordinates( word1 );\n    \n    /* 2 - get coordinates for word2 */\n    boost::numeric::ublas::vector<float> vec2 = get_coordinates( word2 );\n    \n    /* 3 - compute cosine similarity */\n    double inner_prod = boost::numeric::ublas::inner_prod( vec1 , vec2 );\n\n    /* Note : if the inner product is not a number this means (?) that at least one of the two vectors was the null vector */\n    double cosine_similarity = ( inner_prod == 0 || isnan( inner_prod ) ) ? 0 : ( inner_prod / ( boost::numeric::ublas::norm_2( vec1 ) * boost::numeric::ublas::norm_2( vec2 ) ) );\n\n    cout << \"Cosine similarity ( \" << word1 << \" , \" << word2 << \" ) : \" << inner_prod << \" \" << cosine_similarity << endl;\n\n    return cosine_similarity;\n\n  } \n\n  const boost::numeric::ublas::vector<float> get_coordinates( const std::string& word ) {\n    \n    boost::numeric::ublas::vector<float> coordinates( size );\n\n    /* 1 - attempt to get coordinates for word as a phrase */\n    coordinates = _get_coordinates( word );\n\n    /* 2 - attempt to get coordinates using compositionality */\n    if ( ! boost::numeric::ublas::norm_1( coordinates ) ) {\n\n      cout << \"Will process \" << word << \" using compositionality ... \" << endl;\n\n      istringstream word_ss( word );\n      std::vector<string> words;\n      copy( istream_iterator<string>( word_ss ),\n\t    istream_iterator<string>(),\n\t    back_inserter(words) );\n      \n      for ( std::vector<string>::iterator it=words.begin(); it!=words.end(); ++it ) {\n\tcoordinates += _get_coordinates( *it );\n      }\n\n      /* TODO : turn this into a method to avoid code duplication */\n      coordinates /= boost::numeric::ublas::norm_2( coordinates );\n\n    }\n\n    return coordinates;\n\n  }\n\n  const boost::numeric::ublas::vector<float> _get_coordinates( const std::string& word ) {\n\n    /* 0 - replace white spaces with underscores */\n    string word_normalized = word;\n    std::replace( word_normalized.begin() , word_normalized.end() , ' ', '_' );\n\n    /* 1 - determine vocabulary position */\n    long long vocabulary_position = _get_vocabulary_position( word_normalized );\n\n    if ( vocabulary_position == -1 ) {\n      // TODO : should we return an exception instead ?\n      return zero;\n    }\n\n    /* 2 - retrieve coordinates */\n    boost::numeric::ublas::vector<float> coordinates( size );\n    for (long a = 0; a < size; a++) {\n      coordinates[ a ] = M[ a + vocabulary_position * size ];\n      /*\n      if ( coordinates[ a ] < 0 ) {\n      \tcout << \"Found negative coordinate: \" << a << \" / \" << coordinates[ a ] << endl;\n      }\n      */\n    }    \n\n    return coordinates;\n\n  }\n\n  /* nearest neighbor / phrase => coordinates computed by summing up the coordinates of individual terms */\n\n};\n\n  /* TODO : add command line parameter to control the type of server that should be instantiated */\nint main(int argc, char **argv) {\n\n  int port = 9090;\n\n  string filename_model( argv[ 1 ] );\n  shared_ptr<Word2VecHandler> handler(new Word2VecHandler( filename_model ));\n  shared_ptr<TProcessor> processor(new Word2VecProcessor(handler));\n  shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));\n  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());\n  shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());\n\n  /**\n  TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);\n  */\n\n  const int workerCount = 800;\n\n  boost::shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workerCount);\n  boost::shared_ptr<PosixThreadFactory> threadFactory = boost::shared_ptr<PosixThreadFactory>(new PosixThreadFactory());\n\n  threadManager->threadFactory(threadFactory);\n  threadManager->start();\n\n  //  /* previous version\n  TThreadPoolServer server(processor,\n                           serverTransport,\n                           transportFactory,\n                           protocolFactory,\n                           threadManager);\n  //*/\n\n  /* limited by ulimit -n (1024) => accept() Too many open files\n  TThreadedServer server(processor,\n                         serverTransport,\n                         transportFactory,\n                         protocolFactory);\n  */\n\n  //  TNonblockingServer server(processor, protocolFactory, port, threadManager);\n  //TNonblockingServer server(processor, protocolFactory, port, threadManager);\n\n  cout << \"Starting the server...\" << endl;\n  server.serve();\n  cout << \"Done.\" << endl;\n\n  return 0;\n\n}\n", "meta": {"hexsha": "39d0507c28bdb307eb818c9144671f3e7982572b", "size": 14241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "services/word2vec-service/src/c++/word2vec_server.cpp", "max_stars_repo_name": "ypetinot/web-summarization", "max_stars_repo_head_hexsha": "2f7caf51b1e8bf5e510ce91070d622c8119e9865", "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": "services/word2vec-service/src/c++/word2vec_server.cpp", "max_issues_repo_name": "ypetinot/web-summarization", "max_issues_repo_head_hexsha": "2f7caf51b1e8bf5e510ce91070d622c8119e9865", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "services/word2vec-service/src/c++/word2vec_server.cpp", "max_forks_repo_name": "ypetinot/web-summarization", "max_forks_repo_head_hexsha": "2f7caf51b1e8bf5e510ce91070d622c8119e9865", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-03-03T04:58:44.000Z", "max_forks_repo_forks_event_max_datetime": "2016-03-03T04:58:44.000Z", "avg_line_length": 31.5764966741, "max_line_length": 179, "alphanum_fraction": 0.6110525946, "num_tokens": 3748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.039048288812218064, "lm_q1q2_score": 0.0175480128047595}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n#include \"BlockMatrixIterators.hpp\"\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrix.hpp\"\n#include \"SiconosAlgebra.hpp\"\n\nusing namespace Siconos;\n\nvoid SimpleMatrix::addBlock(unsigned int row_min, unsigned int col_min, const SiconosMatrix& m)\n{\n  // add m to current matrix elements, starting from row row_min and column col_min, to the values of the matrix m.\n  // m may be a BlockMatrix.\n\n  if (_num == 6 || _num == 7)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::addBlock(pos,..., m) forbidden for zero or identity matrix.\");\n\n  if (&m == this)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::addBlock(pos,..., m): m = this.\");\n\n  if (row_min >= size(0))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::addBlock(row,col): row is out of range\");\n\n  if (col_min >= size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::addBloc(row,col)k: col is out of range\");\n\n  unsigned int row_max, col_max;\n  row_max = m.size(0) + row_min;\n  col_max = m.size(1) + col_min;\n\n  if (row_max > size(0))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::addBlock(row,col,m): m.row + row is out of range.\");\n\n  if (col_max > size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::addBlock(row,col,m): m.col + col is out of range.\");\n\n  unsigned int numM = m.num();\n\n  if (numM == 0) // if m is a block matrix ...\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    BlocksMat::const_iterator1 it;\n    BlocksMat::const_iterator2 it2;\n    unsigned int posRow = row_min;\n    unsigned int posCol = col_min;\n\n    for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for (it2 = it.begin(); it2 != it.end(); ++it2)\n      {\n        addBlock(posRow, posCol, **it2);\n        posCol += (*it2)->size(1);\n      }\n      posRow += (*it)->size(0);\n      posCol = 0;\n    }\n  }\n  else if (numM == 6) // if m = 0\n  {\n    // nothing to do !\n  }\n  else // if m is a SimpleMatrix\n  {\n    if (_num == 1)\n    {\n      switch (numM)\n      {\n      case 1:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) += *(m.dense());\n        break;\n      case 2:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) += *(m.triang());\n        break;\n      case 3:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) += *(m.sym());\n        break;\n      case 4:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) += *(m.sparse());\n        break;\n      case 5:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) += *(m.banded());\n        break;\n      case 7:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) += *(m.identity());\n        break;\n      default:\n        SiconosMatrixException::selfThrow(\"SimpleMatrix::addBlock(...,m): wrong matrix type for m.\");\n        break;\n      }\n    }\n    else\n      SiconosMatrixException::selfThrow(\"SimpleMatrix::addBlock(...): implemented only for dense matrices.\");\n    resetLU();\n  }\n}\n\nvoid SimpleMatrix::subBlock(unsigned int row_min, unsigned int col_min, const SiconosMatrix& m)\n{\n  // sub m to current matrix elements, starting from row row_min and column col_min, to the values of the matrix m.\n  // m may be a BlockMatrix.\n\n  if (_num == 6 || _num == 7)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(pos,..., m) forbidden for zero or identity matrix.\");\n\n  if (&m == this)\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(pos,..., m): m = this.\");\n\n  if (row_min >= size(0))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(row,col): row is out of range\");\n\n  if (col_min >= size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(row,col): col is out of range\");\n\n  unsigned int row_max, col_max;\n  row_max = m.size(0) + row_min;\n  col_max = m.size(1) + col_min;\n\n  if (row_max > size(0))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(row,col,m): m.row + row is out of range.\");\n\n  if (col_max > size(1))\n    SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(row,col,m): m.col + col is out of range.\");\n\n  unsigned int numM = m.num();\n\n  if (numM == 0) // if m is a block matrix ...\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    BlocksMat::const_iterator1 it;\n    BlocksMat::const_iterator2 it2;\n    unsigned int posRow = row_min;\n    unsigned int posCol = col_min;\n\n    for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for (it2 = it.begin(); it2 != it.end(); ++it2)\n      {\n        subBlock(posRow, posCol, **it2);\n        posCol += (*it2)->size(1);\n      }\n      posRow += (*it)->size(0);\n      posCol = 0;\n    }\n  }\n  else if (numM == 6) // if m = 0\n  {\n    // nothing to do !\n  }\n  else // if m is a SimpleMatrix\n  {\n    if (_num == 1)\n    {\n      switch (numM)\n      {\n      case 1:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) -= *(m.dense());\n        break;\n      case 2:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) -= *(m.triang());\n        break;\n      case 3:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) -= *(m.sym());\n        break;\n      case 4:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) -= *(m.sparse());\n        break;\n      case 5:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) -= *(m.banded());\n        break;\n      case 7:\n        noalias(ublas::subrange(*mat.Dense, row_min, row_max, col_min, col_max)) -= *(m.identity());\n        break;\n      default:\n        SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(...,m): wrong matrix type for m.\");\n        break;\n      }\n    }\n    else\n      SiconosMatrixException::selfThrow(\"SimpleMatrix::subBlock(...): implemented only for dense matrices.\");\n    resetLU();\n  }\n}\n\n\n", "meta": {"hexsha": "1fbaa67d35001e5b57cade90361389ba1b959b41", "size": 6641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixArithmeticBlock.cpp", "max_stars_repo_name": "bremond/siconos", "max_stars_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixArithmeticBlock.cpp", "max_issues_repo_name": "bremond/siconos", "max_issues_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixArithmeticBlock.cpp", "max_forks_repo_name": "bremond/siconos", "max_forks_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8762376238, "max_line_length": 115, "alphanum_fraction": 0.6282186418, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.03622005794566348, "lm_q1q2_score": 0.017544274720237733}}
{"text": "#include <boost/numeric/bindings/ublas/matrix.hpp>\n\n#include \"SpaceFilter.hpp\"\n#include \"SpaceFilter_impl.hpp\"\n\n#include \"Circle.hpp\"\n#include \"Disk.hpp\"\n#include \"DiskDiskR.hpp\"\n#include \"CircleCircleR.hpp\"\n#include \"DiskPlanR.hpp\"\n#include \"DiskMovingPlanR.hpp\"\n#include \"SphereLDS.hpp\"\n#include \"SphereLDSSphereLDSR.hpp\"\n#include \"SphereNEDSSphereNEDSR.hpp\"\n#include \"SphereLDSPlanR.hpp\"\n#include \"SphereNEDS.hpp\"\n#include \"SphereNEDSPlanR.hpp\"\n#include \"ExternalBody.hpp\"\n\n#include <Model.hpp>\n#include <Simulation.hpp>\n#include <NonSmoothDynamicalSystem.hpp>\n#include <SimulationTypeDef.hpp>\n#include <NonSmoothLaw.hpp>\n\n\n#include <cmath>\n//#define DEBUG_MESSAGES 1\n#include \"debug.h\"\n\n\n\n\n\n/* hash is done with encapsulation */\n\n\n/* needed by boost hash */\nbool operator ==(SP::Hashed const& a, SP::Hashed const& b);\nbool operator ==(SP::Hashed const& a, SP::Hashed const& b)\n{\n  return (a->i == b->i &&\n          a->j == b->j &&\n          a->k == b->k);\n}\n\n\nstd::size_t hash_value(SP::Hashed const& h);\nstd::size_t hash_value(SP::Hashed const& h)\n{\n  std::size_t seed = 0;\n  boost::hash_combine(seed, h->i);\n  boost::hash_combine(seed, h->j);\n  boost::hash_combine(seed, h->k);\n  return seed;\n}\n\nSpaceFilter::SpaceFilter(unsigned int bboxfactor,\n              unsigned int cellsize,\n              SP::Model model,\n              SP::SiconosMatrix plans,\n              SP::FMatrix moving_plans) :\n    _bboxfactor(bboxfactor),\n    _cellsize(cellsize),\n    _interID(0),\n    _model(model),\n    _nslaws(new NSLawMatrix()),\n    _plans(plans),\n    _moving_plans(moving_plans),\n    _osnsinit(false),\n    _hash_table(new space_hash()),\n    diskdisk_relations(new DiskDiskRDeclaredPool()),\n    diskplan_relations(new DiskPlanRDeclaredPool()),\n  circlecircle_relations(new CircleCircleRDeclaredPool())\n{};\n\nSpaceFilter::SpaceFilter(unsigned int bboxfactor,\n              unsigned int cellsize,\n              SP::Model model,\n              SP::SiconosMatrix plans) :\n    _bboxfactor(bboxfactor),\n    _cellsize(cellsize),\n    _interID(0),\n    _model(model),\n    _nslaws(new NSLawMatrix()),\n    _plans(plans),\n    _osnsinit(false),\n    _hash_table(new space_hash()),\n    diskdisk_relations(new DiskDiskRDeclaredPool()),\n    diskplan_relations(new DiskPlanRDeclaredPool()),\n    circlecircle_relations(new CircleCircleRDeclaredPool())\n{};\n\nSpaceFilter::SpaceFilter(SP::Model model) :\n  _model(model),\n  _nslaws(new NSLawMatrix()),\n  _osnsinit(false),\n  _hash_table(new space_hash()),\n  diskdisk_relations(new DiskDiskRDeclaredPool()),\n  diskplan_relations(new DiskPlanRDeclaredPool()),\n  circlecircle_relations(new CircleCircleRDeclaredPool())\n{};\n\nSpaceFilter::SpaceFilter() :\n  _osnsinit(false),\n  _hash_table(new space_hash()),\n  diskdisk_relations(new DiskDiskRDeclaredPool()),\n  diskplan_relations(new DiskPlanRDeclaredPool()),\n  circlecircle_relations(new CircleCircleRDeclaredPool())\n{};\n\n\n/* the hashing is done with a visitor */\nstruct SpaceFilter::_BodyHash : public SiconosVisitor\n{\npublic:\n  SpaceFilter& parent;\n  _BodyHash(SpaceFilter& p) : parent(p) {};\n\n  using SiconosVisitor::visit;\n\n  void visit(SP::Disk pds)\n  {\n    int i, j, imin, imax, jmin, jmax;\n    unsigned int _bboxfactor = parent.bboxfactor();\n    unsigned int _cellsize = parent.cellsize();\n\n    imin = (int) floor((pds->getQ(0) - _bboxfactor * pds->getRadius()) / _cellsize);\n    imax = (int) floor((pds->getQ(0) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    jmin = (int) floor((pds->getQ(1) - _bboxfactor * pds->getRadius()) / _cellsize);\n    jmax = (int) floor((pds->getQ(1) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    for (i = imin; i <= imax; ++i)\n    {\n      for (j = jmin; j <= jmax; ++j)\n      {\n        parent.insert(pds, i, j, 0);\n      }\n    }\n  };\n\n  void visit(SP::Circle pds)\n  {\n    int i, j, imin, imax, jmin, jmax;\n\n    unsigned int _bboxfactor = parent.bboxfactor();\n    unsigned int _cellsize = parent.cellsize();\n\n    imin = (int) floor((pds->getQ(0) - _bboxfactor * pds->getRadius()) / _cellsize);\n    imax = (int) floor((pds->getQ(0) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    jmin = (int) floor((pds->getQ(1) - _bboxfactor * pds->getRadius()) / _cellsize);\n    jmax = (int) floor((pds->getQ(1) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    for (i = imin; i <= imax; ++i)\n    {\n      for (j = jmin; j <= jmax; ++j)\n      {\n        parent.insert(pds, i, j, 0);\n      }\n    }\n  }\n\n  void visit(SP::SphereLDS pds)\n  {\n    int i, j, k, imin, imax, jmin, jmax, kmin, kmax;\n\n    unsigned int _bboxfactor = parent.bboxfactor();\n    unsigned int _cellsize = parent.cellsize();\n\n    imin = (int) floor((pds->getQ(0) - _bboxfactor * pds->getRadius()) / _cellsize);\n    imax = (int) floor((pds->getQ(0) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    jmin = (int) floor((pds->getQ(1) - _bboxfactor * pds->getRadius()) / _cellsize);\n    jmax = (int) floor((pds->getQ(1) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    kmin = (int) floor((pds->getQ(2) - _bboxfactor * pds->getRadius()) / _cellsize);\n    kmax = (int) floor((pds->getQ(2) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    for (i = imin; i <= imax; ++i)\n    {\n      for (j = jmin; j <= jmax; ++j)\n      {\n        for (k = kmin; k <= kmax; ++k)\n        {\n          parent.insert(pds, i, j, k);\n        }\n      }\n    }\n\n  }\n\n  void visit(SP::SphereNEDS pds)\n  {\n    int i, j, k, imin, imax, jmin, jmax, kmin, kmax;\n\n    unsigned int _bboxfactor = parent.bboxfactor();\n    unsigned int _cellsize = parent.cellsize();\n\n    imin = (int) floor((pds->getQ(0) - _bboxfactor * pds->getRadius()) / _cellsize);\n    imax = (int) floor((pds->getQ(0) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    jmin = (int) floor((pds->getQ(1) - _bboxfactor * pds->getRadius()) / _cellsize);\n    jmax = (int) floor((pds->getQ(1) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    kmin = (int) floor((pds->getQ(2) - _bboxfactor * pds->getRadius()) / _cellsize);\n    kmax = (int) floor((pds->getQ(2) + _bboxfactor * pds->getRadius()) / _cellsize);\n\n    for (i = imin; i <= imax; ++i)\n    {\n      for (j = jmin; j <= jmax; ++j)\n      {\n        for (k = kmin; k <= kmax; ++k)\n        {\n          parent.insert(pds, i, j, k);\n        }\n      }\n    }\n\n  }\n\n  void visit(SP::ExternalBody d)\n  {\n    d->selfHash(parent);\n  }\n\n  /* ... visit other objects */\n\n};\n\n\n\n/* proximity detection for circular object */\nstruct SpaceFilter::_CircularFilter : public SiconosVisitor\n{\n  using SiconosVisitor::visit;\n\n  SP::SpaceFilter parent;\n  SP::CircularDS ds1;\n\n  _CircularFilter(SP::SpaceFilter parent, SP::CircularDS ds1) : parent(parent), ds1(ds1) {};\n\n  void visit_circular(SP::CircularDS ds2)\n  {\n\n    SP::CircularR rel;\n    SP::DynamicalSystemsGraph DSG0 = parent->model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n    assert(ds1 != ds2);\n    assert(DSG0->bundle(DSG0->descriptor(ds1)) == ds1);\n    assert(DSG0->bundle(DSG0->descriptor(ds2)) == ds2);\n\n    double r1 = ds1->getRadius();\n    double r2 = ds2->getRadius();\n    double tol = r1 + r2;\n\n    double x1 = ds1->getQ(0);\n    double y1 = ds1->getQ(1);\n    double x2 = ds2->getQ(0);\n    double y2 = ds2->getQ(1);\n    double rmax = fmax(r1, r2);\n    double rmin = fmin(r1, r2);\n\n    double d = hypot(x1 - x2, y1 - y2);\n\n    if (d < rmax)\n    {\n      // one inside the other : CircleCircle relation\n      if (rmax - (d + rmin) < tol)\n      {\n        CircleCircleRDeclaredPool::iterator rcandid =\n          parent->circlecircle_relations->find(CircleCircleRDeclared(r1, r2));\n        if (rcandid == parent->circlecircle_relations->end())\n        {\n          // a new relation\n          rel.reset(new CircleCircleR(r1, r2));\n          (*(parent->circlecircle_relations))[CircleCircleRDeclared(r1, r2)] = rel;\n        }\n        else\n        {\n          // get relation from pool\n          rel = (*rcandid).second;\n        }\n      }\n    }\n    else\n    {\n      // a DiskDisk relation\n      if (d - (r1 + r2) < tol)\n      {\n        DiskDiskRDeclaredPool::iterator rcandid =\n          parent->diskdisk_relations->find(DiskDiskRDeclared(r1, r2));\n        if (rcandid == parent->diskdisk_relations->end())\n        {\n          // a new relation\n          rel.reset(new DiskDiskR(r1, r2));\n\n          // FIX : this does not work!!\n          // parent->diskdisk_relations[DiskDiskRDeclared(r1,r2)] = rel;\n        }\n        else\n        {\n          // get relation from pool\n          rel = (*rcandid).second;\n        }\n      }\n    }\n\n    if (rel)\n    {\n      bool found = false;\n      DynamicalSystemsGraph::OEIterator oei, oeiend;\n      for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds1));\n           oei != oeiend; ++oei)\n      {\n        if (DSG0->bundle(DSG0->target(*oei)) == ds2)\n        {\n          found = true;\n          break;\n        }\n      }\n\n      if (!found)\n      {\n        SP::NonSmoothLaw nslaw = (*parent->_nslaws)(DSG0->groupId[DSG0->descriptor(ds1)],\n                                                    DSG0->groupId[DSG0->descriptor(ds2)]);\n\n        SP::Interaction inter(new Interaction(2,\n                                              nslaw,\n                                              rel, parent->_interID++));\n        parent->link(inter, ds1, ds2);\n      }\n    }\n    else\n    {\n      // is interaction in graph ?\n      bool found = false;\n      DynamicalSystemsGraph::OEIterator oei, oeiend;\n      for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds1));\n           oei != oeiend; ++oei)\n      {\n        if (DSG0->bundle(DSG0->target(*oei)) == ds2)\n        {\n          found = true;\n          break;\n        }\n      }\n\n      if (found)\n      {\n\n\n        DEBUG_PRINTF(\"remove interaction : %d\\n\", DSG0->bundle(*oei)->number());\n        parent->model()->nonSmoothDynamicalSystem()->topology()->\n        removeInteraction(DSG0->bundle(*oei));\n      }\n    }\n  }\n\n  void visit(SP::Disk disk)\n  {\n    visit_circular(disk);\n  }\n\n  void visit(SP::Circle circle)\n  {\n    visit_circular(circle);\n  }\n\n  // do nothing (everything must be done in ExternalBody.findInteractions)\n  void visit(SP::ExternalBody)\n  {}\n\n\n};\n\n/* proximity detection for sphere objects */\nstruct SpaceFilter::_SphereLDSFilter : public SiconosVisitor\n{\n  using SiconosVisitor::visit;\n\n  SP::SpaceFilter parent;\n  SP::SphereLDS ds1;\n\n  _SphereLDSFilter(SP::SpaceFilter p, SP::SphereLDS s) : parent(p), ds1(s) {};\n\n  void visit(SP::SphereLDS ds2)\n  {\n    SP::SphereLDSSphereLDSR rel;\n    SP::DynamicalSystemsGraph DSG0 = parent->model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n    assert(ds1 != ds2);\n    assert(DSG0->bundle(DSG0->descriptor(ds1)) == ds1);\n    assert(DSG0->bundle(DSG0->descriptor(ds2)) == ds2);\n\n    double r1 = ds1->getRadius();\n    double r2 = ds2->getRadius();\n    double tol = r1 + r2;\n\n    double x1 = ds1->getQ(0);\n    double y1 = ds1->getQ(1);\n    double z1 = ds1->getQ(2);\n    double x2 = ds2->getQ(0);\n    double y2 = ds2->getQ(1);\n    double z2 = ds2->getQ(2);\n\n    double dx = x1 - x2;\n    double dy = y1 - y2;\n    double dz = z1 - z2;\n\n    double d = sqrt(dx * dx + dy * dy + dz * dz);\n\n    if (d < 2 * tol)\n    {\n      rel.reset(new SphereLDSSphereLDSR(r1, r2));\n\n      bool found = false;\n      DynamicalSystemsGraph::OEIterator oei, oeiend;\n      for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds1));\n           oei != oeiend; ++oei)\n      {\n        if (DSG0->bundle(DSG0->target(*oei)) == ds2)\n        {\n          found = true;\n          break;\n        }\n      }\n\n      if (!found)\n      {\n        SP::NonSmoothLaw nslaw = (*parent->_nslaws)(DSG0->groupId[DSG0->descriptor(ds1)],\n                                                    DSG0->groupId[DSG0->descriptor(ds2)]);\n\n        SP::Interaction inter(new Interaction(3,\n                                              nslaw,\n                                              rel, parent->_interID++));\n\n        parent->link(inter, ds1, ds2);\n      }\n    }\n    else\n    {\n      // is interaction in graph ?\n      bool found = false;\n      DynamicalSystemsGraph::OEIterator oei, oeiend;\n      for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds1));\n           oei != oeiend; ++oei)\n      {\n        if (DSG0->bundle(DSG0->target(*oei)) == ds2)\n        {\n          found = true;\n          break;\n        }\n      }\n\n      if (found)\n      {\n        parent->model()->nonSmoothDynamicalSystem()->topology()->\n        removeInteraction(DSG0->bundle(*oei));\n      }\n\n    }\n  }\n};\n\n\nstruct SpaceFilter::_SphereNEDSFilter : public SiconosVisitor\n{\n  using SiconosVisitor::visit;\n\n  SP::SpaceFilter parent;\n  SP::SphereNEDS ds1;\n\n  _SphereNEDSFilter(SP::SpaceFilter p, SP::SphereNEDS s) : parent(p), ds1(s) {};\n\n  void visit(SP::SphereNEDS ds2)\n  {\n    SP::SphereNEDSSphereNEDSR rel;\n    SP::DynamicalSystemsGraph DSG0 = parent->model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n    assert(ds1 != ds2);\n    assert(DSG0->bundle(DSG0->descriptor(ds1)) == ds1);\n    assert(DSG0->bundle(DSG0->descriptor(ds2)) == ds2);\n\n    double r1 = ds1->getRadius();\n    double r2 = ds2->getRadius();\n    double tol = r1 + r2;\n\n    double x1 = ds1->getQ(0);\n    double y1 = ds1->getQ(1);\n    double z1 = ds1->getQ(2);\n    double x2 = ds2->getQ(0);\n    double y2 = ds2->getQ(1);\n    double z2 = ds2->getQ(2);\n\n    double dx = x1 - x2;\n    double dy = y1 - y2;\n    double dz = z1 - z2;\n\n    double d = sqrt(dx * dx + dy * dy + dz * dz);\n\n    if (d < 2 * tol)\n    {\n      rel.reset(new SphereNEDSSphereNEDSR(r1, r2));\n\n      bool found = false;\n      DynamicalSystemsGraph::OEIterator oei, oeiend;\n      for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds1));\n           oei != oeiend; ++oei)\n      {\n        if (DSG0->bundle(DSG0->target(*oei)) == ds2)\n        {\n          found = true;\n          break;\n        }\n      }\n\n      if (!found)\n      {\n        SP::NonSmoothLaw nslaw = (*parent->_nslaws)(DSG0->groupId[DSG0->descriptor(ds1)],\n                                                    DSG0->groupId[DSG0->descriptor(ds2)]);\n\n        SP::Interaction inter(new Interaction(3,\n                                              nslaw,\n                                              rel, parent->_interID++));\n\n        parent->link(inter, ds1, ds2);\n      }\n    }\n    else\n    {\n      // is interaction in graph ?\n      bool found = false;\n      DynamicalSystemsGraph::OEIterator oei, oeiend;\n      for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds1));\n           oei != oeiend; ++oei)\n      {\n        if (DSG0->bundle(DSG0->target(*oei)) == ds2)\n        {\n          found = true;\n          break;\n        }\n      }\n\n      if (found)\n      {\n        parent->model()->nonSmoothDynamicalSystem()->topology()->\n        removeInteraction(DSG0->bundle(*oei));\n      }\n\n    }\n  }\n};\n\n\n\n/* disk plan relation comparison */\nstruct SpaceFilter::_IsSameDiskPlanR : public SiconosVisitor\n{\n\n  using SiconosVisitor::visit;\n\n  SP::SpaceFilter parent;\n  double A, B, C, r, xCenter, yCenter, width;\n  bool flag;\n  _IsSameDiskPlanR(SP::SpaceFilter p, double A, double B, double C, double r,\n                   double xCenter, double yCenter, double width) :\n    parent(p), A(A), B(B), C(C), r(r), xCenter(xCenter), yCenter(yCenter), width(width), flag(false) {};\n\n\n  void visit(const DiskDiskR&)\n  {\n    flag = false;\n  };\n\n  void visit(const CircleCircleR&)\n  {\n    flag = false;\n  };\n\n  void visit(const DiskMovingPlanR&)\n  {\n    flag = false;\n  };\n\n  void visit(const LagrangianScleronomousR&)\n  {\n    flag = false;\n  };\n\n  void visit(const DiskPlanR& rel)\n  {\n    flag = rel.equal(A, B, C, r, xCenter, yCenter, width);\n  };\n\n};\n\nstruct SpaceFilter::_IsSameDiskMovingPlanR : public SiconosVisitor\n{\n\n  using SiconosVisitor::visit;\n\n  SP::SpaceFilter parent;\n  FTime AF, BF, CF;\n  double r;\n  bool flag;\n  _IsSameDiskMovingPlanR(SP::SpaceFilter p, FTime AF, FTime BF, FTime CF, double r) :\n    parent(p), AF(AF), BF(BF), CF(CF), r(r), flag(false) {};\n\n\n  void visit(const DiskDiskR&)\n  {\n    flag = false;\n  };\n\n  void visit(const CircleCircleR&)\n  {\n    flag = false;\n  };\n\n  void visit(const DiskPlanR&)\n  {\n    flag = false;\n  };\n\n  void visit(const LagrangianScleronomousR&)\n  {\n    flag = false;\n  }\n\n  void visit(const DiskMovingPlanR& rel)\n  {\n    flag = rel.equal(AF, BF, CF, r);\n  };\n\n};\n\n/* sphere plan relation comparison */\nstruct SpaceFilter::_IsSameSpherePlanR : public SiconosVisitor\n{\n\n  using SiconosVisitor::visit;\n\n  SP::SpaceFilter parent;\n  double A, B, C, D, r;\n  bool flag;\n  _IsSameSpherePlanR(SP::SpaceFilter p, double A, double B, double C, double D, double r):\n    parent(p), A(A), B(B), C(C), D(D), r(r), flag(false) {};\n\n  void visit(const SphereLDSSphereLDSR&)\n  {\n    flag = false;\n  };\n\n  void visit(const SphereNEDSSphereNEDSR&)\n  {\n    flag = false;\n  };\n\n  void visit(const SphereLDSPlanR& rel)\n  {\n    flag = rel.equal(A, B, C, D, r);\n  };\n\n  void visit(const SphereNEDSPlanR& rel)\n  {\n    flag = rel.equal(A, B, C, D, r);\n  };\n};\n\n\n/* proximity detection between circular object and plans */\nvoid SpaceFilter::_PlanCircularFilter(double A, double B, double C,\n                                      double xCenter, double yCenter,\n                                      double width, SP::CircularDS ds)\n{\n  double r = ds->getRadius();\n\n  /* tolerance */\n  double tol = r;\n\n  SP::DynamicalSystemsGraph DSG0 = model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n  _IsSameDiskPlanR\n  isSameDiskPlanR = _IsSameDiskPlanR(shared_from_this(), A, B, C, r,\n                                     xCenter, yCenter, width);\n\n\n  // all DS must be in DS graph\n  assert(DSG0->bundle(DSG0->descriptor(ds)) == ds);\n  SP::DiskPlanR relp(new DiskPlanR(r, A, B, C, xCenter, yCenter, width));\n\n  if (relp->distance(ds->getQ(0),\n                     ds->getQ(1),\n                     ds->getRadius()) < tol)\n\n  {\n    // is interaction in graph ?\n    bool found = false;\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(isSameDiskPlanR);\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && isSameDiskPlanR.flag)\n      {\n        found = true;\n        break;\n      }\n    }\n\n    if (!found)\n      // no\n    {\n      SP::NonSmoothLaw nslaw = (*_nslaws)(DSG0->groupId[DSG0->descriptor(ds)],\n                                          DSG0->groupId[DSG0->descriptor(ds)]);\n\n      SP::Interaction inter(new Interaction(2,\n                                            nslaw,\n                                            relp, _interID++));\n      DEBUG_PRINTF(\"insert interaction : %d\\n\", inter->number());\n      link(inter, ds);\n    }\n  }\n  else\n  {\n    // is interaction in graph ?\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(isSameDiskPlanR);\n\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && isSameDiskPlanR.flag)\n      {\n\n        DEBUG_PRINTF(\"remove interaction : %d\\n\", DSG0->bundle(*oei)->number());\n\n        model()->nonSmoothDynamicalSystem()->topology()->\n        removeInteraction(DSG0->bundle(*oei));\n        break;\n      }\n    }\n  }\n}\n\n\n\n/* proximity detection between circular object and plans */\nvoid SpaceFilter::_MovingPlanCircularFilter(unsigned int i, SP::CircularDS ds, double time)\n{\n  double r = ds->getRadius();\n\n  /* tolerance */\n  double tol = r;\n\n  SP::DynamicalSystemsGraph DSG0 = model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n  _IsSameDiskMovingPlanR\n  isSameDiskMovingPlanR = _IsSameDiskMovingPlanR(shared_from_this(),\n                          (*_moving_plans)(i, 0),\n                          (*_moving_plans)(i, 1),\n                          (*_moving_plans)(i, 2),\n                          r);\n\n  // all DS must be in DS graph\n  assert(DSG0->bundle(DSG0->descriptor(ds)) == ds);\n  SP::DiskMovingPlanR relp(new DiskMovingPlanR((*_moving_plans)(i, 0), (*_moving_plans)(i, 1), (*_moving_plans)(i, 2),\n                           (*_moving_plans)(i, 3), (*_moving_plans)(i, 4), (*_moving_plans)(i, 5), r));\n\n  relp->init(time);\n\n  if (relp->distance(ds->getQ(0),\n                     ds->getQ(1),\n                     ds->getRadius()) < tol)\n\n  {\n    // is interaction in graph ?\n    bool found = false;\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(isSameDiskMovingPlanR);\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && isSameDiskMovingPlanR.flag)\n      {\n        found = true;\n        break;\n      }\n    }\n    if (!found)\n      // no\n    {\n      SP::NonSmoothLaw nslaw = (*_nslaws)(DSG0->groupId[DSG0->descriptor(ds)],\n                                          DSG0->groupId[DSG0->descriptor(ds)]);\n\n      SP::Interaction inter(new Interaction(2,\n                                            nslaw,\n                                            relp, _interID++));\n      link(inter, ds);\n    }\n  }\n  else\n  {\n    // is interaction in graph ?\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(isSameDiskMovingPlanR);\n\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && isSameDiskMovingPlanR.flag)\n      {\n        model()->nonSmoothDynamicalSystem()->topology()->\n        removeInteraction(DSG0->bundle(*oei));\n        break;\n      }\n    }\n  }\n}\n\n/* proximity detection between circular object and plans */\nvoid SpaceFilter::_PlanSphereLDSFilter(double A, double B, double C, double D, SP::SphereLDS ds)\n{\n  double r = ds->getRadius();\n\n  /* tolerance */\n  double tol = r;\n\n  SP::DynamicalSystemsGraph DSG0 = model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n  _IsSameSpherePlanR\n  IsSameSpherePlanR =\n    _IsSameSpherePlanR(shared_from_this(), A, B, C, D, r);\n\n\n  // all DS must be in DS graph\n  assert(DSG0->bundle(DSG0->descriptor(ds)) == ds);\n  SP::SphereLDSPlanR relp(new SphereLDSPlanR(r, A, B, C, D));\n  if (relp->distance(ds->getQ(0),\n                     ds->getQ(1),\n                     ds->getQ(2),\n                     ds->getRadius()) < tol)\n\n  {\n    // is interaction in graph ?\n    bool found = false;\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(IsSameSpherePlanR);\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && IsSameSpherePlanR.flag)\n      {\n        found = true;\n        break;\n      }\n    }\n    if (!found)\n      // no\n    {\n      SP::NonSmoothLaw nslaw = (*_nslaws)(DSG0->groupId[DSG0->descriptor(ds)],\n                                                  DSG0->groupId[DSG0->descriptor(ds)]);\n\n      SP::Interaction inter(new Interaction(3,\n                                            nslaw,\n                                            relp, _interID++));\n      link(inter, ds);\n    }\n  }\n  else\n  {\n    // is interaction in graph ?\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(IsSameSpherePlanR);\n\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && IsSameSpherePlanR.flag)\n      {\n        model()->nonSmoothDynamicalSystem()->topology()->\n        removeInteraction(DSG0->bundle(*oei));\n        break;\n      }\n    }\n  }\n}\n\n\n// note : all PlanObject should be merged\nvoid SpaceFilter::_PlanSphereNEDSFilter(double A, double B, double C, double D, SP::SphereNEDS ds)\n{\n  double r = ds->getRadius();\n\n  /* tolerance */\n  double tol = r;\n\n  SP::DynamicalSystemsGraph DSG0 = model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n  _IsSameSpherePlanR\n  isSameSpherePlanR =\n    _IsSameSpherePlanR(shared_from_this(), A, B, C, D, r);\n\n\n  // all DS must be in DS graph\n  assert(DSG0->bundle(DSG0->descriptor(ds)) == ds);\n  SP::SphereNEDSPlanR relp(new SphereNEDSPlanR(r, A, B, C, D));\n  if (relp->distance(ds->getQ(0),\n                     ds->getQ(1),\n                     ds->getQ(2),\n                     ds->getRadius()) < tol)\n\n  {\n    // is interaction in graph ?\n    bool found = false;\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(isSameSpherePlanR);\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && isSameSpherePlanR.flag)\n      {\n        found = true;\n        break;\n      }\n    }\n    if (!found)\n      // no\n    {\n      SP::NonSmoothLaw nslaw = (*_nslaws)(DSG0->groupId[DSG0->descriptor(ds)],\n                                          DSG0->groupId[DSG0->descriptor(ds)]);\n\n      SP::Interaction inter(new Interaction(3,\n                                            nslaw,\n                                            relp, _interID++));\n      link(inter, ds);\n    }\n  }\n  else\n  {\n    // is interaction in graph ?\n    DynamicalSystemsGraph::OEIterator oei, oeiend;\n    for (std11::tie(oei, oeiend) = DSG0->out_edges(DSG0->descriptor(ds));\n         oei != oeiend; ++oei)\n    {\n      DSG0->bundle(*oei)\n      ->relation()->accept(isSameSpherePlanR);\n\n      if (DSG0->bundle(DSG0->target(*oei)) == ds\n          && isSameSpherePlanR.flag)\n      {\n        model()->nonSmoothDynamicalSystem()->topology()->\n        removeInteraction(DSG0->bundle(*oei));\n        break;\n      }\n    }\n  }\n}\n\n\n/* insertion */\nvoid SpaceFilter::insert(SP::Disk ds, int i, int j, int k)\n{\n\n  SP::Hashed hashed(new Hashed(std11::static_pointer_cast<DynamicalSystem>(ds), i, j));\n  _hash_table->insert(hashed);\n}\n\nvoid SpaceFilter::insert(SP::Circle ds, int i, int j, int k)\n{\n\n  SP::Hashed hashed(new Hashed(std11::static_pointer_cast<DynamicalSystem>(ds), i, j));\n  _hash_table->insert(hashed);\n}\n\nvoid SpaceFilter::insert(SP::SphereLDS ds, int i, int j, int k)\n{\n\n  SP::Hashed hashed(new Hashed(ds, i, j, k));\n  _hash_table->insert(hashed);\n}\n\nvoid SpaceFilter::insert(SP::SphereNEDS ds, int i, int j, int k)\n{\n\n  SP::Hashed hashed(new Hashed(ds, i, j, k));\n  _hash_table->insert(hashed);\n}\n\nvoid SpaceFilter::insert(SP::Hashed hashed)\n{\n  _hash_table->insert(hashed);\n}\n\n/* insert other objects */\n\n\n\n/* dynamical systems proximity detection */\ntypedef std::pair<int, int> interPair;\nbool operator ==(interPair const& a, interPair const& b);\nbool operator ==(interPair const& a, interPair const& b)\n{\n  return ((a.first == b.first) && (a.second == b.second));\n}\n\nbool operator ==(std::pair<double, double> const& a,\n                 std::pair<double, double> const& b);\nbool operator ==(std::pair<double, double> const& a,\n                 std::pair<double, double> const& b)\n{\n  return ((a.first == b.first) && (a.second == b.second));\n}\n\nbool operator ==(DiskPlanRDeclared const& a, DiskPlanRDeclared const& b);\nbool operator ==(DiskPlanRDeclared const& a, DiskPlanRDeclared const& b)\n{\n  return ((a[0] == b[0] &&\n           a[1] == b[1] &&\n           a[2] == b[2] &&\n           a[3] == b[3] &&\n           a[4] == b[4] &&\n           a[5] == b[5]));\n}\n\nstruct SpaceFilter::_FindInteractions : public SiconosVisitor\n{\n\n  using SiconosVisitor::visit;\n\n  typedef boost::unordered_multiset < interPair,\n          boost::hash<interPair> > interPairs;\n\n  SP::SpaceFilter parent;\n  double time;\n  _FindInteractions(SP::SpaceFilter p, double time) : parent(p), time(time) {};\n\n  void visit_circular(SP::CircularDS  ds1)\n  {\n    assert(parent->_plans->size(0) > 0);\n\n    // interactions with plans\n\n    if (parent->_plans)\n    {\n      for (unsigned int i = 0; i < parent->_plans->size(0); ++i)\n      {\n        parent->_PlanCircularFilter((*parent->_plans)(i, 0),\n                                    (*parent->_plans)(i, 1),\n                                    (*parent->_plans)(i, 2),\n                                    (*parent->_plans)(i, 3),\n                                    (*parent->_plans)(i, 4),\n                                    (*parent->_plans)(i, 5),\n                                    ds1);\n      }\n    }\n\n    if (parent->_moving_plans)\n    {\n      for (unsigned int i = 0; i < parent->_moving_plans->size1(); ++i)\n      {\n        parent->_MovingPlanCircularFilter(i, ds1, time);\n      }\n    }\n\n    SP::SiconosVector Q1 = ds1->q();\n\n    double x1 = Q1->getValue(0);\n    double y1 = Q1->getValue(1);\n    SP::Hashed hds1(new Hashed(std11::static_pointer_cast<DynamicalSystem>(ds1),\n                             (int) floor(x1 / parent->_cellsize),\n                               (int) floor(y1 / parent->_cellsize)));\n\n    // find all other systems that are in the same cells\n    std::pair<space_hash::iterator, space_hash::iterator>\n    neighbours = parent->_hash_table->equal_range(hds1);\n\n    unsigned int j;\n    interPairs declaredInteractions;\n    std11::shared_ptr<_CircularFilter>\n    circularFilter(new _CircularFilter(parent, ds1));\n\n    for (j = 0; neighbours.first != neighbours.second; ++neighbours.first, ++j)\n    {\n      SP::DynamicalSystem ds2 = (*neighbours.first)->body;\n      int ids1 = ds1->number();\n      int ids2 = ds2->number();\n      int imax = (std::max)(ids1, ids2);\n      int imin = (std::min)(ids1, ids2);\n      if (ids1 != ids2)\n      {\n        // is interaction already treated ?\n        interPair interpair;\n        interpair = std::pair<int, int>(imin, imax);\n\n        if (declaredInteractions.find(interpair)\n            == declaredInteractions.end())\n        {\n          // no, check proximity\n          declaredInteractions.insert(interpair);\n          ds2->acceptSP(circularFilter);\n        }\n\n      }\n    }\n  };\n\n  void visit(SP::Circle circle)\n  {\n    visit_circular(circle);\n  };\n\n\n  void visit(SP::Disk disk)\n  {\n    visit_circular(disk);\n  };\n\n  void visit(SP::SphereLDS ds1)\n  {\n    // interactions with plans\n    for (unsigned int i = 0; i < parent->_plans->size(0); ++i)\n    {\n      parent->_PlanSphereLDSFilter((*parent->_plans)(i, 0),\n                                   (*parent->_plans)(i, 1),\n                                   (*parent->_plans)(i, 2),\n                                   (*parent->_plans)(i, 3), ds1);\n    }\n\n    SP::SiconosVector Q1 = ds1->q();\n\n    double x1 = Q1->getValue(0);\n    double y1 = Q1->getValue(1);\n    double z1 = Q1->getValue(2);\n    SP::Hashed hds1(new Hashed(ds1, (int) floor(x1 / parent->_cellsize),\n                               (int) floor(y1 / parent->_cellsize),\n                               (int) floor(z1 / parent->_cellsize)));\n\n    // find all other systems that are in the same cells\n    std::pair<space_hash::iterator, space_hash::iterator>\n    neighbours = parent->_hash_table->equal_range(hds1);\n\n    unsigned int j;\n    interPairs declaredInteractions;\n\n    std11::shared_ptr<_SphereLDSFilter> sphereFilter(new _SphereLDSFilter(parent, ds1));\n\n    for (j = 0; neighbours.first != neighbours.second; ++neighbours.first, ++j)\n    {\n      SP::DynamicalSystem ds2 = (*neighbours.first)->body;\n      int ids1 = ds1->number();\n      int ids2 = ds2->number();\n      int imax = (std::max)(ids1, ids2);\n      int imin = (std::min)(ids1, ids2);\n      if (ids1 != ids2)\n      {\n        // is interaction already treated ?\n        interPair interpair;\n        interpair = std::pair<int, int>(imin, imax);\n\n        if (declaredInteractions.find(interpair)\n            == declaredInteractions.end())\n        {\n          // no, check proximity\n          declaredInteractions.insert(interpair);\n          ds2->acceptSP(sphereFilter);\n        }\n\n      }\n    }\n  }\n\n\n  void visit(SP::SphereNEDS ds1)\n  {\n    // interactions with plans\n    for (unsigned int i = 0; i < parent->_plans->size(0); ++i)\n    {\n      parent->_PlanSphereNEDSFilter((*parent->_plans)(i, 0),\n                                    (*parent->_plans)(i, 1),\n                                    (*parent->_plans)(i, 2),\n                                    (*parent->_plans)(i, 3), ds1);\n    }\n\n    SP::SiconosVector Q1 = ds1->q();\n\n    double x1 = Q1->getValue(0);\n    double y1 = Q1->getValue(1);\n    double z1 = Q1->getValue(2);\n    SP::Hashed hds1(new Hashed(ds1, (int) floor(x1 / parent->_cellsize),\n                               (int) floor(y1 / parent->_cellsize),\n                               (int) floor(z1 / parent->_cellsize)));\n\n    // find all other systems that are in the same cells\n    std::pair<space_hash::iterator, space_hash::iterator>\n    neighbours = parent->_hash_table->equal_range(hds1);\n\n    unsigned int j;\n    interPairs declaredInteractions;\n\n    std11::shared_ptr<_SphereNEDSFilter> sphereFilter(new _SphereNEDSFilter(parent, ds1));\n\n    for (j = 0; neighbours.first != neighbours.second; ++neighbours.first, ++j)\n    {\n      SP::DynamicalSystem ds2 = (*neighbours.first)->body;\n      int ids1 = ds1->number();\n      int ids2 = ds2->number();\n      int imax = (std::max)(ids1, ids2);\n      int imin = (std::min)(ids1, ids2);\n      if (ids1 != ids2)\n      {\n        // is interaction already treated ?\n        interPair interpair;\n        interpair = std::pair<int, int>(imin, imax);\n\n        if (declaredInteractions.find(interpair)\n            == declaredInteractions.end())\n        {\n          // no, check proximity\n          declaredInteractions.insert(interpair);\n          ds2->acceptSP(sphereFilter);\n        }\n\n      }\n    }\n  }\n\n  void visit(SP::ExternalBody d)\n  {\n    d->selfFindInteractions(parent);\n  }\n\n\n};\n\n\nvoid SpaceFilter::link(SP::Interaction inter, SP::DynamicalSystem ds1,\n                       SP::DynamicalSystem ds2)\n{\n  DEBUG_PRINTF(\"link interaction : %d\\n\", inter->number());\n  model()->nonSmoothDynamicalSystem()->link(inter, ds1, ds2);\n  model()->simulation()->computeLevelsForInputAndOutput(inter);\n  // Note FP : ds init should probably be done once and only once for\n  // all ds (like in simulation->initialize()) but where/when?\n  unsigned int levelMinForInput = inter->lowerLevelForInput();\n  unsigned int levelMaxForInput = inter->upperLevelForInput();\n  bool has2DS = inter->has2Bodies();\n  for (unsigned int k = levelMinForInput ; k < levelMaxForInput + 1; k++)\n  {\n    ds1->initializeNonSmoothInput(k);\n    if(has2DS)\n      ds2->initializeNonSmoothInput(k);\n  }\n\n  SP::InteractionsGraph indexSet0 = model()->nonSmoothDynamicalSystem()->topology()->indexSet0();\n  InteractionsGraph::VDescriptor ui = indexSet0->descriptor(inter);\n\n  inter->initialize(model()->simulation()->nextTime(), indexSet0->properties(ui));\n  //inter->initialize(model()->simulation()->nextTime(), ds1, ds2);\n}\n\n\n/* general proximity detection */\nvoid SpaceFilter::buildInteractions(double time)\n{\n  SP::DynamicalSystemsGraph\n  DSG0 = model()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n\n  std11::shared_ptr<_BodyHash>\n  hasher(new _BodyHash(*this));\n\n  std11::shared_ptr<_FindInteractions>\n  findInteractions(new _FindInteractions(shared_from_this(), time));\n\n  _hash_table->clear();\n\n  // 1: rehash DS\n  DynamicalSystemsGraph::VIterator vi, viend;\n  for (std11::tie(vi, viend) = DSG0->vertices();\n       vi != viend; ++vi)\n  {\n    // to avoid cast see dual dispatch, visitor pattern\n    DSG0->bundle(*vi)->acceptSP(hasher);\n  }\n\n  // 2: prox detection\n  for (std11::tie(vi, viend) = DSG0->vertices();\n       vi != viend; ++vi)\n  {\n    DSG0->bundle(*vi)->acceptSP(findInteractions);\n  }\n  model()->simulation()->initOSNS();\n}\n\n//std::pair<space_hash::iterator, space_hash::iterator> SpaceFilter::neighbours(SP::Hashed h)\n//{\n//  return _hash_table.equal_range(h);\n//}\n\nbool SpaceFilter::haveNeighbours(SP::Hashed h)\n{\n  std::pair<space_hash::iterator, space_hash::iterator> neighbours\n    = _hash_table->equal_range(h);\n  return (neighbours.first != neighbours.second);\n}\n\n\nstruct SpaceFilter::_DiskDistance : public SiconosVisitor\n{\n\n  using SiconosVisitor::visit;\n\n  double x;\n  double y;\n  double r;\n  double result;\n\n  _DiskDistance(double x, double y, double r)\n    : x(x), y(y), r(r)\n  {};\n\n  void visit(SP::Disk d)\n  {\n    double xd = d->q()->getValue(0);\n    double yd = d->q()->getValue(1);\n\n    result = (hypot(x - xd, y - yd) - (r + d->getRadius()));\n  }\n};\n\n\n\n\n/* only for disks at the moment */\ndouble SpaceFilter::minDistance(SP::Hashed h)\n{\n  std::pair<space_hash::iterator, space_hash::iterator> neighbours\n    = _hash_table->equal_range(h);\n\n  SP::SiconosVector q = std11::static_pointer_cast<LagrangianDS>(h->body)->q();\n\n  double dmin = INFINITY;\n\n  {\n    SP::Disk disk = std11::static_pointer_cast<Disk>(h->body);\n\n    std11::shared_ptr<_DiskDistance> distance(new _DiskDistance((*q)(0), (*q)(1), disk->getRadius()));\n\n    for (; neighbours.first != neighbours.second; ++neighbours.first)\n    {\n      (*neighbours.first)->body->acceptSP(distance);\n\n      dmin = (std::min)(dmin, distance->result);\n    }\n  }\n\n  return dmin;\n\n}\n\nvoid SpaceFilter::insert(SP::NonSmoothLaw nslaw,\n                         long unsigned int id1,\n                         long unsigned int id2)\n{\n  NSLawMatrix& nslaws = *_nslaws;\n\n  // ublas::matrix size type is not the same on 32 bits and 64 bits\n  unsigned int id = std::max((unsigned int) id1, (unsigned int) id2);\n  nslaws.resize (std::max((unsigned int) nslaws.size1(), (unsigned int) id+1));\n\n  nslaws(id1, id2) = nslaw;\n}\n", "meta": {"hexsha": "0497e243901d3ca807e34660954e7028eb01d151", "size": 37440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mechanics/src/contactDetection/basicBroadphase/SpaceFilter.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": "mechanics/src/contactDetection/basicBroadphase/SpaceFilter.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": "mechanics/src/contactDetection/basicBroadphase/SpaceFilter.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": 26.9546436285, "max_line_length": 118, "alphanum_fraction": 0.5757478632, "num_tokens": 10811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.036220056775276045, "lm_q1q2_score": 0.01754427415332537}}
{"text": "#include \"stdafx.h\"\n\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/Cholesky>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n\n#include <iostream>\n\ntemplate<int blockSize>\nclass SparseBlockSquareMatrix {\npublic :\n\ttypedef struct {\n\t\tfloat e[blockSize * blockSize];\n\t} block_t;\n\n\ttypedef struct {\n\t\tint col;\n\t\tint blk;\n\t} offset_t;\npublic :\n\tint gridSize;\n\n\t// buffers\n\tstd::vector<int>\t\t\t\trowScan;\t\t// row offset\n\tstd::vector<offset_t>\t\t\tblockInfos;\t\t// column index and block offset for row elements\n\tstd::vector<block_t>\t\t\tblocks;\t\t\t// blocks buffer\n\n\t// graph of sparse matrix for creating buffers\n\tstd::vector<std::vector<int>>\tcolLinks; \n\npublic :\n\tvoid free( void ) {\n\t\tgridSize = 0;\n\t\trowScan.clear();\n\t\tblockInfos.clear();\n\t\tcolLinks.clear();\n\t}\n\n\t// gridSize = mat.size / blockSize\n\tvoid create( int gridSize ) {\n\t\tfree();\n\n\t\tthis->gridSize = gridSize;\n\n\t\tcolLinks.resize( gridSize );\n\n\t\tfor ( int i = 0; i < gridSize; i++ ) {\n\t\t\tinsertLink( i, i );\n\t\t}\n\t}\n\t\n\tbool isIndexValid( int row, int col ) const {\n\t\treturn ( row >= 0 && row < gridSize && col >= 0 && col < gridSize );\n\t}\n\t\n\tint size( void ) const {\n\t\treturn gridSize * blockSize;\n\t}\n\n\tint calcBlockIndex( int row, int col ) const {\n\t\tassert( isIndexValid( row, col ) );\n\t\t\n\t\tint index = findLink( row, col );\n\t\tif ( index < 0 ) {\n\t\t\treturn -1;\n\t\t}\n\n\t\treturn blockInfos[rowScan[row] + index].blk;\n\t}\n\n\t// FIXME: linear search, improve\n\tint findLink( int row, int col ) const {\n\t\tassert( isIndexValid( row, col ) );\n\t\tconst std::vector<int> &links = colLinks[row];\n\t\tfor ( int i = 0; i < links.size(); i++ ) {\n\t\t\tif ( links[i] == col ) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tvoid insertLink( int row, int col ) {\n\t\tassert( isIndexValid( row, col ) );\n\t\tint index = findLink( row, col );\n\t\tif ( index < 0 ) {\n\t\t\tcolLinks[row].push_back( col );\n\t\t}\n\t}\n\n\t// only alloc buffer for upper triangle elements\n\tvoid alloc( void ) {\n\t\t// row scan buffer\n\t\trowScan.resize( gridSize + 1 ); // add additional one for total number\n\t\trowScan[0] = 0;\n\t\tfor ( int i = 1; i <= gridSize; i++ ) {\n\t\t\trowScan[i] = rowScan[i-1] + colLinks[i-1].size();\n\t\t}\n\n\t\t// block info buffer\n\t\tint blockInfosIndex = 0;\n\t\tint blockIndex = 0;\n\t\tblockInfos.resize( rowScan[gridSize] );\n\t\tfor ( int i = 0; i < colLinks.size(); i++ ) {\n\t\t\tconst std::vector<int> &links = colLinks[i];\n\t\t\tfor ( int j = 0; j < links.size(); j++ ) {\n\t\t\t\tint col = links[j];\n\n\t\t\t\toffset_t &index = blockInfos[blockInfosIndex];\n\t\n\t\t\t\tindex.col = col;\n\t\t\t\tif ( col < i ) {\n\t\t\t\t\tindex.blk = calcBlockIndex( col, i );\n\t\t\t\t} else {\n\t\t\t\t\tindex.blk = blockIndex;\n\t\t\t\t\t++blockIndex;\n\t\t\t\t}\n\n\t\t\t\t++blockInfosIndex;\n\t\t\t}\n\t\t}\n\n\t\t// block buffer\n\t\tblocks.resize( blockIndex );\n\t\tmemset( blocks.data(), 0, blocks.size() * sizeof( block_t ) );\n\n\t\tstd::cout << blocks.size() << std::endl;\n\t}\n\n\tEigen::VectorXf diagonal( void ) const {\n\t\tEigen::VectorXf diag = Eigen::VectorXf::Zero( size() );\n\n\t\tfor ( int i = 0; i < gridSize; i++ ) {\n\t\t\tconst block_t &block = blocks[calcBlockIndex( i, i )];\n\t\t\tfor ( int k = 0; k < blockSize; k++ ) {\n\t\t\t\tdiag[k + i * blockSize] = block.e[k + k * blockSize];\n\t\t\t}\n\t\t}\n\n\t\treturn diag;\n\t}\n\n\tstatic void mad_mat_mult_v( int size, const float *B, const float *v, float *r ) {\n\t\tfor ( int row = 0; row < blockSize; row++ ) {\n\t\t\tfloat sum = 0.0f;\n\t\t\tfor ( int col = 0; col < blockSize; col++ ) {\n\t\t\t\tsum += B[col + row * blockSize] * v[col];\n\t\t\t}\n\t\t\tr[row] += sum; // FIXME : +=\n\t\t}\n\t}\n\n\tstatic void mad_v_mult_mat( int size, const float *B, const float *v, float *r ) {\n\t\tfor ( int row = 0; row < blockSize; row++ ) {\n\t\t\tfloat sum = 0.0f;\n\t\t\tfor ( int col = 0; col < blockSize; col++ ) {\n\t\t\t\tsum += B[row + col * blockSize] * v[col];\n\t\t\t}\n\t\t\tr[row] += sum; // FIXME : +=\n\t\t}\n\t}\n\n\tEigen::VectorXf operator*( const Eigen::VectorXf &v ) const {\n\t\tEigen::VectorXf r = Eigen::VectorXf::Zero( size() );\n\n\t\tfor ( int row = 0; row < gridSize; row++ ) { // for each row\n\t\t\tint start = rowScan[row];\n\t\t\tint end = rowScan[row+1]; // column blocks\n\t\t\tfor ( int i = start; i < end; i++ ) {\n\t\t\t\toffset_t info = blockInfos[i];\n\t\t\t\tint col = info.col;\n\t\t\t\tint blk = info.blk;\n\t\t\t\t\n\t\t\t\tconst float *ptr_B = blocks[blk].e;\n\t\t\t\tconst float *ptr_v = &v[col * blockSize];\n\t\t\t\tfloat *ptr_r = &r[row * blockSize];\n\n\t\t\t\tif ( col >= row ) {\t\t\t\t\t\n\t\t\t\t\tmad_mat_mult_v( gridSize, ptr_B, ptr_v, ptr_r );\n\t\t\t\t} else {\n\t\t\t\t\tmad_v_mult_mat( gridSize, ptr_B, ptr_v, ptr_r );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tSparseBlockSquareMatrix<blockSize> &operator=( const Eigen::MatrixXf &m ) {\n\t\tassert( m.rows() == m.cols() );\n\t\tcreate( m.rows() / blockSize );\n\n\t\tfor ( int y = 0; y < gridSize; y++ ) {\n\t\tfor ( int x = 0; x < gridSize; x++ ) {\n\t\t\tinsertLink( y, x );\n\t\t}}\n\t\talloc();\n\n\t\tfor ( int y = 0; y < gridSize; y++ ) {\n\t\tfor ( int x = y; x < gridSize; x++ ) {\n\t\t\tblock_t &block = blocks[calcBlockIndex( y, x )];\n\n\t\t\tfor ( int ly = 0; ly < blockSize; ly++ ) {\n\t\t\tfor ( int lx = 0; lx < blockSize; lx++ ) {\n\t\t\t\tblock.e[lx + ly * blockSize] = m(ly + y * blockSize, lx + x * blockSize);\n\t\t\t}}\t\t\t\n\t\t}}\n\t\treturn *this;\n\t}\n};\n\nEigen::VectorXf PCG( const SparseBlockSquareMatrix<12> &A, const Eigen::VectorXf &b, int maxIters, float threshold = 1e-6 ) {\n\tEigen::VectorXf M = A.diagonal();\n\tfor ( int i = 0; i < M.rows(); i++ ) {\n\t\tif ( fabs( M[i] ) > threshold ) {\n\t\t\tM[i] = 1.0f / M[i];\n\t\t} else {\n\t\t\tM[i] = 1.0f;\n\t\t}\n\t}\n\n\tEigen::VectorXf x = Eigen::VectorXf::Zero(A.size());\n\tEigen::VectorXf p = Eigen::VectorXf::Zero(A.size());\n\tEigen::VectorXf r = b; // b - A * x\n\n\tfor ( int i = 0; i < maxIters; i++ ) {\n\t\tfloat rme = sqrt( r.dot( r ) / A.size() );\n\t\tprintf( \"PCG : %d : %f\\n\", i, rme );\n\t\tif ( rme < 1e-6 ) {\n\t\t\tbreak;\n\t\t}\n\t\tEigen::VectorXf Mr = M.array() * r.array();\n\t\tfloat r_rMr = 1.0f / r.dot( Mr );\n\t\tp += Mr * r_rMr;\n\n\t\tEigen::VectorXf Ap = A * p;\n\t\tfloat r_pAp = 1.0f / p.dot( Ap );\n\t\tx +=  p * r_pAp;\n\t\tr -= Ap * r_pAp;\n\t}\n\n\treturn x;\n}\n\nvoid TestPCG( void ) {\n\tint dim = 48;\n\n\t// A : positive definite matrix\n\tEigen::MatrixXf A = Eigen::MatrixXf::Random( dim, dim );\n\tA = A * A.transpose();\n\tA += Eigen::MatrixXf::Identity( dim, dim ) * dim;\n\n\t//std::cout << A << std::endl;\n\n\t// x\n\tEigen::VectorXf x = Eigen::VectorXf::Random( dim );\n\n\t// b\n\tEigen::VectorXf b = A * x;\n\n\t{\n\t\tEigen::VectorXf xx = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\t\tstd::cout << ( xx - x ).dot( xx - x ) / xx.rows() << std::endl << std::endl;\n\t}\n\n\t{\n\t\tSparseBlockSquareMatrix<12> B;\n\t\tB = A;\n\t\tEigen::VectorXf xx = PCG( B, b, 100 );\n\t\tstd::cout << ( xx - x ).dot( xx - x ) / xx.rows() << std::endl << std::endl;\n\t}\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tTestPCG();\n\t\n\treturn 0;\n}\n\n", "meta": {"hexsha": "d73f2b9c2b562b73a021fec6e405005d7362d95e", "size": 6620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moca/proj-pcg/pcg-cpu.cpp", "max_stars_repo_name": "Edwinzero/Fusion", "max_stars_repo_head_hexsha": "6b71ee807bc33c6d79546ce2dbca47229d663c1d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-21T04:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T06:50:34.000Z", "max_issues_repo_path": "moca/proj-pcg/pcg-cpu.cpp", "max_issues_repo_name": "icg-moca/MOCA", "max_issues_repo_head_hexsha": "61dbb536529bb1dfd6b1972ce3bdcdaf98655acd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moca/proj-pcg/pcg-cpu.cpp", "max_forks_repo_name": "icg-moca/MOCA", "max_forks_repo_head_hexsha": "61dbb536529bb1dfd6b1972ce3bdcdaf98655acd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1468531469, "max_line_length": 125, "alphanum_fraction": 0.5740181269, "num_tokens": 2232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438006939036565, "lm_q2_score": 0.03622005729544823, "lm_q1q2_score": 0.017544273866092232}}
{"text": "// This code is licensed under the MIT License (MIT). See LICENCE.txt for details\n#pragma once\n\n#include <algorithm>\n#include <cstdint>\n#include <exception>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <string>\n\n#include <boost/lexical_cast.hpp>\n\nnamespace collatzOpenCL\n{\n\nclass ValidateErr : public std::exception {\npublic:\n  ValidateErr(const std::string& val, unsigned int expectedStep, unsigned int calculatedStep)\n  {\n    std::stringstream ss(\"Value :\");\n    ss << val << \"\\nExpected Step: \" << expectedStep << \"\\nCalculated Step: \" << calculatedStep << '\\n';\n    errMsg_.assign(ss.str());\n  }\n  const char* what() const override { return errMsg_.c_str(); }\nprivate:\n  std::string errMsg_;\n};\n\ntemplate<typename MaxStepTy = uint32_t, typename MaxPosTy = uint64_t, typename TotalStepsTy = uint64_t>\nstruct Result {\n  MaxStepTy maxStep = 0;\n  MaxPosTy maxPos = 0;\n  TotalStepsTy totalSteps = 0;\n};\n\ntemplate<typename T, typename U, typename V>\ninline decltype(auto) operator << (std::ostream& os, const Result<T,U,V>& result)\n{\n  return os << result.maxStep << '\\n' << result.maxPos << '\\n' << result.totalSteps;\n}\ntemplate<typename T, typename U, typename V>\ninline decltype(auto) operator >> (std::istream& is, Result<T,U,V>& result)\n{\n  return is >> result.maxStep >> result.maxPos >> result.totalSteps;\n}\n\ntemplate<typename T, typename U, typename V, typename ValGen, typename CollatzFunc> \ninline auto compare_and_validate(const Result<T,U,V>& oldRes, const Result<T,U,V>& newRes, ValGen&& get_val, CollatzFunc&& collatz_step)\n{\n  //Only validate the results when new champion arrives\n  if (newRes.maxStep > oldRes.maxStep) {\n    auto val = get_val(newRes); //synthesize the value from the results\n    auto expectedStep = collatz_step(val);\n    if (newRes.maxStep != expectedStep) {\n      throw ValidateErr{ boost::lexical_cast<std::string>(val), expectedStep, newRes.maxStep };\n    }\n    return Result<T, U, V>{ newRes.maxStep, newRes.maxPos, newRes.totalSteps + oldRes.totalSteps };\n  } else {\n    return Result<T, U, V>{ oldRes.maxStep, oldRes.maxPos, newRes.totalSteps + oldRes.totalSteps };\n  }\n}\n\ntemplate <typename MaxStepVec, typename MaxPosVec, typename TotalStepsVec> inline\nauto gather_results(MaxStepVec&& maxStep, MaxPosVec&& maxPos, TotalStepsVec&& totalSteps)\n{\n  using std::cbegin; using std::cend; using std::next;\n  auto pos = std::distance(cbegin(maxStep), std::max_element(cbegin(maxStep), cend(maxStep)));\n  return Result<decltype(maxStep[0]), decltype(maxPos[0]), decltype(totalSteps[0])> {\n    *next(cbegin(maxStep), pos),\n    *next(cbegin(maxPos), pos),\n    std::accumulate(cbegin(totalSteps), cend(totalSteps), 0)\n  };\n}\n\n}", "meta": {"hexsha": "e034e879d74d8e5b1715b85c6036d32ee79d0f47", "size": 2679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "collatzResult.hpp", "max_stars_repo_name": "sosiristseng/collatz-cpp", "max_stars_repo_head_hexsha": "b7ef43ae2ce244da78eedc5ee405c9bfd221d3fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "collatzResult.hpp", "max_issues_repo_name": "sosiristseng/collatz-cpp", "max_issues_repo_head_hexsha": "b7ef43ae2ce244da78eedc5ee405c9bfd221d3fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "collatzResult.hpp", "max_forks_repo_name": "sosiristseng/collatz-cpp", "max_forks_repo_head_hexsha": "b7ef43ae2ce244da78eedc5ee405c9bfd221d3fa", "max_forks_repo_licenses": ["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.25, "max_line_length": 136, "alphanum_fraction": 0.712206047, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.044680874406965415, "lm_q1q2_score": 0.01752995263392349}}
{"text": "/**\n * \\file sim.cpp\n *\n * \\brief Source code for the (Guazzone,2014) paper.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * References:\n * - (Guazzone,2014)\n *   Marco Guazzone, Cosimo Anglano and Matteo Sereno.\n *   A Game-Theoretic Approach to Coalition Formation in Green Cloud Federations\n *   Proc. of the 14th IEEE/ACM International Symposium on Cluster, Cloud and Grid Computing (CCGrid), pp. 618-625, 2014.\n *   doi:[10.1109/CCGrid.2014.37](http://dx.doi.org/10.1109/CCGrid.2014.37).\n * .\n *\n * <hr/>\n *\n * Copyright 2013 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#include <algorithm>\n#include <boost/algorithm/string.hpp>\n#include <boost/random.hpp>\n#include <cstddef>\n#include <cctype>\n#include <dcs/algorithm/combinatorics.hpp>\n#include <dcs/assert.hpp>\n#include <dcs/cli.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/exception.hpp>\n#include <dcs/macro.hpp>\n#include <dcs/math/traits/float.hpp>\n#include <fstream>\n#include <gtpack/cooperative.hpp>\n#if DCS_CLOUD_GT_HAVE_CPLEX_SOLVER\n# include <ilconcert/iloalg.h>\n# include <ilconcert/iloenv.h>\n# include <ilconcert/iloexpression.h>\n# include <ilconcert/ilomodel.h>\n# include <ilcplex/ilocplex.h>\n#elif DCS_CLOUD_GT_HAVE_GUROBI_SOLVER\n# include <gurobi_c++.h>\n#endif // DCS_CLOUD_GT_HAVE_*_SOLVER\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <set>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\n\nnamespace alg = dcs::algorithm;\nnamespace cli = dcs::cli;\nnamespace math = dcs::math;\n\n\nnamespace detail { namespace experiment { namespace /*<unnamed>*/ {\n\nenum coalition_formation_category\n{\n\tmerge_split_stable_coalition_formation,\n\tnash_stable_coalition_formation,\n\tpareto_optimal_coalition_formation,\n\tsocial_optimum_coalition_formation\n};\n\nenum coalition_value_division_category\n{\n\tbanzhaf_coalition_value_division,\n\tnormalized_banzhaf_coalition_value_division,\n\tshapley_coalition_value_division\n};\n\ntemplate <typename RealT>\nstruct options\n{\n\toptions()\n\t: opt_relative_gap(0),\n\t  opt_time_lim(-1),\n\t  coalition_formation(nash_stable_coalition_formation),\n\t  coalition_value_division(shapley_coalition_value_division),\n\t  rnd_gen_vms(false),\n\t  rnd_gen_pm_power_states(false),\n\t  rnd_gen_pm_on_off_costs(false),\n\t  rnd_gen_vm_migration_costs(false),\n\t  rnd_seed(5489),\n\t  rnd_num_iters(1),\n\t  csv_fname()\n\t{\n\t}\n\n\tRealT opt_relative_gap; ///< The relative gap option to set to the optimal solver\n\tRealT opt_time_lim; ///< The time limit (in sec) to set for each execution of the optimal solver\n\tcoalition_formation_category coalition_formation;\n\tcoalition_value_division_category coalition_value_division;\n\tbool rnd_gen_vms; ///< Tells if the number of VMs per CIP should be generated at random; if \\c true, the number of VMs is randomly generated according to a integer uniform distribution in [0, scenario.cip_num_vms[cip]]\n\tbool rnd_gen_pm_power_states; ///< Tells if the power state of PMs per CIP should be generated at random; if \\c true, the power state of PMs is randomly generated according to a Bernoulli distribution with parameter p=0.5\n\tbool rnd_gen_pm_on_off_costs; ///< Tells if the switch-on/off cost of PMs per CIP and PM type should be generated at random; if \\c true, the switch-on/off cost of PMs is randomly generated according to a Normal distribution with parameter mu=3e-4sec and sigma=5e-5sec\n\tbool rnd_gen_vm_migration_costs; ///< Tells if the CIP-to-CIP migration cost of VM per CIP and VM types should be generated at random; if \\c true, the CIP-to-CIP migration cost of VMs is randomly generated according to a Normal distribution with parameter mu=277sec and sigma=182sec, for the the smaller VM and double for increasing VM size.\n\tunsigned long rnd_seed; ///< The seed used for random generation\n\tstd::size_t rnd_num_iters; ///< Number of iterations (used only if rnd_vms is true)\n\tstd::string csv_fname; ///< Name of CSV file where to export coalitions enumeration.\n};\n\ntemplate <typename RealT>\nstruct scenario\n{\n\tstd::size_t num_cips; ///< Number of different CIPs \n\tstd::size_t num_pm_types; ///< Number of different PM types\n\tstd::size_t num_vm_types; ///< Number of different VM types\n\tstd::vector< std::vector<std::size_t> > cip_num_pms; ///< Number of PMs per CIP and PM type\n\tstd::vector< std::vector<std::size_t> > cip_num_vms; ///< Number of VMs per CIP and VM type\n\tstd::vector< std::vector<bool> > cip_pm_power_states; ///< Power states of PMs per CIP and PM\n\tstd::vector< std::vector<RealT> > cip_revenues; ///< Revenues per CIP and VM type ($/hour/VM)\n\tstd::vector<RealT> cip_electricity_costs; ///< Energy cost per CIP (in $/kWh)\n\tstd::vector< std::vector<RealT> > cip_pm_asleep_costs; ///< Costs to switch-off PMs, per CIP and PM type ($/hour)\n\tstd::vector< std::vector<RealT> > cip_pm_awake_costs; ///< Costs to switch-on PMs, per CIP and PM type ($/hour)\n\tstd::vector< std::vector< std::vector<RealT> > > cip_to_cip_vm_migration_costs; ///< Costs to migrate VMs from a CIP to another CIP, per CIP and VM type ($/hour)\n\tstd::vector<RealT> cip_coalition_costs; ///< Cost due to form a coalition structure, per CIP\n\tstd::vector<RealT> pm_spec_min_powers; ///< Min power consumption per PM (in W)\n\tstd::vector<RealT> pm_spec_max_powers; ///< Max power consumption per PM (in W)\n\tstd::vector< std::vector<RealT> > vm_spec_cpus; ///< CPU share requirements per VM type and per PM type\n\tstd::vector< std::vector<RealT> > vm_spec_rams; ///< RAM share requirements per VM type and per PM type\n};\n\ntemplate <typename RealT>\nstruct optimal_allocation_info\n{\n\toptimal_allocation_info()\n\t: solved(false),\n\t  optimal(false),\n\t  objective_value(std::numeric_limits<RealT>::infinity()),\n\t  cost(std::numeric_limits<RealT>::infinity()),\n\t  kwatt(std::numeric_limits<RealT>::infinity())\n\t{\n\t}\n\n\n\tbool solved;\n\tbool optimal;\n\tRealT objective_value;\n\tRealT cost;\n\tRealT kwatt;\n\tstd::vector<bool> pm_power_states;\n\tstd::vector< std::vector<bool> > pm_vm_allocations;\n};\n\ntemplate <typename RealT>\nstruct cip_allocation_info\n{\n\tstd::size_t num_on_pms; // Number of powered on PMs\n\tstd::size_t num_vms; // Number of hosted VMs\n\tRealT tot_watt; // Total consumed watt (in Watt)\n\t//RealT tot_wcost; // Cost rate due to total consumed watt (in kWh)\n};\n\ntemplate <typename RealT>\nstruct coalition_info\n{\n\tcoalition_info()\n\t: optimal_allocation(),\n\t  value(::std::numeric_limits<RealT>::quiet_NaN()),\n\t  core_empty(true),\n\t  payoffs(),\n\t  payoffs_in_core(false),\n\t  cid(gtpack::empty_coalition_id)\n\t{\n\t}\n\n\n\toptimal_allocation_info<RealT> optimal_allocation;\n\tRealT value;\n\tbool core_empty;\n\tstd::map<gtpack::player_type, RealT> payoffs;\n\tbool payoffs_in_core;\n\tgtpack::cid_type cid;\n};\n\ntemplate <typename RealT>\nstruct partition_info\n{\n\tRealT value;\n\tstd::set<gtpack::cid_type> coalitions;\n\tstd::map<gtpack::player_type, RealT> payoffs;\n\tstd::map<gtpack::player_type, RealT> side_payments;\n};\n\ntemplate <typename RealT>\nstruct coalition_formation_info\n{\n\tstd::map< gtpack::cid_type, coalition_info<RealT> > coalitions;\n\tstd::vector< partition_info<RealT> > best_partitions;\n};\n\n\ntemplate <typename RealT>\nscenario<RealT> make_scenario(std::string const& fname)\n{\n\tDCS_ASSERT(!fname.empty(),\n\t\t\t   DCS_EXCEPTION_THROW(std::invalid_argument, \"Invalid scenario file name\"));\n\n\tscenario<RealT> s;\n\n\tstd::ifstream ifs(fname.c_str());\n\n\tDCS_ASSERT(ifs,\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Cannot open scenario file\"));\n\n\tfor (std::string line; std::getline(ifs, line); )\n\t{\n\t\tstd::size_t pos(0);\n\t\tfor (; pos < line.length() && std::isspace(line[pos]); ++pos)\n\t\t{\n\t\t\t; // empty\n\t\t}\n\t\tif (pos > 0)\n\t\t{\n\t\t\tline = line.substr(pos);\n\t\t}\n\t\tif (line.empty() || line.at(0) == '#')\n\t\t{\n\t\t\t// Skip either empty or comment lines\n\t\t\tcontinue;\n\t\t}\n\n\t\tboost::to_lower(line);\n\t\tif (boost::starts_with(line, \"num_cips\"))\n\t\t{\n\t\t\tstd::istringstream iss(line);\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\tiss >> s.num_cips;\n\t\t}\n\t\telse if (boost::starts_with(line, \"num_pm_types\"))\n\t\t{\n\t\t\tstd::istringstream iss(line);\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\tiss >> s.num_pm_types;\n\t\t}\n\t\telse if (boost::starts_with(line, \"num_vm_types\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\tiss >> s.num_vm_types;\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_revenues\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n//\t\t\ts.cip_revenues.resize(s.num_cips);\n//\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n//\t\t\t{\n//\t\t\t\ts.cip_revenues[c].resize(s.num_vm_types);\n//\t\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n//\t\t\t\t{\n//\t\t\t\t\tiss >> s.cip_revenues[c][v];\n//\t\t\t\t}\n//\t\t\t}\n\t\t\ts.cip_revenues.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.cip_revenues[c].resize(s.num_vm_types);\n\t\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t\t{\n\t\t\t\t\tiss >> s.cip_revenues[c][v];\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"pm_spec_min_powers\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.pm_spec_min_powers.resize(s.num_pm_types);\n\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t{\n\t\t\t\tiss >> s.pm_spec_min_powers[p];\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"pm_spec_max_powers\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.pm_spec_max_powers.resize(s.num_pm_types);\n\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t{\n\t\t\t\tiss >> s.pm_spec_max_powers[p];\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_num_pms\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.cip_num_pms.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.cip_num_pms[c].resize(s.num_pm_types);\n\t\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tiss >> s.cip_num_pms[c][p];\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_num_vms\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.cip_num_vms.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.cip_num_vms[c].resize(s.num_vm_types);\n\t\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t\t{\n\t\t\t\t\tiss >> s.cip_num_vms[c][v];\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_pm_power_states\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.cip_pm_power_states.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\tstd::size_t num_pms = 0;\n\t\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tnum_pms += s.cip_num_pms[c][p];\n\t\t\t\t}\n\t\t\t\ts.cip_pm_power_states[c].resize(num_pms);\n\t\t\t\tfor (std::size_t p = 0; p < num_pms; ++p)\n\t\t\t\t{\n\t\t\t\t\tbool ison = false;\n\t\t\t\t\tiss >> ison;\n\t\t\t\t\ts.cip_pm_power_states[c][p] = ison;\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_wcosts\") || boost::starts_with(line, \"cip_electricity_costs\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.cip_electricity_costs.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\tiss >> s.cip_electricity_costs[c];\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_pm_asleep_costs\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.cip_pm_asleep_costs.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.cip_pm_asleep_costs[c].resize(s.num_pm_types);\n\t\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tiss >> s.cip_pm_asleep_costs[c][p];\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_pm_awake_costs\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.cip_pm_awake_costs.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.cip_pm_awake_costs[c].resize(s.num_pm_types);\n\t\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tiss >> s.cip_pm_awake_costs[c][p];\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_coalition_costs\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing at line \" + ::detail::util::to_string(lineno) + \")\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing at line \" + ::detail::util::to_string(lineno) + \")\"));\n\n\t\t\ts.cip_coalition_costs.resize(s.num_cips);\n\t\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t\t{\n\t\t\t\tiss >> s.cip_coalition_costs[c];\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"vm_spec_cpus\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.vm_spec_cpus.resize(s.num_vm_types);\n\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.vm_spec_cpus[v].resize(s.num_pm_types);\n\t\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tiss >> s.vm_spec_cpus[v][p];\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"vm_spec_rams\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.vm_spec_rams.resize(s.num_vm_types);\n\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.vm_spec_rams[v].resize(s.num_pm_types);\n\t\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tiss >> s.vm_spec_rams[v][p];\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t\telse if (boost::starts_with(line, \"cip_to_cip_vm_migration_costs\"))\n\t\t{\n\t\t\tstd::istringstream iss(line.substr(pos));\n\n\t\t\t// Move to '='\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '=');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('=' is missing)\"));\n\n\t\t\t// Move to '['\n\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\ts.cip_to_cip_vm_migration_costs.resize(s.num_cips);\n\t\t\tfor (std::size_t c1 = 0; c1 < s.num_cips; ++c1)\n\t\t\t{\n\t\t\t\t// Move to '['\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\ts.cip_to_cip_vm_migration_costs[c1].resize(s.num_cips);\n\t\t\t\tfor (std::size_t c2 = 0; c2 < s.num_cips; ++c2)\n\t\t\t\t{\n\t\t\t\t\t// Move to '['\n\t\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), '[');\n\t\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file ('[' is missing)\"));\n\n\t\t\t\t\ts.cip_to_cip_vm_migration_costs[c1][c2].resize(s.num_vm_types);\n\t\t\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t\t\t{\n\t\t\t\t\t\tiss >> s.cip_to_cip_vm_migration_costs[c1][c2][v];\n\t\t\t\t\t}\n\n\t\t\t\t\t// Move to ']'\n\t\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t\t}\n\n\t\t\t\t// Move to ']'\n\t\t\t\tiss.ignore(std::numeric_limits<std::streamsize>::max(), ']');\n\t\t\t\tDCS_ASSERT(iss.good(),\n\t\t\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Malformed scenario file (']' is missing)\"));\n\t\t\t}\n\t\t}\n\t}\n\n\t// check: mandatory info\n\tDCS_ASSERT(s.num_cips > 0,\n\t\t\t   DCS_EXCEPTION_THROW(std::logic_error, \"Number of CIP must be a positive number\"));\n\tDCS_ASSERT(s.num_pm_types > 0,\n\t\t\t   DCS_EXCEPTION_THROW(std::logic_error, \"Number of PM types must be a positive number\"));\n\tDCS_ASSERT(s.num_vm_types > 0,\n\t\t\t   DCS_EXCEPTION_THROW(std::logic_error, \"Number of VM types must be a positive number\"));\n\n\t// Consistency checks\n\tDCS_ASSERT(s.cip_revenues.size() == 0 || s.num_cips == s.cip_revenues.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP revenues\"));\n\tDCS_ASSERT(s.cip_num_pms.size() == 0 || s.num_cips == s.cip_num_pms.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP PMs\"));\n\tDCS_ASSERT(s.cip_num_vms.size() == 0 || s.num_cips == s.cip_num_vms.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP VMs\"));\n\tDCS_ASSERT(s.cip_electricity_costs.size() == 0 || s.num_cips == s.cip_electricity_costs.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP electricity costs\"));\n\tDCS_ASSERT(s.cip_pm_power_states.size() == 0 || s.num_cips == s.cip_pm_power_states.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP PM power states\"));\n\tDCS_ASSERT(s.cip_pm_asleep_costs.size() == 0 || s.num_cips == s.cip_pm_asleep_costs.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP PM switch-off costs\"));\n\tDCS_ASSERT(s.cip_pm_awake_costs.size() == 0 || s.num_cips == s.cip_pm_awake_costs.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP PM switch-on costs\"));\n\tDCS_ASSERT(s.pm_spec_min_powers.size() == 0 || s.num_pm_types == s.pm_spec_min_powers.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of PM minimum power consumption specifications\"));\n\tDCS_ASSERT(s.pm_spec_max_powers.size() == 0 || s.num_pm_types == s.pm_spec_max_powers.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of PM maximum power consumption specifications\"));\n\tDCS_ASSERT(s.vm_spec_cpus.size() == 0 || s.num_vm_types == s.vm_spec_cpus.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of VM CPU share requirements\"));\n\tDCS_ASSERT(s.vm_spec_rams.size() == 0 || s.num_vm_types == s.vm_spec_rams.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of VM RAM share requirements\"));\n\tDCS_ASSERT(s.cip_to_cip_vm_migration_costs.size() == 0 || s.num_cips == s.cip_to_cip_vm_migration_costs.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP-to-CIP VM migration costs\"));\n\tDCS_ASSERT(s.cip_coalition_costs.size() == 0 || s.num_cips ==  s.cip_coalition_costs.size(),\n\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of providers in coalition costs by provider\"));\n//\tif (s.num_cips > 0)\n//\t{\n//\t\tDCS_ASSERT(s.cip_revenues[0].size() == 0 || s.num_vm_types == s.cip_revenues[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of VM types in CIP revenues\"));\n//\t\tDCS_ASSERT(s.cip_num_pms[0].size() == 0 || s.num_pm_types == s.cip_num_pms[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of PM types in CIP number of PMs\"));\n//\t\tDCS_ASSERT(s.cip_num_vms[0].size() == 0 || s.num_vm_types == s.cip_num_vms[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of VM types in CIP number of VMs\"));\n//\t\tDCS_ASSERT(s.cip_pm_asleep_costs[0].size() == 0 || s.num_pm_types == s.cip_pm_asleep_costs[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of PM types in CIP switch-off costs of PMs\"));\n//\t\tDCS_ASSERT(s.cip_pm_awake_costs[0].size() == 0 || s.num_pm_types == s.cip_pm_awake_costs[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of PM types in CIP switch-on costs of PMs\"));\n//\t\tDCS_ASSERT(s.cip_to_cip_vm_migration_costs[0].size() == 0 || s.num_cips == s.cip_to_cip_vm_migration_costs[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of CIP types in CIP-to-CIP VM migration costs\"));\n//\t\tDCS_ASSERT(s.cip_to_cip_vm_migration_costs[0][0].size() == 0 || s.num_vm_types == s.cip_to_cip_vm_migration_costs[0][0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of VM types in CIP-to-CIP VM migration costs\"));\n//\t}\n//\tif (s.num_vm_types > 0)\n//\t{\n//\t\tDCS_ASSERT(s.vm_spec_cpus[0].size() == 0 || s.num_pm_types == s.vm_spec_cpus[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of PM types in VM CPU share requirements\"));\n//\t\tDCS_ASSERT(s.vm_spec_rams[0].size() == 0 || s.num_pm_types == s.vm_spec_rams[0].size(),\n//\t\t\t\t   DCS_EXCEPTION_THROW(std::runtime_error, \"Unexpected number of PM types in VM RAM share requirements\"));\n//\t}\n\n\t//TODO: assign default values for the other info\n\tif (s.cip_pm_power_states.size() == 0)\n\t{\n\t\t// Default: all PMs are off\n\n\t\ts.cip_pm_power_states.resize(s.num_cips);\n\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t{\n\t\t\tstd::size_t num_pms = 0;\n\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t{\n\t\t\t\tnum_pms += s.cip_num_pms[c][p];\n\t\t\t}\n\t\t\ts.cip_pm_power_states[c].assign(num_pms, false);\n\t\t}\n\t}\n\tif (s.cip_pm_asleep_costs.size() == 0)\n\t{\n\t\t// Default: all PM switch-off costs are 0\n\n\t\ts.cip_pm_asleep_costs.resize(s.num_cips);\n\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t{\n\t\t\ts.cip_pm_asleep_costs[c].assign(s.num_pm_types, 0);\n\t\t}\n\t}\n\tif (s.cip_pm_awake_costs.size() == 0)\n\t{\n\t\t// Default: all PM switch-on costs are 0\n\n\t\ts.cip_pm_awake_costs.resize(s.num_cips);\n\t\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t\t{\n\t\t\ts.cip_pm_awake_costs[c].assign(s.num_pm_types, 0);\n\t\t}\n\t}\n\tif (s.cip_to_cip_vm_migration_costs.size() == 0)\n\t{\n\t\t// Default: all CIP-to-CIP VM migration costs are 0\n\n\t\ts.cip_to_cip_vm_migration_costs.resize(s.num_cips);\n\t\tfor (std::size_t c1 = 0; c1 < s.num_cips; ++c1)\n\t\t{\n\t\t\ts.cip_to_cip_vm_migration_costs[c1].resize(s.num_cips);\n\t\t\tfor (std::size_t c2 = 0; c2 < s.num_cips; ++c2)\n\t\t\t{\n\t\t\t\ts.cip_to_cip_vm_migration_costs[c1][c2].assign(s.num_vm_types, 0);\n\t\t\t}\n\t\t}\n\t}\n\tif (s.cip_coalition_costs.size() == 0)\n\t{\n\t\ts.cip_coalition_costs.resize(s.num_cips);\n\t\tstd::fill(s.cip_coalition_costs.begin(), s.cip_coalition_costs.end(), 0);\n\t}\n\n\treturn s;\n}\n\ntemplate <typename CharT, typename CharTraitsT, typename RealT>\nstd::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, scenario<RealT> const& s)\n{\n\tos  << \"num_cips=\" << s.num_cips\n\t\t<< \", \" << \"num_pm_types=\" << s.num_pm_types\n\t\t<< \", \" << \"num_vm_types=\" << s.num_vm_types;\n\n\tos << \", \" << \"cip_revenues=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \" \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t{\n\t\t\tif (v > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.cip_revenues[c][v];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"pm_spec_min_powers=[\";\n\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t{\n\t\tif (p > 0)\n\t\t{\n\t\t\tos << \", \";\n\t\t}\n\t\tos << s.pm_spec_min_powers[p];\n\t}\n\tos << \"]\";\n\tos << \", \" << \"pm_spec_max_powers=[\";\n\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t{\n\t\tif (p > 0)\n\t\t{\n\t\t\tos << \", \";\n\t\t}\n\t\tos << s.pm_spec_max_powers[p];\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_num_pms=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \" \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t{\n\t\t\tif (p > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.cip_num_pms[c][p];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_pm_power_states=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \" \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t p = 0; p < s.cip_pm_power_states[c].size(); ++p)\n\t\t{\n\t\t\tif (p > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.cip_pm_power_states[c][p];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_num_vms=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \" \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t{\n\t\t\tif (v > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.cip_num_vms[c][v];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_electricity_costs=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \", \";\n\t\t}\n\t\tos << s.cip_electricity_costs[c];\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_pm_asleep_costs=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \"  \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t{\n\t\t\tif (p > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.cip_pm_asleep_costs[c][p];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_pm_awake_costs=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \"  \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t{\n\t\t\tif (p > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.cip_pm_awake_costs[c][p];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_to_cip_vm_migration_costs=[\";\n\tfor (std::size_t c1 = 0; c1 < s.num_cips; ++c1)\n\t{\n\t\tif (c1 > 0)\n\t\t{\n\t\t\tos << \"  \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t c2 = 0; c2 < s.num_cips; ++c2)\n\t\t{\n\t\t\tif (c2 > 0)\n\t\t\t{\n\t\t\t\tos << \"  \";\n\t\t\t}\n\n\t\t\tos << \"[\";\n\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t{\n\t\t\t\tif (v > 0)\n\t\t\t\t{\n\t\t\t\t\tos << \", \";\n\t\t\t\t}\n\t\t\t\tos << s.cip_to_cip_vm_migration_costs[c1][c2][v];\n\t\t\t}\n\t\t\tos << \"]\";\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"cip_coalition_costs=[\";\n\tfor (std::size_t c = 0; c < s.num_cips; ++c)\n\t{\n\t\tif (c > 0)\n\t\t{\n\t\t\tos << \", \";\n\t\t}\n\t\tos << s.cip_coalition_costs[c];\n\t}\n\tos << \"]\";\n\tos << \", \" << \"vm_spec_cpus=[\";\n\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t{\n\t\tif (v > 0)\n\t\t{\n\t\t\tos << \" \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t{\n\t\t\tif (p > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.vm_spec_cpus[v][p];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\tos << \", \" << \"vm_spec_rams=[\";\n\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t{\n\t\tif (v > 0)\n\t\t{\n\t\t\tos << \" \";\n\t\t}\n\n\t\tos << \"[\";\n\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t{\n\t\t\tif (p > 0)\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << s.vm_spec_rams[v][p];\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\n\treturn os;\n}\n\ntemplate <typename CharT, typename CharTraitsT, typename RealT>\nstd::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, options<RealT> const& opt)\n{\n\tos\t<< \"relative-gap: \" << opt.opt_relative_gap\n\t\t<< \", time_limit: \" << opt.opt_time_lim\n\t\t<< \", coalition_formation: \" << opt.coalition_formation\n\t\t<< \", coalition_value_division: \" << opt.coalition_value_division\n\t\t<< \", csv_file_name: \" << opt.csv_fname\n\t\t<< \", random_gen_vms: \" << std::boolalpha << opt.rnd_gen_vms\n\t\t<< \", random_gen_pm_power_states: \" << std::boolalpha << opt.rnd_gen_pm_power_states\n\t\t<< \", random_gen_pm_on_off_costs: \" << std::boolalpha << opt.rnd_gen_pm_on_off_costs\n\t\t<< \", random_gen_vm_migration_costs: \" << std::boolalpha << opt.rnd_gen_vm_migration_costs\n\t\t<< \", random_seed: \" << opt.rnd_seed\n\t\t<< \", random_num_iters: \" << opt.rnd_num_iters;\n\n\n\treturn os;\n}\n\ntemplate <typename CharT, typename CharTraitsT, typename T>\nstd::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, std::vector<T> const& v)\n{\n\ttypedef typename std::vector<T>::const_iterator iterator;\n\n\titerator end_it(v.end());\n\tos << \"[\";\n\tfor (iterator it = v.begin(); it != end_it; ++it)\n\t{\n\t\tif (it != v.begin())\n\t\t{\n\t\t\tos << \", \";\n\t\t}\n\t\tos << *it;\n\t}\n\tos << \"]\";\n\n\treturn os;\n}\n\ntemplate <typename CharT, typename CharTraitsT, typename T>\nstd::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, std::vector< std::vector<T> > const& v)\n{\n\ttypedef typename std::vector< std::vector<T> >::const_iterator outer_iterator;\n\ttypedef typename std::vector<T>::const_iterator inner_iterator;\n\n\touter_iterator out_end_it(v.end());\n\tos << \"[\";\n\tfor (outer_iterator out_it = v.begin(); out_it != out_end_it; ++out_it)\n\t{\n\t\tif (out_it != v.begin())\n\t\t{\n\t\t\tos << \" \";\n\t\t}\n\t\tos << \"[\";\n\t\tinner_iterator in_end_it(out_it->end());\n\t\tfor (inner_iterator in_it = out_it->begin(); in_it != in_end_it; ++in_it)\n\t\t{\n\t\t\tif (in_it != out_it->begin())\n\t\t\t{\n\t\t\t\tos << \", \";\n\t\t\t}\n\t\t\tos << *in_it;\n\t\t}\n\t\tos << \"]\";\n\t}\n\tos << \"]\";\n\n\treturn os;\n}\n\ntemplate <typename RealT>\ninline\nRealT pm_consumed_power(RealT min_power, RealT max_power, RealT u)\n{\n\treturn min_power + (max_power-min_power)*u;\n}\n\ntemplate <typename CipsWCostVectorT,\n\t\t  typename PmsCipVectorT,\n\t\t  typename PmsCategoryVectorT,\n\t\t  typename PmSpecsMinPowerVectorT,\n\t\t  typename PmSpecsMaxPowerVectorT,\n\t\t  typename VmsCipVectorT,\n\t\t  typename VmsCategoryVectorT,\n\t\t  typename VmSpecsCpuVectorT,\n\t\t  typename VmSpecsRamVectorT,\n\t\t  typename PmPowerStatesVectorT,\n\t\t  typename CipPmAsleepCostsVectorT,\n\t\t  typename CipPmAwakeCostsVectorT,\n\t\t  typename CipToCipVmMigrationCostsCubeT,\n\t\t  typename RealT>\noptimal_allocation_info<RealT> find_optimal_allocation(std::size_t ncips,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   CipsWCostVectorT cips_electricity_cost,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::size_t npms,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   PmsCipVectorT const& pms_cip,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   PmsCategoryVectorT const& pms_category,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   PmSpecsMinPowerVectorT const& pm_specs_min_power,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   PmSpecsMaxPowerVectorT const& pm_specs_max_power,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   std::size_t nvms,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   VmsCipVectorT const& vms_cip,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   VmsCategoryVectorT const& vms_category,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   VmSpecsCpuVectorT const& vm_specs_cpu,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   VmSpecsRamVectorT const& vm_specs_ram,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   PmPowerStatesVectorT const& pm_power_states,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   CipPmAsleepCostsVectorT const& cip_pm_asleep_costs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   CipPmAwakeCostsVectorT const& cip_pm_awake_costs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   CipToCipVmMigrationCostsCubeT const& cip_to_cip_vm_migration_costs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   bool min_power,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   RealT relative_gap = 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   RealT time_lim = -1)\n{\n\tDCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( ncips );\n\n\toptimal_allocation_info<RealT> solution;\n\n\tDCS_DEBUG_TRACE(\"Finding optimal allocation:\");\n\tDCS_DEBUG_TRACE(\"- Number of CIPs: \" << ncips);\n\tDCS_DEBUG_TRACE(\"- Energy Costs per CIP: \" << cips_electricity_cost);\n\tDCS_DEBUG_TRACE(\"- Number of PMs: \" << npms);\n\tDCS_DEBUG_TRACE(\"- CIP per PM: \" << pms_cip);\n\tDCS_DEBUG_TRACE(\"- Category per PM: \" << pms_category);\n\tDCS_DEBUG_TRACE(\"- Mininimum Power Consumption per PM: \" << pm_specs_min_power);\n\tDCS_DEBUG_TRACE(\"- Maximum Power Consumption per PM: \" << pm_specs_max_power);\n\tDCS_DEBUG_TRACE(\"- Number of VMs: \" << nvms);\n\tDCS_DEBUG_TRACE(\"- Category per VM: \" << vms_category);\n\tDCS_DEBUG_TRACE(\"- CPU requirement per VM: \" << vm_specs_cpu);\n\tDCS_DEBUG_TRACE(\"- RAM requirement per VM: \" << vm_specs_ram);\n\tDCS_DEBUG_TRACE(\"- PM Power States: \" << pm_power_states);\n\tDCS_DEBUG_TRACE(\"- PM On->Off Cost per CIP and PM Category: \" << cip_pm_asleep_costs);\n\tDCS_DEBUG_TRACE(\"- PM Off->On Cost per CIP and PM Category: \" << cip_pm_awake_costs);\n\tDCS_DEBUG_TRACE(\"- VM Migration Cost from CIP to CIP per VM Category: \" << cip_to_cip_vm_migration_costs);\n\tDCS_DEBUG_TRACE(\"- Minimum Power: \" << std::boolalpha << min_power);\n\tDCS_DEBUG_TRACE(\"- Relative Gap: \" << relative_gap);\n\n\n#ifdef DCS_CLOUD_GT_HAVE_CPLEX_SOLVER\n\ttypedef IloNumVarArray var_vector_type;\n\ttypedef IloArray<IloNumVarArray> var_matrix_type;\n\n\t//Setting up vars\n\ttry\n\t{\n\t\t// Initialize the Concert Technology app\n\t\tIloEnv env;\n\n\t\tIloModel model(env);\n\n\t\tif (min_power)\n\t\t{\n\t\t\tmodel.setName(\"Min-Power Optimal Allocation (CPLEX)\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmodel.setName(\"Min-Cost Optimal Allocation (CPLEX)\");\n\t\t}\n\n\t\t// Decision Variables\n\n\t\t// Variables y_{vh}: y_{vh}==1 iif VM v is on host h\n\t\tvar_matrix_type y(env, nvms);\n\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t{\n\t\t\ty[v] = var_vector_type(env, npms);\n\n\t\t\tfor (std::size_t h = 0 ; h < npms ; ++h)\n\t\t\t{\n\t\t\t\tstd::ostringstream oss;\n\t\t\t\toss << \"y[\" << v << \"][\" << h << \"]\";\n\t\t\t\ty[v][h] = IloBoolVar(env, 0, 1, oss.str().c_str());\n\t\t\t\tmodel.add(y[v][h]);\n\t\t\t}\n\t\t}\n\n\t\t// Variables x_h\n\t\tvar_vector_type x(env, npms);\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"x[\" << h << \"]\";\n\t\t\tx[h] = IloBoolVar(env, 0, 1, oss.str().c_str());\n\t\t\tmodel.add(x[h]);\n\t\t}\n\n\t\t// Variables s_{h}\n\t\tvar_vector_type s(env, npms);\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"s[\" << h << \"]\";\n\t\t\ts[h] = IloNumVar(env, 0, 1, ILOFLOAT, oss.str().c_str());\n\t\t\tmodel.add(s[h]);\n\t\t}\n\n\t\t// Constraints\n\n\t\tstd::size_t cc(0); // Constraint counter\n\n\t\t// C1: \\forall v \\in V: \\sum_{h \\in H} y_{vh} = 1\n\t\t++cc;\n\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << v << \"}\";\n\n\t\t\tIloConstraint cons(IloSum(y[v]) == 1);\n\t\t\tcons.setName(oss.str().c_str());\n\t\t\tmodel.add(cons);\n\t\t}\n\n\t\t// C2: \\forall h \\in H: \\sum_{v \\in V} y_{vh} \\le |V|*x_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tIloExpr lhs(env);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tlhs += y[v][h];\n\t\t\t}\n\n\t\t\tIloConstraint cons(lhs <= x[h]*IloInt(nvms));\n\t\t\tcons.setName(oss.str().c_str());\n\t\t\tmodel.add(cons);\n\t\t}\n\n\t\t// C3: \\forall h \\in H: \\sum_{v \\in V} y_{vh}M_{q(v),g(h)} \\le x_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tIloExpr lhs(env);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tRealT req(vm_specs_ram[vms_category[v]][pms_category[h]]);\n\t\t\t\tlhs += y[v][h]*req;\n\t\t\t}\n\n\t\t\tIloConstraint cons(lhs <= x[h]);\n\t\t\tcons.setName(oss.str().c_str());\n\t\t\tmodel.add(cons);\n\t\t}\n\n\t\t// C4: \\forall h \\in H: \\sum_{v \\in V} y_{vh}S_{q(v),g(h)} == s_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tIloExpr lhs(env);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tRealT req(vm_specs_cpu[vms_category[v]][pms_category[h]]);\n\t\t\t\tlhs += y[v][h]*req;\n\t\t\t}\n\n\t\t\tIloConstraint cons(lhs == s[h]);\n\t\t\tcons.setName(oss.str().c_str());\n\t\t\tmodel.add(cons);\n\t\t}\n\n\t\t// C5: \\forall h \\in H: s_{h} \\le x_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tIloConstraint cons(s[h] <= x[h]);\n\t\t\tcons.setName(oss.str().c_str());\n\t\t\tmodel.add(cons);\n\t\t}\n\n\t\t// Set objective\n\t\tIloObjective z;\n\t\tif (min_power)\n\t\t{\n\t\t\t//FIXME: this does not work well when PM switch-on/off costs and VM migration costs are != zero!\n\t\t\tstd::cerr << \"(W) Power optimization does not work well when PM switch-on/off costs and VM migration costs are not zero!\" << std::endl;\n\n\t\t\t// z = \\min sum_{h \\in H}{x_h C_{g(h)}^{min} + (C_{g(h)}^{max}-C_{g(h)}^{min})s_{h} + x_h(1-o(i)) + (1-x_h)o(i)}\n\t\t\tIloExpr expr(env);\n\t\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t\t{\n\t\t\t\tRealT dC = pm_specs_max_power[pms_category[h]]-pm_specs_min_power[pms_category[h]];\n\n\t\t\t\texpr += x[h]*pm_specs_min_power[pms_category[h]] + dC*s[h];\n\t\t\t}\n\t\t\tz = IloMinimize(env, expr);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIloExpr expr(env);\n\t\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t\t{\n\t\t\t\tRealT dC = pm_specs_max_power[pms_category[h]]-pm_specs_min_power[pms_category[h]];\n\t\t\t\tRealT wcost = cips_electricity_cost[pms_cip[h]]*1e-3; // Electricity cost in Wh\n\n\t\t\t\texpr += (x[h]*pm_specs_min_power[pms_category[h]]+dC*s[h])*wcost;\n\t\t\t\t// Add PM switch-on/off costs\n\t\t\t\texpr += x[h]*(1-pm_power_states[h])*cip_pm_awake_costs[pms_cip[h]][pms_category[h]]\n\t\t\t\t\t +  (1-x[h])*pm_power_states[h]*cip_pm_asleep_costs[pms_cip[h]][pms_category[h]];\n\t\t\t\t// Add VM migration costs\n\t\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t\t{\n\t\t\t\t\texpr += y[v][h]*cip_to_cip_vm_migration_costs[vms_cip[v]][pms_cip[h]][vms_category[v]];\n\t\t\t\t}\n\t\t\t}\n\t\t\tz = IloMinimize(env, expr);\n\t\t}\n\t\tmodel.add(z);\n\n\t\t// Create the CPLEX solver and make 'model' the active (\"extracted\") model\n\t\tIloCplex solver(model);\n\n\t\t//write model\n#ifndef DCS_DEBUG\n\t\tsolver.setOut(env.getNullStream());\n\t\tsolver.setWarning(env.getNullStream());\n//#else // DCS_DEBUG\n//\t\tsolver.exportModel(\"cplex-model.lp\");\n#endif // DCS_DEBUG\n\n\t\t// Set Relative Gap to (relative_gap*100)%: CPLEX will stop as soon as it has found a feasible integer solution proved to be within (relative_gap*100)% of optimal.\n\t\tif (math::float_traits<RealT>::definitely_greater(relative_gap, 0))\n\t\t{\n\t\t\tsolver.setParam(IloCplex::EpGap, relative_gap);\n\t\t}\n\t\tif (math::float_traits<RealT>::definitely_greater(time_lim, 0))\n\t\t{\n\t\t\tsolver.setParam(IloCplex::TiLim, time_lim);\n\t\t}\n\n\t\tsolution.solved = solver.solve();\n\t\tsolution.optimal = false;\n\n\t\tIloAlgorithm::Status status = solver.getStatus();\n\n\t\tswitch (status)\n\t\t{\n\t\t\tcase IloAlgorithm::Optimal: // The algorithm found an optimal solution.\n\t\t\t\tsolution.objective_value = static_cast<RealT>(solver.getObjValue());\n\t\t\t\tsolution.optimal = true;\n\t\t\t\tbreak;\n\t\t\tcase IloAlgorithm::Feasible: // The algorithm found a feasible solution, though it may not necessarily be optimal.\n\n\t\t\t\tsolution.objective_value = static_cast<RealT>(solver.getObjValue());\n\t\t\t\tstd::cerr << \"(W) Optimization problem solved but non-optimal!\" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase IloAlgorithm::Infeasible: // The algorithm proved the model infeasible (i.e., it is not possible to find an assignment of values to variables satisfying all the constraints in the model).\n\t\t\tcase IloAlgorithm::Unbounded: // The algorithm proved the model unbounded.\n\t\t\tcase IloAlgorithm::InfeasibleOrUnbounded: // The model is infeasible or unbounded.\n\t\t\tcase IloAlgorithm::Error: // An error occurred and, on platforms that support exceptions, that an exception has been thrown.\n\t\t\tcase IloAlgorithm::Unknown: // The algorithm has no information about the solution of the model.\n\t\t\t{\n\t\t\t\t::std::ostringstream oss;\n\t\t\t\tstd::cerr << \"Optimization was stopped with status = \" << status << \" (CPLEX status = \" << solver.getCplexStatus() << \", sub-status = \" << solver.getCplexSubStatus() << \")\" << std::endl;\n\t\t\t\treturn solution;\n\t\t\t}\n\t\t}\n\n#ifdef DCS_DEBUG\n\t\tDCS_DEBUG_TRACE( \"Optimal solution: \" );\n\n\t\tDCS_DEBUG_TRACE( \"- Solved: \" << std::boolalpha << solution.solved );\n\t\tDCS_DEBUG_TRACE( \"- Optimal: \" << std::boolalpha << solution.optimal );\n\n\t\tDCS_DEBUG_TRACE( \"- Decision variables: \" );\n\n\t\t// Output x_{h}\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tDCS_DEBUG_STREAM << x[h].getName() << \" = \" << solver.getValue(x[h]) << \" (\" << static_cast<bool>(IloRound(solver.getValue(x[h]))) << \")\" << ::std::endl;\n\t\t}\n\n\t\t// Output y_{vh}\n\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t{\n\t\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_STREAM << y[v][h].getName() << \" = \" << solver.getValue(y[v][h]) << \" (\" << static_cast<bool>(IloRound(solver.getValue(y[v][h]))) << \")\" << ::std::endl;\n\t\t\t}\n\t\t}\n\n\t\t// Output s_{h}\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tDCS_DEBUG_STREAM << s[h].getName() << \" = \" << solver.getValue(s[h]) << ::std::endl;\n\t\t}\n\n\t\t//Print z\n\t\tDCS_DEBUG_TRACE( \"- Objective value: \" << solution.objective_value );\n#endif // DCS_DEBUG\n\n\t\tsolution.pm_power_states.resize(npms);\n\t\tsolution.pm_vm_allocations.resize(npms);\n\t\tif (min_power)\n\t\t{\n\t\t\t// Computed in the loop below\n\t\t\tsolution.cost = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsolution.cost = solution.objective_value;\n\t\t}\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tsolution.pm_power_states[h] = static_cast<bool>(IloRound(solver.getValue(x[h])));\n\n\t\t\t// Compute the energy cost\n\t\t\tif (min_power && static_cast<bool>(IloRound(solver.getValue(x[h]))))\n\t\t\t{\n\t\t\t\t//RealT dC = pm_specs_max_power[pms_category[h]]-pm_specs_min_power[pms_category[h]];\n\t\t\t\tRealT wcost = cips_electricity_cost[pms_cip[h]]*1e-3; // Electricity cost in Wh\n\n\t\t\t\t//solution.cost += (pm_specs_min_power[pms_category[h]] + dC*static_cast<RealT>(solver.getValue(s[h])))*wcost;\n\t\t\t\tsolution.cost += pm_consumed_power(pm_specs_min_power[pms_category[h]], pm_specs_max_power[pms_category[h]], static_cast<RealT>(solver.getValue(s[h])))*wcost;\n\t\t\t}\n\t\t\tsolution.pm_vm_allocations[h].resize(nvms);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tsolution.pm_vm_allocations[h][v] = static_cast<bool>(IloRound(solver.getValue(y[v][h])));\n\t\t\t}\n\t\t}\n\n\t\tx.end();\n\t\ty.end();\n\t\ts.end();\n\n\t\t// Close the Concert Technology app\n\t\tenv.end();\n\t}\n\tcatch (IloException const& e)\n\t{\n\t\t::std::ostringstream oss;\n\t\toss << \"Got exception from CPLEX: \" << e.getMessage();\n\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t}\n\tcatch (...)\n\t{\n\t\tDCS_EXCEPTION_THROW(::std::runtime_error,\n\t\t\t\t\t\t\t\"Unexpected error during the optimization\");\n\t}\n#elif defined(DCS_CLOUD_GT_HAVE_GUROBI_SOLVER)\n\ttypedef std::vector<GRBVar> var_vector_type;\n\ttypedef std::vector< std::vector<GRBVar> > var_matrix_type;\n\n\n\t//Setting up vars\n\ttry\n\t{\n\t\t// Initialize the Gurobi environment\n\t\tGRBEnv env;\n\n#ifdef DCS_DEBUG\n\t\tenv.set(GRB_IntParam_OutputFlag, 1);\n\t\tenv.set(GRB_IntParam_LogToConsole, 1);\n#else\n\t\tenv.set(GRB_IntParam_OutputFlag, 0);\n\t\tenv.set(GRB_IntParam_LogToConsole, 0);\n#endif // DCS_DEBUG\n\n\t\t// Set Relative Gap to (relative_gap*100)%: CPLEX will stop as soon as it has found a feasible integer solution proved to be within (relative_gap*100)% of optimal.\n\t\tif (math::float_traits<RealT>::definitely_greater(relative_gap, 0))\n\t\t{\n\t\t\tenv.set(GRB_DoubleParam_MIPGap, relative_gap);\n\t\t}\n\t\tif (math::float_traits<RealT>::definitely_greater(time_lim, 0))\n\t\t{\n\t\t\tenv.set(GRB_DoubleParam_TimeLimit, time_lim);\n\t\t}\n\n\t\tGRBModel model(env);\n\n\t\tif (min_power)\n\t\t{\n\t\t\tmodel.set(GRB_StringAttr_ModelName, \"Min-Power Optimal Allocation (GUROBI)\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmodel.set(GRB_StringAttr_ModelName, \"Min-Cost Optimal Allocation (GUROBI)\");\n\t\t}\n\n\t\t// Decision Variables\n\n\t\t// Variables y_{vh}: y_{vh}==1 iif VM v is on host h\n\t\tvar_matrix_type y(nvms, var_vector_type(npms));\n\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t{\n\t\t\tfor (std::size_t h = 0 ; h < npms ; ++h)\n\t\t\t{\n\t\t\t\tstd::ostringstream oss;\n\t\t\t\toss << \"y[\" << v << \"][\" << h << \"]\";\n\t\t\t\ty[v][h] = model.addVar(0, 1, 0, GRB_BINARY, oss.str());\n\t\t\t}\n\t\t}\n\n\t\t// Variables x_h\n\t\tvar_vector_type x(npms);\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"x[\" << h << \"]\";\n\t\t\tx[h] = model.addVar(0, 1, 0, GRB_BINARY, oss.str());\n\t\t}\n\n\t\t// Variables s_{h}\n\t\tvar_vector_type s(npms);\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"s[\" << h << \"]\";\n\t\t\ts[h] = model.addVar(0, 1, 0, GRB_CONTINUOUS, oss.str());\n\t\t}\n\n\t\t// Integrates new variables\n\t\tmodel.update();\n\n\t\t// Constraints\n\n\t\tstd::size_t cc(0); // Constraint counter\n\n\t\t// C1: \\forall v \\in V: \\sum_{h \\in H} y_{vh} = 1\n\t\t++cc;\n\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << v << \"}\";\n\n\t\t\tGRBLinExpr lhs(0);\n\t\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t\t{\n\t\t\t\tlhs += y[v][h];\n\t\t\t}\n\n\t\t\tmodel.addConstr(lhs, GRB_EQUAL, 1, oss.str());\n\t\t}\n\n\t\t// C2: \\forall h \\in H: \\sum_{v \\in V} y_{vh} \\le |V|*x_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tGRBLinExpr lhs(0);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tlhs += y[v][h];\n\t\t\t}\n\n\t\t\tmodel.addConstr(lhs, GRB_LESS_EQUAL, x[h]*static_cast<RealT>(nvms), oss.str());\n\t\t}\n\n\t\t// C3: \\forall h \\in H: \\sum_{v \\in V} y_{vh}M_{q(v),g(h)} \\le x_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tGRBLinExpr lhs(0);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tRealT req(vm_specs_ram[vms_category[v]][pms_category[h]]);\n\t\t\t\tlhs += y[v][h]*req;\n\t\t\t}\n\n\t\t\tmodel.addConstr(lhs, GRB_LESS_EQUAL, x[h], oss.str());\n\t\t}\n\n\t\t// C4: \\forall h \\in H: \\sum_{v \\in V} y_{vh}S_{q(v),g(h)} == s_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tGRBLinExpr lhs(0);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tRealT req(vm_specs_cpu[vms_category[v]][pms_category[h]]);\n\t\t\t\tlhs += y[v][h]*req;\n\t\t\t}\n\n\t\t\tmodel.addConstr(lhs, GRB_EQUAL, s[h], oss.str());\n\t\t}\n\n\t\t// C5: \\forall h \\in H: s_{h} \\le x_{h}\n\t\t++cc;\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"C\" << cc << \"_{\" << h << \"}\";\n\n\t\t\tmodel.addConstr(s[h], GRB_LESS_EQUAL, x[h], oss.str());\n\t\t}\n\n\t\t// Set objective\n\t\tGRBLinExpr z(0);\n\t\tif (min_power)\n\t\t{\n\t\t\t//FIXME: this does not work well when PM switch-on/off costs and VM migration costs are != zero!\n\t\t\tstd::cerr << \"(W) Power optimization does not work well when PM switch-on/off costs and VM migration costs are not zero!\" << std::endl;\n\n\t\t\t// z = \\min sum_{h \\in H}{x_h C_{g(h)}^{min} + (C_{g(h)}^{max}-C_{g(h)}^{min})s_{h} + x_h(1-o(i)) + (1-x_h)o(i)}\n\t\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t\t{\n\t\t\t\tRealT dC = pm_specs_max_power[pms_category[h]]-pm_specs_min_power[pms_category[h]];\n\n\t\t\t\tz += x[h]*pm_specs_min_power[pms_category[h]] + dC*s[h];\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t\t{\n\t\t\t\t// Add PM power costs due to computing demand\n\t\t\t\tRealT dC = pm_specs_max_power[pms_category[h]]-pm_specs_min_power[pms_category[h]];\n\t\t\t\tRealT wcost = cips_electricity_cost[pms_cip[h]]*1e-3; // Electricity cost in Wh\n\t\t\t\tz += (x[h]*pm_specs_min_power[pms_category[h]]+dC*s[h])*wcost;\n\t\t\t\t// Add PM switch-on/off costs\n\t\t\t\tz += x[h]*(1-pm_power_states[h])*cip_pm_awake_costs[pms_cip[h]][pms_category[h]]\n\t\t\t\t  +  (1-x[h])*pm_power_states[h]*cip_pm_asleep_costs[pms_cip[h]][pms_category[h]];\n\t\t\t\t// Add VM migration costs\n\t\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t\t{\n\t\t\t\t\tz += y[v][h]*cip_to_cip_vm_migration_costs[vms_cip[v]][pms_cip[h]][vms_category[v]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmodel.setObjective(z, GRB_MINIMIZE);\n\t\tmodel.update();\n\n#ifdef DCS_DEBUG\n\t\tmodel.write(\"gurobi-model.lp\");\n#endif // DCS_DEBUG\n \n\t\tmodel.optimize();\n\n\t\tsolution.solved = false;\n\t\tsolution.optimal = false;\n\n\t\tint status = model.get(GRB_IntAttr_Status);\n\t\tswitch (status)\n\t\t{\n\t\t\tcase GRB_OPTIMAL: // The algorithm found an optimal solution.\n\t\t\t\tsolution.objective_value = static_cast<RealT>(model.get(GRB_DoubleAttr_ObjVal));\n\t\t\t\tsolution.solved = true;\n\t\t\t\tsolution.optimal = true;\n\t\t\t\tbreak;\n\t\t\tcase GRB_SUBOPTIMAL: // The algorithm found a feasible solution, though it may not necessarily be optimal.\n\t\t\t\tsolution.objective_value = static_cast<RealT>(model.get(GRB_DoubleAttr_ObjVal));\n\t\t\t\tstd::clog << \"(W) Optimization problem solved but non-optimal\" << std::endl;\n\t\t\t\tsolution.solved = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tstd::ostringstream oss;\n\t\t\t\tstd::clog << \"Optimization was stopped with status = \" << status << std::endl;\n\t\t\t\treturn solution;\n\t\t\t}\n\t\t}\n\n#ifdef DCS_DEBUG\n\t\tDCS_DEBUG_TRACE( \"Optimal solution: \" );\n\n\t\tDCS_DEBUG_TRACE( \"- Solved: \" << std::boolalpha << solution.solved );\n\t\tDCS_DEBUG_TRACE( \"- Optimal: \" << std::boolalpha << solution.optimal );\n\n\t\tDCS_DEBUG_TRACE( \"- Decision variables: \" );\n\n\t\t// Output x_{h}\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tDCS_DEBUG_STREAM << x[h].get(GRB_StringAttr_VarName) << \" = \" << x[h].get(GRB_DoubleAttr_X) << \" (\" << static_cast<bool>(x[h].get(GRB_DoubleAttr_X)) << \")\" << ::std::endl;\n\t\t}\n\n\t\t// Output y_{vh}\n\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t{\n\t\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t\t{\n\t\t\t\tDCS_DEBUG_STREAM << y[v][h].get(GRB_StringAttr_VarName) << \" = \" << y[v][h].get(GRB_DoubleAttr_X) << \" (\" << static_cast<bool>(y[v][h].get(GRB_DoubleAttr_X)) << \")\" << ::std::endl;\n\t\t\t}\n\t\t}\n\n\t\t// Output s_{h}\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tDCS_DEBUG_STREAM << s[h].get(GRB_StringAttr_VarName) << \" = \" << s[h].get(GRB_DoubleAttr_X) << std::endl;\n\t\t}\n\n\t\t//Print z\n\t\tDCS_DEBUG_TRACE( \"- Objective value: \" << solution.objective_value );\n#endif // DCS_DEBUG\n\n\t\tsolution.pm_power_states.resize(npms);\n\t\tsolution.pm_vm_allocations.resize(npms);\n\t\tif (min_power)\n\t\t{\n\t\t\t// Computed in the loop below\n\t\t\tsolution.cost = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsolution.cost = solution.objective_value;\n\t\t}\n\t\tfor (std::size_t h = 0; h < npms; ++h)\n\t\t{\n\t\t\tsolution.pm_power_states[h] = static_cast<bool>(x[h].get(GRB_DoubleAttr_X));\n\n\t\t\t// Compute the energy cost\n\t\t\tif (min_power && static_cast<bool>(x[h].get(GRB_DoubleAttr_X)))\n\t\t\t{\n\t\t\t\t//RealT dC = pm_specs_max_power[pms_category[h]]-pm_specs_min_power[pms_category[h]];\n\t\t\t\tRealT wcost = cips_electricity_cost[pms_cip[h]]*1e-3; // Electricity cost in Wh\n\n\t\t\t\t//solution.cost += (pm_specs_min_power[pms_category[h]] + dC*static_cast<RealT>(s[h].get(GRB_DoubleAttr_X)))*wcost;\n\t\t\t\tsolution.cost += pm_consumed_power(pm_specs_min_power[pms_category[h]], pm_specs_max_power[pms_category[h]], static_cast<RealT>(s[h].get(GRB_DoubleAttr_X)))*wcost;\n\t\t\t}\n\t\t\tsolution.pm_vm_allocations[h].resize(nvms);\n\t\t\tfor (std::size_t v = 0; v < nvms; ++v)\n\t\t\t{\n\t\t\t\tsolution.pm_vm_allocations[h][v] = static_cast<bool>(y[v][h].get(GRB_DoubleAttr_X));\n\t\t\t}\n\t\t}\n\t}\n\tcatch (GRBException const& e)\n\t{\n\t\t::std::ostringstream oss;\n\t\toss << \"Got exception from GUROBI: \" << e.getMessage() << \" (\" << e.getErrorCode() << \")\";\n\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t}\n\tcatch (...)\n\t{\n\t\tDCS_EXCEPTION_THROW(::std::runtime_error,\n\t\t\t\t\t\t\t\"Unexpected error during the optimization\");\n\t}\n#else\n# error Unable to find a suitable solver\n#endif // DCS_CLOUD_GT_HAVE_*_SOLVER\n\n\treturn solution;\n}\n\n\ntemplate <typename RealT>\nstruct merge_split_stable_partition_selector\n{\n\t::std::vector< partition_info<RealT> > operator()(::gtpack::cooperative_game<RealT> const& game, ::std::map< gtpack::cid_type, coalition_info<RealT> > const& visited_coalitions)\n\t{\n\t\tnamespace alg = ::dcs::algorithm;\n\n\t\t// Generate all partitions and select the ones that are D_{hp}-stable, that is that are stable according to merge/split operations\n\n\t\t::std::vector< partition_info<RealT> > best_partitions;\n\n\t\tconst ::std::vector<gtpack::player_type> players(game.players());\n\t\tconst ::std::size_t np(players.size());\n\n\t\talg::lexicographic_partition partition(np);\n\n\t\twhile (partition.has_next())\n\t\t{\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_container subset_container;\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_const_iterator subset_iterator;\n\n\t\t\tsubset_container subs;\n\n\t\t\t// Each subset is a collection of coalitions\n\t\t\tsubs = alg::next_partition(players.begin(), players.end(), partition);\n\n\t\t\tDCS_DEBUG_TRACE(\"--- PARTITION: \" << partition);//XXX\n\n\t\t\tpartition_info<RealT> candidate_partition;\n\n\t\t\tbool Dhp_stable(true);\n\n\t\t\tstd::vector<gtpack::cid_type> P;\n\n\t\t\tsubset_iterator sub_end_it(subs.end());\n\t\t\tfor (subset_iterator sub_it = subs.begin();\n\t\t\t\t sub_it != sub_end_it && Dhp_stable;\n\t\t\t\t ++sub_it)\n\t\t\t{\n\t\t\t\tconst gtpack::cid_type cid = gtpack::players_coalition<RealT>::make_id(sub_it->begin(), sub_it->end());\n\n\t\t\t\tP.push_back(cid);\n\n\t\t\t\tif (visited_coalitions.count(cid) == 0)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tDCS_DEBUG_TRACE(\"--- COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \")\");//XXX\n\n\t\t\t\tcandidate_partition.coalitions.insert(cid);\n\n\t\t\t\t// Check that v(P_i) \\ge \\sum_{j=1}^l v(C_j), \\forall partition C=\\{C_1,\\ldots,C_l\\} of P_i\n\n\t\t\t\tRealT vPi = visited_coalitions.at(cid).value;\n\n\t\t\t\t::std::vector<gtpack::player_type> coal_players(sub_it->begin(), sub_it->end());\n\n\t\t\t\talg::lexicographic_partition sub_partition(coal_players.size());\n\t\t\t\tsubset_container sub_subs;\n\t\t\t\tsub_subs = alg::next_partition(coal_players.begin(), coal_players.end(), sub_partition);\n\t\t\t\tsubset_iterator sub_sub_end_it(sub_subs.end());\n\t\t\t\tRealT svC = 0;\n\t\t\t\tfor (subset_iterator sub_sub_it = sub_subs.begin();\n\t\t\t\t\t sub_sub_it != sub_sub_end_it;\n\t\t\t\t\t ++sub_sub_it)\n\t\t\t\t{\n\t\t\t\t\tconst gtpack::cid_type sub_cid = gtpack::players_coalition<RealT>::make_id(sub_sub_it->begin(), sub_sub_it->end());\n\n\t\t\t\t\tif (visited_coalitions.count(sub_cid) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tsvC += visited_coalitions.at(sub_cid).value;\n\t\t\t\t}\n\n\t\t\t\tif (dcs::math::float_traits<RealT>::definitely_less(vPi, svC))\n\t\t\t\t{\n\t\t\t\t\tDhp_stable = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tfor (::std::size_t p = 0; p < coal_players.size(); ++p)\n\t\t\t\t{\n\t\t\t\t\tconst gtpack::player_type pid = coal_players[p];\n\n\t\t\t\t\tif (visited_coalitions.at(cid).payoffs.count(pid) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = visited_coalitions.at(cid).payoffs.at(pid);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = ::std::numeric_limits<RealT>::quiet_NaN();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!Dhp_stable)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\talg::lexicographic_subset P_subset(P.size(), false);\n\n\t\t\twhile (P_subset.has_next() && Dhp_stable)\n\t\t\t{\n\t\t\t\ttypedef typename alg::subset_traits<gtpack::cid_type>::element_container cid_container;\n\n\t\t\t\tconst cid_container sub_P = alg::next_subset(P.begin(), P.end(), P_subset);\n\n\t\t\t\tRealT svPi = 0;\n\t\t\t\tstd::set<gtpack::player_type> UPi_players;\n\t\t\t\tfor (std::size_t i = 0; i < sub_P.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tconst gtpack::cid_type Pi_cid = sub_P[i];\n\n\t\t\t\t\tif (visited_coalitions.count(Pi_cid) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tsvPi += visited_coalitions.at(Pi_cid).value;\n\n\t\t\t\t\tconst std::vector<gtpack::player_type> Pi_players = gtpack::players_coalition<RealT>(np, Pi_cid).players();\n\t\t\t\t\tUPi_players.insert(Pi_players.begin(), Pi_players.end());\n\t\t\t\t}\n\n\t\t\t\tconst gtpack::cid_type UPi_cid = gtpack::players_coalition<RealT>(UPi_players.begin(), UPi_players.end()).id();\n\t\t\t\tif (visited_coalitions.count(UPi_cid) == 0)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst RealT vUPi = visited_coalitions.at(UPi_cid).value;\n\n\t\t\t\tif (dcs::math::float_traits<RealT>::definitely_less(svPi, vUPi))\n\t\t\t\t{\n\t\t\t\t\tDhp_stable = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Dhp_stable)\n\t\t\t{\n\t\t\t\tbest_partitions.push_back(candidate_partition);\n\t\t\t}\n\t\t}\n\n\t\treturn best_partitions;\n\t}\n}; // nash_stable_partition_selector\n\n\ntemplate <typename RealT>\nstruct nash_stable_partition_selector\n{\n\t::std::vector< partition_info<RealT> > operator()(::gtpack::cooperative_game<RealT> const& game, ::std::map< gtpack::cid_type, coalition_info<RealT> > const& visited_coalitions)\n\t{\n\t\tnamespace alg = ::dcs::algorithm;\n\n\t\t// Generate all partitions and select the ones that are Nash-stable\n\n\t\t::std::vector< partition_info<RealT> > best_partitions;\n\n\t\tconst ::std::vector<gtpack::player_type> players(game.players());\n\t\tconst ::std::size_t np(players.size());\n\n\t\talg::lexicographic_partition partition(np);\n\n\t\twhile (partition.has_next())\n\t\t{\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_container subset_container;\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_const_iterator subset_iterator;\n\n\t\t\tsubset_container subs;\n\n\t\t\t// Each subset is a collection of coalitions\n\t\t\tsubs = alg::next_partition(players.begin(), players.end(), partition);\n\n\t\t\tDCS_DEBUG_TRACE(\"--- PARTITION: \" << partition);//XXX\n\n\t\t\tpartition_info<RealT> candidate_partition;\n\n\t\t\tsubset_iterator sub_end_it(subs.end());\n\t\t\tfor (subset_iterator sub_it = subs.begin();\n\t\t\t\t sub_it != sub_end_it;\n\t\t\t\t ++sub_it)\n\t\t\t{\n\t\t\t\tconst gtpack::cid_type cid = gtpack::players_coalition<RealT>::make_id(sub_it->begin(), sub_it->end());\n\n\t\t\t\tif (visited_coalitions.count(cid) == 0)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tDCS_DEBUG_TRACE(\"--- COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \")\");//XXX\n\n\t\t\t\tcandidate_partition.coalitions.insert(cid);\n\n\t\t\t\t::std::vector<gtpack::player_type> coal_players(sub_it->begin(), sub_it->end());\n\t\t\t\tfor (::std::size_t p = 0; p < coal_players.size(); ++p)\n\t\t\t\t{\n\t\t\t\t\tconst gtpack::player_type pid = coal_players[p];\n\n\t\t\t\t\tif (visited_coalitions.at(cid).payoffs.count(pid) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = visited_coalitions.at(cid).payoffs.at(pid);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = ::std::numeric_limits<RealT>::quiet_NaN();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check Nash-stability\n\n\t\t\tbool nash_stable(true);\n\n\t\t\t// For all players $p$\n\t\t\tfor (::std::size_t p = 0; p < np && nash_stable; ++p)\n\t\t\t{\n\t\t\t\tconst gtpack::player_type pid(players[p]);\n\n\t\t\t\t// For all $S_k$ \\in \\Pi \\cup \\{\\emptyset\\}$\n\t\t\t\tbool found_singleton(false);\n\t\t\t\tsubset_iterator sub_end_it(subs.end());\n\t\t\t\tfor (subset_iterator sub_it = subs.begin();\n\t\t\t\t\t sub_it != sub_end_it && nash_stable;\n\t\t\t\t\t ++sub_it)\n\t\t\t\t{\n\t\t\t\t\t::std::set<gtpack::player_type> coal_players(sub_it->begin(), sub_it->end());\n\n\t\t\t\t\tif (coal_players.count(pid) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// This coalition doesn't include player pid, go on\n\n\t\t\t\t\t\t// Evaluate $S_k \\cup {p}\n\t\t\t\t\t\tcoal_players.insert(pid);\n\n\t\t\t\t\t\tconst gtpack::cid_type cid = gtpack::players_coalition<RealT>::make_id(coal_players.begin(), coal_players.end());\n\n\t\t\t\t\t\tDCS_DEBUG_TRACE(\"--- PID: \" << pid << \" - AUGMENTED COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \") - AUGMENTED PAYOFF: \" << (visited_coalitions.at(cid).payoffs.count(pid) ? visited_coalitions.at(cid).payoffs.at(pid) : ::std::numeric_limits<RealT>::quiet_NaN()) << \" - CANDIDATE PAYOFF: \" << candidate_partition.payoffs.at(pid));///XXX\n\n\t\t\t\t\t\t// Check player's preference\n\t\t\t\t\t\tif (visited_coalitions.at(cid).payoffs.count(pid) == 0\n\t\t\t\t\t\t\t|| ::dcs::math::float_traits<RealT>::definitely_greater(visited_coalitions.at(cid).payoffs.at(pid), candidate_partition.payoffs.at(pid)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDCS_DEBUG_TRACE(\"--- PID: \" << pid << \" - AUGMENTED COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \"): NOT NASH STABLE\");//XXX\n\t\t\t\t\t\t\tnash_stable = false;\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\telse if (coal_players.size() == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tfound_singleton = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Check singleton coalition\n\t\t\t\tif (!found_singleton)\n\t\t\t\t{\n\t\t\t\t\tconst gtpack::cid_type cid = gtpack::players_coalition<RealT>::make_id(&(players[p]), &(players[p])+1);\n\n\t\t\t\t\t//DCS_DEBUG_TRACE(\"--- PID: \" << pid << \" - AUGMENTED COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \")\");//XXX\n\t\t\t\t\tDCS_DEBUG_TRACE(\"--- PID: \" << pid << \" - AUGMENTED COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \") - AUGMENTED PAYOFF: \" << (visited_coalitions.count(cid) && visited_coalitions.at(cid).payoffs.count(pid) ? visited_coalitions.at(cid).payoffs.at(pid) : ::std::numeric_limits<RealT>::quiet_NaN()) << \" - CANDIDATE PAYOFF: \" << candidate_partition.payoffs.at(pid));///XXX\n\n\t\t\t\t\tif (candidate_partition.coalitions.count(cid) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// This partition doesn't contain this singleton coalition\n\t\t\t\t\t\tif (visited_coalitions.at(cid).payoffs.count(pid) == 0\n\t\t\t\t\t\t\t|| ::dcs::math::float_traits<RealT>::definitely_greater(visited_coalitions.at(cid).payoffs.at(pid), candidate_partition.payoffs.at(pid)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDCS_DEBUG_TRACE(\"--- PID: \" << pid << \" - AUGMENTED COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \"): NOT NASH STABLE\");//XXX\n\t\t\t\t\t\t\tnash_stable = false;\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\n\t\t\tif (nash_stable)\n\t\t\t{\n\t\t\t\tbest_partitions.push_back(candidate_partition);\n\t\t\t}\n\t\t}\n\n\t\treturn best_partitions;\n\t}\n}; // nash_stable_partition_selector\n\n\ntemplate <typename RealT>\nstruct pareto_optimal_partition_selector\n{\n\t::std::vector< partition_info<RealT> > operator()(::gtpack::cooperative_game<RealT> const& game, ::std::map< gtpack::cid_type, coalition_info<RealT> > const& visited_coalitions)\n\t{\n\t\tnamespace alg = ::dcs::algorithm;\n\n\t\t// Generate all partitions and select the ones that are Pareto optimal\n\n\t\t::std::vector< partition_info<RealT> > best_partitions;\n\n\t\tconst ::std::vector<gtpack::player_type> players(game.players());\n\t\tconst ::std::size_t np(players.size());\n\n\t\talg::lexicographic_partition partition(np);\n\n\t\t::std::vector<RealT> best_payoffs(np, ::std::numeric_limits<RealT>::quiet_NaN());\n\n\t\twhile (partition.has_next())\n\t\t{\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_container subset_container;\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_const_iterator subset_iterator;\n\n\t\t\tsubset_container subs;\n\n\t\t\t// Each subset is a collection of coalitions\n\t\t\tsubs = alg::next_partition(players.begin(), players.end(), partition);\n\n\t\t\tDCS_DEBUG_TRACE(\"--- PARTITION: \" << partition);//XXX\n\n\t\t\tpartition_info<RealT> candidate_partition;\n\n\t\t\tsubset_iterator sub_end_it(subs.end());\n\t\t\tfor (subset_iterator sub_it = subs.begin();\n\t\t\t\t sub_it != sub_end_it;\n\t\t\t\t ++sub_it)\n\t\t\t{\n\t\t\t\tconst gtpack::cid_type cid = gtpack::players_coalition<RealT>::make_id(sub_it->begin(), sub_it->end());\n\n\t\t\t\tif (visited_coalitions.count(cid) == 0)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tDCS_DEBUG_TRACE(\"--- COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \")\");//XXX\n\n\t\t\t\tcandidate_partition.coalitions.insert(cid);\n\n\t\t\t\t::std::vector<gtpack::player_type> coal_players(sub_it->begin(), sub_it->end());\n\t\t\t\tfor (::std::size_t p = 0; p < coal_players.size(); ++p)\n\t\t\t\t{\n\t\t\t\t\tconst gtpack::player_type pid = coal_players[p];\n\n\t\t\t\t\tif (visited_coalitions.at(cid).payoffs.count(pid) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = visited_coalitions.at(cid).payoffs.at(pid);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = ::std::numeric_limits<RealT>::quiet_NaN();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check Pareto optimality\n\n\t\t\tbool pareto_optimal(true);\n\n\t\t\t// For all players $p$\n\t\t\tfor (std::size_t p = 0; p < np && pareto_optimal; ++p)\n\t\t\t{\n\t\t\t\tconst gtpack::player_type pid(players[p]);\n\n\t\t\t\tif (::std::isnan(best_payoffs[p]) || candidate_partition.payoffs.at(pid) > best_payoffs[p])\n\t\t\t\t{\n\t\t\t\t\tbest_payoffs[p] = candidate_partition.payoffs.at(pid);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpareto_optimal = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (pareto_optimal)\n\t\t\t{\n\t\t\t\tbest_partitions.push_back(candidate_partition);\n\t\t\t}\n\t\t}\n\n\t\treturn best_partitions;\n\t}\n}; // pareto_optimal_partition_selector\n\n\ntemplate <typename RealT>\nstruct social_optimum_partition_selector\n{\n\t::std::vector< partition_info<RealT> > operator()(::gtpack::cooperative_game<RealT> const& game, ::std::map< gtpack::cid_type, coalition_info<RealT> > const& visited_coalitions)\n\t{\n\t\tnamespace alg = ::dcs::algorithm;\n\n\t\t// Generate all partitions and select the ones that maximize the social welfare\n\n\t\t::std::vector< partition_info<RealT> > best_partitions;\n\n\t\tconst ::std::vector<gtpack::player_type> players(game.players());\n\t\tconst ::std::size_t np(players.size());\n\t\tRealT best_value(0);\n\n\t\talg::lexicographic_partition partition(np);\n\n\t\twhile (partition.has_next())\n\t\t{\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_container subset_container;\n\t\t\ttypedef typename alg::partition_traits<gtpack::player_type>::subset_const_iterator subset_iterator;\n\n\t\t\tsubset_container subs;\n\n\t\t\t// Each subset is a collection of coalitions\n\t\t\tsubs = alg::next_partition(players.begin(), players.end(), partition);\n\n\t\t\tDCS_DEBUG_TRACE(\"--- PARTITION: \" << partition);//XXX\n\n\t\t\tpartition_info<RealT> candidate_partition;\n\t\t\tRealT candidate_partition_value(0);\n\n\t\t\tsubset_iterator sub_end_it(subs.end());\n\t\t\tfor (subset_iterator sub_it = subs.begin();\n\t\t\t\t sub_it != sub_end_it;\n\t\t\t\t ++sub_it)\n\t\t\t{\n\t\t\t\tconst gtpack::cid_type cid = gtpack::players_coalition<RealT>::make_id(sub_it->begin(), sub_it->end());\n\n\t\t\t\tif (visited_coalitions.count(cid) == 0)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tDCS_DEBUG_TRACE(\"--- COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \")\");//XXX\n\n\t\t\t\tcandidate_partition.coalitions.insert(cid);\n\n\t\t\t\t::std::vector<gtpack::player_type> coal_players(sub_it->begin(), sub_it->end());\n\t\t\t\tfor (::std::size_t p = 0; p < coal_players.size(); ++p)\n\t\t\t\t{\n\t\t\t\t\tconst gtpack::player_type pid = coal_players[p];\n\n\t\t\t\t\tif (visited_coalitions.at(cid).payoffs.count(pid) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = visited_coalitions.at(cid).payoffs.at(pid);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcandidate_partition.payoffs[pid] = ::std::numeric_limits<RealT>::quiet_NaN();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcandidate_partition_value += visited_coalitions.at(cid).value;\n\t\t\t}\n\n\t\t\t// Check for social optimum\n\n\t\t\tif (best_partitions.size() == 0\n\t\t\t\t|| ::dcs::math::float_traits<RealT>::definitely_greater(candidate_partition_value, best_value))\n\t\t\t{\n\t\t\t\tbest_partitions.clear();\n\t\t\t\tbest_partitions.push_back(candidate_partition);\n\t\t\t\tbest_value = candidate_partition_value;\n\t\t\t}\n\t\t\telse if (::dcs::math::float_traits<RealT>::essentially_equal(candidate_partition_value, best_value))\n\t\t\t{\n\t\t\t\tbest_partitions.push_back(candidate_partition);\n\t\t\t}\n\t\t}\n\n\t\treturn best_partitions;\n\t}\n}; // social_optimum_partition_selector\n\n\ntemplate <typename RealT>\ncoalition_formation_info<RealT> analyze_coalitions(scenario<RealT> const& s, options<RealT> const& opts)\n{\n\t//typedef RealT real_type;\n\n\t//const std::size_t ncoals(std::pow(2, s.num_cips)-1);\n\n\tstd::vector<std::size_t> cips(s.num_cips);\n\tstd::size_t num_pms = 0;\n//\tstd::size_t num_vms = 0;\n\n\tgtpack::cooperative_game<RealT> game(s.num_cips, boost::make_shared< gtpack::explicit_characteristic_function<RealT> >());\n\n\tfor (std::size_t k = 0; k < s.num_cips; ++k)\n\t{\n\t\tcips[k] = k;\n\n\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t{\n\t\t\tnum_pms += s.cip_num_pms[k][p];\n\t\t}\n\n//\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n//\t\t{\n//\t\t\tnum_vms += s.cip_num_vms[k][v];\n//\t\t}\n\t}\n\n\tstd::map< gtpack::cid_type, coalition_info<RealT> > visited_coalitions;\n\n\talg::lexicographic_subset subset(s.num_cips, false);\n\n\twhile (subset.has_next())\n\t{\n\t\ttypedef typename alg::subset_traits<std::size_t>::element_container element_container;\n\n\t\tDCS_DEBUG_TRACE(\"--- SUBSET: \" << subset);//XXX\n\n\t\tconst element_container coal_cips = alg::next_subset(cips.begin(), cips.end(), subset);\n\t\tconst std::size_t coal_ncips(coal_cips.size());\n\n\t\tconst gtpack::cid_type cid = gtpack::players_coalition<RealT>::make_id(coal_cips.begin(), coal_cips.end());\n\n\t\tDCS_DEBUG_TRACE(\"--- COALITION: \" << game.coalition(cid) << \" (CID=\" << cid << \")\");//XXX\n\n\t\tstd::size_t coal_npms(0);\n\t\tstd::size_t coal_nvms(0);\n\n\t\tfor (std::size_t i = 0; i < coal_ncips; ++i)\n\t\t{\n\t\t\tstd::size_t cip(coal_cips[i]);\n\n\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t{\n\t\t\t\tcoal_npms += s.cip_num_pms[cip][p];\n\t\t\t}\n\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t{\n\t\t\t\tcoal_nvms += s.cip_num_vms[cip][v];\n\t\t\t}\n\t\t}\n\n\t\tstd::size_t pms_start(0);\n\t\tstd::size_t pms_stop(0);\n\t\tstd::size_t vms_start(0);\n\t\tstd::size_t vms_stop(0);\n\t\tstd::vector<std::size_t> coal_pms_cips(coal_npms);\n\t\tstd::vector<std::size_t> coal_vms_cips(coal_nvms);\n\t\tstd::vector<std::size_t> coal_pms_category(coal_npms);\n\t\tstd::vector<std::size_t> coal_vms_category(coal_nvms);\n\t\tstd::vector<bool> coal_pm_power_states(coal_npms);\n\t\tRealT coal_profit(0);\n\n\t\tfor (std::size_t i = 0; i < coal_ncips; ++i)\n\t\t{\n\t\t\tstd::size_t cip(coal_cips[i]);\n\n\t\t\tfor (std::size_t p = 0; p < s.num_pm_types; ++p)\n\t\t\t{\n\t\t\t\tif (s.cip_num_pms[cip][p] > 0)\n\t\t\t\t{\n\t\t\t\t\tpms_stop += s.cip_num_pms[cip][p];\n//DCS_DEBUG_TRACE(\"FILLING PMS -- CID: \" << cid << \" - CIP: \" << cip << \" - START: \" << pms_start << \" - STOP: \" << pms_stop);\n\t\t\t\t\tstd::fill(coal_pms_category.begin()+pms_start, coal_pms_category.begin()+pms_stop, p);\n\t\t\t\t\tstd::fill(coal_pms_cips.begin()+pms_start, coal_pms_cips.begin()+pms_stop, cip);\n\t\t\t\t\tfor (std::size_t k = 0; k < (pms_stop-pms_start); ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tcoal_pm_power_states[k+pms_start] = s.cip_pm_power_states[cip][k];\n\t\t\t\t\t}\n\t\t\t\t\tpms_start = pms_stop;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (std::size_t v = 0; v < s.num_vm_types; ++v)\n\t\t\t{\n\t\t\t\tcoal_profit += s.cip_revenues[cip][v]*s.cip_num_vms[cip][v];\n\n\t\t\t\tif (s.cip_num_vms[cip][v] > 0)\n\t\t\t\t{\n\t\t\t\t\tvms_stop += s.cip_num_vms[cip][v];\n//DCS_DEBUG_TRACE(\"FILLING VMS -- CID: \" << cid << \" - CIP: \" << cip << \" - START: \" << vms_start << \" - STOP: \" << vms_stop);\n\t\t\t\t\tstd::fill(coal_vms_category.begin()+vms_start, coal_vms_category.begin()+vms_stop, v);\n\t\t\t\t\tstd::fill(coal_vms_cips.begin()+vms_start, coal_vms_cips.begin()+vms_stop, cip);\n\t\t\t\t\tvms_start = vms_stop;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\toptimal_allocation_info<RealT> optimal_allocation;\n\t\toptimal_allocation = find_optimal_allocation(coal_ncips,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.cip_electricity_costs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t coal_npms,\n\t\t\t\t\t\t\t\t\t\t\t\t\t coal_pms_cips,\n\t\t\t\t\t\t\t\t\t\t\t\t\t coal_pms_category,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.pm_spec_min_powers,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.pm_spec_max_powers,\n\t\t\t\t\t\t\t\t\t\t\t\t\t coal_nvms,\n\t\t\t\t\t\t\t\t\t\t\t\t\t coal_vms_cips,\n\t\t\t\t\t\t\t\t\t\t\t\t\t coal_vms_category,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.vm_spec_cpus,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.vm_spec_rams,\n\t\t\t\t\t\t\t\t\t\t\t\t\t coal_pm_power_states,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.cip_pm_asleep_costs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.cip_pm_awake_costs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t s.cip_to_cip_vm_migration_costs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t false,\n\t\t\t\t\t\t\t\t\t\t\t\t\t opts.opt_relative_gap,\n\t\t\t\t\t\t\t\t\t\t\t\t\t opts.opt_time_lim);\n\n\t\tvisited_coalitions[cid].optimal_allocation = optimal_allocation;\n\t\tif (optimal_allocation.solved)\n\t\t{\n\t\t\tRealT coal_cost = 0;\n\n\t\t\tif (coal_ncips > 1)\n\t\t\t{\n\t\t\t\tfor (std::size_t c = 0; c < coal_ncips; ++c)\n\t\t\t\t{\n\t\t\t\t\tstd::size_t cip = coal_cips[c];\n\n\t\t\t\t\tcoal_cost += s.cip_coalition_costs[cip];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgame.value(cid, coal_profit-optimal_allocation.cost-coal_cost);\n\t\t\tvisited_coalitions[cid].value = game.value(cid);\n\n\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - Profit: \" << coal_profit << \" - Allocation Cost: \" << optimal_allocation.cost << \" - Coalition Cost: \" << coal_cost << \" => v(CID)=\" << game.value(cid) );\n\n//#ifdef DCS_DEBUG\n\t\t\tstd::map< std::size_t, cip_allocation_info<RealT> > coal_cips_info;\n\n\t\t\tRealT tot_cost(0);\n\t\t\tRealT tot_watt(0);\n\t\t\tfor (std::size_t c = 0; c < coal_ncips; ++c)\n\t\t\t{\n\t\t\t\tstd::size_t cip(coal_cips[c]);\n\n\t\t\t\tcoal_cips_info[cip].num_on_pms = 0;\n\t\t\t\tcoal_cips_info[cip].num_vms = 0;\n\t\t\t\tcoal_cips_info[cip].tot_watt = 0;\n\t\t\t\t//coal_cips_info[cip].tot_wcost = 0;\n\t\t\t}\n\t\t\tfor (std::size_t p = 0; p < coal_npms; ++p)\n\t\t\t{\n\t\t\t\tif (optimal_allocation.pm_power_states[p])\n\t\t\t\t{\n\t\t\t\t\tstd::size_t cip(coal_pms_cips[p]);\n\t\t\t\t\tstd::size_t pc(coal_pms_category[p]);\n\n\t\t\t\t\tcoal_cips_info[cip].num_on_pms += 1;\n\n\t\t\t\t\tRealT tot_share(0);\n\t\t\t\t\tfor (std::size_t v = 0; v < coal_nvms; ++v)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (optimal_allocation.pm_vm_allocations[p][v])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcoal_cips_info[cip].num_vms += 1;\n\t\t\t\t\t\t\ttot_share += s.vm_spec_cpus[coal_vms_category[v]][pc];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcoal_cips_info[cip].tot_watt += pm_consumed_power(s.pm_spec_min_powers[pc], s.pm_spec_max_powers[pc], tot_share);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (std::size_t c = 0; c < coal_ncips; ++c)\n\t\t\t{\n\t\t\t\tstd::size_t cip(coal_cips[c]);\n\n\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - CIP: \" << cip << \" - # Powered-on PMs: \" << coal_cips_info[cip].num_on_pms << \" - # Hosted VMs: \" << coal_cips_info[cip].num_vms << \" - Consumed Watts: \" << coal_cips_info[cip].tot_watt << \" - Energy Cost: \" << (coal_cips_info[cip].tot_watt*1e-3*s.cip_electricity_costs[cip]));\n\n\t\t\t\ttot_watt += coal_cips_info[cip].tot_watt*1e-3;\n\t\t\t\ttot_cost += coal_cips_info[cip].tot_watt*1e-3*s.cip_electricity_costs[cip];\n\t\t\t}\n//#endif // DCS_DEBUG\n\n\t\t\t//visited_coalitions[cid].optimal_allocation.cost = tot_cost;\n\t\t\tvisited_coalitions[cid].optimal_allocation.kwatt = tot_watt;\n\n\t\t\t// Check core existence\n\t\t\tgtpack::cooperative_game<RealT> subgame = game.subgame(coal_cips.begin(), coal_cips.end());\n\t\t\tgtpack::core<RealT> core = gtpack::find_core(subgame);\n\n\t\t\tif (core.empty())\n\t\t\t{\n\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - The core is empty\" );\n\n\t\t\t\tvisited_coalitions[cid].core_empty = true;\n\t\t\t\tvisited_coalitions[cid].payoffs_in_core = false;\n\t\t\t\t//skip_partition = true;\n\n\t\t\t\tif (subgame.num_players() == cips.size())\n\t\t\t\t{\n\t\t\t\t\t// This is the Grand coalition\n\n\t\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - The Grand-Coalition has an empty core\" );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - The core is not empty\" );\n\n\t\t\t\tvisited_coalitions[cid].core_empty = false;\n\t\t\t}\n\n\t\t\t// Compute the coalition value\n\t\t\tstd::map<gtpack::player_type,RealT> coal_payoffs;\n\t\t\tswitch (opts.coalition_value_division)\n\t\t\t{\n\t\t\t\tcase banzhaf_coalition_value_division:\n\t\t\t\t\tcoal_payoffs = gtpack::banzhaf_value(subgame);\n\t\t\t\t\tbreak;\n\t\t\t\tcase normalized_banzhaf_coalition_value_division:\n\t\t\t\t\tcoal_payoffs = gtpack::norm_banzhaf_value(subgame);\n\t\t\t\t\tbreak;\n\t\t\t\tcase shapley_coalition_value_division:\n\t\t\t\t\tcoal_payoffs = gtpack::shapley_value(subgame);\n\t\t\t\t\tbreak;\n\t\t\t}\n\n#ifdef DCS_DEBUG\n\t\t\tfor (std::size_t c = 0; c < coal_ncips; ++c)\n\t\t\t{\n\t\t\t\tstd::size_t cip(coal_cips[c]);\n\n\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - CIP: \" << cip << \" - Coalition payoff: \" << coal_payoffs[cip] );\n\t\t\t}\n#endif // DCS_DEBUG\n\n\t\t\tvisited_coalitions[cid].payoffs = coal_payoffs;\n\n\t\t\t// Check if the value is in the core (if the core != empty)\n\t\t\tif (!visited_coalitions.at(cid).core_empty)\n\t\t\t{\n\t\t\t\tif (gtpack::belongs_to_core(game.subgame(coal_cips.begin(), coal_cips.end()), coal_payoffs.begin(), coal_payoffs.end()))\n\t\t\t\t{\n\t\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - The Coalition value belongs to the core\" );\n\n\t\t\t\t\tvisited_coalitions[cid].payoffs_in_core = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - The Coaition value does not belong to the core\" );\n\n\t\t\t\t\tvisited_coalitions[cid].payoffs_in_core = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - The allocation problem is infeasible\" );\n\n\t\t\tvisited_coalitions[cid].core_empty = true;\n\t\t\tvisited_coalitions[cid].payoffs_in_core = false;\n\n\t\t\t//skip_partition = true;\n\t\t\tgame.value(cid, -::std::numeric_limits<RealT>::min());\n\n\t\t\tif (game.coalition(cid).num_players() == cips.size())\n\t\t\t{\n\t\t\t\t// This is the Grand coalition\n\n\t\t\t\tDCS_DEBUG_TRACE( \"CID: \" << cid << \" - The Grand-Coalition has an infeasible solution and thus an empty core\" );\n\t\t\t}\n\t\t}\n\t}\n\n\tcoalition_formation_info<RealT> formed_coalitions;\n\n\tformed_coalitions.coalitions = visited_coalitions;\n\tswitch (opts.coalition_formation)\n\t{\n\t\tcase merge_split_stable_coalition_formation:\n\t\t\tformed_coalitions.best_partitions = merge_split_stable_partition_selector<RealT>()(game, visited_coalitions);\n\t\t\tbreak;\n\t\tcase nash_stable_coalition_formation:\n\t\t\tformed_coalitions.best_partitions = nash_stable_partition_selector<RealT>()(game, visited_coalitions);\n\t\t\tbreak;\n\t\tcase pareto_optimal_coalition_formation:\n\t\t\tformed_coalitions.best_partitions = pareto_optimal_partition_selector<RealT>()(game, visited_coalitions);\n\t\t\tbreak;\n\t\tcase social_optimum_coalition_formation:\n\t\t\tformed_coalitions.best_partitions = social_optimum_partition_selector<RealT>()(game, visited_coalitions);\n\t\t\tbreak;\n\t}\n\n/*\n#ifdef DCS_DEBUG\n\tDCS_DEBUG_TRACE( \"FORMED PARTITIONS: \");\n\tfor (std::size_t i = 0; i < formed_coalitions.best_partitions.size(); ++i)\n\t{\n\t\tconst partition_info<RealT> part = formed_coalitions.best_partitions[i];\n\n\t\ttypedef typename std::set<gtpack::cid_type>::const_iterator coalition_iterator;\n\t\tcoalition_iterator coal_end_it(part.coalitions.end());\n\t\tDCS_DEBUG_STREAM << \"  [\";\n\t\tfor (coalition_iterator coal_it = part.coalitions.begin();\n\t\t\t coal_it != coal_end_it;\n\t\t\t ++coal_it)\n\t\t{\n\t\t\tconst gtpack::cid_type cid(*coal_it);\n\n\t\t\tDCS_DEBUG_STREAM << cid << \",\";\n\t\t}\n\t\tDCS_DEBUG_STREAM << \"]\" << std::endl;\n\t}\n#endif // DCS_DEBUG\n*/\n\n\treturn formed_coalitions;\n}\n\ntemplate <typename RealT>\nvoid report(std::size_t ncips, coalition_formation_info<RealT> const& formed_coalitions)\n{\n\ttypedef typename std::map<gtpack::player_type,RealT>::const_iterator coal_val_iterator;\n\n\tstd::vector<gtpack::player_type> players(ncips);\n\tfor (std::size_t c = 0; c < ncips; ++c)\n\t{\n\t\tplayers[c] = static_cast<gtpack::player_type>(c);\n\t}\n\n\t// Retrieve the ID of the grand-coalition\n\tgtpack::cid_type gcid = gtpack::players_coalition<RealT>::make_id(players.begin(), players.end());\n\n\tstd::cout << \"################################################################################\" << std::endl;\n\tstd::cout << \"### Report on Formed Coalitions:\" << std::endl;\n\tstd::cout << \"################################################################################\" << std::endl;\n\n\tstd::cout << \"- Best Partitions:\" << std::endl;\n\tif (formed_coalitions.best_partitions.size() > 0)\n\t{\n\t\tfor (std::size_t i = 0; i < formed_coalitions.best_partitions.size(); ++i)\n\t\t{\n\t//\t\tconst bs::partition_info<RealT> part = formed_coalitions.best_partitions[i];\n\t//\n\t//\t\ttypedef typename std::set<gtpack::cid_type>::const_iterator coalition_iterator;\n\t//\t\tcoalition_iterator coal_end_it(part.coalitions.end());\n\t//\t\tDCS_DEBUG_STREAM << \"  [\";\n\t//\t\tfor (coalition_iterator coal_it = part.coalitions.begin();\n\t//\t\t\t coal_it != coal_end_it;\n\t//\t\t\t ++coal_it)\n\t//\t\t{\n\t//\t\t\tconst gtpack::cid_type cid(*coal_it);\n\t//\n\t//\t\t\tDCS_DEBUG_STREAM << cid << \",\";\n\t//\t\t}\n\t//\t\tDCS_DEBUG_STREAM << \"]\" << std::endl;\n\n\t\t\ttypedef typename std::set<gtpack::cid_type>::const_iterator cid_iterator;\n\n\t\t\tRealT bestpart_value(0);\n\t\t\tRealT grandpart_value(0);\n\t\t\tRealT singlepart_value(0);\n\t\t\tRealT bestpart_kwatt(0);\n\t\t\t//RealT grandpart_kwatt(0);\n\t\t\tRealT singlepart_kwatt(0);\n\n\t\t\tcid_iterator cid_beg_it(formed_coalitions.best_partitions[i].coalitions.begin());\n\t\t\tcid_iterator cid_end_it(formed_coalitions.best_partitions[i].coalitions.end());\n\n\t\t\tstd::cout << \" * Payoffs: {\";\n\t\t\tfor (cid_iterator cid_it = cid_beg_it; cid_it != cid_end_it; ++cid_it)\n\t\t\t{\n\t\t\t\t//typedef typename std::map<gtpack::player_type,RealT>::const_iterator coal_val_iterator;\n\n\t\t\t\tgtpack::cid_type cid(*cid_it);\n\n\t\t\t\tif (cid_it != cid_beg_it)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t}\n\n\t\t\t\tstd::cout << \"{\";\n\t\t\t\tcoal_val_iterator coal_val_end_it(formed_coalitions.coalitions.at(cid).payoffs.end());\n\t\t\t\tcoal_val_iterator coal_val_beg_it(formed_coalitions.coalitions.at(cid).payoffs.begin());\n\t\t\t\tfor (coal_val_iterator coal_val_it = coal_val_beg_it;\n\t\t\t\t\t coal_val_it != coal_val_end_it;\n\t\t\t\t\t ++coal_val_it)\n\t\t\t\t{\n\t\t\t\t\tgtpack::player_type pid(coal_val_it->first);\n\t\t\t\t\tRealT value(coal_val_it->second);\n\n\t\t\t\t\tif (coal_val_it != coal_val_beg_it)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t\t}\n\n\t\t\t\t\tstd::cout << pid << \" => \" << value;\n\t\t\t\t\tbestpart_value += value;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"}\";\n\n\t\t\t\tbestpart_kwatt += formed_coalitions.coalitions.at(cid).optimal_allocation.kwatt;\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\n\t\t\tstd::cout << \" * Value: \" << bestpart_value << std::endl;\n\t\t\tstd::cout << \" * Energy Consumption: \" << bestpart_kwatt << std::endl;\n\n//\t\t\tstd::cout << \" * Side Payments: {\";\n//\t\t\tfor (cid_iterator cid_it = cid_beg_it; cid_it != cid_end_it; ++cid_it)\n//\t\t\t{\n//\t\t\t\tgtpack::cid_type cid(*cid_it);\n//\n//\t\t\t\tif (cid_it != cid_beg_it)\n//\t\t\t\t{\n//\t\t\t\t\tstd::cout << \", \";\n//\t\t\t\t}\n//\n//\t\t\t\tstd::cout << \"{\";\n//\t\t\t\tcoal_val_iterator coal_val_end_it(formed_coalitions.coalitions.at(cid).payoffs.end());\n//\t\t\t\tcoal_val_iterator coal_val_beg_it(formed_coalitions.coalitions.at(cid).payoffs.begin());\n//\t\t\t\tfor (coal_val_iterator coal_val_it = coal_val_beg_it;\n//\t\t\t\t\t coal_val_it != coal_val_end_it;\n//\t\t\t\t\t ++coal_val_it)\n//\t\t\t\t{\n//\t\t\t\t\tgtpack::player_type pid(coal_val_it->first);\n//\n//\t\t\t\t\tif (coal_val_it != coal_val_beg_it)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tstd::cout << \", \";\n//\t\t\t\t\t}\n//\n//\t\t\t\t\tstd::cout << pid << \" => \" << formed_coalitions.best_partitions[i].side_payments.at(pid);\n//\t\t\t\t}\n//\t\t\t\tstd::cout << \"}\";\n//\t\t\t}\n//\t\t\tstd::cout << \"}\" << std::endl;\n\n\t\t\tstd::cout << \" * Core exists?: {\";\n\t\t\tfor (cid_iterator cid_it = cid_beg_it; cid_it != cid_end_it; ++cid_it)\n\t\t\t{\n\t\t\t\tgtpack::cid_type cid(*cid_it);\n\n\t\t\t\tif (cid_it != cid_beg_it)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t}\n\n\t\t\t\tstd::cout << std::boolalpha << !(formed_coalitions.coalitions.at(cid).core_empty);\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\n\t\t\tstd::cout << \" * Value inside the Core?: {\";\n\t\t\tfor (cid_iterator cid_it = cid_beg_it; cid_it != cid_end_it; ++cid_it)\n\t\t\t{\n\t\t\t\tgtpack::cid_type cid(*cid_it);\n\n\t\t\t\tif (cid_it != cid_beg_it)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t}\n\n\t\t\t\tstd::cout << std::boolalpha << formed_coalitions.coalitions.at(cid).payoffs_in_core;\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\n\t\t\tstd::cout << \" * Payoff increments wrt Grand-Coalition: {\";\n\t\t\tfor (cid_iterator cid_it = cid_beg_it; cid_it != cid_end_it; ++cid_it)\n\t\t\t{\n\t\t\t\t//typedef typename std::map<gtpack::player_type,RealT>::const_iterator coal_val_iterator;\n\n\t\t\t\tgtpack::cid_type cid(*cid_it);\n\n\t\t\t\tif (cid_it != cid_beg_it)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t}\n\n\t\t\t\tstd::cout << \"{\";\n\t\t\t\tcoal_val_iterator coal_val_end_it(formed_coalitions.coalitions.at(cid).payoffs.end());\n\t\t\t\tcoal_val_iterator coal_val_beg_it(formed_coalitions.coalitions.at(cid).payoffs.begin());\n\t\t\t\tfor (coal_val_iterator coal_val_it = coal_val_beg_it;\n\t\t\t\t\t coal_val_it != coal_val_end_it;\n\t\t\t\t\t ++coal_val_it)\n\t\t\t\t{\n\t\t\t\t\tgtpack::player_type pid(coal_val_it->first);\n\t\t\t\t\tRealT value(coal_val_it->second);\n\n\t\t\t\t\tif (coal_val_it != coal_val_beg_it)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t\t}\n\n\t\t\t\t\tstd::cout << pid << \" => \" << ((value/formed_coalitions.coalitions.at(gcid).payoffs.at(pid) - 1)*100.0) << \"%\";\n\t\t\t\t\tgrandpart_value += formed_coalitions.coalitions.at(gcid).payoffs.at(pid);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"}\";\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\t\t\tstd::cout << \" * Value increments wrt Grand-Coalition: \" << ((bestpart_value/grandpart_value-1)*100.0) << \"%\" << std::endl;\n\n\t\t\tstd::cout << \" * Payoff increments wrt Singleton Coalitions: {\";\n\t\t\tfor (cid_iterator cid_it = cid_beg_it; cid_it != cid_end_it; ++cid_it)\n\t\t\t{\n\t\t\t\t//typedef typename std::map<gtpack::player_type,RealT>::const_iterator coal_val_iterator;\n\n\t\t\t\tgtpack::cid_type cid(*cid_it);\n\n\t\t\t\tif (cid_it != cid_beg_it)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t}\n\n\t\t\t\tstd::cout << \"{\";\n\t\t\t\tcoal_val_iterator coal_val_end_it(formed_coalitions.coalitions.at(cid).payoffs.end());\n\t\t\t\tcoal_val_iterator coal_val_beg_it(formed_coalitions.coalitions.at(cid).payoffs.begin());\n\t\t\t\tfor (coal_val_iterator coal_val_it = coal_val_beg_it;\n\t\t\t\t\t coal_val_it != coal_val_end_it;\n\t\t\t\t\t ++coal_val_it)\n\t\t\t\t{\n\t\t\t\t\tgtpack::player_type pid(coal_val_it->first);\n\t\t\t\t\tRealT value(coal_val_it->second);\n\n\t\t\t\t\tif (coal_val_it != coal_val_beg_it)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \", \";\n\t\t\t\t\t}\n\n\t\t\t\t\tgtpack::cid_type pcid = gtpack::players_coalition<RealT>::make_id(&pid, &pid+1);\n\t\t\t\t\tstd::cout << pid << \" => \" << ((value/formed_coalitions.coalitions.at(pcid).payoffs.at(pid) - 1)*100.0) << \"%\";\n\t\t\t\t\tsinglepart_value += formed_coalitions.coalitions.at(pcid).payoffs.at(pid);\n\t\t\t\t\tsinglepart_kwatt += formed_coalitions.coalitions.at(pcid).optimal_allocation.kwatt;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"}\";\n\t\t\t}\n\t\t\tstd::cout << \"}\" << std::endl;\n\t\t\tstd::cout << \" * Value increments wrt Singleton Coalitions: \" << ((bestpart_value/singlepart_value-1)*100.0) << \"%\" << std::endl;\n\t\t\tstd::cout << \" * Energy savings wrt Singleton Coalitions: \" << ((1-bestpart_kwatt/singlepart_kwatt)*100.0) << \"%\" << std::endl;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::cout << \" * NOT AVAILABLE\" << std::endl;\n\t}\n\n\tstd::cout << \"- Grand Coalition:\" << std::endl;\n\tif (formed_coalitions.coalitions.count(gcid) > 0)\n\t{\n\t\t//typedef typename std::map<gtpack::player_type,RealT>::const_iterator coal_val_iterator;\n\t\tRealT grandpart_value(0);\n\n\t\tstd::cout << \" * Payoffs: {\";\n\t\tcoal_val_iterator coal_val_end_it(formed_coalitions.coalitions.at(gcid).payoffs.end());\n\t\tcoal_val_iterator coal_val_beg_it(formed_coalitions.coalitions.at(gcid).payoffs.begin());\n\t\tfor (coal_val_iterator coal_val_it = coal_val_beg_it;\n\t\t\t coal_val_it != coal_val_end_it;\n\t\t\t ++coal_val_it)\n\t\t{\n\t\t\tgtpack::player_type pid(coal_val_it->first);\n\t\t\tRealT value(coal_val_it->second);\n\n\t\t\tif (coal_val_it != coal_val_beg_it)\n\t\t\t{\n\t\t\t\tstd::cout << \", \";\n\t\t\t}\n\n\t\t\tstd::cout << pid << \" => \" << value;\n\t\t\tgrandpart_value += value;\n\t\t}\n\t\tstd::cout << \"}\" << std::endl;\n\n\t\tstd::cout << \" * Value: \" << grandpart_value << std::endl;\n\n\t\tstd::cout << \" * Core exists?: {\" << std::boolalpha << !(formed_coalitions.coalitions.at(gcid).core_empty) << \"}\" << std::endl;\n\n\t\tstd::cout << \" * Value inside the Core?: {\" << std::boolalpha << formed_coalitions.coalitions.at(gcid).payoffs_in_core << \"}\" << std::endl;\n\n#ifdef DCS_DEBUG\n\t\tif (formed_coalitions.coalitions.at(gcid).core_empty)\n\t\t{\n\t\t\tDCS_DEBUG_STREAM << \"FOUND Grand-Coalition with empty core\" << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDCS_DEBUG_STREAM << \"NOT FOUND Grand-Coalition with empty core\" << std::endl;\n\t\t}\n#endif // DCS_DEBUG\n\t}\n\telse\n\t{\n\t\tstd::cout << \" * NOT AVAILABLE\" << std::endl;\n\t}\n\n\tstd::cout << \"- Singleton Coalitions:\" << std::endl;\n\t{\n\t\tRealT singlepart_value(0);\n\t\tRealT singlepart_kwatt(0);\n\n\t\tstd::cout << \" * Payoffs: {\";\n\t\tfor (std::size_t c = 0; c < ncips; ++c)\n\t\t{\n\t\t\tgtpack::player_type pid(players[c]);\n\n\t\t\t// Retrieve the ID of the coalition for this player\n\t\t\tgtpack::cid_type pcid = gtpack::players_coalition<RealT>::make_id(players.begin()+c, players.begin()+c+1);\n\n\t\t\tif (c > 0)\n\t\t\t{\n\t\t\t\tstd::cout << \", \";\n\t\t\t}\n\n\t\t\tstd::cout << \"{\" << pid << \" => \" << formed_coalitions.coalitions.at(pcid).payoffs.at(pid) << \"}\";\n\t\t\tsinglepart_value += formed_coalitions.coalitions.at(pcid).payoffs.at(pid);\n\t\t\tsinglepart_kwatt += formed_coalitions.coalitions.at(pcid).optimal_allocation.kwatt;\n\t\t}\n\t\tstd::cout << \"}\" << std::endl;\n\n\t\tstd::cout << \" * Value: \" << singlepart_value << std::endl;\n\t\tstd::cout << \" * Energy Consumption: \" << singlepart_kwatt << std::endl;\n\n\t\tstd::cout << \" * Core exists?: {\";\n\t\tfor (std::size_t c = 0; c < ncips; ++c)\n\t\t{\n\t\t\tgtpack::player_type pid(players[c]);\n\n\t\t\t// Retrieve the ID of the coalition for this player\n\t\t\tgtpack::cid_type pcid = gtpack::players_coalition<RealT>::make_id(&pid, &pid+1);\n\n\t\t\tif (c > 0)\n\t\t\t{\n\t\t\t\tstd::cout << \", \";\n\t\t\t}\n\n\t\t\tstd::cout << \"{\" << std::boolalpha << !(formed_coalitions.coalitions.at(pcid).core_empty) << \"}\";\n\t\t}\n\t\tstd::cout << \"}\" << std::endl;\n\n\t\tstd::cout << \" * Value inside the Core?: {\";\n\t\tfor (std::size_t c = 0; c < ncips; ++c)\n\t\t{\n\t\t\tgtpack::player_type pid(players[c]);\n\n\t\t\t// Retrieve the ID of the coalition for this player\n\t\t\tgtpack::cid_type pcid = gtpack::players_coalition<RealT>::make_id(&pid, &pid+1);\n\n\t\t\tif (c > 0)\n\t\t\t{\n\t\t\t\tstd::cout << \", \";\n\t\t\t}\n\n\t\t\tstd::cout << \"{\" << std::boolalpha << formed_coalitions.coalitions.at(pcid).payoffs_in_core << \"}\";\n\t\t}\n\t\tstd::cout << \"}\" << std::endl;\n\t}\n}\n\ntemplate <typename RealT>\nvoid export_csv(std::string const& fname, std::size_t ncips, coalition_formation_info<RealT> formed_coalitions, bool append = false, char field_sep=',', char line_sep='\\n', char quote='\"')\n{\n\ttypedef typename std::map< gtpack::cid_type, coalition_info<RealT> >::const_iterator coalition_iterator;\n\n\tstd::ofstream ofs(fname.c_str(), append ? (std::ios_base::out | std::ios_base::app) : (std::ios_base::out | std::ios_base::out));\n\tif (!ofs)\n\t{\n\t\tthrow std::runtime_error(\"Unable to open output CSV file\");\n\t}\n\n\t// Print header or separator (i.e., an empty line)\n\tif (append)\n\t{\n\t\tfor (std::size_t p = 0; p < ncips; ++p)\n\t\t{\n\t\t\tofs << field_sep;\n\t\t}\n\t}\n\telse\n\t{\n\t\tofs << quote << \"Coalition ID\" << quote;\n\t\tfor (std::size_t p = 0; p < ncips; ++p)\n\t\t{\n\t\t\tofs << field_sep << quote << \"Payoff(CIP \" << p << \")\" << quote;\n\t\t}\n\t\tofs << field_sep << quote << \"Value(Coalition)\" << quote;\n\t}\n\tofs << line_sep;\n\n\tstd::vector<gtpack::cid_type> cids;\n\tcoalition_iterator coal_end_it(formed_coalitions.coalitions.end());\n\tfor (coalition_iterator it = formed_coalitions.coalitions.begin();\n\t\t it != coal_end_it;\n\t\t ++it)\n\t{\n\t\tcids.push_back(it->first);\n\t}\n\tstd::sort(cids.begin(), cids.end());\n\n\tstd::size_t ncids(cids.size());\n\tfor (std::size_t c = 0; c < ncids; ++c)\n\t{\n\t\tgtpack::cid_type cid(cids[c]);\n\n\t\tofs << cid;\n\n\t\t// Output coalition value\n\t\tRealT value(0);\n\t\tfor (std::size_t p = 0; p < ncips; ++p)\n\t\t{\n\t\t\tofs << field_sep;\n\t\t\tif (formed_coalitions.coalitions.at(cid).payoffs.count(static_cast<gtpack::player_type>(p)) > 0)\n\t\t\t{\n\t\t\t\tofs << formed_coalitions.coalitions.at(cid).payoffs.at(static_cast<gtpack::player_type>(p));\n\t\t\t\tvalue += formed_coalitions.coalitions.at(cid).payoffs.at(static_cast<gtpack::player_type>(p));\n\t\t\t}\n\t\t}\n\t\tofs << field_sep << value;\n\n\t\tofs << line_sep;\n\t}\n\n\tofs.close();\n}\n\ntemplate <typename RealT>\nvoid run_experiment(scenario<RealT> const& scen, options<RealT> const& opts)\n{\n\tconst std::size_t n = opts.rnd_gen_vms ? std::max(static_cast<std::size_t>(1), opts.rnd_num_iters) : 1;\n\n\tboost::random::mt19937 rng_seed(opts.rnd_seed); // RNGs for generating seeds\n\tstd::vector< std::vector<boost::random::mt19937> > rng_vms; // VMs RNGs\n\tstd::vector< std::vector<boost::random::mt19937> > rng_pm_power_states; // PM power states RNGs\n\tstd::vector< std::vector<boost::random::mt19937> > rng_pm_on_off_costs; // PM switch-on/off costs RNGs\n\tstd::vector< std::vector< std::vector<boost::random::mt19937> > > rng_vm_migration_costs; // CIP-to-CIP VM migration costs RNGs\n\n\n\tif (opts.rnd_gen_vms)\n\t{\n\t\tboost::random::mt19937 rng(rng_seed()); // RNG used to generated random seeds for VMs RNGs\n\t\trng_vms.resize(scen.num_cips);\n\t\tfor (std::size_t c = 0; c < scen.num_cips; ++c)\n\t\t{\n\t\t\trng_vms[c].resize(scen.num_vm_types);\n\t\t\tfor (std::size_t v = 0; v < scen.num_vm_types; ++v)\n\t\t\t{\n\t\t\t\trng_vms[c][v].seed(rng());\n\t\t\t}\n\t\t}\n\t}\n\tif (opts.rnd_gen_pm_power_states)\n\t{\n\t\tboost::random::mt19937 rng(rng_seed()); // RNG used to generated random seeds for PM power states RNGs\n\t\trng_pm_power_states.resize(scen.num_cips);\n\t\tfor (std::size_t c = 0; c < scen.num_cips; ++c)\n\t\t{\n\t\t\trng_pm_power_states[c].resize(scen.num_pm_types);\n\t\t\tfor (std::size_t p = 0; p < scen.num_pm_types; ++p)\n\t\t\t{\n\t\t\t\trng_pm_power_states[c][p].seed(rng());\n\t\t\t}\n\t\t}\n\t}\n\tif (opts.rnd_gen_pm_on_off_costs)\n\t{\n\t\tboost::random::mt19937 rng(rng_seed()); // RNG used to generated random seeds for PM power switch-on/off costs RNGs\n\t\trng_pm_on_off_costs.resize(scen.num_cips);\n\t\tfor (std::size_t c = 0; c < scen.num_cips; ++c)\n\t\t{\n\t\t\trng_pm_on_off_costs[c].resize(scen.num_pm_types);\n\t\t\tfor (std::size_t p = 0; p < scen.num_pm_types; ++p)\n\t\t\t{\n\t\t\t\trng_pm_on_off_costs[c][p].seed(rng());\n\t\t\t}\n\t\t}\n\t}\n\tif (opts.rnd_gen_vm_migration_costs)\n\t{\n\t\tboost::random::mt19937 rng(rng_seed()); // RNG used to generated random seeds for PM power switch-on/off costs RNGs\n\t\trng_vm_migration_costs.resize(scen.num_cips);\n\t\tfor (std::size_t c1 = 0; c1 < scen.num_cips; ++c1)\n\t\t{\n\t\t\trng_vm_migration_costs[c1].resize(scen.num_cips);\n\t\t\tfor (std::size_t c2 = 0; c2 < scen.num_cips; ++c2)\n\t\t\t{\n\t\t\t\trng_vm_migration_costs[c1][c2].resize(scen.num_vm_types);\n\t\t\t\tfor (std::size_t v = 0; v < scen.num_vm_types; ++v)\n\t\t\t\t{\n\t\t\t\t\trng_vm_migration_costs[c1][c2][v].seed(rng());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (std::size_t i = 1; i <= n; ++i)\n\t{\n\t\tstd::cout << \"Iteration #\" << i << std::endl;\n\n\t\tscenario<RealT> wrk_scen = scen;\n\n\t\tif (opts.rnd_gen_vms)\n\t\t{\n\t\t\tfor (std::size_t c = 0; c < scen.num_cips; ++c)\n\t\t\t{\n\t\t\t\tfor (std::size_t v = 0; v < scen.num_vm_types; ++v)\n\t\t\t\t{\n\t\t\t\t\tboost::random::uniform_int_distribution<std::size_t> rvg(0, scen.cip_num_vms[c][v]);\n\t\t\t\t\twrk_scen.cip_num_vms[c][v] = std::max(rvg(rng_vms[c][v]), 0UL);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (opts.rnd_gen_pm_power_states)\n\t\t{\n\t\t\twrk_scen.cip_pm_power_states.resize(scen.num_cips);\n\t\t\tfor (std::size_t c = 0; c < scen.num_cips; ++c)\n\t\t\t{\n\t\t\t\tfor (std::size_t p = 0; p < scen.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tfor (std::size_t k = 0; k < wrk_scen.cip_num_pms[c][p]; ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tboost::random::bernoulli_distribution<float> rvg(0.5);\n\t\t\t\t\t\twrk_scen.cip_pm_power_states[c].push_back(rvg(rng_pm_power_states[c][p]));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (opts.rnd_gen_pm_on_off_costs)\n\t\t{\n\t\t\t// We assume the switch-on/off time is randomly distributed as a\n\t\t\t// Normal(300,50) microsec.\n\t\t\t// Such values are taken from [1].\n\t\t\t// Furthermore, we assume the switch-on cost is equal to the\n\t\t\t// switch-off cost and that is independent by the PM type.\n\t\t\t// Thus:\n\t\t\t// - PM switch-on costs:\n\t\t\t//     <max power consumption>*<Average time taken to perform a sleep-state to active-state transition>*<Electricity cost>\n\t\t\t//\n\t\t\t// - PM switch-off costs:\n\t\t\t//     <max power consumption>*<Average time taken to perform a active-state to sleep-state transition>*<Electricity cost>\n\t\t\t//\n\t\t\t// References:\n\t\t\t// 1. D. Meisner, B. Gold and T. Wenisch.\n\t\t\t//    \"PowerNap: Eliminating Server Idle Power,\"\n\t\t\t//    Proc. of the 14th ASPLOS, pp.205-216, 2009.\n\n\t\t\tconst RealT norm = 3600; // normalization constant (secs in a hour)\n\t\t\tconst RealT mu = 3e-4/norm; // Mean switch-on/off time: 300 microsec\n\t\t\tconst RealT sigma = 5e-5/norm; // S.D. switch-on/off time: 50 microsec\n\n\t\t\twrk_scen.cip_pm_asleep_costs.resize(scen.num_cips);\n\t\t\twrk_scen.cip_pm_awake_costs.resize(scen.num_cips);\n\t\t\tfor (std::size_t c = 0; c < scen.num_cips; ++c)\n\t\t\t{\n\t\t\t\twrk_scen.cip_pm_asleep_costs[c].resize(scen.num_pm_types);\n\t\t\t\twrk_scen.cip_pm_awake_costs[c].resize(scen.num_pm_types);\n\t\t\t\tfor (std::size_t p = 0; p < scen.num_pm_types; ++p)\n\t\t\t\t{\n\t\t\t\t\tconst RealT transition_cost_rate = scen.pm_spec_max_powers[p]*1e-3*scen.cip_electricity_costs[c]; // Transition cost in $/h\n\n\t\t\t\t\tboost::random::normal_distribution<RealT> rvg(mu, sigma);\n\t\t\t\t\twrk_scen.cip_pm_asleep_costs[c][p] = wrk_scen.cip_pm_awake_costs[c][p]\n\t\t\t\t\t\t\t\t\t\t\t\t\t   = std::max(rvg(rng_pm_on_off_costs[c][p])*transition_cost_rate, 0.0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (opts.rnd_gen_vm_migration_costs)\n\t\t{\n\t\t\t// The cost for migrating a class-k VM from CIP1 to CIP2 is given by:\n\t\t\t//\n\t\t\t//   <data transfer cost rate>*<data size to transfer>/<activation time>\n\t\t\t//\n\t\t\t// where:\n\t\t\t// - <data transfer cost rate>: is taken from Amazon EC2 data\n\t\t\t//   transfer pricing [3] and set to 0.001 $/GB.\n\t\t\t// - <data size to transfer>: we assume that data are\n\t\t\t//   persistently transferred during the migration time at a fixed\n\t\t\t//   data rate of 100Mbps.\n\t\t\t//   Thus, if we continuously trasmit for T seconds over a 100Mbps\n\t\t\t//   network, we are trasmitting 0.1*T Gbps (i.e., 0.1*T/8 GB/s) and\n\t\t\t//   thus we'll pay 0.1*T*0.001/8 $.\n\t\t\t//   The migration time is randomly generated according as follows:\n\t\t\t//   * The migration time between two PMs of the same CIP is zero.\n\t\t\t//   * For the smaller VM class, the migration time is randomly\n\t\t\t//     generated according to a Normal(277 sec, 182 sec) probability\n\t\t\t//     distribution, as found in [2].\n\t\t\t//   * For larger VM classes, we use the same methodology used for\n\t\t\t//     for the smaller VM class, but doubling the values of the\n\t\t\t//     parameters values.\n\t\t\t//   Thus:\n\t\t\t//   * Migration time for VM small: Normal(277 sec, 182 sec).\n\t\t\t//   * Migration time for VM medium: Normal(554, 364 sec)\n\t\t\t//   * Migration time for VM large: Normal(1108 sec, 728 sec).\n\t\t\t//   * ...\n\t\t\t// - <activation time>: we assume that our algorithm activates every\n\t\t\t//   12 hours.\n\t\t\t//\n\t\t\t// Finally, since we're expressing the time in hours, time and data\n\t\t\t// rate values must be suitably normalized to hours\n\t\t\t// (i.e., t sec -> tn = t/3600 hour, and\n\t\t\t// d bit/sec -> dn = d*3600 bit/hour).\n\t\t\t//\n\t\t\t// References:\n\t\t\t// 2. S. Akoush, R. Sohan, A. Rice, A.W. Moore and Andy Hopper.\n\t\t\t//    \"Predicting the Performance of Virtual Machine Migration,\"\n\t\t\t//    In Proc. of the 2010 IEEE MASCOTS, pp. 37-46, 2010.\n\t\t\t// 3. Amazon EC2.\n\t\t\t//    \"Amazon EC2 Data Transfer Pricing,\"\n\t\t\t//    2013, Online: https://aws.amazon.com/ec2/pricing/#DataTransfer\n\n\t\t\tconst RealT norm = 3600; // normalization constant (secs in a hour)\n\t\t\tconst RealT mu = 277/norm; // Mean migration time: 277 sec\n\t\t\tconst RealT sigma = 61/norm; // S.D. migration time: 182 sec\n\t\t\tconst RealT data_transfer_cost = 1e-5; // Data transfer cost per MB: 0.00001 $/MB\n\t\t\tconst RealT activation_time = 12; // The algorithm activates every 12 hours\n\t\t\tconst RealT data_rate = 12.5*norm; // Data rate: 12.5 MB/sec (100 Mbps)\n\t\t\tconst RealT transfer_cost_rate = data_transfer_cost*data_rate/activation_time; // Transfer cost rate in $/hour\n\n\t\t\twrk_scen.cip_to_cip_vm_migration_costs.resize(scen.num_cips);\n\t\t\tfor (std::size_t c1 = 0; c1 < scen.num_cips; ++c1)\n\t\t\t{\n\t\t\t\twrk_scen.cip_to_cip_vm_migration_costs[c1].resize(scen.num_cips);\n\t\t\t\tfor (std::size_t c2 = 0; c2 < scen.num_cips; ++c2)\n\t\t\t\t{\n\t\t\t\t\tif (c1 != c2)\n\t\t\t\t\t{\n\t\t\t\t\t\tRealT mu2 = mu;\n\t\t\t\t\t\tRealT sigma2 = sigma;\n\n\t\t\t\t\t\t// We assume that VM types are ordered by increasing \"size\", that\n\t\t\t\t\t\t//  VMtype_1 is smaller than VMtype_2 is smaller than VMtype_3 ...\n\t\t\n\t\t\t\t\t\twrk_scen.cip_to_cip_vm_migration_costs[c1][c2].resize(scen.num_vm_types);\n\t\t\t\t\t\tfor (std::size_t v = 0; v < scen.num_vm_types; ++v)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tboost::random::normal_distribution<RealT> rvg(mu2, sigma2);\n\t\t\t\t\t\t\twrk_scen.cip_to_cip_vm_migration_costs[c1][c2][v] = std::max(rvg(rng_vm_migration_costs[c1][c2][v])*transfer_cost_rate, 0.0);\n\n\t\t\t\t\t\t\tmu2 *= 2;\n\t\t\t\t\t\t\tsigma2 *= 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\twrk_scen.cip_to_cip_vm_migration_costs[c1][c2].assign(scen.num_vm_types, 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstd::cout << \"Scenario: \" << wrk_scen << std::endl;\n\t\tstd::cout << \"Options: \" << opts << std::endl;\n\n\t\tstd::cout << \"Analyzing coalitions...\" << std::endl;\n\n\t\tdetail::experiment::coalition_formation_info<RealT> formed_coalitions;\n\t\tformed_coalitions = detail::experiment::analyze_coalitions<RealT>(wrk_scen, opts);\n\n\t\tdetail::experiment::report(wrk_scen.num_cips, formed_coalitions);\n\n\t\tif (!opts.csv_fname.empty())\n\t\t{\n\t\t\tdetail::experiment::export_csv(opts.csv_fname, wrk_scen.num_cips, formed_coalitions, i > 1);\n\t\t}\n\t}\n\n\tstd::cout << \"DONE!\" << std::endl;\n}\n\n}}} // Namespace detail::experiment::<unnamed>\n\n\nnamespace detail { namespace /*<unnamed>*/ {\n\nvoid usage(char const* progname)\n{\n\tstd::cerr << \"Usage: \" << progname << \" {options}\" << std::endl\n\t\t\t  << \"Options:\" << std::endl\n\t\t\t  << \" --csv <file>\" << std::endl\n\t\t\t  << \"   Export all the analyzed coalition onto a CSV file.\" << std::endl \n\t\t\t  << \" --formation {'merge-split'|'nash'|'pareto'|'social'}\" << std::endl\n\t\t\t  << \"   The coalition formation strategy. Can be one of the following:\" << std::endl \n\t\t\t  << \"   - 'merge-split': to form Merge/split-stable partitions\" << std::endl\n\t\t\t  << \"   - 'nash': to form Nash-stable partitions\" << std::endl\n\t\t\t  << \"   - 'pareto': to form Pareto-optimal partitions\" << std::endl\n\t\t\t  << \"   - 'social': to form social-optimum partitions\" << std::endl\n\t\t\t  << \" --help\" << std::endl\n\t\t\t  << \"   Show this message.\" << std::endl\n\t\t\t  << \" --opt-relgap <num>\" << std::endl\n\t\t\t  << \"   A real number in [0,1] used to set the relative gap parameter of the optimal solver.\" << std::endl\n\t\t\t  << \" --opt-tilim <num>\" << std::endl\n\t\t\t  << \"   A real positive number used to set the maximum number of seconds to wait for the termination of the optimal solver.\" << std::endl\n\t\t\t  << \" --payoff {'banzhaf'|'norm-banzhaf'|'shapley'}\" << std::endl\n\t\t\t  << \"   The coalition value division strategy. Can be one of the following:\" << std::endl \n\t\t\t  << \"   - 'banzhaf': the Banzhaf value\" << std::endl \n\t\t\t  << \"   - 'norm-banzhaf': the normalized Banzhaf value\" << std::endl \n\t\t\t  << \"   - 'shapley': the Shapley value\" << std::endl \n\t\t\t  << \" --rnd-genvms\" << std::endl\n\t\t\t  << \"    Enable the random generation of VMs for each CIP.\" << std::endl\n\t\t\t  << \" --rnd-genpmsonoff\" << std::endl\n\t\t\t  << \"    Enable the random generation of PM power states for each CIP.\" << std::endl\n\t\t\t  << \" --rnd-genpmsonoffcosts\" << std::endl\n\t\t\t  << \"    Enable the random generation of switch-on/off costs of PMs for each CIP and PM type.\" << std::endl\n\t\t\t  << \" --rnd-genvmsmigrcosts\" << std::endl\n\t\t\t  << \"    Enable the random generation of CIP-to-CIP migration costs of VMs for each CIP and VM type.\" << std::endl\n\t\t\t  << \" --rnd-numit <number>\" << std::endl\n\t\t\t  << \"   Set the number of times that the given scenario must be run.\" << std::endl\n\t\t\t  << \"   Each run will use a randomly generated number of VMs and PM power states.\" << std::endl \n\t\t\t  << \" --rnd-seed <number>\" << std::endl\n\t\t\t  << \"   Set the seed to use for random number generation.\" << std::endl\n\t\t\t  << \" --scenario <file-name>\" << std::endl\n\t\t\t  << \"   The path to the file describing the scenario to use for the experiment.\" << std::endl;\n}\n\n}} // Namespace detail::<unnamed>\n\n\nint main(int argc, char* argv[])\n{\n\ttypedef double real_type;\n\n\tif (argc < 2)\n\t{\n\t\tdetail::usage(argv[0]);\n\t\treturn -1;\n\t}\n\n\tstd::string opt_csv_fname;\n\tbool opt_help;\n\treal_type opt_relative_gap;\n\treal_type opt_time_lim;\n\tstd::string opt_scenario_file;\n\tdetail::experiment::coalition_formation_category opt_coalition_formation;\n\tdetail::experiment::coalition_value_division_category opt_coalition_value_division;\n\tbool opt_rnd_gen_vms;\n\tbool opt_rnd_gen_pm_power_states;\n\tbool opt_rnd_gen_pm_on_off_costs;\n\tbool opt_rnd_gen_vm_migration_costs;\n\tstd::size_t opt_rnd_num_iters;\n\tunsigned long opt_rnd_seed;\n\tstd::string opt_str;\n\n\t// Parse CLI options\n\topt_csv_fname = cli::simple::get_option<std::string>(argv, argv+argc, \"--csv\", \"\");\n\topt_help = cli::simple::get_option(argv, argv+argc, \"--help\");\n\tif (opt_help)\n\t{\n\t\tdetail::usage(argv[0]);\n\t\treturn 0;\n\t}\n\topt_str = cli::simple::get_option<std::string>(argv, argv+argc, \"--formation\", \"nash\");\n\tif (opt_str == \"nash\")\n\t{\n\t\topt_coalition_formation = detail::experiment::nash_stable_coalition_formation;\n\t}\n\telse if (opt_str == \"merge-split\")\n\t{\n\t\topt_coalition_formation = detail::experiment::merge_split_stable_coalition_formation;\n\t}\n\telse if (opt_str == \"pareto\")\n\t{\n\t\topt_coalition_formation = detail::experiment::pareto_optimal_coalition_formation;\n\t}\n\telse if (opt_str == \"social\")\n\t{\n\t\topt_coalition_formation = detail::experiment::social_optimum_coalition_formation;\n\t}\n\telse\n\t{\n\t\tthrow std::invalid_argument(\"Unknown coalition formation category\");\n\t}\n\topt_str = cli::simple::get_option<std::string>(argv, argv+argc, \"--payoff\", \"shapley\");\n\tif (opt_str == \"banzhaf\")\n\t{\n\t\topt_coalition_value_division = detail::experiment::banzhaf_coalition_value_division;\n\t}\n\telse if (opt_str == \"norm-banzhaf\")\n\t{\n\t\topt_coalition_value_division = detail::experiment::normalized_banzhaf_coalition_value_division;\n\t}\n\telse if (opt_str == \"shapley\")\n\t{\n\t\topt_coalition_value_division = detail::experiment::shapley_coalition_value_division;\n\t}\n\telse\n\t{\n\t\tthrow std::invalid_argument(\"Unknown coalition value division category\");\n\t}\n\topt_relative_gap = cli::simple::get_option<real_type>(argv, argv+argc, \"--opt-relgap\", 0);\n\topt_time_lim = cli::simple::get_option<real_type>(argv, argv+argc, \"--opt-tilim\", -1);\n\topt_rnd_gen_vms = cli::simple::get_option(argv, argv+argc, \"--rnd-genvms\");\n\topt_rnd_gen_pm_power_states = cli::simple::get_option(argv, argv+argc, \"--rnd-genpmsonoff\");\n\topt_rnd_gen_pm_on_off_costs = cli::simple::get_option(argv, argv+argc, \"--rnd-genpmsonoffcosts\");\n\topt_rnd_gen_vm_migration_costs = cli::simple::get_option(argv, argv+argc, \"--rnd-genvmsmigrcosts\");\n\topt_rnd_num_iters = cli::simple::get_option<std::size_t>(argv, argv+argc, \"--rnd-numit\", 1);\n\topt_rnd_seed = cli::simple::get_option<unsigned long>(argv, argv+argc, \"--rnd-seed\", 5489);\n\topt_scenario_file = cli::simple::get_option<std::string>(argv, argv+argc, \"--scenario\");\n\n\t// Check CLI options\n\tif (opt_scenario_file.empty())\n\t{\n\t\tstd::cerr << \"(E) Scenario file not specified\" << std::endl;\n\t\tdetail::usage(argv[0]);\n\t\treturn -1;\n\t}\n\n\t// Run Experiment\n\tdetail::experiment::options<real_type> opts;\n\tdetail::experiment::scenario<real_type> scenario;\n\n\tscenario = detail::experiment::make_scenario<real_type>(opt_scenario_file);\n\topts.opt_relative_gap = opt_relative_gap;\n\topts.opt_time_lim = opt_time_lim;\n\topts.coalition_formation = opt_coalition_formation;\n\topts.coalition_value_division = opt_coalition_value_division;\n\topts.rnd_gen_vms = opt_rnd_gen_vms;\n\topts.rnd_gen_pm_power_states = opt_rnd_gen_pm_power_states;\n\topts.rnd_gen_pm_on_off_costs = opt_rnd_gen_pm_on_off_costs;\n\topts.rnd_gen_vm_migration_costs = opt_rnd_gen_vm_migration_costs;\n\topts.rnd_num_iters = opt_rnd_num_iters;\n\topts.rnd_seed = opt_rnd_seed;\n\topts.csv_fname = opt_csv_fname;\n\n\tdetail::experiment::run_experiment<real_type>(scenario, opts);\n}\n", "meta": {"hexsha": "399407f945d0b7557f353a3440239e2aa1858d5a", "size": 110879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sim.cpp", "max_stars_repo_name": "sguazt/dcsxx-cloud-gt", "max_stars_repo_head_hexsha": "3051aa2c57bc46b9f5b6a160fea87b56cd1a6374", "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/sim.cpp", "max_issues_repo_name": "sguazt/dcsxx-cloud-gt", "max_issues_repo_head_hexsha": "3051aa2c57bc46b9f5b6a160fea87b56cd1a6374", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sim.cpp", "max_forks_repo_name": "sguazt/dcsxx-cloud-gt", "max_forks_repo_head_hexsha": "3051aa2c57bc46b9f5b6a160fea87b56cd1a6374", "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.5158357771, "max_line_length": 386, "alphanum_fraction": 0.6465516464, "num_tokens": 34336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.036769469769929175, "lm_q1q2_score": 0.01752358107274923}}
{"text": "#include <algorithm>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n#include \"DOFMatrix.hpp\"\n#include \"QPsiPhi.hpp\"\n#include \"BasisFunction.hpp\"\n#include \"Boundary.hpp\"\n#include \"DOFAdmin.hpp\"\n#include \"ElInfo.hpp\"\n#include \"FiniteElemSpace.hpp\"\n#include \"Mesh.hpp\"\n#include \"DOFVector.hpp\"\n#include \"Operator.hpp\"\n#include \"BoundaryCondition.hpp\"\n#include \"BoundaryManager.hpp\"\n#include \"Assembler.hpp\"\n\nnamespace AMDiS\n{\n  using namespace mtl;\n\n  DOFMatrix::DOFMatrix()\n    : rowFeSpace(NULL),\n      colFeSpace(NULL),\n      elementMatrix(3, 3),\n      nRow(0),\n      nCol(0),\n      nnzPerRow(0),\n      inserter(NULL)\n  {}\n\n\n  DOFMatrix::DOFMatrix(const FiniteElemSpace* rowSpace,\n                       const FiniteElemSpace* colSpace,\n                       std::string n)\n    : rowFeSpace(rowSpace),\n      colFeSpace(colSpace),\n      name(n),\n      coupleMatrix(false),\n      nnzPerRow(0),\n      inserter(NULL)\n  {\n    FUNCNAME(\"DOFMatrix::DOFMatrix()\");\n\n    TEST_EXIT(rowFeSpace)(\"No fe space for row!\\n\");\n\n    if (!colFeSpace)\n      colFeSpace = rowFeSpace;\n    boundaryManager = new BoundaryManager(rowFeSpace);\n\n    nRow = rowFeSpace->getBasisFcts()->getNumber();\n    nCol = colFeSpace->getBasisFcts()->getNumber();\n    elementMatrix.change_dim(nRow, nCol);\n    rowIndices.resize(nRow);\n    colIndices.resize(nCol);\n  }\n\n\n  DOFMatrix::DOFMatrix(const DOFMatrix& rhs)\n    : name(rhs.name + \"copy\")\n  {\n    FUNCNAME(\"DOFMatrix::DOFMatrix()\");\n\n    *this = rhs;\n    TEST_EXIT(rhs.inserter == 0)(\"Cannot copy during insertion!\\n\");\n    inserter = 0;\n  }\n\n\n  DOFMatrix::~DOFMatrix()\n  {\n    if (boundaryManager)\n      delete boundaryManager;\n    if (inserter)\n      delete inserter;\n  }\n\n\n  void DOFMatrix::print() const\n  {\n    if (inserter)\n      inserter->print();\n  }\n\n  int DOFMatrix::getUsedSize() const\n  {\n    return rowFeSpace->getAdmin()->getUsedSize();\n  }\n\n  DOFMatrix& DOFMatrix::operator=(const DOFMatrix& rhs)\n  {\n    rowFeSpace = rhs.rowFeSpace;\n    colFeSpace = rhs.colFeSpace;\n    operators = rhs.operators;\n    operatorFactor = rhs.operatorFactor;\n    coupleMatrix = rhs.coupleMatrix;\n\n    /// The matrix values may only be copyed, if there is no active insertion.\n    if (rhs.inserter == 0 && inserter == 0)\n      matrix = rhs.matrix;\n\n    if (rhs.boundaryManager)\n      boundaryManager = new BoundaryManager(*rhs.boundaryManager);\n    else\n      boundaryManager = NULL;\n\n    nRow = rhs.nRow;\n    nCol = rhs.nCol;\n    elementMatrix.change_dim(nRow, nCol);\n\n    return *this;\n  }\n\n\n  void DOFMatrix::addElementMatrix(const ElementMatrix& elMat,\n                                   const BoundaryType* bound,\n                                   ElInfo* rowElInfo,\n                                   ElInfo* colElInfo)\n  {\n    FUNCNAME_DBG(\"DOFMatrix::addElementMatrix()\");\n\n    TEST_EXIT_DBG(inserter)(\"DOFMatrix is not in insertion mode\\n\");\n    TEST_EXIT_DBG(rowFeSpace)(\"Have now rowFeSpace!\\n\");\n\n    inserter_type& ins= *inserter;\n\n    // === Get indices mapping from local to global matrix indices. ===\n\n    rowFeSpace->getBasisFcts()->getLocalIndices(rowElInfo->getElement(),\n        rowFeSpace->getAdmin(),\n        rowIndices);\n    if (rowFeSpace == colFeSpace)\n    {\n      colIndices = rowIndices;\n    }\n    else\n    {\n      if (colElInfo)\n      {\n        colFeSpace->getBasisFcts()->getLocalIndices(colElInfo->getElement(),\n            colFeSpace->getAdmin(),\n            colIndices);\n      }\n      else\n      {\n        // If there is no colElInfo pointer, use rowElInfo the get the indices.\n        colFeSpace->getBasisFcts()->getLocalIndices(rowElInfo->getElement(),\n            colFeSpace->getAdmin(),\n            colIndices);\n      }\n    }\n\n    for (int i = 0; i < nRow; i++)\n    {\n      DegreeOfFreedom row = rowIndices[i];\n\n      BoundaryCondition* condition =\n        bound ? boundaryManager->getBoundaryCondition(bound[i]) : NULL;\n\n      if (condition && condition->isDirichlet())\n      {\n        if (condition->applyBoundaryCondition())\n          dirichletDofs.insert(row);\n      }\n      else\n      {\n        for (int j = 0; j < nCol; j++)\n        {\n          DegreeOfFreedom col = colIndices[j];\n          ins[row][col] += elMat[i][j];\n        }\n      }\n    }\n  }\n\n\n  void DOFMatrix::assembleOperator(Operator& op)\n  {\n    FUNCNAME(\"DOFMatrix::assembleOperator()\");\n\n    TEST_EXIT(rowFeSpace->getMesh() == colFeSpace->getMesh())\n    (\"This function does not support for multi mesh procedure!\\n\");\n    TEST_EXIT(op.getRowFeSpace() == rowFeSpace)\n    (\"Row FE spaces do not fit together!\\n\");\n    TEST_EXIT(op.getColFeSpace() == colFeSpace)\n    (\"Column FE spaces do not fit together!\\n\");\n\n    clearOperators();\n    addOperator(&op);\n\n    matrix.change_dim(rowFeSpace->getAdmin()->getUsedSize(),\n                      colFeSpace->getAdmin()->getUsedSize());\n\n    Mesh* mesh = rowFeSpace->getMesh();\n    mesh->dofCompress();\n    const BasisFunction* basisFcts = rowFeSpace->getBasisFcts();\n\n    Flag assembleFlag = getAssembleFlag() |\n                        Mesh::CALL_LEAF_EL                        |\n                        Mesh::FILL_COORDS                         |\n                        Mesh::FILL_DET                            |\n                        Mesh::FILL_GRD_LAMBDA |\n                        Mesh::FILL_NEIGH |\n                        Mesh::FILL_BOUND;\n\n    BoundaryType* bound = new BoundaryType[basisFcts->getNumber()];\n\n    calculateNnz();\n    if (getBoundaryManager())\n      getBoundaryManager()->initMatrix(this);\n\n    startInsertion(getNnz());\n\n    TraverseStack stack;\n    ElInfo* elInfo = stack.traverseFirst(mesh, -1, assembleFlag);\n    while (elInfo)\n    {\n      basisFcts->getBound(elInfo, bound);\n\n      assemble(1.0, elInfo, bound);\n\n      if (getBoundaryManager())\n        getBoundaryManager()->fillBoundaryConditions(elInfo, this);\n\n      elInfo = stack.traverseNext(elInfo);\n    }\n\n    clearDirichletRows();\n    finishAssembling();\n    finishInsertion();\n    getBoundaryManager()->exitMatrix(this);\n\n    delete [] bound;\n  }\n\n\n  void DOFMatrix::assemble(double factor,\n                           ElInfo* elInfo,\n                           const BoundaryType* bound)\n  {\n    set_to_zero(elementMatrix);\n\n    std::vector<Operator*>::iterator it = operators.begin();\n    std::vector<double*>::iterator factorIt = operatorFactor.begin();\n    for (; it != operators.end(); ++it, ++factorIt)\n      if ((*it)->getNeedDualTraverse() == false &&\n          (*factorIt == NULL ||** factorIt != 0.0))\n        (*it)->getElementMatrix(elInfo,\telementMatrix, *factorIt ? **factorIt : 1.0);\n\n    if (factor != 1.0)\n      elementMatrix *= factor;\n\n    if (operators.size())\n      addElementMatrix(elementMatrix, bound, elInfo, NULL);\n  }\n\n\n  void DOFMatrix::assemble(double factor,\n                           ElInfo* elInfo,\n                           const BoundaryType* bound,\n                           Operator* op)\n  {\n    FUNCNAME_DBG(\"DOFMatrix::assemble()\");\n\n    TEST_EXIT_DBG(op)(\"No operator!\\n\");\n\n    set_to_zero(elementMatrix);\n    op->getElementMatrix(elInfo, elementMatrix, factor);\n\n    if (factor != 1.0)\n      elementMatrix *= factor;\n\n    addElementMatrix(elementMatrix, bound, elInfo, NULL);\n  }\n\n\n  void DOFMatrix::finishAssembling()\n  {\n    // call the operators cleanup procedures\n    for (std::vector<Operator*>::iterator it = operators.begin();\n         it != operators.end(); ++it)\n      (*it)->finishAssembling();\n  }\n\n\n  // Should work as before\n  Flag DOFMatrix::getAssembleFlag()\n  {\n    Flag fillFlag(0);\n    for (std::vector<Operator*>::iterator op = operators.begin();\n         op != operators.end(); ++op)\n      fillFlag |= (*op)->getFillFlag();\n\n    return fillFlag;\n  }\n\n\n  void DOFMatrix::addOperator(Operator* op, double* factor, double* estFactor)\n  {\n    operators.push_back(op);\n    operatorFactor.push_back(factor);\n    operatorEstFactor.push_back(estFactor);\n  }\n\n\n  void DOFMatrix::clearOperators()\n  {\n    operators.clear();\n    operatorFactor.clear();\n    operatorEstFactor.clear();\n  }\n\n\n  void DOFMatrix::copy(const DOFMatrix& rhs)\n  {\n    matrix = rhs.matrix;\n  }\n\n\n  void DOFMatrix::clearDirichletRows()\n  {\n    // Do the following only in sequential code. In parallel mode, the specific\n    // solver method must care about dirichlet boundary conditions.\n    inserter_type& ins = *inserter;\n    for (std::set<DegreeOfFreedom>::iterator it = dirichletDofs.begin();\n         it != dirichletDofs.end(); ++it)\n      ins[(*it)][(*it)] = 1.0;\n  }\n\n\n  size_t DOFMatrix::memsize() const\n  {\n    return (num_rows(matrix) + matrix.nnz()) * sizeof(base_matrix_type::size_type)\n           + matrix.nnz() * sizeof(base_matrix_type::value_type);\n  }\n\n\n  void DOFMatrix::startInsertion(int nnz_per_row)\n  {\n    if (inserter)\n    {\n      delete inserter;\n      inserter = NULL;\n    }\n\n    inserter = new inserter_type(matrix, nnz_per_row);\n\n    dirichletDofs.clear();\n  }\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "2f1c6e21a397b08326184d43e7c9bde2e83669c7", "size": 8882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DOFMatrix.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/DOFMatrix.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/DOFMatrix.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": 25.1614730878, "max_line_length": 85, "alphanum_fraction": 0.6053816708, "num_tokens": 2238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.041462273747793106, "lm_q1q2_score": 0.017518003431371523}}
{"text": "/**\n * Copyright (c) 2020, Román Cárdenas Rodríguez\n * ARSLab - Carleton University\n * GreenLSI - Polytechnic University of Madrid\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 notice,\n * this 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\"\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 CADMIUM_CELLDEVS_GRID_UTILS_HPP\n#define CADMIUM_CELLDEVS_GRID_UTILS_HPP\n\n#include <utility>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <utility>\n#include <cassert>\n#include <exception>\n#include <cmath>\n#include <boost/functional/hash.hpp>\n#include <cadmium/celldevs/utils/utils.hpp>\n\n\nnamespace cadmium::celldevs {\n\n    using cell_position = std::vector<int>;  /// Alias to refer to a cell.\n\n    /**\n     * Alias to refer to an unordered map with cell positions as keys.\n     * @tparam X type of the values stored in the unordered map.\n     */\n    template<typename X>\n    using cell_unordered = std::unordered_map<cell_position, X>;\n\n    /**\n     * Cell configuration structure.\n     * @tparam S type used to represent cell states.\n     * @tparam V type used to represent vicinities between cells.\n     */\n    template <typename S, typename V>\n    using grid_cell_config = cell_config<cell_position, S, V>;\n\n    /**\n     * Auxiliary class with useful functions for grid cells.\n     * @tparam S type used to represent cell states.\n     * @tparam V type used to represent vicinities between cells.\n     */\n    template<typename S, typename V=int>\n    class cell_map {\n    public:\n        cell_position shape;                /// Shape of the scenario\n        cell_position location;             /// Location of the cell\n        S state;                            /// Initial state of the cell\n        cell_unordered<V> neighborhood;     /// Indicates the vicinities type of neighbor cells\n        bool wrapped;                       /// It indicates whether the scenario is wrapped or not\n\n        cell_map() { throw std::exception(); }\n\n        cell_map(cell_position shape, cell_position location, S const &state, cell_unordered<V> const &neighborhood, bool wrapped);\n\n        [[maybe_unused]] [[nodiscard]] int manhattan_distance(cell_position const &a) const;\n\n        [[maybe_unused]] [[nodiscard]] int chebyshev_distance(cell_position const &a) const;\n\n        [[maybe_unused]] [[nodiscard]] double n_norm_distance(cell_position const &a, unsigned int n) const;\n\n        [[maybe_unused]] [[nodiscard]] double euclidean_distance(cell_position const &a) const;\n\n        [[maybe_unused]] [[nodiscard]] cell_position neighbor(cell_position const &relative) const;\n\n        [[maybe_unused]] [[nodiscard]] cell_position relative(cell_position const &neighbor) const;\n    };\n\n\n    /**\n     * Class used by grid_coupled to set the scenario.\n     * @tparam S type used to represent cell states.\n     * @tparam V type used to represent vicinities between cells.\n     */\n    template<typename S, typename V>\n    class grid_scenario {\n    public:\n        cell_position shape;                             /// Shape of the scenario.\n        unsigned int dimension;                          /// Dimension of the grid of the scenario.\n        cell_unordered<grid_cell_config<S, V>> configs;  /// Configuration of cells in the grid.\n        bool wrapped;                                    /// It indicates whether the scenario is wrapped or not.\n\n        void set_initial_config(const grid_cell_config<S, V> &config) {\n            configs = cell_unordered<grid_cell_config<S, V>>();\n            cell_position current = cell_position();\n            for (int i = 0; i < dimension; i++)\n                current.push_back(0);\n            while (true) {\n                try {\n                    set_initial_config(current, config);\n                    current = next_cell(current, 0);\n                } catch (std::overflow_error &e) {\n                    break;\n                }\n            }\n        }\n\n        void set_initial_config(const cell_position &cell, const grid_cell_config<S, V> config) {\n            assert(cell_in_scenario(cell));\n            configs[cell] = config;\n        }\n\n        grid_scenario(const cell_position &shape, const grid_cell_config<S, V> &config, bool wrapped):\n        shape(shape), dimension(shape.size()), configs(), wrapped(wrapped) {\n            // Assert that the shape of the scenario is well-defined\n            set_initial_config(config);\n            for (auto const &d: shape)\n                assert(d > 0);\n            for (auto const &cell: configs) {\n                assert(cell.first.size() == dimension);\n            }\n        }\n\n        /***************************************************/\n        /***************** STATIC METHODS ******************/\n        /***************************************************/\n\n        /*************** distance functions ****************/\n        // Auxiliary function for obtaining the distance vector between two cell\n        static cell_position distance_vector(const cell_position &origin, const cell_position &destination,\n                                             const cell_position &shape, bool wrapped) {\n            assert(cell_in_scenario(origin, shape) && cell_in_scenario(destination, shape));\n            cell_position res = cell_position();\n            for (int i = 0; i < origin.size(); i++) {\n                auto diff = destination[i] - origin[i];\n                if (wrapped && std::abs(diff) > shape[i] / 2)\n                    diff = (diff < 0) ? diff + shape[i] : diff - shape[i];\n                res.push_back(diff);\n            }\n            return res;\n        }\n\n        // Auxiliary function for obtaining the destination cell from the origin cell and the distance vector\n        static cell_position destination_cell(const cell_position &origin, const cell_position &distance,\n                                              const cell_position &shape, bool wrapped) {\n            assert(cell_in_scenario(origin, shape) && distance.size() == shape.size());\n            for (int i = 0; i < shape.size(); i++)\n                assert(std::abs(distance[i]) < shape[i]);\n            cell_position res = cell_position();\n            for (int i = 0; i < origin.size(); i++) {\n                auto dest = origin[i] + distance[i];\n                if (wrapped)\n                    dest = (dest + shape[i]) % shape[i];\n                res.push_back(dest);\n            }\n            if (!cell_in_scenario(res, shape))\n                throw std::overflow_error(\"Destination cell is not in scenario\");\n            return res;\n        }\n\n        // Auxiliary function for obtaining the Manhattan distance between two cell of the grid\n        [[maybe_unused]] static int manhattan_distance(const cell_position &a, const cell_position &b,\n                                                       const cell_position &shape, bool wrapped) {\n            int res = 0;\n            for (auto const &d: distance_vector(a, b, shape, wrapped))\n                res += std::abs(d);\n            return res;\n        }\n\n        // Auxiliary function for obtaining the Chebyshev distance between two cell of the grid\n        [[maybe_unused]] static int chebyshev_distance(const cell_position &a, const cell_position &b,\n                                                       const cell_position &shape, bool wrapped) {\n            int res = 0;\n            for (auto const &d: distance_vector(a, b, shape, wrapped)) {\n                auto d_abs = std::abs(d);\n                res = (d_abs > res) ? d_abs : res;\n            }\n            return res;\n        }\n\n        // Auxiliary function for obtaining the N-norm distance between two cell of the grid\n        [[maybe_unused]] static double n_norm_distance(const cell_position &a, const cell_position &b, unsigned int n,\n                                                       const cell_position &shape, bool wrapped) {\n            assert(n > 0);\n            double res = 0;\n            for (auto const &d: distance_vector(a, b, shape, wrapped))\n                res += std::pow((float) std::abs(d), n);\n            return std::pow(res, 1.0 / n);\n        }\n\n        // Auxiliary function for obtaining the Euclidean distance between two cell of the grid\n        [[maybe_unused]] static double euclidean_distance(const cell_position &a, const cell_position &b,\n                                                          const cell_position &shape, bool wrapped) {\n            return n_norm_distance(a, b, 2, shape, wrapped);\n        }\n\n        /************* Neighborhoods functions *************/\n        // Auxiliary function for generating biassed Moore neighborhoods (i.e., center cell is not (0,0...)\n        static std::vector<cell_position> biassed_moore_neighborhood(unsigned int dimension, unsigned int range) {\n            std::vector<cell_position> res = std::vector<cell_position>();\n            cell_position scenario_shape = cell_position();\n            cell_position current = cell_position();\n            for (int i = 0; i < dimension; i++) {\n                scenario_shape.push_back(2 * range + 1);\n                current.push_back(0);\n            }\n            while (true) {\n                res.push_back(current);\n                try {\n                    current = next_cell(current, scenario_shape, 0);\n                }\n                catch (std::overflow_error &e) {\n                    break;\n                }\n            }\n            return res;\n        }\n\n        // Auxiliary function for unbiassing a neighborhood as a function of a middle cell\n        static void unbias_neighborhood(std::vector<cell_position> &biassed_neighborhood, const cell_position &middle) {\n            for (auto &cell: biassed_neighborhood) {\n                int dimension = cell.size();\n                for (int i = 0; i < dimension; i++) {\n                    cell[i] -= middle[i];\n                }\n            }\n        }\n\n        // Auxiliary function for generating von Neumann neighborhoods\n        static std::vector<cell_position> biassed_von_neumann_neighborhood(unsigned int dimension, unsigned int range) {\n            std::vector<cell_position> res = std::vector<cell_position>();\n            std::vector<cell_position> moore = biassed_moore_neighborhood(dimension, range);\n            cell_position middle = cell_position();\n            cell_position shape = cell_position();\n            for (int i = 0; i < dimension; i++) {\n                shape.push_back(2 * range + 1);\n                middle.push_back(range);\n            }\n            for (auto const &neighbor: moore) {\n                if (manhattan_distance(middle, neighbor, shape, false) <= range)\n                    res.push_back(neighbor);\n            }\n            return res;\n        }\n\n        // Auxiliary function for generating Moore neighborhoods\n        static std::vector<cell_position> moore_neighborhood(unsigned int dimension, unsigned int range) {\n            std::vector<cell_position> res = biassed_moore_neighborhood(dimension, range);\n            cell_position middle = cell_position();\n            for (int i = 0; i < dimension; i++) {\n                middle.push_back(range);\n            }\n            unbias_neighborhood(res, middle);\n            return res;\n        }\n\n        // Auxiliary function for generating von Neumann neighborhoods\n        static std::vector<cell_position> von_neumann_neighborhood(unsigned int dimension, unsigned int range) {\n            std::vector<cell_position> res = biassed_von_neumann_neighborhood(dimension, range);\n            cell_position middle = cell_position();\n            for (int i = 0; i < dimension; i++) {\n                middle.push_back(range);\n            }\n            unbias_neighborhood(res, middle);\n            return res;\n        }\n        /*************** Cell space-related **************/\n        // Auxiliary function for iterating over cell of a scenario\n        static cell_position next_cell(cell_position last_cell, cell_position const &scenario_shape, int d) {\n            // If the dimension being explored has not reached the maximum, we just sum 1 to this dimension\n            if (last_cell[d] < scenario_shape[d] - 1) {\n                last_cell[d]++;\n                return last_cell;\n                // If the d is not the maximum dimension, we trigger a recursive call for incrementing the next dimension\n            } else if (d < last_cell.size() - 1) {\n                last_cell[d] = 0;\n                return next_cell(last_cell, scenario_shape, d + 1);\n                // Otherwise, we have reached the limit of our scenario. Throw overflow error.\n            } else {\n                throw std::overflow_error(\"Reached the last cell of the scenario\");\n            }\n        }\n\n        // Returns true if cell is within the boundaries of the scenario\n        static bool cell_in_scenario(cell_position const &cell, cell_position const &shape) {\n            assert(cell.size() == shape.size());\n            for (int i = 0; i < shape.size(); i++) {\n                if (cell[i] < 0 || cell[i] >= shape[i])\n                    return false;\n            }\n            return true;\n        }\n\n        /***************************************************/\n        /*************** NON-STATIC METHODS ****************/\n        /***************************************************/\n\n        /*************** Distance functions ****************/\n        [[maybe_unused]] cell_position distance_vector(cell_position const &origin, cell_position const &destination) {\n            return distance_vector(origin, destination, shape, wrapped);\n        }\n\n        [[maybe_unused]] cell_position destination_cell(cell_position const &origin, cell_position const &distance) {\n            return destination_cell(origin, distance, shape, wrapped);\n        }\n\n        [[maybe_unused]] int manhattan_distance(cell_position const &a, cell_position const &b) {\n            return manhattan_distance(a, b, shape, wrapped);\n        }\n\n        [[maybe_unused]] int chebyshev_distance(cell_position const &a, cell_position const &b) {\n            return chebyshev_distance(a, b, shape, wrapped);\n        }\n\n        [[maybe_unused]] double n_norm_distance(cell_position const &a, cell_position const &b, unsigned int n) {\n            return n_norm_distance(a, b, n, shape, wrapped);\n        }\n\n        [[maybe_unused]] double euclidean_distance(cell_position const &a, cell_position const &b) {\n            return n_norm_distance(a, b, 2);\n        }\n        /*************** Cell space-related **************/\n        // Returns true if cell is within the boundaries of the scenario\n        bool cell_in_scenario(cell_position const &cell) {\n            return cell_in_scenario(cell, shape);\n        }\n\n        cell_position next_cell(cell_position last_cell, int d) {\n            return next_cell(std::move(last_cell), shape, d);\n        }\n\n        // Returns unordered map {relative_neighbor: absolute_neighbor} for a given cell\n        cell_map<S, V> get_cell_map(const cell_position &cell) {\n            assert(cell_in_scenario(cell));\n            auto config = configs[cell];\n            cell_unordered<V> neighborhood = cell_unordered<V>();\n            for (auto const &neighbor: config.neighborhood) {\n                cell_position relative = neighbor.first;\n                V vicinity = neighbor.second;\n                try {\n                    cell_position absolute = destination_cell(cell, relative);\n                    neighborhood.insert({absolute, vicinity});\n                } catch (std::overflow_error &e) {  // Only if neighbor is valid will it be added to the map\n                    continue;\n                }\n            }\n            return cell_map<S, V>(shape, cell, config.state, neighborhood, wrapped);\n        }\n    };\n\n    template<typename S, typename V>\n    cell_map<S, V>::cell_map(cell_position shape, cell_position location, const S &state, const cell_unordered<V> &neighborhood, bool wrapped) :\n        shape(std::move(shape)), location(std::move(location)), state(state), neighborhood(neighborhood), wrapped(wrapped) {}\n\n    template<typename S, typename V>\n    int cell_map<S, V>::manhattan_distance(const cell_position &a) const {\n        return grid_scenario<S, V>::manhattan_distance(location, a, shape, wrapped);\n    }\n\n    template<typename S, typename V>\n    int cell_map<S, V>::chebyshev_distance(const cell_position &a) const {\n        return grid_scenario<S, V>::chebyshev_distance(location, a, shape, wrapped);\n    }\n\n    template<typename S, typename V>\n    double cell_map<S, V>::n_norm_distance(const cell_position &a, unsigned int n) const {\n        return grid_scenario<S, V>::n_norm_distance(location, a, n, shape, wrapped);\n    }\n\n    template<typename S, typename V>\n    [[maybe_unused]] double cell_map<S, V>::euclidean_distance(const cell_position &a) const {\n        return n_norm_distance(a, 2);\n    }\n\n    template<typename S, typename V>\n    [[maybe_unused]] cell_position cell_map<S, V>::neighbor(const cell_position &relative) const {\n        return grid_scenario<S, V>::destination_cell(location, relative, shape, wrapped);\n    }\n\n    template<typename S, typename V>\n    [[maybe_unused]] cell_position cell_map<S, V>::relative(const cell_position &neighbor) const {\n        return grid_scenario<S, V>::distance_vector(location, neighbor, shape, wrapped);\n    }\n} //namespace cadmium::celldevs\n#endif //CADMIUM_CELLDEVS_GRID_UTILS_HPP\n", "meta": {"hexsha": "259f65d925ff4315163cb35606f00d5a7b71b054", "size": 18567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cadmium/celldevs/utils/grid_utils.hpp", "max_stars_repo_name": "romancardenas/cadmium", "max_stars_repo_head_hexsha": "a1c7d0d75569731496852cb3e2bdd37c07c3ddf0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2016-09-16T21:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T17:30:35.000Z", "max_issues_repo_path": "include/cadmium/celldevs/utils/grid_utils.hpp", "max_issues_repo_name": "romancardenas/cadmium", "max_issues_repo_head_hexsha": "a1c7d0d75569731496852cb3e2bdd37c07c3ddf0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2016-10-06T01:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-27T16:15:34.000Z", "max_forks_repo_path": "include/cadmium/celldevs/utils/grid_utils.hpp", "max_forks_repo_name": "romancardenas/cadmium", "max_forks_repo_head_hexsha": "a1c7d0d75569731496852cb3e2bdd37c07c3ddf0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2016-09-17T16:19:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T14:50:35.000Z", "avg_line_length": 46.4175, "max_line_length": 144, "alphanum_fraction": 0.5920719556, "num_tokens": 3755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.043365798609362335, "lm_q1q2_score": 0.017500998904502237}}
{"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_MAP_VIEW_INCLUDE\n#define MTL_MAP_VIEW_INCLUDE\n\n#include <utility>\n#include <boost/utility/enable_if.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/add_reference.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/utility/is_multi_vector_expr.hpp>\n#include <boost/numeric/mtl/utility/auto_type.hpp>\n#include <boost/numeric/mtl/utility/auto_or_const_ref_type.hpp>\n#include <boost/numeric/mtl/matrix/crtp_base_matrix.hpp>\n#include <boost/numeric/mtl/operation/sub_matrix.hpp>\n#include <boost/numeric/mtl/operation/sfunctor.hpp>\n#include <boost/numeric/mtl/operation/tfunctor.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/imag.hpp>\n#include <boost/numeric/mtl/operation/real.hpp>\n\n#include <boost/numeric/mtl/matrix/mat_expr.hpp>\n#include <boost/numeric/mtl/vector/map_view.hpp>\n\n\nnamespace mtl { namespace mat { namespace detail {\n    // Forward declaration for friend declaration\n    template <typename, typename> struct map_value;\n\n    template <typename Functor, typename Matrix> struct map_vector {}; // not defined in general\n    template <typename Functor, typename Vector>\n    struct map_vector<Functor, mtl::mat::multi_vector<Vector> >\n    {\n\ttypedef mtl::vec::map_view<Functor, Vector> type;\n    };\n\n}}}\n\nnamespace mtl { namespace mat {\n\n// View for elementwise mapping of a matrix\ntemplate <typename Functor, typename Matrix> \nstruct map_view \n  : public const_crtp_base_matrix< map_view<Functor, Matrix>, \n\t\t\t\t   typename Functor::result_type, typename Matrix::size_type >,\n    public mat_expr< map_view<Functor, Matrix> >\n{\n    typedef map_view                                                    self;\n    typedef mat_expr< self >                                            expr_base;\n    typedef typename mtl::traits::auto_type<Matrix>::type               other_type; // other as container type\n    typedef typename mtl::traits::auto_or_const_ref_type<Matrix>::type  other;      // container or Matrix&\n//     typedef typename boost::add_reference<other>::type const        const_ref_type;\n//     typedef Matrix                                     other;\n//     typedef const Matrix&                              const_ref_type;\n    typedef typename OrientedCollection<other_type>::orientation        orientation;\n \n    typedef typename Functor::result_type                               value_type;\n    typedef typename Functor::result_type                               const_reference;\n\n    typedef typename other_type::key_type                               key_type;\n    typedef typename other_type::size_type                              size_type;\n    typedef typename other_type::index_type                             index_type;\n    typedef typename other_type::dim_type                               dim_type;\n\n    struct dummy { typedef void type; };\n    // Maybe other_type instead of Matrix for more generality\n    typedef typename boost::mpl::eval_if<mtl::traits::is_multi_vector_expr<Matrix>, detail::map_vector<Functor, Matrix>, dummy>::type vector_type;\n\n    map_view (const Functor& functor, const Matrix& ref) : functor(functor), ref(ref) {}\n    \n    map_view (const Functor& functor, boost::shared_ptr<Matrix> p) \n      : functor(functor), my_copy(p), ref(*p) {}\n    \n#ifdef MTL_WITH_MOVE    \n  map_view (self&& that) : my_copy(std::move(that.my_copy)), functor(that.functor), ref(that.ref) {}\n#endif\n\n    map_view (const self& that) : functor(that.functor), ref(that.ref) { assert(that.my_copy.use_count() == 0); }\n\n    value_type operator() (size_type r, size_type c) const\n    { \n        return functor(ref(r, c));\n    }\n    // for multi_vector, needs enable_if since only defined for multi_vector\n    template <typename S>\n    typename boost::lazy_enable_if<boost::is_integral<S>, detail::map_vector<Functor, Matrix> >::type\n    vector(S c) const\n    {\n\treturn typename detail::map_vector<Functor, Matrix>::type(functor, ref.vector(c));\n    }\n\n    size_type dim1() const { return ref.dim1(); }\n    size_type dim2() const { return ref.dim2(); }\n    dim_type dimensions() const { return ref.dimensions(); }\n\n    size_type begin_row() const { return ref.begin_row(); }\n    size_type end_row() const { return ref.end_row(); }\n    size_type begin_col() const { return ref.begin_col(); }\n    size_type end_col() const {\treturn ref.end_col(); }\n    \n    size_type nnz() const { return ref.nnz(); }\n\n    friend size_type inline num_rows(const self& A) \n    { \tusing mtl::mat::num_rows; return num_rows(A.ref);     }\n    friend size_type inline num_cols(const self& A) \n    { \tusing mtl::mat::num_cols; return num_cols(A.ref);     }\n    template <typename, typename> friend struct detail::map_value;\n\n  protected:\n    boost::shared_ptr<Matrix>           my_copy;\n  public:\n    Functor           functor;\n    other             ref;\n};\n   \ntemplate <typename Functor, typename Matrix> \ninline std::size_t size(const map_view<Functor, Matrix>& A)\n{     return num_rows(A) * num_rows(A); }\n\n// ==========\n// Sub matrix\n// ==========\n\ntemplate <typename Functor, typename Matrix>\nstruct sub_matrix_t< mtl::mat::map_view<Functor, Matrix> >\n{\n    typedef mtl::mat::map_view<Functor, Matrix>                                     view_type;\n\n    // Mapping of sub-matrix type\n    typedef typename sub_matrix_t<Matrix>::const_sub_matrix_type                       ref_sub_type;\n    typedef mtl::mat::map_view<Functor, ref_sub_type>                               const_sub_matrix_type;\n    typedef typename view_type::size_type                                              size_type;\n\n    const_sub_matrix_type operator()(view_type const& view, size_type begin_r, size_type end_r, \n\t\t\t\t     size_type begin_c, size_type end_c)\n    {\n\ttypedef boost::shared_ptr<ref_sub_type>                        pointer_type;\n\n\t// Submatrix of referred matrix (or view)\n\t// Create a submatrix, whos address will be kept by map_view\n\t// Functor is copied from view\n\tpointer_type p(new ref_sub_type(sub_matrix(view.ref, begin_r, end_r, begin_c, end_c)));\n\treturn const_sub_matrix_type(view.functor, p); \n    }\n};\n\n\n}} // namespace mtl::matrix\n\n\nnamespace mtl { namespace traits {\n\n    namespace detail {\n\n\n\ttemplate <typename Functor, typename Matrix> \n\tstruct map_value\n\t{\n\t    typedef typename Matrix::key_type                      key_type;\n\t    typedef typename mtl::mat::map_view<Functor, Matrix>::value_type value_type;\n\t    typedef typename mtl::mat::map_view<Functor, Matrix>::other_type other_type;\n    \t\n\t    map_value(mtl::mat::map_view<Functor, Matrix> const& map_matrix) \n\t      : map_matrix(map_matrix), its_value(map_matrix.ref) \n\t    {}\n\n\t    value_type operator() (key_type const& key) const\n\t    {\n\t\treturn map_matrix.functor(its_value(key));\n\t    }\n\n\t  protected:\n\t    mtl::mat::map_view<Functor, Matrix> const&        map_matrix;\n\t    typename mtl::traits::const_value<other_type>::type its_value;\n        };\n\n\ttemplate <typename Functor, typename Matrix> \n\tstruct mapped_type_helper\n\t{\n\t    static const bool is_id= boost::is_same<Functor, sfunctor::identity<typename Matrix::value_type> >::value;\n\t    typedef typename boost::mpl::if_c<\n\t\tis_id,\n\t\tMatrix,\n\t\ttypename mtl::mat::map_view<Functor, Matrix>::other_type\n\t    >::type other_type;\n\t    typedef typename other_type::key_type   key_type;\n\t    typedef typename other_type::size_type  size_type;\n\t    \n\t    typedef typename boost::mpl::if_c<is_id, \n\t\t\t\t\t      mat::banded_view<Matrix>, \n\t\t\t\t\t      mat::map_view<Functor, Matrix> >::type arg_type;\n\t};\n\t\n\n\ttemplate <typename Functor, typename Matrix> \n\tstruct mapped_row\n\t  : mapped_type_helper<Functor, Matrix>\n\t{\n\t    typedef mapped_type_helper<Functor, Matrix> base;\n\t    explicit mapped_row(typename base::arg_type const& view) : its_row(view.ref) {}\n\n\t    typename base::size_type operator() (typename base::key_type const& key) const\n\t    {\treturn its_row(key);\t    }\n\n\t  protected:\n\t    typename row<typename base::other_type>::type  its_row;\n        };\n\n\n        template <typename Functor, typename Matrix> \n        struct mapped_col\n\t  : mapped_type_helper<Functor, Matrix>\n        {\n\t    typedef mapped_type_helper<Functor, Matrix> base;\n\t    mapped_col(typename base::arg_type const& view) : its_col(view.ref) {}\n\n\t    typename base::size_type operator() (typename base::key_type const& key) const\n\t    {\treturn its_col(key);    }\n\n          protected:\n\t    typename col<typename base::other_type>::type  its_col;\n        };\n\t\n    } // namespace detail\n        \n    template <typename Functor, typename Matrix> \n    struct row<mtl::mat::map_view<Functor, Matrix> >\n    {\n\ttypedef detail::mapped_row<Functor, Matrix>   type;\n    };\n\n    template <typename Functor, typename Matrix> \n    struct col<mtl::mat::map_view<Functor, Matrix> >\n    {\n\ttypedef detail::mapped_col<Functor, Matrix>   type;\n    };\n\n    template <typename Functor, typename Matrix> \n    struct const_value<mtl::mat::map_view<Functor, Matrix> >\n    {\n\ttypedef detail::map_value<Functor, Matrix>  type;\n    };\n\n\n    // ================\n    // Range generators\n    // ================\n\n    // Use range_generator of original matrix\n    template <typename Tag, typename Functor, typename Matrix> \n    struct range_generator<Tag, mtl::mat::map_view<Functor, Matrix> >\n\t: public detail::referred_range_generator<mtl::mat::map_view<Functor, Matrix>, \n\t      range_generator<Tag, typename mtl::mat::map_view<Functor, Matrix>::other_type> >\n    {};\n\n    // To disambigue\n    template <typename Functor, typename Matrix> \n    struct range_generator<tag::major, mtl::mat::map_view<Functor, Matrix> >\n\t: public detail::referred_range_generator<mtl::mat::map_view<Functor, Matrix>, \n\t      range_generator<tag::major, typename mtl::mat::map_view<Functor, Matrix>::other_type> >\n    {};\n\n\n}} // mtl::traits\n\n\nnamespace mtl { namespace mat {\n\ntemplate <typename Scaling, typename Matrix>\nstruct scaled_view\n  : public map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, Matrix>\n{\n    typedef tfunctor::scale<Scaling, typename Matrix::value_type>  functor_type;\n    typedef map_view<functor_type, Matrix>                         base;\n    typedef scaled_view                                            self;\n\n    scaled_view(const Scaling& scaling, const Matrix& matrix)\n      : base(functor_type(scaling), matrix)\n    {}\n    \n    scaled_view(const Scaling& scaling, boost::shared_ptr<Matrix> p)\n      : base(functor_type(scaling), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    scaled_view (self&& that) : base(that) {}\n    scaled_view (const self& that) : base(that) {}\n#endif\n};\n\n// rscaled_view -- added by Hui Li\ntemplate <typename Matrix, typename RScaling>\nstruct rscaled_view\n  : public map_view<tfunctor::rscale<typename Matrix::value_type,RScaling>, Matrix>\n{\n    typedef tfunctor::rscale<typename Matrix::value_type, RScaling>  functor_type;\n    typedef map_view<functor_type, Matrix>                          base;\n    typedef rscaled_view                                            self;\n\t\n    rscaled_view(const Matrix& matrix, const RScaling& rscaling)\n      : base(functor_type(rscaling),matrix)\n    {}\n\n    rscaled_view(boost::shared_ptr<Matrix> p, const RScaling& rscaling)\n      : base(functor_type(rscaling), p)\n    {}\n\n#ifdef MTL_WITH_MOVE    \n    rscaled_view (self&& that) : base(that) {}\n    rscaled_view (const self& that) : base(that) {}\n#endif\n};\n\t\n// divide_by_view -- added by Hui Li\ntemplate <typename Matrix, typename Divisor>\nstruct divide_by_view\n  : public map_view<tfunctor::divide_by<typename Matrix::value_type,Divisor>, Matrix>\n{\n    typedef tfunctor::divide_by<typename Matrix::value_type, Divisor>  functor_type;\n    typedef map_view<functor_type, Matrix>                             base;\n    typedef divide_by_view                                             self;\n\t\n    divide_by_view(const Matrix& matrix,const Divisor& div)\n      : base(functor_type(div), matrix)\n    {}\n\t\n    divide_by_view(boost::shared_ptr<Matrix> p, const Divisor& div)\n      : base(functor_type(div), p)\n    {}\n\t\n#ifdef MTL_WITH_MOVE    \n    divide_by_view (self&& that) : base(that) {}\n    divide_by_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Matrix>\nstruct conj_view\n  : public map_view<mtl::sfunctor::conj<typename Matrix::value_type>, Matrix>\n{\n    typedef mtl::sfunctor::conj<typename Matrix::value_type>            functor_type;\n    typedef map_view<functor_type, Matrix>                              base;\n    typedef conj_view                                                   self;\n\n    conj_view(const Matrix& matrix) : base(functor_type(), matrix) {}\n    conj_view(boost::shared_ptr<Matrix> p) : base(functor_type(), p) {}\n\n#ifdef MTL_WITH_MOVE    \n    conj_view (self&& that) : base(that) {}\n    conj_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Matrix>\nstruct imag_view\n  : public map_view<mtl::sfunctor::imag<typename Matrix::value_type>, Matrix>\n{\n    typedef mtl::sfunctor::imag<typename Matrix::value_type>            functor_type;\n    typedef map_view<functor_type, Matrix>                              base;\n    typedef imag_view                                                   self;\n\n    imag_view(const Matrix& matrix) : base(functor_type(), matrix) {}\n    imag_view(boost::shared_ptr<Matrix> p) : base(functor_type(), p) {}\n\n#ifdef MTL_WITH_MOVE    \n    imag_view (self&& that) : base(that) {}\n    imag_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Matrix>\nstruct negate_view\n  : public map_view<mtl::sfunctor::negate<typename Matrix::value_type>, Matrix>\n{\n    typedef mtl::sfunctor::negate<typename Matrix::value_type>            functor_type;\n    typedef map_view<functor_type, Matrix>                              base;\n    typedef negate_view                                                   self;\n\n    negate_view(const Matrix& matrix) : base(functor_type(), matrix) {}\n    negate_view(boost::shared_ptr<Matrix> p) : base(functor_type(), p) {}\n\n#ifdef MTL_WITH_MOVE    \n    negate_view (self&& that) : base(that) {}\n    negate_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Matrix>\nstruct real_view\n  : public map_view<mtl::sfunctor::real<typename Matrix::value_type>, Matrix>\n{\n    typedef mtl::sfunctor::real<typename Matrix::value_type>            functor_type;\n    typedef map_view<functor_type, Matrix>                              base;\n    typedef real_view                                                   self;\n\n    real_view(const Matrix& matrix) : base(functor_type(), matrix) {}\n    real_view(boost::shared_ptr<Matrix> p) : base(functor_type(), p) {}\n\n#ifdef MTL_WITH_MOVE    \n    real_view (self&& that) : base(that) {}\n    real_view (const self& that) : base(that) {}\n#endif\n};\n\ntemplate <typename Matrix>\nstruct exp_view\n  : public map_view<mtl::sfunctor::exp<typename Matrix::value_type>, Matrix>\n{\n    typedef mtl::sfunctor::exp<typename Matrix::value_type>            functor_type;\n    typedef map_view<functor_type, Matrix>                              base;\n    typedef exp_view                                                   self;\n\n    exp_view(const Matrix& matrix) : base(functor_type(), matrix) {}\n    exp_view(boost::shared_ptr<Matrix> p) : base(functor_type(), p) {}\n\n#ifdef MTL_WITH_MOVE    \n    exp_view (self&& that) : base(that) {}\n    exp_view (const self& that) : base(that) {}\n#endif\n};\n\n\n\n\n\ntemplate <typename Scaling, typename Matrix>\nstruct sub_matrix_t< mtl::mat::scaled_view<Scaling, Matrix> >\n  : public sub_matrix_t< mtl::mat::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, \n\t\t\t\t\t       Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct sub_matrix_t< mtl::mat::conj_view<Matrix> >\n  : public sub_matrix_t< mtl::mat::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename RScaling>\nstruct sub_matrix_t< mtl::mat::rscaled_view<Matrix, RScaling> >\n  : public sub_matrix_t< mtl::mat::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, \n\t\t\t\t\t       Matrix> >\n{};\n\ntemplate <typename Matrix, typename Divisor>\nstruct sub_matrix_t< mtl::mat::divide_by_view<Matrix, Divisor> >\n  : public sub_matrix_t< mtl::mat::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, \n\t\t\t\t\t       Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct sub_matrix_t< mtl::mat::imag_view<Matrix> >\n  : public sub_matrix_t< mtl::mat::map_view<mtl::sfunctor::imag<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct sub_matrix_t< mtl::mat::negate_view<Matrix> >\n  : public sub_matrix_t< mtl::mat::map_view<mtl::sfunctor::negate<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct sub_matrix_t< mtl::mat::real_view<Matrix> >\n  : public sub_matrix_t< mtl::mat::map_view<mtl::sfunctor::real<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct sub_matrix_t< mtl::mat::exp_view<Matrix> >\n  : public sub_matrix_t< mtl::mat::map_view<mtl::sfunctor::exp<typename Matrix::value_type>, Matrix> >\n{};\n\n\n\n}} // namespace mtl::matrix\n\nnamespace mtl { namespace sfunctor {\n\n    template <typename Matrix>\n    struct conj_aux<Matrix, tag::matrix>\n    {\n\ttypedef mat::conj_view<Matrix> result_type;\n\n\tstatic inline result_type apply(const Matrix& matrix)\n\t{\n\t    return result_type(matrix);\n\t}\n\n\tresult_type operator() (const Matrix& matrix) const\n\t{\n\t    return apply(matrix);\n\t}\n    };\n\n}} // namespace mtl::sfunctor\n\n// Traits for specific views\nnamespace mtl { namespace traits {\n\ntemplate <typename Scaling, typename Matrix>\nstruct row< mtl::mat::scaled_view<Scaling, Matrix> >\n  : public row< mtl::mat::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename RScaling>\nstruct row< mtl::mat::rscaled_view<Matrix, RScaling> >\n  : public row< mtl::mat::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename Divisor>\nstruct row< mtl::mat::divide_by_view<Matrix, Divisor> >\n  : public row< mtl::mat::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct row< mtl::mat::conj_view<Matrix> >\n  : public row< mtl::mat::map_view<mtl::sfunctor::conj<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct row< mtl::mat::imag_view<Matrix> >\n  : public row< mtl::mat::map_view<mtl::sfunctor::imag<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct row< mtl::mat::negate_view<Matrix> >\n  : public row< mtl::mat::map_view<mtl::sfunctor::negate<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct row< mtl::mat::real_view<Matrix> >\n  : public row< mtl::mat::map_view<mtl::sfunctor::real<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct row< mtl::mat::exp_view<Matrix> >\n  : row< mtl::mat::map_view<mtl::sfunctor::exp<typename Matrix::value_type>, Matrix> >\n{};\n\n\ntemplate <typename Scaling, typename Matrix>\nstruct col< mtl::mat::scaled_view<Scaling, Matrix> >\n  : public col< mtl::mat::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename RScaling>\nstruct col< mtl::mat::rscaled_view<Matrix, RScaling> >\n  : public col< mtl::mat::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename Divisor>\nstruct col< mtl::mat::divide_by_view<Matrix, Divisor> >\n  : public col< mtl::mat::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct col< mtl::mat::conj_view<Matrix> >\n  : public col< mtl::mat::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct col< mtl::mat::imag_view<Matrix> >\n  : public col< mtl::mat::map_view<mtl::sfunctor::imag<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct col< mtl::mat::negate_view<Matrix> >\n  : public col< mtl::mat::map_view<mtl::sfunctor::negate<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct col< mtl::mat::real_view<Matrix> >\n  : public col< mtl::mat::map_view<mtl::sfunctor::real<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct col< mtl::mat::exp_view<Matrix> >\n  : col< mtl::mat::map_view<mtl::sfunctor::exp<typename Matrix::value_type>, Matrix> >\n{};\n\n\n\n\ntemplate <typename Scaling, typename Matrix>\nstruct const_value< mtl::mat::scaled_view<Scaling, Matrix> >\n  : public const_value< mtl::mat::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename RScaling>\nstruct const_value< mtl::mat::rscaled_view<Matrix, RScaling> >\n  : public const_value< mtl::mat::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename Divisor>\nstruct const_value< mtl::mat::divide_by_view<Matrix, Divisor> >\n  : public const_value< mtl::mat::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct const_value< mtl::mat::conj_view<Matrix> >\n  : public const_value< mtl::mat::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct const_value< mtl::mat::imag_view<Matrix> >\n  : public const_value< mtl::mat::map_view<mtl::sfunctor::imag<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct const_value< mtl::mat::negate_view<Matrix> >\n  : public const_value< mtl::mat::map_view<mtl::sfunctor::negate<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct const_value< mtl::mat::real_view<Matrix> >\n  : public const_value< mtl::mat::map_view<mtl::sfunctor::real<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct const_value< mtl::mat::exp_view<Matrix> >\n  : public const_value< mtl::mat::map_view<mtl::sfunctor::exp<typename Matrix::value_type>, Matrix> >\n{};\n\n\n\ntemplate <typename Tag, typename Scaling, typename Matrix>\nstruct range_generator< Tag, mtl::mat::scaled_view<Scaling, Matrix> >\n    : public range_generator< Tag, mtl::mat::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, \n\t\t\t\t\t\t    Matrix> >\n{};\n\ntemplate <typename Tag, typename Matrix>\nstruct range_generator< Tag, mtl::mat::conj_view<Matrix> >\n    : public range_generator< Tag, mtl::mat::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Tag, typename Matrix, typename RScaling>\nstruct range_generator< Tag, mtl::mat::rscaled_view<Matrix, RScaling> >\n    : public range_generator< Tag, mtl::mat::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, \n\t\t\t\t\t\t    Matrix> >\n{};\n\ntemplate <typename Tag, typename Matrix, typename Divisor>\nstruct range_generator< Tag, mtl::mat::divide_by_view<Matrix, Divisor> >\n    : public range_generator< Tag, mtl::mat::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, \n\t\t\t\t\t\t    Matrix> >\n{};\n\ntemplate <typename Tag, typename Matrix>\nstruct range_generator< Tag, mtl::mat::imag_view<Matrix> >\n    : public range_generator< Tag, mtl::mat::map_view<sfunctor::imag<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Tag, typename Matrix>\nstruct range_generator< Tag, mtl::mat::negate_view<Matrix> >\n    : public range_generator< Tag, mtl::mat::map_view<sfunctor::negate<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Tag, typename Matrix>\nstruct range_generator< Tag, mtl::mat::real_view<Matrix> >\n    : public range_generator< Tag, mtl::mat::map_view<sfunctor::real<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Tag, typename Matrix>\nstruct range_generator< Tag, mtl::mat::exp_view<Matrix> >\n  : range_generator< Tag, mtl::mat::map_view<mtl::sfunctor::exp<typename Matrix::value_type>, Matrix> >\n{};\n\n// Disambiguation \n\ntemplate <typename Scaling, typename Matrix>\nstruct range_generator< tag::major, mtl::mat::scaled_view<Scaling, Matrix> >\n    : public range_generator< tag::major, mtl::mat::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, \n\t\t\t\t\t\t    Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct range_generator< tag::major, mtl::mat::conj_view<Matrix> >\n    : public range_generator< tag::major, mtl::mat::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix, typename RScaling>\nstruct range_generator< tag::major, mtl::mat::rscaled_view<Matrix, RScaling> >\n    : public range_generator< tag::major, mtl::mat::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, \n\t\t\t\t\t\t    Matrix> >\n{};\n\ntemplate <typename Matrix, typename Divisor>\nstruct range_generator< tag::major, mtl::mat::divide_by_view<Matrix, Divisor> >\n    : public range_generator< tag::major, mtl::mat::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, \n\t\t\t\t\t\t    Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct range_generator< tag::major, mtl::mat::imag_view<Matrix> >\n    : public range_generator< tag::major, mtl::mat::map_view<sfunctor::imag<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct range_generator< tag::major, mtl::mat::negate_view<Matrix> >\n    : public range_generator< tag::major, mtl::mat::map_view<sfunctor::negate<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct range_generator< tag::major, mtl::mat::real_view<Matrix> >\n    : public range_generator< tag::major, mtl::mat::map_view<sfunctor::real<typename Matrix::value_type>, Matrix> >\n{};\n\ntemplate <typename Matrix>\nstruct range_generator< tag::major, mtl::mat::exp_view<Matrix> >\n  : range_generator< tag::major, mtl::mat::map_view<mtl::sfunctor::exp<typename Matrix::value_type>, Matrix> >\n{};\n\n\n}} // mtl::traits\n\n\n#endif // MTL_MAP_VIEW_INCLUDE\n", "meta": {"hexsha": "c878c25a3fb0f1d9a354f81c4e9ac884c125e036", "size": 26551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/matrix/map_view.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/mtl/matrix/map_view.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/mtl/matrix/map_view.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2718579235, "max_line_length": 146, "alphanum_fraction": 0.6815939136, "num_tokens": 6687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.04336579799118459, "lm_q1q2_score": 0.01750099865502619}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef bempp_identity_operator_hpp\n#define bempp_identity_operator_hpp\n\n#include \"../common/common.hpp\"\n\n#include \"elementary_abstract_boundary_operator.hpp\"\n\n#include \"abstract_boundary_operator_id.hpp\"\n#include <boost/scoped_ptr.hpp>\n\nnamespace Fiber\n{\n\n/** \\cond FORWARD_DECL */\ntemplate <typename ResultType> class LocalAssemblerForOperators;\n/** \\endcond */\n\n} // namespace Fiber\n\nnamespace Bempp\n{\n\n/** \\cond FORWARD_DECL */\ntemplate <typename BasisFunctionType, typename ResultType> class BoundaryOperator;\ntemplate <typename BasisFunctionType, typename ResultType> class IdentityOperator;\n/** \\endcond */\n\ntemplate <typename BasisFunctionType, typename ResultType>\nclass BEMPP_DEPRECATED IdentityOperatorId : public AbstractBoundaryOperatorId\n{\npublic:\n    IdentityOperatorId(const IdentityOperator<BasisFunctionType, ResultType>& op);\n    virtual size_t hash() const;\n    virtual bool isEqual(const AbstractBoundaryOperatorId &other) const;\n\nprivate:\n    const Space<BasisFunctionType>* m_domain;\n    const Space<BasisFunctionType>* m_range;\n    const Space<BasisFunctionType>* m_dualToRange;\n};\n\n/** \\ingroup identity\n *  \\brief Identity operator.\n *\n *  Let \\f$X\\f$ and \\f$Y\\f$ be two function spaces defined on the same grid. If\n *  \\f$X \\supset Y\\f$, an instance of IdentityOperator with domain \\f$X\\f$\n *  and range \\f$Y\\f$ represents the orthogonal projection operator from\n *  \\f$X\\f$ to \\f$Y\\f$. If \\f$X \\subset Y\\f$, it represents the inclusion\n *  operator from \\f$X\\f$ to \\f$Y\\f$. In the special case of \\f$X = Y\\f$, we\n *  have the standard identity operator. In BEM++ we (ab)use the term \"identity\n *  operator\" to refer to all these three cases.\n *\n *  See AbstractBoundaryOperator for the documentation of the template\n *  parameters.\n *\n *  Use identityOperator() to create a BoundaryOperator object wrapping\n *  an identity operator.\n */\ntemplate <typename BasisFunctionType_, typename ResultType_>\nclass IdentityOperator :\n        public ElementaryAbstractBoundaryOperator<BasisFunctionType_, ResultType_>\n{\n    typedef ElementaryAbstractBoundaryOperator<BasisFunctionType_, ResultType_> Base;\npublic:\n    /** \\copydoc ElementaryAbstractBoundaryOperator::BasisFunctionType */\n    typedef typename Base::BasisFunctionType BasisFunctionType;\n    /** \\copydoc ElementaryAbstractBoundaryOperator::ResultType */\n    typedef typename Base::ResultType ResultType;\n    /** \\copydoc ElementaryAbstractBoundaryOperator::CoordinateType */\n    typedef typename Base::CoordinateType CoordinateType;\n    /** \\copydoc ElementaryAbstractBoundaryOperator::QuadratureStrategy */\n    typedef typename Base::QuadratureStrategy QuadratureStrategy;\n    /** \\copydoc ElementaryAbstractBoundaryOperator::LocalAssembler */\n    typedef typename Base::LocalAssembler LocalAssembler;\n\n    /** \\brief Constructor.\n     *\n     *  \\param[in] domain\n     *    Function space being the domain of the operator.\n     *  \\param[in] range\n     *    Function space being the range of the operator.\n     *  \\param[in] dualToRange\n     *    Function space dual to the the range of the operator.\n     *  \\param[in] label\n     *    Textual label of the operator. If empty, a unique label is generated\n     *    automatically.\n     *  \\param[in] symmetry\n     *    Symmetry of the weak form of the operator. Can be any combination of\n     *    the flags defined in the enumeration type Symmetry.\n     *    If set to AUTO_SYMMETRY (default), the symmetry is determined\n     *    automatically by checking whether its domain and space dual to its\n     *    range are equal. If so, the operator is marked as Hermitian,\n     *    and if the basis functions are real-valued, also as symmetric.\n     *\n     *  All the three spaces must be defined on the same grid. */\n    IdentityOperator(const shared_ptr<const Space<BasisFunctionType> >& domain,\n                     const shared_ptr<const Space<BasisFunctionType> >& range,\n                     const shared_ptr<const Space<BasisFunctionType> >& dualToRange,\n                     const std::string& label = \"\",\n                     int symmetry = AUTO_SYMMETRY);\n    IdentityOperator(const IdentityOperator& other);\n    virtual ~IdentityOperator();\n    IdentityOperator& operator=(const IdentityOperator& rhs);\n\n    /** \\brief Return the identifier of this operator.\n     *\n     *  Identity operators are treated as equivalent if they have the same domain,\n     *  range and dual to range.\n     *\n     *  \\deprecated This function is deprecated and will be removed in a future\n     *  version of BEM++.\n     */\n    BEMPP_DEPRECATED virtual shared_ptr<const AbstractBoundaryOperatorId> id() const;\n\n    /** \\brief Return true. */\n    virtual bool isLocal() const;\n\nprotected:\n    virtual shared_ptr<DiscreteBoundaryOperator<ResultType_> >\n    assembleWeakFormImpl(\n            const Context<BasisFunctionType, ResultType>& context) const;\n\nprivate:\n    virtual std::auto_ptr<LocalAssembler> makeAssemblerImpl(\n            const QuadratureStrategy& quadStrategy,\n            const shared_ptr<const GeometryFactory>& testGeometryFactory,\n            const shared_ptr<const GeometryFactory>& trialGeometryFactory,\n            const shared_ptr<const Fiber::RawGridGeometry<CoordinateType> >& testRawGeometry,\n            const shared_ptr<const Fiber::RawGridGeometry<CoordinateType> >& trialRawGeometry,\n            const shared_ptr<const std::vector<const Fiber::Basis<BasisFunctionType>*> >& testBases,\n            const shared_ptr<const std::vector<const Fiber::Basis<BasisFunctionType>*> >& trialBases,\n            const shared_ptr<const Fiber::OpenClHandler>& openClHandler,\n            const ParallelizationOptions& parallelizationOptions,\n            VerbosityLevel::Level verbosityLevel,\n            bool cacheSingularIntegrals) const;\n\n    virtual shared_ptr<DiscreteBoundaryOperator<ResultType_> >\n    assembleWeakFormInternalImpl(\n            LocalAssembler& assembler,\n            const AssemblyOptions& options) const;\n\n    std::auto_ptr<DiscreteBoundaryOperator<ResultType_> >\n    assembleWeakFormInDenseMode(\n            LocalAssembler& assembler,\n            const AssemblyOptions& options) const;\n\n    std::auto_ptr<DiscreteBoundaryOperator<ResultType_> >\n    assembleWeakFormInSparseMode(\n            LocalAssembler& assembler,\n            const AssemblyOptions& options) const;\n\nprivate:\n    struct Impl;\n    boost::scoped_ptr<Impl> m_impl;\n    shared_ptr<const AbstractBoundaryOperatorId> m_id;\n};\n\n/** \\relates IdentityOperator\n *  \\brief Construct a BoundaryOperator object wrapping an IdentityOperator.\n *\n *  This convenience function constructs an abstract identity operator and wraps\n *  it in a BoundaryOperator object.\n *\n *  \\param[in] context\n *    A Context object that will be used to build the weak form of the\n *    identity operator when necessary.\n *  \\param[in] domain\n *    Function space being the domain of the identity operator.\n *  \\param[in] range\n *    Function space being the range of the identity operator.\n *  \\param[in] dualToRange\n *    Function space dual to the the range of the identity operator.\n *  \\param[in] label\n *    Textual label of the identity operator (optional, used for debugging).\n *  \\param[in] symmetry\n *    Symmetry of the weak form of the operator. Can be any combination of\n *    the flags defined in the enumeration type Symmetry.\n *    If set to AUTO_SYMMETRY (default), the symmetry is determined\n *    automatically by checking whether its domain and space dual to its\n *    range are equal. If so, the operator is marked as Hermitian,\n *    and if the basis functions are real-valued, also as symmetric.\n *\n *  All the three spaces must be defined on the same grid. */\ntemplate <typename BasisFunctionType, typename ResultType>\nBoundaryOperator<BasisFunctionType, ResultType>\nidentityOperator(const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n                 const shared_ptr<const Space<BasisFunctionType> >& domain,\n                 const shared_ptr<const Space<BasisFunctionType> >& range,\n                 const shared_ptr<const Space<BasisFunctionType> >& dualToRange,\n                 const std::string& label = \"\",\n                 int symmetry = AUTO_SYMMETRY);\n\n} // namespace Bempp\n\n#endif\n", "meta": {"hexsha": "a17d4093d86114305d1424a9509b7a295a58d97e", "size": 9354, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/local_operator.hpp", "max_stars_repo_name": "UCL/bempp", "max_stars_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T13:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T13:35:20.000Z", "max_issues_repo_path": "lib/assembly/local_operator.hpp", "max_issues_repo_name": "UCL/bempp", "max_issues_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/assembly/local_operator.hpp", "max_forks_repo_name": "UCL/bempp", "max_forks_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3055555556, "max_line_length": 101, "alphanum_fraction": 0.7237545435, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.037326886273225016, "lm_q1q2_score": 0.01749849440603169}}
{"text": "/* \n * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <boost/lexical_cast.hpp>\n#include <votca/tools/rangeparser.h>\n#include <votca/csg/beadlist.h>\n#include <votca/csg/nblistgrid.h>\n#include \"csg_stat_imc.h\"\n#include <votca/csg/imcio.h>\n\nnamespace votca { namespace csg {\n\nImc::Imc()\n   : _block_length(0), _do_imc(false), _processed_some_frames(false)\n{\n}\n\nImc::~Imc()\n{\n}\n\n// begin the coarse graining process\n// here the data structures are prepared to handle all the data\nvoid Imc::Initialize()\n{\n    // do some output\n    if(_do_imc)\n\t    cout << \"begin to calculate inverse monte carlo parameters\\n\";\n    else\n\t    cout << \"begin to calculate distribution functions\\n\";\n    cout << \"# of bonded interactions: \" << _bonded.size() << endl;\n    cout << \"# of non-bonded interactions: \" << _nonbonded.size() << endl;\n\n    if ( _bonded.size()+_nonbonded.size() == 0 )\n            throw std::runtime_error(\"No interactions defined in options xml-file - nothing to be done\");\n\n    \n   // initialize non-bonded structures\n   for (list<Property*>::iterator iter = _nonbonded.begin();\n            iter != _nonbonded.end(); ++iter) {\n        interaction_t *i = AddInteraction(*iter);\n        i->_is_bonded = false;\n    }\n\n    // initialize non-bonded structures\n   for (list<Property*>::iterator iter = _bonded.begin();\n        iter != _bonded.end(); ++iter) {\n            interaction_t *i = AddInteraction(*iter);\n            i->_is_bonded = true;\n   }\n   \n   // initialize the group structures\n    if(_do_imc)\n        InitializeGroups();\n};\n\nvoid Imc::BeginEvaluate(Topology *top, Topology *top_atom)\n{\n  // we didn't process any frames so far\n    _nframes = 0;\n    _nblock = 0;\n    _processed_some_frames=false;\n\n    // initialize non-bonded structures\n   for (list<Property*>::iterator iter = _nonbonded.begin();\n            iter != _nonbonded.end(); ++iter) {\n        string name = (*iter)->get(\"name\").value();\n\n        interaction_t &i = *_interactions[name];\n\n        // generate the bead lists\n        BeadList beads1, beads2;\n\n        beads1.Generate(*top, (*iter)->get(\"type1\").value());\n        beads2.Generate(*top, (*iter)->get(\"type2\").value());\n\n        if(beads1.size() == 0)\n            throw std::runtime_error(\"Topology does not have beads of type \\\"\" + (*iter)->get(\"type1\").value() + \"\\\"\\n\"\n                    \"This was specified in type1 of interaction \\\"\" + name+ \"\\\"\");\n        if(beads2.size() == 0)\n            throw std::runtime_error(\"Topology does not have beads of type \\\"\" + (*iter)->get(\"type2\").value() + \"\\\"\\n\"\n                    \"This was specified in type2 of interaction \\\"\" + name + \"\\\"\");\n        // calculate normalization factor for rdf\n\n        if ((*iter)->get(\"type1\").value() == (*iter)->get(\"type2\").value())\n            i._norm = 1. / (beads1.size()*(beads2.size()) / 2.);\n        else\n            i._norm = 1. / (beads1.size() * beads2.size());\n    }\n\n    for (list<Property*>::iterator iter = _bonded.begin();\n            iter != _bonded.end(); ++iter) {\n        string name = (*iter)->get(\"name\").value();\n\n        std::list<Interaction *> list = top->InteractionsInGroup(name);\n        if (list.empty() )\n            throw std::runtime_error(\"Bonded interaction '\" + name + \"' defined in options xml-file, but not in topology - check name definition in the mapping file again\");\n    }\n}\n\n// create an entry for interactions\nImc::interaction_t *Imc::AddInteraction(Property *p)\n{\n    string name = p->get(\"name\").value();\n    string group;\n    if(_do_imc)\n        group = p->get(\"inverse.imc.group\").value();\n    else\n        group = \"none\";\n    \n    interaction_t *i = new interaction_t;\n    i->_index = _interactions.size();\n    _interactions[name] = i;\n    getGroup(group)->_interactions.push_back(i);\n    \n    i->_step = p->get(\"step\").as<double>();\n    i->_min = p->get(\"min\").as<double>();\n    i->_max = p->get(\"max\").as<double>();\n    i->_norm = 1.0;\n    i->_p=p;\n    \n    // initialize the current and average histogram\n    int n = (int)((i->_max - i->_min) / i->_step + 1.000000001);\n\n    i->_average.Initialize(i->_min, i->_max+i->_step, n);\n    \n    return i;\n}\n\n// end of trajectory, post processing data\nvoid Imc::EndEvaluate()\n{\n    if(_nframes > 0) {\n        if(_block_length == 0) {\n\t    string suffix = string(\".\") + _extension;\n            WriteDist(suffix);\n            if(_do_imc)\n                WriteIMCData();\n        }\n    }\n    // clear interactions and groups\n    _interactions.clear();\n    _groups.clear();\n    if(!_processed_some_frames)\n        throw std::runtime_error(\"no frames were processed. Please check your input\");\n}\n\n// load options from xml file\nvoid Imc::LoadOptions(const string &file) {\n    load_property_from_xml(_options, file);\n    _bonded = _options.Select(\"cg.bonded\");\n    _nonbonded = _options.Select(\"cg.non-bonded\");\n        \n}\n\n// evaluate current conformation\nvoid Imc::Worker::EvalConfiguration(Topology *top, Topology *top_atom) {\n    \n    _cur_vol = top->BoxVolume();\n    // process non-bonded interactions\n    DoNonbonded(top);\n    // process bonded interactions\n    DoBonded(top);            \n}\n\nvoid Imc::ClearAverages()\n{\n    map<string, interaction_t *>::iterator ic_iter;\n    map<string, group_t *>::iterator group_iter;\n    \n    _nframes = 0;\n    for (ic_iter = _interactions.begin(); ic_iter != _interactions.end(); ++ic_iter)\n        ic_iter->second->_average.Clear();    \n    \n    for (group_iter = _groups.begin(); group_iter != _groups.end(); ++group_iter)\n        group_iter->second->_corr.clear();      \n}\n\nclass IMCNBSearchHandler {\npublic:\n    IMCNBSearchHandler(HistogramNew *hist)\n            : _hist(hist) {}\n\n    HistogramNew *_hist;\n\n    bool FoundPair(Bead *b1, Bead *b2, const vec &r, const double dist) {\n        _hist->Process(dist);\n        return false;\n    }\n};\n\n\n// process non-bonded interactions for current frame\nvoid Imc::Worker::DoNonbonded(Topology *top)\n{\n    for (list<Property*>::iterator iter = _imc->_nonbonded.begin();\n            iter != _imc->_nonbonded.end(); ++iter) {\n        string name = (*iter)->get(\"name\").value();\n        \n        interaction_t &i = *_imc->_interactions[name];\n        \n        // generate the bead lists\n        BeadList beads1, beads2;\n        \n        beads1.Generate(*top, (*iter)->get(\"type1\").value());\n        beads2.Generate(*top, (*iter)->get(\"type2\").value());\n               \n        // generate the neighbour list\n        NBList *nb;\n\n        bool gridsearch=true;\n\n        if(_imc->_options.exists(\"cg.nbsearch\")) {\n            if(_imc->_options.get(\"cg.nbsearch\").as<string>() == \"grid\")\n                gridsearch=true;\n            else if(_imc->_options.get(\"cg.nbsearch\").as<string>() == \"simple\")\n                gridsearch=false;\n            else throw std::runtime_error(\"cg.nbsearch invalid, can be grid or simple\");\n        }\n        if(gridsearch)\n            nb = new NBListGrid();\n        else\n            nb = new NBList();\n\n        nb->setCutoff(i._max + i._step);\n                \n        // clear the current histogram\n        _current_hists[i._index].Clear();\n\n        IMCNBSearchHandler h(&(_current_hists[i._index]));\n\n        nb->SetMatchFunction(&h, &IMCNBSearchHandler::FoundPair);\n\n        // is it same types or different types?\n        if((*iter)->get(\"type1\").value() == (*iter)->get(\"type2\").value())\n            nb->Generate(beads1);\n        else\n            nb->Generate(beads1, beads2);\n\n        // process all pairs\n        /*NBList::iterator pair_iter;\n        for(pair_iter = nb->begin(); pair_iter!=nb->end();++pair_iter) {\n                _current_hists[i._index].Process((*pair_iter)->dist());\n        }*/\n\n        delete nb;\n    }    \n}\n\n// process non-bonded interactions for current frame\nvoid Imc::Worker::DoBonded(Topology *top)\n{\n    for (list<Property*>::iterator iter = _imc->_bonded.begin();\n            iter != _imc->_bonded.end(); ++iter) {\n        string name = (*iter)->get(\"name\").value();\n        \n        interaction_t &i = *_imc->_interactions[name];\n\n        // clear the current histogram\n        _current_hists[i._index].Clear();\n\n        // now fill with new data\n        std::list<Interaction *> list = top->InteractionsInGroup(name);\n\n        std::list<Interaction *>::iterator ic_iter;\n        for(ic_iter=list.begin(); ic_iter!=list.end(); ++ic_iter) {\n            Interaction *ic = *ic_iter;\n            double v = ic->EvaluateVar(*top);\n            _current_hists[i._index].Process(v);\n        }\n    }    \n}\n\n// returns a group, creates it if doesn't exist\nImc::group_t *Imc::getGroup(const string &name)\n{\n    map<string, group_t *>::iterator iter;\n    iter = _groups.find(name);\n    if(iter == _groups.end()) {\n        return _groups[name] = new group_t;\n    }\n    return (*iter).second;\n}\n\n// initialize the groups after interactions are added\nvoid Imc::InitializeGroups()\n{\n    if(!_do_imc) return;\n    map<string, group_t *>::iterator group_iter;\n\n    // clear all the pairs\n    \n    // iterator over all groups\n    for (group_iter = _groups.begin(); group_iter != _groups.end(); ++group_iter) {\n        group_t *grp = (*group_iter).second;      \n        grp->_pairs.clear();\n    \n        int n = 0;\n        // count number of bins needed in matrix\n        for (list<interaction_t*>::iterator i1 = grp->_interactions.begin();\n                i1 != grp->_interactions.end(); ++i1)\n            n+=(*i1)->_average.getNBins();\n    \n        // handy access to matrix\n        group_matrix &M = grp->_corr;\n        \n        // initialize matrix with zeroes\n        M.resize(n,n);\n        M = ub::zero_matrix<double>(n, n);\n        \n        // now create references to the sub matrices\n        int i, j;\n        i=0;j=0;\n        // iterate over all possible compinations of pairs\n        for (list<interaction_t*>::iterator i1 = grp->_interactions.begin();\n                i1 != grp->_interactions.end(); ++i1) {\n            int n1 = (*i1)->_average.getNBins();\n            j = i;\n            for (list<interaction_t*>::iterator i2 = i1;\n                    i2 != grp->_interactions.end(); ++i2) {\n                int n2 = (*i2)->_average.getNBins();\n                \n                // create matrix proxy with sub-matrix\n                pair_matrix corr(M, ub::range(i, i+n1), ub::range(j, j+n2));\n                // add the pair\n                grp->_pairs.push_back(pair_t(*i1, *i2, i, j, corr));\n                j+=n2;\n            }\n            i+=n1;\n        }\n    }\n}\n\n// update the correlation matrix\nvoid Imc::DoCorrelations(Imc::Worker *worker) {\n    if(!_do_imc) return;\n    vector<pair_t>::iterator pair;\n    map<string, group_t *>::iterator group_iter;\n        \n     for (group_iter = _groups.begin(); group_iter != _groups.end(); ++group_iter) {\n        group_t *grp = (*group_iter).second;      \n        // update correlation for all pairs\n        for (pair = grp->_pairs.begin(); pair != grp->_pairs.end(); ++pair) {\n            ub::vector<double> &a = worker->_current_hists[pair->_i1->_index].data().y();\n            ub::vector<double> &b = worker->_current_hists[pair->_i2->_index].data().y();\n            pair_matrix &M = pair->_corr;\n\n            // M_ij += a_i*b_j\n            //for(int i=0; i<M.size1(); ++i)\n            //    for(int j=i; j<M.size2(); ++j)\n            //        M(i,j) = ((((double)_nframes-1.0)*M(i,j)) + (a(i)*b(j)))/(double)_nframes;\n            M = ((((double)_nframes-1.0)*M) + ub::outer_prod(a, b))/(double)_nframes;\n        }\n    }\n}\n\n// write the distribution function\nvoid Imc::WriteDist(const string &suffix)\n{\n    map<string, interaction_t *>::iterator iter;\n\n    // for all interactions\n    for (iter = _interactions.begin(); iter != _interactions.end(); ++iter) {            \n        // calculate the rdf\n        Table &t = iter->second->_average.data();            \n        Table dist(t);\n        if(!iter->second->_is_bonded) {\n            // normalization is calculated using exact shell volume (difference of spheres)\n            for(unsigned int i=0; i<dist.y().size(); ++i) {\n                double x1 = dist.x()[i] - 0.5*iter->second->_step;\n                double x2 = x1 + iter->second->_step;\n                if(x1<0) {\n                    dist.y()[i]=0;\n                }\n                else {\n                    dist.y()[i] = _avg_vol.getAvg()*iter->second->_norm *\n                        dist.y()[i]/(4./3.*M_PI*(x2*x2*x2 - x1*x1*x1));                \n                }\n            }\n        }\n        else {\n\t    // \\TODO normalize bond and angle differently....\n            double norm=ub::norm_1(dist.y());\n            if ( norm > 0 ) {\n              dist.y() = iter->second->_norm * dist.y() / ( norm * iter->second->_step );\n            }\n        }\n        \n        dist.Save((iter->first) + suffix);\n        cout << \"written \" << (iter->first) + suffix << \"\\n\";\n    }\n}\n\n\n/**\n *  Here the inverse monte carlo matrix is calculated and written out\n *\n *  steps:\n *      - calculate th\n */\nvoid Imc::WriteIMCData(const string &suffix) {            \n    if(!_do_imc) return;\n    //map<string, interaction_t *>::iterator ic_iter;\n    map<string, group_t *>::iterator group_iter;\n    \n    // iterate over all groups\n    for(group_iter = _groups.begin(); group_iter!=_groups.end(); ++group_iter) {\n        group_t *grp = (*group_iter).second;    \n        string grp_name = (*group_iter).first;\n        list<interaction_t *>::iterator iter;\n        \n        // number of total bins for all interactions in group is matrix dimension\n        int n=grp->_corr.size1();\n                \n        // build full set of equations + copy some data to make\n        // code better to read\n        group_matrix gmc(grp->_corr);\n        ub::vector<double> dS(n);\n        ub::vector<double> r(n);\n        // the next two variables are to later extract the individual parts\n        // from the whole data after solving equations\n        vector<RangeParser> ranges; // sizes of the individual interactions\n        vector<string> names; // names of the interactions\n                        \n        // copy all averages+r of group to one vector\n        n=0;\n        int begin=1;\n        for(iter=grp->_interactions.begin(); iter != grp->_interactions.end(); ++iter) {\n            interaction_t *ic = *iter;\n            \n            // sub vector for dS\n            ub::vector_range< ub::vector<double> > sub_dS(dS, \n                    ub::range(n, n + ic->_average.getNBins()));\n            \n            // sub vector for r\n            ub::vector_range< ub::vector<double> > sub_r(r, \n                    ub::range(n, n + ic->_average.getNBins()));\n            \n            // read in target and calculate dS\n            CalcDeltaS(ic, sub_dS);\n            \n            // copy r\n            sub_r = ic->_average.data().x();\n            \n            // save size\n\n            RangeParser rp;\n            int end = begin  + ic->_average.getNBins() -1;\n            rp.Add(begin, end);\n            ranges.push_back(rp);\n            begin = end+1;\n            // save name\n            names.push_back(ic->_p->get(\"name\").as<string>());\n            \n            // shift subrange by size of current\n            n+=ic->_average.getNBins();\n        }\n        \n        // now we need to calculate the \n        // A_ij = <S_i*S_j> - <S_i>*<S_j>        \n        vector<pair_t>::iterator pair;\n        for (pair = grp->_pairs.begin(); pair != grp->_pairs.end(); ++pair) {\n            interaction_t *i1 = pair->_i1;\n            interaction_t *i2 = pair->_i2;\n            \n            // make reference to <S_i>\n            ub::vector<double> &a = i1->_average.data().y();\n            // make reference to <S_j>\n            ub::vector<double> &b = i2->_average.data().y();\n            \n            int i=pair->_offset_i;\n            int j=pair->_offset_j;\n            int n1=i1->_average.getNBins();\n            int n2=i2->_average.getNBins();\n            \n            // sub matrix for these two interactions\n            // we only need to take care about one sub-matrix and not the mirrored\n            // one since ublas makes sure the matrix is symmetric\n            pair_matrix M(gmc, ub::range(i, i+n1),\n                               ub::range(j, j+n2));\n            // A_ij = -(<a_i*a_j>  - <a_i>*<b_j>)\n            //for(i=0; i<M.size1(); ++i)\n            //    for(j=i; j<M.size2(); ++j)\n            //        M(i,j) = -(M(i,j) - a(i)*b(j));\n            M = -(M - ub::outer_prod(a, b));\n        }\n        \n        imcio_write_dS(grp_name + suffix + \".imc\", r, dS);\n        imcio_write_matrix(grp_name + suffix + \".gmc\", gmc);\n        imcio_write_index(grp_name + suffix + \".idx\", names, ranges);\n\n    }\n}\n\n// calculate deviation from target vectors\nvoid Imc::CalcDeltaS(interaction_t *interaction, ub::vector_range< ub::vector<double> > &dS)\n{\n    const string &name = interaction->_p->get(\"name\").as<string>();\n                \n    Table target;\n    target.Load(name + \".dist.tgt\");\n\n    if(!interaction->_is_bonded) {\n        for(unsigned int i=0; i<target.y().size(); ++i) {\n            double x1 = target.x()[i] - 0.5*interaction->_step;\n            double x2 = x1 + interaction->_step;\n            if(x1<0)\n                x1=x2=0;\n            target.y()[i] = 1./(_avg_vol.getAvg()*interaction->_norm) *\n                target.y()[i] * (4./3.*M_PI*(x2*x2*x2 - x1*x1*x1));                \n        }        \n    }\n    else {\n            target.y() = (1.0 / interaction->_norm)*target.y();\n    }\n    if(target.y().size() !=  interaction->_average.data().y().size())\n        throw std::runtime_error(\"number of grid points in target does not match the grid\");\n\n    dS = interaction->_average.data().y() - target.y();\n}\n\n\nvoid Imc::WriteIMCBlock(const string &suffix)\n{\n    if(!_do_imc) return;\n    //map<string, interaction_t *>::iterator ic_iter;\n    map<string, group_t *>::iterator group_iter;\n\n    // iterate over all groups\n    for(group_iter = _groups.begin(); group_iter!=_groups.end(); ++group_iter) {\n        group_t *grp = (*group_iter).second;\n        string grp_name = (*group_iter).first;\n        list<interaction_t *>::iterator iter;\n\n        // number of total bins for all interactions in group is matrix dimension\n        int n=grp->_corr.size1();\n\n        // build full set of equations + copy some data to make\n        // code better to read\n        group_matrix gmc(grp->_corr);\n        ub::vector<double> dS(n);\n        ub::vector<double> r(n);\n        // the next two variables are to later extract the individual parts\n        // from the whole data after solving equations\n        vector<int> sizes; // sizes of the individual interactions\n        vector<string> names; // names of the interactions\n\n        // copy all averages+r of group to one vector\n        n=0;\n        for(iter=grp->_interactions.begin(); iter != grp->_interactions.end(); ++iter) {\n            interaction_t *ic = *iter;\n\n            // sub vector for dS\n            ub::vector_range< ub::vector<double> > sub_dS(dS,\n                    ub::range(n, n + ic->_average.getNBins()));\n\n            // sub vector for r\n            ub::vector_range< ub::vector<double> > sub_r(r,\n                    ub::range(n, n + ic->_average.getNBins()));\n\n            // read in target and calculate dS\n            sub_dS = ic->_average.data().y();\n            // copy r\n            sub_r = ic->_average.data().x();\n            // save size\n            sizes.push_back(ic->_average.getNBins());\n            // save name\n            names.push_back(ic->_p->get(\"name\").as<string>());\n\n            // shift subrange by size of current\n            n+=ic->_average.getNBins();\n        }\n\n        // write the dS\n        ofstream out_dS;\n        string name_dS = grp_name + suffix + \".S\";\n        out_dS.open(name_dS.c_str());\n        out_dS << setprecision(8);\n        if(!out_dS)\n            throw runtime_error(string(\"error, cannot open file \") + name_dS);\n\n        for(size_t i=0; i<dS.size(); ++i) {\n            out_dS << r[i] << \" \" << dS[i] << endl;\n        }\n\n        out_dS.close();\n        cout << \"written \" << name_dS << endl;\n\n        // write the correlations\n        ofstream out_cor;\n        string name_cor = grp_name + suffix + \".cor\";\n        out_cor.open(name_cor.c_str());\n        out_cor << setprecision(8);\n\n        if(!out_cor)\n            throw runtime_error(string(\"error, cannot open file \") + name_cor);\n\n        for(group_matrix::size_type i=0; i<grp->_corr.size1(); ++i) {\n            for(group_matrix::size_type j=0; j<grp->_corr.size2(); ++j) {\n                out_cor << grp->_corr(i, j) << \" \";\n            }\n            out_cor << endl;\n        }\n        out_cor.close();\n        cout << \"written \" << name_cor << endl;\n    }\n}\n\nCsgApplication::Worker *Imc::ForkWorker()\n{\n    Imc::Worker *worker;\n    worker = new Imc::Worker;\n    map<string, interaction_t *>::iterator ic_iter;\n\n    worker->_current_hists.resize(_interactions.size());\n    worker->_imc = this;\n\n    for (ic_iter = _interactions.begin(); ic_iter != _interactions.end(); ++ic_iter) {\n        interaction_t *i = ic_iter->second;\n        worker->_current_hists[i->_index].Initialize(\n        i->_average.getMin(),\n        i->_average.getMax(),\n        i->_average.getNBins());\n    }\n    return worker;\n}\n\nvoid Imc::MergeWorker(CsgApplication::Worker* worker_)\n{\n    _processed_some_frames = true;\n    Imc::Worker *worker = dynamic_cast<Imc::Worker *>(worker_);\n        // update the average\n    map<string, interaction_t *>::iterator ic_iter;\n    //map<string, group_t *>::iterator group_iter;\n\n    ++_nframes;\n    _avg_vol.Process(worker->_cur_vol);\n    for (ic_iter = _interactions.begin(); ic_iter != _interactions.end(); ++ic_iter) {\n        interaction_t *i=ic_iter->second;\n        i->_average.data().y() = (((double)_nframes-1.0)*i->_average.data().y()\n            + worker->_current_hists[i->_index].data().y())/(double)_nframes;\n    }\n\n        // update correlation matrices\n    if(_do_imc)\n        DoCorrelations(worker);\n\n    if(_block_length != 0) {\n        if((_nframes % _block_length)==0) {\n            _nblock++;\n            string suffix = string(\"_\") + boost::lexical_cast<string>(_nblock) + string(\".\") + _extension;\n            WriteDist(suffix);\n            WriteIMCData(suffix);\n            WriteIMCBlock(suffix);\n            ClearAverages();\n        }\n    }\n\n}\n\n}}\n", "meta": {"hexsha": "004d4773ccf2eb7ac6aba2d3eb35cda807fc7146", "size": 22918, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tools/csg_stat_imc.cc", "max_stars_repo_name": "Pallavi-Banerjee21/votca.csg", "max_stars_repo_head_hexsha": "d88977b0bec6159b567871d8901f990120a6f2e4", "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/tools/csg_stat_imc.cc", "max_issues_repo_name": "Pallavi-Banerjee21/votca.csg", "max_issues_repo_head_hexsha": "d88977b0bec6159b567871d8901f990120a6f2e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/csg_stat_imc.cc", "max_forks_repo_name": "Pallavi-Banerjee21/votca.csg", "max_forks_repo_head_hexsha": "d88977b0bec6159b567871d8901f990120a6f2e4", "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.7525773196, "max_line_length": 173, "alphanum_fraction": 0.5557640283, "num_tokens": 5802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758367247085, "lm_q2_score": 0.04672496111505598, "lm_q1q2_score": 0.017469333932821022}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\nnamespace py = pybind11;\n\n#include <fmt/format.h>\n#include <fmt/format.cc>\n#include <fmt/string.h>\n#include <fmt/ostream.h>\n\n#include <vector>\n#include <cmath>\n#include <random>\n#include <math.h>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n\n// --------------------------------------------------\n// #include \"definitions.h\"\nconst double pi = M_PI;\ntypedef std::array<double, 3> vec;\n\nusing std::sin;\nusing std::cos;\nusing std::exp;\nusing std::acos;\nusing std::asin;\nusing std::pow;\nusing std::sqrt;\nusing std::log;\n\n\n\n// --------------------------------------------------\nnamespace el_ph {\n\n\n\n    class photon {\n\n        public:\n            std::array<double, 8> data;\n            photon( double, double, double, double, double, double, double, double );\n\n            /// photon four-velocity components\n            const double hv(){ return data[0]; };\n            const double vx(){ return data[1]; };\n            const double vy(){ return data[2]; };\n            const double vz(){ return data[3]; };\n            const double x(){ return data[4]; };\n            const double y(){ return data[5]; };\n            const double z(){ return data[6]; };\n            const double w(){ return data[7]; };\n\n            /// Location \n            // const double x(){ return data[4]; };\n            // const double y(){ return data[5]; };\n            // const double z(){ return data[6]; };\n\n    };\n\n\n    photon::photon(double E, double vx, double vy, double vz, double x, double y, double z, double w) {\n        this->data = {{E, vx, vy, vz, x, y, z, w}};\n    };\n\n\n\n    // --------------------------------------------------\n    class photonBucket {\n\n        /// size of the bucket (in terms of photons)\n        size_t nPhotons = 0;\n\n        /// Photon container\n        std::vector<std::array<double, 8>> bucket;\n\n        public:\n            void push_back( photon ph );\n\n            //const size_t size( ) { return this->nPhotons; };\n            const size_t size( ) { return bucket.size(); };\n\n            void replace( const size_t indx, photon ph );\n\n            photon get( const size_t indx );\n            \n            std::array<double, 8> get_data( const size_t indx );\n\n            void resize(const size_t N);\n\n            void swap(const size_t i1, const size_t i2);\n\n            std::vector<double> vecE();  \n            std::vector<double> vecZ();  \n    };\n\n    /// Append photon into bucket\n    void photonBucket::push_back( photon ph ) {\n        bucket.push_back( ph.data );\n        nPhotons++;\n    };\n\n    /// Replace i:th photon with the given one\n    void photonBucket::replace( const size_t indx, photon ph ) {\n        bucket[indx] = ph.data;\n    };\n\n    /// Swap i1 and i2 photons in the bucket\n    void photonBucket::swap(const size_t i1, const size_t i2) {\n        std::swap( bucket[i1], bucket[i2] );\n    };\n\n    /// return i:th photon data\n    photon photonBucket::get( const size_t indx ) {\n        std::array<double, 8> data = bucket[indx];\n        photon ph(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]);\n\n        return ph;\n    };\n\n    /// return i:th photon raw data\n    std::array<double, 8> photonBucket::get_data( const size_t indx ) {\n        return bucket[indx];\n    };\n\n    /// Resize bucket\n    void photonBucket::resize(const size_t N) {\n        // TODO error check if N < N\n        bucket.resize(N);\n        nPhotons = N;\n\n        return;\n    };\n\n    /// collect energy components of velocity\n    std::vector<double> photonBucket::vecE() {\n        std::vector<double> ve;\n        ve.resize( size() );\n\n        for (size_t i=0; i<size(); i++) {\n            auto d = bucket[i];\n            ve[i] = d[0];\n        }\n        return ve;\n    };\n\n    /// collect z components of velocity\n    std::vector<double> photonBucket::vecZ() {\n        std::vector<double> vz;\n        vz.resize( size() );\n\n        for (size_t i=0; i<size(); i++) {\n            auto d = bucket[i];\n            vz[i] = d[3];\n        }\n        return vz;\n    };\n\n\n\n\n    /*\n    class electron {\n\n        public:\n            std::array<double, 4> data; \n            electron( double, double, double, double );\n           \n            // four-velocity of electron\n            const double v0(){ return data[0]; };\n            const double vx(){ return data[1]; };\n            const double vy(){ return data[2]; };\n            const double vz(){ return data[3]; };\n\n            /// 3-velocity in units of c, i.e. v/c\n            const double v() {\n                return std::sqrt(\n                          pow(vx(), 2.0) \n                        + pow(vy(), 2.0) \n                        + pow(vz(), 2.0) \n                                ); };\n\n            /// gamma factor\n            const double gamma() { return 1.0 / std::sqrt( 1.0 - std::pow( v(), 2.0 ) ); };\n\n            /// proper momentum\n            const double p() { return gamma() * v(); };\n\n    };\n\n    electron::electron(double v0, double vx, double vy, double vz) {\n        this->data = {{v0, vx, vy, vz}};\n    };\n    */\n\n\n    /// Electron with all velocity transformations build-in\n    // Uses Eigen vectors internally for performance\n    class electron {\n\n        public:\n\n        /// spatial components of the four-velocity\n        Vector3d fvel;\n\n        /// load from vector\n        void loadFvel(Vector3d u) { fvel = u; };\n\n        /// Load from components\n        void loadFvelComponents(double ux, double uy, double uz) { \n                fvel(0) = ux;\n                fvel(1) = uy;\n                fvel(2) = uz;\n        };\n\n        /// Load from velocity\n        // u = v*gamma = v/sqrt(1-v^2)\n        void loadVel(Vector3d v) {\n            fvel = v / sqrt(1.0 - v.dot(v));\n        };\n\n        void loadVelComponents(double vx, double vy, double vz) {\n            Vector3d v(vx, vy, vz);\n            loadVel(v);    \n        };\n\n/*        // return 3d components of the electron 4-velocity\n        const double vx(){ return fvel(0); };\n        const double vy(){ return fvel(1); };\n        const double vz(){ return fvel(2); };\n*/        \n\n        /// gamma factor\n        const double gamma() { return sqrt(1.0 + fvel.dot(fvel) ); };\n            \n        /// beta = v/c = sqrt(1-1/gamma^2)\n        const double beta() { return sqrt(1.0 - 1.0/(gamma()*gamma())); };\n\n        /// p = sqrt(gamma^2-1)\n        const double pel() { return sqrt(gamma()*gamma()-1.0); };\n\n        /// coordinate velocity vector v = u/gamma\n        Vector3d vel() { return fvel/gamma(); };\n\n        /// vmod = sqrt(vx^2 + vy^2 + vz^2)\n        const double vmod() { return sqrt(vel().dot(vel())); };\n        \n        // unit vector in the electron direction \n        Vector3d beta0() { return vel()/beta(); };\n\n\n    };\n\n\n\n    // --------------------------------------------------\n    class electronBucket {\n\n        /// size of the bucket (number of electrons)\n        size_t nElectrons = 0;\n\n        /// Electron container\n//        std::vector<std::array<double, 3>> bucket;\n        std::vector<Vector3d> bucket;\n\n        public:\n            void push_back( electron e );\n            const size_t size( ) { return this->nElectrons; };\n\n            void replace( size_t indx, electron e );\n\n            electron get( size_t indx);\n\n    };\n\n    void electronBucket::push_back( electron e ) {\n        bucket.push_back( e.vel() );\n        nElectrons++;\n    };\n\n    void electronBucket::replace( size_t indx, electron e ) {\n        bucket[indx] = e.vel();\n    };\n\n    electron electronBucket::get( size_t indx ) {\n        //std::array<double, 3> data = bucket[indx];\n        electron e;\n        Vector3d vel = bucket[indx];\n        e.loadVel(vel);\n\n        return e;\n    };\n\n}\n\n\n\n\n\n\n// --------------------------------------------------\nPYBIND11_MODULE(el_ph, m) {\n\n\n    py::class_<el_ph::photon>(m, \"photon\" )\n        .def(py::init<double, double, double, double, double, double, double, double >())\n        .def_readwrite(\"data\",      &el_ph::photon::data)\n        .def(\"hv\",  &el_ph::photon::hv)\n        .def(\"vx\",  &el_ph::photon::vx)\n        .def(\"vy\",  &el_ph::photon::vy)\n        .def(\"vz\",  &el_ph::photon::vz)\n        .def(\"x\",  &el_ph::photon::x)\n        .def(\"y\",  &el_ph::photon::y)\n        .def(\"z\",  &el_ph::photon::z)\n        .def(\"w\",  &el_ph::photon::w);\n\n    py::class_<el_ph::electron>(m, \"electron\" )\n        .def(py::init<>())\n        .def(\"vx\",   [](el_ph::electron &e){return e.vel()(0);})\n        .def(\"vy\",   [](el_ph::electron &e){return e.vel()(1);})\n        .def(\"vz\",   [](el_ph::electron &e){return e.vel()(2);})\n        .def(\"loadVelComponents\",  &el_ph::electron::loadVelComponents)\n        .def(\"loadFvelComponents\", &el_ph::electron::loadFvelComponents)\n        .def(\"beta\",  &el_ph::electron::beta)\n        .def(\"gamma\", &el_ph::electron::gamma)\n        .def(\"vmod\", &el_ph::electron::vmod)\n        .def(\"beta0\", &el_ph::electron::beta0);\n\n    py::class_<el_ph::electronBucket>(m, \"electronBucket\" )\n        .def(py::init<>())\n        .def(\"size\",      &el_ph::electronBucket::size)\n        .def(\"replace\",   &el_ph::electronBucket::replace)\n        .def(\"get\",       &el_ph::electronBucket::get)\n        .def(\"push_back\", &el_ph::electronBucket::push_back);\n\n    py::class_<el_ph::photonBucket>(m, \"photonBucket\" )\n        .def(py::init<>())\n        .def(\"size\",      &el_ph::photonBucket::size)\n        .def(\"replace\",   &el_ph::photonBucket::replace)\n        .def(\"get\",       &el_ph::photonBucket::get)\n        .def(\"vecE\",      &el_ph::photonBucket::vecE)\n        .def(\"vecZ\",      &el_ph::photonBucket::vecZ)\n        .def(\"push_back\", &el_ph::photonBucket::push_back);\n\n\n\n}\n", "meta": {"hexsha": "3174ca59cd2c25a0b5d72175dd4038c1b40f38b7", "size": 9640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prototypes/compton/el_ph_classes.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/compton/el_ph_classes.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/compton/el_ph_classes.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.5428571429, "max_line_length": 103, "alphanum_fraction": 0.5046680498, "num_tokens": 2522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.03789242825934403, "lm_q1q2_score": 0.017469045236445768}}
{"text": "/**\n * $Id$\n *\n * Copyright (C)\n * 2015 - $Date$\n *     Martin Wolf <ndhist@martin-wolf.org>\n *\n * This file is distributed under the BSD 2-Clause Open Source License\n * (See LICENSE file).\n *\n */\n#include <sstream>\n#include <vector>\n\n#include <boost/preprocessor/seq/elem.hpp>\n#include <boost/preprocessor/seq/for_each_product.hpp>\n#include <boost/python.hpp>\n\n#include <boost/numpy/ndarray.hpp>\n#include <boost/numpy/iterators/flat_iterator.hpp>\n#include <boost/numpy/iterators/multi_flat_iterator.hpp>\n#include <boost/numpy/python/make_tuple_from_container.hpp>\n\n#include <ndhist/detail/bin_iter_value_type_traits.hpp>\n#include <ndhist/type_support.hpp>\n#include <ndhist/detail/utils.hpp>\n#include <ndhist/stats/median.hpp>\n\nnamespace ndhist {\nnamespace stats {\n\nnamespace detail {\n\ntemplate <typename AxisValueType, typename WeightValueType>\nAxisValueType\ncalc_axis_median_impl(\n    ndhist const & h\n  , intptr_t const axis\n)\n{\n    // Project the given histogram to the given axis (if nd > 1).\n    ndhist const proj = (h.get_nd() == 1 ? h : h.project(bp::object(axis)));\n\n    // Iterate over the bins (which are along the given axis) and exclude\n    // possible under- and overflow bins.\n    Axis const & theaxis = *proj.get_axes()[0];\n    intptr_t nbins = theaxis.get_n_bins();\n    if(theaxis.has_underflow_bin()) --nbins;\n    if(theaxis.has_overflow_bin()) --nbins;\n    bn::ndarray proj_bc_arr = proj.bc_.construct_ndarray(proj.bc_.get_dtype(), 0, /*owner=*/NULL, /*set_owndata_flag=*/false);\n\n    // First calculate the median sum of weights sum.\n    typedef bn::iterators::flat_iterator<\n                ::ndhist::detail::bin_iter_value_type_traits<WeightValueType>\n            >\n            bin_iter_t;\n    bin_iter_t bin_iter(\n        proj_bc_arr\n      , bn::detail::iter_operand::flags::READONLY::value\n    );\n    // Skip the underflow bin.\n    if(theaxis.has_underflow_bin()) ++bin_iter;\n    bool all_bins_are_zero = true;\n    double median_sow_sum = 0;\n    for(intptr_t i=0; i<nbins; ++i)\n    {\n        typename bin_iter_t::value_ref_type bin = *bin_iter;\n        median_sow_sum += *bin.sow_;\n        if(median_sow_sum != 0)\n        {\n            all_bins_are_zero = false;\n        }\n        ++bin_iter;\n    }\n    median_sow_sum *= 0.5;\n    if(all_bins_are_zero)\n    {\n        std::stringstream ss;\n        ss << \"All bin content values are zero. The median value is ambiguous \"\n           << \"in that case!\";\n        throw ValueError(ss.str());\n    }\n\n    // At least one bin content value is unequal than zero, search for the\n    // median axis value.\n    typedef bn::iterators::multi_flat_iterator<3>::impl<\n                bn::iterators::single_value<AxisValueType>\n              , bn::iterators::single_value<AxisValueType>\n              , ::ndhist::detail::bin_iter_value_type_traits<WeightValueType>\n            >\n            multi_iter_t;\n    bn::ndarray axis_bincenters_arr = theaxis.get_bincenters_ndarray();\n    bn::ndarray axis_upper_binedges_arr = theaxis.get_upper_binedges_ndarray();\n    multi_iter_t iter(\n        axis_bincenters_arr\n      , axis_upper_binedges_arr\n      , proj_bc_arr\n      , bn::detail::iter_operand::flags::READONLY::value\n      , bn::detail::iter_operand::flags::READONLY::value\n      , bn::detail::iter_operand::flags::READONLY::value\n    );\n    // Skip the underflow bin.\n    if(theaxis.has_underflow_bin()) ++iter;\n    WeightValueType curr_sow_sum = 0;\n    for(intptr_t i=0; i<nbins; ++i)\n    {\n        typename multi_iter_t::multi_references_type multi_value = *iter;\n        typename multi_iter_t::value_ref_type_0 axis_bincenter_value     = multi_value.value_0;\n        typename multi_iter_t::value_ref_type_1 axis_upper_binedge_value = multi_value.value_1;\n        typename multi_iter_t::value_ref_type_2 bin                      = multi_value.value_2;\n\n        curr_sow_sum += *bin.sow_;\n        if(curr_sow_sum == median_sow_sum)\n        {\n            return axis_upper_binedge_value;\n        }\n        else if(curr_sow_sum > median_sow_sum)\n        {\n            return axis_bincenter_value;\n        }\n\n        ++iter;\n    }\n\n    std::stringstream ss;\n    ss << \"The median value for axis '\"<<axis<<\"' could not be determined. \"\n       << \"This is a BUG!\";\n    throw RuntimeError(ss.str());\n}\n\n}// namespace detail\n\nnamespace py {\n\nnamespace detail {\n\nbp::object\ncalc_axis_median(\n    ndhist const & h\n  , intptr_t const axis\n)\n{\n    // Determine the correct axis index.\n    intptr_t const axis_idx = ::ndhist::detail::adjust_axis_index(h.get_nd(), axis);\n\n    // Check that the axis and weight types are not bp::object.\n    if(   h.get_axes()[axis_idx]->has_object_value_dtype()\n       || h.has_object_weight_dtype()\n    )\n    {\n        std::stringstream ss;\n        ss << \"The axis and weight data types must be POD types. Non-POD types \"\n           << \"are not supported by the median function!\";\n        throw TypeError(ss.str());\n    }\n\n    #define NDHIST_MULTPLEX(r, seq)                                             \\\n        if(   bn::dtype::equivalent(h.get_axes()[axis_idx]->get_dtype(), bn::dtype::get_builtin<BOOST_PP_SEQ_ELEM(0,seq)>())\\\n           && bn::dtype::equivalent(h.get_weight_dtype(), bn::dtype::get_builtin<BOOST_PP_SEQ_ELEM(1,seq)>())\\\n          )                                                                     \\\n        {                                                                       \\\n            BOOST_PP_SEQ_ELEM(0,seq) median = ::ndhist::stats::detail::calc_axis_median_impl<BOOST_PP_SEQ_ELEM(0,seq), BOOST_PP_SEQ_ELEM(1,seq)>(h, axis_idx);\\\n            return bp::object(median);                                          \\\n        }\n    BOOST_PP_SEQ_FOR_EACH_PRODUCT(NDHIST_MULTPLEX, (NDHIST_TYPE_SUPPORT_AXIS_VALUE_TYPES_WITHOUT_OBJECT)(NDHIST_TYPE_SUPPORT_WEIGHT_VALUE_TYPES_WITHOUT_OBJECT))\n    #undef NDHIST_MULTPLEX\n\n    std::stringstream ss;\n    ss << \"The combination of axis value type and weight value type of this \"\n       << \"ndhist object is not supported for the median function!\";\n    throw TypeError(ss.str());\n}\n\n}// namespace detail\n\nbp::object\nmedian(\n    ndhist const & h\n  , bp::object const & axis\n)\n{\n    if(axis != bp::object())\n    {\n        // A particular axis is given. So calculate the median only for that\n        // axis and return a scalar.\n        intptr_t const axis_idx = bp::extract<intptr_t>(axis);\n        return detail::calc_axis_median(h, axis_idx);\n    }\n\n    // No axis was specified, so calculate the median for all axes.\n    intptr_t const nd = h.get_nd();\n\n    // Return a scalar value if the dimensionality of the histogram is 1.\n    if(nd == 1)\n    {\n        return detail::calc_axis_median(h, 0);\n    }\n\n    // Return a tuple holding the moment values for each single axis.\n    std::vector<bp::object> medians;\n    medians.reserve(nd);\n    for(intptr_t i=0; i<nd; ++i)\n    {\n        medians.push_back(detail::calc_axis_median(h, i));\n    }\n    return boost::python::make_tuple_from_container(medians.begin(), medians.end());\n}\n\n}// namespace py\n}// namespace stats\n}// namespace ndhist\n", "meta": {"hexsha": "7d8c45ac570b51695e65482d9d28cd6c71a8f585", "size": 7037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ndhist/stats/median.cpp", "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": "src/ndhist/stats/median.cpp", "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": "src/ndhist/stats/median.cpp", "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.1933962264, "max_line_length": 160, "alphanum_fraction": 0.6350717635, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.03789242717285293, "lm_q1q2_score": 0.01746904473555514}}
{"text": "//\n//   Copyright (C) 2003-2016 Greg Landrum and Rational Discovery LLC\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n#include \"MolTransforms.h\"\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/QueryOps.h>\n#include <Numerics/EigenSolvers/PowerEigenSolver.h>\n#include <Numerics/SymmMatrix.h>\n#include <Numerics/Matrix.h>\n#include <Geometry/Transform3D.h>\n#include <stack>\n#include <boost/dynamic_bitset.hpp>\n#include <RDGeneral/Exceptions.h>\n\n#define EIGEN_TOLERANCE 5.0e-2\nnamespace MolTransforms {\n\nusing namespace RDKit;\nvoid transformAtom(Atom *atom, RDGeom::Transform3D &tform) {\n  PRECONDITION(atom, \"no atom\");\n  ROMol &mol = atom->getOwningMol();\n  for (ROMol::ConstConformerIterator ci = mol.beginConformers();\n       ci != mol.endConformers(); ci++) {\n    RDGeom::Point3D &pos = (*ci)->getAtomPos(atom->getIdx());\n    tform.TransformPoint(pos);\n  }\n  // atom->setPos(pos);\n}\nvoid transformMolsAtoms(ROMol *mol, RDGeom::Transform3D &tform) {\n  PRECONDITION(mol, \"no molecule\");\n\n  ROMol::AtomIterator atomIt;\n  for (atomIt = mol->beginAtoms(); atomIt != mol->endAtoms(); atomIt++) {\n    transformAtom(*atomIt, tform);\n  }\n}\n\nRDGeom::Point3D computeCentroid(const Conformer &conf, bool ignoreHs) {\n  RDGeom::Point3D res(0.0, 0.0, 0.0);\n  const ROMol &mol = conf.getOwningMol();\n  ROMol::ConstAtomIterator cai;\n  unsigned int nAtms = 0;\n\n  for (cai = mol.beginAtoms(); cai != mol.endAtoms(); cai++) {\n    if (((*cai)->getAtomicNum() == 1) && (ignoreHs)) {\n      continue;\n    }\n    res += conf.getAtomPos((*cai)->getIdx());\n    nAtms++;\n  }\n  res /= nAtms;\n  return res;\n}\nnamespace {\nvoid computeCovarianceTerms(const Conformer &conf,\n                            const RDGeom::Point3D &center, double &xx,\n                            double &xy, double &xz, double &yy, double &yz,\n                            double &zz, bool normalize, bool ignoreHs,\n                            const std::vector<double> *weights) {\n  PRECONDITION(!weights || weights->size() >= conf.getNumAtoms(),\n               \"bad weights vector\");\n\n  xx = xy = xz = yy = yz = zz = 0.0;\n  const ROMol &mol = conf.getOwningMol();\n  double wSum = 0.0;\n  for (ROMol::ConstAtomIterator cai = mol.beginAtoms(); cai != mol.endAtoms();\n       cai++) {\n    if (((*cai)->getAtomicNum() == 1) && (ignoreHs)) {\n      continue;\n    }\n    RDGeom::Point3D loc = conf.getAtomPos((*cai)->getIdx());\n    loc -= center;\n    double w = 1.0;\n    if (weights) {\n      w = (*weights)[(*cai)->getIdx()];\n    }\n    wSum += w;\n    xx += w * loc.x * loc.x;\n    xy += w * loc.x * loc.y;\n    xz += w * loc.x * loc.z;\n    yy += w * loc.y * loc.y;\n    yz += w * loc.y * loc.z;\n    zz += w * loc.z * loc.z;\n  }\n  if (normalize) {\n    xx /= wSum;\n    xy /= wSum;\n    xz /= wSum;\n    yy /= wSum;\n    yz /= wSum;\n    zz /= wSum;\n  }\n}\n\nRDNumeric::DoubleSymmMatrix *computeCovarianceMatrix(\n    const Conformer &conf, const RDGeom::Point3D &center, bool normalize,\n    bool ignoreHs) {\n  double xx, xy, xz, yy, yz, zz;\n  computeCovarianceTerms(conf, center, xx, xy, xz, yy, yz, zz, normalize,\n                         ignoreHs, nullptr);\n  auto *res = new RDNumeric::DoubleSymmMatrix(3, 3);\n  res->setVal(0, 0, xx);\n  res->setVal(0, 1, xy);\n  res->setVal(0, 2, xz);\n  res->setVal(1, 1, yy);\n  res->setVal(1, 2, yz);\n  res->setVal(2, 2, zz);\n  return res;\n}\n\nvoid computeInertiaTerms(const Conformer &conf, const RDGeom::Point3D &center,\n                         double &xx, double &xy, double &xz, double &yy,\n                         double &yz, double &zz, bool ignoreHs,\n                         const std::vector<double> *weights) {\n  PRECONDITION(!weights || weights->size() >= conf.getNumAtoms(),\n               \"bad weights vector\");\n\n  xx = xy = xz = yy = yz = zz = 0.0;\n  const ROMol &mol = conf.getOwningMol();\n  for (ROMol::ConstAtomIterator cai = mol.beginAtoms(); cai != mol.endAtoms();\n       cai++) {\n    if (((*cai)->getAtomicNum() == 1) && (ignoreHs)) {\n      continue;\n    }\n    RDGeom::Point3D loc = conf.getAtomPos((*cai)->getIdx());\n    loc -= center;\n    double w = 1.0;\n    if (weights) {\n      w = (*weights)[(*cai)->getIdx()];\n    }\n    xx += w * (loc.y * loc.y + loc.z * loc.z);\n    yy += w * (loc.x * loc.x + loc.z * loc.z);\n    zz += w * (loc.y * loc.y + loc.x * loc.x);\n    xy -= w * loc.x * loc.y;\n    xz -= w * loc.x * loc.z;\n    yz -= w * loc.z * loc.y;\n  }\n}\n}\n#ifdef RDK_HAS_EIGEN3\n#include <Eigen/Dense>\n\nbool computePrincipalAxesAndMoments(const RDKit::Conformer &conf,\n                                    Eigen::Matrix3d &axes,\n                                    Eigen::Vector3d &moments, bool ignoreHs,\n                                    bool force,\n                                    const std::vector<double> *weights) {\n  PRECONDITION((!weights || weights->size() >= conf.getNumAtoms()),\n               \"bad weights vector\");\n  const char *axesPropName = ignoreHs ? \"_principalAxes_noH\" : \"_principalAxes\";\n  const char *momentsPropName =\n      ignoreHs ? \"_principalMoments_noH\" : \"_principalMoments\";\n  if (!weights && !force && conf.getOwningMol().hasProp(axesPropName) &&\n      conf.getOwningMol().hasProp(momentsPropName)) {\n    conf.getOwningMol().getProp(axesPropName, axes);\n    conf.getOwningMol().getProp(momentsPropName, moments);\n    return true;\n  }\n  const ROMol &mol = conf.getOwningMol();\n  RDGeom::Point3D origin(0, 0, 0);\n  double wSum = 0.0;\n  for (unsigned int i = 0; i < conf.getNumAtoms(); ++i) {\n    if (ignoreHs && mol.getAtomWithIdx(i)->getAtomicNum() == 1) continue;\n    double w = 1.0;\n    if (weights) {\n      w = (*weights)[i];\n    }\n    wSum += w;\n    origin += conf.getAtomPos(i) * w;\n  }\n  // std::cerr<<\"  origin: \"<<origin<<\" \"<<wSum<<std::endl;\n  origin /= wSum;\n\n  double sumXX, sumXY, sumXZ, sumYY, sumYZ, sumZZ;\n  computeInertiaTerms(conf, origin, sumXX, sumXY, sumXZ, sumYY, sumYZ, sumZZ,\n                      ignoreHs, weights);\n\n  Eigen::Matrix3d mat;\n  mat << sumXX, sumXY, sumXZ, sumXY, sumYY, sumYZ, sumXZ, sumYZ, sumZZ;\n  // std::cerr<<\"  matrix: \"<<mat<<std::endl;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(mat);\n  if (eigensolver.info() != Eigen::Success) {\n    BOOST_LOG(rdErrorLog) << \"eigenvalue calculation did not converge\"\n                          << std::endl;\n    return false;\n  }\n\n  axes = eigensolver.eigenvectors();\n  moments = eigensolver.eigenvalues();\n  if (!weights) {\n    conf.getOwningMol().setProp(axesPropName, axes, true);\n    conf.getOwningMol().setProp(momentsPropName, moments, true);\n  }\n  return true;\n}\nbool computePrincipalAxesAndMomentsFromGyrationMatrix(\n    const RDKit::Conformer &conf, Eigen::Matrix3d &axes,\n    Eigen::Vector3d &moments, bool ignoreHs, bool force,\n    const std::vector<double> *weights) {\n  PRECONDITION((!weights || weights->size() >= conf.getNumAtoms()),\n               \"bad weights vector\");\n  const char *axesPropName =\n      ignoreHs ? \"_principalAxes_noH_cov\" : \"_principalAxes_cov\";\n  const char *momentsPropName =\n      ignoreHs ? \"_principalMoments_noH_cov\" : \"_principalMoments_cov\";\n  if (!weights && !force && conf.getOwningMol().hasProp(axesPropName) &&\n      conf.getOwningMol().hasProp(momentsPropName)) {\n    conf.getOwningMol().getProp(axesPropName, axes);\n    conf.getOwningMol().getProp(momentsPropName, moments);\n    return true;\n  }\n  const ROMol &mol = conf.getOwningMol();\n  RDGeom::Point3D origin(0, 0, 0);\n  double wSum = 0.0;\n  for (unsigned int i = 0; i < conf.getNumAtoms(); ++i) {\n    if (ignoreHs && mol.getAtomWithIdx(i)->getAtomicNum() == 1) continue;\n    double w = 1.0;\n    if (weights) {\n      w = (*weights)[i];\n    }\n    wSum += w;\n    origin += conf.getAtomPos(i) * w;\n  }\n  // std::cerr<<\"  origin: \"<<origin<<\" \"<<wSum<<std::endl;\n  origin /= wSum;\n\n  double sumXX, sumXY, sumXZ, sumYY, sumYZ, sumZZ;\n  computeCovarianceTerms(conf, origin, sumXX, sumXY, sumXZ, sumYY, sumYZ, sumZZ,\n                         true, ignoreHs, weights);\n\n  Eigen::Matrix3d mat;\n  mat << sumXX, sumXY, sumXZ, sumXY, sumYY, sumYZ, sumXZ, sumYZ, sumZZ;\n  // std::cerr<<\"  matrix: \"<<mat<<std::endl;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(mat);\n  if (eigensolver.info() != Eigen::Success) {\n    BOOST_LOG(rdErrorLog) << \"eigenvalue calculation did not converge\"\n                          << std::endl;\n    return false;\n  }\n\n  axes = eigensolver.eigenvectors();\n  moments = eigensolver.eigenvalues();\n  if (!weights) {\n    conf.getOwningMol().setProp(axesPropName, axes, true);\n    conf.getOwningMol().setProp(momentsPropName, moments, true);\n  }\n  return true;\n}\n#endif\n\nRDGeom::Transform3D *computeCanonicalTransform(const Conformer &conf,\n                                               const RDGeom::Point3D *center,\n                                               bool normalizeCovar,\n                                               bool ignoreHs) {\n  RDGeom::Point3D origin;\n  if (!center) {\n    origin = computeCentroid(conf, ignoreHs);\n  } else {\n    origin = (*center);\n  }\n  RDNumeric::DoubleSymmMatrix *covMat =\n      computeCovarianceMatrix(conf, origin, normalizeCovar, ignoreHs);\n  // find the eigen values and eigen vectors for the covMat\n  RDNumeric::DoubleMatrix eigVecs(3, 3);\n  RDNumeric::DoubleVector eigVals(3);\n  // if we have a single atom system we don't need to do anyhting other than\n  // setting translation\n  // translation\n  unsigned int nAtms = conf.getNumAtoms();\n  auto *trans = new RDGeom::Transform3D;\n\n  // set the translation\n  origin *= -1.0;\n  // trans->SetTranslation(origin);\n  // if we have a single atom system we don't need to do anyhting setting\n  // translation is sufficient\n  if (nAtms > 1) {\n    RDNumeric::EigenSolvers::powerEigenSolver(3, *covMat, eigVals, eigVecs,\n                                              conf.getNumAtoms());\n    // deal with zero eigen value systems\n    unsigned int i, j, dim = 3;\n    for (i = 0; i < 3; ++i) {\n      // std::cerr<<\"  ev: \"<<i<<\": \"<<eigVals.getVal(i)<<std::endl;\n      if (fabs(eigVals.getVal(i)) < EIGEN_TOLERANCE) {\n        dim--;\n      }\n    }\n    CHECK_INVARIANT(dim >= 1, \"\");\n    if (dim < 3) {\n      RDGeom::Point3D first(eigVecs.getVal(0, 0), eigVecs.getVal(0, 1),\n                            eigVecs.getVal(0, 2));\n      if (dim == 1) {\n        // pick an arbitrary eigen vector perpendicular to the first vector\n        RDGeom::Point3D second(first.getPerpendicular());\n        eigVecs.setVal(1, 0, second.x);\n        eigVecs.setVal(1, 1, second.y);\n        eigVecs.setVal(1, 2, second.z);\n        if (eigVals.getVal(0) > 1.0) {\n          eigVals.setVal(1, 1.0);\n        } else {\n          eigVals.setVal(1, eigVals.getVal(0) / 2.0);\n        }\n      }\n      RDGeom::Point3D second(eigVecs.getVal(1, 0), eigVecs.getVal(1, 1),\n                             eigVecs.getVal(1, 2));\n      // pick the third eigen vector perpendicular to the first two\n      RDGeom::Point3D third = first.crossProduct(second);\n      eigVecs.setVal(2, 0, third.x);\n      eigVecs.setVal(2, 1, third.y);\n      eigVecs.setVal(2, 2, third.z);\n      if (eigVals.getVal(1) > 1.0) {\n        eigVals.setVal(2, 1.0);\n      } else {\n        eigVals.setVal(2, eigVals.getVal(1) / 2.0);\n      }\n    }\n    // now set the transformation\n    for (i = 0; i < 3; ++i) {\n      for (j = 0; j < 3; ++j) {\n        trans->setVal(i, j, eigVecs.getVal(i, j));\n      }\n    }\n  }  // end of multiple atom system\n  trans->TransformPoint(origin);\n  trans->SetTranslation(origin);\n  delete covMat;\n\n  return trans;\n}\n\nvoid transformConformer(Conformer &conf, const RDGeom::Transform3D &trans) {\n  RDGeom::POINT3D_VECT &positions = conf.getPositions();\n  RDGeom::POINT3D_VECT_I pi;\n  for (pi = positions.begin(); pi != positions.end(); ++pi) {\n    trans.TransformPoint(*pi);\n  }\n}\n\nvoid canonicalizeConformer(Conformer &conf, const RDGeom::Point3D *center,\n                           bool normalizeCovar, bool ignoreHs) {\n  RDGeom::Transform3D *trans =\n      computeCanonicalTransform(conf, center, normalizeCovar, ignoreHs);\n  transformConformer(conf, *trans);\n  delete trans;\n}\n\nvoid canonicalizeMol(RDKit::ROMol &mol, bool normalizeCovar, bool ignoreHs) {\n  ROMol::ConformerIterator ci;\n  for (ci = mol.beginConformers(); ci != mol.endConformers(); ci++) {\n    canonicalizeConformer(*(*ci), nullptr, normalizeCovar, ignoreHs);\n  }\n}\n\nnamespace {\nvoid _toBeMovedIdxList(const ROMol &mol, unsigned int iAtomId,\n                       unsigned int jAtomId, std::list<unsigned int> &alist) {\n  unsigned int nAtoms = mol.getNumAtoms();\n  boost::dynamic_bitset<> visitedIdx(nAtoms);\n  std::stack<unsigned int> stack;\n  stack.push(jAtomId);\n  visitedIdx[iAtomId] = 1;\n  visitedIdx[jAtomId] = 1;\n  unsigned int tIdx;\n  unsigned int wIdx;\n  ROMol::ADJ_ITER nbrIdx;\n  ROMol::ADJ_ITER endNbrs;\n  bool doMainLoop;\n  while (stack.size()) {\n    doMainLoop = false;\n    tIdx = stack.top();\n    const Atom *tAtom = mol.getAtomWithIdx(tIdx);\n    boost::tie(nbrIdx, endNbrs) = mol.getAtomNeighbors(tAtom);\n    unsigned int eIdx;\n    for (eIdx = 0; nbrIdx != endNbrs; ++nbrIdx, ++eIdx) {\n      wIdx = (mol[*nbrIdx])->getIdx();\n      if (!visitedIdx[wIdx]) {\n        visitedIdx[wIdx] = 1;\n        stack.push(wIdx);\n        doMainLoop = true;\n        break;\n      }\n    }\n    if (doMainLoop) {\n      continue;\n    }\n    visitedIdx[tIdx] = 1;\n    stack.pop();\n  }\n  alist.clear();\n  for (unsigned int i = 0; i < nAtoms; ++i) {\n    if (visitedIdx[i] && (i != iAtomId)) {\n      alist.push_back(i);\n    }\n  }\n}\n}\ndouble getBondLength(const Conformer &conf, unsigned int iAtomId,\n                     unsigned int jAtomId) {\n  const RDGeom::POINT3D_VECT &pos = conf.getPositions();\n  URANGE_CHECK(iAtomId, pos.size());\n  URANGE_CHECK(jAtomId, pos.size());\n\n  return (pos[iAtomId] - pos[jAtomId]).length();\n}\n\nvoid setBondLength(Conformer &conf, unsigned int iAtomId, unsigned int jAtomId,\n                   double value) {\n  RDGeom::POINT3D_VECT &pos = conf.getPositions();\n  URANGE_CHECK(iAtomId, pos.size());\n  URANGE_CHECK(jAtomId, pos.size());\n  ROMol &mol = conf.getOwningMol();\n  Bond *bond = mol.getBondBetweenAtoms(iAtomId, jAtomId);\n  if (!bond) throw ValueErrorException(\"atoms i and j must be bonded\");\n  if (queryIsBondInRing(bond))\n    throw ValueErrorException(\"bond (i,j) must not belong to a ring\");\n  RDGeom::Point3D v = pos[iAtomId] - pos[jAtomId];\n  double origValue = v.length();\n  if (origValue <= 1.e-8)\n    throw ValueErrorException(\"atoms i and j have identical 3D coordinates\");\n\n  // get all atoms bonded to j\n  std::list<unsigned int> alist;\n  _toBeMovedIdxList(mol, iAtomId, jAtomId, alist);\n  v *= (value / origValue - 1.);\n  for (unsigned int &it : alist) {\n    pos[it] -= v;\n  }\n}\n\ndouble getAngleRad(const Conformer &conf, unsigned int iAtomId,\n                   unsigned int jAtomId, unsigned int kAtomId) {\n  const RDGeom::POINT3D_VECT &pos = conf.getPositions();\n  URANGE_CHECK(iAtomId, pos.size());\n  URANGE_CHECK(jAtomId, pos.size());\n  URANGE_CHECK(kAtomId, pos.size());\n  RDGeom::Point3D rJI = pos[iAtomId] - pos[jAtomId];\n  double rJISqLength = rJI.lengthSq();\n  if (rJISqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms i and j have identical 3D coordinates\");\n  RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId];\n  double rJKSqLength = rJK.lengthSq();\n  if (rJKSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms j and k have identical 3D coordinates\");\n  return rJI.angleTo(rJK);\n}\n\nvoid setAngleRad(Conformer &conf, unsigned int iAtomId, unsigned int jAtomId,\n                 unsigned int kAtomId, double value) {\n  RDGeom::POINT3D_VECT &pos = conf.getPositions();\n  URANGE_CHECK(iAtomId, pos.size());\n  URANGE_CHECK(jAtomId, pos.size());\n  URANGE_CHECK(kAtomId, pos.size());\n  ROMol &mol = conf.getOwningMol();\n  Bond *bondJI = mol.getBondBetweenAtoms(jAtomId, iAtomId);\n  if (!bondJI) throw ValueErrorException(\"atoms i and j must be bonded\");\n  Bond *bondJK = mol.getBondBetweenAtoms(jAtomId, kAtomId);\n  if (!bondJK) throw ValueErrorException(\"atoms j and k must be bonded\");\n  if (queryIsBondInRing(bondJI) && queryIsBondInRing(bondJK))\n    throw ValueErrorException(\n        \"bonds (i,j) and (j,k) must not both belong to a ring\");\n\n  RDGeom::Point3D rJI = pos[iAtomId] - pos[jAtomId];\n  double rJISqLength = rJI.lengthSq();\n  if (rJISqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms i and j have identical 3D coordinates\");\n  RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId];\n  double rJKSqLength = rJK.lengthSq();\n  if (rJKSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms j and k have identical 3D coordinates\");\n\n  // we only need to rotate by delta with respect to the current angle value\n  value -= rJI.angleTo(rJK);\n  RDGeom::Point3D &rotAxisBegin = pos[jAtomId];\n  // our rotation axis is the normal to the plane of atoms i, j, k\n  RDGeom::Point3D rotAxisEnd = rJI.crossProduct(rJK) + pos[jAtomId];\n  RDGeom::Point3D rotAxis = rotAxisEnd - rotAxisBegin;\n  rotAxis.normalize();\n  // get all atoms bonded to j and loop through them\n  std::list<unsigned int> alist;\n  _toBeMovedIdxList(mol, jAtomId, kAtomId, alist);\n  for (unsigned int &it : alist) {\n    // translate atom so that it coincides with the origin of rotation\n    pos[it] -= rotAxisBegin;\n    // rotate around our rotation axis\n    RDGeom::Transform3D rotByAngle;\n    rotByAngle.SetRotation(value, rotAxis);\n    rotByAngle.TransformPoint(pos[it]);\n    // translate atom back\n    pos[it] += rotAxisBegin;\n  }\n}\n\ndouble getDihedralRad(const Conformer &conf, unsigned int iAtomId,\n                      unsigned int jAtomId, unsigned int kAtomId,\n                      unsigned int lAtomId) {\n  const RDGeom::POINT3D_VECT &pos = conf.getPositions();\n  URANGE_CHECK(iAtomId, pos.size());\n  URANGE_CHECK(jAtomId, pos.size());\n  URANGE_CHECK(kAtomId, pos.size());\n  URANGE_CHECK(lAtomId, pos.size());\n  RDGeom::Point3D rIJ = pos[jAtomId] - pos[iAtomId];\n  double rIJSqLength = rIJ.lengthSq();\n  if (rIJSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms i and j have identical 3D coordinates\");\n  RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId];\n  double rJKSqLength = rJK.lengthSq();\n  if (rJKSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms j and k have identical 3D coordinates\");\n  RDGeom::Point3D rKL = pos[lAtomId] - pos[kAtomId];\n  double rKLSqLength = rKL.lengthSq();\n  if (rKLSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms k and l have identical 3D coordinates\");\n\n  RDGeom::Point3D nIJK = rIJ.crossProduct(rJK);\n  double nIJKSqLength = nIJK.lengthSq();\n  RDGeom::Point3D nJKL = rJK.crossProduct(rKL);\n  double nJKLSqLength = nJKL.lengthSq();\n  RDGeom::Point3D m = nIJK.crossProduct(rJK);\n  // we want a signed dihedral, that's why we use atan2 instead of acos\n  return -atan2(m.dotProduct(nJKL) / sqrt(nJKLSqLength * m.lengthSq()),\n                nIJK.dotProduct(nJKL) / sqrt(nIJKSqLength * nJKLSqLength));\n}\n\nvoid setDihedralRad(Conformer &conf, unsigned int iAtomId, unsigned int jAtomId,\n                    unsigned int kAtomId, unsigned int lAtomId, double value) {\n  RDGeom::POINT3D_VECT &pos = conf.getPositions();\n  URANGE_CHECK(iAtomId, pos.size());\n  URANGE_CHECK(jAtomId, pos.size());\n  URANGE_CHECK(kAtomId, pos.size());\n  URANGE_CHECK(lAtomId, pos.size());\n  ROMol &mol = conf.getOwningMol();\n  Bond *bondJK = mol.getBondBetweenAtoms(jAtomId, kAtomId);\n  if (!bondJK) throw ValueErrorException(\"atoms j and k must be bonded\");\n\n  if (queryIsBondInRing(bondJK))\n    throw ValueErrorException(\"bond (j,k) must not belong to a ring\");\n  RDGeom::Point3D rIJ = pos[jAtomId] - pos[iAtomId];\n  double rIJSqLength = rIJ.lengthSq();\n  if (rIJSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms i and j have identical 3D coordinates\");\n  RDGeom::Point3D rJK = pos[kAtomId] - pos[jAtomId];\n  double rJKSqLength = rJK.lengthSq();\n  if (rJKSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms j and k have identical 3D coordinates\");\n  RDGeom::Point3D rKL = pos[lAtomId] - pos[kAtomId];\n  double rKLSqLength = rKL.lengthSq();\n  if (rKLSqLength <= 1.e-16)\n    throw ValueErrorException(\"atoms k and l have identical 3D coordinates\");\n\n  RDGeom::Point3D nIJK = rIJ.crossProduct(rJK);\n  double nIJKSqLength = nIJK.lengthSq();\n  RDGeom::Point3D nJKL = rJK.crossProduct(rKL);\n  double nJKLSqLength = nJKL.lengthSq();\n  RDGeom::Point3D m = nIJK.crossProduct(rJK);\n  // we only need to rotate by delta with respect to the current dihedral value\n  value -= -atan2(m.dotProduct(nJKL) / sqrt(nJKLSqLength * m.lengthSq()),\n                  nIJK.dotProduct(nJKL) / sqrt(nIJKSqLength * nJKLSqLength));\n  // our rotation axis is the (j,k) bond\n  RDGeom::Point3D &rotAxisBegin = pos[jAtomId];\n  RDGeom::Point3D &rotAxisEnd = pos[kAtomId];\n  RDGeom::Point3D rotAxis = rotAxisEnd - rotAxisBegin;\n  rotAxis.normalize();\n  // get all atoms bonded to k and loop through them\n  std::list<unsigned int> alist;\n  _toBeMovedIdxList(mol, jAtomId, kAtomId, alist);\n  for (unsigned int &it : alist) {\n    // translate atom so that it coincides with the origin of rotation\n    pos[it] -= rotAxisBegin;\n    // rotate around our rotation axis\n    RDGeom::Transform3D rotByAngle;\n    rotByAngle.SetRotation(value, rotAxis);\n    rotByAngle.TransformPoint(pos[it]);\n    // translate atom back\n    pos[it] += rotAxisBegin;\n  }\n}\n}\n", "meta": {"hexsha": "618795db366585aefa10775aec055fd421514143", "size": 21338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modified_rdkit/Code/GraphMol/MolTransforms/MolTransforms.cpp", "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/MolTransforms/MolTransforms.cpp", "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/MolTransforms/MolTransforms.cpp", "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": 36.5376712329, "max_line_length": 80, "alphanum_fraction": 0.6367044709, "num_tokens": 6469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.035144847664027534, "lm_q1q2_score": 0.01743514206381952}}
{"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 <ored/marketdata/strike.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ored/utilities/to_string.hpp>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/serialization/export.hpp>\n\nusing namespace QuantLib;\nusing std::ostream;\nusing std::ostringstream;\nusing std::string;\nusing std::vector;\n\nnamespace ore {\nnamespace data {\n\nbool operator==(const BaseStrike& lhs, const BaseStrike& rhs) { return lhs.equal_to(rhs); }\n\nAbsoluteStrike::AbsoluteStrike() {}\n\nAbsoluteStrike::AbsoluteStrike(Real strike) : strike_(strike) {}\n\nReal AbsoluteStrike::strike() const { return strike_; }\n\nvoid AbsoluteStrike::fromString(const string& strStrike) { strike_ = parseReal(strStrike); }\n\nstring AbsoluteStrike::toString() const { return to_string(strike_); }\n\nbool AbsoluteStrike::equal_to(const BaseStrike& other) const {\n    if (const AbsoluteStrike* p = dynamic_cast<const AbsoluteStrike*>(&other)) {\n        return close(strike_, p->strike());\n    } else {\n        return false;\n    }\n}\n\nDeltaStrike::DeltaStrike() : deltaType_(DeltaVolQuote::Spot), optionType_(Option::Call) {}\n\nDeltaStrike::DeltaStrike(DeltaVolQuote::DeltaType deltaType, Option::Type optionType, Real delta)\n    : deltaType_(deltaType), optionType_(optionType), delta_(delta) {}\n\nDeltaVolQuote::DeltaType DeltaStrike::deltaType() const { return deltaType_; }\n\nOption::Type DeltaStrike::optionType() const { return optionType_; }\n\nReal DeltaStrike::delta() const { return delta_; }\n\nvoid DeltaStrike::fromString(const string& strStrike) {\n\n    // Expect strStrike of form: DEL / Spot|Fwd|PaSpot|PaFwd / Call|Put / DELTA_VALUE\n    vector<string> tokens;\n    boost::split(tokens, strStrike, boost::is_any_of(\"/\"));\n    QL_REQUIRE(tokens.size() == 4, \"DeltaStrike::fromString expects 4 tokens.\");\n    QL_REQUIRE(tokens[0] == \"DEL\", \"DeltaStrike::fromString expects 1st token to equal 'DEL'.\");\n\n    deltaType_ = parseDeltaType(tokens[1]);\n    optionType_ = parseOptionType(tokens[2]);\n    delta_ = parseReal(tokens[3]);\n}\n\nstring DeltaStrike::toString() const {\n\n    // Write string of form: DEL / Spot|Fwd|PaSpot|PaFwd / Call|Put / DELTA_VALUE\n    ostringstream oss;\n    oss << \"DEL/\" << deltaType_ << \"/\" << optionType_ << \"/\" << to_string(delta_);\n    return oss.str();\n}\n\nbool DeltaStrike::equal_to(const BaseStrike& other) const {\n    if (const DeltaStrike* p = dynamic_cast<const DeltaStrike*>(&other)) {\n        return deltaType_ == p->deltaType() && optionType_ == p->optionType() && close(delta_, p->delta());\n    } else {\n        return false;\n    }\n}\n\nAtmStrike::AtmStrike() : atmType_(DeltaVolQuote::AtmSpot) {}\n\nAtmStrike::AtmStrike(DeltaVolQuote::AtmType atmType, boost::optional<DeltaVolQuote::DeltaType> deltaType)\n    : atmType_(atmType), deltaType_(deltaType) {\n    check();\n}\n\nDeltaVolQuote::AtmType AtmStrike::atmType() const { return atmType_; }\n\nboost::optional<DeltaVolQuote::DeltaType> AtmStrike::deltaType() const { return deltaType_; }\n\nvoid AtmStrike::fromString(const string& strStrike) {\n\n    // Expect strStrike of form:\n    // \"ATM / AtmSpot|AtmFwd|AtmDeltaNeutral|AtmVegaMax|AtmGammaMax|AtmPutCall50\"\n    // with an optional following \"/ DEL / Spot|Fwd|PaSpot|PaFwd\"\n    vector<string> tokens;\n    boost::split(tokens, strStrike, boost::is_any_of(\"/\"));\n    QL_REQUIRE(tokens.size() == 2 || tokens.size() == 4, \"AtmStrike::fromString expects 2 or 4 tokens.\");\n    QL_REQUIRE(tokens[0] == \"ATM\", \"AtmStrike::fromString expects 1st token to equal 'ATM'.\");\n\n    atmType_ = parseAtmType(tokens[1]);\n\n    deltaType_ = boost::none;\n    if (tokens.size() == 4) {\n        QL_REQUIRE(tokens[2] == \"DEL\", \"AtmStrike::fromString expects 3rd token to equal 'DEL'.\");\n        deltaType_ = parseDeltaType(tokens[3]);\n    }\n\n    check();\n}\n\nstring AtmStrike::toString() const {\n\n    // Write strike of form:\n    // \"ATM / AtmSpot|AtmFwd|AtmDeltaNeutral|AtmVegaMax|AtmGammaMax|AtmPutCall50\"\n    // with an optional following \"/ DEL / Spot|Fwd|PaSpot|PaFwd\" if delta type is populated.\n    ostringstream oss;\n    oss << \"ATM/\" << atmType_;\n\n    if (deltaType_) {\n        oss << \"/DEL/\" << (*deltaType_);\n    }\n\n    return oss.str();\n}\n\nbool AtmStrike::equal_to(const BaseStrike& other) const {\n    if (const AtmStrike* p = dynamic_cast<const AtmStrike*>(&other)) {\n        return !(atmType_ != p->atmType() || (deltaType_ && !p->deltaType()) || (!deltaType_ && p->deltaType()) ||\n                 *deltaType_ != *p->deltaType());\n    } else {\n        return false;\n    }\n}\n\nvoid AtmStrike::check() const {\n    QL_REQUIRE(atmType_ != DeltaVolQuote::AtmNull, \"AtmStrike type must not be AtmNull.\");\n    if (atmType_ == DeltaVolQuote::AtmDeltaNeutral) {\n        QL_REQUIRE(deltaType_, \"If AtmStrike type is AtmDeltaNeutral, we need a delta type.\");\n    } else {\n        QL_REQUIRE(!deltaType_, \"If AtmStrike type is not AtmDeltaNeutral, delta type should not be given.\");\n    }\n    if (atmType_ == DeltaVolQuote::AtmPutCall50) {\n        QL_REQUIRE(deltaType_ && *deltaType_ == DeltaVolQuote::Fwd,\n                   \"If AtmStrike type is AtmPutCall50, delta type must be AtmFwd.\");\n    }\n}\n\nMoneynessStrike::MoneynessStrike() : type_(Type::Spot) {}\n\nMoneynessStrike::MoneynessStrike(Type type, Real moneyness) : type_(type), moneyness_(moneyness) {}\n\nMoneynessStrike::Type MoneynessStrike::type() const { return type_; }\n\nReal MoneynessStrike::moneyness() const { return moneyness_; }\n\nvoid MoneynessStrike::fromString(const string& strStrike) {\n\n    // Expect strStrike of form \"MNY / Spot|Fwd / MONEYNESS_VALUE\"\n    vector<string> tokens;\n    boost::split(tokens, strStrike, boost::is_any_of(\"/\"));\n    QL_REQUIRE(tokens.size() == 3, \"MoneynessStrike::fromString expects 3 tokens.\");\n    QL_REQUIRE(tokens[0] == \"MNY\", \"MoneynessStrike::fromString expects 1st token to equal 'MNY'.\");\n\n    type_ = parseMoneynessType(tokens[1]);\n    moneyness_ = parseReal(tokens[2]);\n}\n\nstring MoneynessStrike::toString() const {\n\n    // Write strike of form \"MNY / Spot|Fwd / MONEYNESS_VALUE\"\n    ostringstream oss;\n    oss << \"MNY/\" << type_ << \"/\" << to_string(moneyness_);\n    return oss.str();\n}\n\nbool MoneynessStrike::equal_to(const BaseStrike& other) const {\n    if (const MoneynessStrike* p = dynamic_cast<const MoneynessStrike*>(&other)) {\n        return type_ == p->type() && close(moneyness_, p->moneyness());\n    } else {\n        return false;\n    }\n}\n\nostream& operator<<(ostream& os, const BaseStrike& strike) { return os << strike.toString(); }\n\nostream& operator<<(ostream& os, DeltaVolQuote::DeltaType type) {\n    switch (type) {\n    case DeltaVolQuote::Spot:\n        return os << \"Spot\";\n    case DeltaVolQuote::Fwd:\n        return os << \"Fwd\";\n    case DeltaVolQuote::PaSpot:\n        return os << \"PaSpot\";\n    case DeltaVolQuote::PaFwd:\n        return os << \"PaFwd\";\n    default:\n        QL_FAIL(\"Unknown delta type\");\n    }\n}\n\nostream& operator<<(ostream& os, DeltaVolQuote::AtmType type) {\n    switch (type) {\n    case DeltaVolQuote::AtmNull:\n        return os << \"AtmNull\";\n    case DeltaVolQuote::AtmSpot:\n        return os << \"AtmSpot\";\n    case DeltaVolQuote::AtmFwd:\n        return os << \"AtmFwd\";\n    case DeltaVolQuote::AtmDeltaNeutral:\n        return os << \"AtmDeltaNeutral\";\n    case DeltaVolQuote::AtmVegaMax:\n        return os << \"AtmVegaMax\";\n    case DeltaVolQuote::AtmGammaMax:\n        return os << \"AtmGammaMax\";\n    case DeltaVolQuote::AtmPutCall50:\n        return os << \"AtmPutCall50\";\n    default:\n        QL_FAIL(\"Unknown atm type\");\n    }\n}\n\nostream& operator<<(ostream& os, MoneynessStrike::Type type) {\n    switch (type) {\n    case MoneynessStrike::Type::Spot:\n        return os << \"Spot\";\n    case MoneynessStrike::Type::Forward:\n        return os << \"Fwd\";\n    default:\n        QL_FAIL(\"Unknown moneyness type\");\n    }\n}\n\nMoneynessStrike::Type parseMoneynessType(const string& type) {\n    if (type == \"Spot\") {\n        return MoneynessStrike::Type::Spot;\n    } else if (type == \"Fwd\") {\n        return MoneynessStrike::Type::Forward;\n    } else {\n        QL_FAIL(\"Moneyness type '\" << type << \"' not recognized\");\n    }\n}\n\nboost::shared_ptr<BaseStrike> parseBaseStrike(const string& strStrike) {\n\n    boost::shared_ptr<BaseStrike> strike;\n\n    // Expect strStrike to either:\n    // 1. have a single token which means that we have an absolute strike, or\n    // 2. have multiple tokens beginning with one of DEL, ATM or MNY\n    vector<string> tokens;\n    boost::split(tokens, strStrike, boost::is_any_of(\"/\"));\n\n    if (tokens.size() == 1) {\n        strike = boost::make_shared<AbsoluteStrike>();\n    } else if (tokens[0] == \"DEL\") {\n        strike = boost::make_shared<DeltaStrike>();\n    } else if (tokens[0] == \"ATM\") {\n        strike = boost::make_shared<AtmStrike>();\n    } else if (tokens[0] == \"MNY\") {\n        strike = boost::make_shared<MoneynessStrike>();\n    } else {\n        QL_FAIL(\"Could not parse strike string '\" << strStrike << \"'.\");\n    }\n\n    strike->fromString(strStrike);\n\n    return strike;\n}\n\n} // namespace data\n} // namespace ore\n\nBOOST_CLASS_EXPORT_GUID(ore::data::AbsoluteStrike, \"AbsoluteStrike\");\nBOOST_CLASS_EXPORT_GUID(ore::data::DeltaStrike, \"DeltaStrike\");\nBOOST_CLASS_EXPORT_GUID(ore::data::AtmStrike, \"AtmStrike\");\nBOOST_CLASS_EXPORT_GUID(ore::data::MoneynessStrike, \"MoneynessStrike\");\n", "meta": {"hexsha": "6da8f4cb3313c762c5c6c3cac7a9dc191097bad9", "size": 9988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/marketdata/strike.cpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "OREData/ored/marketdata/strike.cpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OREData/ored/marketdata/strike.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": 34.0887372014, "max_line_length": 114, "alphanum_fraction": 0.676411694, "num_tokens": 2732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.044018649392654464, "lm_q1q2_score": 0.01743438574680861}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2020 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014-2017 by Centre for Geoscience Computing (GeoComp)\n* Development from 2019 by School of Earth and Environmental Sciences\n**\n*****************************************************************************/\n\n#include \"Data.h\"\n#include \"WrappedArray.h\"\n#include \"DataException.h\"\n\n#if ESYS_HAVE_NUMPY_H\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include <numpy/ndarrayobject.h>\n#endif\n\n#include <iostream>\n\n#include <boost/python/tuple.hpp>\n\nusing namespace escript;\nusing namespace boost::python;\nusing DataTypes::cplx_t;\nusing DataTypes::real_t;\n\nnamespace\n{\n\nvoid checkFeatures(const boost::python::object& obj)\n{\n\tusing namespace std;\n\tboost::python::object o2;\n\ttry\n\t{\n\t   /*int len=*/ extract<int>(obj.attr(\"__len__\")());\n\t}\n\tcatch (...)\n\t{\n\t   PyErr_Clear();\n\t   throw DataException(\"Object passed to WrappedArray must support __len__\");\n\t}\n\ttry\n\t{\n\t   o2=obj.attr(\"__getitem__\");\n\t}\n\tcatch (...)\n\t{\n\t   PyErr_Clear();\n\t   throw DataException(\"Object passed to WrappedArray must support __getitem__\");\n\t}\n}\n\n\n// This should not be called on anything which does\n// not have a __len__\nbool checkForComplex(const boost::python::object& obj)\n{\n    try\n    {\n\tint len=extract<int>(obj.attr(\"__len__\")());\n\tfor (int i=0;i<len;++i)\n\t{\n\t    const boost::python::object t=obj[i];\n\t    bool haslen=false;\n\t    try\n            {\n\t        extract<int>(t.attr(\"__len__\")());\n\t        haslen=true;\n\t    }\n\t    catch(...)\n\t    {\n\t\tPyErr_Clear();\n\t    }\n\t    \t// If it has a length, we dig down\n\t\t// if not, we test for complex\n\t    if (haslen)\n\t    {\n                if (checkForComplex(t))\n\t\t{\n\t\t    return true;\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\textract<DataTypes::real_t> er(t);\n\t\tif (!er.check())\n\t\t{\n\t\t    // unfortunately, if this was a numpy object, that check my fail\n\t\t    // even if it should succeed (eg numpy.int64 on python3)\n\t\t    // instead, we will try to call __float__ and see what happens\n\t\t    try\n\t\t    {\n\t\t\tt.attr(\"__float__\")();\n\t\t\treturn false;\t\t\t// if this check succeeds it isn't complex\n\t\t    }\n\t\t    catch (...)\n\t\t    {\n\t\t\tPyErr_Clear();\n\t\t\t// at this point, we have no apparent way to get a real out so \n\t\t\t// we assume it must be complex\n\t\t\treturn true;\n\t\t    }\n\t\t}\n\t    }\n\t}\n\treturn false;\n    }\n    catch(...)\n    {\n        PyErr_Clear();\n\treturn false;\n    }\n    return false;\n}\n\nvoid getObjShape(const boost::python::object& obj, DataTypes::ShapeType& s)\n{\n\tint len=0;\n\ttry\n\t{\n\t   len=extract<int>(obj.attr(\"__len__\")());\n\t}\n\tcatch(...)\n\t{\n\t   PyErr_Clear();\t\t// tell python the error isn't there anymore\n\t   return;\n\t}\n\tif (len<1)\n\t{\n\t   throw DataException(\"Array filter - no empty components in arrays please.\");\n\t}\n\ts.push_back(len);\t\n\n\tif (s.size()>ESCRIPT_MAX_DATA_RANK)\n\t{\n\t   throw DataException(\"Array filter - Maximum rank exceeded in array\");\n\t}\n\tgetObjShape(obj[0],s);\n}\n\n}\n\nWrappedArray::WrappedArray(const boost::python::object& obj_in)\n:obj(obj_in),converted(false),iscomplex(false),scalar_r(nan(\"\")),scalar_c(nan(\"\"))\n{\n\tdat_r=0;\n\tdat_c=0;\n\t// First we check for scalars\n\ttry\n\t{\n\t   extract<DataTypes::cplx_t> ec(obj_in);\n\t   extract<real_t> er(obj_in);\n\t   if (er.check())\t\t// check for real_t first because complex will fail this\n\t   {\n\t      scalar_r=er();\n\t   }\n\t   else\n\t   {\n\t      scalar_c=ec();\n\t      iscomplex=true;\n\t     \n\t   }\n\t   rank=0;\n\t   return;\n\t} \n\tcatch (...)\n\t{\t\t// so we clear the failure\n\t   PyErr_Clear();\n\t}\n\ttry\n\t{\n\t   const boost::python::object obj_in_t=obj_in[make_tuple()];\n\t   extract<DataTypes::cplx_t> ec(obj_in_t);\n\t   extract<real_t> er(obj_in_t);\n\t   if (er.check())\n\t   {\t     \n\t      scalar_r=er();\n\t     \n\t   }\n\t   else\n\t   {\n\t      scalar_c=ec();\n\t      iscomplex=true;\n\t   }\t   \n\t   rank=0;\n\t   return;\n\t} \n\tcatch (...)\n\t{\t\t// so we clear the failure\n\t   PyErr_Clear();\n\t}\n\n\n\tscalar_c=0;\n\tscalar_r=0;\n\tcheckFeatures(obj_in);\n\tgetObjShape(obj,shape);\n\trank=shape.size();\n\tiscomplex=checkForComplex(obj_in);\n\n#if ESYS_HAVE_NUMPY_H\n\t// if obj is a numpy array it is much faster to copy the array through the\n\t// __array_struct__ interface instead of extracting single values from the\n\t// components via getElt(). For this to work we check below that\n\t// (1) this is a valid PyArrayInterface instance\n\t// (2) the data is stored as a contiguous C array\n\t// (3) the data type is suitable (correct type and byte size)\n\ttry\n\t{\n\t\tobject o = (extract<object>(obj.attr(\"__array_struct__\")));\n#ifdef ESPYTHON3\n\t\tif (PyCapsule_CheckExact(o.ptr()))\n#else\n\t\tif (PyCObject_Check(o.ptr()))\n#endif\n\t\t{\n\t\t\tPyObject* cobj=(PyObject*)o.ptr();\n#ifdef ESPYTHON3\n            const char* name = PyCapsule_GetName(cobj);\n\t\t\tPyArrayInterface* arr=(PyArrayInterface*)PyCapsule_GetPointer(cobj, name);\n#else\n\t\t\tPyArrayInterface* arr=(PyArrayInterface*)PyCObject_AsVoidPtr(cobj);\n#endif\n#ifndef NPY_1_7_API_VERSION\n  #define NPY_ARRAY_IN_ARRAY NPY_IN_ARRAY\n  #define NPY_ARRAY_NOTSWAPPED NPY_NOTSWAPPED\n#endif\n\t\t\tif (arr->two==2 && arr->flags&NPY_ARRAY_IN_ARRAY && arr->flags&NPY_ARRAY_NOTSWAPPED)\n\t\t\t{\n\t\t\t\tstd::vector<int> strides;\n\t\t\t\t// convert #bytes to #elements\n\t\t\t\tfor (int i=0; i<arr->nd; i++)\n\t\t\t\t{\n\t\t\t\t\tstrides.push_back(arr->strides[i]/arr->itemsize);\n\t\t\t\t}\n\n\t\t\t\tif (arr->typekind == 'f')\n\t\t\t\t{\n\t\t\t\t\tif (arr->itemsize==sizeof(real_t))\n\t\t\t\t\t{\n\t\t\t\t\t\tconvertNumpyArray<real_t>((const real_t*)arr->data, strides);\n\t\t\t\t\t}\n\t\t\t\t\telse if (arr->itemsize==sizeof(float))\n\t\t\t   \t\t{\n\t\t\t\t\t\tconvertNumpyArray<float>((const float*)arr->data, strides);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (arr->typekind == 'i')\n\t\t\t\t{\n\t\t\t\t\tif (arr->itemsize==sizeof(int))\n\t\t\t\t   \t{\n\t\t\t\t\t\tconvertNumpyArray<int>((const int*)arr->data, strides);\n\t\t\t\t\t}\n\t\t\t\t\telse if (arr->itemsize==sizeof(long))\n\t\t\t\t   \t{\n\t\t\t\t\t\tconvertNumpyArray<long>((const long*)arr->data, strides);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (arr->typekind == 'u')\n\t\t\t\t{\n\t\t\t\t\tif (arr->itemsize==sizeof(unsigned))\n\t\t\t\t   \t{\n\t\t\t\t\t\tconvertNumpyArray<unsigned>((const unsigned*)arr->data, strides);\n\t\t\t\t\t}\n\t\t\t\t\telse if (arr->itemsize==sizeof(unsigned long))\n\t\t\t\t   \t{\n\t\t\t\t\t\tconvertNumpyArray<unsigned long>((const unsigned long*)arr->data, strides);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (arr->typekind == 'c')\n\t\t\t\t{\n\t\t\t\t\tif (arr->itemsize==sizeof(cplx_t))\n\t\t\t\t   \t{\n\t\t\t\t\t\tconvertNumpyArrayC<DataTypes::cplx_t>((const cplx_t*)arr->data, strides);\n\t\t\t\t\t\tiscomplex=true;\n\t\t\t\t\t}\n\t\t\t\t\t// not accomodating other types of complex values\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t}\n\t} catch (...)\n\t{\n\t\tPyErr_Clear();\n\t}\n#endif\n}\n\n\ntemplate<typename T>\nvoid WrappedArray::convertNumpyArrayC(const T* array, const std::vector<int>& strides) const\n{\n\t// this method is only called by the constructor above which does the\n\t// necessary checks and initialisations\n\tint size=DataTypes::noValues(shape);\n\tdat_c=new cplx_t[size];\n\tswitch (rank)\n\t{\n\t\tcase 1:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tdat_c[i]=array[i*strides[0]];\n\t\t\t}\n\t\tbreak;\n\t\tcase 2:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tfor (int j=0;j<shape[1];j++)\n\t\t\t\t{\n\t\t\t\t\tdat_c[DataTypes::getRelIndex(shape,i,j)]=array[i*strides[0]+j*strides[1]];\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase 3:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tfor (int j=0;j<shape[1];j++)\n\t\t\t\t{\n\t\t\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tdat_c[DataTypes::getRelIndex(shape,i,j,k)]=array[i*strides[0]+j*strides[1]+k*strides[2]];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase 4:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tfor (int j=0;j<shape[1];j++)\n\t\t\t\t{\n\t\t\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int m=0;m<shape[3];m++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdat_c[DataTypes::getRelIndex(shape,i,j,k,m)]=array[i*strides[0]+j*strides[1]+k*strides[2]+m*strides[3]];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t}\n}\n\n\ntemplate<typename T>\nvoid WrappedArray::convertNumpyArray(const T* array, const std::vector<int>& strides) const\n{\n\t// this method is only called by the constructor above which does the\n\t// necessary checks and initialisations\n\tint size=DataTypes::noValues(shape);\n\tdat_r=new real_t[size];\n\tswitch (rank)\n\t{\n\t\tcase 1:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tdat_r[i]=array[i*strides[0]];\n\t\t\t}\n\t\tbreak;\n\t\tcase 2:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tfor (int j=0;j<shape[1];j++)\n\t\t\t\t{\n\t\t\t\t\tdat_r[DataTypes::getRelIndex(shape,i,j)]=array[i*strides[0]+j*strides[1]];\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase 3:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tfor (int j=0;j<shape[1];j++)\n\t\t\t\t{\n\t\t\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tdat_r[DataTypes::getRelIndex(shape,i,j,k)]=array[i*strides[0]+j*strides[1]+k*strides[2]];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase 4:\n#pragma omp parallel for\n\t\t\tfor (int i=0;i<shape[0];i++)\n\t\t\t{\n\t\t\t\tfor (int j=0;j<shape[1];j++)\n\t\t\t\t{\n\t\t\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int m=0;m<shape[3];m++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdat_r[DataTypes::getRelIndex(shape,i,j,k,m)]=array[i*strides[0]+j*strides[1]+k*strides[2]+m*strides[3]];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t}\n}\n\n\nvoid WrappedArray::convertArrayR() const\n{\n\tif ((converted) || (rank<=0) || (rank>4))\t// checking illegal rank here to avoid memory issues later\n\t{\t\t\t\t\t// yes the failure is silent here but not doing the copy \n\t    return;\t\t\t\t// will just cause an error to be raised later\n\t}\n\tint size=DataTypes::noValues(shape);\n\treal_t* tdat=new real_t[size];\n\tswitch (rank)\n\t{\n\tcase 1: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t\ttdat[i]=getElt(i);\n\t\t}\n\t\tbreak;\n\tcase 2: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t    for (int j=0;j<shape[1];j++)\n\t\t    {\n\t\t\ttdat[DataTypes::getRelIndex(shape,i,j)]=getElt(i,j);\n\t\t    }\n\t\t}\n\t\tbreak;\n\tcase 3: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t    for (int j=0;j<shape[1];j++)\n\t\t    {\n\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t{\n\t\t\t    tdat[DataTypes::getRelIndex(shape,i,j,k)]=getElt(i,j,k);\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tbreak;\n\tcase 4: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t    for (int j=0;j<shape[1];j++)\n\t\t    {\n\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t{\n\t\t\t    for (int m=0;m<shape[3];m++)\n\t\t\t    {\n\t\t\t    \ttdat[DataTypes::getRelIndex(shape,i,j,k,m)]=getElt(i,j,k,m);\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\t;  // do nothing\n\t\t// can't happen. We've already checked the bounds above\n\t}\n\tdat_r=tdat;    \n\tconverted=true;\n}  \n\n\nvoid WrappedArray::convertArrayC() const\n{\n\tif ((converted) || (rank<=0) || (rank>4))\t// checking illegal rank here to avoid memory issues later\n\t{\t\t\t\t\t// yes the failure is silent here but not doing the copy \n\t    return;\t\t\t\t// will just cause an error to be raised later\n\t}\n\tint size=DataTypes::noValues(shape);\n\tcplx_t* tdat=new cplx_t[size];\n\tswitch (rank)\n\t{\n\tcase 1: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t\ttdat[i]=getElt(i);\n\t\t}\n\t\tbreak;\n\tcase 2: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t    for (int j=0;j<shape[1];j++)\n\t\t    {\n\t\t\ttdat[DataTypes::getRelIndex(shape,i,j)]=getElt(i,j);\n\t\t    }\n\t\t}\n\t\tbreak;\n\tcase 3: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t    for (int j=0;j<shape[1];j++)\n\t\t    {\n\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t{\n\t\t\t    tdat[DataTypes::getRelIndex(shape,i,j,k)]=getElt(i,j,k);\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tbreak;\n\tcase 4: for (int i=0;i<shape[0];i++)\n\t\t{\n\t\t    for (int j=0;j<shape[1];j++)\n\t\t    {\n\t\t\tfor (int k=0;k<shape[2];k++)\n\t\t\t{\n\t\t\t    for (int m=0;m<shape[3];m++)\n\t\t\t    {\n\t\t\t    \ttdat[DataTypes::getRelIndex(shape,i,j,k,m)]=getElt(i,j,k,m);\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\t;  // do nothing\n\t\t// can't happen. We've already checked the bounds above\n\t}\n\tdat_c=tdat;    \n\tconverted=true;\n}  \n\n\nvoid WrappedArray::convertArray() const\n{\n    if (iscomplex)\n    {\n\tconvertArrayC();\n    }\n    else\n    {\n\tconvertArrayR();\n    }\n}\n\nWrappedArray::~WrappedArray()\n{\n    if (dat_r!=0)\n    {\n\tdelete[] dat_r;\n    }\n    if (dat_c!=0)\n    {\n\tdelete[] dat_c;\n    }\n}\n\n\n", "meta": {"hexsha": "c1718e41050f137965ec0de32d9a4ca17db3d949", "size": 12031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "escriptcore/src/WrappedArray.cpp", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "escriptcore/src/WrappedArray.cpp", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "escriptcore/src/WrappedArray.cpp", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6384892086, "max_line_length": 111, "alphanum_fraction": 0.5913057934, "num_tokens": 3805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111975283019596, "lm_q2_score": 0.05261894777652015, "lm_q1q2_score": 0.01742317298194634}}
{"text": "/*\r\n boost/numeric/odeint/stepper/detail/pid_step_adjuster.hpp\r\n\r\n [begin_description]\r\n Implementation of the stepsize controller for the controlled adams bashforth moulton stepper.\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_HPP_INCLUDED\r\n#define BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_PID_STEP_ADJUSTER_HPP_INCLUDED\r\n\r\n#include <boost/numeric/odeint/stepper/detail/rotating_buffer.hpp>\r\n#include <boost/numeric/odeint/stepper/detail/pid_step_adjuster_coefficients.hpp>\r\n\r\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\r\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\r\n\r\n#include <math.h>\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\nnamespace detail {\r\n\r\ntemplate<\r\nclass Value = double,\r\nclass Time = double\r\n>\r\nstruct pid_op\r\n{\r\npublic:\r\n    typedef Value value_type;\r\n    typedef Time time_type;\r\n\r\n    const double beta1;\r\n    const double beta2;\r\n    const double beta3;\r\n    const double alpha1;\r\n    const double alpha2;\r\n\r\n    const time_type dt1;\r\n    const time_type dt2;\r\n    const time_type dt3;\r\n\r\n    const size_t m_steps;\r\n\r\n    pid_op(const size_t steps, const double _dt1, const double _dt2, const double _dt3,\r\n        const double b1 = 1, const double b2 = 0, const double b3 = 0, const double a1 = 0, const double a2 = 0)\r\n    :beta1(b1), beta2(b2), beta3(b3), alpha1(a1), alpha2(a2),\r\n    dt1(_dt1), dt2(_dt2), dt3(_dt3),\r\n    m_steps(steps)\r\n    {};\r\n\r\n    template<class T1, class T2, class T3, class T4>\r\n    void operator()(T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4)\r\n    {\r\n        using std::abs;\r\n\r\n        t1 = adapted_pow(abs(t2), -beta1/(m_steps + 1)) *\r\n            adapted_pow(abs(t3), -beta2/(m_steps + 1)) *\r\n            adapted_pow(abs(t4), -beta3/(m_steps + 1)) *\r\n            adapted_pow(abs(dt1/dt2), -alpha1/(m_steps + 1))*\r\n            adapted_pow(abs(dt2/dt3), -alpha2/(m_steps + 1));\r\n\r\n        t1 = 1/t1;\r\n    };\r\n\r\n    template<class T1, class T2>\r\n    void operator()(T1 &t1, const T2 &t2)\r\n    {\r\n        using std::abs;\r\n\r\n        t1 = adapted_pow(abs(t2), -beta1/(m_steps + 1));\r\n\r\n        t1 = 1/t1;\r\n    };\r\n\r\nprivate:\r\n    template<class T>\r\n    inline value_type adapted_pow(T base, double exp)\r\n    {\r\n        if(exp == 0)\r\n        {\r\n            return 1;\r\n        }\r\n        else if (exp > 0)\r\n        {\r\n            return pow(base, exp);\r\n        }\r\n        else\r\n        {\r\n            return 1/pow(base, -exp);\r\n        }\r\n    };\r\n};\r\n\r\ntemplate<\r\nclass State,\r\nclass Value = double,\r\nclass Deriv = State,\r\nclass Time = double,\r\nclass Algebra = typename algebra_dispatcher< State >::algebra_type,\r\nclass Operations = typename operations_dispatcher< Deriv >::operations_type,\r\nsize_t Type = BASIC\r\n>\r\nstruct pid_step_adjuster\r\n{\r\npublic:\r\n    static double threshold() { return 0.9; };\r\n\r\n    typedef State state_type;\r\n    typedef Value value_type;\r\n    typedef Deriv deriv_type;\r\n    typedef Time time_type;\r\n\r\n    typedef Algebra algebra_type;\r\n    typedef Operations operations_type;\r\n\r\n    typedef rotating_buffer<state_type, 3> error_storage_type;\r\n    typedef rotating_buffer<time_type, 3> time_storage_type;\r\n    typedef pid_step_adjuster_coefficients<Type> coeff_type;\r\n\r\n    pid_step_adjuster(double abs_tol = 1e-6, double rel_tol = 1e-6, time_type dtmax = 1.0)\r\n    :m_dtmax(dtmax), m_error_storage(), m_dt_storage(), m_init(0),\r\n    m_abs_tol(abs_tol), m_rel_tol(rel_tol)\r\n    {};\r\n\r\n    time_type adjust_stepsize(const size_t steps, time_type dt, state_type &err, const state_type &x, const deriv_type &dxdt)\r\n    {\r\n        using std::abs;\r\n        m_algebra.for_each3( err , x , dxdt ,\r\n                typename operations_type::template rel_error< value_type >( m_abs_tol , m_rel_tol , 1.0 , 1.0 * abs(get_unit_value( dt )) ) );\r\n\r\n        m_error_storage[0] = err;\r\n        m_dt_storage[0] = dt;\r\n\r\n        if(m_init >= 2)\r\n        {\r\n            m_algebra.for_each4(err, m_error_storage[0], m_error_storage[1], m_error_storage[2],\r\n                pid_op<>(steps, m_dt_storage[0], m_dt_storage[1], m_dt_storage[2],\r\n                    m_coeff[0], m_coeff[1], m_coeff[2], m_coeff[3], m_coeff[4]));\r\n        }\r\n        else\r\n        {\r\n            m_algebra.for_each2(err, m_error_storage[0],\r\n                pid_op<>(steps, m_dt_storage[0], m_dt_storage[1], m_dt_storage[2], 0.7));\r\n        }\r\n\r\n        value_type ratio = 1 / m_algebra.norm_inf(err);\r\n\r\n        value_type kappa = 1.0;\r\n        ratio = 1.0 + kappa*atan((ratio - 1) / kappa);\r\n\r\n        if(ratio*dt >= m_dtmax)\r\n        {\r\n            ratio = m_dtmax / dt;\r\n        }\r\n\r\n        if(ratio >= threshold())\r\n        {\r\n            m_error_storage.rotate();\r\n            m_dt_storage.rotate();\r\n\r\n            ++m_init;\r\n        }\r\n        else\r\n        {\r\n            m_init = 0;\r\n        }\r\n\r\n        return dt * static_cast<time_type>(ratio);\r\n    };\r\n\r\nprivate:\r\n    algebra_type m_algebra;\r\n\r\n    time_type m_dtmax;\r\n    error_storage_type m_error_storage;\r\n    time_storage_type m_dt_storage;\r\n\r\n    size_t m_init;\r\n    double m_abs_tol;\r\n    double m_rel_tol;\r\n\r\n    coeff_type m_coeff;\r\n};\r\n\r\n} // detail\r\n} // odeint\r\n} // numeric\r\n} // boost\r\n\r\n#endif", "meta": {"hexsha": "74bf8403c562b97ac768db48d61629fef64930f9", "size": 5404, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/numeric/odeint/stepper/detail/pid_step_adjuster.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.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.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": 27.1557788945, "max_line_length": 143, "alphanum_fraction": 0.6138045892, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.03567855421017194, "lm_q1q2_score": 0.01742124558898925}}
{"text": "#if 0\n// This is currently not used but left here in case it becomes useful.\n\n#ifndef SHASTA_DEBRUIJN_GRAPH_HPP\n#define SHASTA_DEBRUIJN_GRAPH_HPP\n\n// A general purpose templated class representing a De Bruijn graph.\n// Each vertex represents a sequence of k symbols occurring in\n// sequences of symbols.\n// Template arguments:\n// - Symbol: the symbols that the sequences are made of.\n// - k: the number of symbols in the sequence represented by a vertex.\n// - SequenceId: the type used to identify the sequences.\n\n// Boost libraries.\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\n// Standard library.\n#include \"fstream.hpp\"\n#include <set>\n#include \"string.hpp\"\n#include \"utility.hpp\"\n#include \"vector.hpp\"\n\n\n\nnamespace shasta {\n\n    template<class Symbol, uint64_t k, class SequenceId> class DeBruijnGraph;\n    template<class Symbol, uint64_t k, class SequenceId> class DeBruijnGraphVertex;\n    template<class Symbol, uint64_t k, class SequenceId> class DeBruijnGraphEdge;\n\n    template<class Symbol, uint64_t k, class SequenceId> using DeBruijnGraphBaseClass =\n        boost::adjacency_list<\n        boost::listS,\n        boost::listS,\n        boost::bidirectionalS,\n        DeBruijnGraphVertex<Symbol, k, SequenceId>,\n        DeBruijnGraphEdge<Symbol, k, SequenceId>\n        >;\n\n}\n\n\n\ntemplate<class Symbol, uint64_t k, class SequenceId> class shasta::DeBruijnGraphVertex {\npublic:\n\n    // The sequence of k symbols represented by this vertex.\n    using VertexSequence = array<Symbol, k>;\n    VertexSequence vertexSequence;\n\n    // The occurrences of the k symbols represented by this vertex\n    // in the input sequences.\n    // The second element of each pair is the position in the sequence\n    // of the first of the k symbols.\n    vector< pair<SequenceId, uint64_t > > occurrences;\n\n    uint64_t vertexId;\n\n    DeBruijnGraphVertex(\n        const VertexSequence& vertexSequence,\n        uint64_t vertexId) :\n        vertexSequence(vertexSequence),\n        vertexId(vertexId) {}\n\n};\n\n\n\ntemplate<class Symbol, uint64_t k, class SequenceId> class shasta::DeBruijnGraphEdge {\npublic:\n\n    // The k-1 symbols associated with this edge.\n    // This are the last k-1 symbols of the source vertex\n    // and also the first k-1 symbols of the target vertex.\n    using EdgeSequence = array<Symbol, k-1>;\n    EdgeSequence edgeSequence;\n\n    DeBruijnGraphEdge(const EdgeSequence& edgeSequence) :\n        edgeSequence(edgeSequence) {}\n\n\n};\n\n\n\ntemplate<class Symbol, uint64_t k, class SequenceId> class shasta::DeBruijnGraph :\n    public DeBruijnGraphBaseClass<Symbol, k, SequenceId> {\npublic:\n\n    using Graph = DeBruijnGraph;\n    using Vertex = DeBruijnGraphVertex<Symbol, k, SequenceId>;\n    using Edge = DeBruijnGraphEdge<Symbol, k, SequenceId>;\n    using BaseClass = DeBruijnGraphBaseClass<Symbol, k, SequenceId>;\n    using vertex_descriptor = typename BaseClass::vertex_descriptor;\n    using edge_descriptor = typename BaseClass::edge_descriptor;\n    using Sequence = vector<Symbol>;\n    using VertexSequence = array<Symbol, k>;\n    using EdgeSequence = array<Symbol, k-1>;\n\n    // The vertices, keyed by the sequence they contain.\n    std::map<VertexSequence, vertex_descriptor> vertexMap;\n    uint64_t nextVertexId = 0;\n\n\n\n    // Add a sequence to the graph.\n    void addSequence(\n        SequenceId sequenceId,\n        const Sequence& sequence)\n    {\n        Graph& graph = *this;\n\n        // Loop over possible starting positions.\n        for(uint64_t startPosition=0; startPosition + k <= sequence.size(); startPosition++) {\n\n            // Extract the k symbols starting here.\n            VertexSequence vertexSequence;\n            for(uint64_t i=0; i<k; i++) {\n                vertexSequence[i] = sequence[startPosition + i];\n            }\n\n            // Get the corresponding vertex, creating it if necessary.\n            vertex_descriptor v;\n            auto it = vertexMap.find(vertexSequence);\n            if(it == vertexMap.end()) {\n                v = add_vertex(Vertex(vertexSequence, nextVertexId++), graph);\n                vertexMap.insert(make_pair(vertexSequence, v));\n            } else {\n                v = it->second;\n            }\n\n            // Store this occurrence of the k symbols.\n            graph[v].occurrences.push_back(make_pair(sequenceId, startPosition));\n        }\n    }\n\n\n\n    void removeLowCoverageVertices(uint64_t minCoverage)\n    {\n        Graph& graph = *this;\n\n        vector<vertex_descriptor> verticesTobeRemoved;\n        BGL_FORALL_VERTICES_T(v, graph, Graph) {\n            if(graph[v].occurrences.size() < minCoverage) {\n                verticesTobeRemoved.push_back(v);\n            }\n        }\n\n        for(const vertex_descriptor v: verticesTobeRemoved) {\n            clear_vertex(v, graph);\n            remove_vertex(v, graph);\n        }\n\n    }\n\n\n\n    // This remove vertices with more than one occurrences of the same sequence.\n    void removeAmbiguousVertices()\n    {\n        Graph& graph = *this;\n\n        vector<vertex_descriptor> verticesTobeRemoved;\n        vector<SequenceId> sequenceIds;\n        BGL_FORALL_VERTICES_T(v, graph, Graph) {\n            const auto& occurrences = graph[v].occurrences;\n            sequenceIds.clear();\n            for(const auto& p: occurrences) {\n                sequenceIds.push_back(p.first);\n            }\n            sort(sequenceIds.begin(), sequenceIds.end());\n            for(uint64_t i=1; i<sequenceIds.size(); i++) {\n                if(sequenceIds[i-1] == sequenceIds[i]) {\n                    verticesTobeRemoved.push_back(v);\n                    break;\n                }\n            }\n        }\n\n\n\n        for(const vertex_descriptor v: verticesTobeRemoved) {\n            clear_vertex(v, graph);\n            remove_vertex(v, graph);\n        }\n\n    }\n\n\n\n    // Create the edges of the De Bruijn graph.\n    // This should be called after all sequences are added.\n    void createEdges()\n    {\n        Graph& graph = *this;\n\n        // Index the vertices by their first k-1 symbols.\n        std::map<EdgeSequence, vector<vertex_descriptor> > vertexIndex;\n        BGL_FORALL_VERTICES_T(v, graph, Graph) {\n            const VertexSequence& vertexSequence = graph[v].vertexSequence;\n            EdgeSequence edgeSequence;\n            const auto begin = vertexSequence.begin();\n            const auto end = begin + (k-1);\n            copy(begin, end, edgeSequence.begin());\n            vertexIndex[edgeSequence].push_back(v);\n        }\n\n        // Use the index to create the edges.\n        BGL_FORALL_VERTICES_T(v0, graph, Graph) {\n            const VertexSequence& vertexSequence0 = graph[v0].vertexSequence;\n            EdgeSequence edgeSequence;\n            const auto begin = vertexSequence0.begin() + 1;\n            const auto end = vertexSequence0.end();\n            copy(begin, end, edgeSequence.begin());\n\n            for(const vertex_descriptor v1: vertexIndex[edgeSequence]) {\n                edge_descriptor e;\n                tie(e, ignore) = add_edge(v0, v1, Edge(edgeSequence), graph);\n            }\n        }\n    }\n\n\n\n    // Find sets of incompatible vertices.\n    // A set of incompatible vertex can be described as the vertices\n    // immediately preceding or following a branch in the graph.\n    // In a set of incompatible vertices, at least one of the following is true:\n    // - All vertices in the set have in-degree 1, and the same parent.\n    // - OR: All vertices in the set have out-degree 1, and the same child.\n    void findIncompatibleVertexSets(\n        std::set< std::set<vertex_descriptor> >& incompatibleSets) const\n    {\n        const Graph& graph = *this;\n\n        BGL_FORALL_VERTICES_T(v0, graph, Graph) {\n\n            // Check the children.\n            std::set<vertex_descriptor> children;\n            if(out_degree(v0, graph) > 1) {\n                bool ok = true;\n                BGL_FORALL_OUTEDGES_T(v0, e, graph, Graph) {\n                    const vertex_descriptor v1 = target(e, graph);\n                    if(in_degree(v1, graph) != 1) {\n                        ok = false;\n                        break;\n                    }\n                    children.insert(v1);\n                }\n                if(ok and not isAmbiguous(children)) {\n                    incompatibleSets.insert(children);\n                }\n            }\n\n            // Check the parents.\n            std::set<vertex_descriptor> parents;\n            if(in_degree(v0, graph) > 1) {\n                bool ok = true;\n                BGL_FORALL_INEDGES_T(v0, e, graph, Graph) {\n                    const vertex_descriptor v1 = source(e, graph);\n                    if(out_degree(v1, graph) != 1) {\n                        ok = false;\n                        break;\n                    }\n                    parents.insert(v1);\n                }\n                if(ok and not isAmbiguous(parents)) {\n                    incompatibleSets.insert(parents);\n                }\n            }\n\n        }\n\n    }\n\n\n\n    // Remove true if a vertex set is ambiguous -\n    // that is, if the same SequenceId appears more than once in\n    // the vertices in the set.\n    bool isAmbiguous(std::set<vertex_descriptor>& vertexSet) const\n    {\n        const Graph& graph = *this;\n\n        std::set<SequenceId> alreadyEncountered;\n        for(const vertex_descriptor v: vertexSet) {\n            for(const auto& p: graph[v].occurrences) {\n                const SequenceId sequenceId = p.first;\n                if(alreadyEncountered.find(sequenceId) == alreadyEncountered.end()) {\n                    alreadyEncountered.insert(sequenceId);\n                } else {\n\n                    // We already encountered this sequence.\n                    return true;\n                }\n            }\n        }\n\n        // If we get here, we never encountered a SequenceId more than once.\n        return false;\n    }\n\n\n\n    void writeGraphviz(const string& fileName) const\n    {\n        const Graph& graph = *this;\n        ofstream s(fileName);\n\n        s << \"digraph DeBruijnGraph {\\n\";\n\n        BGL_FORALL_VERTICES_T(v, graph, Graph) {\n            s << graph[v].vertexId <<\n                \"[label=\\\"\"  <<\n                graph[v].occurrences.size() <<\n                \"\\\"];\\n\";\n        }\n\n        BGL_FORALL_EDGES_T(e, graph, Graph) {\n            const vertex_descriptor v0 = source(e, graph);\n            const vertex_descriptor v1 = target(e, graph);\n            s << graph[v0].vertexId << \"->\";\n            s << graph[v1].vertexId << \";\\n\";\n        }\n\n        s << \"}\\n\";\n\n    }\n\n\n    void createVertexCoverageHistogram(vector<uint64_t>& histogram) const\n    {\n        const Graph& graph = *this;\n\n        histogram.clear();\n        BGL_FORALL_VERTICES_T(v, graph, Graph) {\n            const uint64_t coverage = graph[v].occurrences.size();\n            if(coverage >= histogram.size()) {\n                histogram.resize(coverage + 1, 0);\n            }\n            ++histogram[coverage];\n        }\n\n    }\n};\n\n#endif\n\n#endif\n", "meta": {"hexsha": "ade4b43730386da7a7c70fa6c788fcc02269578f", "size": 10947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DeBruijnGraph.hpp", "max_stars_repo_name": "AustinHartman/shasta", "max_stars_repo_head_hexsha": "105b8e85e272247f72ced59005c88879631931c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 267.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T16:12:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:57:53.000Z", "max_issues_repo_path": "src/DeBruijnGraph.hpp", "max_issues_repo_name": "AustinHartman/shasta", "max_issues_repo_head_hexsha": "105b8e85e272247f72ced59005c88879631931c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 140.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:14:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T22:05:05.000Z", "max_forks_repo_path": "src/DeBruijnGraph.hpp", "max_forks_repo_name": "AustinHartman/shasta", "max_forks_repo_head_hexsha": "105b8e85e272247f72ced59005c88879631931c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T18:29:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T02:45:40.000Z", "avg_line_length": 30.9237288136, "max_line_length": 94, "alphanum_fraction": 0.5929478396, "num_tokens": 2427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.03904829650044906, "lm_q1q2_score": 0.017397169383932445}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <numeric>\n\n#include <boost/filesystem.hpp>\n\n#include <boost/log/core.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/expressions.hpp>\nnamespace logging = boost::log;\n\n#include <boost/program_options.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\nusing namespace boost::multiprecision;\n\n#include <libArrhenius/version.h>\n#include <libArrhenius/Arrhenius.hpp>\n#include <libArrhenius/Utils/GenerateOutputFilename.hpp>\n\nnamespace po = boost::program_options;\nusing namespace std;\n\ntypedef cpp_dec_float_100 DataType;\ntypedef cpp_dec_float_100 HPDataType; // high precision data type\n\nnamespace std {\n  /* std::string to_string(cpp_dec_float_100 val) */\n  /* {return static_cast<std::string>( val ); } */\n\n  /* std::string to_string(cpp_dec_float_50 val) */\n  /* {return static_cast<std::string>( val ); } */\n}\n\nstd::vector<std::pair<std::string,std::string>> cmds = { {\"help\",\"Print usage and exit.\"}\n                                                       , {\"calc-threshold\",\"Calculate the threshold scaling factor for a thermal profile(s).\"}\n                                                       , {\"calc-rate\",\"Calculate the damage rate for a thermal profile(s)\"}\n                                                       , {\"calc-damage\",\"Calculate the damage parameter for a thermal profile(s)\"}\n                                                       , {\"fit\",\"Fit Arrhenius coefficients to a set of thermal profile data.\"}\n                                                       };\n\nvoid print_usage(std::string prog, po::options_description& opts)\n{\n  std::cout << \"Usage: \" << prog << \" [global options] cmd [cmd options]\\n\" << std::endl;\n  std::cout << opts << std::endl;\n  std::cout << \"Commands:\" << std::endl;\n  for( auto c : cmds )\n  {\n    std::cout << \"  \" << c.first << \"\\t\\t- \" << c.second << std::endl;\n  }\n  std::cout << std::endl;\n}\nvoid print_manual()\n{\n  // we are using a raw string literal here (the R\"()\" syntax, which is a C++11 feature.\n  // it allows for a multi-line string to be written directly, instead of needing to quote\n  // each line or insert \\n characters.\n  std::cout << \n  R\"(\n  Under construction.\n    )\"\n  << std::endl;\n}\n\n\n\n\n\nvoid calc_threshold_help(std::string prog, std::string cmd, po::options_description& opts)\n{\n  std::cout << \"Usage: \" << prog << \" [global options] \"<< cmd << \" [\"<< cmd <<\" options]\\n\" << std::endl;\n  std::cout << opts << std::endl;\n  std::cout << std::endl;\n}\nint calc_threshold_cmd( std::string prog, std::string cmd, std::vector<std::string> &cmd_args )\n{\n    po::options_description opt_options(\"Options\");\n    opt_options.add_options()\n      // these are simple flag options, they do not have an argument.\n      (\"help,h\",  \"print help message.\")\n      (\"Ea\", po::value<DataType>()->default_value(6.28e5), \"Activation energy.\")\n      (\"A\",  po::value<DataType>()->default_value(3.1e99), \"Frequency factor.\")\n      (\"n\",  po::value<DataType>()->default_value(0), \"Temperature pre-factor exponent for modified Arrhenius equation.\")\n      (\"T0\", po::value<DataType>()->default_value(0), \"Offset temperature that will be added to all thermal profiles.\")\n      (\"Omega\", po::value<DataType>()->default_value(1), \"Compute threshold corresponding to the value of Omega.\")\n      (\"write-threshold-profiles,w\", \"Write the threshold thermal profile to disk.\")\n      (\"output-filename,o\", po::value<std::string>()->default_value(\"fmt:{ifn}.threshold\"), \"Output filename.\")\n      ;\n    po::options_description arg_options(\"Arguments\");\n    arg_options.add_options()\n      (\"files\"  , po::value<std::vector<std::string>>()->composing(), \"Thermal profile files to analyze.\") // an option that can be given multiple times with each argument getting stored in a vector.\n      ;\n\n    po::options_description all_options(\"Options\");\n    all_options.add(opt_options).add(arg_options);\n\n    // tell boost how to translate positional options to named options\n    po::positional_options_description args;\n    args.add(\"files\"  , -1);\n    \n    // now actually parse them\n    po::variables_map vm;\n    po::store(po::command_line_parser(cmd_args).  options(all_options).positional(args).run(), vm);\n    po::notify(vm);\n\n    if( vm.count(\"help\") || vm.count(\"files\") == 0 )\n    {\n      calc_threshold_help(prog,cmd,opt_options);\n      return 0;\n    }\n\n\n    libArrhenius::ThresholdCalculator< libArrhenius::ModifiedArrheniusIntegral<DataType> > calc;\n    calc.setA( vm[\"A\"].as<DataType>() );\n    calc.setEa( vm[\"Ea\"].as<DataType>() );\n    calc.setExponent( vm[\"n\"].as<DataType>() );\n    calc.setThresholdOmega( vm[\"Omega\"].as<DataType>() );\n    \n    std::cout<< \"filename | Omega | threshold\" << std::endl;\n    for( auto file : vm[\"files\"].as<std::vector<std::string>>() )\n    {\n      int n;\n      DataType *t, *T;\n\n      if( !boost::filesystem::exists(file) )\n        throw std::runtime_error(\"ERROR: '\"+file+\"' does not exist.\");\n      std::ifstream in(file.c_str());\n      RUC::ReadFunction(in, t, T, n);\n      in.close();\n      // add offset temp\n      std::transform( T, T+n, T, std::bind2nd(std::plus<DataType>(), vm[\"T0\"].as<DataType>()) );\n\n      auto Omega = calc.Omega(n,t,T);\n      auto Threshold = calc(n,t,T);\n\n      std::cout << file << \" | \" << Omega << \" | \" << Threshold << std::endl;\n\n      if( vm.count(\"write-threshold-profiles\") )\n      {\n        DataType *TT = new DataType[n];\n        for(size_t i = 0; i < n; ++i)\n          TT[i] = Threshold*(T[i] - T[0]) + T[0];\n\n        std::string ofn = RUC::GenerateOutputFilename(file,vm[\"output-filename\"].as<std::string>());\n        std::ofstream out( ofn );\n        for(size_t i = 0; i < n; i++)\n          out << t[i] << \" \" << TT[i] << \"\\n\";\n        out.close();\n\n        delete[] TT;\n\n      }\n\n      delete[] t;\n      delete[] T;\n    }\n    \n    return 0;\n\n\n\n\n\n\n\n}\n\nvoid calc_rate_help(std::string prog, std::string cmd, po::options_description& opts)\n{\n  std::cout << \"Usage: \" << prog << \" [global options] \"<< cmd << \" [\"<< cmd <<\" options]\\n\" << std::endl;\n  std::cout << opts << std::endl;\n  std::cout << \"Use this command to calculate some statistics on the damage rate for a set of thermal profiles.\" << std::endl;\n  std::cout << \"For example, this command will print the minimum, maximum, and average damage rates.\" << std::endl;\n  std::cout << \"If the --write-rate-profiles option is given, the damage rate at each point in the thermal profile will be written to file.\" << std::endl;\n  std::cout << std::endl;\n}\nint calc_rate_cmd( std::string prog, std::string cmd, std::vector<std::string> &cmd_args )\n{\n    po::options_description opt_options(\"Options\");\n    opt_options.add_options()\n      // these are simple flag options, they do not have an argument.\n      (\"help,h\",  \"print help message.\")\n      (\"Ea\", po::value<DataType>()->default_value(6.28e5), \"Activation energy.\")\n      (\"A\",  po::value<DataType>()->default_value(3.1e99), \"Frequency factor.\")\n      (\"n\",  po::value<DataType>()->default_value(0), \"Temperature pre-factor exponent for modified Arrhenius equation.\")\n      (\"T0\", po::value<DataType>()->default_value(0), \"Offset temperature that will be added to all thermal profiles.\")\n      (\"log\", \"Calculate the log of the rate instead.\")\n      (\"output-filename,o\", po::value<std::string>()->default_value(\"fmt:{ifn}.rate\"), \"Output filename.\")\n      (\"write-rate-profiles,w\", \"Write the rate profile to disk.\")\n      ;\n    po::options_description arg_options(\"Arguments\");\n    arg_options.add_options()\n      (\"files\"  , po::value<std::vector<std::string>>()->composing(), \"Thermal profile files to analyze.\") // an option that can be given multiple times with each argument getting stored in a vector.\n      ;\n\n    po::options_description all_options(\"Options\");\n    all_options.add(opt_options).add(arg_options);\n\n    // tell boost how to translate positional options to named options\n    po::positional_options_description args;\n    args.add(\"files\"  , -1);\n    \n    // now actually parse them\n    po::variables_map vm;\n    po::store(po::command_line_parser(cmd_args).  options(all_options).positional(args).run(), vm);\n    po::notify(vm);\n\n    if( vm.count(\"help\") || vm.count(\"files\") == 0 )\n    {\n      calc_rate_help(prog,cmd,opt_options);\n      return 0;\n    }\n\n    libArrhenius::ModifiedArrheniusIntegral<DataType> integrate;\n    integrate.setA( vm[\"A\"].as<DataType>() );\n    integrate.setEa( vm[\"Ea\"].as<DataType>() );\n    integrate.setExponent( vm[\"n\"].as<DataType>() );\n\n\n    for( auto file : vm[\"files\"].as<std::vector<std::string>>() )\n    {\n      int n;\n      DataType *t, *T;\n\n      if( !boost::filesystem::exists(file) )\n        throw std::runtime_error(\"ERROR: '\"+file+\"' does not exist.\");\n      std::ifstream in(file.c_str());\n      RUC::ReadFunction(in, t, T, n);\n      in.close();\n      // add offset temp\n      std::transform( T, T+n, T, std::bind2nd(std::plus<DataType>(), vm[\"T0\"].as<DataType>()) );\n\n      // just reuse temperature array for rate\n      for(int i = 0; i < n; i++)\n      {\n        if( vm.count(\"log\") )\n          T[i] = log(integrate.rate(T[i]));\n        else\n          T[i] = integrate.rate(T[i]);\n      }\n\n      std::cout << \"file: \" << file << std::endl;\n      // min rate\n      std::cout << \"min rate: \" << *std::min_element(T, T+n) << std::endl;\n      // max rate\n      std::cout << \"max rate: \" << *std::max_element(T, T+n) << std::endl;\n      // avg rate\n      std::cout << \"avg rate: \" << std::accumulate(T, T+n, DataType(0))/n << std::endl;\n      // critical temperature\n      DataType Tcrit = integrate.getCriticalTemperature();\n      std::cout << \"T crit: \" <<  Tcrit << std::endl;\n      // time above critical temp\n      DataType taucrit = 0;\n      for(int i = 1; i < n; i++)\n      {\n        if( (T[i] + T[i-1])/2 > 1 )\n          taucrit += t[i] - t[i-1];\n      }\n      std::cout << \"tau crit: \" <<  taucrit<< std::endl;\n\n      std::cout << std::endl;\n\n      if( vm.count(\"write-rate-profiles\") )\n      {\n        std::string ofn = RUC::GenerateOutputFilename(file,vm[\"output-filename\"].as<std::string>());\n        std::ofstream out( ofn );\n        for(size_t i = 0; i < n; i++)\n          out << t[i] << \" \" << T[i] << \"\\n\";\n        out.close();\n      }\n\n\n      delete[] t;\n      delete[] T;\n    }\n    \n    return 0;\n\n\n\n\n\n\n\n}\n\nvoid calc_damage_help(std::string prog, std::string cmd, po::options_description& opts)\n{\n  std::cout << \"Usage: \" << prog << \" [global options] \"<< cmd << \" [\"<< cmd <<\" options]\\n\" << std::endl;\n  std::cout << opts << std::endl;\n  std::cout << \"Use this command to evaluate the Arrhenius integral for on a set of thermal profiles.\" << std::endl;\n  std::cout << \"If the --write-damage-profiles option is given, the damage accumulation for each time point in the profile,\" << std::endl;\n  std::cout << \"i.e. Omega(t), will be written to a file.\" << std::endl;\n  std::cout << std::endl;\n}\nint calc_damage_cmd( std::string prog, std::string cmd, std::vector<std::string> &cmd_args )\n{\n    po::options_description opt_options(\"Options\");\n    opt_options.add_options()\n      // these are simple flag options, they do not have an argument.\n      (\"help,h\",  \"print help message.\")\n      (\"Ea\", po::value<DataType>()->default_value(6.28e5), \"Activation energy.\")\n      (\"A\",  po::value<DataType>()->default_value(3.1e99), \"Frequency factor.\")\n      (\"n\",  po::value<DataType>()->default_value(0), \"Temperature pre-factor exponent for modified Arrhenius equation.\")\n      (\"T0\", po::value<DataType>()->default_value(0), \"Offset temperature that will be added to all thermal profiles.\")\n      (\"output-filename,o\", po::value<std::string>()->default_value(\"fmt:{ifn}.damage\"), \"Output filename.\")\n      (\"write-damage-profiles,w\", \"Write the damage profiles to disk.\")\n      ;\n    po::options_description arg_options(\"Arguments\");\n    arg_options.add_options()\n      (\"files\"  , po::value<std::vector<std::string>>()->composing(), \"Thermal profile files to analyze.\") // an option that can be given multiple times with each argument getting stored in a vector.\n      ;\n\n    po::options_description all_options(\"Options\");\n    all_options.add(opt_options).add(arg_options);\n\n    // tell boost how to translate positional options to named options\n    po::positional_options_description args;\n    args.add(\"files\"  , -1);\n    \n    // now actually parse them\n    po::variables_map vm;\n    po::store(po::command_line_parser(cmd_args).  options(all_options).positional(args).run(), vm);\n    po::notify(vm);\n\n    if( vm.count(\"help\") || vm.count(\"files\") == 0 )\n    {\n      calc_damage_help(prog,cmd,opt_options);\n      return 0;\n    }\n\n    libArrhenius::ModifiedArrheniusIntegral<DataType> integrate;\n    integrate.setA( vm[\"A\"].as<DataType>() );\n    integrate.setEa( vm[\"Ea\"].as<DataType>() );\n    integrate.setExponent( vm[\"n\"].as<DataType>() );\n\n\n    std::cout<< \"filename | Omega\" << std::endl;\n    for( auto file : vm[\"files\"].as<std::vector<std::string>>() )\n    {\n      int n;\n      DataType *t, *T;\n\n      if( !boost::filesystem::exists(file) )\n        throw std::runtime_error(\"ERROR: '\"+file+\"' does not exist.\");\n      std::ifstream in(file.c_str());\n      RUC::ReadFunction(in, t, T, n);\n      in.close();\n      // add offset temp\n      std::transform( T, T+n, T, std::bind2nd(std::plus<DataType>(), vm[\"T0\"].as<DataType>()) );\n\n      auto Omega = integrate(n,t,T);\n      std::cout << file << \" | \" << Omega << std::endl;\n\n      if( vm.count(\"write-damage-profiles\") )\n      {\n        std::string ofn = RUC::GenerateOutputFilename(file,vm[\"output-filename\"].as<std::string>());\n        std::ofstream out( ofn );\n        // this is NOT efficient\n        for(size_t i = 0; i < n; i++)\n          out << t[i] << \" \" << integrate(i,t,T) << \"\\n\";\n        out.close();\n      }\n\n\n      delete[] t;\n      delete[] T;\n    }\n    \n    return 0;\n\n\n\n\n\n\n\n}\n\nvoid fit_help(std::string prog, std::string cmd, po::options_description& opts)\n{\n  std::cout << \"Usage: \" << prog << \" [global options] \"<< cmd << \" [\"<< cmd <<\" options]\\n\" << std::endl;\n  std::cout << opts << std::endl;\n  std::cout << std::endl;\n}\nint fit_cmd( std::string prog, std::string cmd, std::vector<std::string> &cmd_args )\n{\n    po::options_description opt_options(\"Options\");\n    opt_options.add_options()\n      // these are simple flag options, they do not have an argument.\n      (\"help,h\",  \"print help message.\")\n      (\"methods,m\"  , po::value<std::vector<std::string>>()->composing(), \"List of fitting methods to use. Coefficients for each method will be printed.\")\n      (\"list-methods,l\",  \"print list of available fit methods.\")\n      (\"T0\", po::value<HPDataType>()->default_value(0), \"Offset temperature (in K) that will be added to all thermal profiles.\")\n      (\"T0-uncertainty\", po::value<HPDataType>(), \"Uncertainty in baseline temperature (in K).\")\n      (\"dT-uncertainty\", po::value<HPDataType>(), \"Uncertainty in temperature rise (in K).\")\n      (\"Ea-min\", po::value<HPDataType>(), \"Minimum bound on Ea for methods that perform a search.\")\n      (\"Ea-max\", po::value<HPDataType>(), \"Maximum bound on Ea for methods that perform a search.\")\n      ;\n    po::options_description arg_options(\"Arguments\");\n    arg_options.add_options()\n      (\"files\"  , po::value<std::vector<std::string>>()->composing(), \"Thermal profile (in K vs. s) files to fit. These are ASSUMED to be threshold profiles.\")\n      ;\n\n    po::options_description all_options(\"Options\");\n    all_options.add(opt_options).add(arg_options);\n\n    // tell boost how to translate positional options to named options\n    po::positional_options_description args;\n    args.add(\"files\"  , -1);\n    \n    // now actually parse them\n    po::variables_map vm;\n    po::store(po::command_line_parser(cmd_args).  options(all_options).positional(args).run(), vm);\n    po::notify(vm);\n\n    std::vector<std::pair<std::string,std::string>> supported_methods = {\n     {\"Minimize log(A) Variance and Scaling Factors\",\" - Finds Ea that minimizes variance in log(A), then finds A that minimizes required scaling factor errors.\"}\n    ,{\"Effective Exposures\",\"                          - Computes an 'effective exposure' for each thermal profile and performs the standard linear regression method on them.\"}\n    };\n\n    if( vm.count(\"list-methods\") )\n    {\n      std::cout << \"\\n\\tMethods:\\n\" << std::endl;\n      for( auto m : supported_methods )\n      {\n        std::cout << \"\\t\\t\" << m.first << m.second << std::endl;\n      }\n      return 0;\n    }\n\n\n    if( vm.count(\"help\") || vm.count(\"files\") == 0 )\n    {\n      calc_threshold_help(prog,cmd,opt_options);\n      return 0;\n    }\n\n\n    // read in thermal profiles\n    std::cout << \"Loading thermal profiles.\" << std::endl;\n    std::vector<std::shared_ptr<HPDataType>> ts,Ts;\n    std::vector<size_t> Ns;\n    for( auto file : vm[\"files\"].as<std::vector<std::string>>() )\n    {\n      int n;\n      HPDataType *t, *T;\n\n      if( !boost::filesystem::exists(file) )\n        throw std::runtime_error(\"ERROR: '\"+file+\"' does not exist.\");\n      std::ifstream in(file.c_str());\n      RUC::ReadFunction(in, t, T, n);\n      in.close();\n      // add offset temp\n      std::transform( T, T+n, T, std::bind2nd(std::plus<HPDataType>(), vm[\"T0\"].as<HPDataType>()) );\n\n      // we need to wrap these in shared_ptr's so we don't leak memory\n      Ns.push_back(n);\n      ts.push_back( std::shared_ptr<HPDataType>( t ) );\n      Ts.push_back( std::shared_ptr<HPDataType>( T ) );\n\n    }\n\n\n\n\n\n\n\n    std::vector<std::string> methods;\n    if( vm.count(\"methods\") )\n    {\n      for( auto m : vm[\"methods\"].as<std::vector<std::string>>() )\n        methods.push_back(m);\n    }\n    else\n    {\n      for( auto m : supported_methods )\n        methods.push_back(m.first);\n    }\n\n\n    // loop through various fit methods\n    for( auto m : methods )\n    {\n      std::transform( m.begin(), m.end(), m.begin(), ::tolower);\n\n      std::cout << \"Running \" << m << \" method.\" << std::endl;\n\n      typedef libArrhenius::ArrheniusFitInterface<HPDataType>::Return Coeffs;\n      Coeffs coefficients;\n      Coeffs coefficients_err;\n\n      std::shared_ptr< libArrhenius::ArrheniusFitInterface< HPDataType> > fit;\n\n      // support aliases\n      if(m == \"minimize log(a) variance and scaling factors\")\n        m = \"clark\";\n\n      if(m == \"effective exposures\")\n        m = \"denton\";\n\n      if(m == \"effective exposures linear regression\")\n        m = \"denton\";\n\n\n      // get the correct fitter\n      if(m == \"clark\")\n        fit.reset( new libArrhenius::ArrheniusFit< HPDataType, libArrhenius::MinimizeLogAVarianceAndScalingFactors >());\n\n      if(m == \"denton\")\n        fit.reset( new libArrhenius::ArrheniusFit< HPDataType, libArrhenius::EffectiveExposuresLinearRegression>());\n\n      // now fit the profiles\n      for( int i = 0; i < Ns.size(); ++i )\n        fit->addProfile( Ns[i], ts[i].get(), Ts[i].get() );\n\n      if(vm.count(\"Ea-min\"))\n        fit->setMinEa( vm[\"Ea-min\"].as<HPDataType>() );\n      if(vm.count(\"Ea-max\"))\n        fit->setMaxEa( vm[\"Ea-max\"].as<HPDataType>() );\n\n      coefficients = fit->exec();\n\n      std::vector< Coeffs > errors;\n\n      // propagate error for uncertainty in baseline temperature if given\n      if( vm.count(\"T0-uncertainty\") )\n      {\n        fit->clear();\n        // add uncertainty to the thermal profiles and add them to the fitter\n        for( int i = 0; i < Ns.size(); ++i )\n        {\n          std::transform( Ts[i].get(), Ts[i].get()+Ns[i], Ts[i].get(), std::bind2nd(std::plus<HPDataType>(), vm[\"T0-uncertainty\"].as<HPDataType>()) );\n          fit->addProfile( Ns[i], ts[i].get(), Ts[i].get() );\n        }\n\n        errors.push_back(fit->exec());\n\n        // subtract the uncertainty back off the thermal profiles\n        for( int i = 0; i < Ns.size(); ++i )\n          std::transform( Ts[i].get(), Ts[i].get()+Ns[i], Ts[i].get(), std::bind2nd(std::minus<HPDataType>(), vm[\"T0-uncertainty\"].as<HPDataType>()) );\n      }\n\n      // propagate error for peak temperature rise if given\n      if( vm.count(\"dT-uncertainty\") )\n      {\n        fit->clear();\n        // add uncertainty to the thermal profiles and add them to the fitter\n        for( int i = 0; i < Ns.size(); ++i )\n        {\n          HPDataType Tmax = *std::max_element( Ts[i].get(), Ts[i].get() + Ns[i] );\n          HPDataType scale = 1 + vm[\"dT-uncertainty\"].as<HPDataType>()/(Tmax - Ts[i].get()[0]);\n          for( int j = 0; j < Ns[i]; j++)\n            Ts[i].get()[j] = Ts[i].get()[0] + scale*(Ts[i].get()[j] - Ts[i].get()[0]);\n\n          fit->addProfile( Ns[i], ts[i].get(), Ts[i].get() );\n        }\n\n        errors.push_back(fit->exec());\n\n        // subtract the uncertainty back off the thermal profiles\n        for( int i = 0; i < Ns.size(); ++i )\n        {\n          HPDataType Tmax = *std::max_element( Ts[i].get(), Ts[i].get() + Ns[i] );\n          HPDataType scale = 1 - vm[\"dT-uncertainty\"].as<HPDataType>()/(Tmax - Ts[i].get()[0]);\n          for( int j = 0; j < Ns[i]; j++)\n            Ts[i].get()[j] = Ts[i].get()[0] + scale*(Ts[i].get()[j] - Ts[i].get()[0]);\n        }\n      }\n\n\n      // compute total error\n      coefficients_err.A = 0;\n      coefficients_err.Ea = 0;\n      for( auto e : errors )\n      {\n        auto dA  = e.A.get() - coefficients.A.get();\n        auto dEa = e.Ea.get() - coefficients.Ea.get();\n        coefficients_err.A  = coefficients_err.A.get()  + dA*dA;\n        coefficients_err.Ea = coefficients_err.Ea.get() + dEa*dEa;\n      }\n      coefficients_err.A  = sqrt(coefficients_err.A.get());\n      coefficients_err.Ea = sqrt(coefficients_err.Ea.get());\n\n\n      std::cout << \"A: \" << coefficients.A.get()   << \" +/- \" << coefficients_err.A.get() << std::endl;\n      std::cout << \"Ea: \" << coefficients.Ea.get() << \" +/- \" << coefficients_err.Ea.get() << std::endl;\n\n      std::cout<< \"filename | Omega | threshold\" << std::endl;\n\n      // todo: should we add support for modified arrhenius?\n      libArrhenius::ThresholdCalculator< libArrhenius::ArrheniusIntegral<DataType> > calc;\n      calc.setA( coefficients.A.get() );\n      calc.setEa( coefficients.Ea.get() );\n      //calc.setExponent( vm[\"n\"].as<DataType>() );\n      // what about support for omega != 1?\n      //calc.setThresholdOmega( vm[\"Omega\"].as<DataType>() );\n      std::vector<HPDataType> Thresholds(Ns.size());\n      for( int i = 0; i < vm[\"files\"].as<std::vector<std::string>>().size(); i++ )\n      {\n        auto file = vm[\"files\"].as<std::vector<std::string>>()[i];\n        auto Omega = calc.Omega(Ns[i],ts[i].get(),Ts[i].get());\n        auto Threshold = calc(Ns[i],ts[i].get(),Ts[i].get());\n        std::cout << file << \" | \" << Omega << \" | \" << Threshold << std::endl;\n        Thresholds[i] = Threshold;\n      }\n      // calc sum of residuals\n      std::cout << \"R^2: \" << std::accumulate(Thresholds.begin(), Thresholds.end(), HPDataType(0), []( HPDataType a, HPDataType b ){ return HPDataType(a + (b-1)*(b-1)); } ) << std::endl;\n\n      std::cout << std::endl;\n\n    }\n\n\n\n    \n    return 0;\n\n\n\n\n\n\n\n}\n\n\n\n\n\nint main(int argc, const char** argv)\n{\n    std::vector<std::string> global_args;\n    std::vector<std::string> cmd_args;\n\n    bool cmd_found = false;\n    for( int i = 1; i < argc; i++ )\n    {\n      std::string arg( argv[i] );\n      if(!cmd_found)\n        global_args.push_back( arg );\n\n      if(cmd_found)\n        cmd_args.push_back( arg );\n\n      for( auto c : cmds )\n      {\n        if( c.first == arg )\n        {\n          cmd_found = true;\n          break;\n        }\n      }\n    }\n\n    // setup command line parser for the global arguments.\n    //\n    // note that boost is a little different...\n    // we usually say that a command line program takes options and arguments.\n    // boost calls arguments \"positional options\", which are just options that can\n    // be given without their option name. to create the argument, we define it as\n    // an option first, and then tell boost that it is \"positional\"\n    //\n    // so to define our command line interface\n    // we declare options and arguments that our application will accept.\n\n    // define our regular options. these will be given with a '--' or '-' in front. '--' is used\n    // for the long name, '-' is used for the short name.\n    po::options_description opt_options(\"Options\");\n    opt_options.add_options()\n      // these are simple flag options, they do not have an argument.\n      (\"help,h\",  \"print help message.\")\n      (\"version\", \"print library version.\")\n      (\"manual\",  \"print manual.\")\n      (\"verbose,v\", po::value<int>()->default_value(0), \"verbose level.\") // an option that takes an argument, but has a default value.\n      ;\n      \n    // now define our arguments.\n    po::options_description arg_options(\"Arguments\");\n    arg_options.add_options()\n      (\"command\"  , po::value<std::string>()->default_value(\"help\"),   \"Subcommand.\");\n\n    // combine the options and arguments into one option list.\n    // this is what we will use to parse the command line, but\n    // when we output a description of the options, we will just use\n    // opt_options\n    po::options_description all_options(\"Options\");\n    all_options.add(opt_options).add(arg_options);\n\n    // tell boost how to translate positional options to named options\n    po::positional_options_description args;\n    args.add(\"command\", 1);\n\n    // if no subcommand was found, we need to print the help before the parser\n    // tries to parse because it will likely just fail.\n    // note that we can't do this above because we need the options descriptor\n    if( !cmd_found )\n    {\n      // print out a usage statement and summary of command line options\n      std::cout << \"ERROR: No subcommand found.\" << std::endl;\n      print_usage(argv[0],opt_options);\n      return 1;\n    }\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(global_args).  options(all_options).positional(args).run(), vm);\n    po::notify(vm);\n\n\n    // boiler plate stuff\n\n    if( vm.count(\"help\") || vm[\"command\"].as<std::string>() == \"help\" )\n    {\n      // print out a usage statement and summary of command line options\n      print_usage(argv[0],opt_options);\n      return 0;\n    }\n\n    if( vm.count(\"manual\") )\n    {\n      // print the manual\n      print_manual();\n      return 0;\n    }\n\n    if( vm.count(\"version\") )\n    {\n      // print the version number for the library\n      std::cout << \"libArrhenius \"<<libArrhenius_VERSION_FULL << std::endl;\n      return 0;\n    }\n\n    logging::core::get()->set_filter( logging::trivial::severity >= logging::trivial::error );\n    if( vm[\"verbose\"].as<int>() > 0 )\n      logging::core::get()->set_filter( logging::trivial::severity >= logging::trivial::warning );\n    if( vm[\"verbose\"].as<int>() > 1 )\n      logging::core::get()->set_filter( logging::trivial::severity >= logging::trivial::info );\n    if( vm[\"verbose\"].as<int>() > 2 )\n      logging::core::get()->set_filter( logging::trivial::severity >= logging::trivial::debug );\n    if( vm[\"verbose\"].as<int>() > 3 )\n      logging::core::get()->set_filter( logging::trivial::severity >= logging::trivial::trace );\n\n\n\n\n    if( vm[\"command\"].as<std::string>() == \"calc-threshold\" )\n      return calc_threshold_cmd( argv[0], \"calc-threshold\", cmd_args );\n\n    if( vm[\"command\"].as<std::string>() == \"calc-rate\" )\n      return calc_rate_cmd( argv[0], \"calc-rate\", cmd_args );\n\n    if( vm[\"command\"].as<std::string>() == \"calc-damage\" )\n      return calc_damage_cmd( argv[0], \"calc-damage\", cmd_args );\n\n    if( vm[\"command\"].as<std::string>() == \"fit\" )\n      return fit_cmd( argv[0], \"fit\", cmd_args );\n\n    \n\n\n    return 0;\n}\n", "meta": {"hexsha": "cea6d216df01182614d5087f9db2db9c336f23de", "size": 27496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/Arrhenius-cli.cpp", "max_stars_repo_name": "CD3/libArrhenius", "max_stars_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/Arrhenius-cli.cpp", "max_issues_repo_name": "CD3/libArrhenius", "max_issues_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/Arrhenius-cli.cpp", "max_forks_repo_name": "CD3/libArrhenius", "max_forks_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9895287958, "max_line_length": 199, "alphanum_fraction": 0.5969595578, "num_tokens": 7235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526033, "lm_q2_score": 0.03904829664023509, "lm_q1q2_score": 0.017397168871251933}}
{"text": "/*  $Id: voronoidiagram.cpp 664 2011-02-13 17:37:33Z anders.e.e.wallin $\n * \n *  Copyright 2010-2011 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#ifndef VODI_G_H\n#define VODI_G_H\n\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"point.h\"\n#include \"halfedgediagram.hpp\"\n\n\n\nnamespace ocl {\n\n// this file contains typedefs used by voronoidiagram.h\n\nstruct VertexProps; \nstruct EdgeProps;\nstruct FaceProps;\n\n\ntypedef unsigned int HEFace;    \n\n// the type of graph with which we construct the voronoi-diagram\ntypedef HEDIGraph<     boost::listS,             // out-edges stored in a std::list\n                       boost::listS,             // vertex set stored here\n                       boost::bidirectionalS,    // bidirectional graph.\n                       VertexProps,              // vertex properties\n                       EdgeProps,                // edge properties\n                       FaceProps,                // face properties\n                       boost::no_property,       // graph properties\n                       boost::listS              // edge storage\n                       > HEGraph;\n\ntypedef boost::graph_traits< HEGraph >::vertex_descriptor  HEVertex;\ntypedef boost::graph_traits< HEGraph >::vertex_iterator    HEVertexItr;\ntypedef boost::graph_traits< HEGraph >::edge_descriptor    HEEdge;\ntypedef boost::graph_traits< HEGraph >::edge_iterator      HEEdgeItr;\ntypedef boost::graph_traits< HEGraph >::out_edge_iterator  HEOutEdgeItr;\ntypedef boost::graph_traits< HEGraph >::adjacency_iterator HEAdjacencyItr;\ntypedef boost::graph_traits< HEGraph >::vertices_size_type HEVertexSize;\n\n\n\n\n// typedef std::vector< std::vector< HEEdge > > HEPlanarEmbedding;\n\n/// voronoi-vertices can be of these four different types\n/// as we incrementally construct the diagram the type is updated as follows:\n/// OUT-vertices will not be deleted\n/// IN-vertices will be deleted\n/// UNDECIDED-vertices have not been examied yet\n/// NEW-vertices are constructed on OUT-IN edges\nenum VoronoiVertexType {OUT, IN, UNDECIDED, NEW };\n\n/// properties of a vertex in the voronoi diagram\nstruct VertexProps {\n    VertexProps() {\n        init();\n    }\n    /// construct vertex at position p with type t\n    VertexProps( Point p, VoronoiVertexType t) {\n        position=p;\n        type=t;\n        init();\n    }\n    void init() {\n        index = count;\n        count++;\n        in_queue = false;\n    }\n    void reset() {\n        in_queue = false;\n        type = UNDECIDED;\n    }\n    /// based on previously calculated J2, J3, and J4, set the position of the vertex\n    void set_position() {\n        double w = J4;\n        double x = - J2/w+pk.x;\n        double y = J3/w+pk.y;\n        position =  Point(x,y);\n    }\n    /// based on precalculated J2, J3, J4, calculate the H determinant for Point pl\n    double detH(const Point& pl) {\n        H = J2*(pl.x-pk.x) - J3*(pl.y-pk.y) + 0.5*J4*(square(pl.x-pk.x) + square(pl.y-pk.y));\n        return H;\n    }\n    bool operator<(const VertexProps& other) const {\n        return ( abs(this->H) < abs(other.H) );\n    }\n    /// set the J values\n    void set_J(const Point& pi, const Point& pj, const Point& pkin) { \n        // 1) i-j-k should come in CCW order\n        Point pi_,pj_,pk_;\n        if ( pi.isRight(pj,pkin) ) {\n            pi_ = pj;\n            pj_ = pi;\n            pk_ = pkin;\n        } else {\n            pi_ = pi;\n            pj_ = pj;\n            pk_ = pkin;\n        }\n        assert( !pi_.isRight(pj_,pk_) );\n        // 2) point pk should have the largest angle \n        // largest angle is opposite longest side.\n        Point pi__,pj__,pk__;\n        pi__ = pi_;                          \n        pj__ = pj_;                          \n        pk__ = pk_;\n        double longest_side = (pi_ - pj_).xyNorm();\n        if (  (pj_ - pk_).xyNorm() > longest_side ) {\n            longest_side = (pj_ - pk_).xyNorm(); //j-k is longest, so i should be new k\n            pk__ = pi_;                         // old  i-j-k \n            pi__ = pj_;                         // new  k-i-j\n            pj__ = pk_;\n        }\n        if ( (pi_ - pk_).xyNorm() > longest_side ) { // i-k is longest, so j should be new k                    \n            pk__ = pj_;                          // old  i-j-k\n            pj__ = pi_;                          // new  j-k-i\n            pi__ = pk_;\n        }\n        \n        assert( !pi__.isRight(pj__,pk__) );\n        assert( (pi__ - pj__).xyNorm() >=  (pj__ - pk__).xyNorm() );\n        assert( (pi__ - pj__).xyNorm() >=  (pk__ - pi__).xyNorm() );\n        \n        this->pk = pk__;\n        J2 = detH_J2( pi__, pj__, pk__);\n        J3 = detH_J3( pi__, pj__, pk__);\n        J4 = detH_J4( pi__, pj__, pk__);\n        //assert( J4 > 0.0 );\n    }\n    /// calculate J2\n    double detH_J2(Point& pi, Point& pj, Point& pk) {\n        return (pi.y-pk.y)*(square(pj.x-pk.x)+square(pj.y-pk.y))/2 - (pj.y-pk.y)*(square(pi.x-pk.x)+square(pi.y-pk.y))/2;\n    }\n    /// calculate J3\n    double detH_J3(Point& pi, Point& pj, Point& pk) {\n        return (pi.x-pk.x)*(square(pj.x-pk.x)+square(pj.y-pk.y))/2 - (pj.x-pk.x)*(square(pi.x-pk.x)+square(pi.y-pk.y))/2;\n    }\n    /// calculate J4\n    double detH_J4(Point& pi, Point& pj, Point& pk) {\n        return (pi.x-pk.x)*(pj.y-pk.y) - (pj.x-pk.x)*(pi.y-pk.y);\n    }\n// VD DATA\n    /// vertex type\n    VoronoiVertexType type;\n    /// the reference point for J-calculations\n    Point pk;\n    /// J2 determinant\n    double J2;\n    /// J3 determinant\n    double J3;\n    /// J4 determinant\n    double J4;\n    double H;\n    bool in_queue;\n// HE data\n    /// the position of the vertex\n    Point position;\n    /// index of vertex\n    int index;\n    /// global vertex count\n    static int count;\n};\n\n/// properties of an edge in the voronoi diagram\n/// each edge stores a pointer to the next HEEdge \n/// and the HEFace to which this HEEdge belongs\nstruct EdgeProps {\n    EdgeProps() {}\n    /// create edge with given next, twin, and face\n    EdgeProps(HEEdge n, HEEdge t, HEFace f){\n        next = n;\n        twin = t;\n        face = f;\n    }\n    /// the next edge, counterclockwise, from this edge\n    HEEdge next; \n    /// the twin edge\n    HEEdge twin;\n    /// the face to which this edge belongs\n    HEFace face; \n};\n\n/// types of faces in the voronoi diagram\nenum VoronoiFaceType {INCIDENT, NONINCIDENT};\n\n/// properties of a face in the voronoi diagram\n/// each face stores one edge on the boundary of the face\nstruct FaceProps {\n    /// create face with given edge, generator, and type\n    FaceProps( HEEdge e , Point gen, VoronoiFaceType t) {\n        edge = e;\n        generator = gen;\n        type = t;\n    }\n    /// operator for sorting faces\n    bool operator<(const FaceProps& f) const {return (this->idx<f.idx);}\n    /// face index\n    HEFace idx;\n    /// one edge that bounds this face\n    HEEdge edge;\n    /// the generator for this face\n    Point generator;\n    /// face type\n    VoronoiFaceType type;\n};\n\n\n// these containers are used instead of iterators when accessing\n// adjacent vertices, edges, faces.\n// FIXME: it may be faster to rewrite the code so it uses iterators, as does the BGL.\ntypedef std::vector<HEVertex> VertexVector;\ntypedef std::vector<HEFace> FaceVector;\ntypedef std::vector<HEEdge> EdgeVector;  \n\n\n}\n#endif\n", "meta": {"hexsha": "af911e8845959a5c5a1a32e2cf242fe189a88b9e", "size": 7973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "opencamlib-read-only/src/voronoi/voronoidiagram_graph.hpp", "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/voronoi/voronoidiagram_graph.hpp", "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/voronoi/voronoidiagram_graph.hpp", "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": 32.9462809917, "max_line_length": 121, "alphanum_fraction": 0.5866047912, "num_tokens": 2139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.036769468582465784, "lm_q1q2_score": 0.017380320243045703}}
{"text": "// Copyright (C) 2007-2012 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: Nicholas Edmonds\n//           Douglas Gregor\n//           Andrew Lumsdaine\n\n/**************************************************************************\n * This source file implements the Delta-stepping algorithm:              *\n *                                                                        *\n *   Ulrich Meyer and Peter Sanders. Parallel Shortest Path for Arbitrary *\n *   Graphs. In Proceedings from the 6th International Euro-Par           *\n *   Conference on Parallel Processing, pages 461--470, 2000.             *\n *                                                                        * \n *   Ulrich Meyer, Peter Sanders: [Delta]-stepping: A Parallelizable      *\n *   Shortest Path Algorithm. J. Algorithms 49(1): 114-152, 2003.         *\n *                                                                        *\n * There are several potential optimizations we could still perform for   *\n * this algorithm implementation:                                         *\n *                                                                        *\n *   - Implement \"shortcuts\", which bound the number of reinsertions      *\n *     in a single bucket (to one). The computation of shortcuts looks    *\n *     expensive in a distributed-memory setting, but it could be         *\n *     ammortized over many queries.                                      *\n *                                                                        *\n *   - The size of the \"buckets\" data structure can be bounded to         *\n *     max_edge_weight/delta buckets, if we treat the buckets as a        *\n *     circular array.                                                    *\n *                                                                        *\n *   - If we partition light/heavy edges ahead of time, we could improve  *\n *     relaxation performance by only iterating over the right portion    *\n *     of the out-edge list each time.                                    *\n *                                                                        *\n *   - Implement a more sophisticated algorithm for guessing \"delta\",     *\n *     based on the shortcut-finding algorithm.                           *\n **************************************************************************/\n#ifndef BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_HPP\n#define BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_HPP\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <am++/counter_coalesced_message_type.hpp>\n#include <am++/detail/thread_support.hpp>\n\n#include <boost/parallel/append_buffer.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/parallel/algorithm.hpp> // for all_reduce\n#include <boost/graph/parallel/thread_support.hpp> // for compare_and_swap\n#include <algorithm> // for std::min, std::max\n#include <boost/format.hpp>\n#include <iostream>\n#include <atomic>\n\ntemplate <typename OwnerMap, typename VertexDistanceData>\nstruct vertex_distance_owner {\n  explicit vertex_distance_owner(const OwnerMap& owner) : owner(owner) {}\n\n  const OwnerMap& owner;\n};\n\ntemplate <typename OwnerMap, typename VertexDistanceData>\ntypename boost::property_traits<OwnerMap>::value_type\nget(const vertex_distance_owner<OwnerMap, VertexDistanceData>& o, const VertexDistanceData& data)\n{ return get(o.owner, data.first); }\n\nnamespace boost { namespace graph { namespace distributed {\n\ntemplate<typename Graph, \n\t typename DistanceMap, \n\t typename EdgeWeightMap, \n\t typename WorkStats,\n         typename Bucket = append_buffer<typename graph_traits<Graph>::vertex_descriptor, 10u>,\n         typename MessageGenerator = \n           amplusplus::simple_generator<amplusplus::counter_coalesced_message_type_gen> >\nclass delta_stepping_shortest_paths {\n  typedef delta_stepping_shortest_paths<Graph, DistanceMap, EdgeWeightMap, Bucket> \n    self_type;\n\n  typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap;\n\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef typename graph_traits<Graph>::degree_size_type Degree;\n  typedef typename property_traits<EdgeWeightMap>::value_type Dist;\n\n  typedef typename std::vector<Bucket*>::size_type BucketIndex;\n\n  typedef std::pair<Vertex, Dist> vertex_distance_data;\n\n  struct vertex_distance_handler;\n\n  typedef typename MessageGenerator::template call_result<vertex_distance_data, vertex_distance_handler, \n\t\t\t\t     vertex_distance_owner<OwnerMap, vertex_distance_data>,\n\t\t\t\t     amplusplus::idempotent_combination_t<boost::parallel::minimum<Dist>,\n\t\t\t\t\t\t\t\t\t  Dist> >::type\n    RelaxMessage;\n\n\npublic:\n\n  delta_stepping_shortest_paths(Graph& g,\n                                DistanceMap& distance, \n                                EdgeWeightMap& weight,\n\t\t\t\tamplusplus::transport &t,\n                                Dist delta,\n\t\t\t\tint offs,\n\t\t\t\tWorkStats& stats,\n                                MessageGenerator message_gen = \n                                  MessageGenerator(amplusplus::counter_coalesced_message_type_gen(1 << 12)))\n    : dummy_first_member_for_init_order((amplusplus::register_mpi_datatype<vertex_distance_data>(), 0)),\n      g(g), transport(t), distance(distance), weight(weight), delta(delta), \n    core_offset(offs),\n    work_stats(stats),\n    owner(get(vertex_owner, g)), \n      level_sync(false), current_level(0), buckets_processed(0), current_bucket(0),\n      relax_msg(message_gen, transport, vertex_distance_owner<OwnerMap, vertex_distance_data>(owner),\n\t\tamplusplus::idempotent_combination(boost::parallel::minimum<Dist>(), std::numeric_limits<Dist>::max()))\n  {\n    initialize();\n  }\n\n#ifdef AMPLUSPLUS_PRINT_HIT_RATES\n  typedef std::pair<unsigned long long, unsigned long long> cache_stats;\n  cache_stats\n  get_cache_stats() {\n    cache_stats stats(0, 0);\n    for(size_t i = 0; i < relax_msg.counters.hits.size(); ++i) {\n      stats.first += relax_msg.counters.hits[i];\n      stats.second += relax_msg.counters.tests[i];\n    }\n    return stats;\n  }\n#endif // AMPLUSPLUS_PRINT_HIT_RATES\n\n  void set_source(Vertex s) { source = s; } // for threaded execution\n  void set_level_sync() { level_sync = true; } // force level-synchronized exploration\n  void operator() (int tid) { run(source, tid); }\n\n  void run(Vertex s, int tid = 0);\n\n  BucketIndex get_num_levels() { return buckets_processed; }\n  time_type get_start_time() { return start_time; }\n\nprotected:\n  void initialize();\n  \n  // Relax the edge (u, v), creating a new best path of distance x.\n  void relax(Vertex v, Dist x);\n\n  void find_next_bucket();\n\n  const int dummy_first_member_for_init_order; // Unused\n\n  const Graph& g;\n  amplusplus::transport& transport;\n  DistanceMap& distance;\n  EdgeWeightMap& weight;\n  Dist delta;\n  int core_offset;\n  WorkStats& work_stats;\n  OwnerMap owner;\n  Vertex source;\n  bool level_sync;\n\n  // Bucket data structure. The ith bucket contains all local vertices\n  // with (tentative) distance in the range [i*delta,\n  // (i+1)*delta). \n  std::vector<shared_ptr<Bucket> > buckets;\n\n  // Bucket to hold vertices deleted at each level\n  shared_ptr<Bucket> deleted_vertices;\n  BucketIndex current_level; // How many buckets have we processed?\n  BucketIndex buckets_processed; // Stats tracking\n  BucketIndex num_buckets;\n\n  // Shared thread state to make sure we're all on the same page\n  BucketIndex current_bucket;\n  shared_ptr<amplusplus::detail::barrier> t_bar;\n  RelaxMessage relax_msg;\n  time_type start_time;\n};\n\n#define DELTA_STEPPING_SHORTEST_PATHS_PARMS                                   \\\n      typename Graph, typename DistanceMap, typename EdgeWeightMap, typename WorkStats, typename Bucket, typename MessageGenerator\n\n#define DELTA_STEPPING_SHORTEST_PATHS_TYPE                                    \\\n      delta_stepping_shortest_paths<Graph, DistanceMap, EdgeWeightMap, WorkStats, Bucket, MessageGenerator>\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_TYPE::initialize()\n{\n\n  relax_msg.set_handler(vertex_distance_handler(*this));\n\n  // Setup distance map\n  distance.set_consistency_model(0);\n  set_property_map_role(vertex_distance, distance);\n\n  using boost::parallel::all_reduce;\n  using boost::parallel::maximum;\n  using std::max;\n\n  // Compute the maximum edge weight\n  Dist max_edge_weight = 0;\n  Dist local_max = 0;\n  // CULPRIT !\n  BGL_FORALL_VERTICES_T(u, g, Graph) {\n    BGL_FORALL_OUTEDGES_T(u, e, g, Graph) {\n      auto w = get(weight, e);\n      if (local_max < w)\n\tlocal_max = w;\n    }\n  }\n\n  // do an all reduce to find the maximum\n  MPI_Allreduce(&local_max, &max_edge_weight, 1, \n\t\tMPI_UINT32_T, MPI_MAX, MPI_COMM_WORLD);\n\n  //  all_reduce<Dist, maximum<Dist> > r(transport, maximum<Dist>());\n  //max_edge_weight = r(max_edge_weight);\n\n  // If delta wasn't supplied in the ctor initialize it\n  if (delta == 0) {\n\n    // Compute the maximum edge degree\n    Degree max_degree = 0;\n    BGL_FORALL_VERTICES_T(u, g, Graph) {\n      max_degree = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_degree, out_degree(u, g));\n    }\n    // max_degree = all_reduce(process_group(g), max_degree, maximum<Degree>());\n    all_reduce<Degree, maximum<Degree> > r(transport, maximum<Degree>());\n    max_degree = r(max_degree);\n    \n    // Take a guess at delta, based on what works well for random\n    // graphs.\n    delta = max_edge_weight / max_degree;\n    if (delta == 0)\n      delta = 1;\n  }\n\n  //\n  // Initialize buckets data structure\n  //\n\n  // Extra bucket is so we don't try to insert into the bucket we're processing\n  // when the index wraps\n  num_buckets = max_edge_weight / delta;\n  num_buckets += (num_buckets * delta < (BucketIndex)max_edge_weight) ? 2 : 1;\n\n  // Declare bucket data structure and index variable\n  buckets.resize(num_buckets);\n  for (BucketIndex i = 0 ; i < buckets.size() ; ++i) {\n    shared_ptr<Bucket> p(new Bucket);\n    buckets[i].swap(p);\n  }\n\n  shared_ptr<Bucket> p(new Bucket);\n  deleted_vertices.swap(p);\n\n  // Initialize distance labels\n  BGL_FORALL_VERTICES_T(v, g, Graph) { \n    put(distance, v, (std::numeric_limits<Dist>::max)()); \n  }\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_TYPE::run(Vertex s, int tid)\n{\n  /**\n   *  NOTE: We never remove a vertex from a higher bucket when\n   *  placing it in a lower one because thread-safe insertion is\n   *  cheap as long as we don't have to handle removal\n   *  simultaneously, this will result in additional work and higher\n   *  memory consumption, but the alternative is locking which is\n   *  sure to be slow.\n   */\n  int count_epoch = 0 ; \n  AMPLUSPLUS_WITH_THREAD_ID(tid) {\n    int nthreads = transport.get_nthreads();\n    \n    if (tid == 0)\n      t_bar.reset(new amplusplus::detail::barrier(nthreads));\n    \n    // This barrier acts as a temporary barrier until we can be sure t_bar is initialized \n    { amplusplus::scoped_epoch epoch(transport); } \n    // Now above if branch needs to be executed to every thread\n    // Therefore wait till every thread comes to this point\n    t_bar->wait();\n\n    // if two processes are running on the same node, core_offset\n    // is important to achieve thread affinity\n    if (pin(tid+core_offset) != 0) {\n      std::cerr << \"[ERROR] Unable to pin current thread to \"\n\t\t<< \"core : \" << tid << std::endl;\n      assert(false);\n    }\n\n    // wait till all threads are pinned\n    t_bar->wait();\n    { amplusplus::scoped_epoch epoch(transport); }\n\n    validate_thread_core_relation();\n\n    // last passing thread will update the correct start time\n    start_time = get_time();\n    // Push the source onto the queue\n    { \n      amplusplus::scoped_epoch epoch(transport); \n\n      if (get(owner, s) == transport.rank() && tid == 0)\n        relax(s, 0);\n    }    \n\n    t_bar->wait();\n    \n    typename Bucket::size_type current_bucket_start, current_bucket_end;\n    \n    do {\n      \n      current_bucket_start = 0;\n      current_bucket_end = buckets[current_bucket]->size();\n      \n      // Process current bucket\n      do {\n        \n        unsigned long all_starting_sizes;\n        const unsigned long starting_size = current_bucket_end - current_bucket_start;\n        count_epoch = 0;\n        t_bar->wait();\n        {\n          amplusplus::scoped_epoch_value epoch(transport, starting_size, all_starting_sizes);\n          \n#ifdef PRINT_DEBUG\n          if (tid == 0)\n            std::cerr << transport.rank() << \": processing light edges in bucket \"\n                      << current_bucket << \" [\" << current_bucket_start << \", \" << current_bucket_end << \")\\n\";\n#endif\n\t  \n\t  while (current_bucket_start != current_bucket_end) {\n\t    \n\t    for (typename Bucket::size_type i = current_bucket_start + tid ; i < current_bucket_end ; i+= nthreads) {\n\t      Vertex v = (*buckets[current_bucket])[i];\n\t      Dist dv = distance[v];\n\t      \n              // This is an optimization that is not specified in the algorithm\n\t      if (dv < delta * (Dist)current_level) {\n\t\tcontinue;\n              }\n\n\t      // Add v to set of deleted vertices\n\t      deleted_vertices->push_back(v);\n\t      \n\t      // Relax light edges\n\t      BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t\tVertex u = target(e, g);\n\t\tDist we = get(weight, e);\n\t\tif (we <= delta) {// light edge\n\t\t  relax_msg.send(vertex_distance_data(u, dv + we));\n#ifdef PRINT_DEBUG\n                  std::cerr << \"  Relax \" << get(get(vertex_local, g), v) << \"@\" \n                            << get(get(vertex_owner, g), v) << \"->\"\n                            << get(get(vertex_local, g), u) << \"@\" \n                            << get(get(vertex_owner, g), u) << \"  weight = \"\n                            << we << std::endl;\n#endif\n                }\n              }\n            }\n            \n            // Wait for all threads to finish current bucket\n            t_bar->wait();\n            current_bucket_start = current_bucket_end;\n            current_bucket_end = buckets[current_bucket]->size();       \n            t_bar->wait();\n\n\t    if (level_sync) break;\n\t  } // No more re-insertions into this bucket to process\n\t}\n\tcount_epoch += 1;\n\t// If all processes are done with the current bucket:\n\t//   1. clear the current bucket\n\t//   2. process heavy edges\n\t//   3. find the next bucket to work on \n\tif (all_starting_sizes == 0) {\n\t  \n\t  if (tid == 0) buckets[current_bucket]->clear();\n\t  t_bar->wait();\n\t  \n\t  // Process heavy edges\n\t  // TODO: If we had a separate transport here we could do single-level termination detection\n\t  {\n\t    amplusplus::scoped_epoch epoch(transport);\n\t    \n\t    int nthreads = transport.get_nthreads();\n\t    for (typename Bucket::size_type i = tid ; i < deleted_vertices->size() ; i += nthreads) {\n\t      Vertex v = (*deleted_vertices)[i];\n\t      Dist dv = distance[v];\n\t      \n\t      BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t\tVertex u = target(e, g);\n\t\tDist we = get(weight, e);\n\t\tif (we > delta) // heavy edge\n\t\t  relax_msg.send(vertex_distance_data(u, dv + we));\n\t      }\n\t    }\n\t  } // end_epoch does a thread barrier\n\t  \n#ifdef PRINT_DEBUG\n          std::cerr << tid << \"@\" << transport.rank() << \": Current bucket \" << current_bucket\n                    << \" size \" << buckets[current_bucket]->size() << std::endl;\n#endif\n          assert(buckets[current_bucket]->size() == 0);\n\n          if (tid == 0) deleted_vertices->clear();\n          \n          // find next bucket with work and update current_level \n          BucketIndex old_bucket = current_bucket;\n          \n          t_bar->wait();\n          if (tid == 0) {\n            find_next_bucket();\n\n            if (current_bucket != (std::numeric_limits<BucketIndex>::max)()) {\n              current_level += current_bucket - old_bucket;\n              ++buckets_processed;\n            }\n          }\n          t_bar->wait();\n  \n          break; // exit the do..while loop for the current bucket\n        } else // Update the end of the bucket and continue processing it\n          current_bucket_end = buckets[current_bucket]->size();\n        \n      } while(true);\n      \n      // If there are no non-empty buckets in any process, we're done\n    } while(current_bucket != (std::numeric_limits<BucketIndex>::max)());\n  }\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_TYPE::relax(Vertex v, Dist d) \n{\n  using boost::parallel::val_compare_and_swap;\n\n  Dist old_dist = distance[v], last_old_dist;\n  while (d < old_dist) {\n    last_old_dist = old_dist;\n    old_dist = val_compare_and_swap(&distance[v], old_dist, d);\n    if (last_old_dist == old_dist) {\n#ifdef PBGL2_PRINT_WORK_STATS\n      int tid = amplusplus::detail::get_thread_id();\n      if(old_dist < std::numeric_limits<Dist>::max()) { \n\twork_stats.increment_invalidated(tid);\n      } else {\n\twork_stats.increment_useful(tid);\n      }\n#endif\n      // Insert vertex into new bucket, note we don't remove it from any other\n      // buckets it might be in \n      BucketIndex new_index = \n        static_cast<BucketIndex>((d - (current_level * delta)) / delta);\n\n      //\n      // If new_index == 0, relax all light edges and add it to deleted_vertices\n      //\n      if (new_index == 0) { // This vertex is bound for the current bucket \n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t  Vertex u = target(e, g);\n\t  Dist we = get(weight, e);\n\t  if (we <= delta) // light edge\n\t    relax_msg.send(vertex_distance_data(u, d + we));\n\t}\n\t\n\tdeleted_vertices->push_back(v);\n\n        break; // No need to insert into current bucket now\n      }\n\n      new_index = (current_bucket + new_index) % num_buckets;\n      buckets[new_index]->push_back(v);\n\n      // new_distance now == get(distance, v) so we exit automatically\n      // but this saves us the conditional test\n      break;\n    }\n  }\n#ifdef PBGL2_PRINT_WORK_STATS\n  work_stats.increment_rejected(amplusplus::detail::get_thread_id());\n#endif\n  return;\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_TYPE::find_next_bucket()\n{\n  using boost::parallel::all_reduce;\n  using boost::parallel::minimum;\n\n  BucketIndex old_bucket = current_bucket;\n  BucketIndex max_bucket = (std::numeric_limits<BucketIndex>::max)();\n\n  current_bucket = (current_bucket + 1) % buckets.size();\n  while (current_bucket != old_bucket && buckets[current_bucket]->empty())\n    current_bucket = (current_bucket + 1) % buckets.size();\n  \n  if (current_bucket == old_bucket) \n    current_bucket = max_bucket;\n  \n  // If we wrapped, project index past end of buckets to use min()\n  if (current_bucket < old_bucket) current_bucket += buckets.size();\n  \n  all_reduce<BucketIndex, minimum<BucketIndex> > r(transport, minimum<BucketIndex>());\n  current_bucket = r(current_bucket);\n  \n  // Map index back into range of buckets\n  if (current_bucket != max_bucket) \n    current_bucket %= buckets.size();\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_PARMS>\nstruct DELTA_STEPPING_SHORTEST_PATHS_TYPE::\nvertex_distance_handler {\n  \n  vertex_distance_handler() : self(NULL) {}\n  vertex_distance_handler(delta_stepping_shortest_paths& self) : self(&self) {}\n  \n  void operator() (const vertex_distance_data& data) const {\n    self->work_stats.increment_edges(amplusplus::detail::get_thread_id());\n\n    if (data.second < get(self->distance, data.first))\n      self->relax(data.first, data.second);\n#ifdef PBGL2_PRINT_WORK_STATS\n    else\n      self->work_stats.increment_rejected(amplusplus::detail::get_thread_id());\n#endif\n  }\n\nprotected:\n  delta_stepping_shortest_paths* self;\n};\n\n\n} } } // end namespace boost::graph::distributed\n\n#endif // BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "8397a929e3557ca57cb7793e00256fb29da78bce", "size": 19890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/distributed/delta_stepping_shortest_paths.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": "boost/graph/distributed/delta_stepping_shortest_paths.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": "boost/graph/distributed/delta_stepping_shortest_paths.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": 35.7091561939, "max_line_length": 130, "alphanum_fraction": 0.6415284062, "num_tokens": 4611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869692386284973, "lm_q2_score": 0.041462271378916615, "lm_q1q2_score": 0.017360125482719063}}
{"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 \"lnn_optimization.hpp\"\n\n#include <boost/format.hpp>\n\n#include <core/functor.hpp>\n#include <core/utils/timer.hpp>\n\n#include <reversible/circuit.hpp>\n#include <reversible/functions/copy_circuit.hpp>\n#include <reversible/functions/copy_metadata.hpp>\n#include <reversible/functions/add_gates.hpp>\n\n#include <stack>\n#include <climits>\n\nnamespace cirkit\n{\n\n/**\n * optimizationmode\n */\n  enum lnn_optimization_mode {\n    LNN_OPTIMIZATION_NONE,\n    LNN_OPTIMIZATION_NAIVE,\n    LNN_OPTIMIZATION_LOCAL_REORDER,\n    LNN_OPTIMIZATION_GLOBAL_REORDER,\n  };\n\n  /**\n     calculates the nearest neighbor cost between two lines, where line1 != line2\n  */\n  inline unsigned nnc_func(unsigned u1, unsigned u2){\n    return u1 < u2 ? u2-u1-1 : u1-u2-1;\n  }\n\n/**\n * @brief Function providing the mapping of a specific new allocated line to its index\n *\n * @param src Source line which should be looked up\n * @param allocation Array representing the lines and their current position\n * @param length Length of the allocation array\n *\n * @return The line index of the source line in the allocation\n *\n */\n  unsigned lookup(unsigned src, unsigned allocation[], unsigned length)\n  {\n    for(unsigned index = 0; index < length; index++)\n      if(allocation[index] == src)\n        return index;\n    return 0;\n  }\n\n/**\n * @brief Function providing the mapping of two specific new allocated lines to their indices\n *\n * @param src1 First source line which should be looked up\n * @param src2 Second source line which should be looked up\n * @param allocation Array representing the lines and their current position\n * @param length Length of the allocation array\n *\n * @return the indices of two source lines in the allocation\n *\n */\n  std::pair<unsigned,unsigned> lookup2(unsigned src1, unsigned src2, unsigned allocation[], unsigned length)\n  {\n    unsigned i1 = 0;\n    unsigned i2 = 0;\n    for(unsigned index = 0; index < length; index++){\n        if(allocation[index] == src1)\n    i1 = index;\n        if(allocation[index] == src2)\n    i2 = index;\n    }\n    return std::make_pair(i1,i2);\n  }\n\n  /**\n   * @brief Function calculating the nearest neighbor cost (nnc) of a gate wrt. a line permutation (allocation)\n   *\n   * @param g Specific gate for which the nnc should be calculated\n   * @param allocation Array representing the lines and their current position\n   * @param len Length of the allocation array\n   *\n   * @return the nnc of the gate\n   */\n  unsigned nnc(const gate& g, unsigned *allocation, unsigned len){\n    if(g.size() == 2 && g.controls().front().line() < len && g.targets().front() < len ){\n      auto ctrltar = lookup2(g.controls().front().line(),g.targets().front(), allocation, len);\n      return nnc_func(ctrltar.first, ctrltar.second);\n    }\n    return 0;\n  }\n\n  /**\n   * @brief Function calculating the nearest neighbor cost (nnc) of a gate\n   *\n   * @param g Specific gate for which the nnc should be calculated\n   * @return the nnc of the gate\n   */\n  unsigned nnc(const gate& g){\n    if(g.size() == 2)\n      return nnc_func(g.controls().front().line(), g.targets().front() );\n    return 0;\n  }\n\n  /**\n   * @brief Function calculating the nearest neighbor cost (nnc) of a circuit, which is the sum of the nnc of all gates\n   *\n   * @param circ Specific circuit for which the nnc should be calculated\n   * @return the nnc of the circuit\n   */\n  unsigned NNC(const circuit& circ){\n    unsigned sum = 0;\n    for ( const gate& g : circ )\n      sum += nnc(g);\n    return sum;\n  }\n\n/**\n * @brief Function appending a swap gate exchanging line l1 and line l2 on circuit\n *\n * @param circ Circuit to which the swap gate should be appended\n * @param line1 first target line of the fredkin gate\n * @param line2 second target line of the fredkin gate\n */\n  inline void append_swap_gate(circuit& circ, unsigned line1, unsigned line2)\n  {\n    gate::control_container lc; //control line container is empty\n    append_fredkin(circ, lc , line1, line2);\n  }\n\n  /**\n   * @brief sets the (first) control line of the gate\n   *\n   * @param source_gate The specific gate to modify\n   * @param newcontrolline The new control line of the gate\n   * @return A copy of the gate where the (first) control line is changed to the specified one\n   */\n  gate set_gate_control_line(const gate source_gate, unsigned newcontrolline){\n    gate gate = source_gate;\n    gate.remove_control(gate.controls().front());\n    gate.add_control(make_var(newcontrolline));\n    return gate;\n  }\n\n  /**\n   * @brief sets the (first) target line of the gate\n   *\n   * @param source_gate The specific gate to modify\n   * @param newtargetline The new target line of the gate\n   * @return A copy of the gate where the (first) target line is changed to the specified one\n   */\n  gate set_gate_target_line(const gate source_gate, unsigned newtargetline){\n    gate gate = source_gate;\n    gate.remove_target(gate.targets().front());\n    gate.add_target(newtargetline);\n    return gate;\n  }\n\n/**\n * @brief applies the optimization of the naive lnn_optimization_mode on a circuit.\n *\n * @param circ Target circuit of the performing action\n * @param base Source circuit providing metadata and gates\n *\n * @return the nnc of the circuit\n */\n  unsigned apply_naive_scheme(circuit& circ, const circuit& base){\n    copy_metadata(base,circ);\n    std::stack<std::pair<unsigned,unsigned> > stack;\n\n    for ( const gate& g : base ){\n      unsigned nnc_val = nnc(g);\n      if(nnc_val>0){\n        bool direction = g.controls().front().line() > g.targets().front() ;\n        unsigned s = g.controls().front().line() ;\n\n        for(unsigned i = 0; i < nnc_val; i++){\n\n          auto swap = direction ?\n            std::make_pair(s - i , s - 1 -i) :\n            std::make_pair(s + i , s + 1 +i) ;\n          append_swap_gate(circ , swap.first, swap.second);\n          stack.push(swap);\n        }\n\n        unsigned newcontrol = g.targets().front() + (direction ? 1 : -1);\n        circ.append_gate() = set_gate_control_line(g, newcontrol);\n\n        for(; !stack.empty(); stack.pop())\n          append_swap_gate(circ,stack.top().first,stack.top().second);\n      }\n      else\n        circ.append_gate() = g;\n    }\n\n    return 2*NNC(base);\n  }\n\n\n\n\n  /**\n   * @brief Function applies a permutation on a gate permuting its control and target line\n   *\n   * @param src_gate The gate to transform\n   * @param allocation Array representing the lines and their current position\n   * @return the transformed gate\n   */\n  inline gate transform_gate(const gate src_gate, unsigned* allocation){\n    gate transformedgate;\n    transformedgate.set_type(src_gate.type());\n    transformedgate.add_target(allocation[src_gate.targets().front()]);\n    if(src_gate.size() > 1){\n      transformedgate.add_control(make_var(allocation[src_gate.controls().front().line()]));\n    }\n    return transformedgate;\n  }\n\n  /**\n   * @brief Function applies a permutation on a gate permuting its control and target line\n   *\n   * @param src_gate The gate to transform\n   * @param allocation Array representing the lines and their current position\n   * @param len the length of the allocation array\n   * @return the transformed gate\n   */\n  inline gate transform_gate2(const gate src_gate, unsigned* allocation, unsigned len){\n    gate transformedgate;\n    transformedgate.set_type(src_gate.type());\n\n    if(src_gate.size() == 1){\n      auto tar = lookup(src_gate.targets().front(), allocation, len);\n      transformedgate.add_target(tar);\n    }else{\n      auto ctrltar = lookup2(src_gate.controls().front().line(),src_gate.targets().front(), allocation, len);\n      transformedgate.add_control(make_var(ctrltar.first));\n      transformedgate.add_target(ctrltar.second);\n    }\n    return transformedgate;\n  }\n\n  /**\n   * @brief Function creates and initiates an allocation array\n   *\n   * @return the allocation array\n   */\n  unsigned* init_allocation(unsigned lines){\n    unsigned *allocation;\n    allocation = new unsigned[lines];\n    for(unsigned i=0; i<lines; ++i)\n      allocation[i] = i;\n    return allocation;\n  }\n\n\n/**\n * @brief After switching lines in other functions and changing the allocation, this function maps the allocation on the output and garbage strings\n *\n * @param circ Target circuit of the performing action\n * @param allocation Array representing the lines and their current position\n * @param length Length of the allocation array\n *\n * @return Returns true if the inputs have the right length and the action can be performed\n */\n  bool permute_outputs_and_garbage_lines(circuit& circ, unsigned* allocation, unsigned length){\n    if(circ.lines() != length)\n      return false;\n\n    std::vector<std::string> out = circ.outputs();\n    std::vector<std::string> new_out( circ.lines() );\n    std::vector<bool> garbage = circ.garbage();\n    std::vector<bool> new_garbage( circ.lines() );\n\n    for ( unsigned u = 0; u<length; u++ ){\n      new_out[u] = out[allocation[u]];\n      new_garbage[u] = garbage[allocation[u]];\n    }\n\n    circ.set_outputs(new_out);\n    circ.set_garbage(new_garbage);\n\n    return true;\n}\n\n/**\n * @brief After switching lines in other functions and changing the allocation, this function maps the allocation on the input and constant strings\n *\n * @param circ Target circuit of the performing action\n * @param allocation Array representing the lines and their current position\n * @param length Length of the allocation array\n *\n * @return Returns true if the inputs have the right length and the action can be performed\n */\n  bool permute_inputs_and_constant_inputs(circuit& circ, unsigned* allocation, unsigned length){\n    if(circ.lines() != length){\n      return false;\n    }\n\n    std::vector<std::string> in = circ.inputs();\n    std::vector<std::string> new_in( length );\n    std::vector<constant> constants = circ.constants();\n    std::vector<constant> new_constants ( length );\n\n    for ( unsigned u = 0; u<length; u++ ){\n      new_in[u] = in[allocation[u]];\n      if ( constants[u] )\n        new_constants[u] = constants[allocation[u]];\n    }\n    circ.set_inputs(new_in);\n    circ.set_constants(new_constants);\n\n    return true;\n  }\n\n  /**\n   * @brief Modifies the allocation by swaping two entries in the allocation table\n   *\n   * @param allocation Array representing the lines and their current position\n   * @param l1 first line to swap\n   * @param l2 second line to swap\n   * @param length Length of the allocation array\n   */\n  inline void modify_allocation(unsigned* allocation, unsigned l1, unsigned l2, unsigned length ){\n    if(l1 < length && l2 < length){\n      //switch allocation table entries\n      allocation[l2] += allocation[l1];\n      allocation[l1] =  allocation[l2]-allocation[l1];\n      allocation[l2] -= allocation[l1];\n    }\n  }\n\n/**\n * @brief applies the optimization of the heuristic one-side-swapping lnn_optimization_mode on a circuit wrt. moving the target line towards the control line or the control line towards the target line\n *\n * @param circ Target circuit of the performing action\n * @param base Source circuit providing metadata and gates\n * @param towardstarget this param is set if the control lines should be moved by swap gates towards the target line\n *\n * @return the number of swaps in the circuit\n */\n  unsigned apply_directed_local_reordering_scheme(circuit& circ, const circuit& base, bool towardstarget){\n    copy_metadata(base,circ);\n    unsigned num_swap_gates = 0;\n\n    unsigned* allocation = init_allocation(base.lines());\n\n    for ( const gate& g : base ){\n      unsigned nnc_val = nnc(g, allocation, base.lines());\n      if(nnc_val>0){\n\n        auto ctrltar = lookup2(g.controls().front().line(),g.targets().front(), allocation, base.lines());\n\n        bool direction = towardstarget ?\n          (ctrltar.first > ctrltar.second):\n          (ctrltar.first < ctrltar.second);\n        unsigned s = towardstarget ? ctrltar.first : ctrltar.second;\n\n        for(unsigned i = 0; i < nnc_val; i++){\n          auto swap = direction ?\n            std::make_pair(s - i , s - 1 -i) :\n            std::make_pair(s + i , s + 1 +i) ;\n\n          append_swap_gate(circ , swap.first, swap.second);\n          num_swap_gates++;\n          modify_allocation(allocation, swap.first, swap.second, base.lines());\n        }\n\n        circ.append_gate() = transform_gate2(g, allocation, base.lines());\n\n      }\n      else\n        circ.append_gate() = transform_gate2(g, allocation, base.lines());\n    }\n\n    //clean up\n    permute_outputs_and_garbage_lines(circ, allocation, base.lines());\n    delete allocation;\n\n    return num_swap_gates;\n  }\n\n/**\n * @brief applies the optimization of the heuristic one-side-swapping lnn_optimization_mode on a circuit.\n *\n * @param circ Target circuit of the performing action\n * @param base Source circuit providing metadata and gates\n *\n * @return the nnc of the circuit\n */\n  unsigned apply_local_reordering_scheme(circuit& circ, const circuit& base){\n    circuit c1;\n    circuit c2;\n    copy_metadata(base,c1);\n    copy_metadata(base,c2);\n    unsigned cost1 = apply_directed_local_reordering_scheme(c1, base, true);\n    unsigned cost2 = apply_directed_local_reordering_scheme(c2, base, false);\n    copy_circuit( cost1 < cost2 ? c1 : c2 ,circ);\n    return (cost1 < cost2 ? cost1 : cost2);\n  }\n\n  void switch_lines(circuit& circ, const circuit& base, unsigned l1, unsigned l2 ){\n    for( gate cg : base) {\n      gate g(cg);\n      switch( cg.size() ){\n      case 2:\n        if(cg.controls().front().line() == l1)\n          g = set_gate_control_line(cg,l2);\n        else if (cg.controls().front().line() == l2 )\n          g = set_gate_control_line(cg,l1);\n        //no break - check target line in case 1\n      case 1:\n        if( cg.targets().front() == l1)\n          g = set_gate_control_line(g,l2);\n        else if( cg.targets().front() == l2 )\n          g = set_gate_control_line(g,l1);\n        circ.append_gate() = g;\n        break;\n      }\n    }\n\n    //change circuit metadata: inputs, outputs, constant and garbage lines\n    std::vector<std::string> out = base.outputs();\n    std::string tmp_out;\n    std::vector<std::string> in = base.inputs();\n    std::string tmp_in;\n    std::vector<bool> garbage = base.garbage();\n    bool tmp_garbage;\n    std::vector<constant> constants = base.constants();\n    constant tmp_constants;\n\n    tmp_out = out[l1];\n    out[l1] = out[l2];\n    out[l2] = tmp_out;\n\n    tmp_in = in[l1];\n    in[l1] = in[l2];\n    in[l2] = tmp_in;\n\n    tmp_garbage = garbage[l1];\n    garbage[l1] = garbage[l2];\n    garbage[l2] = tmp_garbage;\n\n    tmp_constants = constants[l1];\n    constants[l1] = constants[l2];\n    constants[l2] = tmp_constants;\n\n    circ.set_inputs(in);\n    circ.set_constants(constants);\n    circ.set_outputs(out);\n    circ.set_garbage(garbage);\n  }\n\n  /**\n   * @brief calculates the impact of the lines. More precisely, for each gate g with\n     control line i and target line j, the NNC value is calculated.\n     This value is added to variables imp_i and imp_j which are used\n     to save the impacts of the circuit lines i and j on the total NNC\n     value, respectively.\n   *\n   * @param circ the circuit for which the impact should be calculated\n   *\n   * @return a vector mapping the impact to a specific line\n   */\n  std::vector< std::pair<unsigned,unsigned> > calculate_impact(const circuit& circ){\n    std::vector< std::pair<unsigned,unsigned> > impact;\n    for(unsigned line_index=0; line_index < circ.lines(); line_index++)\n      impact.push_back(std::make_pair(0,line_index));\n\n    //calculate impact\n    for ( const gate& g : circ) {\n      unsigned nnc_val = nnc(g);\n      if(nnc_val>0){\n        impact[g.controls().front().line()].first +=nnc_val;\n        impact[g.targets().front()].first +=nnc_val;\n      }\n    }\n    impact.shrink_to_fit();\n    return impact;\n  }\n\n  /**\n   * @brief Function switching a line with a middle line\n   *\n   * @param circ Target circuit of the performing action\n   * @param base Source circuit providing metadata and gates\n   * @param\n   *\n   * return the nnc of the circuit\n   */\n  unsigned switch_lines(circuit& circ, const circuit& base, unsigned proposedline){\n    unsigned middle = base.lines()/2;\n    if(base.lines()%2){\n      switch_lines(circ, base, proposedline, middle);\n      return NNC(circ);\n    }\n    else{\n      //two middle lines\n      circuit circ2;\n      copy_metadata(base,circ2);\n      switch_lines(circ, base, proposedline, middle);\n      switch_lines(circ2, base, proposedline, middle-1);\n      unsigned NNC1 = NNC(circ);\n      unsigned NNC2 = NNC(circ2);\n\n      if(NNC2 < NNC1){\n        circ = circ2;\n        return NNC2;\n      }\n      return NNC1;\n    }\n  }\n\n/**\n * @brief heuristic method for reordering the lines of a circuit, with the intention moving the line with the highest NNC impact in the middle\n *\n * @param circ Target circuit of the performing action\n * @param base Source circuit providing metadata and gates\n *\n * @return the nnc of the circuit\n */\n  unsigned global_reorder_circuit(circuit& circ, const circuit& base){\n    auto impact = calculate_impact(base);\n    std::sort(impact.begin(), impact.end(), [](std::pair<unsigned,unsigned> a, std::pair<unsigned,unsigned> b){ return a.first > b.first; });\n    //multiple lines may have the same highest impact (unspecified in the algorithm)\n    std::vector<unsigned> max_lines = [](std::vector<std::pair<unsigned,unsigned>> input){\n      unsigned max = input[0].first;\n      std::vector<unsigned> out;\n      for(std::pair<unsigned,unsigned> p : input)\n        if(p.first == max)\n          out.push_back(p.second);\n      return out;\n    }(impact);\n\n    unsigned best_nnc = UINT_MAX;\n    for(unsigned line : max_lines){\n      if (max_lines.size() < impact.size() && (line == base.lines()/2 || line+1 == base.lines()/2))\n        line = impact[max_lines.size()].second; //select line with the next highest impact\n      circuit circ2;\n      copy_metadata(base,circ2);\n      unsigned circ_nnc = switch_lines(circ2, base, line);\n      if(circ_nnc < best_nnc){\n        circ = circ2;\n        best_nnc = circ_nnc;\n      }\n    }\n    return best_nnc;\n  }\n\n  /**\n   * @brief An ordering of the circuit lines which reduces the total NNC value\n     is desired. To do that, the contribution of each line to the total\n     NNC value is calculated. More precisely, for each gate g with\n     control line i and target line j, the NNC value is calculated.\n     This value is added to variables imp_i and imp_j which are used\n     to save the impacts of the circuit lines i and j on the total NNC\n     value, respectively.\n     Next, the line with the highest NNC impact is chosen for\n     reordering and placed at the middle line (i.e., swapped with the\n     middle line). If the selected line is the middle line itself, a\n     line with the next highest impact is selected. This procedure is\n     repeated until no better NNC value is achieved.\n  *\n  * @param circ Target circuit of the performing action\n  * @param base Source circuit providing metadata and gates\n  *\n  * @return the nnc of the circuit\n  */\nunsigned apply_global_reordering_scheme( circuit& circ, const circuit& base) {\n  copy_metadata(base,circ);\n  unsigned circ_nnc = global_reorder_circuit(circ, base);\n  while (true){\n    circuit circ2;\n    copy_metadata(base,circ2);\n    unsigned circ2_nnc = global_reorder_circuit(circ2, circ);\n    if(circ2_nnc < circ_nnc){\n      circ = circ2;\n      circ_nnc = circ2_nnc;\n    }\n    else\n      return 2*circ_nnc;\n  }\n}\n\n  /**\n   * @brief Applies the linear nearest neighbor optimization to a quantum circuit. Different modes are possible.\n      The global and local reordering scheme have been introduced in [\\ref SWD10].\n   *  reordering mode:\n   *  1: naive, 2: local reordering, 3: global reordering\n   *\n   */\n  bool lnn_optimization( circuit& circ, const circuit& base, properties::ptr settings, properties::ptr statistics )\n  {\n    /* settings */\n    bool verbose = get(settings, \"verbose\", false);\n    /*  1: naive, 2: local reordering, 3: global reordering */\n    unsigned reordering_mode = get<unsigned>(settings, \"reordering_mode\", 0u);\n    \n    // Run-time measuring\n    properties_timer t( statistics );\n\n    unsigned number_of_swaps;\n    switch(reordering_mode) {\n    case LNN_OPTIMIZATION_NONE:\n      copy_circuit(base,circ);\n      number_of_swaps = NNC(base)*2;\n      break;\n    case LNN_OPTIMIZATION_NAIVE:\n      if(NNC(base) == 0)\n\tcopy_circuit(base,circ);\n      else\n\tnumber_of_swaps = apply_naive_scheme(circ,base);\n      break;\n    case LNN_OPTIMIZATION_LOCAL_REORDER:\n      if(NNC(base) == 0)\n\tcopy_circuit(base,circ);\n      else\n\tnumber_of_swaps = apply_local_reordering_scheme(circ, base);\n      break;\n    case LNN_OPTIMIZATION_GLOBAL_REORDER:\n      number_of_swaps = apply_global_reordering_scheme(circ, base);\n      break;\n\n    default:\n      if(verbose)\n\tstd::cout << \"invalid mode.\" << std::endl;\n      return false;\n    }\n\n    if(verbose)\n      std::cout << \"SWAP gates: \" << number_of_swaps << std::endl;\n    \n    return true;\n}\n\noptimization_func lnn_optimization_func( properties::ptr settings, properties::ptr statistics )\n{\n    optimization_func f = [&settings, &statistics]( circuit& circ, const circuit& base ) {\n      return lnn_optimization( circ, base, settings, statistics );\n    };\n    f.init( settings, statistics );\n    return f;\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": "9cd417c2fcb97ff455a305c14b301a8947f420db", "size": 22576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/optimization/lnn_optimization.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/optimization/lnn_optimization.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/optimization/lnn_optimization.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.2979351032, "max_line_length": 201, "alphanum_fraction": 0.6740343728, "num_tokens": 5546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.039638838250092824, "lm_q1q2_score": 0.017354814863477508}}
{"text": "#include <Core/Geometry/Approximation/VariationalShapeApproximation.hpp>\r\n\r\n#include <set>\r\n#include <random>\r\n#include <Eigen/Eigenvalues>\r\n#include <Core/Log/Log.hpp>\r\n#include <Core/Geometry/Triangle/TriangleOperation.hpp>\r\n\r\nnamespace Ra {\r\nnamespace Core {\r\nnamespace Geometry {\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// CONSTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline VariationalShapeApproximationBase< K_Region >::VariationalShapeApproximationBase( const Mesh& mesh ) :\r\n    m_mesh( mesh ),\r\n    m_queue(),\r\n    m_region(),\r\n    m_proxy(),\r\n    m_init( false ) {}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline VariationalShapeApproximationBase< K_Region >::~VariationalShapeApproximationBase() {}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// INIT\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::init() {\r\n    this->compute_data();\r\n    this->compute_seed();\r\n    this->m_init = true;\r\n}\r\n\r\n\r\n\r\ntemplate < uint K_Region >\r\ninline bool VariationalShapeApproximationBase< K_Region >::initialized() const {\r\n    return m_init;\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// EXECUTION\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::exec( const uint iteration ) {\r\n    if( !this->initialized() ) {\r\n        CORE_WARN_IF( false, \"V.S.A. NOT INITIALIZED\" );\r\n        return;\r\n    }\r\n    LOG( logDEBUG ) << \"Computing V.S.A. ...\";\r\n    for( uint i = 0; i < iteration; ++i )  {\r\n        this->proxy_fitting();\r\n        this->geometry_partitioning();\r\n    }\r\n    LOG( logDEBUG ) << \"V.S.A. completed.\";\r\n}\r\n\r\n\r\n\r\ntemplate < uint K_Region >\r\ntemplate < uint Iteration >\r\ninline void VariationalShapeApproximationBase< K_Region >::exec() {\r\n    if( !this->initialized() ) {\r\n        CORE_WARN_IF( false, \"V.S.A. NOT INITIALIZED\" );\r\n        return;\r\n    }\r\n    LOG( logDEBUG ) << \"Computing V.S.A. ...\";\r\n    for( uint i = 0; i < Iteration; ++i )  {\r\n        this->proxy_fitting();\r\n        this->geometry_partitioning();\r\n    }\r\n    LOG( logDEBUG ) << \"V.S.A. completed.\";\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// REGION\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline const typename VariationalShapeApproximationBase< K_Region >::Region& VariationalShapeApproximationBase< K_Region >::region( const uint i ) const {\r\n    return m_region.at( i );\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline const typename VariationalShapeApproximationBase< K_Region >::Proxy& VariationalShapeApproximationBase< K_Region >::proxy( const uint i ) const {\r\n    return m_proxy.at( i );\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// COLOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::create_region_color() {\r\n    for( uint i = 0; i < K; ++i ) {\r\n        const Scalar q = Scalar( i ) / static_cast< Scalar >( K - 1 );\r\n        for( const auto& T : this->m_region[i] ) {\r\n            this->m_fvalue[T]  = q;\r\n        }\r\n    }\r\n}\r\n\r\n\r\n\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::create_energy_color() {\r\n    for( uint i = 0; i < K; ++i ) {\r\n        for( const auto& T : this->m_region[i] ) {\r\n            this->m_fvalue[T]  = this->E( T, this->m_proxy[i] );\r\n        }\r\n    }\r\n}\r\n\r\n\r\n\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::shuffle_regions() {\r\n    //This function was made in order to have a chance for neighboring regions\r\n    //to have distant IDs, hence having a different color.\r\n    std::array< uint, K > id;\r\n    RegionList tmp_region;\r\n    ProxyList  tmp_proxy;\r\n    for( uint i = 0; i < K; ++i ) {\r\n        id[i] = i;\r\n    }\r\n    std::random_shuffle( id.begin(), id.end() );\r\n    for( uint i = 0; i < K; ++i ) {\r\n        tmp_region[i] = this->m_region[id[i]];\r\n        tmp_proxy[i]  = this->m_proxy[id[i]];\r\n    }\r\n    std::swap( tmp_region, this->m_region );\r\n    std::swap( tmp_proxy,  this->m_proxy  );\r\n    for( uint i = 0; i < K; ++i ) {\r\n        for( const auto& T : this->m_region[i] ) {\r\n            this->m_fregion[T] = i;\r\n        }\r\n    }\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DATA\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::compute_data() {\r\n    const uint size = this->m_mesh.m_triangles.size();\r\n    this->m_fbary.resize( size );\r\n    this->m_fnormal.resize( size );\r\n    this->m_farea.resize( size );\r\n    this->m_fregion.resize( size, -1 );\r\n    this->m_fvisited.resize( size, false );\r\n    this->m_fvalue.resize( 0 );\r\n    this->m_fadj.resize( size );\r\n\r\n    std::vector< std::vector< TriangleIdx > > vadj( this->m_mesh.m_vertices.size() );\r\n    for( uint t = 0; t < size; ++t ) {\r\n        const Triangle& T    = this->m_mesh.m_triangles[t];\r\n        const uint      i    = T[0];\r\n        const uint      j    = T[1];\r\n        const uint      k    = T[2];\r\n        const Vector3   v[3] = { this->m_mesh.m_vertices[i], this->m_mesh.m_vertices[j], this->m_mesh.m_vertices[k] };\r\n        this->m_fbary[t] = triangleBarycenter( v[0], v[1], v[2] );\r\n        this->m_fnormal[t] = triangleNormal( v[0], v[1], v[2] );\r\n        this->m_farea[t] = triangleArea( v[0], v[1], v[2] );\r\n        vadj[i].push_back( t );\r\n        vadj[j].push_back( t );\r\n        vadj[k].push_back( t );\r\n    }\r\n\r\n    for( const auto& list : vadj ) {\r\n        for( uint i = 0; i < list.size(); ++i ) {\r\n            for( uint j = i+1; j < list.size(); ++j ) {\r\n                this->m_fadj[list[i]].insert( list[j] );\r\n                this->m_fadj[list[j]].insert( list[i] );\r\n            }\r\n        }\r\n    }\r\n\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// SEED\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::compute_seed() {\r\n    std::set< TriangleIdx > t;\r\n    std::default_random_engine g(time(0));\r\n    std::uniform_int_distribution< TriangleIdx > rnd( 0, this->m_mesh.m_triangles.size()-1 );\r\n    while( t.size() != K ) {\r\n        t.insert( rnd(g) );\r\n    }\r\n    for( uint i = 0; i < K; ++i ) {\r\n        m_region[i].push_back( *t.begin() );\r\n        t.erase( t.begin() );\r\n    }\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// GEOMETRY PARTITIONING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::geometry_partitioning() {\r\n    //Reset the visited flag\r\n    for( TriangleIdx T = 0; T < this->m_mesh.m_triangles.size(); ++T ) {\r\n        this->m_fvisited[T] = false;\r\n    }\r\n\r\n    //Force the queue to be empty\r\n    this->m_queue = PriorityQueue();\r\n\r\n    //Choose best triangle in each region\r\n    for( uint i = 0; i < K; ++i ) {\r\n        assert( !this->m_region[i].empty() );\r\n        Energy min_e = std::numeric_limits< Energy >::max();\r\n        TriangleIdx T;\r\n        for( const auto& t : this->m_region[i] ) {\r\n            const Energy e = this->E( t, this->m_proxy[i] );\r\n            if( e < min_e ) {\r\n                min_e = e;\r\n                T = t;\r\n            }\r\n        }\r\n        this->add_neighbors_to_queue( T, i );\r\n\r\n        // Clear the region\r\n        this->m_region[i].clear();\r\n        this->m_region[i].push_back( T );\r\n        this->m_fregion[T]  = i;\r\n        this->m_fvisited[T] = true;\r\n    }\r\n\r\n    //While the queue is not empty\r\n     while( !this->m_queue.empty() ) {\r\n         const auto q = this->m_queue.top();\r\n         this->m_queue.pop();\r\n         const TriangleIdx t = q.second.first;\r\n         if( this->m_fvisited[t] ) {\r\n             continue;\r\n         }\r\n         const uint R = q.second.second;\r\n         this->m_region[R].push_back( t );\r\n         this->m_fregion[t]  = R;\r\n         this->m_fvisited[t] = true;\r\n\r\n         this->add_neighbors_to_queue( t, R );\r\n     }\r\n}\r\n\r\n\r\n\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximationBase< K_Region >::add_neighbors_to_queue( const TriangleIdx& T, const uint proxy_id ) {\r\n    for( const auto& r : this->m_fadj[T] ) {\r\n        this->m_queue.push( QueueEntry( this->E( r, this->m_proxy[proxy_id] ), Pair( r, proxy_id ) ) );\r\n    }\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n//============================================================================\r\n//============================================================================\r\n//============================================================================\r\n\r\n\r\n\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region, MetricType Type >\r\nVariationalShapeApproximation< K_Region, Type >::~VariationalShapeApproximation() {}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY FITTING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region, MetricType Type >\r\ninline void VariationalShapeApproximation< K_Region, Type >::proxy_fitting() {\r\n    static const Scalar c = 2.0 / 72.0;\r\n    Matrix3 m;\r\n    m << 10.0, 7.0, 0.0, 7.0, 10.0, 0.0, 0.0, 0.0, 0.0;\r\n    for( uint i = 0; i < this->K; ++i ) {\r\n\r\n        Scalar area_sum         = 0;\r\n        this->m_proxy[i].first  = Vector3::Zero();\r\n        Matrix3 Q               = Matrix3::Zero();\r\n\r\n        for( const auto& T : this->m_region[i] ) {\r\n            const Vector3  v[3] = { this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][0]],\r\n                                    this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][1]],\r\n                                    this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][2]] };\r\n            const Vector3& g    = this->m_fbary[T];\r\n\r\n            Matrix3 M;\r\n            M.row(0) = v[1] - v[0];\r\n            M.row(1) = v[2] - v[0];\r\n            M.row(2) = Vector3::Zero();\r\n\r\n            Q += ( c * this->m_farea[T] * M * m * M.transpose() ) + ( this->m_farea[T] * g * g.transpose() );\r\n\r\n            this->m_proxy[i].first += this->m_farea[T] * g;\r\n            area_sum               += this->m_farea[T];\r\n        }\r\n        this->m_proxy[i].first /= area_sum;\r\n        Q -= area_sum * this->m_proxy[i].first * this->m_proxy[i].first.transpose();\r\n        this->m_proxy[i].second = Eigen::SelfAdjointEigenSolver<Matrix3>( Q ).eigenvectors().col( 0 ).normalized();\r\n    }\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// ENERGY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region, MetricType Type >\r\ninline Scalar VariationalShapeApproximation< K_Region, Type >::E( const TriangleIdx& T, const Proxy& P ) const {\r\n    static const Scalar c = 1.0 / 6.0;\r\n    const Vector3 v[3] = { this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][0]],\r\n                           this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][1]],\r\n                           this->m_mesh.m_vertices[this->m_mesh.m_triangles[T][2]] };\r\n    const Vector3 p    = P.first;\r\n    const Vector3 n    = P.second;\r\n    Scalar d[3];\r\n    d[0] = std::abs( n.dot( p - v[0] ) );\r\n    d[1] = std::abs( n.dot( p - v[1] ) );\r\n    d[2] = std::abs( n.dot( p - v[2] ) );\r\n    return ( c * ( ( d[0] * d[0] ) +\r\n                   ( d[1] * d[1] ) +\r\n                   ( d[2] * d[2] ) +\r\n                   ( d[0] * d[1] ) +\r\n                   ( d[0] * d[2] ) +\r\n                   ( d[1] * d[2] ) ) * this->m_farea[T] );\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n//============================================================================\r\n//============================================================================\r\n//============================================================================\r\n\r\n\r\n\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\nVariationalShapeApproximation< K_Region, MetricType::L21 >::~VariationalShapeApproximation() {}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY FITTING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximation< K_Region, MetricType::L21 >::proxy_fitting() {\r\n    for( uint i = 0; i < this->K; ++i ) {\r\n        Scalar area_sum = 0;\r\n        this->m_proxy[i].first  = Vector3::Zero();\r\n        this->m_proxy[i].second = Vector3::Zero();\r\n        for( const auto& T : this->m_region[i] ) {\r\n            this->m_proxy[i].first  += this->m_farea[T] * this->m_fbary[T];\r\n            this->m_proxy[i].second += this->m_farea[T] * this->m_fnormal[T];\r\n            area_sum                += this->m_farea[T];\r\n        }\r\n        this->m_proxy[i].first  /= area_sum;\r\n        this->m_proxy[i].second = this->m_proxy[i].second.normalized();\r\n    }\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// ENERGY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline Scalar VariationalShapeApproximation< K_Region, MetricType::L21 >::E( const TriangleIdx& T, const Proxy& P ) const {\r\n    const Scalar  a      = this->m_farea[T];\r\n    const Vector3 n      = this->m_fnormal[T];\r\n    const Vector3 d      = n - P.second;\r\n    const Scalar  result = a * d.squaredNorm();\r\n    return result;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n//============================================================================\r\n//============================================================================\r\n//============================================================================\r\n\r\n\r\n\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// DESTRUCTOR\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\nVariationalShapeApproximation< K_Region, MetricType::LLOYD >::~VariationalShapeApproximation() {}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// PROXY FITTING\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline void VariationalShapeApproximation< K_Region, MetricType::LLOYD >::proxy_fitting() {\r\n    for( uint i = 0; i < this->K; ++i ) {\r\n        this->m_proxy[i].first  = Vector3::Zero();\r\n        this->m_proxy[i].second = Vector3::Zero();\r\n        for( const auto& T : this->m_region[i] ) {\r\n            this->m_proxy[i].first  += this->m_fbary[T];\r\n            this->m_proxy[i].second += this->m_fnormal[T];\r\n        }\r\n        this->m_proxy[i].first  /= this->m_region[i].size();\r\n        this->m_proxy[i].second  = this->m_proxy[i].second.normalized();\r\n    }\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n// ENERGY\r\n//////////////////////////////////////////////////////////////////////////////\r\ntemplate < uint K_Region >\r\ninline Scalar VariationalShapeApproximation< K_Region, MetricType::LLOYD >::E( const TriangleIdx& T, const Proxy& P ) const {\r\n    const Vector3& b     = this->m_fbary[T];\r\n    const Scalar  result = (b - P.first).norm();\r\n    return result;\r\n}\r\n\r\n\r\n\r\n} // namespace Geometry\r\n} // namespace Core\r\n} // namespace Ra\r\n\r\n\r\n", "meta": {"hexsha": "5f87a4681c6f2de7843610c34ea913e7517a3a63", "size": 16483, "ext": "inl", "lang": "C++", "max_stars_repo_path": "src/Core/Geometry/Approximation/VariationalShapeApproximation.inl", "max_stars_repo_name": "nmellado/Radium-Engine", "max_stars_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "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/Core/Geometry/Approximation/VariationalShapeApproximation.inl", "max_issues_repo_name": "nmellado/Radium-Engine", "max_issues_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/Geometry/Approximation/VariationalShapeApproximation.inl", "max_forks_repo_name": "nmellado/Radium-Engine", "max_forks_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "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.4832635983, "max_line_length": 155, "alphanum_fraction": 0.4319602014, "num_tokens": 3636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.037892428530966804, "lm_q1q2_score": 0.017322019810775045}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <cstddef>\n#include <functional>\n#include <initializer_list>\n#include <iterator>\n#include <map>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <binary_quadratic_model.hpp>\n#include <boost/container/small_vector.hpp>\n#include <boost/functional/hash.hpp>\n#include <robin_hood.h>\n\n#include \"abstract_syntax_tree.hpp\"\n\nnamespace pyqubo {\n  class variables final {\n    robin_hood::unordered_map<std::string, int> _indexes;\n    robin_hood::unordered_map<int, std::string> _names;\n\n  public:\n    variables() noexcept : _indexes{}, _names{} {\n      ;\n    }\n\n    auto index(const std::string& variable_name) noexcept {\n      const auto [it, emplaced] = _indexes.emplace(variable_name, std::size(_indexes));\n\n      if (emplaced) {\n        _names.emplace(it->second, variable_name);\n      }\n\n      return it->second;\n    }\n\n    const auto& name(int index) const noexcept {\n      return _names.find(index)->second;\n    }\n\n    auto names() const noexcept {\n      auto result = std::vector<std::string>(std::size(_names));\n\n      for (const auto& [index, name] : _names) {\n        result[index] = name;\n      }\n\n      return result;\n    }\n  };\n\n  using indexes = boost::container::small_vector<int, 2>;\n\n  class product final {\n    pyqubo::indexes _indexes;\n    std::size_t _hash;\n\n  public:\n    product(const pyqubo::indexes& indexes) noexcept : _indexes(indexes), _hash(boost::hash_range(std::begin(indexes), std::end(indexes))) {\n      ;\n    }\n\n    product(std::initializer_list<int> init) noexcept : product(pyqubo::indexes(init)) {\n      ;\n    }\n\n    const auto& indexes() const noexcept {\n      return _indexes;\n    }\n\n    friend std::hash<product>;\n  };\n\n  inline auto operator*(const product& product_1, const product& product_2) noexcept {\n    return product([&] {\n      auto result = indexes{};\n\n      std::set_union(std::begin(product_1.indexes()), std::end(product_1.indexes()),\n                     std::begin(product_2.indexes()), std::end(product_2.indexes()),\n                     std::back_inserter(result));\n\n      return result;\n    }());\n  }\n\n  inline bool operator==(const product& product_1, const product& product_2) noexcept {\n    return product_1.indexes() == product_2.indexes();\n  }\n}\n\nnamespace std {\n  template <>\n  struct hash<pyqubo::product> {\n    auto operator()(const pyqubo::product& product) const noexcept {\n      return product._hash;\n    }\n  };\n}\n\nnamespace pyqubo {\n  // std::variantを使用してzeroやmonomialな場合の処理削減をやってみたのですが、パフォーマンスは向上しませんでした。なので、unordered_map一本でやります。\n  // よく考えれば、要素数が0の場合の処理とかはunordered_mapの中でやっていそうですし。。。\n\n  using polynomial = robin_hood::unordered_map<product, std::shared_ptr<const expression>>;\n\n  inline auto operator+(const polynomial& polynomial_1, const polynomial& polynomial_2) noexcept {\n    auto result = polynomial_1;\n\n    for (const auto& [product, coefficient] : polynomial_2) {\n      const auto [it, emplaced] = result.emplace(product, coefficient);\n\n      if (!emplaced) {\n        it->second = it->second + coefficient;\n      }\n    }\n\n    return result;\n  }\n\n  inline auto operator*(const polynomial& polynomial_1, const polynomial& polynomial_2) noexcept {\n    auto result = polynomial{};\n\n    for (const auto& [product_1, coefficient_1] : polynomial_1) {\n      for (const auto& [product_2, coefficient_2] : polynomial_2) {\n        const auto [it, emplaced] = result.emplace(product_1 * product_2, coefficient_1 * coefficient_2);\n\n        if (!emplaced) {\n          it->second = it->second + coefficient_1 * coefficient_2;\n        }\n      }\n    }\n\n    return result;\n  }\n\n  class evaluate final {\n    std::unordered_map<std::string, double> _feed_dict;\n\n  public:\n    evaluate(const std::unordered_map<std::string, double>& feed_dict) noexcept : _feed_dict(feed_dict) {\n      ;\n    }\n\n    auto operator()(const std::shared_ptr<const expression>& expression) const noexcept {\n      return visit<double>(*this, expression);\n    }\n\n    auto operator()(const std::shared_ptr<const add_operator>& add_operator) const noexcept {\n      return std::accumulate(std::begin(add_operator->children()), std::end(add_operator->children()), 0.0, [&](const auto& acc, const auto& child) {\n        return acc + visit<double>(*this, child);\n      });\n    }\n\n    auto operator()(const std::shared_ptr<const mul_operator>& mul_operator) const noexcept {\n      return visit<double>(*this, mul_operator->lhs()) * visit<double>(*this, mul_operator->rhs());\n    }\n\n    auto operator()(const std::shared_ptr<const placeholder_variable>& place_holder_variable) const noexcept {\n      return _feed_dict.at(place_holder_variable->name());\n    }\n\n    auto operator()(const std::shared_ptr<const user_defined_expression>& user_defined_expression) const noexcept {\n      return visit<double>(*this, user_defined_expression->expression());\n    }\n\n    auto operator()(const std::shared_ptr<const numeric_literal>& numeric_literal) const noexcept {\n      return numeric_literal->value();\n    }\n  };\n\n  class solution final {\n    std::unordered_map<std::string, int> _sample;\n    double _energy;\n    std::unordered_map<std::string, double> _sub_hamiltonians;\n    std::unordered_map<std::string, std::pair<bool, double>> _constraints;\n\n  public:\n    solution(const std::unordered_map<std::string, int> sample, double energy, const std::unordered_map<std::string, double>& sub_hamiltonians, const std::unordered_map<std::string, std::pair<bool, double>>& constraints) noexcept : _sample(sample), _energy(energy), _sub_hamiltonians(sub_hamiltonians), _constraints(constraints) {\n      ;\n    }\n\n    const auto& sample() const noexcept {\n      return _sample;\n    }\n\n    auto energy() const noexcept {\n      return _energy;\n    }\n\n    const auto& sub_hamiltonians() const noexcept {\n      return _sub_hamiltonians;\n    }\n\n    const auto& constraints() const noexcept {\n      return _constraints;\n    }\n  };\n\n  class model final {\n    polynomial _quadratic_polynomial;\n    robin_hood::unordered_map<std::string, polynomial> _sub_hamiltonians;\n    robin_hood::unordered_map<std::string, std::pair<polynomial, std::function<bool(double)>>> _constraints;\n    variables _variables;\n\n    static auto to_cimod_vartype(const std::string vartype) noexcept {\n      return vartype == \"BINARY\" ? cimod::Vartype::BINARY : cimod::Vartype::SPIN;\n    }\n\n  public:\n    model(const polynomial& quadratic_polynomial, const robin_hood::unordered_map<std::string, polynomial>& sub_hamiltonians, const robin_hood::unordered_map<std::string, std::pair<polynomial, std::function<bool(double)>>>& constraints, const variables& variables) noexcept : _quadratic_polynomial(quadratic_polynomial), _sub_hamiltonians(sub_hamiltonians), _constraints(constraints), _variables(variables) {\n      ;\n    }\n\n    std::vector<std::string> variable_names() const noexcept {\n      return _variables.names();\n    }\n\n    template <typename T = std::string>\n    auto to_bqm_parameters(const std::unordered_map<std::string, double>& feed_dict) const noexcept { // 不格好でごめんなさい。PythonのBinaryQuadraticModelを作成可能にするために、このメンバ関数でBinaryQuadraticModelの引数を生成します。\n      const auto evaluate = pyqubo::evaluate(feed_dict);\n\n      auto linear = cimod::Linear<T, double>{};\n      auto quadratic = cimod::Quadratic<T, double>{};\n      auto offset = 0.0;\n\n      for (const auto& [product, coefficient] : _quadratic_polynomial) {\n        const auto coefficient_value = evaluate(coefficient);\n\n        switch (std::size(product.indexes())) {\n        case 0: {\n          offset = coefficient_value; // 次数が0の項は1つにまとめられるので、この処理は最大で1回しか実行されません。なので、+=ではなくて=を使用しています。\n          break;\n        }\n        case 1: {\n          linear.emplace(_variables.name(product.indexes()[0]), coefficient_value);\n          break;\n        }\n        case 2: {\n          quadratic.emplace(std::pair{_variables.name(product.indexes()[0]), _variables.name(product.indexes()[1])}, coefficient_value);\n          break;\n        }\n        default:\n          throw std::runtime_error(\"invalid term.\"); // ここには絶対にこないはず。\n        }\n      }\n\n      return std::tuple{linear, quadratic, offset};\n    }\n\n    template <typename T = std::string>\n    auto to_bqm(const std::unordered_map<std::string, double>& feed_dict, cimod::Vartype vartype) const noexcept {\n      const auto [linear, quadratic, offset] = to_bqm_parameters<T>(feed_dict);\n\n      return cimod::BinaryQuadraticModel<T, double, cimod::Dense>(linear, quadratic, offset, vartype);\n    }\n\n    template <typename T = std::string>\n    auto energy(const std::unordered_map<T, int>& sample, const std::string& vartype, const std::unordered_map<std::string, double>& feed_dict) const noexcept {\n      return to_bqm<T>(feed_dict, to_cimod_vartype(vartype)).energy([&] {\n        // BinaryQuadraticModelの引数でvartypeを設定しても、energyでは使われないみたい。。。Determine the energy of the specified sample of a binary quadratic modelって書いてある。\n        // しょうがないので、spinからbinaryに変換します。\n\n        auto result = sample;\n\n        if (vartype == \"SPIN\") {\n          for (const auto& [name, value] : sample) {\n            result[name] = (value + 1) / 2;\n          }\n        }\n\n        return result;\n      }());\n    }\n\n    template <typename T = std::string>\n    auto decode_sample(const std::unordered_map<T, int>& sample, const std::string& vartype, const std::unordered_map<std::string, double>& feed_dict) const noexcept {\n      const auto evaluate = pyqubo::evaluate(feed_dict);\n      const auto evaluate_polynomial = [&](const auto& polynomial, const auto& sample) {\n        return std::accumulate(std::begin(polynomial), std::end(polynomial), 0.0, [&](const auto acc, const auto& term) {\n          return acc +\n                 std::accumulate(std::begin(term.first.indexes()), std::end(term.first.indexes()), 1, [&](const auto acc, const auto& index) {\n                   const auto value = sample.at(_variables.name(index));\n\n                   return acc * (vartype == \"BINARY\" ? value : (value + 1) / 2);\n                 }) * evaluate(term.second);\n        });\n      };\n\n      return solution(\n          sample,\n          energy<T>(sample, vartype, feed_dict),\n          [&] {\n            auto result = std::unordered_map<std::string, double>{};\n\n            for (const auto& [name, polynomial] : _sub_hamiltonians) {\n              result.emplace(name, evaluate_polynomial(polynomial, sample));\n            }\n\n            return result;\n          }(),\n          [&] {\n            auto result = std::unordered_map<std::string, std::pair<bool, double>>{};\n\n            for (const auto& [name, pair] : _constraints) {\n              const auto& [polynomial, condition] = pair;\n              const auto energy = evaluate_polynomial(polynomial, sample);\n\n              result.emplace(name, std::pair{condition(energy), energy});\n            }\n\n            return result;\n          }());\n    }\n\n    template <typename T = std::string>\n    auto decode_samples(const std::vector<std::unordered_map<T, int>>& samples, const std::string& vartype, const std::unordered_map<std::string, double>& feed_dict) const noexcept {\n      auto result = std::vector<solution>{};\n\n      std::transform(std::begin(samples), std::end(samples), std::back_inserter(result), [&](const auto& sample) {\n        return decode_sample(sample, vartype, feed_dict);\n      });\n\n      return result;\n    }\n  };\n\n  template <>\n  inline auto model::to_bqm_parameters<int>(const std::unordered_map<std::string, double>& feed_dict) const noexcept { // メンバ関数を特殊化するときは、クラスの外に書かなければなりません。。。\n    const auto evaluate = pyqubo::evaluate(feed_dict);\n\n    auto linear = cimod::Linear<int, double>{};\n    auto quadratic = cimod::Quadratic<int, double>{};\n    auto offset = 0.0;\n\n    for (const auto& [product, coefficient] : _quadratic_polynomial) {\n      const auto coefficient_value = evaluate(coefficient);\n\n      switch (std::size(product.indexes())) {\n      case 0: {\n        offset = coefficient_value; // 次数が0の項は1つにまとめられるので、この処理は最大で1回しか実行されません。なので、+=ではなくて=を使用しています。\n        break;\n      }\n      case 1: {\n        linear.emplace(product.indexes()[0], coefficient_value);\n        break;\n      }\n      case 2: {\n        quadratic.emplace(std::pair{product.indexes()[0], product.indexes()[1]}, coefficient_value);\n        break;\n      }\n      default:\n        throw std::runtime_error(\"invalid term.\"); // ここには絶対にこないはず。\n      }\n    }\n\n    return std::tuple{linear, quadratic, offset};\n  }\n\n  template <>\n  inline auto model::decode_sample<int>(const std::unordered_map<int, int>& sample, const std::string& vartype, const std::unordered_map<std::string, double>& feed_dict) const noexcept {\n    const auto evaluate = pyqubo::evaluate(feed_dict);\n    const auto evaluate_polynomial = [&](const auto& polynomial, const auto& sample) {\n      return std::accumulate(std::begin(polynomial), std::end(polynomial), 0.0, [&](const auto acc, const auto& term) {\n        return acc +\n               std::accumulate(std::begin(term.first.indexes()), std::end(term.first.indexes()), 1, [&](const auto acc, const auto& index) {\n                 const auto value = sample.at(index);\n\n                 return acc * (vartype == \"BINARY\" ? value : (value + 1) / 2);\n               }) * evaluate(term.second);\n      });\n    };\n\n    return solution(\n        [&] {\n          auto result = std::unordered_map<std::string, int>{};\n\n          std::transform(std::begin(sample), std::end(sample), std::inserter(result, std::begin(result)), [&](const auto& index_and_value) {\n            return std::pair{_variables.name(index_and_value.first), index_and_value.second};\n          });\n\n          return result;\n        }(),\n        energy<int>(sample, vartype, feed_dict),\n        [&] {\n          auto result = std::unordered_map<std::string, double>{};\n\n          for (const auto& [name, polynomial] : _sub_hamiltonians) {\n            result.emplace(name, evaluate_polynomial(polynomial, sample));\n          }\n\n          return result;\n        }(),\n        [&] {\n          auto result = std::unordered_map<std::string, std::pair<bool, double>>{};\n\n          for (const auto& [name, pair] : _constraints) {\n            const auto& [polynomial, condition] = pair;\n            const auto energy = evaluate_polynomial(polynomial, sample);\n\n            result.emplace(name, std::pair{condition(energy), energy});\n          }\n\n          return result;\n        }());\n  }\n}\n", "meta": {"hexsha": "28c9f5b5de382de55c937a8a54004089dbc8e22f", "size": 14321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model.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/model.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/model.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": 34.8442822384, "max_line_length": 408, "alphanum_fraction": 0.6437399623, "num_tokens": 3653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.04813677299424019, "lm_q1q2_score": 0.017298630277841006}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2016 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include <trilinoswrap/PreconditionerFactory.h>\n#include <trilinoswrap/TrilinosAdapterException.h>\n#include <trilinoswrap/util.h>\n\n#include <escript/SolverOptions.h>\n\n#include <Ifpack2_Factory.hpp>\n#if 1 //ndef ESYS_INDEXTYPE_LONG\n#include <MueLu_CreateTpetraPreconditioner.hpp>\n#endif\n\n#include <boost/python/dict.hpp>\n\nusing Teuchos::RCP;\n\nnamespace bp = boost::python;\n\nnamespace esys_trilinos {\n\ntemplate<typename ST>\nRCP<OpType<ST> > createPreconditioner(RCP<const MatrixType<ST> > mat,\n                                      const escript::SolverBuddy& sb)\n{\n    using util::extractParamIfSet;\n\n    typedef MatrixType<ST> Matrix;\n\n    RCP<Teuchos::ParameterList> params = Teuchos::parameterList();\n    Ifpack2::Factory factory;\n    RCP<OpType<ST> > prec;\n    RCP<Ifpack2::Preconditioner<ST,LO,GO,NT> > ifprec;\n    const bp::dict& pyParams = sb.getTrilinosParameters();\n\n    switch (sb.getPreconditioner()) {\n        case escript::SO_PRECONDITIONER_NONE:\n            break;\n        case escript::SO_PRECONDITIONER_AMG:\n            {\n#if 1 //ndef ESYS_INDEXTYPE_LONG\n                params->set(\"max levels\", sb.getLevelMax());\n                params->set(\"number of equations\", 1);\n                params->set(\"cycle type\", sb.getCycleType()==1 ? \"V\" : \"W\");\n                params->set(\"problem: symmetric\", sb.isSymmetric());\n                params->set(\"verbosity\", sb.isVerbose()? \"high\":\"none\");\n                // override parameters if set explicitly for trilinos\n                // The set of available parameters is documented in the MueLu\n                // user's guide (PDF download)\n                // NOTE: passing sub parameter lists is not supported via\n                // python due to escript's SolverBuddy constraints.\n                // Use the 'xml parameter file' option instead.\n                extractParamIfSet<std::string>(\"problem: type\", pyParams, *params);\n                extractParamIfSet<std::string>(\"verbosity\", pyParams, *params);\n                extractParamIfSet<int>(\"number of equations\", pyParams, *params);\n                extractParamIfSet<int>(\"max levels\", pyParams, *params);\n                extractParamIfSet<std::string>(\"cycle type\", pyParams, *params);\n                extractParamIfSet<bool>(\"problem: symmetric\", pyParams, *params);\n                extractParamIfSet<std::string>(\"xml parameter file\", pyParams, *params);\n                extractParamIfSet<std::string>(\"smoother: pre or post\", pyParams, *params);\n                extractParamIfSet<std::string>(\"smoother: type\", pyParams, *params);\n                extractParamIfSet<std::string>(\"smoother: pre type\", pyParams, *params);\n                extractParamIfSet<std::string>(\"smoother: post type\", pyParams, *params);\n                extractParamIfSet<int>(\"coarse: max size\", pyParams, *params);\n                extractParamIfSet<std::string>(\"coarse: type\", pyParams, *params);\n                extractParamIfSet<std::string>(\"aggregation: type\", pyParams, *params);\n                extractParamIfSet<std::string>(\"aggregation: ordering\", pyParams, *params);\n                extractParamIfSet<std::string>(\"aggregation: drop scheme\", pyParams, *params);\n                extractParamIfSet<ST>(\"aggregation: drop tol\", pyParams, *params);\n                extractParamIfSet<int>(\"aggregation: min agg size\", pyParams, *params);\n                extractParamIfSet<int>(\"aggregation: max agg size\", pyParams, *params);\n                extractParamIfSet<ST>(\"aggregation: Dirichlet threshold\", pyParams, *params);\n                extractParamIfSet<bool>(\"aggregation: export visualization data\", pyParams, *params);\n                extractParamIfSet<std::string>(\"aggregation: output filename\", pyParams, *params);\n                extractParamIfSet<int>(\"aggregation: output file: time step\", pyParams, *params);\n                extractParamIfSet<int>(\"aggregation: output file: iter\", pyParams, *params);\n                extractParamIfSet<std::string>(\"aggregation: output file: agg style\", pyParams, *params);\n                extractParamIfSet<bool>(\"aggregation: output file: fine graph edges\", pyParams, *params);\n                extractParamIfSet<bool>(\"aggregation: output file: coarse graph edges\", pyParams, *params);\n                extractParamIfSet<bool>(\"aggregation: output file: build colormap\", pyParams, *params);\n                extractParamIfSet<bool>(\"repartition: enable\", pyParams, *params);\n                extractParamIfSet<std::string>(\"repartition: partitioner\", pyParams, *params);\n                extractParamIfSet<int>(\"repartition: start level\", pyParams, *params);\n                extractParamIfSet<int>(\"repartition: min rows per proc\", pyParams, *params);\n                extractParamIfSet<ST>(\"repartition: max imbalance\", pyParams, *params);\n                extractParamIfSet<bool>(\"repartition: remap parts\", pyParams, *params);\n                extractParamIfSet<bool>(\"repartition: rebalance P and R\", pyParams, *params);\n                extractParamIfSet<std::string>(\"multigrid algorithm\", pyParams, *params);\n                extractParamIfSet<int>(\"semicoarsen: coarsen rate\", pyParams, *params);\n                extractParamIfSet<ST>(\"sa: damping factor\", pyParams, *params);\n                extractParamIfSet<bool>(\"sa: use filtered matrix\", pyParams, *params);\n                extractParamIfSet<bool>(\"filtered matrix: use lumping\", pyParams, *params);\n                extractParamIfSet<bool>(\"filtered matrix: reuse eigenvalue\", pyParams, *params);\n                extractParamIfSet<std::string>(\"emin: iterative method\", pyParams, *params);\n                extractParamIfSet<int>(\"emin: num iterations\", pyParams, *params);\n                extractParamIfSet<int>(\"emin: num reuse iterations\", pyParams, *params);\n                extractParamIfSet<std::string>(\"emin: pattern\", pyParams, *params);\n                extractParamIfSet<int>(\"emin: pattern order\", pyParams, *params);\n                extractParamIfSet<std::string>(\"reuse: type\", pyParams, *params);\n                extractParamIfSet<bool>(\"print initial parameters\", pyParams, *params);\n                extractParamIfSet<bool>(\"print unused parameters\", pyParams, *params);\n                extractParamIfSet<bool>(\"transpose: use implicit\", pyParams, *params);\n                RCP<OpType<ST> > A(Teuchos::rcp_const_cast<Matrix>(mat));\n                prec = MueLu::CreateTpetraPreconditioner(A, *params);\n#else\n                throw escript::ValueError(\"MueLu (AMG) is incompatible with index type long!\");\n#endif\n            }\n            break;\n        case escript::SO_PRECONDITIONER_ILUT:\n            ifprec = factory.create<const Matrix>(\"ILUT\", mat);\n            params->set(\"fact: drop tolerance\", sb.getDropTolerance());\n            params->set(\"fact: relax value\", sb.getRelaxationFactor());\n            // override if set explicitly for trilinos\n            extractParamIfSet<ST>(\"fact: relax value\", pyParams, *params);\n            extractParamIfSet<ST>(\"fact: drop tolerance\", pyParams, *params);\n            extractParamIfSet<int>(\"fact: ilut level-of-fill\", pyParams, *params);\n            extractParamIfSet<ST>(\"fact: absolute threshold\", pyParams, *params);\n            extractParamIfSet<ST>(\"fact: relative threshold\", pyParams, *params);\n            break;\n        case escript::SO_PRECONDITIONER_GAUSS_SEIDEL:\n        case escript::SO_PRECONDITIONER_JACOBI:\n          {\n            ifprec = factory.create<const Matrix>(\"RELAXATION\", mat);\n            if (sb.getPreconditioner() == escript::SO_PRECONDITIONER_JACOBI) {\n                params->set(\"relaxation: type\", \"Jacobi\");\n            } else {\n                params->set(\"relaxation: type\", (sb.isSymmetric() ?\n                            \"Symmetric Gauss-Seidel\" : \"Gauss-Seidel\"));\n            }\n            params->set(\"relaxation: sweeps\", sb.getNumSweeps());\n            const ST fac = static_cast<ST>(sb.getRelaxationFactor());\n            params->set(\"relaxation: damping factor\", fac);\n            // override if set explicitly for trilinos\n            extractParamIfSet<int>(\"relaxation: sweeps\", pyParams, *params);\n            extractParamIfSet<ST>(\"relaxation: damping factor\", pyParams, *params);\n            extractParamIfSet<ST>(\"relaxation: min diagonal value\", pyParams, *params);\n            extractParamIfSet<bool>(\"relaxation: zero starting solution\", pyParams, *params);\n            extractParamIfSet<bool>(\"relaxation: backward mode\", pyParams, *params);\n            break;\n          }\n        case escript::SO_PRECONDITIONER_ILU0: // to avoid test failures\n        case escript::SO_PRECONDITIONER_RILU:\n            if (dynamic_cast<const Tpetra::Experimental::BlockCrsMatrix<ST,LO,GO,NT>* >(mat.get())) {\n                ifprec = factory.create<const Matrix>(\"RBILUK\", mat);\n            } else {\n                ifprec = factory.create<const Matrix>(\"RILUK\", mat);\n            }\n            params->set(\"fact: relax value\", sb.getRelaxationFactor());\n            // override if set explicitly for trilinos\n            extractParamIfSet<ST>(\"fact: relax value\", pyParams, *params);\n            extractParamIfSet<int>(\"fact: iluk level-of-fill\", pyParams, *params);\n            extractParamIfSet<int>(\"fact: iluk level-of-overlap\", pyParams, *params);\n            extractParamIfSet<ST>(\"fact: absolute threshold\", pyParams, *params);\n            extractParamIfSet<ST>(\"fact: relative threshold\", pyParams, *params);\n            break;\n        default:\n            throw escript::ValueError(\"Unsupported preconditioner requested.\");\n    }\n    if (!ifprec.is_null()) {\n        ifprec->setParameters(*params);\n        ifprec->initialize();\n        ifprec->compute();\n        prec = ifprec;\n    }\n    return prec;\n}\n\n// instantiate our two supported versions\ntypedef MatrixType<real_t> RealMatrix;\ntypedef MatrixType<cplx_t> ComplexMatrix;\n\ntemplate\nRCP<RealOperator> createPreconditioner<real_t>(RCP<const RealMatrix> mat,\n                                               const escript::SolverBuddy& sb);\ntemplate\nRCP<ComplexOperator> createPreconditioner<cplx_t>(RCP<const ComplexMatrix> mat,\n                                               const escript::SolverBuddy& sb);\n\n}  // end of namespace\n\n", "meta": {"hexsha": "6ddf5a747a8585b9d4f03a09029c683149152323", "size": 10785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trilinoswrap/src/PreconditionerFactory.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "trilinoswrap/src/PreconditionerFactory.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "trilinoswrap/src/PreconditionerFactory.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": 55.0255102041, "max_line_length": 107, "alphanum_fraction": 0.6189151599, "num_tokens": 2484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.0356785520312679, "lm_q1q2_score": 0.01728198003978632}}
{"text": "#include \"trajopt/collision_terms.hpp\"\n#include \"trajopt/collision_checker.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"trajopt/utils.hpp\"\n#include \"sco/expr_vec_ops.hpp\"\n#include \"sco/expr_ops.hpp\"\n#include \"sco/sco_common.hpp\"\n#include <boost/foreach.hpp>\n#include \"utils/eigen_conversions.hpp\"\n#include \"sco/modeling_utils.hpp\"\n#include \"utils/stl_to_string.hpp\"\n#include \"utils/logging.hpp\"\n#include <boost/functional/hash.hpp>\nusing namespace OpenRAVE;\nusing namespace sco;\nusing namespace util;\nusing namespace std;\n\nnamespace trajopt {\n\n\nvoid CollisionsToDistances(const vector<Collision>& collisions, const Link2Int& m_link2ind,\n    DblVec& dists) {\n  // Note: this checking (that the links are in the list we care about) is probably unnecessary\n  // since we're using LinksVsAll\n  dists.clear();\n  dists.reserve(collisions.size());\n  BOOST_FOREACH(const Collision& col, collisions) {\n    Link2Int::const_iterator itA = m_link2ind.find(col.linkA);\n    Link2Int::const_iterator itB = m_link2ind.find(col.linkB);\n    if (itA != m_link2ind.end() || itB != m_link2ind.end()) {\n      dists.push_back(col.distance);\n    }\n  }\n}\n\nvoid CollisionsToDistanceExpressions(const vector<Collision>& collisions, Configuration& rad,\n    const Link2Int& link2ind, const VarVector& vars, const DblVec& dofvals, vector<AffExpr>& exprs, bool isTimestep1) {\n\n  exprs.clear();\n  exprs.reserve(collisions.size());\n  rad.SetDOFValues(dofvals); // since we'll be calculating jacobians\n  BOOST_FOREACH(const Collision& col, collisions) {\n    AffExpr dist(col.distance);\n    Link2Int::const_iterator itA = link2ind.find(col.linkA);\n    if (itA != link2ind.end()) {\n      VectorXd dist_grad = toVector3d(col.normalB2A).transpose()*rad.PositionJacobian(itA->second, col.ptA);\n      exprInc(dist, varDot(dist_grad, vars));\n      exprInc(dist, -dist_grad.dot(toVectorXd(dofvals)));\n    }\n    Link2Int::const_iterator itB = link2ind.find(col.linkB);\n    if (itB != link2ind.end()) {\n      VectorXd dist_grad = -toVector3d(col.normalB2A).transpose()*rad.PositionJacobian(itB->second, (isTimestep1 && (col.cctype == CCType_Between)) ? col.ptB1 : col.ptB);\n      exprInc(dist, varDot(dist_grad, vars));\n      exprInc(dist, -dist_grad.dot(toVectorXd(dofvals)));\n    }\n    if (itA != link2ind.end() || itB != link2ind.end()) {\n      exprs.push_back(dist);\n    }\n  }\n  LOG_DEBUG(\"%ld distance expressions\\n\", exprs.size());\n}\n\nvoid CollisionsToDistanceExpressions(const vector<Collision>& collisions, Configuration& rad, const Link2Int& link2ind,\n    const VarVector& vars0, const VarVector& vars1, const DblVec& vals0, const DblVec& vals1,\n    vector<AffExpr>& exprs) {\n  vector<AffExpr> exprs0, exprs1;\n  CollisionsToDistanceExpressions(collisions, rad, link2ind, vars0, vals0, exprs0, false);\n  CollisionsToDistanceExpressions(collisions, rad, link2ind, vars1, vals1, exprs1,true);\n\n  exprs.resize(exprs0.size());\n  for (int i=0; i < exprs0.size(); ++i) {\n    exprScale(exprs0[i], (1-collisions[i].time));\n    exprScale(exprs1[i], collisions[i].time);\n    exprs[i] = AffExpr(0);\n    exprInc(exprs[i], exprs0[i]);\n    exprInc(exprs[i], exprs1[i]);\n    cleanupAff(exprs[i]);\n  }\n}\n\ninline size_t hash(const DblVec& x) {\n  return boost::hash_range(x.begin(), x.end());\n}\n\nvoid CollisionEvaluator::GetCollisionsCached(const DblVec& x, vector<Collision>& collisions) {\n  double key = hash(getDblVec(x, GetVars()));\n  vector<Collision>* it = m_cache.get(key);\n  if (it != NULL) {\n    LOG_DEBUG(\"using cached collision check\\n\");\n    collisions = *it;\n  }\n  else {\n    LOG_DEBUG(\"not using cached collision check\\n\");\n    CalcCollisions(x, collisions);\n    m_cache.put(key, collisions);\n  }\n}\n\nSingleTimestepCollisionEvaluator::SingleTimestepCollisionEvaluator(ConfigurationPtr rad, const VarVector& vars) :\n  m_env(rad->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars(vars),\n  m_link2ind(),\n  m_links(),\n  m_filterMask(-1) {\n  vector<KinBody::LinkPtr> links;\n  vector<int> inds;\n  rad->GetAffectedLinks(m_links, true, inds);\n  for (int i=0; i < m_links.size(); ++i) {\n    m_link2ind[m_links[i].get()] = inds[i];\n  }\n  // TODO add argument\n}\n\n\nvoid SingleTimestepCollisionEvaluator::CalcCollisions(const DblVec& x, vector<Collision>& collisions) {\n  DblVec dofvals = getDblVec(x, m_vars);\n  m_rad->SetDOFValues(dofvals);\n  m_cc->LinksVsAll(m_links, collisions, m_filterMask);\n}\n\nvoid SingleTimestepCollisionEvaluator::CalcDists(const DblVec& x, DblVec& dists) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  CollisionsToDistances(collisions, m_link2ind, dists);\n}\n\n\nvoid SingleTimestepCollisionEvaluator::CalcDistExpressions(const DblVec& x, vector<AffExpr>& exprs) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  DblVec dofvals = getDblVec(x, m_vars);\n  CollisionsToDistanceExpressions(collisions, *m_rad, m_link2ind, m_vars, dofvals, exprs, false);\n}\n\n////////////////////////////////////////\n\nCastCollisionEvaluator::CastCollisionEvaluator(ConfigurationPtr rad, const VarVector& vars0, const VarVector& vars1) :\n  m_env(rad->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars0(vars0),\n  m_vars1(vars1),\n  m_link2ind(),\n  m_links() {\n  vector<KinBody::LinkPtr> links;\n  vector<int> inds;\n  rad->GetAffectedLinks(m_links, true, inds);\n  for (int i=0; i < m_links.size(); ++i) {\n    m_link2ind[m_links[i].get()] = inds[i];\n  }\n}\n\nvoid CastCollisionEvaluator::CalcCollisions(const DblVec& x, vector<Collision>& collisions) {\n  DblVec dofvals0 = getDblVec(x, m_vars0);\n  DblVec dofvals1 = getDblVec(x, m_vars1);\n  m_rad->SetDOFValues(dofvals0);\n  m_cc->CastVsAll(*m_rad, m_links, dofvals0, dofvals1, collisions);\n}\nvoid CastCollisionEvaluator::CalcDistExpressions(const DblVec& x, vector<AffExpr>& exprs) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  DblVec dofvals0 = getDblVec(x, m_vars0);\n  DblVec dofvals1 = getDblVec(x, m_vars1);\n  CollisionsToDistanceExpressions(collisions, *m_rad, m_link2ind, m_vars0, m_vars1, dofvals0, dofvals1, exprs);\n}\nvoid CastCollisionEvaluator::CalcDists(const DblVec& x, DblVec& dists) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  CollisionsToDistances(collisions, m_link2ind, dists);\n}\n\n\n//////////////////////////////////////////\n\n\n\ntypedef OpenRAVE::RaveVector<float> RaveVectorf;\n\nvoid PlotCollisions(const std::vector<Collision>& collisions, OR::EnvironmentBase& env, vector<OR::GraphHandlePtr>& handles, double safe_dist) {\n  BOOST_FOREACH(const Collision& col, collisions) {\n    RaveVectorf color;\n    if (col.distance < 0) color = RaveVectorf(1,0,0,1);\n    else if (col.distance < safe_dist) color = RaveVectorf(1,1,0,1);\n    else color = RaveVectorf(0,1,0,1);\n\n    if (col.cctype == CCType_Between) {\n      // handles.push_back(env.drawarrow(col.ptB, col.ptB1, .002, RaveVectorf(0,0,0,1)));\n    }\n    OR::Vector ptB = (col.cctype == CCType_Between)  ? ((1-col.time)* col.ptB +col.time*col.ptB1) : col.ptB;\n    // handles.push_back(env.drawarrow(col.ptA, ptB, .0025, color));\n  }\n}\n\nCollisionCost::CollisionCost(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars) :\n    Cost(\"collision\"),\n    m_calc(new SingleTimestepCollisionEvaluator(rad, vars)), m_dist_pen(dist_pen), m_coeff(coeff)\n{}\n\nCollisionCost::CollisionCost(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars0, const VarVector& vars1) :\n    Cost(\"cast_collision\"),\n    m_calc(new CastCollisionEvaluator(rad, vars0, vars1)), m_dist_pen(dist_pen), m_coeff(coeff)\n{}\nConvexObjectivePtr CollisionCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  vector<AffExpr> exprs;\n  m_calc->CalcDistExpressions(x, exprs);\n  for (int i=0; i < exprs.size(); ++i) {\n    AffExpr viol = exprSub(AffExpr(m_dist_pen), exprs[i]);\n    out->addHinge(viol, m_coeff);\n  }\n  return out;\n}\ndouble CollisionCost::value(const vector<double>& x) {\n  DblVec dists;\n  m_calc->CalcDists(x, dists);\n  double out = 0;\n  for (int i=0; i < dists.size(); ++i) {\n    out += pospart(m_dist_pen - dists[i]) * m_coeff;\n  }\n  return out;\n}\n\nvoid CollisionCost::Plot(const DblVec& x, OR::EnvironmentBase& env, std::vector<OR::GraphHandlePtr>& handles) {\n  vector<Collision> collisions;\n  m_calc->GetCollisionsCached(x, collisions);\n  PlotCollisions(collisions, env, handles, m_dist_pen);\n}\n\n// ALMOST EXACTLY COPIED FROM CollisionCost\n\nCollisionConstraint::CollisionConstraint(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars) :\n    m_calc(new SingleTimestepCollisionEvaluator(rad, vars)), m_dist_pen(dist_pen), m_coeff(coeff)\n{\n  name_=\"collision\";\n}\n\nCollisionConstraint::CollisionConstraint(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars0, const VarVector& vars1) :\n    m_calc(new CastCollisionEvaluator(rad, vars0, vars1)), m_dist_pen(dist_pen), m_coeff(coeff)\n{\n  name_=\"collision\";\n}\nConvexConstraintsPtr CollisionConstraint::convex(const vector<double>& x, Model* model) {\n  ConvexConstraintsPtr out(new ConvexConstraints(model));\n  vector<AffExpr> exprs;\n  m_calc->CalcDistExpressions(x, exprs);\n  for (int i=0; i < exprs.size(); ++i) {\n    AffExpr viol = exprSub(AffExpr(m_dist_pen), exprs[i]);\n    out->addIneqCnt(exprMult(viol,m_coeff));\n  }\n  return out;\n}\nDblVec CollisionConstraint::value(const vector<double>& x) {\n  DblVec dists;\n  m_calc->CalcDists(x, dists);\n  DblVec out(dists.size());\n  for (int i=0; i < dists.size(); ++i) {\n    out[i] = pospart(m_dist_pen - dists[i]) * m_coeff;\n  }\n  return out;\n}\n\n/////////////////////////////////////////////////////////\n// Risk-aware section starts here.\n/////////////////////////////////////////////////////////\n\n/**\n * Constructor for the collision chance constraint\n *\n * @param uncertain_body_names: the names of the bodies representing uncertain obstacles\n * @param location_covariances: the covariance matrices of the Gaussian uncertainty in the location of the\n *                              corresponding uncertain bodies. Must have the same length as uncertain_body_names\n * @param risk_tolerance: a double representing the maximum allowable risk at this time step.\n * @param precision: a double representing the desired precision tolerance in our risk estimates. True risk is guaranteed\n *                   not to exceed the estimate by more than precision/2.\n * @param rad: a pointer to the configuration of the robot and evironment.\n * @param vars: an array of variables to be used in constructing symbolic expressions for linearized risk.\n */\nCollisionChanceConstraint::CollisionChanceConstraint(std::vector<std::string> uncertain_body_names,\n                                                     std::vector<Matrix3d> location_covariances,\n                                                     double risk_tolerance,\n                                                     double required_precision,\n                                                     double coeff,\n                                                     double grad_scale_factor,\n                                                     int numsteps,\n                                                     ConfigurationPtr rad,\n                                                     const VarArray& vars) :\n    m_calc(new OverallCollisionRiskEvaluator(uncertain_body_names,\n                                             location_covariances,\n                                             required_precision,\n                                             grad_scale_factor,\n                                             numsteps,\n                                             rad,\n                                             vars)),\n    m_vars(vars),\n    m_uncertain_body_names(uncertain_body_names),\n    m_location_covariances(location_covariances),\n    m_risk_tolerance(risk_tolerance),\n    m_coeff(coeff),\n    m_numsteps(m_numsteps)\n{\n  name_=\"collision\";\n}\n\n\n/**\n * Convexify the constraint with the given values for the degrees of freedom, yielding symbolic expressions in terms\n * of the given model\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n * @param model: the model with which to construct the convexified expressions.\n *\n * @returns a pointer to the convexified constraint.\n */\nConvexConstraintsPtr CollisionChanceConstraint::convex(const vector<double>& x, Model* model) {\n  // Set up the convexified constraint object\n  ConvexConstraintsPtr out(new ConvexConstraints(model));\n\n  // Get the linearized risk expressions\n  vector<AffExpr> exprs;\n  m_calc->CalcRiskExpressions(x, exprs);\n\n  // Accumulate the risks into a single constraint\n  AffExpr risk_violation(-1.0*m_risk_tolerance);\n  for (int i=0; i < exprs.size(); ++i) {\n    // Add this risk expression to the risk violation expression\n    exprInc(risk_violation, exprs[i]);\n  }\n  // Add the accumulated constraint to the model\n  out->addIneqCnt(exprMult(risk_violation, m_coeff)); // <= 0\n  LOG_DEBUG(\"VIOLATION convex: %f\", out->violation(x));\n  LOG_DEBUG(\"Total risk: %f\", out->violation(x) + m_risk_tolerance);\n  return out;\n}\n\n/**\n * Evaluate the constraint with the given values for the degrees of freedom.\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n *\n * @returns a vector of doubles with one element representing the total risk at this timestep:\n *\n * The constraint is (summed over all obstacles)\n *          risk_tolerance - risk >= 0\n * but we relax it using the hingle loss to be\n *          |risk - risk_tolerance|^+\n */\nDblVec CollisionChanceConstraint::value(const vector<double>& x) {\n  // Start by getting the risk estimates\n  DblVec risks;\n  m_calc->CalcRisks(x, risks);\n\n  // Now compute the relaxed hinge-loss penalties\n  DblVec out(1);\n  double accumulator = 0.0;\n  for (int i=0; i < risks.size(); ++i) {\n    accumulator += risks[i];\n  }\n  out[0] = pospart(accumulator - m_risk_tolerance) * m_coeff;\n  LOG_DEBUG(\"Total RISK: %.6f\", accumulator);\n  return out;\n}\n\ntypedef OpenRAVE::RaveVector<float> RaveVectorf;\n\nvoid SingleTimestepCollisionRiskEvaluator::PlotRisks(const std::vector<RiskQueryResult>& risk_query_results, OR::EnvironmentBase& env, vector<OR::GraphHandlePtr>& handles) {\n  BOOST_FOREACH(const RiskQueryResult& risk_result, risk_query_results) {\n    RaveVectorf color1 = RaveVectorf(0,0,1,1);\n\n    // OR::Vector endpoint = OR::Vector(\n    //   risk_result.ptRobotTwoShot[0] + risk_result.contact_normal_into_robot_two_shot(0),\n    //   risk_result.ptRobotTwoShot[1] + risk_result.contact_normal_into_robot_two_shot(1),\n    //   risk_result.ptRobotTwoShot[2] + risk_result.contact_normal_into_robot_two_shot(2));\n    // handles.push_back(env.drawarrow(risk_result.ptRobotTwoShot, endpoint, .0025, color));\n\n    RaveVectorf color2 = RaveVectorf(1,0,0,1);\n\n    // OR::Vector endpoint2 = OR::Vector(\n    //   risk_result.ptRobotOneShot[0] + risk_result.contact_normal_into_robot_one_shot(0),\n    //   risk_result.ptRobotOneShot[1] + risk_result.contact_normal_into_robot_one_shot(1),\n    //   risk_result.ptRobotOneShot[2] + risk_result.contact_normal_into_robot_one_shot(2));\n    // handles.push_back(env.drawarrow(risk_result.ptRobotOneShot, endpoint2, .0025, color2));\n\n    // Get the indices of the two robot links that the risk estimate collides with\n    Link2Int::const_iterator itRobotOneShot = m_link2ind.find(risk_result.linkRobotOneShot);\n    Link2Int::const_iterator itRobotTwoShot = m_link2ind.find(risk_result.linkRobotTwoShot);\n\n    if (risk_result.epsilon > m_precision && itRobotOneShot != m_link2ind.end()) {\n      Vector3d n_hat_one_shot = risk_result.contact_normal_into_robot_one_shot.normalized();\n\n      VectorXd one_shot_jacobian = m_rad->PositionJacobian(itRobotOneShot->second, risk_result.ptRobotOneShot);\n      VectorXd d_epsilon_d_theta_one_shot = risk_result.d_epsilon_dx_one_shot * n_hat_one_shot * n_hat_one_shot.transpose() * one_shot_jacobian;\n\n      VectorXd scaled_nhat_oneshot = risk_result.d_epsilon_dx_one_shot;\n\n      OR::Vector endpoint1 = OR::Vector(\n        risk_result.ptRobotOneShot[0] - scaled_nhat_oneshot(0),\n        risk_result.ptRobotOneShot[1] - scaled_nhat_oneshot(1),\n        risk_result.ptRobotOneShot[2] - scaled_nhat_oneshot(2));\n\n      // handles.push_back(env.drawarrow(risk_result.ptRobotOneShot, endpoint1, .0025, color1));\n\n      // We need to check if we're in case 3 before calculating the gradient for the second shot\n      VectorXd risk_grad;\n      Vector3d n_hat_two_shot;\n      if (itRobotTwoShot != m_link2ind.end()) {\n        // make sure the contact unit vector is normalized\n        Vector3d n_hat_two_shot = risk_result.contact_normal_into_robot_two_shot.normalized();\n\n        VectorXd two_shot_jacobian = m_rad->PositionJacobian(itRobotTwoShot->second, risk_result.ptRobotTwoShot);\n        VectorXd d_epsilon_d_theta_two_shot = risk_result.d_epsilon_dx_two_shot * n_hat_two_shot * n_hat_two_shot.transpose() * two_shot_jacobian;\n\n        // Because the combined one- and two-shot risk estimate is epsilon = 0.5*(epsilon_1 + epsilon_2),\n        // The combined gradient is the sum of half of each separate gradient\n        risk_grad = 0.5 * d_epsilon_d_theta_one_shot + 0.5 * d_epsilon_d_theta_two_shot;\n\n        VectorXd scaled_nhat_twoshot = risk_result.d_epsilon_dx_two_shot;\n        OR::Vector endpoint2 = OR::Vector(\n          risk_result.ptRobotTwoShot[0] - scaled_nhat_twoshot(0),\n          risk_result.ptRobotTwoShot[1] - scaled_nhat_twoshot(1),\n          risk_result.ptRobotTwoShot[2] - scaled_nhat_twoshot(2));\n        // handles.push_back(env.drawarrow(risk_result.ptRobotTwoShot, endpoint2, .0025, color2));\n      }\n    }\n  }\n}\n\nvoid CollisionChanceConstraint::Plot(const DblVec& x, OR::EnvironmentBase& env, std::vector<OR::GraphHandlePtr>& handles) {\n  m_calc->PlotRisks(x, env, handles);\n}\n\n/**\n * Constructor for the SingleTimestepCollisionRiskEvaluator class, which is an object used to evaluate\n * the risk of collision between the robot and all uncertain obstacles at a single timestep.\n *\n * @param uncertain_body_names: the names of the bodies representing uncertain obstacles\n * @param location_covariances: the covariance matrices of the Gaussian uncertainty in the location of the\n *                              corresponding uncertain bodies. Must have the same length as uncertain_body_names\n * @param precision: a double representing the desired precision tolerance in our risk estimates. True risk is guaranteed\n *                   not to exceed the estimate by more than precision/2.\n * @param rad: a pointer to the configuration of the robot and evironment.\n * @param vars: a vector of variables to be used in constructing symbolic expressions for linearized risk.\n */\nSingleTimestepCollisionRiskEvaluator::SingleTimestepCollisionRiskEvaluator(\n    std::vector<std::string> uncertain_body_names,\n    std::vector<Matrix3d> location_covariances,\n    double precision,\n    double grad_scale_factor,\n    ConfigurationPtr rad,\n    const VarVector& vars) :\n  m_env(rad->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars(vars),\n  m_link2ind(),\n  m_link2covariance(),\n  m_links(),\n  m_filterMask(RobotFilter),\n  m_precision(precision),\n  m_grad_scale_factor(grad_scale_factor)\n{\n  // Find uncertain links by body name\n  vector<int> inds;\n  vector<Matrix3d> covariances;\n  int body_index = 0;\n\n  // Match links to covariances\n  BOOST_FOREACH(std::string body_name, uncertain_body_names) {\n    BOOST_FOREACH(const KinBody::LinkPtr& link, m_env->GetKinBody(body_name)->GetLinks()) {\n      if (!link->GetGeometries().empty()) {\n        m_links.push_back(link);\n        inds.push_back(link->GetIndex());\n        covariances.push_back(location_covariances[body_index]);\n      }\n    }\n\n    ++body_index;\n  }\n\n  // For easy access, save the OpenRAVE index and covariance matrix of each link in a map\n  for (int i=0; i < m_links.size(); ++i) {\n    m_link2covariance[m_links[i].get()] = covariances[i];\n  }\n\n  // We also need to save a map from robot link indices to OpenRAVE indices,\n  // so we can get the Jacobian of points on those links later.\n  vector<KinBody::LinkPtr> links;\n  inds.clear();\n  rad->GetAffectedLinks(links, true, inds);\n  for (int i=0; i < links.size(); ++i) {\n    m_link2ind[links[i].get()] = inds[i];\n  }\n}\n\n\n/**\n * Serves as a wrapper for the PerformRiskCheck function, caching results of previous queries to give\n * performance benefits.\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n * @param risks: a vector of RiskQueryResult structs into which we will put the results of the risk query.\n *               These structs contain both the risk estimate itself and information for computing the gradient.\n *\n * @returns void, but risks will filled with the risk query results.\n */\nvoid CollisionRiskEvaluator::GetRisksCached(const DblVec& x, vector<RiskQueryResult>& risks) {\n  double key = hash(getDblVec(x, GetVars()));\n  vector<RiskQueryResult>* it = m_cache.get(key);\n  if (it != NULL) {\n    LOG_DEBUG(\"using cached risk query result\\n\");\n    risks = *it;\n  }\n  else {\n    LOG_DEBUG(\"not using cached risk query result\\n\");\n    PerformRiskCheck(x, risks);\n    m_cache.put(key, risks);\n  }\n}\n\n/**\n * Calls the ProximityAlert risk estimation via the collision checker to estimate the risks of collision\n * between the robot and uncertain obstacles.\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n * @param risks: a vector of RiskQueryResult structs into which we will put the results of the risk query.\n *               These structs contain both the risk estimate itself and information for computing the gradient.\n *\n * @returns void, but risks will filled with the risk query results.\n */\nvoid SingleTimestepCollisionRiskEvaluator::PerformRiskCheck(const DblVec& x, vector<RiskQueryResult>& risks) {\n  DblVec dofvals = getDblVec(x, m_vars);\n  m_rad->SetDOFValues(dofvals);\n  m_cc->LinksVsAllRiskEstimate(m_links, risks, m_filterMask, m_link2covariance, m_precision);\n}\n\n/**\n * Compute the risks of collision between the robot and each uncertain obstacle. Will use cached values if\n * possible; otherwise, will use the ProximityAlert epsilon-shadow algorithm to estimate the risk.\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n * @param risks: a vector of doubles into which we will put the risk estimates\n *\n * @returns void, but risks will be cleared and then filled with the risk estimates.\n */\nvoid SingleTimestepCollisionRiskEvaluator::CalcRisks(const DblVec& x, DblVec& risks) {\n  vector<RiskQueryResult> risk_query_results;\n  GetRisksCached(x, risk_query_results);\n\n  // Extract risk measures from risk_query_results\n  risks.clear();\n  BOOST_FOREACH(const RiskQueryResult& risk_result, risk_query_results) {\n    risks.push_back(risk_result.epsilon);\n  }\n}\n\n/**\n * Construct symbolic expressions for the linearized collision risks at this single timestep.\n *\n * Begins by computing the risk of collision between each uncertain obstacle and the robot at this specific\n * timestep, then for each obstacle, computes the gradient of the risk with respect to joint values and\n * adds a symbolic affine expression to exprs of the form:\n *\n *    \\epsilon_0 + \\nabla_\\theta \\epsilon (\\theta - \\theta_0)\n *\n * where \\epsilon_0 is the risk of collision with the obstacle, and \\theta_0 is the vector of joint values at\n * this timestep, \\nabla_\\theta \\epsilon is the gradient of \\epsilon w.r.t. the joint values, and \\theta is a\n * symbolic vector of joint values.\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n * @param exprs: a vector of symbolic affine expressions into which we will put the linearized risk expressions\n *\n * @returns void, but exprs will be cleared and then filled with the linearized risk expressions.\n */\nvoid SingleTimestepCollisionRiskEvaluator::CalcRiskExpressions(const DblVec& x, vector<AffExpr>& exprs) {\n  vector<RiskQueryResult> risk_query_results;\n  GetRisksCached(x, risk_query_results);\n  DblVec dofvals = getDblVec(x, m_vars);\n\n  exprs.clear();\n  exprs.reserve(risk_query_results.size());\n  m_rad->SetDOFValues(dofvals); // since we'll be calculating jacobians\n\n  // For each risk result, we need to compute the linearized expression for the collision risk\n  // risk(theta) \\approx risk_0 + gradient * (theta - theta_0)\n  BOOST_FOREACH(const RiskQueryResult& risk_result, risk_query_results) {\n    AffExpr risk(risk_result.epsilon);\n\n    // Get the indices of the two robot links that the risk estimate collides with\n    Link2Int::const_iterator itRobotOneShot = m_link2ind.find(risk_result.linkRobotOneShot);\n    Link2Int::const_iterator itRobotTwoShot = m_link2ind.find(risk_result.linkRobotTwoShot);\n\n    // If the risk is extremely small, that means that the largest epsilon shadow used to estimate\n    // the risk did not touch the robot. In that case, the risk is constant at zero, since small motions\n    // are assumed not to bring the robot \"into risk\" from zero-risk.\n    // Because of this, we only add the linear terms if the risk is non-zero (within tolerance).\n    // We can also skip this if both contact links are not valid\n    if (risk_result.epsilon > m_precision && itRobotOneShot != m_link2ind.end()) {\n      \n      // There are three cases:\n      //  1.) neither the one shot nor the two shot search ended in collision with the controlled links\n      //  2.) only the one shot search ended in collision\n      //  3.) both ended in collision\n      // (collision may have occured with an uncontrolled link, like the robot base).\n      //\n      // If (1) occured, then neither risk_result.linkRobotOneShot nor risk_result.linkRobotTwo\n      // are valid.\n      //\n      // If (2) occured, then risk_result.linkRobotOneShot is a valid link but\n      // risk_result.linkRobotTwoShot is not, so we only add the gradient terms from the first shot\n      //\n      // If (3) occured, then both risk_result.linkRobotOneShot and risk_result.linkRobotTwoShot\n      // will be valid links, so we add the gradient terms from both.\n\n      // In either case 2 or case 3, we include the terms from the first shot, so we can calculate\n      // the gradient: d_epsilon_d_theta (epsilon is the risk estimate and theta the joint angles).\n      //\n      // The explanation of this calculation relies on some knowledge of the proximity alert algorithms.\n      // The ProximityAlert risk estimator gives us d_epsilon_d_x for both the one and two shot estimates.\n      // In this context, x is the vector from the center of the epsilon-shadow ellipsoid to the contact point\n      // with the robot, n is a vector into the robot normal to the contact with the shadow, and J is the Jacobian\n      // of the contact point w.r.t. the joint angles. Then, we have\n      //\n      // d_epsilon_d_theta = d_epsilon_d_x * J\n      //\n      // First we need to make sure the contact unit vector is normalized (Note: this might not be needed anymore)\n      Vector3d n_hat_one_shot = risk_result.contact_normal_into_robot_one_shot.normalized();\n\n      DblMatrix one_shot_jacobian = m_rad->PositionJacobian(itRobotOneShot->second, risk_result.ptRobotOneShot);\n      VectorXd d_epsilon_d_theta_one_shot = risk_result.d_epsilon_dx_one_shot * one_shot_jacobian;\n\n      // We need to check if we're in case 3 before calculating the gradient for the second shot\n      VectorXd risk_grad;\n      if (itRobotTwoShot != m_link2ind.end()) {\n        // make sure the contact unit vector is normalized\n        Vector3d n_hat_two_shot = risk_result.contact_normal_into_robot_two_shot.normalized();\n\n        DblMatrix two_shot_jacobian = m_rad->PositionJacobian(itRobotTwoShot->second, risk_result.ptRobotTwoShot);\n        VectorXd d_epsilon_d_theta_two_shot = risk_result.d_epsilon_dx_two_shot * two_shot_jacobian;\n\n        // Because the combined one- and two-shot risk estimate is epsilon = 0.5*(epsilon_1 + epsilon_2),\n        // The combined gradient is the sum of half of each separate gradient\n        risk_grad = 0.5 * d_epsilon_d_theta_one_shot + 0.5 * d_epsilon_d_theta_two_shot;\n      } else {\n        // Otherwise, we're in case 2 and the gradient is just the gradient from the first shot\n        risk_grad = d_epsilon_d_theta_one_shot;\n      }\n      risk_grad *= m_grad_scale_factor;\n      // LOG_DEBUG(\"Risk Gradient: %ld elements, %ld vars\", risk_grad.size(), m_vars.size());\n      // for (int j = 0; j < risk_grad.size(); j++) {\n      //   LOG_DEBUG(\"\\t %.8f\", risk_grad(j));\n      // }\n\n      // Now we add risk_grad * (theta - theta_0) to the affine expression\n      exprInc(risk, varDot(risk_grad, m_vars));\n      exprInc(risk, -risk_grad.dot(toVectorXd(dofvals)));\n    }\n    \n    // And return the risk expression by pushing the affine expression into the supplied vector.\n    exprs.push_back(risk);\n  }\n  LOG_DEBUG(\"%ld risk expressions\\n\", exprs.size());\n}\n\n\nOverallCollisionRiskEvaluator::OverallCollisionRiskEvaluator(\n    std::vector<std::string> uncertain_body_names,\n    std::vector<Matrix3d> location_covariances,\n    double precision,\n    double grad_scale_factor,\n    int numsteps,\n    ConfigurationPtr rad,\n    const VarArray& vars) :\n  m_timestep_risk_evals(),\n  m_env(rad->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars(vars),\n  m_numsteps(numsteps),\n  m_max_risk(false)\n{\n  // Create a single timestep risk evaluator for every timestep\n  for (int i = 0; i < numsteps; ++i) {\n    m_timestep_risk_evals.push_back(SingleTimestepCollisionRiskEvaluator(\n      uncertain_body_names,\n      location_covariances,\n      precision,\n      grad_scale_factor,\n      rad,\n      vars.row(i)));\n  }\n}\n\nOverallCollisionRiskEvaluator::OverallCollisionRiskEvaluator(\n    std::vector<std::string> uncertain_body_names,\n    std::vector<Matrix3d> location_covariances,\n    double precision,\n    double grad_scale_factor,\n    int numsteps,\n    ConfigurationPtr rad,\n    const VarArray& vars,\n    bool use_max_risk) :\n  m_timestep_risk_evals(),\n  m_env(rad->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars(vars),\n  m_numsteps(numsteps),\n  m_max_risk(use_max_risk)\n{\n  // Create a single timestep risk evaluator for every timestep\n  for (int i = 0; i < numsteps; ++i) {\n    m_timestep_risk_evals.push_back(SingleTimestepCollisionRiskEvaluator(\n      uncertain_body_names,\n      location_covariances,\n      precision,\n      grad_scale_factor,\n      rad,\n      vars.row(i)));\n  }\n}\n\n/**\n * Accumulate the risk at each timestep into a single measure of collision risk\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n * @param risks: a vector of doubles into which we will put the risk estimates.\n *\n * @returns void, but risks will be cleared and then filled with the risk estimates from each timestep.\n */\nvoid OverallCollisionRiskEvaluator::CalcRisks(const DblVec& x, DblVec& risks) {\n  risks.clear();\n\n  // There are two modes. If m_max_risk is true, then we only save the maximum risk\n  // for each obstacle (across time). Otherwise, we save all risks for all obstacles.\n  if (m_max_risk) {\n    // Get the number of obstacles, and create a vector to store the maximum risks for each\n    int num_obstacles = m_timestep_risk_evals[0].m_links.size();\n    DblVec max_obstacle_risk;\n    for (int i = 0; i < num_obstacles; i++) {\n      max_obstacle_risk.push_back(0.0);\n    }\n\n    // Now loop through the timesteps, updating our maximum risk for each obstacle\n    DblVec single_step_risks;\n    BOOST_FOREACH(SingleTimestepCollisionRiskEvaluator& evaluator, m_timestep_risk_evals) {\n      // Get risks for this timestep\n      evaluator.CalcRisks(x, single_step_risks);\n\n      // Save new obstacle risks if they are higher than the incumbent\n      for (int i = 0; i < num_obstacles; i++) {\n        if (single_step_risks[i] > max_obstacle_risk[i]) {\n          max_obstacle_risk[i] = single_step_risks[i];\n        }\n      }\n    }\n\n    // Now save the maximum risks\n    risks.insert(risks.begin(), max_obstacle_risk.begin(), max_obstacle_risk.end());\n  } else {\n    // Create a new vector to store the results of each timestep's risk\n    // Has to be different since CalcRisks clears the given vector\n    DblVec single_step_risks;\n    BOOST_FOREACH(SingleTimestepCollisionRiskEvaluator& evaluator, m_timestep_risk_evals) {\n      // Get risks for this timestep\n      evaluator.CalcRisks(x, single_step_risks);\n\n      // Save them by appending to risks\n      risks.insert(risks.begin(), single_step_risks.begin(), single_step_risks.end());\n    }\n    // After this step, risks will be filled with the results of all risk queries\n    // for all timesteps for each uncertain link.\n  }\n}\n\n/**\n * Accumulate the risk expressions at each timestep into a single measure of collision risk\n *\n * @param x: a vector of doubles containing the current values of the degrees of freedom (i.e. \\theta_0)\n * @param exprs: a vector of symbolic affine expressions into which we will put the linearized risk expressions\n *\n * @returns void, but exprs will be cleared and then filled with the risk estimate expressions from each timestep.\n */\nvoid OverallCollisionRiskEvaluator::CalcRiskExpressions(const DblVec& x, vector<AffExpr>& exprs) {\n  exprs.clear();\n\n  // There are two modes. If m_max_risk is true, then we only save the maximum risk\n  // for each obstacle (across time). Otherwise, we save all risks for all obstacles.\n  if (m_max_risk) {\n    // Get the number of obstacles, and create a vector to store the maximum risks for each\n    int num_obstacles = m_timestep_risk_evals[0].m_links.size();\n    vector<AffExpr> max_obstacle_risk;\n    for (int i = 0; i < num_obstacles; i++) {\n      max_obstacle_risk.push_back(AffExpr(0.0));\n    }\n\n    // Now loop through the timesteps, saving the expression associated with the maximum\n    // risk\n    vector<AffExpr> single_step_exprs;\n    BOOST_FOREACH(SingleTimestepCollisionRiskEvaluator& evaluator, m_timestep_risk_evals) {\n      // Get risk expressions for this timestep\n      evaluator.CalcRiskExpressions(x, single_step_exprs);\n\n      // Save new obstacle risks if they are higher than the incumbent\n      for (int i = 0; i < num_obstacles; i++) {\n        if (single_step_exprs[i].constant > max_obstacle_risk[i].constant) {\n          max_obstacle_risk[i] = single_step_exprs[i];\n        }\n      }\n    }\n\n    // Now save the maximum risks\n    exprs.insert(exprs.begin(), max_obstacle_risk.begin(), max_obstacle_risk.end());\n  } else {\n    // Create a new vector to store the results of each timestep's risk expressions\n    // Has to be different since CalcRiskExpressions clears the given vector\n    vector<AffExpr> single_step_exprs;\n    BOOST_FOREACH(SingleTimestepCollisionRiskEvaluator& evaluator, m_timestep_risk_evals) {\n      // Get risk expressions for this timestep\n      evaluator.CalcRiskExpressions(x, single_step_exprs);\n\n      // Save them by appending to exprs\n      exprs.insert(exprs.begin(), single_step_exprs.begin(), single_step_exprs.end());\n    }\n    // After this step, exprs will be filled with the results of all risk queries\n    // for all timesteps for each uncertain link.\n  }\n}\n\n/**\n * Plot the risks at each timestep.\n */\nvoid OverallCollisionRiskEvaluator::PlotRisks(const DblVec& x, OR::EnvironmentBase& env, vector<OR::GraphHandlePtr>& handles) {\n  BOOST_FOREACH(SingleTimestepCollisionRiskEvaluator& evaluator, m_timestep_risk_evals) {\n    vector<RiskQueryResult> risk_query_results;\n    evaluator.GetRisksCached(x, risk_query_results);\n    evaluator.PlotRisks(risk_query_results, env, handles);\n  }\n}\n\n}\n", "meta": {"hexsha": "605fa47dde9782f857f1295abbc7d093eec7be81", "size": 35805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trajopt/collision_terms.cpp", "max_stars_repo_name": "dawsonc/trajopt", "max_stars_repo_head_hexsha": "deab303442c0f211ee25278a36c1bba0c4f7c915", "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/trajopt/collision_terms.cpp", "max_issues_repo_name": "dawsonc/trajopt", "max_issues_repo_head_hexsha": "deab303442c0f211ee25278a36c1bba0c4f7c915", "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/collision_terms.cpp", "max_forks_repo_name": "dawsonc/trajopt", "max_forks_repo_head_hexsha": "deab303442c0f211ee25278a36c1bba0c4f7c915", "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.4733096085, "max_line_length": 173, "alphanum_fraction": 0.7089233347, "num_tokens": 8974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.04084571605589629, "lm_q1q2_score": 0.017257504345920487}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n// __END_LICENSE__\n\n/**\n  Program to clean out low-intensity junk pixels from the edges of\n  Sentinel-1 images.  If these pixels are not cleaned out, the \n  water detection algorithm will almost certainly flag them as water\n  and may corrupt the statistics used to find water in the rest of \n  the image.\n*/\n\n#include <queue>\n#include <vw/Image/ImageIO.h>\n#include <vw/Math/Statistics.h>\n#include <vw/tools/modis_utilities.h>\n#include <vw/tools/modis_water_detection.h>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing namespace vw;\n\n\n/// Applies a median filter to a vector with a window size\n/// - TODO: Move to somewhere in VW, but first we need a place to put it.\ntemplate <typename T>\nvoid window_median_filter(std::vector<T> const& v_in, std::vector<T> &v_out, const int width) {\n\n  // Setup\n  const int length = static_cast<int>(v_in.size());\n  const int half_width = width / 2;\n  v_out = v_in;\n\n  // Handle small input sizes\n  if ((width < 3) || (length < width))\n    return;\n  \n  // Just copy the first few elements\n  for (int i=0; i<half_width; ++i)\n    v_out[i] = v_in[i];\n\n  // Init a queue of neigboring values\n  std::list<T> locals;    \n  for (int i=0; i<width-1; ++i)    \n    locals.push_back(v_in[i]);\n\n  for (int i=half_width; i<length-half_width; ++i) {\n    // Load next value into queue\n    locals.push_back(v_in[i+half_width]);\n  \n    // Compute the median of the neigbors\n    v_out[i] = math::median(locals);\n  \n    // Drop oldest value\n    locals.pop_front();\n  }\n  // Just copy the last few elements\n  for (int i=length-half_width; i<length; ++i) {\n    v_out[i] = v_in[i];\n  }\n} // End median_filter\n\n\n/// Returns the percentage of values equal to a given value\n/// - T is a type that can be accessed with standard iterators.\ntemplate <typename T>\ndouble percent_equal(T const& values, double equal_to) {\n\n  double count = 0;\n  typename T::const_iterator iter;\n  for (iter = values.begin(); iter != values.end(); ++iter) {\n    if (static_cast<double>(*iter) == equal_to)\n      count += 1.0;\n  }\n  return count / static_cast<double>(values.size());\n}\n\n/// Class to locate the best position (if any) of a jump from low pixel values to higher pixel values.\n/// - This is a somewhat arbitrary decision tuned for the available sentinel-1 data.\n/// - This class works by traversing inwards from the image border and maintaining three\n///   sets of pixels.  The leading list is filled up first, then the buffer list, then\n///   the trailing list.  The lead and buffer lists are capped at a fixed size, the trailing\n///   list has no size limit.  The statistics of the lead and trailing buffers are compared\n///   to try and identify the most likely border of real image pixels.\nclass JumpFinder {\npublic:\n\n  /// Constructor\n  /// - lead_size is the number of pixels it in the leading pixel set.\n  JumpFinder(int lead_size) \n    : m_lead_size(static_cast<size_t>(lead_size)), \n      m_best_position(0), m_best_score(15), m_trail_zero_count(0), m_trail_sum(0) {\n  }\n\n  /// Add a new value and return true if a jump was detected\n  bool add_value(double value) {\n  \n    const int    BUFFER_WIDTH = 1; // Keep this many numbers out of the statistics\n    const double CLOSE_ZERO   = 8; // Treat values this small as if they are zero\n  \n    // Add new value to the leading list\n    m_lead_list.push_front(value);\n    \n    if (m_lead_list.size() > m_lead_size) {\n      // Move back of lead list to the trailing list\n      m_buffer_list.push_front(m_lead_list.back());\n      m_lead_list.pop_back();\n      \n      if (m_buffer_list.size() > BUFFER_WIDTH) {\n        double trail_val = m_buffer_list.back();\n        if (trail_val <= CLOSE_ZERO)\n          ++m_trail_zero_count;\n        m_trail_list.push_front(trail_val);\n        m_buffer_list.pop_back();\n        m_trail_sum += trail_val;\n      }\n    }\n    \n    if (m_trail_list.empty()) // Nothing to do until lead buffer is filled\n      return false;\n\n    // Compute statistics\n    double mean_trail=0, mean_lead=0, dev_trail=0;\n    double trail_count  = static_cast<double>(m_trail_list.size());\n    double percent_zero = m_trail_zero_count / trail_count;\n    mean_lead = math::mean(m_lead_list);\n    if (percent_zero < 1.0) { // Save time on big blank regions\n      mean_trail = m_trail_sum / trail_count;\n      dev_trail  = math::standard_deviation(m_trail_list, mean_trail);\n    }\n    \n    const double MAX_DEV_TRAIL    = 5;    // After STD_DEV of trail portion is higher, not a good jump\n    const double MIN_PERCENT_ZERO = 0.30; // Must be this percent or higher zeroes in trail for a jump\n    const double DEV_TRAIL_BREAK  = 20;   // Quit if the trail deviation exceeds this threshold.\n\n    // Evaluate the value of an edge located at the start of the trail region\n    double score = (mean_lead - mean_trail); // Valid pixels should be much brighter than border junk\n    if ((dev_trail > MAX_DEV_TRAIL) || (percent_zero < MIN_PERCENT_ZERO))\n      score = 0;\n    //std::cout << \"Lead  stats: \" << mean_lead  << \", \" << dev_lead  << std::endl;\n    //std::cout << \"Trail stats: \" << mean_trail << \", \" << dev_trail \n    //          << \", size = \" << m_trail_list.size() << \", percent = \" << percent_zero<< std::endl;\n    if (score > m_best_score) { // Record the best edge score to date\n      m_best_score    = score;\n      m_best_position = get_jump_index();\n    }\n    \n    // If one of these things is true, very unlikely to see the edge beyond this point.\n    return ((percent_zero < MIN_PERCENT_ZERO) || (dev_trail > DEV_TRAIL_BREAK)); \n  }\n  \n  /// Return the index at which the jump occurs.\n  int get_jump_index() const {\n    return m_trail_list.size() + 1; // Advance into the buffer pixel\n  }\n  \n  int get_best_jump() const {\n    //printf(\"Best score = %lf and position %d\\n\", m_best_score, m_best_position);\n    return m_best_position;\n  }\n\nprivate:\n  size_t m_lead_size; ///< Max size of the lead list\n  std::list<double> m_lead_list;   ///< Values at the leading part of the window\n  std::list<double> m_trail_list;  ///< Values at the trailing part of the window\n  std::list<double> m_buffer_list; ///< Values in the middle part of the window.\n  int    m_best_position;    ///< Most likely jump position to date.\n  double m_best_score;       ///< Score at m_best_position\n  double m_trail_zero_count; ///< Number of zero pixels in the trailing buffer\n  double m_trail_sum;        ///< Sum of all pixels in the trailing buffer\n\n}; // End class JumpFinder\n\n\n/// View class which attempts to zero out the border noise on each border of the image.\n/// - Because this uses the standard VW tile implementation and does not share information\n///   between tiles, the maximum border size that can be handled is roughly the tile size.\n/// - The JumpFinder class is used to find the border in each row/column and a median filter\n///   is applied to those results to remove outliers.\ntemplate <class ImageT>\nclass Sentinel1CleanBordersView : public ImageViewBase<Sentinel1CleanBordersView<ImageT> > {\n\npublic: // Definitions\n\n  typedef uint16     pixel_type;\n  typedef pixel_type result_type;\n\nprivate: // Variables\n\n  ImageT const& m_input_image;\n\npublic: // Functions\n\n  // Constructor\n  Sentinel1CleanBordersView( ImageT  const& input_image)\n                  : m_input_image(input_image){}\n\n  inline int32 cols  () const { return m_input_image.cols(); }\n  inline int32 rows  () const { return m_input_image.rows(); }\n  inline int32 planes() const { return 1; }\n\n  inline result_type operator()( int32 i, int32 j, int32 p=0 ) const\n  { return 0; } // NOT IMPLEMENTED!\n \n  typedef ProceduralPixelAccessor<Sentinel1CleanBordersView<ImageT> > pixel_accessor;\n  inline pixel_accessor origin() const { return pixel_accessor( *this, 0, 0 ); }\n\n  // Determin which edges of the image this tile is on\n  void check_bbox_edges(BBox2i const& bbox, bool &left, bool &right, bool &top, bool &bottom) const {\n    left   = (bbox.min().x() == 0);\n    top    = (bbox.min().y() == 0);\n    right  = (bbox.max().x() == cols());\n    bottom = (bbox.max().y() == rows());\n  }\n\n  // This function does most of the work\n  typedef CropView<ImageView<result_type> > prerasterize_type;\n  inline prerasterize_type prerasterize( BBox2i const& bbox ) const {\n\n    ImageView<result_type> output_tile = crop(m_input_image, bbox);\n\n    // Check if this is a border tile.  If not, no processing will happen.\n    bool left_edge, right_edge, top_edge, bottom_edge;\n    check_bbox_edges(bbox, left_edge, right_edge, top_edge, bottom_edge);\n\n    const unsigned short NODATA_VALUE        = 0; // Output nodata flag\n    const int            MEDIAN_FILTER_WIDTH = 9; // Width of median filter applied to edge detect results\n    const int            JUMP_WIDTH          = 8; // Width of lead region in the JumpFinder class\n    \n    // For each line coming in from the border, choose the best break point.\n    int num_rows = bbox.height();\n    int num_cols = bbox.width();\n    \n    if (left_edge) {\n      std::vector<int> breaks(num_rows), breaks_filtered;\n      for (int r=0; r<num_rows; ++r) { // For each row in this tile\n        breaks[r] = 0; // Default if no jump found\n        JumpFinder edge_detector(JUMP_WIDTH);\n        // Keep iterating to the right until we detect the start of valid pixels\n        for (int c=0; c<num_cols; ++c) { // Move along the row     \n          int value = output_tile(c,r);\n          if (edge_detector.add_value(value))\n            break;\n        } // End col loop\n        breaks[r] = edge_detector.get_best_jump();\n      } // End row loop\n\n      // Smooth out the borders\n      window_median_filter(breaks, breaks_filtered, MEDIAN_FILTER_WIDTH);\n\n      // Update the output image\n      for (int r=0; r<num_rows; ++r) { // For each row in this tile\n        for (int c=0; c<=breaks_filtered[r]; ++c) // Move along the row\n          output_tile(c,r) = NODATA_VALUE;\n      }\n    } // End left edge case\n\n    if (right_edge) {\n      std::vector<int> breaks(num_rows), breaks_filtered;\n      for (int r=0; r<num_rows; ++r) { // For each row in this tile\n        //std::cout << \"Row = \" << r+bbox.min().y() << std::endl;\n        breaks[r] = num_cols-1; // Default if no jump found\n        JumpFinder edge_detector(JUMP_WIDTH);\n        // Keep iterating to the right until we detect the start of valid pixels\n        for (int c=num_cols-1; c>0; --c) { // Move along the row     \n          int value = output_tile(c,r);\n          if (edge_detector.add_value(value))\n            break;\n        } // End col loop\n        breaks[r] = num_cols-1 - edge_detector.get_best_jump();\n      } // End row loop\n\n      // Smooth out the borders\n      window_median_filter(breaks, breaks_filtered, MEDIAN_FILTER_WIDTH);\n\n      // Update the output image\n      for (int r=0; r<num_rows; ++r) { // For each row in this tile\n        for (int c=num_cols-1; c>=breaks_filtered[r]; --c) // Move along the row\n          output_tile(c,r) = NODATA_VALUE;\n      }\n    } // End right edge case\n\n    if (top_edge) {\n      std::vector<int> breaks(num_cols), breaks_filtered;\n      for (int c=0; c<num_cols; ++c) { // For each column in this tile\n        breaks[c] = 0; // Default if no jump found\n        JumpFinder edge_detector(JUMP_WIDTH);\n        // Keep iterating to the right until we detect the start of valid pixels\n        for (int r=0; r<num_rows; ++r) { // Move along the column\n          int value = output_tile(c,r);\n          if (edge_detector.add_value(value))\n            break;\n        } // End row loop\n        breaks[c] = edge_detector.get_best_jump();\n        //std::cout << \"breaks[c] = \" << breaks[c] << std::endl;\n      } // End col loop\n\n      // Smooth out the borders\n      window_median_filter(breaks, breaks_filtered, MEDIAN_FILTER_WIDTH);\n\n      // Update the output image\n      for (int c=0; c<num_cols; ++c) { // For each column in this tile\n        //std::cout << \"breaks_filtered[c] = \" << breaks_filtered[c] << std::endl;\n        for (int r=0; r<breaks_filtered[c]; ++r) // Move along the column\n          output_tile(c,r) = NODATA_VALUE;\n      }\n    } // End top edge case\n\n    if (bottom_edge) {\n      std::vector<int> breaks(num_cols), breaks_filtered;\n      for (int c=0; c<num_cols; ++c) { // For each column in this tile\n        breaks[c] = num_rows-1; // Default if no jump found\n        JumpFinder edge_detector(JUMP_WIDTH);\n        // Keep iterating to the right until we detect the start of valid pixels\n        for (int r=num_rows-1; r>0; --r) { // Move along the column\n          int value = output_tile(c,r);\n          if (edge_detector.add_value(value))\n            break;\n        } // End row loop\n        breaks[c] = num_rows-1 - edge_detector.get_best_jump();\n      } // End col loop\n\n      // Smooth out the borders\n      window_median_filter(breaks, breaks_filtered, MEDIAN_FILTER_WIDTH);\n\n      // Update the output image\n      for (int c=0; c<num_cols; ++c) { // For each column in this tile\n        for (int r=num_rows-1; r>breaks_filtered[c]; --r) // Move along the column\n          output_tile(c,r) = NODATA_VALUE;\n      }\n    } // End bottom edge case\n\n    // Return the tile we created with fake borders to make it look the size of the entire output image\n    return prerasterize_type(output_tile, -bbox.min().x(), -bbox.min().y(), cols(), rows() );\n\n  } // End prerasterize function\n\n template <class DestT>\n inline void rasterize( DestT const& dest, BBox2i const& bbox ) const {\n   vw::rasterize( prerasterize(bbox), dest, bbox );\n }\n}; // End class Sentinel1CleanBordersView\n\n/// Helper function\ntemplate <class T>\nSentinel1CleanBordersView<T> clean_sentinel1_borders(T const& input) {\n  return Sentinel1CleanBordersView<T>(input);\n}\n\n\n\n/// Compute an optimal tile size close to the input tile size\n/// - The purpose of this function is to avoid a potential issue caused\n///   by processing the image in tiles.  The edge cleaning is limited to\n///   the size of one tile and there is the potential for truncated partial\n///   tiles at the right and bottom edges of the images.\n/// - This function slightly changes the tile size to ensure that any \n///   truncated tiles are at least close to a full tile size and will have\n///   adequate edge cleaning range.\nint compute_new_tile_size(int input_size, int image_size) {\n\n  // Define the safe range of percent size of edge tiles\n  double MIN_TILE_PERCENTAGE = 0.75;\n  double MAX_TILE_PERCENTAGE = 0.99;\n\n  // The current tile usage.  Last tile is the size of a tile at the right\n  //  or bottom of the tiling grid.\n  double num_tiles_used       = (double)image_size / (double)input_size;\n  double last_tile_percentage = num_tiles_used - floor(num_tiles_used);\n  \n  // If the input is in the acceptable range, keep it!\n  if ((last_tile_percentage >= MIN_TILE_PERCENTAGE) && (last_tile_percentage <= MAX_TILE_PERCENTAGE))\n    return input_size;\n\n  //printf(\"Adjusting input tile size:\\n\");\n  //printf(\"num_tiles = %lf, input tile size: %d\\n\", num_tiles_used, input_size);\n\n  // Otherwise the tile size should be adjusted.\n  \n  // Decide how many tiles to shoot for\n  double target_num_tiles = floor(num_tiles_used);\n  if (last_tile_percentage > 0.75)\n    target_num_tiles = ceil(num_tiles_used);\n  \n  // Compute new tile size, rounding up to ensure we don't end up with a tile sliver.\n  int tile_size = ceil((double)image_size / target_num_tiles);\n\n  //double first_num_tiles = (double)image_size / (double)tile_size;\n  //printf(\"first_num_tiles = %lf, Computed new tile size: %d\\n\", first_num_tiles, tile_size);\n\n  // GDAL block write sizes must be a multiple to 16 so if the input value is\n  //  not a multiple of 16 increase it until it is.  This should not have a significant\n  //  effect on the size of the border tiles.\n  const int TILE_MULTIPLE = 16;\n  if (tile_size % TILE_MULTIPLE != 0)\n    tile_size = ((tile_size / TILE_MULTIPLE) + 1) * TILE_MULTIPLE;\n    \n  //double new_num_tiles = (double)image_size / (double)tile_size;\n  //printf(\"new_num_tiles = %lf, Computed new tile size: %d\\n\", new_num_tiles, tile_size);\n    \n  return tile_size;\n}\n\n\nint main(int argc, char **argv) {\n\n  std::string input_file;\n  std::string output_path;\n  int num_threads = 0;\n  int tile_size   = 2048;\n\n  /// Handle the command line parameters\n  cartography::GdalWriteOptions write_options;\n\n  po::options_description general_options(\"Clean up the borders of a Sentinel1 radar image.\\n\\nGeneral Options\");\n  general_options.add_options()\n    (\"output-path,o\",    po::value<std::string>(&output_path), \"The output file path\")\n    (\"num-threads\",      po::value<int>(&num_threads)->default_value(0), \n                         \"Number of threads to use for writing\")\n    (\"tile-size\",        po::value<int>(&tile_size)->default_value(2048), \n                         \"This is the farthest in that bad edges can be corrected.\")\n    (\"help,h\", \"Display this help message\");\n\n  po::options_description hidden_options(\"\");\n  hidden_options.add_options()\n    (\"input-file\", po::value<std::string>(&input_file));\n\n  po::options_description options(\"Allowed Options\");\n  options.add(general_options).add(hidden_options);\n\n  po::positional_options_description p;\n  p.add(\"input-file\", -1);\n\n  std::ostringstream usage;\n  usage << \"Usage: clean_sentinel1_borders [options] <image file>\" <<std::endl << std::endl;\n  usage << general_options << std::endl;\n\n  po::variables_map vm;\n  try {\n    po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );\n    po::notify( vm );\n  } catch (const po::error& e) {\n    std::cout << \"An error occurred while parsing command line arguments.\\n\";\n    std::cout << \"\\t\" << e.what() << \"\\n\\n\";\n    std::cout << usage.str();\n    return 1;\n  }\n\n  if( vm.count(\"help\") ) {\n    std::cout << usage.str();\n    return 0;\n  }\n\n  if( vm.count(\"output-path\") < 1 ) {\n    std::cerr << \"Error: must specify the output file!\" << std::endl << std::endl;\n    std::cout << usage.str();\n    return 1;\n  }\n\n  // Modify tile size to make sure good coverage of the borders.\n  ImageFormat input_format = image_format(input_file);\n  int tile_size_h = compute_new_tile_size(tile_size, input_format.cols);\n  int tile_size_v = compute_new_tile_size(tile_size, input_format.rows); \n\n  // Load tile size and thread count into VW internals\n  write_options.raster_tile_size = Vector2i(tile_size_h, tile_size_v);\n  vw_settings().set_default_tile_size(tile_size);\n  if (num_threads > 0) {\n    write_options.num_threads = num_threads;\n    vw_settings().set_default_num_threads(write_options.num_threads);\n  }\n\n  // Generate the output image\n  const double OUTPUT_NODATA = 0;\n  std::remove(output_path.c_str());\n  block_write_gdal_image(output_path,\n                         clean_sentinel1_borders(DiskImageView<uint16>(input_file)), \n                         OUTPUT_NODATA, write_options);\n  \n}\n", "meta": {"hexsha": "95a966658217ab93249884b3f6f66cace440ffc2", "size": 19596, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/tools/clean_sentinel1_borders.cc", "max_stars_repo_name": "lucasz93/visionworkbench", "max_stars_repo_head_hexsha": "1784572beda475e6770384f5cf34b578a320da51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 318.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T16:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T07:12:20.000Z", "max_issues_repo_path": "src/vw/tools/clean_sentinel1_borders.cc", "max_issues_repo_name": "lucasz93/visionworkbench", "max_issues_repo_head_hexsha": "1784572beda475e6770384f5cf34b578a320da51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-07-30T22:22:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T16:11:55.000Z", "max_forks_repo_path": "src/vw/tools/clean_sentinel1_borders.cc", "max_forks_repo_name": "lucasz93/visionworkbench", "max_forks_repo_head_hexsha": "1784572beda475e6770384f5cf34b578a320da51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T00:57:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T13:51:40.000Z", "avg_line_length": 39.5080645161, "max_line_length": 113, "alphanum_fraction": 0.6699836701, "num_tokens": 5014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.04084571459642654, "lm_q1q2_score": 0.017257503729287752}}
{"text": "// $Id: matrix_BOOST.cpp 27906 2007-04-27 11:50:53Z wmeeusse $\n// Copyright (C) 2002 Klaas Gadeyne <first dot last at gmail dot com>\n\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\n#include \"../config.h\"\n#ifdef __MATRIXWRAPPER_BOOST__\n\n#include \"matrix_BOOST.h\"\n#include \"vector_BOOST.h\"\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nusing namespace std;\n\n// Passing the constructor arguments...\nMyMatrix::Matrix() : BoostMatrix() {}\nMyMatrix::Matrix(int num_rows, int num_cols) : BoostMatrix(num_rows,\n\t\t\t\t\t\t\t   num_cols){}\n\n// Destructor\nMyMatrix::~Matrix(){}\n\n// Copy constructor\nMyMatrix::Matrix(const MyMatrix& a) : BoostMatrix(a){}\n\n// ill-designed\nMyMatrix::Matrix(const BoostMatrix & a) : BoostMatrix(a){}\n\nMyMatrix::Matrix(int num_rows,const RowVector& v):BoostMatrix(num_rows,v.size()){\n  BoostMatrix & m = *this;\n  for(unsigned int i=0;i<num_rows;i++)\n    row(m,i).assign(v);\n}\n\nMyRowVector MyMatrix::operator[](unsigned int i) const{\n  return this->rowCopy(i);\n}\n\n// Size/Capacity\nunsigned int MyMatrix::size() const { return this->size1();}\nunsigned int MyMatrix::capacity() const { return this->size1();}\n\n// Number of Rows/Cols\nunsigned int MyMatrix::rows() const { return this->size1();}\nunsigned int MyMatrix::columns() const { return this->size2();}\n\n// MATRIX - SCALAR operators\nMyMatrix& MyMatrix::operator+= (double a)\n{\n  BoostMatrix & op1 = *this;\n  op1 += boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a);\n  return (MyMatrix&)op1;\n}\n\nMyMatrix& MyMatrix::operator-= (double a)\n{\n  BoostMatrix & op1 = (*this);\n  op1 -= boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a);\n  return (MyMatrix&) op1;\n}\n\nMyMatrix& MyMatrix::operator*= (double a)\n{\n  BoostMatrix & op1 = (*this);\n  op1 *= a;\n  return *this;\n}\n\nMyMatrix& MyMatrix::operator/= (double a)\n{\n  BoostMatrix & op1 = (*this);\n  op1 /= a;\n  return (MyMatrix&) op1;\n}\n\nMyMatrix MyMatrix::operator+ (double a) const\n{\n  return (MyMatrix)(((BoostMatrix)(*this)) + boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a));\n}\n\nMyMatrix MyMatrix::operator- (double a) const\n{\n  return (MyMatrix)(((BoostMatrix)(*this)) - boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a));\n}\n\nMyMatrix MyMatrix::operator* (double a) const\n{\n  const BoostMatrix& op1 = (*this);\n  return (MyMatrix) (op1 *  a);\n}\n\nMyMatrix MyMatrix::operator/ (double a) const\n{\n  const BoostMatrix& op1 = (*this);\n  return (MyMatrix) (op1 /  a);\n}\n\nMyMatrix&\nMyMatrix::operator =(const MySymmetricMatrix& a)\n{\n  *this =(MyMatrix) a;\n\n  return *this;\n}\n\n// MATRIX - MATRIX Operators\nMyMatrix MyMatrix::operator- (const MyMatrix& a) const\n{\n  const BoostMatrix& op1 = *this;\n  const BoostMatrix& op2 = a;\n\n  return (MyMatrix)(op1 - op2);\n}\n\nMyMatrix MyMatrix::operator+ (const MyMatrix& a) const\n{\n  const BoostMatrix& op1 = *this;\n  const BoostMatrix& op2 = a;\n\n  return (MyMatrix)(op1 + op2);\n}\n\nMyMatrix MyMatrix::operator* (const MyMatrix& a) const\n{\n  const BoostMatrix& op1 = *this;\n  const BoostMatrix& op2 = a;\n\n  return (MyMatrix) prod(op1,op2);\n}\n\nMyMatrix & MyMatrix::operator+= (const MyMatrix& a)\n{\n  BoostMatrix & op1 = (*this);\n  const BoostMatrix & op2 = a;\n  op1 += op2;\n  return (MyMatrix &) op1;\n}\n\nMyMatrix & MyMatrix::operator-= (const MyMatrix& a)\n{\n  BoostMatrix & op1 = (*this);\n  const BoostMatrix & op2 = a;\n  op1 -= op2;\n  return (MyMatrix &) op1;\n}\n\n\n// MATRIX - VECTOR Operators\nMyColumnVector MyMatrix::operator* (const MyColumnVector &b) const\n{\n  const BoostMatrix& op1 = (*this);\n  return (MyColumnVector) prod(op1, ((const BoostColumnVector&)b));\n}\n\n\n\ndouble& MyMatrix::operator()(unsigned int a, unsigned int b)\n{\n  BoostMatrix & op1 = (*this);\n  return op1(a-1,b-1);\n}\n\ndouble MyMatrix::operator()(unsigned int a, unsigned int b) const\n{\n  BoostMatrix  op1(*this);\n  return op1(a-1,b-1);\n}\n\nbool MyMatrix::operator==(const MyMatrix& a) const\n{\n  if (this->rows() != a.rows()) return false;\n  if (this->columns() != a.columns()) return false;\n  return(norm_inf((BoostMatrix)(*this)-(BoostMatrix)a) == 0);\n}\n\n\n// Set all elements equal to a\nMyMatrix&\n MyMatrix::operator=(double a)\n{\n  *this = (MyMatrix)boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a);\n\n  return *this;\n}\n\n\nMyRowVector MyMatrix::rowCopy(unsigned int r) const\n{\n  unsigned int cols = columns();\n  BoostRowVector temp(cols);\n  for (unsigned int i=0; i<cols; i++)\n    temp(i) = (*this)(r,i+1);\n  return (MyRowVector) temp;\n}\n\nMyColumnVector MyMatrix::columnCopy(unsigned int c) const\n{\n  unsigned int ro = rows();\n  BoostColumnVector temp(ro);\n  for (unsigned int i=0; i<ro; i++)\n    temp(i) = (*this)(i+1,c);\n  return (MyColumnVector) temp;\n}\n\n\n\n\nMyMatrix MyMatrix::transpose() const\n{\n  const BoostMatrix &op1 = (*this);\n  return (MyMatrix) trans(op1);\n}\n\ndouble MyMatrix::determinant() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  double result = 1.0;\n  const BoostMatrix& A = (*this);\n  switch (r)\n  {\n        case 1:\n            return A(0,0);\n        case 2: \n            return ( ( A(0,0) * A(1,1)) - ( A(1,0) * A(0,1)) );\n        default: \n            BoostMatrix LU(r,r);\n            boost::numeric::ublas::permutation_matrix<> ndx(r);\n            noalias(LU) = A;\n            int res = lu_factorize(LU,ndx);\n            assert(res == 0);\n\n            int s = 1;\n            for (boost::numeric::ublas::matrix<double>::size_type i=0;i<LU.size1();++i) {\n              result *= LU(i,i);\n              if (ndx(i)!=i) s = -s;\n            }\n            return result*s;\n  }\n}\n\n\nMyMatrix MyMatrix::inverse() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  const BoostMatrix& A = (*this);\n  BoostMatrix Ai(r,r);\n  switch (r) \n  {\n     case 1:\n     {\n        Ai(0,0) = 1/A(0,0);\n        break;\n     }\n     case 2:\n     {\n       double det = A(0,0)*A(1,1)-A(0,1)*A(1,0);\n       Ai(0,0) = A(1,1)/det;\n       Ai(1,1) = A(0,0)/det;\n       Ai(0,1) = -A(0,1)/det;\n       Ai(1,0) = -A(1,0)/det;\n       break;\n     }\n     default:\n     {\n       BoostMatrix LU(r,r);\n       boost::numeric::ublas::permutation_matrix<> ndx(r);\n       noalias(LU) = A;\n       int res = lu_factorize(LU,ndx);\n       assert(res == 0);\n       noalias(Ai) = boost::numeric::ublas::identity_matrix<double>(r);\n       lu_substitute(LU,ndx,Ai);\n       break;\n     }\n  }\n  return Ai;\n}\n\n\nint\nMyMatrix::convertToSymmetricMatrix(MySymmetricMatrix& sym)\n{\n  // test if matrix is square matrix\n  assert(this->rows() == this->columns());\n\n  // if necessairy, resize sym\n  // only check cols or rows. Symmetric matrix is square.\n  if ( sym.rows() != this->rows() )\n    sym = MySymmetricMatrix(this->rows());\n\n  // copy elements\n  for ( unsigned int i=0; i<this->rows(); i++ )\n    for ( unsigned int j=0; j<=i; j++ )\n      sym(i+1,j+1) = (*this)(i+1,j+1);\n  return 0;\n}\n\nvoid\nMyMatrix::resize(unsigned int i, unsigned int j, bool copy, bool initialize)\n{\n  BoostMatrix & temp = (BoostMatrix &) (*this);\n  temp.resize(i,j,copy);\n}\n\n// get sub matrix\nMyMatrix MyMatrix::sub(int i_start, int i_end, int j_start , int j_end) const\n{\n  MyMatrix submatrix(i_end-i_start+1, j_end-j_start+1);\n  for (int i=i_start; i<=i_end; i++)\n    for (int j=j_start; j<=j_end; j++)\n      submatrix(i-i_start+1,j-j_start+1) = (*this)(i,j);\n\n  return submatrix;\n}\n\n/////////////////////////////\n// CLASS SYMMETRIC MATRIX  //\n/////////////////////////////\n\nMySymmetricMatrix::SymmetricMatrix() : BoostSymmetricMatrix() {}\nMySymmetricMatrix::SymmetricMatrix(int n) : BoostSymmetricMatrix(n) {}\nMySymmetricMatrix::SymmetricMatrix(int num_rows,const RowVector& v):BoostSymmetricMatrix(num_rows,v.size()){\n  BoostSymmetricMatrix & m = *this;\n  for(unsigned int i=0;i<num_rows;i++)\n    row(m,i).assign(v);\n}\n\nMyRowVector MySymmetricMatrix::operator[](unsigned int i) const{\n  return this->rowCopy(i);\n}\n\n\n\n// Copy constructor\nMySymmetricMatrix::SymmetricMatrix(const SymmetricMatrix& a) : BoostSymmetricMatrix(a){}\nMySymmetricMatrix::SymmetricMatrix(const BoostSymmetricMatrix & a) : BoostSymmetricMatrix(a){}\n\n// Destructor\nMySymmetricMatrix::~SymmetricMatrix(){}\n\n// Size/Capacity\nunsigned int MySymmetricMatrix::size() const { return this->size1();}\nunsigned int MySymmetricMatrix::capacity() const { return this->size1();}\n\n// Ask Number of Rows and Columns\nunsigned int MySymmetricMatrix::rows() const { return this->size1();}\nunsigned int MySymmetricMatrix::columns() const { return this->size2();}\n\n\nMyRowVector MySymmetricMatrix::rowCopy(unsigned int r) const\n{\n  \n  unsigned int cols = columns();\n  BoostRowVector temp(cols);\n  for (unsigned int i=0; i<cols; i++)\n    temp(i) = (*this)(r,i+1);\n  return (MyRowVector) temp;\n}\n\nMySymmetricMatrix MySymmetricMatrix::transpose() const {return (*this);}\n\nMySymmetricMatrix MySymmetricMatrix::inverse() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  const BoostMatrix& A = (*this);\n  BoostMatrix Ai(r,r);\n  switch (r) \n  {\n     case 1:\n     {\n        Ai(0,0) = 1/A(0,0);\n        break;\n     }\n     case 2:\n     {\n       double det = A(0,0)*A(1,1)-A(0,1)*A(1,0);\n       Ai(0,0) = A(1,1)/det;\n       Ai(1,1) = A(0,0)/det;\n       Ai(0,1) = -A(0,1)/det;\n       Ai(1,0) = -A(1,0)/det;\n       break;\n     }\n     default:\n     {\n       BoostMatrix LU(r,r);\n       boost::numeric::ublas::permutation_matrix<> ndx(r);\n       noalias(LU) = A;\n       int res = lu_factorize(LU,ndx);\n       assert(res == 0);\n       noalias(Ai) = boost::numeric::ublas::identity_matrix<double>(r);\n       lu_substitute(LU,ndx,Ai);\n       break;\n     }\n  }\n\n  return MySymmetricMatrix(Ai);\n}\n\ndouble MySymmetricMatrix::determinant() const\n{\n  unsigned int r = this->rows();\n  assert(r == this->columns());\n  const BoostMatrix& A = (*this);\n  switch (r) \n  {\n     case 1:\n     {\n        return A(0,0);\n     }\n     case 2:\n     {\n       return A(0,0)*A(1,1)-A(0,1)*A(1,0);\n     }\n     default:\n     {\n        BoostMatrix LU(r,r);\n        boost::numeric::ublas::permutation_matrix<> ndx(r);\n        noalias(LU) = A;\n        int res = lu_factorize(LU,ndx);\n        assert(res == 0);\n\n        double result = 1.0;\n        int s = 1;\n        for (boost::numeric::ublas::matrix<double>::size_type i=0;i<LU.size1();++i) {\n          result *= LU(i,i);\n          if (ndx(i)!=i) s = -s;\n        }\n        return result*s;\n     }\n  }\n}\n\n\n// Set all elements equal to a\nMySymmetricMatrix& MySymmetricMatrix::operator=(const double a)\n{\n  *this = (MySymmetricMatrix)boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a);\n\n  return *this;\n}\n\n\n// SYMMETRICMATRIX - SCALAR operators\nMySymmetricMatrix& MySymmetricMatrix::operator +=(double a)\n{\n  BoostSymmetricMatrix & op1 = *this;\n  op1 += boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a);\n  return (MySymmetricMatrix&)op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator -=(double a)\n{\n  BoostSymmetricMatrix & op1 = *this;\n  op1 -= boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a);\n  return (MySymmetricMatrix&)op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator *=(double b)\n{\n  BoostSymmetricMatrix & op1 = (*this);\n  op1 *= b;\n  return (MySymmetricMatrix&) op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator /=(double b)\n{\n  BoostSymmetricMatrix & op1 = (*this);\n  op1 /= b;\n  return (MySymmetricMatrix&) op1;\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator +(double a) const\n{\n  return (MySymmetricMatrix)(((BoostSymmetricMatrix)(*this)) + boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a));\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator -(double a) const\n{\n  return (MySymmetricMatrix)(((BoostSymmetricMatrix)(*this)) - boost::numeric::ublas::scalar_matrix<double>(rows(),columns(),a));\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator *(double b) const\n{\n const BoostSymmetricMatrix& op1 = (*this);\n  return (MySymmetricMatrix) (op1 *  b);\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator /(double b) const\n{\n  const BoostSymmetricMatrix& op1 = (*this);\n  return (MySymmetricMatrix) (op1 /  b);\n}\n\n\n\n\n// SYMMETRICMATRIX - MATRIX operators\nMyMatrix& MySymmetricMatrix::operator +=(const MyMatrix& a)\n{\n  BoostSymmetricMatrix & op1 = (*this);\n  op1 += a;\n  return (MyMatrix &) op1;\n}\n\nMyMatrix& MySymmetricMatrix::operator -=(const MyMatrix& a)\n{\n  BoostSymmetricMatrix & op1 = (*this);\n  op1 -= a;\n  return (MyMatrix &) op1;\n}\n\n\nMyMatrix MySymmetricMatrix::operator+ (const MyMatrix &a) const\n{\n  const BoostSymmetricMatrix& op1 = *this;\n  const BoostMatrix& op2 = a;\n\n  return (MyMatrix) (op1 + op2);\n}\n\nMyMatrix MySymmetricMatrix::operator- (const MyMatrix &a) const\n{\n  const BoostSymmetricMatrix& op1 = *this;\n  const BoostMatrix& op2 = a;\n\n  return (MyMatrix) (op1 - op2);\n}\n\nMyMatrix MySymmetricMatrix::operator* (const MyMatrix &a) const\n{\n  const BoostSymmetricMatrix& op1 = *this;\n  const BoostMatrix& op2 = a;\n\n  return (MyMatrix) prod(op1, op2);\n}\n\n\n\n// SYMMETRICMATRIX - SYMMETRICMATRIX operators\nMySymmetricMatrix& MySymmetricMatrix::operator +=(const MySymmetricMatrix& a)\n{\n  BoostSymmetricMatrix & op1 = (*this);\n  const BoostSymmetricMatrix & op2 = a;\n  op1 += op2;\n  return (MySymmetricMatrix &) op1;\n}\n\nMySymmetricMatrix& MySymmetricMatrix::operator -=(const MySymmetricMatrix& a)\n{\n  BoostSymmetricMatrix & op1 = (*this);\n  const BoostSymmetricMatrix & op2 = a;\n  op1 -= op2;\n  return (MySymmetricMatrix &) op1;\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator+ (const MySymmetricMatrix &a) const\n{\n  const BoostSymmetricMatrix& op1 = *this;\n  const BoostSymmetricMatrix& op2 = a;\n\n  return (MySymmetricMatrix) (op1 + op2);\n}\n\nMySymmetricMatrix MySymmetricMatrix::operator- (const MySymmetricMatrix &a) const\n{\n  const BoostSymmetricMatrix& op1 = *this;\n  const BoostSymmetricMatrix& op2 = a;\n\n  return (MySymmetricMatrix) (op1 - op2);\n}\n\nMyMatrix MySymmetricMatrix::operator* (const MySymmetricMatrix &a) const\n{\n  const BoostSymmetricMatrix& op1 = *this;\n  const BoostSymmetricMatrix& op2 = a;\n\n  return (MyMatrix) prod(op1, op2);\n}\n\n\n\n\nMyColumnVector MySymmetricMatrix::operator* (const MyColumnVector &b) const\n{\n  const BoostSymmetricMatrix& op1 = (BoostSymmetricMatrix) *this;\n  return (MyColumnVector) prod(op1, ((const BoostColumnVector&)b));\n}\n\nvoid MySymmetricMatrix::multiply (const MyColumnVector &b, MyColumnVector &result) const\n{\n  const BoostSymmetricMatrix& op1 = (BoostSymmetricMatrix) *this;\n  result = (MyColumnVector) prod(op1, ((const BoostColumnVector&)b));\n}\n\nMyMatrix MySymmetricMatrix::sub(int i_start, int i_end, int j_start , int j_end) const\n{\n  MyMatrix submatrix(i_end-i_start+1, j_end-j_start+1);\n  for (int i=i_start; i<=i_end; i++)\n    for (int j=j_start; j<=j_end; j++)\n      submatrix(i-i_start+1,j-j_start+1) = (*this)(i,j);\n\n  return submatrix;\n}\n\n\n\ndouble& MySymmetricMatrix::operator()(unsigned int a, unsigned int b)\n{\n  BoostSymmetricMatrix & op1 = (*this);\n  return op1(a-1,b-1);\n}\n\ndouble MySymmetricMatrix::operator()(unsigned int a, unsigned int b) const\n{\n  BoostSymmetricMatrix op1(*this);\n  return op1(a-1,b-1);\n}\n\nbool MySymmetricMatrix::operator==(const MySymmetricMatrix& a) const\n{\n  if (this->rows() != a.rows()) return false;\n  if (this->columns() != a.columns()) return false;\n  return(norm_inf((BoostSymmetricMatrix)(*this)-(BoostSymmetricMatrix)a) == 0);\n}\n\nvoid\nMySymmetricMatrix::resize(unsigned int i, bool copy, bool initialize)\n{\n  BoostSymmetricMatrix & temp = (BoostSymmetricMatrix &) (*this);\n  temp.resize(i, copy);\n}\n\n\n#endif\n", "meta": {"hexsha": "dbd1d2e4f2963226312600ef2de340e55f779106", "size": 16074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/turtlebot2_src/src/orocos-bayesian-filtering/orocos_bfl/src/wrappers/matrix/matrix_BOOST.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/matrix/matrix_BOOST.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/matrix/matrix_BOOST.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": 24.6533742331, "max_line_length": 129, "alphanum_fraction": 0.6560283688, "num_tokens": 4769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.040845711239646296, "lm_q1q2_score": 0.01725750231103254}}
{"text": "// \n//  Copyright © 2015 Claus Christmann <hcc |ä| gatech.edu>.\n//\n//  Licensed under the Apache License, Version 2.0 (the \"License\");\n//  you may not use this file except in compliance with the License.\n//  You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n// \n\n\n#ifndef TYPEDEFS_H\n#define TYPEDEFS_H\n\n#include <Eigen/Dense>\n\nnamespace AMG {\n  \n  /** \\brief A tupel of 3 values, representing a set of coordinates.\n   * \n   * The purpose of this type is to allow faster computations by accessing the\n   * underlying Eigen::Vector3d type inside functions and algorithms that have\n   * sorted out the FrameOfReference issues, i.e. all utilized entities are\n   * expressed in the same FrameOfReference.\n   */\n  using CoordinateTupel = Eigen::Vector3d;\n  \n  /** \\brief A tupel of 4 values, representing a set of quaternions.\n   * \n   * Quaternions are normally defined as either <b>q = w + ix + jy + kz</b> or \n   * <b>q = q0 + iq1 + jq2 + kq3</b>. \n   * \n   * Eigen, the underlying matrix library has an own type for quaternions:\n   * Eigen::Quaternion::Coefficients. However, those coefficients are\n   * internally stored in an unconeventional manner, which could lead to \n   * confusion. Eigen stores the quaternion tupel as [x,y,z,w], which could lead \n   * to an ordering permutation when used in the \"flight mechanics way\" as\n   * \n   * \\code\n   * double q0=Eigen::Quaternion::Coefficient[3]; // w, the real part\n   * double q1=Eigen::Quaternion::Coefficient[0]; // x, the 1st imaginary part\n   * double q2=Eigen::Quaternion::Coefficient[1]; // y, the 2nd imaginary part\n   * double q3=Eigen::Quaternion::Coefficient[2]; // z, the 3rd imaginary part\n   * \\endcode\n   * \n   * In order to avoid this, an  AMG::QuaternionTupel is defined as the \n   * [q0,q1,q2,q3] tupel of quaternions: \n   * \n   * \\code\n   * double q0=AMG::QuaternionTupel[0]; // w, the real part\n   * double q1=AMG::QuaternionTupel[1]; // x, the 1st imaginary part\n   * double q2=AMG::QuaternionTupel[2]; // y, the 2nd imaginary part\n   * double q3=AMG::QuaternionTupel[3]; // z, the 3rd imaginary part\n   * \\endcode\n   * \n   * \\warning As a result of this \n   *  AMG::QuaternionTupel != Eigen::Quaternion::Coefficients ! (It is a \n   *  permutation of it.)\n   */\n  using QuaternionTupel = Eigen::Vector4d ;\n  \n  /** \\brief A 3-tupel holding 3-2-1 Euler angles.\n   * \n   * This is a 3-tupel holding the roll/phi, pitch/theta, and yaw/psi \n   * Euler-angles.\n   * \n   * \\note The tupel does not keep track of the used units, i.e. degrees or \n   *  radians! (That's a todo...)\n   * \n   * \\code\n   * AMG::EulerAngleTupel euler;\n   * \n   * double phi   = euler[0]; // roll angle\n   * double theta = euler[1]; // pitch angle\n   * double psi   = euler[2]; // yaw angle\n   * \\endcode\n   * \n   * \\todo Make this a template taking Units::degree or Units::radian\n   */\n  using EulerAngleTupel = Eigen::Vector3d;\n  \n  \n  \n}\n\n\n#endif // TYPEDEFS_H", "meta": {"hexsha": "80e43102e075fd1984a89efdf0c22d1018a09a34", "size": 3276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rdParty/include/amg/typedefs.hpp", "max_stars_repo_name": "mvsframework/mvs", "max_stars_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "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/3rdParty/include/amg/typedefs.hpp", "max_issues_repo_name": "mvsframework/mvs", "max_issues_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/3rdParty/include/amg/typedefs.hpp", "max_forks_repo_name": "mvsframework/mvs", "max_forks_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "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.2258064516, "max_line_length": 81, "alphanum_fraction": 0.6691086691, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.04272219297589361, "lm_q1q2_score": 0.017241260391026875}}
{"text": "/**\n * @file onepass_plus_impl.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 ONEPASS_PLUS_IMPL_HPP\n#define ONEPASS_PLUS_IMPL_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/details/arlib_utils.hpp>\n#include <arlib/type_traits.hpp>\n\n#include <cassert>\n#include <iostream>\n#include <memory>\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace arlib {\n/**\n * Implementations details of kSPwLO algorithms\n */\nnamespace details {\n\n//===----------------------------------------------------------------------===//\n//                    OnePass+ algorithm support classes\n//===----------------------------------------------------------------------===//\n\n/**\n * A label for a node in the graph to keep track of its exploration\n *        state.\n *\n * A label tracks the path from the source to the node @c n it's attached, the\n * similarity of the path <tt>p(s -> n)</tt> wrt to the alternative paths\n * computed so far and the time step the similarities were updated (i.e. the\n * number of alternative paths against which the similarities are currently\n * computed)\n *\n * Labels can either be @c head labels if they are attached to source node, or\n * have a predecessor label, i.e. they are attached to a node @c n such that\n * there exist a label attached to a node @c n' and an edge <tt>(n', n)</tt> in\n * Graph.\n *\n * @tparam Graph A Boost::Graph\n * @tparam Vertex A vertex of Graph.\n * @tparam Length The value type of an edge weight of Graph.\n */\ntemplate <typename Graph, typename Length, typename Edge = edge_of_t<Graph>,\n          typename Vertex = vertex_of_t<Graph>>\nclass OnePassLabel {\nprivate:\n  Vertex node;\n  Length length;\n  Length lower_bound;\n  OnePassLabel *previous;\n  std::vector<double> similarity_map;\n  int k;\n  int checked_at_step;\n\npublic:\n  /**\n   * size_type trait of similarity vector\n   */\n  using similarity_map_size_type = typename decltype(similarity_map)::size_type;\n\n  /**\n   * iterator trait of similarity vector\n   */\n  using similarity_map_iterator_type =\n      typename decltype(similarity_map)::iterator;\n\n  /**\n   * Length\n   */\n  using length_type = Length;\n\n  /**\n   * Vertex\n   */\n  using vertex_type = Vertex;\n\n  /**\n   * Construct a new OnePass Label object with a predecessor label.\n   *\n   * @param node Node to attach this label to.\n   * @param length Distance of this node from source following the path from\n   *        this label to the source's one.\n   * @param lower_bound AStar heuristic of the distance of @p node from target.\n   * @param previous Predecessor label.\n   * @param k Number of k alternative paths to compute.\n   * @param checked_at_step The current time step (i.e. the number of\n   *        alternative paths currently computed)\n   */\n  OnePassLabel(Vertex node, Length length, Length lower_bound,\n               OnePassLabel *previous, int k, int checked_at_step)\n      : node{node}, length{length},\n        lower_bound{lower_bound}, previous{previous},\n        similarity_map(k, 0), k{k}, checked_at_step{checked_at_step} {}\n\n  /**\n   * Construct a new OnePass Label object with no predecessor (i.e. a @c\n   * head label)\n   *\n   * @param node Node to attach this label to.\n   * @param length Distance of this node from source following the path from\n   *        this label to the source's one.\n   * @param lower_bound AStar heuristic of the distance of @p node from target.\n   * @param k Number of k alternative paths to compute.\n   * @param checked_at_step The current time step (i.e. the number of\n   *        alternative paths currently computed)\n   */\n  OnePassLabel(Vertex node, Length length, Length lower_bound, int k,\n               int checked_at_step)\n      : node{node}, length{length}, lower_bound{lower_bound}, previous{nullptr},\n        similarity_map(k, 0), k{k}, checked_at_step{checked_at_step} {}\n\n  std::vector<Edge> get_path(Graph const &G) const {\n    using namespace boost;\n    auto edge_set = std::vector<Edge>{};\n\n    auto v = node;\n    auto prev = previous;\n    while (prev != nullptr) {\n      auto u = prev->node;\n      auto [e, is_ok] = edge(u, v, G);\n      assert(is_ok &&\n             \"[arlib::details::OnePassLabel::get_path] Edge not found.\");\n      edge_set.push_back(e);\n\n      // Shift label pointer back\n      v = u;\n      prev = prev->previous;\n    }\n\n    return edge_set;\n  }\n\n  bool is_path_acyclic(Vertex begin) const {\n    bool is_acyclic = true;\n    auto current = this;\n    while (current != nullptr) {\n      if (current->node == begin) {\n        is_acyclic = false;\n        break;\n      }\n      current = current->previous;\n    }\n    return is_acyclic;\n  }\n\n  /**\n   * @param kth The kth alternative path index.\n   * @return A reference to the similarity of path <tt>p(source, n)</tt> wrt to\n   *         @p kth alternative path.\n   */\n  double &get_similarity_with(int kth) { return similarity_map.at(kth); }\n\n  /**\n   * @param kth The kth alternative path index.\n   * @return A const-reference to the similarity of path <tt>p(source, n)</tt>\n   *         wrt to @p kth alternative path.\n   */\n  const double &get_similarity_with(int kth) const {\n    return similarity_map.at(kth);\n  }\n\n  /**\n   * @return the number of alternative paths for which there exists a similarity\n   *         measure for, for this label.\n   */\n  similarity_map_size_type get_num_paths() const {\n    return similarity_map.size();\n  }\n\n  /**\n   * @return a copy of the similarity vector wrt the alternative paths.\n   */\n  std::vector<double> get_similarity_map() const {\n    return std::vector<double>(std::begin(similarity_map),\n                               std::end(similarity_map));\n  }\n\n  /**\n   * Copies the similarity values from [@p first, @p last) iterators into\n   *        label's similarity vector.\n   *\n   * @param first begin iterator.\n   * @param last past-to-end iterator.\n   */\n  void set_similarities(similarity_map_iterator_type first,\n                        similarity_map_iterator_type last) {\n    std::copy(first, last, std::begin(similarity_map));\n  }\n\n  /**\n   * @return the node this label is attached to.\n   */\n  Vertex get_node() const { return node; }\n\n  /**\n   * @return the distance of this node from source following the path from\n   *         this label to the source's one.\n   */\n  length_type get_length() const { return length; }\n\n  /**\n   * @return AStar heuristic of the distance of the node from target.\n   */\n  length_type get_lower_bound() const { return lower_bound; }\n\n  /**\n   * @return Number of k alternative paths to compute.\n   */\n  int num_paths_k() const { return k; }\n\n  /**\n   * @return the time step the similarities were updated (i.e. the\n   *         number of alternative paths against which the similarities are\n   *         currently computed).\n   */\n  int last_check() const { return checked_at_step; }\n\n  /**\n   * @param currentStep the current time step.\n   * @return true if @c last_check() < @p currentStep.\n   * @return false otherwise.\n   */\n  bool is_outdated(int currentStep) const {\n    return checked_at_step < currentStep;\n  }\n\n  /**\n   * Set the time step of similarities update.\n   *\n   * @param step the time step.\n   */\n  void set_last_check(int step) {\n    assert(step > 0);\n    checked_at_step = step;\n  }\n\nprivate:\n  template <typename Graph2, typename Length2>\n  friend std::ostream &operator<<(std::ostream &os,\n                                  const OnePassLabel<Graph2, Length2> &label);\n};\n\ntemplate <typename Graph2, typename Length2>\nstd::ostream &operator<<(std::ostream &os,\n                         const OnePassLabel<Graph2, Length2> &label) {\n  os << \"(node = \" << label.node << \", length = \" << label.length\n     << \", lower_bound = \" << label.lower_bound << \", k = \" << label.k\n     << \", checked_at_step = \" << label.checked_at_step\n     << \", similarities = [ \";\n  for (auto sim : label.similarity_map) {\n    os << sim << \" \";\n  }\n\n  os << \"])\";\n  return os;\n}\n\n/**\n * A conventient container for labels dominance checking.\n *\n * When a new label @c l' for a node @c n is created we must check it against\n * Lemma 2: Let @c P_LO the set of computed alternative paths so far. If all the\n * labels already existing for node @c n have a similarity with @c P_LO that is\n * less than the similarity of @c l' with @c P_LO, then @c l' is dominated and\n * should be pruned.\n *\n * @tparam Graph A Boost::Graph\n * @tparam Vertex A vertex of Graph.\n */\ntemplate <typename Graph, typename Length, typename Vertex = vertex_of_t<Graph>>\nclass SkylineContainer {\npublic:\n  using Label = OnePassLabel<Graph, Length>;\n  using LabelPtr = Label *;\n\n  /**\n   * Inserts a label into the skyline. Before insertion, you should check\n   * if the skyline already dominates @p label. See dominates().\n   *\n   * @param label A label to add to the skyline.\n   */\n  void insert(Label *label) {\n    auto node_n = label->get_node();\n    // If node_n is new\n    if (!contains(node_n)) {\n      // Initialize the labels for node n with 'label'\n      auto labels_for_n = std::vector<LabelPtr>{label};\n      container.insert(std::make_pair(node_n, labels_for_n));\n    } else {\n      // If not, just add the label to node_n's list of labels\n      container[node_n].push_back(label);\n    }\n  }\n\n  /**\n   * @param node A node of the graph.\n   * @return true if the skyline contains @p node.\n   * @return false otherwise.\n   */\n  bool contains(Vertex node) const {\n    return container.find(node) != std::end(container);\n  }\n\n  /**\n   * Check if the skyline dominates @p label. Refer to SkylineContainer\n   * description for a more clear explanation.\n   *\n   * @param label A label to check if it's dominated by the skyline.\n   * @return true if the skyline dominates @p label.\n   * @return false otherwise.\n   */\n  bool dominates(const Label &label) {\n\n    auto node_n = label.get_node();\n    // If node_n is not in the skyline, then we have no labels to check\n    if (!contains(node_n)) {\n      return false;\n    }\n\n    // For each of the paths p' we have similarity measure in 'label' we\n    // check if label.sim(p') is less than at least one of the labels in the\n    // skyline. If so, the skyline does NOT dominates 'label'.\n    for (const auto label_p : container[node_n]) {\n      LabelPtr tmpLabel = label_p;\n      bool skyline_dominates_label = true;\n\n      for (int i = 0; i < static_cast<int>(label.get_num_paths()); ++i) {\n        if (label.get_similarity_with(i) < tmpLabel->get_similarity_with(i)) {\n          skyline_dominates_label = false;\n          break;\n        }\n      }\n\n      if (skyline_dominates_label) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * @return the number of labels stored in the skyline.\n   */\n  int num_labels() const {\n    int nb_labels = 0;\n\n    for (auto it = std::begin(container); it != std::end(container); ++it) {\n      nb_labels += it->second.size();\n    }\n\n    return nb_labels;\n  }\n\nprivate:\n  std::unordered_map<Vertex, std::vector<LabelPtr>, boost::hash<Vertex>>\n      container{};\n};\n\n/**\n * A Comparator functor to compare two labels in an A* fashion.\n *\n * A lower bound for the distance of the label from the target is used to decide\n * the ordering. The label with the lowest lower bound is the smallest.\n *\n * @tparam Graph A Boost::Graph\n */\ntemplate <typename Graph, typename Length> struct OnePassPlusASComparator {\n  using LabelPtr = OnePassLabel<Graph, Length> *;\n\n  bool operator()(LabelPtr lhs, LabelPtr rhs) const {\n    return lhs->get_lower_bound() > rhs->get_lower_bound();\n  }\n};\n\n//===----------------------------------------------------------------------===//\n//                      OnePass+ algorithm routines\n//===----------------------------------------------------------------------===//\n\ntemplate <typename Graph, typename EdgeMap,\n          typename resPathIndex = typename EdgeMap::mapped_type::size_type>\nvoid update_res_edges(const Graph &candidate, const Graph &graph,\n                      EdgeMap &resEdges, resPathIndex paths_count) {\n  using mapped_type = typename EdgeMap::mapped_type;\n  for (auto ei = edges(candidate).first; ei != edges(candidate).second; ++ei) {\n    auto edge_in_g =\n        edge(source(*ei, candidate), target(*ei, candidate), graph).first;\n\n    auto search = resEdges.find(edge_in_g);\n    if (search != std::end(resEdges)) { // edge found\n      search->second.push_back(paths_count - 1);\n    } else { // new edge, add it to resEdges\n      resEdges.insert(std::make_pair(edge_in_g, mapped_type{paths_count - 1}));\n    }\n  }\n}\n\ntemplate <typename EdgeMap, typename Edge,\n          typename resPathIndex = typename EdgeMap::mapped_type::size_type>\nvoid update_res_edges(const std::vector<Edge> &candidate, EdgeMap &resEdges,\n                      resPathIndex paths_count) {\n  using mapped_type = typename EdgeMap::mapped_type;\n  for (auto &e : candidate) {\n\n    auto search = resEdges.find(e);\n    if (search != std::end(resEdges)) { // edge found\n      search->second.push_back(paths_count - 1);\n    } else { // new edge, add it to resEdges\n      resEdges.insert(std::make_pair(e, mapped_type{paths_count - 1}));\n    }\n  }\n}\n\ntemplate <typename Label, typename Graph, typename EdgesMap, typename PathsMap,\n          typename WeightMap>\nbool update_label_similarity(Label &label, const Graph &G,\n                             const EdgesMap &resEdges, const PathsMap &resPaths,\n                             WeightMap &weight, double theta,\n                             std::size_t step) {\n  using namespace boost;\n  bool below_sim_threshold = true;\n  auto tmpPath = label.get_path(G);\n  for (auto &e : tmpPath) {\n    auto search = resEdges.find(e);\n    // if tmpPath share an edge with any k-th shortest path, update the\n    // overlapping factor\n    if (search != std::end(resEdges)) {\n      for (auto index : search->second) {\n        if (static_cast<int>(index) > label.last_check() && index < step) {\n          label.get_similarity_with(index) += weight[e];\n\n          // Check Lemma 1. The similarity between the candidate path and\n          // all the other k-shortest-paths must be less then theta\n          auto const &alt_path = resPaths[index];\n          auto alt_len = compute_length_from_edges(alt_path.begin(),\n                                                   alt_path.end(), weight);\n          if (label.get_similarity_with(index) / alt_len > theta) {\n            below_sim_threshold = false;\n            break;\n          }\n        }\n      }\n    }\n  }\n  return below_sim_threshold;\n}\n\ntemplate <typename Label, typename Vertex = typename Label::Vertex,\n          typename length_type = typename Label::length_type>\nstd::unique_ptr<Label> expand_path(Label *label, Vertex node,\n                                   length_type node_lower_bound,\n                                   length_type edge_weight, int step) {\n  auto tmpLength = label->get_length() + edge_weight;\n  auto tmpLowerBound = tmpLength + node_lower_bound;\n  return std::make_unique<Label>(node, tmpLength, tmpLowerBound, label,\n                                 label->num_paths_k(), step);\n}\n\ntemplate <typename EdgesMap, typename PathsList, typename WeightMap,\n          typename Edge = typename EdgesMap::key_type>\nbool is_below_sim_threshold(const Edge &c_edge,\n                            std::vector<double> &similarity_map, double theta,\n                            const EdgesMap &resEdges, const PathsList &resPaths,\n                            const WeightMap &weight) {\n  auto search = resEdges.find(c_edge);\n  if (search != std::end(resEdges)) {\n    auto &res_paths_with_c_edge = search->second;\n    for (auto index : res_paths_with_c_edge) {\n      similarity_map[index] += weight[c_edge];\n      auto const &alt_path = resPaths[index];\n      auto alt_len =\n          compute_length_from_edges(alt_path.begin(), alt_path.end(), weight);\n      auto similarity = similarity_map[index] / alt_len;\n      if (similarity > theta) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n} // namespace details\n} // namespace arlib\n\n#endif", "meta": {"hexsha": "13d8a119c777629845a3da54fac77dcaf2111e02", "size": 17246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/details/onepass_plus_impl.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/details/onepass_plus_impl.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/details/onepass_plus_impl.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": 33.2292870906, "max_line_length": 80, "alphanum_fraction": 0.6413661139, "num_tokens": 4060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.03676946990186956, "lm_q1q2_score": 0.017237183381785336}}
{"text": "#include <ScrimpTrivialPar.hpp>\n#include <logging.hpp>\n#include <timing.h>\n#include <partitioning_1d.h>\n#include <binproffile.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <cassert>\n#include <memory>\n#include <cstddef>\n#include <kernels.h>\n\n#include <boost/assert.hpp>\n#include <boost/align.hpp>\n#include <boost/filesystem.hpp>\n\n#include <mpi.h>\n\n#include <papiwrapper.hpp>\n\nusing namespace matrix_profile;\n\nusing DiagPartition = Partition1D;\n\n// easy aligned allocation.\n// code from https://www.boost.org/doc/libs/1_57_0/doc/html/align/examples.html#align.examples.aligned_ptr, licensed under the Boost Software License - Version 1.0\n// see copy of the license terms provided under /licenses/boostSoftwareLicense.txt\ntemplate<class T>\nusing aligned_ptr = std::unique_ptr<T,\n  boost::alignment::aligned_delete>;\n\ntemplate<class T, class... Args>\ninline aligned_ptr<T> make_aligned(Args&&... args)\n{\n  auto p = boost::alignment::\n    aligned_alloc(alignof(T), sizeof(T));\n  if (!p) {\n\tthrow std::bad_alloc();\n  }\n  try {\n\tauto q = ::new(p) T(std::forward<Args>(args)...);\n\treturn aligned_ptr<T>(q);\n  } catch (...) {\n\tboost::alignment::aligned_free(p);\n\tthrow;\n  }\n}\n// condinue own code\n\n\n#define TIMEPOINT( varname ) const Timepoint varname = matrix_profile::get_cur_time();\n\nusing namespace matrix_profile;\n\nstatic FactoryRegistration<ScrimpTrivialPar> s_trivParReg(\"scrimp_triv_par\");\nstatic const int notification_interval_iter = 10000;\n\n\nvoid ScrimpTrivialPar::MPI_MatProfSOA_reduction(void * invec, void *inoutvec, int *len, MPI_Datatype *datatype) {\n\tMatProfSOA* inout = static_cast<MatProfSOA*>(inoutvec);\n\tconst MatProfSOA* const in2 = static_cast<const MatProfSOA* const>(invec);\n\n\tEXEC_TRACE(\"reducing a MatProfSOA!\");\n\t// retrieve the profile length: This is equal to the block length of the datastructure, not the length specified in the reduction!\n\tint num_int, num_add, num_dtype, combiner;\n\tMPI_Type_get_envelope(*datatype, &num_int, &num_add ,&num_dtype, &combiner);\n\n\tif (num_int>3 || num_add>3 || num_dtype >3){\n\t\tEXEC_ERROR(\"Invalid dataype sizes retrieved: num_i \" << num_int\n\t\t           << \" num_add \" << num_add\n\t\t           << \" num_dtype \" << num_dtype\n\t\t           << \"aborting as buffers are too small\");\n\t\tMPI_Abort(MPI_COMM_WORLD, 1);\n\t}\n\n\tint blocklens[3];\n\tMPI_Aint addresses[3];\n\tMPI_Datatype dtypes[3];\n\tMPI_Type_get_contents(*datatype, num_int, num_add, num_dtype, blocklens, addresses, dtypes);\n\n\tEXEC_DEBUG(\"reduction with len \" << *len << \" and blocklen \" << blocklens[1] <<\", \" << blocklens[2]);\n\tassert(blocklens[1] == blocklens[2]);\n\tassert(*len == 1); // only reduction with size 1 is supported: Otherwise strides between SOAs needed to be considered....\n\n\t//\"shortcuts\" for coding convenience\n\ttsa_dtype* inoutprof = inout->profile.data();\n\tidx_dtype* inout_idx = inout->index.data();\n\tconst tsa_dtype* const in2_prof = in2->profile.data();\n\tconst idx_dtype* const in2_idx = in2->index.data();\n\n\t//finally the reduction\n\tconst idx_dtype limit = blocklens[1]; // avoid unnecessary reads\n\tfor (idx_dtype i = 0; i < limit; ++i) {\n\t\tif (in2_prof[i] < inoutprof[i]) {\n\t\t\tinoutprof[i] = in2_prof[i];\n\t\t\tinout_idx[i] = in2_idx[i];\n\t\t}\n\t}\n}\n\nvoid ScrimpTrivialPar::eval_diagonal_block(MatProfSOA& result,\n           const int blocklen,\n           const aligned_tsdtype_vec& A,\n           aligned_tsdtype_vec& initial_zs,\n           const int windowSize,\n           const aligned_tsdtype_vec& ASigmaInv,\n           const aligned_tsdtype_vec& AMeanScaledSigSqrM,\n           const int base_diag\n           )\n{\nEXEC_TRACE(\"evaluate block of diagonals: first \" << base_diag << \" last \" << base_diag+blocklen-1);\n    const int profileLength = AMeanScaledSigSqrM.size();\n\teval_diag_block_triangle(\n\t            result.profile.data(),\n\t            result.index.data(),\n\t            result.profile.data()+base_diag,\n\t            result.index.data()+base_diag,\n\t            initial_zs.data()+base_diag,\n\t            blocklen,\n\t            profileLength-base_diag,\n\t            A.data(),\n\t            A.data()+base_diag,\n\t            windowSize,\n\t            ASigmaInv.data(),\n\t            AMeanScaledSigSqrM.data(),\n\t            ASigmaInv.data()+base_diag,\n\t            AMeanScaledSigSqrM.data()+base_diag,\n\t            base_diag,\n\t            0\n\t    );\n}\n\nvoid ScrimpTrivialPar::compute_matrix_profile(const Scrimppp_params& params) {\n\tTIMEPOINT( tstart );\n\taligned_tsdtype_vec A = fetch_time_series<aligned_tsdtype_vec::allocator_type>(params); //load the time series data\n\tTIMEPOINT( tfileread );\n\taligned_tsdtype_vec AMean(A.size());\n\taligned_tsdtype_vec ASigma(A.size());\n\taligned_tsdtype_vec dotproducts(A.size());\n\tidx_dtype windowSize = params.query_window_len;\n\tidx_dtype exclusionZone = windowSize / 4;\n\tidx_dtype timeSeriesLength = A.size();\n\tidx_dtype profile_length = timeSeriesLength - windowSize + 1;\n\tauto result = make_aligned<MatProfSOA>();\n\tconst int BLOCKING_SIZE = params.block_length;\n\tconst bool distrib_io = (params.filetype == Scrimppp_params::BIN) && params.use_distributed_io;\n\n\tif (params.filetype != Scrimppp_params::BIN && params.use_distributed_io) {\n\t\tEXEC_ERROR(\"distributed I/O is NOT supported with ASCII files. Falling back to master I/O!\");\n\t}\n\n\t// code instrumentaion (if enabled)\n\tPerfCounters ctrs_diaginit(\"diagonal initialization\");\n\tPerfCounters ctrs_eval(\"block evaluations\");\n\tPerfCounters ctrs_mpi_comm(\"MPI communication\");\n\n\t//Initialize Matrix Profile and Matrix Profile Index\n\tresult->profile.fill(-1.0);\n\tresult->index.fill(-1);\n\n\tint world_size;\n\tint world_rank;\n\tMPI_Datatype mpi_result_type;\n\tMPI_Op reduction_op;\n\tMPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\tMPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n\n\n\n\tif (profile_length > RESULT_ALLOC_LEN) { // check, whether the data fit into the preallocated result storage\n\t\tthrow std::runtime_error(\"resulting profile length EXCEEDS MAXIMUM LENGTH. Recompile with different allocation size or choose a smaller problem\");\n\t}\n\telse if(profile_length<=0) {\n\t\tthrow std::runtime_error(\"parameters chosen badly: resulting matrix profile of length 0. done.\");\n\t}\n\n\t//create the MPI dataype for the result\n\tconst int blocklen[] = {static_cast<int>(profile_length),static_cast<int>(profile_length)};\n\tconst MPI_Aint disps[] = {(MPI_Aint)((size_t)((result->profile).data()) - (size_t)(result.get())),\n\t                          (MPI_Aint)((size_t)((result->index).data()) - (size_t)(result.get())) };\n\t//assertion for DOUBLE usage!!! TODO employ some preprocessor or tempalte magic...\n\tstatic_assert(sizeof(tsa_dtype) == sizeof(double), \"NO FLOAT POSSIBLE without modifing MPI Datatype!\" );\n\tstatic_assert(std::is_same<idx_dtype, long>::value, \"Mismatch between idx_dtype and respective mpi type MPI_LONG\" );\n\tconst MPI_Datatype dtypes[] = {MPI_DOUBLE, MPI_LONG};\n\tMPI_Type_create_struct(2, blocklen, disps, dtypes, &mpi_result_type);\n\tMPI_Type_commit(&mpi_result_type);\n\n\t//create the reduction operation for the custom datatype\n\tMPI_Op_create(MPI_MatProfSOA_reduction, 1, &reduction_op);\n\n\t// values regarding work partitioning\n\tconst int num_partitions = 2*world_size; //number of partitions. 2 partitions per process for the sake of balancing\n\tconst int diags_to_process_world = profile_length-exclusionZone-1; //total number of diagonals in the \"adjacency\" matrix to process\n\t// likely the partitions can not be of exactly even size. We assume the first ones to be of partition_size_full_load and the remaining ones to be one element smaller\n\tconst PartitioningInfo partinfo = {\n\t    ._num_partitions = 2*world_size,\n\t    ._num_partitions_full_load = diags_to_process_world - ((diags_to_process_world/num_partitions) * num_partitions),\n\t    ._size_full_load = (diags_to_process_world/num_partitions) + 1\n\t};\n\n\t/*const bool proc_has_reduced_load = world_rank<num_reduced_load;\n\tconst int diags_to_process_proc = (proc_has_reduced_load?diags_to_process_reduced_load:diags_to_process_full_load);\n\tconst int proc_offset = (proc_has_reduced_load? world_rank*diags_to_process_reduced_load\n\t\t\t\t\t\t\t\t\t\t\t\t\t: diags_to_process_reduced_load*num_reduced_load\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+diags_to_process_full_load*(world_rank-num_reduced_load));*/\n\n\t// retrieve the local partitions: each process gets 2. A \"long\" one in the upper half of the triangle and a \"short\" one in the lower half of the triangle\n\tstd::vector<DiagPartition> local_partitions;\n\t    // the upper partition is the \"process-rank\"-th one\n\tDiagPartition part_offsets = get_partition(world_rank, partinfo);\n//NOTE: causes a integer conversion warning. It is not of interest, as using more than MAX_INT diagonals is far beyond the memory limit of a single node (currently)\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(profile_length-1, exclusionZone+1+part_offsets._last_id)} );\n\tpart_offsets = get_partition(num_partitions-world_rank-1, partinfo);\n//NOTE: causes a integer conversion warning. It is not of interest, as using more than MAX_INT diagonals is far beyond the memory limit of a single node\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(profile_length-1, exclusionZone+1+part_offsets._last_id)} );\n\n\t//sum up, how many diags the local proc has to evaluate\n\tint diags_to_process_proc = 0;\n\tfor (auto partit = local_partitions.begin(); partit < local_partitions.end(); ++partit) {\n\t\tdiags_to_process_proc += partit->_last_id - partit->_first_id +1;\n\t}\n\n#ifndef NDEBUG\n\t// sum up over all processes\n\tint num_processed_diags = 0;\n\tMPI_Reduce(&diags_to_process_proc, &num_processed_diags, 1, MPI_INTEGER, MPI_SUM, 0, MPI_COMM_WORLD);\n\tif (world_rank == 0) {\n\t\tBOOST_ASSERT_MSG(num_processed_diags==diags_to_process_world, \"work partitioning of the diagonals is ivalid\");\n\t}\n\tEXEC_INFO(\"partitioning is fine!\");\n#endif\n\n//\tEXEC_INFO(\"Processing all the matrix profile!\");\n//\tlocal_partitions.clear();\n//\tlocal_partitions.push_back( {exclusionZone+1, ProfileLength-1} );\n/*\n\tconst int tmprank=0;\n\tEXEC_INFO(\"Processing the rank\" << tmprank << \" partition of the matrix profile!\");\n\tlocal_partitions.clear();\n\tpart_offsets = get_partition(tmprank, partinfo);\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(ProfileLength-1, exclusionZone+1+part_offsets._last_id)} );\n\tpart_offsets = get_partition(num_partitions-tmprank-1, partinfo);\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(ProfileLength-1, exclusionZone+1+part_offsets._last_id)} );\n*/\n\n\t//validation of parameters\n\tif (timeSeriesLength < windowSize) {\n\t\tthrow std::invalid_argument(\"ERROR: Time series is shorter than the window length, can not proceed\");\n\t}\n\n\tTIMEPOINT( tsetup );\n\n\t//precompute the mean and standard deviations of the sliding windows along the time series\n\tprecompute_window_statistics(windowSize, A, profile_length, AMean, ASigma);\n\n\t//start time measurment\n\tTIMEPOINT( tprecomputations );\n\n\t// randomly shuffle the comutation order of diagonal blocks (according to the blocking size).\n\t// In order to do so split the local partition into blocks and shuffle them.\n\tstd::vector<DiagPartition> eval_blocks;\n\teval_blocks.reserve((diags_to_process_proc/BLOCKING_SIZE) +1);\n\n\tfor (auto partit = local_partitions.begin(); partit < local_partitions.end(); ++partit) {\n\t\t    // split the partitions into block which preserve cache locality\n\t\tconst int partlen = partit->_last_id - partit->_first_id;\n\t\tconst int num_prolonged_blocks = std::max(partlen % BLOCKING_SIZE, partlen/BLOCKING_SIZE) ;\n\t\tint prev_block_end = partit->_first_id-1;\n\n\t\tEXEC_TRACE(\"splitting into blocks a partition with start: \" << partit->_first_id << \" and last: \" << partit->_last_id);\n\n\t\tfor ( int blocki = 0; prev_block_end < partit->_last_id; ++blocki) {\n\t\t\tDiagPartition part;\n\t\t\tpart._first_id = prev_block_end+1;\n\t\t\tif (blocki < num_prolonged_blocks) {\n\t\t\t\tpart._last_id = std::min(part._first_id + BLOCKING_SIZE-1, partit->_last_id);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpart._last_id = std::min(part._first_id+BLOCKING_SIZE-1, partit->_last_id);\n\t\t\t}\n\t\t\teval_blocks.push_back( part );\n\t\t\tprev_block_end = part._last_id;\n\n\t\t\t{\n\t\t\t\tconst ScopedPerfAccumulator monitor(ctrs_diaginit);\n\t\t\t\tinit_diagonals(part._first_id, part._last_id, dotproducts, A, windowSize);\n\t\t\t}\n\t\t}\n\t}\n\t//std::random_shuffle(eval_blocks.begin(), eval_blocks.end());\n\n\tTIMEPOINT( tpartitioning )\n\tEXEC_DEBUG( \"Proc \" << world_rank << \" shall process \" << diags_to_process_proc << \" diagonals\");\n\n\t//init_all_diagonals(dotproducts, A, windowSize);\n\n\t//iteratively evaluate the diagonals of the distance matrix\n\tint progressctr=0;\n\tint next_notification_thresh = notification_interval_iter;\n\tfor (auto blockiter = eval_blocks.begin(); blockiter < eval_blocks.end(); ++blockiter) {\n\t\tconst int blocklen = blockiter->_last_id +1 - blockiter->_first_id;\n\n\t\t// compute distance of the first entry for each entry in the block\n\n\t\t    // might be more efficient, if performed with MASS for ech partition (when splitting them up into blocks)\n\n\n\t\tEXEC_DEBUG(\"Rank \" << world_rank << \" evaluating diags \" << blockiter->_first_id << \" to \" << blockiter->_last_id);\n\t\t{\n\t\t\tconst ScopedPerfAccumulator monitor(ctrs_eval);\n\t\t\teval_diagonal_block(*result, blocklen, A, dotproducts, windowSize,  ASigma, AMean, blockiter->_first_id);\n\t\t\tprogressctr+=blocklen;\n\t\t}\n\t\t//Show time per 10000 iterations\n\t\tif (progressctr > next_notification_thresh && false) //disable in or der for the logging not to disturb the timing\n\t\t{\n\t\t\tconst auto tcur = get_cur_time();\n\t\t\tmatrix_profile::Timespan time_elapsed = tcur - tpartitioning;\n\t\t\tEXEC_INFO (\"finished \" << progressctr << \" iterations in: \" << std::setprecision(4) << time_elapsed);\n\t\t\tnext_notification_thresh += notification_interval_iter;\n\t\t}\n\t}\n\n\tTIMEPOINT( tevaluations)\n\tEXEC_DEBUG(\"apply transformation from score to distance values\")\n\t// apply a correction of the distance values, as we dropped a factor of 2 to avoid unnecessary computations\n\ttsa_dtype twice_m = 2.0*static_cast<tsa_dtype>(windowSize);\n\tauto profile = (result->profile).data();\n\tfor (int i = 0; i<=profile_length; ++i) {\n\t\tprofile[i] = twice_m - 2.0 * profile[i];\n\t}\n\tTIMEPOINT( tpostprocessing)\n\t{\n\t\tconst ScopedPerfAccumulator monitor(ctrs_mpi_comm);\n\t\tEXEC_DEBUG(\"reduce the processes individual results\")\n\t\t//update matrix profile and matrix profile index if the current distance value is smaller\n\t\tif (distrib_io) { //distributed I/O => everyone needs the result => Allreduce\n\t\t\t// actually only a fraction is required: the partition which will be written. That would require several reductions (one for each partition), where the receiver is the process responsible for the partition...\n\t\t\tMPI_Allreduce(MPI_IN_PLACE, result.get(), 1, mpi_result_type, reduction_op, MPI_COMM_WORLD); // in case of distributed binary I/O everyone needs the result\n\t\t}\n\t\telse { // reduction into master only, in case it is the only one writing...\n\t\t\tif (world_rank != 0) {\n\t\t\t\tMPI_Reduce(result.get(), result.get(), 1, mpi_result_type, reduction_op, 0, MPI_COMM_WORLD); // Reduction of length 1, as the datatype is defined as ProfileLength!\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMPI_Reduce(MPI_IN_PLACE, result.get(), 1, mpi_result_type, reduction_op, 0, MPI_COMM_WORLD); // Reduction of length 1, as the datatype is defined as ProfileLength!\n\t\t\t}\n\t\t}\n\t\tEXEC_DEBUG( \"rank \" << world_rank << \" done with reduction\");\n\t}\n\n\tTIMEPOINT( tcommunication)\n\t// MPI_Barrier(MPI_COMM_WORLD); //just for \"debugging\"\n\n\t//store the result\n\tif (world_rank == 0 || distrib_io ){ // storing in parallel if BIN type specified...\n\t\tEXEC_DEBUG(\"Rank \" << world_rank << \"storing the result\");\n\t\tstore_matrix_profile(*result, params, profile_length, distrib_io);\n\t}\n\n\tTIMEPOINT( tfilewrite )\n\n\t// MPI cleanup\n\tMPI_Op_free(&reduction_op);\n\tMPI_Type_free(&mpi_result_type);\n\n\tTIMEPOINT( tmpiclean)\n\n\t_timing_info.dotproduct_time = (tpartitioning-tprecomputations);\n\t_timing_info.setup_time = (tsetup-tfileread) + (tmpiclean-tfilewrite);\n\t_timing_info.comm_time = (tcommunication-tpostprocessing) ;\n\t_timing_info.evaluation_time = tevaluations-tpartitioning;\n\t_timing_info.precomp_time = tprecomputations-tsetup;\n\t_timing_info.comp_time = _timing_info.evaluation_time + _timing_info.dotproduct_time +_timing_info.precomp_time + (tpostprocessing-tevaluations);\n\t_timing_info.work_time = _timing_info.comp_time + _timing_info.comm_time + _timing_info.setup_time;\n\t_timing_info.io_time = (tfileread - tstart) + (tfilewrite-tcommunication);\n\n#define STORE_TIME_TRACE( timer, description ) _timing_info._time_trace_map.insert( TracepointMap::value_type(description, timer));\n\tSTORE_TIME_TRACE( tstart, \"start\");\n\tSTORE_TIME_TRACE( tfileread, \"fileread\");\n\tSTORE_TIME_TRACE( tsetup, \"setup\");\n\tSTORE_TIME_TRACE( tprecomputations, \"precomputations\");\n\tSTORE_TIME_TRACE( tpartitioning, \"partitioning\");\n\tSTORE_TIME_TRACE( tevaluations, \"matrix_eval\");\n\tSTORE_TIME_TRACE( tpostprocessing, \"postprocessing\");\n\tSTORE_TIME_TRACE( tcommunication, \"communication\");\n\tSTORE_TIME_TRACE( tfilewrite, \"filwrite\");\n\tSTORE_TIME_TRACE( tmpiclean, \"mpi_cleanup\");\n\n\tctrs_diaginit.log_perf();\n\tctrs_eval.log_perf();\n\tctrs_mpi_comm.log_perf();\n\n\t_log_info.profile_length = profile_length;\n\t_log_info.windowSize = windowSize;\n\t_log_info.exclusionZone =  exclusionZone;\n\t_log_info.timeSeriesLength = timeSeriesLength;\n\t_log_info.world_size = world_size;\n\t_log_info.world_rank = world_rank;\n\t_log_info.BLOCKING_SIZE = BLOCKING_SIZE;\n\t_log_info.diags_to_process_proc = diags_to_process_proc;\n}\n\nvoid ScrimpTrivialPar::store_matrix_profile(const MatProfSOA& result, const Scrimppp_params& params, const idx_dtype profileLength, const bool distributed_io)\n{\n\tScrimpSequ::store_matrix_profile(result.profile.data(), result.index.data(), profileLength, params, distributed_io);\n}\n\nvoid ScrimpTrivialPar::log_info() {\n\tEXEC_INFO( \"MPI INFO: comm size: \" << _log_info.world_size << \" world rank: \" << _log_info.world_rank);\n\tEXEC_INFO( \"Blocking size: \" << _log_info.BLOCKING_SIZE)\n    #ifdef PROFILING\n\t    PERF_LOG(\"number of matrix profile updates: \" << _profile_updates);\n\t    PERF_LOG(\"number of evaluations: \" << _eval_ctr);\n    #endif\n\n\t// log computation performance\n\tconst double triang_len = _log_info.profile_length-_log_info.exclusionZone;\n\tauto timerprecision = std::numeric_limits<tsa_dtype>::digits10 + 2;\n\tPERF_LOG ( \"evaluation time: \" << std::setprecision(timerprecision) << _timing_info.evaluation_time);\n\tPERF_LOG ( \"local comp time (eval+precomp): \" << std::setprecision(timerprecision) << _timing_info.comp_time );\n\tPERF_LOG ( \"communication time: \" << std::setprecision(timerprecision) << _timing_info.comm_time );\n\tPERF_LOG ( \"local working time: \" << std::setprecision(timerprecision) << _timing_info.work_time );\n\tPERF_LOG ( \"I/O time: \" << std::setprecision(timerprecision) << _timing_info.io_time );\n\tPERF_LOG ( \"dotproduct time: \" << _timing_info.dotproduct_time );\n\n\tPERF_LOG ( \"local throughput evaluations: \" << std::setprecision(6) << _log_info.diags_to_process_proc * triang_len / get_seconds(_timing_info.evaluation_time) << \" matrix entries/second\" );\n\tPERF_LOG ( \"throughput evaluations: \" << std::setprecision(6) << triang_len * triang_len / get_seconds(_timing_info.evaluation_time) << \" matrix entries/second (estimate based on local)\" );\n\tPERF_LOG ( \"local throughput computations: \" << std::setprecision(6) << _log_info.diags_to_process_proc * triang_len / get_seconds(_timing_info.comp_time) << \" matrix entries/second\" );\n\tPERF_LOG ( \"throughput computations: \" << std::setprecision(6) << triang_len * triang_len / get_seconds(_timing_info.comp_time) << \" matrix entries/second (estimate based on local)\" );\n\n\tfor (auto iter = _timing_info._time_trace_map.begin(); iter != _timing_info._time_trace_map.end(); ++iter) {\n\t\tPERF_TRACE ( \"timepoint after \" << iter->first << \": \" << iter->second );\n\t}\n\n\tfor (auto iter = _timing_info._synctime_map.begin(); iter != _timing_info._synctime_map.end(); ++iter) {\n\t\tPERF_LOG(\" sync time \" << iter->first << \": \" << iter->second);\n\t}\n}\n", "meta": {"hexsha": "9e44bce5c12234b9a0086e78aceaa2093fe2a714", "size": 20088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimppp/src/ScrimpTrivialPar.cpp", "max_stars_repo_name": "franzbischoff/ThesisCode", "max_stars_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T22:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:14:16.000Z", "max_issues_repo_path": "scrimppp/src/ScrimpTrivialPar.cpp", "max_issues_repo_name": "franzbischoff/ThesisCode", "max_issues_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scrimppp/src/ScrimpTrivialPar.cpp", "max_forks_repo_name": "franzbischoff/ThesisCode", "max_forks_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-20T22:41:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T09:15:48.000Z", "avg_line_length": 44.7394209354, "max_line_length": 211, "alphanum_fraction": 0.7411389885, "num_tokens": 5148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.036769467922763914, "lm_q1q2_score": 0.017237181908226065}}
{"text": "/*\n * Copyright (c) 2013-, Stephen Miller\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, \n * with or without modification, are permitted provided \n * that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the \n * above copyright notice, this list of conditions \n * and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the \n * above copyright notice, this list of conditions and \n * the following disclaimer in the documentation and/or \n * other materials provided with the distribution.\n * \n * 3. Neither the name of the copyright holder nor the \n * names of its contributors may be used to endorse or\n * promote products derived from this software without \n * specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS \n * AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED \n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A \n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL \n * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER \n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING \n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n\n#include <cpu_tsdf/octree.h>\n#include <pcl/console/print.h>\n#include <pcl/console/time.h>\n#include <pcl/pcl_macros.h>\n#include <boost/shared_ptr.hpp>\n#include <vector>\n#include <stdint.h>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\nvoid\ncpu_tsdf::OctreeNode::getCenter (float &x, float &y, float &z) const\n{\n  x = ctr_x_;\n  y = ctr_y_;\n  z = ctr_z_;\n};\n\nvoid\ncpu_tsdf::OctreeNode::getSize (float &size_x, float &size_y, float &size_z) const\n{\n  size_x = size_;\n  size_y = size_;\n  size_z = size_;\n}\n\nfloat\ncpu_tsdf::OctreeNode::getMaxSize () const\n{\n  return (std::sqrt (3) * size_);\n}\n\nfloat\ncpu_tsdf::OctreeNode::getMinSize () const\n{\n  return (size_);\n}\n\nbool\ncpu_tsdf::OctreeNode::hasChildren () const\n{\n  return (!children_.empty ());\n}\n\nstd::vector<cpu_tsdf::OctreeNode::Ptr>&\ncpu_tsdf::OctreeNode::getChildren ()\n{\n  return children_;\n}\n\nconst std::vector<cpu_tsdf::OctreeNode::Ptr>&\ncpu_tsdf::OctreeNode::getChildren () const\n{\n  return children_;\n}\n\nvoid\ncpu_tsdf::OctreeNode::getLeaves (std::vector<cpu_tsdf::OctreeNode::Ptr> &leaves, int num_levels)\n{\n  for (size_t i = 0; i < children_.size (); i++)\n  {\n    const OctreeNode::Ptr &child = children_[i];\n    if (child->hasChildren () && num_levels != 0)\n      child->getLeaves (leaves, num_levels - 1);\n    else\n      leaves.push_back (child);\n  }\n}\n\n// Get the voxel which contains this point\ncpu_tsdf::OctreeNode*\ncpu_tsdf::OctreeNode::getContainingVoxel (float x, float y, float z, float min_size)\n{\n  if (!hasChildren () || (min_size > 0 && size_ <= min_size))\n    return (this);\n  else\n  {\n    return children_[((x-ctr_x_) > 0) * 4 + ((y-ctr_y_) > 0) * 2 + (z - ctr_z_ > 0)]->getContainingVoxel (x, y, z, min_size);\n  }\n}\n\n// Get the voxel which contains this point\nconst cpu_tsdf::OctreeNode*\ncpu_tsdf::OctreeNode::getContainingVoxel (float x, float y, float z, float min_size) const\n{\n  if (!hasChildren () || (min_size > 0 && size_ <= min_size))\n    return (this);\n  else\n  {\n    return children_[((x-ctr_x_) > 0) * 4 + ((y-ctr_y_) > 0) * 2 + (z - ctr_z_ > 0)]->getContainingVoxel (x, y, z, min_size);\n  }\n}\n\n\nbool\ncpu_tsdf::OctreeNode::getData (float &d, float &w) const\n{\n  d = d_;\n  w = w_;\n  return (true);\n}\n\nbool\ncpu_tsdf::OctreeNode::setData (float d, float w)\n{\n  d_ = d;\n  w_ = w;\n  return (true);\n}\n\nbool\ncpu_tsdf::OctreeNode::addObservation (float d_new, float w_new, float max_weight)\n{\n  float d_old = d_;\n  d_ = (d_ * w_ + d_new * w_new) / (w_ + w_new);\n  w_ += w_new;\n  if (w_ > max_weight)\n    w_ = max_weight;\n  M_ += w_new * (d_new - d_) * (d_new - d_old);\n  ++nsample_;\n  return (true);\n}\n\n\nbool\ncpu_tsdf::OctreeNode::addObservation (float d_new, float w_new, float max_weight, \n                uint8_t r, uint8_t g, uint8_t b)\n{\n  return (addObservation (d_new, w_new, max_weight));\n}\n\nbool\ncpu_tsdf::OctreeNode::getRGB (uint8_t &r, uint8_t &g, uint8_t &b) const\n{\n  r = g = b = 127;\n  return (false);\n}\n\ncpu_tsdf::OctreeNode*\ncpu_tsdf::OctreeNode::instantiateNode (float x, float y, float z, float sx, float sy, float sz)\n{\n  return (new OctreeNode (x, y, z, sx, sy, sz));\n}\n\nstd::string\ncpu_tsdf::OctreeNode::getTypeString ()\n{\n  return (\"NOCOLOR\");\n}\n\ncpu_tsdf::OctreeNode*\ncpu_tsdf::OctreeNode::instantiateByTypeString (const std::string &str)\n{\n  if (str == \"NOCOLOR\")\n    return (new OctreeNode);\n  else if (str == \"RGB\")\n    return (new RGBNode);\n  else if (str == \"RGBNormalized\")\n    return (new RGBNormalized);\n  else if (str == \"LAB\")\n    return (new LABNode);\n  // Handle more examples\n  PCL_ERROR (\"[cpu_tsdf::OctreeNode::instantiateByTypeString] Requested invalid type string %s\\n\", str.c_str ());\n  return (NULL);\n}\n\ncpu_tsdf::OctreeNode*\ncpu_tsdf::OctreeNode::instantiateByTypeString (const std::string &str, \n                         float x, float y, float z, float sx, float sy, float sz)\n{\n  cpu_tsdf::OctreeNode* empty_node = instantiateByTypeString (str);\n  cpu_tsdf::OctreeNode* node = empty_node->instantiateNode (x, y, z, sx, sy, sz);\n  delete empty_node;\n  return (node);\n}\n\nvoid\ncpu_tsdf::OctreeNode::updateAverage ()\n{\n  if (children_.empty ())\n    return;\n\n  float d_avg = 0;\n  float w_avg = 0;\n  int ngood = 0;\n  for (size_t i = 0; i < children_.size (); ++i)\n  {\n    children_[i]->updateAverage ();\n    if (children_[i]->w_ > 0)\n    {\n      d_avg += children_[i]->d_;\n      w_avg += children_[i]->w_;\n      ++ngood;\n    }\n  }\n  if (ngood > 0)\n  {\n    d_ = d_avg/ngood;\n    w_ = w_avg/ngood;\n  }\n}\n\nstd::vector<cpu_tsdf::OctreeNode::Ptr>& \ncpu_tsdf::OctreeNode::split ()\n{\n  children_.resize (8);\n  //float off_x = size_x_ / 4;\n  //float off_y = size_y_ / 4;\n  //float off_z = size_z_ / 4;\n  float off_x = size_ / 4;\n  float off_y = size_ / 4;\n  float off_z = size_ / 4;\n  float newsize_x = size_ / 2;\n  float newsize_y = size_ / 2;\n  float newsize_z = size_ / 2;\n  children_[0].reset (instantiateNode (ctr_x_-off_x, ctr_y_-off_y, ctr_z_-off_z, newsize_x, newsize_y, newsize_z));\n  children_[1].reset (instantiateNode (ctr_x_-off_x, ctr_y_-off_y, ctr_z_+off_z, newsize_x, newsize_y, newsize_z));\n  children_[2].reset (instantiateNode (ctr_x_-off_x, ctr_y_+off_y, ctr_z_-off_z, newsize_x, newsize_y, newsize_z));\n  children_[3].reset (instantiateNode (ctr_x_-off_x, ctr_y_+off_y, ctr_z_+off_z, newsize_x, newsize_y, newsize_z));\n  children_[4].reset (instantiateNode (ctr_x_+off_x, ctr_y_-off_y, ctr_z_-off_z, newsize_x, newsize_y, newsize_z));\n  children_[5].reset (instantiateNode (ctr_x_+off_x, ctr_y_-off_y, ctr_z_+off_z, newsize_x, newsize_y, newsize_z));\n  children_[6].reset (instantiateNode (ctr_x_+off_x, ctr_y_+off_y, ctr_z_-off_z, newsize_x, newsize_y, newsize_z));\n  children_[7].reset (instantiateNode (ctr_x_+off_x, ctr_y_+off_y, ctr_z_+off_z, newsize_x, newsize_y, newsize_z));\n  return (children_);\n}\n\n\nvoid\ncpu_tsdf::OctreeNode::splitRecursive (int num_left)\n{\n  if (num_left <= 0)\n    return;\n  split ();\n  for (size_t i = 0; i < children_.size (); i++)\n  {\n    children_[i]->splitRecursive (num_left-1);\n  }\n}\n\nfloat\ncpu_tsdf::OctreeNode::getVariance () const\n{\n  if (nsample_ < 5)\n    return (std::numeric_limits<float>::infinity ());\n  return ((M_/w_)*(nsample_/(nsample_-1)));\n}\n\nvoid\ncpu_tsdf::OctreeNode::serialize (std::ostream &f) const\n{\n  f.write ((char*)&d_, sizeof (float));\n  f.write ((char*)&w_, sizeof (float));\n  f.write ((char*)&ctr_x_, sizeof (float));\n  f.write ((char*)&ctr_y_, sizeof (float));\n  f.write ((char*)&ctr_z_, sizeof (float));\n  f.write ((char*)&size_, sizeof (float));\n  f.write ((char*)&M_, sizeof (float));\n  f.write ((char*)&nsample_, sizeof (int));\n  size_t nchild = children_.size ();\n  f.write ((char*)&nchild, sizeof (size_t));\n  for (size_t i = 0; i < nchild; ++i)\n    children_[i]->serialize (f);\n}\n\nvoid\ncpu_tsdf::OctreeNode::deserialize (std::istream &f)\n{\n  f.read ((char*)&d_, sizeof (float));\n  f.read ((char*)&w_, sizeof (float));\n  f.read ((char*)&ctr_x_, sizeof (float));\n  f.read ((char*)&ctr_y_, sizeof (float));\n  f.read ((char*)&ctr_z_, sizeof (float));\n  f.read ((char*)&size_, sizeof (float));\n  f.read ((char*)&M_, sizeof (float));\n  f.read ((char*)&nsample_, sizeof (int));\n  size_t nchild;\n  f.read ((char*)&nchild, sizeof (size_t));\n  children_.resize (nchild);\n  for (size_t i = 0; i < nchild; ++i)\n  {\n    children_[i].reset (instantiateNode (0, 0, 0, 0, 0, 0));\n    children_[i]->deserialize (f);\n  }\n}\n\n// RGBNode\nbool\ncpu_tsdf::RGBNode::addObservation (float d_new, float w_new, float max_weight, \n                uint8_t r, uint8_t g, uint8_t b)\n{\n  float wsum = w_ + w_new;\n  r_ = static_cast<uint8_t> ( (w_*r_ + w_new*r) / wsum);\n  g_ = static_cast<uint8_t> ( (w_*g_ + w_new*g) / wsum);\n  b_ = static_cast<uint8_t> ( (w_*b_ + w_new*b) / wsum);\n  return (OctreeNode::addObservation (d_new, w_new, max_weight));\n}\n\nbool\ncpu_tsdf::RGBNode::getRGB (uint8_t &r, uint8_t &g, uint8_t &b) const\n{\n  r = r_;\n  g = g_;\n  b = b_;\n  return (true);\n}\n\ncpu_tsdf::OctreeNode*\ncpu_tsdf::RGBNode::instantiateNode (float x, float y, float z, float sx, float sy, float sz)\n{\n  return (new RGBNode (x, y, z, sx, sy, sz));\n}\n\nstd::string\ncpu_tsdf::RGBNode::getTypeString ()\n{\n  return (\"RGB\");\n}\n\nvoid\ncpu_tsdf::RGBNode::serialize (std::ostream &f) const\n{\n  f.write ((char*)&r_, sizeof (uint8_t));\n  f.write ((char*)&g_, sizeof (uint8_t));\n  f.write ((char*)&b_, sizeof (uint8_t));\n  OctreeNode::serialize (f);\n}\n\nvoid\ncpu_tsdf::RGBNode::deserialize (std::istream &f)\n{\n  f.read ((char*)&r_, sizeof (uint8_t));\n  f.read ((char*)&g_, sizeof (uint8_t));\n  f.read ((char*)&b_, sizeof (uint8_t));\n  OctreeNode::deserialize (f);\n}\n\n// RGBNormalized\nbool\ncpu_tsdf::RGBNormalized::addObservation (float d_new, float w_new, float max_weight, \n                uint8_t r, uint8_t g, uint8_t b)\n{\n  float wsum = w_ + w_new;\n  float i = std::sqrt ((float)r * (float)r + (float)g*(float)g + (float)b*(float)b);\n  float r_f = r / i;\n  float g_f = g / i;\n  float b_f = b / i;\n  r_n_ = (w_*r_n_ + w_new*r_f) / wsum;\n  g_n_ = (w_*g_n_ + w_new*g_f) / wsum;\n  b_n_ = (w_*b_n_ + w_new*b_f) / wsum;\n  i_ = (w_*i_ + w_new*i) / wsum;\n  return (OctreeNode::addObservation (d_new, w_new, max_weight));\n}\n\nbool\ncpu_tsdf::RGBNormalized::getRGB (uint8_t &r, uint8_t &g, uint8_t &b) const\n{\n  r = r_n_ * i_;\n  g = g_n_ * i_;\n  b = b_n_ * i_;\n  return (true);\n}\n\ncpu_tsdf::OctreeNode*\ncpu_tsdf::RGBNormalized::instantiateNode (float x, float y, float z, float sx, float sy, float sz)\n{\n  return (new RGBNormalized (x, y, z, sx, sy, sz));\n}\n\nstd::string\ncpu_tsdf::RGBNormalized::getTypeString ()\n{\n  return (\"RGBNormalized\");\n}\n\nvoid\ncpu_tsdf::RGBNormalized::serialize (std::ostream &f) const\n{\n  f.write ((char*)&r_n_, sizeof (uint8_t));\n  f.write ((char*)&g_n_, sizeof (uint8_t));\n  f.write ((char*)&b_n_, sizeof (uint8_t));\n  f.write ((char*)&i_, sizeof (uint8_t));\n  OctreeNode::serialize (f);\n}\n\nvoid\ncpu_tsdf::RGBNormalized::deserialize (std::istream &f)\n{\n  f.read ((char*)&r_n_, sizeof (uint8_t));\n  f.read ((char*)&g_n_, sizeof (uint8_t));\n  f.read ((char*)&b_n_, sizeof (uint8_t));\n  f.read ((char*)&i_, sizeof (uint8_t));\n  OctreeNode::deserialize (f);\n}\n\nvoid\ncpu_tsdf::RGB2LAB (uint8_t r, uint8_t g, uint8_t b, \n             float &L, float &A, float &B)\n{\n  // RGB to XYZ\n  float rf = (static_cast<float> (r) / 255.);\n  float gf = (static_cast<float> (g) / 255.);\n  float bf = (static_cast<float> (b) / 255.);\n  if (rf > 0.0405) \n    rf = std::pow(((rf + 0.055) / 1.055), 2.4);\n  else\n    rf /= 12.92;\n  if (gf > 0.0405) \n    gf = std::pow(((gf + 0.055) / 1.055), 2.4);\n  else\n    gf /= 12.92;\n  if (bf > 0.0405) \n    bf = std::pow(((bf + 0.055) / 1.055), 2.4);\n  else\n    bf /= 12.92;\n  rf *= 100;\n  gf *= 100;\n  bf *= 100;\n  float X = rf * 0.4124 + gf * 0.3576 + bf * 0.1805;\n  float Y = rf * 0.2126 + gf * 0.7152 + bf * 0.0722;\n  float Z = rf * 0.0193 + gf * 0.1192 + bf * 0.9505;\n  // XYZ to LAB\n  X /= 95.047;\n  Y /= 100.;\n  Z /= 108.883;\n  if (X > 0.008856)\n    X = std::pow (static_cast<double> (X), 1/3.);\n  else\n    X = 7.787 * X + (16 / 116.);\n  if (Y > 0.008856)\n    Y = std::pow (static_cast<double> (Y), 1/3.);\n  else\n    Y = 7.787 * Y + (16 / 116.);\n  if (Z > 0.008856)\n    Z = std::pow (static_cast<double> (Z), 1/3.);\n  else\n    Z = 7.787 * Z + (16 / 116.);\n  L = (116 * Y) - 16;\n  A = 500 * (X - Y);\n  B = 200 * (Y - Z);\n}\n\nvoid\ncpu_tsdf::LAB2RGB (float L, float A, float B, \n             uint8_t &r, uint8_t &g, uint8_t &b)\n{\n  // LAB to XYZ\n  float Y = (L + 16) / 116.;\n  float X = A / 500. + Y;\n  float Z = Y - (B / 200.);\n  if (std::pow (X, 3) > 0.008856)\n    X = std::pow (X, 3);\n  else\n    X = (X - 16 / 116.) / 7.787;\n  if (std::pow (Y, 3) > 0.008856)\n    Y = std::pow (Y, 3);\n  else\n    Y = (Y - 16 / 116.) / 7.787;\n  if (std::pow (Z, 3) > 0.008856)\n    Z = std::pow (Z, 3);\n  else\n    Z = (Z - 16 / 116.) / 7.787;\n  X *= 95.047;\n  Y *= 100.;\n  Z *= 108.883;\n  // XYZ to RGB\n  X /= 100;\n  Y /= 100;\n  Z /= 100;\n  float rf = X * +3.2406 + Y * -1.5372 + Z * -0.4986;\n  float gf = X * -0.9689 + Y * +1.8758 + Z * +0.0415;\n  float bf = X * +0.0557 + Y * -0.2040 + Z * +1.0570;\n  if (rf > 0.0031308)\n    rf = 1.055 * std::pow (static_cast<double> (rf), 1. / 2.4) - 0.055;\n  else\n    rf *= 12.92;\n  if (gf > 0.0031308)\n    gf = 1.055 * std::pow (static_cast<double> (gf), 1. / 2.4) - 0.055;\n  else\n    gf *= 12.92;\n  if (bf > 0.0031308)\n    bf = 1.055 * std::pow (static_cast<double> (bf), 1. / 2.4) - 0.055;\n  else\n    bf *= 12.92;\n  r = static_cast<uint8_t> (rf * 255);\n  g = static_cast<uint8_t> (gf * 255);\n  b = static_cast<uint8_t> (bf * 255);\n}\n\n// LABNode\nbool\ncpu_tsdf::LABNode::addObservation (float d_new, float w_new, float max_weight, \n                uint8_t r, uint8_t g, uint8_t b)\n{\n  float wsum = w_ + w_new;\n  float L_new, A_new, B_new;\n  RGB2LAB (r, g, b, L_new, A_new, B_new);\n  uint8_t r_reconv, g_reconv, b_reconv;\n  LAB2RGB (L_new, A_new, B_new, r_reconv, g_reconv, b_reconv);\n  L_ = (w_*L_ + w_new*L_new) / wsum;\n  A_ = (w_*A_ + w_new*A_new) / wsum;\n  B_ = (w_*B_ + w_new*B_new) / wsum;\n  return (OctreeNode::addObservation (d_new, w_new, max_weight));\n}\n\nbool\ncpu_tsdf::LABNode::getRGB (uint8_t &r, uint8_t &g, uint8_t &b) const\n{\n  LAB2RGB (L_, A_, B_, r, g, b);\n  return (true);\n}\n\ncpu_tsdf::OctreeNode*\ncpu_tsdf::LABNode::instantiateNode (float x, float y, float z, float sx, float sy, float sz)\n{\n  return (new LABNode (x, y, z, sx, sy, sz));\n}\n\nstd::string\ncpu_tsdf::LABNode::getTypeString ()\n{\n  return (\"LAB\");\n}\n\nvoid\ncpu_tsdf::LABNode::serialize (std::ostream &f) const\n{\n  f.write ((char*)&L_, sizeof (uint8_t));\n  f.write ((char*)&A_, sizeof (uint8_t));\n  f.write ((char*)&B_, sizeof (uint8_t));\n  OctreeNode::serialize (f);\n}\n\nvoid\ncpu_tsdf::LABNode::deserialize (std::istream &f)\n{\n  f.read ((char*)&L_, sizeof (uint8_t));\n  f.read ((char*)&A_, sizeof (uint8_t));\n  f.read ((char*)&B_, sizeof (uint8_t));\n  OctreeNode::deserialize (f);\n}\n\n// Octree\nvoid\ncpu_tsdf::Octree::init (int num_splits)\n{\n  // Starts with just one root node\n  root_.reset (OctreeNode::instantiateByTypeString \n      (voxel_type_, 0, 0, 0, size_x_, size_y_, size_z_));\n  root_->splitRecursive (num_splits);\n}\n\nvoid\ncpu_tsdf::Octree::init (float max_size_x, float max_size_y, float max_size_z)\n{\n  int desired_res = std::max (size_x_/max_size_x, std::max (size_y_ / max_size_y, size_z_/max_size_z));\n  int num_levels = std::ceil (std::log (desired_res) / std::log (2));\n  init (num_levels);\n}\n\ncpu_tsdf::OctreeNode::Ptr&\ncpu_tsdf::Octree::getRoot ()\n{\n  return root_;\n}\n\nvoid \ncpu_tsdf::Octree::getLeaves (std::vector<OctreeNode::Ptr> &leaves, int num_levels) const\n{\n  // Recursively find leaf nodes\n  pcl::console::TicToc tt;\n  tt.tic ();\n  if (num_levels == 0)\n    leaves.push_back (root_);\n  else\n    root_->getLeaves (leaves, num_levels-1);\n}\n\nvoid\ncpu_tsdf::Octree::getLeaves (std::vector<OctreeNode::Ptr> &leaves, float max_size_x, float max_size_y, float max_size_z) const\n{\n  int desired_res = std::max (size_x_/max_size_x, std::max (size_y_ / max_size_y, size_z_/max_size_z));\n  int num_levels = std::ceil (std::log (desired_res) / std::log (2));\n  getLeaves (leaves, num_levels);\n}\n\n// Get the voxel which contains this point\nconst cpu_tsdf::OctreeNode*\ncpu_tsdf::Octree::getContainingVoxel (float x, float y, float z, float min_size) const\n{\n  if (std::isnan (z) || std::fabs (x) > size_x_/2 || std::fabs (y) > size_y_/2 || std::fabs (z) > size_z_/2)\n    return (NULL);\n  return (root_->getContainingVoxel (x, y, z, min_size));\n}\n\n// Get the voxel which contains this point\ncpu_tsdf::OctreeNode*\ncpu_tsdf::Octree::getContainingVoxel (float x, float y, float z, float min_size)\n{\n  if (std::isnan (z) || std::fabs (x) > size_x_/2 || std::fabs (y) > size_y_/2 || std::fabs (z) > size_z_/2)\n    return (NULL);\n  return (root_->getContainingVoxel (x, y, z, min_size));\n}\n\nvoid\ncpu_tsdf::Octree::serialize (std::ostream &f) const\n{\n  f << root_->getTypeString () << std::endl;\n  f << \"#OCTREEBINARY\" << std::endl;\n  f.write ((char*)&res_x_, sizeof (size_t));\n  f.write ((char*)&res_y_, sizeof (size_t));\n  f.write ((char*)&res_z_, sizeof (size_t));\n  f.write ((char*)&size_x_, sizeof (float));\n  f.write ((char*)&size_y_, sizeof (float));\n  f.write ((char*)&size_z_, sizeof (float));\n  root_->serialize (f);\n}\n\nvoid\ncpu_tsdf::Octree::deserialize (std::istream &f)\n{\n  std::string root_type;\n  f >> root_type;\n  root_.reset (OctreeNode::instantiateByTypeString (root_type));\n  char tmp[1024];\n  do\n  {\n    f.getline (tmp, 1024);\n  }\n  while (!(tmp[0] == '#' && tmp[1] == 'O'));\n  f.read ((char*)&res_x_, sizeof (size_t));\n  f.read ((char*)&res_y_, sizeof (size_t));\n  f.read ((char*)&res_z_, sizeof (size_t));\n  f.read ((char*)&size_x_, sizeof (float));\n  f.read ((char*)&size_y_, sizeof (float));\n  f.read ((char*)&size_z_, sizeof (float));\n  root_->deserialize (f);\n}\n\n", "meta": {"hexsha": "82bf2bbf5237639caceb3ef780347740031487f1", "size": 18307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/octree.cpp", "max_stars_repo_name": "21Ansh/cpu_tsdf", "max_stars_repo_head_hexsha": "4fba28911b5f5d4015f304aa24b84b7245174a21", "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/octree.cpp", "max_issues_repo_name": "21Ansh/cpu_tsdf", "max_issues_repo_head_hexsha": "4fba28911b5f5d4015f304aa24b84b7245174a21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/octree.cpp", "max_forks_repo_name": "21Ansh/cpu_tsdf", "max_forks_repo_head_hexsha": "4fba28911b5f5d4015f304aa24b84b7245174a21", "max_forks_repo_licenses": ["BSD-3-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.9220588235, "max_line_length": 126, "alphanum_fraction": 0.6380619435, "num_tokens": 6289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.047425875028824706, "lm_q1q2_score": 0.017214132833905643}}
{"text": "//  Copyright (c) 2006, Giovanni P. Deretta\n//\n//  This code may be used under either of the following two licences:\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 \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 FROM, \n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN \n//  THE SOFTWARE. OF SUCH DAMAGE.\n//\n//  Or:\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#include <iostream>\n#include <boost/variant.hpp>\n#include <boost/variant/get.hpp>\n#include <boost/variant/recursive_variant.hpp>\n#include <boost/variant/recursive_wrapper.hpp>\n#include <boost/optional.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include <boost/mpl/deref.hpp>\n#include <boost/coroutine/generator.hpp>\n#include <boost/bind.hpp>\n#include <boost/mpl/at.hpp>\n/**\n * Solve the 'same fringe problem' using coroutines.\n * Given two binary trees, they have the same fringe\n * if all leafs, read from left to right are equals.\n * This is the classical coroutine demonstration problem,\n * because it is hard to solve in O(N) (with best case O(1)) \n * without using coroutines.\n * see http://c2.com/cgi/wiki?CoRoutine\n * NOTE: this solution is an almost verbatim port of the lua solution from\n * the wiki.\n *\n * This is a cleaned up version of samefringe.cpp. It uses generators instead\n * of corutines. The variant is much more cleaner and \n * same_fringe has been simplified.\n */\nnamespace coroutines = boost::coroutines;\nusing coroutines::generator;\n\nnamespace meta {\n  /**\n   * Compact compile-time description of binary trees of ints.\n   */\n  template<typename Left, typename Right>\n  class node{\n    typedef Left left;\n    typedef Right right;\n  };\n  \n  template<int A>\n  struct leaf {\n    enum {value = A};\n  };\n\n  typedef \n  node<node<leaf<0>, leaf<1> >, node<leaf<0>, node<leaf<5>, leaf<7> > > >\n  tree_a; // fringe: 0 1 0 5 7\n\n  typedef \n  node<leaf<0>, node<leaf<1>, node<node<leaf<0>, leaf<5> >, leaf<7> > > >\n  tree_b; // fringe: 0 1 0 5 7\n\n  typedef \n  node<leaf<1>, node<leaf<7>, node<node<leaf<5>, leaf<4> >, leaf<7> > > >\n  tree_c; // fringe: 1 7 5 4 7\n}\n\n// This is ugly, but at least on GCC it is not fount if it is in the the global \n// namespace. It could  work both in boost and in std:\n// - in std   is found through ADL from pair,\n// - in boost is found through ADL from pair's template argument \n//   (boost::variant)\n// Adding overloads in std is not portable so we fallback to the boost \n// namespace.\nnamespace boost {\n  template<typename Element>\n  std::ostream& operator<<(std::ostream& out, \n\t\t\t   const std::pair<Element, Element>& x) {\n    out << \"(\"<< x.first << \", \" << x.second<<\")\";\n    return out;\n  }\n}\n\n\ntypedef int leaf;\ntypedef boost::make_recursive_variant<leaf, \n\t\t\t\t      std::pair<boost::recursive_variant_, \n\t\t\t\t\t\tboost::recursive_variant_> \n>::type element;\ntypedef std::pair<element, element> node;\n\nbool is_leaf(const element& x) {\n  return x.which() == 0;\n}\n\n\ntemplate<typename Left, typename Right>\nelement make_tree(meta::node<Left, Right> const&) {\n  return node(make_tree(Left()), \n\t      make_tree(Right()));\n}\n\ntemplate<int A>\nelement make_tree(meta::leaf<A> const&) {\n  return leaf (A);\n}\n\ntypedef generator<leaf> generator_type;\n\nleaf\ntree_leaves(generator_type::self& self, element& tree) {\n  if (is_leaf(tree)) {\n    self.yield(boost::get<leaf>(tree));\n  } else {\n    tree_leaves(self, boost::get<node>(tree).first);\n    tree_leaves(self, boost::get<node>(tree).second);\n  }\n  self.exit();\n  return 0;\n}\n\nbool same_fringe(const element& tree1, const element& tree2) {\n  generator_type tree_leaves_a(boost::bind(tree_leaves, _1, tree1));\n  generator_type tree_leaves_b(boost::bind(tree_leaves, _1, tree2));\n  while(tree_leaves_a && tree_leaves_b) {\n    if(tree_leaves_a() != tree_leaves_b())\n      return false;\n  }\n  return true && (!tree_leaves_b && !tree_leaves_a);\n}\n\nint main() {\n  std::cout << \"fringe a: \" << make_tree(meta::tree_a()) << \"\\n\";\n  std::cout << \"fringe b: \" << make_tree(meta::tree_b()) << \"\\n\";\n  std::cout << \"frinte c: \" << make_tree(meta::tree_c()) << \"\\n\";\n  std::cout<<\"same_fringe (tree_a, tree_a) -> \"<<same_fringe\n    (make_tree(meta::tree_a()), make_tree(meta::tree_a()))<<\"\\n\";\n  std::cout<<\"same_fringe (tree_a, tree_b) -> \"<<same_fringe\n    (make_tree(meta::tree_a()), make_tree(meta::tree_b()))<<\"\\n\";\n  std::cout<<\"same_fringe (tree_a, tree_c) -> \"<<same_fringe\n    (make_tree(meta::tree_a()), make_tree(meta::tree_c()))<<\"\\n\";\n}\n", "meta": {"hexsha": "5cfd5b5a7fa97963b7550a204d9030fb1bd34664", "size": 5469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/coroutine/example/samefringe2.cpp", "max_stars_repo_name": "erikfrey/coroutine", "max_stars_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-10-19T02:52:00.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-09T09:52:25.000Z", "max_issues_repo_path": "libs/coroutine/example/samefringe2.cpp", "max_issues_repo_name": "erikfrey/coroutine", "max_issues_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/coroutine/example/samefringe2.cpp", "max_forks_repo_name": "erikfrey/coroutine", "max_forks_repo_head_hexsha": "fe1b9e12f96e320446da1ef49015955162edb17f", "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.7592592593, "max_line_length": 82, "alphanum_fraction": 0.6878771256, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.04885777602542246, "lm_q1q2_score": 0.01720779578305045}}
{"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 \"esop_post_optimization.hpp\"\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <stack>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/pending/integer_log2.hpp>\n#include <boost/range/iterator_range.hpp>\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/timer.hpp>\n\n#include <reversible/circuit.hpp>\n#include <reversible/functions/add_circuit.hpp>\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/io/print_circuit.hpp>\n#include <reversible/target_tags.hpp>\n#include <reversible/utils/costs.hpp>\n#include <reversible/variable.hpp>\n\nnamespace cirkit\n{\n\nusing edge_properties = boost::property<boost::edge_weight_t, unsigned>;\nusing mygraph = graph_t<boost::no_property, edge_properties>;\n\nstruct SimpleHash\n{\n  size_t operator()( const std::pair<unsigned, unsigned>& p ) const\n  {\n    return p.first ^ p.second;\n  }\n};\n\nstruct feature\n{\n  uint16_t control = 0u;\n  uint16_t polarity = 0u;\n\n  feature( gate& g );\n  feature();\n};\n\nstruct pair\n{\n  gate f;\n  gate s;\n  feature a;\n  feature b;\n  circuit const* c = nullptr;\n  circuit equivalent;\n\n  pair( const gate& f, const gate& s, const circuit& c, feature& a, feature& b );\n  pair();\n\n  bool computequivalence( unsigned& c1, unsigned& c2, double* t1, double* t2 );\n\n  unsigned long long get_cost();\n\nprivate:\n  std::pair<gate, unsigned> single_control{f, 0u};\n};\n\nclass optimization_graph\n{\npublic:\n  /* you can give the ESOP circuit to be optimized or directly the graph */\n  optimization_graph( circuit& new_c );\n  optimization_graph( const mygraph& opt_g_given );\n\n  std::vector<edge_t<graph_t<>>> greedy_matching( bool describe );\n  std::vector<edge_t<graph_t<>>> exact_matching( bool describe );\n  std::vector<edge_t<graph_t<>>> realexact_matching( bool describe );\n\n  void order_edges();\n\n  /* this function automatically optimize for the greeding matching */\n  circuit optimize_esop();\n\nprivate:\n  circuit c;\n  mygraph opt_g;\n\n  std::unordered_map<std::pair<unsigned, unsigned>, pair, SimpleHash> edge_to_pair;\n\n  std::unordered_map<unsigned, std::vector<edge_t<graph_t<>>>> pos_to_match;\n\n  std::vector<edge_t<graph_t<>>> ordered_edges;\n  std::vector<edge_t<graph_t<>>> matching;\n  unsigned match_w = 0;\n\n  std::vector<vertex_t<graph_t<>>> v_saturated;\n};\n\nbool is_control( gate g, variable control )\n{\n  auto it = std::find( g.controls().begin(), g.controls().end(), control );\n  return it != g.controls().end();\n}\n\npair::pair( const gate& f_given, const gate& s_given, const circuit& c_given,\n            feature& a_given, feature& b_given )\n    : f( f_given ), s( s_given ), c( &c_given ), a( a_given ), b( b_given )\n{\n}\n\npair::pair() {}\n\nint count( const uint16_t bits ) { return __builtin_popcount( bits ); }\n\nint get_bit( uint16_t number, unsigned index )\n{\n  if ( ( ( number >> index ) & 1 ) == 1 )\n    return 1;\n  else\n    return 0;\n}\n\nbool pair::computequivalence( unsigned& c1, unsigned& c2, double* t1,\n                              double* t2 )\n{\n  bool combine = false;\n\n  /* FIRST PROPERTY */\n  if ( ( ( ( a.control & b.control ) & ( a.polarity ^ b.polarity ) ) == 0 ) &&\n       ( ( a.control & b.control ) !=\n         0 ) )\n  {\n    increment_timer t( t1 );\n    c1++;\n    auto a_notb = a.control & ( ~b.control );\n    auto b_nota = ( ~a.control ) & b.control;\n\n    if ( count( a_notb ) == 1 )\n    {\n\n      unsigned target = log2( a_notb );\n\n      std::vector<variable> controls;\n      uint16_t to_create = b_nota;\n      for ( unsigned i = 0; i < 16; i++ )\n      {\n        if ( ( to_create & 1 ) == 1 )\n        {\n          if ( ( ( b.polarity & ( 1 << i ) ) >> i ) == 1 )\n          {\n            controls.push_back( make_var( i, true ) );\n          }\n          else\n          {\n            controls.push_back( make_var( i, false ) );\n          }\n        }\n\n        to_create = to_create >> 1;\n      }\n      equivalent.set_lines( c->lines() );\n      append_toffoli( equivalent, controls, target );\n      append_toffoli( equivalent, f.controls(), f.targets().front() );\n      append_toffoli( equivalent, controls, target );\n      combine = true;\n    }\n    else if ( count( b_nota ) == 1 )\n    {\n      unsigned target = boost::integer_log2( b_nota );\n\n      std::vector<variable> controls;\n      uint16_t to_create = a_notb;\n      for ( unsigned i = 0; i < 16; i++ )\n      {\n        if ( ( to_create & 1 ) == 1 )\n        {\n          if ( ( ( a.polarity >> i ) & 1 ) == 1 )\n          {\n            controls.push_back( make_var( i, true ) );\n          }\n          else\n            controls.push_back( make_var( i, false ) );\n        }\n        to_create = to_create >> 1;\n      }\n\n      equivalent.set_lines( c->lines() );\n      append_toffoli( equivalent, controls, target );\n      append_toffoli( equivalent, s.controls(), s.targets().front() );\n      append_toffoli( equivalent, controls, target );\n\n      combine = true;\n    }\n  }\n  /* SECOND PROPERTY */\n  else if ( a.control == b.control )\n  {\n    increment_timer t( t2 );\n    c2++;\n    auto diff_pol = a.polarity ^ b.polarity;\n\n    if ( count( diff_pol ) >= 1 )\n    {\n      unsigned i = 0;\n      bool done = false;\n      std::vector<unsigned> cnot_targets;\n      unsigned cnot_control;\n      std::vector<variable> common_controls;\n\n      for ( i = 0; i < 16; ++i )\n      {\n        if ( ( diff_pol >> i ) & 1 )\n        {\n          if ( !done )\n          {\n            cnot_control = i;\n            done = true;\n            if ( ( ( a.polarity >> i ) & 1 ) == 1 )\n            {\n              for ( auto con : s.controls() )\n              {\n                if ( con.line() != i )\n                {\n                  common_controls.push_back( con );\n                }\n              }\n            }\n            else if ( ( ( b.polarity >> i ) & 1 ) == 1 )\n            {\n              for ( auto con : f.controls() )\n              {\n                if ( con.line() != i )\n                {\n                  common_controls.push_back( con );\n                }\n              }\n            }\n          }\n          else\n            cnot_targets.push_back( i );\n        }\n      }\n\n      equivalent.set_lines( c->lines() );\n      for ( auto target : cnot_targets )\n      {\n        append_cnot( equivalent, make_var( cnot_control, true ), target );\n      }\n\n      append_toffoli( equivalent, common_controls, s.targets().front() );\n\n      for ( auto target : cnot_targets )\n      {\n        append_cnot( equivalent, make_var( cnot_control, true ), target );\n      }\n    }\n    combine = true;\n  }\n\n  return combine;\n}\n\nunsigned long long pair::get_cost()\n{\n  circuit pair( c->lines() );\n\n  append_toffoli( pair, f.controls(), f.targets().front() );\n  append_toffoli( pair, s.controls(), s.targets().front() );\n\n  return costs( pair, costs_by_gate_func( t_costs() ) );\n}\n\nbool operator==( const gate& g1, const gate& g2 )\n{\n  return ( g1.controls() == g2.controls() ) &&\n         ( g1.targets() == g2.targets() ) && same_type( g1, g2 );\n}\n\noptimization_graph::optimization_graph( const mygraph& opt_g_given )\n    : opt_g( opt_g_given )\n{\n}\n\noptimization_graph::optimization_graph( circuit& new_c )\n{\n  double tempo = 0.0, tempo2 = 0.0, tempo3 = 0.0;\n  double time_case1 = 0.0, time_case2 = 0.0;\n  c = new_c;\n  const auto edge_weights = boost::get( boost::edge_weight, opt_g );\n  add_vertices( opt_g, new_c.num_gates() );\n  std::vector<feature> stack_f;\n\n  {\n    reference_timer costa( &tempo3 );\n    for ( unsigned i = 0; i < new_c.num_gates(); i++ )\n    {\n      feature f( new_c[i] );\n      stack_f.push_back( f );\n    }\n  }\n\n  auto c1 = 0u, c2 = 0u, ctr = 0u;\n  /* set the loop over all the pairs of the circuit */\n  {\n    reference_timer costa( &tempo );\n    for ( unsigned first = 0; first < new_c.num_gates() - 1; ++first )\n    {\n      for ( unsigned second = first + 1; second < new_c.num_gates(); ++second )\n      {\n        pair p( new_c[first], new_c[second], new_c, stack_f[first],\n                stack_f[second] );\n\n        bool result = false;\n        ++ctr;\n        result = p.computequivalence( c1, c2, &time_case1, &time_case2 );\n\n        if ( result )\n        {\n          increment_timer costa2( &tempo2 );\n\n          circuit& eq = p.equivalent;\n\n          auto old_cost = p.get_cost();\n\n          const auto cost = costs( eq, costs_by_gate_func( t_costs() ) );\n          if ( cost < old_cost )\n          {\n            unsigned long long edge_gain =\n                old_cost - cost; // it should be always positive\n\n            auto e = add_edge( first, second, opt_g );\n            auto edge = e.first;\n            edge_weights[edge] = edge_gain;\n\n            // map the fist source vertex with the corresponding pair\n            edge_to_pair.insert( {std::make_pair( first, second ), p} );\n\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid optimization_graph::order_edges()\n{\n  auto edge_weights = boost::get( boost::edge_weight, opt_g );\n\n\n  for ( auto edge : boost::make_iterator_range( boost::edges( opt_g ) ) )\n  {\n    ordered_edges.push_back( edge );\n  }\n\n\n  std::sort(\n      ordered_edges.begin(), ordered_edges.end(),\n      [edge_weights]( const edge_t<graph_t<>>& i, const edge_t<graph_t<>>& j ) {\n        return ( edge_weights[i] > edge_weights[j] );\n      } );\n}\n\nstd::vector<edge_t<graph_t<>>>\noptimization_graph::realexact_matching( bool describe )\n{\n  const auto edge_weights = boost::get( boost::edge_weight, opt_g );\n  matching = {};\n\n  std::vector<unsigned> components( boost::num_vertices( opt_g ) );\n  const auto num_components =\n      boost::connected_components( opt_g, &components[0] );\n  if ( describe )\n  {\n    std::cout << \"graph has\" << num_components\n              << \"components: \" << any_join( components, \" \" ) << std::endl;\n  }\n\n  std::vector<std::vector<unsigned>> map_connected( num_components );\n  for ( unsigned i = 0; i < boost::num_vertices( opt_g ); i++ )\n  {\n    unsigned group = components[i];\n    map_connected[group].push_back( i );\n  }\n\n  if ( describe )\n  {\n    unsigned conta = 0;\n    for ( auto u : map_connected )\n    {\n      if ( describe )\n      {\n        std::cout << \"Group \" << conta << \":\" << std::endl;\n        for ( auto k : u )\n        {\n          std::cout << k << \" \";\n        }\n        std::cout << std::endl;\n      }\n\n      conta++;\n    }\n  }\n\n  // for every group >1\n  for ( auto group : map_connected )\n  {\n    auto g_size = group.size();\n    if ( g_size > 1 )\n    {\n\n      std::vector<boost::dynamic_bitset<>> match_matrix;\n\n      std::vector<std::vector<edge_t<graph_t<>>>> matrix(\n          g_size, std::vector<edge_t<graph_t<>>>( g_size ) );\n      std::vector<std::vector<unsigned>> matrix_w(\n          g_size, std::vector<unsigned>( g_size ) );\n      std::vector<std::pair<unsigned, unsigned>>\n          pair_edge; // contains all the edges in the group\n\n\n\n      for ( auto edge : boost::make_iterator_range( boost::edges( opt_g ) ) )\n      {\n        auto v_source = boost::source( edge, opt_g );\n        auto s_iter = std::find( group.begin(), group.end(), v_source );\n        if ( s_iter != group.end() )\n        {\n\n          auto s_index = s_iter - group.begin();\n          auto v_target = boost::target( edge, opt_g );\n          auto t_index =\n              std::find( group.begin(), group.end(), v_target ) - group.begin();\n          matrix[s_index][t_index] = matrix[t_index][s_index] = edge;\n          matrix_w[s_index][t_index] = matrix_w[t_index][s_index] =\n              edge_weights[edge];\n\n          pair_edge.push_back( std::make_pair( s_index, t_index ) );\n        }\n      }\n\n      if ( describe )\n      {\n        std::cout << \"matrix \" << std::endl;\n        for ( auto i : matrix )\n        {\n          for ( auto k : i )\n          {\n            std::cout << k << \" \";\n          }\n          std::cout << std::endl;\n        }\n        std::cout << \"matrix W\" << std::endl;\n        for ( auto i : matrix_w )\n        {\n          for ( auto k : i )\n          {\n            std::cout << k << \" \";\n          }\n          std::cout << std::endl;\n        }\n        std::cout << \"edges\" << std::endl;\n        for ( auto i : pair_edge )\n        {\n          std::cout << i.first << \"-\" << i.second << std::endl;\n        }\n      }\n\n      boost::dynamic_bitset<> b( pair_edge.size() );\n\n      unsigned wmax_combinations = 0;\n\n      do\n      {\n        if ( describe )\n        {\n          std::cout << \"combination: \" << b << std::endl;\n        }\n        unsigned w = 0;\n\n        std::vector<boost::dynamic_bitset<>> M(\n            g_size, boost::dynamic_bitset<>( g_size ) );\n\n        for ( unsigned bit = 0; bit < pair_edge.size(); bit++ )\n        {\n\n          if ( describe )\n          {\n            std::cout << \"edge num: \" << bit << std::endl;\n          }\n\n          unsigned source, target;\n          source = pair_edge[bit].first;\n          target = pair_edge[bit].second;\n          if ( describe )\n          {\n            std::cout << source << \"-->\" << target << std::endl;\n          }\n          M[source][target] = M[target][source] = b[bit];\n          if ( describe )\n          {\n            for ( auto row : M )\n            {\n              std::cout << row << std::endl;\n            }\n          }\n\n          if ( b[bit] )\n          {\n            w += matrix_w[source][target];\n          } // increment the match weigth\n        }\n\n        if ( describe )\n          std::cout << \"is the matrix for this combination a match?? \"\n                    << std::endl;\n        bool match = true;\n        for ( auto row : M )\n        {\n          if ( describe )\n            std::cout << row << std::endl;\n          if ( row.count() > 1 )\n          {\n            match = false;\n          }\n        }\n        if ( describe )\n          std::cout << match << std::endl;\n\n        if ( match )\n        {\n          if ( w > wmax_combinations )\n          {\n            wmax_combinations = w;\n\n            match_matrix = M;\n          }\n        }\n\n        inc( b );\n\n      } while ( b.any() );\n\n      if ( describe )\n        std::cout << \"max comb weight: \" << wmax_combinations << std::endl;\n      if ( describe )\n        std::cout << \"matching matrix: \";\n\n\n      unsigned count = 0u;\n      for ( auto i : match_matrix )\n      {\n        if ( describe )\n          std::cout << i << std::endl;\n        for ( unsigned k = 0; k < i.size(); k++ )\n        {\n          if ( i[k] == 1 )\n          {\n            matching.push_back( matrix[count][k] );\n            match_w += matrix_w[count][k];\n            match_matrix[k][count] = 0;\n          }\n        }\n        count++;\n      }\n    }\n  }\n\n  if ( describe )\n  {\n    std::cout << \"the found match is: \" << std::endl;\n    for ( auto match_edge : matching )\n    {\n      std::cout << edge_weights[match_edge] << \" \";\n    }\n    std::cout << std::endl;\n    std::cout << \"its weight is: \" << match_w << std::endl;\n  }\n  return matching;\n}\n\nstd::vector<edge_t<graph_t<>>>\noptimization_graph::exact_matching( bool describe )\n{\n  const auto edge_weights = boost::get( boost::edge_weight, opt_g );\n\n  ordered_edges = {};\n\n  order_edges();\n  if ( describe )\n  {\n    std::cout << \"ordered edges: \";\n    for ( auto edge : ordered_edges )\n    {\n      std::cout << edge_weights[edge] << \" \" << boost::source( edge, opt_g )\n                << \" - \" << boost::target( edge, opt_g ) << \", \";\n    }\n    std::cout << std::endl;\n  }\n\n  unsigned max_match = 0;\n  unsigned pos_match = 0;\n  for ( unsigned i = 0; i < ordered_edges.size(); i++ )\n  {\n    matching = {};\n    v_saturated = {};\n    auto value_match = 0u;\n    auto edge_selected = ordered_edges[i];\n\n    if ( describe )\n      std::cout << \"selected is \" << edge_weights[edge_selected];\n\n    auto v_source = boost::source( edge_selected, opt_g );\n    auto v_target = boost::target( edge_selected, opt_g );\n\n    if ( describe )\n      std::cout << \"the vertex are \" << v_source << \" and \" << v_target\n                << std::endl;\n\n    matching.push_back( edge_selected );\n    value_match += edge_weights[edge_selected];\n    // v_sat.set( v_source );\n    v_saturated.push_back( v_source );\n    v_saturated.push_back( v_target );\n\n    for ( auto edge : ordered_edges )\n    {\n      if ( edge != edge_selected )\n      {\n        if ( describe )\n          std::cout << \"edge is \" << edge_weights[edge];\n        auto v_source = boost::source( edge, opt_g );\n        auto v_target = boost::target( edge, opt_g );\n\n        if ( describe )\n          std::cout << \"The sources are: \" << v_source << \"and\" << v_target\n                    << std::endl;\n\n        if ( std::find( v_saturated.begin(), v_saturated.end(), v_source ) ==\n                 v_saturated.end() &&\n             std::find( v_saturated.begin(), v_saturated.end(), v_target ) ==\n                 v_saturated.end() )\n        {\n\n          if ( describe )\n            std::cout << \"can be in the matching\" << std::endl;\n\n          matching.push_back( edge );\n          value_match += edge_weights[edge];\n          v_saturated.push_back( v_source );\n          v_saturated.push_back( v_target );\n        }\n        else\n        {\n          if ( describe )\n            std::cout << \"cannot be in the matching\" << std::endl;\n        }\n      }\n    }\n\n    pos_to_match[i] = matching;\n\n    if ( value_match > max_match )\n    {\n      max_match = value_match;\n      pos_match = i;\n    }\n  }\n\n\n  matching = pos_to_match[pos_match];\n  if ( describe )\n  {\n    std::cout << \"the found match is: \" << std::endl;\n    for ( auto match_edge : matching )\n    {\n      std::cout << edge_weights[match_edge] << \" \";\n    }\n    std::cout << std::endl;\n  }\n  return matching;\n}\n\nstd::vector<edge_t<graph_t<>>>\noptimization_graph::greedy_matching( bool describe )\n{\n\n  const auto edge_weights = boost::get( boost::edge_weight, opt_g );\n\n  order_edges();\n\n\n  for ( auto edge : ordered_edges )\n  {\n\n    auto v_source = boost::source( edge, opt_g );\n    auto v_target = boost::target( edge, opt_g );\n\n    if ( describe )\n      std::cout << \"The sources are: \" << v_source << \"and\" << v_target\n                << std::endl;\n\n    if ( std::find( v_saturated.begin(), v_saturated.end(), v_source ) ==\n             v_saturated.end() &&\n         std::find( v_saturated.begin(), v_saturated.end(), v_target ) ==\n             v_saturated.end() )\n    {\n      if ( describe )\n        std::cout << \"can be in the matching\" << std::endl;\n      matching.push_back( edge );\n\n      v_saturated.push_back( v_source );\n      v_saturated.push_back( v_target );\n    }\n    else\n    {\n      if ( describe )\n        std::cout << \"cant be in the matching\" << std::endl;\n    }\n  }\n  if ( describe )\n  {\n    std::cout << \"the found match is: \" << std::endl;\n    for ( auto match_edge : matching )\n    {\n      std::cout << edge_weights[match_edge] << \" \";\n    }\n    std::cout << std::endl;\n  }\n\n  return matching;\n}\n\ncircuit optimization_graph::optimize_esop()\n{\n  std::vector<unsigned> untouched_pos;\n\n  for ( unsigned pos = 0u; pos < c.num_gates(); ++pos )\n  {\n    untouched_pos.push_back( pos );\n  }\n\n  circuit c_optimized( c.lines() );\n  for ( auto edge : matching )\n  {\n\n    auto v_source = boost::source( edge, opt_g );\n    auto v_target = boost::target( edge, opt_g );\n    std::pair<unsigned, unsigned> key = std::make_pair( v_source, v_target );\n    pair& p_comb = edge_to_pair[key];\n\n    for ( const auto& g : p_comb.equivalent )\n    {\n      c_optimized.append_gate() = g;\n    }\n    untouched_pos.erase(\n        std::remove( untouched_pos.begin(), untouched_pos.end(), v_source ),\n        untouched_pos.end() );\n    untouched_pos.erase(\n        std::remove( untouched_pos.begin(), untouched_pos.end(), v_target ),\n        untouched_pos.end() );\n  }\n\n  for ( unsigned pos : untouched_pos )\n  {\n    append_toffoli( c_optimized, c[pos].controls(), c[pos].targets().front() );\n  }\n\n\n  return c_optimized;\n}\nfeature::feature() {}\n\nfeature::feature( gate& g )\n{\n\n  for ( auto c : g.controls() )\n  {\n    control |= ( 1 << c.line() );\n    if ( c.polarity() == 1 )\n    {\n      polarity |= ( 1 << c.line() );\n    }\n  }\n}\n\ncircuit esop_post_optimization( const circuit& c, const properties::ptr& settings,\n                                const properties::ptr& statistics )\n{\n  const auto verbose = get( settings, \"verbose\", false );\n  const auto greedy = get( settings, \"greedy\", true );\n  const auto exact = get( settings, \"exact\", false );\n\n  if ( greedy && exact )\n  {\n    std::cout << \"[w] both optimization approaches are enabled, will perform greedy matching\" << std::endl;\n  }\n\n  properties_timer t( statistics );\n  double* tempo;\n\n  circuit new_c = c;\n\n  optimization_graph g( new_c );\n  std::vector<edge_t<graph_t<>>> match;\n\n  if ( greedy )\n  {\n    match = g.greedy_matching( false );\n  }\n  else if ( exact )\n  {\n    match = g.realexact_matching( false );\n  }\n\n  if ( verbose )\n  {\n    std::cout << c << std::endl;\n  }\n\n  new_c = g.optimize_esop();\n\n  if ( verbose )\n  {\n    std::cout << new_c << std::endl;\n  }\n\n  unsigned global_pre = costs( c, costs_by_gate_func( t_costs() ) );\n  unsigned global_post = costs( new_c, costs_by_gate_func( t_costs() ) );\n\n  unsigned global_cost_gain = global_pre - global_post;\n\n  double percentage = global_cost_gain;\n  percentage /= global_pre;\n\n  double match_percentage = match.size();\n  match_percentage /= c.num_gates();\n\n  set( statistics, \"% matched pairs\", match_percentage );\n  set( statistics, \"global improvement\", percentage );\n\n  return new_c;\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": "71752680a6870ce686ac5aad2a8a7a6ee360fc4e", "size": 22780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/optimization/esop_post_optimization.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/optimization/esop_post_optimization.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/optimization/esop_post_optimization.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": 25.8276643991, "max_line_length": 107, "alphanum_fraction": 0.5586918349, "num_tokens": 5877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.039638836406525636, "lm_q1q2_score": 0.017202520286826097}}
{"text": "#ifndef BOOST_NUMERIC_CPP_HPP\n#define BOOST_NUMERIC_CPP_HPP\n\n// MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n//  Copyright (c) 2012 Robert Ramey\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// policy which creates results types equal to that of C++ promotions.\n// Using the policy will permit the program to build and run in release\n// mode which is identical to that in debug mode except for the fact\n// that errors aren't trapped. \n\n#include <type_traits> // integral constant, remove_cv, conditional\n#include <limits>\n#include <boost/integer.hpp> // integer type selection\n\n#include \"safe_common.hpp\"\n#include \"checked_result.hpp\"\n\nnamespace boost {\nnamespace safe_numerics {\n\n// in C++ the following rules govern integer arithmetic\n\n// This policy is use to emulate another compiler/machine architecture\n// For example, a Z80 has 8 bit char, 16 bit short, 16 bit int, 32 bit long.  So one\n// would use cpp<8, 16, 16, 32, 32> to test programs destined to run on a Z80\n\n// Follow section 5 of the standard.\ntemplate<\n    int CharBits,\n    int ShortBits,\n    int IntBits,\n    int LongBits,\n    int LongLongBits\n>\nstruct cpp {\npublic:\n    using local_char_type = typename boost::int_t<CharBits>::exact;\n    using local_short_type = typename boost::int_t<ShortBits>::exact;\n    using local_int_type = typename boost::int_t<IntBits>::exact;\n    using local_long_type = typename boost::int_t<LongBits>::exact;\n    using local_long_long_type = typename boost::int_t<LongLongBits>::exact;\n\n    template<class T>\n    using rank =\n        typename std::conditional<\n            std::is_same<local_char_type, typename std::make_signed<T>::type>::value,\n            std::integral_constant<int, 1>,\n        typename std::conditional<\n            std::is_same<local_short_type, typename std::make_signed<T>::type>::value,\n            std::integral_constant<int, 2>,\n        typename std::conditional<\n            std::is_same<local_int_type, typename std::make_signed<T>::type>::value,\n            std::integral_constant<int, 3>,\n        typename std::conditional<\n            std::is_same<local_long_type, typename std::make_signed<T>::type>::value,\n            std::integral_constant<int, 4>,\n        typename std::conditional<\n            std::is_same<local_long_long_type, typename std::make_signed<T>::type>::value,\n            std::integral_constant<int, 5>,\n            std::integral_constant<int, 6> // catch all - never promote integral\n        >::type >::type >::type >::type >::type;\n\n    // section 4.5 integral promotions\n\n   // convert smaller of two types to the size of the larger\n    template<class T, class U>\n    using higher_ranked_type = typename std::conditional<\n        (rank<T>::value < rank<U>::value),\n        U,\n        T\n    >::type;\n\n    template<class T, class U>\n    using copy_sign = typename std::conditional<\n        std::is_signed<U>::value,\n        typename std::make_signed<T>::type,\n        typename std::make_unsigned<T>::type\n    >::type;\n\n    template<class T>\n    using integral_promotion = copy_sign<\n        higher_ranked_type<local_int_type, T>,\n        T\n    >;\n\n    // note presumption that T & U don't have he same sign\n    // if that's not true, these won't work\n    template<class T, class U>\n    using select_signed = typename std::conditional<\n        std::numeric_limits<T>::is_signed,\n        T,\n        U\n    >::type;\n\n    template<class T, class U>\n    using select_unsigned = typename std::conditional<\n        std::numeric_limits<T>::is_signed,\n        U,\n        T\n    >::type;\n\n    // section 5 clause 11 - usual arithmetic conversions\n    template<typename T, typename U>\n    using usual_arithmetic_conversions =\n        // clause 0 - if both operands have the same type\n        typename std::conditional<\n            std::is_same<T, U>::value,\n            // no further conversion is needed\n            T,\n        // clause 1 - otherwise if both operands have the same sign\n        typename std::conditional<\n            std::numeric_limits<T>::is_signed\n            == std::numeric_limits<U>::is_signed,\n            // convert to the higher ranked type\n            higher_ranked_type<T, U>,\n        // clause 2 - otherwise if the rank of he unsigned type exceeds\n        // the rank of the of the signed type\n        typename std::conditional<\n            rank<select_unsigned<T, U>>::value\n            >= rank< select_signed<T, U>>::value,\n            // use unsigned type\n            select_unsigned<T, U>,\n        // clause 3 - otherwise if the type of the signed integer type can\n        // represent all the values of the unsigned type\n        typename std::conditional<\n            std::numeric_limits< select_signed<T, U>>::digits >=\n            std::numeric_limits< select_unsigned<T, U>>::digits,\n            // use signed type\n            select_signed<T, U>,\n        // clause 4 - otherwise use unsigned version of the signed type\n            std::make_signed< select_signed<T, U>>\n        >::type >::type >::type\n    >;\n\n    template<typename T, typename U>\n    using result_type = typename usual_arithmetic_conversions<\n        integral_promotion<typename base_type<T>::type>,\n        integral_promotion<typename base_type<U>::type>\n    >::type;\npublic:\n    template<typename T, typename U>\n    struct addition_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct subtraction_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct multiplication_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct division_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct modulus_result {\n       using type = result_type<T, U>;\n    };\n    // note: comparison_result (<, >, ...) is special.\n    // The return value is always a bool.  The type returned here is\n    // the intermediate type applied to make the values comparable.\n    template<typename T, typename U>\n    struct comparison_result {\n        using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct left_shift_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct right_shift_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct bitwise_and_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct bitwise_or_result {\n       using type = result_type<T, U>;\n    };\n    template<typename T, typename U>\n    struct bitwise_xor_result {\n       using type = result_type<T, U>;\n    };\n};\n\n} // safe_numerics\n} // boost\n\n#endif // BOOST_NUMERIC_cpp_HPP\n", "meta": {"hexsha": "c6df41e4f4efd5e399926cb17e955b322171f780", "size": 6916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/safe_numerics/cpp.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/safe_numerics/cpp.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/safe_numerics/cpp.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": 34.0689655172, "max_line_length": 90, "alphanum_fraction": 0.6454598034, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.04468086884154117, "lm_q1q2_score": 0.017198209673725325}}
{"text": "/////////////////////////////////////////////////////////////\n//                                                         //\n// Copyright (c) 2003-2017 by The University of Queensland //\n// Centre for Geoscience Computing                         //\n// http://earth.uq.edu.au/centre-geoscience-computing      //\n//                                                         //\n// Primary Business: Brisbane, Queensland, Australia       //\n// Licensed under the Open Software License version 3.0    //\n// http://www.apache.org/licenses/LICENSE-2.0              //\n//                                                         //\n/////////////////////////////////////////////////////////////\n\n\n#include <boost/version.hpp>\n#include <boost/python.hpp>\n#include \"Python/esys/lsm/geometry/MiscPy.h\"\n#include \"Python/esys/lsm/geometry/SimpleSpherePy.h\"\n#include \"Python/esys/lsm/util/BoundingBoxPy.h\"\n#include \"Python/esys/lsm/util/Vec3Py.h\"\n\nnamespace esys\n{\n  namespace lsm\n  {\n    class SolidBoxPy : public BoundingBoxPy\n    {\n    public:\n      SolidBoxPy() : BoundingBoxPy()\n      {\n      }\n      \n      SolidBoxPy(const Vec3Py &minPt, const Vec3Py &maxPt)\n        : BoundingBoxPy(minPt, maxPt)\n      {\n      }\n\n      SolidBoxPy(const SolidBoxPy &box)\n        : BoundingBoxPy(box.getMinPt(), box.getMaxPt())\n      {\n      }\n\n      SolidBoxPy(const BoundingBoxPy &box)\n        : BoundingBoxPy(box.getMinPt(), box.getMaxPt())\n      {\n      }\n\n      SolidBoxPy(const BoundingBox &box)\n        : BoundingBoxPy(box.getMinPt(), box.getMaxPt())\n      {\n      }\n\n      /**\n       * Arvo's algorithm for axis-aligned solid-box/solid-sphere intersection.\n       */\n      bool intersectsWithSphere(const Vec3 &centre, double radius) const\n      {\n        double distSqrd = 0.0;\n        for (int i = 0; i < 3; i++)\n        {\n          if (centre[i] < getMinPt()[i])\n          {\n            const double diff = centre[i] - getMinPt()[i];\n            distSqrd += diff*diff;\n          }\n          else if (centre[i] > getMaxPt()[i])\n          {\n            const double diff = centre[i] - getMaxPt()[i];\n            distSqrd += diff*diff;\n          }\n        }\n        return (distSqrd <= (radius*radius));\n      }\n\n      bool intersectsWithSpherePy(const Vec3Py &centre, double radius) const\n      {\n        return intersectsWithSphere(centre, radius);\n      }\n            \n      bool intersects(const SimpleSpherePy &p) const\n      {\n        return intersectsWithSphere(p.getPos(), p.getRad());\n      }\n    };\n\n    class HollowBoxPy : public BoundingBoxPy\n    {\n    public:\n      HollowBoxPy() : BoundingBoxPy()\n      {\n      }\n\n      HollowBoxPy(const Vec3Py &minPt, const Vec3Py &maxPt)\n        : BoundingBoxPy(minPt, maxPt)\n      {\n      }\n\n      HollowBoxPy(const HollowBoxPy &box)\n        : BoundingBoxPy(box.getMinPt(), box.getMaxPt())\n      {\n      }\n\n      HollowBoxPy(const BoundingBoxPy &box)\n        : BoundingBoxPy(box.getMinPt(), box.getMaxPt())\n      {\n      }\n\n      HollowBoxPy(const BoundingBox &box)\n        : BoundingBoxPy(box.getMinPt(), box.getMaxPt())\n      {\n      }\n\n      /**\n       * Arvo's algorithm for axis-aligned hollow-box/solid-sphere intersection.\n       */\n      bool intersectsWithSphere(const Vec3 &centre, double radius) const\n      {\n        double distSqrd = 0;\n        bool face = false;\n        for(int i = 0; i < 3; i++)\n        {\n          if(centre[i] < getMinPt()[i])\n          {\n            face = true;\n            const double diff = (centre[i] - getMinPt()[i]);\n            distSqrd += diff*diff;\n          }\n          else if (centre[i] > getMaxPt()[i])\n          {\n            face = true;\n            const double diff = centre[i] - getMaxPt()[i];\n            distSqrd += diff*diff;\n          }\n          else if ((centre[i] - getMinPt()[i]) <= radius )\n          {\n            face = true;\n          }\n          else if ((getMaxPt()[i] - centre[i]) <= radius)\n          {\n            face = true;\n          }\n        }\n        return (face && (distSqrd <= radius*radius));\n      }\n\n      bool intersectsWithSpherePy(const Vec3Py &centre, double radius) const\n      {\n        return intersectsWithSphere(centre, radius);\n      }\n      \n      bool intersects(const SimpleSpherePy &p) const\n      {\n        return intersectsWithSphere(p.getPos(), p.getRad());\n      }\n    };\n    \n    void exportMisc()\n    {\n      // Disable autogeneration of C++ signatures (Boost 1.34.0 and higher)\n      // for Epydoc which stumbles over indentation in the automatically generated strings.\n      boost::python::docstring_options no_autogen(true,false);\n\n      boost::python::class_<SolidBoxPy, boost::python::bases<BoundingBoxPy> >(\n        \"SolidBox\"\n      )\n      .def(boost::python::init<>())\n      .def(boost::python::init<const Vec3Py &, const Vec3Py &>())\n      .def(boost::python::init<const SolidBoxPy &>())\n      .def(boost::python::init<const BoundingBoxPy &>())\n      .def(\"intersects\", &SolidBoxPy::intersects)\n      .def(\"intersects\", &SolidBoxPy::intersectsWithSpherePy)\n      ;\n\n      boost::python::class_<HollowBoxPy, boost::python::bases<BoundingBoxPy> >(\n        \"HollowBox\"\n      )\n      .def(boost::python::init<>())\n      .def(boost::python::init<const Vec3Py &, const Vec3Py &>())\n      .def(boost::python::init<const HollowBoxPy &>())\n      .def(boost::python::init<const BoundingBoxPy &>())\n      .def(\"intersects\", &HollowBoxPy::intersects)\n      .def(\"intersects\", &HollowBoxPy::intersectsWithSpherePy)\n      ;\n    }\n  }\n}\n", "meta": {"hexsha": "827fc61e175e50fc50b789837266b85ce3cb66d5", "size": 5464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Python/esys/lsm/geometry/MiscPy.cpp", "max_stars_repo_name": "danielfrascarelli/esys-particle", "max_stars_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "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": "Python/esys/lsm/geometry/MiscPy.cpp", "max_issues_repo_name": "danielfrascarelli/esys-particle", "max_issues_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "max_issues_repo_licenses": ["Apache-2.0"], "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/esys/lsm/geometry/MiscPy.cpp", "max_forks_repo_name": "danielfrascarelli/esys-particle", "max_forks_repo_head_hexsha": "e56638000fd9c4af77e21c75aa35a4f8922fd9f0", "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.376344086, "max_line_length": 91, "alphanum_fraction": 0.5283674963, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709194, "lm_q2_score": 0.03461884120468727, "lm_q1q2_score": 0.017174193505078966}}
{"text": "/*\n * Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\n */\n\n#ifndef SOUNDVELOCITYPROFILE_HPP\n#define SOUNDVELOCITYPROFILE_HPP\n\n#include <list>\n#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <vector>\n#include <ctime>\n#include <string>\n#include \"../utils/TimeUtils.hpp\"\n\n/*!\n * \\brief SoundVelocityProfile class\n * \\author Guillaume Labbe-Morissette, Jordan McManus, Emile Gagne\n * \\date August 22, 2018, 10:30 AM\n */\nclass SoundVelocityProfile {\npublic:\n\n    /**Creates a sound velocity*/\n    SoundVelocityProfile() {\n        longitude = latitude = nan(\"\");\n        timestamp = 0;\n    }\n\n    /**Destroys a sound velocity*/\n    ~SoundVelocityProfile() {\n\n    }\n\n    /**Returns the size of the SoundVelocityProfile*/\n    unsigned int getSize() {\n        return getDepths().size();\n    };\n\n    /**Returns the latitude of the SoundVelocityProfile*/\n    double getLatitude() {\n        return latitude;\n    }\n\n    /**\n     * Sets the latitude of the SoundVelocityProfile\n     *\n     * @param l the new latitude\n     */\n    void setLatitude(double l) {\n        latitude = l;\n    }\n\n    /**Returns the longitude of the SoundVelocityProfile*/\n    double getLongitude() {\n        return longitude;\n    }\n\n    /**\n     * Sets the longitude of the SoundVelocityProfile\n     *\n     * @param l the new longitude of the SoundVelocityProfile\n     */\n    void setLongitude(double l) {\n        longitude = l;\n    }\n\n    /**Return the timestamp of the sound velocity*/\n    uint64_t getTimestamp() {\n        return timestamp;\n    };\n\n    /**\n     * Sets the timestamp of the SoundVelocityProfile\n     *\n     * @param t the new timestamp\n     */\n    void setTimestamp(uint64_t t) {\n        timestamp = t;\n    };\n\n    /**\n     * Adds a new value in the vector depths and speeds\n     *\n     * @param depth value to add in depths\n     * @param soundSpeed value to add in speeds\n     */\n    void add(double depth, double soundSpeed) {\n        samples.push_back(std::make_pair(depth, soundSpeed));\n    }\n\n    /**Returns the depths vector*/\n    Eigen::VectorXd & getDepths() {\n        //lazy load internal vector\n        if ((unsigned int) depths.size() != samples.size()) {\n            depths.resize(samples.size());\n\n            for (unsigned int i = 0; i < samples.size(); i++) {\n                depths(i) = samples[i].first;\n            }\n        }\n\n        return depths;\n    }\n\n    /**Returns the speeds vector*/\n    Eigen::VectorXd & getSpeeds() {\n        //lazy load internal vector\n        if ((unsigned int) speeds.size() != samples.size()) {\n            speeds.resize(samples.size());\n\n            for (unsigned int i = 0; i < samples.size(); i++) {\n                speeds(i) = samples[i].second;\n            }\n        }\n\n        return speeds;\n    }\n    \n    /**Returns the sound speed gradient*/\n    Eigen::VectorXd & getSoundSpeedGradient() {\n        if( (unsigned int) gradient.size() != samples.size()-1) {\n            gradient.resize(samples.size() - 1);\n            \n            for (unsigned int k=0; k < samples.size()-1; k++){\n                gradient(k) = (getSpeeds()(k+1)- getSpeeds()(k))/(getDepths()(k+1)- getDepths()(k));\n            }\n        }\n        \n        return gradient;\n    }\n    \n    /**Returns the layer index at specified depth*/\n    unsigned int getLayerIndexForDepth(double depth) {\n        // Warning: do not confuse layer with svp sample\n        // a layer is the space above or beneath a sample\n        \n        if(depth < samples[0].first) {\n            return 0; // the 0-th layer is shallower than the shallowest svp sample\n        }\n        \n        for (unsigned int k=0; k < samples.size()-1; k++){\n            if( depth >= samples[k].first && depth < samples[k+1].first) {\n                return k+1;\n            }\n        }\n        \n        // This layer is deeper than the deepest svp sample\n        return samples.size();\n    }\n\n    /**\n     * Returns the stream in which this ping will be written\n     *\n     * @param os the stream in which to write this ping\n     * @param obj the ping to write in the stream\n     */\n    friend std::ostream& operator<<(std::ostream & os, const SoundVelocityProfile & obj) {\n        return os <<\n                \"timestamp: \" << obj.timestamp << std::endl <<\n                \"latitude: \" << obj.latitude << std::endl <<\n                \"longitude: \" << obj.longitude << std::endl;\n    }\n\nprivate:\n\n    /**timestamp value of the SoundVelocityProfile (micro-second)*/\n    uint64_t timestamp; //timestamp\n\n    /**latitude value of the SoundVelocityProfile*/\n    double latitude;\n\n    /**longitude value of the SoundVelocityProfile*/\n    double longitude;\n\n    /**vector that contains the dephts of the SoundVelocityProfile*/\n    Eigen::VectorXd depths;\n\n    /**vector that contain the speeds of the SoundVelocityProfile*/\n    Eigen::VectorXd speeds;\n    \n    /**vector that contain sound speed gradient*/\n    Eigen::VectorXd gradient;\n\n    /**vector that contain the depths and the speeds*/\n    std::vector<std::pair<double, double>> samples;\n};\n\n#endif /* SOUNDVELOCITYPROFILE_HPP */\n", "meta": {"hexsha": "26f3230a13e09874348d3ef80d5a53c992686568", "size": 5172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/svp/SoundVelocityProfile.hpp", "max_stars_repo_name": "JordanMcManus/MBES-lib", "max_stars_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "src/svp/SoundVelocityProfile.hpp", "max_issues_repo_name": "JordanMcManus/MBES-lib", "max_issues_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "src/svp/SoundVelocityProfile.hpp", "max_forks_repo_name": "JordanMcManus/MBES-lib", "max_forks_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 26.7979274611, "max_line_length": 119, "alphanum_fraction": 0.5883604022, "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.03514484829564469, "lm_q1q2_score": 0.017160645852954418}}
{"text": "/// @file gibbs.hpp A generic templated Gibbs sampler implementation\n\n#ifndef SAMPLING_GIBBS_HPP__\n#define SAMPLING_GIBBS_HPP__\n\n#include <boost/tuple/tuple.hpp>\n#include <functional>\n#include <stdexcept>\n\n#include \"../partition_sampler.hpp\"\n\n\n\nnamespace biggles {\n\ntypedef boost::tuple<partition_sampler_sample, model::parameters> tracker_sample;\n\nnamespace sampling {\n\n/// @brief An implementation of a Gibbs sampler.\n///\n/// A Gibbs sampler can sample from some conditional joint posterior distribution, \\f$ P(x_1, x_2, ..., x_N | Y) \\f$\n/// given only the ability to sample from individual conditional probability distributions \\f$ P(x_i | x_1, ...,\n/// x_{i-1}, x_{i+1}, ..., x_N, Y) \\f$.\n///\n/// Each sample from the sampler is a tuple \\f$(x_1, x_2, ..., x_N)\\f$ of samples from the joint distribution. This\n/// tuple has type \\p SampleTuple which must be an appropriate form of \\c boost::tuple<>. The sampler maintains a copy\n/// of the last sample tuple drawn which may be accessed via the last_sample() member function.\n///\n/// The sampler draws samples from the individual conditional distributions via the \\p ConditionalSampler type. The\n/// sampler maintains an internal instance of this type which is used to draw samples. If \\c cs is an instance of \\p\n/// ConditionalSampler and \\c st is an instance of \\c SampleTuple, then the following expression should draw a sample\n/// for \\f$x_{i+1}\\f$ where \\f$0 \\le i < N\\f$:\n///\n/// @code\n/// cs.template draw<i>(st);\n/// @endcode\n///\n/// The sampler may use values within \\c st not corresponding to index \\c i as conditional values for sampling. As a\n/// concrete example, the following \\c struct would be a minimal declaration matching the \\c ConditionalSampler concept.\n///\n/// @code\n/// #include <boost/tuple.hpp>\n///\n/// // ...\n///\n/// template<typename SampleTuple>\n/// struct ConditionalSampler\n/// {\n///     // Draw a sample for x_{idx+1} from P(x_{idx+1} | x_1, ..., x_{idx}, x_{idx+2}, ..., x_N).\n///     template<int idx>\n///     boost::tuples::element<idx, SampleTuple>::type draw(const SampleTuple&);\n/// };\n/// @endcode\n///\n/// @sa two_var_cond_sampler An example of a \\p ConditionalSampler which assumes that the Gibbs sampler is sampling from\n/// the joint distribution of just two random variables.\n///\n/// @tparam SampleTuple A boost::tuple which specifies the types of \\f$ x_1 \\f$, \\f$ x_2 \\f$, etc.\n/// @tparam ConditionalSampler A sampler which can sample from each conditional distribution. See\n/// two_var_cond_sampler for an example.\ntemplate<typename ConditionalSampler, typename SampleTuple = typename ConditionalSampler::sample_tuple_type>\nclass gibbs_sampler\n{\npublic:\n    /// @brief Specify initial sample tuple and conditional sampler instance.\n    ///\n    /// @param cond_sampler A copy of this conditional sampler is taken to initialise the internal instance.\n    /// @param initial_sample The initial sample tuple to use for the sampler.\n    gibbs_sampler(const ConditionalSampler& cond_sampler = ConditionalSampler(),\n            const SampleTuple& initial_sample = SampleTuple())\n        : sample_(initial_sample)\n        , cond_sampler_(cond_sampler)\n    { }\n\n    /// @brief Draw a new sample from the conditional joint distribution.\n    ///\n    /// @return A reference to the sample drawn by the sampler which can be queried before the next invocation of draw()\n    /// via the last_sample() member function.\n    const SampleTuple& draw()\n    {\n        typedef gibbs_sampler<ConditionalSampler, SampleTuple> self_t;\n\n        // start the sample drawing process.\n        sample_drawer<self_t, boost::tuples::length<SampleTuple>::value, 0>()(*this);\n        return last_sample();\n    }\n\n    /// @brief Obtain a reference to the last sample drawn by the sampler.\n    const SampleTuple& last_sample() const { return sample_; }\n\nprotected:\n    /// @brief The current sample tuple for the sampler.\n    SampleTuple sample_;\n\n    /// @brief The sample evolution functor.\n    ConditionalSampler cond_sampler_;\n\nprivate:\n    /// These implement a template metaprogramming recursion to draw one sample in turn from the conditional PDF.\n    /// @{\n\n    template<typename Parent, int maxidx, int idx>\n    struct sample_drawer\n    {\n        inline void operator() (Parent& p) const\n        {\n            boost::tuples::get<idx>(p.sample_) = p.cond_sampler_.template draw<idx>(p.sample_);\n            sample_drawer<Parent, maxidx, idx+1>()(p);\n        };\n    };\n\n    template<typename Parent, int maxidx>\n    struct sample_drawer<Parent, maxidx, maxidx>\n    {\n        inline void operator() (Parent&) const { }\n    };\n\n    /// @}\n};\n\nclass new_gibbs_sampler {\n    //new_gibbs_sampler();\n    new_gibbs_sampler(const new_gibbs_sampler&);\n    void operator=(const new_gibbs_sampler&);\npublic:\n    new_gibbs_sampler(const partition_ptr_t& initial_partition_ptr = partition_ptr_t(new partition),\n        const model::parameters& initial_parameters = model::parameters());\n    tracker_sample draw();\n    tracker_sample last_sample() const;\n    const partition_sampler_sample& last_partition_sample() const;\n    const model::parameters& last_parameter_sample() const;\n    /** set the observation error to the passed values and stop sampling it\n     *\n     */\n    void fix_observation_error(const float R00, const float R01, const float R11);\n    /** \\brief draw a sample of the oservation error every *lag* samples\n     *\n     * lag==0 does the same as lag==1\n     */\n    void sample_observation_error(const size_t lag = 1);\nprotected:\n    /// \\brief read access to the Metropolis-Hastings sampler\n    const partition_sampler& underlying_partition_sampler() const { return partition_sampler_; }\n    /// \\brief write access to the Metropolis-Hastings sampler\n    partition_sampler& underlying_partition_sampler() { return partition_sampler_; }\nprivate:\n    size_t observation_error_lag_; ///< \\brief the gap between two observation error samples\n    size_t gibbs_sample_count_; ///< \\brief the internal counter for the observation error samples\n    partition_sampler_sample partition_sample_; ///< \\brief the current partition sample incl. proposed/executed moves\n    model::parameters parameter_sample_; ///< \\brief the current parameter sample\n    partition_sampler partition_sampler_; ///< \\brief the Metropolis-Hastings sampler\n};\n\n\n\nnamespace gibbs {\n\n/// @brief An base class for a two-variable sampler.\n///\n/// This class serves as an implementation of the \\c ConditionalSampler concept which can sample from distributions of\n/// the form \\f$ P(x_1, x_2 | Y) \\f$. It does this by taking two \\c UnaryFunction functors which can draw a sample of\n/// \\f$ x_1 \\f$ given \\f$ x_2 \\f$ and vice-versa. Any static data, \\f$Y\\f$, should be hidden within the functor state.\n///\n/// The sampler is templated on two types implementing the \\c UnaryFunction concept, \\p UnaryFunction1 and \\p\n/// UnaryFunction2. The return type of \\p UnaryFunction1 should correspond to \\f$ x_1 \\f$ and the return type of \\p\n/// UnaryFunction2 should correspond to \\f$ x_2 \\f$. The argument types should correspond to \\f$ x_2 \\f$ and \\f$ x_1 \\f$\n/// respectively.\n///\n/// The instances of these functors provided should sample values of \\f$ x_1 \\f$ and \\f$ x_2 \\f$ appropriately\n/// conditioned on their arguments.\n///\n/// @sa mem_fun_two_var_cond_sampler A convenience derived class capable of using its member functions as sampling\n/// functions.\n///\n/// @tparam UnaryFunction1 A std::unary_function to draw samples of \\f$x_1\\f$.\n/// @tparam UnaryFunction2 A std::unary_function to draw samples of \\f$x_2\\f$.\ntemplate<typename UnaryFunction1, typename UnaryFunction2>\nclass two_var_cond_sampler\n{\npublic:\n    /// @brief The C++ type corresponding to \\f$ x_1 \\f$.\n    typedef typename UnaryFunction1::result_type first_sample_type;\n\n    /// @brief The C++ type corresponding to \\f$ x_2 \\f$.\n    typedef typename UnaryFunction2::result_type second_sample_type;\n\n    /// @brief The C++ type corresponding to the tuple \\f$ (x_1, x_2) \\f$.\n    typedef boost::tuple<first_sample_type, second_sample_type> sample_tuple_type;\n\n    /// @brief Initialise the sampling functors.\n    ///\n    /// @param first_sampler An instance of \\p UnaryFunction1 which is copied internally.\n    /// @param second_sampler An instance of \\p UnaryFunction2 which is copied internally.\n    two_var_cond_sampler(\n        const UnaryFunction1 first_sampler = UnaryFunction1(),\n        const UnaryFunction2 second_sampler = UnaryFunction2())\n        :   first_sampler_(first_sampler)\n        ,   second_sampler_(second_sampler)\n    { }\n\n    /// @brief Draw a sample from one conditional distribution.\n    ///\n    /// Draw a sample of \\f$ x_{i+1} \\f$ from the individual conditional distributions.\n    ///\n    /// @tparam i Which random variable to sample.\n    /// @param sample_tuple A tuple giving the conditional values.\n    ///\n    /// @return A new sample of \\f$ x_{i+1} \\f$.\n    template<int i>\n    inline typename boost::tuples::element<i, sample_tuple_type>::type draw(const sample_tuple_type& sample_tuple)\n    {\n        typedef two_var_cond_sampler<UnaryFunction1, UnaryFunction2> self_t;\n        return sampler_func<self_t, i>()(*this, boost::tuples::get<1-i>(sample_tuple));\n    }\n\nprotected:\n    /// @brief A functor for sampling \\f$x_1\\f$ from \\f$P(x_1 | x_2, Y)\\f$.\n    UnaryFunction1 first_sampler_;\n\n    /// @brief A functor for sampling \\f$x_2\\f$ from \\f$P(x_2 | x_1, Y)\\f$.\n    UnaryFunction2 second_sampler_;\n\nprivate:\n    /// These implement a templated functor for sampling from either the first or second sampler.\n    /// @{\n\n    template<typename Parent, int>\n    struct sampler_func { };\n\n    template<typename Parent>\n    struct sampler_func<Parent, 0>\n    {\n        inline first_sample_type operator() (Parent& p, const second_sample_type& a) const\n        {\n            return p.first_sampler_(a);\n        }\n    };\n\n    template<typename Parent>\n    struct sampler_func<Parent, 1>\n    {\n        inline second_sample_type operator() (Parent& p, const first_sample_type& a) const\n        {\n            return p.second_sampler_(a);\n        }\n    };\n\n    /// @}\n};\n\n/// @brief An abstract base class for a class which implements two-variable conditional sampling in member functions.\n///\n/// Derived classes should implement the following the two member functions \\c sample_variable_1() and \\c\n/// sample_variable_2(). For example:\n///\n/// @code\n/// template<typename Variable1, typename Variable2>\n/// struct derived_two_var_cond_sampler\n///     : public mem_fun_two_var_cond_sampler<derived_two_var_cond_sampler, Variable1, Variable2>\n/// {\n///     Variable1 sample_variable_1(Variable2);\n///\n///     Variable2 sample_variable_2(Variable1);\n/// };\n/// @endcode\n///\n/// @tparam Derived The type of the derived class.\n/// @tparam Variable1 The type corresponding to \\f$ x_1 \\f$.\n/// @tparam Variable2 The type corresponding to \\f$ x_2 \\f$.\ntemplate<typename Derived, typename Variable1, typename Variable2>\nclass mem_fun_two_var_cond_sampler\n    : public two_var_cond_sampler<\n      std::binder1st<std::mem_fun1_t<Variable1, Derived, Variable2> >,\n      std::binder1st<std::mem_fun1_t<Variable2, Derived, Variable1> > >\n{\npublic:\n    /// @brief A \\c UnaryFunctor type which returns a sample of \\f$ x_1 \\f$ given a value of \\f$ x_2 \\f$.\n    typedef std::binder1st<std::mem_fun1_t<Variable1, Derived, Variable2> > sampler_1_func;\n\n    /// @brief A \\c UnaryFunctor type which returns a sample of \\f$ x_2 \\f$ given a value of \\f$ x_1 \\f$.\n    typedef std::binder1st<std::mem_fun1_t<Variable2, Derived, Variable1> > sampler_2_func;\n\n    mem_fun_two_var_cond_sampler()\n        : two_var_cond_sampler<sampler_1_func, sampler_2_func>(sampler_1(), sampler_2())\n    { }\n\nprivate:\n    inline sampler_1_func sampler_1() const\n    {\n        return std::bind1st(std::mem_fun(&Derived::sample_variable_1), this);\n    }\n\n    inline sampler_2_func sampler_2() const\n    {\n        return std::bind1st(std::mem_fun(&Derived::sample_variable_2), this);\n    }\n};\n\n} } } // biggles::sampling::gibbs\n\n#endif // SAMPLING_GIBBS_HPP__\n", "meta": {"hexsha": "a37f096db0d7f6804078e239f863ffe5da6924f9", "size": 12047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/sampling/gibbs.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/sampling/gibbs.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/sampling/gibbs.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7590759076, "max_line_length": 120, "alphanum_fraction": 0.7025815556, "num_tokens": 2923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215779698935, "lm_q2_score": 0.040237945500944707, "lm_q1q2_score": 0.017154304420229326}}
{"text": "/**\n * \\file fknm.cpp\n * \\author Jesse Haviland\n *\n *\n */\n\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include \"fknm.h\"\n#include \"methods.h\"\n#include \"linalg.h\"\n#include \"structs.h\"\n\n#include <Python.h>\n#include <numpy/arrayobject.h>\n#include <math.h>\n#include <Eigen/Dense>\n\nstatic PyMethodDef fknmMethods[] = {\n    {\"IK\",\n     (PyCFunction)IK,\n     METH_VARARGS,\n     \"Link\"},\n    {\"Robot_link_T\",\n     (PyCFunction)Robot_link_T,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ETS_hessian0\",\n     (PyCFunction)ETS_hessian0,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ETS_hessiane\",\n     (PyCFunction)ETS_hessiane,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ETS_jacobe\",\n     (PyCFunction)ETS_jacobe,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ETS_jacob0\",\n     (PyCFunction)ETS_jacob0,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ETS_fkine\",\n     (PyCFunction)ETS_fkine,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ETS_init\",\n     (PyCFunction)ETS_init,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ET_update\",\n     (PyCFunction)ET_update,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ET_init\",\n     (PyCFunction)ET_init,\n     METH_VARARGS,\n     \"Link\"},\n    {\"ET_T\",\n     (PyCFunction)ET_T,\n     METH_VARARGS,\n     \"Link\"},\n    {\"r2q\",\n     (PyCFunction)r2q,\n     METH_VARARGS,\n     \"Link\"},\n    {NULL, NULL, 0, NULL} /* Sentinel */\n};\n\nstatic struct PyModuleDef fknmmodule =\n    {\n        PyModuleDef_HEAD_INIT,\n        \"fknm\",\n        \"Fast Kinematics\",\n        -1,\n        fknmMethods};\n\nPyMODINIT_FUNC PyInit_fknm(void)\n{\n    import_array();\n    return PyModule_Create(&fknmmodule);\n}\n\nextern \"C\"\n{\n    static PyObject *IK(PyObject *self, PyObject *args)\n    {\n        npy_float64 *q, *Tep, *ret;\n        PyObject *py_q, *py_Tep;\n        PyArrayObject *py_np_q, *py_np_Tep;\n        PyObject *ets;\n        int n;\n        PyObject *py_ret;\n        npy_intp dim1[2] = {2, 4};\n\n        if (!PyArg_ParseTuple(\n                args, \"iOOO\",\n                &n,\n                &ets,\n                &py_q,\n                &py_Tep))\n            return NULL;\n\n        // Make sure q is number array\n        // Cast to numpy array\n        // Get data out\n        if (!_check_array_type(py_q))\n            return NULL;\n        py_np_q = (PyArrayObject *)PyArray_FROMANY(py_q, NPY_DOUBLE, 1, 2, NPY_ARRAY_DEFAULT);\n        q = (npy_float64 *)PyArray_DATA(py_np_q);\n\n        if (!_check_array_type(py_Tep))\n            return NULL;\n\n        py_np_Tep = (PyArrayObject *)PyArray_FROMANY(py_Tep, NPY_DOUBLE, 1, 2, NPY_ARRAY_DEFAULT);\n        Tep = (npy_float64 *)PyArray_DATA(py_np_Tep);\n\n        py_ret = PyArray_EMPTY(2, dim1, NPY_DOUBLE, 0);\n        ret = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_ret);\n\n        // __mult4(2, 4, )\n\n        _ETS_IK(ets, n, q, Tep, ret);\n\n        // _angle_axis(Te, Tep, ret);\n\n        // Free the memory\n        Py_DECREF(py_np_q);\n        Py_DECREF(py_np_Tep);\n\n        return py_ret;\n    }\n\n    static PyObject *Robot_link_T(PyObject *self, PyObject *args)\n    {\n        ETS *ets;\n        npy_float64 *q;\n        PyObject *py_q, *py_np_q;\n        PyArrayObject *py_self_q;\n        PyObject *ets_list, *T_list;\n        int q_used = 0;\n        Py_ssize_t n_links;\n\n        if (!PyArg_ParseTuple(\n                args, \"OOO!O\",\n                &ets_list,\n                &T_list,\n                &PyArray_Type, &py_self_q,\n                &py_q))\n            return NULL;\n\n        // Make sure q is number array\n        // Cast to numpy array\n        // Get data out\n        if (py_q == Py_None || !_check_array_type(py_q))\n        {\n            q = (npy_float64 *)PyArray_DATA(py_self_q);\n        }\n        else\n        {\n            py_np_q = (PyObject *)PyArray_FROMANY(py_q, NPY_DOUBLE, 1, 2, NPY_ARRAY_DEFAULT);\n            q = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_q);\n            q_used = 1;\n        }\n\n        n_links = PyList_GET_SIZE(ets_list);\n        for (int i = 0; i < n_links; i++)\n        {\n            PyObject *py_ets = PyList_GET_ITEM(ets_list, i);\n            // Extract the ETS object from the python object\n            if (!(ets = (ETS *)PyCapsule_GetPointer(py_ets, \"ETS\")))\n                return NULL;\n\n            npy_float64 *T = (npy_float64 *)PyArray_DATA((PyArrayObject *)PyList_GET_ITEM(T_list, i));\n            MapMatrix4dc eT(T);\n\n            // TODO Add this back\n            _ETS_fkine(ets, q, NULL, NULL, eT);\n        }\n\n        // Free the memory\n        if (q_used)\n        {\n            Py_DECREF(py_np_q);\n        }\n\n        Py_RETURN_NONE;\n    }\n\n    static PyObject *ETS_hessian0(PyObject *self, PyObject *args)\n    {\n        ETS *ets;\n        npy_float64 *H, *J, *q, *tool = NULL;\n        PyObject *py_q, *py_J, *py_tool, *py_np_q, *py_np_tool, *py_np_J;\n        PyObject *py_ets;\n        int tool_used = 0, J_used = 0, q_used = 0;\n\n        if (!PyArg_ParseTuple(\n                args, \"OOOO\",\n                &py_ets,\n                &py_q,\n                &py_J,\n                &py_tool))\n            return NULL;\n\n        // Extract the ETS object from the python object\n        if (!(ets = (ETS *)PyCapsule_GetPointer(py_ets, \"ETS\")))\n            return NULL;\n\n        MapMatrixJc eJ(NULL, 6, ets->n);\n\n        // Check if J is None\n        // Make sure J is number array\n        // Cast to numpy array\n        // Get data out\n        if (py_J != Py_None)\n        {\n            if (!_check_array_type(py_J))\n                return NULL;\n            J_used = 1;\n            py_np_J = (PyObject *)PyArray_FROMANY(py_J, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n            J = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_J);\n            // MapMatrixJc eJ(J, 6, ets->n);\n            new (&eJ) MapMatrixJc(J, 6, ets->n);\n        }\n        else\n        {\n            // Now we must use q instead\n            // Make sure q is number array\n            // Cast to numpy array\n            // Get data out\n            if (!_check_array_type(py_q))\n                return NULL;\n            q_used = 1;\n            py_np_q = (PyObject *)PyArray_FROMANY(py_q, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n            q = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_q);\n\n            // Make our empty Jacobian\n            npy_intp dimsJ[2] = {6, ets->n};\n            PyObject *py_J = PyArray_EMPTY(2, dimsJ, NPY_DOUBLE, 1);\n            J = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_J);\n            // MapMatrixJc eJ(J, 6, ets->n);\n            new (&eJ) MapMatrixJc(J, 6, ets->n);\n\n            // Check if tool is None\n            // Make sure tool is number array\n            // Cast to numpy array\n            // Get data out\n            if (py_tool != Py_None)\n            {\n                if (!_check_array_type(py_tool))\n                    return NULL;\n                tool_used = 1;\n                py_np_tool = (PyObject *)PyArray_FROMANY(py_tool, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n                tool = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_tool);\n            }\n\n            // Calculate the Jacobian\n            _ETS_jacob0(ets, q, tool, eJ);\n        }\n\n        // Make our empty Hessian\n        npy_intp dimsH[3] = {ets->n, 6, ets->n};\n        PyObject *py_H = PyArray_EMPTY(3, dimsH, NPY_DOUBLE, 0);\n        H = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_H);\n        MapMatrixHr eH(H, ets->n * 6, ets->n);\n\n        // Do the job\n        _ETS_hessian(ets->n, eJ, eH);\n\n        // Free the memory\n        if (q_used)\n        {\n            Py_DECREF(py_np_q);\n        }\n\n        if (J_used)\n        {\n            Py_DECREF(py_np_J);\n        }\n\n        if (tool_used)\n        {\n            Py_DECREF(py_np_tool);\n        }\n\n        return py_H;\n        // return Py_None;\n    }\n\n    static PyObject *ETS_hessiane(PyObject *self, PyObject *args)\n    {\n        ETS *ets;\n        npy_float64 *H, *J, *q, *tool = NULL;\n        PyObject *py_q, *py_J, *py_tool, *py_np_q, *py_np_tool, *py_np_J;\n        PyObject *py_ets;\n        int tool_used = 0, J_used = 0, q_used = 0;\n\n        if (!PyArg_ParseTuple(\n                args, \"OOOO\",\n                &py_ets,\n                &py_q,\n                &py_J,\n                &py_tool))\n            return NULL;\n\n        // Extract the ETS object from the python object\n        if (!(ets = (ETS *)PyCapsule_GetPointer(py_ets, \"ETS\")))\n            return NULL;\n\n        MapMatrixJc eJ(NULL, 6, ets->n);\n\n        // Check if J is None\n        // Make sure J is number array\n        // Cast to numpy array\n        // Get data out\n        if (py_J != Py_None)\n        {\n            if (!_check_array_type(py_J))\n                return NULL;\n            J_used = 1;\n            py_np_J = (PyObject *)PyArray_FROMANY(py_J, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n            J = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_J);\n            // MapMatrixJc eJ(J, 6, ets->n);\n            new (&eJ) MapMatrixJc(J, 6, ets->n);\n        }\n        else\n        {\n            // Now we must use q instead\n            // Make sure q is number array\n            // Cast to numpy array\n            // Get data out\n            if (!_check_array_type(py_q))\n                return NULL;\n            q_used = 1;\n            py_np_q = (PyObject *)PyArray_FROMANY(py_q, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n            q = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_q);\n\n            // Make our empty Jacobian\n            npy_intp dimsJ[2] = {6, ets->n};\n            PyObject *py_J = PyArray_EMPTY(2, dimsJ, NPY_DOUBLE, 1);\n            J = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_J);\n            // MapMatrixJc eJ(J, 6, ets->n);\n            new (&eJ) MapMatrixJc(J, 6, ets->n);\n\n            // Check if tool is None\n            // Make sure tool is number array\n            // Cast to numpy array\n            // Get data out\n            if (py_tool != Py_None)\n            {\n                if (!_check_array_type(py_tool))\n                    return NULL;\n                tool_used = 1;\n                py_np_tool = (PyObject *)PyArray_FROMANY(py_tool, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n                tool = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_tool);\n            }\n\n            // Calculate the Jacobian\n            _ETS_jacobe(ets, q, tool, eJ);\n        }\n\n        // Make our empty Hessian\n        npy_intp dimsH[3] = {ets->n, 6, ets->n};\n        PyObject *py_H = PyArray_EMPTY(3, dimsH, NPY_DOUBLE, 0);\n        H = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_H);\n        MapMatrixHr eH(H, ets->n * 6, ets->n);\n\n        // Do the job\n        _ETS_hessian(ets->n, eJ, eH);\n\n        // Free the memory\n        if (q_used)\n        {\n            Py_DECREF(py_np_q);\n        }\n\n        if (J_used)\n        {\n            Py_DECREF(py_np_J);\n        }\n\n        if (tool_used)\n        {\n            Py_DECREF(py_np_tool);\n        }\n\n        return py_H;\n        // return Py_None;\n    }\n\n    static PyObject *ETS_jacob0(PyObject *self, PyObject *args)\n    {\n        ETS *ets;\n        npy_float64 *J, *q, *tool = NULL;\n        PyObject *py_q, *py_tool, *py_np_q, *py_np_tool;\n        PyObject *py_ets;\n        int tool_used = 0;\n\n        if (!PyArg_ParseTuple(\n                args, \"OOO\",\n                &py_ets,\n                &py_q,\n                &py_tool))\n            return NULL;\n\n        // Extract the ETS object from the python object\n        if (!(ets = (ETS *)PyCapsule_GetPointer(py_ets, \"ETS\")))\n            return NULL;\n\n        // Inputs can be:\n        // None - Even q\n        // Not arrays - Will raise exception\n        // Have symbolic data - Will raise exception\n        // q can be 1D or 2D, assumes dimesnions correct (n, 1xn or nx1)\n        // tool can be SE3s or 4x4 numpy array\n\n        // Make our empty Jacobian\n        npy_intp dims[2] = {6, ets->n};\n        PyObject *py_J = PyArray_EMPTY(2, dims, NPY_DOUBLE, 1);\n        J = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_J);\n        MapMatrixJc eJ(J, 6, ets->n);\n\n        // Make sure q is number array\n        // Cast to numpy array\n        // Get data out\n        if (!_check_array_type(py_q))\n            return NULL;\n        py_np_q = (PyObject *)PyArray_FROMANY(py_q, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n        q = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_q);\n\n        // Check if tool is None\n        // Make sure tool is number array\n        // Cast to numpy array\n        // Get data out\n        if (py_tool != Py_None)\n        {\n            if (!_check_array_type(py_tool))\n                return NULL;\n            tool_used = 1;\n            py_np_tool = (PyObject *)PyArray_FROMANY(py_tool, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n            tool = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_tool);\n        }\n\n        // Do the job\n        _ETS_jacob0(ets, q, tool, eJ);\n\n        // Free the memory\n        Py_DECREF(py_np_q);\n\n        if (tool_used)\n        {\n            Py_DECREF(py_np_tool);\n        }\n\n        return py_J;\n    }\n\n    static PyObject *ETS_jacobe(PyObject *self, PyObject *args)\n    {\n        ETS *ets;\n        npy_float64 *J, *q, *tool = NULL;\n        PyObject *py_q, *py_tool, *py_np_q, *py_np_tool;\n        PyObject *py_ets;\n        int tool_used = 0;\n\n        if (!PyArg_ParseTuple(\n                args, \"OOO\",\n                &py_ets,\n                &py_q,\n                &py_tool))\n            return NULL;\n\n        // Extract the ETS object from the python object\n        if (!(ets = (ETS *)PyCapsule_GetPointer(py_ets, \"ETS\")))\n            return NULL;\n\n        // Inputs can be:\n        // None - Even q\n        // Not arrays - Will raise exception\n        // Have symbolic data - Will raise exception\n        // q can be 1D or 2D, assumes dimesnions correct (n, 1xn or nx1)\n        // tool can be SE3s or 4x4 numpy array\n\n        // Make our empty Jacobian\n        npy_intp dims[2] = {6, ets->n};\n        PyObject *py_J = PyArray_EMPTY(2, dims, NPY_DOUBLE, 1);\n        J = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_J);\n        MapMatrixJc eJ(J, 6, ets->n);\n\n        // Make sure q is number array\n        // Cast to numpy array\n        // Get data out\n        if (!_check_array_type(py_q))\n            return NULL;\n        py_np_q = (PyObject *)PyArray_FROMANY(py_q, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n        q = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_q);\n\n        // Check if tool is None\n        // Make sure tool is number array\n        // Cast to numpy array\n        // Get data out\n        if (py_tool != Py_None)\n        {\n            if (!_check_array_type(py_tool))\n                return NULL;\n            tool_used = 1;\n            py_np_tool = (PyObject *)PyArray_FROMANY(py_tool, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n            tool = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_tool);\n        }\n\n        // Do the job\n        // for (int i = 0; i < 1000000; i++)\n        // {\n        //     _ETS_jacobe(ets, q, tool, eJ);\n        // }\n        _ETS_jacobe(ets, q, tool, eJ);\n\n        // Free the memory\n        Py_DECREF(py_np_q);\n\n        if (tool_used)\n        {\n            Py_DECREF(py_np_tool);\n        }\n\n        return py_J;\n    }\n\n    static PyObject *ETS_fkine(PyObject *self, PyObject *args)\n    {\n        ETS *ets;\n        npy_intp dim2[2] = {4, 4}, dim3[3] = {1, 4, 4};\n        int include_base, n = 0, q_nd, trajn = 1, tool_used = 0, base_used = 0;\n        npy_float64 *ret, *retp, *q, *qp, *base = NULL, *tool = NULL;\n        PyObject *py_q, *py_base, *py_tool, *py_np_q, *py_np_tool, *py_np_base;\n        PyObject *py_ret, *py_ets;\n        npy_intp *q_shape;\n\n        if (!PyArg_ParseTuple(\n                args, \"OOOOi\",\n                &py_ets,\n                &py_q,\n                &py_base,\n                &py_tool,\n                &include_base))\n            return NULL;\n\n        // Extract the ETS object from the python object\n        if (!(ets = (ETS *)PyCapsule_GetPointer(py_ets, \"ETS\")))\n            return NULL;\n\n        // Inputs can be:\n        // None - Even q\n        // Not arrays - Will raise exception\n        // Have symbolic data - Will raise exception\n        // q can be 2D or 1D, but assumes dimesnions correct (n, 1xn or nx1)\n        // base and tool can be SE3s or 4x4 numpy array\n\n        // Make sure q is number array\n        // Cast to numpy array\n        // Get data out\n        if (!_check_array_type(py_q))\n            return NULL;\n        py_np_q = (PyObject *)PyArray_FROMANY(py_q, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n        q = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_q);\n\n        // Check the dimesnions of q\n        q_nd = PyArray_NDIM((PyArrayObject *)py_np_q);\n        q_shape = PyArray_SHAPE((PyArrayObject *)py_np_q);\n\n        // Work out how long the trajectory is\n        if (q_nd > 1)\n        {\n            if (q_shape[0] == 1)\n            {\n                // We have a single q vector\n                trajn = 1;\n                n = q_shape[1];\n            }\n            else if (q_shape[1] == 1)\n            {\n                // We have a single q vector\n                trajn = 1;\n                n = q_shape[0];\n            }\n            else\n            {\n                // We have a trajectory of q\n                trajn = q_shape[0];\n                n = q_shape[1];\n            }\n        }\n\n        // Allocate return array\n        if (trajn == 1)\n        {\n            py_ret = PyArray_EMPTY(2, dim2, NPY_DOUBLE, 1);\n        }\n        else\n        {\n            dim3[0] = trajn;\n            py_ret = PyArray_EMPTY(3, dim3, NPY_DOUBLE, 1);\n        }\n\n        // Get numpy reference to return array\n        ret = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_ret);\n\n        // Check if base is None\n        // Make sure base is number array\n        // Cast to numpy array\n        // Get data out\n        if (py_base != Py_None)\n        {\n            if (!_check_array_type(py_base))\n                return NULL;\n\n            if (include_base)\n            {\n                base_used = 1;\n                py_np_base = (PyObject *)PyArray_FROMANY(py_base, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n                base = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_base);\n            }\n        }\n\n        if (py_tool != Py_None)\n        {\n            if (!_check_array_type(py_tool))\n                return NULL;\n            tool_used = 1;\n            py_np_tool = (PyObject *)PyArray_FROMANY(py_tool, NPY_DOUBLE, 1, 2, NPY_ARRAY_F_CONTIGUOUS);\n            tool = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_np_tool);\n        }\n\n        // Do the actual job\n        for (int i = 0; i < trajn; i++)\n        {\n            // Get pointers to the new section of return array and q array\n            retp = ret + (4 * 4 * i);\n            MapMatrix4dc e_retp(retp);\n            qp = q + (n * i);\n            _ETS_fkine(ets, qp, base, tool, e_retp);\n        }\n\n        // Free memory\n        Py_DECREF(py_np_q);\n\n        if (tool_used)\n            Py_DECREF(py_np_tool);\n\n        if (base_used)\n            Py_DECREF(py_np_base);\n\n        return py_ret;\n    }\n\n    static PyObject *ETS_init(PyObject *self, PyObject *args)\n    {\n        ETS *ets;\n        PyObject *etsl, *ret;\n\n        ets = (ETS *)PyMem_RawMalloc(sizeof(ETS));\n\n        if (!PyArg_ParseTuple(args, \"Oii\",\n                              &etsl,\n                              &ets->n,\n                              &ets->m))\n            return NULL;\n\n        ets->ets = (ET **)PyMem_RawMalloc(ets->m * sizeof(ET *));\n\n        PyObject *iter_et = PyObject_GetIter(etsl);\n\n        for (int i = 0; i < ets->m; i++)\n        {\n            if (!(ets->ets[i] = (ET *)PyCapsule_GetPointer(PyIter_Next(iter_et), \"ET\")))\n                return NULL;\n        }\n\n        Py_DECREF(iter_et);\n\n        ret = PyCapsule_New(ets, \"ETS\", NULL);\n        return ret;\n    }\n\n    static PyObject *ET_update(PyObject *self, PyObject *args)\n    {\n        ET *et;\n        int jointtype;\n        PyObject *ret, *py_et;\n        PyArrayObject *py_T, *py_qlim;\n        int isjoint, isflip, jindex;\n\n        et = (ET *)PyMem_RawMalloc(sizeof(ET));\n\n        if (!PyArg_ParseTuple(args, \"OiiiiO!O!\",\n                              &py_et,\n                              &isjoint,\n                              &isflip,\n                              &jindex,\n                              &jointtype,\n                              &PyArray_Type, &py_T,\n                              &PyArray_Type, &py_qlim))\n            return NULL;\n\n        if (!(et = (ET *)PyCapsule_GetPointer(py_et, \"ET\")))\n            return NULL;\n\n        et->T = (npy_float64 *)PyArray_DATA(py_T);\n        new (&et->Tm) MapMatrix4dc(et->T);\n        et->qlim = (npy_float64 *)PyArray_DATA(py_qlim);\n        et->axis = jointtype;\n\n        et->isjoint = isjoint;\n        et->isflip = isflip;\n        et->jindex = jindex;\n\n        if (jointtype == 0)\n        {\n            et->op = rx;\n        }\n        else if (jointtype == 1)\n        {\n            et->op = ry;\n        }\n        else if (jointtype == 2)\n        {\n            et->op = rz;\n        }\n        else if (jointtype == 3)\n        {\n            et->op = tx;\n        }\n        else if (jointtype == 4)\n        {\n            et->op = ty;\n        }\n        else if (jointtype == 5)\n        {\n            et->op = tz;\n        }\n\n        ret = PyCapsule_New(et, \"ET\", NULL);\n        return ret;\n    }\n\n    static PyObject *ET_init(PyObject *self, PyObject *args)\n    {\n        ET *et;\n        int jointtype;\n        PyObject *ret;\n        PyArrayObject *py_T, *py_qlim;\n\n        et = (ET *)PyMem_RawMalloc(sizeof(ET));\n\n        if (!PyArg_ParseTuple(args, \"iiiiO!O!\",\n                              &et->isjoint,\n                              &et->isflip,\n                              &et->jindex,\n                              &jointtype,\n                              &PyArray_Type, &py_T,\n                              &PyArray_Type, &py_qlim))\n            return NULL;\n\n        et->T = (npy_float64 *)PyArray_DATA(py_T);\n        new (&et->Tm) MapMatrix4dc(et->T);\n        et->qlim = (npy_float64 *)PyArray_DATA(py_qlim);\n\n        et->axis = jointtype;\n\n        if (jointtype == 0)\n        {\n            et->op = rx;\n        }\n        else if (jointtype == 1)\n        {\n            et->op = ry;\n        }\n        else if (jointtype == 2)\n        {\n            et->op = rz;\n        }\n        else if (jointtype == 3)\n        {\n            et->op = tx;\n        }\n        else if (jointtype == 4)\n        {\n            et->op = ty;\n        }\n        else if (jointtype == 5)\n        {\n            et->op = tz;\n        }\n\n        ret = PyCapsule_New(et, \"ET\", NULL);\n        return ret;\n    }\n\n    static PyObject *ET_T(PyObject *self, PyObject *args)\n    {\n        npy_intp dims[2] = {4, 4};\n        int nd = 2;\n        ET *et;\n        PyObject *py_et, *py_eta;\n        PyObject *py_ret = PyArray_EMPTY(nd, dims, NPY_DOUBLE, 1);\n        double eta = 0;\n        npy_float64 *ret;\n\n        if (!PyArg_ParseTuple(args, \"OO\", &py_et, &py_eta))\n            return NULL;\n\n        if (!(et = (ET *)PyCapsule_GetPointer(py_et, \"ET\")))\n            return NULL;\n\n        if (py_eta != Py_None)\n        {\n            if (PyFloat_Check(py_eta))\n            {\n                eta = (double)PyFloat_AsDouble(py_eta);\n            }\n            else\n            {\n                PyErr_SetString(PyExc_TypeError, \"Symbolic value\");\n                return NULL;\n            }\n        }\n\n        ret = (npy_float64 *)PyArray_DATA((PyArrayObject *)py_ret);\n        // MapMatrix4dc e_ret(ret);\n\n        _ET_T(et, ret, eta);\n\n        return py_ret;\n    }\n\n    static PyObject *r2q(PyObject *self, PyObject *args)\n    {\n        // r is actually an SE3\n        npy_float64 *r, *q;\n        PyArrayObject *py_r, *py_q;\n\n        if (!PyArg_ParseTuple(\n                args, \"O!O!\",\n                &PyArray_Type, &py_r,\n                &PyArray_Type, &py_q))\n            return NULL;\n\n        r = (npy_float64 *)PyArray_DATA(py_r);\n        q = (npy_float64 *)PyArray_DATA(py_q);\n\n        _r2q(r, q);\n\n        Py_RETURN_NONE;\n    }\n\n    int _check_array_type(PyObject *toCheck)\n    {\n        PyArray_Descr *desc;\n\n        desc = PyArray_DescrFromObject(toCheck, NULL);\n\n        // Check if desc is a number or a sympy symbol\n        if (!PyDataType_ISNUMBER(desc))\n        {\n            PyErr_SetString(PyExc_TypeError, \"Symbolic value\");\n            return 0;\n        }\n\n        return 1;\n    }\n\n    void rx(npy_float64 *data, double eta)\n    {\n        double st, ct;\n\n        ct = cos(eta);\n        st = sin(eta);\n\n        data[0] = 1;\n        data[4] = 0;\n        data[8] = 0;\n        data[12] = 0;\n        data[1] = 0;\n        data[5] = ct;\n        data[9] = -st;\n        data[13] = 0;\n        data[2] = 0;\n        data[6] = st;\n        data[10] = ct;\n        data[14] = 0;\n        data[3] = 0;\n        data[7] = 0;\n        data[11] = 0;\n        data[15] = 1;\n\n        // data[0] = 1;\n        // data[1] = 0;\n        // data[2] = 0;\n        // data[3] = 0;\n        // data[4] = 0;\n        // data[5] = ct;\n        // data[6] = -st;\n        // data[7] = 0;\n        // data[8] = 0;\n        // data[9] = st;\n        // data[10] = ct;\n        // data[11] = 0;\n        // data[12] = 0;\n        // data[13] = 0;\n        // data[14] = 0;\n        // data[15] = 1;\n    }\n\n    void ry(npy_float64 *data, double eta)\n    {\n        double st, ct;\n\n        ct = cos(eta);\n        st = sin(eta);\n\n        data[0] = ct;\n        data[4] = 0;\n        data[8] = st;\n        data[12] = 0;\n        data[1] = 0;\n        data[5] = 1;\n        data[9] = 0;\n        data[13] = 0;\n        data[2] = -st;\n        data[6] = 0;\n        data[10] = ct;\n        data[14] = 0;\n        data[3] = 0;\n        data[7] = 0;\n        data[11] = 0;\n        data[15] = 1;\n\n        // data[0] = ct;\n        // data[1] = 0;\n        // data[2] = st;\n        // data[3] = 0;\n        // data[4] = 0;\n        // data[5] = 1;\n        // data[6] = 0;\n        // data[7] = 0;\n        // data[8] = -st;\n        // data[9] = 0;\n        // data[10] = ct;\n        // data[11] = 0;\n        // data[12] = 0;\n        // data[13] = 0;\n        // data[14] = 0;\n        // data[15] = 1;\n    }\n\n    void rz(npy_float64 *data, double eta)\n    {\n        double st, ct;\n\n        ct = cos(eta);\n        st = sin(eta);\n\n        data[0] = ct;\n        data[4] = -st;\n        data[8] = 0;\n        data[12] = 0;\n        data[1] = st;\n        data[5] = ct;\n        data[9] = 0;\n        data[13] = 0;\n        data[2] = 0;\n        data[6] = 0;\n        data[10] = 1;\n        data[14] = 0;\n        data[3] = 0;\n        data[7] = 0;\n        data[11] = 0;\n        data[15] = 1;\n\n        // data[0] = ct;\n        // data[1] = -st;\n        // data[2] = 0;\n        // data[3] = 0;\n        // data[4] = st;\n        // data[5] = ct;\n        // data[6] = 0;\n        // data[7] = 0;\n        // data[8] = 0;\n        // data[9] = 0;\n        // data[10] = 1;\n        // data[11] = 0;\n        // data[12] = 0;\n        // data[13] = 0;\n        // data[14] = 0;\n        // data[15] = 1;\n    }\n\n    void tx(npy_float64 *data, double eta)\n    {\n        data[0] = 1;\n        data[1] = 0;\n        data[2] = 0;\n        data[12] = eta;\n        data[4] = 0;\n        data[5] = 1;\n        data[6] = 0;\n        data[7] = 0;\n        data[8] = 0;\n        data[9] = 0;\n        data[10] = 1;\n        data[11] = 0;\n        data[3] = 0;\n        data[13] = 0;\n        data[14] = 0;\n        data[15] = 1;\n\n        // data[0] = 1;\n        // data[1] = 0;\n        // data[2] = 0;\n        // data[3] = eta;\n        // data[4] = 0;\n        // data[5] = 1;\n        // data[6] = 0;\n        // data[7] = 0;\n        // data[8] = 0;\n        // data[9] = 0;\n        // data[10] = 1;\n        // data[11] = 0;\n        // data[12] = 0;\n        // data[13] = 0;\n        // data[14] = 0;\n        // data[15] = 1;\n    }\n\n    void ty(npy_float64 *data, double eta)\n    {\n        data[0] = 1;\n        data[1] = 0;\n        data[2] = 0;\n        data[3] = 0;\n        data[4] = 0;\n        data[5] = 1;\n        data[6] = 0;\n        data[13] = eta;\n        data[8] = 0;\n        data[9] = 0;\n        data[10] = 1;\n        data[11] = 0;\n        data[12] = 0;\n        data[7] = 0;\n        data[14] = 0;\n        data[15] = 1;\n\n        // data[0] = 1;\n        // data[1] = 0;\n        // data[2] = 0;\n        // data[3] = 0;\n        // data[4] = 0;\n        // data[5] = 1;\n        // data[6] = 0;\n        // data[7] = eta;\n        // data[8] = 0;\n        // data[9] = 0;\n        // data[10] = 1;\n        // data[11] = 0;\n        // data[12] = 0;\n        // data[13] = 0;\n        // data[14] = 0;\n        // data[15] = 1;\n    }\n\n    void tz(npy_float64 *data, double eta)\n    {\n        data[0] = 1;\n        data[1] = 0;\n        data[2] = 0;\n        data[3] = 0;\n        data[4] = 0;\n        data[5] = 1;\n        data[6] = 0;\n        data[7] = 0;\n        data[8] = 0;\n        data[9] = 0;\n        data[10] = 1;\n        data[14] = eta;\n        data[12] = 0;\n        data[13] = 0;\n        data[11] = 0;\n        data[15] = 1;\n\n        // data[0] = 1;\n        // data[1] = 0;\n        // data[2] = 0;\n        // data[3] = 0;\n        // data[4] = 0;\n        // data[5] = 1;\n        // data[6] = 0;\n        // data[7] = 0;\n        // data[8] = 0;\n        // data[9] = 0;\n        // data[10] = 1;\n        // data[11] = eta;\n        // data[12] = 0;\n        // data[13] = 0;\n        // data[14] = 0;\n        // data[15] = 1;\n    }\n\n} /* extern \"C\" */", "meta": {"hexsha": "9da690a8f10761ff2db6c25316ce5b680c6082a9", "size": 29416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "roboticstoolbox/core/fknm.cpp", "max_stars_repo_name": "Russ76/robotics-toolbox-python", "max_stars_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "roboticstoolbox/core/fknm.cpp", "max_issues_repo_name": "Russ76/robotics-toolbox-python", "max_issues_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "roboticstoolbox/core/fknm.cpp", "max_forks_repo_name": "Russ76/robotics-toolbox-python", "max_forks_repo_head_hexsha": "4b3e82a6522757ffde1f83aef8d05b3ad475e9de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4532374101, "max_line_length": 108, "alphanum_fraction": 0.4635232527, "num_tokens": 8701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03567855036504725, "lm_q1q2_score": 0.017142782714063574}}
{"text": "\n#include <libs/util/util.hpp>\n\n#include <boost/algorithm/string.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <deque>\n\nnamespace util {\n\ndouble interpolate(const std::vector<double> &x, const std::vector<double> &y, const double x_n)\n{\n  // If x_n is outside, return extreme\n  if(x_n <= *x.cbegin())  { return *y.cbegin(); }\n  if(x_n >= *x.crbegin()) { return *y.crbegin(); }\n\n  for(size_t i = 0; i < x.size()-1; ++i) {\n    if(x_n >= x[i] && x_n < x[i+1]) {\n      double m = (y[i+1] - y[i])/(x[i+1] - x[i]);\n      return y[i] + m*(x_n - x[i]);\n    }\n  }\n\n  return 0.0;\n}\n\nstd::vector<std::string> read_text_from_file(const std::string& filename)\n{\n  std::vector<std::string> text;\n  std::ifstream ifs;\n  ifs.open(filename, std::ifstream::in);\n\n  std::string line;\n  while(std::getline(ifs, line)) {\n    text.push_back(line);\n  }\n\n  ifs.close();\n  return text;\n}\n\nstd::map<std::string, std::vector<double>> read_data_from_csv(const std::string& csv_file)\n{\n  // Read all lines fom file\n  std::vector<std::string> text = read_text_from_file(csv_file);\n\n  // Parse first line (i.e. the header) to get column names\n  std::string header = text[0];\n  text.erase(text.begin());\n\n  std::vector<std::string> columns;\n  boost::split(columns, header, boost::is_any_of(\",\"));\n\n  // Parse each line of file to get data\n  std::vector<std::vector<double>> raw_data;\n  for(size_t i = 0; i < columns.size(); ++i)\n    raw_data.push_back(std::vector<double>());\n\n  for(auto &line : text) {\n    std::vector<std::string> data_str;\n    boost::algorithm::trim(line);\n    boost::split(data_str, line, boost::is_any_of(\",\"));\n\n    for(size_t i = 0; i < data_str.size(); ++i) {\n      raw_data[i].push_back(std::stod(data_str[i]));\n    }\n  }\n\n  // Combine header and data in single container\n  std::map<std::string, std::vector<double>> data;\n  for(size_t i = 0; i < columns.size(); ++i) {\n    boost::algorithm::trim(columns[i]);\n    data[columns[i]] = raw_data[i];\n  }\n  return data;\n}\n\nvoid write_data_to_csv(const std::string &csv_file, std::map<std::string, std::vector<double>> data)\n{\n  std::ofstream ofs;\n  ofs.open(csv_file, std::ios::out | std::ios::trunc);\n\n  // Parse column names and write first line (header)\n  std::vector<std::string> headers;\n  for(auto const &x : data) {\n    headers.push_back(x.first);\n    ofs << x.first;\n    if(x.first == data.rbegin()->first) {\n      ofs << \"\\n\";\n    } else {\n      ofs << \",\";\n    }\n  }\n\n  // Use smallest vector of data if they aren't the same size.\n  size_t n = (*std::min_element(data.begin(), data.end(), [](\n    const std::pair<std::string, std::vector<double>> &i,\n    const std::pair<std::string, std::vector<double>> &j)\n    { return i.second.size() < j.second.size(); })).second.size();\n\n  // Write data to file\n  for(size_t i = 0; i < n ; ++i) {\n    for(const auto &name : headers) {\n      ofs << data[name][i];\n      if(name == (*headers.rbegin())) {\n        ofs << \"\\n\";\n      } else {\n        ofs << \",\";\n      }\n    }\n  }\n\n  ofs.close();\n}\n\n// Credit: Tatu Ylonen <ylo@cs.hut.di>\n// See: https://opensource.apple.com/source/OpenSSH/OpenSSH-7.1/openssh/ttymodes.c?txt\nint speed_to_baud(speed_t speed)\n{\n\tswitch (speed) {\n\tcase B0:\n\t\treturn 0;\n\tcase B50:\n\t\treturn 50;\n\tcase B75:\n\t\treturn 75;\n\tcase B110:\n\t\treturn 110;\n\tcase B134:\n\t\treturn 134;\n\tcase B150:\n\t\treturn 150;\n\tcase B200:\n\t\treturn 200;\n\tcase B300:\n\t\treturn 300;\n\tcase B600:\n\t\treturn 600;\n\tcase B1200:\n\t\treturn 1200;\n\tcase B1800:\n\t\treturn 1800;\n\tcase B2400:\n\t\treturn 2400;\n\tcase B4800:\n\t\treturn 4800;\n\tcase B9600:\n\t\treturn 9600;\n\n#ifdef B19200\n\tcase B19200:\n\t\treturn 19200;\n#else // B19200\n#ifdef EXTA\n\tcase EXTA:\n\t\treturn 19200;\n#endif // EXTA\n#endif // B19200\n\n#ifdef B38400\n\tcase B38400:\n\t\treturn 38400;\n#else // B38400\n#ifdef EXTB\n\tcase EXTB:\n\t\treturn 38400;\n#endif // EXTB\n#endif // B38400\n\n#ifdef B7200\n\tcase B7200:\n\t\treturn 7200;\n#endif // B7200\n#ifdef B14400\n\tcase B14400:\n\t\treturn 14400;\n#endif // B14400\n#ifdef B28800\n\tcase B28800:\n\t\treturn 28800;\n#endif // B28800\n#ifdef B57600\n\tcase B57600:\n\t\treturn 57600;\n#endif // B57600\n#ifdef B76800\n\tcase B76800:\n\t\treturn 76800;\n#endif // B76800\n#ifdef B115200\n\tcase B115200:\n\t\treturn 115200;\n#endif // B115200\n#ifdef B230400\n\tcase B230400:\n\t\treturn 230400;\n#endif // B230400\n\tdefault:\n\t\treturn 9600;\n\t}\n}\n\n} // namespace util\n", "meta": {"hexsha": "ac517e76f47cfee772f5fc7ab1bdd0aba165eace", "size": 4286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/util/src/util.cpp", "max_stars_repo_name": "pdsherman/pendulum", "max_stars_repo_head_hexsha": "ed3e708e8cd66c1a7d5282110b4ceb94492c460f", "max_stars_repo_licenses": ["MIT"], "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/util/src/util.cpp", "max_issues_repo_name": "pdsherman/pendulum", "max_issues_repo_head_hexsha": "ed3e708e8cd66c1a7d5282110b4ceb94492c460f", "max_issues_repo_licenses": ["MIT"], "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/util/src/util.cpp", "max_forks_repo_name": "pdsherman/pendulum", "max_forks_repo_head_hexsha": "ed3e708e8cd66c1a7d5282110b4ceb94492c460f", "max_forks_repo_licenses": ["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.9073170732, "max_line_length": 100, "alphanum_fraction": 0.6257582828, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.035678548570655874, "lm_q1q2_score": 0.017142781851896778}}
{"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_TAG_INCLUDE\n#define MTL_TAG_INCLUDE\n\n#include <boost/numeric/mtl/utility/glas_tag.hpp>\n\n\nnamespace mtl { namespace tag {\n\n/** @defgroup Tags Tags for concept-free dispatching\n *  @{\n */\n\n// For internal use (e.g., to invalidate range generators)\n// Is this the same as bottom?\nstruct unsupported {};\n\n// Name says it\nstruct dummy3 {};\nstruct dummy4 {};\n\n/// Tag for all types\nstruct universe {};\n\n/// Tag used to flatten categories\n/** The virtual derivation causes perceivable run-time overhead that can be avoided with this struct using traits::flatcat1 and such. **/\ntemplate <typename T> struct flat : universe {};\n\n// Tag for any scalar value\n/** At the moment default for unknown types (will be precised later) */\nstruct scalar : virtual universe {};\n\n/// For non-MTL types with category not explicitly defined\n/** At the moment all treated as scalars (will be precised later) */\nstruct unknown : virtual scalar {};\n\n/// Tag for intermediate objects that require explicit evaluation \nstruct unevaluated : virtual universe {};\n\n/// Any collection, i.e. vectors, matrices or higher-dimensional tensor\nstruct collection : virtual universe {};\n\n/// Tag for any MTL vector (and user-declared MTL vectors)\nstruct vector : virtual collection {};\n\n/// Tag for references to vector\n/** For instance to not access memory directly but use functions, e.g. in set_to_zero. **/ \nstruct vector_ref : virtual vector {};\n\n/// Tag for any MTL column vector (and user-declared MTL vectors)\nstruct col_vector : virtual vector {};\n\n/// Tag for any MTL row vector (and user-declared MTL vectors)\nstruct row_vector : virtual vector {};\n\n/// Tag for any MTL matrix (and user-declared MTL matrices)\nstruct matrix : virtual collection {};\n\n/// Tag for any dense collection\nstruct dense : virtual universe {};\n    \n/// Tag for vectors with one-dimensional memory addressing\n/** offet v_i is x*i for some x */\nstruct has_1D_layout : virtual dense {};\n    \n/// Tag for matrices with two-dimensional memory addressing\n/** offet a_ij is x*i + y*j for some x and y */\nstruct has_2D_layout : virtual dense {};\n    \n/// Tag for any sparse collection\nstruct sparse : virtual universe {};\n    \n// for distinction between dense and sparse matrices\nstruct dense_matrix : virtual dense, virtual matrix {};\nstruct sparse_matrix : virtual sparse, virtual matrix {};\n\n/// Tag for collections where values are stored contigously in memory\nstruct contiguous_memory : virtual universe {};\n\n/// Tag for dense and contiguous collections\n/** Only short cut */\nstruct contiguous_dense : virtual dense, virtual contiguous_memory {};\n\n/// Collection with iterator\nstruct has_iterator : virtual universe {};\n\n/// Collection with random-access iterator\nstruct has_ra_iterator : virtual has_iterator {};\n\n/// Collection with fast random-access iterator\n/** Meaning: unrolling is probably beneficial. Counter-example: Morton-ordered matrices have\n    random access but this is so slow that regular traversal is favorable */\nstruct has_fast_ra_iterator : virtual has_ra_iterator {};\n\n/// Collection with cursor\nstruct has_cursor : virtual universe {};\n\n/// Collection with random-access cursor\nstruct has_ra_cursor : virtual has_cursor {};\n\n/// Collection with fast random-access cursor\n/** Meaning: unrolling is probably beneficial. Counter-example: Morton-ordered matrices have\n    random access but this is so slow that regular traversal is favorable */\nstruct has_fast_ra_cursor : virtual has_ra_cursor {};\n\n/// Tag for matrices with sub_matrix function exist and doesn't say for which ranges it is defined\nstruct has_sub_matrix : virtual universe {};\n\n/// Sub-divisible into quadrants, i.e. arbitrary sub-matrices not necessarily supported but recursion works\n//  more explanation needed\nstruct qsub_divisible : virtual has_sub_matrix {};\n\n/// Tag for sub-divisible matrix, i.e. sub_matrix works \nstruct sub_divisible : virtual qsub_divisible {};\n\n/// Tag for dense row vector in the category lattice\nstruct dense_row_vector\n  : virtual row_vector, virtual contiguous_dense, \n    virtual has_fast_ra_iterator, virtual has_fast_ra_cursor, virtual has_1D_layout\n{};\n\n/// Tag for dense column vector in the category lattice\nstruct dense_col_vector\n  : virtual col_vector, virtual contiguous_dense, \n    virtual has_fast_ra_iterator, virtual has_fast_ra_cursor, virtual has_1D_layout\n{};\n\n/// Tag for strided row vector in the category lattice\nstruct strided_row_vector\n  : virtual row_vector, virtual vector_ref,\n    virtual has_fast_ra_iterator, virtual has_fast_ra_cursor, virtual has_1D_layout\n{};\n\n/// Tag for strided column vector in the category lattice\nstruct strided_col_vector\n  : virtual col_vector, virtual vector_ref, \n    virtual has_fast_ra_iterator, virtual has_fast_ra_cursor, virtual has_1D_layout\n{};\n\n/// Tag for sparse row vector in the category lattice\nstruct sparse_row_vector\n  : virtual row_vector, virtual sparse\n{};\n\n/// Tag for sparse column vector in the category lattice\nstruct sparse_col_vector\n  : virtual col_vector, virtual sparse\n{};\n\n/// Tag to handle std::vector in the category lattice\nstruct std_vector\n  : virtual vector, virtual contiguous_dense, virtual has_1D_layout\n{};\n\n/// Tag for a view on a (regular) dense matrix in the category lattice\n/** The map perform address computation and has therefore no 2D-layout.\n    It is also not (yet) assumed that the view provides iterators. */\nstruct dense2D_view \n  : virtual matrix, virtual contiguous_dense, virtual has_fast_ra_cursor \n    // , virtual sub_divisible // is currently not sub-divisible\n{};\n\n/// Tag for (regular) dense matrix in the category lattice\nstruct dense2D \n  : virtual dense2D_view, virtual has_fast_ra_iterator, virtual has_2D_layout, virtual sub_divisible\n{};\n\nstruct implicit_dense\n  : virtual matrix, virtual dense, virtual has_fast_ra_cursor\n{};\n\n/// Tag for a view on a Morton-order matrix in the category lattice\n/** It is not (yet) assumed that the view provides iterators. */\nstruct morton_view \n  : virtual matrix, virtual contiguous_dense,  \n    virtual has_ra_cursor // , virtual qsub_divisible // is currently not sub-divisible\n{};\n\n\n/// Tag for Morton-order matrix in the category lattice\nstruct morton_dense \n  : virtual morton_view, virtual has_ra_iterator, virtual qsub_divisible\n{};\n\n/// Tag for a view on a compressed matrix in the category lattice\n/** It is not (yet) assumed that the view provides iterators. */\nstruct compressed2D_view\n  : virtual matrix, virtual sparse, virtual has_cursor\n{};\n\n/// Tag for compressed matrix in the category lattice\nstruct compressed2D \n  : virtual compressed2D_view, virtual has_iterator\n{};\n\n/// Tag for multi_vector\n// Maybe splitting later into sparse and dense form\nstruct multi_vector\n  : virtual matrix, virtual dense\n{};\n\n/// Tag for transposed multi_vector\n// Maybe splitting later into sparse and dense form\nstruct transposed_multi_vector\n  : virtual matrix, virtual dense\n{};\n\n/// Tag for transposed multi_vector\n// Maybe splitting later into sparse and dense form\nstruct hermitian_multi_vector\n  : virtual matrix, virtual dense\n{};\n\n/// Tag for ell_matrix (preliminary)\nstruct ell_matrix\n  : sparse_matrix\n{};\n\n/// Tag for element structure matrix\nstruct element_structure\n  : sparse_matrix\n{};\n\n/// Tag for element structure matrix\nstruct sparse_banded_matrix\n  : sparse_matrix\n{};\n\n/// Tag for mat_cvec_multiplier\nstruct mat_cvec_multiplier\n  : col_vector\n{};\n\n/// Tag for implicit dense matrices\n\n\n/// Tag for bottom of the category lattice\n/** Only for completeness; probably not needed in practice. */\nstruct bottom\n  : virtual compressed2D, virtual morton_dense, virtual dense2D, \n    virtual dense_col_vector, virtual dense_row_vector, virtual unknown,\n    virtual multi_vector\n{};\n\ntemplate <typename Tag1, typename Tag2, typename Tag3= dummy3, typename Tag4= dummy4>\nstruct join\n  : virtual Tag1, virtual Tag2, virtual Tag3, virtual Tag4\n{};\n\n\n// =====================\n// Types for orientation\n// =====================\n\n\n/// Characterizes row-major orientation in matrices and row vector in 1D\nstruct row_major {};\n\n/// Characterizes column-major orientation in matrices and column vector in 1D\nstruct col_major {};\n\n/// Common base for diagonal tags\nstruct universe_diagonal {};\n\n/// Tag indicating that diagonal is stored regularly\nstruct regular_diagonal : universe_diagonal {};\n\n/// Tag indicating that diagonal contains unit elements\nstruct unit_diagonal : universe_diagonal {};\n\n/// Tag indicating that diagonal entries are stored as inverses\n/** Storing value in different ways can be faster in several algorithms.\n    By the time of this writing it is experimental and only used\n    in upper_trisolve and lower_trisolve. **/\nstruct inverse_diagonal : universe_diagonal {};\n\n\n\n\n/*@}*/ // end of group Tags\n\n} // namespace mtl::tag\n\n/** @addtogroup Tags\n *  @{\n */\n\n/// Characterizes row-major orientation in matrices and row vector in 1D\nusing tag::row_major;\n\n/// Characterizes column-major orientation in matrices and column vector in 1D\nusing tag::col_major;\n\n\n\n/*@}*/ // end of group Tags\n\n// =====================\n// Tags for traversals\n// Import some from GLAS\n// =====================\n\nnamespace tag {\n\n/** @addtogroup Tags\n *  @{\n */\n\n    /// Tag for cursor traversal of non-zero elements of a collection\n    /** Also used for elements within rows and columns */\n    using glas::tag::nz;\n\n    /// Tag for cursor traversal of all elements of a collection\n    /** Also used for elements within rows and columns */\n    using glas::tag::all;\n\n    /// Tag for traversal of all rows in a matrix\n    using glas::tag::row;\n    /// Tag for traversal of all columns in a matrix\n    using glas::tag::col;\n\n    /// Tag for traversal of a matrix's major dimension\n    /** Is equivalent to glas::tag::row for row-major matrices and \n\tglas::tag::col for column-major matrices */\n    using glas::tag::major;\n\n    /// Tag for traversal of a matrix's minor dimension\n    /** Is equivalent to glas::tag::row for row-major matrices and \n\tglas::tag::col for column-major matrices */\n    using glas::tag::minor;\n\n    // To define iterators over matrices or rows/cols of it, vectors\n\n    namespace iter {\n\n\t/// Tag for iterator traversal of non-zero elements of a collection\n\t/** Also used for elements within rows and columns */\n\tstruct nz {};\n\n\t/// Tag for iterator traversal of all elements of a collection\n\t/** Also used for elements within rows and columns */\n\tstruct all {};\n\n    } // namespace mtl::tag::iter\n\n    // Same with const iterators\n\n    namespace const_iter {\n\n\t/// Tag for const-iterator traversal of non-zero elements of a collection\n\t/** Also used for elements within rows and columns */\n\tstruct nz {};\n\n\t/// Tag for const-iterator traversal of all elements of a collection\n\t/** Also used for elements within rows and columns */\n\tstruct all {};\n\n    } // namespace mtl::tag::const_iter\n\n/*@}*/ // end of group Tags\n\n} // namespace mtl::tag\n\n\n} // namespace mtl\n\n#endif // MTL_TAG_INCLUDE\n", "meta": {"hexsha": "0b3da34e5f252e67f7d00bae03a0eca22dfb80ff", "size": 11396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/utility/tag.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/utility/tag.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/utility/tag.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.0686015831, "max_line_length": 137, "alphanum_fraction": 0.7344682345, "num_tokens": 2499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.044018646570903076, "lm_q1q2_score": 0.017106439568646537}}
{"text": "/* Copyright (c) 2019, Acme Robotics, Ethan Quist, Corbyn Yhap\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 <organization> 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 <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 * @file DHTable.hpp\n *\n * @brief The class header for our DH Table Class\n *\n * @author Corbyn Yhap (driver) and Ethan Quist (Navigator)\n *\n * @copyright Acme Robotics, Ethan Quist, Corbyn Yhap\n */\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <memory>\n#include <vector>\n\n#include \"PrismaticJoint.hpp\"\n#include \"RevoluteJoint.hpp\"\n\n\n\n\nclass DHTable {\n public:\n  // Default values prevent these pointers from being null.\n  struct Frame {\n    std::shared_ptr<PrismaticJoint> d = std::make_shared<PrismaticJoint>(\n        PrismaticJoint());\n    std::shared_ptr<RevoluteJoint> theta = std::make_shared<RevoluteJoint>(\n        RevoluteJoint());\n    std::shared_ptr<PrismaticJoint> a = std::make_shared<PrismaticJoint>(\n        PrismaticJoint());\n    std::shared_ptr<RevoluteJoint> alpha = std::make_shared<RevoluteJoint>(\n        RevoluteJoint());\n  };\n\n  /**\n\n   * @brief DHTable Constructor with no Parameters.\n\n   * @param None.\n\n   * @return None.\n\n   */\n  DHTable();\n\n  /**\n\n   * @brief Destructor for the DHTable Class\n\n   * @param None.\n\n   * @return None.\n\n   */\n  ~DHTable();\n\n  /**\n\n   * @brief addFrame Method for the user to describe the Robot\n   * The Frame access is 1 indexed. (Preserving 0 for the\n   *  base frame) Frames must be added in the order of relation. i.e. frame 1\n   *  describes the relationship from frame 0 to frame 1 and frame 2 the\n   *  relationship from frame 1 to frame 2.\n\n   * @param const Frame &, The Frame that will be added to the DH Table\n\n   * @return None.\n\n   */\n  void addFrame(const Frame&);\n\n  /**\n\n   * @brief getFrame returns a copy of the frame that was stored\n\n   * @param std::vector<Frame>::size_type 1 Indexed index of desired frame\n\n   * @return A copy of the frame.\n\n   */\n  Frame getFrame(std::vector<Frame>::size_type);\n\n  /**\n\n   * @brief getTransform This function returns the Transformation Matrix from\n   *  one frame to the another. Currently it is required that the first frame\n   *  must precede the second frame.\n\n   * @param size_type,  The index of the frame being transformed from.\n\n   * @param size_type,  The index of the frame being transformed to.\n\n   * @return Eigen::Matrix4d The Transformation Matrix to go from frame one to\n   * frame two.\n\n   */\n  Eigen::Matrix4d getTransform(std::vector<Frame>::size_type,\n                               std::vector<Frame>::size_type);\n\n private:\n  std::vector<Frame> frames;\n  /**\n\n   * @brief getTransform This function acts as a helper by taking the index of\n   * a frame, retrieving that frame and then using those parameters to build a\n   * tranformation matrix.\n\n   * @param size_type,  The index of the frame being transformed to. This\n   * function assumed that the tranform from is from the frame that preceded it.\n\n\n   * @return Eigen::Matrix4d The Transformation Matrix to go to frame index from\n   * the previous frame.\n\n   */\n  Eigen::Matrix4d getTransform(std::vector<Frame>::size_type);\n};\n", "meta": {"hexsha": "a85383ab13e31d08d2a57dad40f3ab707ee25d46", "size": 4515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/DHTable.hpp", "max_stars_repo_name": "EthanQuist/ENPM808X_Midterm", "max_stars_repo_head_hexsha": "ab01777bd9da910cd750dffbeaf15ba60b619062", "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/DHTable.hpp", "max_issues_repo_name": "EthanQuist/ENPM808X_Midterm", "max_issues_repo_head_hexsha": "ab01777bd9da910cd750dffbeaf15ba60b619062", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-13T03:34:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T23:57:43.000Z", "max_forks_repo_path": "include/DHTable.hpp", "max_forks_repo_name": "EthanQuist/ENPM808X_Midterm", "max_forks_repo_head_hexsha": "ab01777bd9da910cd750dffbeaf15ba60b619062", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-10T03:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-10T03:52:53.000Z", "avg_line_length": 31.3541666667, "max_line_length": 82, "alphanum_fraction": 0.7065337763, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.03904829160793826, "lm_q1q2_score": 0.017096259666219252}}
{"text": "#pragma once\n\n#ifndef _common_Term_hpp\n#define _common_Term_hpp\n\n#include <stdint.h>\n#include <stdexcept>\n#include <algorithm>\n#include <vector>\n#include <memory>\n#include <unordered_set>\n#include <unordered_map>\n#include <map>\n#include <boost/lexical_cast.hpp>\n#include <bitset>\n\n#include <boost/noncopyable.hpp>\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\n// #define DEBUG_TERM\n\n//\n// term\n//\n// A term comes from mathematics, where the more commonly known \"formula\"\n// consists of terms. For example, the left hand side of '=', X + 3, is a\n// term. Likewise, the right hand side '=', f(17, Y), is another term.\n//\n// X + 3 = f(17, Y)\n//\n// Terms can be decomposed into terms, and the grammar is quite simple:\n//\n// term ::= constant\n//        | functor(<term>, <term>, ..., <term>)\n//        | Variable\n//\n// Terms can be efficiently represented with cells. A cell is typically\n// a fixed sized integer word (preferbly matching the machine's word\n// size.) In our case a cell is represented with an (unsigned) 64-bit\n// integer.\n//\n// The lower 3 bits of this cell represents a TAG (which gives us 8\n// combinations.) In WAM (Warren's Abstract Machine) the cells of\n// REF, INT, CON, STR are usually enough to represent anything.\n// However, other datatypes can be added such as DBL (double),\n// BIG (bignums), ...\n//\n// The cell type REF (reference) is used to represent variables that\n// can be bound. For unbound variables, following a chain of REF cells\n// always ends up at a REF cell pointing at itself. For example,\n//\n// The term: p(Z, h(Z,W), f(W)) as:\n//\n// Heap\n//\n// [0]:    | 1    STR |\n// [1]:    | h/2  CON |    (functor h with 2 args)\n// [2]:    | 2    REF |\n// [3]:    | 3    REF |\n// [4]:    | 5    STR |\n// [5]:    | f/1  CON |    (functor f with 1 arg)\n// [6]:    | 3    REF |\n// [7]:    | 8    STR | <--- p(Z, h(Z,W), f(W))\n// [8]:    | p/3  CON |    (functor p with 3 args)\n// [9]:    | 2    REF |\n// [10]:   | 1    STR |\n// [11]:   | 5    STR |\n//\n// This example is taken from the book\n// \"Warren's Abstract Machine (A Tutorial Reconstruction)\"\n// by Hassan Ait-Kaci\n//\n// (An excellent book in my opinion that tells how you can compile\n//  Prolog programs into an efficient representation.)\n//\n\nnamespace epilog { namespace common {\n\nclass term_emitter;\nclass heap;\n\n//\n// tag\n//\n// This represents the tag of the cell which is encoded in the\n// lower 3 bits.\n//\nclass tag_t {\npublic:\n    enum kind_t { REF = 0, RFW = 1, INT = 2, BIG = 3, CON = 4, STR = 5, DAT = 6, FWD = 7 };\n\n    inline tag_t( kind_t k ) : kind_(k) { }\n\n    inline bool operator == (kind_t k) const { return kind_ == k; }\n\n    inline kind_t kind() const { return kind_; }\n\n    inline bool is_ref() const { return (static_cast<unsigned int>(kind_) & 6) == 0; }\n\n    inline operator uint64_t () const { return kind_; }\n\n    inline operator std::string () const {\n\treturn str();\n    }\n\n    inline std::string str() const {\n\tswitch (kind_) {\n\tcase REF: return \"REF\";\n\tcase RFW: return \"RFW\";\n\tcase CON: return \"CON\";\n\tcase STR: return \"STR\";\n\tcase INT: return \"INT\";\n\tcase BIG: return \"BIG\";\n\tcase DAT: return \"DAT\";\n\tcase FWD: return \"FWD\";\n\tdefault : return \"???\";\n\t}\n    }\n\nprivate:\n    kind_t kind_;\n};\n\nclass ref_cell; // Forward\n\n//\n// cell\n//\nclass untagged_cell {\npublic:\n    static const size_t CELL_NUM_BITS = 64;\n\n    typedef uint64_t value_t;\n\n    inline untagged_cell() = default;\n   \n    inline untagged_cell(const untagged_cell &other) = default;\n\n    inline untagged_cell(value_t raw_value) : raw_value_(raw_value) { }\n\n    inline value_t raw_value() const { return raw_value_; }\n\n    // inline operator value_t () const { return raw_value_; }\n\n    // inline operator value_t & () { return raw_value_; }\n\nprotected:\n    inline void set_raw_value(value_t v) { raw_value_ = v; }\n\nprivate:\n    value_t raw_value_;\n};\n\nclass cell_byte {\npublic:\n    typedef uint8_t value_t;\n    typedef value_t type;\n\nprivate:\n    inline void set_byte(size_t index, value_t v)\n    { auto byte_off = index % sizeof(untagged_cell);\n      auto bit_off = 8*byte_off;\n      auto bit_mask = ~(static_cast<untagged_cell::value_t>(0xff) << bit_off);\n      auto bit_val = static_cast<untagged_cell::value_t>(v) << bit_off;\n      cached_ = (cached_.raw_value() & bit_mask) | bit_val;\n      dirty_ = true;\n    }\n\n    inline value_t get_byte(size_t index) const\n    { auto byte_off = index % sizeof(untagged_cell);\n      auto bit_off = 8*byte_off;\n      return static_cast<value_t>(cached_.raw_value() >> bit_off);\n    }\n\n    static inline untagged_cell * flush_and_invalidate(const cell_byte &cb0) {\n\tcell_byte &cb = const_cast<cell_byte &>(cb0);\n\tauto *r = cb.base_;\n\tif (!cb.dirty_) {\n\t    cb.base_ = nullptr;\t    \n\t    return r;\n\t}\n\tif (cb.base_) cb.base_[cb.index_/sizeof(untagged_cell)] = cb.cached_;\n\tcb.base_ = nullptr;\n\tcb.dirty_ = false;\n\treturn r;\n    }\n\npublic:\n    inline cell_byte(untagged_cell *base, size_t i, size_t n) :\n\tbase_(base), index_(i), n_(n), cached_(*base), dirty_(false) { }\n\n    cell_byte(const cell_byte &other) = default;\n    cell_byte(cell_byte &&other) = default;\n\n    inline ~cell_byte() { if (base_ && dirty_) base_[index_/sizeof(untagged_cell)] = cached_; }\n\n    inline void set_address(untagged_cell *base, size_t index) {\n\tflush_and_invalidate(*this);\n        base_ = base;\n\tindex_ = index;\n\tcached_ = *base_;\n    }\n\n    inline void operator = (const cell_byte &other) {\n\tif (base_ && dirty_) base_[index_/sizeof(untagged_cell)] = cached_;\n\tbase_ = other.base_;\n\tindex_ = other.index_;\n\tcached_ = other.cached_;\n\tdirty_ = other.dirty_;\n    }\n\t\n    inline void operator ++ () {\n\tif (base_ && ((index_+1) % sizeof(untagged_cell)) == 0) {\n\t    if (dirty_) {\n\t\tbase_[index_/sizeof(untagged_cell)] = cached_;\n\t\tdirty_ = false;\n\t    }\n\t    if ((index_+1) < n_) {\t    \n\t\tcached_ = base_[(index_+1)/sizeof(untagged_cell)];\n\t    }\n\t}\n\tindex_++;\n    }\n\n    inline void operator >>= (size_t n)\n    { set_byte(index_, get_byte(index_) >> n); }\n\n    inline void operator = (value_t v)\n    { set_byte(index_, v); }\n\n    inline operator value_t () const\n    { return get_byte(index_); }\n\n    untagged_cell *base_;\n    size_t index_;\n    size_t n_;\n    untagged_cell cached_;\n    bool dirty_;\n};\n\n}}\n\nnamespace boost {\n    template<> struct make_unsigned<epilog::common::cell_byte> {\n\ttypedef epilog::common::cell_byte type;\n    };\n}\n\nnamespace std { \n    template<> struct make_unsigned<epilog::common::cell_byte> {\n\ttypedef epilog::common::cell_byte type;\n    };\n}\n\n\nnamespace epilog { namespace common {\n\nclass cell : public untagged_cell {\npublic:\n    static const int TAG_SIZE_BITS = 3;\n\n    inline cell(const heap &, const cell other) : untagged_cell(other.raw_value()) { }\n\n    inline cell() = default;\n\n    inline cell(value_t raw_value) : untagged_cell(raw_value) { }\n\n    inline cell(tag_t t) : untagged_cell(static_cast<value_t>(t) & 0x7) { }\n\n    inline cell(tag_t t, value_t v)\n                        : untagged_cell((static_cast<value_t>(t) & 0x7) |\n\t\t\t\t     (v << 3)) { }\n\n    inline cell(const cell &other) = default;\n\n    inline tag_t tag() const { return tag_t(static_cast<tag_t::kind_t>(raw_value()&0x7));}\n\n    // inline operator value_t () { return raw_value() >> 3; }\n\n    inline value_t value() const { return raw_value() >> 3; }\n\n    inline void set_value(value_t v) { set_raw_value((v << 3) | (raw_value() & 0x7)); }\n\n    inline int64_t value_signed() const { return static_cast<int64_t>(raw_value()) >> 3; }\n\n    inline bool operator == (const cell other) const { return raw_value() == other.raw_value(); }\n    inline bool operator != (const cell other) const { return raw_value() != other.raw_value(); }\n    inline bool operator < (const cell other) const { return raw_value() < other.raw_value(); }\n    inline bool operator <= (const cell other) const { return raw_value() <= other.raw_value(); }\n    inline bool operator > (const cell other) const { return raw_value() > other.raw_value(); }\n    inline bool operator >= (const cell other) const { return raw_value() >= other.raw_value(); }\n\n    inline operator bool () const { return raw_value() != 0; }\n\n    std::string str() const;\n    std::string inner_str() const;\n    std::string boxed_str() const;\n    std::string boxed_str_dat() const;\n\n    std::string hex_str() const;\n    std::string hex_str0() const;\n\nprotected:\n    static std::string hex_str(uint64_t value, bool skip_leading_0s = true);\n};\n\nclass term : public cell {\npublic:\n   term() : cell(0) { }\n   term(cell c) : cell(c) {}\n   term(const term &other) = default;\n   term(const heap &src, cell c) : cell(src,c) { }\n   term(heap &src, cell c) : cell(src,c) { }   \n};\n\n//\n// Exceptions\n//\n\nclass term_exception : public std::runtime_error {\npublic:\n    term_exception(const std::string &msg) : std::runtime_error(msg) { }\n};\n\nclass heap_index_out_of_range_exception : public term_exception {\npublic:\n    heap_index_out_of_range_exception(size_t index, size_t max_sz);\n};\n\nclass expected_con_cell_exception : public term_exception {\npublic:\n    expected_con_cell_exception(size_t index, cell c)\n\t: term_exception( std::string(\"Expected CON cell at index \") + boost::lexical_cast<std::string>(index) + \"; was \" + c.tag().str()) { }\n};\n\nclass expected_str_cell_exception : public term_exception {\npublic:\n    expected_str_cell_exception(cell c)\n      : term_exception( std::string(\"Expected STR cell; was \" + c.tag().str())) { }\n};\n\nclass coin_security_exception : public term_exception {\npublic:\n    coin_security_exception();\n};\n\n//\n// ptr_cell this is not a real cell, but any class that uses the upper\n// bits for referencing another cell is inheriting from this class:\n//\n//  Integer value        REF \n// [xxxxxxxxxxxxxxxxxxxx 000]\n//  bits 63-3       bits 0-2\n//\n//\n\nclass ptr_cell : public cell {\npublic:\n    inline ptr_cell(const ptr_cell &other) : cell( other ) { }\n    inline ptr_cell(tag_t tag, size_t index) : cell( tag, static_cast<value_t>(index) ) { }\n\n    inline operator size_t () const { return static_cast<value_t>(value()); }\n\n    inline size_t index() const { return (size_t)*this; }\n\n    void set_index( size_t index ) { set_value(static_cast<value_t>(index)); }\n\n    inline bool operator < (const ptr_cell other) const {\n\treturn index() < other.index();\n    }\n\n    inline std::string inner_str() const {\n\treturn boost::lexical_cast<std::string>(index());\n    }\n\n    inline bool is_ptr_cell(cell c) {\n      auto tag = c.tag();\n      return tag == tag_t::REF ||\n             tag == tag_t::RFW ||\n             tag == tag_t::STR ||\n             tag == tag_t::BIG;\n    }\n};\n\n//\n// REF cells\n// Like in WAM / Warren's Abstract Machine.\n//\nclass ref_cell : public ptr_cell {\npublic:\n    inline ref_cell() : ptr_cell(tag_t::REF, 0) { }\n    inline ref_cell(size_t index) : ptr_cell(tag_t::REF, index) { }\n    inline ref_cell(size_t index, bool) : ptr_cell(tag_t::RFW, index) { }\n    inline ref_cell watch() const { return ref_cell(index(), true); }\n    inline ref_cell unwatch() const { return ref_cell(index()); }\n    inline bool watched() const { return tag() == tag_t::RFW; }\n};\n\n//\n// STR cells\n// Like in WAM / Warren's Abstract Machine.\n//\nclass str_cell : public ptr_cell {\npublic:\n    inline str_cell(ptr_cell pcell) : ptr_cell(pcell) { }\n    inline str_cell(size_t index) : ptr_cell(tag_t::STR, index) { }\n};\n\n//\n// FWD cells\n// Forwading cells used for cycle detection during unification.\nclass fwd_cell : public ptr_cell {\npublic:\n    inline fwd_cell(ptr_cell pcell) : ptr_cell(pcell) { }\n    inline fwd_cell(size_t index) : ptr_cell(tag_t::FWD, index) { }\n};\n\n// \n// CON cells (61 bits)\n//\n// If high (63rd) bit is set, then this encodes the name of the constant\n// directly (7 bytes for constant string).\n//\n// If bit63==1 -->\n//          f        o        o            t     arity CON\n//     [ xxxxxxxx xxxxxxxx xxxxxxxx ... xxxxxxxx yyyyy 001]\n// If bit63==0 -->\n//            Index into const table         arity     CON\n//     [ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyy yyyyy 001]\n//                    48 bits               13 bits\n\nclass con_cell : public cell {\npublic:\n    static const size_t MAX_ARITY = 8192 - 1;\n    static const size_t MAX_NAME_LENGTH = 256;\n  \n    inline con_cell() : cell(tag_t::CON) { }\n    inline con_cell(const con_cell &other) : cell(other) { }\n    inline con_cell( size_t atom_index, size_t arity ) : cell(tag_t::CON)\n    {\n        set_value((atom_index << 13) | arity);\n    }\n\n    con_cell( const std::string &name, size_t arity );\n\n    static inline bool use_compacted( const std::string &name, size_t arity)\n    {\n        return name.length() <= 7 && arity <= 31;\n    }    \n\n    size_t arity() const\n    {\n        if (is_direct()) {\n    \t    // Only 5 bits for arity\n\t    return static_cast<size_t>(value() & 0x1f);\n        } else {\n\t    // 5+8=13 bits for arity\n\t    return static_cast<size_t>(value() & ((1 << 12)-1));\n        }\n    }\n\n    con_cell to_atom() const\n    {\n\tcon_cell c = *this;\n\tc.set_value(value() & ~(0x1f));\n\treturn c;\n    }\n\n    inline size_t atom_index() const\n    {\n        assert(!is_direct());\n\treturn static_cast<size_t>(value() >> 13);\n    }\n\n    std::string name() const;\n    size_t name_length() const;\n    std::string name_and_arity() const;\n\n    std::string inner_str () const;\n\n    // inline operator std::string () const {\n    //\treturn xxxstr();\n    // }\n\n    bool is_direct() const {\n\treturn ((value() >> 60) & 0x1) != 0;\n    }\n\nprivate:\n    uint8_t get_name_byte(size_t index) const;\n\n    friend class heap;\n};\n\n//\n// INT cells (61 bits)\n// Like in WAM / Warren's Abstract Machine\n//\n\nclass int_cell : public cell {\nprivate:\n    typedef int64_t T;\n\n    inline int_cell bin_op( const std::function<T(const T, const T)> &f,\n\t\t\t    const int_cell a,\n\t\t\t    const int_cell b) const {\n\treturn int_cell(f((T)a,(T)b));\n    }\n\nprotected:\n    inline int_cell(tag_t t, int64_t val) : cell(t, val) { }\n\npublic:\n    inline int_cell(size_t val) : cell(tag_t::INT, val) { }\n    inline int_cell(int64_t val) : cell(tag_t::INT, val) { }\n    inline int_cell(int val) : cell(tag_t::INT, val) { }\n\n    inline int_cell(const int_cell &other) : cell(other) { }\n\n    static inline int64_t saturate(int64_t val) {\n\tif (val < min().value()) {\n\t    return min().value();\n\t} else if (val > max().value()) {\n\t    return max().value();\n\t} else {\n\t    return val;\n\t}\n    }\n\n    static inline uint64_t saturate(uint64_t val) {\n\tif (val > static_cast<uint64_t>(max().value())) {\n\t    return static_cast<uint64_t>(max().value());\n\t} else {\n\t    return val;\n\t}\n    }\n\n    inline operator T () const {\n\treturn static_cast<T>(value_signed());\n    }\n\n    inline T value() const {\n\treturn value_signed();\n    }\n\n    inline int_cell operator + (const int_cell other ) const {\n\treturn bin_op( std::plus<T>(), *this, other );\n    }\n\n    inline int_cell & operator ++ () {\n\tset_value(value() + 1);\n\treturn *this;\n    }\n\n    inline int_cell & operator -- () {\n\tset_value(value() - 1);\n\treturn *this;\n    }    \n\n    inline int_cell operator - (const int_cell other ) const {\n\treturn bin_op( std::minus<T>(), *this, other );\n    }\n\n    inline int_cell operator * (const int_cell other) const {\n\treturn bin_op( std::multiplies<T>(), *this, other );\n    }\n\n    inline int_cell operator / (const int_cell other) const {\n\treturn bin_op( std::divides<T>(), *this, other );\n    }\n\n    inline bool operator == (const int other) const {\n\treturn value() == other;\n    }\n\n    inline bool operator == (const int_cell &other) const {\n\treturn value() == other.value();\n    }\n\n    inline bool operator != (const int_cell &other) const {\n\treturn value() != other.value();\n    }\n\n    inline bool operator > (const int_cell &other) const {\n\treturn value() > other.value();\n    }\n\n    inline bool operator < (const int_cell &other) const {\n\treturn value() < other.value();\n    }\n\n    inline bool operator >= (const int_cell &other) const {\n\treturn value() >= other.value();\n    }\n\n    inline bool operator <= (const int_cell &other) const {\n\treturn value() <= other.value();\n    }\n\n    inline int_cell negate() const {\n\treturn int_cell(saturate(-value()));\n    }\n\n    inline int_cell abs() const {\n        if (is_negative()) {\n\t    return int_cell(saturate(-value()));\n\t} else {\n\t    return *this;\n\t}\n    }\n\n    inline int_cell sign() const {\n\treturn is_negative() ? int_cell(-1) : int_cell(1);\n    }\n    \n    inline bool is_negative() const {\n\treturn value() < 0;\n    }\n\n    inline bool is_zero() const {\n\treturn value() == 0;\n    }\n\n    static inline const int_cell max() {\n\tstatic const int_cell max_ = int_cell(std::numeric_limits<int64_t>::max() >> cell::TAG_SIZE_BITS);\n\treturn max_;\n    }\n\n    static inline const int_cell min() {\n\tstatic const int_cell min_ = int_cell(std::numeric_limits<int64_t>::min() >> cell::TAG_SIZE_BITS);\n\treturn min_;\n    }\n\n    std::string inner_str () const;\n    std::string hex_str() const;\n\n    inline operator std::string () const {\n       return str();\n    }\n\n    static int_cell encode_str(const std::string &str, bool has_more);\n\n    static int_cell encode_str(const std::string &str, size_t from,\n\t\t\t       size_t to, bool has_more);\n\nprivate:\n    friend class term_serializer;\n\n    bool is_char_chunk() const;\n    bool is_last_char_chunk() const;\n    std::string as_char_chunk() const;\n\n    inline bool is_valid_char(uint8_t ch) const\n    { return ch >= 1 && ch <= 127; }\n};\n\n//\n// BIG\n// This is to use a binary blob of data. Like STR it points at the\n// beginning of the block which first contains the number of cells.\n//\nclass big_cell : public ptr_cell {\npublic:\n    inline big_cell(const big_cell &other) : ptr_cell(other) { }\n    inline big_cell(size_t index) : ptr_cell(tag_t::BIG, index) { }\n};\n\nclass dat_cell : public int_cell {\nprivate:\n    static const size_t CELL_NUM_BITS_HALF = CELL_NUM_BITS / 2;\n\n    static const size_t NUM_SIZE_BITS = CELL_NUM_BITS_HALF - TAG_SIZE_BITS;\n    \npublic:\n    static const size_t CELL_NUM_BYTES_HALF = CELL_NUM_BITS / 2 / 8;\n\n    // Lower 4 bytes (half cell) = number of bits\n    // (if negative then the number lives separately, not\n    //  directly on heap.)\n    // Upper 4 bytes (half cell) = binary data\n\n    inline dat_cell(size_t num_bits)\n        : int_cell(tag_t::DAT, static_cast<int64_t>(num_bits)) { }\n\n    inline size_t num_bits() const\n    { auto mask = (static_cast<untagged_cell::value_t>(1) << NUM_SIZE_BITS) - 1;\n      auto v = value();\n      auto n = v & mask;\n      return n;\n    }\n\n    // [32] means reserved for 32 bits storing size.\n    //\n    // 288 bits = 5 cells (fits within [32] + 32 + 64 + 64 + 64 + 64)\n    // 256 bits = 5 cells (fits within [32] + 32 + 64 + 64 + 64 + 32)\n    // 224 bits = 4 cells (fits within [32] + 32 + 64 + 64 + 64)\n    //\n    // This means that 33 bytes (typical bitcoin private key, 32 bytes\n    // + 1 byte for meta data = 264 bits) can be stored within 5 cells.\n    // (6 cells if you count the BIG reference.)\n    //\n    // Not optimal, but it is convenient to have everything represented\n    // as terms.\n    //\n    inline size_t num_half_cells() const\n    { return 1 + (num_bits() + CELL_NUM_BITS_HALF - 1) / CELL_NUM_BITS_HALF; }\n\n    inline size_t num_cells() const\n    { return (num_half_cells() + 1) / 2; }\n\n    std::string inner_str() const;    \n};\n\nclass big_header : public dat_cell {\npublic:\n    inline big_header(size_t num_bits) : dat_cell(num_bits) { }\n};\n\ntemplate<typename T> class big_iterator_base : public T {\npublic:\n    big_iterator_base(heap &h, size_t index, size_t num);\n    big_iterator_base(heap &h, size_t index, size_t num, bool);\n    big_iterator_base(const big_iterator_base<T> &other);\n    big_iterator_base<T> & operator ++();\n\n    inline int operator - (const big_iterator_base<T> &other) const\n    { return i_ - other.i_; }\n\n    inline bool operator == (const big_iterator_base<T> &other) const {\n\treturn i_ == other.i_;\n    }\n    inline bool operator != (const big_iterator_base<T> &other) const {\n\treturn ! operator == (other);\n    }\n    \nprotected:\n    heap &heap_;\n    size_t index_;\n    int i_;\n    int end_;\n    cell_byte cell_byte_;\n};\n\nclass big_iterator : public big_iterator_base<std::iterator<std::random_access_iterator_tag, cell_byte> > {\n    using it = std::iterator<std::random_access_iterator_tag, cell_byte>;\npublic:\n    inline big_iterator(heap &h, size_t index, size_t num) : big_iterator_base<it>(h, index, num) { }\n    inline big_iterator(heap &h, size_t index, size_t num, bool b) : big_iterator_base<it>(h, index, num, b) { }\n    inline big_iterator(const big_iterator &other) : big_iterator_base<it>(other) { }\n\n    cell_byte & operator * ();\n};\n\nclass const_big_iterator : public big_iterator_base<std::iterator<std::random_access_iterator_tag, cell_byte> > {\n    using it = std::iterator<std::random_access_iterator_tag, cell_byte>;\npublic:\n    inline const_big_iterator(const heap &h, size_t index, size_t num) : big_iterator_base<it>(const_cast<heap &>(h), index, num) { }\n    inline const_big_iterator(const heap &h, size_t index, size_t num, bool b) : big_iterator_base<it>(const_cast<heap &>(h), index, num, b) { }\n    inline const_big_iterator(const big_iterator &other) : big_iterator_base<it>(other) { }\n\n    const cell_byte & operator * () const;\n};\n\nclass big_inserter {\npublic:\n    big_inserter(heap &heap, big_cell big);\n\n    inline cell_byte & operator * () {\n\treturn *it_;\n    }\n\n    inline void operator ++ () {\n\t++it_;\n    }\n\nprivate:\n    big_iterator it_;\n};\n\nclass heap; // Forward\n    \n//\n// heap_block\n//\n// We don't want to keep _all_ heap blocks in memory. We can\n// cache those that are frequent.\n//\nclass heap_block : private boost::noncopyable {\npublic:\n\n    friend class garbage_collector;\n    static const size_t MAX_SIZE = 8192; // 64k\n\n    inline heap_block(heap &h) : heap_block(h, 0) { }\n    inline heap_block(heap &h, size_t index)\n        : heap_(h), index_(index), offset_(index*MAX_SIZE),\n\t  size_(0), changed_(false) {\n    }\n    ~heap_block() = default;\n\n    inline const cell * cells() const { return &cells_[0]; }\n    inline cell * cells() { return &cells_[0]; }  \n\n    inline bool has_changed() const {\n        return changed_;\n    }\n    inline void clear_changed() {\n        changed_ = false;\n    }\n\n    bool is_head_block() const;\n\n    inline size_t index() const { return index_; }\n    inline size_t offset() const { return offset_; }\n    inline size_t size() const { return size_; }\n    inline bool is_full() const { return size() == MAX_SIZE; }\n\n    inline void set_index(size_t new_index) {\n      index_ = new_index;\n      offset_ = new_index * MAX_SIZE;\n    }\n\n    inline cell & operator [] (size_t addr) {\n        if (!changed_) { changed_ = true; modified(); }\n\treturn cells_[addr - offset_];\n    }\n\n    inline const cell & operator [] (size_t addr) const {\n\treturn cells_[addr - offset_];\n    }\n\n    inline const cell & get(size_t index) const {\n        return cells_[index];\n    }\n\n    inline cell & get(size_t index) {\n        return cells_[index];\n    }\n\n    inline void set(size_t index, cell c) {\n        cells_[index] = c;\n    }\n\n    inline bool can_allocate(size_t n) const {\n\treturn size_ + n <= MAX_SIZE;\n    }\n\n    inline size_t allocate(size_t n) {\n\tsize_t addr = offset_ + size_;\n\tsize_ += n;\n\treturn addr;\n    }\n\n    inline size_t allocate0(size_t n) {\n\tmemset(&cells_[size_], 0, n*sizeof(untagged_cell));\n\treturn allocate(n);\n    }\n    \n    inline void trim(size_t n) {\n\tsize_ = n;\n    }\n\n    // Will transform REF into RFW if value is true and\n    //      transform RFW into REF if value is false.\n    inline void watch(size_t addr, bool value) {\n        cell &c = cells_[addr - offset_];\n\tif (c.tag() == tag_t::REF && value) {\n\t    ref_cell &r = static_cast<ref_cell &>(c);\n\t    r = ref_cell(r.index(), true);\n\t} else if (c.tag() == tag_t::RFW && !value) {\n\t    ref_cell &r = static_cast<ref_cell &>(c);\n\t    r = ref_cell(r.index());\n\t}\n    }\n\n    inline bool watched(size_t addr) const {\n        auto c = cells_[addr - offset_];\n\treturn c.tag() == tag_t::RFW;\n    }\n\n    void modified();\n    \nprivate:\n    heap &heap_;\n    size_t index_;\n    size_t offset_;\n    size_t size_;\n    bool changed_;\n    cell cells_[MAX_SIZE];\n};\n\n//\n// Externally typed cell references.\n//\n// We keep track of which heap the cell comes from. Also the heap\n// gets notified so that whenever a heap GC happens the address can be\n// updated.\n// \n\n#if 0\ntemplate<typename T> class ext {\npublic:\n    inline ext() : heap_(nullptr), ptr_()\n    {\n#ifdef DEBUG_TERM\n\tid_ = 0;\n#endif\n    }\n    inline ext(const heap &h, cell ptr) : heap_(&h), ptr_(ptr)\n    {\n#ifdef DEBUG_TERM\n\tid_ = ext_register(h, &ptr_); \n#else\n\text_register(h, &ptr_);\n#endif\n    }\n    inline ~ext() { if (heap_ != nullptr) ext_unregister(*heap_, &ptr_); }\n\n    inline ext(const ext<T> &other)\n    {\n\tif (other.heap_ != nullptr) {\n\t    heap_ = other.heap_;\n\t    ptr_ = other.ptr_;\n#ifdef DEBUG_TERM\n            id_ = ext_register(*heap_, &ptr_);\n#else\n            ext_register(*heap_, &ptr_);\n#endif\n\t} else {\n\t    heap_ = nullptr;\n\t}\n    }\n\n    inline void operator = (const ext<T> &other)\n    {\n\tif (other.heap_ != nullptr) {\n\t    bool was_null = heap_ == nullptr;\n\t    heap_ = other.heap_;\n\t    ptr_ = other.ptr_;\n\t    if (was_null) {\n#ifdef DEBUG_TERM\n   \t        id_ = ext_register(*heap_, &ptr_);\n#else\n\t        ext_register(*heap_, &ptr_);\n#endif\n            }\n\t} else {\n\t    if (heap_ != nullptr) {\n\t\text_unregister(*heap_, &ptr_);\n\t\theap_ = nullptr;\n\t    }\n\t}\n    }\n\n    inline operator T ();\n    inline operator const T & () const;\n    inline T operator * () const;\n    inline T deref() const;\n    inline const T * operator -> () const;\n    inline T * operator -> ();\n\n    inline bool operator == (const ext<T> &other) const {\n\treturn heap_ == other.heap_ && ptr_ == other.ptr_;\n    }\n\n    inline bool is_void() const {\n\treturn heap_ == nullptr;\n    }\n\nprivate:\n#ifdef DEBUG_TERM\n    inline size_t ext_register(const heap &h, cell *p);\n#else\n    inline void ext_register(const heap &h, cell *p);\n#endif\n    inline void ext_unregister(const heap &h, cell *p);\n\n    const heap *heap_;\n    mutable cell ptr_;\n#ifdef DEBUG_TERM\n    mutable size_t id_;\n#endif\n};\n#endif\n\n//\n// heap\n//\n// This is just a stack of heap_blocks.\n//\n\nclass heap {\npublic:\n    heap();\n    ~heap();\n\n    void reset();\n\n    inline heap & get_heap() { return *this; }\n    inline const heap & get_heap() const { return *this; }\n\n    inline size_t size() const { return size_; }\n\n    inline size_t num_blocks() const { return (size()+heap_block::MAX_SIZE-1)/heap_block::MAX_SIZE; }\n\n    void trim(size_t new_size) {\n\ttrim_fn_(*this, trim_fn_context_, new_size);\n    }\n\nprotected:\n    void internal_trim(size_t new_size);\n\npublic:\n\n    inline void set_size(size_t new_size) {\n        size_ = new_size;\n    }\n\n    inline void coin_security_check(con_cell c) const {\n        if (coin_security_enabled_ && c == COIN) {\n\t    throw coin_security_exception();\n        }\n    }\n\n    friend class garbage_collector;\n\n    class disabled_coin_security;\n    friend class disabled_coin_security;\n\n    class disabled_coin_security {\n    public:\n        inline disabled_coin_security(heap &h) : heap_(h), old_(h.coin_security_enabled_)\n            { heap_.coin_security_enabled_ = false; }\n        inline ~disabled_coin_security()\n            { heap_.coin_security_enabled_ = old_; }\n    private:\n        heap &heap_;\n        bool old_;\n    };\n\n    // Only a couple of builtins will use this.\n    inline disabled_coin_security disable_coin_security() {\n        return disabled_coin_security(*this);\n    }\n\n    inline void check_index(size_t index) const\n    {\n\tif (index >= size()) {\n\t    throw heap_index_out_of_range_exception(index, size());\n\t}\n    }\n\n    inline cell & operator [] (size_t addr)\n    {\n\tauto &block = find_block(addr);\n\treturn block[addr];\n    }\n\n    inline const cell & operator [] (size_t addr) const\n    {\n\treturn get(addr);\n    }\n\n    inline untagged_cell & untagged_at(size_t addr) {\n\treturn (*this)[addr];\n    }\n\n    inline const untagged_cell & untagged_at(size_t addr) const {\n\treturn get(addr);\n    }\n  \n    size_t list_length(const cell lst) const;\n\n    inline con_cell atom(const std::string &name) const\n    {\n        if (name.length() > 7) {\n\t    return con_cell(resolve_atom_index(name), 0);\n\t}\n\treturn con_cell(name, 0);\n    }\n\n    inline std::string atom_name(con_cell cell) const\n    {\n        if (cell.is_direct()) {\n\t    return cell.name();\n        } else {\n\t    size_t index = cell.atom_index();\n\t    auto it = atom_index_to_name_table_.find(index);\n\t    if (it == atom_index_to_name_table_.end()) {\n\t        load_atom_name_fn_(const_cast<heap &>(*this), load_atom_name_fn_context_, index);\n\t\tit = atom_index_to_name_table_.find(index);\n\t    }\n  \t    return it->second;\n\t}\n    }\n\n    inline bool is_dollar_atom_name(con_cell cell) const\n    {\n        if (cell.is_direct()) {\n\t    return cell.name_length() >= 1 && ((cell.get_name_byte(0) & 0x7f) == '$');\n        } else {\n\t    std::string name = atom_name(cell);\n\t    return !name.empty() && name[0] == '$';\n\t}\n    }\n  \n    inline bool is_string(term lst) const\n    {\n\tif (is_empty_list(lst)) {\n\t    return false;\n\t}\n\tbool contain_printables = false;\n\twhile (is_dotted_pair(lst)) {\n\t    term head = arg(lst, 0);\n\t    if (head.tag() != tag_t::INT) {\n\t\treturn false;\n\t    }\n\t    auto val = reinterpret_cast<const int_cell &>(head).value();\n\t    if (val < 0 || val > 255) {\n\t\treturn false;\n\t    }\n\t    if (val >= ' ') {\n\t\tcontain_printables = true;\n\t    }\n\t    lst = arg(lst, 1);\n\t}\n\treturn contain_printables;\n    }\n\n    inline bool is_prefer_string(term lst) const\n    {\n\tif (is_empty_list(lst)) {\n\t    return false;\n\t}\n        size_t printables = 0;\n\twhile (is_dotted_pair(lst)) {\n\t    term head = arg(lst, 0);\n\t    if (head.tag() != tag_t::INT) {\n\t\treturn false;\n\t    }\n\t    auto val = reinterpret_cast<const int_cell &>(head).value();\n\t    if (val < 0 || val > 255) {\n\t\treturn false;\n\t    }\n\t    if (val >= ' ') {\n\t\tprintables++;\n\t    }\n\t    lst = arg(lst, 1);\n\t}\n\treturn printables >= 7;\n    }\n\n    inline std::string list_to_string(term lst) const\n    {\n\tstd::string s;\n\n\twhile (is_dotted_pair(lst)) {\n\t    term head = arg(lst, 0);\n\t    lst = arg(lst, 1);\n\t    if (head.tag() != tag_t::INT) {\n\t\tcontinue;\n\t    }\n\t    auto val = reinterpret_cast<const int_cell &>(head).value();\n\t    if (val >= 0 && val <= 255) {\n\t\ts += static_cast<char>(val);\n\t    }\n\t}\n\treturn s;\n    }\n\n    bool is_name(con_cell cell, const std::string &name) const;\n\n    inline con_cell functor(const std::string &name, size_t arity)\n    {\n\tauto name_len = name.length();\n        if (name_len > 7) {\n\t    assert(name_len < con_cell::MAX_NAME_LENGTH);\n   \t    return con_cell(resolve_atom_index(name), arity);\n\t}\n\t\n        return con_cell(name, arity);\n    }\n\n    inline con_cell to_atom(con_cell c)\n    {\n\tif (c.is_direct()) {\n\t    con_cell c2 = c;\n\t    c2.set_value(c.value() & ~(0x1f));\n\t    return c2;\n\t} else {\n\t    std::string name = atom_name(c);\n\t    return functor(name, 0);\n\t}\n    }\n\n    inline con_cell to_functor(con_cell atom, size_t arity)\n    {\n\tif (arity >= 32) {\n\t    return functor(atom_name(atom), arity);\n\t} else {\n\t    if (atom.is_direct()) {\n\t\tcon_cell f = atom;\n\t\tf.set_value(f.value() | arity);\n\t\treturn f;\n\t    } else {\n\t\treturn functor(atom_name(atom), arity);\n\t    }\n\t}\n    }\n\n    size_t resolve_atom_index(const std::string &name) const;\n\n    inline con_cell functor(const term s) const\n    {\n\tterm ds = deref(s);\n        if (ds.tag() == tag_t::CON) {\n\t    return reinterpret_cast<const con_cell &>(ds);\n        }\n        if (ds.tag() != tag_t::STR) {\n\t    throw expected_str_cell_exception(ds);\n        }\n\treturn functor(reinterpret_cast<const str_cell &>(ds));\n    }\n\n    inline con_cell functor(const str_cell &s) const\n    {\n\tsize_t index = s.index();\n\tcheck_index(index);\n\tcell c = get(index);\n\tif (c.tag() != tag_t::CON) {\n\t    throw expected_con_cell_exception(index, c);\n\t}\n\tconst con_cell &cc = static_cast<const con_cell &>(c);\n\treturn cc;\n    }\n    \n    bool is_list(const cell c) const;\n\n    inline bool is_empty_list(const cell c) const\n    {\n\tif (c.tag() == tag_t::CON) {\n\t    return c == EMPTY_LIST;\n\t} else if (c.tag() == tag_t::STR) {\n   \t    return functor(c) == EMPTY_LIST;\n        } else {\n\t    return false;\n        }\n    }\n\n    inline bool is_dotted_pair(const cell c) const\n    {\n\tif (c.tag() == tag_t::CON) {\n  \t    return c == DOTTED_PAIR;\n\t} else if (c.tag() == tag_t::STR) {\n\t    return functor(c) == DOTTED_PAIR;\n\t} else {\n\t    return false;\n\t}\n    }\n\n    inline bool is_comma(const cell c) const\n    {\n\tif (c.tag() == tag_t::CON) {\n\t    return c == COMMA;\n\t} else if (c.tag() == tag_t::STR) {\n\t    return functor(c) == COMMA;\n\t} else {\n\t    return false;\n\t}\n    }\n\n    cell deref(cell c) const;\n    cell deref_with_cost(cell c, uint64_t &cost) const;\n\n    inline term arg(const cell c, size_t index) const\n    {\n\tauto dc = deref(c);\n        const str_cell &s = static_cast<const str_cell &>(dc);\n\treturn term(*this, deref(get(s.index() + index + 1)));\n    }\n\n    void set_arg(cell str, size_t index, const cell c)\n    {\n\tauto dc = deref(str);\n        str_cell &s = static_cast<str_cell &>(dc);\n\tsize_t i = s.index() + index + 1;\n\t(*this)[i] = c;\n    }\n\n    inline term new_str(con_cell con)\n    {\n        coin_security_check(con);\n\tsize_t arity = con.arity();\n\tcell *p;\n\tsize_t index;\n\tstd::tie(p, index) = allocate(tag_t::STR, 2+ arity);\n\tstatic_cast<ptr_cell &>(*p).set_index(index+1);\n\tp[1] = con;\n\tfor (size_t i = 0; i < arity; i++) {\n\t    p[i+2] = ref_cell(index+i+2);\n\t}\n\treturn term(*this, *p);\n    }\n\n    inline str_cell new_con0(con_cell con)\n    {\n        coin_security_check(con);\n        cell *p;\n\tsize_t index;\n\tsize_t arity = con.arity();\n\tensure_allocate(1+arity);\n        std::tie(p, index) = allocate(tag_t::CON, 1);\n\t*p = con;\n\treturn str_cell(index);\n    }\n\n    inline str_cell new_str0(con_cell con)\n    {\n        coin_security_check(con);\n        cell *p;\n        size_t index;\n\tsize_t arity = con.arity();\n\tensure_allocate(2+arity);\n        std::tie(p, index) = allocate(tag_t::STR, 2);\n\tstatic_cast<ptr_cell &>(*p).set_index(index+1);\n\tp[1] = con;\n\treturn str_cell(index+1);\n    }\n\n    inline size_t num_bits(const big_cell &big) const {\n\tauto &hdr = reinterpret_cast<const big_header &>(get(big.index()));\n\treturn hdr.num_bits();\n    }\n\n    inline size_t num_bytes(const big_cell &big) const {\n\treturn (num_bits(big) + 7) / 8;\n    }\n\n    inline size_t num_cells(const big_cell &big) const {\n\tauto &hdr = reinterpret_cast<const big_header &>(get(big.index()));\n\treturn hdr.num_cells();\n    }\n\n    inline big_iterator begin(const big_cell &big) {\n\tauto dc = deref(big);\n\tbig_cell &b = reinterpret_cast<big_cell &>(dc);\n\tauto &hdr = reinterpret_cast<const big_header &>(untagged_at(b.index()));\n\tsize_t n = (hdr.num_bits() + 7) / 8;\n\treturn big_iterator(*this, b.index(), n);\n    }\n\n    inline big_iterator end(const big_cell &big) {\n\tauto dc = deref(big);\n\tbig_cell &b = reinterpret_cast<big_cell &>(dc);\n\tauto &hdr = reinterpret_cast<const big_header &>(untagged_at(b.index()));\n\tsize_t n = (hdr.num_bits() + 7) / 8;\n\treturn big_iterator(*this, b.index(), n, true);\n    }\n\n    inline const_big_iterator begin(const big_cell &big) const {\n\tauto dc = deref(big);\n\tbig_cell &b = reinterpret_cast<big_cell &>(dc);\n\tauto &hdr = reinterpret_cast<const big_header &>(untagged_at(b.index()));\n\tsize_t n = (hdr.num_bits() + 7) / 8;\n\treturn const_big_iterator(*this, b.index(), n);\n    }\n\n    inline const_big_iterator end(const big_cell &big) const {\n\tauto dc = deref(big);\n\tbig_cell &b = reinterpret_cast<big_cell &>(dc);\n\tauto &hdr = reinterpret_cast<const big_header &>(untagged_at(b.index()));\n\tsize_t n = (hdr.num_bits() + 7) / 8;\n\treturn const_big_iterator(*this, b.index(), n, true);\n    }\n\n    inline big_cell new_big(const boost::multiprecision::cpp_int &i, size_t nbits0)\n    {\n\tusing namespace boost::multiprecision;\n\tsize_t nbits = nbits0 == 0 ? (i ? msb(i)+1 : 1) : nbits0;\n\tnbits = ((nbits + 7) / 8) * 8;\n\tbig_cell big = new_big(nbits);\n\tset_big(big, i);\n\treturn big;\n    }\n\n    // Big nums are special and can span over multiple heap blocks\n    inline big_cell new_big(size_t num_bits)\n    {\n\tauto num_bytes = (num_bits + 7) / 8;\n\tauto num_cells = (num_bytes <= 4) ? 1 : 1+(((num_bytes-4) + sizeof(cell) - 1) / sizeof(cell));\n\n\tbig_header header(num_bits);\n\n\tcell *p;\n\tsize_t index;\n\tsize_t n = num_cells;\n\t// We pass true as second argument to indicate that a bignum can\n\t// span across multiple heap blocks (even for small bignums as\n\t// a small bignum can go across the heap block boundary.)\n\tstd::tie(p, index) = allocate(tag_t::DAT, n, true);\n\t*p = header;\n\treturn big_cell(index);\n    }\n\n    bool big_equal(big_cell big1, big_cell big2, uint64_t &cost) const;\n    int big_compare(big_cell big1, big_cell big2, uint64_t &cost) const;\n\n    void get_big(cell big, uint8_t *bytes, size_t n) const;\n    void set_big(cell big, const uint8_t *bytes, size_t n);\n\n    big_header get_big_header(cell big) const {\n      auto dc = deref(big);\n      big_cell &b = reinterpret_cast<big_cell &>(dc);\n      auto &hdr = reinterpret_cast<const big_header &>(untagged_at(b.index()));\n      return hdr;\n    }\n\n    static std::string big_to_string(const boost::multiprecision::cpp_int &i, size_t base, size_t nbits, size_t limit = std::numeric_limits<size_t>::max());\n  \n    std::string big_to_string(cell big, size_t base, bool capital = false, size_t limit = std::numeric_limits<size_t>::max()) const;\n    std::string big16_to_string(cell big, size_t limit) const;    \n    inline size_t num_cells(const boost::multiprecision::cpp_int &i)\n    {\n\tusing namespace boost::multiprecision;\n\treturn (msb(i) + untagged_cell::CELL_NUM_BITS) /\n\t    untagged_cell::CELL_NUM_BITS;\n    }\n\n    void set_big(cell big, const boost::multiprecision::cpp_int &i);\n\n    inline void get_big(cell big, boost::multiprecision::cpp_int &i,\n\t\t\tsize_t &nbits) const\n    {\n\tusing namespace boost::multiprecision;\n\t\n\tcell dc = deref(big);\n\tauto &b = reinterpret_cast<const big_cell &>(dc);\n\tnbits = num_bits(b);\n\timport_bits(i, begin(b), end(b), 8);\n    }\n    \n    inline size_t new_cell0(cell c, bool has_tag = true)\n    {\n        cell *p;\n        size_t index;\n\tif(has_tag) {\n\t  if(c.tag() == tag_t::CON) {\n\t    auto &con = reinterpret_cast<con_cell &>(c);\n\t    ensure_allocate(1+con.arity());\n\t  }\n\t}\n        std::tie(p, index) = allocate(tag_t::STR, 1);\n\t*p = c;\n\treturn index;\n    }\n\n    inline void new_dat_cell(cell c)\n    {\n        cell *p;\n        size_t index;\n\tstd::tie(p, index) = allocate(tag_t::DAT, 1, true);\n\t*p = c;\n    }\n    \n    inline term new_dotted_pair()\n    {\n        term t = new_str0(DOTTED_PAIR);\n\treturn t;\n    }\n\n    inline term new_dotted_pair(const term a, const term b)\n    {\n\tterm t = new_str(DOTTED_PAIR);\n\tset_arg(t, 0, a);\n\tset_arg(t, 1, b);\n\treturn t;\n    }\n\n    inline term new_ref()\n    {\n\tsize_t index;\n\tcell *p;\n\tstd::tie(p, index) = allocate(tag_t::REF, 1);\n\tstatic_cast<ref_cell &>(*p).set_index(index);\n\treturn term(*this, *p);\n    }\n\n    inline void new_ref(size_t cnt)\n    {\n\tfor (size_t i = 0; i < cnt; i++) {\n\t    new_ref();\n\t}\n    }\n\n    inline size_t external_ptr_count() const\n    {\n\treturn external_ptrs_.size();\n    }\n\n    void print_status(std::ostream &out) const;\n\n    void print(std::ostream &out) const;\n    void print(std::ostream &out, size_t from, size_t to) const;\n\n    inline void add_watched(size_t addr) {\n        if (std::find(watched_.begin(), watched_.end(), addr) == watched_.end()) {\n           watched_.push_back(addr);\n\t}\n    }\n\n    inline bool has_watched() const {\n        return !watched_.empty();\n    }\n\n    inline void clear_watched() {\n        watched_.clear();\n    }\n\n    inline void watch(size_t addr, bool b) {\n        find_block(addr).watch(addr, b);\n    }\n\n    inline const std::vector<size_t> & watched() const {\n        return watched_;\n    }\n\n    inline bool watched(size_t addr) const {\n        return find_block(addr).watched(addr);\n    }  \n  \n    bool check_term(const term t, std::string *name = nullptr) const;\nprivate:\n    friend class term_emitter;\n\nprotected:\n    inline size_t find_block_index(size_t addr) const\n    {\n\treturn addr / heap_block::MAX_SIZE;\n    }\n\n    inline size_t last_block_index() const\n    {\n\tsize_t hsz = size();\n\treturn hsz == 0 ? 0 : find_block_index(hsz-1);\n    }\n\npublic:\n    static const size_t NEW_BLOCK = static_cast<size_t>(-1);\n\n    static inline heap_block & get_block_default(heap &h, void * /*context*/, size_t block_index)\n    {\n        if (block_index == NEW_BLOCK) {\n  \t    new_block_default(h);\n\t    block_index = h.blocks_.size();\n\t}\n        return *h.blocks_[block_index];\n    }\n\n    static inline void modified_block_default(heap_block & /*block*/, void * /* context */) {\n        // Do nothing\n    }\n\n    static inline size_t new_atom_default(const heap &h, void * /* context */, const std::string &name) {\n\t// This is a simple way of returning new identifiers for atoms\n\t// but it is not deterministic. For the global Prolog interpreter\n\t// we need to query the database.\n\treturn h.atom_name_to_index_table_.size();\n    }\n\n    static inline void load_atom_name_default(heap &h, void * /* context */, size_t index)\n    {\n    }\n\n    static inline void load_atom_index_default(heap &, void * /* context */, const std::string &name)\n    {\n    }\n\n    static inline void trim_default(heap &h, void * /* context */, size_t new_size) {\n\th.internal_trim(new_size);\n    }\n\n    inline void set_atom_index(const std::string &name, size_t index)\n    {\n\tatom_name_to_index_table_[name] = index;\n\tatom_index_to_name_table_[index] = name;\n    }\n\n    inline size_t get_atom_index(const std::string &name)\n    {\n\tauto it = atom_name_to_index_table_.find(name);\n\tif (it == atom_name_to_index_table_.end()) {\n\t    return 0;\n\t}\n\treturn it->second;\n    }\n\n    inline void clear_atom_index(const std::string &name, size_t index)\n    {\n\tatom_name_to_index_table_.erase(name);\n\tatom_index_to_name_table_.erase(index);\n    }\n\n    inline heap_block * get_head_block() {\n        return head_block_;\n    }\n  \n    inline void set_head_block(heap_block *h) {\n        head_block_ = h;\n\tif (h != nullptr) {\n\t    size_ = h->index() * heap_block::MAX_SIZE + h->size();\n\t}\n    }\n\nprivate:\n\n    static inline void new_block_default(heap &h)\n    {\n        heap_block *block = new heap_block(h, h.blocks_.size());\n\th.set_head_block(block);\n\th.blocks_.push_back(block);\n    }\n\n    inline heap_block * find_block_from_index(size_t index) const\n    {\n        return blocks_[index];\n    }\n\n    inline heap_block & find_block(size_t addr)\n    {\n        return get_block_fn_(*this, get_block_fn_context_, find_block_index(addr));\n    }\n\n    inline const heap_block & find_block(size_t addr) const\n    {\n        return get_block_fn_(const_cast<heap &>(*this), get_block_fn_context_, find_block_index(addr));\n    }\n\n    inline const bool in_range(size_t addr) const\n    {\n\treturn addr < size();\n    }\n\n    inline heap_block * ensure_allocate(size_t n, bool span = false) {\n\tif (!span) {\n\t    if (head_block_ == nullptr || !head_block_->can_allocate(n)) {\n\t\tget_block_fn_(*this, get_block_fn_context_, NEW_BLOCK);\n\t    }\n\t    return head_block_;\n\t} else {\n\t    heap_block *block = nullptr;\n\t    while (n > 0) {\n\t\tif (head_block_ == nullptr || head_block_->is_full()) {\n\t\t    get_block_fn_(*this, get_block_fn_context_, NEW_BLOCK);\n\t\t}\n\t\tif (!block) block = head_block_;\n\t\tsize_t next_alloc = std::min(n, heap_block::MAX_SIZE - head_block_->size());\n\t\thead_block_->allocate0(next_alloc);\n\t\tn -= next_alloc;\n\t    }\n\t    return block;\n\t}\n    }\n\n    inline std::pair<cell *, size_t> allocate(tag_t::kind_t tag, size_t n, bool span = false) {\n\tsize_t addr = size_;\n\theap_block *block = ensure_allocate(n, span);\n\tif (!span) {\n\t    block = head_block_;\n\t    addr = block->allocate(n);\n\t}\n\tsize_ = head_block_->offset() + head_block_->size();\n\tptr_cell new_cell(tag, addr);\n\tcell *p = &(*block)[addr];\n\t*p = new_cell;\n\treturn std::make_pair(p, addr);\n    }\n\n    inline const cell & get(size_t addr) const\n    {\n\tcheck_index(addr);\n\treturn find_block(addr)[addr];\n    }\n\n    inline cell arg0(const cell &c, size_t index) const\n    {\n        const str_cell &s = static_cast<const str_cell &>(c);\n\treturn get(s.index() + index + 1);\n    }\n\n#ifdef DEBUG_TERM\n    inline size_t register_ext(cell *p) const\n#else\n    inline void register_ext(cell *p) const\n#endif\n    {\n\tif (external_ptrs_.size() > external_ptrs_max_) {\n\t    external_ptrs_max_ = external_ptrs_.size();\n\t}\n#ifdef DEBUG_TERM\n\tsize_t id = id_counter_++;\n        external_ptrs_.insert(std::make_pair(p, id));\n\treturn id;\n#else\n        external_ptrs_.insert(p);\n#endif\n    }\n\n    inline void unregister_ext(cell *p) const\n    {\n#ifdef DEBUG_TERM\n\tassert(external_ptrs_.erase(p) == 1);\n#else\n        external_ptrs_.erase(p);\n#endif\n    }\n\n    bool check_functor(const cell c) const;\n\n    size_t size_;\n    std::vector<heap_block *> blocks_;\n    heap_block * head_block_;\n    std::vector<size_t> watched_;\n\n    bool coin_security_enabled_;\n\n#ifdef DEBUG_TERM\n    mutable std::unordered_map<cell *, size_t> external_ptrs_;\n    static size_t id_counter_;\n#else\n    mutable std::unordered_set<cell *> external_ptrs_;\n#endif\n    mutable size_t external_ptrs_max_;\n\n    mutable std::unordered_map<size_t, std::string> atom_index_to_name_table_;\n    mutable std::unordered_map<std::string, size_t> atom_name_to_index_table_;\n\npublic:\n    static const con_cell EMPTY_LIST;\n    static const con_cell DOTTED_PAIR;\n    static const con_cell COMMA;\n    static const con_cell COIN;\n\n    template<typename T> friend class ext;\n\n    typedef heap_block & (*get_block_fn)(heap &h, void *context, size_t block_index);\n    typedef void (*modified_block_fn)(heap_block &block, void *context);\n    typedef size_t (*new_atom_fn)(const heap &h, void *context, const std::string &atom_name);\n    typedef void (*load_atom_name_fn)(heap &h, void *context, size_t atom_index);\n    typedef void (*load_atom_index_fn)(heap &h, void *context, const std::string &atom_name);\n    typedef void (*trim_fn)(heap &h, void *context, size_t new_size);\n  \n    inline void setup_get_block_fn(get_block_fn fn, void *context) { get_block_fn_ = fn; get_block_fn_context_ = context; }\n    inline void setup_modified_block_fn(modified_block_fn fn, void *context) { modified_block_fn_ = fn; modified_block_fn_context_ = context; }\n    inline void setup_new_atom_fn(new_atom_fn fn, void *context) { new_atom_fn_ = fn; new_atom_fn_context_ = context; }\n    inline void setup_load_atom_name_fn(load_atom_name_fn fn, void *context) { load_atom_name_fn_ = fn; load_atom_name_fn_context_ = context; }    \n    inline void setup_load_atom_index_fn(load_atom_index_fn fn, void *context) { load_atom_index_fn_ = fn; load_atom_index_fn_context_ = context; }\n    inline void setup_trim_fn(trim_fn fn, void *context) { trim_fn_ = fn; trim_fn_context_ = context; }\n\nprivate:\n    get_block_fn get_block_fn_;\n    void *get_block_fn_context_;\n\n    friend class heap_block;\n    modified_block_fn modified_block_fn_;\n    void *modified_block_fn_context_;\n\n    new_atom_fn new_atom_fn_;\n    void *new_atom_fn_context_;\n\n    load_atom_name_fn load_atom_name_fn_;\n    void *load_atom_name_fn_context_;\n\n    load_atom_index_fn load_atom_index_fn_;\n    void *load_atom_index_fn_context_;    \n\n    trim_fn trim_fn_;\n    void *trim_fn_context_;\n};\n\ninline void heap_block::modified() {\n    heap_.modified_block_fn_(*this, heap_.modified_block_fn_context_);\n}\n\ninline bool heap_block::is_head_block() const {\n    return this == heap_.head_block_;\n}\n\ntemplate<typename T> inline big_iterator_base<T>::big_iterator_base(heap &h, size_t index, size_t num) \n : heap_(h),\n   index_(index),\n   i_(4),\n   end_(num+4),\n   cell_byte_(&h.untagged_at(index), 4, num+4) { }\n\ntemplate<typename T> inline big_iterator_base<T>::big_iterator_base(heap &h, size_t index, size_t num, bool b)\n : heap_(h),\n   index_(index),\n   i_(num+4),\n   end_(num+4),\n   cell_byte_(&h.untagged_at(index), 4, num+4) { }\n\ntemplate<typename T> inline big_iterator_base<T>::big_iterator_base(const big_iterator_base<T> &it)\n : heap_(it.heap_),\n   index_(it.index_),\n   i_(it.i_),\n   end_(it.end_),\n   cell_byte_(it.cell_byte_) { }\n\ntemplate<typename T> inline big_iterator_base<T> & big_iterator_base<T>::operator ++()\n{\n    i_++;\n    if (i_ % 8 == 0) {\n\tindex_++;\n\tif ((index_ % heap_block::MAX_SIZE) == 0) {\n\t    // Are we stepping over a heap block boundary?\n\t    // Then we need to switch base address for cell_byte\n\t    cell_byte_.set_address(&heap_.untagged_at(index_), 0);\n\t} else {\n\t    ++cell_byte_;\t    \n\t}\n    } else {\n\t++cell_byte_;\n    }\n    return *this;\n}\n\ninline cell_byte & big_iterator::operator * ()\n{\n    return cell_byte_;\n}\n\ninline const cell_byte & const_big_iterator::operator * () const\n{\n    return cell_byte_;\n}\n\ninline big_inserter::big_inserter(heap &h, big_cell big) :\n    it_(h.begin(big))\n{\n}\n\n//\n//  register and unregister for ref.\n//\n\n#if 0\n\n#ifdef DEBUG_TERM\ntemplate<typename T> size_t ext<T>::ext_register(const heap &h, cell *p)\n{\n    return h.register_ext(p);\n}\n#else\ntemplate<typename T> void ext<T>::ext_register(const heap &h, cell *p)\n{\n    h.register_ext(p);\n}\n#endif\n\ntemplate<typename T> void ext<T>::ext_unregister(const heap &h, cell *p)\n{\n    h.unregister_ext(p);\n}\n\ntemplate<typename T> T ext<T>::deref() const\n{\n    cell c = heap_->deref(ptr_);\n    ptr_ = c;\n    return ext<T>(*heap_, c);\n}\n\ntemplate<typename T> T ext<T>::operator * () const\n{\n    return deref();\n}\n\ntemplate<typename T> const T * ext<T>::operator -> () const\n{\n    deref();\n    return &ptr_;\n}\n\ntemplate<typename T> T * ext<T>::operator -> ()\n{\n    deref();\n    return &ptr_;\n}\n\ntemplate<typename T> ext<T>::operator T ()\n{\n    return ptr_;\n}\n\ntemplate<typename T> ext<T>::operator const T & () const\n{\n    return ptr_;\n}\n\n#endif\n\n} }\n\nnamespace boost {\n    template<> struct make_unsigned<epilog::common::untagged_cell> {\n\ttypedef epilog::common::untagged_cell::value_t type;\n    };\n}\n\nnamespace std {\n    template<> struct hash<epilog::common::cell> {\n        size_t operator()(const epilog::common::cell k) const {\n\t    return hash<uint64_t>()(k.value());\n\t}\n    };\n\n    template<> struct hash<epilog::common::ref_cell> {\n        size_t operator()(const epilog::common::ref_cell k) const {\n\t    return hash<uint64_t>()(k.index());\n\t}\n    };\n\n    template<> struct hash<epilog::common::int_cell> {\n        size_t operator()(const epilog::common::int_cell k) const {\n\t    return hash<uint64_t>()(k.value());\n\t}\n    };\n\n    template<> struct hash<epilog::common::con_cell> {\n\tsize_t operator()(const epilog::common::con_cell k) const {\n\t    return hash<uint64_t>()(k.value());\n\t}\n    };\n\n    template<> struct hash<epilog::common::term> {\n        size_t operator()(const epilog::common::term& k) const {\n\t    auto &c = reinterpret_cast<const epilog::common::cell &>(k);\n\t    return hash<uint64_t>()(c.value());\n\t}\n    };\n}\n\nnamespace epilog { namespace common {\n\n// For term naming\nclass naming_map {\npublic:\n    void clear_names() {\n\tref_2_name_.clear();\n    }\n    const std::string & get_name(ref_cell r) const {\n\tstatic std::string empty;\n\tauto it = ref_2_name_.find(r);\n\tif (it == ref_2_name_.end()) {\n\t    return empty;\n\t}\n\treturn it->second;\n    }\n    void set_name(ref_cell r, const std::string &name) {\n\tref_2_name_[r] = name;\n    }\n    void clear_name(ref_cell r) {\n\tref_2_name_.erase(r);\n    }\n    bool has_name(ref_cell r) const {\n\treturn ref_2_name_.count(r);\n    }\n    size_t size() const {\n\treturn ref_2_name_.size();\n    }\n    void trim_names(size_t heap_limit) {\n\tref_cell r(heap_limit);\n\tauto it_end = ref_2_name_.end();\n\tfor (auto it = ref_2_name_.lower_bound(r); it != it_end; ++it) {\n\t    ref_2_name_.erase(it);\n\t}\n    }\n    \nprivate:\n    std::map<ref_cell, std::string> ref_2_name_;\n};\n\n} }\n\n#endif\n\n", "meta": {"hexsha": "ee1128e1051bf4eb0b57c8221b0c623f07bb4040", "size": 51746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/term.hpp", "max_stars_repo_name": "datavetaren/epilog", "max_stars_repo_head_hexsha": "7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/term.hpp", "max_issues_repo_name": "datavetaren/epilog", "max_issues_repo_head_hexsha": "7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/term.hpp", "max_forks_repo_name": "datavetaren/epilog", "max_forks_repo_head_hexsha": "7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0422747861, "max_line_length": 156, "alphanum_fraction": 0.6383102076, "num_tokens": 13957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.039048292306868335, "lm_q1q2_score": 0.017096259399360134}}
{"text": "#include <chrono>\n#include <iostream>\n#include <vector>\n#include <cmath>\n\n// number of DLA dimensions (must be 2 or 3)\n#define DLA_DIM 3\n\n// change to use float or double precision\nusing precisionT = float;\n\n// BENCHMARKS\n//      It Don't prints values add only to memory, use if you\n//      want to bench several PRNG-algorithms/indices-libs\n//\n//#define DLAF_BENCHMARK\n\n// vec3 represents a point or a vec3\n/////////////////////////////////////////////////////////////////////\ntemplate<typename T> class vec3 {\npublic:\n    T x, y, z;\n\n    vec3() = default;\n    explicit vec3(T s) : x(s), y(s), z(s) {}\n    vec3(T x, T y) : x(x), y(y), z(0) {}\n    vec3(T x, T y, T z) : x(x), y(y), z(z) {}\n\n    vec3 operator-() const { return { -x, -y, -z }; }\n\n    vec3& operator+=(const vec3& v) { x += v.x; y += v.y; z += v.z; return *this; }\n    vec3& operator-=(const vec3& v) { x -= v.x; y -= v.y; z -= v.z; return *this; }\n    vec3& operator*=(const vec3& v) { x *= v.x; y *= v.y; z *= v.z; return *this; }\n    vec3& operator/=(const vec3& v) { x /= v.x; y /= v.y; z /= v.z; return *this; }\n    vec3& operator*=(T s)           { x *= s  ; y *= s  ; z *= s  ; return *this; }\n    vec3& operator/=(T s)           { x /= s  ; y /= s  ; z /= s  ; return *this; }\n\n    vec3 operator+(const vec3& v) const { return { x + v.x, y + v.y, z + v.z }; }\n    vec3 operator-(const vec3& v) const { return { x - v.x, y - v.y, z - v.z }; }\n    vec3 operator*(const vec3& v) const { return { x * v.x, y * v.y, z * v.z }; }\n    vec3 operator/(const vec3& v) const { return { x / v.x, y / v.y, z / v.z }; }\n    vec3 operator*(T s)           const { return { x * s  , y * s  , z * s   }; }\n    vec3 operator/(T s)           const { return { x / s  , y / s  , z / s   }; }\n\n    const T& operator[](int i) const { return *(&x + i); }\n          T& operator[](int i)       { return *(&x + i); }\n\n    explicit operator T *() const { return &x; }\n    explicit operator T *()       { return &x; }\n\n    T Length() const { return std::sqrt(LengthSquared()); }\n    T LengthSquared() const { return x*x + y*y + z*z; }\n    T Distance(const vec3 &v) const { const vec3 dv{*this-v}; return dv.Length(); }\n    vec3 Normalized() const { const T m = 1 / Length(); return { x*m, y*m, z*m }; }\n\n};\n\n// Pseudo Random Generator to use\n/////////////////////////////////////////////////////////////////////\n#define DLAF_USE_FAST_RANDOM    //comment to use std::mt19937 & std::uniform_real_distribution\n#ifdef DLAF_USE_FAST_RANDOM\n//Use Blackman/Vigna fast random generator\n    #include \"fastPRNG.h\"\n    using namespace fastPRNG;\n    #define DLAF_USE_64BIT_GENERATOR\n    #ifdef DLAF_USE_64BIT_GENERATOR\n        fastXS64 fastRandom;\n        #define DLA_RANDOM_VNI fastRandom.xoroshiro128p_VNI<T>()    // [-1.0, 1.0]\n        #define DLA_RANDOM_UNI fastRandom.xoroshiro128p_UNI<T>()    // [ 0.0, 1.0]\n    #else\n        fastXS32 fastRandom;\n        #define DLA_RANDOM_NORM fastRandom.xoshiro128p_VNI<T>()    // [-1.0, 1.0]\n        #define DLA_RANDOM_01   fastRandom.xoshiro128p_UNI<T>()    // [ 0.0, 1.0]\n    #endif\n#else\n// std::mt19937 & std::uniform_real_distribution\n// Random returns a uniformly distributed random number between lo and hi\n    #include <random>\n    template<typename T> T Random(const T lo = 0, const T hi = 1) {\n        static thread_local std::mt19937 gen(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n        std::uniform_real_distribution<T> dist(lo, hi);\n        return dist(gen);\n    }\n    #define DLA_RANDOM_NORM Random(T(-1.0), T(1.0))\n    #define DLA_RANDOM_01   Random(T( 0.0), T(1.0))\n#endif\n\n\n// Library to use for spatial index\n/////////////////////////////////////////////////////////////////////\n#define DLAF_USE_FLANN_LIBRARY   // comment to use boost instead nanoflann\n#ifdef DLAF_USE_FLANN_LIBRARY\n// nanoflann is used for its spatial index\n    #include \"nanoflann.hpp\"\n\n    #define parentPOINT(PARENT) m_Points.pts[PARENT]\n    #define thisPOINT m_Points.pts\n\ntemplate <typename T> struct pointCloud\n{\n    std::vector<vec3<T>> pts;\n    \n    // Must return the number of data points\n    inline size_t kdtree_get_point_count() const { return pts.size(); }\n    \n    // Returns the dim'th component of the idx'th point in the class:\n    // Since this is inlined and the \"dim\" argument is typically an immediate value, the\n    //  \"if/else's\" are actually solved at compile time.\n    inline T kdtree_get_pt(const size_t idx, const size_t dim) const { return pts[idx][dim]; }\n\n    \n    // Optional bounding-box computation: return false to default to a standard bbox computation loop.\n    //   Return true if the BBOX was already computed by the class and returned in \"bb\" so it can be avoided to redo it again.\n    //   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\n    template <class BBOX> bool kdtree_get_bbox(BBOX& /* bb */) const { return false; }\n    \n};\n\nusing tPointCloud =  pointCloud<precisionT>;\nusing tKDTreeDistanceFunc = nanoflann::L2_Adaptor<precisionT, tPointCloud>;\nusing tKDTree = nanoflann::KDTreeSingleIndexDynamicAdaptor<tKDTreeDistanceFunc, tPointCloud, DLA_DIM>;\n#else\n// boost is used for its spatial index\n    #include <boost/function_output_iterator.hpp>\n    #include <boost/geometry/geometry.hpp>\n\n    using BoostPoint = boost::geometry::model::point<precisionT, DLA_DIM, boost::geometry::cs::cartesian>;\n    using IndexValue = std::pair<BoostPoint, uint32_t>;\n    using Index = boost::geometry::index::rtree<IndexValue, boost::geometry::index::linear<4>>;\n\n    #define parentPOINT(PARENT) m_Points[PARENT]\n    #define thisPOINT m_Points\n#endif\n\n// Lerp linearly interpolates from a to b by distance.\ntemplate<typename T> vec3<T> Lerp(const vec3<T> &a, const vec3<T> &b, const T d) {\n    return a + (b - a).Normalized() * d;\n}\n\n// default parameters (documented below)\nconst precisionT DefaultParticleSpacing = 1;\nconst precisionT DefaultAttractionDistance = 3;\nconst precisionT DefaultMinMoveDistance = 1;\nconst precisionT DefaultStickiness = 1;\nconst int DefaultStubbornness = 0;\n\n// Model holds all of the particles and defines their behavior.\ntemplate<typename T> class Model {\npublic:\n    Model<T>() : \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#ifdef  DLAF_USE_FLANN_LIBRARY\n        { m_Index = new tKDTree(DLA_DIM, m_Points, nanoflann::KDTreeSingleIndexAdaptorParams(10 /*max leaf*/)); }\n        ~Model<T>() { delete m_Index; }\n#else        \n        {}\n#endif        \n\n    void SetParticleSpacing(const T a) {\n        m_ParticleSpacing = a;\n    }\n\n    void SetAttractionDistance(const T a) {\n        m_AttractionDistance = a;\n    }\n\n    void SetMinMoveDistance(const T a) {\n        m_MinMoveDistance = a;\n    }\n\n    void SetStubbornness(const int a) {\n        m_Stubbornness = a;\n    }\n\n    void SetStickiness(const T a) {\n        m_Stickiness = a;\n    }\n\n#ifdef DLAF_USE_FLANN_LIBRARY\n    // Add adds a new particle with the specified parent particle\n    void Add(const vec3<T>& p, const size_t parent = 0) {\n        size_t id = m_Points.pts.size();\n        m_Points.pts.push_back(p);\n        m_JoinAttempts.push_back(0);\n        m_Index->addPoints(id, id);\n\n        m_BoundingRadius = std::max(m_BoundingRadius, p.Length() + m_AttractionDistance);\n#ifndef DLAF_BENCHMARK\n        std::cout << id << \",\" << parent << \",\" << p.x << \",\" << p.y << \",\" << p.z << std::endl;\n#endif\n\n    }\n\n    // Nearest returns the index of the particle nearest the specified point\n    size_t Nearest(const vec3<T> &point) const {\n        size_t ret_index;\n        T out_dist_sqr = m_AttractionDistance;\n        nanoflann::KNNResultSet<T> resultSet(1);\n        resultSet.init(&ret_index, &out_dist_sqr );\n        m_Index->findNeighbors(resultSet, (const T *) &point, \n                               nanoflann::SearchParams(0, //how many leafs to visit - not used in nanoflann\n                                                       m_AttractionDistance*T(.5))); //search for eps-approximate neighbours\n        return ret_index;\n    }\n#else\n    // Add adds a new particle with the specified parent particle\n    void Add(const vec3<T> &p, const size_t parent = -1) {\n        const size_t id = m_Points.size();\n        m_Index.insert(std::make_pair(BoostPoint(p.x, p.y, p.z), uint32_t(id)));\n        m_Points.push_back(p);\n        m_JoinAttempts.push_back(0);\n        m_BoundingRadius = std::max(m_BoundingRadius, p.Length() + m_AttractionDistance);\n#ifndef DLAF_BENCHMARK\n        std::cout << id << \",\" << parent << \",\" << p.x << \",\" << p.y << \",\" << p.z << std::endl;\n#endif\n    }\n    // Nearest returns the index of the particle nearest the specified point\n    uint32_t Nearest(const vec3<T> &p) const {\n        uint32_t result = -1;\n        m_Index.query(\n            boost::geometry::index::nearest(BoostPoint(p.x, p.y, p.z), 1),\n            boost::make_function_output_iterator([&result](const auto &value) {\n                result = value.second;\n            }));\n        return result;\n    }\n#endif\n    // RandomInUnitSphere returns a random, uniformly distributed point inside the\n    // unit sphere (radius = 1)\n    vec3<T> RandomInUnitSphere() const {\n        vec3<T> p;\n        do {\n            p = vec3<T>(DLA_RANDOM_VNI,\n                        DLA_RANDOM_VNI,\n                        DLA_DIM == 2 ? T(0) : DLA_RANDOM_VNI);\n        } while(p.Length() >= T(1.0));\n\n        return p;\n    }\n\n    // RandomStartingPosition returns a random point to start a new particle\n    vec3<T> RandomStartingPosition() const {\n        const T 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 vec3<T> &p) const {\n        return p.Length() > m_BoundingRadius * T(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 vec3<T> &p, const size_t parent) {\n        return (m_JoinAttempts[parent]++ < m_Stubbornness) ? false : DLA_RANDOM_UNI <= m_Stickiness;\n    }\n\n    // PlaceParticle computes the final placement of the particle.\n    vec3<T> PlaceParticle(const vec3<T> &p, const size_t parent) const {\n        return Lerp(parentPOINT(parent), p, m_ParticleSpacing);\n    }\n\n    // Motionvec3 returns a vec3 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    vec3<T> Motionvec3(const vec3<T> &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        vec3<T> p = RandomStartingPosition();\n\n        // do the random walk\n        while (true) {\n            // get distance to nearest other particle\n            const size_t parent = Nearest(p);\n            const T d = p.Distance(parentPOINT(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(parentPOINT(parent), p, m_AttractionDistance + m_MinMoveDistance);\n                    continue;\n                }\n\n                // adjust particle position in relation to its parent\n                p = PlaceParticle(p, parent);\n\n                // adjust particle pos in relation to its parent and add the point\n                Add(PlaceParticle(p, parent), parent); \n                return;\n            }\n\n            // move randomly\n            const T m = std::max(m_MinMoveDistance, d - m_AttractionDistance);\n                p += Motionvec3(p).Normalized() * m;\n\n            // check if particle is too far away, reset if so\n            if (ShouldReset(p)) p = RandomStartingPosition();\n        }\n    }\n\nprivate:\n    // m_ParticleSpacing defines the distance between particles that are\n    // joined together\n    T m_ParticleSpacing;\n\n    // m_AttractionDistance defines how close together particles must be in\n    // order to join together\n    T m_AttractionDistance;\n\n    // m_MinMoveDistance defines the minimum distance that a particle will move\n    // during its random walk\n    T 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    T m_Stickiness;\n\n    // m_BoundingRadius defines the radius of the bounding sphere that bounds\n    // all of the particles\n    T m_BoundingRadius;\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\n#ifdef DLAF_USE_FLANN_LIBRARY\n    // m_Index is the spatial index used to accelerate nearest neighbor queries\n    tKDTree *m_Index;\n    // m_Points stores the final particle positions\n    tPointCloud m_Points;\n#else\n    // m_Index is the spatial index used to accelerate nearest neighbor queries\n    Index m_Index;\n    // m_Points stores the final particle positions\n    std::vector<vec3<T>> m_Points;\n#endif\n};\n\nint main() {\n    // use float or double precision\n    //  using precisionT = float;\n\n    auto start = std::chrono::high_resolution_clock::now();\n    // run diffusion-limited aggregation\n\n    // create the model\n    Model<precisionT> model;\n\n    // add seed point(s)\n    model.Add(vec3<precisionT>(0.0));\n\n    // {\n    //     const int n = 3600;\n    //     const precisionT r = 1000;\n    //     for (int i = 0; i < n; i++) {\n    //         const precisionT t = (precisionT)i / n;\n    //         const precisionT a = t * 2 * M_PI;\n    //         const precisionT x = std::cos(a) * r;\n    //         const precisionT y = std::sin(a) * r;\n    //         model.Add(vec3<precisionT>(x, y, 0));\n    //     }\n    // }\n    for (int i = 0; i < 1000000; i++) {\n        model.AddParticle();\n    }\n   \n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> diff = end-start;\n\n    std::cerr << \"Time elapsed: \" << diff.count() << \" sec.\" << std::endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "d9332f542b282e752d647a81c1f743558879dc64", "size": 14617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlaf.cpp", "max_stars_repo_name": "BrutPitt/dlaf-optimized", "max_stars_repo_head_hexsha": "6eea813eccf0f3c559b87f177a7b206afad8e4d3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-12-23T06:58:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T21:48:31.000Z", "max_issues_repo_path": "dlaf.cpp", "max_issues_repo_name": "BrutPitt/DLAf-optimized", "max_issues_repo_head_hexsha": "6eea813eccf0f3c559b87f177a7b206afad8e4d3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-10T01:03:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-10T01:03:56.000Z", "max_forks_repo_path": "dlaf.cpp", "max_forks_repo_name": "BrutPitt/dlaf-optimized", "max_forks_repo_head_hexsha": "6eea813eccf0f3c559b87f177a7b206afad8e4d3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-26T01:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T13:00:53.000Z", "avg_line_length": 37.2882653061, "max_line_length": 126, "alphanum_fraction": 0.6170896901, "num_tokens": 3865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015565456543, "lm_q2_score": 0.036769467131121676, "lm_q1q2_score": 0.017094182502612743}}
{"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/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  Copyright (c) 2006-2011, The libDAI authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license that can be found\n * in the LICENSE file.\n */\n\n#include <iostream>\n#include <iomanip>\n#include <iterator>\n#include <map>\n#include <set>\n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <functional>\n#include <dai/factorgraph.h>\n#include <dai/util.h>\n#include <dai/exceptions.h>\n#include <boost/lexical_cast.hpp>\n\nnamespace dai {\n\nusing namespace std;\n\nFactorGraph::FactorGraph(const std::vector<Factor>& P) : _G(), _backup() {\n  // add factors, obtain variables\n  set<Var> varset;\n  _factors.reserve(P.size());\n  size_t nrEdges = 0;\n  for (vector<Factor>::const_iterator p2 = P.begin(); p2 != P.end(); p2++) {\n    _factors.push_back(*p2);\n    copy(p2->vars().begin(), p2->vars().end(),\n         inserter(varset, varset.begin()));\n    nrEdges += p2->vars().size();\n  }\n\n  // add vars\n  _vars.reserve(varset.size());\n  for (set<Var>::const_iterator p1 = varset.begin(); p1 != varset.end(); p1++)\n    _vars.push_back(*p1);\n\n  // create graph structure\n  constructGraph(nrEdges);\n}\n\nvoid FactorGraph::constructGraph(size_t nrEdges) {\n  // create a mapping for indices\n  hash_map<size_t, size_t> hashmap;\n\n  for (size_t i = 0; i < vars().size(); i++)\n    hashmap[var(i).label()] = i;\n\n  // create edge list\n  vector<Edge> edges;\n  edges.reserve(nrEdges);\n  for (size_t i2 = 0; i2 < nrFactors(); i2++) {\n    const VarSet& ns = factor(i2).vars();\n    for (VarSet::const_iterator q = ns.begin(); q != ns.end(); q++)\n      edges.push_back(Edge(hashmap[q->label()], i2));\n  }\n\n  // create bipartite graph\n  _G.construct(nrVars(), nrFactors(), edges.begin(), edges.end());\n}\n\n/// Writes a FactorGraph to an output stream\nstd::ostream& operator<<(std::ostream& os, const FactorGraph& fg) {\n  os << fg.nrFactors() << endl;\n\n  for (size_t I = 0; I < fg.nrFactors(); I++) {\n    os << endl;\n    os << fg.factor(I).vars().size() << endl;\n    for (VarSet::const_iterator i = fg.factor(I).vars().begin();\n         i != fg.factor(I).vars().end(); i++)\n      os << i->label() << \" \";\n    os << endl;\n    for (VarSet::const_iterator i = fg.factor(I).vars().begin();\n         i != fg.factor(I).vars().end(); i++)\n      os << i->states() << \" \";\n    os << endl;\n    size_t nr_nonzeros = 0;\n    for (size_t k = 0; k < fg.factor(I).nrStates(); k++)\n      if (fg.factor(I)[k] != (Real)0)\n        nr_nonzeros++;\n    os << nr_nonzeros << endl;\n    for (size_t k = 0; k < fg.factor(I).nrStates(); k++)\n      if (fg.factor(I)[k] != (Real)0)\n        os << k << \" \" << setw(os.precision() + 4) << fg.factor(I)[k] << endl;\n  }\n\n  return (os);\n}\n\n/// Reads a FactorGraph from an input stream\nstd::istream& operator>>(std::istream& is, FactorGraph& fg) {\n  long verbose = 0;\n\n  vector<Factor> facs;\n  size_t nr_Factors;\n  string line;\n\n  while ((is.peek()) == '#')\n    getline(is, line);\n  is >> nr_Factors;\n  if (is.fail())\n    DAI_THROWE(INVALID_FACTORGRAPH_FILE, \"Cannot read number of factors\");\n  if (verbose >= 1)\n    cerr << \"Reading \" << nr_Factors << \" factors...\" << endl;\n\n  getline(is, line);\n  if (is.fail() || line.size() > 0)\n    DAI_THROWE(INVALID_FACTORGRAPH_FILE, \"Expecting empty line\");\n\n  map<long, size_t> vardims;\n  for (size_t I = 0; I < nr_Factors; I++) {\n    if (verbose >= 2)\n      cerr << \"Reading factor \" << I << \"...\" << endl;\n    size_t nr_members;\n    while ((is.peek()) == '#')\n      getline(is, line);\n    is >> nr_members;\n    if (verbose >= 2)\n      cerr << \"  nr_members: \" << nr_members << endl;\n\n    vector<long> labels;\n    for (size_t mi = 0; mi < nr_members; mi++) {\n      long mi_label;\n      while ((is.peek()) == '#')\n        getline(is, line);\n      is >> mi_label;\n      labels.push_back(mi_label);\n    }\n    if (verbose >= 2)\n      cerr << \"  labels: \" << labels << endl;\n\n    vector<size_t> dims;\n    for (size_t mi = 0; mi < nr_members; mi++) {\n      size_t mi_dim;\n      while ((is.peek()) == '#')\n        getline(is, line);\n      is >> mi_dim;\n      dims.push_back(mi_dim);\n    }\n    if (verbose >= 2)\n      cerr << \"  dimensions: \" << dims << endl;\n\n    // add the Factor\n    vector<Var> Ivars;\n    Ivars.reserve(nr_members);\n    for (size_t mi = 0; mi < nr_members; mi++) {\n      map<long, size_t>::iterator vdi = vardims.find(labels[mi]);\n      if (vdi != vardims.end()) {\n        // check whether dimensions are consistent\n        if (vdi->second != dims[mi])\n          DAI_THROWE(INVALID_FACTORGRAPH_FILE,\n                     \"Variable with label \" +\n                         boost::lexical_cast<string>(labels[mi]) +\n                         \" has inconsistent dimensions.\");\n      } else\n        vardims[labels[mi]] = dims[mi];\n      Ivars.push_back(Var(labels[mi], dims[mi]));\n    }\n    facs.push_back(\n        Factor(VarSet(Ivars.begin(), Ivars.end(), Ivars.size()), (Real)0));\n    if (verbose >= 2)\n      cerr << \"  vardims: \" << vardims << endl;\n\n    // calculate permutation object\n    Permute permindex(Ivars);\n\n    // read values\n    size_t nr_nonzeros;\n    while ((is.peek()) == '#')\n      getline(is, line);\n    is >> nr_nonzeros;\n    if (verbose >= 2)\n      cerr << \"  nonzeroes: \" << nr_nonzeros << endl;\n    for (size_t k = 0; k < nr_nonzeros; k++) {\n      size_t li;\n      Real val;\n      while ((is.peek()) == '#')\n        getline(is, line);\n      is >> li;\n      while ((is.peek()) == '#')\n        getline(is, line);\n      is >> val;\n\n      // store value, but permute indices first according to internal\n      // representation\n      facs.back().set(permindex.convertLinearIndex(li), val);\n    }\n  }\n\n  if (verbose >= 3)\n    cerr << \"factors:\" << facs << endl;\n\n  fg = FactorGraph(facs);\n\n  return is;\n}\n\nVarSet FactorGraph::Delta(size_t i) const {\n  // calculate Markov Blanket\n  VarSet Del;\n  diaforeach(const Neighbor& I, nbV(i)) // for all neighboring factors I of i\n      diaforeach(const Neighbor& j,\n                 nbF(I)) // for all neighboring variables j of I\n      Del |= var(j);\n\n  return Del;\n}\n\nVarSet FactorGraph::Delta(const VarSet& ns) const {\n  VarSet result;\n  for (VarSet::const_iterator n = ns.begin(); n != ns.end(); n++)\n    result |= Delta(findVar(*n));\n  return result;\n}\n\nvoid FactorGraph::makeCavity(size_t i, bool backup) {\n  // fills all Factors that include var(i) with ones\n  map<size_t, Factor> newFacs;\n  diaforeach(const Neighbor& I, nbV(i)) // for all neighboring factors I of i\n      newFacs[I] = Factor(factor(I).vars(), (Real)1);\n  setFactors(newFacs, backup);\n}\n\nvoid FactorGraph::ReadFromFile(const char* filename) {\n  ifstream infile;\n  infile.open(filename);\n  if (infile.is_open()) {\n    infile >> *this;\n    infile.close();\n  } else\n    DAI_THROWE(CANNOT_READ_FILE,\n               \"Cannot read from file \" + std::string(filename));\n}\n\nvoid FactorGraph::WriteToFile(const char* filename, size_t precision) const {\n  ofstream outfile;\n  outfile.open(filename);\n  if (outfile.is_open()) {\n    outfile.precision(precision);\n    outfile << *this;\n    outfile.close();\n  } else\n    DAI_THROWE(CANNOT_WRITE_FILE,\n               \"Cannot write to file \" + std::string(filename));\n}\n\nvoid FactorGraph::printDot(std::ostream& os) const {\n  os << \"graph FactorGraph {\" << endl;\n  os << \"node[shape=circle,width=0.4,fixedsize=true];\" << endl;\n  for (size_t i = 0; i < nrVars(); i++)\n    os << \"\\tv\" << var(i).label() << \";\" << endl;\n  os << \"node[shape=box,width=0.3,height=0.3,fixedsize=true];\" << endl;\n  for (size_t I = 0; I < nrFactors(); I++)\n    os << \"\\tf\" << I << \";\" << endl;\n  for (size_t i = 0; i < nrVars(); i++)\n    diaforeach(const Neighbor& I, nbV(i)) // for all neighboring factors I of i\n        os\n        << \"\\tv\" << var(i).label() << \" -- f\" << I << \";\" << endl;\n  os << \"}\" << endl;\n}\n\nGraphAL FactorGraph::MarkovGraph() const {\n  GraphAL G(nrVars());\n  for (size_t i = 0; i < nrVars(); i++)\n    diaforeach(const Neighbor& I, nbV(i))\n        diaforeach(const Neighbor& j, nbF(I)) if (i < j) G.addEdge(i, j, true);\n  return G;\n}\n\nbool FactorGraph::isMaximal(size_t I) const {\n  const VarSet& I_vars = factor(I).vars();\n  size_t I_size        = I_vars.size();\n\n  if (I_size == 0) {\n    for (size_t J = 0; J < nrFactors(); J++)\n      if (J != I)\n        if (factor(J).vars().size() > 0)\n          return false;\n    return true;\n  } else {\n    diaforeach(const Neighbor& i, nbF(I)) {\n      diaforeach(const Neighbor& J, nbV(i)) {\n        if (J != I)\n          if ((factor(J).vars() >> I_vars) &&\n              (factor(J).vars().size() != I_size))\n            return false;\n      }\n    }\n    return true;\n  }\n}\n\nsize_t FactorGraph::maximalFactor(size_t I) const {\n  const VarSet& I_vars = factor(I).vars();\n  size_t I_size        = I_vars.size();\n\n  if (I_size == 0) {\n    for (size_t J = 0; J < nrFactors(); J++)\n      if (J != I)\n        if (factor(J).vars().size() > 0)\n          return maximalFactor(J);\n    return I;\n  } else {\n    diaforeach(const Neighbor& i, nbF(I)) {\n      diaforeach(const Neighbor& J, nbV(i)) {\n        if (J != I)\n          if ((factor(J).vars() >> I_vars) &&\n              (factor(J).vars().size() != I_size))\n            return maximalFactor(J);\n      }\n    }\n    return I;\n  }\n}\n\nvector<VarSet> FactorGraph::maximalFactorDomains() const {\n  vector<VarSet> result;\n\n  for (size_t I = 0; I < nrFactors(); I++)\n    if (isMaximal(I))\n      result.push_back(factor(I).vars());\n\n  if (result.size() == 0)\n    result.push_back(VarSet());\n  return result;\n}\n\nReal FactorGraph::logScore(const std::vector<size_t>& statevec) const {\n  // Construct a State object that represents statevec\n  // This decouples the representation of the joint state in statevec from the\n  // factor graph\n  map<Var, size_t> statemap;\n  for (size_t i = 0; i < statevec.size(); i++)\n    statemap[var(i)] = statevec[i];\n  State S(statemap);\n\n  // Evaluate the log probability of the joint configuration in statevec\n  // by summing the log factor entries of the factors that correspond to this\n  // joint configuration\n  Real lS = 0.0;\n  for (size_t I = 0; I < nrFactors(); I++)\n    lS += dai::log(factor(I)[BigInt_size_t(S(factor(I).vars()))]);\n  return lS;\n}\n\nvoid FactorGraph::clamp(size_t i, size_t x, bool backup) {\n  DAI_ASSERT(x <= var(i).states());\n  Factor mask(var(i), (Real)0);\n  mask.set(x, (Real)1);\n\n  map<size_t, Factor> newFacs;\n  diaforeach(const Neighbor& I, nbV(i)) newFacs[I] = factor(I) * mask;\n  setFactors(newFacs, backup);\n\n  return;\n}\n\nvoid FactorGraph::clampVar(size_t i, const vector<size_t>& is, bool backup) {\n  Var n = var(i);\n  Factor mask_n(n, (Real)0);\n\n  diaforeach(size_t i, is) {\n    DAI_ASSERT(i <= n.states());\n    mask_n.set(i, (Real)1);\n  }\n\n  map<size_t, Factor> newFacs;\n  diaforeach(const Neighbor& I, nbV(i)) newFacs[I] = factor(I) * mask_n;\n  setFactors(newFacs, backup);\n}\n\nvoid FactorGraph::clampFactor(size_t I, const vector<size_t>& is, bool backup) {\n  size_t st = factor(I).nrStates();\n  Factor newF(factor(I).vars(), (Real)0);\n\n  diaforeach(size_t i, is) {\n    DAI_ASSERT(i <= st);\n    newF.set(i, factor(I)[i]);\n  }\n\n  setFactor(I, newF, backup);\n}\n\nvoid FactorGraph::backupFactor(size_t I) {\n  map<size_t, Factor>::iterator it = _backup.find(I);\n  if (it != _backup.end())\n    DAI_THROW(MULTIPLE_UNDO);\n  _backup[I] = factor(I);\n}\n\nvoid FactorGraph::restoreFactor(size_t I) {\n  map<size_t, Factor>::iterator it = _backup.find(I);\n  if (it != _backup.end()) {\n    setFactor(I, it->second);\n    _backup.erase(it);\n  } else\n    DAI_THROW(OBJECT_NOT_FOUND);\n}\n\nvoid FactorGraph::backupFactors(const VarSet& ns) {\n  for (size_t I = 0; I < nrFactors(); I++)\n    if (factor(I).vars().intersects(ns))\n      backupFactor(I);\n}\n\nvoid FactorGraph::restoreFactors(const VarSet& ns) {\n  map<size_t, Factor> facs;\n  for (map<size_t, Factor>::iterator uI = _backup.begin();\n       uI != _backup.end();) {\n    if (factor(uI->first).vars().intersects(ns)) {\n      facs.insert(*uI);\n      _backup.erase(uI++);\n    } else\n      uI++;\n  }\n  setFactors(facs);\n}\n\nvoid FactorGraph::restoreFactors() {\n  setFactors(_backup);\n  _backup.clear();\n}\n\nvoid FactorGraph::backupFactors(const std::set<size_t>& facs) {\n  for (std::set<size_t>::const_iterator fac = facs.begin(); fac != facs.end();\n       fac++)\n    backupFactor(*fac);\n}\n\nbool FactorGraph::isPairwise() const {\n  bool pairwise = true;\n  for (size_t I = 0; I < nrFactors() && pairwise; I++)\n    if (factor(I).vars().size() > 2)\n      pairwise = false;\n  return pairwise;\n}\n\nbool FactorGraph::isBinary() const {\n  bool binary = true;\n  for (size_t i = 0; i < nrVars() && binary; i++)\n    if (var(i).states() > 2)\n      binary = false;\n  return binary;\n}\n\nFactorGraph FactorGraph::clamped(size_t i, size_t state) const {\n  Var v             = var(i);\n  Real zeroth_order = (Real)1;\n  vector<Factor> clamped_facs;\n  clamped_facs.push_back(createFactorDelta(v, state));\n  for (size_t I = 0; I < nrFactors(); I++) {\n    VarSet v_I = factor(I).vars();\n    Factor new_factor;\n    if (v_I.intersects(v))\n      new_factor = factor(I).slice(v, state);\n    else\n      new_factor = factor(I);\n\n    if (new_factor.vars().size() != 0) {\n      size_t J = 0;\n      // if it can be merged with a previous one, do that\n      for (J = 0; J < clamped_facs.size(); J++)\n        if (clamped_facs[J].vars() == new_factor.vars()) {\n          clamped_facs[J] *= new_factor;\n          break;\n        }\n      // otherwise, push it back\n      if (J == clamped_facs.size() || clamped_facs.size() == 0)\n        clamped_facs.push_back(new_factor);\n    } else\n      zeroth_order *= new_factor[0];\n  }\n  *(clamped_facs.begin()) *= zeroth_order;\n  return FactorGraph(clamped_facs);\n}\n\nFactorGraph FactorGraph::maximalFactors() const {\n  vector<size_t> maxfac(nrFactors());\n  map<size_t, size_t> newindex;\n  size_t nrmax = 0;\n  for (size_t I = 0; I < nrFactors(); I++) {\n    maxfac[I]         = I;\n    VarSet maxfacvars = factor(maxfac[I]).vars();\n    for (size_t J = 0; J < nrFactors(); J++) {\n      VarSet Jvars = factor(J).vars();\n      if (Jvars >> maxfacvars && (Jvars != maxfacvars)) {\n        maxfac[I]  = J;\n        maxfacvars = factor(maxfac[I]).vars();\n      }\n    }\n    if (maxfac[I] == I)\n      newindex[I] = nrmax++;\n  }\n\n  vector<Factor> facs(nrmax);\n  for (size_t I = 0; I < nrFactors(); I++)\n    facs[newindex[maxfac[I]]] *= factor(I);\n\n  return FactorGraph(facs.begin(), facs.end(), vars().begin(), vars().end(),\n                     facs.size(), nrVars());\n}\n\n} // end of namespace dai\n", "meta": {"hexsha": "26b78f40274d7338b29b82fed8dc8c218859d665", "size": 15594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/bp/libdai/src/factorgraph.cpp", "max_stars_repo_name": "rohankadekodi/compilers_project", "max_stars_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "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/bp/libdai/src/factorgraph.cpp", "max_issues_repo_name": "rohankadekodi/compilers_project", "max_issues_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-02-27T19:24:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T21:04:28.000Z", "max_forks_repo_path": "lonestar/experimental/bp/libdai/src/factorgraph.cpp", "max_forks_repo_name": "rohankadekodi/compilers_project", "max_forks_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T22:00:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T10:18:02.000Z", "avg_line_length": 29.4782608696, "max_line_length": 85, "alphanum_fraction": 0.6024111838, "num_tokens": 4472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.0367694622493283, "lm_q1q2_score": 0.01709418077826721}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2015 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   \n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>\n#include <Core/Algorithms/Base/AlgorithmVariableNames.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/Legacy/Field/FieldInformation.h>\n#include <Core/Datatypes/Legacy/Field/Mesh.h>\n#include <Core/Datatypes/Legacy/Field/VMesh.h>\n#include <Core/Datatypes/Legacy/Field/VField.h>\n\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Datatypes/PropertyManagerExtensions.h>\n\n#include <boost/unordered_map.hpp>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Geometry;\n\nAlgorithmOutputName GetFieldBoundaryAlgo::BoundaryField(\"BoundaryField\");\nAlgorithmOutputName GetFieldBoundaryAlgo::MappingMatrix(\"Mapping\");\n\nGetFieldBoundaryAlgo::GetFieldBoundaryAlgo() \n{\n  add_option(AlgorithmParameterName(\"mapping\"),\"auto\",\"auto|node|elem|none\");\n}\n\nstruct IndexHash {\n  static const size_t bucket_size = 4;\n  static const size_t min_buckets = 8;\n  \n  size_t operator()(const index_type &idx) const\n    { return (static_cast<size_t>(idx)); }\n  \n  bool operator()(const index_type &i1, const index_type &i2) const\n    { return (i1 < i2); }\n};\n\nbool \nGetFieldBoundaryAlgo::run(FieldHandle input, FieldHandle& output, MatrixHandle& mapping) const\n{\n  ScopedAlgorithmStatusReporter asr(this, \"GetFieldBoundary\");\n\n  /// Define types we need for mapping\n  typedef boost::unordered_map<index_type,index_type,IndexHash> hash_map_type;\n\n  hash_map_type node_map;\n  hash_map_type elem_map;\n  \n  /// Check whether we have an input field\n  if (!input)\n  {\n    error(\"No input field\");\n    return (false);\n  }\n\n  /// Figure out what the input type and output type have to be\n  FieldInformation fi(input);\n  FieldInformation fo(input);\n  \n  /// We do not yet support Quadratic and Cubic Meshes here\n  if (fi.is_nonlinear())\n  {\n    error(\"This function has not yet been defined for non-linear elements\");\n    return (false);\n  }\n  \n  /// Figure out which type of field the output is:\n  bool found_method = false;\n  if (fi.is_hex_element())    { fo.make_quadsurfmesh(); found_method = true; }\n  if (fi.is_prism_element())  { fo.make_quadsurfmesh(); found_method = true; }\n  if (fi.is_tet_element())    { fo.make_trisurfmesh(); found_method = true; }\n  if (fi.is_quad_element())   { fo.make_curvemesh(); found_method = true; }\n  if (fi.is_tri_element())    { fo.make_curvemesh(); found_method = true; }\n  if (fi.is_pnt_element())\n  {\n    remark(\"The field boundary of a point cloud is the same point cloud\");\n    output = input;\n    return (true);\n  }\n  \n  /// Check whether we could make a conversion\n  if (!found_method)\n  {\n    error(\"No method available for mesh of type: \" + fi.get_mesh_type());\n    return (false);\n  }\n\n  /// Create the output field\n  output = CreateField(fo);\n  if (!output)\n  {\n    error(\"Could not create output field\");\n    return (false);\n  }\n  \n  /// Get the virtual interfaces:\n  VMesh* imesh = input->vmesh();\n  VMesh* omesh = output->vmesh();\n  VField* ifield = input->vfield();\n  VField* ofield = output->vfield();\n  \n  imesh->synchronize(Mesh::DELEMS_E|Mesh::ELEM_NEIGHBORS_E);\n  \n  /// These are all virtual iterators, virtual index_types and array_types\n  VMesh::Elem::iterator be, ee;\n  VMesh::Elem::index_type nci, ci;\n  VMesh::DElem::array_type delems; \n  VMesh::Node::array_type inodes; \n  VMesh::Node::array_type onodes; \n  VMesh::Node::index_type a;\n\n  inodes.clear();\n  onodes.clear();  \n  Point point;\n\n  /// This algorithm was copy from the original dynamic compiled version\n  /// and was slightly adapted to work here:\n  \n  imesh->begin(be); \n  imesh->end(ee);\n\n  while (be != ee) \n  {\n    ci = *be;\n    imesh->get_delems(delems,ci);\n    for (size_t p =0; p < delems.size(); p++)\n    {\n      bool includeface = false;\n      \n      if(!(imesh->get_neighbor(nci,ci,delems[p]))) includeface = true;\n\n      if (includeface)\n      {\n        imesh->get_nodes(inodes,delems[p]);\n        onodes.resize(inodes.size());\n\n        for (size_t q=0; q<inodes.size(); q++)\n        {\n          a = inodes[q];\n          hash_map_type::iterator it = node_map.find(a);\n          if (it == node_map.end())\n          {\n            imesh->get_center(point,a);\n            onodes[q] = omesh->add_node(point);\n            node_map[a] = onodes[q];            \n          }\n          else\n          {\n            onodes[q] = node_map[a];\n          }\n        }\n        elem_map[omesh->add_elem(onodes)] = ci;\n      }\n    }\n    ++be;\n  }\n  \n  mapping.reset();\n  \n  ofield->resize_fdata();\n  \n  if (\n    (\n    (ifield->basis_order() == 0)\n#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER\n      && check_option(\"mapping\",\"auto\")\n      )\n      ||\n       check_option(\"mapping\",\"elem\")\n#else\n    )\n#endif\n      )\n  {\n    VMesh::Elem::size_type isize;\n    VMesh::Elem::size_type osize;\n    imesh->size(isize);\n    omesh->size(osize);\n\n\n    size_type nrows = osize;\n    size_type ncols = isize;\n\n    typedef SparseRowMatrix::Triplet T;\n    std::vector<T> tripletList;\n    tripletList.reserve(nrows);\n\n    hash_map_type::iterator it, it_end;\n    it = elem_map.begin();\n    it_end = elem_map.end();\n\n    while (it != it_end)\n    {\n      tripletList.push_back(T(it->first, it->second, 1));\n      ++it;\n    }\n    SparseRowMatrixHandle mat(new SparseRowMatrix(nrows, ncols));\n    mat->setFromTriplets(tripletList.begin(), tripletList.end());\n    mapping = mat;\n  }\n  else if (\n    ((ifield->basis_order() == 1) \n#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER\n    && check_option(\"mapping\",\"auto\"))\n    ||\n      check_option(\"mapping\",\"node\")\n#else\n    )\n#endif\n      )\n  {\n    VMesh::Node::size_type isize;\n    VMesh::Node::size_type osize;\n    imesh->size(isize);\n    omesh->size(osize);\n\n    size_type nrows = osize;\n    size_type ncols = isize;\n\n    typedef Eigen::Triplet<double> T;\n    std::vector<T> tripletList;\n    tripletList.reserve(nrows);\n\n    hash_map_type::iterator it, it_end;\n    it = node_map.begin();\n    it_end = node_map.end();\n\n    while (it != it_end)\n    {\n      tripletList.push_back(T(it->second, it->first, 1));\n      ++it;\n    }\n    SparseRowMatrixHandle mat(new SparseRowMatrix(nrows, ncols));\n    mat->setFromTriplets(tripletList.begin(), tripletList.end());\n    mapping = mat;\n  }\n  \n  if (ifield->basis_order() == 0)\n  {\n    hash_map_type::iterator it, it_end;\n    it = elem_map.begin();\n    it_end = elem_map.end();\n\n    while (it != it_end)\n    {      \n      VMesh::Elem::index_type idx1((*it).second);\n      VMesh::Elem::index_type idx2((*it).first);  \n      \n      /// Copying values\n      ofield->copy_value(ifield,idx1,idx2);\n      ++it;\n    }\n  }\n  else if (input->basis_order() == 1)\n  {\n    hash_map_type::iterator it, it_end;\n    it = node_map.begin();\n    it_end = node_map.end();\n    \n    while (it != it_end)\n    {\n      VMesh::Node::index_type idx1((*it).first);\n      VMesh::Node::index_type idx2((*it).second);\n      ofield->copy_value(ifield,idx1,idx2);\n      ++it;\n    }\n  }\n  \n  CopyProperties(*input, *output);\n  \n  return (true);\n}\n\n\n/// A copy of the algorithm without creating the mapping matrix. \n/// Need this for the various algorithms that only use the boundary to\n/// project nodes on.\n\nbool \nGetFieldBoundaryAlgo::run(FieldHandle input, FieldHandle& output)\n{\n  ScopedAlgorithmStatusReporter asr(this, \"GetFieldBoundary\");\n\n  /// Define types we need for mapping\n  typedef boost::unordered_map<index_type,index_type,IndexHash> hash_map_type;\n  \n  hash_map_type node_map;\n  hash_map_type elem_map;\n  \n  /// Check whether we have an input field\n  if (!input)\n  {\n    error(\"No input field\");\n    return (false);\n  }\n\n  /// Figure out what the input type and output type have to be\n  FieldInformation fi(input);\n  FieldInformation fo(input);\n  \n  /// We do not yet support Quadratic and Cubic Meshes here\n  if (fi.is_nonlinear())\n  {\n    error(\"This function has not yet been defined for non-linear elements\");\n    return (false);\n  }\n  \n  /// Figure out which type of field the output is:\n  bool found_method = false;\n  if (fi.is_hex_element())    { fo.make_quadsurfmesh(); found_method = true; }\n  if (fi.is_prism_element())  { fo.make_quadsurfmesh(); found_method = true; }\n  if (fi.is_tet_element())    { fo.make_trisurfmesh(); found_method = true; }\n  if (fi.is_quad_element())   { fo.make_curvemesh(); found_method = true; }\n  if (fi.is_tri_element())    { fo.make_curvemesh(); found_method = true; }\n  if (fi.is_pnt_element())\n  {\n    remark(\"The field boundary of a point cloud is the same point cloud\");\n    output = input;\n    return (true);\n  }\n  \n  /// Check whether we could make a conversion\n  if (!found_method)\n  {\n    error(\"No method available for mesh of type: \" + fi.get_mesh_type());\n    return (false);\n  }\n\n  /// Create the output field\n  output = CreateField(fo);\n  if (!output)\n  {\n    error(\"Could not create output field\");\n    return (false);\n  }\n  \n  /// Get the virtual interfaces:\n  VMesh* imesh = input->vmesh();\n  VMesh* omesh = output->vmesh();\n  VField* ifield = input->vfield();\n  VField* ofield = output->vfield();\n  \n  imesh->synchronize(Mesh::DELEMS_E|Mesh::ELEM_NEIGHBORS_E);\n  \n  /// These are all virtual iterators, virtual index_types and array_types\n  VMesh::Elem::iterator be, ee;\n  VMesh::Elem::index_type nci, ci;\n  VMesh::DElem::array_type delems; \n  VMesh::Node::array_type inodes; \n  VMesh::Node::array_type onodes; \n  VMesh::Node::index_type a;\n\n  inodes.clear();\n  onodes.clear();  \n  Point point;\n\n  /// This algorithm was copy from the original dynamic compiled version\n  /// and was slightly adapted to work here:\n  \n  imesh->begin(be); \n  imesh->end(ee);\n\n  while (be != ee) \n  {\n    ci = *be;\n    imesh->get_delems(delems,ci);\n    for (size_t p =0; p < delems.size(); p++)\n    {\n      bool includeface = false;\n      \n      if(!(imesh->get_neighbor(nci,ci,delems[p]))) includeface = true;\n\n      if (includeface)\n      {\n        imesh->get_nodes(inodes,delems[p]);\n        if (onodes.size() == 0) onodes.resize(inodes.size());\n        for (size_t q=0; q<onodes.size(); q++)\n        {\n          a = inodes[q];\n          hash_map_type::iterator it = node_map.find(a);\n          if (it == node_map.end())\n          {\n            imesh->get_center(point,a);\n            onodes[q] = omesh->add_node(point);\n            node_map[a] = onodes[q];            \n          }\n          else\n          {\n            onodes[q] = node_map[a];\n          }\n        }\n        elem_map[omesh->add_elem(onodes)] = ci;\n      }\n    }\n    ++be;\n  }\n  \n  ofield->resize_fdata();\n  \n  if (ifield->basis_order() == 0)\n  {\n    hash_map_type::iterator it, it_end;\n    it = elem_map.begin();\n    it_end = elem_map.end();\n    \n    while (it != it_end)\n    {      \n      VMesh::Elem::index_type idx1((*it).second);\n      VMesh::Elem::index_type idx2((*it).first);  \n      \n      /// Copying values\n      ofield->copy_value(ifield,idx1,idx2);\n      ++it;\n    }\n  }\n  else if (input->basis_order() == 1)\n  {\n    hash_map_type::iterator it, it_end;\n    it = node_map.begin();\n    it_end = node_map.end();\n    \n    while (it != it_end)\n    {\n      VMesh::Node::index_type idx1((*it).first);\n      VMesh::Node::index_type idx2((*it).second);\n      ofield->copy_value(ifield,idx1,idx2);\n      ++it;\n    }\n  }\n  \n  CopyProperties(*input, *output);\n  \n  return (true);\n}\n\nAlgorithmOutput GetFieldBoundaryAlgo::run_generic(const AlgorithmInput& input) const\n{\n  auto field = input.get<Field>(Variables::InputField);\n\n  FieldHandle boundary;\n  MatrixHandle mapping;\n  if (!run(field, boundary, mapping))\n    THROW_ALGORITHM_PROCESSING_ERROR(\"False returned on legacy run call.\");\n\n  AlgorithmOutput output;\n  output[BoundaryField] = boundary;\n  output[MappingMatrix] = mapping;\n  return output;\n}", "meta": {"hexsha": "29e9f143ac0cdb25cb51eab42557cbf6d008f7ec", "size": 13048, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.cc", "max_stars_repo_name": "mhansen1/SCIRun", "max_stars_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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/Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.cc", "max_issues_repo_name": "mhansen1/SCIRun", "max_issues_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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/Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.cc", "max_forks_repo_name": "mhansen1/SCIRun", "max_forks_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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.2970711297, "max_line_length": 94, "alphanum_fraction": 0.6466891478, "num_tokens": 3524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.051082741290902595, "lm_q1q2_score": 0.017091745188318856}}
{"text": "/* $Id: Paraclu.cpp,v 1.29 2016/08/02 07:21:36 severin Exp $ */\n\n/***\n\nNAME - EEDB::Tools::Paraclu\n\nSYNOPSIS\n\nDESCRIPTION\n\n  Port of the paraclu program into a ZENBU SPStream module\n  Copyright 2011 Martin C. Frith\n \n  Find clusters in 1-dimensional data, using the method described in\n  MC Frith et al. Genome Res. 2008 18(1):1-12.\n \n  http://www.cbrc.jp/paraclu/\n \n  The original command line code uses the input\n    4 columns: chromosome, strand, coordinate, value.\n    For example: chr20 + 60026 2\n \nCONTACT\n\nJessica Severin <severin@gsc.riken.jp>\n\nLICENSE\n\n * Software License Agreement (BSD License)\n * EdgeExpressDB [eeDB] system\n * copyright (c) 2007-2013 Jessica Severin RIKEN OSC\n * All rights reserved.\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 Jessica Severin RIKEN OSC 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 ''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 COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nAPPENDIX\n\nThe rest of the documentation details each of the object methods. Internal methods are usually preceded with a _\n\n***/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <string>\n#include <stdarg.h>\n\n#include <algorithm>  // max, min\n#include <cstdlib>  // EXIT_SUCCESS, EXIT_FAILURE\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n\n#include <rapidxml.hpp>  //rapidxml must be include before boost\n#include <boost/algorithm/string.hpp>\n#include <EEDB/Experiment.h>\n#include <EEDB/Feature.h>\n#include <EEDB/Expression.h>\n#include <EEDB/Symbol.h>\n#include <EEDB/SPStream.h>\n#include <EEDB/Tools/Paraclu.h>\n\nusing namespace std;\n\nconst char*  EEDB::Tools::Paraclu::class_name = \"EEDB::Tools::Paraclu\";\n\n//function prototypes\nvoid _tools_paraclu_delete_func(MQDB::DBObject *obj) { \n  delete (EEDB::Tools::Paraclu*)obj;\n}\nvoid _tools_paraclu_xml_func(MQDB::DBObject *obj, string &xml_buffer) { \n  ((EEDB::Tools::Paraclu*)obj)->_xml(xml_buffer);\n}\nstring _tools_paraclu_display_desc_func(MQDB::DBObject *obj) { \n  return ((EEDB::Tools::Paraclu*)obj)->_display_desc();\n}\n\nconst double infinity = 1e100;\nvoid check_over_memory();  //from TrackCacheBuilder\n\n\n////////////////////////////////////////////////////////////////////////////\n//\n// Cluster object\n//\n////////////////////////////////////////////////////////////////////////////\n\n\nEEDB::Tools::Paraclu::Cluster::Cluster() {\n  //constructor\n  beg = NULL;\n  end = NULL;\n  totalValue = 0.0;\n  minDensity = infinity;\n  maxDensity = infinity;\n  stability = 0.0;\n}\n\nEEDB::Tools::Paraclu::Cluster::~Cluster() { \n  // destructor\n  beg = NULL;\n  end = NULL;\n  totalValue = 0.0;\n  minDensity = infinity;\n  maxDensity = infinity;\n  stability = 0.0;\n}\n\nvoid  EEDB::Tools::Paraclu::Cluster::show() { \n  long cluster_length = end->feature->chrom_start() - beg->feature->chrom_start() + 1;\n\n  std::cerr << beg->feature->chrom_name() << \"\\t\" << beg->feature->strand() << \"\\t\"\n  << std::setprecision(20)\n  << beg->feature->chrom_start() << \"\\t\" << end->feature->chrom_start() << \"\\t\"\n  << cluster_length << \"\\t\" << totalValue << \"\\t\"\n  << std::setprecision(3)\n  << minDensity << \"\\t\" << maxDensity ;\n  std::cerr << \"\\t\" << stability;\n//  if(stability >= _min_stability) { std::cerr << \"\\tSTABLE\"; }\n//  std::cerr << \"\\n\";\n}\n\n  \n////////////////////////////////////////////////////////////////////////////\n//\n// creation methods\n//\n////////////////////////////////////////////////////////////////////////////\n\n\nEEDB::Tools::Paraclu::Paraclu() {\n  init();\n}\n\nEEDB::Tools::Paraclu::~Paraclu() {\n}\n\nvoid EEDB::Tools::Paraclu::init() {\n  MQDB::DBObject::init();\n  _classname                 = EEDB::Tools::Paraclu::class_name;\n  _funcptr_delete            = _tools_paraclu_delete_func;\n  _funcptr_xml               = _tools_paraclu_xml_func;\n  _funcptr_simple_xml        = _tools_paraclu_xml_func;\n  _funcptr_display_desc      = _tools_paraclu_display_desc_func;\n  \n  _min_cutoff_value    = 10.0;\n  _max_cluster_length  = 100;\n  _min_stability       = 1;\n  _min_density         = 0;\n  _selection_mode      = STABILITY_CUT;\n\n  _stream_chrom        = NULL;\n  _fl_buffer_start     = NULL;\n  _fl_buffer_end       = NULL;\n  _best_cluster        = NULL;\n  _cluster_number      = 1;\n\n  //attributes\n  _feature_source = new EEDB::FeatureSource();\n  _feature_source->name(\"Paraclu\");\n  _feature_source->category(\"cluster\");\n  \n  _output_buffer = NULL;\n}\n\n\nvoid  EEDB::Tools::Paraclu::output_buffer(EEDB::Tools::ResortBuffer* buffer) { \n  _output_buffer = buffer; \n}\n\nvoid  EEDB::Tools::Paraclu::feature_source(EEDB::FeatureSource* source) { \n  if(_feature_source) { _feature_source->release(); _feature_source = NULL; }\n  if(source) { source->retain(); }\n  _feature_source = source; \n}\n\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  creation from XML section\n//\n////////////////////////////////////////////////////////////////////////////\n\nstring EEDB::Tools::Paraclu::_display_desc() {\n  string str = \"Paraclu\";\n  return str;\n}\n\n\nvoid EEDB::Tools::Paraclu::_xml(string &xml_buffer) {    \n  char buffer[256];\n  snprintf(buffer, 256, \"<min_cutoff>%f</min_cutoff>\", _min_cutoff_value);\n  xml_buffer.append(buffer);\n\n  snprintf(buffer, 256, \"<stability>%f</stability>\", _min_stability);\n  xml_buffer.append(buffer);\n\n  snprintf(buffer, 256, \"<max_cluster_length>%ld</max_cluster_length>\", _max_cluster_length);\n  xml_buffer.append(buffer);\n  \n  if(_min_density>0) {\n    snprintf(buffer, 256, \"<min_density>%f</min_density>\", _min_density);\n    xml_buffer.append(buffer);\n  }\n\n  switch(_selection_mode) {\n    case FULL_HIERARCHY:  xml_buffer.append(\"<selection_mode>full_hierarchy</selection_mode>\"); break;\n    case BEST_STABLE:     xml_buffer.append(\"<selection_mode>best_stable</selection_mode>\"); break;\n    case STABILITY_CUT:   xml_buffer.append(\"<selection_mode>stability_cut</selection_mode>\"); break;\n    case SMALL_STABLE:    xml_buffer.append(\"<selection_mode>small_stable</selection_mode>\"); break;\n  }\n\n}\n\n\nEEDB::Tools::Paraclu::Paraclu(void *xml_node) {\n  //constructor using a rapidxml <spstream> description\n  init();\n  if(xml_node==NULL) { return; }\n  \n  rapidxml::xml_node<>      *root_node = (rapidxml::xml_node<>*)xml_node;\n  rapidxml::xml_node<>      *node;\n  \n  if((node = root_node->first_node(\"min_cutoff\")) != NULL) {\n    _min_cutoff_value = strtod(node->value(), NULL);\n  }  \n\n  if((node = root_node->first_node(\"stability\")) != NULL) {\n    _min_stability = strtod(node->value(), NULL);\n    if(_min_stability < 1.0) { _min_stability = 1.0; }\n  }  \n\n  if((node = root_node->first_node(\"max_cluster_length\")) != NULL) {\n    _max_cluster_length = strtol(node->value(), NULL, 10);\n  } \n\n  if((node = root_node->first_node(\"min_density\")) != NULL) {\n    _min_density = strtod(node->value(), NULL);\n    if(_min_density < 0) { _min_density = 0; }\n  }  \n  \n  _selection_mode = STABILITY_CUT;\n  if(((node = root_node->first_node(\"full_hierarchy\")) != NULL) and (string(node->value()) == \"true\")) {\n    _selection_mode = FULL_HIERARCHY;\n  }\n  if(((node = root_node->first_node(\"most_stable\")) != NULL) and (string(node->value()) == \"true\")) {\n    _selection_mode = BEST_STABLE;\n  }\n  if((node = root_node->first_node(\"selection_mode\")) != NULL) {\n    if(string(node->value()) == \"full_hierarchy\") { _selection_mode = FULL_HIERARCHY; }\n    if(string(node->value()) == \"best_stable\")    { _selection_mode = BEST_STABLE; }\n    if(string(node->value()) == \"stability_cut\")  { _selection_mode = STABILITY_CUT; }\n    if(string(node->value()) == \"small_stable\")  { _selection_mode = SMALL_STABLE; }\n  }\n\n}\n\n\n////////////////////////////////////////////////////////////\n\n\n \nvoid  EEDB::Tools::Paraclu::process_feature(EEDB::Feature* feature) {\n  //final post processing of subfeat prior to returning\n  if(feature==NULL) { return; }\n  if(!_output_buffer) { return; }\n  \n  // check if we are finished with clusters in the _output_buffer\n  //_output_buffer->transfer_completed(feature->chrom_start());\n\n  //fill in the featurelink buffer to have enough room to cluster properly\n  if(!_stream_chrom) { \n    _stream_chrom = feature->chrom();\n    _stream_chrom->retain();\n  }\n    \n  FeatureLink *fl = new EEDB::FeatureLink();\n  fl->feature = feature;\n  feature->retain();\n  //fprintf(stderr, \"add feature %s to links\\n\", feature->chrom_location().c_str());\n\n  if(_fl_buffer_start == NULL) {\n    //printf(\"reset buffer start..end\\n\");\n    _fl_buffer_start = fl;\n    _fl_buffer_end   = fl;\n  } else {    \n    // add new feature onto end of feature link buffer\n    _fl_buffer_end->next = fl;\n    fl->prev             = _fl_buffer_end;\n    _fl_buffer_end       = fl;\n  }\n\n  if(_fl_buffer_end->feature->chrom_start() - _fl_buffer_start->feature->chrom_start()+1 > _max_cluster_length * 9) {\n    //_show_buffer(_fl_buffer_start, _fl_buffer_end);\n    //long length = _fl_buffer_end->feature->chrom_start() - _fl_buffer_start->feature->chrom_start() + 1;\n\n    switch(_selection_mode) {\n      case FULL_HIERARCHY:\n      case STABILITY_CUT:\n        //fprintf(stderr, \"process buffer %ld .. %ld [ %ld ]\\n\", _fl_buffer_start->feature->chrom_start(), _fl_buffer_end->feature->chrom_start(), length);\n        _process_cluster_range_full(_fl_buffer_start, _fl_buffer_end, -infinity);\n        break;\n      case BEST_STABLE:\n        _process_cluster_range_best(_fl_buffer_start, _fl_buffer_end);\n        break;\n      case SMALL_STABLE:\n        int rtn = _process_cluster_range_smallest(_fl_buffer_start, _fl_buffer_end, -infinity);\n        if(rtn == 0) {\n          //fprintf(stderr, \"entire buffer is too weak now\\n\");\n          _discard_region(_fl_buffer_start, _fl_buffer_end);\n        }\n        break;\n    }\n    check_over_memory();\n  }\n}\n\n\nvoid  EEDB::Tools::Paraclu::finish_processing() {\n  if(!_output_buffer) { return; }\n  FeatureLink *last_fl_start = NULL;\n\n  while(_fl_buffer_start != NULL) {\n    //_show_buffer(_fl_buffer_start, _fl_buffer_end);\n    //long length = _fl_buffer_end->feature->chrom_start() - _fl_buffer_start->feature->chrom_start() + 1;\n    last_fl_start = _fl_buffer_start;\n\n    switch(_selection_mode) {\n      case FULL_HIERARCHY:\n      case STABILITY_CUT:\n        //fprintf(stderr, \"finalize buffer %ld .. %ld [ %ld ]\\n\", _fl_buffer_start->feature->chrom_start(), _fl_buffer_end->feature->chrom_start(), length);\n        _process_cluster_range_full(_fl_buffer_start, _fl_buffer_end, -infinity);\n        break;\n      case BEST_STABLE:\n        _process_cluster_range_best(_fl_buffer_start, _fl_buffer_end);\n        break;\n      case SMALL_STABLE:\n        int rtn = _process_cluster_range_smallest(_fl_buffer_start, _fl_buffer_end, -infinity);\n        if(rtn == 0) {\n          //fprintf(stderr, \"entire buffer is too weak now\\n\");\n          _discard_region(_fl_buffer_start, _fl_buffer_end);\n        }\n        break;\n    }\n    if(_fl_buffer_start == last_fl_start) {\n      //fprintf(stderr, \"hmm buffer didn't change - problem\\n\");\n      _discard_region(_fl_buffer_start, _fl_buffer_end);\n    }\n  }\n  \n  // input stream is empty so move all _subfeature_buffer into _completed_subfeatures\n  //_output_buffer->transfer_all_to_completed();\n}  \n\n\nvoid  EEDB::Tools::Paraclu::reset() {\n  //reset for next region query\n  if(_output_buffer) { _output_buffer->reset(); }\n\n  //reset parameters to defaults\n  _min_cutoff_value    = 10.0;\n  _max_cluster_length  = 100;\n  _min_stability       = 1;\n  _min_density         = 0;\n  _selection_mode      = STABILITY_CUT;\n  \n  //clear from previous run\n  if(_stream_chrom) { _stream_chrom->release(); }\n  _discard_region(_fl_buffer_start, _fl_buffer_end);\n  if(_best_cluster) { delete _best_cluster; }\n\n  _stream_chrom        = NULL;\n  _fl_buffer_start     = NULL;\n  _fl_buffer_end       = NULL;\n  _best_cluster        = NULL;  \n  _cluster_number      = 1;\n}\n\n\n//--------------------------------------------------------------\n\n// Copyright 2011 Martin C. Frith\n\n// Find clusters in 1-dimensional data, using the method described in\n// MC Frith et al. Genome Res. 2008 18(1):1-12.\n\n// The input has 4 columns: chromosome, strand, coordinate, value.\n// For example: chr20 + 60026 2\n\n// Ported into the ZENBU Feature and SPStream system: Jessica Severin copyright 2012\n\n\ndouble  EEDB::Tools::Paraclu::_calc_total_value(FeatureLink *beg, FeatureLink *end) {\n  if(beg==NULL) { return 0; }\n  FeatureLink  *flink = beg;\n  double       totalValue = 0;\n  while(flink) {\n    totalValue += flink->feature->significance();\n    if(flink == end) { break; }\n    flink = flink->next;\n  }\n  return totalValue;\n}\n\n\ndouble  EEDB::Tools::Paraclu::_weakestPrefix(FeatureLink *beg, FeatureLink *end) {\n  if(beg==end) { return 0.0; }\n  unsigned origin   = beg->feature->chrom_start();\n  unsigned stop_pos = end->feature->chrom_start();\n  //printf(\"_weakestPrefix\\n\");\n  \n  _minPrefix = NULL;  //maybe not needed\n  _minPrefixDensity = infinity;\n  \n  FeatureLink  *flink = beg;\n  double       totalValue = 0;\n  unsigned     pos=0;\n  \n  //density is calculated as \n  while(flink) {\n    pos = flink->feature->chrom_start();\n    //loop on identical starts in case input was not pre-clustered at 1bp resolution\n    while(flink && (flink->feature->chrom_start() == pos)) { \n      totalValue += flink->feature->significance();\n      flink = flink->next;\n    }\n    if(!flink) { break; }\n    if(flink->feature->chrom_start() > stop_pos) { break; }\n    \n    double density = totalValue / (flink->feature->chrom_start() - origin);\n    if(density < _minPrefixDensity) {\n      _minPrefix = flink;\n      _minPrefixDensity = density;\n    }    \n  }\n  //printf(\" total=%f  minDensity = %f  pos = %s\\n\", totalValue, _minPrefixDensity, _minPrefix->feature->chrom_location().c_str());\n  return totalValue;\n}\n\n\ndouble  EEDB::Tools::Paraclu::_weakestSuffix(FeatureLink *beg, FeatureLink *end) {\n  if(beg==end) { return 0.0; }\n  unsigned beg_pos = beg->feature->chrom_start();\n  unsigned end_pos = end->feature->chrom_start();\n  //printf(\"_weakestSuffix\\n\");\n\n  _minSuffix = NULL;\n  _minSuffixDensity = infinity;\n  \n  FeatureLink  *flink = end;\n  double       totalValue = 0;\n  unsigned     pos = 0;\n  \n  while(flink) {\n    pos = flink->feature->chrom_start();\n    //printf(\"  pos = %d\\n\", pos);\n    //loop on identical chrom_starts in case input was not pre-clustered at 1bp resolution\n    while(flink && (flink->feature->chrom_start() == pos)) {\n      totalValue += flink->feature->significance();\n      //printf(\"   add to density %s\\n\", flink->feature->chrom_location().c_str());\n      flink = flink->prev;\n    }\n    if(!flink) { break; }\n    if(flink->feature->chrom_start() < beg_pos) { break; }\n\n    double density = totalValue / (end_pos - flink->feature->chrom_start());\n    //printf(\"   density = %f\\n\", density);\n    if(density < _minSuffixDensity) {\n      _minSuffix = flink->next;\n      _minSuffixDensity = density;\n      //printf(\"     !NEW minSuffix %s [ %f ]\\n\", _minSuffix->feature->chrom_location().c_str(), density);\n    }\n  }\n  //printf(\" total=%f  minDensity = %f  pos = %s\\n\", totalValue, _minSuffixDensity, _minSuffix->feature->chrom_location().c_str());\n  return totalValue;\n}\n\n\nvoid EEDB::Tools::Paraclu::_show_buffer(FeatureLink *beg, FeatureLink *end) {\n  printf(\"=== buffer\\n\");\n  FeatureLink *fl = beg;\n  while(1) {\n    printf(\"  %s\\n\", fl->feature->chrom_location().c_str());\n    if(fl == end) { break; }\n    fl = fl->next;\n  }\n}\n\n\nvoid  EEDB::Tools::Paraclu::_discard_region(FeatureLink *beg, FeatureLink *end) {\n  if((beg==NULL) || (end==NULL)) { return; }\n\n  //long cluster_length = end->feature->chrom_start() - beg->feature->chrom_start() + 1;\n  //fprintf(stderr, \"_discard_region %ld .. %ld [ %ld ]\\n\", beg->feature->chrom_start(), end->feature->chrom_start(), cluster_length);\n    \n  //cut off this section from the feature link buffer\n  FeatureLink *b2 = beg->prev;\n  FeatureLink *e2 = end->next;\n  if(b2) { b2->next = e2; }\n  if(e2) { e2->prev = b2; }\n  if(_fl_buffer_start == beg) { \n    _fl_buffer_start = e2;\n    //printf(\"new _fl_buffer_start\\n\");\n  }\n  if(_fl_buffer_end == end)   { \n    _fl_buffer_end = b2; \n    //printf(\"new _fl_buffer_end\\n\");\n  }\n  \n  beg->prev = NULL;\n  end->next = NULL;\n  \n  EEDB::FeatureLink *flink = beg;\n  while(flink!=NULL) {\n    //printf(\"  remove link %s\\n\", flink->feature->chrom_location().c_str());\n    flink->feature->release();\n    flink->feature = NULL;\n    FeatureLink *fl2 = flink;\n    flink = flink->next;\n    delete fl2;\n  }\n}\n\n/*\nvoid  EEDB::Tools::Paraclu::_processOneStream(std::istream &stream) {\n  std::string newSeqname;\n  char newStrand;\n  unsigned p;\n  double v;\n  while (stream >> newSeqname >> newStrand >> p >> v) {\n    if (newSeqname == seqname && newStrand == strand) {\n      if (p > sites.back().chrom_start())\n        sites.push_back(Site(p, v));\n      else if (p == sites.back().chrom_start())\n        sites.back().value += v;\n      else\n        throw std::runtime_error(\"unsorted input\");\n    } else {\n      _writeClusters(sites.begin(), sites.end(), -infinity);\n      sites.clear();\n      seqname = newSeqname;\n      strand = newStrand;\n      sites.push_back(Site(p, v));\n    }\n  }\n  if (!stream.eof()) throw std::runtime_error(\"bad input\");\n  _writeClusters(sites.begin(), sites.end(), -infinity);\n}\n*/\n\n/////////////////////////////////////////////////////////////////////////////////////\n//\n// original ported version. close to direct interpretation of the original ParaClu algorithm\n// but flipped recursion logic so that parent decides based on children and self\n// also working with the sliding input buffer and the ZENBU datamodel objects\n//\n/////////////////////////////////////////////////////////////////////////////////////\n\n\nvoid  EEDB::Tools::Paraclu::_process_cluster_range_full(FeatureLink *beg, FeatureLink *end, double parentDensity) {\n  //OK this is a closer attempt at martin's original algorithm, full hierarchy\n  //recursive algorithm which subdivides sites\n  //original paraclu called the parameter minDensity, but parentDensity is better name\n  \n  if((beg==NULL) || (end==NULL)) { return; }\n  //if(beg==end) {  return; }\n  \n  long   cluster_length = end->feature->chrom_start() - beg->feature->chrom_start() + 1;\n  double totalValue     = _calc_total_value(beg, end);\n  double density        = totalValue / cluster_length;\n  \n  //fprintf(stderr, \"_process_cluster_range_full  %ld .. %ld  [ %ld ] [total=%f density=%f]\\n\", beg->feature->chrom_start(), end->feature->chrom_start(), cluster_length, totalValue, density);\n  \n  if((totalValue < _min_cutoff_value) || (density < _min_density)) { \n    //weak region so can fall out\n    if(cluster_length > _max_cluster_length) { \n      //if >max_length then we are walking down the left-side, so can discard and fall out\n      //fprintf(stderr, \"discard large-weak region %ld .. %ld  [ %ld ] [total=%f density=%f]\\n\", beg->feature->chrom_start(), end->feature->chrom_start(), cluster_length, totalValue, density);\n      _discard_region(beg, end);\n    }\n    return; \n  } \n    \n  if(beg==end) {  \n    double stability = density/parentDensity; //my stability\n    //fprintf(stderr, \"_process_cluster_range  beg == end density[%f] parentDensity[%f] stability[%f] minstab[%f]\\n\", density, parentDensity, stability, _min_stability);\n    if((_selection_mode==FULL_HIERARCHY) || ((_selection_mode==STABILITY_CUT) && (stability >= _min_stability))) {\n      //this is part of the hierarchy\n      //fprintf(stderr, \"single 1bp stable cluster [%ld] & STABLE [%f]\\n\", cluster_length, stability);\n      EEDB::Feature *feature = _generate_cluster(beg, end);\n      if(feature) {\n        feature->metadataset()->add_tag_data(\"density\", d_to_string(density));\n        feature->metadataset()->add_tag_data(\"maxDensity\", d_to_string(density));  //1bp so no children\n        feature->metadataset()->add_tag_data(\"parentDensity\", d_to_string(parentDensity));\n        feature->metadataset()->add_tag_data(\"stability\", d_to_string(stability));\n        _output_buffer->insert_feature(feature);\n      } \n    }\n    return;\n  }\n\n  \n  //\n  // find best mid-cut-point\n  //\n  _weakestPrefix(beg, end);\n  _weakestSuffix(beg, end);\n  \n  double maxDensity;\n  FeatureLink *mid = NULL;\n  if(_minPrefixDensity < _minSuffixDensity) {\n    maxDensity = _minPrefixDensity;\n    mid = _minPrefix;\n    //fprintf(stderr, \"choose prefix %f %d\\n\", _minPrefixDensity, _minPrefix->feature->chrom_start());\n  } else {\n    maxDensity = _minSuffixDensity;\n    mid = _minSuffix;\n    //fprintf(stderr, \"choose suffix %f %d\\n\", _minSuffixDensity, _minSuffix->feature->chrom_start());\n  }  \n  \n  //if no mid point pop out\n  if(mid==NULL) { \n    //did not find a cut so bounce out\n    //fprintf(stderr, \"Paraclu PROBLEM mid is null\\n\");\n    return;\n  }\n  //printf(\"  maxDensity %f\\n\", maxDensity);\n  //printf(\"  parentDensity %f\\n\", parentDensity);\n  //printf(\"  mid link %s\\n\", mid->feature->chrom_location().c_str());\n  \n  double child_stability = maxDensity / parentDensity;\n  \n  if((cluster_length <= _max_cluster_length) && (maxDensity>parentDensity)) {\n    \n    //this is part of the hierarchy\n    /*\n     std::cerr << beg->feature->chrom_name() << \"\\t\" << beg->feature->strand() << \"\\t\"\n     << std::setprecision(20)\n     << beg->feature->chrom_start() << \"\\t\" << end->feature->chrom_start() << \"\\t\"\n     << cluster_length << \"\\t\" << totalValue << \"\\t\"\n     << std::setprecision(3)\n     << parentDensity << \"\\t\" << maxDensity ;\n     std::cerr << \"\\t\" << stability;\n     if(stability >= _min_stability) { std::cerr << \"\\tSTABLE\"; }\n     std::cerr << \"\\n\";\n     */\n    \n    if((_selection_mode==FULL_HIERARCHY) || ((_selection_mode==STABILITY_CUT) && (child_stability >= _min_stability))) {\n      EEDB::Feature *feature = _generate_cluster(beg, end);\n      if(feature) {\n        feature->metadataset()->add_tag_data(\"density\", d_to_string(density));\n        feature->metadataset()->add_tag_data(\"maxDensity\", d_to_string(maxDensity));\n        feature->metadataset()->add_tag_data(\"parentDensity\", d_to_string(parentDensity));\n        feature->metadataset()->add_tag_data(\"child_stability\", d_to_string(child_stability));\n        _output_buffer->insert_feature(feature);\n        //fprintf(stderr, \"make cluster %ld .. %ld  [ %ld ] [total=%f density=%f]\\n\", beg->feature->chrom_start(), end->feature->chrom_start(), cluster_length, totalValue, density);\n      }\n    }\n\n    if((_selection_mode==STABILITY_CUT) && (child_stability >= _min_stability)) {\n      // no need to dig deeper, martin's paraclu-cut picks biggest cluster in hierarchy\n      // Remove clusters that are contained in larger clusters.  This assumes\n      // that the input is sorted by start position (ascending) then end\n      // position (descending).\n      //fprintf(stderr, \"stop stability_cut\\n\");\n      return;\n    }\n\n  }\n  double newMinDensity = max(parentDensity, maxDensity);\n  //double newMinDensity = parentDensity;\n  //if(cluster_length <= _max_cluster_length) { newMinDensity = max(parentDensity, maxDensity); }\n\n  FeatureLink *mid1 = mid->prev;\n  long   left_length  = mid1->feature->chrom_start() - beg->feature->chrom_start() + 1;\n  \n  //fprintf(stderr, \"left\\n\");\n  _process_cluster_range_full(beg, mid1, newMinDensity);\n  \n  //only dig down right side when inside left most cluster <= max_cluster_length\n  if(cluster_length <= _max_cluster_length) { \n    //fprintf(stderr, \"right\\n\");\n    _process_cluster_range_full(mid, end, newMinDensity);\n  }\n    \n  //special transition, from above max_cluster into left-most cluster\n  //once finished here we poping completely out so discard this left-most region\n  if((left_length <= _max_cluster_length) && (cluster_length > _max_cluster_length)) {\n    //fprintf(stderr, \"discard left-side %ld .. %ld  [ %ld ] [total=%f density=%f]\\n\", beg->feature->chrom_start(), end->feature->chrom_start(), cluster_length, totalValue, density);\n    _discard_region(beg, mid1);\n  }\n  \n}\n\n/////////////////////////////////////////////////////////////////////////////////////\n//\n// variation on full-heirarchy cluster-selection where it picks the\n// \"smallest stable\" cluster. chooses from bottom up of recusrison.\n//\n/////////////////////////////////////////////////////////////////////////////////////\n\n\nint  EEDB::Tools::Paraclu::_process_cluster_range_smallest(FeatureLink *beg, FeatureLink *end, double parentDensity) {  \n  //recursive algorithm which subdivides sites\n  // return 0 = false weak region < min_cutoff_value\n  // return 1 = true made cluster, pop out\n  // return 2 = discarded some weak reagion in buffer, pop out\n  //printf(\"_process_cluster_range\\n\");\n  if((beg==NULL) || (end==NULL)) { return 0; }\n  //if(beg==end) {  return 0; }\n  \n  long cluster_length = end->feature->chrom_start() - beg->feature->chrom_start() + 1;\n  double totalValue   = _calc_total_value(beg, end);\n  double density      = totalValue / cluster_length;\n\n  //fprintf(stderr, \"_process_cluster_range  %ld .. %ld  [ %ld ] [total=%f density=%f]\\n\", beg->feature->chrom_start(), end->feature->chrom_start(), cluster_length, totalValue, density);\n\n  if(cluster_length > _max_cluster_length) {\n    //use self density if cluster region is greater than max_cluster_length\n    //don't track parent density above _max_cluster_length since it is meaningless is the ZENBU buffering design\n    parentDensity = density;\n  }\n  double newParentDensity = max(parentDensity, density); //most dense parent for children, either me or my densest parent\n  double stability = density/parentDensity; //my stability\n\n  if(cluster_length <= _max_cluster_length) {\n    //fprintf(stderr, \"_process_cluster_range  %ld .. %ld  [ %ld ] [total=%f stability=%f]\\n\", beg->feature->chrom_start(), end->feature->chrom_start(), cluster_length, totalValue, stability);\n  }\n\n  if(totalValue < _min_cutoff_value) { //weak region so can fall out\n    return 0; \n  } \n\n  if(beg==end) {  \n    //fprintf(stderr, \"_process_cluster_range  beg == end density[%f] parentDensity[%f] stability[%f] minstab[%f]\\n\", density, parentDensity, stability, _min_stability);\n    if(stability >= _min_stability) {\n      //this is part of the hierarchy\n      //fprintf(stderr, \"this region is small [%ld] & STABLE [%f]\\n\", cluster_length, stability);\n      EEDB::Feature *feature = _generate_cluster(beg, end);\n      if(feature) {\n        feature->metadataset()->add_tag_data(\"density\", d_to_string(density));\n        feature->metadataset()->add_tag_data(\"maxDensity\", d_to_string(density));  //1bp so no children\n        feature->metadataset()->add_tag_data(\"parentDensity\", d_to_string(parentDensity));\n        feature->metadataset()->add_tag_data(\"stability\", d_to_string(stability));\n        _output_buffer->insert_feature(feature);\n        return 1;\n      } \n    }\n    //all other cases is a fail\n    return 0;\n  }\n\n  //\n  // find best mid-cut-point\n  //\n  _weakestPrefix(beg, end);\n  _weakestSuffix(beg, end);\n  \n  double maxDensity;\n  FeatureLink *mid = NULL;\n  if(_minPrefixDensity < _minSuffixDensity) {\n    maxDensity = _minPrefixDensity;\n    mid = _minPrefix;\n    //fprintf(stderr, \"choose prefix %f %d\\n\", _minPrefixDensity, _minPrefix->feature->chrom_start());\n  } else {\n    maxDensity = _minSuffixDensity;\n    mid = _minSuffix;\n    //fprintf(stderr, \"choose suffix %f %d\\n\", _minSuffixDensity, _minSuffix->feature->chrom_start());\n  }  \n\n  if(mid==NULL) { \n    //did not find a cut so bounce out\n    //fprintf(stderr, \"Paraclu PROBLEM mid is null\\n\");\n    return 0;\n  }\n  //printf(\"  maxDensity %f\\n\", maxDensity);\n  //printf(\"  parentDensity %f\\n\", parentDensity);\n  //printf(\"  mid link %s\\n\", mid->feature->chrom_location().c_str());\n\n  int rtn =0;\n  int rtn1=0;\n  int rtn2=0;\n\n  //\n  //subdivide code\n  //\n\n  //printf(\"  subdivide\\n\");\n  //check left child first, if it makes a cluster return out\n  //printf(\"\\nleft child  %s .. %s  [ %ld ]\\n\", beg->feature->chrom_location().c_str(), end->feature->chrom_location().c_str(), cluster_length);\n    \n  FeatureLink *mid1 = mid->prev;\n  long   left_length  = mid1->feature->chrom_start() - beg->feature->chrom_start() + 1;\n  //double left_total   = _calc_total_value(beg, mid1);\n  //double left_density = left_total / left_length;\n\n  long   right_length  = end->feature->chrom_start() - mid->feature->chrom_start() + 1;\n  //double right_total   = _calc_total_value(mid, end);\n  //double right_density = right_total/ right_length;\n\n  //fprintf(stderr, \"left\\n\");\n  rtn1 = _process_cluster_range_smallest(beg, mid1, newParentDensity);\n  rtn = rtn1;\n\n  if((left_length <= _max_cluster_length) && (cluster_length > _max_cluster_length)) {\n    //special transition, check if child can be recovered based on signal\n    if(rtn1==0) {\n      double left_total   = _calc_total_value(beg, mid1);\n      double left_density = left_total / left_length;\n      if(left_total >= _min_cutoff_value) {\n        //children failed to find stable sub clusters, but there is enough signal here to make a cluster\n        EEDB::Feature *feature = _generate_cluster(beg, mid1);\n        if(feature) {\n          feature->metadataset()->add_tag_data(\"density\", d_to_string(left_density));\n          feature->metadataset()->add_tag_data(\"maxDensity\", d_to_string(maxDensity));\n          feature->metadataset()->add_tag_data(\"parentDensity\", d_to_string(newParentDensity));\n          feature->metadataset()->add_tag_data(\"stability\", d_to_string(left_density/newParentDensity));\n          string name = feature->primary_name() + \"-wholeleft\";\n          feature->primary_name(name);\n          _output_buffer->insert_feature(feature);\n          rtn = 1;\n        }\n      }\n    }\n    if(rtn==0) { rtn=2; }\n    //fprintf(stderr, \"discard left-side now\\n\");\n    _discard_region(beg, mid1);\n    return rtn;\n  }\n\n  if(cluster_length > _max_cluster_length) { \n    if(rtn==0) {\n      //do partial trimming of left side to slide buffer if still nothing happened below\n      double left_total = _calc_total_value(beg, mid1);\n      if(left_total < _min_cutoff_value) {\n        //fprintf(stderr, \"discard left-side now\\n\");\n        _discard_region(beg, mid1);\n        return 2;\n      }\n    }\n    return rtn;\n  }\n\n  //\n  // next check right child only if we are < max_cluster_length\n  //\n\n  //fprintf(stderr, \"right child  %ld .. %ld .. %ld  [ %ld ]\\n\", beg->feature->chrom_start(), mid->feature->chrom_start(), end->feature->chrom_start(), cluster_length);\n  //cerr <<\"right\\n\";\n  //fprintf(stderr, \"right\\n\");\n  rtn2 = _process_cluster_range_smallest(mid, end, newParentDensity);\n  if(rtn2==1) { rtn = rtn2; }\n  if(rtn2==2) {\n    fprintf(stderr, \"Paraclu PROBLEM right side returned a 2 which should never happen\\n\");\n  }\n\n  if(rtn1==0 && rtn2==1) {\n    //right made clusters, check if left  has enough signal to be cluster\n    double left_total   = _calc_total_value(beg, mid1);\n    double left_density = left_total / left_length;\n    if(left_total >= _min_cutoff_value) {\n      EEDB::Feature *feature = _generate_cluster(beg, mid1);\n      if(feature) {\n        //fprintf(stderr, \"LEFT-fill because right was stable\\n\");\n        feature->metadataset()->add_tag_data(\"density\", d_to_string(left_density));\n        feature->metadataset()->add_tag_data(\"maxDensity\", d_to_string(maxDensity));\n        feature->metadataset()->add_tag_data(\"parentDensity\", d_to_string(newParentDensity));\n        feature->metadataset()->add_tag_data(\"stability\", d_to_string(left_density/newParentDensity));\n        //fprintf(stderr, \"cluster %s\\n\", feature->chrom_location().c_str());\n        string name = feature->primary_name() + \"-leftfill\";\n        feature->primary_name(name);\n        _output_buffer->insert_feature(feature);\n        rtn = 1;\n      }\n    }\n  }\n\n  if(rtn1==1 && rtn2==0) {\n    //left made clusters, check if right  has enough signal to be cluster\n    double right_total   = _calc_total_value(mid, end);\n    double right_density = right_total / right_length;\n    if(right_total >= _min_cutoff_value) {\n      //fprintf(stderr, \"RIGHT-fill because left made cluster\\n\");\n      EEDB::Feature *feature = _generate_cluster(mid, end);\n      if(feature) {\n        feature->metadataset()->add_tag_data(\"density\", d_to_string(right_density));\n        feature->metadataset()->add_tag_data(\"maxDensity\", d_to_string(maxDensity));\n        feature->metadataset()->add_tag_data(\"parentDensity\", d_to_string(newParentDensity));\n        feature->metadataset()->add_tag_data(\"stability\", d_to_string(right_density/newParentDensity));\n        //fprintf(stderr, \"cluster %s\\n\", feature->chrom_location().c_str());\n        string name = feature->primary_name() + \"-rightfill\";\n        feature->primary_name(name);\n        _output_buffer->insert_feature(feature);\n        rtn=1;\n      }\n    }\n  }\n\n  if((cluster_length <= _max_cluster_length) && (stability >= _min_stability)) {\n    //this is part of the hierarchy\n    //fprintf(stderr, \"this region is small [%ld] & STABLE [%f]\\n\", cluster_length, stability);\n    /*\n    std::cerr << beg->feature->chrom_name() << \"\\t\" << beg->feature->strand() << \"\\t\"\n    << std::setprecision(20)\n    << beg->feature->chrom_start() << \"\\t\" << end->feature->chrom_start() << \"\\t\"\n    << cluster_length << \"\\t\" << totalValue << \"\\t\"\n    << std::setprecision(3)\n    << parentDensity << \"\\t\" << maxDensity ;\n    std::cerr << \"\\t\" << stability;\n    if(stability >= _min_stability) { std::cerr << \"\\tSTABLE\"; }\n    std::cerr << \"\\n\";\n    */\n\n    //if children failed to make clusters, BUT I am stable then I can make a cluster\n    if(rtn==0) {\n      EEDB::Feature *feature = _generate_cluster(beg, end);\n      if(feature) {\n        feature->metadataset()->add_tag_data(\"density\", d_to_string(density));\n        feature->metadataset()->add_tag_data(\"maxDensity\", d_to_string(maxDensity));\n        feature->metadataset()->add_tag_data(\"parentDensity\", d_to_string(parentDensity));\n        feature->metadataset()->add_tag_data(\"stability\", d_to_string(stability));\n        _output_buffer->insert_feature(feature);\n        return 1;    \n      }\n    }\n  }\n\n  return rtn;\n}\n\n\n\nEEDB::Feature*  EEDB::Tools::Paraclu::_generate_cluster(FeatureLink *beg, FeatureLink *end) {\n  //this range has been deemed a valid cluster so convert into a Feature for output\n  \n  //fprintf(stderr, \"_generate_cluster %ld .. %ld\\n\", beg->feature->chrom_start(), end->feature->chrom_start());\n  EEDB::Feature *feature = EEDB::Feature::realloc();\n  feature->feature_source(_feature_source);\n  feature->chrom(_stream_chrom);\n  feature->chrom_start(beg->feature->chrom_start());\n  feature->chrom_end(end->feature->chrom_start());\n  feature->strand(beg->feature->strand());\n\n  EEDB::FeatureLink *flink = beg;\n  while(flink) {\n    feature->collate_expression(flink->feature, EEDB::CL_SUM);\n    if(flink==end) { break; }\n    flink = flink->next;\n  }\n\n  feature->calc_significance(CL_SUM);\n  if(feature->significance() < _min_cutoff_value) {\n    //fprintf(stderr, \"trying to make cluster, but it is too weak so give up\\n\");\n    feature->release();\n    return NULL;\n  }\n\n  char buffer[256];\n  snprintf(buffer, 256, \"paraclu_%ld_%s\", _cluster_number++, feature->chrom_location().c_str());\n  feature->primary_name(buffer);\n\n  return feature;\n}\n\n\n///////////////////////////////////////////////////////////////////////////////////////////\n//\n// re-interpretation of paraclu, should behave the same but new \"cut/select\" idea\n//   works only on left-side recursion and adds concept of \"best_cluster\" to the \n//   depth-first search. no need for min_stability cutoff\n//\n///////////////////////////////////////////////////////////////////////////////////////////\n\n\nvoid  EEDB::Tools::Paraclu::_process_cluster_range_best(FeatureLink *beg, FeatureLink *end) {  \n\n  if(_best_cluster) {\n    delete _best_cluster;\n    _best_cluster = NULL;\n  }\n  _best_cluster = new EEDB::Tools::Paraclu::Cluster;\n\n  _recurse_cluster_range(beg, end, -infinity);\n\n  //if((_best_cluster->totalValue >= _min_cutoff_value) && (_best_cluster->stability >= _min_stability)) {\n  //if((cluster_length <= _max_cluster_length) && (stability ) && (maxDensity > minDensity)) {\n  if(_best_cluster->totalValue >= _min_cutoff_value) {\n    EEDB::Feature *feature = _generate_cluster(_best_cluster);\n    //printf(\"cluster %s\\n\", feature->chrom_location().c_str());\n    _output_buffer->insert_feature(feature);\n  } else {\n    _recover_singletons(_best_cluster->beg, _best_cluster->end);\n  }\n  _discard_region(beg, _best_cluster->end);\n}\n\n\nvoid  EEDB::Tools::Paraclu::_recurse_cluster_range(FeatureLink *beg, FeatureLink *end, double minDensity) {  \n  //recursive algorithm which subdivides sites\n  //printf(\"_recurse_cluster_range\\n\");\n  if((beg==NULL) || (end==NULL)) { return; }\n  \n  if(beg==end) {\n    if(_best_cluster->stability == 0) {\n      //singleton, no best above it\n      _best_cluster->beg = beg;\n      _best_cluster->end = end;\n      _best_cluster->totalValue = beg->feature->significance();\n      _best_cluster->stability = 1.0;\n      _best_cluster->minDensity = minDensity;\n      _best_cluster->maxDensity = minDensity;\n      //_best_cluster->show();\n    }\n    return;\n  }\n    \n  long cluster_length = end->feature->chrom_start() - beg->feature->chrom_start() + 1;\n  //fprintf(stderr, \"_recurse_cluster_range  %s .. %s  [ %ld ]\\n\", beg->feature->chrom_location().c_str(), end->feature->chrom_location().c_str(), cluster_length);\n  \n  double maxDensity=0.0, totalValue=0.0;\n  FeatureLink *mid = NULL;\n\n  totalValue = _weakestPrefix(beg, end);\n  if (totalValue < _min_cutoff_value) { \n    //weak region\n    if(_best_cluster->stability == 0) {\n      _best_cluster->beg = beg;\n      _best_cluster->end = end;\n      _best_cluster->totalValue = totalValue;\n      //_best_cluster->show();\n      //printf(\" WEAK < min_cutoff\\n\");\n    }\n    return; \n  } \n  totalValue = _weakestSuffix(beg, end);\n\n  if(_minPrefixDensity < _minSuffixDensity) {\n    maxDensity = _minPrefixDensity;\n    mid = _minPrefix;\n    //fprintf(stderr, \"choose prefix %f %d\\n\", _minPrefixDensity, _minPrefix->feature->chrom_start());\n  } else {\n    maxDensity = _minSuffixDensity;\n    mid = _minSuffix;\n    //fprintf(stderr, \"choose suffix %f %d\\n\", _minSuffixDensity, _minSuffix->feature->chrom_start());\n  }\n\n  //double maxDensity = min(_minPrefixDensity, _minSuffixDensity);\n  double stability = maxDensity/minDensity;\n  //printf(\"  maxDensity %f\\n\", maxDensity);\n  //printf(\"  minDensity %f\\n\", minDensity);\n  //printf(\"  stability %f\\n\", stability);\n  \n  /*\n  if (maxDensity > minDensity) {\n    std::cerr << beg->feature->chrom_name() << \"\\t\" << beg->feature->strand() << \"\\t\"\n    << std::setprecision(20)\n    << beg->feature->chrom_start() << \"\\t\" << end->feature->chrom_start() << \"\\t\"\n    << cluster_length << \"\\t\" << totalValue << \"\\t\"\n    << std::setprecision(3)\n    << minDensity << \"\\t\" << maxDensity ;\n    std::cerr << \"\\t\" << stability;\n    if(stability >= _min_stability) { std::cerr << \"\\tSTABLE\"; }\n    std::cerr << \"\\n\";\n  }\n  */\n  \n  \n  if((cluster_length <= _max_cluster_length) && (maxDensity > minDensity)) {\n  //if((cluster_length <= _max_cluster_length) && (stability >= _min_stability) && (maxDensity > minDensity)) {\n    //printf(\"  this region is small [%ld] & STABLE [%f], but check children first\\n\", cluster_length, stability);\n    if(_best_cluster->stability < stability) {\n      //printf(\"new best cluster\\n\");\n      _best_cluster->beg = beg;\n      _best_cluster->end = end;\n      _best_cluster->minDensity = minDensity;\n      _best_cluster->maxDensity = maxDensity;\n      _best_cluster->totalValue = totalValue;\n      _best_cluster->stability = stability;\n    }\n  }\n  \n  //FeatureLink *mid = (_minPrefixDensity < _minSuffixDensity) ? _minPrefix : _minSuffix;\n  double newMinDensity = max(minDensity, maxDensity);\n  //printf(\"  mid link %s\\n\", mid->feature->chrom_location().c_str());\n\n  //if <max_length and stable -> create cluster\n  \n  if(mid && (maxDensity < infinity)) {\n    //printf(\"  subdivide\\n\");\n    //check left child first, if it makes a cluster return out\n    //printf(\"\\nleft child  %s .. %s  [ %ld ]\\n\", beg->feature->chrom_location().c_str(), end->feature->chrom_location().c_str(), cluster_length);\n    _recurse_cluster_range(beg, mid->prev, newMinDensity);\n  }\n  //printf(\"returned to parent  %s .. %s  [ %ld ]\\n\", beg->feature->chrom_location().c_str(), end->feature->chrom_location().c_str(), cluster_length);\n}\n\n\n\nEEDB::Feature*  EEDB::Tools::Paraclu::_generate_cluster(Cluster *cl) {\n  //this range has been deemed a valid cluster\n  //convert into a feature for output and readjust feature links to remove these features\n  \n  //fprintf(stderr, \"_generate_cluster %ld .. %ld\\n\", cl->beg->feature->chrom_start(), cl->end->feature->chrom_start());\n  EEDB::Feature *feature = EEDB::Feature::realloc();\n  feature->feature_source(_feature_source);\n  feature->chrom(_stream_chrom);\n  feature->chrom_start(cl->beg->feature->chrom_start());\n  feature->chrom_end(cl->end->feature->chrom_start());\n  feature->strand(cl->beg->feature->strand());\n  feature->primary_name(\"paraclu_\" + feature->chrom_location());\n  \n  EEDB::FeatureLink *flink = cl->beg;\n  while(flink) {\n    feature->collate_expression(flink->feature, EEDB::CL_SUM);\n    if(flink==cl->end) { break; }\n    flink = flink->next;\n  }\n  feature->calc_significance(CL_SUM);\n\n  return feature;\n}\n\n\nvoid  EEDB::Tools::Paraclu::_recover_singletons(FeatureLink *beg, FeatureLink *end) {\n  //if I am about to throw away a region I need to recover any strong CTSS singletons\n  //TODO: figure out where I need to call this\n  EEDB::FeatureLink *flink = beg;\n  while(flink) {\n    if(flink->feature->significance() > _min_cutoff_value) {\n      flink->feature->retain();\n      _output_buffer->insert_feature(flink->feature);\n    }\n    if(flink==end) { break; }\n    flink = flink->next;\n  }\n}\n\n", "meta": {"hexsha": "a1245381a10553806c14dbe964005cfe25ff22ff", "size": 42823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/EEDB/Tools/Paraclu.cpp", "max_stars_repo_name": "jessica-severin/ZENBU_2.11.1", "max_stars_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "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": "c++/EEDB/Tools/Paraclu.cpp", "max_issues_repo_name": "jessica-severin/ZENBU_2.11.1", "max_issues_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "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": "c++/EEDB/Tools/Paraclu.cpp", "max_forks_repo_name": "jessica-severin/ZENBU_2.11.1", "max_forks_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8845822567, "max_line_length": 192, "alphanum_fraction": 0.6519627303, "num_tokens": 11436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.0427221987653165, "lm_q1q2_score": 0.017080832384372836}}
{"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\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n#include <votca/ctp/logger.h>\n#include <votca/tools/constants.h>\n#include <votca/tools/linalg.h>\n#include <votca/xtp/gwbse.h>\n#include <votca/xtp/numerical_integrations.h>\n#include <votca/xtp/qmpackagefactory.h>\n\nusing boost::format;\nusing namespace boost::filesystem;\n\nnamespace votca {\nnamespace xtp {\nnamespace ub = boost::numeric::ublas;\n\n// +++++++++++++++++++++++++++++ //\n// GWBSE MEMBER FUNCTIONS        //\n// +++++++++++++++++++++++++++++ //\n\nvoid GWBSE::CleanUp() {}\n\nvoid GWBSE::Initialize(Property *options) {\n\n#if (GWBSE_DOUBLE)\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Compiled with full double support\"\n                                 << flush;\n#else\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << \" Compiled with float/double mixture (standard)\" << flush;\n#endif\n\n  string key = Identify();\n\n  // getting level ranges\n  _ranges = options->ifExistsReturnElseReturnDefault<string>(key + \".ranges\",\n                                                             \"default\");\n\n  // now check validity, and get rpa, qp, and bse level ranges accordingly\n\n  if (_ranges == \"factor\") {\n    // get factors\n    _rpamaxfactor = options->get(key + \".rpamax\").as<double>();\n    _qpminfactor = options->get(key + \".qpmin\").as<double>();\n    _qpmaxfactor = options->get(key + \".qpmax\").as<double>();\n    _bseminfactor = options->get(key + \".bsemin\").as<double>();\n    _bsemaxfactor = options->get(key + \".bsemax\").as<double>();\n  } else if (_ranges == \"explicit\") {\n    // get explicit numbers\n    _rpamax = options->get(key + \".rpamax\").as<unsigned int>();\n    _qpmin = options->get(key + \".qpmin\").as<unsigned int>();\n    _qpmax = options->get(key + \".qpmax\").as<unsigned int>();\n    _bse_vmin = options->get(key + \".bsemin\").as<unsigned int>();\n    _bse_cmax = options->get(key + \".bsemax\").as<unsigned int>();\n  } else if (_ranges == \"\" || _ranges == \"default\") {\n    _ranges = \"default\";\n  } else if (_ranges == \"full\") {\n    _ranges = \"full\";\n  } else {\n    cerr << \"\\nSpecified range option \" << _ranges << \" invalid. \";\n    throw std::runtime_error(\n        \"\\nValid options are: default,factor,explicit,full\");\n  }\n\n  _ignore_corelevels = options->ifExistsReturnElseReturnDefault<bool>(\n      key + \".ignore_corelevels\", false);\n\n  _bse_nmax =\n      options->ifExistsReturnElseReturnDefault<int>(key + \".exctotal\", 25);\n  _bse_nprint =\n      options->ifExistsReturnElseReturnDefault<int>(key + \".print\", 25);\n  _fragA = options->ifExistsReturnElseReturnDefault<int>(key + \".fragment\", -1);\n\n  string BSEtype =\n      options->ifExistsReturnElseReturnDefault<string>(key + \".BSEtype\", \"TDA\");\n\n  if (BSEtype == \"full\") {\n    _do_full_BSE = true;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" BSE type: full\" << flush;\n  } else {\n    _do_full_BSE = false;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" BSE type: TDA\" << flush;\n  }\n\n  _openmp_threads =\n      options->ifExistsReturnElseReturnDefault<int>(key + \".openmp\", 0);\n\n  if (options->exists(key + \".vxc\")) {\n    _doVxc =\n        options->ifExistsReturnElseThrowRuntimeError<bool>(key + \".vxc.dovxc\");\n    if (_doVxc) {\n      _functional = options->ifExistsReturnElseThrowRuntimeError<string>(\n          key + \".vxc.functional\");\n      _grid = options->ifExistsReturnElseReturnDefault<string>(\n          key + \".vxc.grid\", \"medium\");\n    }\n  }\n\n  _gwbasis_name =\n      options->ifExistsReturnElseThrowRuntimeError<string>(key + \".gwbasis\");\n  _dftbasis_name =\n      options->ifExistsReturnElseThrowRuntimeError<string>(key + \".dftbasis\");\n\n  _shift = options->ifExistsReturnElseThrowRuntimeError<double>(key + \".shift\");\n  _g_sc_limit = options->ifExistsReturnElseReturnDefault<double>(\n      key + \".g_sc_limit\",\n      0.00001);  // convergence criteria for qp iteration [Hartree]]\n  _g_sc_max_iterations = options->ifExistsReturnElseReturnDefault<int>(\n      key + \".g_sc_max_iterations\",\n      40);  // convergence criteria for qp iteration [Hartree]]\n\n  _gw_sc_max_iterations = options->ifExistsReturnElseReturnDefault<int>(\n      key + \".gw_sc_max_iterations\",\n      20);  // convergence criteria for qp iteration [Hartree]]\n\n  _gw_sc_limit = options->ifExistsReturnElseReturnDefault<double>(\n      key + \".gw_sc_limit\", 0.00001);  // convergence criteria for shift it\n  _iterate_gw = false;\n  string _shift_type =\n      options->ifExistsReturnElseThrowRuntimeError<string>(key + \".shift_type\");\n  if (_shift_type != \"fixed\") {\n    _iterate_gw = true;\n  }\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Shift: \" << _shift_type << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" g_sc_limit [Hartree]: \" << _g_sc_limit\n                                 << flush;\n  if (_iterate_gw) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" gw_sc_limit [Hartree]: \" << _gw_sc_limit\n                                   << flush;\n    // if(_g_sc_max_iterations<20){\n    //_g_sc_max_iterations=20;\n    // CTP_LOG(ctp::logDEBUG, *_pLog) << \" Setting G iterations to 20, as it\n    // speeds up the GW iterations\" << flush;\n    // }\n  }\n  _min_print_weight = options->ifExistsReturnElseReturnDefault<double>(\n      key + \".bse_print_weight\",\n      0.2);  // print exciton WF composition weight larger that thin minimum\n\n  // setting some defaults\n  _do_qp_diag = false;\n  _do_bse_singlets = false;\n  _do_bse_triplets = false;\n  // possible tasks\n  // diagQP, singlets, triplets, all, ibse\n  string _tasks_string =\n      options->ifExistsReturnElseThrowRuntimeError<string>(key + \".tasks\");\n  if (_tasks_string.find(\"all\") != std::string::npos) {\n    _do_qp_diag = true;\n    _do_bse_singlets = true;\n    _do_bse_triplets = true;\n  }\n  if (_tasks_string.find(\"qpdiag\") != std::string::npos) _do_qp_diag = true;\n  if (_tasks_string.find(\"singlets\") != std::string::npos)\n    _do_bse_singlets = true;\n  if (_tasks_string.find(\"triplets\") != std::string::npos)\n    _do_bse_triplets = true;\n  _store_eh_interaction = false;\n  _do_bse_diag = true;\n  // special construction for ibse mode\n  if (_tasks_string.find(\"igwbse\") != std::string::npos) {\n    _do_qp_diag = false;   // no qp diagonalization\n    _do_bse_diag = false;  // no diagonalization of BSE Hamiltonian\n    _store_eh_interaction = true;\n  }\n\n  // possible storage\n  // qpPert, qpdiag_energies, qp_diag_coefficients, bse_singlet_energies,\n  // bse_triplet_energies, bse_singlet_coefficients, bse_triplet_coefficients\n  _store_qp_pert = true;\n\n  _store_qp_diag = false;\n  _store_bse_triplets = false;\n  _store_bse_singlets = false;\n  string _store_string =\n      options->ifExistsReturnElseThrowRuntimeError<string>(key + \".store\");\n  if ((_store_string.find(\"all\") != std::string::npos) ||\n      (_store_string.find(\"\") != std::string::npos)) {\n    // store according to tasks choice\n    if (_do_qp_diag) _store_qp_diag = true;\n    if (_do_bse_singlets && _do_bse_diag) _store_bse_singlets = true;\n    if (_do_bse_triplets && _do_bse_diag) _store_bse_triplets = true;\n  }\n  if (_store_string.find(\"qpdiag\") != std::string::npos) _store_qp_diag = true;\n  if (_store_string.find(\"singlets\") != std::string::npos)\n    _store_bse_singlets = true;\n  if (_store_string.find(\"triplets\") != std::string::npos)\n    _store_bse_triplets = true;\n  if (_store_string.find(\"ehint\") != std::string::npos)\n    _store_eh_interaction = true;\n\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Tasks: \" << flush;\n  if (_do_qp_diag) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" qpdiag \" << flush;\n  }\n  if (_do_bse_singlets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" singlets \" << flush;\n  }\n  if (_do_bse_triplets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" triplets \" << flush;\n  }\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Store: \" << flush;\n  if (_store_qp_diag) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" qpdiag \" << flush;\n  }\n  if (_store_bse_singlets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" singlets \" << flush;\n  }\n  if (_store_bse_triplets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" triplets \" << flush;\n  }\n  if (_store_eh_interaction) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" ehint \" << flush;\n  }\n\n  return;\n}\n\nvoid GWBSE::addoutput(Property *_summary) {\n\n  const double hrt2ev = tools::conv::hrt2ev;\n  Property *_gwbse_summary = &_summary->add(\"GWBSE\", \"\");\n  _gwbse_summary->setAttribute(\"units\", \"eV\");\n  _gwbse_summary->setAttribute(\"DeltaHLGap\",\n                               (format(\"%1$+1.6f \") % (_shift * hrt2ev)).str());\n\n  _gwbse_summary->setAttribute(\n      \"DFTEnergy\", (format(\"%1$+1.6f \") % _orbitals->getQMEnergy()).str());\n  int printlimit = _bse_nprint;  // I use this to determine how much is printed,\n                                 // I do not want another option to pipe through\n\n  Property *_dft_summary = &_gwbse_summary->add(\"dft\", \"\");\n  _dft_summary->setAttribute(\"HOMO\", _homo);\n  _dft_summary->setAttribute(\"LUMO\", _homo + 1);\n  int begin = _homo - printlimit;\n  int end = _homo + printlimit + 1;\n  if (begin < 0) {\n    begin = 0;\n    end = 2 * _homo + 1;\n  }\n  for (int state = begin; state < end; state++) {\n\n    Property *_level_summary = &_dft_summary->add(\"level\", \"\");\n    _level_summary->setAttribute(\"number\", state);\n    _level_summary->add(\"dft_energy\",\n                        (format(\"%1$+1.6f \") %\n                         ((_orbitals->MOEnergies())(_qpmin + state) * hrt2ev))\n                            .str());\n    _level_summary->add(\n        \"gw_energy\",\n        (format(\"%1$+1.6f \") % (_qp_energies(_qpmin + state) * hrt2ev)).str());\n\n    if (_do_qp_diag) {\n      // cout << \"_do_qp_diag\" <<_do_qp_diag<<endl;\n      _level_summary->add(\n          \"qp_energy\",\n          (format(\"%1$+1.6f \") % (_qp_diag_energies(_qpmin + state) * hrt2ev))\n              .str());\n    }\n  }\n\n  if (_do_bse_singlets) {\n    Property *_singlet_summary = &_gwbse_summary->add(\"singlets\", \"\");\n    for (int state = 0; state < printlimit; ++state) {\n      Property *_level_summary = &_singlet_summary->add(\"level\", \"\");\n      _level_summary->setAttribute(\"number\", state + 1);\n      _level_summary->add(\"omega\", (format(\"%1$+1.6f \") %\n                                    (_bse_singlet_energies(state) * hrt2ev))\n                                       .str());\n      if (_orbitals->hasTransitionDipoles()) {\n\n        const tools::vec &dipoles = (_orbitals->TransitionDipoles())[state];\n        double f = 2 * dipoles * dipoles * _bse_singlet_energies(state) / 3.0;\n\n        _level_summary->add(\"f\", (format(\"%1$+1.6f \") % f).str());\n        Property *_dipol_summary = &_level_summary->add(\n            \"Trdipole\", (format(\"%1$+1.4f %2$+1.4f %3$+1.4f\") % dipoles.getX() %\n                         dipoles.getY() % dipoles.getZ())\n                            .str());\n        _dipol_summary->setAttribute(\"unit\", \"e*bohr\");\n        _dipol_summary->setAttribute(\"gauge\", \"length\");\n      }\n    }\n  }\n  if (_do_bse_triplets) {\n    Property *_triplet_summary = &_gwbse_summary->add(\"triplets\", \"\");\n    for (int state = 0; state < printlimit; ++state) {\n\n      Property *_level_summary = &_triplet_summary->add(\"level\", \"\");\n      _level_summary->setAttribute(\"number\", state + 1);\n      _level_summary->add(\"omega\", (format(\"%1$+1.6f \") %\n                                    (_bse_triplet_energies(state) * hrt2ev))\n                                       .str());\n    }\n  }\n  return;\n}\n\n/*\n *    Many-body Green's fuctions theory implementation\n *\n *  data required from orbitals file\n *  - atomic coordinates\n *  - DFT molecular orbitals (energies and coeffcients)\n *  - DFT exchange-correlation potential matrix in atomic orbitals\n *  - number of electrons, number of levels\n *\n\n */\n\nbool GWBSE::Evaluate() {\n\n// set the parallelization\n#ifdef _OPENMP\n  if (_openmp_threads > 0) {\n    omp_set_num_threads(_openmp_threads);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Using \"\n                                   << omp_get_max_threads() << \" threads\"\n                                   << flush;\n  }\n#endif\n  /* check which QC program was used for the DFT run\n   * -> implicit info about MO coefficient storage order\n   */\n  string _dft_package = _orbitals->getQMpackage();\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" DFT data was created by \" << _dft_package\n                                 << flush;\n\n  std::vector<ctp::QMAtom *> _atoms;\n  for (const auto &atom : _orbitals->QMAtoms()) {\n    if (!atom->from_environment) {\n      _atoms.push_back(atom);\n    }\n  }\n  // load DFT basis set (element-wise information) from xml file\n  BasisSet dftbs;\n\n  if (_dftbasis_name != _orbitals->getDFTbasis()) {\n    throw std::runtime_error(\n        \"Name of the Basisset from .orb file: \" + _orbitals->getDFTbasis() +\n        \" and from GWBSE optionfile \" + _dftbasis_name + \" do not agree.\");\n  }\n\n  dftbs.LoadBasisSet(_dftbasis_name);\n  _orbitals->setDFTbasis(_dftbasis_name);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Loaded DFT Basis Set \"\n                                 << _dftbasis_name << flush;\n\n  // fill DFT AO basis by going through all atoms\n\n  _dftbasis.AOBasisFill(&dftbs, _atoms, _fragA);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled DFT Basis of size \"\n                                 << _dftbasis.AOBasisSize() << flush;\n  if (_dftbasis._AOBasisFragB > 0) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" FragmentA size \"\n                                   << _dftbasis._AOBasisFragA << flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" FragmentB size \"\n                                   << _dftbasis._AOBasisFragB << flush;\n  }\n\n  if (_do_full_BSE)\n    _orbitals->setBSEtype(\"full\");\n  else {\n    _orbitals->setBSEtype(\"TDA\");\n  }\n  /* Preparation of calculation parameters:\n   *  - number of electrons -> index of HOMO\n   *  - number of levels\n   *  - highest level considered in RPA\n   *  - lowest and highest level considered in GWA\n   *  - lowest and highest level considered in BSE\n   *  - number of excitations calculates in BSE\n   */\n\n  // convert _rpamax if needed\n  _homo = _orbitals->getNumberOfElectrons() - 1;  // indexed from 0\n\n  unsigned int _ignored_corelevels = 0;\n  if (_ignore_corelevels) {\n    std::string _ecpsave = _orbitals->getECP();\n    _orbitals->setECP(\"ecp\");\n    int _valence_levels =\n        _orbitals->FragmentNuclearCharges(_atoms.size())(0) / 2;\n    _orbitals->setECP(_ecpsave);\n    _ignored_corelevels = _orbitals->getNumberOfElectrons() - _valence_levels;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Can ignore \"\n                                   << _ignored_corelevels << \" core levels \"\n                                   << flush;\n  }\n\n  _rpamin = 0;  // lowest index occ min(gwa%mmin, screening%nsum_low) ! always 1\n  if (_ranges == \"default\" || _ranges == \"full\") {\n    _rpamax = _orbitals->getNumberOfLevels() - 1;  // total number of levels\n  } else if (_ranges == \"factor\") {\n    _rpamax = _rpamaxfactor * _orbitals->getNumberOfLevels() -\n              1;  // total number of levels\n  }\n  if (_rpamax > _orbitals->getNumberOfLevels() - 1) {\n    _rpamax = _orbitals->getNumberOfLevels() - 1;\n  }\n  // convert _qpmin and _qpmax if needed\n  if (_ranges == \"default\") {\n    _qpmin = 0;              // indexed from 0\n    _qpmax = 2 * _homo + 1;  // indexed from 0\n  } else if (_ranges == \"factor\") {\n    if (_orbitals->getNumberOfElectrons() -\n            int(_qpminfactor * _orbitals->getNumberOfElectrons()) - 1 <\n        0) {\n      _qpmin = 0;\n    } else {\n      _qpmin = _orbitals->getNumberOfElectrons() -\n               int(_qpminfactor * _orbitals->getNumberOfElectrons()) - 1;\n    }\n    _qpmax = _orbitals->getNumberOfElectrons() +\n             int(_qpmaxfactor * _orbitals->getNumberOfElectrons()) - 1;\n  } else if (_ranges == \"explicit\") {\n    _qpmin -= 1;\n    _qpmax -= 1;\n  } else if (_ranges == \"full\") {\n    _qpmin = 0;\n    _qpmax = _orbitals->getNumberOfLevels() - 1;\n  }\n  if (_qpmax > unsigned(_orbitals->getNumberOfLevels() - 1)) {\n    _qpmax = _orbitals->getNumberOfLevels() - 1;\n  }\n\n  // autoignore core levels in QP\n  if (_ignore_corelevels && (_qpmin < _ignored_corelevels)) {\n    _qpmin = _ignored_corelevels;\n  }\n\n  // set BSE band range indices\n  // anything else would be stupid!\n  _bse_vmax = _homo;\n  _bse_cmin = _homo + 1;\n\n  if (_ranges == \"default\") {\n    _bse_vmin = 0;              // indexed from 0\n    _bse_cmax = 2 * _homo + 1;  // indexed from 0\n  } else if (_ranges == \"factor\") {\n    _bse_vmin = _orbitals->getNumberOfElectrons() -\n                int(_bseminfactor * _orbitals->getNumberOfElectrons()) - 1;\n    if (_orbitals->getNumberOfElectrons() -\n            int(_bseminfactor * _orbitals->getNumberOfElectrons()) - 1 <\n        0) {\n      _bse_vmin = 0;\n    }\n    _bse_cmax = _orbitals->getNumberOfElectrons() +\n                int(_bsemaxfactor * _orbitals->getNumberOfElectrons()) - 1;\n  } else if (_ranges == \"explicit\") {\n    _bse_vmin -= 1;\n    _bse_cmax -= 1;\n  } else if (_ranges == \"full\") {\n    _bse_vmin = 0;\n    _bse_cmax = _orbitals->getNumberOfLevels() - 1;\n  }\n  if (_bse_cmax > unsigned(_orbitals->getNumberOfLevels() - 1)) {\n    _bse_cmax = _orbitals->getNumberOfLevels() - 1;\n  }\n\n  // autoignore core levels in BSE\n  if (_ignore_corelevels && (_bse_vmin < _ignored_corelevels)) {\n    _bse_vmin = _ignored_corelevels;\n  }\n\n  _bse_vtotal = _bse_vmax - _bse_vmin + 1;\n  _bse_ctotal = _bse_cmax - _bse_cmin + 1;\n  _bse_size = _bse_vtotal * _bse_ctotal;\n\n  // indexing info BSE vector index to occupied/virtual orbital\n  for (unsigned _v = 0; _v < _bse_vtotal; _v++) {\n    for (unsigned _c = 0; _c < _bse_ctotal; _c++) {\n      _index2v.push_back(_bse_vmin + _v);\n      _index2c.push_back(_bse_cmin + _c);\n    }\n  }\n\n  // some QP - BSE consistency checks are required\n  if (_bse_vmin < _qpmin) _qpmin = _bse_vmin;\n  if (_bse_cmax > _qpmax) _qpmax = _bse_cmax;\n\n  _qptotal = _qpmax - _qpmin + 1;\n  if (_bse_nmax > int(_bse_size) || _bse_nmax < 0) _bse_nmax = int(_bse_size);\n  if (_bse_nprint > _bse_nmax) _bse_nprint = _bse_nmax;\n\n  // store information in _orbitals for later use\n  _orbitals->setRPAindices(_rpamin, _rpamax);\n  _orbitals->setGWAindices(_qpmin, _qpmax);\n  _orbitals->setBSEindices(_bse_vmin, _bse_vmax, _bse_cmin, _bse_cmax,\n                           _bse_nmax);\n\n  // information for hybrid DFT\n\n  _ScaHFX = -1;\n\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Set RPA level range [\"\n                                 << _rpamin + 1 << \":\" << _rpamax + 1 << \"]\"\n                                 << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Set QP  level range [\"\n                                 << _qpmin + 1 << \":\" << _qpmax + 1 << \"]\"\n                                 << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Set BSE level range occ[\" << _bse_vmin + 1 << \":\"\n      << _bse_vmax + 1 << \"]  virt[\" << _bse_cmin + 1 << \":\" << _bse_cmax + 1\n      << \"]\" << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" BSE Hamiltonian has size \" << _bse_size << \"x\"\n      << _bse_size << flush;\n\n  // process the DFT data\n  // a) form the expectation value of the XC functional in MOs\n\n  _ScaHFX = _orbitals->getScaHFX();\n\n  ub::matrix<double> _vxc_ao;\n  if (_orbitals->hasAOVxc()) {\n    if (_doVxc) {\n      CTP_LOG(ctp::logDEBUG, *_pLog)\n          << ctp::TimeStamp()\n          << \" There is already a Vxc matrix loaded from DFT, did you maybe \"\n             \"run a DFT code with outputVxc?\\n I will take the external \"\n             \"implementation\"\n          << flush;\n      _doVxc = false;\n    }\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Loaded external Vxc matrix\" << flush;\n    _vxc_ao = _orbitals->AOVxc();\n  } else if (_doVxc) {\n\n    NumericalIntegration _numint;\n    _numint.setXCfunctional(_functional);\n    double ScaHFX_temp = _numint.getExactExchange(_functional);\n    if (ScaHFX_temp != _ScaHFX) {\n      throw std::runtime_error(\n          (boost::format(\"GWBSE exact exchange a=%s differs from qmpackage \"\n                         \"exact exchange a=%s, probably your functionals are \"\n                         \"inconsistent\") %\n           ScaHFX_temp % _ScaHFX)\n              .str());\n    }\n    _numint.GridSetup(_grid, &dftbs, _atoms, &_dftbasis);\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp()\n        << \" Setup grid for integration with gridsize: \" << _grid << \" with \"\n        << _numint.getGridSize() << \" points, divided into \"\n        << _numint.getBoxesSize() << \" boxes\" << flush;\n\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Converted DFT orbital coefficient order from \"\n        << _dft_package << \" to XTP\" << flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Integrating Vxc in VOTCA with functional \"\n        << _functional << flush;\n    ub::matrix<double> DMAT = _orbitals->DensityMatrixGroundState();\n\n    _vxc_ao = _numint.IntegrateVXC(DMAT);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Calculated Vxc in VOTCA\" << flush;\n\n  } else {\n    throw std::runtime_error(\n        \"So your DFT data contains no Vxc, if you want to proceed use the \"\n        \"dovxc option.\");\n  }\n\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Set hybrid exchange factor: \" << _ScaHFX\n                                 << flush;\n\n  // now get expectation values but only for those in _qpmin:_qpmax range\n  ub::matrix<double> _mos =\n      ub::project(_dft_orbitals, ub::range(_qpmin, _qpmax + 1),\n                  ub::range(0, _dftbasis.AOBasisSize()));\n\n  ub::matrix<double> _temp = ub::prod(_vxc_ao, ub::trans(_mos));\n  _vxc = ub::prod(_mos, _temp);\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp()\n      << \" Calculated exchange-correlation expectation values \" << flush;\n  _vxc_ao.resize(0, 0);\n\n  /// ------- actual calculation begins here -------\n\n  // load auxiliary GW basis set (element-wise information) from xml file\n  BasisSet gwbs;\n  gwbs.LoadBasisSet(_gwbasis_name);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Loaded GW Basis Set \"\n                                 << _gwbasis_name << flush;\n\n  // fill auxiliary GW AO basis by going through all atoms\n  AOBasis gwbasis;\n  gwbasis.AOBasisFill(&gwbs, _atoms);\n  _orbitals->setGWbasis(_gwbasis_name);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled GW Basis of size \"\n                                 << gwbasis.AOBasisSize() << flush;\n\n  /*\n   * for the representation of 2-point functions with the help of the\n   * auxiliary GW basis, its AO overlap matrix is required.\n   * cf. M. Rohlfing, PhD thesis, ch. 3\n   */\n  AOOverlap _gwoverlap;\n  // Fill overlap\n  _gwoverlap.Fill(gwbasis);\n\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled GW Overlap matrix of dimension: \"\n                                 << _gwoverlap.Matrix().size1() << flush;\n\n  /*\n   *  for the calculation of Coulomb and exchange term in the self\n   *  energy and electron-hole interaction, the Coulomb interaction\n   *  is represented using the auxiliary GW basis set.\n   *  Here, we need to prepare the Coulomb matrix expressed in\n   *  the AOs of the GW basis\n   */\n\n  // get Coulomb matrix as AOCoulomb\n  AOCoulomb _gwcoulomb;\n\n  // Fill Coulomb matrix\n  _gwcoulomb.Fill(gwbasis);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled GW Coulomb matrix of dimension: \"\n                                 << _gwcoulomb.Matrix().size1() << flush;\n\n  // PPM is symmetric, so we need to get the sqrt of the Coulomb matrix\n\n  ub::matrix<double> _gwoverlap_cholesky = _gwoverlap.Matrix();\n  linalg_cholesky_decompose(_gwoverlap_cholesky);\n\n// remove L^T from Cholesky\n#pragma omp parallel for\n  for (unsigned i = 0; i < _gwoverlap_cholesky.size1(); i++) {\n    for (unsigned j = i + 1; j < _gwoverlap_cholesky.size1(); j++) {\n      _gwoverlap_cholesky(i, j) = 0.0;\n    }\n  }\n\n  ub::matrix<double> _gwoverlap_cholesky_inverse;  // will also be needed in PPM\n                                                   // itself\n  int removed =\n      linalg_invert_svd(_gwoverlap_cholesky, _gwoverlap_cholesky_inverse, 1e7);\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Removed \" << removed\n      << \" functions from gwoverlap to avoid near linear dependencies\" << flush;\n\n  int removed_functions = _gwcoulomb.Symmetrize(_gwoverlap_cholesky);\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Prepared GW Coulomb matrix for symmetric PPM\"\n      << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Removed \" << removed_functions\n      << \" functions from gwcoulomb to avoid near linear dependencies\" << flush;\n  /* calculate 3-center integrals,  convoluted with DFT eigenvectors\n   *\n   *  M_mn(beta) = \\int{ \\psi^DFT_m(r) \\phi^GW_beta(r) \\psi^DFT_n d3r  }\n   *             = \\sum_{alpha,gamma} { c_m,alpha c_n,gamma \\int\n   * {\\phi^DFT_alpha(r) \\phi^GW_beta(r) \\phi^DFT_gamma(r) d3r}  }\n   *\n   *  cf. M. Rohlfing, PhD thesis, ch. 3.2\n   *\n   */\n\n  // --- prepare a vector (gwdacay) of matrices (orbitals, orbitals) as\n  // container => M_mn\n  // prepare 3-center integral object\n\n  TCMatrix _Mmn;\n  _Mmn.Initialize(gwbasis.AOBasisSize(), _rpamin, _qpmax, _rpamin, _rpamax);\n  _Mmn.Fill(gwbasis, _dftbasis, _dft_orbitals);\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp()\n      << \" Calculated Mmn_beta (3-center-repulsion x orbitals)  \" << flush;\n\n  // make _Mmn symmetric\n  _Mmn.Symmetrize(_gwcoulomb.Matrix());\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Symmetrize Mmn_beta for self-energy  \" << flush;\n\n  // for use in RPA, make a copy of _Mmn with dimensions\n  // (1:HOMO)(gwabasissize,LUMO:nmax)\n  TCMatrix _Mmn_RPA;\n  _Mmn_RPA.Initialize(gwbasis.AOBasisSize(), _rpamin, _homo, _homo + 1,\n                      _rpamax);\n  RPA_prepare_threecenters(_Mmn_RPA, _Mmn);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Prepared Mmn_beta for RPA  \" << flush;\n\n  // fix the frequencies for PPM\n  _screening_freq = ub::zero_matrix<double>(2, 2);  // two frequencies\n  // first one\n  _screening_freq(0, 0) = 0.0;  // real part\n  _screening_freq(0, 1) = 0.0;  // imaginary part\n  // second one\n  _screening_freq(1, 0) = 0.0;  // real part\n  _screening_freq(1, 1) = 0.5;  // imaginary part  //hartree\n\n  // one entry to epsilon for each frequency\n  _epsilon.resize(_screening_freq.size1());\n\n  /* for automatic iteration of _shift, we need to\n   * - make a copy of _Mmn\n   * - calculate eps\n   * - construct ppm\n   * - threecenters for sigma\n   * - sigma_x\n   * - sigma_c\n   * - test for convergence\n   *\n   */\n\n  // initialize _qp_energies;\n  // shift unoccupied levels by the shift\n  _qp_energies = ub::zero_vector<double>(_orbitals->getNumberOfLevels());\n  for (size_t i = 0; i < _qp_energies.size(); ++i) {\n    _qp_energies(i) = _orbitals->MOEnergies()(i);\n    if (i > _homo) {\n      _qp_energies(i) += _shift;\n    }\n  }\n\n  _sigma_c.resize(_qptotal);\n  _sigma_x.resize(_qptotal);\n\n  TCMatrix _Mmn_backup;\n  if (_iterate_gw) {\n\n    // make copy of _Mmn, memory++\n\n    _Mmn_backup.Initialize(gwbasis.AOBasisSize(), _rpamin, _qpmax, _rpamin,\n                           _rpamax);\n    int _mnsize = _Mmn_backup.get_mtot();\n    for (int _i = 0; _i < _mnsize; _i++) {\n      _Mmn_backup[_i] = _Mmn[_i];\n    }\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Made backup of _Mmn  \" << flush;\n  } else {\n    _gw_sc_max_iterations = 1;\n  }\n\n  const ub::vector<double> &_dft_energies = _orbitals->MOEnergies();\n  for (unsigned gw_iteration = 0; gw_iteration < _gw_sc_max_iterations;\n       ++gw_iteration) {\n\n    ub::vector<double> _qp_old_rpa = _qp_energies;\n    if (_iterate_gw) {\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" GW Iteraton \"\n                                     << gw_iteration + 1 << \" of \"\n                                     << _gw_sc_max_iterations << flush;\n    }\n\n    // for symmetric PPM, we can initialize _epsilon with the overlap matrix!\n    for (unsigned _i_freq = 0; _i_freq < _screening_freq.size1(); _i_freq++) {\n      _epsilon[_i_freq] = _gwoverlap.Matrix();\n    }\n\n    // determine epsilon from RPA\n    RPA_calculate_epsilon(_Mmn_RPA);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Calculated epsilon via RPA  \" << flush;\n\n    // construct PPM parameters\n    PPM_construct_parameters(_gwoverlap_cholesky_inverse);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Constructed PPM parameters  \" << flush;\n\n    // prepare threecenters for Sigma\n    sigma_prepare_threecenters(_Mmn);\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Prepared threecenters for sigma  \" << flush;\n\n    sigma_diag(_Mmn);\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Calculated diagonal part of Sigma  \" << flush;\n    // iterative refinement of qp energies\n\n    double _DFTgap = _dft_energies(_homo + 1) - _dft_energies(_homo);\n    double _QPgap = _qp_energies(_homo + 1) - _qp_energies(_homo);\n    _shift = _QPgap - _DFTgap;\n\n    // qp energies outside the update range are simply shifted.\n    for (unsigned i = _qpmax + 1; i < _dft_energies.size(); ++i) {\n      _qp_energies(i) = _dft_energies(i) + _shift;\n    }\n\n    if (_iterate_gw) {\n      bool _gw_converged = true;\n      ub::vector<double> diff = _qp_old_rpa - _qp_energies;\n      unsigned int _l_not_converged = 0;\n      double E_max = 0;\n      for (unsigned l = 0; l < diff.size(); l++) {\n        if (std::abs(diff(l)) > std::abs(E_max)) {\n          _l_not_converged = l;\n          E_max = diff(l);\n        }\n        if (std::abs(diff(l)) > _gw_sc_limit) {\n          _gw_converged = false;\n        }\n      }\n      double alpha = 0.0;\n      _qp_energies = alpha * _qp_old_rpa + (1 - alpha) * _qp_energies;\n      if (tools::globals::verbose) {\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" GW_Iteration: \" << gw_iteration + 1\n            << \" shift=\" << _shift << \" E_diff max=\" << E_max\n            << \" StateNo:\" << _l_not_converged << flush;\n      }\n\n      if (_gw_converged) {\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" Converged after \" << gw_iteration + 1\n            << \" GW iterations\" << flush;\n        break;\n      } else if (gw_iteration == _gw_sc_max_iterations - 1) {\n        // continue regardless for now, but drop WARNING\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" WARNING! GWA spectrum not converged after \"\n            << _gw_sc_max_iterations << \" iterations.\" << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \"          GWA level \" << _l_not_converged\n            << \" energy changed by \" << diff(_l_not_converged) << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp()\n            << \"          Run continues. Inspect results carefully!\" << flush;\n        break;\n      }\n\n      int _mnsize = _Mmn_backup.get_mtot();\n      for (int _i = 0; _i < _mnsize; _i++) {\n        _Mmn[_i] = _Mmn_backup[_i];\n      }\n    }\n  }\n\n  sigma_offdiag(_Mmn);\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Calculated offdiagonal part of Sigma  \" << flush;\n  _gwoverlap.Matrix().resize(0, 0);\n  _gwoverlap_cholesky_inverse.resize(0, 0);\n  _Mmn_RPA.Cleanup();\n  if (_iterate_gw) {\n    _Mmn_backup.Cleanup();\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Cleaned up Overlap, MmnRPA and Mmn_backup \"\n        << flush;\n  } else {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Cleaned up Overlap and MmnRPA\" << flush;\n  }\n  // free no longer required three-center matrices in _Mmn\n  // max required is _bse_cmax (could be smaller than _qpmax)\n  _Mmn.Prune(gwbasis.AOBasisSize(), _bse_vmin, _bse_cmax);\n\n  // Output of quasiparticle energies after all is done:\n\n  CTP_LOG(ctp::logINFO, *_pLog)\n      << (format(\n              \"  ====== Perturbative quasiparticle energies (Hartree) ====== \"))\n             .str()\n      << flush;\n  CTP_LOG(ctp::logINFO, *_pLog)\n      << (format(\"   DeltaHLGap = %1$+1.6f Hartree\") % _shift).str() << flush;\n\n  for (unsigned _i = 0; _i < _qptotal; _i++) {\n    if ((_i + _qpmin) == _homo) {\n      CTP_LOG(ctp::logINFO, *_pLog)\n          << (format(\"  HOMO  = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = \"\n                     \"%4$+1.4f S-C = %5$+1.4f GWA = %6$+1.4f\") %\n              (_i + _qpmin + 1) % _dft_energies(_i + _qpmin) % _vxc(_i, _i) %\n              _sigma_x(_i, _i) % _sigma_c(_i, _i) % _qp_energies(_i + _qpmin))\n                 .str()\n          << flush;\n    } else if ((_i + _qpmin) == _homo + 1) {\n      CTP_LOG(ctp::logINFO, *_pLog)\n          << (format(\"  LUMO  = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = \"\n                     \"%4$+1.4f S-C = %5$+1.4f GWA = %6$+1.4f\") %\n              (_i + _qpmin + 1) % _dft_energies(_i + _qpmin) % _vxc(_i, _i) %\n              _sigma_x(_i, _i) % _sigma_c(_i, _i) % _qp_energies(_i + _qpmin))\n                 .str()\n          << flush;\n\n    } else {\n      CTP_LOG(ctp::logINFO, *_pLog)\n          << (format(\"  Level = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = \"\n                     \"%4$+1.4f S-C = %5$+1.4f GWA = %6$+1.4f\") %\n              (_i + _qpmin + 1) % _dft_energies(_i + _qpmin) % _vxc(_i, _i) %\n              _sigma_x(_i, _i) % _sigma_c(_i, _i) % _qp_energies(_i + _qpmin))\n                 .str()\n          << flush;\n    }\n  }\n\n  // store perturbative QP energy data in orbitals object (DFT, S_x,S_c, V_xc,\n  // E_qp)\n  if (_store_qp_pert) {\n    ub::matrix<double> &_qp_energies_store = _orbitals->QPpertEnergies();\n    _qp_energies_store.resize(_qptotal, 5);\n    for (unsigned _i = 0; _i < _qptotal; _i++) {\n      _qp_energies_store(_i, 0) = _dft_energies(_i + _qpmin);\n      _qp_energies_store(_i, 1) = _sigma_x(_i, _i);\n      _qp_energies_store(_i, 2) = _sigma_c(_i, _i);\n      _qp_energies_store(_i, 3) = _vxc(_i, _i);\n      _qp_energies_store(_i, 4) = _qp_energies(_i + _qpmin);\n    }\n  }\n\n  // constructing full quasiparticle Hamiltonian and diagonalize, if requested\n  if (_do_qp_diag || _do_bse_singlets || _do_bse_triplets) {\n    FullQPHamiltonian();\n    if (_do_qp_diag) {\n      CTP_LOG(ctp::logDEBUG, *_pLog)\n          << ctp::TimeStamp() << \" Full quasiparticle Hamiltonian  \" << flush;\n      CTP_LOG(ctp::logINFO, *_pLog)\n          << (format(\"  ====== Diagonalized quasiparticle energies (Hartree) \"\n                     \"====== \"))\n                 .str()\n          << flush;\n      for (unsigned _i = 0; _i < _qptotal; _i++) {\n        if ((_i + _qpmin) == _homo) {\n          CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  HOMO  = %1$4d PQP = %2$+1.4f DQP = %3$+1.4f \") %\n                  (_i + _qpmin + 1) % _qp_energies(_i + _qpmin) %\n                  _qp_diag_energies(_i))\n                     .str()\n              << flush;\n        } else if ((_i + _qpmin) == _homo + 1) {\n          CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  LUMO  = %1$4d PQP = %2$+1.4f DQP = %3$+1.4f \") %\n                  (_i + _qpmin + 1) % _qp_energies(_i + _qpmin) %\n                  _qp_diag_energies(_i))\n                     .str()\n              << flush;\n\n        } else {\n          CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  Level = %1$4d PQP = %2$+1.4f DQP = %3$+1.4f \") %\n                  (_i + _qpmin + 1) % _qp_energies(_i + _qpmin) %\n                  _qp_diag_energies(_i))\n                     .str()\n              << flush;\n        }\n      }\n\n      // free memory\n\n      if (!_store_qp_diag) {\n        _qp_diag_coefficients.resize(0, 0);\n        _qp_diag_energies.resize(0);\n      }\n    }  // _do_qp_diag\n  }    // constructing full quasiparticle Hamiltonian\n\n  // proceed only if BSE requested\n  if (_do_bse_singlets || _do_bse_triplets) {\n\n    // calculate direct part of eh interaction, needed for singlets and triplets\n    BSE_d_setup(_Mmn);\n    // add qp part to Eh_d\n    BSE_Add_qp2H(_eh_d);\n    // Only if verbose do we use this really\n    if (votca::tools::globals::verbose) {\n      BSE_qp_setup();\n    }\n\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Direct part of e-h interaction \" << flush;\n\n    if (_do_full_BSE) {\n      BSE_d2_setup(_Mmn);\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                     << \" Direct part of e-h interaction RARC \"\n                                     << flush;\n    }\n\n    if (_do_bse_triplets && _do_bse_diag) {\n      BSE_solve_triplets();\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                     << \" Solved BSE for triplets \" << flush;\n      // analyze and report results\n      BSE_analyze_triplets();\n\n    }  // do_triplets\n\n    // constructing electron-hole interaction for BSE\n    if (_do_bse_singlets) {\n      // calculate exchange part of eh interaction, only needed for singlets\n      BSE_x_setup(_Mmn);\n      CTP_LOG(ctp::logDEBUG, *_pLog)\n          << ctp::TimeStamp() << \" Exchange part of e-h interaction \" << flush;\n    }\n\n    if (_do_bse_singlets && _do_bse_diag) {\n\n      if (_do_full_BSE) {\n        BSE_solve_singlets_BTDA();\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" Solved full BSE for singlets \" << flush;\n        BSE_analyze_singlets_BTDA();\n      } else {\n        BSE_solve_singlets();\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                       << \" Solved BSE for singlets \" << flush;\n        BSE_analyze_singlets();\n      }\n\n      if (!_store_eh_interaction) {\n        _eh_d.resize(0, 0);\n        _eh_x.resize(0, 0);\n      }\n    }\n  }\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" GWBSE calculation finished \" << flush;\n  return true;\n}\n}\n};\n", "meta": {"hexsha": "bd7556226530a7b01f6001db7d0d321af6c618e3", "size": 38750, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/gwbse.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/gwbse/gwbse.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/gwbse/gwbse.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.0813397129, "max_line_length": 80, "alphanum_fraction": 0.5912774194, "num_tokens": 11865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.037326890422979896, "lm_q1q2_score": 0.017063492137340687}}
{"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#include <boost/array.hpp>\n\nnamespace boost {\n/*\nnamespace detail{\n    //template <class Graph, class IndexMap, class Value>\n    //struct my_vertex_property_map_generator_helper {};\n    template <class Graph, class IndexMap, class Value>\n    struct my_vertex_property_map_generator_helper{\n        typedef boost::iterator_property_map<Value*, IndexMap> type;\n        static type build(const Graph& g, const IndexMap& index, boost::array<Value>& array_holder) {\n            // array_holder.reset(new Value[num_vertices(g)]);\n            std::fill(array_holder.get(), array_holder.get() + num_vertices(g), Value());\n            return make_iterator_property_map(array_holder.get(), index);\n        }\n    };    \n}*/\n\n// template <class Graph, class IndexMap, class Value>\n// static boost::iterator_property_map<Value*, IndexMap> build(const Graph& g, const IndexMap& index, boost::array<Value>& array_holder){\n//     array_holder.reset(new Value[num_vertices(g)]);\n//     std::fill(array_holder.get(), array_holder.get() + num_vertices(g), Value());\n//     // Vertex index to fetch the pointer address at array holder. \n//     // It maps the indexmap (or index vector) to the values stored in the iteratior, which is the array holder. \n//     return make_iterator_property_map(array_holder.get(), index);\n// };\n\n\n/**\n *  This is an optimized driving distance function based on dijkstra_shortest_paths_no_color_map_no_init\n *  in BGL.\n *\n *  Input:\n *      graph,...,distance_zero: graph definitions\n *      delta: upper bound distance for early stopping\n *      Note: the predecessor map must be initialized with the vertex at each position\n *      and the distance map initialized with infinity\n *\n *  Returns:\n *      predecessor_map: similar to Dijkstra\n *      distance_map: similar to Dijkstra\n *      examined_vertex_map: examined vertexes, that will be used\n *      to clean the predecessor_map and distance_map in repeated queries.\n *\n */\ntemplate <typename Graph,\n          typename PredecessorMap, typename DistanceMap,\n          typename WeightMap, typename VertexIndexMap,\n          typename DistanceCompare, typename DistanceWeightCombine,\n          typename DistanceInfinity, typename DistanceZero>\nvoid dijkstra_shortest_paths_upperbound\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, double distance_goal,\n std::vector<typename Graph::vertex_descriptor> &nodes_within_goal,\n std::vector<typename Graph::vertex_descriptor> &examined_vertices)\n{\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n\n    typedef indirect_cmp<DistanceMap, DistanceCompare> DistanceIndirectCompare;\n    DistanceIndirectCompare\n    distance_indirect_compare(distance_map, distance_compare);\n\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 boost::iterator_property_map<std::size_t *,VertexIndexMap> IndexInHeapMap;\n    typedef\n    d_ary_heap_indirect<Vertex, 4, IndexInHeapMap, DistanceMap, DistanceCompare>\n    VertexQueue;\n    // 80%\n    // boost::scoped_array<std::size_t> index_in_heap_map_holder;\n    // // IndexInHeapMap is actually a boost::iterator_property_map<Value*, IndexMap> \n    // IndexInHeapMap index_in_heap =\n    //     IndexInHeapMapHelper::build(graph, index_map,\n    //                                 index_in_heap_map_holder);\n    // typedef boost::array<std::size_t, std::size_t num_vertices(g)> array;\n    // *dheap_on_stack = new boost::array(std::size_t,num_vertices(g));\n    std::size_t * dheap_on_stack = new std::size_t[num_vertices(graph)];\n    boost::iterator_property_map<std::size_t *,VertexIndexMap> index_in_heap_map = \n        make_iterator_property_map(dheap_on_stack, index_map);\n\n    // The first two arguments in the template of VertexQueue are already defined\n    VertexQueue vertex_queue(distance_map, index_in_heap_map, distance_compare);\n\n    double m_distance_goal; //Delta\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        // visitor.examine_vertex(min_vertex, graph);\n        nodes_within_goal.push_back(min_vertex);\n        if (distance_map[min_vertex] > distance_goal) {\n            nodes_within_goal.pop_back();\n            delete[] dheap_on_stack;\n            return;\n        }\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            delete[] dheap_on_stack;\n            return;\n        }\n\n        // Examine neighbors of min_vertex\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                // visitor.edge_relaxed(current_edge, graph);\n                examined_vertices.push_back(neighbor_vertex);\n                if (is_neighbor_undiscovered) {\n                    // visitor.discover_vertex(neighbor_vertex, graph);\n                    vertex_queue.push(neighbor_vertex);\n                } else {\n                    vertex_queue.update(neighbor_vertex);\n                }\n            } else {\n                // visitor.edge_not_relaxed(current_edge, graph);\n            }\n\n        } // end out edge iteration\n\n        // visitor.finish_vertex(min_vertex, graph);\n    } // end while queue not empty\n    delete[] dheap_on_stack;\n} // dijkstra_shortest_paths_upperbound\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_DIJKSTRA_NO_COLOR_MAP_HPP", "meta": {"hexsha": "24ed94267925a47762b109db4ad1d17b70c171f3", "size": 7957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/bgl_driving_dist.hpp", "max_stars_repo_name": "BeichuanH/fmm", "max_stars_repo_head_hexsha": "8564a0e8c2dc03a7bca70d0b69a70b5c06340508", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T20:52:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T20:52:13.000Z", "max_issues_repo_path": "src/bgl_driving_dist.hpp", "max_issues_repo_name": "BeichuanH/fmm", "max_issues_repo_head_hexsha": "8564a0e8c2dc03a7bca70d0b69a70b5c06340508", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bgl_driving_dist.hpp", "max_forks_repo_name": "BeichuanH/fmm", "max_forks_repo_head_hexsha": "8564a0e8c2dc03a7bca70d0b69a70b5c06340508", "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.0108108108, "max_line_length": 137, "alphanum_fraction": 0.6839261028, "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03410042399448254, "lm_q1q2_score": 0.01705021199724127}}
{"text": "#include <cvecmat.h>\n#include <ccp4_spg.h>\n#include <csymlib.h>\n#include <scitbx/math/utils.h>\n#include <cctbx/miller/asu.h>\n#include <iotbx/mtz/batch.h>\n#include <iotbx/mtz/column.h>\n#include <iotbx/error.h>\n#include <boost/scoped_array.hpp>\n#include <boost/optional.hpp>\n\nnamespace iotbx { namespace mtz {\n\n  af::shared<std::size_t>\n  cmtz_struct_sizes()\n  {\n    af::shared<std::size_t> result;\n    result.push_back(sizeof(CMtz::MTZCOL));\n    result.push_back(sizeof(CMtz::MTZSET));\n    result.push_back(sizeof(CMtz::MTZXTAL));\n    result.push_back(sizeof(CMtz::MTZBAT));\n    result.push_back(sizeof(CMtz::SYMGRP));\n    result.push_back(sizeof(CMtz::MTZ));\n    return result;\n  }\n\n  object::object()\n  :\n    ptr_(CMtz::MtzMalloc(0, 0), ptr_deleter)\n  {\n    if (ptr_.get() == 0) throw cctbx::error(\"MtzMalloc failed.\");\n    ptr_->refs_in_memory = true;\n    init_not_a_number_value();\n  }\n\n  object::object(const char* file_name)\n  {\n    IOTBX_ASSERT(file_name != 0);\n    ptr_ = boost::shared_ptr<CMtz::MTZ>(\n      CMtz::MtzGetUserCellTolerance(file_name, true, 0), ptr_deleter);\n    if (ptr_.get() == 0) {\n      throw cctbx::error(std::string(\"MTZ file read error: \") + file_name);\n    }\n    init_not_a_number_value();\n  }\n\n  void\n  object::init_not_a_number_value()\n  {\n    // based on code from MtzAddColumn()\n    if (strncmp(ptr()->mnf.amnf, \"NAN\", 3U) == 0) {\n      not_a_number_value_ = CCP4::ccp4_nan();\n    }\n    else {\n      not_a_number_value_.f = ptr()->mnf.fmnf;\n    }\n  }\n\n  std::string\n  object::title() const\n  {\n    char result[sizeof(ptr()->title)];\n    int title_length = CMtz::ccp4_lrtitl(ptr(), result);\n    return std::string(result, title_length);\n  }\n\n  object&\n  object::set_title(const char* title, bool append)\n  {\n    IOTBX_ASSERT(title != 0);\n    int set_title_success = CMtz::ccp4_lwtitl(ptr(), title, append);\n    IOTBX_ASSERT(set_title_success);\n    return *this;\n  }\n\n  af::shared<std::string>\n  object::history() const\n  {\n    CMtz::MTZ* p = ptr();\n    af::shared<std::string> result((af::reserve(p->histlines)));\n    for(int i=0;i<p->histlines;i++) {\n      const char* line = p->hist+MTZRECORDLENGTH*i;\n      int j = 0;\n      for(;j<MTZRECORDLENGTH;j++) {\n        if (line[j] == '\\0') break;\n      }\n      result.push_back(std::string(line, j));\n    }\n    return result;\n  }\n\n  object&\n  object::add_history(af::const_ref<std::string> const& lines)\n  {\n    boost::shared_ptr<char> buffer(\n      CMtz::MtzCallocHist(lines.size()), CMtz::MtzFreeHist);\n    for(std::size_t i=0;i<lines.size();i++) {\n      strncpy(\n        buffer.get()+i*MTZRECORDLENGTH,\n        lines[i].c_str(),\n        std::min(\n          static_cast<std::size_t>(MTZRECORDLENGTH),\n          lines[i].size()));\n    }\n    int add_history_success = CMtz::MtzAddHistory(\n      ptr(),\n      reinterpret_cast<char (*)[MTZRECORDLENGTH]>(buffer.get()),\n      lines.size());\n    IOTBX_ASSERT(add_history_success);\n    return *this;\n  }\n\n  object&\n  object::add_history(const char* line)\n  {\n    IOTBX_ASSERT(line != 0);\n    return add_history(af::tiny<std::string, 1>(line).const_ref());\n  }\n\n  object&\n  object::set_space_group_name(const char* name)\n  {\n    IOTBX_ASSERT(name != 0);\n    char* target = ptr()->mtzsymm.spcgrpname;\n    const unsigned target_size = sizeof(ptr()->mtzsymm.spcgrpname);\n    strncpy(target, name, target_size-1);\n    target[target_size-1] = '\\0';\n    return *this;\n  }\n\n  object&\n  object::set_point_group_name(const char* name)\n  {\n    IOTBX_ASSERT(name != 0);\n    char* target = ptr()->mtzsymm.pgname;\n    const unsigned target_size = sizeof(ptr()->mtzsymm.pgname);\n    strncpy(target, name, target_size-1);\n    target[target_size-1] = '\\0';\n    return *this;\n  }\n\n  cctbx::sgtbx::space_group\n  object::space_group() const\n  {\n    CMtz::MTZ* p = ptr();\n    cctbx::sgtbx::space_group result;\n    scitbx::mat3<double> rm;\n    scitbx::vec3<double> tv;\n    for(int im=0;im<p->mtzsymm.nsym;im++) {\n      for (int ir=0;ir<3;ir++) {\n        for (int ic=0;ic<3;ic++) {\n          rm(ir,ic) = p->mtzsymm.sym[im][ir][ic];\n        }\n        tv[ir] = p->mtzsymm.sym[im][ir][3];\n      }\n      result.expand_smx(cctbx::sgtbx::rt_mx(rm, tv));\n    }\n    return result;\n  }\n\n  object&\n  object::set_space_group(cctbx::sgtbx::space_group const& space_group)\n  {\n    CMtz::MTZ* p = ptr();\n    IOTBX_ASSERT(sizeof(p->mtzsymm.sym) / sizeof(*p->mtzsymm.sym)\n              >= space_group.order_z());\n    p->mtzsymm.nsymp = static_cast<int>(space_group.order_p());\n    p->mtzsymm.nsym = static_cast<int>(space_group.order_z());\n    for (int im=0;im<p->mtzsymm.nsym;im++) {\n      cctbx::sgtbx::rt_mx sm = space_group(im).mod_positive();\n      cctbx::sgtbx::rot_mx rm = sm.r();\n      cctbx::sgtbx::tr_vec tv = sm.t();\n      scitbx::mat3<int> rm_num = rm.num();\n      float rm_den = rm.den();\n      scitbx::vec3<int> tv_num = tv.num();\n      float tv_den = tv.den();\n      for (int ir=0;ir<3;ir++) {\n        for (int ic=0;ic<3;ic++) {\n          p->mtzsymm.sym[im][ir][ic] = rm_num(ir,ic)/rm_den;\n        }\n        p->mtzsymm.sym[im][ir][3] = tv_num[ir]/tv_den;\n      }\n      for (int ic=0;ic<3;ic++) {\n        p->mtzsymm.sym[im][3][ic] = 0.;\n      }\n      p->mtzsymm.sym[im][3][3] = 1.;\n    }\n    return *this;\n  }\n\n  void\n  object::reserve(int capacity)\n  {\n    CMtz::MTZ* p = ptr();\n    if (!p->refs_in_memory) return;\n    for(int i=0;i<p->nxtal;i++) {\n      for(int j=0;j<p->xtal[i]->nset;j++) {\n        for(int k=0;k<p->xtal[i]->set[j]->ncol;k++) {\n          capacity = std::max(\n            capacity,\n            column_array_capacity(p->xtal[i]->set[j]->col[k]));\n        }\n      }\n    }\n    for(int i=0;i<p->nxtal;i++) {\n      for(int j=0;j<p->xtal[i]->nset;j++) {\n        for(int k=0;k<p->xtal[i]->set[j]->ncol;k++) {\n          ccp4array_reserve(p->xtal[i]->set[j]->col[k]->ref, capacity);\n        }\n      }\n    }\n  }\n\n  void\n  object::adjust_column_array_sizes(int new_nref)\n  {\n    CMtz::MTZ* p = ptr();\n    if (!p->refs_in_memory) return;\n    if (new_nref > p->nref) {\n      reserve(new_nref);\n      for(int i=0;i<p->nxtal;i++) {\n        for(int j=0;j<p->xtal[i]->nset;j++) {\n          for(int k=0;k<p->xtal[i]->set[j]->ncol;k++) {\n            CMtz::MTZCOL* col_k = p->xtal[i]->set[j]->col[k];\n            int old_size = column_array_size(col_k);\n            if (new_nref > old_size) {\n              ccp4array_resize(col_k->ref, new_nref);\n              for(int iref=old_size;iref<new_nref;iref++) {\n                *(reinterpret_cast<union float_uint_uchar*>(\n                  &col_k->ref[iref])) = not_a_number_value_;\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  af::shared<batch>\n  object::batches() const\n  {\n    af::shared<batch> result((af::reserve(n_batches())));\n    for(int i_batch=0;i_batch<n_batches();i_batch++) {\n      result.push_back(batch(*this, i_batch));\n    }\n    return result;\n  }\n\n  batch\n  object::add_batch()\n  {\n    CMtz::MTZBAT* p = ptr()->batch;\n    CMtz::MTZBAT* p_tail = p;\n    int max_batch_number = 0;\n    int i_batch = 0;\n    for(;;i_batch++) {\n      if (p == 0) break;\n      max_batch_number = std::max(max_batch_number, p->num);\n      p_tail = p;\n      p = p->next;\n    }\n    boost::scoped_array<float> buf(new float[NBATCHINTEGERS+NBATCHREALS]);\n    std::fill_n(buf.get(), NBATCHINTEGERS+NBATCHREALS, static_cast<float>(0));\n#if defined(__DECCXX_VER)\n    BOOST_STATIC_ASSERT(sizeof(float) == sizeof(int));\n#else\n    IOTBX_ASSERT(sizeof(float) == sizeof(int));\n#endif\n    IOTBX_ASSERT(CMtz::ccp4_lwbat(\n      ptr(), 0, max_batch_number+1, buf.get(), \"\") == 1);\n    p = (p_tail == 0 ? ptr()->batch : p_tail->next);\n    IOTBX_ASSERT(p != 0);\n    IOTBX_ASSERT(p->next == 0);\n    IOTBX_ASSERT(p->num == max_batch_number+1);\n    return batch(*this, i_batch);\n  }\n\n  af::shared<crystal>\n  object::crystals() const\n  {\n    af::shared<crystal> result((af::reserve(n_crystals())));\n    for(int i_crystal=0;i_crystal<n_crystals();i_crystal++) {\n      result.push_back(crystal(*this, i_crystal));\n    }\n    return result;\n  }\n\n  crystal\n  object::add_crystal(\n    const char* name,\n    const char* project_name,\n    af::double6 const& unit_cell_parameters)\n  {\n    IOTBX_ASSERT(name != 0);\n    IOTBX_ASSERT(project_name != 0);\n    float uc_params[6];\n    for(int i=0;i<6;i++) uc_params[i] = unit_cell_parameters[i];\n    int i_crystal = n_crystals();\n    CMtz::MTZXTAL* crystal_ptr = CMtz::MtzAddXtal(\n      ptr(), name, project_name, uc_params);\n    IOTBX_ASSERT(crystal_ptr != 0);\n    IOTBX_ASSERT(n_crystals() == i_crystal+1);\n    crystal result(*this, i_crystal);\n    IOTBX_ASSERT(result.ptr() == crystal_ptr);\n    return result;\n  }\n\n  crystal\n  object::add_crystal(\n    const char* name,\n    const char* project_name,\n    cctbx::uctbx::unit_cell const& unit_cell)\n  {\n    return add_crystal(name, project_name, unit_cell.parameters());\n  }\n\n  bool\n  object::has_crystal(const char* name) const\n  {\n    IOTBX_ASSERT(name != 0);\n    for(int i_crystal=0;i_crystal<n_crystals();i_crystal++) {\n      crystal x(*this, i_crystal);\n      if (std::strcmp(x.name(), name) == 0) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  bool\n  object::has_column(const char* label) const\n  {\n    IOTBX_ASSERT(label != 0);\n    for(int i_crystal=0;i_crystal<n_crystals();i_crystal++) {\n      crystal x(*this, i_crystal);\n      for(int i_dataset=0;i_dataset<x.n_datasets();i_dataset++) {\n        dataset s(x, i_dataset);\n        for(int i_column=0;i_column<s.n_columns();i_column++) {\n          column c(s, i_column);\n          if (CMtz::MtzPathMatch(label, c.label())) {\n            return true;\n          }\n        }\n      }\n    }\n    return false;\n  }\n\n  column\n  object::get_column(const char* label) const\n  {\n    IOTBX_ASSERT(label != 0);\n    for(int i_crystal=0;i_crystal<n_crystals();i_crystal++) {\n      crystal x(*this, i_crystal);\n      for(int i_dataset=0;i_dataset<x.n_datasets();i_dataset++) {\n        dataset s(x, i_dataset);\n        for(int i_column=0;i_column<s.n_columns();i_column++) {\n          column c(s, i_column);\n          if (CMtz::MtzPathMatch(label, c.label())) {\n            return c;\n          }\n        }\n      }\n    }\n    throw cctbx::error(std::string(\"Unknown MTZ column label: \") + label);\n  }\n\n  hkl_columns\n  object::get_hkl_columns() const\n  {\n    return hkl_columns(\n      get_column(\"H\"),\n      get_column(\"K\"),\n      get_column(\"L\"));\n  }\n\n  af::double2\n  object::max_min_resolution() const\n  {\n    double d_star_sq_min = -1;\n    double d_star_sq_max = -1;\n    int n_refl = n_reflections();\n    int n_crys = n_crystals();\n    if (n_refl > 0 && n_crys > 0) {\n      hkl_columns hkl = get_hkl_columns();\n      std::vector<cctbx::uctbx::unit_cell> unit_cells;\n      for(int i_crystal=0;i_crystal<n_crys;i_crystal++) {\n        unit_cells.push_back(crystal(*this, i_crystal).unit_cell());\n      }\n      for(int i_refl=0;i_refl<n_refl;i_refl++) {\n        for(int i_crystal=0;i_crystal<n_crys;i_crystal++) {\n          double d_star_sq = unit_cells[i_crystal].d_star_sq(\n            hkl.get_miller_index(i_refl));\n          if (d_star_sq_min > d_star_sq || d_star_sq_min < 0) {\n              d_star_sq_min = d_star_sq;\n          }\n          if (d_star_sq_max < d_star_sq) {\n              d_star_sq_max = d_star_sq;\n          }\n        }\n      }\n    }\n    return af::double2(\n      d_star_sq_min <= 0 ? -1 : 1/std::sqrt(d_star_sq_min),\n      d_star_sq_max <= 0 ? -1 : 1/std::sqrt(d_star_sq_max));\n  }\n\n  namespace {\n    inline\n    std::complex<double>\n    polar_deg(double ampl, double phi)\n    {\n      return ampl * scitbx::math::unit_complex(phi*scitbx::constants::pi_180);\n    }\n  }\n\n  af::shared<cctbx::miller::index<> >\n  object::extract_miller_indices() const\n  {\n    int n_refl = n_reflections();\n    af::shared<cctbx::miller::index<> > result((af::reserve(n_refl)));\n    hkl_columns hkl = get_hkl_columns();\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      result.push_back(hkl.get_miller_index(i_refl));\n    }\n    return result;\n  }\n\n  void\n  object::replace_miller_indices(\n    af::const_ref<cctbx::miller::index<> > const& miller_indices)\n  {\n    IOTBX_ASSERT(miller_indices.size() == n_reflections());\n    hkl_columns hkl = get_hkl_columns();\n    for(int i_refl=0;i_refl<miller_indices.size();i_refl++) {\n      hkl.replace_miller_index(i_refl, miller_indices[i_refl]);\n    }\n  }\n\n  CSym::ccp4_symop Qmat4_to_rotandtrn(const float rsm[4][4]) {\n\n    int i,j;\n    CSym::ccp4_symop symop;\n\n    for (i = 0; i < 3; ++i) {\n      for (j = 0; j < 3; ++j)\n        symop.rot[i][j]=rsm[i][j];\n      symop.trn[i]=rsm[i][3];\n    }\n\n    return (symop);\n  }\n\n  void Qrotandtrn_to_mat4(float rsm[4][4], const CSym::ccp4_symop symop) {\n\n    int i,j;\n\n    for (i = 0; i < 3; ++i) {\n      for (j = 0; j < 3; ++j)\n        rsm[i][j]=symop.rot[i][j];\n      rsm[i][3]=symop.trn[i];\n      rsm[3][i]=0.0;\n    }\n    rsm[3][3]=1.0;\n  }\n\n  //copied from csymlib.c to avoid windows compilation error, unresolved symbol ccp4printf\n  CSym::ccp4_symop ccp4_symop_invert_( const CSym::ccp4_symop op1 )\n  {\n    float rot1[4][4],rot2[4][4];\n\n    Qrotandtrn_to_mat4(rot1,op1);\n    invert4matrix((const float (*)[4])rot1,rot2);\n    return (Qmat4_to_rotandtrn((const float (*)[4])rot2));\n  }\n\n  int\n  iround(float x) { return scitbx::math::float_int_conversions<float,int>::iround(x); }\n\n  af::shared<cctbx::miller::index<> >\n  object::extract_original_index_miller_indices(\n    const char* column_label_m_isym) const\n  {\n    integer_group m_isym( extract_integers(column_label_m_isym) );\n    int n_refl = n_reflections();\n    af::shared<cctbx::miller::index<> > result;\n    // Use of the CCP4 library suggested by David Waterman;\n    // code example documented at ftp://ftp.ccp4.ac.uk/mdw/csym/cmtz_csym_eg.c\n\n    CMtz::MTZ* p = ptr();\n    using CSym::ccp4_symop;\n\n    scitbx::af::shared<ccp4_symop> op1(p->mtzsymm.nsym);\n    for(int i = 0 ; i < p->mtzsymm.nsym; ++i) {\n      for (int k = 0; k < 3; ++k) {\n        for (int l=0; l<3; ++l) {\n          op1[i].rot[k][l] = p->mtzsymm.sym[i][k][l];\n        }\n        op1[i].trn[k] = p->mtzsymm.sym[i][k][3];\n      }\n    }\n\n    scitbx::af::shared<ccp4_symop> invsymop(p->mtzsymm.nsym);\n    for(int i = 0 ; i < p->mtzsymm.nsym; ++i) {\n      invsymop[i] = ccp4_symop_invert_(op1[i]);\n    }\n\n    for (int i_refl=0; i_refl<n_refl; ++i_refl){\n      // Take the CCP4 definition M/ISYM = 256M+ISYM, where M=0 (full) or M=1 (partial).\n      // Therefore we discard the partiality flag M, just getting ISYM.\n      int isym_value = m_isym.data[i_refl] % 256;\n      int jsym = (isym_value - 1) / 2;\n      int isign = (isym_value % 2) ? 1 : -1 ;\n\n      cctbx::miller::index<> asu_hkl = m_isym.indices[i_refl];\n\n      //algorithm borrowed from CSym::ccp4spg_generate_indices(...)\n      result.push_back(cctbx::miller::index<>(\n         isign *     iround(asu_hkl[0]*invsymop[jsym].rot[0][0] +\n                            asu_hkl[1]*invsymop[jsym].rot[1][0] +\n                            asu_hkl[2]*invsymop[jsym].rot[2][0]),\n         isign *     iround(asu_hkl[0]*invsymop[jsym].rot[0][1] +\n                            asu_hkl[1]*invsymop[jsym].rot[1][1] +\n                            asu_hkl[2]*invsymop[jsym].rot[2][1]),\n         isign *     iround(asu_hkl[0]*invsymop[jsym].rot[0][2] +\n                            asu_hkl[1]*invsymop[jsym].rot[1][2] +\n                            asu_hkl[2]*invsymop[jsym].rot[2][2])\n\n      ));\n    }\n    return result;\n  }\n\n  void\n  object::replace_original_index_miller_indices(\n    af::const_ref<cctbx::miller::index<> > const &indices,\n    const char* column_label_m_isym)\n  {\n    column m_isym(get_column(column_label_m_isym));\n    hkl_columns hkl = get_hkl_columns();\n    int n_refl = n_reflections();\n\n    CMtz::MTZ* p = ptr();\n\n    // no_expand = true, since we need the symmetry operators in the same\n    // order as in the mtz file\n    cctbx::sgtbx::space_group sg(true /* no_expand */);\n    scitbx::mat3<double> rm;\n    scitbx::vec3<double> tv;\n    for(int im=0;im<p->mtzsymm.nsym;im++) {\n      for (int ir=0;ir<3;ir++) {\n        for (int ic=0;ic<3;ic++) {\n          rm(ir,ic) = p->mtzsymm.sym[im][ir][ic];\n        }\n        tv[ir] = p->mtzsymm.sym[im][ir][3];\n      }\n      sg.expand_smx(cctbx::sgtbx::rt_mx(rm, tv));\n    }\n\n    cctbx::sgtbx::reciprocal_space::asu asu(sg.type());\n\n    // http://www.ccp4.ac.uk/html/mtzformat.html#storage\n    // Column contains a combination of the partiality flag M and the symmetry\n    // number ISYM: 256M+ISYM. M is 0 for fully recorded reflections or 1 for\n    // partials. ISYM = 2*isymop - 1 for reflections placed in the positive\n    // asu, i.e. I+ of a Friedel pair, and ISYM = 2*isymop for reflections\n    // placed in the negative asu, i.e. I- of a Friedel pair. Here \"isymop\"\n    // is the number of the symmetry operator used.\n\n    // also see cctbx/miller/asu.cpp:\n    //   asym_index::asym_index()\n    for (int i_refl=0; i_refl<n_refl; ++i_refl){\n      int m_value = m_isym.int_datum(i_refl) / 256;\n      int isym = 0;\n      cctbx::miller::index<> h = indices[i_refl];\n      cctbx::miller::index<> hr_;\n      //int  ht_;\n      for(std::size_t i_smx=0;i_smx<sg.n_smx();i_smx++) {\n        cctbx::sgtbx::rt_mx s = sg(0, 0, i_smx);\n        hr_ = h * s.r();\n        if (asu.is_inside(hr_)) {\n          //ht_ = cctbx::sgtbx::ht_mod_1(h, s.t());\n          isym = (i_smx + 1) * 2 - 1;\n          break;\n        }\n        else if (asu.is_inside(-hr_)) {\n          hr_ = -hr_;\n          //ht_ = cctbx::sgtbx::ht_mod_1(h, s.t());\n          isym = (i_smx + 1) * 2;\n          break;\n        }\n      }\n      hkl.replace_miller_index(i_refl, hr_);\n      m_isym.float_datum(i_refl) = static_cast<float>(m_value + isym);\n    }\n  }\n\n  integer_group\n  object::extract_integers(\n    const char* column_label) const\n  {\n    int n_refl = n_reflections();\n    integer_group result(false, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data(get_column(column_label));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      if (!data.is_ccp4_nan(i_refl)) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(data.int_datum(i_refl));\n      }\n    }\n    return result;\n  }\n\n  af::shared<int>\n  object::extract_integers(\n    af::const_ref<int> const& mtz_reflection_indices,\n    const char* column_label) const\n  {\n    int n_refl = n_reflections();\n    af::shared<int> result((af::reserve(mtz_reflection_indices.size())));\n    column data(get_column(column_label));\n    for(int i=0;i<mtz_reflection_indices.size();i++) {\n      int i_refl = mtz_reflection_indices[i];\n      IOTBX_ASSERT(i_refl >= 0 && i_refl < n_refl);\n      IOTBX_ASSERT(!data.is_ccp4_nan(i_refl));\n      result.push_back(data.int_datum(i_refl));\n    }\n    return result;\n  }\n\n  integer_group\n  object::extract_integers_anomalous(\n    const char* column_label_plus,\n    const char* column_label_minus) const\n  {\n    int n_refl = n_reflections();\n    integer_group result(true, 2*n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data_plus(get_column(column_label_plus));\n    column data_minus(get_column(column_label_minus));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      if (!data_plus.is_ccp4_nan(i_refl)) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(data_plus.int_datum(i_refl));\n      }\n      if (!data_minus.is_ccp4_nan(i_refl)) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(-hkl.get_miller_index(i_refl));\n        result.data.push_back(data_minus.int_datum(i_refl));\n      }\n    }\n    return result;\n  }\n\n  real_group\n  object::extract_reals(\n    const char* column_label) const\n  {\n    int n_refl = n_reflections();\n    real_group result(false, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data(get_column(column_label));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      if (!data.is_ccp4_nan(i_refl)) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(data.float_datum(i_refl));\n      }\n    }\n    return result;\n  }\n\n  af::shared<double>\n  object::extract_reals(\n    af::const_ref<int> const& mtz_reflection_indices,\n    const char* column_label) const\n  {\n    int n_refl = n_reflections();\n    af::shared<double> result((af::reserve(mtz_reflection_indices.size())));\n    column data(get_column(column_label));\n    for(int i=0;i<mtz_reflection_indices.size();i++) {\n      int i_refl = mtz_reflection_indices[i];\n      IOTBX_ASSERT(i_refl >= 0 && i_refl < n_refl);\n      IOTBX_ASSERT(!data.is_ccp4_nan(i_refl));\n      result.push_back(data.float_datum(i_refl));\n    }\n    return result;\n  }\n\n  real_group\n  object::extract_reals_anomalous(\n    const char* column_label_plus,\n    const char* column_label_minus) const\n  {\n    int n_refl = n_reflections();\n    real_group result(true, 2*n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data_plus(get_column(column_label_plus));\n    column data_minus(get_column(column_label_minus));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      if (!data_plus.is_ccp4_nan(i_refl)) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(data_plus.float_datum(i_refl));\n      }\n      if (!data_minus.is_ccp4_nan(i_refl)) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(-hkl.get_miller_index(i_refl));\n        result.data.push_back(data_minus.float_datum(i_refl));\n      }\n    }\n    return result;\n  }\n\n  namespace {\n\n    struct nan_and_non_zero_counts\n    {\n      nan_and_non_zero_counts();\n\n      template <std::size_t N>\n      nan_and_non_zero_counts(\n        af::tiny<column, N> const& columns,\n        int i_refl)\n      {\n        compute(columns, i_refl);\n      }\n\n      nan_and_non_zero_counts(\n        column const& column_0,\n        column const& column_1,\n        int i_refl)\n      {\n        compute(af::tiny<column, 2>(column_0, column_1), i_refl);\n      }\n\n      template <std::size_t N>\n      void\n      compute(\n        af::tiny<column, N> const& columns,\n        int i_refl)\n      {\n        n_nan = 0;\n        n_non_zero = 0;\n        for(unsigned i=0;i<N;i++) {\n          if      (columns[i].is_ccp4_nan(i_refl)) n_nan++;\n          else if (columns[i].float_datum(i_refl)) n_non_zero++;\n        }\n      }\n\n      bool\n      are_consistent() const { return (n_nan == 0 || n_non_zero == 0); }\n\n      unsigned n_nan;\n      unsigned n_non_zero;\n    };\n\n    struct observation_pair_evaluator\n    {\n      observation_pair_evaluator() {}\n\n      observation_pair_evaluator(\n        column const& data,\n        column const& sigmas,\n        int i_refl)\n      :\n        datum(0),\n        sigma(0),\n        is_consistent(true),\n        is_usable(true)\n      {\n        if (data.is_ccp4_nan(i_refl)) {\n          is_usable = false;\n          if (!sigmas.is_ccp4_nan(i_refl)) {\n            sigma = sigmas.float_datum(i_refl);\n            if (sigma != 0 && sigma != 1) {\n              is_consistent = false;\n            }\n          }\n        }\n        else {\n          datum = data.float_datum(i_refl);\n          if (!sigmas.is_ccp4_nan(i_refl)) {\n            sigma = sigmas.float_datum(i_refl);\n            if (sigma == 0 && (datum == 0 || datum == 1)) {\n              is_usable = false;\n            }\n          }\n          else {\n            is_usable = false;\n            if (datum != 0 && datum != 1) {\n              is_consistent = false;\n            }\n          }\n        }\n      }\n\n      double datum;\n      double sigma;\n      bool is_consistent;\n      bool is_usable;\n    };\n\n    static const char* phenix_mtz_dump_tip =\n      \" [tip: \\\"phenix.mtz.dump --show_column_data file_name\\\"\"\n      \" is available for inspecting the MTZ file]\";\n  }\n\n  hl_group\n  object::extract_hendrickson_lattman(\n    const char* column_label_a,\n    const char* column_label_b,\n    const char* column_label_c,\n    const char* column_label_d) const\n  {\n    int n_refl = n_reflections();\n    hl_group result(false, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    af::tiny<column, 4> data(\n      get_column(column_label_a),\n      get_column(column_label_b),\n      get_column(column_label_c),\n      get_column(column_label_d));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      nan_and_non_zero_counts counts(data, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting Hendrickson-Lattman array\"\n          \" from columns: \")\n          + column_label_a + \", \"\n          + column_label_b + \", \"\n          + column_label_c + \", \"\n          + column_label_d + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(cctbx::hendrickson_lattman<>(\n          data[0].float_datum(i_refl),\n          data[1].float_datum(i_refl),\n          data[2].float_datum(i_refl),\n          data[3].float_datum(i_refl)));\n      }\n    }\n    return result;\n  }\n\n  hl_group\n  object::extract_hendrickson_lattman_ab_only(\n    const char* column_label_a,\n    const char* column_label_b) const\n  {\n    int n_refl = n_reflections();\n    hl_group result(false, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    af::tiny<column, 2> data(\n      get_column(column_label_a),\n      get_column(column_label_b));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      nan_and_non_zero_counts counts(data, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting Hendrickson-Lattman array\"\n          \" from columns: \")\n          + column_label_a + \", \"\n          + column_label_b + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(cctbx::hendrickson_lattman<>(\n          data[0].float_datum(i_refl),\n          data[1].float_datum(i_refl),\n          0., 0.));\n      }\n    }\n    return result;\n  }\n\n  hl_group\n  object::extract_hendrickson_lattman_anomalous(\n    const char* column_label_a_plus,\n    const char* column_label_b_plus,\n    const char* column_label_c_plus,\n    const char* column_label_d_plus,\n    const char* column_label_a_minus,\n    const char* column_label_b_minus,\n    const char* column_label_c_minus,\n    const char* column_label_d_minus) const\n  {\n    int n_refl = n_reflections();\n    hl_group result(true, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    af::tiny<column, 4> data_p(\n      get_column(column_label_a_plus),\n      get_column(column_label_b_plus),\n      get_column(column_label_c_plus),\n      get_column(column_label_d_plus));\n    af::tiny<column, 4> data_m(\n      get_column(column_label_a_minus),\n      get_column(column_label_b_minus),\n      get_column(column_label_c_minus),\n      get_column(column_label_d_minus));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      nan_and_non_zero_counts counts(data_p, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting Hendrickson-Lattman array\"\n          \" from columns: \")\n          + column_label_a_plus + \", \"\n          + column_label_b_plus + \", \"\n          + column_label_c_plus + \", \"\n          + column_label_d_plus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(cctbx::hendrickson_lattman<>(\n          data_p[0].float_datum(i_refl),\n          data_p[1].float_datum(i_refl),\n          data_p[2].float_datum(i_refl),\n          data_p[3].float_datum(i_refl)));\n      }\n      counts = nan_and_non_zero_counts(data_m, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting Hendrickson-Lattman array\"\n          \" from columns: \")\n          + column_label_a_minus + \", \"\n          + column_label_b_minus + \", \"\n          + column_label_c_minus + \", \"\n          + column_label_d_minus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(-hkl.get_miller_index(i_refl));\n        result.data.push_back(cctbx::hendrickson_lattman<>(\n          data_m[0].float_datum(i_refl),\n          data_m[1].float_datum(i_refl),\n          data_m[2].float_datum(i_refl),\n          data_m[3].float_datum(i_refl)));\n      }\n    }\n    return result;\n  }\n\n  hl_group\n  object::extract_hendrickson_lattman_anomalous_ab_only(\n    const char* column_label_a_plus,\n    const char* column_label_b_plus,\n    const char* column_label_a_minus,\n    const char* column_label_b_minus) const\n  {\n    int n_refl = n_reflections();\n    hl_group result(true, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    af::tiny<column, 2> data_p(\n      get_column(column_label_a_plus),\n      get_column(column_label_b_plus));\n    af::tiny<column, 2> data_m(\n      get_column(column_label_a_minus),\n      get_column(column_label_b_minus));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      nan_and_non_zero_counts counts(data_p, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting Hendrickson-Lattman array\"\n          \" from columns: \")\n          + column_label_a_plus + \", \"\n          + column_label_b_plus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(cctbx::hendrickson_lattman<>(\n          data_p[0].float_datum(i_refl),\n          data_p[1].float_datum(i_refl),\n          0., 0.));\n      }\n      counts = nan_and_non_zero_counts(data_m, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting Hendrickson-Lattman array\"\n          \" from columns: \")\n          + column_label_a_minus + \", \"\n          + column_label_b_minus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(-hkl.get_miller_index(i_refl));\n        result.data.push_back(cctbx::hendrickson_lattman<>(\n          data_m[0].float_datum(i_refl),\n          data_m[1].float_datum(i_refl),\n          0., 0.));\n      }\n    }\n    return result;\n  }\n\n  observations_group\n  object::extract_observations(\n    const char* column_label_data,\n    const char* column_label_sigmas) const\n  {\n    int n_refl = n_reflections();\n    observations_group result(false, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data(get_column(column_label_data));\n    column sigmas(get_column(column_label_sigmas));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      observation_pair_evaluator pair_evaluation(data, sigmas, i_refl);\n      if (!pair_evaluation.is_consistent) {\n        throw cctbx::error(std::string(\n          \"Inconsistent observation/sigma pair in columns: \")\n          + column_label_data + \", \" + column_label_sigmas + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (pair_evaluation.is_usable) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(pair_evaluation.datum);\n        result.sigmas.push_back(pair_evaluation.sigma);\n      }\n    }\n    return result;\n  }\n\n  observations_group\n  object::extract_observations_anomalous(\n    const char* column_label_data_plus,\n    const char* column_label_sigmas_plus,\n    const char* column_label_data_minus,\n    const char* column_label_sigmas_minus) const\n  {\n    int n_refl = n_reflections();\n    observations_group result(true, 2*n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data_plus(get_column(column_label_data_plus));\n    column sigmas_plus(get_column(column_label_sigmas_plus));\n    column data_minus(get_column(column_label_data_minus));\n    column sigmas_minus(get_column(column_label_sigmas_minus));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      observation_pair_evaluator\n        pair_evaluation(data_plus, sigmas_plus, i_refl);\n      if (!pair_evaluation.is_consistent) {\n        throw cctbx::error(std::string(\n          \"Inconsistent observation/sigma pair in columns: \")\n          + column_label_data_plus + \", \" + column_label_sigmas_plus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (pair_evaluation.is_usable) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(pair_evaluation.datum);\n        result.sigmas.push_back(pair_evaluation.sigma);\n      }\n      pair_evaluation = observation_pair_evaluator(\n        data_minus, sigmas_minus, i_refl);\n      if (!pair_evaluation.is_consistent) {\n        throw cctbx::error(std::string(\n          \"Inconsistent observation/sigma pair in columns: \")\n          + column_label_data_minus + \", \" + column_label_sigmas_minus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (pair_evaluation.is_usable) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(-hkl.get_miller_index(i_refl));\n        result.data.push_back(pair_evaluation.datum);\n        result.sigmas.push_back(pair_evaluation.sigma);\n      }\n    }\n    return result;\n  }\n\n  observations_group\n  object::extract_delta_anomalous(\n    const char* column_label_f_data,\n    const char* column_label_f_sigmas,\n    const char* column_label_d_data,\n    const char* column_label_d_sigmas,\n    const char* column_label_isym,\n    bool skip_incompatible_values=false) const\n  {\n    int n_refl = n_reflections();\n    observations_group result(true, 2*n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column f_data(get_column(column_label_f_data));\n    column f_sigmas(get_column(column_label_f_sigmas));\n    column d_data(get_column(column_label_d_data));\n    column d_sigmas(get_column(column_label_d_sigmas));\n    boost::optional<column> isym;\n    if (column_label_isym != 0) {\n      isym = get_column(column_label_isym);\n    }\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      cctbx::miller::index<> const& h = hkl.get_miller_index(i_refl);\n      observation_pair_evaluator\n        pair_evaluation_f(f_data, f_sigmas, i_refl);\n      if (!pair_evaluation_f.is_consistent) {\n        if (skip_incompatible_values) {\n          continue;\n        } else {\n          throw cctbx::error(std::string(\n            \"Inconsistent observation/sigma pair in columns: \")\n            + column_label_f_data + \", \" + column_label_f_sigmas + \", \"\n            + \"hkl=\" + h.as_string()\n            + phenix_mtz_dump_tip);\n        }\n      }\n      observation_pair_evaluator\n        pair_evaluation_d(d_data, d_sigmas, i_refl);\n      if (!pair_evaluation_d.is_consistent) {\n        if (skip_incompatible_values) {\n          continue;\n        } else {\n          throw cctbx::error(std::string(\n            \"Inconsistent observation/sigma pair in columns: \")\n            + column_label_d_data + \", \" + column_label_d_sigmas + \", \"\n            + \"hkl=\" + h.as_string()\n            + phenix_mtz_dump_tip);\n        }\n      }\n      if (    pair_evaluation_d.is_usable\n          &&  pair_evaluation_d.datum != 0\n          && !pair_evaluation_f.is_usable) {\n        if (skip_incompatible_values) {\n          continue;\n        } else {\n          throw cctbx::error(std::string(\n            \"Invalid combination of values while extracting anomalous array\"\n            \" from columns: \")\n            + column_label_f_data   + \", \"\n            + column_label_f_sigmas + \", \"\n            + column_label_d_data   + \", \"\n            + column_label_d_sigmas + \", \"\n            + \"hkl=\" + h.as_string()\n            + phenix_mtz_dump_tip);\n        }\n      }\n      if (pair_evaluation_f.is_usable) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        if (!pair_evaluation_d.is_usable) {\n          if (   !isym\n              || isym->is_ccp4_nan(i_refl)\n              || isym->int_datum(i_refl) != 2) {\n            result.indices.push_back(h);\n          }\n          else {\n            result.indices.push_back(-h);\n          }\n          result.data.push_back(pair_evaluation_f.datum);\n          result.sigmas.push_back(pair_evaluation_f.sigma);\n        }\n        else {\n          double ddh = pair_evaluation_d.datum * .5;\n          double dsh = pair_evaluation_d.sigma * .5;\n          double s = std::sqrt(\n            pair_evaluation_f.sigma*pair_evaluation_f.sigma + dsh*dsh);\n          result.mtz_reflection_indices.push_back(i_refl);\n          result.indices.push_back(h);\n          result.indices.push_back(-h);\n          result.data.push_back(pair_evaluation_f.datum + ddh);\n          result.data.push_back(pair_evaluation_f.datum - ddh);\n          result.sigmas.push_back(s);\n          result.sigmas.push_back(s);\n        }\n      }\n    }\n    return result;\n  }\n\n  complex_group\n  object::extract_complex(\n    const char* column_label_ampl,\n    const char* column_label_phi) const\n  {\n    int n_refl = n_reflections();\n    complex_group result(false, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data_ampl(get_column(column_label_ampl));\n    column data_phi(get_column(column_label_phi));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      nan_and_non_zero_counts counts(data_ampl, data_phi, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting complex array from columns: \")\n          + column_label_ampl + \", \" + column_label_phi + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(polar_deg(\n          data_ampl.float_datum(i_refl), data_phi.float_datum(i_refl)));\n      }\n    }\n    return result;\n  }\n\n  complex_group\n  object::extract_complex_anomalous(\n    const char* column_label_ampl_plus,\n    const char* column_label_phi_plus,\n    const char* column_label_ampl_minus,\n    const char* column_label_phi_minus) const\n  {\n    int n_refl = n_reflections();\n    complex_group result(true, n_refl);\n    hkl_columns hkl = get_hkl_columns();\n    column data_ampl_plus(get_column(column_label_ampl_plus));\n    column data_phi_plus(get_column(column_label_phi_plus));\n    column data_ampl_minus(get_column(column_label_ampl_minus));\n    column data_phi_minus(get_column(column_label_phi_minus));\n    for(int i_refl=0;i_refl<n_refl;i_refl++) {\n      nan_and_non_zero_counts counts(data_ampl_plus, data_phi_plus, i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting complex array from columns: \")\n          + column_label_ampl_plus + \", \" + column_label_phi_plus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(hkl.get_miller_index(i_refl));\n        result.data.push_back(polar_deg(\n          data_ampl_plus.float_datum(i_refl),\n          data_phi_plus.float_datum(i_refl)));\n      }\n      counts = nan_and_non_zero_counts(data_ampl_minus,data_phi_minus,i_refl);\n      if (!counts.are_consistent()) {\n        throw cctbx::error(std::string(\n          \"Unexpected NAN while extracting complex array from columns: \")\n          + column_label_ampl_minus + \", \" + column_label_phi_minus + \", \"\n          + \"hkl=\" + hkl.get_miller_index(i_refl).as_string()\n          + phenix_mtz_dump_tip);\n      }\n      if (counts.n_nan == 0) {\n        result.mtz_reflection_indices.push_back(i_refl);\n        result.indices.push_back(-hkl.get_miller_index(i_refl));\n        result.data.push_back(polar_deg(\n          data_ampl_minus.float_datum(i_refl),\n          data_phi_minus.float_datum(i_refl)));\n      }\n    }\n    return result;\n  }\n\n  void\n  object::write(const char* file_name)\n  {\n    IOTBX_ASSERT(file_name != 0);\n    if (!CMtz::MtzPut(ptr(), file_name)) {\n      throw cctbx::error(\"MTZ write failed.\");\n    }\n  }\n\n  void\n  object::ptr_deleter(CMtz::MTZ* ptr)\n  {\n    if (ptr != 0) {\n      if (ptr->batch != 0 && ptr->n_orig_bat == 0) {\n        ptr->n_orig_bat = 1; // force MtzFreeBatch\n      }\n      IOTBX_ASSERT(CMtz::MtzFree(ptr));\n    }\n  }\n\n}} // namespace iotbx::mtz\n", "meta": {"hexsha": "203cefef44048ededb151219c7678d7ba4d78b8e", "size": 41562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "iotbx/mtz/object.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": "iotbx/mtz/object.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": "iotbx/mtz/object.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": 32.2435996897, "max_line_length": 90, "alphanum_fraction": 0.6153938694, "num_tokens": 11686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.034100422890163976, "lm_q1q2_score": 0.017050211445081988}}
{"text": "#include <iostream>\n#include <cstring>\n#include <cstdlib>\n#include <cstdio>\n#include <climits>\n#include <fstream>\n#include <sstream>\n#include \"common.hpp\"\n#include \"io.hpp\"\n\n#ifndef NOBOOST\n    #include <boost/property_tree/ptree.hpp>\n    #include <boost/property_tree/ini_parser.hpp>\n#endif\n\nusing namespace std;\n\nvoid ReadICsASCII(string Filename, int N, Particle **P_h, int *FileSnapshotNum, Real *FileTime) {\n    *P_h = new Particle[N];\n    string Line;\n    ifstream InputFile(Filename.c_str());\n    int LineNum;\n\n    int i = 0;\n    if (InputFile.is_open()) {\n        getline(InputFile, Line); // First line is the snapshot number.\n        int Count = sscanf(Line.c_str(), \"%d\", FileSnapshotNum);\n        if (Count != 1) {\n            cerr << \"Problem in input file, line 1.\" << endl;\n            exit(1);\n        }\n        getline(InputFile, Line); // Second line is the expected number of particles.\n        int ExpectedN;\n        Count = sscanf(Line.c_str(), \"%d\", &ExpectedN); // We ignore it actually.\n        if (Count != 1) {\n            cerr << \"Problem in input file, line 2.\" << endl;\n            exit(1);\n        }\n        getline(InputFile, Line);\n        double T0;\n        Count = sscanf(Line.c_str(), \"%lf\", &T0);\n        if (Count != 1) {\n            cerr << \"Problem in input file, line 3.\" << endl;\n            exit(1);\n        }\n        *FileTime = (Real)T0;\n        LineNum = 3;\n        while (getline(InputFile, Line))\n        {\n            double m, x, y, z, vx, vy, vz;\n            int id;\n            Particle p;\n            Count = sscanf(Line.c_str(), \"%d %lf %lf %lf %lf %lf %lf %lf\", &id, &m, &x, &y, &z, &vx, &vy, &vz);\n            if (Count != 8) {\n                cerr << \"Problem in input file, line \" << LineNum + 1 << \".\" << endl;\n                exit(1);\n            }\n            p.ID = id;\n            p.m = (Real)m;\n            p.pos = vec3((Real)x, (Real)y, (Real)z);    // This is to ensure proper casting in the case of single prec.\n            p.vel = vec3((Real)vx, (Real)vy, (Real)vz);\n            p.Status = 0;\n            p.CalculateR2();\n            (*P_h)[i] = p;\n            i++;\n            LineNum++;\n            if (i == N) break;\n        }\n        InputFile.close();\n    } else {\n        cerr << \"Can't open file\" << Filename << \".\" << endl;\n        exit(1);\n    }\n    if (i < N) {\n        cerr << \"Was only able to read \" << i << \" particles while \" << N << \" were requested.\" << endl;\n        exit(1);\n    }\n}\n\nvoid WriteSnapshotASCII(string Prefix, int SnapNumber, Particle *P_h, int N, Real T) {\n    char S[512];\n    sprintf(S, \"%s%04d.dat\", Prefix.c_str(), SnapNumber);\n    ofstream SnapshotFile;\n    SnapshotFile.open(S);\n    sprintf(S, \"%06d\\n\", SnapNumber); SnapshotFile << S;\n    sprintf(S, \"%06d\\n\", N); SnapshotFile << S;\n    sprintf(S, \"%.16E\\n\", T); SnapshotFile << S;\n    for (int i = 0; i < N; i++) {\n        sprintf(S, \"%06d%14.6e%14.6e%14.6e%14.6e%14.6e%14.6e%14.6e\\n\", P_h[i].ID, P_h[i].m, P_h[i].pos.x, P_h[i].pos.y, P_h[i].pos.z, P_h[i].vel.x, P_h[i].vel.y, P_h[i].vel.z); SnapshotFile << S;\n    }\n    SnapshotFile.close();\n}\n\n#define THROW_EXCEPTION(str, stat) {cerr << str << endl; exit((stat));}\nvoid ParseInput(int argc, char *argv[], ParametersStruct *Params) {\n    ParametersStruct P;\n#ifndef NOBOOST\n    if (argc < 2) THROW_EXCEPTION(\"Usage: etics [FILE]...\", 1)\n    ifstream TestFileObject(argv[1]);\n    if (!TestFileObject) THROW_EXCEPTION(\"Problem reading file...\", 1)\n    boost::property_tree::ptree pt;\n    boost::property_tree::ini_parser::read_ini(argv[1], pt); // what if file doesn't exist?\n\n    P.N = pt.get<int>(\"N\", 0);\n    if (P.N <= 0) THROW_EXCEPTION(\"Could not read number of particles (N) from ini file.\", 1)\n\n    P.Tcrit = pt.get<Real>(\"Tcrit\", -1);\n    if (P.Tcrit < 0) THROW_EXCEPTION(\"Could not read finish time (Tcrit) from ini file.\", 1)\n\n    P.dT1 = pt.get<Real>(\"dT1\", 0);\n    if (P.dT1 <= 0) THROW_EXCEPTION(\"Could output time interval (dT1) from ini file.\", 1)\n\n    P.dT2 = pt.get<Real>(\"dT2\", 0);\n    if (P.dT2 <= 0) THROW_EXCEPTION(\"Could snapshot time interval (dT2) from ini file.\", 1)\n\n    P.ConstantStep = pt.get<Real>(\"StepSize\", -1);\n    if (P.ConstantStep < 0) THROW_EXCEPTION(\"Could not read step size (StepSize) from ini file.\", 1)\n\n    P.Filename = pt.get<string>(\"Filename\", \"\\n\");\n    if (P.Filename == \"\\n\") THROW_EXCEPTION(\"Could not read initial condition file name (Filename) from ini file.\", 1)\n\n    P.Prefix = pt.get<string>(\"Prefix\", \"\");\n    P.OutputFormat = pt.get<string>(\"OutputFormat\", \"ascii\");\n    P.DeviceID = pt.get<int>(\"device\", -1);\n    if (argc >= 3) { // If there is a argument after the file, it must be either --device or -d\n        int Version1 = strncmp(argv[2], \"--device\", 8);\n        int Version2 = strncmp(argv[2], \"-d\", 2);\n        if ((Version1!=0) && (Version2!=0)) THROW_EXCEPTION(\"Commandline argument after input file must be device number.\", 1)\n        char *DeviceIDStr = strchr(argv[2], '=');\n        if (DeviceIDStr!=NULL) DeviceIDStr = DeviceIDStr + 1;\n        else {\n            if (argc <= 3) THROW_EXCEPTION(\"Device number must follow.\", 1)\n            DeviceIDStr = argv[3];\n        }\n        P.DeviceID = atoi(DeviceIDStr);\n        if ((P.DeviceID==0) && (strcmp(DeviceIDStr, \"0\")!=0)) THROW_EXCEPTION(\"Error understanding device number.\", 1)\n    }\n#else\n    // If no BOOST, we include a file with the parameters and compile it.\n    int N, DeviceID = -1;\n    Real dT1, dT2, Tcrit, StepSize;\n    std::string Filename, Prefix = \"\";\n    #include \"noboost.inc\"\n    P.N = N;\n    P.Filename = Filename;\n    P.dT1 = dT1;\n    P.dT2 = dT2;\n    P.Tcrit = Tcrit;\n    P.ConstantStep = StepSize;\n    P.DeviceID = DeviceID;\n#endif\n    P.Seed = INT_MIN;\n    if ((P.Filename[0]=='_') && (P.Filename.rfind(\"_\") > 0)) {\n        int Break = P.Filename.rfind(\"_\") + 1;\n        string SeedStr = P.Filename.substr(Break, P.Filename.length() - Break);\n        int SeedInt;\n        istringstream iss(SeedStr);\n        iss >> ws >> P.Seed >> ws;\n        if(!iss.eof()) THROW_EXCEPTION(\"Could not understand random seed (in Filename).\", 1)\n        P.Filename = P.Filename.substr(0, Break);\n    }\n    if (P.Seed == INT_MIN) P.Seed = (int)time(NULL);\n    *Params = P;\n}\n\n\n// make safety: if single precision, fail to compile\n#ifdef ETICS_HDF5\n#include \"H5Cpp.h\"\n\nint H5IterNum;\nint *H5IterSnapNumbers;\nstring *H5IterGroupNames;\n\nherr_t file_info(hid_t loc_id, const char *name, void *opdata) {\n    int res = sscanf(name, \"Step#%d\", H5IterSnapNumbers + H5IterNum);\n    if (res != 1) {\n        cerr << \"Problem understanding group \\\"\" << name << \"\\\" in HDF5 file\" << endl;\n        exit(1);\n    }\n    H5IterGroupNames[H5IterNum] = name;\n    H5IterNum++;\n    return 0;\n}\n\n\nvoid ReadICsHDF5(string Filename, int N, Particle **P_h, int *FileSnapshotNum, Real *FileTime) {\n    double *Mass, *X, *Y, *Z, *VX, *VY, *VZ;\n    int *ID;\n    Mass  = new double[N];\n    X  = new double[N];\n    Y  = new double[N];\n    Z  = new double[N];\n    VX = new double[N];\n    VY = new double[N];\n    VZ = new double[N];\n    ID = new int[N];\n\n    H5::H5File file;\n    file = H5::H5File(Filename, H5F_ACC_RDONLY);\n\n    H5::Group group = file.openGroup(\"/\");\n    int NumberOfGroups = group.getNumObjs();\n    H5IterSnapNumbers = new int[NumberOfGroups];\n    H5IterGroupNames = new string[NumberOfGroups];\n    H5IterNum = 0;\n    int ret = file.iterateElems(\"/\", NULL, file_info, NULL);\n    int MaxSnapIndex = 0;\n    for (int i=1; i < NumberOfGroups; i++) MaxSnapIndex = (H5IterSnapNumbers[i]>H5IterSnapNumbers[MaxSnapIndex])?i:MaxSnapIndex;\n    string GroupName = H5IterGroupNames[MaxSnapIndex];\n\n\n    group = file.openGroup(\"/\" + GroupName);\n    H5::Attribute attribute = group.openAttribute(\"Time\");\n    attribute.read(H5::PredType::NATIVE_DOUBLE, FileTime);\n    *FileSnapshotNum = H5IterSnapNumbers[MaxSnapIndex];\n\n    H5::DataSet dataset = file.openDataSet(\"/\" + GroupName + \"/ID\");\n    int NfromFile = dataset.getStorageSize()/sizeof(int);\n    if (NfromFile < N) {\n        cerr << \"Was only able to read \" << NfromFile << \" particles while \" << N << \" were requested.\" << endl;\n        exit(1);\n    }\n    dataset.read(ID, H5::PredType::NATIVE_UINT32);\n\n    dataset = file.openDataSet(\"/\" + GroupName + \"/Mass\");  dataset.read(Mass,  H5::PredType::NATIVE_DOUBLE);\n    dataset = file.openDataSet(\"/\" + GroupName + \"/X\");     dataset.read(X,  H5::PredType::NATIVE_DOUBLE);\n    dataset = file.openDataSet(\"/\" + GroupName + \"/Y\");     dataset.read(Y,  H5::PredType::NATIVE_DOUBLE);\n    dataset = file.openDataSet(\"/\" + GroupName + \"/Z\");     dataset.read(Z,  H5::PredType::NATIVE_DOUBLE);\n    dataset = file.openDataSet(\"/\" + GroupName + \"/VX\");    dataset.read(VX, H5::PredType::NATIVE_DOUBLE);\n    dataset = file.openDataSet(\"/\" + GroupName + \"/VY\");    dataset.read(VY, H5::PredType::NATIVE_DOUBLE);\n    dataset = file.openDataSet(\"/\" + GroupName + \"/VZ\");    dataset.read(VZ, H5::PredType::NATIVE_DOUBLE);\n\n    dataset.close();\n    group.close();\n    file.close();\n\n    *P_h = new Particle[N];\n    for (int i = 0; i < N; i++) {\n        Particle p;\n        p.ID = ID[i];\n        p.m = (Real)Mass[i];\n        p.pos = vec3((Real)X[i], (Real)Y[i], (Real)Z[i]);    // This is to ensure proper casting in the case of single prec.\n        p.vel = vec3((Real)VX[i], (Real)VY[i], (Real)VZ[i]);\n        p.Status = 0;\n        p.CalculateR2();\n        (*P_h)[i] = p;\n    }\n}\n\nbool H5FirstSnapshot = true;\n\nvoid WriteSnapshotHDF5(string Prefix, int SnapNumber, Particle *P_h, int N, Real T) {\n    string Filename = Prefix + \".h5part\";\n\n    H5::H5File file;\n\n    if (H5FirstSnapshot && std::ifstream(Filename.c_str())) {\n        cerr << \"File \\\"\" << Filename << \"\\\" already exist!\" << endl;\n        exit(1);\n    }\n    H5FirstSnapshot = false;\n\n    if (std::ifstream(Filename.c_str())) {\n        file = H5::H5File(Filename, H5F_ACC_RDWR);\n    }\n    else file = H5::H5File(Filename, H5F_ACC_TRUNC);\n\n    char GroupName[64];\n    sprintf(GroupName, \"/Step#%d\", SnapNumber);\n\n    H5::Group group;\n    try {\n        H5::Exception::dontPrint();\n        group = H5::Group(file.createGroup(GroupName));\n    }\n    catch (  H5::FileIException error ) {\n        cerr << \"Couldn't create group \\\"\" << GroupName << \"\\\" in HDF5 file, maybe it already exists?\"  << endl;\n        exit(1);\n    }\n\n    double *Mass, *X, *Y, *Z, *VX, *VY, *VZ, *AX, *AY, *AZ;\n    Mass  = new double[N];\n    X  = new double[N];\n    Y  = new double[N];\n    Z  = new double[N];\n    VX = new double[N];\n    VY = new double[N];\n    VZ = new double[N];\n    AX = new double[N];\n    AY = new double[N];\n    AZ = new double[N];\n    int *ID;\n    ID = new int[N];\n\n    for (int i = 0; i < N; i++) {\n        Particle p = P_h[i];\n        ID[i] = p.ID;\n        Mass[i]  = p.m;\n        X[i]  = p.pos.x;\n        Y[i]  = p.pos.y;\n        Z[i]  = p.pos.z;\n        VX[i] = p.vel.x;\n        VY[i] = p.vel.y;\n        VZ[i] = p.vel.z;\n        AX[i] = p.acc.x;\n        AY[i] = p.acc.y;\n        AZ[i] = p.acc.z;\n    }\n\n    H5::DataSpace attr_dataspace = H5::DataSpace(H5S_SCALAR);\n\n    H5::Attribute attribute = group.createAttribute(\"Time\", H5::PredType::NATIVE_DOUBLE, attr_dataspace);\n    attribute.write( H5::PredType::NATIVE_DOUBLE, &T);\n\n    attribute = group.createAttribute(\"TotalN\", H5::PredType::NATIVE_UINT32, attr_dataspace);\n    attribute.write( H5::PredType::NATIVE_UINT32, &N);\n\n    hsize_t dimsxxx = N;\n    H5::DataSpace dataspacexxx(1, &dimsxxx);\n    H5::DataSet dataset3;\n    dataset3 = H5::DataSet(group.createDataSet(\"ID\", H5::PredType::NATIVE_UINT32, dataspacexxx));\n    dataset3.write(ID, H5::PredType::NATIVE_UINT32);\n    dataset3 = H5::DataSet(group.createDataSet(\"Mass\",  H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(Mass, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"X\",  H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(X, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"Y\",  H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(Y, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"Z\",  H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(Z, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"VX\", H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(VX, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"VY\", H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(VY, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"VZ\", H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(VZ, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"AX\", H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(AX, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"AY\", H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(AY, H5::PredType::NATIVE_DOUBLE);\n    dataset3 = H5::DataSet(group.createDataSet(\"AZ\", H5::PredType::NATIVE_DOUBLE, dataspacexxx));\n    dataset3.write(AZ, H5::PredType::NATIVE_DOUBLE);\n\n    dataset3.close();\n    dataspacexxx.close();\n\n    attr_dataspace.close();\n    attribute.close();\n    group.close();\n    file.close();\n\n    delete [] Mass;\n    delete [] X;\n    delete [] Y;\n    delete [] Z;\n    delete [] VX;\n    delete [] VY;\n    delete [] VZ;\n    delete [] AX;\n    delete [] AY;\n    delete [] AZ;\n    delete [] ID;\n}\n\n#endif\n", "meta": {"hexsha": "89760de846c71cc8033c4331cad92010a3848e7d", "size": 13440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/amuse/community/etics/src/io.cpp", "max_stars_repo_name": "rknop/amuse", "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_issues_repo_path": "src/amuse/community/etics/src/io.cpp", "max_issues_repo_name": "rknop/amuse", "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 690.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_forks_repo_path": "src/amuse/community/etics/src/io.cpp", "max_forks_repo_name": "rieder/amuse", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "avg_line_length": 36.621253406, "max_line_length": 195, "alphanum_fraction": 0.5918154762, "num_tokens": 4052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.0474258688018665, "lm_q1q2_score": 0.0170431568004579}}
{"text": "//==============================================================================\n//         Copyright 2014        LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2014        NumScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_SDK_EXHAUSTIVE_EXHAUSTIVE_HPP_INCLUDED\n#define NT2_SDK_EXHAUSTIVE_EXHAUSTIVE_HPP_INCLUDED\n\n#include <nt2/include/functions/simd/load.hpp>\n#include <nt2/include/functions/simd/extract.hpp>\n#include <nt2/include/functions/simd/successor.hpp>\n#include <nt2/include/functions/simd/splat.hpp>\n#include <nt2/include/functions/scalar/is_invalid.hpp>\n#include <nt2/include/functions/scalar/ulpdist.hpp>\n#include <nt2/include/functions/scalar/iround.hpp>\n#include <nt2/include/functions/scalar/ilog2.hpp>\n#include <nt2/include/functions/scalar/min.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/bitwise_cast.hpp>\n#include <nt2/include/constants/valmin.hpp>\n#include <nt2/include/constants/valmax.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <boost/simd/sdk/meta/cardinal_of.hpp>\n#include <nt2/sdk/meta/type_id.hpp>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cstddef>\n#include \"omp.hpp\"\n\nnamespace nt2\n{\n  /*!\n    @brief Exhaustive precision test for single precision\n\n    Perform a ULP test on every representable single precision value\n    in a given interval. Results are reported using a bucket histogram that\n    gives hint on how many values fall in a given range of ULPs,\n    the smallest and greatest inputs in the chosen range\n    leading to this precision and  the result from this minimum input\n    against the awaited result.\n\n    @par Note:\n    Currently this function is designed to take care of single precision only as\n    running such a test on double precision values take an absurd amount of time.\n\n    @tparam Type          Data type used for computation\n    @param  mini Lower    bound of the test interval\n    @param  maxi Upper    bound of the test interval\n    @param  test_f        Function to test\n    @param  reference_f   Reference function to compare to\n\n    @par Example:\n\n    Here is an example to test SIMD single-precision nt2::log against scalar double-precision std::log.\n\n    @code\n    #include <boost/simd/sdk/simd/native.hpp>\n    #include <nt2/include/functions/log.hpp>\n    #include <nt2/include/constants/zero.hpp>\n    #include <nt2/include/constants/valmax.hpp>\n\n    #include <nt2/sdk/exhaustive/exhaustive.hpp>\n\n    // specific to nt2 tests: specify assert handling\n    #define NT2_ASSERTS_AS_TRAP\n    #include <nt2/sdk/error/assert_as_trap.hpp>\n\n    #include <cmath>\n    #include <cstdlib>\n\n    // function object used for the reference\n    struct std_log\n    {\n      float operator()(float x) const\n      {\n        return float(std::log(double(x)));\n      }\n    };\n\n    int main(int argc, char* argv[])\n    {\n      // define boundaries from command-line arguments,\n      // fallback to default values if not provided\n      float mini = argc >= 2 ? std::atof(argv[1]) : nt2::Zero<float>();\n      float mini = argc >= 3 ? std::atof(argv[2]) : nt2::Valmin<float>();\n\n      // type to call the function object to test with\n      typedef boost::simd::native<float, BOOST_SIMD_DEFAULT_EXTENSION> n_t;\n\n      // run the test\n      nt2::exhaustive_test<n_t>( mini\n                               , maxi\n                               , nt2::functor<nt2::tag::log_>() // function object to test\n                               , std_log()\n                               );\n    }\n    @endcode\n  **/\n  template<typename Type, typename TestF, typename RefF> inline\n  void exhaustive_test(float mini, float maxi, TestF test_f, RefF reference_f)\n  {\n    typedef Type                                                    n_t;\n    typedef typename boost::dispatch::meta::as_integer<Type>::type  in_t;\n\n    static const nt2::uint32_t M = 128;\n    static const nt2::uint32_t N = boost::simd::meta::cardinal_of<n_t>::value;\n    in_t vN = nt2::splat<in_t>(N);\n\n    nt2::uint32_t histo[M+2];\n    float maxin[M+2], minin[M+2], minref[M+2], minval[M+2];\n\n    for(auto& e : histo ) e = 0;\n    for(auto& e : minin ) e = nt2::Valmax<float>();\n    for(auto& e : maxin ) e = nt2::Valmin<float>();\n    for(auto& e : minval) e = nt2::Nan<float>();\n    for(auto& e : minref) e = nt2::Valmax<float>();\n\n    auto t_min = nt2::bitwise_cast<nt2::uint32_t>(nt2::abs(mini));\n    auto t_max = nt2::bitwise_cast<nt2::uint32_t>(nt2::abs(maxi));\n\n    auto diff  = (mini*maxi < 0)  ? std::max(t_max,t_min) + std::min(t_max,t_min)\n                                  : std::max(t_max,t_min) - std::min(t_max,t_min);\n\n    std::cout << \"Exhaustive test for: \" << nt2::type_id(test_f)      << \"\\n\"\n              << \"             versus: \" << nt2::type_id(reference_f) << \"\\n\"\n              << \"             With T: \" << nt2::type_id<Type>()      << \"\\n\"\n              << \"           in range: [\" << mini << \", \" << maxi << \"]\" << \"\\n\"\n              << \"         # of tests: \" << diff << \"\\n\";\n    std::cout << std::endl;\n\n    nt2::uint32_t k = 0;\n\n    #ifdef _OPENMP\n    #pragma omp parallel firstprivate(mini,maxi,diff)\n    #endif\n    {\n      bool  hit_loc[M+2];\n      nt2::uint32_t histo_loc[M+2];\n      float maxin_loc[M+2] , minin_loc[M+2], minref_loc[M+2], minval_loc[M+2];\n\n      for(auto& e : hit_loc   ) e = false;\n      for(auto& e : histo_loc ) e = 0;\n      for(auto& e : minin_loc ) e = nt2::Valmax<float>();\n      for(auto& e : maxin_loc ) e = nt2::Valmin<float>();\n      for(auto& e : minval_loc) e = nt2::Nan<float>();\n      for(auto& e : minref_loc) e = nt2::Valmax<float>();\n\n      std::size_t numThreads  = get_num_threads();\n      std::size_t my_id       = get_thread_num();\n      std::size_t num_inc     = diff / numThreads;\n\n      float my_mini = nt2::successor(mini,my_id*num_inc);\n      float my_maxi = nt2::successor(my_mini,num_inc);\n      if (my_id == numThreads -1) my_maxi = maxi;\n\n      // Fill up the reference SIMD register data\n      float a[N];\n      a[0] = my_mini;\n      for(std::size_t i = 1; i < N; i++) a[i] = nt2::successor(a[i-1], 1);\n      n_t a0 = nt2::load<n_t>(&a[0],0);\n\n      nt2::uint32_t k_loc = 0, j = 0;\n\n      while( nt2::extract(a0,1) < my_maxi )\n      {\n        n_t z = test_f(a0);\n\n        for(std::size_t i = 0; i < N; i++)\n        {\n          if (nt2::extract(a0,i)> my_maxi) break;\n          float v = reference_f(nt2::extract(a0,i));\n          float sz = nt2::extract(z,i);\n\n          double u = nt2::ulpdist(v, sz)*2.0+1.0;\n\n          if(nt2::is_invalid(u))\n          {\n            ++histo_loc[M+1];\n            if (!hit_loc[M+1])\n            {\n              maxin_loc [M+1] = minin_loc [M+1] = nt2::extract(a0,i);\n              minref_loc[M+1] = v;\n              minval_loc[M+1] = nt2::extract(z,i);\n              hit_loc[M+1] = true;\n            }\n            else\n            {\n              maxin_loc [M+1] = nt2::extract(a0,i);\n            }\n          }\n          else\n          {\n            int p = nt2::min(int(M), int(nt2::ilog2(nt2::iround(u))));\n\n            if (!hit_loc[p])\n            {\n              maxin_loc [p] = minin_loc [p] = nt2::extract(a0,i);\n              minref_loc[p] = v;\n              minval_loc[p] = nt2::extract(z,i);\n              hit_loc[p] = true;\n            }\n            else\n            {\n              maxin_loc [p] = nt2::extract(a0,i);\n            }\n            ++histo_loc[p];\n          }\n\n          ++k_loc;\n        }\n        a0 = nt2::successor(a0, vN);\n      }\n\n      #ifdef _OPENMP\n      #pragma omp critical\n      #endif\n      {\n        for (std::size_t kk=0;kk<M+2;kk++)\n        {\n          maxin[kk] = std::max(maxin_loc[kk],maxin[kk]);\n\n          if (minin_loc[kk]<minin[kk])\n          {\n            minin[kk] = std::min(minin_loc[kk],minin[kk]);\n            minval[kk] = minval_loc[kk];\n          }\n\n          minref[kk] = std::min(minref_loc[kk],minref[kk]);\n          histo[kk] += histo_loc[kk];\n        }\n        k += k_loc;\n      }\n    } //end omp parallel\n\n    std::cout << k << \"/\" << diff << \" values computed.\\n\";\n\n    double d = 1;\n    for(std::size_t i = 0; i < M+1; i++, d*= 2.0)\n    {\n      if(histo[i])\n      {\n        printf(\"%10u values (%.2f%%)\\twithin %1.1f ULPs\\t\"\n              , histo[i], (histo[i]*100.0/k), (d < 2 ? 0 : d/4)\n              );\n        if(i)\n          std::cout << std::scientific << std::setprecision(9)\n                    << \"in range [\" << minin[i] << \", \"<< maxin[i] << \"]\" << \".\"\n                    << \" Example: \"<< minin[i] << \" returns \" << minval[i]\n                    << \" instead of \" << minref[i];\n        std::cout << std::endl;\n      }\n    }\n\n    if( histo[M+1])\n    {\n      printf(\"%10u values (%.2f%%)\\twith invalid result.\\t\"\n            , histo[M+1], (histo[M+1]*100.0/k)\n            );\n      std::cout << std::scientific << std::setprecision(9)\n                << \"in range [\" << minin[M+1] << \", \"<< maxin[M+1] << \"]\" << \".\"\n                << \" Example: \"<< minin[M+1] << \" returns \" << minval[M+1]\n                << \" instead of \" << minref[M+1]\n                << std::endl;\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "445cf883ab7a16d2acd587db43dcb59fba7b7bf6", "size": 9318, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/test/exhaustive/include/nt2/sdk/exhaustive/exhaustive.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/test/exhaustive/include/nt2/sdk/exhaustive/exhaustive.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/test/exhaustive/include/nt2/sdk/exhaustive/exhaustive.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": 34.1318681319, "max_line_length": 103, "alphanum_fraction": 0.5362738785, "num_tokens": 2597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.046033901744859135, "lm_q1q2_score": 0.017042919346197134}}
{"text": "//-*-c++-*-\r\n//=======================================================================\r\n// Copyright 1997-2001 University of Notre Dame.\r\n// Authors: Lie-Quan Lee, Jeremy Siek\r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Generic Graph Component Library along with the software;  see the\r\n// file LICENSE.  If not, contact Office of Research, University of Notre\r\n// Dame, Notre Dame, IN  46556.\r\n//\r\n// Permission to modify the code and to distribute modified code is\r\n// granted, provided the text of this NOTICE is retained, a notice that\r\n// the code was modified is included with the above COPYRIGHT NOTICE and\r\n// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE\r\n// file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n//\r\n#ifndef MINIMUM_DEGREE_ORDERING_HPP\r\n#define MINIMUM_DEGREE_ORDERING_HPP\r\n\r\n#include <vector>\r\n#include <cassert>\r\n#include <boost/config.hpp>\r\n#include <boost/pending/bucket_sorter.hpp>\r\n#include <boost/detail/numeric_traits.hpp> // for integer_traits\r\n\r\nnamespace boost {\r\n\r\n  namespace detail {\r\n\r\n    // \r\n    // Given a set of n integers (where the integer values range from\r\n    // zero to n-1), we want to keep track of a collection of stacks\r\n    // of integers. It so happens that an integer will appear in at\r\n    // most one stack at a time, so the stacks form disjoint sets.\r\n    // Because of these restrictions, we can use one big array to\r\n    // store all the stacks, intertwined with one another.\r\n    // No allocation/deallocation happens in the push()/pop() methods\r\n    // so this is faster than using std::stack's.\r\n    //\r\n    template <class SignedInteger>\r\n    class Stacks {\r\n      typedef SignedInteger value_type;\r\n      typedef typename std::vector<value_type>::size_type size_type;\r\n    public:\r\n      Stacks(size_type n) : data(n) {}\r\n      \r\n      //: stack \r\n      class stack {\r\n        typedef typename std::vector<value_type>::iterator Iterator;\r\n      public:\r\n        stack(Iterator _data, const value_type& head)\r\n          :  data(_data), current(head) {}\r\n\r\n        // did not use default argument here to avoid internal compiler error\r\n        // in g++.\r\n        stack(Iterator _data)\r\n          : data(_data), current(-(std::numeric_limits<value_type>::max)()) {}\r\n        \r\n        void pop() {\r\n          assert(! empty());\r\n          current = data[current];\r\n        }\r\n        void push(value_type v) {\r\n          data[v] = current; \r\n          current = v;\r\n        }\r\n        bool empty() {\r\n          return current == -(std::numeric_limits<value_type>::max)(); \r\n        }\r\n        value_type& top() { return current; }\r\n      private:\r\n        Iterator data;\r\n        value_type current;\r\n      };\r\n\r\n      // To return a stack object \r\n      stack make_stack()\r\n        { return stack(data.begin()); }\r\n    protected:\r\n      std::vector<value_type> data;\r\n    };\r\n\r\n\r\n    // marker class, a generalization of coloring. \r\n    //\r\n    // This class is to provide a generalization of coloring which has\r\n    // complexity of amortized constant time to set all vertices' color\r\n    // back to be untagged. It implemented by increasing a tag.\r\n    //\r\n    // The colors are:\r\n    //   not tagged \r\n    //   tagged\r\n    //   multiple_tagged\r\n    //   done\r\n    //\r\n    template <class SignedInteger, class Vertex, class VertexIndexMap>\r\n    class Marker {\r\n      typedef SignedInteger value_type;\r\n      typedef typename std::vector<value_type>::size_type size_type;\r\n      \r\n      static value_type done() \r\n      { return (std::numeric_limits<value_type>::max)()/2; }\r\n    public:\r\n      Marker(size_type _num, VertexIndexMap index_map) \r\n        : tag(1 - (std::numeric_limits<value_type>::max)()),\r\n          data(_num, - (std::numeric_limits<value_type>::max)()),\r\n          id(index_map) {}\r\n      \r\n      void mark_done(Vertex node) { data[id[node]] = done(); }\r\n      \r\n      bool is_done(Vertex node) { return data[id[node]] == done(); }\r\n      \r\n      void mark_tagged(Vertex node) { data[id[node]] = tag; }\r\n      \r\n      void mark_multiple_tagged(Vertex node) { data[id[node]] = multiple_tag; }\r\n  \r\n      bool is_tagged(Vertex node) const { return data[id[node]] >= tag; }\r\n\r\n      bool is_not_tagged(Vertex node) const { return data[id[node]] < tag; }\r\n\r\n      bool is_multiple_tagged(Vertex node) const \r\n        { return data[id[node]] >= multiple_tag; }\r\n\r\n      void increment_tag() {\r\n        const size_type num = data.size();\r\n        ++tag;\r\n        if ( tag >= done() ) {\r\n          tag = 1 - (std::numeric_limits<value_type>::max)();\r\n          for (size_type i = 0; i < num; ++i)\r\n            if ( data[i] < done() ) \r\n              data[i] = - (std::numeric_limits<value_type>::max)();\r\n        }\r\n      }\r\n      \r\n      void set_multiple_tag(value_type mdeg0) \r\n      { \r\n        const size_type num = data.size();\r\n        multiple_tag = tag + mdeg0; \r\n        \r\n        if ( multiple_tag >= done() ) {\r\n          tag = 1-(std::numeric_limits<value_type>::max)();\r\n          \r\n          for (size_type i=0; i<num; i++)\r\n            if ( data[i] < done() ) \r\n              data[i] = -(std::numeric_limits<value_type>::max)();\r\n          \r\n          multiple_tag = tag + mdeg0; \r\n        }\r\n      }\r\n      \r\n      void set_tag_as_multiple_tag() { tag = multiple_tag; }\r\n      \r\n    protected:\r\n      value_type tag;\r\n      value_type multiple_tag;\r\n      std::vector<value_type> data;\r\n      VertexIndexMap id;\r\n    };\r\n    \r\n    template< class Iterator, class SignedInteger, \r\n       class Vertex, class VertexIndexMap, int offset = 1 >\r\n    class Numbering {\r\n      typedef SignedInteger number_type;\r\n      number_type num; //start from 1 instead of zero\r\n      Iterator   data;\r\n      number_type max_num;\r\n      VertexIndexMap id;\r\n    public:\r\n      Numbering(Iterator _data, number_type _max_num, VertexIndexMap id) \r\n        : num(1), data(_data), max_num(_max_num), id(id) {}\r\n      void operator()(Vertex node) { data[id[node]] = -num; }\r\n      bool all_done(number_type i = 0) const { return num + i > max_num; }\r\n      void increment(number_type i = 1) { num += i; }\r\n      bool is_numbered(Vertex node) const {\r\n        return data[id[node]] < 0;\r\n      }\r\n      void indistinguishable(Vertex i, Vertex j) {\r\n        data[id[i]] = - (id[j] + offset);\r\n      }\r\n    };\r\n\r\n    template <class SignedInteger, class Vertex, class VertexIndexMap>\r\n    class degreelists_marker {\r\n    public:\r\n      typedef SignedInteger value_type;\r\n      typedef typename std::vector<value_type>::size_type size_type;\r\n      degreelists_marker(size_type n, VertexIndexMap id)\r\n        : marks(n, 0), id(id) {}\r\n      void mark_need_update(Vertex i) { marks[id[i]] = 1;  }\r\n      bool need_update(Vertex i) { return marks[id[i]] == 1; }\r\n      bool outmatched_or_done (Vertex i) { return marks[id[i]] == -1; }\r\n      void mark(Vertex i) { marks[id[i]] = -1; }\r\n      void unmark(Vertex i) { marks[id[i]] = 0; }\r\n    private:\r\n      std::vector<value_type> marks;\r\n      VertexIndexMap id;\r\n    };\r\n\r\n    // Helper function object for edge removal\r\n    template <class Graph, class MarkerP, class NumberD, class Stack,\r\n      class VertexIndexMap>\r\n    class predicateRemoveEdge1 {\r\n      typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\r\n      typedef typename graph_traits<Graph>::edge_descriptor edge_t;\r\n    public:\r\n      predicateRemoveEdge1(Graph& _g, MarkerP& _marker, \r\n                           NumberD _numbering, Stack& n_e, VertexIndexMap id)\r\n        : g(&_g), marker(&_marker), numbering(_numbering),\r\n          neighbor_elements(&n_e), id(id) {}\r\n\r\n      bool operator()(edge_t e) {\r\n        vertex_t dist = target(e, *g);\r\n        if ( marker->is_tagged(dist) )\r\n          return true;\r\n        marker->mark_tagged(dist);\r\n        if (numbering.is_numbered(dist)) {\r\n          neighbor_elements->push(id[dist]);\r\n          return true;\r\n        }\r\n        return false;\r\n      }\r\n    private:\r\n      Graph*   g;\r\n      MarkerP* marker;\r\n      NumberD  numbering;\r\n      Stack*   neighbor_elements;\r\n      VertexIndexMap id;\r\n    };\r\n\r\n    // Helper function object for edge removal\r\n    template <class Graph, class MarkerP>\r\n    class predicate_remove_tagged_edges\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    public:\r\n      predicate_remove_tagged_edges(Graph& _g, MarkerP& _marker)\r\n        : g(&_g), marker(&_marker) {}\r\n\r\n      bool operator()(edge_t e) {\r\n        vertex_t dist = target(e, *g);\r\n        if ( marker->is_tagged(dist) )\r\n          return true;\r\n        return false;\r\n      }\r\n    private:\r\n      Graph*   g;\r\n      MarkerP* marker;\r\n    };\r\n\r\n    template<class Graph, class DegreeMap, \r\n             class InversePermutationMap, \r\n             class PermutationMap,\r\n             class SuperNodeMap, \r\n             class VertexIndexMap>\r\n    class mmd_impl\r\n    {\r\n      // Typedefs\r\n      typedef graph_traits<Graph> Traits;\r\n      typedef typename Traits::vertices_size_type size_type;\r\n      typedef typename detail::integer_traits<size_type>::difference_type \r\n        diff_t;\r\n      typedef typename Traits::vertex_descriptor vertex_t;\r\n      typedef typename Traits::adjacency_iterator adj_iter;\r\n      typedef iterator_property_map<vertex_t*, \r\n        identity_property_map, vertex_t, vertex_t&> IndexVertexMap;\r\n      typedef detail::Stacks<diff_t> Workspace;\r\n      typedef bucket_sorter<size_type, vertex_t, DegreeMap, VertexIndexMap> \r\n        DegreeLists;\r\n      typedef Numbering<InversePermutationMap, diff_t, vertex_t,VertexIndexMap>\r\n        NumberingD;\r\n      typedef degreelists_marker<diff_t, vertex_t, VertexIndexMap> \r\n        DegreeListsMarker;\r\n      typedef Marker<diff_t, vertex_t, VertexIndexMap> MarkerP;\r\n\r\n      // Data Members\r\n\r\n      // input parameters\r\n      Graph& G;\r\n      int delta;\r\n      DegreeMap degree;\r\n      InversePermutationMap inverse_perm;\r\n      PermutationMap perm;\r\n      SuperNodeMap supernode_size;\r\n      VertexIndexMap vertex_index_map;\r\n\r\n      // internal data-structures\r\n      std::vector<vertex_t> index_vertex_vec;\r\n      size_type n;\r\n      IndexVertexMap index_vertex_map;\r\n      DegreeLists degreelists;\r\n      NumberingD numbering;\r\n      DegreeListsMarker degree_lists_marker;\r\n      MarkerP marker;\r\n      Workspace work_space;\r\n    public:\r\n      mmd_impl(Graph& g, size_type n_, int delta, DegreeMap degree, \r\n               InversePermutationMap inverse_perm, \r\n               PermutationMap perm,\r\n               SuperNodeMap supernode_size, \r\n               VertexIndexMap id) \r\n        : G(g), delta(delta), degree(degree), \r\n        inverse_perm(inverse_perm), \r\n        perm(perm), \r\n        supernode_size(supernode_size), \r\n        vertex_index_map(id),\r\n        index_vertex_vec(n_), \r\n        n(n_),\r\n        degreelists(n_ + 1, n_, degree, id),\r\n        numbering(inverse_perm, n_, vertex_index_map),\r\n        degree_lists_marker(n_, vertex_index_map), \r\n        marker(n_, vertex_index_map),\r\n        work_space(n_)\r\n      {\r\n        typename graph_traits<Graph>::vertex_iterator v, vend;\r\n        size_type vid = 0;\r\n        for (tie(v, vend) = vertices(G); v != vend; ++v, ++vid)\r\n          index_vertex_vec[vid] = *v;\r\n        index_vertex_map = IndexVertexMap(&index_vertex_vec[0]);\r\n\r\n        // Initialize degreelists.  Degreelists organizes the nodes\r\n        // according to their degree.\r\n        for (tie(v, vend) = vertices(G); v != vend; ++v) {\r\n          put(degree, *v, out_degree(*v, G));\r\n          degreelists.push(*v);\r\n        }\r\n      }\r\n\r\n      void do_mmd()\r\n      {\r\n        // Eliminate the isolated nodes -- these are simply the nodes\r\n        // with no neighbors, which are accessible as a list (really, a\r\n        // stack) at location 0.  Since these don't affect any other\r\n        // nodes, we can eliminate them without doing degree updates.\r\n        typename DegreeLists::stack list_isolated = degreelists[0];\r\n        while (!list_isolated.empty()) {\r\n          vertex_t node = list_isolated.top();\r\n          marker.mark_done(node);\r\n          numbering(node);\r\n          numbering.increment();\r\n          list_isolated.pop();\r\n        }\r\n        size_type min_degree = 1;\r\n        typename DegreeLists::stack list_min_degree = degreelists[min_degree];\r\n\r\n        while (list_min_degree.empty()) {\r\n          ++min_degree;\r\n          list_min_degree = degreelists[min_degree];\r\n        }\r\n\r\n        // check if the whole eliminating process is done\r\n        while (!numbering.all_done()) {\r\n\r\n          size_type min_degree_limit = min_degree + delta; // WARNING\r\n          typename Workspace::stack llist = work_space.make_stack();\r\n\r\n          // multiple elimination\r\n          while (delta >= 0) {\r\n\r\n            // Find the next non-empty degree\r\n            for (list_min_degree = degreelists[min_degree]; \r\n                 list_min_degree.empty() && min_degree <= min_degree_limit; \r\n                 ++min_degree, list_min_degree = degreelists[min_degree])\r\n              ;\r\n            if (min_degree > min_degree_limit)\r\n              break;\r\n\r\n            const vertex_t node = list_min_degree.top();\r\n            const size_type node_id = vertex_index_map[node];\r\n            list_min_degree.pop();\r\n            numbering(node);\r\n\r\n            // check if node is the last one\r\n            if (numbering.all_done(supernode_size[node])) {\r\n              numbering.increment(supernode_size[node]);\r\n              break;\r\n            }\r\n            marker.increment_tag();\r\n            marker.mark_tagged(node);\r\n\r\n            this->eliminate(node);\r\n\r\n            numbering.increment(supernode_size[node]);\r\n            llist.push(node_id);\r\n          } // multiple elimination\r\n\r\n          if (numbering.all_done()) \r\n            break;\r\n\r\n          this->update( llist, min_degree);\r\n        }\r\n\r\n      } // do_mmd()\r\n\r\n      void eliminate(vertex_t node)\r\n      {\r\n        typename Workspace::stack element_neighbor = work_space.make_stack();\r\n\r\n        // Create two function objects for edge removal\r\n        typedef typename Workspace::stack WorkStack;\r\n        predicateRemoveEdge1<Graph, MarkerP, NumberingD, \r\n                             WorkStack, VertexIndexMap>\r\n          p(G, marker, numbering, element_neighbor, vertex_index_map);\r\n\r\n        predicate_remove_tagged_edges<Graph, MarkerP> p2(G, marker);\r\n\r\n        // Reconstruct the adjacent node list, push element neighbor in a List.\r\n        remove_out_edge_if(node, p, G);\r\n        //during removal element neighbors are collected.\r\n\r\n        while (!element_neighbor.empty()) {\r\n          // element absorb\r\n          size_type e_id = element_neighbor.top();\r\n          vertex_t element = index_vertex_map[e_id];\r\n          adj_iter i, i_end;\r\n          for (tie(i, i_end) = adjacent_vertices(element, G); i != i_end; ++i){\r\n            vertex_t i_node = *i;\r\n            if (!marker.is_tagged(i_node) && !numbering.is_numbered(i_node)) {\r\n              marker.mark_tagged(i_node);\r\n              add_edge(node, i_node, G);\r\n            }\r\n          }\r\n          element_neighbor.pop();\r\n        }\r\n        adj_iter v, ve;\r\n        for (tie(v, ve) = adjacent_vertices(node, G); v != ve; ++v) {\r\n          vertex_t v_node = *v;\r\n          if (!degree_lists_marker.need_update(v_node) \r\n              && !degree_lists_marker.outmatched_or_done(v_node)) {\r\n            degreelists.remove(v_node);\r\n          }\r\n          //update out edges of v_node\r\n          remove_out_edge_if(v_node, p2, G);\r\n\r\n          if ( out_degree(v_node, G) == 0 ) { // indistinguishable nodes\r\n            supernode_size[node] += supernode_size[v_node];\r\n            supernode_size[v_node] = 0;\r\n            numbering.indistinguishable(v_node, node);\r\n            marker.mark_done(v_node);\r\n            degree_lists_marker.mark(v_node);\r\n          } else {                           // not indistinguishable nodes\r\n            add_edge(v_node, node, G);\r\n            degree_lists_marker.mark_need_update(v_node);\r\n          }\r\n        }\r\n      } // eliminate()\r\n\r\n\r\n      template <class Stack>\r\n      void update(Stack llist, size_type& min_degree)\r\n      {\r\n        size_type min_degree0 = min_degree + delta + 1;\r\n\r\n        while (! llist.empty()) {\r\n          size_type deg, deg0 = 0;\r\n\r\n          marker.set_multiple_tag(min_degree0);\r\n          typename Workspace::stack q2list = work_space.make_stack();\r\n          typename Workspace::stack qxlist = work_space.make_stack();\r\n\r\n          vertex_t current = index_vertex_map[llist.top()];\r\n          adj_iter i, ie;\r\n          for (tie(i,ie) = adjacent_vertices(current, G); i != ie; ++i) {\r\n            vertex_t i_node = *i;\r\n            const size_type i_id = vertex_index_map[i_node];\r\n            if (supernode_size[i_node] != 0) {\r\n              deg0 += supernode_size[i_node];\r\n              marker.mark_multiple_tagged(i_node);\r\n              if (degree_lists_marker.need_update(i_node)) {\r\n                if (out_degree(i_node, G) == 2)\r\n                  q2list.push(i_id);\r\n                else\r\n                  qxlist.push(i_id);\r\n              }\r\n            }\r\n          }\r\n\r\n          while (!q2list.empty()) {\r\n            const size_type u_id = q2list.top();\r\n            vertex_t u_node = index_vertex_map[u_id];\r\n            // if u_id is outmatched by others, no need to update degree\r\n            if (degree_lists_marker.outmatched_or_done(u_node)) {\r\n              q2list.pop();\r\n              continue;\r\n            }\r\n            marker.increment_tag();\r\n            deg = deg0;\r\n\r\n            adj_iter nu = adjacent_vertices(u_node, G).first;\r\n            vertex_t neighbor = *nu;\r\n            if (neighbor == u_node) {\r\n              ++nu;\r\n              neighbor = *nu;\r\n            }\r\n            if (numbering.is_numbered(neighbor)) {\r\n              adj_iter i, ie;\r\n              for (tie(i,ie) = adjacent_vertices(neighbor, G);\r\n                   i != ie; ++i) {\r\n                const vertex_t i_node = *i;\r\n                if (i_node == u_node || supernode_size[i_node] == 0)\r\n                  continue;\r\n                if (marker.is_tagged(i_node)) {\r\n                  if (degree_lists_marker.need_update(i_node)) {\r\n                    if ( out_degree(i_node, G) == 2 ) { // is indistinguishable\r\n                      supernode_size[u_node] += supernode_size[i_node];\r\n                      supernode_size[i_node] = 0;\r\n                      numbering.indistinguishable(i_node, u_node);\r\n                      marker.mark_done(i_node);\r\n                      degree_lists_marker.mark(i_node);\r\n                    } else                        // is outmatched\r\n                      degree_lists_marker.mark(i_node);\r\n                  }\r\n                } else {\r\n                  marker.mark_tagged(i_node);\r\n                  deg += supernode_size[i_node];\r\n                }\r\n              }\r\n            } else\r\n              deg += supernode_size[neighbor];\r\n\r\n            deg -= supernode_size[u_node];\r\n            degree[u_node] = deg; //update degree\r\n            degreelists[deg].push(u_node);\r\n            //u_id has been pushed back into degreelists\r\n            degree_lists_marker.unmark(u_node);\r\n            if (min_degree > deg) \r\n              min_degree = deg;\r\n            q2list.pop();\r\n          } // while (!q2list.empty())\r\n\r\n          while (!qxlist.empty()) {\r\n            const size_type u_id = qxlist.top();\r\n            const vertex_t u_node = index_vertex_map[u_id];\r\n\r\n            // if u_id is outmatched by others, no need to update degree\r\n            if (degree_lists_marker.outmatched_or_done(u_node)) {\r\n              qxlist.pop();\r\n              continue;\r\n            }\r\n            marker.increment_tag();\r\n            deg = deg0;\r\n            adj_iter i, ie;\r\n            for (tie(i, ie) = adjacent_vertices(u_node, G); i != ie; ++i) {\r\n              vertex_t i_node = *i;\r\n              if (marker.is_tagged(i_node)) \r\n                continue;\r\n              marker.mark_tagged(i_node);\r\n\r\n              if (numbering.is_numbered(i_node)) {\r\n                adj_iter j, je;\r\n                for (tie(j, je) = adjacent_vertices(i_node, G); j != je; ++j) {\r\n                  const vertex_t j_node = *j;\r\n                  if (marker.is_not_tagged(j_node)) {\r\n                    marker.mark_tagged(j_node);\r\n                    deg += supernode_size[j_node];\r\n                  }\r\n                }\r\n              } else\r\n                deg += supernode_size[i_node];\r\n            } // for adjacent vertices of u_node\r\n            deg -= supernode_size[u_node];\r\n            degree[u_node] = deg;\r\n            degreelists[deg].push(u_node);\r\n            // u_id has been pushed back into degreelists\r\n            degree_lists_marker.unmark(u_node); \r\n            if (min_degree > deg)\r\n              min_degree = deg;\r\n            qxlist.pop();\r\n          } // while (!qxlist.empty()) {\r\n\r\n          marker.set_tag_as_multiple_tag();\r\n          llist.pop();\r\n        } // while (! llist.empty())\r\n\r\n      } // update()\r\n\r\n\r\n      void build_permutation(InversePermutationMap next,\r\n                             PermutationMap prev) \r\n      {\r\n        // collect the permutation info\r\n        size_type i;\r\n        for (i = 0; i < n; ++i) {\r\n          diff_t size = supernode_size[index_vertex_map[i]];\r\n          if ( size <= 0 ) {\r\n            prev[i] = next[i];\r\n            supernode_size[index_vertex_map[i]]\r\n              = next[i] + 1;  // record the supernode info\r\n          } else\r\n            prev[i] = - next[i];\r\n        }\r\n        for (i = 1; i < n + 1; ++i) {\r\n          if ( prev[i-1] > 0 )\r\n            continue;\r\n          diff_t parent = i;\r\n          while ( prev[parent - 1] < 0 ) {\r\n            parent = - prev[parent - 1];\r\n          }\r\n\r\n          diff_t root = parent;\r\n          diff_t num = prev[root - 1] + 1;\r\n          next[i-1] = - num;\r\n          prev[root-1] = num;\r\n\r\n          parent = i;\r\n          diff_t next_node = - prev[parent - 1];\r\n          while (next_node > 0) {\r\n            prev[parent-1] = - root;\r\n            parent = next_node;\r\n            next_node = - prev[parent - 1];\r\n          }\r\n        }\r\n        for (i = 0; i < n; i++) {\r\n          diff_t num = - next[i] - 1;\r\n          next[i] = num;\r\n          prev[num] = i;\r\n        }\r\n      } // build_permutation()\r\n    };\r\n\r\n  } //namespace detail\r\n\r\n\r\n  // MMD algorithm\r\n  // \r\n  //The implementation presently includes the enhancements for mass\r\n  //elimination, incomplete degree update, multiple elimination, and\r\n  //external degree.\r\n  //\r\n  //Important Note: This implementation requires the BGL graph to be\r\n  //directed.  Therefore, nonzero entry (i, j) in a symmetrical matrix\r\n  //A coresponds to two directed edges (i->j and j->i).\r\n  //\r\n  //see Alan George and Joseph W. H. Liu, The Evolution of the Minimum\r\n  //Degree Ordering Algorithm, SIAM Review, 31, 1989, Page 1-19\r\n  template<class Graph, class DegreeMap, \r\n           class InversePermutationMap, \r\n           class PermutationMap,\r\n           class SuperNodeMap, class VertexIndexMap>\r\n  void minimum_degree_ordering\r\n    (Graph& G, \r\n     DegreeMap degree, \r\n     InversePermutationMap inverse_perm, \r\n     PermutationMap perm, \r\n     SuperNodeMap supernode_size, \r\n     int delta, \r\n     VertexIndexMap vertex_index_map)\r\n  {\r\n    detail::mmd_impl<Graph,DegreeMap,InversePermutationMap,\r\n      PermutationMap, SuperNodeMap, VertexIndexMap> \r\n      impl(G, num_vertices(G), delta, degree, inverse_perm, \r\n           perm, supernode_size, vertex_index_map);\r\n    impl.do_mmd();\r\n    impl.build_permutation(inverse_perm, perm);\r\n  }\r\n\r\n} // namespace boost\r\n\r\n#endif // MINIMUM_DEGREE_ORDERING_HPP\r\n", "meta": {"hexsha": "edecc283657c60156126a30de2de13ef03092f37", "size": 24312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/minimum_degree_ordering.hpp", "max_stars_repo_name": "macaurther/DOCUSA", "max_stars_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-11-20T04:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:08.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/minimum_degree_ordering.hpp", "max_issues_repo_name": "macaurther/DOCUSA", "max_issues_repo_head_hexsha": "40586727c351d1b1130c05c2d4648cca3a8bacf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/minimum_degree_ordering.hpp", "max_forks_repo_name": "dguenms/Dawn-of-Civilization", "max_forks_repo_head_hexsha": "1c4f510af97a869637cddb4c0859759158cea5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 117.0, "max_forks_repo_forks_event_min_datetime": "2015-11-08T02:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T06:29:00.000Z", "avg_line_length": 36.2865671642, "max_line_length": 80, "alphanum_fraction": 0.5597235933, "num_tokens": 5462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.04885777308243654, "lm_q1q2_score": 0.0170340249084413}}
{"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_COMPRESSED2D_INCLUDE\n#define MTL_COMPRESSED2D_INCLUDE\n\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <cmath>\n#include <boost/tuple/tuple.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/config.hpp>\n#include <boost/numeric/mtl/utility/common_include.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/maybe.hpp>\n#include <boost/numeric/mtl/utility/shrink_stl_vector.hpp>\n#include <boost/numeric/mtl/utility/zipped_sort.hpp>\n#include <boost/numeric/mtl/detail/base_cursor.hpp>\n#include <boost/numeric/mtl/operation/is_negative.hpp>\n#include <boost/numeric/mtl/operation/update.hpp>\n#include <boost/numeric/mtl/operation/shift_block.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/matrix/base_matrix.hpp>\n#include <boost/numeric/mtl/matrix/crtp_base_matrix.hpp>\n#include <boost/numeric/mtl/matrix/mat_expr.hpp>\n#include <boost/numeric/mtl/matrix/element_matrix.hpp> \n#include <boost/numeric/mtl/matrix/element_array.hpp> \n#include <boost/numeric/mtl/vector/dense_vector.hpp> \n#include <boost/numeric/mtl/operation/compute_factors.hpp>\n#include <boost/numeric/mtl/operation/num_rows.hpp>\n#include <boost/numeric/mtl/operation/num_cols.hpp>\n#include <boost/numeric/mtl/operation/size.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#ifdef MTL_WITH_INITLIST\n# include <initializer_list>\n#endif\n\n#undef major // fight namespace pollution\n\nnamespace mtl { namespace matrix {\n\n\nstruct compressed_key\n{\n    typedef std::size_t                               size_t;\n    typedef compressed_key                            self;\n    \n    template <typename Elt, typename Parameters>\n    explicit compressed_key(compressed2D<Elt, Parameters> const& matrix, size_t offset) : offset(offset)\n    {\n\tstd::size_t my_major= matrix.indexer.find_major(matrix, offset);\n\tmajor= my_major;\n    }\n\n    template <typename Elt, typename Parameters>\n    explicit compressed_key(compressed2D<Elt, Parameters> const& matrix, size_t r, size_t c)\n    {\n\toffset= matrix.indexer(matrix, r, c).value();\n\tmajor= matrix.indexer.major_minor_c(matrix, r, c).first;\n    }\n\n    compressed_key(compressed_key const& other) { offset= other.offset; major= other.major; }\n\n    self& operator= (self const& other)\n    {\n\toffset= other.offset; major= other.major;\n\treturn *this;\n    }\n\n    bool operator== (compressed_key const& other) const\n    {\n\t//if (offset == other.offset && major != other.major) \n\t//    std::cout << offset << \" \" << other.offset << \" \" << major << \" \" << other.major << '\\n';\n\t// The following tests doesn't hold everywhere (anymore)\n\t// MTL_DEBUG_THROW_IF(offset == other.offset && major != other.major, logic_error(\"equal offsets imply equal major\"));\n\treturn offset == other.offset;\n    }\n\n    bool operator!= (compressed_key const& other) const { return !(*this == other); }\n\n    size_t       major;\n    size_t       offset;\n};\n\n\n// Cursor over every element\ntemplate <typename Elt, typename Parameters>\nstruct compressed_el_cursor \n    : public compressed_key \n{\n    typedef Elt                           value_type;\n    typedef compressed_key                base;\n    typedef compressed_el_cursor          self;\n    typedef std::size_t                   size_t;\n\n    explicit compressed_el_cursor(compressed2D<Elt, Parameters> const& matrix, size_t r, size_t c)\n\t: base(matrix, r, c), matrix(matrix)    {}\n\n    explicit compressed_el_cursor(compressed2D<Elt, Parameters> const& matrix, size_t offset) \n\t: base(matrix, offset), matrix(matrix)    {}\n\n    compressed_el_cursor(const compressed_el_cursor<Elt, Parameters>& other) \n\t: base(other), matrix(other.matrix)     {}\n\n    self& operator= (self const& other) { base::operator=(other); return *this; }\n\n    self& operator++ ()\n    {\n\t++offset;\n\tMTL_DEBUG_THROW_IF(matrix.starts[major+1] < offset, runtime_error(\"Inconsistent incrementation!\"));\n\twhile (major < matrix.starts.size()-1 && matrix.starts[major+1] == offset) \n\t    ++major;\n\treturn *this;\n    }\n\n    base& operator* () { return *this; }\n    const base& operator* () const { return *this; }\n\n    compressed2D<Elt, Parameters> const& matrix;\n};\n\n\n// Cursor over every element\ntemplate <typename Elt, typename Parameters>\nstruct compressed_minor_cursor \n    : public compressed_key \n{\n    typedef Elt                           value_type;\n    typedef compressed_key                base;\n    typedef compressed_minor_cursor       self;\n    typedef std::size_t                   size_t;\n\n    explicit compressed_minor_cursor(mtl::matrix::compressed2D<Elt, Parameters> const& matrix, size_t r, size_t c)\n\t: base(matrix, r, c), matrix(matrix)\n    {}\n\n    explicit compressed_minor_cursor(mtl::matrix::compressed2D<Elt, Parameters> const& matrix, size_t offset) \n\t: base(matrix, offset), matrix(matrix)\n    {}\n\n    compressed_minor_cursor(self const& other) : base(other), matrix(other.matrix) {}\n\n    self& operator= (self const& other)\n    {\tbase::operator=(other);\treturn *this; }\n\n    self& operator++() { ++offset; return *this;  }\n    self& operator+=(size_t inc) { offset+= inc; return *this; }\n    self operator+(size_t inc) const  {\tself tmp(*this); tmp+= inc; return tmp; }\n\n    self& operator--() { --offset; return *this; }\n    base& operator* () { return *this; }\n    const base& operator* () const { return *this; }\n\n    mtl::matrix::compressed2D<Elt, Parameters> const& matrix;\n};\n\n\n\n\n// Indexing for compressed matrices\ntemplate <typename SizeType>\nstruct compressed2D_indexer \n{\n    typedef SizeType                          size_type;\n    typedef std::pair<size_type, size_type>   size_pair;\n  private:\n    // helpers for public functions\n    template <class Matrix>\n    utilities::maybe<size_type> offset(const Matrix& ma, size_type major, size_type minor) const \n    {\n\ttypedef utilities::maybe<size_type>      result_type;\n\tassert(ma.starts[major] <= ma.starts[major+1]); // Check sortedness\n\tassert(ma.starts[major+1] <= ma.my_nnz);        // Check bounds of indices\n\t// Now we are save to use past-end addresses as iterators\n\n\t// Empty matrices are special cases\n\tif (ma.indices.empty())\n\t    return result_type(0, false);\n\n\tconst size_type *first = &ma.indices[0] + ma.starts[major],\n\t             *last = &ma.indices[0] + ma.starts[major+1];\n\t// if empty row (or column) return start of next one\n\tif (first == last) \n\t    return result_type(first - &ma.indices[0], false);\n\n\tconst size_type *index= first;\n\tif (last - index <= int(compressed_linear_search_limit))\n\t    while (index != last && *index < minor) ++index;\n\telse\n\t    index = std::lower_bound(first, last, minor);\n\treturn result_type(index - &ma.indices[0], index != last && *index == minor);\n    }\n\n  public:\n    // Returns major and minor index in C style (starting with 0)\n    template <class Matrix>\n    size_pair major_minor_c(const Matrix& ma, size_type row, size_type col) const\n    {\n\tusing std::make_pair;\n\t// convert into c indices\n\ttypename Matrix::index_type my_index;\n\tsize_type my_row= index::change_from(my_index, row),\n\t       my_col= index::change_from(my_index, col);\n\treturn make_pair(ma.major_(my_row, my_col), ma.minor_(my_row, my_col));\n    }\n\n    // Returns the offset if found\n    // If not found it returns the position where it would be inserted\n    template <class Matrix>\n    utilities::maybe<size_type> operator() (const Matrix& ma, size_type row, size_type col) const\n    {\n\tsize_type major, minor;\n\tboost::tie(major, minor) = major_minor_c(ma, row, col);\n\treturn offset(ma, major, minor);\n    }\n\n    // Same as above if internal representation is already known\n    template <class Matrix>\n    utilities::maybe<size_type> operator() (const Matrix& ma, size_pair major_minor) const \n    {\n\treturn offset(ma, major_minor.first, major_minor.second);\n    }\n\n    // For a given offset the minor can be accessed directly, the major dim has to be searched\n    // Returned in internal (c) representation\n    template <class Matrix>\n    size_type find_major(const Matrix& ma, size_type offset) const\n    {\n\tMTL_DEBUG_THROW_IF(ma.starts.empty(), logic_error(\"Major vector can't be empty\"));\n\tsize_type my_major= std::upper_bound(ma.starts.begin(), ma.starts.end(), offset) - ma.starts.begin();\n\treturn --my_major;\n    }\n\n    template <class Matrix>\n    size_type minor_from_offset(const Matrix& ma, size_type offset) const\n    {\n\ttypedef typename Matrix::index_type my_index;\n\treturn index::change_to(my_index(), ma.indices[offset]);\n    }\n\n}; // compressed2D_indexer\n\n\n/// Compressed 2D matrix type\n// For now no external data\ntemplate <typename Elt, typename Parameters = matrix::parameters<> >\nclass compressed2D \n  : public base_matrix<Elt, Parameters>,\n    public const_crtp_base_matrix< compressed2D<Elt, Parameters>, Elt, typename Parameters::size_type >,\n    public crtp_matrix_assign< compressed2D<Elt, Parameters>, Elt, typename Parameters::size_type >,\n    public mat_expr< compressed2D<Elt, Parameters> >\n{\n    typedef std::size_t                              size_t;\n    typedef base_matrix<Elt, Parameters>             super;\n    typedef compressed2D                             self;\n    typedef mat_expr< compressed2D<Elt, Parameters> >          expr_base;\n\n    // Only allocation of new data, doesn't copy if already existent\n    void allocate(size_t new_nnz)\n    {\n\tif (new_nnz) {\n\t    this->my_nnz = new_nnz;\n\t    data.resize(this->my_nnz);\n\t    indices.resize(this->my_nnz, 0);\n\t}\n    }\n\n  public:\n    typedef Parameters                               parameters;\n    typedef typename Parameters::orientation         orientation;\n    typedef typename Parameters::index               index_type;\n    typedef typename Parameters::dimensions          dimensions;\n    typedef Elt                                      value_type;\n    typedef compressed_key                           key_type;\n    // const value_type& isn't defined everywhere\n    typedef value_type                               const_reference;\n\n    typedef typename Parameters::size_type           size_type;\n    typedef crtp_matrix_assign<self, Elt, size_type>  assign_base;\n    typedef compressed2D_indexer<size_type>          indexer_type;\n\n    void check() const { MTL_DEBUG_THROW_IF(inserting, access_during_insertion()); }\n\n    /// Removes all values; e.g. for set_to_zero\n    void make_empty()\n    {\n\tcheck();\n\tthis->my_nnz = 0;\n\tdata.resize(0);\n\tindices.resize(0);\n\tstd::fill(starts.begin(), starts.end(), 0);\n    }\n\n    /// Change dimension of the matrix; data get lost.\n    void change_dim(size_type r, size_type c)\n    {\n\tcheck();\n\tif (this->num_rows() != r || this->num_cols() != c) {\n\t    super::change_dim(r, c);\n\t    starts.resize(this->dim1()+1);\n\t    make_empty();\n\t}\n    }\n\n    /// Sets nnz and resizes indices and data\n    void set_nnz(size_type n)\n    {\n\tcheck();\n\tindices.resize(n);\n\tdata.resize(n);\n\tthis->my_nnz= n;\n    }\n\n    // if compile time matrix size, we can set the start vector\n    /// Default constructor\n    explicit compressed2D () : inserting(false)\n    {\n\tif (super::dim_type::is_static) starts.resize(super::dim1() + 1);\n    }\n\n\n    /// Setting dimension and allocate starting vector\n    explicit compressed2D (mtl::non_fixed::dimensions d, size_t nnz = 0) \n      : super(d), inserting(false)\n    {\n\tstarts.resize(super::dim1() + 1, 0);\n\tallocate(nnz);\n    }\n\n    /// Setting dimension and allocate starting vector\n    explicit compressed2D (size_type num_rows, size_type num_cols, size_t nnz = 0) \n      : super(non_fixed::dimensions(num_rows, num_cols)), inserting(false)\n    {\n\tstarts.resize(super::dim1() + 1, 0);\n\tallocate(nnz);\n    }\n\n    /// Initializing matrix from 3 arrays: \\p Major, \\p Minor,\\p Entries.\n    /** For a row-major matrix Major shall contain the ranges of rows and Minor the column-indices.\n\tThis function is for advanced users only and should be used with care:\n\terrors can lead to inconsistent matrices and segmentation faults.\n     **/\n    compressed2D (size_type m, size_type n, size_type nnz, \n\t\t  size_type* Major, size_type* Minor, value_type* Entries)\n      : super(non_fixed::dimensions(m, n)), inserting(false)\n    {\n      allocate(nnz);\n\n      data.assign(Entries, Entries + nnz);\n      starts.assign(Major, Major + super::dim1() + 1);\n      indices.assign(Minor, Minor + nnz);\n    }\n\n\n#if 0 // Default is faster !!!\n    /// Copy constructor (just in case that is not generated by all compilers (generic matrix copy slower))\n    compressed2D(const self& src) \n      : super(non_fixed::dimensions(src.num_rows(), src.num_cols())), data(src.data),\n\tstarts(src.starts), indices(src.indices), inserting(false)\n    {}\n#endif\n\n    /// Copy from other types\n    template <typename MatrixSrc>\n    explicit compressed2D (const MatrixSrc& src) : inserting(false)\n    {\n\tif (super::dim_type::is_static) starts.resize(super::dim1() + 1);\n\t*this= src;\n    }\n\n\n#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n    /// Constructor for initializer list \\p values \n    template <typename Value2>\n    compressed2D(std::initializer_list<std::initializer_list<Value2> > values)\n      : super(mtl::non_fixed::dimensions(values.size(), values.size()? values.begin()->size() : 0)),\n\tinserting(false)\n    {\n\tstarts.resize(super::dim1() + 1, 0);\n\tallocate(super::dim1() * super::dim2());\n\t*this= values;\n    }\n#endif\n\n#ifdef MTL_WITH_DEFAULTIMPL\n    compressed2D(const compressed2D&) = default;\n#endif\n\n#ifdef MTL_WITH_MOVE\n    self& operator=(self&& src)\n    {\n\tstd::cout << \"I am moving !!!\\n\";\n\tcheck(); \n\tthis->checked_change_dim(src.num_rows(), src.num_cols());\n\tswap(*this, src);\n\treturn *this;\n    }\n\n    self& operator=(const self& src)\n    {\n\tif (this == &src) \n\t    return *this;\n\tcheck(); \n\tthis->checked_change_dim(src.num_rows(), src.num_cols());\n\tset_nnz(src.nnz());\n\n\tstarts= src.starts;\n\tindices= src.indices;\n\tdata= src.data;\n\treturn *this;\n    }\n#else\n    /// Consuming assignment operator (without move semantics)\n    self& operator=(self src)\n    {\n\tassert(this != &src);  // Self-copy would be an indication of an error\n\t\n\tcheck(); \n\t// TODO Check the following line\n\tthis->checked_change_dim(src.num_rows(), src.num_cols());\n\tswap(*this, src);\n\treturn *this;\n    }\n#endif\n\n    using assign_base::operator=;\n\n#if 0\n    void self_copy(const self& src)\n    {\n\tif (this == &src) \n\t    return;\n\tchange_dim(num_rows(src), num_cols(src));\n\tset_nnz(src.nnz());\n\n\t#ifdef MTL_WITH_OPENMP\n        #  pragma omp parallel for schedule(static, 16) \n\t#endif\n\tfor (int i= 0; i < int(src.dim1()); i++) {\n\t    const size_type cj0= src.starts[i], cj1= src.starts[i+1];\n\t    starts[i]= cj0;\n\t    for (size_type j0= cj0; j0 != cj1; ++j0) {\n\t\tindices[j0]= src.indices[j0];\n\t\tdata[j0]= src.data[j0];\n\t    }\n\t}\n\tstarts[src.dim1()]= src.starts[src.dim1()];\n    }\n#endif \n\n    /// Copy the pattern of matrix \\p src\n    /** Advanced feature. Not generic, i.e. does not exist for all matrix types.\n\tvalue_type of \\p src and target can be different.\n\tChanges dimension of target to that of \\p src.\n\tExisting entries are deleted. **/\n    template <typename Src>\n    void copy_pattern(const Src& src)\n    {\n\tusing std::copy;\n\tchange_dim(num_rows(src), num_cols(src));\n\tcopy(src.ref_major().begin(), src.ref_major().end(), starts.begin());\n\n\tset_nnz(src.ref_minor().size());\n\tcopy(src.ref_minor().begin(), src.ref_minor().end(), indices.begin());\n    }\n\n    void make_symmetric_pattern()\n    {\n\tMTL_THROW_IF(this->num_cols() != this->num_rows(), matrix_not_square());\n\tself A(*this);\n\t{\n\t    using math::zero;\n\t    inserter<self> ins(A, 2 * this->nnz() / this->dim1());\n\n\t    typename traits::row<self>::type                                 row(*this); \n\t    typename traits::col<self>::type                                 col(*this); \n\t    typename traits::const_value<self>::type                         value(*this); \n\t    typedef typename traits::range_generator<mtl::tag::major, self>::type        cursor_type;\n\t    for (cursor_type cursor = mtl::begin<mtl::tag::major>(*this), cend = mtl::end<mtl::tag::major>(*this); \n\t\t cursor != cend; ++cursor) {\n\t\ttypedef mtl::tag::nz     inner_tag;\n\t\ttypedef typename traits::range_generator<inner_tag, cursor_type>::type icursor_type;\n\t\tfor (icursor_type icursor = mtl::begin<inner_tag>(cursor), icend = mtl::end<inner_tag>(cursor); icursor != icend; ++icursor) {\n\t\t    size_type r= row(*icursor), c= col(*icursor);\n\t\t    if (!indexer(*this, c, r))\n\t\t\tins[c][r] << zero(value(*icursor));\n\t      \t}\n\t    }\n\t}\n\tswap(*this, A);\n    }\n\n\n    // Copies range of values and their coordinates into compressed matrix\n    // For brute force initialization, should be used with uttermost care\n    // Won't be suitable for distributed matrices, take care of this to this later\n    template <typename ValueIterator, typename StartIterator, typename IndexIterator>    \n    void raw_copy(ValueIterator first_value, ValueIterator last_value, \n\t\t  StartIterator first_start, IndexIterator first_index)\n    {\n\tusing std::copy;\n\n\t// check if starts has right size\n\tallocate(last_value - first_value); // ???? \n\t// check if nnz and indices has right size\n\n\tcopy(first_value, last_value, data.begin());\n\tcopy(first_start, first_start + this->dim1() + 1, starts.begin());\n\tcopy(first_index, first_index + this->nnz(), indices.begin());\n    }\n\n    /// Value of matrix entry\n    const_reference operator() (size_type row, size_type col) const\n    {\n\tusing ::math::zero;\n\tcheck(); MTL_DEBUG_THROW_IF(is_negative(row) || row >= this->num_rows() || is_negative(col) || col >= this->num_cols(), index_out_of_range());\n\tutilities::maybe<size_type> pos = indexer(*this, row, col);\n\treturn pos ? data[pos.value()] : zero(value_type()); \n    }\n\n    /// L-value reference of stored matrix entry\n    /** To be used with care; in debug mode, exception is thrown if entry is not found **/\n    value_type& lvalue(size_type row, size_type col)\n    {\n\tutilities::maybe<size_type> pos = indexer(*this, row, col);\n\tcheck(); MTL_DEBUG_THROW_IF(!pos, logic_error(\"This entry does not exist in the matrix\"));\n\treturn data[pos.value()];\n    }\n\n    // For internal use\n    const value_type& value_from_offset(size_type offset) const\n    {\n\tcheck(); MTL_DEBUG_THROW_IF(offset >= this->my_nnz, index_out_of_range(\"Offset larger than matrix\"));\n\treturn data[offset];\n    }\n\n    value_type& value_from_offset(size_type offset)\n    {\n\tcheck(); MTL_DEBUG_THROW_IF(offset >= this->my_nnz, index_out_of_range(\"Offset larger than matrix\"));\n\treturn data[offset];\n    }\n\n    /// Swap matrices\n    friend void swap(self& matrix1, self& matrix2)\n    {\n\tusing std::swap;\n\tswap(static_cast<super&>(matrix1), static_cast<super&>(matrix2));\n\t\n\tswap(matrix1.data, matrix2.data);\n\tswap(matrix1.starts, matrix2.starts);\n\tswap(matrix1.indices, matrix2.indices);\n\tswap(matrix1.inserting, matrix2.inserting);\n    }\n\n    /// Remove zero entries\n    void crop()\n    {\n\tcheck(); \n\tif (data.empty()) return;\n\n\tusing math::zero;\n\tvalue_type z= zero(data[0]);\n\tsize_type nzi= 0; // Where to copy next non-zero\n\t\n\tstd::vector<size_type>  new_starts(this->dim1() + 1);\n\tnew_starts[0] = 0;\n\n\tfor (size_type i = 0; i < this->dim1(); i++) {\n\t    for (size_type j= starts[i], end= starts[i+1]; j != end; ++j)\n\t\tif (data[j] != z)\n\t\t    indices[nzi]= indices[j], data[nzi++]= data[j]; \n\t    new_starts[i+1]= nzi;\n\t}\n\tthis->my_nnz= nzi;\n\tdata.resize(nzi);\n\tindices.resize(nzi);\n\tswap(starts, new_starts);\n    }\t\n    \n\n    /// Address of first major index; to be used with care. [advanced]\n    size_type* address_major() { check(); return &starts[0]; }\n    /// Address of first major index; to be used with care. [advanced]\n    const size_type* address_major() const { check(); return &starts[0]; }\n    /// Address of first minor index; to be used with care. [advanced]\n    size_type* address_minor() { check(); return &indices[0]; }\n    /// Address of first minor index; to be used with care. [advanced]\n    const size_type* address_minor() const { check(); return &indices[0]; }\n    /// Address of first data entry; to be used with care. [advanced]\n    value_type* address_data() { check(); return &data[0]; }\n    /// Address of first data entry; to be used with care. [advanced]\n    const value_type* address_data() const { check(); return &data[0]; }\n\n    const std::vector<size_type>& ref_major() const { return starts; } ///< Refer start vector [advanced]\n          std::vector<size_type>& ref_major()       { return starts; } ///< Refer start vector [advanced]\n    const std::vector<size_type>& ref_minor() const { return indices; } ///< Refer index vector [advanced]\n          std::vector<size_type>& ref_minor()       { return indices; } ///< Refer index vector [advanced]\n\n    /// Release unused space in STL vectors\n    void shrink() \n    {\n\tshrink_stl_vector(data);\n\tshrink_stl_vector(starts);\n\tshrink_stl_vector(indices);\n    }\n\n    /// Number of non-zeros in row/column \\p r_or_c when matrix is row-/column-major\n    size_type nnz_local(size_type r_or_c) const \n    { \n\tMTL_DEBUG_THROW_IF(r_or_c >= this->dim1(), index_out_of_range());\n\treturn starts[r_or_c+1] - starts[r_or_c];\n    }\n\n    template <typename> friend struct compressed2D_indexer;\n    template <typename, typename, typename> friend struct compressed2D_inserter;\n    template <typename, typename> friend struct compressed_el_cursor;\n    template <typename, typename> friend struct compressed_minor_cursor;\n\n    indexer_type            indexer;\n    std::vector<value_type> data; \n  protected:\n    std::vector<size_type>  starts;\n    std::vector<size_type>  indices;\n    bool                    inserting;\n};\n\n\n\n// ========\n// Inserter\n// ========\n\n/// Additional data structure to insert entries into a compressed2D matrix\ntemplate <typename Elt, typename Parameters, typename Updater = mtl::operations::update_store<Elt> >\nstruct compressed2D_inserter\n{\n    typedef compressed2D_inserter             self;\n    typedef compressed2D<Elt, Parameters>     matrix_type;\n    typedef typename matrix_type::size_type   size_type;\n    typedef typename matrix_type::value_type  value_type;\n    typedef std::pair<size_type, size_type>   size_pair;\n    typedef std::map<size_pair, value_type>   map_type;\n    typedef operations::update_proxy<self, size_type>   proxy_type;\n\n  private: \n    // stretch matrix rows or columns to slot size (or leave it if equal or greater)\n    void stretch();\n\n    struct bracket_proxy\n    {\n\tbracket_proxy(self& ref, size_type row) : ref(ref), row(row) {}\n\t\n\tproxy_type operator[](size_type col) { return proxy_type(ref, row, col); }\n\n\tself&      ref;\n\tsize_type  row;\n    };\n\n  protected:\n    void finish()\n    {\n\t// std::cout << \"~compressed2D_inserter: \" << matrix.my_nnz << \" entries in matrix already (reserved for \" <<  elements.size() \n\t// \t  << \") and \" << spare.size() << \" entries in map.\\n\";\n\tvampir_trace<3051> tracer;\n\tif (num_rows(matrix) > 0 && num_cols(matrix) > 0) {\n\t    final_place();\n\t    insert_spare();\n\t}\n\tmatrix.inserting = false;\n    }\n\n  public:\n    /// Construction with matrix reference and optional slot size, see \\ref matrix_insertion\n    explicit compressed2D_inserter(matrix_type& matrix, size_type slot_size = 5)\n\t: matrix(matrix), elements(matrix.data), starts(matrix.starts), indices(matrix.indices), \n\t  slot_size(std::min(slot_size, matrix.dim2())), slot_ends(matrix.dim1()+1) \n    {\n\tvampir_trace<3050> tracer;\n\tMTL_THROW_IF(matrix.inserting, runtime_error(\"Two inserters on same matrix\"));\n\tmatrix.inserting = true;\n\tif (size(matrix) > 0) \n\t    stretch();\n    }\n\n    ~compressed2D_inserter()\n    {\n\t// Check if finish wasn't called explicitly before\n\tif (matrix.inserting)\n\t    finish();\n    }\n\t\n    /// Proxy to insert into A[row][col]\n    bracket_proxy operator[] (size_type row)\n    {\n\treturn bracket_proxy(*this, row);\n    }\n\n    /// Proxy to insert into A[row][col]\n    proxy_type operator() (size_type row, size_type col)\n    {\n\treturn proxy_type(*this, row, col);\n    }\n\n    /// Modify A[row][col] with \\p val using \\p Modifier\n    template <typename Modifier>\n    void modify(size_type row, size_type col, value_type val);\n\n    /// Modify A[row][col] with \\p val using the class' updater\n    void update(size_type row, size_type col, value_type val)\n    {\n\tusing math::zero;\n\tmodify<Updater>(row, col, val);\n    }\n\n    /// For debugging only; print entries in all slots; ignores entries in spare map [advanced]\n    void print() const\n    {\n\tfor (size_type j= 0; j < matrix.dim1(); j++)\n\t    print(j);\n    }\n\n    /// For debugging only; print entries in slot; ignores entries in spare map [advanced]\n    void print(size_type i) const\n    {\n\tstd::cout << \"in slot \" << i << \": \";\n\tfor (size_type j= starts[i]; j < slot_ends[i]; ++j)\n\t    std::cout << \"[\" << indices[j] << \": \" << elements[j] << \"]\";\n\tstd::cout << \"\\n\";\n    }\n    \n    /// Empties slot i (row or column according to orientation); for experts only [advanced]\n    /** Does not work if entries are in spare map !!!! **/\n    void make_empty(size_type i)\n    {\tslot_ends[i]= starts[i];    }\n\n    /// Value in A[r][c]\n    value_type value(size_type r, size_type c) const\n    {\n\tsize_pair                      mm= matrix.indexer.major_minor_c(matrix, r, c);\n\tutilities::maybe<size_type>    offset= matrix_offset(mm);\n\treturn offset ? matrix.data[offset.value()] : value_type(0);\n    }\n\n    /// Insert \\p elements into %matrix with pre-sorting\n    /** It should be faster for sufficiently large element matrices but our benchmarks showed the opposite. **/\n    template <typename Matrix, typename Rows, typename Cols>\n    self& sorted_block_insertion(const element_matrix_t<Matrix, Rows, Cols>& elements);\n    \n    /// Insert \\p elements into %matrix\n    template <typename Matrix, typename Rows, typename Cols>\n    self& operator<< (const element_matrix_t<Matrix, Rows, Cols>& elements)\n    {\n\tusing mtl::size;\n#if 0 // shouldn't be slower now\n\tif (size(elements.cols) > sorted_block_insertion_limit\n\t    && boost::is_same<typename Parameters::orientation, row_major>::value)\n\t    return sorted_block_insertion(elements);\n#endif\n\n\tfor (unsigned ri= 0; ri < size(elements.rows); ri++)\n\t    for (unsigned ci= 0; ci < size(elements.cols); ci++)\n\t\tupdate (elements.rows[ri], elements.cols[ci], elements.matrix(ri, ci));\n\treturn *this;\n    }\n\n    /// Insert \\p elements into %matrix\n    template <typename Matrix, typename Rows, typename Cols>\n    self& operator<< (const element_array_t<Matrix, Rows, Cols>& elements)\n    {\n\tusing mtl::size;\n\tfor (unsigned ri= 0; ri < size(elements.rows); ri++)\n\t    for (unsigned ci= 0; ci < size(elements.cols); ci++)\n\t\tupdate (elements.rows[ri], elements.cols[ci], elements.array[ri][ci]);\n\treturn *this;\n    }\n\n    // not so nice functions needed for direct access, e.g. in factorizations\n    std::vector<size_type> const& ref_major() const { return starts; } ///< Refer start vector [advanced]\n    std::vector<size_type> const& ref_minor() const { return indices; } ///< Refer index vector [advanced]\n    std::vector<size_type> const& ref_slot_ends() const { return slot_ends; } ///< Refer slot-end vector [advanced]\n    std::vector<value_type> const& ref_elements() const { return elements; } ///< Refer element vector [advanced]\n\n  private:\n    utilities::maybe<typename self::size_type> matrix_offset(size_pair) const;\n    void final_place();\n    void insert_spare();\n    \n    // Show ith row/column\n    void display(size_type i)\n    {\n\tstd::cout << \"slot \" << i << \" is [\";\n\tfor (size_type j= starts[i]; j < slot_ends[i]; ++j)\n\t    std::cout << '(' << indices[j] << \": \" <<  elements[j] << \")\"\n\t\t      << (j < slot_ends[i] - 1 ? \", \" : \"\");\n\tstd::cout << \"]\\n\";\n    }\n\n    // eliminate double entries in a slot by using the updater\n    // indices are supposed to be sorted\n    void reduce_slot(size_type i)\n    {\n\tsize_type tgt= starts[i], src= tgt + 1, end= slot_ends[i];\n\tfor (; src < end;) {\n\t    while (src < end && indices[tgt] == indices[src])\n\t\tUpdater()(elements[tgt], elements[src++]);\n\t    ++tgt;\n\t    if (tgt == src)\n\t\t++src;\n\t    else if (src < end && indices[tgt] != indices[src]) {\n\t\tindices[tgt]= indices[src];\n\t\telements[tgt]= elements[src++];\n\t\tif (src >= end) ++tgt; // correction to not remain on the last entry\n\t    }       \n\t}\n\tslot_ends[i]= tgt;\n    }\n\n  protected:\n    compressed2D<Elt, Parameters>&      matrix;\n    std::vector<value_type>&            elements;\n    std::vector<size_type>&             starts;\n    std::vector<size_type>&             indices;\n    size_type                           slot_size;\n    std::vector<size_type>              slot_ends;\n    map_type                            spare;\n};\n\ntemplate <typename Elt, typename Parameters, typename Updater>\nvoid compressed2D_inserter<Elt, Parameters, Updater>::stretch()\n{\n    using std::copy;\n    using std::copy_backward;\n    using std::swap;\n\n    vampir_trace<3052> tracer;\n    // Stretching is much simpler for empty matrices\n    if (elements.empty()) {\n\tfor (size_type i= 0, s= 0; i <= matrix.dim1(); i++, s+= slot_size)\n\t    slot_ends[i]= starts[i]= s;\n\tsize_type new_total= (slot_ends[matrix.dim1()]= starts[matrix.dim1()]) + slot_size;\n\telements.reserve(new_total); indices.reserve(new_total);\n\telements.resize(new_total); indices.resize(new_total);\n\treturn;\n    }\n\n\n\n    // If there are enough existing entries then skip the stretching (expensive)\n    if (elements.size() + matrix.dim1()/2 > std::size_t(slot_size * matrix.dim1())) {\n\t// Use start of next row/col as slot_ends\n\tcopy(starts.begin() + 1, starts.end(), slot_ends.begin());\n\tslot_ends[matrix.dim1()]= starts[matrix.dim1()];\n\treturn;\n    }\n\n    std::vector<size_type>  new_starts(matrix.dim1() + 1);\n    new_starts[0] = 0;\n    for (size_type i = 0; i < matrix.dim1(); i++) {\n\tsize_type entries = starts[i+1] - starts[i];\n\tslot_ends[i] = new_starts[i] + entries; \n\tnew_starts[i+1] = new_starts[i] + std::max(entries, slot_size);\n    }\n    // Add an additional slot for temporaries\n    size_type new_total= (slot_ends[matrix.dim1()]= new_starts[matrix.dim1()]) + slot_size;\n    elements.resize(new_total);\n    indices.resize(new_total);\n    // for (int i= 0; i < matrix.dim1()+1; i++) std::cout << \"Slot \" << i << \" is [\" << new_starts[i] << \", \" << slot_ends[i] << \")\\n\";\n   \n    // copy normally if not overlapping and backward if overlapping\n    // i goes down to 1 (not to 0) because i >= 0 never stops for unsigned ;-)\n\t// &v[i] is replaced by &v[0]+i to enable past-end addresses for STL copy\n    for (size_type i = matrix.dim1(); i > 0; i--)\n\tif (starts[i] <= new_starts[i-1]) {\n\t    // std::cout << \"Kopiere vorwaerts von \" << starts[i-1] << \" bis \" << starts[i] << \" nach \" << new_starts[i-1] << \"\\n\";\n\t    copy(&elements[0] + starts[i-1], &elements[0] + starts[i], &elements[0] + new_starts[i-1]);\n\t    copy(&indices[0] + starts[i-1], &indices[0] + starts[i], &indices[0] + new_starts[i-1]);\n\t} else {\n\t    // std::cout << \"Kopiere rueckwaerts von \" << starts[i-1] << \" bis \" << starts[i] << \" nach \" << slot_ends[i-1] << \"\\n\";\n\t    copy_backward(&elements[0] + starts[i-1], &elements[0] + starts[i], &elements[0] + slot_ends[i-1]);\n\t    copy_backward(&indices[0] + starts[i-1], &indices[0] + starts[i], &indices[0] + slot_ends[i-1]);\n\t}\n    swap(starts, new_starts);\t\n}\n\ntemplate <typename Elt, typename Parameters, typename Updater>\ninline utilities::maybe<typename compressed2D_inserter<Elt, Parameters, Updater>::size_type> \ncompressed2D_inserter<Elt, Parameters, Updater>::matrix_offset(size_pair mm) const\n{\n    size_type major, minor;\n    boost::tie(major, minor) = mm;\n\n    if (indices.empty())\n\treturn utilities::maybe<size_type> (0, false);\n\n    // &v[i] isn't liked by all libs -> &v[0]+i circumvents complaints\n    const size_type *first = &indices[0] + starts[major],\n  \t            *last =  &indices[0] + slot_ends[major];\n    if (first == last) \n\treturn utilities::maybe<size_type> (first - &indices[0], false);\n\n    const size_type *index= first;\n    if (last - index < 10)\n\twhile (index != last && *index < minor) ++index;\n    else\n\tindex = std::lower_bound(first, last, minor);\n    return utilities::maybe<size_type>(index - &indices[0], index != last && *index == minor);  \n}\n\n\ntemplate <typename Elt, typename Parameters, typename Updater>\ntemplate <typename Modifier>\ninline void compressed2D_inserter<Elt, Parameters, Updater>::modify(size_type row, size_type col, value_type val)\n{\n    using std::copy_backward;\n    MTL_DEBUG_THROW_IF(is_negative(row) || row >= num_rows(matrix) || is_negative(col) || col >= num_cols(matrix), index_out_of_range());\n\n    Modifier                          modifier;  \n    compressed2D_indexer<size_type>   indexer;\n    size_pair                         mm = indexer.major_minor_c(matrix, row, col);\n    size_type                         major, minor;\n    boost::tie(major, minor) = mm;\n\n    utilities::maybe<size_type>       pos = matrix_offset(mm);\n    // Check if already in matrix and update it\n    if (pos) \n\tmodifier (elements[pos.value()], val); \n    else {\n\tsize_type& my_end = slot_ends[major];\n\t// Check if place in matrix to insert there\n\tif (my_end != starts[major+1]) { \n\t    if (pos.value() != my_end) {\n\t\tcopy_backward(&elements[0] + pos.value(), &elements[0] + my_end, &elements[0] + (my_end+1));\n\t\tcopy_backward(&indices[0] + pos.value(), &indices[0] + my_end, &indices[0] + (my_end+1));\n\t    }\n\t    elements[pos.value()] = modifier.init(val); indices[pos.value()] = minor;\n\t    my_end++;\t    \n\t    matrix.my_nnz++;      // new entry\n\t} else {\n\t    typename map_type::iterator it = spare.find(mm);\n\t    // If not in map insert it, otherwise update the value\n\t    if (it == spare.end()) {\n\t\tspare.insert(std::make_pair(mm, modifier.init(val)));\n\t\tmatrix.my_nnz++;      // new entry\n\t    } else \n\t\tmodifier(it->second, val);\n\t}\n    }\n    // std::cout << \"inserter update: \" << matrix.my_nnz << \" non-zero elements, new value is \" << elements[pos] << \"\\n\";\n}  \n\nnamespace detail {\n    \n    struct cmp_first\n    {\n\ttemplate <typename F, typename S>\n\tbool operator()(const std::pair<F, S>& x, const std::pair<F, S>& y) const\n\t{\n\t    return x.first < y.first;\n\t}\n    };\n}\n\ntemplate <typename Elt, typename Parameters, typename Updater>\ntemplate <typename Matrix, typename Rows, typename Cols>\ncompressed2D_inserter<Elt, Parameters, Updater>& \ncompressed2D_inserter<Elt, Parameters, Updater>::sorted_block_insertion(const element_matrix_t<Matrix, Rows, Cols>& iblock)\n{\n    using std::copy; using std::copy_backward; using std::min;\n    using mtl::size; using mtl::num_rows; using mtl::num_cols;\n    using namespace mtl::utility;\n    typedef zip_it<size_type, value_type> it_type;\n\n    size_type m= size(iblock.rows), n= size(iblock.cols);\n    MTL_THROW_IF(m != num_rows(iblock.matrix) || n != num_cols(iblock.matrix), incompatible_size());\n    MTL_THROW_IF(&iblock.matrix[0][1] - &iblock.matrix[0][0] != 1, logic_error(\"Rows must be consecutive\"));\n\n    size_type rmax= matrix.dim1(), &index_max0= indices[starts[rmax]];\n    value_type& value_max0= elements[starts[rmax]];\n    for (size_type i= 0; i < m; i++) {\n\tsize_type r= iblock.rows[i], &index_0= indices[starts[r]];\n\tvalue_type& value_0= elements[starts[r]];\n\tif (slot_ends[r] == starts[r]) {\n\t    size_type to_copy= min(starts[r+1] - starts[r], n);\n\t    copy(&iblock.cols[0], &iblock.cols[0]+to_copy, &index_0);\n\t    copy(&iblock.matrix[i][0], &iblock.matrix[i][0]+to_copy, &value_0);\n\t    slot_ends[r]= starts[r] + to_copy;\n\t    std::sort(it_type(&index_0, &value_0, 0), it_type(&index_0, &value_0, to_copy), less_0());\n\t    reduce_slot(r);\n\t    // display(r);\t\t \n\t    matrix.my_nnz+= slot_ends[r] - starts[r];\n\t    for (size_type j= to_copy; j < n; ++j)\n\t\tupdate(r, iblock.cols[j], iblock.matrix[i][j]);\n\t} else {\n\t    size_type to_copy= min(slot_size, n);\n\t    copy(&iblock.cols[0], &iblock.cols[0]+to_copy, &index_max0);\n\t    copy(&iblock.matrix[i][0], &iblock.matrix[i][0]+to_copy, &value_max0);\n\t    slot_ends[rmax]= starts[rmax] + to_copy;\n\t    std::sort(it_type(&index_max0, &value_max0, 0), it_type(&index_max0, &value_max0, to_copy), less_0());\n\t    size_type tgt= starts[r], tend= slot_ends[r], later= starts[rmax], src= later, end= slot_ends[rmax];\n\t    for (; src < end; ) {\n\t\t// search for next equal entry in slot r\n\t\twhile (tgt < tend && indices[src] > indices[tgt]) ++tgt;\n\t\t// reduce equal entries (they are consecutive)\n\t\tif (tgt < tend)\n\t\t    while (src < end && indices[src] == indices[tgt])\n\t\t\tUpdater()(elements[tgt], elements[src++]);\n\t\telse { // all new entries are larger than the largest existing\n\t\t    for (; src < end && tgt < starts[r+1]; ++src) { // copy at the end of slot\n\t\t\tindices[tgt]= indices[src];\n\t\t\telements[tgt]= elements[src];\n\t\t\tslot_ends[r]= ++tgt;\n\t\t\t++matrix.my_nnz;\n\t\t    }\n\t\t    for (; src < end; ++src) // remainder goes into spare\n\t\t\tupdate(r, indices[src], elements[src]);\n\t\t    later= starts[rmax]; // we're done, avoid postponed loop\n\t\t}\n\t\t// collect indices not found in r to deal with later    \n\t\twhile (src < end && indices[src] < indices[tgt]) {\n\t\t    if (later != src) {\n\t\t\tindices[later]= indices[src]; \n\t\t\telements[later]= elements[src];\n\t\t    }\n\t\t    ++src; ++later;\n\t\t}\n\t    }\n\t    for (size_type j= starts[rmax]; j < later; ++j)\n\t\tupdate(r, indices[j], elements[j]);\n\t}\n    }\n    return *this;\n}\n\n\ntemplate <typename Elt, typename Parameters, typename Updater>\nvoid compressed2D_inserter<Elt, Parameters, Updater>::final_place()\n{\n    using std::swap;\n    vampir_trace<3053> tracer;\n\n    size_type          dim1 = matrix.dim1();\n    std::vector<size_type>  new_starts(dim1 + 1);\n    new_starts[0] = 0;\n\n    if (spare.empty()) {\n\t// Check if everything is already in place\n\tif (slot_ends[dim1-1] == matrix.my_nnz) {\n\t    starts[dim1]= slot_ends[dim1-1];\n\t    if (std::size_t(matrix.my_nnz) < elements.size()) \n\t\telements.resize(matrix.my_nnz), \n\t\t    indices.resize(matrix.my_nnz);\n\t    return;\n\t}\n\tsize_type pos= 0;\n\tfor (size_type i= 0; i < dim1; ++i) {\n\t    new_starts[i]= pos;\n\t    for (size_type j= starts[i], je= slot_ends[i]; j < je; ++j, ++pos) {\n\t\telements[pos]= elements[j];\n\t\tindices[pos]= indices[j];\n\t    }\n\t}\n\tnew_starts[dim1]= pos;\n\tswap(new_starts, starts);\n\tif (std::size_t(matrix.my_nnz) < elements.size()) \n\t    elements.resize(matrix.my_nnz), \n\t\tindices.resize(matrix.my_nnz);\n\treturn;\n    }\n\n    typename map_type::iterator it = spare.begin();\n    for (size_type i = 0; i < dim1; i++) {\n\tsize_type entries = slot_ends[i] - starts[i];\n\twhile (it != spare.end() && it->first.first == i)\n\t    entries++, it++;\n\tnew_starts[i+1] = new_starts[i] + entries;\n    }\n\n    size_type new_total = new_starts[dim1], old_total = starts[dim1];\n    if (new_total > old_total) {\n\telements.resize(new_total);\n\tindices.resize(new_total); }\n \n    operations::shift_blocks(dim1, starts, new_starts, slot_ends, elements);\n    operations::shift_blocks(dim1, starts, new_starts, slot_ends, indices);\n\n    if (std::size_t(new_total) < elements.size()) {\n\telements.resize(new_total);\n\tindices.resize(new_total); }\n \n    for (size_type i = 0; i < dim1; i++)\n\tslot_ends[i] = new_starts[i] + slot_ends[i] - starts[i];\n\n    swap(starts, new_starts);\t\t    \n}\n\ntemplate <typename Elt, typename Parameters, typename Updater>\nvoid compressed2D_inserter<Elt, Parameters, Updater>::insert_spare()\n{\n    vampir_trace<3054> tracer;\n    using std::copy_backward;\n\n    for (typename map_type::iterator it = spare.begin(); it != spare.end(); ++it) {\n\tsize_pair              mm = it->first;\n\tsize_type              major = mm.first, minor = mm.second;\n\tutilities::maybe<size_type>       pos = matrix_offset(mm);\n\tsize_type&             my_end = slot_ends[major];\n\n\t// &v[i] see above\n\tcopy_backward(&elements[0] + pos.value(), &elements[0] + my_end, &elements[0] + (my_end+1));\n\tcopy_backward(&indices[0] + pos.value(), &indices[0] + my_end, &indices[0] + (my_end+1));\n\telements[pos.value()] = it->second; indices[pos.value()] = minor;\n\tmy_end++;\n    }\n}\n\n// ================\n// Free functions\n// ================\n\ntemplate <typename Value, typename Parameters>\ntypename compressed2D<Value, Parameters>::size_type\ninline num_rows(const compressed2D<Value, Parameters>& matrix)\n{\n    return matrix.num_rows();\n}\n\ntemplate <typename Value, typename Parameters>\ntypename compressed2D<Value, Parameters>::size_type\ninline num_cols(const compressed2D<Value, Parameters>& matrix)\n{\n    return matrix.num_cols();\n}\n\ntemplate <typename Value, typename Parameters>\n// typename compressed2D<Value, Parameters>::size_type risks overflow\nstd::size_t\ninline size(const compressed2D<Value, Parameters>& matrix)\n{\n    return std::size_t(matrix.num_cols()) * std::size_t(matrix.num_rows());\n}\n\n\n}} // namespace mtl::matrix\n\nnamespace mtl {\n\tusing matrix::compressed2D;\n}\n\n// ================\n// Range generators\n// ================\n\nnamespace mtl { namespace traits {\n\n    // VC 8.0 finds ambiguity with mtl::tag::morton_dense (I wonder why, especially here)\n    using mtl::matrix::compressed2D;\n    using mtl::matrix::compressed_el_cursor;\n    using mtl::matrix::compressed_minor_cursor;\n\n    // ===========\n    // For cursors\n    // ===========\n        \n    template <class Elt, class Parameters>\n    struct range_generator<glas::tag::nz, compressed2D<Elt, Parameters> >\n      : detail::all_offsets_range_generator<compressed2D<Elt, Parameters>,\n\t\t\t\t\t    compressed_el_cursor<Elt, Parameters>, \n\t\t\t\t\t    complexity_classes::linear_cached>\n    {};\n\n    // Cursor over all rows\n    // Supported if row major matrix\n    template <typename Elt, typename Parameters>\n    struct range_generator<glas::tag::row, compressed2D<Elt, Parameters> >\n      : boost::mpl::if_<\n\t    boost::is_same<typename Parameters::orientation, row_major>\n \t  , detail::all_rows_range_generator<compressed2D<Elt, Parameters>, complexity_classes::linear_cached>\n \t  , range_generator<tag::unsupported, compressed2D<Elt, Parameters> >\n        >::type {};\n\n\n    template <class Elt, class Parameters>\n    struct range_generator<glas::tag::nz, \n\t\t\t   detail::sub_matrix_cursor<compressed2D<Elt, Parameters>, glas::tag::row, 2> >\n    {\n\ttypedef typename Collection<compressed2D<Elt, Parameters> >::size_type  size_type;\n\ttypedef detail::sub_matrix_cursor<compressed2D<Elt, Parameters>, glas::tag::row, 2> cursor_type;\n\ttypedef complexity_classes::linear_cached         complexity;\n\ttypedef compressed_minor_cursor<Elt, Parameters>  type;\n\tstatic int const                                  level = 1;\n\n\ttype begin(cursor_type const& cursor) const\n\t{\n\t    return type(cursor.ref, cursor.key, cursor.ref.begin_col());\n\t}\n\ttype end(cursor_type const& cursor) const\n\t{\n\t    return type(cursor.ref, cursor.key, cursor.ref.end_col());\n\t}\n\ttype lower_bound(cursor_type const& cursor, size_type position) const\n\t{\n\t    return type(cursor.ref, cursor.key, std::min(position, cursor.ref.end_col()));\n\t}\n    };\n\n    // Cursor over all columns\n    // Supported if column major matrix\n    template <typename Elt, typename Parameters>\n    struct range_generator<glas::tag::col, compressed2D<Elt, Parameters> >\n      : boost::mpl::if_<\n\t    boost::is_same<typename Parameters::orientation, col_major>\n \t  , detail::all_cols_range_generator<compressed2D<Elt, Parameters>, complexity_classes::linear_cached>\n \t  , range_generator<tag::unsupported, compressed2D<Elt, Parameters> >\n        >::type {};\n\n\n    template <class Elt, class Parameters>\n    struct range_generator<glas::tag::nz, \n\t\t\t   detail::sub_matrix_cursor<compressed2D<Elt, Parameters>, glas::tag::col, 2> >\n    {\n\ttypedef typename Collection<compressed2D<Elt, Parameters> >::size_type  size_type;\n\ttypedef detail::sub_matrix_cursor<compressed2D<Elt, Parameters>, glas::tag::col, 2> cursor_type;\n\ttypedef complexity_classes::linear_cached         complexity;\n\ttypedef compressed_minor_cursor<Elt, Parameters>  type;\n\tstatic int const                                  level = 1;\n\n\ttype begin(cursor_type const& cursor) const\n\t{\n\t    return type(cursor.ref, cursor.ref.begin_row(), cursor.key);\n\t}\n\ttype end(cursor_type const& cursor) const\n\t{\n\t    return type(cursor.ref, cursor.ref.end_row(), cursor.key);\n\t}\n\ttype lower_bound(cursor_type const& cursor, size_type position) const\n\t{\n\t    return type(cursor.ref, std::min(position, cursor.ref.end_row()), cursor.key);\n\t}\n    };\n\n    // Cursor over all rows or columns, depending which one is major\n    template <typename Elt, typename Parameters>\n    struct range_generator<glas::tag::major, compressed2D<Elt, Parameters> >\n      : boost::mpl::if_<\n\t    boost::is_same<typename Parameters::orientation, row_major>\n\t  , range_generator<glas::tag::row, compressed2D<Elt, Parameters> >\n\t  , range_generator<glas::tag::col, compressed2D<Elt, Parameters> >\n        >::type {};\n\n\n// =============\n// For iterators\n// =============\n \n\n    template <class Elt, class Parameters>\n    struct range_generator<tag::const_iter::nz, \n\t\t\t   detail::sub_matrix_cursor<compressed2D<Elt, Parameters>, glas::tag::row, 2> >\n    {\n\ttypedef compressed2D<Elt, Parameters>                                         matrix_type;\n\ttypedef typename matrix_type::size_type                                       size_type;\n\ttypedef typename matrix_type::value_type                                      value_type;\n\ttypedef detail::sub_matrix_cursor<matrix_type, glas::tag::row, 2>             cursor;\n\t\n\ttypedef complexity_classes::linear_cached                                     complexity;\n\tstatic int const                                                              level = 1;\n\ttypedef const value_type*                                                     type;\n\t\n\ttype begin(cursor const& c)\n\t{\n\t    const matrix_type& matrix= c.ref;\n\t    size_type offset= matrix.indexer(matrix, c.key, matrix.begin_col());\n\t    return &matrix.data[0] + offset;\n\t}\n\t\n\t// returned pointer can pass the end and must only be used for comparison\n\ttype end(cursor const& c)\n\t{\n\t    const matrix_type& matrix= c.ref;\n\t    size_type offset= matrix.indexer(matrix, c.key, matrix.end_col());\n\t    return &matrix.data[0] + offset;\n\t}\t\n    };\n\n\n    template <class Elt, class Parameters>\n    struct range_generator<tag::const_iter::nz, \n\t\t\t   detail::sub_matrix_cursor<compressed2D<Elt, Parameters>, glas::tag::col, 2> >\n    {\n\ttypedef compressed2D<Elt, Parameters>                                         matrix_type;\n\ttypedef typename matrix_type::size_type                                       size_type;\n\ttypedef typename matrix_type::value_type                                      value_type;\n\ttypedef detail::sub_matrix_cursor<matrix_type, glas::tag::col, 2>             cursor;\n\t\n\ttypedef complexity_classes::linear_cached                                     complexity;\n\tstatic int const                                                              level = 1;\n\ttypedef const value_type*                                                     type;\n\t\n\ttype begin(cursor const& c)\n\t{\n\t    const matrix_type& matrix= c.ref;\n\t    size_type offset= matrix.indexer(matrix, matrix.begin_row(), c.key);\n\t    return &matrix.data[0] + offset;\n\t}\n\t\n\t// returned pointer can pass the end and must only be used for comparison\n\ttype end(cursor const& c)\n\t{\n\t    const matrix_type& matrix= c.ref;\n\t    size_type offset= matrix.indexer(matrix, matrix.end_row(), c.key);\n\t    return &matrix.data[0] + offset;\n\t}\t\n    };\n\n\n}} // namespace mtl::traits\n\n\n\n#endif // MTL_COMPRESSED2D_INCLUDE\n", "meta": {"hexsha": "2bc0da3f7ac274d778bdaf7fbf350bec1d657d86", "size": 47769, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/matrix/compressed2D.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/matrix/compressed2D.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/matrix/compressed2D.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": 35.7284966343, "max_line_length": 143, "alphanum_fraction": 0.6531013837, "num_tokens": 12194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800991636031, "lm_q2_score": 0.03514484652711669, "lm_q1q2_score": 0.017023464245894394}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <iterator>\n#include <numeric>\n#include <memory>\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"VNS.hpp\"\n#include \"Helper.hpp\"\n#include \"Solution.hpp\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n/*********************************************************************************/\n/*                                SHAKING PROCEDURES                             */\n/*********************************************************************************/\n\n// Creates Perturbed Solution S'\nvector<bool> VNS::shakingKOperations(\n\tconst vector<bool> &incumbent_solution,\n\tconst vector<double> &bi,\n\tconst vector<double> &dj,\n\tublas::matrix<double> &cij,\n\tconst double &k,\n\tdouble &fx)\n{\n\tsize_t last = 0, lastS = 0, counter = 0, i1 = 0, i2 = 0;\n\tvector<bool> perturbed_solution = incumbent_solution;\n\tdouble rnd = 0.0;\n\n\tvector<int> I_minus_S(incumbent_solution.size());\n\tvector<int> S(incumbent_solution.size());\n\n\t// I \\ S := all closed Facilities\n\tlast = 0;\n\tlastS = 0;\n\tfor (size_t index = 0; index != perturbed_solution.size(); ++index)\n\t\tif (perturbed_solution[index] == false)\n\t\t\tI_minus_S[last++] = index;\n\t\telse\n\t\t\tS[lastS++] = index;\n\tI_minus_S.erase(I_minus_S.begin() + last, I_minus_S.end());\n\tS.erase(S.begin() + lastS, S.end());\n\n\tdo\n\t{\n\t\t// Uniformed Random Value\n\t\trnd = get_random_double(0.0, 1.0);\n\n\t\t// i1 element S\n\t\tif (S.size() != 0)\n\t\t\ti1 = S[select_randomly(S)];\n\t\telse\n\t\t\ti1 = 0;\n\n\t\t// i2 element I \\ S\n\t\tif (I_minus_S.size() != 0)\n\t\t\ti2 = I_minus_S[select_randomly(I_minus_S)];\n\t\telse\n\t\t\ti2 = 0;\n\n\t\t// Drop\n\t\tif (rnd <= 0.2)\n\t\t{\n\t\t\tperturbed_solution[i1] = 0;\n\t\t\tI_minus_S.push_back(i1);\n\t\t}\n\t\t// Add\n\t\telse if (rnd >= 0.8)\n\t\t{\n\t\t\tperturbed_solution[i2] = 1;\n\t\t\tI_minus_S.erase(remove(\n\t\t\t\tI_minus_S.begin(), I_minus_S.end(), i2), I_minus_S.end());\n\t\t}\n\t\t// Swap\n\t\telse\n\t\t{\n\t\t\tperturbed_solution[i1] = 0;\n\t\t\tperturbed_solution[i2] = 1;\n\n\t\t\tI_minus_S.push_back(i1);\n\t\t\tI_minus_S.erase(remove(\n\t\t\t\tI_minus_S.begin(), I_minus_S.end(), i2), I_minus_S.end());\n\t\t}\n\n\t\tcounter++;\n\t} while (counter < k); // Repeat k-Times\n\n\t// If its in Shaking-Phase and not in creating N_k(S) \n\tif (fx != -1.0)\n\t{\n\t\tif (!canUpdateXij(bi, perturbed_solution, m_sum_dj))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\t// Check Solution if its not feasible return incumbent\n\t\tif (!updateXij(cij, dj, bi, perturbed_solution, m_update_xij_mode, fx))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\treturn perturbed_solution;\n\t}\n\n\treturn perturbed_solution;\n}\n\n// Creates Perturbed Solution S'\nvector<bool> VNS::shakingKMaxOperations(\n\tconst vector<bool> &incumbent_solution,\n\tconst vector<double> &bi,\n\tconst vector<double> &dj,\n\tublas::matrix<double> &cij,\n\tconst double &k,\n\tdouble &fx)\n{\n\tsize_t last = 0, lastS = 0, counter = 0, i1 = 0, i2 = 0;\n\tvector<bool> perturbed_solution = incumbent_solution;\n\tdouble rnd = 0.0;\n\n\tvector<int> I_minus_S(incumbent_solution.size());\n\tvector<int> S(incumbent_solution.size());\n\n\t// I \\ S := all closed Facilities\n\tlast = 0;\n\tlastS = 0;\n\tfor (size_t index = 0; index < perturbed_solution.size(); ++index)\n\t\tif (perturbed_solution[index] == false)\n\t\t\tI_minus_S[last++] = index;\n\t\telse\n\t\t\tS[lastS++] = index;\n\tI_minus_S.erase(I_minus_S.begin() + last, I_minus_S.end());\n\tS.erase(S.begin() + lastS, S.end());\n\n\tdo\n\t{\n\t\t// Uniformed Random Value\n\t\trnd = get_random_double(0.0, 1.0);\n\n\t\t// i1 element S\n\t\tif (S.size() != 0)\n\t\t\ti1 = S[select_randomly(S)];\n\t\telse\n\t\t\ti1 = 0;\n\n\t\t// i2 element I \\ S\n\t\tif (I_minus_S.size() != 0)\n\t\t\ti2 = I_minus_S[select_randomly(I_minus_S)];\n\t\telse\n\t\t\ti2 = 0;\n\n\t\t// Drop\n\t\tif (rnd <= 0.2)\n\t\t{\n\t\t\tperturbed_solution[i1] = 0;\n\t\t\tI_minus_S.push_back(i1);\n\t\t}\n\t\t// Add\n\t\telse if (rnd >= 0.8)\n\t\t{\n\t\t\tperturbed_solution[i2] = 1;\n\t\t\tI_minus_S.erase(remove(\n\t\t\t\tI_minus_S.begin(), I_minus_S.end(), i2), I_minus_S.end());\n\t\t}\n\t\t// Swap\n\t\telse\n\t\t{\n\t\t\tperturbed_solution[i1] = 0;\n\t\t\tperturbed_solution[i2] = 1;\n\n\t\t\tI_minus_S.push_back(i1);\n\t\t\tI_minus_S.erase(remove(\n\t\t\t\tI_minus_S.begin(), I_minus_S.end(), i2), I_minus_S.end());\n\t\t}\t\t\n\n\t\tcounter++;\n\t} while (counter < m_kMax); // Repeat k-Times\n\n\t// If its in Shaking-Phase and not in creating N_k(S) \n\tif (fx != -1.0)\n\t{\n\t\tif (!canUpdateXij(bi, perturbed_solution, m_sum_dj))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\t// Check Solution if its not feasible return incumbent\n\t\tif (!updateXij(cij, dj, bi, perturbed_solution, m_update_xij_mode, fx))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\treturn perturbed_solution;\n\t}\n\n\treturn perturbed_solution;\n}\n\n// Shaking Method from Kratica et al.\nvector<bool> VNS::shakingAssignments(\n\tconst vector<bool> &incumbent_solution,\n\tconst vector<double> &bi,\n\tconst vector<double> &dj,\n\tublas::matrix<double> &cij,\n\tconst double &k,\n\tdouble &fx)\n{\n\tunsigned int nh_mode = get_random_int(0, 2), i_out = 0, rand_indx = 0;\n\tdouble yi_sum = 0.0;\n\tsize_t last = 0, lastS = 0, counter = 0, i1 = 0, i2 = 0;\n\tvector<bool> perturbed_solution = incumbent_solution;\n\tdouble rnd = 0.0;\n\n\tvector<int> I_minus_S(incumbent_solution.size());\n\tvector<int> S(incumbent_solution.size());\n\n\t// I \\ S := all closed Facilities\n\tlast = 0;\n\tlastS = 0;\n\tfor (size_t index = 0; index < perturbed_solution.size(); ++index)\n\t\tif (perturbed_solution[index] == false)\n\t\t\tI_minus_S[last++] = index;\n\t\telse\n\t\t\tS[lastS++] = index;\n\tI_minus_S.erase(I_minus_S.begin() + last, I_minus_S.end());\n\tS.erase(S.begin() + lastS, S.end());\n\t\n\t// Swap\n\tif (nh_mode == 2)\n\t{\n\t\tfor (size_t c = 0; c != k; ++c)\n\t\t{\n\t\t\ti1 = S[select_randomly(S)];\n\t\t\ti2 = I_minus_S[select_randomly(I_minus_S)];\n\n\t\t\tperturbed_solution[i1] = 0;\n\t\t\tperturbed_solution[i2] = 1;\n\t\t}\n\t}\n\t// Close k-Min/Max and open Random\n\telse\n\t{\n\t\tvector<double> assignments(m_locationNumber, 0);\n\n\t\t// Save all assignments\n\t\tfor (size_t i = 0; i != m_flow_tpl.size(); ++i)\n\t\t{\n\t\t\tif (perturbed_solution[get<0>(m_flow_tpl[i])] == 1)\n\t\t\t{\n\t\t\t\tassignments[get<0>(m_flow_tpl[i])] += get<2>(m_flow_tpl[i]);\n\t\t\t}\n\t\t}\n\n\t\t// Index Sort Assignment list\n\t\tyi_sum = accumulate(incumbent_solution.begin(), incumbent_solution.end(), 0);\n\t\tvector<unsigned int> sorted_index;\n\n\t\tfor (size_t indx = 0; indx != perturbed_solution.size(); ++indx)\n\t\t{\n\t\t\tif (perturbed_solution[indx] == 1)\n\t\t\t{\n\t\t\t\tsorted_index.push_back(indx);\n\t\t\t}\n\t\t}\n\n\t\t// sorted_index Index list\n\t\tsort(begin(sorted_index), end(sorted_index),\n\t\t\t[&](int i1, int i2) { return assignments[i1] < assignments[i2]; });\n\n\t\tif (nh_mode == 1)\n\t\t{\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\tif (sorted_index.size() != 0 && c < perturbed_solution.size())\n\t\t\t\t{\n\t\t\t\t\t// Close k-Max\n\t\t\t\t\tif (c < sorted_index.size())\n\t\t\t\t\t\tperturbed_solution[sorted_index[c]] = 0;\n\t\t\t\t\t// Close k-Min\n\t\t\t\t\tif (sorted_index.size() - 1 - c >= 0)\n\t\t\t\t\t\tperturbed_solution[sorted_index[c]] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\trand_indx = select_randomly(perturbed_solution);\n\t\t\t\tperturbed_solution[rand_indx] = 1;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\tif (sorted_index.size() != 0 && c < perturbed_solution.size())\n\t\t\t\t{\n\t\t\t\t\t// Close k-Min\n\t\t\t\t\tif (sorted_index.size() - 1 - c >= 0)\n\t\t\t\t\t\tperturbed_solution[sorted_index[c]] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\trand_indx = select_randomly(perturbed_solution);\n\t\t\t\tperturbed_solution[rand_indx] = 1;\n\t\t\t}\n\t\t}\t\n\t}\n\n\t// If its in Shaking-Phase and not in creating N_k(S) \n\tif (fx != -1.0)\n\t{\n\t\tif (!canUpdateXij(bi, perturbed_solution, m_sum_dj))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\t// Check Solution if its not feasible return incumbent\n\t\tif (!updateXij(cij, dj, bi, perturbed_solution, m_update_xij_mode, fx))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\treturn perturbed_solution;\n\t}\n\n\treturn perturbed_solution;\n}\n\n// Modified Shaking Method from Kratica et al.\nvector<bool> VNS::shakingCosts(\n\tconst vector<bool> &incumbent_solution,\n\tconst vector<double> &bi,\n\tconst vector<double> &dj,\n\tublas::matrix<double> &cij,\n\tconst double &k,\n\tdouble &fx)\n{\n\tunsigned int nh_mode = get_random_int(0, 2), i_out = 0, rand_indx = 0;\n\tdouble yi_sum = 0.0;\n\tsize_t last = 0, lastS = 0, counter = 0, i1 = 0, i2 = 0;\n\tvector<bool> perturbed_solution = incumbent_solution;\n\tdouble rnd = 0.0;\n\n\tvector<int> I_minus_S(incumbent_solution.size());\n\tvector<int> S(incumbent_solution.size());\n\n\t// I \\ S := all closed Facilities\n\tlast = 0;\n\tlastS = 0;\n\tfor (size_t index = 0; index < perturbed_solution.size(); ++index)\n\t\tif (perturbed_solution[index] == false)\n\t\t\tI_minus_S[last++] = index;\n\t\telse\n\t\t\tS[lastS++] = index;\n\tI_minus_S.erase(I_minus_S.begin() + last, I_minus_S.end());\n\tS.erase(S.begin() + lastS, S.end());\n\n\t// Normal Operations\n\tif (nh_mode == 1)\n\t{\n\t\tfor (size_t c = 0; c != k; ++c)\n\t\t{\n\t\t\ti1 = S[select_randomly(S)];\n\t\t\ti2 = I_minus_S[select_randomly(I_minus_S)];\n\n\t\t\tperturbed_solution[i1] = 0;\n\t\t\tperturbed_solution[i2] = 1;\n\t\t}\n\t}\n\t// Close k-Min/Max and open Random\n\telse\n\t{\n\t\tvector<double> costs(m_locationNumber, 0);\n\n\t\t// Save all Costs per Facility\n\t\tfor (size_t i = 0; i != cij.size1(); ++i)\n\t\t{\n\t\t\tublas::matrix_row<ublas::matrix<double>> row_cij(cij, i);\n\n\t\t\t// For every xij link\n\t\t\tfor (size_t f = 0; f != m_flow_tpl.size(); ++f)\n\t\t\t{\n\t\t\t\tif (get<0>(m_flow_tpl[f]) == i)\n\t\t\t\t\tcosts[i] += row_cij[get<1>(m_flow_tpl[f])] * get<2>(m_flow_tpl[f]);\n\t\t\t}\n\t\t}\n\n\t\t// Index Sort Assignment list\n\t\tyi_sum = accumulate(perturbed_solution.begin(), perturbed_solution.end(), 0);\n\t\tvector<unsigned int> sorted_index;\n\n\t\tfor (size_t indx = 0; indx != perturbed_solution.size(); ++indx)\n\t\t{\n\t\t\tif (perturbed_solution[indx] == 1)\n\t\t\t{\n\t\t\t\tsorted_index.push_back(indx);\n\t\t\t}\n\t\t}\n\n\t\t// sorted_index Index list\n\t\tsort(begin(sorted_index), end(sorted_index),\n\t\t\t[&](int i1, int i2) { return costs[i1] < costs[i2]; });\n\n\t\tif (nh_mode == 1)\n\t\t{\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\tif (sorted_index.size() != 0 && c < perturbed_solution.size())\n\t\t\t\t{\n\t\t\t\t\t// Close k-Max\n\t\t\t\t\tif (c < sorted_index.size())\n\t\t\t\t\t\tperturbed_solution[sorted_index[c]] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\trand_indx = select_randomly(perturbed_solution);\n\t\t\t\t} while (perturbed_solution[rand_indx] == 0);\n\n\t\t\t\tperturbed_solution[rand_indx] = 1;\n\t\t\t}\n\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\tif (sorted_index.size() != 0 && c < perturbed_solution.size())\n\t\t\t\t{\n\t\t\t\t\t// Close k-Min\n\t\t\t\t\tif (sorted_index.size() - 1 - c >= 0)\n\t\t\t\t\t\tperturbed_solution[sorted_index[c]] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\trand_indx = select_randomly(perturbed_solution);\n\t\t\t\t} while (perturbed_solution[rand_indx] == 0);\n\n\t\t\t\tperturbed_solution[rand_indx] = 1;\n\t\t\t}\n\t\t}\n\t\t// nh-gap_mode == 2\n\t\telse\n\t\t{\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\tif (sorted_index.size() != 0 && c < perturbed_solution.size())\n\t\t\t\t{\n\t\t\t\t\t// Close k-Max\n\t\t\t\t\tif (c < sorted_index.size())\n\t\t\t\t\t\tperturbed_solution[sorted_index[c]] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (size_t c = 0; c != k; ++c)\n\t\t\t{\n\t\t\t\trand_indx = select_randomly(perturbed_solution);\n\t\t\t\tperturbed_solution[rand_indx] = 1;\n\t\t\t}\n\t\t}\t\n\t}\n\n\t// If its in Shaking-Phase and not in creating N_k(S) \n\tif (fx != -1.0)\n\t{\n\t\tif (!canUpdateXij(bi, perturbed_solution, m_sum_dj))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\t// Check Solution if its not feasible return incumbent\n\t\tif (!updateXij(cij, dj, bi, perturbed_solution, m_update_xij_mode, fx))\n\t\t{\n\t\t\tfx = m_best_fx;\n\t\t\treturn incumbent_solution;\n\t\t}\n\n\t\treturn perturbed_solution;\n\t}\n\n\treturn perturbed_solution;\n}", "meta": {"hexsha": "75641b3374e6e3ba0498c5fc992289eedc20156a", "size": 11638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VNS Implementierung/VNS Implementierung/Shaking.cpp", "max_stars_repo_name": "franneck94/Variable-Neighborhood-Search-FLP", "max_stars_repo_head_hexsha": "891cea0be1c3250cd9990eb35ef5701cb20bf964", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-05T08:26:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-05T08:26:52.000Z", "max_issues_repo_path": "VNS Implementierung/VNS Implementierung/Shaking.cpp", "max_issues_repo_name": "franneck94/Variable-Neighborhood-Search-FLP", "max_issues_repo_head_hexsha": "891cea0be1c3250cd9990eb35ef5701cb20bf964", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-28T09:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-28T09:54:53.000Z", "max_forks_repo_path": "VNS Implementierung/VNS Implementierung/Shaking.cpp", "max_forks_repo_name": "franneck94/Variable-Neighborhood-Search-FLP", "max_forks_repo_head_hexsha": "891cea0be1c3250cd9990eb35ef5701cb20bf964", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-05T08:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-02T09:21:54.000Z", "avg_line_length": 23.416498994, "max_line_length": 83, "alphanum_fraction": 0.6207252105, "num_tokens": 3801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800693903656, "lm_q2_score": 0.035144847790350965, "lm_q1q2_score": 0.017023463811404037}}
{"text": "﻿/***\r\n第六节 模板的一些特殊继承关系说\r\n（2）混入（Mixins）：是一种编程手法,用于描述类与类之间的一种关系。这种关系类似于多重继承，看起来更象颠倒过来的继承。\r\n混入的实现手段：把传入的模板参数当做该类模板的父类。\r\n\r\n（2.1）常规范例\r\n引入混入手段取代传统的继承，这种混入实现手段看起来更像是把某个或者某些类混合到当前类中凑成一个更大的类\r\nrole_npc的效果类似于：class role_npc :public role,public npcattr{...}\r\n\r\n（2.2）用参数化的方式表达成员函数的虚拟性:是一种设计理念\r\n一般来说，一个类如果做父类，那么它应该有析构函数并且这个析构函数都应该是一个虚函数。\r\n什么情况下父类中可以没有析构函数或者析构函数可以不为虚函数：\r\n(1)子类并没有析构函数（不需要在析构函数中释放任何new出来的数据）。\r\n(2)代码中不会出现父类指针指向子类对象（多态）的情形。\r\n\r\n为防止用父类指针new一个子类对象，可以把父类的析构函数用protected来修饰。\r\n有兴趣的同学：可以参考Boost库中的noncopyable类。\r\n*****/\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\n\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\nnamespace _nmsp1\r\n{\r\n\t//role角色类，代表玩家，包括攻击力，防御力，血量（生命值）：\r\n\t//class role\r\n\t//{\r\n\t//public:\r\n\t//\t//构造函数：\r\n\t//\trole() :m_attack(0.0), m_defence(0.0), m_life(100.0) {}//初始时攻击力防御力都为0，血量100；\r\n\t//\trole(double att,double def,double life):m_attack(att), m_defence(def), m_life(life) {}\r\n\r\n\t//public:\r\n\t//\tdouble m_attack; //攻击力\r\n\t//\tdouble m_defence; //防御力\r\n\t//\tdouble m_life;    //血量（生命值）\r\n\t//\t//......\r\n\t//};\r\n\t//class family\r\n\t//{\r\n\t//public:\r\n\t//\tvector<role> m_members;\r\n\t//\t//....其他信息\r\n\t//};\r\n\t//怪物、NPC（非玩家角色）。 NPC分类：0：代表装饰游戏场景的这种NPC，1：代表商人，卖服装。2：代表把游戏任务派送给玩家。  自言自语的说话。\r\n\t//template<typename T>\r\n\t//class family\r\n\t//{\r\n\t//public:\r\n\t//\t//vector<role> m_members;\r\n\t//\tvector<T> m_members;\r\n\t//\t//....其他信息\r\n\t//};\r\n\r\n\t//npc属性类\r\n\tstruct npcattr\r\n\t{\r\n\t\tint m_sort;          //npc种类：0：代表装饰游戏场景的这种NPC，1：代表商人，卖服装。2：代表把游戏任务派送给玩家。\r\n\t\tstd::string m_lang;  //记录自言自语的一句话\r\n\t};\r\n\r\n\t////NPC类\r\n\t//class role_npc :public role\r\n\t//{\r\n\t//public:\r\n\t//\t//构造函数\r\n\t//\trole_npc(): role(), m_strucattr{ 0,\"\" }{}\r\n\t//\trole_npc(double att, double def, double life, int sort, std::string lang) :role(att, def, life), m_strucattr{ sort,lang } {}\r\n\r\n\t//public:\r\n\t//\tnpcattr m_strucattr;\r\n\t//};\r\n\r\n\t//玩家角色属性系统，分为三种：力量，敏捷，体质。玩家每升一级，就能得到10个属性点。可以把属性点加到这三种属性上去\r\n\t//最终目的就是提高玩家攻击力，防御力，血量：每加一点力量，攻击力提高1.2，每加一点敏捷，防御力提高1.5。每加一点体质，血量增加0.6。\r\n\t//引入玩家属性类：\r\n\tstruct playerattr\r\n\t{\r\n\t\tint m_strength; //力量\r\n\t\tint m_agile;  //敏捷\r\n\t\tint m_constitution; //体质\r\n\t};\r\n\t////玩家类(真实玩家）\r\n\t//class role_player :public role\r\n\t//{\r\n\t//public:\r\n\t//\trole_player() : role(), m_strucattr{0,0,0}{}\r\n\t//\trole_player(double att, double def, double life, int sth, int agi,int cons)\r\n\t//\t\t\t\t:role(att, def, life), m_strucattr{ sth,agi,cons } {}\r\n\r\n\t//public:\r\n\t//\tplayerattr m_strucattr;\r\n\t//};\r\n\r\n\ttemplate <typename...T>\r\n\tclass role : public T... //把传入的模板参数当做该类模板的父类\r\n\t{\r\n\tpublic:\r\n\t\trole() : T()..., m_attack(0.0), m_defence(0.0), m_life(100.0) {}//初始时攻击力防御力都为0，血量100；\r\n\t\trole(double att, double def, double life) : T()..., m_attack(att), m_defence(def), m_life(life) {}\r\n\tpublic:\r\n\t\tdouble m_attack;  //攻击力\r\n\t\tdouble m_defence; //防御力\r\n\t\tdouble m_life;    //血量（生命值）\r\n\t};\r\n\r\n\ttemplate <typename...T>\r\n\tclass family\r\n\t{\r\n\tpublic:\r\n\t\tvector< role<T...> > m_members;\r\n\t\t//....其他信息\r\n\t};\r\n\r\n\tusing role_npc = role<npcattr>;\r\n\tusing role_player = role<playerattr>;\r\n\tusing role_mixnpc = role<npcattr, playerattr>; //通过混入技术方便的组合，自由的装配各种功能\r\n\r\n\tusing family_npc = family<npcattr>;\r\n}\r\n\r\nnamespace _nmsp2\r\n{\r\n\ttemplate <typename ... T>\r\n\tclass Base :public T...\r\n\t{\r\n\tpublic:\r\n\t\tvoid myfunc()\r\n\t\t{\r\n\t\t\tcout << \"Base::myfunc()执行了!\" << endl;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename ... T>\r\n\tclass Derived :public Base<T...>\r\n\t{\r\n\tpublic:\r\n\t\tvoid myfunc() //virtual\r\n\t\t{\r\n\t\t\tcout << \"Derived::myfunc()执行了!\" << endl;\r\n\t\t}\r\n\t};\r\n\r\n\tclass A\r\n\t{\r\n\t};\r\n\tclass AVir\r\n\t{\r\n\tpublic:\r\n\t\tvirtual void myfunc() {}\r\n\t};\r\n}\r\n\r\nnamespace _nmsp3\r\n{\r\n\tclass A\r\n\t{\r\n\tprotected:\r\n\t\t~A() {}\r\n\t};\r\n\tclass B :public A {};\r\n}\r\n\r\nint main()\r\n{\r\n\t_nmsp1::role_npc mynpc;\r\n\tmynpc.m_attack = 15;           //攻击\r\n\tmynpc.m_defence = 10;          //防御\r\n\tmynpc.m_life = 120;            //血量\r\n\tmynpc.m_sort = 1;              //npc种类\r\n\tmynpc.m_lang = \"Are You OK?\";  //NPC自言自语时玩家能看到的所说的话\r\n\r\n\r\n\t_nmsp1::family_npc myfamily;\r\n\tmyfamily.m_members.push_back(mynpc);\r\n\r\n\t/*\r\n\t_nmsp2::Base<_nmsp2::A> *pb1 = new _nmsp2::Derived<_nmsp2::A>; //父类指针指向子类对象\r\n\tpb1->myfunc(); //Base::myfunc()执行了!\r\n\r\n\r\n\t_nmsp2::Base<_nmsp2::AVir>* pb2 = new _nmsp2::Derived<_nmsp2::AVir>; //父类指针指向子类对象\r\n\tpb2->myfunc();  //Derived::myfunc()执行了!\r\n\t*/\r\n\r\n\t//_nmsp3::A* pa = new _nmsp3::B();\r\n\t//delete pa; //编译出错\r\n\t//\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "b3656e0eed97d51df32de6b2049f2bfa6ac05f18", "size": 4234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/219.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/219.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/219.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 21.4923857868, "max_line_length": 129, "alphanum_fraction": 0.6166745394, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968261942204597, "lm_q2_score": 0.08632348540087384, "lm_q1q2_score": 0.01699072310329941}}
{"text": "#include \"flamelet.h\"\n\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/lexical_cast.hpp>\n\nusing namespace Camflow;\nusing namespace std;\nusing namespace Gadgets;\n\nFlameLet::FlameLet\n(\n    CamAdmin& ca,\n    CamConfiguration& config,\n    CamControl& cc,\n    CamGeometry& cg,\n    CamProfile& cp,\n    CamSoot& cs,\n    Mechanism& mech\n)\n:\nCamSetup(ca, config, cc, cg, cp, cs, mech),\nstoichZ(stoichiometricMixtureFraction()),\ntimeHistory(false),\nsdrProfile(false),\nsdrAnalytic(false),\nradiation(NULL),\nscalarDissipationRate_(admin_.getInputFile(), stoichZ, reacGeom_.getAxpos(), 1),\nCpSpec(mCord,nSpc),\nsootResidualZeroed(false),\nLewis(admin_.getInputFile(),camMech_,mCord,nSpc)\n{}\n\nFlameLet::~FlameLet()\n{\n    if (radiation != NULL) delete radiation;\n}\n\nvoid FlameLet::checkSetup()\n{\n\n    if (reacGeom_.getAxpos()[mCord-1] != 1)\n        throw std::invalid_argument(\"Mixture fraction does not go from 0 to 1. \"\n                                    \"Check <length unit=\\\"m\\\">1.0</length>\\n\");\n\n    if (stoichZ <= 0.0)\n        throw std::invalid_argument(\"The stoichiometric mixture fraction is not\"\n                                    \" a positive double!\");\n\n}\n\n/*\n*this is called by the model object. The boolean interface decides\n*if the call originates from the interface or from camflow kernel\n*/\nvoid FlameLet::setRestartTime(double t){\n    restartTime = t;\n}\n\nvoid FlameLet::solve()\n{\n    solve(false);\n}\n\n/*\n* Use this call method when calling from openFoam.\n* if sootResidualZeroed is TRUE then, flamelet will\n* be solved to steady state and with soot residual set to zero.\n* (i.e. no soot present at base of flame)\n*\n* When calling the Lagrangian Flamelet (i.e. dynamic)\n* do this via restart() and set steadyStateAtFlameBase to FALSE\n*/\nvoid FlameLet::solve(bool interface, bool steadyStateNoSoot)\n{\n    sootResidualZeroed = steadyStateNoSoot;\n    solve(interface);\n}\n\n\nvoid FlameLet::solve\n(\n    bool interface\n)\n{\n\n    // Check that the problem has been setup properly.\n    checkSetup();\n\n    /*\n    *init the solution vector\n    */\n\n    initSolutionVector();\n\n    reporter_->header(\"Flamelet\");\n\n    if(!interface)\n    {\n        reportToFile(\"initialProfile.dat\",control_.getMaxTime(),solvect);\n        //writeXMLFile(scalarDissipationRate_.getRefSDR(), solvect);\n\n        // Write the molecular weights of species to file.\n        // (This file needed for streamline post processing)\n        std::ofstream file(\"SystemMWs.dat\");\n        for (int l=0; l<nSpc; l++)\n        {\n            file << (*spv_)[l]->Name() << \"\\t\";\n            file << (*spv_)[l]->MolWt() << std::endl;\n        }\n        file.close();\n    }\n\n    if (control_.getSolutionMode() == control_.COUPLED)\n    {\n        csolve(interface);   //ank25:temp while testing splitSolve\n        //splitSolve(interface);\n    }\n    else\n    {\n        ssolve(interface);\n        csolve(interface);\n    }\n\n    if (admin_.getRestartType() == admin_.BINARY)\n    {\n        std::ofstream ofs(admin_.getRestartFile().c_str());\n        boost::archive::binary_oarchive oa(ofs);\n        oa << reacGeom_.getAxpos() << solvect;\n        ofs.close();\n    }\n}\n\n\n/**\n*continuation call from an external code that\n*solves for population balance\n*/\nvoid FlameLet::solve\n(\n    vector<Thermo::Mixture>& cstrs,\n    const vector<vector<double> >& iniSource,\n    const vector<vector<double> >& fnlSource,\n    Mechanism& mech,\n    CamControl& cc,\n    CamAdmin& ca,\n    CamGeometry& cg,\n    CamProfile& cp\n)\n{\n\n    reacGeom_.addZeroWidthCells();\n\n    /*\n    *set the source terms for the particle process\n    */\n    setParticleSource(iniSource,fnlSource);\n\n    /*\n    *  reset the solution vector. cstrs contain only\n    *  the interor cells. The inlet condisions need to\n    *  be taken care of.\n    */\n    CamBoundary& left = admin_.getLeftBoundary();\n    CamBoundary& right = admin_.getRightBoundary();\n    storeInlet(left,fuel);\n    storeInlet(right,oxid);\n    fuel.T = left.getTemperature();\n    oxid.T = right.getTemperature();\n\n    solvect.clear();\n    solvect.resize(nEqn,0.0);\n\n    /**!\n    *  Inlet  boundary ie. z=0\n    *  this is the oxidizer\n    */\n    //Species\n    for(int l=0; l<nSpc; l++){\n        solvect[l] = oxid.Species[l];\n    }\n    solvect[ptrT] = oxid.T;\n\n    /**!\n    *  Interior mesh points\n    */\n    for(int i=iMesh_s; i<iMesh_e;i++){\n        vector<double> massFrac;\n        cstrs[i-1].GetMassFractions(massFrac);\n        for(int l=0; l<nSpc; l++){\n            solvect[i*nVar+l] = massFrac[l];\n        }\n        //Temperature\n        solvect[i*nVar+ptrT] = cstrs[i-1].Temperature();\n    }\n\n    /**\n    *  outlet boundary\n    *  this is the fuel inlet\n    */\n    //Species\n    for(int l=0; l<nSpc; l++){\n        solvect[iMesh_e*nVar+l] = fuel.Species[l];\n    }\n    //Temperature\n    solvect[iMesh_e*nVar+ptrT] = fuel.T;\n\n\n}\n\n\nvoid FlameLet::initSolutionVector()\n{\n\n    // Initialise the radiation class if necessary.\n    if(admin_.getRadiationModel())\n    {\n        radiation = new Radiation\n        (\n            admin_.getInputFile(),\n            mCord,\n            camMech_,\n            avgMolWt,\n            s_mf\n        );\n    }\n\n    /*\n    *left boundary is for the fuel and right boundary is\n    *for oxidizer\n    */\n    CamBoundary& left = admin_.getLeftBoundary();\n    CamBoundary& right = admin_.getRightBoundary();\n    storeInlet(left,fuel);\n    storeInlet(right,oxid);\n\n    profile_.setMixingCenter(stoichZ);\n    profile_.setMixingWidth(0.5*stoichZ);\n    /*\n    *initialize the ODE vector\n    */\n    solvect.resize(nEqn,0.0);\n    vector<double> vSpec, vT, vMom_rho;\t\t// ank25: Solve Mr/rho and not Mr in soot flamelet\n    /*\n    * actual signature follows (left,right,cc,vSpec)\n    * but in the case of flamelets the species mass fractions\n    * are solved for the mixture fraction coordinate, whose\n    * direction is taken the same as physical space.\n    * z=0 corresponds to oxidizer and z=1 corresponds to fuel\n    * therefore the inlets are interchanged here to initialize\n    * the species vector properly\n    */\n    vSpec = initSpecies(right,left);\n    /*\n    *the following will initialize the temperature vector with\n    *a linear profile\n    */\n    //initTempGauss(vT);\n    double inrsctOx, inrsctFl;\n    double slopeOx, slopeFl;\n    inrsctOx = oxid.T;\n\n    slopeOx = (2000.0-oxid.T)/stoichZ;\n    slopeFl = (2000.0-fuel.T)/(stoichZ-1.0);\n    inrsctFl = fuel.T - slopeFl;\n    vector<double> position = reacGeom_.getAxpos();\n    int len = position.size();\n    vT.resize(len,0.0);\n    for (size_t i=0; i<dz.size();i++)\n    {\n        if (position[i] < stoichZ)\n        {\n            vT[i] = slopeOx*position[i] + inrsctOx;\n        }\n        else\n        {\n            vT[i] = slopeFl*position[i] + inrsctFl;\n        }\n    }\n\n    if(profile_.flagLoadTemp())\n    {\n        // Loop over all points, EXCLUDING boundaries\n        for (size_t i=1; i<dz.size()-1; i++)\n        {\n            vT[i] = profile_.getUserDefTemp(position[i]);\n        }\n    }\n\n    if(profile_.flagLoadFracs())\n    {\n        // Loop over all points, EXCLUDING boundaries\n        for (size_t i=cellBegin+1; i<cellEnd-1; ++i)\n        {\n            for (size_t l=0; l<nSpc; ++l)\n            {\n                vSpec[i*nSpc+l] = profile_.getUserDefFracs(position[i],(*spv_)[l]->Name());\n            }\n        }\n    }\n    /*\n    *fix the temperature for mixture fraction zero\n    *i.e oxidizer inlet\n    */\n    vT[0] =oxid.T;\n\n    /*\n    *fix the temperature for mixture fraction 1.\n    *i.e the fuel inlet\n    */\n    vT[iMesh_e] = fuel.T;\n\n    // Set the initial moment values (interior and boundary)\n    // Also initial constants\n    if (sootMom_.active())\n    {\n        vMom_rho.resize(len*nMoments,0.0);\n        for (size_t i=0; i<dz.size(); i++)\n        {\n\n            // ank25: Temp. Hard wire initial moment values.\n            //vMom[i*nMoments] = 1.0e10;\n            //vMom[i*nMoments+1] = 1.0e10;\n            //vMom[i*nMoments+2] = 1.0e10;\n\n\n            vMom_rho[i*nMoments] = sootMom_.getFirstMoment();\n            //cout << \"vMom[i*nMoments]  \" << i*nMoments <<\"  \"  << vMom[i*nMoments] << endl;\n            for (size_t l=1; l<nMoments; ++l)\n            {\n                // ank25: Do we need to multiply by 1e6 here?\n                //vMom[i*nMoments+l] = vMom[i*nMoments+l-1] + 1e6 * log(double(sootMom_.getAtomsPerDiamer()));\n                vMom_rho[i*nMoments+l] = vMom_rho[i*nMoments+l-1] * 1e3;\n                //cout << \"vMom[i*nMoments+l]  \" << i*nMoments+l <<\"  \" << vMom[i*nMoments+l] << endl;\n            }\n\n        }\n\n\n        // Call the soot constants function\n        sootMom_.initMomentsConstants(*camMech_);\n    }\n\n\n    /*\n    *create the actual solution vector by merging the species\n    *vector, the temperature vector, and soot vector (if present)\n    */\n\n    mergeSpeciesVector(&vSpec[0]);\n    mergeEnergyVector(&vT[0]);\n    if (sootMom_.active())\n    {\n        mergeSootMoments(&vMom_rho[0]);\n    }\n\n    if (admin_.getRestartType() == admin_.BINARY)\n    {\n        std::vector<double> solvect_temp, mixFracCoords_temp;\n        std::ifstream ifs(admin_.getRestartFile().c_str());\n        if (ifs.good())\n        {\n            boost::archive::binary_iarchive oi(ifs);\n            oi >> mixFracCoords_temp >> solvect_temp;\n\n            if (mixFracCoords_temp.size() == reacGeom_.getAxpos().size())\n            {\n                // If the size of solvect_temp is not equal to nVar*cellEnd\n                // then we assume that the binary file was previously\n                // generated with soot moments switched off.  In that case\n                // load species and temperature from binary file, but don't\n                // load up moments.\n\n                if \t(solvect_temp.size() == nVar*cellEnd)\n                {\n                    std::cout << \"Loading species, temperature and moments from bin file\"\n                                        << std::endl;\n                    solvect = solvect_temp;\n                }\n                else\n                {\n                    std::cout << \"Loading species and temperature from binary file\" << std::endl;\n                    std::cout << \"Not loading moments from binary file. \" << std::endl;\n                    for(int i=0; i<cellEnd; i++)\n                    {\n                    for(int l=0; l<nSpc; l++)\n                        solvect[i*nVar+l] = solvect_temp[i*(nVar-nMoments)+l];\n                    solvect[i*nVar+ptrT] = solvect_temp[i*(nVar-nMoments)+ptrT];\n                    }\n                }\n            }\n            else\n            {\n                throw std::runtime_error\n                (\n                    \"The solution vector is not the same size \"\n                    \"as the old one you are trying to read in. The old solution \"\n                    \"should be interpolated onto the new grid but that function \"\n                    \"has not been written yet.\\n\");\n            }\n        }\n    }\n    else if (admin_.getRestartType() == admin_.TEXT)\n    {\n        throw std::runtime_error(\"Text restart files not used yet.\");\n    }\n\n}\n\n/*\n*coupled solver\n*/\nvoid FlameLet::csolve\n(\n    bool interface\n)\n{\n\n    if (solverID == control_.CVODE)\n    {\n        CVodeWrapper cvw;\n        eqn_slvd = EQN_ALL;\n        int band = nVar*2;\n\n        // Output the tolerances\n        // control_.setResTol(1.e-04);\n        cout << \"Species Abs  Tol: \" << control_.getSpeciesAbsTol() << endl;\n        cout << \"Species Rel Tol: \" << control_.getSpeciesRelTol() << endl;\n        cout << \"Residual Tol: \" << control_.getResTol() << endl;\n\n        cvw.init(nEqn,solvect,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n            control_.getMaxTime(),band,*this);\n\n        //cvw.initVectorTol(nEqn,solvect,atolVector,control_.getSpeciesRelTol(),\n        //\t\tcontrol_.getMaxTime(),band,*this);\n\n        cvw.solve(CV_ONE_STEP,control_.getResTol());\n\n        // Calculate the mixture viscosity.\n        for (int i=0; i<mCord; ++i)\n        {\n            std::vector<double> mf;\n            for(int l=0; l<nSpc; l++)\n            {\n                mf.push_back(solvect[i*nVar+l]);\n            }\n            camMixture_->SetMassFracs(mf);\n            camMixture_->SetTemperature(m_T[i]);\n            camMixture_->SetMassDensity(m_rho[i]);                      //density\n            m_mu[i] = camMixture_->getViscosity();                      //mixture viscosity\n        }\n\n        /*\n        *write the output to file only if the call is not\n        *from the interface\n        */\n        if(!interface)\n        {\n            reportToFile(\"profile.dat\",control_.getMaxTime(), solvect);\n            //writeXMLFile(scalarDissipationRate_.getStoichSDR(), solvect);\n        }\n\n    }\n    else if (solverID == control_.NEWTON)\n    {\n        std::cout << \"Not implemented\\n\";\n    }\n    else if (solverID == control_.RADAU)\n    {\n\n        RadauWrapper radauWrapper;\n\n        eqn_slvd = EQN_ALL;\n\n        std::vector<double> relTolVector;\n        std::vector<double> absTolVector;\n\n        relTolVector.push_back(control_.getSpeciesRelTol());\n        absTolVector.push_back(control_.getSpeciesAbsTol());\n\n        radauWrapper.setBandWidth(nVar);\n\n        radauWrapper.initSolver(nEqn,\n                                0.0,\n                                control_.getMaxTime(),\n                                solvect,\n                                relTolVector,\n                                absTolVector,\n                                *this);\n\n        radauWrapper.Integrate();\n\n        /*\n        *write the output to file only if the call is not\n        *from the interface\n        */\n        if(!interface) {\n            reportToFile(\"profile.dat\", control_.getMaxTime(), solvect);\n        }\n\n    }\n    else if (solverID == control_.LIMEX)\n    {\n        throw std::logic_error(\"Error -- Limex is not yet supported\");\n    }\n\n}\n\n/*\n*mass matrix evaluation\n*/\nvoid FlameLet::massMatrix(double** M)\n{}\n\n/*\n*restart the solution. This is normally called from the interface routine\n*The solver is reinitialized each time with the previous solution.\n*/\nvoid FlameLet::restart(double flameTime)\n{\n    // Assumption is that a restart is always a Lagrangian flamelet (i.e. not steady state)\n    //steadyStateAtFlameBase = false;\n\n\n    // Stop calculating soot above a user specified flamelet time.\n    if (flameTime < Lewis.sootFlameTimeThreshold)\n    {\n        // Still below the time at which we stop calculating soot residual\n        sootResidualZeroed = false;\n        std::cout << \"Soot residual is active \" << std::endl;\n    }\n    else\n    {\n        // Past the time, beyond which we no longer calculate soot.\n        sootResidualZeroed = true;\n        std::cout << \"Soot residual is zeroed out \" << std::endl;\n    }\n\n    if (solverID == control_.CVODE) {\n        CVodeWrapper cvw;\n        eqn_slvd = EQN_ALL;\n        int band = nVar*2;\n\n        cvw.init(nEqn,solvect,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n            control_.getMaxTime(),band,*this,restartTime);\n\n        // When restarting don't call cvw.solve with a global tolerance\n        // as a stop criteria.  We are solving dynamic flamelets and don't\n        // want to stop at steady state.\n        cvw.solve(CV_ONE_STEP);\n        // Calculate the mixture viscosity.\n        for (int i=0; i<mCord; ++i)\n        {\n            std::vector<double> mf;\n            for(int l=0; l<nSpc; l++)\n            {\n                mf.push_back(solvect[i*nVar+l]);\n            }\n            camMixture_->SetMassFracs(mf);\n            camMixture_->SetTemperature(m_T[i]);\n            camMixture_->SetMassDensity(m_rho[i]);                      //density\n            m_mu[i] = camMixture_->getViscosity();                      //mixture viscosity\n        }\n\n        /*\n        *write the output to file only if the call is not\n        *from the interface\n        */\n        //if(!interface)\n        //{\n            string filename = \"interfaceProfiles/profile\"+boost::lexical_cast<std::string>(restartTime)+\".dat\";\n            reportToFile(filename,control_.getMaxTime(), solvect);\n            if (sootMom_.active())\n            {\n                string filenameSoot = \"interfaceSootRates/sootRatesProfile\"+boost::lexical_cast<std::string>(restartTime)+\".dat\";\n                reportSootRatesToFile(filenameSoot,control_.getMaxTime(), sootComponentRatesAllCells);\n            }\n        //}\n    }\n    else if (solverID == control_.LIMEX) {\n        throw std::logic_error(\"Error -- Limex is not yet supported\");\n    }\n\n}\n\n/*\n*segregated solver\n*/\nvoid FlameLet::ssolve\n(\n    bool interface\n)\n{\n\n    int seg_eqn, band;\n    vector<double> seg_soln_vec;\n\n    if ( solverID == control_.CVODE){\n\n    CVodeWrapper cvw;\n\n    for (int i=0; i<control_.getNumIterations();i++){\n\n        /*\n            *solve soot moment equations\n            */\n        if (sootMom_.active())\n        {\n            cout << \"Solving moment equations  \" << i << endl;\n            //int dd; cin >> dd;\n            eqn_slvd = EQN_MOMENTS;\n            seg_eqn = nMoments*mCord;\n            band = nMoments*2;\n            extractSootMoments(seg_soln_vec);\n            // Might need to change tolerances for moments\n            cvw.init(seg_eqn,seg_soln_vec,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n                control_.getMaxTime(),band,*this,0.0);\n            cvw.solve(CV_ONE_STEP,control_.getResTol());\n            mergeSootMoments(&seg_soln_vec[0]);\n        }\n\n        /*\n        *solve species equations\n        */\n        cout << \"Solving species equations  \" << i << endl;\n        //int dd; cin >> dd;\n        eqn_slvd = EQN_SPECIES;\n        seg_eqn = nSpc*mCord;\n        band = nSpc*2;\n        extractSpeciesVector(seg_soln_vec);\n        cvw.init(seg_eqn,seg_soln_vec,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n            control_.getMaxTime(),band,*this,0.0);\n        cvw.solve(CV_ONE_STEP,control_.getResTol());\n        mergeSpeciesVector(&seg_soln_vec[0]);\n\n        /*\n        *solve energy equation\n        */\n        cout << \"Solving energy equation  \" << i << endl;\n        //cin >> dd;\n        eqn_slvd = EQN_ENERGY;\n        seg_eqn = mCord;\n        band = 1;\n        extractEnergyVector(seg_soln_vec);\n        cvw.init(seg_eqn,seg_soln_vec,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n            control_.getMaxTime(),band,*this,0.0);\n        cvw.solve(CV_ONE_STEP,control_.getResTol());\n        mergeEnergyVector(&seg_soln_vec[0]);\n\n    }\n\n    // Calculate the mixture viscosity.\n    for (int i=0; i<mCord; ++i)\n    {\n        std::vector<double> mf;\n        for(int l=0; l<nSpc; l++)\n        {\n            mf.push_back(solvect[i*nVar+l]);\n        }\n        camMixture_->SetMassFracs(mf);\n        camMixture_->SetTemperature(m_T[i]);\n        camMixture_->SetMassDensity(m_rho[i]);                      //density\n        m_mu[i] = camMixture_->getViscosity();                      //mixture viscosity\n    }\n\n    /*\n    *write the output to file only if the call is not\n        *from the interface\n    */\n    if(!interface)\n    {\n        reportToFile(\"profile.dat\",control_.getMaxTime(), solvect);\n        //writeXMLFile(scalarDissipationRate_.getStoichSDR(), solvect);\n    }\n    }\n\n    else if (solverID == control_.LIMEX) {\n        throw std::logic_error(\"Error -- Limex is not yet supported\");\n    }\n}\n//----------------------\n\n/*\n*splitting solver\n*/\nvoid FlameLet::splitSolve\n(\n    bool interface\n)\n{\n\n    int seg_eqn, band;\n    vector<double> seg_soln_vec;\n\n    // Get the time to which we are integrating.\n    double nextTime = control_.getMaxTime();\n\n    // Break this time step into Nsteps small steps\n    // todo: Get NSteps via function call and ultimately from xml file or similar\n    // Note: The assumption here is that the current (or initial time) is t=0.\n    // This seems to be always be the case when solving flamlets.\n    // This is even true when calling via the interface as the integration occurs\n    // over tau.\n\n    // NOT TRUE:  Flamelet restart has a restart time.  Fix this !!\n\n    int Nsteps = 100;\n    double deltaTime = nextTime / (double)Nsteps;\n    double intermediateTime = 0.0 ;\n\n    if ( solverID == control_.CVODE){\n\n    CVodeWrapper cvw;\n\n    //for (int i=0; i<control_.getNumIterations();i++){\n    for (int i=0; i<Nsteps;i++){\n\n        // Set the integration time\n        nextTime = intermediateTime + deltaTime;\n\n\n        // solve species equations\n        cout << \"Solving species equations  \" << i << endl;\n        //int dd; cin >> dd;\n        eqn_slvd = EQN_SPECIES;\n        seg_eqn = nSpc*mCord;\n        band = nSpc*2;\n        extractSpeciesVector(seg_soln_vec);\n\n        cvw.init(seg_eqn,seg_soln_vec,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n                nextTime,band,*this,intermediateTime);\n\n        cvw.solve(CV_ONE_STEP); //,control_.getResTol());\n\n        mergeSpeciesVector(&seg_soln_vec[0]);\n\n\n        //solve energy equation\n        cout << \"Solving energy equation  \" << i << endl;\n        //cin >> dd;\n        eqn_slvd = EQN_ENERGY;\n        seg_eqn = mCord;\n        band = 1;\n        extractEnergyVector(seg_soln_vec);\n\n        cvw.init(seg_eqn,seg_soln_vec,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n                nextTime,band,*this,intermediateTime);\n\n        cvw.solve(CV_ONE_STEP); //,control_.getResTol());\n\n        mergeEnergyVector(&seg_soln_vec[0]);\n/*\n\n        // solve combined species and energy equations\n        cout << \"Solving species and energy equations  \" << i << endl;\n        //int dd; cin >> dd;\n        eqn_slvd = EQN_SPECIES_ENERGY;\n        seg_eqn = (nSpc+1)*mCord;\n        band = (nSpc+1)*2;\n        extractSpeciesAndEnergyVector(seg_soln_vec);\n\n        cvw.init(seg_eqn,seg_soln_vec,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n                nextTime,band,*this,intermediateTime);\n\n        cvw.solve(CV_ONE_STEP,control_.getResTol());\n\n        mergeSpeciesAndEnergyVector(&seg_soln_vec[0]);\n\n*/\n        /*\n        *solve soot moment equations\n        */\n        if (sootMom_.active())\n        {\n        cout << \"Solving moment equations  \" << i << endl;\n        //int dd; cin >> dd;\n        eqn_slvd = EQN_MOMENTS;\n        seg_eqn = nMoments*mCord;\n        band = nMoments*2;\n        extractSootMoments(seg_soln_vec);\n        // Might need to change tolerances for moments\n        cvw.init(seg_eqn,seg_soln_vec,control_.getSpeciesAbsTol(),control_.getSpeciesRelTol(),\n                nextTime,band,*this,intermediateTime);\n\n        cvw.solve(CV_ONE_STEP); //,control_.getResTol());\n\n        mergeSootMoments(&seg_soln_vec[0]);\n        }\n\n        // Increment time\n        intermediateTime = intermediateTime + deltaTime;\n\n    }\n\n    // Calculate the mixture viscosity.\n    for (int i=0; i<mCord; ++i)\n    {\n        std::vector<double> mf;\n        for(int l=0; l<nSpc; l++)\n        {\n            mf.push_back(solvect[i*nVar+l]);\n        }\n        camMixture_->SetMassFracs(mf);\n        camMixture_->SetTemperature(m_T[i]);\n        camMixture_->SetMassDensity(m_rho[i]);                      //density\n        m_mu[i] = camMixture_->getViscosity();                      //mixture viscosity\n    }\n\n    /*\n    *write the output to file only if the call is not\n        *from the interface\n    */\n    if(!interface)\n    {\n        reportToFile(\"profile.dat\",control_.getMaxTime(), solvect);\n        //writeXMLFile(scalarDissipationRate_.getStoichSDR(), solvect);\n    }\n    }\n    else if (solverID == control_.LIMEX) {\n        throw std::logic_error(\"Error -- Limex is not yet supported\");\n    }\n}\n\n//----------------------\n\n/*\n*residual definitions\n*/\nvoid FlameLet::residual\n(\n    const double& t,\n    double* y,\n    double* f\n)\n{\n\n    if (eqn_slvd == EQN_ALL) // coupled solver part\n    {\n        saveMixtureProp(y);\n        speciesResidual(t,y,&resSp[0]);\n        energyResidual(t,y,&resT[0]);\n        if (sootMom_.active())\n        {\n            if (sootResidualZeroed)\n            {\n                sootMomentResidualZeroedOut(t,y,&resMom[0]);\n            }\n            else\n            {\n                sootMomentResidual(t,y,&resMom[0]);\n            }\n        }\n\n\n        for (int i=0; i<mCord; ++i)\n        {\n            // Put species residual into master residual\n            for (int l=0; l<nSpc; ++l)\n            {\n                f[i*nVar+l] = resSp[i*nSpc+l];\n            }\n\n            // Put temperature into master residual\n            f[i*nVar+ptrT] = resT[i];\n\n            if (sootMom_.active())\n            {\n                // Put moments into master residual\n                for (int l=0; l<nMoments; ++l)\n                {\n                    f[i*nVar+ptrT+1+l] = resMom[i*nMoments+l];\n                }\n            }\n\n        }\n    }\n    else // segregated solver part\n    {\n        if (eqn_slvd == EQN_SPECIES)\n        {\n            mergeSpeciesVector(y);\n            saveMixtureProp(&solvect[0]);\n            speciesResidual(t,y,f);\n        }\n        else if (eqn_slvd==EQN_ENERGY)\n        {\n            mergeEnergyVector(y);\n            saveMixtureProp(&solvect[0]);\n            energyResidual(t,y,f);\n        }\n        else if (eqn_slvd==EQN_SPECIES_ENERGY)\n        {\n            mergeSpeciesAndEnergyVector(y);\n            saveMixtureProp(&solvect[0]);\n            speciesResidual(t,y,&resSp[0]);\n            energyResidual(t,y,&resT[0]);\n            for (int i=0; i<mCord; ++i)\n            {\n                // Put species residual into master residual\n                for (int l=0; l<nSpc; ++l)\n                {\n                    f[i*nSpc+l] = resSp[i*nSpc+l];\n                }\n                // Put temperature into master residual\n                f[i*nSpc+ptrT] = resT[i];\n            }\n        }\n\n        else if (eqn_slvd==EQN_MOMENTS)\n        {\n            mergeSootMoments(y);\n            saveMixtureProp(&solvect[0]);\n            if (sootResidualZeroed)\n            {\n                sootMomentResidualZeroedOut(t,y,&resMom[0]);\n            }\n            else\n            {\n                sootMomentResidual(t,y,&resMom[0]);\n            }\n        }\n    }\n\n    // Refine Grid\n    //if(getResidual() < 1e-6)\n    //{\n    //    reacGeom->refine(y,nVar,nSpc,ptrT);\n    //}\n\n}\n\ndouble FlameLet::getResidual()\nconst\n{\n\n    double resNorm=0;\n\n    for (int i=0; i<nSpc*mCord; ++i)\n    {\n        resNorm += resSp[i]*resSp[i];\n    }\n    for (int i=0; i<mCord; ++i)\n    {\n        resNorm += resT[i]*resT[i];\n    }\n    if (sootMom_.active())\n    {\n        for (int i=0; i<nMoments*mCord; ++i)\n        {\n            resNorm += resMom[i]*resMom[i];\n        }\n    }\n\n    return std::sqrt(resNorm);\n\n}\n\n/*\n*species residual definitions\n*/\nvoid FlameLet::speciesResidual\n(\n    const double& t,\n    double* y,\n    double* f\n)\n{\n\n    double grad_e, grad_w;\n    double zPE, zPW;\n    double sdr, sdrPE, sdrPW;\n    double source;\n    double deltax = 0;\n\n    /*\n    *starting with mixture fraction zero: i.e oxidizer\n    *inlet. The fuel composition is zero. Left inlet is\n    *considered as the oxidizer inlet and the concentrations\n    *are held constant\n    */\n\n    for (int l=0; l<nSpc; ++l)\n    {\n        f[l] = 0.0;\n    }\n\n    /*for (int l=0; l<nSpc; ++l)\n    {\n        // Computation at the i = 0 end of the grid\n        convection(0,l) = oneby16*(1.0/Le(0,l)-1)*4*(s_mf(1,l)-s_mf(0,l))*(m_rho[1]-m_rho[0]);\n\n        // Computation at the i = mCord - 1 end of the grid\n        convection(mCord-1,l) = oneby16*(1.0/Le(mCord-1,l)-1)*4*(s_mf(mCord-1,l)-s_mf(mCord-2,l))*(m_rho[mCord-1]-m_rho[mCord-2]);\n    }*/\n\n    /*\n    *interior mixture fraction coordinates\n    */\n    for (int i=iMesh_s; i<iMesh_e; ++i)\n    {\n\n        zPE = 0.5*(dz[i]+dz[i+1]);\n        zPW = 0.5*(dz[i]+dz[i-1]);\n        deltax = zPE + zPW;\n\n        sdr = scalarDissipationRate_(reacGeom_.getAxpos()[i],t);\n\n        double diffusionConstant = sdr/(2.0*dz[i]);\n        for (int l=0; l<nSpc; ++l)\n        {\n            grad_e = (s_mf(i+1,l)-s_mf(i,l))/zPE;\n            grad_w = (s_mf(i,l)-s_mf(i-1,l))/zPW;\n            source = s_Wdot(i,l)/m_rho[i];\n            f[i*nSpc+l] = diffusionConstant*(grad_e-grad_w)/Lewis(i,l)\n                        + source;\n        }\n\n        if (   admin_.getFlameletEquationType() == admin_.COMPLETE\n            && Lewis.type() != LewisNumber::UNITY)\n        {\n            sdrPE = scalarDissipationRate_(reacGeom_.getAxpos()[i+1],t);\n            sdrPW = scalarDissipationRate_(reacGeom_.getAxpos()[i-1],t);\n\n            double convectionConstant\n                    = 0.25/m_rho[i]\n                        *(\n                            (m_rho[i+1]*sdrPE - m_rho[i-1]*sdrPW)/deltax\n                        +(m_rho[i]*sdr*m_cp[i]/m_k[i])\n                            *(m_k[i+1]/m_cp[i+1] - m_k[i-1]/m_cp[i-1])/deltax\n                        );\n\n            for (int l=0; l<nSpc; ++l)\n            {\n                f[i*nSpc+l] +=\n                convectionConstant\n                *((1.0/Lewis(i,l))-1.0)\n                *(s_mf(i+1,l)-s_mf(i-1,l))/deltax;\n            }\n        }\n\n    }\n\n    /*\n    *Mixture fraction 1. The fuel inlet. Concentrations are\n    *held constant at the fuel composition\n    */\n\n    for (int l=0; l<nSpc; ++l)\n    {\n        f[iMesh_e*nSpc+l] = 0.0;\n    }\n\n}\n\n/*\n* soot residual definitions\n* This is written for the fully simplied soot flamelet equations\n* See Mauss 2006\n*/\nvoid FlameLet::sootMomentResidual\n(\n    const double& t,\n    double* y,\n    double* f\n)\n{\n    double grad_e, grad_w;\n    double zPE, zPW;\n    double source;\n    double deltax = 0;\n    double sdr, sdrPE, sdrPW;\n\n    for (int l=0; l<nMoments; ++l)\n    {\n        f[l] = 0.0;\n    }\n\n    /*\n    *interior mixture fraction coordinates\n    */\n    for (int i=iMesh_s; i<iMesh_e; ++i)\n    {\n\n        zPE = 0.5*(dz[i]+dz[i+1]);\n        zPW = 0.5*(dz[i]+dz[i-1]);\n        sdr = scalarDissipationRate_(reacGeom_.getAxpos()[i],t);\n\n        if (Lewis.sootFlameletType() == LewisNumber::MAUSS06)\n        {\n            // Use the form of the soot flamelet equation given in Mauss et al 2006\n        \t// Or see Knobel thesis\n        \t// The independent variable is Mr/rho not Mr.\n        \t// So divide moments by rho\n\n            double diffusionConstant = sdr/(2.0*dz[i]);\n            for (int l=0; l<nMoments; ++l)\n            {\n                grad_e = (moments(i+1,l)/m_rho[i+1]-moments(i,l)/m_rho[i])/zPE;\n                grad_w = (moments(i,l)/m_rho[i]-moments(i-1,l)/m_rho[i-1] )/zPW;\n                source = moments_dot(i,l)/m_rho[i];\n                f[i*nMoments+l] = diffusionConstant*(grad_e-grad_w)\n                        + source;\n            }\n\n        }\n        else if (Lewis.sootFlameletType() == LewisNumber::PITSCH00DD)\n        {\n            // Use the form of the soot flamelet equation given in Pitsch et al 2000.\n            // And assume differential diffusion. (i.e., neglect M_(r-d) terms per paper.\n\n            /// NOT IMPLEMENTED YET  !!!!!!!!!!!!!\n            for (int l=0; l<nMoments; ++l)\n            {\n                f[iMesh_e*nMoments+l] = 0.0;\n            }\n            /// NOT IMPLEMENTED YET  !!!!!!!!!!!!!\n\n        }\n        else if (Lewis.sootFlameletType() == LewisNumber::CARBONELL09)\n        {\n            // Use the form of the soot flamelet equation given in Carbonel et al 2009.\n\n            deltax = zPE + zPW;\n            sdrPE = scalarDissipationRate_(reacGeom_.getAxpos()[i+1],t);\n            sdrPW = scalarDissipationRate_(reacGeom_.getAxpos()[i-1],t);\n\n            // This bit same as for gas phase species\n            double convectionConstant\n                    = 0.25/m_rho[i]\n                        *(\n                            (m_rho[i+1]*sdrPE - m_rho[i-1]*sdrPW)/deltax\n                        +(m_rho[i]*sdr*m_cp[i]/m_k[i])\n                            *(m_k[i+1]/m_cp[i+1] - m_k[i-1]/m_cp[i-1])/deltax\n                        );\n\n            //std::cout << \"convectionConstant \" << convectionConstant << std::endl;\n\n            for (int l=0; l<nMoments; ++l)\n            // Some differences to gas phase version (Le = inf here)\n            {\n                source = moments_dot(i,l)/m_rho[i];\n\n                f[i*nMoments+l] = -1.0 * convectionConstant\n                            *(moments(i+1,l)-moments(i-1,l))/deltax + source;\n\n                //f[i*nMoments+l] = source;\n            }\n         }\n        else if (Lewis.sootFlameletType() == LewisNumber::EXTENDEDLAGRANGIAN)\n        {\n            for (int l=0; l<nMoments; ++l)\n            {\n            \t// ank25: Set all moment residuals to zero when solving ELFM\n            \t// (Quick and dirst way of still generating soot moments,\n            \t// but not solving a flamelet equation for soot)\n                f[i*nMoments+l] = 0.0;\n            }\n        }\n    }\n\n    /*\n    *Mixture fraction 1. The fuel inlet. Moments held constant here.\n    */\n\n    for (int l=0; l<nMoments; ++l)\n    {\n        f[iMesh_e*nMoments+l] = 0.0;\n    }\n\n}\n\n/*\n* If we are solving a flamelet at the base of a flame then\n* set the soot residual to zero.\n* i.e. we solve a steady state flamelet with no soot present.\n*/\n\nvoid FlameLet::sootMomentResidualZeroedOut\n(\n    const double& t,\n    double* y,\n    double* f\n)\n{\n    for (int i=iMesh_s-1; i<iMesh_e+1; ++i)\n    {\n        for (int l=0; l<nMoments; ++l)\n        {\n            f[i*nMoments+l] = 0.0;\n        }\n    }\n}\n\n/*!\n*energy residual\n*\n*/\nvoid FlameLet::energyResidual\n(\n    const double& t,\n    double* y,\n    double* f\n)\n{\n\n    double grad_e=0, grad_w=0;\n    double zPE=0, zPW=0;\n    double source=0;\n    double deltax=0;\n    double sdr, sdrPE, sdrPW;\n\n    /*\n    *starting with mixture fraction zero: i.e oxidizer\n    *inlet. The temperature is fixed at the oxidizer\n    *inlet temperature\n    */\n    f[0] = 0.0;\n\n    /*\n    *intermediate mixture fraction coordinates\n    */\n    for (int i=iMesh_s; i<iMesh_e; ++i)\n    {\n\n        zPE = 0.5*(dz[i]+dz[i+1]);\n        zPW = 0.5*(dz[i]+dz[i-1]);\n        deltax = zPE + zPW;\n\n        source = 0.0;\n        for (int l=0; l<nSpc; ++l)\n        {\n            source += s_Wdot(i,l)*s_H(i,l);\n        }\n\n        // Get the scalar dissipation rate.\n        sdr = scalarDissipationRate_(reacGeom_.getAxpos()[i],t);\n\n        grad_e = (m_T[i+1]-m_T[i])/zPE;\n        grad_w = (m_T[i]-m_T[i-1])/zPW;\n\n        f[i] = 0.5*sdr*(grad_e-grad_w)/dz[i]\n            - source/(m_rho[i]*m_cp[i]);\n\n        /**\n        * Add some extra terms so that we agree with FlameMaster?\n        */\n        if (admin_.getFlameletEquationType() == admin_.COMPLETE)\n        {\n            double tGrad = (m_T[i+1]-m_T[i-1])/deltax;\n            double cpGrad = (m_cp[i+1]-m_cp[i-1])/deltax;\n            double sumYGrad = 0.0;\n            for (int l=0; l<nSpc; ++l)\n            {\n                sumYGrad += (1.0/Lewis(i,l)) * CpSpec(i,l) * (s_mf(i+1,l)-s_mf(i-1,l))/deltax;\n            }\n            f[i] += (sdr/(2.0*m_cp[i])) * tGrad * (cpGrad + sumYGrad);\n        }\n\n        //======Radiative Heat Loss Term===============\n        if (admin_.getRadiationModel())\n        {\n            //This radiation term is sent to as output to profile.h\n            radiation->calculateRadiativeHeatLoss\n            (\n            i,\n            m_T[i],\n            opPre,\n            sootVolumeFractionMaster[i]\n            );\n\n            // This is the new energy residual term, accounting for radiation.\n            // This is DEFINITELY NEGATIVE!\n            f[i] -= radiation->getRadiation(i)/(m_rho[i]*m_cp[i]);\n        }\n\n    }\n\n    // Hold temperature constant at fuel inlet\n    f[iMesh_e] = 0.0;\n\n}\n/**\n*save the mixture property\n* \\todo This should be trivially parallelisable. A lot of time is spent here.\n*/\nvoid FlameLet::saveMixtureProp(double* y)\n{\n\n    vector<double> mf;\n    vector<double> htemp(nSpc,0.0);\n    vector<double> temp(nSpc,0.0);\n    vector<double> cptemp(nSpc,0.0);\n    vector<double> moments_dot_temp(nMoments,0.0);\n    vector<double> mom_rho_temp(nMoments,0.0);\t\t// ank25: This is Mr/rho\n    vector<double> mom_temp(nMoments,0.0);\t\t\t// ank25: This is Mr\n    vector<double> exp_mom_temp(nMoments,0.0);\n    vector<double> conc(nSpc,0.0);\n    vector<double> wdotSootGasPhase(nMoments,0.0);\n    vector<double> sootComponentRatesTemp(nMoments*4,0.0);\n\n    for (int i=0; i<mCord; ++i)\n    {\n\n        // Extract the mass fractions from the solution vector\n        mf.clear();\n        for(int l=0; l<nSpc; l++)\n        {\n            mf.push_back(y[i*nVar+l]);\n        }\n\n        // Extract temperature from the solution vector\n        m_T[i] = y[i*nVar+ptrT];\n\n        // Extract moments/rho from solution vector\n        mom_rho_temp.clear();\n        //for(int l=0; l<nSpc; l++)\n        for(int l=0; l<nMoments; l++)\n        {\n            mom_rho_temp.push_back(y[i*nVar+ptrT+1+l]);\n        }\n\n        camMixture_->SetMassFracs(mf);                              //mass fraction\n        camMixture_->SetTemperature(m_T[i]);                        //temperature\n        camMixture_->GetConcs(conc);\t\t\t\t\t\t\t\t//molar conc used by soot\n\n        avgMolWt[i] = camMixture_->getAvgMolWt();\n        m_rho[i] = opPre*avgMolWt[i]/(R*m_T[i]);                    //density\n        camMixture_->SetMassDensity(m_rho[i]);                      //density\n        camMech_->Reactions().GetMolarProdRates(*camMixture_,wdot);\n        htemp = camMixture_->getMolarEnthalpy();                    //enthalpy\n        m_cp[i] = camMixture_->getSpecificHeatCapacity();           //specific heat\n        m_k[i] = camMixture_->getThermalConductivity(opPre);        //thermal conductivity\n\n        // MOVE THIS OUTSIDE LOOP TO CSOLVE\n        //m_mu[i] = camMixture_->getViscosity();                      //mixture viscosity\n        if (Lewis.type() == LewisNumber::CALCULATED) temp = camMixture_->getMixtureDiffusionCoeff(opPre);\n        cptemp = camMixture_->getMolarSpecificHeat();\n\n        for(int l=0; l<nSpc; l++)\n        {\n            s_mf(i,l) = mf[l];\n            s_Wdot(i,l) = wdot[l]*(*spv_)[l]->MolWt();\n            s_H(i,l) = htemp[l]/(*spv_)[l]->MolWt();\n            //Specific heat capacity of species in J/Kg K\n            CpSpec(i,l) =cptemp[l]/(*spv_)[l]->MolWt();\n            if (Lewis.type() == LewisNumber::CALCULATED)\n            {\n                s_Diff(i,l) = temp[l];\n                Lewis.calcLewis(i,l) = m_k[i]/(m_rho[i]*m_cp[i]*temp[l]);\n            }\n        }\n\n        if (sootMom_.active())\n        {\n        for(int l=0; l<nMoments; l++)\n        {\n        \t// ank25: Multiply by rho:  Mr/rho ---> Mr\n            moments(i,l) = mom_rho_temp[l] *  m_rho[i];\n            mom_temp[l] = mom_rho_temp[l] *  m_rho[i];\n\n        // DEBUG:  Before calling rateAll check if any moments have gone negative.\n        // If so then:\n        // a) Output the cell number\n        // b) Output the moment\n        if (moments(i,l) <0.0)\n        {\n            std::cout << \"Negative moment found before calling ratesAll\" << std::endl;\n            std::cout << \"Cell index : \" << i << std::endl;\n            std::cout << \"Moment index : \" << l << std::endl;\n            std::cout << \"Moment value : \" << moments(i,l) << std::endl;\n        }\n        // end DEBUG\n\n        }\n\n        moments_dot_temp = sootMom_.rateAll(conc, mom_temp, m_T[i], opPre, 1);\n        for(int l=0; l<nMoments; l++)\n        {\n            moments_dot(i,l) =  moments_dot_temp[l];\n        }\n\n        // Now get the corresponding gas phase rates and add them to s_Wdot\n        // Only do this if we are solving a Lagrangian flamelet (not steady state)\n        if (sootResidualZeroed == false)\n        {\n            wdotSootGasPhase = sootMom_.showGasPhaseRates(nSpc);\n            for (int l=0; l< nSpc; l++)\n            {\n            s_Wdot(i,l) = s_Wdot(i,l) + wdotSootGasPhase[l] * (*spv_)[l]->MolWt();\n            }\n\n            // Also get the component soot rates for output.\n            // Ideally we would only do this at the major output times rather than at each call\n            // of saveMixtureProp. (Inefficient)\n            // ToDo: Move this it a better place.\n            sootComponentRatesTemp = sootMom_.showSootComponentRates(nMoments);\n            for (int l=0; l< nMoments*4; l++)\n            {\n            sootComponentRatesAllCells(i,l) = sootComponentRatesTemp[l];\n            }\n\n            // Calculate soot properties at each Z point.\n            // We need volume fraction for radiation.\n            avgSootDiamMaster[i] = sootMom_.avgSootDiam();\n            dispersionMaster[i] = sootMom_.dispersion();\n            sootSurfaceAreaMaster[i] = sootMom_.sootSurfaceArea(moments(i,0));\n            sootVolumeFractionMaster[i] = sootMom_.sootVolumeFraction(moments(i,0));\n        }\n        }\n        // Check the A4 species exists first (returns -1 if it does not).\n        if(camMech_->FindSpecies(\"A4\") == -1)\n        {\n            wdotA4Master[i] = 0.0;\n        }\n        else\n        {\n            const int iA4 = camMech_->FindSpecies(\"A4\");\n            wdotA4Master[i] = s_Wdot(i,iA4);\n        }\n\n\n\n    }\n}\n\ndouble FlameLet::stoichiometricMixtureFraction()\n{\n    /*\n    *check for C and H atoms\n    */\n\n    vector<Sprog::Species*> fspecies, ospecies;\n\n    int indx_C = camMech_->FindElement(\"C\");\n    int indx_H = camMech_->FindElement(\"H\");\n\n    /*\n    *fuel inlet\n    */\n    map<string, double> species;\n    map<string, double>::iterator sIterator;\n    CamBoundary& fuelInlet = admin_.getLeftBoundary();\n    species = fuelInlet.getInletSpecies();\n    sIterator = species.begin();\n\n    while(sIterator != species.end()){\n        fspecies.push_back(camMech_->GetSpecies(sIterator->first));\n        sIterator++;\n    }\n\n    CamBoundary& oxInlet = admin_.getRightBoundary();\n    species = oxInlet.getInletSpecies();\n    sIterator = species.begin();\n    while(sIterator != species.end()){\n        ospecies.push_back(camMech_->GetSpecies(sIterator->first));\n        sIterator++;\n    }\n\n    int cAtoms=0;\n    int hAtoms=0;\n    double avgMolWt=0;\n    double fuelMassFrac=0;\n    unsigned int i;\n\n    vector<double> temp = getInletMassFrac(fuelInlet);\n\n    int iN2 = camMech_->FindSpecies(\"N2\");\n    int iAR = camMech_->FindSpecies(\"AR\");\n    int iHe = camMech_->FindSpecies(\"HE\");\n    int iO2 = camMech_->FindSpecies(\"O2\");\n\n    for(i=0; i<fspecies.size();i++){\n        int icAtoms = fspecies[i]->AtomCount(indx_C);\n        int ihAtoms = fspecies[i]->AtomCount(indx_H);\n        if (icAtoms != 0 || ihAtoms !=0) avgMolWt += fspecies[i]->MolWt();\n        cAtoms += icAtoms; hAtoms += ihAtoms;\n\n        int spIndx = camMech_->FindSpecies(fspecies[i]->Name());\n        if(spIndx != iN2 && spIndx != iAR && spIndx != iHe){\n            fuelMassFrac += temp[spIndx];\n        }\n    }\n\n    temp = getInletMassFrac(oxInlet);\n    double o2MassFrac = temp[iO2];\n\n\n    cout << \"Number of H Atoms in the fuel species  \" << hAtoms << endl;\n    cout << \"Number of C Atoms in the fuel species  \" << cAtoms << endl;\n    cout << \"avg mol wt of fuel \" << avgMolWt << endl;\n    cout << \"nEqn \" << nEqn << endl;\n    cout << \"Total fuel mass fraction \" << fuelMassFrac << endl;\n    cout << \"O2 mass frac \" << temp[iO2] << endl;\n\n    double stO2 = cAtoms + hAtoms/4.0;\n\n    /*\n    *stoichiometric mass ratio\n    */\n    double smr = stO2*0.032/avgMolWt;\n    cout << \"Avg mol wt \" << avgMolWt << endl;\n    /*\n    *stoichiometric mixture fraction\n    */\n    stoichZ = 1.0/(1+ smr*fuelMassFrac/o2MassFrac);\n\n    cout << \"Stoichiometric mixture fraction \" << stoichZ << endl;\n\n    return stoichZ;\n\n}\n\nvoid FlameLet::setExternalStrainRate(const double strainRate)\n{\n    scalarDissipationRate_.setStrainRate(strainRate);\n}\n\nvoid FlameLet::setExternalSDR(const double sdr)\n{\n    scalarDissipationRate_.setSDRRate(sdr);\n}\n\nvoid FlameLet::setExternalTimeSDR\n(\n    const std::vector<double>& time,\n    const std::vector<double>& sdr\n)\n{\n    scalarDissipationRate_.setExternalScalarDissipationRate(time,sdr);\n}\n\n/*\n*solver call for residual evaluation\n*/\nint FlameLet::eval\n(\n    double x,\n    double* y,\n    double* ydot,\n    bool jacEval\n)\n{\n\n    //Sets soot volume fraction vector to zeros\n    setExternalSootVolumeFraction(std::vector<double>(mCord, 0.0));\n    residual(x,y,ydot);\n    return 0;\n\n}\n\n/*\n*consol output function\n*/\nvoid FlameLet::report(double x, double* solution, double& res)\n{\n\n    static int nStep=0;\n    cout.width(5);\n    cout.setf(ios::scientific);\n    //if(nStep%10==0) reporter->consoleHead(\"time(s) \\t residual\");\n\n    if(nStep%10==0) cout << \"Time\" <<\"\\t\" << \"Residual\" << endl;\n    cout << x <<\"\\t\" << res << endl;\n    nStep++;\n\n}\n/*\n*output function for file output\n*/\nvoid FlameLet::reportToFile(std::string fileName, double t, std::vector<double>& soln)\n{\n\n    double sum;\n    reporter_->openFile(fileName,false);\n\n    reporter_->writeCustomHeader(header());\n\n    vector<double> data, axpos;\n    vector<double> molfrac, massfrac, temperatureVec;\n    axpos = reacGeom_.getAxpos();\n    int len = axpos.size();\n\n    for(int i=0; i<len; i++)\n    {\n        temperatureVec.push_back(soln[i*nVar+ptrT]);\n    }\n\n    for (int i=0; i<len; i++) {\n\n        data.clear();\n        data.push_back(t);\n        data.push_back(axpos[i]);\n        data.push_back(scalarDissipationRate_(axpos[i],0));\n        data.push_back(m_rho[i]);\n        data.push_back(m_mu[i]);\n        data.push_back(m_cp[i]);\n        data.push_back(soln[i*nVar+ptrT]);\n        if (radiation != NULL)\n        {\n            data.push_back(radiation->getRadiation(i));\n        }\n        else\n        {\n            data.push_back(0.0);\n        }\n\n        massfrac.clear();\n        molfrac.clear();\n        for(int l=0; l<nSpc; l++){\n            massfrac.push_back(soln[i*nVar+l]);\n        }\n        if(admin_.getSpeciesOut() == admin_.MASS){\n            sum = 0;\n            for(int l=0; l<nSpc; l++){\n                data.push_back(fabs(massfrac[l]));\n                sum += massfrac[l];\n            }\n        }else{\n            CamConverter cc;\n            cc.mass2mole(massfrac,molfrac,*camMech_);\n            sum = 0;\n            for(int l=0; l<nSpc; l++){\n                data.push_back(fabs(molfrac[l]));\n                sum += molfrac[l];\n            }\n        }\n        data.push_back(sum);\n\n        // Add the moments and soot properties to the data output\n        if (sootMom_.active())\n        {\n            data.push_back(avgSootDiamMaster[i]);\n            data.push_back(dispersionMaster[i]);\n            data.push_back(sootSurfaceAreaMaster[i]);\n            data.push_back(sootVolumeFractionMaster[i]);\n            for(int l=0; l<nMoments; l++)\n            {\n                data.push_back(soln[i*nVar+ptrT+1+l]);\n            }\n        }\n        reporter_->writeCustomFileOut(data);\n    }\n\n    reporter_->closeFile();\n\n    // Output Lewis Numbers to File.\n    std::ofstream file(\"LewisNumbers\");\n    file << setw(5) << \"Z\" << \" \";\n    for (int l=0; l<nSpc; l++)\n    {\n        file << setw(8) << (*spv_)[l]->Name() << \" \";\n    }\n    file<<std::endl;\n    for (int i=0; i<mCord; ++i)\n    {\n        file << setw(5) << axpos[i] << \" \";\n        for (int l=0; l<nSpc; l++)\n        {\n            file << setprecision(5) << setw(8) <<  Lewis(i,l) << \" \";\n        }\n        file << std::endl;\n    }\n    file.close();\n\n    //reacGeom->refine(soln,nVar,nSpc,ptrT);\n\n}\n\n/*\n*output file header\n*/\nstd::vector<std::string> FlameLet::header()\n{\n\n    std::vector<std::string> headerData;\n\n    headerData.clear();\n    headerData.push_back(\"time\");\n    headerData.push_back(\"Z\");\n    headerData.push_back(\"SDR\");\n    headerData.push_back(\"rho\");\n    headerData.push_back(\"mu\");\n    headerData.push_back(\"cp\");\n    headerData.push_back(\"T\");\n    headerData.push_back(\"Radiation\");\n    for (int l = 0; l < nSpc; l++) {\n        headerData.push_back( (*spv_)[l]->Name() );\n    }\n    headerData.push_back(\"sumfracs\");\n    if (sootMom_.active())\n    {\n        headerData.push_back(\"SootAvDiam\");\n        headerData.push_back(\"SootDisp\");\n        headerData.push_back(\"SootArea\");\n        headerData.push_back(\"SootVolFrac\");\n        headerData.push_back(\"M0\");\n        headerData.push_back(\"M1\");\n        headerData.push_back(\"M2\");\n        headerData.push_back(\"M3\");\n        headerData.push_back(\"M4\");\n        headerData.push_back(\"M5\");\n    }\n\n    return headerData;\n\n}\n\n/*!\n*@param[in]    soot_fv     Vector of soot volume fractions, one for each grid cell\n*/\nvoid\nFlameLet::setExternalSootVolumeFraction(const std::vector<double>& soot_fv)\n{\n    m_SootFv = soot_fv;\n\n    //Solver assumes one soot volume fraction for each cell; temperature is already initialized\n    /*if (static_cast<size_t>(reacGeom->getnCells()) != m_SootFv.size()) {\n        std::ostringstream msg (\"new soot volume fraction vector length is \");\n        msg << m_SootFv.size() << \" but geometry length is \" << reacGeom->getnCells();\n        throw std::runtime_error (msg.str());\n    }*/\n}\n\n/*\n*  Return the pyrene(A4) molar production rate term.\n*  Note:  This is not used to pass wdotA4 to interface.\n*/\nvoid\nFlameLet::getWdotA4(std::vector<double>& wdotA4)\nconst\n{\n\n    wdotA4.clear();\n    // Check the species exists first (returns -1 if it does not).\n    if(camMech_->FindSpecies(\"A4\") == -1){\n        std::cout << \"Species A4 not found.\" << std::endl;\n        for(int i=iMesh_s; i<iMesh_e;i++){\n            wdotA4.push_back(0.0);\n        }\n    } else {\n        const int iA4 = camMech_->FindSpecies(\"A4\");\n        for(int i=iMesh_s; i<iMesh_e;i++){\n            wdotA4.push_back(s_Wdot(i,iA4));\n        }\n    }\n\n}\n\n/*\n*output function for file output\n*/\nvoid FlameLet::reportSootRatesToFile(std::string fileName, double t, Array2D& rates)\n{\n\n    double sum;\n\n    std::cout << \"Reporting Component Soot Rates to File\" << std::endl;\n\n    reporter_->openFile(fileName,false);\n\n    reporter_->writeCustomHeader(sootRatesHeader());\n\n    vector<double> data, axpos;\n\n    //vector<double> molfrac, massfrac, temperatureVec;\n    axpos = reacGeom_.getAxpos();\n    int len = axpos.size();\n\n    for (int i=0; i<len; i++) {\n\n        data.clear();\n        data.push_back(t);\n        data.push_back(axpos[i]);\n        data.push_back(scalarDissipationRate_(axpos[i],0));\n\n        for(int l=0; l<nMoments*4; l++){\n            data.push_back(rates(i,l));\n        }\n\n        reporter_->writeCustomFileOut(data);\n\n    }\n    reporter_->closeFile();\n}\n\n/*\n*output file header\n*/\nstd::vector<std::string> FlameLet::sootRatesHeader()\n{\n    std::vector<std::string> headerData;\n\n    headerData.clear();\n    headerData.push_back(\"time\");\n    headerData.push_back(\"Z\");\n    headerData.push_back(\"SDR\");\n\n    for(int l=0; l<nMoments; l++){\n        headerData.push_back(\"Nuc_M\"+boost::lexical_cast<std::string>(l));\n    }\n    for(int l=0; l<nMoments; l++){\n        headerData.push_back(\"Coag_M\"+boost::lexical_cast<std::string>(l));\n    }\n    for(int l=0; l<nMoments; l++){\n        headerData.push_back(\"Cond_M\"+boost::lexical_cast<std::string>(l));\n    }\n    for(int l=0; l<nMoments; l++){\n        headerData.push_back(\"Surf_M\"+boost::lexical_cast<std::string>(l));\n    }\n    return headerData;\n}\n", "meta": {"hexsha": "268ff4d131378a163f493f182fad20dcf707da90", "size": 50823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camflow/source/flamelet.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/camflow/source/flamelet.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/camflow/source/flamelet.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 28.0325427468, "max_line_length": 130, "alphanum_fraction": 0.5543159593, "num_tokens": 14092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.038466195876321656, "lm_q1q2_score": 0.0169894797837883}}
{"text": "/*\n fc_virtual.cpp\n\n Copyright (c) 2018 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 \"fc_virtual.h\"\n#include \"xml_parser.h\"\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <map>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/foreach.hpp>\n#include <boost/version.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"memory.h\"\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n    std::string file_xml1, file_xml2;\n    double alpha = 1.0;\n    int maxorder;\n\n    if (argc == 1) {\n        cout << \" FC_Virtual -- virtual crystal approximation of force constants\" << endl;\n        cout << \" First  FCSXML file (A) :  \";\n        cin >> file_xml1;\n        cout << \" Second FCSXML file (B) :  \";\n        cin >> file_xml2;\n        cout << \" Mixing alpha [alpha * A + (1 - alpha) * B] : \";\n        cin >> alpha;\n        cout << \" Maxorder (2: harmonic, 3: cubic, 4: quartic, ...) : \";\n        cin >> maxorder;\n\n    } else if (argc == 5) {\n\n        file_xml1 = argv[1];\n        file_xml2 = argv[2];\n        alpha = boost::lexical_cast<double>(argv[3]);\n        maxorder = boost::lexical_cast<int>(argv[4]);\n\n    } else {\n        std::cout << \"Usage: \" << std::endl;\n        std::cout << \"(command line) > fc_virtual FCSXML1 FCSXML2 mixalpha maxorder \" << std::endl;\n        std::cout << \"(interactive) > fc_virtual \" << std::endl;\n        std::cout << std::endl;\n    }\n\n    if (alpha < 0.0 || alpha > 1.0) {\n        std::cout << \"alpha must be 0 <= alpha <= 1\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if (maxorder <= 1) {\n        std::cout << \"Maxorder should be larger than 1. \" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    maxorder = maxorder - 1;\n\n    std::vector <FcsArrayWithCell> *fc_orig1, *fc_orig2, *fc_new;\n    StructureProperty structure1, structure2, structure_new;\n\n    allocate(fc_orig1, maxorder);\n    allocate(fc_orig2, maxorder);\n    allocate(fc_new, maxorder);\n\n    load_fcs_xml(file_xml1, maxorder, structure1, fc_orig1);\n    load_fcs_xml(file_xml2, maxorder, structure2, fc_orig2);\n\n    mix_structure(structure1, structure2, structure_new, alpha);\n    mix_forceconstant(fc_orig1, fc_orig2, fc_new, alpha, maxorder);\n\n    deallocate(fc_orig1);\n    deallocate(fc_orig2);\n\n    write_new_xml(\"VCA.xml\", file_xml1, file_xml2, maxorder, alpha, structure_new, fc_new);\n\n    std::cout << std::endl;\n    std::cout << \" A new FCSXML is generated as VCA.xml.\" << std::endl;\n\n    deallocate(fc_new);\n}\n\n\nvoid load_fcs_xml(const std::string file_in,\n                  const int maxorder,\n                  StructureProperty &StructProp,\n                  std::vector <FcsArrayWithCell> *force_constant_with_cell)\n{\n    using namespace boost::property_tree;\n    ptree pt;\n    map<string, int> dict_atomic_kind;\n    std::stringstream ss;\n\n    try {\n        read_xml(file_in, pt);\n    }\n    catch (exception &e) {\n        cout << \"Cannot open file \" + file_in << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    StructProp.nat = boost::lexical_cast<unsigned int>(\n            get_value_from_xml(pt,\n                               \"Data.Structure.NumberOfAtoms\"));\n    StructProp.nspecies = boost::lexical_cast<unsigned int>(\n            get_value_from_xml(pt,\n                               \"Data.Structure.NumberOfElements\"));\n\n    StructProp.ntran = boost::lexical_cast<unsigned int>(\n            get_value_from_xml(pt,\n                               \"Data.Symmetry.NumberOfTranslations\"));\n\n\n    for (auto i = 0; i < 3; ++i) {\n        ss.str(\"\");\n        ss.clear();\n        ss << get_value_from_xml(pt,\n                                 \"Data.Structure.LatticeVector.a\"\n                                 + boost::lexical_cast<string>(i + 1));\n        ss >> StructProp.lattice_vector[0][i]\n           >> StructProp.lattice_vector[1][i]\n           >> StructProp.lattice_vector[2][i];\n    }\n\n    ss.str(\"\");\n    ss.clear();\n    ss << get_value_from_xml(pt, \"Data.Structure.Periodicity\");\n    ss >> StructProp.is_periodic[0]\n       >> StructProp.is_periodic[1]\n       >> StructProp.is_periodic[2];\n\n    // Parse atomic elements and coordinates\n\n    StructProp.kd_symbol.resize(StructProp.nspecies);\n    StructProp.atoms.resize(StructProp.nat);\n\n    int i = 0;\n\n    BOOST_FOREACH(\n    const ptree::value_type &child_, pt.get_child(\"Data.Structure.AtomicElements\")) {\n        const ptree &child = child_.second;\n        const unsigned int icount_kd = child.get<unsigned int>(\"<xmlattr>.number\");\n        dict_atomic_kind[boost::lexical_cast<string>(child_.second.data())] = icount_kd - 1;\n        StructProp.kd_symbol[i++] = boost::lexical_cast<string>(child_.second.data());\n    }\n\n    unsigned int index;\n\n    BOOST_FOREACH(\n    const ptree::value_type &child_, pt.get_child(\"Data.Structure.Position\")) {\n        const ptree &child = child_.second;\n        const string str_index = child.get<string>(\"<xmlattr>.index\");\n        const string str_element = child.get<string>(\"<xmlattr>.element\");\n\n        ss.str(\"\");\n        ss.clear();\n        ss << child.data();\n\n        index = boost::lexical_cast<unsigned int>(str_index) - 1;\n\n        if (index >= StructProp.nat) {\n            cout << \"index is out of range\" << endl;\n            exit(EXIT_FAILURE);\n        }\n\n        StructProp.atoms[index].kind = dict_atomic_kind[str_element];\n        ss >> StructProp.atoms[index].x\n           >> StructProp.atoms[index].y\n           >> StructProp.atoms[index].z;\n    }\n\n    dict_atomic_kind.clear();\n\n    // Parse mapping information\n\n    StructProp.natmin = StructProp.nat / StructProp.ntran;\n\n    unsigned int tran, atom_p, atom_s;\n\n    BOOST_FOREACH(\n    const ptree::value_type &child_, pt.get_child(\"Data.Symmetry.Translations\")) {\n        const ptree &child = child_.second;\n        const string str_tran = child.get<string>(\"<xmlattr>.tran\");\n        const string str_atom = child.get<string>(\"<xmlattr>.atom\");\n\n        tran = boost::lexical_cast<unsigned int>(str_tran) - 1;\n        atom_p = boost::lexical_cast<unsigned int>(str_atom) - 1;\n        atom_s = boost::lexical_cast<unsigned int>(child.data()) - 1;\n\n        if (tran >= StructProp.ntran || atom_p >= StructProp.natmin || atom_s >= StructProp.nat) {\n            cout << \"index is out of range\" << endl;\n            exit(EXIT_FAILURE);\n        }\n\n        StructProp.atoms[atom_s].atom = atom_p;\n        StructProp.atoms[atom_s].tran = tran;\n    }\n\n    // Parse force constants\n\n    std::vector <AtomCellSuper> ivec_with_cell;\n    std::string str_tag;\n    double fcs_val;\n    unsigned int atmn, xyz, cell_s;\n    std::string str_pairs;\n    std::string str_attr;\n    AtomCellSuper ivec_tmp;\n\n    for (auto order = 0; order < maxorder; ++order) {\n\n        if (order == 0) {\n            str_tag = \"Data.ForceConstants.HARMONIC\";\n        } else {\n            str_tag = \"Data.ForceConstants.ANHARM\" + std::to_string(order + 2);\n        }\n\n        boost::optional < ptree &> child_ = pt.get_child_optional(str_tag);\n\n        if (!child_) {\n            std::string str_tmp = str_tag + \" flag not found in the XML file\";\n            exit(EXIT_FAILURE);\n        }\n\n        BOOST_FOREACH(\n        const ptree::value_type &child_, pt.get_child(str_tag)) {\n            const ptree &child = child_.second;\n\n            fcs_val = boost::lexical_cast<double>(child.data());\n\n            ivec_with_cell.clear();\n\n            for (i = 0; i < order + 2; ++i) {\n                str_attr = \"<xmlattr>.pair\" + std::to_string(i + 1);\n                str_pairs = child.get<std::string>(str_attr);\n\n                ss.str(\"\");\n                ss.clear();\n                ss << str_pairs;\n\n                if (i == 0) {\n                    ss >> atmn >> xyz;\n                    ivec_tmp.index = 3 * (atmn - 1) + xyz - 1;\n                    ivec_tmp.cell_s = 0;\n                    ivec_tmp.tran = 0; // dummy\n                    ivec_with_cell.push_back(ivec_tmp);\n\n                } else {\n                    ss >> atmn >> xyz >> cell_s;\n                    ivec_tmp.index = 3 * (atmn - 1) + xyz - 1;\n                    ivec_tmp.cell_s = cell_s - 1;\n                    ivec_tmp.tran = 0; // dummy\n                    ivec_with_cell.push_back(ivec_tmp);\n                }\n            }\n\n            force_constant_with_cell[order].emplace_back(fcs_val, ivec_with_cell);\n\n        }\n\n    }\n\n}\n\nvoid mix_structure(const StructureProperty &Structure1,\n                   const StructureProperty &Structure2,\n                   StructureProperty &Structure_out,\n                   const double alpha)\n{\n    // First, check the consistency of the two structures.\n\n    if (Structure1.nat != Structure2.nat ||\n        Structure1.nspecies != Structure2.nspecies ||\n        Structure1.ntran != Structure2.ntran ||\n        Structure1.atoms.size() != Structure2.atoms.size()) {\n        std::cout << \" Atomic structures of two XML files are different.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    for (auto i = 0; i < Structure1.nspecies; ++i) {\n        if (Structure1.kd_symbol[i] != Structure2.kd_symbol[i]) {\n            std::cout << \" Warning: the atomic symbols don't match.\" << std::endl;\n        }\n    }\n    for (auto i = 0; i < Structure1.nat; ++i) {\n        if (Structure1.atoms[i].kind != Structure2.atoms[i].kind) {\n            std::cout << \" Warning: the kind index doesn't match.\" << std::endl;\n        }\n    }\n    for (auto i = 0; i < 3; ++i) {\n        if (Structure1.is_periodic[i] != Structure2.is_periodic[i]) {\n            std::cout << \" Warning: the periodicity doesn't match.\" << std::endl;\n        }\n    }\n\n    for (auto i = 0; i < Structure1.nat; ++i) {\n        if (Structure1.atoms[i].atom != Structure2.atoms[i].atom ||\n            Structure1.atoms[i].tran != Structure2.atoms[i].tran) {\n            std::cout << \" The mapping information doesn't match.\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    // Copy common variables\n\n    Structure_out.nat = Structure1.nat;\n    Structure_out.nspecies = Structure1.nspecies;\n    Structure_out.ntran = Structure1.ntran;\n    Structure_out.natmin = Structure1.natmin;\n    for (auto i = 0; i < 3; ++i) Structure_out.is_periodic[i] = Structure1.is_periodic[i];\n\n    for (const auto &it : Structure1.kd_symbol) {\n        Structure_out.kd_symbol.push_back(it);\n    }\n\n    // Mix lattice constants\n\n    for (auto i = 0; i < 3; ++i) {\n        for (auto j = 0; j < 3; ++j) {\n            Structure_out.lattice_vector[i][j]\n                    = alpha * Structure1.lattice_vector[i][j]\n                      + (1.0 - alpha) * Structure2.lattice_vector[i][j];\n        }\n    }\n\n    // Mix fractional coordinate\n\n    AtomProperty atoms;\n\n    for (auto i = 0; i < Structure1.nat; ++i) {\n\n        atoms.kind = Structure1.atoms[i].kind;\n        atoms.atom = Structure1.atoms[i].atom;\n        atoms.tran = Structure1.atoms[i].tran;\n\n        atoms.x = alpha * Structure1.atoms[i].x + (1.0 - alpha) * Structure2.atoms[i].x;\n        atoms.y = alpha * Structure1.atoms[i].y + (1.0 - alpha) * Structure2.atoms[i].y;\n        atoms.z = alpha * Structure1.atoms[i].z + (1.0 - alpha) * Structure2.atoms[i].z;\n\n        Structure_out.atoms.push_back(atoms);\n    }\n}\n\n\nvoid mix_forceconstant(std::vector <FcsArrayWithCell> *fc_orig1,\n                       std::vector <FcsArrayWithCell> *fc_orig2,\n                       std::vector <FcsArrayWithCell> *fc_new,\n                       const double alpha, const int maxorder)\n{\n    // Mix force constants with the given mixing fraction \"alpha\"\n\n    for (auto order = 0; order < maxorder; ++order) {\n\n        std::vector <FcsArrayWithCell> fc_tmp;\n\n        for (const auto &it : fc_orig1[order]) {\n            fc_tmp.emplace_back(alpha * it.fcs_val, it.pairs);\n        }\n\n        for (const auto &it : fc_orig2[order]) {\n            fc_tmp.emplace_back((1.0 - alpha) * it.fcs_val, it.pairs);\n        }\n\n        std::sort(fc_tmp.begin(), fc_tmp.end());\n\n        FcsArrayWithCell fc_now = fc_tmp[0];\n        double fcs_val = fc_now.fcs_val;\n\n        for (auto i = 1; i < fc_tmp.size(); ++i) {\n            if (fc_tmp[i] == fc_now) {\n                fcs_val += fc_tmp[i].fcs_val;\n            } else {\n                fc_new[order].emplace_back(fcs_val, fc_now.pairs);\n                fc_now = fc_tmp[i];\n                fcs_val = fc_now.fcs_val;\n            }\n        }\n\n        fc_new[order].emplace_back(fcs_val, fc_now.pairs);\n    }\n}\n\n\nvoid write_new_xml(const std::string file_xml,\n                   const std::string file_xml1,\n                   const std::string file_xml2,\n                   const int maxorder, const double alpha,\n                   const StructureProperty &structure,\n                   std::vector <FcsArrayWithCell> *fcs)\n{\n    int i, j, k;\n    using boost::property_tree::ptree;\n    ptree pt;\n\n    pt.put(\"Data.VCA.Original1\", file_xml1);\n    pt.put(\"Data.VCA.Original2\", file_xml2);\n    pt.put(\"Data.VCA.Mixalpha\", alpha);\n    pt.put(\"Data.Structure.NumberOfAtoms\", structure.nat);\n    pt.put(\"Data.Structure.NumberOfElements\", structure.nspecies);\n\n    for (i = 0; i < structure.nspecies; ++i) {\n        ptree &child = pt.add(\"Data.Structure.AtomicElements.element\",\n                              structure.kd_symbol[i]);\n        child.put(\"<xmlattr>.number\", i + 1);\n    }\n\n    std::string str_pos[3];\n    for (i = 0; i < 3; ++i) {\n        str_pos[i].clear();\n        for (j = 0; j < 3; ++j) {\n            str_pos[i] += \" \" + double2string(structure.lattice_vector[j][i]);\n        }\n    }\n    pt.put(\"Data.Structure.LatticeVector\", \"\");\n    pt.put(\"Data.Structure.LatticeVector.a1\", str_pos[0]);\n    pt.put(\"Data.Structure.LatticeVector.a2\", str_pos[1]);\n    pt.put(\"Data.Structure.LatticeVector.a3\", str_pos[2]);\n\n    std::stringstream ss;\n    ss << structure.is_periodic[0] << \" \"\n       << structure.is_periodic[1] << \" \"\n       << structure.is_periodic[2];\n    pt.put(\"Data.Structure.Periodicity\", ss.str());\n\n    pt.put(\"Data.Structure.Position\", \"\");\n    std::string str_tmp;\n\n    for (i = 0; i < structure.nat; ++i) {\n        str_tmp.clear();\n        str_tmp = \" \" + double2string(structure.atoms[i].x)\n                  + \" \" + double2string(structure.atoms[i].y)\n                  + \" \" + double2string(structure.atoms[i].z);\n        ptree &child = pt.add(\"Data.Structure.Position.pos\", str_tmp);\n        child.put(\"<xmlattr>.index\", i + 1);\n        child.put(\"<xmlattr>.element\", structure.kd_symbol[structure.atoms[i].kind]);\n    }\n\n    int **map_p2s;\n    allocate(map_p2s, structure.natmin, structure.ntran);\n    for (i = 0; i < structure.nat; ++i) {\n        map_p2s[structure.atoms[i].atom][structure.atoms[i].tran] = i;\n    }\n\n    pt.put(\"Data.Symmetry.NumberOfTranslations\", structure.ntran);\n    for (i = 0; i < structure.ntran; ++i) {\n        for (j = 0; j < structure.natmin; ++j) {\n            ptree &child = pt.add(\"Data.Symmetry.Translations.map\",\n                                  map_p2s[j][i] + 1);\n            child.put(\"<xmlattr>.tran\", i + 1);\n            child.put(\"<xmlattr>.atom\", j + 1);\n        }\n    }\n    deallocate(map_p2s);\n\n    std::string elementname;\n\n    for (auto order = 0; order < maxorder; ++order) {\n\n        if (order == 0) {\n            elementname = \"Data.ForceConstants.HARMONIC.FC2\";\n        } else {\n            elementname = \"Data.ForceConstants.ANHARM\" + std::to_string(order + 2)\n                          + \".FC\" + std::to_string(order + 2);\n        }\n\n        for (const auto &it : fcs[order]) {\n\n            ptree &child = pt.add(elementname, double2string(it.fcs_val));\n            child.put(\"<xmlattr>.pair1\", std::to_string(it.pairs[0].index / 3 + 1)\n                                         + \" \" + std::to_string(it.pairs[0].index % 3 + 1));\n\n            for (k = 1; k < order + 2; ++k) {\n                child.put(\"<xmlattr>.pair\" + std::to_string(k + 1),\n                          std::to_string(it.pairs[k].index / 3 + 1)\n                          + \" \" + std::to_string(it.pairs[k].index % 3 + 1)\n                          + \" \" + std::to_string(it.pairs[k].cell_s + 1));\n            }\n        }\n\n    }\n\n    using namespace boost::property_tree::xml_parser;\n    const int indent = 2;\n\n#if BOOST_VERSION >= 105600\n    write_xml(file_xml, pt, std::locale(),\n              xml_writer_make_settings<ptree::key_type>(' ', indent,\n                                                        widen<std::string>(\"utf-8\")));\n#else\n    write_xml(file_xml, pt, std::locale(),\n              xml_writer_make_settings(' ', indent, widen<char>(\"utf-8\")));\n#endif\n}\n\n\nstd::string double2string(const double d, const int nprec)\n{\n    std::string rt;\n    std::stringstream ss;\n\n    ss << std::scientific << std::setprecision(nprec) << d;\n    ss >> rt;\n    return rt;\n}", "meta": {"hexsha": "1eef19dba96e09ead016d921efd34af81d1899c5", "size": 16845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/fc_virtual.cpp", "max_stars_repo_name": "by-student-2017/alamode", "max_stars_repo_head_hexsha": "97bc8daccadc4bbc8859daf9098af0bc810ae463", "max_stars_repo_licenses": ["MIT"], "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/fc_virtual.cpp", "max_issues_repo_name": "by-student-2017/alamode", "max_issues_repo_head_hexsha": "97bc8daccadc4bbc8859daf9098af0bc810ae463", "max_issues_repo_licenses": ["MIT"], "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/fc_virtual.cpp", "max_forks_repo_name": "by-student-2017/alamode", "max_forks_repo_head_hexsha": "97bc8daccadc4bbc8859daf9098af0bc810ae463", "max_forks_repo_licenses": ["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.8362573099, "max_line_length": 99, "alphanum_fraction": 0.5644998516, "num_tokens": 4414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.038466188160327285, "lm_q1q2_score": 0.016989476941232783}}
{"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_OB_TRAN_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_HPP\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <boost/geometry/srs/projections/impl/aasincos.hpp>\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_ell_set.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail {\n    \n        // fwd declaration needed below\n        template <typename T>\n        inline detail::base_v<T, projections::parameters<T> >*\n            create_new(srs::detail::proj4_parameters const& params,\n                       projections::parameters<T> const& parameters);\n\n        template <typename T>\n        inline detail::base_v<T, projections::parameters<T> >*\n            create_new(srs::dpar::parameters<T> const& params,\n                       projections::parameters<T> const& parameters);\n\n    } // namespace detail\n\n    namespace detail { namespace ob_tran\n    {\n\n            static const double tolerance = 1e-10;\n\n            template <typename Parameters>\n            inline Parameters o_proj_parameters(srs::detail::proj4_parameters const& params,\n                                                Parameters const& par)\n            {\n                /* copy existing header into new */\n                Parameters pj = par;\n\n                /* get name of projection to be translated */\n                pj.id = pj_get_param_s(params, \"o_proj\");\n                if (pj.id.is_unknown())\n                    BOOST_THROW_EXCEPTION( projection_exception(error_no_rotation_proj) );\n\n                /* avoid endless recursion */\n                if( pj.id.name == \"ob_tran\")\n                    BOOST_THROW_EXCEPTION( projection_exception(error_failed_to_find_proj) );\n\n                // Commented out for consistency with Proj4 >= 5.0.0\n                /* force spherical earth */\n                //pj.one_es = pj.rone_es = 1.;\n                //pj.es = pj.e = 0.;\n\n                return pj;\n            }\n\n            template <typename T, typename Parameters>\n            inline Parameters o_proj_parameters(srs::dpar::parameters<T> const& params,\n                                                Parameters const& par)\n            {\n                /* copy existing header into new */\n                Parameters pj = par;\n\n                /* get name of projection to be translated */\n                typename srs::dpar::parameters<T>::const_iterator\n                    it = pj_param_find(params, srs::dpar::o_proj);\n                if (it != params.end())\n                    pj.id = static_cast<srs::dpar::value_proj>(it->template get_value<int>());\n                else\n                    BOOST_THROW_EXCEPTION( projection_exception(error_no_rotation_proj) );\n\n                /* avoid endless recursion */\n                if( pj.id.id == srs::dpar::proj_ob_tran)\n                    BOOST_THROW_EXCEPTION( projection_exception(error_failed_to_find_proj) );\n\n                // Commented out for consistency with Proj4 >= 5.0.0\n                /* force spherical earth */\n                //pj.one_es = pj.rone_es = 1.;\n                //pj.es = pj.e = 0.;\n\n                return pj;\n            }\n\n            template <BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX, typename Parameters>\n            inline Parameters o_proj_parameters(srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& params,\n                                                Parameters const& par)\n            {\n                /* copy existing header into new */\n                Parameters pj = par;\n\n                /* get name of projection to be translated */\n                typedef srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> params_type;\n                typedef typename srs::spar::detail::tuples_find_if\n                    <\n                        params_type,\n                        srs::spar::detail::is_param_t<srs::spar::o_proj>::pred\n                    >::type o_proj_type;\n\n                static const bool is_found = srs::spar::detail::tuples_is_found<o_proj_type>::value;\n                BOOST_MPL_ASSERT_MSG((is_found), NO_ROTATION_PROJ, (params_type));\n\n                typedef typename o_proj_type::type proj_type;\n                static const bool is_specialized = srs::spar::detail::proj_traits<proj_type>::is_specialized;\n                BOOST_MPL_ASSERT_MSG((is_specialized), NO_ROTATION_PROJ, (params_type));\n\n                pj.id = srs::spar::detail::proj_traits<proj_type>::id;\n\n                /* avoid endless recursion */\n                static const bool is_non_resursive = ! boost::is_same<proj_type, srs::spar::proj_ob_tran>::value;\n                BOOST_MPL_ASSERT_MSG((is_non_resursive), INVALID_O_PROJ_PARAMETER, (params_type));\n\n                // Commented out for consistency with Proj4 >= 5.0.0\n                /* force spherical earth */\n                //pj.one_es = pj.rone_es = 1.;\n                //pj.es = pj.e = 0.;\n\n                return pj;\n            }\n\n            template <typename T, typename Parameters>\n            struct par_ob_tran\n            {\n                template <typename Params>\n                par_ob_tran(Params const& params, Parameters const& par)\n                    : link(projections::detail::create_new(params, o_proj_parameters(params, par)))\n                {\n                    if (! link.get())\n                        BOOST_THROW_EXCEPTION( projection_exception(error_unknown_projection_id) );\n                }\n\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    link->fwd(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    link->inv(xy_x, xy_y, lp_lon, lp_lat);\n                }\n\n                boost::shared_ptr<base_v<T, Parameters> > link;\n                T lamp;\n                T cphip, sphip;\n            };\n\n            template <typename StaticParameters, typename T, typename Parameters>\n            struct par_ob_tran_static\n            {\n                // this metafunction handles static error handling\n                typedef typename srs::spar::detail::pick_o_proj_tag\n                    <\n                        StaticParameters\n                    >::type o_proj_tag;\n\n                /* avoid endless recursion */\n                static const bool is_o_proj_not_ob_tran = ! boost::is_same<o_proj_tag, srs::spar::proj_ob_tran>::value;\n                BOOST_MPL_ASSERT_MSG((is_o_proj_not_ob_tran), INVALID_O_PROJ_PARAMETER, (StaticParameters));\n\n                typedef typename projections::detail::static_projection_type\n                    <\n                        o_proj_tag,\n                        // Commented out for consistency with Proj4 >= 5.0.0\n                        //srs_sphere_tag, // force spherical\n                        typename projections::detail::static_srs_tag<StaticParameters>::type,\n                        StaticParameters,\n                        T,\n                        Parameters\n                    >::type projection_type;\n\n                par_ob_tran_static(StaticParameters const& params, Parameters const& par)\n                    : link(params, o_proj_parameters(params, par))\n                {}\n\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    link.fwd(lp_lon, lp_lat, xy_x, xy_y);\n                }\n\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    link.inv(xy_x, xy_y, lp_lon, lp_lat);\n                }\n\n                projection_type link;\n                T lamp;\n                T cphip, sphip;\n            };\n\n            template <typename T, typename Par>\n            inline void o_forward(T lp_lon, T lp_lat, T& xy_x, T& xy_y, Par const& proj_parm)\n            {\n                T coslam, sinphi, cosphi;\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), proj_parm.sphip * cosphi * coslam +\n                    proj_parm.cphip * sinphi) + proj_parm.lamp);\n                lp_lat = aasin(proj_parm.sphip * sinphi - proj_parm.cphip * cosphi * coslam);\n\n                proj_parm.fwd(lp_lon, lp_lat, xy_x, xy_y);\n            }\n\n            template <typename T, typename Par>\n            inline void o_inverse(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat, Par const& proj_parm)\n            {\n                T coslam, sinphi, cosphi;\n\n                proj_parm.inv(xy_x, xy_y, lp_lon, lp_lat);\n                if (lp_lon != HUGE_VAL) {\n                    coslam = cos(lp_lon -= proj_parm.lamp);\n                    sinphi = sin(lp_lat);\n                    cosphi = cos(lp_lat);\n                    lp_lat = aasin(proj_parm.sphip * sinphi + proj_parm.cphip * cosphi * coslam);\n                    lp_lon = aatan2(cosphi * sin(lp_lon), proj_parm.sphip * cosphi * coslam -\n                        proj_parm.cphip * sinphi);\n                }\n            }\n\n            template <typename T, typename Par>\n            inline void t_forward(T lp_lon, T lp_lat, T& xy_x, T& xy_y, Par const& proj_parm)\n            {\n                T cosphi, coslam;\n\n                cosphi = cos(lp_lat);\n                coslam = cos(lp_lon);\n                lp_lon = adjlon(aatan2(cosphi * sin(lp_lon), sin(lp_lat)) + proj_parm.lamp);\n                lp_lat = aasin(- cosphi * coslam);\n\n                proj_parm.fwd(lp_lon, lp_lat, xy_x, xy_y);\n            }\n\n            template <typename T, typename Par>\n            inline void t_inverse(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat, Par const& proj_parm)\n            {\n                T cosphi, t;\n\n                proj_parm.inv(xy_x, xy_y, lp_lon, lp_lat);\n                if (lp_lon != HUGE_VAL) {\n                    cosphi = cos(lp_lat);\n                    t = lp_lon - proj_parm.lamp;\n                    lp_lon = aatan2(cosphi * sin(t), - sin(lp_lat));\n                    lp_lat = aasin(cosphi * cos(t));\n                }\n            }\n\n            // General Oblique Transformation\n            template <typename T, typename Params, typename Parameters, typename ProjParameters>\n            inline T setup_ob_tran(Params const& params, Parameters & par, ProjParameters& proj_parm)\n            {\n                static const T half_pi = detail::half_pi<T>();\n\n                T phip, alpha;\n\n                // Commented out for consistency with Proj4 >= 5.0.0\n                //par.es = 0.; /* force to spherical */\n\n                // proj_parm.link should be created at this point\n\n                if (pj_param_r<srs::spar::o_alpha>(params, \"o_alpha\", srs::dpar::o_alpha, alpha)) {\n                    T lamc, phic;\n\n                    lamc    = pj_get_param_r<T, srs::spar::o_lon_c>(params, \"o_lon_c\", srs::dpar::o_lon_c);\n                    phic    = pj_get_param_r<T, srs::spar::o_lon_c>(params, \"o_lat_c\", srs::dpar::o_lat_c);\n                    //alpha   = pj_get_param_r(par.params, \"o_alpha\");\n            \n                    if (fabs(fabs(phic) - half_pi) <= tolerance)\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_0_or_alpha_eq_90) );\n\n                    proj_parm.lamp = lamc + aatan2(-cos(alpha), -sin(alpha) * sin(phic));\n                    phip = aasin(cos(phic) * sin(alpha));\n                } else if (pj_param_r<srs::spar::o_lat_p>(params, \"o_lat_p\", srs::dpar::o_lat_p, phip)) { /* specified new pole */\n                    proj_parm.lamp = pj_get_param_r<T, srs::spar::o_lon_p>(params, \"o_lon_p\", srs::dpar::o_lon_p);\n                    //phip = pj_param_r(par.params, \"o_lat_p\");\n                } else { /* specified new \"equator\" points */\n                    T lam1, lam2, phi1, phi2, con;\n\n                    lam1 = pj_get_param_r<T, srs::spar::o_lon_1>(params, \"o_lon_1\", srs::dpar::o_lon_1);\n                    phi1 = pj_get_param_r<T, srs::spar::o_lat_1>(params, \"o_lat_1\", srs::dpar::o_lat_1);\n                    lam2 = pj_get_param_r<T, srs::spar::o_lon_2>(params, \"o_lon_2\", srs::dpar::o_lon_2);\n                    phi2 = pj_get_param_r<T, srs::spar::o_lat_2>(params, \"o_lat_2\", srs::dpar::o_lat_2);\n                    if (fabs(phi1 - phi2) <= tolerance || (con = fabs(phi1)) <= tolerance ||\n                        fabs(con - half_pi) <= tolerance || fabs(fabs(phi2) - half_pi) <= tolerance)\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_1_or_2_zero_or_90) );\n\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\n                if (fabs(phip) > tolerance) { /* oblique */\n                    proj_parm.cphip = cos(phip);\n                    proj_parm.sphip = sin(phip);\n                } else { /* transverse */\n                }\n\n                // TODO:\n                /* Support some rather speculative test cases, where the rotated projection */\n                /* is actually latlong. We do not want scaling in that case... */\n                //if (proj_parm.link...mutable_parameters().right==PJ_IO_UNITS_ANGULAR)\n                //    par.right = PJ_IO_UNITS_PROJECTED;\n\n                // return phip to choose model\n                return phip;\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_ob_tran_oblique\n                : public base_t_fi<base_ob_tran_oblique<T, Parameters>, T, Parameters>\n            {\n                par_ob_tran<T, Parameters> m_proj_parm;\n\n                inline base_ob_tran_oblique(Parameters const& par,\n                                            par_ob_tran<T, Parameters> const& proj_parm)\n                    : base_t_fi\n                        <\n                            base_ob_tran_oblique<T, Parameters>, T, Parameters\n                        >(*this, par)\n                    , m_proj_parm(proj_parm)\n                {}\n\n                // FORWARD(o_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    o_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                }\n\n                // INVERSE(o_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    o_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\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 T, typename Parameters>\n            struct base_ob_tran_transverse\n                : public base_t_fi<base_ob_tran_transverse<T, Parameters>, T, Parameters>\n            {\n                par_ob_tran<T, Parameters> m_proj_parm;\n\n                inline base_ob_tran_transverse(Parameters const& par,\n                                               par_ob_tran<T, Parameters> const& proj_parm)\n                    : base_t_fi\n                        <\n                            base_ob_tran_transverse<T, Parameters>, T, Parameters\n                        >(*this, par)\n                    , m_proj_parm(proj_parm)\n                {}\n\n                // FORWARD(t_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    t_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                }\n\n                // INVERSE(t_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    t_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ob_tran_transverse\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename StaticParameters, typename T, typename Parameters>\n            struct base_ob_tran_static\n                : public base_t_fi<base_ob_tran_static<StaticParameters, T, Parameters>, T, Parameters>\n            {\n                par_ob_tran_static<StaticParameters, T, Parameters> m_proj_parm;\n                bool m_is_oblique;\n\n                inline base_ob_tran_static(StaticParameters const& params, Parameters const& par)\n                    : base_t_fi<base_ob_tran_static<StaticParameters, T, Parameters>, T, Parameters>(*this, par)\n                    , m_proj_parm(params, par)\n                {}\n\n                // FORWARD(o_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    if (m_is_oblique) {\n                        o_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                    } else {\n                        t_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\n                    }\n                }\n\n                // INVERSE(o_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    if (m_is_oblique) {\n                        o_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\n                    } else {\n                        t_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ob_tran\";\n                }\n\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 T, typename Parameters>\n    struct ob_tran_oblique : public detail::ob_tran::base_ob_tran_oblique<T, Parameters>\n    {\n        inline ob_tran_oblique(Parameters const& par,\n                               detail::ob_tran::par_ob_tran<T, Parameters> const& proj_parm)\n            : detail::ob_tran::base_ob_tran_oblique<T, Parameters>(par, proj_parm)\n        {\n            // already done\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 T, typename Parameters>\n    struct ob_tran_transverse : public detail::ob_tran::base_ob_tran_transverse<T, Parameters>\n    {\n        inline ob_tran_transverse(Parameters const& par,\n                                  detail::ob_tran::par_ob_tran<T, Parameters> const& proj_parm)\n            : detail::ob_tran::base_ob_tran_transverse<T, Parameters>(par, proj_parm)\n        {\n            // already done\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 StaticParameters, typename T, typename Parameters>\n    struct ob_tran_static : public detail::ob_tran::base_ob_tran_static<StaticParameters, T, Parameters>\n    {\n        inline ob_tran_static(StaticParameters const& params, Parameters const& par)\n            : detail::ob_tran::base_ob_tran_static<StaticParameters, T, Parameters>(params, par)\n        {\n            T phip = detail::ob_tran::setup_ob_tran<T>(params, this->m_par, this->m_proj_parm);\n            this->m_is_oblique = fabs(phip) > detail::ob_tran::tolerance;\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        template <typename SP, typename CT, typename P>\n        struct static_projection_type<srs::spar::proj_ob_tran, srs_sphere_tag, SP, CT, P>\n        {\n            typedef ob_tran_static<SP, CT, P> type;\n        };\n        template <typename SP, typename CT, typename P>\n        struct static_projection_type<srs::spar::proj_ob_tran, srs_spheroid_tag, SP, CT, P>\n        {\n            typedef ob_tran_static<SP, CT, P> type;\n        };\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_BEGIN(ob_tran_entry)\n        {\n            Parameters parameters_copy = parameters;\n            detail::ob_tran::par_ob_tran<T, Parameters> proj_parm(params, parameters_copy);\n            T phip = detail::ob_tran::setup_ob_tran<T>(params, parameters_copy, proj_parm);\n\n            if (fabs(phip) > detail::ob_tran::tolerance)\n                return new base_v_fi<ob_tran_oblique<T, Parameters>, T, Parameters>(parameters_copy, proj_parm);\n            else\n                return new base_v_fi<ob_tran_transverse<T, Parameters>, T, Parameters>(parameters_copy, proj_parm);\n        }\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_END\n\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(ob_tran_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(ob_tran, ob_tran_entry)\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_HPP\n\n", "meta": {"hexsha": "f5709228f5303fe8d9c5c84ced1c69d6c0a4344f", "size": 26618, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/geometry/srs/projections/proj/ob_tran.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/ob_tran.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/ob_tran.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": 42.3853503185, "max_line_length": 130, "alphanum_fraction": 0.5576301751, "num_tokens": 5891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.03622005963622317, "lm_q1q2_score": 0.01697962445330498}}
{"text": "/*!\nMIT License\n\nCopyright (c) 2022 Gotelli Andrea\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\n#include <ros/ros.h>\n#include <Eigen/Dense>\n\n#include <std_msgs/Float32.h>\n\n#include <dynamic_reconfigure/server.h>\n\n#include <gazebo_msgs/GetLinkState.h>\n#include <gazebo_msgs/ApplyBodyWrench.h>\n\n#include \"cpr_messages/PIDControllerTuningConfig.h\"\n#include \"cpr_messages/IGMParams.h\"\n#include \"cpr_messages/SE3Pose.h\"\n\n\n#include \"cpr_geometry/skew_operations.h\"\n\n#include <yaml-cpp/yaml.h>\n//#include <log2plot/logger.h>\n//#include <ros/package.h>\n\nusing namespace std;\n\n\nEigen::Affine3d GetDesiredPose(const double &set_point, const int controlled_dof)\n{\n  Eigen::Affine3d desired_pose = Eigen::Affine3d::Identity();\n  Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n\n  //  Depending on the dof to control, define the desired pose from set point\n  switch (controlled_dof) {\n  case 0: // case x is controlled\n    desired_pose.translation().x() = set_point;\n    break;\n  case 1: // case y is controlled\n    desired_pose.translation().y() = set_point;\n    break;\n  case 2: // case z is controlled\n    desired_pose.translation().z() = set_point;\n    break;\n  case 3: // case roll is controlled\n    R = Eigen::AngleAxisd(set_point, Eigen::Vector3d::UnitX())\n        * Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitY())\n        * Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitZ());\n    desired_pose.linear() = R;\n    //LogRotationMatrix( R );\n    break;\n  case 4: // case pitch is controlled\n    R = Eigen::AngleAxisd(0, Eigen::Vector3d::UnitX())\n        * Eigen::AngleAxisd(set_point, Eigen::Vector3d::UnitY())\n        * Eigen::AngleAxisd(0, Eigen::Vector3d::UnitZ());\n    desired_pose.linear() = R;\n    //LogRotationMatrix( R );\n    break;\n  case 5: // case yaw is controlled\n    R = Eigen::AngleAxisd(0, Eigen::Vector3d::UnitX())\n        * Eigen::AngleAxisd(0, Eigen::Vector3d::UnitY())\n        * Eigen::AngleAxisd(set_point, Eigen::Vector3d::UnitZ());\n    desired_pose.linear() = R;\n    //LogRotationMatrix( R );\n    break;\n  }\n\n  return desired_pose;\n}\n\n\nstatic Eigen::Affine3d desired_pose = Eigen::Affine3d::Identity();\nstatic bool callback_executed = false;\nstatic bool just_updated = false;\nvoid IGMParametersCallback(const cpr_messages::IGMParams::ConstPtr &igm_msg)\n{\n  desired_pose.translation() = Eigen::Vector3d(igm_msg->distal_plate_pose.position.x,\n                                                             igm_msg->distal_plate_pose.position.y,\n                                                             igm_msg->distal_plate_pose.position.z);\n\n  Eigen::Quaternion<double> q(igm_msg->distal_plate_pose.orientation.w,\n                              igm_msg->distal_plate_pose.orientation.x,\n                              igm_msg->distal_plate_pose.orientation.y,\n                              igm_msg->distal_plate_pose.orientation.z);\n\n  desired_pose.linear() = q.toRotationMatrix();\n\n  just_updated = true;\n\n  if(!callback_executed)\n    callback_executed = true;\n}\n\nEigen::Affine3d ToAffine3d( const geometry_msgs::Pose &pose)\n{\n  //  Directly compute the position\n  Eigen::Affine3d eigen_pose = Eigen::Affine3d::Identity();\n  eigen_pose.translation() << pose.position.x,\n                              pose.position.y,\n                              pose.position.z;\n\n  //  Copy the quaternion for the  orientation\n  Eigen::Quaternion<double> q(pose.orientation.w,\n                              pose.orientation.x,\n                              pose.orientation.y,\n                              pose.orientation.z);\n\n  //  Convert the quaternion to a rotation matrix\n  eigen_pose.linear() = q.toRotationMatrix();\n\n  return eigen_pose;\n}\n\n\nEigen::VectorXd ComputeSE3Error(const Eigen::Affine3d &desired_pose, const geometry_msgs::Pose &current_pose)\n{\n\n  //  Directly compute the position error\n  Eigen::Vector3d position_error(desired_pose.translation().x() - current_pose.position.x,\n                                 desired_pose.translation().y() - current_pose.position.y,\n                                 desired_pose.translation().z() - current_pose.position.z);\n\n  //  Copy the quaternion for the current distal plate orientation\n  Eigen::Quaternion<double> q_current(current_pose.orientation.w,\n                                      current_pose.orientation.x,\n                                      current_pose.orientation.y,\n                                      current_pose.orientation.z);\n\n  //  Convert the quaternion to a rotation matrix\n  Eigen::Matrix3d R_current = q_current.toRotationMatrix();\n\n  //  Obtain the desired rotation matrix\n  Eigen::Matrix3d R_desired = desired_pose.linear().matrix();\n\n  //  Compute the error in the orientation\n  Eigen::Vector3d orientation_error = cpr_geometry::inv_hat(R_current.transpose()*R_desired -\n                                                              R_current*R_desired.transpose());\n\n  //  Compose the vector containing the vector in SE(3)\n  Eigen::VectorXd SE3_error(6);\n  SE3_error << position_error, orientation_error;\n  return SE3_error;\n}\n\n\n\nEigen::Matrix<double, 6, 6> ToGainMatrix(const double &e_x,\n                                         const double &e_y,\n                                         const double &e_z,\n                                         const double &e_roll,\n                                         const double &e_pitch,\n                                         const double &e_yaw)\n{\n  Eigen::VectorXd proportional_gains(6);\n  proportional_gains << e_x, e_y, e_z, e_roll, e_pitch, e_yaw;\n  return proportional_gains.asDiagonal();\n}\n\ndouble LimitAngle(double angle)\n{\n  double corrected_angle = angle;\n  if(angle > 3)\n    corrected_angle = angle - M_PI;\n  if(angle < -3)\n    corrected_angle = angle + M_PI;\n\n  return corrected_angle;\n}\n\n\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv, \"controller\");\n  ros::NodeHandle nh;\n\n  const double dt = 0.001;\n\n  ros::Subscriber igm_parameters_listener = nh.subscribe<cpr_messages::IGMParams>(\"/igm_parameters\",1, IGMParametersCallback);\n\n  ros::ServiceClient link_state_client = nh.serviceClient<gazebo_msgs::GetLinkState>(\"/gazebo/get_link_state\");\n  gazebo_msgs::GetLinkStateRequest link_state_request;\n  gazebo_msgs::GetLinkStateResponse link_state_response;\n  link_state_request.link_name = \"distal_plate::distal_plate\";\n  link_state_request.reference_frame = \"world\";\n\n  ros::ServiceClient apply_wrench_client = nh.serviceClient<gazebo_msgs::ApplyBodyWrench>(\"/gazebo/apply_body_wrench\");\n  gazebo_msgs::ApplyBodyWrenchRequest apply_body_wrench_request;\n  gazebo_msgs::ApplyBodyWrenchResponse apply_body_wrench_response;\n  apply_body_wrench_request.body_name = \"distal_plate::distal_plate\";\n  apply_body_wrench_request.reference_frame = \"world\";\n  apply_body_wrench_request.duration.fromSec(dt);\n\n\n  ros::Publisher distal_plate_wrench_controller = nh.advertise<geometry_msgs::Wrench>(\"/controller_wrench\", 1);\n  geometry_msgs::Wrench correction_wrench;\n\n  //  Here the declaration of the Server element.\n  dynamic_reconfigure::Server<cpr_messages::PIDControllerTuningConfig> server;\n\n  cpr_messages::SE3Pose desired_values;\n  ros::Publisher desired_values_publisher = nh.advertise<cpr_messages::SE3Pose>(\"/desired_values\", 1);\n\n  cpr_messages::SE3Pose current_values;\n  ros::Publisher current_values_publisher = nh.advertise<cpr_messages::SE3Pose>(\"/current_values\", 1);\n\n\n  ros::Publisher time_publisher = nh.advertise<std_msgs::Float32>(\"/time\", 1);\n\n\n  double set_point = 0.0;\n  ros::Subscriber set_point_listener = nh.subscribe<std_msgs::Float32>(\"/desired_value\", 1,\n                                                                            [&set_point](const std_msgs::Float32::ConstPtr &msg){\n                                                                              set_point = static_cast<double>(msg->data);\n                                                                            });\n\n  double kpe_x     = 2.5;\n  double kpe_y     = 2.5;\n  double kpe_z     = 2.5;\n  double kpe_roll  = 0.04;\n  double kpe_pitch = 0.04;\n  double kpe_yaw   = 0.4;\n\n  Eigen::Matrix<double, 6, 6> Kp = 2*ToGainMatrix(kpe_x, kpe_y, kpe_z, kpe_roll, kpe_pitch, kpe_yaw);\n\n\n  double kde_x     = 2.2;\n  double kde_y     = 2.2;\n  double kde_z     = 2.5;\n  double kde_roll  = 0.035;\n  double kde_pitch = 0.035;\n  double kde_yaw   = 0.4;\n\n  Eigen::Matrix<double, 6, 6> Kd = 1.8*ToGainMatrix(kde_x, kde_y, kde_z, kde_roll, kde_pitch, kde_yaw);\n\n\n//  double kie_x     = 0.0;\n//  double kie_y     = 0.0;\n//  double kie_z     = 0.0;\n//  double kie_roll  = 0.0;\n//  double kie_pitch = 0.0;\n//  double kie_yaw   = 0.0;\n  double kie_x     = 5;\n  double kie_y     = 5;\n  double kie_z     = 5;\n  double kie_roll  = 0.5;\n  double kie_pitch = 0.5;\n  double kie_yaw   = 0.5;\n\n  Eigen::Matrix<double, 6, 6> Ki = 0.01*ToGainMatrix(kie_x, kie_y, kie_z, kie_roll, kie_pitch, kie_yaw);\n\n\n  int controlled_dof = 2;\n  bool start = false;\n  server.setCallback( [&](const cpr_messages::PIDControllerTuningConfig &config, uint32_t){\n    start = config.start;\n\n//    Kp = ToGainMatrix(config.kde_x, config.kde_y, config.kde_z, config.kde_roll, config.kde_pitch, config.kde_yaw);\n\n//    Kd = ToGainMatrix(config.kde_x, config.kde_y, config.kde_z, config.kde_roll, config.kde_pitch, config.kde_yaw);\n\n//    Ki = ToGainMatrix(config.kie_x, config.kie_y, config.kie_z, config.kie_roll, config.kie_pitch, config.kie_yaw);\n\n  } );\n\n\n  Eigen::VectorXd SE3_error = Eigen::VectorXd::Zero(6);\n  Eigen::VectorXd previous_SE3_error = Eigen::VectorXd::Zero(6);\n  Eigen::VectorXd SE3_error_derivative = Eigen::VectorXd::Zero(6);\n  Eigen::VectorXd SE3_error_integral = Eigen::VectorXd::Zero(6);\n  Eigen::VectorXd PID_output = Eigen::VectorXd::Zero(6);\n\n\n  YAML::Emitter emitter;\n  std::vector<double> z_des;\n  std::vector<double> roll_des;\n  std::vector<double> pitch_des;\n\n  std::vector<double> z;\n  std::vector<double> roll;\n  std::vector<double> pitch;\n\n  std::vector<double> time;\n\n  std_msgs::Float32 time_msgs;\n\n\n\n  ros::Rate rate(1.0/dt);\n  while(ros::ok()){\n    ros::spinOnce();\n\n    time.push_back( ros::Time::now().toSec() );\n\n    time_msgs.data = ros::Time::now().toSec();\n    time_publisher.publish( time_msgs );\n\n\n    if(!callback_executed /*|| !start*/) {\n      cout << \"Waiting...\" << endl;\n      PID_output = Eigen::VectorXd::Zero(6);\n      SE3_error_integral = Eigen::VectorXd::Zero(6);\n      cout << \"Desired Pose : \" << endl << GetDesiredPose(set_point, controlled_dof).matrix() << endl << endl;\n      rate.sleep();\n      continue;\n    }\n\n    //  Otherwise get the actual position of the distal plate\n    if(!link_state_client.call(link_state_request, link_state_response)){\n      //  If the call has failed just skip\n      rate.sleep();\n      ROS_WARN_STREAM(link_state_response.status_message);\n      continue;\n    }\n\n\n\n    //  Comput the error in SE3\n//    SE3_error = ComputeSE3Error(GetDesiredPose(set_point, controlled_dof),\n//                                               link_state_response.link_state.pose);\n\n    SE3_error = ComputeSE3Error(desired_pose, link_state_response.link_state.pose);\n\n    //  Comput the integral\n    SE3_error_integral += SE3_error * dt;\n\n    //  Comput the Derivative\n    SE3_error_derivative = (SE3_error - previous_SE3_error)/dt;\n    previous_SE3_error = SE3_error;\n\n\n    PID_output = Kp * SE3_error            +  //  P\n                 Ki * SE3_error_integral   +  //  I\n                 Kd * SE3_error_derivative ;  //  D\n\n\n//    apply_body_wrench_request.start_time = ros::Time::now();\n//    apply_body_wrench_request.wrench.force.x = PID_output[0];\n//    apply_body_wrench_request.wrench.force.y = PID_output[1];\n//    apply_body_wrench_request.wrench.force.z = PID_output[2];\n//    apply_body_wrench_request.wrench.torque.x = PID_output[3];\n//    apply_body_wrench_request.wrench.torque.y = PID_output[4];\n//    apply_body_wrench_request.wrench.torque.z = PID_output[5];\n\n//    if(!apply_wrench_client.call(apply_body_wrench_request, apply_body_wrench_response))\n//      ROS_WARN_STREAM(apply_body_wrench_response.status_message);\n\n\n    correction_wrench.force.x = PID_output[0];\n    correction_wrench.force.y = PID_output[1];\n    correction_wrench.force.z = PID_output[2];\n    correction_wrench.torque.x = PID_output[3];\n    correction_wrench.torque.y = PID_output[4];\n    correction_wrench.torque.z = PID_output[5];\n\n    distal_plate_wrench_controller.publish( correction_wrench );\n\n\n    //  Publish the values for plotting\n    desired_values.x = static_cast<float>( desired_pose.translation().x() );\n    desired_values.y = static_cast<float>( desired_pose.translation().y() );\n    desired_values.z = static_cast<float>( desired_pose.translation().z() );\n    desired_values.roll = static_cast<float>( LimitAngle(desired_pose.linear().eulerAngles(0,1,2)[0]) );\n    desired_values.pitch = static_cast<float>( LimitAngle(desired_pose.linear().eulerAngles(0,1,2)[1]) );\n    desired_values.yaw = static_cast<float>( LimitAngle(desired_pose.linear().eulerAngles(0,1,2)[2]) );\n\n    desired_values_publisher.publish( desired_values );\n\n\n    Eigen::Affine3d current_pose = ToAffine3d( link_state_response.link_state.pose );\n\n\n    current_values.x = static_cast<float>( current_pose.translation().x() );\n    current_values.y = static_cast<float>( current_pose.translation().y() );\n    current_values.z = static_cast<float>( current_pose.translation().z() );\n    current_values.roll = static_cast<float>( LimitAngle(current_pose.linear().eulerAngles(0,1,2)[0]) );\n    current_values.pitch = static_cast<float>( LimitAngle(current_pose.linear().eulerAngles(0,1,2)[1]) );\n    current_values.yaw = static_cast<float>( LimitAngle(current_pose.linear().eulerAngles(0,1,2)[2]) );\n\n\n    current_values_publisher.publish( current_values );\n\n    rate.sleep();\n  }\n\n//  emitter << YAML::BeginMap;\n\n//  emitter << YAML::Key << \"desired_values\";\n//  emitter << YAML::Value << YAML::BeginMap;\n//      emitter << YAML::Key << \"z_desired\" << YAML::Value << YAML::Flow << z_des;\n//  emitter << YAML::EndMap;\n//  emitter << YAML::Newline;\n//  emitter << YAML::Value << YAML::BeginMap;\n//      emitter << YAML::Key << \"roll_desired\" << YAML::Value << YAML::Flow << roll_des;\n//  emitter << YAML::EndMap;\n//  emitter << YAML::Newline;\n//  emitter << YAML::Value << YAML::BeginMap;\n//      emitter << YAML::Key << \"pitch_desired\" << YAML::Value << YAML::Flow << pitch_des;\n//  emitter << YAML::EndMap;\n//  emitter << YAML::Newline;\n\n//  emitter << YAML::Key << \"current_values\";\n//  emitter << YAML::Value << YAML::BeginMap;\n//      emitter << YAML::Key << \"z\" << YAML::Value << YAML::Flow << z;\n//  emitter << YAML::EndMap;\n//  emitter << YAML::Newline;\n//  emitter << YAML::Value << YAML::BeginMap;\n//      emitter << YAML::Key << \"roll\" << YAML::Value << YAML::Flow << roll;\n//  emitter << YAML::EndMap;\n//  emitter << YAML::Newline;\n//  emitter << YAML::Value << YAML::BeginMap;\n//      emitter << YAML::Key << \"pitch\" << YAML::Value << YAML::Flow << pitch;\n//  emitter << YAML::EndMap;\n//  emitter << YAML::Newline;\n\n//  emitter << YAML::EndMap;\n\n\n  return 0;\n}\n", "meta": {"hexsha": "46ab8f5210a054057d3237202b9233c3b003a988", "size": 16007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPR_spatial/cpr_physics/src/controller.cpp", "max_stars_repo_name": "aGotelli/A_Gazebo_Simulator_For_Continuum_Parallel_Robots", "max_stars_repo_head_hexsha": "17b856e619dbd95dfbba3682252fcc5186533b33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-18T19:13:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T19:13:42.000Z", "max_issues_repo_path": "CPR_spatial/cpr_physics/src/controller.cpp", "max_issues_repo_name": "aGotelli/A_Gazebo_Simulator_For_Continuum_Parallel_Robots", "max_issues_repo_head_hexsha": "17b856e619dbd95dfbba3682252fcc5186533b33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPR_spatial/cpr_physics/src/controller.cpp", "max_forks_repo_name": "aGotelli/A_Gazebo_Simulator_For_Continuum_Parallel_Robots", "max_forks_repo_head_hexsha": "17b856e619dbd95dfbba3682252fcc5186533b33", "max_forks_repo_licenses": ["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.0518018018, "max_line_length": 129, "alphanum_fraction": 0.6630849004, "num_tokens": 4052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.03622005755553433, "lm_q1q2_score": 0.01697962347789755}}
{"text": "#pragma once\n#ifndef OPENGM_PARTITION_HXX\n#define OPENGM_PARTITION_HXX\n\n#include <vector>\n#include <map>\n\n#ifdef WITH_BOOST\n#include <boost/unordered_map.hpp>\n#endif\n\n\nnamespace opengm {\n\n/// Disjoint set data structure with path compression.\n/// \\ingroup datastructures\ntemplate<class T = size_t>\nclass Partition {\npublic:\n   typedef T value_type;\n\n   Partition();\n   Partition(const value_type&);\n\n   // query\n   value_type find(const value_type&) const; // without path compression\n   value_type find(value_type); // with path compression\n   value_type numberOfElements() const;\n   value_type numberOfSets() const;\n   template<class Iterator> void elementLabeling(Iterator) const;\n   template<class Iterator> void representatives(Iterator) const;\n   void representativeLabeling(std::map<value_type, value_type>&) const;\n\n\n   #ifdef WITH_BOOST\n   void representativeLabeling(boost::unordered_map<value_type, value_type>&) const;\n   #endif\n\n\n\n   // manipulation\n   void reset(const value_type&);\n   void merge(value_type, value_type);\n   void insert(const value_type&);\n\nprivate:\n   std::vector<value_type> parents_;\n   std::vector<value_type> ranks_;\n   value_type numberOfElements_;\n   value_type numberOfSets_;\n};\n\n/// Construct a partition.\ntemplate<class T>\nPartition<T>::Partition()\n: parents_(),\n  ranks_(),\n  numberOfElements_(0),\n  numberOfSets_(0)\n{}\n\n/// Construct a partition.\n///\n/// \\param size Number of distinct sets.\n///\ntemplate<class T>\ninline\nPartition<T>::Partition\n(\n   const value_type& size\n)\n: parents_(static_cast<size_t>(size)),\n  ranks_(static_cast<size_t>(size)),\n  numberOfElements_(size),\n  numberOfSets_(size)\n{\n   for(T j=0; j<size; ++j) {\n      parents_[static_cast<size_t>(j)] = j;\n   }\n}\n\n/// Reset a partition such that each set contains precisely one element\n///\n/// \\param size Number of distinct sets.\n///\ntemplate<class T>\ninline void\nPartition<T>::reset\n(\n   const value_type& size\n)\n{\n   numberOfElements_ = size;\n   numberOfSets_ = size;\n   ranks_.resize(static_cast<size_t>(size));\n   parents_.resize(static_cast<size_t>(size));\n   for(T j=0; j<size; ++j) {\n      ranks_[static_cast<size_t>(j)] = 0;\n      parents_[static_cast<size_t>(j)] = j;\n   }\n}\n\n/// Find the representative element of the set that contains the given element.\n///\n/// This constant function does not compress the search path.\n///\n/// \\param element Element.\n///\ntemplate<class T>\ninline typename Partition<T>::value_type\nPartition<T>::find\n(\n   const value_type& element\n) const\n{\n   // find the root\n   value_type root = element;\n   while(parents_[static_cast<size_t>(root)] != root) {\n      root = parents_[static_cast<size_t>(root)];\n   }\n   return root;\n}\n\n/// Find the representative element of the set that contains the given element.\n///\n/// This mutable function compresses the search path.\n///\n/// \\param element Element.\n///\ntemplate<class T>\ninline typename Partition<T>::value_type\nPartition<T>::find\n(\n   value_type element // copy to work with\n)\n{\n   // find the root\n   value_type root = element;\n   while(parents_[static_cast<size_t>(root)] != root) {\n      root = parents_[static_cast<size_t>(root)];\n   }\n   // path compression\n   while(element != root) {\n      value_type tmp = parents_[static_cast<size_t>(element)];\n      parents_[static_cast<size_t>(element)] = root;\n      element = tmp;\n   }\n   return root;\n}\n\n/// Merge two sets.\n///\n/// \\param element1 Element in the first set.\n/// \\param element2 Element in the second set.\n///\ntemplate<class T>\ninline void\nPartition<T>::merge\n(\n   value_type element1,\n   value_type element2\n)\n{\n   // merge by rank\n   element1 = find(element1);\n   element2 = find(element2);\n   if(ranks_[static_cast<size_t>(element1)] < ranks_[static_cast<size_t>(element2)]) {\n      parents_[static_cast<size_t>(element1)] = element2;\n      --numberOfSets_;\n   }\n   else if(ranks_[static_cast<size_t>(element1)] > ranks_[static_cast<size_t>(element2)]) {\n      parents_[static_cast<size_t>(element2)] = element1;\n      --numberOfSets_;\n   }\n   else if(element1 != element2) {\n      parents_[static_cast<size_t>(element2)] = element1;\n      ++ranks_[static_cast<size_t>(element1)];\n      --numberOfSets_;\n   }\n}\n\n/// Insert new sets.\n///\n/// \\param number Number of sets to insert.\n///\ntemplate<class T>\ninline void\nPartition<T>::insert\n(\n   const value_type& number\n)\n{\n   ranks_.insert(ranks_.end(), static_cast<size_t>(number), T(0));\n   parents_.insert(parents_.end(), static_cast<size_t>(number), T(0));\n   for(value_type j=numberOfElements_; j<numberOfElements_+number; ++j) {\n      parents_[static_cast<size_t>(j)] = j;\n   }\n   numberOfElements_ += number;\n   numberOfSets_ += number;\n}\n\n/// Output all elements which are set representatives.\n///\n/// \\param it (Output) Iterator into a container.\n///\ntemplate<class T>\ntemplate<class Iterator>\ninline void\nPartition<T>::representatives\n(\n   Iterator it\n) const\n{\n   for(value_type j=0; j<numberOfElements(); ++j) {\n      if(parents_[static_cast<size_t>(j)] == j) {\n         *it = j;\n         ++it;\n      }\n   }\n}\n\n/// Output a continuous labeling of the representative elements.\n///\n/// \\param out (Output) A map that assigns each representative element to its label.\n///\ntemplate<class T>\ninline void\nPartition<T>::representativeLabeling\n(\n   std::map<value_type, value_type>& out\n) const\n{\n   out.clear();\n   std::vector<value_type> r(static_cast<size_t>(numberOfSets()));\n   representatives(r.begin());\n   for(T j=0; j<numberOfSets(); ++j) {\n      out[ r[static_cast<size_t>(j)] ] = j;\n   }\n}\n\n\n#ifdef WITH_BOOST\n/// Output a continuous labeling of the representative elements.\n///\n/// \\param out (Output) A map that assigns each representative element to its label.\n///\ntemplate<class T>\ninline void\nPartition<T>::representativeLabeling\n(\n   boost::unordered_map<value_type, value_type>& out\n) const\n{\n   out.clear();\n   std::vector<value_type> r(static_cast<size_t>(numberOfSets()));\n   representatives(r.begin());\n   for(T j=0; j<numberOfSets(); ++j) {\n      out[ r[static_cast<size_t>(j)] ] = j;\n   }\n}\n\n#endif \n\n/// Output a continuous labeling of all elements.\n///\n/// \\param out (Output) Iterator into a container in which the j-th entry is the label of the element j.\n///\ntemplate<class T>\ntemplate<class Iterator>\ninline void\nPartition<T>::elementLabeling\n(\n   Iterator out\n) const\n{\n   std::map<value_type, value_type> rl;\n   representativeLabeling(rl);\n   for(value_type j=0; j<numberOfElements(); ++j) {\n      *out = rl[find(j)];\n      ++out;\n   }\n}\n\ntemplate<class T>\ninline typename Partition<T>::value_type\nPartition<T>::numberOfElements() const\n{\n   return numberOfElements_;\n}\n\ntemplate<class T>\ninline typename Partition<T>::value_type\nPartition<T>::numberOfSets() const\n{\n   return numberOfSets_;\n}\n\n} // namespace opengm\n\n#endif // #ifndef OPENGM_PARTITION_HXX\n", "meta": {"hexsha": "cb2c161cf6a9897fa52c877d0e6456b501bff96f", "size": 6807, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/opengm/datastructures/partition.hxx", "max_stars_repo_name": "DerThorsten/boring_spaghetti", "max_stars_repo_head_hexsha": "0cacb5cf66d5ebd09f060fda87efcdb7e9c487f3", "max_stars_repo_licenses": ["MIT"], "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/opengm/datastructures/partition.hxx", "max_issues_repo_name": "DerThorsten/boring_spaghetti", "max_issues_repo_head_hexsha": "0cacb5cf66d5ebd09f060fda87efcdb7e9c487f3", "max_issues_repo_licenses": ["MIT"], "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/opengm/datastructures/partition.hxx", "max_forks_repo_name": "DerThorsten/boring_spaghetti", "max_forks_repo_head_hexsha": "0cacb5cf66d5ebd09f060fda87efcdb7e9c487f3", "max_forks_repo_licenses": ["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.6146179402, "max_line_length": 104, "alphanum_fraction": 0.6884089907, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.0453525766833672, "lm_q1q2_score": 0.016956231922310376}}
{"text": "/**\n *  Author: Cedric LE GENTIL\n *\n *  Copyright 2021 Cedric LE GENTIL\n *\n *  This is a simple example of how to generate the UGPMs\n *  \n *  Disclaimer:\n *  This code is not optimised neither for performance neither for maintainability.\n *  There might still be errors in the code, logic or procedure. Every feedback is welcomed.\n *\n *  For any further question or if you see any problem in that code\n *  le.gentil.cedric@gmail.com\n **/\n\n\n#include <iostream>\n#include <string>\n#include <stdio.h>\n#include <fstream>\n#include <iomanip> \n#include <boost/program_options.hpp>\n#include \"sensor_input/imu_simulator.h\"\n#include \"imu_preintegration/preintegration.h\"\n#include \"common/random.h\"\n#include \"common/utils.h\"\n#include <math.h>\n\nstd::string get_content(std::string &str, int N){\n\n    int start_of_path;\n    std::string path;\n    for (int i = 0; i < N; i++) {\n        if(int(str[i]) == 58){\n            start_of_path = i+1;\n        }\n    }\n    path = str.substr(start_of_path, N);\n    path.erase(std::remove_if(path.begin(), path.end(), [](unsigned char x) { return std::isspace(x); }), path.end());\n    \n    return path;\n}\n\nstd::vector<std::string> readYAML()\n{\n    /* This is a primitive yaml-reader custom build for the expected yaml-file*/\n\n    std::ifstream f;\n\n    f.open (\"../config.yaml\");   /* open file with filename as argument */\n    if (! f.is_open()) {    /* validate file open for reading */\n        std::cerr << \"error: file open failed.\\n\";\n    }\n\n    std::vector<std::string> expected_strings = {\"imu_raw:\", \"sampling_times:\", \"save_path\", \"sum_prior\", \"g_const\"};\n    std::vector<std::string> config_content;\n\n    int expected_amount = expected_strings.size();\n    int retrieved_amount = 0;\n\n    bool in_ugpm = false;\n    std::string line;\n\n    while (std::getline (f, line)) {        /* read each line */\n        if(line.find(\"ugpm:\") != std::string::npos){\n            in_ugpm = true;\n        }\n        if(in_ugpm){\n            for(std::string str : expected_strings){\n                if ( line.find(str) != std::string::npos && retrieved_amount<expected_amount) {\n                    int N = line.length();\n                    std::string content = get_content(line,N);\n                    config_content.push_back(content);\n                    retrieved_amount++;\n                }\n            }\n        }\n    }\n    return config_content;\n}\n\n\n\nstd::vector<std::vector<double>> readCSV(std::string path)\n{\n    std::ifstream f;\n    std::cout << \"reading csv file \\n\";\n\n    f.open (path);   /* open file with filename as argument */\n    if (! f.is_open()) {    /* validate file open for reading */\n        std::cerr << \"error: file open failed.\\n\";\n    }\n\n    std::string line, val;                  /* string for line & value */\n    std::vector<std::vector<double>> array;    /* vector of vector<int>  */\n\n    while (std::getline (f, line)) {        /* read each line */\n        std::vector<double> v;                 /* row vector v */\n        std::stringstream s (line);         /* stringstream line */\n        while (getline (s, val, ','))       /* get each value (',' delimited) */\n            v.push_back (std::stod (val));  /* add to row vector */\n        array.push_back (v);                /* add row vector to array */\n    }\n\n    return array;\n}\n\nvoid saveCSV(std::string path, std::vector<std::vector<double>> *array, std::string seperator, int precision, std::string header){\n\n    std::ofstream myfile (path);\n    std::cout << \"Saving csv to \" << path << \"\\n\"; \n    \n    bool write_header = false;\n\n    if (myfile.is_open()){\n        if(!header.empty()){\n            myfile << header << \"\\n\";\n        }\n        for (const auto& inner : *array) {\n            for (const auto& item : inner) {\n\n                myfile << std::fixed << std::setprecision(precision) << std::scientific <<item << seperator << \" \";\n            }\n            myfile << \"\\n\";  \n        }\n        myfile.close();\n    }else{\n        std::cout << \"Unable to open file\";} \n}\n\ncelib::ImuData convertArray(std::vector<std::vector<double>> *array){\n    \n    std::cout << \"converting csv array to ImuData format: \\n\";\n    \n    std::vector<double> imu_raw(7);     // {t, acc_x, acc_y, acc_z, gyr_x, gyr_y, gyr_z}\n    celib::ImuData imu_data;\n\n    int i;\n    for (auto& row : *array) {               /* iterate over rows */\n        celib::ImuSample acc, gyr;\n        i = 0;\n        for (auto& val : row){               /* iterate over vals */\n            imu_raw[i] = val;\n            i++;        \n        }\n\n        double acc_data[3] = {imu_raw[1], imu_raw[2], imu_raw[3]};\n        double gyr_data[3] = {imu_raw[4], imu_raw[5], imu_raw[6]};\n        acc.t = imu_raw[0];\n        gyr.t = imu_raw[0];\n        memcpy(acc.data, acc_data, sizeof(acc_data));\n        memcpy(gyr.data, gyr_data, sizeof(gyr_data));\n\n        imu_data.acc.push_back(acc);\n        imu_data.gyr.push_back(gyr);\n        imu_data.acc_var = 1.25e-7;\n        imu_data.gyr_var = 2.0e-4;\n        \n    }\n    return imu_data;\n}\n\nstd::vector<std::vector<double>> integrate_between_samples(celib::ImuData imu_data, std::vector<std::vector<double>> sample_time_array, \n                                                           celib::PreintOption preint_opt){\n    /*\n        Format is\n\n        t_i delta_t a_x a_y a_z w_x w_y w_z\n\n        t_i is current time\n        delta_t is t_i - t_i-1\n        a_x, a_y, a_z is defined as v_i - v_i-1\n        w_x, w_y, w_z is defined as angle_i - angle_i-1\n    */\n\n    double dpdt_x_prior, dpdt_y_prior, dpdt_z_prior = 0;\n    double dpdt_x, dpdt_y, dpdt_z, dvdt_x, dvdt_y, dvdt_z, t_iter, t_iter_prev, dt;\n\n    t_iter_prev = sample_time_array[0][0];\n\n    int a = 0;\n    int N = sample_time_array.size();\n\n    std::vector<double> data_iter;\n    std::vector<std::vector<double>> t, data_array;\n    \n\n    for(int i = 1; i < N; i++){\n\n        data_iter.clear();\n\n        t_iter = sample_time_array[i][0];\n\n        t.clear();\n        t.push_back({t_iter});\n\n        celib::PreintPrior prior;\n        celib::StopWatch stop_watch;\n        stop_watch.start();\n        celib::ImuPreintegration preint(imu_data, t_iter_prev, t, preint_opt, prior);\n        stop_watch.stop();\n        stop_watch.print();\n\n        celib::PreintMeas preint_meas = preint.get(0,0);\n            \n        // This conversion between R and euler angles may be a possible source of error\n        Eigen::Vector3d euler_t = preint_meas.delta_R.eulerAngles(2, 1, 0);\n\n         \n        dt = t_iter - t_iter_prev;\n\n        data_iter.push_back(t_iter);\n        data_iter.push_back(dt);\n\n        for(int a = 0; a < 3; a++){\n            for(int b = 0; b < 3; b++){\n                data_iter.push_back(preint_meas.delta_R.coeff(a,b));\n            }\n        }\n        for(int a = 0; a < 3; a++){\n            data_iter.push_back(preint_meas.delta_v[a]);\n        }\n        for(int a = 0; a < 3; a++){\n            data_iter.push_back(preint_meas.delta_p[a]);\n        }\n        for(int a = 0; a < 3; a++){\n            for(int b = 0; b < 3; b++){\n                data_iter.push_back(preint_meas.cov.coeff(a,b));\n            }\n        }\n        for(int a = 3; a < 6; a++){\n            for(int b = 3; b < 6; b++){\n                data_iter.push_back(preint_meas.cov.coeff(a,b));\n            }\n        }\n        for(int a = 6; a < 9; a++){\n            for(int b = 6; b < 9; b++){\n                data_iter.push_back(preint_meas.cov.coeff(a,b));\n            }\n        }\n\n        data_array.push_back(data_iter);\n        t_iter_prev = t_iter;\n        dpdt_x_prior = dpdt_x;\n        dpdt_y_prior = dpdt_y;\n        dpdt_z_prior = dpdt_z;\n    }\n    return data_array;\n}\n\nvoid pre_integrate_between_frames(celib::PreintOption preint_opt){\n    std::vector<std::string> config_content = readYAML();\n    std::vector<std::vector<double>> imu_array, sample_time_array, data_array;\n\n    imu_array = readCSV(config_content[0]);\n    sample_time_array = readCSV(config_content[1]);\n\n    celib::ImuData imu_data = convertArray(&imu_array);\n\n    data_array = integrate_between_samples(imu_data, sample_time_array, preint_opt);\n    std::string header_str = \"t dt dR_11 dR_12 dR_13 dR_21 dR_22 dR_23 dR_31 dR_32 dR_33\";\n    header_str += \" dv_x dv_y dv_z dp_x dp_y dp_z\";\n    header_str += \" cov_dR_11 cov_dR_12 cov_dR_13 cov_dR_21 cov_dR_22 cov_dR_23 cov_dR_31 cov_dR_32 cov_dR_33\";\n    header_str += \" cov_dv_11 cov_dv_12 cov_dv_13 cov_dv_21 cov_dv_22 cov_dv_23 cov_dv_31 cov_dv_32 cov_dv_33\";\n    header_str += \" cov_dp_11 cov_dp_12 cov_dp_13 cov_dp_21 cov_dp_22 cov_dp_23 cov_dp_31 cov_dp_32 cov_dp_33\";\n    saveCSV(config_content[2], &data_array, \"\", 18, header_str);\n\n}\n\nint main(int argc, char* argv[]){\n\n    celib::PreintOption preint_opt;\n    bool test_jacobians;\n\n\n    // Program options\n    boost::program_options::options_description opt_description(\"Allowed options\");\n    opt_description.add_options()\n        (\"help,h\", \"Produce help message\")\n        (\"method,m\", boost::program_options::value< std::string >(), \"LPM | GPM | UGPM(default)\")\n        (\"length,l\", boost::program_options::value< double >(), \"Length simulated integration (default = 2.0)\")\n        (\"train,t\", boost::program_options::bool_switch(&preint_opt.train_gpm), \"Flag to activate training\")\n        (\"jacobian,j\", boost::program_options::bool_switch(&test_jacobians), \"Flag to activate the testing of the Jacobians\")\n        (\"nb_inference,n\", boost::program_options::value< int >(), \"Nb of inferrences (to simulate lidar nb of inferences), Default = 1\")\n        (\"quantum,q\", boost::program_options::value< double >(), \"Time quantum for piece-wise integration (useful for long integration intervals, -1 to deactivate (default = 0.2)\")\n        ;\n\n    boost::program_options::variables_map var_map;\n    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, opt_description), var_map);\n    boost::program_options::notify(var_map);    \n\n    if(var_map.count(\"help\")) {\n        std::cout << opt_description << std::endl;\n        return 1;\n    }\n\n    preint_opt.type = celib::UGPM;\n    if(var_map.count(\"method\"))\n    {\n        std::string type = var_map[\"method\"].as<std::string>();\n        std::transform(type.begin(), type.end(), type.begin(), [](unsigned char c){ return std::tolower(c); });\n        if(type == \"lpm\") preint_opt.type = celib::LPM;\n        else if(type == \"gpm\") preint_opt.type = celib::GPM;\n        else if(type == \"ugpm\") preint_opt.type = celib::UGPM;\n        else\n        {\n            std::cout << \"ERROR: The type of preintegration method is unknown, program stopping now\" << std::endl;\n            return 1;\n        }\n    }\n    std::string to_print;\n    switch (preint_opt.type)\n    {\n    case celib::LPM:\n        to_print = \"LPM\";\n        break;\n    \n    case celib::GPM:\n        to_print = \"GPM\";\n        break;\n    \n    case celib::UGPM:\n        to_print = \"UGPM\";\n        break;\n    \n    default:\n        break;\n    }\n    std::cout << \"Preintegration demonstration with \" << to_print << std::endl;\n\n    double integration_length = 0.2;\n    if(var_map.count(\"length\"))\n    {\n        integration_length = var_map[\"length\"].as<double>();\n    }\n\n    int nb_infer = 0;\n    if(var_map.count(\"nb_inference\"))\n    {\n        nb_infer = var_map[\"nb_inference\"].as<int>() - 1;\n    }\n\n    preint_opt.quantum = -1;\n    if(var_map.count(\"quantum\"))\n    {\n        preint_opt.quantum = var_map[\"quantum\"].as<double>();\n    }\n\n    preint_opt.min_freq = 1000;\n\n    pre_integrate_between_frames(preint_opt);\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "cc3b34f685a630bb583198849c51f1be5d55eac6", "size": 11477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/app/src/frame_integration.cpp", "max_stars_repo_name": "ecbaum/ugpm", "max_stars_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/app/src/frame_integration.cpp", "max_issues_repo_name": "ecbaum/ugpm", "max_issues_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/app/src/frame_integration.cpp", "max_forks_repo_name": "ecbaum/ugpm", "max_forks_repo_head_hexsha": "3ab6ff2dbc59642e0e9739f5f4647a906f19e333", "max_forks_repo_licenses": ["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.1484593838, "max_line_length": 180, "alphanum_fraction": 0.5840376405, "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.03904829552194685, "lm_q1q2_score": 0.016946236488710003}}
{"text": "/* ****************************************************************** **\n**    OpenSees - Open System for Earthquake Engineering Simulation    **\n**          Pacific Earthquake Engineering Research Center            **\n**                                                                    **\n**                                                                    **\n** (C) Copyright 1999, The Regents of the University of California    **\n** All Rights Reserved.                                               **\n**                                                                    **\n** Commercial use of this program without express permission of the   **\n** University of California, Berkeley, is strictly prohibited.  See   **\n** file 'COPYRIGHT'  in main directory for information on usage and   **\n** redistribution,  and for a DISCLAIMER OF ALL WARRANTIES.           **\n**                                                                    **\n** Developed by:                                                      **\n**   Frank McKenna (fmckenna@ce.berkeley.edu)                         **\n**   Gregory L. Fenves (fenves@ce.berkeley.edu)                       **\n**   Filip C. Filippou (filippou@ce.berkeley.edu)                     **\n**                                                                    **\n** ****************************************************************** */\n                                                                        \n// $Revision: 1.3 $\n// $Date: 2005-12-19 22:43:36 $\n// $Source: /usr/local/cvs/OpenSees/SRC/analysis/integrator/EigenIntegrator.cpp,v $\n                                                                        \n// Written: Jun Peng\n// Created: Wed Jan 27, 1999\n// Revision: A\n//\n// Description: This file contains the class definition of EigenIntegrator.\n// EigenIntegrator is an algorithmic class for setting up the finite element \n// equations for a eigen problem analysis.\n//\n// This class is inheritanted from the base class of Integrator which was\n// created by fmk (Frank).\n\n\n#include \"EigenIntegrator.h\"\n#include <FE_Element.h>\n#include <AnalysisModel.h>\n#include <EigenSOE.h>\n#include <Vector.h>\n#include <DOF_Group.h>\n#include <FE_EleIter.h>\n#include <DOF_GrpIter.h>\n\nEigenIntegrator::EigenIntegrator()\n  :Integrator(EigenINTEGRATOR_TAGS_Eigen),\n   theSOE(0), theAnalysisModel(0)\n{\n\n}\n\nEigenIntegrator::~EigenIntegrator()\n{\n\n}\n\nvoid\nEigenIntegrator::setLinks(AnalysisModel &theModel, EigenSOE &theSysOE)\n{\n    theAnalysisModel = &theModel;\n    theSOE = &theSysOE;\n}\n\nint \nEigenIntegrator::formEleTangent(FE_Element *theEle)\n{\n  if (flagK == 0)\n      return this->formEleTangK(theEle);\n  else\n      return this->formEleTangM(theEle);\n}\n\nint \nEigenIntegrator::formNodTangent(DOF_Group *theDof)\n{\n  return this->formNodTangM(theDof);\n}\n\nint \nEigenIntegrator::formEleResidual(FE_Element *theEle)\n{\n    return 0;\n}\n\nint \nEigenIntegrator::formNodUnbalance(DOF_Group *theDof)\n{\n    return 0;\n}\n\nint \nEigenIntegrator::newStep()\n{\n    return 0;\n}\n\nint \nEigenIntegrator::getLastResponse(Vector &result, const ID &id)\n{\n    return 0;\n}\n\nint\nEigenIntegrator::formK()\n{\n    if (theAnalysisModel == 0 || theSOE == 0) {\n\topserr << \"WARNING EigenIntegrator::formK -\";\n\topserr << \" no AnalysisModel or EigenSOE has been set\\n\";\n\treturn -1;\n    }\n    \n    // the loops to form and add the tangents are broken into two for \n    // efficiency when performing parallel computations\n\n    // loop through the FE_Elements getting them to form the tangent\n    // FE_EleIter &theEles1 = theAnalysisModel->getFEs();\n    FE_Element *elePtr;\n\n    flagK = 0;\n\n    theSOE->zeroA();\n\n    //while((elePtr = theEles1()) != 0) \n    //  elePtr->formTangent(this);\n   \n   // loop through the FE_Elements getting them to add the tangent    \n    int result = 0;\n    FE_EleIter &theEles2 = theAnalysisModel->getFEs();    \n    while((elePtr = theEles2()) != 0) {\n      \n        if (theSOE->addA(elePtr->getTangent(this), elePtr->getID()) < 0) {\n\t    opserr << \"WARNING EigenIntegrator::formK -\";\n\t    opserr << \" failed in addA for ID \" << elePtr->getID();\t    \n\t    result = -2;\n\t}\n    }\n\n    return result;    \n}\n\n\nint\nEigenIntegrator::formM()\n{\n    if (theAnalysisModel == 0 || theSOE == 0) {\n\topserr << \"WARNING EigenIntegrator::formK -\";\n\topserr << \" no AnalysisModel or EigenSOE has been set\\n\";\n\treturn -1;\n    }\n    \n    // the loops to form and add the tangents are broken into two for \n    // efficiency when performing parallel computations\n\n    // loop through the FE_Elements getting them to form the tangent\n    // FE_EleIter &theEles1 = theAnalysisModel->getFEs();\n    FE_Element *elePtr;\n\n    flagK = 1;\n    theSOE->zeroM();\n\n    // while((elePtr = theEles1()) != 0) \n    //     elePtr->formTangent(this);\n   \n   // loop through the FE_Elements getting them to add the tangent    \n    int result = 0;\n    FE_EleIter &theEles2 = theAnalysisModel->getFEs();    \n    while((elePtr = theEles2()) != 0) {     \n\tif (theSOE->addM(elePtr->getTangent(this), elePtr->getID()) < 0) {\n\t    opserr << \"WARNING EigenIntegrator::formK -\";\n\t    opserr << \" failed in addA for ID \" << elePtr->getID();\t    \n\t    result = -2;\n\t}\n    }\n\n    DOF_Group *dofPtr;\n    DOF_GrpIter &theDofs = theAnalysisModel->getDOFs();    \n    while((dofPtr = theDofs()) != 0) {\n\t//   \tdofPtr->formTangent(this);\n\tif (theSOE->addM(dofPtr->getTangent(this),dofPtr->getID()) < 0) {\n\t    opserr << \"WARNING EigenIntegrator::formM -\";\n\t    opserr << \" failed in addM for ID \" << dofPtr->getID();\t    \n\t    result = -3;\n\t}\n    }\n\n    return result;    \n}\n\nint \nEigenIntegrator::formEleTangK(FE_Element *theEle)\n{\n  theEle->zeroTangent();\n  theEle->addKtToTang(1.0);\n  return 0;\n}\n\nint \nEigenIntegrator::formEleTangM(FE_Element *theEle)\n{\n  theEle->zeroTangent();\n  theEle->addMtoTang(1.0);\n  return 0;\n}\n\nint \nEigenIntegrator::formNodTangM(DOF_Group *theDof)\n{\n  theDof->zeroTangent();\n  theDof->addMtoTang(1.0);\n  return 0;\n}\n\nint \nEigenIntegrator::update(const Vector &deltaU)\n{\n    return 0;\n}\n\nEigenSOE *\nEigenIntegrator::getEigenSOEPtr() const\n{\n    return theSOE;\n}\n\nAnalysisModel *\nEigenIntegrator::getAnalysisModelPtr() const\n{\n    return theAnalysisModel;\n}\n\nint \nEigenIntegrator::sendSelf(int commitTag, Channel &theChannel)\n{\n    return 0;\n}\n\nint \nEigenIntegrator::recvSelf(int commitTag, Channel &theChannel,\n\t\t\t  FEM_ObjectBroker &theBroker)\n{\n    return 0;\n}\n\nvoid \nEigenIntegrator::Print(OPS_Stream &s, int flag)\n{\n    s << \"\\t EigenIntegrator: \\n\";\n}\n\n\n", "meta": {"hexsha": "6c802eded5964db59f56b5be4987d3904c784c26", "size": 6467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OpenSees/SRC/analysis/integrator/EigenIntegrator.cpp", "max_stars_repo_name": "kuanshi/ductile-fracture", "max_stars_repo_head_hexsha": "ccb350564df54f5c5ec3a079100effe261b46650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T14:12:03.000Z", "max_issues_repo_path": "SRC/analysis/integrator/EigenIntegrator.cpp", "max_issues_repo_name": "steva44/OpenSees", "max_issues_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_issues_repo_licenses": ["TCL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRC/analysis/integrator/EigenIntegrator.cpp", "max_forks_repo_name": "steva44/OpenSees", "max_forks_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-21T03:11:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-19T07:29:37.000Z", "avg_line_length": 25.6626984127, "max_line_length": 83, "alphanum_fraction": 0.5814133292, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.044018649235890495, "lm_q1q2_score": 0.01694331267467267}}
{"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_UPDATE_INCLUDE\n#define MTL_UPDATE_INCLUDE\n\n#include <boost/numeric/mtl/operation/assign_mode.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace operations {\n\ntemplate <typename Element>\nstruct update_store\n{\n    template <typename Value>\n    Element& operator() (Element& x, Value const& y)\n    {\n    vampir_trace<13> tracer;\n\treturn x= Element(y);\n    }\n\n    // How to fill empty entries; typically directly with /p y\n    template <typename Value>\n    Element init(Value const& y)\n    {\n\treturn y;\n    }\n};\n\ntemplate <typename Element>\nstruct update_plus\n{\n    template <typename Value>\n    Element& operator() (Element& x, Value const& y)\n    {\n    vampir_trace<14> tracer;\n\treturn x+= Element(y);\n    }\n\n    // How to fill empty entries; typically directly with /p y\n    template <typename Value>\n    Element init(Value const& y)\n    {\n\treturn y;\n    }\n};\n\ntemplate <typename Element>\nstruct update_minus\n{\n    template <typename Value>\n    Element& operator() (Element& x, Value const& y)\n    {\n    vampir_trace<15> tracer;\n\treturn x-= Element(y);\n    }\n\n    // How to fill empty entries. Here the inverse of /p y is needed!!!\n    template <typename Value>\n    Element init(Value const& y)\n    {\n\treturn -y;\n    }\n};\n\ntemplate <typename Element>\nstruct update_times\n{\n    template <typename Value>\n    Element& operator() (Element& x, Value const& y)\n    {\n    vampir_trace<16> tracer;\n\treturn x*= y;\n    }\n\n    // How to fill empty entries; typically directly with /p y\n    template <typename Value>\n    Element init(Value const& y)\n    {\n\treturn y;\n    }\n};\n\ntemplate <typename Element, typename MonoidOp>\nstruct update_adapter\n{\n    template <typename Value>\n    Element& operator() (Element& x, Value const& y)\n    {\n    vampir_trace<17> tracer;\n\treturn x= MonoidOp()(x, y);\n    }\n\n    // How to fill empty entries\n    template <typename Value>\n    Element init(Value const& y)\n    {\n\treturn y;\n    }\n};\n\n\ntemplate <typename Inserter, typename SizeType = std::size_t>\nstruct update_proxy\n{\n    typedef update_proxy          self;\n    typedef typename Inserter::value_type  value_type;\n\n    explicit update_proxy(Inserter& ins, SizeType row, SizeType col) \n      : ins(ins), row(row), col(col) {}\n    \n    template <typename Value>\n    self& operator<< (Value const& val)\n    {\n\tvampir_trace<20> tracer;\n\treturn lshift(val, typename ashape::ashape<Value>::type());\n    }\n\n    template <typename Value>\n    self& operator= (Value const& val)\n    {\n\tvampir_trace<21> tracer;\n\tins.template modify<update_store<value_type> > (row, col, val);\n\treturn *this;\n    }\n\n    template <typename Value>\n    self& operator+= (Value const& val)\n    {\n\tvampir_trace<22> tracer;\n\tins.template modify<update_plus<value_type> > (row, col, val);\n\treturn *this;\n    }  \n\n  private:\n\n    typedef typename Inserter::matrix_type                               matrix_type;\n    typedef typename mtl::ashape::ashape<matrix_type>::type              matrix_shape;\n    typedef typename mtl::ashape::ashape<typename matrix_type::value_type>::type value_shape;\n\n\n    // Update scalar value as before\n    template <typename Value>\n    self& lshift (Value const& val, value_shape)\n    {\n\tins.update (row, col, val);\n\treturn *this;\n    }\t\n\n    // Update an entire matrix considered as block\n    template <typename MatrixSrc>\n    self& lshift (const MatrixSrc& src, matrix_shape)\n    {\n\tnamespace traits = mtl::traits;\n\ttypename traits::row<MatrixSrc>::type             row(src); \n\ttypename traits::col<MatrixSrc>::type             col(src); \n\ttypename traits::const_value<MatrixSrc>::type     value(src); \n\n\ttypedef typename traits::range_generator<tag::major, MatrixSrc>::type  cursor_type;\n\ttypedef typename traits::range_generator<tag::nz, cursor_type>::type   icursor_type;\n\t\n\tfor (cursor_type cursor = begin<tag::major>(src), cend = end<tag::major>(src); cursor != cend; ++cursor) \t    \n\t    for (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor)\n\t\tins.update(row(*icursor) + this->row, col(*icursor) + this->col, value(*icursor));\n\treturn *this;\n    }\n\n    Inserter&  ins;\n    SizeType   row, col;\n};\n\n/// Compute updater that corresponds to assign_mode\ntemplate <typename Assign, typename Value>\nstruct update_assign_mode {};\n\ntemplate <typename Value>\nstruct update_assign_mode<assign::assign_sum, Value>\n{\n    typedef update_plus<Value> type;\n};\n\ntemplate <typename Value>\nstruct update_assign_mode<assign::plus_sum, Value>\n{\n    typedef update_plus<Value> type;\n};\n\ntemplate <typename Value>\nstruct update_assign_mode<assign::minus_sum, Value>\n{\n    typedef update_minus<Value> type;\n};\n\n} // namespace operations\n\nusing operations::update_store;\nusing operations::update_plus;\nusing operations::update_minus;\nusing operations::update_times;\n\n} // namespace mtl\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#if 0\n// inconsistent with linear_algebra/identity.hpp\n\nnamespace math {\n\n// temporary hack, must go to a proper place\ntemplate <typename Element, typename MonoidOp>\nstruct identity {};\n\n#if 0\ntemplate <typename Element, typename MonoidOp>\nstruct identity< Element, mtl::operations::update_adapter< Element, MonoidOp > >\n    : struct identity< Element, MonoidOp >\n{};\n#endif\n\n\ntemplate < class T >\nstruct identity< T, mtl::operations::update_store<T> > \n{ \n    static const T value = 0 ; \n    T operator()() const { return value ; }\n} ;\n\ntemplate < class T >\nconst T identity< T, mtl::operations::update_store< T > >::value ;\n\n\n\ntemplate < class T >\nstruct identity< T, mtl::operations::update_plus<T> > \n{ \n    static const T value = 0 ; \n    T operator()() const { return value ; }\n} ;\n\ntemplate < class T >\nconst T identity< T, mtl::operations::update_plus< T > >::value ;\n\n\n\ntemplate < class T >\nstruct identity< T, mtl::operations::update_mult<T> > \n{ \n    static const T value = 1 ; \n    T operator()() const { return value ; }\n} ;\n\ntemplate < class T >\nconst T identity< T, mtl::operations::update_mult< T > >::value ;\n\n}\n#endif\n\n#endif // MTL_UPDATE_INCLUDE\n", "meta": {"hexsha": "1b95dbe7dc7a60bb8497784de37cf64aa322379e", "size": 6621, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/update.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/operation/update.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/operation/update.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": 22.8310344828, "max_line_length": 115, "alphanum_fraction": 0.6755777073, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.055005289455291144, "lm_q1q2_score": 0.016906316684078097}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Class:       ParamStudy\n//- Description: Implementation code for the ParamStudy class\n//- Owner:       Mike Eldred\n\n#include \"dakota_system_defs.hpp\"\n#include \"dakota_tabular_io.hpp\"\n#include \"ParamStudy.hpp\"\n#include \"ProblemDescDB.hpp\"\n#include \"ParallelLibrary.hpp\"\n#include \"PolynomialApproximation.hpp\"\n#include <boost/lexical_cast.hpp>\n\nstatic const char rcsId[]=\"@(#) $Id: ParamStudy.cpp 7024 2010-10-16 01:24:42Z mseldre $\";\n\n//#define DEBUG\n\n\nnamespace Dakota {\n\nParamStudy::ParamStudy(ProblemDescDB& problem_db, Model& model):\n  PStudyDACE(problem_db, model)\n{\n  // use allVariables instead of default allSamples\n  compactMode = false;\n\n  // Extract specification from ProblemDescDB, perform sanity checking, and\n  // compute/estimate maxEvalConcurrency.\n  bool err_flag = false;\n  switch (methodName) {\n  case LIST_PARAMETER_STUDY: {\n    const RealVector& pt_list\n      = probDescDB.get_rv(\"method.parameter_study.list_of_points\");\n    if (pt_list.empty()) {\n      const String& pt_fname\n\t= probDescDB.get_string(\"method.pstudy.import_file\");\n      unsigned short tabular_format\n\t= probDescDB.get_ushort(\"method.pstudy.import_format\");\n      bool active_only\n\t= probDescDB.get_bool(\"method.pstudy.import_active_only\");\n      if (load_distribute_points(pt_fname, tabular_format, active_only))\n\terr_flag = true;\n    }\n    else if (distribute_list_of_points(pt_list))\n      err_flag = true;\n    break;\n  }\n  case VECTOR_PARAMETER_STUDY: {\n    const RealVector& step_vector\n      = probDescDB.get_rv(\"method.parameter_study.step_vector\");\n    if (step_vector.empty()) { // final_point & num_steps spec.\n      // check length and distribute\n      if (check_final_point(\n\t  probDescDB.get_rv(\"method.parameter_study.final_point\")))\n\terr_flag = true;\n      // check value\n      if (check_num_steps(\n\t  probDescDB.get_int(\"method.parameter_study.num_steps\")))\n\terr_flag = true;\n      // precompute steps (using construct-time initialPoint) and perform error\n      // checks only if in check mode; else avoid additional overhead and rely\n      // on run-time checks for run-time initialPoint.\n      if (numSteps && parallelLib.command_line_check()) {\n\tinitialCVPoint  = iteratedModel.continuous_variables();      // view\n\tinitialDIVPoint = iteratedModel.discrete_int_variables();    // view\n\tinitialDSVPoint.resize(boost::extents[numDiscreteStringVars]);\n\tinitialDSVPoint = iteratedModel.discrete_string_variables(); // copy\n\tinitialDRVPoint = iteratedModel.discrete_real_variables();   // view\n\tfinal_point_to_step_vector(); // covers check_ranges_sets(numSteps)\n      }\n    }\n    else { // step_vector & num_steps spec.\n      // check length and distribute\n      if (check_step_vector(step_vector))\n\terr_flag = true;\n       // check value\n     if (check_num_steps(\n\t  probDescDB.get_int(\"method.parameter_study.num_steps\")))\n\terr_flag = true;\n      // discrete initial pts needed for check_sets(); reassigned in pre-run\n      initialDIVPoint = iteratedModel.discrete_int_variables();    // view\n      initialDSVPoint.resize(boost::extents[numDiscreteStringVars]);\n      initialDSVPoint = iteratedModel.discrete_string_variables(); // copy\n      initialDRVPoint = iteratedModel.discrete_real_variables();   // view\n      if (check_ranges_sets(numSteps))\n\terr_flag = true;\n    }\n    break;\n  }\n  case CENTERED_PARAMETER_STUDY:\n    if (check_step_vector(\n\tprobDescDB.get_rv(\"method.parameter_study.step_vector\")))\n      err_flag = true;\n    if (check_steps_per_variable(\n\tprobDescDB.get_iv(\"method.parameter_study.steps_per_variable\")))\n      err_flag = true;\n    initialDIVPoint = iteratedModel.discrete_int_variables();    // view\n    initialDSVPoint.resize(boost::extents[numDiscreteStringVars]);\n    initialDSVPoint = iteratedModel.discrete_string_variables(); // copy\n    initialDRVPoint = iteratedModel.discrete_real_variables();   // view\n    if (check_ranges_sets(contStepsPerVariable, discIntStepsPerVariable,\n\t\t\t  discStringStepsPerVariable, discRealStepsPerVariable))\n      err_flag = true;\n    break;\n  case MULTIDIM_PARAMETER_STUDY:\n    if (check_variable_partitions(probDescDB.get_usa(\"method.partitions\")))\n      err_flag = true;\n    if (check_finite_bounds())\n      err_flag = true;\n    // precompute steps (using construct-time bounds) and perform error checks\n    // only if in check mode; else avoid additional overhead and rely on\n    // run-time checks for run-time bounds.\n    if (parallelLib.command_line_check())\n      distribute_partitions();\n    break;\n  default:\n    Cerr << \"\\nError: bad methodName (\" << method_enum_to_string(methodName)\n\t << \") in ParamStudy constructor.\" << std::endl;\n    err_flag = true;\n  }\n  if (err_flag)\n    abort_handler(METHOD_ERROR);\n\n  maxEvalConcurrency *= numEvals;\n}\n\nbool ParamStudy::resize()\n{\n  bool parent_reinit_comms = PStudyDACE::resize();\n\n  // TODO:  To get resize() working, move contents of ParamStudy::pre_run()\n  //        to ParamStudy::initialize_run() before Analyzer::initialize_run()\n  //        is called. This populates allVariables. If the model is a\n  //        RecastModel, call inverse_transform_variables() on each entry in\n  //        allVariables to resize and transform to the RecastModel. This call\n  //        to inverse_transform_variables() must occur after\n  //        Analyzer::initialize_run(). Also in ActiveSubspaceModel,\n  //        inverse_transform_variables() is not yet implemented.\n\n  Cerr << \"\\nError: Resizing is not yet supported in method \"\n       << method_enum_to_string(methodName) << \".\" << std::endl;\n  abort_handler(METHOD_ERROR);\n\n  return parent_reinit_comms;\n}\n\n\nvoid ParamStudy::pre_run()\n{\n  Analyzer::pre_run();\n\n  // Capture any changes in initialCVPoint resulting from the strategy layer's\n  // passing of best variable info between iterators.  If no such variable \n  // passing has occurred, then this reassignment is merely repetitive of the \n  // one in the ParamStudy constructor.  If there is a final_point \n  // specification, then contStepVector and numSteps must be (re)computed.\n  const Variables& vars = iteratedModel.current_variables();\n  const SharedVariablesData& svd = vars.shared_data();\n  if (methodName == VECTOR_PARAMETER_STUDY ||\n      methodName == CENTERED_PARAMETER_STUDY) {\n    copy_data(vars.continuous_variables(),      initialCVPoint);  // copy\n    copy_data(vars.discrete_int_variables(),    initialDIVPoint); // copy\n    initialDSVPoint.resize(boost::extents[numDiscreteStringVars]);\n    initialDSVPoint = vars.discrete_string_variables();           // copy\n    copy_data(vars.discrete_real_variables(),   initialDRVPoint); // copy\n  }\n\n  size_t av_size = allVariables.size();\n  if (av_size != numEvals) {\n    allVariables.resize(numEvals);\n    for (size_t i=av_size; i<numEvals; ++i)\n      allVariables[i] = Variables(svd); // use minimal data ctor\n    if ( outputLevel > SILENT_OUTPUT &&\n\t ( methodName == VECTOR_PARAMETER_STUDY ||\n\t   methodName == CENTERED_PARAMETER_STUDY ) )\n      allHeaders.resize(numEvals);\n  }\n\n  switch (methodName) {\n  case LIST_PARAMETER_STUDY:\n    if (outputLevel > SILENT_OUTPUT)\n      Cout << \"\\nList parameter study for \" << numEvals << \" samples\\n\\n\";\n    sample();\n    break;\n  case VECTOR_PARAMETER_STUDY:\n    if (!contStepVector.empty()       || !discIntStepVector.empty() ||\n\t!discStringStepVector.empty() || !discRealStepVector.empty()) {\n      // step_vector & num_steps\n      if (outputLevel > SILENT_OUTPUT) {\n\tCout << \"\\nVector parameter study for \" << numSteps\n\t     << \" steps starting from\\n\";\n\twrite_ordered(Cout, svd.active_components_totals(), initialCVPoint,\n\t\t      initialDIVPoint, initialDSVPoint, initialDRVPoint);\n\tCout << \"with a step vector of\\n\";\n\twrite_ordered(Cout, svd.active_components_totals(), contStepVector,\n\t\t      discIntStepVector, discStringStepVector,\n\t\t      discRealStepVector);\n\tCout << '\\n';\n      }\n    }\n    else { // final_point & num_steps\n      if (outputLevel > SILENT_OUTPUT) {\n\tCout << \"\\nVector parameter study from\\n\";\n\twrite_ordered(Cout, svd.active_components_totals(), initialCVPoint,\n\t\t      initialDIVPoint, initialDSVPoint, initialDRVPoint);\n\tCout << \"to\\n\";\n\twrite_ordered(Cout, svd.active_components_totals(), finalCVPoint,\n\t\t      finalDIVPoint, finalDSVPoint, finalDRVPoint);\n\tCout << \"using \" << numSteps << \" steps\\n\\n\";\n      }\n      if (numSteps) // define step vectors from initial, final, & num steps\n\tfinal_point_to_step_vector();\n    }\n    vector_loop();\n    break;\n  case CENTERED_PARAMETER_STUDY:\n    if (outputLevel > SILENT_OUTPUT) {\n      Cout << \"\\nCentered parameter study with steps per variable\\n\";\n      write_ordered(Cout, svd.active_components_totals(), contStepsPerVariable,\n\t\t    discIntStepsPerVariable, discStringStepsPerVariable,\n\t\t    discRealStepsPerVariable);\n      Cout << \"and increments of\\n\";\n      write_ordered(Cout, svd.active_components_totals(), contStepVector,\n\t\t    discIntStepVector, discStringStepVector,\n\t\t    discRealStepVector);\n      Cout << \"with the following center point:\\n\";\n      write_ordered(Cout, svd.active_components_totals(), initialCVPoint,\n\t\t    initialDIVPoint, initialDSVPoint, initialDRVPoint);\n      Cout << '\\n';\n    }\n    centered_loop();\n    break;\n  case MULTIDIM_PARAMETER_STUDY:\n    if (outputLevel > SILENT_OUTPUT) {\n      Cout << \"\\nMultidimensional parameter study variable partitions of\\n\";\n      write_ordered(Cout, svd.active_components_totals(), contVarPartitions,\n\t\t    discIntVarPartitions, discStringVarPartitions,\n\t\t    discRealVarPartitions);\n    }\n    distribute_partitions();\n    multidim_loop();\n    break;\n  default:\n    Cerr << \"\\nError: bad methodName (\" << method_enum_to_string(methodName)\n\t << \") in ParamStudy::pre_run().\" << std::endl;\n    abort_handler(METHOD_ERROR);\n  }\n}\n\n\nvoid ParamStudy::core_run()\n{\n  // perform the evaluations; multidim exception\n  bool log_resp_flag = (methodName == MULTIDIM_PARAMETER_STUDY)\n    ? (!subIteratorFlag) : false;\n  bool log_best_flag = (numObjFns || numLSqTerms); // opt or NLS data set\n  evaluate_parameter_sets(iteratedModel, log_resp_flag, log_best_flag);\n}\n\n\nvoid ParamStudy::post_input()\n{\n  // call convenience function from Analyzer\n  read_variables_responses(numEvals, numContinuousVars + numDiscreteIntVars +\n\t\t\t   numDiscreteStringVars + numDiscreteRealVars);\n}\n\n\nvoid ParamStudy::post_run(std::ostream& s)\n{\n  bool log_resp_flag = (!subIteratorFlag);\n  if (methodName == MULTIDIM_PARAMETER_STUDY && log_resp_flag)\n    pStudyDACESensGlobal.compute_correlations(allVariables, allResponses, \n      iteratedModel.discrete_set_string_values()); // to map string variable\n                                                   // values back to indices\n\n  Analyzer::post_run(s);\n}\n\n\nvoid ParamStudy::sample()\n{\n  // populate allVariables\n  for (size_t i=0; i<numEvals; ++i) {\n    if (numContinuousVars)\n      allVariables[i].continuous_variables(listCVPoints[i]);\n    if (numDiscreteIntVars)\n      allVariables[i].discrete_int_variables(listDIVPoints[i]);\n    if (numDiscreteStringVars)\n      allVariables[i].discrete_string_variables(\n\tlistDSVPoints[boost::indices[i][idx_range(0, numDiscreteStringVars)]]);\n    if (numDiscreteRealVars)\n      allVariables[i].discrete_real_variables(listDRVPoints[i]);\n  }\n  // free up redundant memory\n  listCVPoints.clear();\n  listDIVPoints.clear();\n  listDSVPoints.resize(boost::extents[0][0]);\n  listDRVPoints.clear();\n}\n\n\nvoid ParamStudy::vector_loop()\n{\n  // Steps along a n-dimensional vector through numSteps additions of\n  // continuous/discrete step vectors.  The step is an absolute step defining\n  // magnitude & direction.  The number of fn. evaluations in the study is\n  // numSteps + 1 since the initial point is also evaluated.\n\n  const BitArray&      di_set_bits = iteratedModel.discrete_int_sets();\n  const IntSetArray&    dsi_values = iteratedModel.discrete_set_int_values();\n  const StringSetArray& dss_values = iteratedModel.discrete_set_string_values();\n  const RealSetArray&   dsr_values = iteratedModel.discrete_set_real_values();\n  size_t i, j, dsi_cntr;\n\n  for (i=0; i<=numSteps; ++i) {\n    Variables& vars = allVariables[i];\n\n    // active continuous\n    for (j=0; j<numContinuousVars; ++j)\n      c_step(j, i, vars);\n\n    // active discrete int: ranges and sets\n    for (j=0, dsi_cntr=0; j<numDiscreteIntVars; ++j)\n      if (di_set_bits[j]) dsi_step(j, i, dsi_values[dsi_cntr++], vars);\n      else                dri_step(j, i, vars);\n\n    // active discrete string: sets only\n    for (j=0; j<numDiscreteStringVars; ++j)\n      dss_step(j, i, dss_values[j], vars);\n\n    // active discrete real: sets only\n    for (j=0; j<numDiscreteRealVars; ++j)\n      dsr_step(j, i, dsr_values[j], vars);\n\n    // store each output header in allHeaders\n    if (outputLevel > SILENT_OUTPUT) {\n      String& h_string = allHeaders[i];\n      h_string.clear();\n      if (iteratedModel.asynch_flag())\n\th_string += \"\\n\\n\";\n      if (numSteps == 0) // Allow numSteps == 0 case\n\th_string += \">>>>> Initial_point only (no steps)\\n\";\n      h_string += \">>>>> Vector parameter study evaluation for \";\n      h_string += boost::lexical_cast<std::string>(i*100./numSteps);\n      h_string += \"% along vector\\n\";\n    }\n  }\n}\n\n\nvoid ParamStudy::centered_loop()\n{\n  size_t k, cntr = 0, dsi_cntr = 0;\n  String cv_str(\"cv\"), div_str(\"div\"), dsv_str(\"dsv\"), drv_str(\"drv\");\n\n  // Always evaluate center point, even if steps_per_variable = 0\n  if (outputLevel > SILENT_OUTPUT)\n    allHeaders[cntr] = (iteratedModel.asynch_flag()) ?\n      \"\\n\\n>>>>> Centered parameter study evaluation for center point\\n\" :\n      \">>>>> Centered parameter study evaluation for center point\\n\";\n  if (numContinuousVars)\n    allVariables[cntr].continuous_variables(initialCVPoint);\n  if (numDiscreteIntVars)\n    allVariables[cntr].discrete_int_variables(initialDIVPoint);\n  if (numDiscreteStringVars)\n    allVariables[cntr].discrete_string_variables(\n      initialDSVPoint[boost::indices[idx_range(0, numDiscreteStringVars)]]);\n  if (numDiscreteRealVars)\n    allVariables[cntr].discrete_real_variables(initialDRVPoint);\n  ++cntr;\n\n  // Evaluate +/- steps for each continuous variable\n  for (k=0; k<numContinuousVars; ++k) {\n    int i, num_steps_k = contStepsPerVariable[k];\n    for (i=-num_steps_k; i<=num_steps_k; ++i)\n      if (i) {\n\tVariables& vars = allVariables[cntr];\n\treset(vars); c_step(k, i, vars);\n\tif (outputLevel > SILENT_OUTPUT) centered_header(cv_str, k, i, cntr);\n\t++cntr;\n      }\n  }\n\n  // Evaluate +/- steps for each discrete int variable\n  const BitArray&   di_set_bits = iteratedModel.discrete_int_sets();\n  const IntSetArray& dsi_values = iteratedModel.discrete_set_int_values();\n  for (k=0; k<numDiscreteIntVars; ++k) {\n    int i, num_steps_k = discIntStepsPerVariable[k];\n    if (di_set_bits[k]) {\n      const IntSet& dsi_vals_k = dsi_values[dsi_cntr];\n      for (i=-num_steps_k; i<=num_steps_k; ++i)\n\tif (i) {\n\t  Variables& vars = allVariables[cntr];\n\t  reset(vars); dsi_step(k, i, dsi_vals_k, vars);\n\t  if (outputLevel > SILENT_OUTPUT) centered_header(div_str, k, i, cntr);\n\t  ++cntr;\n\t}\n      ++dsi_cntr;\n    }\n    else {\n      for (i=-num_steps_k; i<=num_steps_k; ++i)\n\tif (i) {\n\t  Variables& vars = allVariables[cntr];\n\t  reset(vars); dri_step(k, i, vars);\n\t  if (outputLevel > SILENT_OUTPUT) centered_header(div_str, k, i, cntr);\n\t  ++cntr;\n\t}\n    }\n  }\n\n  // Evaluate +/- steps for each discrete string variable\n  const StringSetArray& dss_values = iteratedModel.discrete_set_string_values();\n  for (k=0; k<numDiscreteStringVars; ++k) {\n    int i, num_steps_k = discStringStepsPerVariable[k];\n    const StringSet& dss_vals_k = dss_values[k];\n    for (i=-num_steps_k; i<=num_steps_k; ++i)\n      if (i) {\n\tVariables& vars = allVariables[cntr];\n\treset(vars); dss_step(k, i, dss_vals_k, vars);\n\tif (outputLevel > SILENT_OUTPUT) centered_header(dsv_str, k, i, cntr);\n\t++cntr;\n      }\n  }\n\n  // Evaluate +/- steps for each discrete real variable\n  const RealSetArray& dsr_values = iteratedModel.discrete_set_real_values();\n  for (k=0; k<numDiscreteRealVars; ++k) {\n    int i, num_steps_k = discRealStepsPerVariable[k];\n    const RealSet& dsr_vals_k = dsr_values[k];\n    for (i=-num_steps_k; i<=num_steps_k; ++i)\n      if (i) {\n\tVariables& vars = allVariables[cntr];\n\treset(vars); dsr_step(k, i, dsr_vals_k, vars);\n\tif (outputLevel > SILENT_OUTPUT) centered_header(drv_str, k, i, cntr);\n\t++cntr;\n      }\n  }\n}\n\n\nvoid ParamStudy::multidim_loop()\n{\n  // Perform a multidimensional parameter study based on the number of \n  // partitions specified for each variable.\n\n  const BitArray&      di_set_bits = iteratedModel.discrete_int_sets();\n  const IntSetArray&    dsi_values = iteratedModel.discrete_set_int_values();\n  const StringSetArray& dss_values = iteratedModel.discrete_set_string_values();\n  const RealSetArray&   dsr_values = iteratedModel.discrete_set_real_values();\n  size_t i, j, p_cntr, dsi_cntr,\n    num_c_di_vars    = numContinuousVars + numDiscreteIntVars,\n    num_c_di_ds_vars = num_c_di_vars + numDiscreteStringVars,\n    num_vars = num_c_di_ds_vars + numDiscreteRealVars;\n  UShortArray multidim_indices(num_vars, 0), partition_limits(num_vars);\n  copy_data_partial(contVarPartitions, partition_limits, 0);\n  copy_data_partial(discIntVarPartitions, partition_limits, numContinuousVars);\n  copy_data_partial(discStringVarPartitions, partition_limits, num_c_di_vars);\n  copy_data_partial(discRealVarPartitions, partition_limits, num_c_di_ds_vars);\n\n  for (i=0; i<numEvals; ++i) {\n    Variables& vars = allVariables[i];\n    p_cntr = 0;\n    // active continuous\n    for (j=0; j<numContinuousVars; ++j, ++p_cntr)\n      c_step(j, multidim_indices[p_cntr], vars);\n    // active discrete int: ranges and sets\n    for (j=0, dsi_cntr=0; j<numDiscreteIntVars; ++j, ++p_cntr)\n      if (di_set_bits[j])\n\tdsi_step(j, multidim_indices[p_cntr], dsi_values[dsi_cntr++], vars);\n      else\n\tdri_step(j, multidim_indices[p_cntr], vars);\n    // active discrete string: sets only\n    for (j=0; j<numDiscreteStringVars; ++j, ++p_cntr)\n      dss_step(j, multidim_indices[p_cntr], dss_values[j], vars);\n    // active discrete real: sets only\n    for (j=0; j<numDiscreteRealVars; ++j, ++p_cntr)\n      dsr_step(j, multidim_indices[p_cntr], dsr_values[j], vars);\n    // increment the multidimensional index set\n    Pecos::SharedPolyApproxData::increment_indices(multidim_indices,\n\t\t\t\t\t\t   partition_limits, true);\n  }\n}\n\n\n/** Load from file and distribute points; using this function to\n    manage construction of the temporary arrays.  Historically all\n    data was read as a real (mixture of values and indices), but now\n    points_file is valued-based (reals, integers, strings) so file\n    input matches tabular data output.  Return false on success. */\nbool ParamStudy::\nload_distribute_points(const String& points_filename, \n\t\t       unsigned short tabular_format,\n\t\t       bool active_only)\n{\n  bool err = false;\n\n  // don't know the size until the file is read, so the reader grows\n  // the containers as the read takes place\n\n  // the easiest way to read is with a variables object\n  // read all variables in spec order into a temporary Variables\n  Variables vars(iteratedModel.current_variables().copy());\n\n  // then map the active data from that variables object into the\n  // list*Points arrays and validate it\n \n  // TODO: validate the read values of inactive variables\n\n  // Could read into these dynamically or into a temporary and then allocate\n  numEvals = TabularIO::\n    read_data_tabular(points_filename, \"List Parameter Study\", \n\t\t      listCVPoints, listDIVPoints, listDSVPoints, listDRVPoints,\n\t\t      tabular_format, active_only, \n\t\t      iteratedModel.current_variables().copy());\n  if (numEvals == 0) err = true;\n\n\n  // validation of data: consider moving reader into this class and\n  // validating while reading...\n  for (size_t i=0; i<numEvals; ++i) {\n\n    // validate continuous values read\n    const RealVector& c_lb = iteratedModel.continuous_lower_bounds();\n    const RealVector& c_ub = iteratedModel.continuous_upper_bounds();\n\n    for (size_t j=0; j<numContinuousVars; ++j)\n      if (listCVPoints[i][j] < c_lb[j] || listCVPoints[i][j] > c_ub[j]) {\n\tCerr << \"\\nError: list value \" << listCVPoints[i][j] \n\t     << \" outside bounds for continuous variable \" << j+1 << '.' \n\t     << std::endl;\n\terr = true;\n      }\n\n    // validate discrete integers (sets and ranges) read\n    const BitArray& di_set_bits = iteratedModel.discrete_int_sets();\n    const IntSetArray& dsi_vals = iteratedModel.discrete_set_int_values();\n    const IntVector& di_lb = iteratedModel.discrete_int_lower_bounds();\n    const IntVector& di_ub = iteratedModel.discrete_int_upper_bounds();\n\n    for (size_t j=0, dsi_cntr=0; j<numDiscreteIntVars; ++j)\n      if (di_set_bits[j]) {\n\t// set values\n\tif (set_value_to_index(listDIVPoints[i][j], dsi_vals[dsi_cntr]) \n\t    == _NPOS) {\n\t  Cerr << \"\\nError: list value \" << listDIVPoints[i][j] \n\t       << \" not admissble for discrete int set \" << dsi_cntr+1 << '.'\n\t       << std::endl;\n\t  err = true;\n\t}\n\t++dsi_cntr;\n      }\n      else {\n\t// range values: validate bounds\n\tif (listDIVPoints[i][j] < di_lb[j] || listDIVPoints[i][j] > di_ub[j]) {\n\t  Cerr << \"\\nError: list value \" << listDIVPoints[i][j] \n\t       << \" outside bounds for discrete int range variable \" << j+1 \n\t       << '.' << std::endl;\n\t  err = true;\n\t}\n      }\n\n    // validate discrete string sets read\n    const StringSetArray& dss_vals = iteratedModel.discrete_set_string_values();\n    for (size_t j=0; j<numDiscreteStringVars; ++j)\n      if (set_value_to_index(listDSVPoints[i][j], dss_vals[j]) == _NPOS) {\n        Cerr << \"\\nError: list value \" << listDSVPoints[i][j] \n\t     << \" not admissible for discrete string set \" << j+1 << '.' \n\t     << std::endl;\n        err = true;\n      }\n\n    const RealSetArray& dsr_vals = iteratedModel.discrete_set_real_values();\n    for (size_t j=0; j<numDiscreteRealVars; ++j)\n      if (set_value_to_index(listDRVPoints[i][j], dsr_vals[j]) == _NPOS) {\n        Cerr << \"\\nError: list value \" << listDRVPoints[i][j] \n\t     << \" not admissible for discrete real set \" << j+1 << '.' \n\t     << std::endl;\n        err = true;\n      }\n\n  } // for each eval\n\n  return err;\n\n}\n\n\n/** Parse list of points into typed data containers; list_of_pts will\n    contain values for continuous and discrete integer range, but\n    indices for all discrete set types (int, string, real) */\nbool ParamStudy::distribute_list_of_points(const RealVector& list_of_pts)\n{\n  size_t i, j, dsi_cntr, start, len_lop = list_of_pts.length(),\n    num_vars = numContinuousVars     + numDiscreteIntVars\n             + numDiscreteStringVars + numDiscreteRealVars;\n  if (len_lop % num_vars) {\n    Cerr << \"\\nError: length of list_of_points (\"  << len_lop\n\t << \") must be evenly divisable among number of active variables (\"\n\t << num_vars << \").\" << std::endl;\n    return true;\n  }\n  numEvals = len_lop / num_vars;\n  if (numContinuousVars)   listCVPoints.resize(numEvals);\n  if (numDiscreteIntVars)  listDIVPoints.resize(numEvals);\n  if (numDiscreteStringVars)\n    listDSVPoints.resize(boost::extents[numEvals][numDiscreteStringVars]);\n  if (numDiscreteRealVars) listDRVPoints.resize(numEvals);\n\n  const BitArray&      di_set_bits = iteratedModel.discrete_int_sets();\n  const IntSetArray&    dsi_values = iteratedModel.discrete_set_int_values();\n  const StringSetArray& dss_values = iteratedModel.discrete_set_string_values();\n  const RealSetArray&   dsr_values = iteratedModel.discrete_set_real_values();\n\n  bool err = false;\n  RealVector empty_rv; IntVector empty_iv; StringMultiArray empty_sa;\n  for (i=0, start=0; i<numEvals; ++i) {\n    RealVector& list_cv_i  = (numContinuousVars)  ? listCVPoints[i]  : empty_rv;\n    IntVector&  list_div_i = (numDiscreteIntVars) ? listDIVPoints[i] : empty_iv;\n    StringMultiArrayView list_dsv_i = (numDiscreteStringVars) ?\n      listDSVPoints[boost::indices[i][idx_range(0, numDiscreteStringVars)]] :\n      empty_sa[boost::indices[idx_range(0, 0)]];\n    RealVector& list_drv_i = (numDiscreteRealVars) ?\n      listDRVPoints[i] : empty_rv;\n    IntVector div_combined, dsv_indices, drv_indices;\n\n    // take a view of each sample and partition it into {c,di,dr} components\n    RealVector all_sample(Teuchos::View, const_cast<Real*>(&list_of_pts[start]),\n\t\t\t  num_vars);\n    // if list_of_pts contains range and set values:\n    //distribute(all_sample, list_cv_i, list_div_i, list_dsv_i, list_drv_i);\n    // if list_of_pts contains range values and set indices:\n    distribute(all_sample, list_cv_i, div_combined, dsv_indices, drv_indices);\n    start += num_vars;\n\n    // Promote set indices to admissible set values\n    if (numDiscreteIntVars) list_div_i.sizeUninitialized(numDiscreteIntVars);\n    for (j=0, dsi_cntr=0; j<numDiscreteIntVars; ++j) {\n      if (di_set_bits[j]) {\n\t// if set values:\n\t//if (set_value_to_index(list_div_i[j], dsi_values[dsi_cntr]) == _NPOS){\n\t//  Cerr << \"\\nError: list value \" << list_div_i[j]<< \" not admissible \"\n\t//       << \"for discrete int set \" << dsi_cntr+1 << '.' << std::endl;\n\t//  err = true;\n\t//}\n\t// if set indices:\n\tlist_div_i[j]\n\t  = set_index_to_value(div_combined[j], dsi_values[dsi_cntr]);\n\t++dsi_cntr;\n      }\n      else // range values\n\tlist_div_i[j] = div_combined[j];\n    }\n\n    for (j=0; j<numDiscreteStringVars; ++j)\n      // if set values:\n      //if (set_value_to_index(list_dsv_i[j], dss_values[j]) == _NPOS) {\n      //  Cerr << \"\\nError: list value \" << list_dsv_i[j] << \" not admissible \"\n      //       << \"for discrete string set \" << j+1 << '.' << std::endl;\n      //  err = true;\n      //}\n      // if set indices:\n      list_dsv_i[j] = set_index_to_value(dsv_indices[j], dss_values[j]);\n\n    if (numDiscreteRealVars) list_drv_i.sizeUninitialized(numDiscreteRealVars);\n    for (j=0; j<numDiscreteRealVars; ++j)\n      // if set values:\n      //if (set_value_to_index(list_drv_i[j], dsr_values[j]) == _NPOS) {\n      //  Cerr << \"\\nError: list value \" << list_drv_i[j] << \" not admissible \"\n      //       << \"for discrete real set \" << j+1 << '.' << std::endl;\n      //  err = true;\n      //}\n      // if set indices:\n      list_drv_i[j] = set_index_to_value(drv_indices[j], dsr_values[j]);\n  }\n\n#ifdef DEBUG\n  Cout << \"distribute_list_of_points():\\n\";\n  for (i=0; i<numEvals; ++i) {\n    if (numContinuousVars) {\n      Cout << \"Eval \" << i << \" continuous:\\n\";\n      write_data(Cout, listCVPoints[i]);\n    }\n    if (numDiscreteIntVars) {\n      Cout << \"Eval \" << i << \" discrete int:\\n\";\n      write_data(Cout, listDIVPoints[i]);\n    }\n    if (numDiscreteStringVars) {\n      Cout << \"Eval \" << i << \" discrete string:\\n\";\n      write_data(Cout,\n\tlistDSVPoints[boost::indices[i][idx_range(0, numDiscreteStringVars)]]);\n    }\n    if (numDiscreteRealVars) {\n      Cout << \"Eval \" << i << \" discrete real:\\n\";\n      write_data(Cout, listDRVPoints[i]);\n    }\n  }\n#endif // DEBUG\n\n  return err;\n}\n\n\nvoid ParamStudy::distribute_partitions()\n{\n  contStepVector.sizeUninitialized(numContinuousVars);\n  discIntStepVector.sizeUninitialized(numDiscreteIntVars);\n  discStringStepVector.sizeUninitialized(numDiscreteStringVars);\n  discRealStepVector.sizeUninitialized(numDiscreteRealVars);\n\n  initialCVPoint.sizeUninitialized(numContinuousVars);\n  initialDIVPoint.sizeUninitialized(numDiscreteIntVars);\n  initialDSVPoint.resize(boost::extents[numDiscreteStringVars]);\n  initialDRVPoint.sizeUninitialized(numDiscreteRealVars);\n\n  const RealVector&          c_vars = iteratedModel.continuous_variables();\n  const IntVector&          di_vars = iteratedModel.discrete_int_variables();\n  StringMultiArrayConstView ds_vars = iteratedModel.discrete_string_variables();\n  const RealVector&         dr_vars = iteratedModel.discrete_real_variables();\n\n  const RealVector&  c_l_bnds = iteratedModel.continuous_lower_bounds();\n  const RealVector&  c_u_bnds = iteratedModel.continuous_upper_bounds();\n  const IntVector&  di_l_bnds = iteratedModel.discrete_int_lower_bounds();\n  const IntVector&  di_u_bnds = iteratedModel.discrete_int_upper_bounds();\n  const RealVector& dr_l_bnds = iteratedModel.discrete_real_lower_bounds();\n  const RealVector& dr_u_bnds = iteratedModel.discrete_real_upper_bounds();\n\n  const BitArray&      di_set_bits = iteratedModel.discrete_int_sets();\n  const IntSetArray&    dsi_values = iteratedModel.discrete_set_int_values();\n  const StringSetArray& dss_values = iteratedModel.discrete_set_string_values();\n  const RealSetArray&   dsr_values = iteratedModel.discrete_set_real_values();\n\n  size_t i, dsi_cntr; unsigned short part;\n  for (i=0; i<numContinuousVars; ++i) {\n    part = contVarPartitions[i];\n    if (part) {\n      initialCVPoint[i] = c_l_bnds[i];\n      contStepVector[i] = (c_u_bnds[i] - c_l_bnds[i]) / part;\n    }\n    else\n      { initialCVPoint[i] = c_vars[i]; contStepVector[i] = 0.; }\n  }\n  for (i=0, dsi_cntr=0; i<numDiscreteIntVars; ++i) {\n    part = discIntVarPartitions[i];\n    if (part) {\n      initialDIVPoint[i] = di_l_bnds[i];\n      int range = (di_set_bits[i]) ? dsi_values[dsi_cntr++].size() - 1 :\n\t                             di_u_bnds[i] - di_l_bnds[i];\n      discIntStepVector[i] = integer_step(range, part);\n    }\n    else\n      { initialDIVPoint[i] = di_vars[i]; discIntStepVector[i] = 0; }\n  }\n  for (i=0; i<numDiscreteStringVars; ++i) {\n    part = discStringVarPartitions[i];\n    if (part) {\n      const StringSet& dss_vals_i = dss_values[i];\n      initialDSVPoint[i]      = *dss_vals_i.begin();\n      discStringStepVector[i] = integer_step(dss_vals_i.size() - 1, part);\n    }\n    else\n      { initialDRVPoint[i] = dr_vars[i]; discRealStepVector[i] = 0; }\n  }\n  for (i=0; i<numDiscreteRealVars; ++i) {\n    part = discRealVarPartitions[i];\n    if (part) {\n      initialDRVPoint[i]    = dr_l_bnds[i];\n      discRealStepVector[i] = integer_step(dsr_values[i].size() - 1, part);\n    }\n    else\n      { initialDRVPoint[i] = dr_vars[i]; discRealStepVector[i] = 0; }\n  }\n\n#ifdef DEBUG\n  Cout << \"distribute_partitions():\\n\";\n  if (numContinuousVars) {\n    Cout << \"c_vars:\\n\";             write_data(Cout, c_vars);\n    Cout << \"c_l_bnds:\\n\";           write_data(Cout, c_l_bnds);\n    Cout << \"c_u_bnds:\\n\";           write_data(Cout, c_u_bnds);\n    Cout << \"initialCVPoint:\\n\";     write_data(Cout, initialCVPoint);\n    Cout << \"contStepVector:\\n\";     write_data(Cout, contStepVector);\n  }\n  if (numDiscreteIntVars) {\n    Cout << \"di_vars:\\n\";            write_data(Cout, di_vars);\n    Cout << \"di_l_bnds:\\n\";          write_data(Cout, di_l_bnds);\n    Cout << \"di_u_bnds:\\n\";          write_data(Cout, di_u_bnds);\n    Cout << \"initialDIVPoint:\\n\";    write_data(Cout, initialDIVPoint);\n    Cout << \"discIntStepVector:\\n\";  write_data(Cout, discIntStepVector);\n  }\n  if (numDiscreteStringVars) {\n    Cout << \"ds_vars:\\n\";              write_data(Cout, ds_vars);\n    Cout << \"initialDSVPoint:\\n\";      write_data(Cout, initialDSVPoint);\n    Cout << \"discStringStepVector:\\n\"; write_data(Cout, discStringStepVector);\n  }\n  if (numDiscreteRealVars) {\n    Cout << \"dr_vars:\\n\";            write_data(Cout, dr_vars);\n    Cout << \"dr_l_bnds:\\n\";          write_data(Cout, dr_l_bnds);\n    Cout << \"dr_u_bnds:\\n\";          write_data(Cout, dr_u_bnds);\n    Cout << \"initialDRVPoint:\\n\";    write_data(Cout, initialDRVPoint);\n    Cout << \"discRealStepVector:\\n\"; write_data(Cout, discRealStepVector);\n  }\n#endif // DEBUG\n}\n\n\nvoid ParamStudy::final_point_to_step_vector()\n{\n  //RealVector cv_final, drv_final; IntVector div_final;\n  //StringMultiArray dsv_final;\n  //distribute(finalPoint, cv_final, div_final, dsv_final, drv_final);\n\n  const BitArray&      di_set_bits = iteratedModel.discrete_int_sets();\n  const IntSetArray&    dsi_values = iteratedModel.discrete_set_int_values();\n  const StringSetArray& dss_values = iteratedModel.discrete_set_string_values();\n  const RealSetArray&   dsr_values = iteratedModel.discrete_set_real_values();\n  size_t j, dsi_cntr;\n\n  // active continuous\n  contStepVector.sizeUninitialized(numContinuousVars);\n  for (j=0; j<numContinuousVars; ++j)\n    contStepVector[j] = (finalCVPoint[j] - initialCVPoint[j]) / numSteps;\n\n  // active discrete int: ranges and sets\n  discIntStepVector.sizeUninitialized(numDiscreteIntVars);\n  for (j=0, dsi_cntr=0; j<numDiscreteIntVars; ++j)\n    if (di_set_bits[j]) {\n      discIntStepVector[j] = index_step(\n        set_value_to_index(initialDIVPoint[j], dsi_values[dsi_cntr]),\n\t// for final point defined as index:\n        finalDIVPoint[j], numSteps);\n\t// for final point defined as admissible value:\n        //set_value_to_index(div_final[j], dsi_values[dsi_cntr]), numSteps);\n      ++dsi_cntr;\n    }\n    else\n      discIntStepVector[j]\n\t= integer_step(finalDIVPoint[j] - initialDIVPoint[j], numSteps);\n\n  // active discrete string: sets only\n  discStringStepVector.sizeUninitialized(numDiscreteStringVars);\n  for (j=0; j<numDiscreteStringVars; ++j)\n    discStringStepVector[j] = index_step(\n      set_value_to_index(initialDSVPoint[j], dss_values[j]),\n      // for final point defined as index:\n      finalDSVPoint[j], numSteps);\n      // for final point defined as admissible value:\n      //set_value_to_index(dsv_final[j], dss_values[j]), numSteps);\n\n  // active discrete real: sets only\n  discRealStepVector.sizeUninitialized(numDiscreteRealVars);\n  for (j=0; j<numDiscreteRealVars; ++j)\n    discRealStepVector[j] = index_step(\n      set_value_to_index(initialDRVPoint[j], dsr_values[j]),\n      // for final point defined as index:\n      finalDRVPoint[j], numSteps);\n      // for final point defined as admissible value:\n      //set_value_to_index(drv_final[j], dsr_values[j]), numSteps);\n\n#ifdef DEBUG\n  Cout << \"final_point_to_step_vector():\\n\";\n  if (numContinuousVars) {\n    Cout << \"continuous step vector:\\n\";\n    write_data(Cout, contStepVector);\n  }\n  if (numDiscreteIntVars) {\n    Cout << \"discrete int step vector:\\n\";\n    write_data(Cout, discIntStepVector);\n  }\n  if (numDiscreteStringVars) {\n    Cout << \"discrete string step vector:\\n\";\n    write_data(Cout, discStringStepVector);\n  }\n  if (numDiscreteRealVars) {\n    Cout << \"discrete real step vector:\\n\";\n    write_data(Cout, discRealStepVector);\n  }\n#endif // DEBUG\n}\n\n\nbool ParamStudy::\ncheck_sets(const IntVector& c_steps,  const IntVector& di_steps,\n\t   const IntVector& ds_steps, const IntVector& dr_steps)\n{\n  // checks for vector and centered cases: admissibility of step vectors\n  // and number of steps among int/real sets\n  // > check terminal set indices for out of range\n  // > don't enforce that range variables remain within bounds (for now)\n  // Note: this check is performed at construct time and is dependent on the\n  // initial points; therefore, it is not a definitive check in the case of\n  // multi-iterator execution with updated initial points.  Nonetheless,\n  // verify proper set support for specified steps.\n\n  const BitArray&      di_set_bits = iteratedModel.discrete_int_sets();\n  const IntSetArray&    dsi_values = iteratedModel.discrete_set_int_values();\n  const StringSetArray& dss_values = iteratedModel.discrete_set_string_values();\n  const RealSetArray&   dsr_values = iteratedModel.discrete_set_real_values();\n  size_t j, dsi_cntr;\n  bool err = false;\n\n  // active discrete int: ranges and sets\n  for (j=0, dsi_cntr=0; j<numDiscreteIntVars; ++j)\n    if (di_set_bits[j]) {\n      const IntSet& dsi_vals_j = dsi_values[dsi_cntr];\n      int terminal_index = set_value_to_index(initialDIVPoint[j], dsi_vals_j)\n\t+ discIntStepVector[j] * di_steps[j];\n      if (terminal_index < 0 || terminal_index >= dsi_vals_j.size()) {\n\tCerr << \"\\nError: ParamStudy index \" << terminal_index\n\t     << \" not admissible for discrete int set of size \"\n\t     << dsi_vals_j.size() << '.' << std::endl;\n\terr = true;\n      }\n      ++dsi_cntr;\n    }\n\n  // active discrete string: sets only\n  for (j=0; j<numDiscreteStringVars; ++j) {\n    const StringSet& dss_vals_j = dss_values[j];\n    int terminal_index = set_value_to_index(initialDSVPoint[j], dss_vals_j)\n      + discStringStepVector[j] * ds_steps[j];\n    if (terminal_index < 0 || terminal_index >= dss_vals_j.size()) {\n      Cerr << \"\\nError: ParamStudy index \" << terminal_index\n\t   << \" not admissible for discrete string set of size \"\n\t   << dss_vals_j.size() << '.' << std::endl;\n      err = true;\n    }\n  }\n\n  // active discrete real: sets only\n  for (j=0; j<numDiscreteRealVars; ++j) {\n    const RealSet& dsr_vals_j = dsr_values[j];\n    int terminal_index = set_value_to_index(initialDRVPoint[j], dsr_vals_j)\n      + discRealStepVector[j] * dr_steps[j];\n    if (terminal_index < 0 || terminal_index >= dsr_vals_j.size()) {\n      Cerr << \"\\nError: ParamStudy index \" << terminal_index\n\t   << \" not admissible for discrete real set of size \"\n\t   << dsr_vals_j.size() << '.' << std::endl;\n      err = true;\n    }\n  }\n\n  return err;\n}\n\n} // namespace Dakota\n", "meta": {"hexsha": "8b04dfb92376be80a8afde60ff17e0f0cdf5cbf7", "size": 37108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ParamStudy.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ParamStudy.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ParamStudy.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9380902413, "max_line_length": 89, "alphanum_fraction": 0.6933814811, "num_tokens": 9990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.04146227641277931, "lm_q1q2_score": 0.016888969428247188}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2017-2018 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_FORMULAS_MERIDIAN_SEGMENT_HPP\r\n#define BOOST_GEOMETRY_FORMULAS_MERIDIAN_SEGMENT_HPP\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n#include <boost/geometry/core/radius.hpp>\r\n\r\n#include <boost/geometry/util/condition.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\r\n\r\nnamespace boost { namespace geometry { namespace formula\r\n{\r\n\r\n/*!\r\n\\brief Test if a segment is meridian or not.\r\n*/\r\n\r\nclass meridian_segment\r\n{\r\n\r\npublic :\r\n\r\n    enum SegmentType {NonMeridian, MeridianCrossingPole, MeridianNotCrossingPole};\r\n\r\n    template <typename T>\r\n    static inline SegmentType is_meridian(T lon1, T lat1, T lon2, T lat2)\r\n    {\r\n        SegmentType res = NonMeridian;\r\n        T diff = geometry::math::longitude_distance_signed<geometry::radian>(lon1, lon2);\r\n\r\n        if ( meridian_not_crossing_pole(lat1, lat2, diff) )\r\n        {\r\n            res = MeridianNotCrossingPole;\r\n        }\r\n        else if ( meridian_crossing_pole(diff) )\r\n        {\r\n            res = MeridianCrossingPole;\r\n        }\r\n        return res;\r\n    }\r\n\r\n    template <typename T>\r\n    static bool meridian_not_crossing_pole(T lat1, T lat2, T diff)\r\n    {\r\n        T half_pi = math::half_pi<T>();\r\n        return math::equals(diff, T(0)) ||\r\n               (math::equals(lat2, half_pi) && math::equals(lat1, -half_pi));\r\n    }\r\n\r\n    template <typename T>\r\n    static bool meridian_crossing_pole(T diff)\r\n    {\r\n        return math::equals(math::abs(diff), math::pi<T>());\r\n    }\r\n\r\n};\r\n\r\n}}} // namespace boost::geometry::formula\r\n\r\n#endif //BOOST_GEOMETRY_FORMULAS_MERIDIAN_SEGMENT_HPP\r\n", "meta": {"hexsha": "1b529b04ea3146e0e3f24db5d1c784a799ac3af0", "size": 2081, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/formulas/meridian_segment.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": 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": "deps/boost/include/boost/geometry/formulas/meridian_segment.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": 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": "deps/boost/include/boost/geometry/formulas/meridian_segment.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": 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": 28.5068493151, "max_line_length": 90, "alphanum_fraction": 0.6717924075, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047866316946014, "lm_q2_score": 0.03514484400064827, "lm_q1q2_score": 0.0168863476627307}}
{"text": "#include \"teca_tc_candidates.h\"\n\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_table.h\"\n#include \"teca_database.h\"\n#include \"teca_calendar.h\"\n#include \"teca_coordinate_util.h\"\n#include \"gfdl_tc_candidates.h\"\n\n#include <iostream>\n#include <sstream>\n#include <limits>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <chrono>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\n//#define TECA_DEBUG 2\n\nusing std::cerr;\nusing std::endl;\nusing seconds_t = std::chrono::duration<double, std::chrono::seconds::period>;\n\n// --------------------------------------------------------------------------\nteca_tc_candidates::teca_tc_candidates() :\n    max_core_radius(2.0),\n    min_vorticity_850mb(1.6e-4),\n    vorticity_850mb_window(7.75),\n    max_pressure_delta(400.0),\n    max_pressure_radius(5.0),\n    max_core_temperature_delta(0.8),\n    max_core_temperature_radius(5.0),\n    max_thickness_delta(50.0),\n    max_thickness_radius(4.0),\n    search_lat_low(1.0),\n    search_lat_high(0.0),\n    search_lon_low(1.0),\n    search_lon_high(0.0),\n    minimizer_iterations(50)\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_tc_candidates::~teca_tc_candidates()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_tc_candidates::get_properties_description(\n    const std::string &prefix, options_description &opts)\n{\n    options_description ard_opts(\"Options for \"\n        + (prefix.empty()?\"teca_tc_candidates\":prefix));\n\n    ard_opts.add_options()\n        TECA_POPTS_GET(std::string, prefix, surface_wind_speed_variable,\n            \"name of wind speed variable\")\n        TECA_POPTS_GET(std::string, prefix, vorticity_850mb_variable,\n            \"name of 850 mb vorticity variable\")\n        TECA_POPTS_GET(std::string, prefix, sea_level_pressure_variable,\n            \"name of sea level pressure variable\")\n        TECA_POPTS_GET(std::string, prefix, core_temperature_variable,\n            \"name of core temperature variable\")\n        TECA_POPTS_GET(double, prefix, max_core_radius,\n            \"maximum number of degrees latitude separation between \"\n            \"vorticity max and pressure min defining a storm (2.0)\")\n        TECA_POPTS_GET(double, prefix, min_vorticity_850mb,\n            \"minimum vorticty to be considered a tropical storm (1.6e-4)\")\n        TECA_POPTS_GET(double, prefix, vorticity_850mb_window,\n            \"size of the search window in degrees. storms core must have a \"\n            \"local vorticity max centered on this window (7.74446)\")\n        TECA_POPTS_GET(double, prefix, max_pressure_delta,\n            \"maximum pressure change within specified radius (400.0)\")\n        TECA_POPTS_GET(double, prefix, max_pressure_radius,\n            \"radius in degrees over which max pressure change is computed (5.0)\")\n        TECA_POPTS_GET(double, prefix, max_core_temperature_delta,\n            \"maximum core temperature change over the specified radius (0.8)\")\n        TECA_POPTS_GET(double, prefix, max_core_temperature_radius,\n            \"radius in degrees over which max core temperature change is computed (5.0)\")\n        TECA_POPTS_GET(double, prefix, max_thickness_delta,\n            \"maximum thickness change over the specified radius (50.0)\")\n        TECA_POPTS_GET(double, prefix, max_thickness_radius,\n            \"radius in degrees over with max thickness change is comuted (4.0)\")\n        TECA_POPTS_GET(double, prefix, search_lat_low,\n            \"lowest latitude in degrees to search for storms (-80.0)\")\n        TECA_POPTS_GET(double, prefix, search_lat_high,\n            \"highest latitude in degrees to search for storms (80.0)\")\n        TECA_POPTS_GET(double, prefix, search_lon_low,\n            \"lowest longitude in degrees to search for stroms (1)\")\n        TECA_POPTS_GET(double, prefix, search_lon_high,\n            \"highest longitude in degrees to search for storms (0)\")\n        ;\n\n    opts.add(ard_opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_tc_candidates::set_properties(\n    const std::string &prefix, variables_map &opts)\n{\n    TECA_POPTS_SET(opts, std::string, prefix, surface_wind_speed_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, vorticity_850mb_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, sea_level_pressure_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, core_temperature_variable)\n    TECA_POPTS_SET(opts, double, prefix, max_core_radius)\n    TECA_POPTS_SET(opts, double, prefix, min_vorticity_850mb)\n    TECA_POPTS_SET(opts, double, prefix, vorticity_850mb_window)\n    TECA_POPTS_SET(opts, double, prefix, max_pressure_delta)\n    TECA_POPTS_SET(opts, double, prefix, max_pressure_radius)\n    TECA_POPTS_SET(opts, double, prefix, max_core_temperature_delta)\n    TECA_POPTS_SET(opts, double, prefix, max_core_temperature_radius)\n    TECA_POPTS_SET(opts, double, prefix, max_thickness_delta)\n    TECA_POPTS_SET(opts, double, prefix, max_thickness_radius)\n    TECA_POPTS_SET(opts, double, prefix, search_lat_high)\n    TECA_POPTS_SET(opts, double, prefix, search_lat_low)\n    TECA_POPTS_SET(opts, double, prefix, search_lon_high)\n    TECA_POPTS_SET(opts, double, prefix, search_lon_low)\n}\n#endif\n\n// --------------------------------------------------------------------------\nteca_metadata teca_tc_candidates::get_output_metadata(unsigned int port,\n    const std::vector<teca_metadata> &input_md)\n{\n#if TECA_DEBUG > 1\n    cerr << teca_parallel_id()\n        << \"teca_tc_candidates::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_tc_candidates::get_active_extent(p_teca_variant_array lat,\n    p_teca_variant_array lon, std::vector<unsigned long> &extent) const\n{\n    extent = {1, 0, 1, 0, 0, 0};\n\n    unsigned long high_i = lon->size() - 1;\n    if (this->search_lon_low > this->search_lon_high)\n    {\n        extent[0] = 0l;\n        extent[1] = high_i;\n    }\n    else\n    {\n        TEMPLATE_DISPATCH_FP(\n            teca_variant_array_impl,\n            lon.get(),\n            NT *p_lon = std::dynamic_pointer_cast<TT>(lon)->get();\n\n            if (teca_coordinate_util::index_of(p_lon, 0, high_i, static_cast<NT>(this->search_lon_low), false, extent[0])\n                || teca_coordinate_util::index_of(p_lon, 0, high_i, static_cast<NT>(this->search_lon_high), true, extent[1]))\n            {\n                TECA_ERROR(\n                    << \"requested longitude [\"\n                    << this->search_lon_low << \", \" << this->search_lon_high << \", \"\n                    << \"] is not contained in the current dataset bounds [\"\n                    << p_lon[0] << \", \" << p_lon[high_i] << \"]\")\n                return -1;\n            }\n            )\n\n    }\n    if (extent[0] > extent[1])\n    {\n        TECA_ERROR(\"invalid longitude coordinate array type\")\n        return -1;\n    }\n\n    unsigned long high_j = lat->size() - 1;\n    if (this->search_lat_low > this->search_lat_high)\n    {\n        extent[2] = 0l;\n        extent[3] = high_j;\n    }\n    else\n    {\n        TEMPLATE_DISPATCH_FP(\n            teca_variant_array_impl,\n            lat.get(),\n            NT *p_lat = std::dynamic_pointer_cast<TT>(lat)->get();\n\n            if (teca_coordinate_util::index_of(p_lat, 0, high_j, static_cast<NT>(this->search_lat_low), false, extent[2])\n                || teca_coordinate_util::index_of(p_lat, 0, high_j, static_cast<NT>(this->search_lat_high), true, extent[3]))\n            {\n                TECA_ERROR(\n                    << \"requested latitude [\"\n                    << this->search_lat_low << \", \" << this->search_lat_high\n                    << \"] is not contained in the current dataset bounds [\"\n                    << p_lat[0] << \", \" << p_lat[high_j] << \"]\")\n                return -1;\n            }\n            )\n\n    }\n    if (extent[2] > extent[3])\n    {\n        TECA_ERROR(\"invalid latitude coordinate array type\")\n        return -1;\n    }\n\n    return 0;\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_tc_candidates::get_upstream_request(\n    unsigned int port, 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_tc_candidates::get_upstream_request\" << endl;\n#endif\n    (void)port;\n\n    std::vector<teca_metadata> up_reqs;\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    std::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    std::set<std::string> arrays;\n    request.get(\"arrays\", arrays);\n    arrays.insert(this->surface_wind_speed_variable);\n    arrays.insert(this->vorticity_850mb_variable);\n    arrays.insert(this->sea_level_pressure_variable);\n    arrays.insert(this->core_temperature_variable);\n    arrays.insert(this->thickness_variable);\n\n    teca_metadata up_req(request);\n    up_req.set(\"arrays\", arrays);\n    up_req.set(\"extent\", extent);\n\n    up_reqs.push_back(up_req);\n    return up_reqs;\n}\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_tc_candidates::execute(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_tc_candidates::execute\" << std::endl;\n#endif\n    (void)port;\n    (void)request;\n\n    if (!input_data.size())\n    {\n        TECA_ERROR(\"empty input\")\n        return nullptr;\n    }\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(\"teca_cartesian_mesh is required\")\n        return nullptr;\n    }\n\n    // get coordinate arrays\n    const_p_teca_variant_array y = mesh->get_y_coordinates();\n    const_p_teca_variant_array x = mesh->get_x_coordinates();\n\n    if (!x || !y)\n    {\n        TECA_ERROR(\"mesh coordinates are missing.\")\n        return nullptr;\n    }\n\n    // get time step\n    unsigned long time_step;\n    mesh->get_time_step(time_step);\n\n    // get temporal offset of the current timestep\n    double time_offset = 0.0;\n    mesh->get_time(time_offset);\n\n    // get offset units\n    std::string time_units;\n    mesh->get_time_units(time_units);\n\n    // get offset calendar\n    std::string calendar;\n    mesh->get_calendar(calendar);\n\n    // get extent of data passed in\n    std::vector<unsigned long> extent;\n    mesh->get_extent(extent);\n\n    long nlat = extent[3] - extent[2] + 1;\n    long nlon = extent[1] - extent[0] + 1;\n\n    // get wind speed array\n    const_p_teca_variant_array surface_wind_speed\n        = mesh->get_point_arrays()->get(this->surface_wind_speed_variable);\n\n    if (!surface_wind_speed)\n    {\n        TECA_ERROR(\"Dataset missing wind speed variable \\\"\"\n            << this->surface_wind_speed_variable << \"\\\"\")\n        return nullptr;\n    }\n\n    // get vorticity_850mb array\n    const_p_teca_variant_array vorticity_850mb\n        = mesh->get_point_arrays()->get(this->vorticity_850mb_variable);\n\n    if (!vorticity_850mb)\n    {\n        TECA_ERROR(\"Dataset missing vorticity_850mb variable \\\"\"\n            << this->vorticity_850mb_variable << \"\\\"\")\n        return nullptr;\n    }\n\n    // get core_temperature array\n    const_p_teca_variant_array core_temperature\n        = mesh->get_point_arrays()->get(this->core_temperature_variable);\n\n    if (!core_temperature)\n    {\n        TECA_ERROR(\"Dataset missing core_temperature variable \\\"\"\n            << this->core_temperature_variable << \"\\\"\")\n        return nullptr;\n    }\n\n    // get sea_level_pressure array\n    const_p_teca_variant_array sea_level_pressure\n        = mesh->get_point_arrays()->get(this->sea_level_pressure_variable);\n\n    if (!sea_level_pressure)\n    {\n        TECA_ERROR(\"Dataset missing sea_level_pressure variable \\\"\"\n            << this->sea_level_pressure_variable << \"\\\"\")\n        return nullptr;\n    }\n\n    // get thickness array\n    const_p_teca_variant_array thickness;\n    if (!(thickness = mesh->get_point_arrays()->get(this->thickness_variable)))\n    {\n        TECA_ERROR(\"Dataset missing thickness variable \\\"\"\n            << this->thickness_variable << \"\\\"\")\n        return nullptr;\n    }\n\n    // identify candidates\n    p_teca_table candidates = teca_table::New();\n\n    std::chrono::high_resolution_clock::time_point t0, t1;\n\n    NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n        x.get(), _COORD,\n\n        const NT_COORD *lon = static_cast<const TT_COORD*>(x.get())->get();\n        const NT_COORD *lat = static_cast<const TT_COORD*>(y.get())->get();\n\n        NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n            surface_wind_speed.get(), _VAR,\n\n            // configure the candidate table\n            candidates->declare_columns(\"storm_id\", int(),\n                \"lon\", NT_COORD(), \"lat\", NT_COORD(), \"surface_wind\", NT_VAR(),\n                \"850mb_vorticity\", NT_VAR(), \"sea_level_pressure\", NT_VAR(),\n                \"have_core_temp\", int(), \"have_thickness\", int(),\n                \"core_temp\", NT_VAR(), \"thickness\", NT_VAR());\n\n            const NT_VAR *v = dynamic_cast<const TT_VAR*>(surface_wind_speed.get())->get();\n            const NT_VAR *w = dynamic_cast<const TT_VAR*>(vorticity_850mb.get())->get();\n            const NT_VAR *P = dynamic_cast<const TT_VAR*>(sea_level_pressure.get())->get();\n            const NT_VAR *T = dynamic_cast<const TT_VAR*>(core_temperature.get())->get();\n            const NT_VAR *th = dynamic_cast<const TT_VAR*>(thickness.get())->get();\n\n            t0 = std::chrono::high_resolution_clock::now();\n            // invoke the detector\n            if (teca_gfdl::tc_candidates(this->max_core_radius,\n                this->min_vorticity_850mb, this->vorticity_850mb_window,\n                this->max_pressure_delta, this->max_pressure_radius,\n                this->max_core_temperature_delta, this->max_core_temperature_radius,\n                this->max_thickness_delta, this->max_thickness_radius, v, w,\n                T, P, th, lat, lon, nlat, nlon, this->minimizer_iterations,\n                time_step, candidates.get()))\n            {\n                TECA_ERROR(\"GFDL TC detector encountered an error\")\n                return nullptr;\n            }\n            t1 = std::chrono::high_resolution_clock::now();\n            )\n        )\n\n    // build the output\n    p_teca_table out_table = teca_table::New();\n    out_table->set_calendar(calendar);\n    out_table->set_time_units(time_units);\n\n    // add time stamp\n    out_table->declare_columns(\"step\", long(), \"time\", double());\n    unsigned long n_candidates = candidates->get_number_of_rows();\n    for (unsigned long i = 0; i < n_candidates; ++i)\n        out_table << time_step << time_offset;\n\n    // add the candidates\n    out_table->concatenate_cols(candidates);\n\n#if TECA_DEBUG > 1\n    out_table->to_stream(cerr);\n    cerr << std::endl;\n#endif\n    seconds_t dt(t1 - t0);\n    TECA_STATUS(\"teca_tc_candidates step=\" << time_step\n        << \" t=\" << time_offset << \", dt=\" << dt.count() << \" sec\")\n\n    return out_table;\n}\n\n// --------------------------------------------------------------------------\nvoid teca_tc_candidates::to_stream(std::ostream &os) const\n{\n    (void)os;\n}\n", "meta": {"hexsha": "76ac71657940b3010216e7b56e9c4f01804a0e37", "size": 16537, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_tc_candidates.cxx", "max_stars_repo_name": "mhaseeb123/TECA", "max_stars_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "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_tc_candidates.cxx", "max_issues_repo_name": "mhaseeb123/TECA", "max_issues_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "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_tc_candidates.cxx", "max_forks_repo_name": "mhaseeb123/TECA", "max_forks_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "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": 35.4111349036, "max_line_length": 125, "alphanum_fraction": 0.6189151599, "num_tokens": 3922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.03567855177492626, "lm_q1q2_score": 0.016864661893754258}}
{"text": "/**\n * @file bcsr.cpp\n * @brief\n * @author Oleg Borschuk\n * @date 2009-08-18\n */\n#ifdef BSPY_EXPORTING_PLUGIN\n#include <boost/python.hpp>\n#endif\n\n#include \"bcsr.h\"\n\nusing namespace std;\nusing namespace boost::python;\n\n\nnamespace blue_sky\n{\n  bcsr::bcsr (bs_type_ctor_param)\n        : bcsr_amg_matrix_iface (),\n        values (BS_KERNEL.create_object (v_float::bs_type ())),\n        cols_ind (BS_KERNEL.create_object (v_long::bs_type ())),\n        rows_ptr (BS_KERNEL.create_object (v_long::bs_type ()))\n\n    {\n      n_rows = n_cols = n_block_size = 0;\n    }\n  bcsr::bcsr (const bcsr & /*src*/) : bs_refcounter (),\n        values (BS_KERNEL.create_object (v_float::bs_type ())),\n        cols_ind (BS_KERNEL.create_object (v_long::bs_type ())),\n        rows_ptr (BS_KERNEL.create_object (v_long::bs_type ()))\n     {\n      n_rows = n_cols = n_block_size = 0;\n     }\n\n\n  int\n  bcsr::matrix_vector_product_t (spv_double v_, spv_double r_) const\n  {\n    t_long i, j1, j2, j, cl;\n\n    t_long *r_ptr = &(*rows_ptr)[0];\n    t_long *c_ind = &(*cols_ind)[0];\n    t_float *val = &(*values)[0];\n    t_double *v = &(*v_)[0];\n    t_double *r = &(*r_)[0];\n\n    //BS_ASSERT (v.size ());\n    //BS_ASSERT (r.size ());\n    //BS_ASSERT (v.size () >= r.size ()) (v.size ()) (r.size ());\n    //BS_ASSERT (n_rows == (t_long)v.size ());\n\n    //BS_ASSERT (n_block_size <= 1);\n    if (n_block_size > 1)\n      return -1;\n\n    ////////////////////////////////////////////\n    // loop through columns in transform matrix\n    ////////////////////////////////////////////\n    for (i = 0; i < n_rows; ++i)\n      {\n        j1 = r_ptr[i];\n        j2 = r_ptr[i + 1];\n\n        ////////////////////////////////////////////\n        // loop through rows in transform matrix\n        ////////////////////////////////////////////\n        for (j = j1; j < j2; ++j)\n          {\n            cl = c_ind[j];\n            r[cl] += v[i] * val[j];\n          }\n      }\n    return 0;\n  }\n\n  // calculate linear combination with current matrix A:\n  // r = alpha * A * u + beta * v\n  // 1 step: r = beta * v / alpha\n  // 2 step: r += alpha * matrix * u\n  int\n  bcsr::calc_lin_comb (t_double alpha,\n                       t_double beta,\n                       spv_double u_,\n                       spv_double v_,\n                       spv_double r_) const\n  {\n    static const t_double eps = t_double (1.0e-12);\n    t_long i, n;\n    int r_code = 0;\n\n    t_double *v = &(*v_)[0];\n    t_double *r = &(*r_)[0];\n\n    t_double d = beta;\n\n    if (fabs (alpha) > eps)\n      {\n        //BS_ASSERT (u.size ());\n        //BS_ASSERT (r.size () >= (size_t)(n_rows * n_block_size));\n        d /= alpha;\n      }\n    if (fabs (beta) > eps)\n      {\n        //BS_ASSERT (v.size ());\n        //BS_ASSERT (v.size () == r.size ())(v.size ())(r.size ());\n        //BS_ASSERT (r.size () >= (size_t)(n_rows * n_block_size)) (r.size ()) (n_rows) (n_block_size) (n_rows * n_block_size);\n      }\n\n    n = (t_long)r_->size ();\n    if (fabs (beta) > eps)\n      {\n        i = 0;\n        //t_long n2 = n - (n % 4);\n        // TODO:\n        for (; i < n; ++i)\n          {\n            r[i] = v[i] * d;\n          }\n      }\n    else\n      {\n        memset (r, 0, sizeof (t_double) * n);\n        //r.assign (n, 0);\n        //assign (r, 0);\n      }\n\n    if (fabs (alpha) > eps)\n      {\n        matrix_vector_product_internal <true> (u_, r_, alpha);\n      }\n\n    return r_code;\n  }\n\n  t_double\n  bcsr::get_allocated_memory_in_mbytes () const\n    {\n      t_double d = 0;\n\n      d += sizeof (this);\n      d += sizeof (t_float) * values->size ();\n      d += sizeof (t_long) * rows_ptr->size ();\n      d += sizeof (t_long) * cols_ind->size ();\n      d /= 1024 * 1024;\n      return d;\n    }\n\n  int\n  bcsr::init (const t_long new_n_rows,\n              const t_long new_n_cols,\n              const t_long new_n_block_size,\n              const t_long new_n_non_zeros)\n  {\n    if (new_n_block_size < 1 || new_n_cols < 1)\n      return -1;\n\n    n_block_size = new_n_block_size;\n    n_cols = new_n_cols;\n\n    if (alloc_rows_ptr (new_n_rows)\n        || alloc_cols_ind_and_values (new_n_non_zeros, new_n_block_size))\n      {\n        return -2;\n      }\n\n    return 0;\n  }\n\n  int\n  bcsr::alloc_rows_ptr (const t_long new_n_rows)\n  {\n    if (new_n_rows < 1)\n      return -1;\n\n    n_rows = new_n_rows;\n\n    rows_ptr->resize (n_rows + 1);\n    memset (&(*rows_ptr)[0], 0, sizeof (t_long) * (n_rows + 1));\n\n    return 0;\n  }\n\n  int\n  bcsr::alloc_cols_ind (const t_long new_n_non_zeros)\n  {\n    t_long nnz = new_n_non_zeros;\n\n    if (nnz < 1)\n      nnz = 1;\n\n    cols_ind->resize (nnz);\n    memset (&(*cols_ind)[0], -1, sizeof (t_long) * nnz);\n    return 0;\n  }\n\n  int\n  bcsr::alloc_values (const t_long new_n_non_zeros,\n                               const t_long new_n_block_size)\n  {\n    t_long b_sqr = new_n_block_size * new_n_block_size;\n    t_long nnz = new_n_non_zeros;\n\n    n_block_size = new_n_block_size;\n    if (nnz < 1)\n      nnz = 1;\n    if (b_sqr < 1)\n      b_sqr = 1;\n\n    values->resize (b_sqr * nnz);\n    memset (&(*values)[0], 0, sizeof (t_float) * nnz * b_sqr);\n\n    return 0;\n  }\n\n  int\n  bcsr::alloc_cols_ind_and_values (const t_long new_n_non_zeros,\n                                   const t_long new_n_blok_size)\n  {\n    if (alloc_cols_ind (new_n_non_zeros) || alloc_values (new_n_non_zeros, new_n_blok_size))\n      return -2;\n\n    return 0;\n  }\n\n  int\n  bcsr::init_by_matrix  (sp_bcsr_matrix_iface_t m)\n    {\n      rows_ptr = m->get_rows_ptr ()->clone ();\n      cols_ind = m->get_cols_ind ()->clone ();\n      values = m->get_values ()->clone ();\n      n_rows = m->get_n_rows ();\n      n_cols = m->get_n_cols ();\n      n_block_size = m->get_n_block_size ();\n      return 0;\n    }\n\n  int\n  bcsr::init_struct (const t_long new_n_rows,\n                     const t_long new_n_cols,\n                     const t_long new_n_non_zeros)\n{\n  if (new_n_cols < 1)\n    return -1;\n\n  n_cols = new_n_cols;\n  if (alloc_rows_ptr (new_n_rows) || alloc_cols_ind (new_n_non_zeros))\n    return -2;\n\n  return 0;\n}\n\n  int\n  bcsr::build_transpose_struct (sp_bcsr_matrix_iface_t m,\n                                const t_long rows_offset,\n                                const t_long cols_offset,\n                                const t_long new_n_rows)\n  {\n\n    t_long i,j;\n    t_long row_ind, j1, j2;\n    t_long nnz;\n    t_long nr;\n    t_long *r_ptr;\n    t_long *c_ind;\n    t_long *in_rows_ptr = &(*(m->get_rows_ptr ()))[0];\n    t_long *in_cols_ind = &(*(m->get_cols_ind ()))[0];\n    //t_float *v_ptr;\n\n    nnz = m->get_n_non_zeros ();\n    t_long in_n_rows = m->get_n_rows ();\n    t_long in_n_cols = m->get_n_cols ();\n    t_long in_n_block_size = m->get_n_block_size ();\n\n    if (new_n_rows == 0)\n      nr = in_n_cols;\n    else\n      nr = new_n_rows;\n\n    if (init (nr, in_n_rows, in_n_block_size, nnz))\n      return -1;\n\n    r_ptr = &(*rows_ptr)[0];\n    c_ind = &(*cols_ind)[0];\n    // Count the number of entries in each column of matrix (row of transposed matrix) and fill the rows_ptr array.\n\n    for (i = 0; i < nnz; i++)\n      {\n        ++r_ptr[in_cols_ind[i] + 1 - rows_offset];\n      }\n\n    for (i = 2; i <= n_rows; i++)\n      {\n        r_ptr[i] += r_ptr[i - 1];\n      }\n\n    // Load the values and column numbers of transposed matrix\n\n    for (i = 0; i < in_n_rows; i++)\n      {\n        j1 = in_rows_ptr[i];\n        j2 = in_rows_ptr[i + 1];\n        for (j = j1; j < j2; j++)\n          {\n            row_ind = in_cols_ind[j] - rows_offset;\n            c_ind[r_ptr[row_ind]] = i + cols_offset;\n            r_ptr[row_ind]++;\n          }\n      }\n    // rows_ptr now points to the *end* of the jth row of entries\n    // instead of the beginning.  Restore rows_ptr to front of row.\n\n    for (i = n_rows; i > 0; i--)\n      {\n        r_ptr[i] = r_ptr[i - 1];\n      }\n\n    r_ptr[0] = 0;\n\n    return 0;\n  }\n\n  int\n  bcsr::build_transpose (sp_bcsr_matrix_iface_t m,\n                         const t_long rows_offset,\n                         const t_long cols_offset,\n                         const t_long new_n_rows)\n  {\n\n    t_long i,j;\n    t_long row_ind, j1, j2;\n    t_long nnz;\n    t_long nr;\n    t_long *r_ptr;\n    t_long *c_ind;\n    t_long *in_rows_ptr = &(*(m->get_rows_ptr ()))[0];\n    t_long *in_cols_ind = &(*(m->get_cols_ind ()))[0];\n    t_float *v_ptr;\n    t_float *in_values = &(*(m->get_values ()))[0];\n\n    nnz = m->get_n_non_zeros ();\n    t_long in_n_rows = m->get_n_rows ();\n    t_long in_n_cols = m->get_n_cols ();\n    t_long in_n_block_size = m->get_n_block_size ();\n\n    if (new_n_rows == 0)\n      nr = in_n_cols;\n    else\n      nr = new_n_rows;\n\n    if (init (nr, in_n_rows, in_n_block_size, nnz))\n      return -1;\n\n    r_ptr = &(*rows_ptr)[0];\n    c_ind = &(*cols_ind)[0];\n    v_ptr = &(*values)[0];\n    // Count the number of entries in each column of matrix (row of transposed matrix) and fill the rows_ptr array.\n\n    for (i = 0; i < nnz; i++)\n      {\n        ++r_ptr[in_cols_ind[i] + 1 - rows_offset];\n      }\n\n    for (i = 2; i <= n_rows; i++)\n      {\n        r_ptr[i] += r_ptr[i - 1];\n      }\n\n    // Load the values and column numbers of transposed matrix\n\n    for (i = 0; i < in_n_rows; i++)\n      {\n        j1 = in_rows_ptr[i];\n        j2 = in_rows_ptr[i + 1];\n        for (j = j1; j < j2; j++)\n          {\n            row_ind = in_cols_ind[j] - rows_offset;\n            c_ind[r_ptr[row_ind]] = i + cols_offset;\n            v_ptr[r_ptr[row_ind]] = in_values[j];\n            r_ptr[row_ind]++;\n          }\n      }\n    // rows_ptr now points to the *end* of the jth row of entries\n    // instead of the beginning.  Restore rows_ptr to front of row.\n\n    for (i = n_rows; i > 0; i--)\n      {\n        r_ptr[i] = r_ptr[i - 1];\n      }\n\n    r_ptr[0] = 0;\n\n    return 0;\n  }\n  int\n  bcsr::triple_matrix_product (sp_bcsr_matrix_iface_t r_matrix, sp_bcsr_matrix_iface_t a_matrix,\n                               sp_bcsr_matrix_iface_t p_matrix, const bool update)\n  {\n    t_long i, i1, i2, j;\n    t_long jr1, jr2, jr;\n    t_long ja1, ja2, ja;\n    t_long jp1, jp2, jp;\n    t_long index_counter, i_row_ptr; // indexes of RAP values - current element and current row start element respectively\n    t_long thread_num = 0, n_threads = 1, row_begin, row_end, row_begin_s, row_end_s;\n    t_float r_a_product;\n    t_long *r_ptr;\n    t_long *c_ind;\n    t_float *v_ptr;\n\n    t_long *r_rows_ptr = &(*(r_matrix->get_rows_ptr ()))[0];\n    t_long *r_cols_ind = &(*(r_matrix->get_cols_ind ()))[0];\n    t_float *r_values   = &(*(r_matrix->get_values ()))[0];\n    t_long  r_n_rows   = r_matrix->get_n_rows ();\n\n    t_long *a_rows_ptr = &(*(a_matrix->get_rows_ptr ()))[0];\n    t_long *a_cols_ind = &(*(a_matrix->get_cols_ind ()))[0];\n    t_float *a_values   = &(*(a_matrix->get_values ()))[0];\n    t_long  a_n_cols   = a_matrix->get_n_cols ();\n\n    t_long *p_rows_ptr = &(*(p_matrix->get_rows_ptr ()))[0];\n    t_long *p_cols_ind = &(*(p_matrix->get_cols_ind ()))[0];\n    t_float *p_values   = &(*(p_matrix->get_values ()))[0];\n    t_long  p_n_cols   = p_matrix->get_n_cols ();\n    t_long block_size  = a_matrix->get_n_block_size ();\n\n    // works only with non-blocked matrices\n    if (block_size > 1)\n      {\n        //TODO: print error message\n        return -2;\n      }\n\n    if (!update)\n      {\n        // initializing RAP matrix\n        //result->n_block_size = A->n_block_size;\n        //result->n_cols = P->n_cols;\n        if (alloc_rows_ptr (r_n_rows))\n          {\n            //TODO: print error message\n            return -1;\n          }\n      }\n    r_ptr = &(*rows_ptr)[0];\n\n    // initializing some stuff (c)\n\n#ifdef TRIPLE_MATRIX_PRODUCT_PARALLEL\n#pragma omp master\n    {\n      r_matrix->get_n_rows () < omp_get_max_threads () ? n_threads = r_matrix->get_n_rows () : n_threads = omp_get_max_threads ();\n    }\n#endif //TRIPLE_MATRIX_PRODUCT_PARALLEL\n\n    a_marker_vec.assign (a_n_cols * n_threads, -1 );\n    p_marker_vec.assign (p_n_cols * n_threads, -1 );\n    t_long *a_marker = &a_marker_vec[0];\n    t_long *p_marker = &p_marker_vec[0];\n\n    r_ptr[0] = 0;\n\n    if (!update)\n      {\n        ///////////////////////////////////////\n        //  STEP 1 - calculating non-zero RAP elements count\n        ///////////////////////////////////////\n        // loop through R rows\n#ifdef TRIPLE_MATRIX_PRODUCT_PARALLEL\n#pragma omp parallel  firstprivate (A_marker, P_marker)                                \\\n                          private (i, thread_num, row_begin, row_end, i_row_ptr, jr1, jr2, jr, ja1, ja2, ja, \\\n                                   jp1, jp2, jp, i1, i2, j, index_counter)\n#endif //TRIPLE_MATRIX_PRODUCT_PARALLEL\n        {\n\n#ifdef TRIPLE_MATRIX_PRODUCT_PARALLEL\n          thread_num = omp_get_thread_num ();\n          a_marker += a_matrix->get_n_cols () * thread_num;\n          p_marker += p_matrix->get_n_cols () * thread_num;\n#endif //TRIPLE_MATRIX_PRODUCT_PARALLEL\n          index_counter = 0;\n          if (thread_num < n_threads) // thead is used\n            {\n              row_begin = r_n_rows * thread_num / n_threads;\n              row_end = r_n_rows * (thread_num + 1) / n_threads;\n            }\n          else\n            row_begin = row_end = 0;\n\n          for (i = row_begin; i < row_end; i++)\n            {\n              i_row_ptr = index_counter;\n\n              jr1 = r_rows_ptr[i];\n              jr2 = r_rows_ptr[i + 1];\n              // loop through R columns in i row\n              for (jr = jr1; jr < jr2; jr++)\n                {\n                  i1 = r_cols_ind[jr];\n\n                  ja1 = a_rows_ptr[i1];\n                  ja2 = a_rows_ptr[i1 + 1];\n                  // loop through A columns in i1 row\n                  for (ja = ja1; ja < ja2; ja++)\n                    {\n                      i2 = a_cols_ind[ja];\n\n                      //  Check A_marker to see if point i2 has been previously\n                      //  visited. New entries in RAP only occur from unmarked points.\n\n                      if (a_marker[i2] != i)\n                        {\n\n                          //  Mark i2 as visited.\n\n                          a_marker[i2] = i;\n\n                          jp1 = p_rows_ptr[i2];\n                          jp2 = p_rows_ptr[i2 + 1];\n                          // loop through P columns in i2 row\n                          for (jp = jp1; jp < jp2; jp++)\n                            {\n                              j = p_cols_ind[jp];\n\n                              //  Check P_marker to see that RAP{i,j} has not already\n                              //  been accounted for. If it has not, mark it and increment\n                              //  counter.\n\n                              if (p_marker[j] < i_row_ptr)\n                                {\n                                  // we have new entry in RAP matrix\n                                  p_marker[j] = index_counter;\n                                  index_counter++;\n                                }\n                            }\n                        }\n                    }\n                }\n              r_ptr[i + 1] = index_counter;\n            }\n#ifdef TRIPLE_MATRIX_PRODUCT_PARALLEL\n#pragma omp barrier\n#pragma omp single\n#endif //TRIPLE_MATRIX_PRODUCT_PARALLEL\n          // collect results of all threads at the head of each thread's chunk\n          {\n            i_row_ptr = 0;\n            for (j = 1; j < n_threads - 1; j++)\n              {\n                row_begin_s = r_n_rows * j / n_threads;\n                row_end_s = r_n_rows * (j + 1) / n_threads;\n                r_ptr[row_end_s] += r_ptr[row_begin_s];\n              }\n          }\n          // each thread adds collected head value to each member of own chunk\n          if (thread_num != 0)\n            {\n              for (i = row_begin; i < row_end - 1; i++)\n                {\n                  r_ptr[i + 1] += r_ptr[row_begin];\n                }\n              if (row_end == r_n_rows)\n                r_ptr[row_end] += r_ptr[row_begin];\n            }\n        } // end omp parallel\n\n\n\n        // now we have (RAP_rows_ptr[result->n_rows]) non-zero values in RAP matrix.\n        // Let`s finish it`s initialization\n        if (alloc_cols_ind_and_values(r_ptr[n_rows], 1))\n          //TODO: print error message\n          return -1;\n        set_n_cols (n_rows);\n      }\n    c_ind = &(*cols_ind)[0];\n    v_ptr = &(*values)[0];\n\n    // initializing some stuff (c)\n\n\n    a_marker_vec.assign (a_n_cols * n_threads, -1 );\n    p_marker_vec.assign (p_n_cols * n_threads, -1 );\n    a_marker = &a_marker_vec[0];\n    p_marker = &p_marker_vec[0];\n\n\n\n    ///////////////////////////////////////\n    //  STEP 2 - calculating a product\n    ///////////////////////////////////////\n#ifdef TRIPLE_MATRIX_PRODUCT_PARALLEL\n#pragma omp parallel  firstprivate (a_marker, p_marker)                                   \\\n                      private (i, thread_num, row_begin, row_end, i_row_ptr, jr1, jr2, jr, ja1, ja2, ja, \\\n                               jp1, jp2, jp, i1, i2, j, index_counter, r_a_product)\n#endif //TRIPLE_MATRIX_PRODUCT_PARALLEL\n    {\n#ifdef TRIPLE_MATRIX_PRODUCT_PARALLEL\n      thread_num = omp_get_thread_num ();\n      a_marker += a_matrix.get_n_cols () * thread_num;\n      p_marker += p_matrix.get_n_cols () * thread_num;\n#endif //TRIPLE_MATRIX_PRODUCT_PARALLEL\n\n      if (thread_num < n_threads) // thead is used\n        {\n          row_begin = r_n_rows * thread_num / n_threads;\n          row_end = r_n_rows * (thread_num + 1) / n_threads;\n        }\n      else\n        row_begin = row_end = 0;\n      index_counter = r_ptr[row_begin];\n      for (i = row_begin; i < row_end; i++)\n        {\n          i_row_ptr = index_counter;\n          p_marker[i] = index_counter;\n          v_ptr[index_counter] = 0.0;\n          c_ind[index_counter] = i;\n          ++index_counter;\n\n\n          jr1 = r_rows_ptr[i];\n          jr2 = r_rows_ptr[i + 1];\n\n          // loop through R columns in i row\n          for (jr = jr1; jr < jr2; jr++)\n            {\n              i1 = r_cols_ind[jr];\n\n              ja1 = a_rows_ptr[i1];\n              ja2 = a_rows_ptr[i1 + 1];\n\n              // loop through A columns in i1 row\n              for (ja = ja1; ja < ja2; ja++)\n                {\n                  i2 = a_cols_ind[ja];\n\n                  r_a_product = r_values[jr] * a_values[ja];\n\n                  //  Check A_marker to see if point i2 has been previously\n                  //  visited. New entries in RAP only occur from unmarked points.\n\n                  if (a_marker[i2] != i)\n                    {\n\n                      //  Mark i2 as visited.\n\n                      a_marker[i2] = i;\n\n                      jp1 = p_rows_ptr[i2];\n                      jp2 = p_rows_ptr[i2 + 1];\n\n                      for (jp = jp1; jp < jp2; jp++)\n                        {\n                          j = p_cols_ind[jp];\n\n                          //  Check P_marker to see that RAP{i,j} has not already\n                          //  been accounted for. If it has not, mark it and increment\n                          //  counter.\n\n                          if (p_marker[j] < i_row_ptr)\n                            {\n                              // we have new entry in RAP matrix\n                              v_ptr[index_counter] = p_values[jp] * r_a_product;\n                              c_ind[index_counter] = j;\n\n                              p_marker[j] = index_counter;\n                              index_counter++;\n                            }\n                          else\n                            {\n                              // we have already visited this element, upgrade it\n                              v_ptr[p_marker[j]] += p_values[jp] * r_a_product;\n                            }\n                        }\n                    }\n                  else\n                    {\n                      //  i2 is already visited. No new RAP entries. Just add contribution.\n\n                      jp1 = p_rows_ptr[i2];\n                      jp2 = p_rows_ptr[i2 + 1];\n\n                      for (jp = jp1; jp < jp2; jp++)\n                        {\n                          j = p_cols_ind[jp];\n                          v_ptr[p_marker[j]] += p_values[jp] * r_a_product;\n                        }\n                    }\n                }\n            }\n        }\n    } // end parallel\n\n    return 0;\n  }\n/////////////////////////////////BS Register\n/////////////////////////////////Stuff//////////////////////////\n\n  BLUE_SKY_TYPE_STD_CREATE (bcsr);\n  BLUE_SKY_TYPE_STD_COPY (bcsr);\n\n  BLUE_SKY_TYPE_IMPL (bcsr, bcsr_amg_matrix_iface, \"bcsr_matrix\", \"Block CSR Matrix class\", \"Realization of Block CSR Matricies\");\n}  // blue_sky namespace\n", "meta": {"hexsha": "2b98f09c23ac25df4b1c0fb7b7348359dd0c64da", "size": 20523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bs_mtx/src/bcsr.cpp", "max_stars_repo_name": "bs-eagle/bs-eagle", "max_stars_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-07-16T22:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T10:16:42.000Z", "max_issues_repo_path": "bs_mtx/src/bcsr.cpp", "max_issues_repo_name": "bs-eagle/bs-eagle", "max_issues_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bs_mtx/src/bcsr.cpp", "max_forks_repo_name": "bs-eagle/bs-eagle", "max_forks_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-05T20:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T16:19:10.000Z", "avg_line_length": 29.1934566145, "max_line_length": 130, "alphanum_fraction": 0.4944696195, "num_tokens": 5450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.043365802318428945, "lm_q1q2_score": 0.0168527319093699}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/xtp/forces.h>\n#include <boost/format.hpp>\n\n#include \"votca/xtp/statefilter.h\"\n\nnamespace votca {\n    namespace xtp {\n\n      using std::flush;\n        void Forces::Initialize(tools::Property &options) {\n\n            std::vector<std::string> choices = {\"forward\", \"central\"};\n            _force_method = options.ifExistsAndinListReturnElseThrowRuntimeError<std::string>(\".method\", choices);\n\n            _noisy_output = options.ifExistsReturnElseReturnDefault<bool>(\".noisy\", false); \n           \n            if ((_force_method == \"forward\") || (_force_method == \"central\")) {\n                _displacement = options.ifExistsReturnElseReturnDefault<double>(\".displacement\", 0.001); // Angstrom\n            }\n            _displacement*=tools::conv::ang2bohr;\n\n            // check for force removal options\n            choices = {\"total\", \"none\"};\n            std::string _force_removal = options.ifExistsAndinListReturnElseThrowRuntimeError<std::string>(\".removal\", choices);\n            if (_force_removal == \"total\") _remove_total_force = true;\n\n            _natoms = _orbitals.QMAtoms().size();\n            _forces =Eigen::MatrixX3d::Zero(_natoms,3);\n\n            return;\n        }\n\n        void Forces::Calculate(double energy) {\n\n            ctp::TLogLevel ReportLevel = _pLog->getReportLevel(); // backup report level\n            if ( ! _noisy_output ){\n                _pLog->setReportLevel(ctp::logERROR); // go silent for force calculations\n            }\n            std::vector<QMAtom*>& atoms=_orbitals.QMAtoms();\n            for (unsigned atom_index=0;atom_index<atoms.size();atom_index++) {\n                if ( _noisy_output ){\n                    CTP_LOG(ctp::logINFO, *_pLog) << \"FORCES--DEBUG working on atom \" << atom_index<< flush;\n                }\n                Eigen::Vector3d atom_force=Eigen::Vector3d::Zero();\n                // Calculate Force on this atom\n                if (_force_method == \"forward\") atom_force=NumForceForward(energy, atom_index);\n                if (_force_method == \"central\") atom_force=NumForceCentral(energy, atom_index);\n                _forces.row(atom_index)=atom_force.transpose();\n            }\n            _pLog->setReportLevel(ReportLevel); // \n            if (_remove_total_force) RemoveTotalForce();\n            return;\n        }\n\n        void Forces::Report() const{\n\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"   ---- FORCES (Hartree/Bohr)   \")).str() << flush;\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"        %1$s differences   \") % _force_method).str() << flush;\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"        displacement %1$1.4f Angstrom   \") % (_displacement*tools::conv::bohr2ang)).str() << flush;\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"   Atom\\t x\\t  y\\t  z \")).str() << flush;\n\n            for (unsigned _i = 0; _i < _forces.rows(); _i++) {\n                CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\" %1$4d    %2$+1.4f  %3$+1.4f  %4$+1.4f\")\n                        % _i % _forces(_i, 0) % _forces(_i, 1) % _forces(_i, 2)).str() << flush;\n            }\n            return;\n        }\n\n        /* Calculate forces on an atom numerically by forward differences */\n        Eigen::Vector3d Forces::NumForceForward(double energy,int atom_index) {\n            Eigen::Vector3d force=Eigen::Vector3d::Zero();\n            // get this atoms's current coordinates\n            QMAtom* atom= _orbitals.QMAtoms()[atom_index];\n            const tools::vec current_pos =atom->getPos();\n\n            for (unsigned i_cart = 0; i_cart < 3; i_cart++) {\n                tools::vec displacement_vec(0, 0, 0);          \n                displacement_vec[i_cart]=_displacement;\n                // update the coordinate\n                tools::vec pos_displaced = current_pos + displacement_vec;\n                atom->setPos(pos_displaced); \n                _gwbse_engine.ExcitationEnergies(_orbitals);\n                double energy_displaced = _orbitals.getTotalStateEnergy(_filter.CalcState(_orbitals));\n                force(i_cart) = (energy - energy_displaced) / _displacement;\n                 atom->setPos(current_pos); // restore original coordinate into segment\n            } // Cartesian directions\n            return force;\n        }\n\n        /* Calculate forces on atoms numerically by central differences */\n        Eigen::Vector3d Forces::NumForceCentral(double energy,int atom_index) {\n            QMAtom* atom= _orbitals.QMAtoms()[atom_index];\n            const tools::vec current_pos =atom->getPos();\n            Eigen::Vector3d force=Eigen::Vector3d::Zero();\n            for (unsigned i_cart = 0; i_cart < 3; i_cart++) {\n                if ( _noisy_output ){\n                    CTP_LOG(ctp::logINFO, *_pLog) << \"FORCES--DEBUG           Cartesian component \" << i_cart << flush;\n                }\n                tools::vec displacement_vec(0, 0, 0);          \n                displacement_vec[i_cart]=_displacement;\n                // update the coordinate\n                tools::vec pos_displaced = current_pos + displacement_vec;\n                atom->setPos(pos_displaced); \n                _gwbse_engine.ExcitationEnergies(_orbitals);\n                double energy_displaced_plus = _orbitals.getTotalStateEnergy(_filter.CalcState(_orbitals));\n                // update the coordinate\n                pos_displaced = current_pos - displacement_vec;\n                atom->setPos(pos_displaced); \n                _gwbse_engine.ExcitationEnergies(_orbitals);\n                double energy_displaced_minus = _orbitals.getTotalStateEnergy(_filter.CalcState(_orbitals));\n                force(i_cart) = 0.5 * (energy_displaced_minus - energy_displaced_plus) / _displacement;\n                atom->setPos(current_pos); // restore original coordinate into orbital\n            }\n            return force;\n        }\n\n        void Forces::RemoveTotalForce() {\n            Eigen::Vector3d total_force = _forces.colwise().sum();\n            for (unsigned i_atom = 0; i_atom < _natoms; i_atom++) {\n                _forces.row(i_atom)-=total_force/double(_natoms);\n            }\n            return;\n        }\n\n     \n    }\n}\n", "meta": {"hexsha": "e1c753a852b4ee6bcfaceff344480d0fd52a4274", "size": 6873, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/forces.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/forces.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/forces.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7551020408, "max_line_length": 160, "alphanum_fraction": 0.5853339153, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.04023794722734201, "lm_q1q2_score": 0.01684750414290532}}
{"text": "/*\nCompute Jensen-Shannon distance between an assembly's average tri-nucleotide \nor amino acid distribution and its genes' tri-nucleotide or amino acid distributions.\n*/\n#include <iostream>\n#include <string>\n#include <boost/program_options.hpp>\n#include \"./task/compute_distance_task.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 Jensen-Shannon distance between an assembly's average \"\n            \"tri-nucleotide (or amino acid) distribution and its genes' \"\n            \"tri-nucleotide (or amino acid) distributions\"\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            \t\"n_threads,t\", \n            \tpo::value<int>()->default_value(4),\n            \t\"Number of threads to use.\"\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        cerr << \"Computing Jensen-Shannon distance\" << endl;\n\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        const int n_threads = vm[\"n_threads\"].as<int>();\n        cerr << \"Threads: \" << n_threads << endl;\n\n        compute_distance(kind, n_threads);\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": "2d38b212c379660f45d95acc46489b07e8aaa3d0", "size": 2189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/compute_distance.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/compute_distance.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/compute_distance.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": 28.8026315789, "max_line_length": 85, "alphanum_fraction": 0.5253540429, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.0402379387392226, "lm_q1q2_score": 0.01684750058895596}}
{"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-2014 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef THREADING_HH\n#define THREADING_HH\n\n#include <functional>\n#include <future>\n#include <map>\n#include <queue>\n#include <utility>\n#include <vector>\n\n#define BOOST_THREAD_PROVIDES_INTERRUPTIONS\n\n#ifndef BOOST_DISABLE_THREADS\n#include <boost/thread/condition_variable.hpp>\n#include <boost/thread/locks.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/thread.hpp>\n#endif\n\n//#include <boost/timer/timer.hpp>  // xzl: this seems to conflict with boost/progress.hpp\n\n#include \"utilities/kalloc.hh\"\n\nnamespace Kaskade\n{\n#ifndef BOOST_DISABLE_THREADS\n  /**\n   * \\ingroup threading\n   * \\brief A global lock for the Dune::QuadratureRules factory, which is not thread-safe as of 2015-01-01.\n   */\n  extern boost::mutex DuneQuadratureRulesMutex;\n\n  /**\n   * \\ingroup threading\n   * \\brief A global lock for the Dune::GenericReferenceElement singletons, which are not thread-safe.\n   */\n  extern boost::mutex refElementMutex;\n#endif\n\n  //---------------------------------------------------------------------------\n\n  /**\n   * \\ingroup threading\n   * \\brief Computes partitioning points such that the sum of weights in each partition is roughly the same.\n   *\n   * Let \\f$ w_i, 0\\le i < N \\f$ denote the weights x[i]. On exit, x has size \\f$ k=n+1 \\f$ with values \\f$ x_i \\f$\n   * such that \\f$ x_0 = 0 \\f$, \\f$ x_{k-1} = N\\f$, and\n   * \\f[ \\sum_{j=x_i}^{x_{i+1}-1} w_j \\approx \\frac{1}{k} \\sum_{j=0}^{N-1} w_j. \\f]\n   *\n   * \\param[in,out] x the array of (nonnegative) weights\n   * \\param[in]     n the desired number of partitions (positive).\n   */\n  void equalWeightRanges(std::vector<size_t>& x, size_t n);\n\n  /**\n   * \\ingroup threading\n   * \\brief Computes partitioning points of ranges for uniform weight distributions.\n   *\n   * The functionality is similar to \\ref equalWeightRanges, but for uniform weight distribution, the\n   * partitioning points can be computed directly.\n   *\n   * \\tparam Index an integral type\n   * \\param i the number of the range for which the starting point is to be computed. Has to be in [0,n]\n   * \\param n the number of ranges\n   * \\param m the total number of entries\n   */\n  template <class BlockIndex, class Index>\n  Index uniformWeightRangeStart(BlockIndex i, BlockIndex n, Index m)\n  {\n    assert(i>=0 && i<=n && n>0 && m>0);\n    return (i*m)/n;\n  }\n\n  /**\n   * \\ingroup threading\n   * \\brief Computes the range in which an index is to be found when partitioned for uniform weights.\n   *\n   * \\tparam Index an integral type\n   * \\param j the index for which the range number is to be computed. Has to be in [0,m[\n   * \\param n the number of ranges\n   * \\param m the total number of entries\n   */\n  template <class Index>\n  Index uniformWeightRange(Index j, Index n, Index m)\n  {\n    assert(j>=0 && j<m && n>0 && m>0);\n\n    // We're looking for i such that floor(i*m/n) <= j < floor((i+1)*m/n), i.e. index j has\n    // to be in the half-open range given by the partitioning points of the range. Now this\n    // implies i*m/n-1 <= j < (i+1)*m/n and also j*n/m-1 < i <= (j+1)*n/m. As i is integer,\n    // this implies floor(j*n/m) <= i <= floor((j+1)*n/m). Typically, n/m is small, in which\n    // case this closed interval is likely to contain just one natural number - the result.\n    Index low = (j*n)/m;       // floor is implied by integer arithmetics\n    Index high = ((j+1)*n)/m;  // floor is implied by integer arithmetics\n\n    if (low==high)\n    {\n      assert(uniformWeightRangeStart(low,n,m)<=j && j<uniformWeightRangeStart(low+1,n,m));\n      return low;\n    }\n\n    // The implied inequality chains above are not sharp estimates, therefore the interval\n    // [low,high] can contain several natural numbers. This is always the case if n>m, i.e., we have\n    // more ranges than entries and several ranges are empty. But it can also happen if j*n/m is\n    // just below the next integral number. Now we have to walk through all natural numbers in\n    // the interval to find the correct range. TODO: is there a direct way?\n    Index i = low;\n    while (i<high && !(uniformWeightRangeStart(i,n,m)<=j && j<uniformWeightRangeStart(i+1,n,m)))\n      ++i;\n\n    assert(uniformWeightRangeStart(i,n,m)<=j && j<uniformWeightRangeStart(i+1,n,m));\n    return i;\n  }\n\n  //---------------------------------------------------------------------------\n\n  #ifndef BOOST_DISABLE_THREADS\n  /**\n   * \\ingroup threading\n   * \\brief A concurrent fifo queue.\n   *\n   * The queue is not copyable as it is intended to hold non-copyable std:packaged_task objects.\n   */\n  template <class T>\n  class ConcurrentQueue {\n  public:\n    /**\n     * \\brief Constructs an empty queue.\n     */\n    ConcurrentQueue()\n    {\n    }\n\n    /**\n     * \\brief Moves a queue.\n     */\n    ConcurrentQueue(ConcurrentQueue&& q)\n    {\n      boost::lock_guard<boost::mutex> lock(q.mutex);\n      queue = std::move(q.queue);\n    }\n\n    /**\n     * \\brief Assignment.\n     */\n    ConcurrentQueue& operator=(ConcurrentQueue const& q)\n    {\n      boost::lock_guard<boost::mutex> lock(q.mutex);\n      queue = q.queue;\n      return *this;\n    }\n\n    bool empty() const\n    {\n      boost::lock_guard<boost::mutex> lock(mutex);\n      return queue.empty();\n    }\n\n    size_t size() const\n    {\n      boost::lock_guard<boost::mutex> lock(mutex);\n      return queue.size();\n    }\n\n    /**\n     * \\brief Stores an element at the end of the queue.\n     */\n    void push_back(T&& t)\n    {\n      {\n      boost::lock_guard<boost::mutex> lock(mutex);\n      queue.push(std::move(t));\n      } // release lock before waking up consumers\n      filled.notify_one();\n    }\n\n    /**\n     * \\brief Retrieves the foremost element.\n     *\n     * This method blocks if the queue is empty and waits for data to become available.\n     */\n    T pop_front()\n    {\n      boost::unique_lock<boost::mutex> lock(mutex);\n\n      // Wait for data to become available.\n      while (queue.empty())\n        filled.wait(lock);\n\n      // extract and remove data. When assignment throws an exception, the queue\n      // remains unmodified\n      T t = std::move(queue.front());\n      queue.pop();\n      return t;\n    }\n\n  private:\n    std::queue<T> queue;\n    mutable boost::mutex mutex; // has to be mutable because of empty/size\n    boost::condition_variable filled;\n  };\n#endif\n\n  //----------------------------------------------------------------------------\n#ifndef BOOST_DISABLE_THREADS\n  /**\n   * \\ingroup threading\n   * \\brief Abstract interface for tasks to be scheduled for concurrent execution.\n   */\n  typedef std::packaged_task<void()> Task;\n\n  /**\n   * \\ingroup threading\n   * \\brief Abstract waitable job ticket for submitted tasks.\n   */\n  typedef std::future<void> Ticket;\n#else\n  /**\n   * \\ingroup threading\n   * \\brief Abstract interface for tasks to be scheduled for concurrent execution. This is just a workaround for missing std::packaged_task on GCC/Windows.\n   */\n  typedef std::function<void()> Task;\n\n  /**\n   * \\ingroup threading\n   * \\brief Abstract waitable job ticket for submitted tasks. This is just a workaround for missing std::future on GCC/Windows.\n   */\n  struct Ticket\n  {\n    void get() const {}\n    void wait() const {}\n  };\n#endif\n\n\n\n  //----------------------------------------------------------------------------\n\n  /**\n   * \\ingroup threading\n   * \\brief Implementation of thread pools suitable for parallelization of (more or less) memory-bound algorithms (not only) on NUMA machines.\n   *\n   * This class maintains two thread pools satisfying different needs.\n   *\n   * The threads in the first (global) pool can be moved by the operating system freely between nodes and CPUs, and should be used (by submitting tasks via \\ref run)\n   * whenever there is no particular need to execute the task on a particular NUMA node, i.e. if the task is not memory-bandwidth-bound or works on\n   * data that is not located on a particular NUMA node. The number of global threads defaults to twice the number of available CPUs (such that all CPUs can be\n   * busy even if some threads wait on a mutex), but is at least 4 unless limited to a smaller number on construction of the thread pool, see \\ref instance.\n   *\n   * The threads in the second (NUMA) pool are pinned to nodes (the OS is allowed to move them between CPUS on the same node), and should be used\n   * (by submitting tasks via \\ref runOnNode) whenever the tasks are memory-bandwidth-bound and the data resides on a particular NUMA node.\n   * Note that as the threads are locked to the nodes, the operating system cannot move the threads. This is intended to keep\n   * the thread close to its data in order to have local memory access. On the other hand, on multi-user machines it can lead to\n   * several threads competing for the same CPU while other CPUs are idle. Use the node-locked threads only if locality of memory\n   * access is of top priority.\n   *\n   * Relying on the first-touch policy for controlling memory locality is not guaranteed to keep threads and data close to each other.\n   * First, the allocator may re-use memory blocks previously touched and released by a different thread, leading to remote data\n   * access. Second, the operating system may decide to move a thread to a different node without knowledge of which thread\n   * is memory-bound or compute-bound.\n   *\n   * Caveat: When submitting tasks recursively to the task pool, it is easy to create a deadlock. While the top level tasks wait for the\n   *         completion of the lower level tasks, the lower level task is not processed as all threads in the pool are occupied by the\n   *         top level tasks. Take care not to submit more recursive tasks than there are worker threads available.\n   */\n  class NumaThreadPool {\n  public:\n    /**\n     * \\brief Returns a globally unique thread pool instance.\n     *\n     * On the very first call of this method, the singleton thread pool is created with a limitation of the number of global (unpinned)\n     * threads limited by the given number of maxThreads. Later calls with different value of maxThreads do not change the number of threads.\n     * In case the number of global threads shall be limited throughout, call this method at the very start of the program.\n     *\n     * \\param maxThreads an upper bound for the number of global threads to create.\n     *\n     * As it makes little sense to have multiple thread pools fight for physical ressources, a single instance should be employed.\n     */\n    static NumaThreadPool& instance(int maxThreads = std::numeric_limits<int>::max());\n\n    /**\n     * \\name System information\n     * @{\n     */\n\n    /**\n     * \\brief Reports the number of NUMA nodes (i.e., memory interfaces/CPU sockets)\n     */\n    int nodes() const\n    {\n      return nNode;\n    }\n\n    /**\n     * \\brief Reports the total number of CPUs (usually a multiple of nodes)\n     */\n    int cpus() const\n    {\n      return nCpu;\n    }\n\n    /**\n     * \\brief Reports the number of CPUs on the given node (usually the same for all nodes).\n     */\n    int cpus(int node) const\n    {\n      return cpuByNode[node].size();\n    }\n\n    /**\n     * \\brief Reports the maximal number of CPUs on one node.\n     */\n    int maxCpusOnNode() const\n    {\n      return maxCpusPerNode;\n    }\n\n    /**\n     * @}\n     */\n\n    /**\n     * \\name Task submission\n     * @{\n     */\n\n    /**\n     * \\brief Schedules a task to be executed on an arbitrary CPU.\n     *\n     * Waiting for tasks to be completed can be done by obtaining a waitable Ticket object from the task\n     * before submitting it.\n     *\n     * \\param task the task object to be executed.\n     */\n    Ticket run(Task&& task);\n\n    /**\n     * \\brief Schedules a task to be executed on a CPU belonging to the given NUMA node.\n     *\n     * Waiting for tasks to be completed can be done by obtaining a waitable Ticket object from the task\n     * before submitting it.\n     *\n     * \\param node the number of the node on which to execute the task. 0 <= node < nodes().\n     * \\param task the task object to be executed. The object has to live at least until the call to its call operator returns.\n     */\n    Ticket runOnNode(int node, Task&& task);\n\n    /**\n     * @}\n     */\n\n    /**\n     * \\name NUMA-aware memory management\n     * @{\n     */\n\n    /**\n     * \\brief Returns the allocator used for the given node.\n     */\n    Kalloc& allocator(int node);\n\n    /**\n     * \\brief Allocates memory on a specific node.\n     *\n     * Note: this is comparatively slow and should only be used for allocating large chunks of memory\n     * to be managed locally. The memory has to be released by a subsequent call to deallocate.\n     */\n    void* allocate(size_t n, int node);\n\n    /**\n     * \\brief frees a chunk of memory previously allocated\n     */\n    void deallocate(void* p, size_t n, int node);\n\n    /**\n     * \\brief Reports the alignment size of allocator at given NUMA node.\n     */\n    size_t alignment(int node) const;\n\n    /**\n     * \\brief Tells the allocator to prepare for subsequent allocation of several memory blocks of same size.\n     * \\param n the requested size of the memory blocks\n     * \\param k the number of memory blocks that will be requested\n     * \\param node on which NUMA node\n     *\n     * Use this as a hint for the allocator that allows to improve its performance.\n     */\n    void reserve(size_t n, size_t k, int node);\n\n    /**\n     * @}\n     */\n\n  private:\n\n    // private constructor to be called by instance()\n    NumaThreadPool(int maxThreads);\n    ~NumaThreadPool();\n\n#ifndef BOOST_DISABLE_THREADS\n    Ticket runOnQueue(ConcurrentQueue<Task>& queue, Task&& task);\n#endif\n\n\n    int nCpu, nNode, maxCpusPerNode;\n#ifndef BOOST_DISABLE_THREADS\npublic: // xzl debugging\n    std::vector<ConcurrentQueue<Task>>    nodeQueue;  // task queues for passing to worker threads on nodes\nprivate:\n    ConcurrentQueue<Task>                 globalQueue;\n    boost::thread_group                   threads;    // worker threads\n#endif\n    std::vector<int>                      nodeByCpu;  // NUMA topology info\n    std::vector<std::vector<int>>         cpuByNode;  // NUMA topology info\n    std::map<void*,std::pair<size_t,int>> memBlocks;  // NUMA memory allocations\n    std::vector<Kalloc>                   nodeMemory; // NUMA memory management\n  };\n\n  /**\n   * \\ingroup threading\n   * \\brief A parallel for loop that executes the given functor in parallel on different CPUs\n   *\n   * \\tparam Func a functor with an operator ()(int i, int n)\n   *\n   * \\param f the functor to call\n   * \\param maxTasks the maximal number of tasks to create\n   *\n   * The given function object is called in parallel for values (i,n) with i ranging from 0 to n-1. The number n is\n   * the same for all calls and guaranteed not to exceed maxTasks (but may be smaller).\n   *\n   * The function returns after the last task has been completed, therefore the computational\n   * effort for tasks 0,...,n-1 should be roughly equal, no matter which value n has. For an optimal performance,\n   * maxTasks should be either a small multiple of the number of CPUs in the system (such that ideally all CPUs are\n   * busy the whole time) or much larger than that (such that an imbalance has only a small impact).\n   */\n  template <class Func>\n  void parallelFor(Func const& f, int maxTasks = std::numeric_limits<int>::max())\n  {\n    NumaThreadPool& pool = NumaThreadPool::instance();\n    int nTasks = std::min(4*pool.cpus(),maxTasks);\n\n    std::vector<Ticket> tickets(nTasks);\n    for (int i=0; i<nTasks; ++i)\n      tickets[i] = pool.run(Task([i,&f,nTasks] { f(i,nTasks); }));\n\n    for (auto& ticket: tickets)\n    {\n      ticket.wait();\n    }\n  }\n\n  /**\n   * \\ingroup threading\n   * \\brief A parallel for loop that executes the given functor in parallel on different NUMA nodes\n   *\n   * \\tparam Func a functor with an operator ()(int i, int n)\n   *\n   * \\param f the functor to call\n   * \\param maxTasks the maximal number of tasks to create\n   *\n   * The given function object is called in parallel for values (i,n) with i ranging from 0 to n-1. The number n is\n   * min(nNodes,maxTasks) for all calls to f. Every task is executed on the node given by arguemnt i.\n   *\n   * The function returns after the last task has been completed, therefore the computational\n   * effort for tasks 0,...,n-1 should be roughly equal, no matter which value n has.\n   */\n  template <class Func>\n  void parallelForNodes(Func const& f, int maxTasks = std::numeric_limits<int>::max())\n  {\n    NumaThreadPool& pool = NumaThreadPool::instance();\n    int nTasks = std::min(pool.nodes(),maxTasks);\n    std::vector<Ticket> tickets(nTasks);\n    for (int i=0; i<nTasks; ++i)\n      tickets[i] = pool.runOnNode(i,Task([i,&f,&nTasks] { f(i,nTasks); }));\n    for (auto& ticket: tickets)\n      ticket.wait();\n  }\n\n  //----------------------------------------------------------------------------\n\n  /**\n   * \\cond internals\n   */\n  namespace ThreadingDetail\n  {\n    class NumaAllocatorBase\n    {\n    public:\n      NumaAllocatorBase(int node);\n\n      size_t max_size() const;\n\n      void* allocate(size_t n);\n\n      void deallocate(void* p, size_t n);\n\n      int node() const\n      {\n        return nod;\n      }\n\n    private:\n      int nod;\n    public:  // xzl: for debugging\n      Kalloc* allocator; // xzl: ctor will point this to existing threadpool's NUMA allocator\n    };\n  }\n  /**\n   * \\endcond\n   */\n\n  /**\n   * \\ingroup threading\n   * \\brief An STL allocator that uses memory of a specific NUMA node only.\n   */\n  template <class T>\n  class NumaAllocator\n  {\n  public:\n    typedef T value_type;\n    typedef T* pointer;\n    typedef T const* const_pointer;\n    typedef T& reference;\n    typedef T const& const_reference;\n    typedef std::size_t size_type;\n    typedef std::ptrdiff_t difference_type;\n\n    // make sure that on copying, the target copy has its data in the same\n    // NUMA memory region as the source by default -- this improves data locality.\n    typedef std::true_type propagate_on_container_copy_assignment;\n    typedef std::true_type propagate_on_container_move_assignment;\n    typedef std::true_type propagate_on_container_swap;\n    \n    template <class U>\n    struct rebind\n    {\n      typedef NumaAllocator<U> other;\n    };\n\n    /**\n     * \\brief Construct an allocator for allocating on the given NUMA node.\n     *\n     * \\param node the NUMA node on which to allocate the memory. This has to be less than NumaThreadPool::instance().nodes().\n     *             For negative values, the memory is allocated in interleaved mode.\n     */\n    NumaAllocator(int node): alloc(node)\n    {\n    }\n\n    /* xzl: the following three appears necessary, otherwise rebinding will run into errors \n     * cf: alloc.cpp\n     */\n    NumaAllocator(const NumaAllocator & other) : alloc(other.node()) { }\n    \n    template <class U>\n    NumaAllocator(const NumaAllocator<U> & other) : alloc(other.node()) { }\n    \n    ~NumaAllocator() {}\n    \n    /**\n     * \\brief Reports the node on which we allocate.\n     */\n    int node() const\n    {\n      return alloc.node();\n    }\n\n    pointer address( reference x ) const\n    {\n      return &x;\n    }\n\n    const_pointer address( const_reference x ) const\n    {\n      return &x;\n    }\n\n    size_type max_size() const\n    {\n      return alloc.max_size() / sizeof(T);\n    }\n\n    /**\n     * \\brief Allocates the requested amount of memory.\n     *\n     * If \\arg n == 0, a null pointer is returned.\n     *\n     * \\param n number of objects of type T\n     */\n    pointer allocate( size_type n, std::allocator<void>::const_pointer /* hint */ = 0 )\n    {\n      if (n>0)\n        return static_cast<pointer>(alloc.allocate(n*sizeof(T)));\n      else\n        return nullptr;\n    }\n\n    void deallocate(pointer p, size_type n)\n    {\n      if (p)\n        alloc.deallocate(static_cast<void*>(p),n*sizeof(T));\n    }\n\n    template< class U, class... Args >\n    void construct( U* p, Args&&... args )\n    {\n      ::new((void*)p) U(std::forward<Args>(args)...);\n    }\n\n    template <class U>\n    void destroy( U* p )\n    {\n      p->~U();\n    }\n\n    /**\n     * \\brief comparison for equality\n     *\n     * Allocators compare equal, if they allocate on the same NUMA node.\n     */\n    template <class U>\n    bool operator==(NumaAllocator<U> const& other) const\n    {\n      return node()==other.node();\n    }\n\n    template <class U>\n    bool operator!=(NumaAllocator<U> const& other) const\n    {\n      return !(node() == other.node());\n    }\n\n//  private:\n  public:\t\t\t// xzl: for debugging\n    ThreadingDetail::NumaAllocatorBase alloc; // xzl: storing a ptr to threadpool's existing allocator\n  };\n\n  //----------------------------------------------------------------------------\n\n  /**\n   * \\brief A utility class implementing appropriate copy semantics for boost mutexes.\n   *\n   * \\todo: design appropriate semantics for move construction/assignment\n   */\n  class Mutex\n  {\n  public:\n    /**\n     * \\brief Default constructor.\n     *\n     * The constructed object's mutex is unlocked.\n     */\n    Mutex() = default;\n\n    /**\n     * \\brief Copy constructor.\n     *\n     * The constructed object's mutex is unlocked, independently of the state of m.\n     */\n    Mutex(Mutex const& m) {}\n\n    /**\n     * \\brief Assignment.\n     *\n     * Our mutex doesn't change its state.\n     */\n    Mutex& operator=(Mutex const& m) { return *this; }\n\n    #ifndef KASKADE_SEQUENTIAL\n    /**\n     * \\brief provides access to the mutex to perform the locking.\n     */\n    boost::mutex& get() { return mutex; }\n    #endif\n\n  private:\n    #ifndef KASKADE_SEQUENTIAL\n    boost::mutex mutex;\n    #endif\n  };\n\n}\n\n#endif\n", "meta": {"hexsha": "418a0c6d0559511e579035804a51b20c6f241ae2", "size": 22402, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/utilities/threading.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/utilities/threading.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/utilities/threading.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 32.1406025825, "max_line_length": 165, "alphanum_fraction": 0.6178466208, "num_tokens": 5412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982564942392716, "lm_q2_score": 0.06465348880678597, "lm_q1q2_score": 0.01679863471674577}}
{"text": "// This file is a part of the OpenSurgSim project.\n// Copyright 2013-2016, 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 \"SurgSim/Blocks/KnotIdentificationBehavior.h\"\n\n#include <boost/assign/list_of.hpp>\n#include <boost/math/special_functions/sign.hpp>\n\n#include \"SurgSim/Framework/SceneElement.h\"\n#include \"SurgSim/Graphics/OsgPointCloudRepresentation.h\"\n#include \"SurgSim/Graphics/OsgTextRepresentation.h\"\n#include \"SurgSim/Math/Geometry.h\"\n#include \"SurgSim/Math/RigidTransform.h\"\n#include \"SurgSim/Physics/Fem1DLocalization.h\"\n#include \"SurgSim/Physics/Fem1DRepresentation.h\"\n#include \"SurgSim/Physics/FemElement.h\"\n\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Vector2d;\n\nnamespace SurgSim\n{\nnamespace Blocks\n{\nSURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Blocks::KnotIdentificationBehavior,\n\t\t\t\t KnotIdentificationBehavior);\n\nKnotIdentificationBehavior::KnotIdentificationBehavior(const std::string& name) :\n\tFramework::Behavior(name), m_knotName(\"Undetermined\")\n{\n\tusing boost::assign::list_of;\n\n\tSURGSIM_ADD_SERIALIZABLE_PROPERTY(KnotIdentificationBehavior,\n\t\tstd::shared_ptr<SurgSim::Physics::Fem1DRepresentation>, Fem1d, getFem1d, setFem1d);\n\n\taddKnownKnotCode(\"Trefoil Knot\", boost::assign::list_of(1)(-2)(3)(-1)(2)(-3),\n\t\tboost::assign::list_of(1)(1)(1)(1)(1)(1));\n\taddKnownKnotCode(\"Granny Knot\", boost::assign::list_of(1)(-2)(3)(-4)(5)(-6)(4)(-5)(6)(-1)(2)(-3),\n\t\tboost::assign::list_of(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1));\n\taddKnownKnotCode(\"Granny Knot\", boost::assign::list_of(1)(-2)(3)(4)(-5)(6)(-4)(5)(-6)(-1)(2)(-3),\n\t\tboost::assign::list_of(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1)(-1));\n\taddKnownKnotCode(\"Granny Knot\", boost::assign::list_of(1)(-2)(3)(-4)(5)(-6)(4)(-5)(6)(-1)(2)(-3),\n\t\tboost::assign::list_of(1)(1)(1)(1)(1)(1)(1)(1)(1)(1)(1)(1));\n\taddKnownKnotCode(\"Granny Knot\", boost::assign::list_of(1)(-2)(3)(4)(-5)(6)(-4)(5)(-6)(-1)(2)(-3),\n\t\tboost::assign::list_of(1)(1)(1)(1)(1)(1)(1)(1)(1)(1)(1)(1));\n\taddKnownKnotCode(\"Square Knot\", boost::assign::list_of(1)(-2)(3)(4)(-5)(6)(-4)(5)(-6)(-1)(2)(-3),\n\t\tboost::assign::list_of(-1)(-1)(-1)(1)(1)(1)(1)(1)(1)(-1)(-1)(-1));\n\taddKnownKnotCode(\"Square Knot\", boost::assign::list_of(1)(-2)(3)(-4)(5)(-6)(4)(-5)(6)(-1)(2)(-3),\n\t\tboost::assign::list_of(-1)(-1)(-1)(1)(1)(1)(1)(1)(1)(-1)(-1)(-1));\n\taddKnownKnotCode(\"Square Knot\", boost::assign::list_of(1)(-2)(3)(4)(-5)(6)(-4)(5)(-6)(-1)(2)(-3),\n\t\tboost::assign::list_of(1)(1)(1)(-1)(-1)(-1)(-1)(-1)(-1)(1)(1)(1));\n\taddKnownKnotCode(\"Square Knot\", boost::assign::list_of(1)(-2)(3)(-4)(5)(-6)(4)(-5)(6)(-1)(2)(-3),\n\t\tboost::assign::list_of(1)(1)(1)(-1)(-1)(-1)(-1)(-1)(-1)(1)(1)(1));\n}\n\nvoid KnotIdentificationBehavior::setFem1d(const std::shared_ptr<Framework::Component>& fem1d)\n{\n\tm_fem1d = Framework::checkAndConvert<Physics::Fem1DRepresentation>(fem1d,\n\t\t\"SurgSim::Physics::Fem1DRepresentation\");\n}\n\nconst std::shared_ptr<Physics::Fem1DRepresentation>& KnotIdentificationBehavior::getFem1d() const\n{\n\treturn m_fem1d;\n}\n\nconst std::string& KnotIdentificationBehavior::getKnotName()\n{\n\tboost::lock_guard<boost::mutex> lock(m_mutex);\n\treturn m_knotName;\n}\n\nvoid KnotIdentificationBehavior::update(double dt)\n{\n\tstd::vector<std::string> results;\n\tfor (const auto& projection : m_projections)\n\t{\n\t\tconst auto& knotName = detectAndIdentifyKnot(projection);\n\t\tif (knotName != \"No Knot\")\n\t\t{\n\t\t\tresults.push_back(knotName);\n\t\t}\n\t}\n\tstd::string knotName = \"No Knot\";\n\tif (results.size() > 0)\n\t{\n\t\tknotName = results.back();\n\t\tif (results.size() > 1)\n\t\t{\n\t\t\tstd::vector<std::string> known;\n\t\t\tfor (const auto& r : results)\n\t\t\t{\n\t\t\t\tif (r != \"Unknown Knot\")\n\t\t\t\t{\n\t\t\t\t\tknown.push_back(r);\n\t\t\t\t}\n\t\t\t}\n\t\t\tptrdiff_t maxCount = 0;\n\t\t\tfor (const auto& k : known)\n\t\t\t{\n\t\t\t\tauto count = std::count(known.begin(), known.end(), k);\n\t\t\t\tif (count > maxCount)\n\t\t\t\t{\n\t\t\t\t\tmaxCount = count;\n\t\t\t\t\tknotName = k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tboost::lock_guard<boost::mutex> lock(m_mutex);\n\tm_knotName = knotName;\n}\n\nint KnotIdentificationBehavior::getTargetManagerType() const\n{\n\treturn Framework::MANAGER_TYPE_PHYSICS;\n}\n\nbool KnotIdentificationBehavior::doInitialize()\n{\n\tusing Math::makeRigidTransform;\n\tMath::Matrix33d projection;\n\tm_projections.clear();\n\tm_projections.push_back(Math::Matrix33d::Identity() * 100.0);\n\t{\n\t\tprojection <<\n\t\t\t1.0, 0.0, 0.0,\n\t\t\t0.0, 0.0, -1.0,\n\t\t\t0.0, 1.0, 0.0;\n\t\tm_projections.push_back(projection * 100.0);\n\t}\n\t{\n\t\tprojection <<\n\t\t\t0.0, 0.0, -1.0,\n\t\t\t0.0, 1.0, 0.0,\n\t\t\t1.0, 0.0, 0.0;\n\t\tm_projections.push_back(projection * 100.0);\n\t}\n\t{\n\t\tprojection <<\n\t\t\t0.0, -0.707107, -0.707107,\n\t\t\t0.0, 0.707107, -0.707107,\n\t\t\t1.0, 0.0, 0.0;\n\t\tm_projections.push_back(projection * 100.0);\n\t}\n\t{\n\t\tprojection <<\n\t\t\t-0.707107, 0.0, -0.707107,\n\t\t\t0.0, 1.0, -0.0,\n\t\t\t0.707107, -0.0, -0.707107;\n\t\tm_projections.push_back(projection * 100.0);\n\t}\n\t{\n\t\tprojection <<\n\t\t\t-1.0, 0.0, -0.0,\n\t\t\t0.0, 0.707107, -0.707107,\n\t\t\t0.0, -0.707107, -0.707107;\n\t\tm_projections.push_back(projection * 100.0);\n\t}\n\treturn true;\n}\n\nbool KnotIdentificationBehavior::doWakeUp()\n{\n\tif (m_fem1d == nullptr)\n\t{\n\t\tSURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getDefaultLogger()) << getClassName() << \" named '\" +\n\t\t\tgetName() + \"' must have a Fem1D Representation to detect knots in it.\";\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid KnotIdentificationBehavior::addKnownKnotCode(const std::string& name, const std::vector<int>& code,\n\tconst std::vector<int>& signs)\n{\n\tstd::vector<Crossing> enhancedGaussCode;\n\tauto codeLength = code.size();\n\tSURGSIM_ASSERT(codeLength == signs.size()) << \" \" <<  getClassName() << \"::\" << __func__ <<\n\t\t\" passed a vector of signs that is not the same length as the code.\";\n\tfor (size_t id = 0; id < codeLength; ++id)\n\t{\n\t\tenhancedGaussCode.push_back(Crossing(code[id], 0, 0.0, signs[id]));\n\t}\n\tif (m_knownLists.find(name) == m_knownLists.end())\n\t{\n\t\t\n\t\tauto v = std::vector<std::vector<Crossing>>();\n\t\tv.push_back(enhancedGaussCode);\n\t\tm_knownLists[name] = v;\n\t}\n\telse\n\t{\n\t\tm_knownLists[name].push_back(enhancedGaussCode);\n\t}\n}\n\nvoid KnotIdentificationBehavior::clearKnownKnotCodes()\n{\n\tm_knownLists.clear();\n}\n\nstd::string KnotIdentificationBehavior::detectAndIdentifyKnot(\n\tconst Math::Matrix33d& projection)\n{\n\tauto gaussCode = getGaussCode(projection);\n\n\t// Perform reidmeister moves.\n\tperformReidmeisterMoves(&gaussCode);\n\n\t// Identify the knot.\n\treturn identifyKnot(gaussCode);\n}\n\nstd::vector<KnotIdentificationBehavior::Crossing> KnotIdentificationBehavior::getGaussCode(\n\tconst Math::Matrix33d& projection)\n{\n\tstd::vector<Vector3d> nodes3d;\n\tstd::vector<Vector2d> nodes2d;\n\tstd::vector<Vector3d> segments3d;\n\n\tbuildNodeData(projection.col(0), projection.col(1), &nodes3d, &nodes2d, &segments3d);\n\n\tauto crossings = calculateCrossings(projection.col(2), nodes3d, nodes2d, segments3d);\n\n\tif (crossings.empty())\n\t{\n\t\treturn std::vector<Crossing>();\n\t}\n\n\tstd::sort(crossings.begin(), crossings.end(), [](const Crossing& i, const Crossing& j)\n\t{\n\t\treturn (i.segmentId == j.segmentId) ? (i.segmentLocation < j.segmentLocation) : (i.segmentId < j.segmentId);\n\t});\n\treturn crossings;\n}\n\nvoid KnotIdentificationBehavior::buildNodeData(\n\tconst Vector3d& projectionX,\n\tconst Vector3d& projectionY,\n\tstd::vector<Vector3d>* nodes3d,\n\tstd::vector<Vector2d>* nodes2d,\n\tstd::vector<Vector3d>* segments3d)\n{\n\t// Reserve the memory\n\tnodes3d->reserve(m_fem1d->getNumFemElements() + 2);\n\tnodes2d->reserve(m_fem1d->getNumFemElements() + 2);\n\tsegments3d->reserve(m_fem1d->getNumFemElements() + 1);\n\n\tconst auto& finalState = m_fem1d->getFinalState();\n\n\tVector3d node3d;\n\tVector2d node2d;\n\tfor (size_t i = 0; i < m_fem1d->getNumFemElements(); ++i)\n\t{\n\t\tif (i == 0)\n\t\t{\n\t\t\tnode3d = finalState->getPosition(m_fem1d->getFemElement(i)->getNodeIds()[0]);\n\t\t\tnode2d[0] = projectionX.dot(node3d);\n\t\t\tnode2d[1] = projectionY.dot(node3d);\n\t\t\tnodes3d->push_back(node3d);\n\t\t\tnodes2d->push_back(node2d);\n\t\t}\n\n\t\tnode3d = finalState->getPosition(m_fem1d->getFemElement(i)->getNodeIds()[1]);\n\t\tnode2d[0] = projectionX.dot(node3d);\n\t\tnode2d[1] = projectionY.dot(node3d);\n\n\t\tsegments3d->push_back(node3d - nodes3d->back());\n\n\t\tnodes3d->push_back(node3d);\n\t\tnodes2d->push_back(node2d);\n\t}\n\tconst auto& lastNode = \n\t\tfinalState->getPosition(m_fem1d->getFemElement(m_fem1d->getNumFemElements() - 1)->getNodeIds()[1]);\n\tnode3d = lastNode + 0.99 * (finalState->getPosition(m_fem1d->getFemElement(0)->getNodeIds()[0]) - lastNode);\n\tnode2d[0] = projectionX.dot(node3d);\n\tnode2d[1] = projectionY.dot(node3d);\n\tsegments3d->push_back(node3d - nodes3d->back());\n\tnodes3d->push_back(node3d);\n\tnodes2d->push_back(node2d);\n}\n\nstd::vector<KnotIdentificationBehavior::Crossing> KnotIdentificationBehavior::calculateCrossings(\n\tconst Math::Vector3d& projectionZ,\n\tconst std::vector<SurgSim::Math::Vector3d>& nodes3d,\n\tconst std::vector<SurgSim::Math::Vector2d>& nodes2d,\n\tconst std::vector<SurgSim::Math::Vector3d>& segments3d)\n{\n\tstd::vector<Crossing> crossings;\n\tint crossingId = 1;\n\tdouble s, t;\n\tsize_t numSegments = segments3d.size();\n\tfor (size_t i = 0; i < numSegments - 2; ++i)\n\t{\n\t\tfor (size_t j = i + 2; j < numSegments; ++j)\n\t\t{\n\t\t\tif (Math::doesIntersectSegmentSegment(nodes2d[i], nodes2d[i + 1], nodes2d[j], nodes2d[j + 1], &s, &t))\n\t\t\t{\n\t\t\t\tint sign =\n\t\t\t\t\t((nodes3d[i] + segments3d[i] * s) - (nodes3d[j] + segments3d[j] * t)).dot(projectionZ) > 0.0\n\t\t\t\t\t? 1 : -1;\n\t\t\t\tauto under = i;\n\t\t\t\tauto over = j;\n\t\t\t\tif (sign > 0)\n\t\t\t\t{\n\t\t\t\t\tunder = j;\n\t\t\t\t\tover = i;\n\t\t\t\t}\n\t\t\t\tSurgSim::Math::Vector2d segments2dUnder = nodes2d[under + 1] - nodes2d[under];\n\t\t\t\tSurgSim::Math::Vector2d segments2dOver = nodes2d[over + 1] - nodes2d[over];\n\t\t\t\tdouble dot = segments2dUnder.dot(segments2dOver);\n\t\t\t\tdouble determinant = segments2dUnder.x() * segments2dOver.y() -\n\t\t\t\t\tsegments2dUnder.y() * segments2dOver.x();\n\t\t\t\tint handedness = boost::math::sign(std::atan2(determinant, dot));\n\t\t\t\tcrossings.push_back(Crossing(crossingId * sign, i, s, handedness));\n\t\t\t\tcrossings.push_back(Crossing(crossingId * -sign, j, t, handedness));\n\t\t\t\tcrossingId++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn crossings;\n}\n\nvoid KnotIdentificationBehavior::performReidmeisterMoves(std::vector<Crossing>* gaussCode)\n{\n\tif (gaussCode->empty())\n\t{\n\t\treturn;\n\t}\n\n\t// Setup some variables for Reidmeister Move 3.\n\tReidmeisterMove3Data move3Data;\n\n\t// Perform Reidmeister moves.\n\tstd::vector<int> erased;\n\tbool reidmeisterMovePerformed = false;\n\tdo\n\t{\n\t\treidmeisterMovePerformed =\n\t\t\ttryReidmeisterMove1(gaussCode, &erased) ||\n\t\t\ttryReidmeisterMove2(gaussCode, &erased) ||\n\t\t\ttryReidmeisterMove3(gaussCode, &move3Data);\n\t} while (reidmeisterMovePerformed && !gaussCode->empty());\n\n\tadjustGaussCodeForErasedCrossings(gaussCode);\n}\n\nbool KnotIdentificationBehavior::tryReidmeisterMove1(std::vector<Crossing>* gaussCode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t std::vector<int>* erased)\n{\n\tbool movePerformed = false;\n\tsize_t i = 0;\n\tsize_t j;\n\twhile (i < gaussCode->size())\n\t{\n\t\tj = nextIndex(*gaussCode, i);\n\t\tif (isSameCross(*gaussCode, i, j))\n\t\t{\n\t\t\terased->push_back(std::abs((*gaussCode)[i].id));\n\t\t\terase(gaussCode, i, j);\n\t\t\tmovePerformed = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++i;\n\t\t}\n\t}\n\treturn movePerformed;\n}\n\nbool KnotIdentificationBehavior::tryReidmeisterMove2(std::vector<Crossing>* gaussCode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t std::vector<int>* erased)\n{\n\tsize_t i = 0;\n\tsize_t j;\n\tsize_t k;\n\tsize_t l;\n\twhile (i < gaussCode->size())\n\t{\n\t\tj = nextIndex(*gaussCode, i);\n\t\tif (isSameSign(*gaussCode, i, j))\n\t\t{\n\t\t\tk = nextIndex(*gaussCode, j);\n\t\t\tl = nextIndex(*gaussCode, k);\n\t\t\t// If the gaussCode is correctly formed, then it has to have more than 2 crossings by the time this gets\n\t\t\t// executed, so we don't need to check the case that k == i before l == i.\n\t\t\twhile (l != i)\n\t\t\t{\n\t\t\t\tif (doesOverlap(*gaussCode, i, j, k, l))\n\t\t\t\t{\n\t\t\t\t\terased->push_back(std::abs((*gaussCode)[i].id));\n\t\t\t\t\terased->push_back(std::abs((*gaussCode)[j].id));\n\t\t\t\t\terase(gaussCode, i, j, k, l);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tk = l;\n\t\t\t\tl = nextIndex(*gaussCode, k);\n\t\t\t}\n\t\t}\n\t\t++i;\n\t}\n\treturn false;\n}\n\nbool KnotIdentificationBehavior::tryReidmeisterMove3(std::vector<Crossing>* gaussCode, ReidmeisterMove3Data* data)\n{\n\tsize_t i = 0;\n\tsize_t j;\n\tsize_t k;\n\tsize_t l;\n\tsize_t m;\n\tsize_t n;\n\tif (data->code.empty() || data->code.size() > gaussCode->size())\n\t{\n\t\tdata->code = *gaussCode;\n\t\tdata->i = std::numeric_limits<size_t>::max();\n\t\tdata->iCount = 0;\n\t\tdata->m = std::numeric_limits<size_t>::max();\n\t\tdata->n = std::numeric_limits<size_t>::max();\n\t}\n\telse\n\t{\n\t\t*gaussCode = data->code;\n\t\ti = data->i;\n\t}\n\n\twhile (i < gaussCode->size())\n\t{\n\t\tj = nextIndex(*gaussCode, i);\n\t\tif (isSameSign(*gaussCode, i, j) && data->iCount < 2)\n\t\t{\n\t\t\tk = getComplementCross(*gaussCode, i);\n\t\t\tl = getComplementCross(*gaussCode, j);\n\t\t\tm = (i == data->i) ? data->m : std::numeric_limits<size_t>::max();\n\t\t\tn = (i == data->i) ? data->n : std::numeric_limits<size_t>::max();\n\t\t\tif (hasCommonNeighbor(*gaussCode, k, l, &m, &n))\n\t\t\t{\n\t\t\t\tdata->iCount = (i == data->i) ? (data->iCount + 1) : 1;\n\t\t\t\tdata->i = i;\n\t\t\t\tdata->m = m;\n\t\t\t\tdata->n = n;\n\t\t\t\tstd::swap(gaussCode->at(k), gaussCode->at(l));\n\t\t\t\tstd::swap(gaussCode->at(k), gaussCode->at(m));\n\t\t\t\tstd::swap(gaussCode->at(l), gaussCode->at(n));\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t++i;\n\t}\n\treturn false;\n}\n\nvoid KnotIdentificationBehavior::adjustGaussCodeForErasedCrossings(std::vector<Crossing>* gaussCode)\n{\n\tusing boost::math::sign;\n\tstd::map<int, int> oldToNew;\n\tint next = 1;\n\tfor (auto& code : *gaussCode)\n\t{\n\t\tconst auto id = std::abs(code.id);\n\t\tint newId;\n\t\tif (oldToNew.find(id) == oldToNew.end())\n\t\t{\n\t\t\tnewId = next;\n\t\t\t++next;\n\t\t\toldToNew[id] = newId;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnewId = oldToNew[id];\n\t\t}\n\t\tcode.id = sign(code.id) * newId;\n\t}\n}\n\nstd::string KnotIdentificationBehavior::identifyKnot(const std::vector<Crossing>& gaussCode)\n{\n\tif (gaussCode.empty())\n\t{\n\t\treturn \"No Knot\";\n\t}\n\n\tfor (const auto& knotVector : m_knownLists)\n\t{\n\t\tfor (const auto& knot : knotVector.second)\n\t\t{\n\t\t\tif (isSameCode(gaussCode, knot))\n\t\t\t{\n\t\t\t\treturn knotVector.first;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"Unknown Knot\";\n}\n\nsize_t KnotIdentificationBehavior::nextIndex(const std::vector<Crossing>& code, size_t i)\n{\n\treturn (++i) % code.size();\n}\n\nsize_t KnotIdentificationBehavior::prevIndex(const std::vector<Crossing>& code, size_t i)\n{\n\treturn (i + code.size() - 1) % code.size();\n}\n\nbool KnotIdentificationBehavior::isSameSign(const std::vector<Crossing>& code, size_t i, size_t j)\n{\n\tusing boost::math::sign;\n\treturn sign(code[i].id) == sign(code[j].id);\n}\n\nbool KnotIdentificationBehavior::isSameCross(const std::vector<Crossing>& code, size_t i, size_t j)\n{\n\treturn code[i].id == -code[j].id;\n}\n\nbool KnotIdentificationBehavior::doesOverlap(const std::vector<Crossing>& code, size_t i, size_t j, size_t k, size_t l)\n{\n\treturn isSameSign(code, i, j) && isSameSign(code, k, l) && !isSameSign(code, i, k) &&\n\t\t   ((isSameCross(code, i, k) && isSameCross(code, j, l)) ||\n\t\t\t(isSameCross(code, i, l) && isSameCross(code, j, k)));\n}\n\nvoid KnotIdentificationBehavior::erase(std::vector<Crossing>* code, size_t i, size_t j)\n{\n\tcode->erase(code->begin() + std::max(i, j));\n\tcode->erase(code->begin() + std::min(i, j));\n}\n\nvoid KnotIdentificationBehavior::erase(std::vector<Crossing>* code, size_t i, size_t j, size_t k, size_t l)\n{\n\tstd::vector<size_t> list = { i, j, k, l };\n\tstd::sort(list.begin(), list.end(), std::greater<size_t>());\n\tcode->erase(code->begin() + list[0]);\n\tcode->erase(code->begin() + list[1]);\n\tcode->erase(code->begin() + list[2]);\n\tcode->erase(code->begin() + list[3]);\n}\n\nsize_t KnotIdentificationBehavior::getComplementCross(const std::vector<Crossing>& code, size_t i)\n{\n\tfor (size_t j = 0; j < code.size(); ++j)\n\t{\n\t\tif (code[j].id == -code[i].id)\n\t\t{\n\t\t\treturn j;\n\t\t}\n\t}\n\tSURGSIM_FAILURE() << \"Cannot find the complement cross for \" << i;\n\treturn std::numeric_limits<size_t>::max();\n}\n\nbool KnotIdentificationBehavior::hasCommonNeighbor(const std::vector<Crossing>& code, size_t i, size_t j,\n\t\t\t\t\t\t\t\t\t\t\t\t   size_t* k, size_t* l)\n{\n\tsize_t iPrev = prevIndex(code, i);\n\tsize_t iNext = nextIndex(code, i);\n\tsize_t jPrev = prevIndex(code, j);\n\tsize_t jNext = nextIndex(code, j);\n\n\tif (isSameCross(code, iPrev, jPrev) && !(*k == iPrev && *l == jPrev))\n\t{\n\t\t*k = iPrev;\n\t\t*l = jPrev;\n\t\treturn true;\n\t}\n\tif (isSameCross(code, iPrev, jNext) && !(*k == iPrev && *l == jNext))\n\t{\n\t\t*k = iPrev;\n\t\t*l = jNext;\n\t\treturn true;\n\t}\n\tif (isSameCross(code, iNext, jPrev) && !(*k == iNext && *l == jPrev))\n\t{\n\t\t*k = iNext;\n\t\t*l = jPrev;\n\t\treturn true;\n\t}\n\tif (isSameCross(code, iNext, jNext) && !(*k == iNext && *l == jNext))\n\t{\n\t\t*k = iNext;\n\t\t*l = jNext;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool KnotIdentificationBehavior::isSameCode(const std::vector<Crossing>& code, const std::vector<Crossing>& knot)\n{\n\tif (code.size() != knot.size())\n\t{\n\t\treturn false;\n\t}\n\n\tbool isSame = true;\n\tfor (size_t i = 0; i < code.size() && isSame; ++i)\n\t{\n\t\tisSame = (code[i].id == knot[i].id) && (code[i].sign == knot[i].sign);\n\t}\n\n\tif (!isSame)\n\t{\n\t\t// Check if (code * -1) is the same as knot.\n\t\tisSame = true;\n\t\tfor (size_t i = 0; i < code.size() && isSame; ++i)\n\t\t{\n\t\t\tisSame = (-code[i].id == knot[i].id) && (code[i].sign == knot[i].sign);\n\t\t}\n\t}\n\n\treturn isSame;\n}\n\n} //namespace Blocks\n} //namespace SurgSim\n", "meta": {"hexsha": "bde2eca20affa15c7d25438500a956e8d95b17fb", "size": 17646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SurgSim/Blocks/KnotIdentificationBehavior.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/Blocks/KnotIdentificationBehavior.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/Blocks/KnotIdentificationBehavior.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": 27.9208860759, "max_line_length": 119, "alphanum_fraction": 0.6596395784, "num_tokens": 5920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.03410042939337387, "lm_q1q2_score": 0.016783826770403305}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_BACON_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_BACON_HPP\r\n\r\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\r\n// This file is automatically generated. DO NOT EDIT.\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 4.9.1\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#include <boost/geometry/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\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct apian {};\r\n    struct ortel {};\r\n    struct bacon {};\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 bacon\r\n    {\r\n\r\n            //static const double HLFPI2 = 2.46740110027233965467;\r\n            static const double EPS = 1e-10;\r\n\r\n            struct par_bacon\r\n            {\r\n                int bacn;\r\n                int ortl;\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_bacon_spheroid : public base_t_f<base_bacon_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>\r\n            {\r\n\r\n                typedef CalculationType geographic_type;\r\n                typedef CalculationType cartesian_type;\r\n\r\n                par_bacon m_proj_parm;\r\n\r\n                inline base_bacon_spheroid(const Parameters& par)\r\n                    : base_t_f<base_bacon_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\r\n                    static const CalculationType HLFPI2 = detail::HALFPI_SQR<CalculationType>();\r\n\r\n                    CalculationType ax, f;\r\n\r\n                    xy_y = this->m_proj_parm.bacn ? HALFPI * sin(lp_lat) : lp_lat;\r\n                    if ((ax = fabs(lp_lon)) >= EPS) {\r\n                        if (this->m_proj_parm.ortl && ax >= HALFPI)\r\n                            xy_x = sqrt(HLFPI2 - lp_lat * lp_lat + EPS) + ax - HALFPI;\r\n                        else {\r\n                            f = 0.5 * (HLFPI2 / ax + ax);\r\n                            xy_x = ax - f + sqrt(f * f - xy_y * xy_y);\r\n                        }\r\n                        if (lp_lon < 0.) xy_x = - xy_x;\r\n                    } else\r\n                        xy_x = 0.;\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"bacon_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Apian Globular I\r\n            template <typename Parameters>\r\n            inline void setup_apian(Parameters& par, par_bacon& proj_parm)\r\n            {\r\n                proj_parm.bacn = proj_parm.ortl = 0;\r\n                par.es = 0.;\r\n            }\r\n\r\n            // Ortelius Oval\r\n            template <typename Parameters>\r\n            inline void setup_ortel(Parameters& par, par_bacon& proj_parm)\r\n            {\r\n                proj_parm.bacn = 0;\r\n                proj_parm.ortl = 1;\r\n                par.es = 0.;\r\n            }\r\n\r\n            // Bacon Globular\r\n            template <typename Parameters>\r\n            inline void setup_bacon(Parameters& par, par_bacon& proj_parm)\r\n            {\r\n                proj_parm.bacn = 1;\r\n                proj_parm.ortl = 0;\r\n                par.es = 0.;\r\n            }\r\n\r\n    }} // namespace detail::bacon\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Apian Globular I projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Miscellaneous\r\n         - Spheroid\r\n         - no inverse\r\n        \\par Example\r\n        \\image html ex_apian.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct apian_spheroid : public detail::bacon::base_bacon_spheroid<CalculationType, Parameters>\r\n    {\r\n        inline apian_spheroid(const Parameters& par) : detail::bacon::base_bacon_spheroid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::bacon::setup_apian(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Ortelius Oval projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Miscellaneous\r\n         - Spheroid\r\n         - no inverse\r\n        \\par Example\r\n        \\image html ex_ortel.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct ortel_spheroid : public detail::bacon::base_bacon_spheroid<CalculationType, Parameters>\r\n    {\r\n        inline ortel_spheroid(const Parameters& par) : detail::bacon::base_bacon_spheroid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::bacon::setup_ortel(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Bacon Globular projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Miscellaneous\r\n         - Spheroid\r\n         - no inverse\r\n        \\par Example\r\n        \\image html ex_bacon.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct bacon_spheroid : public detail::bacon::base_bacon_spheroid<CalculationType, Parameters>\r\n    {\r\n        inline bacon_spheroid(const Parameters& par) : detail::bacon::base_bacon_spheroid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::bacon::setup_bacon(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::apian, apian_spheroid, apian_spheroid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::bacon, bacon_spheroid, bacon_spheroid)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::ortel, ortel_spheroid, ortel_spheroid)\r\n\r\n        // Factory entry(s)\r\n        template <typename CalculationType, typename Parameters>\r\n        class apian_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                    return new base_v_f<apian_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        class ortel_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                    return new base_v_f<ortel_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        class bacon_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                    return new base_v_f<bacon_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void bacon_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"apian\", new apian_entry<CalculationType, Parameters>);\r\n            factory.add_to_factory(\"ortel\", new ortel_entry<CalculationType, Parameters>);\r\n            factory.add_to_factory(\"bacon\", new bacon_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_BACON_HPP\r\n\r\n", "meta": {"hexsha": "c6fb886ef1b8776fd3df7ddcdb34c40e7837d657", "size": 10619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/bacon.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/bacon.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/bacon.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": 38.8974358974, "max_line_length": 132, "alphanum_fraction": 0.6150296638, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.04813677265285739, "lm_q1q2_score": 0.016782651616094844}}
{"text": "// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n\n#ifndef   CPPQEDELEMENTS_UTILS_AVERAGINGUTILS_TCC_INCLUDED\n#define   CPPQEDELEMENTS_UTILS_AVERAGINGUTILS_TCC_INCLUDED\n\n#include \"AveragingUtils.h\"\n\n#include \"DensityOperator.h\"\n#include \"LazyDensityOperator.h\"\n#include \"NegPT.tcc\"\n\n#include \"Algorithm.h\"\n#include \"MathExtensions.h\"\n#include \"MultiIndexIterator.h\"\n\n\n#include <boost/bind.hpp>\n\n#include <boost/range/adaptor/transformed.hpp>\n\n#include <algorithm>\n\n\ntemplate<int RANK>\nauto\nReducedDensityOperator<RANK>::helper(const Dimensions& dim, bool offDiagonals, const KeyLabels& subsequent) -> const KeyLabels\n{\n  typedef cpputils::MultiIndexIterator<RANK> Iterator;\n  using std::ostringstream;\n\n  KeyLabels res;\n  Iterator i(dim-1,cpputils::mii::begin);\n\n  // Diagonals\n  for (; i!=i.getEnd(); ++i) {\n    ostringstream ss;\n    ss<<\"rho_\"<<*i<<';'<<*i;\n    res.push_back(ss.str());\n  }\n\n  if (!offDiagonals) return res;\n\n  // Offdiagonals\n  for (i.setToBegin(); i!=i.getEnd(); ++i) \n    for (Iterator j(std::next(i)); j!=j.getEnd(); ++j) {\n      {\n        ostringstream ss;\n        ss<<\"real[\"<<\"rho_\"<<*i<<';'<<*j<<']';\n        res.push_back(ss.str());\n      }\n      {\n        ostringstream ss;\n        ss<<\"imag[\"<<\"rho_\"<<*i<<';'<<*j<<']';\n        res.push_back(ss.str());\n      }\n  }\n\n  res.insert(res.end(),subsequent.begin(),subsequent.end());\n\n  return res;\n\n}\n\n\ntemplate<int RANK>\nReducedDensityOperator<RANK>::ReducedDensityOperator(const std::string& label, const Dimensions& dim, bool offDiagonals, const KeyLabels& subsequent) :\n  DimensionsBookkeeper<RANK>(dim),\n  Base(label,helper(getDimensions(),offDiagonals,subsequent)),\n  offDiagonals_(offDiagonals)\n{\n}\n\n\ntemplate<int RANK>\nconst typename ReducedDensityOperator<RANK>::Averages \nReducedDensityOperator<RANK>::average_v(structure::NoTime, const LazyDensityOperator& matrix) const\n{\n  return deflate(matrix,offDiagonals_);\n}\n\n\ntemplate<int RANK, typename V>\nconst typename ReducedDensityOperatorNegativity<RANK,V>::Averages \nReducedDensityOperatorNegativity<RANK,V>::average_v(structure::NoTime t, const LazyDensityOperator& matrix) const\n{\n  Averages res(Base::average_v(t,matrix));\n  res.resize(res.size()+1);\n  return res;\n}\n\n\ntemplate<int RANK, typename V>\nvoid ReducedDensityOperatorNegativity<RANK,V>::process_v(Averages& averages) const\n{\n  quantumdata::DensityOperator<RANK> rho(getDimensions());\n  linalg::CMatrix matrix(rho.matrixView()); // references the same data\n  const size_t dim=getTotalDimension();\n  \n  {\n    int idx=0;  \n    for (int i=0; i<dim; ++i, ++idx) matrix(i,i)=averages(idx);\n    for (int i=0; i<dim; ++i) for (int j=i+1; j<dim; ++j, idx+=2) matrix(j,i)=conj(matrix(i,j)=dcomp(averages(idx),averages(idx+1)));\n  }\n  \n  averages(averages.size()-1)=\n#ifndef   DO_NOT_USE_FLENS\n    quantumdata::negPT(rho,V())\n#else  // DO_NOT_USE_FLENS\n    0\n#endif // DO_NOT_USE_FLENS\n    ;\n  \n}\n\n\ntemplate<int RANK, bool IS_TIME_DEPENDENT>\naveragingUtils::Collecting<RANK,IS_TIME_DEPENDENT>::Collecting(const Collection& collection)\n  : Base(collection.front().getTitle(),\n         cpputils::concatenateGrow<KeyLabels>( collection | boost::adaptors::transformed(bind(&Element::getLabels,_1)) )),\n    collection_(collection.clone())\n{}\n\n\ntemplate<int RANK, bool IS_TIME_DEPENDENT>\naveragingUtils::Collecting<RANK,IS_TIME_DEPENDENT>::Collecting(const Collecting& collecting)\n  : Base(collecting),\n    collection_(collecting.collection_.clone())\n{}\n\n\nnamespace averagingUtils { namespace details {\n\ndouble convert(structure::OneTime t) {return t ;}\ndouble convert(structure:: NoTime  ) {return 0.;}\n\n} } // averagingUtils::details\n\n\ntemplate<int RANK, bool IS_TIME_DEPENDENT>\nauto\naveragingUtils::Collecting<RANK,IS_TIME_DEPENDENT>::average_v(Time t, const LazyDensityOperator& matrix) const -> const Averages\n{\n  Averages res(this->nAvr()); res=0;\n  return cpputils::concatenate( collection_ | boost::adaptors::transformed(bind(&Element::average,_1,details::convert(t),boost::cref(matrix))) , res);\n\n}\n\n\ntemplate<int RANK, bool IS_TIME_DEPENDENT>\nvoid\naveragingUtils::Collecting<RANK,IS_TIME_DEPENDENT>::process_v(Averages& avr) const\n{\n  struct Helper\n  {\n    static void doIt(const Element& eav, Averages& avr, ptrdiff_t& l, ptrdiff_t& u)\n    {\n      using blitz::Range;\n      if ((u=l+eav.nAvr())>l) {\n        Averages temp(avr(Range(l+1,u)));\n        eav.process(temp);\n      }\n      std::swap(l,u);\n    }\n  };\n \n  ptrdiff_t l=-1, u=0;\n  for_each(collection_,boost::bind(Helper::doIt,_1,avr,l,u));\n}\n\n\ntemplate<int RANKFROM, int RANKTO, bool IS_TIME_DEPENDENT>\nauto\naveragingUtils::Transferring<RANKFROM,RANKTO,IS_TIME_DEPENDENT>::average_v(Time t, const LazyDensityOperator&) const -> const Averages\n{\n  return averaged_->average(details::convert(t),ldo_);\n}\n\n\n/* The earlier solution fails with the C++11 standard due to a \"bug\" in Boost.Assign, cf. https://svn.boost.org/trac/boost/ticket/7364\n\ntemplate<int RANK>\nstruct ReducedDensityOperator<RANK>::Helper\n{\n  typedef cpputils::MultiIndexIterator<RANK> Iterator;\n  \n  Helper(const Dimensions& dim) : i_(Dimensions(size_t(0)),dim-1,cpputils::mii::begin), j_(i_), real_(true), offDiagonals_(false) {++i_; ++j_;}\n  \n  Helper() : i_(Dimensions(size_t(0)),Dimensions(size_t(0)),cpputils::mii::begin), j_(i_), real_(true), offDiagonals_(false) {}\n\n  const std::string operator()()\n  {\n    using namespace std;\n    stringstream ss(stringstream::out);\n\n    // Diagonals\n    if (!offDiagonals_ && i_!=i_.getEnd()) {\n      ss<<\"rho_\"<<*i_<<';'<<*i_;\n      ++i_;\n    }\n    else if (!offDiagonals_ && i_==i_.getEnd()) {\n      offDiagonals_=true;\n      i_.setToBegin();\n    }\n    \n    // Offdiagonals\n    if (offDiagonals_) {\n      ss<<(real_ ? \"real[\" : \"imag[\")<<\"rho_\"<<*i_<<','<<*j_<<']';\n      if (real_)\n        real_=false;\n      else {\n        real_=true;\n        ++j_;\n        if (j_==j_.getEnd())\n          ++(j_=++i_);\n      }\n    }\n    \n    return ss.str();\n  }\n\nprivate:\n  Iterator i_, j_;\n  bool real_, offDiagonals_;\n  \n};\n\n\n\ntemplate<int RANK>\nReducedDensityOperator<RANK>::ReducedDensityOperator(const std::string& label, const Dimensions& dim, bool offDiagonals, const KeyLabels& subsequent) :\n  DimensionsBookkeeper<RANK,true>(dim),\n  Base(label,boost::assign::repeat_fun((offDiagonals ? mathutils::sqr(getTotalDimension()) : getTotalDimension())-1,\n                                       Helper(getDimensions())).range(subsequent)),\n  offDiagonals_(offDiagonals)\n{\n}\n\n*/\n\n#endif // CPPQEDELEMENTS_UTILS_AVERAGINGUTILS_TCC_INCLUDED\n", "meta": {"hexsha": "8bc79a1e00b92432bc4e00ec19bc92bdad877bfe", "size": 6565, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "CPPQEDelements/utils/AveragingUtils.tcc", "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/utils/AveragingUtils.tcc", "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/utils/AveragingUtils.tcc", "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": 27.2406639004, "max_line_length": 151, "alphanum_fraction": 0.6859101295, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.0373268831943749, "lm_q1q2_score": 0.0167744263750785}}
{"text": "/*\n * Software License Agreement (New BSD License)\n *\n * Copyright (c) 2013, Keith Leung, Felipe Inostroza\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Advanced Mining Technology Center (AMTC), the\n *       Universidad de Chile, nor the names of its contributors may be \n *       used to endorse or promote products derived from this software without \n *       specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AMTC, UNIVERSIDAD DE CHILE, OR THE COPYRIGHT \n * HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE \n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT \n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF \n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <boost/lexical_cast.hpp>\n#include <libconfig.h++>\n#include \"RBPHDFilter.hpp\"\n#include <stdio.h>\n\n/**\n * \\class Simulator2d\n * \\brief A 2d SLAM Simulator using the RB-PHD Filter\n * \\author Keith Leung\n */\nclass Simulator2d{\n\npublic:\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  Simulator2d(){\n    pFilter_ = NULL;\n  }\n  \n  ~Simulator2d(){\n    \n    if(pFilter_ != NULL){\n      delete pFilter_;\n    }\n\n  }\n\n  /** Read the simulator configuration file */\n  bool readConfigFile(){\n    \n    libconfig::Config cfg;\n    const char* fileName= \"cfg/simulator2d.cfg\";\n    try{\n      cfg.readFile( fileName );\n    }catch( libconfig::FileIOException &ex){\n      printf(\"\\nCannot read file: %s\\n\\n\", fileName);\n      return false;\n    }catch( libconfig::ParseException &ex){\n      const char* error = ex.getError();\n      int line = ex.getLine();\n      printf(\"\\n%s LINE %d\\n\\n\", error, line);\n      return false;\n    }\n    kMax_ = cfg.lookup(\"timesteps\");\n    dT_ = cfg.lookup(\"sec_per_timestep\");\n    \n    nSegments_ = cfg.lookup(\"Trajectory.nSegments\");\n    max_dx_ = cfg.lookup(\"Trajectory.max_dx_per_sec\");\n    max_dy_ = cfg.lookup(\"Trajectory.max_dy_per_sec\");\n    max_dz_ = cfg.lookup(\"Trajectory.max_dz_per_sec\");\n    min_dx_ = cfg.lookup(\"Trajectory.min_dx_per_sec\");\n    vardx_ = cfg.lookup(\"Trajectory.vardx\");\n    vardy_ = cfg.lookup(\"Trajectory.vardy\");\n    vardz_ = cfg.lookup(\"Trajectory.vardz\");\n\n    nLandmarks_ = cfg.lookup(\"Landmarks.nLandmarks\");\n    varlmx_ = cfg.lookup(\"Landmarks.varlmx\");\n    varlmy_ = cfg.lookup(\"Landmarks.varlmy\");\n\n    rangeLimitMax_ = cfg.lookup(\"Measurement.rangeLimitMax\");\n    rangeLimitMin_ = cfg.lookup(\"Measurement.rangeLimitMin\");\n    rangeLimitBuffer_ = cfg.lookup(\"Measurement.rangeLimitBuffer\");\n    Pd_ = cfg.lookup(\"Measurement.probDetection\");\n    c_ = cfg.lookup(\"Measurement.clutterIntensity\");\n    varzr_ = cfg.lookup(\"Measurement.varzr\");\n    varzb_ = cfg.lookup(\"Measurement.varzb\");\n\n    nParticles_ = cfg.lookup(\"Filter.nParticles\");\n    pNoiseInflation_ = cfg.lookup(\"Filter.processNoiseInflationFactor\");\n    zNoiseInflation_ = cfg.lookup(\"Filter.measurementNoiseInflationFactor\");\n    innovationRangeThreshold_ = cfg.lookup(\"Filter.innovationRangeThreshold\");\n    birthGaussianWeight_ = cfg.lookup(\"Filter.birthGaussianWeight\");\n    newGaussianCreateInnovMDThreshold_ = cfg.lookup(\"Filter.newGaussianCreateInnovMDThreshold\");\n    importanceWeightingMeasurementLikelihoodMDThreshold_ = cfg.lookup(\"Filter.importanceWeightingMeasurementLikelihoodMDThreshold\");\n    effNParticleThreshold_ = cfg.lookup(\"Filter.effectiveNumberOfParticlesThreshold\");\n    minInterSampleTimesteps_ = cfg.lookup(\"Filter.minInterSampleTimesteps\");\n    gaussianMergingThreshold_ = cfg.lookup(\"Filter.gaussianMergingThreshold\");\n    gaussianMergingCovarianceInflationFactor_ = cfg.lookup(\"Filter.gaussianMergingCovarianceInflationFactor\");\n    gaussianPruningThreshold_ = cfg.lookup(\"Filter.gaussianPruningThreshold\");\n    reportTimingInfo_ = cfg.lookup(\"Filter.reportTimingInfo\");\n    importanceWeightingEvalPointCount_ = cfg.lookup(\"Filter.importanceWeightingEvalPointCount\");\n    useClusterProcess_ = cfg.lookup(\"Filter.useClusterProcess\");\n\n    logToFile_ = cfg.lookup(\"Computation.logToFile\");\n    \n    return true;   \n  }\n\n  /** Generate a random trajectory in 2d space */\n  void generateTrajectory(int randSeed = 0){\n\n    printf(\"Generating trajectory with random seed = %d\\n\", randSeed);\n    srand48( randSeed);\n\n    int seg = 0;\n    OdometryMotionModel2d::TState::Mat Q;\n    Q << vardx_, 0, 0, 0, vardy_, 0, 0, 0, vardz_;\n    Q = dT_ * Q * dT_;\n    OdometryMotionModel2d motionModel(Q);\n    OdometryMotionModel2d::TInput input_k(0, 0, 0, 0, 0, 0, 0);\n    OdometryMotionModel2d::TState pose_k(0, 0, 0, 0, 0, 0, 0);\n    OdometryMotionModel2d::TState pose_km(0, 0, 0, 0, 0, 0, 0);\n    groundtruth_displacement_.reserve( kMax_ );\n    groundtruth_pose_.reserve( kMax_ );\n    groundtruth_displacement_.push_back(input_k);\n    groundtruth_pose_.push_back(pose_k);\n\n    for( int k = 1; k < kMax_; k++ ){\n\n      if( k <= 50 ){\n\tdouble dx = 0;\n\tdouble dy = 0;\n\tdouble dz = 0;\n\tinput_k = OdometryMotionModel2d::TInput(dx, dy, dz, \n\t\t\t\t\t\t0, 0, 0, k);\n      }else if( k >= kMax_ / nSegments_ * seg ){\n\tseg++;\n\tdouble dx = drand48() * max_dx_ * dT_;\n\twhile( dx < min_dx_ * dT_ ){\n\t  dx = drand48() * max_dx_ * dT_;\n\t}\n\tdouble dy = (drand48() * max_dy_ * 2 - max_dy_) * dT_;\n\tdouble dz = (drand48() * max_dz_ * 2 - max_dz_) * dT_; \n\tinput_k = OdometryMotionModel2d::TInput(dx, dy, dz, \n\t\t\t\t\t\tQ(0,0), Q(1,1), Q(2,2), k);  \n      }\n\n      groundtruth_displacement_.push_back(input_k);\n      groundtruth_displacement_.back().setTime(k);\n\n      OdometryMotionModel2d::TState x_k;\n      motionModel.step(x_k, groundtruth_pose_[k-1], input_k);\n      groundtruth_pose_.push_back( x_k );\n      groundtruth_pose_.back().setTime(k);\n\n    }\n\n  }\n  \n  /** Generate odometry measurements */\n  void generateOdometry(){\n\n    odometry_.reserve( kMax_ );\n    OdometryMotionModel2d::TInput zero;\n    OdometryMotionModel2d::TInput::Vec u0;\n    u0.setZero();\n    zero.set(u0, 0);\n    odometry_.push_back( zero );\n\n\n    OdometryMotionModel2d::TState::Mat Q;\n    Q << vardx_, 0, 0, 0, vardy_, 0, 0, 0, vardz_;\n    OdometryMotionModel2d motionModel(Q);\n    deadReckoning_pose_.reserve( kMax_ );\n    deadReckoning_pose_.push_back( groundtruth_pose_[0] );\n\n    for( int k = 1; k < kMax_; k++){\n      \n      OdometryMotionModel2d::TInput in = groundtruth_displacement_[k];\n      in.setCov(Q);\n      OdometryMotionModel2d::TInput out;\n      RandomVecMathTools<OdometryMotionModel2d::TInput>::sample(in, out);\n      \n      odometry_.push_back( out );\n\n      OdometryMotionModel2d::TState p;\n      motionModel.step(p, deadReckoning_pose_[k-1], odometry_[k]);\n      p.setTime(k);\n      deadReckoning_pose_.push_back( p );\n    }\n\n  }\n\n  /** Generate landmarks */\n  void generateLandmarks(){\n\n    RangeBearingModel measurementModel( varzr_, varzb_);\n    RangeBearingModel::TPose pose;\n\n    groundtruth_landmark_.reserve(nLandmarks_);\n\n    int nLandmarksCreated = 0;\n    for( int k = 1; k < kMax_; k++ ){\n\n      if( k >= kMax_ / nLandmarks_ * nLandmarksCreated){\n\n\tRangeBearingModel::TPose pose;\n\tRangeBearingModel::TMeasurement measurementToCreateLandmark;\n\tRangeBearingModel::TMeasurement::Vec z;\n\tdouble r = drand48() * rangeLimitMax_;\n\tdouble b = drand48() * 2 * PI;\n\tz << r, b;\n\tmeasurementToCreateLandmark.set(z);\n\tRangeBearingModel::TLandmark lm;\n\t\n\tmeasurementModel.inverseMeasure( groundtruth_pose_[k], \n\t\t\t\t\t measurementToCreateLandmark, \n\t\t\t\t\t lm);\n\n\tgroundtruth_landmark_.push_back(lm);\n\n\tnLandmarksCreated++;\n\t\n      }\n\n    }\n\n  }\n\n  /** Generate landmark measurements */\n  void generateMeasurements(){\n\n    RangeBearingModel measurementModel( varzr_, varzb_ );\n    RangeBearingModel::TMeasurement::Mat R;\n    measurementModel.getNoise(R);\n    measurementModel.config.rangeLimMax_ = rangeLimitMax_;\n    measurementModel.config.rangeLimMin_ = rangeLimitMin_;\n    measurementModel.config.probabilityOfDetection_ = Pd_;\n    measurementModel.config.uniformClutterIntensity_ = c_;\n    double meanClutter = measurementModel.clutterIntensityIntegral();\n    \n    double expNegMeanClutter = exp( -meanClutter );\n    double poissonPmf[100];\n    double poissonCmf[100];\n    double mean_pow_i = 1;\n    double i_factorial = 1;\n    poissonPmf[0] = expNegMeanClutter;\n    poissonCmf[0] = poissonPmf[0];\n    for( int i = 1; i < 100; i++){\n      mean_pow_i *= meanClutter;\n      i_factorial *= i;\n      poissonPmf[i] = mean_pow_i / i_factorial * expNegMeanClutter;\n      poissonCmf[i] = poissonCmf[i-1] + poissonPmf[i]; \n    }\n\n    for( int k = 1; k < kMax_; k++ ){\n      \n      groundtruth_pose_[k];\n      \n      // Real detections\n      for( int m = 0; m < groundtruth_landmark_.size(); m++){\n\t\n\tbool success;\n\tRangeBearingModel::TMeasurement z_m_k;\n\tsuccess = measurementModel.sample( groundtruth_pose_[k],\n\t\t\t\t\t   groundtruth_landmark_[m],\n\t\t\t\t\t   z_m_k);\n\tif(success){\n   \n\t  if(z_m_k.get(0) <= rangeLimitMax_ && z_m_k.get(0) >= rangeLimitMin_ && drand48() <= Pd_){\n\t    z_m_k.setTime(k);\n\t    z_m_k.setCov(R);\n\t    measurements_.push_back( z_m_k );\n\t  }\n\t}\n\n      }\n\n      // False alarms\n      double randomNum = drand48();\n      int nClutterToGen = 0;\n      while( randomNum > poissonCmf[ nClutterToGen ] ){\n\tnClutterToGen++;\n      }\n      for( int i = 0; i < nClutterToGen; i++ ){\n\t\n\tdouble r = drand48() * rangeLimitMax_;\n\twhile(r < rangeLimitMin_)\n\t  r = drand48() * rangeLimitMax_;\n\tdouble b = drand48() * 2 * PI - PI;\n\tRangeBearingModel::TMeasurement z_clutter;\n\tRangeBearingModel::TMeasurement::Vec z;\n\tz << r, b;\n\tz_clutter.set(z, k);\n\tmeasurements_.push_back(z_clutter);\n\t\n      }\n      \n    }\n    \n  }\n\n  /** Data Logging */\n  void exportSimData(){\n\n    double t;\n\n    FILE* pGTPoseFile;\n    pGTPoseFile = fopen(\"data/gtPose.dat\", \"w\");\n    OdometryMotionModel2d::TState::Vec x;\n    for(int i = 0; i < groundtruth_pose_.size(); i++){\n      groundtruth_pose_[i].get(x, t);\n      fprintf( pGTPoseFile, \"%f   %f   %f   %f\\n\", t, x(0), x(1), x(2));\n    }\n    fclose(pGTPoseFile);\n\n    FILE* pGTLandmarkFile;\n    pGTLandmarkFile = fopen(\"data/gtLandmark.dat\", \"w\");\n    RangeBearingModel::TLandmark::Vec m;\n    for(int i = 0; i < groundtruth_landmark_.size(); i++){\n      groundtruth_landmark_[i].get(m);\n      fprintf( pGTLandmarkFile, \"%f   %f\\n\", m(0), m(1));\n    }\n    fclose(pGTLandmarkFile);\n\n    FILE* pOdomFile;\n    pOdomFile = fopen(\"data/odometry.dat\",\"w\");\n    OdometryMotionModel2d::TInput::Vec u;\n    for(int i = 0; i < odometry_.size(); i++){\n      odometry_[i].get(u, t);\n      fprintf( pOdomFile, \"%f   %f   %f   %f\\n\", t, u(0), u(1), u(2));\n    }\n    fclose(pOdomFile);\n\n    FILE* pMeasurementFile;\n    pMeasurementFile = fopen(\"data/measurement.dat\", \"w\");\n    RangeBearingModel::TMeasurement::Vec z;\n    for(int i = 0; i < measurements_.size(); i++){\n      measurements_[i].get(z, t);\n      fprintf( pMeasurementFile, \"%f   %f   %f\\n\", t, z(0), z(1) );\n    }\n    fclose(pMeasurementFile);\n\n    FILE* pDeadReckoningFile;\n    pDeadReckoningFile = fopen(\"data/deadReckoning.dat\", \"w\");\n    OdometryMotionModel2d::TState::Vec odo;\n    for(int i = 0; i < deadReckoning_pose_.size(); i++){\n      deadReckoning_pose_[i].get(odo, t);\n      fprintf( pDeadReckoningFile, \"%f   %f   %f   %f\\n\", t, odo(0), odo(1), odo(2));\n    }\n    fclose(pDeadReckoningFile);\n\n  }\n\n  /** RB-PHD Filter Setup */\n  void setupRBPHDFilter(){\n    \n    pFilter_ = new RBPHDFilter<OdometryMotionModel2d,\n\t\t\t       StaticProcessModel<Landmark2d>,\n\t\t\t       RangeBearingModel,\n\t\t\t       RangeBearingKalmanFilter>( nParticles_ );\n\n    // configure robot motion model\n    OdometryMotionModel2d::TState::Mat Q;\n    Q << vardx_, 0, 0, 0, vardy_, 0, 0, 0, vardz_;\n    Q *= pNoiseInflation_;\n    pFilter_->getProcessModel()->setNoise(Q);\n\n    // configure landmark process model\n    Landmark2d::Mat Q_lm;\n    Q_lm << varlmx_, 0, 0, varlmy_;\n    pFilter_->getLmkProcessModel()->setNoise(Q_lm);\n\n    // configure measurement model\n    RangeBearingModel::TMeasurement::Mat R;\n    R << varzr_, 0, 0, varzb_;\n    R *= zNoiseInflation_;\n    pFilter_->getMeasurementModel()->setNoise(R);\n    pFilter_->getMeasurementModel()->config.probabilityOfDetection_ = Pd_;\n    pFilter_->getMeasurementModel()->config.uniformClutterIntensity_ = c_;\n    pFilter_->getMeasurementModel()->config.rangeLimMax_ = rangeLimitMax_;\n    pFilter_->getMeasurementModel()->config.rangeLimMin_ = rangeLimitMin_;\n    pFilter_->getMeasurementModel()->config.rangeLimBuffer_ = rangeLimitBuffer_;\n\n    // configure the Kalman filter for landmark updates\n    pFilter_->getKalmanFilter()->config.rangeInnovationThreshold_ = innovationRangeThreshold_;\n\n    // configure the filter\n    pFilter_->config.birthGaussianWeight_ = birthGaussianWeight_;\n    pFilter_->setEffectiveParticleCountThreshold(effNParticleThreshold_);\n    pFilter_->config.minInterSampleTimesteps_ = minInterSampleTimesteps_;\n    pFilter_->config.newGaussianCreateInnovMDThreshold_ = newGaussianCreateInnovMDThreshold_;\n    pFilter_->config.importanceWeightingMeasurementLikelihoodMDThreshold_ = importanceWeightingMeasurementLikelihoodMDThreshold_;\n    pFilter_->config.importanceWeightingEvalPointCount_ = importanceWeightingEvalPointCount_;\n    pFilter_->config.gaussianMergingThreshold_ = gaussianMergingThreshold_;\n    pFilter_->config.gaussianMergingCovarianceInflationFactor_ = gaussianMergingCovarianceInflationFactor_;\n    pFilter_->config.gaussianPruningThreshold_ = gaussianPruningThreshold_;\n    pFilter_->config.reportTimingInfo_ = reportTimingInfo_;\n    pFilter_->config.useClusterProcess_ = useClusterProcess_;\n  }\n\n  /** Run the simulator */\n  void run(){\n    \n    printf(\"Running simulation\\n\\n\");\n\n    //////// Initialization at first timestep //////////\n\n    FILE* pParticlePoseFile;\n    if(logToFile_){\n      pParticlePoseFile = fopen(\"data/particlePose.dat\", \"w\");\n      fprintf( pParticlePoseFile, \"Timesteps: %d\\n\", kMax_);\n      fprintf( pParticlePoseFile, \"nParticles: %d\\n\\n\", pFilter_->getParticleCount());\n    }\n    FILE* pLandmarkEstFile;\n    if(logToFile_){\n      pLandmarkEstFile = fopen(\"data/landmarkEst.dat\", \"w\");\n      fprintf( pLandmarkEstFile, \"Timesteps: %d\\n\", kMax_);\n      fprintf( pLandmarkEstFile, \"nParticles: %d\\n\\n\", pFilter_->getParticleCount());\n    }\n    OdometryMotionModel2d::TState x_i;\n    int zIdx = 0;\n\n    if(logToFile_){\n      fprintf( pParticlePoseFile, \"k = 0\\n\");\n      for(int i = 0; i < pFilter_->getParticleCount(); i++){\n\tpFilter_->getParticleSet()->at(i)->getPose(x_i);\n\tfprintf( pParticlePoseFile, \"%f   %f   %f   1.0\\n\", x_i.get(0), x_i.get(1), x_i.get(2));\n      }\n      for(int i = 0; i < pFilter_->getParticleCount(); i++){\n\tfprintf( pLandmarkEstFile, \"Timestep: %d\\tParticle: %d\\tMap Size: %d\\n\", 0, i, 0);\n      }      \n    }\n\n    boost::timer::auto_cpu_timer *stepTimer = NULL;\n    boost::timer::auto_cpu_timer *processTimer = new boost::timer::auto_cpu_timer(6, \"Total run time: %ws\\n\");\n\n    /////////// Run simulator from k = 1 to kMax_ /////////\n\n    for(int k = 1; k < kMax_; k++){\n\n      if(reportTimingInfo_){\n\tstepTimer = new boost::timer::auto_cpu_timer(6, \"Step time: %ws\\n\");\n      }\n      \n      if( k % 1 == 0)\n\tprintf(\"k = %d\\n\", k);\n      \n      if(logToFile_){\n\tfprintf( pParticlePoseFile, \"k = %d\\n\", k);\n      }\n      \n      ////////// Prediction Step //////////\n      pFilter_->predict( odometry_[k], k );\n      \n      if( k <= 100){\n\tfor( int i = 0; i < nParticles_; i++)\n\t  pFilter_->setParticlePose(0, groundtruth_pose_[k]);\n      }\n\n      // Prepare measurement vector for update\n      std::vector<RangeBearingModel::TMeasurement> Z;\n      double kz = measurements_[ zIdx ].getTime();\n      while( kz == k ){\n\tZ.push_back( measurements_[zIdx] );\n\tzIdx++;\n\tif(zIdx >= measurements_.size())\n\t  break;\n\tkz = measurements_[ zIdx ].getTime();\n      }\n\n      ////////// Update Step //////////\n      pFilter_->update(Z, k);\n\n      // Log particle poses\n      if(logToFile_){\n\tfor(int i = 0; i < pFilter_->getParticleCount(); i++){\n\t  pFilter_->getParticleSet()->at(i)->getPose(x_i);\n\t  double w = pFilter_->getParticleSet()->at(i)->getWeight();\n\t  fprintf( pParticlePoseFile, \"%f   %f   %f   %f\\n\", x_i.get(0), x_i.get(1), x_i.get(2), w);\n\t}\n\tfprintf( pParticlePoseFile, \"\\n\");\n      }\n\n      // Log landmark estimates\n      if(logToFile_){\n\tfor(int i = 0; i < pFilter_->getParticleCount(); i++){\n\t  int mapSize = pFilter_->getGMSize(i);\n\t  fprintf( pLandmarkEstFile, \"Timestep: %d\\tParticle: %d\\tMap Size: %d\\n\", k, i, mapSize);\n\t  for( int m = 0; m < mapSize; m++ ){\n\t    RangeBearingModel::TLandmark::Vec u;\n\t    RangeBearingModel::TLandmark::Mat S;\n\t    double w;\n\t    pFilter_->getLandmark(i, m, u, S, w);\n\t    \n\t    fprintf( pLandmarkEstFile, \"%f   %f      \", u(0), u(1));\n\t    fprintf( pLandmarkEstFile, \"%f   %f   \", S(0,0), S(0,1));\n\t    fprintf( pLandmarkEstFile, \"%f   %f   \", S(1,0), S(1,1));\n\t    fprintf( pLandmarkEstFile, \"   %f\\n\", w );\n\t  }\n\t  fprintf( pLandmarkEstFile, \"\\n\");\n\t}\n\tfprintf( pLandmarkEstFile, \"\\n\");\n      }\n\n      if(reportTimingInfo_){\n\tdelete stepTimer;\n\tstepTimer = NULL;\n      }\n\n    }\n\n    if(reportTimingInfo_){\n      delete processTimer;\n      processTimer = NULL;\n    }\n\n    if(logToFile_){\n      fclose(pParticlePoseFile);\n      fclose(pLandmarkEstFile);\n    }\n  }\n\nprivate:\n\n  int kMax_; /**< number of timesteps */\n  double dT_;\n\n  // Trajectory\n  int nSegments_;\n  double max_dx_;\n  double max_dy_;\n  double max_dz_;\n  double min_dx_;\n  double vardx_;\n  double vardy_;\n  double vardz_;\n  std::vector<OdometryMotionModel2d::TInput> groundtruth_displacement_;\n  std::vector<OdometryMotionModel2d::TState> groundtruth_pose_;\n  std::vector<OdometryMotionModel2d::TInput> odometry_;\n  std::vector<OdometryMotionModel2d::TState> deadReckoning_pose_;\n\n  // Landmarks \n  int nLandmarks_;\n  std::vector<RangeBearingModel::TLandmark> groundtruth_landmark_;\n  double varlmx_;\n  double varlmy_;\n\n  // Range-Bearing Measurements\n  double rangeLimitMax_;\n  double rangeLimitMin_;\n  double rangeLimitBuffer_;\n  double Pd_;\n  double c_;\n  double varzr_;\n  double varzb_;\n  std::vector<RangeBearingModel::TMeasurement> measurements_;\n\n  // Filters\n  RangeBearingKalmanFilter kf_;\n  RBPHDFilter<OdometryMotionModel2d, \n\t      StaticProcessModel<Landmark2d>,\n\t      RangeBearingModel,  \n\t      RangeBearingKalmanFilter> *pFilter_; \n  int nParticles_;\n  double pNoiseInflation_;\n  double zNoiseInflation_;\n  double innovationRangeThreshold_;\n  double birthGaussianWeight_;\n  double newGaussianCreateInnovMDThreshold_;\n  double importanceWeightingMeasurementLikelihoodMDThreshold_;\n  double effNParticleThreshold_;\n  int minInterSampleTimesteps_;\n  double gaussianMergingThreshold_;\n  double gaussianMergingCovarianceInflationFactor_;\n  double gaussianPruningThreshold_;\n  int importanceWeightingEvalPointCount_;\n  bool reportTimingInfo_;\n  bool useClusterProcess_;\n\n  bool logToFile_;\n};\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char* argv[]){\n\n  int initRandSeed = 0;\n  if( argc == 2 ){\n    initRandSeed = boost::lexical_cast<int>(argv[1]);\n  }\n\n  Simulator2d sim;\n  if( !sim.readConfigFile() ){\n    return -1;\n  }\n  sim.generateTrajectory( initRandSeed );\n  sim.generateOdometry();\n  sim.generateLandmarks();\n  sim.generateMeasurements();\n  sim.exportSimData();\n \n  sim.setupRBPHDFilter();\n\n  sim.run();\n\n  return 0;\n\n}\n", "meta": {"hexsha": "9704f862b9d8ed21a1b64998cfa4d5df273d63fc", "size": 20091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation2d.cpp", "max_stars_repo_name": "szma/RFS-SLAM", "max_stars_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T04:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T04:15:16.000Z", "max_issues_repo_path": "src/simulation2d.cpp", "max_issues_repo_name": "szma/RFS-SLAM", "max_issues_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation2d.cpp", "max_forks_repo_name": "szma/RFS-SLAM", "max_forks_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9411764706, "max_line_length": 132, "alphanum_fraction": 0.6766711463, "num_tokens": 5719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.034618840706684854, "lm_q1q2_score": 0.016768676979075508}}
{"text": "#include <memory>\n#include <chrono>\n#include <tuple>\n#include <unistd.h>\n#include <gflags/gflags.h>\n#include <string.h>\n#include <assert.h>\n#include <Eigen/StdVector>\n\n#include \"drake/solvers/snopt_solver.h\"\n#include \"drake/systems/analysis/simulator.h\"\n#include \"drake/systems/framework/diagram.h\"\n#include \"drake/systems/framework/diagram_builder.h\"\n#include \"drake/multibody/parsing/parser.h\"\n#include <drake/multibody/inverse_kinematics/inverse_kinematics.h>\n#include \"drake/geometry/geometry_visualization.h\"\n#include \"drake/solvers/solve.h\"\n\n#include \"common/find_resource.h\"\n#include \"systems/trajectory_optimization/dircon/dircon.h\"\n#include \"multibody/kinematic/world_point_evaluator.h\"\n#include \"solvers/nonlinear_constraint.h\"\n#include \"multibody/kinematic/distance_evaluator.h\"\n#include \"multibody/multibody_utils.h\"\n#include \"multibody/visualization_utils.h\"\n#include \"multibody/kinematic/kinematic_constraints.h\"\n#include \"solvers/nonlinear_cost.h\"\n#include \"examples/Spirit/spirit_utils.h\"\n\n\nusing drake::AutoDiffXd;\nusing drake::multibody::MultibodyPlant;\nusing drake::geometry::SceneGraph;\nusing drake::multibody::Parser;\nusing drake::trajectories::PiecewisePolynomial;\n\nusing Eigen::Vector3d;\nusing Eigen::VectorXd;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\n\nnamespace dairlib {\n\nusing systems::trajectory_optimization::DirconModeSequence;\nusing systems::trajectory_optimization::DirconMode;\nusing systems::trajectory_optimization::Dircon;\nusing systems::trajectory_optimization::KinematicConstraintType;\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\n/// Get a nominal Spirit Stand (i.e. zero hip ad/abduction motor torque, toes below motors) for initializing\ntemplate <typename T>\nvoid nominalSpiritStand( MultibodyPlant<T>& plant, Eigen::VectorXd& xState, double height){\n  //Get joint name dictionaries\n  auto positions_map = dairlib::multibody::makeNameToPositionsMap(plant);\n  auto velocities_map = dairlib::multibody::makeNameToVelocitiesMap(plant);\n  \n  // Initialize state vector and add orienation and goal height\n  xState = Eigen::VectorXd::Zero(plant.num_positions() + plant.num_velocities());\n  xState(positions_map.at(\"base_qw\")) = 1;\n  xState(positions_map.at(\"base_z\")) = height;\n  \n  //Calculate the inverse kinematics to get the joint angles for toe placement\n  double upperLegLength = 0.206; // length of the upper leg link\n  double hipLength = 0.10098; //absOffset ToeLocation\n  double hip2toeZLength = sqrt(height*height - hipLength*hipLength);// length of lower legs (2dof)\n  double theta1 = asin(hip2toeZLength/(2*upperLegLength )) ; //upper angle\n  double theta2 = 2*theta1 ; //lower angle\n  double alpha = asin(hipLength/(height)); //hip angle\n\n  int upperInd, kneeInd, hipInd;\n  int mirroredFlag;\n  for (int j = 0; j < 4; j++){\n    upperInd = j * 2;\n    kneeInd = j * 2 + 1;\n    hipInd = j + 8;\n    xState(positions_map.at(\"joint_\" + std::to_string(upperInd))) = theta1 ;\n    xState(positions_map.at(\"joint_\" + std::to_string(kneeInd))) = theta2 ;\n    mirroredFlag = -1;\n    if ( hipInd > 9 ){\n      mirroredFlag = 1;\n    }\n    xState(positions_map.at(\"joint_\" + std::to_string(hipInd))) = mirroredFlag * alpha;\n  }\n}\n\nvoid ikSpiritStand(drake::multibody::MultibodyPlant<double>& plant,\n                   Eigen::VectorXd& xState,\n                   Eigen::Matrix<bool,1,4> contactSequence,\n                   double com_height,\n                   double leg_height,\n                   double roll,\n                   double pitch,\n                   double eps){\n  drake::multibody::InverseKinematics ik(plant);\n  const auto& world_frame = plant.world_frame();\n  const auto& body_frame  = plant.GetFrameByName(\"body\");\n\n  // Position of the com\n  Vector3d pos = {0, 0, com_height};\n  // Orientation of body\n  drake::math::RotationMatrix<double> orientation;\n  orientation = drake::math::RotationMatrix<double>::MakeXRotation(-roll) *\n                drake::math::RotationMatrix<double>::MakeYRotation(-pitch) ;\n\n  const double n_x = plant.num_positions() + plant.num_velocities();\n  const double n_q = plant.num_positions();\n\n\n  // Constrain body location and pose\n  ik.AddPositionConstraint(body_frame, Vector3d(0, 0, 0), world_frame,\n                           pos,\n                           pos);\n  ik.AddOrientationConstraint(body_frame, orientation,\n                              world_frame, drake::math::RotationMatrix<double>(), 0);\n\n  // Constrain toes\n  for(int toe = 0; toe < 4; toe ++){\n    constrainToe(plant, ik, toe, contactSequence[toe], orientation, com_height, leg_height, eps);\n  }\n\n  // Add initial guess and solve\n  Eigen::VectorXd initial_guess;\n  dairlib::nominalSpiritStand(plant, initial_guess, com_height);\n  ik.get_mutable_prog()->SetInitialGuess(ik.q(), initial_guess.head(n_q));\n  const auto result = Solve(ik.prog());\n  const auto q_sol = result.GetSolution(ik.q());\n  std::cout << (result.is_success() ? \"IK Success\" : \"IK Fail\") << std::endl;\n\n  // Return\n  VectorXd x_const = VectorXd::Zero(n_x);\n  x_const.head(n_q) = q_sol;\n  xState = x_const;\n}\n\nvoid constrainToe(drake::multibody::MultibodyPlant<double> & plant,\n                  drake::multibody::InverseKinematics &ik,\n                  int toe, bool inContact, drake::math::RotationMatrix<double> orientation,\n                  double com_height, double leg_height, double eps){\n  // Get frames\n  const auto& toe_frame = dairlib::getSpiritToeFrame(plant, toe);\n  const auto& world_frame = plant.world_frame();\n  const auto& body_frame  = plant.GetFrameByName(\"body\");\n  Vector3d eps_vec = {eps, eps, eps};\n\n  // Chose distance between toe and com\n  const double hip_width = 0.07;\n  const double body_length = 0.2263;\n  Vector3d toe_offset;\n  switch (toe) {\n    case 0:\n      toe_offset = {body_length, hip_width, -abs(leg_height)};\n      break;\n    case 1:\n      toe_offset = {-body_length, hip_width, -abs(leg_height)};\n      break;\n    case 2:\n      toe_offset = {body_length, -hip_width, -abs(leg_height)};\n      break;\n    case 3:\n      toe_offset = {-body_length, -hip_width, -abs(leg_height)};\n      break;\n    default:\n      break;\n  }\n\n  if(inContact){\n    // Toe is in contact with ground\n\n    // Constrain toe to be under hip with distance constraint\n    toe_offset(2) = 0; // vector between body and hip in body frame\n    // Location hip in world frame\n    Vector3d hip_in_world = orientation.transpose() * toe_offset + Vector3d({0, 0, abs(com_height)});\n    // Vector between hip and toe in world frame\n    Vector3d  hip_to_toe_world = {0, 0, -hip_in_world(2)};\n    // Vector between body and toe in body frame\n    Vector3d body_to_toe_body = toe_offset + orientation * hip_to_toe_world;\n    //ik.AddPositionConstraint(body_frame, body_to_toe_body, toe_frame, -eps_vec, eps_vec);\n\n    // Toe is in contact with ground\n    ik.AddPositionConstraint(toe_frame, Vector3d(0, 0, 0), world_frame,\n                             toe_offset,\n                             toe_offset);\n\n  }\n  else{\n    // Toe is under hip in body frame\n    ik.AddPositionConstraint(body_frame, toe_offset, toe_frame,\n                             Vector3d(0, 0, 0),\n                             Vector3d(0, 0, 0));\n  }\n}\n\ntemplate <typename T>\nvoid nominalSpiritStandConstraint(\n    drake::multibody::MultibodyPlant<T>& plant,\n    dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,\n    double height,\n    std::vector<int> knotPoints,\n    double eps){\n  int nx = plant.num_positions() + plant.num_velocities();\n  VectorXd x_state(nx);\n  dairlib::nominalSpiritStand( plant, x_state,  height); //get desired x_state\n\n  auto positions_map = dairlib::multibody::makeNameToPositionsMap(plant);\n\n  for(int knot_index : knotPoints){\n    auto xi = trajopt.state(knot_index);\n    for(int joint = 0; joint< 12; joint ++){\n      std::string joint_string = \"joint_\"+std::to_string(joint);\n      double joint_val = x_state[positions_map.at(joint_string)];\n      trajopt.AddBoundingBoxConstraint(joint_val-eps, joint_val+eps, xi(positions_map.at(joint_string)));\n    }\n  }\n\n}\n\ntemplate <typename T>\nconst drake::multibody::Frame<T>& getSpiritToeFrame( MultibodyPlant<T>& plant, u_int8_t toeIndex ){\n  assert(toeIndex<4);\n  return plant.GetFrameByName( \"toe\" + std::to_string(toeIndex) );\n}\n\ntemplate <typename T>\nstd::unique_ptr<dairlib::multibody::WorldPointEvaluator<T>> getSpiritToeEvaluator( \n                      MultibodyPlant<T>& plant, \n                      const Eigen::Vector3d toePoint ,\n                      u_int8_t toeIndex,\n                      const Eigen::Vector3d normal ,\n                      const Eigen::Vector3d offset ,\n                      bool xy_active, \n                      double mu \n                      ){\n  assert(toeIndex<4); // Check that toeIndex is an actual Spirit leg\n  auto toe_eval =  std::make_unique<dairlib::multibody::WorldPointEvaluator<T>>(\n        plant, \n        toePoint, \n        getSpiritToeFrame(plant, toeIndex ) , \n        normal, \n        offset, \n        xy_active );\n  if(!std::isinf(mu)){\n    toe_eval->set_frictional(); toe_eval->set_mu(mu);\n  }\n  return toe_eval;\n}\n\ntemplate <typename T>\nstd::tuple<\n                std::vector<std::unique_ptr<DirconMode<T>>>,\n                std::vector<std::unique_ptr<dairlib::multibody::WorldPointEvaluator<T>>> ,\n                std::vector<std::unique_ptr<dairlib::multibody::KinematicEvaluatorSet<T>>>\n          > createSpiritModeSequence( \n          MultibodyPlant<T>& plant, // multibodyPlant\n          std::vector<Eigen::Matrix<bool,1,4>> modeSeqVect, // bool matrix describing toe contacts as true or false e.g. {{1,1,1,1},{0,0,0,0}} would be a full support mode and flight mode\n          std::vector<int> knotpointVect, // Matrix of knot points for each mode  \n          std::vector<Eigen::Vector3d> normals,\n          std::vector<Eigen::Vector3d> offsets, \n          std::vector<double> mus, \n          std::vector<double> minTs, \n          std::vector<double> maxTs ){\n\n  // std::cout<<modeSeqMat<<std::endl;\n  // std::cout<<knotpointVect<<std::endl;  \n\n  const double toeRadius = 0.02;\n  const Vector3d toeOffset(toeRadius,0,0); // vector to \"contact point\"\n  int num_modes = modeSeqVect.size();\n  assert( num_modes == knotpointVect.size() );\n  assert( num_modes == mus.size() );\n\n  std::vector<std::unique_ptr<dairlib::multibody::WorldPointEvaluator<T>>> toeEvals;\n  std::vector<std::unique_ptr<dairlib::multibody::KinematicEvaluatorSet<T>>> toeEvalSets;\n  std::vector<std::unique_ptr<DirconMode<T>>> modeVector;\n  // DirconModeSequence<T> sequence = DirconModeSequence<T>(plant);\n\n  for (int iMode = 0; iMode<num_modes; iMode++)\n  {\n    \n    toeEvalSets.push_back( std::move( std::make_unique<dairlib::multibody::KinematicEvaluatorSet<T>>(plant) ));\n    for ( int iLeg = 0; iLeg < 4; iLeg++ ){\n      if (modeSeqVect.at(iMode)(iLeg)){\n        toeEvals.push_back( std::move( getSpiritToeEvaluator(plant, toeOffset, iLeg, normals.at(iMode), offsets.at(iMode), true, mus.at(iMode) )) );\n        (toeEvalSets.back())->add_evaluator(  (toeEvals.back()).get()  ); //add evaluator to the set if active //Works ish\n      }\n    }\n    auto dumbToeEvalPtr = (toeEvalSets.back()).get() ;\n    int num_knotpoints = knotpointVect.at(iMode);\n    modeVector.push_back(std::move( std::make_unique<DirconMode<T>>( *dumbToeEvalPtr , num_knotpoints, minTs.at(iMode), maxTs.at(iMode) )));\n    // DirconMode<T> modeDum = DirconMode<T>( *dumbToeEvalPtr , num_knotpoints );\n    // sequence.AddMode(  &modeDum  ); // Add the evaluator set to the mode sequence\n    \n  }\n  \n  return {std::move(modeVector), std::move(toeEvals), std::move(toeEvalSets)};\n  // return {std::move(toeEvals), std::move(toeEvalSets)};\n}\n\n\ntemplate <typename T>\nstd::tuple<\n                std::vector<std::unique_ptr<DirconMode<T>>>,\n                std::vector<std::unique_ptr<dairlib::multibody::WorldPointEvaluator<T>>> ,\n                std::vector<std::unique_ptr<dairlib::multibody::KinematicEvaluatorSet<T>>>\n          > createSpiritModeSequence( \n          MultibodyPlant<T>& plant, // multibodyPlant\n          const dairlib::ModeSequenceHelper& msh ){\n\nreturn createSpiritModeSequence(plant, msh.modes , msh.knots , msh.normals , msh.offsets, msh.mus, msh.minTs, msh.maxTs);\n}\n\n\n\n\n// **********************************************************\n//   SETSPIRITJOINTLIMITS \n\n\ntemplate <typename T> \nvoid setSpiritJointLimits(drake::multibody::MultibodyPlant<T> & plant, \n                          dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,  \n                          int iJoint, \n                          double minVal, \n                          double maxVal  ){\n\n  auto positions_map = multibody::makeNameToPositionsMap(plant);\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  // std::cout<<\"joint_\" + std::to_string(iJoint)<<std::endl;\n  int N_knotpoints = trajopt.N();\n  for(int i = 0; i<N_knotpoints;i++){\n    auto xi = trajopt.state(i);\n    trajopt.AddBoundingBoxConstraint(minVal,maxVal,xi(positions_map.at(\"joint_\" + std::to_string(iJoint))));\n  }\n}\n\ntemplate <typename T> \nvoid setSpiritJointLimits(drake::multibody::MultibodyPlant<T> & plant,\n                          dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,\n                          std::vector<int> iJoints, \n                          std::vector<double> minVals, \n                          std::vector<double> maxVals  ){\n  int numJoints = iJoints.size();\n  assert(numJoints==minVals.size());\n  assert(numJoints==maxVals.size());\n  for (int i = 0; i<numJoints; i++){\n    setSpiritJointLimits( plant, \n                          trajopt,  \n                          iJoints[i], \n                          minVals[i], \n                          maxVals[i] );\n  }\n}\ntemplate <typename T> \nvoid setSpiritJointLimits(drake::multibody::MultibodyPlant<T> & plant,\n                          dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,\n                          std::vector<int> iJoints, \n                          double minVal, \n                          double maxVal  ){\n\n  for (int iJoint: iJoints){\n    setSpiritJointLimits( plant, \n                          trajopt,  \n                          iJoint, \n                          minVal, \n                          maxVal );\n  }\n}\ntemplate <typename T> \nvoid setSpiritJointLimits(drake::multibody::MultibodyPlant<T> & plant, \n                          dairlib::systems::trajectory_optimization::Dircon<T>& trajopt ){\n  // Upper doesn't need a joint limit for now, but we may eventually want to\n  // change this to help the optimizations\n  double minValUpper = -2 * M_PI ;\n  double maxValUpper =  2 * M_PI ;\n\n  // Lower limits are set to 0 and pi in the URDF might be better to include\n  // the few degrees that come with the body collision and to remove a few to stay\n  // away from singularity\n  double minValLower =  0;\n  double maxValLower =  M_PI-0.2;\n  \n  // The URDF defines symmetric limits if asymmetric constraints we need to\n  // add a mirror since the hips are positive in the same direction\n  double abKinLimit = 0.707 ; //From the URDF\n  double minValAbduc = -abKinLimit ;\n  double maxValAbduc =  abKinLimit ;\n  \n  // Upper 0,2,4,6\n  std::vector<int> indicesUpper = {0,2,4,6};\n  // Lower 1,3,5,7\n  std::vector<int> indicesLower = {1,3,5,7};\n  // Hips  8,9,10,11\n  std::vector<int> indicesAbduc = {8,9,10,11};\n\n//See above: Upper doesn't need joint limit since there isnt a meaningful set\nsetSpiritJointLimits( plant, \n                     trajopt,  \n                     indicesUpper, \n                     minValUpper, \n                     maxValUpper  );\n                     \nsetSpiritJointLimits( plant, \n                     trajopt,  \n                     indicesLower, \n                     minValLower , \n                     maxValLower );\n                     \nsetSpiritJointLimits( plant, \n                     trajopt,  \n                     indicesAbduc, \n                     minValAbduc, \n                     maxValAbduc  );\n\n}\n//   \\SETSPIRITJOINTLIMITS \n\n\n// **********************************************************\n//   SETSPIRITACTUATIONLIMITS\ntemplate <typename T>  \nvoid setSpiritActuationLimits(drake::multibody::MultibodyPlant<T> & plant, \n                          dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,\n                          double actuatorLimit){\n  auto actuators_map = multibody::makeNameToActuatorsMap(plant);\n\n  // Upper 0,2,4,6\n  std::vector<int> indicesUpper = {0,2,4,6};\n  // Lower 1,3,5,7\n  std::vector<int> indicesLower = {1,3,5,7};\n  // Hips  8,9,10,11\n  std::vector<int> indicesAbduc = {8,9,10,11};\n\n  double mechanicalReductionKnee = 1.5;\n  \n  \n  int N_knotpoints = trajopt.N();\n  for(int iKnot = 0; iKnot<N_knotpoints;iKnot++){\n    auto ui = trajopt.input(iKnot);\n    for (int iMotor : indicesUpper){\n      trajopt.AddBoundingBoxConstraint(\n        -actuatorLimit,\n         actuatorLimit,\n         ui(actuators_map.at(\"motor_\" + std::to_string(iMotor))));\n    }\n    for (int iMotor : indicesLower){\n      trajopt.AddBoundingBoxConstraint(\n        -actuatorLimit*mechanicalReductionKnee,\n         actuatorLimit*mechanicalReductionKnee,\n         ui(actuators_map.at(\"motor_\" + std::to_string(iMotor))));\n    }\n    for (int iMotor : indicesAbduc){\n      trajopt.AddBoundingBoxConstraint(\n        -actuatorLimit,\n         actuatorLimit,\n         ui(actuators_map.at(\"motor_\" + std::to_string(iMotor))));\n    }\n  }\n\n}\n//   \\SETSPIRITACTUATIONLIMITS\n\n\n// **********************************************************\n//   SETSPIRITSYMMETRY\n\ntemplate <typename T>\nvoid makeSaggitalSymmetric(\n        drake::multibody::MultibodyPlant<T> & plant, \n        dairlib::systems::trajectory_optimization::Dircon<T>& trajopt){\n\n  // Get position and velocity dictionaries \n  auto positions_map = multibody::makeNameToPositionsMap(plant);\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  int num_knotpoints = trajopt.N();\n  /// Symmetry constraints\n  for (int i = 0; i < num_knotpoints; i++){\n    \n    auto xi = trajopt.state(i);  \n    // Symmetry constraints (mirrored hips all else equal across)\n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_8\") ) == -xi( positions_map.at(\"joint_10\") ) );\n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_9\") ) == -xi( positions_map.at(\"joint_11\") ) );\n    // // Front legs equal and back legs equal constraints \n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_0\") ) ==  xi( positions_map.at(\"joint_4\") ) );\n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_1\") ) ==  xi( positions_map.at(\"joint_5\") ) );\n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_2\") ) ==  xi( positions_map.at(\"joint_6\") ) );\n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_3\") ) ==  xi( positions_map.at(\"joint_7\") ) );\n  }\n}\ntemplate <typename T>\nvoid setSpiritSymmetry(\n        drake::multibody::MultibodyPlant<T> & plant, \n        dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,\n        std::vector<std::string> symmetries){\n  \n  bool hasSaggital = false;\n  bool hasForeAft  = false;\n  hasSaggital = std::any_of(symmetries.begin(), symmetries.end(), [](const std::string & str) {\n                                                        return str == \"sagittal\";\n                                                    });\n                                                    \n  hasForeAft = std::any_of(symmetries.begin(), symmetries.end(), [](const std::string & str) {\n                                                        return str == \"foreaft\";\n                                                    });\n  if (hasSaggital&&hasForeAft){\n    // Avoids having overconstrained system of symmetry\n    std::cerr << \"Warning: Simultaneous Saggital and ForeAft not implemented yet. Only adding saggital constraints.\" << std::endl;\n    makeSaggitalSymmetric(plant,trajopt);\n  }else if (hasSaggital){\n    makeSaggitalSymmetric(plant,trajopt);\n  }else if (hasForeAft){\n    std::cerr << \"Warning: ForeAft not implemented yet. No constraints added\" << std::endl;\n  }else{\n    std::cerr << \"Warning: Failed to add symmetric constraint. Check spelling or implemenation. No constraints added\" << std::endl;\n  }\n\n}\n\ntemplate <typename T>\nvoid setSpiritSymmetry(drake::multibody::MultibodyPlant<T> & plant, \n                       dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,\n                       std::string symmetry,\n                       bool ignoreWarning){\n\n  static bool hasRun = false;\n  if(hasRun && !ignoreWarning){\n    std::cerr << \"Warning: Running different symmetries seperately could cause system to be overconstrained. Use vector overload to avoid this or set ignoreWarning flag if not a problem.\" \n              << std::endl;\n  }else{\n    hasRun = true;\n  }\n\n  std::vector<std::string> symmetries;\n  symmetries.push_back(symmetry);\n  setSpiritSymmetry(\n                    plant,\n                    trajopt,\n                    symmetries);\n}\n//   \\SETSPIRITSYMMETRY\n\n\ntemplate <typename T>\ndouble calcWork(\n    drake::multibody::MultibodyPlant<T> & plant,\n    drake::trajectories::PiecewisePolynomial<double>& x_traj,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj){\n\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  auto actuator_map = multibody::makeNameToActuatorsMap(plant);\n  int n_q = plant.num_positions();\n\n  double work = 0;\n  std::vector<double> knot_points = x_traj.get_segment_times();\n\n  for(int knot_index = 0; knot_index < knot_points.size()-1; knot_index++){\n      auto u_low = u_traj.value(knot_points[knot_index]);\n      auto u_up  = u_traj.value(knot_points[knot_index + 1]);\n      auto x_low = x_traj.value(knot_points[knot_index]);\n      auto x_up  = x_traj.value(knot_points[knot_index + 1]);\n\n    for (int joint = 0; joint < 12; joint++){\n\n      double actuation_low = u_low(actuator_map.at(\"motor_\" + std::to_string(joint)));\n      double actuation_up  =  u_up(actuator_map.at(\"motor_\" + std::to_string(joint)));\n\n      double velocity_low = x_low(n_q + velocities_map.at(\"joint_\" + std::to_string(joint) +\"dot\"));\n      double velocity_up  =  x_up(n_q + velocities_map.at(\"joint_\" + std::to_string(joint) +\"dot\"));\n\n      double pow_low = abs(actuation_low*velocity_low);\n      double pow_up  = abs(actuation_up*velocity_up);\n\n      // trapazoidal integration\n      work += (knot_points[knot_index + 1] - knot_points[knot_index])/2.0 * (pow_low + pow_up);\n    }\n  }\n  return work;\n}\n\ntemplate <typename T>\ndouble calcMechanicalWork(\n    drake::multibody::MultibodyPlant<T> & plant,\n    std::vector<drake::trajectories::PiecewisePolynomial<double>>& x_trajs,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj){\n\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  auto actuator_map = multibody::makeNameToActuatorsMap(plant);\n  int n_q = plant.num_positions();\n\n  double work = 0;\n  for(const auto& x_traj : x_trajs) {\n    std::vector<double> knot_points = x_traj.get_segment_times();\n    for (int knot_index = 0; knot_index < knot_points.size() - 1; knot_index++) {\n      auto u_low = u_traj.value(knot_points[knot_index]);\n      auto u_up = u_traj.value(knot_points[knot_index + 1]);\n      auto x_low = x_traj.value(knot_points[knot_index]);\n      auto x_up = x_traj.value(knot_points[knot_index + 1]);\n\n      for (int joint = 0; joint < 12; joint++) {\n\n        double actuation_low = u_low(actuator_map.at(\"motor_\" + std::to_string(joint)));\n        double actuation_up = u_up(actuator_map.at(\"motor_\" + std::to_string(joint)));\n\n        double velocity_low = x_low(n_q + velocities_map.at(\"joint_\" + std::to_string(joint) + \"dot\"));\n        double velocity_up = x_up(n_q + velocities_map.at(\"joint_\" + std::to_string(joint) + \"dot\"));\n\n        double pow_low = abs(actuation_low * velocity_low);\n        double pow_up = abs(actuation_up * velocity_up);\n\n        // trapazoidal integration\n        work += (knot_points[knot_index + 1] - knot_points[knot_index]) / 2.0 * (pow_low + pow_up);\n      }\n    }\n  }\n  return work;\n}\n\n\ntemplate <typename T>\ndouble calcElectricalWork(\n    drake::multibody::MultibodyPlant<T> & plant,\n    std::vector<drake::trajectories::PiecewisePolynomial<double>>& x_trajs,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj,\n    double efficiency){\n\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  auto actuator_map = multibody::makeNameToActuatorsMap(plant);\n  int n_q = plant.num_positions();\n\n  double work = 0;\n  double Q;\n  for(const auto& x_traj : x_trajs) {\n    std::vector<double> knot_points = x_traj.get_segment_times();\n    for (int knot_index = 0; knot_index < knot_points.size() - 1; knot_index++) {\n      auto u_low = u_traj.value(knot_points[knot_index]);\n      auto u_up = u_traj.value(knot_points[knot_index + 1]);\n      auto x_low = x_traj.value(knot_points[knot_index]);\n      auto x_up = x_traj.value(knot_points[knot_index + 1]);\n\n      for (int joint = 0; joint < 12; joint++) {\n        if(joint == 1 or joint == 3 or joint == 5 or joint == 7){\n          Q = Q_knee;\n        }\n        else{\n          Q = Q_not_knee;\n        }\n\n        double actuation_low = u_low(actuator_map.at(\"motor_\" + std::to_string(joint)));\n        double actuation_up = u_up(actuator_map.at(\"motor_\" + std::to_string(joint)));\n\n        double velocity_low = x_low(n_q + velocities_map.at(\"joint_\" + std::to_string(joint) + \"dot\"));\n        double velocity_up = x_up(n_q + velocities_map.at(\"joint_\" + std::to_string(joint) + \"dot\"));\n\n        double pow_low = actuation_low * velocity_low + Q * actuation_low * actuation_low;\n        double pow_up = actuation_up * velocity_up+ Q * actuation_up * actuation_up;\n\n        double battery_pow_low = positivePart(pow_low) + efficiency * negativePart(pow_low);\n        double battery_pow_up = positivePart(pow_up) + efficiency * negativePart(pow_up);\n\n        // trapazoidal integration\n        work += (knot_points[knot_index + 1] - knot_points[knot_index]) / 2.0 * (battery_pow_low + battery_pow_up);\n      }\n    }\n  }\n  return work;\n}\n\ntemplate <typename T>\ndouble calcVelocityInt(\n    drake::multibody::MultibodyPlant<T> & plant,\n    drake::trajectories::PiecewisePolynomial<double>& x_traj){\n\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  int n_v = plant.num_velocities();\n\n  double vel_int = 0;\n  std::vector<double> knot_points = x_traj.get_segment_times();\n\n  for(int knot_index = 0; knot_index < knot_points.size()-1; knot_index++){\n    Eigen::VectorXd x_low = x_traj.value(knot_points[knot_index]);\n    Eigen::VectorXd x_up  = x_traj.value(knot_points[knot_index + 1]);\n\n    Eigen::VectorXd velocity_low = x_low.tail(n_v);\n    Eigen::VectorXd velocity_up  =  x_up.tail(n_v);\n\n    double vel_sq_low = velocity_low.transpose() * velocity_low;\n    double vel_sq_up  = velocity_up.transpose()  * velocity_up;\n\n    // trapazoidal integration\n    vel_int += (knot_points[knot_index + 1] - knot_points[knot_index])/2.0 * (vel_sq_low  + vel_sq_up);\n  }\n\n  return vel_int;\n}\n\n\ntemplate <typename T>\ndouble calcVelocityInt(\n    drake::multibody::MultibodyPlant<T> & plant,\n    std::vector<drake::trajectories::PiecewisePolynomial<double>>& x_trajs){\n\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  int n_v = plant.num_velocities();\n\n  double vel_int = 0;\n\n  for(const auto& x_traj : x_trajs){\n    std::vector<double> knot_points = x_traj.get_segment_times();\n\n    for(int knot_index = 0; knot_index < knot_points.size()-1; knot_index++){\n      Eigen::VectorXd x_low = x_traj.value(knot_points[knot_index]);\n      Eigen::VectorXd x_up  = x_traj.value(knot_points[knot_index + 1]);\n\n      Eigen::VectorXd velocity_low = x_low.tail(n_v);\n      Eigen::VectorXd velocity_up  =  x_up.tail(n_v);\n\n      double vel_sq_low = velocity_low.transpose() * velocity_low;\n      double vel_sq_up  = velocity_up.transpose()  * velocity_up;\n\n      // trapazoidal integration\n      vel_int += (knot_points[knot_index + 1] - knot_points[knot_index])/2.0 * (vel_sq_low  + vel_sq_up);\n    }\n\n  }\n  return vel_int;\n}\n\ntemplate <typename T>\ndouble calcTorqueInt(\n    drake::multibody::MultibodyPlant<T> & plant,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj){\n\n  auto actuator_map = multibody::makeNameToActuatorsMap(plant);\n\n  double act_int = 0;\n  std::vector<double> knot_points = u_traj.get_segment_times();\n\n  for(int knot_index = 0; knot_index < knot_points.size()-1; knot_index++){\n    Eigen::VectorXd u_low = u_traj.value(knot_points[knot_index]);\n    Eigen::VectorXd u_up  = u_traj.value(knot_points[knot_index + 1]);\n\n    double act_sq_low = u_low.transpose() * u_low;\n    double act_sq_up  = u_up.transpose() * u_up;\n\n    // trapazoidal integration\n    act_int += (knot_points[knot_index + 1] - knot_points[knot_index])/2.0 * (act_sq_low + act_sq_up);\n  }\n  return act_int;\n}\n\ntemplate <typename T>\nstd::vector<drake::solvers::Binding<drake::solvers::Cost>> AddWorkCost(drake::multibody::MultibodyPlant<T> & plant,\n                 dairlib::systems::trajectory_optimization::Dircon<T>& trajopt,\n                 double cost_work_gain){\n  std::vector<drake::solvers::Binding<drake::solvers::Cost>> cost_joint_work_bindings;\n  int n_q = plant.num_positions();\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  auto actuator_map = multibody::makeNameToActuatorsMap(plant);\n\n  double Q = 0;\n  // Loop through each joint\n  for (int joint = 0; joint < 12; joint++) {\n    if(joint == 1 or joint == 3 or joint == 5 or joint == 7)\n      Q = Q_knee;\n    else\n      Q = Q_not_knee;\n    auto joint_work_cost = std::make_shared<JointWorkCost>(plant,  Q, cost_work_gain,4);\n    int act_int = actuator_map.at(\"motor_\" + std::to_string(joint));\n    int vel_int = n_q + velocities_map.at(\"joint_\" + std::to_string(joint) +\"dot\");\n    // Loop through each mode\n    for (int mode_index = 0; mode_index < trajopt.num_modes(); mode_index++) {\n      for (int knot_index = 0; knot_index < trajopt.mode_length(mode_index)-1; knot_index++) {\n        auto u_i = trajopt.input(trajopt.get_mode_start(mode_index) + knot_index)(act_int);\n        auto x_i   = trajopt.state_vars(mode_index, knot_index)(vel_int);\n        auto u_ip = trajopt.input(trajopt.get_mode_start(mode_index) + knot_index+1)(act_int);\n        auto x_ip   = trajopt.state_vars(mode_index, knot_index+1)(vel_int);\n\n        auto hi = trajopt.timestep(trajopt.get_mode_start(mode_index) + knot_index);\n        drake::solvers::VectorXDecisionVariable variables(5);\n        variables(0) = hi[0];\n        variables(1) = u_i;\n        variables(2) = u_ip;\n        variables(3) = x_i;\n        variables(4) = x_ip;\n        cost_joint_work_bindings.push_back(trajopt.AddCost(joint_work_cost, variables));\n      } // knot point loop\n    } // Mode loop\n  } // Joint loop\n  return cost_joint_work_bindings;\n}\n\nJointWorkCost::JointWorkCost(const drake::multibody::MultibodyPlant<double>& plant,\n                             const double &Q,\n                             const double &cost_work,\n                             const double &alpha,\n                             const std::string &description)\n    :solvers::NonlinearCost<double>(5,description), plant_(plant){\n  Q_ = Q;\n  cost_work_ = cost_work;\n  alpha_ = alpha;\n  n_q_ = plant_.num_positions();\n  n_v_ = plant_.num_velocities();\n  n_u_ = plant_.num_actuators();\n  DRAKE_DEMAND(alpha_ > 0);\n}\n\ndouble JointWorkCost::relu_smooth(const double x) const{\n  return  x>5 ? x : 1/alpha_ * log(1 + exp(alpha_ * x));\n}\n\nvoid JointWorkCost::EvaluateCost(const Eigen::Ref<const drake::VectorX<double>> &x,\n                  drake::VectorX<double> *y) const{\n\n\n\ndouble h_i = x(0);\n//auto u_i_all = x.segment(1, n_u_);\n//auto u_ip_all = x.segment(1+n_u_, n_u_);\n//auto x_i_all = x.segment(1+n_u_+n_u_, n_q_+n_v_);\n//auto x_ip_all = x.segment(1+n_u_+n_u_+n_q_+n_v_, n_q_+n_v_);\n\ndouble u_i = x(1);\ndouble u_ip = x(2);\ndouble v_i = x(3);\ndouble v_ip = x(4);\ndouble work_low = cost_work_ * relu_smooth(u_i * v_i + Q_ * u_i * u_i);\ndouble work_up = cost_work_ * relu_smooth(u_ip * v_ip + Q_ * u_ip * u_ip);\n\ndrake::VectorX<double> rv(1);\nrv[0] = 1/2.0 * h_i *(work_low + work_up);\n(*y) = rv;\n};\n\ndouble positivePart(double x){\n  return(std::max(x,0.0));\n}\n\ndouble negativePart(double x){\n  return(std::min(x,0.0));\n}\n\ntemplate void nominalSpiritStand(\n    drake::multibody::MultibodyPlant<double>& plant, \n    Eigen::VectorXd& xState, \n    double height); // NOLINT \n\ntemplate void nominalSpiritStandConstraint(\n    drake::multibody::MultibodyPlant<double>& plant,\n    dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,\n    double height,\n    std::vector<int> knotPoints,\n    const double eps); // NOLINT\n\ntemplate const drake::multibody::Frame<double>& getSpiritToeFrame( \n    drake::multibody::MultibodyPlant<double>& plant, \n    u_int8_t toeIndex ); // NOLINT \n\ntemplate std::unique_ptr<multibody::WorldPointEvaluator<double>> getSpiritToeEvaluator( \n                      MultibodyPlant<double>& plant, \n                      const Eigen::Vector3d toePoint ,\n                      u_int8_t toeIndex,\n                      const Eigen::Vector3d normal ,\n                      const Eigen::Vector3d offset ,\n                      bool xy_active, \n                      double mu \n                      ); // NOLINT\n                      \ntemplate std::tuple<  std::vector<std::unique_ptr<dairlib::systems::trajectory_optimization::DirconMode<double>>>,\n             std::vector<std::unique_ptr<multibody::WorldPointEvaluator<double>>> ,\n             std::vector<std::unique_ptr<multibody::KinematicEvaluatorSet<double>>>   \n          >     \n    createSpiritModeSequence( \n          drake::multibody::MultibodyPlant<double>& plant, // multibodyPlant\n          std::vector<Eigen::Matrix<bool,1,4>> modeSeqVect, // bool matrix describing toe contacts as true or false e.g. {{1,1,1,1},{0,0,0,0}} would be a full support mode and flight mode\n          std::vector<int> knotpointVect, // Matrix of knot points for each mode  \n          std::vector<Eigen::Vector3d> normals,\n          std::vector<Eigen::Vector3d> offsets, \n          std::vector<double> mus , \n          std::vector<double> minTs, \n          std::vector<double> maxTs); // NOLINT\n          \n\ntemplate std::tuple<\n                std::vector<std::unique_ptr<DirconMode<double>>>,\n                std::vector<std::unique_ptr<dairlib::multibody::WorldPointEvaluator<double>>> ,\n                std::vector<std::unique_ptr<dairlib::multibody::KinematicEvaluatorSet<double>>>\n          > createSpiritModeSequence( \n          MultibodyPlant<double>& plant, // multibodyPlant\n          const dairlib::ModeSequenceHelper& msh );//NOLINT\n          \n  \ntemplate void setSpiritJointLimits(\n          drake::multibody::MultibodyPlant<double> & plant, \n          dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,  \n          int iJoint, \n          double minVal, \n          double maxVal  );\n\ntemplate void setSpiritJointLimits(\n          drake::multibody::MultibodyPlant<double> & plant,\n          dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,\n          std::vector<int> iJoints, \n          std::vector<double> minVals, \n          std::vector<double> maxVals  );\n\ntemplate void setSpiritJointLimits(\n          drake::multibody::MultibodyPlant<double> & plant,\n          dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,\n          std::vector<int> iJoints, \n          double minVal, \n          double maxVal  );\n\ntemplate void setSpiritJointLimits(\n          drake::multibody::MultibodyPlant<double> & plant,\n          dairlib::systems::trajectory_optimization::Dircon<double>& trajopt );\n\ntemplate void setSpiritActuationLimits(\n          drake::multibody::MultibodyPlant<double> & plant, \n          dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,\n          double actuatorLimit);\n\ntemplate void setSpiritSymmetry(\n        drake::multibody::MultibodyPlant<double> & plant, \n        dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,\n        std::string symmetry,\n        bool ignoreWarning);\n\ntemplate void setSpiritSymmetry(\n        drake::multibody::MultibodyPlant<double> & plant, \n        dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,\n        std::vector<std::string> symmetries);\n\ntemplate double calcWork(\n    drake::multibody::MultibodyPlant<double> & plant,\n    drake::trajectories::PiecewisePolynomial<double>& x_traj,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj);\n\ntemplate double calcMechanicalWork(\n    drake::multibody::MultibodyPlant<double> & plant,\n    std::vector<drake::trajectories::PiecewisePolynomial<double>>& x_traj,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj);\n\ntemplate double calcElectricalWork(\n    drake::multibody::MultibodyPlant<double> & plant,\n    std::vector<drake::trajectories::PiecewisePolynomial<double>>& x_traj,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj,\n    double efficiency);\n\ntemplate double calcVelocityInt(\n    drake::multibody::MultibodyPlant<double> & plant,\n    drake::trajectories::PiecewisePolynomial<double>& x_traj);\n\ntemplate double calcVelocityInt(\n    drake::multibody::MultibodyPlant<double> & plant,\n    std::vector<drake::trajectories::PiecewisePolynomial<double>>& x_trajs);\n\ntemplate double calcTorqueInt(\n    drake::multibody::MultibodyPlant<double> & plant,\n    drake::trajectories::PiecewisePolynomial<double>& u_traj);\n\ntemplate std::vector<drake::solvers::Binding<drake::solvers::Cost>> AddWorkCost(drake::multibody::MultibodyPlant<double> & plant,\n                 dairlib::systems::trajectory_optimization::Dircon<double>& trajopt,\n                 double cost_work_gain);\n\n}//namespace dairlib", "meta": {"hexsha": "7f8258e41fe61004213987c0a56f6294f4cdefdf", "size": 37736, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/Spirit/spirit_utils.cc", "max_stars_repo_name": "KodlabPenn/dairlib", "max_stars_repo_head_hexsha": "e544e16d2a97c3834e1eb5d534e436a45b8e4f4b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Spirit/spirit_utils.cc", "max_issues_repo_name": "KodlabPenn/dairlib", "max_issues_repo_head_hexsha": "e544e16d2a97c3834e1eb5d534e436a45b8e4f4b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-25T20:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T04:00:54.000Z", "max_forks_repo_path": "examples/Spirit/spirit_utils.cc", "max_forks_repo_name": "KodlabPenn/dairlib", "max_forks_repo_head_hexsha": "e544e16d2a97c3834e1eb5d534e436a45b8e4f4b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0641821946, "max_line_length": 188, "alphanum_fraction": 0.6531693873, "num_tokens": 10034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.03514484791667439, "lm_q1q2_score": 0.01674931935681464}}
{"text": "#include \"Setup.hpp\"\n#include \"math/Common.hpp\"\n\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <iostream>\n#include <locale>\n#include <memory>\n#include <random>\n#include <regex>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <mpreal.h>\n#include <unistd.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/date_time/date_facet.hpp>\n#include <boost/date_time/time_facet.hpp>\n#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n#include <readline/history.h>\n#include <readline/readline.h>\n\nstatic const std::unordered_map<mpfr_rnd_t, std::string> rmodeNameMap = {\n    {mpfr_rnd_t::MPFR_RNDN, \"N\"},\n    {mpfr_rnd_t::MPFR_RNDZ, \"Z\"},\n    {mpfr_rnd_t::MPFR_RNDU, \"U\"},\n    {mpfr_rnd_t::MPFR_RNDD, \"D\"},\n    {mpfr_rnd_t::MPFR_RNDA, \"A\"},\n    {mpfr_rnd_t::MPFR_RNDF, \"F\"},\n    {mpfr_rnd_t::MPFR_RNDNA, \"NA\"},\n};\n\nstatic const std::unordered_map<std::string, mpfr_rnd_t> rmodeNameMap2 = {\n    {\"N\", mpfr_rnd_t::MPFR_RNDN},\n    {\"Z\", mpfr_rnd_t::MPFR_RNDZ},\n    {\"U\", mpfr_rnd_t::MPFR_RNDU},\n    {\"D\", mpfr_rnd_t::MPFR_RNDD},\n    {\"A\", mpfr_rnd_t::MPFR_RNDA},\n    {\"F\", mpfr_rnd_t::MPFR_RNDF},\n    {\"NA\", mpfr_rnd_t::MPFR_RNDNA},\n};\n\nstatic const std::unordered_map<Associativity, std::string> associativityNameMap = {\n    {Associativity::Left, \"Left\"},\n    {Associativity::Right, \"Right\"},\n    {Associativity::Any, \"Any\"},\n};\n\nmpfr_rnd_t strToRmode(const std::string value)\n{\n  const auto iter = rmodeNameMap2.find(boost::to_upper_copy(value));\n  if(iter != rmodeNameMap2.cend())\n  {\n    return iter->second;\n  }\n  else\n  {\n    throw std::domain_error(\"Invalid rounding mode\");\n  }\n}\n\nstatic std::istream& operator>>(std::istream& stream, mpfr_rnd_t& result)\n{\n  std::string value;\n  stream >> value;\n  result = strToRmode(value);\n  return stream;\n}\n\nvoid resolveEnvironmentVariables(std::vector<std::string>& result)\n{\n  const char* pTmp;\n\n  if((pTmp = std::getenv(\"KALK_PREC\")) != nullptr)\n  {\n    result.push_back(\"KALK_PREC\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_RMODE\")) != nullptr)\n  {\n    result.push_back(\"KALK_RMODE\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_DIGITS\")) != nullptr)\n  {\n    result.push_back(\"KALK_DIGITS\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_OBASE\")) != nullptr)\n  {\n    result.push_back(\"KALK_OBASE\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_IBASE\")) != nullptr)\n  {\n    result.push_back(\"KALK_IBASE\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_BASE\")) != nullptr)\n  {\n    result.push_back(\"KALK_BASE\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_JUXTA\")) != nullptr)\n  {\n    result.push_back(\"KALK_JUXTA\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_DATE_OFMT\")) != nullptr)\n  {\n    result.push_back(\"KALK_DATE_OFMT\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_INTERACTIVE\")) != nullptr)\n  {\n    result.push_back(\"KALK_INTERACTIVE\");\n    result.push_back(pTmp);\n  }\n\n  if((pTmp = std::getenv(\"KALK_VERBOSE\")) != nullptr)\n  {\n    result.push_back(\"KALK_VERBOSE\");\n    result.push_back(pTmp);\n  }\n}\n\nstatic void handleResult(const DefaultValueType* value, bool verbose)\n{\n  results.push_back(*value);\n  if(verbose)\n  {\n    printValue(*value);\n  }\n\n  if(!defaultUninitializedVariableCache.empty())\n  {\n    std::cout << \"*** Warning: Uninitialized variable(s)\" << std::endl;\n    while(!defaultUninitializedVariableCache.empty())\n    {\n      auto iter = defaultUninitializedVariableCache.begin();\n      defaultVariables.erase(iter->first);\n      defaultUninitializedVariableCache.erase(iter);\n    }\n  }\n}\n\nstatic void evaluate(std::string expression, ExpressionParser& expressionParser, bool verbose = true)\n{\n  constexpr char kWhitespaceCharacters[] = \" \\t\\v\\n\\r\\f\";\n  bool end                               = false;\n  while(!end && expression.find_first_not_of(kWhitespaceCharacters) != std::string::npos)\n  {\n    const auto result = expressionParser.Evaluate(expression);\n    handleResult(result->As<const DefaultValueType*>(), verbose);\n    if(!(end = expressionParser.GetCurrent() != ';'))\n    {\n      expression = (expressionParser.GetRemaining() + 1u);\n    }\n  }\n}\n\nvoid list(const std::string& searchPattern)\n{\n  const std::regex regex(searchPattern);\n  bool isPrevEmptyLine = true;\n\n  std::cerr << \"Unary operators\" << std::endl;\n  for(const auto& i : unaryOperatorInfoMap)\n  {\n    const auto& entry = std::get<0u>(i);\n    if(entry == nullptr)\n    {\n      if(!isPrevEmptyLine)\n      {\n        std::cerr << std::endl;\n        isPrevEmptyLine = true;\n      }\n\n      continue;\n    }\n\n    const auto identifier    = std::string(1u, entry->GetIdentifier());\n    const auto precedence    = entry->GetPrecedence();\n    const auto associativity = associativityNameMap.at(entry->GetAssociativity());\n    const auto& title        = std::get<1u>(i);\n    const auto& description  = std::get<2u>(i);\n    if(std::regex_match(identifier.begin(), identifier.end(), regex) || std::regex_match(title.begin(), title.end(), regex) ||\n       std::regex_match(description.begin(), description.end(), regex))\n    {\n      std::cout << (boost::format(\"  %|1$-5|%|2$-5|%|3$-9|%|4$-20|%|5$|\") % identifier % precedence % associativity % title % description) << std::endl;\n      isPrevEmptyLine = false;\n    }\n  }\n  std::cerr << std::endl;\n\n  isPrevEmptyLine = true;\n  std::cerr << \"Binary operators\" << std::endl;\n  for(const auto& i : binaryOperatorInfoMap)\n  {\n    const auto& entry = std::get<0u>(i);\n    if(entry == nullptr)\n    {\n      if(!isPrevEmptyLine)\n      {\n        std::cerr << std::endl;\n        isPrevEmptyLine = true;\n      }\n\n      continue;\n    }\n\n    const auto& identifier   = entry->GetIdentifier();\n    const auto precedence    = entry->GetPrecedence();\n    const auto associativity = associativityNameMap.at(entry->GetAssociativity());\n    const auto& title        = std::get<1u>(i);\n    const auto& description  = std::get<2u>(i);\n    if(std::regex_match(identifier.begin(), identifier.end(), regex) || std::regex_match(title.begin(), title.end(), regex) ||\n       std::regex_match(description.begin(), description.end(), regex))\n    {\n      std::cout << (boost::format(\"  %|1$-6|%|2$-5|%|3$-9|%|4$-25|%|5$|\") % identifier % precedence % associativity % title % description) << std::endl;\n      isPrevEmptyLine = false;\n    }\n  }\n  std::cerr << std::endl;\n\n  isPrevEmptyLine = true;\n  std::cerr << \"Functions\" << std::endl;\n  for(const auto& i : functionInfoMap)\n  {\n    const auto& entry = std::get<0u>(i);\n    if(entry == nullptr)\n    {\n      if(!isPrevEmptyLine)\n      {\n        std::cerr << std::endl;\n        isPrevEmptyLine = true;\n      }\n\n      continue;\n    }\n\n    const auto& identifier = entry->GetIdentifier();\n    const auto argMinCount = ((entry->GetMinArgumentCount() != FunctionToken::GetArgumentCountMaxLimit()) ? std::to_string(entry->GetMinArgumentCount()) : \"-\");\n    const auto argMaxCount = ((entry->GetMaxArgumentCount() != FunctionToken::GetArgumentCountMaxLimit()) ? std::to_string(entry->GetMaxArgumentCount()) : \"-\");\n    const auto& title      = std::get<1u>(i);\n    const auto& description = std::get<2u>(i);\n    if(std::regex_match(identifier.begin(), identifier.end(), regex) || std::regex_match(title.begin(), title.end(), regex) ||\n       std::regex_match(description.begin(), description.end(), regex))\n    {\n      std::cout << (boost::format(\"  %|1$-15|%|2$-5|%|3$-5|%|4$-27|%|5$|\") % identifier % argMinCount % argMaxCount % title % description) << std::endl;\n      isPrevEmptyLine = false;\n    }\n  }\n  std::cerr << std::endl;\n\n  isPrevEmptyLine = true;\n  std::cerr << \"Variables\" << std::endl;\n  for(const auto& i : variableInfoMap)\n  {\n    const auto& entry = std::get<0u>(i);\n    if(entry == nullptr)\n    {\n      if(!isPrevEmptyLine)\n      {\n        std::cerr << std::endl;\n        isPrevEmptyLine = true;\n      }\n\n      continue;\n    }\n\n    const auto& identifier  = entry->GetIdentifier();\n    const auto& title       = std::get<1u>(i);\n    const auto& description = std::get<2u>(i);\n    if(std::regex_match(identifier.begin(), identifier.end(), regex) || std::regex_match(title.begin(), title.end(), regex) ||\n       std::regex_match(description.begin(), description.end(), regex))\n    {\n      std::cout << (boost::format(\"  %|1$-16|%|2$-29|%|3$|\") % identifier % title % description) << std::endl;\n      isPrevEmptyLine = false;\n    }\n  }\n}\n\nstatic void printOptions()\n{\n  std::cerr << \"Options\" << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Precision\" % options.precision) << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Rounding mode\" % rmodeNameMap.at(options.roundingMode)) << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Output precision\" % options.digits) << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Output base\" % options.output_base) << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Input base\" % options.input_base) << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Juxtaposition precedence\" % options.jpo_precedence) << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Date output format\" % options.date_ofmt) << std::endl;\n  std::cerr << (boost::format(\"  %|1$-26|%|2$|\") % \"Seed\" % options.seed) << std::endl;\n  std::cerr << std::endl;\n}\n\nstatic void printVersion() { std::cout << (boost::format(\"%1% v%2%\") % PROJECT_NAME % PROJECT_VERSION) << std::endl; }\n\nstatic void printUsage(const boost::program_options::options_description& desc)\n{\n  std::cerr << (boost::format(\"%1% -[xprnbBjdzZilvVh] expr...\") % PROJECT_EXECUTABLE) << std::endl;\n  std::cerr << desc << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n  std::vector<std::string> envs;\n  resolveEnvironmentVariables(envs);\n\n  boost::program_options::options_description namedEnvDescs;\n  namedEnvDescs.add_options()(\"KALK_PREC\", boost::program_options::value<mpfr_prec_t>(&options.precision)->default_value(defaultOptions.precision));\n  namedEnvDescs.add_options()(\"KALK_RMODE\", boost::program_options::value<mpfr_rnd_t>(&options.roundingMode)->default_value(defaultOptions.roundingMode));\n  namedEnvDescs.add_options()(\"KALK_DIGITS\", boost::program_options::value<int>(&options.digits)->default_value(defaultOptions.digits));\n  namedEnvDescs.add_options()(\"KALK_OBASE\", boost::program_options::value<int>(&options.output_base));\n  namedEnvDescs.add_options()(\"KALK_IBASE\", boost::program_options::value<int>(&options.input_base));\n  namedEnvDescs.add_options()(\"KALK_BASE\", boost::program_options::value<int>()->default_value(defaultOptions.output_base)->notifier([](int value) {\n    options.output_base = value;\n    options.input_base  = value;\n  }));\n  namedEnvDescs.add_options()(\"KALK_JUXTA\", boost::program_options::value<int>()->default_value(defaultOptions.jpo_precedence)->notifier([](int value) {\n    options.jpo_precedence = Math::Sign(value);\n  }));\n  namedEnvDescs.add_options()(\"KALK_DATE_OFMT\", boost::program_options::value<std::string>(&options.date_ofmt)->default_value(defaultOptions.date_ofmt));\n  namedEnvDescs.add_options()(\"KALK_INTERACTIVE\", boost::program_options::value<bool>(&options.interactive)->default_value(defaultOptions.interactive));\n  namedEnvDescs.add_options()(\"KALK_VERBOSE\", boost::program_options::value<std::string>()->default_value(\"\"));\n\n  boost::program_options::variables_map envVariableMap;\n  boost::program_options::store(boost::program_options::command_line_parser(envs)\n                                    .options(namedEnvDescs)\n                                    .extra_parser([](const std::string& value) { return std::make_pair(value, std::string()); })\n                                    .run(),\n                                envVariableMap);\n  boost::program_options::notify(envVariableMap);\n\n  boost::program_options::options_description namedArgDescs(\"Options\");\n  namedArgDescs.add_options()(\"expr,x\", boost::program_options::value<std::vector<std::string>>(), \"Add an expression\");\n  namedArgDescs.add_options()(\"prec,p\", boost::program_options::value<mpfr_prec_t>(&options.precision), \"Set precision\");\n  namedArgDescs.add_options()(\"rmode,r\", boost::program_options::value<mpfr_rnd_t>(&options.roundingMode), \"Set rounding mode (N, Z, U, D, A, F, NA)\");\n  namedArgDescs.add_options()(\"digits,n\", boost::program_options::value<int>(&options.digits), \"Set output precision (Number of digits)\");\n  namedArgDescs.add_options()(\"obase,b\", boost::program_options::value<int>(&options.output_base), \"Set output base\");\n  namedArgDescs.add_options()(\"ibase,B\", boost::program_options::value<int>(&options.input_base), \"Set input base\");\n  namedArgDescs.add_options()(\"base\",\n                              boost::program_options::value<int>()->notifier([](int value) { options.input_base = options.output_base = value; }),\n                              \"Set output and input base\");\n  namedArgDescs.add_options()(\"juxta,j\",\n                              boost::program_options::value<int>()->notifier([](int value) { options.jpo_precedence = Math::Sign(value); }),\n                              \"Set juxtaposition operator precedence (-1, 0, 1)\");\n  namedArgDescs.add_options()(\"date_ofmt,d\", boost::program_options::value<std::string>(&options.date_ofmt), \"Set date output format\");\n  namedArgDescs.add_options()(\"seed,z\", boost::program_options::value<unsigned int>(&options.seed), \"Set random seed (number)\");\n  namedArgDescs.add_options()(\"seedstr,Z\",\n                              boost::program_options::value<std::string>()->notifier([](std::string value) {\n                                std::hash<std::string> hasher;\n                                options.seed = value.empty() ? defaultOptions.seed : static_cast<unsigned int>(hasher(value));\n                              }),\n                              \"Set random seed (string)\");\n  namedArgDescs.add_options()(\"interactive,i\", boost::program_options::value<bool>(&options.interactive)->implicit_value(true), \"Enable interactive mode\");\n  namedArgDescs.add_options()(\"list,l\", boost::program_options::value<std::string>()->implicit_value(\".*\"), \"List available operators/functions/variables\");\n  namedArgDescs.add_options()(\"verbose,v\", boost::program_options::value<std::string>()->default_value(\"\")->implicit_value(\"op\"), \"Enable verbose mode\");\n  namedArgDescs.add_options()(\"version,V\", \"Print version\");\n  namedArgDescs.add_options()(\"help,h\", \"Print usage\");\n\n  boost::program_options::positional_options_description positionalArgDescs;\n  positionalArgDescs.add(\"expr\", -1);\n\n  boost::program_options::variables_map argVariableMap;\n  boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(namedArgDescs).positional(positionalArgDescs).run(),\n                                argVariableMap);\n  boost::program_options::notify(argVariableMap);\n\n  if(argVariableMap.count(\"help\") > 0u)\n  {\n    printUsage(namedArgDescs);\n    std::exit(EXIT_SUCCESS);\n  }\n\n  if(argVariableMap.count(\"version\") > 0u)\n  {\n    printVersion();\n    std::exit(EXIT_SUCCESS);\n  }\n\n  mpfr::random((options.seed != 0u) ? options.seed : std::random_device()());\n\n  if((options.precision < MPFR_PREC_MIN) || (options.precision > MPFR_PREC_MAX))\n  {\n    std::cerr << (boost::format(\"*** Error: Precision out of range: %1% (%2% - %3%)\") % options.precision % MPFR_PREC_MIN % MPFR_PREC_MAX) << std::endl;\n    std::exit(EXIT_FAILURE);\n  }\n\n  mpfr::mpreal::set_default_prec(options.precision);\n  mpfr::mpreal::set_default_rnd(options.roundingMode);\n\n  auto dateFacet = new boost::posix_time::time_facet(options.date_ofmt.c_str());\n  std::cout.imbue(std::locale(std::cout.getloc(), dateFacet));\n\n  const bool verboseOptions = envVariableMap[\"KALK_VERBOSE\"].as<const std::string&>().find_first_of(\"oO\") != std::string::npos ||\n                              argVariableMap[\"verbose\"].as<const std::string&>().find_first_of(\"oO\") != std::string::npos;\n  const bool verbosePipe = envVariableMap[\"KALK_VERBOSE\"].as<const std::string&>().find_first_of(\"pP\") != std::string::npos ||\n                           argVariableMap[\"verbose\"].as<const std::string&>().find_first_of(\"pP\") != std::string::npos;\n\n  if(verboseOptions)\n  {\n    printOptions();\n  }\n\n  ExpressionParser expressionParser;\n  InitDefaultExpressionParser(expressionParser);\n\n  CommandParser commandParser;\n  InitCommandParser(commandParser);\n\n  if(argVariableMap.count(\"list\") > 0u)\n  {\n    list(argVariableMap[\"list\"].as<const std::string&>());\n    std::exit(EXIT_SUCCESS);\n  }\n\n  std::unique_ptr<FILE, decltype(&std::fclose)> file_stdin(nullptr, &std::fclose);\n  bool hasPipedData = std::cin.rdbuf()->in_avail() != -1 && isatty(fileno(stdin)) == 0;\n  if(hasPipedData)\n  {\n    std::string input;\n    while(std::getline(std::cin, input))\n    {\n      evaluate(input, expressionParser, verbosePipe);\n    }\n\n    if(options.interactive)\n    {\n      const char* ttyFileName = ttyname(fileno(stdout));\n      if(ttyFileName == nullptr)\n      {\n        std::cerr << \"*** Error: \" << std::strerror(errno) << std::endl;\n        std::exit(EXIT_FAILURE);\n      }\n\n      FILE* tmpFile;\n      if((tmpFile = freopen(ttyFileName, \"r\", stdin)) == nullptr)\n      {\n        std::cerr << \"*** Error: \" << std::strerror(errno) << std::endl;\n        std::exit(EXIT_FAILURE);\n      }\n\n      file_stdin.reset(tmpFile);\n    }\n  }\n\n  if(argVariableMap.count(\"expr\") == 0u && !options.interactive && !hasPipedData)\n  {\n    std::cerr << \"*** Error: No expression specified\" << std::endl;\n    std::exit(EXIT_FAILURE);\n  }\n\n  if(argVariableMap.count(\"expr\") > 0u)\n  {\n    results.clear();\n\n    const auto& exprs = argVariableMap[\"expr\"].as<const std::vector<std::string>&>();\n    for(auto& expr : exprs)\n    {\n      evaluate(expr, expressionParser);\n    }\n  }\n\n  if(options.interactive)\n  {\n    results.clear();\n\n    char* tmpInput;\n    while(!quit && (tmpInput = readline(\"> \")) != nullptr)\n    {\n      auto tmpPtr       = std::unique_ptr<char, decltype(&std::free)>(tmpInput, &std::free);\n      std::string input = tmpInput;\n\n      boost::trim_left(input);\n      if(!input.empty())\n      {\n        if(input.front() == '/')\n        {\n          try\n          {\n            commandParser.Execute(input.erase(0, 1));\n          }\n          catch(const SyntaxError& e)\n          {\n            std::cerr << \"*** Command error: \" << e.what() << std::endl;\n          }\n          catch(const std::runtime_error& e)\n          {\n            std::cerr << \"*** Command error: \" << e.what() << std::endl;\n          }\n          catch(const std::domain_error& e)\n          {\n            std::cerr << \"*** Command error: \" << e.what() << std::endl;\n          }\n        }\n        else\n        {\n          try\n          {\n            evaluate(input, expressionParser);\n          }\n          catch(const SyntaxError& e)\n          {\n            std::cerr << \"*** Expression error: \" << e.what() << std::endl;\n          }\n          catch(const std::runtime_error& e)\n          {\n            std::cerr << \"*** Expression error: \" << e.what() << std::endl;\n          }\n          catch(const std::domain_error& e)\n          {\n            std::cerr << \"*** Expression error: \" << e.what() << std::endl;\n          }\n        }\n\n        add_history(tmpInput);\n      }\n    }\n  }\n\n  std::exit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "466baba5942f6b42908e270d0ca846e33bf530a0", "size": 19386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "albrdev/kalk", "max_stars_repo_head_hexsha": "529472931308da37391601ef47e59e03bc91b693", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "albrdev/kalk", "max_issues_repo_head_hexsha": "529472931308da37391601ef47e59e03bc91b693", "max_issues_repo_licenses": ["Apache-2.0"], "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": "albrdev/kalk", "max_forks_repo_head_hexsha": "529472931308da37391601ef47e59e03bc91b693", "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.0334572491, "max_line_length": 160, "alphanum_fraction": 0.6289590426, "num_tokens": 5173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.035144846527116684, "lm_q1q2_score": 0.016749318694579716}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"latbuilder/Parser/EmbeddingType.h\"\n#include \"latbuilder/Parser/Lattice.h\"\n#include \"latbuilder/Parser/CommandLine.h\"   \n#include \"latbuilder/TextStream.h\"\n#include \"latbuilder/Types.h\"\n\n#include \"netbuilder/DigitalNet.h\"\n#include \"netbuilder/Types.h\"\n\n#include \"netbuilder/Parser/OutputStyleParser.h\"\n\n#include <fstream>\n#include <chrono>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string/join.hpp>\n\nnamespace LatBuilder{\nusing TextStream::operator<<;\n\nstatic unsigned int merit_digits_displayed = 0; \n\ntemplate <LatticeType LR, EmbeddingType ET>\nvoid onLatticeSelected(const Task::Search<LR, ET>& s)\n   {\n     Dimension currentDim = s.bestLattice().dimension();\n     Dimension totalDim = s.dimension();\n      unsigned int old_precision = (unsigned int) std::cout.precision();\n      if (merit_digits_displayed){\n        std::cout.precision(merit_digits_displayed);\n      }\n      std::string lattice;\n      if (s.minObserver().totalCount() == 1){\n        lattice = \" lattice\";\n      }\n      else{\n        lattice = \" lattices\";\n      }\n      \n       std::cout << \"End coordinate: \" << currentDim << \"/\" << totalDim << \" - \"\n       << s.minObserver().totalCount() << lattice  << \" explored (\" << s.minObserver().acceptedCount() << \" accepted)\"\n       << \" - partial merit value: \" << s.bestMeritValue() << std::endl;\n     \n      if (merit_digits_displayed){\n        std::cout.precision(old_precision);\n      }\n      if (currentDim < totalDim){\n        std::cout << \"Begin coordinate \" << currentDim+1 << \"/\" << totalDim << std::endl;\n      }\n   }\n\nboost::program_options::options_description\nmakeOptionsDescription()\n{\n   namespace po = boost::program_options;\n   po::options_description desc(\"allowed options\");\n\n   desc.add_options ()\n   (\"help,h\", \"produce help message\")\n   (\"version\", \"show version\")\n   (\"set-type,t\", po::value<std::string>(),\n    \"(required) point set type; possible values:\\n\"\n    \"  lattice\\n\"\n    \"  net\\n\")\n   (\"construction,c\", po::value<std::string>(),\n   \"lattice construction; possible values:\\n\"\n   \"  ordinary\\n\"\n   \"  polynomial\\n\")\n   (\"dimension,d\", po::value<std::string>(),\n    \"(required) point set dimension\\n\")\n   (\"size-parameter,s\", po::value<std::string>(),\n    \"(required) modulus of the lattice; possible values:\\n\"\n   \"  <modulus>\\n\"\n   \"  <base>^<max-level>\\n\"\n   \"  input format :\\n\"\n   \"  ordinary lattice rules: integer (decimal representation)\\n\"\n   \"  polynomial lattice rules: polynomial (list of coefficients: 1011 stands for 1 + X^2 + X^3), or\\n\"\n   \"                            2^<max_level> (default irreducible modulus, not available for multilevel)\\n\"\n   )\n   (\"exploration-method,e\", po::value<std::string>(),\n    \"(required) exploration method; possible values:\\n\"\n    \"  evaluation:<a1>,...,<as>\\n\"\n    \"  exhaustive\\n\"\n    \"  random:<r>\\n\"\n    \"  Korobov\\n\"\n    \"  random-Korobov:<r>\\n\"\n    \"  full-CBC\\n\"\n    \"  random-CBC:<r>\\n\"\n    \"  fast-CBC\\n\"\n    \"  extend:<num-points>:<a1>,...,<as>\\n\"\n    \"where <r> is the number of samples, \"\n    \"and <a1>,...,<as> are the components of the generating vector\\n\")\n   (\"figure-of-merit,f\", po::value<std::string>(),\n    \"(required) type of figure of merit; format: [CU:]<merit>\\n\"\n    \"  where the optional \\\"CU:\\\" prefix switches on the coordinate-uniform evaluation algorithm,\\n\"\n    \"  and where <merit> is one of:\\n\"\n    \"    spectral  (only for ordinary lattice rules, no CU)\\n\"\n    \"    P<alpha>  (for both constructions, CU for l_2 norm)\\n\"\n    \"    R<alpha>  (only for ordinary lattice rules, CU for l_2 norm)\\n\"\n    \"    R         (for both constructions, CU for l_2 norm)\\n\"\n    \"    IA<alpha> (for interlaced polynomial lattice rules, CU for l_1 norm)\\n\"\n    \"    IB (for interlaced polynomial lattice rules, CU for l_1 norm)\\n\")\n    (\"interlacing-factor,i\", po::value<std::string>()->default_value(\"1\"),\n    \"(default: 1) interlacing factor (only for polynomial lattice rules). If larger than one, the constructed\"\n    \"point set is an interlaced polynomial lattice rule. In this case, the figure of merit must be\"\n    \"specific to interlaced polynomial lattice rules.\\n\")\n   (\"norm-type,q\", po::value<std::string>(),\n    \"norm type used to combine the value of the projection-dependent figure of merit for all projections; possible values:\"\n    \"    <q>: a real number corresponding the l_<q> norm\\n\"\n    \"    inf: corresponding to the `max' norm\\n\")\n   (\"weights,w\", po::value<std::vector<std::string>>()->multitoken(),\n    \"(required) whitespace-separated list of weights specifications (the actual weights are the sum of these); possible values:\\n\"\n    \"  product:<default>:<coord1-weight>[,...]\\n\"\n    \"  order-dependent:<default>:<order-1-weight>,...,<order-s-weight>\\n\"\n    \"  POD:<default>:<order-1-weight>,...,<order-s-weight>:<default>:<coord1-weight>[,...]\\n\"\n    \"  projection-dependent:<proj-1>:<weight-1>[:<proj-2>:<weight-2>[:...]]\\n\"\n    \"    where <proj-n> is a comma-separated list of coordinates\\n\"\n    \"  file:\\\"<file>\\\"\\n\"\n    \"    line format in <file>:\\n\"\n    \"      <i1>,<i2>,...: <weight>\\n\"\n    \"      order <x>: <weight>\\n\"\n    \"      default: <weight>\\n\"\n    \"    if <file> is `-' data is read from standard input\\n\")\n   (\"weights-power,p\", po::value<Real>(),\n    \"(default: same value as for the --norm-type argument) real number specifying that the weights passed as input will be assumed to be already elevated at that power (a value of `inf' is mapped to 1)\\n\")\n   (\"multilevel,M\", po::value<std::string>()->default_value(\"false\"),\n    \"multilevel point set; possible values:\\n\"\n   \"  false (default)\\n\"\n   \"  true\\n\")\n   (\"combiner,C\", po::value<std::string>(),\n    \"(required for multilevel) combiner for multilevel merit values; possible values:\\n\"\n    \"  sum\\n\"\n    \"  max\\n\"\n    \"  level:{<level>|max}\\n\")\n   (\"filters,F\", po::value<std::vector<std::string>>()->multitoken(),\n    \"whitespace-separated list of filters for merit values; possible values:\\n\"\n    \"  norm[:<levels>] for a default normalization (if available)\"\n    \"  norm:{P<alpha>-SL10|P<alpha>-DPW08|P<alpha>|IA<alpha>|IB}[:<levels>]\\n\"\n    \"  low-pass:<threshold>\\n\"\n    \"where in the case of multilevel lattices, the optional parameter <levels> specifies the selected levels; possible values:\\n\"\n    \"  select[:<min-level>[:<max-level>]] (default)\\n\")\n   (\"repeat,r\", po::value<unsigned int>()->default_value(1),\n    \"(optional) number of times the exploration must be executed\\n\"\n   \"(can be useful to obtain different results from random exploration)\\n\")\n   (\"verbose,v\", po::value<int>()->default_value(0),\n   \"specify the verbosity of the program;\\n\"\n   \"ranges between 0 (default) and 3\\n\")\n    (\"output-folder,o\", po::value<std::string>(),\n    \"(optional) path to the folder for the outputs of LatNeBuilder. The contents of the folder may be overwritten. If the folder does not exist, it is created. If no path is provided, no output folder is created.\")\n    (\"output-style,O\", po::value<std::string>()->default_value(\"\"),\n    \"(optional) TBD\")\n   (\"merit-digits-displayed\", po::value<unsigned int>()->default_value(0),\n    \"(optional) number of significant figures to use when displaying merit values\\n\");\n\n   return desc;\n}\n\n\nboost::program_options::variables_map\nparse(int argc, const char* argv[])\n{\n   namespace po = boost::program_options;\n\n   auto desc = makeOptionsDescription();\n\n   po::variables_map opt;\n   po::store(po::parse_command_line(argc, argv, desc), opt);\n   po::notify(opt);\n\n   if (opt.count(\"help\")) {\n      std::cout << desc << std::endl;\n      std::exit (0);\n   }\n\n   for (const auto x : {\"construction\", \"size-parameter\", \"exploration-method\", \"dimension\", \"figure-of-merit\", \"norm-type\"}) {\n      if (opt.count(x) != 1)\n         throw std::runtime_error(\"--\" + std::string(x) + \" must be specified exactly once (try --help)\");\n   }\n\n  if (opt.count(\"combiner\") < 1 && opt[\"multilevel\"].as<std::string>() == \"true\"){\n    throw std::runtime_error(\"--combiner must be specified for multilevel set type (try --help)\");\n  }\n\n   if (opt.count(\"weights\") < 1)\n      throw std::runtime_error(\"--weights must be specified (try --help)\");\n\n   return opt;\n}\n\ntemplate <EmbeddingType ET>\nstd::string helper(const SizeParam<LatticeType::ORDINARY, ET>& param);\n\ntemplate<>\nstd::string helper(const SizeParam<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>& param)\n{\n  return std::to_string(param.base()) + \"  // Base\\n\" + std::to_string(param.maxLevel()) + \"  // Maximum level\\n\";\n}\n\ntemplate<>\nstd::string helper(const SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>& param)\n{\n  return \"0  // Base\\n0  // Maximum level\\n\";\n}\n\n\ntemplate <EmbeddingType ET>\nstd::string helper2(const SizeParam<LatticeType::ORDINARY, ET>& param);\n\ntemplate<>\nstd::string helper2(const SizeParam<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL>& param)\n{\n  return \", embedded from \" + std::to_string(param.base()) + \" to \" + std::to_string(param.maxLevel()) + \"\\n\";\n}\n\ntemplate<>\nstd::string helper2(const SizeParam<LatticeType::ORDINARY, EmbeddingType::UNILEVEL>& param)\n{\n  return \"\\n\";\n}\n\n\n\ntemplate <EmbeddingType ET>\nvoid executeOrdinary(const Parser::CommandLine<LatticeType::ORDINARY, ET>& cmd, int verbose, unsigned int repeat, std::string outputFolder)\n{\n   const LatticeType LR = LatticeType::ORDINARY ;\n   using namespace std::chrono;\n\n   auto search = cmd.parse();\n\n   const std::string separator = \"====================\\n\";\n  \n   std::cout << separator << \"    Input\" << std::endl << separator << *search << std::endl;\n    if (outputFolder != \"\"){\n      std::ofstream outFile;\n      std::string fileName = outputFolder + \"/input.txt\";\n      outFile.open(fileName);\n      outFile << \"Input Command Line: \" << cmd.originalCommandLine << std::endl << std::endl;\n      outFile << *search; \n      outFile.close();\n    }\n\n   if (verbose > 0) {\n      search->onLatticeSelected().connect(onLatticeSelected<LR,ET>);\n      search->setObserverVerbosity(verbose-1);\n      search->setVerbose(verbose-2);\n   }\n\n   for (unsigned int i = 0; i < repeat; i++) {\n        if (repeat > 1){\n          std::cout << separator << \"      Run \" << i+1 << std::endl << separator;\n        }\n        else{\n          std::cout << separator << \"Running the task...\" << std::endl << separator;\n        }\n\n      auto t0 = high_resolution_clock::now();\n      search->execute();\n      auto t1 = high_resolution_clock::now();\n\n      unsigned int old_precision = (unsigned int) std::cout.precision();\n      if (merit_digits_displayed)\n   std::cout.precision(merit_digits_displayed);\n     const auto lat = search->bestLattice();\n     \n   auto dt = duration_cast<duration<double>>(t1 - t0);\n         std::cout << std::endl;\n         std::cout << separator << \"      Result\" << std::endl << separator;\n        std::cout << lat;\n        std::cout << \"Merit: \" << search->bestMeritValue() << std::endl;\n        std::cout << std::endl;\n         std::cout << \"ELAPSED CPU TIME: \" << dt.count() << \" seconds\" << std::endl << std::endl;\n\n      if (outputFolder != \"\"){\n        std::ofstream outFile;\n        std::string fileName = outputFolder + \"/output.txt\";\n        outFile.open(fileName);\n        outFile << \"# Input Command Line: \" << cmd.originalCommandLine << std::endl;\n        outFile << \"# Merit: \" << search->bestMeritValue() << std::endl;\n        outFile << \"# Parameters for a lattice rule\";\n        outFile << helper2<ET>(lat.sizeParam());\n        outFile << lat.dimension() <<\"    # s = \"<< lat.dimension() << \" dimensions\\n\";\n        outFile << lat.sizeParam().numPoints() <<\"    # modulus = n = \"<< lat.sizeParam().numPoints() << \" points\\n\";\n        auto vec = lat.gen();\n        outFile << \"# Coordinates of generating vector, starting at j=1\" << std::endl;\n        for (unsigned int coord = 0; coord < vec.size(); coord++){\n          if (coord < vec.size() - 1){\n            outFile << vec[coord] << std::endl;\n          }\n          else{\n            outFile << vec[coord];\n          }\n        }\n        outFile.close();\n      }\n      \n      if (merit_digits_displayed)\n   std::cout.precision(old_precision);\n\n      search->reset();\n    }\n}\n\n\ntemplate <EmbeddingType ET>\nvoid executePolynomial(const Parser::CommandLine<LatticeType::POLYNOMIAL, ET>& cmd, int verbose, unsigned int repeat, std::string outputFolder, NetBuilder::OutputStyle outputStyle)\n{\n   const LatticeType LR = LatticeType::POLYNOMIAL ;\n   using namespace std::chrono;\n\n   auto search = cmd.parse();\n   \n   unsigned int interlacingFactor = 1;\n    try{\n      interlacingFactor = boost::lexical_cast<unsigned int>(cmd.interlacingFactor);\n    }\n    catch (boost::bad_lexical_cast&) {}\n\n   const std::string separator = \"====================\\n\";\n  \n   std::cout << separator << \"    Input\" << std::endl << separator << *search << std::endl;\n    if (outputFolder != \"\"){\n      std::ofstream outFile;\n      std::string fileName = outputFolder + \"/input.txt\";\n      outFile.open(fileName);\n      outFile << \"Input Command Line: \" << cmd.originalCommandLine << std::endl << std::endl;\n      outFile << *search;\n      outFile.close();\n    }\n\n   if (verbose > 0) {\n      search->onLatticeSelected().connect(onLatticeSelected<LR,ET>);\n      search->setObserverVerbosity(verbose-1);\n      search->setVerbose(verbose-2);\n   }\n\n   for (unsigned int i = 0; i < repeat; i++) {\n        if (repeat > 1){\n          std::cout << separator << \"      Run \" << i+1 << std::endl << separator;\n        }\n        else{\n          std::cout << separator << \"Running the task...\" << std::endl << separator;\n        }\n\n        auto t0 = high_resolution_clock::now();\n        search->execute();\n        auto t1 = high_resolution_clock::now();\n\n        unsigned int old_precision = (unsigned int) std::cout.precision();\n        if (merit_digits_displayed){\n          std::cout.precision(merit_digits_displayed);\n        }\n       const auto lat = search->bestLattice();\n      \n        auto dt = duration_cast<duration<double>>(t1 - t0);\n           std::cout << std::endl;\n           std::cout << separator << \"    Result\" << std::endl << separator;\n           std::cout << lat;\n           std::cout << \"Merit: \" << search->bestMeritValue() << std::endl;\n           std::cout << std::endl;\n           std::cout << \"ELAPSED CPU TIME: \" << dt.count() << \" seconds\" << std::endl << std::endl;\n\n      if (outputFolder != \"\"){\n          NetBuilder::DigitalNet<NetBuilder::NetConstruction::POLYNOMIAL> net((unsigned int) lat.gen().size(), lat.sizeParam().modulus(),lat.gen());\n          \n          if (outputStyle != NetBuilder::OutputStyle::TERMINAL){\n            std::ofstream outFile;\n            std::string fileName = outputFolder + \"/output.txt\";\n            outFile.open(fileName);\n            outFile << \"# Input Command Line: \" << cmd.originalCommandLine << std::endl;\n            outFile << \"# Merit: \" << search->bestMeritValue() << std::endl;\n            outFile << net.format(outputStyle, interlacingFactor) ;\n            outFile.close();\n          }\n      }\n\n        \n        if (merit_digits_displayed){\n          std::cout.precision(old_precision);\n        }\n          \n        search->reset();\n    }\n}\n\n   \n \n\n\n\n\nint main(int argc, const char *argv[])\n{\n\n   try {\n        auto opt = parse(argc, argv);\n\n        // bool quiet = opt.count(\"quiet\");\n        int verbose = opt[\"verbose\"].as<int>();\n        \n        auto repeat = opt[\"repeat\"].as<unsigned int>();\n\n        std::string outputFolder = \"\";\n        if (opt.count(\"output-folder\") >= 1){\n          outputFolder = opt[\"output-folder\"].as<std::string>();\n          std::cout << \"Writing in output folder: \" << outputFolder << std::endl;\n          boost::filesystem::create_directories(outputFolder);\n        }        \n\n        // global variable\n        merit_digits_displayed = opt[\"merit-digits-displayed\"].as<unsigned int>();\n\n        std::string outputstyle = opt[\"output-style\"].as<std::string>();\n\n       LatBuilder::LatticeType lattice = Parser::LatticeParser::parse(opt[\"construction\"].as<std::string>());\n\n       std::vector<std::string> all_args;\n       if (argc > 1) {\n          all_args.assign(argv + 1, argv + argc);\n        }\n\n       if(lattice == LatticeType::ORDINARY){\n\n            Parser::CommandLine<LatticeType::ORDINARY, EmbeddingType::MULTILEVEL> cmd;\n\n            \n            cmd.originalCommandLine = boost::algorithm::join(all_args, \" \");\n            cmd.construction  = opt[\"exploration-method\"].as<std::string>();\n            cmd.size          = opt[\"size-parameter\"].as<std::string>();\n            cmd.dimension     = opt[\"dimension\"].as<std::string>();\n            cmd.normType      = opt[\"norm-type\"].as<std::string>();\n            cmd.figure        = opt[\"figure-of-merit\"].as<std::string>();\n            cmd.weights       = opt[\"weights\"].as<std::vector<std::string>>();\n\n            if (opt.count(\"combiner\") == 1){\n              cmd.combiner      = opt[\"combiner\"].as<std::string>();\n            }\n            else{\n              cmd.combiner = \"level:max\";\n            }\n\n            if (opt[\"interlacing-factor\"].as<std::string>() != \"1\")\n            {\n              throw std::runtime_error(\"Interlacing can only be used with polynomial lattice rules.\");\n            }\n            else\n            {\n              cmd.interlacingFactor = \"1\";\n            }\n\n            cmd.weightsPowerScale = 1.0;\n            if (opt.count(\"weights-power\") >= 1) {\n               // assume 1.0 if norm-type is `inf' or anything else\n               cmd.weightsPowerScale = 1.0;\n               try {\n                  // start the value of norm-type as a default\n                  if (cmd.normType != \"inf\")\n                     cmd.weightsPowerScale = boost::lexical_cast<Real>(cmd.normType);\n               }\n               catch (boost::bad_lexical_cast&) {}\n               // then scale down according to interpretation of input\n               cmd.weightsPowerScale /= opt[\"weights-power\"].as<Real>();\n            }\n\n            if (opt.count(\"filters\") >= 1)\n               cmd.filters = opt[\"filters\"].as<std::vector<std::string>>();\n\n            EmbeddingType latType = Parser::EmbeddingType::parse(opt[\"multilevel\"].as<std::string>());\n\n            if (latType == EmbeddingType::UNILEVEL){\n               executeOrdinary<EmbeddingType::UNILEVEL> (cmd, verbose, repeat, outputFolder);\n               \n             }\n            else{\n               executeOrdinary<EmbeddingType::MULTILEVEL> (cmd, verbose, repeat, outputFolder);\n               \n             }\n      }\n\n      else if(lattice == LatticeType::POLYNOMIAL){\n\n            Parser::CommandLine<LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL> cmd;\n\n            \n            cmd.originalCommandLine = boost::algorithm::join(all_args, \" \");\n            cmd.construction  = opt[\"exploration-method\"].as<std::string>();\n            cmd.size          = opt[\"size-parameter\"].as<std::string>();\n            cmd.dimension     = opt[\"dimension\"].as<std::string>();\n            cmd.normType      = opt[\"norm-type\"].as<std::string>();\n            cmd.figure        = opt[\"figure-of-merit\"].as<std::string>();\n            cmd.weights       = opt[\"weights\"].as<std::vector<std::string>>();\n            cmd.interlacingFactor = opt[\"interlacing-factor\"].as<std::string>();\n            if (opt.count(\"combiner\") == 1){\n              cmd.combiner      = opt[\"combiner\"].as<std::string>();\n            }\n            else{\n              cmd.combiner = \"level:max\";\n            }\n\n            cmd.weightsPowerScale = 1.0;\n            if (opt.count(\"weights-power\") >= 1) {\n               // assume 1.0 if norm-type is `inf' or anything else\n               cmd.weightsPowerScale = 1.0;\n               try {\n                  // start the value of norm-type as a default\n                  if (cmd.normType != \"inf\")\n                     cmd.weightsPowerScale = boost::lexical_cast<Real>(cmd.normType);\n               }\n               catch (boost::bad_lexical_cast&) {}\n               // then scale down according to interpretation of input\n               cmd.weightsPowerScale /= opt[\"weights-power\"].as<Real>();\n            }\n\n            if (opt.count(\"filters\") >= 1)\n               cmd.filters = opt[\"filters\"].as<std::vector<std::string>>();\n\n            EmbeddingType latType = Parser::EmbeddingType::parse(opt[\"multilevel\"].as<std::string>());\n\n            NetBuilder::OutputStyle outputStyle = NetBuilder::Parser::OutputStyleParser<NetBuilder::NetConstruction::POLYNOMIAL>::parse(outputstyle);\n\n\n            if (latType == EmbeddingType::UNILEVEL){\n              executePolynomial< EmbeddingType::UNILEVEL> (cmd, verbose, repeat, outputFolder, outputStyle);\n               \n             }\n            else{\n              executePolynomial<EmbeddingType::MULTILEVEL> (cmd, verbose, repeat, outputFolder, outputStyle);\n               \n             }\n      }\n   }\n   catch (Parser::ParserError& e) {\n      std::cerr << \"COMMAND LINE ERROR: \" << e.what() << std::endl;\n      std::exit(1);\n   }\n   catch (std::exception& e) {\n      std::cerr << \"ERROR: \" << e.what() << std::endl;\n      std::exit(1);\n   }\n\n   return 0;\n}\n\n}\n", "meta": {"hexsha": "4149d15db53a774e7c763cf58d60f216a6ea0940", "size": 21760, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/latbuilder.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "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/LatBuilder/latbuilder.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LatBuilder/latbuilder.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "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.8571428571, "max_line_length": 214, "alphanum_fraction": 0.5933363971, "num_tokens": 5404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.03514484614814641, "lm_q1q2_score": 0.016749318513970195}}
{"text": "﻿//***********************************************************************\r\n// program to analyze bands and report some information on changing\r\n//\t\t\t\t\t\t\t\t\t \r\n//***********************************************************************\r\n// version \r\n// 1.0.1\t17/04/2019\tRémi Saint-Amant\tSome bug correction, add debug\r\n// 1.0.0\t31/01/2019\tRémi Saint-Amant\tCreation\r\n\r\n\r\n//-te -790800 7649400 -711300 7709400 -multi -co \"tiled=YES\" -co \"BLOCKXSIZE=512\" -co \"BLOCKYSIZE=512\" -co \"compress=LZW\" -RGB Natural -of VRT --config GDAL_CACHEMAX 4096 -stats -overview {2,4,8,16} -overwrite \"C:\\Lansat(Fire)\\Fire\\fire.vrt\"  \"C:\\Lansat(Fire)\\Input\\Landsat_2010-2015.vrt\" \"C:\\Lansat(Fire)\\Output\\BC.vrt\"\r\n//\"U:\\GIS\\#documents\\TestCodes\\FireSeverity\\Fires\\Fires.vrt\" \"U:\\GIS\\#documents\\TestCodes\\FireSeverity\\Input\\Landsat_2010-2015.vrt\" \"U:\\GIS\\#documents\\TestCodes\\FireSeverity\\Output\\test.vrt\"\r\n\r\n#include \"stdafx.h\"\r\n//#include \"VisualLeakDetector\\include\\vld.h\"\r\n\r\n#include <float.h>\r\n#include <math.h>\r\n#include <array>\r\n#include <utility>\r\n#include <iostream>\r\n#include <bitset>\r\n#include <boost/dynamic_bitset.hpp>\r\n\r\n#include \"FireSeverity.h\"\r\n#include \"Basic/UtilTime.h\"\r\n#include \"Basic/UtilMath.h\"\r\n#include \"Basic/OpenMP.h\"\r\n#include \"Geomatic/GDALBasic.h\"\r\n#include \"Geomatic/LandsatDataset.h\"\r\n\r\n\r\n\r\n\r\n\r\n#pragma warning(disable: 4275 4251)\r\n#include \"gdal_priv.h\"\r\n\r\n#include \"windows.h\"\r\n#include \"psapi.h\"\r\n\r\n\r\n\r\nusing namespace std;\r\nusing namespace WBSF;\r\nusing namespace WBSF::Landsat;\r\n\r\nstatic const char* version = \"1.0.1\";\r\n\r\nstd::string CFireSeverity::GetDescription()\r\n{\r\n\treturn  std::string(\"FireSeverity version \") + version + \" (\" + _T(__DATE__) + \")\\n\";\r\n}\r\n\r\n\r\nCFireSeverityOption::CFireSeverityOption()\r\n{\r\n\tm_outputType = GDT_Int16;\r\n\tm_scenesSize = Landsat::SCENES_SIZE;\r\n\tm_scenesLoaded = { NOT_INIT ,NOT_INIT };\r\n\tm_scenesTreated = { NOT_INIT ,NOT_INIT };\r\n\tm_buffer = 8;\r\n\tm_bDebug = false;\r\n\r\n\tm_appDescription = \"This software compute fire severity (delta NBR) from Landsat images series\";\r\n\r\n\tstatic const COptionDef OPTIONS[] =\r\n\t{\r\n\t\t\t{ \"-Buffer\", 1, \"nbPixels\", false, \"Set buffer size around fires to do NBR correction. 8 by default. 0 to don't use correction.\" },\r\n\t\t\t{ \"-Debug\",0,\"\",false,\"Output debug information.\"},\r\n\t\t\t{ \"Fires\", 0, \"\", false, \"fires zones (0=no fire, 1=fire) for each years. Bands name must finish with _year.\" },\r\n\t\t\t{ \"srcfile\", 0, \"\", false, \"Input LANDSAT scenes image file path.\" },\r\n\t\t\t{ \"dstfile\", 0, \"\", false, \"Output LANDSAT scenes image file path.\" }\r\n\t};\r\n\r\n\tfor (int i = 0; i < sizeof(OPTIONS) / sizeof(COptionDef); i++)\r\n\t\tAddOption(OPTIONS[i]);\r\n\r\n\t//AddOption(\"-Period\");\r\n\tRemoveOption(\"-ot\");\r\n\tstatic const CIOFileInfoDef IO_FILE_INFO[] =\r\n\t{\r\n\t\t{ \"Fire\", \"f\", \"\", \"\", \"\", \"File of fires zones (0=no fire, 1=fire) for each years. Bands name must finish with _year.\" },\r\n\t\t{ \"LANDSAT\", \"src1file\", \"NbScenes\", \"ScenesSize(9)\", \"B1: Landsat band 1|B2: Landsat band 2|B3: Landsat band 3|B4: Landsat band 4|B5: Landsat band 5|B6: Landsat band 6|B7: Landsat band 7|QA: Image quality|JD: Date(Julian day 1970)|... for each scene\" },\r\n\t\t{ \"Output\", \"dstfile\", \"Nb scenes processed\", \"\", \"DeltaNBR|zScore|FireSeverity\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < sizeof(IO_FILE_INFO) / sizeof(CIOFileInfoDef); i++)\r\n\t\tAddIOFileInfo(IO_FILE_INFO[i]);\r\n\r\n}\r\n\r\nERMsg CFireSeverityOption::ProcessOption(int& i, int argc, char* argv[])\r\n{\r\n\tERMsg msg;\r\n\r\n\r\n\tif (IsEqual(argv[i], \"-Buffer\"))\r\n\t{\r\n\t\tm_buffer = atoi(argv[++i]);\r\n\t\tif (m_buffer > 100)\r\n\t\t\tmsg.ajoute(\"Invalid buffer. Buffer must be smaller than 100.\");\r\n\t}\r\n\telse if (IsEqual(argv[i], \"-Debug\"))\r\n\t{\r\n\t\tm_bDebug = true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\t//Look to see if it's a know base option\r\n\t\tmsg = CBaseOptions::ProcessOption(i, argc, argv);\r\n\t}\r\n\r\n\treturn msg;\r\n}\r\n\r\nERMsg CFireSeverityOption::ParseOption(int argc, char* argv[])\r\n{\r\n\tERMsg msg = CBaseOptions::ParseOption(argc, argv);\r\n\r\n\tASSERT(NB_FILE_PATH == 3);\r\n\tif (msg && m_filesPath.size() != NB_FILE_PATH)\r\n\t{\r\n\t\tmsg.ajoute(\"ERROR: Invalid argument line. 3 files are needed: the fire series, the LANDSAT images series and the destination image.\");\r\n\t\tmsg.ajoute(\"Argument found: \");\r\n\t\tfor (size_t i = 0; i < m_filesPath.size(); i++)\r\n\t\t\tmsg.ajoute(\"   \" + to_string(i + 1) + \"- \" + m_filesPath[i]);\r\n\t}\r\n\r\n\t\r\n\t\r\n\r\n\t\r\n\treturn msg;\r\n}\r\n\r\n\r\n//***********************************************************************\r\n\r\n\r\nERMsg CFireSeverity::OpenAll(CLandsatDataset& landsatDS, CGDALDatasetEx& maskDS, CGDALDatasetEx& fireDS, CGDALDatasetEx& outputDS, CGDALDatasetEx& debugDS)\r\n{\r\n\tERMsg msg;\r\n\r\n\tif (!m_options.m_bQuiet)\r\n\t{\r\n\t\tcout << endl << \"Open input image...\" << endl;\r\n\t}\r\n\r\n\tmsg = landsatDS.OpenInputImage(m_options.m_filesPath[CFireSeverityOption::LANDSAT_FILE_PATH], m_options);\r\n\r\n\tif (msg && landsatDS.GetNbScenes() < 3)\r\n\t\tmsg.ajoute(\"Input Landsat series need at least 3 scenes\");\r\n\r\n\tif (msg)\r\n\t\tlandsatDS.UpdateOption(m_options);\r\n\r\n\tif (msg)\r\n\t{\r\n\t\tconst std::vector<CTPeriod>& scenesPeriod = landsatDS.GetScenePeriod();\r\n\t\tCTPeriod p = m_options.m_period;//period to load\r\n\t\tset<size_t> toLoad;\r\n\r\n\t\tfor (size_t s = 0; s < landsatDS.GetNbScenes(); s++)\r\n\t\t{\r\n\t\t\tif (p.IsIntersect(scenesPeriod[s]))\r\n\t\t\t\ttoLoad.insert(s);\r\n\t\t}\r\n\r\n\t\tsize_t nb_input_scenes = 0;\r\n\t\tif (!toLoad.empty())\r\n\t\t{\r\n\t\t\tm_options.m_scenesLoaded[0] = *toLoad.begin();\r\n\t\t\tm_options.m_scenesLoaded[1] = *toLoad.rbegin();\r\n\t\t}\r\n\r\n\t\tif (m_options.m_periodTreated.IsInit())\r\n\t\t{\r\n\t\t\tconst std::vector<CTPeriod>& scenesPeriod = landsatDS.GetScenePeriod();\r\n\t\t\tCTPeriod p = m_options.m_periodTreated;\r\n\r\n\t\t\tset<size_t> selected;\r\n\r\n\t\t\tfor (size_t s = 0; s < scenesPeriod.size(); s++)\r\n\t\t\t{\r\n\t\t\t\tif (s > 1 && (scenesPeriod[s].End() < scenesPeriod[s - 1].Begin()))\r\n\t\t\t\t\tmsg.ajoute(\"Scenes of the input Landsat images (\" + GetFileName(m_options.m_filesPath[CFireSeverityOption::LANDSAT_FILE_PATH]) + \") are not chronologically ordered.\");\r\n\r\n\t\t\t\tif (p.IsIntersect(scenesPeriod[s]))\r\n\t\t\t\t\tselected.insert(s);\r\n\t\t\t}\r\n\r\n\t\t\tif (!selected.empty())\r\n\t\t\t{\r\n\t\t\t\tm_options.m_scenesTreated[0] = *selected.begin();\r\n\t\t\t\tm_options.m_scenesTreated[1] = *selected.rbegin();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tmsg.ajoute(\"No input scenes intersect -PeriodTrait (\" + m_options.m_periodTreated.GetFormatedString(\"%1 %2\", \"%F\") + \").\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tif (m_options.m_scenesTreated[0] == NOT_INIT)\r\n\t\t\tm_options.m_scenesTreated[0] = 0;\r\n\r\n\t\tif (m_options.m_scenesTreated[1] == NOT_INIT)\r\n\t\t\tm_options.m_scenesTreated[1] = landsatDS.GetNbScenes() - 1;\r\n\r\n\t\tif (m_options.m_scenesTreated[0] >= landsatDS.GetNbScenes() || m_options.m_scenesTreated[1] >= landsatDS.GetNbScenes())\r\n\t\t\tmsg.ajoute(\"Scenes {\" + to_string(m_options.m_scenesTreated[0] + 1) + \", \" + to_string(m_options.m_scenesTreated[1] + 1) + \"} must be in range {1, \" + to_string(landsatDS.GetNbScenes()) + \"}\");\r\n\r\n\t\tif (m_options.m_scenesTreated[0] > m_options.m_scenesTreated[1])\r\n\t\t\tmsg.ajoute(\"First scene (\" + to_string(m_options.m_scenesTreated[0] + 1) + \") must be smaller or equal to the last scene (\" + to_string(m_options.m_scenesTreated[1] + 1) + \")\");\r\n\r\n\t}\r\n\r\n\tif (!msg)\r\n\t\treturn msg;\r\n\r\n\t//update period from scene\r\n\tsize_t nbSceneLoaded = m_options.m_scenesLoaded[1] - m_options.m_scenesLoaded[0] + 1;\r\n\tsize_t nbScenedProcess = m_options.m_scenesTreated[1] - m_options.m_scenesTreated[0] + 1;\r\n\r\n\r\n\r\n\tCTPeriod loadedPeriod;\r\n\tCTPeriod processPeriod;\r\n\tconst std::vector<CTPeriod>& p = landsatDS.GetScenePeriod();\r\n\r\n\tASSERT(m_options.m_scenesTreated[0] < p.size());\r\n\tASSERT(m_options.m_scenesTreated[1] < p.size());\r\n\r\n\tfor (size_t i = 0; i < p.size(); i++)\r\n\t{\r\n\t\tif (i >= m_options.m_scenesLoaded[0] && i <= m_options.m_scenesLoaded[1])\r\n\t\t\tloadedPeriod += p[i];\r\n\r\n\t\tif (i >= m_options.m_scenesTreated[0] && i <= m_options.m_scenesTreated[1])\r\n\t\t\tprocessPeriod += p[i];\r\n\t}\r\n\r\n\tif (!m_options.m_bQuiet)\r\n\t{\r\n\t\tCGeoExtents extents = landsatDS.GetExtents();\r\n\t\tCProjectionPtr pPrj = landsatDS.GetPrj();\r\n\t\tstring prjName = pPrj ? pPrj->GetName() : \"Unknown\";\r\n\r\n\t\tif (m_options.m_period.IsInit())\r\n\t\t\tcout << \"    User's Input loading period  = \" << m_options.m_period.GetFormatedString() << endl;\r\n\r\n\t\tif (m_options.m_periodTreated.IsInit())\r\n\t\t\tcout << \"    User's Input treating period = \" << m_options.m_periodTreated.GetFormatedString() << endl;\r\n\r\n\t\tcout << \"    Size           = \" << landsatDS->GetRasterXSize() << \" cols x \" << landsatDS->GetRasterYSize() << \" rows x \" << landsatDS.GetRasterCount() << \" bands\" << endl;\r\n\t\tcout << \"    Extents        = X:{\" << ToString(extents.m_xMin) << \", \" << ToString(extents.m_xMax) << \"}  Y:{\" << ToString(extents.m_yMin) << \", \" << ToString(extents.m_yMax) << \"}\" << endl;\r\n\t\tcout << \"    Projection     = \" << prjName << endl;\r\n\t\tcout << \"    NbBands        = \" << landsatDS.GetRasterCount() << endl;\r\n\t\tcout << \"    Scene size     = \" << landsatDS.GetSceneSize() << endl;\r\n\t\tcout << \"    Entire period  = \" << landsatDS.GetPeriod().GetFormatedString() << \" (nb scenes = \" << landsatDS.GetNbScenes() << \")\" << endl;\r\n\t\tcout << \"    Loaded period  = \" << loadedPeriod.GetFormatedString() << \" (nb scenes = \" << nbSceneLoaded << \")\" << endl;\r\n\t\t//cout << \"    Treated period = \" << processPeriod.GetFormatedString() << \" (nb scenes = \" << nbScenedProcess << \")\" << endl;\r\n\t}\r\n\r\n\r\n\r\n\tif (!m_options.m_period.IsIntersect(processPeriod))\r\n\t\tmsg.ajoute(\"Input period and process period does not intersect. Verify period or scenes options\");\r\n\r\n\r\n\tif (msg && !m_options.m_maskName.empty())\r\n\t{\r\n\t\tif (!m_options.m_bQuiet)\r\n\t\t\tcout << \"Open mask image...\" << endl;\r\n\r\n\t\tmsg += maskDS.OpenInputImage(m_options.m_maskName);\r\n\t}\r\n\r\n\tif (msg)\r\n\t\tmsg = fireDS.OpenInputImage(m_options.m_filesPath[CFireSeverityOption::FIRE_FILE_PATH], m_options);\r\n\r\n\r\n\tif (msg && m_options.m_bCreateImage)\r\n\t{\r\n\t\tif (!m_options.m_bQuiet)\r\n\t\t\tcout << \"Open output images \" << endl;\r\n\t\t//cout << \"Open output images \" << \" x(\" << m_options.m_extents.m_xSize << \" C x \" << m_options.m_extents.m_ySize << \" R x \" << m_options.m_nbBands << \" bands) with \" << m_options.m_CPU << \" threads...\" << endl;\r\n\r\n\r\n\t\tstring filePath = m_options.m_filesPath[CFireSeverityOption::OUTPUT_FILE_PATH];\r\n\t\tCFireSeverityOption options = m_options;\r\n\t\toptions.m_nbBands = NB_OUTPUTS * fireDS.GetRasterCount();\r\n\r\n\t\tfor (size_t zz = 0; zz < fireDS.GetRasterCount(); zz++)\r\n\t\t{\r\n\t\t\tstring title = GetFileTitle(fireDS.GetInternalName(zz));\r\n\t\t\tif (title.length() > 4)\r\n\t\t\t{\r\n\t\t\t\tstring sYear = title.substr(title.size() - 4);\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_dNBR.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_zScore1.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_zScore2.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_FireS.tif|\";\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tmsg += outputDS.CreateImage(filePath, options);\r\n\t}\r\n\r\n\tif (msg && m_options.m_bDebug)\r\n\t{\r\n\t\tif (!m_options.m_bQuiet )\r\n\t\t\tcout << \"Open debug images \" << endl;\r\n\t\t//cout << \"Open output images \" << \" x(\" << m_options.m_extents.m_xSize << \" C x \" << m_options.m_extents.m_ySize << \" R x \" << m_options.m_nbBands << \" bands) with \" << m_options.m_CPU << \" threads...\" << endl;\r\n\r\n\r\n\t\tstring filePath = m_options.m_filesPath[CFireSeverityOption::OUTPUT_FILE_PATH];\r\n\t\tSetFileTitle(filePath, GetFileTitle(filePath) + \"_debug\");\r\n\t\tCFireSeverityOption options = m_options;\r\n\t\toptions.m_nbBands = NB_DEBUGS * fireDS.GetRasterCount();\r\n\r\n\t\tfor (size_t zz = 0; zz < fireDS.GetRasterCount(); zz++)\r\n\t\t{\r\n\t\t\tstring title = GetFileTitle(fireDS.GetInternalName(zz));\r\n\t\t\tif (title.length() > 4)\r\n\t\t\t{\r\n\t\t\t\tstring sYear = title.substr(title.size() - 4);\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_nbMissing.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_dNBR0.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_offset.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T1_B3.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T1_B4.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T1_B5.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T1_B7.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T3_B3.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T3_B4.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T3_B5.tif|\";\r\n\t\t\t\toptions.m_VRTBandsName += GetFileTitle(filePath) + \"_\" + sYear + \"_T3_B7.tif|\";\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tmsg += debugDS.CreateImage(filePath, options);\r\n\t}\r\n\r\n\treturn msg;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\nERMsg CFireSeverity::Execute()\r\n{\r\n\tERMsg msg;\r\n\r\n\tif (!m_options.m_bQuiet)\r\n\t{\r\n\t\tcout << \"Output: \" << m_options.m_filesPath[CFireSeverityOption::OUTPUT_FILE_PATH] << endl;\r\n\t\tcout << \"From:   \" << m_options.m_filesPath[CFireSeverityOption::LANDSAT_FILE_PATH] << endl;\r\n\t\tcout << \"Fires:  \" << m_options.m_filesPath[CFireSeverityOption::FIRE_FILE_PATH] << endl;\r\n\r\n\t\tif (!m_options.m_maskName.empty())\r\n\t\t\tcout << \"Mask:   \" << m_options.m_maskName << endl;\r\n\t}\r\n\r\n\tGDALAllRegister();\r\n\r\n\tCLandsatDataset inputDS;\r\n\tCGDALDatasetEx maskDS;\r\n\tCGDALDatasetEx outputDS;\r\n\tCGDALDatasetEx fireDS;\r\n\tCGDALDatasetEx debugDS;\r\n\r\n\tmsg = OpenAll(inputDS, maskDS, fireDS, outputDS, debugDS);\r\n\r\n\r\n\tFireBitset fires;\r\n\tvector <bool> bHaveFire;\r\n\tif (msg)\r\n\t{\r\n\t\tmsg += LoadFires(inputDS, fireDS, fires, bHaveFire);\r\n\t}\r\n\r\n\tif (msg)\r\n\t{\r\n\t\tPROCESS_MEMORY_COUNTERS memCounter;\r\n\t\tif (!m_options.m_bQuiet)\r\n\t\t{\r\n\t\t\tGetProcessMemoryInfo(GetCurrentProcess(), &memCounter, sizeof(memCounter));\r\n\t\t\tcout << \"Memory used: \" << memCounter.WorkingSetSize / (1024 * 1024) << \" Mo\" << endl;\r\n\t\t}\r\n\r\n\t\t//size_t nbScenedProcess = m_options.m_scenesTreated[1] - m_options.m_scenesTreated[0] + 1;\r\n\t\t//size_t nbScenedLoaded = m_options.m_scenesLoaded[1] - m_options.m_scenesLoaded[0] + 1;\r\n\r\n\t\tCBandsHolderMT bandHolder(1, m_options.m_memoryLimit, m_options.m_IOCPU, m_options.m_BLOCK_THREADS);\r\n\r\n\t\tif (maskDS.IsOpen())\r\n\t\t\tbandHolder.SetMask(maskDS.GetSingleBandHolder(), m_options.m_maskDataUsed);\r\n\r\n\t\tmsg += bandHolder.Load(inputDS, m_options.m_bQuiet, m_options.m_extents, m_options.m_period);\r\n\r\n\t\tif (!msg)\r\n\t\t\treturn msg;\r\n\r\n\r\n\t\tCGeoExtents extents = bandHolder.GetExtents();\r\n\t\tvector<pair<int, int>> XYindex = extents.GetBlockList();\r\n\t\tsize_t nbPixels = extents.m_xSize*extents.m_ySize;\r\n\r\n\t\tBufferStat bufferStat(fires.size());\r\n\t\tif (m_options.m_buffer > 0)\r\n\t\t{\r\n\t\t\tif (!m_options.m_bQuiet)\r\n\t\t\t\tcout << \"Compute buffer statistics with \" << m_options.m_BLOCK_THREADS << \" block threads (\" << m_options.BLOCK_CPU() << \" threads/block)\" << endl;\r\n\r\n\t\t\tm_options.ResetBar((size_t)fires.size()*nbPixels);\r\n\r\n\t\t\t//pass 1 : find dates\r\n\t\t\tomp_set_nested(1);\r\n#pragma omp parallel for schedule(static, 1) num_threads(m_options.m_BLOCK_THREADS) if (m_options.m_bMulti)\r\n\t\t\tfor (__int64 b = 0; b < (__int64)XYindex.size(); b++)\r\n\t\t\t{\r\n\t\t\t\tsize_t thread = omp_get_thread_num();\r\n\t\t\t\tsize_t xBlock = XYindex[b].first;\r\n\t\t\t\tsize_t yBlock = XYindex[b].second;\r\n\r\n\t\t\t\tif (bHaveFire[b])//there is some fire in this block?\r\n\t\t\t\t{\r\n\t\t\t\t\tReadBlock(xBlock, yBlock, bandHolder[thread]);\r\n\t\t\t\t\tComputeBufferStat(xBlock, yBlock, bandHolder[thread], fires, bufferStat);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tCGeoSize blockSize = extents.GetBlockSize((int)xBlock, (int)yBlock);\r\n#pragma omp atomic\t\t\r\n\t\t\t\t\tm_options.m_xx += fires.size()* blockSize.m_x*blockSize.m_y;\r\n\t\t\t\t\tm_options.UpdateBar();\r\n\t\t\t\t}\r\n\t\t\t}//for all blocks\r\n\t\t}\r\n\r\n\t\t//pass 2 : compute dNBR and fire severity\r\n\t\tif (!m_options.m_bQuiet)\r\n\t\t\tcout << \"Compute fire severity with \" << m_options.m_BLOCK_THREADS << \" block threads (\" << m_options.BLOCK_CPU() << \" threads/block)\" << endl;\r\n\r\n\t\tm_options.ResetBar((size_t)fires.size()*nbPixels);\r\n\r\n\t\tomp_set_nested(1);\r\n#pragma omp parallel for schedule(static, 1) num_threads(m_options.m_BLOCK_THREADS) if (m_options.m_bMulti)\r\n\t\tfor (__int64 b = 0; b < (__int64)XYindex.size(); b++)\r\n\t\t{\r\n\t\t\tsize_t thread = omp_get_thread_num();\r\n\t\t\tsize_t xBlock = XYindex[b].first;\r\n\t\t\tsize_t yBlock = XYindex[b].second;\r\n\r\n\t\t\tif (bHaveFire[b])//there is some fire in this block?\r\n\t\t\t{\r\n\t\t\t\tOutputData output;\r\n\t\t\t\tDebugData debug;\r\n\t\t\t\tReadBlock(xBlock, yBlock, bandHolder[thread]);\r\n\t\t\t\tProcessBlock(xBlock, yBlock, bandHolder[thread], fires, bufferStat, output, debug);\r\n\t\t\t\tWriteBlock(xBlock, yBlock, output, debug, outputDS, debugDS);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tCGeoSize blockSize = extents.GetBlockSize((int)xBlock, (int)yBlock);\r\n#pragma omp atomic\t\t\r\n\t\t\t\tm_options.m_xx += fires.size()* blockSize.m_x*blockSize.m_y;\r\n\t\t\t\tm_options.UpdateBar();\r\n\t\t\t}\r\n\t\t}//for all blocks\r\n\r\n\t\t//close inputs and outputs\r\n\t\tCloseAll(inputDS, maskDS, fireDS, outputDS, debugDS);\r\n\r\n\t\tGetProcessMemoryInfo(GetCurrentProcess(), &memCounter, sizeof(memCounter));\r\n\t\tcout << \"Memory used: \" << memCounter.WorkingSetSize / (1024 * 1024) << \" Mo\" << endl;\r\n\t}\r\n\r\n\treturn msg;\r\n}\r\n\r\n\r\nvoid CFireSeverity::ReadBlock(size_t xBlock, size_t yBlock, CBandsHolder& bandHolder)\r\n{\r\n#pragma omp critical(ReadBlockIO)\r\n\t{\r\n\t\tm_options.m_timerRead.Start();\r\n\t\tbandHolder.LoadBlock((int)xBlock, (int)yBlock);\r\n\t\tm_options.m_timerRead.Stop();\r\n\t}\r\n}\r\n\r\nERMsg CFireSeverity::LoadFires(CLandsatDataset& lansatDS, CGDALDatasetEx& fireDS, FireBitset& fires, std::vector <bool>& bHaveFire)\r\n{\r\n\tERMsg msg;\r\n\r\n\r\n\r\n\tif (msg)\r\n\t{\r\n\t\tCBandsHolderMT bandHolder = CBandsHolderMT(1, m_options.m_memoryLimit, m_options.m_IOCPU, 2);\r\n\t\tmsg += bandHolder.Load(fireDS, m_options.m_bQuiet, m_options.m_extents, m_options.m_period);\r\n\r\n\t\tif (msg)\r\n\t\t{\r\n\t\t\tCGeoExtents extents = bandHolder.GetExtents();\r\n\r\n\t\t\tfires.resize(bandHolder.GetRasterCount());\r\n\t\t\tfor (size_t i = 0; i < fires.size(); i++)\r\n\t\t\t{\r\n\t\t\t\tint year = GetYear(fireDS.GetInternalName(i));\r\n\t\t\t\tif (year != -999)\r\n\t\t\t\t{\r\n\t\t\t\t\tfires[i].first[T_JD] = CBaseOptions::GetTRefIndex(CBaseOptions::JDAY1970, CTRef(year, JANUARY, DAY_01));\r\n\t\t\t\t\tfires[i].first[T_Z] = FindLayerIndex(lansatDS, year);\r\n\t\t\t\t\tif (fires[i].first[T_Z] < lansatDS.GetNbScenes())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfires[i].second[T_FIRE].resize((size_t)extents.m_xSize*extents.m_ySize);\r\n\t\t\t\t\t\tif (m_options.m_buffer > 0)\r\n\t\t\t\t\t\t\tfires[i].second[T_BUFFER].resize((size_t)extents.m_xSize*extents.m_ySize);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmsg.ajoute(\"Unable to find year (\" + to_string(year) + \") in the input image\");\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\t\tmsg.ajoute(\"Error: file name of fire file must end with 4 digits year (YYYY)\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (msg)\r\n\t\t\t{\r\n\t\t\t\tvector<pair<int, int>> XYindex = extents.GetBlockList();\r\n\t\t\t\tbHaveFire.resize(XYindex.size(), false);\r\n\t\t\t\tif (!m_options.m_bQuiet)\r\n\t\t\t\t\tcout << \"Load fires with \" << m_options.m_CPU << \" threads\" << endl;\r\n\r\n\t\t\t\tsize_t nbPixels = extents.m_xSize*extents.m_ySize;\r\n\t\t\t\tm_options.ResetBar((size_t)fires.size()*nbPixels * 2);\r\n\r\n\t\t\t\tCTimer timerRead(true);\r\n\t\t\t\t//pass 1 : load fire pixel\r\n\t\t\t\tomp_set_nested(1);\r\n#pragma omp parallel for schedule(static, 1) num_threads(2) if (m_options.m_bMulti)\r\n\t\t\t\tfor (__int64 b = 0; b < (__int64)XYindex.size(); b++)\r\n\t\t\t\t{\r\n\r\n\t\t\t\t\tsize_t thread = omp_get_thread_num();\r\n\t\t\t\t\tsize_t xBlock = XYindex[b].first;\r\n\t\t\t\t\tsize_t yBlock = XYindex[b].second;\r\n\t\t\t\t\tCGeoRectIndex index = extents.GetBlockRect((int)xBlock, (int)yBlock);\r\n\t\t\t\t\tCGeoSize blockSize = extents.GetBlockSize((int)xBlock, (int)yBlock);\r\n\r\n#pragma omp critical(LOAD_FIRES)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbandHolder[thread].LoadBlock((int)xBlock, (int)yBlock);\r\n\t\t\t\t\t}\r\n\r\n#pragma omp critical(READ_FIRES)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (!bandHolder[thread].IsEmpty())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tbHaveFire[b] = true;\r\n\t\t\t\t\t\t\tCRasterWindow fire_window = bandHolder[thread].GetWindow();\r\n\t\t\t\t\t\t\tASSERT(fire_window.GetNbScenes() >= fires.size());\r\n#pragma omp parallel for num_threads(m_options.m_CPU) if (m_options.m_bMulti)\r\n\t\t\t\t\t\t\tfor (__int64 zz = 0; zz < (__int64)fires.size(); zz++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tfor (size_t y = 0; y < blockSize.m_y; y++)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tfor (size_t x = 0; x < blockSize.m_x; x++)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tsize_t xy2 = ((size_t)index.m_y + y)* extents.m_xSize + index.m_x + x;\r\n\t\t\t\t\t\t\t\t\t\tif (fire_window[zz]->IsValid((int)x, (int)y))\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tbool bSet = fire_window[zz]->at((int)x, (int)y) > 0;\r\n\t\t\t\t\t\t\t\t\t\t\tfires[zz].second[T_FIRE].set(xy2, bSet);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}//x\r\n\t\t\t\t\t\t\t\t}//y\r\n\t\t\t\t\t\t\t}//zz\r\n\t\t\t\t\t\t}//block not empty\r\n\r\n#pragma omp atomic\r\n\t\t\t\t\t\tm_options.m_xx += fires.size()*blockSize.m_x*blockSize.m_y;\r\n\t\t\t\t\t\tm_options.UpdateBar();\r\n\t\t\t\t\t}//critical\r\n\t\t\t\t}//\r\n\r\n\t\t\t\t//set buffer if any\r\n\t\t\t\tif (m_options.m_buffer > 0)\r\n\t\t\t\t{\r\n#pragma omp parallel for num_threads(m_options.m_CPU) if (m_options.m_bMulti)\r\n\t\t\t\t\tfor (__int64 zz = 0; zz < (__int64)fires.size(); zz++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (size_t y = 0; y < extents.m_ySize; y++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (size_t x = 0; x < extents.m_xSize; x++)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tsize_t xy = y * extents.m_xSize + x;\r\n\t\t\t\t\t\t\t\tif (fires[zz].second[T_FIRE].test(xy))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tfor (size_t yy = 0; (yy < 2 * m_options.m_buffer + 1); yy++)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tfor (size_t xx = 0; (xx < 2 * m_options.m_buffer + 1); xx++)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tsize_t yyy = y + yy - m_options.m_buffer;\r\n\t\t\t\t\t\t\t\t\t\t\tsize_t xxx = x + xx - m_options.m_buffer;\r\n\t\t\t\t\t\t\t\t\t\t\tif (yyy < (size_t)extents.m_ySize && xxx < (size_t)extents.m_xSize)\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\tsize_t xy2 = yyy * extents.m_xSize + xxx;\r\n\t\t\t\t\t\t\t\t\t\t\t\tif (!fires[zz].second[T_FIRE].test(xy2))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tfires[zz].second[T_BUFFER].set(xy2, true);\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}//xx\r\n\t\t\t\t\t\t\t\t\t}//yy\r\n\t\t\t\t\t\t\t\t}//if fire\r\n\t\t\t\t\t\t\t}//x\r\n#pragma omp atomic\r\n\t\t\t\t\t\t\tm_options.m_xx += extents.m_xSize;\r\n\t\t\t\t\t\t\tm_options.UpdateBar();\r\n\r\n\t\t\t\t\t\t}//y\r\n\t\t\t\t\t}//zz\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tm_options.m_xx += fires.size()*nbPixels;\r\n\t\t\t\t\tm_options.UpdateBar();\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttimerRead.Stop();\r\n\r\n\t\t\t\tif (!m_options.m_bQuiet)\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << endl << \"Time to load fires = \" << SecondToDHMS(timerRead.Elapsed()) << endl;\r\n\t\t\t\t\tcout << \"Fire pixels \" << endl;\r\n\t\t\t\t\tfor (__int64 zz = 0; zz < (__int64)fires.size(); zz++)\r\n\t\t\t\t\t\tcout << zz + 1 << \":\" << fires[zz].second[T_FIRE].count() << \" (\" << fires[zz].second[T_BUFFER].count() << \")\" << endl;\r\n\t\t\t\t}\r\n\r\n\t\t\t}//if msg\r\n\t\t}//if msg\r\n\t}//if msg\r\n\r\n\treturn msg;\r\n}\r\n\r\nsize_t CFireSeverity::FindLayerIndex(CLandsatDataset& lansatDS, int year)\r\n{\r\n\tsize_t index = NOT_INIT;\r\n\tconst std::vector<CTPeriod>& periods = lansatDS.GetScenePeriod();\r\n\tfor (size_t z = 0; z < periods.size() && index == NOT_INIT; z++)\r\n\t{\r\n\t\tif (periods[z].GetFirstYear() == year)\r\n\t\t\tindex = z;\r\n\t}\r\n\r\n\treturn index;\r\n}\r\n\r\nint CFireSeverity::GetYear(const std::string& name)\r\n{\r\n\tint year = -999;\r\n\r\n\tstring title = GetFileTitle(name);\r\n\tif (title.length() > 4)\r\n\t{\r\n\t\tstring sYear = title.substr(title.length() - 4);\r\n\t\tyear = stoi(sYear);\r\n\t}\r\n\t\r\n\treturn year;\r\n}\r\n\r\n\r\nsize_t CFireSeverity::GetPrevious(size_t z, size_t x, size_t y, const CLandsatWindow& window)\r\n{\r\n\tsize_t previous = NOT_INIT;\r\n\tfor (size_t zz = z - 1; zz < window.GetNbScenes() && previous == NOT_INIT; zz--)\r\n\t\tif (window.GetPixel(zz, (int)x, (int)y).IsValid())\r\n\t\t\tprevious = zz;\r\n\r\n\treturn previous;\r\n}\r\n\r\nsize_t CFireSeverity::GetNext(size_t z, size_t x, size_t y, const CLandsatWindow& window)\r\n{\r\n\tsize_t next = NOT_INIT;\r\n\tfor (size_t zz = z + 1; zz < window.GetNbScenes() && next == NOT_INIT; zz++)\r\n\t\tif (window.GetPixel(zz, (int)x, (int)y).IsValid())\r\n\t\t\tnext = zz;\r\n\r\n\treturn next;\r\n}\r\n\r\n\r\nvoid CFireSeverity::ComputeBufferStat(size_t xBlock, size_t yBlock, const CBandsHolder& bandHolder, const FireBitset& fires, BufferStat& bufferStat)\r\n{\r\n\tsize_t nbScenesLoaded = m_options.m_scenesLoaded[1] - m_options.m_scenesLoaded[0] + 1;\r\n\tsize_t nbScenesProcess = m_options.m_scenesTreated[1] - m_options.m_scenesTreated[0] + 1;\r\n\tsize_t nbScenes = bandHolder.GetNbScenes();\r\n\tsize_t sceneSize = bandHolder.GetSceneSize();\r\n\tCGeoExtents extents = bandHolder.GetExtents();\r\n\tCGeoRectIndex index = extents.GetBlockRect((int)xBlock, (int)yBlock);\r\n\tCGeoSize blockSize = extents.GetBlockSize((int)xBlock, (int)yBlock);\r\n\r\n\tASSERT(!bandHolder.IsEmpty());\r\n\r\n\tCLandsatWindow window = bandHolder.GetWindow();\r\n\r\n\r\n\t//compute offset when buffer\r\n#pragma omp parallel for num_threads( m_options.BLOCK_CPU()) if (m_options.m_bMulti)\r\n\tfor (__int64 zz = 0; zz < (__int64)fires.size(); zz++)\r\n\t{\r\n\t\tsize_t z = fires[zz].first[T_Z];\r\n\t\t__int16 JD_base = __int16(fires[zz].first[T_JD]);\r\n\t\t//find dates\r\n\t\tfor (size_t y = 0; y < blockSize.m_y; y++)\r\n\t\t{\r\n\t\t\tfor (size_t x = 0; x < blockSize.m_x; x++)\r\n\t\t\t{\r\n\t\t\t\tsize_t xy = y * blockSize.m_x + x;\r\n\t\t\t\tsize_t xy2 = ((size_t)index.m_y + y)* extents.m_xSize + index.m_x + x;\r\n\r\n\t\t\t\tif (fires[zz].second[T_BUFFER].test(xy2))\r\n\t\t\t\t{\r\n\t\t\t\t\tsize_t z0 = GetPrevious(z, x, y, window);\r\n\t\t\t\t\tsize_t z2 = GetNext(z, x, y, window);\r\n\t\t\t\t\tif (z0 != NOT_INIT && z2 != NOT_INIT)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tarray <CLandsatPixel, 2> p;\r\n\t\t\t\t\t\tp[0] = window.GetPixel(z0, (int)x, (int)y);\r\n\t\t\t\t\t\tp[1] = window.GetPixel(z2, (int)x, (int)y);\r\n\r\n\t\t\t\t\t\t//buffer is variable that are share over many block at the same time\r\n\t\t\t\t\t\t//this variable must be protect when writing\r\n#pragma omp critical(BUFFER_STAT)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tpair<__int16, __int16> date = make_pair(p[0][I_JD], p[1][I_JD]);\r\n\t\t\t\t\t\t\tdouble dNBR = GetDeltaNBR(JD_base, p);\r\n\t\t\t\t\t\t\tbufferStat[zz][date] += dNBR;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}//if buffer\r\n\t\t\t\t}//is init\r\n\t\t\t}//x\r\n\t\t}//y\r\n\r\n\r\n#pragma omp atomic\t\t\r\n\t\tm_options.m_xx += (size_t)blockSize.m_x*blockSize.m_y;\r\n\r\n\t\tm_options.UpdateBar();\r\n\r\n\t}//zz\r\n\r\n}\r\n\r\n//Get input image reference\r\nvoid CFireSeverity::ProcessBlock(size_t xBlock, size_t yBlock, const CBandsHolder& bandHolder, const FireBitset& fires, const BufferStat& bufferStat, OutputData& output, DebugData& debug)\r\n{\r\n\tsize_t nbScenesLoaded = m_options.m_scenesLoaded[1] - m_options.m_scenesLoaded[0] + 1;\r\n\tsize_t nbScenesProcess = m_options.m_scenesTreated[1] - m_options.m_scenesTreated[0] + 1;\r\n\tsize_t nbScenes = bandHolder.GetNbScenes();\r\n\tsize_t sceneSize = bandHolder.GetSceneSize();\r\n\tCGeoExtents extents = bandHolder.GetExtents();\r\n\tCGeoRectIndex index = extents.GetBlockRect((int)xBlock, (int)yBlock);\r\n\tCGeoSize blockSize = extents.GetBlockSize((int)xBlock, (int)yBlock);\r\n\r\n\tif (bandHolder.IsEmpty())\r\n\t{\r\n#pragma omp atomic\t\t\r\n\t\tm_options.m_xx += (nbScenesProcess + nbScenesLoaded)* blockSize.m_x*blockSize.m_y;\r\n\t\tm_options.UpdateBar();\r\n\r\n\t\treturn;\r\n\t}\r\n\r\n\t//allocate process memory and load data\r\n\tCLandsatWindow window = bandHolder.GetWindow();\r\n\r\n\t__int16 noData = (__int16)::GetDefaultNoData(GDT_Int16);\r\n\toutput.resize(fires.size());\r\n\tfor (size_t i = 0; i < output.size(); i++)\r\n\t{\r\n\t\tfor (size_t j = 0; j < output[i].size(); j++)\r\n\t\t\toutput[i][j].resize(blockSize.m_x*blockSize.m_y, noData);\r\n\t}\r\n\r\n\tif (m_options.m_bDebug)\r\n\t{\r\n\t\t\r\n\t\t__int16 noData = (__int16)::GetDefaultNoData(GDT_Int16);\r\n\t\tdebug.resize(fires.size());\r\n\t\tfor (size_t i = 0; i < debug.size(); i++)\r\n\t\t{\r\n\t\t\tfor (size_t j = 0; j < debug[i].size(); j++)\r\n\t\t\t\tdebug[i][j].resize(blockSize.m_x*blockSize.m_y, noData);\r\n\t\t}\r\n\t}\r\n\t\r\n\t//compute dNBR and apply offset when buffer\r\n#pragma omp parallel for num_threads( m_options.BLOCK_CPU()) if (m_options.m_bMulti)\r\n\tfor (__int64 zz = 0; zz < (__int64)fires.size(); zz++)\r\n\t{\r\n\t\tsize_t z = fires[zz].first[T_Z];\r\n\t\t__int16 JD_base = __int16(fires[zz].first[T_JD]);\r\n\r\n\t\t//find dates\r\n\t\tfor (size_t y = 0; y < blockSize.m_y; y++)\r\n\t\t{\r\n\t\t\tfor (size_t x = 0; x < blockSize.m_x; x++)\r\n\t\t\t{\r\n\t\t\t\tsize_t xy = y * blockSize.m_x + x;\r\n\t\t\t\tsize_t xy2 = ((size_t)index.m_y + y)* extents.m_xSize + index.m_x + x;\r\n\r\n\t\t\t\tif (fires[zz].second[T_FIRE].test(xy2))\r\n\t\t\t\t{\r\n\t\t\t\t\tsize_t z0 = GetPrevious(z, x, y, window);\r\n\t\t\t\t\tsize_t z2 = GetNext(z, x, y, window);\r\n\t\t\t\t\tif (z0 != NOT_INIT && z2 != NOT_INIT)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tarray <CLandsatPixel, 2> p;\r\n\t\t\t\t\t\tp[0] = window.GetPixel(z0, (int)x, (int)y);\r\n\t\t\t\t\t\tp[1] = window.GetPixel(z2, (int)x, (int)y);\r\n\r\n\t\t\t\t\t\tpair<__int16, __int16> date = make_pair(p[0][I_JD], p[1][I_JD]);\r\n\t\t\t\t\t\tauto it = bufferStat[zz].find(date);\r\n\t\t\t\t\t\t__int16 offset = 0;\r\n\t\t\t\t\t\tif (it != bufferStat[zz].end())\r\n\t\t\t\t\t\t\toffset = __int16(Round(it->second[MEAN]));\r\n\r\n\t\t\t\t\t\t__int16 dNBR0 = GetDeltaNBR(JD_base, p);\r\n\t\t\t\t\t\tarray<__int16, 2> Zscore = GetZscore(p);\r\n\t\t\t\t\t\toutput[zz][O_DNBR][xy] = dNBR0 - offset;\r\n\t\t\t\t\t\toutput[zz][O_ZSCORE1][xy] = Zscore[0];\r\n\t\t\t\t\t\toutput[zz][O_ZSCORE2][xy] = Zscore[1];\r\n\t\t\t\t\t\toutput[zz][O_FIRE_SEV][xy] = GetFireSeverity(dNBR0 - offset);\r\n\r\n\t\t\t\t\t\tif (!debug.empty())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdebug[zz][D_NB_MISSING][xy] = GetNbMissing(JD_base, p);\r\n\t\t\t\t\t\t\tdebug[zz][D_DNBR0][xy] = dNBR0;\r\n\t\t\t\t\t\t\tdebug[zz][D_OFFSET][xy] = offset;\r\n\t\t\t\t\t\t\tdebug[zz][D_T1_B3][xy] = p[0][I_B3];\r\n\t\t\t\t\t\t\tdebug[zz][D_T1_B4][xy] = p[0][I_B4];\r\n\t\t\t\t\t\t\tdebug[zz][D_T1_B5][xy] = p[0][I_B5];\r\n\t\t\t\t\t\t\tdebug[zz][D_T1_B7][xy] = p[0][I_B7];\r\n\t\t\t\t\t\t\tdebug[zz][D_T3_B3][xy] = p[1][I_B3];\r\n\t\t\t\t\t\t\tdebug[zz][D_T3_B4][xy] = p[1][I_B4];\r\n\t\t\t\t\t\t\tdebug[zz][D_T3_B5][xy] = p[1][I_B5];\r\n\t\t\t\t\t\t\tdebug[zz][D_T3_B7][xy] = p[1][I_B7];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}//x\r\n\t\t}//y\r\n\r\n\r\n#pragma omp atomic\t\t\r\n\t\tm_options.m_xx += (size_t)blockSize.m_x*blockSize.m_y;\r\n\r\n\t\tm_options.UpdateBar();\r\n\r\n\t}//zz\r\n}\r\n\r\n__int16 CFireSeverity::GetFireSeverity(__int16 dNBR)\r\n{\r\n\tstatic const double F[2][2] =\r\n\t{\r\n\t\t{ 0.22, 0.311 },//Ron\r\n\t\t{ 0.09, 0.019 }//Jo\r\n\t};\r\n\r\n\tdouble fs = (double)Round(100.0 * ((double)dNBR / (F[1][0] * dNBR + F[1][1])));\r\n\treturn __int16(max(-32767.0, min(32767.0, fs)));\r\n}\r\n\r\narray<__int16, 2> CFireSeverity::GetZscore(const array <CLandsatPixel, 2>& p)\r\n{\r\n\tstatic const double F[2][4][2] =\r\n\t{\r\n\t\t{ {278.4841,121.1584},{1839.0676,365.3447},{920.9541,332.3372},{435.8769,195.7674 } },//pre-salvage\r\n\t\t{ {676.3447,676.3447},{1456.5572,253.4981},{2316.8939,2316.8939},{1855.5038,349.1989 } }//salvage\r\n\t};\r\n\r\n\tstatic const size_t B[4] = { I_B3, I_B4, I_B5, I_B7 };\r\n\t\r\n\r\n\tdouble Zsore[2] = { 0 };\r\n\tfor (int f = 0; f < 2; f++)\r\n\t{\r\n\t\tfor (int i = 0; i < 4; i++)\r\n\t\t{\r\n\t\t\tZsore[f] += 10*Square((p[1][B[i]] - F[f][i][0]) / F[f][i][1]) / 4.0;\r\n\t\t}\r\n\t}\r\n\r\n\t//array<__int16, 2>\r\n\treturn { {__int16(Zsore[0]), __int16(Zsore[1])} };\r\n\t//return (Zsore[0]<15&& Zsore[1]<10)?1:0;\r\n}\r\n\r\n__int16 CFireSeverity::GetNbMissing(__int16 JD_base, array <CLandsatPixel, 2> p)\r\n{\r\n\tint nbDays = p[1][I_JD] - JD_base;\r\n\tASSERT(nbDays >= 365); // at least the next year\r\n\r\n\t__int16 nbMissing = __int16(max(0, nbDays-365)/365);\r\n\r\n\treturn nbMissing;\r\n}\r\n\r\n__int16 CFireSeverity::GetDeltaNBR(__int16 JD_base, array <CLandsatPixel, 2> p)\r\n{\r\n\t//CTRef test1 = CBaseOptions::GetTRef(CBaseOptions::JDAY1970, JD_base);\r\n\t//CTRef test2 = CBaseOptions::GetTRef(CBaseOptions::JDAY1970, p[0][I_JD]);\r\n\t//CTRef test3 = CBaseOptions::GetTRef(CBaseOptions::JDAY1970, p[1][I_JD]);\r\n\t//int nbDays = p[1][I_JD] - JD_base;\r\n\t//ASSERT(nbDays >= 365); // at least the next year\r\n\r\n\tstatic const double F[2][4][2] =\r\n\t{\r\n\t\t//B3 B4 B5 B7\r\n\t\t{ {0.66, 138.87}, { 0.65,163.13 }, { 0.66,453.22 }, { 0.70,434.00 }},//T3 is missing\r\n\t\t{{0.60,156.54},{0.57,195.84},{0.60,506.01},{0.71,447.77}}//T3 and T4 is missing\r\n\t};\r\n\r\n\t__int16 nbMissing = GetNbMissing(JD_base, p);\r\n\r\n\t//make correction if missing year\r\n\t//if (nbDays > 2 * 365)\r\n\tif (nbMissing>0)\r\n\t{\r\n\t\tstatic const size_t B[4] = { B3, B4, B5, B7 };\r\n\t\t//size_t f = (nbDays < 3 * 365) ? 0 : 1;\r\n\t\tsize_t f = nbMissing == 1 ? 0 : 1;\r\n\r\n\t\tfor (int i = 0; i < 4; i++)\r\n\t\t{\r\n\t\t\tp[1][B[i]] = __int16(p[1][B[i]] * F[f][i][0] + F[f][i][1]);\r\n\t\t}\r\n\t}\r\n\r\n\treturn __int16(p[0][I_NBR] - p[1][I_NBR]);\r\n}\r\n\r\n\r\n\r\nvoid CFireSeverity::WriteBlock(size_t xBlock, size_t yBlock, OutputData& output, DebugData& debug, CGDALDatasetEx& outputDS, CGDALDatasetEx& debugDS)\r\n{\r\n\r\n#pragma omp critical(WriteBlockIO)\r\n\t{\r\n\r\n\t\tm_options.m_timerWrite.Start();\r\n\r\n\t\tCGeoExtents extents = outputDS.GetExtents();\r\n\t\tCGeoSize blockSize = extents.GetBlockSize((int)xBlock, (int)yBlock);\r\n\t\tCGeoRectIndex outputRect = extents.GetBlockRect((int)xBlock, (int)yBlock);\r\n\r\n\t\tASSERT(outputRect.Width() == blockSize.m_x);\r\n\t\tASSERT(outputRect.Height() == blockSize.m_y);\r\n\r\n\t\tif (m_options.m_bCreateImage)\r\n\t\t{\r\n\t\t\t__int16 noData = (__int16)::GetDefaultNoData(GDT_Int16);\r\n\t\t\tfor (size_t z = 0; z < outputDS.GetRasterCount() / NB_OUTPUTS; z++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t i = 0; i < NB_OUTPUTS; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tsize_t b = z * NB_OUTPUTS + i;\r\n\t\t\t\t\tASSERT(output.empty() || output[z][i].size() == outputRect.Width()*outputRect.Height());\r\n\r\n\t\t\t\t\tGDALRasterBand *pBand = outputDS.GetRasterBand(b);\r\n\t\t\t\t\tif (!output.empty())\r\n\t\t\t\t\t\tpBand->RasterIO(GF_Write, outputRect.m_x, outputRect.m_y, outputRect.Width(), outputRect.Height(), &(output[z][i][0]), outputRect.Width(), outputRect.Height(), GDT_Int16, 0, 0);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tpBand->RasterIO(GF_Write, outputRect.m_x, outputRect.m_y, outputRect.Width(), outputRect.Height(), &(noData), 1, 1, GDT_Int16, 0, 0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (m_options.m_bDebug)\r\n\t\t{\r\n\t\t\t__int16 noData = (__int16)::GetDefaultNoData(GDT_Int16);\r\n\t\t\tfor (size_t z = 0; z < debugDS.GetRasterCount() / NB_DEBUGS; z++)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t i = 0; i < NB_DEBUGS; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tsize_t b = z * NB_DEBUGS + i;\r\n\t\t\t\t\tASSERT(debug.empty() || debug[z][i].size() == outputRect.Width()*outputRect.Height());\r\n\r\n\t\t\t\t\tGDALRasterBand *pBand = debugDS.GetRasterBand(b);\r\n\t\t\t\t\tif (!debug.empty())\r\n\t\t\t\t\t\tpBand->RasterIO(GF_Write, outputRect.m_x, outputRect.m_y, outputRect.Width(), outputRect.Height(), &(debug[z][i][0]), outputRect.Width(), outputRect.Height(), GDT_Int16, 0, 0);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tpBand->RasterIO(GF_Write, outputRect.m_x, outputRect.m_y, outputRect.Width(), outputRect.Height(), &(noData), 1, 1, GDT_Int16, 0, 0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tm_options.m_timerWrite.Stop();\r\n\t}\r\n\r\n\t\r\n\r\n}\r\n\r\nvoid CFireSeverity::CloseAll(CGDALDatasetEx& landsatDS, CGDALDatasetEx& maskDS, CGDALDatasetEx& fireDS, CGDALDatasetEx& outputDS, CGDALDatasetEx& debugDS)\r\n{\r\n\tif (!m_options.m_bQuiet)\r\n\t\t_tprintf(\"\\nClose all files...\\n\");\r\n\r\n\tlandsatDS.Close();\r\n\tmaskDS.Close();\r\n\tfireDS.Close();\r\n\r\n\tm_options.m_timerWrite.Start();\r\n\toutputDS.Close(m_options);\r\n\tdebugDS.Close(m_options);\r\n\r\n\r\n\tm_options.m_timerWrite.Stop();\r\n\tm_options.PrintTime();\r\n}\r\n\r\nvoid CFireSeverity::LoadData(const CBandsHolder& bandHolder, LansatData& data)\r\n{\r\n\tCGeoExtents extents = bandHolder.GetExtents();\r\n\tCLandsatWindow window = bandHolder.GetWindow();\r\n\tsize_t nbScenesLoaded = m_options.m_scenesLoaded[1] - m_options.m_scenesLoaded[0] + 1;\r\n\r\n\tCGeoSize blockSize = window.GetGeoSize();\r\n\tdata.resize(blockSize.m_x*blockSize.m_y);\r\n\r\n\tfor (size_t y = 0; y < blockSize.m_y; y++)\r\n\t\tfor (size_t x = 0; x < blockSize.m_x; x++)\r\n\t\t\tdata[y*blockSize.m_x + x].resize(nbScenesLoaded);\r\n\r\n#pragma omp parallel for num_threads(m_options.BLOCK_CPU()) if (m_options.m_bMulti)\r\n\tfor (int zz = 0; zz < (int)nbScenesLoaded; zz++)\r\n\t{\r\n\t\tsize_t z = m_options.m_scenesLoaded[0] + zz;\r\n\t\tfor (size_t y = 0; y < blockSize.m_y; y++)\r\n\t\t{\r\n\t\t\tfor (size_t x = 0; x < blockSize.m_x; x++)\r\n\t\t\t{\r\n\t\t\t\tdata[y*blockSize.m_x + x][zz] = window.GetPixel(z, (int)x, (int)y);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//#pragma omp atomic\t\t\r\n\t\t\t//\tm_options.m_xx += (size_t)blockSize.m_x*blockSize.m_y;\r\n\t\t\t\t//m_options.UpdateBar();\r\n\r\n\t}\r\n}\r\n\r\n\r\nstring CFireSeverity::GetScenesDateFormat(const std::vector<CTPeriod>& p)\r\n{\r\n\tstring str;\r\n\r\n\tset<size_t> stat;\r\n\tfor (size_t z = 0; z < p.size(); z++)\r\n\t\tstat.insert(p[z].size());\r\n\r\n\tif (*stat.rbegin() == 1)\r\n\t\tstr = \"%F\";  //Individual input\r\n\telse //if (stat[HIGHEST] <= 366)\r\n\t\tstr = \"%Y\";\t//annual input\r\n\t//else\r\n\t\t//str = \"%1-%2\", \"%Y\");\t//multi annual input\r\n\r\n\treturn str;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "be96f83d8d15644f605eea1a72a8168b1ec79d77", "size": 35524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeomaticTools/FireSeverity/FireSeverity.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": "GeomaticTools/FireSeverity/FireSeverity.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": "GeomaticTools/FireSeverity/FireSeverity.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": 32.6507352941, "max_line_length": 321, "alphanum_fraction": 0.6286735728, "num_tokens": 11038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.0378924308397605, "lm_q1q2_score": 0.016736063820935974}}
{"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_python_interface.hh\"\n\n#include <boost/python.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_util.hh\"\n\n#include \"coroutine.hh\"\n#include \"graph_python_interface.hh\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\n\nclass DJKVisitorWrapper\n{\npublic:\n    DJKVisitorWrapper(GraphInterface& gi, python::object vis)\n        : _gi(gi), _vis(vis) {}\n\n    template <class Vertex, class Graph>\n    void initialize_vertex(Vertex u, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _vis.attr(\"initialize_vertex\")(PythonVertex<Graph>(gp, u));\n    }\n\n    template <class Vertex, class Graph>\n    void discover_vertex(Vertex u, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _vis.attr(\"discover_vertex\")(PythonVertex<Graph>(gp, u));\n    }\n\n    template <class Vertex, class Graph>\n    void examine_vertex(Vertex u, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _vis.attr(\"examine_vertex\")(PythonVertex<Graph>(gp, u));\n    }\n\n    template <class Edge, class Graph>\n    void examine_edge(Edge e, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _vis.attr(\"examine_edge\")(PythonEdge<Graph>(gp, e));\n    }\n\n    template <class Edge, class Graph>\n    void edge_relaxed(Edge e, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _vis.attr(\"edge_relaxed\")(PythonEdge<Graph>(gp, e));\n    }\n\n    template <class Edge, class Graph>\n    void edge_not_relaxed(Edge e, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _vis.attr(\"edge_not_relaxed\")(PythonEdge<Graph>(gp, e));\n    }\n\n    template <class Vertex, class Graph>\n    void finish_vertex(Vertex u, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _vis.attr(\"finish_vertex\")(PythonVertex<Graph>(gp, u));\n    }\n\nprivate:\n    GraphInterface& _gi;\n    boost::python::object _vis;\n};\n\n\nclass DJKCmp\n{\npublic:\n    DJKCmp() {}\n    DJKCmp(python::object cmp): _cmp(cmp) {}\n\n    template <class Value1, class Value2>\n    bool operator()(const Value1& v1, const Value2& v2) const\n    {\n        return python::extract<bool>(_cmp(v1, v2));\n    }\n\nprivate:\n    python::object _cmp;\n};\n\nclass DJKCmb\n{\npublic:\n    DJKCmb() {}\n    DJKCmb(python::object cmb): _cmb(cmb) {}\n\n    template <class Value1, class Value2 >\n    Value1 operator()(const Value1& v1, const Value2& v2) const\n    {\n        return python::extract<Value1>(_cmb(v1, v2));\n    }\n\nprivate:\n    python::object _cmb;\n};\n\nstruct do_djk_search\n{\n    template <class Graph, class DistanceMap, class PredMap, class Visitor>\n    void operator()(const Graph& g, size_t s, DistanceMap dist,\n                    PredMap pred_map, boost::any aweight,\n                    Visitor vis, const DJKCmp& cmp, const DJKCmb& cmb,\n                    pair<python::object, python::object> range) const\n    {\n        typedef typename property_traits<DistanceMap>::value_type dtype_t;\n        dtype_t z = python::extract<dtype_t>(range.first);\n        dtype_t i = python::extract<dtype_t>(range.second);\n        typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n        DynamicPropertyMapWrap<dtype_t, edge_t> weight(aweight,\n                                                       edge_properties());\n\n        if (vertex(s, g) == graph_traits<Graph>::null_vertex())\n        {\n            for (auto u : vertices_range(g))\n            {\n                vis.initialize_vertex(u, g);\n                put(dist, u, i);\n                put(pred_map, u, u);\n            }\n            for (auto u : vertices_range(g))\n            {\n                if (dist[u] != i)\n                    continue;\n                dist[u] = z;\n                dijkstra_shortest_paths_no_color_map_no_init\n                    (g, u, pred_map, dist, weight, get(vertex_index_t(), g),\n                     cmp, cmb, i, z, vis);\n            }\n        }\n        else\n        {\n            dijkstra_shortest_paths_no_color_map\n                (g, vertex(s, g), visitor(vis).weight_map(weight).\n                 predecessor_map(pred_map).\n                 distance_map(dist).distance_compare(cmp).\n                 distance_combine(cmb).distance_inf(i).distance_zero(z));\n        }\n    }\n};\n\nstruct do_djk_search_fast\n{\n    template <class Graph, class DistanceMap, class WeightMap, class Visitor>\n    void operator()(const Graph& g, size_t s, DistanceMap dist,\n                    WeightMap weight, Visitor vis,\n                    pair<python::object, python::object> range) const\n    {\n        typedef typename property_traits<DistanceMap>::value_type dtype_t;\n        dtype_t z = python::extract<dtype_t>(range.first);\n        dtype_t i = python::extract<dtype_t>(range.second);\n\n        if (vertex(s, g) == graph_traits<Graph>::null_vertex())\n        {\n            for (auto u : vertices_range(g))\n            {\n                vis.initialize_vertex(u, g);\n                put(dist, u, i);\n            }\n            for (auto u : vertices_range(g))\n            {\n                if (dist[u] != i)\n                    continue;\n                dist[u] = z;\n                dijkstra_shortest_paths_no_color_map_no_init\n                    (g, u, dummy_property_map(), dist, weight,\n                     get(vertex_index_t(), g), std::less<dtype_t>(),\n                     boost::closed_plus<dtype_t>(), i, z, vis);\n            }\n        }\n        else\n        {\n            dijkstra_shortest_paths_no_color_map\n                (g, vertex(s, g), visitor(vis).weight_map(weight).\n                 distance_map(dist).distance_inf(i).distance_zero(z));\n        }\n    }\n};\n\n\nvoid dijkstra_search(GraphInterface& g, size_t source, boost::any dist_map,\n                     boost::any pred_map, boost::any weight, python::object vis,\n                     python::object cmp, python::object cmb,\n                     python::object zero, python::object inf)\n{\n    typedef typename property_map_type::\n        apply<int64_t, GraphInterface::vertex_index_map_t>::type pred_t;\n    pred_t pred = any_cast<pred_t>(pred_map);\n    run_action<graph_tool::all_graph_views, mpl::true_>()\n        (g, std::bind(do_djk_search(), std::placeholders::_1, source,\n                      std::placeholders::_2, pred, weight,\n                      DJKVisitorWrapper(g, vis), DJKCmp(cmp), DJKCmb(cmb),\n                      make_pair(zero, inf)),\n         writable_vertex_properties())(dist_map);\n}\n\n#ifdef HAVE_BOOST_COROUTINE\n\nclass DJKGeneratorVisitor : public dijkstra_visitor<>\n{\npublic:\n    DJKGeneratorVisitor(GraphInterface& gi,\n                        coro_t::push_type& yield)\n        : _gi(gi), _yield(yield) {}\n\n    template <class Edge, class Graph>\n    void edge_relaxed(const Edge& e, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _yield(boost::python::object(PythonEdge<Graph>(gp, e)));\n    }\n\nprivate:\n    GraphInterface& _gi;\n    coro_t::push_type& _yield;\n};\n\n#endif // HAVE_BOOST_COROUTINE\n\nboost::python::object dijkstra_search_generator(GraphInterface& g,\n                                                size_t source,\n                                                boost::any dist_map,\n                                                boost::any weight,\n                                                python::object cmp,\n                                                python::object cmb,\n                                                python::object zero,\n                                                python::object inf)\n{\n#ifdef HAVE_BOOST_COROUTINE\n    auto dispatch = [&](auto& yield)\n        {\n            DJKGeneratorVisitor vis(g, yield);\n            run_action<graph_tool::all_graph_views, mpl::true_>()\n            (g, std::bind(do_djk_search(), std::placeholders::_1, source,\n                          std::placeholders::_2, dummy_property_map(), weight,\n                          vis, DJKCmp(cmp), DJKCmb(cmb),\n                          make_pair(zero, inf)),\n             writable_vertex_properties())(dist_map);\n        };\n    return boost::python::object(CoroGenerator(dispatch));\n#else\n    throw GraphException(\"This functionality is not available because boost::coroutine was not found at compile-time\");\n#endif\n}\n\nboost::python::object dijkstra_search_generator_fast(GraphInterface& g,\n                                                     size_t source,\n                                                     boost::any dist_map,\n                                                     boost::any weight,\n                                                     python::object zero, python::object inf)\n{\n#ifdef HAVE_BOOST_COROUTINE\n    auto dispatch = [&](auto& yield)\n        {\n            DJKGeneratorVisitor vis(g, yield);\n            run_action<graph_tool::all_graph_views, mpl::true_>()\n            (g, std::bind(do_djk_search_fast(), std::placeholders::_1, source,\n                          std::placeholders::_2, std::placeholders::_3,\n                          vis, make_pair(zero, inf)),\n             writable_vertex_scalar_properties(),\n             edge_scalar_properties())(dist_map, weight);\n        };\n    return boost::python::object(CoroGenerator(dispatch));\n#else\n    throw GraphException(\"This functionality is not available because boost::coroutine was not found at compile-time\");\n#endif\n}\n\nclass DJKArrayVisitor: public dijkstra_visitor<>\n{\npublic:\n    DJKArrayVisitor(std::vector<std::array<size_t, 2>>& edges)\n        : _edges(edges) {}\n\n    template <class Edge, class Graph>\n    void edge_relaxed(const Edge& e, Graph& g)\n    {\n        _edges.push_back({{source(e, g), target(e,g)}});\n    }\n\nprivate:\n    std::vector<std::array<size_t, 2>>& _edges;\n};\n\n\nboost::python::object dijkstra_search_array(GraphInterface& g,\n                                            size_t source,\n                                            boost::any dist_map,\n                                            boost::any weight,\n                                            python::object cmp,\n                                            python::object cmb,\n                                            python::object zero,\n                                            python::object inf)\n{\n    std::vector<std::array<size_t, 2>> edges;\n    DJKArrayVisitor vis(edges);\n    run_action<graph_tool::all_graph_views, mpl::true_>()\n        (g, std::bind(do_djk_search(), std::placeholders::_1, source,\n                      std::placeholders::_2, dummy_property_map(), weight,\n                      vis, DJKCmp(cmp), DJKCmb(cmb),\n                      make_pair(zero, inf)),\n         writable_vertex_properties())(dist_map);\n    return wrap_vector_owned<size_t,2>(edges);\n}\n\nboost::python::object dijkstra_search_array_fast(GraphInterface& g,\n                                                 size_t source,\n                                                 boost::any dist_map,\n                                                 boost::any weight,\n                                                 python::object zero,\n                                                 python::object inf)\n{\n    std::vector<std::array<size_t, 2>> edges;\n    DJKArrayVisitor vis(edges);\n    run_action<graph_tool::all_graph_views, mpl::true_>()\n        (g, std::bind(do_djk_search_fast(), std::placeholders::_1, source,\n                      std::placeholders::_2, std::placeholders::_3,\n                      vis, make_pair(zero, inf)),\n         writable_vertex_scalar_properties(),\n         edge_scalar_properties())(dist_map, weight);\n    return wrap_vector_owned<size_t,2>(edges);\n}\n\nvoid export_dijkstra()\n{\n    using namespace boost::python;\n    def(\"dijkstra_search\", &dijkstra_search);\n    def(\"dijkstra_generator\", &dijkstra_search_generator);\n    def(\"dijkstra_generator_fast\", &dijkstra_search_generator_fast);\n    def(\"dijkstra_array\", &dijkstra_search_array);\n    def(\"dijkstra_array_fast\", &dijkstra_search_array_fast);\n}\n", "meta": {"hexsha": "4017e644d14bb6334ab862c601a2869db38a4b3a", "size": 12839, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/search/graph_dijkstra.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/search/graph_dijkstra.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/search/graph_dijkstra.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.271978022, "max_line_length": 119, "alphanum_fraction": 0.5683464444, "num_tokens": 2809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.038466189538183315, "lm_q1q2_score": 0.016693613281205194}}
{"text": "﻿/***\r\n第四章\t标准库的典型内容\r\n第一节 std::declval\r\n\r\n（2.2）返回左值引用还是返回右值引用\r\ndecltype(DeclValRight<A>)())的返回类型 = class _nmsp1::A &\r\ndecltype(DeclValRight<A&>)())的返回类型 = class _nmsp1::A &\r\ndecltype(DeclValRight<A&&>)())的返回类型 = class _nmsp1::A &\r\n\r\ndecltype(DeclValRight<A>)())的返回类型 = class _nmsp1::A &&\r\ndecltype(DeclValRight<A&>)())的返回类型 = class _nmsp1::A &\r\ndecltype(DeclValRight<A&&>)())的返回类型 = class _nmsp1::A &&\r\n\r\n（2.3）调用引用限定符修饰的成员函数范例\r\n\r\n（3）推导函数返回值范例\r\nT_F：是int (*)(int,int)类型，也就是函数指针类型\r\ndecltype(std::DeclValLeft<T_F>()   (std::DeclValLeft<U_Args>()...))：是int类型，也就是Add函数的返回类型\r\na)decltype(std::DeclValLeft<T_F>() )：是 int (* && )(int,int),函数指针的右值引用类型，其实就简单理解成函数指针类型\r\nb)decltype(std::DeclValLeft<U_Args>()...)这种写法：推导出来的是两个int &&\r\n***/\r\n\r\n#include <iostream>\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n\r\nnamespace _nmsp2\r\n{\r\n\t//函数类型一般是由函数的返回值和参数类型决定，与函数名没有关系，所以Add代表的函数类型是: int(int,int);\r\n\tint Add(int a, int b) \r\n\t{\r\n\t\treturn a + b;\r\n\t}\r\n\r\n\t//std::declval<>中的U_Args写成U_Args&&或者U_Args&\r\n\t//decltype(std::declval<T_F>() (std::declval<U_Args>()...))写法的作用：根据函数类型以及函数参数类型，推导函数返回值类型。\r\n\t//decltype(T_F(U_Args...)) TestFnRtnImpl(T_F func, U_Args... args) -报错：\r\n\t//decltype后面圆括号中出现的一般都是变量、对象、表达式、函数名、函数指针名等等。\r\n\ttemplate<typename T_F, typename... U_Args>\r\n\tdecltype(std::declval<T_F>() (std::declval<U_Args>()...)) TestFnRtnImpl(T_F func, U_Args... args)\r\n\t{\r\n\t\tauto rtnvalue = func(args...);\r\n\t\treturn rtnvalue;\r\n\t}\r\n\t\r\n\t//decltype(func(args...))：int类型，也就是Add的返回类型。\r\n\t//decltype(func)：int(*)(int,int)类型，函数指针类型\r\n\ttemplate<typename T_F, typename... U_Args>\r\n\tauto TestFnRtnImpl2(T_F func, U_Args... args)->decltype(func(args...)) \t\t                                                                   \r\n\t{\r\n\t\tauto rtnvalue = func(args...);\r\n\t\treturn rtnvalue;\r\n\t}\r\n\t\r\n}\r\n\r\nint main()\r\n{ \r\n\t/*_nmsp2测试*/\r\n\t//函数指针类型fp_var = int(*)(int,int)\r\n\t//函数指针的右值引用rr_fp_var = int(* &&)(int,int),现在rr_fp_var就可以代表fp_var\r\n\tint (*fp_var)(int x, int y);                            \r\n\tint (* &&rr_fp_var)(int x, int y) = std::move(fp_var);  \r\n\tfp_var = _nmsp2::Add;\r\n\tcout << fp_var(1, 2) << endl;    //输出值为3\r\n\tcout << rr_fp_var(1, 2) << endl; //输出值为3\r\n\t\r\n\tauto result1 = _nmsp2::TestFnRtnImpl(_nmsp2::Add, 5, 5);                   //T_F被推断出 int(*)(int,int)\r\n\tcout << result1 << endl;\r\n\r\n\tauto result2 = _nmsp2::TestFnRtnImpl<int(int,int)>(_nmsp2::Add, 5, 7);  //T_F被推断出 int(*)(int,int)\r\n\tcout << result2 << endl;\r\n\t\r\n\tauto result3 = _nmsp2::TestFnRtnImpl2(_nmsp2::Add, 15, 15);\r\n\tcout << result3 << endl;\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "9bd4552d65a3e5ef632cba77f430e19d0ab9b1ad", "size": 2498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/4/402b.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/4/402b.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/4/402b.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 31.225, "max_line_length": 142, "alphanum_fraction": 0.6192954363, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070997458932, "lm_q2_score": 0.07585818524437762, "lm_q1q2_score": 0.01668933932760223}}
{"text": "\r\n\r\n#include <NTL/vec_ZZ_p.h>\r\n\r\nNTL_START_IMPL\r\n\r\nstatic \r\nvoid BasicBlockConstruct(ZZ_p* x, long n, long d)\r\n{\r\n   long m, j;\r\n\r\n   long i = 0;\r\n\r\n   NTL_SCOPE(guard) { BlockDestroy(x, i); };\r\n\r\n   while (i < n) {\r\n      m = ZZ_BlockConstructAlloc(x[i]._ZZ_p__rep, d, n-i);\r\n      for (j = 1; j < m; j++)\r\n         ZZ_BlockConstructSet(x[i]._ZZ_p__rep, x[i+j]._ZZ_p__rep, j);\r\n      i += m;\r\n   }\r\n\r\n   guard.relax();\r\n}\r\n\r\nvoid BlockConstruct(ZZ_p* x, long n)\r\n{\r\n   if (n <= 0) return; \r\n\r\n   if (!ZZ_pInfo)\r\n      LogicError(\"ZZ_p constructor called while modulus undefined\");\r\n\r\n   long d = ZZ_p::ModulusSize();\r\n\r\n   BasicBlockConstruct(x, n, d);\r\n}\r\n\r\nvoid BlockConstructFromVec(ZZ_p* x, long n, const ZZ_p* y)\r\n{\r\n   if (n <= 0) return;\r\n\r\n   long d = y->_ZZ_p__rep.MaxAlloc() - 1;\r\n   BasicBlockConstruct(x, n, d);\r\n\r\n   NTL_SCOPE(guard) { BlockDestroy(x, n); };\r\n\r\n   long i;\r\n   for (i = 0; i < n; i++) x[i] = y[i];\r\n\r\n   guard.relax();\r\n}\r\n\r\nvoid BlockConstructFromObj(ZZ_p* x, long n, const ZZ_p& y)\r\n{\r\n   if (n <= 0) return;\r\n\r\n\r\n   if (!ZZ_pInfo)\r\n      LogicError(\"ZZ_p constructor called while modulus undefined\");\r\n\r\n   long d = ZZ_p::ModulusSize();\r\n\r\n   BasicBlockConstruct(x, n, d);\r\n\r\n   NTL_SCOPE(guard) { BlockDestroy(x, n); };\r\n\r\n   long i;\r\n   for (i = 0; i < n; i++) x[i] = y;\r\n\r\n   guard.relax();\r\n}\r\n\r\n\r\nvoid BlockDestroy(ZZ_p* x, long n)\r\n{\r\n   if (n <= 0) return;\r\n\r\n   long i = 0;\r\n   long m;\r\n\r\n   while (i < n) {\r\n      m = ZZ_BlockDestroy(x[i]._ZZ_p__rep);\r\n      i += m;\r\n   }\r\n}\r\n\r\n\r\nvoid conv(vec_ZZ_p& x, const vec_ZZ& a)\r\n{\r\n   long i, n;\r\n\r\n   n = a.length();\r\n   x.SetLength(n);\r\n\r\n   ZZ_p* xp = x.elts();\r\n   const ZZ* ap = a.elts();\r\n\r\n   for (i = 0; i < n; i++)\r\n      conv(xp[i], ap[i]);\r\n}\r\n\r\nvoid conv(vec_ZZ& x, const vec_ZZ_p& a)\r\n{\r\n   long n = a.length();\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      x[i] = rep(a[i]);\r\n}\r\n\r\n\r\n\r\nvoid InnerProduct(ZZ_p& x, const vec_ZZ_p& a, const vec_ZZ_p& b)\r\n{\r\n   long n = min(a.length(), b.length());\r\n   long i;\r\n   NTL_ZZRegister(accum);\r\n   NTL_ZZRegister(t);\r\n\r\n   clear(accum);\r\n   for (i = 0; i < n; i++) {\r\n      mul(t, rep(a[i]), rep(b[i]));\r\n      add(accum, accum, t);\r\n   }\r\n\r\n   conv(x, accum);\r\n}\r\n\r\nvoid InnerProduct(ZZ_p& x, const vec_ZZ_p& a, const vec_ZZ_p& b,\r\n                  long offset)\r\n{\r\n   if (offset < 0) LogicError(\"InnerProduct: negative offset\");\r\n   if (NTL_OVERFLOW(offset, 1, 0)) \r\n      ResourceError(\"InnerProduct: offset too big\");\r\n\r\n   long n = min(a.length(), b.length()+offset);\r\n   long i;\r\n   NTL_ZZRegister(accum);\r\n   NTL_ZZRegister(t);\r\n\r\n   clear(accum);\r\n   for (i = offset; i < n; i++) {\r\n      mul(t, rep(a[i]), rep(b[i-offset]));\r\n      add(accum, accum, t);\r\n   }\r\n\r\n   conv(x, accum);\r\n}\r\n\r\nvoid mul(vec_ZZ_p& x, const vec_ZZ_p& a, const ZZ_p& b_in)\r\n{\r\n   NTL_ZZ_pRegister(b);\r\n   b = b_in;\r\n   long n = a.length();\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      mul(x[i], a[i], b);\r\n}\r\n\r\nvoid mul(vec_ZZ_p& x, const vec_ZZ_p& a, long b_in)\r\n{\r\n   NTL_ZZ_pRegister(b);\r\n   b = b_in;\r\n   long n = a.length();\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      mul(x[i], a[i], b);\r\n}\r\n\r\n\r\nvoid add(vec_ZZ_p& x, const vec_ZZ_p& a, const vec_ZZ_p& b)\r\n{\r\n   long n = a.length();\r\n   if (b.length() != n) LogicError(\"vector add: dimension mismatch\");\r\n\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      add(x[i], a[i], b[i]);\r\n}\r\n\r\nvoid sub(vec_ZZ_p& x, const vec_ZZ_p& a, const vec_ZZ_p& b)\r\n{\r\n   long n = a.length();\r\n   if (b.length() != n) LogicError(\"vector sub: dimension mismatch\");\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      sub(x[i], a[i], b[i]);\r\n}\r\n\r\nvoid clear(vec_ZZ_p& x)\r\n{\r\n   long n = x.length();\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      clear(x[i]);\r\n}\r\n\r\nvoid negate(vec_ZZ_p& x, const vec_ZZ_p& a)\r\n{\r\n   long n = a.length();\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      negate(x[i], a[i]);\r\n}\r\n\r\nlong IsZero(const vec_ZZ_p& a)\r\n{\r\n   long n = a.length();\r\n   long i;\r\n\r\n   for (i = 0; i < n; i++)\r\n      if (!IsZero(a[i]))\r\n         return 0;\r\n\r\n   return 1;\r\n}\r\n\r\nvec_ZZ_p operator+(const vec_ZZ_p& a, const vec_ZZ_p& b)\r\n{\r\n   vec_ZZ_p res;\r\n   add(res, a, b);\r\n   NTL_OPT_RETURN(vec_ZZ_p, res);\r\n}\r\n\r\nvec_ZZ_p operator-(const vec_ZZ_p& a, const vec_ZZ_p& b)\r\n{\r\n   vec_ZZ_p res;\r\n   sub(res, a, b);\r\n   NTL_OPT_RETURN(vec_ZZ_p, res);\r\n}\r\n\r\n\r\nvec_ZZ_p operator-(const vec_ZZ_p& a)\r\n{\r\n   vec_ZZ_p res;\r\n   negate(res, a);\r\n   NTL_OPT_RETURN(vec_ZZ_p, res);\r\n}\r\n\r\n\r\nZZ_p operator*(const vec_ZZ_p& a, const vec_ZZ_p& b)\r\n{\r\n   ZZ_p res;\r\n   InnerProduct(res, a, b);\r\n   NTL_OPT_RETURN(ZZ_p, res);\r\n}\r\n\r\n\r\nvoid VectorCopy(vec_ZZ_p& x, const vec_ZZ_p& a, long n)\r\n{\r\n   if (n < 0) LogicError(\"VectorCopy: negative length\");\r\n   if (NTL_OVERFLOW(n, 1, 0)) ResourceError(\"overflow in VectorCopy\");\r\n\r\n   long m = min(n, a.length());\r\n\r\n   x.SetLength(n);\r\n   \r\n   long i;\r\n\r\n   for (i = 0; i < m; i++)\r\n      x[i] = a[i];\r\n\r\n   for (i = m; i < n; i++)\r\n      clear(x[i]);\r\n}\r\n\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "4f359bbc97b150c4e28fef0c5e68765daea9861b", "size": 5080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/vec_ZZ_p.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/vec_ZZ_p.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/vec_ZZ_p.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5401459854, "max_line_length": 71, "alphanum_fraction": 0.5273622047, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.042087728966949636, "lm_q1q2_score": 0.01666960963457861}}
{"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 <functional>\n#include <limits>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/ApplyMatrices.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Matrix.hpp\"\n#include \"DataStructures/Tags.hpp\"       // IWYU pragma: keep\n#include \"DataStructures/Variables.hpp\"  // IWYU pragma: keep\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.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/LinearOperators/MeanValue.hpp\"\n#include \"Utilities/Algorithm.hpp\"\n#include \"Utilities/EqualWithinRoundoff.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\n/// \\cond\ntemplate <size_t VolumeDim>\nclass Element;\ntemplate <size_t VolumeDim>\nclass ElementId;\ntemplate <size_t>\nclass Mesh;\n/// \\endcond\n\nnamespace Limiters::Weno_detail {\n\n// Caching class that holds various precomputed terms used in the constrained-\n// fit algebra on each element.\n//\n// The terms to precompute and cache depend on the configuration of neighbors to\n// the element (how many neighbors, in which directions, of what resolution).\n// Each instance of the caching class represents one particular neighbor\n// configuration, and typical simulations will create many instances of\n// the caching class: one instance for each neighbor-element configuration\n// present in the computational domain.\n//\n// Because the current implementation of the HWENO fitting makes the simplifying\n// restrictions of no h/p-refinement, the structure of the caching is also\n// simplified. In particular, with no h/p-refinement, the allowable neighbor\n// configurations satisfy,\n// 1. the element has at most one neighbor per dimension, AND\n// 2. the mesh on every neighbor is the same as on the element.\n// With these restrictions, the number of independent configurations to be\n// cached is greatly reduced. Because an element has 2*VolumeDim boundaries,\n// it has 2^(2*VolumeDim) possible configurations of internal/external\n// boundaries, and therefore there are 2^(2*VolumeDim) configurations to cache.\n// Different elements with the same configuration of internal/external\n// boundaries vs. direction can share the same caching-class instance.\n//\n// Each instance of the caching class holds several terms, some of which also\n// depend on the neighbor configuration. The restriction of no h/p-refinement\n// therefore simplifies each cache instance, as well as reducing the necessary\n// number of instances.\n//\n// The most complicated term to cache is the A^{-1} matrix. The complexity\n// arises because the matrix can take many values depending on (runtime) choices\n// made for each individual HWNEO fit: which element is the primary neighbor,\n// and which element(s) are the excluded neighbors.\n// Fits with one excluded neighbor are overwhelmingly the most likely, and the\n// cache is designed for this particular case. Fits with no excluded neighbors\n// can arise in elements with only one neighbor (always the primary neighbor);\n// these cases are also handled. However, the very rare case in which more than\n// one neighbor is excluded is not handled by the cache; the caller must compute\n// A^{-1} from scratch if this scenario arises.\ntemplate <size_t VolumeDim>\nclass ConstrainedFitCache {\n public:\n  ConstrainedFitCache(const Element<VolumeDim>& element,\n                      const Mesh<VolumeDim>& mesh) noexcept;\n\n  // Valid calls must satisfy these constraints on directions_to_exclude:\n  // - the vector is empty, OR\n  // - the vector contains one element, and this element is a direction\n  //   different from the direction to the primary neighbor.\n  // The very rare case where more than one neighbor is excluded from the fit is\n  // not cached. In this case, A^{-1} must be computed from scratch.\n  const Matrix& retrieve_inverse_a_matrix(\n      const Direction<VolumeDim>& primary_direction,\n      const std::vector<Direction<VolumeDim>>& directions_to_exclude) const\n      noexcept;\n\n  DataVector quadrature_weights;\n  DirectionMap<VolumeDim, Matrix> interpolation_matrices;\n  DirectionMap<VolumeDim, DataVector>\n      quadrature_weights_dot_interpolation_matrices;\n  // The many possible values of A^{-1} are stored in a map of maps. The outer\n  // map indexes over the primary neighbor, and the inner map indexes over the\n  // excluded neighbor.\n  // This data structure is not perfect: configurations with only one neighbor\n  // (always the primary neighbor) lead to no excluded neighbors, and there is\n  // no natural place to hold A^{-1} in the maps. For this case, we simply store\n  // the data in the normally-nonsensical slot where\n  // excluded_neighbor == primary_neighbor.\n  DirectionMap<VolumeDim, DirectionMap<VolumeDim, Matrix>> inverse_a_matrices;\n};\n\n// Return the appropriate cache for the given element and mesh.\ntemplate <size_t VolumeDim>\nconst ConstrainedFitCache<VolumeDim>& constrained_fit_cache(\n    const Element<VolumeDim>& element, const Mesh<VolumeDim>& mesh) noexcept;\n\n// Compute the inverse of the matrix A_st for the constrained fit.\n// See the documentation of `hweno_modified_neighbor_solution`.\ntemplate <size_t VolumeDim>\nMatrix inverse_a_matrix(\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const DataVector& quadrature_weights,\n    const DirectionMap<VolumeDim, Matrix>& interpolation_matrices,\n    const DirectionMap<VolumeDim, DataVector>&\n        quadrature_weights_dot_interpolation_matrices,\n    const Direction<VolumeDim>& primary_direction,\n    const std::vector<Direction<VolumeDim>>& directions_to_exclude) noexcept;\n\n// Not all secondary neighbors (i.e., neighbors that are not the primary) are\n// included in the HWENO constrained fit. In particular, for the tensor\n// component specified by `Tag` and `tensor_index`, the secondary neighbor whose\n// mean is most different from the troubled cell's mean is excluded.\n//\n// Zhu2016 indicate that when multiple secondary neighbors share the property of\n// being \"most different\" from the troubled cell, then all of these secondary\n// neighbors should be excluded from the minimization. The probability of this\n// occuring is exceedingly low, but we handle it anyway. We return the excluded\n// secondary neighbors in a vector.\n//\n// Note that if there is only one neighbor, it is the primary neighbor, and so\n// there are no secondary neighbors to exclude. We return an empty vector. This\n// scenario can arise in various test cases, but is unlikely to arise in science\n// cases.\ntemplate <typename Tag, size_t VolumeDim, typename Package>\nstd::vector<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>\nsecondary_neighbors_to_exclude_from_fit(\n    const double local_mean, const size_t tensor_index,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, Package,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data,\n    const std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>&\n        primary_neighbor) noexcept {\n  // Rare case: with only one neighbor, there is no secondary to exclude\n  if (UNLIKELY(neighbor_data.size() == 1)) {\n    return std::vector<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>{};\n  }\n\n  // Identify element with maximum mean difference\n  const auto mean_difference =\n      [&tensor_index, &local_mean](\n          const std::pair<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n                          Package>& neighbor_and_data) noexcept {\n        return fabs(get<::Tags::Mean<Tag>>(\n                        neighbor_and_data.second.means)[tensor_index] -\n                    local_mean);\n      };\n\n  double max_difference = std::numeric_limits<double>::lowest();\n  std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>\n      neighbor_max_difference{};\n  for (const auto& neighbor_and_data : neighbor_data) {\n    const auto& neighbor = neighbor_and_data.first;\n    if (neighbor == primary_neighbor) {\n      continue;\n    }\n    const double difference = mean_difference(neighbor_and_data);\n    if (difference > max_difference) {\n      max_difference = difference;\n      neighbor_max_difference = neighbor;\n    }\n  }\n\n  std::vector<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>\n      neighbors_to_exclude{{neighbor_max_difference}};\n\n  // See if other elements share this maximum mean difference. This loop should\n  // only rarely find other neighbors with the same maximal mean difference to\n  // add to the vector, so it will usually not change the vector.\n  for (const auto& neighbor_and_data : neighbor_data) {\n    const auto& neighbor = neighbor_and_data.first;\n    if (neighbor == primary_neighbor or neighbor == neighbor_max_difference) {\n      continue;\n    }\n    const double difference = mean_difference(neighbor_and_data);\n    if (UNLIKELY(equal_within_roundoff(difference, max_difference))) {\n      neighbors_to_exclude.push_back(neighbor);\n    }\n  }\n\n  ASSERT(not alg::found(neighbors_to_exclude, primary_neighbor),\n         \"Logical inconsistency: trying to exclude the primary neighbor.\");\n\n  return neighbors_to_exclude;\n}\n\n// Compute the vector b_s for the constrained fit. For details, see the\n// documentation of `hweno_modified_neighbor_solution` below.\ntemplate <typename Tag, size_t VolumeDim, typename Package>\nDataVector b_vector(\n    const size_t tensor_index, const Mesh<VolumeDim>& mesh,\n    const DataVector& quadrature_weights,\n    const DirectionMap<VolumeDim, Matrix>& interpolation_matrices,\n    const DirectionMap<VolumeDim, DataVector>&\n        quadrature_weights_dot_interpolation_matrices,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, Package,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data,\n    const std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>&\n        primary_neighbor,\n    const std::vector<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>&\n        neighbors_to_exclude) noexcept {\n  const size_t number_of_grid_points = mesh.number_of_grid_points();\n  DataVector b(number_of_grid_points, 0.);\n\n  for (const auto& neighbor_and_data : neighbor_data) {\n    // Generally, neighbors_to_exclude contains just one neighbor to exclude,\n    // and the loop over neighbor_data will hit this (in 3D) roughly 1/6 times.\n    // So the condition is somewhat, but not overwhelmingly, unlikely:\n    if (UNLIKELY(alg::found(neighbors_to_exclude, neighbor_and_data.first))) {\n      continue;\n    }\n\n    const auto& direction = neighbor_and_data.first.first;\n    ASSERT(interpolation_matrices.contains(direction),\n           \"interpolation_matrices does not contain key: \" << direction);\n    ASSERT(\n        quadrature_weights_dot_interpolation_matrices.contains(direction),\n        \"quadrature_weights_dot_interpolation_matrices does not contain key: \"\n            << direction);\n\n    const auto& neighbor_mesh = mesh;\n    const auto& neighbor_quadrature_weights = quadrature_weights;\n    const auto& interpolation_matrix = interpolation_matrices.at(direction);\n    const auto& quadrature_weights_dot_interpolation_matrix =\n        quadrature_weights_dot_interpolation_matrices.at(direction);\n\n    const auto& neighbor_tensor_component =\n        get<Tag>(neighbor_and_data.second.volume_data)[tensor_index];\n\n    // Add terms from the primary neighbor\n    if (neighbor_and_data.first == primary_neighbor) {\n      for (size_t r = 0; r < neighbor_mesh.number_of_grid_points(); ++r) {\n        for (size_t s = 0; s < number_of_grid_points; ++s) {\n          b[s] += neighbor_tensor_component[r] *\n                  neighbor_quadrature_weights[r] * interpolation_matrix(r, s);\n        }\n      }\n    }\n    // Add terms from the secondary neighbors\n    else {\n      const double quadrature_weights_dot_u = [&]() noexcept {\n        double result = 0.;\n        for (size_t r = 0; r < neighbor_mesh.number_of_grid_points(); ++r) {\n          result +=\n              neighbor_tensor_component[r] * neighbor_quadrature_weights[r];\n        }\n        return result;\n      }();\n      b += quadrature_weights_dot_u *\n           quadrature_weights_dot_interpolation_matrix;\n    }\n  }\n  return b;\n}\n\n// Solve the constrained fit problem that gives the HWENO modified solution,\n// for one particular tensor component. For details, see documentation of\n// `hweno_modified_neighbor_solution` below.\ntemplate <typename Tag, size_t VolumeDim, typename Package>\nvoid solve_constrained_fit(\n    const gsl::not_null<DataVector*> constrained_fit_result,\n    const DataVector& u, const size_t tensor_index, const Mesh<VolumeDim>& mesh,\n    const Element<VolumeDim>& element,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, Package,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data,\n    const std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>&\n        primary_neighbor,\n    const std::vector<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>&\n        neighbors_to_exclude) noexcept {\n  ASSERT(not alg::found(neighbors_to_exclude, primary_neighbor),\n         \"Logical inconsistency: trying to exclude the primary neighbor.\");\n  ASSERT(not neighbors_to_exclude.empty() or neighbor_data.size() == 1,\n         \"The HWENO constrained fit algorithm expects at least one neighbor \\n\"\n         \"to exclude from the fit (unless if the element has a single \\n\"\n         \"neighbor, which would automatically be the primary neighbor).\");\n\n  // Get the cache of linear algebra quantities for this element\n  const ConstrainedFitCache<VolumeDim>& cache =\n      constrained_fit_cache(element, mesh);\n\n  // Because we don't support h-refinement, the direction is the only piece\n  // of the neighbor information that we actually need.\n  const Direction<VolumeDim> primary_direction = primary_neighbor.first;\n  const std::vector<Direction<VolumeDim>> directions_to_exclude =\n      [&neighbors_to_exclude]() noexcept {\n        std::vector<Direction<VolumeDim>> result(neighbors_to_exclude.size());\n        for (size_t i = 0; i < result.size(); ++i) {\n          result[i] = neighbors_to_exclude[i].first;\n        }\n        return result;\n      }();\n\n  const DataVector& w = cache.quadrature_weights;\n  const DirectionMap<VolumeDim, Matrix>& interp_matrices =\n      cache.interpolation_matrices;\n  const DirectionMap<VolumeDim, DataVector>& w_dot_interp_matrices =\n      cache.quadrature_weights_dot_interpolation_matrices;\n\n  // Use cache if possible, or compute matrix if we are in edge case\n  const Matrix& inverse_a =\n      LIKELY(directions_to_exclude.size() < 2)\n          ? cache.retrieve_inverse_a_matrix(primary_direction,\n                                            directions_to_exclude)\n          : inverse_a_matrix(mesh, element, w, interp_matrices,\n                             w_dot_interp_matrices, primary_direction,\n                             directions_to_exclude);\n\n  const DataVector b = b_vector<Tag>(tensor_index, mesh, w, interp_matrices,\n                                     w_dot_interp_matrices, neighbor_data,\n                                     primary_neighbor, neighbors_to_exclude);\n\n  const size_t number_of_points = b.size();\n  const DataVector inverse_a_times_b = apply_matrices(\n      std::array<std::reference_wrapper<const Matrix>, 1>{{inverse_a}}, b,\n      Index<1>(number_of_points));\n  const DataVector inverse_a_times_w = apply_matrices(\n      std::array<std::reference_wrapper<const Matrix>, 1>{{inverse_a}}, w,\n      Index<1>(number_of_points));\n\n  // Compute Lagrange multiplier:\n  // Note: we take w as an argument (instead of as a lambda capture), because\n  //       some versions of Clang incorrectly warn about capturing w.\n  const double lagrange_multiplier = [&number_of_points, &inverse_a_times_b,\n                                      &inverse_a_times_w,\n                                      &u](const DataVector& local_w) noexcept {\n    double numerator = 0.;\n    double denominator = 0.;\n    for (size_t s = 0; s < number_of_points; ++s) {\n      numerator += local_w[s] * (inverse_a_times_b[s] - u[s]);\n      denominator += local_w[s] * inverse_a_times_w[s];\n    }\n    return -numerator / denominator;\n  }(w);\n\n  // Compute solution:\n  *constrained_fit_result =\n      inverse_a_times_b + lagrange_multiplier * inverse_a_times_w;\n}\n\n/*!\n * \\ingroup LimitersGroup\n * \\brief Compute the HWENO solution for one tensor\n *\n * The HWENO limiter reconstructs a new solution from the linear combination of\n * the local DG solution and a \"modified\" solution from each neighbor element.\n * This function computes the modified solution for a particular tensor and\n * neighbor, following Section 3 of \\cite Zhu2016.\n *\n * The modified solution associated with a particular neighbor (the \"primary\"\n * neighbor) is obtained by solving a constrained fit over the local element,\n * the primary neighbor, and the other (\"secondary\") neighbors of the local\n * element. This fit seeks to minimize in a least-squared sense:\n * 1. The distance between the modified solution and the original solution on\n *    the primary neighbor.\n * 2. The distance between the cell average of the modified solution and the\n *    cell average of the original solution on each secondary neighbor. Note\n *    however that one secondary neighbor (or, rarely, several) is excluded from\n *    this minimization: the secondary neighbor(s) where the original solution\n *    has the most different cell average from the local element. This helps to\n *    prevent an outlier (e.g., near a shock) from biasing the fit.\n *\n * The constraint on the minimization is the following: the cell average of the\n * modified solution on the local element must equal the cell average of the\n * local element's original solution.\n *\n * Below we give the mathematical form of the constraints described above and\n * show how these are translated into a numerical algorithm.\n *\n * Consider an element \\f$I_0\\f$ with neighbors \\f$I_1, I_2, ...\\f$. For a\n * given tensor component \\f$u\\f$, the values on each of these elements are\n * \\f$u^{(0)}, u^{(1)}, u^{(2)}, ...\\f$. Taking for the sake of example the\n * primary neighbor to be \\f$I_1\\f$, the modified solution \\f$\\phi\\f$ must\n * minimize\n *\n * \\f[\n * \\chi^2 = \\int_{I_1} (\\phi - u^{(1)})^2 dV\n *          + \\sum_{\\ell \\in L} \\left(\n *                              \\int_{I_{\\ell}} ( \\phi - u^{(\\ell)} ) dV\n *                              \\right)^2,\n * \\f]\n *\n * subject to the constaint\n *\n * \\f[\n * C = \\int_{I_0} ( \\phi - u^{(0)} ) dV = 0.\n * \\f]\n *\n * where \\f$\\ell\\f$ ranges over a subset \\f$L\\f$ of the secondary neighbors.\n * \\f$L\\f$ excludes the one (or more) secondary neighbor(s) where the mean of\n * \\f$u\\f$ is the most different from the mean of \\f$u^{(0)}\\f$. Typically, only\n * one secondary neighbor is excluded, so \\f$L\\f$ contains two fewer neighbors\n * than the total number of neighbors to the element. Note that in 1D, this\n * implies that \\f$L\\f$ is the empty set; for each modified solution, one\n * neighbor is the primary neighbor and the other is the excluded neighbor.\n *\n * The integrals are evaluated by quadrature. We denote the quadrature weights\n * by \\f$w_s\\f$ and the values of some data \\f$X\\f$ at the quadrature\n * nodes by \\f$X_s\\f$. We use subscripts \\f$r,s\\f$ to denote quadrature nodes\n * on the neighbor and local elements, respectively. The minimization becomes\n *\n * \\f[\n * \\chi^2 = \\sum_r w^{(1)}_r ( \\phi_r - u^{(1)}_r )^2\n *          + \\sum_{\\ell \\in L} \\left(\n *                              \\sum_r w^{(\\ell)}_r ( \\phi_r - u^{(\\ell)}_r )\n *                              \\right)^2,\n * \\f]\n *\n * subject to the constraint\n *\n * \\f[\n * C = \\sum_s w^{(0)}_s ( \\phi_s - u^{(0)}_s ) = 0.\n * \\f]\n *\n * Note that \\f$\\phi\\f$ is a function defined on the local element \\f$I_0\\f$,\n * and so is fully represented by its values \\f$\\phi_s\\f$ at the quadrature\n * points on this element. When evaluating \\f$\\phi\\f$ on element \\f$I_{\\ell}\\f$,\n * we obtain the function values \\f$\\phi_r\\f$ by polynomial extrapolation,\n * \\f$\\phi_r = \\sum_s \\mathcal{I}^{(\\ell)}_{rs} \\phi_s\\f$, where\n * \\f$\\mathcal{I}^{(\\ell)}_{rs}\\f$ is the interpolation/extrapolation matrix\n * that interpolates data defined at grid points \\f$x_s\\f$ and evaluates it at\n * grid points \\f$x_r\\f$ of \\f$I_{\\ell}\\f$. Thus,\n *\n * \\f[\n * \\chi^2 = \\sum_r w^{(1)}_r\n *                 \\left(\n *                 \\sum_s \\mathcal{I}^{(1)}_{rs} \\phi_s - u^{(1)}_r\n *                 \\right)^2\n *          + \\sum_{\\ell \\in L} \\left(\n *                              \\sum_r w^{(\\ell)}_r\n *                                     \\left(\n *                                     \\sum_s \\mathcal{I}^{(\\ell)}_{rs} \\phi_s\n *                                             - u^{(\\ell)}_r\n *                                     \\right)\n *                      \\right)^2.\n * \\f]\n *\n * The solution to this optimization problem is found in the standard way,\n * using a Lagrange multiplier \\f$\\lambda\\f$ to impose the constraint:\n *\n * \\f[\n * 0 = \\frac{d}{d \\phi_s} \\left( \\chi^2 + \\lambda C \\right).\n * \\f]\n *\n * Working out the differentiation with respect to \\f$\\phi_s\\f$ leads to the\n * linear problem that must be inverted to obtain the solution,\n *\n * \\f[\n * 0 = A_{st} \\phi_t - b_s - \\lambda w^{(0)}_s,\n * \\f]\n *\n * where\n *\n * \\f{align*}{\n * A_{st} &= \\sum_r \\left( w^{(1)}_r\n *                  \\mathcal{I}^{(1)}_{rs} \\mathcal{I}^{(1)}_{rt}\n *                  \\right)\n *          + \\sum_{\\ell \\in L} \\left(\n *                              \\sum_r \\left(\n *                                     w^{(\\ell)}_r \\mathcal{I}^{(\\ell)}_{rt}\n *                                     \\right)\n *                              \\cdot\n *                              \\sum_r \\left(\n *                                     w^{(\\ell)}_r \\mathcal{I}^{(\\ell)}_{rs}\n *                                     \\right)\n *                              \\right)\n * \\\\\n * b_s &= \\sum_r \\left( w^{(1)}_r u^{(1)}_r \\mathcal{I}^{(1)}_{rs} \\right)\n *         + \\sum_{\\ell \\in L} \\left(\n *                             \\sum_r \\left( w^{(\\ell)}_r u^{(\\ell)}_r \\right)\n *                             \\cdot\n *                             \\sum_r \\left(\n *                                    w^{(\\ell)}_r \\mathcal{I}^{(\\ell)}_{rs}\n *                                    \\right)\n *                             \\right).\n * \\f}\n *\n * Finally, the solution to the constrained fit is\n *\n * \\f{align*}{\n * \\lambda &= - \\frac{ \\sum_s w^{(0)}_s\n *                            \\left( (A^{-1})_{st} b_t - u^{(0)}_s \\right)\n *              }{ \\sum_s w^{(0)}_s (A^{-1})_{st} w^{(0)}_t }\n * \\\\\n * \\phi_s &= (A^{-1})_{st} ( b_t + \\lambda w^{(0)}_t ).\n * \\f}\n *\n * Note that the matrix \\f$A\\f$ does not depend on the values of the tensor\n * \\f$u\\f$, so its inverse \\f$A^{-1}\\f$ can be precomputed and stored.\n *\n * \\warning\n * Note also that the implementation currently does not support h- or\n * p-refinement; this is checked by some assertions. The implementation is\n * untested for grids where elements are curved, and it should not be expected\n * to work in these cases.\n *\n * When calling `hweno_impl`, `modified_neighbor_solution_buffer` should contain\n * one DataVector for each neighboring element (i.e. for each entry in\n * `neighbor_data`).\n */\ntemplate <typename Tag, size_t VolumeDim, typename PackagedData>\nvoid hweno_impl(\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  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 hweno_impl.\");\n\n  alg::for_each(\n      neighbor_data, [&element, &mesh](const auto& neighbor_and_data) noexcept {\n        ASSERT(Weno_detail::check_element_has_one_similar_neighbor_in_direction(\n                   element, neighbor_and_data.first.first),\n               \"Found some amount of h-refinement; this is not supported\");\n        ASSERT(neighbor_and_data.second.mesh == mesh,\n               \"Found some amount of p-refinement; this is not supported\");\n      });\n\n  for (size_t tensor_index = 0; tensor_index < tensor->size(); ++tensor_index) {\n    const auto& tensor_component = (*tensor)[tensor_index];\n    for (const auto& neighbor_and_data : neighbor_data) {\n      const auto& primary_neighbor = neighbor_and_data.first;\n      const auto neighbors_to_exclude =\n          secondary_neighbors_to_exclude_from_fit<Tag>(\n              mean_value(tensor_component, mesh), tensor_index, neighbor_data,\n              primary_neighbor);\n\n      DataVector& buffer =\n          modified_neighbor_solution_buffer->at(primary_neighbor);\n      solve_constrained_fit<Tag>(make_not_null(&buffer), tensor_component,\n                                 tensor_index, mesh, element, neighbor_data,\n                                 primary_neighbor, neighbors_to_exclude);\n    }\n\n    // Sum local and modified neighbor polynomials for the WENO reconstruction\n    Weno_detail::reconstruct_from_weighted_sum(\n        make_not_null(&((*tensor)[tensor_index])), neighbor_linear_weight,\n        Weno_detail::DerivativeWeight::PowTwoEllOverEllFactorial, mesh,\n        *modified_neighbor_solution_buffer);\n  }\n}\n\n}  // namespace Limiters::Weno_detail\n", "meta": {"hexsha": "e795ab5e9cf785ebaa6185386a8a6a0c161f13e6", "size": 26378, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/HwenoImpl.hpp", "max_stars_repo_name": "Ambrou/spectre", "max_stars_repo_head_hexsha": "a819ebbcca607d8af9683db3683bea14bf4ac23c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/HwenoImpl.hpp", "max_issues_repo_name": "Ambrou/spectre", "max_issues_repo_head_hexsha": "a819ebbcca607d8af9683db3683bea14bf4ac23c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/HwenoImpl.hpp", "max_forks_repo_name": "Ambrou/spectre", "max_forks_repo_head_hexsha": "a819ebbcca607d8af9683db3683bea14bf4ac23c", "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": 45.4793103448, "max_line_length": 80, "alphanum_fraction": 0.6789749033, "num_tokens": 6180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.0367694662075391, "lm_q1q2_score": 0.016666196203768465}}
{"text": "#include \"optimizers.hpp\"\n#include \"modeling.hpp\"\n#include \"utils/logging.hpp\"\n#include <boost/foreach.hpp>\n#include \"solver_interface.hpp\"\n#include \"expr_ops.hpp\"\n#include <cmath>\n#include <cstdio>\n#include \"sco_common.hpp\"\n#include \"utils/stl_to_string.hpp\"\n#include \"macros.h\"\n#include <boost/format.hpp>\nusing namespace std;\nusing namespace util;\n\nnamespace sco {\n\ntypedef vector<double> DblVec;\n\nstd::ostream& operator<<(std::ostream& o, const OptResults& r) {\n  o << \"Optimization results:\" << endl\n    << \"status: \" << statusToString(r.status) << endl\n    << \"cost values: \" << Str(r.cost_vals) << endl\n    << \"constraint violations: \" << Str(r.cnt_viols) << endl\n    << \"n func evals: \" << r.n_func_evals << endl\n    << \"n qp solves: \" << r.n_qp_solves << endl;\n  return o;\n}\n\n//////////////////////////////////////////////////\n////////// private utility functions for  sqp /////////\n//////////////////////////////////////////////////\n\n\n\nstatic DblVec evaluateCosts(vector<CostPtr>& costs, const DblVec& x) {\n  DblVec out(costs.size());\n  for (size_t i=0; i < costs.size(); ++i) {\n    out[i] = costs[i]->value(x);\n  }\n  return out;\n}\nstatic DblVec evaluateConstraintViols(vector<ConstraintPtr>& constraints, const DblVec& x) {\n  DblVec out(constraints.size());\n  for (size_t i=0; i < constraints.size(); ++i) {\n    out[i] = constraints[i]->violation(x);\n  }\n  return out;\n}\nstatic vector<ConvexObjectivePtr> convexifyCosts(vector<CostPtr>& costs, const DblVec& x, Model* model) {\n  vector<ConvexObjectivePtr> out(costs.size());\n  for (size_t i=0; i < costs.size(); ++i) {\n    out[i] = costs[i]->convex(x,  model);\n  }\n  return out;\n}\nstatic vector<ConvexConstraintsPtr> convexifyConstraints(vector<ConstraintPtr>& cnts, const DblVec& x, Model* model) {\n  vector<ConvexConstraintsPtr> out(cnts.size());\n  for (size_t i=0; i < cnts.size(); ++i) {\n    out[i] = cnts[i]->convex(x, model);\n  }\n  return out;\n}\n\nDblVec evaluateModelCosts(vector<ConvexObjectivePtr>& costs, const DblVec& x) {\n  DblVec out(costs.size());\n  for (size_t i=0; i < costs.size(); ++i) {\n    out[i] = costs[i]->value(x);\n  }\n  return out;\n}\nDblVec evaluateModelCntViols(vector<ConvexConstraintsPtr>& cnts, const DblVec& x) {\n  DblVec out(cnts.size());\n  for (size_t i=0; i < cnts.size(); ++i) {\n    out[i] = cnts[i]->violation(x);\n  }\n  return out;\n}\n\nstatic vector<string> getCostNames(const vector<CostPtr>& costs) {\n  vector<string> out(costs.size());\n  for (size_t i=0; i < costs.size(); ++i) out[i] = costs[i]->name();\n  return out;\n}\nstatic vector<string> getCntNames(const vector<ConstraintPtr>& cnts) {\n  vector<string> out(cnts.size());\n  for (size_t i=0; i < cnts.size(); ++i) out[i] = cnts[i]->name();\n  return out;\n}\n\nvoid printCostInfo(const vector<double>& old_cost_vals, const vector<double>& model_cost_vals, const vector<double>& new_cost_vals,\n                  const vector<double>& old_cnt_vals, const vector<double>& model_cnt_vals, const vector<double>& new_cnt_vals,\n    const vector<string>& cost_names, const vector<string>& cnt_names, double merit_coeff) {\n    printf(\"%15s | %10s | %10s | %10s | %10s\\n\", \"\", \"oldexact\", \"dapprox\", \"dexact\", \"ratio\");\n    printf(\"%15s | %10s---%10s---%10s---%10s\\n\", \"COSTS\", \"----------\", \"----------\", \"----------\", \"----------\");\n    for (size_t i=0; i < old_cost_vals.size(); ++i) {\n      double approx_improve = old_cost_vals[i] - model_cost_vals[i];\n      double exact_improve = old_cost_vals[i] - new_cost_vals[i];\n      if (fabs(approx_improve) > 1e-8) \n        printf(\"%15s | %10.3e | %10.3e | %10.3e | %10.3e\\n\", cost_names[i].c_str(), old_cost_vals[i], approx_improve, exact_improve, exact_improve/approx_improve);\n      else\n        printf(\"%15s | %10.3e | %10.3e | %10.3e | %10s\\n\",cost_names[i].c_str(), old_cost_vals[i], approx_improve, exact_improve, \"  ------  \");\n    }\n    if (cnt_names.size() == 0) return;\n    printf(\"%15s | %10s---%10s---%10s---%10s\\n\", \"CONSTRAINTS\", \"----------\", \"----------\", \"----------\", \"----------\");\n    for (size_t i=0; i < old_cnt_vals.size(); ++i) {\n      double approx_improve = old_cnt_vals[i] - model_cnt_vals[i];\n      double exact_improve = old_cnt_vals[i] - new_cnt_vals[i];\n      if (fabs(approx_improve > 1e-8)) \n        printf(\"%15s | %10.3e | %10.3e | %10.3e | %10.3e\\n\", cnt_names[i].c_str(), merit_coeff*old_cnt_vals[i], merit_coeff*approx_improve, merit_coeff*exact_improve, exact_improve/approx_improve); \n      else \n        printf(\"%15s | %10.3e | %10.3e | %10.3e | %10s\\n\", cnt_names[i].c_str(), merit_coeff*old_cnt_vals[i], merit_coeff*approx_improve, merit_coeff*exact_improve, \"  ------  \"); \n    }\n\n}\n\n// todo: use different coeffs for each constraint\nvector<ConvexObjectivePtr> cntsToCosts(const vector<ConvexConstraintsPtr>& cnts, double err_coeff, Model* model) {\n  vector<ConvexObjectivePtr> out;\n  BOOST_FOREACH(const ConvexConstraintsPtr& cnt, cnts) {\n    ConvexObjectivePtr obj(new ConvexObjective(model));\n    BOOST_FOREACH(const AffExpr& aff, cnt->eqs_) {\n      obj->addAbs(aff, err_coeff);\n    }\n    BOOST_FOREACH(const AffExpr& aff, cnt->ineqs_) {\n      obj->addHinge(aff, err_coeff);\n    }\n    out.push_back(obj);\n  }\n  return out;\n}\n\nvoid Optimizer::addCallback(const Callback& cb) {\n  callbacks_.push_back(cb);\n}\nvoid Optimizer::callCallbacks(DblVec& x) {\n  for (int i=0; i < callbacks_.size(); ++i) {\n    callbacks_[i](prob_.get(), x);\n  }\n}\n\nvoid Optimizer::initialize(const vector<double>& x) {\n  if (!prob_) PRINT_AND_THROW(\"need to set the problem before initializing\");\n  if (prob_->getVars().size() != x.size()) \n    PRINT_AND_THROW(boost::format(\"initialization vector has wrong length. expected %i got %i\")%prob_->getVars().size()%x.size());\n  results_.clear(); \n  results_.x = x;\n}\n\nBasicTrustRegionSQP::BasicTrustRegionSQP() {\n  initParameters();\n}\nBasicTrustRegionSQP::BasicTrustRegionSQP(OptProbPtr prob) {\n  initParameters();\n  setProblem(prob);\n}\n\nvoid BasicTrustRegionSQP::initParameters() {\n\n  improve_ratio_threshold_ = .25;\n  min_trust_box_size_ = 1e-4;\n  min_approx_improve_= 1e-4;\n  min_approx_improve_frac_ = -INFINITY;\n  max_iter_ = 50;\n  trust_shrink_ratio_=.1;\n  trust_expand_ratio_ = 1.5;\n  cnt_tolerance_ = 1e-4;\n  max_merit_coeff_increases_ = 5;\n  merit_coeff_increase_ratio_ = 10;\n  max_time_ = INFINITY;\n\n  merit_error_coeff_ = 10;\n  trust_box_size_ = 1e-1;\n\n\n}\n\nvoid BasicTrustRegionSQP::setProblem(OptProbPtr prob) {\n  Optimizer::setProblem(prob);\n  model_ = prob->getModel();\n}\n\nvoid BasicTrustRegionSQP::adjustTrustRegion(double ratio) {\n  trust_box_size_ *= ratio;\n}\nvoid BasicTrustRegionSQP::setTrustBoxConstraints(const DblVec& x) {\n  vector<Var>& vars = prob_->getVars();\n  assert(vars.size() == x.size());\n  DblVec& lb=prob_->getLowerBounds(), ub=prob_->getUpperBounds();\n  DblVec lbtrust(x.size()), ubtrust(x.size());\n  vector<bool> incmask = prob_->getIncrementMask();\n  if (incmask.empty()) incmask = vector<bool>(x.size(), false);\n  for (size_t i=0; i < x.size(); ++i) {\n    lbtrust[i] = fmax((incmask[i] ? 0 : x[i]) - trust_box_size_, lb[i]);\n    ubtrust[i] = fmin((incmask[i] ? 0 : x[i]) + trust_box_size_, ub[i]);\n  }\n  model_->setVarBounds(vars, lbtrust, ubtrust);\n}\n\n#if 0\nstruct MultiCritFilter {\n  /**\n   * Checks if you're making an improvement on a multidimensional objective\n   * Given a set of past error vectors, the improvement is defined as\n   * min_{olderrvec in past_err_vecs} | olderrvec - errvec |^+\n   */\n  vector<DblVec> errvecs;\n  double improvement(const DblVec& errvec) {\n    double leastImprovement=INFINITY;\n    BOOST_FOREACH(const DblVec& olderrvec, errvecs) {\n      double improvement=0;\n      for (int i=0; i < errvec.size(); ++i) improvement += pospart(olderrvec[i] - errvec[i]);\n      leastImprovement = fmin(leastImprovement, improvement);\n    }\n    return leastImprovement;\n  }\n  void insert(const DblVec& x) {errvecs.push_back(x);}\n  bool empty() {return errvecs.size() > 0;}\n};\n#endif\n\nOptStatus BasicTrustRegionSQP::optimize() {\n\n  vector<string> cost_names = getCostNames(prob_->getCosts());\n  vector<ConstraintPtr> constraints = prob_->getConstraints();\n  vector<string> cnt_names = getCntNames(constraints);\n\n  DblVec& x_ = results_.x; // just so I don't have to rewrite code\n  if (x_.size() == 0) PRINT_AND_THROW(\"you forgot to initialize!\");\n  if (!prob_) PRINT_AND_THROW(\"you forgot to set the optimization problem\");    \n  \n  x_ = prob_->getClosestFeasiblePoint(x_);\n\n  assert(x_.size() == prob_->getVars().size());\n  assert(prob_->getCosts().size() > 0 || constraints.size() > 0);\n\n  OptStatus retval = INVALID;\n\n  for (int merit_increases=0; merit_increases < max_merit_coeff_increases_; ++merit_increases) { /* merit adjustment loop */\n    for (int iter=1; ; ++iter) { /* sqp loop */\n      callCallbacks(x_);\n\n      LOG_DEBUG(\"current iterate: %s\", CSTR(x_));\n      LOG_INFO(\"iteration %i\", iter);\n\n      // speedup: if you just evaluated the cost when doing the line search, use that\n      if (results_.cost_vals.empty()) { //only happens on the first iteration\n        results_.cnt_viols = evaluateConstraintViols(constraints, x_);\n        results_.cost_vals = evaluateCosts(prob_->getCosts(), x_);\n        assert(results_.n_func_evals == 0);\n        ++results_.n_func_evals;\n      }\n\n      vector<ConvexObjectivePtr> cost_models = convexifyCosts(prob_->getCosts(),x_, model_.get());\n      vector<ConvexConstraintsPtr> cnt_models = convexifyConstraints(constraints, x_, model_.get());\n      vector<ConvexObjectivePtr> cnt_cost_models = cntsToCosts(cnt_models, merit_error_coeff_, model_.get());\n      model_->update();\n      BOOST_FOREACH(ConvexObjectivePtr& cost, cost_models)cost->addConstraintsToModel();\n      BOOST_FOREACH(ConvexObjectivePtr& cost, cnt_cost_models)cost->addConstraintsToModel();\n      model_->update();\n      QuadExpr objective;\n      BOOST_FOREACH(ConvexObjectivePtr& co, cost_models)exprInc(objective, co->quad_);\n      BOOST_FOREACH(ConvexObjectivePtr& co, cnt_cost_models){\n      exprInc(objective, co->quad_);\n    }\n//    objective = cleanupExpr(objective);\n      model_->setObjective(objective);\n\n//    if (logging::filter() >= IPI_LEVEL_DEBUG) {\n//      DblVec model_cost_vals;\n//      BOOST_FOREACH(ConvexObjectivePtr& cost, cost_models) {\n//        model_cost_vals.push_back(cost->value(x));\n//      }\n//      LOG_DEBUG(\"model costs %s should equalcosts  %s\", printer(model_cost_vals), printer(cost_vals));\n//    }\n\n      while (trust_box_size_ >= min_trust_box_size_) {\n\n        setTrustBoxConstraints(x_);\n        CvxOptStatus status = model_->optimize();\n        ++results_.n_qp_solves;\n        if (status != CVX_SOLVED) {\n          LOG_ERROR(\"convex solver failed! set LOG_DEBUG_LEVEL=DEBUG to see solver output. saving model to /tmp/fail.lp\");\n          model_->writeToFile(\"/tmp/fail.lp\");\n          retval = OPT_FAILED;\n          goto cleanup;\n        }\n        DblVec model_var_vals = model_->getVarValues(model_->getVars());\n\n        DblVec model_cost_vals = evaluateModelCosts(cost_models, model_var_vals);\n        DblVec model_cnt_viols = evaluateModelCntViols(cnt_models, model_var_vals);\n\n        // the n variables of the OptProb happen to be the first n variables in the Model\n        DblVec new_x(model_var_vals.begin(), model_var_vals.begin() + x_.size());\n\n        if (GetLogLevel() >= util::LevelDebug) {\n          DblVec model_cnt_viols2 = evaluateModelCosts(cnt_cost_models, model_var_vals);\n          LOG_DEBUG(\"SHOULD BE THE SAME: %.2f*%s ?= %s\", merit_error_coeff_, CSTR(model_cnt_viols), CSTR(model_cnt_viols2));\n        }\n\n        DblVec new_cost_vals = evaluateCosts(prob_->getCosts(), new_x);\n        DblVec new_cnt_viols = evaluateConstraintViols(constraints, new_x);\n        ++results_.n_func_evals;\n\n        double old_merit = vecSum(results_.cost_vals) + merit_error_coeff_ * vecSum(results_.cnt_viols);\n        double model_merit = vecSum(model_cost_vals) + merit_error_coeff_ * vecSum(model_cnt_viols);\n        double new_merit = vecSum(new_cost_vals) + merit_error_coeff_ * vecSum(new_cnt_viols);\n        double approx_merit_improve = old_merit - model_merit;\n        double exact_merit_improve = old_merit - new_merit;\n        double merit_improve_ratio = exact_merit_improve / approx_merit_improve;\n\n        if (util::GetLogLevel() >= util::LevelInfo) {\n          LOG_INFO(\"\");\n          printCostInfo(results_.cost_vals, model_cost_vals, new_cost_vals,\n                        results_.cnt_viols, model_cnt_viols, new_cnt_viols, cost_names,\n                        cnt_names, merit_error_coeff_);\n          printf(\"%15s | %10.3e | %10.3e | %10.3e | %10.3e\\n\", \"TOTAL\", old_merit, approx_merit_improve, exact_merit_improve, merit_improve_ratio);\n        }\n\n        //cout << \"approx merit improve: \" << approx_merit_improve << endl;\n\n        if (approx_merit_improve < -1e-4) {\n          LOG_ERROR(\"approximate merit function got worse (%.3e). (convexification is probably wrong to zeroth order)\", approx_merit_improve);\n        }\n        if (approx_merit_improve < min_approx_improve_) {\n          LOG_INFO(\"converged because improvement was small (%.3e < %.3e)\", approx_merit_improve, min_approx_improve_);\n          retval = OPT_CONVERGED;\n          goto penaltyadjustment;\n        }\n        if (approx_merit_improve / old_merit < min_approx_improve_frac_) {\n          LOG_INFO(\n              \"converged because improvement ratio was small (%.3e < %.3e)\",\n              approx_merit_improve/old_merit, min_approx_improve_frac_);\n          retval = OPT_CONVERGED;\n          goto penaltyadjustment;\n        } \n        else if (exact_merit_improve < 0 || merit_improve_ratio < improve_ratio_threshold_) {\n          adjustTrustRegion(trust_shrink_ratio_);\n          LOG_INFO(\"shrunk trust region. new box size: %.4f\",\n              trust_box_size_);\n        } else {\n          x_ = new_x;\n          results_.cost_vals = new_cost_vals;\n          results_.cnt_viols = new_cnt_viols;\n          adjustTrustRegion(trust_expand_ratio_);\n          LOG_INFO(\"expanded trust region. new box size: %.4f\",trust_box_size_);\n          break;\n        }\n      }\n\n      if (trust_box_size_ < min_trust_box_size_) {\n        LOG_INFO(\"converged because trust region is tiny\");\n        retval = OPT_CONVERGED;\n        goto penaltyadjustment;\n      } else if (iter >= max_iter_) {\n        LOG_INFO(\"iteration limit\");\n        retval = OPT_ITERATION_LIMIT;\n        goto cleanup;\n      }\n    }\n\n    penaltyadjustment:\n    if (results_.cnt_viols.empty() || vecMax(results_.cnt_viols) < cnt_tolerance_) {\n      if (results_.cnt_viols.size() > 0) LOG_INFO(\"woo-hoo! constraints are satisfied (to tolerance %.2e)\", cnt_tolerance_);\n      goto cleanup;\n    }\n    else {\n      merit_error_coeff_ *= merit_coeff_increase_ratio_;\n      LOG_INFO(\"not all constraints are satisfied. increasing penalties to %.4f\", merit_error_coeff_);\n      trust_box_size_ = fmax(trust_box_size_, min_trust_box_size_ * 5);\n    }\n\n\n\n  }\n  retval = OPT_ITERATION_LIMIT;\n  LOG_INFO(\"optimization couldn't satisfy all constraints\");\n\n\n  cleanup:\n  assert(retval != INVALID && \"should never happen\");\n  results_.status = retval;\n  results_.total_cost = vecSum(results_.cost_vals);\n  LOG_INFO(\"\\n==================\\n%s==================\", CSTR(results_));\n  callCallbacks(x_);\n\n  return retval;\n\n}\n\n\n}\n", "meta": {"hexsha": "132749e979a25408bd393c16fa2af13b85e1d181", "size": 15230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sco/optimizers.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/sco/optimizers.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/sco/optimizers.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": 38.7531806616, "max_line_length": 198, "alphanum_fraction": 0.659422193, "num_tokens": 4211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.033589508673293675, "lm_q1q2_score": 0.016663547987780924}}
{"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 xmg_exact_decomp.hpp\n *\n * @brief Exact MAJ decomposition\n *\n * @author Mathias Soeken\n * @author Eleonora Testa\n * @since  2.4\n */\n\n#ifndef XMG_EXACT_DECOMP_HPP\n#define XMG_EXACT_DECOMP_HPP\n\n#include <array>\n#include <chrono>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost/optional.hpp>\n\n#include <classical/abc/abc_api.hpp>\n#include <classical/xmg/xmg.hpp>\n#include <fmt/format.h>\n#include <sat/glucose/AbcGlucose.h>\n\nnamespace cirkit\n{\n\nnamespace detail\n{\n\ntemplate<uint32_t NumVars, uint32_t NumGates>\nstruct xmg_exact_decomposition_impl\n{\npublic:\n  xmg_exact_decomposition_impl()\n  {\n    for ( auto& a : select )\n    {\n      for ( auto& a2 : a )\n      {\n        a2.fill( 0 );\n      }\n    }\n\n    add_structure_variables();\n\n    solver = abc::bmcg_sat_solver_start();\n    abc::bmcg_sat_solver_set_nvars( solver, var_index );\n  }\n\n  ~xmg_exact_decomposition_impl()\n  {\n    abc::bmcg_sat_solver_stop( solver );\n  }\n  \n  void write_dimacs(std::string filename)\n  {\n  \tfile.open(filename, std::ofstream::out); \n\tfile << fmt::format( \"P cnf {} {}\",\n                       abc::bmcg_sat_solver_varnum( solver ),\n\t\t\t\t\t   abc::bmcg_sat_solver_clausenum( solver ))\n\t\t << std::endl; \n    file << str; \n  }\n\n  bool run(std::string filename)\n  {\n\t  \n    if ( !add_main_cnf() )\n    {\n      return false;\n    }\n\n    // add value CNF for each interesting minterm\n    for ( uint32_t i = 0; i < ( uint32_t( 1 ) << NumVars ); ++i )\n    {\n      auto cnt = __builtin_popcount( i );\n\n      switch ( cnt )\n      {\n      default:\n        break;\n      case NumVars / 2 - 1:\n        if ( !add_minterm( i, 0 ) )\n        {\n          return false;\n        }\n        break;\n      case NumVars / 2 + 1:\n        if ( !add_minterm( i, 1 ) )\n        {\n          return false;\n        }\n        break;\n      case NumVars / 2:\n        if ( !add_minterm( i, 2 ) )\n        {\n          return false;\n        }\n        break;\n      }\n    }\n\n    /* write dimacs file */\n\twrite_dimacs(filename);\n\t\n    /* solving time */\n    const auto start = std::chrono::high_resolution_clock::now();\n    const auto result = abc::bmcg_sat_solver_solve( solver, nullptr, 0 );\n    const auto stop = std::chrono::high_resolution_clock::now();\n\n    solving_time = std::chrono::duration<double>{stop - start}.count();\n\n    if ( result == GLUCOSE_SAT )\n    {\n      return true;\n    }\n    return false;\n  }\n  \n \n  void print_statistics( std::ostream& os = std::cout )\n  {\n    os << fmt::format( \"[i] vars = {}   cls = {}   learnt = {}   conf = {}   time = {:.2f}\",\n                       abc::bmcg_sat_solver_varnum( solver ),\n                       abc::bmcg_sat_solver_clausenum( solver ),\n                       abc::bmcg_sat_solver_learntnum( solver ),\n                       abc::bmcg_sat_solver_conflictnum( solver ),\n                       solving_time )\n       << std::endl;\n  }\n\n  void print_solution( std::ostream& os = std::cout )\n  {\n    for ( auto i = 0; i < NumGates; ++i )\n    {\n      os << fmt::format( \"n{} = <\", i + NumVars + 1 );\n\n      for ( auto k = 0; k < 3; ++k )\n      {\n        for ( auto j = 0; j < NumVars + i; ++j )\n        {\n          if ( select[i][k][j] && abc::bmcg_sat_solver_read_cex_varvalue( solver, select[i][k][j] ) )\n          {\n            os << fmt::format( \"{}{}\", j < NumVars ? 'x' : 'n', j + 1 );\n          }\n        }\n      }\n\n      os << \">\" << std::endl;\n    }\n  }\n\n  xmg_graph extract_circuit()\n  {\n    xmg_graph g;\n\n    std::vector<xmg_function> functions;\n\n    for ( auto i = 0; i < NumVars; ++i )\n    {\n      functions.push_back( g.create_pi( fmt::format( \"x{}\", i + 1 ) ) );\n    }\n\n    for ( auto i = 0; i < NumGates; ++i )\n    {\n      std::vector<xmg_function> children;\n\n      for ( auto k = 0; k < 3; ++k )\n      {\n        for ( auto j = 0; j < NumVars + i; ++j )\n        {\n          if ( select[i][k][j] && abc::bmcg_sat_solver_read_cex_varvalue( solver, select[i][k][j] ) )\n          {\n            children.push_back( functions[j] );\n          }\n        }\n      }\n\n      assert( children.size() == 3u );\n\n      functions.push_back( g.create_maj( children[0], children[1], children[2] ) );\n    }\n\n    const auto out = g.create_maj( g.create_pi( fmt::format( \"x{}\", NumVars ) ), functions[functions.size() - 2], functions[functions.size() - 1] );\n    g.create_po( out, \"f\" );\n\n    return g;\n  }\n\nprivate:\n  bool add_clause(abc::bmcg_sat_solver* solver, std::vector<int> lits, int size)\n  { \n\t  for (auto& l : lits)\n\t  {\n\t\t  auto divs = l/2; \n\t\t  if (l%2 == 0)\n\t\t\t  //str << divs << \" \";\n\t\t      str += fmt::format( \"{} \", divs); \n\t\t  else \n\t\t\t  str += fmt::format( \"-{} \", divs);\n\t\t\t  \n\t  }\n\t  str += \"0\\n\"; \n\t  \n\t  if (!abc::bmcg_sat_solver_addclause( solver, &lits[0], size))\n\t\t  {\n\t\t\t  return false; \n\t\t  }\n\t  return true;  \n  } \n  \n  void add_structure_variables()\n  {\n    /* first gate is <x1x2x3> */\n    for ( auto k = 0; k < 3; ++k )\n    {\n      select[0][k][k] = var_index++;\n    }\n\n    for ( auto i = 1; i < NumGates; ++i )\n    {\n      for ( auto k = 0; k < 3; ++k )\n      {\n        const auto max = ( k == 0 ) ? NumVars : ( ( i == NumGates - 1 ) ? NumVars + i - 1 : NumVars + i );\n        for ( auto j = 0; j < max; ++j )\n        {\n          select[i][k][j] = var_index;\n          if ( j >= NumVars && ( j - NumVars ) < NumGates - 2 )\n          {\n            output_lits[j - NumVars].push_back( abc::Abc_Var2Lit( var_index, 0 ) );\n          }\n          var_index++;\n        }\n      }\n    }\n  }\n\n  bool add_main_cnf()\n  {\n    /* every node has three children */\n    for ( auto i = 0; i < NumGates; ++i )\n    {\n      for ( auto k = 0; k < 3; ++k )\n      {\n        std::vector<int> lits;\n\n        for ( auto j = 0; j < NumVars + i; ++j )\n        {\n          if ( !select[i][k][j] )\n            continue;\n\n          lits.push_back( abc::Abc_Var2Lit( select[i][k][j], 0 ) );\n        }\n\n        if ( !add_clause( solver, lits, lits.size() ) )\n        {\n          return false;\n        }\n\n        for ( auto l = 1; l < lits.size(); ++l )\n        {\n          for ( auto m = 0; m < l; ++m )\n          {\n            std::vector<int> plits = {abc::Abc_LitNot( lits[m] ), abc::Abc_LitNot( lits[l] )};\n            if ( !add_clause( solver, plits, 2 ) )\n            {\n              return false;\n            }\n          }\n        }\n\n        /* symmetry breaking */\n        if ( k == 2 )\n          break;\n\n        for ( auto l = 1; l < NumVars + i; ++l )\n        {\n          for ( auto m = 0; m < l; ++m )\n          {\n            // select[i][k][l] -> !select[i][k + 1][m]\n            if ( !select[i][k][l] || !select[i][k + 1][m] )\n              continue;\n\n            std::vector<int> plits = {abc::Abc_Var2Lit( select[i][k][l], 1 ), abc::Abc_Var2Lit( select[i][k + 1][m], 1 )};\n            if ( !add_clause( solver, plits, 2 ) )\n            {\n              return false;\n            }\n          }\n        }\n      }\n\n      /* no gate appears twice */\n      for ( auto ii = 0; ii < i; ++ii )\n      {\n        for ( auto l = 2; l < NumVars + ii; ++l )\n        {\n          for ( auto m = 1; m < l; ++m )\n          {\n            for ( auto n = 0; n < m; ++n )\n            {\n              if ( !select[i][0][n] || !select[i][1][m] || !select[i][2][l] || !select[ii][0][n] || !select[ii][1][m] || !select[ii][2][l] )\n                continue;\n\n              std::vector<int> plits = {abc::Abc_Var2Lit( select[i][0][n], 1 ), abc::Abc_Var2Lit( select[i][1][m], 1 ), abc::Abc_Var2Lit( select[i][2][l], 1 ),\n                             abc::Abc_Var2Lit( select[ii][0][n], 1 ), abc::Abc_Var2Lit( select[ii][1][m], 1 ), abc::Abc_Var2Lit( select[ii][2][l], 1 )};\n              if ( !add_clause( solver, plits, 6 ) )\n              {\n                return false;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    /* every gate needs to be used */\n    for ( auto& lits : output_lits )\n    {\n      if ( !add_clause( solver, lits, lits.size() ) )\n      {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  bool add_minterm( uint32_t minterm, int expected_value )\n  {\n    std::array<bool, NumVars> assignment;\n\n    for ( auto i = 0; i < NumVars; ++i )\n    {\n      assignment[i] = ( minterm >> i ) & 1;\n    }\n\n    abc::bmcg_sat_solver_set_nvars( solver, var_index + 4 * NumGates );\n\n    /* structure propagation */\n    for ( auto i = 0; i < NumGates; ++i )\n    {\n      const auto base_var_i = var_index + 4 * i;\n\n      for ( auto k = 0; k < 3; ++k )\n      {\n\n        for ( auto j = 0; j < NumVars + i; ++j )\n        {\n          if ( !select[i][k][j] )\n            continue;\n\n          std::vector<int> lits;\n          lits.push_back( abc::Abc_Var2Lit( select[i][k][j], 1 ) );\n\n          if ( j < NumVars ) /* node i'th k'th input should have value of PI j */\n          {\n            lits.push_back( abc::Abc_Var2Lit( base_var_i + k, assignment[j] ? 0 : 1 ) );\n            if ( !add_clause( solver, lits, lits.size() ) )\n            {\n              return false;\n            }\n          }\n          else /* node i'th k'th input should have value of node j */\n          {\n            const auto base_var_j = var_index + 4 * ( j - NumVars );\n            lits.push_back( abc::Abc_Var2Lit( base_var_j + 3, 0 ) );\n            lits.push_back( abc::Abc_Var2Lit( base_var_i + k, 1 ) );\n            if ( !add_clause( solver, lits, lits.size() ) )\n            {\n              return false;\n            }\n            lits[1] = abc::Abc_LitNot( lits[1] );\n            lits[2] = abc::Abc_LitNot( lits[2] );\n            if ( !add_clause( solver, lits, lits.size() ) )\n            {\n              return false;\n            }\n          }\n        }\n      }\n\n      for ( auto n = 0; n < 2; ++n )\n      {\n        if ( i >= NumGates - 2 && expected_value < 2 && n == expected_value )\n        {\n          continue;\n        }\n\n        for ( auto k = 0; k < 3; k++ )\n        {\n          std::vector<int> pLits(3); \n\t\t  int nLits = 0;\n          if ( k != 0 )\n          {\n            pLits[nLits++] = abc::Abc_Var2Lit( base_var_i + 0, n );\n          }\n          if ( k != 1 )\n          {\n            pLits[nLits++] = abc::Abc_Var2Lit( base_var_i + 1, n );\n          }\n          if ( k != 2 )\n          {\n            pLits[nLits++] = abc::Abc_Var2Lit( base_var_i + 2, n );\n          }\n          if ( i < NumGates - 2 || expected_value == 2 )\n          {\n            pLits[nLits++] = abc::Abc_Var2Lit( base_var_i + 3, !n );\n          }\n          assert( nLits <= 3 );\n          if ( !add_clause( solver, pLits, nLits ) )\n          {\n            return false;\n          }\n        }\n      }\n    }\n\n    /* special case for expected_value == 2 */\n    if ( expected_value == 2 )\n    {\n      std::vector<int> pLits(2); \n      pLits[0] = abc::Abc_Var2Lit( var_index + 4 * ( NumGates - 2 ) + 3, 0 );\n      pLits[1] = abc::Abc_Var2Lit( var_index + 4 * ( NumGates - 1 ) + 3, 0 );\n      if ( !add_clause( solver, pLits, 2 ) )\n      {\n        return false;\n      }\n      pLits[0] = abc::Abc_LitNot( pLits[0] );\n      pLits[1] = abc::Abc_LitNot( pLits[1] );\n      if ( !add_clause( solver, pLits, 2 ) )\n      {\n        return false;\n      }\n    }\n\n    var_index += 4 * NumGates;\n\n    return true;\n  }\n\nprivate:\n  std::array<std::array<std::array<int, NumGates + NumVars - 1>, 3>, NumGates> select;\n  std::array<std::vector<int>, NumGates - 2> output_lits;\n\n  abc::bmcg_sat_solver* solver;\n\n  int var_index = 1;\n  \n  std::ofstream file;\n  std::string str; \n\n  double solving_time = 0.0;\n};\n}\n\ntemplate<uint32_t NumVars, uint32_t NumGates>\nboost::optional<xmg_graph> xmg_exact_decomposition (std::string filename)\n{\n  detail::xmg_exact_decomposition_impl<NumVars, NumGates> impl;\n  const auto result = impl.run(filename);\n  impl.print_statistics();\n  if ( result )\n  {\n    impl.print_solution();\n\n    return impl.extract_circuit();\n  }\n  else\n  {\n    std::cout << \"[i] no circuit found\" << std::endl;\n    return boost::none;\n  }\n}\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": "87bfe1dcb928a77363a4b04bdce39d019d83248e", "size": 13214, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/classical/xmg/xmg_exact_decomp.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": "src/classical/xmg/xmg_exact_decomp.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": "src/classical/xmg/xmg_exact_decomp.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": 25.6582524272, "max_line_length": 159, "alphanum_fraction": 0.503632511, "num_tokens": 3985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.039048291607938254, "lm_q1q2_score": 0.016647129295324786}}
{"text": "//\r\n// Created by bevan on 29/11/2020.\r\n//\r\n\r\n#ifndef LIBAPR_APRDENOISE_H\r\n#define LIBAPR_APRDENOISE_H\r\n\r\n#include <Eigen/Dense>\r\n#include <Eigen/Sparse>\r\n#include <unsupported/Eigen/IterativeSolvers>\r\n\r\n#include <random>\r\n#include <unordered_set>\r\n\r\n#include \"data_structures/Mesh/PixelData.hpp\"\r\n#include \"io/hdf5functions_blosc.h\"\r\n#include \"data_structures/APR/APR.hpp\"\r\n#include \"data_structures/APR/particles/ParticleData.hpp\"\r\n#include \"numerics/APRReconstruction.hpp\"\r\n\r\n//Helper classes\r\n\r\ntemplate<typename stencilType>\r\nclass Stencil {\r\npublic:\r\n    std::vector<stencilType> linear_coeffs;\r\n\r\n    std::vector<int> stencil_dims = {0, 0, 0};\r\n\r\n};\r\n\r\n\r\nclass StencilSetUp {\r\n\r\npublic:\r\n\r\n    StencilSetUp(APR& apr) {\r\n      auto it = apr.iterator();\r\n      dim = it.number_dimensions();\r\n    }\r\n\r\n    size_t dim;\r\n    std::vector<int64_t> index;\r\n    std::vector<std::vector<int>> stencil_index_base;\r\n\r\n    PixelData<double> stencil_index_1;\r\n    PixelData<double> stencil_index_2;\r\n\r\n    int stencil_span;\r\n\r\n    std::vector<int> stencil_dims = {0, 0, 0};\r\n\r\n    size_t center_index;\r\n\r\n    std::vector<uint64_t> l_index_1;\r\n\r\n    std::vector<uint64_t> nl_index_1;\r\n    std::vector<uint64_t> nl_index_2;\r\n\r\n\r\n    void stencil_l_index() {\r\n\r\n        l_index_1.resize(stencil_index_base.size() - 1, 0);\r\n\r\n        size_t counter = 0;\r\n\r\n        for (size_t i = 0; i < l_index_1.size(); ++i) {\r\n            if (i != center_index) {\r\n                l_index_1[counter] = i;\r\n                counter++;\r\n            }\r\n        }\r\n\r\n\r\n    }\r\n\r\n\r\n    void setup_standard(std::vector<int> &stencil_dims_in) {\r\n\r\n\r\n        stencil_dims[0] = stencil_dims_in[0];\r\n        stencil_dims[1] = stencil_dims_in[1];\r\n        stencil_dims[2] = stencil_dims_in[2];\r\n\r\n        std::vector<int> temp;\r\n        temp.resize(3);\r\n\r\n        uint64_t counter = 0;\r\n\r\n        for (int i = -stencil_dims[2]; i < (stencil_dims[2] + 1); ++i) {\r\n            for (int j = -stencil_dims[1]; j < (stencil_dims[1] + 1); ++j) {\r\n                for (int k = -stencil_dims[0]; k < (stencil_dims[0] + 1); ++k) {\r\n\r\n                    temp[0] = k;\r\n                    temp[1] = j;\r\n                    temp[2] = i;\r\n                    stencil_index_base.push_back(temp);\r\n\r\n                    if ((i == 0) && (j == 0) && (k == 0)) {\r\n                        center_index = counter;\r\n                    } else {\r\n                        l_index_1.push_back(counter);\r\n                    }\r\n\r\n                    counter++;\r\n\r\n                }\r\n            }\r\n        }\r\n\r\n        stencil_span = std::max(stencil_dims[0], std::max(stencil_dims[1], stencil_dims[2]));\r\n\r\n    }\r\n\r\n    template<typename T>\r\n    void calculate_global_index(PixelData<T> &img) {\r\n\r\n        uint64_t x_num = img.x_num + 2 * stencil_span;\r\n        uint64_t y_num = img.y_num + 2 * stencil_span;\r\n\r\n        index.resize(stencil_index_base.size());\r\n\r\n        for (size_t i = 0; i < stencil_index_base.size(); ++i) {\r\n            index[i] = stencil_index_base[i][0] + stencil_index_base[i][1] * y_num +\r\n                       stencil_index_base[i][2] * y_num * x_num;\r\n        }\r\n\r\n\r\n    }\r\n\r\n};\r\n\r\nclass APRStencils {\r\n\r\npublic:\r\n    std::vector<Stencil<float>> stencils;\r\n    int dim;\r\n    int number_levels;\r\n\r\n    void init(int _number_levels,int _dim)  {\r\n      number_levels = _number_levels;\r\n      dim = _dim;\r\n      stencils.resize(number_levels+1);\r\n    }\r\n\r\n\r\n  void read_stencil(const std::string& file_name) {\r\n\r\n    hid_t fileId = H5Fopen(file_name.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\r\n    hid_t base = H5Gopen2(fileId, \"/\", H5P_DEFAULT);\r\n\r\n    int number_levels;\r\n    int dim;\r\n    //stored relative to maximum level to allow the read and write functions to be used with different sized APRs. (inherent assumption of only the image size changing not resolution).\r\n    readAttr(H5T_NATIVE_INT, \"number_levels\", base, &number_levels);\r\n    readAttr(H5T_NATIVE_INT, \"dim\", base, &dim);\r\n\r\n    this->dim = dim;\r\n    this->number_levels = number_levels;\r\n\r\n    stencils.resize(number_levels + 1);\r\n\r\n    for (int d_level = 0; d_level <= number_levels; ++d_level) {\r\n\r\n      auto &stencil = stencils[d_level];\r\n\r\n      std::string level_name = \"_level_\" + std::to_string(d_level);\r\n\r\n      int num_pts_1;\r\n      int num_pts_2;\r\n\r\n      //get the number of points\r\n      readAttr(H5T_NATIVE_INT, \"num_pts_l\" + level_name, base, &num_pts_1);\r\n\r\n      //read in the full stencil\r\n      std::vector<double> coeff_full;\r\n      coeff_full.resize(num_pts_1 + num_pts_2);\r\n\r\n      std::string coeff_n = \"coeff\" + level_name;\r\n\r\n      hdf5_load_data_blosc(base, H5T_NATIVE_DOUBLE, coeff_full.data(), coeff_n.c_str());\r\n\r\n      //now compute the linear stencil\r\n\r\n      stencil.linear_coeffs.resize(num_pts_1, 0); //need to include the 0 center\r\n      auto offset = 0;\r\n\r\n      for (size_t k1 = 0; k1 < stencil.linear_coeffs.size(); ++k1) {\r\n\r\n        stencil.linear_coeffs[k1] = coeff_full[k1 + offset];\r\n\r\n      }\r\n\r\n\r\n    }\r\n\r\n    H5Fclose(fileId);\r\n\r\n  }\r\n\r\n\r\n  void write_stencil(std::string &file_name) {\r\n\r\n    hid_t fileId = hdf5_create_file_blosc(file_name);\r\n\r\n    //hid_t base = H5Gcreate2(fileId, \"/a\",  H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\r\n\r\n    if(this->number_levels==0){\r\n      std::cerr << \"Attempting to write non-intialized APR Stencils\" << std::endl;\r\n    }\r\n\r\n    int _number_levels = this->number_levels;\r\n    //stored relative to maximum level to allow the read and write functions to be used with different sized APRs. (inherent assumption of only the image size changing not resolution).\r\n    writeAttr(H5T_NATIVE_INT, \"number_levels\", fileId, &_number_levels);\r\n\r\n    writeAttr(H5T_NATIVE_INT, \"dim\", fileId, &(this->dim));\r\n\r\n    for (int d_level = 0; d_level <= number_levels; ++d_level) {\r\n\r\n      auto &stencil = stencils[d_level];\r\n\r\n      std::string level_name = \"_level_\" + std::to_string(d_level);\r\n\r\n      int num_pts_linear = stencil.linear_coeffs.size();\r\n\r\n      //get the number of points\r\n      writeAttr(H5T_NATIVE_INT, \"num_pts_l\" + level_name, fileId, &num_pts_linear);\r\n\r\n      int dim1 = stencil.stencil_dims[0];\r\n      int dim2 = stencil.stencil_dims[1];\r\n      int dim3 = stencil.stencil_dims[2];\r\n\r\n      writeAttr(H5T_NATIVE_INT, \"dim_1\" + level_name, fileId, &dim1);\r\n      writeAttr(H5T_NATIVE_INT, \"dim_2\" + level_name, fileId, &dim2);\r\n      writeAttr(H5T_NATIVE_INT, \"dim_3\" + level_name, fileId, &dim3);\r\n\r\n      //read in the full stencil\r\n      std::vector<double> coeff_full;\r\n      coeff_full.resize(num_pts_linear);\r\n\r\n      auto offset = 0;\r\n\r\n      for (size_t k1 = 0; k1 < stencil.linear_coeffs.size(); ++k1) {\r\n\r\n        coeff_full[k1 + offset] = stencil.linear_coeffs[k1];\r\n\r\n      }\r\n\r\n\r\n      writeData(H5T_NATIVE_DOUBLE, \"coeff\" + level_name, coeff_full, fileId);\r\n\r\n    }\r\n\r\n    H5Fclose(fileId);\r\n\r\n  }\r\n\r\n\r\nprivate:\r\n\r\n\r\n    static void readAttr(hid_t type, std::string name, hid_t aGroupId, void *aDest) {\r\n        hid_t attr_id = H5Aopen(aGroupId, name.c_str(), H5P_DEFAULT);\r\n        H5Aread(attr_id, type, aDest);\r\n        H5Aclose(attr_id);\r\n    }\r\n\r\n    static void writeAttr(hid_t type, std::string name, hid_t aGroupId, const void *const aSrc) {\r\n        hsize_t dims[] = {1};\r\n        hdf5_write_attribute_blosc(aGroupId, type, name.c_str(), 1, dims, aSrc);\r\n    }\r\n    template<typename T>\r\n    static void writeData(hid_t type, std::string name, T aContainer, hid_t location) {\r\n        hsize_t dims[] = {aContainer.size()};\r\n        const hsize_t rank = 1;\r\n        hdf5_write_data_blosc(location, type, name.c_str(), rank, dims, aContainer.data(), BLOSC_ZSTD, 1l, 0);\r\n    }\r\n\r\n\r\n\r\n};\r\n\r\nstd::vector<int> sample_without_replacement(int k, int N, std::default_random_engine &gen) {\r\n    // Sample k elements from the range [1, N] without replacement\r\n    // k should be <= N\r\n\r\n    // Create an unordered set to store the samples\r\n    std::unordered_set<int> samples;\r\n\r\n    // Sample and insert values into samples\r\n    for (int r = N - k; r < N; ++r) {\r\n        int v = std::uniform_int_distribution<>(1, r)(gen);\r\n        if (!samples.insert(v).second) samples.insert(r);\r\n    }\r\n\r\n    // Copy samples into vector\r\n    std::vector<int> result(samples.begin(), samples.end());\r\n\r\n    // Shuffle vector\r\n    std::shuffle(result.begin(), result.end(), gen);\r\n\r\n    return result;\r\n}\r\n\r\nclass APRDenoise {\r\n\r\npublic:\r\n\r\n    bool verbose = true;\r\n\r\n    int max_level = 4;\r\n    int others_level = 1;\r\n\r\n    int number_levels = 4;\r\n\r\n    int iteration_max = 1000;\r\n    int iteration_others = 600;\r\n\r\n    int N_max = 1000;\r\n    int N_ = 1000;\r\n\r\n    int level_min = 0;\r\n\r\n    bool estimate_center_flag = true;\r\n\r\n    int train_factor = 3; // minimum number of points above the stencil size required for the stencil to train.\r\n\r\n    float tolerance = 0.05;\r\n\r\n    // Train APR\r\n\r\n    template<typename S>\r\n    void train_denoise(APR &apr, ParticleData <S> &parts, APRStencils &aprStencils) {\r\n\r\n        train_denoise(apr, parts, parts, aprStencils);\r\n    }\r\n\r\n\r\n    template<typename S>\r\n    void train_denoise(APR &apr, ParticleData <S> &parts, ParticleData <S> &parts_gt, APRStencils &aprStencils) {\r\n        //\r\n        //  Trains a level dependent de-noising model\r\n        //\r\n\r\n        auto it = apr.iterator();\r\n        int viable_levels = 0;\r\n\r\n        for(int level = it.level_max(); level >= it.level_min(); level--){\r\n            uint64_t total_parts = it.particles_level_end(level) - it.particles_level_begin(level);\r\n\r\n            //check if enough particles to train a kernel; (K*size of kernel?)\r\n\r\n            int stencil_sz;\r\n            if (level == apr.level_max()) {\r\n              stencil_sz = max_level;\r\n\r\n            } else {\r\n              stencil_sz = others_level;\r\n\r\n            }\r\n\r\n            uint64_t pts = std::pow(2*stencil_sz+1,it.number_dimensions())*train_factor;\r\n\r\n            if(total_parts >= pts){\r\n                viable_levels++;\r\n            }\r\n\r\n        }\r\n\r\n        if(viable_levels < this->number_levels) {\r\n          std::cout << \"Not enough particles at levels to train kernel of desired number of levels\" << std::endl;\r\n          std::cout << \"Setting number of kernel levels to: \" << viable_levels << std::endl;\r\n          this->number_levels = viable_levels;\r\n        }\r\n\r\n        aprStencils.init(this->number_levels,it.number_dimensions());\r\n\r\n        int stencil_level = aprStencils.number_levels;\r\n\r\n        float tol_ = this->tolerance;\r\n\r\n        APRTimer timer(this->verbose);\r\n\r\n        timer.start_timer(\"train\");\r\n\r\n        for (int level = apr.level_max(); level >= apr.level_min(); --level) {\r\n\r\n            StencilSetUp setUp(apr);\r\n\r\n            int stencil_sz;\r\n\r\n            int it;\r\n            int N;\r\n\r\n            if (level == apr.level_max()) {\r\n                stencil_sz = max_level;\r\n                it = iteration_max;\r\n                N = N_max;\r\n            } else {\r\n                it = iteration_others;\r\n                N = N_;\r\n                stencil_sz = others_level;\r\n\r\n            }\r\n\r\n            //set the dimension of the stencils learned.\r\n            std::vector<int> stencil_dim;\r\n            stencil_dim.resize(3);\r\n\r\n            if (aprStencils.dim == 3) {\r\n                stencil_dim[0] = stencil_sz;\r\n                stencil_dim[1] = stencil_sz;\r\n                stencil_dim[2] = stencil_sz;\r\n\r\n            } else if (aprStencils.dim == 2) {\r\n\r\n                stencil_dim[0] = stencil_sz;\r\n                stencil_dim[1] = stencil_sz;\r\n                stencil_dim[2] = 0;\r\n\r\n            } else if (aprStencils.dim == 1) {\r\n\r\n                stencil_dim[0] = stencil_sz;\r\n                stencil_dim[1] = 0;\r\n                stencil_dim[2] = 0;\r\n\r\n            }\r\n\r\n\r\n            setUp.setup_standard(stencil_dim);\r\n\r\n            //change the stencil size, the stencil is way to big for the lower levels.\r\n            assemble_system_guided(apr, parts, parts_gt, setUp, aprStencils.stencils[stencil_level], N, it, level,\r\n                                   tol_,verbose);\r\n\r\n            tol_ = tol_ / 8; // check this is this necessary, and I don't think the decay makes much sense beyond the first two layers. (This was based on a noise reduction per level).\r\n\r\n            if(stencil_level > 1){\r\n              stencil_level--;\r\n            } else {\r\n              break;\r\n            }\r\n\r\n        }\r\n\r\n        timer.stop_timer();\r\n\r\n\r\n    }\r\n\r\n\r\n// Apply model APR\r\n\r\n    template<typename R,typename S>\r\n    void apply_denoise(APR &apr, ParticleData <R> &parts_in, ParticleData <S> &parts_out, APRStencils &aprStencils) {\r\n\r\n        APRTimer timer(this->verbose);\r\n\r\n        int stencil_level = aprStencils.number_levels;\r\n\r\n        timer.start_timer(\"apply\");\r\n\r\n        for (int level = apr.level_max(); level >= std::max((int) apr.level_min(), level_min); --level) {\r\n\r\n\r\n            StencilSetUp setUp(apr);\r\n            setUp.setup_standard(aprStencils.stencils[stencil_level].stencil_dims);\r\n\r\n            apply_conv_guided(apr, parts_in, parts_out, setUp, aprStencils.stencils[stencil_level], level);\r\n\r\n            if(stencil_level > 1){\r\n                stencil_level--;\r\n            }\r\n\r\n        }\r\n        timer.stop_timer();\r\n\r\n    }\r\n\r\n\r\n    template<typename T, typename R,typename S>\r\n    float\r\n    apply_conv_guided(APR &apr, ParticleData <T> &parts_in,ParticleData <R> &parts_out, StencilSetUp &stencilSetUp, Stencil<S> &stencil, int level) {\r\n\r\n        APRTimer timer(this->verbose);\r\n\r\n        PixelData<T> img; //change to be level dependent\r\n\r\n        if(parts_out.size() != parts_in.size()) {\r\n          parts_out.init(apr);\r\n        }\r\n\r\n        int delta = level - apr.level_max();\r\n\r\n        APRReconstruction::interp_img_us_smooth(apr, img, parts_in, false, delta);\r\n\r\n        stencilSetUp.calculate_global_index(img);\r\n\r\n        PixelData<T> pad_img;\r\n\r\n        timer.start_timer(\"pad_img\");\r\n\r\n        paddPixels(img, pad_img, stencilSetUp.stencil_span, stencilSetUp.stencil_span, stencilSetUp.stencil_span);\r\n\r\n        timer.stop_timer();\r\n\r\n        const uint64_t off_y = (uint64_t) stencilSetUp.stencil_span;\r\n        const uint64_t off_x = (uint64_t) std::min((int) stencilSetUp.stencil_span, img.x_num - 1);\r\n        const uint64_t off_z = (uint64_t) std::min((int) stencilSetUp.stencil_span, img.z_num - 1);\r\n\r\n        const uint64_t x_num_p = img.x_num + 2 * off_x;\r\n        const uint64_t y_num_p = img.y_num + 2 * off_y;\r\n\r\n        std::vector<float> local_vec;\r\n\r\n        local_vec.resize(stencilSetUp.index.size(), 0);\r\n\r\n        const int stencil_size = stencilSetUp.index.size();\r\n        const int unroll_size = 16;\r\n        const int loop_sz = (stencil_size / unroll_size) * unroll_size;\r\n\r\n        timer.start_timer(\"conv guided\");\r\n\r\n\r\n        auto it = apr.iterator();\r\n\r\n        int z = 0;\r\n#ifdef HAVE_OPENMP\r\n#pragma omp parallel for schedule(dynamic) private(z) firstprivate(local_vec, it)\r\n#endif\r\n        for (z = 0; z < img.z_num; ++z) {\r\n            for (int x = 0; x < img.x_num; ++x) {\r\n\r\n                float temp_val = 0;\r\n\r\n                const uint64_t global_off = off_y + (off_x + x) * y_num_p + (off_z + z) * x_num_p * y_num_p;\r\n\r\n                for (it.begin(level, z, x); it < it.end(); it++) {\r\n\r\n                    uint64_t y = it.y();\r\n\r\n                    //Get the local stencil of points\r\n                    const uint64_t global_off_l = y + global_off;\r\n\r\n                    int i = 0;\r\n\r\n                    for (; i < loop_sz; i += unroll_size) {\r\n                        local_vec[i] = pad_img.mesh[global_off_l + stencilSetUp.index[i]];\r\n                        local_vec[i + 1] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 1]];\r\n                        local_vec[i + 2] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 2]];\r\n                        local_vec[i + 3] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 3]];\r\n                        local_vec[i + 4] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 4]];\r\n                        local_vec[i + 5] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 5]];\r\n                        local_vec[i + 6] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 6]];\r\n                        local_vec[i + 7] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 7]];\r\n                        local_vec[i + 8] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 8]];\r\n                        local_vec[i + 9] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 9]];\r\n                        local_vec[i + 10] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 10]];\r\n                        local_vec[i + 11] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 11]];\r\n                        local_vec[i + 12] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 12]];\r\n                        local_vec[i + 13] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 13]];\r\n                        local_vec[i + 14] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 14]];\r\n                        local_vec[i + 15] = pad_img.mesh[global_off_l + stencilSetUp.index[i + 15]];\r\n                    }\r\n\r\n                    for (; i < stencil_size; i++) {\r\n                        local_vec[i] = pad_img.mesh[global_off_l + stencilSetUp.index[i]];\r\n                    }\r\n\r\n\r\n                    parts_out[it] = std::inner_product(local_vec.begin(),\r\n                                                 local_vec.end(),\r\n                                                 stencil.linear_coeffs.begin(),\r\n                                                 temp_val);\r\n\r\n                }\r\n            }\r\n        }\r\n\r\n        timer.stop_timer();\r\n\r\n        float time = timer.timings.back();\r\n        return time;\r\n\r\n    }\r\n\r\n\r\n\r\n    template<typename T, typename S>\r\n    void\r\n    assemble_system_guided(APR &apr, ParticleData <T> &parts, ParticleData <T> &parts_g, StencilSetUp &stencilSetUp,\r\n                           Stencil<S> &stencil, uint64_t N, int num_rep, int level, float factor = 0.05,\r\n                           bool verbose = false) {\r\n\r\n        APRTimer timer(this->verbose);\r\n\r\n        PixelData<T> img; //change to be level dependent\r\n        // apr.interp_img(img,parts);\r\n        int delta = (level - apr.level_max());\r\n\r\n        auto level_ = level;\r\n\r\n        auto apr_iterator = apr.iterator();\r\n\r\n        uint64_t total_parts = apr_iterator.particles_level_end(level_) - apr_iterator.particles_level_begin(level_);\r\n\r\n        APRReconstruction::interp_img_us_smooth(apr, img, parts, false, delta);\r\n        stencilSetUp.calculate_global_index(img);\r\n\r\n        if (total_parts < (uint64_t) N) {\r\n            N =  stencilSetUp.l_index_1.size()*this->train_factor;\r\n        }\r\n\r\n        PixelData<T> pad_img;\r\n\r\n        timer.start_timer(\"pad_img\");\r\n\r\n        paddPixels(img, pad_img, stencilSetUp.stencil_span, stencilSetUp.stencil_span, stencilSetUp.stencil_span);\r\n\r\n        timer.stop_timer();\r\n\r\n        const uint64_t off_y = (uint64_t) stencilSetUp.stencil_span;\r\n        const uint64_t off_x = (uint64_t) stencilSetUp.stencil_span;\r\n        const uint64_t off_z = (uint64_t) std::min((int) stencilSetUp.stencil_span, img.z_num - 1);\r\n\r\n        const uint64_t x_num_p = img.x_num + 2 * off_x;\r\n        const uint64_t y_num_p = img.y_num + 2 * off_y;\r\n\r\n        std::vector<T> local_vec;\r\n\r\n        local_vec.resize(stencilSetUp.index.size(), 0);\r\n\r\n        std::vector<float> nl_local_vec;\r\n        nl_local_vec.resize(stencilSetUp.nl_index_1.size(), 0);\r\n\r\n        size_t n =  stencilSetUp.l_index_1.size() + stencilSetUp.nl_index_1.size();\r\n\r\n        std::vector<uint64_t> random_index;\r\n\r\n        random_index.resize(N);\r\n\r\n        auto l_num = stencilSetUp.l_index_1.size();\r\n\r\n        //PixelData<float> A_temp;\r\n        //A_temp.init(n,N,1);\r\n\r\n        std::vector<double> b_temp;\r\n        b_temp.resize(N);\r\n\r\n        std::vector<std::vector<double>> coeff_store;\r\n        coeff_store.resize(num_rep);\r\n\r\n\r\n\r\n        timer.start_timer(\"assemble\");\r\n\r\n\r\n        auto total_p = (img.x_num * img.z_num * img.y_num) / N;\r\n\r\n        total_p = total_parts / N;\r\n\r\n        std::vector<double> A_temp;\r\n        A_temp.resize(n * N, 0);\r\n\r\n        Eigen::Map<Eigen::MatrixXd> A(A_temp.data(), n, N);\r\n\r\n        //Eigen::MatrixXd A(n,N);\r\n\r\n        Eigen::VectorXd coeff_prev(n);\r\n\r\n        std::vector<uint16_t> x_vec;\r\n        std::vector<uint16_t> y_vec;\r\n        std::vector<uint16_t> z_vec;\r\n\r\n        std::vector<uint64_t> global_index;\r\n\r\n\r\n        int z = 0;\r\n        int x = 0;\r\n\r\n\r\n        for (z = 0; z < apr_iterator.z_num(level_); z++) {\r\n            for (x = 0; x < apr_iterator.x_num(level_); ++x) {\r\n\r\n                for (apr_iterator.begin(level_, z, x); apr_iterator < apr_iterator.end(); apr_iterator++) {\r\n\r\n                    x_vec.push_back(x);\r\n                    z_vec.push_back(z);\r\n                    y_vec.push_back(apr_iterator.y());\r\n\r\n                    global_index.push_back(apr_iterator.global_index());\r\n\r\n                }\r\n            }\r\n        }\r\n\r\n        timer.stop_timer();\r\n\r\n        timer.start_timer(\"solve loop\");\r\n\r\n\r\n        for (int l = 0; l < num_rep; ++l) {\r\n\r\n            APRTimer timer_l(verbose);\r\n\r\n            timer_l.start_timer(\"random\");\r\n\r\n            random_index[0] = std::rand() % total_p + 1;\r\n\r\n            for (size_t j = 1; j < random_index.size(); ++j) {\r\n\r\n                random_index[j] = random_index[j - 1] + std::rand() % total_p + 1;\r\n            }\r\n\r\n            timer_l.stop_timer();\r\n\r\n            uint64_t k = 0;\r\n\r\n            timer_l.start_timer(\"A\");\r\n\r\n#ifdef HAVE_OPENMP\r\n#pragma omp parallel for schedule(static) private(k) firstprivate(local_vec)\r\n#endif\r\n            for (k = 0; k < N; ++k) {\r\n\r\n                const uint64_t r_i = random_index[k];\r\n\r\n                const uint64_t z = z_vec[r_i];\r\n                const uint64_t x = x_vec[r_i];\r\n                const uint64_t y = y_vec[r_i];\r\n\r\n                const uint64_t global_off = off_y + (off_x + x) * y_num_p + (off_z + z) * x_num_p * y_num_p;\r\n\r\n                //Get the local stencil of points\r\n                const uint64_t global_off_l = y + global_off;\r\n\r\n                for (size_t i = 0; i < stencilSetUp.index.size(); ++i) {\r\n                    local_vec[i] = pad_img.mesh[global_off_l + stencilSetUp.index[i]];\r\n                }\r\n\r\n                //b_temp[k] = local_vec[stencilSetUp.center_index];\r\n                b_temp[k] = parts_g[global_index[r_i]];\r\n\r\n                for (size_t i = 0; i < stencilSetUp.l_index_1.size(); ++i) {\r\n                    //A_temp(i, k, 0) = local_vec[stencilSetUp.l_index_1[i]];\r\n                    A(i, k) = local_vec[stencilSetUp.l_index_1[i]];\r\n                }\r\n\r\n                //Apply the non-linear kernel\r\n                for (size_t i = 0; i < stencilSetUp.nl_index_1.size(); ++i) {\r\n                    //A_temp(i + l_num, k, 0) =\r\n                    //      local_vec[stencilSetUp.nl_index_1[i]] * local_vec[stencilSetUp.nl_index_2[i]];\r\n                    A(i + l_num, k) =\r\n                            local_vec[stencilSetUp.nl_index_1[i]] * local_vec[stencilSetUp.nl_index_2[i]];\r\n                }\r\n\r\n\r\n            }\r\n\r\n            timer_l.stop_timer();\r\n\r\n            timer_l.start_timer(\"solve\");\r\n\r\n            std::vector<double> norm_c;\r\n            norm_c.resize(n, 0);\r\n\r\n            Eigen::Map<Eigen::VectorXd> norm_c_(norm_c.data(), n);\r\n\r\n\r\n            std::vector<double> std;\r\n\r\n            for (int i = 0; i < A.rows(); i++) {\r\n                Eigen::ArrayXd vec = A.row(i);\r\n                double std_dev = std::sqrt((vec - vec.mean()).square().sum() / (vec.size() - 1));\r\n                //std_dev = 1;\r\n                norm_c_(i) = std_dev;\r\n                A.row(i) = A.row(i) / std_dev;\r\n                std.push_back(std_dev);\r\n            }\r\n\r\n\r\n            Eigen::Map<Eigen::VectorXd> b(b_temp.data(), N);\r\n\r\n            coeff_store[l].resize(n, 0);\r\n\r\n            if (l == 0) {\r\n                float eps = .01;\r\n                for (size_t i = 0; i < n; ++i) {\r\n                    coeff_store[l][i] = std::rand() * 2 * eps - eps;\r\n                }\r\n\r\n\r\n            }\r\n\r\n            Eigen::Map<Eigen::VectorXd> coeff(coeff_store[l].data(), n);\r\n\r\n            Eigen::LeastSquaresConjugateGradient<Eigen::MatrixXd, Eigen::IdentityPreconditioner> solver;\r\n\r\n            //Need to compute desired tol\r\n            float val = factor;\r\n            Eigen::VectorXf ones_v = val * Eigen::VectorXf::Ones(N);\r\n\r\n            float norm_b = b.norm();\r\n            float norm_e = ones_v.norm();\r\n\r\n            float tol = norm_e / norm_b;\r\n\r\n            solver.setMaxIterations(800);\r\n            solver.setTolerance(tol);\r\n            solver.compute(A.transpose());\r\n\r\n            for (int m = 0; m < coeff_prev.size(); ++m) {\r\n                coeff_prev(m) = coeff_prev(m) * norm_c_(m);\r\n            }\r\n\r\n            if (l > 0) {\r\n                solver.setMaxIterations(20);\r\n                coeff = solver.solveWithGuess(b, coeff_prev);\r\n            } else {\r\n                tol *= 0.0001;\r\n                solver.setTolerance(tol);\r\n                coeff = solver.solve(b);\r\n\r\n            }\r\n\r\n\r\n            for (size_t i1 = 0; i1 < n; ++i1) {\r\n                coeff(i1) = coeff(i1) / norm_c_(i1);\r\n            }\r\n\r\n            coeff_prev = coeff;\r\n\r\n            if (verbose) {\r\n                std::cout << \"#iterations: \" << solver.iterations() << std::endl;\r\n            }\r\n\r\n            timer_l.stop_timer();\r\n\r\n        }\r\n\r\n        timer.stop_timer();\r\n\r\n\r\n        //now compute the linear stencil\r\n\r\n        stencil.linear_coeffs.resize(stencilSetUp.index.size(), 0); //need to include the 0 center\r\n        auto offset = 0;\r\n\r\n        stencil.stencil_dims[0] = stencilSetUp.stencil_dims[0];\r\n        stencil.stencil_dims[1] = stencilSetUp.stencil_dims[1];\r\n        stencil.stencil_dims[2] = stencilSetUp.stencil_dims[2];\r\n\r\n        int include = std::floor(0.5 * num_rep);\r\n\r\n        for (size_t k1 = 0; k1 < stencil.linear_coeffs.size(); ++k1) {\r\n\r\n            if (k1 == stencilSetUp.center_index) {\r\n                offset = -1;\r\n            } else {\r\n\r\n                double sum = 0;\r\n                double counter = 0;\r\n\r\n                for (int i = include; i < num_rep; ++i) {\r\n                    sum += coeff_store[i][k1 + offset];\r\n                    counter++;\r\n                }\r\n                stencil.linear_coeffs[k1] = sum / (counter * 1.0);\r\n\r\n            }\r\n\r\n        }\r\n\r\n\r\n\r\n\r\n        if(this->estimate_center_flag) {\r\n          // set the center pixel to the largest weight in the kernel, and then re-normalise the kernel\r\n\r\n          float factor = 0;\r\n          float sum = 0;\r\n\r\n          for (size_t j = 0; j < stencil.linear_coeffs.size(); ++j) {\r\n            factor = std::max(factor, std::abs(stencil.linear_coeffs[j]));\r\n            sum += stencil.linear_coeffs[j];\r\n          }\r\n\r\n          stencil.linear_coeffs[stencilSetUp.center_index] = factor;\r\n\r\n          for (size_t j = 0; j < stencil.linear_coeffs.size(); ++j) {\r\n            stencil.linear_coeffs[j] = stencil.linear_coeffs[j]*(sum)/(sum+factor);\r\n          }\r\n\r\n        }\r\n\r\n\r\n        //NAN check, this can occur if you have noise free data, and the system becomes ill-posed. (likely other reasons as well, hence the warning).\r\n\r\n        bool valid_check = true;\r\n\r\n        double coeff_sum = 0;\r\n\r\n        for (size_t l1 = 0; l1 < stencil.linear_coeffs.size(); ++l1) {\r\n          if(std::isnan(stencil.linear_coeffs[l1])){\r\n            valid_check = false;\r\n          }\r\n            coeff_sum += stencil.linear_coeffs[l1];\r\n        }\r\n\r\n\r\n\r\n        // Does it sum close to 1? very liberal to detect agian non-convergence.\r\n        float error_threshold = 0.1;\r\n        double val = coeff_sum - 1.0;\r\n\r\n        if(std::abs(val) > error_threshold){\r\n            valid_check = false;\r\n        }\r\n\r\n        std::cout << \"kernel sum: \" << coeff_sum << std::endl;\r\n\r\n        bool diverged_val = std::isnan(coeff_sum);\r\n\r\n        if(diverged_val){\r\n            valid_check = false;\r\n        }\r\n\r\n        if(!valid_check){\r\n            std::wcerr << \"Inference hasn't converged to a solution, setting the kernel to identity. This could be due to std(signal) = 0, or the signal is noise free.\" << std::endl;\r\n\r\n            std::fill(stencil.linear_coeffs.begin(),stencil.linear_coeffs.end(),0);\r\n            stencil.linear_coeffs[stencilSetUp.center_index] = 1;\r\n        }\r\n\r\n\r\n\r\n    }\r\n\r\n\r\n};\r\n\r\n#endif //LIBAPR_APRDENOISE_H\r\n", "meta": {"hexsha": "93c14fb0d0ced88e6f63826b0a2c853c14732034", "size": 28484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/numerics/APRDenoise.hpp", "max_stars_repo_name": "mosaic-group/LibAPR", "max_stars_repo_head_hexsha": "69097a662bf671d77a548fc47dae2c590675bfac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-12-03T20:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T17:53:51.000Z", "max_issues_repo_path": "src/numerics/APRDenoise.hpp", "max_issues_repo_name": "mosaic-group/LibAPR", "max_issues_repo_head_hexsha": "69097a662bf671d77a548fc47dae2c590675bfac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2018-11-28T09:10:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T20:42:11.000Z", "max_forks_repo_path": "src/numerics/APRDenoise.hpp", "max_forks_repo_name": "mosaic-group/LibAPR", "max_forks_repo_head_hexsha": "69097a662bf671d77a548fc47dae2c590675bfac", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-13T07:41:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T13:54:39.000Z", "avg_line_length": 30.2057264051, "max_line_length": 185, "alphanum_fraction": 0.5446917568, "num_tokens": 6948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.04401865221440602, "lm_q1q2_score": 0.01661883201320285}}
{"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, 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 tools/license/license.mtl.txt in the distribution.\n\n#ifndef MTL_IO_WRITE_AST_DISPATCH_INCLUDE\n#define MTL_IO_WRITE_AST_DISPATCH_INCLUDE\n\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/io/functor_symbol.hpp>\n#include <boost/numeric/mtl/vector/vec_vec_aop_expr.hpp>\n\nnamespace mtl { namespace io {\n\ntemplate <typename Value, typename Parameters> \nvoid write_ast_dispatch(const mtl::dense_vector<Value, Parameters>& v, std::string s, std::ofstream& f);\ntemplate <typename E1, typename E2, typename SFunctor>\nvoid write_ast_dispatch(const mtl::vec_vec_aop_expr<E1, E2, SFunctor>& expr, std::string s, std::ofstream& f);\ntemplate <class E1, class E2, typename SFunctor>\nvoid write_ast_dispatch(const mtl::vec_vec_pmop_expr<E1, E2, SFunctor>& expr, std::string s, std::ofstream& f);\ntemplate <typename Functor, typename Vector> \nvoid write_ast_dispatch(const mtl::map_view<Functor, Vector>& expr, std::string s, std::ofstream& f);\ntemplate <typename Scaling, typename Vector>\nvoid write_ast_dispatch(const mtl::scaled_view<Scaling, Vector>& expr, std::string s, std::ofstream& f);\ntemplate <typename Matrix, typename Vector> \nvoid write_ast_dispatch(const mtl::mat_cvec_times_expr<Matrix, Vector>& expr, std::string s, std::ofstream& f);\ntemplate <typename Expr>\nvoid write_ast_dispatch(const mtl::operation::compute_summand<Expr>& expr, std::string s, std::ofstream& f);\ntemplate <typename Matrix, typename Vector> \nvoid write_ast_dispatch(const mtl::operation::compute_summand<mtl::mat_cvec_times_expr<Matrix, Vector> >& expr, std::string s, std::ofstream& f);\ntemplate <typename Vector1, typename Vector2> \nvoid write_ast_dispatch(const mtl::mat::outer_product_matrix<Vector1, Vector2>& expr, std::string s, std::ofstream& f);\n\n\n\ntemplate <typename Value>\ntypename boost::enable_if_c<boost::is_floating_point<Value>::value || boost::is_integral<Value>::value>::type\nwrite_ast_dispatch(const Value& v, std::string s, std::ofstream& f)\n{   \n    f << \"  \" << s << \"[shape=box,label=\\\"scalar\\\\n\" << v << \"\\\"]\\n\";\n}\n\n\ntemplate <typename Value, typename Parameters> \nvoid write_ast_dispatch(const mtl::dense_vector<Value, Parameters>& v, std::string s, std::ofstream& f)\n{   \n    f << \"  \" << s << \"[shape=box,label=\\\"vector\\\\n\" << &v << \"\\\"]\\n\";\n}\n\ntemplate <typename E1, typename E2, typename SFunctor>\nvoid write_ast_dispatch(const mtl::vec_vec_aop_expr<E1, E2, SFunctor>& expr, std::string s, std::ofstream& f)\n{\n    f << \"  \" << s << \"[label=\\\"\" << functor_symbol(SFunctor()) << \"\\\"]\\n\"; \n    std::string target= s + \"t\", source= s + \"s\";\n    write_ast_dispatch(expr.first_argument(), target, f);\n    write_ast_dispatch(expr.second_argument(), source, f);\n    f << \"  \" << s << \"->\" << target << '\\n';\n    f << \"  \" << s << \"->\" << source << '\\n';\n}\n\ntemplate <class E1, class E2, typename SFunctor>\nvoid write_ast_dispatch(const mtl::vec_vec_pmop_expr<E1, E2, SFunctor>& expr, std::string s, std::ofstream& f)\n{\n    f << \"  \" << s << \"[label=\\\"\" << functor_symbol(SFunctor()) << \"\\\"]\\n\"; \n    std::string first= s + \"f\", second= s + \"s\";\n    write_ast_dispatch(expr.first_argument(), first, f);\n    write_ast_dispatch(expr.second_argument(), second, f);\n    f << \"  \" << s << \"->\" << first << '\\n';\n    f << \"  \" << s << \"->\" << second << '\\n';\n}\n\ntemplate <typename Scaling, typename Vector>\nvoid write_ast_dispatch(const mtl::scaled_view<Scaling, Vector>& expr, std::string s, std::ofstream& f)\n{\n    f << \"  \" << s << \"[label=\\\"scaled_view\\\"]\\n\"; \n    std::string functor= s + \"f\", ref= s + \"r\";\n    \n    write_ast_dispatch(expr.functor.value, functor, f);\n    write_ast_dispatch(expr.ref, ref, f);\n\n    f << \"  \" << s << \"->\" << functor << '\\n';\n    f << \"  \" << s << \"->\" << ref << '\\n';\n}\n\ntemplate <typename Value1, typename Value2>\nvoid write_ast_dispatch(const mtl::tfunctor::scale<Value1, Value2, mtl::tag::scalar>& expr, std::string s, std::ofstream& f)\n{\n    f << \"  \" << s << \"[label=\\\"scale\\\"]\\n\"; \n    std::string factor= s + \"f\", ref= s + \"r\";\n    write_ast_dispatch(expr.value(), factor, f);\n    f << \"  \" << ref << \"[label=\\\".\\\"]\\n\"; \n\n    f << \"  \" << s << \"->\" << factor << '\\n';\n    f << \"  \" << s << \"->\" << ref << '\\n';\n}\n\ntemplate <typename Functor, typename Vector> \nvoid write_ast_dispatch(const mtl::map_view<Functor, Vector>& expr, std::string s, std::ofstream& f)\n{\n    f << \"  \" << s << \"[label=\\\"map\\\"]\\n\"; \n    std::string functor= s + \"f\", ref= s + \"r\";\n    \n    write_ast_dispatch(expr.functor, functor, f);\n    write_ast_dispatch(expr.ref, ref, f);\n\n    f << \"  \" << s << \"->\" << functor << '\\n';\n    f << \"  \" << s << \"->\" << ref << '\\n';\n}\n\n// template <typename Matrix, typename Vector> \n// void write_ast_dispatch(const mtl::mat_cvec_times_expr<Matrix, Vector>& expr, std::string s, std::ofstream& f)\n// {\n// }\n\ntemplate <typename Expr>\nvoid write_ast_dispatch(const mtl::operation::compute_summand<Expr>& expr, std::string s, std::ofstream& f)\n{\n    write_ast_dispatch(expr.value, s, f);\n}\n\ntemplate <typename Matrix, typename Vector> \nvoid write_ast_dispatch(const mtl::operation::compute_summand<mtl::mat_cvec_times_expr<Matrix, Vector> >& expr, std::string s, std::ofstream& f)\n{\n# ifdef NDEBUG\n    write_ast_dispatch(expr.value, s, f);\n# else\n    f << \"  \" << s << \"[label=\\\"*\\\"]\\n\"; \n    std::string first= s + \"f\", second= s + \"s\";\n    write_ast_dispatch(expr.first, first, f);\n    write_ast_dispatch(expr.second, second, f);\n    f << \"  \" << s << \"->\" << first << '\\n';\n    f << \"  \" << s << \"->\" << second << '\\n';\n# endif \n}\n\ntemplate <typename Vector1, typename Vector2> \nvoid write_ast_dispatch(const mtl::mat::outer_product_matrix<Vector1, Vector2>& expr, std::string s, std::ofstream& f)\n{\n    f << \"  \" << s << \"[label=\\\"outer product\\\"]\\n\"; \n    std::string first= s + \"f\", second= s + \"s\";\n    write_ast_dispatch(expr.v1(), first, f);\n    write_ast_dispatch(expr.v2(), second, f);\n    f << \"  \" << s << \"->\" << first << '\\n';\n    f << \"  \" << s << \"->\" << second << '\\n';\n}\n\n}} // namespace mtl::io\n\n#endif // MTL_IO_WRITE_AST_DISPATCH_INCLUDE\n", "meta": {"hexsha": "e39dd29b646b7f135f8051d0d02b35b1b3b16316", "size": 6597, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/io/write_ast_dispatch.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/io/write_ast_dispatch.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/io/write_ast_dispatch.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": 40.472392638, "max_line_length": 145, "alphanum_fraction": 0.6452933151, "num_tokens": 1887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845760163515857, "lm_q2_score": 0.05834583938364053, "lm_q1q2_score": 0.01660382654248588}}
{"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// std_real_concept is an archetype for built-in Real types.\r\n\r\n// The main purpose in providing this type is to verify\r\n// that std lib functions are found via a using declaration\r\n// bringing those functions into the current scope, and not\r\n// just because they happen to be in global scope.\r\n//\r\n// If ::pow is found rather than std::pow say, then the code\r\n// will silently compile, but truncation of long doubles to\r\n// double will cause a significant loss of precision.\r\n// A template instantiated with std_real_concept will *only*\r\n// compile if it std::whatever is in scope.\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/math/tools/real_cast.hpp>\r\n#include <boost/math/tools/precision.hpp>\r\n#include <boost/math/policies/policy.hpp>\r\n\r\n#include <ostream>\r\n#include <istream>\r\n#include <cmath>\r\n#include <math.h> // fmodl\r\n\r\n#ifndef BOOST_MATH_STD_REAL_CONCEPT_HPP\r\n#define BOOST_MATH_STD_REAL_CONCEPT_HPP\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace concepts\r\n{\r\n\r\nclass std_real_concept\r\n{\r\npublic:\r\n   // Constructors:\r\n   std_real_concept() : m_value(0){}\r\n   std_real_concept(char c) : m_value(c){}\r\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\r\n   std_real_concept(wchar_t c) : m_value(c){}\r\n#endif\r\n   std_real_concept(unsigned char c) : m_value(c){}\r\n   std_real_concept(signed char c) : m_value(c){}\r\n   std_real_concept(unsigned short c) : m_value(c){}\r\n   std_real_concept(short c) : m_value(c){}\r\n   std_real_concept(unsigned int c) : m_value(c){}\r\n   std_real_concept(int c) : m_value(c){}\r\n   std_real_concept(unsigned long c) : m_value(c){}\r\n   std_real_concept(long c) : m_value(c){}\r\n#if defined(BOOST_HAS_LONG_LONG) || defined(__DECCXX) || defined(__SUNPRO_CC)\r\n   std_real_concept(unsigned long long c) : m_value(static_cast<long double>(c)){}\r\n   std_real_concept(long long c) : m_value(static_cast<long double>(c)){}\r\n#endif\r\n   std_real_concept(float c) : m_value(c){}\r\n   std_real_concept(double c) : m_value(c){}\r\n   std_real_concept(long double c) : m_value(c){}\r\n\r\n   // Assignment:\r\n   std_real_concept& operator=(char c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(unsigned char c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(signed char c) { m_value = c; return *this; }\r\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\r\n   std_real_concept& operator=(wchar_t c) { m_value = c; return *this; }\r\n#endif\r\n   std_real_concept& operator=(short c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(unsigned short c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(int c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(unsigned int c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(long c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(unsigned long c) { m_value = c; return *this; }\r\n#if defined(BOOST_HAS_LONG_LONG) || defined(__DECCXX) || defined(__SUNPRO_CC)\r\n   std_real_concept& operator=(long long c) { m_value = static_cast<long double>(c); return *this; }\r\n   std_real_concept& operator=(unsigned long long c) { m_value = static_cast<long double>(c); return *this; }\r\n#endif\r\n   std_real_concept& operator=(float c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(double c) { m_value = c; return *this; }\r\n   std_real_concept& operator=(long double c) { m_value = c; return *this; }\r\n\r\n   // Access:\r\n   long double value()const{ return m_value; }\r\n\r\n   // Member arithmetic:\r\n   std_real_concept& operator+=(const std_real_concept& other)\r\n   { m_value += other.value(); return *this; }\r\n   std_real_concept& operator-=(const std_real_concept& other)\r\n   { m_value -= other.value(); return *this; }\r\n   std_real_concept& operator*=(const std_real_concept& other)\r\n   { m_value *= other.value(); return *this; }\r\n   std_real_concept& operator/=(const std_real_concept& other)\r\n   { m_value /= other.value(); return *this; }\r\n   std_real_concept operator-()const\r\n   { return -m_value; }\r\n   std_real_concept const& operator+()const\r\n   { return *this; }\r\n\r\nprivate:\r\n   long double m_value;\r\n};\r\n\r\n// Non-member arithmetic:\r\ninline std_real_concept operator+(const std_real_concept& a, const std_real_concept& b)\r\n{\r\n   std_real_concept result(a);\r\n   result += b;\r\n   return result;\r\n}\r\ninline std_real_concept operator-(const std_real_concept& a, const std_real_concept& b)\r\n{\r\n   std_real_concept result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\ninline std_real_concept operator*(const std_real_concept& a, const std_real_concept& b)\r\n{\r\n   std_real_concept result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\ninline std_real_concept operator/(const std_real_concept& a, const std_real_concept& b)\r\n{\r\n   std_real_concept result(a);\r\n   result /= b;\r\n   return result;\r\n}\r\n\r\n// Comparison:\r\ninline bool operator == (const std_real_concept& a, const std_real_concept& b)\r\n{ return a.value() == b.value(); }\r\ninline bool operator != (const std_real_concept& a, const std_real_concept& b)\r\n{ return a.value() != b.value();}\r\ninline bool operator < (const std_real_concept& a, const std_real_concept& b)\r\n{ return a.value() < b.value(); }\r\ninline bool operator <= (const std_real_concept& a, const std_real_concept& b)\r\n{ return a.value() <= b.value(); }\r\ninline bool operator > (const std_real_concept& a, const std_real_concept& b)\r\n{ return a.value() > b.value(); }\r\ninline bool operator >= (const std_real_concept& a, const std_real_concept& b)\r\n{ return a.value() >= b.value(); }\r\n\r\n#if 0\r\n// Non-member mixed compare:\r\ntemplate <class T>\r\ninline bool operator == (const T& a, const std_real_concept& b)\r\n{\r\n   return a == b.value();\r\n}\r\ntemplate <class T>\r\ninline bool operator != (const T& a, const std_real_concept& b)\r\n{\r\n   return a != b.value();\r\n}\r\ntemplate <class T>\r\ninline bool operator < (const T& a, const std_real_concept& b)\r\n{\r\n   return a < b.value();\r\n}\r\ntemplate <class T>\r\ninline bool operator > (const T& a, const std_real_concept& b)\r\n{\r\n   return a > b.value();\r\n}\r\ntemplate <class T>\r\ninline bool operator <= (const T& a, const std_real_concept& b)\r\n{\r\n   return a <= b.value();\r\n}\r\ntemplate <class T>\r\ninline bool operator >= (const T& a, const std_real_concept& b)\r\n{\r\n   return a >= b.value();\r\n}\r\n#endif  // Non-member mixed compare:\r\n\r\n} // namespace concepts\r\n} // namespace math\r\n} // namespace boost\r\n\r\nnamespace std{\r\n\r\n// Non-member functions:\r\ninline boost::math::concepts::std_real_concept acos(boost::math::concepts::std_real_concept a)\r\n{ return std::acos(a.value()); }\r\ninline boost::math::concepts::std_real_concept cos(boost::math::concepts::std_real_concept a)\r\n{ return std::cos(a.value()); }\r\ninline boost::math::concepts::std_real_concept asin(boost::math::concepts::std_real_concept a)\r\n{ return std::asin(a.value()); }\r\ninline boost::math::concepts::std_real_concept atan(boost::math::concepts::std_real_concept a)\r\n{ return std::atan(a.value()); }\r\ninline boost::math::concepts::std_real_concept atan2(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\r\n{ return std::atan2(a.value(), b.value()); }\r\ninline boost::math::concepts::std_real_concept ceil(boost::math::concepts::std_real_concept a)\r\n{ return std::ceil(a.value()); }\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\ninline boost::math::concepts::std_real_concept fmod(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\r\n{ return fmodl(a.value(), b.value()); }\r\n#else\r\ninline boost::math::concepts::std_real_concept fmod(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\r\n{ return std::fmod(a.value(), b.value()); }\r\n#endif\r\ninline boost::math::concepts::std_real_concept cosh(boost::math::concepts::std_real_concept a)\r\n{ return std::cosh(a.value()); }\r\ninline boost::math::concepts::std_real_concept exp(boost::math::concepts::std_real_concept a)\r\n{ return std::exp(a.value()); }\r\ninline boost::math::concepts::std_real_concept fabs(boost::math::concepts::std_real_concept a)\r\n{ return std::fabs(a.value()); }\r\ninline boost::math::concepts::std_real_concept abs(boost::math::concepts::std_real_concept a)\r\n{ return std::abs(a.value()); }\r\ninline boost::math::concepts::std_real_concept floor(boost::math::concepts::std_real_concept a)\r\n{ return std::floor(a.value()); }\r\ninline boost::math::concepts::std_real_concept modf(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept* ipart)\r\n{\r\n   long double ip;\r\n   long double result = std::modf(a.value(), &ip);\r\n   *ipart = ip;\r\n   return result;\r\n}\r\ninline boost::math::concepts::std_real_concept frexp(boost::math::concepts::std_real_concept a, int* expon)\r\n{ return std::frexp(a.value(), expon); }\r\ninline boost::math::concepts::std_real_concept ldexp(boost::math::concepts::std_real_concept a, int expon)\r\n{ return std::ldexp(a.value(), expon); }\r\ninline boost::math::concepts::std_real_concept log(boost::math::concepts::std_real_concept a)\r\n{ return std::log(a.value()); }\r\ninline boost::math::concepts::std_real_concept log10(boost::math::concepts::std_real_concept a)\r\n{ return std::log10(a.value()); }\r\ninline boost::math::concepts::std_real_concept tan(boost::math::concepts::std_real_concept a)\r\n{ return std::tan(a.value()); }\r\ninline boost::math::concepts::std_real_concept pow(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\r\n{ return std::pow(a.value(), b.value()); }\r\n#if !defined(__SUNPRO_CC)\r\ninline boost::math::concepts::std_real_concept pow(boost::math::concepts::std_real_concept a, int b)\r\n{ return std::pow(a.value(), b); }\r\n#else\r\ninline boost::math::concepts::std_real_concept pow(boost::math::concepts::std_real_concept a, int b)\r\n{ return std::pow(a.value(), static_cast<long double>(b)); }\r\n#endif\r\ninline boost::math::concepts::std_real_concept sin(boost::math::concepts::std_real_concept a)\r\n{ return std::sin(a.value()); }\r\ninline boost::math::concepts::std_real_concept sinh(boost::math::concepts::std_real_concept a)\r\n{ return std::sinh(a.value()); }\r\ninline boost::math::concepts::std_real_concept sqrt(boost::math::concepts::std_real_concept a)\r\n{ return std::sqrt(a.value()); }\r\ninline boost::math::concepts::std_real_concept tanh(boost::math::concepts::std_real_concept a)\r\n{ return std::tanh(a.value()); }\r\n\r\n} // namespace std\r\n\r\nnamespace boost{ namespace math{ namespace concepts{\r\n\r\n// Streaming:\r\ntemplate <class charT, class traits>\r\ninline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const std_real_concept& a)\r\n{\r\n   return os << a.value();\r\n}\r\ntemplate <class charT, class traits>\r\ninline std::basic_istream<charT, traits>& operator>>(std::basic_istream<charT, traits>& is, std_real_concept& a)\r\n{\r\n   long double v;\r\n   is >> v;\r\n   a = v;\r\n   return is;\r\n}\r\n\r\n} // namespace concepts\r\n\r\nnamespace tools\r\n{\r\n// real_cast converts from T to integer and narrower floating-point types.\r\n\r\n// Convert from T to integer types.\r\n\r\ntemplate <>\r\ninline unsigned int real_cast<unsigned int, concepts::std_real_concept>(concepts::std_real_concept r)\r\n{\r\n   return static_cast<unsigned int>(r.value());\r\n}\r\n\r\ntemplate <>\r\ninline int real_cast<int, concepts::std_real_concept>(concepts::std_real_concept r)\r\n{\r\n   return static_cast<int>(r.value());\r\n}\r\n\r\ntemplate <>\r\ninline long real_cast<long, concepts::std_real_concept>(concepts::std_real_concept r)\r\n{\r\n   return static_cast<long>(r.value());\r\n}\r\n\r\n// Converts from T to narrower floating-point types, float, double & long double.\r\n\r\ntemplate <>\r\ninline float real_cast<float, concepts::std_real_concept>(concepts::std_real_concept r)\r\n{\r\n   return static_cast<float>(r.value());\r\n}\r\ntemplate <>\r\ninline double real_cast<double, concepts::std_real_concept>(concepts::std_real_concept r)\r\n{\r\n   return static_cast<double>(r.value());\r\n}\r\ntemplate <>\r\ninline long double real_cast<long double, concepts::std_real_concept>(concepts::std_real_concept r)\r\n{\r\n   return r.value();\r\n}\r\n\r\ntemplate <>\r\ninline concepts::std_real_concept max_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\r\n{\r\n   return max_value<long double>();\r\n}\r\n\r\ntemplate <>\r\ninline concepts::std_real_concept min_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\r\n{\r\n   return min_value<long double>();\r\n}\r\n\r\ntemplate <>\r\ninline concepts::std_real_concept log_max_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\r\n{\r\n   return log_max_value<long double>();\r\n}\r\n\r\ntemplate <>\r\ninline concepts::std_real_concept log_min_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\r\n{\r\n   return log_min_value<long double>();\r\n}\r\n\r\ntemplate <>\r\ninline concepts::std_real_concept epsilon<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\r\n{\r\n   return tools::epsilon<long double>();\r\n}\r\n\r\ntemplate <>\r\ninline int digits<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\r\n{ // Assume number of significand bits is same as long double,\r\n  // unless std::numeric_limits<T>::is_specialized to provide digits.\r\n   return digits<long double>();\r\n}\r\n\r\n} // namespace tools\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_STD_REAL_CONCEPT_HPP\r\n\r\n\r\n", "meta": {"hexsha": "2d921661611014a224051cd0d55d8f365a210f33", "size": 13595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/windows/boost/include/boost/math/concepts/std_real_concept.hpp", "max_stars_repo_name": "foxostro/CheeseTesseract", "max_stars_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-05-17T03:36:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-17T03:36:52.000Z", "max_issues_repo_path": "external/windows/boost/include/boost/math/concepts/std_real_concept.hpp", "max_issues_repo_name": "foxostro/CheeseTesseract", "max_issues_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_issues_repo_licenses": ["MIT"], "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/windows/boost/include/boost/math/concepts/std_real_concept.hpp", "max_forks_repo_name": "foxostro/CheeseTesseract", "max_forks_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_forks_repo_licenses": ["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.081232493, "max_line_length": 144, "alphanum_fraction": 0.7160720853, "num_tokens": 3550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.04958902298403174, "lm_q1q2_score": 0.01659196349251858}}
{"text": "/*\n * WAnalyser.cpp\n *\n *  Created on: 12 Jan 2015\n *      Author: ejclemen\n */\n\n#include \"../../interface/Analysers/WAnalyser.h\"\n\n#include <boost/scoped_ptr.hpp>\n\nnamespace BAT {\n\nvoid WAnalyser::analyse(const EventPtr event) {\n\t// weight_ = event->weight();\n}\n\nvoid WAnalyser::analyseHadronicW(const EventPtr event, const JetCollection jets, const JetCollection bjets) {\n\n\tweight_ = event->weight();\n\n\t// Get cleaned jets that aren't b tagged\n\tJetCollection jetsWithoutBs;\n\tfor ( unsigned int jetIndex=0; jetIndex < jets.size(); ++jetIndex ) {\n\t\tbool isBJet = false;\n\t\tJetPointer thisJet = jets[jetIndex];\n\t\tfor ( unsigned int bJetIndex=0; bJetIndex < bjets.size(); ++bJetIndex ) {\n\t\t\tJetPointer thisBJet = bjets[bJetIndex];\n\t\t\tif ( thisJet == thisBJet ) {\n\t\t\t\tisBJet = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif ( !isBJet ) jetsWithoutBs.push_back( thisJet );\n\t}\n\n\tif ( jetsWithoutBs.size() < 2 ) return;\n\n\n\t// Need these for some gen level studies\n\tconst JetCollection genJets( event->GenJets() );\n\thistMan_->setCurrentHistogramFolder(histogramFolder_);\n\ttreeMan_->setCurrentFolder(histogramFolder_);\n\ttreeMan_->Fill(\"EventWeight\", event->weight());\n\n\t// Get each jet pair combination and form a W candidate\n\tfor ( unsigned int jet1Index=0; jet1Index < jetsWithoutBs.size()-1; ++jet1Index ) {\n\t\tfor ( unsigned int jet2Index=jet1Index+1; jet2Index < jetsWithoutBs.size(); ++jet2Index ) {\n\t\t\tJetPointer jet1 = jetsWithoutBs[jet1Index];\n\t\t\tJetPointer jet2 = jetsWithoutBs[jet2Index];\n\n\t\t\t// W mass from RAW jets\n\t\t\t// Note there will be some bias, as only jets with corrected pt > 30 are in the ntuple\n\t\t\tParticlePointer jet1Raw = jet1->raw_jet();\n\t\t\tParticlePointer jet2Raw = jet2->raw_jet();\n\n\t\t\tif ( jet1Raw->pt() > 30 && jet2Raw->pt() > 30 ) {\n\t\t\t\tParticle hadronicWRaw(*jet1Raw + *jet2Raw);\n\n\t\t\t\thistMan_->H1D(\"hadronicWMass_RAW\")->Fill(hadronicWRaw.mass() , weight_);\n\t\t\t\thistMan_->H1D(\"jetPt_RAW\")->Fill(jet1Raw->pt() , weight_);\n\t\t\t\thistMan_->H1D(\"jetPt_RAW\")->Fill(jet2Raw->pt() , weight_);\n\t\t\t\thistMan_->H1D(\"jetEta_RAW\")->Fill(jet1Raw->eta() , weight_);\n\t\t\t\thistMan_->H1D(\"jetEta_RAW\")->Fill(jet2Raw->eta() , weight_);\n\t\t\t}\n\n\n\t\t\tif (jet1->pt()<=30 || jet2->pt()<=30 ) continue;\n\n\t\t\tParticle hadronicW(*jet1 + *jet2);\n\t\t\thistMan_->setCurrentHistogramFolder(histogramFolder_);\n\t\t\thistMan_->H1D(\"hadronicWMass\")->Fill(hadronicW.mass() , weight_);\n\t\t\thistMan_->H1D(\"jetPt\")->Fill(jet1->pt() , weight_);\n\t\t\thistMan_->H1D(\"jetPt\")->Fill(jet2->pt() , weight_);\n\t\t\thistMan_->H1D(\"jetEta\")->Fill(jet1->eta() , weight_);\n\t\t\thistMan_->H1D(\"jetEta\")->Fill(jet2->eta() , weight_);\n\n\t\t\ttreeMan_->setCurrentFolder(histogramFolder_);\n\t\t\ttreeMan_->Fill(\"mjj\",hadronicW.mass());\n\t\t\ttreeMan_->Fill(\"jetPt\",jet1->pt());\n\t\t\ttreeMan_->Fill(\"jetPt\",jet2->pt());\n\t\t\ttreeMan_->Fill(\"jetEta\",jet1->eta());\n\t\t\ttreeMan_->Fill(\"jetEta\",jet2->eta());\n\t\t\ttreeMan_->Fill(\"NPU\",event->Vertices().size());\n\n\t\t\t// Look at matched generator jets\n\t\t\tconst ParticlePointer genJet1 = jet1->matched_generated_jet();\n\t\t\tconst ParticlePointer genJet2 = jet2->matched_generated_jet();\n\n\t\t\tif ( genJet1 != 0 && genJet2 != 0 ) {\n\t\t\t\tParticle hadronicW_fromGenJets(*genJet1 + *genJet2);\n\t\t\t\thistMan_->H1D(\"hadronicWMass_genJets\")->Fill(hadronicW_fromGenJets.mass() , weight_);\n\t\t\t\thistMan_->H1D(\"jetPt_genJet\")->Fill(genJet1->pt() , weight_);\n\t\t\t\thistMan_->H1D(\"jetPt_genJet\")->Fill(genJet2->pt() , weight_);\n\t\t\t\thistMan_->H1D(\"jetEta_genJet\")->Fill(genJet1->eta() , weight_);\n\t\t\t\thistMan_->H1D(\"jetEta_genJet\")->Fill(genJet2->eta() , weight_);\n\n\t\t\t\ttreeMan_->Fill(\"mjj_genJet\",hadronicW.mass());\n\t\t\t\ttreeMan_->Fill(\"genJetPt\",genJet1->pt());\n\t\t\t\ttreeMan_->Fill(\"genJetPt\",genJet2->pt());\n\t\t\t\ttreeMan_->Fill(\"genJetEta\",genJet1->eta());\n\t\t\t\ttreeMan_->Fill(\"genJetEta\",genJet2->eta());\n\n\t\t\t\t// Now check if these gen jets correspond to those matched to the W decay products\n\t\t\t\tconst TTGenInfoPointer ttGen( event->TTGenInfo() );\n\t\t\t\tint quarkGenJetIndex = ttGen->getQuarkGenJetIndex();\n\t\t\t\tint quarkBarGenJetIndex = ttGen->getQuarkBarGenJetIndex();\n\t\t\t\tif ( quarkGenJetIndex >= 0 && quarkBarGenJetIndex >= 0 ) {\n\t\t\t\t\tJetPointer quarkGenJet( genJets[quarkGenJetIndex] );\n\t\t\t\t\tJetPointer quarkBarGenJet( genJets[quarkBarGenJetIndex] );\n\n\t\t\t\t\tif ( ( genJet1->getFourVector() == quarkGenJet->getFourVector() && genJet2->getFourVector() == quarkBarGenJet->getFourVector() ) ||\n\t\t\t\t\t\t( genJet2->getFourVector() == quarkGenJet->getFourVector() && genJet1->getFourVector() == quarkBarGenJet->getFourVector() ) ) {\n\n\t\t\t\t\t\t// These reco jets actually correspond to thos from a W\n\t\t\t\t\t\thistMan_->H1D(\"hadronicWMass_recoMatchedToPartons\")->Fill(hadronicW.mass() , weight_);\n\t\t\t\t\t\thistMan_->H1D(\"jetPt_recoMatchedToPartons\")->Fill(jet1->pt() , weight_);\n\t\t\t\t\t\thistMan_->H1D(\"jetPt_recoMatchedToPartons\")->Fill(jet2->pt() , weight_);\n\t\t\t\t\t\thistMan_->H1D(\"jetEta_recoMatchedToPartons\")->Fill(jet1->eta() , weight_);\n\t\t\t\t\t\thistMan_->H1D(\"jetEta_recoMatchedToPartons\")->Fill(jet2->eta() , weight_);\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//  Get jets that are fairly separated from other jets\n\t// These jets are a further subset of jetsWithoutBs\n\tJetCollection cleanedJets;\n\tfor ( unsigned int jet1Index=0; jet1Index < jetsWithoutBs.size(); ++jet1Index ) {\n\t\tJetPointer jet1 = jetsWithoutBs[jet1Index];\n\t\tdouble minDeltaR = 999.;\n\t\tfor ( unsigned int jet2Index=jet1Index+1; jet2Index < jetsWithoutBs.size(); ++jet2Index ) {\n\n\t\t\tJetPointer jet2 = jetsWithoutBs[jet2Index];\n\n\t\t\tdouble deltaRToOtherJet = jet1->deltaR( jet2 );\n\n\t\t\tif ( deltaRToOtherJet < minDeltaR )\n\t\t\t\tminDeltaR = deltaRToOtherJet;\n\t\t}\n\t\tif ( minDeltaR > 1 ) {\n\t\t\thistMan_->H1D(\"minDeltaR_cleanedReco\")->Fill( minDeltaR, weight_ );\n\t\t\tcleanedJets.push_back( jet1 );\n\t\t}\n\t}\n\n\tif ( cleanedJets.size() < 2 ) return;\n\n\t// Get each jet pair combination and form a W candidate\n\tfor ( unsigned int jet1Index=0; jet1Index < cleanedJets.size()-1; ++jet1Index ) {\n\t\tfor ( unsigned int jet2Index=jet1Index+1; jet2Index < cleanedJets.size(); ++jet2Index ) {\n\t\t\tJetPointer jet1 = cleanedJets[jet1Index];\n\t\t\tJetPointer jet2 = cleanedJets[jet2Index];\n\n\t\t\tif (jet1->pt()<=30 || jet2->pt()<=30 ) continue;\n\n\t\t\tParticle hadronicW(*jet1 + *jet2);\n\n\t\t\thistMan_->setCurrentHistogramFolder(histogramFolder_);\n\t\t\thistMan_->H1D(\"hadronicWMass_cleanedReco\")->Fill(hadronicW.mass() , weight_);\n\t\t\thistMan_->H1D(\"jetPt_cleanedReco\")->Fill(jet1->pt() , weight_);\n\t\t\thistMan_->H1D(\"jetPt_cleanedReco\")->Fill(jet2->pt() , weight_);\n\t\t\thistMan_->H1D(\"jetEta_cleanedReco\")->Fill(jet1->eta() , weight_);\n\t\t\thistMan_->H1D(\"jetEta_cleanedReco\")->Fill(jet2->eta() , weight_);\n\t\t}\n\t}\n\n}\n\nvoid WAnalyser::analyseHadronicW_partons(const EventPtr event) {\n\tweight_ = event->weight();\n\n\t// Get partons associated with W decay\n\tconst TTGenInfoPointer ttGen( event->TTGenInfo() );\n\tconst ParticlePointer quarkParton = ttGen->getQuark();\n\tconst ParticlePointer quarkBarParton = ttGen->getQuarkBar();\n\tconst Particle hadronicW_fromPartons(*quarkParton + *quarkBarParton);\n\n\tif ( quarkParton->pt() > 30 && quarkBarParton->pt() > 30 &&\n\t\t\tfabs(quarkParton->eta()) < 2.5 && fabs(quarkBarParton->eta()) < 2.5 ) {\n\n\t\thistMan_->setCurrentHistogramFolder(histogramFolder_);\n\t\thistMan_->H1D(\"hadronicWMass_partons\")->Fill(hadronicW_fromPartons.mass() , weight_);\n\t\thistMan_->H1D(\"jetPt_partons\")->Fill(quarkParton->pt() , weight_);\n\t\thistMan_->H1D(\"jetPt_partons\")->Fill(quarkBarParton->pt() , weight_);\n\t\thistMan_->H1D(\"jetEta_partons\")->Fill(quarkParton->eta() , weight_);\n\t\thistMan_->H1D(\"jetEta_partons\")->Fill(quarkBarParton->eta() , weight_);\n\n\t\ttreeMan_->setCurrentFolder(histogramFolder_);\n\t\ttreeMan_->Fill(\"mjj_parton\",hadronicW_fromPartons.mass());\n\t\ttreeMan_->Fill(\"partonPt\",quarkParton->pt());\n\t\ttreeMan_->Fill(\"partonPt\",quarkBarParton->pt());\n\t\ttreeMan_->Fill(\"partonEta\",quarkParton->eta());\n\t\ttreeMan_->Fill(\"partonEta\",quarkBarParton->eta());\n\n\t\t// Get gen jets associated with partons\n\t\t// Note these gen jets are not cleaned against leptons.  But as we are considering the ones matched to the quarks from W decay, this shouldn't be too much of a problem\n\t\tconst JetCollection genJets( event->GenJets() );\n\t\tint quarkGenJetIndex = ttGen->getQuarkGenJetIndex();\n\t\tint quarkBarGenJetIndex = ttGen->getQuarkBarGenJetIndex();\n\n\t\tif ( quarkGenJetIndex >= 0 && quarkBarGenJetIndex >= 0 ) {\n\t\t\tJetPointer quarkGenJet( genJets[quarkGenJetIndex] );\n\t\t\tJetPointer quarkBarGenJet( genJets[quarkBarGenJetIndex] );\n\n\t\t\tif ( quarkGenJet->pt() > 30 && quarkBarGenJet->pt() > 30 &&\n\t\t\t\tfabs(quarkGenJet->eta()) < 2.5 && fabs(quarkBarGenJet->eta()) < 2.5 ) {\n\n\t\t\t\tconst Particle hadronicW_fromGenJetsMatchedToPartons(*quarkGenJet + *quarkBarGenJet);\n\n\t\t\t\thistMan_->H1D(\"hadronicWMass_partonsGenJets\")->Fill(hadronicW_fromGenJetsMatchedToPartons.mass() , weight_);\n\t\t\t\thistMan_->H1D(\"jetPt_partonsGenJets\")->Fill(quarkGenJet->pt() , weight_);\n\t\t\t\thistMan_->H1D(\"jetPt_partonsGenJets\")->Fill(quarkBarGenJet->pt() , weight_);\n\t\t\t\thistMan_->H1D(\"jetEta_partonsGenJets\")->Fill(quarkGenJet->eta() , weight_);\n\t\t\t\thistMan_->H1D(\"jetEta_partonsGenJets\")->Fill(quarkBarGenJet->eta() , weight_);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid WAnalyser::fillHistograms(std::string subcollection, std::string suffix) {\n\thistMan_->setCurrentHistogramFolder(histogramFolder_);\n\n\t// unsigned short numberOfSolutions = allSolutions.size();\n\t// for (unsigned short index = 0; index < numberOfSolutions; ++index) {\n\t// \tTtbarHypothesisPointer currentSolution = allSolutions.at(index);\n\t// \tconst ParticlePointer resonance = currentSolution->resonance;\n\n\t// \tdouble hadronicWMass = currentSolution->hadronicW->mass();\n\n\t// \tif (index == 0) {\n\t// \t\thistMan_->H1D_BJetBinned(\"hadronicWMass\" + suffix)->Fill(hadronicWMass, weight_ * scale_);\n\t// \t}\n\n\t// \tdouble normalisedWeight = weight_ * scale_ / numberOfSolutions;\n\t// \thistMan_->H1D_BJetBinned(\"hadronicWMass_allSolutions\" + suffix)->Fill(hadronicWMass, normalisedWeight);\n\t// }\n}\n\nvoid WAnalyser::createHistograms() {\n\thistMan_->setCurrentHistogramFolder(histogramFolder_);\n\n\thistMan_->addH1D(\"hadronicWMass\", \"hadronic W mass; m(W_{had}) [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetPt\", \"jet pt; p_{t} [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetEta\", \"jet eta; #eta; events/0.06\", 100, -3, 3);\n\n\thistMan_->addH1D(\"hadronicWMass_RAW\", \"hadronic W mass with RAW jets; m(W_{had}) [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetPt_RAW\", \"jet pt with RAW jets; p_{t} [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetEta_RAW\", \"jet eta with RAW jets; #eta; events/0.06\", 100, -3, 3);\n\n\thistMan_->addH1D(\"hadronicWMass_genJets\", \"hadronic W mass from gen jets; m(W_{had}) [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetPt_genJet\", \"gen jet pt; p_{t} [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetEta_genJet\", \"gen jet eta; #eta; events/0.06\", 100, -3, 3);\n\n\thistMan_->addH1D(\"hadronicWMass_partons\", \"hadronic W mass from partons; m(W_{had}) [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetPt_partons\", \"parton pt; p_{t} [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetEta_partons\", \"parton eta; #eta; events/0.06\", 100, -3, 3);\n\n\thistMan_->addH1D(\"hadronicWMass_partonsGenJets\", \"hadronic W mass from gen jets matched to partons; m(W_{had}) [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetPt_partonsGenJets\", \"gen jet matched to parton pt; p_{t} [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetEta_partonsGenJets\", \"gen jet matched to parton eta; #eta; events/0.06\", 100, -3, 3);\n\n\thistMan_->addH1D(\"hadronicWMass_recoMatchedToPartons\", \"hadronic W mass from reco jets matched to partons; m(W_{had}) [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetPt_recoMatchedToPartons\", \"reco jet matched to parton pt; p_{t} [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetEta_recoMatchedToPartons\", \"reco jet matched to parton eta; #eta; events/0.06\", 100, -3, 3);\n\n\thistMan_->addH1D(\"hadronicWMass_cleanedReco\", \"hadronic W mass; m(W_{had}) [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetPt_cleanedReco\", \"jet pt; p_{t} [GeV]; events/1 GeV\", 500, 0, 500);\n\thistMan_->addH1D(\"jetEta_cleanedReco\", \"jet eta; #eta; events/0.06\", 100, -3, 3);\n\thistMan_->addH1D(\"minDeltaR_cleanedReco\", \"deltaR to nearest jet; #Delta R; events/0.013\", 100, 0, 1.3);\n\n}\n\nvoid WAnalyser::createTrees() {\n\ttreeMan_->setCurrentFolder(histogramFolder_);\n\n\ttreeMan_->addBranch(\"mjj\", \"F\", \"W Bosons\" + Globals::treePrefix_);\n\ttreeMan_->addBranch(\"mjj_genJet\", \"F\", \"W Bosons\" + Globals::treePrefix_);\n\ttreeMan_->addBranch(\"mjj_parton\", \"F\", \"W Bosons\" + Globals::treePrefix_);\n\ttreeMan_->addBranch(\"jetPt\", \"F\", \"W Bosons\" + Globals::treePrefix_, false);\n\ttreeMan_->addBranch(\"jetEta\", \"F\", \"W Bosons\" + Globals::treePrefix_, false);\n\ttreeMan_->addBranch(\"genJetPt\", \"F\", \"W Bosons\" + Globals::treePrefix_, false);\n\ttreeMan_->addBranch(\"genJetEta\", \"F\", \"W Bosons\" + Globals::treePrefix_, false);\n\ttreeMan_->addBranch(\"partonPt\", \"F\", \"W Bosons\" + Globals::treePrefix_, false);\n\ttreeMan_->addBranch(\"partonEta\", \"F\", \"W Bosons\" + Globals::treePrefix_, false);\n\n\ttreeMan_->addBranch(\"NPU\", \"F\", \"W Bosons\" + Globals::treePrefix_);\n}\n\nWAnalyser::WAnalyser(boost::shared_ptr<HistogramManager> histMan, boost::shared_ptr<TreeManager> treeMan, std::string histogramFolder) :\n\t\tBasicAnalyser(histMan, treeMan, histogramFolder) {\n}\n\nWAnalyser::~WAnalyser() {\n}\n\n} /* namespace BAT */\n", "meta": {"hexsha": "35d86afc823cd5f229613e42047a85ee7bf4ec54", "size": 13326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Analysers/WAnalyser.cpp", "max_stars_repo_name": "kreczko/AnalysisSoftware", "max_stars_repo_head_hexsha": "fa83a3775a8d644e6098d28dbc6f3d7f1a11b400", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Analysers/WAnalyser.cpp", "max_issues_repo_name": "kreczko/AnalysisSoftware", "max_issues_repo_head_hexsha": "fa83a3775a8d644e6098d28dbc6f3d7f1a11b400", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Analysers/WAnalyser.cpp", "max_forks_repo_name": "kreczko/AnalysisSoftware", "max_forks_repo_head_hexsha": "fa83a3775a8d644e6098d28dbc6f3d7f1a11b400", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.42, "max_line_length": 169, "alphanum_fraction": 0.698409125, "num_tokens": 4458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.03789242948164655, "lm_q1q2_score": 0.016590196065592637}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// Definitions corresponding to collision_operator.hpp.\n\n#include <collision_operator.hpp>\n#include <constants.hpp>\n#include <limits>\n#include <iostream>\n#include <fstream>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <boost/serialization/unordered_map.hpp>\n#include <boost/serialization/vector.hpp>\n#if BOOST_VERSION >= 106700\n#include <boost/container_hash/hash.hpp>\n#else\n#include <boost/functional/hash.hpp>\n#endif \n/// Threading through Intel TBB\n#include <tbb/concurrent_unordered_map.h>\n#include <tbb/parallel_for.h>\n#include <mutex>\n\nnamespace alma {\n\nEigen::MatrixXd get_collision_operator_dense(\n    const alma::Gamma_grid& grid,\n    const alma::Crystal_structure& cell,\n    std::vector<alma::Thirdorder_ifcs>& anhIFC,\n    double Treference,\n    boost::mpi::communicator& world) {\n    /// First we are getting sizes\n    std::size_t nqpoints = grid.nqpoints;\n    std::size_t nbands = grid.get_spectrum_at_q(0).omega.size();\n    std::size_t nmodes = nbands * nqpoints;\n\n    std::size_t my_id = world.rank();\n    std::size_t nprocs = world.size();\n\n    /// Fill B matrix with 0\n    if ((nmodes - 3) * (nmodes - 3) > std::numeric_limits<int>::max()) {\n        if (my_id == 0) {\n            std::cerr << \"FATAL ERROR the number of matrix elements will not \"\n                         \"fit in MPI buffer\"\n                      << std::endl;\n            std::cerr << \"max_buffer_elements = \"\n                      << std::numeric_limits<int>::max() << std::endl;\n            std::cerr << \"matrix_elements     = \" << (nmodes - 3) * (nmodes - 3)\n                      << std::endl;\n        }\n        world.barrier();\n        world.abort(1);\n    }\n\n    Eigen::MatrixXcd cB = Eigen::MatrixXcd::Zero(\n        nmodes - 3,\n        nmodes - 3); /// We are not counting the Gamma-point acustic bands.\n\n    /// We first calculate the equilibrium distribution for reference\n    /// temperature:\n    std::vector<double> neq(nmodes, 0.);\n\n    for (std::size_t iq = 0; iq < nqpoints; iq++) {\n        auto s = grid.get_spectrum_at_q(iq);\n        for (std::size_t ib = 0; ib < nbands; ib++) {\n            double omega = s.omega(ib);\n            if (omega >= 1.0e-6) {\n                neq[iq * nbands + ib] = alma::bose_einstein(omega, Treference);\n            }\n        }\n    }\n\n\n    /// Create a unique set of Three_phonon processes from irreductible triplets\n    /// including the symmetry:\n    auto limits = alma::my_jobs(grid.get_nequivalences(), nprocs, my_id);\n    std::array<int, 2> signs(\n        {{static_cast<int>(alma::threeph_type::emission),\n          static_cast<int>(alma::threeph_type::absorption)}});\n\n    std::vector<alma::Threeph_process> myprocesses;\n\n    std::unordered_map<std::array<std::size_t, 3>, alma::Threeph_process>\n        emission_processes;\n    std::unordered_map<std::array<std::size_t, 3>, alma::Threeph_process>\n        absorption_processes;\n\n\n    tbb::concurrent_unordered_map<std::array<std::size_t, 3>,\n                                  alma::Threeph_process,\n                                  std::hash<std::array<std::size_t, 3>>>\n        emission_processes_tbb;\n    tbb::concurrent_unordered_map<std::array<std::size_t, 3>,\n                                  alma::Threeph_process,\n                                  std::hash<std::array<std::size_t, 3>>>\n        absorption_processes_tbb;\n\n    /// Calculating the three phonon processes for full BZ. The anhIFC are\n    /// needed in case that due to symmetrization we are registering some\n    /// transition that was not available in the already calculated elements. We\n    /// are calculating them under the assumption that the matrix element is\n    /// invariant to rotations, inversions and reciprocity but the smearing is\n    /// not.\n    for (auto ic = limits[0]; ic < limits[1]; ++ic) {\n        if (my_id == 0)\n            std::cout << \"#Recalculating fullBZ triplets \"\n                      << static_cast<std::size_t>(ic - limits[0]) << \" / \"\n                      << static_cast<std::size_t>(limits[1] - limits[0])\n                      << std::endl;\n        auto iq1 = grid.get_representative(ic);\n        auto coords1 = grid.one_to_three(iq1);\n        auto spectrum1 = grid.get_spectrum_at_q(iq1);\n\n        tbb::parallel_for(\n            tbb::blocked_range<std::size_t>(0, grid.nqpoints),\n            [&](tbb::blocked_range<std::size_t> iq2range) {\n                for (std::size_t iq2 = iq2range.begin(); iq2 < iq2range.end();\n                     ++iq2) {\n                    auto coords2 = grid.one_to_three(iq2);\n                    auto spectrum2 = grid.get_spectrum_at_q(iq2);\n                    decltype(coords2) coords3;\n\n                    // Emission and absorption processes satisfy different\n                    // conservation rules, with the second phonon in\n                    // different sides of the equations.\n                    for (auto s : signs) {\n                        for (auto i = 0; i < 3; ++i)\n                            coords3[i] = coords1[i] + s * coords2[i];\n                        auto iq3 = grid.three_to_one(coords3);\n                        auto spectrum3 = grid.get_spectrum_at_q(iq3);\n\n                        auto eqqtrip =\n                            grid.equivalent_qtriplets({iq1, iq2, iq3});\n\n\n                        for (decltype(nbands) im1 = 0; im1 < nbands; ++im1) {\n                            if (alma::almost_equal(spectrum1.omega(im1), 0.))\n                                continue;\n\n                            for (decltype(nbands) im2 = 0; im2 < nbands;\n                                 ++im2) {\n                                if (alma::almost_equal(spectrum2.omega(im2),\n                                                       0.))\n                                    continue;\n\n                                for (decltype(nbands) im3 = 0; im3 < nbands;\n                                     ++im3) {\n                                    if (alma::almost_equal(spectrum3.omega(im3),\n                                                           0.))\n                                        continue;\n                                    \n                                    auto delta =\n                                        std::fabs(spectrum1.omega(im1) +\n                                                  s * spectrum2.omega(im2) -\n                                                  spectrum3.omega(im3));\n\n                                    std::vector<double> vpsXdelta; //, sigmas;\n                                    std::vector<alma::Threeph_process> mythree;\n\n\n                                    for (auto& qt : eqqtrip) {\n                                        auto v1 = grid.get_spectrum_at_q(qt[0])\n                                                      .vg.col(im1);\n                                        auto v2 = grid.get_spectrum_at_q(qt[1])\n                                                      .vg.col(im2);\n                                        auto v3 = grid.get_spectrum_at_q(qt[2])\n                                                      .vg.col(im3);\n\n\n                                        if (static_cast<alma::threeph_type>(\n                                                s) ==\n                                            alma::threeph_type::absorption) {\n                                            auto sigma =\n                                                1.0 *\n                                                std::sqrt(\n                                                    boost::math::pow<2>(\n                                                        grid.base_sigma(v1)) +\n                                                    boost::math::pow<2>(\n                                                        grid.base_sigma(v2)) +\n                                                    boost::math::pow<2>(\n                                                        grid.base_sigma(v3)));\n                                            alma::Threeph_process\n                                                Gamma_of_triplet1(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[0],\n                                                          qt[1],\n                                                          qt[2]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im1, im2, im3}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet1);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet1\n                                                        .compute_gaussian());\n                                            }\n                                            alma::Threeph_process\n                                                Gamma_of_triplet2(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[1],\n                                                          qt[0],\n                                                          qt[2]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im2, im1, im3}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet2);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet2\n                                                        .compute_gaussian());\n                                            }\n                                            alma::Threeph_process\n                                                Gamma_of_triplet3(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[2],\n                                                          qt[0],\n                                                          qt[1]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im3, im1, im2}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(-s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet3);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet3\n                                                        .compute_gaussian());\n                                            }\n                                            alma::Threeph_process\n                                                Gamma_of_triplet4(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[2],\n                                                          qt[1],\n                                                          qt[0]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im3, im2, im1}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(-s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet4);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet4\n                                                        .compute_gaussian());\n                                            }\n                                        }\n                                        else {\n                                            auto sigma =\n                                                1.0 *\n                                                std::sqrt(\n                                                    boost::math::pow<2>(\n                                                        grid.base_sigma(v1)) +\n                                                    boost::math::pow<2>(\n                                                        grid.base_sigma(v2)) +\n                                                    boost::math::pow<2>(\n                                                        grid.base_sigma(v3)));\n                                            alma::Threeph_process\n                                                Gamma_of_triplet1(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[0],\n                                                          qt[1],\n                                                          qt[2]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im1, im2, im3}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet1);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet1\n                                                        .compute_gaussian());\n                                            }\n                                            alma::Threeph_process\n                                                Gamma_of_triplet2(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[0],\n                                                          qt[2],\n                                                          qt[1]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im1, im3, im2}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet2);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet2\n                                                        .compute_gaussian());\n                                            }\n                                            alma::Threeph_process\n                                                Gamma_of_triplet3(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[2],\n                                                          qt[1],\n                                                          qt[0]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im3, im2, im1}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(-s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet3);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet3\n                                                        .compute_gaussian());\n                                            }\n                                            alma::Threeph_process\n                                                Gamma_of_triplet4(\n                                                    ic,\n                                                    std::array<std::size_t, 3>(\n                                                        {{qt[1],\n                                                          qt[2],\n                                                          qt[0]}}),\n                                                    std::array<std::size_t, 3>(\n                                                        {{im2, im3, im1}}),\n                                                    static_cast<\n                                                        alma::threeph_type>(-s),\n                                                    delta,\n                                                    sigma);\n                                            mythree.push_back(\n                                                Gamma_of_triplet4);\n                                            if (delta <=\n                                                alma::constants::nsigma *\n                                                    sigma) {\n                                                vpsXdelta.push_back(\n                                                    Gamma_of_triplet4\n                                                        .compute_gaussian());\n                                            }\n                                        }\n                                    }\n\n                                    if (vpsXdelta.empty())\n                                        continue;\n                                    std::sort(mythree.begin(), mythree.end());\n                                    double VP2 = mythree[0].compute_vp2(\n                                        cell, grid, anhIFC);\n\n                                    double SymGamma = 0.;\n                                    for (auto& vD : vpsXdelta) {\n                                        SymGamma += VP2 * vD;\n                                    }\n\n                                    SymGamma /= 4 * eqqtrip.size();\n\n\n                                    /// If not 0 all register in map, we account\n                                    /// for a state decaying into two of same\n                                    /// index\n                                    if (!almost_equal(SymGamma,\n                                        0.,1.0e-12,1.0e-9)) {\n                                        for (auto& peq : mythree) {\n                                            peq.set_vp2(SymGamma);\n                                            std::array<std::size_t, 3>\n                                                triplet_indexes;\n                                            for (std::size_t idx_ = 0; idx_ < 3;\n                                                 idx_++)\n                                                triplet_indexes[idx_] =\n                                                    peq.q[idx_] * nbands +\n                                                    peq.alpha[idx_];\n                                            if (peq.type == alma::threeph_type::\n                                                                absorption) {\n                                                if (absorption_processes.count(\n                                                        triplet_indexes) == 0) {\n                                                    absorption_processes_tbb\n                                                        .emplace(std::make_pair(\n                                                            triplet_indexes,\n                                                            peq));\n                                                }\n                                            }\n                                            else {\n                                                // We account for those states\n                                                // by multiplying by 2\n                                                if (triplet_indexes[1] ==\n                                                    triplet_indexes[2]) {\n                                                    double effective_vp2 =\n                                                        2 * peq.get_vp2();\n                                                    peq.set_vp2(effective_vp2);\n                                                }\n                                                if (emission_processes_tbb.count(\n                                                        triplet_indexes) == 0) {\n                                                    emission_processes_tbb\n                                                        .emplace(std::make_pair(\n                                                            triplet_indexes,\n                                                            peq));\n                                                }\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            });\n    }\n\n    /// Passing tbb map to stl map for more classic stuff like MPI:\n    /// It can be avoided if serialization of tbb container is achieved\n    absorption_processes.insert(absorption_processes_tbb.begin(),\n                                absorption_processes_tbb.end());\n    emission_processes.insert(emission_processes_tbb.begin(),\n                              emission_processes_tbb.end());\n\n    /// We are now working on isotopic/mass-disoreder scattering\n    if (my_id == 0)\n        std::cout << \"#Working on 2ph processes\" << std::endl;\n\n    std::unordered_map<std::pair<std::size_t, std::size_t>, double>\n        isotopic_processes;\n\n    auto twoph_processes = alma::find_allowed_twoph(grid, world, 1.0);\n\n    double scalebroad_iso = 1.0;\n\n    /// We need sigma full list to symmetrize:\n    Eigen::ArrayXXd broadening_sigmas(nbands, grid.nqpoints);\n    for (std::size_t iq = 0; iq < grid.nqpoints; ++iq) {\n        for (std::size_t im = 0; im < nbands; ++im) {\n            auto spectrum = grid.get_spectrum_at_q(iq);\n            broadening_sigmas(im, iq) =\n                scalebroad_iso * grid.base_sigma(spectrum.vg.col(im));\n        }\n    }\n    // And refine them by removing outliers.\n    auto percent = calc_percentiles_log(broadening_sigmas);\n    double lbound = std::exp(percent[0] - 1.5 * (percent[1] - percent[0]));\n    broadening_sigmas =\n        (broadening_sigmas < lbound).select(lbound, broadening_sigmas);\n\n\n    for (auto& twoph : twoph_processes) {\n        auto b0 = twoph.alpha[0];\n        auto b1 = twoph.alpha[1];\n\n        auto sp0 = grid.get_spectrum_at_q(twoph.q[0]);\n        auto sp1 = grid.get_spectrum_at_q(twoph.q[1]);\n\n        auto delta = std::abs(sp0.omega(b0) - sp1.omega(b1));\n\n        /// If some of them is Gamma-point and acoustic, ignore\n        if (twoph.q[0] * nbands + b0 < 3 or twoph.q[1] * nbands + b1 < 3)\n            continue;\n\n        /// The scattering to itselt has no effect in scattering operator\n        if (twoph.q[0] * nbands + b0 == twoph.q[1] * nbands + b1)\n            continue;\n\n        auto qpairs = grid.equivalent_qpairs({twoph.q[0], twoph.q[1]});\n\n        std::vector<alma::Twoph_process> mytwo;\n\n        double gamma = 0.;\n\n        for (auto& qi : qpairs) {\n            auto sigma = std::hypot(broadening_sigmas(b0, qi[0]),\n                                    broadening_sigmas(b1, qi[1]));\n            alma::Twoph_process t1(0,\n                                   std::array<std::size_t, 2>({{qi[0], qi[1]}}),\n                                   std::array<std::size_t, 2>({{b0, b1}}),\n                                   delta,\n                                   sigma);\n            alma::Twoph_process t2(0,\n                                   std::array<std::size_t, 2>({{qi[1], qi[0]}}),\n                                   std::array<std::size_t, 2>({{b1, b0}}),\n                                   delta,\n                                   sigma);\n            mytwo.push_back(t1);\n            mytwo.push_back(t2);\n            if (delta <= alma::constants::nsigma * sigma) {\n                gamma += t1.compute_gamma(cell, grid);\n                gamma += t2.compute_gamma(cell, grid);\n            }\n        }\n        gamma /= 2 * qpairs.size();\n        /// If some equivalent process is not null\n        if (!almost_equal(gamma,0.,1.0e-12,1.0e-9)) {\n            for (auto& peq : mytwo) {\n                std::pair<std::size_t, std::size_t> pair_mode_ids =\n                    std::make_pair(peq.q[0] * nbands + peq.alpha[0],\n                                   peq.q[1] * nbands + peq.alpha[1]);\n                if (isotopic_processes.count(pair_mode_ids) == 0)\n                    isotopic_processes.emplace(\n                        std::make_pair(pair_mode_ids, gamma));\n            }\n        }\n    }\n\n\n    /// Sync section\n    if (nprocs > 1) {\n        if (my_id == 0)\n            std::cout << \"#Element distribution along processes\" << std::endl;\n        /// Chunking map\n        std::vector<std::unordered_map<std::array<std::size_t, 3>,\n                                       alma::Threeph_process>>\n            chunked_map_emission(nprocs);\n        std::vector<std::unordered_map<std::array<std::size_t, 3>,\n                                       alma::Threeph_process>>\n            chunked_map_absorption(nprocs);\n        std::vector<\n            std::unordered_map<std::pair<std::size_t, std::size_t>, double>>\n            chunked_map_isotopic(nprocs);\n        for (auto& process_block : emission_processes) {\n            auto id1 = process_block.first[0];\n            /// Check where we want this\n            auto mode_proc_id = alma::index_proc(id1, nmodes, nprocs);\n            chunked_map_emission[mode_proc_id].insert(process_block);\n        }\n        for (auto& process_block : absorption_processes) {\n            auto id1 = process_block.first[0];\n            /// Check where we want this\n            auto mode_proc_id = alma::index_proc(id1, nmodes, nprocs);\n            chunked_map_absorption[mode_proc_id].insert(process_block);\n        }\n        for (auto& process_block : isotopic_processes) {\n            auto id1 = process_block.first.first;\n            /// Check where we want this\n            auto mode_proc_id = alma::index_proc(id1, nmodes, nprocs);\n            chunked_map_isotopic[mode_proc_id].insert(process_block);\n        }\n\n\n        /// Here we distributing the chunks (there is no real balance, but for a\n        /// big mesh it is expected to be quite even)\n        for (std::size_t iproc = 0; iproc < nprocs; iproc++) {\n            std::vector<std::unordered_map<std::array<std::size_t, 3>,\n                                           alma::Threeph_process>>\n                collector_abs, collector_emi;\n            std::vector<\n                std::unordered_map<std::pair<std::size_t, std::size_t>, double>>\n                collector_iso;\n            /// Gathering the chunk of process in collector\n            gather(world, chunked_map_absorption[iproc], collector_abs, iproc);\n            gather(world, chunked_map_emission[iproc], collector_emi, iproc);\n            gather(world, chunked_map_isotopic[iproc], collector_iso, iproc);\n            /// If a am the collector put in my map\n            if (my_id == iproc) {\n                absorption_processes.clear();\n                for (auto& map2insert : collector_abs) {\n                    absorption_processes.insert(map2insert.begin(),\n                                                map2insert.end());\n                }\n                emission_processes.clear();\n                for (auto& map2insert : collector_emi) {\n                    emission_processes.insert(map2insert.begin(),\n                                              map2insert.end());\n                }\n                isotopic_processes.clear();\n                for (auto& map2insert : collector_iso) {\n                    isotopic_processes.insert(map2insert.begin(),\n                                              map2insert.end());\n                }\n            }\n            world.barrier();\n        }\n\n        if (my_id == 0)\n            std::cout << \"#Element distribution along processes=>DONE\"\n                      << std::endl;\n    }\n    std::size_t proc_nemi = emission_processes.size();\n    std::size_t proc_nabs = absorption_processes.size();\n    std::size_t proc_niso = isotopic_processes.size();\n    std::size_t tnemi = 0;\n    std::size_t tnabs = 0;\n    std::size_t tniso = 0;\n\n    boost::mpi::all_reduce(\n        world, &proc_nemi, 1, &tnemi, std::plus<std::size_t>());\n    boost::mpi::all_reduce(\n        world, &proc_nabs, 1, &tnabs, std::plus<std::size_t>());\n    boost::mpi::all_reduce(\n        world, &proc_niso, 1, &tniso, std::plus<std::size_t>());\n\n    if (my_id == 0) {\n        std::cout << \"#Nemi \" << tnemi << std::endl;\n        std::cout << \"#Nabs \" << tnabs << std::endl;\n        std::cout << \"#Niso \" << tniso << std::endl;\n    }\n    std::size_t ntot = proc_nemi + proc_nabs + proc_niso;\n\n    std::size_t iel = 0;\n\n\n    for (auto& process_block : emission_processes) {\n        auto process(process_block.second);\n        auto q0 = process.q[0];\n        auto q1 = process.q[1];\n        auto q2 = process.q[2];\n        auto b0 = process.alpha[0];\n        auto b1 = process.alpha[1];\n        auto b2 = process.alpha[2];\n        double omega0 = grid.get_spectrum_at_q(q0).omega(b0);\n        double omega1 = grid.get_spectrum_at_q(q1).omega(b1);\n        double omega2 = grid.get_spectrum_at_q(q2).omega(b2);\n\n\n        double factor = 1.0e6 * alma::constants::hbar * alma::constants::pi /\n                        (4.0 * omega0 * omega1 * omega2) / nqpoints;\n\n        double vpdelta = factor * process.get_vp2();\n\n        if (process.type == alma::threeph_type::emission)\n            vpdelta /= 2;\n\n        if (process.type == alma::threeph_type::emission) {\n            auto I = q0 * nbands + b0;\n            auto J = q1 * nbands + b1;\n            auto K = q2 * nbands + b2;\n            /// Check if normal\n\n            cB(I - 3, I - 3) = NeumaierSum(cB(I - 3, I - 3),\n                                           -vpdelta * (neq[K] + neq[J] + 1.0));\n            cB(I - 3, J - 3) =\n                NeumaierSum(cB(I - 3, J - 3),\n                            (omega0 / omega1) * vpdelta * (neq[K] - neq[I]));\n            cB(I - 3, K - 3) =\n                NeumaierSum(cB(I - 3, K - 3),\n                            (omega0 / omega2) * vpdelta * (neq[J] - neq[I]));\n        }\n        else {\n            std::cerr << \"#Error building collision operator this process \"\n                         \"should not be in this list\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n        iel++;\n        if (my_id == 0) {\n            std::cout << \"#iel => \" << iel << \" / \" << ntot << std::endl;\n        }\n    }\n\n\n    for (auto& process_block : absorption_processes) {\n        auto process(process_block.second);\n        auto q0 = process.q[0];\n        auto q1 = process.q[1];\n        auto q2 = process.q[2];\n        auto b0 = process.alpha[0];\n        auto b1 = process.alpha[1];\n        auto b2 = process.alpha[2];\n        double omega0 = grid.get_spectrum_at_q(q0).omega(b0);\n        double omega1 = grid.get_spectrum_at_q(q1).omega(b1);\n        double omega2 = grid.get_spectrum_at_q(q2).omega(b2);\n\n        double factor = 1.0e6 * alma::constants::hbar * alma::constants::pi /\n                        (4.0 * omega0 * omega1 * omega2) / nqpoints;\n\n        double vpdelta = factor * process.get_vp2();\n\n        if (process.type == alma::threeph_type::absorption) {\n            auto I = q0 * nbands + b0;\n            auto J = q1 * nbands + b1;\n            auto K = q2 * nbands + b2;\n\n            cB(I - 3, I - 3) =\n                NeumaierSum(cB(I - 3, I - 3), vpdelta * (neq[K] - neq[J]));\n            cB(I - 3, J - 3) =\n                NeumaierSum(cB(I - 3, J - 3),\n                            omega0 / omega1 * vpdelta * (neq[K] - neq[I]));\n            cB(I - 3, K - 3) = NeumaierSum(cB(I - 3, K - 3),\n                                           omega0 / omega2 * vpdelta *\n                                               (neq[J] + neq[I] + 1.0));\n        }\n        else {\n            std::cerr << \"#Error building collision operator this process \"\n                         \"should not be in this list\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n\n        iel++;\n        if (my_id == 0) {\n            std::cout << \"#iel => \" << iel << \" / \" << ntot << std::endl;\n        }\n    }\n\n\n    for (auto& process_block : isotopic_processes) {\n        auto I = process_block.first.first;\n        auto J = process_block.first.second;\n        auto q0 = I / nbands;\n        auto q1 = J / nbands;\n        auto b0 = I % nbands;\n        auto b1 = J % nbands;\n        double omega0 = grid.get_spectrum_at_q(q0).omega(b0);\n        double omega1 = grid.get_spectrum_at_q(q1).omega(b1);\n        /// It goes with Umklapp as they do not conserve the momentum\n        cB(I - 3, I - 3) = NeumaierSum(cB(I - 3, I - 3), -process_block.second);\n        cB(I - 3, J - 3) = NeumaierSum(\n            cB(I - 3, J - 3), (omega0 / omega1) * process_block.second);\n\n        iel++;\n        if (my_id == 0) {\n            std::cout << \"#iel => \" << iel << \" / \" << ntot << std::endl;\n        }\n    }\n\n\n    /// Now we collapse the matrix in root and broadcast to other procs:\n    /// This is not RAM friendly (from memory point of view it will be cheaper\n    /// to reduce by element or chunk of elements)\n    Eigen::MatrixXd B(nmodes-3,nmodes-3);\n    ///We collapse from procs and we \n    ///eval the Neumaier Summations\n    if (nprocs == 1 ) {\n        for (decltype(nmodes) J=0; J < nmodes-3; J++) {\n            for (decltype(nmodes) I=0; I < nmodes-3; I++) {\n                B(I,J) = \n                    evalNeumaierSum(cB(I,J));\n            }\n        }\n    }\n    else {\n        for (decltype(nmodes) J = 0; J < nmodes - 3; J++) {\n            for (decltype(nmodes) I = 0; I < nmodes - 3; I++) {\n                std::vector<std::complex<double>> v;\n\n                gather(world, cB(I, J), v, 0);\n\n                /// Eval Neumaier\n                if (my_id == 0) {\n                    B(I, J) = combineNeumaierSums(v);\n                }\n\n                broadcast(world, B(I, J), 0);\n            }\n        }\n    }\n    \n    \n    ///Enforcing energy conservation\n    for (std::size_t J = 0; J < nmodes - 3; J++) {\n        /// Getting the mean of energy that we need to add back to enforce\n        /// energy conservation column-major ordering makes those column\n        /// operations efficient\n        Eigen::VectorXd Bcol = B.col(J);\n        \n        auto deltaj_mean = -(NeumaierSum(Bcol.data(),\n                         Bcol.rows())) / (nmodes - 3);\n        /// We are now adding deltaj_mean to counter the defficit in\n        /// conservation\n        for (std::size_t I = 0; I < nmodes - 3; I++)\n            B(I, J) += deltaj_mean;\n        // Making sanity check:\n        \n        // Making sanity check:\n        if (!alma::almost_equal(B.col(J).sum(),0.)) {\n            std::cerr << \"Error in enforcing energy\"\n                      << std::endl;\n            world.abort(1);\n        }\n    }\n    /// We return B, the user should take care and use std::move as it is\n    /// cheaper than copying.\n\n    return B;\n}\n\n\nvoid Arnoldi_algorithm(const Eigen::MatrixXd& A,\n                       const Eigen::VectorXd& b,\n                       int n,\n                       Eigen::MatrixXd& B,\n                       Eigen::MatrixXd& H,\n                       double t) {\n    // Init some variables\n    int m = A.rows();\n    H.resize(n, n);\n    H.setZero();\n    B.resize(m, n);\n    B.setZero();\n    Eigen::VectorXd q = b / b.norm(); // Normalize the input vector\n    B.col(0) =\n        q; // Use the normalized input vector as first Krylov subspace basis\n\n    for (int k = 0; k < n; k++) {\n        Eigen::VectorXd z = t * A * q;\n        for (int j = 0; j < k;\n             j++) { // We are substracting the projections from previous vectors\n            H(j, k) = B.col(j).transpose() * z;\n            z -= H(j, k) * B.col(j);\n        }\n        \n\t/// Break Arnoldi's, it is complete\n        if (almost_equal(z.norm(),\n            0.,1.0e-12,1.0e-9)) {\n            break;\n        }\n        \n        if (k + 1 < n) {\n            H(k + 1, k) = z.norm();\n            q = z / H(k + 1, k); // Getting new vector\n            B.col(k + 1) = q;\n        }\n    }\n}\n\n\npropagator_H::propagator_H() {\n}\n\npropagator_H::propagator_H(Eigen::VectorXd& b) {\n    std::size_t data_size = b.size();\n    (this->signed_cumm).resize(data_size);\n\n    this->pcol_abssum = b.array().abs().sum();\n\n    double accumulator = 0.;\n    for (std::size_t i = 0; i < data_size; i++) {\n        accumulator += std::abs(b(i));\n        (this->signed_cumm)(i) = (b(i) < 0.)\n                                     ? -accumulator / (this->pcol_abssum)\n                                     : accumulator / (this->pcol_abssum);\n    }\n}\n\npropagator_H::propagator_H(const propagator_H& B) :\n        signed_cumm(B.signed_cumm) , pcol_abssum(B.pcol_abssum) {\n}\n\npropagator_H::propagator_H(propagator_H&& B) : \n        signed_cumm(std::move(B.signed_cumm)) , \n        pcol_abssum(std::move(B.pcol_abssum)) {\n}\n\npropagator_H& propagator_H::operator=(const propagator_H& B) {\n    this->signed_cumm = B.signed_cumm;\n    this->pcol_abssum = B.pcol_abssum;\n    return *this;\n}\n\nbool propagator_H::operator<(const propagator_H& B) const {\n    return this->pcol_abssum < B.pcol_abssum;\n};\n\n\nstd::pair<int, std::size_t> propagator_H::get(double R) const {\n    auto im = this->lower_bound(R);\n\n    if ((this->signed_cumm)(im) > 0.)\n        return std::make_pair(1, im + 3);\n    else\n        return std::make_pair(-1, im + 3);\n\n    std::cerr << \"Error in selection\" << std::endl;\n    exit(EXIT_FAILURE);\n    return std::make_pair(0, 0);\n}\n\nEigen::VectorXd propagator_H::get_signed_cumm() const {\n    return this->signed_cumm;\n}\n\nstd::size_t propagator_H::byte_size() const {\n    return sizeof(double) * (this->signed_cumm).size() +\n           sizeof(Eigen::VectorXd) + sizeof(double);\n}\n\nstd::size_t propagator_H::size() const {\n    return (this->signed_cumm).size();\n}\n\nalma::propagator_H lirp(alma::propagator_H& H1,\n                        alma::propagator_H& H2,\n                        double T1,\n                        double T2,\n                        double Tx) {\n    Eigen::VectorXd Pint =\n        H1.signed_cumm +\n        (Tx - T1) * (H2.signed_cumm - H1.signed_cumm) / (T2 - T1);\n    double absint = H1.pcol_abssum +\n                    (Tx - T1) * (H2.pcol_abssum - H1.pcol_abssum) / (T2 - T1);\n    return alma::propagator_H(Pint, absint);\n}\n\nvoid save_P(std::string fname,\n            Eigen::MatrixXd& data,\n            boost::mpi::communicator& world) {\n    std::size_t master = 0;\n    std::size_t my_id = world.rank();\n    std::size_t nprocs = world.size();\n    if (nprocs > 1) {\n        for (std::size_t iproc = 0; iproc < nprocs; iproc++) {\n            if (my_id == iproc) {\n                if (my_id == master) {\n                    Eigen::MatrixXd::Index nmodes = data.rows();\n                    auto flags =\n                        std::ios::out | std::ios::binary | std::ios::trunc;\n                    std::ofstream out((fname).c_str(), flags);\n                    out.write((char*)(&nmodes), sizeof(Eigen::MatrixXd::Index));\n                    out.write((char*)data.data(), data.size() * sizeof(double));\n                    out.close();\n                }\n                else {\n                    /// Other nodes open but not erase the info\n                    auto flags =\n                        std::ios::out | std::ios::binary | std::ios::app;\n                    std::ofstream out((fname).c_str(), flags);\n                    out.write((char*)data.data(), data.size() * sizeof(double));\n                    out.close();\n                }\n            }\n            world.barrier();\n        }\n    }\n    else {\n        Eigen::MatrixXd::Index nmodes = data.rows();\n        auto flags = std::ios::out | std::ios::binary | std::ios::trunc;\n        std::ofstream out((fname).c_str(), flags);\n        out.write((char*)(&nmodes), sizeof(Eigen::MatrixXd::Index));\n        out.write((char*)data.data(), data.size() * sizeof(double));\n        out.close();\n    }\n}\n\n\nvoid load_P(std::string fname,\n            Eigen::MatrixXd& pmat,\n            boost::mpi::communicator& world) {\n    std::size_t master = 0;\n    std::size_t my_id = world.rank();\n    std::size_t nprocs = world.size();\n\n    std::vector<Eigen::MatrixXd> pmat_procs(nprocs);\n\n    /// Read binary to memory only in master\n    Eigen::MatrixXd::Index nmodes = 0;\n\n    /// It might be\n    if (my_id == master) {\n        auto flags = std::ios::in | std::ios::binary;\n        std::ifstream in((fname).c_str(), flags);\n        in.read((char*)(&nmodes), sizeof(Eigen::MatrixXd::Index));\n        /// Scale propagator (not the most efficient way)\n        if (nprocs > 1) {\n            for (std::size_t iproc = 0; iproc < nprocs; iproc++) {\n                auto limits = alma::my_jobs(nmodes, nprocs, iproc);\n                // If node do not contain info simply ignore\n                if (limits[1] - limits[0] == 0)\n                    continue;\n                auto ncols = limits[1] - limits[0];\n                /// Master is special case\n                pmat_procs[iproc].resize(nmodes, ncols);\n                in.read((char*)pmat_procs[iproc].data(),\n                        nmodes * ncols * sizeof(double));\n            }\n        }\n        else {\n            pmat.resize(nmodes, nmodes);\n            in.read((char*)pmat.data(), nmodes * nmodes * sizeof(double));\n        }\n        in.close();\n    }\n\n    // If multiple procs scatter info\n    if (nprocs > 1)\n        scatter(world, pmat_procs, pmat, 0.);\n}\n\nvoid build_P(Eigen::MatrixXd& A,\n             Eigen::MatrixXd& P,\n             double t,\n             boost::mpi::communicator& world,\n             double eps) {\n    /// Check for optimal Kryslov subspace\n    int ksize = 2;\n\n    while (true) {\n        /// Check that the error per element is lower than the eps\n        if (error_bound(A, ksize, t) / A.size() < eps) {\n            break;\n        }\n        ksize++;\n    }\n\n    /// Now we will break the problem by MPI processes, taking each of them care\n    /// of a column.\n    auto limits = alma::my_jobs(A.cols(), world.size(), world.rank());\n\n    auto proc_cols = limits[1] - limits[0];\n\n    if (proc_cols != 0)\n        P.resize(A.cols(), proc_cols);\n\n    std::mutex coutmutex;\n    std::size_t colcount = 0;\n    /// TBB parallelism combined with boost mpi (use MPI for diferent nodes and\n    /// TBB inside the same node)\n    tbb::parallel_for(\n        tbb::blocked_range<std::size_t>(limits[0], limits[1]),\n        [&](tbb::blocked_range<std::size_t> colrange) {\n            for (auto ii = colrange.begin(); ii < colrange.end(); ii++) {\n                coutmutex.lock();\n                std::cout << \"#Exp \" << colcount << \"/\" << A.cols()\n                          << std::endl;\n                colcount++;\n                coutmutex.unlock();\n                Eigen::MatrixXd B, H;\n                Eigen::VectorXd b(A.cols());\n                b.setZero();\n                b(ii) = 1.0;\n                alma::Arnoldi_algorithm(A, b, ksize, B, H, t);\n                P.col(ii - limits[0]) =\n                    (B * (H.exp())).col(0); /// This is the Krylov approach to\n                                            /// the exponential\n            }\n        });\n}\n\n\nvoid build_histogram(Eigen::MatrixXd& A,\n                     std::unordered_map<std::size_t, propagator_H>& modes_histo,\n                     double t,\n                     boost::mpi::communicator& world,\n                     double eps,\n                     bool print_info) {\n    /// Check for optimal Kryslov subspace\n    int ksize = 2;\n\n    while (true) {\n        /// Check that the error per element is lower than the eps\n        if (error_bound(A, ksize, t) / A.size() < eps) {\n            break;\n        }\n        ksize++;\n    }\n\n    /// Now we will break the problem by MPI processes, taking each of them care\n    /// of a column.\n    auto limits = alma::my_jobs(A.cols(), world.size(), world.rank());\n\n    std::size_t ram_size = 0, nel = 0;\n\n    for (auto i = limits[0]; i < limits[1]; i++) {\n        Eigen::MatrixXd B, H;\n        Eigen::VectorXd b(A.cols());\n        b.setZero();\n        b(i) = 1.0;\n        alma::Arnoldi_algorithm(A, b, ksize, B, H, t);\n        b = (B * (H.exp()))\n                .col(0); /// This is the Krylov approach to the exponential\n        modes_histo[i + 3] = propagator_H(b);\n        ram_size += modes_histo[i + 3].byte_size();\n        nel += modes_histo[i + 3].size();\n    }\n\n    if (print_info) {\n        std::cout << \"the size in RAM \" << ram_size << \" bytes\" << std::endl;\n        std::cout << \"non null elements count \" << nel << \" / \" << A.size()\n                  << std::endl;\n        std::cout << \"density \" << (double)nel / (double)A.size() * 100.0\n                  << \" %\" << std::endl;\n    }\n}\n\n\n} // namespace alma\n", "meta": {"hexsha": "1d880731fe6f03adbe87d0733fa4a492430d00bf", "size": 48848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/collision_operator.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/collision_operator.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/collision_operator.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": 43.888589398, "max_line_length": 81, "alphanum_fraction": 0.3912954471, "num_tokens": 9785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.041462269158095026, "lm_q1q2_score": 0.016577098453922304}}
{"text": "#ifndef _LOOKUP_TABLE_H_\n#define _LOOKUP_TABLE_H_\n\n#include <boost/tuple/tuple_comparison.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n#include <memory>\n#include <algorithm>\n#include <vector>\n#include <cstdlib>\n#include <cassert>\n#include <limits>\n#include <boost/functional/hash.hpp>\n#include <boost/optional.hpp>\n\nnamespace sdo\n{\n\nusing boost::optional;\n/**\n * Class to store a lookup table as a piecwise linear function.\n */\nclass LookupTable\n{\npublic:\n   using iterator = boost::zip_iterator<\n      boost::tuple <std::vector<double>::const_iterator, std::vector<double>::const_iterator>\n   >;\n\n   void addPoint( double, double );\n\n   iterator getPoint( unsigned i ) const;\n   iterator begin() const;\n   iterator end() const;\n\n   std::vector<double>& getXvals()\n   {\n      return x;\n   }\n\n   std::vector<double>& getYvals()\n   {\n      return y;\n   }\n\n   const std::vector<double>& getXvals() const\n   {\n      return x;\n   }\n\n   const std::vector<double>& getYvals() const\n   {\n      return y;\n   }\n\n   std::size_t size() const {\n      return x.size();\n   }\n\n   double operator()( double ) const;\n\n   template<class Archive>\n   void serialize( Archive& ar, const unsigned int version )\n   {\n      ar& x;\n      ar& y;\n   }\n\nprivate:\n   std::vector<double> x;\n   std::vector<double> y;\n};\n\n// =================== Inline implementation =====================\n\ninline void LookupTable::addPoint( double px, double py )\n{\n   x.push_back( px );\n   y.push_back( py );\n}\n\n\ninline LookupTable::iterator LookupTable::getPoint( unsigned i ) const\n{\n   return boost::make_zip_iterator(\n             boost::make_tuple(\n                x.begin() + i,\n                y.begin() + i ) );\n}\n\ninline LookupTable::iterator LookupTable::begin() const\n{\n   return boost::make_zip_iterator(\n             boost::make_tuple(\n                x.begin(),\n                y.begin() ) );\n}\n\ninline LookupTable::iterator LookupTable::end() const\n{\n   return boost::make_zip_iterator(\n             boost::make_tuple(\n                x.end(),\n                y.end() ) );\n}\n\n\ninline double LookupTable::operator()( double v ) const\n{\n   if( v >= *( x.end() - 1 ) )\n      return *( y.end() - 1 );\n\n   if( v <= *x.begin() )\n      return *y.begin();\n\n   int j = std::upper_bound(\n              x.begin(),\n              x.end(), v ) - x.begin() - 1;\n   return  y[j] + ( y[j + 1] - y[j] ) * ( v - x[j] ) / ( x[j + 1] - x[j] );\n}\n\ninline\nbool operator==( const LookupTable &a, const LookupTable &b )\n{\n   LookupTable::iterator aiter, biter;\n   aiter = a.begin();\n   biter = b.begin();\n\n   while( aiter != a.end() && biter != b.end() )\n   {\n      if( *( aiter++ ) != *( biter++ ) )\n         return false;\n   }\n\n   return aiter == a.end() && biter == b.end();\n}\n\ninline\nstd::size_t hash_value( const LookupTable& lkp )\n{\n   std::size_t hash = boost::hash_range( lkp.getXvals().begin(), lkp.getXvals().end() );\n   boost::hash_combine(\n      hash,\n      boost::hash_range( lkp.getYvals().begin(), lkp.getYvals().end() )\n   );\n   return hash;\n}\n\n\n}\n\n\n#endif // _LOOKUP_TABLE_H_\n\n", "meta": {"hexsha": "159bf4f549914cb54cb3c589aa51498450280da9", "size": 3040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdo/LookupTable.hpp", "max_stars_repo_name": "rgottwald/libsdo", "max_stars_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdo/LookupTable.hpp", "max_issues_repo_name": "rgottwald/libsdo", "max_issues_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdo/LookupTable.hpp", "max_forks_repo_name": "rgottwald/libsdo", "max_forks_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7402597403, "max_line_length": 93, "alphanum_fraction": 0.5766447368, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.043365794282118335, "lm_q1q2_score": 0.016531889286582578}}
{"text": "\n#include <NTL/lzz_p.h>\n\n\nNTL_START_IMPL\n\n\nNTL_TLS_GLOBAL_DECL(SmartPtr<zz_pInfoT>, zz_pInfo_stg)\n\nNTL_CHEAP_THREAD_LOCAL zz_pInfoT *zz_pInfo = 0;\n\n\n\nSmartPtr<zz_pInfoT> Build_zz_pInfo(FFTPrimeInfo *info)\n{\n   return MakeSmart<zz_pInfoT>(INIT_FFT, info);\n}\n\n\nzz_pInfoT::zz_pInfoT(long NewP, long maxroot)\n{\n   if (maxroot < 0) LogicError(\"zz_pContext: maxroot may not be negative\");\n\n   if (NewP <= 1) LogicError(\"zz_pContext: p must be > 1\");\n   if (NumBits(NewP) > NTL_SP_NBITS) ResourceError(\"zz_pContext: modulus too big\");\n\n   ZZ P, B, M, M1, MinusM;\n   long n, i;\n   long q, t;\n   mulmod_t qinv;\n\n   p = NewP;\n   pinv = PrepMulMod(p);\n   red_struct = sp_PrepRem(p);\n   ll_red_struct = make_sp_ll_reduce_struct(p);\n   ZZ_red_struct.build(p);\n\n   p_info = 0;\n\n   conv(P, p);\n\n   sqr(B, P);\n   LeftShift(B, B, maxroot+NTL_FFTFudge);\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   if (n > 4) LogicError(\"zz_pInit: too many primes\");\n\n   NumPrimes = n;\n   PrimeCnt = n;\n   MaxRoot = CalcMaxRoot(q);\n\n   if (maxroot < MaxRoot)\n      MaxRoot = maxroot;\n\n   negate(MinusM, M);\n   MinusMModP = rem(MinusM, p);\n   MinusMModPpinv = PrepMulModPrecon(MinusMModP, p, pinv);\n\n   CoeffModP.SetLength(n);\n   CoeffModPpinv.SetLength(n);\n   x.SetLength(n);\n   u.SetLength(n);\n   uqinv.SetLength(n);\n\n   for (i = 0; i < n; i++) {\n      q = GetFFTPrime(i);\n      qinv = GetFFTPrimeInv(i);\n\n      div(M1, M, q);\n      t = rem(M1, q);\n      t = InvMod(t, q);\n      CoeffModP[i] = rem(M1, p);\n      CoeffModPpinv[i] = PrepMulModPrecon(CoeffModP[i], p, pinv); \n      x[i] = ((double) t)/((double) q);\n      u[i] = t;\n      uqinv[i] = PrepMulModPrecon(t, q, qinv);\n   }\n}\n\nzz_pInfoT::zz_pInfoT(INIT_FFT_TYPE, FFTPrimeInfo *info)\n{\n   p = info->q;\n   pinv = info->qinv;\n   red_struct = sp_PrepRem(p);\n   ll_red_struct = make_sp_ll_reduce_struct(p);\n   ZZ_red_struct.build(p);\n\n\n   p_info = info;\n\n   NumPrimes = 1;\n   PrimeCnt = 0;\n\n   MaxRoot = CalcMaxRoot(p);\n}\n\n// FIXME: we could make bigtab an optional argument\n\nzz_pInfoT::zz_pInfoT(INIT_USER_FFT_TYPE, long q)\n{\n   long w;\n   if (!IsFFTPrime(q, w)) LogicError(\"invalid user supplied prime\");\n\n   p = q;\n   pinv = PrepMulMod(p);\n   red_struct = sp_PrepRem(p);\n   ll_red_struct = make_sp_ll_reduce_struct(p);\n   ZZ_red_struct.build(p);\n\n\n   p_info_owner.make();\n   p_info = p_info_owner.get();\n\n   long bigtab_index = -1;\n#ifdef NTL_FFT_BIGTAB\n   bigtab_index = 0;\n#endif\n   InitFFTPrimeInfo(*p_info, q, w, bigtab_index); \n\n   NumPrimes = 1;\n   PrimeCnt = 0;\n\n   MaxRoot = CalcMaxRoot(p);\n}\n\n\nvoid zz_p::init(long p, long maxroot)\n{\n   zz_pContext c(p, maxroot);\n   c.restore();\n\n}\n\nvoid zz_p::FFTInit(long index)\n{\n   zz_pContext c(INIT_FFT, index);\n   c.restore();\n}\n\nvoid zz_p::UserFFTInit(long q)\n{\n   zz_pContext c(INIT_USER_FFT, q);\n   c.restore();\n}\n\nzz_pContext::zz_pContext(long p, long maxroot) : \n   ptr(MakeSmart<zz_pInfoT>(p, maxroot)) \n{ }\n\nzz_pContext::zz_pContext(INIT_FFT_TYPE, long index)\n{\n   if (index < 0)\n      LogicError(\"bad FFT prime index\");\n\n   UseFFTPrime(index);\n\n   ptr =  FFTTables[index]->zz_p_context;\n}\n\nzz_pContext::zz_pContext(INIT_USER_FFT_TYPE, long q) :\n   ptr(MakeSmart<zz_pInfoT>(INIT_USER_FFT, q))\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   NTL_TLS_GLOBAL_ACCESS(zz_pInfo_stg);\n   zz_pInfo_stg = ptr;\n   zz_pInfo = zz_pInfo_stg.get();\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\n\n\n\n\n\nistream& operator>>(istream& s, zz_p& x)\n{\n   NTL_ZZRegister(y);\n   NTL_INPUT_CHECK_RET(s, s >> y);\n   conv(x, y);\n\n   return s;\n}\n\nostream& operator<<(ostream& s, zz_p a)\n{\n   NTL_ZZRegister(y);\n   y = rep(a);\n   s << y;\n\n   return s;\n}\n\n\n\n// ***********************************************************************\n\n\n#ifdef NTL_HAVE_LL_TYPE\n\n\n// NOTE: the following code sequence will generate imulq \n// instructions on x86_64 machines, which empirically is faster\n// than using the mulq instruction or even the mulxq instruction,\n// (tested on a Haswell machine).\n\nlong \nInnerProd_LL(const long *ap, const zz_p *bp, long n, long d, \n          sp_ll_reduce_struct dinv)\n{\n   const long BLKSIZE = (1L << min(20, 2*(NTL_BITS_PER_LONG-NTL_SP_NBITS)));\n\n   unsigned long acc0 = 0;\n   ll_type acc21;\n   ll_init(acc21, 0);\n\n   long i;\n   for (i = 0; i <= n-BLKSIZE; i += BLKSIZE, ap += BLKSIZE, bp += BLKSIZE) {\n      // sum ap[j]*rep(bp[j]) for j in [0..BLKSIZE)\n\n      ll_type sum;\n      ll_init(sum, 0);\n      for (long j = 0; j < BLKSIZE; j += 4) {\n         ll_imul_add(sum, ap[j+0], rep(bp[j+0]));\n         ll_imul_add(sum, ap[j+1], rep(bp[j+1]));\n         ll_imul_add(sum, ap[j+2], rep(bp[j+2]));\n         ll_imul_add(sum, ap[j+3], rep(bp[j+3]));\n      }\n\n      ll_add(sum, acc0); \n      acc0 = ll_get_lo(sum);\n      ll_add(acc21, ll_get_hi(sum));\n   }\n\n   if (i < n) {\n      // sum ap[i]*rep(bp[j]) for j in [0..n-i)\n\n      ll_type sum; \n      ll_init(sum, 0);\n      long j = 0;\n      for (; j <= n-i-4; j += 4) {\n         ll_imul_add(sum, ap[j+0], rep(bp[j+0]));\n         ll_imul_add(sum, ap[j+1], rep(bp[j+1]));\n         ll_imul_add(sum, ap[j+2], rep(bp[j+2]));\n         ll_imul_add(sum, ap[j+3], rep(bp[j+3]));\n      }\n\n      for (; j < n-i; j++)\n         ll_imul_add(sum, ap[j], rep(bp[j]));\n\n\n      ll_add(sum, acc0); \n      acc0 = ll_get_lo(sum);\n      ll_add(acc21, ll_get_hi(sum));\n   }\n\n   if (dinv.nbits == NTL_SP_NBITS) \n      return sp_ll_red_31_normalized(ll_get_hi(acc21), ll_get_lo(acc21), acc0, d, dinv);\n   else\n      return sp_ll_red_31(ll_get_hi(acc21), ll_get_lo(acc21), acc0, d, dinv);\n}\n\n\nlong \nInnerProd_LL(const zz_p *ap, const zz_p *bp, long n, long d, \n          sp_ll_reduce_struct dinv)\n{\n   const long BLKSIZE = (1L << min(20, 2*(NTL_BITS_PER_LONG-NTL_SP_NBITS)));\n\n   unsigned long acc0 = 0;\n   ll_type acc21;\n   ll_init(acc21, 0);\n\n   long i;\n   for (i = 0; i <= n-BLKSIZE; i += BLKSIZE, ap += BLKSIZE, bp += BLKSIZE) {\n      // sum ap[j]*rep(bp[j]) for j in [0..BLKSIZE)\n\n      ll_type sum;\n      ll_init(sum, 0);\n      for (long j = 0; j < BLKSIZE; j += 4) {\n         ll_imul_add(sum, rep(ap[j+0]), rep(bp[j+0]));\n         ll_imul_add(sum, rep(ap[j+1]), rep(bp[j+1]));\n         ll_imul_add(sum, rep(ap[j+2]), rep(bp[j+2]));\n         ll_imul_add(sum, rep(ap[j+3]), rep(bp[j+3]));\n      }\n\n      ll_add(sum, acc0); \n      acc0 = ll_get_lo(sum);\n      ll_add(acc21, ll_get_hi(sum));\n   }\n\n   if (i < n) {\n      // sum ap[i]*rep(bp[j]) for j in [0..n-i)\n\n      ll_type sum; \n      ll_init(sum, 0);\n      long j = 0;\n      for (; j <= n-i-4; j += 4) {\n         ll_imul_add(sum, rep(ap[j+0]), rep(bp[j+0]));\n         ll_imul_add(sum, rep(ap[j+1]), rep(bp[j+1]));\n         ll_imul_add(sum, rep(ap[j+2]), rep(bp[j+2]));\n         ll_imul_add(sum, rep(ap[j+3]), rep(bp[j+3]));\n      }\n\n      for (; j < n-i; j++)\n         ll_imul_add(sum, rep(ap[j]), rep(bp[j]));\n\n\n      ll_add(sum, acc0); \n      acc0 = ll_get_lo(sum);\n      ll_add(acc21, ll_get_hi(sum));\n   }\n\n   if (dinv.nbits == NTL_SP_NBITS) \n      return sp_ll_red_31_normalized(ll_get_hi(acc21), ll_get_lo(acc21), acc0, d, dinv);\n   else\n      return sp_ll_red_31(ll_get_hi(acc21), ll_get_lo(acc21), acc0, d, dinv);\n}\n\n\nlong \nInnerProd_L(const long *ap, const zz_p *bp, long n, long d, \n          sp_reduce_struct dinv, long bound)\n{\n   unsigned long sum = 0;\n   long j = 0;\n\n   if (n <= bound) {\n      for (; j <= n-4; j += 4) {\n\t sum += (ap[j+0]) * rep(bp[j+0]);\n\t sum += (ap[j+1]) * rep(bp[j+1]);\n\t sum += (ap[j+2]) * rep(bp[j+2]);\n\t sum += (ap[j+3]) * rep(bp[j+3]);\n      }\n\n      for (; j < n; j++)\n\t sum += (ap[j]) * rep(bp[j]);\n\n      return rem(sum, d, dinv);\n   }\n\n   for (; j <= n-bound; j += bound) {\n\n      long i = 0;\n      for (; i <= bound-4; i += 4) {\n         sum += (ap[j+i+0]) * rep(bp[j+i+0]);\n         sum += (ap[j+i+1]) * rep(bp[j+i+1]);\n         sum += (ap[j+i+2]) * rep(bp[j+i+2]);\n         sum += (ap[j+i+3]) * rep(bp[j+i+3]);\n      }\n\n      for (; i < bound; i++) {\n         sum += (ap[j+i]) * rep(bp[j+i]);\n      }\n\n      sum = rem(sum, d, dinv);\n   }\n\n   if (j >= n) return sum;\n\n   for (; j <= n-4; j += 4) {\n      sum += (ap[j+0]) * rep(bp[j+0]);\n      sum += (ap[j+1]) * rep(bp[j+1]);\n      sum += (ap[j+2]) * rep(bp[j+2]);\n      sum += (ap[j+3]) * rep(bp[j+3]);\n   }\n\n   for (; j < n; j++)\n      sum += (ap[j]) * rep(bp[j]);\n\n   return rem(sum, d, dinv);\n}\n\nlong \nInnerProd_L(const zz_p *ap, const zz_p *bp, long n, long d, \n          sp_reduce_struct dinv, long bound)\n{\n   unsigned long sum = 0;\n   long j = 0;\n\n   if (n <= bound) {\n      for (; j <= n-4; j += 4) {\n\t sum += rep(ap[j+0]) * rep(bp[j+0]);\n\t sum += rep(ap[j+1]) * rep(bp[j+1]);\n\t sum += rep(ap[j+2]) * rep(bp[j+2]);\n\t sum += rep(ap[j+3]) * rep(bp[j+3]);\n      }\n\n      for (; j < n; j++)\n\t sum += rep(ap[j]) * rep(bp[j]);\n\n      return rem(sum, d, dinv);\n   }\n\n   for (; j <= n-bound; j += bound) {\n\n      long i = 0;\n      for (; i <= bound-4; i += 4) {\n         sum += rep(ap[j+i+0]) * rep(bp[j+i+0]);\n         sum += rep(ap[j+i+1]) * rep(bp[j+i+1]);\n         sum += rep(ap[j+i+2]) * rep(bp[j+i+2]);\n         sum += rep(ap[j+i+3]) * rep(bp[j+i+3]);\n      }\n\n      for (; i < bound; i++) {\n         sum += rep(ap[j+i]) * rep(bp[j+i]);\n      }\n\n      sum = rem(sum, d, dinv);\n   }\n\n   if (j >= n) return sum;\n\n   for (; j <= n-4; j += 4) {\n      sum += rep(ap[j+0]) * rep(bp[j+0]);\n      sum += rep(ap[j+1]) * rep(bp[j+1]);\n      sum += rep(ap[j+2]) * rep(bp[j+2]);\n      sum += rep(ap[j+3]) * rep(bp[j+3]);\n   }\n\n   for (; j < n; j++)\n      sum += rep(ap[j]) * rep(bp[j]);\n\n   return rem(sum, d, dinv);\n}\n\n#endif\n\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "7dff12ff03643c1b4e0904553f2bdac2f46b498f", "size": 9802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/lzz_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/lzz_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/lzz_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.9444444444, "max_line_length": 88, "alphanum_fraction": 0.5422362783, "num_tokens": 3407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.034100426325821886, "lm_q1q2_score": 0.0165175673775827}}
{"text": "/* Copyright (c) 2016, Jakob Engel\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 and/or \n * other materials provided with the distribution.\n * \n * 3. Neither the name of the copyright holder nor the names of its contributors \n * may be used to endorse or promote products derived from this software without \n * specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, \n * 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) \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#include \"FOVUndistorter.h\"\n\n#include <sstream>\n#include <fstream>\n\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <locale.h>\n\n\nUndistorterFOV::UndistorterFOV()\n{\n\tremapX = nullptr;\n\tremapY = nullptr;\n\tvalid=false;\n}\n\nUndistorterFOV::UndistorterFOV(const char* configFileName)\n{\n\n\tsetlocale(LC_NUMERIC, \"C\");\n\tremapX = nullptr;\n\tremapY = nullptr;\n\tvalid=false;\n\n\t// read parameters\n\tstd::ifstream infile(configFileName);\n\tif(!infile.good())\n\t{\n\t\tprintf(\"Failed to read camera calibration (invalid format?)\\nCalibration file: %s\\n\", configFileName);\n\t\treturn;\n\t}\n\n\n\tstd::string l1,l2,l3,l4;\n\tstd::getline(infile,l1);\n\tstd::getline(infile,l2);\n\tstd::getline(infile,l3);\n\tstd::getline(infile,l4);\n\n\n\t// l1 & l2\n\tif(std::sscanf(l1.c_str(), \"%f %f %f %f %f\", &inputCalibration[0], &inputCalibration[1], &inputCalibration[2], &inputCalibration[3], &inputCalibration[4]) == 5 &&\n\t\t\tstd::sscanf(l2.c_str(), \"%d %d\", &in_width, &in_height) == 2)\n\t{\n\t\tprintf(\"Input resolution: %d %d\\n\",in_width, in_height);\n\t\tprintf(\"Input Calibration (fx fy cx cy): %f %f %f %f %f\\n\",\n\t\t\t\tin_width*inputCalibration[0], in_height*inputCalibration[1], in_width*inputCalibration[2], in_height*inputCalibration[3], inputCalibration[4]);\n\t}\n\telse\n\t{\n\t\tprintf(\"Failed to read camera calibration (invalid format?)\\nCalibration file: %s\\n\", configFileName);\n\t\treturn;\n\t}\n\n\n\t// l3\n\tif(l3 == \"crop\")\n\t{\n\t\toutputCalibration[0] = -1;\n\t\tprintf(\"Out: Crop\\n\");\n\t}\n\telse if(l3 == \"full\")\n\t{\n\t\toutputCalibration[0] = -2;\n\t\tprintf(\"Out: Full\\n\");\n\t}\n\telse if(l3 == \"none\")\n\t{\n\t\tprintf(\"NO RECTIFICATION\\n\");\n\t\treturn;\n\t}\n\telse if(std::sscanf(l3.c_str(), \"%f %f %f %f %f\", &outputCalibration[0], &outputCalibration[1], &outputCalibration[2], &outputCalibration[3], &outputCalibration[4]) == 5)\n\t{\n\t\tprintf(\"Out: %f %f %f %f %f\\n\",\n\t\t\t\toutputCalibration[0], outputCalibration[1], outputCalibration[2], outputCalibration[3], outputCalibration[4]);\n\t}\n\telse\n\t{\n\t\tprintf(\"Out: Failed to Read Output pars... not rectifying.\\n\");\n\t\treturn;\n\t}\n\n\n\n\t// l4\n\tif(std::sscanf(l4.c_str(), \"%d %d\", &out_width, &out_height) == 2)\n\t{\n\t\tprintf(\"Output resolution: %d %d\\n\",out_width, out_height);\n\t}\n\telse\n\t{\n\t\tprintf(\"Out: Failed to Read Output resolution... not rectifying.\\n\");\n\t\treturn;\n\t}\n\n\n\tvalid=true;\n\n\n\t// =============================== find optimal new camera matrix ===============================\n\t// prep warp matrices\n\tfloat dist = inputCalibration[4];\n\tfloat d2t = 2.0f * tan(dist / 2.0f);\n\n\t// current camera parameters\n\tfloat fx = inputCalibration[0] * in_width;\n\tfloat fy = inputCalibration[1] * in_height;\n\tfloat cx = inputCalibration[2] * in_width - 0.5;\n\tfloat cy = inputCalibration[3] * in_height - 0.5;\n\n\t// output camera parameters\n\tfloat ofx, ofy, ocx, ocy;\n\n\t// find new camera matrix for \"crop\" and \"full\"\n\tif (inputCalibration[4] == 0)\n\t{\n\t\tofx = inputCalibration[0] * out_width;\n\t\tofy = inputCalibration[1] * out_height;\n\t\tocx = (inputCalibration[2] * out_width) - 0.5;\n\t\tocy = (inputCalibration[3] * out_height) - 0.5;\n\t}\n\telse if(outputCalibration[0] == -1)\t// \"crop\"\n\t{\n\t\t// find left-most and right-most radius\n\t\tfloat left_radius = (cx)/fx;\n\t\tfloat right_radius = (in_width-1 - cx)/fx;\n\t\tfloat top_radius = (cy)/fy;\n\t\tfloat bottom_radius = (in_height-1 - cy)/fy;\n\n\t\tfloat trans_left_radius = tan(left_radius * dist)/d2t;\n\t\tfloat trans_right_radius = tan(right_radius * dist)/d2t;\n\t\tfloat trans_top_radius = tan(top_radius * dist)/d2t;\n\t\tfloat trans_bottom_radius = tan(bottom_radius * dist)/d2t;\n\n\t\tofy = fy * ((top_radius + bottom_radius) / (trans_top_radius + trans_bottom_radius)) * ((float)out_height / (float)in_height);\n\t\tocy = (trans_top_radius/top_radius) * ofy*cy/fy;\n\n\t\tofx = fx * ((left_radius + right_radius) / (trans_left_radius + trans_right_radius)) * ((float)out_width / (float)in_width);\n\t\tocx = (trans_left_radius/left_radius) * ofx*cx/fx;\n\n\t\tprintf(\"new K: %f %f %f %f\\n\",ofx,ofy,ocx,ocy);\n\t\tprintf(\"old K: %f %f %f %f\\n\",fx,fy,cx,cy);\n\t}\n\telse if(outputCalibration[0] == -2)\t // \"full\"\n\t{\n\t\tfloat left_radius = cx/fx;\n\t\tfloat right_radius = (in_width-1 - cx)/fx;\n\t\tfloat top_radius = cy/fy;\n\t\tfloat bottom_radius = (in_height-1 - cy)/fy;\n\n\t\t// find left-most and right-most radius\n\t\tfloat tl_radius = sqrt(left_radius*left_radius + top_radius*top_radius);\n\t\tfloat tr_radius = sqrt(right_radius*right_radius + top_radius*top_radius);\n\t\tfloat bl_radius = sqrt(left_radius*left_radius + bottom_radius*bottom_radius);\n\t\tfloat br_radius = sqrt(right_radius*right_radius + bottom_radius*bottom_radius);\n\n\t\tfloat trans_tl_radius = tan(tl_radius * dist)/d2t;\n\t\tfloat trans_tr_radius = tan(tr_radius * dist)/d2t;\n\t\tfloat trans_bl_radius = tan(bl_radius * dist)/d2t;\n\t\tfloat trans_br_radius = tan(br_radius * dist)/d2t;\n\n\t\tfloat hor = std::max(br_radius,tr_radius) + std::max(bl_radius,tl_radius);\n\t\tfloat vert = std::max(tr_radius,tl_radius) + std::max(bl_radius,br_radius);\n\n\t\tfloat trans_hor = std::max(trans_br_radius,trans_tr_radius) + std::max(trans_bl_radius,trans_tl_radius);\n\t\tfloat trans_vert = std::max(trans_tr_radius,trans_tl_radius) + std::max(trans_bl_radius,trans_br_radius);\n\n\t\tofy = fy * ((vert) / (trans_vert)) * ((float)out_height / (float)in_height);\n\t\tocy = std::max(trans_tl_radius/tl_radius,trans_tr_radius/tr_radius) * ofy*cy/fy;\n\n\t\tofx = fx * ((hor) / (trans_hor)) * ((float)out_width / (float)in_width);\n\t\tocx = std::max(trans_bl_radius/bl_radius,trans_tl_radius/tl_radius) * ofx*cx/fx;\n\n\t\tprintf(\"new K: %f %f %f %f\\n\",ofx,ofy,ocx,ocy);\n\t\tprintf(\"old K: %f %f %f %f\\n\",fx,fy,cx,cy);\n\t}\n\telse\n\t{\n\t\tofx = outputCalibration[0] * out_width;\n\t\tofy = outputCalibration[1] * out_height;\n\t\tocx = outputCalibration[2] * out_width-0.5;\n\t\tocy = outputCalibration[3] * out_height-0.5;\n\t}\n\n\toutputCalibration[0] = ofx / out_width;\n\toutputCalibration[1] = ofy / out_height;\n\toutputCalibration[2] = (ocx+0.5) / out_width;\n\toutputCalibration[3] = (ocy+0.5) / out_height;\n\toutputCalibration[4] = 0;\n\n\n\n\n\t// =============================== build rectification map ===============================\n\tremapX = new float[out_width * out_height];\n\tremapY = new float[out_width * out_height];\n\tfor(int y=0;y<out_height;y++)\n\t\tfor(int x=0;x<out_width;x++)\n\t\t{\n\t\t\tremapX[x+y*out_width] = x;\n\t\t\tremapY[x+y*out_width] = y;\n\t\t}\n\tdistortCoordinates(remapX, remapY, out_height*out_width);\n\n\tbool hasBlackPoints = false;\n\tfor(int i=0;i<out_width * out_height;i++)\n\t{\n\t\tif(remapX[i] == 0) remapX[i] = 0.01;\n\t\tif(remapY[i] == 0) remapY[i] = 0.01;\n\t\tif(remapX[i] == in_width-1) remapX[i] = in_width-1.01;\n\t\tif(remapY[i] == in_height-1) remapY[i] = in_height-1.01;\n\n\n\t\tif(!(remapX[i] > 0 && remapY[i] > 0 && remapX[i] < in_width-1 &&  remapY[i] < in_height-1))\n\t\t{\n\t\t\t//printf(\"black pixel at %d %d %f %f!\\n\", i, i, remapX[i], remapY[i]);\n\t\t\thasBlackPoints=true;\n\t\t\tremapX[i]=-1;\n\t\t\tremapY[i]=-1;\n\n\t\t}\n\t}\n\n\tif(hasBlackPoints)\n\t\tprintf(\"\\n\\nFOV Undistorter: Warning! Image has black pixels.\\n\\n\\n\");\n\n\t// =============================== set Krect ===============================\n\tKrect.setIdentity();\n\tKrect(0,0) = outputCalibration[0] * out_width;\n\tKrect(1,1) = outputCalibration[1] * out_height;\n\tKrect(0,2) = outputCalibration[2] * out_width-0.5;\n\tKrect(1,2) = outputCalibration[3] * out_height-0.5;\n\n\n\tKorg.setIdentity();\n\tKorg(0,0) = inputCalibration[0] * in_width;\n\tKorg(1,1) = inputCalibration[1] * in_height;\n\tKorg(0,2) = inputCalibration[2] * in_width-0.5;\n\tKorg(1,2) = inputCalibration[3] * in_height-0.5;\n}\n\n\n\nUndistorterFOV::~UndistorterFOV()\n{\n\tif(remapX != 0) delete[] remapX;\n\tif(remapY != 0) delete[] remapY;\n}\n\n\nvoid UndistorterFOV::distortCoordinates(float* in_x, float* in_y, int n)\n{\n\tif(!valid)\n\t{\n\t\tprintf(\"ERROR: invalid UndistorterFOV!\\n\");\n\t\treturn;\n\t}\n\n\n\tfloat dist = inputCalibration[4];\n\tfloat d2t = 2.0f * tan(dist / 2.0f);\n\n\t// current camera parameters\n\tfloat fx = inputCalibration[0] * in_width;\n\tfloat fy = inputCalibration[1] * in_height;\n\tfloat cx = inputCalibration[2] * in_width - 0.5;\n\tfloat cy = inputCalibration[3] * in_height - 0.5;\n\n\tfloat ofx = outputCalibration[0]*out_width;\n\tfloat ofy = outputCalibration[1]*out_height;\n\tfloat ocx = outputCalibration[2]*out_width-0.5f;\n\tfloat ocy = outputCalibration[3]*out_height-0.5f;\n\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tfloat x = in_x[i];\n\t\tfloat y = in_y[i];\n\t\tfloat ix = (x - ocx) / ofx;\n\t\tfloat iy = (y - ocy) / ofy;\n\n\t\tfloat r = sqrtf(ix*ix + iy*iy);\n\t\tfloat fac = (r==0 || dist==0) ? 1 : atanf(r * d2t)/(dist*r);\n\n\t\tix = fx*fac*ix+cx;\n\t\tiy = fy*fac*iy+cy;\n\n\t\tin_x[i] = ix;\n\t\tin_y[i] = iy;\n\t}\n}\n\n\ntemplate<typename T>\nvoid UndistorterFOV::undistort(const T* input, float* output, int nPixIn, int nPixOut) const\n{\n\tif(!valid) return;\n\n\tif(nPixIn != in_width*in_height)\n\t{\n\t\tprintf(\"ERROR: undistort called with wrong input image dismesions (expected %d pixel, got %d pixel)\\n\",\n\t\t\t\tin_width*in_height, nPixIn);\n\t\treturn;\n\t}\n\tif(nPixOut != out_width*out_height)\n\t{\n\t\tprintf(\"ERROR: undistort called with wrong output image dismesions (expected %d pixel, got %d pixel)\\n\",\n\t\t\t\tout_width*out_height, nPixOut);\n\t\treturn;\n\t}\n\n\n\tfor(int idx = 0; idx < out_width*out_height;idx++)\n\t{\n\t\t// get interp. values\n\t\tfloat xx = remapX[idx];\n\t\tfloat yy = remapY[idx];\n\n\t\tif(xx<0)\n\t\t\toutput[idx] = 0;\n\t\telse\n\t\t{\n\t\t\t// get integer and rational parts\n\t\t\tint xxi = xx;\n\t\t\tint yyi = yy;\n\t\t\txx -= xxi;\n\t\t\tyy -= yyi;\n\t\t\tfloat xxyy = xx*yy;\n\n\t\t\t// get array base pointer\n\t\t\tconst T* src = input + xxi + yyi * in_width;\n\n\t\t\t// interpolate (bilinear)\n\t\t\toutput[idx] =  xxyy * src[1+in_width]\n\t\t\t\t\t\t\t\t+ (yy-xxyy) * src[in_width]\n\t\t\t\t\t\t\t\t+ (xx-xxyy) * src[1]\n\t\t\t\t\t\t\t\t+ (1-xx-yy+xxyy) * src[0];\n\t\t}\n\t}\n}\ntemplate void UndistorterFOV::undistort<float>(const float* input, float* output, int nPixIn, int nPixOut) const;\ntemplate void UndistorterFOV::undistort<unsigned char>(const unsigned char* input, float* output, int nPixIn, int nPixOut) const;\n", "meta": {"hexsha": "6bbfb790b7b9840300d158823e9e816417cd3366", "size": 11450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FOVUndistorter.cpp", "max_stars_repo_name": "tweichselbaumer/mono_dataset_code", "max_stars_repo_head_hexsha": "1f5b3baa3fb8e6248387a9837a4bf0a5f01a72c7", "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/FOVUndistorter.cpp", "max_issues_repo_name": "tweichselbaumer/mono_dataset_code", "max_issues_repo_head_hexsha": "1f5b3baa3fb8e6248387a9837a4bf0a5f01a72c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FOVUndistorter.cpp", "max_forks_repo_name": "tweichselbaumer/mono_dataset_code", "max_forks_repo_head_hexsha": "1f5b3baa3fb8e6248387a9837a4bf0a5f01a72c7", "max_forks_repo_licenses": ["BSD-3-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.5333333333, "max_line_length": 171, "alphanum_fraction": 0.6724017467, "num_tokens": 3628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.03461883784317106, "lm_q1q2_score": 0.016498633659528444}}
{"text": "#include \"trajopt/collision_terms.hpp\"\n#include \"trajopt/collision_checker.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"trajopt/utils.hpp\"\n#include \"sco/expr_vec_ops.hpp\"\n#include \"sco/expr_ops.hpp\"\n#include \"sco/sco_common.hpp\"\n#include <boost/foreach.hpp>\n#include \"utils/eigen_conversions.hpp\"\n#include \"sco/modeling_utils.hpp\"\n#include \"utils/stl_to_string.hpp\"\n#include \"utils/logging.hpp\"\n#include <boost/functional/hash.hpp>\nusing namespace OpenRAVE;\nusing namespace sco;\nusing namespace util;\nusing namespace std;\n\nnamespace trajopt {\n\n\nvoid CollisionsToDistances(const vector<Collision>& collisions, const Link2Int& m_link2ind,\n    DblVec& dists) {\n  // Note: this checking (that the links are in the list we care about) is probably unnecessary\n  // since we're using LinksVsAll\n  dists.clear();\n  dists.reserve(collisions.size());\n  BOOST_FOREACH(const Collision& col, collisions) {\n    Link2Int::const_iterator itA = m_link2ind.find(col.linkA);\n    Link2Int::const_iterator itB = m_link2ind.find(col.linkB);\n    if (itA != m_link2ind.end() || itB != m_link2ind.end()) {\n      dists.push_back(col.distance);\n    }\n  }\n}\n\nvoid CollisionsToDistanceExpressions(const vector<Collision>& collisions, Configuration& rad,\n    const Link2Int& link2ind, const VarVector& vars, const DblVec& dofvals, vector<AffExpr>& exprs, bool isTimestep1) {\n\n  exprs.clear();\n  exprs.reserve(collisions.size());\n  rad.SetDOFValues(dofvals); // since we'll be calculating jacobians\n  BOOST_FOREACH(const Collision& col, collisions) {\n    AffExpr dist(col.distance);\n    Link2Int::const_iterator itA = link2ind.find(col.linkA);\n    if (itA != link2ind.end()) {\n      VectorXd dist_grad = toVector3d(col.normalB2A).transpose()*rad.PositionJacobian(itA->second, col.ptA);\n      exprInc(dist, varDot(dist_grad, vars));\n      exprInc(dist, -dist_grad.dot(toVectorXd(dofvals)));\n    }\n    Link2Int::const_iterator itB = link2ind.find(col.linkB);\n    if (itB != link2ind.end()) {\n      VectorXd dist_grad = -toVector3d(col.normalB2A).transpose()*rad.PositionJacobian(itB->second, (isTimestep1 && (col.cctype == CCType_Between)) ? col.ptB1 : col.ptB);\n      exprInc(dist, varDot(dist_grad, vars));\n      exprInc(dist, -dist_grad.dot(toVectorXd(dofvals)));\n    }\n    if (itA != link2ind.end() || itB != link2ind.end()) {\n      exprs.push_back(dist);\n    }\n  }\n  LOG_DEBUG(\"%ld distance expressions\\n\", exprs.size());\n}\n\nvoid CollisionsToDistanceExpressions(const vector<Collision>& collisions, Configuration& rad, const Link2Int& link2ind,\n    const VarVector& vars0, const VarVector& vars1, const DblVec& vals0, const DblVec& vals1,\n    vector<AffExpr>& exprs) {\n  vector<AffExpr> exprs0, exprs1;\n  CollisionsToDistanceExpressions(collisions, rad, link2ind, vars0, vals0, exprs0, false);\n  CollisionsToDistanceExpressions(collisions, rad, link2ind, vars1, vals1, exprs1,true);\n\n  exprs.resize(exprs0.size());\n  for (int i=0; i < exprs0.size(); ++i) {\n    exprScale(exprs0[i], (1-collisions[i].time));\n    exprScale(exprs1[i], collisions[i].time);\n    exprs[i] = AffExpr(0);\n    exprInc(exprs[i], exprs0[i]);\n    exprInc(exprs[i], exprs1[i]);\n    cleanupAff(exprs[i]);\n  }\n}\n\ninline size_t hash(const DblVec& x) {\n  return boost::hash_range(x.begin(), x.end());\n}\n\nvoid CollisionEvaluator::GetCollisionsCached(const DblVec& x, vector<Collision>& collisions) {\n  double key = hash(getDblVec(x, GetVars()));\n  vector<Collision>* it = m_cache.get(key);\n  if (it != NULL) {\n    LOG_DEBUG(\"using cached collision check\\n\");\n    collisions = *it;\n  }\n  else {\n    LOG_DEBUG(\"not using cached collision check\\n\");\n    CalcCollisions(x, collisions);\n    m_cache.put(key, collisions);\n  }\n}\n\nSingleTimestepCollisionEvaluator::SingleTimestepCollisionEvaluator(ConfigurationPtr rad, const VarVector& vars) :\n  m_env(rad->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars(vars),\n  m_link2ind(),\n  m_links(),\n  m_filterMask(-1) {\n  vector<KinBody::LinkPtr> links;\n  vector<int> inds;\n  rad->GetAffectedLinks(m_links, true, inds);\n  for (int i=0; i < m_links.size(); ++i) {\n    m_link2ind[m_links[i].get()] = inds[i];\n  }\n  // TODO add argument\n}\n\n\nvoid SingleTimestepCollisionEvaluator::CalcCollisions(const DblVec& x, vector<Collision>& collisions) {\n  DblVec dofvals = getDblVec(x, m_vars);\n  m_rad->SetDOFValues(dofvals);\n  m_cc->LinksVsAll(m_links, collisions, m_filterMask);\n}\n\nvoid SingleTimestepCollisionEvaluator::CalcDists(const DblVec& x, DblVec& dists) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  CollisionsToDistances(collisions, m_link2ind, dists);\n}\n\n\nvoid SingleTimestepCollisionEvaluator::CalcDistExpressions(const DblVec& x, vector<AffExpr>& exprs) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  DblVec dofvals = getDblVec(x, m_vars);\n  CollisionsToDistanceExpressions(collisions, *m_rad, m_link2ind, m_vars, dofvals, exprs, false);\n}\n\n////////////////////////////////////////\n\nCastCollisionEvaluator::CastCollisionEvaluator(ConfigurationPtr rad, const VarVector& vars0, const VarVector& vars1) :\n  m_env(rad->GetEnv()),\n  m_cc(CollisionChecker::GetOrCreate(*m_env)),\n  m_rad(rad),\n  m_vars0(vars0),\n  m_vars1(vars1),\n  m_link2ind(),\n  m_links() {\n  vector<KinBody::LinkPtr> links;\n  vector<int> inds;\n  rad->GetAffectedLinks(m_links, true, inds);\n  for (int i=0; i < m_links.size(); ++i) {\n    m_link2ind[m_links[i].get()] = inds[i];\n  }\n}\n\nvoid CastCollisionEvaluator::CalcCollisions(const DblVec& x, vector<Collision>& collisions) {\n  DblVec dofvals0 = getDblVec(x, m_vars0);\n  DblVec dofvals1 = getDblVec(x, m_vars1);\n  m_rad->SetDOFValues(dofvals0);\n  m_cc->CastVsAll(*m_rad, m_links, dofvals0, dofvals1, collisions);\n}\nvoid CastCollisionEvaluator::CalcDistExpressions(const DblVec& x, vector<AffExpr>& exprs) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  DblVec dofvals0 = getDblVec(x, m_vars0);\n  DblVec dofvals1 = getDblVec(x, m_vars1);\n  CollisionsToDistanceExpressions(collisions, *m_rad, m_link2ind, m_vars0, m_vars1, dofvals0, dofvals1, exprs);\n}\nvoid CastCollisionEvaluator::CalcDists(const DblVec& x, DblVec& dists) {\n  vector<Collision> collisions;\n  GetCollisionsCached(x, collisions);\n  CollisionsToDistances(collisions, m_link2ind, dists);\n}\n\n\n//////////////////////////////////////////\n\n\n\ntypedef OpenRAVE::RaveVector<float> RaveVectorf;\n\nvoid PlotCollisions(const std::vector<Collision>& collisions, OR::EnvironmentBase& env, vector<OR::GraphHandlePtr>& handles, double safe_dist) {\n  BOOST_FOREACH(const Collision& col, collisions) {\n    RaveVectorf color;\n    if (col.distance < 0) color = RaveVectorf(1,0,0,1);\n    else if (col.distance < safe_dist) color = RaveVectorf(1,1,0,1);\n    else color = RaveVectorf(0,1,0,1);\n    if (col.cctype == CCType_Between) {\n      handles.push_back(env.drawarrow(col.ptB, col.ptB1, .002, RaveVectorf(0,0,0,1)));\n    }\n    OR::Vector ptB = (col.cctype == CCType_Between)  ? ((1-col.time)* col.ptB +col.time*col.ptB1) : col.ptB;\n    handles.push_back(env.drawarrow(col.ptA, ptB, .0025, color));\n  }\n}\n\nCollisionCost::CollisionCost(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars) :\n    Cost(\"collision\"),\n    m_calc(new SingleTimestepCollisionEvaluator(rad, vars)), m_dist_pen(dist_pen), m_coeff(coeff)\n{}\n\nCollisionCost::CollisionCost(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars0, const VarVector& vars1) :\n    Cost(\"cast_collision\"),\n    m_calc(new CastCollisionEvaluator(rad, vars0, vars1)), m_dist_pen(dist_pen), m_coeff(coeff)\n{}\nConvexObjectivePtr CollisionCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  vector<AffExpr> exprs;\n  m_calc->CalcDistExpressions(x, exprs);\n  for (int i=0; i < exprs.size(); ++i) {\n    AffExpr viol = exprSub(AffExpr(m_dist_pen), exprs[i]);\n    out->addHinge(viol, m_coeff);\n  }\n  return out;\n}\ndouble CollisionCost::value(const vector<double>& x) {\n  DblVec dists;\n  m_calc->CalcDists(x, dists);\n  double out = 0;\n  for (int i=0; i < dists.size(); ++i) {\n    out += pospart(m_dist_pen - dists[i]) * m_coeff;\n  }\n  return out;\n}\n\nvoid CollisionCost::Plot(const DblVec& x, OR::EnvironmentBase& env, std::vector<OR::GraphHandlePtr>& handles) {\n  vector<Collision> collisions;\n  m_calc->GetCollisionsCached(x, collisions);\n  PlotCollisions(collisions, env, handles, m_dist_pen);\n}\n\n// ALMOST EXACTLY COPIED FROM CollisionCost\n\nCollisionConstraint::CollisionConstraint(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars) :\n    m_calc(new SingleTimestepCollisionEvaluator(rad, vars)), m_dist_pen(dist_pen), m_coeff(coeff)\n{\n  name_=\"collision\";\n}\n\nCollisionConstraint::CollisionConstraint(double dist_pen, double coeff, ConfigurationPtr rad, const VarVector& vars0, const VarVector& vars1) :\n    m_calc(new CastCollisionEvaluator(rad, vars0, vars1)), m_dist_pen(dist_pen), m_coeff(coeff)\n{\n  name_=\"collision\";\n}\nConvexConstraintsPtr CollisionConstraint::convex(const vector<double>& x, Model* model) {\n  ConvexConstraintsPtr out(new ConvexConstraints(model));\n  vector<AffExpr> exprs;\n  m_calc->CalcDistExpressions(x, exprs);\n  for (int i=0; i < exprs.size(); ++i) {\n    AffExpr viol = exprSub(AffExpr(m_dist_pen), exprs[i]);\n    out->addIneqCnt(exprMult(viol,m_coeff));\n  }\n  return out;\n}\nDblVec CollisionConstraint::value(const vector<double>& x) {\n  DblVec dists;\n  m_calc->CalcDists(x, dists);\n  DblVec out(dists.size());\n  for (int i=0; i < dists.size(); ++i) {\n    out[i] = pospart(m_dist_pen - dists[i]) * m_coeff;\n  }\n  return out;\n}\n\n\n\n}\n", "meta": {"hexsha": "4b77e6b26d35b977908cde24453de3ebd7489536", "size": 9578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trajopt/collision_terms.cpp", "max_stars_repo_name": "HARPLab/trajopt", "max_stars_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 250.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:52:54.000Z", "max_issues_repo_path": "src/trajopt/collision_terms.cpp", "max_issues_repo_name": "HARPLab/trajopt", "max_issues_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-08-19T13:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:08:26.000Z", "max_forks_repo_path": "src/trajopt/collision_terms.cpp", "max_forks_repo_name": "HARPLab/trajopt", "max_forks_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 118.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T11:44:00.000Z", "avg_line_length": 35.872659176, "max_line_length": 170, "alphanum_fraction": 0.715598246, "num_tokens": 2740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.03904829636066302, "lm_q1q2_score": 0.016498086761865455}}
{"text": "// Edited by:\n//  @authors:     Ahmad Humayun\n//  @contact:     ahumayun@cc.gatech.edu\n//  @affiliation: Georgia Institute of Technology\n//  @date:        Fall 2013 - Summer 2014\n\n/* maxflow.cpp */\n\n#ifndef __MAXFLOWIMPL_HPP__\n#define __MAXFLOWIMPL_HPP__\n\n#include <stdio.h>\n#include <iostream>\n#include <boost/format.hpp>\n\n#include \"graph.h\"\n\nusing boost::format;\n\n\n/*\n\tspecial constants for node->parent. Duplicated in graph.cpp, both should match!\n*/\n#define TERMINAL ( (arc *) 1 )\t\t/* to terminal */\n#define ORPHAN   ( (arc *) 2 )\t\t/* orphan */\n\n\n#define INFINITE_D ((int)(((unsigned)-1)/2))\t\t/* infinite distance to the terminal */\n\n\n\n/*\n\tReturns the next active node.\n\tIf it is connected to the sink, it stays in the list,\n\totherwise it is removed from the list\n*/\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tinline typename Graph<captype,tcaptype,flowtype>::node* Graph<captype,tcaptype,flowtype>::next_active()\n{\n\tnode *i;\n\n\twhile ( 1 )\n\t{\n\t  // if the queue 0 is empty, swap with queue 1\n\t\tif (!(i=queue_first[0]))\n\t\t{\n\t\t\tqueue_first[0] = i = queue_first[1];\n\t\t\tqueue_last[0]  = queue_last[1];\n\t\t\tqueue_first[1] = NULL;\n\t\t\tqueue_last[1]  = NULL;\n\t\t\tif (!i) return NULL;\n\t\t}\n\n\t\t/* remove it from the active list */\n\t\tif (i->next == i) queue_first[0] = queue_last[0] = NULL;\n\t\telse              queue_first[0] = i -> next;\n\t\ti -> next = NULL;\n\n\t\t/* a node in the list is active iff it has a parent */\n\t\tif (i->parent) return i;\n\t}\n}\n\n/***********************************************************************/\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tinline void Graph<captype,tcaptype,flowtype>::set_orphan_front(node *i)\n{\n\tnodeptr *np;\n\ti -> parent = ORPHAN;\n\t//i -> src_origin_idx = INVALID_SRC_ID;\n\tnp = nodeptr_block -> New();\n\tnp -> ptr = i;\n\tnp -> next = orphan_first;\n\torphan_first = np;\n}\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tinline void Graph<captype,tcaptype,flowtype>::set_orphan_rear(node *i)\n{\n\tnodeptr *np;\n\ti -> parent = ORPHAN;\n\t//i -> src_origin_idx = INVALID_SRC_ID;\n\tnp = nodeptr_block -> New();\n\tnp -> ptr = i;\n\tif (orphan_last) orphan_last -> next = np;\n\telse             orphan_first        = np;\n\torphan_last = np;\n\tnp -> next = NULL;\n}\n\n/***********************************************************************/\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tinline void Graph<captype,tcaptype,flowtype>::add_to_changed_list(node *i)\n{\n\tif (changed_list && !i->is_in_changed_list)\n\t{\n\t\tnode_id* ptr = changed_list->New();\n\t\t*ptr = (node_id)(i - nodes);\n\t\ti->is_in_changed_list = true;\n\t}\n}\n\n/************************************************process_sink_orphan***********************/\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tvoid Graph<captype,tcaptype,flowtype>::maxflow_init()\n{\n\tnode *i;\n\n\tqueue_first[0] = queue_last[0] = NULL;\n\tqueue_first[1] = queue_last[1] = NULL;\n\torphan_first = NULL;\n\n\tTIME = 0;\n\n\tfor (i=nodes; i<node_last; i++)\n\t{\n\t\ti -> next = NULL;\n\t\ti -> is_marked = 0;\n\t\ti -> is_in_changed_list = 0;\n\t\ti -> TS = TIME;\n\t\tif (i->tr_cap > 0)\n\t\t{\n\t\t\t/* i is connected to the source */\n\t\t\ti -> is_sink = 0;\n\t\t\ti -> parent = TERMINAL;\n\t\t\tset_active(i);\n\t\t\ti -> DIST = 1;\n\t\t\tif (i -> src_origin_idx == INVALID_SRC_ID)\n\t\t\t  i -> src_origin_idx = 0;\n\t\t}\n\t\telse if (i->tr_cap < 0)\n\t\t{\n\t\t\t/* i is connected to the sink */\n\t\t\ti -> is_sink = 1;\n\t\t\ti -> parent = TERMINAL;\n\t\t\tset_active(i);\n\t\t\ti -> DIST = 1;\n\t\t\ti -> src_origin_idx = INVALID_SRC_ID;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/* i is free */\n\t\t\ti -> parent = NULL;\n\t\t\ti -> src_origin_idx = INVALID_SRC_ID;\n\t\t}\n\t}\n}\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tvoid Graph<captype,tcaptype,flowtype>::maxflow_reuse_trees_init()\n{\n\tnode* i;\n\tnode* j;\n\t// the queue would be checked from the second list\n\tnode* queue = queue_first[1];\n\tarc* a;\n\tnodeptr* np;\n\n\t// vacate all queues because they will rebuilt\n\tqueue_first[0] = queue_last[0] = NULL;\n\tqueue_first[1] = queue_last[1] = NULL;\n\torphan_first = orphan_last = NULL;\n\n\tTIME ++;\n\n\t// iterate over the whole active list (coming from the second list)\n\twhile ((i=queue))\n\t{\n\t  // de-queue the first node\n\t\tqueue = i->next;\n\t\t// if node was last in queue, set queue to NULL\n\t\tif (queue == i) queue = NULL;\n\t\t// disconnect the current node from the queue\n\t\ti->next = NULL;\n\t\ti->is_marked = 0;\n\t\t// add node to the second queue\n\t\tset_active(i);\n\n\t\t// in case node has no residual capacity to src/sink\n\t\tif (i->tr_cap == 0)\n\t\t{\n\t\t  // if the node has a parent, then set the node to orphan\n\t\t  // - this is a simple thing to do because you don't need to go up on the\n\t\t  //   tree to see if the root still belongs to the same src/sink this node\n\t\t  //   belongs to\n\t\t\tif (i->parent) set_orphan_rear(i);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (i->tr_cap > 0)\n\t\t{\n\t    // if node could be connected to src\n\n\t\t  // if node has no parent (neither is terminal or orphan) OR is is in the\n\t\t  // sink side of the cut\n\t\t\tif (!i->parent || i->is_sink)\n\t\t\t{\n\t\t\t  // assign node to src (because have residual cap to src)\n\t\t\t\ti->is_sink = 0;\n\t\t\t\tif (curr_src_origin_idx != INVALID_SRC_ID)\n\t\t\t\t  i->src_origin_idx = curr_src_origin_idx;\n\t\t\t\t// iterate over all the edges connected to this node\n\t\t\t\tfor (a=i->first; a; a=a->next)\n\t\t\t\t{\n\t\t\t\t\tj = a->head;\n\t\t\t\t\t// if not already marked (only marked by mark_node() - used to\n\t\t\t\t\t// indicate which parts of the tree have changed)\n\t\t\t\t\tif (!j->is_marked)\n\t\t\t\t\t{\n\t\t\t\t\t  // if neighboring node j is child of i, with edge going to i\n\t\t\t\t\t  //  (as a sink tree), then set to orphan\n\t\t\t\t\t\tif (j->parent == a->sister) set_orphan_rear(j);\n\t\t\t\t\t\t// if neighboring node is in sink and there is residual capacity to\n\t\t\t\t\t\t//  push flow, then set to active\n\t\t\t\t\t\tif (j->parent && j->is_sink && a->r_cap > 0) set_active(j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tadd_to_changed_list(i);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t  // if node could be connected to sink\n\n      // if node has no parent (neither is terminal or orphan) OR is in the\n      // src side of the cut\n\t\t\tif (!i->parent || !i->is_sink)\n\t\t\t{\n\t\t\t  // assign node to sink (because have residual cap to sink)\n\t\t\t\ti->is_sink = 1;\n\t\t\t\ti->src_origin_idx = INVALID_SRC_ID;\n\t\t\t\t// iterate over all the edges connected to this node\n\t\t\t\tfor (a=i->first; a; a=a->next)\n\t\t\t\t{\n\t\t\t\t\tj = a->head;\n\t\t\t\t\t// if not already marked\n\t\t\t\t\tif (!j->is_marked)\n\t\t\t\t\t{\n\t\t\t\t\t  // if neighboring node j is child of i, with edge going to i\n\t\t\t\t\t  //  (as a sink tree), then set to orphan\n\t\t\t\t\t\tif (j->parent == a->sister) set_orphan_rear(j);\n\t\t\t\t\t\t// if neighboring node is in src and there is residual capacity to\n            //  push flow, then set to active\n\t\t\t\t\t\tif (j->parent && !j->is_sink && a->sister->r_cap > 0) set_active(j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tadd_to_changed_list(i);\n\t\t\t}\n\t\t}\n\t\t// if set to src/sink - directly connect to terminal\n\t\ti -> parent = TERMINAL;\n\t\ti -> TS = TIME;\n\t\ti -> DIST = 1;\n\t}\n\n\t//test_consistency();\n\n\t/* adoption */\n\t// iterate over all orphans and try to adopt them into trees\n\twhile ((np=orphan_first))\n\t{\n\t\torphan_first = np -> next;\n\t\ti = np -> ptr;\n\t\tnodeptr_block -> Delete(np);\n\t\tif (!orphan_first) orphan_last = NULL;\n\t\tif (i->is_sink) process_sink_orphan(i);\n\t\telse            process_source_orphan(i);\n\t}\n\t/* adoption end */\n\n\t//test_consistency();\n}\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tvoid Graph<captype,tcaptype,flowtype>::augment(arc *middle_arc)\n{\n\tnode *i;\n\tarc *a;\n\ttcaptype bottleneck;\n\n\t/* 1. Finding bottleneck capacity */\n\t/* 1a - the source tree */\n\tbottleneck = middle_arc -> r_cap;\n\tfor (i=middle_arc->sister->head; ; i=a->head)\n\t{\n\t\ta = i -> parent;\n\t\tif (a == TERMINAL) break;\n\t\tif (bottleneck > a->sister->r_cap) bottleneck = a -> sister -> r_cap;\n\t\t//gassert(i->src_origin_idx != INVALID_SRC_ID, \"src_origin_idx needs to be src\");\n\n\t\t//if (i->parent->head->parent != TERMINAL && i->parent->head->parent != ORPHAN && i->parent->head->parent != NULL) {\n\t\t//  gassert(i->parent->head->parent->head != i, \"circular\");\n\t\t//}\n\t}\n\tif (bottleneck > i->tr_cap) bottleneck = i -> tr_cap;\n\t/* 1b - the sink tree */\n\tfor (i=middle_arc->head; ; i=a->head)\n\t{\n\t\ta = i -> parent;\n\t\tif (a == TERMINAL) break;\n\t\tif (bottleneck > a->r_cap) bottleneck = a -> r_cap;\n\n\t\t//gassert(i->src_origin_idx == INVALID_SRC_ID, \"src_origin_idx needs to be sink\");\n\t}\n\tif (bottleneck > - i->tr_cap) bottleneck = - i -> tr_cap;\n\t//gassert(bottleneck > 0, \"bottleneck should be positive\");\n\n\t/* 2. Augmenting */\n\t/* 2a - the source tree */\n\tmiddle_arc -> sister -> r_cap += bottleneck;\n\tmiddle_arc -> r_cap -= bottleneck;\n\tfor (i=middle_arc->sister->head; ; i=a->head)\n\t{\n\t\ta = i -> parent;\n\t\tif (a == TERMINAL) break;\n\t\ta -> r_cap += bottleneck;\n\t\ta -> sister -> r_cap -= bottleneck;\n\t\tif (!a->sister->r_cap)\n\t\t{\n\t\t\tset_orphan_front(i); // add i to the beginning of the adoption list\n\t\t}\n\t}\n\ti -> tr_cap -= bottleneck;\n\tif (!i->tr_cap)\n\t{\n\t\tset_orphan_front(i); // add i to the beginning of the adoption list\n\t}\n\t/* 2b - the sink tree */\n\tfor (i=middle_arc->head; ; i=a->head)\n\t{\n\t\ta = i -> parent;\n\t\tif (a == TERMINAL) break;\n\t\ta -> sister -> r_cap += bottleneck;\n\t\ta -> r_cap -= bottleneck;\n\t\tif (!a->r_cap)\n\t\t{\n\t\t\tset_orphan_front(i); // add i to the beginning of the adoption list\n\t\t}\n\t}\n\ti -> tr_cap += bottleneck;\n\tif (!i->tr_cap)\n\t{\n\t\tset_orphan_front(i); // add i to the beginning of the adoption list\n\t}\n\n\t++num_augmentations;\n\n\tflow += bottleneck;\n}\n\n/***********************************************************************/\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tvoid Graph<captype,tcaptype,flowtype>::process_source_orphan(node *i)\n{\n\tnode *j;\n\tarc *a0, *a0_min = NULL, *a;\n\tint d, d_min = INFINITE_D;\n\n\tif (i->tr_cap > 0) {\n\t  // if there is direct residual capacity to the src\n\t  a0_min = TERMINAL;\n\t  d_min = 0;\n\t} else {\n\t  // set node free if it has some children (i.e. don't attempt to adopt)\n\t  bool has_children = false;\n    for (a0=i->first; a0; a0=a0->next) {\n      j = a0 -> head;\n      if (j->parent && j->parent != TERMINAL && j->parent != ORPHAN) {\n        if (j->parent->head == i) {\n          has_children = true;\n          break;\n        }\n      }\n    }\n\n    /* trying to find a new parent */\n    for (a0=i->first; !has_children && a0; a0=a0->next) {\n      // if the reverse arc has residual capacity, it can possibly adopt\n      if (a0->sister->r_cap)\n      {\n        // j now is the node the arc points to\n        j = a0 -> head;\n        // if j is in src\n        if (!j->is_sink && (a=j->parent) &&\n            j->src_origin_idx == i->src_origin_idx)\n        {\n          /*\n          // if the arc points to something that is a child\n          if (j->parent != TERMINAL && j->parent != ORPHAN) {\n            if (j->parent->head == i)\n              break;\n          }*/\n          // checking the origin of j\n          d = 0;\n          while ( 1 )\n          {\n            // if the timing is up to date, find the distance terminal\n            if (j->TS == TIME)\n            {\n              d += j -> DIST;\n              break;\n            }\n            // if the time stamp was old, then keep moving up on the tree\n            a = j -> parent;\n            d ++;\n            if (a==TERMINAL)\n            {\n              j -> TS = TIME;\n              j -> DIST = 1;\n              break;\n            }\n            if (a==ORPHAN) { d = INFINITE_D; break; }\n            j = a -> head;\n          }\n          if (d<INFINITE_D) // if j is on a path at some distance from src\n          {\n            if (d<d_min)\n            {\n              a0_min = a0;\n              d_min = d;\n            }\n            /* set marks along the path */\n            for (j=a0->head; j->TS!=TIME; j=j->parent->head)\n            {\n              j -> TS = TIME;\n              j -> DIST = d --;\n            }\n          }\n        }\n      }\n    }\n\t}\n\n\tif (i->parent = a0_min)\n\t{\n\t\ti -> TS = TIME;\n\t\ti -> DIST = d_min + 1;\n\n\t\t++num_adoptions;\n\t}\n\telse\n\t{\n\t  i -> src_origin_idx = INVALID_SRC_ID;\n\n\t\t/* no parent is found */\n\t\tadd_to_changed_list(i);\n\n\t\t/* make sure now its source id is set to default null value */\n\t\ti->src_origin_idx = INVALID_SRC_ID;\n\n\t\t/* process neighbors */\n\t\tfor (a0=i->first; a0; a0=a0->next)\n\t\t{\n\t\t\tj = a0 -> head;\n\t\t\tif (!j->is_sink && (a=j->parent))\n\t\t\t{\n\t\t\t\tif (a0->sister->r_cap) set_active(j);\n\t\t\t\tif (a!=TERMINAL && a!=ORPHAN && a->head==i)\n\t\t\t\t{\n\t\t\t\t\tset_orphan_rear(j); // add j to the end of the adoption list\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tvoid Graph<captype,tcaptype,flowtype>::process_sink_orphan(node *i)\n{\n\tnode *j;\n\tarc *a0, *a0_min = NULL, *a;\n\tint d, d_min = INFINITE_D;\n\n  if (i->tr_cap < 0) {\n    // if there is direct residual capacity to the sink\n    a0_min = TERMINAL;\n    d_min = 0;\n  } else {\n    // set node free if it has some children (i.e. don't attempt to adopt)\n    bool has_children = false;\n    for (a0=i->first; a0; a0=a0->next) {\n      j = a0 -> head;\n      if (j->parent && j->parent != TERMINAL && j->parent != ORPHAN) {\n        if (j->parent->head == i) {\n          has_children = true;\n          break;\n        }\n      }\n    }\n\n    /* trying to find a new parent */\n    for (a0=i->first; !has_children && a0; a0=a0->next) {\n      // if the arc has residual capacity, it can possibly adopt\n      if (a0->r_cap)\n      {\n        // j now is the node the arc points to\n        j = a0 -> head;\n        if (j->is_sink && (a=j->parent))\n        {\n          /*\n          // if the arc points to something that is a child\n          if (j->parent != TERMINAL && j->parent != ORPHAN) {\n            if (j->parent->head == i)\n              break;\n          }*/\n          /* checking the origin of j */\n          d = 0;\n          while ( 1 )\n          {\n            // if the timing is up to date, find the distance terminal\n            if (j->TS == TIME)\n            {\n              d += j -> DIST;\n              break;\n            }\n            // if the time stamp was old, then keep moving up on the tree\n            a = j -> parent;\n            d ++;\n            if (a==TERMINAL)\n            {\n              j -> TS = TIME;\n              j -> DIST = 1;\n              break;\n            }\n            if (a==ORPHAN) { d = INFINITE_D; break; }\n            j = a -> head;\n          }\n          if (d<INFINITE_D) // if j is on a path at some distance from sink\n          {\n            if (d<d_min)\n            {\n              a0_min = a0;\n              d_min = d;\n            }\n            /* set marks along the path */\n            for (j=a0->head; j->TS!=TIME; j=j->parent->head)\n            {\n              j -> TS = TIME;\n              j -> DIST = d --;\n            }\n          }\n        }\n      }\n    }\n\t}\n\n\tif (i->parent = a0_min)\n\t{\n\t\ti -> TS = TIME;\n\t\ti -> DIST = d_min + 1;\n\n\t\t++num_adoptions;\n\t}\n\telse\n\t{\n\t  i -> src_origin_idx = INVALID_SRC_ID;\n\n\t\t/* no parent is found */\n\t\tadd_to_changed_list(i);\n\n\t\t/* process neighbors */\n\t\tfor (a0=i->first; a0; a0=a0->next)\n\t\t{\n\t\t\tj = a0 -> head;\n\t\t\tif (j->is_sink && (a=j->parent))\n\t\t\t{\n\t\t\t\tif (a0->r_cap) set_active(j);\n\t\t\t\tif (a!=TERMINAL && a!=ORPHAN && a->head==i)\n\t\t\t\t{\n\t\t\t\t\tset_orphan_rear(j); // add j to the end of the adoption list\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n/***********************************************************************/\n\ntemplate <typename captype, typename tcaptype, typename flowtype> \n\tflowtype Graph<captype,tcaptype,flowtype>::maxflow(bool reuse_trees, Block<node_id>* _changed_list, bool run_init_func)\n{\n\tnode *i, *j, *current_node = NULL;\n\tarc *a;\n\tnodeptr *np, *np_next;\n\n\tif (!nodeptr_block)\n\t{\n\t\tnodeptr_block = new DBlock<nodeptr>(NODEPTR_BLOCK_SIZE, error_function);\n\t}\n\n\t// initialize the counters\n\tnum_growths = 0;\n\tnum_augmentations = 0;\n\tnum_adoptions = 0;\n\n\tchanged_list = _changed_list;\n\tif (maxflow_iteration == 0 && reuse_trees) { if (error_function) (*error_function)(\"reuse_trees cannot be used in the first call to maxflow()!\"); exit(1); }\n\tif (changed_list && !reuse_trees) { if (error_function) (*error_function)(\"changed_list cannot be used without reuse_trees!\"); exit(1); }\n\n\tif (run_init_func) {\n\t    if (reuse_trees) maxflow_reuse_trees_init();\n\t    else             maxflow_init();\n\t}\n\n\t// main loop\n\twhile ( 1 )\n\t{\n\t\t// test_consistency(current_node);\n\n\t\tif ((i=current_node))\n\t\t{\n\t\t\ti -> next = NULL; /* remove active flag */\n\t\t\tif (!i->parent) i = NULL;\n\t\t}\n\t\tif (!i)\n\t\t{\n\t\t  /* get the next active node (and remove from the active list)\n\t\t   * - when no active nodes remaining, the algorithm ends\n\t\t   */\n\t\t\tif (!(i = next_active())) break;\n\t\t}\n\n\t\t/* growth */\n\t\tif (!i->is_sink)\n\t\t{\n\t\t\t/* grow source tree */\n\t\t  /* iterate over all the edges coming out of this active node */\n\t\t\tfor (a=i->first; a; a=a->next) {\n\t\t\t  /* if the edge has a residual capacity, it can potentially become part of the S tree */\n        if (a->r_cap)\n        {\n          j = a -> head;\n          /* in case the terminus node of the arc is free, add to S tree (and\n           * set newly added node to active) */\n          if (!j->parent)\n          {\n            j -> is_sink = 0;\n            j -> parent = a -> sister;\n            j -> TS = i -> TS;\n            j -> DIST = i -> DIST + 1;\n            j -> src_origin_idx = i ->src_origin_idx;\n            set_active(j);\n            add_to_changed_list(j);\n            ++num_growths;\n          }\n          /* if arc connects S tree to T tree, an augmenting path has been found */\n          else if (j->is_sink)\n            break;\n          else if (j->TS <= i->TS &&\n                   j->DIST > i->DIST &&\n                   j -> src_origin_idx == i -> src_origin_idx)\n          {\n            /* heuristic - trying to make the distance from j to the source shorter */\n            j -> parent = a -> sister;\n            j -> TS = i -> TS;\n            j -> DIST = i -> DIST + 1;\n          }\n        }\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/* grow sink tree */\n\t\t  /* iterate over all the edges coming out of this active node */\n\t\t\tfor (a=i->first; a; a=a->next) {\n\t\t\t  /* if the reverse edge has a residual capacity, it can potentially become part of the T tree */\n        if (a->sister->r_cap)\n        {\n          j = a -> head;\n          /* in case the terminus node of the arc is free, add to T tree (and\n           * set newly added node to active) */\n          if (!j->parent)\n          {\n            j -> is_sink = 1;\n            j -> parent = a -> sister;\n            j -> TS = i -> TS;\n            j -> DIST = i -> DIST + 1;\n            set_active(j);\n            add_to_changed_list(j);\n            ++num_growths;\n          }\n          /* if arc connects T tree to S tree, an augmenting path has been found */\n          else if (!j->is_sink) {\n            /* set arc to the reverse edge (which we checked has residual capacity) */\n            a = a -> sister;\n            break;\n          }\n          else if (j->TS <= i->TS &&\n                   j->DIST > i->DIST)\n          {\n            /* heuristic - trying to make the distance from j to the sink shorter */\n            j -> parent = a -> sister;\n            j -> TS = i -> TS;\n            j -> DIST = i -> DIST + 1;\n          }\n        }\n\t\t\t}\n\t\t}\n\n\t\tTIME ++;\n\n\t\t/* if we found an augmenting path */\n\t\tif (a)\n\t\t{\n\t\t\ti -> next = i; /* set active flag */\n\t\t\tcurrent_node = i;\n\n\t\t\t/* augmentation */\n\t\t\taugment(a);\n\t\t\t/* augmentation end */\n\n\t\t\t/* adoption - adopt all orphans or set them free */\n\t\t\twhile ((np=orphan_first))\n\t\t\t{\n\t\t\t\tnp_next = np -> next;\n\t\t\t\tnp -> next = NULL;\n\n\t\t\t\twhile ((np=orphan_first))\n\t\t\t\t{\n\t\t\t\t\torphan_first = np -> next;\n\t\t\t\t\ti = np -> ptr;\n\t\t\t\t\tnodeptr_block -> Delete(np);\n\t\t\t\t\tif (!orphan_first) orphan_last = NULL;\n\t\t\t\t\tif (i->is_sink) process_sink_orphan(i);\n\t\t\t\t\telse            process_source_orphan(i);\n\t\t\t\t}\n\n\t\t\t\torphan_first = np_next;\n\t\t\t}\n\t\t\t/* adoption end */\n\t\t}\n\t\telse current_node = NULL;\n\t}\n\n\t// test_consistency();\n\n\tif (!reuse_trees || (maxflow_iteration % 64) == 0)\n\t{\n\t\tdelete nodeptr_block; \n\t\tnodeptr_block = NULL; \n\t}\n\n\tmaxflow_iteration ++;\n\treturn flow;\n}\n\n/***********************************************************************/\n\n\ntemplate <typename captype, typename tcaptype, typename flowtype>\n\tvoid Graph<captype,tcaptype,flowtype>::test_consistency(node* current_node) const\n{\n  std::cout << \"Checking tree consistency\" << std::endl;\n\n\tnode *i;\n\tarc *a;\n\tint r;\n\tint num1 = 0, num2 = 0;\n\n\t// test whether all nodes i with i->next!=NULL are indeed in the queue\n\tfor (i=nodes; i<node_last; i++)\n\t{\n\t\tif (i->next || i==current_node) num1 ++;\n\t}\n\tfor (r=0; r<3; r++)\n\t{\n\t\ti = (r == 2) ? current_node : queue_first[r];\n\t\tif (i)\n\t\tfor ( ; ; i=i->next)\n\t\t{\n\t\t\tnum2 ++;\n\t\t\tif (i->next == i)\n\t\t\t{\n\t\t\t  // check if the last node is also indicated by queue_last\n\t\t\t\tif (r<2) gassert(i == queue_last[r], \"i != queue_last[r]\");\n\t\t\t\telse gassert(i == current_node, \"i != current_node\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tgassert(num1 == num2, \"num1 != num2\");\n\n\tfor (i=nodes; i<node_last; i++)\n\t{\n    node_id nid = (node_id)(i - nodes);\n\n\t\t// test whether all edges in search trees are non-saturated\n    if (i->parent == NULL) {\n      // if node is free\n\t\t  gassert(i->tr_cap == 0,\n\t\t          (format(\"free node %d cannot have any tr cap\") % nid).str());\n\t\t  gassert(i->src_origin_idx == INVALID_SRC_ID,\n\t\t          (format(\"free node %d cannot have src id\") % nid).str());\n\t\t}\n\t\telse if (i->parent == ORPHAN) {}\n\t\telse if (i->parent == TERMINAL)\n\t\t{\n\t\t  // if node is terminal, it should have appropriate residual\n\t\t  if (!i->is_sink) {\n\t\t\t  gassert(i->tr_cap > 0,\n\t\t\t          (format(\"src node %d has <= 0 tr cap\") % nid).str());\n\t\t\t  gassert(i->src_origin_idx != INVALID_SRC_ID,\n\t\t\t          (format(\"src node %d INVALID_SRC_ID\") % nid).str());\n\t\t  } else {\n\t\t\t  gassert(i->tr_cap < 0,\n\t\t\t          (format(\"sink node %d has >= 0 tr cap\") % nid).str());\n        gassert(i->src_origin_idx == INVALID_SRC_ID,\n                (format(\"sink node %d not INVALID_SRC_ID\") % nid).str());\n\t\t  }\n\t\t}\n\t\telse\n\t\t{\n\t\t  node_id pid = (node_id)(i - nodes);\n\n\t\t  // if the node has a parent\n\t\t\tif (!i->is_sink) {\n        gassert(i->tr_cap >= 0,\n                (format(\"src node %d has < 0 tr cap\") % nid).str());\n        gassert(i->parent->head->src_origin_idx == i->src_origin_idx,\n                (format(\"src node %d doesn't have same src id as parent %d (%d %d)\") % nid % (node_id)(i->parent->head-nodes) % i->src_origin_idx % i->parent->head->src_origin_idx).str());\n\t\t\t  gassert(i->parent->sister->r_cap > 0,\n\t\t\t          (format(\"src node %d connected to the parent %d with <= 0 residual cap arc\") % nid % pid).str());\n\t\t\t} else {\n\t\t\t  gassert(i->tr_cap <= 0,\n                (format(\"sink node %d has > 0 tr cap\") % nid).str());\n        gassert(i->src_origin_idx == INVALID_SRC_ID,\n                (format(\"sink node %d doesn't have INVALID_SRC_ID\") % nid).str());\n\t\t\t  gassert(i->parent->r_cap > 0,\n\t\t\t          (format(\"sink node %d connected to the parent %d with <= 0 residual cap arc\") % nid % pid).str());\n\t\t\t}\n\t\t}\n\n\t\t// test whether passive nodes in search trees have neighbors in\n\t\t// a different tree through non-saturated edges\n\t\tif (i->parent && !i->next)\n\t\t{\n\t\t\tif (!i->is_sink)\n\t\t\t{\n\t\t\t\tfor (a=i->first; a; a=a->next)\n\t\t\t\t{\n\t\t\t\t\tif (a->r_cap > 0) {\n\t\t\t\t\t  gassert(a->head->parent != NULL && a->head->parent != ORPHAN,\n\t\t\t\t\t          \"src passive node cannot have a remaining residual \"\n\t\t\t\t\t          \"connection to a null or an orphan node\");\n            gassert(!a->head->is_sink, \"src passive node cannot have a \"\n                    \"remaining residual connection to a sink node\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (a=i->first; a; a=a->next)\n\t\t\t\t{\n\t\t\t\t\tif (a->sister->r_cap > 0) {\n\t\t\t\t\t  gassert(a->head->parent != NULL && a->head->parent != ORPHAN,\n\t\t\t\t\t          \"sink passive node cannot have a remaining residual \"\n\t\t\t\t\t          \"connection to a null or an orphan node\");\n            gassert(a->head->is_sink, \"sink passive node cannot have a \"\n                    \"remaining residual connection to a src node\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// test marking invariants\n\t\tif (i->parent && i->parent!=ORPHAN && i->parent!=TERMINAL)\n\t\t{\n\t\t  gassert(i->TS <= i->parent->head->TS, \"i->TS > i->parent->head->TS\");\n\n\t\t\tif (i->TS == i->parent->head->TS)\n\t\t\t  gassert(i->DIST > i->parent->head->DIST,\n\t\t\t          (format(\"%d->DIST <= (PARENT)%d->DIST\")\n\t\t\t              % (node_id)(i-nodes) % (node_id)(i->parent->head-nodes)).str());\n\t\t}\n\t}\n}\n\n#endif", "meta": {"hexsha": "682801ff7d8c052c0fc0e569ecc7d6f383a6fd33", "size": 24350, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/maxflow-impl.hpp", "max_stars_repo_name": "ajmalk/RIGOR-cpp", "max_stars_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maxflow-impl.hpp", "max_issues_repo_name": "ajmalk/RIGOR-cpp", "max_issues_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/maxflow-impl.hpp", "max_forks_repo_name": "ajmalk/RIGOR-cpp", "max_forks_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_forks_repo_licenses": ["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.6077097506, "max_line_length": 188, "alphanum_fraction": 0.5459958932, "num_tokens": 7093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.03963883952640863, "lm_q1q2_score": 0.016446108768230275}}
{"text": " /*!\n  * @file   swp_birth_process.cpp\n  * @author Matthew Celnik, William Menz\n  * @brief  Implementation of a birth process\n  *\n  *   Licence:\n  *      mops 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 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 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 program; if not, write to the Free Software\n  *      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n  *      02111-1307, USA.\n  *\n  *   Contact:\n  *      Prof Markus Kraft\n  *      Dept of Chemical Engineering\n  *      University of Cambridge\n  *      New Museums Site\n  *      Pembroke Street\n  *      Cambridge\n  *      CB2 3RA, UK\n  *\n  *      Email:       mk306@cam.ac.uk\n  *      Website:     http://como.cheng.cam.ac.uk\n  */\n\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include \"swp_birth_process.h\"\n#include \"swp_mechanism.h\"\n#include <stdexcept>\n\nusing namespace Sweep;\nusing namespace Sweep::Processes;\nusing namespace std;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (protected).\nBirthProcess::BirthProcess(void)\n: m_cell(NULL),\n  m_btype(BirthProcess::iStochastic),\n  m_on(true)\n{\n    m_name = \"Birth Process\";\n}\n\n/*!\n * Initialising constructor\n *\n * @param mech  The mechanism defining the process\n * @return      A new BirthProcess\n */\nBirthProcess::BirthProcess(const Sweep::Mechanism &mech)\n: Process(mech),\n  m_cell(NULL),\n  m_btype(BirthProcess::iStochastic),\n  m_on(true)\n{\n    m_name = \"Birth Process\";\n}\n\n/*!\n * Copy constructor\n *\n * @param copy  Process to copy\n * @return      A new BirthProcess, copy of the original\n */\nBirthProcess::BirthProcess(const BirthProcess &copy)\n: m_cell(copy.m_cell)\n{\n    *this = copy;\n}\n\n// OPERATOR OVERLOADS.\n\n// Assignment operator.\nBirthProcess &BirthProcess::operator =(const BirthProcess &rhs)\n{\n    if (this != &rhs) {\n        Process::operator =(rhs);\n        // Copy pointer to sampling ensemble.\n        m_cell = rhs.m_cell;\n        m_btype = rhs.m_btype;\n        m_on = rhs.m_on;\n    }\n    return *this;\n}\n\n//! Set the Cell from which this process samples.\nvoid BirthProcess::SetCell(Cell* c) {\n    m_cell = c;\n}\n\n//! Sets the birth process type\nvoid BirthProcess::SetBirthType(const BirthType t) {\n    m_btype = t;\n}\n\n//! Turn the process on or off\nvoid BirthProcess::SetProcessSwitch(const bool s) {\n    m_on = s;\n}\n\n\n// INFORMATION FOR THE SOLVER\n// Does the Cell inflow have particles present?\nbool BirthProcess::HasParticlesInCell() const {\n    if ((m_cell->Particles().Count() + m_cell->Particles().GetTotalParticleNumber())>0u) return true;\n    else return false;\n}\n\n// TOTAL RATE CALCULATIONS.\n\n/*!\n * Weights are scaled by this quantity when particles move from cell to cell.\n *\n * @param sys   System to evaluate scaling factor for\n * @return      The cell-transfer scaling factor\n */\ndouble BirthProcess::F(const Cell &sys) const {\n    return sys.SampleVolume() / m_cell->SampleVolume();\n}\n\n/*!\n *@param[in]            t           Time at which rate is being calculated\n *@param[in]            sys         System for which rate is to be calculated\n *@param[in]            local_geom  Spatial configuration information (ignored)\n *\n *@return   Process rate\n */\ndouble BirthProcess::Rate(double t, const Cell &sys,\n                        const Geometry::LocalGeometry1d &local_geom) const\n\n{\n    if (m_btype == BirthProcess::iStochastic && m_on) {\n        return InternalRate(t, sys, local_geom);\n    }\n    return 0.0;\n}\n\n/*!\n *@param[in]            t           Time at which rate is being calculated\n *@param[in]            sys         System for which rate is to be calculated\n *@param[in]            local_geom  Spatial configuration information (ignored)\n *\n *@return   Process rate\n */\ndouble BirthProcess::InternalRate(\n        double t,\n        const Cell &sys,\n        const Geometry::LocalGeometry1d &local_geom) const {\n    if (m_cell == NULL) throw runtime_error(\"No cell specified for sampling.\"\n                \" (Sweep, BirthProcess::InternalRate)\");\n    unsigned int n_total = m_cell->Particles().Count() + m_cell->Particles().GetTotalParticleNumber();\n    return A() * (double)n_total;\n}\n\n// RATE TERM CALCULATIONS.\n\n// Returns the number of rate terms for this process (one).\nunsigned int BirthProcess::TermCount(void) const {return 1;}\n\n/*!\n *\n * @param t             Time at which rate is being calculated\n * @param sys           System for which rate is to be calculated\n * @param local_geom    Spatial configuration information (ignored)\n * @param iterm         Iterator on rates vector\n * @return              Rate of birth process\n */\ndouble BirthProcess::RateTerms(const double t, const Cell &sys,\n                             const Geometry::LocalGeometry1d &local_geom,\n                             fvector::iterator &iterm) const\n{\n    *iterm = Rate(t, sys, local_geom);\n    return *(iterm++);\n}\n\n// PERFORMING THE PROCESS.\n\n/*!\n * \\param[in]       t           Time\n * \\param[in,out]   sys         System to update\n * \\param[in]       local_geom  Details of local phsyical layout\n * \\param[in]       iterm       Process term responsible for this event\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      0 on success, otherwise negative.\n */\nint BirthProcess::Perform(double t, Sweep::Cell &sys, \n                          const Geometry::LocalGeometry1d& local_geom,\n                          unsigned int iterm,\n                          rng_type &rng) const\n{\n    if (m_cell == NULL)\n        throw runtime_error(\"No cell specified for sampling.\"\n            \" (Sweep, BirthProcess::Perform)\");\n\n    int i = 0;\n    // If all particles in ensemble, select a particle at random\n    if (!(m_mech->IsHybrid()))\n        i = m_cell->Particles().Select(rng);\n    else\n    {\n        // Select a particle from the ensemble or particle-number list\n        // ===========================================================\n        // Get totals\n        double ntotal_pn = (double)(m_cell->Particles().GetTotalParticleNumber());\n        double ntotal_ens = (double)(m_cell->ParticleCount());\n\n        // Here there should be a check that the index chosen is smaller than the threshold size\n        // because nothing stops the stream having a larger threshold size than current system.\n        // In that instance, particles could be added to the ensemble like with surface growth. \n        // However this cannot be done here easily because it requires construction of a new particles. \n        // Print warning message.\n        if (m_cell->Particles().GetHybridThreshold() > sys.Particles().GetHybridThreshold())\n            printf(\"sweep: Mixture PN threshold > reactor PN threshold; \"\n\t           \"could inflow particle that cannot be stored\\n\");\n\n        // Select the particle\n        boost::uniform_01<rng_type&, double> unifDistrib(rng);\n        double test = unifDistrib() * (ntotal_pn + ntotal_ens);\n        if (ntotal_pn >= test)\n        {\n            // Particle is chosen from the number list\n            double repeats = F(sys);\n            if (repeats != floor(repeats)) \n            {\n                boost::random::bernoulli_distribution<double> decider(repeats);\n                repeats = floor(repeats);\n                if (decider(rng))\n                    repeats += 1.0;\n            }\n            if (repeats > 0.0)\n            {\n                unsigned int index = m_mech->SetRandomParticle(m_cell->Particles(), t, test, iUniform, rng);\n\t\t// Check we found a valid index\n                if (index > 0)\n\t\t{\n\t\t    sys.Particles().UpdateTotalsWithIndex(index, repeats);\n\t\t    sys.Particles().UpdateNumberAtIndex(index, (int)repeats);\n\t\t    sys.Particles().UpdateTotalParticleNumber((int)repeats);\n\t\t}\n            }\n            i = -1;\n        }\n        else\n        {\n            // Particle is chosen from the ensemble\n            i = m_cell->Particles().Select_usingGivenRand(iUniform, test - ntotal_pn, rng);\n        }\n\n    }\n    if (i >= 0)\n    {\n        DoParticleBirth(t, i, sys,\n        m_cell->Particles().At(i)->getStatisticalWeight() * F(sys),\n        rng);\n    }\n    // ===========================================================\n\n    return 0;\n}\n\n/*!\n * Create particles over time dt.\n *\n * @param t     Current time of the system\n * @param dt    Time to remove particles over\n * @param sys   The system to do transport for\n * @param local_geom    Geometry of the system\n * @param rng   Random number generator\n */\nvoid BirthProcess::PerformDT (\n        double t,\n        double dt,\n        Sweep::Cell &sys,\n        const Geometry::LocalGeometry1d& local_geom,\n        rng_type &rng) const {\n\n    if (m_btype == BirthProcess::iContinuous) {\n\n        Process::PerformDT(dt, t, sys, local_geom, rng);\n\n        // Get the rate, and do n times like a LPDA process\n        double rate = InternalRate(t, sys, local_geom) * dt;\n        if (rate > 0.0) {\n            boost::random::poisson_distribution<unsigned, double> rpt(rate);\n            unsigned num = rpt(rng);\n            while (num > 0) {\n                // Do the process to the particle.\n                Perform(t, sys, local_geom, 0, rng);\n                num--;\n            }\n        }\n\n    }\n    // Don't do anything for the iStochastic case, as the Perform() will be called\n    // in the usual manner for jump processes.\n\n}\n\n/*!\n * Create the particle in this system's cell.\n *\n * @param t     Time to create particle at\n * @param isp   Index of particle to clone\n * @param sys   System to put particle into\n * @param wt    Weight of the particle\n * @param rng   Random number generator\n */\nvoid BirthProcess::DoParticleBirth(\n        const double t,\n        const int isp,\n        Sweep::Cell &sys,\n        const double wt,\n        rng_type &rng) const {\n\n    // Get reference to a particle.\n    Sweep::Particle *sp = m_cell->Particles().At(isp)->Clone();\n\n    // Reset some properties\n    sp->resetCoagCount();\n    sp->resetFragCount();\n    sp->SetTime(t);     // Set LPDA update time.\n\n    // Note that we could just adjust the weight of isp and add it (SWAs only),\n    // but this makes the ensemble more sensitive to depletion for very\n    // downstream reactors.\n\n    double repeats = F(sys);\n    int counter(-1);\n    while (repeats > 0.0) {\n        if (repeats >= 1.0) sys.Particles().Add(*(sp->Clone()), rng);\n        else {\n            boost::random::bernoulli_distribution<double> decider(repeats);\n            if (decider(rng))\n                counter = sys.Particles().Add(*sp, rng);\n        }\n        repeats -= 1.0;\n    }\n\n    // Delete the particle copy if it wasn't added by the decider\n    if (counter < 0) delete sp;\n\n}\n\n// READ/WRITE/COPY.\n\n// Creates a copy of the inception.\nBirthProcess *const BirthProcess::Clone(void) const {return new BirthProcess(*this);}\n\n// Returns the process type.  Used to identify different\n// processes and for serialisation.\nProcessType BirthProcess::ID(void) const {return Birth_ID;}\n\n", "meta": {"hexsha": "35c16eb08d8106e6f6602604c3ea3844cbdddd99", "size": 11437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_birth_process.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_birth_process.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_birth_process.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 31.2486338798, "max_line_length": 108, "alphanum_fraction": 0.6143219376, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.03789242934583516, "lm_q1q2_score": 0.016444612547281138}}
{"text": "/*\n * Copyright (c) 2019 Opticks Team. All Rights Reserved.\n *\n * This file is part of Opticks\n * (see https://bitbucket.org/simoncblyth/opticks).\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 <cstdio>\n#include <cmath>  \n\n//#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/constants/constants.hpp>\n#include \"BStr.hh\"\n\n#include \"NGLM.hpp\"\n\n#include \"PLOG.hh\"\n\n// npy-\n#include \"GLMPrint.hpp\"\n#include \"GLMFormat.hpp\"\n\n#include \"Trackball.hh\"\n\nconst plog::Severity Trackball::LEVEL = debug ; \n\n\nconst char* Trackball::PREFIX = \"trackball\" ;\nconst char* Trackball::getPrefix()\n{\n   return PREFIX ; \n}\n\n\nconst char* Trackball::RADIUS = \"radius\" ;\nconst char* Trackball::ORIENTATION = \"orientation\" ;\nconst char* Trackball::TRANSLATE = \"translate\" ;\nconst char* Trackball::TRANSLATEFACTOR = \"translatefactor\" ;\n\n\n\nstd::vector<std::string> Trackball::getTags()\n{\n    std::vector<std::string> tags ;\n    tags.push_back(RADIUS);\n    tags.push_back(ORIENTATION);\n    tags.push_back(TRANSLATE);\n    tags.push_back(TRANSLATEFACTOR);\n    return tags ; \n}\n\n\nfloat Trackball::getTranslationMin()\n{\n    return -m_translate_max ; \n}\n\nfloat Trackball::getTranslationMax()\n{\n    return m_translate_max ; \n}\n\n\nfloat* Trackball::getRadiusPtr()\n{\n    return &m_radius ;\n}\nfloat Trackball::getRadiusMin()\n{\n    return m_radius_clip[0] ; \n}\nfloat Trackball::getRadiusMax()\n{\n    return m_radius_clip[1] ; \n}\n\n\n\nfloat* Trackball::getTFactorPtr()\n{\n    return &m_translatefactor ;\n}\nfloat Trackball::getTFactorMin()\n{\n    return m_translatefactor_clip[0] ; \n}\nfloat Trackball::getTFactorMax()\n{\n    return m_translatefactor_clip[1] ; \n}\n\n\n\n\n\n\n\nTrackball::Trackball() :\n          m_radius(1.f),\n          m_translatefactor(1000.f),\n          m_drag_renorm(97),\n          m_drag_count(0),\n          m_changed(true)\n{\n    home();\n\n    setTranslateMax(1e5);\n    setRadiusClip(0.1f, 10.f);\n    setTranslateFactorClip(10.f, 1e6);\n}\n\n\nvoid Trackball::setTranslateMax(float _max)\n{\n    m_translate_max = _max ; \n}\n\nvoid Trackball::setRadiusClip(float _min, float _max)\n{\n    m_radius_clip[0] = _min ;  \n    m_radius_clip[1] = _max ;  \n}\n\nvoid Trackball::setTranslateFactorClip(float _min, float _max)\n{\n    m_translatefactor_clip[0] = _min ;  \n    m_translatefactor_clip[1] = _max ;  \n}\n\n\nfloat Trackball::getRadius()\n{\n    return m_radius ; \n}\nfloat Trackball::getTranslateFactor()\n{\n    return m_translatefactor  ; \n}\n\n\nvoid Trackball::setRadius(float r)\n{\n    m_radius = r ; \n    m_changed = true ; \n}\nvoid Trackball::setTranslateFactor(float tf)\n{\n    m_translatefactor = tf ; \n    m_changed = true ; \n}\nvoid Trackball::setTranslate(float x, float y, float z)\n{\n    m_translate.x = x;\n    m_translate.y = y;\n    m_translate.z = z;\n    m_changed = true ; \n}\n \nvoid Trackball::home()\n{\n    m_translate.x = 0.f ; \n    m_translate.y = 0.f ; \n    m_translate.z = 0.f ; \n    setOrientation(0.f, 0.f);\n    m_changed = true ; \n}\nvoid Trackball::zoom_to(float , float , float , float dy)\n{\n    m_translate.z += dy*m_translatefactor ;\n    m_changed = true ; \n} \nvoid Trackball::pan_to(float , float , float dx, float dy)\n{\n    m_translate.x += dx*m_translatefactor ;\n    m_translate.y += dy*m_translatefactor ;\n    m_changed = true ; \n} \n\nbool Trackball::hasChanged()\n{\n    return m_changed ; \n}\nvoid Trackball::setChanged(bool changed)\n{\n    m_changed = changed ; \n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nglm::vec3 Trackball::getTranslation()\n{\n    return m_translate;\n}\n\nfloat* Trackball::getTranslationPtr()\n{\n    return glm::value_ptr(m_translate);\n}\n\nfloat* Trackball::getOrientationPtr()\n{\n    return glm::value_ptr(m_orientation);\n}\n\nstd::string Trackball::getOrientationString()\n{\n    return gformat(m_orientation) ;\n}\n\n\n\nglm::mat4 Trackball::getTranslationMatrix()\n{\n    return glm::translate(  glm::mat4(1.0f), m_translate);\n}\n\nglm::mat4 Trackball::getCombinedMatrix()\n{\n    // http://stackoverflow.com/questions/9920624/glm-combine-rotation-and-translation\n    //\n    // glm::translate,  translates before rotates\n    //\n    //        rot * trans;\n    //\n\n    return glm::translate( getOrientationMatrix(), m_translate);\n}\n\nvoid Trackball::getCombinedMatrices(glm::mat4& rt, glm::mat4& rti)\n{\n    glm::mat4 rot  = getOrientationMatrix();  \n    glm::mat4 irot = glm::transpose(rot);\n\n    glm::mat4 tra(glm::translate(m_translate));  \n    glm::mat4 itra(glm::translate(-m_translate));  \n\n    rt = rot * tra  ;    // translates then rotate\n\n    rti = itra * irot ;  //    \n\n    //  rti * rt = itra * irot * rot * tra = identity \n    //\n\n} \n\nvoid Trackball::getOrientationMatrices(glm::mat4& rot, glm::mat4& irot)\n{\n    rot  = getOrientationMatrix();  \n    irot = glm::transpose(rot);\n} \n\nvoid Trackball::getTranslationMatrices(glm::mat4& tra, glm::mat4& itra)\n{\n    tra = glm::translate(m_translate);  \n    itra = glm::translate(-m_translate);  \n} \n\n\n\nvoid Trackball::configureI(const char* , std::vector<int> )\n{\n}\n\n\n\nvoid Trackball::configureF(const char* name, std::vector<float> values)\n{\n     if(values.empty())\n     {\n         printf(\"Trackball::configureF %s no values \\n\", name);\n     }\n     else         \n     {\n         float vlast = values.back() ;\n\n#ifdef VERBOSE\n         LOG(info) << \"Trackball::configureF\"\n                   << \" name \" << name \n                   << \" vals \" << values.size()\n                   ;\n\n         for(size_t i=0 ; i < values.size() ; i++ ) printf(\"%10.3f \", values[i]);\n         printf(\" : vlast %10.3f \\n\", vlast );\n#endif\n\n         if(      strcmp(name, RADIUS) ==  0)          setRadius(vlast);\n         else if( strcmp(name, TRANSLATEFACTOR) ==  0) setTranslateFactor(vlast);\n         else\n              printf(\"Trackball::configureF ignoring unknown parameter %s : %10.3f \\n\", name, vlast); \n     }\n}\n \n\nvoid Trackball::configureS(const char* name, std::vector<std::string> values)\n{\n     if(values.empty())\n     {\n         printf(\"Trackball::configureS %s no values \\n\", name);\n     }\n     else         \n     {\n         std::string  vlast = values.back() ;\n#ifdef VERBOSE\n         LOG(info) << \"Trackball::configureS\"\n                   << \" name \" << name \n                   << \" vals \" << values.size()\n                   ;\n\n         for(size_t i=0 ; i < values.size() ; i++ ) printf(\"%20s \", values[i].c_str());\n         printf(\" : vlast %20s \\n\", vlast.c_str() );\n#endif\n         set(name, vlast);\n    }\n}\n\n\n\nbool Trackball::accepts(const char* name)\n{\n    return \n         strcmp(name,TRANSLATE)==0  ||\n         strcmp(name,TRANSLATEFACTOR)==0  ||\n         strcmp(name,ORIENTATION)==0 ||\n         strcmp(name,RADIUS)==0 ;\n}\n\nvoid Trackball::configure(const char* name, const char* value_)\n{\n    std::string value(value_);\n    set(name, value);\n}\n\nvoid Trackball::set(const char* name, std::string& s)\n{\n    if(      strcmp(name, TRANSLATE)   ==  0)     setTranslate(s);\n    else if( strcmp(name, ORIENTATION) ==  0)     setOrientation(s);\n    else if( strcmp(name, RADIUS) ==  0)          setRadius(s);\n    else if( strcmp(name, TRANSLATEFACTOR) ==  0) setTranslateFactor(s);\n    else\n        printf(\"Trackball::set ignoring unknown parameter %s : %s \\n\", name, s.c_str()); \n}\n\n\nstd::string Trackball::get(const char* name)\n{\n    std::string s ; \n    if(strcmp(name,TRANSLATE)==0)\n    {\n         glm::vec3 v = getTranslation(); \n         s = gformat(v);\n    }\n    else if( strcmp(name, ORIENTATION) ==  0)\n    {\n         glm::quat q = getOrientation();\n         s = gformat(q);\n    }\n    else if( strcmp(name, RADIUS) ==  0)\n    {\n         float r = getRadius();\n         s = gformat(r);\n    }\n    else if( strcmp(name, TRANSLATEFACTOR) ==  0)\n    {\n         float f = getTranslateFactor();\n         s = gformat(f);\n    }\n    else\n         printf(\"Trackball::get bad name %s\\n\", name);\n\n    return s ;\n}\n\n\nvoid Trackball::setRadius(std::string s)\n{\n    setRadius(gfloat_(s)); \n}\n\nvoid Trackball::setTranslateFactor(std::string s)\n{\n    setTranslateFactor(gfloat_(s)); \n}\n\n \nvoid Trackball::setOrientation(std::string _tp)\n{\n    std::vector<std::string> tp;\n    //boost::split(tp, _tp, boost::is_any_of(\",\"));\n    BStr::split(tp, _tp.c_str(), ',');  \n\n\n    if(tp.size() == 2 )\n    {\n        float theta = boost::lexical_cast<float>(tp[0]); \n        float phi   = boost::lexical_cast<float>(tp[1]); \n        setOrientation(theta,phi);\n    }\n    else if(tp.size() == 4 )\n    {\n        glm::quat q = gquat(_tp);\n        setOrientation(q);  \n    }\n    else\n    {\n        printf(\"Trackball::setOrientation malformed _tp : %s \\n\", _tp.c_str() );\n    }\n}\n\nvoid Trackball::setTranslate(std::string _xyz)\n{\n    glm::vec3 v = gvec3(_xyz);\n    setTranslate(v.x,v.y,v.z);\n}\n\n\nvoid Trackball::setOrientation(float _theta, float _phi)\n{\n    m_theta_deg = _theta ; \n    m_phi_deg  = _phi ;  \n\n    setOrientation();\n}\n\nvoid Trackball::setOrientation()\n{\n    float pi = boost::math::constants::pi<float>() ;\n    float theta = m_theta_deg*pi/180.f ;\n    float phi   = m_phi_deg*pi/180.f ;\n\n    glm::quat xrot(cos(0.5f*theta),sin(0.5f*theta),0.f,0.f);\n    glm::quat zrot(cos(0.5f*phi),  0.f,0.f,sin(0.5f*phi));\n    glm::quat q = xrot * zrot ; \n    setOrientation(q);\n}\n\n\nglm::quat Trackball::getOrientation()\n{\n   return m_orientation ;  \n}\n\nglm::mat4 Trackball::getOrientationMatrix()\n{\n   return glm::toMat4(m_orientation) ;  \n}\n\nvoid Trackball::setOrientation(glm::quat& q)\n{\n    m_orientation = q  ; \n    m_changed = true ; \n}\n\nvoid Trackball::drag_to(float x, float y, float dx, float dy)\n{\n    //printf(\"Trackball::drag_to %10.3f %10.3f %10.3f %10.3f \\n\", x, y, dx, dy);\n\n    m_drag_count += 1 ; \n\n    glm::quat drag = rotate(x,y,dx,dy);\n\n    bool bad =\n                std::isnan(drag.x) || \n                std::isnan(drag.y) || \n                std::isnan(drag.z) || \n                std::isnan(drag.w) ||\n                std::isinf(drag.x) || \n                std::isinf(drag.y) || \n                std::isinf(drag.z) || \n                std::isinf(drag.w)  ;\n\n    if(bad)\n    {\n        LOG(LEVEL) << \"IGNORING bad drag \" ; \n        return ;  \n    }\n\n    glm::quat qrot = m_orientation * drag ;   // perturb orientation by drag rotation  \n\n    if(m_drag_count > m_drag_renorm)\n    {\n        //print(qrot, \"Trackball::drag_to before renorm\");\n        qrot = glm::normalize(qrot);         \n        //print(qrot, \"Trackball::drag_to after renorm\");\n        m_drag_count = 0 ;\n    }\n\n    setOrientation(qrot);\n}\n\n\nvoid Trackball::Summary(const char* msg)\n{\n    printf(\" trackballradius  %10.3f \\n\", m_radius );\n    print(getOrientation(), msg);\n    //print(getOrientationMatrix(), msg);\n}\n\n\nglm::quat Trackball::rotate(float x, float y, float dx, float dy)\n{\n    // p0, p1 are positions of screen before and after coordinates \n    // projected onto a deformed virtual trackball\n\n    glm::vec3 p0(x   ,    y, project(m_radius,x,y)); \n    glm::vec3 p1(x+dx, y+dy, project(m_radius,x+dx,y+dy)); \n   \n    // axis of rotation        \n    glm::vec3 axis = glm::cross(p1, p0);\n\n    // angle of rotation\n    float t = glm::clamp(glm::length(p1-p0)/(2.f*m_radius), -1.f, 1.f ) ;\n    float phi = 2.f * asin(t) ;\n\n    glm::quat q = glm::angleAxis( phi, glm::normalize(axis) );\n\n#ifdef DEBUG\n    print(p0,  \"Trackball::rotate p0\");\n    print(p1,  \"Trackball::rotate p1\");\n    print(axis,\"Trackball::rotate axis\");\n    printf(\"Trackball::rotate t %15.5f phi %15.5f \\n\", t, phi );\n    print(q,   \"Trackball::rotate q\");\n#endif\n\n    return q ; \n}\n \n\n\n\nfloat Trackball::project(float r, float x, float y)\n{\n  /*\n        Project an x,y pair onto a sphere of radius r OR a hyperbolic sheet\n        if we are away from the center of the sphere.\n\n        For points inside xy circle::\n\n                  d^2 = x^2 + y^2\n\n                    d < r / sqrt(2)   \n\n                  d^2 < r^2 / 2 \n\n            x^2 + y^2 < r^2 / 2 \n   \n\n        determine z from::\n\n                z^2 + d^2 = r^2 \n\n        So are projecting onto sphere the center of which is on the screen plane.\n  */      \n \n  float z, t, d ;\n  d = sqrt(x*x + y*y);\n  if (d < r * 0.70710678118654752440f)\n  {     \n      z = sqrt(r*r - d*d);\n  }\n  else\n  {   \n     t = r / 1.41421356237309504880f ;\n     z = t*t / d  ;\n  }\n  return z;\n}\n\n\n", "meta": {"hexsha": "b3c48811ae5fcb84b6eb539f3f5ece895dd8a793", "size": 12656, "ext": "cc", "lang": "C++", "max_stars_repo_path": "optickscore/Trackball.cc", "max_stars_repo_name": "hanswenzel/opticks", "max_stars_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-07-05T02:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:52:44.000Z", "max_issues_repo_path": "optickscore/Trackball.cc", "max_issues_repo_name": "hanswenzel/opticks", "max_issues_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optickscore/Trackball.cc", "max_forks_repo_name": "hanswenzel/opticks", "max_forks_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T20:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T07:42:21.000Z", "avg_line_length": 20.9883913765, "max_line_length": 102, "alphanum_fraction": 0.5952117573, "num_tokens": 3589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.042722202117087986, "lm_q1q2_score": 0.01644429383108213}}
{"text": "/**\n * @file path.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 Licence\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 ALTERNATIVE_ROUTING_LIB_PATH_HPP\n#define ALTERNATIVE_ROUTING_LIB_PATH_HPP\n\n#include <arlib/details/path_impl.hpp>\n#include <arlib/type_traits.hpp>\n\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n\n#include <utility>\n\n/**\n * An Alternative-Routing library for Boost.Graph\n */\nnamespace arlib {\n/**\n * A *view* of a graph to a simple path. A (simple) Path from `s` to `t` is a\n * cycle-free connected sequence of edges \\f$p_{st} = \\langle\t(s, v_1), (v_1,\n * v_x), \\dots , (v_y, t) \\rangle\\f$.\n *\n * This class wraps a `boost::filtered_graph<Graph>` to expose only vertices and\n * edges that make up a simple path. Moreover it provides the `length` of the\n * path, which is defined as the sum of the weights of all the edges. In\n * formula: \\f$\\ell(p) = \\sum_{\\forall (u, v) \\in p} w_{uv}\\f$.\n *\n * Just like `boost::filtered_graph`, Path models the same concepts as the\n * underlying graph type. If the underlying `Graph` type models\n * `VertexAndEdgeListGraph` and `PropertyGraph` then so does the Path.\n * If the underlying `Graph` type models fewer or smaller concepts than these,\n * then so does the Path.\n *\n * @tparam Graph The graph type\n */\ntemplate <typename Graph, typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>,\n          typename Length = length_of_t<Graph>>\nclass Path {\npublic:\n  /**\n   * The inner boost::filtered_graph type\n   */\n  using FilteredGraph =\n      boost::filtered_graph<Graph, details::alternative_path_edges<Edge>,\n                            details::alternative_path_vertices<Vertex>>;\n  /**\n   * Construct a new Path object from a FilteredGraph and the Path length.\n   *\n   * @param g The FilteredGraph to wrap.\n   * @param length The path length.\n   */\n  Path(std::shared_ptr<FilteredGraph> g, Length length)\n      : graph_{std::move(g)}, length_{length} {};\n  /**\n   * Copy-construct a new Path.\n   *\n   * Copy operations on Path are always **shallow**. That means\n   * that multiple copies always refer to the **same memory location**.\n   *\n   * @param other The Path to copy from.\n   */\n  Path(Path const &other) = default;\n  /**\n   * Move-construct a new Path.\n   *\n   * @param other The Path to move.\n   */\n  Path(Path &&other) noexcept = default;\n  /**\n   * Copy-assign a Path to `this`.\n   *\n   * Copy operations on Path are always **shallow**. That means\n   * that multiple copies always refer to the **same memory location**.\n   *\n   * @param other The Path to copy from.\n   * @return `this`.\n   */\n  Path &operator=(Path const &other) = default;\n  /**\n   * Move-assign a Path to `this`.\n   *\n   * @param other The Path to move.\n   * @return `this`.\n   */\n  Path &operator=(Path &&other) noexcept = default;\n  /**\n   * Swaps `this` with another Path.\n   *\n   * @param other The Path to swap with.\n   */\n  void swap(Path &other) {\n    using std::swap;\n    swap(graph_, other.graph_);\n    swap(length_, length_);\n  }\n  /**\n   * @return the length of the path.\n   */\n  Length length() const { return length_; }\n\n  //===-------------------------------------------------------------------===//\n  //                           Graph concept\n  //===-------------------------------------------------------------------===//\n  /**\n   * The type for the vertex descriptors associated with the Path,\n   * which is the same type as the `vertex_descriptor` for the original `Graph`.\n   */\n  using vertex_descriptor =\n      typename boost::graph_traits<FilteredGraph>::vertex_descriptor;\n  /**\n   * The type for the edge descriptors associated with the Path,\n   * which is the same type as the `edge_descriptor` for the original `Graph`.\n   */\n  using edge_descriptor =\n      typename boost::graph_traits<FilteredGraph>::edge_descriptor;\n  /**\n   * Provides information about whether the graph is directed (`directed_tag`)\n   * or undirected (`undirected_tag`).\n   */\n  using directed_category =\n      typename boost::graph_traits<FilteredGraph>::directed_category;\n  /**\n   * This describes whether the graph class allows the insertion of parallel\n   * edges (edges with the same source and target). The two tags are\n   * `allow_parallel_edge_tag` and `disallow_parallel_edge_tag`.\n   */\n  using edge_parallel_category =\n      typename boost::graph_traits<FilteredGraph>::edge_parallel_category;\n  /**\n   * The ways in which the vertices and edges of the graph can be visited\n   */\n  using traversal_category =\n      typename boost::graph_traits<FilteredGraph>::traversal_category;\n  /**\n   * @return A special `boost::graph_traits<Path<Graph>>::vertex_descriptor`\n   * object which does not refer to any vertex of graph object which type is\n   * `Graph`.\n   */\n  static vertex_descriptor null_vertex() {\n    return boost::graph_traits<FilteredGraph>::null_vertex();\n  }\n\n  //===-------------------------------------------------------------------===//\n  //                         IncidenceGraph concept\n  //===-------------------------------------------------------------------===//\n  /**\n   * The type for the iterators returned by out_edges().\n   * The iterator is a model of `MultiPassInputIterator`.\n   */\n  using out_edge_iterator =\n      typename boost::graph_traits<FilteredGraph>::out_edge_iterator;\n  /**\n   * The type used for dealing with the number of edges incident to a vertex in\n   * the graph\n   */\n  using degree_size_type =\n      typename boost::graph_traits<FilteredGraph>::degree_size_type;\n\n  template <typename G>\n  friend std::pair<typename Path<G>::out_edge_iterator,\n                   typename Path<G>::out_edge_iterator>\n  out_edges(typename Path<G>::vertex_descriptor u, Path<G> const &g);\n\n  template <typename G>\n  friend typename Path<G>::vertex_descriptor\n  source(typename Path<G>::edge_descriptor e, Path<G> const &g);\n\n  template <typename G>\n  friend typename Path<G>::vertex_descriptor\n  target(typename Path<G>::edge_descriptor e, Path<G> const &g);\n\n  template <typename G>\n  friend typename Path<G>::degree_size_type\n  out_degree(typename Path<G>::vertex_descriptor v, Path<G> const &g);\n\n  //===-------------------------------------------------------------------===//\n  //                       BidirectionalGraph concept\n  //===-------------------------------------------------------------------===//\n  /**\n   * The type for the iterators returned by in_edges().\n   * The iterator is a model of `MultiPassInputIterator`.\n   */\n  using in_edge_iterator =\n      typename boost::graph_traits<FilteredGraph>::in_edge_iterator;\n\n  template <typename G>\n  friend std::pair<typename Path<G>::in_edge_iterator,\n                   typename Path<G>::in_edge_iterator>\n  in_edges(typename Path<G>::vertex_descriptor v, Path<G> const &g);\n\n  template <typename G>\n  friend typename Path<G>::degree_size_type\n  in_degree(typename Path<G>::vertex_descriptor v, Path<G> const &g);\n\n  template <typename G>\n  friend typename Path<G>::degree_size_type\n  degree(typename Path<G>::vertex_descriptor v, Path<G> const &g);\n\n  //===-------------------------------------------------------------------===//\n  //                        AdjacencyGraph concept\n  //===-------------------------------------------------------------------===//\n  /**\n   * The type for the iterators returned by adjacent_vertices().\n   * The iterator is a model of `MultiPassInputIterator`.\n   */\n  using adjacency_iterator =\n      typename boost::graph_traits<FilteredGraph>::adjacency_iterator;\n\n  template <typename G>\n  friend std::pair<typename Path<G>::adjacency_iterator,\n                   typename Path<G>::adjacency_iterator>\n  adjacent_vertices(typename Path<G>::vertex_descriptor v, Path<G> const &g);\n\n  //===-------------------------------------------------------------------===//\n  //                        VertexListGraph concept\n  //===-------------------------------------------------------------------===//\n  /**\n   * The type for the iterators returned by vertices().\n   * The iterator is a model of `MultiPassInputIterator`.\n   */\n  using vertex_iterator =\n      typename boost::graph_traits<FilteredGraph>::vertex_iterator;\n  /**\n   * The type used for dealing with the number of vertices in the graph.\n   */\n  using vertices_size_type =\n      typename boost::graph_traits<FilteredGraph>::vertices_size_type;\n\n  template <typename G>\n  friend std::pair<typename Path<G>::vertex_iterator,\n                   typename Path<G>::vertex_iterator>\n  vertices(Path<G> const &g);\n\n  template <typename G>\n  friend typename Path<G>::vertices_size_type num_vertices(Path<G> const &g);\n\n  //===-------------------------------------------------------------------===//\n  //                        VertexListGraph concept\n  //===-------------------------------------------------------------------===//\n  /**\n   * The type for the iterators returned by edges().\n   * The iterator is a model of `MultiPassInputIterator`.\n   */\n  using edge_iterator =\n      typename boost::graph_traits<FilteredGraph>::edge_iterator;\n  /**\n   * The type used for dealing with the number of edges in the graph.\n   */\n  using edges_size_type =\n      typename boost::graph_traits<FilteredGraph>::edges_size_type;\n\n  template <typename G>\n  friend std::pair<typename Path<G>::edge_iterator,\n                   typename Path<G>::edge_iterator>\n  edges(Path<G> const &g);\n\n  template <typename G>\n  friend typename Path<G>::edges_size_type num_edges(Path<G> const &g);\n\n  template <typename G>\n  friend std::pair<typename Path<G>::edge_descriptor, bool>\n  edge(typename Path<G>::vertex_descriptor u,\n       typename Path<G>::vertex_descriptor v, Path<G> const &g);\n\n  //===-------------------------------------------------------------------===//\n  //                          PropertyMap concept\n  //===-------------------------------------------------------------------===//\n\n  template <typename G, typename Property>\n  friend typename boost::property_map<typename Path<G>::FilteredGraph,\n                                      Property>::type\n  get(Property p, Path<G> &g);\n\n  template <typename G, typename Property>\n  friend typename boost::property_map<typename Path<G>::FilteredGraph,\n                                      Property>::const_type\n  get(Property p, const Path<G> &g);\n\n  template <typename G, typename Property, typename Key>\n  friend typename boost::property_map_value<typename Path<G>::FilteredGraph,\n                                            Property>::type\n  get(Property p, const Path<G> &g, const Key &k);\n\n  template <typename G, typename Property, typename Key, typename Value>\n  friend void put(Property p, const Path<G> &g, const Key &k, const Value &val);\n\nprivate:\n  std::shared_ptr<FilteredGraph> graph_ = {};\n  Length length_ = {};\n};\n/**\n * Swap between two Path.\n *\n * @tparam Graph The graph type.\n * @param v1 The first Path.\n * @param v2 The second Path.\n */\ntemplate <typename Graph> void swap(Path<Graph> &v1, Path<Graph> &v2) {\n  v1.swap(v2);\n}\n\n//===----------------------------------------------------------------------===//\n//                Non-member functions for the Path Incidence Graph\n//===----------------------------------------------------------------------===//\n/**\n * @return An iterator-range providing access to the out-edges of vertex `u` in\n * graph `g`. If the graph is undirected, this iterator-range provides access to\n * all edges incident on vertex `u`. For both directed and undirected graphs,\n * for an out-edge `e`, `source(e, g) == u` and `target(e, g) == v` where `v` is\n * a vertex adjacent to `u`.\n */\ntemplate <typename G>\nstd::pair<typename Path<G>::out_edge_iterator,\n          typename Path<G>::out_edge_iterator>\nout_edges(typename Path<G>::vertex_descriptor u, Path<G> const &g) {\n  using boost::out_edges;\n  return out_edges(u, *g.graph_);\n}\n/**\n * @return The source vertex of edge `e`.\n */\ntemplate <typename G>\ntypename Path<G>::vertex_descriptor source(typename Path<G>::edge_descriptor e,\n                                           Path<G> const &g) {\n  using boost::source;\n  return source(e, *g.graph_);\n}\n/**\n * @return The target vertex of edge `e`.\n */\ntemplate <typename G>\ntypename Path<G>::vertex_descriptor target(typename Path<G>::edge_descriptor e,\n                                           Path<G> const &g) {\n  using boost::target;\n  return target(e, *g.graph_);\n}\n/**\n * @return The number of edges leaving vertex `u`.\n */\ntemplate <typename G>\ntypename Path<G>::degree_size_type\nout_degree(typename Path<G>::vertex_descriptor u, Path<G> const &g) {\n  using boost::out_degree;\n  return out_degree(u, *g.graph_);\n}\n\n//===----------------------------------------------------------------------===//\n//              Non-member functions for the Path Bidirectional Graph\n//===----------------------------------------------------------------------===//\n/**\n * @return An iterator-range providing access to the in-edges of vertex\n * `v` in graph `g`. For an in-edge `e`, `target(e, g) == v` and `source(e, g)\n * == u` for some vertex `u` that is adjacent to `v`, whether the graph is\n * directed or undirected.\n */\ntemplate <typename G>\nstd::pair<typename Path<G>::in_edge_iterator,\n          typename Path<G>::in_edge_iterator>\nin_edges(typename Path<G>::vertex_descriptor v, Path<G> const &g) {\n  using boost::in_edges;\n  return in_edges(v, *g.graph_);\n}\n/**\n * @return The number of edges entering vertex `v`.\n */\ntemplate <typename G>\ntypename Path<G>::degree_size_type\nin_degree(typename Path<G>::vertex_descriptor v, Path<G> const &g) {\n  using boost::in_degree;\n  return in_degree(v, *g.graph_);\n}\n/**\n * @return The number of in-edges plus out-edges (for directed graphs)\n * or the number of incident edges (for undirected graphs) of vertex `v` in\n * graph `g`.\n */\ntemplate <typename G>\ntypename Path<G>::degree_size_type degree(typename Path<G>::vertex_descriptor v,\n                                          Path<G> const &g) {\n  using boost::degree;\n  return degree(v, *g.graph_);\n}\n\n//===----------------------------------------------------------------------===//\n//              Non-member function for the Path Adjacency Graph\n//===----------------------------------------------------------------------===//\n/**\n * @return An iterator-range providing access to the vertices adjacent\n * to vertex `v` in graph `g`.\n */\ntemplate <typename G>\nstd::pair<typename Path<G>::adjacency_iterator,\n          typename Path<G>::adjacency_iterator>\nadjacent_vertices(typename Path<G>::vertex_descriptor v, Path<G> const &g) {\n  using boost::adjacent_vertices;\n  return adjacent_vertices(v, *g.graph_);\n}\n\n//===----------------------------------------------------------------------===//\n//             Non-member function for the Path Vertex List Graph\n//===----------------------------------------------------------------------===//\n/**\n * @return An iterator-range providing access to the vertex set of graph `g`.\n */\ntemplate <typename G>\nstd::pair<typename Path<G>::vertex_iterator, typename Path<G>::vertex_iterator>\nvertices(Path<G> const &g) {\n  using boost::vertices;\n  return vertices(*g.graph_);\n}\n/**\n * @return The number of vertices in the underlying graph.\n */\ntemplate <typename G>\ntypename Path<G>::vertices_size_type num_vertices(Path<G> const &g) {\n  using boost::num_vertices;\n  return num_vertices(*g.graph_);\n}\n\n//===----------------------------------------------------------------------===//\n//              Non-member functions for the Edge List Graph\n//===----------------------------------------------------------------------===//\n/**\n * @return An iterator-range providing access to the edge set of graph `g`.\n */\ntemplate <typename G>\nstd::pair<typename Path<G>::edge_iterator, typename Path<G>::edge_iterator>\nedges(Path<G> const &g) {\n  using boost::edges;\n  return edges(*g.graph_);\n}\n/**\n * @return The number of edges in the underlying graph.\n */\ntemplate <typename G>\ntypename Path<G>::edges_size_type num_edges(Path<G> const &g) {\n  using boost::num_edges;\n  return num_edges(*g.graph_);\n}\n/**\n * @return The edge connecting vertex `u` to vertex `v` in graph `g`.\n */\ntemplate <typename G>\nstd::pair<typename Path<G>::edge_descriptor, bool>\nedge(typename Path<G>::vertex_descriptor u,\n     typename Path<G>::vertex_descriptor v, Path<G> const &g) {\n  using boost::edge;\n  return edge(u, v, *g.graph_);\n}\n\n//===----------------------------------------------------------------------===//\n//                              Property Map\n//===----------------------------------------------------------------------===//\n/**\n * @return The property map object for the vertex property specified by\n * `Property`. The `Property` must match one of the properties specified in\n * the graph's `VertexProperty` template argument.\n */\ntemplate <typename G, typename Property>\ntypename boost::property_map<typename Path<G>::FilteredGraph, Property>::type\nget(Property p, Path<G> &g) {\n  return get(p, const_cast<typename Path<G>::FilteredGraph &>(*g.graph_));\n}\n/**\n * @return The property map object for the vertex property specified by\n * `Property`. The `Property` must match one of the properties specified in\n * the graph's `VertexProperty` template argument.\n */\ntemplate <typename G, typename Property>\ntypename boost::property_map<typename Path<G>::FilteredGraph,\n                             Property>::const_type\nget(Property p, const Path<G> &g) {\n  return get(p, (const typename Path<G>::FilteredGraph &)*(g.graph_));\n}\n/**\n * @return The property value for `k`, where `k` is either a vertex or\n * edge descriptor\n */\ntemplate <typename G, typename Property, typename Key>\ntypename boost::property_map_value<typename Path<G>::FilteredGraph,\n                                   Property>::type\nget(Property p, const Path<G> &g, const Key &k) {\n  return get(p, (const typename Path<G>::FilteredGraph &)*(g.graph_), k);\n}\n/**\n * This sets the property value for `k` to `val`. `k` is either a vertex or edge\n * descriptor. `Value` must be convertible to `typename\n * property_traits<property_map<Path<G>, Property>::type>::value_type`\n */\ntemplate <typename G, typename Property, typename Key, typename Value>\nvoid put(Property p, const Path<G> &g, const Key &k, const Value &val) {\n  put(p, const_cast<typename Path<G>::FilteredGraph &>(*g.graph_), k, val);\n}\n\n//===----------------------------------------------------------------------===//\n//              Non-member functions for the Path instantiation\n//===----------------------------------------------------------------------===//\n\ntemplate <typename Graph, typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>>\nstd::shared_ptr<\n    boost::filtered_graph<Graph, details::alternative_path_edges<Edge>,\n                          details::alternative_path_vertices<Vertex>>>\nmake_path_filtered_graph(\n    Graph const &G, std::unordered_set<Edge, boost::hash<Edge>> const &edges,\n    std::unordered_set<Vertex, boost::hash<Vertex>> const &vertices) {\n  using FilteredGraph =\n      boost::filtered_graph<Graph, details::alternative_path_edges<Edge>,\n                            details::alternative_path_vertices<Vertex>>;\n  auto ap_edges = details::alternative_path_edges{edges};\n  auto ap_vertices = details::alternative_path_vertices{vertices};\n  return std::make_shared<FilteredGraph>(G, ap_edges, ap_vertices);\n}\n\ntemplate <typename Graph, typename Vertex = vertex_of_t<Graph>,\n          typename Edge = edge_of_t<Graph>>\nstd::shared_ptr<\n    boost::filtered_graph<Graph, details::alternative_path_edges<Edge>,\n                          details::alternative_path_vertices<Vertex>>>\nmake_path_filtered_graph(\n    Graph const &G, std::unordered_set<Edge, boost::hash<Edge>> &&edges,\n    std::unordered_set<Vertex, boost::hash<Vertex>> &&vertices) {\n  using FilteredGraph =\n      boost::filtered_graph<Graph, details::alternative_path_edges<Edge>,\n                            details::alternative_path_vertices<Vertex>>;\n  auto ap_edges = details::alternative_path_edges{std::move(edges)};\n  auto ap_vertices = details::alternative_path_vertices{std::move(vertices)};\n  return std::make_shared<FilteredGraph>(G, ap_edges, ap_vertices);\n}\n} // namespace arlib\n\n/**\n * A collection of free, peer-reviewed C++ libraries.\n */\nnamespace boost {\n/**\n * The property map type for vertex or edge properties in the graph. The same\n * property maps from the wrapped `filtered_graph` graph are available in the\n * Path.\n */\ntemplate <typename G, typename Property>\nstruct property_map<arlib::Path<G>, Property>\n    : property_map<typename arlib::Path<G>::FilteredGraph, Property> {};\n} // namespace boost\n\n#endif // ALTERNATIVE_ROUTING_LIB_PATH_HPP\n", "meta": {"hexsha": "48d2a45dc0a129deae788e0940c502963dcc1d1a", "size": 21827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/path.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/path.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/path.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": 37.8284228769, "max_line_length": 80, "alphanum_fraction": 0.6135978375, "num_tokens": 4712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.04958902210616799, "lm_q1q2_score": 0.01641990408825065}}
{"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 <algorithm>\n#include <iomanip>\n#include <fstream>\n#include <set>\n#include <map>\n#include <utility>\n#include <boost/uuid/uuid.hpp>\n#include <wx/filename.h>\n\n#include \"../GenUtils.h\"\n#include \"../Project.h\"\n#include \"../VarCalc/WeightsManInterface.h\"\n#include \"../DataViewer/TableInterface.h\"\n#include \"GalWeight.h\"\n\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// GalElement\n//\n////////////////////////////////////////////////////////////////////////////////\nGalElement::GalElement()\n{\n    is_nbrAvgW_empty = true;\n}\n\nbool GalElement::Check(long nbrIdx)\n{\n    if (nbrLookup.find(nbrIdx) != nbrLookup.end())\n        return true;\n    return false;\n}\n\n// return row standardized weights value\ndouble GalElement::GetRW(int idx)\n{\n    if (is_nbrAvgW_empty) {\n        size_t sz = nbr.size();\n        nbrAvgW.resize(sz);\n        double sumW = 0.0;\n        \n        for (size_t i=0; i<sz; i++)\n            sumW += nbrWeight[i];\n        \n        for (size_t i=0; i<sz; i++) {\n            nbrAvgW[i] = nbrWeight[i] / sumW;\n        }\n        is_nbrAvgW_empty = false;\n    }\n    \n    if (nbrLookup.find(idx) != nbrLookup.end())\n        return nbrAvgW[nbrLookup[idx]];\n    return 0;\n}\n\nvoid GalElement::SetSizeNbrs(size_t\tsz)\n{\n\tnbr.resize(sz);\n    nbrWeight.resize(sz);\n    for(size_t i=0; i<sz; i++) {\n        nbrWeight[i] = 1.0;\n    }\n}\n\n// (which neighbor, what ID)\nvoid GalElement::SetNbr(size_t pos, long n)\n{\n    if (pos < nbr.size()) {\n        nbr[pos] = n;\n        nbrLookup[n] = pos;\n    }\n    // this should be called by GAL created only\n    if (pos < nbrWeight.size()) {\n        nbrWeight[pos] = 1.0;\n    }\n}\n\n// (which neighbor, what ID, what value)\nvoid GalElement::SetNbr(size_t pos, long n, double w)\n{\n    if (pos < nbr.size()) {\n        nbr[pos] = n;\n        nbrLookup[n] = pos;\n    } else {\n        nbr.push_back(n);\n        nbrLookup[n] = pos;\n    }\n    \n    // this should be called by GWT-GAL \n    if (pos < nbrWeight.size()) {\n        nbrWeight[pos] = w;\n    } else {\n        nbrWeight.push_back(w);\n    }\n}\n\n// Update neighbor information on the fly using undefs information\n// NOTE: this has to be used with a copy of weights (keep the original weights!)\nvoid GalElement::Update(const std::vector<bool>& undefs)\n{\n    std::vector<int> undef_obj_positions;\n   \n    for (int i=0; i<nbr.size(); i++) {\n        int obj_id = nbr[i];\n        if (undefs[obj_id]) {\n            int pos = nbrLookup[obj_id];\n            undef_obj_positions.push_back(pos);\n        }\n    }\n   \n    if (undef_obj_positions.empty())\n        return;\n    \n    // sort the positions in descending order, for removing from std::vector\n\tstd::sort(undef_obj_positions.begin(),\n              undef_obj_positions.end(), std::greater<int>());\n   \n    for (int i=0; i<undef_obj_positions.size(); i++) {\n        int pos = undef_obj_positions[i];\n        if (pos < nbr.size()) {\n            nbrLookup.erase( nbr[pos] );\n            nbr.erase( nbr.begin() + pos);\n        }\n        if (pos < nbrWeight.size()) {\n            nbrWeight.erase( nbrWeight.begin() + pos);\n        }\n    }\n}\n\n/*\nvoid GalElement::SetNbrs(const std::vector<long>& nbrs)\n{\n\tnbr = nbrs;\n    if (nbrWeight.empty()) {\n        size_t sz = nbr.size();\n        nbrWeight.resize(sz);\n        for(size_t i=0; i<sz; i++) {\n            nbrLookup[nbrs[i]] = i;\n            nbrWeight[i] = 1.0;\n        }\n    }\n}\n */\n\nvoid GalElement::SetNbrs(const GalElement& gal)\n{\n    size_t sz = gal.Size();\n    nbr.resize(sz);\n    nbrWeight.resize(sz);\n    \n    nbr = gal.GetNbrs();\n    nbrLookup = gal.nbrLookup;\n    nbrWeight = gal.GetNbrWeights();\n    nbrLookup = gal.nbrLookup;\n    nbrAvgW = gal.nbrAvgW;\n}\n\nconst std::vector<long> & GalElement::GetNbrs() const\n{\n\treturn nbr;\n}\n\nconst std::vector<double> & GalElement::GetNbrWeights() const\n{\n\treturn nbrWeight;\n}\n\nvoid GalElement::SortNbrs()\n{\n\tstd::sort(nbr.begin(), nbr.end(), std::greater<long>());\n}\n\n/** Compute spatial lag for a contiguity weights matrix.\n Automatically performs standardization of the result. */\ndouble GalElement::SpatialLag(const std::vector<double>& x) const\n{\n\tdouble lag = 0;\n\tsize_t sz = Size();\n   \n    double sumW = 0;\n\tfor (size_t i=0; i<sz; ++i) {\n        sumW += nbrWeight[i];\n    }\n    \n    if (sumW == 0)\n        lag = 0;\n    else {\n        for (size_t i=0; i<sz; ++i) {\n            \n            lag += x[nbr[i]] * nbrWeight[i] / sumW;\n        }\n    }\n\t\n\treturn lag;\n}\n\n/** Compute spatial lag for a contiguity weights matrix.\n Automatically performs standardization of the result. */\ndouble GalElement::SpatialLag(const double *x) const\n{\n\tdouble lag = 0;\n\tsize_t sz = Size();\n    \n    double sumW = 0;\n\tfor (size_t i=0; i<sz; ++i) {\n        sumW += nbrWeight[i];\n    }\n    \n    if (sumW == 0)\n        lag = 0;\n    else {\n        for (size_t i=0; i<sz; ++i) {\n            lag += x[nbr[i]] * nbrWeight[i] / sumW;\n        }\n    }\n\t\n\t//for (size_t i=0; i<sz; ++i) lag += x[nbr[i]];\n\t//if (sz>1) lag /= (double) sz;\n\treturn lag;\n}\n\ndouble GalElement::SpatialLag(const std::vector<double>& x,\n\t\t\t\t\t\t\t  const int* perm) const  \n{\n    // todo: this should also handle ReadGWtAsGAL like previous 2 functions\n\tdouble lag = 0;\n\tsize_t sz = Size();\n\tfor (size_t i=0; i<sz; ++i) lag += x[perm[nbr[i]]];\n\tif (sz>1) lag /= (double) sz;\n\treturn lag;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// GalWeight\n//\n////////////////////////////////////////////////////////////////////////////////\nGalWeight::GalWeight(const GalWeight& gw)\n: GeoDaWeight(gw)\n{\n\tGalWeight::operator=(gw);\n}\n\nGalWeight& GalWeight::operator=(const GalWeight& gw)\n{\n\tGeoDaWeight::operator=(gw);\n\tgal = new GalElement[num_obs];\n    \n    for (int i=0; i<num_obs; ++i) {\n        gal[i].SetNbrs(gw.gal[i]);\n    }\n    \n    this->num_obs = gw.num_obs;\n    this->wflnm = gw.wflnm;\n    this->id_field = gw.id_field;\n    \n\treturn *this;\n}\n\nvoid GalWeight::Update(const std::vector<bool>& undefs)\n{\n    for (int i=0; i<num_obs; ++i) {\n        gal[i].Update(undefs);\n    }\n\n}\n\nbool GalWeight::HasIsolates(GalElement *gal, int num_obs)\n{\n    if (!gal) {\n        return false;\n    }\n\tfor (int i=0; i<num_obs; i++) {\n        if (gal[i].Size() <= 0) {\n            return true;\n        }\n    }\n\treturn false;\n}\n\nbool GalWeight::SaveDIDWeights(Project* project, int num_obs,\n                               std::vector<wxInt64>& newids,\n                               std::vector<wxInt64>& stack_ids,\n                               const wxString& ofname)\n{\n    using namespace std;\n    if (!project || ofname.empty()) return false;\n    \n    WeightsManInterface* wmi = project->GetWManInt();\n    if (!wmi) return false;\n    \n    wxString layer_name = GenUtils::GetFileNameNoExt(ofname);\n    \n    GalElement* gal = this->gal;\n    if (!gal) return false;\n    \n    int n = newids.size();\n    \n    ofstream out;\n    out.open(GET_ENCODED_FILENAME(ofname));\n    if (!(out.is_open() && out.good())) return false;\n  \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    wxString id_var_name(\"STID\");\n    out << \"0 \" << n << \" \" << layer_name;\n    out << \" \" << id_var_name << endl;\n   \n    int offset = 0;\n    \n    for (size_t i=0; i<n; ++i) {\n        int orig_id = stack_ids[i];\n        if (i == num_obs) {\n            offset = num_obs;\n            num_obs += num_obs;\n        }\n        \n        out << newids[i];\n        out << \" \" << gal[orig_id].Size() << endl;\n        \n        for (int cp=gal[orig_id].Size(); --cp >= 0;) {\n\t\t\tint n_id = gal[orig_id][cp];\n            out << n_id + offset + 1; // n_id starts from 0, so add 1\n            if (cp > 0) out << \" \";\n        }\n        out << endl;\n    }\n    return true;\n}\n\nbool GalWeight::SaveSpaceTimeWeights(const wxString& ofname, WeightsManInterface* wmi, TableInterface* table_int)\n{\n    using namespace std;\n    \n    if (ofname.empty() || !wmi || !table_int)\n        return false;\n    \n    wxString layer_name = GenUtils::GetFileNameNoExt(ofname);\n    GalElement* gal = this->gal;\n    if (!gal) return false;\n\n    vector<wxString> id_vec;\n    int c_id = table_int->FindColId(this->id_field);\n    if (c_id < 0) return false;\n\n    table_int->GetColData(c_id, 1, id_vec);\n    \n    std::vector<wxString> time_ids;\n    table_int->GetTimeStrings(time_ids);\n\n    size_t num_obs = id_vec.size();\n    size_t num_t = time_ids.size();\n    size_t n = num_obs * num_t;\n\n    \n    typedef std::pair<wxString, wxString> STID_KEY;\n    std::map<STID_KEY, int> stid_dict;\n    \n    int id=1;\n    for (size_t i=0; i<num_t; ++i) {\n        for (size_t j=0; j<num_obs; ++j) {\n            STID_KEY k(id_vec[j], time_ids[i]);\n            stid_dict[k] = id++;\n        }\n    }\n\n    ofstream out;\n    out.open(GET_ENCODED_FILENAME(ofname));\n    if (!(out.is_open() && out.good())) return false;\n    \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    wxString id_var_name(\"STID\");\n    out << \"0 \" << n << \" \" << layer_name;\n    out << \" \" << id_var_name << endl;\n\n    for (size_t i=0; i<num_t; ++i) {\n        for (size_t j=0; j<num_obs; ++j) {\n            STID_KEY k(id_vec[j], time_ids[i]);\n            int m_id = stid_dict[k];\n            out << m_id;\n            out << \" \" << gal[j].Size() << endl;\n            \n            for (int cp=gal[j].Size(); --cp >= 0;) {\n                STID_KEY k(id_vec[gal[j][cp]], time_ids[i]);\n                int n_id = stid_dict[k];\n                out << n_id;\n                if (cp > 0) out << \" \";\n            }\n            out << endl;\n        }\n    }\n\n    return true;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// TODO: following old style functions should be moved into GalWeight class\nbool Gda::SaveGal(const GalElement* g,\n                  const wxString& _layer_name,\n                  const wxString& ofname,\n                  const wxString& id_var_name,\n                  const std::vector<wxInt64>& id_vec)\n{\n\tusing namespace std;\n\tif (g == NULL || ofname.empty() ||\n\t\t\tid_var_name.empty() || id_vec.size() == 0) return false;\n\t\n\twxFileName wx_fn(ofname);\n\twx_fn.SetExt(\"gal\");\n\twxString final_fon(wx_fn.GetFullPath());\n\tofstream out;\n\tout.open(GET_ENCODED_FILENAME(final_fon));\n\tif (!(out.is_open() && out.good())) return false;\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\tsize_t num_obs = (int) id_vec.size();\n\tout << \"0 \" << num_obs << \" \" << layer_name;\n\tout << \" \" << id_var_name << endl;\n\t\n\tfor (size_t i=0; i<num_obs; ++i) {\n\t\tout << id_vec[i];\n\t\tout << \" \" << g[i].Size() << endl;\n\t\tfor (int cp=g[i].Size(); --cp >= 0;) {\n\t\t\tout << id_vec[g[i][cp]];\n\t\t\tif (cp > 0)\n                out << \" \";\n\t\t}\n\t\tout << endl;\n\t}\n\treturn true;\n}\n\nbool Gda::SaveGal(const GalElement* g,\n                  const wxString& _layer_name,\n                  const wxString& ofname,\n                  const wxString& id_var_name,\n                  const std::vector<wxString>& id_vec)\n{\n\tusing namespace std;\n\tif (g == NULL || ofname.empty() ||\n        id_var_name.empty() || id_vec.size() == 0) return false;\n\t\n\twxFileName wx_fn(ofname);\n\twx_fn.SetExt(\"gal\");\n\twxString final_fon(wx_fn.GetFullPath());\n\tofstream out;\n\tout.open(GET_ENCODED_FILENAME(final_fon));\n\tif (!(out.is_open() && out.good()))\n        return false;\n\n    wxString layer_name(_layer_name);\n    \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\tsize_t num_obs = (int) id_vec.size();\n\tout << \"0 \" << num_obs << \" \" << layer_name;\n\tout << \" \" << id_var_name << endl;\n\t\n\tfor (size_t i=0; i<num_obs; ++i) {\n\t\tout << id_vec[i];\n\t\tout << \" \" << g[i].Size() << endl;\n\t\tfor (int cp=g[i].Size(); --cp >= 0;) {\n\t\t\tout << id_vec[g[i][cp]];\n\t\t\tif (cp > 0)\n                out << \" \";\n\t\t}\n\t\tout << endl;\n\t}\n\treturn true;\n}\n\nbool Gda::SaveSpaceTimeGal(const GalElement* g,\n                  const std::vector<wxString>& time_ids,\n                  const wxString& _layer_name,\n                  const wxString& ofname,\n                  const wxString& id_var_name,\n                  const std::vector<wxString>& id_vec)\n{\n\tusing namespace std;\n\tif (g == NULL || ofname.empty() ||\n        id_var_name.empty() || id_vec.size() == 0) return false;\n\t\n\twxFileName wx_fn(ofname);\n\twx_fn.SetExt(\"gal\");\n\twxString final_fon(wx_fn.GetFullPath());\n\tofstream out;\n\tout.open(GET_ENCODED_FILENAME(final_fon));\n\tif (!(out.is_open() && out.good())) return false;\n\t\n\tsize_t num_obs = id_vec.size();\n    size_t num_t = time_ids.size();\n    size_t n = num_obs * num_t;\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\tout << \"0 \" << n << \" \" << layer_name;\n\tout << \" \" << id_var_name << endl;\n\n    for (size_t i=0; i<num_t; ++i) {\n    \tfor (size_t j=0; j<num_obs; ++j) {\n            out << id_vec[i] << \"_t\" << time_ids[i];\n    \t\tout << \" \" << g[i].Size() << endl;\n            \n    \t\tfor (int cp=g[i].Size(); --cp >= 0;) {\n    \t\t\tout << id_vec[g[i][cp]] << \"_t\" << time_ids[i];\n    \t\t\tif (cp > 0) out << \" \";\n    \t\t}\n    \t\tout << endl;\n    \t}\n    }\n\treturn true;\n}\n\n/** Add higher order neighbors up to (and including) distance.\n If cummulative true, then include lower orders as well.  Otherwise,\n only include elements on frontier. */\nvoid Gda::MakeHigherOrdContiguity(size_t distance, size_t obs,\n                                  GalElement* W,\n                                  bool cummulative)\n{\t\n\tusing namespace std;\n\tif (obs < 1 || distance <=1) return;\n\tvector<vector<long> > X(obs);\n\tfor (size_t i=0; i<obs; ++i) {\n\t\tvector<set<long> > n_at_d(distance+1);\n\t\tn_at_d[0].insert(i);\n\t\tfor (size_t j=0, sz=W[i].Size(); j<sz; ++j) {\n\t\t\tn_at_d[1].insert(W[i][j]);\n\t\t}\n\t\tfor (size_t d=2; d<=distance; ++d) {\n\t\t\tfor (set<long>::const_iterator it=n_at_d[d-1].begin();\n\t\t\t\t\t it!=n_at_d[d-1].end(); ++it)\n\t\t\t{\n\t\t\t\tfor (size_t j=0, sz=W[*it].Size(); j<sz; ++j) {\n\t\t\t\t\tlong nbr = W[*it][j];\n\t\t\t\t\tif (n_at_d[d-1].find(nbr) == n_at_d[d-1].end() &&\n\t\t\t\t\t\t\tn_at_d[d-2].find(nbr) == n_at_d[d-2].end()) {\n\t\t\t\t\t\tn_at_d[d].insert(nbr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsize_t sz_Xi = 0;\n\t\tfor (size_t d=(cummulative ? 1 : distance); d<=distance; ++d) {\n\t\t\tsz_Xi += n_at_d[d].size();\n\t\t}\n\t\tX[i].resize(sz_Xi);\n\t\tsize_t cnt=0;\n\t\tfor (size_t d=(cummulative ? 1 : distance); d<=distance; ++d) {\n\t\t\tfor (set<long>::const_iterator it=n_at_d[d].begin();\n\t\t\t\t\t it!=n_at_d[d].end(); ++it) { X[i][cnt++] = *it; }\n\t\t}\n\t\tsort(X[i].begin(), X[i].end(), greater<long>());\n\t}\n\tfor (size_t i=0; i<obs; ++i) {\n\t\tW[i].SetSizeNbrs(X[i].size());\n\t\tfor (size_t j=0, sz=X[i].size(); j<sz; ++j) W[i].SetNbr(j, X[i][j]);\n\t}\n}\n\n", "meta": {"hexsha": "813c45959be84294e8f368e49b74cd3767fbb132", "size": 15980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ShapeOperations/GalWeight.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": "ShapeOperations/GalWeight.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": "ShapeOperations/GalWeight.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": 26.5008291874, "max_line_length": 113, "alphanum_fraction": 0.5458072591, "num_tokens": 4470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.03622005508471649, "lm_q1q2_score": 0.01641716910291768}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Filename    : misc.cpp                                                                              *\n * Project     : Planewalker - Schnorr-Euchner sphere decoder simulation for space-time lattice codes  *\n * Authors     : Pasi Pyrrö, Oliver Gnilke                                                             *\n * Version     : 1.0                                                                                   *\n * Copyright   : Aalto University ~ School of Science ~ Department of Mathematics and Systems Analysis *\n * Date        : 17.8.2017                                                                             *\n * Language    : C++ (2011 or newer standard)                                                          *\n * Description : contain miscellaneous utilities for the sphere decoder program, mainly I/O stuff      *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#define ARMA_NO_DEBUG /* disable Armadillo bound checks for addiotional speed */\n\n#include <iostream>\n#include <mutex>\n#include <ctime>\n#include <string>\n#include <map>\n#include <fstream>\n#include <algorithm>\n#include <armadillo>\n\n#include \"misc.hpp\"\n#ifdef PLOTTING\n#include \"gnuplot-iostream.hpp\" /* Stand alone header file for Gnuplot API (requires Boost library though) */\n#endif\n\nusing namespace std;\nusing namespace arma;\n\n/* objects for parallel computing synchronazation */\nstd::mutex log_mutex;\nstd::mutex output_mutex;\n\nstring red = \"\\e[1;31m\";\nstring green = \"\\e[1;32m\";\nstring yellow = \"\\e[1;33m\";\nstring def = \"\\e[0m\";\n\n/* Generates a standard datetime string of current local time */\nstring time_str(){\n    struct tm *timeinfo;\n    time_t t = time(nullptr);\n    timeinfo = localtime(&t);\n    char timestamp[50]; \n    strftime(timestamp, 50, \"%d-%m-%Y %T\", timeinfo);\n    return string(timestamp);\n}\n\n/* function used for logging, should be thread safe, outputs to terminal and into a txt file\n *\n * Defined values for lvl argument:\n * \"Raw\"   : msg is printed as is without prefix or color\n * \"Info\"  : default value, has prefix but no color, used for basic logging\n * \"Alert\" : Something unexpected happened, uses yellow color\n * \"Error\" : An error occurred and the program needs to terminate, uses red color\n */\nvoid log_msg(const string msg, const string lvl) {\n    string prefix = \"\";\n    string color = \"\";\n    if (lvl.compare(\"Raw\") != 0) { /* raw input contains no prefix */\n        prefix += time_str();\n        prefix += \" | [\" + lvl + \"]\\t\";\n    }\n    if (lvl.compare(\"Alert\") == 0){\n        color = yellow;\n    } \n    if (lvl.compare(\"Error\") == 0){\n        color = red;\n    }\n    lock_guard<mutex> lock(log_mutex); /* make sure other threads don't write to log file simultaneosly */\n    ofstream logfile(filenames[\"log\"], ios_base::app);\n    if (msg.compare(\"-start-\") == 0)   /* just writes newline to log file to indicate new program run */\n        logfile << endl;\n    else {\n        logfile << prefix << msg << endl; /* log txt file */\n        cout << color << prefix << msg << def << endl;    /* stdout */\n    }\n    logfile.close();\n}\n\n/* Makes the user input somewhat more readable */\nvoid clean_input(string &input){\n    /* remove comments from string */\n    string::size_type start = input.find(\"//\", 0);\n    if (start != string::npos)\n        input = input.substr(0, start);\n    /* remove white spaces from string */\n    input.erase(remove_if(input.begin(), input.end(), ::isspace), input.end());\n}\n\n/* removes all characters c from input string */\nvoid remove_from_string(string &input, const char c){\n    input.erase(remove(input.begin(), input.end(), c), input.end());\n}\n\n/* Generates the output filename from current time and the used bases file name */\nvoid create_output_filename(){\n    string bf = filenames[\"bases\"];\n    size_t a = bf.find(\"/\")+1;\n    size_t b = bf.find(\".\");\n    string name = bf.substr(a, b-a);\n    filenames[\"output\"] = string(\"output/\") + time_str() + string(\" \") + name + string(\" output.csv\");\n}\n\n/* Writes a vector of strings (lines) in a csv file */\nvoid output_csv(const parallel_vector<string> &lines){\n    ofstream csv(filenames[\"output\"]);\n    for (const auto &line : lines){\n        csv << line << endl;\n    }\n    csv.close();\n}\n\n/* Used to compare the SNR values of each output line */\nbool snr_ordering(string &a, string &b){\n    /* Example: \n     * a = \"16,15.976382,10000,9.760000\"\n     * b = \"18,17.976382,10000,10.160000\"\n     * --> i = 16, j = 18\n     * --> a comes before b\n     */\n    int i = strtol(a.substr(0, a.find(\",\")).c_str(), NULL, 10);\n    int j = strtol(b.substr(0, b.find(\",\")).c_str(), NULL, 10);\n    return (i < j);\n}\n\n\n/* Uses gnuplot stream to plot the columns of the output csv file */\nvoid plot_csv(int xcol, int ycol, const string &xlabel, const string &ylabel, bool logscale){\n    #ifdef PLOTTING /* This function does nothing if PLOTTING is not defined when compiled */\n    Gnuplot gp;\n    gp << \"set terminal x11\\n\"; /* Open plots in a new GUI window by default, can also be saved in png file for example */\n    if (logscale)\n        gp << \"set logscale y 10\\n\";  /* Set y axis to logscale of base 10 (SNR is already in log10 scale) */\n    gp << \"set datafile separator \\\",\\\"\\n\";\n    gp << \"set xlabel \\\"\" << xlabel << \"\\\"\\n\";\n    gp << \"set ylabel \\\"\" << ylabel << \"\\\"\\n\";\n    gp << \"set grid\\n\";\n    /* plot using the data from output csv file */\n    gp << \"plot '\" << filenames[\"output\"] << \"' using \" << xcol << \":\" << ycol << \" with linespoints ls 3\\n\";\n    #endif\n}\n\n/* Prints simulation results in a file and optionally plots the results */\nvoid output_data(parallel_vector<string> &output){\n    if (output.size() > 1){\n        sort(output.begin()+1, output.end(), snr_ordering); /* sort vector by SNR (ascending order) */\n        log_msg(\"Printing simulation output to '\" + filenames[\"output\"] + \"'...\");\n        output_csv(output);\n        #ifdef PLOTTING /* Draw plots with Gnuplot if plotting is enabled */\n        if (params[\"plot_results\"] > 0){\n            log_msg(\"Drawing plots...\");\n            plot_csv(2, 7, \"SNR (dB)\", \"BLER (%)\", true);\n            plot_csv(2, 3, \"SNR (dB)\", \"Average Complexity (# visited points)\", false);\n        }\n        #endif\n    }\n}\n\n\n/* outputs real matrix into a file in mathematica format */\nvoid output_real_matrix(const string &filepath, const mat &A, bool append){\n    ofstream mfile;\n    /* selects write mode: either overwrite the old file or append to it */\n    if (!append)\n        mfile = ofstream(filepath);\n    else\n        mfile = ofstream(filepath, ios_base::app);\n    mfile << \"{\";\n    for (auto i = 0u; i < A.n_rows; i++){\n        mfile << \"{\";\n        for (auto j = 0u; j < A.n_cols; j++){\n            mfile << float2str(A(i, j), 16);\n            if (j < A.n_cols - 1)\n                mfile << \", \";\n        }\n        mfile << \"}\";\n        if (i < A.n_rows - 1)\n            mfile << \",\" << endl;\n    }\n    mfile << \"}\";\n    if (append) mfile << endl << endl;\n    mfile.close();\n}\n\n\n/* outputs complex matrix into a file in mathematica format */\nvoid output_complex_matrix(const string &filepath, const cx_mat &A, bool append){\n    ofstream mfile;\n    string real, imag;\n    /* selects write mode: either overwrite the old file or append to it */\n    if (!append)\n        mfile = ofstream(filepath);\n    else\n        mfile = ofstream(filepath, ios_base::app);\n    mfile << \"{\";\n    for (auto i = 0u; i < A.n_rows; i++){\n        mfile << \"{\";\n        for (auto j = 0u; j < A.n_cols; j++){\n            real = float2str(A(i, j).real(), 16);\n            imag = float2str(A(i, j).imag(), 16);\n            if (imag[0] == '-')\n                mfile << real << \" - \" << imag.substr(1) << \" *I\";\n            else\n                mfile << real << \" + \" << imag << \" *I\";\n            if (j < A.n_cols - 1)\n                mfile << \", \";\n        }\n        mfile << \"}\";\n        if (i < A.n_rows - 1)\n            mfile << \",\" << endl;\n    }\n    mfile << \"}\";\n    if (append) mfile << endl << endl;\n    mfile.close();\n}\n", "meta": {"hexsha": "56e58799e847ab9cc756695e7e915e3d5ec536aa", "size": 8124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/misc.cpp", "max_stars_repo_name": "Hyper5phere/sphere-decoder", "max_stars_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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/misc.cpp", "max_issues_repo_name": "Hyper5phere/sphere-decoder", "max_issues_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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/misc.cpp", "max_forks_repo_name": "Hyper5phere/sphere-decoder", "max_forks_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "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.2660550459, "max_line_length": 122, "alphanum_fraction": 0.5491137371, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.07369627733527156, "lm_q1q2_score": 0.01641217119347344}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Overload of uBLAS prod function with MKL/GSL implementations\n\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n#include <votca/ctp/logger.h>\n#include <votca/tools/constants.h>\n#include <votca/xtp/gwbse.h>\n#include <votca/xtp/numerical_integrations.h>\n#include <votca/xtp/qmpackagefactory.h>\n#include <votca/xtp/ppm.h>\n#include <votca/xtp/sigma.h>\n#include <votca/xtp/bse.h>\n#include <votca/xtp/sigma.h>\n#include <votca/xtp/orbitals.h>\n\nusing boost::format;\nusing namespace boost::filesystem;\nusing std::flush;\nnamespace votca {\nnamespace xtp {\n\n\nvoid GWBSE::Initialize(tools::Property& options) {\n\n#if (GWBSE_DOUBLE)\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Compiled with full double support\"\n                                 << flush;\n#else\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << \" Compiled with float/double mixture (standard)\" << flush;\n#endif\n\n  std::string key = Identify();\n\n  // getting level ranges\n  double qpminfactor=0;\n  double qpmaxfactor=0;\n  double rpamaxfactor=0;\n  double bseminfactor=0;\n  double bsemaxfactor=0;\nstd::string ranges = options.ifExistsReturnElseReturnDefault<std::string>(key + \".ranges\",\n                                                             \"default\");\n\n  // now check validity, and get rpa, qp, and bse level ranges accordingly\n\n  if (ranges == \"factor\") {\n    // get factors\n    rpamaxfactor = options.get(key + \".rpamax\").as<double>();\n    qpminfactor = options.get(key + \".qpmin\").as<double>();\n    qpmaxfactor = options.get(key + \".qpmax\").as<double>();\n    bseminfactor = options.get(key + \".bsemin\").as<double>();\n    bsemaxfactor = options.get(key + \".bsemax\").as<double>();\n  } else if (ranges == \"explicit\") {\n    // get explicit numbers\n    _rpamax = options.get(key + \".rpamax\").as<int>();\n    _qpmin = options.get(key + \".qpmin\").as<int>();\n    _qpmax = options.get(key + \".qpmax\").as<int>();\n    _bse_vmin = options.get(key + \".bsemin\").as<int>();\n    _bse_cmax = options.get(key + \".bsemax\").as<int>();\n  } else if (ranges == \"\" || ranges == \"default\") {\n    ranges = \"default\";\n  } else if (ranges == \"full\") {\n    ranges = \"full\";\n  } else {\n    std::cerr << \"\\nSpecified range option \" << ranges << \" invalid. \";\n    throw std::runtime_error(\n        \"\\nValid options are: default,factor,explicit,full\");\n  }\n  \n  \n  /* Preparation of calculation parameters:\n   *  - number of electrons -> index of HOMO\n   *  - number of levels\n   *  - highest level considered in RPA\n   *  - lowest and highest level considered in GWA\n   *  - lowest and highest level considered in BSE\n   *  - number of excitations calculates in BSE\n   */\n\n  _homo = _orbitals.getNumberOfElectrons() - 1;  // indexed from 0\n\n _reset_3c=options.ifExistsReturnElseReturnDefault<int>(\n      key + \".rebuild_threecenter_freq\", 5);\n\n  _rpamin = 0;  // lowest index occ min(gwa%mmin, screening%nsum_low) ! always 1\n  if (ranges == \"default\" || ranges == \"full\") {\n    _rpamax = _orbitals.getNumberOfLevels() - 1;  // total number of levels\n  } else if (ranges == \"factor\") {\n    _rpamax = rpamaxfactor * _orbitals.getNumberOfLevels() -\n              1;  // total number of levels\n  }\n  if (_rpamax > _orbitals.getNumberOfLevels() - 1) {\n    _rpamax = _orbitals.getNumberOfLevels() - 1;\n  }\n  // convert _qpmin and _qpmax if needed\n  if (ranges == \"default\") {\n    _qpmin = 0;              // indexed from 0\n    _qpmax = 2 * _homo + 1;  // indexed from 0\n  } else if (ranges == \"factor\") {\n    if (_orbitals.getNumberOfElectrons() -\n            int(qpminfactor * _orbitals.getNumberOfElectrons()) - 1 <\n        0) {\n      _qpmin = 0;\n    } else {\n      _qpmin = _orbitals.getNumberOfElectrons() -\n               int(qpminfactor * _orbitals.getNumberOfElectrons()) - 1;\n    }\n    _qpmax = _orbitals.getNumberOfElectrons() +\n             int(qpmaxfactor * _orbitals.getNumberOfElectrons()) - 1;\n  } else if (ranges == \"explicit\") {\n    _qpmin -= 1;\n    _qpmax -= 1;\n  } else if (ranges == \"full\") {\n    _qpmin = 0;\n    _qpmax = _orbitals.getNumberOfLevels() - 1;\n  }\n  if (_qpmax > int(_orbitals.getNumberOfLevels() - 1)) {\n    _qpmax = _orbitals.getNumberOfLevels() - 1;\n  }\n  if (_qpmax> _rpamax){\n    _qpmax=_rpamax;\n  }\n  \n  // set BSE band range indices\n  // anything else would be stupid!\n  _bse_vmax = _homo;\n  _bse_cmin = _homo + 1;\n\n  if (ranges == \"default\") {\n    _bse_vmin = 0;              // indexed from 0\n    _bse_cmax = 2 * _homo + 1;  // indexed from 0\n  } else if (ranges == \"factor\") {\n    _bse_vmin = _orbitals.getNumberOfElectrons() -\n                int(bseminfactor * _orbitals.getNumberOfElectrons()) - 1;\n    if (_orbitals.getNumberOfElectrons() -\n            int(bseminfactor * _orbitals.getNumberOfElectrons()) - 1 <\n        0) {\n      _bse_vmin = 0;\n    }\n    _bse_cmax = _orbitals.getNumberOfElectrons() +\n                int(bsemaxfactor * _orbitals.getNumberOfElectrons()) - 1;\n  } else if (ranges == \"explicit\") {\n    _bse_vmin -= 1;\n    _bse_cmax -= 1;\n  } else if (ranges == \"full\") {\n    _bse_vmin = 0;\n    _bse_cmax = _orbitals.getNumberOfLevels() - 1;\n  }\n  if (_bse_cmax > int(_orbitals.getNumberOfLevels() - 1)) {\n    _bse_cmax = _orbitals.getNumberOfLevels() - 1;\n  }\n\n  bool ignore_corelevels = options.ifExistsReturnElseReturnDefault<bool>(\n      key + \".ignore_corelevels\", false);\n  \n  \n   int ignored_corelevels = 0;\n  if (ignore_corelevels) {\n    if(!_orbitals.hasECP()){\n      BasisSet basis;\n      basis.LoadPseudopotentialSet(\"corelevels\");//\n      int coreElectrons=0;\n      for(const auto& atom:_orbitals.QMAtoms()){\n        coreElectrons+=basis.getElement(atom->getType()).getNcore();   \n      }\n       ignored_corelevels = coreElectrons/2;\n    }\n   \n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Ignoring \"\n                                   << ignored_corelevels << \" core levels \"\n                                   << flush;\n  }\n  // autoignore core levels in QP\n  if (ignore_corelevels && (_qpmin < ignored_corelevels)) {\n    _qpmin = ignored_corelevels;\n  }\n  // autoignore core levels in BSE\n  if (ignore_corelevels && (_bse_vmin < ignored_corelevels)) {\n    _bse_vmin = ignored_corelevels;\n  }\n\n  int bse_vtotal = _bse_vmax - _bse_vmin + 1;\n  int bse_ctotal = _bse_cmax - _bse_cmin + 1;\n  int bse_size = bse_vtotal * bse_ctotal;\n\n\n  // some QP - BSE consistency checks are required\n  if (_bse_vmin < _qpmin) _qpmin = _bse_vmin;\n  if (_bse_cmax > _qpmax) _qpmax = _bse_cmax;\n\n  _qptotal = _qpmax - _qpmin + 1;\n\n  // information for hybrid DFT\n\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Set RPA level range [\"\n                                 << _rpamin + 1 << \":\" << _rpamax + 1 << \"]\"\n                                 << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Set QP  level range [\"\n                                 << _qpmin + 1 << \":\" << _qpmax + 1 << \"]\"\n                                 << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Set BSE level range occ[\" << _bse_vmin + 1 << \":\"\n      << _bse_vmax + 1 << \"]  virt[\" << _bse_cmin + 1 << \":\" << _bse_cmax + 1\n      << \"]\" << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" BSE Hamiltonian has size \" << bse_size << \"x\"\n      << bse_size << flush;\n  \n  _bse_maxeigenvectors =\n      options.ifExistsReturnElseReturnDefault<int>(key + \".exctotal\", 25);\n   if (_bse_maxeigenvectors > int(bse_size) || _bse_maxeigenvectors < 0) _bse_maxeigenvectors = bse_size;\n  _fragA = options.ifExistsReturnElseReturnDefault<int>(key + \".fragment\", -1);\n\n  std::string BSEtype =\n      options.ifExistsReturnElseReturnDefault<std::string>(key + \".BSEtype\", \"TDA\");\n\n  if (BSEtype == \"full\") {\n    _do_full_BSE = true;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" BSE type: full\" << flush;\n  } else {\n    _do_full_BSE = false;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" BSE type: TDA\" << flush;\n  }\n\n  _openmp_threads =\n      options.ifExistsReturnElseReturnDefault<int>(key + \".openmp\", 0);\n\n  if (options.exists(key + \".vxc\")) {\n    _doVxc =\n        options.ifExistsReturnElseThrowRuntimeError<bool>(key + \".vxc.dovxc\");\n    if (_doVxc) {\n      _functional = options.ifExistsReturnElseThrowRuntimeError<std::string>(\n          key + \".vxc.functional\");\n      _grid = options.ifExistsReturnElseReturnDefault<std::string>(\n          key + \".vxc.grid\", \"medium\");\n    }\n  }\n\n  _auxbasis_name =\n      options.ifExistsReturnElseThrowRuntimeError<std::string>(key + \".gwbasis\");\n  _dftbasis_name =\n      options.ifExistsReturnElseThrowRuntimeError<std::string>(key + \".dftbasis\");\n\n  _shift = options.ifExistsReturnElseThrowRuntimeError<double>(key + \".shift\");\n  _g_sc_limit = options.ifExistsReturnElseReturnDefault<double>(\n      key + \".g_sc_limit\",\n      0.00001);  // convergence criteria for qp iteration [Hartree]]\n  _g_sc_max_iterations = options.ifExistsReturnElseReturnDefault<int>(\n      key + \".g_sc_max_iterations\",\n      40);  // convergence criteria for qp iteration [Hartree]]\n\n  _gw_sc_max_iterations = options.ifExistsReturnElseReturnDefault<int>(\n      key + \".gw_sc_max_iterations\",\n      20);  // convergence criteria for qp iteration [Hartree]]\n\n  _gw_sc_limit = options.ifExistsReturnElseReturnDefault<double>(\n      key + \".gw_sc_limit\", 0.00001);  // convergence criteria for shift it\n  _iterate_gw = false;\n  std::string _shift_type =\n      options.ifExistsReturnElseThrowRuntimeError<std::string>(key + \".shift_type\");\n  if (_shift_type != \"fixed\") {\n    _iterate_gw = true;\n  }\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Shift: \" << _shift_type << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" g_sc_limit [Hartree]: \" << _g_sc_limit\n                                 << flush;\n  if (_iterate_gw) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" gw_sc_limit [Hartree]: \" << _gw_sc_limit\n                                   << flush;\n  }\n  _min_print_weight = options.ifExistsReturnElseReturnDefault<double>(\n      key + \".bse_print_weight\",\n      0.2);  // print exciton WF composition weight larger that thin minimum\n\n  // setting some defaults\n  _do_qp_diag = false;\n  _do_bse_singlets = false;\n  _do_bse_triplets = false;\n  // possible tasks\n  // diagQP, singlets, triplets, all, ibse\n  std::string _tasks_string =\n      options.ifExistsReturnElseThrowRuntimeError<std::string>(key + \".tasks\");\n  if (_tasks_string.find(\"all\") != std::string::npos) {\n    _do_qp_diag = true;\n    _do_bse_singlets = true;\n    _do_bse_triplets = true;\n  }\n  if (_tasks_string.find(\"qpdiag\") != std::string::npos) _do_qp_diag = true;\n  if (_tasks_string.find(\"singlets\") != std::string::npos)\n    _do_bse_singlets = true;\n  if (_tasks_string.find(\"triplets\") != std::string::npos)\n    _do_bse_triplets = true;\n  _store_eh_interaction = false;\n  _do_bse_diag = true;\n  // special construction for ibse mode\n  if (_tasks_string.find(\"iqm\") != std::string::npos) {\n    _do_qp_diag = false;   // no qp diagonalization\n    _do_bse_diag = false;  // no diagonalization of BSE Hamiltonian\n    _store_eh_interaction = true;\n  }\n\n  // possible storage\n  // qpPert, qpdiag_energies, qp_diag_coefficients, bse_singlet_energies,\n  // bse_triplet_energies, bse_singlet_coefficients, bse_triplet_coefficients\n  _store_qp_pert = true;\n\n  _store_qp_diag = false;\n  _store_bse_triplets = false;\n  _store_bse_singlets = false;\n  std::string _store_string =\n      options.ifExistsReturnElseThrowRuntimeError<std::string>(key + \".store\");\n  if ((_store_string.find(\"all\") != std::string::npos) ||\n      (_store_string.find(\"\") != std::string::npos)) {\n    // store according to tasks choice\n    if (_do_qp_diag) _store_qp_diag = true;\n    if (_do_bse_singlets && _do_bse_diag) _store_bse_singlets = true;\n    if (_do_bse_triplets && _do_bse_diag) _store_bse_triplets = true;\n  }\n  if (_store_string.find(\"qpdiag\") != std::string::npos) _store_qp_diag = true;\n  if (_store_string.find(\"singlets\") != std::string::npos)\n    _store_bse_singlets = true;\n  if (_store_string.find(\"triplets\") != std::string::npos)\n    _store_bse_triplets = true;\n  if (_store_string.find(\"ehint\") != std::string::npos)\n    _store_eh_interaction = true;\n\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Tasks: \" << flush;\n  if (_do_qp_diag) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" qpdiag \" << flush;\n  }\n  if (_do_bse_singlets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" singlets \" << flush;\n  }\n  if (_do_bse_triplets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" triplets \" << flush;\n  }\n  CTP_LOG(ctp::logDEBUG, *_pLog) << \" Store: \" << flush;\n  if (_store_qp_diag) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" qpdiag \" << flush;\n  }\n  if (_store_bse_singlets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" singlets \" << flush;\n  }\n  if (_store_bse_triplets) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" triplets \" << flush;\n  }\n  if (_store_eh_interaction) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << \" ehint \" << flush;\n  }\n\n  return;\n}\n\nvoid GWBSE::addoutput(tools::Property& summary) {\n\n  const double hrt2ev = tools::conv::hrt2ev;\n  tools::Property& gwbse_summary = summary.add(\"GWBSE\", \"\");\n  gwbse_summary.setAttribute(\"units\", \"eV\");\n  gwbse_summary.setAttribute(\"DeltaHLGap\",\n                               (format(\"%1$+1.6f \") % (_shift * hrt2ev)).str());\n\n  gwbse_summary.setAttribute(\n      \"DFTEnergy\", (format(\"%1$+1.6f \") % _orbitals.getQMEnergy()).str());\n  int printlimit = _bse_maxeigenvectors;  // I use this to determine how much is printed,\n                                 // I do not want another option to pipe through\n\n  tools::Property &dft_summary = gwbse_summary.add(\"dft\", \"\");\n  dft_summary.setAttribute(\"HOMO\", _homo);\n  dft_summary.setAttribute(\"LUMO\", _homo + 1);\n  \n  for (int state = _qpmin; state < _qpmax+1; state++) {\n\n     tools::Property& level_summary = dft_summary.add(\"level\", \"\");\n    level_summary.setAttribute(\"number\", state);\n    level_summary.add(\"dft_energy\",\n                        (format(\"%1$+1.6f \") %\n                         ((_orbitals.MOEnergies())(_qpmin + state) * hrt2ev))\n                            .str());\n    level_summary.add(\n        \"gw_energy\",\n        (format(\"%1$+1.6f \") % (_orbitals.QPpertEnergies()(_qpmin + state) * hrt2ev)).str());\n\n    if (_do_qp_diag) {\n      level_summary.add(\n          \"qp_energy\",\n          (format(\"%1$+1.6f \") % (_orbitals.QPdiagEnergies()(_qpmin + state) * hrt2ev))\n              .str());\n    }\n  }\n\n  if (_do_bse_singlets) {\n     tools::Property &singlet_summary = gwbse_summary.add(\"singlets\", \"\");\n    for (int state = 0; state < _bse_maxeigenvectors; ++state) {\n       tools::Property &level_summary = singlet_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + 1);\n      level_summary.add(\"omega\", (format(\"%1$+1.6f \") %\n                                    (_orbitals.BSESingletEnergies()(state) * hrt2ev))\n                                       .str());\n      if (_orbitals.hasTransitionDipoles()) {\n\n        const tools::vec &dipoles = (_orbitals.TransitionDipoles())[state];\n        double f = 2 * dipoles * dipoles * _orbitals.BSESingletEnergies()(state) / 3.0;\n\n        level_summary.add(\"f\", (format(\"%1$+1.6f \") % f).str());\n         tools::Property& dipol_summary = level_summary.add(\n            \"Trdipole\", (format(\"%1$+1.4f %2$+1.4f %3$+1.4f\") % dipoles.getX() %\n                         dipoles.getY() % dipoles.getZ())\n                            .str());\n        dipol_summary.setAttribute(\"unit\", \"e*bohr\");\n        dipol_summary.setAttribute(\"gauge\", \"length\");\n      }\n    }\n  }\n  if (_do_bse_triplets) {\n     tools::Property &triplet_summary = gwbse_summary.add(\"triplets\", \"\");\n    for (int state = 0; state < printlimit; ++state) {\n       tools::Property &level_summary = triplet_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + 1);\n      level_summary.add(\"omega\", (format(\"%1$+1.6f \") %\n                                    (_orbitals.BSETripletEnergies()(state) * hrt2ev))\n                                       .str());\n    }\n  }\n  return;\n}\n\n/*\n *    Many-body Green's fuctions theory implementation\n *\n *  data required from orbitals file\n *  - atomic coordinates\n *  - DFT molecular orbitals (energies and coeffcients)\n *  - DFT exchange-correlation potential matrix in atomic orbitals\n *  - number of electrons, number of levels\n *\n\n */\n\nEigen::MatrixXd GWBSE::CalculateVXC(const AOBasis& dftbasis){\n  \n  Eigen::MatrixXd vxc_ao;\n  if (_orbitals.hasAOVxc()) {\n    if (_doVxc) {\n      if(_orbitals.getQMpackage()==\"xtp\"){\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n              << ctp::TimeStamp()\n              << \" Taking VXC from xtp DFT run.\"\n              << flush;\n      }else{\n      CTP_LOG(ctp::logDEBUG, *_pLog)\n              << ctp::TimeStamp()\n              << \" There is already a Vxc matrix loaded from DFT, did you maybe \"\n              \"run a DFT code with outputVxc?\\n I will take the external \"\n              \"implementation\"\n              << flush;\n      }\n      _doVxc = false;\n    }\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n            << \" Loaded external Vxc matrix\" << flush;\n    vxc_ao = _orbitals.AOVxc();\n  } else if (_doVxc) {\n    \n    NumericalIntegration numint;\n    numint.setXCfunctional(_functional);\n    double ScaHFX_temp = numint.getExactExchange(_functional);\n    if (ScaHFX_temp != _orbitals.getScaHFX()) {\n      throw std::runtime_error(\n              (boost::format(\"GWBSE exact exchange a=%s differs from qmpackage \"\n              \"exact exchange a=%s, probably your functionals are \"\n              \"inconsistent\") %\n              ScaHFX_temp %  _orbitals.getScaHFX())\n              .str());\n    }\n    numint.GridSetup(_grid, _orbitals.QMAtoms(),dftbasis);\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp()\n            << \" Setup grid for integration with gridsize: \" << _grid << \" with \"\n            << numint.getGridSize() << \" points, divided into \"\n            << numint.getBoxesSize() << \" boxes\" << flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" Integrating Vxc in VOTCA with functional \"\n            << _functional << flush;\n    Eigen::MatrixXd DMAT = _orbitals.DensityMatrixGroundState();\n    \n    vxc_ao = numint.IntegrateVXC(DMAT);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n            << \" Calculated Vxc in VOTCA\" << flush;\n    \n  } else {\n    throw std::runtime_error(\n            \"So your DFT data contains no Vxc, if you want to proceed use the \"\n            \"dovxc option.\");\n  }\n  \n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n          << \" Set hybrid exchange factor: \" <<  _orbitals.getScaHFX()\n          << flush;\n  \n  // now get expectation values but only for those in _qpmin:_qpmax range\n  Eigen::MatrixXd _mos = _orbitals.MOCoefficients().block(0,_qpmin,_orbitals.MOCoefficients().rows(),_qptotal);\n  \n  Eigen::MatrixXd vxc =_mos.transpose()*vxc_ao*_mos;\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n          << ctp::TimeStamp()\n          << \" Calculated exchange-correlation expectation values \" << flush;\n  return vxc;\n}\n\nvoid GWBSE::PrintGWA_Energies(const Eigen::MatrixXd& vxc, const Sigma& sigma,const Eigen::VectorXd& _dft_energies){\n  const Eigen::VectorXd& gwa_energies=sigma.getGWAEnergies();\n\n  CTP_LOG(ctp::logINFO, *_pLog)\n          << (format(\n          \"  ====== Perturbative quasiparticle energies (Hartree) ====== \"))\n          .str()\n          << flush;\n  CTP_LOG(ctp::logINFO, *_pLog)\n          << (format(\"   DeltaHLGap = %1$+1.6f Hartree\") % _shift).str() << flush;\n  \n  for (int i = 0; i < _qptotal; i++) {\n    if ((i + _qpmin) == _homo) {\n      CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  HOMO  = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = \"\n              \"%4$+1.4f S-C = %5$+1.4f GWA = %6$+1.4f\") %\n              (i + _qpmin + 1) % _dft_energies(i + _qpmin) % vxc(i, i) %\n              sigma.x(i) % sigma.c(i) % gwa_energies(i + _qpmin))\n              .str()\n              << flush;\n    } else if ((i + _qpmin) == _homo + 1) {\n      CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  LUMO  = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = \"\n              \"%4$+1.4f S-C = %5$+1.4f GWA = %6$+1.4f\") %\n              (i + _qpmin + 1) % _dft_energies(i + _qpmin) % vxc(i, i) %\n              sigma.x(i) % sigma.c(i) % gwa_energies(i + _qpmin))\n              .str()\n              << flush;\n      \n    } else {\n      CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  Level = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = \"\n              \"%4$+1.4f S-C = %5$+1.4f GWA = %6$+1.4f\") %\n              (i + _qpmin + 1) % _dft_energies(i + _qpmin) % vxc(i, i) %\n              sigma.x(i) % sigma.c(i) % gwa_energies(i + _qpmin))\n              .str()\n              << flush;\n    }\n  }\n  return;\n}\n\nvoid GWBSE::PrintQP_Energies(const Eigen::VectorXd& gwa_energies, const Eigen::VectorXd& qp_diag_energies){\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n          << ctp::TimeStamp() << \" Full quasiparticle Hamiltonian  \" << flush;\n  CTP_LOG(ctp::logINFO, *_pLog)\n          << (format(\"  ====== Diagonalized quasiparticle energies (Hartree) \"\n          \"====== \"))\n          .str()\n          << flush;\n  for (int _i = 0; _i < _qptotal; _i++) {\n    if ((_i + _qpmin) == _homo) {\n      CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  HOMO  = %1$4d PQP = %2$+1.4f DQP = %3$+1.4f \") %\n              (_i + _qpmin + 1) % gwa_energies(_i + _qpmin) %\n              qp_diag_energies(_i))\n              .str()\n              << flush;\n    } else if ((_i + _qpmin) == _homo + 1) {\n      CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  LUMO  = %1$4d PQP = %2$+1.4f DQP = %3$+1.4f \") %\n              (_i + _qpmin + 1) % gwa_energies(_i + _qpmin) %\n              qp_diag_energies(_i))\n              .str()\n              << flush;\n      \n    } else {\n      CTP_LOG(ctp::logINFO, *_pLog)\n              << (format(\"  Level = %1$4d PQP = %2$+1.4f DQP = %3$+1.4f \") %\n              (_i + _qpmin + 1) % gwa_energies(_i + _qpmin) %\n              qp_diag_energies(_i))\n              .str()\n              << flush;\n    }\n  }\n  return;\n}\n\nbool GWBSE::Evaluate() {\n\n// set the parallelization\n#ifdef _OPENMP\n  if (_openmp_threads > 0) {\n    omp_set_num_threads(_openmp_threads);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Using \"\n                                   << omp_get_max_threads() << \" threads\"\n                                   << flush;\n  }\n#endif\n  \n  if(tools::globals::VOTCA_MKL){\n     CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Using MKL overload for Eigen \"<< flush;\n  }else{\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Using native Eigen implementation, no BLAS overload \"<< flush;\n  }\n  \n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Molecule Coordinates [A] \" << flush;\n  for (QMAtom* atom:_orbitals.QMAtoms()) {\n    std::string output=(boost::format(\"  %1$s\"\n                                         \"   %2$+1.4f %3$+1.4f %4$+1.4f\")\n                         %atom->getType() %(atom->getPos().getX()*tools::conv::bohr2ang)\n                         %(atom->getPos().getY()*tools::conv::bohr2ang)\n                         %(atom->getPos().getZ()*tools::conv::bohr2ang) ).str();\n        \n        CTP_LOG(ctp::logDEBUG, *_pLog) <<output<< flush;\n  }\n  \n  \n  /* check which QC program was used for the DFT run\n   * -> implicit info about MO coefficient storage order\n   */\n  std::string dft_package = _orbitals.getQMpackage();\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" DFT data was created by \" << dft_package\n                                 << flush;\n  \n   // store information in _orbitals for later use\n  _orbitals.setRPAindices(_rpamin, _rpamax);\n  _orbitals.setGWAindices(_qpmin, _qpmax);\n  _orbitals.setBSEindices(_bse_vmin, _bse_vmax, _bse_cmin, _bse_cmax,\n                           _bse_maxeigenvectors);\n  \n    if (_do_full_BSE)\n    _orbitals.setBSEtype(\"full\");\n  else {\n    _orbitals.setBSEtype(\"TDA\");\n  }\n\n\n            \n  // load DFT basis set (element-wise information) from xml file\n  BasisSet dftbs;\n\n  if (_dftbasis_name != _orbitals.getDFTbasis()) {\n    throw std::runtime_error(\n        \"Name of the Basisset from .orb file: \" + _orbitals.getDFTbasis() +\n        \" and from GWBSE optionfile \" + _dftbasis_name + \" do not agree.\");\n  }\n\n  dftbs.LoadBasisSet(_dftbasis_name);\n  _orbitals.setDFTbasis(_dftbasis_name);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Loaded DFT Basis Set \"\n                                 << _dftbasis_name << flush;\n\n  // fill DFT AO basis by going through all atoms\n  AOBasis dftbasis;\n  dftbasis.AOBasisFill(dftbs, _orbitals.QMAtoms(), _fragA);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled DFT Basis of size \"\n                                 << dftbasis.AOBasisSize() << flush;\n  if (dftbasis.getAOBasisFragB() > 0  && dftbasis.getAOBasisFragA()>0) {\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" FragmentA size \"\n                                   << dftbasis.getAOBasisFragA() << flush;\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" FragmentB size \"\n                                   << dftbasis.getAOBasisFragB()<< flush;\n  }\n  \n  // load auxiliary basis set (element-wise information) from xml file\n  BasisSet auxbs;\n  auxbs.LoadBasisSet(_auxbasis_name);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Loaded Auxbasis Set \"\n                                 << _auxbasis_name << flush;\n\n  // fill auxiliary AO basis by going through all atoms\n  AOBasis auxbasis;\n  auxbasis.AOBasisFill(auxbs, _orbitals.QMAtoms());\n  _orbitals.setAuxbasis(_auxbasis_name);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled Auxbasis of size \"\n                                 << auxbasis.AOBasisSize() << flush;\n  \n   // process the DFT data\n  // a) form the expectation value of the XC functional in MOs\n  Eigen::MatrixXd vxc=CalculateVXC(dftbasis);\n\n  /*\n   * for the representation of 2-point functions with the help of the\n   * auxiliary basis, its AO overlap matrix is required.\n   * cf. M. Rohlfing, PhD thesis, ch. 3\n   */\n  AOOverlap auxoverlap;\n  // Fill overlap\n  auxoverlap.Fill(auxbasis);\n\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled Aux Overlap matrix of dimension: \"\n                                 << auxoverlap.Matrix().rows() << flush;\n\n  /*\n   *  for the calculation of Coulomb and exchange term in the self\n   *  energy and electron-hole interaction, the Coulomb interaction\n   *  is represented using the auxiliary basis set.\n   *  Here, we need to prepare the Coulomb matrix expressed in\n   *  the AOs of the auxbasis\n   */\n\n  // get Coulomb matrix as AOCoulomb\n  AOCoulomb auxcoulomb;\n\n  // Fill Coulomb matrix\n  auxcoulomb.Fill(auxbasis);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Filled Aux Coulomb matrix of dimension: \"\n                                 << auxcoulomb.Matrix().rows() << flush;\n \n\n  Eigen::MatrixXd Coulomb_sqrtInv=auxcoulomb.Pseudo_InvSqrt_GWBSE(auxoverlap,5e-7);\n    auxoverlap.FreeMatrix();\n    auxcoulomb.FreeMatrix();\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Calculated Matrix Sqrt of Aux Coulomb Matrix\"\n      << flush;\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Removed \" << auxcoulomb.Removedfunctions()\n      << \" functions from Aux Coulomb matrix to avoid near linear dependencies\" << flush;\n  \n  // container => M_mn\n  // prepare 3-center integral object\n\n  TCMatrix_gwbse Mmn;\n  //rpamin here, because RPA needs till rpamin\n  Mmn.Initialize(auxbasis.AOBasisSize(), _rpamin, _qpmax, _rpamin, _rpamax);\n  Mmn.Fill(auxbasis, dftbasis, _orbitals.MOCoefficients());\n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp()\n      << \" Calculated Mmn_beta (3-center-repulsion x orbitals)  \" << flush;\n\n  // make _Mmn symmetric\n  Mmn.MultiplyRightWithAuxMatrix(Coulomb_sqrtInv);\n  \n  CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp()\n      << \" Multiplied Mmn_beta with Coulomb Matrix \" << flush;\n  PPM ppm;\n  RPA rpa;\n  rpa.configure(_homo,_rpamin,_rpamax);\n  Eigen::VectorXd screen_r=Eigen::VectorXd::Zero(1);\n  screen_r(0)=ppm.getScreening_r();\n  Eigen::VectorXd screen_i=Eigen::VectorXd::Zero(1);\n  screen_i(0)=ppm.getScreening_i();\n  rpa.setScreening(screen_r,screen_i);\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" Prepared RPA  \" << flush;\n  \n  Sigma sigma=Sigma(_pLog);\n  sigma.configure(_homo,_qpmin,_qpmax,_g_sc_max_iterations,_g_sc_limit);\n  sigma.setDFTdata(_orbitals.getScaHFX(),&vxc,&_orbitals.MOEnergies());\n \n  // initialize _qp_energies;\n  // shift unoccupied levels by the shift\n  Eigen::VectorXd gwa_energies = Eigen::VectorXd::Zero(_orbitals.getNumberOfLevels());\n  for (int i = 0; i < gwa_energies.size(); ++i) {\n    gwa_energies(i) = _orbitals.MOEnergies()(i);\n    if (i > int(_homo)) {\n      gwa_energies(i) += _shift;\n    }\n  }\n  sigma.setGWAEnergies(gwa_energies);\n  \n   /* for automatic iteration of both G and W, we need to\n   * - make a copy of _Mmn\n   * - calculate eps\n   * - construct ppm\n   * - threecenters for sigma\n   * - sigma_x\n   * - sigma_c\n   * - test for convergence\n   *\n   */\n\n  if (!_iterate_gw) {\n    _gw_sc_max_iterations = 1;\n  }\n\n  const Eigen::VectorXd &dft_energies = _orbitals.MOEnergies();\n  for (int gw_iteration = 0; gw_iteration < _gw_sc_max_iterations;\n       ++gw_iteration) {\n\n    Eigen::VectorXd qp_old_rpa = gwa_energies;\n    if (_iterate_gw) {\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" GW Iteraton \"\n                                     << gw_iteration + 1 << \" of \"\n                                     << _gw_sc_max_iterations << flush;\n    }\n    \n    \n    if(gw_iteration%_reset_3c==0 && gw_iteration!=0){\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Rebuilding Mmn_beta (3-center-repulsion x orbitals)\" << flush;\n       Mmn.Fill(auxbasis, dftbasis, _orbitals.MOCoefficients());\n       Mmn.MultiplyRightWithAuxMatrix(Coulomb_sqrtInv);\n    }\n  \n    rpa.calculate_epsilon(gwa_energies,Mmn);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Calculated epsilon via RPA  \" << flush;\n    ppm.PPM_construct_parameters(rpa);\n    CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Constructed PPM parameters  \" << flush;\n    \n    Mmn.MultiplyRightWithAuxMatrix(ppm.getPpm_phi());\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Prepared threecenters for sigma  \" << flush;\n\n    sigma.CalcdiagElements(Mmn,ppm);\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n        << ctp::TimeStamp() << \" Calculated diagonal part of Sigma  \" << flush;\n    // iterative refinement of qp energies\n    gwa_energies=sigma.getGWAEnergies();\n    double _DFTgap = dft_energies(_homo + 1) - dft_energies(_homo);\n    double _QPgap = gwa_energies(_homo + 1) - gwa_energies(_homo);\n    _shift = _QPgap - _DFTgap;\n    \n    // qp energies outside the update range are simply shifted.\n    for (int i = _qpmax + 1; i < dft_energies.size(); ++i) {\n      gwa_energies(i) = dft_energies(i) + _shift;\n    }\n    \n    if (_iterate_gw) {\n      bool gw_converged = true;\n      Eigen::VectorXd diff = qp_old_rpa - gwa_energies;\n      int state = 0;\n      double E_diff_max=diff.cwiseAbs().maxCoeff(&state);\n      if(E_diff_max>_gw_sc_limit){\n           gw_converged = false;\n      }\n      \n      double alpha = 0.0;\n      gwa_energies = alpha * qp_old_rpa + (1 - alpha) * gwa_energies;\n      sigma.setGWAEnergies(gwa_energies);\n      if (tools::globals::verbose) {\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" GW_Iteration: \" << gw_iteration + 1\n            << \" shift=\" << _shift << \" E_diff max=\" << E_diff_max\n            << \" StateNo:\" << state << flush;\n      }\n\n      if (gw_converged) {\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" Converged after \" << gw_iteration + 1\n            << \" GW iterations\" << flush;\n        break;\n      } else if (gw_iteration == _gw_sc_max_iterations - 1) {\n        // continue regardless for now, but drop WARNING\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \" WARNING! GWA spectrum not converged after \"\n            << _gw_sc_max_iterations << \" iterations.\" << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp() << \"          GWA level \" << state\n            << \" energy changed by \" << E_diff_max << flush;\n        CTP_LOG(ctp::logDEBUG, *_pLog)\n            << ctp::TimeStamp()\n            << \"          Run continues. Inspect results carefully!\" << flush;\n        break;\n      }\n    }else\n    {\n      sigma.setGWAEnergies(gwa_energies);\n     }\n  }\n   \n  ppm.FreeMatrix();\n  rpa.FreeMatrices();\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                   << \" Cleaned up PPM and MmnRPA Matrices\" << flush;\n  \n  // Output of quasiparticle energies after all is done:\n  PrintGWA_Energies(vxc, sigma, dft_energies);\n\n  // store perturbative QP energy data in orbitals object (DFT, S_x,S_c, V_xc,\n  // E_qp)\n  if (_store_qp_pert) {\n    Eigen::MatrixXd &qp_energies_store = _orbitals.QPpertEnergies();\n    qp_energies_store=Eigen::MatrixXd::Zero(_qptotal, 5);\n    for (int i = 0; i < _qptotal; i++) {\n      qp_energies_store(i, 0) = dft_energies(i + _qpmin);\n      qp_energies_store(i, 1) = sigma.x(i);\n      qp_energies_store(i, 2) = sigma.c(i);\n      qp_energies_store(i, 3) = vxc(i, i);\n      qp_energies_store(i, 4) = gwa_energies(i + _qpmin);\n    }\n  }\n \n  if (_do_qp_diag || _do_bse_singlets || _do_bse_triplets) {\n      CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Calculating offdiagonal part of Sigma  \" << flush;\n  sigma.CalcOffDiagElements(Mmn,ppm);\n   CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Calculated offdiagonal part of Sigma  \" << flush;\n    // free no longer required three-center matrices in _Mmn\n  // max required is _bse_cmax (could be smaller than _qpmax)\n  Mmn.Prune(_bse_vmin, _bse_cmax);   \n    Eigen::MatrixXd Hqp=sigma.SetupFullQPHamiltonian();\n \n    if (_do_qp_diag) {\n      Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Hqp);\n      const Eigen::VectorXd& qp_diag_energies=es.eigenvalues();\n    \n      if(es.info()==Eigen::ComputationInfo::Success){\n    CTP_LOG(ctp::logDEBUG, *_pLog)\n      << ctp::TimeStamp() << \" Diagonalized QP Hamiltonian  \"<< flush;\n      }\n      \n      PrintQP_Energies(gwa_energies, qp_diag_energies);\n\n      if (_store_qp_diag) {\n        _orbitals.QPdiagCoefficients()=es.eigenvectors();\n        _orbitals.QPdiagEnergies()=es.eigenvalues();\n      }\n    }  // _do_qp_diag\n  \n\n  // proceed only if BSE requested\n  if (_do_bse_singlets || _do_bse_triplets) {\n      \n      BSE bse=BSE(_orbitals,_pLog,_min_print_weight);\n      bse.setBSEindices(_homo,_bse_vmin,_bse_cmax,_bse_maxeigenvectors);\n      bse.setGWData(&Mmn,&ppm,&Hqp);\n       // calculate direct part of eh interaction, needed for singlets and triplets\n\n        if (_do_bse_triplets && _do_bse_diag) {\n            bse.Solve_triplets();\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                    << \" Solved BSE for triplets \" << flush;\n            // analyze and report results\n            bse.Analyze_triplets(dftbasis);\n            if (!_store_bse_triplets) {\n                bse.FreeTriplets();\n            }\n        } // do_triplets\n\n        if (_do_bse_singlets && _do_bse_diag) {\n            if (_do_full_BSE) {\n                bse.Solve_singlets_BTDA();\n                CTP_LOG(ctp::logDEBUG, *_pLog)\n                        << ctp::TimeStamp() << \" Solved full BSE for singlets \" << flush;\n            } else {\n                bse.Solve_singlets();\n                CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                        << \" Solved BSE for singlets \" << flush;\n            }\n            bse.Analyze_singlets(dftbasis);\n            if (!_store_bse_singlets) {\n                bse.FreeSinglets();\n            }\n        }\n        if (_store_eh_interaction) {\n            if (_do_bse_singlets) {\n                bse.SetupHs();\n            }\n            if (_do_bse_triplets) {\n                bse.SetupHt();\n            }\n        }\n    }\n  }\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\n                                 << \" GWBSE calculation finished \" << flush;\n  return true;\n}\n}\n};\n", "meta": {"hexsha": "ca1ea37e551f73ce8cc6dbccbedece66a66eda00", "size": 37129, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/gwbse.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/gwbse/gwbse.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/gwbse/gwbse.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4284274194, "max_line_length": 124, "alphanum_fraction": 0.5941716717, "num_tokens": 11034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.03358950843143849, "lm_q1q2_score": 0.016401199223220853}}
{"text": "// #include \"nabo/nabo.h\"\n#include \"helpers.hpp\"\n#include <pcl/io/ply_io.h>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <pcl/io/io.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/registration/icp.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/common/transforms.h>\n#include <omp.h>\n#include <iostream>\n\n// using namespace Nabo;\nusing namespace Eigen;\nusing namespace std;\nusing namespace TransformationUtilities;\nusing namespace InputUtilities;\nusing namespace InterfaceUtilities;\n\ntypedef pcl::PointXYZRGB PointT;\ntypedef pcl::PointCloud<PointT> PointCloudT;\n\nclass Optimizer\n{\n    private:\n        string config_file;\n        vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> clouds;\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;\n        vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> cloud_downsampled;\n        vector<MatrixXd> inverse_kinematics;\n        std::vector<double> transformation_initial;\n        std::vector<double> flange_transformation_initial;\n        vector<double> getTransVector(boost::property_tree::ptree &pt,string s);\n    public:\n        Optimizer(string filename);\n        void getInputs();\n        void discreteCombintorialOptimizerTranslation();\n        void discreteCombintorialOptimizerRotation();\n        void discreteCombintorialOptimizerSmallBruteForce();\n        void discreteCombintorialOptimizerObject();\n        void discreteCombintorialOptimizerCamera();\n        std::vector<double> transformation;\n        std::vector<double> flange_transformation;\n\n};\n\nOptimizer::Optimizer(string filename)\n{\n    config_file = filename;\n    cloud.reset (new PointCloudT);\n    transformation = std::vector<double>(6,0);\n    flange_transformation = std::vector<double>(6,0);\n    transformation_initial = std::vector<double>(6,0);\n    flange_transformation_initial = std::vector<double>(6,0);\n}\n\nvector<double> Optimizer::getTransVector(boost::property_tree::ptree &pt,string s)\n{\n    string angle_metric = pt.get<std::string>(s+\".angle\",\"radian\");\n    string camera_approx_trans_metric = pt.get<std::string>(s+\".metric\",\"m\");\n    double cam_approx_scale = 1.0;\n    if(camera_approx_trans_metric==\"cm\")\n        cam_approx_scale = 100.0;\n    else if(camera_approx_trans_metric==\"mm\")\n        cam_approx_scale=1000.0;\n    string approx_transformation = pt.get<std::string>(s+\".value\",\"0,0,0,0,0,0\");\n    cout<<approx_transformation<<endl;\n    vector<string> coords_str;\n    boost::split(coords_str, approx_transformation , boost::is_any_of(\",\"));\n    vector<double> coords;\n    for(int i=0;i<coords_str.size();i++)\n        if(i<3)\n            coords.push_back(stof(coords_str[i])/cam_approx_scale);\n        else\n        {\n            double value = stof(coords_str[i]);\n            if(angle_metric==\"degree\")\n                value=degreeToRadian(value);\n            coords.push_back(value);\n        }\n    for(auto x:coords)\n        cout<<x<<\" \";\n    cout<<endl;\n    return coords;\n}\nvoid Optimizer::getInputs()\n{\n    ifstream file;\n    std::cout<<\"Config File: \"<<config_file<<endl;\n    file.open(config_file);\n    using boost::property_tree::ptree;\n    ptree pt;\n    read_xml(file, pt);\n    string camera_metric = pt.get<std::string>(\"data.camera.metric\",\"m\");\n    cout<<\"------------- \"<<camera_metric<<endl;\n    for (const auto &cloud : pt.get_child(\"data.camera.clouds\"))\n    {\n        string filename = cloud.second.data();\n\tifstream file(filename);\n\tstring line;\n\tfor(int c=0;c<14&&getline(file,line);c++);\n        PointCloudT::Ptr pointcloud(new PointCloudT);\n\twhile(getline(file,line))\n\t{\n\t\tvector<string> values_from_file;\n\t\tboost::split(values_from_file, line, boost::is_any_of(\" \"));\n\t\tpcl::PointXYZRGB pt;\n\t\tpt.x = stof(values_from_file[0]);\n\t\tpt.y = stof(values_from_file[1]);\n\t\tpt.z = stof(values_from_file[2]);\n\t\tpt.r = stof(values_from_file[3]);\n\t\tpt.g = stof(values_from_file[4]);\n\t\tpt.b = stof(values_from_file[5]);\n\t\tpointcloud->points.push_back(pt);\n\t}\n        PointCloudT::Ptr temp_cloud(new PointCloudT);\n        for(int i=0;i<pointcloud->points.size();i++)\n        {\n            auto pt = pointcloud->points[i];\n            if(pt.x==0.0&&pt.y==0.0&&pt.z==0.0)\n                continue;\n            temp_cloud->points.push_back(pt);\n        }\n        clouds.push_back(temp_cloud);\n        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_bw_temp(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::copyPointCloud(*temp_cloud,*cloud_bw_temp);\n        pcl::VoxelGrid<pcl::PointXYZ> sor;\n        sor.setInputCloud (cloud_bw_temp);\n        constexpr double leaf = 0.0225f;\n        // constexpr double leaf = 0.007f;\n        sor.setLeafSize (leaf, leaf, leaf);\n        sor.filter (*cloud_filtered);\n        cloud_downsampled.push_back(cloud_filtered);\n        // PointCloudT::Ptr pointcloud_output(new PointCloudT);\n        // cloud_outputs.push_back(pointcloud_output);\n        cout<<filename<<endl;\n    }\n    string ik_filename  = pt.get<std::string>(\"data.camera.transformations.inverse_kinematics\");\n    cout<<ik_filename<<endl;\n    inverse_kinematics = readTransformations(ik_filename,true);\n    cout<<\"Transformations Read\"<<endl;\n    //Reading the scan cloud.\n    string object_metric = pt.get<std::string>(\"data.scan.metric\",\"m\");\n    cout<<\"------------- \"<<object_metric <<endl;\n    for(const auto &cloud_location :pt.get_child(\"data.scan.clouds\"))\n    {\n        string filename = cloud_location.second.data();\n        readPointCloud(filename,cloud,object_metric );\n    }\n    cout<<\"Scan read\"<<endl; \n    //Reading Default Values;\n    auto transformation_initial_object= getTransVector(pt,\"data.scan.transformations.approximate_transformation\");\n    for(int i=0;i<transformation_initial_object.size();i++)\n    {\n        transformation[i]=transformation_initial_object[i];\n        transformation_initial[i] = transformation_initial_object[i];\n    }\n    auto transformation_initial_flange= getTransVector(pt,\"data.camera.transformations.approximate_transformation\");\n    for(int i=0;i<transformation_initial_flange.size();i++)\n    {\n        flange_transformation[i]=transformation_initial_flange[i];\n        flange_transformation_initial[i]=transformation_initial_flange[i];\n    }\n    cout<<\"Here\"<<endl;\n}\n\nvoid Optimizer::discreteCombintorialOptimizerTranslation()\n{\n    int K = 1;\n    MatrixXf M = MatrixXf::Zero(3, cloud->points.size());\n    for(int i=0;i<cloud->points.size();i++)\n    {\n        auto pt = cloud->points[i];\n        M(0,i) = pt.x;\n        M(1,i) = pt.y;\n        M(2,i) = pt.z;\n    }\n    // NNSearchF* nns = NNSearchF::createKDTreeLinearHeap(M);\n    //Setting up the structures.\n    vector<MatrixXf> Ns;\n    vector<MatrixXi> indis;\n    vector<MatrixXf> dists;\n    for(int i=0;i<clouds.size();i++)\n    {\n        MatrixXf N = MatrixXf::Zero(3, cloud_downsampled[i]->points.size());\n        Ns.push_back(N);\n        MatrixXi indices;\n        MatrixXf dists2;\n        indices.resize(1, Ns[i].cols());\n        dists2.resize(1, Ns[i].cols());\n        indis.push_back(indices);\n        dists.push_back(dists2);\n        cout<<\"Points Size: \"<<cloud_downsampled[i]->points.size()<<endl;\n    }\n    double min_error = 1e9;\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    vector<double> trans(6),flange_trans(6);\n    int iter_min = -25;\n    int iter_max = 25;\n    TIC();\n    int iterations = 0;\n    for(int xf=iter_min;xf<=iter_max;xf+=5)\n        for(int yf=iter_min;yf<=iter_max;yf+=5)\n            for(int zf=iter_min;zf<=iter_max;zf+=5)\n                for(int xo=iter_min;xo<=iter_max;xo+=5)\n                    for(int yo=iter_min;yo<=iter_max;yo+=5)\n                        for(int zo=iter_min;zo<=iter_max;zo+=5)\n                        {\n                            double err = 0.0;\n                            flange_transformation[0]+=xf/1000.0;\n                            flange_transformation[1]+=yf/1000.0;\n                            flange_transformation[2]+=zf/1000.0;\n                            transformation[0]+=xo/1000.0;\n                            transformation[1]+=yo/1000.0;\n                            transformation[2]+=zo/1000.0;\n                            TIC();\n                            // #pragma omp parallel\n                            // #pragma omp for\n                            for(int j=0;j<clouds.size();j++)\n                            {\n                                float average = 0.0;\n                                float maximum = -1e9;\n                                int counter = 0;\n                                Eigen::MatrixXd world_T_object = vectorToTransformationMatrix(transformation);\n                                Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(flange_transformation);\n                                Eigen::MatrixXd transformation = inverse_kinematics[j]*cam_T_flange;\n                                world_T_object = world_T_object.inverse();\n                                Eigen::Affine3d trans;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        trans(a,b) = transformation(a,b);\n                                Eigen::Affine3d transW;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        transW(a,b) = world_T_object(a,b);\n                                for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n                                {\n                                    auto point = cloud_downsampled[j]->points[i];\n#if 0\n                                    float src[3];\n                                    float out[3];\n                                    src[0] = point.x;\n                                    src[1] = point.y;\n                                    src[2] = point.z;\n                                    apply_transformation_optimized(src,out,trans);\n                                    src[0] = out[0];\n                                    src[1] = out[1];\n                                    src[2] = out[2];\n                                    apply_transformation_optimized(src,out,transW);\n                                    Ns[j](0,i) = out[0];\n                                    Ns[j](1,i) = out[1];\n                                    Ns[j](2,i) = out[2];\n#else\n                                    pts(0,0)=point.x;\n                                    pts(0,1)=point.y;\n                                    pts(0,2)=point.z;\n                                    pts=apply_transformation(pts,transformation);\n                                    pts=apply_transformation(pts,world_T_object);\n                                    Ns[j](0,i) = pts(0,0);\n                                    Ns[j](1,i) = pts(0,1);\n                                    Ns[j](2,i) = pts(0,2);\n#endif\n                                    counter++;\n                                }\n\n                                // nns->knn(Ns[j], indis[j],dists[j], 1, 0.1, NNSearchF::SORT_RESULTS);\n\n                                for(int i=0;i<counter;i++)\n                                {\n                                    double distance = sqrt(dists[j](0,i));\n                                    if(maximum<distance)\n                                        maximum=distance;\n                                    average+=distance;\n                                }\n                                average=average/counter;\n                                err = err + average;\n                            }\n                            if(err<min_error)\n                            {\n                                min_error = err;\n                                flange_trans = flange_transformation;\n                                trans = transformation;\n                            }\n                            if(iterations%100000==0)\n                            {\n                                cout<<\"Iteration: \"<<iterations<<endl;\n                                cout<<xf<<\" \"<<yf<<\" \"<<zf<<\" \"<<xo<<\" \"<<yo<<\" \"<<zo<<endl;\n                                cout<<\"Minimum Error: \"<<min_error<<endl;\n                                cout<<\"Flange Transformation\"<<endl;\n                                for(auto x:flange_trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                                cout<<\"Object Transformation\"<<endl;\n                                for(auto x:trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                                ofstream ofile(\"temp.tmp\",std::ios_base::app);\n                                ofile<<\"Iteration: \"<<iterations<<endl;\n                                ofile<<xf<<\" \"<<yf<<\" \"<<zf<<\" \"<<xo<<\" \"<<yo<<\" \"<<zo<<endl;\n                                ofile<<\"Minimum Error: \"<<min_error<<endl;\n                                ofile<<\"Flange Transformation\"<<endl;\n                                for(auto x:flange_trans)\n                                    ofile<<x<<\" \";\n                                ofile<<endl;\n                                ofile<<\"Object Transformation\"<<endl;\n                                for(auto x:trans)\n                                    ofile<<x<<\" \";\n                                ofile<<endl;\n                                sleep(10);\n                                cout<<\"Sleep Over\"<<endl;\n                            }\n                            flange_transformation[0]-=xf/1000.0;\n                            flange_transformation[1]-=yf/1000.0;\n                            flange_transformation[2]-=zf/1000.0;\n                            transformation[0]-=xo/1000.0;\n                            transformation[1]-=yo/1000.0;\n                            transformation[2]-=zo/1000.0;\n                            iterations++;\n                        }\n    TOC();\n    cout<<\"Iterations: \"<<iterations<<endl;\n    cout<<\"Final Minimum Error: \"<<min_error<<endl;\n    cout<<\"Flange Transformation\"<<endl;\n    for(auto x:flange_trans)\n        cout<<x<<\" \";\n    cout<<\"Object Transformation\"<<endl;\n    for(auto x:trans)\n        cout<<x<<\" \";\n    flange_transformation = flange_trans;\n    transformation = trans;\n}\n\nvoid Optimizer::discreteCombintorialOptimizerRotation()\n{\n    int K = 1;\n    MatrixXf M = MatrixXf::Zero(3, cloud->points.size());\n    for(int i=0;i<cloud->points.size();i++)\n    {\n        auto pt = cloud->points[i];\n        M(0,i) = pt.x;\n        M(1,i) = pt.y;\n        M(2,i) = pt.z;\n    }\n    // NNSearchF* nns = NNSearchF::createKDTreeLinearHeap(M);\n    //Setting up the structures.\n    vector<MatrixXf> Ns;\n    vector<MatrixXi> indis;\n    vector<MatrixXf> dists;\n    for(int i=0;i<clouds.size();i++)\n    {\n        MatrixXf N = MatrixXf::Zero(3, cloud_downsampled[i]->points.size());\n        Ns.push_back(N);\n        MatrixXi indices;\n        MatrixXf dists2;\n        indices.resize(1, Ns[i].cols());\n        dists2.resize(1, Ns[i].cols());\n        indis.push_back(indices);\n        dists.push_back(dists2);\n        cout<<\"Points Size: \"<<cloud_downsampled[i]->points.size()<<endl;\n    }\n    double min_error = 1e9;\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    vector<double> trans(6),flange_trans(6);\n    int iter_min = -1;\n    int iter_max = 1;\n    TIC();\n    int iterations = 0;\n    for(float xf=iter_min;xf<=iter_max;xf+=1)\n        for(float yf=iter_min;yf<=iter_max;yf+=1)\n            for(float zf=iter_min;zf<=iter_max;zf+=1)\n                for(float xo=iter_min;xo<=iter_max;xo+=1)\n                    for(float yo=iter_min;yo<=iter_max;yo+=1)\n                        for(float zo=iter_min;zo<=iter_max;zo+=1)\n                        {\n                            double err = 0.0;\n                            flange_transformation[3]+=degreeToRadian(double(xf));\n                            flange_transformation[4]+=degreeToRadian(double(yf));\n                            flange_transformation[5]+=degreeToRadian(double(zf));\n                            transformation[3]+=degreeToRadian(double(xo));\n                            transformation[4]+=degreeToRadian(double(yo));\n                            transformation[5]+=degreeToRadian(double(zo));\n                            TIC();\n                            // #pragma omp parallel\n                            // #pragma omp for\n                            for(int j=0;j<clouds.size();j++)\n                            {\n                                float average = 0.0;\n                                float maximum = -1e9;\n                                int counter = 0;\n                                Eigen::MatrixXd world_T_object = vectorToTransformationMatrix(transformation);\n                                Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(flange_transformation);\n                                Eigen::MatrixXd transformation = inverse_kinematics[j]*cam_T_flange;\n                                world_T_object = world_T_object.inverse();\n                                Eigen::Affine3d trans;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        trans(a,b) = transformation(a,b);\n                                Eigen::Affine3d transW;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        transW(a,b) = world_T_object(a,b);\n                                for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n                                {\n                                    auto point = cloud_downsampled[j]->points[i];\n#if 1\n                                    float src[3];\n                                    float out[3];\n                                    src[0] = point.x;\n                                    src[1] = point.y;\n                                    src[2] = point.z;\n                                    apply_transformation_optimized(src,out,trans);\n                                    src[0] = out[0];\n                                    src[1] = out[1];\n                                    src[2] = out[2];\n                                    apply_transformation_optimized(src,out,transW);\n                                    Ns[j](0,i) = out[0];\n                                    Ns[j](1,i) = out[1];\n                                    Ns[j](2,i) = out[2];\n#else\n                                    pts(0,0)=point.x;\n                                    pts(0,1)=point.y;\n                                    pts(0,2)=point.z;\n                                    pts=apply_transformation(pts,transformation);\n                                    pts=apply_transformation(pts,world_T_object);\n                                    Ns[j](0,i) = pts(0,0);\n                                    Ns[j](1,i) = pts(0,1);\n                                    Ns[j](2,i) = pts(0,2);\n#endif\n                                    counter++;\n                                }\n\n                                // nns->knn(Ns[j], indis[j],dists[j], 1, 0.1, NNSearchF::SORT_RESULTS);\n\n                                for(int i=0;i<counter;i++)\n                                {\n                                    double distance = sqrt(dists[j](0,i));\n                                    if(maximum<distance)\n                                        maximum=distance;\n                                    average+=distance;\n                                }\n                                average=average/counter;\n                                err = err + average*0.5 + maximum*0.5;\n                            }\n                            if(err<min_error)\n                            {\n                                min_error = err;\n                                flange_trans = flange_transformation;\n                                trans = transformation;\n                            }\n                            if(iterations%100000==0)\n                            {\n                                cout<<\"Iteration: \"<<iterations<<endl;\n                                cout<<xf<<\" \"<<yf<<\" \"<<zf<<\" \"<<xo<<\" \"<<yo<<\" \"<<zo<<endl;\n                                cout<<\"Minimum Error: \"<<min_error<<endl;\n                                cout<<\"Flange Transformation\"<<endl;\n                                for(auto x:flange_trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                                cout<<\"Object Transformation\"<<endl;\n                                for(auto x:trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                            }\n                            flange_transformation[3]-=degreeToRadian(xf/10.0);\n                            flange_transformation[4]-=degreeToRadian(yf/10.0);\n                            flange_transformation[5]-=degreeToRadian(zf/10.0);\n                            transformation[3]-=degreeToRadian(xo/10.0);\n                            transformation[4]-=degreeToRadian(yo/10.0);\n                            transformation[5]-=degreeToRadian(zo/10.0);\n                            iterations++;\n                        }\n    TOC();\n    cout<<\"Iterations: \"<<iterations<<endl;\n    cout<<\"Final Minimum Error: \"<<min_error<<endl;\n    cout<<\"Flange Transformation\"<<endl;\n    for(auto x:flange_trans)\n        cout<<x<<\" \";\n    cout<<endl;\n    cout<<\"Object Transformation\"<<endl;\n    for(auto x:trans)\n        cout<<x<<\" \";\n    cout<<endl;\n    cout<<degreeToRadian(1)<<endl;\n}\n\nvoid Optimizer::discreteCombintorialOptimizerObject()\n{\n    int K = 1;\n    MatrixXf M = MatrixXf::Zero(3, cloud->points.size());\n    for(int i=0;i<cloud->points.size();i++)\n    {\n        auto pt = cloud->points[i];\n        M(0,i) = pt.x;\n        M(1,i) = pt.y;\n        M(2,i) = pt.z;\n    }\n    // NNSearchF* nns = NNSearchF::createKDTreeLinearHeap(M);\n    //Setting up the structures.\n    vector<MatrixXf> Ns;\n    vector<MatrixXi> indis;\n    vector<MatrixXf> dists;\n    for(int i=0;i<clouds.size();i++)\n    {\n        MatrixXf N = MatrixXf::Zero(3, cloud_downsampled[i]->points.size());\n        Ns.push_back(N);\n        MatrixXi indices;\n        MatrixXf dists2;\n        indices.resize(1, Ns[i].cols());\n        dists2.resize(1, Ns[i].cols());\n        indis.push_back(indices);\n        dists.push_back(dists2);\n        cout<<\"Points Size: \"<<cloud_downsampled[i]->points.size()<<endl;\n    }\n    double min_error = 1e9;\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    vector<double> trans(6),flange_trans(6);\n    int iter_min = -10;\n    int iter_max = 10;\n    TIC();\n    int iterations = 0;\n    for(int xc=iter_min;xc<iter_max;xc+=2)\n    for(int yc=iter_min;yc<iter_max;yc+=2)\n    for(int zc=iter_min;zc<iter_max;zc+=2)\n    for(int xr=iter_min;xr<iter_max;xr+=2)\n    for(int yr=iter_min;yr<iter_max;yr+=2)\n    for(int zr=iter_min;zr<iter_max;zr+=2)\n                        {\n                            double err = 0.0;\n                            transformation[0]+=xc/1000.0;\n                            transformation[1]+=yc/1000.0;\n                            transformation[2]+=zc/1000.0;\n                            transformation[3]+=degreeToRadian(xr/5.0);\n                            transformation[4]+=degreeToRadian(yr/5.0);\n                            transformation[5]+=degreeToRadian(zr/5.0);\n                            TIC();\n                            // #pragma omp parallel\n                            // #pragma omp for\n                            for(int j=0;j<clouds.size();j++)\n                            {\n                                float average = 0.0;\n                                float maximum = -1e9;\n                                int counter = 0;\n                                Eigen::MatrixXd world_T_object = vectorToTransformationMatrix(transformation);\n                                Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(flange_transformation);\n                                Eigen::MatrixXd transformation = inverse_kinematics[j]*cam_T_flange;\n                                world_T_object = world_T_object.inverse();\n                                Eigen::Affine3d trans;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        trans(a,b) = transformation(a,b);\n                                Eigen::Affine3d transW;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        transW(a,b) = world_T_object(a,b);\n                                for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n                                {\n                                    auto point = cloud_downsampled[j]->points[i];\n#if 0\n                                    float src[3];\n                                    float out[3];\n                                    src[0] = point.x;\n                                    src[1] = point.y;\n                                    src[2] = point.z;\n                                    apply_transformation_optimized(src,out,trans);\n                                    src[0] = out[0];\n                                    src[1] = out[1];\n                                    src[2] = out[2];\n                                    apply_transformation_optimized(src,out,transW);\n                                    Ns[j](0,i) = out[0];\n                                    Ns[j](1,i) = out[1];\n                                    Ns[j](2,i) = out[2];\n#else\n                                    pts(0,0)=point.x;\n                                    pts(0,1)=point.y;\n                                    pts(0,2)=point.z;\n                                    pts=apply_transformation(pts,transformation);\n                                    pts=apply_transformation(pts,world_T_object);\n                                    Ns[j](0,i) = pts(0,0);\n                                    Ns[j](1,i) = pts(0,1);\n                                    Ns[j](2,i) = pts(0,2);\n#endif\n                                    counter++;\n                                }\n\n                                // nns->knn(Ns[j], indis[j],dists[j], 1, 0.1, NNSearchF::SORT_RESULTS);\n\n                                for(int i=0;i<counter;i++)\n                                {\n                                    double distance = sqrt(dists[j](0,i));\n                                    if(maximum<distance)\n                                        maximum=distance;\n                                    average+=distance;\n                                }\n                                average=average/counter;\n                                err = err + average;\n                            }\n                            if(err<min_error)\n                            {\n                                min_error = err;\n                                flange_trans = flange_transformation;\n                                trans = transformation;\n                            }\n                            if(iterations%100000==0)\n                            {\n                                cout<<\"Iteration: \"<<iterations<<endl;\n                                cout<<\"Minimum Error: \"<<min_error<<endl;\n                                cout<<\"Flange Transformation\"<<endl;\n                                for(auto x:flange_trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                                cout<<\"Object Transformation\"<<endl;\n                                for(auto x:trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                                ofstream ofile(\"temp.tmp\",std::ios_base::app);\n                                ofile<<\"Iteration: \"<<iterations<<endl;\n                                ofile<<\"Minimum Error: \"<<min_error<<endl;\n                                ofile<<\"Flange Transformation\"<<endl;\n                                for(auto x:flange_trans)\n                                    ofile<<x<<\" \";\n                                ofile<<endl;\n                                ofile<<\"Object Transformation\"<<endl;\n                                for(auto x:trans)\n                                    ofile<<x<<\" \";\n                                ofile<<endl;\n                                sleep(10);\n                                cout<<\"Sleep Over\"<<endl;\n                            }\n                            transformation[0]-=xc/1000.0;\n                            transformation[1]-=yc/1000.0;\n                            transformation[2]-=zc/1000.0;\n                            transformation[3]-=degreeToRadian(xr/5.0);\n                            transformation[4]-=degreeToRadian(yr/5.0);\n                            transformation[5]-=degreeToRadian(zr/5.0);\n                            iterations++;\n                        }\n    TOC();\n    cout<<\"Iterations: \"<<iterations<<endl;\n    cout<<\"Final Minimum Error: \"<<min_error<<endl;\n    cout<<\"Flange Transformation\"<<endl;\n    for(auto x:flange_trans)\n        cout<<x<<\" \";\n    cout<<\"Object Transformation\"<<endl;\n    for(auto x:trans)\n        cout<<x<<\" \";\n    flange_transformation = flange_trans;\n    transformation = trans;\n}\n\nvoid Optimizer::discreteCombintorialOptimizerCamera()\n{\n    int K = 1;\n    MatrixXf M = MatrixXf::Zero(3, cloud->points.size());\n    for(int i=0;i<cloud->points.size();i++)\n    {\n        auto pt = cloud->points[i];\n        M(0,i) = pt.x;\n        M(1,i) = pt.y;\n        M(2,i) = pt.z;\n    }\n    // NNSearchF* nns = NNSearchF::createKDTreeLinearHeap(M);\n    //Setting up the structures.\n    vector<MatrixXf> Ns;\n    vector<MatrixXi> indis;\n    vector<MatrixXf> dists;\n    for(int i=0;i<clouds.size();i++)\n    {\n        MatrixXf N = MatrixXf::Zero(3, cloud_downsampled[i]->points.size());\n        Ns.push_back(N);\n        MatrixXi indices;\n        MatrixXf dists2;\n        indices.resize(1, Ns[i].cols());\n        dists2.resize(1, Ns[i].cols());\n        indis.push_back(indices);\n        dists.push_back(dists2);\n        cout<<\"Points Size: \"<<cloud_downsampled[i]->points.size()<<endl;\n    }\n    double min_error = 1e9;\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    vector<double> trans(6),flange_trans(6);\n    int iter_min = -10;\n    int iter_max = 10;\n    TIC();\n    int iterations = 0;\n    for(int xc=iter_min;xc<iter_max;xc+=2)\n    for(int yc=iter_min;yc<iter_max;yc+=2)\n    for(int zc=iter_min;zc<iter_max;zc+=2)\n    for(int xr=iter_min;xr<iter_max;xr+=2)\n    for(int yr=iter_min;yr<iter_max;yr+=2)\n    for(int zr=iter_min;zr<iter_max;zr+=2)\n                        {\n                            double err = 0.0;\n                            flange_transformation[0]+=xc/1000.0;\n                            flange_transformation[1]+=yc/1000.0;\n                            flange_transformation[2]+=zc/1000.0;\n                            flange_transformation[3]+=degreeToRadian(xr/5.0);\n                            flange_transformation[4]+=degreeToRadian(yr/5.0);\n                            flange_transformation[5]+=degreeToRadian(zr/5.0);\n                            TIC();\n                            // #pragma omp parallel\n                            // #pragma omp for\n                            for(int j=0;j<clouds.size();j++)\n                            {\n                                float average = 0.0;\n                                float maximum = -1e9;\n                                int counter = 0;\n                                Eigen::MatrixXd world_T_object = vectorToTransformationMatrix(transformation);\n                                Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(flange_transformation);\n                                Eigen::MatrixXd transformation = inverse_kinematics[j]*cam_T_flange;\n                                world_T_object = world_T_object.inverse();\n                                Eigen::Affine3d trans;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        trans(a,b) = transformation(a,b);\n                                Eigen::Affine3d transW;\n                                for(int a=0;a<3;a++)\n                                    for(int b=0;b<4;b++)\n                                        transW(a,b) = world_T_object(a,b);\n                                for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n                                {\n                                    auto point = cloud_downsampled[j]->points[i];\n#if 0\n                                    float src[3];\n                                    float out[3];\n                                    src[0] = point.x;\n                                    src[1] = point.y;\n                                    src[2] = point.z;\n                                    apply_transformation_optimized(src,out,trans);\n                                    src[0] = out[0];\n                                    src[1] = out[1];\n                                    src[2] = out[2];\n                                    apply_transformation_optimized(src,out,transW);\n                                    Ns[j](0,i) = out[0];\n                                    Ns[j](1,i) = out[1];\n                                    Ns[j](2,i) = out[2];\n#else\n                                    pts(0,0)=point.x;\n                                    pts(0,1)=point.y;\n                                    pts(0,2)=point.z;\n                                    pts=apply_transformation(pts,transformation);\n                                    pts=apply_transformation(pts,world_T_object);\n                                    Ns[j](0,i) = pts(0,0);\n                                    Ns[j](1,i) = pts(0,1);\n                                    Ns[j](2,i) = pts(0,2);\n#endif\n                                    counter++;\n                                }\n\n                                // nns->knn(Ns[j], indis[j],dists[j], 1, 0.1, NNSearchF::SORT_RESULTS);\n\n                                for(int i=0;i<counter;i++)\n                                {\n                                    double distance = sqrt(dists[j](0,i));\n                                    if(maximum<distance)\n                                        maximum=distance;\n                                    average+=distance;\n                                }\n                                average=average/counter;\n                                err = err + average;\n                            }\n                            if(err<min_error)\n                            {\n                                min_error = err;\n                                flange_trans = flange_transformation;\n                                trans = transformation;\n                            }\n                            if(iterations%100000==0)\n                            {\n                                cout<<\"Iteration: \"<<iterations<<endl;\n                                cout<<\"Minimum Error: \"<<min_error<<endl;\n                                cout<<\"Flange Transformation\"<<endl;\n                                for(auto x:flange_trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                                cout<<\"Object Transformation\"<<endl;\n                                for(auto x:trans)\n                                    cout<<x<<\" \";\n                                cout<<endl;\n                                ofstream ofile(\"temp.tmp\",std::ios_base::app);\n                                ofile<<\"Iteration: \"<<iterations<<endl;\n                                ofile<<\"Minimum Error: \"<<min_error<<endl;\n                                ofile<<\"Flange Transformation\"<<endl;\n                                for(auto x:flange_trans)\n                                    ofile<<x<<\" \";\n                                ofile<<endl;\n                                ofile<<\"Object Transformation\"<<endl;\n                                for(auto x:trans)\n                                    ofile<<x<<\" \";\n                                ofile<<endl;\n                                sleep(10);\n                                cout<<\"Sleep Over\"<<endl;\n                            }\n                            flange_transformation[0]-=xc/1000.0;\n                            flange_transformation[1]-=yc/1000.0;\n                            flange_transformation[2]-=zc/1000.0;\n                            flange_transformation[3]-=degreeToRadian(xr/5.0);\n                            flange_transformation[4]-=degreeToRadian(yr/5.0);\n                            flange_transformation[5]-=degreeToRadian(zr/5.0);\n                            iterations++;\n                        }\n    TOC();\n    cout<<\"Iterations: \"<<iterations<<endl;\n    cout<<\"Final Minimum Error: \"<<min_error<<endl;\n    cout<<\"Flange Transformation\"<<endl;\n    for(auto x:flange_trans)\n        cout<<x<<\" \";\n    cout<<\"Object Transformation\"<<endl;\n    for(auto x:trans)\n        cout<<x<<\" \";\n    flange_transformation = flange_trans;\n    transformation = trans;\n}\n\nvoid Optimizer::discreteCombintorialOptimizerSmallBruteForce()\n{\n    int K = 1;\n    MatrixXf M = MatrixXf::Zero(3, cloud->points.size());\n    for(int i=0;i<cloud->points.size();i++)\n    {\n        auto pt = cloud->points[i];\n        M(0,i) = pt.x;\n        M(1,i) = pt.y;\n        M(2,i) = pt.z;\n    }\n    // NNSearchF* nns = NNSearchF::createKDTreeLinearHeap(M);\n    //Setting up the structures.\n    vector<MatrixXf> Ns;\n    vector<MatrixXi> indis;\n    vector<MatrixXf> dists;\n    for(int i=0;i<clouds.size();i++)\n    {\n        MatrixXf N = MatrixXf::Zero(3, cloud_downsampled[i]->points.size());\n        Ns.push_back(N);\n        MatrixXi indices;\n        MatrixXf dists2;\n        indices.resize(1, Ns[i].cols());\n        dists2.resize(1, Ns[i].cols());\n        indis.push_back(indices);\n        dists.push_back(dists2);\n        cout<<\"Points Size: \"<<cloud_downsampled[i]->points.size()<<endl;\n    }\n    double min_error = 1e9;\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    vector<double> trans(6),flange_trans(6);\n    int iter_min = -1;\n    int iter_max = 1;\n    TIC();\n    int iterations = 0;\n    for(int x=0;x<7;x++)\n        for(int a=iter_min;a<=iter_max;a++)\n            for(int b=iter_min;b<=iter_max;b++)\n                for(int c=iter_min;c<=iter_max;c++)\n                    for(int d=iter_min;d<=iter_max;d++)\n                        for(int e=iter_min;e<=iter_max;e++)\n                            for(int f=iter_min;f<=iter_max;f++)\n                                for(int g=iter_min;g<=iter_max;g++)\n                                    for(int h=iter_min;h<=iter_max;h++)\n                                        for(int i=iter_min;i<=iter_max;i++)\n                                            for(int j=iter_min;j<=iter_max;j++)\n                                                for(int k=iter_min;k<=iter_max;k++)\n                                                    for(int l=iter_min;l<=iter_max;l++)\n                                                    {\n                                                        double err = 0.0;\n                                                        flange_transformation[0]+=a/1000.0;\n                                                        flange_transformation[1]+=b/1000.0;\n                                                        flange_transformation[2]+=c/1000.0;\n                                                        flange_transformation[3]+=degreeToRadian(float(d/2.0));\n                                                        flange_transformation[4]+=degreeToRadian(float(e/2.0));\n                                                        flange_transformation[5]+=degreeToRadian(float(f/2.0));\n                                                        transformation[0]+=g/1000.0;\n                                                        transformation[1]+=h/1000.0;\n                                                        transformation[2]+=i/1000.0;\n                                                        transformation[3]+=degreeToRadian(float(j/2.0));\n                                                        transformation[4]+=degreeToRadian(float(k/2.0));\n                                                        transformation[5]+=degreeToRadian(float(l/2.0));\n                                                        TIC();\n                                                        // #pragma omp parallel\n                                                        // #pragma omp for\n                                                        for(int j=0;j<clouds.size();j++)\n                                                        {\n                                                            float average = 0.0;\n                                                            float maximum = -1e9;\n                                                            int counter = 0;\n                                                            Eigen::MatrixXd world_T_object = vectorToTransformationMatrix(transformation);\n                                                            Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(flange_transformation);\n                                                            Eigen::MatrixXd transformation = inverse_kinematics[j]*cam_T_flange;\n                                                            world_T_object = world_T_object.inverse();\n                                                            Eigen::Affine3d trans;\n                                                            for(int a=0;a<3;a++)\n                                                                for(int b=0;b<4;b++)\n                                                                    trans(a,b) = transformation(a,b);\n                                                            Eigen::Affine3d transW;\n                                                            for(int a=0;a<3;a++)\n                                                                for(int b=0;b<4;b++)\n                                                                    transW(a,b) = world_T_object(a,b);\n                                                            for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n                                                            {\n                                                                auto point = cloud_downsampled[j]->points[i];\n#if 1\n                                                                float src[3];\n                                                                float out[3];\n                                                                src[0] = point.x;\n                                                                src[1] = point.y;\n                                                                src[2] = point.z;\n                                                                apply_transformation_optimized(src,out,trans);\n                                                                src[0] = out[0];\n                                                                src[1] = out[1];\n                                                                src[2] = out[2];\n                                                                apply_transformation_optimized(src,out,transW);\n                                                                Ns[j](0,i) = out[0];\n                                                                Ns[j](1,i) = out[1];\n                                                                Ns[j](2,i) = out[2];\n#else\n                                                                pts(0,0)=point.x;\n                                                                pts(0,1)=point.y;\n                                                                pts(0,2)=point.z;\n                                                                pts=apply_transformation(pts,transformation);\n                                                                pts=apply_transformation(pts,world_T_object);\n                                                                Ns[j](0,i) = pts(0,0);\n                                                                Ns[j](1,i) = pts(0,1);\n                                                                Ns[j](2,i) = pts(0,2);\n#endif\n                                                                counter++;\n                                                            }\n\n                                                            // nns->knn(Ns[j], indis[j],dists[j], 1, 0.1, NNSearchF::SORT_RESULTS);\n\n                                                            for(int i=0;i<counter;i++)\n                                                            {\n                                                                double distance = sqrt(dists[j](0,i));\n                                                                if(maximum<distance)\n                                                                    maximum=distance;\n                                                                average+=distance;\n                                                            }\n                                                            average=average/counter;\n                                                            err = err + average*0.5 + maximum*0.5;\n                                                        }\n                                                        if(err<min_error)\n                                                        {\n                                                            min_error = err;\n                                                            flange_trans = flange_transformation;\n                                                            trans = transformation;\n                                                        }\n                                                        if(iterations%100000==0)\n                                                        {\n                                                            cout<<\"Iteration: \"<<iterations<<endl;\n                                                            cout<<\"Minimum Error: \"<<min_error<<endl;\n                                                            cout<<\"Flange Transformation\"<<endl;\n                                                            for(auto x:flange_trans)\n                                                                cout<<x<<\" \";\n                                                            cout<<endl;\n                                                            cout<<\"Object Transformation\"<<endl;\n                                                            for(auto x:trans)\n                                                                cout<<x<<\" \";\n                                                            cout<<endl;\n                                                        }\n                                                        flange_transformation[0]-=a/1000.0;\n                                                        flange_transformation[1]-=b/1000.0;\n                                                        flange_transformation[2]-=c/1000.0;\n                                                        flange_transformation[3]-=degreeToRadian(float(d/2.0));\n                                                        flange_transformation[4]-=degreeToRadian(float(e/2.0));\n                                                        flange_transformation[5]-=degreeToRadian(float(f/2.0));\n                                                        transformation[0]-=g/1000.0;\n                                                        transformation[1]-=h/1000.0;\n                                                        transformation[2]-=i/1000.0;\n                                                        transformation[3]-=degreeToRadian(float(j/2.0));\n                                                        transformation[4]-=degreeToRadian(float(k/2.0));\n                                                        transformation[5]-=degreeToRadian(float(l/2.0));\n                                                        iterations++;\n                                                    }\n    TOC();\n    cout<<\"Iterations: \"<<iterations<<endl;\n    cout<<\"Final Minimum Error: \"<<min_error<<endl;\n    cout<<\"Flange Transformation\"<<endl;\n    for(auto x:flange_trans)\n        cout<<x<<\" \";\n    cout<<endl;\n    cout<<\"Object Transformation\"<<endl;\n    for(auto x:trans)\n        cout<<x<<\" \";\n    cout<<endl;\n    cout<<degreeToRadian(1)<<endl;\n}\n\nint main(int argc, char** argv)\n{\n    if(argc<2)\n    {\n        std::cout<<\"Usage: optimizer_test <config file>\"<<endl;\n        exit(-1);\n    }\n    Optimizer opti = Optimizer(string(argv[1]));\n    opti.getInputs();\n    cout<<\" Discrete optimization on Translation..\"<<endl;\n    // opti.discreteCombintorialOptimizerSmallBruteForce();\n    opti.discreteCombintorialOptimizerTranslation();\n    opti.discreteCombintorialOptimizerRotation();\n    // opti.discreteCombintorialOptimizerObject();\n    // opti.discreteCombintorialOptimizerCamera();\n    return 0;\n}\n\n", "meta": {"hexsha": "6de8b426ad54ee0c907cb4cc86b4087de5c0b8f0", "size": 49426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimizer_test.cpp", "max_stars_repo_name": "REXJJ/CameraCalibration", "max_stars_repo_head_hexsha": "6c35d88f64846e5d7e74b4156a75080a9a5f1adf", "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/optimizer_test.cpp", "max_issues_repo_name": "REXJJ/CameraCalibration", "max_issues_repo_head_hexsha": "6c35d88f64846e5d7e74b4156a75080a9a5f1adf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimizer_test.cpp", "max_forks_repo_name": "REXJJ/CameraCalibration", "max_forks_repo_head_hexsha": "6c35d88f64846e5d7e74b4156a75080a9a5f1adf", "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": 49.1800995025, "max_line_length": 143, "alphanum_fraction": 0.3975640351, "num_tokens": 9508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.03358950613381431, "lm_q1q2_score": 0.016401198101329117}}
{"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 <string>\n#include <type_traits>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/ContainerHelpers.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/ErrorHandling/Error.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n\nnamespace gr::Solutions {\nstd::ostream& operator<<(std::ostream& os, const TovCoordinates coords) {\n  switch (coords) {\n    case TovCoordinates::Schwarzschild:\n      return os << \"Schwarzschild\";\n    case TovCoordinates::Isotropic:\n      return os << \"Isotropic\";\n    default:\n      ERROR(\"Unknown TovCoordinates\");\n  }\n}\n}  // namespace gr::Solutions\n\ntemplate <>\ngr::Solutions::TovCoordinates\nOptions::create_from_yaml<gr::Solutions::TovCoordinates>::create<void>(\n    const Options::Option& options) {\n  const auto type_read = options.parse_as<std::string>();\n  if (\"Schwarzschild\" == type_read) {\n    return gr::Solutions::TovCoordinates::Schwarzschild;\n  } else if (\"Isotropic\" == type_read) {\n    return gr::Solutions::TovCoordinates::Isotropic;\n  }\n  PARSE_ERROR(options.context(),\n              \"Failed to convert '\"\n                  << type_read\n                  << \"' to gr::Solutions::TovCoordinates. Must be \"\n                     \"'Schwarzschild' or 'Isotropic'.\");\n}\n\nnamespace gr::Solutions {\nnamespace {\n\n// In Schwarzschild coords we integrate u=r^2 and v=m/r (2 vars), and in\n// isotropic coords we also integrate w=ln(psi) (3 vars).\ntemplate <TovCoordinates CoordSystem>\nusing TovVars =\n    std::conditional_t<CoordSystem == TovCoordinates::Schwarzschild,\n                       std::array<double, 2>, std::array<double, 3>>;\n\ntemplate <TovCoordinates CoordSystem>\nvoid lindblom_rhs(\n    const gsl::not_null<TovVars<CoordSystem>*> dvars,\n    const TovVars<CoordSystem>& vars, const double log_enthalpy,\n    const EquationsOfState::EquationOfState<true, 1>& equation_of_state) {\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    if constexpr (CoordSystem == TovCoordinates::Isotropic) {\n      double& d_log_conformal_factor = (*dvars)[2];\n      d_log_conformal_factor = -0.25 * d_mass_over_radius;\n    }\n  } else {\n    const double one_minus_two_m_over_r = 1.0 - 2.0 * mass_over_radius;\n    const double denominator =\n        4.0 * M_PI * radius_squared * pressure + mass_over_radius;\n    const double common_factor = one_minus_two_m_over_r / denominator;\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    if constexpr (CoordSystem == TovCoordinates::Isotropic) {\n      double& d_log_conformal_factor = (*dvars)[2];\n      d_log_conformal_factor = sqrt(one_minus_two_m_over_r) /\n                               (1.0 + sqrt(one_minus_two_m_over_r)) *\n                               mass_over_radius / denominator;\n    }\n  }\n}\n\ntemplate <TovCoordinates CoordSystem>\nclass IntegralObserver {\n public:\n  void operator()(const TovVars<CoordSystem>& vars,\n                  const double current_log_enthalpy) {\n    radius.push_back(std::sqrt(vars[0]));\n    mass_over_radius.push_back(vars[1]);\n    if constexpr (CoordSystem == TovCoordinates::Isotropic) {\n      conformal_factor.push_back(exp(vars[2]));\n    }\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> conformal_factor;\n  std::vector<double> log_enthalpy;\n};\n\n}  // namespace\n\ntemplate <TovCoordinates CoordSystem>\nvoid TovSolution::integrate(\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  using Vars = TovVars<CoordSystem>;\n  Vars vars{};\n  // Initial integration variables at the center of the star\n  vars[0] = 0.;  // u = r^2 = 0\n  vars[1] = 0.;  // v = m / r = 0\n  if constexpr (CoordSystem == TovCoordinates::Isotropic) {\n    vars[2] = 0.;  // w = ln(psi) = 0 (rescaled later)\n  }\n  Vars dvars{};\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<CoordSystem>(make_not_null(&dvars), vars, central_log_enthalpy,\n                            equation_of_state);\n  double initial_step =\n      -std::min(std::abs(1.0 / dvars[0]), std::abs(1.0 / dvars[1]));\n  if constexpr (CoordSystem == TovCoordinates::Isotropic) {\n    initial_step = -std::min(std::abs(initial_step), std::abs(1.0 / dvars[2]));\n  }\n  using StateDopri5 = boost::numeric::odeint::runge_kutta_dopri5<Vars>;\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  IntegralObserver<CoordSystem> observer{};\n  boost::numeric::odeint::integrate_adaptive(\n      dopri5,\n      [&equation_of_state](const Vars& local_vars, Vars& local_dvars,\n                           const double local_enthalpy) {\n        return lindblom_rhs<CoordSystem>(&local_dvars, local_vars,\n                                         local_enthalpy, equation_of_state);\n      },\n      vars, 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  injection_energy_ = sqrt(1. - 2. * total_mass_ / outer_radius_);\n\n  if constexpr (CoordSystem == TovCoordinates::Isotropic) {\n    // Transform outer radius to isotropic\n    const double outer_areal_radius = outer_radius_;\n    outer_radius_ = 0.5 * (outer_areal_radius - total_mass_ +\n                           sqrt(square(outer_areal_radius) -\n                                2. * total_mass_ * outer_areal_radius));\n\n    // Match conformal factor to exterior solution\n    const double outer_conformal_factor =\n        1.0 + 0.5 * total_mass_ / outer_radius_;\n    const double matching_constant =\n        outer_conformal_factor / observer.conformal_factor.back();\n    const size_t num_points = observer.radius.size();\n    for (size_t i = 0; i < num_points; ++i) {\n      observer.conformal_factor[i] *= matching_constant;\n      // Transform observed radius to isotropic, so we use the isotropic radius\n      // for all interpolations below\n      observer.radius[i] /= square(observer.conformal_factor[i]);\n    }\n    conformal_factor_interpolant_ = intrp::BarycentricRational(\n        observer.radius, observer.conformal_factor, 5);\n  }\n\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\nTovSolution::TovSolution(\n    const EquationsOfState::EquationOfState<true, 1>& equation_of_state,\n    const double central_mass_density, const TovCoordinates coordinate_system,\n    const double log_enthalpy_at_outer_radius, const double absolute_tolerance,\n    const double relative_tolerance)\n    : coordinate_system_(coordinate_system) {\n  if (coordinate_system_ == TovCoordinates::Schwarzschild) {\n    integrate<TovCoordinates::Schwarzschild>(\n        equation_of_state, central_mass_density, log_enthalpy_at_outer_radius,\n        absolute_tolerance, relative_tolerance);\n  } else {\n    integrate<TovCoordinates::Isotropic>(\n        equation_of_state, central_mass_density, log_enthalpy_at_outer_radius,\n        absolute_tolerance, relative_tolerance);\n  }\n}\n\ntemplate <typename DataType>\nDataType TovSolution::mass_over_radius(const DataType& r) const {\n  // Possible optimization: Support DataVector in intrp::BarycentricRational\n  auto result = make_with_value<DataType>(r, 0.);\n  for (size_t i = 0; i < get_size(r); ++i) {\n    ASSERT(\n        get_element(r, i) >= 0.0 and get_element(r, i) <= outer_radius_,\n        \"Invalid radius: \" << r << \" not in [0.0, \" << outer_radius_ << \"]\\n\");\n    get_element(result, i) = mass_over_radius_interpolant_(get_element(r, i));\n  }\n  return result;\n}\n\ntemplate <typename DataType>\nDataType TovSolution::log_specific_enthalpy(const DataType& r) const {\n  // Possible optimization: Support DataVector in intrp::BarycentricRational\n  auto result = make_with_value<DataType>(r, 0.);\n  for (size_t i = 0; i < get_size(r); ++i) {\n    ASSERT(\n        get_element(r, i) >= 0.0 and get_element(r, i) <= outer_radius_,\n        \"Invalid radius: \" << r << \" not in [0.0, \" << outer_radius_ << \"]\\n\");\n    get_element(result, i) = log_enthalpy_interpolant_(get_element(r, i));\n  }\n  return result;\n}\n\ntemplate <typename DataType>\nDataType TovSolution::conformal_factor(const DataType& r) const {\n  ASSERT(coordinate_system_ == TovCoordinates::Isotropic,\n         \"The conformal factor is computed only for isotropic coordinates.\");\n  // Possible optimization: Support DataVector in intrp::BarycentricRational\n  auto result = make_with_value<DataType>(r, 0.);\n  for (size_t i = 0; i < get_size(r); ++i) {\n    ASSERT(\n        get_element(r, i) >= 0.0 and get_element(r, i) <= outer_radius_,\n        \"Invalid radius: \" << r << \" not in [0.0, \" << outer_radius_ << \"]\\n\");\n    get_element(result, i) = conformal_factor_interpolant_(get_element(r, i));\n  }\n  return result;\n}\n\nvoid TovSolution::pup(PUP::er& p) {  // NOLINT\n  p | coordinate_system_;\n  p | outer_radius_;\n  p | total_mass_;\n  p | injection_energy_;\n  p | mass_over_radius_interpolant_;\n  p | log_enthalpy_interpolant_;\n  p | conformal_factor_interpolant_;\n}\n\n#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)\n\n#define INSTANTIATE(_, data)                                                \\\n  template DTYPE(data) TovSolution::mass_over_radius(const DTYPE(data) & r) \\\n      const;                                                                \\\n  template DTYPE(data)                                                      \\\n      TovSolution::log_specific_enthalpy(const DTYPE(data) & r) const;      \\\n  template DTYPE(data) TovSolution::conformal_factor(const DTYPE(data) & r) \\\n      const;\n\nGENERATE_INSTANTIATIONS(INSTANTIATE, (double, DataVector))\n\n#undef DTYPE\n\n}  // namespace gr::Solutions\n", "meta": {"hexsha": "2a8e61d5891b3e0f09c14b1b60e8cbabbbfa0782", "size": 11949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:17:33.000Z", "max_issues_repo_path": "src/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Tov.cpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "max_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": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["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.3682432432, "max_line_length": 80, "alphanum_fraction": 0.6901832789, "num_tokens": 3070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.03410042804365096, "lm_q1q2_score": 0.016384528587281188}}
{"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\n#include \"Exception.h\"\n#include \"JacobianInverseKinematics.h\"\n#include \"Kinematic.h\"\n#include \"Prismatic.h\"\n#include \"Revolute.h\"\n\nnamespace rl\n{\n\tnamespace mdl\n\t{\n\t\tKinematic::Kinematic() :\n\t\t\tMetric(),\n\t\t\tinvJ(),\n\t\t\tJ(),\n\t\t\tJdqd()\n\t\t{\n\t\t}\n\t\t\n\t\tKinematic::~Kinematic()\n\t\t{\n\t\t}\n\t\t\n\t\tbool\n\t\tKinematic::calculateInversePosition(const ::rl::math::Transform& x, const ::std::size_t& leaf, const ::rl::math::Real& delta, const ::rl::math::Real& epsilon, const ::std::size_t& iterations)\n\t\t{\n\t\t\tJacobianInverseKinematics ik(this);\n\t\t\tik.setDelta(delta);\n\t\t\tik.setEpsilon(epsilon);\n\t\t\tik.setIterations(iterations);\n\t\t\tik.addGoal(x, leaf);\n\t\t\treturn ik.solve();\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::calculateJacobian(const bool& inWorldFrame)\n\t\t{\n\t\t\tthis->calculateJacobian(this->J, inWorldFrame);\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::calculateJacobian(::rl::math::Matrix& J, const bool& inWorldFrame)\n\t\t{\n\t\t\tassert(J.rows() == this->getOperationalDof() * 6);\n\t\t\tassert(J.cols() == this->getDof());\n\t\t\t\n\t\t\t::rl::math::Vector tmp(this->getDof());\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->setVelocity(tmp);\n\t\t\t\tthis->forwardVelocity();\n\t\t\t\t\n\t\t\t\tfor (::std::size_t j = 0; j < this->getOperationalDof(); ++j)\n\t\t\t\t{\n\t\t\t\t\tif (inWorldFrame)\n\t\t\t\t\t{\n\t\t\t\t\t\tJ.block(j * 6, i, 3, 1) = this->getOperationalPosition(j).linear() * this->getOperationalVelocity(j).linear();\n\t\t\t\t\t\tJ.block(j * 6 + 3, i, 3, 1) = this->getOperationalPosition(j).linear() * this->getOperationalVelocity(j).angular();\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tJ.block(j * 6, i, 3, 1) = this->getOperationalVelocity(j).linear();\n\t\t\t\t\t\tJ.block(j * 6 + 3, i, 3, 1) = this->getOperationalVelocity(j).angular();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::calculateJacobianDerivative(const bool& inWorldFrame)\n\t\t{\n\t\t\tthis->calculateJacobianDerivative(this->Jdqd, inWorldFrame);\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::calculateJacobianDerivative(::rl::math::Vector& Jdqd, const bool& inWorldFrame)\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->setAcceleration(tmp);\n\t\t\tthis->forwardVelocity();\n\t\t\tthis->forwardAcceleration();\n\t\t\t\n\t\t\tfor (::std::size_t j = 0; j < this->getOperationalDof(); ++j)\n\t\t\t{\n\t\t\t\tif (inWorldFrame)\n\t\t\t\t{\n\t\t\t\t\t::rl::math::Matrix33 wR = this->getOperationalVelocity(j).angular().cross33() * this->getOperationalPosition(j).linear();\n\t\t\t\t\tJdqd.segment(j * 6, 3) = this->getOperationalPosition(j).linear() * this->getOperationalAcceleration(j).linear() + wR * this->getOperationalVelocity(j).linear();\n\t\t\t\t\tJdqd.segment(j * 6 + 3, 3) = this->getOperationalPosition(j).linear() * this->getOperationalAcceleration(j).angular() + wR * this->getOperationalVelocity(j).angular();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tJdqd.segment(j * 6, 3) = this->getOperationalAcceleration(j).linear();\n\t\t\t\t\tJdqd.segment(j * 6 + 3, 3) = this->getOperationalAcceleration(j).angular();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::calculateJacobianInverse(const ::rl::math::Real& lambda, const bool& doSvd)\n\t\t{\n\t\t\tthis->calculateJacobianInverse(this->J, this->invJ, lambda, doSvd);\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::calculateJacobianInverse(const ::rl::math::Matrix& J, ::rl::math::Matrix& invJ, const ::rl::math::Real& lambda, const bool& doSvd) const\n\t\t{\n\t\t\tif (doSvd)\n\t\t\t{\n\t\t\t\tinvJ.setZero();\n\t\t\t\t\n\t\t\t\t::Eigen::JacobiSVD<::rl::math::Matrix> svd(J, ::Eigen::ComputeFullU | ::Eigen::ComputeFullV);\n\t\t\t\t\n\t\t\t\t::rl::math::Real wMin = svd.singularValues().minCoeff();\n\t\t\t\t::rl::math::Real lambdaSqr = wMin < static_cast<::rl::math::Real>(1.0e-9) ? (1 - ::std::pow((wMin / static_cast<::rl::math::Real>(1.0e-9)), 2)) * ::std::pow(lambda, 2) : 0;\n\t\t\t\t\n\t\t\t\tfor (::std::ptrdiff_t i = 0; i < svd.nonzeroSingularValues(); ++i)\n\t\t\t\t{\n\t\t\t\t\tinvJ.noalias() += (\n\t\t\t\t\t\tsvd.singularValues()(i) / (::std::pow(svd.singularValues()(i), 2) + lambdaSqr) *\n\t\t\t\t\t\tsvd.matrixV().col(i) * svd.matrixU().col(i).transpose()\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\tinvJ = J.transpose() * (\n\t\t\t\t\tJ * J.transpose() + ::std::pow(lambda, 2) *\n\t\t\t\t\t::rl::math::Matrix::Identity(this->getOperationalDof() * 6, this->getOperationalDof() * 6)\n\t\t\t\t).inverse();\n\t\t\t}\n\t\t}\n\t\t\n\t\t::rl::math::Real\n\t\tKinematic::calculateManipulabilityMeasure() const\n\t\t{\n\t\t\treturn calculateManipulabilityMeasure(this->J);\n\t\t}\n\t\t\n\t\t::rl::math::Real\n\t\tKinematic::calculateManipulabilityMeasure(const ::rl::math::Matrix& J) const\n\t\t{\n\t\t\treturn ::std::sqrt((J * J.transpose()).determinant());\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::forwardAcceleration()\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)->forwardAcceleration();\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::forwardPosition()\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)->forwardPosition();\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::forwardVelocity()\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)->forwardVelocity();\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst ::rl::math::Matrix&\n\t\tKinematic::getJacobian() const\n\t\t{\n\t\t\treturn this->J;\n\t\t}\n\t\t\n\t\tconst ::rl::math::Vector&\n\t\tKinematic::getJacobianDerivative() const\n\t\t{\n\t\t\treturn this->Jdqd;\n\t\t}\n\t\t\n\t\tconst ::rl::math::Matrix&\n\t\tKinematic::getJacobianInverse() const\n\t\t{\n\t\t\treturn this->invJ;\n\t\t}\n\t\t\n\t\tbool\n\t\tKinematic::isSingular() const\n\t\t{\n\t\t\treturn this->isSingular(this->J);\n\t\t}\n\t\t\n\t\tbool\n\t\tKinematic::isSingular(const ::rl::math::Matrix& J) const\n\t\t{\n\t\t\t::Eigen::JacobiSVD<::rl::math::Matrix> svd(J);\n\t\t\treturn (::std::abs(svd.singularValues()(svd.singularValues().size() - 1)) > ::std::numeric_limits<::rl::math::Real>::epsilon()) ? false : true;\n\t\t}\n\t\t\n\t\tvoid\n\t\tKinematic::update()\n\t\t{\n\t\t\tMetric::update();\n\t\t\t\n\t\t\tthis->invJ = ::rl::math::Matrix::Identity(this->getDof(), 6 * this->getOperationalDof());\n\t\t\tthis->J = ::rl::math::Matrix::Identity(6 * this->getOperationalDof(), this->getDof());\n\t\t\tthis->Jdqd = ::rl::math::Vector::Zero(6 * this->getOperationalDof());\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "88101be1933bf1f0ff0fbc2452252ece6dccaf2b", "size": 7579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rl/mdl/Kinematic.cpp", "max_stars_repo_name": "Broekman/rl", "max_stars_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 568.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T03:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:12:56.000Z", "max_issues_repo_path": "src/rl/mdl/Kinematic.cpp", "max_issues_repo_name": "Broekman/rl", "max_issues_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-03-23T13:16:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T05:58:06.000Z", "max_forks_repo_path": "src/rl/mdl/Kinematic.cpp", "max_forks_repo_name": "Broekman/rl", "max_forks_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 169.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T12:59:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:44:54.000Z", "avg_line_length": 29.8385826772, "max_line_length": 193, "alphanum_fraction": 0.641509434, "num_tokens": 2331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.03410042534420531, "lm_q1q2_score": 0.016384527290255115}}
{"text": "// This file is part of MeshUtility, a collection of python mesh processing\n// utilities.\n//\n// Copyright (C) 2021 Zishun Liu <liuzishun@gmail.com>\n//\n// This Source Code Form is subject to the terms of the 3-Clause BSD License.\n// If a copy of the BSD-3-Clause was not distributed with this file, You can\n// obtain one at https://opensource.org/licenses/BSD-3-Clause.\n#include <iostream>\n\n#include <Eigen/Sparse>\n\n#include \"isocurve.h\"\n\nisocurve::isocurve(const Eigen::MatrixXd& V,\n                   const Eigen::MatrixXi& F,\n                   const Eigen::VectorXd& field)\n{\n    if (V.rows() != field.size())\n        throw std::invalid_argument( \"V.rows() != field.size()\" );\n    if (F.cols() != 3)\n        throw std::invalid_argument( \"Not a triangular mesh\" );\n\n    V_ = V;\n    F_ = F;\n    field_ = field;\n\n    mesh_.clean();\n    std::vector<EigenTriMesh::VertexHandle> vhandles(V.rows());\n    for (Eigen::Index i = 0; i < V.rows(); ++i)\n    {\n        //vhandles[i] = mesh_.add_vertex(EigenTriMesh::Point(V(i,0), V(i,1), V(i,2)));\n        vhandles[i] = mesh_.add_vertex(V.row(i));\n    }\n\n    std::vector<EigenTriMesh::VertexHandle> face_vhandles(3);\n    for (Eigen::Index i = 0; i < F.rows(); ++i)\n    {\n        face_vhandles[0] = vhandles[F(i,0)];\n        face_vhandles[1] = vhandles[F(i,1)];\n        face_vhandles[2] = vhandles[F(i,2)];\n        mesh_.add_face(face_vhandles);\n    }\n}\n\nisocurve::~isocurve(){}\n\nvoid isocurve::extract(const double val, const double eqlTol,\n                       Eigen::MatrixXd& _pts,\n                       Eigen::MatrixXi& _on_edge,\n                       Eigen::VectorXd& _ratio,\n                       std::vector<std::deque<int>>& _curve_all) const\n{\n    std::vector<Eigen::Vector3d> pts;\n    std::vector<Eigen::Vector2i> on_edge;\n    std::vector<double> ratio;\n    std::vector<Eigen::Vector2i> curve_segments;\n    std::vector<CurveSegmentDir> curve_segments_dir;\n\n    Eigen::VectorXi idxOnVerts(mesh_.n_vertices());\n    Eigen::VectorXi idxOnEdges(mesh_.n_edges());\n    idxOnVerts.fill(-1);\n    idxOnEdges.fill(-1);\n\n    collect_pts(idxOnVerts, idxOnEdges, pts, on_edge, ratio, val, eqlTol);\n\n    for (Eigen::Index i = 0; i < F_.rows(); ++i) {\n        Eigen::VectorXi fv = F_.row(i);\n        int cnt = 0;\n        for (int j = 0; j < 3; ++j) {\n            if (idxOnVerts[fv[j]] >= 0)\n                cnt++;\n        }\n        switch (cnt) {\n        case 3:\n            std::cout << \"[Warning!] Not handled: a whole triangle lays on the iso value.\" << std::endl;\n            break;\n        case 2:\n            extract_on_face_through2(static_cast<unsigned int>(i), val,\n                                     idxOnVerts, idxOnEdges,\n                                     curve_segments, curve_segments_dir);\n            break;\n        case 1:\n            extract_on_face_through1(static_cast<unsigned int>(i), val,\n                                     idxOnVerts, idxOnEdges,\n                                     curve_segments, curve_segments_dir);\n            break;\n        case 0:\n            extract_on_face_through0(static_cast<unsigned int>(i), val,\n                                     idxOnVerts, idxOnEdges,\n                                     curve_segments, curve_segments_dir);\n            break;\n        default:\n            break;\n        }\n    }\n\n    // collect results\n    _pts.resize(pts.size(), 3);\n    for (size_t i = 0; i < pts.size(); ++i) {\n        _pts.row(i) = pts[i];\n    }\n    _on_edge.resize(on_edge.size(), 2);\n    for (size_t i = 0; i < on_edge.size(); ++i) {\n        _on_edge.row(i) = on_edge[i];\n    }\n    _ratio = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(ratio.data(), ratio.size());\n\n    // collect results: topology\n    construct_topology(_curve_all, _pts.rows(), curve_segments, curve_segments_dir);\n}\n\nvoid isocurve::collect_pts(Eigen::VectorXi& idxOnVerts,\n                           Eigen::VectorXi& idxOnEdges,\n                           std::vector<Eigen::Vector3d>& pts,\n                           std::vector<Eigen::Vector2i>& on_edge,\n                           std::vector<double>& ratio,\n                           const double val, const double eqlTol) const {\n    int cntPts = 0;\n\n    for (Eigen::Index i = 0; i < V_.rows(); ++i) {\n        if (std::abs(field_[i]-val) < eqlTol) {\n            idxOnVerts[i] = cntPts;\n            cntPts++;\n            pts.push_back(V_.row(i));\n            on_edge.push_back(Eigen::Vector2i(i, i));\n            ratio.push_back(0.0);\n        }\n    }\n\n    // std::vector<bool> face_visited(mesh_.n_faces(), false);  // actually useless\n\n    for (EigenTriMesh::EdgeHandle eh : mesh_.all_edges()) {\n        EigenTriMesh::HalfedgeHandle heh = mesh_.halfedge_handle(eh, 0);\n        EigenTriMesh::VertexHandle vh0 = mesh_.from_vertex_handle(heh);\n        EigenTriMesh::VertexHandle vh1 = mesh_.to_vertex_handle(heh);\n        if (idxOnVerts[vh0.idx()] >= 0 || idxOnVerts[vh1.idx()] >= 0) {\n            continue;\n        }\n        double x0 = field_[vh0.idx()];\n        double x1 = field_[vh1.idx()];\n        if ( (x0 < val && x1 > val) || (x0 > val && x1 < val) ) {\n            double t0 = std::abs(x0-val);\n            double t1 = std::abs(x1-val);\n            double t = t0+t1;\n            t0 /= t;\n            t1 /= t;\n            pts.push_back(t1*V_.row(vh0.idx())+t0*V_.row(vh1.idx()));\n            on_edge.push_back(Eigen::Vector2i(vh0.idx(), vh1.idx()));\n            ratio.push_back(t0);\n            idxOnEdges[eh.idx()] = cntPts;\n            cntPts++;\n        }\n    }\n}\n\nvoid isocurve::extract_on_face_through2(const unsigned int i,\n                                        const double val,\n                                        const Eigen::VectorXi& idxOnVerts,\n                                        const Eigen::VectorXi& idxOnEdges,\n                                        std::vector<Eigen::Vector2i>& curve_segments,\n                                        std::vector<CurveSegmentDir>& curve_segments_dir\n                                        ) const {\n    EigenTriMesh::FaceHandle fh = mesh_.face_handle(i);\n    EigenTriMesh::HalfedgeHandle heh;\n    EigenTriMesh::VertexHandle vh0;\n    EigenTriMesh::VertexHandle vh1;\n    // find heh\n    for (EigenTriMesh::HalfedgeHandle h : mesh_.fh_range(fh)) {\n        vh0 = mesh_.from_vertex_handle(h);\n        vh1 = mesh_.to_vertex_handle(h);\n        if (idxOnVerts[vh0.idx()] >= 0 && idxOnVerts[vh1.idx()] >= 0) {\n            heh = h;\n            break;\n        }\n    }\n\n    //        vh1\n    //        /|\\\n    //       / | \\\n    //      /  |  \\\n    // vh2 /---|---\\ vh3\n    //        vh0\n\n    EigenTriMesh::HalfedgeHandle heh2 = mesh_.next_halfedge_handle(heh);\n    EigenTriMesh::VertexHandle vh2 = mesh_.to_vertex_handle(heh2);\n    if (field_[vh2.idx()] < val) {\n        curve_segments.push_back(Eigen::Vector2i(idxOnVerts[vh0.idx()],\n                                 idxOnVerts[vh1.idx()]));\n    }else{  // field_[vh2.idx()] > val. Cannot be == val\n        curve_segments.push_back(Eigen::Vector2i(idxOnVerts[vh1.idx()],\n                                 idxOnVerts[vh0.idx()]));\n    }\n\n    EigenTriMesh::HalfedgeHandle heh1 = mesh_.opposite_halfedge_handle(heh);\n    if (mesh_.is_boundary(heh1)) {\n        curve_segments_dir.push_back(CurveSegmentDir::Determined);\n        return;\n    }\n    // not boundary\n    EigenTriMesh::HalfedgeHandle heh3 = mesh_.next_halfedge_handle(heh1);\n    EigenTriMesh::VertexHandle vh3 = mesh_.to_vertex_handle(heh3);\n    if ( idxOnVerts[vh3.idx()] ||\n         (field_[vh2.idx()] < val && field_[vh3.idx()] > val) ||\n         (field_[vh2.idx()] > val && field_[vh3.idx()] < val) ) {\n        curve_segments_dir.push_back(CurveSegmentDir::Determined);\n        return;\n    }\n\n    std::cout << \"[Warning!] Local extrema edge!\" << std::endl;\n    curve_segments_dir.push_back(CurveSegmentDir::Flexible);\n    return;\n}\n\nvoid isocurve::extract_on_face_through1(const unsigned int i,\n                                        const double val,\n                                        const Eigen::VectorXi& idxOnVerts,\n                                        const Eigen::VectorXi& idxOnEdges,\n                                        std::vector<Eigen::Vector2i>& curve_segments,\n                                        std::vector<CurveSegmentDir>& curve_segments_dir\n                                        ) const {\n    auto fh = mesh_.face_handle(i);\n    for (EigenTriMesh::HalfedgeHandle heh : mesh_.fh_range(fh)) {\n        // auto eh = mesh_.edge_handle(heh);\n        auto vh = mesh_.from_vertex_handle(heh);\n        if (idxOnVerts[vh.idx()] < 0)\n        {\n            continue;\n        }\n        auto heh1 = mesh_.next_halfedge_handle(heh);\n        auto eh1 = mesh_.edge_handle(heh1);\n        if (idxOnEdges[eh1.idx()] < 0) {\n            // only passes a vertex, does not enter this triangle.\n            return;\n        }\n        auto vh1 = mesh_.to_vertex_handle(heh);\n        if (field_[vh1.idx()] > val) {\n            curve_segments.push_back(Eigen::Vector2i(idxOnVerts[vh.idx()],\n                                     idxOnEdges[eh1.idx()]));\n            curve_segments_dir.push_back(CurveSegmentDir::Determined);\n        } else {\n            curve_segments.push_back(Eigen::Vector2i(idxOnEdges[eh1.idx()],\n                                     idxOnVerts[vh.idx()]));\n            curve_segments_dir.push_back(CurveSegmentDir::Determined);\n        }\n        return;\n    }\n}\n\nvoid isocurve::extract_on_face_through0(const unsigned int i,\n                                        const double val,\n                                        const Eigen::VectorXi& idxOnVerts,\n                                        const Eigen::VectorXi& idxOnEdges,\n                                        std::vector<Eigen::Vector2i>& curve_segments,\n                                        std::vector<CurveSegmentDir>& curve_segments_dir\n                                        ) const {\n    auto fh = mesh_.face_handle(i);\n    for (EigenTriMesh::HalfedgeHandle heh : mesh_.fh_range(fh)) {\n        auto eh = mesh_.edge_handle(heh);\n        auto vh = mesh_.from_vertex_handle(heh);\n        if (idxOnEdges[eh.idx()] < 0 || field_[vh.idx()] > val) {\n            continue;\n        }\n        auto heh1 = mesh_.next_halfedge_handle(heh);\n        auto eh1 = mesh_.edge_handle(heh1);\n        if (idxOnEdges[eh1.idx()] >= 0) {\n            curve_segments.push_back(Eigen::Vector2i(idxOnEdges[eh.idx()],\n                                     idxOnEdges[eh1.idx()]));\n            curve_segments_dir.push_back(CurveSegmentDir::Determined);\n            return;\n        }\n        // actually here should have an \"else\"\n        heh1 = mesh_.next_halfedge_handle(heh1);\n        eh1 = mesh_.edge_handle(heh1);\n        if (idxOnEdges[eh1.idx()] >= 0) {\n            curve_segments.push_back(Eigen::Vector2i(idxOnEdges[eh.idx()],\n                                     idxOnEdges[eh1.idx()]));\n            curve_segments_dir.push_back(CurveSegmentDir::Determined);\n            return;\n        }\n        // indeed should have an \"else\"\n        throw std::invalid_argument( \"Isocurve cuts through one edge. Not possible!\" );\n    }\n}\n\nvoid isocurve::construct_topology(std::vector<std::deque<int>>& curve_all,\n                                  const Eigen::Index num_pts,\n                                  std::vector<Eigen::Vector2i>& curve_segments,\n                                  const std::vector<CurveSegmentDir>& curve_segments_dir) const {\n\n    typedef Eigen::Triplet<int> T;\n\n    // construct graph\n    std::vector<T> triplets;\n    for (size_t i = 0; i < curve_segments.size(); ++i) {\n        int i0 = curve_segments[i][0];\n        int i1 = curve_segments[i][1];\n        switch (curve_segments_dir[i]) {\n        case CurveSegmentDir::Determined:\n            triplets.push_back(T(i0, i1, 1));\n            triplets.push_back(T(i1, i0, -1));\n            break;\n        case CurveSegmentDir::Flexible:\n            triplets.push_back(T(i0, i1, 2));\n            triplets.push_back(T(i1, i0, 2));\n            break;\n        //default:\n        //    break;\n        }\n    }\n\n    SpMat G(num_pts,num_pts);\n    G.setFromTriplets(triplets.begin(), triplets.end());\n\n    // std::vector<int> pts_directed(num_pts, 0);\n    // std::vector<int> pts_ends;\n\n    // check manifoldness\n    std::vector<int> neighbors;\n    std::vector<int> neighbor_tags;\n    for (int k=0; k < G.outerSize(); ++k) {\n        neighbors.clear();\n        neighbor_tags.clear();\n        for (SpMat::InnerIterator it(G,k); it; ++it)\n        {\n            neighbors.push_back(it.col());\n            neighbor_tags.push_back(it.value());\n//            if (it.value() == 1 || it.value() == -1) {\n//                pts_directed[k] = 1;\n//            }\n        }\n        switch (neighbors.size()) {\n        case 0:\n            std::cout << \"[Warning!] Isolated point.\" << std::endl;\n            break;\n        case 1:\n//        if (neighbors.size() == 1) {\n//            pts_ends.push_back(k);\n//        }\n            break;\n        case 2:\n            if (neighbor_tags[0] == neighbor_tags[1] && std::abs(neighbor_tags[1]) == 1) {\n                // both 1 or both -1\n                std::cout << \"[Warning!] Non-manifold curve.\" << std::endl;\n            }\n            break;\n        default:\n            std::cout << \"[Warning!] Non-manifold. more than 2 neighbors.\" << std::endl;\n            break;\n        }\n    }\n    // sm1.coeffRef(i,j) = v_ij;\n    // heads = Eigen::Map<Eigen::VectorXi, Eigen::Unaligned>(heads_vec.data(), heads_vec.size());\n\n    std::vector<int> pts_visited(num_pts, 0);\n    //std::vector<std::deque<int>> curve_all;\n    //std::cout << pts_visited[0] << std::endl;\n    int start = find_zero(pts_visited);\n    //std::cout << \"start\" << start << std::endl;\n    //std::vector<std::deque<int>> curve_all_t;\n    while (start >= 0) {\n        std::deque<int> curve;\n        curve.push_back(start);\n        pts_visited[start] = 1;\n        int invert = extend(curve, G, pts_visited);\n        if (invert == 1)\n            std::reverse(curve.begin(), curve.end());\n        curve_all.push_back(curve);\n\n        start = find_zero(pts_visited);\n    }\n\n//    triplets.clear();\n//    for (size_t i = 0; i < curve_all.size(); ++i) {\n//        for (size_t j = 0; j < curve_all[i].size()-1; ++j) {\n//            triplets.push_back(T(curve_all_t[i][j], curve_all_t[i][j+1], 1));\n//            triplets.push_back(T(curve_all_t[i][j], curve_all_t[i][j+1], -1));\n//        }\n//    }\n\n//    SpMat G1(num_pts,num_pts);\n//    G1.setFromTriplets(triplets.begin(), triplets.end());\n\n//    // compare G and G1\n\n}\n\ninline int isocurve::find_zero(const std::vector<int>& vec) const {\n    for (size_t i = 0; i < vec.size(); ++i) {\n        if (vec[i] == 0)\n            return i;\n    }\n    return -1;\n}\n\nint isocurve::extend(std::deque<int>& curve, const SpMat& G, std::vector<int>& pts_visited) const {\n    // return value:\n    // 1: invert; 0: flexible; -1: not invert.\n\n    std::vector<int> neighbors;\n    //std::vector<int> neighbor_tags;\n    for (SpMat::InnerIterator it(G, curve[0]); it; ++it) {\n        neighbors.push_back(it.col());\n        //neighbor_tags.push_back(it.value());\n    }\n    if (neighbors.size() == 0) {\n        // curve[0] already marked visited.\n        return 0;\n    }\n\n    // not really front/back\n    int invert = extend_front(curve, neighbors[0], G, pts_visited);\n    //if (neighbors.size() == 2 && curve[0] != *curve.end()) {\n    if (neighbors.size() == 2 && curve[0] != curve.back()) {\n        // i.e. not a ring\n        int invert1 = extend_back(curve, neighbors[1], G, pts_visited);\n        if (invert1 + invert == 0 && invert != 0) {\n            // 1 and -1\n            printf(\"[Warning!] Complex direction!\");\n        }\n        invert = std::max(invert, invert1);\n    }\n\n    return invert;\n}\n\nint isocurve::extend_front(std::deque<int>& curve, int front, const SpMat& G, std::vector<int>& visited) const {\n    int invert = 0;\n\n    //int prev = *curve.end();\n    int prev = curve[0];\n    int now = front;\n    if (visited[now] == 1)\n        return invert;\n    while (true) {\n        visited[now] = 1;\n        curve.push_back(now);\n        bool found_next = false;\n        for (SpMat::InnerIterator it(G, now); it; ++it) {\n            int n = it.col();\n            if (n != prev) {\n                prev = now;\n                now = n;\n                found_next = true;\n                if (it.value() == 1) {\n                    if (invert == 1)\n                        printf(\"[Warning!] Complex direction!\");\n                    invert = -1;  // not invert\n                }\n                if (it.value() == -1) {\n                    if (invert == -1)\n                        printf(\"[Warning!] Complex direction!\");\n                    invert = 1;\n                }\n                break;\n            }\n        }\n        if (!found_next)\n            break;\n        if (visited[now] == 1) {  // ring\n            curve.push_back(now);\n            break;\n        }\n    }\n    return invert;\n}\n\nint isocurve::extend_back(std::deque<int>& curve, int back, const SpMat& G, std::vector<int>& visited) const {\n    // must not be a ring\n\n    int invert = 0;\n\n    int prev = curve[0];\n    int now = back;\n    while (visited[now] != 1) {\n        visited[now] = 1;\n        curve.push_front(now);\n        for (SpMat::InnerIterator it(G, now); it; ++it) {\n            int n = it.col();\n            if (n != prev) {\n                prev = now;\n                now = n;\n                if (it.value() == 1) {\n                    if (invert == -1)\n                        printf(\"[Warning!] Complex direction!\");\n                    invert = 1;\n                }\n                if (it.value() == -1) {\n                    if (invert == 1)\n                        printf(\"[Warning!] Complex direction!\");\n                    invert = -1;\n                }\n                break;\n            }\n        }\n    }\n    return invert;\n}\n\nstd::tuple<Eigen::MatrixXd, Eigen::MatrixXi, Eigen::VectorXd, std::vector<std::deque<int>>>\nisocurve::extract(const double val, const double eqlTol) {\n    Eigen::MatrixXd pts;\n    Eigen::MatrixXi on_edge;\n    Eigen::VectorXd ratio;\n    std::vector<std::deque<int>> curves_all;\n    extract(val, eqlTol, pts, on_edge, ratio, curves_all);\n    // std::cout << curves_all.size() << std::endl;\n    auto res = std::make_tuple(pts, on_edge, ratio, curves_all);\n    return res;\n}\n", "meta": {"hexsha": "44583d0a26c03482b2a0e5c9f3b4dc1f76bf3e1c", "size": 18338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pyisocurve/isocurve.cpp", "max_stars_repo_name": "zishun/MeshUtility", "max_stars_repo_head_hexsha": "571132cf546b7dac40577cf6034b11f26386670b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-05-05T17:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T09:46:55.000Z", "max_issues_repo_path": "src/pyisocurve/isocurve.cpp", "max_issues_repo_name": "zishun/MeshUtility", "max_issues_repo_head_hexsha": "571132cf546b7dac40577cf6034b11f26386670b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T09:11:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T12:15:56.000Z", "max_forks_repo_path": "src/pyisocurve/isocurve.cpp", "max_forks_repo_name": "zishun/MeshUtility", "max_forks_repo_head_hexsha": "571132cf546b7dac40577cf6034b11f26386670b", "max_forks_repo_licenses": ["BSD-3-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.8864970646, "max_line_length": 112, "alphanum_fraction": 0.5186497982, "num_tokens": 4647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.036769462513209006, "lm_q1q2_score": 0.016381881537165008}}
{"text": "//   GAMBIT: Global and Modular BSM Inference Tool\n//   *********************************************\n///  \\file\n///\n//\n///  *********************************************\n///\n///  Authors:\n///  <!-- add name and date if you modify -->\n///\n///  \\author Ben Farmer\n///          (benjamin.farmer@fysik.su.se)\n///  \\date 2015 Apr\n///\n///  \\author Pat Scott\n///          (p.scott@imperial.ac.uk)\n///  \\date 2016 Oct\n///\n///  *********************************************\n\n#include \"gambit/Models/SimpleSpectra/MSSMSimpleSpec.hpp\"\n#include \"gambit/Elements/mssm_slhahelp.hpp\"\n#include \"gambit/Utils/util_functions.hpp\"\n#include \"gambit/Utils/variadic_functions.hpp\"\n#include \"gambit/Logs/logger.hpp\"\n\n#include <math.h>\n#include <boost/lexical_cast.hpp>\n\nusing namespace SLHAea;\n\nnamespace Gambit\n{\n\n      /// Helper function for sorting int, double pairs according to the double\n      bool orderer (std::pair<int, double> a, std::pair<int, double> b) { return a.second < b.second; }\n\n      /// @{ Member functions for SLHAeaModel class\n\n      /// Default Constructor\n      MSSMea::MSSMea()\n        : SLHAeaModel()\n      {}\n\n      /// Constructor via SLHAea object\n      MSSMea::MSSMea(const SLHAea::Coll& input)\n        : SLHAeaModel(input)\n      {\n        std::map<int, int>& slha1to2 = PDG_translation_map;\n        str blocks[4] = {\"DSQMIX\", \"USQMIX\", \"SELMIX\", \"SNUMIX\"};\n        str gen3mix[3] = {\"SBOTMIX\", \"STOPMIX\", \"STAUMIX\"};\n        logger() << LogTags::utils;\n\n        // Work out if this SLHAea object is SLHA1 or SLHA2\n        if (data.find(blocks[0]) == data.end() or\n            data.find(blocks[1]) == data.end() or\n            data.find(blocks[2]) == data.end() or\n            data.find(blocks[3]) == data.end() )\n        {\n          if (data.find(gen3mix[0]) == data.end() or\n              data.find(gen3mix[1]) == data.end() or\n              data.find(gen3mix[2]) == data.end() )\n          {\n            utils_error().raise(LOCAL_INFO, \"Input SLHA data appears to be neither SLHA1 nor SLHA2.\");\n          }\n          logger() << \"Input SLHA for setting up simple spectrum is SLHA1.  You old dog.\" << EOM;\n\n          // Get scale, needed for specifying SLHA2 blocks\n          /// TODO: Currently assumes all blocks at same scale. Should check if this\n          /// is true.\n          double scale = 0.0;\n          try\n          {\n            scale = SLHAea::to<double>(data.at(\"GAUGE\").find_block_def()->at(3));\n          }\n          catch (const std::out_of_range& e)\n          {\n            std::ostringstream errmsg;\n            errmsg << \"Could not find block \\\"GAUGE\\\" in SLHAea object (required to retrieve scale Q). Received out_of_range error with message: \" << e.what();\n            utils_error().raise(LOCAL_INFO,errmsg.str());\n          }\n\n          //Looks like it is SLHA1, so convert it to SLHA2.\n          int lengths[4] = {6, 6, 6, 3};\n          str names[4] = {\"~d_\", \"~u_\", \"~l_\", \"~nu_\"};\n          std::vector<int> pdg[4];\n          std::vector< std::pair<int, double> > masses[4];\n          pdg[0] = initVector<int>(1000001, 1000003, 1000005, 2000001, 2000003, 2000005); // d-type squarks\n          pdg[1] = initVector<int>(1000002, 1000004, 1000006, 2000002, 2000004, 2000006); // u-type squarks\n          pdg[2] = initVector<int>(1000011, 1000013, 1000015, 2000011, 2000013, 2000015); // sleptons\n          pdg[3] = initVector<int>(1000012, 1000014, 1000016);                            // sneutrinos\n          for (int j = 0; j < 4; j++)\n          {\n            // Get the masses\n            for (int i = 0; i < lengths[j]; i++) masses[j].push_back(std::pair<int, double>(pdg[j][i], getdata(\"MASS\",pdg[j][i])));\n\n            // Sort them\n            std::sort(masses[j].begin(), masses[j].end(), orderer);\n\n            // Rewrite them in correct order, and populate the pdg-pdg maps\n            for (int i = 0; i < lengths[j]; i++)\n            {\n              //data[\"MASS\"][pdg[j][i]][1] = boost::lexical_cast<str>(masses[j][i].second);\n              //data[\"MASS\"][pdg[j][i]][2] = \"# \"+names[j]+boost::lexical_cast<str>(i+1);\n              str masspdg = boost::lexical_cast<str>(masses[j][i].second);\n              str comment = \"# \"+names[j]+boost::lexical_cast<str>(i+1);\n              SLHAea_add(data, \"MASS\", pdg[j][i], masspdg, comment, true);\n              slha1to2[masses[j][i].first] = pdg[j][i];\n            }\n\n            // Write the mixing block.  i is the SLHA2 index, k is the SLHA1 index.\n            //data[blocks[j]][\"\"] << \"BLOCK\" << blocks[j];\n            SLHAea_check_block(data, blocks[j]);\n            for (int i = 0; i < lengths[j]; i++) for (int k = 0; k < lengths[j]; k++)\n            {\n              double datum;\n              if (lengths[j] == 3 or (k != 2 and k != 5)) // first or second generation (or neutrinos)\n              {\n                datum = (slha1to2.at(pdg[j][k]) == pdg[j][i]) ? 1.0 : 0.0;\n              }\n              else // third generation => need to use the 2x2 SLHA1 mixing matrices.\n              {\n                double family_index = 0;\n                if (k == 2)\n                {\n                  if (slha1to2.at(pdg[j][k]) == pdg[j][i]) family_index = 1;\n                  else if (slha1to2.at(pdg[j][5]) == pdg[j][i]) family_index = 2;\n                }\n                else if (k == 5)\n                {\n                  if (slha1to2.at(pdg[j][k]) == pdg[j][i]) family_index = 2;\n                  else if (slha1to2.at(pdg[j][2]) == pdg[j][i]) family_index = 1;\n                }\n                if (family_index > 0)\n                {\n                  datum = getdata(gen3mix[j], family_index, (k+1)/3);\n                }\n                else datum = 0.0;\n              }\n              //data[blocks[j]][\"\"] << i+1 << k+1 << datum << \"# \"+blocks[j]+boost::lexical_cast<str>(i*10+k+11);\n              SLHAea_add(data, blocks[j], i+1, k+1, datum, \"# \"+blocks[j]+boost::lexical_cast<str>(i*10+k+11), true);\n            }\n\n          }\n          // Now deal with MSOFT --> SLHA2 soft mass matrix blocks\n          // (inverse of retrieval code in add_MSSM_spectrum_to_SLHAea) \n          sspair M[5] = {sspair(\"MSL2\",\"ml2\"), sspair(\"MSE2\",\"me2\"), sspair(\"MSQ2\",\"mq2\"), sspair(\"MSU2\",\"mu2\"), sspair(\"MSD2\",\"md2\")};\n          for (int k=0;k<5;k++)\n          {\n            std::string block(M[k].first);\n            if(not SLHAea_block_exists(data, block)) SLHAea_add_block(data, block, scale); //TODO: maybe just always delete and replace\n            for(int i=1;i<4;i++) for(int j=1;j<4;j++)\n            {\n              std::ostringstream comment;\n              comment << block << \"(\" << i << \",\" << j << \")\";\n              double entry;\n              if(i==j)\n              {\n                entry = getdata(\"MSOFT\",30+3*k+i+(k>1?4:0)); // black magic to get correct index in MSOFT matching diagonal elements\n              }\n              else\n              {\n                // Everything off-diagonal is zero in SLHA1\n                entry = 0;\n              }\n              //data[block][\"\"] << i << j << entry*entry << \"# \"+comment.str();\n              SLHAea_add(data, block, i, j, entry*entry, \"# \"+comment.str(), true);\n            }\n          }\n\n          // Yukawa and trilinear blocks.  YU, YD and YE, plus [YU, YD and YE; SLHA1 only], or [TU, TD and TE; SLHA2 only].\n          sspair A[3] = {sspair(\"AU\",\"Au\"), sspair(\"AD\",\"Ad\"), sspair(\"AE\",\"Ae\")};\n          sspair Y[3] = {sspair(\"YU\",\"Yu\"), sspair(\"YD\",\"Yd\"), sspair(\"YE\",\"Ye\")};\n          sspair T[3] = {sspair(\"TU\",\"TYu\"), sspair(\"TD\",\"TYd\"), sspair(\"TE\",\"TYe\")};\n          for (int k=0;k<3;k++)\n          {\n            SLHAea_check_block(data, A[k].first);\n            SLHAea_check_block(data, Y[k].first);\n            SLHAea_check_block(data, T[k].first); // TODO: should delete superceded slha1 \"A\" blocks?\n            for(int i=1;i<4;i++)\n            {\n              for(int j=1;j<4;j++)\n              {\n                std::ostringstream comment;\n                comment << \"(\" << i << \",\" << j << \")\";\n                // SLHA1 has only diagonal elements in Y and A. We should fill them out fully.\n                // Assume missing diagonal elements are also zero.\n                double Yentry;\n                double Aentry;\n                if(i==j)\n                {\n                  if(SLHAea_check_block(data,Y[k].first,i,j))\n                  {\n                    Yentry = getdata(Y[k].first,i,j);\n                  }\n                  else\n                  {\n                    Yentry = 0;\n                  }\n\n                  if(SLHAea_check_block(data,A[k].first,i,j))\n                  {\n                    Aentry = getdata(A[k].first,i,j);\n                  }\n                  else\n                  {\n                    Aentry = 0;\n                  }\n                }\n                else\n                {\n                  Yentry = 0;\n                  Aentry = 0;\n                }\n              \n                double Tentry = Aentry * Yentry;\n                SLHAea_add(data, Y[k].first, i, j, Yentry, \"# \"+Y[k].first+\"_\"+comment.str(), true);\n                SLHAea_add(data, A[k].first, i, j, Aentry, \"# \"+A[k].first+\"_\"+comment.str(), true);\n                SLHAea_add(data, T[k].first, i, j, Tentry, \"# \"+T[k].first+\"_\"+comment.str(), true);\n              }\n            }\n          }\n\n\n        }\n\n        else logger() << \"Input SLHA data for setting up simple spectrum is SLHA2.  *living in the future*\" << EOM;\n        // In the end, we should always have converted to SLHA2 by now, so set this as the internally-tracked version.\n        wrapped_slha_version = 2;\n      }\n\n      /// @{ Getters for MSSM information\n      double MSSMea::get_Mu()      const{ return getdata(\"HMIX\",1); } // mu(Q) DRbar\n      double MSSMea::get_tanbeta() const{ return getdata(\"HMIX\",2); } // tan beta(Q) DRbar ( = vu/vd)\n      double MSSMea::get_tanbeta_mZ() const{ return getdata(\"MINPAR\",3); } // tan beta(mZ) DRbar\n      double MSSMea::get_v()       const{ return getdata(\"HMIX\",3); } // v = sqrt(vd^2 + vu^2) DRbar\n      double MSSMea::get_mA2()     const{ return getdata(\"HMIX\",4); } // m^2_A=[m3^2/cosBsinB](Q) DRbar, tree\n      ////// THESE ARE NOT SLHA! Therefore cannot rely on them being in the SLHAea object.\n      ////// But we can compute them instead.\n      // double MSSMea::get_BMu()     const { return getdata(\"HMIX\",101); }\n      // double MSSMea::get_vd()      const { return getdata(\"HMIX\",102); }\n      // double MSSMea::get_vu()      const { return getdata(\"HMIX\",103); }\n      ///////\n      double MSSMea::get_BMu() const \n      {\n        double tb = get_tanbeta();\n        double cb = cos(atan(tb));\n        double sb = sin(atan(tb));\n        return get_mA2() * (sb * cb);\n      }\n      double MSSMea::get_vd() const \n      {\n        double v = get_v();\n        double tb = get_tanbeta();\n        return sqrt(abs( v*v / ( tb*tb + 1 ) ));\n      }\n      double MSSMea::get_vu() const\n      {\n        double v = get_v();\n        double itb = 1./get_tanbeta();\n        return sqrt(abs( v*v / ( itb*itb + 1 ) )); \n      }\n\n      double MSSMea::get_MassB () const { return getdata(\"MSOFT\",1); }\n      double MSSMea::get_MassWB() const { return getdata(\"MSOFT\",2); }\n      double MSSMea::get_MassG () const { return getdata(\"MSOFT\",3); }\n      double MSSMea::get_mHd2() const { return getdata(\"MSOFT\",21); }\n      double MSSMea::get_mHu2() const { return getdata(\"MSOFT\",22); }\n\n      double MSSMea::get_mq2(int i, int j) const { return getdata(\"MSQ2\",i,j); }\n      double MSSMea::get_ml2(int i, int j) const { return getdata(\"MSL2\",i,j); }\n      double MSSMea::get_md2(int i, int j) const { return getdata(\"MSD2\",i,j); }\n      double MSSMea::get_mu2(int i, int j) const { return getdata(\"MSU2\",i,j); }\n      double MSSMea::get_me2(int i, int j) const { return getdata(\"MSE2\",i,j); }\n\n      double MSSMea::get_TYd(int i, int j) const { return getdata(\"Td\",i,j); }\n      double MSSMea::get_TYu(int i, int j) const { return getdata(\"Tu\",i,j); }\n      double MSSMea::get_TYe(int i, int j) const { return getdata(\"Te\",i,j); }\n\n      double MSSMea::get_Yd(int i, int j) const { return getdata(\"Yd\",i,j); }\n      double MSSMea::get_Yu(int i, int j) const { return getdata(\"Yu\",i,j); }\n      double MSSMea::get_Ye(int i, int j) const { return getdata(\"Ye\",i,j); }\n\n      double MSSMea::get_g1() const { return getdata(\"GAUGE\",1)/sqrt(3./5.); } // Convert from gy (in SLHAea object) to g1\n      double MSSMea::get_g2() const { return getdata(\"GAUGE\",2); }\n      double MSSMea::get_g3() const { return getdata(\"GAUGE\",3); }\n      double MSSMea::get_sinthW2_DRbar() const\n      {\n        double sg1 = 0.6 * Utils::sqr(get_g1());\n        return sg1 / (sg1 + Utils::sqr(get_g2()));\n      }\n\n      double MSSMea::get_MGlu_pole() const { return getdata(\"MASS\",1000021); }\n\n      double MSSMea::get_Mhh_pole_slha(int i) const\n      {\n         if      (i==1){ return getdata(\"MASS\",25); } // Neutral Higgs(1)\n         else if (i==2){ return getdata(\"MASS\",35); } // Neutral Higgs(2)\n         else { utils_error().raise(LOCAL_INFO,\"Invalid index input to get_Mhh_pole_slha! Please check index range limits in wrapper SubSpectrum class!\"); return -1; } // Should not return.\n      }\n      double MSSMea::get_MAh_pole () const { return getdata(\"MASS\",36); }\n      double MSSMea::get_MHpm_pole() const { return getdata(\"MASS\",37); }\n      double MSSMea::get_MW_pole()    const { return getdata(\"MASS\",24); } // REQUIRED output of MSSM-compatible subspectrum\n\n      double MSSMea::get_MCha_pole_slha(int i) const\n      {\n         if      (i==1){ return getdata(\"MASS\",1000024); } // Chargino(1)\n         else if (i==2){ return getdata(\"MASS\",1000037); } // Chargino(2)\n         else { utils_error().raise(LOCAL_INFO,\"Invalid index input to get_MCha_pole_slha! Please check index range limits in wrapper SubSpectrum class!\"); return -1; } // Should not return.\n      }\n      double MSSMea::get_MSd_pole_slha(int i) const\n      {\n         static std::map<int,int> match;\n\n         if      (i==1){ return getdata(\"MASS\",1000001); } // d-type squark(1)\n         else if (i==2){ return getdata(\"MASS\",1000003); } // d-type squark(2)\n         else if (i==3){ return getdata(\"MASS\",1000005); } // d-type squark(3)\n         else if (i==4){ return getdata(\"MASS\",2000001); } // d-type squark(4)\n         else if (i==5){ return getdata(\"MASS\",2000003); } // d-type squark(5)\n         else if (i==6){ return getdata(\"MASS\",2000005); } // d-type squark(6)\n         else { utils_error().raise(LOCAL_INFO,\"Invalid index input to get_MSd_pole_slha! Please check index range limits in wrapper SubSpectrum class!\"); return -1; } // Should not return.\n      }\n      double MSSMea::get_MSu_pole_slha(int i) const\n      {\n         if      (i==1){ return getdata(\"MASS\",1000002); } // u-type squark(1)\n         else if (i==2){ return getdata(\"MASS\",1000004); } // u-type squark(2)\n         else if (i==3){ return getdata(\"MASS\",1000006); } // u-type squark(3)\n         else if (i==4){ return getdata(\"MASS\",2000002); } // u-type squark(4)\n         else if (i==5){ return getdata(\"MASS\",2000004); } // u-type squark(5)\n         else if (i==6){ return getdata(\"MASS\",2000006); } // u-type squark(6)\n         else { utils_error().raise(LOCAL_INFO,\"Invalid index input to get_MSd_pole_slha! Please check index range limits in wrapper SubSpectrum class!\"); return -1; } // Should not return.\n      }\n      double MSSMea::get_MSe_pole_slha(int i) const\n      {\n         if      (i==1){ return getdata(\"MASS\",1000011); } // charged slepton(1)\n         else if (i==2){ return getdata(\"MASS\",1000013); } // charged slepton(2)\n         else if (i==3){ return getdata(\"MASS\",1000015); } // charged slepton(3)\n         else if (i==4){ return getdata(\"MASS\",2000011); } // charged slepton(4)\n         else if (i==5){ return getdata(\"MASS\",2000013); } // charged slepton(5)\n         else if (i==6){ return getdata(\"MASS\",2000015); } // charged slepton(6)\n         else { utils_error().raise(LOCAL_INFO,\"Invalid index input to get_MSd_pole_slha! Please check index range limits in wrapper SubSpectrum class!\"); return -1; } // Should not return.\n      }\n      double MSSMea::get_MSv_pole_slha(int i) const\n      {\n         if      (i==1){ return getdata(\"MASS\",1000012); } // Sneutrino(1)\n         else if (i==2){ return getdata(\"MASS\",1000014); } // Sneutrino(2)\n         else if (i==3){ return getdata(\"MASS\",1000016); } // Sneutrino(3)\n         else { utils_error().raise(LOCAL_INFO,\"Invalid index input to get_MSd_pole_slha! Please check index range limits in wrapper SubSpectrum class!\"); return -1; } // Should not return.\n      }\n      double MSSMea::get_MChi_pole_slha(int i) const\n      {\n         if      (i==1){ return getdata(\"MASS\",1000022); } // Neutralino(1)\n         else if (i==2){ return getdata(\"MASS\",1000023); } // Neutralino(2)\n         else if (i==3){ return getdata(\"MASS\",1000025); } // Neutralino(3)\n         else if (i==4){ return getdata(\"MASS\",1000035); } // Neutralino(4)\n         else { utils_error().raise(LOCAL_INFO,\"Invalid index input to get_MChi_pole_slha! Please check index range limits in wrapper SubSpectrum class!\"); return -1; } // Should not return.\n      }\n\n      // Pole Mixings\n      double MSSMea::get_ZD_pole_slha(int i, int j) const { return getdata(\"DSQMIX\",i,j); }\n      double MSSMea::get_ZU_pole_slha(int i, int j) const { return getdata(\"USQMIX\",i,j); }\n\n      double MSSMea::get_ZV_pole_slha(int i, int j) const { return getdata(\"SNUMIX\",i,j); }\n      double MSSMea::get_ZE_pole_slha(int i, int j) const { return getdata(\"SELMIX\",i,j); }\n\n      double MSSMea::get_ZH_pole_slha(int i, int j) const { return getdata(\"SCALARMIX\",i,j); }\n      double MSSMea::get_ZA_pole_slha(int i, int j) const { return getdata(\"PSEUDOSCALARMIX\",i,j); }\n\n      double MSSMea::get_ZP_pole_slha(int i, int j) const { return getdata(\"CHARGEMIX\",i,j); }\n      double MSSMea::get_ZN_pole_slha(int i, int j) const { return getdata(\"NMIX\",i,j); }\n\n      double MSSMea::get_UM_pole_slha(int i, int j) const { return getdata(\"UMIX\",i,j); }\n      double MSSMea::get_UP_pole_slha(int i, int j) const { return getdata(\"VMIX\",i,j); }\n\n      /// @}\n\n\n      /// @{ Member functions for MSSMSimpleSpec class\n\n      /// @{ Constructors\n\n      /// Default Constructor\n      MSSMSimpleSpec::MSSMSimpleSpec(double uncert)\n      {\n        set_pole_mass_uncertainties(uncert);\n      }\n\n      /// Constructor via SLHAea object\n      MSSMSimpleSpec::MSSMSimpleSpec(const SLHAea::Coll& input, double uncert)\n        : SLHASimpleSpec(input)\n      {\n        set_pole_mass_uncertainties(uncert);\n      }\n\n      /// Copy constructor: needed by clone function.\n      MSSMSimpleSpec::MSSMSimpleSpec(const MSSMSimpleSpec& other, double uncert)\n        : SLHASimpleSpec(other)\n      {\n        set_pole_mass_uncertainties(uncert);\n      }\n\n      /// @}\n\n      /// Ofset from user-input indices (user assumes 1,2,3 indexed, e.g. use offset=-1 for zero-indexing)\n      int MSSMSimpleSpec::get_index_offset() const {return 0.;} // we use indices starting from 1 in this file, matching user assumptions. (because Peter is god, he knows user assumptions before they do.)\n\n      /// Retrieve SLHAea object \n      // NOTE! No need to write this function, SubSpectrum base class can handle it if add_to_SLHAea exists.\n      //SLHAea::Coll MSSMSimpleSpec::getSLHAea(int slha_version) const \n\n      /// Add SLHAea object to another\n      void MSSMSimpleSpec::add_to_SLHAea(int slha_version, SLHAea::Coll& slha) const\n      {\n        // Add SPINFO data if not already present\n        SLHAea_add_GAMBIT_SPINFO(slha);\n\n        // All MSSM blocks\n        slhahelp::add_MSSM_spectrum_to_SLHAea(*this, slha, slha_version);\n      }\n\n      /// Retrieve the PDG translation map\n      const std::map<int, int>& MSSMSimpleSpec::PDG_translator() const { return slhawrap.PDG_translator(); }\n\n      /// Set pole mass uncertainties\n      void MSSMSimpleSpec::set_pole_mass_uncertainties(double uncert)\n      {\n        const std::vector<int> i12        = initVector(1,2);\n        const std::vector<int> i123       = initVector(1,2,3);\n        const std::vector<int> i1234      = initVector(1,2,3,4);\n        const std::vector<int> i123456    = initVector(1,2,3,4,5,6);\n        const std::vector<str> sbosons1   = initVector<str>(\"~g\",\"A0\",\"H+\",\"H-\",\"W+\",\"W-\");\n        const std::vector<str> sbosons2   = initVector<str>(\"~chi+\",\"~chi-\",\"h0\");\n        const std::vector<str> sfermions1 = initVector<str>(\"~u\",\"~d\",\"~e-\",\"~ubar\",\"~dbar\",\"~e+\");\n        const std::vector<str> sfermions2 = initVector<str>(\"~nu\",\"~nubar\");\n        set_override_vector(Par::Pole_Mass_1srd_high, uncert, sfermions1, i123456, true);\n        set_override_vector(Par::Pole_Mass_1srd_low,  uncert, sfermions1, i123456, true);\n        set_override_vector(Par::Pole_Mass_1srd_high, uncert, sfermions2, i123, true);\n        set_override_vector(Par::Pole_Mass_1srd_low,  uncert, sfermions2, i123, true);\n        set_override_vector(Par::Pole_Mass_1srd_high, uncert, sbosons1, true);\n        set_override_vector(Par::Pole_Mass_1srd_low,  uncert, sbosons1, true);\n        set_override_vector(Par::Pole_Mass_1srd_high, uncert, sbosons2, i12, true);\n        set_override_vector(Par::Pole_Mass_1srd_low,  uncert, sbosons2, i12, true);\n        set_override_vector(Par::Pole_Mass_1srd_high, uncert, \"~chi0\", i1234, true);\n        set_override_vector(Par::Pole_Mass_1srd_low,  uncert, \"~chi0\", i1234, true);\n      }\n\n      // Map fillers\n\n      MSSMSimpleSpec::GetterMaps MSSMSimpleSpec::fill_getter_maps()\n      {\n         GetterMaps map_collection;\n\n         typedef MTget::FInfo1 FInfo1;\n         typedef MTget::FInfo2 FInfo2;\n\n         // Can't use c++11 initialiser lists, se have to initialise the index sets like this.\n         static const int i12v[] = {1,2};\n         static const std::set<int> i12(i12v, Utils::endA(i12v));\n\n         static const int i123v[] = {1,2,3};\n         static const std::set<int> i123(i123v, Utils::endA(i123v));\n\n         static const int i1234v[] = {1,2,3,4};\n         static const std::set<int> i1234(i1234v, Utils::endA(i1234v));\n\n         static const int i123456v[] = {1,2,3,4,5,6};\n         static const std::set<int> i123456(i123456v, Utils::endA(i123456v));\n\n         // Running parameters\n         {\n            MTget::fmap0 tmp_map;\n            tmp_map[\"BMu\"] = &Model::get_BMu;\n            tmp_map[\"mA2\"] = &Model::get_mA2;\n            tmp_map[\"mHd2\"] = &Model::get_mHd2;\n            tmp_map[\"mHu2\"] = &Model::get_mHu2;\n            map_collection[Par::mass2].map0 = tmp_map;\n         }\n         {\n            MTget::fmap2 tmp_map;\n            tmp_map[\"mq2\"] = FInfo2( &Model::get_mq2, i123, i123);\n            tmp_map[\"ml2\"] = FInfo2( &Model::get_ml2, i123, i123);\n            tmp_map[\"md2\"] = FInfo2( &Model::get_md2, i123, i123);\n            tmp_map[\"mu2\"] = FInfo2( &Model::get_mu2, i123, i123);\n            tmp_map[\"me2\"] = FInfo2( &Model::get_me2, i123, i123);\n            map_collection[Par::mass2].map2 = tmp_map;\n         }\n         {\n            MTget::fmap0 tmp_map;\n            tmp_map[\"M1\"]= &Model::get_MassB;\n            tmp_map[\"M2\"]= &Model::get_MassWB;\n            tmp_map[\"M3\"]= &Model::get_MassG;\n            tmp_map[\"Mu\"]= &Model::get_Mu;\n            tmp_map[\"vu\"]= &Model::get_vu;\n            tmp_map[\"vd\"]= &Model::get_vd;\n            map_collection[Par::mass1].map0 = tmp_map;\n         }\n         {\n            MTget::fmap2 tmp_map;\n            tmp_map[\"TYd\"]= FInfo2( &Model::get_TYd, i123, i123);\n            tmp_map[\"TYe\"]= FInfo2( &Model::get_TYe, i123, i123);\n            tmp_map[\"TYu\"]= FInfo2( &Model::get_TYu, i123, i123);\n            tmp_map[\"ad\"] = FInfo2( &Model::get_TYd, i123, i123);\n            tmp_map[\"ae\"] = FInfo2( &Model::get_TYe, i123, i123);\n            tmp_map[\"au\"] = FInfo2( &Model::get_TYu, i123, i123);\n            map_collection[Par::mass1].map2 = tmp_map;\n         }\n         {\n            MTget::fmap0 tmp_map;\n            tmp_map[\"g1\"]= &Model::get_g1;\n            tmp_map[\"g2\"]= &Model::get_g2;\n            tmp_map[\"g3\"]= &Model::get_g3;\n            tmp_map[\"tanbeta\"]= &Model::get_tanbeta;\n            tmp_map[\"tanbeta(mZ)\"]= &Model::get_tanbeta_mZ; // Special entry for reproducing MINPAR entry in SLHA\n            tmp_map[\"sinW2\"]= &Model::get_sinthW2_DRbar;\n            map_collection[Par::dimensionless].map0 = tmp_map;\n         }\n         {\n            MTget::fmap2 tmp_map;\n            tmp_map[\"Yd\"]= FInfo2( &Model::get_Yd, i123, i123);\n            tmp_map[\"Yu\"]= FInfo2( &Model::get_Yu, i123, i123);\n            tmp_map[\"Ye\"]= FInfo2( &Model::get_Ye, i123, i123);\n            map_collection[Par::dimensionless].map2 = tmp_map;\n         }\n\n         // \"Physical\" parameters\n         {\n            MTget::fmap0 tmp_map;\n            tmp_map[\"~g\"] = &Model::get_MGlu_pole;\n            tmp_map[\"A0\"] = &Model::get_MAh_pole;\n            tmp_map[\"H+\"] = &Model::get_MHpm_pole;\n            // Antiparticle label\n            tmp_map[\"H-\"] = &Model::get_MHpm_pole;\n            tmp_map[\"W+\"] = &Model::get_MW_pole;\n            map_collection[Par::Pole_Mass].map0 = tmp_map;\n         }\n         {\n            MTget::fmap1 tmp_map;\n            tmp_map[\"~d\"] =    FInfo1( &Model::get_MSd_pole_slha, i123456 );\n            tmp_map[\"~u\"] =    FInfo1( &Model::get_MSu_pole_slha, i123456 );\n            tmp_map[\"~e-\"] =   FInfo1( &Model::get_MSe_pole_slha, i123456 );\n            tmp_map[\"~nu\"] =   FInfo1( &Model::get_MSv_pole_slha, i123 );\n            tmp_map[\"h0\"] =    FInfo1( &Model::get_Mhh_pole_slha, i12 );\n            tmp_map[\"~chi+\"] = FInfo1( &Model::get_MCha_pole_slha, i12 );\n            tmp_map[\"~chi0\"] = FInfo1( &Model::get_MChi_pole_slha, i1234 );\n\n            // Antiparticles (same getters, just different string name)\n            tmp_map[\"~dbar\"] = FInfo1( &Model::get_MSd_pole_slha, i123456 );\n            tmp_map[\"~ubar\"] = FInfo1( &Model::get_MSu_pole_slha, i123456 );\n            tmp_map[\"~e+\"]   = FInfo1( &Model::get_MSe_pole_slha, i123456 );\n            tmp_map[\"~nubar\"]= FInfo1( &Model::get_MSv_pole_slha, i123 );\n            tmp_map[\"~chi-\"] = FInfo1( &Model::get_MCha_pole_slha, i12 );\n            map_collection[Par::Pole_Mass].map1 = tmp_map;\n         }\n         {\n            MTget::fmap2 tmp_map;\n            tmp_map[\"~d\"] =    FInfo2( &Model::get_ZD_pole_slha, i123456, i123456);\n            tmp_map[\"~nu\"] =   FInfo2( &Model::get_ZV_pole_slha, i123, i123);\n            tmp_map[\"~u\"] =    FInfo2( &Model::get_ZU_pole_slha, i123456, i123456);\n            tmp_map[\"~e-\"]=    FInfo2( &Model::get_ZE_pole_slha, i123456, i123456);\n            tmp_map[\"h0\"] =    FInfo2( &Model::get_ZH_pole_slha, i12, i12);\n            tmp_map[\"A0\"] =    FInfo2( &Model::get_ZA_pole_slha, i12, i12);\n            tmp_map[\"H+\"] =    FInfo2( &Model::get_ZP_pole_slha, i12, i12);\n            tmp_map[\"~chi0\"] = FInfo2( &Model::get_ZN_pole_slha, i1234, i1234);\n            tmp_map[\"~chi-\"] = FInfo2( &Model::get_UM_pole_slha, i12, i12);\n            tmp_map[\"~chi+\"] = FInfo2( &Model::get_UP_pole_slha, i12, i12);\n            map_collection[Par::Pole_Mixing].map2 = tmp_map;\n         }\n\n         return map_collection;\n      }\n\n\n} // end Gambit namespace\n\n\n", "meta": {"hexsha": "a9a82f5d160d6de909d7003c95c0674c865f385f", "size": 27141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Models/src/SimpleSpectra/MSSMSimpleSpec.cpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-21T19:59:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-21T19:59:18.000Z", "max_issues_repo_path": "Models/src/SimpleSpectra/MSSMSimpleSpec.cpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-10-06T14:03:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T11:53:54.000Z", "max_forks_repo_path": "Models/src/SimpleSpectra/MSSMSimpleSpec.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": 47.1197916667, "max_line_length": 204, "alphanum_fraction": 0.5545116245, "num_tokens": 8285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.039048292306868335, "lm_q1q2_score": 0.01634939873802327}}
{"text": "/********************************************************************************\n *\n * Stub for the low-level API\n *\n * Author: Maxime Arthaud (maxime@arthaud.me)\n *\n * Copyright (c) 2014 Carnegie Mellon University\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n *******************************************************************************/\n\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n\n#include <api/api.hpp>\n\nusing namespace boost::python;\nnamespace python = boost::python;\nusing namespace ikos;\nusing namespace ikos::api;\n\n/* imported class */\nobject fraction;\n\n/*\n * Conversion class, from Python to IKOS\n */\nclass CFGFactory {\n  private:\n    string_factory V;\n\n  public:\n    z_var_t get_z_var(object py_var) {\n      std::string name = extract< std::string >(py_var.attr(\"name\"));\n      return z_var_t(V[name]);\n    }\n\n    q_var_t get_q_var(object py_var) {\n      std::string name = extract< std::string >(py_var.attr(\"name\"));\n      return q_var_t(V[name]);\n    }\n\n    z_linear_expression_t get_z_linear_expression(object py_expr) {\n      z_linear_expression_t ikos_expr;\n\n      object py_tuple = py_expr.attr(\"normalize\")();\n      long cst = extract< long >(py_tuple[1]);\n\n      stl_input_iterator< object > it(py_tuple[0]), end;\n      for(; it != end; ++it) {\n        object py_term = *it;\n        long factor = extract< long >(py_term[0]);\n        ikos_expr = ikos_expr + z_number(factor) * get_z_var(py_term[1]);\n      }\n\n      ikos_expr = ikos_expr + z_number(cst);\n      return ikos_expr;\n    }\n\n    q_linear_expression_t get_q_linear_expression(object py_expr) {\n      q_linear_expression_t ikos_expr;\n\n      object py_tuple = py_expr.attr(\"normalize\")();\n      long cst_num = extract< long >(py_tuple[1].attr(\"numerator\"));\n      long cst_den = extract< long >(py_tuple[1].attr(\"denominator\"));\n\n\n      stl_input_iterator< object > it(py_tuple[0]), end;\n      for(; it != end; ++it) {\n        object py_term = *it;\n        long factor_num = extract< long >(py_term[0].attr(\"numerator\"));\n        long factor_den = extract< long >(py_term[0].attr(\"denominator\"));\n        ikos_expr = ikos_expr + q_number(factor_num, factor_den) * get_q_var(py_term[1]);\n      }\n\n      ikos_expr = ikos_expr + q_number(cst_num, cst_den);\n      return ikos_expr;\n    }\n\n    z_linear_constraint_t get_z_linear_constraint(object py_constraint) {\n      z_linear_expression_t ikos_expr = get_z_linear_expression(py_constraint.attr(\"expression\"));\n      z_linear_constraint_t::kind_t kind = z_linear_constraint_t::DISEQUATION;\n\n      if(py_constraint.attr(\"operator\") == \"<=\") {\n        kind = z_linear_constraint_t::INEQUALITY;\n      } else if(py_constraint.attr(\"operator\") == \"=\") {\n        kind = z_linear_constraint_t::EQUALITY;\n      } else if(py_constraint.attr(\"operator\") == \"!=\") {\n        kind = z_linear_constraint_t::DISEQUATION;\n      } else {\n        throw_error(\"invalid operator in LinearConstraint: %s\", py_constraint.attr(\"operator\"));\n      }\n\n      return z_linear_constraint_t(ikos_expr, kind);\n    }\n\n    q_linear_constraint_t get_q_linear_constraint(object py_constraint) {\n      q_linear_expression_t ikos_expr = get_q_linear_expression(py_constraint.attr(\"expression\"));\n      q_linear_constraint_t::kind_t kind = q_linear_constraint_t::DISEQUATION;\n\n      if(py_constraint.attr(\"operator\") == \"<=\") {\n        kind = q_linear_constraint_t::INEQUALITY;\n      } else if(py_constraint.attr(\"operator\") == \"=\") {\n        kind = q_linear_constraint_t::EQUALITY;\n      } else if(py_constraint.attr(\"operator\") == \"!=\") {\n        kind = q_linear_constraint_t::DISEQUATION;\n      } else {\n        throw_error(\"invalid operator in LinearConstraint: %s\", py_constraint.attr(\"operator\"));\n      }\n\n      return q_linear_constraint_t(ikos_expr, kind);\n    }\n\n    cfg_t get_cfg(object py_cfg) {\n      stl_input_iterator< object > end;\n      std::string entry_name = extract< std::string >(py_cfg.attr(\"entry\").attr(\"name\"));\n      cfg_t cfg(entry_name);\n\n      /* create blocks */\n      for(stl_input_iterator< object > it(py_cfg.attr(\"blocks\")); it != end; ++it) {\n        object py_block = *it;\n        std::string block_name = extract< std::string >(py_block.attr(\"name\"));\n\n        block_t& block = cfg.insert_basic_block(block_name);\n        block_add_statements(block, py_block.attr(\"statements\"));\n      }\n\n      /* create links */\n      for(stl_input_iterator< object > it(py_cfg.attr(\"blocks\")); it != end; ++it) {\n        object py_block = *it;\n        std::string block_name = extract< std::string >(py_block.attr(\"name\"));\n\n        for(stl_input_iterator< object > it2(py_block.attr(\"next_blocks\")); it2 != end; ++it2) {\n          object py_next = *it2;\n          std::string next_name = extract< std::string >(py_next.attr(\"name\"));\n          cfg.get_node(nodename_t(block_name)) >> cfg.get_node(nodename_t(next_name));\n        }\n      }\n\n      return cfg;\n    }\n\n  private:\n    void block_add_statements(block_t& block, object py_statements) {\n      stl_input_iterator< object > it(py_statements), end;\n\n      for(; it != end; ++it) {\n        object py_statement = *it;\n        object class_name = py_statement.attr(\"__class__\").attr(\"__name__\");\n\n        if(class_name == \"BinaryOperation\") {\n          object type = py_statement.attr(\"var\").attr(\"type\");\n          object op = py_statement.attr(\"operator\");\n\n          if(type == \"int\") {\n            z_var_t var = get_z_var(py_statement.attr(\"var\"));\n            z_var_t left = get_z_var(py_statement.attr(\"left\"));\n            z_var_t right = get_z_var(py_statement.attr(\"right\"));\n\n            if(op == \"+\") block.add(var, left, right);\n            else if(op == \"+\") block.sub(var, left, right);\n            else if(op == \"*\") block.mul(var, left, right);\n            else if(op == \"/\") block.div(var, left, right);\n            else throw_error(\"invalid operator in BinaryStatement: %s\", op);\n          }\n          else if(type == \"rational\") {\n            q_var_t var = get_q_var(py_statement.attr(\"var\"));\n            q_var_t left = get_q_var(py_statement.attr(\"left\"));\n            q_var_t right = get_q_var(py_statement.attr(\"right\"));\n\n            if(op == \"+\") block.add(var, left, right);\n            else if(op == \"+\") block.sub(var, left, right);\n            else if(op == \"*\") block.mul(var, left, right);\n            else if(op == \"/\") block.div(var, left, right);\n            else throw_error(\"invalid operator in BinaryStatement: %s\", op);\n          }\n          else {\n            throw_error(\"invalid variable type: %s\", type);\n          }\n        }\n        else if(class_name == \"Assign\") {\n          object type = py_statement.attr(\"var\").attr(\"type\");\n\n          if(type == \"int\") {\n            z_var_t var = get_z_var(py_statement.attr(\"var\"));\n            z_linear_expression_t expr = get_z_linear_expression(py_statement.attr(\"expression\"));\n            block.assign(var, expr);\n          }\n          else if(type == \"rational\") {\n            q_var_t var = get_q_var(py_statement.attr(\"var\"));\n            q_linear_expression_t expr = get_q_linear_expression(py_statement.attr(\"expression\"));\n            block.assign(var, expr);\n          }\n          else {\n            throw_error(\"invalid variable type: %s\", type);\n          }\n        }\n        else if(class_name == \"Assert\") {\n          object type = py_statement.attr(\"constraint\").attr(\"type\");\n\n          if(type == \"int\") {\n            z_linear_constraint_t cst = get_z_linear_constraint(py_statement.attr(\"constraint\"));\n            block.assertion(cst);\n          }\n          else if(type == \"rational\") {\n            q_linear_constraint_t cst = get_q_linear_constraint(py_statement.attr(\"constraint\"));\n            block.assertion(cst);\n          }\n          else {\n            throw_error(\"invalid LinearConstraint type: %s\", type);\n          }\n        }\n        else if(class_name == \"Checkpoint\") {\n          std::string name = extract< std::string >(py_statement.attr(\"name\"));\n          block.check(name);\n        }\n        else {\n          throw_error(\"invalid statement: %s\", class_name);\n        }\n      }\n    }\n\n    void throw_error(std::string format, object value) {\n      object py_message = format % value.attr(\"__repr__\")();\n      std::string message = extract< std::string >(py_message);\n      throw ikos::error(message);\n    }\n\n}; // class CFGFactory\n\n\n/*\n * Conversion class, from IKOS to Python\n */\nclass PythonFactory {\n  public:\n    python::list get_z_linear_expression(z_linear_expression_t expr) {\n      python::list result;\n\n      for(z_linear_expression_t::iterator it = expr.begin(); it != expr.end(); ++it) {\n        result.append(python::make_tuple(it->first.si(), it->second.name().str()));\n      }\n\n      if(expr.constant() != 0) {\n        result.append(expr.constant().si());\n      }\n\n      return result;\n    }\n\n    python::list get_q_linear_expression(q_linear_expression_t expr) {\n      python::list result;\n\n      for(q_linear_expression_t::iterator it = expr.begin(); it != expr.end(); ++it) {\n        object factor = fraction(it->first.numerator().si(), it->first.denominator().si());\n        result.append(python::make_tuple(factor, it->second.name().str()));\n      }\n\n      if(expr.constant() != 0) {\n        object py_cst = fraction(expr.constant().numerator().si(), expr.constant().denominator().si());\n        result.append(py_cst);\n      }\n\n      return result;\n    }\n\n    python::tuple get_z_linear_constraint(z_extended_constraint_t cst) {\n      python::list py_expr = get_z_linear_expression(cst.expression());\n\n      switch(cst.kind()) {\n        case z_extended_constraint_t::INF:\n          return python::make_tuple(py_expr, \"<\");\n        case z_extended_constraint_t::INF_EQ:\n          return python::make_tuple(py_expr, \"<=\");\n        case z_extended_constraint_t::SUP:\n          return python::make_tuple(py_expr, \">\");\n        case z_extended_constraint_t::SUP_EQ:\n          return python::make_tuple(py_expr, \">=\");\n        case z_extended_constraint_t::EQ:\n          return python::make_tuple(py_expr, \"=\");\n        case z_extended_constraint_t::NOT_EQ:\n          return python::make_tuple(py_expr, \"!=\");\n        case z_extended_constraint_t::MOD:\n          return python::make_tuple(py_expr, \"mod\", cst.modulus().get().si());\n        default:\n          throw error(\"unreachable\");\n      }\n    }\n\n    python::tuple get_q_linear_constraint(q_extended_constraint_t cst) {\n      python::list py_expr = get_q_linear_expression(cst.expression());\n\n      switch(cst.kind()) {\n        case q_extended_constraint_t::INF:\n          return python::make_tuple(py_expr, \"<\");\n        case q_extended_constraint_t::INF_EQ:\n          return python::make_tuple(py_expr, \"<=\");\n        case q_extended_constraint_t::SUP:\n          return python::make_tuple(py_expr, \">\");\n        case q_extended_constraint_t::SUP_EQ:\n          return python::make_tuple(py_expr, \">=\");\n        case q_extended_constraint_t::EQ:\n          return python::make_tuple(py_expr, \"=\");\n        case q_extended_constraint_t::NOT_EQ:\n          return python::make_tuple(py_expr, \"!=\");\n        default:\n          throw error(\"unreachable\");\n      }\n    }\n\n    python::list get_z_linear_constraints(z_extended_constraint_system_t csts) {\n      python::list result;\n\n      for(z_extended_constraint_system_t::iterator it = csts.begin(); it != csts.end(); ++it) {\n        result.append(get_z_linear_constraint(*it));\n      }\n\n      return result;\n    }\n\n    python::list get_q_linear_constraints(q_extended_constraint_system_t csts) {\n      python::list result;\n\n      for(q_extended_constraint_system_t::iterator it = csts.begin(); it != csts.end(); ++it) {\n        result.append(get_q_linear_constraint(*it));\n      }\n\n      return result;\n    }\n\n}; // class PythonFactory\n\n/*\n * Fix point computation\n */\ntemplate< typename ZDomain, typename QDomain>\ndict compute_fixpoint_call(cfg_t& cfg) {\n  typedef typename fixpoint_iterator< ZDomain, QDomain >::AbstractValue AbstractValue;\n\n  PythonFactory py_factory;\n  domain_constraints< z_number, VarName > z_domain_export;\n  domain_constraints< q_number, VarName > q_domain_export;\n  dict result;\n\n  fixpoint_iterator< ZDomain, QDomain > it(cfg);\n  it.run_from_top();\n\n  std::map< CheckPointName, AbstractValue >& checkpoints = it.checkpoints();\n  for(typename std::map< CheckPointName, AbstractValue >::iterator it = checkpoints.begin(); it != checkpoints.end(); ++it) {\n    CheckPointName name = it->first;\n\n    z_extended_constraint_system_t z_csts = z_domain_export.get_constraints(it->second.first());\n    q_extended_constraint_system_t q_csts = q_domain_export.get_constraints(it->second.second());\n\n    python::list py_z_csts = py_factory.get_z_linear_constraints(z_csts);\n    python::list py_q_csts = py_factory.get_q_linear_constraints(q_csts);\n\n    result[name] = python::make_tuple(py_z_csts, py_q_csts);\n  }\n\n  return result;\n}\n\n/*\n * Ikos Exceptions\n */\n\n/* Python C-API, only to define a custom exception (impossible with boost::python) */\nPyObject* create_exception_class(const char* name, PyObject* base_type = PyExc_Exception)\n{\n  std::string scope_name = extract< std::string >(scope().attr(\"__name__\"));\n  std::string qualified_name = scope_name + \".\" + name;\n\n  PyObject* type_obj = PyErr_NewException(const_cast< char* >(qualified_name.c_str()), base_type, 0);\n\n  if(!type_obj)\n    throw_error_already_set();\n\n  scope().attr(name) = handle<>(borrowed(type_obj));\n  return type_obj;\n}\n\nPyObject* ikos_exception = NULL;\n\nvoid ikos_exception_translator(ikos::error const& e) {\n  /*\n   * Bad design in IKOS:\n   * boost::python enforces having a const& argument for exception translators,\n   * and error::message() is not const, that's why I use a copy here.\n   */\n  ikos::error e_copy(e);\n  PyErr_SetString(ikos_exception, e_copy.message().c_str());\n}\n\n/*\n * Binding functions\n */\n\nvoid print_linear_expression(object py_expr) {\n  if(py_expr.attr(\"type\") == \"int\") {\n    z_linear_expression_t expr = CFGFactory().get_z_linear_expression(py_expr);\n    std::cout << expr << std::endl;\n  }\n  else {\n    q_linear_expression_t expr = CFGFactory().get_q_linear_expression(py_expr);\n    std::cout << expr << std::endl;\n  }\n}\n\nvoid print_linear_constraint(object py_constraint) {\n  if(py_constraint.attr(\"type\") == \"int\") {\n    z_linear_constraint_t cst = CFGFactory().get_z_linear_constraint(py_constraint);\n    std::cout << cst << std::endl;\n  }\n  else {\n    q_linear_constraint_t cst = CFGFactory().get_q_linear_constraint(py_constraint);\n    std::cout << cst << std::endl;\n  }\n}\n\nvoid print_cfg(object py_cfg) {\n  cfg_t cfg = CFGFactory().get_cfg(py_cfg);\n  std::cout << cfg << std::endl;\n}\n\n/* it's ugly, but there is no other way */\n\n#define ZDOMAIN_FROM_PYTHON(var, type_name, todo)                        \\\n  do {                                                                   \\\n    if((var) == \"constant\") {                                            \\\n      typedef constant_domain< z_number, VarName > type_name;            \\\n      todo;                                                              \\\n    } else if((var) == \"interval\") {                                     \\\n      typedef interval_domain< z_number, VarName > type_name;            \\\n      todo;                                                              \\\n    } else if((var) == \"octagon\") {                                      \\\n      typedef octagon< z_number, VarName > type_name;                    \\\n      todo;                                                              \\\n    }                                                                    \\\n  } while (0)\n\n#define QDOMAIN_FROM_PYTHON(var, type_name, todo)                        \\\n  do {                                                                   \\\n    if((var) == \"constant\") {                                            \\\n      typedef constant_domain< q_number, VarName > type_name;            \\\n      todo;                                                              \\\n    } else if((var) == \"interval\") {                                     \\\n      typedef interval_domain< q_number, VarName > type_name;            \\\n      todo;                                                              \\\n    } else if((var) == \"octagon\") {                                      \\\n      typedef octagon< q_number, VarName > type_name;                    \\\n      todo;                                                              \\\n    } else {                                                             \\\n      throw ikos::error(\"cannot use this domain with rational numbers\"); \\\n    }                                                                    \\\n  } while (0)\n\ndict compute_fixpoint(object py_cfg, std::string py_z_domain, std::string py_q_domain) {\n  cfg_t cfg = CFGFactory().get_cfg(py_cfg);\n\n  #define FIXPOINT_CALL return compute_fixpoint_call< ZDomain, QDomain >(cfg)\n  #define FIXPOINT_CALL_QDOMAIN QDOMAIN_FROM_PYTHON(py_q_domain, QDomain, FIXPOINT_CALL)\n  ZDOMAIN_FROM_PYTHON(py_z_domain, ZDomain, FIXPOINT_CALL_QDOMAIN);\n  #undef FIXPOINT_CALL_QDOMAIN\n  #undef FIXPOINT_CALL\n\n  return dict(); // unreachable\n}\n\n\nBOOST_PYTHON_MODULE(apicore) {\n  /* import */\n  fraction = import(\"fractions\").attr(\"Fraction\");\n\n  /* exception handling */\n  ikos_exception = create_exception_class(\"IkosException\");\n  register_exception_translator< ikos::error >(ikos_exception_translator);\n\n  /* for debugging purpose */\n  def(\"print_linear_expression\", print_linear_expression, \"Print a LinearExpression\");\n  def(\"print_linear_constraint\", print_linear_constraint, \"Print a LinearConstraint\");\n  def(\"print_cfg\", print_cfg, \"Print a Cfg\");\n\n  /* IKOS call */\n  def(\"compute_fixpoint\", compute_fixpoint, \"Compute a fix point\");\n}\n", "meta": {"hexsha": "cb65cc3e82467554a9cccf21fbfe03c8bc91d666", "size": 18761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIkos/ikos/apicore.cpp", "max_stars_repo_name": "coco-team/Ikos-Api", "max_stars_repo_head_hexsha": "3a6bc20e5696aacc55d34b8e3e26e8f74a7bcdf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T00:15:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-22T00:15:02.000Z", "max_issues_repo_path": "PyIkos/ikos/apicore.cpp", "max_issues_repo_name": "coco-team/Ikos-Api", "max_issues_repo_head_hexsha": "3a6bc20e5696aacc55d34b8e3e26e8f74a7bcdf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PyIkos/ikos/apicore.cpp", "max_forks_repo_name": "coco-team/Ikos-Api", "max_forks_repo_head_hexsha": "3a6bc20e5696aacc55d34b8e3e26e8f74a7bcdf1", "max_forks_repo_licenses": ["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.2242063492, "max_line_length": 125, "alphanum_fraction": 0.6060444539, "num_tokens": 4184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.03789242839515542, "lm_q1q2_score": 0.01629932760565501}}
{"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#ifndef DUNE_STUFF_FUNCTIONS_DERIVED_HH\n#define DUNE_STUFF_FUNCTIONS_DERIVED_HH\n\n#include <type_traits>\n#include <memory>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/typetraits.hh>\n\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/memory.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Functions {\nnamespace internal {\n\nenum class Derivative\n{\n  divergence\n};\n\ntemplate <class FunctionType, Derivative derivative>\nclass SelectDerived\n{\n  static_assert(is_localizable_function<FunctionType>::value, \"FunctionType has to be a LocalizableFunction!\");\n\npublic:\n  typedef typename FunctionType::EntityType E;\n  typedef typename FunctionType::DomainFieldType D;\n  static const size_t d = FunctionType::dimDomain;\n  typedef typename FunctionType::RangeFieldType R;\n\nprivate:\n  template <class F>\n  class Choose\n  {\n    template <size_t d, size_t r, size_t rC, Derivative der, bool anything = true>\n    class Dimension\n    {\n      static_assert(!anything, \"No derivative for these dimensions available!\");\n    };\n\n    template <size_t d, bool anything>\n    class Dimension<d, d, 1, Derivative::divergence, anything>\n    {\n    public:\n      static const size_t r  = 1;\n      static const size_t rC = 1;\n    };\n\n  public:\n    static const size_t r  = Dimension<d, F::dimRange, F::dimRangeCols, derivative>::r;\n    static const size_t rC = Dimension<d, F::dimRange, F::dimRangeCols, derivative>::rC;\n  }; // class SelectDerived\n\npublic:\n  static const size_t r  = Choose<FunctionType>::r;\n  static const size_t rC = Choose<FunctionType>::rC;\n\n  typedef typename FunctionType::LocalfunctionType FunctionLocalfunctionType;\n  typedef typename LocalfunctionInterface<E, D, d, R, r, rC>::DomainType DomainType;\n  typedef typename LocalfunctionInterface<E, D, d, R, r, rC>::RangeType RangeType;\n  typedef typename LocalfunctionInterface<E, D, d, R, r, rC>::JacobianRangeType JacobianRangeType;\n\nprivate:\n  template <Derivative der, bool anything = true>\n  class Call\n  {\n    static_assert(!anything, \"Nothing available for this derivative!\");\n  }; // class Call\n\n  template <bool anything>\n  class Call<Derivative::divergence, anything>\n  {\n  public:\n    static std::string type() { return \"divergence\"; }\n\n    static size_t order(const size_t ord)\n    {\n      return boost::numeric_cast<size_t>(std::max(boost::numeric_cast<ssize_t>(ord) - 1, ssize_t(0)));\n    }\n\n    static void evaluate(const FunctionLocalfunctionType& func_local, const DomainType& xx, RangeType& ret)\n    {\n      typename FunctionLocalfunctionType::JacobianRangeType tmp_jac(0.0);\n      func_local.jacobian(xx, tmp_jac);\n      ret *= 0.0;\n      for (size_t dd = 0; dd < d; ++dd)\n        ret[0] += tmp_jac[dd][dd];\n    } // ... evaluate(...)\n\n    static void jacobian(const FunctionLocalfunctionType& /*func_local*/, const DomainType& /*xx*/,\n                         JacobianRangeType& /*ret*/)\n    {\n      DUNE_THROW(NotImplemented, \"for divergence!\");\n    }\n  }; // class Call< ..., divergence >\n\npublic:\n  static std::string type() { return Call<derivative>::type(); }\n\n  static size_t order(const size_t ord) { return Call<derivative>::order(ord); }\n\n  static void evaluate(const FunctionLocalfunctionType& func_local, const DomainType& xx, RangeType& ret)\n  {\n    Call<derivative>::evaluate(func_local, xx, ret);\n  }\n\n  static void jacobian(const FunctionLocalfunctionType& func_local, const DomainType& xx, JacobianRangeType& ret)\n  {\n    Call<derivative>::jacobian(func_local, xx, ret);\n  }\n}; // class SelectDerived\n\ntemplate <class FunctionType, Derivative derivative>\nclass DerivedLocalFunction\n    : public LocalfunctionInterface<\n          typename SelectDerived<FunctionType, derivative>::E, typename SelectDerived<FunctionType, derivative>::D,\n          SelectDerived<FunctionType, derivative>::d, typename SelectDerived<FunctionType, derivative>::R,\n          SelectDerived<FunctionType, derivative>::r, SelectDerived<FunctionType, derivative>::rC>\n{\n  typedef LocalfunctionInterface<\n      typename SelectDerived<FunctionType, derivative>::E, typename SelectDerived<FunctionType, derivative>::D,\n      SelectDerived<FunctionType, derivative>::d, typename SelectDerived<FunctionType, derivative>::R,\n      SelectDerived<FunctionType, derivative>::r, SelectDerived<FunctionType, derivative>::rC> BaseType;\n\n  typedef SelectDerived<FunctionType, derivative> Select;\n\npublic:\n  typedef typename BaseType::EntityType EntityType;\n  typedef typename BaseType::DomainType DomainType;\n  typedef typename BaseType::RangeType RangeType;\n  typedef typename BaseType::JacobianRangeType JacobianRangeType;\n\n  DerivedLocalFunction(const FunctionType& func, const EntityType& ent)\n    : BaseType(ent), func_local_(func.local_function(this->entity()))\n  {\n  }\n\n  virtual size_t order() const override final { return Select::order(func_local_->order()); }\n\n  virtual void evaluate(const DomainType& xx, RangeType& ret) const override final\n  {\n    Select::evaluate(*func_local_, xx, ret);\n  }\n\n  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final\n  {\n    Select::jacobian(*func_local_, xx, ret);\n  }\n\nprivate:\n  const std::unique_ptr<const typename FunctionType::LocalfunctionType> func_local_;\n}; // class DerivedLocalFunction\n\ntemplate <class FunctionType, Derivative derivative>\nclass Derived\n    : public LocalizableFunctionInterface<\n          typename SelectDerived<FunctionType, derivative>::E, typename SelectDerived<FunctionType, derivative>::D,\n          SelectDerived<FunctionType, derivative>::d, typename SelectDerived<FunctionType, derivative>::R,\n          SelectDerived<FunctionType, derivative>::r, SelectDerived<FunctionType, derivative>::rC>\n{\n  typedef LocalizableFunctionInterface<\n      typename SelectDerived<FunctionType, derivative>::E, typename SelectDerived<FunctionType, derivative>::D,\n      SelectDerived<FunctionType, derivative>::d, typename SelectDerived<FunctionType, derivative>::R,\n      SelectDerived<FunctionType, derivative>::r, SelectDerived<FunctionType, derivative>::rC> BaseType;\n  typedef Common::ConstStorageProvider<FunctionType> FunctionStorageType;\n  typedef Derived<FunctionType, derivative> ThisType;\n\npublic:\n  typedef typename BaseType::EntityType EntityType;\n  typedef typename BaseType::LocalfunctionType LocalfunctionType;\n\n  Derived(const FunctionType& func, const std::string nm = \"\")\n    : func_(Common::make_unique<FunctionStorageType>(func))\n    , name_(nm.empty() ? SelectDerived<FunctionType, derivative>::type() + \" of '\" + func.name() + \"'\" : nm)\n  {\n  }\n\n  Derived(const std::shared_ptr<const FunctionType> func, const std::string nm = \"\")\n    : func_(Common::make_unique<FunctionStorageType>(func))\n    , name_(nm.empty()\n                ? SelectDerived<FunctionType, derivative>::type() + \" of '\" + func_->storage_access().name() + \"'\"\n                : nm)\n  {\n  }\n\n  Derived(ThisType&& source) = default;\n  Derived(const ThisType& other) = delete;\n\n  ThisType& operator=(const ThisType& other) = delete;\n  ThisType& operator=(ThisType&& other) = delete;\n\n  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const override final\n  {\n    typedef DerivedLocalFunction<FunctionType, derivative> RealLocalFunctionType;\n    assert(func_);\n    return DSC::make_unique<RealLocalFunctionType>(func_->storage_access(), entity);\n  } // ... local_function(...)\n\n  virtual ThisType* copy() const { DUNE_THROW(NotImplemented, \"Are you kidding me?\"); }\n\n  virtual std::string type() const override final\n  {\n    return SelectDerived<FunctionType, derivative>::type() + \" of '\" + func_->storage_access().type() + \"'\";\n  }\n\n  virtual std::string name() const override final { return name_; }\n\nprivate:\n  std::unique_ptr<const FunctionStorageType> func_;\n  const std::string name_;\n}; // class Derived\n\n} // namespace internal\n\ntemplate <class FunctionType>\nclass Divergence : public internal::Derived<FunctionType, internal::Derivative::divergence>\n{\n  typedef internal::Derived<FunctionType, internal::Derivative::divergence> BaseType;\n\npublic:\n  template <class... Args>\n  Divergence(Args&&... args)\n    : BaseType(std::forward<Args>(args)...)\n  {\n  }\n}; // class Divergence\n\ntemplate <class T, class... Args>\nstd::shared_ptr<Divergence<T>> make_divergence(const T& func, Args&&... args)\n{\n  return std::make_shared<Divergence<T>>(func, std::forward<Args>(args)...);\n}\n\ntemplate <class T, class... Args>\nstd::shared_ptr<Divergence<T>> make_divergence(std::shared_ptr<T> func, Args&&... args)\n{\n  return std::make_shared<Divergence<T>>(func, std::forward<Args>(args)...);\n}\n\n} // namespace Functions\n} // namespace Stuff\n} // namespace Dune\n\n#endif // DUNE_STUFF_FUNCTIONS_DERIVED_HH\n", "meta": {"hexsha": "34e684da479e6da6fa0c6acf8057addb2b4215d7", "size": 8961, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/stuff/functions/derived.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/functions/derived.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/functions/derived.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": 35.00390625, "max_line_length": 115, "alphanum_fraction": 0.7250306885, "num_tokens": 2165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111085480195975, "lm_q2_score": 0.0396388429299176, "lm_q1q2_score": 0.016295958600279044}}
{"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/*****************************************************************************\r\n\r\n               Lambert Conformal Conic Alternative\r\n               -----------------------------------\r\n\r\n    This is Gerald Evenden's 2003 implementation of an alternative\r\n    \"almost\" LCC, which has been in use historically, but which\r\n    should NOT be used for new projects - i.e: use this implementation\r\n    if you need interoperability with old data represented in this\r\n    projection, but not in any other case.\r\n\r\n    The code was originally discussed on the PROJ.4 mailing list in\r\n    a thread archived over at\r\n\r\n    http://lists.maptools.org/pipermail/proj/2003-March/000644.html\r\n\r\n    It was discussed again in the thread starting at\r\n\r\n    http://lists.maptools.org/pipermail/proj/2017-October/007828.html\r\n        and continuing at\r\n    http://lists.maptools.org/pipermail/proj/2017-November/007831.html\r\n\r\n    which prompted Clifford J. Mugnier to add these clarifying notes:\r\n\r\n    The French Army Truncated Cubic Lambert (partially conformal) Conic\r\n    projection is the Legal system for the projection in France between\r\n    the late 1800s and 1948 when the French Legislature changed the law\r\n    to recognize the fully conformal version.\r\n\r\n    It was (might still be in one or two North African prior French\r\n    Colonies) used in North Africa in Algeria, Tunisia, & Morocco, as\r\n    well as in Syria during the Levant.\r\n\r\n    Last time I have seen it used was about 30+ years ago in\r\n    Algeria when it was used to define Lease Block boundaries for\r\n    Petroleum Exploration & Production.\r\n\r\n    (signed)\r\n\r\n    Clifford J. Mugnier, c.p., c.m.s.\r\n    Chief of Geodesy\r\n    LSU Center for GeoInformatics\r\n    Dept. of Civil Engineering\r\n    LOUISIANA STATE UNIVERSITY\r\n\r\n*****************************************************************************/\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_LCCA_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_LCCA_HPP\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\r\n\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 lcca\r\n    {\r\n\r\n            static const int max_iter = 10;\r\n            static const double del_tol = 1e-12;\r\n\r\n            template <typename T>\r\n            struct par_lcca\r\n            {\r\n                detail::en<T> en;\r\n                T    r0, l, M0;\r\n                T    C;\r\n            };\r\n\r\n            template <typename T> /* func to compute dr */\r\n            inline T fS(T const& S, T const& C)\r\n            {\r\n                return(S * ( 1. + S * S * C));\r\n            }\r\n\r\n            template <typename T> /* deriv of fs */\r\n            inline T fSp(T const& S, T const& C)\r\n            {\r\n                return(1. + 3.* S * S * C);\r\n            }\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_lcca_ellipsoid\r\n                : public base_t_fi<base_lcca_ellipsoid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_lcca<T> m_proj_parm;\r\n\r\n                inline base_lcca_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_lcca_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 const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T S, r, dr;\r\n\r\n                    S = pj_mlfn(lp_lat, sin(lp_lat), cos(lp_lat), this->m_proj_parm.en) - this->m_proj_parm.M0;\r\n                    dr = fS(S, this->m_proj_parm.C);\r\n                    r = this->m_proj_parm.r0 - dr;\r\n                    xy_x = this->m_par.k0 * (r * sin( lp_lon *= this->m_proj_parm.l ) );\r\n                    xy_y = this->m_par.k0 * (this->m_proj_parm.r0 - r * cos(lp_lon) );\r\n                }\r\n\r\n                // INVERSE(e_inverse)  ellipsoid & spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    T theta, dr, S, dif;\r\n                    int i;\r\n\r\n                    xy_x /= this->m_par.k0;\r\n                    xy_y /= this->m_par.k0;\r\n                    theta = atan2(xy_x , this->m_proj_parm.r0 - xy_y);\r\n                    dr = xy_y - xy_x * tan(0.5 * theta);\r\n                    lp_lon = theta / this->m_proj_parm.l;\r\n                    S = dr;\r\n                    for (i = max_iter; i ; --i) {\r\n                        S -= (dif = (fS(S, this->m_proj_parm.C) - dr) / fSp(S, this->m_proj_parm.C));\r\n                        if (fabs(dif) < del_tol) break;\r\n                    }\r\n                    if (!i) {\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                    }\r\n                    lp_lat = pj_inv_mlfn(S + this->m_proj_parm.M0, this->m_par.es, this->m_proj_parm.en);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"lcca_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Lambert Conformal Conic Alternative\r\n            template <typename Parameters, typename T>\r\n            inline void setup_lcca(Parameters& par, par_lcca<T>& proj_parm)\r\n            {\r\n                T s2p0, N0, R0, tan0;\r\n\r\n                proj_parm.en = pj_enfn<T>(par.es);\r\n                \r\n                if (par.phi0 == 0.) {\r\n                    BOOST_THROW_EXCEPTION( projection_exception(error_lat_0_is_zero) );\r\n                }\r\n                proj_parm.l = sin(par.phi0);\r\n                proj_parm.M0 = pj_mlfn(par.phi0, proj_parm.l, cos(par.phi0), proj_parm.en);\r\n                s2p0 = proj_parm.l * proj_parm.l;\r\n                R0 = 1. / (1. - par.es * s2p0);\r\n                N0 = sqrt(R0);\r\n                R0 *= par.one_es * N0;\r\n                tan0 = tan(par.phi0);\r\n                proj_parm.r0 = N0 / tan0;\r\n                proj_parm.C = 1. / (6. * R0 * N0);\r\n            }\r\n\r\n    }} // namespace detail::lcca\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Lambert Conformal Conic Alternative projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Conic\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Projection parameters\r\n         - lat_0: Latitude of origin\r\n        \\par Example\r\n        \\image html ex_lcca.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct lcca_ellipsoid : public detail::lcca::base_lcca_ellipsoid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline lcca_ellipsoid(Params const& , Parameters const& par)\r\n            : detail::lcca::base_lcca_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::lcca::setup_lcca(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_lcca, lcca_ellipsoid, lcca_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(lcca_entry, lcca_ellipsoid)\r\n        \r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(lcca_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(lcca, lcca_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_LCCA_HPP\r\n\r\n", "meta": {"hexsha": "b1f3d9a17c8c671180019fe2e787befb428eb6f3", "size": 10042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/srs/projections/proj/lcca.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/lcca.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/lcca.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": 39.0739299611, "max_line_length": 114, "alphanum_fraction": 0.5824536945, "num_tokens": 2291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03258974570562265, "lm_q1q2_score": 0.016294872852811323}}
{"text": "// Persistent Homology code by Hubert Wagner based on an implementation by Chao Chen\r\n#include <cmath>\r\n#include <vector>\r\n#include <map>\r\n#include <set>\r\n#include <list>\r\n#include <cassert>\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <deque>\r\n#include <cstring>\r\n#include <ctime>\r\n#include <blitz/array.h>\r\n#include <blitz/tinyvec-et.h>\r\n\r\nusing namespace std;\r\n\r\nconst int BIG_INT = 0x7FFFFFFF;\t//be careful, could be too small compared to # of cubes\r\ntypedef int CellNrType; // it could be long for really large inputs...\r\n\r\n#include \"PersistenceIO.h\"\r\n#include \"Debugging.h\"\r\n#include \"GeneralFiltration.h\"\r\n\r\n#include \"InputRunner.h\"\r\n\r\n#include \"PersistentPair.h\"\r\n#include \"DataReaders.h\"\r\n\r\n#include \"PersistenceCalculator.h\"\r\n#include \"PersistenceCalcRunner.h\"\r\n\r\n\r\nint main(int argc, const char* argv[]){\r\n\r\n\ttime_t startTime1, startTime2, endTime;\t\t\r\n\r\n\tif (argc < 2)\r\n\t{\r\n\t\tstd::cout << \"usage: \" << argv[0] << \" input_file.ext\" << std::endl;\t\t\r\n\t\treturn 1;\r\n\t}\t\t\r\n\r\n\tstring input_file = argv[1];\r\n\tdouble pers_thd = 0.0;\t\r\n\r\n\tstring lfile = \"log.txt\";\t\r\n\tstring efile = \"error.txt\";\t\r\n\tDebuggerClass::init( false, lfile, efile );\r\n\t\r\n\tInputFileInfo input_file_info(input_file);\r\n\t\r\n\tint max_pers_pts = BIG_INT; // the maximal number of persistence pairs recorded\r\n\r\n\tfstream filestr;\r\n\tfilestr.open (lfile.c_str(), fstream::out | fstream::trunc);\r\n\t//\tfilestr.open (LOG_FILE, fstream::out | fstream::ate);\r\n\tfilestr << \"################################################\" << endl;\r\n\tfilestr << \"start computing persistence\" << endl;\r\n\tfilestr << \"Input file = \\'\" << input_file << \"\\'\" << endl;\r\n\t// filestr << \"Output file = \\'\" << output_file << \"\\'\" << endl;\t\r\n\tfilestr << \"Maximal number of persistence points recorded = \" << max_pers_pts << endl;\r\n\tfilestr.close();\t\r\n\r\n\ttime(&startTime1);\t\t\r\n\r\n\tswitch(input_file_info.dimension)\r\n\t{\r\n\tcase 1:\r\n\t\tInputRunner<1>::run(input_file_info, pers_thd);\r\n\t\tbreak;\r\n\tcase 2:\r\n\t\tInputRunner<2>::run(input_file_info, pers_thd);\r\n\t\tbreak;\r\n\tcase 3:\r\n\t\tInputRunner<3>::run(input_file_info, pers_thd);\r\n\t\tbreak;\r\n\tcase 4:\r\n\t\tInputRunner<4>::run(input_file_info, pers_thd);\r\n\t\tbreak;\r\n\tcase 5:\r\n\t\tInputRunner<5>::run(input_file_info, pers_thd);\r\n\t\tbreak;\r\n\tcase 6:\r\n\t\tInputRunner<6>::run(input_file_info, pers_thd);\r\n\t\tbreak;\t\r\n\tcase 7:\r\n\t\tInputRunner<7>::run(input_file_info, pers_thd);\r\n\t\tbreak;\t\r\n\tcase 8:\r\n\t\tInputRunner<8>::run(input_file_info, pers_thd);\r\n\t\tbreak;\t\r\n\t}\r\n\r\n\ttime(&endTime);\r\n\tdouble ellapsed1 = difftime (endTime,startTime1);\t\r\n\r\n\tcout << \"All calculations computed in \" << setprecision(2) << ellapsed1/60.0 << endl;\r\n\tDebuggerClass::finish();\r\n\t\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "a00bf11eb147a5529d005bbba53d49c482855998", "size": 2703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/cPers/cPers/PersistenceCubic.cpp", "max_stars_repo_name": "HuXiaoling/TopoNet", "max_stars_repo_head_hexsha": "5cb98177de50a3694f5886137ff7c6f55fd51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2019-12-22T03:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:13:46.000Z", "max_issues_repo_path": "Code/cPers/cPers/PersistenceCubic.cpp", "max_issues_repo_name": "HuXiaoling/TopoNet", "max_issues_repo_head_hexsha": "5cb98177de50a3694f5886137ff7c6f55fd51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-12-17T06:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T09:04:19.000Z", "max_forks_repo_path": "Code/cPers/cPers/PersistenceCubic.cpp", "max_forks_repo_name": "HuXiaoling/TopoNet", "max_forks_repo_head_hexsha": "5cb98177de50a3694f5886137ff7c6f55fd51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-01-02T06:16:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-30T17:12:39.000Z", "avg_line_length": 25.5, "max_line_length": 88, "alphanum_fraction": 0.6540880503, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.032589741359985346, "lm_q1q2_score": 0.016294870679992673}}
{"text": "#include \"puppeteer.hpp\"\n\n#include \"file_io/vtk_solution_reader.hpp\"\n#include \"file_io/vtk_solution_writer.hpp\"\n#include \"governing_equations/cahn_hilliard/cahn_hilliard_2d_fd.hpp\"\n#include \"governing_equations/cahn_hilliard/cahn_hilliard_3d_fd.hpp\"\n#include \"governing_equations/cahn_hilliard/cahn_hilliard_initial_conditions.hpp\"\n#include \"governing_equations/cahn_hilliard/cahn_hilliard_parameters.hpp\"\n#include \"governing_equations/cahn_hilliard/cahn_hilliard_solution_monitor.hpp\"\n#include \"governing_equations/initial_conditions.hpp\"\n#include \"governing_equations/initial_conditions_from_file.hpp\"\n#include \"governing_equations/residual_calculator.hpp\"\n#include \"logger/logger.hpp\"\n#include \"spatial_discretization/discretization_2d_cart.hpp\"\n#include \"spatial_discretization/discretization_3d_cart.hpp\"\n#include \"time_stepping/time_integrator.hpp\"\n#include \"time_stepping/time_integrator_options.hpp\"\n#include \"utils/registry.hpp\"\n\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n#include <iomanip>\n\n\nPuppeteer::Puppeteer(const std::vector<std::string>& cmd_line)\n{\n  ProgramOptionsParser parser;\n  parser.parseInputOptions(cmd_line);\n\n  Logger::get().initLogFile(Options::get().log_file());\n  Logger::get().InfoMessage(parser.getConfigurationFileTemplate());\n\n  const auto init_cond_file = Options::get().initial_condition_file();\n  if (init_cond_file != \"none\") {\n    solution_reader_ = std::make_unique<VTKSolutionReader>(init_cond_file);\n    Logger::get().InfoMessage(\"Using initial conditions file \" + init_cond_file);\n  }\n\n  file_output_string_ = [&]() {\n    if (Options::get().solution_output_file().empty()) {\n      return Options::get().log_file();\n    }\n    return Options::get().solution_output_file();\n  }();\n\n  //\n  // construct the primary simulation components\n  //\n  geom_               = geomFactory();\n  rhs_                = rhsFactory(*geom_);\n  initial_conditions_ = initialConditionsFactory();\n  time_integrator_    = timeIntegratorFactory(*rhs_);\n\n  //\n  // construct and attach observers\n  //\n  attachResidualObservers(*time_integrator_, *rhs_);\n  attachSolutionObservers(*time_integrator_, *geom_, *rhs_);\n  attachTimeObservers(*time_integrator_);\n\n  time_integrator_->setNotifyFrequency(Event::TimeStepComplete, Options::get().log_frequency());\n  time_integrator_->setNotifyFrequency(Event::SolutionUpdate, Options::get().save_every());\n}\n\n\nPuppeteer::~Puppeteer() = default;\n\n\nvoid\nPuppeteer::run()\n{\n  profile();\n  auto run_timer = Logger::get().timer(\"Starting solver\");\n\n  time_integrator_->solve(*rhs_, *initial_conditions_);\n\n  write_solution_to_vtk(time_integrator_->getCurrentSolutionState(), *geom_, file_output_string_ + \"_final\");\n\n  Logger::get().InfoMessage(Profiler::get().finalize());\n}\n\nnamespace {\nBCType\nparseBC(const std::string bcstr)\n{\n  if (bcstr == \"periodic\") {\n    return BCType::Periodic;\n  }\n  if (bcstr == \"neumann\") {\n    return BCType::Neumann;\n  }\n  Logger::get().FatalMessage(\"BC type string \" + bcstr + \" not recognized.\");\n  abort();\n}\n}  // namespace\n\n\nstd::unique_ptr<SpatialDiscretization>\nPuppeteer::geomFactory()\n{\n  CartesianDomainDefinition domain;\n\n  if (solution_reader_) {\n    domain = solution_reader_->getCartesianDomain();\n  }\n  else {\n    domain.nx   = Options::get().domain_resolution();\n    domain.ny   = domain.nx;\n    domain.nz   = domain.nx;\n    domain.xbeg = Options::get().domain_x_begin();\n    domain.xend = Options::get().domain_x_end();\n    domain.ybeg = Options::get().domain_x_begin();\n    domain.zbeg = Options::get().domain_x_begin();\n  }\n\n  domain.nhalo = 2;  // should be dependent on equation and order / stencil size\n\n  domain.xbc = parseBC(Options::get().bc_x());\n  domain.ybc = parseBC(Options::get().bc_y());\n  domain.zbc = parseBC(Options::get().bc_z());\n\n  const int dim = Options::get().dimension();\n  switch (dim) {\n    case 2:\n      return std::make_unique<Discretization2DCart>(domain);\n    case 3:\n      return std::make_unique<Discretization3DCart>(domain);\n    default:\n      Logger::get().FatalMessage(\"Only dimensions 2 and 3 supported.\");\n  }\n  return nullptr;\n}\n\n\nstd::unique_ptr<TimeIntegrableRHS>\nPuppeteer::rhsFactory(SpatialDiscretization& geom)\n{\n  Logger::get().FatalAssert(\n      Options::get().equation_type() == \"cahn-hilliard\", \"Only equation_type=cahn-hilliard currently supported.\");\n\n  CahnHilliardParameters params;\n\n  const int dim = Options::get().dimension();\n  switch (dim) {\n    case 2:\n      return std::make_unique<CahnHilliard2DFD>(dynamic_cast<Discretization2DCart&>(geom), params);\n      ;\n    case 3:\n      return std::make_unique<CahnHilliard3DFD>(dynamic_cast<Discretization3DCart&>(geom), params);\n      ;\n    default:\n      Logger::get().FatalMessage(\"Only dimensions 2 and 3 supported.\");\n  }\n\n  return nullptr;\n}\n\n\nstd::unique_ptr<InitialConditions>\nPuppeteer::initialConditionsFactory()\n{\n  Logger::get().FatalAssert(\n      Options::get().equation_type() == \"cahn-hilliard\", \"Only equation_type=cahn-hilliard currently supported.\");\n\n  if (solution_reader_) {\n    return std::make_unique<InitialConditionsFromFile>(*solution_reader_);\n  }\n  else {\n    CahnHilliardParameters params;\n    return std::make_unique<CahnHilliardInitialConditions>(params);\n  }\n}\n\n\nstd::unique_ptr<TimeIntegrator>\nPuppeteer::timeIntegratorFactory(TimeIntegrableRHS& rhs)\n{\n  auto time_opts = getTimeOptionsUsingGlobalOptions();\n  return FactoryRegistry<TimeIntegrator>::get().lookup(Options::get().time_integrator())(rhs, time_opts);\n}\n\n\nvoid\nPuppeteer::attachTimeObservers(TimeIntegrator& time_integrator)\n{\n  time_integrator.registerObserver(\n      Event::TimeStepComplete, [&]() { Logger::get().setTimeMonitor(time_integrator.getIterationStatus()); });\n\n  time_integrator.registerObserver(Event::TimeStepComplete, [&]() { Logger::get().updateLog(); });\n}\n\nvoid\nPuppeteer::attachResidualObservers(TimeIntegrator& time_integrator, TimeIntegrableRHS& rhs)\n{\n  time_integrator.registerObserver(Event::TimeStepComplete, [&]() {\n    Logger::get().setResidualMonitor(residual_calculator(rhs, time_integrator.getCurrentResidual()));\n  });\n}\n\nvoid\nPuppeteer::attachSolutionObservers(TimeIntegrator& time_integrator, SpatialDiscretization& geom, TimeIntegrableRHS& rhs)\n{\n  const int dim = Options::get().dimension();\n  switch (dim) {\n    case 2:\n      time_integrator.registerObserver(Event::TimeStepComplete, [&]() {\n        Logger::get().setSolutionMonitor(cahn_hilliard_solution_monitor(\n            rhs, dynamic_cast<Discretization2DCart&>(geom), time_integrator.getCurrentSolutionState()));\n      });\n      break;\n    case 3:\n      time_integrator.registerObserver(Event::TimeStepComplete, [&]() {\n        Logger::get().setSolutionMonitor(cahn_hilliard_solution_monitor(\n            rhs, dynamic_cast<Discretization3DCart&>(geom), time_integrator.getCurrentSolutionState()));\n      });\n      break;\n    default:\n      Logger::get().FatalMessage(\"Only dimensions 2 and 3 supported.\");\n  }\n\n  const int save_every = Options::get().save_every();\n\n  if (save_every) {\n    time_integrator.registerObserver(Event::SolutionUpdate, [&]() {\n      const int   iterwidth  = int(log10(Options::get().max_time_steps()) + 1);\n      std::string iterstring = boost::lexical_cast<std::string>(time_integrator.getCurrentStep());\n      iterstring.erase(std::remove(iterstring.begin(), iterstring.end(), ','), iterstring.end());\n\n      std::ostringstream ss;\n      ss << std::setw(iterwidth) << std::setfill('0') << iterstring;\n      write_solution_to_vtk(\n          time_integrator_->getCurrentSolutionState(), *geom_, file_output_string_ + \"_step_\" + ss.str());\n    });\n  }\n}\n", "meta": {"hexsha": "8607e33545828d16ae214a255c8df259a9e69df0", "size": 7588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "initialization/puppeteer.cpp", "max_stars_repo_name": "mlohry/maDGiCart-CH", "max_stars_repo_head_hexsha": "36723e992449fce670d17279b606f54d4b5b5545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-25T19:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:10:39.000Z", "max_issues_repo_path": "initialization/puppeteer.cpp", "max_issues_repo_name": "mlohry/maDGiCart-CH", "max_issues_repo_head_hexsha": "36723e992449fce670d17279b606f54d4b5b5545", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2021-12-17T14:58:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T21:25:35.000Z", "max_forks_repo_path": "initialization/puppeteer.cpp", "max_forks_repo_name": "mlohry/maDGiCart-CH", "max_forks_repo_head_hexsha": "36723e992449fce670d17279b606f54d4b5b5545", "max_forks_repo_licenses": ["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.1525423729, "max_line_length": 120, "alphanum_fraction": 0.7239061676, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.05921024825110538, "lm_q1q2_score": 0.016290499952669645}}
{"text": "// Copyright (c) 2018, 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 \"base/pose.h\"\n\n#include <Eigen/Eigenvalues>\n\n#include \"base/projection.h\"\n#include \"base/triangulation.h\"\n\nnamespace colmap {\n\nEigen::Matrix3d CrossProductMatrix(const Eigen::Vector3d& vector) {\n  Eigen::Matrix3d matrix;\n  matrix << 0, -vector(2), vector(1), vector(2), 0, -vector(0), -vector(1),\n      vector(0), 0;\n  return matrix;\n}\n\nvoid RotationMatrixToEulerAngles(const Eigen::Matrix3d& R, double* rx,\n                                 double* ry, double* rz) {\n  *rx = std::atan2(-R(1, 2), R(2, 2));\n  *ry = std::asin(R(0, 2));\n  *rz = std::atan2(-R(0, 1), R(0, 0));\n\n  *rx = IsNaN(*rx) ? 0 : *rx;\n  *ry = IsNaN(*ry) ? 0 : *ry;\n  *rz = IsNaN(*rz) ? 0 : *rz;\n}\n\nEigen::Matrix3d EulerAnglesToRotationMatrix(const double rx, const double ry,\n                                            const double rz) {\n  const Eigen::Matrix3d Rx =\n      Eigen::AngleAxisd(rx, Eigen::Vector3d::UnitX()).toRotationMatrix();\n  const Eigen::Matrix3d Ry =\n      Eigen::AngleAxisd(ry, Eigen::Vector3d::UnitY()).toRotationMatrix();\n  const Eigen::Matrix3d Rz =\n      Eigen::AngleAxisd(rz, Eigen::Vector3d::UnitZ()).toRotationMatrix();\n  return Rz * Ry * Rx;\n}\n\nEigen::Vector4d RotationMatrixToQuaternion(const Eigen::Matrix3d& rot_mat) {\n  const Eigen::Quaterniond quat(rot_mat);\n  return EigenQuaternionToQuaternion(quat);\n}\n\nEigen::Vector4d EigenQuaternionToQuaternion(const Eigen::Quaterniond& quat) {\n  return Eigen::Vector4d(quat.w(), quat.x(), quat.y(), quat.z());\n}\n\nEigen::Quaterniond QuaternionToEigenQuaternion(const Eigen::Vector4d& quat) {\n  return Eigen::Quaterniond(quat(0), quat(1), quat(2), quat(3));\n}\n\nEigen::Matrix3d QuaternionToRotationMatrix(const Eigen::Vector4d& qvec) {\n  const Eigen::Vector4d normalized_qvec = NormalizeQuaternion(qvec);\n  const Eigen::Quaterniond quat(normalized_qvec(0), normalized_qvec(1),\n                                normalized_qvec(2), normalized_qvec(3));\n  return quat.toRotationMatrix();\n}\n\nEigen::Vector4d NormalizeQuaternion(const Eigen::Vector4d& qvec) {\n  const double norm = qvec.norm();\n  if (norm == 0) {\n    // We do not just use (1, 0, 0, 0) because that is a constant and when used\n    // for automatic differentiation that would lead to a zero derivative.\n    return Eigen::Vector4d(1.0, qvec(1), qvec(2), qvec(3));\n  } else {\n    return qvec / norm;\n  }\n}\n\nEigen::Vector4d InvertQuaternion(const Eigen::Vector4d& qvec) {\n  return Eigen::Vector4d(qvec(0), -qvec(1), -qvec(2), -qvec(3));\n}\n\nEigen::Vector4d ConcatenateQuaternions(const Eigen::Vector4d& qvec1,\n                                       const Eigen::Vector4d& qvec2) {\n  const Eigen::Vector4d normalized_qvec1 = NormalizeQuaternion(qvec1);\n  const Eigen::Vector4d normalized_qvec2 = NormalizeQuaternion(qvec2);\n  const Eigen::Quaterniond quat1(normalized_qvec1(0), normalized_qvec1(1),\n                                 normalized_qvec1(2), normalized_qvec1(3));\n  const Eigen::Quaterniond quat2(normalized_qvec2(0), normalized_qvec2(1),\n                                 normalized_qvec2(2), normalized_qvec2(3));\n  const Eigen::Quaterniond cat_quat = quat2 * quat1;\n  return NormalizeQuaternion(EigenQuaternionToQuaternion(cat_quat));\n}\n\nEigen::Vector3d QuaternionRotatePoint(const Eigen::Vector4d& qvec,\n                                      const Eigen::Vector3d& point) {\n  const Eigen::Vector4d normalized_qvec = NormalizeQuaternion(qvec);\n  const Eigen::Quaterniond quat(normalized_qvec(0), normalized_qvec(1),\n                                normalized_qvec(2), normalized_qvec(3));\n  return quat * point;\n}\n\nEigen::Vector4d AverageQuaternions(const std::vector<Eigen::Vector4d>& qvecs,\n                                   const std::vector<double>& weights) {\n  CHECK_EQ(qvecs.size(), weights.size());\n  CHECK_GT(qvecs.size(), 0);\n\n  if (qvecs.size() == 1) {\n    return qvecs[0];\n  }\n\n  Eigen::Matrix4d A = Eigen::Matrix4d::Zero();\n  double weight_sum = 0;\n\n  for (size_t i = 0; i < qvecs.size(); ++i) {\n    CHECK_GT(weights[i], 0);\n    const Eigen::Vector4d qvec = NormalizeQuaternion(qvecs[i]);\n    A += weights[i] * qvec * qvec.transpose();\n    weight_sum += weights[i];\n  }\n\n  A.array() /= weight_sum;\n\n  const Eigen::Matrix4d eigenvectors =\n      Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d>(A).eigenvectors();\n\n  return eigenvectors.col(3);\n}\n\nEigen::Matrix3d RotationFromUnitVectors(const Eigen::Vector3d& vector1,\n                                        const Eigen::Vector3d& vector2) {\n  const Eigen::Vector3d v1 = vector1.normalized();\n  const Eigen::Vector3d v2 = vector2.normalized();\n  const Eigen::Vector3d v = v1.cross(v2);\n  const Eigen::Matrix3d v_x = CrossProductMatrix(v);\n  const double c = v1.dot(v2);\n  if (c == -1) {\n    return Eigen::Matrix3d::Identity();\n  } else {\n    return Eigen::Matrix3d::Identity() + v_x + 1 / (1 + c) * (v_x * v_x);\n  }\n}\n\nEigen::Vector3d ProjectionCenterFromMatrix(\n    const Eigen::Matrix3x4d& proj_matrix) {\n  return -proj_matrix.leftCols<3>().transpose() * proj_matrix.rightCols<1>();\n}\n\nEigen::Vector3d ProjectionCenterFromPose(const Eigen::Vector4d& qvec,\n                                         const Eigen::Vector3d& tvec) {\n  // Inverse rotation as conjugate quaternion.\n  const Eigen::Vector4d normalized_qvec = NormalizeQuaternion(qvec);\n  const Eigen::Quaterniond quat(normalized_qvec(0), -normalized_qvec(1),\n                                -normalized_qvec(2), -normalized_qvec(3));\n  return quat * -tvec;\n}\n\nvoid ComputeRelativePose(const Eigen::Vector4d& qvec1,\n                         const Eigen::Vector3d& tvec1,\n                         const Eigen::Vector4d& qvec2,\n                         const Eigen::Vector3d& tvec2, Eigen::Vector4d* qvec12,\n                         Eigen::Vector3d* tvec12) {\n  const Eigen::Vector4d inv_qvec1 = InvertQuaternion(qvec1);\n  *qvec12 = ConcatenateQuaternions(inv_qvec1, qvec2);\n  *tvec12 = tvec2 - QuaternionRotatePoint(*qvec12, tvec1);\n}\n\nvoid ConcatenatePoses(const Eigen::Vector4d& qvec1,\n                      const Eigen::Vector3d& tvec1,\n                      const Eigen::Vector4d& qvec2,\n                      const Eigen::Vector3d& tvec2, Eigen::Vector4d* qvec12,\n                      Eigen::Vector3d* tvec12) {\n  *qvec12 = ConcatenateQuaternions(qvec1, qvec2);\n  *tvec12 = tvec2 + QuaternionRotatePoint(qvec2, tvec1);\n}\n\nvoid InvertPose(const Eigen::Vector4d& qvec, const Eigen::Vector3d& tvec,\n                Eigen::Vector4d* inv_qvec, Eigen::Vector3d* inv_tvec) {\n  *inv_qvec = InvertQuaternion(qvec);\n  *inv_tvec = -QuaternionRotatePoint(*inv_qvec, tvec);\n}\n\nvoid InterpolatePose(const Eigen::Vector4d& qvec1, const Eigen::Vector3d& tvec1,\n                     const Eigen::Vector4d& qvec2, const Eigen::Vector3d& tvec2,\n                     const double t, Eigen::Vector4d* qveci,\n                     Eigen::Vector3d* tveci) {\n  const Eigen::Vector4d normalized_qvec1 = NormalizeQuaternion(qvec1);\n  const Eigen::Vector4d normalized_qvec2 = NormalizeQuaternion(qvec2);\n  const Eigen::Quaterniond quat1(normalized_qvec1(0), normalized_qvec1(1),\n                                 normalized_qvec1(2), normalized_qvec1(3));\n  const Eigen::Quaterniond quat2(normalized_qvec2(0), normalized_qvec2(1),\n                                 normalized_qvec2(2), normalized_qvec2(3));\n  const Eigen::Vector3d tvec12 = tvec2 - tvec1;\n\n  const Eigen::Quaterniond quati = quat1.slerp(t, quat2);\n\n  *qveci = EigenQuaternionToQuaternion(quati);\n  *tveci = tvec1 + tvec12 * t;\n}\n\nEigen::Vector3d CalculateBaseline(const Eigen::Vector4d& qvec1,\n                                  const Eigen::Vector3d& tvec1,\n                                  const Eigen::Vector4d& qvec2,\n                                  const Eigen::Vector3d& tvec2) {\n  const Eigen::Vector3d center1 = ProjectionCenterFromPose(qvec1, tvec1);\n  const Eigen::Vector3d center2 = ProjectionCenterFromPose(qvec2, tvec2);\n  return center2 - center1;\n}\n\nbool CheckCheirality(const Eigen::Matrix3d& R, const Eigen::Vector3d& t,\n                     const std::vector<Eigen::Vector2d>& points1,\n                     const std::vector<Eigen::Vector2d>& points2,\n                     std::vector<Eigen::Vector3d>* points3D) {\n  CHECK_EQ(points1.size(), points2.size());\n  const Eigen::Matrix3x4d proj_matrix1 = Eigen::Matrix3x4d::Identity();\n  const Eigen::Matrix3x4d proj_matrix2 = ComposeProjectionMatrix(R, t);\n  const double kMinDepth = std::numeric_limits<double>::epsilon();\n  const double max_depth = 1000.0f * (R.transpose() * t).norm();\n  points3D->clear();\n  for (size_t i = 0; i < points1.size(); ++i) {\n    const Eigen::Vector3d point3D =\n        TriangulatePoint(proj_matrix1, proj_matrix2, points1[i], points2[i]);\n    const double depth1 = CalculateDepth(proj_matrix1, point3D);\n    if (depth1 > kMinDepth && depth1 < max_depth) {\n      const double depth2 = CalculateDepth(proj_matrix2, point3D);\n      if (depth2 > kMinDepth && depth2 < max_depth) {\n        points3D->push_back(point3D);\n      }\n    }\n  }\n  return !points3D->empty();\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "3ede5f32f56895ec527f74cd248a3b1a9b1ac7b1", "size": 10661, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/base/pose.cc", "max_stars_repo_name": "Pascal-So/colmap", "max_stars_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-08T11:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-05T09:00:33.000Z", "max_issues_repo_path": "src/base/pose.cc", "max_issues_repo_name": "Pascal-So/colmap", "max_issues_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/pose.cc", "max_forks_repo_name": "Pascal-So/colmap", "max_forks_repo_head_hexsha": "7c82a22a2ac97e54272d54a1c7276cb293bcdd2f", "max_forks_repo_licenses": ["BSD-3-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.4824902724, "max_line_length": 80, "alphanum_fraction": 0.6615702092, "num_tokens": 2869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.03308597838870413, "lm_q1q2_score": 0.01628452602163482}}
{"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_LOGICAL_DETAIL_LOGICAL_FWD_HPP\n#define BOOST_HANA_LOGICAL_DETAIL_LOGICAL_FWD_HPP\n\n#include <boost/hana/core/typeclass.hpp>\n#include <boost/hana/detail/constexpr.hpp>\n#include <boost/hana/detail/variadic/foldl.hpp>\n\n\nnamespace boost { namespace hana {\n    namespace logical_detail { namespace operators { struct enable { }; }}\n\n    //! @ingroup group-typeclasses\n    //! The `Logical` type class is for data types acting like a boolean.\n    //!\n    //! @anchor Logical_terminology\n    //! ### Terminology\n    //! Let `x` be a `Logical`. Then, we say that `x` is true-valued if and\n    //! only if `or_(x, y) == x` for all `Logical`s `y`. Conversely, we say\n    //! that `x` is false-valued if and only if `and_(x, y) == y` for all\n    //! `Logical`s `y`.\n    //!\n    //! Also, we say that `x` is a _compile-time_ `Logical` if and only if\n    //! it can have values of different types in both branches of the `if_`\n    //! method.\n    //!\n    //!\n    //! @bug\n    //! We don't short-circuit right now. Don't forget to change the examples\n    //! and unit tests when that's implemented.\n    //!\n    //! @todo\n    //! Consider making this a real boolean algebra.\n    struct Logical {\n        BOOST_HANA_TYPECLASS(Logical);\n        struct mcd;\n        using operators = logical_detail::operators::enable;\n    };\n\n    //! Conditionally return one of two values based on a condition.\n    //! @relates Logical\n    //!\n    //! Specifically, `then_` is returned iff `logical` is true-valued, and\n    //! `else_` is returned otherwise. Note that some `Logical` instances\n    //! may allow values of different types while others may require both\n    //! values to have the same type.\n    //!\n    //!\n    //! @param logical\n    //! The condition determining which of the two values is returned.\n    //!\n    //! @param then_\n    //! The value returned when `logical` is true-valued.\n    //!\n    //! @param else_\n    //! The value returned when `logical` is false-valued.\n    //!\n    //!\n    //! ### Example\n    //! @snippet example/logical/if.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto if_ = [](auto logical, auto then_, auto else_) {\n        return Logical::instance<\n            datatype_t<decltype(logical)>\n        >::if_impl(logical, then_, else_);\n    };\n\n    //! Conditionally execute one of two branches based on a condition.\n    //! @relates Logical\n    //!\n    //! The selected branch will be invoked with an identity function, wich\n    //! allows making types and values dependent inside a lambda and achieve\n    //! a lazy-like behavior. However, type instantiation laziness can only\n    //! be achieved with `Integral` conditions or equivalent. The result of\n    //! the `eval_if` is the result of the invoked branch.\n    //!\n    //!\n    //! @param logical\n    //! The condition determining which of the two branches is selected.\n    //!\n    //! @param then_branch\n    //! A function called as `then_branch([](auto x) { return x; })` iff\n    //! `logical` is true-valued.\n    //!\n    //! @param else_branch\n    //! A function called as `else_branch([](auto x) { return x; })` iff\n    //! `logical` is false-valued.\n    //!\n    //!\n    //! ### Example (purely compile-time condition)\n    //! @snippet example/logical/eval_if.cpp heterogeneous\n    //!\n    //! ### Example (runtime or `constexpr` condition)\n    //! @snippet example/logical/eval_if.cpp homogeneous\n    BOOST_HANA_CONSTEXPR_LAMBDA auto eval_if = [](auto logical, auto then_branch, auto else_branch) {\n        return Logical::instance<\n            datatype_t<decltype(logical)>\n        >::eval_if_impl(logical, then_branch, else_branch);\n    };\n\n    //! Negates a `Logical`.\n    //! @relates Logical\n    //!\n    //! Specifically, `not_(x)` returns a false-valued `Logical` iff `x`\n    //! is a true-valued `Logical`, and a true-valued one otherwise.\n    //!\n    //! ### Example\n    //! @snippet example/logical/not.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto not_ = [](auto logical) {\n        return Logical::instance<\n            datatype_t<decltype(logical)>\n        >::not_impl(logical);\n    };\n\n    namespace logical_detail {\n        BOOST_HANA_CONSTEXPR_LAMBDA auto and2 = [](auto x, auto y) {\n            return Logical::instance<datatype_t<decltype(x)>>::and_impl(x, y);\n        };\n\n        BOOST_HANA_CONSTEXPR_LAMBDA auto or2 = [](auto x, auto y) {\n            return Logical::instance<datatype_t<decltype(x)>>::or_impl(x, y);\n        };\n    }\n\n    //! Return whether all the arguments are true-valued.\n    //! @relates Logical\n    //!\n    //! `and_` can be called with one argument or more. When called with\n    //! two arguments, `and_` dispatches to the type class implementation.\n    //! Otherwise,\n    //! @code\n    //!     and_(x) == x\n    //!     and_(x, y, ...z) == and_(and_(x, y), z...)\n    //! @endcode\n    //!\n    //! ### Example\n    //! @snippet example/logical/and.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto and_ = [](auto x, auto ...y) {\n        return detail::variadic::foldl(logical_detail::and2, x, y...);\n    };\n\n    //! Return whether any of the arguments is true-valued.\n    //! @relates Logical\n    //!\n    //! `or_` can be called with one argument or more. When called with\n    //! two arguments, `or_` dispatches to the type class implementation.\n    //! Otherwise,\n    //! @code\n    //!     or_(x) == x\n    //!     or_(x, y, ...z) == or_(or_(x, y), z...)\n    //! @endcode\n    //!\n    //! ### Example\n    //! @snippet example/logical/or.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto or_ = [](auto x, auto ...y) {\n        return detail::variadic::foldl(logical_detail::or2, x, y...);\n    };\n\n    namespace logical_detail { namespace operators {\n        //! Equivalent to `and_`.\n        //! @relates boost::hana::Logical\n        template <typename X, typename Y>\n        constexpr auto operator&&(X x, Y y)\n        { return and_(x, y); }\n\n        //! Equivalent to `or_`.\n        //! @relates boost::hana::Logical\n        template <typename X, typename Y>\n        constexpr auto operator||(X x, Y y)\n        { return or_(x, y); }\n\n        //! Equivalent to `not_`.\n        //! @relates boost::hana::Logical\n        template <typename X>\n        constexpr auto operator!(X x)\n        { return not_(x); }\n    }}\n}} // end namespace boost::hana\n\n#endif // !BOOST_HANA_LOGICAL_DETAIL_LOGICAL_FWD_HPP\n", "meta": {"hexsha": "8327e4db33a8731a17d1a4a85d7d4eedee09f818", "size": 6545, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/hana/logical/detail/logical_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/logical/detail/logical_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/logical/detail/logical_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": 34.8138297872, "max_line_length": 101, "alphanum_fraction": 0.6137509549, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.051845471411056325, "lm_q1q2_score": 0.016282099217705615}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Standard includes\n#include <exception>\n#include <fstream>\n\n// Third party includes\n#include <boost/format.hpp>\n#include <boost/progress.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n#include <votca/tools/property.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/eigen.h\"\n#include \"votca/xtp/gnode.h\"\n#include \"votca/xtp/qmstate.h\"\n#include \"votca/xtp/topology.h\"\n\n// Local private VOTCA includes\n#include \"kmclifetime.h\"\n\nnamespace votca {\nnamespace xtp {\n\nvoid KMCLifetime::ParseSpecificOptions(const tools::Property& options) {\n\n  insertions_ = options.get(\".numberofinsertions\").as<unsigned long>();\n  lifetimefile_ = options.get(\".lifetimefile\").as<std::string>();\n\n  probfile_ = options.ifExistsReturnElseReturnDefault<std::string>(\n      \".decayprobfile\", \"\");\n\n  const tools::Property& carrier_options = options.get(\".carrierenergy\");\n  do_carrierenergy_ = carrier_options.get(\".run\").as<bool>();\n  energy_outputfile_ = carrier_options.get(\".outputfile\").as<std::string>();\n  alpha_ = carrier_options.get(\".alpha\").as<double>();\n  outputsteps_ = carrier_options.get(\".outputsteps\").as<unsigned long>();\n\n  log_.setReportLevel(Log::current_level);\n  log_.setCommonPreface(\"\\n ...\");\n\n  carriertype_ = QMStateType(QMStateType::Singlet);\n  XTP_LOG(Log::error, log_)\n      << \"carrier type:\" << carriertype_.ToLongString() << std::flush;\n  field_ = Eigen::Vector3d::Zero();\n}\n\nvoid KMCLifetime::WriteDecayProbability(std::string filename) {\n\n  Eigen::VectorXd outrates = Eigen::VectorXd::Zero(nodes_.size());\n  Eigen::VectorXd inrates = Eigen::VectorXd::Zero(nodes_.size());\n  Eigen::VectorXd decayrates = Eigen::VectorXd::Ones(nodes_.size());\n\n  for (unsigned i = 0; i < nodes_.size(); i++) {\n    GNode& node = nodes_[i];\n    if (node.canDecay()) {\n      for (const GLink& event : node.Events()) {\n        if (event.isDecayEvent()) {\n          decayrates[i] = event.getRate();\n        } else {\n          inrates[event.getDestination()->getId()] += event.getRate();\n          outrates[i] += event.getRate();\n        }\n      }\n    }\n  }\n  outrates = decayrates.cwiseQuotient(outrates + decayrates);\n  inrates = decayrates.cwiseQuotient(inrates + decayrates);\n\n  std::fstream probs;\n  probs.open(filename, std::fstream::out);\n  if (!probs.is_open()) {\n    std::string error_msg = \"Unable to write to file \" + filename;\n    throw std::runtime_error(error_msg);\n  }\n  probs << \"#SiteID, Relative Prob outgoing, Relative Prob ingoing\\n\";\n  for (unsigned i = 0; i < nodes_.size(); i++) {\n    probs << nodes_[i].getId() << \" \" << outrates[i] << \" \" << inrates[i]\n          << std::endl;\n  }\n  probs.close();\n  return;\n}\n\nvoid KMCLifetime::ReadLifetimeFile(std::string filename) {\n  tools::Property xml;\n  xml.LoadFromXML(filename);\n  std::vector<tools::Property*> jobProps = xml.Select(\"lifetimes.site\");\n  if (jobProps.size() != nodes_.size()) {\n    throw std::runtime_error(\n        (boost::format(\"The number of sites in the topology: %i does not match \"\n                       \"the number in the lifetimefile: %i\") %\n         nodes_.size() % jobProps.size())\n            .str());\n  }\n\n  for (tools::Property* prop : jobProps) {\n    Index site_id = prop->getAttribute<Index>(\"id\");\n    double lifetime = boost::lexical_cast<double>(prop->value());\n    bool check = false;\n    for (auto& node : nodes_) {\n      if (node.getId() == site_id && !(node.canDecay())) {\n        node.AddDecayEvent(1.0 / lifetime);\n        check = true;\n        break;\n      } else if (node.getId() == site_id && node.canDecay()) {\n        throw std::runtime_error(\n            (boost::format(\"Node %i appears twice in your list\") % site_id)\n                .str());\n      }\n    }\n    if (!check) {\n      throw std::runtime_error(\n          (boost::format(\"Site from file with id: %i not found in state file\") %\n           site_id)\n              .str());\n    }\n  }\n  for (auto& node : nodes_) {\n    node.InitEscapeRate();\n    node.MakeHuffTree();\n  }\n  return;\n}\n\nvoid KMCLifetime::WriteToTraj(std::fstream& traj, unsigned long insertioncount,\n                              double simtime,\n                              const Chargecarrier& affectedcarrier) const {\n  const Eigen::Vector3d& dr_travelled = affectedcarrier.get_dRtravelled();\n  traj << simtime << \"\\t\" << insertioncount << \"\\t\" << affectedcarrier.getId()\n       << \"\\t\" << affectedcarrier.getLifetime() << \"\\t\"\n       << affectedcarrier.getSteps() << \"\\t\"\n       << affectedcarrier.getCurrentNodeId() + 1 << \"\\t\"\n       << dr_travelled.x() * tools::conv::bohr2nm << \"\\t\"\n       << dr_travelled.y() * tools::conv::bohr2nm << \"\\t\"\n       << dr_travelled.z() * tools::conv::bohr2nm << std::endl;\n}\n\nvoid KMCLifetime::RunVSSM() {\n\n  std::chrono::time_point<std::chrono::system_clock> realtime_start =\n      std::chrono::system_clock::now();\n  XTP_LOG(Log::error, log_)\n      << \"\\nAlgorithm: VSSM for Multiple Charges with finite Lifetime\\n\"\n         \"number of charges: \"\n      << numberofcarriers_ << \"\\nnumber of nodes: \" << nodes_.size()\n      << std::flush;\n\n  if (numberofcarriers_ > Index(nodes_.size())) {\n    throw std::runtime_error(\n        \"ERROR in kmclifetime: specified number of charges is greater than the \"\n        \"number of nodes. This conflicts with single occupation.\");\n  }\n\n  std::fstream traj;\n  std::fstream energyfile;\n\n  XTP_LOG(Log::error, log_)\n      << \"Writing trajectory to \" << trajectoryfile_ << \".\" << std::flush;\n\n  traj.open(trajectoryfile_, std::fstream::out);\n  if (!traj.is_open()) {\n    std::string error_msg = \"Unable to write to file \" + trajectoryfile_;\n    throw std::runtime_error(error_msg);\n  }\n\n  traj << \"#Simtime [s]\\t Insertion\\t Carrier ID\\t Lifetime[s]\\tSteps\\t Last \"\n          \"Segment\\t x_travelled[nm]\\t y_travelled[nm]\\t z_travelled[nm]\\n\";\n\n  if (do_carrierenergy_) {\n\n    XTP_LOG(Log::error, log_)\n        << \"Tracking the energy of one charge carrier and exponential average \"\n           \"with alpha=\"\n        << alpha_ << \" to \" << energy_outputfile_ << std::flush;\n    energyfile.open(energy_outputfile_, std::fstream::out);\n    if (!energyfile.is_open()) {\n      std::string error_msg = \"Unable to write to file \" + energy_outputfile_;\n      throw std::runtime_error(error_msg);\n    }\n\n    energyfile << \"Simtime [s]\\tSteps\\tCarrier ID\\tEnergy_a=\" << alpha_\n               << \"[eV]\\n\";\n  }\n\n  // Injection\n  XTP_LOG(Log::error, log_)\n      << \"\\ninjection method: \" << injectionmethod_ << std::flush;\n\n  RandomlyCreateCharges();\n\n  unsigned long insertioncount = 0;\n  unsigned long step = 0;\n  double simtime = 0.0;\n\n  std::vector<GNode*> forbiddennodes;\n  std::vector<GNode*> forbiddendests;\n\n  time_t now = time(nullptr);\n  tm* localtm = localtime(&now);\n  XTP_LOG(Log::error, log_)\n      << \"Run started at \" << asctime(localtm) << std::flush;\n\n  double avlifetime = 0.0;\n  double meanfreepath = 0.0;\n  Eigen::Vector3d difflength_squared = Eigen::Vector3d::Zero();\n\n  double avgenergy = carriers_[0].getCurrentEnergy();\n  Index carrieridold = carriers_[0].getId();\n\n  while (insertioncount < insertions_) {\n    std::chrono::duration<double> elapsed_time =\n        std::chrono::system_clock::now() - realtime_start;\n    if (elapsed_time.count() > (maxrealtime_ * 60. * 60.)) {\n      XTP_LOG(Log::error, log_)\n          << \"\\nReal time limit of \" << maxrealtime_ << \" hours (\"\n          << Index(maxrealtime_ * 60 * 60 + 0.5)\n          << \" seconds) has been reached. Stopping here.\\n\"\n          << std::flush;\n      break;\n    }\n\n    double cumulated_rate = 0;\n\n    for (const auto& carrier : carriers_) {\n      cumulated_rate += carrier.getCurrentEscapeRate();\n    }\n    if (cumulated_rate == 0) {  // this should not happen: no possible jumps\n                                // defined for a node\n      throw std::runtime_error(\n          \"ERROR in kmclifetime: Incorrect rates in the database file. All the \"\n          \"escape rates for the current setting are 0.\");\n    }\n    // go forward in time\n    double dt = Promotetime(cumulated_rate);\n\n    if (do_carrierenergy_) {\n      bool print = false;\n      if (carriers_[0].getId() > carrieridold) {\n        avgenergy = carriers_[0].getCurrentEnergy();\n        print = true;\n        carrieridold = carriers_[0].getId();\n      } else if (step % outputsteps_ == 0) {\n        avgenergy =\n            alpha_ * carriers_[0].getCurrentEnergy() + (1 - alpha_) * avgenergy;\n        print = true;\n      }\n      if (print) {\n        energyfile << simtime << \"\\t\" << step << \"\\t\" << carriers_[0].getId()\n                   << \"\\t\" << avgenergy * tools::conv::hrt2ev << std::endl;\n      }\n    }\n\n    simtime += dt;\n    step++;\n    for (auto& carrier : carriers_) {\n      carrier.updateLifetime(dt);\n      carrier.updateSteps(1);\n      carrier.updateOccupationtime(dt);\n    }\n\n    ResetForbiddenlist(forbiddennodes);\n    bool secondlevel = true;\n    while (secondlevel) {\n\n      // determine which carrier will escape\n      GNode* newnode = nullptr;\n      Chargecarrier* affectedcarrier = ChooseAffectedCarrier(cumulated_rate);\n\n      if (CheckForbidden(affectedcarrier->getCurrentNode(), forbiddennodes)) {\n        continue;\n      }\n\n      // determine where it will jump to\n      ResetForbiddenlist(forbiddendests);\n      boost::progress_display progress(insertions_);\n\n      while (true) {\n        // LEVEL 2\n\n        newnode = nullptr;\n        const GLink& event =\n            ChooseHoppingDest(affectedcarrier->getCurrentNode());\n\n        if (event.isDecayEvent()) {\n          const Eigen::Vector3d& dr_travelled =\n              affectedcarrier->get_dRtravelled();\n          avlifetime += affectedcarrier->getLifetime();\n          meanfreepath += dr_travelled.norm();\n          difflength_squared += dr_travelled.cwiseAbs2();\n          WriteToTraj(traj, insertioncount, simtime, *affectedcarrier);\n          ++progress;\n          RandomlyAssignCarriertoSite(*affectedcarrier);\n          affectedcarrier->resetCarrier();\n          insertioncount++;\n          affectedcarrier->setId(numberofcarriers_ - 1 + insertioncount);\n          secondlevel = false;\n          break;\n        } else {\n          newnode = event.getDestination();\n        }\n\n        // check after the event if this was allowed\n        if (CheckForbidden(*newnode, forbiddendests)) {\n          continue;\n        }\n\n        // if the new segment is unoccupied: jump; if not: add to forbidden list\n        // and choose new hopping destination\n        if (newnode->isOccupied()) {\n          if (CheckSurrounded(affectedcarrier->getCurrentNode(),\n                              forbiddendests)) {\n            AddtoForbiddenlist(affectedcarrier->getCurrentNode(),\n                               forbiddennodes);\n            break;  // select new escape node (ends level 2 but without setting\n                    // level1step to 1)\n          }\n          AddtoForbiddenlist(*newnode, forbiddendests);\n          continue;  // select new destination\n        } else {\n          affectedcarrier->jumpAccordingEvent(event);\n          secondlevel = false;\n\n          break;  // this ends LEVEL 2 , so that the time is updated and the\n                  // next MC step started\n        }\n\n        // END LEVEL 2\n      }\n      // END LEVEL 1\n    }\n  }\n\n  XTP_LOG(Log::error, log_)\n      << \"\\nTotal runtime:\\t\\t\\t\\t\\t\" << simtime\n      << \" s\\n\"\n         \"Total KMC steps:\\t\\t\\t\\t\"\n      << step << \"\\nAverage lifetime:\\t\\t\\t\\t\"\n      << avlifetime / double(insertioncount) << \" s\\n\"\n      << \"Mean freepath\\t l=<|r_x-r_o|> :\\t\\t\"\n      << (meanfreepath * tools::conv::bohr2nm / double(insertioncount))\n      << \" nm\\n\"\n      << \"Average diffusionlength\\t d=sqrt(<(r_x-r_o)^2>)\\t\"\n      << std::sqrt(difflength_squared.norm() / double(insertioncount)) *\n             tools::conv::bohr2nm\n      << \" nm\\n\"\n      << std::flush;\n\n  WriteOccupationtoFile(simtime, occfile_);\n  traj.close();\n  if (do_carrierenergy_) {\n    energyfile.close();\n  }\n  return;\n}\n\nbool KMCLifetime::Evaluate(Topology& top) {\n  XTP_LOG(Log::error, log_) << \"\\n-----------------------------------\"\n                               \"\\n      KMCLIFETIME started\"\n                               \"\\n-----------------------------------\\n\"\n                            << std::flush;\n\n  XTP_LOG(Log::info, log_) << \"\\nInitialising random number generator\"\n                           << std::flush;\n\n  RandomVariable_.init(seed_);\n  LoadGraph(top);\n  ReadLifetimeFile(lifetimefile_);\n\n  if (!probfile_.empty()) {\n    WriteDecayProbability(probfile_);\n  }\n  RunVSSM();\n\n  time_t now = time(nullptr);\n  tm* localtm = localtime(&now);\n\n  XTP_LOG(Log::info, log_) << \" KMCLIFETIME finished at:\" << asctime(localtm)\n                           << std::flush;\n  std::cout << log_;\n  return true;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "f6a1093ffb178c78fd94fc6e871b4ec52b727a33", "size": 13352, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/calculators/kmclifetime.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/calculators/kmclifetime.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/calculators/kmclifetime.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1315136476, "max_line_length": 80, "alphanum_fraction": 0.6079988017, "num_tokens": 3399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796659321433, "lm_q2_score": 0.03410042473069496, "lm_q1q2_score": 0.0162515690262988}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <NTL/lzz_pXFactoring.h>\nNTL_CLIENT\n#include \"FHE.h\"\n#include \"EncryptedArray.h\"\n\n#include <cstdlib>\n#include <cassert>\n#include <list>\n#include <sstream>\n\n#if (__cplusplus>199711L)\n#include <memory>\n#else\n#include <tr1/memory>\n#endif\n\n#include <NTL/vector.h>\n#include \"NumbTh.h\"\n#include \"permutations.h\"\n\nstatic void \nrecursiveGeneralBenesInit(long n, long k, long d, long delta_j,\n                          const Permut& perm, const Permut& iperm,\n                          Vec< Vec<short> >& level, Vec< Vec<short> >& ilevel)\n{\n  long sz = perm.length();\n\n  if (d == k-1) {\n    // recursion stops\n\n    if (sz == 1) {\n      level[d][delta_j] = 0;\n      ilevel[d][delta_j] = 0;\n    }\n  \n    if (sz == 2) {\n      // only two possibilities for perm: the identity perm or the swap perm\n  \n      if (perm[0] == 0) {\n        // the identity perm\n  \n        level[d][delta_j] = 0;\n        level[d][delta_j+1] = 0;\n        ilevel[d][delta_j] = 0;\n        ilevel[d][delta_j+1] = 0;\n      }\n      else {\n        // the swap perm\n  \n        level[d][delta_j] = 1;\n        level[d][delta_j+1] = -1;\n        ilevel[d][delta_j] = 1;\n        ilevel[d][delta_j+1] = -1;\n      }\n    }\n    return;\n  }\n\n  long nlev = 2*k-1;\n\n  long sz0 = GeneralBenesNetwork::shamt(n, k, d); // size of upper internal network\n  long sz1 = sz - sz0;\n\n  assert(labs(sz0-sz1) <= 1);\n\n  // id_perm: the identity permutation on {0,...,sz-1}\n  Permut id_perm;\n  id_perm.SetLength(sz);\n  for (long j = 0; j < sz; j++) id_perm[j] = j;\n  \n  // *xperm[0] is the perm on LHS of network\n  // *xperm[1] is the perm on RHS of network\n  // *xiperm[0] is the inv perm on LHS of network\n  // *xiperm[1] is the inv perm on RHS\n  const Permut *xperm[] = { &id_perm, &perm };\n  const Permut *xiperm[] = { &id_perm, &iperm };\n\n  // *first_level[0] is the first level when traversing left to right\n  // *first_level[1] is the first level when traversing right to left\n  // *ifirst_level[0] is the reversed first level when traversing left to right\n  // *ifirst_level[1] is the reversed first level when traversing right to left\n  Vec<short> *first_level[] = { &level[d], &ilevel[nlev-1-d] };\n  Vec<short> *ifirst_level[] = { &ilevel[d], &level[nlev-1-d] };\n\n  // *last_level[0] is the last level when traversing left to right\n  // *last_level[1] is the last level when traversing right to left\n  // *ilast_level[0] is the reversed last level when traversing left to right\n  // *ilast_level[1] is the reversed last level when traversing right to left\n  Vec<short> *last_level[] = { &level[nlev-1-d], &ilevel[d] };\n  Vec<short> *ilast_level[] = { &ilevel[nlev-1-d], &level[d] };\n\n  // inner_perm[0][0] upper internal perm\n  // inner_perm[0][1] upper internal inv perm\n  // inner_perm[1][0] lower internal perm\n  // inner_perm[1][1] lower internal inv perm\n  Permut inner_perm[2][2];\n\n  inner_perm[0][0].SetLength(sz0);\n  inner_perm[0][1].SetLength(sz0);\n  inner_perm[1][0].SetLength(sz1);\n  inner_perm[1][1].SetLength(sz1);\n\n  // marked[0] indicates which nodes on left have been marked\n  // marked[1] indicates which nodes on right have been marked\n  Vec<bool> marked[2];\n  marked[0].SetLength(sz);\n  for (long j = 0; j < sz; j++) marked[0][j] = false;\n  marked[1].SetLength(sz);\n  for (long j = 0; j < sz; j++) marked[1][j] = false;\n\n  // counter[0] is used to count through nodes on left side\n  // counter[1] is used to count through nodes on right side\n  long counter[2];\n  counter[0] = 0;\n  counter[1] = 0;\n\n\n\n  long dir = 0; // direction, initially left to right\n  long e = 0;  // current edge, initially straight\n\n  long node; // current node\n  long stop_node; // stopping node, initially undefined\n  long stop_side;  // stopping side\n  \n\n  if (sz0 == sz1) {\n    // an even split\n    node = 0;\n    stop_node = sz0;\n    stop_side = 0;\n  }\n  else if (sz0 > sz1) {\n    // an odd split, top larger\n    node = sz0-1;\n    stop_node = sz0-1;\n    stop_side = 1;\n  }\n  else { // sz0 < sz1\n    // an odd split, bottom larger\n    node = sz-1;\n    stop_node = sz-1;\n    stop_side = 1;\n  }\n\n \n\n  for (;;) {\n    marked[dir][node] = true; // mark current node\n\n    // traverse path through graph\n\n    long v = (*xperm[dir])[node]; // value associated with this node\n\n    long net = long(node >= sz0)^labs(e);\n       // net = 0 => upper internal network\n       // net = 1 => lower internal network\n\n    long node1 = node - sz0*long(node >= sz0); \n      // node adjacent to node in the internal network\n\n    long node3 = (*xiperm[1-dir])[v]; \n      // corresponding node of the other side of the external network\n\n    long node2 = node3 - sz0*long(node3 >= sz0);\n      // node adjacent to node3 in the internal network\n\n    long e2 = (node3 - (node2 + net*sz0))/sz0;\n      // edge type for edge connecting node2 to node3\n\n    /* here is the picture:\n     *\n     *         e                       e2\n     *  node ------ node1 ---- node2 ----- node3\n     *               \\           /\n     *                \\_________/\n     *                     |\n     *              internal network\n     */\n\n    // update external edges in level graph\n\n    (*first_level[dir])[delta_j+node] = e;\n    (*ifirst_level[dir])[delta_j+net*sz0+node1] = -e;\n\n    (*last_level[dir])[delta_j+net*sz0+node2] = e2;\n    (*ilast_level[dir])[delta_j+node3] = -e2;\n\n    // update internal permutations\n\n    inner_perm[net][dir][node2] = node1;\n    inner_perm[net][1-dir][node1] = node2;\n\n    // change direction\n    dir = 1-dir;\n\n    // mark node3 on new side\n    marked[dir][node3] = true;\n\n    // check for stop node\n    if (node3 == stop_node && dir == stop_side) {\n       // search for unmarked node \n\n      while (counter[dir] < sz && marked[dir][counter[dir]]) counter[dir]++;\n      if (counter[dir] >= sz) break; // we're done!!\n\n\n      // update node, e, stop_node, stop_side\n      node = counter[dir];\n      e = 0;\n\n      if (node < sz0)\n        stop_node = node + sz0;\n      else\n        stop_node = node - sz0; \n\n      stop_side = dir;\n    }\n    else {\n       // calculate sibling node and continue\n      if (node3 < sz0) \n        node = node3 + sz0; \n      else \n        node = node3 - sz0;\n\n      e = e2;\n    }\n  }\n\n  // done constructing the external edges and internal permutations...\n  // time to recurse\n\n  // recurse on upper internal network:\n  recursiveGeneralBenesInit(n, k, d+1, delta_j, \n                            inner_perm[0][0], inner_perm[0][1], level, ilevel);\n\n  // recurse on lower intrernal network\n  recursiveGeneralBenesInit(n, k, d+1, delta_j + sz0, \n                            inner_perm[1][0], inner_perm[1][1], level, ilevel);  \n}\n\n\nGeneralBenesNetwork::GeneralBenesNetwork(const Permut& perm)\n{\n  n = perm.length();\n\n  // check that n > 1\n  assert(n > 1);\n\n  // compute recursion depth k = least integer k s/t 2^k >= n\n  k = GeneralBenesNetwork::depth(n);\n\n  // construct the inverse perm, which is convenient in the recursive function.\n  // As a byproduct, verify that perm is indeed a permutation on {0,...,n-1}.\n\n  Permut iperm;\n  iperm.SetLength(n);\n\n  for (long j = 0; j < n; j++)\n    iperm[j] = -1;\n\n  for (long j = 0; j < n; j++) {\n    long j1 = perm[j];\n    assert(j1 >= 0 && j1 < n);\n    iperm[j1] = j;\n  }\n\n\n  for (long j = 0; j < n; j++)\n    assert(iperm[j] != -1);\n\n  // allocate space for the levels graph\n\n  level.SetLength(2*k-1);\n  for (long i = 0; i < 2*k-1; i++)\n    level[i].SetLength(n);\n\n  // allocate space for the reverse levels graph...\n  // makes the recursive construction more convenient\n\n  Vec< Vec<short> > ilevel;\n  ilevel.SetLength(2*k-1);\n  for (long i = 0; i < 2*k-1; i++)\n    ilevel[i].SetLength(n);\n\n  // recursively construct the levels graph\n\n  recursiveGeneralBenesInit(n, k, 0, 0, perm, iperm, level, ilevel);\n}\n\n\nbool GeneralBenesNetwork::testNetwork(const Permut& perm) const\n{\n  long sz = getSize();\n  long nlev = getNumLevels();\n\n  for (long j = 0; j < sz; j++) {\n    // find correct position for j\n\n    long j1 = j;\n    for (long i = 0; i < nlev; i++) {\n      const Vec<short>& lev = getLevel(i);\n      j1 += shamt(i)*lev[j1];\n    }\n    if (perm[j1] != j) return false;\n  }\n  return true;\n}\n", "meta": {"hexsha": "ed447d6d6d9538f65152b1a685cb789f6dd53c75", "size": 8721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BenesNetwork.cpp", "max_stars_repo_name": "Valenceo/HElib", "max_stars_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T17:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T06:46:20.000Z", "max_issues_repo_path": "src/BenesNetwork.cpp", "max_issues_repo_name": "Valenceo/HElib", "max_issues_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T21:41:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-18T21:37:26.000Z", "max_forks_repo_path": "src/BenesNetwork.cpp", "max_forks_repo_name": "Valenceo/HElib", "max_forks_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-10T07:24:51.000Z", "avg_line_length": 27.253125, "max_line_length": 83, "alphanum_fraction": 0.5994725376, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.036769467922763914, "lm_q1q2_score": 0.016240081414136173}}
{"text": "#ifndef HMLIB_ODEINT_INTERFERE_BREAKABLEINTEGRATECONST_INC\n#define HMLIB_ODEINT_INTERFERE_BREAKABLEINTEGRATECONST_INC 100\n#\n#include <tuple>\n#include <boost/numeric/odeint/util/unwrap_reference.hpp>\n#include <boost/numeric/odeint/util/unit_helper.hpp>\n#include <boost/numeric/odeint/util/detail/less_with_sign.hpp>\n#include <boost/numeric/odeint/integrate/null_observer.hpp>\n#include \"../utility.hpp\"\n#include \"../stepper_categories.hpp\"\nnamespace hmLib {\n\tnamespace odeint {\n\t\tnamespace detail {\n\t\t\tnamespace boost_odeint = boost::numeric::odeint;\n\n\t\t\t//breakable integrate const for simple stepper\n\t\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker, class Observer >\n\t\t\tstd::tuple<bool, size_t, Time> breakable_integrate_const(\n\t\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\t\tTime start_time, Time end_time, Time dt, Breaker breaker,\n\t\t\t\tObserver observer, stepper_tag\n\t\t\t){\n\t\t\t\ttypename boost_odeint::unwrap_reference< Observer >::type& obs = observer;\n\t\t\t\ttypename boost_odeint::unwrap_reference< Stepper >::type& st = stepper;\n\n\t\t\t\t// check breaker condition with the initial state\n\t\t\t\tbool IsBreak = breaker(start_state, start_time);\n\n\t\t\t\tTime time = start_time;\n\t\t\t\tint step = 0;\n\n\n\t\t\t\t// cast time+dt explicitely in case of expression templates (e.g. multiprecision)\n\t\t\t\twhile (!IsBreak && boost_odeint::detail::less_eq_with_sign(static_cast<Time>(time + dt), end_time, dt))\n\t\t\t\t{\n\t\t\t\t\tobs(start_state, time);\n\t\t\t\t\tst.do_step(sys, start_state, time, dt);\n\n\t\t\t\t\t// direct computation of the time avoids error propagation happening when using time += dt\n\t\t\t\t\t// we need clumsy type analysis to get boost units working here\n\t\t\t\t\t++step;\n\t\t\t\t\ttime = start_time + static_cast<typename boost_odeint::unit_value_type<Time>::type>(step) * dt;\n\n\t\t\t\t\t// check breaker condition\n\t\t\t\t\tIsBreak = breaker(start_state, time);\n\t\t\t\t}\n\t\t\t\tobs(start_state, time);\n\n\t\t\t\treturn std::make_tuple(IsBreak, step, time);\n\t\t\t}\n\n\n\t\t\t// forward declaration for breakable integrate const for controlled_stepper\n\t\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker, class Observer >\n\t\t\tstd::tuple<bool, size_t, Time> breakable_integrate_adaptive(\n\t\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\t\tTime start_time, Time end_time, Time dt, Breaker breaker,\n\t\t\t\tObserver observer, controlled_stepper_tag\n\t\t\t);\n\n\t\t\t//breakable integrate const for controlled_stepper\n\t\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker, class Observer >\n\t\t\tstd::tuple<bool, size_t, Time> breakable_integrate_const(\n\t\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\t\tTime start_time, Time end_time, Time dt, Breaker breaker,\n\t\t\t\tObserver observer, controlled_stepper_tag\n\t\t\t)\n\t\t\t{\n\t\t\t\ttypename boost_odeint::unwrap_reference< Observer >::type& obs = observer;\n\n\t\t\t\tTime time = start_time;\n\t\t\t\tconst Time time_step = dt;\n\t\t\t\tint real_steps = 0;\n\t\t\t\tint step = 0;\n\n\t\t\t\t// check breaker condition with the initial state\n\t\t\t\tif (breaker(start_state, start_time)) {\n\t\t\t\t\tobs(start_state, start_time);\n\t\t\t\t\treturn std::make_tuple(true, real_steps, start_time);\n\t\t\t\t}\n\n\t\t\t\twhile (boost_odeint::detail::less_eq_with_sign(static_cast<Time>(time + time_step), end_time, dt)){\n\t\t\t\t\tobs(start_state, time);\n\t\t\t\t\t// integrate_adaptive_checked uses the given checker to throw if an overflow occurs\n\t\t\t\t\tauto ans = breakable_integrate_adaptive(stepper, sys, start_state,\n\t\t\t\t\t\ttime, static_cast<Time>(time + time_step), dt, breaker,\n\t\t\t\t\t\tboost_odeint::null_observer(), controlled_stepper_tag());\n\n\t\t\t\t\t//if break is detected, finish immidiately\n\t\t\t\t\tif (std::get<0>(ans)) {\n\t\t\t\t\t\treturn ans;\n\t\t\t\t\t}\n\n\t\t\t\t\treal_steps += std::get<1>(ans);\n\t\t\t\t\t// direct computation of the time avoids error propagation happening when using time += dt\n\t\t\t\t\t// we need clumsy type analysis to get boost units working here\n\t\t\t\t\tstep++;\n\t\t\t\t\ttime = start_time + static_cast<typename boost_odeint::unit_value_type<Time>::type>(step) * time_step;\n\t\t\t\t}\n\t\t\t\tobs(start_state, time);\n\n\t\t\t\treturn std::make_tuple(false, real_steps, time);\n\t\t\t}\n\n\n\t\t\t//breakable integrate const for dense_output_stepper\n\t\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker, class Observer >\n\t\t\tstd::tuple<bool, size_t, Time> breakable_integrate_const(\n\t\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\t\tTime start_time, Time end_time, Time dt, Breaker breaker,\n\t\t\t\tObserver observer, dense_output_stepper_tag\n\t\t\t){\n\t\t\t\ttypename boost_odeint::unwrap_reference< Observer >::type& obs = observer;\n\t\t\t\ttypename boost_odeint::unwrap_reference< Stepper >::type& st = stepper;\n\n\t\t\t\tTime time = start_time;\n\t\t\t\tint obs_step(1);\n\t\t\t\tint real_step(0);\n\n\t\t\t\tst.initialize(start_state, time, dt);\n\t\t\t\tbool IsBreak = breaker(start_state, time);\n\t\t\t\tobs(start_state, time);\n\t\t\t\tif (IsBreak) {\n\t\t\t\t\treturn std::make_tuple(true, real_step, time);\n\t\t\t\t}\n\t\t\t\ttime += dt;\n\t\t\t\twhile (boost_odeint::detail::less_eq_with_sign(static_cast<Time>(time + dt), end_time, dt)){\n\t\t\t\t\twhile (boost_odeint::detail::less_eq_with_sign(time, st.current_time(), dt)){\n\t\t\t\t\t\tcalc_state(st, sys, time, start_state);\n\t\t\t\t\t\tobs(start_state, time);\n\t\t\t\t\t\t++obs_step;\n\t\t\t\t\t\t// direct computation of the time avoids error propagation happening when using time += dt\n\t\t\t\t\t\t// we need clumsy type analysis to get boost units working here\n\t\t\t\t\t\ttime = start_time + static_cast<typename boost_odeint::unit_value_type<Time>::type>(obs_step) * dt;\n\t\t\t\t\t}\n\t\t\t\t\t// we have not reached the end, do another real step\n\t\t\t\t\tif (boost_odeint::detail::less_with_sign(static_cast<Time>(st.current_time() + st.current_time_step()),\n\t\t\t\t\t\tend_time,\n\t\t\t\t\t\tst.current_time_step())) {\n\t\t\t\t\t\twhile (!IsBreak && boost_odeint::detail::less_eq_with_sign(st.current_time(), time, dt))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tst.do_step(sys);\n\t\t\t\t\t\t\tIsBreak = breaker(st.current_state(), st.current_time());\n\t\t\t\t\t\t\t++real_step;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (boost_odeint::detail::less_with_sign(st.current_time(), end_time, st.current_time_step()))\n\t\t\t\t\t{ // do the last step ending exactly on the end point\n\t\t\t\t\t\tst.initialize(st.current_state(), st.current_time(), end_time - st.current_time());\n\t\t\t\t\t\tst.do_step(sys);\n\t\t\t\t\t\tIsBreak = breaker(st.current_state(), st.current_time());\n\t\t\t\t\t\t++real_step;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (IsBreak) {\n\t\t\t\t\t\t//last observation before break\n\t\t\t\t\t\twhile (boost_odeint::detail::less_eq_with_sign(time, st.current_time(), dt)) {\n\t\t\t\t\t\t\tcalc_state(st, sys, time, start_state);\n\t\t\t\t\t\t\tobs(start_state, time);\n\t\t\t\t\t\t\t++obs_step;\n\t\t\t\t\t\t\t// direct computation of the time avoids error propagation happening when using time += dt\n\t\t\t\t\t\t\t// we need clumsy type analysis to get boost units working here\n\t\t\t\t\t\t\ttime = start_time + static_cast<typename boost_odeint::unit_value_type<Time>::type>(obs_step) * dt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn std::make_tuple(true, real_step, st.current_time());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// last observation, if we are still in observation interval\n\t\t\t\t// might happen due to finite precision problems when computing the the time\n\t\t\t\tif (boost_odeint::detail::less_eq_with_sign(time, end_time, dt)){\n\t\t\t\t\tcalc_state(st, sys, time, start_state);\n\t\t\t\t\tobs(start_state, time);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn std::make_tuple(false, real_step, st.current_time());\n\t\t\t}\n\n\n\t\t\t// forward declaration for breakable integrate const for adaptive_stepper_tag\n\t\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker, class Observer >\n\t\t\tstd::tuple<bool, size_t, Time> breakable_integrate_adaptive(\n\t\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\t\tTime start_time, Time end_time, Time dt, Breaker breaker,\n\t\t\t\tObserver observer, adaptive_stepper_tag\n\t\t\t);\n\n\t\t\t//breakable integrate const for dense_output_stepper\n\t\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker, class Observer >\n\t\t\tstd::tuple<bool, size_t, Time> breakable_integrate_const(\n\t\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\t\tTime start_time, Time end_time, Time dt, Breaker breaker,\n\t\t\t\tObserver observer, adaptive_stepper_tag\n\t\t\t) {\n\t\t\t\ttypename boost_odeint::unwrap_reference< Observer >::type& obs = observer;\n\n\t\t\t\tTime time = start_time;\n\t\t\t\tconst Time time_step = dt;\n\t\t\t\tint real_steps = 0;\n\t\t\t\tint step = 0;\n\n\t\t\t\t// check breaker condition with the initial state\n\t\t\t\tif (breaker(start_state, start_time)) {\n\t\t\t\t\tobs(start_state, start_time);\n\t\t\t\t\treturn std::make_tuple(true, real_steps, start_time);\n\t\t\t\t}\n\n\t\t\t\twhile (boost_odeint::detail::less_eq_with_sign(static_cast<Time>(time + time_step), end_time, dt)) {\n\t\t\t\t\tobs(start_state, time);\n\t\t\t\t\t// integrate_adaptive_checked uses the given checker to throw if an overflow occurs\n\t\t\t\t\tauto ans = breakable_integrate_adaptive(stepper, sys, start_state,\n\t\t\t\t\t\ttime, static_cast<Time>(time + time_step), dt, breaker,\n\t\t\t\t\t\tboost_odeint::null_observer(), adaptive_stepper_tag());\n\n\t\t\t\t\t//if break is detected, finish immidiately\n\t\t\t\t\tif (std::get<0>(ans)) {\n\t\t\t\t\t\treturn ans;\n\t\t\t\t\t}\n\n\t\t\t\t\treal_steps += std::get<1>(ans);\n\t\t\t\t\t// direct computation of the time avoids error propagation happening when using time += dt\n\t\t\t\t\t// we need clumsy type analysis to get boost units working here\n\t\t\t\t\tstep++;\n\t\t\t\t\ttime = start_time + static_cast<typename boost_odeint::unit_value_type<Time>::type>(step) * time_step;\n\t\t\t\t}\n\t\t\t\tobs(start_state, time);\n\n\t\t\t\treturn std::make_tuple(false, real_steps, time);\n\t\t\t}\n\t\t}\n\n\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker, class Observer >\n\t\tstd::tuple<bool, size_t, Time> breakable_integrate_const(\n\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\tTime start_time, Time end_time, Time dt, \n\t\t\tBreaker breaker, Observer observer) {\n\t\t\tusing stepper_category = typename boost::numeric::odeint::unwrap_reference<Stepper>::type::stepper_category;\n\t\t\treturn detail::breakable_integrate_const(stepper, sys, start_state, start_time, end_time, dt, breaker, observer, stepper_category());\n\t\t}\n\n\t\ttemplate< class Stepper, class System, class State, class Time, class Breaker>\n\t\tstd::tuple<bool, size_t, Time> breakable_integrate_const(\n\t\t\tStepper stepper, System sys, State& start_state,\n\t\t\tTime start_time, Time end_time, Time dt,\n\t\t\tBreaker breaker) {\n\t\t\tusing stepper_category = typename boost::numeric::odeint::unwrap_reference<Stepper>::type::stepper_category;\n\t\t\treturn detail::breakable_integrate_const(stepper, sys, start_state, start_time, end_time, dt, breaker, boost::numeric::odeint::null_observer(), stepper_category());\n\t\t}\n\n\t}\n}\n#\n#endif\n", "meta": {"hexsha": "feb889a6eaf83bee2b94994e43db7f803e3d64bc", "size": 10451, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "odeint/integrate/breakable_integrate_const.hpp", "max_stars_repo_name": "hmito/hmLib", "max_stars_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "odeint/integrate/breakable_integrate_const.hpp", "max_issues_repo_name": "hmito/hmLib", "max_issues_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "odeint/integrate/breakable_integrate_const.hpp", "max_forks_repo_name": "hmito/hmLib", "max_forks_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-22T03:32:11.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-22T03:32:11.000Z", "avg_line_length": 41.4722222222, "max_line_length": 167, "alphanum_fraction": 0.7110324371, "num_tokens": 2647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.0402379420481503, "lm_q1q2_score": 0.01623869967315835}}
{"text": "#include \"SpikeTrain.h\"\n#include \"RanUtilsRandom.h\"\n#include <stdexcept>\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n\nusing namespace boost::python;\n\nstd::vector<double> * SpikeTrain::getTds(){\n    std::vector<double> * a=new std::vector<double>(number_of_tds);\n    for (int i=0 ; i<number_of_tds; ++i){\n        (*a)[i]=tds[i]->timeBlock*timeBlockSize + tds[i]->time;\n    }\n    return a;\n}\nstd::vector<double> * SpikeTrain::getTdsMinusEps(){\n        std::vector<double> * a=new std::vector<double>(number_of_tds);\n        for (int i=0 ; i<number_of_tds; ++i){\n                (*a)[i]=tds_minus_eps[i]->timeBlock*timeBlockSize + tds_minus_eps[i]->time;\n    }\n    return a;\n}\n\nSpikeTrain * generatePoissonSpikeTrian(boost::python::object const & mean_rates,\n                                       double T,int N,\n                                       int N_noise){\n    /* \n     * Generates a spike train with N Poisson spike times with mean rate mean_rates[i]\n     * For Duration T. In addition adds a single spike at a random time from each \n     * noise afferent with N_noise noise afferents \n     */\n    \n    static RU::PoissonProccess p;\n    static RU::Random rnd;\n    static double t;\n    SpikeTrain * st_ptr = new SpikeTrain();\n    boost::python::stl_input_iterator<double> x_i(mean_rates),x_end;\n    int i = 0;\n    while (x_i!=x_end){\n        // generate poisson rates with mean rate x_i\n        p.setTau(1./(*x_i));\n        t=0.0;\n        while (t<T){\n            t += p.NextEvent();\n            st_ptr->add_spike(i,t);\n        }\n        st_ptr->pop_back();\n        ++i;\n        ++x_i;\n    }\n    if (i!=N)\n        throw std::runtime_error(\"Number of elements in iterable object is not N\");//assert i==N\n    //generate noise spikes (1 spike per afferent.)\n    for(i=N; i<N+N_noise; ++i){\n        t = rnd.nextFloat(T);\n        st_ptr->add_spike(i,t);\n    }\n    //sorting according to spike time   \n    st_ptr->sort();\n    \n    return st_ptr;\n}\n\nSpikeTrain * generateNoisySpikeTrian(SpikeTrain * st, double sigma,\n                                       double T,int N, int N_noise){\n    static RU::Random rnd;\n    NR::GausianDist g(0.0,sigma);\n    SpikeTrain * st_ptr = new SpikeTrain();\n    \n    for (auto spike=st->begin(); spike!=st->end(); ++spike){\n        st_ptr->add_spike(spike->affarent,spike->time+g());\n    } \n    \n    //generate noise spikes (1 spike per afferent.)\n    for(int i=N; i<N+N_noise; ++i){\n        st_ptr->add_spike(i,rnd.nextFloat(T));\n    }\n    //sorting according to spike time   \n    st_ptr->sort();\n    \n    return st_ptr;\n}\n\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(setTdMarkers_OL,setTdMarkers,1,2)\n\nvoid export_SpikeTrain(){\n    class_<SpikeTrain>(\"SpikeTrain\")\n        .def(vector_indexing_suite<SpikeTrain>())\n        .def(\"getTds\",&SpikeTrain::getTds,return_value_policy<manage_new_object>())\n        .def(\"getTdsMinusEps\",&SpikeTrain::getTdsMinusEps,return_value_policy<manage_new_object>())\n        .def(\"sort\",&SpikeTrain::sort)\n        .def(\"setTdMarkers\",&SpikeTrain::setTdMarkers,setTdMarkers_OL())\n        .def_readwrite(\"timeBlockSize\",&SpikeTrain::timeBlockSize)\n        .def(\"applyTimeBlock\",&SpikeTrain::applyTimeBlock)\n        .def(\"calcExponents\",&SpikeTrain::calcExponents)\n        .def(\"_cpp_add_spike\",&SpikeTrain::add_spike)\n    ;\n    def(\"CPPgeneratePoissonSpikeTrian\",generatePoissonSpikeTrian,return_value_policy<manage_new_object>());\n    def(\"CPPgenerateNoisySpikeTrian\",generateNoisySpikeTrian,return_value_policy<manage_new_object>());\n}", "meta": {"hexsha": "266b89a50270cd32efe930a23fe021082f6a89bd", "size": 3590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LIFsim/source/pySpikeTrain.cpp", "max_stars_repo_name": "ranr01/Rubin2017Balanced", "max_stars_repo_head_hexsha": "e3725170abd3c16309b189ebdf4a48bdd1835e0f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-04T18:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T04:34:34.000Z", "max_issues_repo_path": "LIFsim/source/pySpikeTrain.cpp", "max_issues_repo_name": "ranr01/Rubin2017Balanced", "max_issues_repo_head_hexsha": "e3725170abd3c16309b189ebdf4a48bdd1835e0f", "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": "LIFsim/source/pySpikeTrain.cpp", "max_forks_repo_name": "ranr01/Rubin2017Balanced", "max_forks_repo_head_hexsha": "e3725170abd3c16309b189ebdf4a48bdd1835e0f", "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": 34.854368932, "max_line_length": 107, "alphanum_fraction": 0.6311977716, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.03514484400064827, "lm_q1q2_score": 0.016202362790612632}}
{"text": "/*\nThe MIT License\n\nCopyright (c) 2015-2016 Albert Murienne\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#include \"network_vexcl.h\"\n\n#include \"common/network_config.h\"\n#include \"common/network_exception.h\"\n#include \"common/network_random.h\"\n\n#include <boost/shared_array.hpp>\n\n// vex::constant is not available for cuda backend,\n// so we have to redefine a forwarding identity function:\n// http://stackoverflow.com/questions/38353823/identity-function-with-perfect-forwarding\n#ifdef VEXCL_BACKEND_CUDA\nnamespace vex {\n    template<typename V>\n    constexpr V&& constant(V&& v) { return std::forward<V>(v); }\n};\n#endif\n\nnamespace neurocl { namespace mlp {\n\nVEX_CONSTANT(_zero, 0.f);\nVEX_CONSTANT(_one, 1.f);\n\nclass my_vex_ctx\n{\npublic:\n    static my_vex_ctx& instance() { static my_vex_ctx _ctx; return _ctx; }\n    vex::Context& get() { return m_ctx; }\nprotected:\n\tmy_vex_ctx() : m_ctx( vex::Filter::GPU && vex::Filter::Count(1) ) {}\n    virtual ~my_vex_ctx() {}\nprivate:\n    vex::Context m_ctx;\n};\n\ntemplate<typename T>\nconst std::string dump_vec( const vex::vector<T>& vec, boost::optional<std::string> label = boost::none )\n{\n    std::string separator;\n    std::stringstream ss;\n    ss << ( label ? label.get() : \"\" ) << std::endl;\n    for( typename vex::vector<T>::const_iterator it = vec.begin(); it != vec.end(); ++it )\n    {\n            ss << separator << *it;\n            separator = \" \";\n    }\n    ss << std::endl;\n    return ss.str();\n}\n\nvoid random_normal_init( vex::vector<float>& container, const float stddev = 1.f )\n{\n    random::rand_gaussian_generator rgg( 0.f, stddev );\n\n    boost::shared_array<float> arand( new float[container.size()] );\n\n    for ( size_t i=0; i<container.size(); i++ )\n        arand[i] = rgg();\n\n    vex::copy( arand.get(), arand.get()+container.size(), container.begin() );\n}\n\nlayer_vexcl::layer_vexcl()\n{\n}\n\n// WARNING : size is the square side size\nvoid layer_vexcl::populate( const layer_size& cur_layer_size, const layer_size& next_layer_size )\n{\n    //LOGGER(info) << \"layer_vexcl::populate - populating layer of size \" << cur_layer_size << \" (next size is \" << next_layer_size << \")\" << std::endl;\n\n    vex::Context& _ctx = my_vex_ctx::instance().get();\n\n    if ( next_layer_size.size() ) // non-output layer\n    {\n        m_weights_size = std::make_pair( next_layer_size.size(), cur_layer_size.size() );\n        m_output_weights = vex::vector<float>( _ctx, next_layer_size.size() * cur_layer_size.size() );\n        // cf. http://neuralnetworksanddeeplearning.com/chap3.html#weight_initialization\n        random_normal_init( m_output_weights, 1.f / std::sqrt( cur_layer_size.size() ) );\n        m_deltas_weight = vex::vector<float>( _ctx, next_layer_size.size() * cur_layer_size.size() );\n        m_deltas_weight = _zero();\n\n        m_bias = vex::vector<float>( _ctx, next_layer_size.size() );\n        random_normal_init( m_bias, 1.f );\n        m_deltas_bias = vex::vector<float>( _ctx, next_layer_size.size() );\n        m_deltas_bias = _zero();\n    }\n\n    m_activations = vex::vector<float>( _ctx, cur_layer_size.size() );\n    m_activations = _zero();\n    m_errors = vex::vector<float>( _ctx, cur_layer_size.size() );\n    m_errors = _zero();\n}\n\nconst std::string layer_vexcl::dump_weights() const\n{\n    return dump_vec( m_output_weights );\n}\n\nconst std::string layer_vexcl::dump_bias() const\n{\n    return dump_vec( m_bias );\n}\n\nconst std::string layer_vexcl::dump_activations() const\n{\n    return dump_vec( m_activations );\n}\n\nnetwork_vexcl::network_vexcl() : m_training_samples( 0 ), m_learning_rate( 3.0f/*0.01f*/ ), m_weight_decay( 0.0f )\n{\n    const network_config& nc = network_config::instance();\n    nc.update_optional( \"learning_rate\", m_learning_rate );\n\n    vex::Context& _ctx = my_vex_ctx::instance().get();\n\n    if ( !_ctx ) throw std::runtime_error( \"No devices available.\" );\n\n    // Print out list of selected devices:\n    LOGGER(info) << \"network_vexcl::network_vexcl - vexcl devices:\" << std::endl;\n    LOGGER(info) << _ctx << std::endl;\n}\n\nvoid network_vexcl::set_input(  const size_t& in_size, const float* in )\n{\n    if ( in_size > m_layers[0].activations().size() )\n        throw network_exception( \"sample size exceeds allocated layer size!\" );\n\n    //LOGGER(info) << \"network_vexcl::set_input - input (\" << in << \") size = \" << in_size << std::endl;\n\n    vex::copy( in, in + in_size, m_layers[0].activations().begin() );\n}\n\nvoid network_vexcl::set_output( const size_t& out_size, const float* out )\n{\n    if ( out_size > m_training_output.size() )\n        throw network_exception( \"output size exceeds allocated layer size!\" );\n\n    //LOGGER(info) << \"network_vexcl::set_output - output (\" << out << \") size = \" << out_size << std::endl;\n\n    vex::copy( out, out + out_size, m_training_output.begin() );\n}\n\nvoid network_vexcl::add_layers_2d( const std::vector<layer_size>& layer_sizes )\n{\n    m_layers.resize( layer_sizes.size() );\n\n    // Last layer should be output layer\n    const layer_size& _last_size = layer_sizes.back();\n    m_layers.back().populate( _last_size, layer_size( 0, 0 ) );\n\n    vex::Context& _ctx = my_vex_ctx::instance().get();\n\n    // Initialize training output\n    m_training_output = vex::vector<float>( _ctx, _last_size.size() );\n\n    // Populate all but input layer\n    for ( int idx=layer_sizes.size()-2; idx>=0; idx-- )\n    {\n        const layer_size& _size = layer_sizes[idx];\n        const layer_size& _next_layer_size = layer_sizes[idx+1];\n        m_layers[idx].populate( _size, _next_layer_size );\n    }\n}\n\nconst layer_ptr network_vexcl::get_layer_ptr( const size_t layer_idx )\n{\n    if ( layer_idx >= m_layers.size() )\n    {\n        LOGGER(error) << \"network_vexcl::get_layer_ptr - cannot access layer \" << layer_idx << std::endl;\n        throw network_exception( \"invalid layer index\" );\n    }\n\n    vex::vector<float>& weights = m_layers[layer_idx].weights();\n    vex::vector<float>& bias = m_layers[layer_idx].bias();\n\n    layer_ptr l( weights.size(), bias.size() );\n    vex::copy( weights.begin(), weights.end(), l.weights.get() );\n    vex::copy( bias.begin(), bias.end(), l.bias.get() );\n\n    return l;\n}\n\nvoid network_vexcl::set_layer_ptr( const size_t layer_idx, const layer_ptr& layer )\n{\n    if ( layer_idx >= m_layers.size() )\n    {\n        LOGGER(error) << \"network_vexcl::set_layer_ptr - cannot access layer \" << layer_idx << std::endl;\n        throw network_exception( \"invalid layer index\" );\n    }\n\n    vex::vector<float>& weights = m_layers[layer_idx].weights();\n    std::copy( layer.weights.get(), layer.weights.get() + layer.num_weights, weights.begin() );\n    vex::vector<float>& bias = m_layers[layer_idx].bias();\n    std::copy( layer.bias.get(), layer.bias.get() + layer.num_bias, bias.begin() );\n}\n\nconst output_ptr network_vexcl::output()\n{\n    // very slow for a GPU backend!!!\n    vex::vector<float>& output = m_layers.back().activations();\n    output_ptr l( output.size() );\n    vex::copy( output.begin(), output.end(), l.outputs.get() );\n\n    return l;\n}\n\nvoid network_vexcl::feed_forward()\n{\n    //std::cout << m_layers.size() << \" layers propagation\" << std::endl;\n\n    for ( size_t i=0; i<m_layers.size()-1; i++ )\n    {\n        const size_t n = m_layers[i].w_size().first;\n        const size_t m = m_layers[i].w_size().second;\n\n        m_layers[i+1].activations() = _one() / ( _one() + exp(\n            -( vex::reduce<vex::SUM>(\n                vex::extents[n][m],     // Shape of the expression to reduce,\n                m_layers[i].weights()\n                *\n                vex::reshape(\n                    m_layers[i].activations(),\n                    vex::extents[n][m], // (We need an n x m matrix...\n                    vex::extents[1]     // ... but we only have vector of size m).\n                ),                      // the expression,\n                1                       // and the dimension to reduce along.\n            )\n            + m_layers[i].bias() ) )\n        );\n    }\n}\n\nvoid network_vexcl::back_propagate()\n{\n    // PREREQUISITE : FEED FORWARD PASS\n\n    // Output layer error vector\n    layer_vexcl& output_layer = m_layers.back();\n    output_layer.errors() = output_layer.activations() * ( _one() - output_layer.activations() )\n        * ( output_layer.activations() - vex::constant( m_training_output ) );\n\n    // Hidden layers error vectors\n    for ( size_t i=m_layers.size()-2; i>0; i-- )\n    {\n        size_t n = m_layers[i].w_size().first;\n        size_t m = m_layers[i].w_size().second;\n\n        m_layers[i].errors() = m_layers[i].activations() * ( _one() - m_layers[i].activations() )\n            *\n            vex::reduce<vex::SUM>(\n                vex::extents[m][n],     // Shape of the expression to reduce,\n                vex::reshape(\n                    m_layers[i].weights(),\n                    vex::extents[m][n], // new shape\n                    vex::extents[1][0]  // m_layers[i].weights is shaped as [n][m]\n                )\n                *\n                vex::reshape(\n                    m_layers[i+1].errors(),\n                    vex::extents[m][n], // (We need an m x n matrix...\n                    vex::extents[1]     // ... but we only have vector of size m).\n                ),                      // the expression,\n                1                       // and the dimension to reduce along.\n            );\n    }\n\n    // Update gradients\n    for ( size_t i=0; i<m_layers.size()-1; i++ )\n    {\n        size_t n = m_layers[i].w_size().first;\n        size_t m = m_layers[i].w_size().second;\n\n        m_layers[i].w_deltas() += vex::reduce<vex::SUM>(\n            vex::extents[n][1][m],\n        \tvex::reshape( m_layers[i+1].errors(), vex::extents[n][1][m], vex::extents[0][1] )\n            * vex::reshape( m_layers[i].activations(), vex::extents[n][1][m], vex::extents[1][2] ),\n            1 );\n        m_layers[i].b_deltas() += m_layers[i+1].errors();\n    }\n\n    ++m_training_samples;\n}\n\nvoid network_vexcl::gradient_descent()\n{\n    //LOGGER(info) << \"network_bnu::gradient_descent - updating after \" << m_training_samples << \" backpropagations\" << std::endl;\n\n    float invm = 1.f / static_cast<float>( m_training_samples );\n\n    for ( size_t i=0; i<m_layers.size()-1; i++ ) // avoid output layer\n    {\n        m_layers[i].weights() -= m_learning_rate * ( ( invm * m_layers[i].w_deltas() ) + ( m_weight_decay * m_layers[i].weights() ) );\n        m_layers[i].bias() -= m_learning_rate * ( invm * m_layers[i].b_deltas() );\n    }\n}\n\nvoid network_vexcl::clear_gradients()\n{\n    // Clear gradients\n    for ( size_t i=0; i<m_layers.size()-1; i++ )\n    {\n        m_layers[i].w_deltas() = _zero();\n        m_layers[i].b_deltas() = _zero();\n    }\n\n    m_training_samples = 0;\n}\n\nfloat network_vexcl::loss()\n{\n    vex::Reductor<float,vex::SUM> sum;\n\n    layer_vexcl& output_layer = m_layers.back();\n    float _loss = sum( ( output_layer.activations() - vex::constant( m_training_output ) )\n        * ( output_layer.activations() - vex::constant( m_training_output ) ) );\n\n    return 0.5f * _loss / static_cast<float>( m_training_output.size() );\n}\n\nconst std::string network_vexcl::dump_weights()\n{\n    return \"WEIGHTS DUMPING NOT IMPLEMENTED YET\";\n}\n\nconst std::string network_vexcl::dump_bias()\n{\n    std::stringstream ss;\n    ss << \"*************************************************\" << std::endl;\n    for( const auto& layer : m_layers )\n    {\n        ss << layer.dump_bias();\n        ss << \"-------------------------------------------------\" << std::endl;\n    }\n    ss << \"*************************************************\" << std::endl;\n    return ss.str();\n}\n\nconst std::string network_vexcl::dump_activations()\n{\n    std::stringstream ss;\n    ss << \"*************************************************\" << std::endl;\n    for( const auto& layer : m_layers )\n    {\n        ss << layer.dump_activations();\n        ss << \"-------------------------------------------------\" << std::endl;\n    }\n    ss << \"*************************************************\" << std::endl;\n    return ss.str();\n}\n\nvoid network_vexcl::gradient_check( const output_ptr& out_ref )\n{\n    LOGGER(error) << \"network_vexcl::gradient_check - not implemented yet for MLP\" << std::endl;\n}\n\n} /*namespace neurocl*/ } /*namespace mlp*/\n", "meta": {"hexsha": "05ff0c84e4efba67b83b7e691af2c5bf1da733c9", "size": 13175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlp/network_vexcl.cpp", "max_stars_repo_name": "blackccpie/neurocl", "max_stars_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-01T22:19:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T19:06:24.000Z", "max_issues_repo_path": "src/mlp/network_vexcl.cpp", "max_issues_repo_name": "blackccpie/neurocl", "max_issues_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlp/network_vexcl.cpp", "max_forks_repo_name": "blackccpie/neurocl", "max_forks_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-19T08:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T08:17:54.000Z", "avg_line_length": 34.4895287958, "max_line_length": 152, "alphanum_fraction": 0.6090322581, "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.03514484336903119, "lm_q1q2_score": 0.01620236249942656}}
{"text": "#include <boost/thread.hpp>\n#include <seq2map/solve.hpp>\n\nusing namespace seq2map;\n\n//==[ LeastSquaresProblem ]===================================================//\n\nsize_t LeastSquaresProblem::GetHardwareConcurrency()\n{\n    return boost::thread::hardware_concurrency();\n}\n\nVectorisableD::Vec LeastSquaresProblem::operator() (const VectorisableD& vec) const\n{\n    VectorisableD::Vec v;\n\n    if (!vec.Store(v))\n    {\n        E_ERROR << \"vectorisation failed\";\n        return VectorisableD::Vec();\n    }\n\n    return (*this)(v);\n}\n\ncv::Mat LeastSquaresProblem::ComputeJacobian(const VectorisableD::Vec& x, VectorisableD::Vec& y) const\n{\n    cv::Mat J = cv::Mat::zeros(static_cast<int>(m_conds), static_cast<int>(m_varIdx.size()), CV_64F);\n    bool masking = !m_jacobianPattern.empty();\n\n    boost::thread_group threads;\n\n    y = y.empty() ? (*this)(x) : y;\n\n    // make evaluation slices for multi-threaded numerical differentiation\n    std::vector<JacobianSlices> slices(m_diffThreads);\n    size_t i = 0;\n\n    for (IndexList::const_iterator var = m_varIdx.begin(); var != m_varIdx.end(); var++)\n    {\n        JacobianSlice slice;\n        size_t threadIdx = i % m_diffThreads;\n\n        slice.x    = x;\n        slice.y    = y;\n        slice.var  = *var;\n        slice.col  = J.col(static_cast<int>(i));\n        slice.mask = masking ? m_jacobianPattern.col(static_cast<int>(*var)) : cv::Mat();\n\n        slices[threadIdx].push_back(slice);\n\n        i++;\n    }\n\n    // lunch the threads\n    for (size_t k = 0; k < slices.size(); k++)\n    {\n        threads.add_thread(new boost::thread(\n            LeastSquaresProblem::DiffThread,\n            (const LeastSquaresProblem*) this,\n            boost::ref(slices[k]))\n        );\n    }\n\n    // wait for completions\n    threads.join_all();\n\n    return J;\n}\n\nvoid LeastSquaresProblem::DiffThread(const LeastSquaresProblem* lsq, JacobianSlices& slices)\n{\n    BOOST_FOREACH (JacobianSlice& slice, slices)\n    {\n        cv::Mat x = cv::Mat(slice.x).clone();\n        cv::Mat y = cv::Mat(slice.y).clone();\n        double dx = lsq->m_diffStep;\n\n        x.at<double>(static_cast<int>(slice.var)) += dx;\n        cv::Mat dy = cv::Mat((*lsq)(x)) - y;\n\n        // Jk = (f(x+dx) - f(x)) / dx\n        cv::divide(dy, dx, slice.col);\n    }\n}\n\nbool LeastSquaresProblem::SetActiveVars(const IndexList& varIdx)\n{\n    BOOST_FOREACH(size_t var, varIdx)\n    {\n        if (var >= m_vars) return false;\n    }\n\n    m_varIdx = varIdx;\n\n    return true;\n}\n\ncv::Mat LeastSquaresProblem::ApplyUpdate(const VectorisableD::Vec& x0, const VectorisableD::Vec& delta)\n{\n    assert(delta.size() <= x0.size());\n    VectorisableD::Vec x = x0;\n    size_t i = 0;\n    \n    BOOST_FOREACH(size_t var, m_varIdx)\n    {\n        x[var] += delta[i++];\n    }\n\n    return cv::Mat(x, true);\n}\n\n//==[ LeastSquaresSolver ]====================================================//\n\nbool LeastSquaresSolver::Logger::operator() (const LeastSquaresSolver::State& state)\n{\n    if (state.updates == 0)\n    {\n        E_TRACE << std::setw(80) << std::setfill('=') << \"\";\n        E_TRACE << std::setw( 6) << std::right << \"Update\" \n                << std::setw(14) << std::right << \"RMSE\"\n                << std::setw(20) << std::right << \"Lambda\"\n                << std::setw(20) << std::right << \"Rel. Step Size\"\n                << std::setw(20) << std::right << \"Rel. Error Drop\";\n        E_TRACE << std::setw(80) << std::setfill('=') << \"\";\n        E_TRACE << std::setw( 6) << std::right << state.updates\n                << std::setw(14) << std::right << state.error\n                << std::setw(20) << std::right << state.lambda\n                << std::setw(20) << std::right << \"-\"\n                << std::setw(20) << std::right << \"-\";\n    }\n    else\n    {\n        E_TRACE << std::setw(6)  << std::right << state.updates\n                << std::setw(14) << std::right << state.error\n                << std::setw(20) << std::right << state.lambda\n                << std::setw(20) << std::right << state.relStep\n                << std::setw(20) << std::right << state.relError;\n    }\n\n    return true;\n}\n\n//==[ LevenbergMarquardtAlgorithm ]===========================================//\n\nbool LevenbergMarquardtAlgorithm::Solve(LeastSquaresProblem& f, State& state)\n{\n    assert(m_eta > 1.0f);\n\n    if (!f.Initialise(state.x))\n    {\n        return false;\n    }\n\n    state.y = f(state.x);\n    state.error = rms(cv::Mat(state.y, false));\n    state.lambda = m_lambda;\n    state.converged = false;\n    state.updates = 0;\n\n    if (m_verbose && m_updater)\n    {\n        (*m_updater)(state);\n    }\n\n    try\n    {\n        //\n        // outer loop : goes until a possible minimum is approached, or termination criterion met\n        //\n        while (!state.converged)\n        {\n            cv::Mat J = f.ComputeJacobian(state.x, state.y); // Jacobian matrix\n            cv::Mat H = J.t() * J;                           // Hessian matrix\n            cv::Mat D = J.t() * cv::Mat(state.y);            // error gradient\n\n            state.lambda = state.lambda < 0 ? cv::mean(H.diag())[0] : state.lambda;\n            state.jacobian = J;\n            state.hessian  = H;\n\n            bool better = false;\n            size_t trials = 0;\n\n            //\n            // inner loop : keep trying\n            //\n            while (!better && !state.converged)\n            {\n                // augmented normal equations\n                cv::Mat A = H + state.lambda * cv::Mat::diag(H.diag()); // or A = N + lambda*eye(d);\n                cv::Mat x_delta = A.inv() * -D; // x_delta =  A \\ -D;\n\n                VectorisableD::Vec x = f.ApplyUpdate(state.x, x_delta); // = cv::Mat(cv::Mat(x_best) + x_delta);\n                VectorisableD::Vec y = f(x);\n\n                const double e_try = rms(cv::Mat(y));\n                const double de = state.error - e_try;\n\n                better = de > 0;\n                trials++;\n\n                if (better) // accept the update\n                {\n                    state.lambda /= m_eta;\n\n                    state.de.push_back(de);\n                    state.x        = x;\n                    state.y        = y;\n                    state.error    = e_try;\n                    state.relError = state.de.size() > 1 ? (state.de.rbegin()[0] / state.de.rbegin()[1]) : 1.0f;\n                    state.relStep  = cv::norm(x_delta) / cv::norm(cv::Mat(x, false));\n                    state.updates++;\n                }\n                else // reject the update\n                {\n                    state.lambda *= m_eta;\n                }\n\n                // convergence control\n                state.converged |= (state.updates >= m_term.maxCount); // # iterations check\n                state.converged |= (state.updates > 1) && (state.relError < m_term.epsilon); // error differential check\n                state.converged |= (state.updates > 1) && (state.relStep  < m_term.epsilon); // step ratio check\n                state.converged |= (!better && trials >= m_term.maxCount);\n\n                cv::Mat icv = H.diag();\n\n                bool ill = false;\n\n                for (int d = 0; d < icv.total(); d++)\n                {\n                    if (icv.at<double>(d) == 0)\n                    {\n                        E_WARNING << \"change of parameter \" << d << \" not responsive\";\n                        ill = true;\n                    }\n                }\n\n                ill |= !isfinite(norm(x_delta));\n\n                if (ill)\n                {\n                    PersistentMat(J).Store(Path(\"J.bin\"));\n                    PersistentMat(x_delta).Store(Path(\"x_delta.bin\"));\n                    PersistentMat(cv::Mat(x)).Store(Path(\"x.bin\"));\n                    PersistentMat(cv::Mat(y)).Store(Path(\"y.bin\"));\n\n                    E_ERROR << \"problem ill-posed\";\n\n                    return false;\n                }\n            }\n\n            if (m_verbose && m_updater)\n            {\n                if (!(*m_updater)(state))\n                {\n                    return true;\n                }\n            }\n        }\n    }\n    catch (std::exception& ex)\n    {\n        E_ERROR << \"exception caught in optimisation loop\";\n        E_ERROR << ex.what();\n\n        return false;\n    }\n\n    if (!f.Finalise(state.x))\n    {\n        E_ERROR << \"error setting solution\";\n        E_ERROR << mat2string(cv::Mat(state.x, false), \"x_final\");\n\n        return false;\n    }\n\n    return true;\n}\n", "meta": {"hexsha": "0eb034eb70cc6d9a63e02a7c336b785665631b9f", "size": 8385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/base/solve.cpp", "max_stars_repo_name": "SimonsRoad/seq2map", "max_stars_repo_head_hexsha": "cc8cd20842b3c6db01f73d2e6ecf543189e56891", "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": "sources/base/solve.cpp", "max_issues_repo_name": "SimonsRoad/seq2map", "max_issues_repo_head_hexsha": "cc8cd20842b3c6db01f73d2e6ecf543189e56891", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/base/solve.cpp", "max_forks_repo_name": "SimonsRoad/seq2map", "max_forks_repo_head_hexsha": "cc8cd20842b3c6db01f73d2e6ecf543189e56891", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-01T13:11:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-01T13:11:39.000Z", "avg_line_length": 29.9464285714, "max_line_length": 120, "alphanum_fraction": 0.4888491354, "num_tokens": 2056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.032589743591528754, "lm_q1q2_score": 0.016167570699796855}}
{"text": "/// @file EntropyBase.tcc\n/// @brief Entropy operations as needed for Cornwell-Evans algorithm\n/// @ingroup Deconvolver\n///\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Tim Cornwell <tim.cornwell@csiro.au>\n///\n\n#include <string>\n\n#include <askap/AskapLogging.h>\n#include <boost/shared_ptr.hpp>\n#include <casacore/casa/aips.h>\n#include <casacore/casa/Arrays/Array.h>\n#include <casacore/casa/Arrays/ArrayMath.h>\n#include <casacore/casa/BasicMath/Math.h>\nASKAP_LOGGER(decentropybaselogger, \".deconvolution.entropy\");\n\nusing namespace casa;\n\nnamespace askap {\n\n    namespace synthesis {\n\n        template<class T>\n        EntropyBase<T>::EntropyBase() : itsAlpha(T(0.0)), itsBeta(T(0.0)), itsQ(T(40.0)), itsScale(1.0),\n                itsTolerance(0.3), itsUseFluxConstraint(false)\n        {\n        };\n\n        template<class T>\n        EntropyBase<T>::~EntropyBase()\n        {\n        };\n\n        template<class T>\n        T EntropyBase<T>::entropy(const Array<T>& model)\n        {\n            throw(AskapError(\"Called base class entropy\"));\n            ASKAPCHECK(model.shape().nelements(), \"Model has no elements\");\n            return 0.0;\n        };\n\n        template<class T>\n        T EntropyBase<T>::entropy(const Array<T>& model, const Array<T>& mask)\n        {\n            throw(AskapError(\"Called base class entropy\"));\n            ASKAPCHECK(model.shape().conform(mask.shape()), \"Model and mask images have different shapes\");\n            return 0.0;\n        };\n\n        template<class T>\n        void EntropyBase<T>::gradEntropy(Array<T>& gradH, Array<T>& rHess, const Array<T>& model)\n        {\n            throw(AskapError(\"Called base class gradEntropy\"));\n            // Silence the compiler by doing meaningless comparisons\n            ASKAPCHECK(gradH.shape().conform(rHess.shape()), \"Gradient and Hessian images have different shapes\");\n            ASKAPCHECK(gradH.shape().conform(model.shape()), \"Gradient and model images have different shapes\");\n        }\n\n        template<class T>\n        void EntropyBase<T>::gradEntropy(Array<T>& gradH, Array<T>& rHess, const Array<T>& model,\n                                         const Array<T>& mask)\n        {\n            throw(AskapError(\"Called base class gradEntropy\"));\n            // Silence the compiler by doing meaningless comparisons\n            ASKAPCHECK(gradH.shape().conform(rHess.shape()), \"Gradient and Hessian images have different shapes\");\n            ASKAPCHECK(gradH.shape().conform(model.shape()), \"Gradient and model images have different shapes\");\n            ASKAPCHECK(gradH.shape().conform(mask.shape()), \"Gradient and mask images have different shapes\");\n        }\n\n        template<class T>\n        void EntropyBase<T>::setScale(const T scale)\n        {\n            this->itsScale = scale;\n        };\n\n        template<class T>\n        T EntropyBase<T>::formLength(const Matrix<T>& GDG)\n        {\n            return GDG(H, H) +  square(this->itsAlpha) * GDG(C, C) + square(this->itsBeta)*GDG(F, F);\n        }\n\n        template<class T>\n        Matrix<T> EntropyBase<T>::formGDG(const Array<T>& model, const Array<T>& residual)\n        {\n            ASKAPCHECK(model.shape().conform(residual.shape()), \"Model and residual images have different shapes\");\n\n            Matrix<T> GDG(4, 4);\n            GDG.set(0.0);\n\n            Array<T> rHess(model.shape());\n            Array<T> gradH(model.shape());\n            gradEntropy(gradH, rHess, model);\n            Array<T> gradC = -T(2.0) * residual;\n            GDG(H, H) = sum(gradH * rHess * gradH);\n            GDG(H, C) = sum(gradH * rHess * gradC);\n            GDG(H, F) = sum(gradH * rHess);\n            GDG(C, C) = sum(gradC * rHess * gradC);\n            GDG(C, F) = sum(gradC * rHess);\n            GDG(F, F) = sum(rHess);\n            GDG(H, J) = GDG(H, H) -  this->itsAlpha * GDG(H, C) - this->itsBeta * GDG(H, F);\n            GDG(C, J) = GDG(H, C) -  this->itsAlpha * GDG(C, C) - this->itsBeta * GDG(C, F);\n            GDG(F, J) = GDG(H, F) -  this->itsAlpha * GDG(C, F) - this->itsBeta * GDG(F, F);\n            GDG(J, J) = GDG(H, H) +  square(this->itsAlpha) * GDG(C, C)\n                        + square(this->itsBeta) * GDG(F, F)  + 2 * this->itsAlpha * this->itsBeta * GDG(C, F)\n                        - 2 * this->itsAlpha * GDG(H, C) - 2 * this->itsBeta * GDG(H, F);\n            return GDG;\n        }\n\n        template<class T>\n        Matrix<T> EntropyBase<T>::formGDGStep(const Array<T>& model, const Array<T>& residual, Array<T>& step)\n        {\n            ASKAPCHECK(model.shape().conform(residual.shape()), \"Model and residual images have different shapes\");\n\n            Matrix<T> GDG(4, 4);\n            GDG.set(0.0);\n\n            // Probably need to write as iterators soon\n            Array<T> rHess(model.shape());\n            Array<T> gradH(model.shape());\n            gradEntropy(gradH, rHess, model);\n            Array<T> gradC = - T(2.0) * residual;\n            Array<T> gradJ = gradH - this->itsAlpha * gradC - this->itsBeta;\n            step = rHess * gradJ;\n            GDG(H, H) = sum(gradH * rHess * gradH);\n            GDG(H, C) = sum(gradH * rHess * gradC);\n            GDG(H, F) = sum(gradH * rHess);\n            GDG(C, C) = sum(gradC * rHess * gradC);\n            GDG(C, F) = sum(gradC * rHess);\n            GDG(F, F) = sum(rHess);\n            GDG(H, J) = GDG(H, H) -  this->itsAlpha * GDG(H, C) - this->itsBeta * GDG(H, F);\n            GDG(C, J) = GDG(H, C) -  this->itsAlpha * GDG(C, C) - this->itsBeta * GDG(C, F);\n            GDG(F, J) = GDG(H, F) -  this->itsAlpha * GDG(C, F) - this->itsBeta * GDG(F, F);\n            GDG(J, J) = GDG(H, H) +  square(this->itsAlpha) * GDG(C, C)\n                        + square(this->itsBeta) * GDG(F, F)  + 2 * this->itsAlpha * this->itsBeta * GDG(C, F)\n                        - 2 * this->itsAlpha * GDG(H, C) - 2 * this->itsBeta * GDG(H, F);\n\n            ASKAPCHECK(model.shape().conform(step.shape()), \"Model and step images have different shapes\");\n\n            return GDG;\n        }\n\n        template<class T>\n        T EntropyBase<T>::formGDS(const Array<T>& model, const Array<T>& residual, const Array<T>& step)\n        {\n            ASKAPCHECK(model.shape().conform(step.shape()), \"Model and step images have different shapes\");\n            ASKAPCHECK(model.shape().conform(residual.shape()), \"Model and residual images have different shapes\");\n\n            // Probably need to write as iterators soon\n            Array<T> gradH(model.shape());\n            Array<T> rHess(model.shape());\n            gradEntropy(gradH, rHess, model);\n            return - sum(step *(gradH + T(2.0) * this->itsAlpha * residual - this->itsBeta));\n        };\n\n        template<class T>\n        void EntropyBase<T>::changeAlphaBeta(const Matrix<T>& GDG, const T targetChisq, const T chisq,\n                                             const T targetFlux, const T flux)\n        {\n            T length = GDG(H, H) + square(this->itsAlpha) * GDG(C, C) + square(this->itsBeta) * GDG(F, F);\n            if (this->itsAlpha == 0.0 && this->itsBeta == 0.0) {\n                length = GDG(F, F);\n            }\n            T normGrad = GDG(J, J) / length;\n            if (this->itsAlpha == 0.0) {\n                normGrad = 0.0;\n            }\n            if (normGrad < this->itsTolerance) {\n                this->updateAlphaBeta(GDG, targetChisq, chisq, targetFlux, flux);\n            } else {\n                this->initialiseAlphaBeta(GDG);\n            }\n        };\n\n        template<class T>\n        Bool EntropyBase<T>::initialiseAlphaBeta(const Matrix<T>& GDG)\n        {\n            if (this->itsAlpha > T(0.0)) {\n                return false;\n            }\n            if (!this->itsUseFluxConstraint) {\n                this->itsAlpha = max(0.0,  abs(GDG(H, C) / GDG(C, C)));\n                this->itsBeta = 0.0;\n            } else {\n                Double det = GDG(C, C) * GDG(F, F) - GDG(C, F) * GDG(C, F);\n                this->itsAlpha = (GDG(F, F) * GDG(H, C) - GDG(C, F) * GDG(H, F)) / det;\n                this->itsBeta = (GDG(C, C) * GDG(H, F) - GDG(C, F) * GDG(H, C)) / det;\n            }\n            return true;\n        };\n\n        template<class T>\n        void EntropyBase<T>::updateAlphaBeta(const Matrix<T>& GDG, const T targetChisq, const T chisq,\n                                             const T targetFlux, const T flux)\n        {\n\n            // code stolen from SDE's mem.f\n            T length(this->formLength(GDG));\n\n            Double a = GDG(C, J) / GDG(C, C);\n            Double b = square(a) - (GDG(J, J) - this->itsTolerance * length) / GDG(C, C);\n\n            Double dAMax;\n            Double dAMin;\n            Double dBMax;\n            Double dBMin;\n\n            if (b > 0.0) {\n                b = sqrt(b);\n                dAMax = a + b;\n                dAMin = a - b;\n            } else {\n                dAMax = 0.0;\n                dAMin = 0.0;\n            }\n\n            Double dChisq;\n            Double dAlpha;\n            Double dBeta;\n            Double dFlux;\n\n            if (! this->itsUseFluxConstraint) {\n                dChisq =  chisq -  targetChisq + GDG(C, J);\n                dAlpha = dChisq / GDG(C, C);\n\n                dAlpha = max(dAMin, min(dAMax, dAlpha));\n                this->itsAlpha = max(0.0, this->itsAlpha + dAlpha);\n            } else {\n                a = GDG(F, J) / GDG(F, F);\n                b = square(a) - (GDG(J, J) - this->itsTolerance * length) / GDG(F, F);\n                if (b > 0.0) {\n                    b = sqrt(b);\n                    dBMax = a + b;\n                    dBMin = a - b;\n                } else {\n                    dBMax = 0.0;\n                    dBMin = 0.0;\n                }\n\n                dChisq = chisq - targetChisq + GDG(C, J);\n                dFlux  = flux  - targetFlux  + GDG(F, J);\n                T det = GDG(C, C) * GDG(F, F) - square(GDG(F, C));\n                dAlpha = (GDG(F, F) * dChisq - GDG(C, F) * dFlux) / det;\n                dBeta = (GDG(C, C) * dFlux  - GDG(C, F) * dChisq) / det;\n\n                dAlpha = max(dAMin, min(dAMax, dAlpha));\n                this->itsAlpha = max(0.0, this->itsAlpha + dAlpha);\n                dBeta    = max(dBMin, min(dBMax, dBeta));\n                this->itsBeta  = itsBeta + dBeta;\n            }\n        };\n\n    } // namespace synthesis\n\n} // namespace askap\n", "meta": {"hexsha": "4feaaec6cf1538d2cde56f5b1160fe2388fc1ff4", "size": 11324, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/EntropyBase.tcc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/EntropyBase.tcc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/EntropyBase.tcc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5878136201, "max_line_length": 115, "alphanum_fraction": 0.5234899329, "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833804028559, "lm_q2_score": 0.0330859819640103, "lm_q1q2_score": 0.01615533511733487}}
{"text": "/*\n* MIT License\n*\n* Copyright (c) 2020 International Business Machines\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 \"DoubleMatrix.h\"\n//#include \"DoubleMatrixArray.h\"\n#include <cassert>\n#include <stdlib.h>\n#include <algorithm>\n#include <iomanip>\n#include <math.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"h5Parser.h\"\n\nusing namespace std;\n\nDoubleMatrix::~DoubleMatrix() {\n  \n}\n\nDoubleMatrix::DoubleMatrix() :\n            m(0, 0) {\n\n}\n\nDoubleMatrix::DoubleMatrix(int r, int c, double fixedVal) :\n            m(r, c, fixedVal) {\n}\n\nDoubleMatrix::DoubleMatrix(vector<double> v, int matrixRows) {\n  int matrixCols = (v.size() + matrixRows - 1) / matrixRows;\n  m.resize(matrixRows, matrixCols);\n  for (int i = 0; i < (int) v.size(); ++i)\n    set(i / cols(), i % cols(), v[i]);\n}\n\nDoubleMatrix::DoubleMatrix(ifstream& matrixFile) {\n\n  vector<vector<double>> inputVals(0);\n  string line;\n\n  // Read all double arrays from \"matrixFile\" into \"inputVals\" matrix.\n  // Note that \"matrixFile\" is expected to have the following format:\n  // [vals_{11}, vals_{12}, ... , vals_{1n}]\n  // [vals_{21}, vals_{22}, ... , vals_{2n}]\n  // ...\n  // [vals_{m1}, vals_{m2}, ... , vals_{mn}].\n  while (getline(matrixFile, line)) {\n    inputVals.push_back(vector<double>(0));\n\n    // Read current array in matrix file into \"sstream\"\n    istringstream sstream(line);\n    char nextChar;\n\n    // Ignore '[' charecter in the current array in \"matrixFile\".\n    // Note that '[' charecter is expected to appear at the begining of every array.\n    sstream.ignore();\n\n    // Check whether the current array is empty\n    nextChar = sstream.peek();\n\n    if (nextChar == ']') {\n      // The current array is empty\n      continue;\n    }\n\n    string nextVal;\n\n    // Read all doubles from current array\n    while (getline(sstream, nextVal, ',')) {\n      // If getline() returned extra ']' charecter in the last read, remove ']' charecter\n      // from \"nextVal\".\n      // Note that an Extra ']' charecter will be returned when reading the last number in\n      // the current array.\n      if (nextVal.back() == ']') {\n        nextVal.pop_back();\n      }\n\n      double doubleVal = stod(nextVal.c_str());\n\n      inputVals.back().push_back(doubleVal);\n\n      // Ignore space charecter\n      sstream.ignore();\n    }\n  }\n\n  init(inputVals);\n}\n\nDoubleMatrix::DoubleMatrix(const vector<vector<float> >& matrix) {\n  init(matrix);\n}\n\nDoubleMatrix::DoubleMatrix(const vector<vector<double> >& matrix) {\n  init(matrix);\n}\n\nDoubleMatrix::DoubleMatrix(const std::vector<std::vector<double> >& matrix, int r, int c, double fixedVal) :\n\tm(r, c, fixedVal)\n{\n\t  for (int i = 0; i < matrix.size(); ++i) {\n\t    for (int j = 0; j < matrix[0].size(); ++j) {\n\t      m(i, j) = static_cast<double>(matrix[i][j]);\n\t    }\n\t  }\n}\n\nDoubleMatrix::DoubleMatrix(const string& h5File, const string& path) {\n  load(h5File, path);\n}\n\nvoid DoubleMatrix::load(const string& h5File, const string& path) {\n  H5Parser h5P(h5File);\n\n  // Initialize \"vals\" member matrix with the corresponding matrix provided in the h5 file\n  init(h5P.parseFC(path));\n\n  transpose();\n}\n\nvector<vector<double> > DoubleMatrix::getVals() const {\n  vector<vector<double>> res(rows());\n  for (int i = 0; i < rows(); ++i) {\n    res[i].resize(cols());\n    for (int j = 0; j < cols(); ++j) {\n      res[i][j] = m(i, j);\n    }\n  }\n  return res;\n}\n\nvoid DoubleMatrix::elementMultiply(const DoubleMatrix& other) {\n  assert(rows() == other.rows());\n  assert(cols() == other.cols());\n  m = boost::numeric::ublas::element_prod(m, other.m);\n}\n\nvoid DoubleMatrix::elementMultiplyAt(const DoubleMatrix&other,int startRow,int startCol) {\n  for (int i = 0; i < other.rows(); ++i) {\n    for (int j = 0; j < other.cols(); ++j) {\n      m(startRow+i, startCol+j) *= other.m(i ,j);\n    }\n  }\n}\n\nvoid DoubleMatrix::meanAlongRows() {\n  *this = getMeanAlongRows();\n}\n\nDoubleMatrix DoubleMatrix::getMeanAlongRows() const{\n  int rowsOrig = rows();\n  DoubleMatrix dm = getSumAlongRows();\n  dm.multiplyByScalar((double)1/rowsOrig);\n  return dm;\n}\n\nvoid DoubleMatrix::meanAlongCols() {\n  *this = getMeanAlongCols();\n}\n\nDoubleMatrix DoubleMatrix::getMeanAlongCols() const{\n  int colsOrig = cols();\n  DoubleMatrix dm = getSumAlongCols();\n  dm.multiplyByScalar((double)1/colsOrig);\n  return dm;\n}\n\nvoid DoubleMatrix::sumAlongRows() {\n  *this = getSumAlongRows();\n}\n\nDoubleMatrix DoubleMatrix::getSumAlongRows() const {\n  if (rows()==0)\n    throw runtime_error(\"empty matrix\");\n  DoubleMatrix res(1, m.size2());\n  for (int j = 0; j < cols(); ++j) {\n    double sum = 0;\n    for (int i = 0; i < rows(); ++i) {\n      sum += get(i, j);\n    }\n    res.set(0, j, sum);\n  }\n\n  return res;\n}\n\nvoid DoubleMatrix::sumAlongCols() {\n  *this = getSumAlongCols();\n}\n\nDoubleMatrix DoubleMatrix::getSumAlongCols() const {\n  if (cols()==0) {\n    throw invalid_argument(\"empty matrix\");\n  }\n  DoubleMatrix res(rows(), 1);\n  for (int i = 0; i < rows(); ++i) {\n    double sum = 0;\n    for (int j = 0; j < cols(); ++j) {\n      sum += get(i, j);\n    }\n    res.set(i, 0, sum);\n  }\n\n  return res;\n}\ndouble DoubleMatrix::getMaxDiff(const DoubleMatrix&other) const {\n  if (size() == 0)\n    throw invalid_argument(\"empty matrix\");\n  double res = 0;\n  for (int i = 0; i < rows(); ++i)\n    for (int j = 0; j < cols(); ++j)\n      res = max(res, abs(get(i, j) - other.get(i, j)));\n  return res;\n}\n\ndouble DoubleMatrix::getMaxRelDiff(const DoubleMatrix&other,\n    double tolerance) const {\n  if (size() == 0)\n    throw invalid_argument(\"empty matrix\");\n  double res = 0;\n  for (int i = 0; i < rows(); ++i)\n    for (int j = 0; j < cols(); ++j) {\n      double v1 = get(i, j);\n      double v2 = other.get(i, j);\n      double diff = abs(v1 - v2);\n      double m = max(abs(v1), abs(v2));\n      double relDiff = m < (tolerance * 10) ? diff : (diff / m);\n      res = max(res, relDiff);\n    }\n  return res;\n}\n\ndouble DoubleMatrix::getMaxAbs() const {\n  if (size() == 0)\n    throw invalid_argument(\"empty matrix\");\n  double res = 0;\n  for (int i = 0; i < rows(); ++i)\n    for (int j = 0; j < cols(); ++j)\n      res = max(get(i, j),res);\n  return res;\n}\n\nDoubleMatrix DoubleMatrix::getMultiply(const DoubleMatrix& other) const {\n  if (cols() != other.rows()) {\n    cerr << \"Can't multiply: \" << endl;\n    debugPrint(cerr, 0);\n    other.debugPrint(cerr, 0);\n    throw invalid_argument(\"mismatching dims\");\n  }\n  DoubleMatrix res(rows(), other.cols());\n  res.m = boost::numeric::ublas::prod(m, other.m);\n  return res;\n}\n\n/*DoubleMatrixArray DoubleMatrix::getConvolution(const DoubleMatrixArray& filters,\n    int strideRows, int strideCols) const {\n  DoubleMatrixArray res;\n\n  for (int f = 0; f < filters.size(); f++) {\n    DoubleMatrix currentFilterConvRes = getConvolution(filters.getMat(f),\n        strideRows, strideCols);\n\n    res.pushBackMatrix(currentFilterConvRes);\n  }\n\n  return res;\n}*/\n\nDoubleMatrix DoubleMatrix::getConvolution(const DoubleMatrix& filter,\n    int strideRows, int strideCols) const {\n  int filterNumRows = filter.rows();\n  int filterNumCols = filter.cols();\n\n  DoubleMatrix res(ceil((double)(rows() - filterNumRows) / strideRows) + 1,\n                   ceil((double)(cols() - filterNumCols) / strideCols) + 1);\n\n  for (int r = 0, tr = 0; r + filterNumRows - strideRows < rows(); r += strideRows, tr++) {\n    for (int c = 0, tc = 0; c + filterNumCols - strideCols < cols(); c += strideCols, tc++) {\n      double currentInnerProduct = 0;\n      for (int i = 0; i < filterNumRows; i++) {\n        for (int j = 0; j < filterNumCols; j++) {\n        \tif(r+i >= rows() || c+j >= cols())\n        \t\tcontinue;\n          currentInnerProduct += (filter.get(i, j) * get(i + r, j + c));\n        }\n      }\n      res.set(tr, tc, currentInnerProduct);\n    }\n  }\n\n  return res;\n}\n\n\nDoubleMatrix DoubleMatrix::getSubMatrix(int row1,int col1,int row2,int col2) const {\n  if ((row1 < 0) || (row1 >= row2) || (row2 > rows()) || (col1 < 0) || (col1 >= col2) || (col2 > cols())) {\n    cerr << \"Requesting range: (\" << row1 << \",\" << col1 <<\")-(\"\n        << row2 <<\",\" << col2 << \")\" << endl;\n    cerr << \"Out of this: \" << *this << endl;\n    throw invalid_argument(\"out of range\");\n  }\n  \n  DoubleMatrix res(row2-row1,col2-col1);\n  for (int i=row1;i<row2;++i)\n    for (int j=col1;j<col2;++j)\n      res.set(i-row1,j-col1,get(i,j));\n  \n  return res;\n}\n\nvoid DoubleMatrix::multiply(const DoubleMatrix& other) {\n  *this = getMultiply(other);\n}\n\nvoid DoubleMatrix::appendRow(const vector<double>& vec) {\n  if ((vec.size() != cols()) && (rows() != 0)) {\n    throw invalid_argument(\"mismatching dims\");\n  }\n\n  int newCols = rows() == 0 ? vec.size() : cols();\n  m.resize(rows() + 1, newCols, true);\n  boost::numeric::ublas::matrix_row<double_matrix_t> lastRow(m, rows() - 1);\n  for (int i = 0; i < lastRow.size(); ++i) {\n    lastRow(i) = vec[i];\n  }\n}\n\nvoid DoubleMatrix::appendCols(const DoubleMatrix&other) {\n  if (cols()!=0 && other.rows()!=rows())\n    throw invalid_argument(\"mismatching dims\");\n  int origCols = cols();\n  m.resize(other.rows(), cols() + other.cols(), true);\n  for (int i = 0; i < other.rows(); ++i) {\n    for (int j = 0; j < other.cols(); ++j) {\n      m(i, origCols + j) = other.get(i, j);\n    }\n  }\n}\n\nvoid DoubleMatrix::appendRows(const DoubleMatrix &other) {\n    if (rows() != 0 && other.cols() != cols())\n        throw invalid_argument(\"mismatching dims\");\n    int origRows = rows();\n    m.resize(rows() + other.rows(), other.cols(), true);\n    for (int i = 0; i < other.rows(); ++i) {\n        for (int j = 0; j < other.cols(); ++j) {\n            m(origRows + i, j) = other.get(i, j);\n        }\n    }\n}\n\nvoid DoubleMatrix::init(vector<vector<float> > matrix) {\n  m.resize(matrix.size(), matrix[0].size(), false);\n  for (int i = 0; i < m.size1(); ++i) {\n    for (int j = 0; j < m.size2(); ++j) {\n      m(i, j) = static_cast<double>(matrix[i][j]);\n    }\n  }\n}\n\nvoid DoubleMatrix::init(vector<vector<double> > matrix) {\n  m.resize(matrix.size(), matrix[0].size(), false);\n  for (int i = 0; i < m.size1(); ++i) {\n    for (int j = 0; j < m.size2(); ++j) {\n      m(i, j) = matrix[i][j];\n    }\n  }\n}\n\nvoid DoubleMatrix::initRandom() {\n  for (int i = 0; i < m.size1(); ++i) {\n    for (int j = 0; j < m.size2(); ++j) {\n      int val = rand() % 10000;\n      double dval = ((double) val / 10000.0) * 2 - 1;\n      m(i, j) = dval;\n    }\n  }\n}\n\nvoid DoubleMatrix::initConst(double v) {\n  std::fill(m.data().begin(), m.data().end(), v);\n}\n\nstreamoff DoubleMatrix::save(ostream& stream) const {\n  streampos streamStartPos = stream.tellp();\n\n  const int r = rows();\n  stream.write(reinterpret_cast<const char*>(&r), sizeof(int));\n\n  const int c = cols();\n  stream.write(reinterpret_cast<const char*>(&c), sizeof(int));\n\n  for (int i = 0; i < rows(); i++) {\n    for (int j = 0; j < cols(); j++) {\n      const double d = get(i, j);\n      stream.write(reinterpret_cast<const char*>(&d), sizeof(double));\n    }\n  }\n\n  streampos streamEndPos = stream.tellp();\n\n  return streamEndPos - streamStartPos;\n}\n\nstreamoff DoubleMatrix::load(istream& stream) {\n  streampos streamStartPos = stream.tellg();\n\n  int r = 0;\n  stream.read(reinterpret_cast<char*>(&r), sizeof(int));\n\n  int c = 0;\n  stream.read(reinterpret_cast<char*>(&c), sizeof(int));\n\n  m.resize(r, c);\n\n  for (int i = 0; i < rows(); i++) {\n    for (int j = 0; j < cols(); j++) {\n      double d = 0;\n      stream.read(reinterpret_cast<char*>(&d), sizeof(double));\n      set(i, j, d);\n    }\n  }\n\n  streampos streamEndPos = stream.tellg();\n\n  return streamEndPos - streamStartPos;\n}\n\nvoid DoubleMatrix::flattenIntoVec(vector<double>& vv) const {\n  for (int i = 0; i < rows(); ++i) {\n    for (int j = 0; j < cols(); ++j) {\n      vv.push_back(get(i, j));\n    }\n  }\n}\n\nvector<double> DoubleMatrix::getFlatten() const {\n  vector<double> res;\n  flattenIntoVec(res);\n  return res;\n}\n\nvoid DoubleMatrix::unFlatten(const vector<double>& v) {\n  if (v.size() != size()) {\n    throw invalid_argument(\"mismatching dims\");\n  }\n\n  int pos = 0;\n  for (int i = 0; i < rows(); ++i)\n    for (int j = 0; j < cols(); ++j)\n      set(i, j, v[pos++]);\n}\n\nvoid DoubleMatrix::debugPrint(ostream&out, int verboseLevel) const {\n  out << \"Matrix \" << rows() << \" x \" << cols() << endl;\n  if (verboseLevel == 0)\n    return;\n  const int precision = verboseLevel > 1 ? 10 : 3;\n  out << fixed;\n  for (int i = 0; i < rows(); ++i) {\n    for (int j = 0; j < cols(); ++j)\n      out << setw(precision + 6) << setprecision(precision) << get(i, j);\n    out << endl;\n  }\n  out << defaultfloat;\n}\n\nostream& operator<<(ostream&out, const DoubleMatrix&dm) {\n  dm.debugPrint(out, 1);\n  return out;\n}\n\nvoid DoubleMatrix::multiplyByScalar(double scalar) {\n  m *= scalar;\n  //for (int i = 0; i < rows(); ++i)\n  //  for (int j = 0; j < cols(); ++j)\n  //    set(i, j, get(i, j) * scalar);\n}\n\nDoubleMatrix DoubleMatrix::getTranspose() const {\n  DoubleMatrix res(cols(), rows());\n  for (int i = 0; i < rows(); ++i)\n    for (int j = 0; j < cols(); ++j)\n      res.set(j, i, get(i, j));\n  res.m = boost::numeric::ublas::trans(m);\n  return res;\n}\n\nvoid DoubleMatrix::transpose() {\n  *this = getTranspose();\n}\n\nvoid DoubleMatrix::testEqual(const string& title, const DoubleMatrix&other,\n    double tolerance) const {\n  testSameSize(title, other);\n  double maxDiff = getMaxRelDiff(other, tolerance);\n  if (maxDiff < tolerance) {\n    cout << title << \" OK (diff=\" << maxDiff << \")\" << endl;\n  } else {\n    cout << title << endl;\n    cout << \"EXP: \" << *this;\n    cout << \"ACT: \" << other;\n    cout << \"rel-diff: \" << maxDiff << endl;\n    cout << \"abs-diff: \" << getMaxDiff(other) << endl;\n    throw runtime_error(\"test failed\");\n  }\n\n}\n\nvoid DoubleMatrix::testSameSize(const string& title,\n    const DoubleMatrix&other) const {\n  if (other.rows() == rows() && other.cols() == cols())\n    return;\n  cerr << title << \":\" << endl;\n  debugPrint(cerr, 0);\n  other.debugPrint(cerr, 0);\n  throw invalid_argument(\"mismatching sizes\");\n}\n\nbool DoubleMatrix::checkIfEqual(const DoubleMatrix&other,\n    double tolerance) const {\n  if (!checkIfSameSize(other)) {\n    cout << \"different dims\" << endl;\n    return false;\n  }\n\n  for (int i = 0; i < rows(); i++) {\n    for (int j = 0; j < cols(); j++) {\n      const double diff = fabs(get(i, j) - other.get(i, j));\n      if (diff >= tolerance) {\n        cout << \"difference in indexes \" << i << \", \" << j << endl;\n        cout << \"first val = \" << get(i, j) << endl;\n        cout << \"second val = \" << other.get(i, j) << endl;\n        cout << \"diff = \" << std::setprecision(9) << diff << endl;\n        cout << \"tolerance = \" << std::setprecision(9) << tolerance << endl;\n        return false;\n      }\n    }\n  }\n\n  return true;\n}\n\nbool DoubleMatrix::checkIfSameSize(const DoubleMatrix&other) const {\n  return ((rows() == other.rows()) && (cols() == other.cols()));\n}\n\nvoid DoubleMatrix::copy(const DoubleMatrix&other) {\n  testSameSize(\"copy\",other);\n  m = other.m;\n}\n\n\nDoubleMatrix& DoubleMatrix::operator-=(const DoubleMatrix& other) {\n  testSameSize(\"-=\", other);\n  m -= other.m;\n  return *this;\n}\n\nDoubleMatrix& DoubleMatrix::operator+=(const DoubleMatrix& other) {\n  testSameSize(\"+=\", other);\n  m += other.m;\n  return *this;\n}\n\nvoid DoubleMatrix::addAt(const DoubleMatrix&other,int startRow,int startCol) {\n  if ((startRow < 0) || (startCol < 0) || (startRow + other.rows() > rows()) || (startCol + other.cols() > cols())) {\n    throw invalid_argument(\"mismatching dims\");\n  }\n  \n  for (int i = 0; i < other.rows(); ++i) {\n    for (int j = 0; j < other.cols(); ++j) {\n      m(startRow+i, startCol+j) += other.get(i, j);\n    }\n  }\n}\n\nDoubleMatrix DoubleMatrix::getDuplicate(int dupRows, int dupCols) const {\n  DoubleMatrix res(rows() * dupRows, cols() * dupCols);\n  for (int i = 0; i < res.rows(); ++i)\n    for (int j = 0; j < res.cols(); ++j)\n      res.set(i, j, get(i / dupRows, j / dupCols));\n  return res;\n}\n\nstring DoubleMatrix::niceFormat(double v) {\n  if (abs(v) < 1e-8)\n    return \"[0]\";\n  ostringstream out;\n  out.precision(12);\n  out << std::fixed << v;\n  return out.str();\n  //return to_string(v);\n}\n\nDoubleMatrix DoubleMatrix::smartUnFlatten(const vector<double>& vals,\n    int innerDup, int outerDup, int valsPerRow, int cols) {\n  assert(cols >= valsPerRow * innerDup);\n  int rows = (int) (vals.size() * outerDup + valsPerRow - 1) / valsPerRow;\n  DoubleMatrix res(rows, cols);\n  int row = 0;\n  int col = 0;\n  int valsInRow = 0;\n  for (int odup = 0; odup < outerDup; ++odup) {\n    for (int i = 0; i < (int) vals.size(); ++i) {\n      for (int dup = 0; dup < innerDup; ++dup) {\n        res.set(row, col, vals[i]);\n        ++col;\n      }\n      ++valsInRow;\n      if (valsInRow >= valsPerRow) {\n        valsInRow = 0;\n        ++row;\n        col = 0;\n      }\n    }\n  }\n  return res;\n}\n\nDoubleMatrix DoubleMatrix::smartReFlatten(int innerDup, int outerDup,\n    int valsPerRow, int cols) {\n  return smartUnFlatten(getFlatten(), innerDup, outerDup, valsPerRow, cols);\n}\n\nvoid DoubleMatrix::clear() {\n  m.resize(0, 0, false);\n}\n", "meta": {"hexsha": "935c7afab615337bb6075542136a5cb9dbdecdd1", "size": 17966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DEPENDENCIES/simple_ml_helib/src/DoubleMatrix.cpp", "max_stars_repo_name": "sakshi170920/IBM-fhe-toolkit-Genome", "max_stars_repo_head_hexsha": "41b47699a264b8354128b73b9afe34785a3c5bf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T07:22:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T18:58:50.000Z", "max_issues_repo_path": "DEPENDENCIES/simple_ml_helib/src/DoubleMatrix.cpp", "max_issues_repo_name": "sakshi170920/IBM-fhe-toolkit-Genome", "max_issues_repo_head_hexsha": "41b47699a264b8354128b73b9afe34785a3c5bf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-28T11:22:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T11:22:48.000Z", "max_forks_repo_path": "DEPENDENCIES/simple_ml_helib/src/DoubleMatrix.cpp", "max_forks_repo_name": "sakshi170920/IBM-fhe-toolkit-Genome", "max_forks_repo_head_hexsha": "41b47699a264b8354128b73b9afe34785a3c5bf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-08T19:04:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T14:02:01.000Z", "avg_line_length": 27.5975422427, "max_line_length": 117, "alphanum_fraction": 0.6054770121, "num_tokens": 5252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.033085974694221476, "lm_q1q2_score": 0.016155332060366526}}
{"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_algorithm.hpp\"\n#include \"log_helper.hpp\"\n#include \"fastpam1.hpp\"\n#include \"pam.hpp\"\n#include \"banditpam.hpp\"\n\n#include <carma>\n#include <armadillo>\n#include <unordered_map>\n#include <regex>\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 buildConfidence Constant that affects the sensitivity of build confidence bounds\n *  @param swapConfidence Constant that affects the sensitiviy of swap confidence bounds\n *  @param logFilename The name of the output log file\n */\nkm::KMedoids::KMedoids(size_t n_medoids, const std::string& algorithm, size_t verbosity,\n                   size_t max_iter, size_t buildConfidence, size_t swapConfidence,\n                   std::string logFilename\n    ): n_medoids(n_medoids),\n       algorithm(algorithm),\n       max_iter(max_iter),\n       buildConfidence(buildConfidence),\n       swapConfidence(swapConfidence),\n       verbosity(verbosity),\n       logFilename(logFilename) {\n  km::KMedoids::checkAlgorithm(algorithm);\n}\n\n/**\n *  \\brief Destroys KMedoids object.\n *\n *  Destructor for the KMedoids class.\n */\nkm::KMedoids::~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 km::KMedoids::checkAlgorithm(const std::string& algorithm) {\n  if ((algorithm != \"BanditPAM\") && (algorithm != \"naive\") && (algorithm != \"FastPAM1\")) {\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 km::KMedoids::fit\n *  has been called.\n */\narma::rowvec km::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 km::KMedoids::fit\n *  has been called.\n */\narma::rowvec km::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 km::KMedoids::fit\n *  has been called and the final medoids have been identified\n */\narma::rowvec km::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 *  km::KMedoids::fit\n */\nsize_t km::KMedoids::getSteps() {\n  return steps;\n}\n\n/**\n *  \\brief Sets the loss function\n *\n *  Sets the loss function used during km::KMedoids::fit\n *\n *  @param loss Loss function to be used e.g. L2\n */\nvoid km::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 = &km::KMedoids::manhattan;\n    } else if (loss == \"cos\") {\n        lossFn = &km::KMedoids::cos;\n    } else if (loss == \"inf\") {\n        lossFn = &km::KMedoids::LINF;\n    } else if (std::isdigit(loss.at(0))) {\n        lossFn = &km::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 km::KMedoids::fit\n */\nsize_t km::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 km::KMedoids::fit\n */\nvoid km::KMedoids::setNMedoids(size_t 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 km::KMedoids::fit\n */\nstd::string km::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 km::KMedoids::fit\n *\n *  @param new_alg New algorithm to use\n */\nvoid km::KMedoids::setAlgorithm(const std::string& new_alg) {\n  algorithm = new_alg;\n  km::KMedoids::checkAlgorithm(algorithm);\n}\n\n/**\n *  \\brief Returns the verbosity for KMedoids\n *\n *  Returns the verbosity used during km::KMedoids::fit, with 0 not creating a\n *  logfile, and >0 creating a detailed logfile.\n */\nsize_t km::KMedoids::getVerbosity() {\n  return verbosity;\n}\n\n/**\n *  \\brief Sets the verbosity for KMedoids\n *\n *  Sets the verbosity used during km::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 km::KMedoids::setVerbosity(size_t 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 *  km::KMedoids::fit\n */\nsize_t km::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 km::KMedoids::fit\n *\n *  @param new_max New maximum number of iterations to use\n */\nvoid km::KMedoids::setMaxIter(size_t new_max) {\n  max_iter = new_max;\n}\n\n/**\n *  \\brief Returns the constant buildConfidence\n *\n *  Returns the constant that affects the sensitivity of build confidence bounds\n *  that can be run during km::KMedoids::fit\n */\nsize_t km::KMedoids::getbuildConfidence() {\n  return buildConfidence;\n}\n\n/**\n *  \\brief Sets the constant buildConfidence\n *\n *  Sets the constant that affects the sensitivity of build confidence bounds\n *  that can be run during km::KMedoids::fit\n *\n *  @param new_buildConfidence New buildConfidence\n */\nvoid km::KMedoids::setbuildConfidence(size_t new_buildConfidence) {\n  buildConfidence = new_buildConfidence;\n}\n\n/**\n *  \\brief Returns the constant swapConfidence\n *\n *  Returns the constant that affects the sensitivity of swap confidence bounds\n *  that can be run during km::KMedoids::fit\n */\nsize_t km::KMedoids::getswapConfidence() {\n  return swapConfidence;\n}\n\n/**\n *  \\brief Sets the constant swapConfidence\n *\n *  Sets the constant that affects the sensitivity of swap confidence bounds\n *  that can be run during km::KMedoids::fit\n *\n *  @param new_swapConfidence New swapConfidence\n */\nvoid km::KMedoids::setswapConfidence(size_t new_swapConfidence) {\n  swapConfidence = new_swapConfidence;\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 *  km::KMedoids::fit if verbosity is >0\n */\nstd::string km::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 *  km::KMedoids::fit if verbosity is >0\n *\n *  @param new_lname New logfile name\n */\nvoid km::KMedoids::setLogFilename(const 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 km::KMedoids::fit(const arma::mat& input_data, const std::string& loss) {\n  km::KMedoids::setLossFn(loss);\n  if (algorithm == \"naive\") {\n    static_cast<PAM*>(this)->fit_naive(input_data);\n  } else if (algorithm == \"BanditPAM\") {\n    static_cast<BanditPAM*>(this)->fit_bpam(input_data);\n  } else if (algorithm == \"FastPAM1\") {\n    static_cast<FastPAM1*>(this)->fit_fastpam1(input_data);\n  }\n\n  if (this->verbosity > 0) {\n      this->logHelper.init(this->logFilename);\n      this->logHelper.writeProfile(this->medoid_indices_build, this->medoid_indices_final, this->steps,\n                                                        this->logHelper.loss_swap.back());\n      this->logHelper.close();\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 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 */\narma::rowvec km::KMedoids::build_sigma(\n  const arma::mat& data,\n  arma::rowvec& best_distances,\n  arma::uword batch_size,\n  bool use_absolute) {\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    arma::rowvec updated_sigma(N); \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        updated_sigma(i) = arma::stddev(sample);\n    }\n    arma::rowvec P = {0.25, 0.5, 0.75};\n    arma::rowvec Q = arma::quantile(updated_sigma, P);\n    std::ostringstream sigma_out;\n    sigma_out << \"min: \" << arma::min(updated_sigma)\n              << \", 25th: \" << Q(0)\n              << \", median: \" << Q(1)\n              << \", 75th: \" << Q(2)\n              << \", max: \" << arma::max(updated_sigma)\n              << \", mean: \" << arma::mean(updated_sigma);\n    logHelper.sigma_build.push_back(sigma_out.str());\n    return updated_sigma;\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 km::KMedoids::calc_best_distances_swap(\n  const arma::mat& data,\n  arma::rowvec& medoid_indices,\n  arma::rowvec& best_distances,\n  arma::rowvec& second_distances,\n  arma::rowvec& assignments) {\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 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 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::mat km::KMedoids::swap_sigma(\n  const arma::mat& data,\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 = n_medoids;\n    arma::mat updated_sigma(K, N, arma::fill::zeros);\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        updated_sigma(k, n) = arma::stddev(sample);\n    }\n  return updated_sigma;\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 km::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 km::KMedoids::calc_loss(\n  const arma::mat& data,\n  arma::rowvec& medoid_indices) {\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 km::KMedoids::LP(const arma::mat& data, size_t i, size_t j) const {\n    return arma::norm(data.col(i) - data.col(j), lp);\n}\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 km::KMedoids::cos(const arma::mat& data, size_t i, size_t 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 km::KMedoids::manhattan(const arma::mat& data, size_t i, size_t 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 km::KMedoids::LINF(const arma::mat& data, size_t i, size_t j) const {\n    return arma::max(arma::abs(data.col(i) - data.col(j)));\n}\n", "meta": {"hexsha": "13d6ff554c38abc226829998770bf919e1424d68", "size": 17411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kmedoids_algorithm.cpp", "max_stars_repo_name": "ThrunGroup/BanditPAM", "max_stars_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 251.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T19:37:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T11:21:31.000Z", "max_issues_repo_path": "src/kmedoids_algorithm.cpp", "max_issues_repo_name": "ThrunGroup/BanditPAM", "max_issues_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 152.0, "max_issues_repo_issues_event_min_datetime": "2020-12-05T00:32:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T12:33:47.000Z", "max_forks_repo_path": "src/kmedoids_algorithm.cpp", "max_forks_repo_name": "ThrunGroup/BanditPAM", "max_forks_repo_head_hexsha": "ca5c8ba2ec8227db979c3b6381c61846cf18d8ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-05-07T16:31:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T13:51:54.000Z", "avg_line_length": 30.5456140351, "max_line_length": 103, "alphanum_fraction": 0.6511975188, "num_tokens": 4510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.03963883754102852, "lm_q1q2_score": 0.01614622303983173}}
{"text": "#ifndef CANNON_LOGIC_CNF_H\n#define CANNON_LOGIC_CNF_H \n\n/*!\n * \\file cannon/logic/cnf.hpp\n * \\brief File containing classes and utility functions for working with\n * Conjunctive Normal Form (CNF) formulas.\n */\n\n#include <set>\n#include <vector>\n#include <iostream>\n#include <valarray>\n#include <algorithm>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace logic {\n\n    /*!\n     * \\brief Enumeration representing the three possible states that can be\n     * assigned to a proposition. \n     */ \n    enum class PropAssignment {\n      False,\n      Unassigned,\n      True\n    };\n\n    using Assignment=std::valarray<PropAssignment>;\n    using Simplification=std::valarray<bool>;\n\n    /*!\n     * \\brief Class representing a single literal in a CNF formula.\n     */\n    class Literal {\n      public:\n        Literal() = delete;\n\n        /*!\n         * \\brief Constructor taking a proposition number for this literal and\n         * whether it is negated.\n         */\n        Literal(unsigned int prop_num, bool negated) : prop_(prop_num), negated_(negated) {}\n\n        /*!\n         * \\brief Copy constructor.\n         */\n        Literal(const Literal& l) : prop_(l.prop_), negated_(l.negated_) {}\n        \n        /*!\n         * \\brief Move constructor.\n         */\n        Literal(Literal&& l) : prop_(l.prop_), negated_(l.negated_) {}\n\n        /*!\n         * \\brief Copy assignment operator.\n         */\n        Literal& operator=(const Literal &o) {\n          prop_ = o.prop_;\n          negated_ = o.negated_;\n          return *this;\n        }\n\n        /*!\n         * \\brief Evaluate this literal with the input assignment. The\n         * proposition number stored by this literal is taken as an index into\n         * the assignment.\n         *\n         * \\param assignment An assignment of values to propositions to\n         * evaluate this literal on.\n         *\n         * \\returns The value of this literal in the assignment.\n         */\n        PropAssignment eval(const Assignment& assignment) const;\n\n        /*!\n         * \\brief Comparison operator for sorting literals.\n         */\n        bool operator<(const Literal& l) const {\n          if (prop_ < l.prop_) {\n            return true;\n          } else if (prop_ > l.prop_) {\n            return false;\n          } else {\n            return negated_ == l.negated_ ? false : negated_;\n          }\n        }\n\n        friend std::ostream& operator<<(std::ostream& os, const Literal& l);\n\n        friend class Clause;\n        friend class CNFFormula;\n\n        unsigned int prop_; //!< Proposition number for this literal\n        bool negated_; //!< Whether this literal is negated\n    };\n\n    /*!\n     * \\brief Class representing a clause in a Conjunctive Normal Form (CNF)\n     * formula, which is defined as a disjunction of literals.\n     */\n    class Clause {\n      public:\n        \n        /*!\n         * \\brief Default constructor.\n         */\n        Clause() {}\n\n        /*!\n         * \\brief Copy constructor.\n         */\n        Clause(const Clause& o) : literals_(o.literals_), num_props_(o.num_props_) {}\n        \n        /*!\n         * \\brief Move constructor.\n         */\n        Clause(Clause&& o) : literals_(std::move(o.literals_)), num_props_(o.num_props_) {}\n\n        /*!\n         * \\brief Destructor.\n         */\n        ~Clause() {}\n\n        /*!\n         * \\brief Copy assignment operator.\n         */\n        Clause& operator=(const Clause& o) {\n          literals_ = o.literals_;\n          num_props_ = o.num_props_;\n          return *this;\n        }\n\n        /*!\n         * \\brief Add a literal to this clause.\n         *\n         * \\param l The literal to add to this clause.\n         */\n        void add_literal(Literal l);\n        \n        /*!\n         * \\brief Construct and add a literal to this clause.\n         *\n         * \\param prop_num Proposition number for the clause to add.\n         * \\param negated Whether the literal should be negated.\n         */\n        void add_literal(unsigned int prop_num, bool negated);\n\n        /*!\n         * \\brief Get the number of literals in this clause.\n         *\n         * \\returns Clause size.\n         */\n        unsigned int size() const;\n\n        /*!\n         * \\brief Get the number of unassigned literals in this clause with\n         * respect to the input assignment.\n         *\n         * \\param a Assignment to use to compute size.\n         *\n         * \\returns The number of unassigned literals in this clause.\n         */\n        unsigned int size(const Assignment& a) const;\n\n        /*!\n         * \\brief Determine if this clause is a unit clause.\n         *\n         * \\returns Whether this clause has only a single literal.\n         */\n        bool is_unit() const;\n\n        /*!\n         * \\brief Determine if this clause is a unit clause with respect to the\n         * input assignment.\n         *\n         * \\param a Assignment to use to compute if this clause is a unit.\n         *\n         * \\returns Whether this clause has only a single unassigned literal.\n         */\n        bool is_unit(const Assignment& a) const;\n\n        /*!\n         * \\brief Get the propositions in this clause which are unassigned in\n         * the input assignment.\n         *\n         * \\param a Assignment to compute props with respect to.\n         *\n         * \\returns Set of propositions in this clause.\n         */\n        std::set<unsigned int> get_props(const Assignment& a);\n\n        /*!\n         * \\brief Determine whether this clause includes the input prop when\n         * simplified according to the input assignment.\n         *\n         * \\param a The assignment to check membership with respect to.\n         * \\param prop The prop to check for membership.\n         *\n         * \\returns Whether this clause contains the query prop.\n         */\n        bool contains_prop(const Assignment& a, unsigned int prop) const;\n\n        /*!\n         * \\brief Determine whether this clause includes an unnegated literal\n         * of the input prop when simplified according to the input assignment.\n         *\n         * \\param a The assignment to check membership with respect to.\n         * \\param prop The prop to check for membership.\n         *\n         * \\returns Whether this clause contains the query prop.\n         */\n        bool has_pos_literal(const Assignment& a, unsigned int prop) const;\n\n        /*!\n         * \\brief Evalute this clause on the input assignment. Clauses evaluate\n         * to True if a single Literal in them evaluates to True, and otherwise\n         * evalute to Unassigned if any Literal evalues to Unassigned. A Clause\n         * evaluates to False iff all contained Literals evaluate to False.\n         * Trivially, an empty Clause evaluates to False.\n         *\n         * \\param a Assignment to evaluate this clause on.\n         *\n         * \\returns Evaluation of this clause.\n         */\n        PropAssignment eval(const Assignment& assignment) const;\n\n        /*!\n         * \\brief If this clause is a unit with respect to the input\n         * assignment, get the corresponding proposition.\n         *\n         * \\param a Assignment that this clause is a unit with respect to.\n         *\n         * \\returns Proposition for unit clause.\n         */\n        unsigned int get_unit_prop(const Assignment& a);\n\n        /*!\n         * \\brief If this clause is a unit with respect to the input\n         * assignment, get whether it is negated.\n         *\n         * \\param a Assignment that this clause is a unit with respect to.\n         *\n         * \\returns Whether the unit clause is negated.\n         */\n        bool get_unit_negated(const Assignment& a);\n\n        /*!\n         * \\brief Get the assignment for the input proposition which causes\n         * this clause to evaluate to True.\n         *\n         * \\param prop Proposition to get assignment for.\n         *\n         * \\returns Assignment for input prop that causes this clause to\n         * evaluate to True, or Unassigned if the proposition does not appear\n         * in this clause.\n         */\n        PropAssignment get_assignment_for_literal(unsigned int prop);\n\n        friend std::ostream& operator<<(std::ostream& os, const Clause& c);\n\n        friend class CNFFormula;\n\n        bool operator==(const Clause& c) const {\n          if (c.literals_.size() == literals_.size()) {\n            for (auto& l : literals_) {\n              if (c.literals_.find(l) == c.literals_.end()) {\n                return false;\n              }\n            }\n\n            return true;\n          } else {\n            return false;\n          }\n        }\n\n        std::set<Literal> literals_; //!< Literals in this clause\n\n      private:\n        unsigned int num_props_ = 0; //!< Number of propositions implied by proposition numbers stored in this Clause\n    };\n\n    /*!\n     * \\brief Class representing a Conjunctive Normal Form formula, which is a\n     * conjunction of Clauses.\n     */\n    class CNFFormula {\n      public:\n\n        /*!\n         * \\brief Add a Clause to this formula. \n         *\n         * \\param c Clause to add. This argument is an rval to avoid copying Literal set.\n         */\n        void add_clause(Clause&& c);\n\n        /*!\n         * \\brief Construct and add a unit clause to this formula.\n         *\n         * \\param prop Proposition for the unit clause.\n         * \\param negated Whether the proposition should be negated.\n         */\n        void add_unit_clause(unsigned int prop, bool negated);\n\n        /*!\n         * \\brief Evaluate this formula on the input assignment and\n         * simplification. Clauses are simplified when their truth can be\n         * deduced from a partial assignment, and so further proposition\n         * assignments cannot change their truth value.\n         *\n         * \\param assignment Assignment to evaluate this formula on.\n         * \\param s Simplification to accelerate evaluation.\n         */\n        PropAssignment eval(const Assignment& assignment,\n            const Simplification& s) const;\n\n        /*!\n         * \\brief Get propositions occuring in unit clauses in this formula.\n         *\n         * \\param a Assignment to find unit clauses with respect to.\n         * \\param s Simplification to accelerate unit clause finding.\n         *\n         * \\returns Vector of tuples containing propositions that occur in unit\n         * clauses, whether they are negated, and indices of the clauses in which\n         * they occur.\n         */\n        std::vector<std::tuple<unsigned int, bool, int>> get_unit_clause_props(const\n            Assignment& a, const Simplification& s) const;\n\n        /*!\n         * \\brief Get propositions occuring in unit clauses in this formula.\n         *\n         * \\param a Assignment to find unit clauses with respect to.\n         * \\param s Simplification to accelerate unit clause finding.\n         * \\param watched Watched list for all propositions used to speed up search.\n         *\n         * \\returns Vector of tuples containing propositions that occur in unit\n         * clauses, whether they are negated, and indices of the clauses in which\n         * they occur.\n         */\n        std::vector<std::tuple<unsigned int, bool, int>> get_unit_clause_props(const\n            Assignment& a, const Simplification& s,\n            std::vector<std::vector<unsigned int>> watched) const;\n\n        /*!\n         * \\brief Get propositions occuring in unit clauses in this formula.\n         *\n         * \\param a Assignment to find unit clauses with respect to.\n         * \\param s Simplification to accelerate unit clause finding.\n         * \\param unit_clauses Candidate clauses to check for being units.\n         *\n         * \\returns Vector of tuples containing propositions that occur in unit\n         * clauses, whether they are negated, and indices of the clauses in which\n         * they occur.\n         */\n        std::vector<std::tuple<unsigned int, bool, int>> get_unit_clause_props(const\n            Assignment& a, const Simplification& s, std::vector<unsigned int>\n            unit_clauses) const;\n\n        /*!\n         * \\brief Get the size of the smallest clause in this Formula.\n         *\n         * \\param a Assignment to compute clause sizes with respect to.\n         * \\param s Simplification to speed up checking.\n         *\n         * \\returns Smallest clause size.\n         */\n        unsigned int get_smallest_clause_size(const Assignment& a, const Simplification& s) const;\n\n        /*!\n         * \\brief Get the number of propositions in this formula.\n         *\n         * \\returns Number of propositions.\n         */\n        unsigned int get_num_props() const;\n        \n        /*!\n         * \\brief Get the number of clauses in this formula.\n         *\n         * \\returns The number of clauses.\n         */\n        unsigned int get_num_clauses() const;\n\n        /*!\n         * \\brief Get the number of clauses containing the input proposition\n         * and one other literal in this formula.\n         *\n         * \\param a Assignment to compute clauses sizes with respect to.\n         * \\param s Simplification to speed counting.\n         * \\param prop Proposition to compute two-clauses for.\n         *\n         * \\returns Number of two-clauses in this formula for the input proposition.\n         */\n        unsigned int get_num_two_clauses(const Assignment& a, const\n            Simplification& s, unsigned int prop) const;\n\n        /*!\n         * \\brief Get the number of two-clauses for each proposition in the input.\n         *\n         * \\param a Assignment to compute clauses sizes with respect to.\n         * \\param s Simplification to speed counting.\n         * \\param props Propositions to compute two-clauses for.\n         *\n         * \\returns Number of two-clauses in this formula for each input proposition.\n         */\n        std::vector<unsigned int> get_num_two_clauses(const Assignment& a, const\n            Simplification& s, const std::vector<unsigned int>& props) const;\n\n        /*!\n         * \\brief Get all unassigned propositions in this formula.\n         *\n         * \\param a Assignment to compute unassigned propositions with respect to.\n         * \\param s Simplification to speed up search.\n         *\n         * \\returns Unassigned propositions.\n         */\n        std::vector<unsigned int> get_props(const Assignment& a,\n            const Simplification& s);\n\n        /*!\n         * \\brief Make adjacency matrix for this formula. Two propositions are\n         * adjacent if they occur in the same clause.\n         *\n         * \\param a Assignment to compute adjacency matrix with respect to.\n         * \\param s Simplification to speed up construction.\n         *\n         * \\returns Adjacency matrix\n         */\n        MatrixXd make_adjacency_mat(const Assignment& a, const Simplification& s) const;\n\n        /*!\n         * \\brief Get multiset of all unassigned propositions in this formula.\n         *\n         * \\param a Assignment to compute unassigned propositions with respect to.\n         * \\param s Simplification to speed up search.\n         *\n         * \\returns Unassigned propositions.\n         */\n        std::multiset<unsigned int> get_props_multiset(const Assignment& a,\n            const Simplification& s);\n\n        /*!\n         * \\brief Check whether the input proposition is a pure literal in this\n         * formula. A pure literal is one that appears only as a positive\n         * proposition or negated proposition in the formula.\n         *\n         * \\param a Assignment to compute whether the input prop is a pure\n         * literal with respect to.\n         * \\param s Simplification to speed up search.\n         * \\param prop Proposition to check.\n         *\n         * \\returns Unassigned if the input prop is not a pure literal in this\n         * formula, or else the assignment (True or False) which makes literals\n         * containing the input prop evaluate true.\n         */\n        PropAssignment is_pure_literal(const Assignment& a, const Simplification& s,\n            unsigned int prop);\n\n        /*!\n         * \\brief Generate a simplification for this formula.\n         *\n         * \\param a Assignment to generate a simplification with respect to.\n         * \\param s Previous simplification to speed up generation.\n         *\n         * \\returns A new simplification skipping clauses which evaluate to true.\n         */\n        Simplification simplify(const Assignment& a,\n            const Simplification& s) const;\n\n        /*!\n         * \\brief Merge the input formula into this formula.\n         *\n         * \\param f Formula to merge.\n         */\n        void merge(CNFFormula&& f);\n\n        bool operator==(const CNFFormula f) const {\n          if (f.clauses_.size() == clauses_.size()) {\n            for (auto& c : clauses_) {\n              if (std::find(f.clauses_.begin(), f.clauses_.end(), c) == f.clauses_.end()) {\n                return false;\n              }\n            }\n\n            return true;\n          } else {\n            return false;\n          }\n        }\n\n        friend std::ostream& operator<<(std::ostream& os, const CNFFormula& f);\n\n        std::vector<Clause> clauses_; //!< Clauses in this formula\n\n      private:\n        unsigned int num_props_ = 0; //!< Number of propositions in this formula\n    };\n\n    /*!\n     * \\brief Generate a random 3-clause using propositions 0 to num_props-1.\n     *\n     * \\param num_props Maximum number of propositions to choose from.\n     *\n     * \\returns Generated clause.\n     */\n    Clause generate_random_clause(unsigned int num_props);\n\n    /*!\n     * \\brief Generate a random 3-CNF formula.\n     *\n     * \\param num_props Maximum number of propositions to choose from.\n     * \\param num_clauses Number of clauses in random formula\n     *\n     * \\returns Generated formula.\n     */\n    CNFFormula generate_random_formula(unsigned int num_props, unsigned int num_clauses);\n\n    /*!\n     * \\brief Attempt to resolve two CNF clauses on the input proposition.\n     * Throws an exception if the two clauses cannot be resolved on the input\n     * prop (i.e., they do not both contain the proposition or the literals\n     * containing the proposition don't have opposite negation).\n     *\n     * \\param c1 First clause to resolve, which will be modified to contain the resolved clause\n     * \\param c2 Second clause to use in resolution.\n     * \\param prop Proposition to resolve on.\n     */\n    void resolve(Clause& c1, const Clause& c2, unsigned int prop);\n\n    std::ostream& operator<<(std::ostream& os, PropAssignment a);\n    std::ostream& operator<<(std::ostream& os, const Literal& l);\n    std::ostream& operator<<(std::ostream& os, const Clause& c);\n    std::ostream& operator<<(std::ostream& os, const CNFFormula& f);\n\n    std::ostream& operator<<(std::ostream& os, const std::valarray<PropAssignment>& v);\n    bool operator==(const std::valarray<PropAssignment>& v1, const std::valarray<PropAssignment>& v2);\n    bool operator!=(const std::valarray<PropAssignment>& v1, const std::valarray<PropAssignment>& v2);\n\n  } // namespace logic\n} // namespace cannon\n\n#endif /* ifndef CANNON_LOGIC_CNF_H */\n", "meta": {"hexsha": "75f755c0b9950a02e96609bea942067e9bf2d681", "size": 19153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/logic/cnf.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/logic/cnf.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/logic/cnf.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": 34.8870673953, "max_line_length": 117, "alphanum_fraction": 0.5937973163, "num_tokens": 4004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658972248186, "lm_q2_score": 0.04401864719795893, "lm_q1q2_score": 0.016136783660326667}}
{"text": "/******************************************************************************\n* Turbo C++11 metaprogramming Library                                         *\n*                                                                             *\n* Copyright (C) 2013 - 2014, Manuel Sánchez Pérez                             *\n*                                                                             *\n* This file is part of The Turbo Library.                                     *\n*                                                                             *\n* The Turbo Library 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, version 2 of the License.                     *\n*                                                                             *\n* The Turbo 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 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 The Turbo Library. If not, see <http://www.gnu.org/licenses/>.   *\n******************************************************************************/\n\n#ifndef EVAL_HPP\n#define\tEVAL_HPP\n\n#include <type_traits>\n\n#include \"list.hpp\"\n#include \"enable_if.hpp\"\n#include \"function.hpp\"\n#include \"chameleon.hpp\"\n\n#include <boost/preprocessor.hpp>\n\n#define TURBO_EVAL_ARGS_APPLY_NO_ARGS(...) >\n#define TURBO_EVAL_ARGS_APPLY_ARGS(...) ,__VA_ARGS__>\n\n#define TURBO_EVAL_ARGS_APPLY(...) BOOST_PP_IIF( \\\n    BOOST_PP_GREATER(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), 1), \\\n        TURBO_EVAL_ARGS_APPLY_ARGS, TURBO_EVAL_ARGS_APPLY_NO_ARGS)\n\n#define TURBO_EVAL_ARGS_APPLY_CALLER(...) TURBO_EVAL_ARGS_APPLY(__,__VA_ARGS__)(__VA_ARGS__)\n\n\n#define $(...) tml::eval<__VA_ARGS__>\n\nnamespace tml\n{\n    \n    /*\n     * This metafunction says if one type of expression has overrided the default\n     * behaviour of tml::eval. Every user-defined type which wants to override \n     * tml::eval should be registered specializing this metafunction inheriting\n     * from tml::true_type.\n     */\n    template<typename E>\n    struct overrides_eval : public tml::false_type\n    {};\n    \n    namespace impl\n    {\n        /*\n         * Here we implement the user-side tml::eval<> metafunction. \n         * \n         * The purpose of that metafunction is to evaluate any kind of expression.\n         * That serves to evaluate functions and other functional expressions.\n         */   \n\n         template<typename... Args>\n         struct args_list {};\n\n         using no_args = args_list<>;\n\n        /*\n         * The implementation has three parameters:\n         * \n         *  - E: The expression to be evaluated.\n         * \n         *  - ARGS: evaluate could be used as a high-order metafunction to evaluate a given\n         *             function entity with the specified parameters. This variadic pack is that\n         *             set of parameters. The result of the evaluation is the result of evaluating\n         *             the functional expresion E with the specified ARGS... arguments.\n         *             Note that in this case the argumments are evaluated too (Just for the case they are\n         *             functional expressions).\n         * \n         *  - SFINAE_FALGS: Parameters used to enable/disable certain specializations.\n         * \n         *  Of course this metafunction is a function too, so it stores the result of the evaluation in a 'result' member type.\n         */\n        template<typename E , typename ARGS , typename SFINAE_FLAGS = tml::sfinae_return>\n        struct eval\n        {\n            using result = E;\n        };\n        \n        /*\n         * Non-decayed function pointer types (i.e. R(ARGS...) ) are used as a shorthand for a metafunction call F(ARGS...).\n         * So they should be discarded to not match the simple expression tml::eval specialization.\n         */\n        template<typename T>\n        struct is_function_ptr_type : public tml::false_type\n        {};\n        \n        template<typename F , typename... ARGS>\n        struct is_function_ptr_type<F(ARGS...)> : public tml::true_type\n        {};\n\n        /* This is the most simple case: There are no evaluation parameters (So the expression could be any\n         * kind of expression, not just a function) BUT the flag says the expression is not a function.\n         * The result of evaluating such expression is the expression itself.\n         */\n        template<typename E>\n        struct eval<E,no_args,\n                    TURBO_SFINAE_ALL(\n                                     DISABLE_IF(tml::overrides_eval<E>),\n                                     DISABLE_IF(tml::is_function<E>),\n                                     DISABLE_IF(is_function_ptr_type<E>),\n                                     DISABLE_IF(tml::is_aggregate<E>),\n                                     DISABLE_IF(tml::is_metafunction_class<E>)\n                                    )\n                   >\n        {\n            using result = E;\n        };\n\n        template<typename E, typename Args, typename = void>\n        struct expand\n        {\n            using result = E;\n        };\n\n        template<typename E, typename Args>\n        struct expand<E,Args,TURBO_ENABLE_IF(tml::is_expandible<E>)>\n        {\n            using result = typename eval<E,Args>::result;\n        };\n\n        template<typename E>\n        struct eval<E,no_args,\n                TURBO_SFINAE_ALL(\n                        DISABLE_IF(tml::overrides_eval<E>),\n                        ENABLE_IF(tml::is_function<E>),\n                        DISABLE_IF(is_function_ptr_type<E>),\n                        DISABLE_IF(tml::is_aggregate<E>),\n                        DISABLE_IF(tml::is_metafunction_class<E>)\n                )\n        >\n        {\n            template<typename T, bool is_stl_function = tml::is_stl_function<T>::value>\n            struct call\n            {\n                using result = typename T::type;\n            };\n\n            template<typename T>\n            struct call<T, false>\n            {\n                using result = typename T::result;\n            };\n\n            using result = typename call<E>::result;\n        };\n        \n\n        template<template<typename...> class F , typename... ARGS>\n        struct eval<F<ARGS...>,no_args,\n                    TURBO_SFINAE_ALL(DISABLE_IF(tml::overrides_eval<F<ARGS...>>),\n                                     ENABLE_IF(tml::is_aggregate<F<ARGS...>>),\n                                     ENABLE_IF(tml::is_turbo_function<F<ARGS...>>),\n                                     DISABLE_IF(tml::is_metafunction_class<F<ARGS...>>)\n                                    )\n                   > \n        {\n            using f = F<typename expand<ARGS,no_args>::result...>;\n\n            template<typename T, bool is_stl_function = tml::is_stl_function<f>::value>\n            struct call\n            {\n                using result = typename T::type;\n            };\n\n            template<typename T>\n            struct call<T, false>\n            {\n                using result = typename T::result;\n            };\n\n            using result = typename call<f>::result;\n        };\n        \n        /*\n         * This specialization matches the case when the expression passed is a parametrized\n         * expression (But not a function).\n         * \n         * The parameters are evaluated too (Could be functional/parametrized expressions too) to evaluate the entire\n         * expression recursively.\n         */\n        template<template<typename...> class E , typename... ARGS>\n        struct eval<E<ARGS...>,no_args,\n                    TURBO_SFINAE_ALL(\n                                     DISABLE_IF(tml::overrides_eval<E<ARGS...>>),\n                                     DISABLE_IF(tml::is_function<E<ARGS...>>),\n                                     ENABLE_IF(tml::is_aggregate<E<ARGS...>>),\n                                     DISABLE_IF(tml::is_metafunction_class<E<ARGS...>>)\n                                    )\n                   > : \n                   public tml::function<E<typename expand<ARGS,no_args>::result...>>\n        {};\n\n        /*\n         * This is the case when the expression passed is a function, and a set of parameters (At least one) is \n         * passed to evaluate the function with. \n         *\n         * Note that the parameters of the function call are evaluated too.\n         * \n         * The result is the result of evaluating the function with that parameters.\n         */\n        template<template<typename...> class F , typename... PLACEHOLDERS , typename ARG , typename... ARGS>\n        struct eval<F<PLACEHOLDERS...> , args_list<ARG,ARGS...>,\n                    TURBO_SFINAE_ALL(\n                                     DISABLE_IF(tml::overrides_eval<F<PLACEHOLDERS...>>),\n                                     ENABLE_IF(tml::is_function<F<PLACEHOLDERS...>>),\n                                     DISABLE_IF(tml::is_metafunction_class<F<PLACEHOLDERS...>>)\n                                    )\n                   > : \n                   public F<typename expand<ARG,no_args>::result,\n                            typename expand<ARGS,no_args>::result...\n                           >\n        {\n            \n        };\n        \n        /*\n         * This is the case when the expression passed is a parametrized expression (And not a function),\n         * and a set of parameters (At least one) is passed to evaluate the expression with. \n         * \n         * Note that the parameters of the function call are evaluated too.\n         */\n        template<template<typename...> class E , typename... PLACEHOLDERS , typename ARG , typename... ARGS>\n        struct eval<E<PLACEHOLDERS...> , args_list<ARG,ARGS...>,\n                    TURBO_SFINAE_ALL(\n                                     DISABLE_IF(tml::overrides_eval<E<PLACEHOLDERS...>>),\n                                     DISABLE_IF(tml::is_function<E<PLACEHOLDERS...>>),\n                                     DISABLE_IF(tml::is_metafunction_class<E<PLACEHOLDERS...>>)\n                                    )\n                   > : \n                   public tml::function<E<typename expand<ARG,no_args>::result,\n                                          typename expand<ARGS,no_args>::result...\n                                         >\n                                       >\n        {\n            //static_assert( sizeof...(PLACEHOLDERS) == (1 + sizeof...(ARGS)) , \"Wrong number of function call parameters.\" );  \n        };\n\n        template<typename F, typename... ARGS>\n        struct eval<F, args_list<ARGS...>,\n                    TURBO_SFINAE_ALL(ENABLE_IF(tml::is_metafunction_class<F>))\n                   >\n        {\n            //static_assert(sizeof(F) != sizeof(F), \"compiler bug!\");\n\n            using apply = tml::impl::get_apply<F, typename expand<ARGS,no_args>::result...>;\n\n            template<typename T, bool is_stl_function = tml::is_stl_function<T>::value>\n            struct call\n            {\n                using result = typename T::type;\n            };\n\n            template<typename T>\n            struct call<T, false>\n            {\n                using result = typename T::result;\n            };\n\n            using result = typename call<apply>::result;\n        };\n        \n        /*\n         * Alternative call-like syntax\n         */\n        template<typename F , typename... ARGS>\n        struct eval<F(ARGS...),no_args,\n                    TURBO_SFINAE_ALL(\n                                     ENABLE_IF( tml::true_type )\n                                    )\n                   >:\n                   public tml::impl::eval<F,args_list<ARGS...>>\n        {};\n\n        template<typename F, typename G, typename... Args>\n        struct eval<F(*)(G), args_list<Args...>>\n        {\n            using result = typename eval<F,args_list<typename eval<G,args_list<Args...>>::result>>::result;\n        };\n    }\n    \n    /*\n     * Metafunction to evaluate expressions.\n     * \n     * The purpose of this metafunction is to evaluate homogeneously any kind of expression.\n     * Also, this could be used as a high-order metafunction to reevaluate an specified functional\n     * expression with a custom set of parameters.\n     * \n     * Note that the parameters of the expression will be ignored during reevaluation. \n     * If your intention is to pass the expression to a high order metafunction,\n     * you have to fill that parameters even if they will not be used during evaluation.\n     * The set of placeholders defined in \"placeholders.hpp\" could be used for that purpose.\n     * Also the template wrapper 'tml::lazy' defined in \"lazy.hpp\" could be used to pass a template\n     * without parameters and pass that parameters later when the evaluation is done.\n     * \n     * The metafunction has the following parameters:\n     *  - E: The expression to be evaluated.\n     * \n     *  - ARGS...: eval could be used as a high-order metafunction to reevaluate a given\n     *             function entity with the specified parameters. This variadic pack is that\n     *             set of parameters. The result of the evaluation is the result of evaluating\n     *             the functional expresion E with the specified ARGS... arguments.\n     *             Note that in this case the argumments are evaluated too (Just for the case they are\n     *             functional/parametrized expressions).\n     */\n    template<typename EXPRESSION , typename... ARGS>\n    using eval = typename impl::eval<EXPRESSION , impl::args_list<ARGS...>>::result;\n    \n    \n    \n    /*\n     * Provides delayed evaluation of an expression until its placeholders are substituted by its values.\n     * Is a special case for lambda bodies expressions.\n     * \n     * Lambda bodies with evaluating expressions such as 'tml::eval<F,_1>' doesn't work because the placeholder is substituted after the \n     * expression evaluation.\n     * \n     * The library provides the template tml::delayed_eval<F,ARGS...> for that purpose: It holds a functional expression reevaluation\n     * with parameters that may be placeholders. When doing let on such template, tml::let substitutes the letted placeholders with its\n     * values, and the tml::delayed_eval template with tml::eval.\n     * \n     * NOTE: See the documentation of the specialization of tml::let in \"let_expressions.hpp\" for more info.\n     */\n    template<typename... ARGS>\n    struct delayed_eval : public tml::value_chameleon\n    {\n    };\n\n    template<typename... ARGS>\n    struct overrides_eval<tml::delayed_eval<ARGS...>> : public tml::true_type\n    {};\n\n    namespace impl\n    {\n        template<typename E, typename... ARGS>\n        struct eval<tml::delayed_eval<E,ARGS...>, no_args> : \n            public tml::function<tml::eval<E,ARGS...>>\n        {};\n    }\n    \n    /*\n     * Simple shorthand alias:\n     */\n    template<typename... ARGS>\n    using deval = tml::delayed_eval<ARGS...>;\n}\n\n#endif\t/* EVAL_HPP */\n\n", "meta": {"hexsha": "ab78efc1ca7e4844caf37252224ec59a32fe25e5", "size": 15341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eval.hpp", "max_stars_repo_name": "Manu343726/Turbo", "max_stars_repo_head_hexsha": "9b2b70cee1f3dbaaf839edf8faf52fd4cb9a4eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T14:04:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T17:49:32.000Z", "max_issues_repo_path": "include/eval.hpp", "max_issues_repo_name": "Manu343726/Turbo", "max_issues_repo_head_hexsha": "9b2b70cee1f3dbaaf839edf8faf52fd4cb9a4eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-03-23T09:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-08T06:39:48.000Z", "max_forks_repo_path": "include/eval.hpp", "max_forks_repo_name": "Manu343726/Turbo", "max_forks_repo_head_hexsha": "9b2b70cee1f3dbaaf839edf8faf52fd4cb9a4eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T21:09:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-03T07:38:08.000Z", "avg_line_length": 42.1456043956, "max_line_length": 137, "alphanum_fraction": 0.532885731, "num_tokens": 3037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245628973633, "lm_q2_score": 0.05921024949619564, "lm_q1q2_score": 0.016106642238246444}}
{"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_VECTOR_H\n#define BOOST_UBLAS_VECTOR_H\n\n#include <boost/numeric/ublas/config.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/vector_assign.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n\n// Iterators based on ideas of Jeremy Siek\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    // Array based vector class\n    template<class T, class A>\n    class vector:\n        public vector_expression<vector<T, A> > {\n    public:\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\n        BOOST_UBLAS_USING vector_expression<vector<T, A> >::operator ();\n#endif\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef T value_type;\n        // typedef const T &const_reference;\n        typedef typename type_traits<T>::const_reference const_reference;\n        typedef T &reference;\n        typedef const T *const_pointer;\n        typedef T *pointer;\n        typedef A array_type;\n        typedef const A const_array_type;\n        typedef const vector<T, A> const_self_type;\n        typedef vector<T, A> self_type;\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\n        typedef const vector_const_reference<const_self_type> const_closure_type;\n#else\n        typedef const vector_reference<const_self_type> const_closure_type;\n#endif\n        typedef vector_reference<self_type> closure_type;\n        typedef typename A::const_iterator const_iterator_type;\n        typedef typename A::iterator iterator_type;\n        typedef dense_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        vector ():\n            size_ (0), data_ (0) {}\n        BOOST_UBLAS_EXPLICIT BOOST_UBLAS_INLINE\n        vector (size_type size):\n            size_ (size), data_ (size) {}\n        BOOST_UBLAS_INLINE\n        vector (size_type size, const array_type &data):\n            size_ (size), data_ (data) {}\n        BOOST_UBLAS_INLINE\n        vector (const vector &v):\n            size_ (v.size_), data_ (v.data_) {}\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector (const vector_expression<AE> &ae):\n            size_ (ae ().size ()), data_ (ae ().size ()) {\n            vector_assign (scalar_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n        }\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n        BOOST_UBLAS_INLINE\n        const_array_type &data () const {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        array_type &data () {\n            return data_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size) {\n            size_ = size;\n            data ().resize (size);\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            return data () [i];\n        }\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i) {\n            return data () [i];\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const {\n            return (*this) (i);\n        }\n        BOOST_UBLAS_INLINE\n        reference operator [] (size_type i) {\n            return (*this) (i);\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        vector &operator = (const vector &v) {\n            BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n            size_ = v.size_;\n            data () = v.data ();\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        vector &assign_temporary (vector &v) {\n            swap (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &operator = (const vector_expression<AE> &ae) {\n#ifdef BOOST_UBLAS_MUTABLE_TEMPORARY\n            return assign_temporary (self_type (ae));\n#else\n            // return assign (self_type (ae));\n            self_type temporary (ae);\n            return assign_temporary (temporary);\n#endif\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &reset (const vector_expression<AE> &ae) {\n            self_type temporary (ae);\n            resize (temporary.size ());\n            return assign_temporary (temporary);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &assign (const vector_expression<AE> &ae) {\n            vector_assign (scalar_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &operator += (const vector_expression<AE> &ae) {\n#ifdef BOOST_UBLAS_MUTABLE_TEMPORARY\n            return assign_temporary (self_type (*this + ae));\n#else\n            // return assign (self_type (*this + ae));\n            self_type temporary (*this + ae);\n            return assign_temporary (temporary);\n#endif\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &plus_assign (const vector_expression<AE> &ae) {\n            vector_assign (scalar_plus_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &operator -= (const vector_expression<AE> &ae) {\n#ifdef BOOST_UBLAS_MUTABLE_TEMPORARY\n            return assign_temporary (self_type (*this - ae));\n#else\n            // return assign (self_type (*this - ae));\n            self_type temporary (*this - ae);\n            return assign_temporary (temporary);\n#endif\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &minus_assign (const vector_expression<AE> &ae) {\n            vector_assign (scalar_minus_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        vector &operator *= (const AT &at) {\n            vector_assign_scalar (scalar_multiplies_assign<value_type, AT> (), *this, at);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        vector &operator /= (const AT &at) {\n            vector_assign_scalar (scalar_divides_assign<value_type, AT> (), *this, at);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (vector &v) {\n            // Too unusual semantic.\n            // BOOST_UBLAS_CHECK (this != &v, external_logic ());\n            if (this != &v) {\n                // Precondition for container relaxed as requested during review.\n                // BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n                std::swap (size_, v.size_);\n                data ().swap (v.data ());\n            }\n        }\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\n        BOOST_UBLAS_INLINE\n        friend void swap (vector &v1, vector &v2) {\n            v1.swap (v2);\n        }\n#endif\n\n        // Element insertion and erasure\n        // These functions should work with std::vector.\n        // Thanks to Kresimir Fresl for spotting this.\n        BOOST_UBLAS_INLINE\n        void insert (size_type i, const_reference t) {\n            BOOST_UBLAS_CHECK (data () [i] == value_type (), bad_index ());\n            // data ().insert (data ().begin () + i, t);\n            data () [i] = t;\n        }\n        BOOST_UBLAS_INLINE\n        void erase (size_type i) {\n            // data ().erase (data ().begin () + i);\n            data () [i] = value_type ();\n        }\n        BOOST_UBLAS_INLINE\n        void clear () {\n            // data ().clear ();\n            std::fill (data ().begin (), data ().end (), value_type ());\n        }\n\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_iterator<self_type, dense_random_access_iterator_tag> iterator;\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\n#else\n        class const_iterator;\n        class iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator (*this, data ().begin () + i);\n#else\n            return const_iterator (*this, i);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        iterator find (size_type i) {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return iterator (*this, data ().begin () + i);\n#else\n            return iterator (*this, i);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_first (size_type i) const {\n            return find (i);\n        }\n        BOOST_UBLAS_INLINE\n        iterator find_first (size_type i) {\n            return find (i);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_last (size_type i) const {\n            return find (i);\n        }\n        BOOST_UBLAS_INLINE\n        iterator find_last (size_type i) {\n            return find (i);\n        }\n\n        // Iterators simply are pointers.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef dense_random_access_iterator_tag iterator_category;\n#ifdef BOOST_MSVC_STD_ITERATOR\n            typedef const_reference reference;\n#else\n            typedef typename vector::difference_type difference_type;\n            typedef typename vector::value_type value_type;\n            typedef typename vector::const_reference reference;\n            typedef typename vector::const_pointer pointer;\n#endif\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &v, const const_iterator_type &it):\n                container_const_reference<self_type> (v), it_ (it) {}\n            BOOST_UBLAS_INLINE\n#ifndef BOOST_UBLAS_QUALIFIED_TYPENAME\n            const_iterator (const iterator &it):\n#else\n            const_iterator (const typename self_type::iterator &it):\n#endif\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\n                return *it_;\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                return it_ - (*this) ().begin ().it_;\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_iterator_type it_;\n\n            friend class iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find_first (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find_first (size_);\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class iterator:\n            public container_reference<vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               iterator, value_type> {\n        public:\n            typedef dense_random_access_iterator_tag iterator_category;\n#ifndef BOOST_MSVC_STD_ITERATOR\n            typedef typename vector::difference_type difference_type;\n            typedef typename vector::value_type value_type;\n            typedef typename vector::reference reference;\n            typedef typename vector::pointer pointer;\n#endif\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            iterator ():\n                container_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            iterator (self_type &v, const iterator_type &it):\n                container_reference<self_type> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\n                return *it_;\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                return it_ - (*this) ().begin ().it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            iterator &operator = (const iterator &it) {\n                container_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            iterator_type it_;\n\n            friend class const_iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        iterator begin () {\n            return find_first (0);\n        }\n        BOOST_UBLAS_INLINE\n        iterator end () {\n            return find_first (size_);\n        }\n\n        // Reverse iterator\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\n#else\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef reverse_iterator_base<iterator, value_type, reference> reverse_iterator;\n#else\n        typedef reverse_iterator_base<iterator> reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator rbegin () {\n            return reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rend () {\n            return reverse_iterator (begin ());\n        }\n\n    private:\n        size_type size_;\n        array_type data_;\n    };\n\n    // Unit vector class\n    template<class T>\n    class unit_vector:\n        public vector_expression<unit_vector<T> > {\n    public:\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\n        BOOST_UBLAS_USING vector_expression<unit_vector<T> >::operator ();\n#endif\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef T value_type;\n        // typedef const T &const_reference;\n        typedef typename type_traits<T>::const_reference const_reference;\n        typedef T &reference;\n        typedef const T *const_pointer;\n        typedef T *pointer;\n        typedef const unit_vector<T> const_self_type;\n        typedef unit_vector<T> self_type;\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\n        typedef const vector_const_reference<const_self_type> const_closure_type;\n#else\n        typedef const vector_reference<const_self_type> const_closure_type;\n#endif\n        typedef size_type const_iterator_type;\n        typedef packed_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        unit_vector (): \n            size_ (0), index_ (0) {}\n        BOOST_UBLAS_INLINE\n        unit_vector (size_type size, size_type index): \n            size_ (size), index_ (index) {}\n        BOOST_UBLAS_INLINE\n        unit_vector (const unit_vector &v): \n            size_ (v.size_), index_ (v.index_) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const { \n            return size_; \n        }\n        BOOST_UBLAS_INLINE\n        size_type index () const { \n            return index_; \n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size) {\n            size_ = size;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            return i == index_ ? one_ : zero_; \n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const {\n            return (*this) (i); \n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        unit_vector &operator = (const unit_vector &v) { \n            BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n            size_ = v.size_;\n            index_ = v.index_;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        unit_vector &assign_temporary (unit_vector &v) { \n            swap (v);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (unit_vector &v) {\n            // Too unusual semantic.\n            // BOOST_UBLAS_CHECK (this != &v, external_logic ());\n            if (this != &v) {\n                // Precondition for container relaxed as requested during review.\n                // BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n                std::swap (size_, v.size_);\n                std::swap (index_, v.index_);\n            }\n        }\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\n        BOOST_UBLAS_INLINE\n        friend void swap (unit_vector &v1, unit_vector &v2) {\n            v1.swap (v2);\n        }\n#endif\n\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator<self_type, packed_random_access_iterator_tag> iterator;\n        typedef indexed_const_iterator<self_type, packed_random_access_iterator_tag> const_iterator;\n#else\n        class const_iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find_first (size_type i) const {\n            return const_iterator (*this, std::max (i, index_));\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_last (size_type i) const {\n            return const_iterator (*this, std::min (i, index_ + 1));\n        }\n\n        // Iterators simply are pointers.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<unit_vector>,\n            public random_access_iterator_base<packed_random_access_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef packed_random_access_iterator_tag iterator_category;\n#ifdef BOOST_MSVC_STD_ITERATOR\n            typedef const_reference reference;\n#else\n            typedef typename unit_vector::difference_type difference_type;\n            typedef typename unit_vector::value_type value_type;\n            typedef typename unit_vector::const_reference reference;\n            typedef typename unit_vector::const_pointer pointer;\n#endif\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<unit_vector> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const unit_vector &v, const const_iterator_type &it):\n                container_const_reference<unit_vector> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\n                return (*this) () (index ());\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                return it_;\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<unit_vector>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_iterator_type it_;\n        };\n\n        typedef const_iterator iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find_first (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find_first (size_);\n        }\n\n        // Reverse iterator\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\n#else\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n    private:\n        size_type size_;\n        size_type index_;\n        static value_type zero_;\n        static value_type one_;\n    };\n\n    template<class T>\n    typename unit_vector<T>::value_type unit_vector<T>::zero_ = 0;\n    template<class T>\n    typename unit_vector<T>::value_type unit_vector<T>::one_ = 1;\n\n    // Zero vector class\n    template<class T>\n    class zero_vector:\n        public vector_expression<zero_vector<T> > {\n    public:\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\n        BOOST_UBLAS_USING vector_expression<zero_vector<T> >::operator ();\n#endif\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef T value_type;\n        // typedef const T &const_reference;\n        typedef typename type_traits<T>::const_reference const_reference;\n        typedef T &reference;\n        typedef const T *const_pointer;\n        typedef T *pointer;\n        typedef const zero_vector<T> const_self_type;\n        typedef zero_vector<T> self_type;\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\n        typedef const vector_const_reference<const_self_type> const_closure_type;\n#else\n        typedef const vector_reference<const_self_type> const_closure_type;\n#endif\n        typedef size_type const_iterator_type;\n        typedef sparse_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        zero_vector ():\n            size_ (0) {}\n        BOOST_UBLAS_EXPLICIT BOOST_UBLAS_INLINE\n        zero_vector (size_type size):\n            size_ (size) {}\n        BOOST_UBLAS_INLINE\n        zero_vector (const zero_vector &v):\n            size_ (v.size_) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size) {\n            size_ = size;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            return zero_;\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const {\n            return (*this) (i);\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        zero_vector &operator = (const zero_vector &v) {\n            BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n            size_ = v.size_;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        zero_vector &assign_temporary (zero_vector &v) {\n            swap (v);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (zero_vector &v) {\n            // Too unusual semantic.\n            // BOOST_UBLAS_CHECK (this != &v, external_logic ());\n            if (this != &v) {\n                // Precondition for container relaxed as requested during review.\n                // BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n                std::swap (size_, v.size_);\n            }\n        }\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\n        BOOST_UBLAS_INLINE\n        friend void swap (zero_vector &v1, zero_vector &v2) {\n            v1.swap (v2);\n        }\n#endif\n\n        class const_iterator;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find_first (size_type i) const {\n            return const_iterator (*this, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_last (size_type i) const {\n            return const_iterator (*this, 0);\n        }\n\n        // Iterators simply are pointers.\n\n        class const_iterator:\n            public container_const_reference<zero_vector>,\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef sparse_bidirectional_iterator_tag iterator_category;\n#ifdef BOOST_MSVC_STD_ITERATOR\n            typedef const_reference reference;\n#else\n            typedef typename zero_vector::difference_type difference_type;\n            typedef typename zero_vector::value_type value_type;\n            typedef typename zero_vector::const_reference reference;\n            typedef typename zero_vector::const_pointer pointer;\n#endif\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &v, const const_iterator_type &it):\n                container_const_reference<self_type> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\n                return (*this) () (index ());\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                return it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n\n        private:\n            const_iterator_type it_;\n        };\n\n        typedef const_iterator iterator;\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find_first (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find_first (size_);\n        }\n\n        // Reverse iterator\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\n#else\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n    private:\n        size_type size_;\n        static value_type zero_;\n    };\n\n    template<class T>\n    typename zero_vector<T>::value_type zero_vector<T>::zero_ = 0;\n\n    // Scalar vector class\n    template<class T>\n    class scalar_vector:\n        public vector_expression<scalar_vector<T> > {\n    public:\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\n        BOOST_UBLAS_USING vector_expression<scalar_vector<T> >::operator ();\n#endif\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef T value_type;\n        // typedef const T &const_reference;\n        typedef typename type_traits<T>::const_reference const_reference;\n        typedef T &reference;\n        typedef const T *const_pointer;\n        typedef T *pointer;\n        typedef const scalar_vector<T> const_self_type;\n        typedef scalar_vector<T> self_type;\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\n        typedef const vector_const_reference<const_self_type> const_closure_type;\n#else\n        typedef const vector_reference<const_self_type> const_closure_type;\n#endif\n        typedef size_type const_iterator_type;\n        typedef dense_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        scalar_vector ():\n            size_ (0), value_ () {}\n        BOOST_UBLAS_INLINE\n        scalar_vector (size_type size, const value_type &value):\n            size_ (size), value_ (value) {}\n        BOOST_UBLAS_INLINE\n        scalar_vector (const scalar_vector &v):\n            size_ (v.size_), value_ (v.value_) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const { \n            return size_; \n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size) {\n            size_ = size;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            return value_; \n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const { \n            return value_; \n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        scalar_vector &operator = (const scalar_vector &v) {\n            BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n            size_ = v.size_;\n            value_ = v.value_;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        scalar_vector &assign_temporary (scalar_vector &v) { \n            swap (v);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (scalar_vector &v) {\n            // Too unusual semantic.\n            // BOOST_UBLAS_CHECK (this != &v, external_logic ());\n            if (this != &v) {\n                // Precondition for container relaxed as requested during review.\n                // BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n                std::swap (size_, v.size_);\n                std::swap (value_, v.value_);\n            }\n        }\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\n        BOOST_UBLAS_INLINE\n        friend void swap (scalar_vector &v1, scalar_vector &v2) {\n            v1.swap (v2);\n        }\n#endif\n\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> iterator;\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\n#else\n        class const_iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n            return const_iterator (*this, i);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_first (size_type i) const {\n            return find (i);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_last (size_type i) const {\n            return find (i);\n        }\n\n        // Iterators simply are pointers.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<scalar_vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef dense_random_access_iterator_tag iterator_category;\n#ifdef BOOST_MSVC_STD_ITERATOR\n            typedef const_reference reference;\n#else\n            typedef typename scalar_vector::difference_type difference_type;\n            typedef typename scalar_vector::value_type value_type;\n            typedef typename scalar_vector::const_reference reference;\n            typedef typename scalar_vector::const_pointer pointer;\n#endif\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<scalar_vector> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const scalar_vector &v, const const_iterator_type &it):\n                container_const_reference<scalar_vector> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\n                return (*this) () (index ());\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                return it_;\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<scalar_vector>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_iterator_type it_;\n        };\n\n        typedef const_iterator iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find_first (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find_first (size_);\n        }\n\n        // Reverse iterator\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\n#else\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n    private:\n        size_type size_;\n        value_type value_;\n    };\n\n    // Array based vector class \n    template<class T, std::size_t N>\n    class c_vector:\n        public vector_expression<c_vector<T, N> > {\n    public:\n#ifndef BOOST_UBLAS_NO_PROXY_SHORTCUTS\n        BOOST_UBLAS_USING vector_expression<c_vector<T, N> >::operator ();\n#endif\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef T value_type;\n        // typedef const T &const_reference;\n        typedef typename type_traits<T>::const_reference const_reference;\n        typedef T &reference;\n        typedef const T *const_pointer;\n        typedef T *pointer;\n        typedef const c_vector<T, N> const_self_type;\n        typedef c_vector<T, N> self_type;\n#ifndef BOOST_UBLAS_CT_REFERENCE_BASE_TYPEDEFS\n        typedef const vector_const_reference<const_self_type> const_closure_type;\n#else\n        typedef const vector_reference<const_self_type> const_closure_type;\n#endif\n        typedef vector_reference<self_type> closure_type;\n        typedef const T *const_iterator_type;\n        typedef T *iterator_type;\n        typedef dense_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        c_vector ():\n            size_ (N) /* , data_ () */ {}\n        BOOST_UBLAS_EXPLICIT BOOST_UBLAS_INLINE\n        c_vector (size_type size):\n            size_ (size) /* , data_ () */ {\n            if (size_ > N) \n                // Raising exceptions abstracted as requested during review.\n                // throw std::bad_alloc ();\n                bad_size ().raise ();\n        }\n        BOOST_UBLAS_INLINE\n        c_vector (const c_vector &v): \n            size_ (v.size_) /* , data_ () */ {\n            if (size_ > N) \n                // Raising exceptions abstracted as requested during review.\n                // throw std::bad_alloc ();\n                bad_size ().raise ();\n            *this = v;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector (const vector_expression<AE> &ae):\n            size_ (ae ().size ()) /* , data_ () */ {\n            if (size_ > N)\n                // Raising exceptions abstracted as requested during review.\n                // throw std::bad_alloc ();\n                bad_size ().raise ();\n            vector_assign (scalar_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n        }\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const { \n            return size_; \n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size) {\n            if (size > N) \n                // Raising exceptions abstracted as requested during review.\n                // throw std::bad_alloc ();\n                bad_size ().raise ();\n            // The content of the array is intentionally not copied.\n            size_ = size;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            BOOST_UBLAS_CHECK (i < size_,  bad_index ());\n            return data_ [i]; \n        }\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i) {\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\n            return data_ [i]; \n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const { \n            return (*this) (i); \n        }\n        BOOST_UBLAS_INLINE\n        reference operator [] (size_type i) { \n            return (*this) (i); \n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        c_vector &operator = (const c_vector &v) { \n            BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n            size_ = v.size_;\n            std::copy (v.data_, v.data_ + v.size_, data_);\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        c_vector &assign_temporary (c_vector &v) {\n            swap (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &operator = (const vector_expression<AE> &ae) {\n#ifdef BOOST_UBLAS_MUTABLE_TEMPORARY\n            return assign_temporary (self_type (ae));\n#else\n            // return assign (self_type (ae));\n            self_type temporary (ae);\n            return assign_temporary (temporary);\n#endif\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &reset (const vector_expression<AE> &ae) {\n            self_type temporary (ae);\n            resize (temporary.size ());\n            return assign_temporary (temporary);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &assign (const vector_expression<AE> &ae) {\n            vector_assign (scalar_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &operator += (const vector_expression<AE> &ae) {\n#ifdef BOOST_UBLAS_MUTABLE_TEMPORARY\n            return assign_temporary (self_type (*this + ae));\n#else\n            // return assign (self_type (*this + ae));\n            self_type temporary (*this + ae);\n            return assign_temporary (temporary);\n#endif\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &plus_assign (const vector_expression<AE> &ae) {\n            vector_assign (scalar_plus_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &operator -= (const vector_expression<AE> &ae) {\n#ifdef BOOST_UBLAS_MUTABLE_TEMPORARY\n            return assign_temporary (self_type (*this - ae));\n#else\n            // return assign (self_type (*this - ae));\n            self_type temporary (*this - ae);\n            return assign_temporary (temporary);\n#endif\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &minus_assign (const vector_expression<AE> &ae) {\n            vector_assign (scalar_minus_assign<value_type, BOOST_UBLAS_TYPENAME AE::value_type> (), *this, ae);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        c_vector &operator *= (const AT &at) {\n            vector_assign_scalar (scalar_multiplies_assign<value_type, AT> (), *this, at);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        c_vector &operator /= (const AT &at) {\n            vector_assign_scalar (scalar_divides_assign<value_type, AT> (), *this, at);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (c_vector &v) {\n            // Too unusual semantic.\n            // BOOST_UBLAS_CHECK (this != &v, external_logic ());\n            if (this != &v) {\n                BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n                std::swap (size_, v.size_);\n                std::swap_ranges (data_, data_ + size_, v.data_);\n            }\n        }\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\n        BOOST_UBLAS_INLINE\n        friend void swap (c_vector &v1, c_vector &v2) {\n            v1.swap (v2);\n        }\n#endif\n\n        // Element insertion and erasure\n        BOOST_UBLAS_INLINE\n        void insert (size_type i, const_reference t) {\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\n            BOOST_UBLAS_CHECK (data_ [i] == value_type (), bad_index ());\n            data_ [i] = t;\n        }\n        BOOST_UBLAS_INLINE\n        void erase (size_type i) {\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\n            data_ [i] = value_type ();\n        }\n        BOOST_UBLAS_INLINE\n        void clear () {\n            std::fill (data_, data_ + size_, value_type ());\n        }\n\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_iterator<self_type, dense_random_access_iterator_tag> iterator;\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\n#else\n        class const_iterator;\n        class iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator (*this, &data_ [i]);\n#else\n            return const_iterator (*this, i);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        iterator find (size_type i) {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return iterator (*this, &data_ [i]);\n#else\n            return iterator (*this, i);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_first (size_type i) const {\n            return find (i);\n        }\n        BOOST_UBLAS_INLINE\n        iterator find_first (size_type i) {\n            return find (i);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator find_last (size_type i) const {\n            return find (i);\n        }\n        BOOST_UBLAS_INLINE\n        iterator find_last (size_type i) {\n            return find (i);\n        }\n\n        // Iterators simply are pointers.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<c_vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef dense_random_access_iterator_tag iterator_category;\n#ifdef BOOST_MSVC_STD_ITERATOR\n            typedef const_reference reference;\n#else\n            typedef typename c_vector::difference_type difference_type;\n            typedef typename c_vector::value_type value_type;\n            typedef typename c_vector::const_reference reference;\n            typedef typename c_vector::const_pointer pointer;\n#endif\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &v, const const_iterator_type &it):\n                container_const_reference<self_type> (v), it_ (it) {}\n            BOOST_UBLAS_INLINE\n#ifndef BOOST_UBLAS_QUALIFIED_TYPENAME\n            const_iterator (const iterator &it):\n#else\n            const_iterator (const typename self_type::iterator &it):\n#endif\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\n                return *it_;\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                const self_type &v = (*this) ();\n                return it_ - v.begin ().it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_iterator_type it_;\n\n            friend class iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find_first (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find_first (size_);\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class iterator:\n            public container_reference<c_vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               iterator, value_type> {\n        public:\n            typedef dense_random_access_iterator_tag iterator_category;\n#ifndef BOOST_MSVC_STD_ITERATOR\n            typedef typename c_vector::difference_type difference_type;\n            typedef typename c_vector::value_type value_type;\n            typedef typename c_vector::reference reference;\n            typedef typename c_vector::pointer pointer;\n#endif\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            iterator ():\n                container_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            iterator (self_type &v, const iterator_type &it):\n                container_reference<self_type> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ());\n                return *it_;\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                self_type &v = (*this) ();\n                return it_ - v.begin ().it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            iterator &operator = (const iterator &it) {\n                container_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            iterator_type it_;\n\n            friend class const_iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        iterator begin () {\n            return find_first (0);\n        }\n        BOOST_UBLAS_INLINE\n        iterator end () {\n            return find_first (size_);\n        }\n\n        // Reverse iterator\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef reverse_iterator_base<const_iterator, value_type, const_reference> const_reverse_iterator;\n#else\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef reverse_iterator_base<iterator, value_type, reference> reverse_iterator;\n#else\n        typedef reverse_iterator_base<iterator> reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator rbegin () {\n            return reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rend () {\n            return reverse_iterator (begin ());\n        }\n\n    private:\n        size_type size_;\n        value_type data_ [N];\n    };\n\n}}}\n\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ad7ebd2161d6c3c01be51ca1a1e32f3627ebd81c", "size": 57117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rd party/boost/boost/numeric/ublas/vector.hpp", "max_stars_repo_name": "OLR-xray/OLR-3.0", "max_stars_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "src/3rd party/boost/boost/numeric/ublas/vector.hpp", "max_issues_repo_name": "OLR-xray/OLR-3.0", "max_issues_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/3rd party/boost/boost/numeric/ublas/vector.hpp", "max_forks_repo_name": "OLR-xray/OLR-3.0", "max_forks_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 32.6943331425, "max_line_length": 111, "alphanum_fraction": 0.5664688271, "num_tokens": 11873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.04023794708347558, "lm_q1q2_score": 0.01608759964344542}}
{"text": "// exact C++ implementation of lowe's sift program\n// Copyright (C) zerofrog(@gmail.com), 2008-2009\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 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//Lesser GNU 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#define BOOST_ENABLE_ASSERT_HANDLER\n\n#include <vector>\n\n#define PY_ARRAY_UNIQUE_SYMBOL PyArrayHandle\n#include <boost/python.hpp>\n#include <boost/python/exception_translator.hpp>\n#include <pyconfig.h>\n#include <numpy/arrayobject.h>\n\n#include <boost/format.hpp>\n\n#include \"siftfast.h\"\n\n#define CHECK_POINTER(p) { \\\n    if( (p) == NULL ) throw siftfast_exception(\"invalid pointer\"); \\\n}\n\nusing namespace boost::python;\nusing namespace std;\n\nextern int DoubleImSize;\nextern int Scales;\nextern float InitSigma;\nextern float PeakThresh;\n\nstruct siftfast_exception : std::exception\n{\n    siftfast_exception() : std::exception(), _s(\"unknown exception\") {}\n    siftfast_exception(const string& s) : std::exception() { _s = \"siftfast: \" + s; }\n    virtual ~siftfast_exception() noexcept {}\n    char const* what() noexcept const { return _s.c_str(); }\n    string _s;\n};\n\n#if defined(BOOST_ENABLE_ASSERT_HANDLER)\nnamespace boost\n{\ninline void assertion_failed(char const * expr, char const * function, char const * file, long line)\n{\n    throw siftfast_exception(str(boost::format(\"[%s:%d] -> %s, expr: %s\")%file%line%function%expr));\n}\n}\n#endif\n\nvoid translate_siftfast_exception(siftfast_exception const& e)\n{\n    // Use the Python 'C' API to set up an exception object\n    PyErr_SetString(PyExc_RuntimeError, e.what());\n}\n\ninline object toPyArrayN(const float* pvalues, int N)\n{\n    npy_intp dims[] = {N};\n    PyObject *pyvalues = PyArray_SimpleNew(1,dims, PyArray_FLOAT);\n    if( pvalues != NULL )\n        memcpy(PyArray_DATA(pyvalues),pvalues,N*sizeof(float));\n    return static_cast<numeric::array>(handle<>(pyvalues));\n}\n\ntemplate <typename T>\ninline vector<T> ExtractArray(object o)\n{\n    vector<T> v(len(o));\n    for(size_t i = 0; i < v.size(); ++i)\n        v[i] = extract<T>(o[i]);\n    return v;\n}\n\ninline vector<float> ExtractFloatArray(object oraw)\n{\n    object o = oraw.attr(\"flat\");\n\n    // check the types of o\n    extract<float> xr(o[0]);\n    if( xr.check() )\n        return ExtractArray<float>(o);\n\n    vector<float> v(len(o));\n    object onew = ((numeric::array)oraw).astype(\"f8\").attr(\"flat\");\n    for(size_t i = 0; i < v.size(); ++i)\n        v[i] = (float)(extract<double>(onew[i]));\n    return v;\n}\n\nclass PyImage\n{\npublic:\n    PyImage(int width, int height) : width(width), height(height)\n    {\n        BOOST_ASSERT(width>0&&height>0);\n        stride = (width+3)&~3;\n        vimage.resize(height*stride);\n    }\n    PyImage(object oimage)\n    {\n        object shape = oimage.attr(\"shape\");\n        BOOST_ASSERT(len(shape)==2);\n        width = extract<int>(shape[1]);\n        height = extract<int>(shape[0]);\n        stride = (width+3)&~3;\n        vimage.resize(height*stride);\n        SetData(oimage);\n    }\n\n    void SetData(object arr)\n    {\n        object shape = arr.attr(\"shape\");\n        if( len(shape) != 2 )\n            throw siftfast_exception(\"array needs 2 dimensions\");\n        if( height != extract<int>(shape[0]) )\n            throw siftfast_exception(\"array rows do not match height\");\n        if( width != extract<int>(shape[1]) )\n            throw siftfast_exception(\"array columns do not match width\");\n\n        string dtype = extract<string>(arr.attr(\"dtype\").attr(\"name\"));\n        if( (dtype.size() >= 3 && dtype[0] == 'i' && dtype[1] == 'n' && dtype[2] == 't') ||\n            (dtype.size() >= 4 && dtype[1] == 'i' && dtype[2] == 'n' && dtype[3] == 't') ) {\n            extract<int> xi(arr[0][0]);\n            if( xi.check() ) {\n                for(int i = 0; i < height; ++i)\n                    for(int j = 0; j < width; ++j)\n                        vimage[i*stride+j] = extract<int>(arr[i][j])*(1.0f/255.0f);\n                return;\n            }\n        }\n\n        extract<float> xr(arr[0][0]);\n        if( xr.check() ) {\n            for(int i = 0; i < height; ++i)\n                for(int j = 0; j < width; ++j)\n                    vimage[i*stride+j] = extract<float>(arr[i][j]);\n            return;\n        }\n        extract<double> xd(arr[0][0]);\n        if( xd.check() ) {\n            for(int i = 0; i < height; ++i)\n                for(int j = 0; j < width; ++j)\n                    vimage[i*stride+j] = extract<double>(arr[i][j]);\n            return;\n        }\n\n        throw siftfast_exception(\"array not in correct format\");\n    }\n\n    int width,height,stride;\n    vector<float> vimage;\n};\n\nclass Image_pickle_suite : public pickle_suite\n{\npublic:\n    static tuple getinitargs(const PyImage& im)\n    {\n        return make_tuple(im.width,im.height,im.stride,toPyArrayN(&im.vimage[0],im.vimage.size()));\n    }\n};\n\nobject PyGetKeypoints(PyImage& im)\n{\n    struct ImageSt siftimage;\n    siftimage.rows = im.height;\n    siftimage.cols = im.width;\n    siftimage.pixels = &im.vimage[0];\n    siftimage.stride = im.stride;\n    \n    Keypoint keypts = GetKeypoints(&siftimage);\n\n    int numkeys = 0;\n    Keypoint key = keypts;\n    while(key) {\n        numkeys++;\n        key = key->next;\n    }\n\n    npy_intp dims[2] = {numkeys,4};\n    PyObject *pyframes = PyArray_SimpleNew(2,dims, PyArray_FLOAT);\n    float* pframes = (float*)PyArray_DATA(pyframes);\n    \n    dims[1] = 128;\n    PyObject *pydesc = PyArray_SimpleNew(2,dims, PyArray_FLOAT);\n    float* pdesc = (float*)PyArray_DATA(pydesc);\n\n    int index = 0;\n    key = keypts;\n    while(key) {\n\n        for(int j = 0; j < 128; ++j)\n            pdesc[128*index+j] = key->descrip[j];\n\n        pframes[4*index+0] = key->col;\n        pframes[4*index+1] = key->row;\n        pframes[4*index+2] = key->ori;\n        pframes[4*index+3] = key->scale;\n\n        key = key->next;\n        ++index;\n    }\n\n    FreeKeypoints(keypts);\n    DestroyAllImages();\n\n    return make_tuple(static_cast<numeric::array>(handle<>(pyframes)),static_cast<numeric::array>(handle<>(pydesc)));\n}\n\nobject PyGetKeypoints(numeric::array oarray)\n{\n    PyImage pimage(oarray);\n    return PyGetKeypoints(pimage);\n}\n\nstruct DummyStruct {};\n\nstruct int_from_int\n{\n    int_from_int()\n    {\n        converter::registry::push_back(&convertible, &construct, type_id<int>());\n    }\n\n    static void* convertible( PyObject* obj)\n    {\n        PyObject* newobj = PyNumber_Int(obj);\n        if (!PyString_Check(obj) && newobj) {\n            Py_DECREF(newobj);\n            return obj;\n        }\n        else {\n            if (newobj) {\n                Py_DECREF(newobj);\n            }\n            PyErr_Clear();\n            return 0;\n        }\n    }\n\n    static void construct(PyObject* _obj, converter::rvalue_from_python_stage1_data* data)\n    {\n        PyObject* newobj = PyNumber_Int(_obj);\n        int* storage = (int*)((converter::rvalue_from_python_storage<int>*)data)->storage.bytes;\n        *storage = extract<int>(newobj);\n        Py_DECREF(newobj);\n        data->convertible = storage;\n    }\n};\n\ntemplate<typename T>\nstruct T_from_number\n{\n    T_from_number()\n    {\n        converter::registry::push_back(&convertible, &construct, type_id<T>());\n    }\n\n    static void* convertible( PyObject* obj)\n    {\n        PyObject* newobj = PyNumber_Float(obj);\n        if (!PyString_Check(obj) && newobj) {\n            Py_DECREF(newobj);\n            return obj;\n        }\n        else {\n            if (newobj) {\n                Py_DECREF(newobj);\n            }\n            PyErr_Clear();\n            return 0;\n        }\n    }\n\n    static void construct(PyObject* _obj, converter::rvalue_from_python_stage1_data* data)\n    {\n        PyObject* newobj = PyNumber_Float(_obj);\n        T* storage = (T*)((converter::rvalue_from_python_storage<T>*)data)->storage.bytes;\n        *storage = extract<T>(newobj);\n        Py_DECREF(newobj);\n        data->convertible = storage;\n    }\n};\n\nint GetDoubleImSize() { return DoubleImSize; }\nvoid SetDoubleImSize(int i) { DoubleImSize = i; }\nint GetScales() { return Scales; }\nvoid SetScales(int i) { Scales = i; }\nfloat GetInitSigma() { return InitSigma; }\nvoid SetInitSigma(float f) { InitSigma = f; }\nfloat GetPeakThresh() { return PeakThresh; }\nvoid SetPeakThresh(float f) { PeakThresh = f; }\n\nBOOST_PYTHON_MODULE(siftfastpy)\n{\n    import_array();\n    numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n    register_exception_translator<siftfast_exception>(&translate_siftfast_exception);\n    int_from_int();\n    T_from_number<float>();\n    T_from_number<double>();\n\n    def(\"DestroyAllResources\",DestroyAllResources);\n    object (*pkeypoints1)(PyImage&) = PyGetKeypoints;\n    object (*pkeypoints2)(numeric::array) = PyGetKeypoints;\n    def(\"GetKeypoints\",pkeypoints1,args(\"image\"));\n    def(\"GetKeypoints\",pkeypoints2,args(\"array\"));\n\n    class_<PyImage>(\"Image\", no_init)\n        .def(init<int,int>())\n        .def(init<object>())\n        .def_readonly(\"width\",&PyImage::width)\n        .def_readonly(\"height\",&PyImage::height)\n        .def(\"SetData\",&PyImage::SetData,args(\"array\"))\n        .def_pickle(Image_pickle_suite())\n        ;\n\n    {\n        scope options = class_<DummyStruct>(\"options\")\n            .add_property(\"DoubleImSize\",GetDoubleImSize,SetDoubleImSize)\n            .add_property(\"Scales\",GetScales,SetScales)\n            .add_property(\"InitSigma\",GetInitSigma,SetInitSigma)\n            .add_property(\"PeakThresh\",GetPeakThresh,SetPeakThresh)\n            ;\n    }\n}\n", "meta": {"hexsha": "b1533f750f55ca39d0ab1864546c089467889c4f", "size": 9924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ThirdParty/SiftFast/src/otbsiftfast/siftfastpy.cpp", "max_stars_repo_name": "heralex/OTB", "max_stars_repo_head_hexsha": "c52b504b64dc89c8fe9cac8af39b8067ca2c3a57", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 317.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T08:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:55:48.000Z", "max_issues_repo_path": "Modules/ThirdParty/SiftFast/src/otbsiftfast/siftfastpy.cpp", "max_issues_repo_name": "guandd/OTB", "max_issues_repo_head_hexsha": "707ce4c6bb4c7186e3b102b2b00493a5050872cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2015-07-29T14:13:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-29T12:36:24.000Z", "max_forks_repo_path": "Modules/ThirdParty/SiftFast/src/otbsiftfast/siftfastpy.cpp", "max_forks_repo_name": "guandd/OTB", "max_forks_repo_head_hexsha": "707ce4c6bb4c7186e3b102b2b00493a5050872cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 132.0, "max_forks_repo_forks_event_min_datetime": "2015-02-21T23:57:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T16:03:16.000Z", "avg_line_length": 29.3609467456, "max_line_length": 117, "alphanum_fraction": 0.6097339782, "num_tokens": 2603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.04023794132881817, "lm_q1q2_score": 0.016087597342666404}}
{"text": "//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <list>\n\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/thread.hpp>\n\n#include <parmcb/parmcb.hpp>\n#include <parmcb/util.hpp>\n\nusing namespace boost;\nnamespace po = boost::program_options;\n\n#define USAGE \"Computes the minimum cycle basis of a weighted undirected graph given in DIMACS format.\"\n\nint main(int argc, char *argv[]) {\n\n    po::variables_map vm;\n    try {\n        po::options_description desc(USAGE);\n        // @formatter:off\n        desc.add_options()\n                (\"help,h\", \"Help\")\n                (\"verbose,v\", po::value<bool>()->default_value(false)->implicit_value(true), \"Verbose\")\n                (\"signed\", po::value<bool>()->default_value(true), \"Use the signed graph algorithm\")\n                (\"fvstrees\", po::value<bool>()->default_value(false), \"Use cycles collection from feedback vertex set trees\")\n                (\"isotrees\", po::value<bool>()->default_value(false), \"Use isometric cycles collection\")\n                (\"parallel,p\", po::value<bool>()->default_value(true), \"Use parallelization\")\n                (\"printcycles\", po::value<bool>()->default_value(false)->implicit_value(true), \"Print cycles\")\n                (\"cores\", po::value<int>()->default_value(0), \"Number of cores\")\n                (\"input-file,I\",po::value<std::string>(), \"Input filename\");\n        // @formatter:on\n        po::positional_options_description pos_desc;\n        pos_desc.add(\"input-file\", 1);\n        po::command_line_parser parser { argc, argv };\n        parser.options(desc).positional(pos_desc).allow_unregistered();\n        po::parsed_options parsed_options = parser.run();\n        po::store(parsed_options, vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << desc << std::endl;\n            return EXIT_SUCCESS;\n        }\n        po::notify(vm);\n\n        if (!vm.count(\"input-file\")) {\n            std::cerr << \"Input file missing. See usage by calling with -h .\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n\n    } catch (const po::error &ex) {\n        std::cerr << \"Invalid arguments:\" << ex.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    typedef adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_weight_t, double> > graph_t;\n    typedef graph_traits<graph_t>::edge_descriptor edge_descriptor;\n\n    // create graph\n    graph_t graph;\n    FILE *fp = fopen(vm[\"input-file\"].as<std::string>().c_str(), \"r\");\n    if (fp == NULL) {\n        std::cerr << \"Failed to open input file.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    parmcb::read_dimacs_from_file(fp, graph);\n    fclose(fp);\n\n    if (parmcb::has_loops(graph)) {\n        std::cerr << \"Graph has loops, aborting..\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    if (parmcb::has_multiple_edges(graph)) {\n        std::cerr << \"Graph has multiple edges, aborting..\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    if (parmcb::has_non_positive_weights(graph, get(boost::edge_weight, graph))) {\n        std::cerr << \"Graph has negative or zero weight edges, aborting..\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    std::cout << \"Graph has \" << num_vertices(graph) << \" vertices\" << std::endl;\n    std::cout << \"Graph has \" << num_edges(graph) << \" edges\" << std::endl;\n    std::cout << std::flush;\n\n    std::size_t cores = 0;\n    if (vm.count(\"cores\")) {\n        cores = vm[\"cores\"].as<int>();\n    }\n    if (cores == 0) {\n        cores = boost::thread::hardware_concurrency();\n    }\n    if (vm[\"verbose\"].as<bool>() && vm[\"parallel\"].as<bool>()) {\n        std::cout << \"Using cores: \" << cores << std::endl;\n    }\n\n    boost::timer::cpu_timer timer;\n\n    std::list<std::list<edge_descriptor>> cycles;\n    double mcb_weight;\n    if (vm[\"signed\"].as<bool>()) {\n        if (vm[\"parallel\"].as<bool>()) {\n            std::cout << \"Using PAR_MCB_SVA_SIGNED\" << std::endl;\n            mcb_weight = parmcb::mcb_sva_signed_tbb(graph, get(boost::edge_weight, graph), std::back_inserter(cycles),\n                    cores);\n        } else {\n            std::cout << \"Using MCB_SVA_SIGNED\" << std::endl;\n            mcb_weight = parmcb::mcb_sva_signed(graph, get(boost::edge_weight, graph), std::back_inserter(cycles));\n        }\n    } else if (vm[\"fvstrees\"].as<bool>()) {\n        if (vm[\"parallel\"].as<bool>()) {\n            std::cout << \"Using PAR_MCB_SVA_FVS_TREES\" << std::endl;\n            mcb_weight = parmcb::mcb_sva_fvs_trees_tbb(graph, get(boost::edge_weight, graph), std::back_inserter(cycles));\n        } else {\n            std::cout << \"Using MCB_SVA_FVS_TREES\" << std::endl;\n            mcb_weight = parmcb::mcb_sva_fvs_trees(graph, get(boost::edge_weight, graph), std::back_inserter(cycles));\n        }\n    } else {\n        if (vm[\"parallel\"].as<bool>()) {\n            std::cout << \"Using PAR_MCB_SVA_ISO_TREES\" << std::endl;\n            mcb_weight = parmcb::mcb_sva_iso_trees_tbb(graph, get(boost::edge_weight, graph), std::back_inserter(cycles));\n        } else {\n            std::cout << \"Using MCB_SVA_ISO_TREES\" << std::endl;\n            mcb_weight = parmcb::mcb_sva_iso_trees(graph, get(boost::edge_weight, graph), std::back_inserter(cycles));\n        }\n    }\n\n    timer.stop();\n\n    std::cout << \"MCB weight = \" << mcb_weight << std::endl;\n\n    if (vm[\"printcycles\"].as<bool>()) {\n        std::cout << \"MCB cycles\" << std::endl;\n        for (auto it = cycles.begin(); it != cycles.end(); it++) {\n            auto cycle = *it;\n\n            for (auto eit = cycle.begin(); eit != cycle.end(); eit++) {\n                std::cout << *eit << \" \";\n            }\n            std::cout << std::endl;\n\n            assert(parmcb::is_cycle(graph, cycle));\n        }\n    }\n\n    if (vm[\"verbose\"].as<bool>()) {\n        std::cout << \"time:\" << timer.format();\n    }\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "73db6d108bb58d92931cefd99207035ff712e6f9", "size": 6225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mcb-dimacs.cpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mcb-dimacs.cpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mcb-dimacs.cpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9573170732, "max_line_length": 125, "alphanum_fraction": 0.5876305221, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.04468086613833535, "lm_q1q2_score": 0.016056701877938926}}
{"text": "#define BIORBD_API_EXPORTS\n#include \"Utils/Equation.h\"\n\n#include <boost/lexical_cast.hpp>\n#include \"Utils/Error.h\"\n\nstd::vector<biorbd::utils::Equation> biorbd::utils::Equation::prepareMathSymbols(){\n    // Classés en ordre de priorité des opérations\n    std::vector<biorbd::utils::Equation> symbols;\n    symbols.push_back(\"(\");\n    symbols.push_back(\")\");\n    symbols.push_back(\"e\");\n    symbols.push_back(\"/\");\n    symbols.push_back(\"*\");\n    symbols.push_back(\"+\");\n    symbols.push_back(\"-\");\n\n    return symbols;\n}\n\nbiorbd::utils::Equation::Equation() :\n    biorbd::utils::String(\"\")\n{\n\n}\n\nbiorbd::utils::Equation::Equation(const char *c) :\n    biorbd::utils::String(c)\n{\n\n}\n\nbiorbd::utils::Equation::Equation(const biorbd::utils::String &s) :\n    biorbd::utils::String(s)\n{\n\n}\n\nbiorbd::utils::Equation::Equation(const std::basic_string<char> &c) :\n    biorbd::utils::String(c)\n{\n\n}\n\nstd::vector<biorbd::utils::Equation> biorbd::utils::Equation::splitIntoEquation(\n        biorbd::utils::Equation wholeEq,\n        const std::map<biorbd::utils::Equation, double>& variables)\n{\n    // variable de sortie\n    std::vector<biorbd::utils::Equation> eq;\n\n    // Remplacer les variables par un nombre\n    replaceVar(wholeEq, variables);\n\n    // Déclaration des marqueurs arithmétiques\n    const std::vector<biorbd::utils::Equation>& symbols(prepareMathSymbols());\n\n    // Sur tout le long du string\n    while (1){\n        int firstIdx(static_cast<int>(wholeEq.size())+1);// Mettre un index trop grand\n        unsigned int toStop(0); // Mettre stop a 0\n        // Balayer chaque symbols pour voir s'ils se trouvent dans l'equation\n        for (unsigned int i=0; i<symbols.size(); ++i){\n            int idx = static_cast<int>(wholeEq.find(symbols[i]));\n            if (idx < 0){ // Si non, le noter\n                ++toStop;\n                continue;\n            }\n            if (idx < firstIdx && idx != -1) // si oui, regarder s'il est avant un autre symbol\n                firstIdx = idx;\n        }\n        if (toStop == symbols.size()){ // S'il ne reste aucun symbole, sortir du while\n            eq.push_back(wholeEq);\n            break;\n        }\n        if (wholeEq.size() == 1){\n            eq.push_back(wholeEq(0));\n            break;\n        }\n        if (firstIdx+1 == static_cast<int>(wholeEq.size())){\n            eq.push_back(wholeEq.substr(0,static_cast<unsigned int>(firstIdx)));\n            eq.push_back(wholeEq(static_cast<unsigned int>(firstIdx)));\n            break;\n        }\n        else if (firstIdx == 0){\n            if (!wholeEq(0).compare(\"-\")){\n                // Si l'équation commencer par un \"-\"\n                std::vector<biorbd::utils::Equation> tp(splitIntoEquation(wholeEq.substr(1), variables));\n                if (eq.size() != 0 && !eq[eq.size()-1].compare(\"e\") ){\n                    // special case of scientific notation (1e-x)\n                    eq.push_back(wholeEq(0));\n                    wholeEq = wholeEq.substr(1);\n                } else if (!tp[0].compare(\"(\")) {\n                    // Resolve now the parenthese to apply the minus after\n                    size_t idx = wholeEq.find_first_of(\")\");\n                    biorbd::utils::Equation newWholeEq(wholeEq.substr(2, idx-2));\n                    double res(-1*resolveEquation(splitIntoEquation(newWholeEq, variables)));\n                    wholeEq = std::to_string(res) + wholeEq.substr(idx+1);\n                } else {\n                    tp[0] = \"-\" + tp[0];\n                    eq.insert(eq.end(), tp.begin(), tp.end());\n                    return eq;\n                }\n            }\n            else if (!wholeEq(0).compare(\"+\")){\n                // Si l'équation commencer par un +\n                std::vector<biorbd::utils::Equation> tp(splitIntoEquation(wholeEq.substr(1), variables));\n                if (eq.size() != 0) // S'il n'y a rien avant, est faux dans les cas 1ex\n                    eq.push_back(\"+\");\n                eq.insert(eq.end(), tp.begin(), tp.end());\n                return eq;\n            }\n            else{\n                eq.push_back(wholeEq(0));\n                wholeEq = wholeEq.substr(1);\n            }\n        }\n        else{\n            eq.push_back(wholeEq.substr(0,static_cast<unsigned int>(firstIdx))); // Prendre tout ce qui vient avant le symbole\n            eq.push_back(wholeEq(static_cast<unsigned int>(firstIdx))); // Récupérer le symbole\n            wholeEq = wholeEq.substr(static_cast<unsigned int>(firstIdx)+1); // Garder tout ce qu'il y a apres le symbole et recommencer\n        }\n\n    }\n\n    // Remplacer les constantes par un nombre\n    replaceCste(eq);\n\n    // Retourner l'équation\n    return eq;\n}\n\nvoid biorbd::utils::Equation::replaceCste(\n        std::vector<biorbd::utils::Equation> &eq)\n{\n    for (unsigned int i=0; i<eq.size(); ++i)\n        if (!eq[i].tolower().compare(\"pi\"))\n            eq[i] = boost::lexical_cast< std::string>(PI);\n}\n\nvoid biorbd::utils::Equation::replaceVar(\n        biorbd::utils::Equation &eq,\n        const std::map<biorbd::utils::Equation, double>& variables)\n{\n    for (auto var : variables)\n        while (eq.find(var.first) != std::string::npos){\n            size_t pos(eq.find(var.first));\n            size_t length(var.first.length());\n            eq = eq.substr(0, pos) + \"(\" +\n                    std::to_string(var.second) + \")\" +\n                    eq.substr(pos + length);\n        }\n}\n\n\ndouble biorbd::utils::Equation::resolveEquation(\n        std::vector<biorbd::utils::Equation> wholeEq)\n{\n    return resolveEquation(wholeEq,0);\n}\n\ndouble biorbd::utils::Equation::resolveEquation(\n        std::vector<biorbd::utils::Equation> eq,\n        unsigned int math)\n{\n    // Si on a traité tout\n    if (eq.size() == 1)\n        return boost::lexical_cast<double>(eq[0]);\n\n    // Déclaration des marqueurs arithmétiques\n    const std::vector<biorbd::utils::Equation>& symbols(prepareMathSymbols());\n    std::vector<biorbd::utils::Equation> eq2;\n    bool continuer(true);\n\n    for (unsigned int j=0; j<eq.size(); ++j){\n        if (!eq[j].compare(symbols[math]) && continuer){\n            if (j==0 && (!symbols[math].compare(\"+\") || !symbols[math].compare(\"-\"))){\n                // Écraser la valeur précédente\n                if (!symbols[math].compare(\"+\"))\n                    eq2[j-1] = boost::lexical_cast<std::string>(0.0 + boost::lexical_cast<double>(eq[j+1]));\n                else if (!symbols[math].compare(\"-\"))\n                    eq2[j-1] = boost::lexical_cast<std::string>(0.0 - boost::lexical_cast<double>(eq[j+1]));\n            }\n            else{\n                // Écraser la valeur précédente\n                if (!symbols[math].compare(\"(\")){\n                    std::vector<biorbd::utils::Equation> eq_tp;\n                    bool foundIdx(false);\n                    int cmpValues(0);\n                    unsigned int cmpOpen(0);\n                    for (unsigned int k=j+1; k<eq.size();++k){\n                        if (!eq[k].compare(\"(\"))\n                            cmpOpen++;\n                        else if (!eq[k].compare(\")\")){\n                            if (cmpOpen == 0){\n                                foundIdx = true;\n                                break;\n                            }\n                            else\n                                cmpOpen--;\n                        }\n\n                        eq_tp.push_back(eq[k]);\n                        ++cmpValues;\n                    }\n                    biorbd::utils::Error::check(foundIdx, \"You must close brackets!\");\n\n                    eq2.push_back(boost::lexical_cast<std::string>(boost::lexical_cast<std::string>(resolveEquation(eq_tp))));\n                    j+=static_cast<unsigned int>(cmpValues);\n                }\n                else if (!symbols[math].compare(\"/\"))\n                    eq2[j-1] = boost::lexical_cast<std::string>(boost::lexical_cast<double>(eq[j-1]) / boost::lexical_cast<double>(eq[j+1]));\n                else if (!symbols[math].compare(\"*\"))\n                    eq2[j-1] = boost::lexical_cast<std::string>(boost::lexical_cast<double>(eq[j-1]) * boost::lexical_cast<double>(eq[j+1]));\n                else if (!symbols[math].compare(\"+\"))\n                    eq2[j-1] = boost::lexical_cast<std::string>(boost::lexical_cast<double>(eq[j-1]) + boost::lexical_cast<double>(eq[j+1]));\n                else if (!symbols[math].compare(\"-\"))\n                    eq2[j-1] = boost::lexical_cast<std::string>(boost::lexical_cast<double>(eq[j-1]) - boost::lexical_cast<double>(eq[j+1]));\n                else if (!symbols[math].compare(\"e\")){\n                    if (!eq[j+1].compare(\"-\")){\n                        eq2[j-1] = boost::lexical_cast<std::string>(boost::lexical_cast<double>(eq[j-1]) * pow(10,-1*boost::lexical_cast<double>(eq[j+2])));\n                        ++j;\n                    }\n                    else if (!eq[j+1].compare(\"+\")){\n                        eq2[j-1] = boost::lexical_cast<std::string>(boost::lexical_cast<double>(eq[j-1]) * pow(10,boost::lexical_cast<double>(eq[j+2])));\n                        ++j;\n                    }\n                    else\n                        eq2[j-1] = boost::lexical_cast<std::string>(boost::lexical_cast<double>(eq[j-1]) * pow(10,boost::lexical_cast<double>(eq[j+1])));\n\n                }\n            }\n\n            j+=2;\n            continuer = false;\n        }\n        if (j<eq.size())\n            eq2.push_back(eq[j]);\n    }\n\n    if (continuer)\n        return resolveEquation(eq2, ++math);\n    else\n        return resolveEquation(eq2, math);\n}\n\ndouble biorbd::utils::Equation::resolveEquation(\n        biorbd::utils::Equation wholeEq,\n        const std::map<biorbd::utils::Equation, double>& variables)\n{\n    return resolveEquation(splitIntoEquation(wholeEq, variables));\n}\ndouble biorbd::utils::Equation::resolveEquation(\n        biorbd::utils::Equation wholeEq)\n{\n    std::map<biorbd::utils::Equation, double> dumb;\n    return resolveEquation(splitIntoEquation(wholeEq, dumb));\n}\n", "meta": {"hexsha": "12e8d6ce21460acdd716f03cfa7570b593322d6c", "size": 9965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Equation.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/Equation.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/Equation.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": 38.4749034749, "max_line_length": 156, "alphanum_fraction": 0.5294530858, "num_tokens": 2461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.03904829007029213, "lm_q1q2_score": 0.016053176472827634}}
{"text": "/* Copyright (C) 2019-2020 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 <ros/ros.h>\n\n/* Include standard libraries */\n#include <string>\n#include <boost/bind.hpp>\n#include <cmath>\n\n/* Include ROS libraries */\n#include <tf/transform_datatypes.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_listener.h>\n#include <tf/LinearMath/Quaternion.h>\n\n/* Include message types */\n#include \"std_msgs/String.h\"\n#include \"std_msgs/Float64.h\"\n#include \"geometry_msgs/Pose.h\"\n#include \"geometry_msgs/Twist.h\"\n#include \"geometry_msgs/Quaternion.h\"\n#include \"geometry_msgs/Vector3.h\"\n#include \"nav_msgs/Odometry.h\"\n#include \"ackermann_msgs/AckermannDrive.h\"\n\n/* Include generated Services */\n\n/* Include generated Message Types */\n#include <jetsoncar_msgs/Encoders.h>\n\n/* Include generated Dynamic Reconfigure parameters */\n\n// For CLion to update/capture the changes made to generated services, message types and parameters, open the \"build\" folder and run \"make\"\n\n\n/* This node Subscribes to the /encoders message and integrates that using the Bicycle model into\n * odometry messages (/odom) and odometry transformations (odom frame) */\n\n/* Global variables */\nstd::string tfPrefix;\ndouble min_steering = 0.003;\ndouble max_steering = 1.0;\ndouble min_omega = 0.01;\ndouble wheel_radius = 1;\ndouble front_to_rear_wheel_distance = 1;\ndouble left_to_right_wheel_distance = 1;\n\nros::Time prev_odometry_time(0);\ndouble prev_front_angle = 0;\ndouble prev_rear_angle = 0;\ndouble prev_steering_angle = 0;\ndouble x_prev = 0;\ndouble y_prev = 0;\ndouble theta_prev = 0;\n\nvoid PublishOdometry(double v, double rho, double dt, ros::Time time, tf::TransformBroadcaster& tfBroadcaster, ros::Publisher& pubOdom)\n{\n    // Use the Bicycle Kinematic model with the origin (position) defined in the center of mass\n    // which is assumed to be the midpoint between front and rear wheels (base_link frame)\n    // https://www.coursera.org/lecture/intro-self-driving-cars/lesson-2-the-kinematic-bicycle-model-Bi8yE\n    // https://borrelli.me.berkeley.edu/pdfpub/IV_KinematicMPC_jason.pdf\n    // dx = v * cos(theta + beta)\n    // dy = v * sin(theta + beta)\n    // dtheta = v * cos(beta) * tan(rho) / L\n    // beta = atan(l_r/L * tan(rho))\n    // Where\n    //   L   : distance between front to rear wheels\n    //   l_r : distance between rear wheels to center of mass (midpoint)\n    //   rho : steering angle\n    // l_r is assumed to be L/2\n\n    // To discretize this we assume the velocity and steering angle is constant during the discretization interval, dt\n    // In that case the Coordinated Turn Model can be used\n    // See Chapter 5.2.2 of http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.142.6137&rep=rep1&type=pdf\n    // x[k+1] = x[k] + 2*v[k]/omega[k] * sin(dt/2*omega[k]) * cos(theta[k] + beta[k] + dt/2*omega[k])\n    // y[k+1] = x[k] + 2*v[k]/omega[k] * sin(dt/2*omega[k]) * sin(theta[k] + beta[k] + dt/2*omega[k])\n    // theta[k+1] = theta[k] + dt*omega[k]\n    // Where\n    //    omega[k] = v[k] * cos(beta[k]) * tan(rho[k]) / L\n    // A different form can be found in equation 5.9 on page 101 of Probabilistic Robotics by Sebastian Thrun\n\n    double x = x_prev;\n    double y = y_prev;\n    double theta = theta_prev;\n    double omega = 0;\n    std::cout << \"v = \" << v << std::endl;\n\n    if (std::abs(rho) > min_steering) {\n        double beta = std::atan((front_to_rear_wheel_distance / 2) / front_to_rear_wheel_distance * std::tan(rho));\n        omega = v * std::cos(beta) * std::tan(rho) / front_to_rear_wheel_distance;\n\n        std::cout << \"rho = \" << rho << std::endl;\n        std::cout << \"beta = \" << beta << std::endl;\n        std::cout << \"omega = \" << omega << std::endl;\n\n        if (std::abs(omega) > min_omega) {\n            // Compute predicted odometry position\n            x += 2 * v / omega * std::sin(dt / 2 * omega) * std::cos(theta_prev + beta + dt / 2 * omega);\n            y += 2 * v / omega * std::sin(dt / 2 * omega) * std::sin(theta_prev + beta + dt / 2 * omega);\n            theta += dt * omega;\n        } else {\n            x += dt * cos(theta) * v;\n            y += dt * sin(theta) * v;\n        }\n    } else {\n        x += dt * cos(theta) * v;\n        y += dt * sin(theta) * v;\n    }\n\n    double dx_est, dy_est;\n    dx_est = (x - x_prev) / dt;\n    dy_est = (y - y_prev) / dt;\n\n    // Construct odometry transform and publish\n    tf::Transform odom_transform;\n    odom_transform.setOrigin(tf::Vector3(x, y, 0));\n    odom_transform.setRotation(tf::createQuaternionFromYaw(theta));\n    tfBroadcaster.sendTransform(tf::StampedTransform(odom_transform, time, \"odom\", \"footprint\"));\n\n    std::cout.precision(3);\n    std::cout.setf(std::ios::fixed,std::ios::floatfield);\n    std::cout << \"At time \" << time.toSec() << std::endl;\n    double yaw, pitch, roll;\n    odom_transform.getBasis().getRPY(roll, pitch, yaw);\n    tf::Quaternion q = odom_transform.getRotation();\n    tf::Vector3 tv = odom_transform.getOrigin();\n    std::cout << \"- Translation: [\" << tv.getX() << \", \" << tv.getY() << \", \" << tv.getZ() << \"]\" << std::endl;\n    std::cout << \"- Rotation: in Quaternion [\" << q.getX() << \", \" << q.getY() << \", \"\n              << q.getZ() << \", \" << q.getW() << \"]\" << std::endl\n              << \"            in RPY (radian) [\" <<  roll << \", \" << pitch << \", \" << yaw << \"]\" << std::endl\n              << \"            in RPY (degree) [\" <<  roll*180.0/M_PI << \", \" << pitch*180.0/M_PI << \", \" << yaw*180.0/M_PI << \"]\" << std::endl;\n\n    /* Send odometry message */\n    //   This represents an estimate of a position and velocity in free space.\n    //   The pose in this message should be specified in the coordinate frame given by header.frame_id\n    //   The twist in this message should be specified in the coordinate frame given by the child_frame_id\n    nav_msgs::Odometry odom_msg;\n    odom_msg.header.stamp = ros::Time::now();\n    odom_msg.header.frame_id = \"odom\";\n    odom_msg.child_frame_id = \"footprint\";\n    odom_msg.pose.pose.position.x = x; // inertial frame position\n    odom_msg.pose.pose.position.y = y;\n    odom_msg.pose.pose.position.z = 0;\n    odom_msg.pose.pose.orientation.w = odom_transform.getRotation().w();\n    odom_msg.pose.pose.orientation.x = odom_transform.getRotation().x();\n    odom_msg.pose.pose.orientation.y = odom_transform.getRotation().y();\n    odom_msg.pose.pose.orientation.z = odom_transform.getRotation().z();\n    odom_msg.twist.twist.linear.x = v; // body frame velocity\n    odom_msg.twist.twist.linear.y = 0;\n    odom_msg.twist.twist.linear.z = 0;\n    odom_msg.twist.twist.angular.x = 0;\n    odom_msg.twist.twist.angular.y = 0;\n    odom_msg.twist.twist.angular.z = omega;\n\n    odom_msg.pose.covariance[0] = 0.001;\n    odom_msg.pose.covariance[7] = 0.001;\n    odom_msg.pose.covariance[14] = 1000000000000.0;\n    odom_msg.pose.covariance[21] = 1000000000000.0;\n    odom_msg.pose.covariance[28] = 1000000000000.0;\n\n    odom_msg.pose.covariance[35] = 0.01; // std::abs(angular_vel.z) < 0.0001\n    //odom_msg.pose.covariance[35] = 100.0;\n\n    odom_msg.twist.covariance[0] = 0.001;\n    odom_msg.twist.covariance[7] = 0.001;\n    odom_msg.twist.covariance[14] = 0.001;\n    odom_msg.twist.covariance[21] = 1000000000000.0;\n    odom_msg.twist.covariance[28] = 1000000000000.0;\n    odom_msg.twist.covariance[35] = 0.01; // std::abs(angular_vel.z) < 0.0001\n    //odom_msg.twist.covariance[35] = 100.0;\n\n    pubOdom.publish(odom_msg);\n\n    // Store updated states for next iteration\n    x_prev = x;\n    y_prev = y;\n    theta_prev = theta;\n}\n\n\n\nvoid ROS_Callback_encoders(const jetsoncar_msgs::Encoders::ConstPtr& msg, tf::TransformBroadcaster& tfBroadcaster, ros::Publisher& pubOdom)\n{\n    auto time_diff = msg->receive_time - prev_odometry_time;\n    double dt = time_diff.toSec();\n\n    if (dt > 0 && prev_odometry_time.toSec() != 0) {\n        // Since we want to use and integrate the encoder measurements, we will compute the instantaneous velocity by\n        // differentiating the encoder readings\n        double front_velocity = (msg->front_angle - prev_front_angle) / dt;\n        double rear_velocity = (msg->front_angle - prev_front_angle) / dt;\n        double wheel_velocity = (front_velocity + rear_velocity) / 2.0;\n\n        // Compute necessary variables\n        double v = wheel_radius * wheel_velocity; // translational velocity\n        double rho = msg->steering_angle;\n\n        PublishOdometry(v, rho, dt, msg->receive_time, tfBroadcaster, pubOdom);\n    }\n\n    prev_odometry_time = msg->receive_time;\n    prev_front_angle = msg->front_angle;\n    prev_rear_angle = msg->rear_angle;\n    prev_steering_angle = msg->steering_angle;\n}\n\nvoid ROS_Callback_cmd_ackermann(const ackermann_msgs::AckermannDrive::ConstPtr& msg, tf::TransformBroadcaster& tfBroadcaster, ros::Publisher& pubOdom)\n{\n    ros::Time current_time = ros::Time::now();\n\n    // Convert cmd_vel command into actuation commends sent to the Gazebo simulated wheel controllers\n    double speed = msg->speed;\n    double steering_angle = msg->steering_angle; // misuse of using this to capture the steering angle\n\n    auto time_diff = current_time - prev_odometry_time;\n    double dt = time_diff.toSec();\n\n    if (dt > 0 && prev_odometry_time.toSec() != 0) {\n        PublishOdometry(speed, steering_angle, dt, current_time, tfBroadcaster, pubOdom);\n    }\n\n    prev_odometry_time = current_time;\n}\n\nint main(int argc, char **argv) {\n\tstd::string nodeName = \"odometry_node\";\n\tros::init(argc, argv, nodeName.c_str());\n\tros::NodeHandle n; // default/current namespace node handle\n\tros::NodeHandle nParam(\"~\"); // default/current namespace node handle for parameters\n\n    tfPrefix = tf::getPrefixParam(n);\n\ttf::TransformBroadcaster tfBroadcaster;\n\n\tbool use_encoders = true;\n    if (!nParam.getParam(\"use_encoders\", use_encoders)) {\n        ROS_WARN_STREAM(\"Use encoders flag not set (Parameter: use_encoders). Defaults to: \" << use_encoders);\n    }\n\n    if (!nParam.getParam(\"wheel_radius\", wheel_radius)) {\n        ROS_WARN_STREAM(\"Wheel radius not set (Parameter: wheel_radius). Defaults to: \" << wheel_radius);\n    }\n    if (!nParam.getParam(\"front_to_rear_wheel_distance\", front_to_rear_wheel_distance)) {\n        ROS_WARN_STREAM(\"Wheel distance not set (Parameter: front_to_rear_wheel_distance). Defaults to: \" << front_to_rear_wheel_distance);\n    }\n    if (!nParam.getParam(\"left_to_right_wheel_distance\", left_to_right_wheel_distance)) {\n        ROS_WARN_STREAM(\"Wheel distance not set (Parameter: front_to_rear_wheel_distance). Defaults to: \" << left_to_right_wheel_distance);\n    }\n    if (!nParam.getParam(\"min_steering\", min_steering)) {\n        ROS_WARN_STREAM(\"Minimum steering angle not set (Parameter: min_steering). Defaults to: \" << min_steering);\n    }\n    if (!nParam.getParam(\"max_steering\", max_steering)) {\n        ROS_WARN_STREAM(\"Maximum steering angle not set (Parameter: max_steering). Defaults to: \" << max_steering);\n    }\n    if (!nParam.getParam(\"min_omega\", min_omega)) {\n        ROS_WARN_STREAM(\"Minimum angular velocity set (Parameter: min_omega). Defaults to: \" << min_omega);\n    }\n\n    /* Configure publishers */\n    ros::Publisher pub_odom = n.advertise<nav_msgs::Odometry>(\"odom\", 50);\n\n    /* Configure subscribers */\n    ros::Subscriber sub;\n    if (use_encoders)\n        sub = n.subscribe<jetsoncar_msgs::Encoders>(\"encoders\", 50, boost::bind(&ROS_Callback_encoders, _1, boost::ref(tfBroadcaster), boost::ref(pub_odom)));\n    else\n        sub = n.subscribe<ackermann_msgs::AckermannDrive>(\"cmd_ackermann\", 50, boost::bind(&ROS_Callback_cmd_ackermann, _1, boost::ref(tfBroadcaster), boost::ref(pub_odom)));\n\n    ros::spin();\n}", "meta": {"hexsha": "fd77cca80c11ffa670fefdb7d8ba9df445acb8a2", "size": 12195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jetsoncar_driver/src/odometry_node.cpp", "max_stars_repo_name": "mindThomas/JetsonCar-ROS", "max_stars_repo_head_hexsha": "eb171e9fd1515c6172f80daaa410e57d877d8639", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T21:52:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T12:24:52.000Z", "max_issues_repo_path": "jetsoncar_driver/src/odometry_node.cpp", "max_issues_repo_name": "mindThomas/JetsonCar-ROS", "max_issues_repo_head_hexsha": "eb171e9fd1515c6172f80daaa410e57d877d8639", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jetsoncar_driver/src/odometry_node.cpp", "max_forks_repo_name": "mindThomas/JetsonCar-ROS", "max_forks_repo_head_hexsha": "eb171e9fd1515c6172f80daaa410e57d877d8639", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-04T02:30:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-24T02:31:43.000Z", "avg_line_length": 42.7894736842, "max_line_length": 174, "alphanum_fraction": 0.6653546535, "num_tokens": 3298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.042087728966949636, "lm_q1q2_score": 0.016044665781486937}}
{"text": "/*\r\n *            Copyright 2009-2018 The VOTCA Development Team\r\n *                       (http://www.votca.org)\r\n *\r\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\r\n *\r\n * You may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *              http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\r\n */\r\n\r\n// Overload of uBLAS prod function with MKL/GSL implementations\r\n\r\n#include \"votca/xtp/aobasis.h\"\r\n#include \"votca/xtp/qminterface.h\"\r\n#include \"votca/xtp/qmatom.h\"\r\n#include <votca/xtp/dftengine.h>\r\n\r\n#include <boost/format.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <votca/xtp/aomatrix.h>\r\n#include <votca/xtp/orbitals.h>\r\n#include <votca/xtp/qmpackagefactory.h>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <votca/tools/constants.h>\r\n#include <votca/tools/elements.h>\r\n#include <votca/ctp/xinteractor.h>\r\n\r\n\r\n\r\nusing boost::format;\r\nusing namespace boost::filesystem;\r\nusing std::flush;\r\nusing namespace votca::tools;\r\n\r\nnamespace votca {\r\n  namespace xtp {\r\n\r\n\r\n    void DFTEngine::Initialize(Property& options) {\r\n\r\n      string key = \"package\";\r\n\r\n      _openmp_threads = options.ifExistsReturnElseReturnDefault<int>(key + \".threads\", 0);\r\n\r\n      _dftbasis_name = options.ifExistsReturnElseThrowRuntimeError<string>(key + \".dftbasis\");\r\n\r\n      if (options.exists(key + \".auxbasis\")) {\r\n        _auxbasis_name = options.get(key + \".auxbasis\").as<string>();\r\n        _with_RI = true;\r\n      } else {\r\n        _with_RI = false;\r\n      }\r\n\r\n      if (!_with_RI) {\r\n        std::vector<std::string> choices = {\"direct\", \"cache\"};\r\n        _four_center_method = options.ifExistsAndinListReturnElseThrowRuntimeError<std::string>(key + \".four_center_method\", choices);\r\n\r\n        _with_screening = options.ifExistsReturnElseReturnDefault<bool>(key + \".with_screening\", true);\r\n        _screening_eps = options.ifExistsReturnElseReturnDefault<double>(key + \".screening_eps\", 1e-9);\r\n      }\r\n\r\n      if (options.exists(key + \".ecp\")) {\r\n        _ecp_name = options.get(key + \".ecp\").as<string>();\r\n        _with_ecp = true;\r\n      } else {\r\n        _with_ecp = false;\r\n      }\r\n      _with_guess = options.ifExistsReturnElseReturnDefault<bool>(key + \".read_guess\", false);\r\n      _initial_guess = options.ifExistsReturnElseReturnDefault<string>(key + \".initial_guess\", \"atom\");\r\n\r\n      _grid_name = options.ifExistsReturnElseReturnDefault<string>(key + \".integration_grid\", \"medium\");\r\n      _use_small_grid = options.ifExistsReturnElseReturnDefault<bool>(key + \".integration_grid_small\", true);\r\n      _grid_name_small = ReturnSmallGrid(_grid_name);\r\n      _xc_functional_name = options.ifExistsReturnElseThrowRuntimeError<string>(key + \".xc_functional\");\r\n      \r\n      if (options.exists(key + \".externaldensity\")){\r\n        _integrate_ext_density=true;\r\n          _orbfilename=options.ifExistsReturnElseThrowRuntimeError<string>(key + \".externaldensity.orbfile\");\r\n          _gridquality=options.ifExistsReturnElseThrowRuntimeError<string>(key + \".externaldensity.gridquality\");\r\n          _state=options.ifExistsReturnElseThrowRuntimeError<string>(key + \".externaldensity.state\");        \r\n      }\r\n      \r\n      if (options.exists(key + \".convergence\")) {\r\n        _Econverged = options.ifExistsReturnElseReturnDefault<double>(key + \".convergence.energy\", 1e-7);\r\n        _error_converged = options.ifExistsReturnElseReturnDefault<double>(key + \".convergence.error\", 1e-7);\r\n        _max_iter = options.ifExistsReturnElseReturnDefault<int>(key + \".convergence.max_iterations\", 100);\r\n\r\n        if (options.exists(key + \".convergence.method\")) {\r\n          string method = options.get(key + \".convergence.method\").as<string>();\r\n          if (method == \"DIIS\") {\r\n            _usediis = true;\r\n          } else if (method == \"mixing\") {\r\n            _usediis = false;\r\n          } else {\r\n            cout << \"WARNING method not known. Using Mixing\" << endl;\r\n            _usediis = false;\r\n          }\r\n        } else {\r\n          _usediis = true;\r\n        }\r\n        if (!_usediis) {\r\n          _histlength = 1;\r\n          _maxout = false;\r\n        }\r\n        _mixingparameter = options.ifExistsReturnElseReturnDefault<double>(key + \".convergence.mixing\", 0.7);\r\n        _levelshift = options.ifExistsReturnElseReturnDefault<double>(key + \".convergence.levelshift\", 0.0);\r\n        _levelshiftend = options.ifExistsReturnElseReturnDefault<double>(key + \".convergence.levelshift_end\", 0.8);\r\n        _maxout = options.ifExistsReturnElseReturnDefault<bool>(key + \".convergence.DIIS_maxout\", false);\r\n        _histlength = options.ifExistsReturnElseReturnDefault<int>(key + \".convergence.DIIS_length\", 10);\r\n        _diis_start = options.ifExistsReturnElseReturnDefault<double>(key + \".convergence.DIIS_start\", 0.01);\r\n        _adiis_start = options.ifExistsReturnElseReturnDefault<double>(key + \".convergence.ADIIS_start\", 2);\r\n      } else {\r\n        _Econverged = 1e-7;\r\n        _error_converged = 1e-7;\r\n        _maxout = false;\r\n        _diis_start = 0.01;\r\n        _adiis_start = 2;\r\n        _histlength = 10;\r\n        _mixingparameter = 0.7;\r\n        _usediis = true;\r\n        _max_iter = 100;\r\n        _levelshift = 0.25;\r\n        _levelshiftend = 0.8;\r\n      }\r\n\r\n      return;\r\n    }\r\n\r\n \r\nvoid DFTEngine::PrintMOs(const Eigen::VectorXd& MOEnergies){\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \"  Orbital energies: \" << flush;\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \"  index occupation energy(Hartree) \" << flush;\r\n      for (int i = 0; i<MOEnergies.size(); i++) {\r\n        int occupancy=0;\r\n        if (i < _numofelectrons / 2 ) {\r\n          occupancy=2;\r\n        }\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) <<(boost::format(\" %1$5d      %2$1d   %3$+1.10f\")\r\n                                     %i %occupancy %MOEnergies(i)).str()<<flush;\r\n         \r\n      }\r\n      return;\r\n    }\r\n\r\n\r\nvoid DFTEngine::CalcElDipole(){\r\n  AODipole dipole;\r\n  dipole.Fill(_dftbasis);\r\n  CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Electric Dipole is[e*bohr]:\\n\\t\\t dx=\" \r\n                          << _dftAOdmat.cwiseProduct(dipole.Matrix()[0]).sum()\r\n          << \"\\n\\t\\t dy=\" << _dftAOdmat.cwiseProduct(dipole.Matrix()[1]).sum()\r\n          << \"\\n\\t\\t dz=\" << _dftAOdmat.cwiseProduct(dipole.Matrix()[2]).sum()<<flush;\r\n  return;\r\n}\r\n\r\n   /*\r\n     *    Density Functional theory implementation\r\n     *\r\n     */\r\n    bool DFTEngine::Evaluate(Orbitals& orbitals) {\r\n      // set the parallelization\r\n#ifdef _OPENMP\r\n      omp_set_num_threads(_openmp_threads);\r\n#endif\r\n\r\n      Eigen::VectorXd& MOEnergies = orbitals.MOEnergies();\r\n      Eigen::MatrixXd& MOCoeff = orbitals.MOCoefficients();\r\n      if (MOEnergies.size() != _dftbasis.AOBasisSize()) {\r\n        MOEnergies.resize(_dftbasis.AOBasisSize());\r\n      }\r\n      if (MOCoeff.rows() != _dftbasis.AOBasisSize() || MOCoeff.cols() != _dftbasis.AOBasisSize()) {\r\n        MOCoeff.conservativeResize(_dftbasis.AOBasisSize(), _dftbasis.AOBasisSize());\r\n      }\r\n\r\n      Eigen::MatrixXd H0 = _dftAOkinetic.Matrix() + _dftAOESP.getNuclearpotential();\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Constructed independent particle hamiltonian \" << flush;\r\n      NuclearRepulsion();\r\n      if(_with_ecp){\r\n          H0+=_dftAOECP.Matrix();\r\n      }\r\n      if (_addexternalsites) {\r\n        H0 += _dftAOESP.getExternalpotential();\r\n        H0 += _dftAODipole_Potential.getExternalpotential();\r\n        H0 += _dftAOQuadrupole_Potential.getExternalpotential();\r\n        double estat = ExternalRepulsion();\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" E_electrostatic \" << estat << flush;\r\n        _E_nucnuc += estat;\r\n      }\r\n      \r\n      if(_integrate_ext_density){\r\n        Orbitals extdensity;\r\n        extdensity.ReadFromCpt(_orbfilename);\r\n        H0+=IntegrateExternalDensity(extdensity);\r\n      }\r\n\r\n      if (_do_externalfield) {\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Integrated external potential on grid \" << flush;\r\n        double externalgrid_nucint = ExternalGridRepulsion(_externalgrid_nuc);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                << \" Nuclei external potential interaction \" << externalgrid_nucint << \" Hartree\" << flush;\r\n        H0 += _gridIntegration_ext.IntegrateExternalPotential(_externalgrid);\r\n        _E_nucnuc += externalgrid_nucint;\r\n      }\r\n\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n              << \" Nuclear Repulsion Energy is \" << _E_nucnuc << flush;\r\n\r\n      if (_with_guess) {\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Reading guess from orbitals object/file\" << flush;\r\n        orbitals.MOCoefficients()=OrthogonalizeGuess(orbitals.MOCoefficients() );\r\n        _dftAOdmat = _conv_accelerator.DensityMatrix(MOCoeff,MOEnergies);\r\n      } else {\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Setup Initial Guess using: \" << _initial_guess << flush;\r\n        if (_initial_guess == \"independent\") {\r\n          _conv_accelerator.SolveFockmatrix(MOEnergies, MOCoeff, H0);\r\n          _dftAOdmat = _conv_accelerator.DensityMatrix(MOCoeff,MOEnergies);\r\n\r\n        } else if (_initial_guess == \"atom\") {\r\n          _dftAOdmat = AtomicGuess(orbitals);\r\n          CalculateERIs(_dftbasis, _dftAOdmat);\r\n\r\n          if (_use_small_grid) {\r\n            orbitals.AOVxc() = _gridIntegration_small.IntegrateVXC(_dftAOdmat);\r\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled approximate DFT Vxc matrix \" << flush;\r\n          } else {\r\n            orbitals.AOVxc() = _gridIntegration.IntegrateVXC(_dftAOdmat);\r\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Vxc matrix \" << flush;\r\n          }\r\n          Eigen::MatrixXd H = H0 + _ERIs.getERIs() + orbitals.AOVxc();\r\n          if(_ScaHFX>0){\r\n              if (_with_RI) {\r\n             _ERIs.CalculateEXX(_dftAOdmat);\r\n           } else {\r\n             _ERIs.CalculateEXX_4c_small_molecule(_dftAOdmat);\r\n           }\r\n            H-=0.5*_ScaHFX*_ERIs.getEXX();\r\n          }      \r\n          _conv_accelerator.SolveFockmatrix(MOEnergies, MOCoeff, H);\r\n          _dftAOdmat = _conv_accelerator.DensityMatrix(MOCoeff,MOEnergies);\r\n\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Full atomic density Matrix gives N=\"\r\n                  << std::setprecision(9) << _dftAOdmat.cwiseProduct(_dftAOoverlap.Matrix()).sum() << \" electrons.\" << flush;\r\n        } else {\r\n          throw std::runtime_error(\"Initial guess method not known/implemented\");\r\n        }\r\n\r\n      }\r\n\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" STARTING SCF cycle\" << flush;\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \" --------------------------------------------------------------------------\" << flush;\r\n\r\n      double energyold = std::numeric_limits<double>::max();\r\n\r\n      for (int this_iter = 0; this_iter < _max_iter; this_iter++) {\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << flush;\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Iteration \" \r\n                << this_iter + 1 << \" of \" << _max_iter << flush;\r\n\r\n        \r\n\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Electron repulsion matrix\" << flush;\r\n        double vxcenergy = 0.0;\r\n        if (_use_small_grid && _conv_accelerator.getDIIsError() > 1e-3) {\r\n          orbitals.AOVxc() = _gridIntegration_small.IntegrateVXC(_dftAOdmat);\r\n          vxcenergy = _gridIntegration_small.getTotEcontribution();\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled approximate DFT Vxc matrix \" << flush;\r\n        } else {\r\n          orbitals.AOVxc() = _gridIntegration.IntegrateVXC(_dftAOdmat);\r\n          vxcenergy = _gridIntegration.getTotEcontribution();\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Vxc matrix \" << flush;\r\n        }\r\n        CalculateERIs(_dftbasis, _dftAOdmat);\r\n        Eigen::MatrixXd H = H0 + _ERIs.getERIs() + orbitals.AOVxc();\r\n        if(_ScaHFX>0){\r\n              if (_with_RI) {\r\n                if(_conv_accelerator.getUseMixing()){\r\n                  _ERIs.CalculateEXX(_dftAOdmat); \r\n                }else{\r\n                  Eigen::Block<Eigen::MatrixXd> occblock=MOCoeff.block(0,0,MOEnergies.rows(), _numofelectrons / 2);\r\n                  _ERIs.CalculateEXX(occblock,_dftAOdmat); \r\n                }\r\n           } else {\r\n             _ERIs.CalculateEXX_4c_small_molecule(_dftAOdmat);\r\n           } \r\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Filled DFT Electron exchange matrix\"<< flush;\r\n            H-=0.5*_ScaHFX*_ERIs.getEXX();\r\n          }\r\n      \r\n        double Eone = _dftAOdmat.cwiseProduct(H0).sum();\r\n        double Etwo = 0.5 * _ERIs.getERIsenergy() + vxcenergy;\r\n        if(_ScaHFX>0){\r\n          Etwo-=_ScaHFX/4*_ERIs.getEXXsenergy();\r\n        }\r\n        double totenergy = Eone + _E_nucnuc + Etwo;\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Single particle energy \"\r\n                << std::setprecision(12) << Eone << flush;\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Two particle energy \" \r\n                << std::setprecision(12) << Etwo << flush;\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                << std::setprecision(12) << \" Local Exc contribution \" << vxcenergy << flush;\r\n        if(_ScaHFX>0){\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                  << std::setprecision(12) << \" Non local Ex contribution \" << -_ScaHFX/4*_ERIs.getEXXsenergy() << flush;\r\n        }\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Total Energy \" << std::setprecision(12) << totenergy << flush;\r\n\r\n        _dftAOdmat = _conv_accelerator.Iterate(_dftAOdmat, H, MOEnergies, MOCoeff, totenergy);\r\n\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" DIIs error \" << _conv_accelerator.getDIIsError() << std::flush;\r\n        double deltaE=totenergy - energyold;\r\n        if(this_iter == 0){\r\n          deltaE=0;\r\n        }\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Delta Etot \" <<deltaE<< std::flush;\r\n        if (tools::globals::verbose) {\r\n          PrintMOs(MOEnergies);\r\n        }\r\n\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\tGAP \" \r\n                << MOEnergies(_numofelectrons / 2) - MOEnergies(_numofelectrons / 2 - 1) << flush;\r\n\r\n        if (std::abs(totenergy - energyold) < _Econverged && _conv_accelerator.getDIIsError() < _error_converged) {\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                  << \" Total Energy has converged to \" << std::setprecision(9) \r\n                  << std::abs(totenergy - energyold) << \"[Ha] after \" << this_iter + 1 <<\r\n                  \" iterations. DIIS error is converged up to \" << _error_converged << \"[Ha]\" << flush;\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Final Single Point Energy \"\r\n                  << std::setprecision(12) << totenergy << \" Ha\" << flush;\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" MO Energies  [Ha]\" << flush;\r\n          \r\n          PrintMOs(MOEnergies);\r\n           CalcElDipole();\r\n          // orbitals saves total energies in [eV]\r\n          orbitals.setQMEnergy(totenergy * tools::conv::hrt2ev);\r\n          break;\r\n        } else {\r\n          energyold = totenergy;\r\n        }\r\n        \r\n        \r\n       \r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Density Matrix gives N=\" \r\n                << _dftAOdmat.cwiseProduct(_dftAOoverlap.Matrix()).sum() << \" electrons.\" << flush;\r\n\r\n      }\r\n      return true;\r\n    }\r\n\r\n\r\n\r\n\r\n    // SETUP INVARIANT AOMatrices\r\n\r\n    void DFTEngine::SetupInvariantMatrices() {\r\n      \r\n        _dftAOoverlap.Fill(_dftbasis);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                << \" Filled DFT Overlap matrix.\"<< flush;\r\n\r\n      _dftAOkinetic.Fill(_dftbasis);\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n              << \" Filled DFT Kinetic energy matrix .\"<< flush;\r\n\r\n      _dftAOESP.Fillnucpotential(_dftbasis, _atoms);\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n              << \" Filled DFT nuclear potential matrix.\"<< flush;\r\n\r\n      if (_addexternalsites) {\r\n        _dftAOESP.Fillextpotential(_dftbasis, _externalsites);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                << \" Filled DFT external pointcharge potential matrix\"<< flush;\r\n\r\n        _dftAODipole_Potential.Fillextpotential(_dftbasis, _externalsites);\r\n        if (_dftAODipole_Potential.Dimension() > 0) {\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                  << \" Filled DFT external dipole potential matrix\" << flush;\r\n        }\r\n        _dftAOQuadrupole_Potential.Fillextpotential(_dftbasis, _externalsites);\r\n        if (_dftAOQuadrupole_Potential.Dimension()) {\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                  << \" Filled DFT external quadrupole potential matrix.\"<< flush;\r\n        }\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()<< \" External sites\"<<flush;\r\n        CTP_LOG(ctp::logDEBUG, *_pLog)<<\" Name      Coordinates[nm]     charge[e]         dipole[e*nm]    \" \r\n                                        \"              quadrupole[e*nm^2]         \" << flush;\r\n\r\n\r\n        for (auto segment:_externalsites) {\r\n          for (ctp::APolarSite* site:*segment){\r\n            std::string output=(boost::format(\"  %1$s\"\r\n                                            \"   %2$+1.4f %3$+1.4f %4$+1.4f\"\r\n                                            \"   %5$+1.4f\")\r\n                                            %site->getName()\r\n                                            %site->getPos().getX() %site->getPos().getY() %site->getPos().getZ() \r\n                                            %site->getQ00()).str();\r\n            if (site->getRank() > 0) {\r\n              tools::vec dipole = site->getQ1();\r\n              output+=(boost::format(\"   %1$+1.4f %2$+1.4f %3$+1.4f\")\r\n                                     %dipole.getX() %dipole.getY() %dipole.getZ()).str();\r\n            }\r\n            if (site->getRank() > 1) {\r\n              std::vector<double> quadrupole = site->getQ2();\r\n              output+=(boost::format(\"   %1$+1.4f %2$+1.4f %3$+1.4f %4$+1.4f %5$+1.4f\")\r\n                                     %quadrupole[0] %quadrupole[1] %quadrupole[2] \r\n                                     %quadrupole[3] %quadrupole[4]).str();\r\n            }\r\n            CTP_LOG(ctp::logDEBUG, *_pLog) <<output<< flush;\r\n          }\r\n        }\r\n      }\r\n\r\n      if (_with_ecp) {\r\n        _dftAOECP.setECP(&_ecp);\r\n        _dftAOECP.Fill(_dftbasis);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() \r\n                << \" Filled DFT ECP matrix\" << flush;\r\n      }\r\n\r\n      _conv_accelerator.Configure(ConvergenceAcc::KSmode::closed, _usediis,\r\n              true, _histlength, _maxout, _adiis_start, _diis_start,\r\n              _levelshift, _levelshiftend, _numofelectrons, _mixingparameter);\r\n      _conv_accelerator.setLogger(_pLog);\r\n      _conv_accelerator.setOverlap(&_dftAOoverlap, 1e-8);\r\n\r\n      if (_with_RI) {\r\n\r\n        AOCoulomb auxAOcoulomb;\r\n        auxAOcoulomb.Fill(_auxbasis);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Filled auxiliary Coulomb matrix\"<< flush;\r\n\r\n        Eigen::MatrixXd Inverse=auxAOcoulomb.Pseudo_InvSqrt(1e-8);\r\n\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Inverted AUX Coulomb matrix, removed \" << auxAOcoulomb.Removedfunctions()\r\n                << \" functions from aux basis\" << flush;\r\n\r\n        // prepare invariant part of electron repulsion integrals\r\n        _ERIs.Initialize(_dftbasis, _auxbasis, Inverse);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Setup invariant parts of Electron Repulsion integrals \" << flush;\r\n      } else {\r\n\r\n        if (_four_center_method==\"cache\") {\r\n\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculating 4c integrals. \" << flush;\r\n          _ERIs.Initialize_4c_small_molecule(_dftbasis);\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculated 4c integrals. \" << flush;\r\n        }\r\n\r\n        if (_with_screening && _four_center_method==\"direct\") {\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculating 4c diagonals. \" << flush;\r\n          _ERIs.Initialize_4c_screening(_dftbasis, _screening_eps);\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculated 4c diagonals. \" << flush;\r\n        }\r\n      }\r\n\r\n      return;\r\n    }\r\n    \r\n    Eigen::MatrixXd DFTEngine::RunAtomicDFT_unrestricted(QMAtom* uniqueAtom){\r\n      bool with_ecp = _with_ecp;\r\n      if (uniqueAtom->getType() == \"H\" || uniqueAtom->getType() == \"He\") {\r\n        with_ecp = false;\r\n      }\r\n      \r\n       std::vector<QMAtom*> atom;\r\n        atom.push_back(uniqueAtom);\r\n\r\n        AOBasis dftbasis;\r\n        NumericalIntegration gridIntegration;\r\n        dftbasis.AOBasisFill(_dftbasisset, atom);\r\n        AOBasis ecp;\r\n        if (with_ecp) {\r\n          ecp.ECPFill(_ecpbasisset, atom);\r\n        }\r\n        gridIntegration.GridSetup(_grid_name, atom, dftbasis);\r\n        gridIntegration.setXCfunctional(_xc_functional_name);\r\n        int numofelectrons = uniqueAtom->getNuccharge();\r\n        int alpha_e = 0;\r\n        int beta_e = 0;\r\n\r\n        if ((numofelectrons % 2) != 0) {\r\n          alpha_e = numofelectrons / 2 + numofelectrons % 2;\r\n          beta_e = numofelectrons / 2;\r\n        } else {\r\n          alpha_e = numofelectrons / 2;\r\n          beta_e = alpha_e;\r\n        }\r\n\r\n        AOOverlap dftAOoverlap;\r\n        AOKinetic dftAOkinetic;\r\n        AOESP dftAOESP;\r\n        AOECP dftAOECP;\r\n        ERIs ERIs_atom;\r\n\r\n        // DFT AOOverlap matrix\r\n\r\n        dftAOoverlap.Fill(dftbasis);\r\n        dftAOkinetic.Fill(dftbasis);\r\n\r\n        dftAOESP.Fillnucpotential(dftbasis, atom);\r\n        ERIs_atom.Initialize_4c_small_molecule(dftbasis);\r\n\r\n        Eigen::VectorXd MOEnergies_alpha;\r\n        Eigen::MatrixXd MOCoeff_alpha;\r\n        Eigen::VectorXd MOEnergies_beta;\r\n        Eigen::MatrixXd MOCoeff_beta;\r\n        ConvergenceAcc Convergence_alpha;\r\n\r\n        ConvergenceAcc Convergence_beta;\r\n        double adiisstart = 0;\r\n        double diisstart = 0;\r\n\r\n        Convergence_alpha.Configure(ConvergenceAcc::KSmode::open, true, false, \r\n                20, 0, adiisstart, diisstart, 0.1, diisstart, alpha_e, _mixingparameter);\r\n        Convergence_alpha.setLogger(_pLog);\r\n        Convergence_alpha.setOverlap(&dftAOoverlap, 1e-8);\r\n        Convergence_beta.Configure(ConvergenceAcc::KSmode::open, true, false, \r\n                20, 0, adiisstart, diisstart, 0.1, diisstart, beta_e, _mixingparameter);\r\n        Convergence_beta.setLogger(_pLog);\r\n        Convergence_beta.setOverlap(&dftAOoverlap, 1e-8);\r\n        /**** Construct initial density  ****/\r\n\r\n        Eigen::MatrixXd H0 = dftAOkinetic.Matrix() + dftAOESP.getNuclearpotential();\r\n        if (with_ecp) {\r\n          dftAOECP.setECP(&ecp);\r\n          dftAOECP.Fill(dftbasis);\r\n          H0 += dftAOECP.Matrix();\r\n        }\r\n        Convergence_alpha.SolveFockmatrix(MOEnergies_alpha, MOCoeff_alpha, H0);\r\n\r\n        Eigen::MatrixXd dftAOdmat_alpha = Convergence_alpha.DensityMatrix(MOCoeff_alpha, MOEnergies_alpha);\r\n        if (uniqueAtom->getType() == \"H\") {\r\n          return dftAOdmat_alpha;\r\n        }\r\n        Convergence_beta.SolveFockmatrix(MOEnergies_beta, MOCoeff_beta, H0);\r\n        Eigen::MatrixXd dftAOdmat_beta = Convergence_beta.DensityMatrix(MOCoeff_beta, MOEnergies_beta);\r\n   \r\n        double energyold = 0;\r\n        int maxiter = 80;\r\n        for (int this_iter = 0; this_iter < maxiter; this_iter++) {\r\n          ERIs_atom.CalculateERIs_4c_small_molecule(dftAOdmat_alpha + dftAOdmat_beta);\r\n          double E_two_alpha = ERIs_atom.getERIs().cwiseProduct(dftAOdmat_alpha).sum();\r\n          double E_two_beta = ERIs_atom.getERIs().cwiseProduct(dftAOdmat_beta).sum();\r\n          Eigen::MatrixXd H_alpha = H0 + ERIs_atom.getERIs();\r\n          Eigen::MatrixXd H_beta = H0 + ERIs_atom.getERIs();\r\n          \r\n            Eigen::MatrixXd AOVxc_alpha = gridIntegration.IntegrateVXC(dftAOdmat_alpha);\r\n            double E_vxc_alpha = gridIntegration.getTotEcontribution();\r\n\r\n            Eigen::MatrixXd AOVxc_beta = gridIntegration.IntegrateVXC(dftAOdmat_beta);\r\n            double E_vxc_beta = gridIntegration.getTotEcontribution();\r\n            H_alpha += AOVxc_alpha;\r\n            H_beta += AOVxc_beta;\r\n            E_two_alpha += E_vxc_alpha;\r\n            E_two_beta += E_vxc_beta;\r\n          \r\n            if(_ScaHFX>0){\r\n              ERIs_atom.CalculateEXX_4c_small_molecule(dftAOdmat_alpha);\r\n              double E_exx_alpha =-0.5*_ScaHFX*ERIs_atom.getEXX().cwiseProduct(dftAOdmat_alpha).sum();\r\n              H_alpha -=_ScaHFX* ERIs_atom.getEXX();\r\n              E_two_alpha += E_exx_alpha;\r\n              ERIs_atom.CalculateEXX_4c_small_molecule(dftAOdmat_beta);\r\n              double E_exx_beta =-0.5*_ScaHFX*ERIs_atom.getEXX().cwiseProduct(dftAOdmat_beta).sum();\r\n              H_beta -=_ScaHFX*ERIs_atom.getEXX();\r\n              E_two_beta += E_exx_beta;\r\n            }\r\n\r\n          double E_one_alpha = dftAOdmat_alpha.cwiseProduct(H0).sum();\r\n          double E_one_beta = dftAOdmat_beta.cwiseProduct(H0).sum();\r\n          double E_alpha = E_one_alpha + E_two_alpha;\r\n          double E_beta = E_one_beta + E_two_beta;\r\n          double totenergy = E_alpha + E_beta;\r\n          //evolve alpha\r\n          dftAOdmat_alpha = Convergence_alpha.Iterate(dftAOdmat_alpha, H_alpha,\r\n                  MOEnergies_alpha, MOCoeff_alpha, E_alpha);\r\n          //evolve beta\r\n          dftAOdmat_beta = Convergence_beta.Iterate(dftAOdmat_beta, H_beta,\r\n                  MOEnergies_beta, MOCoeff_beta, E_beta);\r\n\r\n          if (tools::globals::verbose) {\r\n            CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Iter \" << this_iter << \" of \" << maxiter\r\n                    << \" Etot \" << totenergy \r\n                    << \" diise_a \" << Convergence_alpha.getDIIsError() \r\n                    << \" diise_b \" << Convergence_beta.getDIIsError()\r\n                    << \"\\n\\t\\t a_gap \" << MOEnergies_alpha(alpha_e) - MOEnergies_alpha(alpha_e - 1) \r\n                    << \" b_gap \" << MOEnergies_beta(beta_e) - MOEnergies_beta(beta_e - 1) \r\n                    <<\" Nalpha=\"<<dftAOoverlap.Matrix().cwiseProduct(dftAOdmat_alpha).sum()\r\n                    <<\" Nbeta=\"<<dftAOoverlap.Matrix().cwiseProduct(dftAOdmat_beta).sum()<<flush;\r\n          }\r\n          bool converged = (std::abs(totenergy - energyold) < _Econverged &&\r\n                  Convergence_alpha.getDIIsError() < _error_converged &&\r\n                  Convergence_beta.getDIIsError() < _error_converged);\r\n          if (converged || this_iter == maxiter - 1) {\r\n\r\n            if (converged) {\r\n              CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Converged after \" << this_iter + 1 << \" iterations\" << flush;\r\n            } else {\r\n              CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Not converged after \"\r\n                      << this_iter + 1 <<\" iterations. Unconverged density.\\n\\t\\t\\t\"\r\n                      <<\" DIIsError_alpha=\" << Convergence_alpha.getDIIsError()\r\n                      << \" DIIsError_beta=\" << Convergence_beta.getDIIsError() << flush;\r\n            }\r\n            break;\r\n\r\n          } else {\r\n            energyold = totenergy;\r\n          }\r\n        }\r\n        Eigen::MatrixXd avgmatrix=SphericalAverageShells(dftAOdmat_alpha + dftAOdmat_beta,dftbasis);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Atomic density Matrix for \" << uniqueAtom->getType() << \" gives N=\"\r\n                << std::setprecision(9) << avgmatrix.cwiseProduct(dftAOoverlap.Matrix()).sum() << \" electrons.\" << flush;\r\n        return avgmatrix;\r\n    }\r\n    \r\n    \r\n  \r\n\r\n    Eigen::MatrixXd DFTEngine::AtomicGuess(Orbitals& orbitals) {\r\n\r\n      std::vector<QMAtom*> uniqueelements;\r\n       \r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Scanning molecule of size \" << _atoms.size() << \" for unique elements\" << flush;\r\n      for (QMAtom* atom:_atoms) {\r\n        bool exists = false;\r\n        if (uniqueelements.size() == 0) {\r\n          exists = false;\r\n        } else {\r\n          for (const QMAtom* unique_atom:uniqueelements){\r\n            if (atom->getType() == unique_atom->getType()) {\r\n              exists = true;\r\n              break;\r\n            }\r\n          }\r\n        }\r\n        if (!exists) {\r\n          uniqueelements.push_back(atom);\r\n        }\r\n      }\r\n      \r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" \" << uniqueelements.size() << \" unique elements found\" << flush;\r\n      std::vector< Eigen::MatrixXd > uniqueatom_guesses;\r\n      for ( QMAtom* unique_atom:uniqueelements) {\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Calculating atom density for \" << unique_atom->getType() << flush;\r\n        Eigen::MatrixXd dmat_unrestricted=RunAtomicDFT_unrestricted(unique_atom);\r\n        uniqueatom_guesses.push_back(dmat_unrestricted);\r\n      }\r\n \r\n      Eigen::MatrixXd guess = Eigen::MatrixXd::Zero(_dftbasis.AOBasisSize(), _dftbasis.AOBasisSize());\r\n      int start = 0;\r\n      for (QMAtom* atom:_atoms) {\r\n        unsigned index = 0;\r\n        for (index = 0; index < uniqueelements.size(); index++) {\r\n          if (atom->getType() == uniqueelements[index]->getType()) {\r\n            break;\r\n          }\r\n        }\r\n        Eigen::MatrixXd& dmat_unrestricted= uniqueatom_guesses[index];\r\n        guess.block(start, start, dmat_unrestricted.rows(),dmat_unrestricted.cols())=dmat_unrestricted;\r\n        start += dmat_unrestricted.rows();\r\n      }\r\n      \r\n      return guess;\r\n    }\r\n\r\n    void DFTEngine::ConfigOrbfile(Orbitals& orbitals) {\r\n      if (_with_guess) {\r\n\r\n        if (orbitals.hasDFTbasis()) {\r\n          if (orbitals.getDFTbasis() != _dftbasis_name) {\r\n            throw runtime_error((boost::format(\"Basisset Name in guess orb file \"\r\n                    \"and in dftengine option file differ %1% vs %2%\") \r\n                    % orbitals.getDFTbasis() % _dftbasis_name).str());\r\n          }\r\n        } else {\r\n          CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" WARNING: \"\r\n                  \"Orbital file has no basisset information,\"\r\n                  \"using it as a guess might work or not for calculation with \"\r\n                  << _dftbasis_name << flush;\r\n        }\r\n      }\r\n      orbitals.setQMpackage(\"xtp\");\r\n      orbitals.setDFTbasis(_dftbasis_name);\r\n      orbitals.setBasisSetSize(_dftbasis.AOBasisSize());\r\n      orbitals.setScaHFX(_ScaHFX);\r\n      if (_with_ecp) {\r\n        orbitals.setECP(_ecp_name);\r\n      }\r\n      if (_with_RI) {\r\n        orbitals.setAuxbasis(_auxbasis_name);\r\n      }\r\n\r\n      if (_with_guess) {\r\n        if (orbitals.hasECP() || _with_ecp) {\r\n          if (orbitals.getECP() != _ecp_name) {\r\n            throw runtime_error((boost::format(\"ECPs in orb file: %1% and options %2% differ\")\r\n                    % orbitals.getECP() % _ecp_name).str());\r\n          }\r\n        }\r\n        if (orbitals.getNumberOfElectrons() != _numofelectrons / 2) {\r\n          throw runtime_error((boost::format(\"Number of electron in guess orb file: %1% and in dftengine: %2% differ.\")\r\n                  % orbitals.getNumberOfElectrons() % (_numofelectrons / 2)).str());\r\n        }\r\n        if (orbitals.getNumberOfLevels() != _dftbasis.AOBasisSize()) {\r\n          throw runtime_error((boost::format(\"Number of levels in guess orb file: %1% and in dftengine: %2% differ.\") \r\n                  % orbitals.getNumberOfLevels() % _dftbasis.AOBasisSize()).str());\r\n        }\r\n      } else {\r\n        orbitals.setNumberOfElectrons(_numofelectrons / 2);\r\n        orbitals.setNumberOfLevels(_numofelectrons / 2, _dftbasis.AOBasisSize() - _numofelectrons / 2);\r\n      }\r\n      return;\r\n    }\r\n\r\n\r\n    // PREPARATION\r\nvoid DFTEngine::Prepare(Orbitals& orbitals) {\r\n#ifdef _OPENMP\r\n\r\n      omp_set_num_threads(_openmp_threads);\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Using \" << omp_get_max_threads() << \" threads\" << flush;\r\n\r\n#endif\r\n      if(tools::globals::VOTCA_MKL){\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Using MKL overload for Eigen \" << flush;\r\n      } else {\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Using native Eigen implementation, no BLAS overload \" << flush;\r\n      }\r\n\r\n      if (_atoms.size() == 0) {\r\n        _atoms = orbitals.QMAtoms();\r\n      }\r\n\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \" Molecule Coordinates [A] \" << flush;\r\n      for (const QMAtom* atom:_atoms) {\r\n        \r\n      std::string output=(boost::format(\"  %1$s\"\r\n                                         \"   %2$+1.4f %3$+1.4f %4$+1.4f\")\r\n                         %atom->getType() %(atom->getPos().getX()*tools::conv::bohr2ang)\r\n                         %(atom->getPos().getY()*tools::conv::bohr2ang)\r\n                         %(atom->getPos().getZ()*tools::conv::bohr2ang) ).str();\r\n        \r\n        CTP_LOG(ctp::logDEBUG, *_pLog) <<output<< flush;\r\n      }\r\n\r\n      _dftbasisset.LoadBasisSet(_dftbasis_name);\r\n\r\n      _dftbasis.AOBasisFill(_dftbasisset, _atoms);\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n              << \" Loaded DFT Basis Set \" << _dftbasis_name \r\n              << \" with \"<<_dftbasis.AOBasisSize()<<\" functions\"<< flush;\r\n\r\n      if (_with_RI) {\r\n        _auxbasisset.LoadBasisSet(_auxbasis_name);\r\n        _auxbasis.AOBasisFill(_auxbasisset, _atoms);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Loaded AUX Basis Set \" << _auxbasis_name  \r\n                << \" with \"<<_auxbasis.AOBasisSize()<<\" functions\"<< flush;\r\n      }\r\n      if (_with_ecp) {\r\n        _ecpbasisset.LoadPseudopotentialSet(_ecp_name);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Loaded ECP library \" << _ecp_name << flush;\r\n\r\n        _ecp.ECPFill(_ecpbasisset, _atoms);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Filled ECP Basis of size \" << _ecp.getNumofShells() << flush;\r\n      }\r\n\r\n      _gridIntegration.GridSetup(_grid_name, _atoms, _dftbasis);\r\n      _gridIntegration.setXCfunctional(_xc_functional_name);\r\n\r\n      _ScaHFX = _gridIntegration.getExactExchange(_xc_functional_name);\r\n      if (_ScaHFX > 0) {\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n                << \" Using hybrid functional with alpha=\" << _ScaHFX << flush;\r\n      }\r\n\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup numerical integration grid \"\r\n              << _grid_name << \" for vxc functional \"\r\n              << _xc_functional_name <<  flush;\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \"<<\" with \" << _gridIntegration.getGridSize() << \" points\" \r\n              << \" divided into \"<< _gridIntegration.getBoxesSize() << \" boxes\" << flush;\r\n      if (_use_small_grid) {\r\n        _gridIntegration_small.GridSetup(_grid_name_small, _atoms, _dftbasis);\r\n        _gridIntegration_small.setXCfunctional(_xc_functional_name);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup small numerical integration grid \"\r\n                << _grid_name_small << \" for vxc functional \"\r\n                << _xc_functional_name  << flush;\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << \"\\t\\t \" << \" with \" << _gridIntegration_small.getGridSize() << \" points\"\r\n                << \" divided into \"<< _gridIntegration_small.getBoxesSize() << \" boxes\" << flush;\r\n      }\r\n\r\n      if (_do_externalfield) {\r\n        _gridIntegration_ext.GridSetup(_grid_name_ext, _atoms, _dftbasis);\r\n        CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << \" Setup numerical integration grid \"\r\n                << _grid_name_ext << \" for external field with \"\r\n                << _gridIntegration_ext.getGridpoints().size() << \" points\" << flush;\r\n      }\r\n\r\n      for (auto& atom : _atoms) {\r\n        _numofelectrons += atom->getNuccharge();\r\n      }\r\n\r\n      // here number of electrons is actually the total number, everywhere else in votca it is just alpha_electrons\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp()\r\n              << \" Total number of electrons: \" << _numofelectrons << flush;\r\n\r\n      ConfigOrbfile(orbitals);\r\n      SetupInvariantMatrices();\r\n      return;\r\n    }\r\n\r\n    void DFTEngine::NuclearRepulsion() {\r\n      _E_nucnuc = 0.0;\r\n\r\n      for (unsigned i = 0; i < _atoms.size(); i++) {\r\n        const tools::vec& r1 = _atoms[i]->getPos();\r\n        double charge1 = _atoms[i]->getNuccharge();\r\n        for (unsigned j = 0; j < i; j++) {\r\n          const tools::vec& r2 = _atoms[j]->getPos();\r\n          double charge2 = _atoms[j]->getNuccharge();\r\n          _E_nucnuc += charge1 * charge2 / (abs(r1 - r2));\r\n        }\r\n      }\r\n      return;\r\n    }\r\n\r\n    double DFTEngine::ExternalRepulsion(ctp::Topology* top) {\r\n\r\n\r\n      if (_externalsites.size() == 0) {\r\n        return 0;\r\n      }\r\n\r\n      QMInterface qmminter;\r\n      ctp::PolarSeg nuclei = qmminter.Convert(_atoms);\r\n\r\n      for (unsigned i = 0; i < nuclei.size(); ++i) {\r\n        ctp::APolarSite* nucleus = nuclei[i];\r\n        nucleus->setIsoP(0.0);\r\n        double Q = _atoms[i]->getNuccharge();\r\n        nucleus->setQ00(Q, 0);\r\n      }\r\n      ctp::XInteractor actor;\r\n      actor.ResetEnergy();\r\n      nuclei.CalcPos();\r\n      double E_ext = 0.0;\r\n      for (std::shared_ptr<ctp::PolarSeg>  seg : _externalsites) {\r\n        seg->CalcPos();\r\n        tools::vec s = tools::vec(0.0);\r\n        if (top != NULL) {\r\n          s = top->PbShortestConnect(nuclei.getPos(),\r\n                  seg->getPos())+nuclei.getPos()-seg->getPos();\r\n        }\r\n\r\n        for (auto nucleus : nuclei) {\r\n          nucleus->Depolarize();\r\n          nucleus->Charge(0);\r\n          for (auto site : (*seg)) {\r\n            site->Charge(0);\r\n            actor.BiasIndu(*nucleus, *site, s);\r\n            E_ext += actor.E_f(*nucleus, *site);\r\n\r\n          }\r\n        }\r\n      }\r\n      return E_ext * tools::conv::int2eV * tools::conv::ev2hrt;\r\n    }\r\n\r\n    double DFTEngine::ExternalGridRepulsion(std::vector<double> externalpotential_nuc) {\r\n      double E_ext = 0.0;\r\n      if (!_do_externalfield) {\r\n        return 0;\r\n      }\r\n      for (unsigned i = 0; i < _atoms.size(); i++) {\r\n        double Q = _atoms[i]->getNuccharge();\r\n        E_ext += Q * externalpotential_nuc[i];\r\n      }\r\n      return E_ext;\r\n    }\r\n\r\n    string DFTEngine::ReturnSmallGrid(const string& largegrid) {\r\n      string smallgrid;\r\n\r\n      if (largegrid == \"xfine\") {\r\n        smallgrid = \"fine\";\r\n      } else if (largegrid == \"fine\") {\r\n        smallgrid = \"medium\";\r\n      } else if (largegrid == \"medium\") {\r\n        _use_small_grid = false;\r\n        smallgrid = \"medium\";\r\n      } else if (largegrid == \"coarse\") {\r\n        _use_small_grid = false;\r\n        smallgrid = \"coarse\";\r\n      } else if (largegrid == \"xcoarse\") {\r\n        _use_small_grid = false;\r\n        smallgrid = \"xcoarse\";\r\n      } else {\r\n        throw runtime_error(\"Grid name for Vxc integration not known.\");\r\n      }\r\n      return smallgrid;\r\n    }\r\n\r\n\r\n    //average atom densities matrices, for SP and other combined shells average each subshell separately.\r\n\r\n    Eigen::MatrixXd DFTEngine::SphericalAverageShells(const Eigen::MatrixXd& dmat, AOBasis& dftbasis) {\r\n      Eigen::MatrixXd avdmat = Eigen::MatrixXd::Zero(dmat.rows(), dmat.cols());\r\n      int start = 0.0;\r\n      std::vector<int> starts;\r\n      std::vector<int> ends;\r\n      for (AOShell* shell:dftbasis) {\r\n        int end = shell->getNumFunc() + start;\r\n\r\n        if (shell->isCombined()) {\r\n          std::vector<int> temp = NumFuncSubShell(shell->getType());\r\n          int numfunc = start;\r\n          for (int & SubshellFunc:temp) {\r\n            starts.push_back(numfunc);\r\n            numfunc +=SubshellFunc;\r\n            ends.push_back(numfunc);\r\n          }\r\n        } else {\r\n          starts.push_back(start);\r\n          ends.push_back(end);\r\n        }\r\n        start = end;\r\n      }\r\n      for (unsigned k = 0; k < starts.size(); k++) {\r\n        int s1 = starts[k];\r\n        int e1 = ends[k];\r\n        int len1 = e1 - s1;\r\n        for (unsigned l = 0; l < starts.size(); l++) {\r\n          int s2 = starts[l];\r\n          int e2 = ends[l];\r\n          int len2 = e2 - s2;\r\n          double diag = 0.0;\r\n          double offdiag = 0.0;\r\n          for (int i = 0; i < len1; ++i) {\r\n            for (int j = 0; j < len2; ++j) {\r\n              if (i == j) {\r\n                diag += dmat(s1 + i, s2 + j);\r\n              } else {\r\n                offdiag += dmat(s1 + i, s2 + j);\r\n              }\r\n            }\r\n          }\r\n          if (len1 == len2) {\r\n            diag = diag / double(len1);\r\n            offdiag = offdiag / double(len1 * (len1 - 1));\r\n          } else {\r\n            double avg = (diag + offdiag) / double(len1 * len2);\r\n            diag = avg;\r\n            offdiag = avg;\r\n          }\r\n          for (int i = 0; i < len1; ++i) {\r\n            for (int j = 0; j < len2; ++j) {\r\n              if (i == j) {\r\n                avdmat(s1 + i, s2 + j) = diag;\r\n              } else {\r\n                avdmat(s1 + i, s2 + j) = offdiag;\r\n              }\r\n            }\r\n          }\r\n        }\r\n      }\r\n\r\n      return avdmat;\r\n    }\r\n    \r\n    \r\n    Eigen::MatrixXd DFTEngine::IntegrateExternalDensity(Orbitals& extdensity){\r\n      BasisSet basis;\r\n      basis.LoadBasisSet(extdensity.getDFTbasis());\r\n      AOBasis aobasis;\r\n      aobasis.AOBasisFill(basis,extdensity.QMAtoms());\r\n      NumericalIntegration numint;\r\n      numint.GridSetup(_gridquality,extdensity.QMAtoms(),aobasis);\r\n      Eigen::MatrixXd dmat=extdensity.DensityMatrixGroundState();\r\n      \r\n      numint.IntegrateDensity(dmat);\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() <<\" Calculated external density\"<<flush;\r\n      Eigen::MatrixXd e_contrib=numint.IntegratePotential(_dftbasis);\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() <<\" Calculated potential from electron density\"<<flush;\r\n      AOESP esp;\r\n      esp.Fillnucpotential(_dftbasis,extdensity.QMAtoms());\r\n      \r\n      double nuc_energy=0.0;\r\n      for(const QMAtom* atom:_atoms){\r\n        nuc_energy+=numint.IntegratePotential(atom->getPos())*atom->getNuccharge();\r\n        for(const QMAtom* extatom:extdensity.QMAtoms()){\r\n          const double dist=tools::abs(atom->getPos()-extatom->getPos());\r\n          nuc_energy+=atom->getNuccharge()*extatom->getNuccharge()/dist;\r\n        }\r\n      }\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() <<\" Calculated potential from nuclei\"<<flush;\r\n      CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() <<\" Elelctrostatic: \"<<nuc_energy<<flush;\r\n      _E_nucnuc+=nuc_energy;\r\n      return e_contrib+esp.getNuclearpotential();\r\n    }\r\n\r\n    void DFTEngine::CalculateERIs(const AOBasis& dftbasis, const Eigen::MatrixXd& DMAT) {\r\n\r\n      if (_with_RI)\r\n        _ERIs.CalculateERIs(_dftAOdmat);\r\n      else if (_four_center_method.compare(\"cache\") == 0)\r\n        _ERIs.CalculateERIs_4c_small_molecule(_dftAOdmat);\r\n      else if (_four_center_method.compare(\"direct\") == 0)\r\n        _ERIs.CalculateERIs_4c_direct(_dftbasis, _dftAOdmat);\r\n    }\r\n    \r\n    Eigen::MatrixXd DFTEngine::OrthogonalizeGuess(const Eigen::MatrixXd& GuessMOs ){\r\n      Eigen::MatrixXd nonortho=GuessMOs.transpose()*_dftAOoverlap.Matrix()*GuessMOs;\r\n      Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(nonortho);\r\n      Eigen::MatrixXd result=GuessMOs*es.operatorInverseSqrt();\r\n      return result;\r\n    }\r\n    \r\n  }\r\n}\r\n", "meta": {"hexsha": "9ab2a63147398c4b23e57115454c6eb2895b16af", "size": 44261, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/dftengine/dftengine.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/dftengine/dftengine.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/dftengine/dftengine.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.640655106, "max_line_length": 143, "alphanum_fraction": 0.5714737579, "num_tokens": 11946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.032589747819716665, "lm_q1q2_score": 0.016040287222997208}}
{"text": "/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"compiler/bcc/parser.h\"\n\n#include <cassert>\n#include <cctype>\n#include <cerrno>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"compiler/bcc/token.h\"\n#include \"compiler/bcc/tokenizer.h\"\n#include \"flint/bc.h\"\n\nnamespace flint {\nnamespace compiler {\nnamespace bcc {\n\nnamespace {\n\nvoid ReportUnexpectedToken(Token &t)\n{\n\tstd::cerr << \"unexpected token: \";\n\tt.Write(std::cerr) << std::endl;\n}\n\nint ConvertToInteger(const char *p, const char *q)\n{\n\tassert(p < q);\n\tint n = 0;\n\twhile (p < q) {\n\t\tn *= 10;\n\t\tchar c = *p++;\n\t\tassert('0' <= c && c <= '9');\n\t\tn += c - '0';\n\t}\n\treturn n;\n}\n\nint GetIntegerFromAddress(const Token &t)\n{\n\tassert(t.type == Token::Type::kAddress);\n\tconst char *p = t.lexeme + 1; // add offset for \"$\"\n\tconst char *q = t.lexeme + t.size;\n\treturn ConvertToInteger(p, q);\n}\n\nint GetIntegerFromLabel(const Token &t)\n{\n\tassert(t.type == Token::Type::kLabel);\n\tconst char *p = t.lexeme + 1; // add offset for \"L\"\n\tconst char *q = t.lexeme + t.size;\n\treturn ConvertToInteger(p, q);\n}\n\nint GetIntegerFromNumber(const Token &t)\n{\n\tassert(t.type == Token::Type::kNumber);\n\tconst char *p = t.lexeme;\n\tconst char *q = t.lexeme + t.size;\n\treturn ConvertToInteger(p, q);\n}\n\nint GetIntegerFromIntReg(const Token &t)\n{\n\tassert(t.type == Token::Type::kIntReg);\n\tconst char *p = t.lexeme + 2; // offset for \"$i\"\n\tconst char *q = t.lexeme + t.size; // subtract offset too\n\treturn ConvertToInteger(p, q);\n}\n\n}\n\nclass ParserImpl {\npublic:\n\texplicit ParserImpl(const char *input);\n\n\tbool Parse(Body *body);\n\nprivate:\n\tbool ParseInst(bc::Code *code);\n\tbool ParseLabelColon(int n, Body *body);\n\tbool ParseInstOp(int a, bc::Code *code);\n\tbool ParseCall1(int a, bc::Call1::Op op, bc::Code *code);\n\tbool ParseCall2(int a, bc::Call2::Op op, bc::Code *code);\n\tbool ParseGen1(int a, bc::Gen1::Type type, bc::Code *code);\n\tbool ParseGen2(int a, bc::Gen2::Type type, bc::Code *code);\n\tbool ParseFr(int *a);\n\tbool ParseInstBr(bc::Code *code);\n\tbool ParseLabel(int *n);\n\tbool ParseInstJmp(bc::Code *code);\n\tbool ParseInstLb(bc::Code *code);\n\tbool ParseInstLc(bc::Code *code);\n\tbool ParseInstLd(bc::Code *code);\n\tbool ParseInstLoad(bc::Code *code);\n\tbool ParseInstLoadi(bc::Code *code);\n\tbool ParseImm(double *d);\n\tbool ParseInstStore(bc::Code *code);\n\tbool ParseInstRefer(bc::Code *code);\n\tbool ParseIr(int *i);\n\tbool ParseInstDeref(bc::Code *code);\n\tbool ParseInstAlloc(bc::Code *code);\n\tbool ParseInstSave(bc::Code *code);\n\tbool ParseInstMove(bc::Code *code);\n\tbool ParseInstTranspose(bc::Code *code);\n\tbool ParseInstOuterproduct(bc::Code *code);\n\tbool ParseInstScalarproduct(bc::Code *code);\n\tbool ParseInstVectorproduct(bc::Code *code);\n\tbool ParseInstDeterminant(bc::Code *code);\n\tbool ParseInstSelect2(bc::Code *code);\n\tbool ParseInstSelect3(bc::Code *code);\n\tbool ParseInstSelrow(bc::Code *code);\n\tbool ParseInstMult(bc::Code *code);\n\tbool ParseInstMmul(bc::Code *code);\n\n\tbool ReadIdentifier(Token *t);\n\tbool ReadInteger(int *i);\n\tbool ReadToken(Token::Type type);\n\tbool ReadToken(Token::Type type, Token *t);\n\tbool ReadToken(Token *t);\n\tbool SkipParenClose();\n\tbool SkipSpace();\n\n\ttemplate<bc::Call1::Op op1, bc::Call2::Op op2>\n\tbool ParseCall(int a, bc::Code *code) {\n\t\tint a1;\n\t\tif (!ParseFr(&a1))\n\t\t\treturn false;\n\t\tToken t;\n\t\tif (!ReadToken(&t))\n\t\t\treturn false;\n\t\tswitch (t.type) {\n\t\tcase Token::Type::kParenClose:\n\t\t\t{\n\t\t\t\tcode->set_type(bc::Code::kCall1);\n\t\t\t\tauto *call1 = code->mutable_call1();\n\t\t\t\tcall1->set_a(a);\n\t\t\t\tcall1->set_op(op1);\n\t\t\t\tcall1->set_a1(a1);\n\t\t\t\treturn true;\n\t\t\t}\n\t\tcase Token::Type::kSpace:\n\t\t\t// one more argument\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tReportUnexpectedToken(t);\n\t\t\treturn false;\n\t\t}\n\t\tif ( !ReadToken(Token::Type::kAddress, &t) ||\n\t\t\t !SkipParenClose() )\n\t\t\treturn false;\n\t\tcode->set_type(bc::Code::kCall2);\n\t\tauto *call2 = code->mutable_call2();\n\t\tcall2->set_a(a);\n\t\tcall2->set_op(op2);\n\t\tcall2->set_a1(a1);\n\t\tcall2->set_a2(GetIntegerFromAddress(t));\n\t\treturn true;\n\t}\n\n\tvoid ReportTruncatedLine();\n\n\tTokenizer lexer_;\n};\n\nParserImpl::ParserImpl(const char *input)\n\t: lexer_(input)\n{\n\tassert(input);\n}\n\nbool ParserImpl::Parse(Body *body)\n{\n\tToken t;\n\twhile ( int r = lexer_(&t) ) {\n\t\tif (r < 0)\n\t\t\treturn false;\n\t\tif (t.type != Token::Type::kSpace) {\n\t\t\tstd::cerr << \"line starting with non-space: \";\n\t\t\tt.Write(std::cerr) << std::endl;\n\t\t\treturn false;\n\t\t}\n\t\tswitch (lexer_(&t)) {\n\t\tcase 1:\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\tReportTruncatedLine();\n\t\t\treturn false;\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\t\tswitch (t.type) {\n\t\tcase Token::Type::kSpace:\n\t\t\t{\n\t\t\t\tbc::Code code;\n\t\t\t\tif (!ParseInst(&code))\n\t\t\t\t\treturn false;\n\t\t\t\tbody->code.push_back(code);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Token::Type::kLabel:\n\t\t\tif (!ParseLabelColon(GetIntegerFromLabel(t), body))\n\t\t\t\treturn false;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tReportUnexpectedToken(t);\n\t\t\treturn false;\n\t\t}\n\t\tif (!ReadToken(Token::Type::kEol))\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool ParserImpl::ParseInst(bc::Code *code)\n{\n\tToken t;\n\tswitch (lexer_(&t)) {\n\tcase 1:\n\t\tbreak;\n\tcase 0:\n\t\tReportTruncatedLine();\n\t\treturn false;\n\tdefault:\n\t\treturn false;\n\t}\n\tswitch (t.type) {\n\tcase Token::Type::kAddress:\n\t\treturn ParseInstOp(GetIntegerFromAddress(t), code);\n\tcase Token::Type::kBr:\n\t\treturn ParseInstBr(code);\n\tcase Token::Type::kJmp:\n\t\treturn ParseInstJmp(code);\n\tcase Token::Type::kLb:\n\t\treturn ParseInstLb(code);\n\tcase Token::Type::kLc:\n\t\treturn ParseInstLc(code);\n\tcase Token::Type::kLd:\n\t\treturn ParseInstLd(code);\n\tcase Token::Type::kLoad:\n\t\treturn ParseInstLoad(code);\n\tcase Token::Type::kLoadi:\n\t\treturn ParseInstLoadi(code);\n\tcase Token::Type::kRet:\n\t\tcode->set_type(bc::Code::kRet);\n\t\treturn true;\n\tcase Token::Type::kStore:\n\t\treturn ParseInstStore(code);\n\tcase Token::Type::kRefer:\n\t\treturn ParseInstRefer(code);\n\tcase Token::Type::kDeref:\n\t\treturn ParseInstDeref(code);\n\tcase Token::Type::kAlloc:\n\t\treturn ParseInstAlloc(code);\n\tcase Token::Type::kSave:\n\t\treturn ParseInstSave(code);\n\tcase Token::Type::kMove:\n\t\treturn ParseInstMove(code);\n\tcase Token::Type::kTranspose:\n\t\treturn ParseInstTranspose(code);\n\tcase Token::Type::kOuterproduct:\n\t\treturn ParseInstOuterproduct(code);\n\tcase Token::Type::kScalarproduct:\n\t\treturn ParseInstScalarproduct(code);\n\tcase Token::Type::kVectorproduct:\n\t\treturn ParseInstVectorproduct(code);\n\tcase Token::Type::kDeterminant:\n\t\treturn ParseInstDeterminant(code);\n\tcase Token::Type::kSelect2:\n\t\treturn ParseInstSelect2(code);\n\tcase Token::Type::kSelect3:\n\t\treturn ParseInstSelect3(code);\n\tcase Token::Type::kSelrow:\n\t\treturn ParseInstSelrow(code);\n\tcase Token::Type::kMult:\n\t\treturn ParseInstMult(code);\n\tcase Token::Type::kMmul:\n\t\treturn ParseInstMmul(code);\n\tdefault:\n\t\tbreak;\n\t}\n\tReportUnexpectedToken(t);\n\treturn false;\n}\n\nbool ParserImpl::ParseLabelColon(int n, Body *body)\n{\n\tassert(n >= 0);\n\tif (body->labels.size() <= static_cast<size_t>(n))\n\t\tbody->labels.resize(n + 1);\n\tbody->labels.at(n) = static_cast<int>(body->code.size());\n\treturn ReadToken(Token::Type::kColon);\n}\n\nbool ParserImpl::ParseInstOp(int a, bc::Code *code)\n{\n\tif ( !SkipSpace() ||\n\t\t !ReadToken(Token::Type::kEqualSign) ||\n\t\t !SkipSpace() ||\n\t\t !ReadToken(Token::Type::kParenOpen) )\n\t\treturn false;\n\tToken t;\n\tswitch (lexer_(&t)) {\n\tcase 1:\n\t\tbreak;\n\tcase 0:\n\t\tReportTruncatedLine();\n\t\treturn false;\n\tdefault:\n\t\treturn false;\n\t}\n\tswitch (t.type) {\n\tcase Token::Type::kAbs:\n\t\treturn ParseCall1(a, bc::Call1::kAbs, code);\n\tcase Token::Type::kArccos:\n\t\treturn ParseCall1(a, bc::Call1::kArccos, code);\n\tcase Token::Type::kArccosh:\n\t\treturn ParseCall1(a, bc::Call1::kArccosh, code);\n\tcase Token::Type::kArccot:\n\t\treturn ParseCall1(a, bc::Call1::kArccot, code);\n\tcase Token::Type::kArccoth:\n\t\treturn ParseCall1(a, bc::Call1::kArccoth, code);\n\tcase Token::Type::kArccsc:\n\t\treturn ParseCall1(a, bc::Call1::kArccsc, code);\n\tcase Token::Type::kArccsch:\n\t\treturn ParseCall1(a, bc::Call1::kArccsch, code);\n\tcase Token::Type::kArcsec:\n\t\treturn ParseCall1(a, bc::Call1::kArcsec, code);\n\tcase Token::Type::kArcsech:\n\t\treturn ParseCall1(a, bc::Call1::kArcsech, code);\n\tcase Token::Type::kArcsin:\n\t\treturn ParseCall1(a, bc::Call1::kArcsin, code);\n\tcase Token::Type::kArcsinh:\n\t\treturn ParseCall1(a, bc::Call1::kArcsinh, code);\n\tcase Token::Type::kArctan:\n\t\treturn ParseCall1(a, bc::Call1::kArctan, code);\n\tcase Token::Type::kArctanh:\n\t\treturn ParseCall1(a, bc::Call1::kArctanh, code);\n\tcase Token::Type::kCeiling:\n\t\treturn ParseCall1(a, bc::Call1::kCeiling, code);\n\tcase Token::Type::kCos:\n\t\treturn ParseCall1(a, bc::Call1::kCos, code);\n\tcase Token::Type::kCosh:\n\t\treturn ParseCall1(a, bc::Call1::kCosh, code);\n\tcase Token::Type::kCot:\n\t\treturn ParseCall1(a, bc::Call1::kCot, code);\n\tcase Token::Type::kCoth:\n\t\treturn ParseCall1(a, bc::Call1::kCoth, code);\n\tcase Token::Type::kCsc:\n\t\treturn ParseCall1(a, bc::Call1::kCsc, code);\n\tcase Token::Type::kCsch:\n\t\treturn ParseCall1(a, bc::Call1::kCsch, code);\n\tcase Token::Type::kExp:\n\t\treturn ParseCall1(a, bc::Call1::kExp, code);\n\tcase Token::Type::kFloor:\n\t\treturn ParseCall1(a, bc::Call1::kFloor, code);\n\tcase Token::Type::kFactorial:\n\t\treturn ParseCall1(a, bc::Call1::kFactorial, code);\n\tcase Token::Type::kLn:\n\t\treturn ParseCall1(a, bc::Call1::kLn, code);\n\tcase Token::Type::kLog10:\n\t\treturn ParseCall1(a, bc::Call1::kLog10, code);\n\tcase Token::Type::kMinus: // 1 or 2 args\n\t\treturn ParseCall<bc::Call1::kMinus1, bc::Call2::kMinus2>(a, code);\n\tcase Token::Type::kRoot: // 1 or 2 args\n\t\treturn ParseCall<bc::Call1::kRoot1, bc::Call2::kRoot2>(a, code);\n\tcase Token::Type::kSec:\n\t\treturn ParseCall1(a, bc::Call1::kSec, code);\n\tcase Token::Type::kSech:\n\t\treturn ParseCall1(a, bc::Call1::kSech, code);\n\tcase Token::Type::kSin:\n\t\treturn ParseCall1(a, bc::Call1::kSin, code);\n\tcase Token::Type::kSinh:\n\t\treturn ParseCall1(a, bc::Call1::kSinh, code);\n\tcase Token::Type::kTan:\n\t\treturn ParseCall1(a, bc::Call1::kTan, code);\n\tcase Token::Type::kTanh:\n\t\treturn ParseCall1(a, bc::Call1::kTanh, code);\n\t// Call2\n\tcase Token::Type::kDivide:\n\t\treturn ParseCall2(a, bc::Call2::kDivide, code);\n\tcase Token::Type::kEq:\n\t\treturn ParseCall2(a, bc::Call2::kEq, code);\n\tcase Token::Type::kGeq:\n\t\treturn ParseCall2(a, bc::Call2::kGeq, code);\n\tcase Token::Type::kGt:\n\t\treturn ParseCall2(a, bc::Call2::kGt, code);\n\tcase Token::Type::kLeq:\n\t\treturn ParseCall2(a, bc::Call2::kLeq, code);\n\tcase Token::Type::kLog:\n\t\treturn ParseCall2(a, bc::Call2::kLog, code);\n\tcase Token::Type::kLt:\n\t\treturn ParseCall2(a, bc::Call2::kLt, code);\n\tcase Token::Type::kMax:\n\t\treturn ParseCall2(a, bc::Call2::kMax, code);\n\tcase Token::Type::kMin:\n\t\treturn ParseCall2(a, bc::Call2::kMin, code);\n\tcase Token::Type::kNeq:\n\t\treturn ParseCall2(a, bc::Call2::kNeq, code);\n\tcase Token::Type::kPlus:\n\t\treturn ParseCall2(a, bc::Call2::kPlus, code);\n\tcase Token::Type::kPower:\n\t\treturn ParseCall2(a, bc::Call2::kPower, code);\n\tcase Token::Type::kRem: // remainder\n\t\treturn ParseCall2(a, bc::Call2::kRemainder, code);\n\tcase Token::Type::kTimes:\n\t\treturn ParseCall2(a, bc::Call2::kTimes, code);\n\tcase Token::Type::kMod: // Modulo\n\t\treturn ParseCall2(a, bc::Call2::kModulo, code);\n\t// Gen1\n\tcase Token::Type::kExponentialVariate:\n\t\treturn ParseGen1(a, bc::Gen1::kExponentialVariate, code);\n\tcase Token::Type::kPoissonVariate:\n\t\treturn ParseGen1(a, bc::Gen1::kPoissonVariate, code);\n\t// Gen2\n\tcase Token::Type::kGammaVariate:\n\t\treturn ParseGen2(a, bc::Gen2::kGammaVariate, code);\n\tcase Token::Type::kGaussVariate:\n\t\treturn ParseGen2(a, bc::Gen2::kGaussVariate, code);\n\tcase Token::Type::kLognormalVariate:\n\t\treturn ParseGen2(a, bc::Gen2::kLognormalVariate, code);\n\tcase Token::Type::kUniformVariate:\n\t\treturn ParseGen2(a, bc::Gen2::kUniformVariate, code);\n\tcase Token::Type::kWeibullVariate:\n\t\treturn ParseGen2(a, bc::Gen2::kWeibullVariate, code);\n\tdefault:\n\t\tstd::cerr << \"unknown instruction: \";\n\t\tt.Write(std::cerr) << std::endl;\n\t\treturn false;\n\t}\n}\n\nbool ParserImpl::ParseCall1(int a, bc::Call1::Op op, bc::Code *code)\n{\n\tint a1;\n\tif ( ParseFr(&a1) && SkipParenClose() ) {\n\t\tcode->set_type(bc::Code::kCall1);\n\t\tauto *call1 = code->mutable_call1();\n\t\tcall1->set_a(a);\n\t\tcall1->set_op(op);\n\t\tcall1->set_a1(a1);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseCall2(int a, bc::Call2::Op op, bc::Code *code)\n{\n\tint a1, a2;\n\tif ( ParseFr(&a1) && ParseFr(&a2) && SkipParenClose() ) {\n\t\tcode->set_type(bc::Code::kCall2);\n\t\tauto *call2 = code->mutable_call2();\n\t\tcall2->set_a(a);\n\t\tcall2->set_op(op);\n\t\tcall2->set_a1(a1);\n\t\tcall2->set_a2(a2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseGen1(int a, bc::Gen1::Type type, bc::Code *code)\n{\n\tint a1;\n\tif ( ParseFr(&a1) && SkipParenClose() ) {\n\t\tcode->set_type(bc::Code::kGen1);\n\t\tauto *gen1 = code->mutable_gen1();\n\t\tgen1->set_a(a);\n\t\tgen1->set_type(type);\n\t\tgen1->set_a1(a1);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseGen2(int a, bc::Gen2::Type type, bc::Code *code)\n{\n\tint a1, a2;\n\tif ( ParseFr(&a1) && ParseFr(&a2) && SkipParenClose() ) {\n\t\tcode->set_type(bc::Code::kGen2);\n\t\tauto *gen2 = code->mutable_gen2();\n\t\tgen2->set_a(a);\n\t\tgen2->set_type(type);\n\t\tgen2->set_a1(a1);\n\t\tgen2->set_a2(a2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseFr(int *a)\n{\n\tToken t;\n\tif ( SkipSpace() && ReadToken(Token::Type::kAddress, &t) ) {\n\t\t*a = GetIntegerFromAddress(t);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstBr(bc::Code *code)\n{\n\tint a, n;\n\tif ( ParseFr(&a) && ParseLabel(&n) ) {\n\t\tcode->set_type(bc::Code::kBr);\n\t\tauto *br = code->mutable_br();\n\t\tbr->set_a(a);\n\t\tbr->set_l(n);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseLabel(int *n)\n{\n\tToken t;\n\tif ( SkipSpace() && ReadToken(Token::Type::kLabel, &t) ) {\n\t\t*n = GetIntegerFromLabel(t);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstJmp(bc::Code *code)\n{\n\tint n;\n\tif (ParseLabel(&n)) {\n\t\tcode->set_type(bc::Code::kJmp);\n\t\tauto *jmp = code->mutable_jmp();\n\t\tjmp->set_l(n);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstLb(bc::Code *code)\n{\n\tint a, d;\n\tToken t;\n\tif ( ParseFr(&a) &&\n\t\t SkipSpace() && ReadIdentifier(&t) &&\n\t\t ParseFr(&d) ) {\n\t\tcode->set_type(bc::Code::kLb);\n\t\tauto *lb = code->mutable_lb();\n\t\tlb->set_a(a);\n\t\tlb->set_v(t.lexeme, t.size);\n\t\tlb->set_d(d);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstLc(bc::Code *code)\n{\n\tint a, i0, d;\n\tif ( ParseFr(&a) &&\n\t\t SkipSpace() && ReadInteger(&i0) &&\n\t\t ParseFr(&d) ) {\n\t\tcode->set_type(bc::Code::kLc);\n\t\tauto *lc = code->mutable_lc();\n\t\tlc->set_a(a);\n\t\tlc->set_i0(i0);\n\t\tlc->set_d(d);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstLd(bc::Code *code)\n{\n\tint a, i0, i1, d;\n\tif ( ParseFr(&a) &&\n\t\t SkipSpace() && ReadInteger(&i0) &&\n\t\t SkipSpace() && ReadInteger(&i1) &&\n\t\t ParseFr(&d) ) {\n\t\tcode->set_type(bc::Code::kLd);\n\t\tauto *ld = code->mutable_ld();\n\t\tld->set_a(a);\n\t\tld->set_i0(i0);\n\t\tld->set_i1(i1);\n\t\tld->set_d(d);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstLoad(bc::Code *code)\n{\n\tint a;\n\tToken t;\n\tif ( ParseFr(&a) &&\n\t\t SkipSpace() && ReadIdentifier(&t) ) {\n\t\tcode->set_type(bc::Code::kLoad);\n\t\tauto *load = code->mutable_load();\n\t\tload->set_a(a);\n\t\tload->set_v(t.lexeme, t.size); // TODO\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstLoadi(bc::Code *code)\n{\n\tint a;\n\tdouble v;\n\tif ( ParseFr(&a) && ParseImm(&v) ) {\n\t\tcode->set_type(bc::Code::kLoadi);\n\t\tauto *loadi = code->mutable_loadi();\n\t\tloadi->set_a(a);\n\t\tloadi->set_v(v);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseImm(double *d)\n{\n\tif (!SkipSpace())\n\t\treturn false;\n\tToken t;\n\tif (!ReadToken(&t))\n\t\treturn false;\n\tswitch (t.type) {\n\tcase Token::Type::kEulergamma:\n\t\t*d = boost::math::constants::euler<double>();\n\t\treturn true;\n\tcase Token::Type::kExponentiale:\n\t\t*d = boost::math::constants::e<double>();\n\t\treturn true;\n\tcase Token::Type::kPi:\n\t\t*d = boost::math::constants::pi<double>();\n\t\treturn true;\n\tcase Token::Type::kTrue:\n\t\t*d = 1;\n\t\treturn true;\n\tcase Token::Type::kFalse:\n\t\t*d = 0;\n\t\treturn true;\n\tcase Token::Type::kNumber:\n\t\t{\n\t\t\tconst char *c = std::strpbrk(t.lexeme, \"/\\n\");\n\t\t\tif ( c && *c == '/' ) { // rationals\n\t\t\t\tdouble num = std::atof(t.lexeme);\n\t\t\t\tif (num == HUGE_VAL) {\n\t\t\t\t\tstd::cerr << \"numerator is out of range: \";\n\t\t\t\t\tt.Write(std::cerr) << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tdouble den = std::atof(++c);\n\t\t\t\tif (den == HUGE_VAL) {\n\t\t\t\t\tstd::cerr << \"denominator is out of range: \";\n\t\t\t\t\tt.Write(std::cerr) << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (den == 0) {\n\t\t\t\t\tstd::cerr << \"invalid denominator: \";\n\t\t\t\t\tt.Write(std::cerr) << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t*d = num/den;\n\t\t\t} else {\n\t\t\t\t*d = std::atof(t.lexeme);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\tdefault:\n\t\tstd::cerr << \"immediate value expected, but got: \";\n\t\tt.Write(std::cerr) << std::endl;\n\t\treturn false;\n\t}\n}\n\nbool ParserImpl::ParseInstStore(bc::Code *code)\n{\n\tToken t;\n\tint a;\n\tif ( SkipSpace() && ReadIdentifier(&t) &&\n\t\t ParseFr(&a) ) {\n\t\tcode->set_type(bc::Code::kStore);\n\t\tauto *store = code->mutable_store();\n\t\tstore->set_v(t.lexeme, t.size);\n\t\tstore->set_a(a);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstRefer(bc::Code *code)\n{\n\tint i0;\n\tToken t;\n\tif ( ParseIr(&i0) &&\n\t\t SkipSpace() && ReadIdentifier(&t) ) {\n\t\tcode->set_type(bc::Code::kRefer);\n\t\tauto *x = code->mutable_refer();\n\t\tx->set_i0(i0);\n\t\tx->set_v(t.lexeme, t.size);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseIr(int *i)\n{\n\tToken t;\n\tif ( SkipSpace() && ReadToken(Token::Type::kIntReg, &t) ) {\n\t\t*i = GetIntegerFromIntReg(t);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstDeref(bc::Code *code)\n{\n\tint f0, i1, k;\n\tif ( ParseFr(&f0) &&\n\t\t ParseIr(&i1) &&\n\t\t SkipSpace() && ReadInteger(&k) ) {\n\t\tcode->set_type(bc::Code::kDeref);\n\t\tauto *x = code->mutable_deref();\n\t\tx->set_f0(f0);\n\t\tx->set_i1(i1);\n\t\tx->set_k(k);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstAlloc(bc::Code *code)\n{\n\tint i0, k;\n\tif ( ParseIr(&i0) &&\n\t\t SkipSpace() && ReadInteger(&k) ) {\n\t\tcode->set_type(bc::Code::kAlloc);\n\t\tauto *x = code->mutable_alloc();\n\t\tx->set_i0(i0);\n\t\tx->set_k(k);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstSave(bc::Code *code)\n{\n\tint i1, k;\n\tToken t;\n\tif ( SkipSpace() && ReadIdentifier(&t) &&\n\t\t ParseIr(&i1) &&\n\t\t SkipSpace() && ReadInteger(&k) ) {\n\t\tcode->set_type(bc::Code::kSave);\n\t\tauto *x = code->mutable_save();\n\t\tx->set_v(t.lexeme, t.size);\n\t\tx->set_i1(i1);\n\t\tx->set_k(k);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstMove(bc::Code *code)\n{\n\tint i0, f1, k;\n\tif ( ParseIr(&i0) &&\n\t\t ParseFr(&f1) &&\n\t\t SkipSpace() && ReadInteger(&k) ) {\n\t\tcode->set_type(bc::Code::kMove);\n\t\tauto *x = code->mutable_move();\n\t\tx->set_i0(i0);\n\t\tx->set_f1(f1);\n\t\tx->set_k(k);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstTranspose(bc::Code *code)\n{\n\tint i0, i1, kr, kc;\n\tif ( ParseIr(&i0) &&\n\t\t ParseIr(&i1) &&\n\t\t SkipSpace() && ReadInteger(&kr) &&\n\t\t SkipSpace() && ReadInteger(&kc) ) {\n\t\tcode->set_type(bc::Code::kTranspose);\n\t\tauto *x = code->mutable_transpose();\n\t\tx->set_i0(i0);\n\t\tx->set_i1(i1);\n\t\tx->set_kc(kc);\n\t\tx->set_kr(kr);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstOuterproduct(bc::Code *code)\n{\n\tint i0, k1, i1, k2, i2;\n\tif ( ParseIr(&i0) &&\n\t\t SkipSpace() && ReadInteger(&k1) &&\n\t\t ParseIr(&i1) &&\n\t\t SkipSpace() && ReadInteger(&k2) &&\n\t\t ParseIr(&i2) ) {\n\t\tcode->set_type(bc::Code::kOuterproduct);\n\t\tauto *x = code->mutable_outerproduct();\n\t\tx->set_i0(i0);\n\t\tx->set_k1(k1);\n\t\tx->set_i1(i1);\n\t\tx->set_k2(k2);\n\t\tx->set_i2(i2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstScalarproduct(bc::Code *code)\n{\n\tint f0, k, i1, i2;\n\tif ( ParseFr(&f0) &&\n\t\t SkipSpace() && ReadInteger(&k) &&\n\t\t ParseIr(&i1) &&\n\t\t ParseIr(&i2) ) {\n\t\tcode->set_type(bc::Code::kScalarproduct);\n\t\tauto *x = code->mutable_scalarproduct();\n\t\tx->set_f0(f0);\n\t\tx->set_k(k);\n\t\tx->set_i1(i1);\n\t\tx->set_i2(i2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstVectorproduct(bc::Code *code)\n{\n\tint i0, i1, i2;\n\tif ( ParseIr(&i0) && ParseIr(&i1) && ParseIr(&i2) ) {\n\t\tcode->set_type(bc::Code::kVectorproduct);\n\t\tauto *x = code->mutable_vectorproduct();\n\t\tx->set_i0(i0);\n\t\tx->set_i1(i1);\n\t\tx->set_i2(i2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstDeterminant(bc::Code *code)\n{\n\tint f0, k, i1;\n\tif ( ParseFr(&f0) &&\n\t\t SkipSpace() && ReadInteger(&k) &&\n\t\t ParseIr(&i1) ) {\n\t\tcode->set_type(bc::Code::kDeterminant);\n\t\tauto *x = code->mutable_determinant();\n\t\tx->set_f0(f0);\n\t\tx->set_k(k);\n\t\tx->set_i1(i1);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstSelect2(bc::Code *code)\n{\n\tint f0, i1, f2;\n\tif ( ParseFr(&f0) && ParseIr(&i1) && ParseFr(&f2) ) {\n\t\tcode->set_type(bc::Code::kSelect2);\n\t\tauto *x = code->mutable_select2();\n\t\tx->set_f0(f0);\n\t\tx->set_i1(i1);\n\t\tx->set_f2(f2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstSelect3(bc::Code *code)\n{\n\tint f0, kr, kc, i1, f2, f3;\n\tif ( ParseFr(&f0) &&\n\t\t SkipSpace() && ReadInteger(&kr) &&\n\t\t SkipSpace() && ReadInteger(&kc) &&\n\t\t ParseIr(&i1) &&\n\t\t ParseFr(&f2) &&\n\t\t ParseFr(&f3) ) {\n\t\tcode->set_type(bc::Code::kSelect3);\n\t\tauto *x = code->mutable_select3();\n\t\tx->set_f0(f0);\n\t\tx->set_kc(kc);\n\t\tx->set_kr(kr);\n\t\tx->set_i1(i1);\n\t\tx->set_f2(f2);\n\t\tx->set_f3(f3);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstSelrow(bc::Code *code)\n{\n\tint i0, kr, kc, i1, f2;\n\tif ( ParseIr(&i0) &&\n\t\t SkipSpace() && ReadInteger(&kr) &&\n\t\t SkipSpace() && ReadInteger(&kc) &&\n\t\t ParseIr(&i1) &&\n\t\t ParseFr(&f2) ) {\n\t\tcode->set_type(bc::Code::kSelrow);\n\t\tauto *x = code->mutable_selrow();\n\t\tx->set_i0(i0);\n\t\tx->set_kc(kc);\n\t\tx->set_kr(kr);\n\t\tx->set_i1(i1);\n\t\tx->set_f2(f2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstMult(bc::Code *code)\n{\n\tint i0, k, f1, i2;\n\tif ( ParseIr(&i0) &&\n\t\t SkipSpace() && ReadInteger(&k) &&\n\t\t ParseFr(&f1) &&\n\t\t ParseIr(&i2) ) {\n\t\tcode->set_type(bc::Code::kMult);\n\t\tauto *x = code->mutable_mult();\n\t\tx->set_i0(i0);\n\t\tx->set_k(k);\n\t\tx->set_f1(f1);\n\t\tx->set_i2(i2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ParseInstMmul(bc::Code *code)\n{\n\tint i0, kr, kx, kc, i1, i2;\n\tif ( ParseIr(&i0) &&\n\t\t SkipSpace() && ReadInteger(&kr) &&\n\t\t SkipSpace() && ReadInteger(&kx) &&\n\t\t SkipSpace() && ReadInteger(&kc) &&\n\t\t ParseIr(&i1) &&\n\t\t ParseIr(&i2) ) {\n\t\tcode->set_type(bc::Code::kMmul);\n\t\tauto *x = code->mutable_mmul();\n\t\tx->set_i0(i0);\n\t\tx->set_kr(kr);\n\t\tx->set_kx(kx);\n\t\tx->set_kc(kc);\n\t\tx->set_i1(i1);\n\t\tx->set_i2(i2);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ReadIdentifier(Token *t)\n{\n\treturn ReadToken(Token::Type::kIdentifier, t);\n}\n\nbool ParserImpl::ReadInteger(int *i)\n{\n\tToken t;\n\tif (ReadToken(Token::Type::kNumber, &t)) {\n\t\t*i = GetIntegerFromNumber(t);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool ParserImpl::ReadToken(Token::Type type)\n{\n\tToken t;\n\treturn ReadToken(type, &t);\n}\n\nbool ParserImpl::ReadToken(Token::Type type, Token *t)\n{\n\tif (!ReadToken(t))\n\t\treturn false;\n\tif (t->type == type)\n\t\treturn true;\n\tstd::cerr << \"expected token of type \"\n\t\t\t  << static_cast<int>(type)\n\t\t\t  << \", but got: \";\n\tt->Write(std::cerr) << std::endl;\n\treturn false;\n}\n\nbool ParserImpl::ReadToken(Token *t)\n{\n\tswitch (lexer_(t)) {\n\tcase 1:\n\t\treturn true;\n\tcase 0:\n\t\tReportTruncatedLine();\n\t\treturn false;\n\tdefault:\n\t\treturn false;\n\t}\n}\n\nbool ParserImpl::SkipParenClose()\n{\n\treturn ReadToken(Token::Type::kParenClose);\n}\n\nbool ParserImpl::SkipSpace()\n{\n\treturn ReadToken(Token::Type::kSpace);\n}\n\nvoid ParserImpl::ReportTruncatedLine()\n{\n\tstd::cerr << \"truncated line: \";\n\tlexer_.Dump(std::cerr) << std::endl;\n}\n\n\nParser::Parser(const char *input)\n\t: impl_(new ParserImpl(input))\n{\n\tassert(input);\n}\n\nParser::~Parser() = default;\n\nbool Parser::operator()(Body *body)\n{\n\tassert(body);\n\treturn impl_->Parse(body);\n}\n\n}\n}\n}\n", "meta": {"hexsha": "0f75267cb32a79d66f81aa03794fc6fc24bac855", "size": 23789, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/compiler/bcc/parser.cc", "max_stars_repo_name": "Abhisheknishant/Flint", "max_stars_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-09-07T05:33:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T03:35:08.000Z", "max_issues_repo_path": "src/compiler/bcc/parser.cc", "max_issues_repo_name": "Abhisheknishant/Flint", "max_issues_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T02:10:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T08:20:51.000Z", "max_forks_repo_path": "src/compiler/bcc/parser.cc", "max_forks_repo_name": "Abhisheknishant/Flint", "max_forks_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-03-26T00:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T23:21:42.000Z", "avg_line_length": 22.7211079274, "max_line_length": 107, "alphanum_fraction": 0.6480726386, "num_tokens": 7863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.03308597934211908, "lm_q1q2_score": 0.0160261894621222}}
{"text": "// This file is part of sibilla : inference in epidemics with Belief Propagation\n// Author: Alfredo Braunstein\n\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl_bind.h>\n#include <pybind11/stl.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pytypes.h>\n#include <pybind11/iostream.h>\n#include <string>\n#include <sstream>\n#include <numeric>\n#include <boost/lexical_cast.hpp>\n#include <iterator>\n#include <exception>\n#include \"bp.h\"\n#include \"drop.h\"\n\n\nPYBIND11_MAKE_OPAQUE(std::valarray<real_t>);\nPYBIND11_MAKE_OPAQUE(std::vector<real_t>);\nPYBIND11_MAKE_OPAQUE(std::vector<int>);\nPYBIND11_MAKE_OPAQUE(std::vector<Node>);\n\nnamespace py = pybind11;\nusing namespace std;\nusing boost::lexical_cast;\n\n\n\n\n\nvector<real_t> make_vector(py::list & l)\n{\n    vector<real_t> v(l.size());\n    int i = 0;\n    for (py::handle o : l) {\n        v[i++] = py::cast<real_t>(o);\n    }\n    return v;\n}\n\nmap<int, vector<times_t> >\nget_times(FactorGraph const & f) {\n        map<int, vector<times_t> > times;\n        for (int i = 0; i < int(f.nodes.size()); ++i) {\n            times[i] = f.nodes[i].times;\n            times[i].pop_back();\n        }\n        return times;\n}\n\nvector<tuple<real_t, real_t, real_t>>\nget_marginal(Node const & n)\n{\n        vector<real_t> rbt(n.bt.size());\n        vector<real_t> lbg(n.bg.size());\n        int const T = n.bt.size() - 1;\n        lbg[0] = n.bg[0];\n        rbt[T] = n.bt[T];\n        for (int t = 1; t <= T; ++t) {\n            lbg[t] = lbg[t-1] + n.bg[t];\n            rbt[T - t] = rbt[T - t + 1] + n.bt[T - t];\n        }\n        auto marg = vector<tuple<real_t, real_t, real_t>>(T-1);\n        for (int t = 1; t < T; ++t)\n            marg[t-1] = make_tuple(rbt[t], 1-rbt[t]-lbg[t-1], lbg[t-1]);\n        return marg;\n}\n\ntuple<real_t, real_t, real_t> get_marginal_index(Node const & n, int t)\n{\n        if (t < 0 || t >= int(n.bt.size()) - 2)\n            throw py::key_error(\"Time out of range\");\n        return get_marginal(n)[t];\n}\n\n\n\nvoid check_index(FactorGraph const & G, int i)\n{\n        if (i < 0 || i >= int(G.nodes.size()))\n                throw invalid_argument(\"unexistent index\");\n\n}\n\n\ntemplate<int i>\nreal_t mygetter(Proba & p)\n{\n    return p.theta[i];\n}\n\ntemplate<int i>\nvoid mysetter(Proba & p, real_t x)\n{\n    p.theta[i] = x;\n}\n\nPYBIND11_MODULE(_sib, m) {\n    py::class_<RealParams>(m, \"RealParams\", py::buffer_protocol())\n        .def(py::init([](py::buffer const b) {\n                py::buffer_info info = b.request();\n                if (info.format != py::format_descriptor<real_t>::format() || info.ndim != 1)\n                throw std::runtime_error(\"Incompatible buffer format!\");\n\n                auto v = new RealParams(info.shape[0]);\n                memcpy(&(*v)[0], info.ptr, sizeof(real_t) * (size_t) (v->size()));\n                return v;\n                }))\n        .def(py::init([](vector<real_t> const & p)->RealParams {return RealParams(&p[0], p.size());}))\n        .def(py::init([](py::list & l)->RealParams {auto v = make_vector(l); return RealParams(&v[0], v.size());}))\n        .def_buffer([](RealParams &p) -> py::buffer_info {\n            return py::buffer_info(\n                &p[0],                               /* Pointer to buffer */\n                sizeof(real_t),                          /* Size of one scalar */\n                py::format_descriptor<real_t>::format(), /* Python struct-style format descriptor */\n                1,                                      /* Number of dimensions */\n                { p.size() },                 /* Buffer dimensions */\n                { sizeof(real_t) }             /* Strides (in bytes) for each index */\n                );\n        })\n        .def(\"__add__\", [](RealParams & p, RealParams & q)->RealParams { return p + q; })\n        .def(\"__getitem__\", [](const RealParams &p, ssize_t i) {\n                if (i > int(p.size()))\n                    throw py::index_error();\n                return p[i];\n                })\n        .def(\"__setitem__\", [](RealParams &p, ssize_t i, real_t v) {\n                if (i > int(p.size()))\n                    throw py::index_error();\n                p[i] = v;\n                })\n        .def(\"__repr__\", [](RealParams &p) {\n                    string s = \"RealParams([\";\n                    for (size_t i = 0; i < p.size(); ++i)\n                        s += (i ? \",\":\"\") + lexical_cast<string>(p[i]);\n                    s+=\"])\";\n                    return s;\n                });\n    // py::add_ostream_redirect(m, \"ostream_redirect\");\n    py::bind_vector<std::vector<int>>(m, \"VectorInt\");\n    py::bind_vector<std::vector<real_t>>(m, \"VectorReal\");\n    py::bind_vector<std::vector<Node>>(m, \"VectorNode\");\n\n    py::class_<Test, shared_ptr<Test>>(m, \"Test\")\n        .def(py::init<real_t,real_t,real_t>(), py::arg(\"ps\")=0.0, py::arg(\"pi\")=0.0, py::arg(\"pr\")=0.0)\n        .def(py::init([](int s)->Test{return Test(s==0, s==1, s==2);}))\n        .def(\"__repr__\", &lexical_cast<string, Test>)\n        .def_readwrite(\"ps\", &Test::ps, \"probability of S\")\n        .def_readwrite(\"pi\", &Test::pi, \"probability of I\")\n        .def_readwrite(\"pr\", &Test::pr, \"probability of R\");\n\n    py::class_<Proba, shared_ptr<Proba>>(m, \"Proba\")\n        .def(\"__call__\", [](Proba const & p, real_t d) { return p(d); } )\n        .def(\"grad\", [](Proba const & p, real_t d) { RealParams dtheta(0.0, p.theta.size()); p.grad(dtheta, d); return dtheta;} )\n        .def(\"__repr__\", &lexical_cast<string, Proba>)\n        .def_readwrite(\"theta\", &Proba::theta);\n\n    py::class_<Uniform, Proba, shared_ptr<Uniform>>(m, \"Uniform\")\n        .def(py::init<real_t>(), py::arg(\"p\") = 1.0)\n        .def_property(\"p\", &mygetter<0>, &mysetter<0>);\n\n    py::class_<Exponential, Proba, shared_ptr<Exponential>>(m, \"Exponential\")\n        .def(py::init<real_t>(), py::arg(\"mu\") = 0.1)\n        .def_property(\"mu\", &mygetter<0>, &mysetter<0>);\n\n    py::class_<Gamma, Proba, shared_ptr<Gamma>>(m, \"Gamma\")\n        .def(py::init<real_t, real_t>(), py::arg(\"k\") = 1.0, py::arg(\"mu\") = 0.1)\n        .def_property(\"k\", &mygetter<0>, &mysetter<0>)\n        .def_property(\"mu\", &mygetter<1>, &mysetter<1>);\n\n    py::class_<ConstantRate, Proba, shared_ptr<ConstantRate>>(m, \"ConstantRate\")\n        .def(py::init<real_t, real_t>(), py::arg(\"gamma\") = 1.0, py::arg(\"Dt\") = 1.0)\n        .def_property(\"gamma\", &mygetter<0>, &mysetter<0>)\n        .def_property(\"Dt\", [](ConstantRate & p){ return p.Dt; }, [](ConstantRate & p, real_t Dt) { p.Dt = Dt; });\n\n    py::class_<UnnormalizedGammaPDF, Proba, shared_ptr<UnnormalizedGammaPDF>>(m, \"UnnormalizedGammaPDF\")\n        .def(py::init<real_t, real_t>(), py::arg(\"k\") = 1.0, py::arg(\"mu\") = 0.1)\n        .def_property(\"k\", &mygetter<0>, &mysetter<0>)\n        .def_property(\"mu\", &mygetter<1>, &mysetter<1>);\n    py::class_<PiecewiseLinear, Proba, shared_ptr<PiecewiseLinear>>(m, \"PiecewiseLinear\")\n        .def(py::init<RealParams const &, real_t>(), py::arg(\"theta\"), py::arg(\"step\") = 1.0)\n        .def(py::init<Proba const &, int, real_t>(), py::arg(\"prob\"), py::arg(\"num\"), py::arg(\"step\") = 1.0);\n\n    py::class_<Cached, Proba, shared_ptr<Cached>>(m, \"Cached\")\n        .def(py::init<std::shared_ptr<Proba> const &, int>(), py::arg(\"prob\"), py::arg(\"T\"))\n        .def_property(\"theta\", &Cached::get_theta, &Cached::set_theta);\n\n    py::class_<Scaled, Proba, shared_ptr<Scaled>>(m, \"Scaled\")\n        .def(py::init<std::shared_ptr<Proba> const &, real_t>(), py::arg(\"prob\"), py::arg(\"scale\") = 1.0);\n\n    py::class_<PDF, Proba, shared_ptr<PDF>>(m, \"PDF\")\n        .def(py::init<std::shared_ptr<Proba> const &>());\n\n\n    py::class_<Params>(m, \"Params\")\n        .def(py::init<shared_ptr<Proba> const &, shared_ptr<Proba> const &, real_t, real_t, real_t, real_t>(),\n                \"SIB Params class. prob_i and prob_r parameters are defaults.\",\n                py::arg(\"prob_i\") = *new Uniform(1.0),\n                py::arg(\"prob_r\") = *new Exponential(0.1),\n                py::arg(\"pseed\") = 0.01,\n                py::arg(\"psus\") = 0.5,\n                py::arg(\"pautoinf\") = 0.0,\n                py::arg(\"learn_rate\") = 0.0)\n\n        .def_readwrite(\"prob_r\", &Params::prob_r)\n        .def_readwrite(\"prob_i\", &Params::prob_i)\n        .def_readonly(\"fakeobs\", &Params::fakeobs)\n        .def_readwrite(\"pseed\", &Params::pseed)\n        .def_readwrite(\"psus\", &Params::psus)\n        .def_readwrite(\"pautoinf\", &Params::pautoinf)\n        .def_readwrite(\"learn_rate\", &Params::learn_rate)\n        .def(\"__repr__\", &lexical_cast<string, Params>);\n\n    py::class_<FactorGraph>(m, \"FactorGraph\", \"SIB class representing the graphical model of the epidemics\")\n        .def(py::init<Params const &,\n                vector<tuple<int,int,times_t,real_t>>,\n                vector<tuple<int,shared_ptr<Test>,times_t>>,\n                vector<tuple<int,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>>>\n                >(),\n                py::arg(\"params\") = Params(shared_ptr<Proba>(new Uniform(1.0)), shared_ptr<Proba>(new Exponential(0.5)), 0.1, 0.45, 0.0, 0.0),\n                py::arg(\"contacts\") = vector<tuple<int,int,times_t,real_t>>(),\n                py::arg(\"tests\") = vector<tuple<int,shared_ptr<Test>,times_t>>(),\n                py::arg(\"individuals\") = vector<tuple<int,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>>>())\n        .def(\"update\", &FactorGraph::iteration,\n                py::arg(\"damping\") = 0.0,\n                py::arg(\"learn\") = false,\n                \"perform one iteration\")\n        .def(\"loglikelihood\", &FactorGraph::loglikelihood, \"compute the bethe log-likelihood\")\n        .def(\"__repr__\", &lexical_cast<string, FactorGraph>)\n        .def(\"append_contact\", (void (FactorGraph::*)(int,int,times_t,real_t,real_t)) &FactorGraph::append_contact,\n                py::arg(\"i\"),\n                py::arg(\"j\"),\n                py::arg(\"t\"),\n                py::arg(\"lambdaij\"),\n                py::arg(\"lambdaji\") = real_t(FactorGraph::DO_NOT_OVERWRITE),\n                \"appends a new contact from i to j at time t with transmission probabilities lambdaij, lambdaji\")\n        .def(\"reset_observations\", &FactorGraph::reset_observations,\n                py::arg(\"obs\"),\n                \"resets all observations\")\n        .def(\"append_observation\", (void (FactorGraph::*)(int,int,times_t)) &FactorGraph::append_observation,\n                py::arg(\"i\"),\n                py::arg(\"s\"),\n                py::arg(\"t\"),\n                \"adds a new observation state s to node i at time t\")\n        .def(\"append_observation\", (void (FactorGraph::*)(int,shared_ptr<Test> const &,times_t)) &FactorGraph::append_observation,\n                py::arg(\"i\"),\n                py::arg(\"o\"),\n                py::arg(\"t\"),\n                \"adds a new test o to node i at time t\")\n        .def(\"show\", &FactorGraph::show_graph)\n        .def(\"drop_contacts\", &FactorGraph::drop_contacts, \"drop contacts at time t (first time)\")\n        .def(\"drop_time\", &drop_time, \"drop time t (first time)\")\n        .def(\"drop_sc\", &drop_sc,\n                py::arg(\"t\"),\n                py::arg(\"maxit_bp\") = 1,\n                py::arg(\"tol_bp\") = 1e-3,\n                py::arg(\"damping_bp\") = 0.0,\n                py::arg(\"maxit_sc\") = 20,\n                py::arg(\"tol_sc\") = 1e-3,\n                py::arg(\"damping_sc\") = 0.1,\n                \"drop contacts at time t (first time), adjusting fields\")\n\n        .def(\"showmsg\", [](FactorGraph & f){f.show_msg(std::cout);}, \"show messages for debugging\")\n        .def_readonly(\"nodes\", &FactorGraph::nodes, \"all nodes in this FactorGraph\")\n        .def_readonly(\"params\", &FactorGraph::params, \"parameters\");\n\n    py::class_<Node>(m, \"Node\", \"SIB class representing an individual\")\n        .def(\"marginal\", &get_marginal, \"compute marginal probabilities (pS,pI,pR) corresponding to times n.times[1:]\")\n        .def(\"marginal_index\", &get_marginal_index, \"marginal at a given time (excluding time -1)\")\n        .def_readwrite(\"ht\", &Node::ht, \"external prior on ti\")\n        .def_readwrite(\"hg\", &Node::hg, \"external prior on gi\")\n        .def_readonly(\"bt\", &Node::bt, \"belief on ti\")\n        .def_readonly(\"bg\", &Node::bg, \"belief on gi\")\n        .def_readonly(\"err\", &Node::err_, \"error on update\")\n        .def_readonly(\"df_i\", &Node::df_i, \"gradient on prior_i params\")\n        .def_readonly(\"df_r\", &Node::df_r, \"gradient on prior_r params\")\n        .def_readonly(\"times\", &Node::times, \"event times of this node\")\n        .def_readonly(\"index\", &Node::index, \"node index (deprecated, do not use)\")\n        .def_readonly(\"prob_i\", &Node::prob_i, \"probability of infection as function of t-ti\")\n        .def_readonly(\"prob_r\", &Node::prob_r, \"cumulative probability of recovery P(tr>t)\")\n        .def_readonly(\"prob_i0\", &Node::prob_i0, \"probability of infection as function of t-ti for ti=0\")\n        .def_readonly(\"prob_r0\", &Node::prob_r0, \"cumulative probability of recovery P(tr>t) for ti=0\");\n\n    m.def(\"set_num_threads\", &omp_set_num_threads, \"sets the maximum number of simultaneous cpu threads\");\n    m.def(\"version\", [](){return VERSION;}, \"compiled version of sib\");\n}\n", "meta": {"hexsha": "4bf6686a38fc408ad56056591dc6a3f6b76e1581", "size": 13108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pysib.cpp", "max_stars_repo_name": "sibyl-team/sib", "max_stars_repo_head_hexsha": "0c19f17dd4d0d8e86aceee0e3dfe6a14d8610cc9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T07:23:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T17:02:42.000Z", "max_issues_repo_path": "pysib.cpp", "max_issues_repo_name": "sibyl-team/sib", "max_issues_repo_head_hexsha": "0c19f17dd4d0d8e86aceee0e3dfe6a14d8610cc9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pysib.cpp", "max_forks_repo_name": "sibyl-team/sib", "max_forks_repo_head_hexsha": "0c19f17dd4d0d8e86aceee0e3dfe6a14d8610cc9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-04T12:45:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T10:00:03.000Z", "avg_line_length": 45.2, "max_line_length": 142, "alphanum_fraction": 0.5569118096, "num_tokens": 3777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.033589508431438486, "lm_q1q2_score": 0.016008076207655354}}
{"text": "// g2o - General Graph Optimization\n// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n//   notice, this list of conditions and the following disclaimer in the\n//   documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"sparse_optimizer.h\"\n#include <Eigen/LU>\n#include <fstream>\n#include <iomanip>\n#include <chrono>\n\n#include \"../stuff/timeutil.h\"\n#include \"../stuff/macros.h\"\n#include \"../stuff/misc.h\"\n\nnamespace g2o {\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename Traits>\nBlockSolver<Traits>::BlockSolver(LinearSolverType* linearSolver) :\n  BlockSolverBase(),\n  _linearSolver(linearSolver)\n{\n  // workspace\n  _Hpp=0;\n  _Hll=0;\n  _Hpl=0;\n  _HplCCS = 0;\n  _HschurTransposedCCS = 0;\n  _Hschur=0;\n  _DInvSchur=0;\n  _coefficients=0;\n  _bschur = 0;\n  _xSize=0;\n  _numPoses=0;\n  _numLandmarks=0;\n  _sizePoses=0;\n  _sizeLandmarks=0;\n  _doSchur=true;\n}\n\ntemplate <typename Traits>\nvoid BlockSolver<Traits>::resize(int* blockPoseIndices, int numPoseBlocks, \n              int* blockLandmarkIndices, int numLandmarkBlocks,\n              int s)\n{\n  deallocate();\n\n  resizeVector(s);\n\n  if (_doSchur) {\n    // the following two are only used in schur\n    assert(_sizePoses > 0 && \"allocating with wrong size\");\n    _coefficients = new double [s];\n    _bschur = new double[_sizePoses];\n  }\n\n  _Hpp=new PoseHessianType(blockPoseIndices, blockPoseIndices, numPoseBlocks, numPoseBlocks);\n  if (_doSchur) {\n    _Hschur=new PoseHessianType(blockPoseIndices, blockPoseIndices, numPoseBlocks, numPoseBlocks);\n    _Hll=new LandmarkHessianType(blockLandmarkIndices, blockLandmarkIndices, numLandmarkBlocks, numLandmarkBlocks);\n    _DInvSchur = new SparseBlockMatrixDiagonal<LandmarkMatrixType>(_Hll->colBlockIndices());\n    _Hpl=new PoseLandmarkHessianType(blockPoseIndices, blockLandmarkIndices, numPoseBlocks, numLandmarkBlocks);\n    _HplCCS = new SparseBlockMatrixCCS<PoseLandmarkMatrixType>(_Hpl->rowBlockIndices(), _Hpl->colBlockIndices());\n    _HschurTransposedCCS = new SparseBlockMatrixCCS<PoseMatrixType>(_Hschur->colBlockIndices(), _Hschur->rowBlockIndices());\n#ifdef G2O_OPENMP\n    _coefficientsMutex.resize(numPoseBlocks);\n#endif\n  }\n}\n\ntemplate <typename Traits>\nvoid BlockSolver<Traits>::deallocate()\n{\n  if (_Hpp){\n    delete _Hpp;\n    _Hpp=0;\n  }\n  if (_Hll){\n    delete _Hll;\n    _Hll=0;\n  }\n  if (_Hpl){\n    delete _Hpl;\n    _Hpl = 0;\n  }\n  if (_Hschur){\n    delete _Hschur;\n    _Hschur=0;\n  }\n  if (_DInvSchur){\n    delete _DInvSchur;\n    _DInvSchur=0;\n  }\n  if (_coefficients) {\n    delete[] _coefficients;\n    _coefficients = 0;\n  }\n  if (_bschur) {\n    delete[] _bschur;\n    _bschur = 0;\n  }\n  if (_HplCCS) {\n    delete _HplCCS;\n    _HplCCS = 0;\n  }\n  if (_HschurTransposedCCS) {\n    delete _HschurTransposedCCS;\n    _HschurTransposedCCS = 0;\n  }\n}\n\ntemplate <typename Traits>\nBlockSolver<Traits>::~BlockSolver()\n{\n  delete _linearSolver;\n  deallocate();\n}\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::buildStructure(bool zeroBlocks)\n{\n  assert(_optimizer);\n\n  size_t sparseDim = 0;\n  _numPoses=0;\n  _numLandmarks=0;\n  _sizePoses=0;\n  _sizeLandmarks=0;\n  int* blockPoseIndices = new int[_optimizer->indexMapping().size()];\n  int* blockLandmarkIndices = new int[_optimizer->indexMapping().size()];\n\n  for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i) {\n    OptimizableGraph::Vertex* v = _optimizer->indexMapping()[i];\n    int dim = v->dimension();\n    if (! v->marginalized()){\n      v->setColInHessian(_sizePoses);\n      _sizePoses+=dim;\n      blockPoseIndices[_numPoses]=_sizePoses;\n      ++_numPoses;\n    } else {\n      v->setColInHessian(_sizeLandmarks);\n      _sizeLandmarks+=dim;\n      blockLandmarkIndices[_numLandmarks]=_sizeLandmarks;\n      ++_numLandmarks;\n    }\n    sparseDim += dim;\n  }\n  resize(blockPoseIndices, _numPoses, blockLandmarkIndices, _numLandmarks, sparseDim);\n  delete[] blockLandmarkIndices;\n  delete[] blockPoseIndices;\n\n  // allocate the diagonal on Hpp and Hll\n  int poseIdx = 0;\n  int landmarkIdx = 0;\n  for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i) {\n    OptimizableGraph::Vertex* v = _optimizer->indexMapping()[i];\n    if (! v->marginalized()){\n      //assert(poseIdx == v->hessianIndex());\n      PoseMatrixType* m = _Hpp->block(poseIdx, poseIdx, true);\n      if (zeroBlocks)\n        m->setZero();\n      v->mapHessianMemory(m->data());\n      ++poseIdx;\n    } else {\n      LandmarkMatrixType* m = _Hll->block(landmarkIdx, landmarkIdx, true);\n      if (zeroBlocks)\n        m->setZero();\n      v->mapHessianMemory(m->data());\n      ++landmarkIdx;\n    }\n  }\n  assert(poseIdx == _numPoses && landmarkIdx == _numLandmarks);\n\n  // temporary structures for building the pattern of the Schur complement\n  SparseBlockMatrixHashMap<PoseMatrixType>* schurMatrixLookup = 0;\n  if (_doSchur) {\n    schurMatrixLookup = new SparseBlockMatrixHashMap<PoseMatrixType>(_Hschur->rowBlockIndices(), _Hschur->colBlockIndices());\n    schurMatrixLookup->blockCols().resize(_Hschur->blockCols().size());\n  }\n\n  // here we assume that the landmark indices start after the pose ones\n  // create the structure in Hpp, Hll and in Hpl\n  for (SparseOptimizer::EdgeContainer::const_iterator it=_optimizer->activeEdges().begin(); it!=_optimizer->activeEdges().end(); ++it){\n    OptimizableGraph::Edge* e = *it;\n\n    for (size_t viIdx = 0; viIdx < e->vertices().size(); ++viIdx) {\n      OptimizableGraph::Vertex* v1 = (OptimizableGraph::Vertex*) e->vertex(viIdx);\n      int ind1 = v1->hessianIndex();\n      if (ind1 == -1)\n        continue;\n      int indexV1Bak = ind1;\n      for (size_t vjIdx = viIdx + 1; vjIdx < e->vertices().size(); ++vjIdx) {\n        OptimizableGraph::Vertex* v2 = (OptimizableGraph::Vertex*) e->vertex(vjIdx);\n        int ind2 = v2->hessianIndex();\n        if (ind2 == -1)\n          continue;\n        ind1 = indexV1Bak;\n        bool transposedBlock = ind1 > ind2;\n        if (transposedBlock){ // make sure, we allocate the upper triangle block\n          swap(ind1, ind2);\n        }\n        if (! v1->marginalized() && !v2->marginalized()){\n          PoseMatrixType* m = _Hpp->block(ind1, ind2, true);\n          if (zeroBlocks)\n            m->setZero();\n          e->mapHessianMemory(m->data(), viIdx, vjIdx, transposedBlock);\n          if (_Hschur) {// assume this is only needed in case we solve with the schur complement\n            schurMatrixLookup->addBlock(ind1, ind2);\n          }\n        } else if (v1->marginalized() && v2->marginalized()){\n          // RAINER hmm.... should we ever reach this here????\n          LandmarkMatrixType* m = _Hll->block(ind1-_numPoses, ind2-_numPoses, true);\n          if (zeroBlocks)\n            m->setZero();\n          e->mapHessianMemory(m->data(), viIdx, vjIdx, false);\n        } else { \n          if (v1->marginalized()){ \n            PoseLandmarkMatrixType* m = _Hpl->block(v2->hessianIndex(),v1->hessianIndex()-_numPoses, true);\n            if (zeroBlocks)\n              m->setZero();\n            e->mapHessianMemory(m->data(), viIdx, vjIdx, true); // transpose the block before writing to it\n          } else {\n            PoseLandmarkMatrixType* m = _Hpl->block(v1->hessianIndex(),v2->hessianIndex()-_numPoses, true);\n            if (zeroBlocks)\n              m->setZero();\n            e->mapHessianMemory(m->data(), viIdx, vjIdx, false); // directly the block\n          }\n        }\n      }\n    }\n  }\n\n  if (! _doSchur)\n    return true;\n\n  _DInvSchur->diagonal().resize(landmarkIdx);\n  _Hpl->fillSparseBlockMatrixCCS(*_HplCCS);\n\n  for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i) {\n    OptimizableGraph::Vertex* v = _optimizer->indexMapping()[i];\n    if (v->marginalized()){\n      const HyperGraph::EdgeSet& vedges=v->edges();\n      for (HyperGraph::EdgeSet::const_iterator it1=vedges.begin(); it1!=vedges.end(); ++it1){\n        for (size_t i=0; i<(*it1)->vertices().size(); ++i)\n        {\n          OptimizableGraph::Vertex* v1= (OptimizableGraph::Vertex*) (*it1)->vertex(i);\n          if (v1->hessianIndex()==-1 || v1==v)\n            continue;\n          for  (HyperGraph::EdgeSet::const_iterator it2=vedges.begin(); it2!=vedges.end(); ++it2){\n            for (size_t j=0; j<(*it2)->vertices().size(); ++j)\n            {\n              OptimizableGraph::Vertex* v2= (OptimizableGraph::Vertex*) (*it2)->vertex(j);\n              if (v2->hessianIndex()==-1 || v2==v)\n                continue;\n              int i1=v1->hessianIndex();\n              int i2=v2->hessianIndex();\n              if (i1<=i2) {\n                schurMatrixLookup->addBlock(i1, i2);\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  _Hschur->takePatternFromHash(*schurMatrixLookup);\n  delete schurMatrixLookup;\n  _Hschur->fillSparseBlockMatrixCCSTransposed(*_HschurTransposedCCS);\n\n  return true;\n}\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::updateStructure(const std::vector<HyperGraph::Vertex*>& vset, const HyperGraph::EdgeSet& edges)\n{\n  for (std::vector<HyperGraph::Vertex*>::const_iterator vit = vset.begin(); vit != vset.end(); ++vit) {\n    OptimizableGraph::Vertex* v = static_cast<OptimizableGraph::Vertex*>(*vit);\n    int dim = v->dimension();\n    if (! v->marginalized()){\n      v->setColInHessian(_sizePoses);\n      _sizePoses+=dim;\n      _Hpp->rowBlockIndices().push_back(_sizePoses);\n      _Hpp->colBlockIndices().push_back(_sizePoses);\n      _Hpp->blockCols().push_back(typename SparseBlockMatrix<PoseMatrixType>::IntBlockMap());\n      ++_numPoses;\n      int ind = v->hessianIndex();\n      PoseMatrixType* m = _Hpp->block(ind, ind, true);\n      v->mapHessianMemory(m->data());\n    } else {\n      std::cerr << \"updateStructure(): Schur not supported\" << std::endl;\n      abort();\n    }\n  }\n  resizeVector(_sizePoses + _sizeLandmarks);\n\n  for (HyperGraph::EdgeSet::const_iterator it = edges.begin(); it != edges.end(); ++it) {\n    OptimizableGraph::Edge* e = static_cast<OptimizableGraph::Edge*>(*it);\n\n    for (size_t viIdx = 0; viIdx < e->vertices().size(); ++viIdx) {\n      OptimizableGraph::Vertex* v1 = (OptimizableGraph::Vertex*) e->vertex(viIdx);\n      int ind1 = v1->hessianIndex();\n      int indexV1Bak = ind1;\n      if (ind1 == -1)\n        continue;\n      for (size_t vjIdx = viIdx + 1; vjIdx < e->vertices().size(); ++vjIdx) {\n        OptimizableGraph::Vertex* v2 = (OptimizableGraph::Vertex*) e->vertex(vjIdx);\n        int ind2 = v2->hessianIndex();\n        if (ind2 == -1)\n          continue;\n        ind1 = indexV1Bak;\n        bool transposedBlock = ind1 > ind2;\n        if (transposedBlock) // make sure, we allocate the upper triangular block\n          swap(ind1, ind2);\n\n        if (! v1->marginalized() && !v2->marginalized()) {\n          PoseMatrixType* m = _Hpp->block(ind1, ind2, true);\n          e->mapHessianMemory(m->data(), viIdx, vjIdx, transposedBlock);\n        } else { \n          std::cerr << __PRETTY_FUNCTION__ << \": not supported\" << std::endl;\n        }\n      }\n    }\n\n  }\n\n  return true;\n}\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::solve(){\n  //cerr << __PRETTY_FUNCTION__ << endl;\n  if (! _doSchur){\n    double t=get_monotonic_time();\n    bool ok = _linearSolver->solve(*_Hpp, _x, _b);\n    G2OBatchStatistics* globalStats = G2OBatchStatistics::globalStats();\n    if (globalStats) {\n      globalStats->timeLinearSolver = get_monotonic_time() - t;\n      globalStats->hessianDimension = globalStats->hessianPoseDimension = _Hpp->cols();\n    }\n    return ok;\n  }\n\n  // schur thing\n\n  // backup the coefficient matrix\n  double t=get_monotonic_time();\n\n  // _Hschur = _Hpp, but keeping the pattern of _Hschur\n  _Hschur->clear();\n  _Hpp->add(_Hschur);\n\n  //_DInvSchur->clear();\n  memset (_coefficients, 0, _sizePoses*sizeof(double));\n# ifdef G2O_OPENMP\n# pragma omp parallel for default (shared) schedule(dynamic, 10)\n# endif\n  for (int landmarkIndex = 0; landmarkIndex < static_cast<int>(_Hll->blockCols().size()); ++landmarkIndex) {\n    const typename SparseBlockMatrix<LandmarkMatrixType>::IntBlockMap& marginalizeColumn = _Hll->blockCols()[landmarkIndex];\n    assert(marginalizeColumn.size() == 1 && \"more than one block in _Hll column\");\n\n    // calculate inverse block for the landmark\n    const LandmarkMatrixType * D = marginalizeColumn.begin()->second;\n    assert (D && D->rows()==D->cols() && \"Error in landmark matrix\");\n    LandmarkMatrixType& Dinv = _DInvSchur->diagonal()[landmarkIndex];\n    Dinv = D->inverse();\n\n    LandmarkVectorType  db(D->rows());\n    for (int j=0; j<D->rows(); ++j) {\n      db[j]=_b[_Hll->rowBaseOfBlock(landmarkIndex) + _sizePoses + j];\n    }\n    db=Dinv*db;\n\n    assert((size_t)landmarkIndex < _HplCCS->blockCols().size() && \"Index out of bounds\");\n    const typename SparseBlockMatrixCCS<PoseLandmarkMatrixType>::SparseColumn& landmarkColumn = _HplCCS->blockCols()[landmarkIndex];\n\n    for (typename SparseBlockMatrixCCS<PoseLandmarkMatrixType>::SparseColumn::const_iterator it_outer = landmarkColumn.begin();\n        it_outer != landmarkColumn.end(); ++it_outer) {\n      int i1 = it_outer->row;\n\n      const PoseLandmarkMatrixType* Bi = it_outer->block;\n      assert(Bi);\n\n      PoseLandmarkMatrixType BDinv = (*Bi)*(Dinv);\n      assert(_HplCCS->rowBaseOfBlock(i1) < _sizePoses && \"Index out of bounds\");\n      typename PoseVectorType::MapType Bb(&_coefficients[_HplCCS->rowBaseOfBlock(i1)], Bi->rows());\n#    ifdef G2O_OPENMP\n      ScopedOpenMPMutex mutexLock(&_coefficientsMutex[i1]);\n#    endif\n      Bb.noalias() += (*Bi)*db;\n\n      assert(i1 >= 0 && i1 < static_cast<int>(_HschurTransposedCCS->blockCols().size()) && \"Index out of bounds\");\n      typename SparseBlockMatrixCCS<PoseMatrixType>::SparseColumn::iterator targetColumnIt = _HschurTransposedCCS->blockCols()[i1].begin();\n\n      typename SparseBlockMatrixCCS<PoseLandmarkMatrixType>::RowBlock aux(i1, 0);\n      typename SparseBlockMatrixCCS<PoseLandmarkMatrixType>::SparseColumn::const_iterator it_inner = lower_bound(landmarkColumn.begin(), landmarkColumn.end(), aux);\n      for (; it_inner != landmarkColumn.end(); ++it_inner) {\n        int i2 = it_inner->row;\n        const PoseLandmarkMatrixType* Bj = it_inner->block;\n        assert(Bj); \n        while (targetColumnIt->row < i2 /*&& targetColumnIt != _HschurTransposedCCS->blockCols()[i1].end()*/)\n          ++targetColumnIt;\n        assert(targetColumnIt != _HschurTransposedCCS->blockCols()[i1].end() && targetColumnIt->row == i2 && \"invalid iterator, something wrong with the matrix structure\");\n        PoseMatrixType* Hi1i2 = targetColumnIt->block;//_Hschur->block(i1,i2);\n        assert(Hi1i2);\n        (*Hi1i2).noalias() -= BDinv*Bj->transpose();\n      }\n    }\n  }\n  //cerr << \"Solve [marginalize] = \" <<  get_monotonic_time()-t << endl;\n\n  // _bschur = _b for calling solver, and not touching _b\n  memcpy(_bschur, _b, _sizePoses * sizeof(double));\n  for (int i=0; i<_sizePoses; ++i){\n    _bschur[i]-=_coefficients[i];\n  }\n\n  G2OBatchStatistics* globalStats = G2OBatchStatistics::globalStats();\n  if (globalStats){\n    globalStats->timeSchurComplement = get_monotonic_time() - t;\n  }\n\n  t=get_monotonic_time();\n  bool solvedPoses = _linearSolver->solve(*_Hschur, _x, _bschur);\n  if (globalStats) {\n    globalStats->timeLinearSolver = get_monotonic_time() - t;\n    globalStats->hessianPoseDimension = _Hpp->cols();\n    globalStats->hessianLandmarkDimension = _Hll->cols();\n    globalStats->hessianDimension = globalStats->hessianPoseDimension + globalStats->hessianLandmarkDimension;\n  }\n  //cerr << \"Solve [decompose and solve] = \" <<  get_monotonic_time()-t << endl;\n\n  if (! solvedPoses)\n    return false;\n\n  // _x contains the solution for the poses, now applying it to the landmarks to get the new part of the\n  // solution;\n  double* xp = _x;\n  double* cp = _coefficients;\n\n  double* xl=_x+_sizePoses;\n  double* cl=_coefficients + _sizePoses;\n  double* bl=_b+_sizePoses;\n\n  // cp = -xp\n  for (int i=0; i<_sizePoses; ++i)\n    cp[i]=-xp[i];\n\n  // cl = bl\n  memcpy(cl,bl,_sizeLandmarks*sizeof(double));\n\n  // cl = bl - Bt * xp\n  //Bt->multiply(cl, cp);\n  _HplCCS->rightMultiply(cl, cp);\n\n  // xl = Dinv * cl\n  memset(xl,0, _sizeLandmarks*sizeof(double));\n  _DInvSchur->multiply(xl,cl);\n  //_DInvSchur->rightMultiply(xl,cl);\n  //cerr << \"Solve [landmark delta] = \" <<  get_monotonic_time()-t << endl;\n\n  return true;\n}\n\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::computeMarginals(SparseBlockMatrix<MatrixXd>& spinv, const std::vector<std::pair<int, int> >& blockIndices)\n{\n  double t = get_monotonic_time();\n  bool ok = _linearSolver->solvePattern(spinv, blockIndices, *_Hpp);\n  G2OBatchStatistics* globalStats = G2OBatchStatistics::globalStats();\n  if (globalStats) {\n    globalStats->timeMarginals = get_monotonic_time() - t;\n  }\n  return ok;\n}\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::buildSystem()\n{\n  // clear b vector\n# ifdef G2O_OPENMP\n# pragma omp parallel for default (shared) if (_optimizer->indexMapping().size() > 1000)\n# endif\n  for (int i = 0; i < static_cast<int>(_optimizer->indexMapping().size()); ++i) {\n    OptimizableGraph::Vertex* v=_optimizer->indexMapping()[i];\n    assert(v);\n    v->clearQuadraticForm();\n  }\n  _Hpp->clear();\n  if (_doSchur) {\n    _Hll->clear();\n    _Hpl->clear();\n  }\n\n  // resetting the terms for the pairwise constraints\n  // built up the current system by storing the Hessian blocks in the edges and vertices\n# ifndef G2O_OPENMP\n  // no threading, we do not need to copy the workspace\n  JacobianWorkspace& jacobianWorkspace = _optimizer->jacobianWorkspace();\n# else\n  // if running with threads need to produce copies of the workspace for each thread\n  JacobianWorkspace jacobianWorkspace = _optimizer->jacobianWorkspace();\n# pragma omp parallel for default (shared) firstprivate(jacobianWorkspace) if (_optimizer->activeEdges().size() > 100)\n# endif\n  //printf(\"do linearize...........................................\\n\");\n  //std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\n  for (int k = 0, m = 0; k < static_cast<int>(_optimizer->activeEdges().size()); ++k, m++) {\n    OptimizableGraph::Edge* e = _optimizer->activeEdges()[k];\n    while(isnan(der_[6*m])) m++;\n    e->set_j(der_[6*m],der_[6*m+1],der_[6*m+2],der_[6*m+3],der_[6*m+4],der_[6*m+5]);\n    e->linearizeOplus(jacobianWorkspace); // jacobian of the nodes' oplus (manifold)\n    e->constructQuadraticForm();\n#  ifndef NDEBUG\n    for (size_t i = 0; i < e->vertices().size(); ++i) {\n      const OptimizableGraph::Vertex* v = static_cast<const OptimizableGraph::Vertex*>(e->vertex(i));\n      if (! v->fixed()) {\n        bool hasANan = arrayHasNaN(jacobianWorkspace.workspaceForVertex(i), e->dimension() * v->dimension());\n        if (hasANan) {\n          cerr << \"buildSystem(): NaN within Jacobian for edge \" << e << \" for vertex \" << i << endl;\n          break;\n        }\n      }\n    }\n#  endif\n  }\n  //std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();\n  //std::chrono::duration<double, std::milli> time_span = t2 - t1;\n  //printf(\"Costs %f ms to calculate the jacobian value, CPU \\n\", time_span.count());\n  //printf(\"finish computing jacobian...........................................with edge numbre %d \\n\", counter);\n\n  // flush the current system in a sparse block matrix\n# ifdef G2O_OPENMP\n# pragma omp parallel for default (shared) if (_optimizer->indexMapping().size() > 1000)\n# endif\n  for (int i = 0; i < static_cast<int>(_optimizer->indexMapping().size()); ++i) {\n    OptimizableGraph::Vertex* v=_optimizer->indexMapping()[i];\n    int iBase = v->colInHessian();\n    if (v->marginalized())\n      iBase+=_sizePoses;\n    v->copyB(_b+iBase);\n  }\n\n  return 0;\n}\n\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::setLambda(double lambda, bool backup)\n{\n  if (backup) {\n    _diagonalBackupPose.resize(_numPoses);\n    _diagonalBackupLandmark.resize(_numLandmarks);\n  }\n# ifdef G2O_OPENMP\n# pragma omp parallel for default (shared) if (_numPoses > 100)\n# endif\n  for (int i = 0; i < _numPoses; ++i) {\n    PoseMatrixType *b=_Hpp->block(i,i);\n    if (backup)\n      _diagonalBackupPose[i] = b->diagonal();\n    b->diagonal().array() += lambda;\n  }\n# ifdef G2O_OPENMP\n# pragma omp parallel for default (shared) if (_numLandmarks > 100)\n# endif\n  for (int i = 0; i < _numLandmarks; ++i) {\n    LandmarkMatrixType *b=_Hll->block(i,i);\n    if (backup)\n      _diagonalBackupLandmark[i] = b->diagonal();\n    b->diagonal().array() += lambda;\n  }\n  return true;\n}\n\ntemplate <typename Traits>\nvoid BlockSolver<Traits>::restoreDiagonal()\n{\n  assert((int) _diagonalBackupPose.size() == _numPoses && \"Mismatch in dimensions\");\n  assert((int) _diagonalBackupLandmark.size() == _numLandmarks && \"Mismatch in dimensions\");\n  for (int i = 0; i < _numPoses; ++i) {\n    PoseMatrixType *b=_Hpp->block(i,i);\n    b->diagonal() = _diagonalBackupPose[i];\n  }\n  for (int i = 0; i < _numLandmarks; ++i) {\n    LandmarkMatrixType *b=_Hll->block(i,i);\n    b->diagonal() = _diagonalBackupLandmark[i];\n  }\n}\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::init(SparseOptimizer* optimizer, bool online)\n{\n  _optimizer = optimizer;\n  if (! online) {\n    if (_Hpp)\n      _Hpp->clear();\n    if (_Hpl)\n      _Hpl->clear();\n    if (_Hll)\n      _Hll->clear();\n  }\n  _linearSolver->init();\n  return true;\n}\n\ntemplate <typename Traits>\nvoid BlockSolver<Traits>::setWriteDebug(bool writeDebug)\n{\n  _linearSolver->setWriteDebug(writeDebug);\n}\n\ntemplate <typename Traits>\nbool BlockSolver<Traits>::saveHessian(const std::string& fileName) const\n{\n  return _Hpp->writeOctave(fileName.c_str(), true);\n}\n\n} // end namespace\n", "meta": {"hexsha": "78a73332f45f5ed6d5396069e7cdf576cbb49569", "size": 22689, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "g2o/g2o/core/block_solver.hpp", "max_stars_repo_name": "arpg/NID-Pose-Estimation", "max_stars_repo_head_hexsha": "523a5f17365edb05111e6d0ccd097f0c01ca4ce8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-17T07:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T02:02:15.000Z", "max_issues_repo_path": "g2o/g2o/core/block_solver.hpp", "max_issues_repo_name": "arpg/NID-Pose-Estimation", "max_issues_repo_head_hexsha": "523a5f17365edb05111e6d0ccd097f0c01ca4ce8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "g2o/g2o/core/block_solver.hpp", "max_forks_repo_name": "arpg/NID-Pose-Estimation", "max_forks_repo_head_hexsha": "523a5f17365edb05111e6d0ccd097f0c01ca4ce8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-21T04:13:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T04:13:07.000Z", "avg_line_length": 35.176744186, "max_line_length": 172, "alphanum_fraction": 0.6604081273, "num_tokens": 6584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.03358950468268333, "lm_q1q2_score": 0.016008074421074932}}
{"text": "/**\n *  This file is part of dvo.\n *\n *  Copyright 2012 Christian Kerl <christian.kerl@in.tum.de> (Technical University of Munich)\n *  For more information see <http://vision.in.tum.de/data/software/dvo>.\n *\n *  dvo 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 *  dvo 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 dvo.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <dvo_core/rgbd_image.h>\n\n#include <assert.h>\n\n#include <boost/unordered_map.hpp>\n\n#include <dvo_core/interpolation.h>\n\n//#include \"../util.h\"\n//#include \"../stopwatch.h\"\n\n\ntemplate<typename T>\nstatic void pyrDownMeanSmooth(const cv::Mat& in, cv::Mat& out)\n{\n  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());\n\n  for(int y = 0; y < out.rows; ++y)\n  {\n    for(int x = 0; x < out.cols; ++x)\n    {\n      int x0 = x * 2;\n      int x1 = x0 + 1;\n      int y0 = y * 2;\n      int y1 = y0 + 1;\n\n      out.at<T>(y, x) = (T) ( (in.at<T>(y0, x0) + in.at<T>(y0, x1) + in.at<T>(y1, x0) + in.at<T>(y1, x1)) / 4.0f );\n    }\n  }\n}\n\ntemplate<typename T>\nstatic void pyrDownMeanSmoothIgnoreInvalid(const cv::Mat& in, cv::Mat& out)\n{\n  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());\n\n  for(int y = 0; y < out.rows; ++y)\n  {\n    for(int x = 0; x < out.cols; ++x)\n    {\n      int x0 = x * 2;\n      int x1 = x0 + 1;\n      int y0 = y * 2;\n      int y1 = y0 + 1;\n\n      T total = 0;\n      int cnt = 0;\n\n      if(std::isfinite(in.at<T>(y0, x0)))\n      {\n        total += in.at<T>(y0, x0);\n        cnt++;\n      }\n\n      if(std::isfinite(in.at<T>(y0, x1)))\n      {\n        total += in.at<T>(y0, x1);\n        cnt++;\n      }\n\n      if(std::isfinite(in.at<T>(y1, x0)))\n      {\n        total += in.at<T>(y1, x0);\n        cnt++;\n      }\n\n      if(std::isfinite(in.at<T>(y1, x1)))\n      {\n        total += in.at<T>(y1, x1);\n        cnt++;\n      }\n\n      if(cnt > 0)\n      {\n        out.at<T>(y, x) = (T) ( total / cnt );\n      }\n      else\n      {\n        out.at<T>(y, x) = InvalidDepth;\n      }\n    }\n  }\n}\n\ntemplate<typename T>\nstatic void pyrDownMedianSmooth(const cv::Mat& in, cv::Mat& out)\n{\n  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());\n\n  cv::Mat in_smoothed;\n  cv::medianBlur(in, in_smoothed, 3);\n\n  for(int y = 0; y < out.rows; ++y)\n  {\n    for(int x = 0; x < out.cols; ++x)\n    {\n      out.at<T>(y, x) = in_smoothed.at<T>(y * 2, x * 2);\n    }\n  }\n}\n\nRgbdImagePyramid::RgbdImagePyramid(cv::Mat intensity, cv::Mat depth) : levels(1)\n{\n  levels[0].intensity = intensity;\n  levels[0].depth = depth;\n  levels[0].initialize();\n}\n\nvoid RgbdImagePyramid::compute(const size_t num_levels)\n{\n  if(levels.size() >= num_levels) return;\n\n  // if we already have some levels, we just need to compute the coarser levels\n  size_t first = levels.size();\n\n  levels.resize(num_levels);\n\n  for(size_t idx = first; idx < num_levels; ++idx)\n  {\n    pyrDownMeanSmooth<IntensityType>(levels[idx - 1].intensity, levels[idx].intensity);\n    //pyrDownMeanSmoothIgnoreInvalid<float>(levels[idx - 1].depth, levels[idx].depth);\n    pyrDownMedianSmooth<float>(levels[idx - 1].depth, levels[idx].depth);\n    levels[idx].initialize();\n  }\n}\n\nRgbdImage& RgbdImagePyramid::level(size_t idx)\n{\n  assert(idx < levels.size());\n\n  return levels[idx];\n}\n\nvoid RgbdImage::initialize()\n{\n  assert(hasIntensity() || hasDepth());\n\n  if(hasIntensity() && hasDepth())\n  {\n    assert(intensity.size() == depth.size());\n  }\n\n  if(hasIntensity())\n  {\n    assert(intensity.type() == cv::DataType<IntensityType>::type && intensity.channels() == 1);\n    width = intensity.cols;\n    height = intensity.rows;\n  }\n  if(hasDepth())\n  {\n    assert(depth.type() == cv::DataType<DepthType>::type && depth.channels() == 1);\n    width = depth.cols;\n    height = depth.rows;\n  }\n\n  intensity_requires_calculation_ = true;\n  depth_requires_calculation_ = true;\n  pointcloud_requires_build_ = true;\n}\n\nbool RgbdImage::hasIntensity() const\n{\n  return !intensity.empty();\n}\n\nbool RgbdImage::hasRgb() const\n{\n  return !rgb.empty();\n}\n\nbool RgbdImage::hasDepth() const\n{\n  return !depth.empty();\n}\n\nvoid RgbdImage::calculateDerivatives()\n{\n  calculateIntensityDerivatives();\n  calculateDepthDerivatives();\n}\n\nbool RgbdImage::calculateIntensityDerivatives()\n{\n  if(!intensity_requires_calculation_) return false;\n\n  assert(hasIntensity());\n\n  calculateDerivativeX<IntensityType>(intensity, intensity_dx);\n  //calculateDerivativeY<IntensityType>(intensity, intensity_dy);\n  calculateDerivativeYSseFloat(intensity, intensity_dy);\n  /*\n  cv::Mat dy_ref, diff;\n  calculateDerivativeY<IntensityType>(intensity, dy_ref);\n  cv::absdiff(dy_ref, intensity_dy, diff);\n  tracker::util::show(\"diff\", diff);\n  cv::waitKey(0);\n   */\n  intensity_requires_calculation_ = false;\n  return true;\n}\n\nvoid RgbdImage::calculateDepthDerivatives()\n{\n  if(!depth_requires_calculation_) return;\n\n  assert(hasDepth());\n\n  calculateDerivativeX<DepthType>(depth, depth_dx);\n  calculateDerivativeY<DepthType>(depth, depth_dy);\n\n  depth_requires_calculation_ = false;\n}\n\ntemplate<typename T>\nvoid RgbdImage::calculateDerivativeX(const cv::Mat& img, cv::Mat& result)\n{\n  result.create(img.size(), img.type());\n\n  for(int y = 0; y < img.rows; ++y)\n  {\n    for(int x = 0; x < img.cols; ++x)\n    {\n      int prev = std::max(x - 1, 0);\n      int next = std::min(x + 1, img.cols - 1);\n\n      result.at<T>(y, x) = (T) (img.at<T>(y, next) - img.at<T>(y, prev)) * 0.5f;\n    }\n  }\n\n  //cv::Sobel(img, result, -1, 1, 0, 3, 1.0f / 4.0f, 0, cv::BORDER_REPLICATE);\n\n  // compiler auto-vectorization\n  /*\n  const float* img_ptr = img.ptr<float>();\n  float* result_ptr = result.ptr<float>();\n\n  for(int y = 0; y < img.rows; ++y)\n  {\n    *result_ptr++ = img_ptr[1] - img_ptr[0];\n\n    for(int x = 1; x < img.cols - 1; ++x, ++img_ptr)\n    {\n      *result_ptr++ = img_ptr[2] - img_ptr[0];\n    }\n\n    *result_ptr++ = img_ptr[1] - img_ptr[0];\n\n    img_ptr++;\n  }\n   */\n}\n\ntemplate<typename T>\nvoid RgbdImage::calculateDerivativeY(const cv::Mat& img, cv::Mat& result)\n{\n  result.create(img.size(), img.type());\n\n  for(int y = 0; y < img.rows; ++y)\n  {\n    for(int x = 0; x < img.cols; ++x)\n    {\n      int prev = std::max(y - 1, 0);\n      int next = std::min(y + 1, img.rows - 1);\n\n      result.at<T>(y, x) = (T) (img.at<T>(next, x) - img.at<T>(prev, x)) * 0.5f;\n    }\n  }\n  //cv::Sobel(img, result, -1, 0, 1, 3, 1.0f / 4.0f, 0, cv::BORDER_REPLICATE);\n\n  // compiler auto-vectorization\n  /*\n  for(int y = 0; y < img.rows; ++y)\n  {\n    const float* prev_row = img.ptr<float>(std::max(y - 1, 0), 0);\n    const float* next_row = img.ptr<float>(std::min(y + 1, img.rows - 1), 0);\n    float* cur_row = result.ptr<float>(y, 0);\n\n    for(int x = 0; x < img.cols; ++x)\n    {\n      *cur_row++ = *next_row++ - *prev_row++;\n    }\n  }\n   */\n}\n\nvoid RgbdImage::buildPointCloud(const IntrinsicMatrix& intrinsics)\n{\n  if(!pointcloud_requires_build_) return;\n\n  assert(hasDepth());\n\n  static boost::unordered_map<IntrinsicMatrix, PointCloud, IntrinsicMatrix::Hash, IntrinsicMatrix::Equal> cache;\n\n  if(cache.find(intrinsics) == cache.end())\n  {\n    PointCloud& def = cache[intrinsics];\n    def.resize(Eigen::NoChange, width * height);\n\n    int idx = 0;\n\n    for(size_t y = 0; y < height; ++y)\n    {\n      for(size_t x = 0; x < width; ++x, ++idx)\n      {\n        def(0, idx) = (x - intrinsics.ox()) / intrinsics.fx();\n        def(1, idx) = (y - intrinsics.oy()) / intrinsics.fy();\n        def(2, idx) = 1.0;\n        def(3, idx) = 0.0;\n      }\n    }\n  }\n\n  PointCloud& def = cache[intrinsics];\n  pointcloud.resize(Eigen::NoChange, width * height);\n\n  const float* depth_ptr = depth.ptr<float>();\n  int idx = 0;\n\n  for(size_t y = 0; y < height; ++y)\n  {\n    for(size_t x = 0; x < width; ++x, ++depth_ptr, ++idx)\n    {\n      pointcloud.col(idx) = def.col(idx) * (*depth_ptr);\n      pointcloud(3, idx) = 1.0;\n    }\n  }\n\n  pointcloud_requires_build_ = false;\n}\n\nvoid RgbdImage::warpIntensity(const AffineTransform& transformationd, const PointCloud& reference_pointcloud, const IntrinsicMatrix& intrinsics, RgbdImage& result, PointCloud& transformed_pointcloud)\n{\n  Eigen::Affine3f transformation = transformationd.cast<float>();\n\n  cv::Mat warped_image(intensity.size(), intensity.type());\n  cv::Mat warped_depth(depth.size(), depth.type());\n\n  float ox = intrinsics.ox();\n  float oy = intrinsics.oy();\n\n  float* warped_intensity_ptr = warped_image.ptr<IntensityType>();\n  float* warped_depth_ptr = warped_depth.ptr<DepthType>();\n\n  int outliers = 0;\n  int total = 0;\n  int idx = 0;\n\n  transformed_pointcloud = transformation * reference_pointcloud;\n\n  for(size_t y = 0; y < height; ++y)\n  {\n    for(size_t x = 0; x < width; ++x, ++idx, ++warped_intensity_ptr, ++warped_depth_ptr)\n    {\n\n      const Eigen::Vector4f& p3d = transformed_pointcloud.col(idx);\n\n      if(!std::isfinite(p3d(2)))\n      {\n        *warped_intensity_ptr = Invalid;\n        *warped_depth_ptr = InvalidDepth;\n        continue;\n      }\n\n      float x_projected = (float) (p3d(0) * intrinsics.fx() / p3d(2) + ox);\n      float y_projected = (float) (p3d(1) * intrinsics.fy() / p3d(2) + oy);\n\n      if(inImage(x_projected, y_projected))\n      {\n        float z = (float) p3d(2);\n\n        *warped_intensity_ptr = Interpolation::bilinearWithDepthBuffer(this->intensity, this->depth, x_projected, y_projected, z);\n        *warped_depth_ptr = z;\n      }\n      else\n      {\n        *warped_intensity_ptr = Invalid;\n        *warped_depth_ptr = InvalidDepth;\n        //outliers++;\n      }\n\n      //total++;\n    }\n  }\n\n  result.intensity = warped_image;\n  result.depth = warped_depth;\n  result.initialize();\n}\n\nvoid RgbdImage::warpDepthForward(const AffineTransform& transformationx, const IntrinsicMatrix& intrinsics, RgbdImage& result, cv::Mat_<cv::Vec3d>& cloud)\n{\n  Eigen::Affine3d transformation = transformationx.cast<double>();\n\n  cloud = cv::Mat_<cv::Vec3d>(depth.size(), cv::Vec3d(0, 0, 0));\n  cv::Mat warped_depth = cv::Mat::zeros(depth.size(), depth.type());\n  warped_depth.setTo(InvalidDepth);\n\n  float ox = intrinsics.ox();\n  float oy = intrinsics.oy();\n\n  const float* depth_ptr = depth.ptr<float>();\n  int outliers = 0;\n  int total = 0;\n\n  for(size_t y = 0; y < height; ++y)\n  {\n    for(size_t x = 0; x < width; ++x, ++depth_ptr)\n    {\n      if(!std::isfinite(*depth_ptr))\n      {\n        continue;\n      }\n\n      float depth = *depth_ptr;\n      Eigen::Vector3d p3d((x - ox) * depth / intrinsics.fx(), (y - oy) * depth / intrinsics.fy(), depth);\n      Eigen::Vector3d p3d_transformed = transformation * p3d;\n\n      float x_projected = (float) (p3d_transformed(0) * intrinsics.fx() / p3d_transformed(2) + ox);\n      float y_projected = (float) (p3d_transformed(1) * intrinsics.fy() / p3d_transformed(2) + oy);\n\n      if(inImage(x_projected, y_projected))\n      {\n        int yi = (int) y_projected, xi = (int) x_projected;\n\n        if(!std::isfinite(warped_depth.at<DepthType>(yi, xi)) || (warped_depth.at<DepthType>(yi, xi) - 0.05) > depth)\n          warped_depth.at<DepthType>(yi, xi) = depth;\n      }\n\n      p3d = p3d_transformed;\n\n      total++;\n      cloud(y, x) = cv::Vec3d(p3d(0), p3d(1), p3d(2));\n    }\n  }\n\n  result.depth = warped_depth;\n  result.initialize();\n}\n\nvoid RgbdImage::warpIntensityForward(const AffineTransform& transformationx, const IntrinsicMatrix& intrinsics, RgbdImage& result, cv::Mat_<cv::Vec3d>& cloud)\n{\n  Eigen::Affine3d transformation = transformationx.cast<double>();\n\n  bool identity = transformation.affine().isIdentity(1e-6);\n\n  cloud = cv::Mat_<cv::Vec3d>(intensity.size(), cv::Vec3d(0, 0, 0));\n  cv::Mat warped_image = cv::Mat::zeros(intensity.size(), intensity.type());\n\n  float ox = intrinsics.ox();\n  float oy = intrinsics.oy();\n\n  const float* depth_ptr = depth.ptr<float>();\n  int outliers = 0;\n  int total = 0;\n\n  for(size_t y = 0; y < height; ++y)\n  {\n    for(size_t x = 0; x < width; ++x, ++depth_ptr)\n    {\n      if(*depth_ptr <= 1e-6f) continue;\n\n      float depth = *depth_ptr;\n      Eigen::Vector3d p3d((x - ox) * depth / intrinsics.fx(), (y - oy) * depth / intrinsics.fy(), depth);\n\n      if(!identity)\n      {\n        Eigen::Vector3d p3d_transformed = transformation * p3d;\n\n        float x_projected = (float) (p3d_transformed(0) * intrinsics.fx() / p3d_transformed(2) + ox);\n        float y_projected = (float) (p3d_transformed(1) * intrinsics.fy() / p3d_transformed(2) + oy);\n\n        if(inImage(x_projected, y_projected))\n        {\n          int xp, yp;\n          xp = (int) std::floor(x_projected);\n          yp = (int) std::floor(y_projected);\n\n          warped_image.at<IntensityType>(yp, xp) = intensity.at<IntensityType>(y, x);\n        }\n        else\n        {\n          outliers++;\n        }\n\n        p3d = p3d_transformed;\n      }\n\n      total++;\n      cloud(y, x) = cv::Vec3d(p3d(0), p3d(1), p3d(2));\n    }\n  }\n\n  //std::cerr << \"warp out: \" << outliers << \" total: \" << total << std::endl;\n\n  if(identity)\n  {\n    warped_image = intensity;\n  }\n  else\n  {\n    //std::cerr << \"did warp\" << std::endl;\n  }\n\n  result.intensity = warped_image;\n  result.depth = depth;\n  result.initialize();\n}\n\nvoid RgbdImage::warpDepthForwardAdvanced(const AffineTransform& transformation, const IntrinsicMatrix& intrinsics, RgbdImage& result)\n{\n  assert(hasDepth());\n\n  this->buildPointCloud(intrinsics);\n\n  PointCloud transformed_pointcloud = transformation.cast<float>() * pointcloud;\n\n  cv::Mat warped_depth(depth.size(), depth.type());\n  warped_depth.setTo(InvalidDepth);\n\n  float z_factor1 = transformation.rotation()(0, 0) + transformation.rotation()(0, 1) * (intrinsics.fx() / intrinsics.fy());\n  float x_factor1 = -transformation.rotation()(2, 0) - transformation.rotation()(2, 1) * (intrinsics.fx() / intrinsics.fy());\n\n  float z_factor2 = transformation.rotation()(1, 1) + transformation.rotation()(1, 0) * (intrinsics.fy() / intrinsics.fx());\n  float y_factor2 = -transformation.rotation()(2, 1) - transformation.rotation()(2, 0) * (intrinsics.fy() / intrinsics.fx());\n\n  for(int idx = 0; idx < height * width; ++idx)\n  {\n    Vector4 p3d = pointcloud.col(idx);\n    NumType z = p3d(2);\n\n    if(!std::isfinite(z)) continue;\n\n    int x_length = (int) std::ceil(z_factor1 + x_factor1 * p3d(0) / z) + 1; // magic +1\n    int y_length = (int) std::ceil(z_factor2 + y_factor2 * p3d(1) / z) + 1; // magic +1\n\n    Vector4 p3d_transformed = transformed_pointcloud.col(idx);\n    NumType z_transformed = p3d_transformed(2);\n\n    int x_projected = (int) std::floor(p3d_transformed(0) * intrinsics.fx() / z_transformed + intrinsics.ox());\n    int y_projected = (int) std::floor(p3d_transformed(1) * intrinsics.fy() / z_transformed + intrinsics.oy());\n\n    // TODO: replace inImage(...) checks, with max(..., 0) on initial value of x_, y_ and  min(..., width/height) for their respective upper bound\n    //for (int y_ = y_projected; y_ < y_projected + y_length; y_++)\n    //  for (int x_ = x_projected; x_ < x_projected + x_length; x_++)\n\n    int x_begin = std::max(x_projected, 0);\n    int y_begin = std::max(y_projected, 0);\n    int x_end = std::min(x_projected + x_length, (int) width);\n    int y_end = std::min(y_projected + y_length, (int) height);\n\n    for (int y = y_begin; y < y_end; ++y)\n    {\n      DepthType* v = warped_depth.ptr<DepthType>(y, x_begin);\n\n      for (int x = x_begin; x < x_end; ++x, ++v)\n      {\n        if(!std::isfinite(*v) || (*v) > z_transformed)\n        {\n          (*v) = (DepthType) z_transformed;\n        }\n      }\n    }\n  }\n\n  result.depth = warped_depth;\n  result.initialize();\n}\n\nbool RgbdImage::inImage(const float& x, const float& y) const\n{\n  return x >= 0 && x < width && y >= 0 && y < height;\n}\n\n", "meta": {"hexsha": "1419bd25f8b39f0bfa587e36a7c6c013a5dd6a2d", "size": 16023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dvo_core/rgbd_image.cpp", "max_stars_repo_name": "Leone9689/dvo", "max_stars_repo_head_hexsha": "25d0a2cab3b25e9cc579f764ffb747610667f88d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dvo_core/rgbd_image.cpp", "max_issues_repo_name": "Leone9689/dvo", "max_issues_repo_head_hexsha": "25d0a2cab3b25e9cc579f764ffb747610667f88d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dvo_core/rgbd_image.cpp", "max_forks_repo_name": "Leone9689/dvo", "max_forks_repo_head_hexsha": "25d0a2cab3b25e9cc579f764ffb747610667f88d", "max_forks_repo_licenses": ["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.9747474747, "max_line_length": 199, "alphanum_fraction": 0.6138675654, "num_tokens": 4954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.03622005794566348, "lm_q1q2_score": 0.015997421325831776}}
{"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC and\n// UT-Battelle, LLC.\n// Produced at the Lawrence Livermore National Laboratory and the Oak Ridge\n// National Laboratory.\n// LLNL-CODE-743438\n// All rights reserved.\n// This file is part of MGmol. For details, see https://github.com/llnl/mgmol.\n// Please also read this link https://github.com/llnl/mgmol/LICENSE\n\n//\n//                  main.cc\n//\n//    Description:\n//        Real grid, finite difference, molecular dynamics program\n//        for with nonorthogonal localized orbitals.\n//\n//        Uses Mehrstellen operators, multigrid accelerations, and\n//        non-local pseudopotentials.\n//\n//     Includes LDA and PBE exchange and correlation functionals.\n//\n// Units:\n//   Potentials, eigenvalues and operators in Rydberg\n//   Energies in Hartree\n//\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <vector>\nusing namespace std;\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#ifdef USE_CNR\n#include <mkl.h>\n#endif\n\n#include <mpi.h>\n\n#include \"Control.h\"\n#include \"DistMatrix.h\"\n#include \"ExtendedGridOrbitals.h\"\n#include \"LocGridOrbitals.h\"\n#include \"MGmol.h\"\n#include \"MGmol_MPI.h\"\n#include \"MPIdata.h\"\n#include \"MatricesBlacsContext.h\"\n#include \"Mesh.h\"\n#include \"PackedCommunicationBuffer.h\"\n#include \"ReplicatedWorkSpace.h\"\n#include \"SparseDistMatrix.h\"\n#include \"magma_singleton.h\"\n#include \"tools.h\"\n\n#include <fenv.h>\n#include <sys/cdefs.h>\n#include <time.h>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n//#include \"MemTrack.h\"\n\n/*\nvoid trapfpe () {\n  feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);\n}\n*/\n\n// A helper function\ntemplate <class T>\nostream& operator<<(ostream& os, const vector<T>& v)\n{\n    copy(v.begin(), v.end(), ostream_iterator<T>(cout, \" \"));\n    return os;\n}\n\nint main(int argc, char** argv)\n{\n    // change handling of memory allocation errors\n    set_new_handler(noMoreMemory);\n\n    cout.sync_with_stdio();\n\n    int mpirc = MPI_Init(&argc, &argv);\n    if (mpirc != MPI_SUCCESS)\n    {\n        cerr << \"MPI Initialization failed!!!\" << endl;\n        MPI_Abort(MPI_COMM_WORLD, 0);\n    }\n    MPI_Comm_rank(MPI_COMM_WORLD, &mype);\n    assert(mype > -1);\n    onpe0 = (mype == 0);\n\n#ifdef HAVE_MAGMA\n    magma_int_t magmalog;\n\n    magmalog = magma_init();\n    if (magmalog == MAGMA_SUCCESS)\n    {\n        std::cout << \"MAGMA Initialization: success\" << std::endl;\n    }\n    else\n    {\n        if (magmalog == MAGMA_ERR_UNKNOWN)\n            std::cout << \"MAGMA Initialization: unknown error\" << std::endl;\n        if (magmalog == MAGMA_ERR_HOST_ALLOC)\n            std::cout << \"MAGMA Initialization: fails host alloc\" << std::endl;\n        return 1;\n    }\n#endif\n\n    string input_file(\"\");\n    string lrs_filename;\n    string constraints_filename(\"\");\n    bool tcheck = false;\n\n    float total_spin = 0.;\n    bool with_spin   = false;\n\n    po::variables_map vm;\n\n    // use configure file if it can be found\n    // std::string config_filename(\"mgmol.cfg\");\n\n    // read options from PE0 only\n    if (onpe0) try\n        {\n            string config_file;\n\n            // Declare a group of options that will be\n            // allowed only on command line\n            po::options_description generic(\"Generic options\");\n            generic.add_options()(\"version,v\", \"print version string\")(\"help,h\",\n                \"produce help message\")(\"check\", \"check input\")(\"config,c\",\n                po::value<string>(&config_file)->default_value(\"mgmol.cfg\"),\n                \"name of a file of a configuration.\")(\"atomicCoordinates,i\",\n                po::value<vector<string>>(),\n                \"coordinates filename\")(\"LRsFilename,l\",\n                po::value<string>(&lrs_filename), \"LRs filename\");\n\n            // Declare a group of options (with default when appropriate) that\n            // will be allowed in config file\n            po::options_description config(\"Configuration\");\n            config.add_options()(\n                \"spin\", po::value<float>(), \"system total spin\")(\"verbosity\",\n                po::value<short>()->default_value(1), \"verbosity level\")(\n                \"constraintsFilename\", po::value<string>(&constraints_filename),\n                \"Name of file with list of constraints\")(\"xcFunctional\",\n                po::value<string>()->required(), \"XC functional: LDA or PBE\")(\n                \"FDtype\", po::value<string>()->default_value(\"Mehrstellen\"),\n                \"Finite Difference scheme\")(\"charge\",\n                po::value<short>()->default_value(0), \"system total charge\")(\n                \"Domain.lx\", po::value<float>()->required(),\n                \"domain dimension in x direction\")(\"Domain.ly\",\n                po::value<float>()->required(),\n                \"domain dimension in y direction\")(\"Domain.lz\",\n                po::value<float>()->required(),\n                \"domain dimension in z direction\")(\"Domain.ox\",\n                po::value<float>()->required(), \"domain origin in x direction\")(\n                \"Domain.oy\", po::value<float>()->required(),\n                \"domain origin in y direction\")(\"Domain.oz\",\n                po::value<float>()->required(), \"domain origin in z direction\")(\n                \"Mesh.nx\", po::value<short>()->required(),\n                \"mesh dimension in x direction\")(\"Mesh.ny\",\n                po::value<short>()->required(),\n                \"mesh dimension in y direction\")(\"Mesh.nz\",\n                po::value<short>()->required(),\n                \"mesh dimension in z direction\")(\"Potentials.pseudopotential\",\n                po::value<vector<string>>()->multitoken(),\n                \"pseudopotentials list\")(\"Potentials.external\",\n                po::value<vector<string>>()->multitoken(),\n                \"external potentials list\")(\"Potentials.binExternal\",\n                po::value<bool>()->default_value(true),\n                \"binary external potential\")(\"Restart.input_filename\",\n                po::value<string>()->default_value(\"\"),\n                \"Read restart filename/directory\")(\"Restart.input_level\",\n                po::value<short>()->default_value(0),\n                \"Read restart level\")(\"Restart.input_type\",\n                po::value<string>()->default_value(\"distributed\"),\n                \"Read restart type: distributed or single_file\")(\n                \"Restart.output_filename\",\n                po::value<string>()->default_value(\"auto\"),\n                \"Dump restart filename/directory\")(\"Restart.output_level\",\n                po::value<short>()->default_value(3),\n                \"Write restart level\")(\"Restart.output_type\",\n                po::value<string>()->default_value(\"distributed\"),\n                \"Write restart type: distributed or single_file\")(\n                \"Restart.interval\", po::value<short>()->default_value(1000),\n                \"Restart frequency\")(\"Restart.rescale_v\",\n                po::value<double>()->default_value(1.),\n                \"rescaling factor velocity of all atoms\")(\"Poisson.bcx\",\n                po::value<string>()->default_value(\"periodic\"),\n                \"boundary condition x\")(\"Poisson.bcy\",\n                po::value<string>()->default_value(\"periodic\"),\n                \"boundary condition y\")(\"Poisson.bcz\",\n                po::value<string>()->default_value(\"periodic\"),\n                \"boundary condition z\")(\"Poisson.diel\",\n                po::value<string>()->default_value(\"off\"),\n                \"continuum solvent: on/off\")(\"Run.type\",\n                po::value<string>()->default_value(\"QUENCH\"), \"Run type\")(\n                \"Quench.solver\", po::value<string>()->default_value(\"ABPG\"),\n                \"Iterative solver for quench\")(\"Quench.max_steps\",\n                po::value<short>()->default_value(200),\n                \"Max. steps in loose quench\")(\"Quench.max_steps_tight\",\n                po::value<short>()->default_value(1000),\n                \"Max. steps in tight quench\")(\"Quench.atol\",\n                po::value<float>()->default_value(1.e-12),\n                \"Abs. tol. in quench convergence\")(\"Quench.rtol\",\n                po::value<float>()->default_value(-1.),\n                \"Rel. tol. in quench convergence\")(\"Quench.conv_criterion\",\n                po::value<string>()->default_value(\"deltaE\"),\n                \"Convergence criterion\")(\"Quench.MLWC\", po::value<bool>(),\n                \"Compute MLWC in quench\")(\"Quench.MLWF\",\n                po::value<bool>()->default_value(false),\n                \"Compute MLWF (apply rotation) in quench\")(\n                \"Quench.num_lin_iterations\",\n                po::value<short>()->default_value(0),\n                \"Number of iterations without potential update in quench\")(\n                \"Quench.preconditioner_num_levels\",\n                po::value<short>()->default_value(2),\n                \"Number of levels for MG preconditioner\")(\n                \"Quench.spread_penalty_damping\",\n                po::value<float>()->default_value(0.),\n                \"Spread penalty damping factor\")(\"Quench.spread_penalty_target\",\n                po::value<float>()->default_value(2.),\n                \"Spread penalty target\")(\"SpreadPenalty.type\",\n                po::value<string>()->default_value(\"individual\"),\n                \"Spread penalty type (individual,volume)\")(\n                \"SpreadPenalty.damping\", po::value<float>()->default_value(1.),\n                \"Spread penalty damping factor\")(\"SpreadPenalty.target\",\n                po::value<float>()->default_value(-1.),\n                \"Spread penalty target\")(\"SpreadPenalty.alpha\",\n                po::value<float>()->default_value(0.),\n                \"Spread penalty factor\")(\"MD.num_steps\",\n                po::value<short>()->default_value(1), \"number of MD steps\")(\n                \"MD.dt\", po::value<float>(), \"time step for MD (a.u.)\")(\n                \"MD.print_interval\", po::value<short>()->default_value(1),\n                \"print intervale for MD data\")(\"MD.print_directory\",\n                po::value<string>()->default_value(\"MD\"),\n                \"print directory for MD data\")(\"MD.thermostat\",\n                po::value<string>()->default_value(\"OFF\"),\n                \"MD thermostat: ON or OFF\")(\"MD.remove_mass_center_motion\",\n                po::value<bool>()->default_value(true),\n                \"Remove mass center motion\")(\"MD.type\",\n                po::value<string>()->default_value(\"BOMD\"), \"MD type: BOMD\")(\n                \"GeomOpt.type\", po::value<string>()->default_value(\"LBFGS\"),\n                \"Geometry optimization algorithm\")(\"GeomOpt.tol\",\n                po::value<float>()->default_value(4.e-4),\n                \"Tolerance on forces for Geometry optimization\")(\n                \"GeomOpt.max_steps\", po::value<short>()->default_value(1),\n                \"max. number of Geometry optimization steps\")(\"GeomOpt.dt\",\n                po::value<float>(), \"Delta t for trial pseudo-time steps\")(\n                \"atomicCoordinates\", po::value<vector<string>>(),\n                \"coordinates filename\")(\"Thermostat.type\",\n                po::value<string>()->default_value(\"Langevin\"),\n                \"Thermostat type\")(\"Thermostat.temperature\",\n                po::value<float>()->default_value(-1.),\n                \"Thermostat temperature\")(\"Thermostat.relax_time\",\n                po::value<float>()->default_value(-1.),\n                \"Thermostat relaxation time\")(\"Thermostat.width\",\n                po::value<float>()->default_value(-1.),\n                \"Thermostat width (for SCALING)\")(\"Orbitals.nempty\",\n                po::value<short>()->default_value(0),\n                \"Number of empty orbitals\")(\"Orbitals.initial_type\",\n                po::value<string>()->default_value(\"random\"),\n                \"initial orbitals type\")(\"Orbitals.initial_width\",\n                po::value<float>()->default_value(10000.),\n                \"initial orbitals radius\")(\"Orbitals.temperature\",\n                po::value<float>()->default_value(0.),\n                \"electronic temperature [K]\")(\"ProjectedMatrices.solver\",\n                po::value<string>()->default_value(\"exact\"),\n                \"solver for projected matrices\")(\"ProjectedMatrices.printMM\",\n                po::value<bool>()->default_value(false),\n                \"print projected matrices in MM format\")(\n                \"LocalizationRegions.radius\",\n                po::value<float>()->default_value(1000.),\n                \"Localization regions radius\")(\"LocalizationRegions.adaptive\",\n                po::value<bool>()->default_value(true),\n                \"Localization regions adaptivity\")(\n                \"LocalizationRegions.move_tol\",\n                po::value<float>()->default_value(1000.),\n                \"Localization regions move tolerance\")(\n                \"Parallel.atomic_info_radius\",\n                po::value<float>()->default_value(8.),\n                \"Max. distance for atomic data communication\")(\n                \"LoadBalancing.alpha\", po::value<float>()->default_value(0.0),\n                \"Parameter for computing bias for load balancing algo\")(\n                \"LoadBalancing.damping_tol\",\n                po::value<float>()->default_value(0.9),\n                \"Damping parameter for computing bias for load balancing algo\")(\n                \"LoadBalancing.max_iterations\",\n                po::value<short>()->default_value(50),\n                \"Maximum number of iterations for load balancing algo\")(\n                \"LoadBalancing.modulo\", po::value<short>()->default_value(1),\n                \"Modulos or parameter to control how often clusters are \"\n                \"recomputed during md\")(\"LoadBalancing.output_file\",\n                po::value<string>()->default_value(\"\"),\n                \"Output file for dumping cluster information in vtk format\");\n\n            // Hidden options, will be allowed in config file, but will not be\n            // shown to the user.\n            po::options_description hidden(\"Hidden options\");\n            hidden.add_options()(\"Quench.interval_print_residual\",\n                po::value<short>()->default_value(0),\n                \"Print interval for residual in quench (0 for none)\")(\n                \"Quench.required_tol\", po::value<float>()->default_value(1000.),\n                \"required tolerance (code stops if not reached)\")(\n                \"Quench.compute_cond_Gram\",\n                po::value<bool>()->default_value(false),\n                \"Compute condition number of S during quench\")(\n                \"Quench.min_Gram_eigenvalue\",\n                po::value<float>()->default_value(0.),\n                \"min. eigenvalue for Gram matrix\")(\"Quench.step_length\",\n                po::value<float>()->default_value(-1.),\n                \"Step length for corrections in quench\")(\"Quench.ortho_freq\",\n                po::value<short>()->default_value(1000),\n                \"Orthonormalization frequency\")(\n                \"Quench.pair_mlwf_distance_threshold\",\n                po::value<float>()->default_value(4.),\n                \"Max. distance between pairs for MLWF transform\")(\n                \"AOMM.kernel_radius\", po::value<float>()->default_value(-1.),\n                \"Radius of kernel functions in AOMM algorithm\")(\n                \"AOMM.threshold_factor\", po::value<float>()->default_value(-1.),\n                \"Multiplicative factor of kernel radius to set threshold in \"\n                \"AOMM projectors dropping\")(\"Orbitals.type\",\n                po::value<string>()->default_value(\"NO\"),\n                \"orbital type\")(\"Orbitals.dotProduct\",\n                po::value<string>()->default_value(\"diagonal\"),\n                \"orbital dot product type\")(\"Orbitals.overallocate_factor\",\n                po::value<float>()->default_value(1.2),\n                \"safety factor to use for static allocation of orbitals\")(\n                \"Potentials.filterPseudo\",\n                po::value<char>()->default_value('f'),\n                \"filter\")(\"Poisson.solver\",\n                po::value<string>()->default_value(\"CG\"), \"solver\")(\n                \"Poisson.rho0\", po::value<float>()->default_value(0.0004),\n                \"continuum solvent: rho0\")(\"Poisson.beta\",\n                po::value<float>()->default_value(1.3),\n                \"continuum solvent: beta\")(\"Poisson.FDtype\",\n                po::value<string>()->default_value(\"Mehrstellen\"), \"FDtype\")(\n                \"Poisson.nu1\", po::value<short>()->default_value(2), \"nu_1\")(\n                \"Poisson.nu2\", po::value<short>()->default_value(2), \"nu_2\")(\n                \"Poisson.max_steps\", po::value<short>()->default_value(20),\n                \"max. nb. steps Poisson solver\")(\"Poisson.max_steps_initial\",\n                po::value<short>()->default_value(20),\n                \"max. nb. steps Poisson solver in first solve\")(\n                \"Poisson.max_levels\", po::value<short>()->default_value(10),\n                \"max. nb. MG levels Poisson solver\")(\"Poisson.reset\",\n                po::value<bool>()->default_value(false),\n                \"reset Hartree potential at each MD step\")(\"ABPG.m\",\n                po::value<short>()->default_value(1),\n                \"History length for Anderson extrapolation\")(\"ABPG.beta\",\n                po::value<float>()->default_value(1.),\n                \"beta for Anderson extrapolation\")(\"NLCG.parallel_transport\",\n                po::value<bool>()->default_value(true),\n                \"Turn ON/OFF parallel transport algorithm\")(\n                \"MD.extrapolation_type\", po::value<short>()->default_value(1),\n                \"MD extrapolation type\")(\"MD.compute_cond_Gram\",\n                po::value<bool>()->default_value(false),\n                \"Compute condition number of S at end of quench\")(\n                \"MD.min_Gram_eigenvalue\", po::value<float>()->default_value(0.),\n                \"min. eigenvalue for Gram matrix\")(\n                \"ShortSightedInverse.spread_factor\",\n                po::value<float>()->default_value(2.),\n                \"Shortsighted spread factor\")(\"ShortSightedInverse.tol\",\n                po::value<float>()->default_value(1.e-10),\n                \"Shortsighted tolerance\")(\"ShortSightedInverse.krylov_dim\",\n                po::value<short>()->default_value(10),\n                \"Shortsighted Krylov space max. dimension\")(\n                \"ShortSightedInverse.max_iterations\",\n                po::value<short>()->default_value(10),\n                \"Shortsighted max. number of GMRES iterations\")(\n                \"ShortSightedInverse.ilu_type\",\n                po::value<string>()->default_value(\"ILU\"),\n                \"Shortsighted ILU type: ILU or ILUT\")(\n                \"ShortSightedInverse.ilu_drop_tol\",\n                po::value<float>()->default_value(1.e-5),\n                \"Shortsighted ILU dropping tolerance\")(\n                \"ShortSightedInverse.ilu_filling_level\",\n                po::value<short>()->default_value(0),\n                \"Shortsighted ILU filling level\")(\n                \"ShortSightedInverse.ilut_max_fill\",\n                po::value<int>()->default_value(10000),\n                \"Shortsighted max. filling for ILUT\")(\"Coloring.algo\",\n                po::value<string>()->default_value(\"RLF\"),\n                \"Coloring algorithm: RLF or Greedy\")(\"Coloring.scope\",\n                po::value<string>()->default_value(\"local\"),\n                \"Coloring scope: local or global\")(\n                \"LocalizationRegions.min_distance\",\n                po::value<float>()->default_value(0.),\n                \"min. distance between Localization centers\")(\n                \"LocalizationRegions.extrapolation_scheme\",\n                po::value<string>()->default_value(\"linear\"),\n                \"Extrapolation order for localization centers\")(\n                \"LocalizationRegions.computation\",\n                po::value<short>()->default_value(0),\n                \"Flag for computing new centers from extrapolated orbitals.\")(\n                \"DensityMatrix.mixing\", po::value<float>()->default_value(1.),\n                \"Mixing coefficient for Density Matrix\")(\"DensityMatrix.solver\",\n                po::value<string>()->default_value(\"Mixing\"),\n                \"Algorithm for updating Density Matrix: Mixing, MVP, HMVP\")(\n                \"DensityMatrix.nb_inner_it\",\n                po::value<short>()->default_value(3),\n                \"Max. number of inner iterations in DM optimization\")(\n                \"DensityMatrix.algo\",\n                po::value<string>()->default_value(\"Diagonalization\"),\n                \"Algorithm for computing Density Matrix. \"\n                \"Diagonalization or SP2 or Chebyshev.\")(\"DensityMatrix.use_old\",\n                po::value<bool>()->default_value(true),\n                \"Start DM optimization with matrix of previous WF step\")(\n                \"DensityMatrix.approximation_order\",\n                po::value<short>()->default_value(500),\n                \"Polynomial order for Chebyshev approximation \"\n                \"of density matrix. \")(\"DensityMatrix.approximation_ndigits\",\n                po::value<short>()->default_value(1),\n                \"Number of digits of precision for Chebyshev \"\n                \"approximation of density matrix. \")(\n                \"DensityMatrix.approximation_power_maxits\",\n                po::value<short>()->default_value(100),\n                \"Maximum number of iterations for power method \"\n                \"to compute interval for Chebyshev \"\n                \"approximation of density matrix. \")(\"DensityMatrix.tol\",\n                po::value<float>()->default_value(1.e-7),\n                \"tolerance, used in iterative DM computation convergence \"\n                \"criteria\");\n\n            po::options_description cmdline_options;\n            cmdline_options.add(generic);\n\n            po::options_description config_file_options;\n            config_file_options.add(config).add(hidden);\n\n            po::options_description visible(\"Allowed options\");\n            visible.add(generic).add(config);\n\n            po::positional_options_description pd;\n            pd.add(\"atomicCoordinates\", -1);\n\n            store(po::command_line_parser(argc, argv)\n                      .options(cmdline_options)\n                      .positional(pd)\n                      .run(),\n                vm);\n            notify(vm);\n\n            ifstream ifs(config_file.c_str());\n            if (!ifs)\n            {\n                cout << \"can not open config file: \" << config_file << \"\\n\";\n                return 0;\n            }\n            else\n            {\n                store(parse_config_file(ifs, config_file_options), vm);\n                notify(vm);\n            }\n\n            if (vm.count(\"help\"))\n            {\n                if (onpe0) cout << visible << \"\\n\";\n                return 0;\n            }\n\n            if (vm.count(\"version\"))\n            {\n                if (onpe0)\n                {\n#ifdef GITHASH\n#define xstr(x) #x\n#define LOG(x) cout << \" MGmol: git_hash \" << xstr(x) << endl;\n                    LOG(GITHASH);\n                    cout << endl;\n#endif\n                }\n                return 0;\n            }\n\n            if (vm.count(\"check\"))\n            {\n                tcheck = true;\n            }\n            if (vm.count(\"spin\"))\n            {\n                total_spin = vm[\"spin\"].as<float>();\n                with_spin  = true;\n                if (onpe0) cout << \"Spin was set to \" << total_spin << endl;\n            }\n            if (vm.count(\"atomicCoordinates\"))\n            {\n                if (onpe0)\n                    cout << \"Input files is: \"\n                         << vm[\"atomicCoordinates\"].as<vector<string>>()[0]\n                         << \"\\n\";\n                input_file = vm[\"atomicCoordinates\"].as<vector<string>>()[0];\n            }\n            else\n            {\n                if (vm[\"Restart.input_level\"].as<short>() == 0)\n                {\n                    throw std::runtime_error(\n                        \"ERROR: No coordinates file provided!!!\");\n                }\n            }\n\n            if (onpe0) cout << \"Spin: \" << total_spin << \"\\n\";\n\n        } // try\n        catch (exception& e)\n        {\n            cerr << e.what() << \"\\n\";\n            return 1;\n        }\n\n    MGmol_MPI::setup(MPI_COMM_WORLD, std::cout, with_spin);\n    MGmol_MPI& mmpi      = *(MGmol_MPI::instance());\n    MPI_Comm global_comm = mmpi.commGlobal();\n\n    Control::setup(global_comm, with_spin, total_spin);\n    Control& ct = *(Control::instance());\n\n    ct.setOptions(vm);\n    ct.sync();\n\n    int ret = ct.checkOptions();\n    if (ret < 0) return ret;\n\n    mmpi.bcastGlobal(input_file);\n    mmpi.bcastGlobal(lrs_filename);\n\n#ifdef _OPENMP\n    if (onpe0)\n    {\n        cout << \" \" << omp_get_max_threads() << \" thread\"\n             << (omp_get_max_threads() > 1 ? \"s \" : \" \");\n        cout << \"active\" << endl << endl;\n    }\n    omp_set_nested(0);\n    if (omp_get_nested())\n    {\n        cerr << \"Nested parallelism not allowed\" << endl;\n        return 1;\n    }\n#endif\n\n    // Enter main scope\n    {\n        // setup standard output and error\n        sout = &std::cout;\n        serr = &std::cerr;\n\n        MGmolInterface* mgmol;\n        if (ct.isLocMode())\n            mgmol = new MGmol<LocGridOrbitals>(global_comm, *MPIdata::sout);\n        else\n            mgmol\n                = new MGmol<ExtendedGridOrbitals>(global_comm, *MPIdata::sout);\n\n        unsigned ngpts[3]    = { ct.ngpts_[0], ct.ngpts_[1], ct.ngpts_[2] };\n        double origin[3]     = { ct.ox_, ct.oy_, ct.oz_ };\n        const double cell[3] = { ct.lx_, ct.ly_, ct.lz_ };\n        Mesh::setup(mmpi.commSpin(), ngpts, origin, cell, ct.lap_type);\n\n        mgmol->setupFromInput(input_file);\n        if (ct.restart_info < 3 || !ct.isLocMode())\n            mgmol->setupLRsFromInput(lrs_filename);\n        mgmol->setupConstraintsFromInput(constraints_filename);\n\n        ct.checkNLrange();\n\n        LocGridOrbitals::setDotProduct(ct.dot_product_type);\n\n        Mesh* mymesh             = Mesh::instance();\n        const pb::PEenv& myPEenv = mymesh->peenv();\n\n        if (!ct.short_sighted)\n        {\n            MatricesBlacsContext::instance().setup(mmpi.commSpin(), ct.numst);\n\n            dist_matrix::DistMatrix<DISTMATDTYPE>::setBlockSize(64);\n\n            dist_matrix::DistMatrix<DISTMATDTYPE>::setDefaultBlacsContext(\n                MatricesBlacsContext::instance().bcxt());\n\n            ReplicatedWorkSpace<double>::instance().setup(ct.numst);\n\n            dist_matrix::SparseDistMatrix<\n                DISTMATDTYPE>::setNumTasksPerPartitioning(128);\n\n            MGmol_MPI& mmpi = *(MGmol_MPI::instance());\n            int npes        = mmpi.size();\n            setSparseDistMatriConsolidationNumber(npes);\n        }\n\n        if (myPEenv.color() > 0)\n        {\n            cerr << \"Code should be called with \" << myPEenv.n_mpi_tasks()\n                 << \" MPI tasks only\" << endl;\n            ct.global_exit(2);\n        }\n\n        assert(myPEenv.color() == 0);\n\n        if (myPEenv.color() == 0)\n        {\n            assert(ct.getMGlevels() >= -1);\n            if (ct.getMGlevels() >= 0 && ct.getPrecondType() % 10 == 0)\n            {\n                const pb::Grid& mygrid = mymesh->grid();\n\n                if ((mygrid.dim(0) % (1 << ct.getMGlevels())) != 0)\n                {\n                    cerr << \"main: mygrid.dim(0)=\" << mygrid.dim(0)\n                         << \" not evenly divisible by \"\n                         << \"2^(ct.getMGlevels())=\" << (1 << ct.getMGlevels())\n                         << endl;\n                    return -1;\n                }\n                if ((mygrid.dim(1) % (1 << ct.getMGlevels())) != 0)\n                {\n                    cerr << \"main: mygrid.dim(1)=\" << mygrid.dim(1)\n                         << \" not evenly divisible by \"\n                         << \"2^(ct.getMGlevels())=\" << (1 << ct.getMGlevels())\n                         << endl;\n                    return -1;\n                }\n                if ((mygrid.dim(2) % (1 << ct.getMGlevels())) != 0)\n                {\n                    cerr << \"main: mygrid.dim(2)=\" << mygrid.dim(2)\n                         << \" not evenly divisible by \"\n                         << \"2^(ct.getMGlevels())=\" << (1 << ct.getMGlevels())\n                         << endl;\n                    return -1;\n                }\n            }\n\n            myPEenv.barrier(); // wait to see if everybody is OK before\n                               // continuing...\n\n            if (!tcheck)\n            {\n#ifdef DEBUG\n                *MPIdata::sout << \" Run begins on processor \"\n                               << myPEenv.mytask() << endl;\n#endif\n\n#ifdef USE_CNR\n                /* use conditional numerical reproducibility for MKL */\n                int my_cbwr_branch = mkl_cbwr_get_auto_branch();\n                if (mkl_cbwr_set(my_cbwr_branch) != MKL_CBWR_SUCCESS)\n                {\n                    printf(\"Error in setting MKL_CBWR_BRANCH! Aborting…\\n\");\n                    return (-1);\n                }\n#endif\n                mgmol->run();\n            }\n            else\n            {\n                *MPIdata::sout << \" Input parameters OK\\n\";\n            }\n        }\n        delete mgmol;\n\n        if (!ct.short_sighted)\n        {\n            // need to destroy any MPI based object befor calling MPI_Finalize\n            MatricesBlacsContext::instance().clear();\n        }\n    } // close main scope\n\n    // release memory for static arrays\n    PackedCommunicationBuffer::deleteStorage();\n    Mesh::deleteInstance();\n    Control::deleteInstance();\n    MGmol_MPI::deleteInstance();\n\n#ifdef HAVE_MAGMA\n    // Delete the data in the singleton before finalizing magma\n    auto& magma_singleton = MagmaSingleton::get_magma_singleton();\n    magma_singleton.free();\n\n    magmalog = magma_finalize();\n\n    if (magmalog == MAGMA_SUCCESS)\n    {\n        std::cout << \"MAGMA Finalize: success\" << std::endl;\n    }\n    else\n    {\n        if (magmalog == MAGMA_ERR_UNKNOWN)\n            std::cout << \"MAGMA Finalize: unknown error\" << std::endl;\n        if (magmalog == MAGMA_ERR_HOST_ALLOC)\n            std::cout << \"MAGMA FINALIZE: fails host alloc\" << std::endl;\n        return 1;\n    }\n\n#endif\n\n    mpirc = MPI_Finalize();\n    if (mpirc != MPI_SUCCESS)\n    {\n        cerr << \"MPI Finalize failed!!!\" << endl;\n    }\n\n    time_t tt;\n    time(&tt);\n    if (onpe0) cout << \" Run ended at \" << ctime(&tt) << endl;\n\n    // MemTrack::TrackDumpBlocks();\n\n    //    MemTrack::TrackListMemoryUsage();\n\n    return 0;\n}\n", "meta": {"hexsha": "04ee522b3584c67b030b3bebe625164f82fa9fac", "size": 30434, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "oseikuffuor1/mgmol", "max_stars_repo_head_hexsha": "5442962959a54c919a5e18c4e78db6ce41ee8f4e", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "oseikuffuor1/mgmol", "max_issues_repo_head_hexsha": "5442962959a54c919a5e18c4e78db6ce41ee8f4e", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cc", "max_forks_repo_name": "oseikuffuor1/mgmol", "max_forks_repo_head_hexsha": "5442962959a54c919a5e18c4e78db6ce41ee8f4e", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3871866295, "max_line_length": 80, "alphanum_fraction": 0.5387395676, "num_tokens": 6660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.03622005625510387, "lm_q1q2_score": 0.015997421111533548}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#ifndef BOOST_MATH_RATIONAL_ADAPTER_HPP\n#define BOOST_MATH_RATIONAL_ADAPTER_HPP\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <boost/cstdint.hpp>\n#include <boost/functional/hash_fwd.hpp>\n#include <boost/multiprecision/number.hpp>\n#ifdef BOOST_MSVC\n#  pragma warning(push)\n#  pragma warning(disable:4512 4127)\n#endif\n#include <boost/rational.hpp>\n#ifdef BOOST_MSVC\n#  pragma warning(pop)\n#endif\n\nnamespace boost{\nnamespace multiprecision{\nnamespace backends{\n\ntemplate <class IntBackend>\nstruct rational_adaptor\n{\n   typedef number<IntBackend>                integer_type;\n   typedef boost::rational<integer_type>        rational_type;\n\n   typedef typename IntBackend::signed_types    signed_types;\n   typedef typename IntBackend::unsigned_types  unsigned_types;\n   typedef typename IntBackend::float_types     float_types;\n\n   rational_adaptor() BOOST_MP_NOEXCEPT_IF(noexcept(rational_type())) {}\n   rational_adaptor(const rational_adaptor& o) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<rational_type&>() = std::declval<const rational_type&>()))\n   {\n      m_value = o.m_value;\n   }\n   rational_adaptor(const IntBackend& o) BOOST_MP_NOEXCEPT_IF(noexcept(rational_type(std::declval<const IntBackend&>()))) : m_value(o) {}\n\n   template <class U>\n   rational_adaptor(const U& u, typename enable_if_c<is_convertible<U, IntBackend>::value>::type* = 0) \n      : m_value(static_cast<integer_type>(u)){}\n   template <class U>\n   explicit rational_adaptor(const U& u, \n      typename enable_if_c<\n         boost::multiprecision::detail::is_explicitly_convertible<U, IntBackend>::value && !is_convertible<U, IntBackend>::value\n      >::type* = 0) \n      : m_value(IntBackend(u)){}\n   template <class U>\n   typename enable_if_c<(boost::multiprecision::detail::is_explicitly_convertible<U, IntBackend>::value && !is_arithmetic<U>::value), rational_adaptor&>::type operator = (const U& u) \n   {\n      m_value = IntBackend(u);\n   }\n\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   rational_adaptor(rational_adaptor&& o) BOOST_MP_NOEXCEPT_IF(noexcept(rational_type(std::declval<rational_type>()))) : m_value(static_cast<rational_type&&>(o.m_value)) {}\n   rational_adaptor(IntBackend&& o) BOOST_MP_NOEXCEPT_IF(noexcept(rational_type(std::declval<IntBackend>()))) : m_value(static_cast<IntBackend&&>(o)) {}\n   rational_adaptor& operator = (rational_adaptor&& o) BOOST_MP_NOEXCEPT_IF(noexcept(std::declval<rational_type&>() = std::declval<rational_type>()))\n   {\n      m_value = static_cast<rational_type&&>(o.m_value);\n      return *this;\n   }\n#endif\n   rational_adaptor& operator = (const rational_adaptor& o)\n   {\n      m_value = o.m_value;\n      return *this;\n   }\n   rational_adaptor& operator = (const IntBackend& o)\n   {\n      m_value = o;\n      return *this;\n   }\n   template <class Int>\n   typename enable_if<is_integral<Int>, rational_adaptor&>::type operator = (Int i)\n   {\n      m_value = i;\n      return *this;\n   }\n   template <class Float>\n   typename enable_if<is_floating_point<Float>, rational_adaptor&>::type operator = (Float i)\n   {\n      int e;\n      Float f = std::frexp(i, &e);\n      f = std::ldexp(f, std::numeric_limits<Float>::digits);\n      e -= std::numeric_limits<Float>::digits;\n      integer_type num(f);\n      integer_type denom(1u);\n      if(e > 0)\n      {\n         num <<= e;\n      }\n      else if(e < 0)\n      {\n         denom <<= -e;\n      }\n      m_value.assign(num, denom);\n      return *this;\n   }\n   rational_adaptor& operator = (const char* s)\n   {\n      std::string s1;\n      multiprecision::number<IntBackend> v1, v2;\n      char c;\n      bool have_hex = false;\n      const char* p = s; // saved for later\n\n      while((0 != (c = *s)) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F'))))\n      {\n         if(c == 'x' || c == 'X')\n            have_hex = true;\n         s1.append(1, c);\n         ++s;\n      }\n      v1.assign(s1);\n      s1.erase();\n      if(c == '/')\n      {\n         ++s;\n         while((0 != (c = *s)) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F'))))\n         {\n            if(c == 'x' || c == 'X')\n               have_hex = true;\n            s1.append(1, c);\n            ++s;\n         }\n         v2.assign(s1);\n      }\n      else\n         v2 = 1;\n      if(*s)\n      {\n         BOOST_THROW_EXCEPTION(std::runtime_error(std::string(\"Could not parse the string \\\"\") + p + std::string(\"\\\" as a valid rational number.\")));\n      }\n      data().assign(v1, v2);\n      return *this;\n   }\n   void swap(rational_adaptor& o)\n   {\n      std::swap(m_value, o.m_value);\n   }\n   std::string str(std::streamsize digits, std::ios_base::fmtflags f)const\n   {\n      //\n      // We format the string ourselves so we can match what GMP's mpq type does:\n      //\n      std::string result = data().numerator().str(digits, f);\n      if(data().denominator() != 1)\n      {\n         result.append(1, '/');\n         result.append(data().denominator().str(digits, f));\n      }\n      return result;\n   }\n   void negate()\n   {\n      m_value = -m_value;\n   }\n   int compare(const rational_adaptor& o)const\n   {\n      return m_value > o.m_value ? 1 : (m_value < o.m_value ? -1 : 0);\n   }\n   template <class Arithmatic>\n   typename enable_if_c<is_arithmetic<Arithmatic>::value && !is_floating_point<Arithmatic>::value, int>::type compare(Arithmatic i)const\n   {\n      return m_value > i ? 1 : (m_value < i ? -1 : 0);\n   }\n   template <class Arithmatic>\n   typename enable_if_c<is_floating_point<Arithmatic>::value, int>::type compare(Arithmatic i)const\n   {\n      rational_adaptor r;\n      r = i;\n      return this->compare(r);\n   }\n   rational_type& data() { return m_value; }\n   const rational_type& data()const { return m_value; }\n\n   template <class Archive>\n   void serialize(Archive& ar, const mpl::true_&)\n   {\n      // Saving\n      integer_type n(m_value.numerator()), d(m_value.denominator());\n      ar & n;\n      ar & d;\n   }\n   template <class Archive>\n   void serialize(Archive& ar, const mpl::false_&)\n   {\n      // Loading\n      integer_type n, d;\n      ar & n;\n      ar & d;\n      m_value.assign(n, d);\n   }\n   template <class Archive>\n   void serialize(Archive& ar, const unsigned int /*version*/)\n   {\n      typedef typename Archive::is_saving tag;\n      serialize(ar, tag());\n   }\nprivate:\n   rational_type m_value;\n};\n\ntemplate <class IntBackend>\ninline void eval_add(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)\n{\n   result.data() += o.data();\n}\ntemplate <class IntBackend>\ninline void eval_subtract(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)\n{\n   result.data() -= o.data();\n}\ntemplate <class IntBackend>\ninline void eval_multiply(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)\n{\n   result.data() *= o.data();\n}\ntemplate <class IntBackend>\ninline void eval_divide(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)\n{\n   using default_ops::eval_is_zero;\n   if(eval_is_zero(o))\n   {\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero.\"));\n   }\n   result.data() /= o.data();\n}\n\ntemplate <class R, class IntBackend>\ninline typename enable_if_c<number_category<R>::value == number_kind_floating_point>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)\n{\n   //\n   // The generic conversion is as good as anything we can write here:\n   //\n   ::boost::multiprecision::detail::generic_convert_rational_to_float(*result, backend);\n}\n\ntemplate <class R, class IntBackend>\ninline typename enable_if_c<(number_category<R>::value != number_kind_integer) && (number_category<R>::value != number_kind_floating_point)>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)\n{\n   typedef typename component_type<number<rational_adaptor<IntBackend> > >::type comp_t;\n   comp_t num(backend.data().numerator());\n   comp_t denom(backend.data().denominator());\n   *result = num.template convert_to<R>();\n   *result /= denom.template convert_to<R>();\n}\n\ntemplate <class R, class IntBackend>\ninline typename enable_if_c<number_category<R>::value == number_kind_integer>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)\n{\n   typedef typename component_type<number<rational_adaptor<IntBackend> > >::type comp_t;\n   comp_t t = backend.data().numerator();\n   t /= backend.data().denominator();\n   *result = t.template convert_to<R>();\n}\n\ntemplate <class IntBackend>\ninline bool eval_is_zero(const rational_adaptor<IntBackend>& val)\n{\n   return eval_is_zero(val.data().numerator().backend());\n}\ntemplate <class IntBackend>\ninline int eval_get_sign(const rational_adaptor<IntBackend>& val)\n{\n   return eval_get_sign(val.data().numerator().backend());\n}\n\ntemplate<class IntBackend, class V>\ninline void assign_components(rational_adaptor<IntBackend>& result, const V& v1, const V& v2)\n{\n   result.data().assign(v1, v2);\n}\n\ntemplate <class IntBackend>\ninline std::size_t hash_value(const rational_adaptor<IntBackend>& val)\n{\n   std::size_t result = hash_value(val.data().numerator());\n   boost::hash_combine(result, val.data().denominator());\n   return result;\n}\n\n\n} // namespace backends\n\ntemplate<class IntBackend>\nstruct expression_template_default<backends::rational_adaptor<IntBackend> > : public expression_template_default<IntBackend> {};\n   \ntemplate<class IntBackend>\nstruct number_category<backends::rational_adaptor<IntBackend> > : public mpl::int_<number_kind_rational>{};\n\nusing boost::multiprecision::backends::rational_adaptor;\n\ntemplate <class T>\nstruct component_type<rational_adaptor<T> >\n{\n   typedef number<T> type;\n};\n\ntemplate <class IntBackend, expression_template_option ET>\ninline number<IntBackend, ET> numerator(const number<rational_adaptor<IntBackend>, ET>& val)\n{\n   return val.backend().data().numerator();\n}\ntemplate <class IntBackend, expression_template_option ET>\ninline number<IntBackend, ET> denominator(const number<rational_adaptor<IntBackend>, ET>& val)\n{\n   return val.backend().data().denominator();\n}\n\n#ifdef BOOST_NO_SFINAE_EXPR\n\nnamespace detail{\n\ntemplate<class U, class IntBackend>\nstruct is_explicitly_convertible<U, rational_adaptor<IntBackend> > : public is_explicitly_convertible<U, IntBackend> {};\n\n}\n\n#endif\n\n}} // namespaces\n\n\nnamespace std{\n\ntemplate <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>\nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> > : public std::numeric_limits<boost::multiprecision::number<IntBackend, ExpressionTemplates> >\n{\n   typedef std::numeric_limits<boost::multiprecision::number<IntBackend> > base_type;\n   typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend> > number_type;\npublic:\n   BOOST_STATIC_CONSTEXPR bool is_integer = false;\n   BOOST_STATIC_CONSTEXPR bool is_exact = true;\n   BOOST_STATIC_CONSTEXPR number_type (min)() { return (base_type::min)(); }\n   BOOST_STATIC_CONSTEXPR number_type (max)() { return (base_type::max)(); }\n   BOOST_STATIC_CONSTEXPR number_type lowest() { return -(max)(); }\n   BOOST_STATIC_CONSTEXPR number_type epsilon() { return base_type::epsilon(); }\n   BOOST_STATIC_CONSTEXPR number_type round_error() { return epsilon() / 2; }\n   BOOST_STATIC_CONSTEXPR number_type infinity() { return base_type::infinity(); }\n   BOOST_STATIC_CONSTEXPR number_type quiet_NaN() { return base_type::quiet_NaN(); }\n   BOOST_STATIC_CONSTEXPR number_type signaling_NaN() { return base_type::signaling_NaN(); }\n   BOOST_STATIC_CONSTEXPR number_type denorm_min() { return base_type::denorm_min(); }\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\ntemplate <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> >::is_integer;\ntemplate <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> >::is_exact;\n\n#endif\n\n\n}\n\n#endif\n", "meta": {"hexsha": "334238c92f0e842534378d03a4b50de7f6169065", "size": 12632, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/multiprecision/rational_adaptor.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 886.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T20:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:47:52.000Z", "max_issues_repo_path": "nheqminer/3rdparty/boost/multiprecision/rational_adaptor.hpp", "max_issues_repo_name": "EuroLine/nheqminer", "max_issues_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "nheqminer/3rdparty/boost/multiprecision/rational_adaptor.hpp", "max_forks_repo_name": "EuroLine/nheqminer", "max_forks_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 34.6082191781, "max_line_length": 220, "alphanum_fraction": 0.6827105763, "num_tokens": 3159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.034100428166353045, "lm_q1q2_score": 0.015985961088327855}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Standard includes\n#include <chrono>\n\n// Third party includes\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n#include <votca/tools/property.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/gnode.h\"\n#include \"votca/xtp/qmstate.h\"\n#include \"votca/xtp/topology.h\"\n\n// Local private VOTCA includes\n#include \"kmcmultiple.h\"\n\nnamespace votca {\nnamespace xtp {\nvoid KMCMultiple::ParseSpecificOptions(const tools::Property& options) {\n\n  runtime_ = options.get(\".runtime\").as<double>();\n  field_ = options.get(\".field\").as<Eigen::Vector3d>();\n  double mtobohr = 1E9 * tools::conv::nm2bohr;\n  field_ *=\n      (tools::conv::ev2hrt / mtobohr);  // Converting from V/m to Hartree/bohr\n\n  outputtime_ = options.get(\".outputtime\").as<double>();\n  timefile_ = options.ifExistsReturnElseReturnDefault<std::string>(\".timefile\",\n                                                                   timefile_);\n\n  std::string carriertype = options.get(\".carriertype\").as<std::string>();\n  carriertype_ = QMStateType(carriertype);\n  if (!carriertype_.isKMCState()) {\n    throw std::runtime_error(\"KMC cannot be run for state:\" +\n                             carriertype_.ToLongString());\n  }\n\n  log_.setReportLevel(Log::current_level);\n  log_.setCommonPreface(\"\\n ...\");\n}\n\nvoid KMCMultiple::PrintDiffandMu(const Eigen::Matrix3d& avgdiffusiontensor,\n                                 double simtime, unsigned long step) {\n  double absolute_field = field_.norm();\n\n  if (absolute_field == 0) {\n    unsigned long diffusionsteps = step / diffusionresolution_;\n    Eigen::Matrix3d result =\n        avgdiffusiontensor /\n        (double(diffusionsteps) * 2.0 * simtime * double(numberofcarriers_));\n    XTP_LOG(Log::error, log_)\n        << \"\\nStep: \" << step\n        << \" Diffusion tensor averaged over all carriers (nm^2/s):\\n\"\n        << result * tools::conv::bohr2nm * tools::conv::bohr2nm << std::flush;\n  } else {\n    double average_mobility = 0;\n    double bohr2Hrts_to_nm2Vs =\n        tools::conv::bohr2nm * tools::conv::bohr2nm / tools::conv::hrt2ev;\n    XTP_LOG(Log::error, log_) << \"\\nMobilities (nm^2/Vs): \" << std::flush;\n    for (Index i = 0; i < numberofcarriers_; i++) {\n      Eigen::Vector3d velocity = carriers_[i].get_dRtravelled() / simtime;\n      double mobility =\n          velocity.dot(field_) / (absolute_field * absolute_field);\n      XTP_LOG(Log::error, log_)\n          << std::scientific << \"    carrier \" << i + 1\n          << \": mu=\" << mobility * bohr2Hrts_to_nm2Vs << std::flush;\n      average_mobility +=\n          velocity.dot(field_) / (absolute_field * absolute_field);\n    }\n    average_mobility /= double(numberofcarriers_);\n    XTP_LOG(Log::error, log_)\n        << std::scientific\n        << \"  Overall average mobility in field direction <mu>=\"\n        << average_mobility * bohr2Hrts_to_nm2Vs << \" nm^2/Vs  \" << std::flush;\n  }\n}\n\nvoid KMCMultiple::WriteToTrajectory(std::fstream& traj,\n                                    std::vector<Eigen::Vector3d>& startposition,\n                                    double simtime, unsigned long step) const {\n  traj << simtime << \"\\t\";\n  traj << step << \"\\t\";\n  for (Index i = 0; i < numberofcarriers_; i++) {\n    Eigen::Vector3d pos = startposition[i] + carriers_[i].get_dRtravelled();\n    traj << pos.x() * tools::conv::bohr2nm << \"\\t\";\n    traj << pos.y() * tools::conv::bohr2nm << \"\\t\";\n    traj << pos.z() * tools::conv::bohr2nm;\n    if (i < numberofcarriers_ - 1) {\n      traj << \"\\t\";\n    } else {\n      traj << std::endl;\n    }\n  }\n}\n\nvoid KMCMultiple::WriteToEnergyFile(std::fstream& tfile, double simtime,\n                                    unsigned long step) const {\n  double absolute_field = field_.norm();\n  double currentenergy = 0;\n  double currentmobility = 0;\n  Eigen::Vector3d dr_travelled_current = Eigen::Vector3d::Zero();\n  double dr_travelled_field = 0.0;\n  Eigen::Vector3d avgvelocity_current = Eigen::Vector3d::Zero();\n  if (absolute_field != 0) {\n    for (const auto& carrier : carriers_) {\n      dr_travelled_current += carrier.get_dRtravelled();\n      currentenergy += carrier.getCurrentEnergy();\n    }\n    dr_travelled_current /= double(numberofcarriers_);\n    currentenergy /= double(numberofcarriers_);\n    avgvelocity_current = dr_travelled_current / simtime;\n    currentmobility =\n        avgvelocity_current.dot(field_) / (absolute_field * absolute_field);\n    dr_travelled_field = dr_travelled_current.dot(field_) / absolute_field;\n  }\n  double bohr2Hrts_to_nm2Vs =\n      tools::conv::bohr2nm * tools::conv::bohr2nm / tools::conv::hrt2ev;\n  tfile << simtime << \"\\t\" << step << \"\\t\"\n        << currentenergy * tools::conv::hrt2ev << \"\\t\"\n        << currentmobility * bohr2Hrts_to_nm2Vs << \"\\t\"\n        << dr_travelled_field * tools::conv::bohr2nm << \"\\t\"\n        << dr_travelled_current.norm() * tools::conv::bohr2nm << \"\\t\"\n        << std::endl;\n}\n\nvoid KMCMultiple::PrintDiagDandMu(const Eigen::Matrix3d& avgdiffusiontensor,\n                                  double simtime, unsigned long step) {\n  unsigned long diffusionsteps = step / diffusionresolution_;\n  Eigen::Matrix3d result =\n      avgdiffusiontensor /\n      (double(diffusionsteps) * 2.0 * simtime * double(numberofcarriers_));\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n  es.computeDirect(result);\n  double bohr2_nm2 = tools::conv::bohr2nm * tools::conv::bohr2nm;\n  XTP_LOG(Log::error, log_) << \"\\nEigenvalues:\\n \" << std::flush;\n  for (Index i = 0; i < 3; i++) {\n    XTP_LOG(Log::error, log_)\n        << \"Eigenvalue: \" << es.eigenvalues()(i) * bohr2_nm2 << std::flush\n        << \"Eigenvector: \" << es.eigenvectors().col(i).x() << \"   \"\n        << es.eigenvectors().col(i).y() << \"   \" << es.eigenvectors().col(i).z()\n        << \"\\n\"\n        << std::flush;\n  }\n  double bohr2Hrts_to_nm2Vs =\n      tools::conv::bohr2nm * tools::conv::bohr2nm / tools::conv::hrt2ev;\n  // calculate average mobility from the Einstein relation\n  if (field_.norm() == 0) {\n    XTP_LOG(Log::error, log_)\n        << \"The following value is calculated using the Einstein relation \"\n           \"and assuming an isotropic medium\"\n        << std::flush;\n    double avgD = 1. / 3. * es.eigenvalues().sum();\n    double average_mobility = std::abs(avgD / temperature_);\n    XTP_LOG(Log::error, log_)\n        << std::scientific << \"  Overall average mobility <mu>=\"\n        << average_mobility * bohr2Hrts_to_nm2Vs << \" nm^2/Vs \" << std::flush;\n  }\n}\n\nvoid KMCMultiple::PrintChargeVelocity(double simtime) {\n  Eigen::Vector3d avg_dr_travelled = Eigen::Vector3d::Zero();\n  for (Index i = 0; i < numberofcarriers_; i++) {\n    XTP_LOG(Log::error, log_)\n        << std::scientific << \"    carrier \" << i + 1 << \": \"\n        << carriers_[i].get_dRtravelled().transpose() / simtime *\n               tools::conv::bohr2nm\n        << std::flush;\n    avg_dr_travelled += carriers_[i].get_dRtravelled();\n  }\n  avg_dr_travelled /= double(numberofcarriers_);\n\n  Eigen::Vector3d avgvelocity = avg_dr_travelled / simtime;\n  XTP_LOG(Log::error, log_)\n      << std::scientific << \"  Overall average velocity (nm/s): \"\n      << avgvelocity.transpose() * tools::conv::bohr2nm << std::flush;\n}\n\nvoid KMCMultiple::RunVSSM() {\n\n  std::chrono::time_point<std::chrono::system_clock> realtime_start =\n      std::chrono::system_clock::now();\n  XTP_LOG(Log::error, log_)\n      << \"\\nAlgorithm: VSSM for Multiple Charges\" << std::flush;\n  XTP_LOG(Log::error, log_)\n      << \"number of carriers: \" << numberofcarriers_ << std::flush;\n  XTP_LOG(Log::error, log_)\n      << \"number of nodes: \" << nodes_.size() << std::flush;\n\n  bool checkifoutput = (outputtime_ != 0);\n  double nexttrajoutput = 0;\n  unsigned long maxsteps = boost::numeric_cast<unsigned long>(runtime_);\n  unsigned long outputstep = boost::numeric_cast<unsigned long>(outputtime_);\n  bool stopontime = false;\n\n  if (runtime_ > 100) {\n    XTP_LOG(Log::error, log_)\n        << \"stop condition: \" << maxsteps << \" steps.\" << std::flush;\n\n    if (checkifoutput) {\n      XTP_LOG(Log::error, log_) << \"output frequency: \";\n      XTP_LOG(Log::error, log_)\n          << \"every \" << outputstep << \" steps.\" << std::flush;\n    }\n  } else {\n    stopontime = true;\n    XTP_LOG(Log::error, log_)\n        << \"stop condition: \" << runtime_ << \" seconds runtime.\" << std::flush;\n\n    if (checkifoutput) {\n      XTP_LOG(Log::error, log_) << \"output frequency:\\n \"\n                                   \"every \"\n                                << outputtime_ << \" seconds.\" << std::flush;\n    }\n  }\n  XTP_LOG(Log::error, log_)\n      << \"(If you specify runtimes larger than 100 kmcmultiple assumes that \"\n         \"you are specifying the number of steps for both runtime and \"\n         \"outputtime.)\"\n      << std::flush;\n\n  if (!stopontime && outputtime_ != 0 && floor(outputtime_) != outputtime_) {\n    throw std::runtime_error(\n        \"ERROR in kmcmultiple: runtime was specified in steps (>100) and \"\n        \"outputtime in seconds (not an integer). Please use the same units for \"\n        \"both input parameters.\");\n  }\n\n  if (numberofcarriers_ > Index(nodes_.size())) {\n    throw std::runtime_error(\n        \"ERROR in kmcmultiple: specified number of carriers is greater than \"\n        \"the \"\n        \"number of nodes. This conflicts with single occupation.\");\n  }\n\n  std::fstream traj;\n  std::fstream tfile;\n\n  if (checkifoutput) {\n\n    XTP_LOG(Log::error, log_)\n        << \"Writing trajectory to \" << trajectoryfile_ << \".\" << std::flush;\n    traj.open(trajectoryfile_, std::fstream::out);\n\n    traj << \"time[s]\\tsteps\\t\";\n    for (Index i = 0; i < numberofcarriers_; i++) {\n      traj << \"carrier\" << i + 1 << \" x_\\t\";\n      traj << \"carrier\" << i + 1 << \" y_\\t\";\n      traj << \"carrier\" << i + 1 << \" z_\";\n      if (i < numberofcarriers_ - 1) {\n        traj << \"'\\t\";\n      }\n    }\n    traj << std::endl;\n    if (!timefile_.empty()) {\n      XTP_LOG(Log::error, log_)\n          << \"Writing time dependence of energy and mobility to \" << timefile_\n          << \".\" << std::flush;\n      tfile.open(timefile_, std::fstream::out);\n      tfile << \"time[s]\\t \"\n               \"steps\\tenergy_per_carrier[eV]\\tmobility[nm**2/\"\n               \"Vs]\\tdistance_fielddirection[nm]\\tdistance_absolute[nm]\"\n            << std::endl;\n    }\n  }\n  RandomlyCreateCharges();\n  std::vector<Eigen::Vector3d> startposition(numberofcarriers_,\n                                             Eigen::Vector3d::Zero());\n  for (Index i = 0; i < numberofcarriers_; i++) {\n    startposition[i] = carriers_[i].getCurrentPosition();\n  }\n\n  traj << 0 << \"\\t\";\n  traj << 0 << \"\\t\";\n  for (Index i = 0; i < numberofcarriers_; i++) {\n    traj << startposition[i].x() * tools::conv::bohr2nm << \"\\t\";\n    traj << startposition[i].y() * tools::conv::bohr2nm << \"\\t\";\n    traj << startposition[i].z() * tools::conv::bohr2nm;\n    if (i < numberofcarriers_ - 1) {\n      traj << \"\\t\";\n    } else {\n      traj << std::endl;\n    }\n  }\n\n  std::vector<GNode*> forbiddennodes;\n  std::vector<GNode*> forbiddendests;\n\n  Eigen::Matrix3d avgdiffusiontensor = Eigen::Matrix3d::Zero();\n\n  double simtime = 0.0;\n  unsigned long step = 0;\n\n  while (((stopontime && simtime < runtime_) ||\n          (!stopontime && step < maxsteps))) {\n\n    std::chrono::duration<double> elapsed_time =\n        std::chrono::system_clock::now() - realtime_start;\n    if (elapsed_time.count() > (maxrealtime_ * 60. * 60.)) {\n      XTP_LOG(Log::error, log_)\n          << \"\\nReal time limit of \" << maxrealtime_ << \" hours (\"\n          << Index(maxrealtime_ * 60 * 60 + 0.5)\n          << \" seconds) has been reached. Stopping here.\\n\"\n          << std::flush;\n      break;\n    }\n\n    double cumulated_rate = 0;\n    for (const auto& carrier : carriers_) {\n      cumulated_rate += carrier.getCurrentEscapeRate();\n    }\n    if (cumulated_rate <= 0) {  // this should not happen: no possible jumps\n                                // defined for a node\n      throw std::runtime_error(\n          \"ERROR in kmcmultiple: Incorrect rates. All \"\n          \"the escape rates for the current setting are 0.\");\n    }\n\n    double dt = Promotetime(cumulated_rate);\n\n    simtime += dt;\n    step++;\n\n    for (auto& carrier : carriers_) {\n      carrier.updateOccupationtime(dt);\n    }\n\n    ResetForbiddenlist(forbiddennodes);\n    bool level1step = true;\n    while (level1step) {\n\n      // determine which electron will escape\n      GNode* newnode = nullptr;\n      Chargecarrier* affectedcarrier = ChooseAffectedCarrier(cumulated_rate);\n\n      if (CheckForbidden(affectedcarrier->getCurrentNode(), forbiddennodes)) {\n        continue;\n      }\n      ResetForbiddenlist(forbiddendests);\n      while (true) {\n        // LEVEL 2\n\n        const GLink& event =\n            ChooseHoppingDest(affectedcarrier->getCurrentNode());\n        newnode = event.getDestination();\n\n        if (newnode == nullptr) {\n          AddtoForbiddenlist(affectedcarrier->getCurrentNode(), forbiddennodes);\n          break;  // select new escape node (ends level 2 but without setting\n                  // level1step to 1)\n        }\n\n        // check after the event if this was allowed\n        if (CheckForbidden(*newnode, forbiddendests)) {\n          continue;\n        }\n\n        // if the new segment is unoccupied: jump; if not: add to forbidden\n        // list and choose new hopping destination\n        if (newnode->isOccupied()) {\n          if (CheckSurrounded(affectedcarrier->getCurrentNode(),\n                              forbiddendests)) {\n            AddtoForbiddenlist(affectedcarrier->getCurrentNode(),\n                               forbiddennodes);\n            break;  // select new escape node (ends level 2 but without\n                    // setting level1step to 1)\n          }\n          AddtoForbiddenlist(*newnode, forbiddendests);\n          continue;  // select new destination\n        } else {\n          affectedcarrier->jumpAccordingEvent(event);\n          level1step = false;\n          break;  // this ends LEVEL 2 , so that the time is updated and the\n                  // next MC step started\n        }\n        // END LEVEL 2\n      }\n      // END LEVEL 1\n    }\n\n    if (step % diffusionresolution_ == 0) {\n      for (const auto& carrier : carriers_) {\n        avgdiffusiontensor += (carrier.get_dRtravelled()) *\n                              (carrier.get_dRtravelled()).transpose();\n      }\n    }\n\n    if (step != 0 && step % intermediateoutput_frequency_ == 0) {\n      PrintDiffandMu(avgdiffusiontensor, simtime, step);\n    }\n\n    if (checkifoutput) {\n      bool outputsteps = (!stopontime && step % outputstep == 0);\n      bool outputtime = (stopontime && simtime > nexttrajoutput);\n      if (outputsteps || outputtime) {\n        // write to trajectory file\n        nexttrajoutput = simtime + outputtime_;\n        WriteToTrajectory(traj, startposition, simtime, step);\n        if (!timefile_.empty()) {\n          WriteToEnergyFile(tfile, simtime, step);\n        }\n      }\n    }\n  }  // KMC\n\n  if (checkifoutput) {\n    traj.close();\n    if (!timefile_.empty()) {\n      tfile.close();\n    }\n  }\n\n  WriteOccupationtoFile(simtime, occfile_);\n\n  XTP_LOG(Log::error, log_) << \"\\nfinished KMC simulation after \" << step\n                            << \" steps.\\n\"\n                               \"simulated time \"\n                            << simtime << \" seconds.\\n\"\n                            << std::flush;\n\n  PrintChargeVelocity(simtime);\n\n  XTP_LOG(Log::error, log_) << \"\\nDistances travelled (nm): \" << std::flush;\n  for (Index i = 0; i < numberofcarriers_; i++) {\n    XTP_LOG(Log::error, log_)\n        << std::scientific << \"    carrier \" << i + 1 << \": \"\n        << carriers_[i].get_dRtravelled().transpose() * tools::conv::bohr2nm\n        << std::flush;\n  }\n\n  PrintDiffandMu(avgdiffusiontensor, simtime, step);\n  PrintDiagDandMu(avgdiffusiontensor, simtime, step);\n\n  return;\n}\n\nbool KMCMultiple::Evaluate(Topology& top) {\n\n  XTP_LOG(Log::error, log_) << \"\\n-----------------------------------\"\n                               \"\\n      KMC FOR MULTIPLE CHARGES\"\n                               \"\\n-----------------------------------\\n\"\n                            << std::flush;\n\n  XTP_LOG(Log::info, log_) << \"\\nInitialising random number generator\"\n                           << std::flush;\n  RandomVariable_.init(seed_);\n\n  LoadGraph(top);\n  RunVSSM();\n  std::cout << log_;\n  return true;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "1627950277751e22490417c21a86095f39bcd21d", "size": 16971, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/calculators/kmcmultiple.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/calculators/kmcmultiple.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/calculators/kmcmultiple.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7284210526, "max_line_length": 80, "alphanum_fraction": 0.5956042661, "num_tokens": 4529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.03410042804365097, "lm_q1q2_score": 0.01598596103080627}}
{"text": "//\n// Created by minseok on 11/09/18.\n//\n#include <Eigen/Geometry>\n#include \"BVHparser.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <math.h>\n#include <algorithm>\n#define M_PI 3.14159265358979323846\n\nusing namespace std;\n\nMotionNode::MotionNode()\n{\n\tname = \"\";\n\taxisOrder = \"\";\n\tisRoot = false;\n\tisEnd = false;\n\tparent = nullptr;\n\tnext = nullptr;\n\tchilds = vector<MotionNode*>();\n\tchannelNum = 0;\n\t// orientation = Eigen::AngleAxisd::Identity();\n}\nMotionNode* MotionNode::getParent()\n{\n\treturn parent;\n}\nvector<MotionNode*> MotionNode::getChilds()\n{\n\treturn childs;\n}\nvoid MotionNode::setParent(MotionNode* pnode)\n{\n\tparent = pnode;\n\tpnode->addChild(this);\n}\nvoid MotionNode::addChild(MotionNode* cnode)\n{\n\tchilds.push_back(cnode);\n}\nvoid MotionNode::setRoot()\n{\n\tisRoot = true;\n}\nvoid MotionNode::setEnd()\n{\n\tisEnd = true;\n}\nvoid MotionNode::setName(string mname)\n{\n\tname = mname;\n}\nvoid MotionNode::setAxisOrder(string maxisOrder)\n{\n\taxisOrder = maxisOrder;\n}\nvoid MotionNode::setOffset(float x, float y, float z)\n{\n\toffset[0] = x;\n\toffset[1] = y;\n\toffset[2] = z;\n}\nvoid MotionNode::setNext(MotionNode *nextNode)\n{\n\tnext = nextNode;\n}\nvoid MotionNode::setChannelNum(int mchannelNum)\n{\n\tchannelNum = mchannelNum;\n}\nbool MotionNode::checkEnd()\n{\n\treturn isEnd;\n}\nstring MotionNode::getName_std()\n{\n\tif(match_name_list.size()>=1)\n\t\treturn match_name_list[0];\n\telse\n\t{\n\t\tcout<<\"no such name in list\"<<name<<endl;\n\t\treturn \"\";\n\t}\n}\nstring MotionNode::getName()\n{\n\treturn name;\n}\nstring MotionNode::getAxisOrder()\n{\n\treturn axisOrder;\n}\nvoid MotionNode::getOffset(float* outOffset)\n{\n\tfor(int i=0;i<3;i++)\n\t{\n\t\toutOffset[i] = offset[i];\n\t}\n}\nfloat MotionNode::getOffset(int index)\n{\n\treturn offset[index];\n}\nint MotionNode::getChannelNum()\n{\n\treturn channelNum;\n}\nMotionNode* MotionNode::getNextNode()\n{\n\treturn next;\n}\nvoid MotionNode::initData(int frames)\n{\n\tdata = new float*[frames];\n\tfor(int i = 0; i < frames; i++)\n\t{\n\t\tdata[i] = new float[channelNum];\n\t}\n}\nbool MotionNode::ContainedInModel()\n{\n\tif(match_name_list.size()==0)\n\t\treturn false;\n\telse\n\t\treturn true;\n}\n/// convert quaternion -> log(quaternion)\nEigen::Vector3d QuaternionToAngleAxis(Eigen::Quaterniond qt)\n{\n\tdouble angle = 2.0*atan2(qt.vec().norm(), qt.w());\n\tif(std::abs(angle) < 1e-4)\n\t\treturn Eigen::Vector3d::Zero();\n\treturn angle * qt.vec().normalized();\n}\n\n/// convert log(quaternion) -> quaternion\nEigen::Quaterniond AngleAxisToQuaternion(Eigen::Vector3d angleAxis)\n{\n\tEigen::Quaterniond qt;\n\tif(angleAxis.norm() < 1e-4)\n\t\treturn Eigen::Quaterniond(1,0,0,0);\n\tqt.vec() = angleAxis.normalized() * sin(angleAxis.norm());\n\tqt.w() = cos(angleAxis.norm());\n\treturn qt;\n}\n\nvoid BVHparser::initMatchNameListForMotionNode(const char* path)\n{\n\tstring line;\n\tstringstream s;\n\tifstream in(path);\n    // std::cout<<\"# reading file \"<<path<<std::endl;\n\tstring muscleName_std;\n\tstring muscleName;\n\tMotionNode* curNode = getRootNode();\n\tfloat value;\n\twhile(!in.eof())\n\t{\n\t\tgetline(in, line);\n\t\tif(line.empty())\n\t\t\tbreak;\n\t\ts = stringstream(line);\n\t\tstd::vector<string> match_name_list;\n\t\twhile(!s.eof())\n\t\t{\n\t\t\ts>>muscleName;\n\t\t\tmatch_name_list.push_back(muscleName);\n\t\t}\n\t\tcurNode = getRootNode();\n\t\twhile(curNode!=NULL)\n\t\t{\n\t\t\tfor(auto& name : match_name_list)\n\t\t\t{\n\t\t\t\tif(curNode->getName() == name)\n\t\t\t\t{\n\t\t\t\t\tcurNode->match_name_list = match_name_list;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurNode = curNode->getNextNode();\n\t\t}\n\t}\n\tin.close();\n}\n\n// BVHparser::BVHparser(const char* path)\n// {\n\n// }\n\nBVHparser::BVHparser(const char* path, BVHType bvhType)\n{\n\tmBvhType = bvhType;\n\tthis->scale = 1.0;\n\tint lineNum = 0;\n\tint channelNum = 0;\n\tstring channels[6];\n\tfloat offx, offy, offz;\n\tmPath = path;\n\tlowerBodyOnly = false;\n\tupperBodyOnly = false;\n\tifstream in;\n\tin.open(path, ios::in);\n\tif(!in)\n\t{\n\t\tcerr << \"Cannot open \"<<path<<endl; exit(1);\n\t}\n\tstring line;\n\tgetline(in, line);\t\t\t\t\t\t\t\t\t\t//HIERARCHY\n\tlineNum++;\n\n\tif(line.compare(0,9,\"HIERARCHY\")!=0)\n\t{ \n\t\tcout << \"Check the file format. The line number \"<<lineNum<<\" is not fit to the format\"<<endl;\n\t\tcout<<line.compare(\"HIERARCHY\")<<endl;\n\t\tcout<<line.length()<<endl;\n\t\tcout << line<<endl;\n\t\texit(-1);\n\t}\n\tgetline(in, line);\t\t\t\t\t\t\t\t\t\t//ROOT Hips\n\tlineNum++;\n\trootNode = new MotionNode();\n\trootNode->setRoot();\n\tistringstream s(line);\n\tstring bvh_keyword;\n\tstring bvh_nodeName;\n\ts >> bvh_keyword; s >> bvh_nodeName;\n\tif(bvh_keyword.compare(\"ROOT\")!=0)\n\t{\n\t\tcout << \"Check the file format. The line number \"<<lineNum<<\" is not fit to the format\"<<endl;\n\t\tcout << line<<endl;\n\t\texit(-1);\n\t}\n\trootNode->setName(bvh_nodeName);\n\tgetline(in, line);\t\t\t\t\t\t\t\t\t\t//{\n\n\tgetline(in, line);\t\t\t\t\t\t\t\t\t\t//\tOFFSET 0.00 0.00 0.00\n\ts.str(\"\");\n\ts = istringstream(line);\n\ts >> bvh_keyword; s >> offx; s >> offy; s >> offz;\n\tif(mBvhType == BVHType::BASKET)\n\t\trootNode->setOffset(offx, offy-85.5177, offz);\n\telse\n\t\trootNode->setOffset(offx, offy, offz);\n\n\n\tgetline(in, line);\t\t\t\t\t\t\t\t\t\t//\tCHANNELS 6 Xposition Yposition Zposition Xrotation Yrotation Zrotation\n\ts.str(\"\");\n\ts = istringstream(line);\n\ts >> bvh_keyword; s >> channelNum;\n\tstring newAxisOrder = \"\";\n\tfor(int i = 0; i < channelNum; i++)\n\t{\n\t\ts >> channels[i];\n\t\tif(channels[i].substr(1) == \"rotation\")\n\t\t{\n\t\t\ttransform(channels[i].begin(), channels[i].end(), channels[i].begin(), ::tolower);\n\t\t\tnewAxisOrder += channels[i][0];\n\t\t}\n\t}\n\trootNode->setAxisOrder(newAxisOrder);\n\trootNode->setChannelNum(channelNum);\n\tMotionNode* prevNode = rootNode;\n\tMotionNode* prevNode4NextNode = rootNode;\n\tgetline(in, line);\n\twhile(line.compare(0, 6, \"MOTION\") != 0)\t\t\t\t\t\t\n\t{\n\t\ts.str(\"\");\n\t\ts = istringstream(line);\n\t\ts >> bvh_keyword; s >> bvh_nodeName;\n\t\tif(bvh_keyword==\"JOINT\")\t\t\t\t\t\t\t//\tJOINT LeftUpLeg\n\t\t{\n\t\t\tMotionNode *newNode = new MotionNode();\n\t\t\tnewNode->setName(bvh_nodeName);\n\n\t\t\tgetline(in, line);\t\t\t\t\t\t\t\t//\t{\n\t\t\tgetline(in, line);\t\t\t\t\t\t\t\t//\t\tOFFSET 3.64953 0.00000 0.00000\n\t\t\ts.str(\"\");\n\t\t\ts = istringstream(line);\n\t\t\ts >> bvh_keyword; s >> offx; s >> offy; s >> offz;\n\t\t\tnewNode->setOffset(offx, offy, offz);\n\n\t\t\tgetline(in, line);\t\t\t\t\t\t\t\t//\t\tCHANNELS 3 Xrotation Yrotation Zrotation\n\t\t\ts.str(\"\");\n\t\t\ts = istringstream(line);\n\t\t\ts >> bvh_keyword; s >> channelNum;\n\n\t\t\tnewAxisOrder = \"\";\n\t\t\tfor(int i = 0;i < channelNum;i++)\n\t\t\t{\n\t\t\t\ts >> channels[i];\n\t\t\t\tif(channels[i].substr(1) == \"rotation\")\n\t\t\t\t{\n\t\t\t\t\ttransform(channels[i].begin(), channels[i].end(), channels[i].begin(), ::tolower);\n\t\t\t\t\tnewAxisOrder += channels[i][0];\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewNode->setParent(prevNode);\n\t\t\tnewNode->setChannelNum(channelNum);\n\t\t\tnewNode->setAxisOrder(newAxisOrder);\n\t\t\tprevNode4NextNode->setNext(newNode);\n\t\t\tprevNode = newNode;\n\t\t\tprevNode4NextNode = newNode;\n\t\t}\n\t\telse if(bvh_keyword ==\"End\")\t\t\t\t\t\t//\tEnd Site\n\t\t{\n\t\t\tMotionNode *newNode = new MotionNode();\n\t\t\tnewNode->setName(prevNode->getName()+bvh_nodeName);\n\t\t\tnewNode->setEnd();\n\t\t\tgetline(in, line);\t\t\t\t\t\t\t\t//\t{\n\t\t\tgetline(in, line);\t\t\t\t\t\t\t\t//\t\tOFFSET 3.64953 0.00000 0.00000\n\t\t\ts.str(\"\");\n\t\t\ts = istringstream(line);\n\t\t\ts >> bvh_keyword; s >> offx; s >> offy; s >> offz;\n\t\t\tnewNode->setOffset(offx, offy, offz);\n\n\t\t\tnewNode->setParent(prevNode);\n\t\t\tgetline(in, line);\t\t\t\t\t\t\t\t//\t}\n\t\t}\n\t\telse if(bvh_keyword ==\"}\")\n\t\t{\n\t\t\tprevNode = prevNode->getParent();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"Check the file format. \"<< bvh_keyword <<\" is right?\" <<endl;\n\t\t\texit(-1);\n\t\t}\n\t\tgetline(in, line);\n\t}\n\n// \tStart MotionNode\t\t\t\t\t\t\t\t\t\t//MOTION\n\tstring str1, str2;\t//to get the string for format\n\tfloat fvalue;\n\tgetline(in, line);\t\t\t\t\t\t\t\t\t\t//Frames: 4692\n\ts.str(\"\");\n\ts = istringstream(line);\n\ts >> str1; s >> fvalue;\n\tframes = fvalue;\n\n\tgetline(in, line);\t\t\t\t\t\t\t\t\t\t//Frame Time: 0.008333\n\ts.str(\"\");\n\ts = istringstream(line);\n\ts >> str1; s >> str2; s >> fvalue;\n\tframeTime = fvalue;\n\n\t// cout << \"frames : \" << frames <<\", frame time : \" << frameTime << endl;\n\n\tfloat f[6];\n\tMotionNode *curNode;\n\tcurNode = rootNode;\n\twhile(curNode != nullptr)\n\t{\n\t\tcurNode->initData(frames);\n\t\tcurNode = curNode->getNextNode();\n\t}\n\n\tfor(int i = 0; i < frames; i++)\n\t{\n\t\tcurNode = rootNode;\n\t\tgetline(in, line);\n\t\ts.str(\"\");\n\t\ts = istringstream(line);\n\t\twhile(curNode != nullptr)\n\t\t{\n\t\t\tfor(int j = 0; j < curNode->getChannelNum(); j++)\n\t\t\t{\n\t\t\t\ts >> f[j];\n\t\t\t\tcurNode->data[i][j] = f[j];\n\t\t\t}\n\t\t\tcurNode = curNode->getNextNode();\n\t\t}\n\n\t}\n\tin.close();\n\tEigen::Quaterniond q;\n\tEigen::Vector3d euler;\n\tcurNode = rootNode;\n\tfor(int i = 0; i < frames; i++)\n\t{\n\t\tq = Eigen::Quaterniond::Identity();\n\t\tfor(int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif(curNode->getAxisOrder().substr(j,1).compare(\"x\") == 0)\n\t\t\t{\n\t\t\t\tq = q * Eigen::AngleAxisd(curNode->data[i][j+3]/360.0 * 2.0 * M_PI, Eigen::Vector3d::UnitX());\n\t\t\t}\n\t\t\telse if(curNode->getAxisOrder().substr(j,1).compare(\"y\") == 0)\n\t\t\t{\n\t\t\t\tq = q * Eigen::AngleAxisd(curNode->data[i][j+3]/360.0 * 2.0 * M_PI, Eigen::Vector3d::UnitY());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tq = q * Eigen::AngleAxisd(curNode->data[i][j+3]/360.0 * 2.0 * M_PI, Eigen::Vector3d::UnitZ());\n\t\t\t}\n\t\t}\n\t\tfloat theta;\n\t\ttheta = atan2(sqrt(q.x()*q.x() + q.y()*q.y() + q.z()*q.z()), q.w());\n\t\tEigen::Vector3d root_axis = Eigen::Vector3d(q.x(), q.y(), q.z());\n\t\troot_axis.normalize();\n\t\tcurNode->data[i][3] = 2.0 * theta * root_axis.x();\n\t\tcurNode->data[i][4] = 2.0 * theta * root_axis.y();\n\t\tcurNode->data[i][5] = 2.0 * theta * root_axis.z();\n\t}\n\tcurNode = curNode->getNextNode();\n\twhile(curNode != nullptr)\n\t{\n\t\tfor(int i = 0; i < frames; i++)\n\t\t{\n\t\t\tq = Eigen::Quaterniond::Identity();\n\t\t\tfor(int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif(curNode->getAxisOrder().substr(j,1).compare(\"x\") == 0)\n\t\t\t\t{\n\t\t\t\t\tq = q * Eigen::AngleAxisd(curNode->data[i][j]/360.0 * 2.0 * M_PI, Eigen::Vector3d::UnitX());\n\t\t\t\t}\n\t\t\t\telse if(curNode->getAxisOrder().substr(j,1).compare(\"y\") == 0)\n\t\t\t\t{\n\t\t\t\t\tq = q * Eigen::AngleAxisd(curNode->data[i][j]/360.0 * 2.0 * M_PI, Eigen::Vector3d::UnitY());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tq = q * Eigen::AngleAxisd(curNode->data[i][j]/360.0 * 2.0 * M_PI, Eigen::Vector3d::UnitZ());\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tfloat theta;\n\t\t\ttheta = atan2(sqrt(q.x()*q.x() + q.y()*q.y() + q.z()*q.z()), q.w());\n\t\t\tEigen::Vector3d root_axis = Eigen::Vector3d(q.x(), q.y(), q.z());\n\t\t\troot_axis.normalize();\n\t\t\tcurNode->data[i][0] = 2.0 * theta * root_axis.x();\n\t\t\tcurNode->data[i][1] = 2.0 * theta * root_axis.y();\n\t\t\tcurNode->data[i][2] = 2.0 * theta * root_axis.z();\n\t\t}\n\t\tcurNode = curNode->getNextNode();\n\t}\n\t// this->initMatchNameListForMotionNode(\"../motion/bodyNameMatch.txt\");\n}\n\n\n\nMotionNode* BVHparser::getRootNode()\n{\n\treturn rootNode;\n}\nstring bvhpath_2_skelpath_(const char* path)\n{\n\tstring pathString; pathString = path;\n\tif(pathString.find(\".bvh\") != std::string::npos)\n\t{\n\t\tpathString.erase(pathString.find(\".bvh\"), 5);\n\t}\n\treturn pathString;\n}\n\nstring getFileName_(const char* path)\n{\n\tstring pathString; pathString = path;\n\tint cur = 0;\n\twhile(pathString.find(\"/\") != std::string::npos)\n\t{\n\t\tpathString.erase(0, pathString.find(\"/\")+1);\n\t}\n\n\treturn pathString.substr(0, pathString.find(\".\"));\n}\n\nEigen::Vector3d getShaft(float* childOffset)\n{\n\tEigen::Vector3d shaft((fabs(childOffset[0])>fabs(childOffset[1]) && fabs(childOffset[0])>fabs(childOffset[2]))? childOffset[0]/fabs(childOffset[0]): 0.0,\n\t\t\t\t\t\t(fabs(childOffset[1])>fabs(childOffset[0]) && fabs(childOffset[1])>fabs(childOffset[2]))? childOffset[1]/fabs(childOffset[1]) : 0.0,\n\t\t\t\t\t\t(fabs(childOffset[2])>fabs(childOffset[0]) && fabs(childOffset[2])>fabs(childOffset[1]))? childOffset[2]/fabs(childOffset[2]) : 0.0);\n\treturn shaft;\n\n}\n//node's size is fixed to 0.1, 0.1, 0.1\n#include <boost/filesystem.hpp>\n// #define PATH_MAX 100\nvoid BVHparser::writeSkelFile()\n{\n\tofstream outfile;\n\n\tboost::filesystem::path dir(\"../data/skels/\");\n\n\tif(!(boost::filesystem::exists(dir))){\n\t    // std::cout<<\"Doesn't Exists\"<<std::endl;\n\t    if (boost::filesystem::create_directory(dir))\n\t        std::cout << \"../data/skels directory was successfully created !\" << std::endl;\n\t}\n\t// if(n == 0)\n\toutfile.open(\"../data/skels/\"+getFileName_(mPath)+\".skel\", ios::trunc);\n\n\tchar resolved_path[PATH_MAX]; \n\trealpath(\"../\", resolved_path); \n\t// printf(\"\\n%s\\n\",resolved_path); \n\n\tstd::string absolutePathProject = resolved_path;\n\n\tskelFilePath = absolutePathProject+\"/data/skels/\"+getFileName_(mPath)+\".skel\";\n\t// else\n\t// \toutfile.open(bvhpath_2_skelpath_(mPath)+\"Mocap.skel\", ios::trunc);\n\toutfile << fixed << showpoint;\n\toutfile << setprecision(4);\n\toutfile << \"<?xml version=\\\"1.0\\\" ?>\" <<endl;\n\toutfile << \"<skel version=\\\"1.0\\\">\" <<endl;\n\t// outfile << \"    <world name=\\\"world 1\\\">\" <<endl;\n\toutfile << \"\t\t<physics>\"<<endl;\n    outfile << \"\t\t\t<time_step>0.001</time_step>\"<<endl;\n    outfile << \"\t\t\t<gravity>0 -9.81 0</gravity>\"<<endl;\n    outfile << \"\t\t\t<collision_detector>bullet</collision_detector>\"<<endl;\n    outfile << \"\t\t</physics>\"<<endl;\n    outfile << \"\t\t<skeleton name=\\\"\"<< getFileName_(mPath) << \"\\\">\"<<endl;\n\n    //outfile << \"\t\t<skeleton name=\\\"biped\\\">\"<<endl;\n    outfile << \"\t\t\t<transformation>0 0 0 0 0 0</transformation>\"<<endl;\n    MotionNode *curNode = rootNode;\n    MotionNode *parentNode = nullptr;\n    int tabCount = 3;\n    float curOffset[3];\n    float parentOffset[3];\n    float childOffset[3];\n    float resize_factor = 0.01;\n    while(curNode != nullptr)\n    {\n\n    \tparentNode = curNode->getParent();\n    \tcurNode->getOffset(curOffset);\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"<body name=\\\"\" <<curNode->getName() << \"\\\">\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n\n    \t// Eigen::AngleAxisd curOrientation = Eigen::AngleAxisd::Identity();\n    \twhile(parentNode!= nullptr)\n    \t{\n    \t\tparentNode->getOffset(parentOffset);\n    \t\tfor(int i = 0; i<3; i++)\n    \t\t{\n    \t\t\tcurOffset[i] += parentOffset[i];\n    \t\t}\n    \t\t// curOrientation = parentNode->orientation * curOrientation;\n    \t\tparentNode = parentNode->getParent();\n    \t}\n    \toutfile << \"\t<transformation>\";\n\n\t   \toutfile << curOffset[0]*resize_factor <<\" \"<< curOffset[1]*resize_factor<<\" \"<< curOffset[2]*resize_factor<<\" \";\n\n    \tif(curNode->getChilds().size()==1)\n    \t{\n    \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n    \t\tEigen::Vector3d shaft = getShaft(childOffset);\n\n    \t\tif(shaft.norm() == 0.0)\n    \t\t{\n    \t\t\toutfile <<\"0 0 0</transformation>\" <<endl;\n\t   \t\t}\n    \t\telse\n    \t\t{\n    \t\t\tEigen::Vector3d targetShaft(childOffset[0], childOffset[1], childOffset[2]);\n\n    \t\t\ttargetShaft.normalize();\n    \t\t\tshaft = getShaft(childOffset);\n\n    \t\t\tEigen::VectorXd axis = shaft.cross(targetShaft);\n    \t\t\tdouble cosAngle = shaft.dot(targetShaft);\n    \t\t\tdouble angle = atan2(axis.norm(), cosAngle);\n    \t\t\taxis.normalize();\n    \t\t\taxis*= angle;\n    \t\t\t// Eigen::AngleAxisd mNodeOrientation = Eigen::AngleAxisd(angle, axis);\n\n    \t\t\t// curNode->orientation = mNodeOrientation;\n    \t\t\t// axis = mNodeOrientation.axis();\n\n    \t\t\toutfile<<axis[0]<<\" \"<<axis[1]<<\" \"<<axis[2]<<\"</transformation>\"<<endl;\n    \t\t}\n    \t}\n    \telse\n    \t{\n    \t\toutfile <<\"0 0 0</transformation>\" <<endl;\n    \t}\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t<inertia>\" <<endl;\n           \n    \toutfile << \"\t\t\t\";\n    \tif(curNode->getName().compare(0, 4, \"Head\")==0)\n    \t{\n    \t\toutfile <<\t\"\t\t<mass>\"<<8.0<<\"</mass>\"<<endl;\n    \t}\n    \telse if(curNode->getName().compare(0, 5, \"Spine\")==0)\n    \t{\n    \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n       \t\toutfile << \"\t\t<mass>\";\n       \t\toutfile <<5.0\n       \t\t<<\"</mass>\"<<endl;\n    \t}\n       \telse if(curNode->getChilds().size()==1)\n       \t{\n       \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n\t    \toutfile << \"\t\t<mass>\"\n\t    \t<<((fabs(childOffset[0])>fabs(childOffset[1]) && fabs(childOffset[0])>fabs(childOffset[2]))? fabs(childOffset[0]) : 5.0 )\n\t    \t*((fabs(childOffset[1])>fabs(childOffset[0]) && fabs(childOffset[1])>fabs(childOffset[2]))? fabs(childOffset[1]) : 5.0 )\n\t    \t*((fabs(childOffset[2])>fabs(childOffset[0]) && fabs(childOffset[2])>fabs(childOffset[1]))? fabs(childOffset[2]) : 5.0 ) *resize_factor\n\t    \t<<\"</mass>\" <<endl;\n    \t}\n    \telse\n    \t{\n    \t\toutfile <<\t\"\t\t<mass>\"<<4.0<<\"</mass>\"<<endl;\n    \t}\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t<offset>0.0 0 0.0</offset>\" <<endl;   \n                    \n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t</inertia>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t<visualization_shape>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n\n   \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n\n    \tEigen::VectorXd shaftScaled = getShaft(childOffset);\n    \tdouble length = sqrt(pow(childOffset[0],2)+pow(childOffset[1],2)+pow(childOffset[2],2));\n    \tshaftScaled*= length;\n   \t\toutfile << \"\t\t<transformation>\"\n  \t\t<< (shaftScaled[0])/2.0 * resize_factor<<\" \"\n   \t\t<< (shaftScaled[1])/2.0 * resize_factor<<\" \"\n   \t\t<< (shaftScaled[2])/2.0 * resize_factor<<\" \"\n   \t\t<<\" 0 0 0</transformation>\" <<endl;\n\n\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t<geometry>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t\t<box>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \tif(curNode->getName().compare(0, 4, \"Head\")==0)\n    \t{\n    \t\toutfile <<\t\"\t\t\t\t<size>0.3 0.3 0.3</size>\"<<endl;\n    \t}\n    \tif(mBvhType == BVHType::BASKET && curNode->getName().compare(0, 5, \"Spine\")==0)\n    \t{\n    \t\tcurNode->getOffset(curOffset);\n    \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n       \t\toutfile << \"\t\t\t\t<size>\";\n\n\t       \t\toutfile <<sqrt(pow(childOffset[0],2)+pow(childOffset[1],2)+pow(childOffset[2],2)) *resize_factor<<\" \" \n\t       \t\t<<\"0.3 0.3</size>\"<<endl;\n\n\n    \t}\n       \telse if(curNode->getChilds().size()==1)\n       \t{\n       \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n       \t\toutfile << \"\t\t\t\t<size>\";\n\n    \t\tEigen::Vector3d shaft = getShaft(childOffset);\n    \t\tshaft *= sqrt(pow(childOffset[0],2)+pow(childOffset[1],2)+pow(childOffset[2],2));\n\n\n       \t\toutfile <<((shaft[0] != 0)? fabs(shaft[0]) : 5.0 )*resize_factor<<\" \" \n       \t\t<<((shaft[1] != 0)? fabs(shaft[1]) : 5.0 )*resize_factor<<\" \"\n       \t\t<<((shaft[2] != 0)? fabs(shaft[2]) : 5.0 )*resize_factor;\n       \t\toutfile <<\"</size>\" <<endl;\n       \t}\n       \telse\n       \t{\n\n       \t\toutfile << \"\t\t\t\t<size>0.1 0.1 0.1</size>\" <<endl;\n       \t}\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t\t</box>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t</geometry>\" <<endl;\n\n    \toutfile << \"\t\t<color> 1.0 1.0 1.0 </color>\"<<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t</visualization_shape>\" <<endl;\n\n\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t<collision_shape>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n\n   \t\toutfile << \"\t\t<transformation>\"\n  \t\t<< (shaftScaled[0])/2.0 * resize_factor<<\" \"\n   \t\t<< (shaftScaled[1])/2.0 * resize_factor<<\" \"\n   \t\t<< (shaftScaled[2])/2.0 * resize_factor<<\" \"\n   \t\t<<\" 0 0 0</transformation>\" <<endl;\n\n\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t<geometry>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t\t<box>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \tif(curNode->getName().compare(0, 4, \"Head\")==0)\n    \t{\n    \t\toutfile <<\t\"\t\t\t\t<size>0.3 0.3 0.3</size>\"<<endl;\n    \t}\n    \tif(mBvhType == BVHType::BASKET && curNode->getName().compare(0, 5, \"Spine\")==0)\n    \t{\n    \t\tcurNode->getOffset(curOffset);\n    \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n       \t\toutfile << \"\t\t\t\t<size>\";\n\n\t       \t\toutfile <<sqrt(pow(childOffset[0],2)+pow(childOffset[1],2)+pow(childOffset[2],2)) *resize_factor<<\" \" \n\t       \t\t<<\"0.3 0.3</size>\"<<endl;\n\n    \t}\n       \telse if(curNode->getChilds().size()==1)\n       \t{\n       \t\tcurNode->getChilds()[0]->getOffset(childOffset);\n       \t\toutfile << \"\t\t\t\t<size>\";\n\n    \t\tEigen::Vector3d shaft = getShaft(childOffset);\n    \t\tshaft *= sqrt(pow(childOffset[0],2)+pow(childOffset[1],2)+pow(childOffset[2],2));\n\n\n       \t\toutfile <<((shaft[0] != 0)? fabs(shaft[0]) : 5.0 )*resize_factor<<\" \" \n       \t\t<<((shaft[1] != 0)? fabs(shaft[1]) : 5.0 )*resize_factor<<\" \"\n       \t\t<<((shaft[2] != 0)? fabs(shaft[2]) : 5.0 )*resize_factor;\n       \t\toutfile <<\"</size>\" <<endl;\n       \t}\n       \telse\n\t\t{\n       \t\toutfile << \"\t\t\t\t<size>0.1 0.1 0.1</size>\" <<endl;\n       \t}\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t\t</box>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t\t</geometry>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t</collision_shape>\" <<endl;\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"</body>\" <<endl;\n    \tcurNode = curNode->getNextNode();\n    }\n\n    curNode = rootNode;\n    while(curNode != nullptr)\n    {\n    \toutfile << \"\t\t\t\";\n    \tif(curNode->getName() == rootNode->getName())\n    \t\toutfile << \"<joint type=\\\"free\\\" name=\\\"j_\"<< curNode->getName() << \"\\\">\" <<endl;\n    \telse\n    \t\toutfile << \"<joint type=\\\"ball\\\" name=\\\"j_\"<< curNode->getName() << \"\\\">\" <<endl;\n\n\n    \tif(curNode->getName() != rootNode->getName())\n    \t{\n    \t\toutfile << \"\t\t\t\";\n    \t\toutfile << \"\t<transformation>0.0 0.0 0.0 0.0 0.0 0.0</transformation>\" << endl;\n    \t}\n\n    \toutfile << \"\t\t\t\";\n    \tif(curNode->getName() == rootNode->getName())\n    \t\toutfile << \"\t<parent>world</parent>\" <<endl;\n    \telse\n    \t\toutfile << \"\t<parent>\" << curNode->getParent()->getName() << \"</parent>\" <<endl;\t\t\n\n    \toutfile << \"\t\t\t\";\n    \toutfile << \"\t<child>\" << curNode->getName() << \"</child>\" <<endl;\n\n\t\t// if(curNode->getName() != rootNode->getName())\n  //   \t{\n  //   \t\toutfile << \"\t\t\t\";\n  //   \t\toutfile << \"\t<axis_order>\" << \"xyz\" << \"</axis_order>\" << endl;\n  //   \t} \n\n     \toutfile << \"\t\t\t\";\n    \tif(curNode->getName() == rootNode->getName())\n    \t\toutfile << \"\t<init_pos>0 0 0 0 0 0</init_pos>\" <<endl;\n    \telse\n    \t\toutfile << \"\t<init_pos>0 0 0</init_pos>\" <<endl;\n\n     \toutfile << \"\t\t\t\";\n    \tif(curNode->getName() == rootNode->getName())     \t\n\t\t\toutfile << \"\t<init_vel>0 0 0 0 0 0</init_vel>\" <<endl;\n\t\telse\n\t\t\toutfile << \"\t<init_vel>0 0 0</init_vel>\" <<endl;\n\n     \toutfile << \"\t\t\t\";    \t\n\t\toutfile << \"</joint>\" <<endl;\n\t\tcurNode = curNode->getNextNode();\t\t\n    }\n    \n\n    outfile << \"\t\t</skeleton>\" <<endl;\n    // outfile << \"\t</world>\" <<endl;\n    outfile << \"</skel>\" <<endl;\n    outfile.close();\n\n    // if(n == 0)\n    cout<< \"Generating skel file is completed ! : \"<< \"../data/skels/\"+getFileName_(mPath)+\".skel\" <<endl;\n    // else\n    // \tcout<< \"Generating skel file is completed ! : \"<< bvhpath_2_skelpath_(mPath)+\"Mocap.skel\" <<endl;\n\t\n}", "meta": {"hexsha": "bf19fee1772f9b1804c56d55f5b0f87a4e9cbb93", "size": 22033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "motion/BVHparser.cpp", "max_stars_repo_name": "snumrl/VSports", "max_stars_repo_head_hexsha": "c35bc82db31cd7252ab3d0f78c3f941bae5e799b", "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": "motion/BVHparser.cpp", "max_issues_repo_name": "snumrl/VSports", "max_issues_repo_head_hexsha": "c35bc82db31cd7252ab3d0f78c3f941bae5e799b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "motion/BVHparser.cpp", "max_forks_repo_name": "snumrl/VSports", "max_forks_repo_head_hexsha": "c35bc82db31cd7252ab3d0f78c3f941bae5e799b", "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.7066666667, "max_line_length": 154, "alphanum_fraction": 0.5822629692, "num_tokens": 6984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.04023794722734201, "lm_q1q2_score": 0.015936969972965013}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2020 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014-2017 by Centre for Geoscience Computing (GeoComp)\n* Development from 2019 by School of Earth and Environmental Sciences\n**\n*****************************************************************************/\n\n#include \"DataVector.h\"\n\n#include \"DataException.h\"\n#include \"DataTypes.h\"\n#include \"Taipan.h\"\n#include \"WrappedArray.h\"\n\n#include <boost/python/extract.hpp>\n\n#ifdef ESYS_HAVE_BOOST_NUMPY\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#endif\n\nusing namespace std;\nusing namespace escript;\nusing namespace boost::python;\nusing namespace DataTypes;\n\nnamespace {\n\ninline\nvoid cplxout(std::ostream& os, const DataTypes::cplx_t& c)\n{\n    os << c.real();\n    if (c.imag()>=0)\n    {\n        os << '+';\n    }\n    os << c.imag() << 'j';\n}\n\n}\n\n\nnamespace escript {\n\n   void\n   DataTypes::pointToStream(std::ostream& os, const CplxVectorType::ElementType* data,const ShapeType& shape, int offset, bool needsep, const std::string& sep)\n   {\n      using namespace std;\n      ESYS_ASSERT(data!=0, \"Error - data is null\");\n//      ESYS_ASSERT(data.size()>0,\"Error - Data object is empty.\");\n      switch (getRank(shape)) {\n      case 0:\n         if (needsep){\n            os << sep;\n         } else {\n            needsep = true;\n         }\n         cplxout(os,data[offset]);\n         break;\n      case 1:\n         for (int i=0;i<shape[0];i++) {\n            if (needsep) {\n               os << sep;\n            } else {\n               needsep=true;\n            }\n            cplxout(os,data[i+offset]);\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               if (needsep){\n                  os << sep;\n               } else {\n                  needsep=true;\n               }\n               cplxout(os,data[offset+getRelIndex(shape,i,j)]);\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  if (needsep) {\n                     os << sep;\n                  } else { \n                     needsep=true;\n                  }\n                  cplxout(os,data[offset+getRelIndex(shape,i,j,k)]);\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     if (needsep) {\n                        os << sep;\n                     } else {\n                        needsep=true;\n                     }\n                     cplxout(os,data[offset+getRelIndex(shape,i,j,k,l)]);\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (pointToStream) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n   }\n\n\n   void\n   DataTypes::pointToStream(std::ostream& os, const RealVectorType::ElementType* data,const ShapeType& shape, int offset, bool needsep, const std::string& sep)\n   {\n      using namespace std;\n      ESYS_ASSERT(data!=0, \"Error - data is null\");\n//      ESYS_ASSERT(data.size()>0,\"Error - Data object is empty.\");\n      switch (getRank(shape)) {\n      case 0:\n         if (needsep) {\n            os << sep;\n         } else {\n            needsep=true;\n         }\n         os << data[offset];\n         break;\n      case 1:\n         for (int i=0;i<shape[0];i++) {\n            if (needsep) {\n               os << sep;\n            } else {\n               needsep=true;\n            }\n            os << data[i+offset];\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               if (needsep) {\n                  os << sep;\n               } else {\n                  needsep=true;\n               }\n               os << data[offset+getRelIndex(shape,i,j)];\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  if (needsep) {\n                     os << sep;\n                  } else {\n                     needsep=true;\n                  }\n                  os << data[offset+getRelIndex(shape,i,j,k)];\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     if (needsep) {\n                        os << sep;\n                     } else {\n                        needsep=true;\n                     }\n                     os << data[offset+getRelIndex(shape,i,j,k,l)];\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (pointToStream) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n   }\n\n#ifdef ESYS_HAVE_BOOST_NUMPY\n   void\n   DataTypes::pointToNumpyArrayOld(boost::python::numpy::ndarray& dataArray, const RealVectorType::ElementType* data, \n      const ShapeType& shape, long offset, long numsamples, long dpps, long totalNumSamples)\n   {\n      using namespace std;\n      \n      ESYS_ASSERT(data != 0, \"Error - data is null\");\n      ESYS_ASSERT(data.size() > 0,\"Error - Data object is empty.\");\n\n      switch (getRank(shape)) {\n      case 0:\n         dataArray[0] = data[offset];\n         break;\n      case 1:\n         for (int i = 0; i < shape[0]; i++) {\n            dataArray[getRelIndex(shape,i)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i)];\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               dataArray[getRelIndex(shape,i,j)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i,j)];\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  dataArray[getRelIndex(shape,i,j,k)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i,j,k)];\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     dataArray[getRelIndex(shape,i,j,k,l)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i,j,k,l)];\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (pointToStream) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n   }\n\n\n   void\n   DataTypes::pointToNumpyArrayOld(boost::python::numpy::ndarray& dataArray, const CplxVectorType::ElementType* data, \n      const ShapeType& shape, long offset, long numsamples, long dpps, long totalNumSamples)\n   {\n      \n      using namespace std;\n\n      \n      ESYS_ASSERT(data != 0, \"Error - data is null\");\n      ESYS_ASSERT(data.size() > 0,\"Error - Data object is empty.\");\n\n      switch (getRank(shape)) {\n      case 0:\n         dataArray[0] = data[offset];\n         break;\n      case 1:\n         for (int i = 0; i < shape[0]; i++) {\n            dataArray[getRelIndex(shape,i)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i)];\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               dataArray[getRelIndex(shape,i,j)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i,j)];\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  dataArray[getRelIndex(shape,i,j,k)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i,j,k)];\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     dataArray[getRelIndex(shape,i,j,k,l)][numsamples+dpps*totalNumSamples] = data[offset+getRelIndex(shape,i,j,k,l)];\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (pointToStream) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n   }\n\n\n   void\n   DataTypes::pointToNumpyArray(boost::python::numpy::ndarray& dataArray, const RealVectorType::ElementType* data, \n      const ShapeType& shape, int offset, int d, int index)\n   {\n      using namespace std;\n\n      ESYS_ASSERT(data != 0, \"Error - data is null\");\n      ESYS_ASSERT(data.size() > 0,\"Error - Data object is empty.\");\n\n      switch (getRank(shape)) {\n      case 0:\n         dataArray[d] = data[offset];\n         break;\n      case 1:\n         for (int i = 0; i < shape[0]; i++) {\n            dataArray[d + getRelIndex(shape,i)][index] = data[offset+getRelIndex(shape,i)];\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               dataArray[d + getRelIndex(shape,i,j)][index] = data[offset+getRelIndex(shape,i,j)];\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  dataArray[d + getRelIndex(shape,i,j,k)][index] = data[offset+getRelIndex(shape,i,j,k)];\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     dataArray[d + getRelIndex(shape,i,j,k,l)][index] = data[offset+getRelIndex(shape,i,j,k,l)];\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (pointToStream) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n   }\n\n\n   void\n   DataTypes::pointToNumpyArray(boost::python::numpy::ndarray& dataArray, const CplxVectorType::ElementType* data, \n      const ShapeType& shape, int offset, int d, int index)\n   {\n      \n      using namespace std;\n      \n      ESYS_ASSERT(data != 0, \"Error - data is null\");\n      ESYS_ASSERT(data.size() > 0,\"Error - Data object is empty.\");\n\n      switch (getRank(shape)) {\n      case 0:\n         dataArray[d] = data[offset];\n         break;\n      case 1:\n         for (int i = 0; i < shape[0]; i++) {\n            dataArray[d + getRelIndex(shape,i)][index] = data[offset+getRelIndex(shape,i)];\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               dataArray[d + getRelIndex(shape,i,j)][index] = data[offset+getRelIndex(shape,i,j)];\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  dataArray[d + getRelIndex(shape,i,j,k)][index] = data[offset+getRelIndex(shape,i,j,k)];\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     dataArray[d + getRelIndex(shape,i,j,k,l)][index] = data[offset+getRelIndex(shape,i,j,k,l)];\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (pointToStream) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n   }\n#endif\n\n   std::string\n   DataTypes::pointToString(const CplxVectorType& data,const ShapeType& shape, int offset, const std::string& prefix)\n   {\n      using namespace std;\n      ESYS_ASSERT(data.size()>0,\"Error - Data object is empty.\");\n      stringstream temp;\n      string finalPrefix=prefix;\n      if (prefix.length() > 0) {\n         finalPrefix+=\" \";\n      }\n      switch (getRank(shape)) {\n      case 0:\n         temp << finalPrefix;\n         cplxout(temp,data[offset]);\n         break;\n      case 1:\n         for (int i=0;i<shape[0];i++) {\n            temp << finalPrefix << \"(\" << i <<  \") \";\n            cplxout(temp,data[i+offset]);\n            if (i!=(shape[0]-1)) {\n               temp << endl;\n            }\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               temp << finalPrefix << \"(\" << i << \",\" << j << \") \";\n               cplxout(temp,data[offset+getRelIndex(shape,i,j)]);\n               if (!(i==(shape[0]-1) && j==(shape[1]-1))) {\n                  temp << endl;\n               }\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  temp << finalPrefix << \"(\" << i << \",\" << j << \",\" << k << \") \";\n                  cplxout(temp,data[offset+getRelIndex(shape,i,j,k)]);\n                  if (!(i==(shape[0]-1) && j==(shape[1]-1) && k==(shape[2]-1))) {\n                     temp << endl;\n                  }\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     temp << finalPrefix << \"(\" << i << \",\" << j << \",\" << k << \",\" << l << \") \";\n                     cplxout(temp,data[offset+getRelIndex(shape,i,j,k,l)]);\n                     if (!(i==(shape[0]-1) && j==(shape[1]-1) && k==(shape[2]-1) && l==(shape[3]-1))) {\n                        temp << endl;\n                     }\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (toString) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n      return temp.str();\n   }\n\n   std::string\n   DataTypes::pointToString(const RealVectorType& data,const ShapeType& shape, int offset, const std::string& prefix)\n   {\n      using namespace std;\n      ESYS_ASSERT(data.size()>0,\"Error - Data object is empty.\");\n      stringstream temp;\n      string finalPrefix=prefix;\n      if (prefix.length() > 0) {\n         finalPrefix+=\" \";\n      }\n      switch (getRank(shape)) {\n      case 0:\n         temp << finalPrefix << data[offset];\n         break;\n      case 1:\n         for (int i=0;i<shape[0];i++) {\n            temp << finalPrefix << \"(\" << i <<  \") \" << data[i+offset];\n            if (i!=(shape[0]-1)) {\n               temp << endl;\n            }\n         }\n         break;\n      case 2:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               temp << finalPrefix << \"(\" << i << \",\" << j << \") \" << data[offset+getRelIndex(shape,i,j)];\n               if (!(i==(shape[0]-1) && j==(shape[1]-1))) {\n                  temp << endl;\n               }\n            }\n         }\n         break;\n      case 3:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  temp << finalPrefix << \"(\" << i << \",\" << j << \",\" << k << \") \" << data[offset+getRelIndex(shape,i,j,k)];\n                  if (!(i==(shape[0]-1) && j==(shape[1]-1) && k==(shape[2]-1))) {\n                     temp << endl;\n                  }\n               }\n            }\n         }\n         break;\n      case 4:\n         for (int i=0;i<shape[0];i++) {\n            for (int j=0;j<shape[1];j++) {\n               for (int k=0;k<shape[2];k++) {\n                  for (int l=0;l<shape[3];l++) {\n                     temp << finalPrefix << \"(\" << i << \",\" << j << \",\" << k << \",\" << l << \") \" << data[offset+getRelIndex(shape,i,j,k,l)];\n                     if (!(i==(shape[0]-1) && j==(shape[1]-1) && k==(shape[2]-1) && l==(shape[3]-1))) {\n                        temp << endl;\n                     }\n                  }\n               }\n            }\n         }\n         break;\n      default:\n         stringstream mess;\n         mess << \"Error - (toString) Invalid rank: \" << getRank(shape);\n         throw DataException(mess.str());\n      }\n      return temp.str();\n   }\n\n\n   void DataTypes::copyPoint(RealVectorType& dest, RealVectorType::size_type doffset, RealVectorType::size_type nvals, const RealVectorType& src, RealVectorType::size_type soffset)\n   {\n      ESYS_ASSERT((dest.size()>0&&src.size()>0&&checkOffset(doffset,dest.size(),nvals)),\n                 \"Error - Couldn't copy due to insufficient storage.\");\n      if (checkOffset(doffset,dest.size(),nvals) && checkOffset(soffset,src.size(),nvals)) {\n         memcpy(&dest[doffset],&src[soffset],sizeof(real_t)*nvals);\n      } else {\n         throw DataException(\"Error - invalid offset specified.\");\n      }\n   }\n\n   void DataTypes::copyPoint(CplxVectorType& dest, CplxVectorType::size_type doffset, CplxVectorType::size_type nvals, const CplxVectorType& src, CplxVectorType::size_type soffset)\n   {\n      ESYS_ASSERT((dest.size()>0&&src.size()>0&&checkOffset(doffset,dest.size(),nvals)),\n                 \"Error - Couldn't copy due to insufficient storage.\");\n      if (checkOffset(doffset,dest.size(),nvals) && checkOffset(soffset,src.size(),nvals)) {\n         memcpy(&dest[doffset],&src[soffset],sizeof(cplx_t)*nvals);\n      } else {\n         throw DataException(\"Error - invalid offset specified.\");\n      }\n   }\n\n   /**\n    * \\brief copy data from a real vector to a complex vector\n    * The complex vector will be resized as needed and any previous\n    * values will be replaced.\n   */\n   void DataTypes::fillComplexFromReal(const RealVectorType& r, CplxVectorType& c)\n   {\n       if (c.size()!=r.size())\n       {\n\t   c.resize(r.size(), 0, 1);\n       }\n       size_t limit=r.size();\n#ifdef _WIN32 // error C3016: 'i': index variable in OpenMP 'for' statement must have signed integral type\n#define OMP_LOOP_IDX_T int\n#else\n#define OMP_LOOP_IDX_T size_t\n#endif\n       #pragma omp parallel for schedule(static)\n       for (OMP_LOOP_IDX_T i=0;i<limit;++i)\n       {\n\t   c[i]=r[i];\n       }\n   }\n\n} // end of namespace\n\n", "meta": {"hexsha": "a74399f27638a7fcc41870e27276b50db46c7921", "size": 19407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "escriptcore/src/DataVector.cpp", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "escriptcore/src/DataVector.cpp", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "escriptcore/src/DataVector.cpp", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0247524752, "max_line_length": 180, "alphanum_fraction": 0.4633894986, "num_tokens": 5010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.04023793931468827, "lm_q1q2_score": 0.01593696683901475}}
{"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 <cfloat>\n#include <iomanip>\n#include <limits>\n#include <math.h>\n#include <sstream>\n#include <boost/math/distributions/students_t.hpp>\n#include <wx/dc.h>\n#include <wx/msgdlg.h>\n#include <wx/stdpaths.h>\n#include \"GdaConst.h\"\n#include \"GenUtils.h\"\n\nusing namespace std;\n\n\nwxString GdaColorUtils::ToHexColorStr(const wxColour& c)\n{\n\treturn c.GetAsString(wxC2S_HTML_SYNTAX);\n}\n\nwxColour GdaColorUtils::ChangeBrightness(const wxColour& input_col,\n\t\t\t\t\t\t\t\t\t\t int brightness)\n{\n\tunsigned char r = input_col.Red(); \n\tunsigned char g = input_col.Green();\n\tunsigned char b = input_col.Blue();\n\tunsigned char alpha = input_col.Alpha();\n\twxColour::ChangeLightness(&r, &g, &b, brightness);\n\treturn wxColour(r,g,b,alpha);\n}\n\nuint64_t Gda::ThomasWangHashUInt64(uint64_t key) {\n\tkey = (~key) + (key << 21); // key = (key << 21) - key - 1;\n\tkey = key ^ (key >> 24);\n\tkey = (key + (key << 3)) + (key << 8); // key * 265\n\tkey = key ^ (key >> 14);\n\tkey = (key + (key << 2)) + (key << 4); // key * 21\n\tkey = key ^ (key >> 28);\n\tkey = key + (key << 31);\n\treturn key;\n}\n\ndouble Gda::ThomasWangHashDouble(uint64_t key) {\n\tkey = (~key) + (key << 21); // key = (key << 21) - key - 1;\n\tkey = key ^ (key >> 24);\n\tkey = (key + (key << 3)) + (key << 8); // key * 265\n\tkey = key ^ (key >> 14);\n\tkey = (key + (key << 2)) + (key << 4); // key * 21\n\tkey = key ^ (key >> 28);\n\tkey = key + (key << 31);\n\treturn 5.42101086242752217E-20 * key;\n}\n\n/** Use with std::sort for sorting in ascending order */\nbool Gda::dbl_int_pair_cmp_less(const dbl_int_pair_type& ind1,\n\t\t\t\t\t\t\t\t  const dbl_int_pair_type& ind2)\n{\n\treturn ind1.first < ind2.first;\n}\n\n/** Use with std::sort for sorting in descending order */\nbool Gda::dbl_int_pair_cmp_greater(const dbl_int_pair_type& ind1,\n\t\t\t\t\t\t\t\t\t const dbl_int_pair_type& ind2)\n{\n\treturn ind1.first > ind2.first;\n}\n\n/** Use with std::sort for sorting in ascending order */\nbool Gda::dbl_int_pair_cmp_second_less(const dbl_int_pair_type& ind1,\n\t\t\t\t\t\t\t\t\t\t const dbl_int_pair_type& ind2)\n{\n\treturn ind1.second < ind2.second;\n}\n\n/** Use with std::sort for sorting in descending order */\nbool Gda::dbl_int_pair_cmp_second_greater(const dbl_int_pair_type& ind1,\n\t\t\t\t\t\t\t\t\t\t\tconst dbl_int_pair_type& ind2)\n{\n\treturn ind1.second > ind2.second;\n}\n\n\nvoid\nHingeStats::\nCalculateHingeStats(const std::vector<Gda::dbl_int_pair_type>& data)\n{\n\tnum_obs = data.size();\n\tdouble N = num_obs;\n\tis_even_num_obs = (num_obs % 2) == 0;\n\tmin_val = data[0].first;\n\tmax_val = data[num_obs-1].first;\n\tQ2_ind = (N+1)/2.0 - 1;\n\tif (is_even_num_obs) {\n\t\tQ1_ind = (N+2)/4.0 - 1;\n\t\tQ3_ind = (3*N+2)/4.0 - 1;\n\t} else {\n\t\tQ1_ind = (N+3)/4.0 - 1;\n\t\tQ3_ind = (3*N+1)/4.0 - 1;\n\t}\n\tQ1 = (data[(int) floor(Q1_ind)].first +\n\t\t  data[(int) ceil(Q1_ind)].first)/2.0;\n\tQ2 = (data[(int) floor(Q2_ind)].first +\n\t\t  data[(int) ceil(Q2_ind)].first)/2.0;\n\tQ3 = (data[(int) floor(Q3_ind)].first +\n\t\t  data[(int) ceil(Q3_ind)].first)/2.0;\n\tIQR = Q3 - Q1;\n\textreme_lower_val_15 = Q1 - 1.5*IQR;\n\textreme_lower_val_30 = Q1 - 3.0*IQR;\n\textreme_upper_val_15 = Q3 + 1.5*IQR;\n\textreme_upper_val_30 = Q3 + 3.0*IQR;\n\tmin_IQR_ind = -1;\n\tfor (int i=0; i<num_obs; i++) {\n\t\tif (data[i].first < Q1) min_IQR_ind = i;\n\t\telse break;\n\t}\n\tif (min_IQR_ind < num_obs-1) min_IQR_ind++;\n\tmax_IQR_ind = num_obs;\n\tfor (int i=num_obs-1; i>=0; i--) {\n\t\tif (data[i].first > Q3) max_IQR_ind = i;\n\t\telse break;\n\t}\n\tif (max_IQR_ind > 0) max_IQR_ind--;\n}\n\nvoid\nHingeStats::\nCalculateHingeStats(const std::vector<Gda::dbl_int_pair_type>& data,\n                    const std::vector<bool>& data_undef)\n{\n    num_obs = data.size();\n    double N = 0.0;\n    std::vector<double> data_valid;\n    \n    bool has_init = false;\n    for (size_t i =0; i<num_obs; i++) {\n        int obs_idx = data[i].second;\n        if (!data_undef[obs_idx]) {\n            double val = data[i].first;\n            data_valid.push_back(val); // sorted\n            if (!has_init) {\n                min_val = val;\n                max_val = val;\n                has_init = true;\n            }\n            if (val < min_val)\n                min_val = val;\n            if (val > max_val)\n                max_val = val;\n        }\n    }\n    \n    N = data_valid.size();\n    is_even_num_obs = (data_valid.size() % 2) == 0;\n    \n    Q2_ind = (N+1)/2.0 - 1;\n    if (is_even_num_obs) {\n        Q1_ind = (N+2)/4.0 - 1;\n        Q3_ind = (3*N+2)/4.0 - 1;\n    } else {\n        Q1_ind = (N+3)/4.0 - 1;\n        Q3_ind = (3*N+1)/4.0 - 1;\n    }\n    Q1 = (data_valid[(int) floor(Q1_ind)] + data_valid[(int) ceil(Q1_ind)])/2.0;\n    Q2 = (data_valid[(int) floor(Q2_ind)] + data_valid[(int) ceil(Q2_ind)])/2.0;\n    Q3 = (data_valid[(int) floor(Q3_ind)] + data_valid[(int) ceil(Q3_ind)])/2.0;\n    \n    IQR = Q3 - Q1;\n    \n    extreme_lower_val_15 = Q1 - 1.5*IQR;\n    extreme_lower_val_30 = Q1 - 3.0*IQR;\n    extreme_upper_val_15 = Q3 + 1.5*IQR;\n    extreme_upper_val_30 = Q3 + 3.0*IQR;\n    \n    min_IQR_ind = -1;\n    for (int i=0; i<num_obs; i++) {\n        if (data[i].first < Q1) {\n            min_IQR_ind = i;\n        }\n        else\n            break;\n    }\n    if (min_IQR_ind < num_obs-1) {\n        min_IQR_ind++;\n    }\n    max_IQR_ind = num_obs;\n    \n    for (int i=num_obs-1; i>=0; i--) {\n        if (data[i].first > Q3) {\n            max_IQR_ind = i;\n        }\n        else\n            break;\n    }\n    if (max_IQR_ind > 0)\n        max_IQR_ind--;\n}\n\n// Assume input v is sorted.  If not, can sort\n// with std::sort(v.begin(), v.end())\n// Testing: for v = {15, 20, 35, 40, 50},\n// percentile(1, v) = 15, percentile(10, v) = 15, percentile(11) = 15.25\n// percentile(50, v) = 35, percentile(89, v) = 49.5,\n// percentile(90, v) = 50, percentile(99, v) = 50\ndouble Gda::percentile(double x, const std::vector<double>& v)\n{\n\tint N = v.size();\n\tdouble Nd = (double) N;\n\tdouble p_0 = (100.0/Nd) * (1.0-0.5);\n\tdouble p_Nm1 = (100.0/Nd) * (Nd-0.5);\n\tif (x <= p_0) return v[0];\n\tif (x >= p_Nm1) return v[N-1];\n\t\n\tfor (int i=1; i<N; i++) {\n\t\tdouble p_i = (100.0/Nd) * ((((double) i)+1.0)-0.5);\n\t\tif (x == p_i) return v[i];\n\t\tif (x < p_i) {\n\t\t\tdouble p_im1 = (100.0/Nd) * ((((double) i))-0.5);\n\t\t\treturn v[i-1] + Nd*((x-p_im1)/100.0)*(v[i]-v[i-1]);\n\t\t}\n\t}\n\treturn v[N-1]; // execution should never get here\n}\n\n// Same assumptions as above\ndouble Gda::percentile(double x, const Gda::dbl_int_pair_vec_type& v,\n                       const std::vector<bool>& undefs)\n{\n    std::vector<double> valid_data;\n    for (size_t i = 0; i<v.size(); i++ ) {\n        double val = v[i].first;\n        int ind = v[i].second;\n        \n        if (undefs[ind])\n            continue;\n        \n        valid_data.push_back(val);\n    }\n    return percentile(x, valid_data);\n}\n\n// Same assumptions as above\ndouble Gda::percentile(double x, const Gda::dbl_int_pair_vec_type& v)\n{\n\tint N = v.size();\n\tdouble Nd = (double) N;\n\tdouble p_0 = (100.0/Nd) * (1.0-0.5);\n\tdouble p_Nm1 = (100.0/Nd) * (Nd-0.5);\n    \n\tif (x <= p_0)\n        return v[0].first;\n    \n\tif (x >= p_Nm1)\n        return v[N-1].first;\n\t\n\tfor (int i=1; i<N; i++) {\n\t\tdouble p_i = (100.0/Nd) * ((((double) i)+1.0)-0.5);\n\t\tif (x == p_i)\n            return v[i].first;\n\t\tif (x < p_i) {\n\t\t\tdouble p_im1 = (100.0/Nd) * ((((double) i))-0.5);\n\t\t\treturn v[i-1].first + Nd*((x-p_im1)/100.0)*(v[i].first\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t-v[i-1].first);\n\t\t}\n\t}\n\treturn v[N-1].first; // execution should never get here\n}\n\nSampleStatistics::SampleStatistics(const std::vector<double>& data)\n\t: sample_size(0), min(0), max(0), mean(0),\n\tvar_with_bessel(0), var_without_bessel(0),\n\tsd_with_bessel(0), sd_without_bessel(0)\n{\n\tCalculateFromSample(data);\n}\n\nSampleStatistics::SampleStatistics(const std::vector<double>& data,\n                                   const std::vector<bool>& undefs)\n\t: sample_size(0), min(0), max(0), mean(0),\n\tvar_with_bessel(0), var_without_bessel(0),\n\tsd_with_bessel(0), sd_without_bessel(0)\n{\n    std::vector<double> valid_data;\n    for (int i=0; i<data.size(); i++) {\n        if (undefs[i] == false)\n            valid_data.push_back(data[i]);\n    }\n\tCalculateFromSample(valid_data);\n}\n\nSampleStatistics::SampleStatistics(const std::vector<double>& data,\n                                   const std::vector<bool>& undefs1,\n                                   const std::vector<bool>& undefs2)\n\t: sample_size(0), min(0), max(0), mean(0),\n\tvar_with_bessel(0), var_without_bessel(0),\n\tsd_with_bessel(0), sd_without_bessel(0)\n{\n    std::vector<double> valid_data;\n    for (int i=0; i<data.size(); i++) {\n        if (undefs1[i] || undefs2[i])\n            continue;\n        valid_data.push_back(data[i]);\n    }\n\tCalculateFromSample(valid_data);\n}\n\nvoid SampleStatistics::CalculateFromSample(const std::vector<double>& data,\n                                           const std::vector<bool>& undefs)\n{\n    std::vector<double> valid_data;\n    for (int i=0; i<data.size(); i++) {\n        if (undefs[i] == false)\n            valid_data.push_back(data[i]);\n    }\n    CalculateFromSample(valid_data);\n}\nvoid SampleStatistics::CalculateFromSample(const std::vector<double>& data)\n{\n\tsample_size = data.size();\n\tif (sample_size == 0) return;\n\n\tCalcMinMax(data, min, max);\n\tmean = CalcMean(data);\n\t\n\tdouble n = sample_size;\n\tdouble sum_squares = 0;\n\tfor (int i=0, iend = data.size(); i<iend; i++) {\n\t\tsum_squares += data[i] * data[i];\n\t}\n\t\n\tvar_without_bessel = (sum_squares/n) - (mean*mean);\n\tsd_without_bessel = sqrt(var_without_bessel);\n\t\n\tif (sample_size == 1) {\n\t\tvar_with_bessel = var_without_bessel;\n\t\tsd_with_bessel = sd_without_bessel;\n\t} else {\n\t\tvar_with_bessel = (n/(n-1)) * var_without_bessel;\n\t\tsd_with_bessel = sqrt(var_with_bessel);\n\t}\n}\n\n/** We assume that the data has been sorted in ascending order */\nvoid\nSampleStatistics::\nCalculateFromSample(const std::vector<Gda::dbl_int_pair_type>& data_,\n                    const std::vector<bool>& undefs)\n{\n    std::vector<double> data;\n    for (int i=0, iend = data_.size(); i<iend; i++) {\n        int id = data_[i].second;\n        if (!undefs[id]) {\n            data.push_back(data_[i].first);\n        }\n    }\n    \n\tsample_size = data.size();\n\tif (sample_size == 0) return;\n\t\n\tmin = data[0];\n\tmax = data[sample_size-1];\n\tmean = CalcMean(data);\n\t\n\tdouble n = sample_size;\n\tdouble sum_squares = 0;\n\tfor (int i=0, iend = data.size(); i<iend; i++) {\n\t\tsum_squares += data[i] * data[i];\n\t}\n\t\n\tvar_without_bessel = (sum_squares/n) - (mean*mean);\n\tsd_without_bessel = sqrt(var_without_bessel);\n\t\n\tif (sample_size == 1) {\n\t\tvar_with_bessel = var_without_bessel;\n\t\tsd_with_bessel = sd_without_bessel;\n\t} else {\n\t\tvar_with_bessel = (n/(n-1)) * var_without_bessel;\n\t\tsd_with_bessel = sqrt(var_with_bessel);\n\t}\n}\n\nstring SampleStatistics::ToString()\n{\n\tostringstream ss;\n\tss << \"sample_size = \" << sample_size << endl;\n\tss << \"min = \" << min << endl;\n\tss << \"max = \" << max << endl;\n\tss << \"mean = \" << mean << endl;\n\tss << \"var_with_bessel = \" << var_with_bessel << endl;\n\tss << \"var_without_bessel = \" << var_without_bessel << endl;\n\tss << \"sd_with_bessel = \" << sd_with_bessel << endl;\n\tss << \"sd_without_bessel = \" << sd_without_bessel << endl;\n\treturn ss.str();\n}\n\ndouble SampleStatistics::CalcMin(const std::vector<double>& data)\n{\n\tdouble min = std::numeric_limits<double>::max();\n\tfor (int i=0, iend=data.size(); i<iend; i++) {\n\t\tif ( data[i] < min ) min = data[i];\n\t}\n\treturn min;\n}\n\ndouble SampleStatistics::CalcMax(const std::vector<double>& data)\n{\n\tdouble max = -std::numeric_limits<double>::max();\n\tfor (int i=0, iend=data.size(); i<iend; i++) {\n\t\tif ( data[i] > max ) max = data[i];\n\t}\n\treturn max;\n}\n\nvoid SampleStatistics::CalcMinMax(const std::vector<double>& data,\n\t\t\t\t\t\t\t\t  double& min, double& max)\n{\n\tif (data.size() == 0) return;\n\tmin = data[0];\n\tmax = data[0];\n\tfor (int i=1, iend=data.size(); i<iend; i++) {\n\t\tif ( data[i] < min ) {\n\t\t\tmin = data[i];\n\t\t} else if ( data[i] > max ) {\n\t\t\tmax = data[i];\n\t\t}\n\t}\n}\n\n\ndouble SampleStatistics::CalcMean(const std::vector<double>& data)\n{\n\tif (data.size() == 0) return 0;\n\tdouble total = 0;\n\tfor (int i=0, iend=data.size(); i<iend; i++) {\n\t\ttotal += data[i];\n\t}\n\treturn total / (double) data.size();\n}\n\ndouble SampleStatistics::CalcMean(\n\t\t\t\t\t\t\tconst std::vector<Gda::dbl_int_pair_type>& data)\n{\n\tif (data.size() == 0) return 0;\n\tdouble total = 0;\n\tfor (int i=0, iend=data.size(); i<iend; i++) {\n\t\ttotal += data[i].first;\n\t}\n\treturn total / (double) data.size();\n}\n\nSimpleLinearRegression::SimpleLinearRegression(const std::vector<double>& X,\n\t\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\t   double meanX, double meanY,\n\t\t\t\t\t\t\t\t\t\t\t   double varX, double varY)\n\t: n(0), covariance(0), correlation(0), alpha(0), beta(0), r_squared(0),\n\tstd_err_of_estimate(0), std_err_of_beta(0), std_err_of_alpha(0),\n\tt_score_alpha(0), t_score_beta(0), p_value_alpha(0), p_value_beta(0),\n\tvalid(false), valid_correlation(false), valid_std_err(false),\n\terror_sum_squares(0)\n{\n\tCalculateRegression(X, Y, meanX, meanY, varX, varY);\n}\n\nSimpleLinearRegression::SimpleLinearRegression(const std::vector<double>& X,\n\t\t\t\t\t\t\t\t\t\t\t   const std::vector<double>& Y,\n                                               const std::vector<bool>& X_undef,\n                                               const std::vector<bool>& Y_undef,\n\t\t\t\t\t\t\t\t\t\t\t   double meanX, double meanY,\n\t\t\t\t\t\t\t\t\t\t\t   double varX, double varY)\n\t: n(0), covariance(0), correlation(0), alpha(0), beta(0), r_squared(0),\n\tstd_err_of_estimate(0), std_err_of_beta(0), std_err_of_alpha(0),\n\tt_score_alpha(0), t_score_beta(0), p_value_alpha(0), p_value_beta(0),\n\tvalid(false), valid_correlation(false), valid_std_err(false),\n\terror_sum_squares(0)\n{\n    \n    std::vector<double> X_valid;\n    std::vector<double> Y_valid;\n    \n    for (int i=0; i<X.size(); i++) {\n        if (X_undef[i] || Y_undef[i])\n            continue;\n        \n        X_valid.push_back(X[i]);\n        Y_valid.push_back(Y[i]);\n    }\n\tCalculateRegression(X_valid, Y_valid, meanX, meanY, varX, varY);\n}\n\nvoid SimpleLinearRegression::CalculateRegression(const std::vector<double>& X,\n\t\t\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\t\t double meanX, double meanY,\n\t\t\t\t\t\t\t\t\t\t\t\t double varX, double varY)\n{\n    n = X.size();\n\tif (X.size() != Y.size() || X.size() < 2 )\n        return;\n\tdouble expectXY = 0;\n\tfor (int i=0, iend=X.size(); i<iend; i++) {\n\t\texpectXY += X[i]*Y[i];\n\t}\n\texpectXY /= (double) X.size();\n\tcovariance = expectXY - meanX * meanY;\n\tif (varX > 4*DBL_MIN) {\n\t\tbeta = covariance / varX;\n\t\talpha = meanY - beta * meanX;\n\t\tvalid = true;\n\t}\n\tdouble SS_tot = varY*Y.size();\n\terror_sum_squares = 0; // error_sum_squares = SS_err\n\tdouble err=0;\n\tfor (int i=0, iend=Y.size(); i<iend; i++) {\n\t\terr = Y[i] - (alpha + beta * X[i]);\n\t\terror_sum_squares += err * err;\n\t}\n\tif (error_sum_squares < 16*DBL_MIN) {\n\t\tr_squared = 1;\n\t} else {\n\t\tr_squared = 1 - error_sum_squares / SS_tot;\n\t}\n\t\n\tif (Y.size()>2 && varX > 4*DBL_MIN) {\n\t\t// error_sum_squares/(n-k-1), k=1\n\t\tstd_err_of_estimate = error_sum_squares/(Y.size()-2); \n\t\tstd_err_of_estimate = sqrt(std_err_of_estimate);\n\t\tstd_err_of_beta = std_err_of_estimate/sqrt(X.size()*varX);\n\t\tdouble sum_x_squared = 0;\n\t\tfor (int i=0, iend=X.size(); i<iend; i++) {\n\t\t\tsum_x_squared += X[i] * X[i];\n\t\t}\n\t\tstd_err_of_alpha = std_err_of_beta * sqrt(sum_x_squared / X.size());\n\t\t\n\t\tif (std_err_of_alpha >= 16*DBL_MIN) {\n\t\t\tt_score_alpha = alpha / std_err_of_alpha;\n\t\t} else {\n\t\t\tt_score_alpha = 100;\n\t\t}\n\t\tif (std_err_of_beta >= 16*DBL_MIN) {\n\t\t\tt_score_beta = beta\t/ std_err_of_beta;\n\t\t} else {\n\t\t\tt_score_beta = 100;\n\t\t}\n\t\tp_value_alpha = TScoreTo2SidedPValue(t_score_alpha, X.size()-2);\n\t\tp_value_beta = TScoreTo2SidedPValue(t_score_beta, X.size()-2);\n\t\t\n\t\tvalid_std_err = true;\n\t}\n\t\n\tdouble d = sqrt(varX)*sqrt(varY);\n\tif (d > 4*DBL_MIN) {\n\t\tcorrelation = covariance / d;\n\t\tvalid_correlation = true;\n\t}\n}\n\ndouble SimpleLinearRegression::TScoreTo2SidedPValue(double tscore, int df)\n{\n\tusing namespace boost::math;\n\tstudents_t dist(df);\n\t// Cumulative Distribution Function evaluated at tscore\n\tif ( tscore >= 0) {\n\t\treturn 2*(1.0-cdf(dist, tscore));\n\t} else {\n\t\treturn 2*cdf(dist,tscore);\n\t}\n\n}\n\nstring SimpleLinearRegression::ToString()\n{\n\tostringstream ss;\n\tss << \"covariance = \" << covariance << endl;\n\tss << \"correlation = \" << correlation << endl;\n\tss << \"alpha = \" << alpha << endl;\n\tss << \"beta = \" << beta << endl;\n\tss << \"r_squared = \" << r_squared << endl;\n\tss << \"valid = \" << (valid ? \"true\" : \"false\") << endl;\n\tss << \"valid_correlation = \" << (valid_correlation ? \"true\" : \"false\")\n\t\t<< endl;\n\tss << \"error_sum_squares = \" << error_sum_squares << endl;\n\treturn ss.str();\n}\n\nAxisScale::AxisScale(double data_min_s, double data_max_s, int ticks_s, int lbl_precision_s)\n: data_min(0), data_max(0), scale_min(0), scale_max(0),\nscale_range(0), tic_inc(0), p(0), ticks(ticks_s), lbl_precision(lbl_precision_s)\n{\n\tCalculateScale(data_min_s, data_max_s, ticks_s);\n}\n\nAxisScale::AxisScale(const AxisScale& s)\n: data_min(s.data_min), data_max(s.data_max),\n\tscale_min(s.scale_min), scale_max(s.scale_max),\n\tscale_range(s.scale_range), tic_inc(s.tic_inc), p(s.p),\n\ttics(s.tics), tics_str(s.tics_str), tics_str_show(s.tics_str_show),\n\tticks(s.ticks)\n{\n}\n\nAxisScale& AxisScale::operator=(const AxisScale& s)\n{\n\tdata_min = s.data_min;\n\tdata_max = s.data_max;\n\tscale_min = s.scale_min;\n\tscale_max = s.scale_max;\n\tscale_range = s.scale_range;\n\ttic_inc = s.tic_inc;\n\tp = s.p;\n\ttics = s.tics;\n\ttics_str = s.tics_str;\n\ttics_str_show = s.tics_str_show;\n\tticks = s.ticks;\n\treturn *this;\n}\n\nvoid AxisScale::CalculateScale(double data_min_s, double data_max_s,\n\t\t\t\t\t\t\t   const int ticks)\n{\n\tif (data_min_s <= data_max_s) {\n\t\tdata_min = data_min_s;\n\t\tdata_max = data_max_s;\n\t} else {\n\t\tdata_min = data_max_s;\n\t\tdata_max = data_min_s;\t\n\t}\n\t\n\tdouble data_range = data_max - data_min;\n\tif ( data_range <= 2*DBL_MIN ) {\n\t\tscale_max = ceil((data_max + 0.05)*10)/10;\n\t\tscale_min = floor((data_min - 0.05)*10)/10;\n\t\tscale_range = scale_max - scale_min;\n\t\tp = 1;\n\t\ttic_inc = scale_range/2;\n\t\ttics.resize(3);\n\t\ttics_str.resize(3);\n\t\ttics[0] = scale_min;\n\t\ttics[1] = scale_min + tic_inc;\n\t\ttics[2] = scale_max;\n\t} else {\n\t\tp = floor(log10(data_range))-1;\n\t\tscale_max = ceil(data_max / pow((double)10,p)) * pow((double)10,p);\n\t\tscale_min = floor(data_min / pow((double)10,p)) * pow((double)10,p);\n\t\tscale_range = scale_max - scale_min;\n\t\ttic_inc = floor((scale_range / pow((double)10,p))/ticks)\n\t\t\t* pow((double)10,p);\n\t\tif (scale_min + tic_inc*(ticks+1) <= scale_max + 2*DBL_MIN) {\n\t\t\ttics.resize(ticks+2);\n\t\t\ttics_str.resize(ticks+2);\n\t\t} else {\n\t\t\ttics.resize(ticks+1);\n\t\t\ttics_str.resize(ticks+1);\n\t\t}\n\t\tfor (int i=0, iend=tics.size(); i<iend; i++) {\n\t\t\ttics[i] = scale_min + i*tic_inc;\n\t\t}\n\t}\n\ttics_str_show.resize(tics_str.size());\n\tfor (int i=0, iend=tics.size(); i<iend; i++) {\n        tics_str[i] = GenUtils::DblToStr(tics[i], lbl_precision);\n\t\ttics_str_show[i] = true;\n\t}\n}\n\n/** only display every other tic value */\nvoid AxisScale::SkipEvenTics()\n{\n\tfor (int i=0; i<tics_str_show.size(); i++) tics_str_show[i] = (i%2 == 0);\n}\n\nvoid AxisScale::ShowAllTics()\n{\n\tfor (int i=0; i<tics_str_show.size(); i++) tics_str_show[i] = true;\n}\n\nstring AxisScale::ToString()\n{\n\tostringstream ss;\n\tss << \"data_min = \" << data_min << endl;\n\tss << \"data_max = \" << data_max << endl;\n\tss << \"scale_min = \" << scale_min << endl;\n\tss << \"scale_max = \" << scale_max << endl;\n\tss << \"scale_range = \" << scale_range << endl;\n\tss << \"p = \" << p << endl;\n\tss << \"tic_inc = \" << tic_inc << endl;\n\tfor (int i=0, iend=tics.size(); i<iend; i++) {\n\t\tss << \"tics[\" << i << \"] = \" << tics[i];\n\t\tss << \",  tics_str[\" << i << \"] = \" << tics_str[i] << endl;\n\t}\n\tss << \"Exiting AxisScale::CalculateScale\" << endl;\n\treturn ss.str();\n}\n\nwxString GenUtils::BoolToStr(bool b)\n{\n\treturn b ? \"true\" : \"false\";\n}\n\nbool GenUtils::StrToBool(const wxString& s)\n{\n\tif (s.CmpNoCase(\"1\") == 0) return true;\n\tif (s.CmpNoCase(\"true\") == 0) return true;\n\treturn false;\n}\n\n/** If input string has length < width, then prepends (or appends\n if pad_left=false) string with spaces so that total length is now width.\n If string length >= width, then returns original input string. */\nwxString GenUtils::Pad(const wxString& s, int width, bool pad_left)\n{\n\tif (s.length() >= width) return s;\n\tint pad_len = width - s.length();\n\twxString output;\n\tif (!pad_left) output << s;\n\tfor (int i=0; i<pad_len; i++) output << \" \";\n\tif (pad_left) output << s;\n\treturn output;\n}\n\nwxString GenUtils::PadTrim(const wxString& s, int width, bool pad_left)\n{\n    if (s.length() > width) {\n        int trim_w = width - 2; //\"xxx..xxx\"\n        int second_w = trim_w / 2;\n        int first_w = trim_w - second_w;\n        wxString tmp = s.SubString(0, first_w-2);\n        tmp << \"..\" << s.SubString(s.length() - second_w -1, s.length()-1);\n        return tmp;\n    }\n    int pad_len = width - s.length();\n    wxString output;\n    if (!pad_left) output << s;\n    for (int i=0; i<pad_len; i++) output << \" \";\n    if (pad_left) output << s;\n    return output;\n}\n\nwxString GenUtils::DblToStr(double x, int precision)\n{\n\tstd::stringstream ss;\n    if (x < 10000000) {\n        ss << std::fixed;\n    }\n\tss << std::setprecision(precision);\n\tss << x;\n\treturn wxString(ss.str().c_str(), wxConvUTF8);\n}\n\nwxString GenUtils::PtToStr(const wxPoint& p)\n{\n\tstd::stringstream ss;\n\tss << \"(\" << p.x << \",\" << p.y << \")\";\n\treturn wxString(ss.str().c_str(), wxConvUTF8);\n}\n\nwxString GenUtils::PtToStr(const wxRealPoint& p)\n{\n\tstd::stringstream ss;\n\tss << std::setprecision(5);\n\tss << \"(\" << p.x << \",\" << p.y << \")\";\n\treturn wxString(ss.str().c_str(), wxConvUTF8);\n}\n\n// NOTE: should take into account undefined values.\nvoid GenUtils::DeviationFromMean(int nObs, double* data)\n{\n\tif (nObs == 0) return;\n\tdouble sum = 0.0;\n\tfor (int i=0, iend=nObs; i<iend; i++) sum += data[i];\n\tconst double mean = sum / (double) nObs;\n\tfor (int i=0, iend=nObs; i<iend; i++) data[i] -= mean;\n}\n\nvoid GenUtils::DeviationFromMean(int nObs, double* data, std::vector<bool>& undef)\n{\n\tif (nObs == 0) return;\n    \n    int nValid = 0;\n\tdouble sum = 0.0;\n    for (int i=0, iend=nObs; i<iend; i++) {\n        if (undef[i])\n            continue;\n        sum += data[i];\n        nValid += 1;\n    }\n\tconst double mean = sum / (double) nValid;\n    for (int i=0, iend=nObs; i<iend; i++) {\n        data[i] -= mean;\n    }\n}\n\nvoid GenUtils::DeviationFromMean(std::vector<double>& data)\n{\n\tif (data.size() == 0) return;\n\tdouble sum = 0.0;\n\tfor (int i=0, iend=data.size(); i<iend; i++) sum += data[i];\n\tconst double mean = sum / (double) data.size();\n\tfor (int i=0, iend=data.size(); i<iend; i++) data[i] -= mean;\n}\n\nbool GenUtils::StandardizeData(int nObs, double* data)\n{\n\tif (nObs <= 1) return false;\n\tGenUtils::DeviationFromMean(nObs, data);\n\tdouble ssum = 0.0;\n\tfor (int i=0, iend=nObs; i<iend; i++) ssum += data[i] * data[i];\n\tconst double sd = sqrt(ssum / (double) (nObs-1.0));\n\tif (sd == 0) return false;\n\tfor (int i=0, iend=nObs; i<iend; i++) data[i] /= sd;\n\treturn true;\n}\n\nbool GenUtils::StandardizeData(int nObs, double* data, std::vector<bool>& undef)\n{\n\tif (nObs <= 1) return false;\n    \n    int nValid = 0;\n    for (int i=0; i<undef.size(); i++) {\n        if (!undef[i])\n            nValid += 1;\n    }\n    \n\tGenUtils::DeviationFromMean(nObs, data, undef);\n\tdouble ssum = 0.0;\n    for (int i=0, iend=nObs; i<iend; i++) {\n        if (undef[i])\n            continue;\n        ssum += data[i] * data[i];\n    }\n\tconst double sd = sqrt(ssum / (double) (nValid-1.0));\n\tif (sd == 0)\n        return false;\n    for (int i=0, iend=nObs; i<iend; i++) {\n        data[i] /= sd;\n    }\n\treturn true;\n}\n\nbool GenUtils::StandardizeData(std::vector<double>& data)\n{\n\tif (data.size() <= 1) return false;\n\tGenUtils::DeviationFromMean(data);\n\tdouble ssum = 0.0;\n\tfor (int i=0, iend=data.size(); i<iend; i++) ssum += data[i] * data[i];\n\tconst double sd = sqrt(ssum / (double) (data.size()-1.0));\n\tif (sd == 0) return false;\n\tfor (int i=0, iend=data.size(); i<iend; i++) data[i] /= sd;\n\treturn true;\n}\n\nwxString GenUtils::swapExtension(const wxString& fname, const wxString& ext)\n{\n\tif (ext.IsEmpty()) return fname;\n\twxString prefix = fname.BeforeLast('.');\n\tif (prefix.IsEmpty()) return fname + \".\" + ext;\n\treturn prefix + \".\" + ext;\n}\n\nwxString GenUtils::GetFileDirectory(const wxString& path)\n{\n\tint pos = path.Find('/',true);\n\tif (pos >= 0)\n\t\treturn path.Left(pos) + '/';\n\tpos = path.Find('\\\\',true);\n\tif (pos >= 0)\n\t\treturn path.Left(pos) + '\\\\';\n\treturn wxEmptyString;\n}\n\nwxString GenUtils::GetFileName(const wxString& path)\n{\n\tint pos = path.Find('/',true);\n\tif (pos >= 0)\n\t\treturn path.Right(path.length() - pos - 1);\n\tpos = path.Find('\\\\',true);\n\tif (pos >= 0)\n\t\treturn path.Right(path.length() - pos - 1);\n\treturn wxEmptyString;\n}\n\nwxString GenUtils::GetFileNameNoExt(const wxString& path)\n{\n    wxString fname = GetFileName(path);\n    int pos = fname.Find('.');\n    if (pos >=0)\n        return fname.SubString(0, pos-1);\n    return fname;\n}\n\nwxString GenUtils::GetFileExt(const wxString& path)\n{\n\tint pos = path.Find('.',true);\n\tif (pos >= 0)\n\t\treturn path.Right(path.length() - pos - 1);\n\treturn wxEmptyString;\n}\n\nwxString GenUtils::RestorePath(const wxString& proj_path, const wxString& path)\n{\n\twxFileName path_fn(path);\n\tif (path_fn.IsAbsolute()) return path;\n\tif (!path_fn.IsOk()) return path;\n\twxFileName wd;\n\twxFileName prj_path_fn(proj_path);\n\tif (prj_path_fn.GetExt().IsEmpty()) {\n\t\twd.AssignDir(proj_path);\n\t} else {\n\t\twd.AssignDir(prj_path_fn.GetPath());\n\t}\n\tif (!wd.IsOk() || !wd.IsDir() || !wd.IsAbsolute()) return path;\n\tif (path_fn.MakeAbsolute(wd.GetPath())) {\n\t\tif (path_fn.GetExt().IsEmpty()) {\n\t\t\treturn path_fn.GetPath();\n\t\t}\n\t\treturn path_fn.GetFullPath();\n\t}\n\treturn path;\n}\n\nwxString GenUtils::SimplifyPath(const wxString& proj_path, const wxString& path)\n{\n\twxFileName wd;\n        wxFileName proj_path_fn(proj_path); \n\tif (proj_path_fn.GetExt().IsEmpty()) {\n\t\twd.AssignDir(proj_path);\n\t} else {\n\t\twd.AssignDir(proj_path_fn.GetPath());\n\t}\n\treturn GenUtils::SimplifyPath(wd, path);\n}\n\nwxString GenUtils::SimplifyPath(const wxFileName& wd, const wxString& path)\n{\n    wxFileName path_fn(path);\n\tif (!wd.IsOk() || !wd.IsDir() || !wd.IsAbsolute() ||\n\t\tpath_fn.IsRelative()) return path;\n\twxFileName p;\n\tif (wxDirExists(path)) {\n\t\tp.AssignDir(path);\n\t} else {\n\t\tp.Assign(path);\n\t}\n\tif (p.GetVolume() != wd.GetVolume()) return path;\n\twxArrayString p_dirs = p.GetDirs();\n\twxArrayString wd_dirs = wd.GetDirs();\n\tif (p_dirs.size() < wd_dirs.size()) return path;\n\tfor (int i=0, sz=wd_dirs.size(); i<sz; ++i) {\n\t\tif (p_dirs[i] != wd_dirs[i]) return path;\n\t}\n\tif (p.MakeRelativeTo(wd.GetPath())) {\n\t\tif (p.IsDir()) {\n\t\t\treturn p.GetPath();\n\t\t}\n\t\treturn p.GetFullPath();\n\t}\n\treturn path;\n}\n\nvoid GenUtils::SplitLongPath(const wxString& path,\n\t\t\t\t\t\t\t std::vector<wxString>& parts,\n\t\t\t\t\t\t\t wxString& html_formatted,\n\t\t\t\t\t\t\t int max_chars_per_part)\n{\n\tif (max_chars_per_part < 15) max_chars_per_part = 15;\n\tparts.clear();\n\thtml_formatted = \"\";\n\tif (path.size() <= max_chars_per_part) {\n\t\tparts.push_back(path);\n\t\thtml_formatted = path;\n\t\treturn;\n\t}\n\twxFileName fn(path);\n\twxArrayString dirs(fn.GetDirs());\n\tif (dirs.size() <= 1) {\n\t\tparts.push_back(path);\n\t\thtml_formatted = path;\n\t\treturn;\n\t}\n\twxString sep = wxFileName::GetPathSeparator();\n\t// Note: always add sep char after dir added\n\tif (path.SubString(0,0) == sep) {\n\t\tparts.push_back(sep);\n\t} else if (fn.HasVolume()) {\n\t\t// We'll assume this is a Windows system since only other\n\t\t// supported are OSX and Linux and HasVolume should always\n\t\t// be false for these.\n\t\tparts.push_back(fn.GetVolume());\n\t\tparts[0] << wxFileName::GetVolumeSeparator(wxPATH_WIN);\n\t\tparts[0] << wxFileName::GetPathSeparator(wxPATH_WIN);\n\t} else {\n\t\tparts.push_back(\"\");\n\t}\n\tsize_t cp = 0; // current part\n\tfor (size_t i=0; i<dirs.size(); ++i) {\n\t\tif (parts[cp].size() > max_chars_per_part) {\n\t\t\t++cp;\n\t\t\tparts.push_back(\"\");\n\t\t}\n\t\tif ((parts[cp].size() + dirs[i].size() > max_chars_per_part) &&\n\t\t\t(parts[cp].size() > 0)) {\n\t\t\t++cp;\n\t\t\tparts.push_back(\"\");\n\t\t}\n\t\tparts[cp] << dirs[i] << sep;\n\t}\n\tif (fn.HasName()) {\n\t\twxString name = fn.GetName();\n\t\tname << \".\" << fn.GetExt();\n\t\tif ((parts[cp].size() + name.size() > max_chars_per_part) &&\n\t\t\t(parts[cp].size() > 0)) {\n\t\t\t++cp;\n\t\t\tparts.push_back(\"\");\n\t\t}\n\t\tparts[cp] << name;\n\t}\n\tfor (size_t i=0, last_part=parts.size()-1; i<=last_part; ++i) {\n\t\thtml_formatted << parts[i];\n\t\tif (i < last_part) html_formatted << \"<br />&nbsp;&nbsp;&nbsp;&nbsp;\";\n\t}\n}\n\n/*\n Reverse\n Changes the order of bytes in the presentation of a 4 byte number.\n  */\nwxInt32 GenUtils::Reverse(const wxInt32 &val)\n{\n\tunion {\n\t\twxInt32 v;\n\t\tchar d[4];\n\t} chameleon;\n\tchameleon.v= val;\n\tchar tmp = chameleon.d[0];\n\tchameleon.d[0] = chameleon.d[3];\n\tchameleon.d[3] = tmp;\n\ttmp = chameleon.d[1];\n\tchameleon.d[1] = chameleon.d[2];\n\tchameleon.d[2] = tmp;\n\treturn chameleon.v;\n}\n\nlong GenUtils::ReverseInt(const int &val)\n{\n\tunion {\n\t\tint v;\n\t\tchar d[4];\n\t} chameleon;\n\tchameleon.v= val;\n\tchar tmp = chameleon.d[0];\n\tchameleon.d[0] = chameleon.d[3];\n\tchameleon.d[3] = tmp;\n\ttmp = chameleon.d[1];\n\tchameleon.d[1] = chameleon.d[2];\n\tchameleon.d[2] = tmp;\n\treturn chameleon.v;\n}\n\nvoid GenUtils::SkipTillNumber(std::istream &s)\n{\n\tchar ch;\n\twhile (s >> ch) {\n\t\tif ((ch >= '0' && ch <= '9') || ch == '-' || ch == '+' || ch == '.')\n\t\t\tbreak;\n\t}\n\tif (s.good()) s.putback(ch);\n}\n\n// This is an implementation of ltoa\nvoid GenUtils::longToString(const long d, char* Id, const int base) \n{\n\tint i = 0;\n\tlong j = d;\n\tchar rId[ GdaConst::ShpObjIdLen ];\n\tif (d == 0) {\n\t\tId[0] = '0';\n\t\tId[1] = '\\0';\n\t\treturn;\n\t}\n\tif (d < 0) j = -d;\n\twhile (j != 0) {\n\t\trId[i] = (j % base) + '0';\n\t\tj = j / base;\n\t\ti++;\n\t}\n\tj = i;\n\tif (d < 0) {\n\t\tId[0] = '-';\n\t\tId[i + 1] = '\\0';\n\t\twhile (i > 0) {\n\t\t\tId[i] = rId[j - i];\n\t\t\ti--;\n\t\t}\n\t\treturn;\n\t}\n\t\n\tId[i] = '\\0';\n\twhile (i > 0) {\n\t\tId[i - 1] = rId[j - i];\n\t\ti--;\n\t}\n\treturn;\n}\n\n// Calculates Euclidean distance\ndouble GenUtils::distance(const wxRealPoint& p1, const wxRealPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn sqrt(dx*dx + dy*dy);\n}\n\ndouble GenUtils::distance(const wxRealPoint& p1, const wxPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn sqrt(dx*dx + dy*dy);\n}\n\ndouble GenUtils::distance(const wxPoint& p1, const wxRealPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn sqrt(dx*dx + dy*dy);\n}\n\ndouble GenUtils::distance(const wxPoint& p1, const wxPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn sqrt(dx*dx + dy*dy);\n}\n\n// Calculates Euclidean distance\ndouble GenUtils::distance_sqrd(const wxRealPoint& p1, const wxRealPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn dx*dx + dy*dy;\n}\n\ndouble GenUtils::distance_sqrd(const wxRealPoint& p1, const wxPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn dx*dx + dy*dy;\n}\n\ndouble GenUtils::distance_sqrd(const wxPoint& p1, const wxRealPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn dx*dx + dy*dy;\n}\n\ndouble GenUtils::distance_sqrd(const wxPoint& p1, const wxPoint& p2)\n{\n\tdouble dx = p1.x - p2.x;\n\tdouble dy = p1.y - p2.y;\n\treturn dx*dx + dy*dy;\n}\n\n// calculates distance from point p0 to an infinite line passing through\n// points p1 and p2\ndouble GenUtils::pointToLineDist(const wxPoint& p0, const wxPoint& p1,\n\t\t\t\t\t\t\t\t const wxPoint& p2)\n{\n\tdouble d_p1p2 = distance(p1, p2);\n\tif (d_p1p2 <= 16*DBL_MIN) return distance(p0, p1);\n\treturn abs((p2.x-p1.x)*(p1.y-p0.y)-(p1.x-p0.x)*(p2.y-p1.y))/d_p1p2;\n}\n\nvoid GenUtils::strToInt64(const wxString& str, wxInt64 *val)\n{\n\tchar buf[1024];\n\tstrcpy( buf, (const char*)str.mb_str(wxConvUTF8) );\n\tstrToInt64(buf, val);\n}\n\n// Convert an ASCII string into a wxInt64 (or long long)\nvoid GenUtils::strToInt64(const char *str, wxInt64 *val)\n{\n\twxInt64 total = 0;\n\tbool minus = 0;\n \n\twhile (isspace(*str)) str++;\n\tif (*str == '+') {\n\t\tstr++;\n\t} else if (*str == '-') {\n\t\tminus = true;\n\t\tstr++;\n\t}\n\twhile (isdigit(*str)) {\n\t\ttotal *= 10;\n\t\ttotal += (*str++ - '0');\n\t}\n\t*val = minus ? -total : total;\n}\n\nbool GenUtils::validInt(const wxString& str)\n{\n\tchar buf[1024];\n\tstrcpy( buf, (const char*)str.mb_str(wxConvUTF8) );\n\treturn validInt(buf);\n}\n\n// Checks that an ASCII string can be parsed to a valid integer.  At least\n// one digit must been found.\nbool GenUtils::validInt(const char* str)\n{\n\t//LOG_MSG(wxString::Format(\"GenUtils::validInt(\\\"%s\\\"):\", str));\n\twhile (isspace(*str)) str++;\n\tif (*str == '+' || *str == '-') str++;\n\tconst char* t = str;\n\twhile (isdigit(*str)) str++;\n\tif (t == str) {\n\t\t// no digit found so return false\n\t\t//LOG_MSG(\"   no digit found\");\n\t\treturn false;\n\t}\n\twhile (isspace(*str)) str++;\n\t// only return true if we are finally pointing at\n\t// the null terminating character.\n\t//LOG_MSG(wxString::Format(\"   final char is null: %d\", *str == '\\0'));\n\treturn *str == '\\0';\n}\n\nbool GenUtils::isEmptyOrSpaces(const wxString& str)\n{\n\tchar buf[1024];\n\tstrcpy( buf, (const char*)str.mb_str(wxConvUTF8) );\n\treturn isEmptyOrSpaces(buf);\n}\n\n// returns true if the string is either empty\n// or has only space characters\nbool GenUtils::isEmptyOrSpaces(const char *str)\n{\n\twhile (isspace(*str)) str++;\n\t// if the first not-space char is not the end of the string,\n\t// return false.\n\treturn *str == '\\0';\n}\n\nbool GenUtils::ExistsShpShxDbf(const wxFileName& fname, bool* shp_found,\n\t\t\t\t\t\t\t   bool* shx_found, bool* dbf_found)\n{\n\twxFileName shp(fname);\n\tshp.SetExt(\"shp\");\n\twxFileName shx(fname);\n\tshx.SetExt(\"shx\");\n\twxFileName dbf(fname);\n\tdbf.SetExt(\"dbf\");\n\tif (shp_found) *shp_found = shp.FileExists();\n\tif (shx_found) *shx_found = shx.FileExists();\n\tif (dbf_found) *dbf_found = dbf.FileExists();\n\treturn shp.FileExists() && shx.FileExists() && dbf.FileExists();\n}\n\nwxString GenUtils::FindLongestSubString(const std::vector<wxString> strings,\n\t\t\t\t\t\t\t\t\t\tbool cs)\n{\n\tusing namespace std;\n\tint n=strings.size();\n\tif (n == 0) return \"\";\n\tvector<wxString> strs(strings);\n\tif (!cs) for (int i=0; i<n; i++) strs[i].MakeLower();\n\twxString ref_str = strs[0];\n\tfor (int i=0; i<n; ++i) {\n\t\tif (strs[i].length() < ref_str.length()) ref_str = strs[i];\n\t}\n\tint len = ref_str.length();\n\tif (len == 0) return \"\";\n\t// iterate over all possible substrings in ref_str starting from first\n\t// position in ref_str, and starting with full ref_str.  Reduce length\n\t// of substring to search each iteration.\n\tfor (int cur_len=len; cur_len > 0; --cur_len) {\n\t\tfor (int cur_pos=0; cur_pos <= len-cur_len; ++cur_pos) {\n\t\t\twxString ss = ref_str.substr(cur_pos, cur_len);\n\t\t\tbool all_match = true; // substring found everywhere currently\n\t\t\tfor (int i=0; i<n && all_match; i++) {\n\t\t\t\tif (strs[i].find(ss) == wxString::npos) all_match = false;\n\t\t\t}\n\t\t\tif (all_match) {\n\t\t\t\t// common substring found.  Return unmodified (case-preserved)\n\t\t\t\t// substring from first string\n\t\t\t\treturn strings[0].substr(strs[0].find(ss), cur_len);\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"; // no substring match, return empty string.\n}\n\n\nbool GenUtils::less_vectors(const std::vector<int>& a,const std::vector<int>& b) {\n    return a.size() > b.size();\n}\n\nwxString GenUtils::WrapText(wxWindow *win, const wxString& text, int widthMax)\n{\n\tclass HardBreakWrapper : public wxTextWrapper\n\t{\n\t\tpublic:\n\t\tHardBreakWrapper(wxWindow *win, const wxString& text, int widthMax) {\n\t\t\tWrap(win, text, widthMax);\n\t\t}\n\t\twxString const& GetWrapped() const { return m_wrapped; }\n\t\tprotected:\n\t\tvirtual void OnOutputLine(const wxString& line) {\n\t\t\tm_wrapped += line;\n\t\t}\n\t\tvirtual void OnNewLine() {\n\t\t\tm_wrapped += '\\n';\n\t\t}\n\t\tprivate:\n\t\twxString m_wrapped;\n\t};\n\tHardBreakWrapper wrapper(win, text, widthMax);\n\treturn wrapper.GetWrapped();\n}\n\nwxString GenUtils::GetBasemapCacheDir()\n{\n\twxString exePath = wxStandardPaths::Get().GetExecutablePath();\n\twxFileName exeFile(exePath);\n\twxString exeDir = exeFile.GetPathWithSep();\n\treturn exeDir;\n}\n\nwxString GenUtils::GetWebPluginsDir()\n{\n\twxString exePath = wxStandardPaths::Get().GetExecutablePath();\n\twxFileName exeFile(exePath);\n\twxString exeDir = exeFile.GetPathWithSep();\n    exeDir << \"web_plugins\" << wxFileName::GetPathSeparator();\n    \n\treturn exeDir;\n}\n\nwxString GenUtils::GetResourceDir()\n{\n\twxString exePath = wxStandardPaths::Get().GetExecutablePath();\n\twxFileName exeFile(exePath);\n\twxString exeDir = exeFile.GetPathWithSep();\n    exeDir << \"../Resources\" << wxFileName::GetPathSeparator();\n    \n\treturn exeDir;\n}\n\nwxString GenUtils::GetSamplesDir()\n{\n#ifdef __WXOSX__\n    return GetResourceDir();\n#else\n    return GetWebPluginsDir();\n#endif\n}\n", "meta": {"hexsha": "3b5175581a965eb0792617a65f40bb88521f05a4", "size": 37021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GenUtils.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": "GenUtils.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": "GenUtils.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": 26.9439592431, "max_line_length": 92, "alphanum_fraction": 0.622376489, "num_tokens": 11553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618332444286, "lm_q2_score": 0.035144847790350965, "lm_q1q2_score": 0.015929818138550884}}
{"text": "//  Copyright (c) 2019 AUTHORS\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"octotiger/defs.hpp\"\n#include \"octotiger/grid.hpp\"\n#include \"octotiger/options.hpp\"\n#include \"octotiger/physcon.hpp\"\n#include \"octotiger/real.hpp\"\n#include \"octotiger/common_kernel/interaction_constants.hpp\"\n\n#include <boost/program_options.hpp>\n\n#include <cmath>\n#include <iosfwd>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#define IN_OPTIONS_CPP\n\nconstexpr real mass_solar = 1.2969;\nconstexpr real number_solar = 1.0994;\nconstexpr real X_solar = 0.7068;\nconstexpr real Z_solar = 0.0181;\n\noptions& opts() {\n\tstatic options opts_;\n\treturn opts_;\n}\n\ninline std::string to_string(const std::string &str) {\n\treturn str;\n}\n\ninline std::string to_string(const real &num) {\n\tstd::ostringstream strm;\n\tstrm << std::scientific << num;\n\treturn strm.str();\n}\n\ninline std::string to_string(const integer &num) {\n\treturn std::to_string(num);\n}\n\ninline std::string to_string(const size_t &num) {\n\treturn std::to_string(num);\n}\n\ninline std::string to_string(const bool &b) {\n\treturn b ? \"T\" : \"F\";\n}\n\nbool options::process_options(int argc, char *argv[]) {\n\tnamespace po = boost::program_options;\n\tcode_to_s = code_to_g = code_to_cm = 1.0;\n\n\tpo::options_description command_opts(\"options\");\n\n\tcommand_opts.add_options() //\n\t(\"help\", \"produce help message\")(\"xscale\", po::value<real>(&(opts().xscale))->default_value(1.0), \"grid scale\")           //\n\t(\"dt_max\", po::value<real>(&(opts().dt_max))->default_value(0.333333), \"max allowed pct change for positive fields in a timestep\")           //\n\t(\"cfl\", po::value<real>(&(opts().cfl))->default_value(0.4), \"cfl factor\")           //\n\t(\"omega\", po::value<real>(&(opts().omega))->default_value(0.0), \"(initial) angular frequency\")                          //\n\t(\"v1309\", po::value<bool>(&(opts().v1309))->default_value(false), \"V1309 subproblem of DWD\")                   //\n\t(\"idle_rates\", po::value<bool>(&(opts().idle_rates))->default_value(true), \"show idle rates and locality info in SILO\")                 //\n\t(\"eblast0\", po::value<real>(&(opts().eblast0))->default_value(1.0), \"energy for blast wave\")     //\n\t(\"rho_floor\", po::value<real>(&(opts().rho_floor))->default_value(0.0), \"density floor\")     //\n\t(\"tau_floor\", po::value<real>(&(opts().tau_floor))->default_value(0.0), \"entropy tracer floor\")     //\n\t(\"sod_rhol\", po::value<real>(&(opts().sod_rhol))->default_value(1.0), \"density in the left part of the grid\")     //\n\t(\"sod_rhor\", po::value<real>(&(opts().sod_rhor))->default_value(0.125), \"density in the right part of the grid\")     //\n\t(\"sod_pl\", po::value<real>(&(opts().sod_pl))->default_value(1.0), \"pressure in the left part of the grid\")     //\n\t(\"sod_pr\", po::value<real>(&(opts().sod_pr))->default_value(0.1), \"pressure in the right part of the grid\")     //\n\t(\"sod_theta\", po::value<real>(&(opts().sod_theta))->default_value(0.0), \"angle made by diaphragm normal w/x-axis (deg)\")     //\n\t(\"sod_phi\", po::value<real>(&(opts().sod_phi))->default_value(90.0), \"angle made by diaphragm normal w/z-axis (deg)\")     //\n\t(\"sod_gamma\", po::value<real>(&(opts().sod_gamma))->default_value(1.4), \"ratio of specific heats for gas\")     //\n        (\"solid_sphere_xcenter\", po::value<real>(&(opts().solid_sphere_xcenter))->default_value(0.25), \"x-position of the sphere center\")     //\n        (\"solid_sphere_ycenter\", po::value<real>(&(opts().solid_sphere_ycenter))->default_value(0.0), \"y-position of the sphere center\")     //\n        (\"solid_sphere_zcenter\", po::value<real>(&(opts().solid_sphere_zcenter))->default_value(0.0), \"z-position of the sphere center\")     //\n        (\"solid_sphere_radius\", po::value<real>(&(opts().solid_sphere_radius))->default_value(1.0 / 3.0), \"radius of the sphere\")     //\n        (\"solid_sphere_mass\", po::value<real>(&(opts().solid_sphere_mass))->default_value(1.0), \"total mass enclosed inside the sphere\")     //\n        (\"solid_sphere_rho_min\", po::value<real>(&(opts().solid_sphere_rho_min))->default_value(1.0e-12), \"minimal density outside (and within) the sphere\")     //\n        (\"star_xcenter\", po::value<real>(&(opts().star_xcenter))->default_value(0.0), \"x-position of the star center\")     //\n        (\"star_ycenter\", po::value<real>(&(opts().star_ycenter))->default_value(0.0), \"y-position of the star center\")     //\n        (\"star_zcenter\", po::value<real>(&(opts().star_zcenter))->default_value(0.0), \"z-position of the star center\")     //\n        (\"star_n\", po::value<real>(&(opts().star_n))->default_value(1.5), \"polytropic index of the star\")     //\n        (\"star_rmax\", po::value<real>(&(opts().star_rmax))->default_value(1.0 / 3.0), \"maximal star radius\")     //\n        (\"star_dr\", po::value<real>(&(opts().star_dr))->default_value(1.0 / (3.0 * 128.0)), \"differential radius for solving the Lane-Emden equation\")     //\n        (\"star_alpha\", po::value<real>(&(opts().star_alpha))->default_value(1.0 / (3.0 * 3.65375)), \"scaling factor for the Lane-Emden equation\") // for default n=3/2, ksi_1=3.65375 and alpha=rmax/ksi_1\n        (\"star_rho_center\", po::value<real>(&(opts().star_rho_center))->default_value(1.0), \"density at the center of the star\")     //\n        (\"star_rho_out\", po::value<real>(&(opts().star_rho_out))->default_value(1.0e-10), \"density outside the star\")     //\n\t(\"star_egas_out\", po::value<real>(&(opts().star_egas_out))->default_value(1.0e-10), \"gas energy outside the star\")     //\n        (\"moving_star_xvelocity\", po::value<real>(&(opts().moving_star_xvelocity))->default_value(1.0), \"velocity of the star in the x-direction\")     //\n        (\"moving_star_yvelocity\", po::value<real>(&(opts().moving_star_yvelocity))->default_value(1.0), \"velocity of the star in the y-direction\")     //\n        (\"moving_star_zvelocity\", po::value<real>(&(opts().moving_star_zvelocity))->default_value(1.0), \"velocity of the star in the z-direction\")     //\n\t(\"clight_retard\", po::value<real>(&(opts().clight_retard))->default_value(1.0), \"retardation factor for speed of light\")                 //\n\t(\"driving_rate\", po::value<real>(&(opts().driving_rate))->default_value(0.0), \"angular momentum loss driving rate\")     //\n\t(\"driving_time\", po::value<real>(&(opts().driving_time))->default_value(0.0), \"A.M. driving rate time\")                 //\n\t(\"entropy_driving_time\", po::value<real>(&(opts().entropy_driving_time))->default_value(0.0), \"entropy driving rate time\")                 //\n\t(\"entropy_driving_rate\", po::value<real>(&(opts().entropy_driving_rate))->default_value(0.0), \"entropy loss driving rate\")      //\n\t(\"future_wait_time\", po::value<integer>(&(opts().future_wait_time))->default_value(-1), \"\")      //\n\t(\"silo_offset_x\", po::value<integer>(&(opts().silo_offset_x))->default_value(0), \"\")      //\n\t(\"silo_offset_y\", po::value<integer>(&(opts().silo_offset_y))->default_value(0), \"\")      //\n\t(\"silo_offset_z\", po::value<integer>(&(opts().silo_offset_z))->default_value(0), \"\")      //\n\t(\"amrbnd_order\", po::value<integer>(&(opts().amrbnd_order))->default_value(1), \"amr boundary interpolation order\")        //\n\t(\"scf_output_frequency\", po::value<integer>(&(opts().scf_output_frequency))->default_value(25), \"Frequency of SCF output\")        //\n\t(\"silo_num_groups\", po::value<integer>(&(opts().silo_num_groups))->default_value(-1), \"Number of SILO I/O groups\")        //\n\t(\"core_refine\", po::value<bool>(&(opts().core_refine))->default_value(false), \"refine cores by one more level\")           //\n\t(\"accretor_refine\", po::value<integer>(&(opts().accretor_refine))->default_value(0), \"number of extra levels for accretor\") //\n\t(\"extra_regrid\", po::value<integer>(&(opts().extra_regrid))->default_value(0), \"number of extra regrids on startup\") //\n\t(\"donor_refine\", po::value<integer>(&(opts().donor_refine))->default_value(0), \"number of extra levels for donor\")      //\n\t(\"ngrids\", po::value<integer>(&(opts().ngrids))->default_value(-1), \"fix numbger of grids\")                             //\n\t(\"refinement_floor\", po::value<real>(&(opts().refinement_floor))->default_value(1.0e-3), \"density refinement floor\")      //\n\t(\"theta\", po::value<real>(&(opts().theta))->default_value(0.5), \"controls nearness determination for FMM, must be between 1/3 and 1/2\")               //\n\t(\"eos\", po::value<eos_type>(&(opts().eos))->default_value(IDEAL), \"gas equation of state\")                              //\n\t(\"hydro\", po::value<bool>(&(opts().hydro))->default_value(true), \"hydro on/off\")    //\n\t(\"radiation\", po::value<bool>(&(opts().radiation))->default_value(false), \"radiation on/off\")    //\n\t(\"correct_am_hydro\", po::value<bool>(&(opts().correct_am_hydro))->default_value(true), \"Angular momentum correction switch for hydro\")    //\n\t(\"correct_am_grav\", po::value<bool>(&(opts().correct_am_grav))->default_value(true), \"Angular momentum correction switch for gravity\")    //\n\t(\"rewrite_silo\", po::value<bool>(&(opts().rewrite_silo))->default_value(false), \"rewrite silo and exit\")    //\n\t(\"rad_implicit\", po::value<bool>(&(opts().rad_implicit))->default_value(true), \"implicit radiation on/off\")    //\n\t(\"gravity\", po::value<bool>(&(opts().gravity))->default_value(true), \"gravity on/off\")    //\n\t(\"bench\", po::value<bool>(&(opts().bench))->default_value(false), \"run benchmark\") //\n\t(\"datadir\", po::value<std::string>(&(opts().data_dir))->default_value(\"./\"), \"directory for output\") //\n\t(\"output\", po::value<std::string>(&(opts().output_filename))->default_value(\"\"), \"filename for output\") //\n\t(\"odt\", po::value<real>(&(opts().output_dt))->default_value(1.0 / 100.0), \"output frequency\") //\n\t(\"dual_energy_sw1\", po::value<real>(&(opts().dual_energy_sw1))->default_value(0.001), \"dual energy switch 1\") //\n\t(\"dual_energy_sw2\", po::value<real>(&(opts().dual_energy_sw2))->default_value(0.1), \"dual energy switch 2\") //\n\t(\"hard_dt\", po::value<real>(&(opts().hard_dt))->default_value(-1), \"timestep size\") //\n\t(\"experiment\", po::value<int>(&(opts().experiment))->default_value(0), \"experiment\") //\n\t(\"unigrid\", po::value<bool>(&(opts().unigrid))->default_value(false), \"unigrid\") //\n\t(\"inflow_bc\", po::value<bool>(&(opts().inflow_bc))->default_value(false), \"Inflow Boundary Conditions\") //\n\t(\"reflect_bc\", po::value<bool>(&(opts().reflect_bc))->default_value(false), \"Reflecting Boundary Conditions\") //\n\t(\"cdisc_detect\", po::value<bool>(&(opts().cdisc_detect))->default_value(true), \"PPM contact discontinuity detection\") //\n\t(\"disable_output\", po::value<bool>(&(opts().disable_output))->default_value(false), \"disable silo output\") //\n\t(\"disable_diagnostics\", po::value<bool>(&(opts().disable_diagnostics))->default_value(false), \"disable diagnostics\") //\n\t(\"problem\", po::value<problem_type>(&(opts().problem))->default_value(NONE), \"problem type\")                            //\n\t(\"restart_filename\", po::value<std::string>(&(opts().restart_filename))->default_value(\"\"), \"restart filename\")         //\n\t(\"stop_time\", po::value<real>(&(opts().stop_time))->default_value(std::numeric_limits<real>::max()), \"time to end simulation\") //\n\t(\"stop_step\", po::value<integer>(&(opts().stop_step))->default_value(std::numeric_limits<integer>::max() - 1), \"number of timesteps to run\")          //\n\t(\"min_level\", po::value<integer>(&(opts().min_level))->default_value(1), \"minimum number of refinement levels\")         //\n\t(\"max_level\", po::value<integer>(&(opts().max_level))->default_value(1), \"maximum number of refinement levels\")         //\n\t(\"multipole_kernel_type\", po::value<interaction_kernel_type>(&(opts().m2m_kernel_type))->default_value(SOA_CPU), \"boundary multipole-multipole kernel type\") //\n\t(\"p2p_kernel_type\", po::value<interaction_kernel_type>(&(opts().p2p_kernel_type))->default_value(SOA_CPU), \"boundary particle-particle kernel type\")   //\n\t(\"p2m_kernel_type\", po::value<interaction_kernel_type>(&(opts().p2m_kernel_type))->default_value(SOA_CPU), \"boundary particle-multipole kernel type\") //\n\t(\"cuda_streams_per_locality\", po::value<size_t>(&(opts().cuda_streams_per_locality))->default_value(size_t(0)), \"cuda streams per HPX locality\") //\n\t(\"cuda_streams_per_gpu\", po::value<size_t>(&(opts().cuda_streams_per_gpu))->default_value(size_t(0)), \"cuda streams per GPU (per locality)\") //\n\t(\"cuda_scheduling_threads\", po::value<size_t>(&(opts().cuda_scheduling_threads))->default_value(size_t(0)),\n\t\t\t\"Number of worker threads per locality that mamage cuda streams\") //\n\t(\"input_file\", po::value<std::string>(&(opts().input_file))->default_value(\"\"), \"input file for test problems\") //\n\t(\"config_file\", po::value<std::string>(&(opts().config_file))->default_value(\"\"), \"configuration file\") //\n\t(\"n_species\", po::value<integer>(&(opts().n_species))->default_value(5), \"number of mass species\") //\n\t(\"atomic_mass\", po::value<std::vector<real>>(&(opts().atomic_mass))->multitoken(), \"atomic masses\") //\n\t(\"atomic_number\", po::value<std::vector<real>>(&(opts().atomic_number))->multitoken(), \"atomic numbers\") //\n\t(\"X\", po::value<std::vector<real>>(&(opts().X))->multitoken(), \"X - hydrogen mass fraction\") //\n\t(\"Z\", po::value<std::vector<real>>(&(opts().Z))->multitoken(), \"Z - metallicity\") //\n\t(\"code_to_g\", po::value<real>(&(opts().code_to_g))->default_value(1), \"code units to grams\") //\n\t(\"code_to_cm\", po::value<real>(&(opts().code_to_cm))->default_value(1), \"code units to centimeters\") //\n\t(\"code_to_s\", po::value<real>(&(opts().code_to_s))->default_value(1), \"code units to seconds\") //\n\t(\"rotating_star_amr\", po::value<bool>(&(opts().rotating_star_amr))->default_value(false), \"rotating star with AMR boundary in star\") //\n\t(\"rotating_star_x\", po::value<real>(&(opts().rotating_star_x))->default_value(0.0), \"x center of rotating_star\") //\n\t\t\t;\n\n\tboost::program_options::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, command_opts), vm);\n\tpo::notify(vm);\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << command_opts << \"\\n\";\n\t\treturn false;\n\t}\n\tif (!config_file.empty()) {\n\t\tstd::ifstream cfg_fs { vm[\"config_file\"].as<std::string>() };\n\t\tif (cfg_fs) {\n\t\t\tpo::store(po::parse_config_file(cfg_fs, command_opts), vm);\n\t\t} else {\n\t\t\tprintf(\"Configuration file %s not found!\\n\", config_file.c_str());\n\t\t\treturn false;\n\t\t}\n\t}\n\tpo::notify(vm);\n\tif (opts().silo_num_groups == -1) {\n\t\topts().silo_num_groups = hpx::find_all_localities().size();\n\n\t}\n\tif (opts().problem == DWD) {\n\t\topts().n_species = std::max(int(5), int(opts().n_species));\n\t}\n        if (opts().problem == MOVING_STAR || opts().problem == ROTATING_STAR) {\n                opts().n_species = std::max(int(2), int(opts().n_species));\n\t}\n\tn_fields = n_species + 10;\n\tif (!opts().restart_filename.empty()) {\n\t\tFILE *fp = fopen(opts().restart_filename.c_str(), \"rb\");\n\t\tif (fp == NULL) {\n\t\t\tprintf(\"restart.silo does not exist or invalid permissions\\n\");\n\t\t\tsleep(10);\n\t\t\tabort();\n\t\t} else {\n\t\t\tfclose(fp);\n\t\t}\n\t\tload_options_from_silo(opts().restart_filename);\n\t}\n\tif (opts().theta < octotiger::fmm::THETA_FLOOR) {\n\t\tstd::cerr << \"theta \" << theta << \" is too small since Octo-Tiger was compiled for a minimum of \" << octotiger::fmm::THETA_FLOOR << std::endl;\n\t\tstd::cerr << \"Either increase theta or recompile with a new theta minimum using the cmake parameter OCTOTIGER_THETA_MINIMUM\";\n\t\tabort();\n\t}\n\t{\n#define SHOW( opt ) std::cout << std::string( #opt ) << \" = \" << to_string(opt) << '\\n';\n\t\tstd::cout << \"atomic_number=\";\n\t\tfor (auto r : atomic_number) {\n\t\t\tstd::cout << std::to_string(r) << ',';\n\t\t}\n\t\tstd::cout << '\\n';\n\t\tstd::cout << \"atomic_mass=\";\n\t\tfor (auto r : atomic_mass) {\n\t\t\tstd::cout << std::to_string(r) << ',';\n\t\t}\n\t\tstd::cout << '\\n';\n\t\tstd::cout << \"X=\";\n\t\tfor (auto r : X) {\n\t\t\tstd::cout << std::to_string(r) << ',';\n\t\t}\n\t\tstd::cout << '\\n';\n\t\tstd::cout << \"Z=\";\n\t\tfor (auto r : Z) {\n\t\t\tstd::cout << std::to_string(r) << ',';\n\t\t}\n\t\tstd::cout << '\\n';\n\t\tconst auto num_loc = hpx::find_all_localities().size();\n\t\tif (silo_num_groups > num_loc) {\n\t\t\tprintf(\"Number of SILO file groups cannot be greater than number of localities. Setting silo_num_groupds to %li\\n\", num_loc);\n\t\t\tsilo_num_groups = num_loc;\n\t\t}\n\t\tSHOW(accretor_refine);\n\t\tSHOW(amrbnd_order);\n\t\tSHOW(bench);\n\t\tSHOW(cdisc_detect);\n\t\tSHOW(cfl);\n\t\tSHOW(clight_retard);\n\t\tSHOW(config_file);\n\t\tSHOW(core_refine);\n\t\tSHOW(correct_am_grav);\n\t\tSHOW(correct_am_hydro);\n\t\tSHOW(code_to_cm);\n\t\tSHOW(code_to_g);\n\t\tSHOW(code_to_s);\n\t\tSHOW(cuda_streams_per_locality);\n\t\tSHOW(cuda_streams_per_gpu);\n\t\tSHOW(data_dir);\n\t\tSHOW(disable_output);\n\t\tSHOW(driving_rate);\n\t\tSHOW(driving_time);\n\t\tSHOW(dt_max);\n\t\tSHOW(donor_refine);\n\t\tSHOW(dual_energy_sw1);\n\t\tSHOW(dual_energy_sw2);\n\t\tSHOW(eblast0);\n\t\tSHOW(eos);\n\t\tSHOW(entropy_driving_rate);\n\t\tSHOW(entropy_driving_time);\n\t\tSHOW(future_wait_time);\n\t\tSHOW(hard_dt);\n\t\tSHOW(hydro);\n\t\tSHOW(inflow_bc);\n\t\tSHOW(input_file);\n\t\tSHOW(m2m_kernel_type);\n\t\tSHOW(min_level);\n\t\tSHOW(max_level);\n\t\tSHOW(n_species);\n\t\tSHOW(ngrids);\n\t\tSHOW(omega);\n\t\tSHOW(output_dt);\n\t\tSHOW(output_filename);\n\t\tSHOW(p2m_kernel_type);\n\t\tSHOW(p2p_kernel_type);\n\t\tSHOW(problem);\n\t\tSHOW(rad_implicit);\n\t\tSHOW(radiation);\n\t\tSHOW(refinement_floor);\n\t\tSHOW(reflect_bc);\n\t\tSHOW(restart_filename);\n\t\tSHOW(rotating_star_amr);\n\t\tSHOW(rotating_star_x);\n\t\tSHOW(scf_output_frequency);\n\t\tSHOW(silo_num_groups);\n\t\tSHOW(stop_step);\n\t\tSHOW(stop_time);\n\t\tSHOW(theta);\n\t\tSHOW(unigrid);\n\t\tSHOW(v1309);\n\t\tSHOW(idle_rates);\n\t\tSHOW(xscale);\n\n\t}\n\twhile (atomic_number.size() < opts().n_species) {\n\t\tatomic_number.push_back(number_solar);\n\t}\n\twhile (atomic_mass.size() < opts().n_species) {\n\t\tatomic_mass.push_back(mass_solar);\n\t}\n\twhile (X.size() < opts().n_species) {\n\t\tX.push_back(X_solar);\n\t}\n\twhile (Z.size() < opts().n_species) {\n\t\tZ.push_back(Z_solar);\n\t}\n\tnormalize_constants();\n\tif (opts().problem == DWD) {\n\t\tif (opts().restart_filename == \"\" && opts().disable_diagnostics) {\n\t\t\tprintf(\"Diagnostics must be enabled for DWD\\n\");\n\t\t\tsleep(10);\n\t\t\tabort();\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstd::vector<hpx::id_type> options::all_localities = { };\n", "meta": {"hexsha": "db5efad56ec0735ffb1858f6463566b532888bd6", "size": 17933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/options.cpp", "max_stars_repo_name": "cclauss/octotiger", "max_stars_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/options.cpp", "max_issues_repo_name": "cclauss/octotiger", "max_issues_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/options.cpp", "max_forks_repo_name": "cclauss/octotiger", "max_forks_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.6925465839, "max_line_length": 202, "alphanum_fraction": 0.6586181899, "num_tokens": 5145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.03514484450594194, "lm_q1q2_score": 0.015929817168976634}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#include <fstream>\n#include <boost/format.hpp>\n\n//#include \"phycas/force_include.h\"\n#include \"probability_distribution.hpp\"\n#include \"model.hpp\"\n#include \"tree_likelihood.hpp\"\n#include \"xlikelihood.hpp\"\n#include \"mcmc_chain_manager.hpp\"\n#include \"bush_move.hpp\"\n#include \"basic_tree.hpp\"\n#include \"tree_manip.hpp\"\n\n//#define KEEP_BRANCHES_LEGAL\n//#define MAX_LEGAL_BRLEN 285\n\nusing namespace phycas;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tThe constructor sets `num_taxa' and `num_nodes_in_fully_resolved_tree' to zero, `edgelen_mean' to 1.0, `is_move' to\n|   true, creates the `topo_prior_calculator', and finally calls BushMove::reset to re-initialize all other variables.\n*/\nBushMove::BushMove()\n  : MCMCUpdater()\n\t{\n\tis_move = true;\n\tedgelen_mean = 1.0;\n\n\tnum_taxa = 0;\n\tnum_nodes_in_fully_resolved_tree = 0;\n\n\treset();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tDestructor does not need to do anything.\n*/\nBushMove::~BushMove()\n    {\n    //std::cerr << \"BushMove dying...\" << std::endl;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns true because this class is capable of computing the tree topology prior.\n*/\nbool BushMove::computesTopologyPrior() const\n    {\n    return true;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCalls proposeNewState(), then decides whether to accept or reject the proposed new state, calling accept() or\n|\trevert(), whichever is appropriate.\n*/\nbool BushMove::update()\n\t{\n\t// The only case in which is_fixed is true occurs when the user decides to fix the edge lengths.\n\t// A proposed BushMove cannot be accepted without changing edge lengths, so it is best to bail out now.\n\tif (is_fixed)\n\t\treturn false;\n\n\tif (num_taxa == 0)\n\t\t{\n\t\tthrow XLikelihood(\"Must call finalize() before calling update() for BushMove\");\n\t\t}\n\n    // chain_mgr is a weak_ptr: calling lock() creates a shared_ptr which ensures that the ChainManager\n    // object pointed to does not go away before we are done using it\n\tChainManagerShPtr p = chain_mgr.lock();\n\tPHYCAS_ASSERT(p);\n    JointPriorManagerShPtr jpm = p->getJointPriorManager();\n\n\tdouble prev_ln_like = p->getLastLnLike();\n\tdouble prev_ln_prior = jpm->getLogJointPrior();\n\n\tproposeNewState();\n\n\tcurr_ln_like = (heating_power > 0.0 ? likelihood->calcLnL(tree) : 0.0);\n\tcurr_ln_prior = jpm->getLogJointPrior();\n\n\t//likelihood->startTreeViewer(tree, str(boost::format(\"Bush move PROPOSED (%s)\") % (add_edge_move_proposed ? \"add edge\" : \"delete edge\")));\n\n    double prev_posterior = 0.0;\n\tdouble curr_posterior = 0.0;\n\n    if (is_standard_heating)\n        {\n        prev_posterior = heating_power*(prev_ln_like + prev_ln_prior);\n\t    curr_posterior = heating_power*(curr_ln_like + curr_ln_prior);\n        PHYCAS_ASSERT(!use_ref_dist);   // Bush move not ready for generalized steppingstone yet\n        }\n    else\n        {\n        prev_posterior = heating_power*prev_ln_like + prev_ln_prior;\n\t    curr_posterior = heating_power*curr_ln_like + curr_ln_prior;\n        }\n\n\tdouble ln_accept_ratio = curr_posterior - prev_posterior + ln_hastings + ln_jacobian;\n\n    bool accepted = (ln_accept_ratio >= 0.0 || std::log(rng->Uniform()) <= ln_accept_ratio);\n    if (save_debug_info)\n        {\n    \tif (add_edge_move_proposed)\n            {\n            debug_info = str(boost::format(\"Bush: add (%s)\") % (accepted ? \"accepted\" : \"rejected\"));\n            }\n        else\n            {\n            debug_info = str(boost::format(\"Bush: del (%s)\") % (accepted ? \"accepted\" : \"rejected\"));\n            }\n        }\n\n\tif (accepted)\n\t\t{\n\t\tp->setLastLnLike(curr_ln_like);\n\t\taccept();\n\t\t}\n\telse\n\t\t{\n\t\tcurr_ln_like = p->getLastLnLike();\n\t\trevert();\n\t\t}\n\n    return accepted;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tProposes either an add-edge move (addition of an edge to a polytomy) or a delete-edge move (deletion of an existing\n|\tedge) with equal probability. If tree is currently fully-resolved, proposes only a delete-edge move. If tree is\n|\tcurrently the star tree, proposes only an add-edge move.\n*/\nvoid BushMove::proposeNewState()\n\t{\n\tunsigned nnodes = tree->GetNNodes();\n\tconst bool fully_resolved_before = (num_nodes_in_fully_resolved_tree == nnodes);\n\tconst bool star_tree_before = (nnodes == num_taxa + 1);\n\tadd_edge_move_proposed = (!fully_resolved_before) && (star_tree_before || rng->Uniform() < 0.5);\n\n\trefreshPolytomies();\n\tnum_polytomies = (unsigned)polytomies.size();\n\n\t// One internal edge leads to the tip node serving as the root, but that one doesn't count\n\tconst unsigned num_internal_edges_before = tree->GetNInternals() - 1;\n\n\tTreeNode * nd = NULL;\n\tif (add_edge_move_proposed)\n\t\t{\n\t\t// Choose a polytomy at random to split\n\t\t//\n\t\tPHYCAS_ASSERT(num_polytomies > 0);\n\t\tunsigned i = rng->SampleUInt(num_polytomies);\n\t\tnd = polytomies[i];\n\t\tproposeAddEdgeMove(nd);\n\n\t\t// Compute the Jacobian by working backwards to obtain the uniform used to sample new_edgelen (done in\n\t\t// proposeAddEdgeMove function). Remember that U = 1 - e^{-theta*v} where v is the new edge length,\n\t\t// and theta = 1/edgelen_mean is the hazard parameter of the exponential distribution used for\n\t\t// sampling new edge lengths. log(1 - U) = -theta*v = -v/edgelen_mean. The Jacobian for this move\n\t\t// can be obtained using the Green (2003) approach. The new edge length v that exists after the\n\t\t// add-edge move corresponds with the uniform random deviate U before the add-edge move. The\n\t\t// Jacobian is the matrix of the derivatives of all post-move quantities with respect to all\n\t\t// pre-move quantities. In this case, there is only one post-move quantity (v) and only one pre-move\n\t\t// quantity (U), so the Jacobian is a 1x1 matrix consisting only of the derivative of v with respect\n\t\t// to U. The quantity v can be written as -edgelen_mean*log(1 - U), so the partial derivative is\n        // simply edgelen_mean/(1 - U). The log of the jacobian is thus:\n\t\t//\n\t\t//      ln_jacobian = log(edgelen_mean) - log(1 - U) = log(edgelen_mean) + v/edgelen_mean\n\t\t//\n\t\tln_jacobian = log(edgelen_mean) + new_edgelen/edgelen_mean;\n\n\t\t// The Hastings ratio is the probability of the reverse move divided by probability of the forward move.\n\t\t// The add-edge move involves the following 4 steps:\n\t\t//   1) choosing a polytomy to break (the probability of this is the inverse of the number of polytomies)\n\t\t//   2) choosing the number of spokes to move over to the new node\n\t\t//   3) selecting exactly which spokes to move\n\t\t//   4) choosing U ~ Uniform(0,1) to determine the new edge length (probability density is 1).\n\t\t// The probability of steps 2 and 3 are easier to compute jointly because of some convenient cancellation:\n\t\t// For step 2, assuming x spokes out of n total are moved, the probability is (see explanation in\n\t\t// documentation for BushMove::computePolytomyDistribution):\n\t\t//\n\t\t//              {n choose x} + {n choose (n-x)}\n\t\t// Pr(step 2) = -------------------------------\n\t\t//                       2^n - 2*(n+1)\n\t\t//\n\t\t// If x is exactly half of n, the numerator will have only the one term (n choose x), whereas the\n\t\t// denominator will remain the same. For example, let the tree be the 4-taxon star tree (A,B,C,D),\n\t\t// so n = 4, and let 2 nodes (A and C) be moved, then\n\t\t//\n\t\t//              {4 choose 2}       6\n\t\t// Pr(step 2) = ------------- = ------- = 1\n\t\t//              2^4 - 2*(4+1)   16 - 10\n\t\t//\n\t\t// For step 3, the probability is simply 1 over the number of distinct trees in which an n-spoke\n\t\t// polytomy has been divided into a node with x+1 spokes and another with n - x + 1 spokes:\n\t\t//\n\t\t//                              2\n\t\t// Pr(step 3) = -------------------------------\n\t\t//               {n choose x} + {n choose n-x}\n\t\t//\n\t\t// Again, if x is exactly half of n, the denominator will have only the one term {n choose x}. For\n\t\t// example, continuing the example above with n = 4 and x = 2, and the tree after the add-edge\n\t\t// move is (B, D, (A, C))\n\t\t//\n\t\t//                   2        2     1\n\t\t// Pr(step 3) = ---------- = --- = ---\n\t\t//              4 choose 2    6     3\n\t\t//\n\t\t// The 6 in the denominator corresponds with these possibilities, and the 2 in the numerator are\n\t\t// indicated by asterisks:\n\t\t//\n\t\t//  A     C   A     B   A     B   B     A   B     A   C     A\n\t\t//   \\___/     \\___/     \\___/     \\___/     \\___/     \\___/\n\t\t//   /   \\     / * \\     /   \\     /   \\     / * \\     /   \\  <not a backslash>\n\t\t//  B     D   C     D   C     D   C     D   D     C   D     B\n\t\t//\n\t\t//\n\t\t// Fortunately, the hard part of both calculations cancels, and the probability of steps 2 and 3 is:\n\t\t//\n\t\t//                                2                1\n\t\t// Pr(step 2 and step 3) = -------------- = ---------------\n\t\t//                           2^n - 2(n+1)   2^(n-1) - n - 1\n\t\t//\n\t\t// A different way to obtain Pr(step 2 and step 3) is to imagine placing nodes randomly in two piles,\n\t\t// pile 1 and pile 2. After the first node is placed, arbitrarily establishing pile 1, there are\n\t\t// n - 1 nodes left. For each one let the probability it is placed in pile 1 be 0.5, with the\n\t\t// probability of placing the node in pile 2 being 0.5 also. The probability of any one outcome is\n\t\t// thus 2^{n-1}, but some outcomes are not acceptable. The n outcomes in which one taxon is separated\n\t\t// from all other taxa are not acceptable because they are indistinguishable from the orignal polytomy.\n\t\t// In addition, the outcome in which all taxa end up in pile 1 is unacceptable for the same reason.\n\t\t// Thus, there are n + 1 unacceptable outcomes, and these must be subtracted from the 2^{n-1} possible\n\t\t// outcomes when determining the denominator of the probability.\n\t\t//\n\t\t// The probability of proposing an add-edge move is thus:\n\t\t//\n\t\t//                          1                   1             1                     1\n\t\t// Pr(add-edge move) = -------------- X ---------------- X ------- = ----------------------------------\n\t\t//                     num_polytomies    2^(n-1) - n - 1   (1 - 0)   num_polytomies * [2^(n-1) - n - 1]\n\t\t//\n\t\t// The delete-edge move is simpler, involving only the choice of the edge that must be deleted from the tree to\n\t\t// reverse the add-edge move (probability is inverse of the number of edges in the post-add-edge-move tree).\n\t\t//\n\t\t// Thus, the Hastings ratio for an add-edge move is:\n\t\t//\n\t\t//                                                                1\n\t\t//                                                  -----------------------------\n\t\t//  Pr(delete-edge of proposed add-edge move)       num_internal_edges_before + 1\n\t\t//  ----------------------------------------- = -------------------------------------\n\t\t//      Pr(proposed add-edge move)                                1\n\t\t//                                              -------------------------------------\n\t\t//                                               num_polytomies * [2^(n-1) - n - 1]\n\t\t//\n\t\t//                                                num_polytomies * [2^(n-1) - n - 1]\n\t\t//                                            =  -------------------------------------\n\t\t//                                                   num_internal_edges_before + 1\n\t\t//\n\t\t// If proposed state is the fully-resolved tree, or if the reverse move would generate a fully-resolved tree,\n\t\t// then the Hastings ratio must account for the fact that one of the moves is only attempted half the time\n\t\t// whereas the other move is the only move possible. If the proposal generates a fully-resolved tree,\n\t\t// multiply the Hastings ratio as calculated above by 2.0. If the proposal takes us away from a fully-resolved\n\t\t// tree, then divide the Hastings ratio as calculated above by 2.0.\n\n\t\t// nspokes is n_p in Lewis, Holder and Holsinger (2005)\n\t\tdouble nspokes = (double)polytomy_size;\n\n\t\t// Compute the log of the Hastings ratio\n\t\tln_hastings = log((double)num_polytomies);\n\t\tln_hastings += log(pow(2.0, nspokes - 1.0) - nspokes - 1.0);\n\t\tln_hastings -= log((double)num_internal_edges_before + 1.0);\n\n\t\t// Now multiply by the value of the quantity labeled gamma_b in the paper\n\t\tnnodes = tree->GetNNodes();\n\t\tconst bool fully_resolved_after = (nnodes == num_nodes_in_fully_resolved_tree);\n\t\tif (star_tree_before && !fully_resolved_after)\n\t\t\tln_hastings -= log(2.0);\n\t\telse if (fully_resolved_after && !star_tree_before)\n\t\t\tln_hastings += log(2.0);\n\t\t//@POL the pow will be problematic for large polytomies\n\t\t}\n\telse\n\t\t{\n\t\t// Choose an internal node at random (but not the only child of the root node)\n\t\t// and delete its edge to create a polytomy (or a bigger polytomy if there is\n\t\t// already a polytomy)\n\t\t//\n\t\tunsigned num_internals = nnodes - num_taxa - 1;\n\t\tPHYCAS_ASSERT(num_internals > 0);\n\t\tPHYCAS_ASSERT(num_internals < num_taxa);\n\t\tunsigned i = rng->SampleUInt(num_internals);\n\n\t\tfor (nd = tree->GetFirstPreorder(); nd != NULL; nd = nd->GetNextPreorder())\n\t\t\t{\n\t\t\tif (nd->IsTip() || nd->GetParent()->IsTipRoot())\n\t\t\t\tcontinue;\n\n\t\t\tif (i == 0)\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\t--i;\n\t\t\t}\n        //nd->SelectNode();\n\t\t//likelihood->startTreeViewer(tree, \"Delete edge move\");\n\t\tproposeDeleteEdgeMove(nd);\n\n\t\t// The Jacobian is the matrix of the derivatives of all post-move quantities with respect to all\n\t\t// pre-move quantities. In this case, there is only one pre-move quantity (v) and only one post-move\n\t\t// quantity (U), so the Jacobian is a 1x1 matrix consisting only of the derivative of U with respect\n\t\t// to v. U = 1 - exp{-theta*v}, so the Jacobian for this delete-edge move is theta*exp(-theta*v),\n\t\t// where v is the length of the edge being deleted and theta = 1/edgelen_mean is the hazard parameter\n\t\t// of the exponential distribution used for sampling new edge lengths. Thus,\n\t\t//\n\t\t// ln_jacobian = log[theta*exp(-theta*v)]\n\t\t//             = log[exp(-v/edgelen_mean)/edgelen_mean]\n\t\t//             = -(v/edgelen_mean) - log(edgelen_mean)\n\t\t//\n\t\t// Note that v = orig_edgelen; orig_edgelen was set in ProposeDeleteEdgeMove.\n\t\tln_jacobian = -orig_edgelen/edgelen_mean - log(edgelen_mean);\n\n\t\t// Hastings ratio is inverse of that for the add-edge move (see extensive notes above), but be\n\t\t// careful to use the number of polytomies in tree *after* a delete-edge move and the number of internal\n\t\t// edges *before* a delete-edge move in the formula. Here, n is the number of spokes in the polytomy\n\t\t// created by the delete-edge move. Both polytomy_size and num_polytomies are correctly computed by\n\t\t// ProposeDeleteEdgeMove.\n\t\t//\n\t\t//  Pr(add-edge move that reverts proposed delete-edge move)         num_internal_edges_before\n\t\t//  -------------------------------------------------------- = -----------------------------------------\n\t\t//                Pr(proposed delete-edge move)                 num_polytomies_after * [2^(n-1) - n - 1]\n\t\t//\n\t\t// If the proposed state is the star tree, then the Hastings ratio must account for the fact that\n\t\t// the forward move is only attempted half the time whereas the reverse move is the only move possible\n\t\t// for the star tree. Thus, if the number of nodes in the tree after the proposal is 1 more than the\n\t\t// number of taxa, the Hastings ratio as computed above must be multiplied by 2.0. If the proposal takes\n\t\t// us away from the star tree, then the Hastings ratio must be divided by 2.0.\n\t\t//\n\t\tdouble nspokes = (double)polytomy_size;\n\n\t\t// Compute the log of the Hastings ratio\n\t\tln_hastings = log((double)num_internal_edges_before);\n\t\tln_hastings -= log((double)num_polytomies);\n\t\tln_hastings -= log(pow(2.0, nspokes - 1.0) - nspokes - 1.0);\n\n\t\t// Now multiply by the value of the quantity labeled gamma_d in the paper\n\t\tnnodes = tree->GetNNodes();\n\t\tconst bool star_tree_after = (nnodes == num_taxa + 1);\n\t\tif (fully_resolved_before && !star_tree_after)\n\t\t\t{\n\t\t\tln_hastings -= log(2.0);\n\t\t\t}\n\t\telse if (star_tree_after && !fully_resolved_before)\n\t\t\t{\n\t\t\tln_hastings += log(2.0);\n\t\t\t}\n\t\t//@POL the pow will be problematic for large polytomies\n\t\t}\n\n\tChainManagerShPtr p = chain_mgr.lock();\n\tPHYCAS_ASSERT(p);\n    JointPriorManagerShPtr jpm = p->getJointPriorManager();\n    jpm->skipNextDebugCheck();\n    jpm->allEdgeLensModified(tree);\n    jpm->topologyModified(\"tree_topology\", tree);\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|\tSets `num_taxa' to the number of tips in `tree', computes the polytomy distribution, and sets the number of taxa for the\n|\t`topo_prior_calculator' object to `num_taxa'.\n*/\nvoid BushMove::finalize()\n\t{\n\tnum_taxa = tree->GetNTips();\n\tnum_nodes_in_fully_resolved_tree = 2*(num_taxa - 1);    // ASSUMES UNROOTED TREE\n\n    // 1   2 3   4    1   2   3   4    Fully-resolved rooted trees have 2*num_taxa nodes\n    //  \\ /   \\ /      \\   \\   \\ /     if the root node (fake tip) is included, regardless\n    //   5     6        \\   \\   5      of symmetry.\n    //    \\   /          \\   \\ /\n    //     \\ /            \\   6\n    //      7              \\ /\n    //      |               7\n    //      8               |\n    //                      8\n\n\tcomputePolytomyDistribution(num_taxa);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCalled if the proposed move is rejected. Causes tree to be returned to its state just prior to proposing the move.\n*/\nvoid BushMove::revert()\n\t{\n\tMCMCUpdater::revert();\n\tif (add_edge_move_proposed)\n\t\t{\n\t\t// An add-edge move was previously proposed, which means a new internal node (orig_lchild) and its edge were created.\n\t\t// orig_lchild's parent is known as orig_par. The children of orig_lchild represent a subset of the original children\n\t\t// of orig_par. To reverse the add-edge move, we need only transfer all children of orig_lchild to orig_par, then store\n\t\t// orig_lchild for use in some later add-edge move proposal\n\n\t\t// Must discard CLAs before moving children, otherwise orig_lchild will look like a tip node\n\t\t// which causes invalidateBothEndsDiscardCache to attempt to access its TipData structure\n\t\tlikelihood->invalidateBothEndsDiscardCache(orig_lchild); //@POL should not be any cached CLAs here\n\n\t\t// Transfer all children of orig_lchild to orig_par\n\t\twhile (orig_lchild->GetLeftChild() != NULL)\n\t\t\t{\n\t\t\tTreeNode * s = orig_lchild->GetLeftChild();\n\t\t\ttree_manipulator.DetachSubtree(s);\n\t\t\ttree_manipulator.InsertSubtree(s, orig_par, TreeManip::kOnRight);\n\t\t\t}\n\n\t\t// Now delete orig_lchild\n\t\t//\n\t\ttree_manipulator.DetachSubtree(orig_lchild);\n\t\ttree->StoreInternalNode(orig_lchild);\n\n\t\tlikelihood->useAsLikelihoodRoot(orig_par);\n\t\tlikelihood->restoreFromCacheAwayFromNode(*orig_par);\n\n\t\t//likelihood->startTreeViewer(tree, \"Add edge move REVERTED\");\n\n\t\ttree->InvalidateNodeCounts();\n\t\t}\n\telse\n\t\t{\n\t\t// A delete-edge move was proposed, which means an internal node and its edge have been deleted. This deleted\n\t\t// node's parent is known as orig_par. The children of the deleted node have been added as children of orig_par,\n\t\t// with the first being identified now as orig_lchild and the last in the series now pointed to by orig_rchild.\n\t\t// To revert the delete-edge move, create a new child of orig_par having edgelen equal to orig_edgelen, then transfer\n\t\t// the nodes from orig_lchild to orig_rchild (following rSib pointers, and including both orig_lchild and\n\t\t// orig_rchild) to the new node.\n\t\t//\n\t\tTreeNode * u = tree->GetNewNode();\n\t\tu->SetEdgeLen(orig_edgelen);\n\t\ttree_manipulator.InsertSubtree(u, orig_par, TreeManip::kOnRight);\n\n\t\tTreeNode * nd = orig_lchild;\n\t\tfor (;;)\n\t\t\t{\n\t\t\tTreeNode * s = nd;\n\t\t\tPHYCAS_ASSERT(s != NULL);\n\t\t\tnd = nd->GetRightSib();\n\t\t\ttree_manipulator.SibToChild(u, s, TreeManip::kOnRight);\n\t\t\tif (s == orig_rchild)\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tlikelihood->useAsLikelihoodRoot(orig_par);\n\t\tlikelihood->restoreFromCacheAwayFromNode(*orig_lchild);\n\t\tlikelihood->restoreFromCacheParentalOnly(orig_lchild);\n\n\t\t//orig_par->UnselectNode();\n\t\t//likelihood->startTreeViewer(tree, \"Delete edge move REVERTED\");\n\n\t\ttree->InvalidateNodeCounts();\n\t\t}\n\n\treset();\n\n\tChainManagerShPtr p = chain_mgr.lock();\n\tPHYCAS_ASSERT(p);\n    JointPriorManagerShPtr jpm = p->getJointPriorManager();\n    jpm->skipNextDebugCheck();\n    jpm->allEdgeLensModified(tree);\n    jpm->topologyModified(\"tree_topology\", tree);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tClears the `polytomies' vector, then walks the tree adding nodes that represent polytomies (more than two children)\n|\tto the `polytomies' vector.\n*/\nvoid BushMove::refreshPolytomies()\n\t{\n\t//@POL should keep polytomies list up to date rather than building anew\n\tpolytomies.clear();\n\tfor (TreeNode *nd = tree->GetFirstPreorder(); nd != NULL; nd = nd->GetNextPreorder())\n\t\t{\n\t\tif (nd->IsTipRoot())\n\t\t\tcontinue;\n\n\t\tunsigned s = nd->CountChildren();\n\t\tif (s > 2)\n\t\t\t{\n\t\t\tpolytomies.push_back(nd);\n\t\t\t}\n\t\t}\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|\tDetermines distribution of x given nspokes, where x is the number spokes assigned to the newly created node in an\n|\tadd-edge move. The number of ways of choosing x spokes to move out of nspokes total is {nspokes \\choose x}. We are not\n|\tinterested in the values x = 0, x = 1, x = nspokes - 1, and x = n because these lead either to a non-move (x = 0 and\n|\tx = nspokes) or to a tree that has an invalid structure (x = 1 and x = nspokes - 1). Thus, the total number of possible\n|\ttrees considered is {nspokes \\choose 2} + {nspokes \\choose 3} + ... + {n \\choose nspokes - 2} =\n|\t2^nspokes - 2*(nspokes + 1). The 2^nspokes comes from the fact that 2^nspokes is the sum of all binomial coefficients\n|\tfor a sample size of nspokes. The subtracted term 2(nspokes + 1) comes from the fact that the first and last binomial\n|\tcoefficients - {nspokes \\choose 0} and {nspokes \\choose nspokes} - are always 1 and the second and penultimate binomial\n|\tcoefficients - {nspokes \\choose 1} and {nspokes \\choose nspokes - 1} - always equal nspokes. Thus, if one wishes to\n|\tchoose randomly from all possible ways of splitting the polytomy into two groups of spokes, select x with probability:\n|>\n|\t                    (nspokes \\choose x}\n|\t  Pr(X = x) = -----------------------------, x = 2, 3, ..., nspokes - 2\n|\t                2^nspokes - 2*(nspokes + 1)\n|>\n*/\nconst VecPolytomyDistr & BushMove::computePolytomyDistribution(unsigned nspokes)\n\t{\n\tPHYCAS_ASSERT(nspokes > 2);\n\tstd::pair<PolytomyDistrMap::const_iterator, bool> retval;\n\tPolytomyDistrMap::const_iterator i = poly_prob.find(nspokes);\n\tif (i == poly_prob.end())\n\t\t{\n\t\t// There is no existing probability distribution vector corresponding to nspokes\n\t\t// Need to calcuate it and insert into poly_prob map.\n\t\tdouble ln_nfact = cdf.LnGamma((double)(nspokes + 1));\n\t\tdouble denom = exp((double)nspokes * log(2.0)) - 2.0*nspokes - 2.0; //@POL may need to factor if n large\n\t\tdouble ln_denom = log(denom);\n\t\tVecPolytomyDistr v;\n\t\tfor (unsigned x = 2; x <= nspokes - 2; ++x)\n\t\t\t{\n\t\t\tdouble ln_numer = ln_nfact - cdf.LnGamma((double)(x + 1)) - cdf.LnGamma((double)(nspokes - x + 1));\n\t\t\tdouble prob_x = exp(ln_numer - ln_denom);\n\t\t\tv.push_back(prob_x);\n\t\t\t}\n\t\tretval = poly_prob.insert(PolytomyDistrMap::value_type(nspokes, v));\n\t\tPHYCAS_ASSERT(retval.second == true);\n\t\ti = retval.first;\n\t\t}\n\treturn (i->second);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSplit up the polytomy at `u' by creating a new internal node v and a new edge connecting u with v. Node u is saved\n|\tas `orig_par' and node v is saved as `orig_lchild' in case we need to revert the proposed move.\n*/\nvoid BushMove::proposeAddEdgeMove(TreeNode * u)\n\t{\n\tPHYCAS_ASSERT(u != NULL);\n\tpolytomy_size = 1 + u->CountChildren();\n\n\tconst std::vector<double> & prob_n = computePolytomyDistribution(polytomy_size);\n\n\t// Select number of spokes to move over to new node\n\tunsigned x;\n\tdouble p = rng->Uniform();\n\tdouble cum = 0.0;\n\tfor (unsigned k = 0; k <= polytomy_size - 4; ++k)\n\t\t{\n\t\tx = k + 2;\n\t\tdouble prob_k_given_n = prob_n[k];\n\t\tcum += prob_k_given_n;\n\t\tif (p < cum)\n\t\t\tbreak;\n\t\t}\n\tPHYCAS_ASSERT(x < polytomy_size - 1);\n\n\t// Create the new node that will receive the x randomly-chosen spokes\n\tnew_edgelen = edgelen_dist->Sample();\n\tTreeNode * v = tree->GetNewNode();\n\tv->SetEdgeLen(new_edgelen);\n\tv->SetNodeNum(tree->GetNNodes());\n\tlikelihood->prepareInternalNodeForLikelihood(v);\n\ttree_manipulator.InsertSubtree(v, u, TreeManip::kOnLeft);\n\n\t// Save u and v. If revert is necessary, all of orig_lchild's nodes will be returned\n\t// to orig_par, and orig_lchild will be deleted.\n\t//\n\torig_par = u;\n\torig_lchild = v;\n\n\t// After the move, either v or u should have x spokes and the other node polytomy_size - x spokes (u and v will\n\t// each have 1 additional connector spoke).Choose x spokes randomly out of the polytomy_size available.\n\t// If u->par is included, let u retain the x spokes and move polytomy_size - x spokes to v. Otherwise, move the\n\t// x spokes to v leaving polytomy_size - x spokes behind.\n\t//\n\tstd::vector<TreeNode *> uspokes;\n\tuspokes.push_back(u->GetParent());\n\tfor (TreeNode *uchild = u->GetLeftChild(); uchild != NULL; uchild = uchild->GetRightSib())\n\t\t{\n\t\tif (uchild != v)\n\t\t\tuspokes.push_back(uchild);\n\t\t}\n\tPHYCAS_ASSERT(uspokes.size() == polytomy_size);\n\n\tbool reverse_polarity = false;\n\tstd::vector<TreeNode *> vspokes;\n\ttypedef std::vector<TreeNode *>::iterator::difference_type vec_it_diff;\n\tfor (unsigned k = 0; k < x; ++k)\n\t\t{\n\t\tunsigned num_u_spokes = (unsigned)uspokes.size();\n\t\tPHYCAS_ASSERT(num_u_spokes > 0);\n\t\tunsigned j = rng->SampleUInt(num_u_spokes);\n\t\tTreeNode * s = uspokes[j];\n\t\tif (s == u->GetParent())\n\t\t\treverse_polarity = true;\n\t\tvspokes.push_back(s);\n\t\tuspokes.erase(uspokes.begin() + (vec_it_diff) j);\n\t\t}\n\tPHYCAS_ASSERT(uspokes.size() + vspokes.size() == polytomy_size);\n\n\tif (reverse_polarity)\n\t\t{\n\t\t// transfer nodes in uspokes to v\n\t\t//\n\t\tstd::vector<TreeNode *>::iterator s;\n\t\tfor (s = uspokes.begin(); s != uspokes.end(); ++s)\n\t\t\t{\n\t\t\ttree_manipulator.DetachSubtree(*s);\n\t\t\ttree_manipulator.InsertSubtree(*s, v, TreeManip::kOnRight);\n\t\t\t}\n\t\t}\n\telse\n\t\t{\n\t\t// transfer nodes in vspokes to v\n\t\t//\n\t\tstd::vector<TreeNode *>::iterator s;\n\t\tfor (s = vspokes.begin(); s != vspokes.end(); ++s)\n\t\t\t{\n\t\t\ttree_manipulator.DetachSubtree(*s);\n\t\t\ttree_manipulator.InsertSubtree(*s, v, TreeManip::kOnRight);\n\t\t\t}\n\t\t}\n\n\t//orig_lchild->SelectNode();\n\n    //v->SelectNode();\n    //likelihood->startTreeViewer(tree, \"proposeAddEdgeMove\");\n\n\tlikelihood->useAsLikelihoodRoot(orig_lchild);\n\tlikelihood->invalidateAwayFromNode(*orig_lchild);\n\tlikelihood->invalidateBothEnds(orig_lchild);\t//@POL really just need invalidateParentalOnly function\n\n\ttree->InvalidateNodeCounts();\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|\tDelete the edge associated with `u' to create a polytomy (or a bigger polytomy if `u->par' was already a polytomy).\n|\tThe supplied node u should not be the only child of the root node.\n|>\n|\t      b       c\n|\t       \\     /\n|\t        \\   /\n|\t         \\ /\n|\t  a       u\t\t   a   b   c\n|\t   \\     /\t\t    \\  |  /\n|\t    \\   /\t\t     \\ | /\n|\t     \\ /\t\t      \\|/\n|         v                v\n|\t     /\t\t\t      /\n|\n|\t    Before           After\n|>\n|\tReturns the number of polytomies in the tree after the proposed delete-edge move. The return value will be incorrect if\n|\tthe polytomies vector is not up-to-date.\n*/\nvoid BushMove::proposeDeleteEdgeMove(TreeNode * u)\n\t{\n\t// Node u will be stored, so get rid of any CLAs\n\t//@POL should not discard cache here in case move is reverted - right now we're discarding because\n\t// tree_manipulator.DeleteLeaf stores node u, and we do not want any CLAs to travel to node storage\n\t// and come back to haunt us later. Better solution would be to keep u around until we know the move\n\t// will be accepted, at which point the CLAs can definitely be discarded\n\tlikelihood->invalidateBothEndsDiscardCache(u);\n\n    bool u_is_internal = u->IsInternal();\n\n    // Save nd's edge length in case we need to revert\n\t//\n\torig_edgelen = u->GetEdgeLen();\n\n\t// This operation should not leave the root node (which is a tip) with more than\n\t// one child, so check to make sure that the supplied node is not the root nor a\n\t// child of root\n\t//\n\torig_par = u->GetParent();\n\tPHYCAS_ASSERT(orig_par != NULL);\n\tPHYCAS_ASSERT(!orig_par->IsTipRoot());\n\n\tnum_polytomies = (unsigned)polytomies.size();\n\n\t// Compute size of polytomy after the delete-edge move, a quantity that is needed for computing the Hastings ratio.\n\t// Note that one of v's children (i.e. u) is deleted but this is made up for by considering v->par, which is\n\t// also a spoke that counts.\n\t//\n\tunsigned u_children = u->CountChildren();\n\tunsigned v_children = orig_par->CountChildren();\n\tpolytomy_size = v_children + u_children;\n\n\tbool u_polytomy_before = (u_children > 2);\n\tbool v_polytomy_before = (v_children > 2);\n\tif (u_polytomy_before && v_polytomy_before)\n\t\t{\n\t\t// No. polytomies will decrease by one as a result of this delete-edge move\n\t\t//\n\t\t--num_polytomies;\n\t\t}\n\telse if (!u_polytomy_before && !v_polytomy_before)\n\t\t{\n\t\t// No. polytomies will increase by one as a result of this delete-edge move\n\t\t//\n\t\t++num_polytomies;\n\t\t}\n\n\t// Make all of u's children left siblings (i.e. children of u->par)\n\t//\n\torig_lchild = u->GetLeftChild();\n\twhile (u->GetLeftChild() != NULL)\n\t\t{\n\t\torig_rchild = u->GetLeftChild();\n\t\ttree_manipulator.DetachSubtree(orig_rchild);\n\t\ttree_manipulator.InsertSubtree(orig_rchild, orig_par, TreeManip::kOnRight);\n\t\t}\n\n\ttree_manipulator.DeleteLeaf(u, u_is_internal);\n\n\t//orig_par->SelectNode();\n\n\tlikelihood->useAsLikelihoodRoot(orig_par);\n\tlikelihood->invalidateAwayFromNode(*orig_par);\n\n\ttree->InvalidateNodeCounts();\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|\tSetup `edgelen_dist' data member.\n*/\nvoid BushMove::setEdgeLenDistMean(\n  double mean)\n\t{\n\tPHYCAS_ASSERT(mean > 0.0);\n\tif (rng)\n\t\t{\n\t\tedgelen_mean = mean;\n\t\tedgelen_dist = ExponentialDistributionShPtr(new phycas::ExponentialDistribution(1.0/edgelen_mean));\n\t\tedgelen_dist->SetMeanAndVariance(edgelen_mean, edgelen_mean);\n\t\tedgelen_dist->SetLot(rng.get());  //@POL should just be able to pass in the shared_ptr rather than a raw pointer\n\t\t}\n\telse\n\t\t{\n\t\tthrow XLikelihood(\"Must set the pseudorandom number generator before calling setEdgeLenDistMean\");\n\t\t}\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|\tCalled if the move is accepted.\n*/\nvoid BushMove::accept()\n\t{\n\tMCMCUpdater::accept();\n\tif (add_edge_move_proposed)\n\t\t{\n\t\t// Keeping added edge, where orig_par was original polytomous node and orig_lchild was the added node\n\t\tlikelihood->useAsLikelihoodRoot(orig_lchild);\n\t\tlikelihood->discardCacheAwayFromNode(*orig_lchild);\n\t\tlikelihood->discardCacheBothEnds(orig_lchild);\n\n\t\t//likelihood->startTreeViewer(tree, \"Add edge move ACCEPTED\");\n\t\t}\n\telse\n\t\t{\n\t\t// Keeping edge deletion, orig_par is the new polytomous node\n\t\tlikelihood->useAsLikelihoodRoot(orig_par);\n\t\tlikelihood->discardCacheAwayFromNode(*orig_par);\n\n\t\t//likelihood->startTreeViewer(tree, \"Delete edge move ACCEPTED\");\n\t\t}\n\n\treset();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns current value of `add_edge_move_proposed' data member, which is true if the last move proposed was an\n|\tadd-edge move and false if last move proposed was a delete-edge move.\n*/\nbool BushMove::addEdgeMoveProposed() const\n\t{\n\treturn add_edge_move_proposed;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tRe-initializes all data members that are recomputed each time ProposeNewState is called.\n*/\nvoid BushMove::reset()\n\t{\n\t// Workspace used for computing edge length prior\n\t// Should always be length one.\n\t//if (one_edgelen.empty())\n    //    one_edgelen.push_back(0.0);\n\n\tpolytomies.clear();\n\n\tadd_edge_move_proposed\t= false;\n\torig_edgelen\t\t\t= 0.0;\n\torig_lchild\t\t\t\t= NULL;\n\torig_rchild\t\t\t\t= NULL;\n\torig_par\t\t\t\t= NULL;\n\tln_jacobian\t\t\t\t= 0.0;\n\tln_hastings\t\t\t\t= 0.0;\n\tnew_edgelen\t\t\t\t= 0.0;\n\tpolytomy_size\t\t\t= 0;\n\tnum_polytomies\t\t\t= 0;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the value of `ln_hastings', which is the natural log of the Hastings ratio for this move and which is\n|\tcomputed in both BushMove::ProposeAddEdgeMove and BushMove::ProposeDeleteEdgeMove.\n*/\ndouble BushMove::getLnHastingsRatio() const\n\t{\n\treturn ln_hastings;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the value of `ln_jacobian', which is the natural log of the Jacobian for this move and which is computed in\n|\tboth BushMove::ProposeAddEdgeMove and BushMove::ProposeDeleteEdgeMove.\n*/\ndouble BushMove::getLnJacobian() const\n\t{\n\treturn ln_jacobian;\n\t}\n", "meta": {"hexsha": "1dd3a829b0b33572f45853feb4dbc8ffb4226927", "size": 34930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/bush_move.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/bush_move.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/bush_move.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 41.6825775656, "max_line_length": 140, "alphanum_fraction": 0.6152877183, "num_tokens": 9233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.03514484286373754, "lm_q1q2_score": 0.015929816424628037}}
{"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// activate deprecation warning\n#ifdef AIMSDATA_CLASS_NO_DEPREC_WARNING\n#undef AIMSDATA_CLASS_NO_DEPREC_WARNING\n#endif\n\n#include <aims/sparsematrix/sparseMatrix.h>\n#include <aims/sparsematrix/sparseMatrixItemR.h>\n#include <aims/sparsematrix/sparseMatrixItemW.h>\n#include <cartobase/object/object_d.h>\n#include <fstream>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace aims;\nusing namespace carto;\n\n\naims::SparseMatrix::SparseMatrix( int32_t size1, int32_t size2 )\n  : _matrix( size1, size2, 0 ), _header( Object::value( PropertySet() ) )\n{\n}\n\n\naims::SparseMatrix::SparseMatrix( const aims::SparseMatrix& other )\n  : RCObject(), \n    _matrix( other._matrix ), _header( Object::value( PropertySet() ) )\n{\n  *_header = *other.header();\n}\n\n\naims::SparseMatrix::~SparseMatrix()\n{\n}\n\n\n\naims::SparseMatrix& \n    aims::SparseMatrix::operator=( const aims::SparseMatrix& other )\n{\n\n  try\n  {\n\n    _matrix = other._matrix;\n    *_header = *other.header();\n\n    return *this;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string(\"aims::SparseMatrix& \"\n        \"aims::SparseMatrix::operator=( \"\n        \"const aims::SparseMatrix& other )\") + e.what() );\n  }\n\n}\n\nvoid aims::SparseMatrix::reallocate( int32_t size1, int32_t size2 )\n{\n\n  try\n  {\n\n    // do not preservce because not implemented in boost !\n    _matrix.resize( size1, size2, false );\n\n  }\n\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::reallocate( \"\n        \"int32_t size1, int32_t size2 )\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::iterator1 aims::SparseMatrix::begin1()\n{\n\n  try\n  {\n\n    return _matrix.begin1();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::iterator1 \"\n        \"aims::SparseMatrix::begin1()\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::iterator1 aims::SparseMatrix::end1()\n{\n\n  try\n  {\n\n    return _matrix.end1();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::iterator1 \"\n        \"aims::SparseMatrix::end1()\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::const_iterator1 aims::SparseMatrix::begin1() const\n{\n\n  try\n  {\n\n    return _matrix.begin1();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::iterator1 \"\n        \"aims::SparseMatrix::begin1() const\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::const_iterator1 aims::SparseMatrix::end1() const\n{\n\n  try\n  {\n\n    return _matrix.end1();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::const_iterator1 \"\n        \"aims::SparseMatrix::end1() const\" ) + e.what() );\n  }\n\n}\n\naims::SparseMatrix::iterator2 aims::SparseMatrix::begin2()\n{\n\n  try\n  {\n\n    return _matrix.begin2();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::iterator2 \"\n        \"aims::SparseMatrix::begin2()\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::iterator2 aims::SparseMatrix::end2()\n{\n\n  try\n  {\n\n    return _matrix.end2();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::iterator2 \"\n        \"aims::SparseMatrix::end2()\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::const_iterator2 aims::SparseMatrix::begin2() const\n{\n\n  try\n  {\n\n    return _matrix.begin2();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::iterator2 \"\n        \"aims::SparseMatrix::begin2() const\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::const_iterator2 aims::SparseMatrix::end2() const\n{\n\n  try\n  {\n\n    return _matrix.end2();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix::const_iterator2 \"\n        \"aims::SparseMatrix::end2() const\" ) + e.what() );\n  }\n\n}\n\nint32_t aims::SparseMatrix::getSize1() const\n{\n\n  try\n  {\n\n    return ( int32_t )_matrix.size1();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"int32_t \"\n        \"aims::SparseMatrix::getSize1() const\" ) + e.what() );\n  }\n\n}\n\n\nint32_t aims::SparseMatrix::getSize2() const\n{\n\n  try\n  {\n\n    return ( int32_t )_matrix.size2();\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"int32_t \"\n        \"aims::SparseMatrix::getSize2() const\" ) + e.what() );\n  }\n\n}\n\n\nint32_t aims::SparseMatrix::getNonZeroElementCount() const\n{\n\n  try\n  {\n\n#if BOOST_VERSION < 103300\n    boost_sparse_matrix::size_type filled = 0;\n    boost_sparse_matrix::const_iterator2 itv2, etv2;\n    for (boost_sparse_matrix::const_iterator1 itv = _matrix.begin1 (); itv != _matrix.end1 (); ++ itv)\n      for( itv2=itv.begin(), etv2=itv.end(); itv2!=etv2; ++itv2 )\n        ++filled;\n    return filled;\n\n#else\n    return ( int32_t )_matrix.nnz();\n#endif\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"int32_t aims::SparseMatrix::getNonZeroElementCount() \"\n        \"const\" ) + e.what() );\n  }\n\n}\n\n\nbool aims::SparseMatrix::hasElement( int32_t i, int32_t j ) const\n{\n\n  try\n  {\n\n#if BOOST_VERSION < 103300\n    return _matrix.at_element( i, j ) != 0;\n#else\n    return _matrix.find_element( i, j );\n#endif\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"bool \"\n        \"aims::SparseMatrix::hasElement( \"\n        \"int32_t i, int32_t j ) const\" ) + e.what() );\n  }\n\n\n}\n\n\naims::SparseMatrix::const_reference \n    aims::SparseMatrix::operator()( int32_t i, int32_t j ) const\n{\n\n  try\n  {\n\n    return _matrix( i, j );\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"const double& \"\n        \"aims::SparseMatrix::operator()( \"\n        \"int32_t i, int32_t j ) const\" ) +  e.what() );\n  }\n\n}\n\n\naims::SparseMatrix::reference \n    aims::SparseMatrix::operator()( int32_t i, int32_t j )\n{\n\n  try\n  {\n\n    return _matrix( i, j );\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"double& aims::SparseMatrix::operator()( \"\n        \"int32_t i, int32_t j )\" ) + e.what() );\n  }\n\n}\n\n\nbool aims::SparseMatrix::isSquare() const\n{\n\n  try\n  {\n\n    return ( _matrix.size1() == _matrix.size2() );\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"bool \"\n        \"aims::SparseMatrix::isSquare() const\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::setZero()\n{\n\n  try\n  {\n    _matrix.clear();\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::setZero()\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::setIdentity()\n{\n\n  try\n  {\n\n    _matrix.clear();\n\n    int32_t size = getSize1();\n\n    int32_t s = 0;\n    for ( s = 0; s < size; s++ )\n    {\n\n        _matrix( s, s ) = 1.0;\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::setIdentity()\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::setRow( int32_t s1, const std::vector<double>& row )\n{\n\n  try\n  {\n\n    if ( int32_t(row.size()) != getSize2() )\n    {\n\n      throw std::runtime_error( \"incoherent size(s)\" );\n\n    }\n    int32_t s2;\n    for ( s2 = 0; s2 < getSize2(); s2++ )\n    {\n\n      const double & element = row[s2];\n      if( element == 0 )\n        erase_element( s1, s2 );\n      else\n        ( *this )( s1, s2 ) = element;\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::setRow( int32_t s1, \"\n        \"const std::vector<double>& row )\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::setColumn( int32_t s2, const std::vector<double>& column )\n{\n\n  try\n  {\n\n    if ( int32_t(column.size()) != getSize1() )\n    {\n\n      throw std::runtime_error( \"incoherent size(s)\" );\n\n    }\n    int32_t s1;\n    for ( s1 = 0; s1 < getSize1(); s1++ )\n    {\n\n      ( *this )( s1, s2 ) = column[ s1 ];\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::setColumn( \"\n        \"int32_t s2, const std::vector<double>& column )\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::fill( const double& value )\n{\n\n  try\n  {\n\n    int32_t size1 = getSize1();\n    int32_t size2 = getSize2();\n\n    int32_t s1 = 0;\n    int32_t s2 = 0;\n    for ( s1 = 0; s1 < size1; s1++ )\n    {\n\n      for ( s2 = 0; s2 < size2; s2++ )\n      {\n\n        _matrix( s1, s2 ) = value;\n\n      }\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::fill( \"\n        \"const double& value )\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::fill( int32_t offset1,\n                               int32_t offset2,\n                               int32_t size1,\n                               int32_t size2,\n                               const double& value )\n{\n\n  try\n  {\n\n    if ( ( offset1 < 0 ) ||\n           ( offset2 < 0 ) ||\n           ( offset1 + size1 > getSize1() ) ||\n           ( offset2 + size2 > getSize2() ) )\n\n    {\n\n      throw std::runtime_error( \"incompatible offset(s)/size(s)\" );\n\n    }\n    int32_t s1, s2;\n    for ( s1 = 0; s1 < size1; s1++ )\n    {\n\n      for ( s2 = 0; s2 < size2; s2++ )\n      {\n\n        ( *this )( offset1 + s1, offset2 + s2 ) = value;\n\n      }\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void aims::SparseMatrix::fill( \"\n        \"int32_t offset1, \"\n        \"int32_t offset2, \"\n        \"int32_t size1, \"\n        \"int32_t size2, \"\n        \"const double& value )\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::fill( int32_t offset1,\n                               int32_t offset2,\n                               const aims::SparseMatrix& other,\n                               int32_t size1,\n                               int32_t size2 )\n{\n\n  try\n  {\n\n\n    if ( ( size1 < 0 ) || ( size2 < 0 ) )\n    {\n\n      throw std::runtime_error( \"size1 and size2 must be nul or positive\" );\n\n    }\n\n    int32_t targetSize1 = ( size1 ? size1 : other.getSize1() );\n    int32_t targetSize2 = ( size2 ? size2 : other.getSize2() );\n\n    if ( ( offset1 < 0 ) ||\n           ( offset2 < 0 ) ||\n           ( offset1 + targetSize1 > getSize1() ) ||\n           ( offset2 + targetSize2 > getSize2() ) )\n    {\n\n      throw std::runtime_error( \"incompatible offset(s)/other matrix size\" );\n\n    }\n    int32_t s1, s2;\n    for ( s1 = 0; s1 < targetSize1; s1++ )\n    {\n\n      for ( s2 = 0; s2 < targetSize2; s2++ )\n      {\n\n        if ( hasElement( s1, s2 ) )\n        {\n\n          ( *this )( offset1 + s1, offset2 + s2 ) = other( s1, s2 );\n\n        }\n\n      }\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void aims::SparseMatrix::fill( \"\n        \"int32_t offset1, \"\n        \"int32_t offset2, \"\n        \"const aims::SparseMatrix& other, \"\n        \"int32_t size1, \"\n        \"int32_t size2 )\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::setDiagonal( const double& value )\n{\n\n  try\n  {\n\n    _matrix.clear();\n    int32_t s;\n    int32_t maximumS = std::min( getSize1(), getSize2() );\n    for ( s = 0; s < maximumS; s++ )\n    {\n\n      _matrix( s, s ) = value;\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::setDiagonal( \"\n        \"const double& value )\" ) + e.what() );\n  }\n\n}\n\n\nvoid aims::SparseMatrix::transpose()\n{\n\n  try\n  {\n\n    aims::SparseMatrix tmp( *this );\n    reallocate( tmp.getSize2(), tmp.getSize1() );\n\n    for ( int32_t s1 = 0; s1 < getSize1(); s1++ )\n    {\n\n      for ( int32_t s2 = 0; s2 < getSize2(); s2++ )\n      {\n\n        if ( tmp.hasElement( s2, s1 ) )\n        {\n\n          ( *this )( s1, s2 ) = tmp( s2, s1 );\n\n        }\n\n      }\n\n    }\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::transpose()\" ) +  e.what() );\n  }\n\n}\n\n\ndouble aims::SparseMatrix::getTrace() const\n{\n\n  try\n  {\n\n    if ( !isSquare() )\n    {\n\n      throw std::runtime_error( \"not a square matrix\" );\n\n    }\n\n    double trace = 0.0;\n    int32_t s;\n    for ( s = 0; s < getSize1(); s++ )\n    {\n\n      trace += ( *this )( s, s );\n\n    }\n\n    return trace;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"double \"\n        \"aims::SparseMatrix::getTrace() const\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix aims::SparseMatrix::getTransposition() const\n{\n\n  try\n  {\n\n    aims::SparseMatrix matrix( *this );\n    matrix.transpose();\n    return matrix;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"aims::SparseMatrix::getTransposition() const\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix \n    aims::SparseMatrix::getComposition( const aims::SparseMatrix& other ) const\n{\n\n  try\n  {\n\n    if ( getSize2() != other.getSize1() )\n    {\n\n      std::runtime_error( \"the row count for other matrix is not equal to \"\n          \"the column count for this matrix\" );\n    }\n\n    aims::SparseMatrix composition( getSize1(), other.getSize2() );\n\n    for ( int32_t s1 = 0; s1 < composition.getSize1(); s1++ )\n    {\n\n      for ( int32_t s2 = 0; s2 < composition.getSize2(); s2++ )\n      {\n\n        double value = 0.0;\n        bool nonZero = false;\n        for ( int32_t k = 0; k < getSize2(); k++ )\n        {\n\n          if ( this->hasElement( s1, k ) && other.hasElement( k, s2 ) )\n          {\n\n            value += ( *this )( s1, k ) * other( k, s2 );\n            nonZero = true;\n\n          }\n\n        }\n\n        if ( nonZero )\n        {\n\n          composition( s1, s2 ) = value;\n\n        }\n\n      }\n\n    }\n    return composition;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"aims::SparseMatrix::getComposition( \"\n        \"const aims::SparseMatrix& other ) const\" ) + e.what() );\n  }\n\n}\n\n\nstd::vector<double> \n    aims::SparseMatrix::getComposition( const std::vector<double>& other ) const\n{\n\n  try\n  {\n\n    if ( getSize2() != int32_t(other.size()) )\n    {\n\n      std::runtime_error( \"the vector size is not equal to \"\n          \"the column count for this matrix\" );\n    }\n\n    std::vector<double> composition( getSize1() );\n\n    for ( int32_t s = 0; s < ( int32_t )composition.size(); s++ )\n    {\n\n      composition[ s ] = 0.0;\n      for ( int32_t k = 0; k < getSize2(); k++ )\n      {\n\n        composition[ s ] += ( *this )( s, k ) * other[ k ];\n\n      }\n\n    }\n    return composition;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::Vector \"\n        \"aims::SparseMatrix::getComposition( \"\n        \"const aims::Vector& other ) const\" ) + e.what() );\n  }\n\n}\n\n\nstd::vector<double> aims::SparseMatrix::toVector() const\n{\n\n  try\n  {\n\n    std::vector<double> result;\n    if ( getSize1() == 1 )\n    {\n\n      result.resize( getSize2() );\n      for ( int32_t s = 0; s < ( int32_t )result.size(); s++ )\n      {\n\n        result[ s ] = ( *this )( 0, s );\n\n      }\n\n    }\n    else if ( getSize2() == 1 )\n    {\n\n      result.resize( getSize1() );\n      for ( int32_t s = 0; s < ( int32_t )result.size(); s++ )\n      {\n\n        result[ s ] = ( *this )( s, 0 );\n\n      }\n\n    }\n    else\n    {\n\n      std::runtime_error( \"none of the size is equal to 1\" );\n\n    }\n    return result;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"std::vector \"\n        \"aims::SparseMatrix::toVector() const\" ) + e.what() );\n  }\n\n}\n\n\nstd::vector<double> aims::SparseMatrix::getRow( int32_t i ) const\n{\n\n  try\n  {\n\n    std::vector<double> row( getSize2(), 0. );\n    boost_sparse_matrix::const_iterator1\n      ir = _matrix.find1( 0, i, 0 );\n    if( ir != _matrix.end1() && ir.index1() == static_cast<size_t>(i) )\n    {\n      boost_sparse_matrix::const_iterator2\n        ic, ec = ir.end();\n      long n = 0;\n      for( ic=ir.begin(); ic!=ec; ++ic, ++n )\n        row[ic.index2()] = *ic;\n    }\n    return row;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"std::vector \"\n        \"aims::SparseMatrix::getRow( \"\n        \"int32_t i ) const\" ) + e.what() );\n  }\n\n}\n\n\nstd::vector<double> aims::SparseMatrix::getColumn( int32_t j ) const\n{\n\n  try\n  {\n\n    std::vector<double> column( getSize1() );\n    for ( int32_t s = 0; s < getSize1(); s++ )\n    {\n\n      column[ s ] = ( *this )( s, j );\n\n    }\n    return column;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"std::vector \"\n        \"aims::SparseMatrix::getColumn( \"\n        \"int32_t j ) const\" ) + e.what() );\n  }\n\n}\n\n\n// #ifdef SPARSEVECTOR_H\n// til::SparseVector<double> aims::SparseMatrix::getSparseRow( int32_t i ) const\n// {\n// \n//   try\n//   {\n// \n//     til::SparseVector<double> row( getSize2() );\n//     boost_sparse_matrix::const_iterator1\n//       ir = _matrix.find1( 0, i, 0 );\n//     if( ir != _matrix.end1() && ir.index1() == i )\n//     {\n//       boost_sparse_matrix::const_iterator2\n//         ic, ec = ir.end();\n//       long n = 0;\n//       for( ic=ir.begin(); ic!=ec; ++ic, ++n )\n//         row[ic.index2()] = *ic;\n//     }\n//     return row;\n// \n//   }\n//   catch( std::exception & e )\n//   {\n//     throw std::runtime_error( std::string( \"til::SparseVector<double> \"\n//         \"aims::SparseMatrix::getSparseRow( \"\n//         \"int32_t i ) const\" ) + e.what() );\n//   }\n// \n// }\n// \n// \n// til::SparseVector<double> aims::SparseMatrix::getSparseColumn( int32_t j ) const\n// {\n// \n//   try\n//   {\n// \n//     til::SparseVector<double> column( getSize1() );\n//     for ( int32_t s = 0; s < getSize1(); s++ )\n//     {\n// \n//       column[ s ] = ( *this )( s, j );\n// \n//     }\n//     return column;\n// \n//   }\n//   catch( std::exception & e )\n//   {\n//     throw std::runtime_error( std::string( \"til::SparseVector<double> \"\n//         \"aims::SparseMatrix::getSparseColumn( \"\n//         \"int32_t j ) const\" ) + e.what() );\n//   }\n// \n// }\n// #endif\n\n\nvoid aims::SparseMatrix::erase_element( int32_t i, int32_t j )\n\n{\n\n  try\n  {\n\n#if BOOST_VERSION < 103300\n    _matrix.erase( i, j );\n#else\n    _matrix.erase_element( i, j );\n#endif\n\n  }\n  catch (std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::erase_element\"\n        \"( int32_t i, int32_t j )\" ) + e.what() );\n  }\n\n  \n}\n\nvoid aims::SparseMatrix::read( const std::string& filename,\n                               const std::string & openmode, \n                               bool bswap )\n{\n  \n  try\n  {\n    \n    std::ifstream is( filename.c_str() );\n\n    aims::DefaultItemReader<aims::SparseMatrix> \n        defaultItemR;\n    aims::ItemReader<aims::SparseMatrix>*\n        sparseMatrixItemR = defaultItemR.reader( openmode, bswap );\n\n    sparseMatrixItemR->read( is, *this );\n    is.close();\n\n    delete sparseMatrixItemR;\n    \n  }\n  catch (std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::read( const std::string& filename, \"\n        \"const std::string & openmode, \"\n        \"bool bswap )\" ) + e.what() );\n  }\n  \n}\n\n\nvoid aims::SparseMatrix::write( const std::string& filename,\n                                const std::string & openmode, \n                                bool bswap ) const\n{\n  \n  try\n  {\n    \n    std::ofstream os( filename.c_str() );\n\n    aims::DefaultItemWriter<aims::SparseMatrix> \n        defaultItemW;\n    aims::ItemWriter<aims::SparseMatrix>*\n        sparseMatrixItemW = defaultItemW.writer( openmode, bswap );\n\n    sparseMatrixItemW->write( os, *this );\n    os.close();\n\n    delete sparseMatrixItemW;\n    \n  }\n  catch (std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"void \"\n        \"aims::SparseMatrix::write( const std::string& filename, \"\n        \"const std::string & openmode, \"\n        \"bool bswap )\" )+  e.what() );\n  }\n  \n}\n\n\n//\n// unary operators + & -\n//\n\n// + SparseMatrix\naims::SparseMatrix \n    operator + ( const aims::SparseMatrix& thing )\n{\n\n  try\n  {\n\n    return thing;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix  \"\n        \"operator + ( const aims::SparseMatrix& thing )\" ) +  e.what() );\n  }\n\n}\n\n// - SparseMatrix\naims::SparseMatrix \n    aims::operator - ( const aims::SparseMatrix& thing )\n{\n\n  try\n  {\n\n    aims::SparseMatrix result( thing );\n    result *= -1;\n\n    return result;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"operator - ( const aims::SparseMatrix& thing )\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix &\n    aims::SparseMatrix::operator += ( const aims::SparseMatrix& thing )\n{\n\n  try\n  {\n\n    if ( ( thing.getSize1() != getSize1() ) ||\n           ( thing.getSize2() != getSize2() ) )\n    {\n\n      throw std::runtime_error( \"incompatible matrix size(s)\" );\n\n    }\n\n    _matrix += thing._matrix;\n\n    return *this;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"operator + ( const aims::SparseMatrix& thing1, \"\n        \"const aims::SparseMatrix& thing2 )\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix &\n    aims::SparseMatrix::operator -= ( const aims::SparseMatrix& thing )\n{\n\n  try\n  {\n\n    if ( ( thing.getSize1() != getSize1() ) ||\n           ( thing.getSize2() != getSize2() ) )\n    {\n\n      throw std::runtime_error( \"incompatible matrix size(s)\" );\n\n    }\n\n    _matrix -= thing._matrix;\n\n    return *this;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"operator + ( const aims::SparseMatrix& thing1, \"\n        \"const aims::SparseMatrix& thing2 )\" ) + e.what() );\n  }\n\n}\n\n\naims::SparseMatrix &\n    aims::SparseMatrix::operator *= ( double x )\n{\n\n  _matrix *= x;\n\n  return *this;\n}\n\n\naims::SparseMatrix &\n    aims::SparseMatrix::operator /= ( double x )\n{\n\n  _matrix /= x;\n\n  return *this;\n}\n\n\n\n//\n// binary operator +\n//\n\n// SparseMatrix + SparseMatrix\naims::SparseMatrix\n    aims::operator + ( const aims::SparseMatrix& thing1,\n                 const aims::SparseMatrix& thing2 )\n{\n\n  try\n  {\n\n    if ( ( thing1.getSize1() != thing2.getSize1() ) ||\n           ( thing1.getSize2() != thing2.getSize2() ) )\n    {\n\n      throw std::runtime_error( \"incompatible matrix size(s)\" );\n\n    }\n\n    aims::SparseMatrix result( thing1 );\n    result += thing2;\n\n    return result;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"operator + ( const aims::SparseMatrix& thing1, \"\n        \"const aims::SparseMatrix& thing2 )\" ) + e.what() );\n  }\n\n}\n\n//\n// binary operator -\n//\n\n// SparseMatrix - SparseMatrix\naims::SparseMatrix\n    aims::operator - ( const aims::SparseMatrix& thing1,\n                 const aims::SparseMatrix& thing2 )\n{\n\n  try\n  {\n\n    if ( ( thing1.getSize1() != thing2.getSize1() ) ||\n           ( thing2.getSize1() != thing2.getSize2() ) )\n    {\n\n      throw std::runtime_error( \"incompatible matrix size(s)\" );\n\n    }\n\n    aims::SparseMatrix result( thing1 );\n    result -= thing2;\n\n    return result;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"operator - ( const aims::SparseMatrix& thing1, \"\n        \"const aims::SparseMatrix& thing2 )\" ) + e.what() );\n  }\n\n}\n\n//\n// binary operator *\n//\n\n// SparseMatrix * SparseMatrix\naims::SparseMatrix\n    aims::operator * ( const aims::SparseMatrix& thing1,\n                 const aims::SparseMatrix& thing2 )\n{\n\n  try\n  {\n\n    return thing1.getComposition( thing2 );\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"operator * ( const aims::SparseMatrix& thing1, \"\n        \"const aims::SparseMatrix& thing2 )\" ) + e.what() );\n  }\n\n}\n\n// SparseMatrix * std::vector<double>\nstd::vector<double>\n    aims::operator * ( const aims::SparseMatrix& thing1,\n                 const std::vector<double>& thing2 )\n{\n\n  try\n  {\n\n    return thing1.getComposition( thing2 );\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"std::vector<double> \"\n        \"operator * ( const aims::SparseMatrix& thing1, \"\n        \"const std::vector<double>& thing2 )\" ) + e.what() );\n  }\n\n}\n\n// SparseMatrix * double\naims::SparseMatrix\n    aims::operator * ( const aims::SparseMatrix& thing1,\n                 const double& thing2 )\n{\n\n  try\n  {\n\n    aims::SparseMatrix result( thing1 );\n    result *= thing2;\n\n    return result;\n\n  }\n  catch( std::exception & e )\n  {\n    throw std::runtime_error( std::string( \"aims::SparseMatrix \"\n        \"operator * ( const aims::SparseMatrix& thing1, \"\n        \"const double& thing2 )\" ) + e.what() );\n  }\n\n}\n\n//\n// binary operator /\n//\n\n// SparseMatrix / double\naims::SparseMatrix\n    aims::operator / ( const aims::SparseMatrix& thing1,\n                 const double& thing2 )\n{\n\n  try\n  {\n\n    aims::SparseMatrix result( thing1 );\n    result /= thing2;\n\n    return result;\n\n  }\n  catch( std::exception & e )\n  {\n    \n    throw std::runtime_error( \n      std::string( \"aims::SparseMatrix \"\n                   \"operator / ( const aims::SparseMatrix& thing1, \"\n                   \"const double& thing2 ) : \" ) + e.what() );\n  }\n\n}\n\n//\n// standard operator(s)\n//\n\nstd::ostream& std::operator << ( std::ostream& os, \n                                 const aims::SparseMatrix& thing )\n{\n\n  for ( int32_t s1 = 0; s1 < thing.getSize1(); s1++ )\n  {\n\n    for ( int32_t s2 = 0; s2 < thing.getSize2(); s2++ )\n    {\n\n      if ( thing.hasElement( s1, s2 ) )\n      {\n\n        os << thing( s1, s2 ) << \" \";\n\n      }\n      else\n      {\n\n        os << \"- \";\n\n      }\n\n    }\n    if ( s1 != thing.getSize1() - 1 )\n    {\n\n      os << std::endl;\n\n    }\n\n  }\n  return os;\n\n}\n\n\nbool std::operator == ( const aims::SparseMatrix& thing1,\n                        const aims::SparseMatrix& thing2 )\n{\n  if( thing1.getSize1() != thing2.getSize1()\n    || thing1.getSize2() != thing2.getSize2() )\n    return false;\n\n  aims::SparseMatrix::const_iterator1 il1, el1 = thing1.end1(),\n    il2, el2 = thing2.end1();\n  aims::SparseMatrix::const_iterator2 ic1, ec1, ic2, ec2;\n\n  for( il1=thing1.begin1(), il2=thing2.begin1();\n      il1!=el1 && il2!=el2 && il1.index1() == il2.index1(); ++il1, ++il2 )\n  {\n    for( ic1=il1.begin(), ec1=il1.end(), ic2=il2.begin(), ec2=il2.end();\n        ic1!=ec1 && ic2!=ec2 && ic1.index2() == ic2.index2(); ++ic1, ++ic2 )\n      if( *ic1 != *ic2 )\n        return false;\n    if( ic1 != ec1 || ic2 != ec2 )\n      return false;\n  }\n  if( il1 != el1 || il2 != el2 )\n    return false;\n  return true;\n}\n\n\nvoid SparseMatrix::setHeader( Object ph )\n{\n  _header = ph;\n}\n\n\nnamespace carto \n{\n\nINSTANTIATE_GENERIC_OBJECT_TYPE( aims::SparseMatrix )\n\n}\n", "meta": {"hexsha": "4eb7d7bc4444ff1b29615479d14934f4744c9433", "size": 28402, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aimsdata/src/aimsdata/sparsematrix/sparseMatrix.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": "aimsdata/src/aimsdata/sparsematrix/sparseMatrix.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": "aimsdata/src/aimsdata/sparsematrix/sparseMatrix.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": 18.9220519654, "max_line_length": 102, "alphanum_fraction": 0.5624251813, "num_tokens": 8156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593016, "lm_q2_score": 0.03904829356494251, "lm_q1q2_score": 0.015905674183799647}}
{"text": "/// \\file   kelly_bettor.cpp\n///\n/// \\brief\n///\n/// \\authors    maarten\n/// \\date       2020-11-06\n/// \\copyright  Copyright 2017-2020 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#include \"kelly_bettor.hpp\"\n\n#include <utility>\n\n#include <boost/accumulators/statistics/mean.hpp>\n\n#include <esl/data/log.hpp>\nusing economics::finance::securities_lending_contract;\n\nusing namespace esl;\nusing namespace esl::economics;\nusing namespace esl::economics::markets;\n\n\nkelly_bettor::kelly_bettor(const identity<fund> &i, const jurisdiction &j)\n: agent(i)\n, owner<cash>(i)\n, owner<stock>(i)\n, fund(i, j)\n, past_price(100'00, currencies::USD)\n{\n    estimates(0.);\n}\n\ntime_point kelly_bettor::invest(std::shared_ptr<walras::quote_message> message, simulation::time_interval interval, std::seed_seq &seed)\n{\n    if(message->received < interval.lower){\n        return interval.lower;\n    }\n\n    demand.clear();\n    for(auto [p,q]: message->proposed){\n        demand.emplace(p->identifier, 1.0);\n    }\n\n    auto nav_ =  net_asset_value(interval);\n    LOG(trace) << describe() << \" \" << identifier << \" inventory \" <<  inventory << std::endl;\n    double update_value_ = 0.;\n\n    if(interval.lower <= 100){\n        return interval.lower;\n    }\n\n    auto m = this->template create_message<kelly_bettor_ddsf>(\n        message->sender, interval.lower, (*this), message->sender,\n        interval.lower, interval.lower,nav_,demand);\n\n\n    price price_ = price::approximate(100.00, currencies::USD);\n    double dividend_rate = 0.;\n    for(auto [property_, quote_] : message->proposed) {\n\n        price_ = std::get<price>(quote_.type);\n\n        auto i = market_data.dividend_per_share.find(*property_);\n        // it is assumed all assets are quoted with a price\n        if(i != market_data.dividend_per_share.end()) {\n            // in this simplified model, we assume there is one dividend payment per period, and therefore the dividend yield is in USD/day\n\n            auto payment_ = double(i->second);\n            auto shares_outstanding_ = market_data.shares_outstanding.find(property_->identifier)->second;\n            dividend_rate = (payment_ / shares_outstanding_) ;\n            update_value_ = 0.01 * std::min(interval.lower, 100ul) * (\n                                (double(price_) / double(past_price)) - 1 + dividend_rate/ double(price_));\n            past_price = price_;\n        }\n    }\n    m->estimates = estimates;\n    m->time = interval.lower;\n\n    for(auto [p,q]: inventory){\n        auto cast_ = std::dynamic_pointer_cast<stock>(p);\n        if(cast_){\n            if(0 == q.amount){\n                continue;\n            }\n            m->supply.emplace(p->identifier, std::make_tuple(q, quantity(0)));\n        }else{\n            auto cast2_ = std::dynamic_pointer_cast<securities_lending_contract>(p);\n            if(cast2_){\n                if(0 == q.amount){\n                    continue;\n                }\n                if(m->supply.end() != m->supply.find(cast2_->security)){\n                    std::get<1>( m->supply.find(cast2_->security)->second ) = q;\n                }else{\n                    m->supply.emplace(cast2_->security, std::make_tuple(quantity(0), q));\n                }\n            }\n        }\n    }\n\n    for(auto [p,q]: owner<stock>::properties.items){\n\n\n    }\n    for(auto [p,q]: owner<securities_lending_contract>::properties.items){\n\n    }\n\n\n\n    m->past_price = past_price;\n    m->dividend_rate = dividend_rate;\n    estimates(update_value_);\n    return interval.lower;\n}\n\nstd::string kelly_bettor::describe() const\n{\n    return \"kelly bettor\";\n}\n\n///\n///\n///\nkelly_bettor_ddsf::kelly_bettor_ddsf(\n    const identity<agent> &sender,\n    const identity<agent> &recipient,\n    simulation::time_point sent, simulation::time_point received,\n    price net_asset_value,\n    std::map<identity<law::property>, double> variates\n)\n    : differentiable_order_message(sender, recipient, sent, received)\n    , variates(std::move(variates))\n    , net_asset_value(net_asset_value)\n{\n\n}\n\nstd::map<identity<law::property>, esl::variable>\nkelly_bettor_ddsf::excess_demand(\n    const std::map<identity<law::property>,\n        std::tuple<economics::markets::quote, variable>> &quotes)\nconst\n{\n    std::map<esl::identity<property>, esl::variable> result_;\n    auto scale_ = double(net_asset_value) / quotes.size();\n\n    for(auto &[k, v] : quotes) {\n        const auto &[quote_, variable_] = v;\n        const auto quoted_price_ = double(std::get<price>(quote_.type));\n        auto i = variates.find(k);\n        if(variates.end() != i) {\n            auto value_ = i->second;\n            auto j = supply.find(k);\n            if(supply.end() == j){\n                result_.emplace(k,  scale_ * value_ * value_);\n            }else{\n                auto supply_long_  = double(std::get<0>(j->second));\n                auto supply_short_ = double(std::get<1>(j->second));\n\n                double ease_in_ = 0.01 * std::min(time, 100ul);\n                ease_in_ *= ease_in_;\n\n                auto m = boost::accumulators::mean(estimates);\n                m = std::max(-0.5, std::min(0.5, std::pow(1. + ease_in_ * m, 252.)-1));\n\n                double x = quoted_price_ * adept::value(variable_);\n                auto update_value_ = ease_in_ * ((x / double(past_price)) - 1 + dividend_rate/ x);\n\n\n                const_cast<decltype(estimates) &>( estimates)(update_value_);\n\n                auto sigma = std::sqrt(boost::accumulators::variance(estimates));\n                sigma = std::max(0.001, sigma);\n                sigma *= std::sqrt(252);\n\n                // fractional kelly\n                double c = ease_in_;\n                double r = 0.01;  //   annual\n//\n//                std::cout << std::setprecision(6) << \"price=\" << x\n//                          << \" signal \" << signal\n//                          << \" mu \" << mu\n//                          << \" sigma \" << sigma\n//                          << \" d \" << dividend_rate\n//                          << \" t \" << time << std::endl;\n\n                auto lambda_ = 0.9 * 2;\n                result_.emplace(k, scale_ * (lambda_ / (1. + adept::exp( - (c * ((m*time + (ease_in_ * ((quoted_price_ * variable_) / double(past_price) - 1 + dividend_rate/ (quoted_price_ * variable_))))/(time+1) - r) / (sigma*sigma)) )) - lambda_/2 + 0.5)\n                                       - (supply_long_ - supply_short_) * (quoted_price_ * variable_)\n                );\n            }\n        }\n    }\n    return result_;\n}\n", "meta": {"hexsha": "357ac5819735a04f914141fb93209c1c904cbadd", "size": 7326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "strategies/kelly_bettor.cpp", "max_stars_repo_name": "vishalbelsare/market-ecology", "max_stars_repo_head_hexsha": "c486ebd4989bc9ccdce8a78b49c838d8dbdbefc4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-03-22T13:25:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T18:52:02.000Z", "max_issues_repo_path": "strategies/kelly_bettor.cpp", "max_issues_repo_name": "vishalbelsare/market-ecology", "max_issues_repo_head_hexsha": "c486ebd4989bc9ccdce8a78b49c838d8dbdbefc4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "strategies/kelly_bettor.cpp", "max_forks_repo_name": "vishalbelsare/market-ecology", "max_forks_repo_head_hexsha": "c486ebd4989bc9ccdce8a78b49c838d8dbdbefc4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-02T18:42:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T18:52:06.000Z", "avg_line_length": 34.3943661972, "max_line_length": 257, "alphanum_fraction": 0.5746655747, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.03308597969964969, "lm_q1q2_score": 0.01589710778800757}}
{"text": "/*!\n * @file swp_surfvol_primary.cpp\n * @author Matthew Celnik (msc37)\n *\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the SurfVolPrimary class declared in the\n    swp_surfvol_primary.h header file.\n    @brief Implementation of particle described by its volume and surface area.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_primary.h\"\n#include \"swp_surfvol_primary.h\"\n#include \"swp_aggmodel_type.h\"\n#include \"swp_model_factory.h\"\n\n#include <stdexcept>\n#include <boost/random/poisson_distribution.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::AggModels;\n\nusing namespace std;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (protected).\nSurfVolPrimary::SurfVolPrimary(void)\n: m_sphsurf(0.0)\n{\n}\n\n// Initialising constructor.\nSurfVolPrimary::SurfVolPrimary(double time, const Sweep::ParticleModel &model)\n: Primary(time, model), m_sphsurf(0.0)\n{\n}\n\n// Copy constructor.\nSurfVolPrimary::SurfVolPrimary(const SurfVolPrimary &copy) \n{\n    *this = copy;\n}\n\n// Stream-reading constructor.\nSurfVolPrimary::SurfVolPrimary(std::istream &in, const Sweep::ParticleModel &model)\n{\n    Deserialize(in, model);\n}\n\n// Default destructor.\nSurfVolPrimary::~SurfVolPrimary()\n{\n    releaseMem();\n}\n\n\n// OPERATOR OVERLOADS.\n\n// Assignment operator (Primary RHS).\nSurfVolPrimary &SurfVolPrimary::operator=(const Primary &rhs)\n{\n    // Now check the type of the RHS to see if additional data\n    // copying is required.\n    if (rhs.AggID() == Spherical_ID) {\n        Primary::operator=(rhs);\n        // The RHS is a spherical primary, therefore the \n        // surface area is equal to the equiv. sphere\n        // surface.  We must assign this separately because the\n        // copyTo() implementation for a spherical primary is not\n        // aware of this variable.\n        m_sphsurf = rhs.SurfaceArea();\n    } else {\n        // Attempt to cast the primary to a SurfVolPrimary.  This will\n        // throw an exception if the cast fails.\n        operator=(dynamic_cast<const SurfVolPrimary&>(rhs));\n    }\n\n    return *this;\n}\n\n// Assignment operator (SurfVolPrimary RHS).\nSurfVolPrimary &SurfVolPrimary::operator=(const SurfVolPrimary &rhs)\n{\n    // First copy everything for spherical primaries.\n    Primary::operator=(rhs);\n\n    // Now set surface-volume specific variables.\n    m_sphsurf = rhs.m_sphsurf;\n\n    return *this;\n}\n\n\n// AGGREGATION MODEL.\n\n// Returns the aggregation model which this primary describes.\nAggModels::AggModelType SurfVolPrimary::AggID(void) const {return AggModels::SurfVol_ID;}\n\n// BASIC DERIVED PARTICLE PROPERTIES.\n\n// Calculates the derived properties from the unique properties.  This\n// function is broadly similar to the version in the spherical Primary\n// class except that it uses the surface-volume model.  Therefore the\n// surface area is not altered and the collision diameter is calculated\n// using the arithmetic mean function.\n//\n// Mobility diameter:\n// This calculation is based on the work of Rogak et al., 1993 Aer. Sci.\n// Tech. 18:25-47, who give the calculation of dmob in the FM, SF and\n// transition regime.\nvoid SurfVolPrimary::UpdateCache(void)\n{\n    // Store the correct surface area.\n    double s = m_surf;\n\n    // Pretend that the primary is spherical and set the cache\n    // accordingly.\n    Primary::UpdateCache();\n\n    // The surface area is now set to that of a sphere. Set \n    // correct surface area (minimum is spherical surface area).\n    m_sphsurf = m_surf;\n    m_surf = max(s, m_sphsurf);\n\n   \n    // Calculate diameters.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n\n    // Calculate mobility diameter\n    m_dmob = PP_Diameter();\n    if (false) {\n        // SF regime mobility diameter\n        m_dmob *= 0.9 * sqrt(m_pmodel->GetFractDim() / (m_pmodel->GetFractDim() + 2));\n        m_dmob *= pow(PP_Count(), (1.0/m_pmodel->GetFractDim()));\n    } else {\n        // FM regime mobility diameter\n        m_dmob *= sqrt(0.802*(PP_Count()-1) + 1);\n    }\n\n    if (m_dmob < m_diam) m_dmob = m_diam;\n}\n\n// Returns the equivalent spherical particle surface area.\ndouble SurfVolPrimary::SphSurfaceArea(void) const {return m_sphsurf;}\n\n// Returns the number of primary particles if the aggregate is assumed\n// to consist of mono-sized primaries.\nunsigned int SurfVolPrimary::PP_Count(void) const\n{\n    // Note the minimum number of primary particles must be 1.\n    return max(1u, (unsigned int)((m_surf * m_surf * m_surf) / \n                                  (36.0 * PI * m_vol * m_vol)));\n}\n\n// Returns the primary particle diameter if the aggregate is assumed\n// to consist of mono-sized primaries.\ndouble SurfVolPrimary::PP_Diameter(void) const\n{\n    // This should always be <= equiv. sphere diameter.\n    return 6.0 * m_vol / m_surf;\n}\n\n\n// OPERATIONS.\n\n// Adjusts the primary with the given composition and \n// tracker values changes n times.  If the particle cannot be adjust\n// n times, then this function returns the number of times\n// it was adjusted.\nunsigned int SurfVolPrimary::Adjust(const fvector &dcomp, const fvector &dvalues, rng_type &rng,\n                                    unsigned int n)\n{\n    // Store initial surface and volume\n    double surfOld = m_surf;\n    double volOld  = m_vol;\n\n    // Adjust the particle assuming that it is spherical.\n    n = Primary::Adjust(dcomp, dvalues, rng, n);\n\n\n    // Calculate change in volume.\n    double dvol = 0.0;\n    for (unsigned int i=0; i!=dcomp.size(); ++i) {\n        dvol += dcomp[i] * m_pmodel->Components(i)->MolWt() / \n                m_pmodel->Components(i)->Density();\n    }\n    dvol *= (double)n / NA;\n\n    // Calculate change in surface area.\n    double invRadius = 0.0;\n    if (dvol > 0.0) {\n        // Inverse growth radius.\n        invRadius = sqrt(4.0 * PI / surfOld);\n    } else {\n        // Inverse oxidation radius.    \n        invRadius = surfOld / (3.0 * volOld);\n    }\n\n    // Save new surface area.\n    double s = surfOld + (2.0 * dvol * invRadius);\n\n    // Set correct surface area, which was incorrectly set by\n    // Primary::Adjust.\n    m_sphsurf = m_surf;\n    m_surf    = max(s, m_sphsurf);\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return n;\n}\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nSurfVolPrimary &SurfVolPrimary::Coagulate(const Primary &rhs, rng_type &rng)\n\n{\n    // Store the resultant surface area.\n    double s = m_surf + rhs.SurfaceArea();\n\n    // Perform the coagulation.\n    Primary::Coagulate(rhs, rng);\n\n    // The spherical particle Coagulate() routine has set the\n    // surface area incorrectly.  We now replace the surface area\n    // to the correct point-contact value.\n    m_sphsurf = m_surf;\n    m_surf    = max(m_sphsurf, s);\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return *this;\n}\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nSurfVolPrimary &SurfVolPrimary::Fragment(const Primary &rhs, rng_type &rng)\n\n{\n    // Store the resultant surface area.\n    double s = m_surf + rhs.SurfaceArea();\n\n    // Perform the coagulation.\n    Primary::Fragment(rhs, rng);\n\n    // The spherical particle Coagulate() routine has set the\n    // surface area incorrectly.  We now replace the surface area\n    // to the correct point-contact value.\n    m_sphsurf = m_surf;\n    m_surf    = max(m_sphsurf, s);\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return *this;\n}\n\n// This routine sinters the Primary for the given length of\n// time using the provided sintering model.\nvoid SurfVolPrimary::Sinter(double dt, Cell &sys,\n                            const Processes::SinteringModel &model,\n                            rng_type &rng,\n                            double wt)\n{\n    // Perform a first order integration method to sinter\n    // the primary for the given time.\n    \n    // Declare time step variables.\n    double t1=0.0, delt=0.0, tstop=dt;\n    double r=0.0;\n\n    // Define the maximum allowed change in surface\n    // area in one internal time step (10% spherical surface).\n    double dAmax = 0.1 * m_sphsurf;\n\n    // The scale parameter discretises the delta-S when using\n    // the Poisson distribution.  This allows a smoother change\n    // (smaller scale = higher precision).\n    double scale = 0.01;\n\n    // Perform integration loop.\n    while (t1 < tstop) {\n        // Calculate sintering rate.\n        r = model.Rate(m_time+t1, sys, *this);\n\n        if(r > 0) {\n            // Calculate next time-step end point so that the\n            // surface area changes by no more than dAmax.\n            delt = dAmax / max(r, 1.0e-300);\n\n            // Approximate sintering by a poisson process.  Calculate\n            // number of poisson events.\n            double mean;\n            if (tstop > (t1+delt)) {\n                // A sub-step, we have changed surface by dAmax, on average\n                mean = 1.0 / scale;\n            } else {\n                // Step until end.  Calculate degree of sintering explicitly.\n                mean = r * (tstop - t1) / (scale*dAmax);\n            }\n            boost::random::poisson_distribution<unsigned, double> repeatDistribution(mean);\n            const unsigned n = repeatDistribution(rng);\n\n            // Adjust the surface area.\n            if (n > 0) {\n                m_surf -= n * scale * dAmax;\n                // Check that primary is not completely sintered.\n                if (m_surf <= m_sphsurf) {\n                    m_surf = m_sphsurf;\n                    break;\n                }\n            }\n\n            // Set t1 for next time step.\n            t1 += delt;\n        }\n        else {\n            // No sintering is happening.\n            // This may need refining so that a step in which nothing is happening\n            // cannot be too long.\n            break;\n        }\n    }\n}\n\n\n// READ/WRITE/COPY.\n\n// Returns a copy of the model data.\nSurfVolPrimary *const SurfVolPrimary::Clone(void) const\n{\n    return new SurfVolPrimary(*this);\n}\n\n// Writes the object to a binary stream.\nvoid SurfVolPrimary::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Output base class.\n        Primary::Serialize(out);\n\n        // Write spherical surface area.\n        double val = (double)m_sphsurf;\n        out.write((char*)&val, sizeof(val));\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, SurfVolPrimary::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid SurfVolPrimary::Deserialize(std::istream &in, const Sweep::ParticleModel &model)\n{\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        double val = 0.0;\n\n        switch (version) {\n            case 0:\n                // Read base class.\n                Primary::Deserialize(in, model);\n\n                // Read spherical surface area.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_sphsurf = (double)val;\n\n                break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, SurfVolPrimary::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, SurfVolPrimary::Deserialize).\");\n    }\n}\n", "meta": {"hexsha": "fd0466b7ec06adfffde340e9c6bfac037a80d3da", "size": 13778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_surfvol_primary.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_surfvol_primary.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_surfvol_primary.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 31.0315315315, "max_line_length": 96, "alphanum_fraction": 0.6363042532, "num_tokens": 3357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054584, "lm_q2_score": 0.04208772686428807, "lm_q1q2_score": 0.015889829138072954}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"bempp/common/config_ahmed.hpp\"\n#include \"bempp/common/config_trilinos.hpp\"\n\n#include \"aca_global_assembler.hpp\"\n\n#include \"assembly_options.hpp\"\n#include \"block_coalescer.hpp\"\n#include \"cluster_construction_helper.hpp\"\n#include \"context.hpp\"\n#include \"evaluation_options.hpp\"\n#include \"index_permutation.hpp\"\n#include \"discrete_boundary_operator_composition.hpp\"\n#include \"discrete_sparse_boundary_operator.hpp\"\n\n#include \"../common/armadillo_fwd.hpp\"\n#include \"../common/auto_timer.hpp\"\n#include \"../common/boost_shared_array_fwd.hpp\"\n#include \"../common/chunk_statistics.hpp\"\n#include \"../common/to_string.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/local_assembler_for_integral_operators.hpp\"\n#include \"../fiber/local_assembler_for_potential_operators.hpp\"\n#include \"../fiber/serial_blas_region.hpp\"\n#include \"../fiber/scalar_traits.hpp\"\n#include \"../space/space.hpp\"\n\n#include <stdexcept>\n#include <fstream>\n#include <iostream>\n\n#include <boost/type_traits/is_complex.hpp>\n\n#include <tbb/atomic.h>\n#include <tbb/parallel_for.h>\n#include <tbb/task_scheduler_init.h>\n#include <tbb/concurrent_queue.h>\n\n#ifdef WITH_AHMED\n#include \"ahmed_aux.hpp\"\n\n#ifdef __INTEL_COMPILER\n#pragma warning(disable : 381)\n#endif\n\n#include <apprx.h>\n\n#ifdef __INTEL_COMPILER\n#pragma warning(default : 381)\n#endif\n\n#include \"discrete_aca_boundary_operator.hpp\"\n#include \"modified_aca.hpp\"\n#include \"potential_operator_aca_assembly_helper.hpp\"\n#include \"scattered_range.hpp\"\n#include \"weak_form_aca_assembly_helper.hpp\"\n#endif\n\n// This is a workaround of the problem of the abs() function being declared\n// both in Epetra and in AHMED. It relies of the implementation detail (!) that\n// in Epetra the declaration of abs is put between #ifndef __IBMCPP__ ...\n// #endif. So it may well break in future versions of Trilinos. The ideal\n// solution would be for AHMED to use namespaces.\n\n// Note: this particular instance of this kludge could be removed --\n// we could move permuteEpetraMatrix() to another file\n#ifndef __IBMCPP__\n#define __IBMCPP__\n#include <Epetra_CrsMatrix.h>\n#include <EpetraExt_MatrixMatrix.h>\n#undef __IBMCPP__\n#else\n#include <Epetra_CrsMatrix.h>\n#include <EpetraExt_MatrixMatrix.h>\n#endif\n\n// #define DUMP_DENSE_BLOCKS // if defined, contents and DOF lists of blocks\n// stored as dense matrices will be printed to the\n// screen\n\nnamespace Bempp {\n\n// Body of parallel loop\nnamespace {\n\n#ifdef WITH_AHMED\ntemplate <typename BasisFunctionType, typename ResultType,\n          typename AcaAssemblyHelper>\nclass AcaAssemblerLoopBody {\n  typedef typename Fiber::ScalarTraits<ResultType>::RealType CoordinateType;\n  typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n  typedef bbxbemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n  typedef mblock<typename AhmedTypeTraits<ResultType>::Type> AhmedMblock;\n\npublic:\n  typedef tbb::concurrent_queue<size_t> LeafClusterIndexQueue;\n\n  AcaAssemblerLoopBody(AcaAssemblyHelper *helper,\n                       AcaAssemblyHelper *admissibleHelper,\n                       AhmedLeafClusterArray &leafClusters,\n                       AhmedLeafClusterArray &localLeafClusters,\n                       LeafClusterIndexQueue &leafClusterIndexQueue,\n                       boost::shared_array<AhmedMblock *> blocks,\n                       boost::shared_array<AhmedMblock *> flatLocalBlocks,\n                       BlockCoalescer<ResultType> *coalescer,\n                       const AcaOptions &options, tbb::atomic<size_t> &done,\n                       bool verbose, bool symmetric,\n                       std::vector<ChunkStatistics> &stats)\n      : m_helper(helper), m_admissibleHelper(admissibleHelper),\n        m_leafClusters(leafClusters), m_localLeafClusters(localLeafClusters),\n        m_leafClusterIndexQueue(leafClusterIndexQueue), m_blocks(blocks),\n        m_flatLocalBlocks(flatLocalBlocks), m_coalescer(coalescer),\n        m_options(options), m_done(done), m_verbose(verbose),\n        m_symmetric(symmetric), m_stats(stats) {}\n\n  template <typename Range> void operator()(const Range &r) const {\n    const char *TEXT = \"Approximating ... \";\n    for (typename Range::const_iterator i = r.begin(); i != r.end(); ++i) {\n      size_t leafClusterIndex = 0;\n      if (!m_leafClusterIndexQueue.try_pop(leafClusterIndex)) {\n        std::cerr << \"AcaWeakFormAssemblerLoopBody::operator(): \"\n                     \"Warning: try_pop failed; this shouldn't happen!\"\n                  << std::endl;\n        continue;\n      }\n      m_stats[leafClusterIndex].valid = true;\n      m_stats[leafClusterIndex].chunkStart = r.begin();\n      m_stats[leafClusterIndex].chunkSize = r.size();\n      m_stats[leafClusterIndex].startTime = tbb::tick_count::now();\n\n      AhmedBemBlcluster *cluster =\n          dynamic_cast<AhmedBemBlcluster *>(m_leafClusters[leafClusterIndex]);\n      AhmedBemBlcluster *localCluster = dynamic_cast<AhmedBemBlcluster *>(\n          m_localLeafClusters[leafClusterIndex]);\n      bool globalAssembly = m_options.mode != AcaOptions::HYBRID_ASSEMBLY ||\n                            !localCluster->isadm();\n      AcaAssemblyHelper *helper =\n          globalAssembly ? m_helper : m_admissibleHelper;\n      AhmedMblock **blocks =\n          globalAssembly ? m_blocks.get() : m_flatLocalBlocks.get();\n      if (!globalAssembly)\n        cluster = localCluster;\n      if (m_symmetric)\n        apprx_sym(*helper, blocks[cluster->getidx()], cluster, m_options.eps,\n                  m_options.maximumRank, true /* complex_sym */);\n      else {\n        if (m_options.useAhmedAca)\n          apprx_unsym(*helper, blocks[cluster->getidx()], cluster,\n                      m_options.eps, m_options.maximumRank);\n        else\n          apprx_unsym_shooting(*helper, blocks[cluster->getidx()], cluster,\n                               m_options.eps, m_options.maximumRank);\n      }\n      if (m_leafClusters[leafClusterIndex]->isadm() &&\n          !blocks[cluster->getidx()]->isLrM()) {\n        // // Show clusters for which ACA failed\n        //                std::cout << \"global assembly: \" << globalAssembly <<\n        // \"\\n\";\n        //                typedef ExtendedBemCluster<AhmedDofType>\n        // AhmedBemCluster;\n        //                if (globalAssembly) {\n        //                    std::cout << \"Global cluster 1:\\n\";\n        //                    dynamic_cast<AhmedBemCluster&>(\n        //                                *cluster->getcl1()).printBboxes();\n        //                    std::cout << \"Global cluster 2:\\n\";\n        //                    dynamic_cast<AhmedBemCluster&>(\n        //                                *cluster->getcl2()).printBboxes();\n        //                } else {\n        //                    std::cout << \"Local cluster 1:\\n\";\n        //                    dynamic_cast<AhmedBemCluster&>(\n        //                                *localCluster->getcl1()).printBboxes();\n        //                    std::cout << \"Local cluster 2:\\n\";\n        //                    dynamic_cast<AhmedBemCluster&>(\n        //                                *localCluster->getcl2()).printBboxes();\n        //                }\n      }\n      if (!globalAssembly)\n        m_coalescer->coalesceBlock(cluster->getidx());\n      m_stats[leafClusterIndex].endTime = tbb::tick_count::now();\n      // TODO: recompress\n      const int HASH_COUNT = 20;\n      if (m_verbose)\n        progressbar(std::cout, TEXT, (++m_done) - 1, m_leafClusters.size(),\n                    HASH_COUNT, true);\n    }\n  }\n\nprivate:\n  AcaAssemblyHelper *m_helper;\n  AcaAssemblyHelper *m_admissibleHelper;\n  AhmedLeafClusterArray &m_leafClusters;\n  AhmedLeafClusterArray &m_localLeafClusters;\n  boost::shared_array<AhmedMblock *> m_blocks;\n  boost::shared_array<AhmedMblock *> m_flatLocalBlocks;\n  BlockCoalescer<ResultType> *m_coalescer;\n  const AcaOptions &m_options;\n  tbb::atomic<size_t> &m_done;\n  bool m_verbose;\n  LeafClusterIndexQueue &m_leafClusterIndexQueue;\n  bool m_symmetric;\n  std::vector<ChunkStatistics> &m_stats;\n};\n\nvoid reallyGetClusterIds(const cluster &clusterTree,\n                         const std::vector<unsigned int> &p2oDofs,\n                         std::vector<unsigned int> &clusterIds,\n                         unsigned int &id) {\n  if (clusterTree.isleaf())\n    for (unsigned int nDof = clusterTree.getnbeg();\n         nDof < clusterTree.getnend(); ++nDof)\n      clusterIds[p2oDofs[nDof]] = id;\n  else\n    for (unsigned int nSon = 0; nSon < clusterTree.getns(); ++nSon)\n      reallyGetClusterIds(*clusterTree.getson(nSon), p2oDofs, clusterIds, ++id);\n}\n\nvoid getClusterIds(const cluster &clusterTree,\n                   const std::vector<unsigned int> &p2oDofs,\n                   std::vector<unsigned int> &clusterIds) {\n  clusterIds.resize(p2oDofs.size());\n  unsigned int id = 0;\n  reallyGetClusterIds(clusterTree, p2oDofs, clusterIds, id);\n}\n\ntemplate <typename T>\nvoid save_arma_matrix(const arma::Mat<T> &a, const std::string &fname) {\n  std::ofstream out;\n  out.precision(17);\n  out.open(fname.c_str());\n  arma::diskio::save_raw_ascii(a, out);\n  out.close();\n}\ntemplate <typename T>\nvoid save_arma_matrix(const arma::Mat<std::complex<T>> &a,\n                      const std::string &fname) {\n  std::ofstream out;\n  out.precision(17);\n  out.open((fname + \"-real.txt\").c_str());\n  arma::Mat<T> component = arma::real(a);\n  arma::diskio::save_raw_ascii(component, out);\n  out.close();\n  out.open((fname + \"-imag.txt\").c_str());\n  component = arma::imag(a);\n  arma::diskio::save_raw_ascii(component, out);\n  out.close();\n}\n\ntemplate <typename ValueType>\nvoid dumpDenseBlocks(\n    typename DiscreteAcaBoundaryOperator<ValueType>::AhmedBemBlcluster *\n        clusterTree,\n    typename DiscreteAcaBoundaryOperator<ValueType>::AhmedMblockArray &blocks,\n    const std::vector<unsigned int> &p2oRows,\n    const std::vector<unsigned int> &p2oCols,\n    const std::vector<\n        Point3D<typename Fiber::ScalarTraits<ValueType>::RealType>> &rowDofs,\n    const std::vector<\n        Point3D<typename Fiber::ScalarTraits<ValueType>::RealType>> &colDofs,\n    int singleClusterIndex = -1) {\n  if (!clusterTree)\n    return;\n  typedef typename Fiber::ScalarTraits<ValueType>::RealType CoordinateType;\n  typedef DiscreteAcaBoundaryOperator<ValueType> AcaOp;\n  typedef typename AcaOp::AhmedDofType AhmedDofType;\n  typedef typename AcaOp::AhmedMblock AhmedMblock;\n  typedef bbxbemcluster<AhmedDofType> Cluster;\n  if (clusterTree->isleaf()) {\n    unsigned int idx = clusterTree->getidx();\n    if ((singleClusterIndex < 0 && clusterTree->isGeM(blocks.get()) &&\n         clusterTree->isadm()) ||\n        idx == singleClusterIndex) {\n      std::cout << \"Dense block; \" << clusterTree->getb1() << \" \"\n                << clusterTree->getb2() << \" \" << clusterTree->getn1() << \" \"\n                << clusterTree->getn2() << \"\\n\";\n      // if (clusterTree->getn1() < 500 || clusterTree->getn2() < 500)\n      //     return;\n      Cluster *clRow = clusterTree->getcl1();\n      assert(clRow);\n      std::cout << \"Row center of mass: (\" << clRow->getcom(0) << \", \"\n                << clRow->getcom(1) << \", \" << clRow->getcom(2) << \")\\n\";\n      std::cout << \"Row icm: \" << clRow->geticom() - clusterTree->getb1()\n                << std::endl;\n      for (unsigned int nDof = clRow->getnbeg(); nDof < clRow->getnend();\n           ++nDof) {\n        assert(nDof < p2oRows.size());\n        assert(p2oRows[nDof] < rowDofs.size());\n        const Point3D<CoordinateType> dofPos = rowDofs[p2oRows[nDof]];\n        std::cout << \"  Row dof #\" << p2oRows[nDof] << \" at \" << dofPos.x\n                  << \", \" << dofPos.y << \", \" << dofPos.z << \"\\n\";\n      }\n      Cluster *clCol = clusterTree->getcl2();\n      assert(clCol);\n      std::cout << \"Col center of mass: (\" << clCol->getcom(0) << \", \"\n                << clCol->getcom(1) << \", \" << clCol->getcom(2) << \")\\n\";\n      std::cout << \"Column icm: \" << clCol->geticom() - clusterTree->getb2()\n                << std::endl;\n      for (unsigned int nDof = clCol->getnbeg(); nDof < clCol->getnend();\n           ++nDof) {\n        assert(nDof < p2oCols.size());\n        assert(p2oCols[nDof] < colDofs.size());\n        const Point3D<CoordinateType> dofPos = colDofs[p2oCols[nDof]];\n        std::cout << \"  Col dof #\" << p2oCols[nDof] << \" at \" << dofPos.x\n                  << \", \" << dofPos.y << \", \" << dofPos.z << \"\\n\";\n      }\n      //            AhmedMblock* block = blocks[idx];\n      //            arma::Mat<ValueType> ablock(clusterTree->getn1(),\n      //                                        clusterTree->getn2());\n      //            for (size_t i = 0; i < block->nvals(); ++i)\n      //                ablock[i] = block->getdata()[i];\n      //            save_arma_matrix(ablock, \"block-\" + toString(idx) + \".txt\");\n    }\n  } else\n    for (unsigned int nRowSon = 0; nRowSon < clusterTree->getnrs(); ++nRowSon)\n      for (unsigned int nColSon = 0; nColSon < clusterTree->getncs(); ++nColSon)\n        dumpDenseBlocks<ValueType>(\n            dynamic_cast<typename AcaOp::AhmedBemBlcluster *>(\n                clusterTree->getson(nRowSon, nColSon)),\n            blocks, p2oRows, p2oCols, rowDofs, colDofs, singleClusterIndex);\n}\n\nshared_ptr<const Epetra_CrsMatrix>\npermuteEpetraCrsMatrix(const Epetra_CrsMatrix &mat,\n                       const IndexPermutation &p2oCols,\n                       const IndexPermutation &o2pRows) {\n  shared_ptr<const Epetra_CrsMatrix> p2oColsMat = p2oCols.permutationMatrix();\n  shared_ptr<const Epetra_CrsMatrix> o2pRowsMat = o2pRows.permutationMatrix();\n\n  shared_ptr<Epetra_CrsMatrix> tmp(\n      new Epetra_CrsMatrix(Copy, mat.RowMap(), p2oColsMat->ColMap(),\n                           3 /* three entries per row  -- just a guess */));\n  EpetraExt::MatrixMatrix::Multiply(mat, false, *p2oColsMat, false, *tmp);\n  shared_ptr<Epetra_CrsMatrix> result(\n      new Epetra_CrsMatrix(Copy, o2pRowsMat->RowMap(), tmp->ColMap(),\n                           3 /* three entries per row  -- just a guess */));\n  EpetraExt::MatrixMatrix::Multiply(*o2pRowsMat, false, *tmp, false, *result);\n\n  return result;\n}\n\n// Reorder elements of array leafCluster so that for each i\n// leafClusters[i]->getidx() == refLeafClusters[i]->getidx()\nvoid reorderIdentically(AhmedLeafClusterArray &leafClusters,\n                        const AhmedLeafClusterArray &refLeafClusters) {\n  const size_t size = leafClusters.size();\n  if (refLeafClusters.size() != size)\n    throw std::invalid_argument(\"reorderIdentically(): \"\n                                \"arrays must have the same size\");\n  std::vector<blcluster *> idx2pblcluster(size);\n  for (size_t i = 0; i < size; ++i) {\n    unsigned idx = leafClusters[i]->getidx();\n    if (idx >= size)\n      throw std::invalid_argument(\"reorderIdentically(): \"\n                                  \"invalid cluster index encountered\");\n    idx2pblcluster[leafClusters[i]->getidx()] = leafClusters[i];\n  }\n  for (size_t i = 0; i < size; ++i)\n    leafClusters[i] = idx2pblcluster[refLeafClusters[i]->getidx()];\n  for (size_t i = 0; i < size; ++i)\n    assert(leafClusters[i]->getidx() == refLeafClusters[i]->getidx());\n}\n\ntemplate <typename AcaAssemblyHelper, typename BasisFunctionType,\n          typename ResultType>\nstd::unique_ptr<DiscreteAcaBoundaryOperator<ResultType>> assembleAcaOperator(\n    AcaAssemblyHelper *helper, AcaAssemblyHelper *admissibleHelper,\n    const shared_ptr<typename DiscreteAcaBoundaryOperator<\n        ResultType>::AhmedBemBlcluster> &blclusterTree,\n    const shared_ptr<typename DiscreteAcaBoundaryOperator<\n        ResultType>::AhmedBemBlcluster> &localBlclusterTree,\n    const ParallelizationOptions &parallelOptions, const AcaOptions &acaOptions,\n    bool verbosityAtLeastDefault, bool verbosityAtLeastHigh, bool symmetric,\n    const shared_ptr<IndexPermutation> &test_o2pPermutation,\n    const shared_ptr<IndexPermutation> &trial_o2pPermutation,\n    const shared_ptr<const Epetra_CrsMatrix> &permutedTestGlobalToLocalMap,\n    const shared_ptr<const Epetra_CrsMatrix> &permutedTrialGlobalToLocalMap\n#ifdef DUMP_DENSE_BLOCKS\n    ,\n    const shared_ptr<IndexPermutation> &test_p2oPermutation,\n    const shared_ptr<IndexPermutation> &trial_p2oPermutation,\n    const std::vector<Point3D<\n        typename Fiber::ScalarTraits<ResultType>::RealType>> &testDofCenters,\n    const std::vector<Point3D<\n        typename Fiber::ScalarTraits<ResultType>::RealType>> &trialDofCenters\n#endif // DUMP_DENSE_BLOCKS\n    ) {\n  const bool indexWithGlobalDofs =\n      acaOptions.mode != AcaOptions::HYBRID_ASSEMBLY;\n\n  typedef mblock<typename AhmedTypeTraits<ResultType>::Type> AhmedMblock;\n  boost::shared_array<AhmedMblock *> blocks =\n      allocateAhmedMblockArray<ResultType>(blclusterTree.get());\n  boost::shared_array<AhmedMblock *> decomposedBlocks;\n  if (!indexWithGlobalDofs)\n    decomposedBlocks =\n        allocateAhmedMblockArray<ResultType>(localBlclusterTree.get());\n\n  const size_t testDofCount = test_o2pPermutation->size();\n  const size_t trialDofCount = trial_o2pPermutation->size();\n\n  AhmedLeafClusterArray leafClusters(blclusterTree.get());\n  leafClusters.sortAccordingToClusterSize();\n  if (acaOptions.firstClusterIndex >= 0)\n    leafClusters.startWithClusterOfIndex(acaOptions.firstClusterIndex);\n  const size_t leafClusterCount = leafClusters.size();\n\n  AhmedLeafClusterArray localLeafClusters(localBlclusterTree.get());\n  reorderIdentically(localLeafClusters, leafClusters);\n\n  int maxThreadCount = 1;\n  if (!parallelOptions.isOpenClEnabled()) {\n    if (parallelOptions.maxThreadCount() == ParallelizationOptions::AUTO)\n      maxThreadCount = tbb::task_scheduler_init::automatic;\n    else\n      maxThreadCount = parallelOptions.maxThreadCount();\n  }\n  tbb::task_scheduler_init scheduler(maxThreadCount);\n  tbb::atomic<size_t> done;\n  done = 0;\n\n#ifdef DUMP_DENSE_BLOCKS\n  if (acaOptions.firstClusterIndex >= 0)\n    dumpDenseBlocks<ResultType>(\n        bemBlclusterTree.get(), blocks, test_p2oPermutation->permutedIndices(),\n        trial_p2oPermutation->permutedIndices(), testDofCenters,\n        trialDofCenters, acaOptions.firstClusterIndex);\n#endif\n\n  std::vector<ChunkStatistics> chunkStats(leafClusterCount);\n\n  typedef AcaAssemblerLoopBody<BasisFunctionType, ResultType, AcaAssemblyHelper>\n  Body;\n  typename Body::LeafClusterIndexQueue leafClusterIndexQueue;\n  for (size_t i = 0; i < leafClusterCount; ++i)\n    leafClusterIndexQueue.push(i);\n\n  std::unique_ptr<BlockCoalescer<ResultType>> coalescer;\n  if (!indexWithGlobalDofs)\n    coalescer.reset(new BlockCoalescer<ResultType>(\n        blclusterTree.get(), localBlclusterTree.get(),\n        permutedTestGlobalToLocalMap, permutedTrialGlobalToLocalMap, blocks,\n        decomposedBlocks, acaOptions));\n  if (verbosityAtLeastDefault)\n    std::cout << \"About to start the ACA assembly loop\" << std::endl;\n  tbb::tick_count loopStart = tbb::tick_count::now();\n  {\n    Fiber::SerialBlasRegion region; // if possible, ensure that BLAS is\n                                    // single-threaded\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, leafClusterCount),\n                      Body(helper, admissibleHelper, leafClusters,\n                           localLeafClusters, leafClusterIndexQueue, blocks,\n                           decomposedBlocks, coalescer.get(), acaOptions, done,\n                           verbosityAtLeastDefault, symmetric, chunkStats));\n  }\n  tbb::tick_count loopEnd = tbb::tick_count::now();\n  if (verbosityAtLeastDefault) {\n    std::cout << \"\\n\"; // the progress bar doesn't print the final \\n\n    std::cout << \"ACA loop took \" << (loopEnd - loopStart).seconds() << \" s\"\n              << std::endl;\n  }\n\n  // TODO: parallelise!\n  if (acaOptions.recompress) {\n    if (verbosityAtLeastDefault)\n      std::cout << \"About to start ACA agglomeration\" << std::endl;\n    agglH(blclusterTree.get(), blocks.get(), acaOptions.eps,\n          acaOptions.maximumRank);\n    if (verbosityAtLeastDefault)\n      std::cout << \"Agglomeration finished\" << std::endl;\n  }\n\n  // // Dump timing data of individual chunks\n  //    std::cout << \"\\nChunks:\\n\";\n  //    for (int i = 0; i < leafClusterCount; ++i)\n  //        if (chunkStats[i].valid) {\n  //            int blockIndex = leafClusters[i]->getidx();\n  //            std::cout << chunkStats[i].chunkStart << \"\\t\"\n  //                      << chunkStats[i].chunkSize << \"\\t\"\n  //                      << (chunkStats[i].startTime - loopStart).seconds() <<\n  // \"\\t\"\n  //                      << (chunkStats[i].endTime - loopStart).seconds() <<\n  // \"\\t\"\n  //                      << (chunkStats[i].endTime -\n  // chunkStats[i].startTime).seconds() << \"\\t\"\n  //                      << blocks[blockIndex]->getn1() << \"\\t\"\n  //                      << blocks[blockIndex]->getn2() << \"\\t\"\n  //                      << blocks[blockIndex]->islwr() << \"\\t\"\n  //                      << (blocks[blockIndex]->islwr() ?\n  // blocks[blockIndex]->rank() : 0) << \"\\n\";\n  //        }\n\n  if (verbosityAtLeastDefault) {\n#ifdef CHECK_ACA_ERROR // a define from include/AHMED/apprx.h\n    std::cout << \"ACA finished. Max error: \" << ACA_error_max << std::endl;\n#endif\n    size_t totalEntryCount = testDofCount * trialDofCount;\n    size_t origMemory = sizeof(ResultType) * totalEntryCount;\n    size_t ahmedMemory = sizeH(blclusterTree.get(), blocks.get());\n    int maximumRank = Hmax_rank(blclusterTree.get(), blocks.get());\n    size_t accessedEntryCount = helper->accessedEntryCount();\n    double accessedFraction = double(accessedEntryCount) / totalEntryCount;\n    std::cout << \"\\nNeeded storage: \" << ahmedMemory / 1024. / 1024. << \" MB.\\n\"\n              << \"Without approximation: \" << origMemory / 1024. / 1024.\n              << \" MB.\\n\"\n              << \"Compressed to \" << (100. * ahmedMemory) / origMemory << \"%.\\n\"\n              << \"Maximum rank: \" << maximumRank << \".\\n\";\n    // We only display this information in global and local ACA modes;\n    // in hybrid modes the percentage is not really well defined,\n    // since some blocks are accessed using global indexing, and others\n    // using local indexing\n    if (indexWithGlobalDofs)\n      std::cout << \"Accessed \" << 100. * accessedFraction\n                << \"% matrix entries.\\n\";\n\n    tbb::tick_count::interval_t localAdmTime, globalAdmTime, inadmTime;\n    for (size_t i = 0; i < leafClusterCount; ++i)\n      if (localLeafClusters[i]->isadm())\n        localAdmTime += chunkStats[i].endTime - chunkStats[i].startTime;\n      else if (leafClusters[i]->isadm())\n        globalAdmTime += chunkStats[i].endTime - chunkStats[i].startTime;\n      else\n        inadmTime += chunkStats[i].endTime - chunkStats[i].startTime;\n\n    if (verbosityAtLeastHigh) {\n      std::cout << \"CPU time spent on assembly of admissible local blocks: \"\n                << localAdmTime.seconds() << \" s\\n\";\n      std::cout << \"CPU time spent on assembly of admissible global blocks: \"\n                << globalAdmTime.seconds() << \" s\\n\";\n      std::cout << \"CPU time spent on assembly of inadmissible blocks: \"\n                << inadmTime.seconds() << \"\\n\";\n    }\n    std::cout << std::endl;\n  }\n\n  if (acaOptions.outputPostscript) {\n    if (verbosityAtLeastDefault)\n      std::cout << \"Writing matrix partition ...\" << std::flush;\n    std::ofstream os(acaOptions.outputFname.c_str());\n    if (symmetric)\n      // psoutputHeH() seems to work also for symmetric matrices\n      psoutputHeH(os, blclusterTree.get(), trialDofCount, blocks.get());\n    else\n      psoutputGeH(os, blclusterTree.get(),\n                  std::max(testDofCount, trialDofCount), blocks.get());\n    os.close();\n    if (verbosityAtLeastDefault)\n      std::cout << \" done.\" << std::endl;\n  }\n\n  int outSymmetry = NO_SYMMETRY;\n  if (symmetric) {\n    outSymmetry = SYMMETRIC;\n    if (!boost::is_complex<ResultType>())\n      outSymmetry |= HERMITIAN;\n  }\n  typedef DiscreteAcaBoundaryOperator<ResultType> DiscreteAcaLinOp;\n  std::unique_ptr<DiscreteAcaLinOp> acaOp(new DiscreteAcaLinOp(\n      testDofCount, trialDofCount, acaOptions.eps, acaOptions.maximumRank,\n      outSymmetry, blclusterTree, blocks, *trial_o2pPermutation, // domain\n      *test_o2pPermutation,                                      // range\n      parallelOptions));\n  return acaOp;\n}\n\n#endif\n\n} // namespace\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::unique_ptr<DiscreteBoundaryOperator<ResultType>>\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n    const Space<BasisFunctionType> &testSpace,\n    const Space<BasisFunctionType> &trialSpace,\n    const std::vector<LocalAssemblerForIntegralOperators *> &localAssemblers,\n    const std::vector<LocalAssemblerForIntegralOperators *> &\n        localAssemblersForAdmissibleBlocks,\n    const std::vector<const DiscreteBndOp *> &sparseTermsToAdd,\n    const std::vector<ResultType> &denseTermMultipliers,\n    const std::vector<ResultType> &sparseTermMultipliers,\n    const Context<BasisFunctionType, ResultType> &context, int symmetry) {\n#ifdef WITH_AHMED\n  typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n  typedef ExtendedBemCluster<AhmedDofType> AhmedBemCluster;\n  typedef bbxbemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n  typedef DiscreteAcaBoundaryOperator<ResultType> DiscreteAcaLinOp;\n\n  const AssemblyOptions &options = context.assemblyOptions();\n  const AcaOptions &acaOptions = options.acaOptions();\n  const bool indexWithGlobalDofs =\n      acaOptions.mode != AcaOptions::HYBRID_ASSEMBLY;\n  const bool verbosityAtLeastDefault =\n      (options.verbosityLevel() >= VerbosityLevel::DEFAULT);\n  const bool verbosityAtLeastHigh =\n      (options.verbosityLevel() >= VerbosityLevel::HIGH);\n\n  // Currently we don't support Hermitian ACA operators. This is because we\n  // don't have the means to really test them -- we would need complex-valued\n  // basis functions for that. (Assembly of such a matrix would be very easy\n  // -- just change complex_sym from true to false in the call to apprx_sym()\n  // in AcaWeakFormAssemblerLoopBody::operator() -- but operations on\n  // symmetric/Hermitian matrices are not always trivial and we do need to be\n  // able to test them properly.)\n  bool symmetric = symmetry & SYMMETRIC;\n  if (symmetry & HERMITIAN && !(symmetry & SYMMETRIC) &&\n      verbosityAtLeastDefault)\n    std::cout << \"Warning: assembly of non-symmetric Hermitian H-matrices \"\n                 \"is not supported yet. A general H-matrix will be assembled\"\n              << std::endl;\n\n#ifndef WITH_TRILINOS\n  if (!indexWithGlobalDofs)\n    throw std::runtime_error(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                             \"local-mode ACA assembly requires BEM++ to be \"\n                             \"linked with Trilinos\");\n#endif // WITH_TRILINOS\n\n  const size_t testDofCount = indexWithGlobalDofs\n                                  ? testSpace.globalDofCount()\n                                  : testSpace.flatLocalDofCount();\n  const size_t trialDofCount = indexWithGlobalDofs\n                                   ? trialSpace.globalDofCount()\n                                   : trialSpace.flatLocalDofCount();\n\n  if (symmetric && testDofCount != trialDofCount)\n    throw std::invalid_argument(\n        \"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n        \"you cannot generate a symmetric weak form \"\n        \"using test and trial spaces with different \"\n        \"numbers of DOFs\");\n\n  // Construct cluster trees indexed with global indices\n\n  // o2p: map of original indices to permuted indices\n  // p2o: map of permuted indices to original indices\n  typedef ClusterConstructionHelper<BasisFunctionType> CCH;\n  shared_ptr<AhmedBemCluster> testClusterTree;\n  shared_ptr<IndexPermutation> test_o2pPermutation, test_p2oPermutation;\n  CCH::constructBemCluster(testSpace, true /*indexWithGlobalDofs*/, acaOptions,\n                           testClusterTree, test_o2pPermutation,\n                           test_p2oPermutation);\n  shared_ptr<AhmedBemCluster> trialClusterTree;\n  shared_ptr<IndexPermutation> trial_o2pPermutation, trial_p2oPermutation;\n  if (symmetric || &testSpace == &trialSpace) {\n    trialClusterTree = testClusterTree;\n    trial_o2pPermutation = test_o2pPermutation;\n    trial_p2oPermutation = test_p2oPermutation;\n  } else\n    CCH::constructBemCluster(trialSpace, true /*indexWithGlobalDofs*/,\n                             acaOptions, trialClusterTree, trial_o2pPermutation,\n                             trial_p2oPermutation);\n\n  // If necessary, construct cluster trees indexed with flat local indices\n  shared_ptr<AhmedBemCluster> testLocalClusterTree = testClusterTree;\n  shared_ptr<IndexPermutation> testLocal_o2pPermutation = test_o2pPermutation;\n  shared_ptr<IndexPermutation> testLocal_p2oPermutation = test_p2oPermutation;\n  shared_ptr<AhmedBemCluster> trialLocalClusterTree = trialClusterTree;\n  shared_ptr<IndexPermutation> trialLocal_o2pPermutation = trial_o2pPermutation;\n  shared_ptr<IndexPermutation> trialLocal_p2oPermutation = trial_p2oPermutation;\n  if (!indexWithGlobalDofs) {\n    if (!testSpace.isDiscontinuous())\n      CCH::constructBemCluster(testSpace, false /*indexWithGlobalDofs*/,\n                               acaOptions, testLocalClusterTree,\n                               testLocal_o2pPermutation,\n                               testLocal_p2oPermutation);\n    if (symmetric || &testSpace == &trialSpace) {\n      trialLocalClusterTree = testLocalClusterTree;\n      trialLocal_o2pPermutation = testLocal_o2pPermutation;\n      trialLocal_p2oPermutation = testLocal_p2oPermutation;\n    } else if (!trialSpace.isDiscontinuous())\n      CCH::constructBemCluster(trialSpace, false /*indexWithGlobalDofs*/,\n                               acaOptions, trialLocalClusterTree,\n                               trialLocal_o2pPermutation,\n                               trialLocal_p2oPermutation);\n  }\n\n  //    // Export VTK plots showing the disctribution of leaf cluster ids\n  //    std::vector<unsigned int> testClusterIds;\n  //    getClusterIds(*testClusterTree, test_p2oPermutation->permutedIndices(),\n  // testClusterIds);\n  //    testSpace.dumpClusterIds(\"testClusterIds\", testClusterIds,\n  //                             indexWithGlobalDofs ? GLOBAL_DOFS :\n  // FLAT_LOCAL_DOFS);\n  //    std::vector<unsigned int> trialClusterIds;\n  //    getClusterIds(*trialClusterTree,\n  // trial_p2oPermutation->permutedIndices(), trialClusterIds);\n  //    trialSpace.dumpClusterIds(\"trialClusterIds\", trialClusterIds,\n  //                              indexWithGlobalDofs ? GLOBAL_DOFS :\n  // FLAT_LOCAL_DOFS);\n\n  if (verbosityAtLeastHigh)\n    std::cout << \"Test cluster count: \" << testClusterTree->getncl()\n              << \"\\nTrial cluster count: \" << trialClusterTree->getncl()\n              << std::endl;\n\n  // Create block cluster trees\n  unsigned int blockCount = 0;\n  bool useStrongAdmissibilityCondition =\n      !indexWithGlobalDofs ||\n      // experiments indicate that for spaces with discontinuous basis\n      // functions one gets faster assembly (although *slightly* higher memory\n      // consumption) with the strong admissibility condition\n      (testSpace.isDiscontinuous() && trialSpace.isDiscontinuous());\n  shared_ptr<AhmedBemBlcluster> blclusterTree(CCH::constructBemBlockCluster(\n      acaOptions, symmetric, *testClusterTree, *trialClusterTree,\n      useStrongAdmissibilityCondition, blockCount).release());\n  shared_ptr<AhmedBemBlcluster> localBlclusterTree = blclusterTree;\n  if (!indexWithGlobalDofs &&\n      (!testSpace.isDiscontinuous() || !trialSpace.isDiscontinuous())) {\n    unsigned int localBlockCount = 0;\n    localBlclusterTree.reset(CCH::constructBemBlockCluster(\n        acaOptions, symmetric, *testLocalClusterTree, *trialLocalClusterTree,\n        useStrongAdmissibilityCondition, localBlockCount).release());\n    CCH::truncateBemBlockCluster(localBlclusterTree.get(), blclusterTree.get());\n    if (localBlclusterTree->nleaves() != blclusterTree->nleaves())\n      throw std::runtime_error(\n          \"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n          \"internal error: truncated local-dof cluster tree is not \"\n          \"identical to global-dof cluster tree\");\n  }\n\n  if (verbosityAtLeastHigh)\n    std::cout << \"Mblock count: \" << blockCount << std::endl;\n\n#ifdef DUMP_DENSE_BLOCKS\n  std::vector<Point3D<CoordinateType>> testDofCenters, trialDofCenters;\n  if (indexWithGlobalDofs) {\n    testSpace.getGlobalDofPositions(testDofCenters);\n    trialSpace.getGlobalDofPositions(trialDofCenters);\n  } else {\n    testSpace.getFlatLocalDofPositions(testDofCenters);\n    trialSpace.getFlatLocalDofPositions(trialDofCenters);\n  }\n#endif // DUMP_DENSE_BLOCKS\n\n  typedef WeakFormAcaAssemblyHelper<BasisFunctionType, ResultType>\n  AcaAssemblyHelper;\n\n  // Construct assembly helpers\n\n  // It will be possible to remove this kludge if we get rid of the concept\n  // of flat local indices and just use a separate discontinuous space.\n  AssemblyOptions assemblyOptionsWithGlobalIndices = options;\n  AcaOptions acaOptionsWithGlobalIndices = acaOptions;\n  acaOptionsWithGlobalIndices.mode = AcaOptions::GLOBAL_ASSEMBLY;\n  assemblyOptionsWithGlobalIndices.switchToAcaMode(acaOptionsWithGlobalIndices);\n\n  // TODO: It might be better (more efficient and elegant)\n  // to pass p2oPermutation than p2oDofs.\n  // Also, it might be more logical to rename IndexPermutation to IndexMapping\n  // and permute/unpermute to map/unmap.\n  shared_ptr<AcaAssemblyHelper> helper(new AcaAssemblyHelper(\n      testSpace, trialSpace, test_p2oPermutation->permutedIndices(),\n      trial_p2oPermutation->permutedIndices(), localAssemblers,\n      sparseTermsToAdd, denseTermMultipliers, sparseTermMultipliers,\n      assemblyOptionsWithGlobalIndices));\n  shared_ptr<AcaAssemblyHelper> admissibleHelper = helper;\n  if (!indexWithGlobalDofs)\n    admissibleHelper.reset(new AcaAssemblyHelper(\n        testSpace, trialSpace, testLocal_p2oPermutation->permutedIndices(),\n        trialLocal_p2oPermutation->permutedIndices(),\n        localAssemblersForAdmissibleBlocks, sparseTermsToAdd,\n        denseTermMultipliers, sparseTermMultipliers, options));\n\n  // If necessary, construct maps between (permuted) flat local and global\n  // indices\n  shared_ptr<const Epetra_CrsMatrix> testGlobalToLocal, trialGlobalToLocal;\n  if (!indexWithGlobalDofs) {\n    typedef DiscreteSparseBoundaryOperator<ResultType> SparseOp;\n    if (!testSpace.isDiscontinuous()) {\n      shared_ptr<SparseOp> op = constructOperatorMappingGlobalToFlatLocalDofs<\n          BasisFunctionType, ResultType>(testSpace);\n      testGlobalToLocal = op->epetraMatrix();\n      testGlobalToLocal = permuteEpetraCrsMatrix(\n          *testGlobalToLocal, *test_p2oPermutation, *testLocal_o2pPermutation);\n    }\n    if (!trialSpace.isDiscontinuous()) {\n      shared_ptr<SparseOp> op = constructOperatorMappingGlobalToFlatLocalDofs<\n          BasisFunctionType, ResultType>(trialSpace);\n      trialGlobalToLocal = op->epetraMatrix();\n      trialGlobalToLocal =\n          permuteEpetraCrsMatrix(*trialGlobalToLocal, *trial_p2oPermutation,\n                                 *trialLocal_o2pPermutation);\n    }\n  }\n\n  std::unique_ptr<DiscreteAcaBoundaryOperator<ResultType>> acaOp =\n      assembleAcaOperator<AcaAssemblyHelper, BasisFunctionType, ResultType>(\n          helper.get(), admissibleHelper.get(), blclusterTree,\n          localBlclusterTree, options.parallelizationOptions(), acaOptions,\n          verbosityAtLeastDefault, verbosityAtLeastHigh, symmetric,\n          test_o2pPermutation, trial_o2pPermutation, testGlobalToLocal,\n          trialGlobalToLocal\n#ifdef DUMP_DENSE_BLOCKS\n          ,\n          test_p2oPermutation, trial_p2oPermutation, testDofCenters,\n          trialDofCenters\n#endif // DUMP_DENSE_BLOCKS\n          );\n\n  std::unique_ptr<DiscreteBndOp> result;\n  result = acaOp;\n  return result;\n\n#else  // without Ahmed\n  throw std::runtime_error(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                           \"To enable assembly in ACA mode, recompile BEM++ \"\n                           \"with the symbol WITH_AHMED defined.\");\n#endif // WITH_AHMED\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::unique_ptr<DiscreteBoundaryOperator<ResultType>>\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n    const Space<BasisFunctionType> &testSpace,\n    const Space<BasisFunctionType> &trialSpace,\n    LocalAssemblerForIntegralOperators &localAssembler,\n    LocalAssemblerForIntegralOperators &localAssemblerForAdmissibleBlocks,\n    const Context<BasisFunctionType, ResultType> &context, int symmetry) {\n  typedef LocalAssemblerForIntegralOperators Assembler;\n  std::vector<Assembler *> localAssemblers(1, &localAssembler);\n  std::vector<Assembler *> localAssemblersForAdmissibleBlocks(\n      1, &localAssemblerForAdmissibleBlocks);\n  std::vector<const DiscreteBndOp *> sparseTermsToAdd;\n  std::vector<ResultType> denseTermsMultipliers(1, 1.0);\n  std::vector<ResultType> sparseTermsMultipliers;\n\n  return assembleDetachedWeakForm(testSpace, trialSpace, localAssemblers,\n                                  localAssemblersForAdmissibleBlocks,\n                                  sparseTermsToAdd, denseTermsMultipliers,\n                                  sparseTermsMultipliers, context, symmetry);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::unique_ptr<DiscreteBoundaryOperator<ResultType>>\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assemblePotentialOperator(\n    const arma::Mat<CoordinateType> &points,\n    const Space<BasisFunctionType> &trialSpace,\n    const std::vector<LocalAssemblerForPotentialOperators *> &localAssemblers,\n    const std::vector<ResultType> &termMultipliers,\n    const EvaluationOptions &options) {\n#ifdef WITH_AHMED\n  const int symmetric = false;\n\n  typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n  typedef ExtendedBemCluster<AhmedDofType> AhmedBemCluster;\n  typedef bbxbemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n  typedef DiscreteAcaBoundaryOperator<ResultType> DiscreteAcaLinOp;\n\n  const AcaOptions &acaOptions = options.acaOptions();\n  const bool indexWithGlobalDofs =\n      acaOptions.mode != AcaOptions::HYBRID_ASSEMBLY;\n  const bool verbosityAtLeastDefault =\n      (options.verbosityLevel() >= VerbosityLevel::DEFAULT);\n  const bool verbosityAtLeastHigh =\n      (options.verbosityLevel() >= VerbosityLevel::HIGH);\n\n#ifndef WITH_TRILINOS\n  if (!indexWithGlobalDofs)\n    throw std::runtime_error(\"AcaGlobalAssembler::assemblePotentialOperator(): \"\n                             \"local-mode ACA assembly requires BEM++ to be \"\n                             \"linked with Trilinos\");\n#endif // WITH_TRILINOS\n\n  if (localAssemblers.empty())\n    throw std::runtime_error(\"AcaGlobalAssembler::assemblePotentialOperator(): \"\n                             \"the 'localAssemblers' vector must not be empty\");\n\n  const size_t pointCount = points.n_cols;\n  const int componentCount = localAssemblers[0]->resultDimension();\n  const size_t testDofCount = pointCount * componentCount;\n  const size_t trialDofCount = indexWithGlobalDofs\n                                   ? trialSpace.globalDofCount()\n                                   : trialSpace.flatLocalDofCount();\n\n  // o2p: map of original indices to permuted indices\n  // p2o: map of permuted indices to original indices\n  typedef ClusterConstructionHelper<BasisFunctionType> CCH;\n  shared_ptr<AhmedBemCluster> testClusterTree;\n  shared_ptr<IndexPermutation> test_o2pPermutation, test_p2oPermutation;\n  CCH::constructBemCluster(points, componentCount, acaOptions, testClusterTree,\n                           test_o2pPermutation, test_p2oPermutation);\n  shared_ptr<AhmedBemCluster> trialClusterTree;\n  shared_ptr<IndexPermutation> trial_o2pPermutation, trial_p2oPermutation;\n  CCH::constructBemCluster(trialSpace, indexWithGlobalDofs, acaOptions,\n                           trialClusterTree, trial_o2pPermutation,\n                           trial_p2oPermutation);\n\n// Print the distribution of cluster ids\n#ifdef DUMP_DENSE_BLOCKS\n  std::vector<Point3D<CoordinateType>> testDofCenters, trialDofCenters;\n  CCH::getComponentDofPositions(points, componentCount, testDofCenters);\n  if (indexWithGlobalDofs)\n    trialSpace.getGlobalDofPositions(trialDofCenters);\n  else\n    trialSpace.getFlatLocalDofPositions(trialDofCenters);\n#endif // DUMP_DENSE_BLOCKS\n\n  if (verbosityAtLeastHigh)\n    std::cout << \"Test cluster count: \" << testClusterTree->getncl()\n              << \"\\nTrial cluster count: \" << trialClusterTree->getncl()\n              << std::endl;\n\n  unsigned int blockCount = 0;\n  bool useStrongAdmissibilityCondition = !indexWithGlobalDofs;\n  shared_ptr<AhmedBemBlcluster> bemBlclusterTree(CCH::constructBemBlockCluster(\n      acaOptions, false /* symmetric */, *testClusterTree, *trialClusterTree,\n      useStrongAdmissibilityCondition, blockCount).release());\n\n  if (verbosityAtLeastHigh)\n    std::cout << \"Mblock count: \" << blockCount << std::endl;\n\n  std::vector<unsigned int> p2oPoints = test_p2oPermutation->permutedIndices();\n  std::vector<unsigned int> p2oTrialDofs =\n      trial_p2oPermutation->permutedIndices();\n  typedef PotentialOperatorAcaAssemblyHelper<BasisFunctionType, ResultType>\n  AcaAssemblyHelper;\n  AcaAssemblyHelper helper(points, trialSpace, p2oPoints, p2oTrialDofs,\n                           localAssemblers, termMultipliers, options);\n\n  // If necessary, construct maps between (permuted) flat local and global\n  // indices\n  shared_ptr<const Epetra_CrsMatrix> testGlobalToLocal, trialGlobalToLocal;\n\n  std::unique_ptr<DiscreteAcaBoundaryOperator<ResultType>> acaOp =\n      assembleAcaOperator<AcaAssemblyHelper, BasisFunctionType, ResultType>(\n          &helper, &helper, bemBlclusterTree, bemBlclusterTree,\n          options.parallelizationOptions(), options.acaOptions(),\n          verbosityAtLeastDefault, verbosityAtLeastHigh, symmetric,\n          test_o2pPermutation, trial_o2pPermutation, testGlobalToLocal,\n          trialGlobalToLocal\n#ifdef DUMP_DENSE_BLOCKS\n          ,\n          test_p2oPermutation, trial_p2oPermutation, testDofCenters,\n          trialDofCenters\n#endif // DUMP_DENSE_BLOCKS\n          );\n\n  std::unique_ptr<DiscreteBndOp> result;\n  if (indexWithGlobalDofs)\n    result = acaOp;\n  else {\n#ifdef WITH_TRILINOS\n    // without Trilinos, this code will never be reached -- an exception\n    // will be thrown earlier in this function\n    typedef DiscreteBoundaryOperatorComposition<ResultType> DiscreteBndOpComp;\n    shared_ptr<DiscreteBndOp> acaOpShared(acaOp.release());\n    shared_ptr<DiscreteBndOp> trialGlobalToLocal =\n        constructOperatorMappingGlobalToFlatLocalDofs<BasisFunctionType,\n                                                      ResultType>(trialSpace);\n    result.reset(new DiscreteBndOpComp(acaOpShared, trialGlobalToLocal));\n#endif // WITH_TRILINOS\n  }\n  return result;\n\n#else  // without Ahmed\n  throw std::runtime_error(\"AcaGlobalAssembler::assemblePotentialOperator(): \"\n                           \"To enable assembly in ACA mode, recompile BEM++ \"\n                           \"with the symbol WITH_AHMED defined.\");\n#endif // WITH_AHMED\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::unique_ptr<DiscreteBoundaryOperator<ResultType>>\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assemblePotentialOperator(\n    const arma::Mat<CoordinateType> &points,\n    const Space<BasisFunctionType> &trialSpace,\n    LocalAssemblerForPotentialOperators &localAssembler,\n    const EvaluationOptions &options) {\n  std::vector<LocalAssemblerForPotentialOperators *> localAssemblers(\n      1, &localAssembler);\n  std::vector<ResultType> termMultipliers(1, 1.0);\n\n  return assemblePotentialOperator(points, trialSpace, localAssemblers,\n                                   termMultipliers, options);\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(AcaGlobalAssembler);\n\n} // namespace Bempp\n", "meta": {"hexsha": "a36b83b6bea4c880dae25b44c9a5762a634154e3", "size": 44903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/aca_global_assembler.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/aca_global_assembler.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/aca_global_assembler.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9929859719, "max_line_length": 81, "alphanum_fraction": 0.683116941, "num_tokens": 11177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.033589509157004045, "lm_q1q2_score": 0.015877205966306537}}
{"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// The formulae for sphere intersection area and volume are\n// derived from those presented in: \"Measuring Space Filling\n// Diagrams and Voids\" by Herbert Edelsbrunner and Ping Fu.\n\n#include \"molecularsurface.h\"\n\n#include <boost/bind.hpp>\n#include <boost/thread.hpp>\n\n#include \"atom.h\"\n#include \"foreach.h\"\n#include \"vector3.h\"\n#include \"geometry.h\"\n#include \"molecule.h\"\n#include \"alphashape.h\"\n#include \"concurrent.h\"\n#include \"delaunaytriangulation.h\"\n\nnamespace chemkit {\n\nnamespace {\n\nconst Real pi = chemkit::constants::Pi;\n\nReal angleDihedral(const Point3 &s, const Point3 &t, const Point3 &u, const Point3 &v)\n{\n    Vector3 mu = (u - s).cross(u - t);\n    Vector3 mv = (v - s).cross(v - t);\n\n    Vector3 nu = mu.normalized();\n    Vector3 nv = mv.normalized();\n\n    return acos(nu.dot(nv)) / (2.0 * pi);\n}\n\n} // end anonymous namespace\n\n// === MolecularSurfacePrivate ============================================= //\nclass MolecularSurfacePrivate\n{\npublic:\n    const Molecule *molecule;\n    MolecularSurface::SurfaceType surfaceType;\n    Real probeRadius;\n    std::vector<Point3> points;\n    std::vector<Real> radii;\n    AlphaShape *alphaShape;\n    Real volume;\n    Real surfaceArea;\n    bool volumeCalculated;\n    bool surfaceAreaCalculated;\n};\n\n// === MolecularSurface ==================================================== //\n/// \\class MolecularSurface molecularsurface.h chemkit/molecularsurface.h\n/// \\ingroup chemkit\n/// \\brief  The MolecularSurface class represents a molecular\n///         surface.\n///\n/// The following example shows how to calculate the solvent\n/// accessible surface area of a molecule.\n/// \\code\n/// // create the surface object for the molecule\n/// MolecularSurface surface(molecule);\n///\n/// // set the surface type to solvent accessible\n/// surface.setSurfaceType(MolecularSurface::SolventAccessible);\n///\n/// // set the solvent probe radius to 1.4 angstroms\n/// surface.setProbeRadius(1.4);\n///\n/// // calculate the surface area\n/// double area = surface.surfaceArea();\n/// \\endcode\n\n/// \\enum MolecularSurface::SurfaceType\n/// Provides names for each of the available surface types:\n///     - \\c VanDerWaals\n///     - \\c SolventAccessible\n///     - \\c SolventExcluded\n\n// --- Construction and Destruction ---------------------------------------- //\n/// Creates a new molecular surface for \\p molecule.\nMolecularSurface::MolecularSurface(const Molecule *molecule, SurfaceType type)\n    : d(new MolecularSurfacePrivate)\n{\n    d->molecule = molecule;\n    d->surfaceType = type;\n    d->probeRadius = 1.4;\n\n    if(molecule){\n        foreach(const Atom *atom, molecule->atoms()){\n            d->points.push_back(atom->position());\n            d->radii.push_back(atom->vanDerWaalsRadius());\n        }\n    }\n\n    d->alphaShape = 0;\n    d->volumeCalculated = false;\n    d->surfaceAreaCalculated = false;\n}\n\n/// Destroys the molecular surface object.\nMolecularSurface::~MolecularSurface()\n{\n    delete d->alphaShape;\n    delete d;\n}\n\n// --- Properties ---------------------------------------------------------- //\n/// Sets the molecule for the surface.\nvoid MolecularSurface::setMolecule(const Molecule *molecule)\n{\n    d->molecule = molecule;\n\n    // update atom positions and radii\n    if(molecule){\n        d->points.resize(molecule->size());\n        d->radii.resize(molecule->size());\n\n        for(size_t i = 0; i < molecule->size(); i++){\n            const Atom *atom = molecule->atom(i);\n\n            d->points[i] = atom->position();\n            d->radii[i] = atom->vanDerWaalsRadius();\n        }\n    }\n\n    setCalculated(false);\n}\n\n/// Returns the molecule for the surface.\nconst Molecule* MolecularSurface::molecule() const\n{\n    return d->molecule;\n}\n\n/// Sets the surface type to \\p type.\nvoid MolecularSurface::setSurfaceType(SurfaceType type)\n{\n    d->surfaceType = type;\n\n    setCalculated(false);\n}\n\n/// Returns the surface type.\nMolecularSurface::SurfaceType MolecularSurface::surfaceType() const\n{\n    return d->surfaceType;\n}\n\n/// Sets the probe radius to \\p radius.\nvoid MolecularSurface::setProbeRadius(Real radius)\n{\n    d->probeRadius = radius;\n\n    setCalculated(false);\n}\n\n/// Returns the probe radius.\n///\n/// The default probe radius is 1.4 Angstroms which approximates\n/// the radius of a water molecule.\nReal MolecularSurface::probeRadius() const\n{\n    return d->probeRadius;\n}\n\nconst AlphaShape* MolecularSurface::alphaShape() const\n{\n    if(!d->alphaShape){\n        // calculate weights (weight = radius sqaured)\n        std::vector<Real> weights(d->points.size());\n        for(unsigned int i = 0; i < d->points.size(); i++){\n            weights[i] = pow(radius(i), 2);\n        }\n\n        d->alphaShape = new AlphaShape(d->points, weights);\n    }\n\n    return d->alphaShape;\n}\n\n// --- Geometry ------------------------------------------------------------ //\n/// Returns the position of the sphere at \\p index.\nPoint3 MolecularSurface::position(int index) const\n{\n    return d->points[index];\n}\n\n/// Returns the radius of the sphere at \\p index.\nReal MolecularSurface::radius(int index) const\n{\n    if(d->surfaceType == VanDerWaals)\n        return d->radii[index];\n    else\n        return d->radii[index] + d->probeRadius;\n}\n\n/// Returns the total volume of the surface. The returned volume\n/// is in Angstroms cubed (\\f$ \\AA^{3} \\f$).\nReal MolecularSurface::volume() const\n{\n    if(!d->volumeCalculated){\n        d->volume = 0;\n\n        const AlphaShape *alphaShape = this->alphaShape();\n\n        // add volume and area for each vertex\n        for(unsigned int i = 0; i < d->points.size(); i++){\n            Real r = radius(i);\n\n            d->volume += (4.0/3.0) * pi * r*r*r;\n        }\n\n        // subtract volume from each edge\n        foreach(const AlphaShape::Edge &edge, alphaShape->edges()){\n            d->volume -= intersectionVolume(edge[0], edge[1]);\n        }\n\n        // add volume from each triangle\n        foreach(const AlphaShape::Triangle &triangle, alphaShape->triangles()){\n            d->volume += intersectionVolume(triangle[0], triangle[1], triangle[2]);\n        }\n\n        // subtract volume from each tetrahedron\n        foreach(const std::vector<int> &tetrahedron, alphaShape->tetrahedra()){\n            d->volume -= intersectionVolume(tetrahedron[0], tetrahedron[1], tetrahedron[2], tetrahedron[3]);\n        }\n\n        d->volumeCalculated = true;\n    }\n\n    return d->volume;\n}\n\n/// Runs the volume() method asynchronously and returns a future\n/// containing the result.\n///\n/// \\internal\nboost::shared_future<Real> MolecularSurface::volumeAsync() const\n{\n    return chemkit::concurrent::run(boost::bind(&MolecularSurface::volume, this));\n}\n\n/// Returns the total surface area of the surface. The returned\n/// area is in Angstroms squared (\\f$ \\AA^{2} \\f$).\nReal MolecularSurface::surfaceArea() const\n{\n    if(!d->surfaceAreaCalculated){\n        d->surfaceArea = 0;\n\n        const AlphaShape *alphaShape = this->alphaShape();\n\n        // add volume and area for each vertex\n        for(unsigned int i = 0; i < d->points.size(); i++){\n            Real r = radius(i);\n\n            d->surfaceArea += 4.0 * pi * r*r;\n        }\n\n        // subtract volume and area from each edge\n        foreach(const AlphaShape::Edge &edge, alphaShape->edges()){\n            d->surfaceArea -= intersectionArea(edge[0], edge[1]);\n        }\n\n        // add volume and area from each triangle\n        foreach(const AlphaShape::Triangle &triangle, alphaShape->triangles()){\n            d->surfaceArea += intersectionArea(triangle[0], triangle[1], triangle[2]);\n        }\n\n        // subtract volume and area from each tetrahedron\n        foreach(const std::vector<int> &tetrahedron, alphaShape->tetrahedra()){\n            d->surfaceArea -= intersectionArea(tetrahedron[0], tetrahedron[1], tetrahedron[2], tetrahedron[3]);\n        }\n\n        d->surfaceAreaCalculated = true;\n    }\n\n    return d->surfaceArea;\n}\n\n/// Runs the surfaceArea() method asynchronously and returns a future\n/// containing the result.\n///\n/// \\internal\nboost::shared_future<Real> MolecularSurface::surfaceAreaAsync() const\n{\n    return chemkit::concurrent::run(boost::bind(&MolecularSurface::surfaceArea, this));\n}\n\n// --- Internal Methods ---------------------------------------------------- //\nvoid MolecularSurface::setCalculated(bool calculated) const\n{\n    if(calculated == false){\n        delete d->alphaShape;\n        d->alphaShape = 0;\n        d->volumeCalculated = false;\n        d->surfaceAreaCalculated = false;\n    }\n}\n\n/// Returns the area of intersection between spheres \\p i and \\p j.\nReal MolecularSurface::intersectionArea(int i, int j) const\n{\n    return 2.0 * pi * (radius(i) * capHeight(i, j) + radius(j) * capHeight(j, i));\n}\n\n/// Returns the area of intersection between spheres \\p i, \\p j and\n/// \\p k.\nReal MolecularSurface::intersectionArea(int i, int j, int k) const\n{\n    return cap2Area(i, j, k) + cap2Area(j, i, k) + cap2Area(k, i, j);\n}\n\n/// Returns the area of intersection between spheres \\p i, \\p j, \\p k\n/// and \\p l.\nReal MolecularSurface::intersectionArea(int i, int j, int k, int l) const\n{\n    return cap3Area(i, j, k, l) + cap3Area(j, i, k, l) + cap3Area(k, i, j, l) + cap3Area(l, i, j, k);\n}\n\n/// Returns the volume of intersection between spheres \\p i, and\n/// \\p j.\nReal MolecularSurface::intersectionVolume(int i, int j) const\n{\n    return capVolume(i, j) + capVolume(j, i);\n}\n\n/// Returns the volume of intersection between spheres \\p i, \\p j,\n/// and \\p k.\nReal MolecularSurface::intersectionVolume(int i, int j, int k) const\n{\n    return cap2Volume(i, j, k) + cap2Volume(j, i, k) + cap2Volume(k, i, j);\n}\n\n/// Returns the volume of intersection between spheres \\p i, \\p j,\n/// \\p k and \\p l.\nReal MolecularSurface::intersectionVolume(int i, int j, int k, int l) const\n{\n    return cap3Volume(i, j, k, l) + cap3Volume(j, i, k, l) + cap3Volume(k, i, j, l) + cap3Volume(l, i, j, k);\n}\n\nReal MolecularSurface::ballArea(int index) const\n{\n    Real r = radius(index);\n\n    return 4.0 * pi * r*r;\n}\n\nReal MolecularSurface::capHeight(int i, int j) const\n{\n    const Point3 &s = position(i);\n\n    Point3 y = d->alphaShape->orthocenter(i, j);\n\n    // check if vertex i is attached to vertex j\n    if(d->alphaShape->vertexAttached(i, j)){\n        return radius(i) + chemkit::geometry::distance(s, y);\n    }\n    else{\n        return radius(i) - chemkit::geometry::distance(s, y);\n    }\n}\n\nReal MolecularSurface::capArea(int i, int j) const\n{\n    return 2.0 * pi * radius(i) * capHeight(i, j);\n}\n\nReal MolecularSurface::capVolume(int i, int j) const\n{\n    Real s = radius(i) * capArea(i, j);\n    Real c = (radius(i) - capHeight(i, j)) * diskArea(i, j);\n\n    return (1.0/3.0) * (s - c);\n}\n\nReal MolecularSurface::cap2Area(int i, int j, int k) const\n{\n    Point3 pjk = triangleDual(i, j, k);\n\n    Real lj = segmentAngle(i, j, k);\n    Real lk = segmentAngle(i, k, j);\n\n    const Point3 &s = position(i);\n    const Point3 &t = position(j);\n    const Point3 &u = position(k);\n\n    Real r = radius(i);\n    Real phi = (1.0/2.0) - angleDihedral(s, pjk, t, u);\n\n    Real a1 = ballArea(i) * phi;\n    Real a2 = 2.0 * pi * r * lj * (r - capHeight(i, j));\n    Real a3 = 2.0 * pi * r * lk * (r - capHeight(i, k));\n\n    return a1 - a2 - a3;\n}\n\nReal MolecularSurface::cap2Volume(int i, int j, int k) const\n{\n    Real s2 = (1.0/3.0) * radius(i) * cap2Area(i, j, k);\n    Real cj = (1.0/3.0) * (radius(i) - capHeight(i, j)) * segmentArea(i, j, k);\n    Real ck = (1.0/3.0) * (radius(i) - capHeight(i, k)) * segmentArea(i, k, j);\n\n    return s2 - cj - ck;\n}\n\nReal MolecularSurface::cap3Area(int i, int j, int k, int l) const\n{\n    if(!ccw(i, j, k, l)){\n        std::swap(k, l);\n    }\n\n    const Point3 &s = position(i);\n    const Point3 &t = position(j);\n    const Point3 &u = position(k);\n    const Point3 &v = position(l);\n\n    Point3 pkj = triangleDual(i, k, j);\n    Point3 plk = triangleDual(i, l, k);\n    Point3 pjl = triangleDual(i, j, l);\n\n    Real lj = segment2Angle(i, j, k, l);\n    Real lk = segment2Angle(i, k, l, j);\n    Real ll = segment2Angle(i, l, j, k);\n\n    Real rho_kj = (1.0/2.0) - angleDihedral(s, pkj, u, t);\n    Real rho_lk = (1.0/2.0) - angleDihedral(s, plk, v, u);\n    Real rho_jl = (1.0/2.0) - angleDihedral(s, pjl, t, v);\n\n    Real a1 = (1.0/2.0) * ballArea(i) * (rho_kj + rho_lk + rho_jl - (1.0/2.0));\n    Real a2 = 2.0 * pi * radius(i) * lj * (radius(i) - capHeight(i, j));\n    Real a3 = 2.0 * pi * radius(i) * lk * (radius(i) - capHeight(i, k));\n    Real a4 = 2.0 * pi * radius(i) * ll * (radius(i) - capHeight(i, l));\n\n    return a1 - a2 - a3 - a4;\n}\n\nReal MolecularSurface::cap3Volume(int i, int j, int k, int l) const\n{\n    Real s3 = (1.0/3.0) * radius(i) * cap3Area(i, j, k, l);\n    Real cj = (1.0/3.0) * (radius(i) - capHeight(i, j)) * segment2Area(i, j, k, l);\n    Real ck = (1.0/3.0) * (radius(i) - capHeight(i, k)) * segment2Area(i, k, j, l);\n    Real cl = (1.0/3.0) * (radius(i) - capHeight(i, l)) * segment2Area(i, l, j, k);\n\n    return s3 - cj - ck - cl;\n}\n\nReal MolecularSurface::diskArea(int i, int j) const\n{\n    return (1.0/2.0) * diskRadius(i, j) * diskLength(i, j);\n}\n\nReal MolecularSurface::diskLength(int i, int j) const\n{\n    return 2.0 * pi * diskRadius(i, j);\n}\n\nReal MolecularSurface::diskRadius(int i, int j) const\n{\n    return sqrt(capHeight(i, j) * (2.0 * radius(i) - capHeight(i, j)));\n}\n\nPoint3 MolecularSurface::triangleDual(int i, int j, int k) const\n{\n    Point3 y = d->alphaShape->orthocenter(i, j, k);\n\n    const Point3 &s = d->points[i];\n    const Point3 &t = d->points[j];\n    const Point3 &u = d->points[k];\n\n    Vector3 n = (t - s).cross(u - s);\n\n    Vector3 ys = y - s;\n\n    Real s1 = (ys).dot(n);\n    Real s2 = n.dot(n);\n    Real s3 = (ys).dot(ys);\n\n    Real r = radius(i);\n\n    Real xi = (-s1 + sqrt(s1*s1 - s3 * s2 + r*r * s2)) / s2;\n\n    return y + (n * xi);\n}\n\nReal MolecularSurface::segmentArea(int i, int j, int k) const\n{\n    Real s = (1.0/2.0) * diskRadius(i, j) * segmentLength(i, j, k);\n\n    Point3 pjk = triangleDual(i, j, k);\n    Point3 pkj = triangleDual(i, k, j);\n\n    Real h = diskRadius(i, j) - segmentHeight(i, j, k);\n    Real t = (1.0/2.0) * h * chemkit::geometry::distance(pjk, pkj);\n\n    return s - t;\n}\n\nReal MolecularSurface::segmentAngle(int i, int j, int k) const\n{\n    Point3 pjk = triangleDual(i, j, k);\n\n    const Point3 &s = d->points[i];\n    const Point3 &t = d->points[j];\n    const Point3 &u = d->points[k];\n\n    return 2.0 * angleDihedral(s, t, u, pjk);\n}\n\nReal MolecularSurface::segmentLength(int i, int j, int k) const\n{\n    return segmentAngle(i, j, k) * diskLength(i, j);\n}\n\nReal MolecularSurface::segmentHeight(int i, int j, int k) const\n{\n    Point3 y2 = d->alphaShape->orthocenter(i, j);\n    Point3 y3 = d->alphaShape->orthocenter(i, j, k);\n\n    // check if vertex k is attached to the edge (i, j)\n    if(d->alphaShape->edgeAttached(i, j, k)){\n        return diskRadius(i, j) + chemkit::geometry::distance(y2, y3);\n    }\n    else{\n        return diskRadius(i, j) - chemkit::geometry::distance(y2, y3);\n    }\n}\n\nReal MolecularSurface::segment2Area(int i, int j, int k, int l) const\n{\n    if(!ccw(i, j, k, l))\n        std::swap(k, l);\n\n    Point3 pkj = triangleDual(i, k, j);\n    Point3 pjl = triangleDual(i, j, l);\n\n    Point3 y = d->alphaShape->orthocenter(i, j, k, l);\n\n    Real hk = segmentHeight(i, j, k);\n    Real hl = segmentHeight(i, j, l);\n\n    Real rij = diskRadius(i, j);\n\n    Real s = (1.0/2.0) * rij * segment2Length(i, j, k, l);\n    Real tk = (1.0/2.0) * (rij - hk) * chemkit::geometry::distance(pkj, y);\n    Real tl = (1.0/2.0) * (rij - hl) * chemkit::geometry::distance(pjl, y);\n\n    return s - tk - tl;\n}\n\nReal MolecularSurface::segment2Angle(int i, int j, int k, int l) const\n{\n    Point3 pjl = triangleDual(i, j, l);\n    Point3 pkj = triangleDual(i, k, j);\n\n    const Point3 &s = d->points[i];\n    const Point3 &t = d->points[j];\n    const Point3 &u = d->points[k];\n    const Point3 &v = d->points[l];\n\n    return angleDihedral(s, t, u, pkj) + angleDihedral(s, t, v, pjl) - angleDihedral(s, t, u, v);\n}\n\nReal MolecularSurface::segment2Length(int i, int j, int k, int l) const\n{\n    return segment2Angle(i, j, k, l) * diskLength(i, j);\n}\n\nbool MolecularSurface::ccw(int i, int j, int k, int l) const\n{\n    const Point3 &a = position(i);\n    const Point3 &b = position(j);\n    const Point3 &c = position(k);\n    const Point3 &d = position(l);\n\n    return chemkit::geometry::planeOrientation(a, b, c, d) > 0;\n}\n\n} // end chemkit namespace\n", "meta": {"hexsha": "1c5d0555f9179049e7aa533712482508b0902eb6", "size": 18280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/chemkit/molecularsurface.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/chemkit/molecularsurface.cpp", "max_issues_repo_name": "quizzmaster/chemkit", "max_issues_repo_head_hexsha": "803e4688b514008c605cb5c7790f7b36e67b68fc", "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/chemkit/molecularsurface.cpp", "max_forks_repo_name": "quizzmaster/chemkit", "max_forks_repo_head_hexsha": "803e4688b514008c605cb5c7790f7b36e67b68fc", "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": 29.6272285251, "max_line_length": 111, "alphanum_fraction": 0.6178884026, "num_tokens": 5154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969238628498, "lm_q2_score": 0.03789242527149358, "lm_q1q2_score": 0.015865441898877272}}
{"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 <iostream>\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 <RansacLib/ransac.h>\n#include \"line_estimator.h\"\n\n// Assumes that inlier threshold << 0.5.\nvoid GenerateRandomInstance(const int num_inliers, const int num_outliers,\n                            double inlier_threshold, Eigen::Matrix2Xd* points) {\n  const int kNumPoints = num_inliers + num_outliers;\n  points->resize(2, kNumPoints);\n\n  std::vector<int> indices(kNumPoints);\n  std::iota(indices.begin(), indices.end(), 0);\n\n  std::random_device rand_dev;\n  std::mt19937 rng(rand_dev());\n\n  std::shuffle(indices.begin(), indices.end(), rng);\n\n  // Generates num_inliers points along the x-axis in the interval [0, 1] with\n  // a y-value in the range (-inlier_threshold, inlier_threshold) choosen\n  // at random.\n  std::uniform_real_distribution<double> distr(-inlier_threshold,\n                                               inlier_threshold);\n\n  const double kXStep = 1.0 / static_cast<double>(num_inliers);\n  double x = 0.0;\n  for (int i = 0; i < num_inliers; ++i, x += kXStep) {\n    const int kIndex = indices[i];\n    points->col(kIndex)[0] = x;\n    while (true) {\n      points->col(kIndex)[1] = distr(rng);\n      if (points->col(kIndex)[1] > -inlier_threshold) {\n        break;\n      }\n    }\n  }\n\n  // Randomly generates outliers in the range [0, 1] x [-0.5, 0.5].\n  std::uniform_real_distribution<double> distr_x(0.0, 1.0);\n  std::uniform_real_distribution<double> distr_y(-0.5, 0.5);\n  for (int i = num_inliers; i < kNumPoints; ++i) {\n    double x = distr_x(rng);\n    double y = distr_y(rng);\n    while (std::fabs(y) < 5.0 * inlier_threshold) {\n      y = distr_y(rng);\n    }\n\n    const int kIndex = indices[i];\n    points->col(kIndex)[0] = x;\n    points->col(kIndex)[1] = y;\n  }\n\n  // Randomly rotates and translates the points.\n  const double kAngle = distr_y(rng) * M_PI;\n  Eigen::Matrix2d R;\n  R << std::cos(kAngle), -std::sin(kAngle), std::sin(kAngle), std::cos(kAngle);\n  Eigen::Vector2d t(distr_y(rng) * 10.0, distr_y(rng) * 10.0);\n\n  for (int i = 0; i < kNumPoints; ++i) {\n    Eigen::Vector2d p = R * points->col(i) + t;\n    points->col(i) = p;\n  }\n}\n\nint main(int argc, char** argv) {\n  ransac_lib::LORansacOptions options;\n  options.min_num_iterations_ = 100u;\n  options.max_num_iterations_ = 100000u;\n  options.squared_inlier_threshold_ = 0.01 * 0.01;\n\n  std::random_device rand_dev;\n  options.random_seed_ = rand_dev();\n\n  // Generates random instances for outlier ratios 10%, 20%, 30%, ..., 90%,\n  // and then applies RANSAC on it.\n  // kNumDataPoints data points are used.\n  const int kNumDataPoints = 10000;\n  std::vector<double> outlier_ratios = {0.1, 0.2, 0.3, 0.4,  0.5,  0.6,\n                                        0.7, 0.8, 0.9, 0.95, 0.99, 0.999};\n  for (const double outlier_ratio : outlier_ratios) {\n    std::cout << \" Inlier ratio: \" << 1.0 - outlier_ratio << std::endl;\n    int num_outliers =\n        static_cast<int>(static_cast<double>(kNumDataPoints) * outlier_ratio);\n    int num_inliers = kNumDataPoints - num_outliers;\n\n    Eigen::Matrix2Xd data;\n    GenerateRandomInstance(num_inliers, num_outliers, 0.5 * 0.01, &data);\n    std::cout << \"   ... instance generated\" << std::endl;\n\n    ransac_lib::LineEstimator solver(data);\n    ransac_lib::LocallyOptimizedMSAC<Eigen::Vector3d,\n                                     std::vector<Eigen::Vector3d>,\n                                     ransac_lib::LineEstimator>\n        lomsac;\n    ransac_lib::RansacStatistics ransac_stats;\n\n    std::cout << \"   ... running LOMSAC\" << std::endl;\n    Eigen::Vector3d best_model;\n    int num_ransac_inliers =\n        lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n    std::cout << \"   ... LOMSAC found \" << num_ransac_inliers << \" inliers in \"\n              << ransac_stats.num_iterations << \" iterations with an inlier \"\n              << \"ratio of \" << ransac_stats.inlier_ratio << std::endl;\n  }\n}\n", "meta": {"hexsha": "7074a824db9d9354dc86f6387eec945f158fea75", "size": 5746, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/line_estimation.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/line_estimation.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/line_estimation.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": 38.5637583893, "max_line_length": 80, "alphanum_fraction": 0.6672467804, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.03622005300402792, "lm_q1q2_score": 0.015857990875700147}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 15:03:20\n\n#ifndef NUHMSSM_SLHA_IO_H\n#define NUHMSSM_SLHA_IO_H\n\n#include \"NUHMSSM_mass_eigenstates.hpp\"\n#include \"NUHMSSM_model_slha.hpp\"\n#include \"NUHMSSM_info.hpp\"\n#include \"NUHMSSM_observables.hpp\"\n#include \"NUHMSSM_physical.hpp\"\n#include \"problems.hpp\"\n#include \"spectrum_generator_problems.hpp\"\n#include \"standard_model_two_scale_model.hpp\"\n#include \"slha_io.hpp\"\n#include \"ckm.hpp\"\n#include \"ew_input.hpp\"\n#include \"lowe.h\"\n\n#include <Eigen/Core>\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp>\n\n#define Pole(p) physical.p\n#define PHYSICAL(p) model.get_physical().p\n#define PHYSICAL_SLHA(p) model.get_physical_slha().p\n#define LOCALPHYSICAL(p) physical.p\n#define MODEL model\n#define MODELPARAMETER(p) model.get_##p()\n#define EXTRAPARAMETER(p) model.get_##p()\n#define OBSERVABLES observables\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define SCALES(p) scales.p\n\nnamespace flexiblesusy {\n\nstruct NUHMSSM_input_parameters;\nclass Spectrum_generator_settings;\n\ntemplate <class T>\nclass NUHMSSM;\n\nstruct NUHMSSM_scales {\n   double HighScale{0.}, SUSYScale{0.}, LowScale{0.};\n   double pole_mass_scale{0.};\n};\n\nclass NUHMSSM_slha_io {\npublic:\n   NUHMSSM_slha_io();\n\n   void clear();\n\n   void fill(softsusy::QedQcd& qedqcd) const { slha_io.fill(qedqcd); }\n   void fill(NUHMSSM_input_parameters&) const;\n   void fill(NUHMSSM_mass_eigenstates&) const;\n   template <class Model> void fill(NUHMSSM_slha<Model>&) const;\n   void fill(Physical_input&) const;\n   void fill(Spectrum_generator_settings&) const;\n   double get_parameter_output_scale() const;\n   const SLHA_io& get_slha_io() const { return slha_io; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   void set_block(const std::string& str, SLHA_io::Position position = SLHA_io::back) { slha_io.set_block(str, position); }\n   void set_blocks(const std::vector<std::string>& vec, SLHA_io::Position position = SLHA_io::back) { slha_io.set_blocks(vec, position); }\n   template <class Model> void set_extra(const NUHMSSM_slha<Model>&, const NUHMSSM_scales&, const NUHMSSM_observables&);\n   void set_input(const NUHMSSM_input_parameters&);\n   void set_modsel(const SLHA_io::Modsel&);\n   void set_physical_input(const Physical_input&);\n   void set_settings(const Spectrum_generator_settings&);\n   void set_sminputs(const softsusy::QedQcd&);\n   template <class... Ts> void set_spectrum(const std::tuple<Ts...>&);\n   template <class Model> void set_spectrum(const NUHMSSM_slha<Model>&);\n   template <class T> void set_spectrum(const NUHMSSM<T>&);\n   void set_spectrum(const standard_model::Standard_model& m) { slha_io.set_spectrum(m); }\n   void set_spinfo(const Spectrum_generator_problems&);\n   void set_spinfo(const Problems&);\n   void set_spinfo(const std::vector<std::string>&, const std::vector<std::string>&);\n   void set_print_imaginary_parts_of_majorana_mixings(bool);\n   void write_to(const std::string&) const;\n   void write_to_file(const std::string& file_name) const { slha_io.write_to_file(file_name); }\n   void write_to_stream(std::ostream& ostr = std::cout) const { slha_io.write_to_stream(ostr); }\n\n   static void fill_minpar_tuple(NUHMSSM_input_parameters&, int, double);\n   static void fill_extpar_tuple(NUHMSSM_input_parameters&, int, double);\n   static void fill_imminpar_tuple(NUHMSSM_input_parameters&, int, double);\n   static void fill_imextpar_tuple(NUHMSSM_input_parameters&, int, double);\n\n   template <class Model>\n   static void fill_slhaea(SLHAea::Coll&, const NUHMSSM_slha<Model>&, const softsusy::QedQcd&, const NUHMSSM_scales&, const NUHMSSM_observables&);\n\n   template <class Model>\n   static SLHAea::Coll fill_slhaea(const NUHMSSM_slha<Model>&, const softsusy::QedQcd&, const NUHMSSM_scales&, const NUHMSSM_observables&);\n\nprivate:\n   SLHA_io slha_io; ///< SLHA io class\n   bool print_imaginary_parts_of_majorana_mixings;\n\n   void set_extpar(const NUHMSSM_input_parameters&);\n   void set_imminpar(const NUHMSSM_input_parameters&);\n   void set_imextpar(const NUHMSSM_input_parameters&);\n   void set_minpar(const NUHMSSM_input_parameters&);\n   void set_mass(const NUHMSSM_physical&, bool);\n   void set_mixing_matrices(const NUHMSSM_physical&, bool);\n   template <class Model> void set_model_parameters(const NUHMSSM_slha<Model>&);\n   void set_ckm(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   void set_pmns(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   double read_scale() const;\n   void fill_drbar_parameters(NUHMSSM_mass_eigenstates&) const;\n   void fill_physical(NUHMSSM_physical&) const;\n};\n\n/**\n * Reads DR-bar parameters, pole masses and mixing matrices from a\n * SLHA output file.\n */\ntemplate <class Model>\nvoid NUHMSSM_slha_io::fill(NUHMSSM_slha<Model>& model) const\n{\n   fill(static_cast<NUHMSSM_mass_eigenstates&>(model));\n   fill_physical(model.get_physical_slha());\n}\n\ntemplate <class Model>\nvoid NUHMSSM_slha_io::fill_slhaea(\n   SLHAea::Coll& slhaea, const NUHMSSM_slha<Model>& model,\n   const softsusy::QedQcd& qedqcd, const NUHMSSM_scales& scales,\n   const NUHMSSM_observables& observables)\n{\n   NUHMSSM_slha_io slha_io;\n   const NUHMSSM_input_parameters& input = model.get_input();\n   const auto& problems = model.get_problems();\n   const bool error = problems.have_problem();\n\n   slha_io.set_spinfo(problems);\n   slha_io.set_sminputs(qedqcd);\n   slha_io.set_input(input);\n   if (!error) {\n      slha_io.set_spectrum(model);\n      slha_io.set_extra(model, scales, observables);\n   }\n\n   slhaea = slha_io.get_slha_io().get_data();\n}\n\ntemplate <class Model>\nSLHAea::Coll NUHMSSM_slha_io::fill_slhaea(\n   const NUHMSSM_slha<Model>& model, const softsusy::QedQcd& qedqcd,\n   const NUHMSSM_scales& scales, const NUHMSSM_observables& observables)\n{\n   SLHAea::Coll slhaea;\n   NUHMSSM_slha_io::fill_slhaea(slhaea, model, qedqcd, scales, observables);\n\n   return slhaea;\n}\n\n/**\n * Stores the model (DR-bar) parameters in the SLHA object.\n *\n * @param model model class\n */\ntemplate <class Model>\nvoid NUHMSSM_slha_io::set_model_parameters(const NUHMSSM_slha<Model>& model)\n{\n   {\n      std::ostringstream block;\n      block << \"Block gauge Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(g1) * 0.7745966692414834), \"g1 * 0.7745966692414834\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(g2)), \"g2\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(g3)), \"g3\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"Yu\", ToMatrix(MODELPARAMETER(Yu_slha)), \"Yu\", model.get_scale());\n   slha_io.set_block(\"Yd\", ToMatrix(MODELPARAMETER(Yd_slha)), \"Yd\", model.get_scale());\n   slha_io.set_block(\"Ye\", ToMatrix(MODELPARAMETER(Ye_slha)), \"Ye\", model.get_scale());\n   slha_io.set_block(\"Te\", MODELPARAMETER(TYe_slha), \"TYe\", model.get_scale());\n   slha_io.set_block(\"Td\", MODELPARAMETER(TYd_slha), \"TYd\", model.get_scale());\n   slha_io.set_block(\"Tu\", MODELPARAMETER(TYu_slha), \"TYu\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block HMIX Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(Mu)), \"Mu\")\n            << FORMAT_ELEMENT(101, (MODELPARAMETER(BMu)), \"BMu\")\n            << FORMAT_ELEMENT(102, (MODELPARAMETER(vd)), \"vd\")\n            << FORMAT_ELEMENT(103, (MODELPARAMETER(vu)), \"vu\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"MSQ2\", MODELPARAMETER(mq2_slha), \"mq2\", model.get_scale());\n   slha_io.set_block(\"MSE2\", MODELPARAMETER(me2_slha), \"me2\", model.get_scale());\n   slha_io.set_block(\"MSL2\", MODELPARAMETER(ml2_slha), \"ml2\", model.get_scale());\n   slha_io.set_block(\"MSU2\", MODELPARAMETER(mu2_slha), \"mu2\", model.get_scale());\n   slha_io.set_block(\"MSD2\", MODELPARAMETER(md2_slha), \"md2\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block MSOFT Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(21, (MODELPARAMETER(mHd2)), \"mHd2\")\n            << FORMAT_ELEMENT(22, (MODELPARAMETER(mHu2)), \"mHu2\")\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(MassB)), \"MassB\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(MassWB)), \"MassWB\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(MassG)), \"MassG\")\n      ;\n      slha_io.set_block(block);\n   }\n\n   {\n      std::ostringstream block;\n      block << \"Block Phases Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (Re(MODELPARAMETER(PhaseGlu))), \"Re(PhaseGlu)\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block IMPhases Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (Im(MODELPARAMETER(PhaseGlu))), \"Im(PhaseGlu)\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Writes extra SLHA blocks\n *\n * @param model model class\n * @param scales struct of boundary condition scales\n * @param observables struct of observables\n */\ntemplate <class Model>\nvoid NUHMSSM_slha_io::set_extra(\n   const NUHMSSM_slha<Model>& model, const NUHMSSM_scales& scales,\n   const NUHMSSM_observables& observables)\n{\n   const NUHMSSM_physical physical(model.get_physical_slha());\n\n   {\n      std::ostringstream block;\n      block << \"Block FlexibleSUSYLowEnergy Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (OBSERVABLES.a_muon), \"Delta(g-2)_muon/2 FlexibleSUSY\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block EFFHIGGSCOUPLINGS\" << '\\n'\n            << FORMAT_RANK_THREE_TENSOR(25, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon(0))), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(35, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon(1))), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(25, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon(0))), \"Abs(effective H-Gluon-Gluon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(35, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon(1))), \"Abs(effective H-Gluon-Gluon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(36, 22, 22, (Abs(OBSERVABLES.eff_cp_pseudoscalar_photon_photon)), \"Abs(effective A-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(36, 21, 21, (Abs(OBSERVABLES.eff_cp_pseudoscalar_gluon_gluon)), \"Abs(effective A-Gluon-Gluon coupling)\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices of\n * all given models in the SLHA object.\n *\n * @todo Use generic lambda instead of Set_spectrum in C++14\n *\n * @param models model classes\n */\ntemplate <class... Ts>\nvoid NUHMSSM_slha_io::set_spectrum(const std::tuple<Ts...>& models)\n{\n   Set_spectrum<NUHMSSM_slha_io> ss(this);\n   boost::fusion::for_each(models, ss);\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in BPMZ convention\n */\ntemplate <class T>\nvoid NUHMSSM_slha_io::set_spectrum(const NUHMSSM<T>& model)\n{\n   set_spectrum(NUHMSSM_slha<NUHMSSM<T> >(model));\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in SLHA convention\n */\ntemplate <class Model>\nvoid NUHMSSM_slha_io::set_spectrum(const NUHMSSM_slha<Model>& model)\n{\n   const NUHMSSM_physical physical(model.get_physical_slha());\n   const bool write_sm_masses = model.do_calculate_sm_pole_masses();\n\n   set_model_parameters(model);\n   set_mass(physical, write_sm_masses);\n   set_mixing_matrices(physical, write_sm_masses);\n\n   if (slha_io.get_modsel().quark_flavour_violated)\n      set_ckm(model.get_ckm_matrix(), model.get_scale());\n\n   if (slha_io.get_modsel().lepton_flavour_violated)\n      set_pmns(model.get_pmns_matrix(), model.get_scale());\n}\n\n} // namespace flexiblesusy\n\n#undef Pole\n#undef PHYSICAL\n#undef PHYSICAL_SLHA\n#undef LOCALPHYSICAL\n#undef MODEL\n#undef MODELPARAMETER\n#undef EXTRAPARAMETER\n#undef OBSERVABLES\n#undef LowEnergyConstant\n#undef SCALES\n\n#endif\n", "meta": {"hexsha": "eb65f90b010e30ca01358a745450371c81ec8e53", "size": 13029, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_slha_io.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_slha_io.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_slha_io.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.6560693642, "max_line_length": 148, "alphanum_fraction": 0.7113362499, "num_tokens": 3655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.03622005196368367, "lm_q1q2_score": 0.015857989888838204}}
{"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 ADAMANTINE_HH\n#define ADAMANTINE_HH\n\n#include <Geometry.hh>\n#include <PostProcessor.hh>\n#include <ThermalPhysics.hh>\n#include <Timer.hh>\n#include <ensemble_management.hh>\n#include <material_deposition.hh>\n#include <utils.hh>\n\n#include <deal.II/base/mpi.h>\n#include <deal.II/distributed/solution_transfer.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/numerics/error_estimator.h>\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/info_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#ifdef ADAMANTINE_WITH_CALIPER\n#include <caliper/cali.h>\n#endif\n\n#include <cmath>\n#include <iostream>\n\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\nvoid output_pvtu(\n    adamantine::PostProcessor<dim> &post_processor, unsigned int cycle,\n    unsigned int n_time_step, double time,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType>\n        &solution,\n    std::vector<adamantine::Timer> &timers)\n{\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_FUNCTION;\n#endif\n  timers[adamantine::output].start();\n  affine_constraints.distribute(solution);\n  post_processor.output_pvtu(cycle, n_time_step, time, solution);\n  timers[adamantine::output].stop();\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\nvoid output_pvtu(\n    adamantine::PostProcessor<dim> &post_processor, unsigned int cycle,\n    unsigned int n_time_step, double time,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType>\n        &solution,\n    std::vector<adamantine::Timer> &timers)\n{\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_FUNCTION;\n#endif\n  timers[adamantine::output].start();\n  dealii::LinearAlgebra::distributed::Vector<double, dealii::MemorySpace::Host>\n      solution_host(solution.get_partitioner());\n  solution_host.import(solution, dealii::VectorOperation::insert);\n  affine_constraints.distribute(solution_host);\n  post_processor.output_pvtu(cycle, n_time_step, time, solution_host);\n  timers[adamantine::output].stop();\n}\n#endif\n\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\ndealii::Vector<float> estimate_error(\n    dealii::parallel::distributed::Triangulation<dim> const &triangulation,\n    dealii::DoFHandler<dim> const &dof_handler, int fe_degree,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &solution)\n{\n  dealii::Vector<float> estimated_error_per_cell(\n      triangulation.n_active_cells());\n  dealii::KellyErrorEstimator<dim>::estimate(\n      dof_handler, dealii::QGauss<dim - 1>(fe_degree + 1),\n      std::map<dealii::types::boundary_id,\n               const dealii::Function<dim, double> *>(),\n      solution, estimated_error_per_cell, dealii::ComponentMask(), nullptr, 0,\n      triangulation.locally_owned_subdomain());\n\n  return estimated_error_per_cell;\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\ndealii::Vector<float> estimate_error(\n    dealii::parallel::distributed::Triangulation<dim> const &triangulation,\n    dealii::DoFHandler<dim> const &dof_handler, int fe_degree,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &solution)\n{\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>\n      solution_host(solution.get_partitioner());\n  solution_host.import(solution, dealii::VectorOperation::insert);\n  dealii::Vector<float> estimated_error_per_cell(\n      triangulation.n_active_cells());\n  dealii::KellyErrorEstimator<dim>::estimate(\n      dof_handler, dealii::QGauss<dim - 1>(fe_degree + 1),\n      std::map<dealii::types::boundary_id,\n               const dealii::Function<dim, double> *>(),\n      solution_host, estimated_error_per_cell, dealii::ComponentMask(), nullptr,\n      0, triangulation.locally_owned_subdomain());\n\n  return estimated_error_per_cell;\n}\n#endif\n\n// inlining this function so we can have in the header\ninline void initialize_timers(MPI_Comm const &communicator,\n                              std::vector<adamantine::Timer> &timers)\n{\n  timers.push_back(adamantine::Timer(communicator, \"Main\"));\n  timers.push_back(adamantine::Timer(communicator, \"Refinement\"));\n  timers.push_back(adamantine::Timer(communicator, \"Add Material, Search\"));\n  timers.push_back(adamantine::Timer(communicator, \"Add Material, Activate\"));\n  timers.push_back(adamantine::Timer(communicator, \"Evolve One Time Step\"));\n  timers.push_back(adamantine::Timer(\n      communicator, \"Evolve One Time Step: evaluate_thermal_physics\"));\n  timers.push_back(adamantine::Timer(\n      communicator, \"Evolve One Time Step: id_minus_tau_J_inverse\"));\n  timers.push_back(adamantine::Timer(\n      communicator, \"Evolve One Time Step: evaluate_material_properties\"));\n  timers.push_back(adamantine::Timer(communicator, \"Output\"));\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nstd::vector<std::shared_ptr<adamantine::HeatSource<dim>>> &initialize(\n    MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    adamantine::Geometry<dim> &geometry,\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics)\n{\n  thermal_physics.reset(\n      new adamantine::ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                                     QuadratureType>(communicator, database,\n                                                     geometry));\n  return static_cast<adamantine::ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                                                QuadratureType> *>(\n             thermal_physics.get())\n      ->get_heat_sources();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nstd::vector<std::shared_ptr<adamantine::HeatSource<dim>>> &\ninitialize_quadrature(\n    std::string const &quadrature_type, MPI_Comm const &communicator,\n    boost::property_tree::ptree const &database,\n    adamantine::Geometry<dim> &geometry,\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics)\n{\n  if (quadrature_type.compare(\"gauss\") == 0)\n    return initialize<dim, fe_degree, MemorySpaceType, dealii::QGauss<1>>(\n        communicator, database, geometry, thermal_physics);\n  else\n  {\n    adamantine::ASSERT_THROW(quadrature_type.compare(\"lobatto\") == 0,\n                             \"quadrature should be Gauss or Lobatto.\");\n    return initialize<dim, fe_degree, MemorySpaceType,\n                      dealii::QGaussLobatto<1>>(communicator, database,\n                                                geometry, thermal_physics);\n  }\n}\n\ntemplate <int dim, typename MemorySpaceType>\nstd::vector<std::shared_ptr<adamantine::HeatSource<dim>>> &\ninitialize_thermal_physics(\n    unsigned int fe_degree, std::string const &quadrature_type,\n    MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    adamantine::Geometry<dim> &geometry,\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics)\n{\n  switch (fe_degree)\n  {\n  case 1:\n  {\n    return initialize_quadrature<dim, 1, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 2:\n  {\n    return initialize_quadrature<dim, 2, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 3:\n  {\n    return initialize_quadrature<dim, 3, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 4:\n  {\n    return initialize_quadrature<dim, 4, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 5:\n  {\n    return initialize_quadrature<dim, 5, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 6:\n  {\n    return initialize_quadrature<dim, 6, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 7:\n  {\n    return initialize_quadrature<dim, 7, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 8:\n  {\n    return initialize_quadrature<dim, 8, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 9:\n  {\n    return initialize_quadrature<dim, 9, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  default:\n  {\n    adamantine::ASSERT_THROW(fe_degree == 10,\n                             \"fe_degree should be between 1 and 10.\");\n    return initialize_quadrature<dim, 10, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  }\n}\n\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\nvoid refine_and_transfer(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::DoFHandler<dim> &dof_handler,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution)\n{\n  dealii::parallel::distributed::Triangulation<dim> &triangulation =\n      dynamic_cast<dealii::parallel::distributed::Triangulation<dim> &>(\n          const_cast<dealii::Triangulation<dim> &>(\n              dof_handler.get_triangulation()));\n\n  std::shared_ptr<adamantine::MaterialProperty<dim>> material_property =\n      thermal_physics->get_material_property();\n\n  dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, MemorySpaceType>>\n      solution_transfer(dof_handler);\n  std::vector<dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, MemorySpaceType>>>\n      material_state(\n          static_cast<unsigned int>(adamantine::MaterialState::SIZE),\n          dealii::parallel::distributed::SolutionTransfer<\n              dim, dealii::LA::distributed::Vector<double, MemorySpaceType>>(\n              material_property->get_dof_handler()));\n\n  // We need to update the ghost values before we can do the interpolation on\n  // the new mesh.\n  solution.update_ghost_values();\n\n  // Prepare the Triangulation and the diffent SolutionTransfers for refinement\n  triangulation.prepare_coarsening_and_refinement();\n  solution_transfer.prepare_for_coarsening_and_refinement(solution);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].prepare_for_coarsening_and_refinement(\n        material_property->get_state()[i]);\n\n  // Execute the refinement\n  triangulation.execute_coarsening_and_refinement();\n\n  // Update the AffineConstraints and resize the solution\n  thermal_physics->setup_dofs();\n  thermal_physics->initialize_dof_vector(solution);\n\n  // Update MaterialProperty DoFHandler and resize the state vectors\n  material_property->reinit_dofs();\n\n  // Interpolate the solution and the state onto the new mesh\n  solution_transfer.interpolate(solution);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].interpolate(material_property->get_state()[i]);\n\n#if ADAMANTINE_DEBUG\n  // Check that we are not losing material\n  std::array<dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>,\n             static_cast<unsigned int>(adamantine::MaterialState::SIZE)>\n      state = material_property->get_state();\n  unsigned int const local_size = state[0].locally_owned_size();\n  unsigned int constexpr n_material_states =\n      static_cast<unsigned int>(adamantine::MaterialState::SIZE);\n  for (unsigned int i = 0; i < local_size; ++i)\n  {\n    double material_ratio = 0.;\n    for (unsigned int j = 0; j < n_material_states; ++j)\n      material_ratio += state[j].local_element(i);\n    adamantine::ASSERT(std::abs(material_ratio - 1.) < 1e-14,\n                       \"Material is lost.\");\n  }\n#endif\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\nvoid refine_and_transfer(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::DoFHandler<dim> &dof_handler,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution)\n{\n  dealii::parallel::distributed::Triangulation<dim> &triangulation =\n      dynamic_cast<dealii::parallel::distributed::Triangulation<dim> &>(\n          const_cast<dealii::Triangulation<dim> &>(\n              dof_handler.get_triangulation()));\n\n  // Update the material state from the ThermalOperator to MaterialProperty\n  // because, for now, we need to use state from MaterialProperty to perform the\n  // transfer to the refined mesh.\n  thermal_physics->set_state_to_material_properties();\n  std::shared_ptr<adamantine::MaterialProperty<dim>> material_property =\n      thermal_physics->get_material_property();\n\n  dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>>\n      solution_transfer(dof_handler);\n  std::vector<dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>>>\n      material_state(\n          static_cast<unsigned int>(adamantine::MaterialState::SIZE),\n          dealii::parallel::distributed::SolutionTransfer<\n              dim, dealii::LA::distributed::Vector<double,\n                                                   dealii::MemorySpace::Host>>(\n              material_property->get_dof_handler()));\n\n  // We need to update the ghost values before we can do the interpolation on\n  // the new mesh.\n  solution.update_ghost_values();\n\n  // Prepare the Triangulation and the diffent SolutionTransfers for refinement\n  triangulation.prepare_coarsening_and_refinement();\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>\n      solution_host(solution.get_partitioner());\n  solution_host.import(solution, dealii::VectorOperation::insert);\n  solution_transfer.prepare_for_coarsening_and_refinement(solution_host);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].prepare_for_coarsening_and_refinement(\n        material_property->get_state()[i]);\n\n  // Execute the refinement\n  triangulation.execute_coarsening_and_refinement();\n\n  // Update MaterialProperty DoFHandler and resize the state vectors\n  material_property->reinit_dofs();\n\n  // Update the AffineConstraints and resize the solution\n  thermal_physics->setup_dofs();\n  thermal_physics->initialize_dof_vector(solution);\n  solution_host.reinit(solution.get_partitioner());\n\n  // Interpolate the solution and the state onto the new mesh\n  solution_transfer.interpolate(solution_host);\n  solution.import(solution_host, dealii::VectorOperation::insert);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].interpolate(material_property->get_state()[i]);\n  // Update the material states in the ThermalOperator\n  thermal_physics->get_state_from_material_properties();\n\n#if ADAMANTINE_DEBUG\n  // Check that we are not losing material\n  std::array<dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>,\n             static_cast<unsigned int>(adamantine::MaterialState::SIZE)>\n      state = material_property->get_state();\n  unsigned int const local_size = state[0].locally_owned_size();\n  unsigned int constexpr n_material_states =\n      static_cast<unsigned int>(adamantine::MaterialState::SIZE);\n  for (unsigned int i = 0; i < local_size; ++i)\n  {\n    double material_ratio = 0.;\n    for (unsigned int j = 0; j < n_material_states; ++j)\n      material_ratio += state[j].local_element(i);\n    adamantine::ASSERT(std::abs(material_ratio - 1.) < 1e-14,\n                       \"Material is lost.\");\n  }\n#endif\n}\n#endif\n\ntemplate <int dim>\nstd::vector<typename dealii::parallel::distributed::Triangulation<\n    dim>::active_cell_iterator>\ncompute_cells_to_refine(\n    dealii::parallel::distributed::Triangulation<dim> &triangulation,\n    double const time, double const next_refinement_time,\n    unsigned int const n_time_steps,\n    std::vector<std::shared_ptr<adamantine::HeatSource<dim>>> &heat_sources,\n    double const current_source_height, double const refinement_beam_cutoff)\n{\n\n  // Compute the position of the beams between time and next_refinement_time and\n  // refine the mesh where the source is greater than refinement_beam_cutoff.\n  // This cut-off is due to the fact that the source is gaussian and thus never\n  // strictly zero. If the beams intersect, some cells will appear twice in the\n  // vector. This is not a problem.\n  std::vector<typename dealii::parallel::distributed::Triangulation<\n      dim>::active_cell_iterator>\n      cells_to_refine;\n  for (unsigned int i = 0; i < n_time_steps; ++i)\n  {\n    double const current_time = time + static_cast<double>(i) /\n                                           static_cast<double>(n_time_steps) *\n                                           (next_refinement_time - time);\n    for (auto &beam : heat_sources)\n    {\n      for (auto cell : dealii::filter_iterators(\n               triangulation.active_cell_iterators(),\n               dealii::IteratorFilters::LocallyOwnedCell()))\n      {\n        if (beam->value(cell->center(), current_time, current_source_height) >\n            refinement_beam_cutoff)\n        {\n          cells_to_refine.push_back(cell);\n        }\n      }\n    }\n  }\n\n  return cells_to_refine;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid refine_mesh(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution,\n    std::vector<std::shared_ptr<adamantine::HeatSource<dim>>> &heat_sources,\n    double const time, double const next_refinement_time,\n    unsigned int const time_steps_refinement,\n    boost::property_tree::ptree const &refinement_database)\n{\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_FUNCTION;\n#endif\n  dealii::DoFHandler<dim> &dof_handler = thermal_physics->get_dof_handler();\n  // Use the Kelly error estimator to refine the mesh. This is done so that the\n  // part of the domain that were heated stay refined.\n  // PropertyTreeInput refinement.n_heat_refinements\n  unsigned int const n_kelly_refinements =\n      refinement_database.get(\"n_heat_refinements\", 2);\n  double coarsening_fraction = 0.3;\n  double refining_fraction = 0.6;\n  // PropertyTreeInput refinement.heat_cell_ratio\n  double cells_fraction = refinement_database.get(\"heat_cell_ratio\", 1.);\n  dealii::parallel::distributed::Triangulation<dim> &triangulation =\n      dynamic_cast<dealii::parallel::distributed::Triangulation<dim> &>(\n          const_cast<dealii::Triangulation<dim> &>(\n              dof_handler.get_triangulation()));\n  // Number of times the mesh on the beam paths will be refined and maximum\n  // number of time a cell can be refined.\n  // PropertyTreeInput refinement.n_beam_refinements\n  unsigned int const n_beam_refinements =\n      refinement_database.get(\"n_beam_refinements\", 2);\n  // PropertyTreeInput refinement.max_level\n  int max_level = refinement_database.get<int>(\"max_level\");\n\n  // PropertyTreeInput refinement.beam_cutoff\n  const double refinement_beam_cutoff =\n      refinement_database.get<double>(\"beam_cutoff\", 1.0e-15);\n\n  for (unsigned int i = 0; i < n_kelly_refinements; ++i)\n  {\n    // Estimate the error. For simplicity, always use dealii::QGauss\n    dealii::Vector<float> estimated_error_per_cell =\n        estimate_error(triangulation, dof_handler, fe_degree, solution);\n\n    // Flag the cells for refinement.\n    unsigned int new_n_cells = static_cast<unsigned int>(\n        cells_fraction *\n        static_cast<double>(triangulation.n_global_active_cells()));\n    dealii::GridRefinement::refine_and_coarsen_fixed_fraction(\n        triangulation, estimated_error_per_cell, refining_fraction,\n        coarsening_fraction, new_n_cells);\n\n    // Don't refine cells that are already as much refined as it is allowed.\n    for (auto cell :\n         dealii::filter_iterators(triangulation.active_cell_iterators(),\n                                  dealii::IteratorFilters::LocallyOwnedCell()))\n      if (cell->level() >= max_level)\n        cell->clear_refine_flag();\n\n    // Execute the refinement and transfer the solution onto the new mesh.\n    refine_and_transfer(thermal_physics, dof_handler, solution);\n  }\n\n  // Refine the mesh along the trajectory of the sources.\n  double current_source_height =\n      dynamic_cast<adamantine::ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                                              dealii::QGauss<1>> *>(\n          thermal_physics.get())\n          ? dynamic_cast<adamantine::ThermalPhysics<\n                dim, fe_degree, MemorySpaceType, dealii::QGauss<1>> *>(\n                thermal_physics.get())\n                ->get_current_source_height()\n          : dynamic_cast<adamantine::ThermalPhysics<\n                dim, fe_degree, MemorySpaceType, dealii::QGaussLobatto<1>> *>(\n                thermal_physics.get())\n                ->get_current_source_height();\n\n  for (unsigned int i = 0; i < n_beam_refinements; ++i)\n  {\n    // Compute the cells to be refined.\n    std::vector<typename dealii::parallel::distributed::Triangulation<\n        dim>::active_cell_iterator>\n        cells_to_refine = compute_cells_to_refine(\n            triangulation, time, next_refinement_time, time_steps_refinement,\n            heat_sources, current_source_height, refinement_beam_cutoff);\n\n    // PropertyTreeInput refinement.coarsen_after_beam\n    const bool coarsen_after_beam =\n        refinement_database.get<bool>(\"coarsen_after_beam\", false);\n\n    // If coarsening is allowed, set the coarsening flag everywhere\n    if (coarsen_after_beam)\n    {\n      for (auto cell : dealii::filter_iterators(\n               triangulation.active_cell_iterators(),\n               dealii::IteratorFilters::LocallyOwnedCell()))\n      {\n        if (cell->level() > 0)\n          cell->set_coarsen_flag();\n      }\n    }\n\n    // Flag the cells for refinement.\n    for (auto &cell : cells_to_refine)\n    {\n      if (coarsen_after_beam)\n        cell->clear_coarsen_flag();\n      if (cell->level() < max_level)\n        cell->set_refine_flag();\n    }\n\n    // Execute the refinement and transfer the solution onto the new mesh.\n    refine_and_transfer(thermal_physics, dof_handler, solution);\n  }\n\n  // Recompute the inverse of the mass matrix\n  thermal_physics->compute_inverse_mass_matrix();\n}\n\ntemplate <int dim, typename MemorySpaceType>\nvoid refine_mesh(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution,\n    std::vector<std::shared_ptr<adamantine::HeatSource<dim>>> &heat_sources,\n    double const time, double const next_refinement_time,\n    unsigned int const time_steps_refinement,\n    boost::property_tree::ptree const &refinement_database,\n    unsigned int const fe_degree)\n{\n  switch (fe_degree)\n  {\n  case 1:\n  {\n    refine_mesh<dim, 1>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 2:\n  {\n    refine_mesh<dim, 2>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 3:\n  {\n    refine_mesh<dim, 3>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 4:\n  {\n    refine_mesh<dim, 4>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 5:\n  {\n    refine_mesh<dim, 5>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 6:\n  {\n    refine_mesh<dim, 6>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 7:\n  {\n    refine_mesh<dim, 7>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 8:\n  {\n    refine_mesh<dim, 8>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 9:\n  {\n    refine_mesh<dim, 9>(thermal_physics, solution, heat_sources, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 10:\n  {\n    refine_mesh<dim, 10>(thermal_physics, solution, heat_sources, time,\n                         next_refinement_time, time_steps_refinement,\n                         refinement_database);\n    break;\n  }\n  default:\n  {\n    adamantine::ASSERT_THROW(false, \"fe_degree should be between 1 and 10.\");\n  }\n  }\n}\n\ntemplate <int dim, typename MemorySpaceType>\ndealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType>\nrun(MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    std::vector<adamantine::Timer> &timers)\n{\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_FUNCTION;\n#endif\n\n  // Extract property tree children\n  boost::property_tree::ptree geometry_database =\n      database.get_child(\"geometry\");\n  boost::property_tree::ptree discretization_database =\n      database.get_child(\"discretization\");\n  boost::property_tree::ptree time_stepping_database =\n      database.get_child(\"time_stepping\");\n  boost::property_tree::ptree post_processor_database =\n      database.get_child(\"post_processor\");\n  boost::property_tree::ptree refinement_database =\n      database.get_child(\"refinement\");\n\n  // PropertyTreeInput discretization.fe_degree\n  unsigned int const fe_degree =\n      discretization_database.get<unsigned int>(\"fe_degree\");\n  // PropertyTreeInput discretization.quadrature\n  std::string quadrature_type =\n      discretization_database.get(\"quadrature\", \"gauss\");\n  std::transform(quadrature_type.begin(), quadrature_type.end(),\n                 quadrature_type.begin(),\n                 [](unsigned char c) { return std::tolower(c); });\n  // PropertyTreeInput materials.initial_temperature\n  double const initial_temperature =\n      database.get(\"materials.initial_temperature\", 300.);\n  // PropertyTreeInput materials.new_material_temperature\n  double const new_material_temperature =\n      database.get(\"materials.new_material_temperature\", 300.);\n  adamantine::Geometry<dim> geometry(communicator, geometry_database);\n\n  std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> thermal_physics;\n  std::vector<std::shared_ptr<adamantine::HeatSource<dim>>> &heat_sources =\n      initialize_thermal_physics<dim>(fe_degree, quadrature_type, communicator,\n                                      database, geometry, thermal_physics);\n\n  adamantine::PostProcessor<dim> post_processor(\n      communicator, post_processor_database, thermal_physics->get_dof_handler(),\n      thermal_physics->get_material_property());\n\n  thermal_physics->setup_dofs();\n  thermal_physics->compute_inverse_mass_matrix();\n  dealii::LA::distributed::Vector<double, MemorySpaceType> solution;\n  thermal_physics->initialize_dof_vector(initial_temperature, solution);\n  thermal_physics->get_state_from_material_properties();\n\n  unsigned int progress = 0;\n  unsigned int cycle = 0;\n  unsigned int n_time_step = 0;\n  double time = 0.;\n  // Output the initial solution\n  dealii::AffineConstraints<double> &affine_constraints =\n      thermal_physics->get_affine_constraints();\n  output_pvtu(post_processor, cycle, n_time_step, time, affine_constraints,\n              solution, timers);\n  ++n_time_step;\n\n  // PropertyTreeInput refinement.verbose\n  bool const verbose_refinement = refinement_database.get(\"verbose\", false);\n  // PropertyTreeInput refinement.time_steps_between_refinement\n  unsigned int const time_steps_refinement =\n      refinement_database.get(\"time_steps_between_refinement\", 10);\n  double next_refinement_time = time;\n  // PropertyTreeInput time_stepping.time_step\n  double time_step = time_stepping_database.get<double>(\"time_step\");\n  // PropertyTreeInput time_stepping.duration\n  double const duration = time_stepping_database.get<double>(\"duration\");\n  // PropertyTreeInput post_processor.time_steps_between_output\n  unsigned int const time_steps_output =\n      post_processor_database.get(\"time_steps_between_output\", 1);\n\n  auto [material_deposition_boxes, deposition_times] =\n      adamantine::create_material_deposition_boxes<dim>(geometry_database,\n                                                        heat_sources);\n\n  // Unless we use an embedded method, we know in advance the time step.\n\n  // Thus we can get for each time step, the list of elements that we will need\n  // to activate. This list will be invalidated every time we refine the mesh.\n  timers[adamantine::add_material_search].start();\n\n  auto elements_to_activate = adamantine::get_elements_to_activate(\n      thermal_physics->get_dof_handler(), material_deposition_boxes);\n  timers[adamantine::add_material_search].stop();\n\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_LOOP_BEGIN(main_loop_id, \"main_loop\");\n#endif\n  while (time < duration)\n  {\n#ifdef ADAMANTINE_WITH_CALIPER\n    CALI_CXX_MARK_LOOP_ITERATION(main_loop_id, n_time_step - 1);\n#endif\n    if ((time + time_step) > duration)\n      time_step = duration - time;\n    unsigned int rank = dealii::Utilities::MPI::this_mpi_process(communicator);\n\n    // Refine the mesh after time_steps_refinement time steps or when time\n    // is greater or equal than the next predicted time for refinement. This\n    // is necessary when using an embedded method.\n    if (((n_time_step % time_steps_refinement) == 0) ||\n        (time >= next_refinement_time))\n    {\n      next_refinement_time = time + time_steps_refinement * time_step;\n      timers[adamantine::refine].start();\n      refine_mesh(thermal_physics, solution, heat_sources, time,\n                  next_refinement_time, time_steps_refinement,\n                  refinement_database, fe_degree);\n      timers[adamantine::refine].stop();\n      if ((rank == 0) && (verbose_refinement == true))\n        std::cout << \"n_dofs: \" << thermal_physics->get_dof_handler().n_dofs()\n                  << std::endl;\n\n      timers[adamantine::add_material_search].start();\n      elements_to_activate = adamantine::get_elements_to_activate(\n          thermal_physics->get_dof_handler(), material_deposition_boxes);\n      timers[adamantine::add_material_search].stop();\n    }\n\n    // Add material if necessary.\n\n    // We use an epsilon to get the \"expected\" behavior when the deposition time\n    // and the time match should match exactly but don't because of floating\n    // point accuracy.\n    timers[adamantine::add_material_activate].start();\n\n    double const eps = time_step / 1e12;\n    auto activation_start =\n        std::lower_bound(deposition_times.begin(), deposition_times.end(),\n                         time - eps) -\n        deposition_times.begin();\n    auto activation_end =\n        std::lower_bound(deposition_times.begin(), deposition_times.end(),\n                         time + time_step - eps) -\n        deposition_times.begin();\n    for (unsigned int i = activation_start; i < activation_end; ++i)\n      thermal_physics->add_material(elements_to_activate[i],\n                                    new_material_temperature, solution);\n\n    if ((rank == 0) && (verbose_refinement == true) &&\n        (activation_end - activation_start > 0))\n      std::cout << \"n_dofs: \" << thermal_physics->get_dof_handler().n_dofs()\n                << std::endl;\n    // Remove elements that have been activated\n    elements_to_activate.erase(elements_to_activate.begin() + activation_start,\n                               elements_to_activate.begin() + activation_end);\n    deposition_times.erase(deposition_times.begin() + activation_start,\n                           deposition_times.begin() + activation_end);\n\n    material_deposition_boxes.erase(\n        material_deposition_boxes.begin() + activation_start,\n        material_deposition_boxes.begin() + activation_end);\n\n    timers[adamantine::add_material_activate].stop();\n\n    // Time can be different than time + time_step if an embedded scheme is\n    // used. Note that this is a problem when adding material because it\n    // means that the amount of material that needs to be added is not\n    // known.\n#if ADAMANTINE_DEBUG\n    double const old_time = time;\n    bool const adding_material =\n        (activation_start == activation_end) ? false : true;\n#endif\n    timers[adamantine::evol_time].start();\n    time = thermal_physics->evolve_one_time_step(time, time_step, solution,\n                                                 timers);\n#if ADAMANTINE_DEBUG\n    adamantine::ASSERT(!adding_material ||\n                           ((time - old_time) < time_step / 1e-9),\n                       \"Unexpected time step while adding material.\");\n#endif\n    timers[adamantine::evol_time].stop();\n\n    // Get the new time step\n    time_step = thermal_physics->get_delta_t_guess();\n\n    // Output progress on screen\n    if (rank == 0)\n    {\n      double adim_time = time / (duration / 10.);\n      double int_part = 0;\n      std::modf(adim_time, &int_part);\n      if (int_part > progress)\n      {\n        std::cout << int_part * 10 << '%' << \" completed\" << std::endl;\n        ++progress;\n      }\n    }\n\n    // Output the solution\n    if (n_time_step % time_steps_output == 0)\n    {\n      thermal_physics->set_state_to_material_properties();\n      output_pvtu(post_processor, cycle, n_time_step, time, affine_constraints,\n                  solution, timers);\n    }\n    ++n_time_step;\n  }\n\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_LOOP_END(main_loop_id);\n#endif\n\n  post_processor.output_pvd();\n\n  // This is only used for integration test\n  return solution;\n}\n\ntemplate <int dim, typename MemorySpaceType>\nstd::vector<dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType>>\nrun_ensemble(MPI_Comm const &communicator,\n             boost::property_tree::ptree const &database,\n             std::vector<adamantine::Timer> &timers)\n{\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_FUNCTION;\n#endif\n\n  // Extract property tree children\n  boost::property_tree::ptree geometry_database =\n      database.get_child(\"geometry\");\n  boost::property_tree::ptree discretization_database =\n      database.get_child(\"discretization\");\n  boost::property_tree::ptree time_stepping_database =\n      database.get_child(\"time_stepping\");\n  boost::property_tree::ptree post_processor_database =\n      database.get_child(\"post_processor\");\n  boost::property_tree::ptree refinement_database =\n      database.get_child(\"refinement\");\n  boost::property_tree::ptree ensemble_database =\n      database.get_child(\"ensemble\");\n\n  // PropertyTreeInput discretization.fe_degree\n  unsigned int const fe_degree =\n      discretization_database.get<unsigned int>(\"fe_degree\");\n  // PropertyTreeInput discretization.quadrature\n  std::string quadrature_type =\n      discretization_database.get(\"quadrature\", \"gauss\");\n  std::transform(quadrature_type.begin(), quadrature_type.end(),\n                 quadrature_type.begin(),\n                 [](unsigned char c) { return std::tolower(c); });\n\n  // PropertyTreeInput materials.initial_temperature\n  double const initial_temperature =\n      database.get(\"materials.initial_temperature\", 300.);\n  // Get the nominal (mean) values of the ensemble parameters\n  // PropertyTreeInput materials.new_material_temperature\n  double const new_material_temperature_mean =\n      database.get(\"materials.new_material_temperature\", 300.);\n\n  // PropertyTreeInput sources.n_beams\n  unsigned int const n_beams = database.get<unsigned int>(\"sources.n_beams\");\n  double beam_0_max_power_mean;\n  if (n_beams > 0)\n  {\n    // PropertyTreeInput sources.beam_0.max_power\n    beam_0_max_power_mean = database.get<double>(\"sources.beam_0.max_power\");\n  }\n  else\n  {\n    beam_0_max_power_mean = 0;\n  }\n\n  // Set up the ensemble members\n  // There might be a more efficient way to share some of these objects between\n  // ensemble members. For now, we'll do the simpler approach of duplicating\n  // everything.\n  // PropertyTreeInput ensemble.ensemble_size\n  const unsigned int ensemble_size = ensemble_database.get(\"ensemble_size\", 5);\n\n  // PropertyTreeInput ensemble.new_material_temperature_stddev\n  const double new_material_temperature_stddev =\n      ensemble_database.get(\"new_material_temperature_stddev\", 0.0);\n\n  std::vector<double> new_material_temperature =\n      adamantine::fill_and_sync_random_vector(ensemble_size,\n                                              new_material_temperature_mean,\n                                              new_material_temperature_stddev);\n\n  // PropertyTreeInput ensemble.beam_0_max_power_stddev\n  const double beam_0_max_power_stddev =\n      ensemble_database.get(\"beam_0_max_power_stddev\", 0.0);\n\n  std::vector<double> beam_0_max_power =\n      adamantine::fill_and_sync_random_vector(\n          ensemble_size, beam_0_max_power_mean, beam_0_max_power_stddev);\n\n  // Create a new property tree database for each ensemble member\n  std::vector<boost::property_tree::ptree> database_ensemble(ensemble_size,\n                                                             database);\n\n  std::vector<std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>>>\n      thermal_physics_ensemble(ensemble_size);\n\n  std::vector<std::vector<std::shared_ptr<adamantine::HeatSource<dim>>>>\n      heat_sources_ensemble(ensemble_size);\n\n  std::vector<dealii::LA::distributed::Vector<double, MemorySpaceType>>\n      solution_ensemble(ensemble_size);\n\n  std::vector<std::unique_ptr<adamantine::Geometry<dim>>> geometry_ensemble;\n\n  std::vector<std::unique_ptr<adamantine::PostProcessor<dim>>>\n      post_processor_ensemble;\n\n  for (unsigned int member = 0; member < ensemble_size; ++member)\n  {\n    // Edit the database for the ensemble\n    if (n_beams > 0)\n    {\n      // PropertyTreeInput sources.beam_0.max_power\n      database_ensemble[member].put(\"sources.beam_0.max_power\",\n                                    beam_0_max_power[member]);\n    }\n\n    geometry_ensemble.push_back(std::make_unique<adamantine::Geometry<dim>>(\n        communicator, geometry_database));\n\n    heat_sources_ensemble[member] = initialize_thermal_physics<dim>(\n        fe_degree, quadrature_type, communicator, database_ensemble[member],\n        *geometry_ensemble[member], thermal_physics_ensemble[member]);\n\n    thermal_physics_ensemble[member]->setup_dofs();\n    thermal_physics_ensemble[member]->compute_inverse_mass_matrix();\n\n    thermal_physics_ensemble[member]->initialize_dof_vector(\n        initial_temperature, solution_ensemble[member]);\n    thermal_physics_ensemble[member]->get_state_from_material_properties();\n\n    post_processor_ensemble.push_back(\n        std::make_unique<adamantine::PostProcessor<dim>>(\n            communicator, post_processor_database,\n            thermal_physics_ensemble[member]->get_dof_handler(),\n            thermal_physics_ensemble[member]->get_material_property(), member));\n  }\n\n  unsigned int progress = 0;\n  unsigned int cycle = 0;\n  unsigned int n_time_step = 0;\n  double time = 0.;\n\n  // Output the initial solution\n  std::vector<dealii::AffineConstraints<double>> affine_constraints_ensemble;\n  for (unsigned int member = 0; member < ensemble_size; ++member)\n  {\n    affine_constraints_ensemble.push_back(\n        thermal_physics_ensemble[member]->get_affine_constraints());\n\n    output_pvtu(*post_processor_ensemble[member], cycle, n_time_step, time,\n                affine_constraints_ensemble[member], solution_ensemble[member],\n                timers);\n  }\n\n  // Increment the time step\n  ++n_time_step;\n\n  // PropertyTreeInput refinement.verbose\n  bool const verbose_refinement = refinement_database.get(\"verbose\", false);\n  // PropertyTreeInput refinement.time_steps_between_refinement\n  unsigned int const time_steps_refinement =\n      refinement_database.get(\"time_steps_between_refinement\", 10);\n  double next_refinement_time = time;\n  // PropertyTreeInput time_stepping.time_step\n  double time_step = time_stepping_database.get<double>(\"time_step\");\n  // PropertyTreeInput time_stepping.duration\n  double const duration = time_stepping_database.get<double>(\"duration\");\n  // PropertyTreeInput post_processor.time_steps_between_output\n  unsigned int const time_steps_output =\n      post_processor_database.get(\"time_steps_between_output\", 1);\n\n  // For now assume that all ensemble members share the same geometry (they have\n  // independent adamantine::Geometry objects, but all are constructed from\n  // identical parameters), base new additions on the 0th ensemble member\n  auto [material_deposition_boxes, deposition_times] =\n      adamantine::create_material_deposition_boxes<dim>(\n          geometry_database, heat_sources_ensemble[0]);\n\n  // Unless we use an embedded method, we know in advance the time step.\n\n  // Thus we can get for each time step, the list of elements that we will need\n  // to activate. This list will be invalidated every time we refine the mesh.\n  timers[adamantine::add_material_search].start();\n\n  auto elements_to_activate = adamantine::get_elements_to_activate(\n      thermal_physics_ensemble[0]->get_dof_handler(),\n      material_deposition_boxes);\n  timers[adamantine::add_material_search].stop();\n\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_LOOP_BEGIN(main_loop_id, \"main_loop\");\n#endif\n  while (time < duration)\n  {\n\n#ifdef ADAMANTINE_WITH_CALIPER\n    CALI_CXX_MARK_LOOP_ITERATION(main_loop_id, n_time_step - 1);\n#endif\n    if ((time + time_step) > duration)\n      time_step = duration - time;\n    unsigned int rank = dealii::Utilities::MPI::this_mpi_process(communicator);\n\n    // Refine the mesh after time_steps_refinement time steps or when time\n    // is greater or equal than the next predicted time for refinement. This\n    // is necessary when using an embedded method.\n    if (((n_time_step % time_steps_refinement) == 0) ||\n        (time >= next_refinement_time))\n    {\n      next_refinement_time = time + time_steps_refinement * time_step;\n      timers[adamantine::refine].start();\n\n      for (unsigned int member = 0; member < ensemble_size; ++member)\n      {\n        refine_mesh(thermal_physics_ensemble[member], solution_ensemble[member],\n                    heat_sources_ensemble[member], time, next_refinement_time,\n                    time_steps_refinement, refinement_database, fe_degree);\n      }\n      timers[adamantine::refine].stop();\n      if ((rank == 0) && (verbose_refinement == true))\n        std::cout << \"n_dofs: \"\n                  << thermal_physics_ensemble[0]->get_dof_handler().n_dofs()\n                  << std::endl;\n\n      timers[adamantine::add_material_search].start();\n      elements_to_activate = adamantine::get_elements_to_activate(\n          thermal_physics_ensemble[0]->get_dof_handler(),\n          material_deposition_boxes);\n      timers[adamantine::add_material_search].stop();\n    }\n\n    // Add material if necessary.\n\n    // We use an epsilon to get the \"expected\" behavior when the deposition time\n    // and the time match should match exactly but don't because of floating\n    // point accuracy.\n    timers[adamantine::add_material_activate].start();\n\n    double const eps = time_step / 1e12;\n    auto activation_start =\n        std::lower_bound(deposition_times.begin(), deposition_times.end(),\n                         time - eps) -\n        deposition_times.begin();\n    auto activation_end =\n        std::lower_bound(deposition_times.begin(), deposition_times.end(),\n                         time + time_step - eps) -\n        deposition_times.begin();\n    for (unsigned int i = activation_start; i < activation_end; ++i)\n    {\n      for (unsigned int member = 0; member < ensemble_size; ++member)\n      {\n        thermal_physics_ensemble[member]->add_material(\n            elements_to_activate[i], new_material_temperature[member],\n            solution_ensemble[member]);\n      }\n    }\n\n    if ((rank == 0) && (verbose_refinement == true) &&\n        (activation_end - activation_start > 0))\n      std::cout << \"n_dofs: \"\n                << thermal_physics_ensemble[0]->get_dof_handler().n_dofs()\n                << std::endl;\n    // Remove elements that have been activated\n    elements_to_activate.erase(elements_to_activate.begin() + activation_start,\n                               elements_to_activate.begin() + activation_end);\n    deposition_times.erase(deposition_times.begin() + activation_start,\n                           deposition_times.begin() + activation_end);\n\n    material_deposition_boxes.erase(\n        material_deposition_boxes.begin() + activation_start,\n        material_deposition_boxes.begin() + activation_end);\n\n    timers[adamantine::add_material_activate].stop();\n\n    // Time can be different than time + time_step if an embedded scheme is\n    // used. Note that this is a problem when adding material because it\n    // means that the amount of material that needs to be added is not\n    // known.\n#if ADAMANTINE_DEBUG\n    double const old_time = time;\n    bool const adding_material =\n        (activation_start == activation_end) ? false : true;\n#endif\n    timers[adamantine::evol_time].start();\n    for (unsigned int member = 0; member < ensemble_size; ++member)\n    {\n      time = thermal_physics_ensemble[member]->evolve_one_time_step(\n          time, time_step, solution_ensemble[member], timers);\n    }\n#if ADAMANTINE_DEBUG\n    adamantine::ASSERT(!adding_material ||\n                           ((time - old_time) < time_step / 1e-9),\n                       \"Unexpected time step while adding material.\");\n#endif\n    timers[adamantine::evol_time].stop();\n\n    // Get the new time step (needs to be the same for all ensemble members,\n    // obtained from the 0th member)\n    time_step = thermal_physics_ensemble[0]->get_delta_t_guess();\n\n    // Output progress on screen\n    if (rank == 0)\n    {\n      double adim_time = time / (duration / 10.);\n      double int_part = 0;\n      std::modf(adim_time, &int_part);\n      if (int_part > progress)\n      {\n        std::cout << int_part * 10 << '%' << \" completed\" << std::endl;\n        ++progress;\n      }\n    }\n\n    // Output the solution\n    if (n_time_step % time_steps_output == 0)\n    {\n      for (unsigned int member = 0; member < ensemble_size; ++member)\n      {\n        thermal_physics_ensemble[member]->set_state_to_material_properties();\n        output_pvtu(*post_processor_ensemble[member], cycle, n_time_step, time,\n                    affine_constraints_ensemble[member],\n                    solution_ensemble[member], timers);\n      }\n    }\n\n    ++n_time_step;\n  }\n\n#ifdef ADAMANTINE_WITH_CALIPER\n  CALI_CXX_MARK_LOOP_END(main_loop_id);\n#endif\n\n  for (unsigned int member = 0; member < ensemble_size; ++member)\n  {\n    post_processor_ensemble[member]->output_pvd();\n  }\n\n  // This is only used for integration test\n  return solution_ensemble;\n}\n#endif\n", "meta": {"hexsha": "90e4b6d1bcf8186f46df8c0756be96c8e62ee892", "size": 48446, "ext": "hh", "lang": "C++", "max_stars_repo_path": "application/adamantine.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": "application/adamantine.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": "application/adamantine.hh", "max_forks_repo_name": "Rombur/adamantine", "max_forks_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-12T15:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T02:58:56.000Z", "avg_line_length": 39.9389942292, "max_line_length": 80, "alphanum_fraction": 0.6987986624, "num_tokens": 11065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.036769468846346534, "lm_q1q2_score": 0.015816288995951763}}
{"text": "// Copyright (C) 2018  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n#include \"opaque_types.h\"\n#include <dlib/python.h>\n#include \"dlib/pixel.h\"\n#include <dlib/image_transforms.h>\n#include <dlib/image_processing.h>\n\nusing namespace dlib;\nusing namespace std;\n\nnamespace py = pybind11;\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\npy::array convert_image_scaled (\n    const numpy_image<T>& img,\n    const string& dtype,\n    const double thresh = 4\n)\n{\n    if (dtype == \"uint8\")    {numpy_image<uint8_t>   out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"uint16\")   {numpy_image<uint16_t>  out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"uint32\")   {numpy_image<uint32_t>  out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"uint64\")   {numpy_image<uint64_t>  out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"int8\")     {numpy_image<int8_t>    out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"int16\")    {numpy_image<int16_t>   out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"int32\")    {numpy_image<int32_t>   out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"int64\")    {numpy_image<int64_t>   out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"float32\")  {numpy_image<float>     out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"float64\")  {numpy_image<double>    out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"float\")    {numpy_image<float>     out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"double\")   {numpy_image<double>    out; assign_image_scaled(out, img, thresh); return out;}\n    if (dtype == \"rgb_pixel\"){numpy_image<rgb_pixel> out; assign_image_scaled(out, img, thresh); return out;}\n\n\n    throw dlib::error(\"convert_image_scaled() called with invalid dtype, must be one of these strings: \\n\"\n        \"uint8, int8, uint16, int16, uint32, int32, uint64, int64, float32, float, float64, double, or rgb_pixel\");\n}\n\n// ----------------------------------------------------------------------------------------\n\nstruct py_pyramid_down\n{\n\n    void dostuff(point) {}\n\n    py_pyramid_down(\n    ) = default;\n\n    py_pyramid_down (\n        unsigned int N_\n    ) : N(N_) \n    {\n        DLIB_CASSERT( 1 <= N && N <= 20, \"pyramid downsampling rate must be between 1 and 20.\");\n    }\n\n    unsigned int pyramid_downsampling_rate (\n    ) const { return N; }\n\n    template <typename T>\n    dlib::vector<double,2> point_down (\n        const dlib::vector<T,2>& pp\n    ) const\n    {\n        dpoint p = pp;\n        switch(N)\n        {\n            case 1: return pyr1.point_down(p);\n            case 2: return pyr2.point_down(p);\n            case 3: return pyr3.point_down(p);\n            case 4: return pyr4.point_down(p);\n            case 5: return pyr5.point_down(p);\n            case 6: return pyr6.point_down(p);\n            case 7: return pyr7.point_down(p);\n            case 8: return pyr8.point_down(p);\n            case 9: return pyr9.point_down(p);\n            case 10: return pyr10.point_down(p);\n            case 11: return pyr11.point_down(p);\n            case 12: return pyr12.point_down(p);\n            case 13: return pyr13.point_down(p);\n            case 14: return pyr14.point_down(p);\n            case 15: return pyr15.point_down(p);\n            case 16: return pyr16.point_down(p);\n            case 17: return pyr17.point_down(p);\n            case 18: return pyr18.point_down(p);\n            case 19: return pyr19.point_down(p);\n            case 20: return pyr20.point_down(p);\n        }\n\n        DLIB_CASSERT(false, \"This should never happen\");\n    }\n\n    template <typename T>\n    dlib::vector<double,2> point_up (\n        const dlib::vector<T,2>& pp\n    ) const\n    {\n        dpoint p = pp;\n        switch(N)\n        {\n            case 1: return pyr1.point_up(p);\n            case 2: return pyr2.point_up(p);\n            case 3: return pyr3.point_up(p);\n            case 4: return pyr4.point_up(p);\n            case 5: return pyr5.point_up(p);\n            case 6: return pyr6.point_up(p);\n            case 7: return pyr7.point_up(p);\n            case 8: return pyr8.point_up(p);\n            case 9: return pyr9.point_up(p);\n            case 10: return pyr10.point_up(p);\n            case 11: return pyr11.point_up(p);\n            case 12: return pyr12.point_up(p);\n            case 13: return pyr13.point_up(p);\n            case 14: return pyr14.point_up(p);\n            case 15: return pyr15.point_up(p);\n            case 16: return pyr16.point_up(p);\n            case 17: return pyr17.point_up(p);\n            case 18: return pyr18.point_up(p);\n            case 19: return pyr19.point_up(p);\n            case 20: return pyr20.point_up(p);\n        }\n        DLIB_CASSERT(false, \"This should never happen\");\n    }\n\n// -----------------------------\n\n    template <typename T>\n    dlib::vector<double,2> point_down2 (\n        const dlib::vector<T,2>& p,\n        unsigned int levels\n    ) const\n    {\n        dlib::vector<double,2> temp = p;\n        for (unsigned int i = 0; i < levels; ++i)\n            temp = point_down(temp);\n        return temp;\n    }\n\n    template <typename T>\n    dlib::vector<double,2> point_up2 (\n        const dlib::vector<T,2>& p,\n        unsigned int levels\n    ) const\n    {\n        dlib::vector<double,2> temp = p;\n        for (unsigned int i = 0; i < levels; ++i)\n            temp = point_up(temp);\n        return temp;\n    }\n\n// -----------------------------\n\n    template <typename rect_type>\n    rect_type rect_up (\n        const rect_type& rect\n    ) const\n    {\n        return rect_type(point_up(rect.tl_corner()), point_up(rect.br_corner()));\n    }\n\n    template <typename rect_type>\n    rect_type rect_up2 (\n        const rect_type& rect,\n        unsigned int levels\n    ) const\n    {\n        return rect_type(point_up2(rect.tl_corner(),levels), point_up2(rect.br_corner(),levels));\n    }\n\n// -----------------------------\n\n    template <typename rect_type>\n    rect_type rect_down (\n        const rect_type& rect\n    ) const\n    {\n        return rect_type(point_down(rect.tl_corner()), point_down(rect.br_corner()));\n    }\n\n    template <typename rect_type>\n    rect_type rect_down2 (\n        const rect_type& rect,\n        unsigned int levels\n    ) const\n    {\n        return rect_type(point_down2(rect.tl_corner(),levels), point_down2(rect.br_corner(),levels));\n    }\n\n    template <\n        typename T\n        >\n    numpy_image<T> down (\n        const numpy_image<T>& img\n    ) const\n    {\n\n        numpy_image<T> down;\n        switch(N)\n        {\n            case 1: pyr1(img,down); break;\n            case 2: pyr2(img,down); break;\n            case 3: pyr3(img,down); break;\n            case 4: pyr4(img,down); break;\n            case 5: pyr5(img,down); break;\n            case 6: pyr6(img,down); break;\n            case 7: pyr7(img,down); break;\n            case 8: pyr8(img,down); break;\n            case 9: pyr9(img,down); break;\n            case 10: pyr10(img,down); break;\n            case 11: pyr11(img,down); break;\n            case 12: pyr12(img,down); break;\n            case 13: pyr13(img,down); break;\n            case 14: pyr14(img,down); break;\n            case 15: pyr15(img,down); break;\n            case 16: pyr16(img,down); break;\n            case 17: pyr17(img,down); break;\n            case 18: pyr18(img,down); break;\n            case 19: pyr19(img,down); break;\n            case 20: pyr20(img,down); break;\n        }\n\n        return down;\n    }\n\nprivate:\n    unsigned int N = 2;\n\n    pyramid_down<1> pyr1;\n    pyramid_down<2> pyr2;\n    pyramid_down<3> pyr3;\n    pyramid_down<4> pyr4;\n    pyramid_down<5> pyr5;\n    pyramid_down<6> pyr6;\n    pyramid_down<7> pyr7;\n    pyramid_down<8> pyr8;\n    pyramid_down<9> pyr9;\n    pyramid_down<10> pyr10;\n    pyramid_down<11> pyr11;\n    pyramid_down<12> pyr12;\n    pyramid_down<13> pyr13;\n    pyramid_down<14> pyr14;\n    pyramid_down<15> pyr15;\n    pyramid_down<16> pyr16;\n    pyramid_down<17> pyr17;\n    pyramid_down<18> pyr18;\n    pyramid_down<19> pyr19;\n    pyramid_down<20> pyr20;\n\n};\n\n// ----------------------------------------------------------------------------------------\n\npy::tuple py_find_bright_lines (\n    const numpy_image<float>& xx,\n    const numpy_image<float>& xy,\n    const numpy_image<float>& yy\n)\n{\n    numpy_image<float> horz, vert;\n    find_bright_lines(xx,xy,yy,horz,vert);\n    return py::make_tuple(horz,vert);\n}\n\npy::tuple py_find_dark_lines (\n    const numpy_image<float>& xx,\n    const numpy_image<float>& xy,\n    const numpy_image<float>& yy\n)\n{\n    numpy_image<float> horz, vert;\n    find_dark_lines(xx,xy,yy,horz,vert);\n    return py::make_tuple(horz,vert);\n}\n\nnumpy_image<float> py_find_bright_keypoints (\n    const numpy_image<float>& xx,\n    const numpy_image<float>& xy,\n    const numpy_image<float>& yy\n)\n{\n    numpy_image<float> sal;\n    find_bright_keypoints(xx,xy,yy,sal);\n    return sal;\n}\n\nnumpy_image<float> py_find_dark_keypoints (\n    const numpy_image<float>& xx,\n    const numpy_image<float>& xy,\n    const numpy_image<float>& yy\n)\n{\n    numpy_image<float> sal;\n    find_dark_keypoints(xx,xy,yy,sal);\n    return sal;\n}\n\ntemplate <typename T>\npy::tuple py_sobel_edge_detector (\n    const numpy_image<T>& img\n)\n{\n    numpy_image<float> horz, vert;\n    sobel_edge_detector(img, horz, vert);\n    return py::make_tuple(horz,vert);\n}\n\nnumpy_image<float> py_suppress_non_maximum_edges (\n    const numpy_image<float>& horz,\n    const numpy_image<float>& vert\n)\n{\n    numpy_image<float> out;\n    suppress_non_maximum_edges(horz,vert,out);\n    return out;\n}\n\nnumpy_image<float> py_suppress_non_maximum_edges2 (\n    const py::tuple& horz_and_vert_gradients \n)\n{\n    numpy_image<float> out, horz, vert;\n    horz = horz_and_vert_gradients[0];\n    vert = horz_and_vert_gradients[1];\n    suppress_non_maximum_edges(horz,vert,out);\n    return out;\n}\n\ntemplate <typename T> \nstd::vector<point> py_find_peaks (\n    const numpy_image<T>& img,\n    const double non_max_suppression_radius,\n    const T& thresh\n)\n{\n    return find_peaks(img, non_max_suppression_radius, thresh);\n}\n\ntemplate <typename T> \nstd::vector<point> py_find_peaks2 (\n    const numpy_image<T>& img,\n    const double non_max_suppression_radius\n)\n{\n    return find_peaks(img, non_max_suppression_radius, partition_pixels(img));\n}\n\n\n// ----------------------------------------------------------------------------------------\n\ntemplate <typename T>\nnumpy_image<unsigned char> py_hysteresis_threshold (\n    const numpy_image<T>& img,\n    T lower_thresh,\n    T upper_thresh\n)\n{\n    numpy_image<unsigned char> out;\n    hysteresis_threshold(img, out, lower_thresh, upper_thresh);\n    return out;\n}\n\ntemplate <typename T>\nnumpy_image<unsigned char> py_hysteresis_threshold2 (\n    const numpy_image<T>& img\n)\n{\n    numpy_image<unsigned char> out;\n    hysteresis_threshold(img, out);\n    return out;\n}\n\n// ----------------------------------------------------------------------------------------\n\nvoid bind_image_classes3(py::module& m)\n{\n    const char* docs;\n\n    docs = \n\"requires \\n\\\n    - thresh > 0 \\n\\\nensures \\n\\\n    - Converts an image to a target pixel type.  dtype must be a string containing one of the following: \\n\\\n      uint8, int8, uint16, int16, uint32, int32, uint64, int64, float32, float, float64, double, or rgb_pixel \\n\\\n \\n\\\n      The contents of img will be scaled to fit the dynamic range of the target \\n\\\n      pixel type.  The thresh parameter is used to filter source pixel values which \\n\\\n      are outliers.  These outliers will saturate at the edge of the destination \\n\\\n      image's dynamic range. \\n\\\n    - Specifically, for all valid r and c: \\n\\\n        - We scale img[r][c] into the dynamic range of the target pixel type.  This \\n\\\n          is done using the mean and standard deviation of img. Call the mean M and \\n\\\n          the standard deviation D.  Then the scaling from source to destination is \\n\\\n          performed using the following mapping: \\n\\\n            let SRC_UPPER  = min(M + thresh*D, max(img)) \\n\\\n            let SRC_LOWER  = max(M - thresh*D, min(img)) \\n\\\n            let DEST_UPPER = max value possible for the selected dtype.  \\n\\\n            let DEST_LOWER = min value possible for the selected dtype. \\n\\\n \\n\\\n            MAPPING: [SRC_LOWER, SRC_UPPER] -> [DEST_LOWER, DEST_UPPER] \\n\\\n \\n\\\n          Where this mapping is a linear mapping of values from the left range \\n\\\n          into the right range of values.  Source pixel values outside the left \\n\\\n          range are modified to be at the appropriate end of the range.\";\n    /*!\n        requires\n            - thresh > 0\n        ensures\n            - Converts an image to a target pixel type.  dtype must be a string containing one of the following:\n              uint8, int8, uint16, int16, uint32, int32, uint64, int64, float32, float, float64, double, or rgb_pixel\n\n              The contents of img will be scaled to fit the dynamic range of the target\n              pixel type.  The thresh parameter is used to filter source pixel values which\n              are outliers.  These outliers will saturate at the edge of the destination\n              image's dynamic range.\n            - Specifically, for all valid r and c:\n                - We scale img[r][c] into the dynamic range of the target pixel type.  This\n                  is done using the mean and standard deviation of img. Call the mean M and\n                  the standard deviation D.  Then the scaling from source to destination is\n                  performed using the following mapping:\n                    let SRC_UPPER  = min(M + thresh*D, max(img))\n                    let SRC_LOWER  = max(M - thresh*D, min(img))\n                    let DEST_UPPER = max value possible for the selected dtype. \n                    let DEST_LOWER = min value possible for the selected dtype.\n\n                    MAPPING: [SRC_LOWER, SRC_UPPER] -> [DEST_LOWER, DEST_UPPER]\n\n                  Where this mapping is a linear mapping of values from the left range\n                  into the right range of values.  Source pixel values outside the left\n                  range are modified to be at the appropriate end of the range.\n    !*/\n    m.def(\"convert_image_scaled\", convert_image_scaled<uint8_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<uint16_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<uint32_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<uint64_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<int8_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<int16_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<int32_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<int64_t>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<float>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<double>, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n    m.def(\"convert_image_scaled\", convert_image_scaled<rgb_pixel>, docs, py::arg(\"img\"), py::arg(\"dtype\"), py::arg(\"thresh\")=4);\n\n\n\n    const char* class_docs;\n\n\n    class_docs =\n\"This is a simple object to help create image pyramids.  In particular, it \\n\\\ndownsamples images at a ratio of N to N-1. \\n\\\n \\n\\\nNote that setting N to 1 means that this object functions like \\n\\\npyramid_disable (defined at the bottom of this file).   \\n\\\n \\n\\\nWARNING, when mapping rectangles from one layer of a pyramid \\n\\\nto another you might end up with rectangles which extend slightly  \\n\\\noutside your images.  This is because points on the border of an  \\n\\\nimage at a higher pyramid layer might correspond to points outside  \\n\\\nimages at lower layers.  So just keep this in mind.  Note also \\n\\\nthat it's easy to deal with.  Just say something like this: \\n\\\n    rect = rect.intersect(get_rect(my_image)); # keep rect inside my_image \";\n        /*!\n                This is a simple object to help create image pyramids.  In particular, it\n                downsamples images at a ratio of N to N-1.\n\n                Note that setting N to 1 means that this object functions like\n                pyramid_disable (defined at the bottom of this file).  \n\n                WARNING, when mapping rectangles from one layer of a pyramid\n                to another you might end up with rectangles which extend slightly \n                outside your images.  This is because points on the border of an \n                image at a higher pyramid layer might correspond to points outside \n                images at lower layers.  So just keep this in mind.  Note also\n                that it's easy to deal with.  Just say something like this:\n                    rect = rect.intersect(get_rect(my_image)); # keep rect inside my_image \n        !*/\n\n    docs =\n\"- Downsamples img to make a new image that is roughly (pyramid_downsampling_rate()-1)/pyramid_downsampling_rate()  \\n\\\n  times the size of the original image.   \\n\\\n- The location of a point P in original image will show up at point point_down(P) \\n\\\n  in the downsampled image.   \\n\\\n- Note that some points on the border of the original image might correspond to  \\n\\\n  points outside the downsampled image.\";\n        /*!\n          - Downsamples img to make a new image that is roughly (pyramid_downsampling_rate()-1)/pyramid_downsampling_rate() \n            times the size of the original image.  \n          - The location of a point P in original image will show up at point point_down(P)\n            in the downsampled image.  \n          - Note that some points on the border of the original image might correspond to \n            points outside the downsampled image.  \n        !*/\n    py::class_<py_pyramid_down>(m, \"pyramid_down\", class_docs)\n        .def(py::init<unsigned int>(), \"Creates this class with the provided downsampling rate. i.e. pyramid_downsampling_rate()==N. \\nN must be in the range 1 to 20.\", py::arg(\"N\"))\n        .def(py::init<>(), \"Creates this class with pyramid_downsampling_rate()==2\")\n        .def(\"pyramid_downsampling_rate\", &py_pyramid_down::pyramid_downsampling_rate,\n            \"Returns a number N that defines the downsampling rate.  In particular, images are downsampled by a factor of N to N-1.\")\n        .def(\"point_up\", &py_pyramid_down::point_up<long>,   py::arg(\"p\"))\n        .def(\"point_up\", &py_pyramid_down::point_up<double>, \n            \"Maps from pixels in a downsampled image to pixels in the original image.\",  py::arg(\"p\"))\n        .def(\"point_up\", &py_pyramid_down::point_up2<long>,   py::arg(\"p\"), py::arg(\"levels\"))\n        .def(\"point_up\", &py_pyramid_down::point_up2<double>, \n            \"Applies point_up() to p levels times and returns the result.\",  py::arg(\"p\"), py::arg(\"levels\"))\n        .def(\"point_down\", &py_pyramid_down::point_down<long>,   py::arg(\"p\"))\n        .def(\"point_down\", &py_pyramid_down::point_down<double>, \n            \"Maps from pixels in a source image to the corresponding pixels in the downsampled image.\", py::arg(\"p\"))\n        .def(\"point_down\", &py_pyramid_down::point_down2<long>,   py::arg(\"p\"), py::arg(\"levels\"))\n        .def(\"point_down\", &py_pyramid_down::point_down2<double>, \"Applies point_down() to p levels times and returns the result.\",   \n            py::arg(\"p\"), py::arg(\"levels\"))\n        .def(\"rect_down\", &py_pyramid_down::rect_down<rectangle>,   py::arg(\"rect\"))\n        .def(\"rect_down\", &py_pyramid_down::rect_down<drectangle>,\n          \"returns drectangle(point_down(rect.tl_corner()), point_down(rect.br_corner()));\\n (i.e. maps rect into a downsampled)\",\n          py::arg(\"rect\"))\n        .def(\"rect_down\", &py_pyramid_down::rect_down2<rectangle>,   py::arg(\"rect\"), py::arg(\"levels\"))\n        .def(\"rect_down\", &py_pyramid_down::rect_down2<drectangle>, \"Applies rect_down() to rect levels times and returns the result.\",\n            py::arg(\"rect\"), py::arg(\"levels\"))\n        .def(\"rect_up\", &py_pyramid_down::rect_up<rectangle>,   py::arg(\"rect\"))\n        .def(\"rect_up\", &py_pyramid_down::rect_up<drectangle>,   \n          \"returns drectangle(point_up(rect.tl_corner()), point_up(rect.br_corner()));\\n (i.e. maps rect into a parent image)\",\n            py::arg(\"rect\"))\n        .def(\"rect_up\", &py_pyramid_down::rect_up2<rectangle>,   py::arg(\"rect\"), py::arg(\"levels\"))\n        .def(\"rect_up\", &py_pyramid_down::rect_up2<drectangle>,  \"Applies rect_up() to rect levels times and returns the result.\",\n            py::arg(\"p\"), py::arg(\"levels\"))\n        .def(\"__call__\", &py_pyramid_down::down<uint8_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<uint16_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<uint32_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<uint64_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<int8_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<int16_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<int32_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<int64_t>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<float>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<double>,   py::arg(\"img\"))\n        .def(\"__call__\", &py_pyramid_down::down<rgb_pixel>, docs,  py::arg(\"img\"));\n\n\n    docs =\n\"requires \\n\\\n    - xx, xy, and yy all have the same dimensions. \\n\\\nensures \\n\\\n    - This routine is similar to sobel_edge_detector(), except instead of finding \\n\\\n      an edge it finds a bright/white line.  For example, the border between a \\n\\\n      black piece of paper and a white table is an edge, but a curve drawn with a \\n\\\n      pencil on a piece of paper makes a line.  Therefore, the output of this \\n\\\n      routine is a vector field encoded in the horz and vert images, which are \\n\\\n      returned in a tuple where the first element is horz and the second is vert. \\n\\\n \\n\\\n      The vector obtains a large magnitude when centered on a bright line in an image and the \\n\\\n      direction of the vector is perpendicular to the line.  To be very precise, \\n\\\n      each vector points in the direction of greatest change in second derivative \\n\\\n      and the magnitude of the vector encodes the derivative magnitude in that \\n\\\n      direction.  Moreover, if the second derivative is positive then the output \\n\\\n      vector is zero.  This zeroing if positive gradients causes the output to be \\n\\\n      sensitive only to bright lines surrounded by darker pixels. \\n\\\n \\n\\\n    - We assume that xx, xy, and yy are the 3 second order gradients of the image \\n\\\n      in question.  You can obtain these gradients using the image_gradients class. \\n\\\n    - The output images will have the same dimensions as the input images. \";\n    /*!\n        requires\n            - xx, xy, and yy all have the same dimensions.\n        ensures\n            - This routine is similar to sobel_edge_detector(), except instead of finding\n              an edge it finds a bright/white line.  For example, the border between a\n              black piece of paper and a white table is an edge, but a curve drawn with a\n              pencil on a piece of paper makes a line.  Therefore, the output of this\n              routine is a vector field encoded in the horz and vert images, which are\n              returned in a tuple where the first element is horz and the second is vert.\n\n              The vector obtains a large magnitude when centered on a bright line in an image and the\n              direction of the vector is perpendicular to the line.  To be very precise,\n              each vector points in the direction of greatest change in second derivative\n              and the magnitude of the vector encodes the derivative magnitude in that\n              direction.  Moreover, if the second derivative is positive then the output\n              vector is zero.  This zeroing if positive gradients causes the output to be\n              sensitive only to bright lines surrounded by darker pixels.\n\n            - We assume that xx, xy, and yy are the 3 second order gradients of the image\n              in question.  You can obtain these gradients using the image_gradients class.\n            - The output images will have the same dimensions as the input images. \n    !*/\n    m.def(\"find_bright_lines\",     &py_find_bright_lines,     docs, py::arg(\"xx\"), py::arg(\"xy\"), py::arg(\"yy\"));\n\n\n\n    docs =\n\"requires \\n\\\n    - xx, xy, and yy all have the same dimensions. \\n\\\nensures \\n\\\n    - This routine is similar to sobel_edge_detector(), except instead of finding \\n\\\n      an edge it finds a dark line.  For example, the border between a black piece \\n\\\n      of paper and a white table is an edge, but a curve drawn with a pencil on a \\n\\\n      piece of paper makes a line.  Therefore, the output of this routine is a \\n\\\n      vector field encoded in the horz and vert images, which are returned in a \\n\\\n      tuple where the first element is horz and the second is vert. \\n\\\n \\n\\\n      The vector obtains a large magnitude when centered on a dark line in an image \\n\\\n      and the direction of the vector is perpendicular to the line.  To be very \\n\\\n      precise, each vector points in the direction of greatest change in second \\n\\\n      derivative and the magnitude of the vector encodes the derivative magnitude \\n\\\n      in that direction.  Moreover, if the second derivative is negative then the \\n\\\n      output vector is zero.  This zeroing if negative gradients causes the output \\n\\\n      to be sensitive only to dark lines surrounded by darker pixels. \\n\\\n \\n\\\n    - We assume that xx, xy, and yy are the 3 second order gradients of the image \\n\\\n      in question.  You can obtain these gradients using the image_gradients class. \\n\\\n    - The output images will have the same dimensions as the input images. \";\n    /*!\n        requires\n            - xx, xy, and yy all have the same dimensions.\n        ensures\n            - This routine is similar to sobel_edge_detector(), except instead of finding\n              an edge it finds a dark line.  For example, the border between a black piece\n              of paper and a white table is an edge, but a curve drawn with a pencil on a\n              piece of paper makes a line.  Therefore, the output of this routine is a\n              vector field encoded in the horz and vert images, which are returned in a\n              tuple where the first element is horz and the second is vert.\n\n              The vector obtains a large magnitude when centered on a dark line in an image\n              and the direction of the vector is perpendicular to the line.  To be very\n              precise, each vector points in the direction of greatest change in second\n              derivative and the magnitude of the vector encodes the derivative magnitude\n              in that direction.  Moreover, if the second derivative is negative then the\n              output vector is zero.  This zeroing if negative gradients causes the output\n              to be sensitive only to dark lines surrounded by darker pixels.\n\n            - We assume that xx, xy, and yy are the 3 second order gradients of the image\n              in question.  You can obtain these gradients using the image_gradients class.\n            - The output images will have the same dimensions as the input images. \n    !*/\n    m.def(\"find_dark_lines\",       &py_find_dark_lines,       docs, py::arg(\"xx\"), py::arg(\"xy\"), py::arg(\"yy\"));\n\n\n\n    docs =\n\"requires \\n\\\n    - xx, xy, and yy all have the same dimensions. \\n\\\nensures \\n\\\n    - This routine finds bright \\\"keypoints\\\" in an image.  In general, these are \\n\\\n      bright/white localized blobs.  It does this by computing the determinant of \\n\\\n      the image Hessian at each location and storing this value into the returned \\n\\\n      image if both eigenvalues of the Hessian are negative.  If either eigenvalue \\n\\\n      is positive then the output value for that pixel is 0.  I.e. \\n\\\n        - Let OUT denote the returned image. \\n\\\n        - for all valid r,c: \\n\\\n            - OUT[r][c] == a number >= 0 and larger values indicate the \\n\\\n              presence of a keypoint at this pixel location. \\n\\\n    - We assume that xx, xy, and yy are the 3 second order gradients of the image \\n\\\n      in question.  You can obtain these gradients using the image_gradients class. \\n\\\n    - The output image will have the same dimensions as the input images.\";\n    /*!\n        requires\n            - xx, xy, and yy all have the same dimensions.\n        ensures\n            - This routine finds bright \"keypoints\" in an image.  In general, these are\n              bright/white localized blobs.  It does this by computing the determinant of\n              the image Hessian at each location and storing this value into the returned\n              image if both eigenvalues of the Hessian are negative.  If either eigenvalue\n              is positive then the output value for that pixel is 0.  I.e.\n                - Let OUT denote the returned image.\n                - for all valid r,c:\n                    - OUT[r][c] == a number >= 0 and larger values indicate the\n                      presence of a keypoint at this pixel location.\n            - We assume that xx, xy, and yy are the 3 second order gradients of the image\n              in question.  You can obtain these gradients using the image_gradients class.\n            - The output image will have the same dimensions as the input images.\n    !*/\n    m.def(\"find_bright_keypoints\", &py_find_bright_keypoints, docs, py::arg(\"xx\"), py::arg(\"xy\"), py::arg(\"yy\"));\n\n\n\n    docs =\n\"requires \\n\\\n    - xx, xy, and yy all have the same dimensions. \\n\\\nensures \\n\\\n    - This routine finds dark \\\"keypoints\\\" in an image.  In general, these are \\n\\\n      dark localized blobs.  It does this by computing the determinant of \\n\\\n      the image Hessian at each location and storing this value into the returned \\n\\\n      image if both eigenvalues of the Hessian are negative.  If either eigenvalue \\n\\\n      is negative then the output value for that pixel is 0.  I.e. \\n\\\n        - Let OUT denote the returned image. \\n\\\n        - for all valid r,c: \\n\\\n            - OUT[r][c] == a number >= 0 and larger values indicate the \\n\\\n              presence of a keypoint at this pixel location. \\n\\\n    - We assume that xx, xy, and yy are the 3 second order gradients of the image \\n\\\n      in question.  You can obtain these gradients using the image_gradients class. \\n\\\n    - The output image will have the same dimensions as the input images.\";\n    /*!\n        requires\n            - xx, xy, and yy all have the same dimensions.\n        ensures\n            - This routine finds dark \"keypoints\" in an image.  In general, these are\n              dark localized blobs.  It does this by computing the determinant of\n              the image Hessian at each location and storing this value into the returned\n              image if both eigenvalues of the Hessian are negative.  If either eigenvalue\n              is negative then the output value for that pixel is 0.  I.e.\n                - Let OUT denote the returned image.\n                - for all valid r,c:\n                    - OUT[r][c] == a number >= 0 and larger values indicate the\n                      presence of a keypoint at this pixel location.\n            - We assume that xx, xy, and yy are the 3 second order gradients of the image\n              in question.  You can obtain these gradients using the image_gradients class.\n            - The output image will have the same dimensions as the input images.\n    !*/\n    m.def(\"find_dark_keypoints\",   &py_find_dark_keypoints,   docs, py::arg(\"xx\"), py::arg(\"xy\"), py::arg(\"yy\"));\n\n\n\n    docs = \n\"requires \\n\\\n    - The two input images have the same dimensions. \\n\\\nensures \\n\\\n    - Returns an image, of the same dimensions as the input.  Each element in this \\n\\\n      image holds the edge strength at that location.  Moreover, edge pixels that are not  \\n\\\n      local maximizers have been set to 0. \\n\\\n    - let edge_strength(r,c) == sqrt(pow(horz[r][c],2) + pow(vert[r][c],2)) \\n\\\n      (i.e. The Euclidean norm of the gradient) \\n\\\n    - let OUT denote the returned image. \\n\\\n    - for all valid r and c: \\n\\\n        - if (edge_strength(r,c) is at a maximum with respect to its 2 neighboring \\n\\\n          pixels along the line indicated by the image gradient vector (horz[r][c],vert[r][c])) then \\n\\\n            - OUT[r][c] == edge_strength(r,c) \\n\\\n        - else \\n\\\n            - OUT[r][c] == 0\";\n    /*!\n        requires\n            - The two input images have the same dimensions.\n        ensures\n            - Returns an image, of the same dimensions as the input.  Each element in this\n              image holds the edge strength at that location.  Moreover, edge pixels that are not \n              local maximizers have been set to 0.\n            - let edge_strength(r,c) == sqrt(pow(horz[r][c],2) + pow(vert[r][c],2))\n              (i.e. The Euclidean norm of the gradient)\n            - let OUT denote the returned image.\n            - for all valid r and c:\n                - if (edge_strength(r,c) is at a maximum with respect to its 2 neighboring\n                  pixels along the line indicated by the image gradient vector (horz[r][c],vert[r][c])) then\n                    - OUT[r][c] == edge_strength(r,c)\n                - else\n                    - OUT[r][c] == 0\n    !*/\n    m.def(\"suppress_non_maximum_edges\", &py_suppress_non_maximum_edges, docs, py::arg(\"horz\"), py::arg(\"vert\"));\n    m.def(\"suppress_non_maximum_edges\", &py_suppress_non_maximum_edges2,\n        \"Performs: return suppress_non_maximum_edges(horz_and_vert_gradients[0], horz_and_vert_gradients[1])\",\n        py::arg(\"horz_and_vert_gradients\"));\n\n\n\n    docs =\n\"requires \\n\\\n    - non_max_suppression_radius >= 0 \\n\\\nensures \\n\\\n    - Scans the given image and finds all pixels with values >= thresh that are \\n\\\n      also local maximums within their 8-connected neighborhood of the image.  Such \\n\\\n      pixels are collected, sorted in decreasing order of their pixel values, and \\n\\\n      then non-maximum suppression is applied to this list of points using the \\n\\\n      given non_max_suppression_radius.  The final list of peaks is then returned. \\n\\\n \\n\\\n      Therefore, the returned list, V, will have these properties: \\n\\\n        - len(V) == the number of peaks found in the image. \\n\\\n        - When measured in image coordinates, no elements of V are within \\n\\\n          non_max_suppression_radius distance of each other.  That is, for all valid i!=j \\n\\\n          it is true that length(V[i]-V[j]) > non_max_suppression_radius. \\n\\\n        - For each element of V, that element has the maximum pixel value of all \\n\\\n          pixels in the ball centered on that pixel with radius \\n\\\n          non_max_suppression_radius.\";\n    /*!\n        requires\n            - non_max_suppression_radius >= 0\n        ensures\n            - Scans the given image and finds all pixels with values >= thresh that are\n              also local maximums within their 8-connected neighborhood of the image.  Such\n              pixels are collected, sorted in decreasing order of their pixel values, and\n              then non-maximum suppression is applied to this list of points using the\n              given non_max_suppression_radius.  The final list of peaks is then returned.\n\n              Therefore, the returned list, V, will have these properties:\n                - len(V) == the number of peaks found in the image.\n                - When measured in image coordinates, no elements of V are within\n                  non_max_suppression_radius distance of each other.  That is, for all valid i!=j\n                  it is true that length(V[i]-V[j]) > non_max_suppression_radius.\n                - For each element of V, that element has the maximum pixel value of all\n                  pixels in the ball centered on that pixel with radius\n                  non_max_suppression_radius.\n    !*/\n    m.def(\"find_peaks\", &py_find_peaks<float>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<double>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<uint8_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<uint16_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<uint32_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<uint64_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<int8_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<int16_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<int32_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n    m.def(\"find_peaks\", &py_find_peaks<int64_t>, py::arg(\"img\"), docs, py::arg(\"non_max_suppression_radius\"), py::arg(\"thresh\"));\n\n    m.def(\"find_peaks\", &py_find_peaks2<float>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<double>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<uint8_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<uint16_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<uint32_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<uint64_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<int8_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<int16_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<int32_t>, py::arg(\"img\"), py::arg(\"non_max_suppression_radius\")=0);\n    m.def(\"find_peaks\", &py_find_peaks2<int64_t>, py::arg(\"img\"),\n        \"performs: return find_peaks(img, non_max_suppression_radius, partition_pixels(img))\",\n        py::arg(\"non_max_suppression_radius\")=0);\n\n\n\n    docs =\n\"Applies the sobel edge detector to the given input image and returns two gradient \\n\\\nimages in a tuple.  The first contains the x gradients and the second contains the \\n\\\ny gradients of the image.\";\n    /*!\n         Applies the sobel edge detector to the given input image and returns two gradient\n         images in a tuple.  The first contains the x gradients and the second contains the\n         y gradients of the image.\n    !*/\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<uint8_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<uint16_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<uint32_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<uint64_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<int8_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<int16_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<int32_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<int64_t>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<float>, py::arg(\"img\"));\n    m.def(\"sobel_edge_detector\", &py_sobel_edge_detector<double>, docs, py::arg(\"img\"));\n\n\n    docs =\n\"Applies hysteresis thresholding to img and returns the results.  In particular, \\n\\\npixels in img with values >= upper_thresh have an output value of 255 and all \\n\\\nothers have a value of 0 unless they are >= lower_thresh and are connected to a \\n\\\npixel with a value >= upper_thresh, in which case they have a value of 255.  Here \\n\\\npixels are connected if there is a path between them composed of pixels that would \\n\\\nreceive an output of 255.\";\n    /*!\n        Applies hysteresis thresholding to img and returns the results.  In particular,\n        pixels in img with values >= upper_thresh have an output value of 255 and all\n        others have a value of 0 unless they are >= lower_thresh and are connected to a\n        pixel with a value >= upper_thresh, in which case they have a value of 255.  Here\n        pixels are connected if there is a path between them composed of pixels that would\n        receive an output of 255.\n    !*/\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<uint8_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<uint16_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<uint32_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<uint64_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<int8_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<int16_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<int32_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<int64_t>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<float>, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold<double>, docs, py::arg(\"img\"), py::arg(\"lower_thresh\"), py::arg(\"upper_thresh\"));\n\n    docs =\n\"performs: return hysteresis_threshold(img, t1, t2) where the thresholds \\n\\\nare first obtained by calling [t1, t2]=partition_pixels(img).\";\n    /*!\n        performs: return hysteresis_threshold(img, t1, t2) where the thresholds\n        are first obtained by calling [t1, t2]=partition_pixels(img).\n    !*/\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<uint8_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<uint16_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<uint32_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<uint64_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<int8_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<int16_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<int32_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<int64_t>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<float>, py::arg(\"img\"));\n    m.def(\"hysteresis_threshold\", &py_hysteresis_threshold2<double>, docs, py::arg(\"img\"));\n}\n\n", "meta": {"hexsha": "024b74a70acc6fd3aa587f04620abd4033807174", "size": 43992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/python/src/image3.cpp", "max_stars_repo_name": "enric1994/dlib", "max_stars_repo_head_hexsha": "42c25bd024d0ad9388ba8dcfff7507a2658160ad", "max_stars_repo_licenses": ["BSL-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/image3.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/image3.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": 49.9909090909, "max_line_length": 182, "alphanum_fraction": 0.6408210584, "num_tokens": 11247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.03846619174275306, "lm_q1q2_score": 0.015813869523414455}}
{"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-2011 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 SCALARSPACE_HH\n#define SCALARSPACE_HH\n\n#include <algorithm>\n#include <functional>\n#include <map>\n#include <vector>\n\n#include <boost/compressed_pair.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#include \"fem/firstless.hh\"\n#include \"fem/gridcombinatorics.hh\"\n#include \"fem/views.hh\"\n\nnamespace Kaskade\n{\n  // forward declarations\n  template <class,class> class ContinuousLagrangeBoundaryMapper;\n\n  namespace ScalarSpaceDetail\n  {\n    struct Empty {};\n\n    /**\n     * \\brief A functor for extracting the first component of a boost compressed pair.\n     */\n    template <class Pair>\n    struct CompressedFirst\n    {\n      typedef typename Pair::first_const_reference result_type;\n\n      typename Pair::first_const_reference operator()(Pair const& pair) const\n      {\n        return pair.first();\n      }\n    };\n\n    // Overload here as compressed pair's entries are accessed by method call. \n    struct FirstLess\n    {\n      template <class Data>\n      bool operator()(boost::compressed_pair<size_t,Data> const& a, boost::compressed_pair<size_t,Data> const& b)\n      {\n        return a.first() < b.first();\n      }\n    };\n\n    /// Default policy, in general use this.\n    /**\n     * \\tparam Implementation ...MapperImplementation\n     * \\tparam optional additional data stored for each shapefunction (see hierarchical and boundary spaces for examples)\n     */\n    template <class Implementation,class SFData=Empty>\n    class MapperPolicy\n    {\n      typedef typename Implementation::Grid              Grid;\n      typedef typename Implementation::GridView          GridView;\n      typedef typename GridView::IndexSet                IndexSet;\n      typedef typename Grid::template Codim<0>::Entity   Cell;\n      typedef typename Implementation::ShapeFunctionSet  ShapeFunctionSet;\n      typedef boost::compressed_pair<size_t,SFData>      Data;\n\n    protected:\n      static constexpr bool boundaryPolicy = false;\n\n      explicit MapperPolicy(Implementation const& impl) : implementation(impl)\n      {}\n\n      /**\n       * \\brief Computes the number of dofs associated to each geometry type in the grid and \n       *        initializes the startIndex indices accordingly, and resizes globIdx and sortedIdx appropriately.\n       */\n      template <class GlobalIndices, class SortedIndices>\n      void initIndices(std::map<Dune::GeometryType,size_t>& startIndex, GlobalIndices& globIdx, SortedIndices& sortedIdx)\n      {\n        globIdx.resize(implementation.indexSet().size(0));\n        sortedIdx.resize(implementation.indexSet().size(0));\n        size_t n = 0;\n        for (int codim=0; codim<=Grid::dimension; ++codim)\n          for(auto const& geoType: implementation.indexSet().geomTypes(codim))\n          {\n            startIndex[geoType] = n;\n            n += implementation.indexSet().size(geoType) * implementation.dofOnEntity(geoType);\n          }\n      }\n\n      /**\n       * \\brief Store the global indices of the ansatz functions on cell into globIdx and a pair of global and local indices in sortedIdx.\n       * \n       * Sorting of sortedIdx will be performed in UniformScalarMapper::update() and thus must not be done here.\n       *\n       * \\param startIndex holds offsets for different geometry types, useful if global indices are ordered according to geometry types, see below\n       */\n      template <class GlobalIndices, class SortedIndices>\n      void computeIndices(Cell const& cell, std::map<Dune::GeometryType,size_t>& startIndex, GlobalIndices& globIdx, SortedIndices& sortedIdx, size_t cellIndex) const\n      {\n        ShapeFunctionSet const& sf = implementation.shapeFunctions(cell);\n        size_t localNumberOfShapeFunctions = sf.size();\n        globIdx[cellIndex].resize(localNumberOfShapeFunctions);\n        sortedIdx[cellIndex].resize(localNumberOfShapeFunctions);\n\n        // step through all shape functions.\n        // TODO: pull common parts out of this loop\n        for(size_t i=0; i<localNumberOfShapeFunctions; ++i)\n        {\n          Dune::GeometryType gt;\n          int subentity, codim, indexInSubentity;\n          SFData sfData;\n          implementation.entityIndex(cell,sf[i],i,gt,subentity,codim,indexInSubentity,sfData);\n\n          // compute the global index of the subentity to which the shape function is associated\n          int gt_idx = subIndex(implementation.indexSet(),cell,codim,subentity);\n\n          auto mi = startIndex.find(gt);\n          assert(mi!=startIndex.end());\n\n          globIdx[cellIndex][i] =  Data(mi->second+gt_idx*implementation.dofOnEntity(gt)+indexInSubentity,sfData);\n          sortedIdx[cellIndex][i] = std::make_pair(globIdx[cellIndex][i].first(),i);\n        }\n      }\n\n      template <class Container, class ShapeFunctionSet>\n      void initShapeFunctionSet(Container& sfs, ShapeFunctionSet const& sf, size_t cellIndex) const\n      {\n        sfs[cellIndex] = &sf; // cache shape function set\n      }\n\n      Implementation implementation;\n    };\n\n    /**\n     * \\cond internal\n     */\n    inline bool onFace_3D(int codim, int id, int localFaceId)\n    {\n      // edges\n      if(codim==2)\n      {\n        if(localFaceId==0) return (id>=0 && id<3);\n        if(localFaceId==1) return (id==0 || id==3 || id==4);\n        if(localFaceId==2) return (id==1 || id==3 || id==5);\n        if(localFaceId==3) return (id==2 || id==4 || id==5);\n      }\n      // vertices\n      if(codim==3)\n      {\n        if(localFaceId==0) return (id>=0 && id<3);\n        if(localFaceId==1) return (id==0 || id==1 || id==3);\n        if(localFaceId==2) return (id==0 || id==2 || id==3);\n        if(localFaceId==3) return (id==1 || id==2 || id==3);\n      }\n      return false;\n    }\n    /**\n     * \\endcond \n     */\n\n    /// check if subentity is subentity of face\n    /**\n     * \\param dim space dimension\n     * \\param codim codimension of subentity\n     * \\param id index within the subentities with codimension codim\n     * \\param localFaceId local index of face in cell\n     */\n   inline bool onFace(int dim, int codim, int id, int localFaceId)\n    {\n      if(codim==0) return false;\n      if(codim==1) return id==localFaceId;\n\n      if(dim==2)\n      {\n        if(localFaceId==0) return (id==0 || id==1);\n        if(localFaceId==1) return (id==0 || id==2);\n        if(localFaceId==2) return (id==2 || id==1);\n      }\n      if(dim==3) return onFace_3D(codim,id,localFaceId);\n\n      return false;\n    }\n\n    static constexpr int defaultIndex = -94279;\n\n    template <class Face>\n    int getBoundaryId(Face const& face, std::vector<int> const& boundaryIds)\n    {\n      size_t boundarySegmentIndex = face.boundarySegmentIndex();\n      if(boundarySegmentIndex < boundaryIds.size()) return boundaryIds[boundarySegmentIndex];\n      return defaultIndex;\n    }\n\n    inline bool usedId(int id, std::vector<int> const& usedIds)\n    {\n      if (id==defaultIndex) return false;\n      return std::find(usedIds.begin(), usedIds.end(), id) != usedIds.end();\n    }\n\n    template <class Face>\n    inline bool considerFace(Face const& face, std::vector<int> const& boundaryIds, std::vector<int> const& usedIds)\n    {\n      if(boundaryIds.empty()) return face.boundary();\n      return (face.boundary() && usedId(getBoundaryId(face,boundaryIds),usedIds));\n    }\n\n    ///\n    struct RestrictToBoundary\n    {\n      //static constexpr int defaultIndex = -99999;\n\n      RestrictToBoundary() : boundaryIds(), usedIds() {}\n      RestrictToBoundary(RestrictToBoundary const& other) : boundaryIds(other.boundaryIds), usedIds(other.usedIds) {}\n      RestrictToBoundary(std::vector<int> const& boundaryIds_, std::vector<int> const& usedIds_) : boundaryIds(boundaryIds_), usedIds(usedIds_)\n      {}\n\n      template <class Data, class GridView, class Cell>\n      void treatBoundary(Data& data, GridView const& gridView, Cell const& cell, int codim, int subentity) const\n      {\n        // ignore shape functions that are associated with codim-0 entities\n        if(codim > 0) {\n          for(auto const& face : intersections(gridView,cell)) {\n            // only consider boundary faces\n            if(considerFace(face,boundaryIds,usedIds)) {\n              if(onFace(GridView::dimension,codim,subentity,face.indexInInside())) {\n                data.first() = true;\n              }\n            }\n          }\n        }\n      }\n\n      std::vector<int> const boundaryIds;\n      std::vector<int> const usedIds;\n    };\n\n    template <class Policy>\n    constexpr bool isRestriction()\n    {\n      return std::is_same<Policy,RestrictToBoundary>::value;\n    }\n\n    ///\n    struct AllShapeFunctions\n    {\n      template <class Data, class GridView, class Cell> void treatBoundary(Data&, GridView const&, Cell const&, int, int) const {}\n    };\n  } // End of namespace ScalarSpaceDetail\n  \n  // --------------------------------------------------------------------------------------------\n  // --------------------------------------------------------------------------------------------\n\n  /**\n   * \\brief A traits class defining the type of argument that is provided by\n   * UniformScalarMapper:combiner on the call to the Combiner constructor.\n   */\n  template <class SFData>\n  struct UniformScalarMapperCombinerArgument\n  {\n    // nice try :DD\n    // private:\n    typedef typename std::vector<boost::compressed_pair<size_t,SFData> >::const_iterator Iterator;\n    /**\n     * \\brief The sequence type that is provided to the call of the Combiner constructor. \n     * \n     * The type is a lightweight view type and should be kept by value, not by reference.\n     */\n    typedef RangeView<Iterator> type;\n  };\n\n  /**\n   * \\ingroup fem\n   * \\brief Base class for uniform scalar local to global mappers.\n   *\n   * It manages degrees of freedom for ansatz spaces where to each type of entity\n   * of the grid the same number of global degrees of freedom is\n   * associated and on each cell live the same number of shape\n   * functions.\n   *\n   * We call a degree of freedom associated to an entity e of the grid\n   * - if the support of the ansatz function is contained within the union\n   *   of the cells (codim 0 entitites) which are incident to e and\n   * - the ansatz function vanishes on all subentities of incident cells\n   *   with a codimension not less than e.\n   * This includes the usual polynomial FE spaces of arbitrary but fixed order.\n   *\n   * With each shape function on each cell, we associate its global\n   * degree of freedom and additional data the type of is specified as\n   * template parameter \\a SFData.\n   * \n   * \\tparam Implementation\n   * \\tparam SFData type of (optional) additional data associated to global degrees of freedom\n   *\n   */\n  template <class Implementation, class SFData = ScalarSpaceDetail::Empty>\n  class UniformScalarMapper : public ScalarSpaceDetail::MapperPolicy<Implementation,SFData>\n  {\n  public:\n    typedef typename Implementation::Grid              Grid;\n    typedef typename Grid::template Codim<0>::Entity   Cell;\n    typedef typename Implementation::ShapeFunctionSet  ShapeFunctionSet;\n    typedef typename Implementation::Converter         Converter;\n    typedef typename Implementation::Combiner          Combiner;\n    typedef typename Implementation::Scalar            Scalar;\n    typedef typename Implementation::GridView          GridView;\n    typedef typename GridView::IndexSet                IndexSet;\n    typedef std::pair<size_t,int>                      IndexPair;\n\n  private:\n    typedef boost::compressed_pair<size_t,SFData> Data;\n\n    typedef ScalarSpaceDetail::CompressedFirst<Data> First;\n\n    typedef boost::transform_iterator<First,typename std::vector<Data>::const_iterator> GlobalIndexIterator;\n    typedef std::vector<IndexPair>::const_iterator                                      SortedIndexIterator;\n\n    static constexpr int dim = Grid::dimension;\n\n  public:\n    typedef RangeView<GlobalIndexIterator> GlobalIndexRange;\n    typedef RangeView<SortedIndexIterator> SortedIndexRange;\n\n    /**\n     * \\brief Whether the ansatz functions have global support (i.e. lead to dense matrices).\n     */\n    static bool const globalSupport = false;\n\n\n    UniformScalarMapper(Implementation const& impl) : ScalarSpaceDetail::MapperPolicy<Implementation,SFData>(impl)\n    {\n      update();\n    }\n\n    /**\n     * \\brief Returns the maximal polynomial order of shape functions encountered in any cell.\n     */\n    int maxOrder() const\n    {\n      return order;\n    }\n    \n    \n    /**\n     * \\brief Returns an empty range just for initialization purposes, since RangeView is not default constructible.\n     */\n    GlobalIndexRange initGlobalIndexRange() const\n    {\n      return GlobalIndexRange(GlobalIndexIterator(globIdx[0].begin(),First()),\n                              GlobalIndexIterator(globIdx[0].begin(),First()));\n    }\n\n\n    /**\n     * \\brief Returns an immutable sequence containing the global indices of the shape functions associated to this cell. \n     * \n     * Global indices start at 0 and are consecutive - in the range returned here, an unordered subset\n     * is contained.\n     */\n    GlobalIndexRange globalIndices(Cell const& cell) const\n    {\n      return globalIndices(implementation.indexSet().index(cell));\n    }\n\n    /**\n     * \\brief Returns an immutable sequence containing the global indices of the shape functions associated to this cell. \n     * \n     * Global indices start at 0 and are consecutive - in the range returned here, an unordered subset\n     * is contained.\n     */\n    GlobalIndexRange globalIndices(size_t n) const\n    {\n      return GlobalIndexRange(GlobalIndexIterator(globIdx[n].begin(),First()),\n                              GlobalIndexIterator(globIdx[n].end(),  First()));\n    }\n\n    /**\n     * \\brief Returns an empty range just for initialization, since RangeView is not default constructible.\n     */\n    static SortedIndexRange initSortedIndexRange()\n    {\n      static std::vector<IndexPair> dummy; // empty\n      return SortedIndexRange(dummy.begin(),dummy.end());\n    }\n\n    /**\n     * \\brief Returns an immutable sequence of (global index, local index) pairs sorted in ascending global index order.\n     */\n    SortedIndexRange sortedIndices(Cell const& cell) const\n    {\n      return sortedIndices(implementation.indexSet().index(cell));\n    }\n\n    /**\n     * \\brief Returns an immutable sequence of (global index, local index) pairs sorted in ascending global index order.\n     */\n    SortedIndexRange sortedIndices(size_t n) const\n    {\n      return SortedIndexRange(sortedIdx[n].begin(),sortedIdx[n].end());\n    }\n\n    /**\n     * \\brief Returns the number of global degrees of freedom managed. \n     * \n     * Note that this does not correspond directly to the number of\n     * coefficients in a FE function (if the FE function has more than\n     * one component).\n     */\n    size_t size() const { return n; }\n\n    /**\n     * \\brief DEPRECATED. Use maxOrder instead. This method will be removed after 2016-12-31.\n     */\n    int getOrder() const { return order; }\n\n    /**\n     * \\brief Returns the set of shape functions defined on this cell.\n     * \\param cell the codim 0 entity of the grid for wich the shape functions are to be retrieved\n     * \\param contained if true, the method may assume that the cell is contained in the index set of the space.\n     *                  (The other case occurs during interpolation between different grids).\n     */\n    ShapeFunctionSet const& shapefunctions(Cell const& cell, bool contained=false) const\n    {\n      if (contained || implementation.indexSet().contains(cell))\n        return shapefunctions(implementation.indexSet().index(cell));\n      else\n        return implementation.shapeFunctions(cell);\n      // This is the previous implementation (as of Kaskade 7.1). I'm not sure the\n      // condition of the if makes sense at all. First, cell has to be contained in\n      // the index set, otherwise the index and hence globalIndices(cell) is undefined.\n      // However, if the cell is contained in the index set, the globalIndices are not\n      // empty (compare the construction in update()). Ws-2012-06-07.\n      //\n      //     if ( cell.isLeaf() && globalIndices(cell).empty() )\n      //       return implementation.emptyShapeFunctionSet();\n      //     else\n      //       return implementation.shapeFunctions(cell);\n    }\n\n    ShapeFunctionSet& shapefunctions_non_const(Cell const& cell)\n    {\n      return shapefunctions_non_const(implementation.indexSet().index(cell));\n    }\n\n    /**\n     * \\brief Returns the set of shape functions defined on this cell.\n     */\n    ShapeFunctionSet const& shapefunctions(size_t n) const\n    {\n      return *sfs[n];    \n    }\n\n    ShapeFunctionSet& shapefunctions_non_const(size_t n)\n    {\n      return *sfs[n];\n    }\n\n    ShapeFunctionSet const& lowerShapeFunctions(Cell const& cell) const\n    {\n      if (globalIndices(cell).empty())\n        return implementation.emptyShapeFunctionSet();\n      else\n        return implementation.lowerShapeFunctions(cell);\n    }\n\n    /**\n     * \\brief Returns a combiner for the given leaf cell.\n     * \\param cell the grid cell for which the combiner is requested\n     * \\param index the index of the cell\n     */\n    Combiner combiner(Cell const& cell, size_t index) const {\n      assert(implementation.indexSet().index(cell)==index);\n      return Combiner(rangeView(globIdx[index].begin(),globIdx[index].end()));\n    }\n\n    /**\n     * \\brief (Re)computes the internal data.\n     *\n     * This has to be called after grid modifications and on construction.\n     */\n    void update()\n    {\n      GridView const& gridView = implementation.gridView();\n      IndexSet const& indexSet = implementation.indexSet();\n\n      // For each codimension (i.e. type of subentity) compute the\n      // number of global ansatz functions as well as an accumulated\n      // index into an array of all ansatz functions.\n      startIndex.clear();\n      // compute global degrees of freedom and store the offsets for\n      // different geometry types in startIndex\n      // see MapperPolicy\n      // Precompute and cache all the global indices. First allocate the\n      // memory needed to prevent frequent reallocation.\n      this->initIndices(startIndex,globIdx,sortedIdx);\n\n      sfs.resize(indexSet.size(0));\n      order = 0;\n\n      // Step through all cells and compute the global ansatz function\n      // indices of all shape functions on that cell.\n      for(auto const& element : elements(gridView))\n      {\n        size_t const cellIndex = indexSet.index(element);\n        ShapeFunctionSet const& sf = implementation.shapeFunctions(element);\n        this->initShapeFunctionSet(sfs,sf,cellIndex);                           // initShapeFunctionSet is defined in template base class MapperPolicy.\n        order = std::max(order,sf.order());\n        this->computeIndices(element, startIndex, globIdx, sortedIdx, cellIndex);   // computeIndices is defined in template base class MapperPolicy.\n\n\n        // sort the index pairs according to the global index\n        std::sort(sortedIdx[cellIndex].begin(),sortedIdx[cellIndex].end(),FirstLess());\n\n        // make sure that any assigned shape function forms at most one ansatz function.\n        // This is a functionality restriction, but seems quite reasonable as a debugging check.\n        // Note that not all shape functions need not be assigned. If a shape function is mapped     //Jakob: Are negative indices for unused shape function really allowed? Are'nt they simply not present in globIdx, such that the check idx[j]<0 below is nonsense?\n        // to negative global index, it takes not part at all (e.g. in hp-methods).\n#ifndef NDEBUG\n        std::vector<int> idx(globIdx[cellIndex].size());\n        for (int j=0; j<idx.size(); ++j) idx[j] = globIdx[cellIndex][j].first();\n        std::sort(idx.begin(),idx.end());\n        for (int j=1; j<idx.size(); ++j) assert(idx[j]>idx[j-1] || idx[j]<0);\n#endif\n      }\n\n      // compute overall number of degrees of freedom\n      n = 0;\n      for(size_t i=0; i<globIdx.size(); ++i)\n        if(globIdx[i].size() > 0)\n          n = std::max(n,std::max_element(globIdx[i].begin(),globIdx[i].end(),ScalarSpaceDetail::FirstLess())->first());\n      ++n;\n    }\n\n    /**\n     * \\brief Returns a half-open range of global indices that are associated\n     * to the entities with given geometry type.\n     *\n     * This is useful to partition stiffness matrices when using higher\n     * order hierarcical ansatz functions in order to use a direct\n     * solver on the low order ansatz functions as a preconditioner.\n     */\n    std::pair<size_t,size_t> globalIndexRange(Dune::GeometryType gt) const\n    {\n      assert(startIndex.find(gt)!=startIndex.end());\n\n      size_t first = startIndex.find(gt)->second;\n      size_t last = size();\n\n      for (auto const& si: startIndex)\n        if (si.second>first && si.second<last)\n          last = si.second;\n\n      return std::make_pair(first,last);\n    }\n\n  private:\n    // In startIndex, for any geometry type that occurs in the indexSet\n    // there is an index stored, such that the dofs associated with\n    // nodes on subentities of this type start at this index. We request\n    // that there is a fixed number of dofs associated with each\n    // subentity type, such that equal length index blocks are assigned\n    // to each subentity of a given type. The layout of dofs is thus as\n    // follows (example continuous 2D simplex mesh with two triangles,\n    // order 4):\n    //\n    // [Interior Triangle Nodes, Interior Edge Nodes, Vertex Nodes] with substructuring\n    // [ [[t1a,t1b,t1c],[t2a,t2b,t2c]], [[e1a,e1b],[e2a,e2b],[e3a,e3b],[e4a,e4b],[e5a,e5b]], [v1,v2,v3,v4] ]\n    //     | start index triangles        | start index edges                                 | start index vertices\n    // localDofs(triangles)=3, localDofs(edges)=2, localDofs(vertices)=1\n    size_t                              n;\n    std::map<Dune::GeometryType,size_t> startIndex;\n\n    // In globIdx, for each cell there are the global ansatz function indices of the\n    // shape functions on that cell.\n    std::vector<std::vector<Data>>      globIdx;\n\n    // In sortedIdx, for each cell there is a vector of (global index, local index) pairs, sorted ascendingly\n    // by the global index. This could be computed outside on demand, but the sorting takes time and may be\n    // amortized over multiple assembly passes/matrix blocks if cached here.\n    std::vector<std::vector<IndexPair> > sortedIdx;\n\n    // In sfs, for each cell there is a pointer to the shape function set on this cell cached.\n    std::vector<typename std::conditional<ScalarSpaceDetail::MapperPolicy<Implementation,SFData>::boundaryPolicy,ShapeFunctionSet,ShapeFunctionSet const>::type*> sfs;\n    //std::vector<ShapeFunctionSet const*> sfs;\n\n    int                                 order;\n\n  protected:\n    using ScalarSpaceDetail::MapperPolicy<Implementation,SFData>::implementation; // direct access to base class member variable\n  };\n} // end of namespace Kaskade\n\n#endif\n", "meta": {"hexsha": "0f545590de6291ebe5bd00de069cd26321bd87f8", "size": 23812, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/scalarspace.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/scalarspace.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/scalarspace.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": 39.4892205638, "max_line_length": 263, "alphanum_fraction": 0.6377876701, "num_tokens": 5445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.038466189538183315, "lm_q1q2_score": 0.01581386861709187}}
{"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}  // namespace applications\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\nint main(int argc, char* argv[]) {\n  std::string problem, domain;\n  size_t initial_refines = 0;\n  size_t max_level = 0;\n  size_t max_dofs = 0;\n  std::string refine;\n  bool calculate_condition_PY = false;\n  bool calculate_condition_PX = false;\n  bool print_time_apply = false;\n  bool print_centers = false;\n  double solve_rtol = 1e-5;\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_level\",\n      po::value<size_t>(&max_level)\n          ->default_value(std::numeric_limits<std::size_t>::max()))(\n      \"max_dofs\", po::value<size_t>(&max_dofs)->default_value(\n                      std::numeric_limits<std::size_t>::max()))(\n      \"refine\", po::value<std::string>(&refine)->default_value(\"sparse\"))(\n      \"print_centers\", po::value<bool>(&print_centers))(\n      \"print_time_apply\", po::value<bool>(&print_time_apply))(\n      \"calculate_condition_PX\", po::value<bool>(&calculate_condition_PX))(\n      \"calculate_condition_PY\", po::value<bool>(&calculate_condition_PY));\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_rtol\", po::value<double>(&solve_rtol))(\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  if (refine != \"sparse\" && refine != \"full\" && refine != \"local\") {\n    std::cout << \"Refine method `\" << refine << \"` not recognized.\"\n              << std::endl;\n    return 1;\n  }\n\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 << \"\\tRefinement method: \" << refine << std::endl;\n  std::cout << std::endl;\n  std::cout << adapt_opts << \"\\tsolve-rtol: \" << solve_rtol << std::endl\n            << std::endl;\n\n  auto T = InitialTriangulation(domain, initial_refines);\n  auto B = Time::Bases();\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  auto start_algorithm = std::chrono::steady_clock::now();\n\n  Eigen::VectorXd solution = Eigen::VectorXd::Zero(vec_Xd->container().size());\n  std::vector<typename HeatEquation::TypeXVector::DNType*> max_gradedness;\n  for (int level = 1; level < max_level; level++) {\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    vec_Xd->FromVectorContainer(solution);\n\n    // Refine underlying\n    if (refine == \"sparse\")\n      vec_Xd->SparseRefine(2 * level, {2, 1}, /* grow_tree */ true);\n    else if (refine == \"full\")\n      vec_Xd->UniformRefine({level, 2 * level}, /* grow_tree */ true);\n    else if (refine == \"local\")\n      vec_Xd->DeepRefine(\n          [level](auto dblnode) {\n            auto [psi_time, psi_space] = dblnode;\n            if (2 * psi_time->level() + psi_space->level() > 2 * level)\n              return false;\n            return (psi_time->is_metaroot() ||\n                    psi_time->Interval().first == 0) &&\n                   (psi_space->is_metaroot() ||\n                    psi_space->TouchesDomainBoundary());\n          },\n          [&](auto dblnode) {\n            dblnode->node_0()->Refine();\n            dblnode->node_1()->Refine();\n          });\n\n    solution = vec_Xd->ToVectorContainer();\n    size_t ndof_Xd = vec_Xd->Bfs().size();  // A slight overestimate.\n    if (ndof_Xd == 0) continue;\n    if (ndof_Xd > max_dofs) break;\n    AdaptiveHeatEquation heat_eq(vec_Xd, std::move(problem_data.first),\n                                 std::move(problem_data.second), adapt_opts);\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 << \"\\nlevel: \" << level << \"\\n\\tXDelta-size: \" << ndof_Xd\n              << \"\\n\\tXDelta-Gradedness: \"\n              << vec_Xd->Gradedness(&max_gradedness)\n              << \"\\n\\tXDelta-time-size: \" << vec_Xd->Project_0()->Bfs().size()\n              << \"\\n\\tXDelta-space-size: \" << vec_Xd->Project_1()->Bfs().size()\n              << \"\\n\\tXDeltaDelta-size: \" << ndof_Xdd\n              << \"\\n\\tYDeltaDelta-size: \" << ndof_Ydd\n              << \"\\n\\ttotal-memory-kB: \" << getmem() << std::flush;\n\n    if (calculate_condition_PY || calculate_condition_PX) {\n      auto start = std::chrono::steady_clock::now();\n      std::chrono::duration<double> duration_cond =\n          std::chrono::steady_clock::now() - start;\n\n      if (calculate_condition_PY) {\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        std::cout << \"\\n\\tlmin-PY-A: \" << lanczos_Y.min()\n                  << \"\\n\\tlmax-PY-A: \" << lanczos_Y.max();\n      }\n\n      if (calculate_condition_PX) {\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-PX-S: \" << lanczos_X.min()\n                  << \"\\n\\tlmax-PX-S: \" << lanczos_X.max();\n      }\n      std::cout << \"\\n\\tcond-time: \" << duration_cond.count();\n      continue;\n    }\n\n    // Solve - estimate.\n    auto start = std::chrono::steady_clock::now();\n    auto [cur_solution, pcg_data] =\n        heat_eq.Solve(solution, heat_eq.RHS(), solve_rtol,\n                      tools::linalg::StoppingCriterium::Relative);\n    solution = cur_solution;\n    std::chrono::duration<double> duration_solve =\n        std::chrono::steady_clock::now() - start;\n    std::cout << \"\\n\\tsolve-PCG-steps: \" << pcg_data.iterations\n              << \"\\n\\tsolve-time: \" << duration_solve.count()\n              << \"\\n\\tsolve-memory: \" << getmem() << std::flush;\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\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    std::chrono::duration<double> duration_estimate =\n        std::chrono::steady_clock::now() - start;\n\n    std::cout << \"\\n\\tresidual-norm: \" << residual_norm\n              << \"\\n\\testimate-time: \" << duration_estimate.count()\n              << \"\\n\\testimate-memory: \" << getmem() << std::flush;\n    std::cout << \"\\n\\tglobal-error: \" << global_error.error\n              << \"\\n\\tYnorm-error: \" << global_error.error_Yprime\n              << \"\\n\\tT0-error: \" << global_error.error_t0\n              << \"\\n\\ttotal-time-algorithm: \"\n              << std::chrono::duration<double>(\n                     std::chrono::steady_clock::now() - start_algorithm)\n                     .count()\n              << std::flush;\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\n  return 0;\n}\n", "meta": {"hexsha": "4d52bc373decd683816a44e7aac8add90665ad64", "size": 12742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/applications/uniform.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/uniform.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/uniform.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": 42.6153846154, "max_line_length": 79, "alphanum_fraction": 0.5908020719, "num_tokens": 3398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03161876532954494, "lm_q1q2_score": 0.01580938266477247}}
{"text": "/*****************************************************************************/\n/*  Copyright (c) 2015, Karl Pauwels                                         */\n/*  All rights reserved.                                                     */\n/*                                                                           */\n/*  Redistribution and use in source and binary forms, with or without       */\n/*  modification, are permitted provided that the following conditions       */\n/*  are met:                                                                 */\n/*                                                                           */\n/*  1. Redistributions of source code must retain the above copyright        */\n/*  notice, this list of conditions and the following disclaimer.            */\n/*                                                                           */\n/*  2. Redistributions in binary form must reproduce the above copyright     */\n/*  notice, this list of conditions and the following disclaimer in the      */\n/*  documentation and/or other materials provided with the distribution.     */\n/*                                                                           */\n/*  3. Neither the name of the copyright holder nor the names of its         */\n/*  contributors may be used to endorse or promote products derived from     */\n/*  this software without specific prior written permission.                 */\n/*                                                                           */\n/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      */\n/*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT        */\n/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */\n/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT     */\n/*  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   */\n/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT         */\n/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */\n/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */\n/*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT      */\n/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */\n/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */\n/*****************************************************************************/\n\n#include <cmath>\n#include <cstdio>\n#include <translation_rotation_3d.h>\n#undef Success\n#include <Eigen/Geometry>\n\nnamespace pose {\n\nconst double TranslationRotation3D::PI_ = 3.1415926535897931;\n\nTranslationRotation3D::TranslationRotation3D(bool valid) : valid_{ valid } {\n  double tmpT[3] = { 0.0, 0.0, 0.0 };\n  setT(tmpT);\n  double tmpR[3] = { 0.0, 0.0, 0.0 };\n  setR(tmpR);\n}\n\nTranslationRotation3D::TranslationRotation3D(const double *T_in,\n                                             const double *R_in)\n    : valid_{ true } {\n  setT(T_in);\n  setR(R_in);\n}\n\nTranslationRotation3D::TranslationRotation3D(Eigen::Vector3d T,\n                                             Eigen::Vector3d R) {\n  double T_in[3];\n  double R_in[3];\n  Eigen::Map<Eigen::Vector3d> T_tmp(T_in);\n  Eigen::Map<Eigen::Vector3d> R_tmp(R_in);\n  T_tmp = T;\n  R_tmp = R;\n  setT(T_in);\n  setR(R_in);\n}\n\ntemplate <typename Type>\nTranslationRotation3D::TranslationRotation3D(const Type TR_in[6])\n    : valid_{ true } {\n  double T_in[3], R_in[3];\n  for (int i = 0; i < 3; i++) {\n    T_in[i] = static_cast<double>(TR_in[i]);\n    R_in[i] = static_cast<double>(TR_in[i + 3]);\n  }\n  setT(T_in);\n  setR(R_in);\n}\ntemplate TranslationRotation3D::TranslationRotation3D<float>(\n    const float TR_in[6]);\ntemplate TranslationRotation3D::TranslationRotation3D<double>(\n    const double TR_in[6]);\n\nTranslationRotation3D::TranslationRotation3D(\n    const Ogre::Vector3 &ogre_translation,\n    const Ogre::Quaternion &ogre_rotation)\n    : valid_{ true } {\n  double tmpT[3] = { ogre_translation.x, ogre_translation.y,\n                     ogre_translation.z };\n  double tmpR_mat[9];\n\n  Eigen::Quaterniond q_eigen(ogre_rotation.w, ogre_rotation.x, ogre_rotation.y,\n                             ogre_rotation.z);\n\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_eig(tmpR_mat);\n  rot_eig = q_eigen.toRotationMatrix();\n\n  setT(tmpT);\n  setR_mat(tmpR_mat);\n}\n\nbool TranslationRotation3D::operator==(const TranslationRotation3D &op) const {\n  bool equal = true;\n  for (int i = 0; i < 3; i++) {\n    equal = (equal && (op.T_[i] == T_[i]));\n    equal = (equal && (op.R_[i] == R_[i]));\n  }\n  equal = (equal && (op.valid_ == valid_));\n  return (equal);\n}\n\nbool TranslationRotation3D::operator!=(const TranslationRotation3D &op) const {\n  return (!(*this == op));\n}\n\nTranslationRotation3D &TranslationRotation3D::\noperator*=(const TranslationRotation3D &rhs) {\n  // Fl = Fl*Fr;\n  Eigen::Map<Eigen::Vector3d> tra_left(T_);\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_left(R_mat_);\n  double T_rhs[3];\n  rhs.getT(T_rhs);\n  Eigen::Map<Eigen::Vector3d> tra_right(T_rhs);\n  double R_mat_rhs[9];\n  rhs.getR_mat(R_mat_rhs);\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_right(\n      R_mat_rhs);\n\n  tra_left = rot_left * tra_right + tra_left;\n  rot_left *= rot_right;\n  updateR();\n\n  // convert back to rotation matrix to increase numerical stability\n  updateR_mat();\n\n  // apply logical AND to validity\n  setValid(isValid() && rhs.isValid());\n\n  return *this;\n}\n\ndouble TranslationRotation3D::normT2() const {\n  return (T_[0] * T_[0] + T_[1] * T_[1] + T_[2] * T_[2]);\n}\n\ndouble TranslationRotation3D::normR2() const {\n  return (R_[0] * R_[0] + R_[1] * R_[1] + R_[2] * R_[2]);\n}\n\nTranslationRotation3D TranslationRotation3D::changeHandedness() const {\n\n  // Eigen conversion\n  // ----------------\n\n  //  Eigen::Vector3d t(t_buf[0], t_buf[1], t_buf[2]);\n  //  Eigen::Matrix3d Rl;\n\n  //  Rl << r_buf[0], r_buf[1], r_buf[2],\n  //      r_buf[3], r_buf[4], r_buf[5],\n  //      r_buf[6], r_buf[7], r_buf[8];\n\n  //  // transform translation to right-handed system (flip-y)\n  //  t(1) = -t(1);\n\n  //  // transform rotation to right-handed system\n  //  // flip-y, followed by 180 degree rotation around x-axis to convert ogre\n  // (z-out)\n  //  // to vision (z-forward)\n  //  Eigen::Matrix3d Sy = Eigen::Matrix<double, 3, 3>::Identity();\n  //  Sy(1,1) = -1.0;\n  //  Eigen::Matrix3d Rx_180 = Eigen::Matrix<double, 3, 3>::Identity();\n  //  Rx_180(1,1) = -1.0;\n  //  Rx_180(2,2) = -1.0;\n  //  Eigen::Matrix3d R = Sy * Rl * Sy * Rx_180;\n\n  // direct conversion\n  // -----------------\n\n  // flip ty\n  double T_out[]{ T_[0], -T_[1], T_[2] };\n\n  // (flip row 2 and then flip column 3)\n  double R_out[]{ R_mat_[0], R_mat_[1], -R_mat_[2], -R_mat_[3], -R_mat_[4],\n                  R_mat_[5], R_mat_[6], R_mat_[7],  -R_mat_[8] };\n\n  TranslationRotation3D TR_out;\n  TR_out.setT(T_out);\n  TR_out.setR_mat(R_out);\n  TR_out.setValid(valid_);\n\n  return TR_out;\n}\n\nTranslationRotation3D TranslationRotation3D::rotateX180() const {\n  double T_out[]{ T_[0], T_[1], T_[2] };\n  double R_out[]{ R_mat_[0],  -R_mat_[1], -R_mat_[2], R_mat_[3], -R_mat_[4],\n                  -R_mat_[5], R_mat_[6],  -R_mat_[7], -R_mat_[8] };\n\n  TranslationRotation3D TR_out;\n  TR_out.setT(T_out);\n  TR_out.setR_mat(R_out);\n  TR_out.setValid(valid_);\n\n  return TR_out;\n}\n\nTranslationRotation3D TranslationRotation3D::inverseTransform() const {\n\n  Eigen::Map<const Eigen::Vector3d> tra(T_);\n  Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot(R_mat_);\n\n  double rot_inv_ptr[9];\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_inv(\n      rot_inv_ptr);\n\n  rot_inv = rot.transpose();\n  double tra_inv_ptr[3];\n  Eigen::Map<Eigen::Vector3d> tra_inv(tra_inv_ptr);\n  tra_inv = -rot_inv * tra;\n\n  TranslationRotation3D pose_inv;\n  pose_inv.setT(tra_inv_ptr);\n  pose_inv.setR_mat(rot_inv_ptr);\n  pose_inv.setValid(valid_);\n\n  return (pose_inv);\n}\n\nOgre::Vector3 TranslationRotation3D::ogreTranslation() const {\n  return Ogre::Vector3(T_[0], T_[1], T_[2]);\n}\n\nvoid TranslationRotation3D::getQuaternion(double &x, double &y, double &z,\n                                          double &w) const {\n  Eigen::Matrix3d R_eigen;\n  R_eigen << R_mat_[0], R_mat_[1], R_mat_[2], R_mat_[3], R_mat_[4], R_mat_[5],\n      R_mat_[6], R_mat_[7], R_mat_[8];\n\n  Eigen::Quaterniond q_eigen;\n  q_eigen = R_eigen;\n\n  x = q_eigen.x();\n  y = q_eigen.y();\n  z = q_eigen.z();\n  w = q_eigen.w();\n}\n\nOgre::Quaternion TranslationRotation3D::ogreRotation() const {\n  double x, y, z, w;\n  getQuaternion(x, y, z, w);\n  return Ogre::Quaternion(w, x, y, z);\n}\n\nEigen::Vector3d TranslationRotation3D::eigenTranslation() const {\n  Eigen::Map<const Eigen::Vector3d> trans(T_);\n  return trans;\n}\n\nEigen::Matrix3d TranslationRotation3D::eigenRotation() const {\n  Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_mat(\n      R_mat_);\n  return rot_mat;\n}\n\nEigen::MatrixXd TranslationRotation3D::adjoint() const {\n  double F_ptr[4 * 4];\n  Eigen::Map<const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> > F(F_ptr);\n  getF(F_ptr);\n  Eigen::MatrixXd adj(6, 6);\n  Eigen::Vector3d T = F.topRightCorner<3, 1>();\n  Eigen::Matrix3d R = F.topLeftCorner<3, 3>();\n  Eigen::Matrix3d skewT;\n  skewT << 0.0, -T(2), T(1), T(2), 0.0, -T(0), -T(1), T(0), 0.0;\n  adj << R, skewT *R, Eigen::Matrix3d::Zero(), R;\n  return adj;\n}\n\nvoid TranslationRotation3D::createGLModelMatrix(float *M_out) const {\n  double TGL[3], RGL[3];\n  getT(TGL);\n  getR(RGL);\n\n  TGL[2] = -TGL[2];\n  RGL[2] = -RGL[2];\n\n  TranslationRotation3D TR(TGL, RGL);\n\n  double R_matGL[9];\n  TR.getR_mat(R_matGL);\n\n  M_out[0] = R_matGL[0];\n  M_out[1] = R_matGL[1];\n  M_out[2] = R_matGL[2];\n  M_out[3] = 0.0;\n  M_out[4] = R_matGL[3];\n  M_out[5] = R_matGL[4];\n  M_out[6] = R_matGL[5];\n  M_out[7] = 0.0;\n  M_out[8] = R_matGL[6];\n  M_out[9] = R_matGL[7];\n  M_out[10] = R_matGL[8];\n  M_out[11] = 0.0;\n  M_out[12] = TGL[0];\n  M_out[13] = TGL[1];\n  M_out[14] = TGL[2];\n  M_out[15] = 1.0;\n}\n\nbool TranslationRotation3D::isFinite() const {\n  bool res = true;\n  for (int i = 0; i < 3; i++) {\n    res = res && std::isfinite(T_[i]);\n    res = res && std::isfinite(R_[i]);\n  }\n\n  return res;\n}\n\nvoid TranslationRotation3D::getEuler(double &Ex, double &Ey, double &Ez) const {\n  //  [ 0 1 2\n  //    3 4 5\n  //    6 7 8 ]\n  // http://nghiaho.com/?page_id=846\n\n  double r32 = R_mat_[7];\n  double r33 = R_mat_[8];\n  double r31 = R_mat_[6];\n  double r21 = R_mat_[3];\n  double r11 = R_mat_[0];\n\n  Ex = atan2(r32, r33);\n  Ey = atan2(-r31, sqrt(r32 * r32 + r33 * r33));\n  Ez = atan2(r21, r11);\n}\n\nvoid TranslationRotation3D::getF(double *F_out) const {\n  Eigen::Map<Eigen::Matrix<double, 4, 4, Eigen::RowMajor> > hom(F_out);\n  hom << eigenRotation(), eigenTranslation(), 0.0, 0.0, 0.0, 1.0;\n}\n\nvoid TranslationRotation3D::setT(const double *T_in) {\n  for (int i = 0; i < 3; i++)\n    T_[i] = T_in[i];\n}\n\nvoid TranslationRotation3D::setR(const double *R_in) {\n  for (int i = 0; i < 3; i++)\n    R_[i] = R_in[i];\n  updateR_mat();\n}\n\nvoid TranslationRotation3D::setR_mat(double *R_mat_in) {\n  for (int i = 0; i < 9; i++)\n    R_mat_[i] = R_mat_in[i];\n  updateR();\n}\n\nvoid TranslationRotation3D::setF(const std::vector<double> &F_in) {\n  if (F_in.size() != 16)\n    throw std::runtime_error(\n        \"TranslationRotation3D::setF: F_in requires 16 elements\");\n\n  if ((F_in.at(12) != 0.0) || (F_in.at(13) != 0.0) || (F_in.at(14) != 0.0) ||\n      (F_in.at(15) != 1.0))\n    throw std::runtime_error(\n        \"TranslationRotation3D::setF: bottom row of F_in should be [0 0 0 1]\");\n\n  Eigen::Map<const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> > F_in_eig(\n      F_in.data());\n\n  Eigen::Transform<double, 3, Eigen::Affine> F;\n  F = F_in_eig;\n\n  double tmpT[3];\n  Eigen::Map<Eigen::Vector3d> tra_eig(tmpT);\n  tra_eig = F.translation();\n\n  double tmpR_mat[9];\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_eig(tmpR_mat);\n  rot_eig = F.rotation();\n\n  setT(tmpT);\n  setR_mat(tmpR_mat);\n  updateR_mat(); // for stability\n}\n\nvoid TranslationRotation3D::translateX(double Tx) { T_[0] += Tx; }\n\nvoid TranslationRotation3D::translateY(double Ty) { T_[1] += Ty; }\n\nvoid TranslationRotation3D::translateZ(double Tz) { T_[2] += Tz; }\n\nvoid TranslationRotation3D::rotateX(double angle_deg) {\n  double angle_rad = angle_deg * PI_ / 180.0;\n  double c = cos(angle_rad);\n  double s = sin(angle_rad);\n  Eigen::Matrix3d Rx;\n  Rx << 1.0, 0.0, 0.0, 0.0, c, -s, 0.0, s, c;\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot(R_mat_);\n  rot *= Rx;\n  updateR();\n  updateR_mat(); // for stability\n}\n\nvoid TranslationRotation3D::rotateY(double angle_deg) {\n  double angle_rad = angle_deg * PI_ / 180.0;\n  double c = cos(angle_rad);\n  double s = sin(angle_rad);\n  Eigen::Matrix3d Rx;\n  Rx << c, 0.0, s, 0.0, 1.0, 0.0, -s, 0, c;\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot(R_mat_);\n  rot *= Rx;\n  updateR();\n  updateR_mat(); // for stability\n}\n\nvoid TranslationRotation3D::rotateZ(double angle_deg) {\n  double angle_rad = angle_deg * PI_ / 180.0;\n  double c = cos(angle_rad);\n  double s = sin(angle_rad);\n  Eigen::Matrix3d Rx;\n  Rx << c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0;\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot(R_mat_);\n  rot *= Rx;\n  updateR();\n  updateR_mat(); // for stability\n}\n\nvoid TranslationRotation3D::show() const {\n  printf(\"T =     %+2.6f %+2.6f %+2.6f\\n\", T_[0], T_[1], T_[2]);\n  printf(\"R =     %+2.6f %+2.6f %+2.6f\\n\", R_[0], R_[1], R_[2]);\n  printf(\"R_mat = %+2.6f %+2.6f %+2.6f\\n\", R_mat_[0], R_mat_[1], R_mat_[2]);\n  printf(\"        %+2.6f %+2.6f %+2.6f\\n\", R_mat_[3], R_mat_[4], R_mat_[5]);\n  printf(\"        %+2.6f %+2.6f %+2.6f\\n\", R_mat_[6], R_mat_[7], R_mat_[8]);\n}\n\nvoid TranslationRotation3D::showCompact() const {\n  printf(\"T = %+2.6f %+2.6f %+2.6f | R = %+2.6f %+2.6f %+2.6f \", T_[0], T_[1],\n         T_[2], R_[0], R_[1], R_[2]);\n  if (isValid())\n    printf(\"valid\\n\");\n  else\n    printf(\"invalid\\n\");\n}\n\nvoid TranslationRotation3D::updateR() {\n  Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_mat(\n      R_mat_);\n  Eigen::Map<Eigen::Vector3d> rot_axis_angle(R_);\n  Eigen::AngleAxis<double> tmp(rot_mat);\n  rot_axis_angle = tmp.angle() * tmp.axis();\n}\n\nvoid TranslationRotation3D::updateR_mat() {\n\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > rot_mat(R_mat_);\n  Eigen::Map<const Eigen::Vector3d> rot_axis_angle(R_);\n\n  double angle = rot_axis_angle.norm();\n\n  if (angle < 1e-15) {\n    // identity matrix\n    rot_mat = Eigen::Matrix<double, 3, 3>::Identity();\n  } else {\n    rot_mat = Eigen::AngleAxis<double>(angle, rot_axis_angle / angle)\n                  .toRotationMatrix();\n  }\n}\n}\n", "meta": {"hexsha": "141ee08dd4fb29683b2f9a363d0115625c80c729", "size": 14722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation/src/translation_rotation_3d.cpp", "max_stars_repo_name": "carlo-/simtrack", "max_stars_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 99.0, "max_stars_repo_stars_event_min_datetime": "2015-07-06T11:18:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T08:20:12.000Z", "max_issues_repo_path": "pose_estimation/src/translation_rotation_3d.cpp", "max_issues_repo_name": "carlo-/simtrack", "max_issues_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T19:11:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-25T03:51:39.000Z", "max_forks_repo_path": "pose_estimation/src/translation_rotation_3d.cpp", "max_forks_repo_name": "carlo-/simtrack", "max_forks_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-07-06T11:36:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T01:32:18.000Z", "avg_line_length": 31.2569002123, "max_line_length": 80, "alphanum_fraction": 0.6024317348, "num_tokens": 4637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.032100704170602755, "lm_q1q2_score": 0.015799585741053737}}
{"text": "/*\n* Copyright 2019, Giorgio Zoppi\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 <string>\n#include <vector>\n#include <cstdlib>\n#include <boost/date_time.hpp>\n#include <amcl/mpin_BN254.h>\n#include <bsd/stdlib.h>\n#include <amcl/randapi.h>\n#include <amcl/pbc_support.h>\n#include <amcl/amcl.h>\n#include <utils.h>\n#include <secret_proxy.h>\n\nnamespace milagro\n{\n  namespace secure_store\n  {\n\n    using namespace BN254;\n    using namespace boost::local_time;\n\n      secret_proxy::secret_proxy ()\n    {\n      init_state ();\n    }\n    secret_proxy::secret_proxy (const std::string & path)\n    {\n      init_state ();\n\n    }\n    secret_proxy::~secret_proxy ()\n    {\n      KILL_CSPRNG (&_secure_random);\n    }\n    void secret_proxy::init_state ()\n    {\n      char raw[100];\n      // FIXME this works only on linux and bsd\n      arc4random_buf (raw, sizeof raw);\n      amcl::octet row_octet =\n      {\n      0, sizeof (raw), raw};\n      CREATE_CSPRNG (&_secure_random, &row_octet);\n    }\n    /*\n     * Generate the D-TA master secret -\n     * @param type  type of the store, optional parameter.\n     */\n    amcl::octet secret_proxy::generate_master_secret (store_type type)\n    {\n      char secret_chars[PGS_BN254];\n      amcl::octet secret =\n      {\n      0, sizeof (secret_chars), secret_chars};\n      _master_startTime = boost::posix_time::second_clock::local_time ();\n      MPIN_RANDOM_GENERATE (&_secure_random, &secret);\n      return secret;\n    }\n    /*\n     *  Generate the client secret for the MPIN Protocol. \n     *  One between the user_id or the hash_pin_id shall be present.\n     *  If juse the user_id is present create the hash from the user_id.\n     *  @param user_id optional value for the user identifier\n     *  @param hash_pin_id optional value for the mpin\n     *  @returns An octect to be used as a secret key \n     */\n    amcl::octet secret_proxy::generate_client_secret (const std::optional <\n\t\t\t\t\t\t      std::string > &user_id,\n\t\t\t\t\t\t      const std::optional <\n\t\t\t\t\t\t      std::string >\n\t\t\t\t\t\t      &hash_pin_id,\n\t\t\t\t\t\t      store_type type)\n    {\n      char client_id[256];\n      char idhex[256];\n      char token[2 * PFS_BN254 + 1];\n      char hcid[PFS_BN254];\n      amcl::octet HCID =\n      {\n      0, sizeof (hcid), hcid};\n      amcl::octet CLIENT_ID =\n      {\n      0, sizeof (client_id), client_id};\n      // compute when we shall expire.\n      auto local = local_sec_clock::local_time (time_zone_ptr ());\n      local += boost::gregorian::days (DAYS_CLIENT_SECRET_MAX);\n      _client_expireTime = local.utc_time ();\n      if (!user_id.has_value () && (!hash_pin_id.value ().size () == 64))\n\t{\n\t  throw std::invalid_argument (\"Client identifier too long\");\n\t}\n      milagro::utils::make_hash_id (hash_pin_id, user_id, HCID);\n      // we have here the hash id anyway.\n      amcl::octet TOKEN =\n      {\n      0, sizeof (token), token};\n      int currentSize = _master_secret.size ();\n      amcl::octet S =\n      {\n      currentSize, currentSize,\n\t  const_cast < char *>(_master_secret.c_str ())};\n      MPIN_GET_CLIENT_SECRET (&S, &HCID, &TOKEN);\n      return TOKEN;\n    }\n    /*\n     *  Get the time permits \n     * @param mash_\n     */\n    std::vector < std::string >\n      secret_proxy::get_time_permits (const\n\t\t\t\t      std::optional < std::string >\n\t\t\t\t      &mhash_pin_id, int count)\n    {\n      char permit[2 * PFS_BN254 + 1];\n      int day = amcl::today ();\n      std::vector < std::string > tmp;\n      amcl::octet HCID;\n      amcl::octet PERMIT =\n      {\n      0, sizeof (permit), permit};\n      int currentSize = _master_secret.size ();\n      amcl::octet S =\n      {\n      currentSize,\n\t  currentSize, const_cast < char *>(_master_secret.c_str ())};\n      milagro::utils::make_hash_id (mhash_pin_id, std::nullopt, HCID);\n      for (int i = 0; i < count; ++count)\n\t{\n\t  MPIN_GET_CLIENT_PERMIT (HASH_TYPE_BN254, day, &S, &HCID, &PERMIT);\n\t  // This encoding makes Time permit look random \n\t  if (MPIN_ENCODING (&_secure_random, &PERMIT) != 0)\n\t    {\n\t      throw std::runtime_error (\"Encoding permit is not possible\");\n\t    }\n\t  std::string str = milagro::utils::octet_to_string (PERMIT);\n\t  tmp.push_back (str);\n\t  std::memset (&PERMIT, 0, sizeof (amcl::octet));\n\t}\n      return tmp;\n    }\n    /*\n     *\n     */\n    boost::posix_time::ptime secret_proxy::client_key_expire ()const\n    {\n      return _client_expireTime;\n    }\n    /*\n     *\n     */\n    boost::posix_time::ptime secret_proxy::server_key_start () const\n    {\n      return _master_startTime;\n    }\n    /*\n     *  \n     */\n    std::optional < amcl::octet > secret_proxy::search_key (int appId)\n    {\n      auto value = _key_store.find (appId);\n      if (value != _key_store.end ())\n\t{\n\t  return std::make_optional < amcl::octet > (value->second);\n\t}\n      return std::nullopt;\n\n    }\n\n  }\n}\n", "meta": {"hexsha": "f4a3a22eba5fcb5ac7820d7092e5c9149e189403", "size": 5300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grpcserver/src/dta/secret_proxy.cpp", "max_stars_repo_name": "apache/incubator-milagro-mfa-server", "max_stars_repo_head_hexsha": "b33dfe864ff0bcb8a26a46745b9c596d72d22ccf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-09-18T19:13:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T18:35:30.000Z", "max_issues_repo_path": "grpcserver/src/dta/secret_proxy.cpp", "max_issues_repo_name": "apache/incubator-milagro-mfa-server", "max_issues_repo_head_hexsha": "b33dfe864ff0bcb8a26a46745b9c596d72d22ccf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-09-21T14:58:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-29T23:35:32.000Z", "max_forks_repo_path": "grpcserver/src/dta/secret_proxy.cpp", "max_forks_repo_name": "apache/incubator-milagro-mfa-server", "max_forks_repo_head_hexsha": "b33dfe864ff0bcb8a26a46745b9c596d72d22ccf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-05-24T11:15:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T18:35:22.000Z", "avg_line_length": 28.6486486486, "max_line_length": 75, "alphanum_fraction": 0.6196226415, "num_tokens": 1416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.032589742651931514, "lm_q1q2_score": 0.01578582229230782}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_LCCA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_LCCA_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/core/ignore_unused.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/pj_mlfn.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct lcca {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace lcca\n    {\n\n            static const int MAX_ITER = 10;\n            static const double DEL_TOL = 1e-12;\n\n            template <typename T>\n            struct par_lcca\n            {\n                T    en[EN_SIZE];\n                T    r0, l, M0;\n                T    C;\n            };\n\n            template <typename T> /* func to compute dr */\n            inline T fS(T const& S, T const& C)\n            {\n                return(S * ( 1. + S * S * C));\n            }\n\n            template <typename T> /* deriv of fs */\n            inline T fSp(T const& S, T const& C)\n            {\n                return(1. + 3.* S * S * C);\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_lcca_ellipsoid : public base_t_fi<base_lcca_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_lcca<CalculationType> m_proj_parm;\n\n                inline base_lcca_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_lcca_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, 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                    CalculationType S, r, dr;\n\n                    S = pj_mlfn(lp_lat, sin(lp_lat), cos(lp_lat), this->m_proj_parm.en) - this->m_proj_parm.M0;\n                    dr = fS(S, this->m_proj_parm.C);\n                    r = this->m_proj_parm.r0 - dr;\n                    xy_x = this->m_par.k0 * (r * sin( lp_lon *= this->m_proj_parm.l ) );\n                    xy_y = this->m_par.k0 * (this->m_proj_parm.r0 - r * cos(lp_lon) );\n                }\n\n                // INVERSE(e_inverse)  ellipsoid & 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                    CalculationType theta, dr, S, dif;\n                    int i;\n\n                    xy_x /= this->m_par.k0;\n                    xy_y /= this->m_par.k0;\n                    theta = atan2(xy_x , this->m_proj_parm.r0 - xy_y);\n                    dr = xy_y - xy_x * tan(0.5 * theta);\n                    lp_lon = theta / this->m_proj_parm.l;\n                    S = dr;\n                    for (i = MAX_ITER; i ; --i) {\n                        S -= (dif = (fS(S, this->m_proj_parm.C) - dr) / fSp(S, this->m_proj_parm.C));\n                        if (fabs(dif) < DEL_TOL) break;\n                    }\n                    if (!i)\n                        BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                    lp_lat = pj_inv_mlfn(S + this->m_proj_parm.M0, this->m_par.es, this->m_proj_parm.en);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"lcca_ellipsoid\";\n                }\n\n            };\n\n            // Lambert Conformal Conic Alternative\n            template <typename Parameters, typename T>\n            inline void setup_lcca(Parameters& par, par_lcca<T>& proj_parm)\n            {\n                T s2p0, N0, R0, tan0, tan20;\n\n                if (!pj_enfn(par.es, proj_parm.en))\n                    BOOST_THROW_EXCEPTION( projection_exception(0) );\n                if (!pj_param(par.params, \"tlat_0\").i)\n                    BOOST_THROW_EXCEPTION( projection_exception(50) );\n                if (par.phi0 == 0.)\n                    BOOST_THROW_EXCEPTION( projection_exception(51) );\n                proj_parm.l = sin(par.phi0);\n                proj_parm.M0 = pj_mlfn(par.phi0, proj_parm.l, cos(par.phi0), proj_parm.en);\n                s2p0 = proj_parm.l * proj_parm.l;\n                R0 = 1. / (1. - par.es * s2p0);\n                N0 = sqrt(R0);\n                R0 *= par.one_es * N0;\n                tan0 = tan(par.phi0);\n                tan20 = tan0 * tan0;\n                proj_parm.r0 = N0 / tan0;\n                proj_parm.C = 1. / (6. * R0 * N0);\n                boost::ignore_unused(tan20);\n            }\n\n    }} // namespace detail::lcca\n    #endif // doxygen\n\n    /*!\n        \\brief Lambert Conformal Conic 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         - Conic\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_0: Latitude of origin\n        \\par Example\n        \\image html ex_lcca.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct lcca_ellipsoid : public detail::lcca::base_lcca_ellipsoid<CalculationType, Parameters>\n    {\n        inline lcca_ellipsoid(const Parameters& par) : detail::lcca::base_lcca_ellipsoid<CalculationType, Parameters>(par)\n        {\n            detail::lcca::setup_lcca(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::lcca, lcca_ellipsoid, lcca_ellipsoid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class lcca_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<lcca_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void lcca_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"lcca\", new lcca_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_LCCA_HPP\n\n", "meta": {"hexsha": "a1a2069d8f1dce7e8035fec6168bff109c768c0b", "size": 9090, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/lcca.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/lcca.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/lcca.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": 39.1810344828, "max_line_length": 131, "alphanum_fraction": 0.600220022, "num_tokens": 2094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.033085980057180296, "lm_q1q2_score": 0.01576810483075073}}
{"text": "//==============================================================================\n//         Copyright 2014 - Jean-Thierry Lapresté\n//         Copyright 2003 - 2013   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_LU_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_LU_HPP_INCLUDED\n\n#include <nt2/linalg/functions/lu.hpp>\n#include <nt2/include/functions/eye.hpp>\n#include <nt2/include/functions/function.hpp>\n#include <nt2/include/functions/getrf.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/min.hpp>\n#include <nt2/include/functions/numel.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/include/functions/triu.hpp>\n#include <nt2/include/functions/tri1l.hpp>\n#include <nt2/include/functions/width.hpp>\n#include <nt2/core/container/colon/colon.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/error/warning.hpp>\n#include <nt2/linalg/options.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/core/ignore_unused.hpp>\n#include <algorithm>\n\n///Utilitary macro\n/// INTERNAL ONLY undefined at end of file\n#define CHECK_LAPACK_LU_SUCCESS(info)                        \\\n  {                                                          \\\n    nt2_la_int info_ = info;                                 \\\n    boost::ignore_unused(info_);                   \\\n    NT2_WARNING(info_ <= 0                                   \\\n               , \"LU factorization has been completed, \"     \\\n                \"but input matrix is exactly singular. \"     \\\n                \"Division by zero will occur if it is used \" \\\n                \"to solve a system of equations.\"            \\\n               );                                            \\\n  }                                                          \\\n  /**/\n\nnamespace nt2 { namespace ext\n{\n  //============================================================================\n  //lu Scalar\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( lu_, 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  //============================================================================\n  //lu Scalar\n  //============================================================================\n  BOOST_DISPATCH_IMPLEMENT  ( lu_, 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  //lu\n  //============================================================================\n  /// INTERNAL ONLY\n  BOOST_DISPATCH_IMPLEMENT  ( lu_, tag::cpu_\n                            , (A0)(N0)(A1)(N1)\n                            , ((node_ < A0, nt2::tag::lu_\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 nt2::memory::container<tag::table_, type_t, nt2::_2D>        o_semantic;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const\n    {\n      eval(a0, a1, N0(), N1());\n    }\n  private:\n    /// INTERNAL ONLY - y =  lu(a)\n    /// y is the direct lapack return from ?getrf and permutation is lost\n    /// only call for which raw_ is the default\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const& // # inputs\n              , boost::mpl::long_<1> const& // # outputs\n              ) const\n    {\n      //1_1 means 1 input 1 output\n      eval1_1(a0, a1\n             , nt2::policy<ext::raw_>());\n    }\n\n    /// INTERNAL ONLY - y =  lu(a, raw_)\n    /// y is the direct lapack return from ?getrf, and permutation is lost\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const& // # inputs\n              , boost::mpl::long_<1> const& // # outputs\n              ) const\n    {\n      // 1_2 means 1 input 2 outputs\n      eval1_2(a0, a1\n             , nt2::policy<ext::raw_>());\n    }\n\n    /// INTERNAL ONLY - [y, ls] =  lu(a, raw_)\n    /// y is the direct lapack return from ?getrf\n    /// permutation ls is in lapack swap lines indices form\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const& // # inputs\n              , boost::mpl::long_<2> const& // # outputs\n              ) const\n    {\n      // 2_2 means 2 input 2 outputs\n      eval1_2(a0, a1\n             , nt2::policy<ext::raw_>());\n    }\n\n    /// INTERNAL ONLY - [pl, u] =  lu(a)\n    /// pl is a permuted lower triangular matrix\n    //  u  is an upper triangular matrix\n    /// pl*u ==  a\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const& // # inputs\n              , boost::mpl::long_<2> const& // # outputs\n              ) const\n    {\n      // 1_2 means 1 input 2 outputs\n      eval1_2(a0, a1\n             , nt2::policy<ext::matrix_>());\n    }\n\n    /// INTERNAL ONLY - [l, u, p] =  lu(a)\n    /// pl is a permuted lower triangular matrix\n    //  u  is an upper triangular matrix\n    /// pl*u ==  a\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<1> const& // # inputs\n              , boost::mpl::long_<3> const& // # outputs\n              ) const\n    {\n      // 2_3 means 2 input 3 outputs\n      eval2_3(a0, a1\n             , nt2::policy<ext::matrix_>());\n    }\n\n    /// INTERNAL ONLY - [l, u, p] =  lu(a, vector_/matrix_)\n    /// pl is a permuted lower triangular matrix\n    //  u  is an upper triangular matrix\n    /// pl*u ==  a\n    BOOST_FORCEINLINE\n    void eval ( A0& a0, A1& a1\n              , boost::mpl::long_<2> const& // # inputs\n              , boost::mpl::long_<3> const& // # outputs\n              ) const\n    {\n      // 2_3 means 2 input 3 outputs\n      eval2_3(a0, a1\n             , boost::proto::value(boost::proto::child_c<1>(a0)));\n    }\n\n\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // evali_j bunch\n    ///////////////////////////////////////////////////////////////////////////////\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 1i 1o raw_\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\n                           , lu, boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      nt2::container::table<nt2_la_int> ls(of_size(dim(lu), 1));\n      CHECK_LAPACK_LU_SUCCESS((nt2::getrf( boost::proto::value(lu)\n                                         , boost::proto::value(ls))));\n      assign_swap(boost::proto::child_c<0>(a1), lu);\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 1i 2o raw_\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::raw_>&\n                   ) const\n    {\n      typedef nt2::memory::container<tag::table_, nt2_la_int, nt2::_2D> i_semantic;\n      NT2_AS_TERMINAL_INOUT(o_semantic\n                           , lu, boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_OUT(i_semantic, ls\n                         , boost::proto::child_c<1>(a1));\n\n      ls.resize(of_size(dim(lu), 1));\n      CHECK_LAPACK_LU_SUCCESS(nt2::getrf( boost::proto::value(lu)\n                                        , boost::proto::value(ls)));\n      assign_swap(boost::proto::child_c<0>(a1), lu);\n      assign_swap(boost::proto::child_c<1>(a1), ls);\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 1i 2o T other from raw_\n    template < class T >\n    BOOST_FORCEINLINE\n    void eval1_2 ( A0& a0, A1& a1\n                   , const T &\n                   ) const\n    {\n      NT2_AS_TERMINAL_INOUT(o_semantic, lu\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      std::size_t d  = dim(lu);\n      nt2::container::table<nt2_la_int> ls(of_size(d, 1));\n      CHECK_LAPACK_LU_SUCCESS(nt2::getrf( boost::proto::value(lu)\n                                        , boost::proto::value(ls)));\n      nt2::container::table<nt2_la_int> ip;\n      construct_ip(ls, ip, height(lu));\n      boost::proto::child_c<0>(a1) = nt2::tri1l(lu(nt2::_, nt2::_(1, d) ) )(ip, nt2::_);\n      boost::proto::child_c<1>(a1) = nt2::triu(lu( nt2::_(1, d), nt2::_) );\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 3o\n    BOOST_FORCEINLINE\n    void eval2_3 ( A0& a0, A1& a1\n                   , const nt2::policy<ext::vector_>&\n                   ) const\n    {\n      typedef typename boost::proto::result_of::child_c<A1&,2>::value_type     child;\n      typedef typename child::value_type                                     itype_t;\n      NT2_AS_TERMINAL_INOUT(o_semantic, lu\n                           , boost::proto::child_c<0>(a0)\n                           , boost::proto::child_c<1>(a1));\n      std::size_t d  = dim(lu);\n      nt2::container::table<nt2_la_int> ls(of_size(d, 1));\n      CHECK_LAPACK_LU_SUCCESS(nt2::getrf( boost::proto::value(lu)\n                                        , boost::proto::value(ls)));\n      nt2::container::table<itype_t> ip;\n      construct_ip(ls, ip, height(lu));\n      boost::proto::child_c<0>(a1) = nt2::tri1l(lu(nt2::_, nt2::_(1, d) ) );\n      boost::proto::child_c<1>(a1) = nt2::triu(lu( nt2::_(1, d), nt2::_) );\n      inverse(ip);\n      assign_swap(boost::proto::child_c<2>(a1), ip);\n    }\n\n    ///////////////////////////////////////////////////////////////////////////////\n    /// INTERNAL ONLY: 2i 3o\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, lu\n                           , boost::proto::child_c<0>(a0), work);\n      std::size_t d  = dim(lu);\n      nt2::container::table<nt2_la_int> ls(of_size(d, 1)), ip;\n      CHECK_LAPACK_LU_SUCCESS(nt2::getrf( boost::proto::value(lu)\n                                        , boost::proto::value(ls)));\n      construct_ip(ls, ip, height(lu));\n      boost::proto::child_c<1>(a1) = nt2::triu(lu( nt2::_(1, d), nt2::_) );\n      boost::proto::child_c<0>(a1) = nt2::tri1l(lu(nt2::_, nt2::_(1, d) ) );\n      boost::proto::child_c<2>(a1) = eye(height(lu), nt2::meta::as_<rtype_t>())(nt2::_, ip);\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 nt2::min(nt2::height(work),nt2::width(work));\n    }\n\n    /// INTERNAL ONLY\n    /// construct permutation vector from lapack swap vector\n    template < class T1, class T2>\n    BOOST_FORCEINLINE\n    void construct_ip(T1& ls, T2& ips, size_t h) const\n    {\n      std::size_t d = nt2::numel(ls);\n      ips = nt2::_(nt2_la_int(1), nt2_la_int(h));\n      for(std::size_t i = d; i >= 1; --i)\n      {\n        std::swap(ips(i), ips(ls(i)));\n      }\n    }\n\n    template < class T1>\n    BOOST_FORCEINLINE\n    void inverse(T1& ip) const\n    {\n      T1 inv(of_size(1, numel(ip)));\n      inv(ip) =  nt2::_(nt2_la_int(1), nt2_la_int(numel(ip)));\n      assign_swap(ip, inv);\n    }\n  };\n\n} }\n\n#undef CHECK_LAPACK_LU_SUCCESS\n\n#endif\n", "meta": {"hexsha": "194b2d17eb304dd10cde3db56573a316c7a86d9f", "size": 13215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/factorizations/lu.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/lu.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/lu.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.083573487, "max_line_length": 92, "alphanum_fraction": 0.4636398033, "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796361952087, "lm_q2_score": 0.033085977316112354, "lm_q1q2_score": 0.015768103032475753}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_Measurement_def.hpp\n//! \\author Alex Robinson\n//! \\brief  The measurement class declaration.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_MEASUREMENT_DEF_HPP\n#define UTILITY_MEASUREMENT_DEF_HPP\n\n// Std Lib Includes\n#include <cmath>\n#include <functional>\n\n// Boost Includes\n#include <boost/io/ios_state.hpp>\n\nnamespace Utility{\n\n// Constructor\ntemplate<typename T>\nMeasurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::Measurement(\n                                                 const ValueType& value,\n                                                 const ValueType& uncertainty )\n  : d_value( value ),\n    d_uncertainty( uncertainty )\n{\n  // Make sure the value is valid\n  testPrecondition( !Utility::isnaninf( value ) );\n  // Make sure the uncertainty is valid\n  testPrecondition( !Utility::isnaninf( uncertainty ) );\n  testPrecondition( uncertainty >= 0.0 );\n}\n\n// Copy constructor\ntemplate<typename T>\nMeasurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::Measurement( const Measurement<T>& other_measurement )\n  : d_value( other_measurement.d_value ),\n    d_uncertainty( other_measurement.d_uncertainty )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !Utility::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !Utility::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n}\n\n// Method for placing the object in an output stream\ntemplate<typename T>\ninline void Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::toStream( std::ostream& os ) const\n{\n  os << Utility::toString( d_value ) << \" +/- \"\n     << Utility::toString( d_uncertainty );\n}\n\n// Return the value of the measurement\ntemplate<typename T>\ninline auto Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::getValue() const -> const ValueType&\n{\n  return d_value;\n}\n\n// Return the uncertainty of the measurement\ntemplate<typename T>\ninline auto Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::getUncertainty() const -> const ValueType&\n{\n  return d_uncertainty;\n}\n\n// Return the relative uncertainty of the measurement\ntemplate<typename T>\ninline auto Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::getRelativeUncertainty() const -> ValueType\n{\n  if( d_value != 0.0 )\n    return d_uncertainty/fabs(d_value);\n  else\n    return 0.0;\n}\n\n// Return the lower bound of the measurement\ntemplate<typename T>\ninline auto Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::getLowerBound() const -> ValueType\n{\n  return d_value - d_uncertainty;\n}\n\n// Return the upper bound of the measurement\ntemplate<typename T>\ninline auto Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::getUpperBound() const -> ValueType\n{\n  return d_value + d_uncertainty;\n}\n\n// In-place addition operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator+=( const ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !Utility::isnaninf( value ) );\n\n  d_value += value;\n\n  return *this;\n}\n\n// In-place addition operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator+=( const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !Utility::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !Utility::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n\n  d_value += other_measurement.d_value;\n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( d_uncertainty*d_uncertainty +\n\t\t\t     other_measurement.d_uncertainty*\n\t\t\t     other_measurement.d_uncertainty );\n\n  return *this;\n}\n\n// In-place subtraction operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator-=( const ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !Utility::isnaninf( value ) );\n\n  d_value -= value;\n\n  return *this;\n}\n\n// In-place subtraction operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator-=( const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !Utility::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !Utility::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n\n  d_value -= other_measurement.d_value;\n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( d_uncertainty*d_uncertainty +\n\t\t\t     other_measurement.d_uncertainty*\n\t\t\t     other_measurement.d_uncertainty );\n\n  return *this;\n}\n\n// In-place multiplication operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator*=( const ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !Utility::isnaninf( value ) );\n\n  d_value *= value;\n\n  d_uncertainty *= fabs( value );\n\n  return *this;\n}\n\n// In-place multiplication operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator*=( const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !Utility::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !Utility::isnaninf( other_measurement.d_uncertainty ) );\n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( d_uncertainty*d_uncertainty*\n\t       other_measurement.d_value*other_measurement.d_value +\n\t       other_measurement.d_uncertainty*other_measurement.d_uncertainty*\n\t       d_value*d_value );\n\n  d_value *= other_measurement.d_value;\n\n  return *this;\n}\n\n// In-place division operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator/=( const ValueType& value )\n{\n  // Make sure the value is valid\n  testPrecondition( !Utility::isnaninf( value ) );\n  testPrecondition( value != 0.0 );\n\n  d_value /= value;\n\n  d_uncertainty /= fabs( value );\n\n  return *this;\n}\n\n// In-place division operator\ntemplate<typename T>\ninline Measurement<T>& Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type>::operator/=( const Measurement<T>& other_measurement )\n{\n  // Make sure the other measurement is valid\n  testPrecondition( !Utility::isnaninf( other_measurement.d_value ) );\n  testPrecondition( !Utility::isnaninf( other_measurement.d_uncertainty ) );\n  testPrecondition( other_measurement.d_value != 0.0 );\n  testPrecondition( other_measurement.d_uncertainty >= 0.0 );\n\n  double other_value_sqr = other_measurement.d_value*other_measurement.d_value;\n\n  double term_1 = d_uncertainty*d_uncertainty/other_value_sqr;\n\n  double term_2 =\n    other_measurement.d_uncertainty*other_measurement.d_uncertainty*\n    d_value*d_value/(other_value_sqr*other_value_sqr);\n\n\n  // Propagate the uncertainty of the measurements\n  d_uncertainty = std::sqrt( term_1 + term_2 );\n\n  d_value /= other_measurement.d_value;\n\n  return *this;\n}\n\nnamespace Details{\n\n//! Calculate the propagated uncertainty of a measurement to a real power\ntemplate<typename T1, typename T2>\ninline T1 calculatePropagatedUncertaintyFromRealPowerOp(\n                                                const T1 value,\n                                                const T1 value_to_exponent,\n                                                const T1 uncertainty,\n                                                const T2 exponent )\n{ return std::fabs(exponent*value_to_exponent*(uncertainty/value)); }\n\n//! The pow method implementation\ntemplate<typename T, typename ExponentType, typename BasePowMethod>\ninline Utility::Measurement<T> powImpl( const Utility::Measurement<T>& x,\n                                       const ExponentType exponent,\n                                       BasePowMethod basePow )\n{\n  if( x.getValue() != Utility::QuantityTraits<T>::zero() )\n  {\n    const T new_value = basePow( x.getValue() );\n\n    const T propagated_uncertainty =\n      Utility::Details::calculatePropagatedUncertaintyFromRealPowerOp(\n                                                            x.getValue(),\n                                                            new_value,\n                                                            x.getUncertainty(),\n                                                            exponent );\n    \n    return Utility::Measurement<T>( new_value, propagated_uncertainty );\n  }\n  else if( x.getValue() == Utility::QuantityTraits<T>::zero() &&\n           x.getUncertainty() > Utility::QuantityTraits<T>::zero() )\n  {\n    return Utility::Measurement<T>( Utility::QuantityTraits<T>::zero(),\n                                    Utility::QuantityTraits<T>::inf() );\n  }\n  // quantity.getValue() == 0, quantity.getUncertainty() == 0\n  else\n  {\n    return Utility::Measurement<T>( Utility::QuantityTraits<T>::zero(), Utility::QuantityTraits<T>::zero() );\n  }\n}\n  \n} // end Details namespace\n\n} // end Utility namespace\n\nnamespace std{\n\n// Overload of sqrt for a measurement\ntemplate<typename T>\ninline Utility::Measurement<T> sqrt( const Utility::Measurement<T>& x )\n{\n  if( x.getValue() > Utility::QuantityTraits<T>::zero() )\n  {\n    const T new_value = std::sqrt( x.getValue() );\n\n    const T propagated_uncertainty =\n      Utility::Details::calculatePropagatedUncertaintyFromRealPowerOp(\n                                                            x.getValue(),\n                                                            new_value,\n                                                            x.getUncertainty(),\n                                                            0.5 );\n    return Utility::Measurement<T>( new_value, propagated_uncertainty );\n  }\n  else if( x.getValue() == Utility::QuantityTraits<T>::zero() &&\n           x.getUncertainty() > Utility::QuantityTraits<T>::zero() )\n  {\n    return Utility::Measurement<T>( Utility::QuantityTraits<T>::zero(),\n                                    Utility::QuantityTraits<T>::inf() );\n  }\n  else if( x.getValue() == Utility::QuantityTraits<T>::zero() &&\n           x.getUncertainty() == Utility::QuantityTraits<T>::zero() )\n  {\n    return Utility::Measurement<T>( Utility::QuantityTraits<T>::zero(), Utility::QuantityTraits<T>::zero() );\n  }\n  else\n  {\n    return Utility::Measurement<T>( Utility::QuantityTraits<T>::nan(), Utility::QuantityTraits<T>::nan() );\n  }\n}\n\n// Overload of cbrt for a measurement\ntemplate<typename T>\ninline Utility::Measurement<T> cbrt( const Utility::Measurement<T>& x )\n{\n  if( x.getValue() != Utility::QuantityTraits<T>::zero() )\n  {\n    const T new_value = std::cbrt( x.getValue() );\n\n    const T propagated_uncertainty =\n      Utility::Details::calculatePropagatedUncertaintyFromRealPowerOp(\n                                                            x.getValue(),\n                                                            new_value,\n                                                            x.getUncertainty(),\n                                                            1.0/3 );\n    return Utility::Measurement<T>( new_value, propagated_uncertainty );\n  }\n  else if( x.getValue() == Utility::QuantityTraits<T>::zero() &&\n           x.getUncertainty() > Utility::QuantityTraits<T>::zero() )\n  {\n    return Utility::Measurement<T>( Utility::QuantityTraits<T>::zero(),\n                                    Utility::QuantityTraits<T>::inf() );\n  }\n  // quantity.getValue() == 0, quantity.getUncertainty() == 0\n  else\n  {\n    return Utility::Measurement<T>( Utility::QuantityTraits<T>::zero(), Utility::QuantityTraits<T>::zero() );\n  }\n}\n\n// Overload of pow for a measurement\ntemplate<typename T, typename ExponentType>\ninline Utility::Measurement<T> pow( const Utility::Measurement<T>& x,\n                                    const ExponentType exponent )\n{\n  return Utility::Details::powImpl( x, exponent, std::bind<T>( static_cast<T (*)(T,T)>(&std::pow<T>), std::placeholders::_1, static_cast<T>(exponent) ) );\n}\n\n} // end std namespace\n\nnamespace Utility{\n\n// Partial specialization of Utility::QuantityTraits for Utility::Measurement\ntemplate<typename T>\nstruct QuantityTraits<Measurement<T>,typename std::enable_if<std::is_floating_point<T>::value>::type>\n{\nprivate:\n\n  // The quantity traits for the raw type\n  typedef QuantityTraits<T> RawQuantityTraits;\n\n  // These quantity traits\n  typedef QuantityTraits<Measurement<T>,typename std::enable_if<std::is_floating_point<T>::value>::type> ThisType;\n\npublic:\n  \n  //! The unit type\n  typedef void UnitType;\n\n  //! The raw quantity type\n  typedef Measurement<T> RawType;\n\n  //! The raw floating-point quantity type\n  typedef Measurement<T> RawFloatingPointType;\n\n  //! The real raw floating-point quantity type\n  typedef Measurement<T> RealRawFloatingPointType;\n\n  //! The quantity type\n  typedef Measurement<T> QuantityType;\n\n  //! The floating-point quantity type\n  typedef Measurement<T> FloatingPointQuantityType;\n\n  //! The real floating-point quantity type\n  typedef Measurement<T> RealFloatingPointQuantityType;\n\n  //! The quantity raised to power N/D type\n  template<boost::units::integer_type N, boost::units::integer_type D = 1>\n  struct GetQuantityToPowerType\n  {\n    typedef QuantityType type;\n    typedef FloatingPointQuantityType AsFloatingPointType;\n  };\n\n  //! Used to check if the traits class for quantity type is specialized\n  typedef typename RawQuantityTraits::is_specialized is_specialized;\n\n  //! Used to check if the quantity is signed\n  typedef typename RawQuantityTraits::is_signed is_signed;\n\n  //! Used to check if the quantity is an integer type\n  typedef typename RawQuantityTraits::is_integer is_integer;\n\n  //! Used to check if the quantity is complex\n  typedef typename RawQuantityTraits::is_complex is_complex;\n\n  //! Used to check if the quantity uses exact representations\n  typedef typename RawQuantityTraits::is_exact is_exact;\n\n  //! Used to check if a quantity adheres to IEC-559/IEEE-754 standard\n  typedef typename RawQuantityTraits::is_iec559 is_iec559;\n\n  //! Used to check if the set of values represented by the quantity is finite\n  typedef typename RawQuantityTraits::is_bounded is_bounded;\n\n  //! Used to check if the quantity is modulo\n  typedef typename RawQuantityTraits::is_modulo is_modulo;\n\n  //! Used to check if the quantity has a representation for positive infinity\n  typedef typename RawQuantityTraits::has_infinity has_infinity;\n\n  //! Used to check if the quantity has a representation for quiet nan\n  typedef typename RawQuantityTraits::has_quiet_nan has_quiet_nan;\n\n  //! Used to check if the quantity has a representation for signaling nan\n  typedef typename RawQuantityTraits::has_signaling_nan has_signaling_nan;\n\n  //! Used to check if the quantity allows denormalized values\n  typedef typename RawQuantityTraits::has_denorm has_denorm;\n\n  //! Used to check if a loss of accuracy is detected as a denormalization loss instead of an inexact result\n  typedef typename RawQuantityTraits::has_denorm_loss has_denorm_loss;\n\n  //! Used to check if trapping is implemented for the quantity\n  typedef typename RawQuantityTraits::traps traps;\n\n  //! Used to check if tinyness is implemented before rounding\n  typedef typename RawQuantityTraits::tinyness_before tinyness_before;\n\n  //! Used to check the rounding style of floating-point quantities \n  typedef typename RawQuantityTraits::round_style round_style;\n\n    //! The number of non-sign bits\n  typedef typename RawQuantityTraits::digits digits;\n\n  //! The number of digits (in decimal base) that can be represented\n  typedef typename RawQuantityTraits::digits10 digits10;\n\n  //! The number of digits (in decimal base) required to ensure that values that differ are always differentiated\n  typedef typename RawQuantityTraits::max_digits10 max_digits10;\n\n  //! Base of the representation\n  typedef typename RawQuantityTraits::radix radix;\n\n  //! Min negative integer value such that radix raised to (this-1) generates a normalized floating-point quantity \n  typedef typename RawQuantityTraits::min_exponent min_exponent;\n\n  //! Min negative integer value such that 10 raised to that power generates a normalized floating-point quantity \n  typedef typename RawQuantityTraits::min_exponent10 min_exponent10;\n\n  //! One more than the largest integer power of the radix that is a valid finite floating-point value\n  typedef typename RawQuantityTraits::max_exponent max_exponent;\n\n  //! Max integer power of 10 that is a valid finite floating-point value\n  typedef typename RawQuantityTraits::max_exponent10 max_exponent10;\n\n  //! Get the zero quantity\n  static inline QuantityType zero() noexcept\n  { return QuantityType(RawQuantityTraits::zero(), RawQuantityTraits::zero()); }\n\n  //! Get the one quantity\n  static inline QuantityType one() noexcept\n  { return QuantityType(RawQuantityTraits::one(), RawQuantityTraits::zero()); }\n\n  //! Get the min quantity\n  static inline QuantityType min() noexcept\n  { return QuantityType(RawQuantityTraits::min(), RawQuantityTraits::zero()); }\n\n  //! Get the min positive denormalized value\n  static inline QuantityType denormMin() noexcept\n  { return QuantityType(RawQuantityTraits::denormMin(), RawQuantityTraits::zero()); }\n\n  //! Get the max quantity\n  static inline QuantityType max() noexcept\n  { return QuantityType(RawQuantityTraits::max(), RawQuantityTraits::zero()); }\n\n  //! Get the lowest quantity\n  static inline QuantityType lowest() noexcept\n  { return QuantityType(RawQuantityTraits::lowest(), RawQuantityTraits::zero()); }\n\n  //! Get the machine epsilon (only defined for floating-point types)\n  static inline QuantityType epsilon() noexcept\n  { return QuantityType(RawQuantityTraits::epsilon(), RawQuantityTraits::zero()); }\n\n  //! Get the maximum rounding error (only defined for floating-point types)\n  static inline QuantityType roundError() noexcept\n  { return QuantityType(RawQuantityTraits::roundError(), RawQuantityTraits::zero()); }\n\n  //! Get the inf quantity (only defined for floating-point types)\n  static inline QuantityType inf() noexcept\n  { return QuantityType(RawQuantityTraits::inf(), RawQuantityTraits::zero()); }\n\n  //! Get the quiet nan quantity (only defined for floating-point types)\n  static inline QuantityType nan() noexcept\n  { return QuantityType(RawQuantityTraits::nan(), RawQuantityTraits::zero()); }\n\n  //! Get the signaling nan quantity (only defined for floating-point types)\n  static inline QuantityType signalingNan() noexcept\n  { return QuantityType(RawQuantityTraits::signalingNan(), RawQuantityTraits::zero()); }\n\n  //! Get the absolute value of a quantity\n  static inline RealFloatingPointQuantityType abs( const QuantityType& a )\n  { return RealFloatingPointQuantityType(RawQuantityTraits::abs(a.getValue()), a.getUncertainty()); }\n\n  //! Get the conjugate of a quantity\n  static inline FloatingPointQuantityType conj( const QuantityType& a )\n  { return a; }\n\n  //! Get the real part of the quantity\n  static inline RealFloatingPointQuantityType real( const QuantityType& a )\n  { return a; }\n\n  //! Get the imaginary part of the quantity\n  static inline RealFloatingPointQuantityType imag( const QuantityType& a )\n  { return RealFloatingPointQuantityType(RawQuantityTraits::zero(),RawQuantityTraits::zero()); }\n\n  //! Test if the quantity is a nan or inf \n  static inline bool isnaninf( const QuantityType& a )\n  {\n    if( RawQuantityTraits::isnaninf( a.getValue() ) ||\n        RawQuantityTraits::isnaninf( a.getUncertainty() ) )\n      return true;\n\n    return false;\n  }\n\n  //! Take the square root of a quantity (only one root will be calculated)\n  static inline typename GetQuantityToPowerType<1,2>::AsFloatingPointType sqrt( const QuantityType& quantity )\n  { return std::sqrt( quantity ); }\n\n  //! Take the cube root of a quantity (only one root will be calculated)\n  static inline typename GetQuantityToPowerType<1,3>::AsFloatingPointType cbrt( const QuantityType& quantity )\n  { return std::cbrt( quantity ); }\n\n  //! Take a quantity to the desired rational power\n  template<boost::units::integer_type N, boost::units::integer_type D>\n  static typename GetQuantityToPowerType<N,D>::AsFloatingPointType rpow( const QuantityType& quantity )\n  {\n    return Details::powImpl( quantity, static_cast<double>(N)/D, &RawQuantityTraits::template rpow<N,D> );\n  }\n\n  //! Initialize a quantity (potentially dangerous!)\n  static inline QuantityType initializeQuantity( const RawType& raw_quantity ) noexcept\n  { return raw_quantity; }\n\n  //! Get the raw value of a quantity\n  static inline const RawType& getRawQuantity( const QuantityType& quantity ) noexcept\n  { return quantity; }\n\n  //! Set the value of a quantity (potentially dangerous!)\n  static inline void setQuantity( QuantityType& quantity,\n\t\t\t\t  const RawType& raw_quantity ) noexcept\n  { quantity = raw_quantity; }\n};\n\n// Partial specialization of Utility::QuantityTraits for\n// boost::units::quantity<Unit,Utility::Measurement> types\ntemplate<typename Unit, typename T>\nstruct QuantityTraits<boost::units::quantity<Unit,Measurement<T> >,typename std::enable_if<std::is_floating_point<T>::value>::type>\n{\n  // The quantity traits for the raw type\n  typedef QuantityTraits<Measurement<T> > RawQuantityTraits;\n\n  // These quantity traits\n  typedef QuantityTraits<boost::units::quantity<Unit,Measurement<T> >,typename std::enable_if<std::is_floating_point<T>::value>::type> ThisType;\n\npublic:\n  \n  //! The unit type\n  typedef Unit UnitType;\n\n  //! The raw quantity type\n  typedef Measurement<T> RawType;\n\n  //! The raw floating-point quantity type\n  typedef Measurement<T> RawFloatingPointType;\n\n  //! The real raw floating-point quantity type\n  typedef Measurement<T> RealRawFloatingPointType;\n\n  //! The quantity type\n  typedef boost::units::quantity<Unit,Measurement<T> > QuantityType;\n\n  //! The floating-point quantity type\n  typedef boost::units::quantity<Unit,Measurement<T> > FloatingPointQuantityType;\n\n  //! The real floating-point quantity type\n  typedef boost::units::quantity<Unit,Measurement<T> > RealFloatingPointQuantityType;\n\n  //! The quantity raised to power N/D type\n  template<boost::units::integer_type N, boost::units::integer_type D = 1>\n  struct GetQuantityToPowerType\n  {\n    typedef typename Details::QuantityToPowerTypeHelper<N,D,QuantityType>::QuantityToRpowType type;\n    typedef typename Details::QuantityToPowerTypeHelper<N,D,FloatingPointQuantityType>::QuantityToRpowType AsFloatingPointType;\n  };\n\n  //! Used to check if the traits class for quantity type is specialized\n  typedef typename RawQuantityTraits::is_specialized is_specialized;\n\n  //! Used to check if the quantity is signed\n  typedef typename RawQuantityTraits::is_signed is_signed;\n\n  //! Used to check if the quantity is an integer type\n  typedef typename RawQuantityTraits::is_integer is_integer;\n\n  //! Used to check if the quantity is complex\n  typedef typename RawQuantityTraits::is_complex is_complex;\n\n  //! Used to check if the quantity uses exact representations\n  typedef typename RawQuantityTraits::is_exact is_exact;\n\n  //! Used to check if a quantity adheres to IEC-559/IEEE-754 standard\n  typedef typename RawQuantityTraits::is_iec559 is_iec559;\n\n  //! Used to check if the set of values represented by the quantity is finite\n  typedef typename RawQuantityTraits::is_bounded is_bounded;\n\n  //! Used to check if the quantity is modulo\n  typedef typename RawQuantityTraits::is_modulo is_modulo;\n\n  //! Used to check if the quantity has a representation for positive infinity\n  typedef typename RawQuantityTraits::has_infinity has_infinity;\n\n  //! Used to check if the quantity has a representation for quiet nan\n  typedef typename RawQuantityTraits::has_quiet_nan has_quiet_nan;\n\n  //! Used to check if the quantity has a representation for signaling nan\n  typedef typename RawQuantityTraits::has_signaling_nan has_signaling_nan;\n\n  //! Used to check if the quantity allows denormalized values\n  typedef typename RawQuantityTraits::has_denorm has_denorm;\n\n  //! Used to check if a loss of accuracy is detected as a denormalization loss instead of an inexact result\n  typedef typename RawQuantityTraits::has_denorm_loss has_denorm_loss;\n\n  //! Used to check if trapping is implemented for the quantity\n  typedef typename RawQuantityTraits::traps traps;\n\n  //! Used to check if tinyness is implemented before rounding\n  typedef typename RawQuantityTraits::tinyness_before tinyness_before;\n\n  //! Used to check the rounding style of floating-point quantities \n  typedef typename RawQuantityTraits::round_style round_style;\n\n    //! The number of non-sign bits\n  typedef typename RawQuantityTraits::digits digits;\n\n  //! The number of digits (in decimal base) that can be represented\n  typedef typename RawQuantityTraits::digits10 digits10;\n\n  //! The number of digits (in decimal base) required to ensure that values that differ are always differentiated\n  typedef typename RawQuantityTraits::max_digits10 max_digits10;\n\n  //! Base of the representation\n  typedef typename RawQuantityTraits::radix radix;\n\n  //! Min negative integer value such that radix raised to (this-1) generates a normalized floating-point quantity \n  typedef typename RawQuantityTraits::min_exponent min_exponent;\n\n  //! Min negative integer value such that 10 raised to that power generates a normalized floating-point quantity \n  typedef typename RawQuantityTraits::min_exponent10 min_exponent10;\n\n  //! One more than the largest integer power of the radix that is a valid finite floating-point value\n  typedef typename RawQuantityTraits::max_exponent max_exponent;\n\n  //! Max integer power of 10 that is a valid finite floating-point value\n  typedef typename RawQuantityTraits::max_exponent10 max_exponent10;\n\n  //! Get the zero quantity\n  static inline QuantityType zero() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::zero() ); }\n\n  //! Get the one quantity\n  static inline QuantityType one() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::one() ); }\n\n  //! Get the min quantity\n  static inline QuantityType min() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::min() ); }\n\n  //! Get the min positive denormalized value\n  static inline QuantityType denormMin() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::denormMin() ); }\n\n  //! Get the max quantity\n  static inline QuantityType max() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::max() ); }\n\n  //! Get the lowest quantity\n  static inline QuantityType lowest() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::lowest() ); }\n\n  //! Get the machine epsilon (only defined for floating-point types)\n  static inline QuantityType epsilon() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::epsilon() ); }\n\n  //! Get the maximum rounding error (only defined for floating-point types)\n  static inline QuantityType roundError() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::roundError() ); }\n\n  //! Get the inf quantity (only defined for floating-point types)\n  static inline QuantityType inf() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::inf() ); }\n\n  //! Get the quiet nan quantity (only defined for floating-point types)\n  static inline QuantityType nan() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::nan() ); }\n\n  //! Get the signaling nan quantity (only defined for floating-point types)\n  static inline QuantityType signalingNan() noexcept\n  { return QuantityType::from_value( RawQuantityTraits::signalingNan() ); }\n\n  //! Get the absolute value of a quantity\n  static inline RealFloatingPointQuantityType abs( const QuantityType& a )\n  { return RealFloatingPointQuantityType::from_value( RawQuantityTraits::abs(a.value()) ); }\n\n  //! Get the conjugate of a quantity\n  static inline FloatingPointQuantityType conj( const QuantityType& a )\n  { return FloatingPointQuantityType::from_value( RawQuantityTraits::conj(a.value()) ); }\n\n  //! Get the real part of the quantity\n  static inline RealFloatingPointQuantityType real( const QuantityType& a )\n  { return RealFloatingPointQuantityType::from_value( RawQuantityTraits::real(a.value()) ); }\n\n  //! Get the imaginary part of the quantity\n  static inline RealFloatingPointQuantityType imag( const QuantityType& a )\n  { return RealFloatingPointQuantityType::from_value( RawQuantityTraits::imag(a.value()) ); }\n\n  //! Test if the quantity is a nan or inf \n  static inline bool isnaninf( const QuantityType& a )\n  { return RawQuantityTraits::isnaninf(a.value()); }\n\n  //! Take the square root of a quantity (only one root will be calculated)\n  static inline typename GetQuantityToPowerType<1,2>::AsFloatingPointType sqrt( const QuantityType& quantity )\n  { return GetQuantityToPowerType<1,2>::AsFloatingPointType::from_value( RawQuantityTraits::sqrt( quantity.value() ) ); }\n\n  //! Take the cube root of a quantity (only one root will be calculated)\n  static inline typename GetQuantityToPowerType<1,3>::AsFloatingPointType cbrt( const QuantityType& quantity )\n  { return GetQuantityToPowerType<1,3>::AsFloatingPointType::from_value( RawQuantityTraits::cbrt( quantity.value() ) ); }\n\n  //! Take a quantity to the desired rational power\n  template<boost::units::integer_type N, boost::units::integer_type D>\n  static typename GetQuantityToPowerType<N,D>::AsFloatingPointType rpow( const QuantityType& quantity )\n  { return GetQuantityToPowerType<N,D>::AsFloatingPointType::from_value( RawQuantityTraits::template rpow<N,D>( quantity.value() ) ); }\n\n  //! Initialize a quantity (potentially dangerous!)\n  static inline QuantityType initializeQuantity( const RawType& raw_quantity ) noexcept\n  { return QuantityType::from_value( raw_quantity ); }\n\n  //! Get the raw value of a quantity\n  static inline const RawType& getRawQuantity( const QuantityType& quantity ) noexcept\n  { return quantity.value(); }\n\n  //! Set the value of a quantity (potentially dangerous!)\n  static inline void setQuantity( QuantityType& quantity,\n\t\t\t\t  const RawType& raw_quantity ) noexcept\n  { quantity = QuantityType::from_value( raw_quantity ); }\n};\n\n} // end Utility namespace\n\n#endif // end UTILITY_MEASUREMENT_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_Measurement_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "448ef85a30dedd4859f736bc13ff19ce86740ead", "size": 30962, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/stats/src/Utility_Measurement_def.hpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/utility/stats/src/Utility_Measurement_def.hpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/utility/stats/src/Utility_Measurement_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": 39.6948717949, "max_line_length": 156, "alphanum_fraction": 0.7150054906, "num_tokens": 6770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.03358950806865571, "lm_q1q2_score": 0.01574644653557238}}
{"text": "/*!\n  \\author      Robert I A Patterson\n  \\author      Sashikumaar Ganesan\n\n  Copyright (C) 2011 Robert I A Patterson & Sashikumaar Ganesan\n\n  \\file moonmd_interface.cpp\n  \\brief Interface between continuum flow solver and stochastic particle\n         population balance solver\n\n  Licence:\n\n    This file is free software; you can redistribute it and/or\n    modify it under the terms of the GNU General Public License\n    as published by the Free Software Foundation; either version 2\n    of the License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr. Robert Patterson\n    Weierstrass Institute\n    Mohrenstrasse 39\n    10117 Berlin\n    Germany\n    riap@cantab.net\n*/\n\n#include \"moonmd_interface.h\"\n\n#include \"geometry1d.h\"\n#include \"settings_io.h\"\n#include \"reactor1d.h\"\n#include \"reset_chemistry.h\"\n#include \"pred_corr_solver.h\"\n#include \"simulator.h\"\n\n#include \"mops_settings_io.h\"\n#include \"mops_mechanism.h\"\n\n#include \"swp_model_stats.h\"\n#include \"swp_mech_parser.h\"\n\n#include \"linear_interpolator.hpp\"\n\n#include <boost/filesystem/operations.hpp>\n\n#include <memory>\n#include <iostream>\n#include <stdexcept>\n#include <limits>\n\n/*!\n * Function private to this file\n *\n * Work out how long a particle should take to travel through each cell and return the shortest residence\n * time.  A mid point velocity integration is currently used.  This function is useful in determining the number of\n * time splitting steps which the solver must make between particle processes such as coagulation and inception\n * and particle transport.\n *\n *\\param[in]         geom                Geometry defining the cells\n *\\param[in]         solution_length     Communication is by vectors which must all be at least this long\n *\\param[in]         solution_nodes      Distances from start of reactor (in m) at which velocity values are specified\n *\\param[in]         velocity            Flow velocity in \\f$\\mathrm{ms}^{-1}\\f$\n */\ndouble minimumResidenceTime(const Geometry::Geometry1d& geom, const size_t solution_length,\n                                 const double solution_nodes[], const double velocity[])\n{\n    const Utils::LinearInterpolator<double, double> velocityProfile(std::vector<double>(solution_nodes, solution_nodes + solution_length),\n                                                                    std::vector<double>(velocity,       velocity + solution_length ));\n\n    double minTime = std::numeric_limits<double>::max();\n    for(size_t i = 0; i < geom.numCells(); ++i) {\n        // In the 1d case cellVolume == length of cell\n        double residenceTime = std::abs(geom.cellVolume(i) / velocityProfile.interpolate(geom.cellCentre(i)));\n        minTime = residenceTime < minTime ? residenceTime : minTime;\n    }\n    return minTime;\n}\n\n/*!\n *\\param[in]    chemfile     Path to file listing chemical species to consider\n *\\param[in]    thermfile    Path to thermodynamic data file\n *\\param[in]    settfile     Path to file specifying control parameters for Brush\n *\\param[in]    swpfile      Path to XML file specifying the particle mechanism\n *\\param[in]    partsolnfile Path to XML file specifying the initial particle population\n *\\param[in]    chemsolnfile Path to file specifying the initial continuum phase composition\n *\\param[in]    num_grid_nodes   Number of cell boundaries specified in grid_nodes\n *\\param[in]    grid_nodes   Boundaries of cells to be used in Brush specified in meters.\n *\n *\\pre [grid_nodes, grid_nodes + num_grid_nodes) must be a valid range\n *\n *\\return    Pointer to new brush reactor object.   Client must call delete on this pointer.\n */\nBrush::MooNMDInterface::particle_reactor_pointer \n Brush::MooNMDInterface::InitialiseBrush(\n    const std::string& chemfile, const std::string& thermfile, const std::string& settfile,\n    const std::string& swpfile, const std::string& partsolnfile, const std::string& chemsolnfile,\n    const size_t num_grid_nodes, const double grid_nodes[])\n{\n    std::cout << \"Setting up Brush\\n\";\n\n    // Look at working directory (to help debug tests)\n    std::cout << \"Working directory is \" << boost::filesystem::current_path() << std::endl;\n\n    // diagnostic level (could be a user input)\n   const int diag = 1;\n\n    // Geometry\n    std::auto_ptr<Geometry::Geometry1d> pGeom;\n    // Build the geometry object and hold a smart pointer to it\n    pGeom.reset(new Geometry::Geometry1d(std::vector<double>(grid_nodes, grid_nodes + num_grid_nodes),\n                                          Geometry::dirichlet, Geometry::neumann));\n\n    // Variables to hold data read from the input file\n    Mops::timevector timeIntervals;\n    std::string outputFileBaseName;\n    std::vector<std::pair<double, double> > maxPCounts, maxM0s;\n    Sweep::Stats::IModelStats::StatBound statBound;\n\n    {\n        // Load the XML\n        CamXML::Document settingsXML;\n        settingsXML.Load(settfile);\n        const CamXML::Element * const root = settingsXML.Root();\n\n        // Time intervals for stepping through the solution process with output\n        const CamXML::Element * node = root->GetFirstChild(\"timeintervals\");\n        if (node != NULL) {\n            Mops::Settings_IO::readTimeIntervals(*node, timeIntervals);\n        } else {\n            throw std::runtime_error(\"No time intervals found\");\n        }\n\n        // Maximum number of computational particles per cell\n        maxPCounts = Brush::Settings_IO::readProfile(root, \"pcount\");\n\n        // Maximum particle concentration\n        maxM0s = Brush::Settings_IO::readProfile(root, \"maxm0\");\n\n        // Output details\n        node = root->GetFirstChild(\"output\");\n        if(node != NULL) {\n            const CamXML::Element * const filenameNode = node->GetFirstChild(\"filename\");\n            if(filenameNode != NULL) {\n                outputFileBaseName = filenameNode->Data();\n            }\n            else {\n                throw std::runtime_error(\"A <filename> element must be supplied in the output section\");\n            }\n\n            // See if the stats bounds were specified in the input file\n            const CamXML::Element * const statsBoundNode = node->GetFirstChild(\"statsbound\");\n            if(statsBoundNode != NULL) {\n                // Read the data from the file\n                Sweep::PropID statsboundPropertyID;\n                double statsLowerBound;\n                double statsUpperBound;\n                Mops::Settings_IO::ReadStatsBound(*statsBoundNode, statsboundPropertyID, statsLowerBound, statsUpperBound);\n\n                // Adjust statBound with the newly read data\n                statBound.PID = statsboundPropertyID;\n                statBound.Lower = statsLowerBound;\n                statBound.Upper = statsUpperBound;\n            }\n            // If no statsbound was specified in the input file, the default constructed value of\n            // statBound will be used.\n        }\n        else {\n            throw std::runtime_error(\"A <output> element must be supplied with details for the required output\");\n        }\n\n    }\n\n    //========= Load chemical mechanism ==========================\n    // For fixed chemistry simulations the mech does not have to\n    // contain reactions, only the species names are required.\n    Mops::Mechanism mech;\n    {\n        if(diag > 0) {\n            std::cout << \"Reading chemical mechanism...\\n\";\n        }\n\n        Sprog::IO::MechanismParser::ReadChemkin(chemfile, mech.GasMech(), thermfile, diag);\n\n        if (diag>0)\n            mech.GasMech().WriteDiagnostics(\"ckmech.diag\");\n    }\n\n    //========= Load particle mechanism ==========================\n    {\n        if(diag > 0) {\n            std::cout << \"Setting species on particle mechanism...\\n\";\n        }\n        mech.ParticleMech().SetSpecies(mech.GasMech().Species());\n        if(diag > 0) {\n            std::cout << \"Species on particle mechanism are at \" << mech.ParticleMech().Species() << '\\n';\n            std::cout << \"Reading particle mechanism...\\n\";\n        }\n        Sweep::MechParser::Read(swpfile, mech.ParticleMech());\n        if(diag > 0) {\n            std::cout << \"Read particle mechanism with \" << mech.ParticleMech().ProcessCount()\n                      << \" processes\\n\";\n            if(diag > 1) {\n                // Get names of the processes\n                std::vector<std::string> procNames;\n                mech.ParticleMech().GetProcessNames(procNames);\n            \t\n                // Print the process names out one line at a time\n                std::vector<std::string>::const_iterator it = procNames.begin();\n                const std::vector<std::string>::const_iterator itEnd = procNames.end();\n                while(it != itEnd) {\n                    std::cout << ' ' << *it++ << '\\n';\n                }\n            }\n        }\n    }\n\n    //======== Read the initial state of the continuum phase ================\n    if(diag > 0) {\n        std::cout << \"Reading initial continuum solution...\\n\";\n    }\n    Brush::ResetChemistry initChem(chemsolnfile, Brush::ResetChemistry::Camflow, mech.GasMech(), diag);\n    if(diag > 0) {\n        std::cout << \"Read initial continuum solution\\n\";\n    }\n\n    //========= Read initial guess for particle solution ==================\n    std::list<ParticlePopulationPoint1d> initialPopulationPoints;\n    {\n        if(diag > 0) {\n            std::cout << \"Reading initial particle population...\\n\";\n        }\n\n        // Load the XML\n        CamXML::Document initialParticlesXML;\n        initialParticlesXML.Load(partsolnfile);\n        const CamXML::Element * const root = initialParticlesXML.Root();\n\n        // Now get the XML for each separate population\n        typedef std::vector<CamXML::Element*> xml_element_list;\n        xml_element_list populations;\n        root->GetChildren(\"population\", populations);\n\n        // Read the position and details of each population\n        for(xml_element_list::const_iterator it = populations.begin();\n            it != populations.end(); ++it) {\n\n            ParticlePopulationPoint1d populationDetails;\n\n            // Get the position\n            const CamXML::Attribute *attr = (*it)->GetAttribute(\"x\");\n            if(attr) {\n                populationDetails.position = atof(attr->GetValue().c_str());\n            }\n            else {\n                throw std::runtime_error(\"No x (position) attribute for a <population> element.\");\n            }\n\n            // Get the number density of the particles\n            const CamXML::Element * const m0XML = (*it)->GetFirstChild(\"m0\");\n            if(m0XML) {\n                populationDetails.m0 = atof(m0XML->Data().c_str());\n            }\n            else {\n                throw std::runtime_error(\"No <m0> (number density) child element for a <population> element.\");\n            }\n\n            // Read in the population\n            populationDetails.particleList =\n                    Mops::Settings_IO::ReadInitialParticles(**it, mech.ParticleMech());\n\n            initialPopulationPoints.push_back(populationDetails);\n        }\n    }\n\n    //========= Build the initial reactor ========================\n    Reactor1d *pReactor = new Reactor1d(*pGeom, mech.GasMech(), false, mech.ParticleMech(), maxPCounts, maxM0s);\n\n    std::cout << \"Setting the initial continuum solution\\n\";\n    pReactor->ReplaceChemistry(initChem, true);\n\n    // Put the initial particles into the reactor\n    pReactor->ReplaceParticles(initialPopulationPoints.begin(), initialPopulationPoints.end());\n\n    return pReactor;\n}\n\n/*!\n * Simulate the particle processes from the current reactor time until t_stop\n * and calculate mean energy and mass source terms.\n *\n *\\param[in,out]     reac                The reactor specifying the initial condition and particle dynamics\n *\\param[in]         t_stop              Time upto which to simulate\n *\\param[in]         solution_length     Communication is by vectors which must all be at least this long\n *\\param[in]         num_species         Number of species for which mass concentrations are supplied\n *\\param[in]         solution_nodes      Distances from start of reactor (in m) at which solution values are specified\n *\\param[in]         temperature         Reactor temperature in K\n *\\param[in]         velocity            Flow velocity in \\f$\\mathrm{ms}^{-1}\\f$\n *\\param[in]         mass_concs          Concentrations of species in \\f$\\mathrm{kg m}^{-3}\\f$\n *\\param[in]         path_id             Integer identifying the path so that different sequences of random numbers can be used for each path\n *\\param[out]        energy_source       Energy release by particle processes in \\f$\\mathrm{J m}^{-3} \\mathrm{s}^{-1}\\f$\n *\\param[out]        mass_conc_sources   Release of species into solution by particle processes in \\f$\\mathrm{kg m}^{-3}\\mathrm{s}^{-1}\\f$\n *\\param[in,out]     moment_output       Stream to which textual moment data can be written during calculation.\n *\n *\\pre  All the 1d arrays supplied by the caller must have length at least solution_length, this includes\n *       the output arrays.\n *\n *\\pre  The arrays mass_concs and mass_conc_sources are effectively 2d arrays and must have length at least \n *       solution_length * num_species\n *\n *\\return    Pointer to updated brush reactor object.\n *\n * Sign convention for source terms: Positive source terms indicate release of energy or material by the solid\n * phase.  Thus a positive energy source would indicate exothermic crystallisation and a positive mass source\n * would indicate that crystals were dissolving.\n *\n * The data in mass_concs shall be ordered such that data for species i begins at mass_concs + i * num_species,\n * that is the fastest varying index shall be the index for spatial position.  This is fairly easy to change,\n * but it is important to keep all comments and code consistent!  The data in mass_conc_sources shall be ordered\n * in the same way as that in mass_concs.\n */\nBrush::MooNMDInterface::particle_reactor_pointer Brush::MooNMDInterface::RunParticlePhase(\n    particle_reactor& reac, const double t_stop,\n    const size_t solution_length,\n    const size_t num_species,\n    const double solution_nodes[],\n    const double temperature[],\n    const double velocity[],\n    const double mass_concs[],\n    const size_t path_id,\n    double energy_source[],\n    double mass_conc_sources[],\n    std::ostream &moment_output)\n{\n    //========= Set the chemistry on the reactors ==========\n    // First put the data in vectors, because this is what the interface to ResetChemistry expects\n    const fvector solutionNodes(solution_nodes, solution_nodes + solution_length);\n    const fvector temperatureVector(temperature, temperature + solution_length);\n    const fvector velocityVector(velocity, velocity + solution_length);\n\n    // Work out the total density in kg m^-3\n    fvector density(solution_length, 0.0);\n    // Loop over the spatial positions\n    for (unsigned i = 0u; i < solution_length; ++i) {\n        // Add up the contribution of all the species at current position\n        for (unsigned j = 0u; j < num_species; ++j) {\n            density[i] += mass_concs[i + j * solution_length];\n        }\n    }\n\n    // Now calculate mass fractions (because this is what the ResetChemistry constructor requires)\n    std::vector<fvector> massFracs(num_species, fvector(solution_length));\n    // Loop over the species\n    for (unsigned i = 0u; i < num_species; ++i) {\n        // Scale by the total mass density at each point\n        for (unsigned j = 0u; j < solution_length; ++j) {\n            massFracs[i][j] = mass_concs[j + i * solution_length] / density[j];\n        }\n    }\n\n    // Dummy vector to fill unused argument positions\n    const fvector vec(solution_length);\n\n    ResetChemistry chemInterpolator(solutionNodes, temperatureVector, density, velocityVector,\n                                    vec, vec, vec, vec, vec, massFracs);\n\n    // Put the chemistry into the reactor\n    reac.ReplaceChemistry(chemInterpolator, true);\n\n    //======== Simulate to update the particle population =======\n    Brush::PredCorrSolver solver(chemInterpolator, 0, 0.0, 0.0, false, 0.0, true, true, false);\n\n    // Need to make sure that transport is simulated on intervals that do not\n    // always take particles over cell boundaries.\n    double minResidence = minimumResidenceTime(reac.getGeometry(), solution_length, solution_nodes, velocity);\n    unsigned numSplittings = std::ceil(10 * t_stop / minResidence);\n    std::cout << \"Num splittings \" << numSplittings << \", min residence \" << minResidence << std::endl;\n    solver.solve(reac, 0.0, t_stop, numSplittings, path_id);\n    Brush::Simulator::saveParticleStats(reac, t_stop, Sweep::Stats::IModelStats::StatBound(), moment_output);\n\n    //======== Estimate the source terms to return to the client =====\n\n    return &reac;\n}\n\n", "meta": {"hexsha": "6c37f955826dc6e26420cee93ddc89a2fbc335cf", "size": 17198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/brush/source/moonmd_interface.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/brush/source/moonmd_interface.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/brush/source/moonmd_interface.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 43.6497461929, "max_line_length": 141, "alphanum_fraction": 0.647284568, "num_tokens": 3827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.033589502264131835, "lm_q1q2_score": 0.015746443814465997}}
{"text": "//\n// Created by miguelyermo on 23/7/20.\n//\n\n#include \"AccumTime.h\"\n#include \"convexHull.hpp\"\n#include \"handlers.h\"\n#include \"laspec.h\"\n#include \"pseudoInverseMoorePenrose.h\"\n#include \"SMRF.h\"\n\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <memory>\n#include <omp.h>\n#include <ostream>\n#include <stack>\n#include <utility>\n#include <vector>\n\n//\n// Created by miguelyermo on 9/7/20.\n//\n\n/*\n* FILENAME :  dtm.h\n* PROJECT  :  rule-based-classifier-cpp\n* DESCRIPTION : Creation and handling of a dtm.\n*\n*\n*\n*\n*\n* AUTHOR :    Miguel Yermo        START DATE : 09:20 9/7/20\n*\n*/\n\nnamespace SMRF\n{\n\nconstexpr unsigned g_cluster_max_size{ 128 };\n\nvoid classify(std::vector<Lpoint> & points, DTMGrid & dtm)\n{\n\tint count = 0;\n\n\tstd::ofstream f(mainOptions.outputDirName + \"/smrf/result.xyz\");\n\n\tf << std::fixed << std::setprecision(3);\n\n\tstd::cout << \"Labeling points...\\n\";\n\n\tfor (Lpoint & p : points)\n\t{\n\t\tdouble dtmZ = dtm.nnInterpolation(p);\n\t\tp.setClass(p.z() < dtmZ + MAX_HEIGHT ? GROUND : UNCLASSIFIED);\n\t\tcount += p.getClass() == GROUND;\n\t\tf << p.x() << \" \" << p.y() << \" \" << p.z() << \" \"\n\t\t\t<< p.I() << \" \" << p.rn() << \" \" << p.nor() << \" \" << p.dir() << \" \" << p.edge()\n\t\t\t<< \" \" << p.getClass() << \"\\n\";\n\t}\n\tstd::cout << \"Ground \" << count / double(points.size()) * 100 << \"%\\n\";\n}\n\n\n/* Distance from point to cell center */\ndouble distP2C(Lpoint & p, DTMCell * cell)\n{\n\treturn sqrt((p.x() - cell->center[0]) * (p.x() - cell->center[0]) +\n\t            (p.y() - cell->center[1]) * (p.y() - cell->center[1]));\n}\n\n/* Ensure neighbors indices are inside grid boundaries **/\ninline void DTMGrid::clampNeighIdcs(int ci, int cj, int r, int min[2], int max[2]) const\n{\n\tmin[0] = ci - r >= 0 ? ci - r : 0;\n\tmin[1] = cj - r >= 0 ? cj - r : 0;\n\tmax[0] = ci + r < rows ? ci + r : rows - 1;\n\tmax[1] = cj + r < cols ? cj + r : cols - 1;\n}\n\n/** Get non-empty neighboring cells in (row,col) pairs for a given radius (starts from left-bottom) */\n// TODO: Funcion muy optimizable si se asignan los vecinos al crear la malla\n// (8 vecinos salvo en esquinas y bordes) Ver computeCellNeighbors()\n// Tambien son necesarios los vecinos de orden superior\ninline std::vector<size_t> DTMGrid::getNeighCells(int Ci, int Cj, int r)\n{\n\tint min[2], max[2], maxNeighs = 0;\n\n\tclampNeighIdcs(Ci, Cj, r, min, max);\n\tmaxNeighs = (2 * r + 1) * (2 * r + 1) - 1;\n\tstd::vector<size_t> neighs;\n\tneighs.reserve(2 * maxNeighs);\n\tfor (size_t i = min[0]; i <= max[0]; i++)\n\t\tfor (size_t j = min[1]; j <= max[1]; j++)\n\t\t\tif ((i != Ci || j != Cj) && (!cells[i * cols + j].empty || cells[i * cols + j].inpainted))\n\t\t\t{\n\t\t\t\tneighs.push_back(i);\n\t\t\t\tneighs.push_back(j);\n\t\t\t}\n\treturn neighs;\n}\n\ndouble DTMGrid::nnInterpolation(Lpoint& p)\n{\n\tint    Ci = 0, Cj = 0, i = 0, j = 0, n = 0;\n\tdouble dist = 0, minDist = 0, z = 0;\n\tCi                         = ci[p.id()];\n\tCj                         = cj[p.id()];\n\tz                          = cells[Ci * cols + Cj].z;\n\tminDist                    = distP2C(p, &cells[Ci * cols + Cj]);\n\tstd::vector<size_t> neighs = getNeighCells(Ci, Cj, 1);\n\tfor (n = 0; n < neighs.size(); n += 2)\n\t{\n\t\ti = neighs[n];\n\t\tj = neighs[n + 1];\n\t\tif ((int) cells[i * cols + j].z == NO_DATA_VAL) continue;\n\t\tdist = distP2C(p, &cells[i * cols + j]);\n\t\tif (dist < minDist)\n\t\t{\n\t\t\tz       = cells[i * cols + j].z;\n\t\t\tminDist = dist;\n\t\t}\n\t}\n\treturn z;\n}\n\ndouble DTMGrid::slopeInterpolation(Lpoint & p)\n{\n\tint    Ci = 0, Cj = 0, i = 0, j = 0, n = 0;\n\tdouble dist = 0, minDist = 0, slope = 0;\n\tCi                         = ci[p.id()];\n\tCj                         = cj[p.id()];\n\tslope                      = cells[Ci * cols + Cj].slope;\n\tminDist                    = distP2C(p, &cells[Ci * cols + Cj]);\n\tstd::vector<size_t> neighs = getNeighCells(Ci, Cj, 1);\n\tfor (n = 0; n < neighs.size(); n += 2)\n\t{\n\t\ti = neighs[n];\n\t\tj = neighs[n + 1];\n\t\tif ((int) cells[i * cols + j].z == NO_DATA_VAL) continue;\n\t\tdist = distP2C(p, &cells[i * cols + j]);\n\t\tif (dist < minDist)\n\t\t{\n\t\t\tslope   = cells[i * cols + j].slope;\n\t\t\tminDist = dist;\n\t\t}\n\t}\n\treturn slope;\n}\n\nvoid DTMGrid::computeDtmZ(std::vector<Lpoint> & points, Octree & octree)\n{\n\tstd::cout << \"Computing dtm...\\n\";\n\n\tfor (auto& p : points)\n\t{\n\t\tp.setSlopeDTM(slopeInterpolation(p));\n\t\tp.setDtmZ(nnInterpolation(p));\n\t\t// TODO: check DTM and solve the bug to avoid it\n\t\tif ((p.z() - p.getDtmZ()) < 0)\n\t\t\tp.setRealZ(0.01);\n\t\telse\n\t\t\tp.setRealZ(p.z() - p.getDtmZ());\n\t}\n}\n\n/** Compare pairs by value (descending order) */\nstatic int pairCmpDesc(const void * p1, const void * p2)\n{\n\tint v1 = ((Pair *) p1)->value;\n\tint v2 = ((Pair *) p2)->value;\n\treturn v2 - v1;\n}\n\nstatic int cmpX(const void * a, const void * b)\n{\n\tdouble v1 = ((struct Coordinate *) a)->value;\n\tdouble v2 = ((struct Coordinate *) b)->value;\n\n\treturn (v1 > v2) - (v1 < v2);\n}\n\nextern DTMGrid* createGridDTM(double * min, double * max, int numPts, double cs)\n{\n\tint       i = 0, j = 0;\n\tdouble    r    = cs / 2.0;\n\tDTMGrid * grid = nullptr;\n\n\tgrid         = new DTMGrid;\n\tgrid->min[0] = ceil(min[0]);\n\tgrid->min[1] = ceil(min[1]);\n\tgrid->rows   = ceil((floor(max[0]) - grid->min[0]) / cs);\n\tgrid->cols   = ceil((floor(max[1]) - grid->min[1]) / cs);\n\tgrid->size   = grid->rows * grid->cols;\n\tgrid->ci.resize(numPts);\n\tgrid->cj.resize(numPts);\n\tgrid->cells.resize(grid->size);\n\tfor (i = 0; i < grid->rows; i++)\n\t{\n\t\tfor (j = 0; j < grid->cols; j++)\n\t\t{\n\t\t\tgrid->cells[i * grid->cols + j].id        = i * grid->cols + j;\n\t\t\tgrid->cells[i * grid->cols + j].obj       = false;\n\t\t\tgrid->cells[i * grid->cols + j].empty     = true;\n\t\t\tgrid->cells[i * grid->cols + j].inpainted = false;\n\t\t\tgrid->cells[i * grid->cols + j].center[0] = grid->min[0] + (i * cs) + r;\n\t\t\tgrid->cells[i * grid->cols + j].center[1] = grid->min[1] + (j * cs) + r;\n\t\t\tgrid->cells[i * grid->cols + j].z         = std::numeric_limits<double>::max();\n\t\t}\n\t}\n\treturn grid;\n}\n\n/** Get the adjacent cells for BE Surface */\nstd::vector<indexOfCell_t> DTMGrid::getAdjCellsBE(int ci, int cj)\n{\n\tint min[2], max[2];\n\n\tclampNeighIdcs(ci, cj, 1, min, max);\n\n\tstd::vector<indexOfCell_t> neighs{};\n\n\tfor (int i = min[0]; i <= max[0]; i++)\n\t\tfor (int j = min[1]; j <= max[1]; j++)\n\t\t{\n\t\t\tif ((i != ci || j != cj) && cells[i * cols + j].inhull)\n\t\t\t{\n\t\t\t\tneighs.emplace_back(i, j);\n\t\t\t}\n\t\t}\n\treturn neighs;\n}\n\n/** Get the adjacent cells for Minimun Surface */\nstd::vector<indexOfCell_t> DTMGrid::getAdjCellsMS(int Ci, int Cj)\n{\n\tint min[2], max[2]; // range of index for neighbours\n\n\tclampNeighIdcs(Ci, Cj, 1, min, max);\n\tstd::vector<indexOfCell_t> neighs{};\n\n\tfor (int i = min[0]; i <= max[0]; i++)\n\t\tfor (int j = min[1]; j <= max[1]; j++)\n\t\t\tif ((i != Ci || j != Cj) && cells[i * cols + j].inhull)\n\t\t\t\tneighs.emplace_back(i, j);\n\n\treturn neighs;\n}\n\n/** Check if a set have at least one cell which is not object */\nbool checkFullObj(DTMGrid *grid, std::vector<indexOfCell_t>& vec)\n{\n\tfor(const auto& cell : vec)\n\t{\n\t\tint pos{cell.first * grid->cols + cell.second};\n\t\tif (!grid->cells[pos].obj || (grid->cells[pos].obj && grid->cells[pos].inpainted))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** Filter the set taking object cells */\nstd::vector<indexOfCell_t> checkForObjCells(DTMGrid *grid, std::vector<indexOfCell_t>& vec)\n{\n\tstd::vector<indexOfCell_t> tmp{};\n\tfor (const auto& cell : vec)\n\t{\n\t\tint pos{cell.first * grid->cols + cell.second};\n\t\tif (grid->cells[pos].obj && !grid->cells[pos].inpainted)\n\t\t\ttmp.emplace_back(cell);\n\t}\n\treturn tmp;\n}\n\nvoid DTMGrid::createClusters(std::vector<indexOfCell_t>& inpaintCells, std::map<indexOfCell_t, std::vector<indexOfCell_t>>& neighbourCells,\n\t\tstd::vector<Cluster>& clusters, ListNeighsFn listNeighsFn, CheckNeighsFn chNeighsFn)\n{\n\tstd::vector<indexOfCell_t> remainingCells(inpaintCells);\n\n\twhile (!remainingCells.empty())\n\t{\n\t\tCluster cluster{};\n\t\t// stackCheckCell: cola que contén as celas baleiras adxacentes pendentes de comprobar\n\t\t// se teñen a súa vez máis celas adxacentes\n\t\tstd::stack<indexOfCell_t> stackCells{};\n\n\t\tstackCells.emplace(remainingCells[0]);\n\t\t\n\t\t// introducimos a primeira cela das que quedan por facer o inpainting\n\t\t// bucle para buscar veciños\n\t\twhile (!stackCells.empty())\n\t\t{\n\t\t\tauto& cell = stackCells.top();\n\t\t\tstackCells.pop();\n\n\t\t\t// evita que caia en bucle infinito: para que non volva a revisar a mesma cela\n\t\t\tauto begin(remainingCells.begin());\n\t\t\tauto end(remainingCells.end());\n\t\t\tif (std::find(begin, end, cell) == end)\n\t\t\t{\t\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::vector<indexOfCell_t> neighbours;\n\n\t\t\tneighbours = neighbourCells.at(cell);\n\t\t\t\n\t\t\t// quitamos esa cela da lista de pendentes por ver\n\t\t\tstd::erase(remainingCells, cell);\n\t\t\t\n            // anotamos esa cela para despois usala no sistema de ecuacións\n\t\t\tcluster.emplace_back(cell);\n\t\t\t\n            // lista de veciños do mesmo tipo da cela extraida\n\t\t\tauto listNeighs(listNeighsFn(this, neighbours));\n\n\t\t\tfor (int pos = 0; pos < listNeighs.size(); ++pos)\n\t\t\t{\n\t\t\t\tauto& empty = listNeighs[pos];\n\t\t\t\tstackCells.push(empty);\n\t\t\t}\n\t\t}\n\t\tclusters.emplace_back(cluster);\n\t}\n}\n\nvoid DTMGrid::solveSystems(std::vector<Cluster>& clusters, std::map<indexOfCell_t, std::vector<indexOfCell_t>>& neighbourCells,\n\tCheckValueCellFn chValueCellFn, ListNeighsFn listNeighsFn, CheckNeighsFn chNeighsFn, ChangeCellStateFn chCellStateFn)\n{\n\t/* resolución dos clusters */\n\tfor (auto pos{clusters.begin()}; pos != clusters.end(); ++pos)\n\t{\n\t\tCluster cluster{*pos};\n\t\t\n\t\twhile (!cluster.empty())\n\t\t{\n\t\t\tint col{};\n\t\t\tstd::vector<indexOfCell_t> columns{};\n\t\t\tstd::stack<indexOfCell_t> stackCells{};\n\n\t\t\tstackCells.emplace(cluster[0]);\n\t\t\t\n\t\t\twhile (!stackCells.empty() && columns.size() < g_cluster_max_size)\n\t\t\t{\n\t\t\t\tauto& cell = stackCells.top();\n\t\t\t\tstackCells.pop();\n\n\t\t\t\t// evita que caia en bucle infinito: para que non volva a revisar a mesma cela\n\t\t\t\tauto begin{cluster.begin()};\n\t\t\t\tauto end{cluster.end()};\n\t\t\t\tif (std::find(begin, end, cell) == end)\n\t\t\t\t{\t\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tauto neighbours(neighbourCells.at(cell));\n\t\t\t\tif (chNeighsFn(this, neighbours))\n\t\t\t\t{\n\t\t\t\t\tif (columns.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::erase(cluster, cell);\n\t\t\t\t\t\tcluster.emplace_back(cell);\n\t\t\t\t\t\tstackCells.emplace(cluster[0]);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// quitamos esa cela da lista de pendentes por ver\n\t\t\t\tstd::erase(cluster, cell);\n\t\t\t\t\n\t\t\t\t// anotamos esa cela para despois usala no sistema de ecuacións\n\t\t\t\tcolumns.emplace_back(cell);\n\t\t\t\t\n\t\t\t\t// lista de veciños do mesmo tipo da cela extraida\n\t\t\t\tauto listNeighs(listNeighsFn(this, neighbours));\n\n\t\t\t\tfor (auto neigh{listNeighs.begin()}; neigh != listNeighs.end(); ++neigh)\n\t\t\t\t{\n\t\t\t\t\tstackCells.push(*neigh);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tEigen::MatrixXd M{columns.size() * 8, columns.size()};\n\t\t\tM.setZero();\n\t\t\tEigen::VectorXd b{columns.size() * 8};\n\t\t\tb.setZero();\n\t\t\t\n\t\t\tauto columnBegin{columns.begin()};\n\t\t\tauto columnEnd{columns.end()};\n\n\t\t\tint currentRow{};\n\t\t\tfor (int posCell{}; posCell < columns.size(); ++posCell)\n\t\t\t{\n\t\t\t\tauto cell{columns[posCell]};\n\t\t\t\tauto local{neighbourCells.at(cell)};\n\n\t\t\t\tint currentCol(posCell);\n\n\t\t\t\t// obtemos os valores Z das celas veciñas\n\t\t\t\tfor (int posNeigh = 0; posNeigh < local.size(); ++posNeigh)\n\t\t\t\t{\n\t\t\t\t\tbool emptyNeigh{false};\n                    std::vector<indexOfCell_t>::iterator found{};\n                    indexOfCell_t neighbour(local[posNeigh]);\n\t\t\t\t\t\n                    emptyNeigh = chValueCellFn(this, neighbour);\n\t\t\t\t\tfound = std::find(columnBegin, columnEnd, neighbour);\n\n\t\t\t\t\tif (emptyNeigh && found == columnEnd)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tdouble z{emptyNeigh ? 0.0 : cells[neighbour.first * cols + neighbour.second].z};\n                \n\t\t\t\t\tif (emptyNeigh)\n\t\t\t\t\t{\n\t\t\t\t\t\tM(currentRow, std::distance(columnBegin, found)) = -1.0; \n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tM(currentRow, currentCol) = 1.0;\n\t\t\t\t\tb[currentRow] = z;\n\t\t\t\t\t\n\t\t\t\t\t++currentRow;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tEigen::VectorXd x = pseudoInverse(M) * b;\n            \n\t\t\tfor (int posCell = 0; posCell < columns.size(); ++posCell)\n\t\t\t{\n\t\t\t\tauto cell{columns[posCell]};\n\t\t\t\tcells[cell.first * cols + cell.second].z = x[posCell];\n\t\t\t\tchCellStateFn(this, cell);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool isObj(DTMGrid* grid, indexOfCell_t cell)\n{\n\treturn grid->cells[cell.first * grid->cols + cell.second].obj;\n}\n\nvoid changeObjToFalse(DTMGrid* grid, indexOfCell_t& cell)\n{\n\tgrid->cells[cell.first * grid->cols + cell.second].obj = false;\n\tgrid->cells[cell.first * grid->cols + cell.second].inpainted = true;\n}\n\n/** Inpaint Bare Earth */\nvoid DTMGrid::inpaintBE()\n{\n\tstd::vector<indexOfCell_t> vectorOfObjCells{};\n\n\t// assign column for every cell\n\tfor (int i = 0; i < rows; ++i)\n\t\tfor (int j = 0; j < cols; ++j)\n\t\t\tif (cells[i * cols + j].inhull && cells[i * cols + j].obj)\n\t\t\t{\n\t\t\t\tvectorOfObjCells.emplace_back(std::make_pair(i, j));\n\t\t\t}\n\n\tconst int numObj{static_cast<int>(vectorOfObjCells.size())};\n\tstd::cout << numObj << \" obj cells \" << numObj * 100.0 / size << \"%\\n\";\n\tstd::cout << \"Inpainting... \" << std::flush;\n\n\t// collemos tódolas celas baleiras e almacenamos os seus veciños nunha lista\n\tstd::map<indexOfCell_t, std::vector<indexOfCell_t>> neighbourOfObjCells{};\n\t// remainingCells contén as celas restantes para o inpainting (inicialmente todas)\n\t\n\tfor (int pos = 0; pos < vectorOfObjCells.size(); ++pos)\n\t{\n\t\tauto cell{vectorOfObjCells.at(pos)};\n\t\tneighbourOfObjCells.emplace(cell, getAdjCellsBE(cell.first, cell.second));\n\t}\n\t\n\tauto chValueFn{ &isObj };\n\tauto chCellStateFn{ &changeObjToFalse };\n\tauto lsNeighsFn{ &checkForObjCells };\n\tauto chNeighsFn{ &checkFullObj};\n\n\tstd::vector<Cluster> clusters{};\n\t\n\tcreateClusters(vectorOfObjCells, neighbourOfObjCells, clusters, lsNeighsFn, chNeighsFn);\n\tsolveSystems(clusters, neighbourOfObjCells, chValueFn, lsNeighsFn, chNeighsFn, chCellStateFn);\n\n\tstd::cout << numObj << \" inpainted\" << '\\n';\n}\n\n/** Get number of valid adjacent cells for Minimum Surface */\nint DTMGrid::getNumAdjMS(int Ci, int Cj)\n{\n\tint num = 0, min[2], max[2];\n\n\tclampNeighIdcs(Ci, Cj, 1, min, max);\n\tfor (size_t i = min[0]; i <= max[0]; i++)\n\t\tfor (size_t j = min[1]; j <= max[1]; j++)\n\t\t\tif ((i != Ci || j != Cj) && (!cells[i * cols + j].empty || cells[i * cols + j].inpainted)) num++;\n\treturn num;\n}\n\nbool areAdjacent(indexOfCell_t c1, indexOfCell_t c2)\n{\n\t// first, we check if c2 is in a near row\n\tif (c1.first == c2.first || c1.first == c2.first + 1 || c1.first == c2.first - 1)\n\t\t// second, the same with the column\n\t\tif (c1.second == c2.second || c1.second == c2.second + 1 || c1.second == c2.second - 1)\n\t\t\treturn true;\n\n\treturn false;\n}\n\nbool checkFullEmpty(DTMGrid *grid, std::vector<indexOfCell_t> & vec)\n{\n\tfor(auto cell{vec.begin()}; cell != vec.end(); ++cell)\n\t{\n\t\tint pos{cell->first * grid->cols + cell->second};\n\t\tif (!grid->cells[pos].empty || (grid->cells[pos].empty && grid->cells[pos].inpainted))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nstd::vector<indexOfCell_t> checkForEmptyCells(DTMGrid *grid, std::vector<indexOfCell_t> & vec)\n{\n\tstd::vector<indexOfCell_t> tmp{};\n\n\tfor (auto& cell : vec)\n\t{\n\t\tint pos{cell.first * grid->cols + cell.second};\n\t\tif (grid->cells[pos].empty && !grid->cells[pos].inpainted)\n\t\t\ttmp.emplace_back(cell);\n\t}\n\treturn tmp;\n}\n\nvoid changeInpaintedToTrue(DTMGrid *grid, indexOfCell_t& cell)\n{\n\tgrid->cells[cell.first * grid->cols + cell.second].inpainted = true;\n}\n\nbool isEmpty(DTMGrid* grid, indexOfCell_t cell)\n{\n\treturn grid->cells[cell.first * grid->cols + cell.second].empty && !grid->cells[cell.first * grid->cols + cell.second].inpainted;\n}\n\n/** Inpaint Minimum Surface */\nvoid DTMGrid::inpaintMS(std::vector<indexOfCell_t>& vectorOfEmptyCells)\n{\n\tconst int numEmpty(vectorOfEmptyCells.size());\n\tstd::cout << \"Inpainting... \" << std::flush;\n\n\t// collemos tódolas celas baleiras e almacenamos os seus veciños nunnha lista\n\tstd::map<indexOfCell_t, std::vector<indexOfCell_t>> neighbourOfEmptyCells{};\n\n\tfor (int pos = 0; pos < vectorOfEmptyCells.size(); ++pos)\n\t{\n\t\tauto& cell{vectorOfEmptyCells.at(pos)};\n\t\tneighbourOfEmptyCells.emplace(cell, getAdjCellsMS(cell.first, cell.second));\n\t}\n\n\tauto chValueFn{ &isEmpty };\n\tauto chCellStateFn{ &changeInpaintedToTrue };\n\tauto lsNeighsFn{ &checkForEmptyCells };\n\tauto chNeighsFn{ &checkFullEmpty };\n\t\n\tstd::vector<Cluster> clusters{};\n\n\tcreateClusters(vectorOfEmptyCells, neighbourOfEmptyCells, clusters, lsNeighsFn, chNeighsFn);\n\tsolveSystems(clusters, neighbourOfEmptyCells, chValueFn, lsNeighsFn, chNeighsFn, chCellStateFn);\n\t\n\tstd::cout << numEmpty << \" inpainted\" << '\\n';\n}\n\n/** Generate a minimun surface with the lowest cell points */\nvoid DTMGrid::genMinSurface(Octree & octree, ConvexHull & hull)\n{\n\tLpoint center(0, 0, 0, 0);\n\tstd::vector<indexOfCell_t> emptyCells{};\n\n\tfor (int i{}; i < rows; ++i)\n\t\tfor (int j{}; j < cols; ++j)\n\t\t{\n\t\t\tcenter.id(-1);\n\t\t\tcenter.setX(cells[i * cols + j].center[0]);\n\t\t\tcenter.setY(cells[i * cols + j].center[1]);\n\t\t\tcells[i * cols + j].inhull = hull.inHull(center);\n\t\t\tif (!cells[i * cols + j].inhull) continue;\n\t\t\tstd::vector<Lpoint *> points = octree.searchNeighbors2D(center, CELL_SIZE);\n\t\t\tif (!points.empty())\n\t\t\t{\n\t\t\t\tfor (int k{}; k < points.size(); ++k)\n\t\t\t\t{\n\t\t\t\t\tci[points[k]->id()] = i;\n\t\t\t\t\tcj[points[k]->id()] = j;\n\t\t\t\t\tif (points[k]->z() < cells[i * cols + j].z) cells[i * cols + j].z = points[k]->z();\n\t\t\t\t}\n\t\t\t\tcells[i * cols + j].empty = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\temptyCells.emplace_back(std::make_pair(i, j));\n\t\t\t}\n\t\t}\n\n\tint numEmpty{static_cast<int>(emptyCells.size())};\n\n\tstd::cout << std::setprecision(2);\n\tstd::cout << numEmpty << \" empty cells \" << numEmpty * 100.0 / size << \"%\\n\";\n\tAccumTime::instance().start();\n\tinpaintMS(emptyCells);\n\tAccumTime::instance().stop(\"Inpaint Minimum Surface\");\n}\n\n/** Perform morphological opening */\nDTMGrid DTMGrid::morphologicalOpening(int radius, int numPts)\n{\n\tint i = 0, j = 0, n = 0, ni = 0, nj = 0, numNeighs = 0;\n\n\tDTMGrid eGrid = *this;\n\n#pragma omp parallel for default(none) private(i, j, n, ni, nj, numNeighs) \\\n    shared(radius, eGrid)\n\tfor (i = 0; i < rows; i++) // Erosion\n\t\tfor (j = 0; j < cols; j++)\n\t\t{\n#if USE_DISK\n\t\t\tneighs = getDiskNeighCells(grid, i, j, radius, &numNeighs);\n#else\n\t\t\tstd::vector<size_t> neighs = getNeighCells(i, j, radius);\n#endif\n\t\t\tfor (n = 0; n < neighs.size(); n += 2)\n\t\t\t{\n\t\t\t\tni = neighs[n];\n\t\t\t\tnj = neighs[n + 1];\n\t\t\t\tif (cells[ni * cols + nj].z < eGrid.cells[i * cols + j].z) eGrid.cells[i * cols + j].z = cells[ni * cols + nj].z;\n\t\t\t}\n\t\t}\n\n\tDTMGrid oGrid = eGrid;\n#pragma omp parallel for default(none) private(i, j, n, ni, nj, numNeighs) \\\n    shared(radius, eGrid, oGrid)\n\tfor (i = 0; i < eGrid.rows; i++) // Dilation\n\t\tfor (j = 0; j < eGrid.cols; j++)\n\t\t{\n#if USE_DISK\n\t\t\tneighs = getDiskNeighCells(eGrid, i, j, radius, &numNeighs);\n#else\n\t\t\tstd::vector<size_t> neighs = eGrid.getNeighCells(i, j, radius);\n#endif\n\t\t\tfor (n = 0; n < neighs.size(); n += 2)\n\t\t\t{\n\t\t\t\tni = neighs[n];\n\t\t\t\tnj = neighs[n + 1];\n\t\t\t\tif (eGrid.cells[ni * cols + nj].z > oGrid.cells[i * cols + j].z)\n\t\t\t\t\toGrid.cells[i * cols + j].z = eGrid.cells[ni * cols + nj].z;\n\t\t\t}\n\t\t}\n\n\treturn oGrid;\n}\n\n\nvoid getMinMaxCoordinates(std::vector<Lpoint> & points, double * min, double * max)\n{\n\tmin[0] = min[1] = min[2] = std::numeric_limits<double>::max();\n\tmax[0] = max[1] = max[2] = -std::numeric_limits<double>::max();\n\tfor (auto & p : points)\n\t{\n\t\tif (p.x() < min[0]) min[0] = p.x();\n\t\tif (p.y() < min[1]) min[1] = p.y();\n\t\tif (p.z() < min[2]) min[2] = p.z();\n\t\tif (p.x() > max[0]) max[0] = p.x();\n\t\tif (p.y() > max[1]) max[1] = p.y();\n\t\tif (p.z() > max[2]) max[2] = p.z();\n\t}\n}\n\n/** Calculate plane slope by average maximum technique (ArGIS)\n *  @todo Handle slope when the cell it's at the grid boundary\n */\nvoid DTMGrid::calcSlopes()\n{\n\tdouble a = 0, b = 0, c = 0, d = 0, f = 0, g = 0, h = 0, I = 0, dzdx = 0, dzdy = 0,\n\t       rise = 0;\n\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < cols; j++)\n\t\t\tif (!cells[i * cols + j].empty || cells[i * cols + j].inpainted)\n\t\t\t{\n\t\t\t\tstd::vector<size_t> neighs = getNeighCells(i, j, 1);\n\t\t\t\tif (neighs.size() == 16)\n\t\t\t\t{\n\t\t\t\t\tg                 = cells[neighs[0] * cols + neighs[1]].z;\n\t\t\t\t\th                 = cells[neighs[2] * cols + neighs[3]].z;\n\t\t\t\t\tI                 = cells[neighs[4] * cols + neighs[5]].z;\n\t\t\t\t\td                 = cells[neighs[6] * cols + neighs[7]].z;\n\t\t\t\t\tf                 = cells[neighs[8] * cols + neighs[9]].z;\n\t\t\t\t\ta                 = cells[neighs[10] * cols + neighs[11]].z;\n\t\t\t\t\tb                 = cells[neighs[12] * cols + neighs[13]].z;\n\t\t\t\t\tc                 = cells[neighs[14] * cols + neighs[15]].z;\n\t\t\t\t\tdzdx              = ((c + 2 * f + I) - (a + 2 * d + g)) / (8 * CELL_SIZE);\n\t\t\t\t\tdzdy              = ((g + 2 * h + I) - (a + 2 * b + c)) / (8 * CELL_SIZE);\n\t\t\t\t\trise              = sqrt(dzdx * dzdx + dzdy * dzdy);\n\t\t\t\t\tcells[i * cols +j].slope = atan(rise) * 180 / M_PI;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// see todo\n\t\t\t\t}\n\t\t\t}\n}\n\n\nvoid DTMGrid::computeDTM(std::vector<Lpoint>& points, Octree & octree, double * Min,\n                         double * max)\n{\n\tAccumTime::instance().start();\n\tConvexHull hull(points);\n\tAccumTime::instance().stop(\"Computing Convex Hull\");\n\n\t// medición de inpaintMS no interior\n\tgenMinSurface(octree, hull);\n\n\tAccumTime::instance().start();\n\tidentifyCells(points.size());\n\tAccumTime::instance().stop(\"Identifying cells\");\n\n\tAccumTime::instance().start();\n\tidentifyOutliers(points.size(), Min[2], max[2]);\n\tAccumTime::instance().stop(\"Identifying outliers\");\n\n\tAccumTime::instance().start();\n\tinpaintBE();\n\tAccumTime::instance().stop(\"Inpainting Bare Earth\");\n}\n\n/** Improved Simple Morphological Filter (SMRF) (Pingel, 2013) */\nDTMGrid smrf(std::vector<Lpoint> & points, Octree & octree, double min[3], double max[3])\n{\n\tstd::cout << \"---- Computing DTM (SMRF) ----\\n\";\n\tDTMGrid dtm(min, max, points.size(), CELL_SIZE);\n\tdtm.computeDTM(points, octree, min, max);\n\n\n\tdtm.calcSlopes();\n\tdtm.computeDtmZ(points, octree);\n\n\tstd::string outDir = mainOptions.outputDirName + \"/smrf\";\n\tcreateDirectory(outDir);\n\tdtm.writeToFile(outDir + \"/dtm.xyz\");\n\tdtm.createDTM(outDir + \"/dtm.asc\");\n\n\tclassify(points, dtm);\n\n\treturn dtm;\n}\n\nDTMGrid::DTMGrid(double * min, double * max, int numPts_, double cs)\n{\n\tint    i = 0, j = 0;\n\tdouble r = cs / 2.0;\n\n\tmin[0] = ceil(min[0]);\n\tmin[1] = ceil(min[1]);\n\tcols   = ceil((floor(max[0]) - min[0]) / cs);\n\trows   = ceil((floor(max[1]) - min[1]) / cs);\n\tsize   = rows * cols;\n\tnumPts = numPts_;\n\tci.resize(numPts);\n\tcj.resize(numPts);\n\tcells.resize(size);\n\n\tfor (i = 0; i < rows; i++)\n\t{\n\t\tfor (j = 0; j < cols; j++)\n\t\t{\n\t\t\tcells[i * cols + j].id        = i * cols + j;\n\t\t\tcells[i * cols + j].obj       = false;\n\t\t\tcells[i * cols + j].empty     = true;\n\t\t\tcells[i * cols + j].inpainted = false;\n\t\t\tcells[i * cols + j].center[0] = min[0] + (j * cs) + r;\n\t\t\tcells[i * cols + j].center[1] = min[1] + (i * cs) + r;\n\t\t\tcells[i * cols + j].z         = std::numeric_limits<double>::max();\n\t\t}\n\t}\n\n\tstd::cout << \"Cols: \" << cols << \", Rows: \" <<  rows << \"\\n\";\n}\n\n// Copy Constructor\nDTMGrid::DTMGrid(const DTMGrid & dtm)\n{\n\trows  = dtm.rows;\n\tcols  = dtm.cols;\n\tsize  = dtm.size;\n\tci    = dtm.ci;\n\tcj    = dtm.cj;\n\tmin   = dtm.min;\n\tcells = dtm.cells;\n}\n\nvoid DTMGrid::identifyOutliers(int numPts_, double minZ, double maxZ)\n{\n\tint     i = 0, j = 0, count = 0;\n\tdouble  maxHeight = 0;\n\tDTMGrid oInvMinSurface;\n\n\tstd::cout << \"Identifying outliers... \" << std::flush;\n\n\tDTMGrid invMinSurface = *this;\n\n\tfor (i = 0; i < invMinSurface.rows; i++)\n\t\tfor (j = 0; j < invMinSurface.cols; j++)\n\t\t\tinvMinSurface.cells[i * cols + j].z = (maxZ + minZ) - invMinSurface.cells[i * cols + j].z;\n\n\tmaxHeight      = 5 * MAX_SLOPE * 1 * CELL_SIZE;\n\toInvMinSurface = invMinSurface.morphologicalOpening(1, numPts_);\n\n\tfor (i = 0; i < invMinSurface.rows; i++)\n\t\tfor (j = 0; j < invMinSurface.cols; j++)\n\t\t\tif (invMinSurface.cells[i * cols + j].z - oInvMinSurface.cells[i * cols + j].z > maxHeight)\n\t\t\t{\n\t\t\t\tcells[i * cols + j].obj = true;\n\t\t\t\tcount++;\n\t\t\t}\n\tstd::cout << count << \" outliers\\n\";\n}\n\nvoid DTMGrid::identifyCells(int numPts_)\n{\n\tint     maxWindow = 0;\n\tdouble  maxHeight = 0;\n\n\tDTMGrid lastSurface = *this;\n\n\tmaxWindow = std::ceil(MAX_WINDOW_SIZE / CELL_SIZE);\n\tfor (int window = 1; window <= maxWindow; window++)\n\t{\n\t\tmaxHeight = MAX_SLOPE * (float) window * CELL_SIZE;\n\n#if DEBUG\n\t\tstd::cout << std::setprecision(2);\n\t\tstd::cout << \"SMRF w=\" << window << \"/\" << maxWindow << \" h=\" << maxHeight << \"...\\n\";\n#endif\n\n\t\tDTMGrid thisSurface = lastSurface.morphologicalOpening(window, numPts_);\n\t\tfor (int i = 0; i < thisSurface.rows; i++)\n\t\t\tfor (int j = 0; j < thisSurface.cols; j++)\n\t\t\t\tif (lastSurface.cells[i * cols + j].z - thisSurface.cells[i * cols + j].z > maxHeight)\n\t\t\t\t\tthisSurface.cells[i * cols + j].obj = true;\n\n\t\tlastSurface = thisSurface;\n\t}\n\tfor (int i = 0; i < lastSurface.rows; i++)\n\t\tfor (int j = 0; j < lastSurface.cols; j++)\n\t\t\tcells[i * cols + j].obj = lastSurface.cells[i * cols + j].obj;\n}\n\n} // namespace dtm\n", "meta": {"hexsha": "df57fd0c20951014d491944fef184ae9a686176d", "size": 24835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SMRF.cpp", "max_stars_repo_name": "xannieto/rule-based-classifier-cpp", "max_stars_repo_head_hexsha": "d458ff7808ed59de29692843f28167902a47a536", "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/SMRF.cpp", "max_issues_repo_name": "xannieto/rule-based-classifier-cpp", "max_issues_repo_head_hexsha": "d458ff7808ed59de29692843f28167902a47a536", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SMRF.cpp", "max_forks_repo_name": "xannieto/rule-based-classifier-cpp", "max_forks_repo_head_hexsha": "d458ff7808ed59de29692843f28167902a47a536", "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.4805045872, "max_line_length": 139, "alphanum_fraction": 0.6052748138, "num_tokens": 8105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.033589502264131835, "lm_q1q2_score": 0.015746443315893498}}
{"text": "\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <regex>\n#include <GBPCalc.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/program_options.hpp>\n\nusing boost::property_tree::getSortedChildren;\nnamespace po = boost::program_options;\n\n\nvoid print_usage( std::string program_name, po::options_description &options_desc)\n{\n  std::cerr << \"Usage: \" << program_name << \" [options] [<infile>] \"<<std::endl;\n  std::cerr << options_desc << std::endl;\n  exit (8);\n}\n\n\n// read configuration file (in various formats) and return a property tree\nptree readConfig(std::string filename, std::string format = \"ini\")\n{\n  ptree configTree;\n  if( format == \"ini\" )\n  {\n    ptree stage;\n    boost::property_tree::read_ini( filename, stage);\n\n    for(auto iter : stage)\n      configTree.put( iter.first, iter.second.get<std::string>(\"\") );\n  }\n\n  if( format == \"json\" )\n  {\n    boost::property_tree::read_json( filename, configTree);\n  }\n\n  if( format == \"xml\" )\n  {\n    boost::property_tree::read_xml( filename, configTree);\n  }\n\n  return configTree;\n}\n\n// utility function to convert data to strings\ntemplate<typename T>\nstd::string toString( T v )\n{\n  std::stringstream stream;\n  stream << v;\n  return stream.str();\n}\n\n// get a parameter from a beam based on a parameter name\nstd::string getBeamParam( GaussianBeam &beam, std::string name )\n{\n  \n#define RETURN( pattern, param )\\\n  if(std::regex_match(name, std::regex(pattern, std::regex_constants::icase ) ) ) { return toString( beam.get##param().value() ); }\n\nRETURN(\"^beam\\\\s*diameter$\", Diameter);\nRETURN(\"^diameter$\", Diameter);\nRETURN(\"^divergence$\", Divergence );\nRETURN(\"^radius\\\\s*of\\\\s*curvature$\", Divergence );\nRETURN(\"^RoC$\", Divergence );\n\nreturn \"UNKNOWN\";\n}\n\n// structure for managing data to log\nstruct Log\n{\n  std::queue<std::string> lines;\n  std::string line;\n\n  std::vector<std::string> inputNames;\n  std::vector<std::string> outputNames;\n\n  std::string filename;\n\n  template<typename T>\n  void stage(T data)\n  {\n    if( line != \"\" )\n      line += \" \";\n\n    line += toString(data);\n  }\n\n  void push()\n  {\n    lines.push( line );\n    line = \"\";\n  }\n\n  void write( std::ostream& out )\n  {\n    while( !lines.empty() )\n    {\n      out << lines.front() << \"\\n\";\n      lines.pop();\n    }\n  }\n\n  void write( )\n  {\n    std::ofstream out( filename );\n    write(out);\n    out.close();\n  }\n\n  void readOutputs( GaussianBeam beam )\n  {\n    for( auto name : outputNames )\n      this->stage( getBeamParam( beam, name ) );\n  }\n\n  void readInputs( ptree config )\n  {\n    for( auto name : inputNames )\n      this->stage( config.get<std::string>( name, \"UNKNOWN\") );\n  }\n\n  void setFilename( std::string prefix, std::string name)\n  {\n    filename = prefix+\".\"+name+\".log\";\n  }\n\n\n};\n\n\nint main(int argc, char *argv[])\n{\n\n\n  // option handler\n  po::options_description options(\"Supported Options\");\n  options.add_options()\n      (\"help,h\"                                                                           , \"print help message\")\n      (\"verbose,v\"                , po::value<int>()->default_value(0)                    , \"the verbose level (-v -> verbose level 1, -vv -> verbose level 2, etc)\" )\n      (\"debug,d\"                  , po::value<int>()->default_value(0)                    , \"the debug level (-d -> debug level 1, -dd -> debug level 2, etc)\" )\n      (\"config,m\"                 , po::value<std::string>()->default_value(\"gbp.conf\")   , \"configuration file\" )\n      ;\n\n  po::positional_options_description args;\n  args.add(\"config\", 1);\n\n\n  po::variables_map vm;\n  po::store(  po::command_line_parser(argc, argv).options(options).positional(args).run(), vm);\n  po::notify(vm);\n\n  // options (including arguments) have been parsed.\n\n  if (argc == 1 || vm.count(\"help\"))\n  {\n    print_usage( argv[0], options );\n    return 1;\n  }\n  \n\n\n\n  // application\n\n\n  GBPCalc<t::centimeter> calculator;\n  ptree configTree;\n\n  // read config file.\n  configTree = readConfig( vm[\"config\"].as<std::string>(), \"ini\" );\n  //boost::property_tree::write_json( std::cout, configTree );\n\n\n  for( auto run : configTree.get_child(\"parametric_runs\") )\n  {\n    ptree configTreeCopy = configTree;\n    std::string x_name = run.second.get<std::string>(\"parameters.0.name\");\n    std::queue<double> x_vals;\n    boost::optional<double> min = run.second.get<double>(\"parameters.0.min\");\n    boost::optional<double> max = run.second.get<double>(\"parameters.0.max\");\n    boost::optional<size_t> n   = run.second.get<size_t>(\"parameters.0.n\");\n\n    if(min && max && n)\n    {\n      double dz = (max.value() - min.value())/(n.value()-1);\n\n      for( size_t i = 0; i < n.value(); i++)\n        x_vals.push( (min.value() + i*dz) );\n    }\n    auto valuesConfig = run.second.get_child_optional(\"values\");\n    if(valuesConfig)\n      for( auto iter: getSortedChildren( valuesConfig.value(), keyIntComp, isInt ) )\n        x_vals.push( iter->second.get<double>(\"\") );\n\n\n    std::map<std::string, boost::shared_ptr<Log>> logs;\n    std::string logPrefix = run.second.get<std::string>(\"logging.prefix\", \"GBP\");\n    for( auto logConfig : getSortedChildren( run.second.get_child(\"logging.loggers\"), keyIntComp, isInt) )\n    {\n      std::string name = logConfig->second.get<std::string>(\"tag\",\"data\");\n      logs[ name ] = boost::shared_ptr<Log>( new Log() );\n      logs[ name ]->setFilename( logPrefix, name );\n      logs[ name ]->stage(\"#\");\n      calculator.sig_calculatedBeam.connect( decltype(calculator.sig_calculatedBeam)::slot_type( &Log::readOutputs, logs[ name ].get(), _1 ).track(logs[name]) );\n      if( logConfig->second.get_child_optional(\"inputs\") )\n      {\n        for( auto data : getSortedChildren( logConfig->second.get_child(\"inputs\"), keyIntComp, isInt) )\n        {\n          std::string inputName = data->second.get<std::string>(\"name\");\n          logs[ name ]->inputNames.push_back( inputName );\n          logs[ name ]->stage( inputName );\n        }\n      }\n      if( logConfig->second.get_child_optional(\"outputs\") )\n      {\n        for( auto data : getSortedChildren( logConfig->second.get_child(\"outputs\"), keyIntComp, isInt) )\n        {\n          std::string outputName = data->second.get<std::string>(\"name\");\n          logs[ name ]->outputNames.push_back( data->second.get<std::string>(\"name\") );\n          logs[ name ]->stage( outputName );\n        }\n      }\n      logs[ name ]->push();\n    }\n\n\n    while( !x_vals.empty() )\n    {\n      configTreeCopy.put( x_name, x_vals.front() );\n\n      calculator.configure( configTreeCopy );\n\n      // make sure inputs get logged first\n      for( auto log : logs )\n        log.second->readInputs( configTreeCopy );\n\n      calculator.calculate();\n\n      // push new line onto log\n      for( auto log : logs )\n        log.second->push();\n\n      x_vals.pop();\n    }\n\n    for( auto log : logs )\n      log.second->write();\n\n\n\n  }\n\n \n\n  return 0;\n}\n", "meta": {"hexsha": "69d54561dd81b580445b365cdbfb7ff9df1d1acb", "size": 6940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/gbp-cli.cpp", "max_stars_repo_name": "CD3/libGBP", "max_stars_repo_head_hexsha": "6561f41d74d0e4010872c12db1dcc12363826365", "max_stars_repo_licenses": ["MIT"], "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/gbp-cli.cpp", "max_issues_repo_name": "CD3/libGBP", "max_issues_repo_head_hexsha": "6561f41d74d0e4010872c12db1dcc12363826365", "max_issues_repo_licenses": ["MIT"], "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/gbp-cli.cpp", "max_forks_repo_name": "CD3/libGBP", "max_forks_repo_head_hexsha": "6561f41d74d0e4010872c12db1dcc12363826365", "max_forks_repo_licenses": ["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.2878787879, "max_line_length": 166, "alphanum_fraction": 0.6096541787, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.04603390534395609, "lm_q1q2_score": 0.015724375829196342}}
{"text": "/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */\n#include \"cas.h\"\n\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <deque>\n#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <string>\n\n#include <boost/spirit/include/lex_lexertl.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/uuid/uuid_io.hpp>\n\n#include \"cas/dimension.h\"\n#include \"cas/helper.h\"\n\nusing namespace boost::spirit;\n\nnamespace flint {\nnamespace cas {\n\nnamespace {\n\nbool IsConditional(const Compound &x)\n{\n\treturn x.keyword == \"case-set\";\n}\n\nbool IsConditional(const Expr &x, Compound &y)\n{\n\tif (x.which() != kExprIsCompound) return false;\n\ty = boost::get<Compound>(x);\n\treturn IsConditional(y);\n}\n\nbool IsEquation(const Compound &x)\n{\n\treturn x.keyword == \"eq\" && x.children.size() >= 2;\n}\n\nbool IsEquation(const Expr &x, Compound &y)\n{\n\tif (x.which() != kExprIsCompound) return false;\n\ty = boost::get<Compound>(x);\n\treturn IsEquation(y);\n}\n\nbool IsBoundVariable(const Expr &expr)\n{\n\tif (expr.which() == kExprIsCompound) {\n\t\tconst Compound &c = boost::get<Compound>(expr);\n\t\tif (c.keyword == \"bvar\") {\n\t\t\tif (c.children.size() == 1) {\n\t\t\t\tconst Expr &e0 = c.children[0];\n\t\t\t\tif (e0.which() == kExprIsIdentifier) {\n\t\t\t\t\tconst std::string &s0 = boost::get<Identifier>(e0).name;\n\t\t\t\t\tif (s0 == \"%time\")\n\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tstd::cerr << \"unsupported bound variable of <diff>\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\tstd::cerr << \"unsupported form of <diff>'s 1st argument\" << std::endl;\n\treturn false;\n}\n\nvoid ReportInvalidLeafOfCaseSet(const boost::uuids::uuid &uuid)\n{\n\tstd::cerr << \"invalid formula found in <case-set>: \" << uuid << std::endl;\n}\n\nbool TransformConditional(const Compound &c, Expr &lhs, Compound &rhs)\n{\n\trhs.keyword = \"piecewise\";\n\trhs.children.clear();\n\n\tfor (const auto &child : c.children) {\n\t\tassert(child.which() == kExprIsCompound);\n\t\tconst Compound &cs = boost::get<Compound>(child);\n\t\tassert(cs.keyword == \"case\");\n\t\tCompound r;\n\t\tCompound w;\n\t\tswitch (cs.children.size()) {\n\t\tcase 1:\n\t\t\t{\n\t\t\t\tr.keyword = \"otherwise\";\n\t\t\t\tr.children.resize(1);\n\n\t\t\t\tconst Expr &v(cs.children[0]);\n\t\t\t\tif (IsConditional(v, w)) {\n\t\t\t\t\tCompound t;\n\t\t\t\t\tif (!TransformConditional(w, lhs, t)) return false;\n\t\t\t\t\tr.children[0] = t;\n\t\t\t\t} else if (IsEquation(v, w)) {\n\t\t\t\t\tlhs = w.children[0];\n\t\t\t\t\tr.children[0] = w.children[1];\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\trhs.children.push_back(r);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\t{\n\t\t\t\tr.keyword = \"piece\";\n\t\t\t\tr.children.resize(2);\n\n\t\t\t\tconst Expr &v0(cs.children[0]);\n\t\t\t\tconst Expr &v1(cs.children[1]);\n\t\t\t\tr.children[1] = v0;\n\t\t\t\tif (IsConditional(v1, w)) {\n\t\t\t\t\tCompound t;\n\t\t\t\t\tif (!TransformConditional(w, lhs, t)) return false;\n\t\t\t\t\tr.children[0] = t;\n\t\t\t\t} else if (IsEquation(v1, w)) {\n\t\t\t\t\tlhs = w.children[0];\n\t\t\t\t\tr.children[0] = w.children[1];\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\trhs.children.push_back(r);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(false);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn true;\n}\n\ntemplate<typename TLexer>\nstruct Lexer : lex::lexer<TLexer> {\n\n\tLexer() {\n\t\tthis->self.add_pattern\n\t\t\t(\"SIGN\", \"[-+]\")\n\t\t\t(\"EXPONENT\", \"[eE]{SIGN}?\\\\d+\")\n\t\t\t(\"FLOAT\", \"(\\\".\\\"\\\\d+|\\\\d+\\\".\\\"\\\\d*){EXPONENT}?|\\\\d+{EXPONENT}\")\n\t\t\t;\n\n\t\tcase_set_ = \"case-set\";\n\t\tcase_ = \"case\";\n\t\tcondition_ = \"condition\";\n\t\teq_ = \"eq\";\n\t\tdelay_ = \"\\\"$\\\"Delay\";\n\t\tdelta_time_ = \"\\\"$\\\"DeltaTime\";\n\n\t\treal = \"{SIGN}?{FLOAT}\";\n\t\trational = \"{SIGN}?(0|[1-9]\\\\d*)\\\"/\\\"[1-9]\\\\d*\";\n\t\tinteger = \"{SIGN}?\\\\d+\";\n\t\tid = \"\\\"%\\\"[a-zA-Z_][a-zA-Z_0-9:]*\";\n\t\tkeyword = \"[$]?[a-zA-Z_]\\\\w*\";\n\n\t\tthis->self = lex::token_def<>('\\n') | '\\r' | '(' | ')' | ' ';\n\t\tthis->self += case_set_ | case_ | condition_ | eq_ | delay_ | delta_time_;\n\t\tthis->self += real | rational | integer | id | keyword;\n\t}\n\n\tlex::token_def<std::string> case_set_, case_, condition_, eq_, delay_, delta_time_;\n\tlex::token_def<std::string> id, keyword;\n\tlex::token_def<int> integer;\n\tlex::token_def<flint::lexer::Rational> rational;\n\tlex::token_def<flint::lexer::Real> real;\n};\n\nvoid RewriteDelayParam(Compound &x, const Expr &expr)\n{\n\tCompound c;\n\tc.keyword = \"minus\";\n\tc.children.push_back(Identifier(\"%time\"));\n\tc.children.push_back(expr);\n\tx.children.push_back(c);\n}\n\ntemplate<typename TIterator>\nstruct Grammar : qi::grammar<TIterator, Compound()> {\n\n\ttemplate<typename TTokenDef>\n\tGrammar(TTokenDef const &td)\n\t: Grammar::base_type(statement)\n\t{\n\t\tusing boost::phoenix::at_c;\n\t\tusing boost::phoenix::push_back;\n\t\tusing boost::phoenix::val;\n\n\t\tstatement = '(' >> bare_statement >> ')';\n\n\t\tbare_statement = equation | conditional;\n\n\t\tequation = td.eq_ [at_c<0>(_val) = _1]\n\t\t\t>> ' ' >> expr [push_back(at_c<1>(_val), _1)]\n\t\t\t>> ' ' >> expr [push_back(at_c<1>(_val), _1)];\n\n\t\tconditional = td.case_set_ [at_c<0>(_val) = _1]\n\t\t\t>> cseq [at_c<1>(_val) = _1];\n\n\t\tcseq = +(' ' >> celem);\n\n\t\tcelem = '(' >> cexp >> ')';\n\n\t\tcexp = conditioned_case | unconditioned_case;\n\n\t\tconditioned_case = td.case_ [at_c<0>(_val) = _1]\n\t\t\t>> ' ' >> '(' >> td.condition_\n\t\t\t>> ' ' >> expr [push_back(at_c<1>(_val), _1)]\n\t\t\t>> ')'\n\t\t\t>> ' '\n\t\t\t>> statement [push_back(at_c<1>(_val), _1)];\n\n\t\tunconditioned_case = td.case_ [at_c<0>(_val) = _1]\n\t\t\t>> ' '\n\t\t\t>> statement [push_back(at_c<1>(_val), _1)];\n\n\t\texpr = comp_expr\n\t\t\t| td.real\n\t\t\t| td.rational\n\t\t\t| td.integer\n\t\t\t| td.id\n\t\t\t| td.keyword;\n\n\t\tcomp_expr = '(' >> bare_expr >> ')';\n\n\t\tbare_expr = delay_expr | delta_time_expr | eq_expr | general_expr;\n\n\t\tdelay_expr = td.delay_ [at_c<0>(_val) = val(\"$lookback\")]\n\t\t\t>> ' ' >> expr [push_back(at_c<1>(_val), _1)]\n\t\t\t>> ' ' >> expr [bind(&RewriteDelayParam, _val, _1)];\n\n\t\tdelta_time_expr = td.delta_time_ >> ' ' >> td.id [bind(&RewriteDeltaTime, _val, _1)];\n\n\t\teq_expr = td.eq_ [at_c<0>(_val) = _1]\n\t\t\t>> seq1 [at_c<1>(_val) = _1];\n\n\t\tgeneral_expr = td.keyword [at_c<0>(_val) = _1]\n\t\t\t>> seq0 [at_c<1>(_val) = _1];\n\n\t\tseq0 = *rest;\n\n\t\tseq1 = +rest;\n\n\t\trest = ' ' >> expr;\n\t}\n\n\tqi::rule<TIterator, Expr()> expr, rest;\n\tqi::rule<TIterator, Compound()> statement, bare_statement, equation,\n\t\tconditional, celem, cexp, conditioned_case, unconditioned_case,\n\t\tcomp_expr, bare_expr, delay_expr, delta_time_expr, eq_expr, general_expr;\n\tqi::rule<TIterator, std::deque<Expr>()> cseq, seq0, seq1;\n};\n\n/*\n * This class creates and keeps both tokens and grammar objects which\n * construction is expensive in terms of performance.\n */\nclass Parser {\npublic:\n\ttypedef const char *base_iterator_type;\n\ttypedef lex::lexertl::token<base_iterator_type> token_type;\n\ttypedef lex::lexertl::lexer<token_type> lexer_type;\n\ttypedef Lexer<lexer_type> RealLexer;\n\ttypedef Grammar<RealLexer::iterator_type> RealGrammar;\n\n\texplicit Parser(System *output)\n\t\t: tokens_()\n\t\t, grammar_(tokens_)\n\t\t, da_()\n\t\t, output_(output)\n\t{\n\t}\n\n\tbool Load(sqlite3 *db) {\n\t\treturn da_.Load(db);\n\t}\n\n\tint Parse(const boost::uuids::uuid &uuid, const char *math) {\n\t\tbase_iterator_type it = math;\n\t\tbase_iterator_type eit = math + std::strlen(math);\n\t\tCompound statement;\n\t\tbool r = lex::tokenize_and_parse(it, eit, tokens_, grammar_, statement);\n\t\tif (!r || it != eit) {\n\t\t\tstd::cerr << \"failed to parse equation: \" << it << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\treturn ProcessUuidAndStatement(uuid, statement);\n\t}\n\nprivate:\n\tint ProcessUuidAndStatement(const boost::uuids::uuid &uuid, Compound &statement)\n\t{\n\t\tExpr lhs, rhs;\n\t\tif (IsConditional(statement)) {\n\t\t\tCompound c;\n\t\t\tif (!TransformConditional(statement, lhs, c)) {\n\t\t\t\tReportInvalidLeafOfCaseSet(uuid);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\trhs = c;\n\t\t} else if (IsEquation(statement)) {\n\t\t\tlhs = statement.children[0];\n\t\t\trhs = statement.children[1];\n\t\t} else {\n\t\t\tassert(false);\n\t\t\treturn 1;\n\t\t}\n\t\tint lhs_col, lhs_row;\n\t\tif (!da_.Analyse(uuid, &lhs, &lhs_col, &lhs_row))\n\t\t\treturn 1;\n\t\tint rhs_col, rhs_row;\n\t\tif (!da_.Analyse(uuid, &rhs, &rhs_col, &rhs_row))\n\t\t\treturn 1;\n\t\tif (lhs_col != rhs_col) {\n\t\t\tstd::cerr << \"col mismatch between RHS and LHS\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (lhs_row != rhs_row) {\n\t\t\tstd::cerr << \"row mismatch between RHS and LHS\" << std::endl;\n\t\t\treturn 1;\n\t\t}\n\t\tif (lhs.which() == kExprIsCompound) {\n\t\t\tconst Compound &c = boost::get<Compound>(lhs);\n\t\t\treturn AcceptCompound(uuid, c, lhs_col, lhs_row, rhs) ? 0 : 1;\n\t\t} else if (lhs.which() == kExprIsIdentifier) {\n\t\t\toutput_->Add(uuid, Def(boost::get<Identifier>(lhs).name, lhs_col, lhs_row, rhs));\n\t\t} else {\n\t\t\tstd::cerr << \"unsupported form of equation\" << std::endl; // TODO\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool AcceptCompound(const boost::uuids::uuid &uuid, const Compound &c,\n\t\t\t\t\t\tint col, int row,\n\t\t\t\t\t\tExpr rhs, Expr mass = 1)\n\t{\n\t\tif (c.keyword == \"diff\") {\n\t\t\tassert(c.children.size() == 2);\n\t\t\tif (!IsBoundVariable(c.children[0]))\n\t\t\t\treturn false;\n\t\t\tconst Expr &e1 = c.children[1];\n\t\t\tif (e1.which() == kExprIsIdentifier) {\n\t\t\t\toutput_->Add(uuid, Ode(boost::get<Identifier>(e1).name,\n\t\t\t\t\t\t\t\t\t   col, row, rhs, mass));\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else if (c.keyword == \"times\") {\n\t\t\tif (c.children.size() == 2) {\n\t\t\t\tconst Expr &e1 = c.children[1];\n\t\t\t\tif (e1.which() == kExprIsCompound)\n\t\t\t\t\treturn AcceptCompound(uuid, boost::get<Compound>(e1),\n\t\t\t\t\t\t\t\t\t\t  col, row, rhs, c.children[0]);\n\t\t\t}\n\t\t}\n\t\tstd::cerr << \"unsupported form of equation's LHS\" << std::endl; // TODO\n\t\treturn false;\n\t}\n\n\tRealLexer tokens_;\n\tRealGrammar grammar_;\n\tDimensionAnalyzer da_;\n\tSystem *output_;\n};\n\nint Process(void *data, int argc, char **argv, char **names)\n{\n\tParser *parser = static_cast<Parser *>(data);\n\t(void)names;\n\tassert(argc == 2);\n\tassert(argv[0]);\n\tboost::uuids::uuid u;\n\tstd::memcpy(&u, argv[0], u.size());\n\treturn parser->Parse(u, argv[1]);\n}\n\n}\n\nbool AnnotateEquations(sqlite3 *db, const char *input, System *output)\n{\n\tstd::unique_ptr<Parser> parser(new Parser(output));\n\tif (!parser->Load(db))\n\t\treturn false;\n\n\tstd::ostringstream oss;\n\toss << \"SELECT * FROM \" << input;\n\tstd::string query = oss.str();\n\n\tchar *em;\n\tint e = sqlite3_exec(db, query.c_str(), Process, parser.get(), &em);\n\tif (e != SQLITE_OK) {\n\t\tif (e != SQLITE_ABORT)\n\t\t\tstd::cerr << \"failed to select \" << input\n\t\t\t\t << \": \" << e << \": \" << em << std::endl;\n\t\tsqlite3_free(em);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n}\n}\n", "meta": {"hexsha": "6a4a44ae116d63500550705d1a4efefa858af4df", "size": 10189, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/cas/equation.cc", "max_stars_repo_name": "Abhisheknishant/Flint", "max_stars_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-09-07T05:33:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T03:35:08.000Z", "max_issues_repo_path": "src/cas/equation.cc", "max_issues_repo_name": "Abhisheknishant/Flint", "max_issues_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T02:10:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T08:20:51.000Z", "max_forks_repo_path": "src/cas/equation.cc", "max_forks_repo_name": "Abhisheknishant/Flint", "max_forks_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-03-26T00:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T23:21:42.000Z", "avg_line_length": 24.8512195122, "max_line_length": 107, "alphanum_fraction": 0.6230248307, "num_tokens": 3158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.034100424239886684, "lm_q1q2_score": 0.01572086775625619}}
{"text": "/*\n * This file is part of So-bogus, a C++ sparse block matrix library and\n * Second Order Cone solver.\n *\n * Copyright 2013 Gilles Daviet <gdaviet@gmail.com>\n *\n * So-bogus 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 * So-bogus 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 So-bogus.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"MecheInterface.hpp\"\n\n#include \"FrictionProblem.hpp\"\n\n#include \"../Core/Block.impl.hpp\"\n#include \"../Core/Block.io.hpp\"\n\n#include \"../Core/BlockSolvers/GaussSeidel.hpp\"\n#include \"../Core/BlockSolvers/ProductGaussSeidel.hpp\"\n#include \"../Core/BlockSolvers/ProjectedGradient.hpp\"\n#include \"../Core/BlockSolvers/Coloring.impl.hpp\"\n\n#include \"../Core/BlockSolvers/ADMM.hpp\"\n#include \"../Extra/SecondOrder.impl.hpp\"\n\n#include \"../Core/Utils/Timer.hpp\"\n\n#include <algorithm>\n\n#ifdef BOGUS_WITH_BOOST_SERIALIZATION\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n\n#include <fstream>\n#endif\n\nnamespace bogus\n{\n\nMecheFrictionProblem::Options::Options()\n    : maxThreads(0), maxIters(0), cadouxIters(0),\n      tolerance(0), useInfinityNorm( false ),\n      algorithm( GaussSeidel ),\n      gsRegularization( 0 ), gsColoring( false ),\n      gsSkipIters( -1 ), // -1 means default\n      tryZeroAsWell( true ),\n      pgVariant( projected_gradient::SPG ),\n      admmProjStepSize( 1 ), admmFpStepSize(1.e-3)\n{\n}\n\nMecheFrictionProblem::MecheFrictionProblem()\n    : m_primal( BOGUS_NULL_PTR(PrimalFrictionProblem<3u>) ),\n      m_dual( BOGUS_NULL_PTR(DualFrictionProblem<3u>) ),\n        m_lastSolveTime( 0 ),\n        m_f( BOGUS_NULL_PTR(double) ),\n        m_w( BOGUS_NULL_PTR(double) ),\n        m_mu( BOGUS_NULL_PTR(double) ),\n        m_out( &std::cout )\n{\n}\n\nMecheFrictionProblem::~MecheFrictionProblem()\n{\n\tdestroy() ;\n}\n\nvoid MecheFrictionProblem::destroy()\n{\n\tdelete[] m_f ;\n\tm_f = BOGUS_NULL_PTR(double) ;\n\tdelete[] m_w ;\n\tm_w = BOGUS_NULL_PTR(double) ;\n\tdelete[] m_mu ;\n\tm_mu = BOGUS_NULL_PTR(double) ;\n\tdelete m_primal ;\n\tm_primal = BOGUS_NULL_PTR(PrimalFrictionProblem<3u>) ;\n\tdelete m_dual ;\n\tm_dual =  BOGUS_NULL_PTR(DualFrictionProblem<3u>) ;\n}\n\nvoid MecheFrictionProblem::ackCurrentResidual( unsigned GSIter, double err )\n{\n\tif( m_out )\n\t{\n\t\t*m_out << \"Finished iteration \" << GSIter\n\t\t         << \" with residual \" << err\n\t\t         << std::endl ;\n\t}\n\tm_callback.trigger( GSIter, err, m_timer.elapsed() );\n}\n\nvoid MecheFrictionProblem::reset ()\n{\n\tdestroy() ;\n\n\tm_primal = new PrimalFrictionProblem<3u>() ;\n\tm_lastSolveTime = 0 ;\n}\n\nvoid MecheFrictionProblem::fromPrimal (\n        unsigned int NObj, //!< number of subsystems\n        const unsigned int * ndof, //!< array of size \\a NObj, the number of degree of freedom of each subsystem\n        const double *const * MassMat, //!< array of pointers to the mass matrix of each subsystem\n        const double * f_in, //!< the constant term in \\f$ M v + f= {}^t \\! H r \\f$\n        unsigned int n_in, //!< number of contact points\n        const double * mu_in, //!< array of size \\a n giving the friction coeffs\n        const double * E_in, //!< array of size \\f$ n \\times d \\times d \\f$ giving the \\a n normals followed by the \\a n tangent vectors (and by again \\a n tangent vectors if \\a d is 3). Said otherwise, \\a E is a \\f$ (nd) \\times d \\f$ matrix, stored column-major, formed by \\a n blocks of size \\f$ d \\times d \\f$ with each block being an orthogonal matrix (the transition matrix from the world space coordinates \\f$ (x_1, x_2, x_3) \\f$ to the local coordinates \\f$ (x_N, x_{T1}, x_{T2}) \\f$\n        const double * w_in, //!< array of size \\a nd, the constant term in \\f$ u = H v + w \\f$\n        const int * const ObjA, //!< array of size \\a n, the first object involved in the \\a i-th contact (must be an internal object) (counted from 0)\n        const int * const ObjB, //!< array of size \\a n, the second object involved in the \\a i-th contact (-1 for an external object) (counted from 0)\n        const double *const HA[], //!< array of size \\a n, containing pointers to a dense, colum-major matrix of size <c> d*ndof[ObjA[i]] </c> corresponding to the H-matrix of <c> ObjA[i] </c>\n        const double *const HB[] //!< array of size \\a n, containing pointers to a dense, colum-major matrix of size <c> d*ndof[ObjA[i]] </c> corresponding to the H-matrix of <c> ObjB[i] </c> (\\c NULL for an external object)\n        )\n{\n\treset() ;\n\n\t// Copy M\n\t// We don't actually need it after having computed a factorization of M, but we keep it around\n\t// in case we want to use dumpToFile()\n\n\tm_primal->M.reserve( NObj ) ;\n\tm_primal->M.setRows( NObj, ndof ) ;\n\tm_primal->M.setCols( NObj, ndof ) ;\n\n\tfor( unsigned i = 0 ; i < NObj ; ++i )\n\t{\n\t\tm_primal->M.insertBack( i, i ) = Eigen::MatrixXd::Map( MassMat[i], ndof[i], ndof[i] ) ;\n\t}\n\tm_primal->M.finalize() ;\n\n\t// E\n\tEigen::Map< const Eigen::Matrix< double, Eigen::Dynamic, 3 > > E_flat( E_in, 3*n_in, 3 ) ;\n\n\tm_primal->E.reserve( n_in ) ;\n\tm_primal->E.setRows( n_in ) ;\n\tm_primal->E.setCols( n_in ) ;\n\tfor( unsigned i = 0 ; i < n_in ; ++i )\n\t{\n\t\tm_primal->E.insertBack( i, i ) = E_flat.block< 3,3 > ( 3*i, 0 ) ;\n\t}\n\tm_primal->E.finalize() ;\n\tm_primal->E.cacheTranspose() ;\n\n\n\t// Build H\n\n\tstd::size_t Hnnz = 0 ;\n#ifndef BOGUS_DONT_PARALLELIZE\n#pragma omp parallel for reduction( +:Hnnz )\n#endif\n\tfor( std::ptrdiff_t i = 0 ; i < (std::ptrdiff_t) n_in ; ++i )\n\t{\n\t\tHnnz += 3*ndof[ObjA[i]] ;\n\t\tif( ObjB[i] != -1 && ObjB[i] == ObjA[i] )\n\t\t{\n\t\t\tHnnz += 3*ndof[ObjB[i]] ;\n\t\t}\n\t}\n\n\tm_primal->H.setRows( n_in ) ;\n\tm_primal->H.setCols( NObj, ndof ) ;\n\tm_primal->H.reserve( 2*n_in, Hnnz ) ;\n\n#ifndef BOGUS_DONT_PARALLELIZE\n#pragma omp parallel for\n#endif\n\tfor( std::ptrdiff_t i = 0 ; i < (std::ptrdiff_t) n_in ; ++i )\n\t{\n\t\tconst Eigen::Matrix3d Et = m_primal->E.diagonal(i).transpose() ;\n\t\tif( ObjB[i] == -1 )\n\t\t{\n\t\t\tm_primal->H.insert( i, ObjA[i] ) =  Et *\n\t\t\t        Eigen::MatrixXd::Map( HA[i], 3, ndof[ ObjA[i] ] ) ;\n\t\t} else if( ObjB[i] == ObjA[i] )\n\t\t{\n\t\t\tm_primal->H.insert( i, ObjA[i] ) =  Et *\n\t\t\t        ( Eigen::MatrixXd::Map( HA[i], 3, ndof[ ObjA[i] ] ) -\n\t\t\t        Eigen::MatrixXd::Map( HB[i], 3, ndof[ ObjA[i] ] ) ) ;\n\t\t} else {\n\t\t\tm_primal->H.insert( i, ObjA[i] ) =  Et *\n\t\t\t        Eigen::MatrixXd::Map( HA[i], 3, ndof[ ObjA[i] ] ) ;\n\t\t\tm_primal->H.insert( i, ObjB[i] ) =  - Et *\n\t\t\t        Eigen::MatrixXd::Map( HB[i], 3, ndof[ ObjB[i] ] ) ;\n\t\t}\n\t}\n\tm_primal->H.finalize() ;\n\n\tm_primal->f = f_in ;\n\tm_primal->w = w_in ;\n\tm_primal->mu = mu_in ;\n\n\tm_primal->computeMInv();\n}\n\nunsigned MecheFrictionProblem::nDegreesOfFreedom() const\n{\n\treturn m_primal ? m_primal->M.rows() : 0u ;\n}\n\nunsigned MecheFrictionProblem::nContacts() const\n{\n\treturn m_primal ? m_primal->H.rowsOfBlocks() : 0u ;\n}\n\nvoid MecheFrictionProblem::computeDual( double regularization )\n{\n\tdelete m_dual ;\n\tm_dual = new DualFrictionProblem<3u>() ;\n\tm_dual->computeFrom( *m_primal );\n\n\tif( regularization > 0. )\n\t{\n\t\tm_dual->W += regularization * m_dual->W.Identity() ;\n\t}\n}\n\n\ndouble MecheFrictionProblem::solve(\n        double *r,\n        double *v,\n        int maxThreads,\n        double tol,\n        unsigned maxIters,\n        bool staticProblem,\n        double regularization,\n        bool useInfinityNorm,\n        bool useProjectedGradient,\n        unsigned cadouxIters\n                                     )\n{\n\tOptions options ;\n\tdouble problemRegularization = 0 ;\n\n\toptions.maxThreads = maxThreads ;\n\toptions.maxIters = maxIters ;\n\toptions.cadouxIters = cadouxIters ;\n\n\toptions.tolerance = tol ;\n\toptions.useInfinityNorm = useInfinityNorm ;\n\n\tif( useProjectedGradient )\n\t\toptions.algorithm = ProjectedGradient ;\n\n\tif( staticProblem ) {\n\t\tproblemRegularization = regularization ;\n\t} else {\n\t\toptions.gsRegularization = regularization ;\n\t}\n\n\treturn solve( r, v, options, staticProblem, problemRegularization ) ;\n}\n\n\ndouble MecheFrictionProblem::solve(\n        double *r,\n        double *v,\n        const Options& options,\n        bool staticProblem,\n        double problemRegularization\n        )\n{\n\tassert( m_primal ) ;\n\tconst unsigned m = m_primal->H.cols() ;\n\tconst unsigned n = m_primal->H.rowsOfBlocks() ;\n\n\t// r to local coords\n\tEigen::VectorXd r_loc = m_primal->E.transpose() * Eigen::VectorXd::Map( r, 3*n ) ;\n\n\n\tdouble res ;\n\n\n\tif( options.algorithm == ADMM || options.algorithm == DualAMA )\n\t{\n\t\t// Primal-dual solve\n\n\t\tEigen::VectorXd v_data  ;\n\t\tif( !v ) {\n\t\t\tv_data = m_primal->MInv * ( m_primal->H.transpose() * r_loc -\n\t\t\t                            Eigen::VectorXd::Map( m_primal->f, m_primal->H.cols() ) ) ;\n\t\t\tv = v_data.data() ;\n\t\t}\n\n\t\tm_timer.reset();\n\n\t\tif( options.algorithm == DualAMA )\n\t\t{\n\n\t\t\tbogus::DualAMA< bogus::PrimalFrictionProblem<3u>::HType > dama ;\n\t\t\tdama.callback().connect( *this, &MecheFrictionProblem::ackCurrentResidual ) ;\n\n\t\t\tif( options.tolerance != 0. ) dama.setTol( options.tolerance );\n\t\t\tif( options.maxIters  != 0  ) dama.setMaxIters( options.maxIters );\n\t\t\tdama.useInfinityNorm( options.useInfinityNorm );\n\n\t\t\tdama.setLineSearchIterations( 0 );\n\t\t\tdama.setFpStepSize( options.admmFpStepSize );\n\t\t\tdama.setProjStepSize( options.admmProjStepSize );\n\n\t\t\tres = m_primal->solveWith( dama, v, r_loc.data(), staticProblem ) ;\n\t\t} else {\n\t\t\tbogus::ADMM< bogus::PrimalFrictionProblem<3u>::HType > admm ;\n\t\t\tadmm.callback().connect( *this, &MecheFrictionProblem::ackCurrentResidual ) ;\n\n\t\t\tadmm.setStepSize( options.admmProjStepSize );\n\n\t\t\tif( options.tolerance != 0. ) admm.setTol( options.tolerance );\n\t\t\tif( options.maxIters  != 0  ) admm.setMaxIters( options.maxIters );\n\t\t\tadmm.useInfinityNorm( options.useInfinityNorm );\n\n\t\t\tres = m_primal->solveWith( admm, 0., v, r_loc.data() ) ;\n\t\t}\n\n\t} else {\n\n\t\tSignal< unsigned, double > callback ;\n\t\tcallback.connect( *this, &MecheFrictionProblem::ackCurrentResidual );\n\n\t\tif( options.algorithm == MatrixFreeGaussSeidel )\n\t\t{\n\t\t\tPrimalFrictionProblem< 3u >::ProductGaussSeidelType gs ;\n\t\t\tif( options.tolerance   != 0. ) gs.setTol( options.tolerance );\n\t\t\tif( options.maxIters    != 0  ) gs.setMaxIters( options.maxIters );\n\t\t\tif( options.gsSkipIters >= 0  ) gs.setSkipIters( options.gsSkipIters );\n\n\t\t\tgs.useInfinityNorm( options.useInfinityNorm ) ;\n\t\t\tgs.setMaxThreads( options.maxThreads );\n\t\t\tgs.setAutoRegularization( options.gsRegularization ) ;\n\t\t\tgs.doTryZeroAsWell( options.tryZeroAsWell );\n\n\t\t\tgs.callback().connect( callback );\n\t\t\tres = m_primal->solveWith( gs, r_loc.data(), staticProblem ) ;\n\n\t\t} else {\n\n\t\t\t// If dual has not been computed yet\n\t\t\tif( !m_dual )\n\t\t\t{\n\t\t\t\tcomputeDual( problemRegularization );\n\t\t\t}\n\n\t\t\t// Proper solving\n\n\t\t\tm_timer.reset();\n\t\t\tif( options.algorithm == ProjectedGradient ) {\n\n\t\t\t\tDualFrictionProblem< 3u >::ProjectedGradientType pg ;\n\t\t\t\tif( options.tolerance != 0. ) pg.setTol( options.tolerance );\n\t\t\t\tif( options.maxIters  != 0  ) pg.setMaxIters( options.maxIters );\n\n\t\t\t\tpg.useInfinityNorm( options.useInfinityNorm ) ;\n\t\t\t\tpg.setDefaultVariant( options.pgVariant  );\n\n\t\t\t\tif( staticProblem || options.cadouxIters == 0 )\n\t\t\t\t{\n\t\t\t\t\tpg.callback().connect( callback );\n\t\t\t\t\tres = m_dual->solveWith( pg, r_loc.data(), staticProblem ) ;\n\t\t\t\t} else {\n\t\t\t\t\tres = m_dual->solveCadoux( pg, r_loc.data(), options.cadouxIters, &callback ) ;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Setup GS parameters\n\t\t\t\tbogus::DualFrictionProblem<3u>::GaussSeidelType gs ;\n\n\t\t\t\tif( options.tolerance   != 0. ) gs.setTol( options.tolerance );\n\t\t\t\tif( options.maxIters    != 0  ) gs.setMaxIters( options.maxIters );\n\t\t\t\tif( options.gsSkipIters >= 0  ) gs.setSkipIters( options.gsSkipIters );\n\n\t\t\t\tgs.setMaxThreads( options.maxThreads );\n\t\t\t\tgs.setAutoRegularization( options.gsRegularization ) ;\n\t\t\t\tgs.useInfinityNorm( options.useInfinityNorm ) ;\n\n\t\t\t\tm_dual->undoPermutation() ;\n\n\t\t\t\tconst bool useColoring =\n\t\t\t\t        options.maxThreads != 1 && options.gsColoring ;\n\t\t\t\tgs.coloring().update( useColoring, m_dual->W );\n\n\t\t\t\tif( useColoring )\n\t\t\t\t{\n\t\t\t\t\tm_dual->applyPermutation( gs.coloring().permutation ) ;\n\t\t\t\t\tgs.coloring().resetPermutation();\n\t\t\t\t}\n\t\t\t\tm_dual->W.cacheTranspose() ;\n\n\t\t\t\tif( staticProblem || options.cadouxIters == 0 )\n\t\t\t\t{\n\t\t\t\t\tgs.doTryZeroAsWell( options.tryZeroAsWell );\n\t\t\t\t\tgs.callback().connect( callback );\n\t\t\t\t\tres = m_dual->solveWith( gs, r_loc.data(), staticProblem ) ;\n\t\t\t\t} else {\n\t\t\t\t\tgs.doTryZeroAsWell( false );\n\t\t\t\t\tres = m_dual->solveCadoux( gs, r_loc.data(), options.cadouxIters, &callback ) ;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\t// compute v\n\t\tif( v )\n\t\t{\n\t\t\tEigen::VectorXd::Map( v, m ) = m_primal->MInv * (\n\t\t\t            m_primal->H.transpose() * r_loc -\n\t\t\t            Eigen::VectorXd::Map( m_primal->f, m_primal->H.cols() ) ) ;\n\t\t}\n\t}\n\n\tm_lastSolveTime = m_timer.elapsed() ;\n\n\tif( m_out && n != 0 )\n\t{\n\t\t*m_out << \"Max coeff: \" << r_loc.lpNorm< Eigen::Infinity >() << std::endl ;\n\t}\n\n\t// r to world coords\n\tEigen::VectorXd::Map( r, 3*n ) = m_primal->E * r_loc ;\n\n\n\treturn res ;\n}\n\nvoid MecheFrictionProblem::setOutStream( std::ostream *out )\n{\n\tm_out = out ;\n}\n\n#ifdef BOGUS_WITH_BOOST_SERIALIZATION\nbool MecheFrictionProblem::dumpToFile( const char* fileName, const double * r0 ) const\n{\n\tstatic const int version = 1 ;\n\n\tif( !m_primal ) return false ;\n\n\tstd::ofstream ofs( fileName );\n\tboost::archive::binary_oarchive oa(ofs);\n\n\ttry{\n\t\toa << version ;\n\t\toa << m_primal->M << m_primal->H << m_primal->E ;\n\t\toa << boost::serialization::make_array( m_primal->f , nDegreesOfFreedom() ) ;\n\t\toa << boost::serialization::make_array( m_primal->w , 3 * nContacts() ) ;\n\t\toa << boost::serialization::make_array( m_primal->mu, nContacts() ) ;\n\t\tbool has_r0 = r0 != 0 ;\n\t\toa << has_r0 ; ;\n\t\tif( r0 )\n\t\t{\n\t\t\toa << boost::serialization::make_array( r0, 3*nContacts() ) ;\n\t\t}\n\n\t} catch (std::exception &e) {\n\t\tstd::cerr << \"Error writing MecheFrictionProblem to \"<< fileName << \":\\n> \" << e.what() << std::endl ;\n\t\treturn false ;\n\t}\n\n\treturn true ;\n}\n\nbool MecheFrictionProblem::fromFile( const char* fileName, double *& r0, bool old )\n{\n\tstd::ifstream ifs( fileName );\n\tif( !ifs.is_open() ) return false ;\n\n\treset() ;\n\n\tboost::archive::binary_iarchive ia(ifs);\n\n\ttry{\n\t\tif( old ) {\n\t\t\tbogus::SparseBlockMatrix< PrimalFrictionProblem<3>::HBlock, UNCOMPRESSED > Hold ;\n\t\t\tia >> m_primal->M >> Hold >> m_primal->E ;\n\t\t\tm_primal->H = Hold ;\n\t\t} else {\n\t\t\tint version ;\n\t\t\tia >> version ;\n\t\t\tia >> m_primal->M >> m_primal->H >> m_primal->E ;\n\t\t}\n\t} catch (std::exception &e) {\n\t\tstd::cerr << \"Error reading MecheFrictionProblem from \"<< fileName << \":\\n> \" << e.what() << std::endl ;\n\t\treturn false ;\n\t}\n\n\tm_f  = new double[ nDegreesOfFreedom() ] ;\n\tm_w  = new double[ 3 * nContacts() ] ;\n\tm_mu = new double[ nContacts() ] ;\n\n\tr0 = new double[ 3 * nContacts() ] ;\n\n\tstd::cout << fileName << \": \" << nDegreesOfFreedom() << \" dofs, \" << nContacts() << \" contacts\" << std::endl ;\n\n\ttry{\n\t\tia >> boost::serialization::make_array( m_f , nDegreesOfFreedom() ) ;\n\t\tia >> boost::serialization::make_array( m_w , 3 * nContacts() ) ;\n\t\tia >> boost::serialization::make_array( m_mu, nContacts() ) ;\n\n\t\tbool has_r0 ;\n\t\tia >> has_r0 ;\n\t\tif ( has_r0 ) {\n\t\t\tia >> boost::serialization::make_array( r0, 3*nContacts() ) ;\n\t\t} else {\n\t\t\tEigen::VectorXd::Map( r0, 3*nContacts() ).setZero() ;\n\t\t}\n\n\t} catch (std::exception &e) {\n\t\tstd::cerr << \"Error reading MecheFrictionProblem from \"<< fileName << \":\\n> \" << e.what() << std::endl ;\n\t\tdelete m_f ;\n\t\tdelete m_w ;\n\t\tdelete m_mu ;\n\t\tdelete r0 ;\n\t\tr0 = m_f = m_w = m_mu = BOGUS_NULL_PTR( double ) ;\n\t\treturn false ;\n\t}\n\n\tm_primal->f  = m_f ;\n\tm_primal->w  = m_w ;\n\tm_primal->mu = m_mu ;\n\n\tm_primal->computeMInv();\n\n\treturn true ;\n}\n\n#else\nbool MecheFrictionProblem::dumpToFile( const char*, const double* ) const\n{\n\tstd::cerr << \"MecheInterface::dumpToFile: Error, bogus compiled without serialization capabilities\" ;\n\treturn false ;\n}\nbool MecheFrictionProblem::fromFile( const char* , double *& , bool )\n{\n\tstd::cerr << \"MecheInterface::fromFile: Error, bogus compiled without serialization capabilities\" ;\n\treturn false ;\n}\n#endif\n\n}\n\n\n", "meta": {"hexsha": "817cf6127c19a6c76ff12fe389331ea87b0f1fec", "size": 16294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/src/Interfaces/MecheInterface.cpp", "max_stars_repo_name": "sjokic/WallDestruction", "max_stars_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "include/src/Interfaces/MecheInterface.cpp", "max_issues_repo_name": "sjokic/WallDestruction", "max_issues_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/src/Interfaces/MecheInterface.cpp", "max_forks_repo_name": "sjokic/WallDestruction", "max_forks_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.679417122, "max_line_length": 490, "alphanum_fraction": 0.6483981834, "num_tokens": 4918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.034618840457683646, "lm_q1q2_score": 0.015691399601999508}}
{"text": "// Copyright 2004, 2005 The Trustees of Indiana University.\r\n\r\n// Use, modification and distribution is subject to the Boost Software\r\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Nick Edmonds\r\n//           Andrew Lumsdaine\r\n#ifndef BOOST_GRAPH_DISTRIBUTED_RMAT_GENERATOR_HPP\r\n#define BOOST_GRAPH_DISTRIBUTED_RMAT_GENERATOR_HPP\r\n\r\n#ifndef BOOST_GRAPH_USE_MPI\r\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\r\n#endif\r\n\r\n#include <boost/graph/parallel/algorithm.hpp>\r\n#include <boost/graph/parallel/process_group.hpp>\r\n#include <math.h>\r\n\r\nnamespace boost {\r\n\r\n  // Memory-scalable (amount of memory required will scale down\r\n  // linearly as the number of processes increases) generator, which\r\n  // requires an MPI process group.  Run-time is slightly worse than\r\n  // the unique rmat generator.  Edge list generated is sorted and\r\n  // unique.\r\n  template<typename ProcessGroup, typename Distribution, \r\n           typename RandomGenerator, typename Graph>\r\n  class scalable_rmat_iterator\r\n  {\r\n      typedef typename graph_traits<Graph>::directed_category directed_category;\r\n      typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\r\n      typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\r\n\r\n  public:\r\n      typedef std::input_iterator_tag iterator_category;\r\n      typedef std::pair<vertices_size_type, vertices_size_type> value_type;\r\n      typedef const value_type& reference;\r\n      typedef const value_type* pointer;\r\n      typedef void difference_type;\r\n\r\n      // No argument constructor, set to terminating condition\r\n      scalable_rmat_iterator()\r\n        : gen(), done(true)\r\n      { }\r\n\r\n      // Initialize for edge generation\r\n      scalable_rmat_iterator(ProcessGroup pg, Distribution distrib,\r\n                             RandomGenerator& gen, vertices_size_type n, \r\n                             edges_size_type m, double a, double b, double c, \r\n                             double d, bool permute_vertices = true)\r\n          : gen(), done(false)\r\n      {\r\n          assert(a + b + c + d == 1);\r\n          int id = process_id(pg);\r\n\r\n          this->gen.reset(new uniform_01<RandomGenerator>(gen));\r\n\r\n          std::vector<vertices_size_type> vertexPermutation;\r\n          if (permute_vertices) \r\n              generate_permutation_vector(gen, vertexPermutation, n);\r\n\r\n          int SCALE = int(floor(log(double(n))/log(2.)));\r\n          boost::uniform_01<RandomGenerator> prob(gen);\r\n      \r\n          std::map<value_type, bool> edge_map;\r\n\r\n          edges_size_type generated = 0, local_edges = 0;\r\n          do {\r\n              edges_size_type tossed = 0;\r\n              do {\r\n                  vertices_size_type u, v;\r\n                  boost::tie(u, v) = generate_edge(this->gen, n, SCALE, a, b, c, d);\r\n\r\n                  if (permute_vertices) {\r\n                      u = vertexPermutation[u];\r\n                      v = vertexPermutation[v];\r\n                  }\r\n\r\n                  // Lowest vertex number always comes first (this\r\n                  // means we don't have to worry about i->j and j->i\r\n                  // being in the edge list)\r\n                  if (u > v && is_same<directed_category, undirected_tag>::value)\r\n                      std::swap(u, v);\r\n\r\n                  if (distrib(u) == id || distrib(v) == id) {\r\n                      if (edge_map.find(std::make_pair(u, v)) == edge_map.end()) {\r\n                          edge_map[std::make_pair(u, v)] = true;\r\n                          local_edges++;\r\n                      } else {\r\n                          tossed++;\r\n\r\n                          // special case - if both u and v are on same\r\n                          // proc, ++ twice, since we divide by two (to\r\n                          // cover the two process case)\r\n                          if (distrib(u) == id && distrib(v) == id)\r\n                              tossed++;\r\n                      }\r\n                  }\r\n                  generated++;\r\n\r\n              } while (generated < m);\r\n              tossed = all_reduce(pg, tossed, boost::parallel::sum<vertices_size_type>());\r\n              generated -= (tossed / 2);\r\n          } while (generated < m);\r\n          // NGE - Asking for more than n^2 edges will result in an infinite loop here\r\n          //       Asking for a value too close to n^2 edges may as well\r\n\r\n          values.reserve(local_edges);\r\n          typename std::map<value_type, bool>::reverse_iterator em_end = edge_map.rend();\r\n          for (typename std::map<value_type, bool>::reverse_iterator em_i = edge_map.rbegin();\r\n               em_i != em_end ;\r\n               ++em_i) {\r\n              values.push_back(em_i->first);\r\n          }\r\n\r\n          current = values.back();\r\n          values.pop_back();\r\n      }\r\n\r\n      reference operator*() const { return current; }\r\n      pointer operator->() const { return &current; }\r\n    \r\n      scalable_rmat_iterator& operator++()\r\n      {\r\n          if (!values.empty()) {\r\n              current = values.back();\r\n              values.pop_back();\r\n          } else \r\n              done = true;\r\n\r\n          return *this;\r\n      }\r\n\r\n      scalable_rmat_iterator operator++(int)\r\n      {\r\n          scalable_rmat_iterator temp(*this);\r\n          ++(*this);\r\n          return temp;\r\n      }\r\n\r\n      bool operator==(const scalable_rmat_iterator& other) const\r\n      {\r\n          return values.empty() && other.values.empty() && done && other.done;\r\n      }\r\n\r\n      bool operator!=(const scalable_rmat_iterator& other) const\r\n      { return !(*this == other); }\r\n\r\n  private:\r\n\r\n      // Parameters\r\n      shared_ptr<uniform_01<RandomGenerator> > gen;\r\n\r\n      // Internal data structures\r\n      std::vector<value_type> values;\r\n      value_type              current;\r\n      bool                    done;\r\n  };\r\n\r\n} // end namespace boost\r\n\r\n#endif // BOOST_GRAPH_DISTRIBUTED_RMAT_GENERATOR_HPP\r\n", "meta": {"hexsha": "ffbf40cce94d02fe6c7003029f534d03fdf7efd9", "size": 6042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/graph/distributed/rmat_graph_generator.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T01:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-26T07:38:43.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/graph/distributed/rmat_graph_generator.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T01:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T01:56:28.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/graph/distributed/rmat_graph_generator.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": 36.8414634146, "max_line_length": 102, "alphanum_fraction": 0.5571002979, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.031618767610839704, "lm_q1q2_score": 0.015685875507212545}}
{"text": "/*\n * Copyright 2012 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#include \"decimal.hpp\"\n#include \"assert.hpp\"\n#include \"checked_arithmetic.hpp\"\n#include \"decimal_exceptions.hpp\"\n#include \"exception.hpp\"\n#include \"num_digits.hpp\"\n#include <boost/numeric/conversion/cast.hpp>\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <cctype>\n#include <limits>\n#include <numeric>\n#include <vector>\n\nusing boost::numeric_cast;\nusing std::accumulate;\nusing std::find;\nusing std::numeric_limits;\nusing std::max_element;\nusing std::max;\nusing std::pow;\nusing std::vector;\n\nnamespace jewel\n{\n\nnamespace\n{\n\n    /*\n     * Hack: using this instead of static_cast because there appears to be a\n     * bug in GCC 4.6.1 (at least on MinGW on Windows) when casting to\n     * long long using static_cast or implicit cast.\n     */\n    template <typename Target>\n    struct Converter\n    {\n        template <typename Source>\n        static Target convert(Source p_source)\n        {\n            return p_source;\n        }\n    };\n\n    /*\n     * Specialize for conversions to long long to use boost::numeric cast to\n     * avoid the bug.\n     *\n     * NOTE: Don't rely on the exceptions thrown by boost::numeric_cast.\n     * If boost::numeric_cast is throws here, there's something wrong\n     * with the program!\n     */\n    template <>\n    struct Converter<long long>\n    {\n        template <typename Source>\n        static long long convert(Source p_source)\n        {\n            return numeric_cast<long long>(p_source);\n        }\n    };\n\n    template <typename Target, typename Source>\n    Target num_cast(Source p_source);\n\n    template <typename Target, typename Source>\n    inline\n    Target num_cast(Source p_source)\n    {\n        return Converter<Target>::template convert(p_source);\n    }\n\n}  // end anonymous namespace\n\n\n/*\n * NOTE: Don't rely on the exceptions thrown by boost::numeric_cast.\n * If boost::numeric_cast is throws here, there's something wrong\n * with the program!\n */\n#ifndef NDEBUG\n#   define JEWEL_NUMERIC_CAST numeric_cast\n#else\n#   define JEWEL_NUMERIC_CAST num_cast      // faster\n#endif\n\n\n// initialize static data members\n\nsize_t const\nDecimal::s_max_places = NumDigits::num_digits\n(   numeric_limits<int_type>::min()\n);\n\nDecimal const\nDecimal::s_maximum = Decimal(numeric_limits<int_type>::max(), 0);\n\nDecimal const\nDecimal::s_minimum = Decimal(numeric_limits<int_type>::min(), 0);\n\n\n// static member functions\n\n\nvoid Decimal::co_normalize(Decimal& x, Decimal& y)\n{\n    if (x.m_places == y.m_places)\n    {\n        // do nothing\n    }\n    else if (x.m_places < y.m_places)\n    {\n        if (x.rescale(y.m_places) != 0)\n        {\n            JEWEL_THROW\n            (   DecimalRangeException,\n                \"Unsafe attempt to set fractional precision in course \"\n                \"of co-normalization attempt.\"\n            );\n        }\n    }\n    else\n    {\n        JEWEL_ASSERT (y.m_places < x.m_places);\n        if (y.rescale(x.m_places) != 0)\n        {\n            JEWEL_THROW\n            (   DecimalRangeException,\n                \"Unsafe attempt to set fractional precision in course \"\n                \"of co-normalization attempt.\"\n            );\n        }\n    }\n    return;\n}\n\n\n// some member functions\n\n\nDecimal::Decimal(): m_places(0), m_intval(0)\n{\n}\n\nDecimal::Decimal(int_type p_intval, places_type p_places):\n    m_places(p_places),\n    m_intval(p_intval)\n{\n    JEWEL_ASSERT (s_max_places == maximum_precision());\n    if (m_places > s_max_places)\n    {\n        // There is no point setting m_intval and m_places to 0 (or any other\n        // other valid value) here, since the Decimal instance is not going\n        // to be created anyway - nothing will be able to refer to it after\n        // this exception is thrown.\n        JEWEL_THROW\n        (   DecimalRangeException,\n            \"Attempt to construct Decimal with precision greater\"\n            \" than maximum precision.\"\n        );\n    }\n}\n\nvoid\nDecimal::rationalize(places_type min_places)\n{\n    JEWEL_ASSERT (s_base > 0);\n    JEWEL_ASSERT (!remainder_is_unsafe(m_intval, s_base));\n    while ((m_places > min_places) && (m_intval % s_base == 0))\n    {\n        JEWEL_ASSERT (!division_is_unsafe(m_intval, s_base));\n        m_intval /= s_base;\n        JEWEL_ASSERT (m_places > 0);\n        --m_places;\n    }\n    return;\n}\n\nint Decimal::rescale(places_type p_places)\n{\n    #ifndef NDEBUG\n        places_type const DEBUGVARIABLE_orig_places = m_places;\n        int_type const DEBUGVARIABLE_orig_intval = m_intval;\n    #endif\n\n    if (m_places == p_places)\n    {\n        return 0;\n    }\n\n    // remember sign\n    bool const is_positive = (m_intval > 0);\n    #ifndef NDEBUG\n        bool const is_zero = (m_intval == 0);\n        bool const is_negative = (m_intval < 0);\n    #endif\n\n    if (m_places < p_places)\n    {   \n        if (p_places > s_max_places)\n        {\n            JEWEL_ASSERT (m_places == DEBUGVARIABLE_orig_places);\n            JEWEL_ASSERT (m_intval == DEBUGVARIABLE_orig_intval);\n            return 1;\n        }\n        JEWEL_ASSERT (p_places <= s_max_places);\n        // This should never cause overflow, as p_places is never greater\n        // than s_max_places, and s_base raised to a number equal to or\n        // greater than p_places will always be less than\n        // numeric_limits<int_type>::max(), given that s_max_places is\n        // equal to the number of digits in numeric_limits<int_type>::min().\n        JEWEL_ASSERT (!subtraction_is_unsafe(p_places, m_places));\n        int_type multiplier = JEWEL_NUMERIC_CAST<int_type>\n        (   pow(s_base, p_places - m_places)\n        );\n\n        if (multiplication_is_unsafe(m_intval, multiplier))\n        {\n            JEWEL_ASSERT (m_places == DEBUGVARIABLE_orig_places);\n            JEWEL_ASSERT (m_intval == DEBUGVARIABLE_orig_intval);\n            return 1;\n         }\n        m_intval *= multiplier;\n    }\n    else\n    {\n        JEWEL_ASSERT (p_places < m_places);\n\n        // truncate all but one of the required places\n        JEWEL_ASSERT (m_places > 0);\n        for (unsigned int j = m_places - 1; j != p_places; --j)\n        {\n            JEWEL_ASSERT (!division_is_unsafe(m_intval, s_base));\n            m_intval /= s_base;\n        }\n\n        // with one more place still to eliminate, we calculate\n        // whether rounding is required\n        JEWEL_ASSERT (!remainder_is_unsafe(m_intval, s_base));\n        bool remainder =\n        (   std::abs(m_intval % s_base) >=\n            s_rounding_threshold\n        );\n\n        // now remove the remaining place\n        JEWEL_ASSERT (!division_is_unsafe(m_intval, s_base));\n        JEWEL_ASSERT (s_base > 1);\n        m_intval /= s_base;\n        JEWEL_ASSERT (m_intval < numeric_limits<int_type>::max());\n        JEWEL_ASSERT (m_intval > numeric_limits<int_type>::min());\n\n        // and add rounding if required\n        if (remainder)\n        {\n            if (is_positive)\n            {\n                JEWEL_ASSERT\n                (   !addition_is_unsafe(m_intval, static_cast<int_type>(1))\n                );\n                ++m_intval;\n            }\n            else\n            {\n                JEWEL_ASSERT (is_negative);\n                JEWEL_ASSERT (!is_zero);\n                JEWEL_ASSERT\n                (   !subtraction_is_unsafe(m_intval, static_cast<int_type>(1))\n                );\n                --m_intval;\n            }\n        }\n    }\n    m_places = p_places;\n    return 0;\n}\n\n\nDecimal::int_type\nDecimal::implicit_divisor() const\n{   \n    static bool calculated_already = false;\n    static vector<int_type> divisor_lookup(1, 1);\n    while (!calculated_already)\n    {\n        while (divisor_lookup.size() != s_max_places)\n        {\n            JEWEL_ASSERT (!divisor_lookup.empty());\n            JEWEL_ASSERT\n            (   !multiplication_is_unsafe(divisor_lookup.back(), s_base)\n            );\n            divisor_lookup.push_back(divisor_lookup.back() * s_base);\n        }\n        calculated_already = true;\n    }\n    JEWEL_ASSERT (m_places < divisor_lookup.size());\n    return divisor_lookup[m_places];\n}\n\n\n\n// operators\n\nDecimal const& Decimal::operator++()\n{\n    #ifndef NDEBUG\n        places_type const benchmark_places = m_places;\n        Decimal const orig = *this;\n    #endif\n    if (addition_is_unsafe(m_intval, implicit_divisor()))\n    {\n        JEWEL_ASSERT (*this == orig);\n        JEWEL_THROW\n        (   DecimalIncrementationException,\n            \"Incrementation may cause overflow.\"\n        );\n    }\n    m_intval += implicit_divisor();\n    JEWEL_ASSERT (m_places >= benchmark_places);\n    return *this;\n}\n\nDecimal Decimal::operator++(int)\n{\n    Decimal const ret(*this);\n    ++*this;\n    return ret;\n}\n\nDecimal const& Decimal::operator--()\n{\n    #ifndef NDEBUG\n        places_type const benchmark_places = m_places;\n        Decimal const orig = *this;\n    #endif\n    if (subtraction_is_unsafe(m_intval, implicit_divisor()))\n    {\n        JEWEL_ASSERT (*this == orig);\n        JEWEL_THROW\n        (   DecimalDecrementationException,\n            \"Decrementation may cause \"\n            \"overflow.\"\n        );\n    }\n    m_intval -= implicit_divisor();\n    JEWEL_ASSERT (m_places >= benchmark_places);\n    return *this;\n}\n\nDecimal Decimal::operator--(int)\n{\n    Decimal const ret(*this);\n    --*this;\n    return ret;\n}\n\nDecimal& Decimal::operator+=(Decimal rhs)\n{\n    #ifndef NDEBUG\n        places_type const benchmark_places = max(m_places, rhs.m_places);\n    #endif\n    Decimal orig = *this;\n    co_normalize(*this, rhs);\n    if (addition_is_unsafe(m_intval, rhs.m_intval))\n    {\n        *this = orig;\n        JEWEL_THROW(DecimalAdditionException, \"Addition may cause overflow.\");\n    }\n    m_intval += rhs.m_intval;\n    JEWEL_ASSERT (m_places >= benchmark_places);\n    return *this;\n}\n\n\n\nDecimal& Decimal::operator-=(Decimal rhs)\n{\n    #ifndef NDEBUG\n        places_type const benchmark_places = max(m_places, rhs.m_places);\n    #endif\n    Decimal orig = *this;\n    co_normalize(*this, rhs);\n    if (subtraction_is_unsafe(m_intval, rhs.m_intval))\n    {\n        *this = orig;\n        JEWEL_THROW\n        (   DecimalSubtractionException,\n            \"Subtraction may cause overflow.\"\n        );\n    }\n    m_intval -= rhs.m_intval;\n    JEWEL_ASSERT (m_places >= benchmark_places);\n    return *this;\n}\n\n\nDecimal& Decimal::operator*=(Decimal rhs)\n{\n    Decimal orig = *this;\n    rationalize();\n    rhs.rationalize();\n\n    // Rule out problematic smallest Decimal\n    JEWEL_ASSERT (minimum() == Decimal(numeric_limits<int_type>::min(), 0));\n    JEWEL_ASSERT (maximum() == Decimal(numeric_limits<int_type>::max(), 0));\n    if (*this == minimum() || rhs == minimum())\n    {\n        JEWEL_ASSERT (*this == orig);\n        JEWEL_THROW\n        (   DecimalMultiplicationException,\n            \"Cannot multiply smallest possible \"\n            \"Decimal safely.\"\n        );\n    }\n\n    // Make absolute and remember signs\n    bool const signs_differ =\n    (   (m_intval < 0 && rhs.m_intval > 0) ||\n        (m_intval > 0 && rhs.m_intval < 0)\n    );\n    if (m_intval < 0)\n    {\n        JEWEL_ASSERT\n        (   !multiplication_is_unsafe(m_intval, static_cast<int_type>(-1))\n        );\n        m_intval *= -1;\n    }\n    if (rhs.m_intval < 0)\n    {\n        JEWEL_ASSERT\n        (   !multiplication_is_unsafe(rhs.m_intval, static_cast<int_type>(-1))\n        );\n        rhs.m_intval *= -1;\n    }\n\n    // Do \"unchecked multiply\" if we can\n    JEWEL_ASSERT (m_intval >= 0 && rhs.m_intval >= 0);    \n    if (!multiplication_is_unsafe(m_intval, rhs.m_intval))\n    {\n        JEWEL_ASSERT (!addition_is_unsafe(m_places, rhs.m_places));\n        m_intval *= rhs.m_intval;\n        m_places += rhs.m_places;\n        while (m_places > s_max_places)\n        {\n            JEWEL_ASSERT (m_places > 0);\n            #ifndef NDEBUG\n                int const check = rescale(m_places - 1);\n                JEWEL_ASSERT (check == 0);\n            #else\n                rescale(m_places - 1);\n            #endif\n        }\n        if (signs_differ)\n        {\n            JEWEL_ASSERT (m_intval != numeric_limits<int_type>::min());\n            JEWEL_ASSERT\n            (   !multiplication_is_unsafe\n                (   m_intval,\n                    static_cast<int_type>(-1)\n                )\n            );\n            m_intval *= -1;\n        }\n        rationalize();\n        return *this;\n    }\n\n    *this = orig;\n    JEWEL_THROW(DecimalMultiplicationException, \"Unsafe multiplication.\");\n    JEWEL_HARD_ASSERT (false);  // Execution should never reach here.\n    return *this;    // Silence compiler re. return from non-void function.\n\n}\n\n\nDecimal& Decimal::operator/=(Decimal rhs)\n{\n    // Record original dividend and divisor\n    Decimal const orig = *this;\n\n    rhs.rationalize();\n\n    // Capture division by zero\n    if (rhs.m_intval == 0)\n    {\n        JEWEL_ASSERT (*this == orig);\n        JEWEL_THROW(DecimalDivisionByZeroException, \"Division by zero.\");\n    }\n    \n    // To prevent complications\n    if ( m_intval == numeric_limits<int_type>::min() ||\n      rhs.m_intval == numeric_limits<int_type>::min() )\n    {\n        JEWEL_ASSERT (*this == orig);\n        JEWEL_THROW\n        (   DecimalDivisionException,\n            \"Smallest possible Decimal cannot \"\n            \"feature in division operation.\"\n        );\n    }\n    JEWEL_ASSERT (NumDigits::num_digits(rhs.m_intval) <= maximum_precision());\n    if (NumDigits::num_digits(rhs.m_intval) == maximum_precision())\n    {\n        JEWEL_ASSERT (*this == orig);\n        JEWEL_THROW\n        (   DecimalDivisionException,\n            \"Dividend has a number of significant\"\n             \"digits that is greater than or equal to the return value of \"\n            \"Decimal::maximum_precision(); as a result, division cannot be \"\n            \"performed safely.\"\n        );\n    }\n    \n    // Remember required sign of product\n    bool const diff_signs =\n    (   ( m_intval > 0 && rhs.m_intval < 0) ||\n        ( m_intval < 0 && rhs.m_intval > 0)\n    );\n\n    // Make absolute\n    JEWEL_ASSERT\n    (   !multiplication_is_unsafe(m_intval, static_cast<int_type>(-1))\n    );\n    JEWEL_ASSERT\n    (   !multiplication_is_unsafe(rhs.m_intval, static_cast<int_type>(-1))\n    );\n    if (m_intval < 0) m_intval *= -1;\n    if (rhs.m_intval < 0) rhs.m_intval *= -1;\n\n    // Rescale the dividend as high as we can\n    while (m_places < rhs.m_places && rescale(m_places + 1) == 0)\n    {\n    }\n    if (rhs.m_places > m_places)\n    {\n        // We can't rescale high enough to proceed, so reset and throw\n        *this = orig;\n        JEWEL_THROW(DecimalDivisionException, \"Unsafe division.\");\n    }\n\n    // Proceed with basic division algorithm\n    JEWEL_ASSERT (m_places >= rhs.m_places);\n    JEWEL_ASSERT (!subtraction_is_unsafe(m_places, rhs.m_places));\n    m_places -= rhs.m_places;\n    JEWEL_ASSERT (rhs.m_intval != 0);\n    JEWEL_ASSERT (m_intval != numeric_limits<int_type>::min());\n    JEWEL_ASSERT (!remainder_is_unsafe(m_intval, rhs.m_intval));\n    int_type remainder = m_intval % rhs.m_intval;\n    JEWEL_ASSERT (!division_is_unsafe(m_intval, rhs.m_intval));\n    m_intval /= rhs.m_intval;\n\n    // Deal with any remainder using \"long division\"\n    while (remainder != 0 && rescale(m_places + 1) == 0)\n    {\n        JEWEL_ASSERT (!multiplication_is_unsafe(remainder, s_base));\n\n        /*\n         * Previously this commented-out section of code dealt\n         * with the case where it was unsafe to multiply remainder\n         * and s_base. However, this is now dealt with by the fact that\n         * an exception is thrown if the number of significant digits\n         * in the dividend is equal to Decimal::maximum_precision().\n         * This makes for a more straightforward API, since the\n         * below code caused loss of precision under difficult-to-explain\n         * circumstances.\n        if (multiplication_is_unsafe(remainder, s_base))\n        {\n            // Then we can't proceed with ordinary \"long division\" safely,\n            // and need to \"scale down\" first\n\n            bool add_rounding_right = false;\n            if (rhs.m_intval % s_base >= s_rounding_threshold)\n            {\n                add_rounding_right = true;\n            }\n            rhs.m_intval /= s_base;\n            if (add_rounding_right)\n            {\n                JEWEL_ASSERT (!addition_is_unsafe(rhs.m_intval,\n                  JEWEL_NUMERIC_CAST<int_type>(1)));\n                ++(rhs.m_intval);\n            }\n\n            // Redo the Decimal division on a \"safe scale\"\n            Decimal lhs = orig;\n            if (lhs.m_intval < 0) lhs.m_intval *= -1;\n            JEWEL_ASSERT (rhs.m_intval >= 0);\n            lhs /= rhs;\n            bool add_rounding_left = false;\n            if (lhs.m_intval % s_base >= s_rounding_threshold)\n            {\n                add_rounding_left = true;    \n            }\n            lhs.m_intval /= s_base;\n            if (add_rounding_left)\n            {\n                JEWEL_ASSERT (!addition_is_unsafe(lhs.m_intval,\n                  JEWEL_NUMERIC_CAST<int_type>(1)));\n                ++(lhs.m_intval);\n            }\n            if (diff_signs) lhs.m_intval *= -1;\n            *this = lhs;\n\n            return *this;\n        }\n        */\n\n        // It's safe to proceed with ordinary \"long division\"\n        JEWEL_ASSERT (!multiplication_is_unsafe(remainder, s_base));\n        remainder *= s_base;\n\n        JEWEL_ASSERT (rhs.m_intval > 0);\n        JEWEL_ASSERT (!remainder_is_unsafe(remainder, rhs.m_intval));\n        int_type const temp_remainder = remainder % rhs.m_intval;\n        JEWEL_ASSERT (!division_is_unsafe(remainder, rhs.m_intval));\n        m_intval += remainder / rhs.m_intval;\n        remainder = temp_remainder;\n    }\n\n    // Do rounding if required\n    JEWEL_ASSERT (rhs.m_intval >= remainder);\n    JEWEL_ASSERT (!subtraction_is_unsafe(rhs.m_intval, remainder));\n    if (rhs.m_intval - remainder <= remainder)\n    {\n        // If the required rounding would be unsafe, we throw\n        if (addition_is_unsafe(m_intval, JEWEL_NUMERIC_CAST<int_type>(1)))\n        {\n            *this = orig;\n            JEWEL_THROW(DecimalDivisionException, \"Unsafe division.\");\n        }\n        // Do the rounding, it's safe\n        ++m_intval;\n    }\n\n    // Put the correct sign\n    JEWEL_ASSERT (m_intval >= 0);\n    JEWEL_ASSERT\n    (   !multiplication_is_unsafe(m_intval, static_cast<int_type>(-1))\n    );\n    if (diff_signs) m_intval *= -1;\n    rationalize();\n    return *this;\n}\n\n\nbool Decimal::operator<(Decimal rhs) const\n{   \n    Decimal lhs = *this;\n    lhs.rationalize();\n    rhs.rationalize();\n    if (lhs.m_places == rhs.m_places)\n    {\n        return lhs.m_intval < rhs.m_intval;\n    }\n    bool const left_is_longer = (lhs.m_places > rhs.m_places);\n    Decimal const *const shorter = (left_is_longer? &rhs: &lhs);\n    Decimal const *const longer = (left_is_longer? &lhs: &rhs);\n    places_type const target_places = shorter->m_places;\n    int_type longers_revised_intval = longer->m_intval;\n    int_type const shorters_intval = shorter->m_intval;\n    bool const longer_is_negative = (longers_revised_intval < 0);\n    for\n    (   places_type longers_places = longer->m_places;\n        longers_places != target_places;\n        --longers_places\n    )\n    {\n        JEWEL_ASSERT (s_base > 0);\n        JEWEL_ASSERT (!division_is_unsafe(longers_revised_intval, s_base));\n        longers_revised_intval /= s_base;\n        JEWEL_ASSERT (longers_places > 0);\n    }\n    bool longer_is_smaller =\n    (   longer_is_negative?\n        (longers_revised_intval <= shorters_intval):\n        (longers_revised_intval < shorters_intval)\n    );\n    return ( &lhs == (longer_is_smaller? longer: shorter) );\n}\n\n\nbool Decimal::operator==(Decimal rhs) const\n{\n    Decimal temp_lhs = *this;\n    temp_lhs.rationalize();\n    rhs.rationalize();\n    return\n    (   temp_lhs.m_intval == rhs.m_intval &&\n        temp_lhs.m_places == rhs.m_places\n    );\n}\n\n\nDecimal round(Decimal const& x, Decimal::places_type decimal_places)\n{\n    Decimal ret = x;\n    if (ret.rescale(decimal_places) != 0)\n    {   \n        JEWEL_THROW\n        (   DecimalRangeException,\n            \"Decimal number cannot safely be rounded to \"\n            \"this number of places.\"\n        );\n    }\n    return ret;\n}\n\n\nDecimal operator-(Decimal const& d)\n{\n    typedef Decimal::int_type int_type;\n    if (d.m_intval == numeric_limits<int_type>::min())\n    {\n        JEWEL_THROW\n        (   DecimalUnaryMinusException,\n            \"Unsafe arithmetic operation (unary minus).\"\n        );\n    }\n    JEWEL_ASSERT (d.m_intval != numeric_limits<int_type>::min());\n    Decimal ret = d;\n    JEWEL_ASSERT\n    (   !multiplication_is_unsafe(ret.m_intval, static_cast<int_type>(-1))\n    );\n    ret.m_intval *= -1;\n    return ret;\n}\n\n\n\n}  // namespace jewel\n", "meta": {"hexsha": "6dac0ca647eb56be530149205ce8fe537556bdfe", "size": 21225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/decimal.cpp", "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": "src/decimal.cpp", "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": "src/decimal.cpp", "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": 28.4136546185, "max_line_length": 78, "alphanum_fraction": 0.6055123675, "num_tokens": 5215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.042722199831789216, "lm_q1q2_score": 0.01566151997143823}}
{"text": "#include <iostream>\n#include <cmath>\n#include <cpp_gala/integrate/integrate.h>\n#include <cpp_gala/simulation/simulation.h>\n#include <cpp_gala/utils.h>\n\n#include <boost/numeric/odeint.hpp>\n#include <cpp_gala/extern/nested_range_algebra.hpp>\n#include <cpp_gala/extern/vector_vector_resize.hpp>\n\n// TODO: remove! just for printing...s\n#include <pybind11/pybind11.h>\nnamespace py = pybind11;\nusing namespace pybind11::literals;\n\nusing namespace boost::numeric;\n\nusing namespace gala::utils;\nusing namespace gala::integrate;\n\n\n/* ------------------------------------------------------------------------------------------------\n    Base class\n\n    TODO:\n    - Redundant methods below! integrate/integrate_save_all...\n\n*/\nBaseIntegrator::BaseIntegrator(gala::simulation::Simulation &sim) {\n    this->sim = &sim;\n}\n\nvoid BaseIntegrator::integrate(const vector_1d t, double *result_w) {\n    int i, j, k, idx, ps_ndim = 2 * this->sim->n_dim;\n    int ntimes = t.size();\n    int nparticles = this->sim->get_n_particles();\n\n    // Call any custom setup needed before starting to step the integrator:\n    this->setup_integrate(t);\n    this->sim->step_callback(0, t[0]);\n\n    for (int n=1; n < ntimes; n++) {\n        this->step(t[n-1], t[n] - t[n-1]);\n        this->sim->step_callback(n, t[n]);\n    }\n\n    // Store the w vector at the final timestep\n    k = 0;\n    for (auto &pair : this->sim->particles) {\n        for (i=0; i < pair.second.n_particles; i++) {\n            for (j=0; j < ps_ndim; j++) {\n                idx = i2d(k, j, nparticles, ps_ndim);\n                result_w[idx] = pair.second.w[i][j];\n            }\n            k++;\n        }\n    }\n}\n\nvoid BaseIntegrator::integrate_save_all(const vector_1d t, double *result_w) {\n    int i, j, k, idx, ps_ndim = 2 * this->sim->n_dim;\n    int ntimes = t.size();\n    int nparticles = this->sim->get_n_particles();\n\n    // Store the initial values in the first block of the result array:\n    k = 0;\n    for (auto &pair : this->sim->particles) {\n        for (i=0; i < pair.second.n_particles; i++) {\n            for (j=0; j < ps_ndim; j++)\n                result_w[j + ps_ndim * k] = pair.second.w[i][j];\n            k++;\n        }\n    }\n\n    // Call any custom setup needed before starting to step the integrator:\n    this->setup_integrate(t);\n    this->sim->step_callback(0, t[0]);\n\n    for (int n=1; n < ntimes; n++) {\n        this->step(t[n-1], t[n] - t[n-1]);\n        this->sim->step_callback(n, t[n]);\n\n        // Store the w vector at this timestep\n        k = 0;\n        for (auto &pair : this->sim->particles) {\n            for (i=0; i < pair.second.n_particles; i++) {\n                for (j=0; j < ps_ndim; j++) {\n                    idx = i3d(n, k, j, ntimes, nparticles, ps_ndim);\n                    result_w[idx] = pair.second.w[i][j];\n                }\n                k++;\n            }\n        }\n    }\n}\n\n// vector_2d BaseIntegrator::integrate(const vector_1d t) {\n//     // Call any custom setup needed before starting to step the integrator:\n//     this->setup_integrate(t);\n\n//     for (int n=1; n < t.size(); n++)\n//         this->step(t[n-1], t[n] - t[n-1]);\n\n//     return this->sim->state_w;\n// }\n\n// vector_3d BaseIntegrator::integrate_save_all(const vector_1d t) {\n//     // The return array:\n//     vector_3d result_w;\n\n//     // Store the initial values in the first block of the result array:\n//     result_w.push_back(this->sim->state_w);\n\n//     // Call any custom setup needed before starting to step the integrator:\n//     this->setup_integrate(t);\n\n//     for (int n=1; n < t.size(); n++) {\n//         this->step(t[n-1], t[n] - t[n-1]);\n\n//         // Store the w vector at this timestep\n//         result_w.push_back(this->sim->state_w);\n//     }\n\n//     return result_w;\n// }\n\n// These are the methods that are overridden by subclasses\n// Note: If I don't include these, I get a \"Symbol not found\" error on import of cpp_gala._integrate\nvoid BaseIntegrator::setup_integrate(const vector_1d &t) {\n    if (t.size() < 2)\n        throw std::runtime_error(\"Input time array must have > 1 element.\");\n\n    this->tmp_w = this->sim->get_state_w();\n    this->tmp_dwdt = this->sim->get_dwdt(t[0]);\n}\n\nvoid BaseIntegrator::step(const double t, const double dt) { }\n\n\n/* ------------------------------------------------------------------------------------------------\n    Leapfrog\n*/\nLeapfrogIntegrator::LeapfrogIntegrator(gala::simulation::Simulation &sim)\n: BaseIntegrator(sim) {\n    for (int i=0; i < sim.get_n_particles(); i++)\n        this->v_ip1_2.push_back(vector_1d(sim.n_dim, NAN));\n}\n\nvoid LeapfrogIntegrator::setup_integrate(const vector_1d &t) {\n    BaseIntegrator::setup_integrate(t);\n    // In BaseIntegrator::setup_integrate, the initial state_w and dwdt is stored in tmp_w and\n    // tmp_dwdt, so we can use them below to initialize the array of velocities (1/2 step forward)\n\n    double dt = t[1] - t[0];\n\n    // First step all of the velocities by 1/2 step to initialize\n    for (int i=0; i < this->tmp_w.size(); i++)\n        for (int j=0; j < this->sim->n_dim; j++) {\n            this->v_ip1_2[i][j] = this->tmp_w[i][this->sim->n_dim + j]\n                + dt/2 * this->tmp_dwdt[i][this->sim->n_dim + j];\n        }\n}\n\nvoid LeapfrogIntegrator::step(const double t, const double dt) {\n    int i, j;\n\n    // TODO: if (this->sim->fixed_n_particles == false), need to resize and recompute\n    // tmp_w, tmp_dwdt, v_ip1_2 at the beginning of each step\n    if (this->sim->fixed_n_particles == false) {\n        this->tmp_w = this->sim->get_state_w();\n        this->tmp_dwdt = this->sim->get_dwdt(t);\n        for (int i=0; i < this->tmp_w.size(); i++)\n            for (int j=0; j < this->sim->n_dim; j++) {\n                this->v_ip1_2[i][j] = this->tmp_w[i][this->sim->n_dim + j]\n                    + dt/2 * this->tmp_dwdt[i][this->sim->n_dim + j];\n            }\n    }\n\n    // print_vector_2d(this->tmp_w);\n    // print_vector_2d(this->tmp_dwdt);\n    // print_vector_2d(this->v_ip1_2);\n\n    // Evolve the positions forward by a full step, using the retarded velocities\n    for (i=0; i < this->tmp_w.size(); i++)\n        for (j=0; j < this->sim->n_dim; j++)\n            this->tmp_w[i][j] += dt * this->v_ip1_2[i][j];\n\n    // Set the simulation state where now the velocity values are 1/2 step behind\n    this->sim->set_state_w(this->tmp_w);\n\n    // Compute the acceleration at the new positions:\n    this->sim->get_dwdt(t, this->tmp_dwdt);\n\n    // Evolve the velocity forward first by a half step, snapshot the time-aligned position and\n    // velocity, then finish the full step to leapfrog over the positions\n    for (i=0; i < this->tmp_w.size(); i++) {\n        for (j=0; j < this->sim->n_dim; j++) {\n            this->tmp_w[i][this->sim->n_dim + j] = this->v_ip1_2[i][j]\n                + dt/2 * this->tmp_dwdt[i][this->sim->n_dim + j];\n            this->v_ip1_2[i][j] = this->tmp_w[i][this->sim->n_dim + j]\n                + dt/2 * this->tmp_dwdt[i][this->sim->n_dim + j];\n        }\n    }\n\n    // Set the simulation state: the position and velocity should be synced, so ready for output\n    this->sim->set_state_w(this->tmp_w);\n}\n\n\n/* ------------------------------------------------------------------------------------------------\n    Boost\n*/\n\nBoostIntegrator::BoostIntegrator(gala::simulation::Simulation &sim,\n                                 std::string choice, int sub_steps)\n: BaseIntegrator(sim) {\n    /*\n    choice\n        Can be one of:\n            rk4 (4th order Runge-Kutta)\n            dopri5 (5th order Runge-Kutta)\n            rk78 (8th order Runge-Kutta)\n            adm (Adam-Bashforth-M)\n    sub_steps\n        The number of sub-steps to take (used in the Adam-Bashforth method).\n    */\n    this->sub_steps = sub_steps;\n    this->choice = choice;\n}\n\n// Built from example here:\n// https://github.com/headmyshoulder/odeint-v2/blob/master/examples/2d_lattice/spreading.cpp\n\n// TODO: shit - will this work if w size changes for each step?\n\ntemplate <typename T>\nvoid BoostIntegrator::step_worker(T stepper, const double t, const double dt) {\n    stepper.do_step([this](const vector_2d &w, vector_2d &dw, const double t) {\n        // TODO: this currently just gets the 3-acceleration, but need to compute the 6-acc\n        this->sim->set_state_w(w);\n        this->sim->get_dwdt(t, dw);\n    }, this->tmp_w, t, dt);\n    this->sim->set_state_w(this->tmp_w);\n}\n\n// List of steppers here:\n// https://www.boost.org/doc/libs/1_63_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/odeint_in_detail/steppers.html\n\n// ---\nvoid BoostIntegrator::step_rk4(const double t, const double dt) {\n    // https://www.boost.org/doc/libs/1_60_0/libs/numeric/odeint/doc/html/boost/numeric/odeint/runge_kutta4.html\n    typedef odeint::runge_kutta4 <\n        vector_2d, double, vector_2d, double,\n        nested_range_algebra <odeint::range_algebra>,\n        odeint::default_operations\n    > stepper_type_rk4;\n\n    stepper_type_rk4 stepper;\n    this->step_worker(stepper, t, dt);\n}\n\nvoid BoostIntegrator::step_dopri5(const double t, const double dt) {\n    // https://www.boost.org/doc/libs/1_60_0/libs/numeric/odeint/doc/html/boost/numeric/odeint/runge_kutta_dopri5.html\n    typedef odeint::runge_kutta_dopri5<\n        vector_2d, double, vector_2d, double,\n        nested_range_algebra< odeint::range_algebra >,\n        odeint::default_operations\n    > stepper_type_dopri5;\n\n    stepper_type_dopri5 stepper;\n    this->step_worker(stepper, t, dt);\n}\n\nvoid BoostIntegrator::step_rk78(const double t, const double dt) {\n    // https://www.boost.org/doc/libs/1_60_0/libs/numeric/odeint/doc/html/boost/numeric/odeint/runge_kutta_fehlberg78.html\n    typedef odeint::runge_kutta_fehlberg78 <\n        vector_2d, double, vector_2d, double,\n        nested_range_algebra <odeint::range_algebra>,\n        odeint::default_operations\n    > stepper_type_rk78;\n\n    stepper_type_rk78 stepper;\n    this->step_worker(stepper, t, dt);\n}\n\ntemplate <const int substeps>\nvoid BoostIntegrator::step_adm(const double t, const double dt) {\n    // https://www.boost.org/doc/libs/1_60_0/libs/numeric/odeint/doc/html/boost/numeric/odeint/adams_bashforth_moulton.html\n    typedef odeint::adams_bashforth_moulton <\n        substeps,\n        vector_2d, double, vector_2d, double,\n        nested_range_algebra <odeint::range_algebra>,\n        odeint::default_operations\n    > stepper_type_adm;\n\n    stepper_type_adm stepper;\n    this->step_worker(stepper, t, dt);\n}\n\nvoid BoostIntegrator::step(const double t, const double dt) {\n    if (this->choice == \"rk4\") {\n        step_rk4(t, dt);\n    } else if (this->choice == \"rk78\") {\n        step_rk78(t, dt);\n    } else if (this->choice == \"dopri5\") {\n        step_dopri5(t, dt);\n    } else if (this->choice == \"adm\") {\n        switch (this->sub_steps) {\n            case 2:\n                step_adm<2>(t, dt);\n            case 4:\n                step_adm<4>(t, dt);\n            case 6:\n                step_adm<6>(t, dt);\n            case 8:\n                step_adm<8>(t, dt);\n            default:\n                throw std::invalid_argument(\"Invalid setting of sub_steps\");\n        }\n    } else {\n        throw std::invalid_argument(\"Invalid integrator choice\");\n    }\n\n}\n", "meta": {"hexsha": "edd9a2261849cce7fedb87ef96053dd0bc589ac5", "size": 11159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp_gala/lib/src/cpp_gala/integrate/integrate.cpp", "max_stars_repo_name": "adrn/cpp-gala", "max_stars_repo_head_hexsha": "6e0c639f8339a4751f752b1b7e28949bbee619ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T16:52:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T16:52:32.000Z", "max_issues_repo_path": "src/cpp_gala/lib/src/cpp_gala/integrate/integrate.cpp", "max_issues_repo_name": "adrn/cpp-gala", "max_issues_repo_head_hexsha": "6e0c639f8339a4751f752b1b7e28949bbee619ce", "max_issues_repo_licenses": ["MIT"], "max_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_gala/lib/src/cpp_gala/integrate/integrate.cpp", "max_forks_repo_name": "adrn/cpp-gala", "max_forks_repo_head_hexsha": "6e0c639f8339a4751f752b1b7e28949bbee619ce", "max_forks_repo_licenses": ["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.3353846154, "max_line_length": 123, "alphanum_fraction": 0.5993368581, "num_tokens": 3166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.03514484299006095, "lm_q1q2_score": 0.01565806555640064}}
{"text": "#include <boost/program_options.hpp>\nusing namespace boost::program_options;\n\n#include <iostream>\nusing namespace std;\n\n#include <OpenImageIO/imageio.h>\nOIIO_NAMESPACE_USING\n\n#include <algorithm>\n\n#include \"Perlin.h\"\n\nint main(int argc, char* argv[])\n{\n\ttry\n\t{\n\t\toptions_description desc(\"Allowed options\");\n\t\tdesc.add_options()\n\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t(\"xres,x\", value<int>()->default_value(255),\n\t\t\t\t\"x resolution\")\n\t\t\t(\"yres,y\", value<int>()->default_value(255),\n\t\t\t\t\"y resolution\")\n\t\t\t(\"sample-size,s\", value<int>()->default_value(256),\n\t\t\t\t\"sample size\")\n\t\t\t(\"seed,r\", value<int>()->default_value(0),\n\t\t\t\t\"psuedo-random seed\")\n\t\t\t(\"persistence,p\", value<float>()->default_value(0.5f),\n\t\t\t\t\"persistence value\")\n\t\t\t(\"octaves,o\", value<int>()->default_value(2),\n\t\t\t\t\"number of octaves\")\n\t\t;\n\n\t\toptions_description hidden(\"Hidden options\");\n\t\thidden.add_options()\n\t\t\t(\"output-file\", value<string>()->required(), \"output file\")\n\t\t;\n\n\t\toptions_description all(\"Allowed options\");\n\t\tall.add(desc).add(hidden);\n\n\t\tpositional_options_description p;\n\t\tp.add(\"output-file\", 1);\n\n\t\tvariables_map vm;\n\t\tstore(command_line_parser(argc, argv).options(all)\n\t\t\t.positional(p).run(), vm);\n\n\t\tif (vm.count(\"help\"))\n\t\t{\n\t\t\tcout << \"Usage: \" << argv[0] << \" [options] output-file\" << endl;\n\t\t\tcout << desc << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tnotify(vm);\n\n\t\tstring outputfile = vm[\"output-file\"].as<string>();\n\t\tImageOutput* out = ImageOutput::create(outputfile);\n\t\tif (!out)\n\t\t{\n\t\t\tcerr << \"Could not create an ImageOutput for \"\n\t\t\t\t<< outputfile << \", error = \"\n\t\t\t\t<< OpenImageIO::geterror() << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst int xres = vm[\"xres\"].as<int>();\n\t\tconst int yres = vm[\"yres\"].as<int>();\n\t\tconst int channels = 3; // RGB\n\t\tImageSpec outspec(xres, yres, channels, TypeDesc::UINT8);\n\n\t\tif (!out->open(outputfile, outspec))\n\t\t{\n\t\t\tcerr << \"Could not open \" << outputfile\n\t\t\t\t<< \", error = \" << out->geterror() << endl;\n\t\t\tImageOutput::destroy(out);\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst int sample_size = vm[\"sample-size\"].as<int>();\n\t\tconst int seed = vm[\"seed\"].as<int>();\n\t\tPerlin perlin(sample_size, seed);\n\n\t\tfloat persistence = vm[\"persistence\"].as<float>();\n\t\tint octaves = vm[\"octaves\"].as<int>();\n\n\t\tunsigned char pixels[xres * yres * channels];\n\t\tfor (int y = 0; y < yres; y++)\n\t\t{\n\t\t\tfor (int x = 0; x < xres; x++)\n\t\t\t{\n\t\t\t\tfloat frequency, amplitude;\n\t\t\t\tfloat total = 0.0f;\n\n\t\t\t\tfor (int i = 1; i <= octaves; ++i)\n\t\t\t\t{\n\t\t\t\t\tfrequency = pow(2.0f, i);\n\t\t\t\t\tamplitude = pow(persistence, i);\n\n\t\t\t\t\ttotal += (perlin.Noise2(frequency * x / sample_size,\n\t\t\t\t\t\tfrequency * y / sample_size) + 1)/ 2.0f * amplitude;\n\t\t\t\t}\n\t\n\t\t\t\ttotal = min<float>(1.0f, max<float>(0.0f, total));\n\t\t\t\tunsigned int noise = (unsigned int) (total * 255);\n\n\t\t\t\tpixels[y * xres * channels + x * channels] = noise;\n\t\t\t\tpixels[y * xres * channels + x * channels + 1] = noise;\n\t\t\t\tpixels[y * xres * channels + x * channels + 2] = noise;\n\t\t\t}\n\t\t}\n\n\t\tif (!out->write_image(TypeDesc::UINT8, pixels))\n\t\t{\n\t\t\tcerr << \"Could not write pixels to \" << outputfile\n\t\t\t\t<< \", error = \" << out->geterror() << endl;\n\t\t\tImageOutput::destroy(out);\n\t\t\treturn 0;\n\t\t}\n\n\t\tImageOutput::destroy(out);\n\t}\n\tcatch (exception& e)\n\t{\n\t\tcerr << e.what() << endl;\n\t}\n}\n\n", "meta": {"hexsha": "91aef52aaa80a60785203445986ee7f67aa2518a", "size": 3214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Perlin/main.cpp", "max_stars_repo_name": "Simononon/Perlin", "max_stars_repo_head_hexsha": "ef381035d7ddb7c13e95acb80f8f325390a3f7cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Perlin/main.cpp", "max_issues_repo_name": "Simononon/Perlin", "max_issues_repo_head_hexsha": "ef381035d7ddb7c13e95acb80f8f325390a3f7cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Perlin/main.cpp", "max_forks_repo_name": "Simononon/Perlin", "max_forks_repo_head_hexsha": "ef381035d7ddb7c13e95acb80f8f325390a3f7cb", "max_forks_repo_licenses": ["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.534351145, "max_line_length": 68, "alphanum_fraction": 0.6104542626, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.03308597469422148, "lm_q1q2_score": 0.015639193545840275}}
{"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_FACTORY_HPP\n#define AMA_TENSOR_MUL_MUL_FACTORY_HPP 1\n\n#include <ama/tensor/mul/mul_outer.hpp>\n#include <ama/tensor/mul/mul_reducer.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/vector/vector0_c.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* reduction over all indices */\n    template <typename WHAT>\n    struct mul_factory\n    {\n      template <typename LEFT, typename RIGHT>\n      static\n      WHAT apply(LEFT const & left, RIGHT const & right)\n      {\n        BOOST_MPL_ASSERT_MSG(\n              (mpl::equal<WHAT, typename LEFT::value_type>::type::value)\n            , THIS_STRUCT_CAN_BE_CALLED_ONLY_TO_REDUCE_OVER_ALL_INDICES\n            , (WHAT));\n\n        return mul_reducer<LEFT,RIGHT>(left, right).template at< ::boost::mpl::vector0_c<size_t> >();\n      }\n    };\n\n\n\n\n    /* specialization for reduction of product */\n    template <typename TENSOR, typename CTLIST, typename COLIST>\n    struct mul_factory< iexp_temporary<TENSOR,CTLIST,COLIST> >\n    {\n      template <typename LEFT, typename RIGHT>\n      static\n      iexp_temporary<TENSOR,CTLIST,COLIST> apply(LEFT const & left,\n                                                 RIGHT const & right)\n      {\n        return iexp_temporary<TENSOR,CTLIST,COLIST>(mul_reducer<LEFT,RIGHT>(left,right));\n      }\n    };\n\n\n\n\n    /* specialization for outer product */\n    template <typename LEFT, typename RIGHT>\n    struct mul_factory< mul_outer<LEFT, RIGHT> >\n    {\n      template <typename T1, typename T2>\n      static\n      mul_outer<LEFT, RIGHT> apply(LEFT const & left,\n                                   RIGHT const & right)\n      {\n        return mul_outer<LEFT, RIGHT>(left,right);\n      }\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_MUL_MUL_FACTORY_HPP */\n", "meta": {"hexsha": "becc1e1525723d124fca03e9a382a61f8a60d19f", "size": 3415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/mul/mul_factory.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_factory.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_factory.hpp", "max_forks_repo_name": "mattiapenati/amanita", "max_forks_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5729166667, "max_line_length": 101, "alphanum_fraction": 0.6916544656, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186968948485238, "lm_q2_score": 0.037326887611855576, "lm_q1q2_score": 0.01562865193744376}}
{"text": "/*\n  Copyright (C) 2020 Skandinaviska Enskilda Banken AB (publ)\n  All rights reserved.\n  This file is part of ORE, a free-software/open-source library\n  for transparent pricing and risk analysis - http://opensourcerisk.org\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  This program is distributed on the basis that it will form a useful\n  contribution to risk analytics and model standardisation, but WITHOUT\n  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n  FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n */\n\n /*! \\file portfolio/builders/asianoption.hpp\n     \\brief Abstract engine builders for European Asian Options\n     \\ingroup builders\n */\n\n #pragma once\n\n #include <ored/portfolio/builders/vanillaoption.hpp>\n #include <boost/make_shared.hpp>\n #include <ored/portfolio/builders/cachingenginebuilder.hpp>\n #include <ored/utilities/log.hpp>\n #include <ored/utilities/to_string.hpp>\n #include <ored/utilities/parsers.hpp>\n #include <ored/utilities/indexparser.hpp>\n #include <ql/pricingengines/asian/analytic_cont_geom_av_price.hpp>\n #include <ql/pricingengines/asian/analytic_discr_geom_av_price.hpp>\n #include <ql/pricingengines/asian/analytic_discr_geom_av_strike.hpp>\n #include <ql/pricingengines/asian/mc_discr_arith_av_price.hpp>\n #include <ql/pricingengines/asian/mc_discr_arith_av_strike.hpp>\n #include <ql/utilities/null.hpp>\n\n namespace ore {\n namespace data {\n\n //! Abstract Engine Builder for Asian Options\n /*! Pricing engines are cached by asset/currency/expiry, where\n     expiry is null (Date()) if irrelevant.\n     \\ingroup builders\n  */\n class AsianOptionEngineBuilder\n     : public CachingOptionEngineBuilder<string, const string&, const Currency&, const AssetClass&, const Date&> {\n public:\n     AsianOptionEngineBuilder(const string& model, const string& engine, const set<string>& tradeTypes,\n                              const AssetClass& assetClass, const Date& expiryDate)\n         : CachingOptionEngineBuilder(model, engine, tradeTypes, assetClass), expiryDate_(expiryDate) {}\n\n     boost::shared_ptr<PricingEngine> engine(const string& assetName, const Currency& ccy, const Date& expiryDate) {\n         return CachingPricingEngineBuilder<string, const string&, const Currency&, const AssetClass&,\n                                            const Date&>::engine(assetName, ccy, assetClass_, expiryDate);\n     }\n\n     boost::shared_ptr<PricingEngine> engine(const Currency& ccy1, const Currency& ccy2, const Date& expiryDate) {\n         return CachingPricingEngineBuilder<string, const string&, const Currency&, const AssetClass&,\n                                            const Date&>::engine(ccy1.code(), ccy2, assetClass_, expiryDate);\n     }\n\n     //! This is used in building the option to select between Discrete- and ContinuousAveragingAsianOption\n     virtual std::string processType() { return \"\"; }\n\n protected:\n     virtual string keyImpl(const string& assetName, const Currency& ccy, const AssetClass& assetClassUnderlying,\n                            const Date& expiryDate) override {\n         return assetName + \"/\" + ccy.code() + \"/\" + to_string(expiryDate);\n     }\n\n     Date expiryDate_;\n };\n\n //! Discrete Monte Carlo Engine Builder for European Asian Arithmetic Average Price Options\n /*! Pricing engines are cached by asset/currency/expiry, where\n     expiry is null (Date()) if irrelevant.\n     \\ingroup builders\n  */\n class EuropeanAsianOptionMCDAAPEngineBuilder : public AsianOptionEngineBuilder {\n public:\n     EuropeanAsianOptionMCDAAPEngineBuilder(const string& model, const set<string>& tradeTypes,\n                                            const AssetClass& assetClass, const Date& expiryDate)\n         : AsianOptionEngineBuilder(model, \"MCDiscreteArithmeticAPEngine\", tradeTypes, assetClass, expiryDate) {}\n\n     std::string processType() override { return \"Discrete\"; }\n\n protected:\n     virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                         const AssetClass& assetClassUnderlying,\n                                                         const Date& expiryDate) override {\n         bool brownianBridge = ore::data::parseBool(engineParameter(\"BrownianBridge\", \"\", false, \"true\"));\n         bool antitheticVariate = ore::data::parseBool(engineParameter(\"AntitheticVariate\", \"\", false, \"true\"));\n         bool controlVariate = ore::data::parseBool(engineParameter(\"ControlVariate\", \"\", false, \"true\"));\n         Size requiredSamples = ore::data::parseInteger(engineParameter(\"RequiredSamples\", \"\", false, \"0\"));\n         Real requiredTolerance = ore::data::parseReal(engineParameter(\"RequiredTolerance\", \"\", false, \"0\"));\n         Size maxSamples = ore::data::parseInteger(engineParameter(\"MaxSamples\", \"\", false, \"0\"));\n         BigNatural seed = ore::data::parseInteger(engineParameter(\"Seed\", \"\", false, \"123456\"));\n\n         // Check if values defaulted to 0, if so replace by Null<T>().\n         if (requiredSamples == 0)\n             requiredSamples = Null<Size>();\n         if (requiredTolerance == 0)\n             requiredTolerance = Null<Real>();\n         if (maxSamples == 0)\n             maxSamples = Null<Size>();\n         QL_REQUIRE(requiredSamples != QuantLib::Null<Size>() || requiredTolerance != QuantLib::Null<Real>(),\n                    \"RequiredSamples or RequiredTolerance must be set for engine MCDiscreteArithmeticAPEngine.\");\n\n         boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n             getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n         return boost::make_shared<MCDiscreteArithmeticAPEngine<LowDiscrepancy>>(gbsp, brownianBridge, antitheticVariate,\n                                                                                 controlVariate, requiredSamples,\n                                                                                 requiredTolerance, maxSamples, seed);\n     }\n };\n\n //! Discrete Monte Carlo Engine Builder for European Asian Arithmetic Average Strike Options\n /*! Pricing engines are cached by asset/currency/expiry, where\n     expiry is null (Date()) if irrelevant.\n     \\ingroup builders\n  */\n class EuropeanAsianOptionMCDAASEngineBuilder : public AsianOptionEngineBuilder {\n public:\n     EuropeanAsianOptionMCDAASEngineBuilder(const string& model, const set<string>& tradeTypes,\n                                            const AssetClass& assetClass, const Date& expiryDate)\n         : AsianOptionEngineBuilder(model, \"MCDiscreteArithmeticASEngine\", tradeTypes, assetClass, expiryDate) {}\n\n     std::string processType() override { return \"Discrete\"; }\n\n protected:\n     virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                         const AssetClass& assetClassUnderlying,\n                                                         const Date& expiryDate) override {\n         bool brownianBridge = ore::data::parseBool(engineParameter(\"BrownianBridge\", \"\", false, \"true\"));\n         bool antitheticVariate = ore::data::parseBool(engineParameter(\"AntitheticVariate\", \"\", false, \"true\"));\n         Size requiredSamples = ore::data::parseInteger(engineParameter(\"RequiredSamples\", \"\", false, \"0\"));\n         Real requiredTolerance = ore::data::parseReal(engineParameter(\"RequiredTolerance\", \"\", false, \"0\"));\n         Size maxSamples = ore::data::parseInteger(engineParameter(\"MaxSamples\", \"\", false, \"0\"));\n         BigNatural seed = ore::data::parseInteger(engineParameter(\"Seed\", \"\", false, \"123456\"));\n\n         // Check if values defaulted to 0, if so replace by Null<T>().\n         if (requiredSamples == 0)\n             requiredSamples = Null<Size>();\n         if (requiredTolerance == 0)\n             requiredTolerance = Null<Real>();\n         if (maxSamples == 0)\n             maxSamples = Null<Size>();\n         QL_REQUIRE(requiredSamples != QuantLib::Null<Size>() || requiredTolerance != QuantLib::Null<Real>(),\n                    \"RequiredSamples or RequiredTolerance must be set for engine MCDiscreteArithmeticASEngine.\");\n\n         boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n             getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n         return boost::make_shared<MCDiscreteArithmeticASEngine<LowDiscrepancy>>(\n             gbsp, brownianBridge, antitheticVariate, requiredSamples, requiredTolerance, maxSamples, seed);\n     }\n };\n\n //! Discrete Monte Carlo Engine Builder for European Asian Geometric Average Price Options\n /*! Pricing engines are cached by asset/currency/expiry, where\n     expiry is null (Date()) if irrelevant.\n     \\ingroup builders\n  */\n class EuropeanAsianOptionMCDGAPEngineBuilder : public AsianOptionEngineBuilder {\n public:\n     EuropeanAsianOptionMCDGAPEngineBuilder(const string& model, const set<string>& tradeTypes,\n                                            const AssetClass& assetClass, const Date& expiryDate)\n         : AsianOptionEngineBuilder(model, \"MCDiscreteGeometricAPEngine\", tradeTypes, assetClass, expiryDate) {}\n\n     std::string processType() override { return \"Discrete\"; }\n\n protected:\n     virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                         const AssetClass& assetClassUnderlying,\n                                                         const Date& expiryDate) override {\n         bool brownianBridge = ore::data::parseBool(engineParameter(\"BrownianBridge\", \"\", false, \"true\"));\n         bool antitheticVariate = ore::data::parseBool(engineParameter(\"AntitheticVariate\", \"\", false, \"true\"));\n         Size requiredSamples = ore::data::parseInteger(engineParameter(\"RequiredSamples\", \"\", false, \"0\"));\n         Real requiredTolerance = ore::data::parseReal(engineParameter(\"RequiredTolerance\", \"\", false, \"0\"));\n         Size maxSamples = ore::data::parseInteger(engineParameter(\"MaxSamples\", \"\", false, \"0\"));\n         BigNatural seed = ore::data::parseInteger(engineParameter(\"Seed\", \"\", false, \"123456\"));\n\n         // Check if values defaulted to 0, if so replace by Null<T>().\n         if (requiredSamples == 0)\n             requiredSamples = Null<Size>();\n         if (requiredTolerance == 0)\n             requiredTolerance = Null<Real>();\n         if (maxSamples == 0)\n             maxSamples = Null<Size>();\n         QL_REQUIRE(requiredSamples != QuantLib::Null<Size>() || requiredTolerance != QuantLib::Null<Real>(),\n                    \"RequiredSamples or RequiredTolerance must be set for engine MCDiscreteGeometricAPEngine.\");\n\n         boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n             getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n         return boost::make_shared<MCDiscreteGeometricAPEngine<LowDiscrepancy>>(\n             gbsp, brownianBridge, antitheticVariate, requiredSamples, requiredTolerance, maxSamples, seed);\n     }\n };\n\n //! Discrete Analytic Engine Builder for European Asian Geometric Average Price Options\n /*! Pricing engines are cached by asset/currency\n     \\ingroup builders\n  */\n class EuropeanAsianOptionADGAPEngineBuilder : public AsianOptionEngineBuilder {\n public:\n     EuropeanAsianOptionADGAPEngineBuilder(const string& model, const set<string>& tradeTypes,\n                                           const AssetClass& assetClass)\n         : AsianOptionEngineBuilder(model, \"AnalyticDiscreteGeometricAPEngine\", tradeTypes, assetClass, Date()) {}\n\n     std::string processType() override { return \"Discrete\"; }\n\n protected:\n     virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                         const AssetClass& assetClassUnderlying,\n                                                         const Date& expiryDate) override {\n         boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n             getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n         return boost::make_shared<AnalyticDiscreteGeometricAveragePriceAsianEngine>(gbsp);\n     }\n };\n\n //! Discrete Analytic Engine Builder for European Asian Geometric Average Strike Options\n /*! Pricing engines are cached by asset/currency\n     \\ingroup builders\n  */\n class EuropeanAsianOptionADGASEngineBuilder : public AsianOptionEngineBuilder {\n public:\n     EuropeanAsianOptionADGASEngineBuilder(const string& model, const set<string>& tradeTypes,\n                                           const AssetClass& assetClass)\n         : AsianOptionEngineBuilder(model, \"AnalyticDiscreteGeometricASEngine\", tradeTypes, assetClass, Date()) {}\n\n     std::string processType() override { return \"Discrete\"; }\n\n protected:\n     virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                         const AssetClass& assetClassUnderlying,\n                                                         const Date& expiryDate) override {\n         boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n             getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n         return boost::make_shared<AnalyticDiscreteGeometricAverageStrikeAsianEngine>(gbsp);\n     }\n };\n\n //! Continuous Analytic Engine Builder for European Asian Geometric Average Price Options\n /*! Pricing engines are cached by asset/currency\n     Note that this engine disregards fixing dates, i.e. it utilizes continuous averaging and is mainly for testing.\n     \\ingroup builders\n  */\n class EuropeanAsianOptionACGAPEngineBuilder : public AsianOptionEngineBuilder {\n public:\n     EuropeanAsianOptionACGAPEngineBuilder(const string& model, const set<string>& tradeTypes,\n                                           const AssetClass& assetClass)\n         : AsianOptionEngineBuilder(model, \"AnalyticContinuousGeometricAPEngine\", tradeTypes, assetClass, Date()) {}\n\n     std::string processType() override { return \"Continuous\"; }\n\n protected:\n     virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                         const AssetClass& assetClassUnderlying,\n                                                         const Date& expiryDate) override {\n         boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n             getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n         return boost::make_shared<AnalyticContinuousGeometricAveragePriceAsianEngine>(gbsp);\n     }\n };\n\n } // namespace data\n } // namespace ore\n", "meta": {"hexsha": "6f77d31bb2a3ed28432d6f0190024d4ada104619", "size": 14829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/portfolio/builders/asianoption.hpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREData/ored/portfolio/builders/asianoption.hpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREData/ored/portfolio/builders/asianoption.hpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 55.3320895522, "max_line_length": 121, "alphanum_fraction": 0.6661946187, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.03567855280029284, "lm_q1q2_score": 0.015620908830355018}}
{"text": "// Copyright 2005 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#include \"graph_types.hpp\"\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/bc_clustering.hpp>\n\nnamespace boost { namespace graph { namespace python {\n\ntemplate<typename Graph>\nvoid \nbrandes_betweenness_centrality\n  (const Graph& g, \n   vector_property_map<\n     float,\n     typename property_map<Graph, vertex_index_t>::const_type\n   >* in_vertex_centrality,\n   vector_property_map<\n     float, \n     typename property_map<Graph, edge_index_t>::const_type\n   >* in_edge_centrality,\n   vector_property_map<\n     float, \n     typename property_map<Graph, edge_index_t>::const_type>* weight)\n{\n  typedef vector_property_map<\n            float, typename property_map<Graph, vertex_index_t>::const_type> \n    VertexCentralityMap;\n\n  typedef vector_property_map<\n            float, typename property_map<Graph, edge_index_t>::const_type> \n    EdgeCentralityMap;\n\n  VertexCentralityMap vertex_centrality = \n    in_vertex_centrality? *in_vertex_centrality \n    : VertexCentralityMap(num_vertices(g), get(vertex_index, g));\n\n  EdgeCentralityMap edge_centrality = \n    in_edge_centrality? *in_edge_centrality \n    : EdgeCentralityMap(num_edges(g), get(edge_index, g));\n\n  if (weight) {\n    boost::brandes_betweenness_centrality\n      (g, \n       weight_map(*weight).\n       centrality_map(vertex_centrality).\n       edge_centrality_map(edge_centrality));\n  } else {\n    boost::brandes_betweenness_centrality\n      (g, \n       centrality_map(vertex_centrality).\n       edge_centrality_map(edge_centrality));\n  }\n}\n\ntemplate<typename Graph>\nvoid \nrelative_betweenness_centrality\n  (const Graph& g, \n   vector_property_map<\n     float, \n     typename property_map<Graph, vertex_index_t>::const_type>& centrality)\n{ \n  relative_betweenness_centrality(g, centrality); \n}\n\ntemplate<typename Graph>\nfloat\ncentral_point_dominance\n  (const Graph& g, \n   vector_property_map<\n     float, \n     typename property_map<Graph, vertex_index_t>::const_type>& centrality)\n{ \n  return boost::central_point_dominance(g, centrality); \n}\n\nstruct bc_clustering_done_python\n{\n  explicit bc_clustering_done_python(boost::python::object done) \n    : done(done) { }\n\n  template<typename Graph>\n  bool \n  operator()(float max_centrality, \n             typename graph_traits<Graph>::edge_descriptor e,\n             const Graph& g)\n  {\n    using boost::python::extract;\n    return extract<bool>(done(max_centrality, e, ref(g)));\n  }\n\nprivate:\n  boost::python::object done;\n};\n\ntemplate<typename Graph>\nvoid \nbetweenness_centrality_clustering\n  (Graph& g, boost::python::object done,\n   vector_property_map<\n     float, \n     typename property_map<Graph, edge_index_t>::const_type\n   >* in_edge_centrality)\n{\n  typedef vector_property_map<\n            float, typename property_map<Graph, edge_index_t>::const_type> \n    EdgeCentralityMap;\n\n  EdgeCentralityMap edge_centrality = \n    in_edge_centrality? *in_edge_centrality \n    : EdgeCentralityMap(num_edges(g), get(edge_index, g));\n\n  boost::betweenness_centrality_clustering(g, \n                                           bc_clustering_done_python(done),\n                                           edge_centrality);\n}\n\nvoid export_betweenness_centrality()\n{\n  using boost::python::arg;\n  using boost::python::def;\n\n#define UNDIRECTED_GRAPH(Name,Type)                                     \\\n  {                                                                     \\\n    typedef property_map<Type, vertex_index_t>::const_type VertexIndexMap;  \\\n    typedef property_map<Type, edge_index_t>::const_type EdgeIndexMap;      \\\n    typedef vector_property_map<float, VertexIndexMap> VertexCentralityMap; \\\n    typedef vector_property_map<float, EdgeIndexMap> EdgeCentralityMap; \\\n                                                                        \\\n    def(\"brandes_betweenness_centrality\",                               \\\n        &brandes_betweenness_centrality<Type>,                          \\\n        (arg(\"graph\"),                                                  \\\n         arg(\"vertex_centrality_map\") = static_cast<VertexCentralityMap*>(0), \\\n         arg(\"edge_centrality_map\") = static_cast<EdgeCentralityMap*>(0), \\\n         arg(\"weight_map\") = static_cast<EdgeCentralityMap*>(0)));      \\\n    def(\"relative_betweenness_centrality\",                              \\\n        &relative_betweenness_centrality<Type>,                         \\\n        (arg(\"graph\"), arg(\"vertex_centrality_map\")));                  \\\n    def(\"central_point_dominance\",                                      \\\n        &central_point_dominance<Type>,                                 \\\n        (arg(\"graph\"), arg(\"vertex_centrality_map\")));                  \\\n    def(\"betweenness_centrality_clustering\",                            \\\n        &betweenness_centrality_clustering<Type>,                       \\\n        (arg(\"graph\"), arg(\"done\"),                                     \\\n         arg(\"edge_centrality_map\") = static_cast<EdgeCentralityMap*>(0))); \\\n  }\n#include \"graphs.hpp\"\n}\n\n} } } // end namespace boost::graph::python\n", "meta": {"hexsha": "7335c9561596c572cf91e61d8eb746d0cb603cff", "size": 5351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/betweenness_centrality.cpp", "max_stars_repo_name": "erwinvaneijk/bgl-python", "max_stars_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-06-19T08:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:09:05.000Z", "max_issues_repo_path": "src/betweenness_centrality.cpp", "max_issues_repo_name": "erwinvaneijk/bgl-python", "max_issues_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "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/betweenness_centrality.cpp", "max_forks_repo_name": "erwinvaneijk/bgl-python", "max_forks_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:08:03.000Z", "avg_line_length": 34.0828025478, "max_line_length": 79, "alphanum_fraction": 0.636516539, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.03358950698030741, "lm_q1q2_score": 0.015615814576802315}}
{"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 \"CSparseMatrix_internal.h\"\n#include \"SiconosMatrix.hpp\"\n#include \"SiconosAlgebra.hpp\"\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include \"BlockMatrix.hpp\"\n\n// Constructor with the type-number\nSiconosMatrix::SiconosMatrix(unsigned int type): _num(type)\n{}\n\nconst SP::Index SiconosMatrix::tabRow() const\n{\n  SiconosMatrixException::selfThrow(\"SiconosMatrix::tabRow() : not implemented for this type of matrix (Simple?) reserved to BlockMatrix.\");\n  // fake to avoid error on warning.\n  return SP::Index();\n}\n\nconst SP::Index SiconosMatrix::tabCol() const\n{\n  SiconosMatrixException::selfThrow(\"SiconosMatrix::tabCol() : not implemented for this type of matrix (Simple?) reserved to BlockMatrix.\");\n  // fake to avoid error on warning.\n  return SP::Index();\n}\n\n\n\n//=====================\n// matrices comparison\n//=====================\nbool isComparableTo(const  SiconosMatrix& m1, const  SiconosMatrix& m2)\n{\n  // return:\n  // - true if one of the matrices is a Simple and if they have the same dimensions.\n  // - true if both are block but with blocks which are facing each other of the same size.\n  // - false in other cases\n\n  if ((!m1.isBlock() || !m2.isBlock()) && (m1.size(0) == m2.size(0)) && (m1.size(1) == m2.size(1)))\n    return true;\n\n  const SP::Index I1R = m1.tabRow();\n  const SP::Index I2R = m2.tabRow();\n  const SP::Index I1C = m1.tabCol();\n  const SP::Index I2C = m2.tabCol();\n\n  return ((*I1R == *I2R) && (*I1C == *I2C));\n}\n\nSiconosMatrix& operator *=(SiconosMatrix& m, const double& s)\n{\n  if (m._num == 0) // BlockMatrix\n  {\n    BlockMatrix& mB = static_cast<BlockMatrix&>(m);\n    BlocksMat::iterator1 it;\n    BlocksMat::iterator2 it2;\n    for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for (it2 = it.begin(); it2 != it.end(); ++it2)\n        (**it2) *= s;\n    }\n  }\n  else if (m._num == 1)\n    *m.dense() *= s;\n  else if (m._num == 2)\n    *m.triang() *= s;\n  else if (m._num == 3)\n    *m.sym() *= s;\n  else if (m._num == 4)\n    *m.sparse() *= s;\n  else if (m._num == 5)\n    *m.banded() *= s;\n  else if (m._num == 6) {} // nothing!\n  else //if(_num == 7)\n    SiconosMatrixException::selfThrow(\" SP::SiconosMatrix = (double) : invalid type of matrix\");\n\n  return m;\n}\n\nSiconosMatrix& operator /=(SiconosMatrix& m, const double& s)\n{\n  if (m._num == 0) // BlockMatrix\n  {\n    BlockMatrix& mB = static_cast<BlockMatrix&>(m);\n    BlocksMat::iterator1 it;\n    BlocksMat::iterator2 it2;\n    for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for (it2 = it.begin(); it2 != it.end(); ++it2)\n        (**it2) /= s;\n    }\n  }\n  else if (m._num == 1)\n    *m.dense() /= s;\n  else if (m._num == 2)\n    *m.triang() /= s;\n  else if (m._num == 3)\n    *m.sym() /= s;\n  else if (m._num == 4)\n    *m.sparse() /= s;\n  else if (m._num == 5)\n    *m.banded() /= s;\n  else if (m._num == 6) {} // nothing!\n  else //if(_num == 7)\n    SiconosMatrixException::selfThrow(\" SiconosMatrix *= (double) : invalid type of matrix\");\n\n  return m;\n}\n\nsize_t SiconosMatrix::nnz(double tol)\n{\n  size_t nnz = 0;\n  if (_num == 1) //dense\n  {\n    double* arr = getArray();\n    for (size_t i = 0; i < size(0)*size(1); ++i)\n    {\n      if (fabs(arr[i]) > tol) { nnz++; }\n    }\n  }\n  else if (_num == 4)\n  {\n    nnz = sparse()->nnz();\n  }\n  else\n  {\n     SiconosMatrixException::selfThrow(\"SiconosMatrix::nnz not implemented for the given matrix type\");\n  }\n\n  return nnz;\n\n}\n\nbool SiconosMatrix::fillCSC(CSparseMatrix* csc, size_t row_off, size_t col_off, double tol)\n{\n  assert(csc);\n  double* Mx = csc->x; // data\n  CS_INT* Mi = csc->i; // row indx\n  CS_INT* Mp = csc->p; // column pointers\n\n  assert(Mp[col_off] >= 0);\n  size_t nz = csc->p[col_off];\n\n  size_t nrow = size(0);\n  size_t ncol = size(1);\n\n  CS_INT pval = Mp[col_off];\n\n  if (_num == 1) //dense\n  {\n    double* arr = getArray();\n    for (size_t j = 0, joff = col_off; j < ncol; ++j)\n    {\n      for (size_t i = 0; i < nrow; ++i)\n      {\n        // col-major\n        double elt_val = arr[i + j*nrow];\n        // std::cout << \" a(i=\" << i << \",j=\" << j << \") = \"<< elt_val << std::endl;\n        if (fabs(elt_val) > tol)\n        {\n          Mx[pval] = elt_val;\n          Mi[pval] = i + row_off;\n          // std::cout << \"Mx[\" <<pval <<\"] = \" << Mx[pval]<<   std::endl;\n          // std::cout << \"Mp[\" <<pval <<\"] = \" << Mi[pval]<<   std::endl;\n          ++pval;\n        }\n      }\n      // std::cout << \"joff\" << joff << std::endl;\n      Mp[++joff] = pval;\n\n    }\n  }\n  else if (_num == 4)\n  {\n    const Index& ptr = sparse()->index1_data();\n    const Index& indx = sparse()->index2_data();\n    const ublas::unbounded_array<double>& vals = sparse()->value_data();\n\n    size_t nnz =  sparse()->nnz();\n\n    assert(ptr.size() == ncol + 1);\n    assert(indx.size() == nnz);\n    assert(vals.size() == nnz);\n\n    for (size_t i = 0; i < nnz; ++i)\n    {\n      Mx[pval] = vals[i];\n      Mi[pval++] = row_off + indx[i];\n    }\n    for (size_t j = 1, joff = col_off + 1; j < ncol+1; ++j, ++joff)\n    {\n      Mp[joff] = nz + ptr[j];\n    }\n  }\n  else\n  {\n     SiconosMatrixException::selfThrow(\"SiconosMatrix::fillCSC not implemented for the given matrix type\");\n  }\n\n  return true;\n}\n\nbool SiconosMatrix::fillTriplet(CSparseMatrix* triplet, size_t row_off, size_t col_off, double tol)\n{\n  assert(triplet);\n  size_t nrow = size(0);\n  size_t ncol = size(1);\n\n  if (_num == 1) //dense\n  {\n    double* arr = getArray();\n    for (size_t j = 0; j < ncol; ++j)\n    {\n      for (size_t i = 0; i < nrow; ++i)\n      {\n        // col-major\n\n        CSparseMatrix_zentry(triplet, i + row_off, j + col_off, arr[i + j*nrow] );\n      }\n    }\n  }\n  else\n  {\n     SiconosMatrixException::selfThrow(\"SiconosMatrix::fillCSC not implemented for the given matrix type\");\n  }\n\n  return true;\n}\n\n\nstd::ostream& operator<<(std::ostream& os, const SiconosMatrix& sm)\n{\n  os << sm.toString();\n  return os;\n}\n", "meta": {"hexsha": "103d45c8fa60e14771039b3e433fa6f2a1bcc72d", "size": 6550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosMatrix.cpp", "max_stars_repo_name": "bremond/siconos", "max_stars_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosMatrix.cpp", "max_issues_repo_name": "bremond/siconos", "max_issues_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosMatrix.cpp", "max_forks_repo_name": "bremond/siconos", "max_forks_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9920634921, "max_line_length": 140, "alphanum_fraction": 0.5839694656, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.04336579381848507, "lm_q1q2_score": 0.01558411142476912}}
{"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 ISTLINTERFACE_HH\n#define ISTLINTERFACE_HH\n\n#include <memory>\n#include <type_traits>\n\n#include <boost/fusion/algorithm.hpp>\n#include <boost/fusion/sequence.hpp>\n\n#include <dune/istl/operators.hh>\n#include \"dune/istl/preconditioners.hh\"\n\n#include \"fem/fixdune.hh\"\n#include \"fem/functionspace.hh\"\n\n#include \"linalg/triplet.hh\"\n#include \"linalg/crsutil.hh\"\n#include \"linalg/factorization.hh\"\n#include \"linalg/symmetricOperators.hh\"\n#include \"linalg/threadedMatrix.hh\"\n\n#include \"utilities/duneInterface.hh\"\n\n//---------------------------------------------------------------------\n\nnamespace Kaskade\n{\n  /**\n   * \\cond internals\n   */\n  namespace IstlInterfaceDetail {\n\n    template <class T>\n    typename T::iterator begin(T& t)\n    {\n      return t.begin();\n    }\n\n    template <class T>\n    typename T::const_iterator begin(T const& t)\n    {\n      return t.begin();\n    }\n\n    template <class Scalar>\n    typename std::vector<Scalar>::iterator begin(std::vector<Scalar>& vec) { return vec.begin(); }\n\n    template <class Scalar>\n    typename std::vector<Scalar>::const_iterator begin(std::vector<Scalar> const& vec) { return vec.begin(); }\n\n    using namespace boost::fusion;\n\n\n    /** \n     * \\brief This is a lightweight matrix block class, holding a reference to the actual matrix that is owned by the matrix block in the\n     *        assembler as well as a NUMA-aware copy.\n     * \\tparam ElementType          the type of block matrix elements\n     * \\tparam rid the row index of the block\n     * \\tparam cid the column index of the block\n     * \\tparam sym whether the block is symmetric or not\n     * \\tparam trans whether the block is mirrored\n     * \n     * If the block is mirrored, the assembler matrix may have a different element type than this block (m x n instead of n x m).\n     */\n    template <class ElementType, int rid, int cid, bool sym, bool trans>\n    struct Block\n    {\n      static int const rowId = rid;          // row index of the block\n      static int const colId = cid;          // col index of the block\n      static bool const symmetric = sym;     // symmetry\n      static bool const transposed = trans;  // whether only its mirror image is available in the assembler\n\n      typedef ElementType BlockType;\n      typedef typename BlockType::field_type Scalar;\n      typedef NumaBCRSMatrix<typename Transpose<BlockType,transposed>::type> Matrix; // Matrix type in assembler\n      typedef Dune::BlockVector<Dune::FieldVector<Scalar,BlockType::cols>> Domain; // take care of transposition\n      typedef Dune::BlockVector<Dune::FieldVector<Scalar,BlockType::rows>> Range;\n      typedef NumaBCRSMatrix<BlockType> TMatrix;\n\n      explicit Block(std::shared_ptr<Matrix const> const& m): matrix(m) {}\n\n      std::shared_ptr<Matrix const> matrix;\n      std::shared_ptr<TMatrix> threadedMatrix;\n    };\n\n    // Provides a heterogeneous sequence of all matrix blocks appearing\n    // conceptually in the Galerkin operator, even if they are not stored\n    // explicitly in the assembler because of symmetry.\n    template <class GOP>\n    class AllBlocks\n    {\n      struct Copy\n      {\n        template <class MBlock>\n        auto operator()(MBlock const& mb) const {\n          typedef std::remove_reference_t<MBlock> MB;\n          typedef Block<typename MB::BlockType,MB::rowId,MB::colId,MB::symmetric,false> type;\n          return type(mb.globalMatrixPointer());\n        }\n      };\n\n      // Filters out flagged blocks with row index -1\n      struct Cleanup {\n        template <class MB> struct apply { typedef boost::mpl::bool_<MB::rowId>=0> type; };\n      };\n\n      // Blocks not to be mirrored are flagged with row index -1 to be filtered out later by Cleanup.\n      struct Mirror\n      {        \n        template <class T> struct result {};\n\n        template <class MBlock>\n        struct result<Mirror(MBlock)> {\n          typedef typename std::remove_reference<MBlock>::type MB;\n          typedef typename Transpose<typename MB::BlockType,true>::type ElementType;\n          typedef Block<ElementType,\n              MB::mirror?MB::colId:-1, MB::rowId, MB::symmetric, true> type;\n        };\n\n        template <class MB>\n        typename result<Mirror(MB)>::type operator()(MB const& mb) const {\n          return typename result<Mirror(MB)>::type(mb.globalMatrixPointer());\n        }\n      };\n\n      // It would be more natural to filter the mirror blocks before\n      // actually mirroring them, but this does frequently result in empty\n      // filter lists. For some reasons (don't know why), the filter view\n      // produces wrong type results when empty lists occur.\n\n      typedef typename result_of::transform<typename GOP::MatrixBlockArray const,Copy>::type CopiedBlocks;\n      typedef typename result_of::transform<typename GOP::MatrixBlockArray const,Mirror>::type MirroredBlocks;\n      typedef typename result_of::join<CopiedBlocks const,MirroredBlocks const>::type JointBlocks;\n\n\n    public:\n      typedef typename result_of::filter_if<JointBlocks const,Cleanup>::type const A;\n      typedef typename result_of::as_vector<A>::type result;\n\n      static result apply(GOP const& op) {\n        return filter_if<Cleanup>(join(transform(op.getMatrix(),Copy()),transform(op.getMatrix(),Mirror())));\n      }\n    };\n\n    // A boost fusion predicate that is true for some matrix block if it\n    // lies within the half-open subrange given by the template\n    // parameters.\n    template <int firstRow, int lastRow, int firstCol, int lastCol>\n    struct RangeBlockSelector\n    {\n      template <class Block> struct apply\n      {\n        typedef boost::mpl::bool_<firstRow<=Block::rowId && Block::rowId<lastRow && firstCol<=Block::colId && Block::colId<lastCol> type;\n      };\n    };\n\n    // Shifts row and column indices of matrix blocks downwards and initializes the threaded matrix held by this block.\n    template <int firstRow, int firstCol>\n    struct Translate {\n      // Constructor takes the number of threads onto which the threaded matrix shall be distributed.\n      // As a conservative default, this is 1 (sequential).\n      Translate(int nThreads_=1): nThreads(nThreads_)\n      {\n      }\n\n      template <class T> struct result {};\n\n      template <class Blk>\n      struct result<Translate(Blk)> {\n        typedef typename std::remove_reference<Blk>::type Bl;\n        typedef Block<typename Bl::BlockType,Bl::rowId-firstRow,Bl::colId-firstCol,Bl::symmetric,Bl::transposed> type;\n      };\n\n      template <class Bl>\n      auto operator()(Bl const& bl) const \n      { \n        Block<typename Bl::BlockType,Bl::rowId-firstRow,Bl::colId-firstCol,Bl::symmetric,Bl::transposed>  blk(bl.matrix); \n        blk.threadedMatrix.reset(new typename Bl::TMatrix(*blk.matrix,bl.symmetric,bl.transposed,false));\n        return blk;\n      }\n\n    private:\n      int nThreads;\n    };\n\n    /// Coordinate mapping.\n    /**\n     * Enabled/disabled via std::enable_if on return type.  \n     */\n    template <class FSElement, class Vector>\n    typename std::enable_if<!std::is_same<FSElement,Vector>::value,void>::type\n    toVector(FSElement const& x, Vector& coefficients)\n    {\n      coefficients.resize(x.dim());\n      vectorToSequence(x,begin(coefficients));\n    }\n\n    /// Coordinate mapping is the identity if range_type = vector_type\n    template <class FSElement, class Vector>\n    typename std::enable_if<std::is_same<FSElement,Vector>::value,void>::type\n    toVector(FSElement const& x, Vector& coefficients)\n    {\n      coefficients = x;\n    }\n\n    /// Coordinate mapping\n    template <class FSElement, class Vector>\n    typename std::enable_if<!std::is_same<FSElement,Vector>::value,void>::type\n    fromVector(Vector const& coefficients, FSElement& x)\n    {\n      assert(coefficients.size()>=x.dim());\n      vectorFromSequence(x,begin(coefficients));\n    }\n\n    /// Coordinate mapping is the identity if range_type = vector_type\n    template <class FSElement, class Vector>\n    typename std::enable_if<std::is_same<FSElement,Vector>::value,void>::type\n    fromVector(Vector const& coefficients, FSElement& x)\n    {\n      x = coefficients;\n    }\n\n\n    template <class T>\n    void toFile(std::vector<T> const& v, std::string const& filename, size_t precision = 10)\n    {\n      std::ofstream os;\n      os.precision(precision);\n      os.open(filename);\n\n      for(T t : v) os << t << \"\\t\";\n      os << std::endl;\n\n      os.close();\n    }\n\n\n    // Container storing information on blocks\n    template <int firstRow_, int lastRow_, int firstCol_,int lastCol_>\n    struct BlockInfo\n    {\n      static int const firstRow = firstRow_;\n      static int const lastRow = lastRow_;\n      static int const firstCol = firstCol_;\n      static int const lastCol = lastCol_;\n    };\n  } // End of namespace IstlInterfaceDetail\n\n  /**\n   * \\endcond\n   */\n\n  //---------------------------------------------------------------------\n\n/*  template <class Operator>\n  class TransposedOperator\n  {\n  public:\n    typedef typename Operator::Domain Range;\n    typedef typename Operator::Range Domain;\n    typedef typename Operator::Scalar Scalar;\n\n    explicit TransposedOperator(Operator const& A_) : A(A_) {}\n\n    void apply(const Domain &x, Range &b) const { return A.applyTransposed(x,b); }\n\n    void applyscaleadd(Scalar alpha, Domain const& x, Range& b) const { return A.applyscaleaddTransposed(alpha,x,b); }\n\n    Operator const& getOperator() const { return A; }\n\n  private:\n    Operator const& A;\n  };\n*/\n\n\n  /**\n   * \\ingroup linalg\n   *\n   * \\brief Operator with matrix-representation and coordinate mappings.\n   *\n   * Note that the operator creates a copy of the passed matrix (if not passed as rvalue).\n   * This allows the implementation of a rvalue-constructor and assures that further manipulation\n   * of the matrix data does not change the operator's behaviour.\n   *\n   * Implements the MatrixRepresentedOperator concept.\n   * \n   * \\todo docme: How does this relate to Dune::MatrixAdapter and Dune::AssembledLinearOperator?\n   */\n  template <class Matrix_, class Domain_, class Range_> class MatrixRepresentedOperator;\n\n  template <class Scalar_, class SparseInt, class Domain_, class Range_>\n  class MatrixRepresentedOperator<MatrixAsTriplet<Scalar_,SparseInt>,Domain_,Range_>\n      : public Dune::LinearOperator<Domain_,Range_>\n  {\n  public:\n    typedef MatrixAsTriplet<Scalar_,SparseInt> Matrix;\n    typedef Matrix matrix_type; // for compatibility with Dune::MatrixAdapter\n    typedef Domain_ Domain;\n    typedef Range_ Range;\n    typedef Scalar_ Scalar;\n\n    static int const category = Dune::SolverCategory::sequential;\n\n    MatrixRepresentedOperator() = default;\n\n    explicit MatrixRepresentedOperator(Matrix const& A_) : A(A_)\n    {}\n\n    explicit MatrixRepresentedOperator(Matrix&& A_) : A(A_)\n    {}\n\n    MatrixAsTriplet<Scalar,SparseInt> getTriplet() const { return get<MatrixAsTriplet<Scalar,SparseInt> >(); }\n\n    /// Access matrix\n    template <class OtherMatrix=Matrix>\n    typename std::enable_if<std::is_same<Matrix,OtherMatrix>::value, Matrix const&>::type get() const { return A; }\n\n    Matrix& get_non_const() { return A; }\n\n    /// Access matrix in another matrix format specified by OtherMatrix.\n    /**\n     * Note that OtherMatrix must be constructible from Matrix.\n     */\n    template <class OtherMatrix>\n    typename std::enable_if<!std::is_same<Matrix,OtherMatrix>::value, OtherMatrix>::type get() const { return OtherMatrix(A); }\n\n    /// compute \\f$b=Ax\\f$\n    void apply(Domain const& x, Range& b) const\n    {\n//      A.mv(x,b);\n            std::vector<Scalar> tmpx, tmpb;\n            domainToVector(x,tmpx);\n\n            A.mv(tmpx,tmpb);\n\n            vectorToRange(tmpb,b);\n    }\n\n    void applyTransposed(Range const& x, Domain& b) const\n    {\n//      A.mv(x,b);\n            std::vector<Scalar> tmpx, tmpb;\n            domainToVector(x,tmpx);\n\n            A.mtv(tmpx,tmpb);\n\n            vectorToRange(tmpb,b);\n    }\n\n    /// Access matrix via unique_ptr. Use if Matrix does not support move-semantics.\n    template <class OtherMatrix=Matrix> \n    typename std::enable_if<std::is_same<OtherMatrix,Matrix>::value,std::unique_ptr<Matrix> >::type getPointer() const\n    {\n      return std::unique_ptr<Matrix>(new Matrix(A));\n    }\n\n    /// Access matrix via unique_ptr. Use if Matrix does not support move-semantics.\n    template <class OtherMatrix> \n    typename std::enable_if<std::is_same<OtherMatrix,Dune::BCRSMatrix<Dune::FieldMatrix<Scalar,1,1> > >::value,std::unique_ptr<OtherMatrix> >::type getPointer() const\n    {\n      return A.toBCRS();\n    }\n\n    /// compute \\f$b=b+\\alpha Ax\\f$\n    void applyscaleadd(Scalar alpha, Domain const& x, Range& b) const\n    {\n//      A.usmv(alpha,x,b);\n            std::vector<Scalar> tmpx, tmpb;\n            domainToVector(x,tmpx);\n            rangeToVector(b,tmpb);\n\n            A.usmv(alpha,tmpx, tmpb);\n\n            vectorToRange(tmpb,b);\n    }\n\n    void applyscaleaddTransposed(Scalar alpha, Range const& x, Domain& b) const\n    {\n//      A.usmv(alpha,x,b);\n            std::vector<Scalar> tmpx, tmpb;\n            domainToVector(x,tmpx);\n            rangeToVector(b,tmpb);\n\n            A.usmtv(alpha,tmpx, tmpb);\n\n            vectorToRange(tmpb,b);\n    }\n    /// Get coefficient vector \\f$ \\mathrm{coefficients}\\in\\mathbb{K}^m\\f$ from \\f$y\\in Y\\f$.\n    /**\n     * Apply \\f$S_Y\\f$  to \\f$y\\in Y\\f$: \\f$\\mathrm{coefficients}=S_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> \n    void rangeToVector(Range const& y, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(y,coefficients);\n    }\n\n    /// Get coefficients vector \\f$\\mathrm{coefficients}\\in\\mathbb{K}^n\\f$ from \\f$x\\in X\\f$.\n    /**\n     * Apply \\f$S_X\\f$  to \\f$x\\in X\\f$: \\f$\\mathrm{coefficients}=S_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> \n    void domainToVector(Domain const& x, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(x, coefficients);\n    }\n\n    /// Get \\f$x\\in X\\f$ from coefficients vector \\f$\\mathrm{coefficients}\\in\\mathbb{K}^n\\f$\n    /**\n     * Apply \\f$S^{-1}_X\\f$ to \\f$\\mathrm{coefficients}\\f$: \\f$x=S^{-1}_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToDomain(Vector const& coefficients, Domain& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    /// Get \\f$y\\in Y\\f$ from coefficient vector \\f$\\mathrm{coefficients}\\in\\mathbb{K}^m\\f$\n    /**\n     * Apply \\f$S^{-1}_Y\\f$ to \\f$\\mathrm{coefficients}\\f$: \\f$x=S^{-1}_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToRange(Vector const& coefficients, Range& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    MatrixRepresentedOperator& operator=(MatrixRepresentedOperator const& other) = default;\n\n    MatrixRepresentedOperator& operator=(Matrix const& B)\n    {\n      A = B;   return *this;\n    }\n\n    MatrixRepresentedOperator& operator*= (Scalar alpha)\n    {\n      A *= alpha;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator/= (Scalar alpha)\n    {\n      A /= alpha;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator+= (MatrixRepresentedOperator const& B)\n    {\n      A += B;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator+= (Matrix const& B)\n    {\n      A += B;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator-= (MatrixRepresentedOperator const& B)\n    {\n      A -= B;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator-= (Matrix const& B)\n    {\n      A -= B;   return *this;\n    }\n\n  private:\n    Matrix A;\n  };\n\n  template <class MatrixBlock, class Allocator, class Domain_, class Range_>\n  class MatrixRepresentedOperator<Dune::BCRSMatrix<MatrixBlock,Allocator>,Domain_,Range_>\n      : public Dune::LinearOperator<Domain_,Range_>\n  {\n  public:\n    typedef Dune::BCRSMatrix<MatrixBlock,Allocator> Matrix;\n    typedef Domain_ Domain;\n    typedef Range_ Range;\n    typedef typename GetScalar<Domain>::type Scalar;\n\n    static int const category = Dune::SolverCategory::sequential;\n\n    MatrixRepresentedOperator() = default;\n\n    explicit MatrixRepresentedOperator(Matrix const& A_) : A(A_)\n    {}\n\n    explicit MatrixRepresentedOperator(Matrix&& A_) : A(A_)\n    {}\n\n    MatrixAsTriplet<Scalar> getTriplet() const { return get<MatrixAsTriplet<Scalar> >(); }\n\n    /// Access matrix\n    template <class OtherMatrix=Matrix>\n    typename std::enable_if<std::is_same<Matrix,OtherMatrix>::value, Matrix const&>::type get() const { return A; }\n\n    Matrix& get_non_const() { return A; }\n\n    /// Access matrix in another matrix format specified by OtherMatrix.\n    /**\n     * Note that OtherMatrix must be constructible from Matrix.\n     */\n    template <class OtherMatrix>\n    typename std::enable_if<!std::is_same<Matrix,OtherMatrix>::value, OtherMatrix>::type get() const { return OtherMatrix(A); }\n\n    /// compute \\f$b=Ax\\f$\n    void apply(Domain const& x, Range& b) const\n    {\n      A.mv(x,b);\n    }\n\n    void applyTransposed(Range const& x, Domain& b) const\n    {\n      A.mtv(x,b);\n    }\n\n    /// Access matrix via unique_ptr. Use if Matrix does not support move-semantics.\n    template <class OtherMatrix=Matrix>\n    typename std::enable_if<std::is_same<OtherMatrix,Matrix>::value,std::unique_ptr<Matrix> >::type getPointer() const\n    {\n      return std::unique_ptr<Matrix>(new Matrix(A));\n    }\n\n    /// Access matrix via unique_ptr. Use if Matrix does not support move-semantics.\n    template <class OtherMatrix>\n    typename std::enable_if<std::is_same<OtherMatrix,Dune::BCRSMatrix<Dune::FieldMatrix<Scalar,1,1> > >::value,std::unique_ptr<OtherMatrix> >::type getPointer() const\n    {\n      return A.toBCRS();\n    }\n\n    /// compute \\f$b=b+\\alpha Ax\\f$\n    void applyscaleadd(Scalar alpha, Domain const& x, Range& b) const\n    {\n      A.usmv(alpha,x,b);\n    }\n\n    void applyscaleaddTransposed(Scalar alpha, Range const& x, Domain& b) const\n    {\n      A.usmtv(alpha,x,b);\n    }\n\n    /// Get coefficient vector \\f$ \\mathrm{coefficients}\\in\\mathbb{K}^m\\f$ from \\f$y\\in Y\\f$.\n    /**\n     * Apply \\f$S_Y\\f$  to \\f$y\\in Y\\f$: \\f$\\mathrm{coefficients}=S_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> void rangeToVector(Range const& y, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(y,coefficients);\n    }\n\n    /// Get coefficients vector \\f$\\mathrm{coefficients}\\in\\mathbb{K}^n\\f$ from \\f$x\\in X\\f$.\n    /**\n     * Apply \\f$S_X\\f$  to \\f$x\\in X\\f$: \\f$\\mathrm{coefficients}=S_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> void domainToVector(Domain const& x, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(x, coefficients);\n    }\n\n    /// Get \\f$x\\in X\\f$ from coefficients vector \\f$\\mathrm{coefficients}\\in\\mathbb{K}^n\\f$\n    /**\n     * Apply \\f$S^{-1}_X\\f$ to \\f$\\mathrm{coefficients}\\f$: \\f$x=S^{-1}_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToDomain(Vector const& coefficients, Domain& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    /// Get \\f$y\\in Y\\f$ from coefficient vector \\f$\\mathrm{coefficients}\\in\\mathbb{K}^m\\f$\n    /**\n     * Apply \\f$S^{-1}_Y\\f$ to \\f$\\mathrm{coefficients}\\f$: \\f$x=S^{-1}_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToRange(Vector const& coefficients, Range& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    MatrixRepresentedOperator& operator=(MatrixRepresentedOperator const& other) = default;\n\n    MatrixRepresentedOperator& operator=(Matrix const& B)\n    {\n      A = B;   return *this;\n    }\n\n    MatrixRepresentedOperator& operator*= (Scalar alpha)\n    {\n      A *= alpha;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator/= (Scalar alpha)\n    {\n      A /= alpha;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator+= (MatrixRepresentedOperator const& B)\n    {\n      A += B;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator+= (Matrix const& B)\n    {\n      A += B;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator-= (MatrixRepresentedOperator const& B)\n    {\n      A -= B;   return *this;\n    }\n    \n    MatrixRepresentedOperator& operator-= (Matrix const& B)\n    {\n      A -= B;   return *this;\n    }\n    \n  private:\n    Matrix A;\n  };\n\n  //--------------------------------------------------------------------------------------------\n\n  /// \\cond internals\n  namespace IstlInterfaceDetail {\n\n\n    template <class Assembler,\n              int firstRow, int lastRow,\n              int firstCol, int lastCol,\n              bool symmetric=false>\n    struct Base\n    {\n      typedef typename Assembler::AnsatzVariableSet::template CoefficientVectorRepresentation<firstCol,lastCol>::type Domain;\n      typedef typename Assembler::TestVariableSet::template CoefficientVectorRepresentation<firstRow,lastRow>::type   Range;\n\n      static bool const inferredSymmetry = (lastRow-firstRow == lastCol-firstCol)              // make sure the number of domain/range variables is the same\n                                                &&\n                                                ((Assembler::Functional::type==VariationalFunctional       // a diagonally-centered block of a symmetric block matrix\n                                                    && firstRow==firstCol && lastRow==lastCol)\n                                                    || (firstRow+1==lastRow && firstCol+1==lastCol && false)); /* true if this one block is symmetric */  // TODO: implement the symmetry check\n\n      typedef typename std::conditional<symmetric,\n          SymmetricLinearOperator<Domain,Range>,\n          Dune::LinearOperator<Domain,Range>>::type type;\n    };\n  } // end of namespace IstlInterfaceDetail\n  /// \\endcond\n\n\n\n  /**\n   * \\ingroup linalg\n   * \\brief An adaptor presenting a Dune::LinearOperator <domain_type,range_type> interface to a\n   * contiguous sub-blockmatrix of an assembled heterogeneous Galerkin operator.\n   * \n   * \\tparam Assembler the \\ref VariationalFunctionalAssembler containing the Galerkin matrix\n   * \\tparam firstRow the first block row to be included\n   * \\tparam lastRow one behind the final row to be included (half-open range)\n   * \\tparam firstCol the first block column to be included\n   * \\tparam lastCol one behind the final column to be included (half-open range)\n   * \\tparam BlockFilter a boost::fusion predicate working on the assembler's matrix blocks, defining which blocks to include\n   * \\tparam symmetric whether the resulting operator is symmetric. The default is a conservative check whether the operator is symmetric or not.\n   *\n   * Due to data sharing, the GalerkinOperator is still valid\n   * even if the referenced assembler is deleted or otherwise\n   * invalidated. However, reassembling without invalidation of the\n   * assembler's data structures also modifies the values in the\n   * GalerkinOperator.\n   */\n  template <class Assembler_,\n            int firstRow=0, int lastRow=Assembler_::TestVariableSet::noOfVariables,\n            int firstCol=0, int lastCol=Assembler_::AnsatzVariableSet::noOfVariables,\n            class BlockFilter=IstlInterfaceDetail::RangeBlockSelector<firstRow,lastRow,firstCol,lastCol>,\n            bool symmetric=IstlInterfaceDetail::Base<Assembler_,firstRow,lastRow,firstCol,lastCol>::inferredSymmetry>\n  class AssembledGalerkinOperator: public IstlInterfaceDetail::Base<Assembler_,firstRow,lastRow,firstCol,lastCol,symmetric>::type\n  {\n  public:\n    typedef typename IstlInterfaceDetail::Base<Assembler_,firstRow,lastRow,firstCol,lastCol,symmetric>::type Base;\n    typedef Assembler_ Assembler;\n    typedef typename Assembler::AnsatzVariableSet::template CoefficientVectorRepresentation<firstCol,lastCol>::type Domain;\n    typedef typename Assembler::TestVariableSet::template CoefficientVectorRepresentation<firstRow,lastRow>::type   Range;\n    typedef typename Assembler::Scalar                                                                              Scalar;\n\n    typedef IstlInterfaceDetail::BlockInfo<firstRow,lastRow,firstCol,lastCol> BlockInfo;\n\n    // do we need this?\n    static int const category = Dune::SolverCategory::sequential;\n\n    /**\n     * \\brief Constructor.\n     * \\param op the variational assembler.\n     * \\param onlyLowerTriangle if true, only the lower triangle is returned if a matrix is requested\n     * \\param nThreads use given number of threads (or a machine-dependent default if nThreads<=0).\n     */\n    explicit AssembledGalerkinOperator(Assembler const& assembler_, bool onlyLowerTriangle_=false, int nThreads_=0):\n        onlyLowerTriangle(onlyLowerTriangle_),\n        assembler(assembler_),\n        blocks(boost::fusion::transform(boost::fusion::filter_if<BlockFilter>(IstlInterfaceDetail::AllBlocks<Assembler>::apply(assembler)),\n                                        IstlInterfaceDetail::Translate<firstRow,firstCol>(nThreads_))),\n        nThreads(nThreads_)\n    { }\n\n    virtual ~AssembledGalerkinOperator(){}\n\n    /// update operator if grid has changed or assemble(...) has been called.\n    void update()\n    {\n      blocks = boost::fusion::transform(boost::fusion::filter_if<BlockFilter>(IstlInterfaceDetail::AllBlocks<Assembler>::apply(assembler)),\n                                        IstlInterfaceDetail::Translate<firstRow,firstCol>(nThreads));\n    }\n\n    virtual MatrixAsTriplet<Scalar> getTriplet() const { return get<MatrixAsTriplet<Scalar> >(); }\n\n    /// Access matrix. Use if Matrix does support move-semantics.\n    template <class Matrix> \n    Matrix get() const\n    {\n      return assembler.template get<Matrix>(onlyLowerTriangle, firstRow, lastRow, firstCol, lastCol);\n    }\n\n    /// Access matrix via unique_ptr. Use if Matrix does not support move-semantics.\n    template <class Matrix> \n    std::unique_ptr<Matrix> getPointer() const\n    {\n      return assembler.template getPointer<Matrix,firstRow,lastRow,firstCol,lastCol>(onlyLowerTriangle);\n    }\n\n    /**\n     * \\brief returns a reference to the matrix\n     */\n    MatrixAsTriplet<Scalar> getmat() const __attribute__((deprecated));\n\n    /// Get coefficient vector \\f$coefficients\\in\\mathbb{K}^m\\f$ from \\f$y\\in Y\\f$.\n    /**\n     * Apply \\f$S_Y\\f$  to \\f$y\\in Y\\f$: \\f$coefficients=S_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> \n    void rangeToVector(Range const& y, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(y, coefficients);\n    }\n\n    /// Get coefficients vector \\f$coefficients\\in\\mathbb{K}^n\\f$ from \\f$x\\in X\\f$.\n    /**\n     * Apply \\f$S_X\\f$  to \\f$x\\in X\\f$: \\f$coefficients=S_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> \n    void domainToVector(Domain const& x, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(x, coefficients);\n    }\n\n    /// Get \\f$x\\in X\\f$ from coefficients vector \\f$coefficients\\in\\mathbb{K}^n\\f$\n    /**\n     * Apply \\f$S^{-1}_X\\f$ to \\f$coefficients\\f$: \\f$x=S^{-1}_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToDomain(Vector const& coefficients, Domain& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    /**\n     * \\brief Get \\f$ y\\in Y \\f$ from coefficient vector \\f$coefficients\\in\\mathbb{K}^m\\f$\n     * Apply \\f$S^{-1}_Y\\f$ to \\f$coefficients\\f$: \\f$x=S^{-1}_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToRange(Vector const& coefficients, Range& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    /// compute \\f$ b \\leftarrow Ax \\f$\n    virtual void apply(Domain const& x, Range& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      boost::fusion::for_each(blocks,ApplyScaleAdd(assembler,1.0,x,b,true));\n    }\n\n    void applyTransposed(Range const& x, Domain& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      boost::fusion::for_each(blocks,TransposedApplyScaleAdd(assembler,1.0,x,b,true));\n    }\n\n    /**\n     * \\brief Computes \\f$ b \\leftarrow Ax \\f$ and, in case \\f$ A \\f$ is symmetric, also \\f$ \\langle x, b \\rangle \\f$\n     * \n     * If \\f$ A \\f$ is not symmetric, zero is returned.\n     */\n    virtual Scalar applyDp(Domain const& x, Range& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      Scalar dp = 0;\n      boost::fusion::for_each(blocks,ApplyScaleAdd(assembler,1.0,x,b,true,&dp));\n      return symmetric? dp: 0;\n    }\n\n    virtual Scalar dp(Domain const& x, Range const& y) const\n    {\n      std::cerr << \"AssembledGalerkinOperator::dp not yet implemented!\\n\"; abort();\n      return 0; // TODO: fixme\n    }\n\n    /**\n     * \\brief  Compute \\f$b=b+\\alpha Ax\\f$\n     * Note that x and b must not refer to the same memory locations (in case Domain==Range).\n     */\n    virtual void applyscaleadd(Scalar alpha, Domain const& x, Range& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      boost::fusion::for_each(blocks,ApplyScaleAdd(assembler,alpha,x,b,false));\n    }\n\n    virtual void applyscaleaddTransposed(Scalar alpha, Range const& x, Domain& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      boost::fusion::for_each(blocks,TransposedApplyScaleAdd(assembler,alpha,x,b,false));\n    }\n\n    /**\n     * \\brief Provides access to the underlying assembler.\n     */\n    Assembler const& getAssembler() const \n    { \n      return assembler; \n    }\n\n    bool getOnlyLowerTriangle() const { return onlyLowerTriangle; }\n\n  protected:\n    typedef typename boost::fusion::result_of::as_vector<\n        typename IstlInterfaceDetail::AllBlocks<Assembler>::result\n        >::type allblocks;\n\n    typedef typename boost::fusion::result_of::as_vector<\n        typename boost::fusion::result_of::filter_if<allblocks,BlockFilter>::type\n        >::type filtered;\n\n    bool onlyLowerTriangle;\n    Assembler const& assembler;\n\n    typename boost::fusion::result_of::as_vector<\n    typename boost::fusion::result_of::transform<filtered,\n    IstlInterfaceDetail::Translate<firstRow,firstCol>>::type\n    >::type blocks;\n    bool isSymmetric;\n\n\n    struct ApplyScaleAdd \n    {\n      Assembler const& assembler;\n      // Constructs the functor for matrix-vector multiplication and addition. If init is true, the first block\n      // encountered in each row is called with apply (using alpha=1 and initializing the rhs to zero), otherwise\n      // applyscaleadd is used. This prevents a double access of the right hand side, first for setting to zero,\n      // then for adding the MV product.\n      ApplyScaleAdd(Assembler const& as, Scalar a_, Domain const& x_, Range& y_, bool init, Scalar* dp_=0): assembler(as), a(a_), x(x_), y(y_), dp(dp_? dp_: &dummy)\n      {\n        for (int i=0; i<lastRow; ++i)\n          doInit[i] = init;\n        *dp = 0;\n      }\n\n      template <class Block>\n      void operator()(Block const& b) const {\n        using namespace boost::fusion;\n\n        typename result_of::at_c<typename Domain::Functions const,Block::colId>::type xi = at_c<Block::colId>(x.data);\n        typename result_of::at_c<typename Range::Functions,Block::rowId>::type  yi = at_c<Block::rowId>(y.data);\n        if (!b.threadedMatrix.get())\n          abort();\n\n        if (doInit[Block::rowId])\n        {\n          *dp += b.threadedMatrix->mv(xi,yi);\n          doInit[Block::rowId] = false;\n        }\n        else\n          *dp += b.threadedMatrix->usmv(a,xi,yi);      \n\n        return;\n      }\n\n    private:\n      Scalar a;\n      Domain const& x;\n      Range& y;\n      Scalar* dp;\n      Scalar dummy;                 // something to point to in case no target pointer has been provided\n      mutable bool doInit[lastRow]; // ugly, but boost::fusion::for_each only works with const functors\n    };\n\n    struct TransposedApplyScaleAdd\n    {\n      Assembler const& assembler;\n      // Constructs the functor for matrix-vector multiplication and addition. If init is true, the first block\n      // encountered in each row is called with apply (using alpha=1 and initializing the rhs to zero), otherwise\n      // applyscaleadd is used. This prevents a double access of the right hand side, first for setting to zero,\n      // then for adding the MV product.\n      TransposedApplyScaleAdd(Assembler const& as, Scalar a_, Range const& x_, Domain& y_, bool init, Scalar* dp_=0): assembler(as), a(a_), x(x_), y(y_), dp(dp_? dp_: &dummy)\n      {\n        for (int i=0; i<lastCol; ++i)\n          doInit[i] = init;\n        *dp = 0;\n      }\n\n      template <class Block>\n      void operator()(Block const& b) const {\n        using namespace boost::fusion;\n\n        typename result_of::at_c<typename Range::Functions const,Block::rowId>::type xi = at_c<Block::rowId>(x.data);\n        typename result_of::at_c<typename Domain::Functions,Block::colId>::type  yi = at_c<Block::colId>(y.data);\n        if (!b.threadedMatrix.get())\n          abort();\n\n        if (doInit[Block::colId])\n        {\n          *dp += b.threadedMatrix->mv(xi,yi);\n          doInit[Block::colId] = false;\n        }\n        else\n          *dp += b.threadedMatrix->usmv(a,xi,yi);\n\n        return;\n      }\n\n    private:\n      Scalar a;\n      Range const& x;\n      Domain& y;\n      Scalar* dp;\n      Scalar dummy;                 // something to point to in case no target pointer has been provided\n      mutable bool doInit[lastCol]; // ugly, but boost::fusion::for_each only works with const functors\n    };\n\n    int nThreads;\n  };\n\n\n  /**\n   * \\todo docme\n   */\n  template <class NormalStepAssembler, class TangentialStepAssembler, int stateId=1, int controlId=0, int adjointId=2>\n  class LagrangeOperator: public Dune::LinearOperator<typename NormalStepAssembler::AnsatzVariableSet::template CoefficientVectorRepresentation<>::type,typename NormalStepAssembler::TestVariableSet::template CoefficientVectorRepresentation<>::type>\n  {\n    typedef typename NormalStepAssembler::AnsatzVariableSet::template CoefficientVectorRepresentation<>::type Domain;\n    typedef typename NormalStepAssembler::TestVariableSet::template CoefficientVectorRepresentation<>::type Range;\n    static constexpr int firstRow = 0;\n    static constexpr int firstCol = 0;\n    static constexpr int lastRow = NormalStepAssembler::TestVariableSet::noOfVariables;\n    static constexpr int lastCol = NormalStepAssembler::AnsatzVariableSet::noOfVariables;\n    typedef IstlInterfaceDetail::RangeBlockSelector<firstRow,lastRow,firstCol,lastCol> NormalStepBlockFilter;\n    typedef IstlInterfaceDetail::RangeBlockSelector<firstRow,adjointId,firstCol,adjointId> TangentialStepBlockFilter;\n\n  public:\n    typedef typename NormalStepAssembler::Scalar Scalar;\n    typedef MatrixAsTriplet<Scalar> Triplet;\n\n    typedef IstlInterfaceDetail::BlockInfo<firstRow,lastRow,firstCol,lastCol> BlockInfo;\n\n    static int const category = Dune::SolverCategory::sequential;\n\n    /**\n     * \\param op the variational assembler.\n     * \\param onlyLowerTriangle\n     * \\param nThreads use given number of threads (or a machine-dependent default if nThreads<=0).\n     */\n    LagrangeOperator(NormalStepAssembler const& normalStepAssembler_, TangentialStepAssembler const& tangentialStepAssembler_,  bool onlyLowerTriangle_=false, int nThreads_=0):\n      onlyLowerTriangle(onlyLowerTriangle_),\n      normalStepAssembler(normalStepAssembler_), tangentialStepAssembler(tangentialStepAssembler_),\n      normalStepBlocks(boost::fusion::transform(boost::fusion::filter_if<NormalStepBlockFilter>(IstlInterfaceDetail::AllBlocks<NormalStepAssembler>::apply(normalStepAssembler)),IstlInterfaceDetail::Translate<firstRow,firstCol>(nThreads_))),\n      tangentialStepBlocks(boost::fusion::transform(boost::fusion::filter_if<TangentialStepBlockFilter>(IstlInterfaceDetail::AllBlocks<TangentialStepAssembler>::apply(tangentialStepAssembler)),IstlInterfaceDetail::Translate<firstRow,firstCol>(nThreads_))),\n      nThreads(nThreads_)\n    {}\n\n    virtual ~LagrangeOperator(){}\n\n    /// update operator if grid has changed or assemble(...) has been called.\n    void update()\n    {\n      assert(false);\n      //      blocks = boost::fusion::transform(boost::fusion::filter_if<BlockFilter>(IstlInterfaceDetail::AllBlocks<Assembler>::apply(assembler)),\n      //          IstlInterfaceDetail::Translate<firstRow,firstCol>(nThreads));\n    }\n\n    virtual MatrixAsTriplet<Scalar> getTriplet() const\n    {\n      std::vector<size_t> offset(3,0);\n      Triplet result, tmp;\n      for(size_t i=0; i<3; ++i)\n      {\n        for(size_t j=0; j<3; ++j)\n        {\n          if(i==adjointId || j== adjointId || (i==controlId && j==controlId)) tmp = normalStepAssembler.template get<Triplet>(onlyLowerTriangle,i,i+1,j,j+1);\n          else tmp = tangentialStepAssembler.template get<Triplet>(onlyLowerTriangle,i,i+1,j,j+1);\n          tmp.shiftIndices(offset[i],offset[j]);\n          result += tmp;\n          if(i==0)\n          {\n            if(j==0) offset[1] = tmp.nrows();\n            if(j==1) offset[2] = tmp.nrows();\n          }\n        }\n      }\n\n      return result;\n    }\n\n    //    /// Access matrix. Use if Matrix does support move-semantics.\n    //    template <class Matrix> Matrix get() const\n    //    {\n    //      return assembler.template get<Matrix>(onlyLowerTriangle, firstRow, lastRow, firstCol, lastCol);\n    //    }\n\n    //    /// Access matrix via unique_ptr. Use if Matrix does not support move-semantics.\n    //    template <class Matrix> std::unique_ptr<Matrix> getPointer() const\n    //        {\n    //      return assembler.template getPointer<Matrix,firstRow,lastRow,firstCol,lastCol>(onlyLowerTriangle);\n    //  }\n\n    /**\n     * \\brief returns a reference to the matrix\n     */\n    //    MatrixAsTriplet<Scalar> getmat() const __attribute__((deprecated));\n\n    /// Get coefficient vector \\f$coefficients\\in\\mathbb{K}^m\\f$ from \\f$y\\in Y\\f$.\n    /**\n     * Apply \\f$S_Y\\f$  to \\f$y\\in Y\\f$: \\f$coefficients=S_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> void rangeToVector(Range const& y, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(y, coefficients);\n    }\n\n    /// Get coefficients vector \\f$coefficients\\in\\mathbb{K}^n\\f$ from \\f$x\\in X\\f$.\n    /**\n     * Apply \\f$S_X\\f$  to \\f$x\\in X\\f$: \\f$coefficients=S_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::iterator std::begin(Vector&);\n     */\n    template <class Vector> void domainToVector(Domain const& x, Vector& coefficients) const\n    {\n      IstlInterfaceDetail::toVector(x, coefficients);\n    }\n\n    /// Get \\f$x\\in X\\f$ from coefficients vector \\f$coefficients\\in\\mathbb{K}^n\\f$\n    /**\n     * Apply \\f$S^{-1}_X\\f$ to \\f$coefficients\\f$: \\f$x=S^{-1}_X(x)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToDomain(Vector const& coefficients, Domain& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    /**\n     * \\brief Get \\f$ y\\in Y \\f$ from coefficient vector \\f$coefficients\\in\\mathbb{K}^m\\f$\n     * Apply \\f$S^{-1}_Y\\f$ to \\f$coefficients\\f$: \\f$x=S^{-1}_Y(y)\\f$.\n     *\n     * The used vector type Vector must provide:\n     * - its iterator type via typename Vector::const_iterator\n     * - (possibly overloads of) the free functions:\n     *    - typename Vector::const_iterator std::begin(Vector const&);\n     */\n    template <class Vector>\n    void vectorToRange(Vector const& coefficients, Range& x) const\n    {\n      IstlInterfaceDetail::fromVector(coefficients, x);\n    }\n\n    /// compute \\f$ b \\leftarrow Ax \\f$\n    virtual void apply(Domain const& x, Range& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      boost::fusion::for_each(normalStepBlocks,NormalStepApplyScaleAdd(normalStepAssembler,1.0,x,b,true));\n      boost::fusion::for_each(tangentialStepBlocks,TangentialStepApplyScaleAdd(tangentialStepAssembler,1.0,x,b,false));\n    }\n\n    /**\n     * \\brief Computes \\f$ b \\leftarrow Ax \\f$ and, in case \\f$ A \\f$ is symmetric, also \\f$ \\langle x, b \\rangle \\f$\n     *\n     * If \\f$ A \\f$ is not symmetric, zero is returned.\n     */\n    virtual Scalar applyDp(Domain const& x, Range& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      std::cerr << \"AssembledGalerkinOperator::dp not yet implemented!\\n\"; abort();\n      return 0;\n    }\n\n    virtual Scalar dp(Domain const& x, Range const& y) const\n    {\n      std::cerr << \"AssembledGalerkinOperator::dp not yet implemented!\\n\"; abort();\n      return 0; // TODO: fixme\n    }\n\n    /**\n     * \\brief  Compute \\f$b=b+\\alpha Ax\\f$\n     * Note that x and b must not refer to the same memory locations (in case Domain==Range).\n     */\n    virtual void applyscaleadd(Scalar alpha, Domain const& x, Range& b) const\n    {\n      assert(static_cast<void const*>(&x) != static_cast<void const*>(&b));\n      boost::fusion::for_each(normalStepBlocks,NormalStepApplyScaleAdd(normalStepAssembler,1.0,x,b,false));\n      boost::fusion::for_each(tangentialStepBlocks,TangentialStepApplyScaleAdd(tangentialStepAssembler,1.0,x,b,false));\n    }\n\n    /**\n     * \\brief Provides access to the underlying assembler.\n     */\n    //    Assembler const& getAssembler() const\n    //    {\n    //      return assembler;\n    //    }\n    //\n    //    bool getOnlyLowerTriangle() const { return onlyLowerTriangle; }\n\n  protected:\n    typedef typename IstlInterfaceDetail::AllBlocks<NormalStepAssembler>::result AllNormalStepBlocksSeq;\n    typedef typename IstlInterfaceDetail::AllBlocks<TangentialStepAssembler>::result AllTangentialStepBlocksSeq;\n    typedef typename boost::fusion::result_of::filter_if<AllNormalStepBlocksSeq,NormalStepBlockFilter>::type FilteredNormalStepBlocksSeq;\n    typedef typename boost::fusion::result_of::filter_if<AllTangentialStepBlocksSeq,TangentialStepBlockFilter>::type FilteredTangentialStepBlocksSeq;\n\n    typedef typename boost::fusion::result_of::as_vector<AllNormalStepBlocksSeq>::type AllNormalStepBlocks;\n    typedef typename boost::fusion::result_of::as_vector<AllTangentialStepBlocksSeq>::type AllTangentialStepBlocks;\n    typedef typename boost::fusion::result_of::as_vector<FilteredNormalStepBlocksSeq>::type FilteredNormalStepBlocks;\n    typedef typename boost::fusion::result_of::as_vector<FilteredTangentialStepBlocksSeq>::type FilteredTangentialStepBlocks;\n\n    typedef typename boost::fusion::result_of::as_vector<typename boost::fusion::result_of::transform<FilteredNormalStepBlocks,IstlInterfaceDetail::Translate<firstRow,firstCol>>::type>::type NormalBlocks;\n    typedef typename boost::fusion::result_of::as_vector<typename boost::fusion::result_of::transform<FilteredTangentialStepBlocks,IstlInterfaceDetail::Translate<0,0>>::type>::type TangentialBlocks;\n\n    bool onlyLowerTriangle;\n    NormalStepAssembler const& normalStepAssembler;\n    TangentialStepAssembler const& tangentialStepAssembler;\n\n    NormalBlocks  normalStepBlocks;\n    TangentialBlocks tangentialStepBlocks;\n\n    bool isSymmetric;\n    int nThreads;\n\n    struct NormalStepApplyScaleAdd\n    {\n      NormalStepAssembler const& assembler;\n      // Constructs the functor for matrix-vector multiplication and addition. If init is true, the first block\n      // encountered in each row is called with apply (using alpha=1 and initializing the rhs to zero), otherwise\n      // applyscaleadd is used. This prevents a double access of the right hand side, first for setting to zero,\n      // then for adding the MV product.\n      NormalStepApplyScaleAdd(NormalStepAssembler const& as, Scalar a_, Domain const& x_, Range& y_, bool init, Scalar* dp_=0): assembler(as), a(a_), x(x_), y(y_), dp(dp_? dp_: &dummy)\n      {\n        for (int i=0; i<lastRow; ++i)\n          doInit[i] = init;\n        *dp = 0;\n      }\n\n      template <class Block>\n      void operator()(Block const& b) const {\n        if( ( (Block::rowId==stateId && Block::colId==stateId) || (Block::rowId==stateId && Block::colId==controlId) || (Block::colId==stateId && Block::rowId==controlId) ) ) return;\n//        if( (Block::rowId==stateId && Block::colId==stateId) ) return;\n        using namespace boost::fusion;\n\n        typename result_of::at_c<typename Domain::Functions const,Block::colId>::type xi = at_c<Block::colId>(x.data);\n        typename result_of::at_c<typename Range::Functions,Block::rowId>::type  yi = at_c<Block::rowId>(y.data);\n        if (!b.threadedMatrix.get())\n          abort();\n\n        if (doInit[Block::rowId])\n        {\n          *dp += b.threadedMatrix->mv(xi,yi);\n          doInit[Block::rowId] = false;\n        }\n        else\n          *dp += b.threadedMatrix->usmv(a,xi,yi);\n\n        return;\n      }\n\n    private:\n      Scalar a;\n      Domain const& x;\n      Range& y;\n      Scalar* dp;\n      Scalar dummy;                 // something to point to in case no target pointer has been provided\n      mutable bool doInit[lastRow]; // ugly, but boost::fusion::for_each only works with const functors\n    };\n\n\n    struct TangentialStepApplyScaleAdd\n    {\n      TangentialStepAssembler const& assembler;\n      // Constructs the functor for matrix-vector multiplication and addition. If init is true, the first block\n      // encountered in each row is called with apply (using alpha=1 and initializing the rhs to zero), otherwise\n      // applyscaleadd is used. This prevents a double access of the right hand side, first for setting to zero,\n      // then for adding the MV product.\n      TangentialStepApplyScaleAdd(TangentialStepAssembler const& as, Scalar a_, Domain const& x_, Range& y_, bool init, Scalar* dp_=0): assembler(as), a(a_), x(x_), y(y_), dp(dp_? dp_: &dummy)\n      {\n        for (int i=0; i<lastRow; ++i)\n          doInit[i] = init;\n        *dp = 0;\n      }\n\n      template <class Block>\n      void operator()(Block const& b) const {\n        if( !( (Block::rowId==stateId && Block::colId==stateId) || (Block::rowId==stateId && Block::colId==controlId) || (Block::colId==stateId && Block::rowId==controlId) ) ) return;\n        using namespace boost::fusion;\n\n        typename result_of::at_c<typename Domain::Functions const,Block::colId>::type xi = at_c<Block::colId>(x.data);\n        typename result_of::at_c<typename Range::Functions,Block::rowId>::type  yi = at_c<Block::rowId>(y.data);\n        if (!b.threadedMatrix.get())\n          abort();\n\n        if (doInit[Block::rowId])\n        {\n          *dp += b.threadedMatrix->mv(xi,yi);\n          doInit[Block::rowId] = false;\n        }\n        else\n          *dp += b.threadedMatrix->usmv(a,xi,yi);\n\n        return;\n      }\n\n    private:\n      Scalar a;\n      Domain const& x;\n      Range& y;\n      Scalar* dp;\n      Scalar dummy;                 // something to point to in case no target pointer has been provided\n      mutable bool doInit[lastRow]; // ugly, but boost::fusion::for_each only works with const functors\n    };\n  };\n\n  template <class Operator>\n  class TransposedOperator : public Dune::LinearOperator<typename Operator::Range,typename Operator::Domain>\n  {\n  public:\n    typedef typename Operator::Scalar Scalar;\n    typedef typename Operator::Range Domain;\n    typedef typename Operator::Domain Range;\n    typedef typename Operator::Assembler Assembler;\n\n    explicit TransposedOperator(Operator const& A_) : A(A_.getTriplet().transpose()){}\n\n    virtual ~TransposedOperator(){}\n\n    virtual void apply(Domain const& x, Range& b) const\n    {\n      A.apply(x,b);\n    }\n\n    virtual void applyscaleadd(Scalar alpha, Domain const& x, Range& b) const\n    {\n      A.applyscaleadd(alpha,x,b);\n    }\n\n    MatrixAsTriplet<Scalar> getTriplet() const { return A.getTriplet(); }\n\n  private:\n    MatrixRepresentedOperator<MatrixAsTriplet<double>,Domain,Range> A;\n  };\n\n} // end of namespace Kaskade\n\n#endif\n", "meta": {"hexsha": "52c5b20a9d09abc09d73738aaec51a5c1837b167", "size": 51738, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/istlinterface.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/istlinterface.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/istlinterface.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": 38.3528539659, "max_line_length": 256, "alphanum_fraction": 0.6490200626, "num_tokens": 12838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111085480195975, "lm_q2_score": 0.037892425543116344, "lm_q1q2_score": 0.015577987455550174}}
{"text": "//\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n\n\n#include \"Geomlib_TriMeshEdgeSplit.h\"\n\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Core>\n\n#pragma warning(push, 0)\n#include <igl/edge_flaps.h>\n#include <igl/is_edge_manifold.h>\n#include <igl/is_vertex_manifold.h>\n#include <igl/is_border_vertex.h>\n#pragma warning(pop)\n\n#include <Urho3D/IO/Log.h>\n\n#include \"TriMesh.h\"\n#include \"ConversionUtilities.h\"\n\n#pragma warning(disable : 4244)\n\nusing Urho3D::Variant;\n\nnamespace {\n\n/*==============================================================================\nASSUMPTIONS:\nOriginal mesh was OV, OF, OE, EMAP.\nLooped over edges in OE, and edges to be split were marked.\nSizes of new vertex and face matrices were determined, and\nV, F, E were initialized to the right size, matching OV, OF, OE in\ntheir starting blocks.\n\ne:       index into OE of original edge to split\ni:       e is the ith edge to be split (starting at 0)\nV, F, E: partially updated matrices before edge e is split\n\nOutputs:\nV, F, E: partially updated matrices after edge e is split\n==============================================================================*/\nvoid split_edge(\n\tint e,\n\tint count,\n\tint orig_vcount,\n\tint orig_fcount,\n\tint orig_ecount,\n\tEigen::MatrixXf& V,\n\tEigen::MatrixXi& F,\n\tEigen::MatrixXi& E,\n\tEigen::MatrixXi& EMAP,\n\tEigen::MatrixXi& EF,\n\tEigen::MatrixXi& EI\n)\n{\n\tint i = E(e, 0);\n\tint j = E(e, 1);\n\n\tint f0 = EF(e, 0); // face opposite e=(i-->j)\n\tint f1 = EF(e, 1); // face opposite e=(j-->i)\n\n\tint k = F(f0, EI(e, 0));\n\tint l = F(f1, EI(e, 1));\n\n\tint r = orig_vcount + count;\n\tV.row(r) = 0.5f * (V.row(i) + V.row(j));\n\n\tint f = orig_fcount + 2 * count;\n\t// update row f0\n\tint v = EI(e, 0);\n\tint ejtok = EMAP(f0, (v + 1) % 3);\n\tF(f0, (v + 2) % 3) = r;\n\t// update row f1\n\tint w = EI(e, 1);\n\tint eltoj = EMAP(f1, (w + 2) % 3);\n\n\tF(f1, (w + 1) % 3) = r;\n\t// fill row f\n\tF.row(f) = Eigen::RowVector3i(j, k, r);\n\t// fill row f + 1\n\tF.row(f + 1) = Eigen::RowVector3i(l, j, r);\n\n\tint s = orig_ecount + 3 * count;\n\t// update row e from e=(i-->j) to e=(i-->r)\n\tE(e, 1) = r;\n\t// fill row s with (r-->j)\n\tE.row(s) = Eigen::RowVector2i(r, j);\n\t// fill row s + 1\n\tE.row(s + 1) = Eigen::RowVector2i(k, r);\n\t// fill row s + 2\n\tE.row(s + 2) = Eigen::RowVector2i(r, l);\n\n\t// EF\n\t// EF.row(e) does not require update\n\t// s=(r-->j)\n\tEF.row(s) = Eigen::RowVector2i(f + 1, f);\n\tEF.row(s + 1) = Eigen::RowVector2i(f, f0);\n\tEF.row(s + 2) = Eigen::RowVector2i(f + 1, f1);\n\n\tif (EF(ejtok, 0) == f0) {\n\t\tEF(ejtok, 0) = f;\n\t\tEI(ejtok, 0) = 2;\n\t}\n\telse {\n\t\tEF(ejtok, 1) = f;\n\t\tEI(ejtok, 1) = 2;\n\t}\n\tif (EF(eltoj, 0) == f1) {\n\t\tEF(eltoj, 0) = f + 1;\n\t\tEI(eltoj, 0) = 2;\n\t}\n\telse {\n\t\tEF(eltoj, 1) = f + 1;\n\t\tEI(eltoj, 1) = 2;\n\t}\n\n\t// s used for EI\n\t// EI.row(e) does not require update\n\tEI.row(s) = Eigen::RowVector2i(1, 0); // refers to lines 65, 67 respectively\n\tEI.row(s + 1) = Eigen::RowVector2i(0, (v + 1) % 3);\n\tEI.row(s + 2) = Eigen::RowVector2i(1, (w + 2) % 3);\n\n\t// where it used to say j->k should now be r->k i.e. edge s+1\n\tEMAP(f0, (v + 1) % 3) = s + 1;\n\t// where it used to say l->j should now be l->r i.e. edge s+2\n\tEMAP(f1, (w + 2) % 3) = s + 2;\n\t// ? is j-->k\n\tEMAP.row(f) = Eigen::RowVector3i(s + 1, s, ejtok);\n\t// ? is l-->j\n\tEMAP.row(f + 1) = Eigen::RowVector3i(s, s + 2, eltoj);\n}\n\nvoid split_edges_above_length(\n\tconst Eigen::MatrixXf& OV,\n\tconst Eigen::MatrixXi& OF,\n\tEigen::MatrixXf& NV,\n\tEigen::MatrixXi& NF,\n\tfloat L\n)\n{\n\tEigen::MatrixXi OE, EF, EI;\n\tEigen::VectorXi EMAP;\n\n\tigl::edge_flaps(OF, OE, EMAP, EF, EI);\n\tEigen::MatrixXi NE = OE;\n\n\tNV = OV;\n\tNF = OF;\n\n\t/***********************/\n\n\tstd::vector<bool> border_verts = igl::is_border_vertex(NV, NF);\n\n\t/***********************/\n\n\tstd::vector<int> edges_to_split;\n\n\tfor (int e = 0; e < OE.rows(); ++e) {\n\n\t\tbool totally_interior_edge = false;\n\t\tif (\n\t\t\tborder_verts[OE(e, 0)] == false &&\n\t\t\tborder_verts[OE(e, 1)] == false\n\t\t\t)\n\t\t{\n\t\t\ttotally_interior_edge = true;\n\t\t}\n\n\t\t// after we see if this is faster, convert to SQUAREDNORM!\n\t\tfloat len = (OV.row(OE(e, 0)) - OV.row(OE(e, 1))).norm();\n\t\tif (len > L && totally_interior_edge) {\n\t\t\tedges_to_split.push_back(e);\n\t\t}\n\t}\n\n\tint split_count = edges_to_split.size();\n\n\t/***********************/\n\n\tint orig_vcount = NV.rows();\n\tint orig_fcount = NF.rows();\n\tint orig_ecount = NE.rows();\n\n\tNV.conservativeResize(NV.rows() + split_count, Eigen::NoChange);\n\tNF.conservativeResize(NF.rows() + 2 * split_count, Eigen::NoChange);\n\tNE.conservativeResize(NE.rows() + 3 * split_count, Eigen::NoChange);\n\tEF.conservativeResize(EF.rows() + 3 * split_count, Eigen::NoChange);\n\tEI.conservativeResize(EI.rows() + 3 * split_count, Eigen::NoChange);\n\n\tEigen::MatrixXi NEMAP(NF.rows(), 3);\n\tNEMAP.block(0, 0, OF.rows(), 1) = EMAP.block(0, 0, OF.rows(), 1);\n\tNEMAP.block(0, 1, OF.rows(), 1) = EMAP.block(OF.rows(), 0, OF.rows(), 1);\n\tNEMAP.block(0, 2, OF.rows(), 1) = EMAP.block(2 * OF.rows(), 0, OF.rows(), 1);\n\n\tfor (int count = 0; count < edges_to_split.size(); ++count) {\n\t\tint e = edges_to_split[count];\n\t\tsplit_edge(\n\t\t\te,\n\t\t\tcount,\n\t\t\torig_vcount,\n\t\t\torig_fcount,\n\t\t\torig_ecount,\n\t\t\tNV,\n\t\t\tNF,\n\t\t\tNE,\n\t\t\tNEMAP,\n\t\t\tEF,\n\t\t\tEI\n\t\t);\n\t}\n}\n\n} // namespace\n\nUrho3D::Variant Geomlib::TriMesh_SplitLongEdges(\n\tconst Urho3D::Variant& tri_mesh,\n\tfloat split_threshold\n)\n{\n\tif (!TriMesh_Verify(tri_mesh)) {\n\t\treturn Variant();\n\t}\n\n\tEigen::MatrixXf V, NV;\n\tEigen::MatrixXi F, NF;\n\tbool igl_success = IglMeshToMatrices(tri_mesh, V, F);\n\tif (!igl_success) {\n\t\treturn Variant();\n\t}\n\n\tif (!igl::is_edge_manifold(F)) {\n\t\treturn Variant();\n\t}\n\n\tEigen::VectorXi B;\n\tif (!igl::is_vertex_manifold(F, B)) {\n\t\tURHO3D_LOGINFO(\"TriMeshEdgeSplit --- not a vertex manifold, exiting\");\n\t\treturn Variant();\n\t}\n\n\tsplit_edges_above_length(V, F, NV, NF, split_threshold);\n\n\treturn TriMesh_Make(NV, NF);\n}", "meta": {"hexsha": "d9de7850d3fe57cea4fecca699e9005cab746c01", "size": 6835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_TriMeshEdgeSplit.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_TriMeshEdgeSplit.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_TriMeshEdgeSplit.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 25.7924528302, "max_line_length": 80, "alphanum_fraction": 0.6215069495, "num_tokens": 2295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.03514484854829155, "lm_q1q2_score": 0.015522530891951982}}
{"text": "#include \"RBGL.hpp\"\n#include <boost/graph/isomorphism.hpp>\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n#include <boost/graph/bandwidth.hpp>\n#include <boost/graph/profile.hpp>\n#include <boost/graph/wavefront.hpp>\n#include <boost/graph/minimum_degree_ordering.hpp>\n#include <boost/graph/sloan_ordering.hpp>\n#include <boost/graph/king_ordering.hpp>\n\nextern \"C\"\n{\n\t// These are more easily done in R alone, no point to use BGL\n\t// copy_graph\n\t// transpose_graph\n\n\tSEXP BGL_isomorphism(\n\t\tSEXP num_verts_in1, SEXP num_edges_in1, SEXP R_edges_in1,  \n\t\tSEXP num_verts_in2, SEXP num_edges_in2, SEXP R_edges_in2\n\t\t\t )\n\t{\n\t\tusing namespace boost;\n\n\t\tbool r = FALSE;\n\n\t\tconst int NV1 = Rf_asInteger(num_verts_in1);\n\t\tconst int NV2 = Rf_asInteger(num_verts_in2);\n\t\tconst int NE1 = Rf_asInteger(num_edges_in1);\n\t\tconst int NE2 = Rf_asInteger(num_edges_in2);\n\n\t\tif ( NV1 == NV2 )\n\t\t{\n\t\ttypedef adjacency_list < vecS, listS, undirectedS,\n\t\t\tproperty < vertex_index_t, int> > VEGraph;\n\n\t\tVEGraph g1(NV1), g2(NV2);\n\n\t\tstd::vector<graph_traits<VEGraph>::vertex_descriptor> v1(NV1), v2(NV2);\n\t\tproperty_map<VEGraph, vertex_index_t>::type\n\t\t\tv1_index_map = get(vertex_index, g1),\n\t\t\tv2_index_map = get(vertex_index, g2);\n\n\t\tgraph_traits<VEGraph>::vertex_iterator i, end;\n\t\tint id = 0;\n\t\tfor (tie(i, end) = vertices(g1); i != end; ++i, ++id) \n\t\t{\n\t\t      put(v1_index_map, *i, id);\n\t\t      v1[id] = *i;\n\t\t}\n\t\tid = 0;\n\t\tfor (tie(i, end) = vertices(g2); i != end; ++i, ++id) \n\t\t{\n\t\t      put(v2_index_map, *i, id);\n\t\t      v2[id] = *i;\n\t\t}\n\t\t\n\t\tint* edges_in = INTEGER(R_edges_in1);\n\t\tfor ( int i = 0; i < NE1; i++, edges_in += 2 )\n\t\t\tadd_edge(v1[*edges_in], v1[*(edges_in+1)], g1);\n\t\t\n\t\tedges_in = INTEGER(R_edges_in2);\n\t\tfor ( int i = 0; i < NE2; i++, edges_in += 2 )\n\t\t\tadd_edge(v2[*edges_in], v2[*(edges_in+1)], g2);\n\t\t\n\t\tstd::vector<graph_traits<VEGraph>::vertex_descriptor> f(NV1);\n\n\t\tsignal(SIGABRT, sigabrt_handler);\n\t\tr = isomorphism(g1, g2, isomorphism_map \n\t\t\t(make_iterator_property_map(f.begin(), v1_index_map, f[0])));\n\t\t}\n\t\tsignal(SIGABRT, SIG_DFL);\n\n\t\tSEXP ansList, conn;\n\t\tPROTECT(ansList = Rf_allocVector(VECSXP,1));\n\t\tPROTECT(conn = Rf_allocVector(LGLSXP, 1));\n\n\t\tLOGICAL(conn)[0] = r;\n\n\t\tSET_VECTOR_ELT(ansList,0,conn);\n\t\tUNPROTECT(2);\n\t\treturn(ansList);\n\t}\n\n\tSEXP BGL_cuthill_mckee_ordering(SEXP num_verts_in, SEXP num_edges_in,\n                         SEXP R_edges_in)\n\t{\n\t\tusing namespace boost;\n\n\t\ttypedef graph_traits<Graph_ud>::vertex_descriptor Vertex;\n\t\ttypedef graph_traits<Graph_ud>::vertices_size_type size_type;\n\n\t\tconst int N = Rf_asInteger(num_verts_in);\n\t\tstd::vector<Vertex>    inv_perm(N);\n\t\tstd::vector<size_type> perm(N);\n\n\t\tGraph_ud g(num_verts_in, num_edges_in, R_edges_in);\n\n\t\tcuthill_mckee_ordering(g, inv_perm.rbegin(), get(vertex_color, g), make_degree_map(g));\n\n\t\tSEXP ansList, invpermList, robw, rbw;\n\t\tPROTECT(ansList = Rf_allocVector(VECSXP,3));\n\t\tPROTECT(invpermList = Rf_allocVector(INTSXP,N));\n\t\tPROTECT(robw = Rf_allocVector(INTSXP, 1));\n\t\tPROTECT(rbw = Rf_allocVector(INTSXP, 1));\n\n\t\tproperty_map<Graph_ud, vertex_index_t>::type index_map = get(vertex_index, g);\n\t\tstd::vector<Vertex>::const_iterator i;\n\t\tint j = 0;\n\n\t\tfor ( i = inv_perm.begin(); i != inv_perm.end(); i++ )\n\t\t\tINTEGER(invpermList)[j++] = index_map[*i];\n\t\tfor ( size_type c = 0; c != inv_perm.size(); ++c )\n\t\t\tperm[index_map[inv_perm[c]]] = c;\n\n\t\tINTEGER(robw)[0] = bandwidth(g);\n\t\tINTEGER(rbw)[0] = bandwidth(g, make_iterator_property_map(&perm[0], index_map, perm[0]));\n\n\t\tSET_VECTOR_ELT(ansList,0,invpermList);\n\t\tSET_VECTOR_ELT(ansList,1,robw);\n\t\tSET_VECTOR_ELT(ansList,2,rbw);\n\n\t\tUNPROTECT(4);\n\t\treturn(ansList);\n\t}\n\n\tSEXP BGL_min_degree_ordering(SEXP num_verts_in, SEXP num_edges_in,\n                         SEXP R_edges_in,   SEXP R_delta)\n\t{\n\t\tusing namespace boost;\n\n\t\tint delta = Rf_asInteger(R_delta);\n\t\tconst int NV = Rf_asInteger(num_verts_in);\n\t\ttypedef graph_traits<Graph_dd>::vertex_descriptor Vertex;\n\t\tGraph_dd g(num_verts_in, num_edges_in, R_edges_in);\n\t\tstd::vector<int> inverse_perm(NV, 0);\n\t\tstd::vector<int> perm(NV, 0);\n\t\tstd::vector<int> degree(NV, 0);\n\t\tstd::vector<int> supernode_sizes(NV, 1);\n\t\tproperty_map<Graph_dd, vertex_index_t>::type id = get(vertex_index, g);\n\n\t\tminimum_degree_ordering(g, \n\t\t\tmake_iterator_property_map(&degree[0], id, degree[0]), \n\t\t\t&inverse_perm[0], \n\t\t\t&perm[0], \n\t\t\tmake_iterator_property_map(&supernode_sizes[0], id, supernode_sizes[0]), \n\t\t\tdelta, id);\n\n\t\tSEXP ansList, invpermList, permList;\n\t\tPROTECT(ansList = Rf_allocVector(VECSXP,2));\n\t\tPROTECT(invpermList = Rf_allocVector(INTSXP,NV));\n\t\tPROTECT(permList = Rf_allocVector(INTSXP,NV));\n\n\t\tstd::vector<int>::const_iterator i;\n\t\tint j = 0;\n\n\t\tfor ( i = inverse_perm.begin(); i != inverse_perm.end(); i++ )\n\t\t\tINTEGER(invpermList)[j++] = inverse_perm[*i];\n\n\t\tj = 0;\n\t\tfor ( i = perm.begin(); i != perm.end(); i++ )\n\t\t\tINTEGER(permList)[j++] = perm[*i];\n\n\t\tSET_VECTOR_ELT(ansList,0,invpermList);\n\t\tSET_VECTOR_ELT(ansList,1,permList);\n\t\tUNPROTECT(3);\n\t\treturn(ansList);\n\t}\n\n\tSEXP BGL_king_ordering(SEXP num_verts_in, SEXP num_edges_in,\n                         SEXP R_edges_in,   SEXP R_delta)\n\t{\n\t\tusing namespace boost;\n\n\t\t//int delta = Rf_asInteger(R_delta);\n\t\tconst int NV = Rf_asInteger(num_verts_in);\n\t\ttypedef graph_traits<Graph_dd>::vertex_descriptor Vertex;\n\t\tGraph_dd g(num_verts_in, num_edges_in, R_edges_in);\n\t\tstd::vector<int> inverse_perm(NV, 0);\n\t\tstd::vector<int> perm(NV, 0);\n\t\tstd::vector<int> degree(NV, 0);\n\t\tstd::vector<int> supernode_sizes(NV, 1);\n\t\tproperty_map<Graph_dd, vertex_index_t>::type id = get(vertex_index, g);\n\n                // TODO: fill in\n/*\n\t\tking_ordering(g, \n\t\t\tmake_iterator_property_map(&degree[0], id, degree[0]), \n\t\t\t&inverse_perm[0], \n\t\t\t&perm[0], \n\t\t\tmake_iterator_property_map(&supernode_sizes[0], id, supernode_sizes[0]), \n\t\t\tdelta, id);\n*/\n\n\t\tSEXP ansList, invpermList, permList;\n\t\tPROTECT(ansList = Rf_allocVector(VECSXP,2));\n\t\tPROTECT(invpermList = Rf_allocVector(INTSXP,NV));\n\t\tPROTECT(permList = Rf_allocVector(INTSXP,NV));\n\n\t\tstd::vector<int>::const_iterator i;\n\t\tint j = 0;\n\n\t\tfor ( i = inverse_perm.begin(); i != inverse_perm.end(); i++ )\n\t\t\tINTEGER(invpermList)[j++] = inverse_perm[*i];\n\n\t\tj = 0;\n\t\tfor ( i = perm.begin(); i != perm.end(); i++ )\n\t\t\tINTEGER(permList)[j++] = perm[*i];\n\n\t\tSET_VECTOR_ELT(ansList,0,invpermList);\n\t\tSET_VECTOR_ELT(ansList,1,permList);\n\t\tUNPROTECT(3);\n\t\treturn(ansList);\n\t}\n\n\tSEXP BGL_sloan_ordering(SEXP num_verts_in, SEXP num_edges_in,\n                     SEXP R_edges_in, SEXP R_W1, SEXP R_W2 )\n\t{\n\t\tusing namespace boost;\n\n\t\tconst int NV = Rf_asInteger(num_verts_in);\n\t\tconst int NE = Rf_asInteger(num_edges_in);\n\t\tconst int W1 = Rf_asInteger(R_W1);\n\t\tconst int W2 = Rf_asInteger(R_W2);\n\n\t\ttypedef adjacency_list< setS, vecS, undirectedS, \n\t\t    property< vertex_color_t, default_color_type,\n\t\t    property< vertex_degree_t, int,\n\t\t    property< vertex_priority_t, double > > > > IGraph;\n\n\t\ttypedef graph_traits<IGraph>::vertex_descriptor Vertex;\n\t\ttypedef graph_traits<IGraph>::vertices_size_type size_type;\n\t\ttypedef std::pair<std::size_t, std::size_t> Pair;\n\n\t\tIGraph g(NV);\n\n\t\tint* edges_in = INTEGER(R_edges_in);\n\t\tfor ( int i = 0; i < NE; i++, edges_in += 2 )\n\t\t\tadd_edge(*edges_in, *(edges_in+1), g);\n\t\t\n\t\tproperty_map<IGraph, vertex_index_t>::type index_map = get(vertex_index, g);\n\n\t\tstd::vector<Vertex>    sloan_order(NV);\n\t\tstd::vector<size_type> perm(NV);\n\n\t\tsloan_ordering(g, sloan_order.begin(), get(vertex_color, g), \n\t\t\tmake_degree_map(g), get(vertex_priority, g), W1, W2);\n\n\t\tSEXP ansList, sList, rbw, rpf, rmw, raw, rrw;\n\t\tPROTECT(ansList = Rf_allocVector(VECSXP,6));\n\t\tPROTECT(sList = Rf_allocVector(INTSXP,NV));\n\t\tPROTECT(rbw = Rf_allocVector(INTSXP, 1));\n\t\tPROTECT(rpf = Rf_allocVector(INTSXP, 1));\n\t\tPROTECT(rmw = Rf_allocVector(INTSXP, 1));\n\t\tPROTECT(raw = Rf_allocVector(REALSXP, 1));\n\t\tPROTECT(rrw = Rf_allocVector(REALSXP, 1));\n\n\t\tstd::vector<Vertex>::const_iterator i;\n\t\tint j = 0;\n\n\t\tfor ( i = sloan_order.begin(); i != sloan_order.end(); i++ )\n\t\t\tINTEGER(sList)[j++] = index_map[*i];\n\n\t\tfor ( size_type c = 0; c != sloan_order.size(); ++c )\n\t\t\tperm[index_map[sloan_order[c]]] = c;\n\n\t\tINTEGER(rbw)[0] = bandwidth(g, make_iterator_property_map(&perm[0], index_map, perm[0]));\n\t\tINTEGER(rpf)[0] = profile(g, make_iterator_property_map(&perm[0], index_map, perm[0]));\n\t\tINTEGER(rmw)[0] = max_wavefront(g, make_iterator_property_map(&perm[0], index_map, perm[0]));\n\t\tREAL(raw)[0] = aver_wavefront(g, make_iterator_property_map(&perm[0], index_map, perm[0]));\n\t\tREAL(rrw)[0] = rms_wavefront(g, make_iterator_property_map(&perm[0], index_map, perm[0]));\n\n\t\tSET_VECTOR_ELT(ansList,0,sList);\n\t\tSET_VECTOR_ELT(ansList,1,rbw);\n\t\tSET_VECTOR_ELT(ansList,2,rpf);\n\t\tSET_VECTOR_ELT(ansList,3,rmw);\n\t\tSET_VECTOR_ELT(ansList,4,raw);\n\t\tSET_VECTOR_ELT(ansList,5,rrw);\n\n\t\tUNPROTECT(7);\n\t\treturn(ansList);\n\t}\n\n}\n\n", "meta": {"hexsha": "774033ffa1bae49d32d4735141842b3ab37e9f6c", "size": 8827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ordering.cpp", "max_stars_repo_name": "HenrikBengtsson/RBGL", "max_stars_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ordering.cpp", "max_issues_repo_name": "HenrikBengtsson/RBGL", "max_issues_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-09-05T02:26:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-30T20:28:53.000Z", "max_forks_repo_path": "src/ordering.cpp", "max_forks_repo_name": "HenrikBengtsson/RBGL", "max_forks_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-19T10:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T01:22:29.000Z", "avg_line_length": 30.9719298246, "max_line_length": 95, "alphanum_fraction": 0.6856236547, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.03514484501123562, "lm_q1q2_score": 0.015522529329729856}}
{"text": "#include <ctime>\n\n#include <boost/format.hpp>\n\n#include \"output.hpp\"\n#include \"logger.hpp\"\n#include \"defines.hpp\"\n#include \"particle.hpp\"\n#include \"simulation.hpp\"\n\nnamespace sph\n{\n\ninline void output(const SPHParticle & p, std::ofstream &out, const char sep = ' ')\n{\n#define OUTPUT_SCALAR(name) do { out << p.name << sep; } while(0)\n#define OUTPUT_VECTOR(name) do { for(int i = 0; i < DIM; ++i) out << p.name[i] << sep; } while(0)\n\n    OUTPUT_VECTOR(pos);\n    OUTPUT_VECTOR(vel);\n    OUTPUT_VECTOR(acc);\n    OUTPUT_SCALAR(mass);\n    OUTPUT_SCALAR(dens);\n    OUTPUT_SCALAR(pres);\n    OUTPUT_SCALAR(ene);\n    OUTPUT_SCALAR(sml);\n    OUTPUT_SCALAR(id);\n    OUTPUT_SCALAR(neighbor);\n    OUTPUT_SCALAR(alpha);\n    OUTPUT_SCALAR(gradh);\n    out << std::endl;\n}\n\nOutput::Output(int count)\n{\n    m_count = count;\n    const std::string dir_name = Logger::get_dir_name();\n    const std::string file_name = dir_name + \"/energy.dat\";\n    m_out_energy.open(file_name);\n    m_out_energy << \"# time kinetic thermal potential total\\n\";\n}\n\nOutput::~Output()\n{\n    m_out_energy.close();\n}\n\nvoid Output::output_particle(std::shared_ptr<Simulation> sim)\n{\n    const auto & particles = sim->get_particles();\n    const int num = sim->get_particle_num();\n    const real time = sim->get_time();\n\n    const std::string dir_name = Logger::get_dir_name();\n    const std::string file_name = dir_name + (boost::format(\"/%05d.dat\") % m_count).str();\n    std::ofstream out(file_name);\n    out << \"# \" << time << std::endl;\n\n    for(int i = 0; i < num; ++i) {\n        output(particles[i], out);\n    }\n    WRITE_LOG << \"write \" << file_name;\n    ++m_count;\n}\n\nvoid Output::output_energy(std::shared_ptr<Simulation> sim)\n{\n    const auto & particles = sim->get_particles();\n    const int num = sim->get_particle_num();\n    const real time = sim->get_time();\n\n    real kinetic = 0.0;\n    real thermal = 0.0;\n    real potential = 0.0;\n\n#pragma omp parallel for reduction(+: kinetic, thermal, potential)\n    for(int i = 0; i < num; ++i) {\n        const auto & p_i = particles[i];\n        kinetic += 0.5 * p_i.mass * abs2(p_i.vel);\n        thermal += p_i.mass * p_i.ene;\n        potential += 0.5 * p_i.mass * p_i.phi;\n    }\n\n    const real e_k = kinetic;\n    const real e_t = thermal;\n    const real e_p = potential;\n    const real total = e_k + e_t + e_p;\n\n    m_out_energy << time << \" \" << e_k << \" \" << e_t << \" \" << e_p << \" \" << total << std::endl;\n}\n\n}\n", "meta": {"hexsha": "0dc513a3f6464225fa4b20699a831440143d2c50", "size": 2423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/output.cpp", "max_stars_repo_name": "shohirose/sphcode", "max_stars_repo_head_hexsha": "67efb8882520cd8d53ca12ec07439dfa515fd862", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T12:39:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:29:30.000Z", "max_issues_repo_path": "src/output.cpp", "max_issues_repo_name": "shohirose/sphcode", "max_issues_repo_head_hexsha": "67efb8882520cd8d53ca12ec07439dfa515fd862", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T14:07:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-12T13:51:22.000Z", "max_forks_repo_path": "src/output.cpp", "max_forks_repo_name": "shohirose/sphcode", "max_forks_repo_head_hexsha": "67efb8882520cd8d53ca12ec07439dfa515fd862", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-13T11:21:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T05:56:07.000Z", "avg_line_length": 26.0537634409, "max_line_length": 97, "alphanum_fraction": 0.6203054065, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.033589504924538494, "lm_q1q2_score": 0.015485325379005913}}
{"text": "//   -----------------------------------------------------------------------------------------------\n//    Copyright 2015 André Bergner. Distributed under the Boost Software License, Version 1.0.\n//     (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//      --------------------------------------------------------------------------------------------\n\n#include <iostream>\n#include <algorithm>\n#include <array>\n#include <vector>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/min_max.hpp>\n#include <boost/mpl/eval_if.hpp>\n#include <boost/mpl/identity.hpp>\n#include <boost/mpl/next_prior.hpp>\n#include <boost/typeof/typeof.hpp>\n#include <boost/typeof/std/ostream.hpp>\n#include <boost/typeof/std/iostream.hpp>\n#include <boost/proto/core.hpp>\n#include <boost/proto/context.hpp>\n#include <boost/proto/transform.hpp>\n\n#include \"demangle.h\"\n#include \"tuple_tools.hpp\"\n\n\n//  TODO \n//  √ use callable transform instead of context\n//  • implement currying\n//  √ operator() -> enable if # of args\n\n\nnamespace mpl = boost::mpl;\nnamespace proto = boost::proto;\n\n\n\n// Forward declaration of the lambda expression wrapper\n\ntemplate<typename T>\nstruct lambda;\n\nstruct lambda_domain\n  : proto::domain<proto::pod_generator<lambda> >\n{};\n\n\n\n\n\nnamespace boost { namespace proto\n{\n    // boost.proto (similar to functional from the STL) requires a result\n    // type or trait to be declared within function objects. This helper\n    // works around this design limitation of boost.proto by automatically\n    // deriving the result type by using decltype on the object itself.\n\n    struct callable_decltype : callable\n    {\n        template< typename Signature >\n        struct result;\n\n        template< typename This , typename... Args >\n        struct result< This( Args... ) > \n        {\n            using type = decltype( std::declval<This>()( std::declval<Args>()... ));\n        };\n    };\n}}\n\n\n//  ------------------------------------------------------------------------------------------------\n// main part\n//  ------------------------------------------------------------------------------------------------\n\n\ntemplate< typename I >  struct placeholder       { using arity = I; };\ntemplate< typename T >  struct placeholder_arity { using type = typename T::arity; };\n\n\n\nBOOST_PROTO_DEFINE_ENV_VAR( current_input_t, current_input );\nBOOST_PROTO_DEFINE_ENV_VAR( delayed_input_t, delayed_input );\n\n\nnamespace transforms\n{\n    using namespace proto;\n\n    template< typename idx = _ >\n    using delayed_placeholder = subscript< terminal<placeholder<idx>> , terminal<placeholder<_>> >;\n\n\n    struct lambda_arity : or_\n    <   when\n        <   delayed_placeholder<>\n        ,   placeholder_arity<_value(_left)>()\n        >\n    ,   when\n        <   terminal< placeholder<_> >\n        ,   placeholder_arity<_value>()\n        >\n    ,   when\n        <   terminal<_>\n        ,   mpl::int_<0>()\n        >\n    ,   when\n        <   nary_expr<_, vararg<_>>\n        ,   fold<_, mpl::int_<0>(), mpl::max<lambda_arity, _state>()>\n        >\n    >\n    {};\n\n\n    template< typename idx >\n    struct static_max_delay_impl   // excapsulates template parameter, proto gets confused elsewise\n    {\n        struct apply : or_\n        <   when\n            <   delayed_placeholder<idx>\n            ,   placeholder_arity< _value(_right) >()\n            >\n        ,   when\n            <   terminal<_>\n            ,   mpl::int_<0>()\n            >\n        ,   when\n            <   nary_expr<_, vararg<_>>\n            ,   fold<_, mpl::int_<0>(), mpl::max<apply, _state>()>\n            >\n        >\n        {};\n    };\n\n    template< typename idx = _ >\n    using static_max_delay = typename static_max_delay_impl<idx>::apply;\n\n\n    struct place_the_holder : callable_decltype\n    {\n        template< typename I , typename Tuple >\n        auto operator()( placeholder<I> const & , Tuple const & args ) const\n        {\n            return std::get<I::value-1>( args );\n        }\n    };\n\n\n    struct place_delay : callable_decltype\n    {\n        template< typename I , typename J , typename Delayed_input >\n        auto operator()( placeholder<I> const & , placeholder<J> const & , Delayed_input const & del_in ) const\n        {\n            auto const & s = std::get<I::value-1>(del_in);\n            return s[s.size()-J::value];\n        }\n    };\n\n\n    struct eval_it : or_\n    <   when\n        <   delayed_placeholder<>\n        ,   place_delay( _value(_left) , _value(_right) , _env_var<delayed_input_t> )\n        >\n    ,   when\n        <   terminal< placeholder<_> >\n        ,   place_the_holder( _value , _env_var<current_input_t> )\n        >\n    ,   when\n        <   _\n        ,   _default< eval_it >\n        >\n    >\n    {};\n\n}\n\nusing  transforms :: lambda_arity;\nusing  transforms :: static_max_delay;\nusing  transforms :: eval_it;\n\ntemplate< typename idx , typename Expr >\nusing static_max_delay_t = typename boost::result_of<static_max_delay<idx>(Expr)>::type;\n\ntemplate< typename Expr >\nusing lambda_arity_t = typename boost::result_of<lambda_arity(Expr)>::type;\n\n\n\n\ntemplate< size_t arity, typename Expr >\nstruct delay_for_placeholder\n{\n    using type = decltype( std::tuple_cat( std::declval<typename delay_for_placeholder<arity-1,Expr>::type>()\n                                         , std::declval<std::tuple< static_max_delay_t<mpl::int_<arity>,Expr>>>() ));\n};\n\ntemplate< typename Expr >\nstruct delay_for_placeholder<0,Expr>\n{\n    using type = std::tuple<>;\n};\n\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// supporting tools\n//  ------------------------------------------------------------------------------------------------\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// lift_into_tuple  --  lifts a meta-function into a tuple,\n//                      i.e. applies it on each type in tuple, returns tuple of new types\n\ntemplate< typename F , typename Tuple >\nstruct lift_into_tuple;\n\ntemplate< typename F , typename... Ts >\nstruct lift_into_tuple< F , std::tuple<Ts...> >\n{\n    using type = std::tuple< typename F::template apply_t<Ts>... >;\n};\n\ntemplate< typename F , typename Tuple >\nusing lift_into_tuple_t = typename lift_into_tuple<F,Tuple>::type;\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// to_array  --  meta-function that maps mpl::int_<N> to array<T,N>\n\ntemplate< typename T >\nstruct to_array\n{\n    template< typename Int >\n    struct apply\n    {\n        using type = std::array< T , Int::value >;\n    };\n\n    template< typename Int >\n    using apply_t = typename apply<Int>::type;\n};\n\n\n//  ------------------------------------------------------------------------------------------------\n// very simple delay_line operation on std::array --> TODO should be own type static_delay_line !\n\nstruct {\n    template< typename T , size_t N , typename Y >\n    void operator()( std::array<T,N>& xs , Y y )\n    {\n        for ( size_t n = 1 ; n < xs.size() ; ++n )  xs[n-1] = xs[n];\n        xs.back() = y;\n    }\n} rotate_push_back;\n\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// compile  --  main function of framework\n//              • takes a zignal/dsp expressions\n//              • generta\n//              • returns clojure\n//  ------------------------------------------------------------------------------------------------\n\nauto compile = []( auto expr )        // TODO need to define value_type for state\n{\n    using expr_t = decltype(expr);\n    using tuple_t = typename delay_for_placeholder< lambda_arity_t<expr_t>::value, expr_t >::type;\n    using state_t = lift_into_tuple_t< to_array<float> , tuple_t >;\n\n    return [ expr , state = state_t{} ]( auto const&... xs ) mutable\n    {\n        auto result = eval_it{}( expr, proto::_state{}, ( current_input = std::make_tuple(xs...) , delayed_input = state ) );\n        tuple_for_each( rotate_push_back, state, std::make_tuple(xs...) );\n        return result;\n    };\n};\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// compile2 -- same as compile, but return type is curryable\n//  ------------------------------------------------------------------------------------------------\n\ntemplate\n<   typename Expression\n,   typename State\n,   size_t   arity\n>\nstruct stateful_lambda\n{\nprivate:\n\n    Expression  expr_;\n    State       state_;\n\n    template< typename... Args >\n    auto call_impl( mpl::int_<0> , Args const &... args ) -> decltype(auto)\n    {\n        auto result = eval_it{}( expr_, proto::_state{}, ( current_input = std::make_tuple(args...) , delayed_input = state_ ) );\n        tuple_for_each( rotate_push_back, state_, std::make_tuple(args...) );\n        return result;\n    }\n\n    template< int arg_diff , typename... Args >\n    auto call_impl( mpl::int_<arg_diff> , Args const &... args ) const\n    {\n        return [ &args...                 // TODO should copy args into lambda\n               , expr = *this ]           // TODO should not be a lambda, but a type that is\n        ( auto const &... missing_args )  //      aware of the # of args (enable_if them)\n        {\n            return expr( args..., missing_args... );\n        };\n    }\n\npublic:\n\n    stateful_lambda( Expression expr ) : expr_( std::move(expr)) {}\n\n    template< typename... Args , typename = std::enable_if_t< sizeof...(Args) <= arity > >\n    auto operator()( Args const &... args ) -> decltype(auto)\n    {\n        return call_impl( mpl::int_< arity - sizeof...(Args) >{} , args... );\n    }\n};\n\n\nauto compile2 = []( auto expr )        // TODO need to define value_type for state\n{\n    using expr_t = decltype(expr);\n    using arity_t = lambda_arity_t<expr_t>;\n    using tuple_t = typename delay_for_placeholder< arity_t::value, expr_t >::type;\n    using state_t = lift_into_tuple_t< to_array<float> , tuple_t >;\n\n    return stateful_lambda< expr_t, state_t, arity_t::value>{ expr };\n};\n\n\n\n\n\n\n\n\n\n\nconst proto::terminal< placeholder< mpl::int_<1> >>::type   _1  = {{}};\nconst proto::terminal< placeholder< mpl::int_<2> >>::type   _2  = {{}};\nconst proto::terminal< placeholder< mpl::int_<3> >>::type   _3  = {{}};\nconst proto::terminal< placeholder< mpl::int_<4> >>::type   _4  = {{}};\nconst proto::terminal< placeholder< mpl::int_<5> >>::type   _5  = {{}};\n\n\n\nint main()\n{\n    std::cout << \"arities -----------------\" << std::endl;\n    std::cout << lambda_arity{}( _1 + _2 ) << std::endl;\n    std::cout << lambda_arity{}( _1[_4] + _3 ) << std::endl;\n    std::cout << lambda_arity{}( _1 + _2[_1] ) << std::endl;\n    std::cout << \"delays -----------------\" << std::endl;\n    std::cout << static_max_delay<mpl::int_<1>>{}( _1 + _2 ) << std::endl;\n    std::cout << static_max_delay<mpl::int_<1>>{}( _1[_4] + _3 ) << std::endl;\n    std::cout << static_max_delay<mpl::int_<1>>{}( _1 + _2[_1] ) << std::endl;\n    std::cout << \"-------------------------\" << std::endl;\n\n    auto print_expr_state = []( auto expr )\n    {\n        using expr_t = decltype(expr);\n        using state_t = typename delay_for_placeholder< lambda_arity_t<expr_t>::value, expr_t >::type;\n        std::cout << lambda_arity_t<expr_t>::value << \"  \" << type_name<state_t>() << std::endl;\n    };\n\n    print_expr_state( _1 + _2 );\n    print_expr_state( _1[_4] + _3 );\n    print_expr_state( _1 + _2[_1] + _4[_3] );\n\n    std::cout << \"-------------------------\" << std::endl;\n\n\n    auto unit_delay = compile( _1[_1] );\n    auto differentiator = compile2( _1 - _1[_1] );\n\n    for ( auto x : {1,1,1,1,1} )\n        std::cout << differentiator(x) << std::endl;\n\n/*\n    {  // test to check assembly output\n        auto test_expr = compile( _1[_1] - _1[_2]*2.f );\n\n        std::vector<float> xs(1000);\n        {\n            float u = 0.87;\n            for ( auto& x : xs ) x = u *= 4.0*(1.-u);\n        }\n\n        auto acc = 0.f;\n        __asm__ __volatile__(\"nop\":::\"memory\");\n        for ( auto x : xs )\n            acc += test_expr(x);\n        __asm__ __volatile__(\"nop\":::\"memory\");\n        std::cout << acc << std::endl;\n\n        for ( auto x : xs )\n            std::cout << test_expr(x) << std::endl;\n    }\n*/\n}\n", "meta": {"hexsha": "f74384d493629ff1342d6e2d22c769e7a6dd676f", "size": 12214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental_steps/lambda_with_delay.cpp", "max_stars_repo_name": "andre-bergner/zignal", "max_stars_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2016-02-04T20:56:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T15:51:17.000Z", "max_issues_repo_path": "experimental_steps/lambda_with_delay.cpp", "max_issues_repo_name": "andre-bergner/zignal", "max_issues_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-02-05T14:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-05T14:46:11.000Z", "max_forks_repo_path": "experimental_steps/lambda_with_delay.cpp", "max_forks_repo_name": "andre-bergner/zignal", "max_forks_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-20T15:27:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-09T16:34:04.000Z", "avg_line_length": 29.5738498789, "max_line_length": 129, "alphanum_fraction": 0.5284918945, "num_tokens": 2861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.03567855100590134, "lm_q1q2_score": 0.01548382982762167}}
{"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_SCONICS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_SCONICS_HPP\n\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/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace sconics\n    {\n\n            enum proj_type {\n                proj_euler  = 0,\n                proj_murd1  = 1,\n                proj_murd2  = 2,\n                proj_murd3  = 3,\n                proj_pconic = 4,\n                proj_tissot = 5,\n                proj_vitk1  = 6\n            };\n            static const double epsilon10 = 1.e-10;\n            static const double epsilon = 1e-10;\n\n            template <typename T>\n            struct par_sconics\n            {\n                T   n;\n                T   rho_c;\n                T   rho_0;\n                T   sig;\n                T   c1, c2;\n                proj_type type;\n            };\n\n            /* get common factors for simple conics */\n            template <typename Params, typename T>\n            inline int phi12(Params const& params, par_sconics<T>& proj_parm, T *del)\n            {\n                T p1, p2;\n                int err = 0;\n\n                if (!pj_param_r<srs::spar::lat_1>(params, \"lat_1\", srs::dpar::lat_1, p1) ||\n                    !pj_param_r<srs::spar::lat_2>(params, \"lat_2\", srs::dpar::lat_2, p2)) {\n                    err = -41;\n                } else {\n                    //p1 = pj_get_param_r(par.params, \"lat_1\"); // set above\n                    //p2 = pj_get_param_r(par.params, \"lat_2\"); // set above\n                    *del = 0.5 * (p2 - p1);\n                    proj_parm.sig = 0.5 * (p2 + p1);\n                    err = (fabs(*del) < epsilon || fabs(proj_parm.sig) < epsilon) ? -42 : 0;\n                }\n                return err;\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_sconics_spheroid\n                : public base_t_fi<base_sconics_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_sconics<T> m_proj_parm;\n\n                inline base_sconics_spheroid(const Parameters& par)\n                    : base_t_fi<base_sconics_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    T rho;\n\n                    switch (this->m_proj_parm.type) {\n                    case proj_murd2:\n                        rho = this->m_proj_parm.rho_c + tan(this->m_proj_parm.sig - lp_lat);\n                        break;\n                    case proj_pconic:\n                        rho = this->m_proj_parm.c2 * (this->m_proj_parm.c1 - tan(lp_lat - this->m_proj_parm.sig));\n                        break;\n                    default:\n                        rho = this->m_proj_parm.rho_c - lp_lat;\n                        break;\n                    }\n                    xy_x = rho * sin( lp_lon *= this->m_proj_parm.n );\n                    xy_y = this->m_proj_parm.rho_0 - rho * cos(lp_lon);\n                }\n\n                // INVERSE(s_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                    T rho;\n\n                    rho = boost::math::hypot(xy_x, xy_y = this->m_proj_parm.rho_0 - xy_y);\n                    if (this->m_proj_parm.n < 0.) {\n                        rho = - rho;\n                        xy_x = - xy_x;\n                        xy_y = - xy_y;\n                    }\n\n                    lp_lon = atan2(xy_x, xy_y) / this->m_proj_parm.n;\n\n                    switch (this->m_proj_parm.type) {\n                    case proj_pconic:\n                        lp_lat = atan(this->m_proj_parm.c1 - rho / this->m_proj_parm.c2) + this->m_proj_parm.sig;\n                        break;\n                    case proj_murd2:\n                        lp_lat = this->m_proj_parm.sig - atan(rho - this->m_proj_parm.rho_c);\n                        break;\n                    default:\n                        lp_lat = this->m_proj_parm.rho_c - rho;\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"sconics_spheroid\";\n                }\n\n            };\n\n            template <typename Params, typename Parameters, typename T>\n            inline void setup(Params const& params, Parameters& par, par_sconics<T>& proj_parm, proj_type type) \n            {\n                static const T half_pi = detail::half_pi<T>();\n\n                T del, cs;\n                int err;\n\n                proj_parm.type = type;\n\n                err = phi12(params, proj_parm, &del);\n                if(err)\n                    BOOST_THROW_EXCEPTION( projection_exception(err) );\n\n                switch (proj_parm.type) {\n                case proj_tissot:\n                    proj_parm.n = sin(proj_parm.sig);\n                    cs = cos(del);\n                    proj_parm.rho_c = proj_parm.n / cs + cs / proj_parm.n;\n                    proj_parm.rho_0 = sqrt((proj_parm.rho_c - 2 * sin(par.phi0))/proj_parm.n);\n                    break;\n                case proj_murd1:\n                    proj_parm.rho_c = sin(del)/(del * tan(proj_parm.sig)) + proj_parm.sig;\n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    proj_parm.n = sin(proj_parm.sig);\n                    break;\n                case proj_murd2:\n                    proj_parm.rho_c = (cs = sqrt(cos(del))) / tan(proj_parm.sig);\n                    proj_parm.rho_0 = proj_parm.rho_c + tan(proj_parm.sig - par.phi0);\n                    proj_parm.n = sin(proj_parm.sig) * cs;\n                    break;\n                case proj_murd3:\n                    proj_parm.rho_c = del / (tan(proj_parm.sig) * tan(del)) + proj_parm.sig;\n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    proj_parm.n = sin(proj_parm.sig) * sin(del) * tan(del) / (del * del);\n                    break;\n                case proj_euler:\n                    proj_parm.n = sin(proj_parm.sig) * sin(del) / del;\n                    del *= 0.5;\n                    proj_parm.rho_c = del / (tan(del) * tan(proj_parm.sig)) + proj_parm.sig;\n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    break;\n                case proj_pconic:\n                    proj_parm.n = sin(proj_parm.sig);\n                    proj_parm.c2 = cos(del);\n                    proj_parm.c1 = 1./tan(proj_parm.sig);\n                    if (fabs(del = par.phi0 - proj_parm.sig) - epsilon10 >= half_pi)\n                        BOOST_THROW_EXCEPTION( projection_exception(error_lat_0_half_pi_from_mean) );\n                    proj_parm.rho_0 = proj_parm.c2 * (proj_parm.c1 - tan(del));\n                    break;\n                case proj_vitk1:\n                    proj_parm.n = (cs = tan(del)) * sin(proj_parm.sig) / del;\n                    proj_parm.rho_c = del / (cs * tan(proj_parm.sig)) + proj_parm.sig;\n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    break;\n                }\n\n                par.es = 0;\n            }\n\n\n            // Euler\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_euler(Params const& params, Parameters& par, par_sconics<T>& proj_parm)\n            {\n                setup(params, par, proj_parm, proj_euler);\n            }\n\n            // Tissot\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_tissot(Params const& params, Parameters& par, par_sconics<T>& proj_parm)\n            {\n                setup(params, par, proj_parm, proj_tissot);\n            }\n\n            // Murdoch I\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_murd1(Params const& params, Parameters& par, par_sconics<T>& proj_parm)\n            {\n                setup(params, par, proj_parm, proj_murd1);\n            }\n\n            // Murdoch II\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_murd2(Params const& params, Parameters& par, par_sconics<T>& proj_parm)\n            {\n                setup(params, par, proj_parm, proj_murd2);\n            }\n\n            // Murdoch III\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_murd3(Params const& params, Parameters& par, par_sconics<T>& proj_parm)\n            {\n                setup(params, par, proj_parm, proj_murd3);\n            }            \n\n            // Perspective Conic\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_pconic(Params const& params, Parameters& par, par_sconics<T>& proj_parm)\n            {\n                setup(params, par, proj_parm, proj_pconic);\n            }\n\n            // Vitkovsky I\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_vitk1(Params const& params, Parameters& par, par_sconics<T>& proj_parm)\n            {\n                setup(params, par, proj_parm, proj_vitk1);\n            }\n\n    }} // namespace detail::sconics\n    #endif // doxygen\n    \n    /*!\n        \\brief Tissot projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n        \\par Example\n        \\image html ex_tissot.gif\n    */\n    template <typename T, typename Parameters>\n    struct tissot_spheroid : public detail::sconics::base_sconics_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline tissot_spheroid(Params const& params, const Parameters& par)\n            : detail::sconics::base_sconics_spheroid<T, Parameters>(par)\n        {\n            detail::sconics::setup_tissot(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Murdoch I projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n        \\par Example\n        \\image html ex_murd1.gif\n    */\n    template <typename T, typename Parameters>\n    struct murd1_spheroid : public detail::sconics::base_sconics_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline murd1_spheroid(Params const& params, const Parameters& par)\n            : detail::sconics::base_sconics_spheroid<T, Parameters>(par)\n        {\n            detail::sconics::setup_murd1(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Murdoch II projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n        \\par Example\n        \\image html ex_murd2.gif\n    */\n    template <typename T, typename Parameters>\n    struct murd2_spheroid : public detail::sconics::base_sconics_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline murd2_spheroid(Params const& params, const Parameters& par)\n            : detail::sconics::base_sconics_spheroid<T, Parameters>(par)\n        {\n            detail::sconics::setup_murd2(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Murdoch III projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n        \\par Example\n        \\image html ex_murd3.gif\n    */\n    template <typename T, typename Parameters>\n    struct murd3_spheroid : public detail::sconics::base_sconics_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline murd3_spheroid(Params const& params, const Parameters& par)\n            : detail::sconics::base_sconics_spheroid<T, Parameters>(par)\n        {\n            detail::sconics::setup_murd3(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Euler projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n        \\par Example\n        \\image html ex_euler.gif\n    */\n    template <typename T, typename Parameters>\n    struct euler_spheroid : public detail::sconics::base_sconics_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline euler_spheroid(Params const& params, const Parameters& par)\n            : detail::sconics::base_sconics_spheroid<T, Parameters>(par)\n        {\n            detail::sconics::setup_euler(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Perspective Conic projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n        \\par Example\n        \\image html ex_pconic.gif\n    */\n    template <typename T, typename Parameters>\n    struct pconic_spheroid : public detail::sconics::base_sconics_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline pconic_spheroid(Params const& params, const Parameters& par)\n            : detail::sconics::base_sconics_spheroid<T, Parameters>(par)\n        {\n            detail::sconics::setup_pconic(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Vitkovsky I projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel\n         - lat_2: Latitude of second standard parallel\n        \\par Example\n        \\image html ex_vitk1.gif\n    */\n    template <typename T, typename Parameters>\n    struct vitk1_spheroid : public detail::sconics::base_sconics_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline vitk1_spheroid(Params const& params, const Parameters& par)\n            : detail::sconics::base_sconics_spheroid<T, Parameters>(par)\n        {\n            detail::sconics::setup_vitk1(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_euler, euler_spheroid, euler_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_murd1, murd1_spheroid, murd1_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_murd2, murd2_spheroid, murd2_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_murd3, murd3_spheroid, murd3_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_pconic, pconic_spheroid, pconic_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_tissot, tissot_spheroid, tissot_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_vitk1, vitk1_spheroid, vitk1_spheroid)\n        \n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(euler_entry, euler_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(murd1_entry, murd1_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(murd2_entry, murd2_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(murd3_entry, murd3_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(pconic_entry, pconic_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(tissot_entry, tissot_spheroid)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(vitk1_entry, vitk1_spheroid)\n\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(sconics_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(euler, euler_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(murd1, murd1_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(murd2, murd2_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(murd3, murd3_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(pconic, pconic_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(tissot, tissot_entry)\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(vitk1, vitk1_entry)\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_SCONICS_HPP\n\n", "meta": {"hexsha": "44d606cab41bb24662111bce64d6cf9b0bc7d4f6", "size": 20684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/sconics.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/sconics.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/sconics.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": 40.7165354331, "max_line_length": 117, "alphanum_fraction": 0.5974182943, "num_tokens": 4827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938145706678, "lm_q2_score": 0.031143832670502195, "lm_q1q2_score": 0.015450262749860022}}
{"text": "/*\n * The MIT License (MIT)\n * =====================\n *\n * Copyright © 2019-2020 Azavea\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 <cstdio>\n#include <cstdint>\n#include <cmath>\n\n#include <set>\n#include <vector>\n\n#include <boost/polygon/segment_data.hpp>\n#include <boost/polygon/voronoi.hpp>\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\nnamespace bp = boost::polygon;\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\ntypedef int64_t integral_coordinate_t;\n\nstruct integral_point_t\n{\n    integral_coordinate_t x;\n    integral_coordinate_t y;\n} __attribute__((packed));\n\nbool operator<(const integral_point_t &a, const integral_point_t &b)\n{\n    if (a.x == b.x)\n    {\n        return (a.y < b.y);\n    }\n    else\n    {\n        return (a.x < b.x);\n    }\n}\n\nstruct integral_segment_t\n{\n    integral_point_t v0;\n    integral_point_t v1;\n} __attribute__((packed));\n\nbool operator<(const integral_segment_t &a, const integral_segment_t &b)\n{\n    if (a.v0.x == b.v0.x)\n    {\n        return (a.v0.y <= b.v0.y);\n    }\n    else\n    {\n        return (a.v0.x <= b.v0.x);\n    }\n}\n\ntypedef bp::voronoi_edge<double> voronoi_edge_t;\ntypedef bp::voronoi_diagram<double> voronoi_diagram_t;\n\ntypedef std::pair<const integral_segment_t *, uint32_t> integral_rtree_value_t;\ntypedef bgi::rtree<integral_rtree_value_t, bgi::linear<16>> integral_rtree_t;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> real_point_t;\ntypedef bg::model::segment<real_point_t> real_segment_t;\ntypedef std::pair<real_segment_t, uint32_t> real_rtree_value_t;\ntypedef bgi::rtree<real_rtree_value_t, bgi::linear<16>> real_rtree_t;\n\n// Geometry concepts\nnamespace boost\n{\nnamespace geometry\n{\nnamespace traits\n{\ntemplate <>\nstruct tag<integral_point_t>\n{\n    typedef point_tag type;\n};\n\ntemplate <>\nstruct coordinate_type<integral_point_t>\n{\n    typedef integral_coordinate_t type;\n};\n\ntemplate <>\nstruct coordinate_system<integral_point_t>\n{\n    typedef cs::cartesian type;\n};\n\ntemplate <>\nstruct dimension<integral_point_t> : boost::mpl::int_<2>\n{\n};\n\ntemplate <std::size_t Dimension>\nstruct access<integral_point_t, Dimension>\n{\n    static inline integral_coordinate_t get(integral_point_t const &p)\n    {\n        if (Dimension == 0)\n        {\n            return p.x;\n        }\n        else if (Dimension == 1)\n        {\n            return p.y;\n        }\n        else\n        {\n            throw __LINE__;\n        }\n    }\n\n    static inline void set(integral_point_t &p, integral_coordinate_t c)\n    {\n        if (Dimension == 0)\n        {\n            p.x = c;\n        }\n        else if (Dimension == 1)\n        {\n            p.y = c;\n        }\n        else\n        {\n            throw __LINE__;\n        }\n    }\n};\n\ntemplate <>\nstruct tag<integral_segment_t>\n{\n    typedef segment_tag type;\n};\n\ntemplate <>\nstruct point_type<integral_segment_t>\n{\n    typedef integral_point_t type;\n};\n\ntemplate <std::size_t Index, std::size_t Dimension>\nstruct indexed_access<integral_segment_t, Index, Dimension>\n{\n    static inline integral_coordinate_t get(integral_segment_t const &s)\n    {\n        if (Index == 0 && Dimension == 0)\n        {\n            return s.v0.x;\n        }\n        else if (Index == 0 && Dimension == 1)\n        {\n            return s.v0.y;\n        }\n        else if (Index == 1 && Dimension == 0)\n        {\n            return s.v1.x;\n        }\n        else if (Index == 1 && Dimension == 1)\n        {\n            return s.v1.y;\n        }\n        else\n        {\n            throw __LINE__;\n        }\n    }\n};\n} // namespace traits\n} // namespace geometry\n} // namespace boost\n\n// Polygon concepts\nnamespace boost\n{\nnamespace polygon\n{\ntemplate <>\nstruct geometry_concept<integral_point_t>\n{\n    typedef point_concept type;\n};\n\ntemplate <>\nstruct point_traits<integral_point_t>\n{\n    typedef int64_t coordinate_type;\n\n    static coordinate_type get(const integral_point_t &p, orientation_2d orient)\n    {\n        if (orient.to_int() == 0)\n        {\n            return p.x;\n        }\n        else\n        {\n            return p.y;\n        }\n    }\n};\n\ntemplate <>\nstruct geometry_concept<integral_segment_t>\n{\n    typedef segment_concept type;\n};\n\ntemplate <>\nstruct segment_traits<integral_segment_t>\n{\n    typedef point_traits<integral_point_t>::coordinate_type coordinate_type;\n    typedef integral_point_t point_type;\n\n    static inline point_type get(const integral_segment_t &s, direction_1d dir)\n    {\n        if (dir.to_int() == 0)\n        {\n            return s.v0;\n        }\n        else\n        {\n            return s.v1;\n        }\n    }\n};\n} // namespace polygon\n} // namespace boost\n\n#define MAGIC_COLOR (33)\n\nextern \"C\" int get_skeleton(int n, void *segment_data, double **return_data)\n{\n    auto segments = static_cast<integral_segment_t *>(segment_data);\n    std::vector<real_segment_t> axis_vector;\n    std::vector<double> sorted_axis_vector;\n    voronoi_diagram_t vd;\n    integral_rtree_t input_segment_rtree;\n    real_rtree_t voronoi_segment_rtree;\n\n    // construct voronoi diagram\n    bp::construct_voronoi(segments, segments + (n >> 2), &vd);\n\n    // construct rtree over input segments\n    for (int i = 0; i < (n >> 2); ++i)\n    {\n        auto segment = static_cast<const integral_segment_t *>(segment_data) + i;\n        input_segment_rtree.insert(std::make_pair(segment, i));\n    }\n\n    // iterate through the voronoi vertices looking for boundary vertices\n    for (auto vit = vd.vertices().cbegin(); vit != vd.vertices().cend(); ++vit)\n    {\n        auto starting_edge = vit->incident_edge()->rot_next();\n        for (; starting_edge->cell() != vit->incident_edge()->cell(); starting_edge = starting_edge->rot_next())\n        {\n            if (starting_edge->is_primary())\n            {\n                break;\n            }\n        }\n        if (!starting_edge->is_primary())\n        {\n            break;\n        }\n        auto starting_source_segment = segments[starting_edge->cell()->source_index()];\n        auto shared_endpoints = std::set<integral_point_t>();\n\n        // Initialization\n        shared_endpoints.insert(static_cast<integral_point_t>(starting_source_segment.v0));\n        shared_endpoints.insert(static_cast<integral_point_t>(starting_source_segment.v1));\n\n        for (auto edge = starting_edge->rot_next(); edge->cell() != starting_edge->cell(); edge = edge->rot_next())\n        {\n            if (!edge->is_primary())\n            {\n                continue;\n            }\n            auto associated_cell = edge->cell();\n            auto source_segment = segments[associated_cell->source_index()];\n            auto old_shared_endpoints = shared_endpoints;\n\n            // Remove non-shared endpoints\n            shared_endpoints.clear();\n            if (old_shared_endpoints.count(source_segment.v0) > 0)\n            {\n                shared_endpoints.insert(source_segment.v0);\n            }\n            if (old_shared_endpoints.count(source_segment.v1) > 0)\n            {\n                shared_endpoints.insert(source_segment.v1);\n            }\n\n            // If the number of shared endpoints has dropped to zero, leave\n            if (shared_endpoints.size() == 0)\n            {\n                break;\n            }\n        }\n\n        // If there is a shared endpoint between the source segments\n        // of all of the cells that meet this voronoi vertex, then it\n        // is a boundary vertex (see\n        // http://boost.2283326.n4.nabble.com/voronoi-medial-axis-tp4651161p4651225.html )\n        if (shared_endpoints.size() > 0)\n        {\n            vit->color(MAGIC_COLOR);\n        }\n    }\n\n    // Loop over voronoi edges, recording those that do not meet a boundary vertex\n    for (auto eit = vd.edges().cbegin(); eit != vd.edges().cend(); ++eit)\n    {\n        if (eit->is_primary() && eit->is_finite() && eit->vertex0()->color() != MAGIC_COLOR && eit->vertex1()->color() != MAGIC_COLOR)\n        {\n            double x1, y1, x2, y2;\n\n            x1 = eit->vertex0()->x();\n            y1 = eit->vertex0()->y();\n            x2 = eit->vertex1()->x();\n            y2 = eit->vertex1()->y();\n            if ((x1 <= x2) && std::isfinite(x1) && std::isfinite(y1) && std::isfinite(x2) && std::isfinite(y2))\n            {\n                axis_vector.push_back(real_segment_t(real_point_t(x1, y1), real_point_t(x2, y2)));\n                voronoi_segment_rtree.insert(std::make_pair(axis_vector.back(), axis_vector.size() - 1));\n            }\n        }\n    }\n\n    // Get segments in \"sorted\" order\n    real_point_t &current_point = axis_vector.front().first;\n    while (voronoi_segment_rtree.size() > 0)\n    {\n        auto results = std::vector<real_rtree_value_t>();\n        voronoi_segment_rtree.query(bgi::nearest(current_point, 1), std::back_inserter(results));\n        auto result = results.front();\n        const auto current_segment = axis_vector[result.second]; // XXX first entry is not only mutable but apparently mutated!!\n        double x1, y1, d1, x2, y2, d2;\n\n        if (bg::distance(current_point, current_segment.first) < bg::distance(current_point, current_segment.second))\n        {\n            // Insert segment in original orientation\n\n            x1 = current_segment.first.get<0>();\n            y1 = current_segment.first.get<1>();\n            x2 = current_segment.second.get<0>();\n            y2 = current_segment.second.get<1>();\n        }\n        else\n        {\n            // Insert flipped segment\n            x1 = current_segment.second.get<0>();\n            y1 = current_segment.second.get<1>();\n            x2 = current_segment.first.get<0>();\n            y2 = current_segment.first.get<1>();\n        }\n\n        auto results1 = std::vector<integral_rtree_value_t>();\n        auto v1 = integral_point_t{.x = static_cast<integral_coordinate_t>(x1), .y = static_cast<integral_coordinate_t>(y1)};\n        input_segment_rtree.query(bgi::nearest(v1, 1), std::back_inserter(results1)); // This is okay due to (pre-)scaling\n        d1 = bg::distance(v1, segments[results1.front().second]);\n\n        auto results2 = std::vector<integral_rtree_value_t>();\n        auto v2 = integral_point_t{.x = static_cast<integral_coordinate_t>(x2), .y = static_cast<integral_coordinate_t>(y2)};\n        input_segment_rtree.query(bgi::nearest(v2, 1), std::back_inserter(results2)); // okay due to scaling\n        d2 = bg::distance(v2, segments[results2.front().second]);\n\n        sorted_axis_vector.push_back(x1);\n        sorted_axis_vector.push_back(y1);\n        sorted_axis_vector.push_back(x2);\n        sorted_axis_vector.push_back(y2);\n        sorted_axis_vector.push_back(d1);\n        sorted_axis_vector.push_back(d2);\n\n        current_point = current_segment.second;\n        auto return_code = voronoi_segment_rtree.remove(result);\n        assert(return_code > 0);\n    }\n    axis_vector.clear();\n\n    // Copy results back\n    auto m = sorted_axis_vector.size();\n    auto l = m * sizeof(double);\n    *return_data = static_cast<double *>(malloc(l));\n    memcpy(*return_data, sorted_axis_vector.data(), l);\n\n    return sorted_axis_vector.size();\n}\n", "meta": {"hexsha": "7f79f6fef043164905e8839f601e8b2025063ab9", "size": 12173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libmedial/medial.cpp", "max_stars_repo_name": "geotrellis/deeplab-nlcd", "max_stars_repo_head_hexsha": "9444299597e1d1bc34ee187f2092890449c188be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libmedial/medial.cpp", "max_issues_repo_name": "geotrellis/deeplab-nlcd", "max_issues_repo_head_hexsha": "9444299597e1d1bc34ee187f2092890449c188be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-08-21T20:01:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T19:59:23.000Z", "max_forks_repo_path": "src/libmedial/medial.cpp", "max_forks_repo_name": "geotrellis/deeplab-nlcd", "max_forks_repo_head_hexsha": "9444299597e1d1bc34ee187f2092890449c188be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-21T20:44:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T02:58:15.000Z", "avg_line_length": 28.9833333333, "max_line_length": 134, "alphanum_fraction": 0.6237574961, "num_tokens": 2907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.031143827949428875, "lm_q1q2_score": 0.015450260871815625}}
{"text": "/*****************************************************************************\r\n *\r\n * This file is part of Mapnik (c++ mapping toolkit)\r\n *\r\n * Copyright (C) 2011 Artem Pavlenko\r\n *\r\n * This library is free software; you can redistribute it and/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\r\n *\r\n *****************************************************************************/\r\n\r\n#ifndef MAPNIK_QUAD_TREE_HPP\r\n#define MAPNIK_QUAD_TREE_HPP\r\n\r\n// mapnik\r\n#include <mapnik/box2d.hpp>\r\n#include <mapnik/noncopyable.hpp>\r\n\r\n// boost\r\n#include <boost/ptr_container/ptr_vector.hpp>\r\n\r\n// stl\r\n#include <vector>\r\n#include <cstring>\r\n\r\nnamespace mapnik\r\n{\r\ntemplate <typename T>\r\nclass quad_tree : mapnik::noncopyable\r\n{\r\n    struct node\r\n    {\r\n        typedef T value_t;\r\n        typedef std::vector<T> cont_t;\r\n        typedef typename cont_t::iterator iterator;\r\n        typedef typename cont_t::const_iterator const_iterator;\r\n        box2d<double> extent_;\r\n        cont_t cont_;\r\n        node * children_[4];\r\n\r\n        explicit node(box2d<double> const& ext)\r\n            : extent_(ext)\r\n        {\r\n            std::memset(children_,0,4*sizeof(node*));\r\n        }\r\n\r\n        box2d<double> const& extent() const\r\n        {\r\n            return extent_;\r\n        }\r\n\r\n        iterator begin()\r\n        {\r\n            return cont_.begin();\r\n        }\r\n\r\n        const_iterator begin() const\r\n        {\r\n            return cont_.begin();\r\n        }\r\n\r\n        iterator end()\r\n        {\r\n            return cont_.end();\r\n        }\r\n\r\n        const_iterator end() const\r\n        {\r\n            return cont_.end();\r\n        }\r\n        ~node () {}\r\n    };\r\n\r\n    typedef boost::ptr_vector<node> nodes_t;\r\n    typedef typename node::cont_t cont_t;\r\n    typedef typename cont_t::iterator node_data_iterator;\r\n\r\npublic:\r\n    typedef typename nodes_t::iterator iterator;\r\n    typedef typename nodes_t::const_iterator const_iterator;\r\n    typedef typename boost::ptr_vector<T,boost::view_clone_allocator> result_t;\r\n    typedef typename result_t::iterator query_iterator;\r\n\r\n\r\n    explicit quad_tree(box2d<double> const& ext,\r\n                       unsigned int max_depth = 8,\r\n                       double ratio = 0.55)\r\n        : max_depth_(max_depth),\r\n          ratio_(ratio),\r\n          query_result_(),\r\n          nodes_()\r\n    {\r\n        nodes_.push_back(new node(ext));\r\n        root_ = &nodes_[0];\r\n    }\r\n\r\n    void insert(T data, box2d<double> const& box)\r\n    {\r\n        unsigned int depth=0;\r\n        do_insert_data(data,box,root_,depth);\r\n    }\r\n\r\n    query_iterator query_in_box(box2d<double> const& box)\r\n    {\r\n        query_result_.clear();\r\n        query_node(box,query_result_,root_);\r\n        return query_result_.begin();\r\n    }\r\n\r\n    query_iterator query_end()\r\n    {\r\n        return query_result_.end();\r\n    }\r\n\r\n    const_iterator begin() const\r\n    {\r\n        return nodes_.begin();\r\n    }\r\n\r\n\r\n    const_iterator end() const\r\n    {\r\n        return  nodes_.end();\r\n    }\r\n\r\n    void clear ()\r\n    {\r\n        box2d<double> ext = root_->extent_;\r\n        nodes_.clear();\r\n        nodes_.push_back(new node(ext));\r\n        root_ = &nodes_[0];\r\n    }\r\n\r\n    box2d<double> const& extent() const\r\n    {\r\n        return root_->extent_;\r\n    }\r\n\r\nprivate:\r\n\r\n    void query_node(box2d<double> const& box, result_t & result, node * node_) const\r\n    {\r\n        if (node_)\r\n        {\r\n            box2d<double> const& node_extent = node_->extent();\r\n            if (box.intersects(node_extent))\r\n            {\r\n                node_data_iterator i=node_->begin();\r\n                node_data_iterator end=node_->end();\r\n                while ( i!=end)\r\n                {\r\n                    result.push_back(&(*i));\r\n                    ++i;\r\n                }\r\n                for (int k = 0; k < 4; ++k)\r\n                {\r\n                    query_node(box,result,node_->children_[k]);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void do_insert_data(T data, box2d<double> const& box, node * n, unsigned int& depth)\r\n    {\r\n        if (++depth >= max_depth_)\r\n        {\r\n            n->cont_.push_back(data);\r\n        }\r\n        else\r\n        {\r\n            box2d<double> const& node_extent = n->extent();\r\n            box2d<double> ext[4];\r\n            split_box(node_extent,ext);\r\n            for (int i=0;i<4;++i)\r\n            {\r\n                if (ext[i].contains(box))\r\n                {\r\n                    if (!n->children_[i])\r\n                    {\r\n                        nodes_.push_back(new node(ext[i]));\r\n                        n->children_[i]=&nodes_.back();\r\n                    }\r\n                    do_insert_data(data,box,n->children_[i],depth);\r\n                    return;\r\n                }\r\n            }\r\n            n->cont_.push_back(data);\r\n        }\r\n    }\r\n\r\n    void split_box(box2d<double> const& node_extent,box2d<double> * ext)\r\n    {\r\n        //coord2d c=node_extent.center();\r\n\r\n        double width=node_extent.width();\r\n        double height=node_extent.height();\r\n\r\n        double lox=node_extent.minx();\r\n        double loy=node_extent.miny();\r\n        double hix=node_extent.maxx();\r\n        double hiy=node_extent.maxy();\r\n\r\n        ext[0]=box2d<double>(lox,loy,lox + width * ratio_,loy + height * ratio_);\r\n        ext[1]=box2d<double>(hix - width * ratio_,loy,hix,loy + height * ratio_);\r\n        ext[2]=box2d<double>(lox,hiy - height*ratio_,lox + width * ratio_,hiy);\r\n        ext[3]=box2d<double>(hix - width * ratio_,hiy - height*ratio_,hix,hiy);\r\n    }\r\n\r\n    const unsigned int max_depth_;\r\n    const double ratio_;\r\n    result_t query_result_;\r\n    nodes_t nodes_;\r\n    node * root_;\r\n\r\n};\r\n}\r\n\r\n#endif // MAPNIK_QUAD_TREE_HPP\r\n", "meta": {"hexsha": "df4e5ce5a98ac70b81c75075a9b40427efc92799", "size": 6346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/include/mapnik/quad_tree.hpp", "max_stars_repo_name": "Wujingli/OpenWebGlobeDataProcessing", "max_stars_repo_head_hexsha": "932eaa00c81fc0571122bc618ade010fa255735e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external/include/mapnik/quad_tree.hpp", "max_issues_repo_name": "Wujingli/OpenWebGlobeDataProcessing", "max_issues_repo_head_hexsha": "932eaa00c81fc0571122bc618ade010fa255735e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/include/mapnik/quad_tree.hpp", "max_forks_repo_name": "Wujingli/OpenWebGlobeDataProcessing", "max_forks_repo_head_hexsha": "932eaa00c81fc0571122bc618ade010fa255735e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-08T15:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T08:13:01.000Z", "avg_line_length": 27.5913043478, "max_line_length": 89, "alphanum_fraction": 0.5267885282, "num_tokens": 1393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.037892424320813946, "lm_q1q2_score": 0.015434850034580245}}
{"text": "/*=============================================================================\nCopyright (c) 2011, The Trustees of Indiana University\nAll rights reserved.\n\nAuthors: Michael Hansen (mihansen@indiana.edu), Shinya Ito\n\nRedistribution and use in source and binary forms, with or without\nmodification, 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 Indiana University nor the names of its contributors\n     may be used to endorse or promote products derived from this software\n     without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n=============================================================================*/\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/limits.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/program_options.hpp>\n\n#include \"transent.hpp\"\n\n// Typedefs\ntypedef int TimeType;\ntypedef std::vector<TimeType> TimeSeries;\ntypedef std::vector< std::vector<TimeType> > TimeSeriesCollection;\n\ntypedef boost::multi_array<double, 2> ResultMatrix;\ntypedef ResultMatrix::index arr_index;\n\nint main(int argc, char *argv[]) {\n\n  namespace opt = boost::program_options;\n  opt::options_description desc(\"Calculates transfer entropy for a block of time series (y -> x)\");\n  desc.add_options()\n    (\"help\", \"Show this help message\")\n    (\"x-order\", opt::value<TimeType>()->default_value(1), \"Order of predicted time series (default 1)\")\n    (\"y-order\", opt::value<TimeType>()->default_value(1), \"Order of predictor time series (default 1)\")\n    (\"y-delay\", opt::value<TimeType>()->default_value(1), \"Delay of predictor time series (default 1)\")\n    (\"in-file\", opt::value<std::string>(), \"Input time series file path\")\n    (\"out-file\", opt::value<std::string>(), \"Output transfer entropy file path\")\n    (\"col-start\", opt::value<arr_index>()->default_value(0), \"Column offset of block (default 0)\")\n    (\"cols\", opt::value<arr_index>()->default_value(0), \"Columns in block (default 0 for remainder)\")\n    (\"row-start\", opt::value<arr_index>()->default_value(0), \"Row offset of block (default 0)\")\n    (\"rows\", opt::value<arr_index>()->default_value(0), \"Rows in block (default 0 for remainder)\")\n    ;\n\n  opt::variables_map opt_vars;\n  opt::store(opt::parse_command_line(argc, argv, desc), opt_vars);\n  opt::notify(opt_vars);\n\n  if (opt_vars.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return (0);\n  }\n\n  const std::size_t x_order = opt_vars[\"x-order\"].as<TimeType>(),\n                    y_order = opt_vars[\"y-order\"].as<TimeType>(),\n                    y_delay = opt_vars[\"y-delay\"].as<TimeType>();\n\n  const std::size_t num_series = 1 + y_order + x_order;\n\n  assert(x_order > 0);\n  assert(y_order > 0);\n  assert(y_delay > 0);\n\n  if (num_series > MAX_XY_ORDER) {\n    std::cout << \"The combined order of x and y cannot exceed \" << MAX_XY_ORDER << std::endl;\n    return (0);\n  }\n\n  // Parse arguments\n  if (!opt_vars.count(\"in-file\") || !opt_vars.count(\"out-file\")) {\n    std::cout << \"Input and output file paths are required\" << std::endl;\n    return (0);\n  }\n\n  std::string in_file_path = opt_vars[\"in-file\"].as<std::string>(),\n              out_file_path = opt_vars[\"out-file\"].as<std::string>();\n\n  arr_index col_start = opt_vars[\"col-start\"].as<arr_index>(),\n            cols = opt_vars[\"cols\"].as<arr_index>(),\n            row_start = opt_vars[\"row-start\"].as<arr_index>(),\n            rows = opt_vars[\"rows\"].as<arr_index>();\n\n  // Read in time series block\n  std::vector<TimeSeries> all_series;\n\n  std::ifstream in_file(in_file_path.c_str());\n  std::string line;\n\n  getline(in_file, line);\n  TimeType duration = boost::lexical_cast<TimeType>(line);\n\n  while (getline(in_file, line)) {\n\n    std::istringstream line_stream(line);\n    TimeSeries cur_series;\n\n    // This could be more efficient, but it's fast enough for now\n    std::copy(std::istream_iterator<TimeType>(line_stream),\n              std::istream_iterator<TimeType>(),\n              std::back_inserter(cur_series));\n\n    all_series.push_back(cur_series);\n  }\n\n  if (rows == 0) {\n    rows = all_series.size();\n  }\n\n  if (cols == 0) {\n    cols = all_series.size();\n  }\n\n  // Calculate TE\n  ResultMatrix te_result(boost::extents[rows][cols]);\n\n  transent_ho(all_series, x_order, y_order, y_delay, duration, te_result,\n              row_start, rows, col_start, cols);\n\n  // Write results\n  std::ofstream out_file(out_file_path.c_str());\n\n  for (arr_index i = 0; i < rows; ++i) {\n    for (arr_index j = 0; j < cols; ++j) {\n      out_file << te_result[j][i] << \" \";\n    }\n\n    out_file << std::endl;\n  }\n\n  return (0);\n}\n\n", "meta": {"hexsha": "f58fdc5c35b324b28a83a72f3691e2eef03114f8", "size": 5730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/te_block.cpp", "max_stars_repo_name": "darg0001/transfer-entropy-toolbox", "max_stars_repo_head_hexsha": "9b611de3b33ce89d4bf8152596c066089661f88b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T00:13:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-05T00:13:53.000Z", "max_issues_repo_path": "cpp/te_block.cpp", "max_issues_repo_name": "shixnya/transfer-entropy-toolbox", "max_issues_repo_head_hexsha": "932bd33f46799d6a079695d69f24a6220f395c18", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/te_block.cpp", "max_forks_repo_name": "shixnya/transfer-entropy-toolbox", "max_forks_repo_head_hexsha": "932bd33f46799d6a079695d69f24a6220f395c18", "max_forks_repo_licenses": ["BSD-3-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.2658227848, "max_line_length": 103, "alphanum_fraction": 0.6720767888, "num_tokens": 1382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.03210070995788811, "lm_q1q2_score": 0.015423706684965363}}
{"text": "/*\n Copyright (c) 2016-2017 Paul Lagrée\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 <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_01.hpp>\n#include \"common.hpp\"\n\nclass Policy {\n protected:\n  unsigned int n_experts_;                   // Number of experts\n\n  /**\n    Get the `k` largest elements of a vector and returns them as unordered_set.\n    Trick with negative weights to get the lowest element of the priority_queue.\n  */\n  template<typename T>\n  std::unordered_set<T> get_k_largest_arguments(\n        std::vector<float>& vec, unsigned int k) {\n    std::priority_queue<std::pair<float, T>> q;\n    for (T i = 0; i < k; ++i) {\n      q.push(std::pair<float, T>(-vec[i], i));\n    }\n    for (T i = k; i < vec.size(); ++i) {\n      if (q.top().first > -vec[i]) {\n        q.pop();\n        q.push(std::pair<float, T>(-vec[i], i));\n      }\n    }\n    std::unordered_set<T> result;\n    while (!q.empty()) {\n      result.insert(q.top().second);\n      q.pop();\n    }\n    return result;\n  }\n\n public:\n  Policy(unsigned int n_experts) : n_experts_(n_experts) {}\n\n  virtual std::unordered_set<unsigned int> selectExpert(unsigned int k) = 0;\n\n  /**\n    This method does not necessarly need to be overloaded by classes inheriting\n    Policy (e.g. RandomPolicy).\n  */\n  virtual void updateState(unsigned int,\n                           const std::unordered_set<unode_int>&) {}\n\n  /**\n    Reinitialize the object to start parameters.\n  */\n  virtual void init() {}\n};\n\n/**\n  Selects randomly the expert to play at each round.\n*/\nclass RandomPolicy : public Policy {\n private:\n  std::mt19937 gen_;\n  std::uniform_int_distribution<unsigned int> dst_;\n public:\n  RandomPolicy(unsigned int n_experts)\n      : Policy(n_experts), gen_(seed_ns()), dst_(0, n_experts_) {}\n\n  std::unordered_set<unsigned int> selectExpert(unsigned int k) {\n    std::unordered_set<unsigned int> result;\n    while (result.size() < k)\n      result.insert(dst_(gen_));\n    return result;\n  }\n};\n\n/**\n  Type of spread estimation.\n*/\nenum Sigma {\n  MEAN,       // Replace sigma by the mean of observed spreads\n  SAMPLE_STD, // Mean + sampled standard deviation of observed spreads\n  INTERSECTING_SUPPORT, // Simple heuristic when intersecting support isn't null\n};\n\n/**\n  Good-UCB policy for our problem. Each experts maintains a missing mass\n  estimator which is used to select the next expert to play. See paper for\n  details.\n*/\nclass GoodUcbPolicy : public Policy {\n private:\n  std::vector<unode_int>& nb_neighbours_; // Number of reachable nodes for each expert\n  unsigned int t_;                            // Number of rounds played\n  std::vector<float> n_plays_;                // Number of times experts were played\n  // For each expert, hashmap {node : #activations}\n  std::vector<std::unordered_map<unode_int, unsigned int>> n_rewards_;\n  std::vector<std::vector<double>> spreads_;  // List of sampled spreads for each experts\n  Sigma sigma_type_;        // Type of estimation of expert expected diffusion\n\n public:\n  GoodUcbPolicy(unsigned int n_experts, std::vector<unode_int>& nb_neighbours,\n                Sigma type=MEAN)\n      : Policy(n_experts), nb_neighbours_(nb_neighbours),\n        sigma_type_(type) { init(); }\n\n  /**\n    Selects `k` experts whose Good-UCB indices are the largest.\n  */\n  std::unordered_set<unsigned int> selectExpert(unsigned int k) {\n    // 1. Test if all experts were played at least once\n    std::unordered_set<unsigned int> chosen_experts;\n    unsigned int n_selected_experts = 0;\n    for (unsigned int i = 0; i < n_experts_; i++) {\n      if (n_plays_[i] == 0) {\n        chosen_experts.insert(i);\n        n_selected_experts++;\n        if (n_selected_experts == k)\n          break;\n      }\n    }\n    if (chosen_experts.size() > 0) {\n      for (unsigned int i = 0; i < n_experts_ && chosen_experts.size() < k;\n           i++) {\n        chosen_experts.insert(i);\n      }\n      return chosen_experts;\n    }\n    // 2. If all experts were played once, use missing mass estimator\n    std::vector<float> ucbs(n_experts_, 0);\n    for (unsigned int i = 0; i < n_experts_; i++) {\n      // 2. (a) Compute missing mass estimator\n      float missing_mass_i = (float)std::count_if(\n          n_rewards_[i].begin(), n_rewards_[i].end(), [](auto& elt) {\n            return elt.second == 1; // Count hapaxes\n          }) / n_plays_[i];\n      // 2. (b) Compute estimator of expected diffusion from this expert\n      float sigma = 0;\n      for (auto& elt : n_rewards_[i])\n        sigma += elt.second;\n      sigma /= n_plays_[i];\n      if (sigma_type_ == SAMPLE_STD) {  // If we estimate sum of p(x) by the sample mean + std\n        double empirical_std = 0;\n        for (auto elt : spreads_[i])\n          empirical_std += (elt - sigma) * (elt - sigma);\n        if (n_plays_[i] == 1)\n          empirical_std = sigma;\n        else\n          empirical_std = sqrt(empirical_std / (n_plays_[i] - 1));\n        sigma += empirical_std;\n      } else if (sigma_type_ == INTERSECTING_SUPPORT) {\n        missing_mass_i = 0;\n        for (auto& elt : n_rewards_[i]) {\n          if (elt.second != 1)\n            continue;\n          float degree_experts = 1; // Number of experts which activated this node\n          for (unsigned int j = 0; j < n_experts_; j++) {\n            if (i == j)\n              continue;\n            else if (n_rewards_[j].find(elt.first) == n_rewards_[j].end())\n              continue;\n            else\n              degree_experts += 1;\n          }\n          missing_mass_i += 1 / degree_experts;\n        }\n        missing_mass_i /= n_plays_[i];\n      }\n      ucbs[i] = missing_mass_i + (1 + sqrt(2)) * sqrt(sigma * log(4 * t_) /\n          n_plays_[i]) + log(4 * t_) / (3 * n_plays_[i]);\n    }\n    return get_k_largest_arguments<unsigned int>(ucbs, k);\n  }\n\n  /**\n    Update statistics on the chosen expert (k == 1).\n  */\n  void updateState(unsigned int expert,\n                   const std::unordered_set<unode_int>& stage_spread) {\n    t_++;\n    for (auto& activated_node : stage_spread) {\n      if (n_rewards_[expert].count(activated_node) == 0)\n        n_rewards_[expert][activated_node] = 0;\n      n_rewards_[expert][activated_node]++;\n    }\n    spreads_[expert].push_back(stage_spread.size());\n    n_plays_[expert]++;\n  }\n\n  /**\n    Initialize datastructures required for computing UCB bounds. It is useful\n    when restarting the algorithm (to reset).\n  */\n  void init() {\n    t_ = 0;\n    n_plays_ = std::vector<float>(n_experts_, 0);\n    spreads_ = std::vector<std::vector<double>>(n_experts_);\n    for (unsigned int k = 0; k < n_experts_; k++) {\n      n_rewards_.push_back(std::unordered_map<unode_int, unsigned int>());\n    }\n  }\n};\n", "meta": {"hexsha": "9ccbd03b3d0032acb349936f49c77b3ba16cc46d", "size": 7748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Policy.hpp", "max_stars_repo_name": "smaniu/oim", "max_stars_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-05-21T13:54:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T11:47:17.000Z", "max_issues_repo_path": "src/Policy.hpp", "max_issues_repo_name": "smaniu/oim", "max_issues_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-30T03:34:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-25T18:28:38.000Z", "max_forks_repo_path": "src/Policy.hpp", "max_forks_repo_name": "smaniu/oim", "max_forks_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T08:45:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-17T04:36:22.000Z", "avg_line_length": 34.7443946188, "max_line_length": 94, "alphanum_fraction": 0.6402942695, "num_tokens": 1953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03210070799021097, "lm_q1q2_score": 0.015423705739538454}}
{"text": "//\n// $Id$\n//\n//\n// Original author: Matt Chambers <matt.chambers <a.t> vanderbilt.edu>\n//\n// Copyright 2008 Vanderbilt University - Nashville, TN 37232\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \n// you may not use this file except in compliance with the License. \n// You may obtain a copy of the License at \n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software \n// distributed under the License is distributed on an \"AS IS\" BASIS, \n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n// See the License for the specific language governing permissions and \n// limitations under the License.\n//\n\n\n#ifndef _SAVITZKYGOLAYSMOOTHER_HPP_ \n#define _SAVITZKYGOLAYSMOOTHER_HPP_\n\n\n#include \"Smoother.hpp\"\n#include <vector>\n#include <boost/shared_ptr.hpp>\n\n\nnamespace pwiz {\nnamespace analysis {\n\n\nstruct PWIZ_API_DECL SavitzkyGolaySmoother : public Smoother\n{\n    SavitzkyGolaySmoother(int polynomialOrder, int windowSize);\n    ~SavitzkyGolaySmoother();\n\n    /// smooth y values to existing vectors using Savitzky-Golay algorithm;\n    /// preconditions:\n    /// - samples within the window must be (approximately) equally spaced\n    virtual void smooth(const std::vector<double>& x, const std::vector<double>& y,\n                        std::vector<double>& xSmoothed, std::vector<double>& ySmoothed);\n\n    /// smooth y values and copy back to the input vectors using Savitzky-Golay algorithm;\n    /// preconditions:\n    /// - samples within the window must be (approximately) equally spaced\n    virtual void smooth_copy(std::vector<double>& x, std::vector<double>& y);\n\n    private:\n    struct Impl;\n    boost::shared_ptr<Impl> impl_;\n};\n\n\n} // namespace analysis\n} // namespace pwiz\n\n#endif // _SAVITZKYGOLAYSMOOTHER_HPP_\n", "meta": {"hexsha": "d2d36a563615e4a6bee73b09ac7738f9e1fb03c1", "size": 1837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/analysis/common/SavitzkyGolaySmoother.hpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz/analysis/common/SavitzkyGolaySmoother.hpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/analysis/common/SavitzkyGolaySmoother.hpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6290322581, "max_line_length": 90, "alphanum_fraction": 0.7196516059, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.03258974617542131, "lm_q1q2_score": 0.015404634524375599}}
{"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    ISAM2-inl.h\n * @brief   Incremental update functionality (ISAM2) for BayesTree, with fluid relinearization.\n * @author  Michael Kaess, Richard Roberts\n */\n\n#include <boost/foreach.hpp>\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <gtsam/base/timing.h>\n#include <gtsam/base/debug.h>\n#include <gtsam/inference/BayesTree.h>\n#include <gtsam/linear/GaussianJunctionTree.h>\n#include <gtsam/linear/GaussianSequentialSolver.h>\n#include <gtsam/linear/HessianFactor.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n\n#include <gtsam/nonlinear/ISAM2.h>\n#include <gtsam/nonlinear/DoglegOptimizerImpl.h>\n#include <gtsam/nonlinear/nonlinearExceptions.h>\n#include <gtsam/nonlinear/LinearContainerFactor.h>\n\nnamespace gtsam {\n\nusing namespace std;\n\nstatic const bool disableReordering = false;\nstatic const double batchThreshold = 0.65;\n\n/* ************************************************************************* */\nstd::string ISAM2DoglegParams::adaptationModeTranslator(const DoglegOptimizerImpl::TrustRegionAdaptationMode& adaptationMode) const {\n  std::string s;\n  switch (adaptationMode) {\n  case DoglegOptimizerImpl::SEARCH_EACH_ITERATION:   s = \"SEARCH_EACH_ITERATION\";  break;\n  case DoglegOptimizerImpl::ONE_STEP_PER_ITERATION:  s = \"ONE_STEP_PER_ITERATION\"; break;\n  default:                                           s = \"UNDEFINED\";              break;\n  }\n  return s;\n}\n\n/* ************************************************************************* */\nDoglegOptimizerImpl::TrustRegionAdaptationMode ISAM2DoglegParams::adaptationModeTranslator(const std::string& adaptationMode) const {\n  std::string s = adaptationMode;  boost::algorithm::to_upper(s);\n  if (s == \"SEARCH_EACH_ITERATION\")  return DoglegOptimizerImpl::SEARCH_EACH_ITERATION;\n  if (s == \"ONE_STEP_PER_ITERATION\") return DoglegOptimizerImpl::ONE_STEP_PER_ITERATION;\n\n  /* default is SEARCH_EACH_ITERATION */\n  return DoglegOptimizerImpl::SEARCH_EACH_ITERATION;\n}\n\n/* ************************************************************************* */\nISAM2Params::Factorization ISAM2Params::factorizationTranslator(const std::string& str) const {\n  std::string s = str;  boost::algorithm::to_upper(s);\n  if (s == \"QR\") return ISAM2Params::QR;\n  if (s == \"CHOLESKY\") return ISAM2Params::CHOLESKY;\n\n  /* default is CHOLESKY */\n  return ISAM2Params::CHOLESKY;\n}\n\n/* ************************************************************************* */\nstd::string ISAM2Params::factorizationTranslator(const ISAM2Params::Factorization& value) const {\n  std::string s;\n  switch (value) {\n  case ISAM2Params::QR:         s = \"QR\"; break;\n  case ISAM2Params::CHOLESKY:   s = \"CHOLESKY\"; break;\n  default:                      s = \"UNDEFINED\"; break;\n  }\n  return s;\n}\n\n/* ************************************************************************* */\nISAM2::ISAM2(const ISAM2Params& params):\n    deltaDoglegUptodate_(true), deltaUptodate_(true), params_(params) {\n  if(params_.optimizationParams.type() == typeid(ISAM2DoglegParams))\n    doglegDelta_ = boost::get<ISAM2DoglegParams>(params_.optimizationParams).initialDelta;\n}\n\n/* ************************************************************************* */\nISAM2::ISAM2():\n    deltaDoglegUptodate_(true), deltaUptodate_(true) {\n  if(params_.optimizationParams.type() == typeid(ISAM2DoglegParams))\n    doglegDelta_ = boost::get<ISAM2DoglegParams>(params_.optimizationParams).initialDelta;\n}\n\n/* ************************************************************************* */\nISAM2::ISAM2(const ISAM2& other) {\n  *this = other;\n}\n\n/* ************************************************************************* */\nISAM2& ISAM2::operator=(const ISAM2& rhs) {\n  // Copy BayesTree\n  this->Base::operator=(rhs);\n\n  // Copy our variables\n  // When we have Permuted<...>, it is only necessary to copy this permuted\n  // view and not the original, because copying the permuted view automatically\n  // copies the original.\n  theta_ = rhs.theta_;\n  variableIndex_ = rhs.variableIndex_;\n  delta_ = rhs.delta_;\n  deltaNewton_ = rhs.deltaNewton_;\n  RgProd_ = rhs.RgProd_;\n  deltaDoglegUptodate_ = rhs.deltaDoglegUptodate_;\n  deltaUptodate_ = rhs.deltaUptodate_;\n  deltaReplacedMask_ = rhs.deltaReplacedMask_;\n  nonlinearFactors_ = rhs.nonlinearFactors_;\n\n  linearFactors_ = GaussianFactorGraph();\n  linearFactors_.reserve(rhs.linearFactors_.size());\n  BOOST_FOREACH(const GaussianFactor::shared_ptr& linearFactor, rhs.linearFactors_) {\n    linearFactors_.push_back(linearFactor ? linearFactor->clone() : GaussianFactor::shared_ptr()); }\n\n  ordering_ = rhs.ordering_;\n  params_ = rhs.params_;\n  doglegDelta_ = rhs.doglegDelta_;\n\n  lastAffectedVariableCount = rhs.lastAffectedVariableCount;\n  lastAffectedFactorCount = rhs.lastAffectedFactorCount;\n  lastAffectedCliqueCount = rhs.lastAffectedCliqueCount;\n  lastAffectedMarkedCount = rhs.lastAffectedMarkedCount;\n  lastBacksubVariableCount = rhs.lastBacksubVariableCount;\n  lastNnzTop = rhs.lastNnzTop;\n\n  return *this;\n}\n\n/* ************************************************************************* */\nFastList<size_t> ISAM2::getAffectedFactors(const FastList<Index>& keys) const {\n  static const bool debug = false;\n  if(debug) cout << \"Getting affected factors for \";\n  if(debug) { BOOST_FOREACH(const Index key, keys) { cout << key << \" \"; } }\n  if(debug) cout << endl;\n\n  FactorGraph<NonlinearFactor > allAffected;\n  FastList<size_t> indices;\n  BOOST_FOREACH(const Index key, keys) {\n//    const list<size_t> l = nonlinearFactors_.factors(key);\n//    indices.insert(indices.begin(), l.begin(), l.end());\n    const VariableIndex::Factors& factors(variableIndex_[key]);\n    BOOST_FOREACH(size_t factor, factors) {\n      if(debug) cout << \"Variable \" << key << \" affects factor \" << factor << endl;\n      indices.push_back(factor);\n    }\n  }\n  indices.sort();\n  indices.unique();\n  if(debug) cout << \"Affected factors are: \";\n  if(debug) { BOOST_FOREACH(const size_t index, indices) { cout << index << \" \"; } }\n  if(debug) cout << endl;\n  return indices;\n}\n\n/* ************************************************************************* */\n// retrieve all factors that ONLY contain the affected variables\n// (note that the remaining stuff is summarized in the cached factors)\nFactorGraph<GaussianFactor>::shared_ptr\nISAM2::relinearizeAffectedFactors(const FastList<Index>& affectedKeys, const FastSet<Index>& relinKeys) const {\n\n  gttic(getAffectedFactors);\n  FastList<size_t> candidates = getAffectedFactors(affectedKeys);\n  gttoc(getAffectedFactors);\n\n  NonlinearFactorGraph nonlinearAffectedFactors;\n\n  gttic(affectedKeysSet);\n  // for fast lookup below\n  FastSet<Index> affectedKeysSet;\n  affectedKeysSet.insert(affectedKeys.begin(), affectedKeys.end());\n  gttoc(affectedKeysSet);\n\n  gttic(check_candidates_and_linearize);\n  FactorGraph<GaussianFactor>::shared_ptr linearized = boost::make_shared<FactorGraph<GaussianFactor> >();\n  BOOST_FOREACH(size_t idx, candidates) {\n    bool inside = true;\n    bool useCachedLinear = params_.cacheLinearizedFactors;\n    BOOST_FOREACH(Key key, nonlinearFactors_[idx]->keys()) {\n      Index var = ordering_[key];\n      if(affectedKeysSet.find(var) == affectedKeysSet.end()) {\n        inside = false;\n        break;\n      }\n      if(useCachedLinear && relinKeys.find(var) != relinKeys.end())\n        useCachedLinear = false;\n    }\n    if(inside) {\n      if(useCachedLinear) {\n#ifdef GTSAM_EXTRA_CONSISTENCY_CHECKS\n        assert(linearFactors_[idx]);\n        assert(linearFactors_[idx]->keys() == nonlinearFactors_[idx]->symbolic(ordering_)->keys());\n#endif\n        linearized->push_back(linearFactors_[idx]);\n      } else {\n        GaussianFactor::shared_ptr linearFactor = nonlinearFactors_[idx]->linearize(theta_, ordering_);\n        linearized->push_back(linearFactor);\n        if(params_.cacheLinearizedFactors) {\n#ifdef GTSAM_EXTRA_CONSISTENCY_CHECKS\n          assert(linearFactors_[idx]->keys() == linearFactor->keys());\n#endif\n          linearFactors_[idx] = linearFactor;\n        }\n      }\n    }\n  }\n  gttoc(check_candidates_and_linearize);\n\n  return linearized;\n}\n\n/* ************************************************************************* */\n// find intermediate (linearized) factors from cache that are passed into the affected area\nGaussianFactorGraph ISAM2::getCachedBoundaryFactors(Cliques& orphans) {\n\n  static const bool debug = false;\n\n  GaussianFactorGraph cachedBoundary;\n\n  BOOST_FOREACH(sharedClique orphan, orphans) {\n    // find the last variable that was eliminated\n    Index key = (*orphan)->frontals().back();\n    // retrieve the cached factor and add to boundary\n    cachedBoundary.push_back(orphan->cachedFactor());\n    if(debug) { cout << \"Cached factor for variable \" << key; orphan->cachedFactor()->print(\"\"); }\n  }\n\n  return cachedBoundary;\n}\n\nboost::shared_ptr<FastSet<Index> > ISAM2::recalculate(const FastSet<Index>& markedKeys,\n    const FastSet<Index>& relinKeys, const FastVector<Index>& observedKeys, const FastSet<Index>& unusedIndices,\n    const boost::optional<FastMap<Index,int> >& constrainKeys, ISAM2Result& result) {\n\n  // TODO:  new factors are linearized twice, the newFactors passed in are not used.\n\n  const bool debug = ISDEBUG(\"ISAM2 recalculate\");\n\n  // Input: BayesTree(this), newFactors\n\n//#define PRINT_STATS // figures for paper, disable for timing\n#ifdef PRINT_STATS\n  static int counter = 0;\n  int maxClique = 0;\n  double avgClique = 0;\n  int numCliques = 0;\n  int nnzR = 0;\n  if (counter>0) { // cannot call on empty tree\n    GaussianISAM2_P::CliqueData cdata =  this->getCliqueData();\n    GaussianISAM2_P::CliqueStats cstats = cdata.getStats();\n    maxClique = cstats.maxCONDITIONALSize;\n    avgClique = cstats.avgCONDITIONALSize;\n    numCliques = cdata.conditionalSizes.size();\n    nnzR = calculate_nnz(this->root());\n  }\n  counter++;\n#endif\n\n  if(debug) {\n    cout << \"markedKeys: \";\n    BOOST_FOREACH(const Index key, markedKeys) { cout << key << \" \"; }\n    cout << endl;\n    cout << \"observedKeys: \";\n    BOOST_FOREACH(const Index key, observedKeys) { cout << key << \" \"; }\n    cout << endl;\n  }\n\n  // 1. Remove top of Bayes tree and convert to a factor graph:\n  // (a) For each affected variable, remove the corresponding clique and all parents up to the root.\n  // (b) Store orphaned sub-trees \\BayesTree_{O} of removed cliques.\n  gttic(removetop);\n  Cliques orphans;\n  BayesNet<GaussianConditional> affectedBayesNet;\n  this->removeTop(markedKeys, affectedBayesNet, orphans);\n  gttoc(removetop);\n\n  if(debug) affectedBayesNet.print(\"Removed top: \");\n  if(debug) orphans.print(\"Orphans: \");\n\n  //    FactorGraph<GaussianFactor> factors(affectedBayesNet);\n  // bug was here: we cannot reuse the original factors, because then the cached factors get messed up\n  // [all the necessary data is actually contained in the affectedBayesNet, including what was passed in from the boundaries,\n  //  so this would be correct; however, in the process we also generate new cached_ entries that will be wrong (ie. they don't\n  //  contain what would be passed up at a certain point if batch elimination was done, but that's what we need); we could choose\n  //  not to update cached_ from here, but then the new information (and potentially different variable ordering) is not reflected\n  //  in the cached_ values which again will be wrong]\n  // so instead we have to retrieve the original linearized factors AND add the cached factors from the boundary\n\n  // BEGIN OF COPIED CODE\n\n  // ordering provides all keys in conditionals, there cannot be others because path to root included\n  gttic(affectedKeys);\n  FastList<Index> affectedKeys = affectedBayesNet.ordering();\n  gttoc(affectedKeys);\n\n  boost::shared_ptr<FastSet<Index> > affectedKeysSet(new FastSet<Index>()); // Will return this result\n\n  if(affectedKeys.size() >= theta_.size() * batchThreshold) {\n\n    gttic(batch);\n\n    gttic(add_keys);\n    BOOST_FOREACH(const Ordering::value_type& key_index, ordering_) { affectedKeysSet->insert(key_index.second); }\n    gttoc(add_keys);\n\n    gttic(reorder);\n    gttic(CCOLAMD);\n    // Do a batch step - reorder and relinearize all variables\n    vector<int> cmember(theta_.size(), 0);\n    if(constrainKeys) {\n      if(!constrainKeys->empty()) {\n        typedef std::pair<const Index,int> Index_Group;\n        if(theta_.size() > constrainKeys->size()) { // Only if some variables are unconstrained\n          BOOST_FOREACH(const Index_Group& index_group, *constrainKeys) {\n            cmember[index_group.first] = index_group.second; }\n        } else {\n          int minGroup = *boost::range::min_element(boost::adaptors::values(*constrainKeys));\n          BOOST_FOREACH(const Index_Group& index_group, *constrainKeys) {\n            cmember[index_group.first] = index_group.second - minGroup; }\n        }\n      }\n    } else {\n      if(theta_.size() > observedKeys.size()) { // Only if some variables are unconstrained\n        BOOST_FOREACH(Index var, observedKeys) { cmember[var] = 1; }\n      }\n    }\n    Permutation::shared_ptr colamd(inference::PermutationCOLAMD_(variableIndex_, cmember));\n    Permutation::shared_ptr colamdInverse(colamd->inverse());\n    gttoc(CCOLAMD);\n\n    // Reorder\n    gttic(permute_global_variable_index);\n    variableIndex_.permuteInPlace(*colamd);\n    gttoc(permute_global_variable_index);\n    gttic(permute_delta);\n    delta_.permuteInPlace(*colamd);\n    deltaNewton_.permuteInPlace(*colamd);\n    RgProd_.permuteInPlace(*colamd);\n    gttoc(permute_delta);\n    gttic(permute_ordering);\n    ordering_.permuteInPlace(*colamd);\n    gttoc(permute_ordering);\n    gttoc(reorder);\n\n    gttic(linearize);\n    GaussianFactorGraph linearized = *nonlinearFactors_.linearize(theta_, ordering_);\n    if(params_.cacheLinearizedFactors)\n      linearFactors_ = linearized;\n    gttoc(linearize);\n\n    gttic(eliminate);\n    JunctionTree<GaussianFactorGraph, Base::Clique> jt(linearized, variableIndex_);\n    sharedClique newRoot;\n    if(params_.factorization == ISAM2Params::CHOLESKY)\n      newRoot = jt.eliminate(EliminatePreferCholesky);\n    else if(params_.factorization == ISAM2Params::QR)\n      newRoot = jt.eliminate(EliminateQR);\n    else assert(false);\n    if(debug) newRoot->print(\"Eliminated: \");\n    gttoc(eliminate);\n\n    gttic(insert);\n    this->clear();\n    this->insert(newRoot);\n    gttoc(insert);\n\n    result.variablesReeliminated = affectedKeysSet->size();\n    result.factorsRecalculated = nonlinearFactors_.size();\n\n    lastAffectedMarkedCount = markedKeys.size();\n    lastAffectedVariableCount = affectedKeysSet->size();\n    lastAffectedFactorCount = linearized.size();\n\n    // Reeliminated keys for detailed results\n    if(params_.enableDetailedResults) {\n      BOOST_FOREACH(Key key, theta_.keys()) {\n        result.detail->variableStatus[key].isReeliminated = true;\n      }\n    }\n\n    gttoc(batch);\n\n  } else {\n\n    gttic(incremental);\n\n    // 2. Add the new factors \\Factors' into the resulting factor graph\n    FastList<Index> affectedAndNewKeys;\n    affectedAndNewKeys.insert(affectedAndNewKeys.end(), affectedKeys.begin(), affectedKeys.end());\n    affectedAndNewKeys.insert(affectedAndNewKeys.end(), observedKeys.begin(), observedKeys.end());\n    gttic(relinearizeAffected);\n    GaussianFactorGraph factors(*relinearizeAffectedFactors(affectedAndNewKeys, relinKeys));\n    if(debug) factors.print(\"Relinearized factors: \");\n    gttoc(relinearizeAffected);\n\n    if(debug) { cout << \"Affected keys: \"; BOOST_FOREACH(const Index key, affectedKeys) { cout << key << \" \"; } cout << endl; }\n\n    // Reeliminated keys for detailed results\n    if(params_.enableDetailedResults) {\n      BOOST_FOREACH(Index index, affectedAndNewKeys) {\n        result.detail->variableStatus[ordering_.key(index)].isReeliminated = true;\n      }\n    }\n\n    result.variablesReeliminated = affectedAndNewKeys.size();\n    result.factorsRecalculated = factors.size();\n    lastAffectedMarkedCount = markedKeys.size();\n    lastAffectedVariableCount = affectedKeys.size();\n    lastAffectedFactorCount = factors.size();\n\n#ifdef PRINT_STATS\n    // output for generating figures\n    cout << \"linear: #markedKeys: \" << markedKeys.size() << \" #affectedVariables: \" << affectedKeys.size()\n              << \" #affectedFactors: \" << factors.size() << \" maxCliqueSize: \" << maxClique\n              << \" avgCliqueSize: \" << avgClique << \" #Cliques: \" << numCliques << \" nnzR: \" << nnzR << endl;\n#endif\n\n    gttic(cached);\n    // add the cached intermediate results from the boundary of the orphans ...\n    GaussianFactorGraph cachedBoundary = getCachedBoundaryFactors(orphans);\n    if(debug) cachedBoundary.print(\"Boundary factors: \");\n    factors.push_back(cachedBoundary);\n    gttoc(cached);\n\n    // END OF COPIED CODE\n\n    // 3. Re-order and eliminate the factor graph into a Bayes net (Algorithm [alg:eliminate]), and re-assemble into a new Bayes tree (Algorithm [alg:BayesTree])\n\n    gttic(reorder_and_eliminate);\n\n    gttic(list_to_set);\n    // create a partial reordering for the new and contaminated factors\n    // markedKeys are passed in: those variables will be forced to the end in the ordering\n    affectedKeysSet->insert(markedKeys.begin(), markedKeys.end());\n    affectedKeysSet->insert(affectedKeys.begin(), affectedKeys.end());\n    gttoc(list_to_set);\n\n    gttic(PartialSolve);\n    Impl::ReorderingMode reorderingMode;\n    reorderingMode.nFullSystemVars = ordering_.size();\n    reorderingMode.algorithm = Impl::ReorderingMode::COLAMD;\n    reorderingMode.constrain = Impl::ReorderingMode::CONSTRAIN_LAST;\n    if(constrainKeys) {\n      reorderingMode.constrainedKeys = *constrainKeys;\n    } else {\n      reorderingMode.constrainedKeys = FastMap<Index,int>();\n      BOOST_FOREACH(Index var, observedKeys) { reorderingMode.constrainedKeys->insert(make_pair(var, 1)); }\n    }\n    FastSet<Index> affectedUsedKeys = *affectedKeysSet; // Remove unused keys from the set we pass to PartialSolve\n    BOOST_FOREACH(Index unused, unusedIndices) {\n      affectedUsedKeys.erase(unused);\n    }\n    // Remove unaffected keys from the constraints\n    FastMap<Index,int>::iterator iter = reorderingMode.constrainedKeys->begin();\n    while(iter != reorderingMode.constrainedKeys->end()) {\n      if(affectedUsedKeys.find(iter->first) == affectedUsedKeys.end()) {\n        reorderingMode.constrainedKeys->erase(iter++);\n      } else {\n        ++iter;\n      }\n    }\n    Impl::PartialSolveResult partialSolveResult =\n        Impl::PartialSolve(factors, affectedUsedKeys, reorderingMode, (params_.factorization == ISAM2Params::QR));\n    gttoc(PartialSolve);\n\n    // We now need to permute everything according this partial reordering: the\n    // delta vector, the global ordering, and the factors we're about to\n    // re-eliminate.  The reordered variables are also mentioned in the\n    // orphans and the leftover cached factors.\n    gttic(permute_global_variable_index);\n    variableIndex_.permuteInPlace(partialSolveResult.reorderingSelector, partialSolveResult.reorderingPermutation);\n    gttoc(permute_global_variable_index);\n    gttic(permute_delta);\n    delta_.permuteInPlace(partialSolveResult.reorderingSelector, partialSolveResult.reorderingPermutation);\n    deltaNewton_.permuteInPlace(partialSolveResult.reorderingSelector, partialSolveResult.reorderingPermutation);\n    RgProd_.permuteInPlace(partialSolveResult.reorderingSelector, partialSolveResult.reorderingPermutation);\n    gttoc(permute_delta);\n    gttic(permute_ordering);\n    ordering_.permuteInPlace(partialSolveResult.reorderingSelector, partialSolveResult.reorderingPermutation);\n    gttoc(permute_ordering);\n    if(params_.cacheLinearizedFactors) {\n      gttic(permute_cached_linear);\n      //linearFactors_.permuteWithInverse(partialSolveResult.fullReorderingInverse);\n      FastList<size_t> permuteLinearIndices = getAffectedFactors(affectedAndNewKeys);\n      BOOST_FOREACH(size_t idx, permuteLinearIndices) {\n        linearFactors_[idx]->reduceWithInverse(partialSolveResult.reorderingInverse);\n      }\n      gttoc(permute_cached_linear);\n    }\n\n    gttoc(reorder_and_eliminate);\n\n    gttic(reassemble);\n    if(partialSolveResult.bayesTree) {\n      assert(!this->root_);\n      this->insert(partialSolveResult.bayesTree);\n    }\n    gttoc(reassemble);\n\n    // 4. Insert the orphans back into the new Bayes tree.\n    gttic(orphans);\n    gttic(permute);\n    BOOST_FOREACH(sharedClique orphan, orphans) {\n      (void)orphan->reduceSeparatorWithInverse(partialSolveResult.reorderingInverse);\n    }\n    gttoc(permute);\n    gttic(insert);\n    // add orphans to the bottom of the new tree\n    BOOST_FOREACH(sharedClique orphan, orphans) {\n      // Because the affectedKeysSelector is sorted, the orphan separator keys\n      // will be sorted correctly according to the new elimination order after\n      // applying the permutation, so findParentClique, which looks for the\n      // lowest-ordered parent, will still work.\n      Index parentRepresentative = Base::findParentClique((*orphan)->parents());\n      sharedClique parent = (*this)[parentRepresentative];\n      parent->children_ += orphan;\n      orphan->parent_ = parent; // set new parent!\n    }\n    gttoc(insert);\n    gttoc(orphans);\n\n    gttoc(incremental);\n  }\n\n  // Root clique variables for detailed results\n  if(params_.enableDetailedResults) {\n    BOOST_FOREACH(Index index, this->root()->conditional()->frontals()) {\n      result.detail->variableStatus[ordering_.key(index)].inRootClique = true;\n    }\n  }\n\n  return affectedKeysSet;\n}\n\n/* ************************************************************************* */\nISAM2Result ISAM2::update(\n    const NonlinearFactorGraph& newFactors, const Values& newTheta, const FastVector<size_t>& removeFactorIndices,\n    const boost::optional<FastMap<Key,int> >& constrainedKeys, const boost::optional<FastList<Key> >& noRelinKeys,\n    const boost::optional<FastList<Key> >& extraReelimKeys, bool force_relinearize) {\n\n  const bool debug = ISDEBUG(\"ISAM2 update\");\n  const bool verbose = ISDEBUG(\"ISAM2 update verbose\");\n\n  static int count = 0;\n  count++;\n\n  lastAffectedVariableCount = 0;\n  lastAffectedFactorCount = 0;\n  lastAffectedCliqueCount = 0;\n  lastAffectedMarkedCount = 0;\n  lastBacksubVariableCount = 0;\n  lastNnzTop = 0;\n  ISAM2Result result;\n  if(params_.enableDetailedResults)\n    result.detail = ISAM2Result::DetailedResults();\n  const bool relinearizeThisStep = force_relinearize || (params_.enableRelinearization && count % params_.relinearizeSkip == 0);\n\n  if(verbose) {\n    cout << \"ISAM2::update\\n\";\n    this->print(\"ISAM2: \");\n  }\n\n  // Update delta if we need it to check relinearization later\n  if(relinearizeThisStep) {\n    gttic(updateDelta);\n    updateDelta(disableReordering);\n    gttoc(updateDelta);\n  }\n\n  gttic(push_back_factors);\n  // Add the new factor indices to the result struct\n  result.newFactorsIndices.resize(newFactors.size());\n  for(size_t i=0; i<newFactors.size(); ++i)\n    result.newFactorsIndices[i] = i + nonlinearFactors_.size();\n\n  // 1. Add any new factors \\Factors:=\\Factors\\cup\\Factors'.\n  if(debug || verbose) newFactors.print(\"The new factors are: \");\n  nonlinearFactors_.push_back(newFactors);\n\n  // Remove the removed factors\n  NonlinearFactorGraph removeFactors; removeFactors.reserve(removeFactorIndices.size());\n  BOOST_FOREACH(size_t index, removeFactorIndices) {\n    removeFactors.push_back(nonlinearFactors_[index]);\n    nonlinearFactors_.remove(index);\n    if(params_.cacheLinearizedFactors)\n      linearFactors_.remove(index);\n  }\n\n  // Remove removed factors from the variable index so we do not attempt to relinearize them\n  variableIndex_.remove(removeFactorIndices, *removeFactors.symbolic(ordering_));\n\n  // Compute unused keys and indices\n  FastSet<Key> unusedKeys;\n  FastSet<Index> unusedIndices;\n  {\n    // Get keys from removed factors and new factors, and compute unused keys,\n    // i.e., keys that are empty now and do not appear in the new factors.\n    FastSet<Key> removedAndEmpty;\n    BOOST_FOREACH(Key key, removeFactors.keys()) {\n      if(variableIndex_[ordering_[key]].empty())\n        removedAndEmpty.insert(removedAndEmpty.end(), key);\n    }\n    FastSet<Key> newFactorSymbKeys = newFactors.keys();\n    std::set_difference(removedAndEmpty.begin(), removedAndEmpty.end(),\n      newFactorSymbKeys.begin(), newFactorSymbKeys.end(), std::inserter(unusedKeys, unusedKeys.end()));\n\n    // Get indices for unused keys\n    BOOST_FOREACH(Key key, unusedKeys) {\n      unusedIndices.insert(unusedIndices.end(), ordering_[key]);\n    }\n  }\n  gttoc(push_back_factors);\n\n  gttic(add_new_variables);\n  // 2. Initialize any new variables \\Theta_{new} and add \\Theta:=\\Theta\\cup\\Theta_{new}.\n  Impl::AddVariables(newTheta, theta_, delta_, deltaNewton_, RgProd_, deltaReplacedMask_, ordering_);\n  // New keys for detailed results\n  if(params_.enableDetailedResults) {\n    BOOST_FOREACH(Key key, newTheta.keys()) { result.detail->variableStatus[key].isNew = true; } }\n  gttoc(add_new_variables);\n\n  gttic(evaluate_error_before);\n  if(params_.evaluateNonlinearError)\n    result.errorBefore.reset(nonlinearFactors_.error(calculateEstimate()));\n  gttoc(evaluate_error_before);\n\n  gttic(gather_involved_keys);\n  // 3. Mark linear update\n  FastSet<Index> markedKeys = Impl::IndicesFromFactors(ordering_, newFactors); // Get keys from new factors\n  // Also mark keys involved in removed factors\n  {\n    FastSet<Index> markedRemoveKeys = Impl::IndicesFromFactors(ordering_, removeFactors); // Get keys involved in removed factors\n    markedKeys.insert(markedRemoveKeys.begin(), markedRemoveKeys.end()); // Add to the overall set of marked keys\n  }\n  // Also mark any provided extra re-eliminate keys\n  if(extraReelimKeys) {\n    BOOST_FOREACH(Key key, *extraReelimKeys) {\n      markedKeys.insert(ordering_.at(key));\n    }\n  }\n\n  // Observed keys for detailed results\n  if(params_.enableDetailedResults) {\n    BOOST_FOREACH(Index index, markedKeys) {\n      result.detail->variableStatus[ordering_.key(index)].isObserved = true;\n    }\n  }\n  // NOTE: we use assign instead of the iterator constructor here because this\n  // is a vector of size_t, so the constructor unintentionally resolves to\n  // vector(size_t count, Index value) instead of the iterator constructor.\n  FastVector<Index> observedKeys;  observedKeys.reserve(markedKeys.size());\n  BOOST_FOREACH(Index index, markedKeys) {\n    if(unusedIndices.find(index) == unusedIndices.end()) // Only add if not unused\n      observedKeys.push_back(index); // Make a copy of these, as we'll soon add to them\n  }\n  gttoc(gather_involved_keys);\n\n  // Check relinearization if we're at the nth step, or we are using a looser loop relin threshold\n  FastSet<Index> relinKeys;\n  if (relinearizeThisStep) {\n    gttic(gather_relinearize_keys);\n    // 4. Mark keys in \\Delta above threshold \\beta: J=\\{\\Delta_{j}\\in\\Delta|\\Delta_{j}\\geq\\beta\\}.\n    if(params_.enablePartialRelinearizationCheck)\n      relinKeys = Impl::CheckRelinearizationPartial(root_, delta_, ordering_, params_.relinearizeThreshold);\n    else\n      relinKeys = Impl::CheckRelinearizationFull(delta_, ordering_, params_.relinearizeThreshold);\n    if(disableReordering) relinKeys = Impl::CheckRelinearizationFull(delta_, ordering_, 0.0); // This is used for debugging\n\n    // Remove from relinKeys any keys whose linearization points are fixed\n    BOOST_FOREACH(Key key, fixedVariables_) {\n      relinKeys.erase(ordering_[key]);\n    }\n    if(noRelinKeys) {\n      BOOST_FOREACH(Key key, *noRelinKeys) {\n        relinKeys.erase(ordering_[key]);\n      }\n    }\n\n    // Above relin threshold keys for detailed results\n    if(params_.enableDetailedResults) {\n      BOOST_FOREACH(Index index, relinKeys) {\n        result.detail->variableStatus[ordering_.key(index)].isAboveRelinThreshold = true;\n        result.detail->variableStatus[ordering_.key(index)].isRelinearized = true; } }\n\n    // Add the variables being relinearized to the marked keys\n    vector<bool> markedRelinMask(ordering_.size(), false);\n    BOOST_FOREACH(const Index j, relinKeys) { markedRelinMask[j] = true; }\n    markedKeys.insert(relinKeys.begin(), relinKeys.end());\n    gttoc(gather_relinearize_keys);\n\n    gttic(fluid_find_all);\n    // 5. Mark all cliques that involve marked variables \\Theta_{J} and all their ancestors.\n    if (!relinKeys.empty() && this->root()) {\n      // add other cliques that have the marked ones in the separator\n      Impl::FindAll(this->root(), markedKeys, markedRelinMask);\n\n      // Relin involved keys for detailed results\n      if(params_.enableDetailedResults) {\n        FastSet<Index> involvedRelinKeys;\n        Impl::FindAll(this->root(), involvedRelinKeys, markedRelinMask);\n        BOOST_FOREACH(Index index, involvedRelinKeys) {\n          if(!result.detail->variableStatus[ordering_.key(index)].isAboveRelinThreshold) {\n            result.detail->variableStatus[ordering_.key(index)].isRelinearizeInvolved = true;\n            result.detail->variableStatus[ordering_.key(index)].isRelinearized = true; } }\n      }\n    }\n    gttoc(fluid_find_all);\n\n    gttic(expmap);\n    // 6. Update linearization point for marked variables: \\Theta_{J}:=\\Theta_{J}+\\Delta_{J}.\n    if (!relinKeys.empty())\n      Impl::ExpmapMasked(theta_, delta_, ordering_, markedRelinMask, delta_);\n    gttoc(expmap);\n\n    result.variablesRelinearized = markedKeys.size();\n  } else {\n    result.variablesRelinearized = 0;\n  }\n\n  gttic(linearize_new);\n  // 7. Linearize new factors\n  if(params_.cacheLinearizedFactors) {\n    gttic(linearize);\n    FactorGraph<GaussianFactor>::shared_ptr linearFactors = newFactors.linearize(theta_, ordering_);\n    linearFactors_.push_back(*linearFactors);\n    assert(nonlinearFactors_.size() == linearFactors_.size());\n    gttoc(linearize);\n\n    gttic(augment_VI);\n    // Augment the variable index with the new factors\n    variableIndex_.augment(*linearFactors);\n    gttoc(augment_VI);\n  } else {\n    variableIndex_.augment(*newFactors.symbolic(ordering_));\n  }\n  gttoc(linearize_new);\n\n  gttic(recalculate);\n  // 8. Redo top of Bayes tree\n  // Convert constrained symbols to indices\n  boost::optional<FastMap<Index,int> > constrainedIndices;\n  if(constrainedKeys) {\n    constrainedIndices = FastMap<Index,int>();\n    typedef pair<const Key, int> Key_Group;\n    BOOST_FOREACH(Key_Group key_group, *constrainedKeys) {\n      constrainedIndices->insert(make_pair(ordering_[key_group.first], key_group.second));\n    }\n  }\n  boost::shared_ptr<FastSet<Index> > replacedKeys;\n  if(!markedKeys.empty() || !observedKeys.empty())\n    replacedKeys = recalculate(markedKeys, relinKeys, observedKeys, unusedIndices, constrainedIndices, result);\n\n  // Update replaced keys mask (accumulates until back-substitution takes place)\n  if(replacedKeys) {\n    BOOST_FOREACH(const Index var, *replacedKeys) {\n      deltaReplacedMask_[var] = true; } }\n  gttoc(recalculate);\n\n  // After the top of the tree has been redone and may have index gaps from\n  // unused keys, condense the indices to remove gaps by rearranging indices\n  // in all data structures.\n  if(!unusedKeys.empty()) {\n    gttic(remove_variables);\n    Impl::RemoveVariables(unusedKeys, root_, theta_, variableIndex_, delta_, deltaNewton_, RgProd_,\n        deltaReplacedMask_, ordering_, Base::nodes_, linearFactors_, fixedVariables_);\n    gttoc(remove_variables);\n  }\n  result.cliques = this->nodes().size();\n  deltaDoglegUptodate_ = false;\n  deltaUptodate_ = false;\n\n  gttic(evaluate_error_after);\n  if(params_.evaluateNonlinearError)\n    result.errorAfter.reset(nonlinearFactors_.error(calculateEstimate()));\n  gttoc(evaluate_error_after);\n\n  return result;\n}\n\n/* ************************************************************************* */\nvoid ISAM2::marginalizeLeaves(const FastList<Key>& leafKeys, boost::optional<std::vector<size_t>&> marginalFactorsIndices,\n    boost::optional<std::vector<size_t>&> deletedFactorsIndices)\n{\n  // Convert set of keys into a set of indices\n  FastSet<Index> indices;\n  BOOST_FOREACH(Key key, leafKeys) {\n    indices.insert(ordering_[key]);\n  }\n\n  // Keep track of marginal factors - map from clique to the marginal factors\n  // that should be incorporated into it, passed up from it's children.\n  multimap<sharedClique, GaussianFactor::shared_ptr> marginalFactors;\n\n  // Remove each variable and its subtrees\n  BOOST_REVERSE_FOREACH(Index j, indices) {\n    if(nodes_[j]) { // If the index was not already removed by removing another subtree\n      sharedClique clique = nodes_[j];\n\n      // See if we should remove the whole clique\n      bool marginalizeEntireClique = true;\n      BOOST_FOREACH(Index frontal, clique->conditional()->frontals()) {\n        if(indices.find(frontal) == indices.end()) {\n          marginalizeEntireClique = false;\n          break; } }\n\n      // Remove either the whole clique or part of it\n      if(marginalizeEntireClique) {\n        // Remove the whole clique and its subtree, and keep the marginal factor.\n        GaussianFactor::shared_ptr marginalFactor = clique->cachedFactor();\n        // We do not need the marginal factors associated with this clique\n        // because their information is already incorporated in the new\n        // marginal factor.  So, now associate this marginal factor with the\n        // parent of this clique.\n        marginalFactors.insert(make_pair(clique->parent(), marginalFactor));\n        // Now remove this clique and its subtree - all of its marginal\n        // information has been stored in marginalFactors.\n        const Cliques removedCliques = this->removeSubtree(clique); // Remove the subtree and throw away the cliques\n        BOOST_FOREACH(const sharedClique& removedClique, removedCliques) {\n          marginalFactors.erase(removedClique);\n          BOOST_FOREACH(Index indexInClique, removedClique->conditional()->frontals()) {\n            if(indices.find(indexInClique) == indices.end())\n              throw runtime_error(\"Requesting to marginalize variables that are not leaves, the ISAM2 object is now in an inconsistent state so should no longer be used.\"); }\n        }\n      }\n      else {\n        // Reeliminate the current clique and the marginals from its children,\n        // then keep only the marginal on the non-marginalized variables.  We\n        // get the childrens' marginals from any existing children, plus\n        // the marginals from the marginalFactors multimap, which come from any\n        // subtrees already marginalized out.\n        \n        // Add child marginals and remove marginalized subtrees\n        GaussianFactorGraph graph;\n        FastSet<size_t> factorsInSubtreeRoot;\n        Cliques subtreesToRemove;\n        BOOST_FOREACH(const sharedClique& child, clique->children()) {\n          // Remove subtree if child depends on any marginalized keys\n          BOOST_FOREACH(Index parentIndex, child->conditional()->parents()) {\n            if(indices.find(parentIndex) != indices.end()) {\n              subtreesToRemove.push_back(child);\n              graph.push_back(child->cachedFactor()); // Add child marginal\n              break;\n            }\n          }\n        }\n        Cliques childrenRemoved;\n        BOOST_FOREACH(const sharedClique& childToRemove, subtreesToRemove) {\n          const Cliques removedCliques = this->removeSubtree(childToRemove); // Remove the subtree and throw away the cliques\n          childrenRemoved.insert(childrenRemoved.end(), removedCliques.begin(), removedCliques.end());\n          BOOST_FOREACH(const sharedClique& removedClique, removedCliques) {\n            marginalFactors.erase(removedClique);\n            BOOST_FOREACH(Index indexInClique, removedClique->conditional()->frontals()) {\n              if(indices.find(indexInClique) == indices.end())\n                throw runtime_error(\"Requesting to marginalize variables that are not leaves, the ISAM2 object is now in an inconsistent state so should no longer be used.\"); }\n          }\n        }\n\n        // Gather remaining children after we removed marginalized subtrees\n        vector<sharedClique> orphans(clique->children().begin(), clique->children().end());\n\n        // Add the factors that are pulled into the current clique by the marginalized variables.\n        // These are the factors that involve *marginalized* frontal variables in this clique\n        // but do not involve frontal variables of any of its children.\n        FastSet<size_t> factorsFromMarginalizedInClique;\n        BOOST_FOREACH(Index indexInClique, clique->conditional()->frontals()) {\n          if(indices.find(indexInClique) != indices.end())\n            factorsFromMarginalizedInClique.insert(variableIndex_[indexInClique].begin(), variableIndex_[indexInClique].end()); }\n        BOOST_FOREACH(const sharedClique& removedChild, childrenRemoved) {\n          BOOST_FOREACH(Index indexInClique, removedChild->conditional()->frontals()) {\n            BOOST_FOREACH(size_t factorInvolving, variableIndex_[indexInClique]) {\n              factorsFromMarginalizedInClique.erase(factorInvolving); } } }\n        BOOST_FOREACH(size_t i, factorsFromMarginalizedInClique) {\n          graph.push_back(nonlinearFactors_[i]->linearize(theta_, ordering_)); }\n\n        // Remove the current clique\n        sharedClique parent = clique->parent();\n        this->removeClique(clique);\n\n        // Reeliminate the linear graph to get the marginal and discard the conditional\n        const FastSet<Index> cliqueFrontals(clique->conditional()->beginFrontals(), clique->conditional()->endFrontals());\n        FastSet<Index> cliqueFrontalsToEliminate;\n        std::set_intersection(cliqueFrontals.begin(), cliqueFrontals.end(), indices.begin(), indices.end(),\n          std::inserter(cliqueFrontalsToEliminate, cliqueFrontalsToEliminate.end()));\n        vector<Index> cliqueFrontalsToEliminateV(cliqueFrontalsToEliminate.begin(), cliqueFrontalsToEliminate.end());\n        pair<GaussianConditional::shared_ptr, GaussianFactorGraph> eliminationResult1 =\n          graph.eliminate(cliqueFrontalsToEliminateV,\n          params_.factorization==ISAM2Params::QR ? EliminateQR : EliminatePreferCholesky);\n\n        // Add the resulting marginal\n        BOOST_FOREACH(const GaussianFactor::shared_ptr& marginal, eliminationResult1.second) {\n          if(marginal)\n            marginalFactors.insert(make_pair(clique, marginal)); }\n\n        // Recover the conditional on the remaining subset of frontal variables\n        // of this clique being martially marginalized.\n        size_t nToEliminate = std::find(clique->conditional()->beginFrontals(), clique->conditional()->endFrontals(), j) - clique->conditional()->begin() + 1;\n        GaussianFactorGraph graph2;\n        graph2.push_back(clique->conditional()->toFactor());\n        GaussianFactorGraph::EliminationResult eliminationResult2 = \n          params_.factorization == ISAM2Params::QR ?\n          EliminateQR(graph2, nToEliminate) :\n          EliminatePreferCholesky(graph2, nToEliminate);\n        GaussianFactorGraph graph3;\n        graph3.push_back(eliminationResult2.second);\n        GaussianFactorGraph::EliminationResult eliminationResult3 = \n          params_.factorization == ISAM2Params::QR ?\n          EliminateQR(graph3, clique->conditional()->nrFrontals() - nToEliminate) :\n          EliminatePreferCholesky(graph3, clique->conditional()->nrFrontals() - nToEliminate);\n        sharedClique newClique = boost::make_shared<Clique>(make_pair(eliminationResult3.first, clique->cachedFactor()));\n\n        // Add the marginalized clique to the BayesTree\n        this->addClique(newClique, parent);\n\n        // Add the orphans\n        BOOST_FOREACH(const sharedClique& orphan, orphans) {\n          this->addClique(orphan, newClique); }\n      }\n    }\n  }\n\n  // At this point we have updated the BayesTree, now update the remaining iSAM2 data structures\n\n  // Gather factors to add - the new marginal factors\n  GaussianFactorGraph factorsToAdd;\n  typedef pair<sharedClique, GaussianFactor::shared_ptr> Clique_Factor;\n  BOOST_FOREACH(const Clique_Factor& clique_factor, marginalFactors) {\n    if(clique_factor.second) {\n      factorsToAdd.push_back(clique_factor.second);\n      if(marginalFactorsIndices) marginalFactorsIndices->push_back(nonlinearFactors_.size());\n      nonlinearFactors_.push_back(boost::make_shared<LinearContainerFactor>(\n        clique_factor.second, ordering_));\n      if(params_.cacheLinearizedFactors) {\n        linearFactors_.push_back(clique_factor.second);\n      }\n      BOOST_FOREACH(Index factorIndex, *clique_factor.second) {\n        fixedVariables_.insert(ordering_.key(factorIndex)); \n      }\n    }\n  }\n  variableIndex_.augment(factorsToAdd); // Augment the variable index\n\n  // Remove the factors to remove that have been summarized in the newly-added marginal factors\n  FastSet<size_t> factorIndicesToRemove;\n  BOOST_FOREACH(Index j, indices) {\n    factorIndicesToRemove.insert(variableIndex_[j].begin(), variableIndex_[j].end()); }\n  vector<size_t> removedFactorsIndices;\n  SymbolicFactorGraph removedFactors;\n  BOOST_FOREACH(size_t i, factorIndicesToRemove) {\n    if(deletedFactorsIndices) deletedFactorsIndices->push_back(i);\n    removedFactorsIndices.push_back(i);\n    removedFactors.push_back(nonlinearFactors_[i]->symbolic(ordering_));\n    nonlinearFactors_.remove(i);\n    if(params_.cacheLinearizedFactors)\n      linearFactors_.remove(i);\n  }\n  variableIndex_.remove(removedFactorsIndices, removedFactors);\n\n  // Remove the marginalized variables\n  Impl::RemoveVariables(FastSet<Key>(leafKeys.begin(), leafKeys.end()), root_, theta_, variableIndex_, delta_, deltaNewton_, RgProd_,\n    deltaReplacedMask_, ordering_, nodes_, linearFactors_, fixedVariables_);\n}\n\n/* ************************************************************************* */\nvoid ISAM2::updateDelta(bool forceFullSolve) const {\n\n  if(params_.optimizationParams.type() == typeid(ISAM2GaussNewtonParams)) {\n    // If using Gauss-Newton, update with wildfireThreshold\n    const ISAM2GaussNewtonParams& gaussNewtonParams =\n        boost::get<ISAM2GaussNewtonParams>(params_.optimizationParams);\n    const double effectiveWildfireThreshold = forceFullSolve ? 0.0 : gaussNewtonParams.wildfireThreshold;\n    gttic(Wildfire_update);\n    lastBacksubVariableCount = Impl::UpdateDelta(this->root(), deltaReplacedMask_, delta_, effectiveWildfireThreshold);\n    gttoc(Wildfire_update);\n\n  } else if(params_.optimizationParams.type() == typeid(ISAM2DoglegParams)) {\n    // If using Dogleg, do a Dogleg step\n    const ISAM2DoglegParams& doglegParams =\n        boost::get<ISAM2DoglegParams>(params_.optimizationParams);\n\n    // Do one Dogleg iteration\n    gttic(Dogleg_Iterate);\n    DoglegOptimizerImpl::IterationResult doglegResult(DoglegOptimizerImpl::Iterate(\n        *doglegDelta_, doglegParams.adaptationMode, *this, nonlinearFactors_, theta_, ordering_, nonlinearFactors_.error(theta_), doglegParams.verbose));\n    gttoc(Dogleg_Iterate);\n\n    gttic(Copy_dx_d);\n    // Update Delta and linear step\n    doglegDelta_ = doglegResult.Delta;\n    delta_ = doglegResult.dx_d; // Copy the VectorValues containing with the linear solution\n    gttoc(Copy_dx_d);\n  }\n\n  deltaUptodate_ = true;\n}\n\n/* ************************************************************************* */\nValues ISAM2::calculateEstimate() const {\n  // We use ExpmapMasked here instead of regular expmap because the former\n  // handles Permuted<VectorValues>\n  gttic(Copy_Values);\n  Values ret(theta_);\n  gttoc(Copy_Values);\n  gttic(getDelta);\n  const VectorValues& delta(getDelta());\n  gttoc(getDelta);\n  gttic(Expmap);\n  vector<bool> mask(ordering_.size(), true);\n  Impl::ExpmapMasked(ret, delta, ordering_, mask);\n  gttoc(Expmap);\n  return ret;\n}\n\n/* ************************************************************************* */\nconst Value& ISAM2::calculateEstimate(Key key) const {\n  const Index index = getOrdering()[key];\n  const Vector& delta = getDelta()[index];\n  return *theta_.at(key).retract_(delta);\n}\n\n/* ************************************************************************* */\nValues ISAM2::calculateBestEstimate() const {\n  VectorValues delta(theta_.dims(ordering_));\n  internal::optimizeInPlace<Base>(this->root(), delta);\n  return theta_.retract(delta, ordering_);\n}\n\n/* ************************************************************************* */\nMatrix ISAM2::marginalCovariance(Index key) const {\n  return marginalFactor(ordering_[key],\n    params_.factorization == ISAM2Params::QR ? EliminateQR : EliminatePreferCholesky)\n    ->information().inverse();\n}\n\n/* ************************************************************************* */\nconst VectorValues& ISAM2::getDelta() const {\n  if(!deltaUptodate_)\n    updateDelta();\n  return delta_;\n}\n\n/* ************************************************************************* */\nVectorValues optimize(const ISAM2& isam) {\n  gttic(allocateVectorValues);\n  VectorValues delta = *allocateVectorValues(isam);\n  gttoc(allocateVectorValues);\n  optimizeInPlace(isam, delta);\n  return delta;\n}\n\n/* ************************************************************************* */\nvoid optimizeInPlace(const ISAM2& isam, VectorValues& delta) {\n  // We may need to update the solution calculations\n  if(!isam.deltaDoglegUptodate_) {\n    gttic(UpdateDoglegDeltas);\n    double wildfireThreshold = 0.0;\n    if(isam.params().optimizationParams.type() == typeid(ISAM2GaussNewtonParams))\n      wildfireThreshold = boost::get<ISAM2GaussNewtonParams>(isam.params().optimizationParams).wildfireThreshold;\n    else if(isam.params().optimizationParams.type() == typeid(ISAM2DoglegParams))\n      wildfireThreshold = boost::get<ISAM2DoglegParams>(isam.params().optimizationParams).wildfireThreshold;\n    else\n      assert(false);\n    ISAM2::Impl::UpdateDoglegDeltas(isam, wildfireThreshold, isam.deltaReplacedMask_, isam.deltaNewton_, isam.RgProd_);\n    isam.deltaDoglegUptodate_ = true;\n    gttoc(UpdateDoglegDeltas);\n  }\n\n  gttic(copy_delta);\n  delta = isam.deltaNewton_;\n  gttoc(copy_delta);\n}\n\n/* ************************************************************************* */\nVectorValues optimizeGradientSearch(const ISAM2& isam) {\n  gttic(Allocate_VectorValues);\n  VectorValues grad = *allocateVectorValues(isam);\n  gttoc(Allocate_VectorValues);\n\n  optimizeGradientSearchInPlace(isam, grad);\n\n  return grad;\n}\n\n/* ************************************************************************* */\nvoid optimizeGradientSearchInPlace(const ISAM2& isam, VectorValues& grad) {\n  // We may need to update the solution calcaulations\n  if(!isam.deltaDoglegUptodate_) {\n    gttic(UpdateDoglegDeltas);\n    double wildfireThreshold = 0.0;\n    if(isam.params().optimizationParams.type() == typeid(ISAM2GaussNewtonParams))\n      wildfireThreshold = boost::get<ISAM2GaussNewtonParams>(isam.params().optimizationParams).wildfireThreshold;\n    else if(isam.params().optimizationParams.type() == typeid(ISAM2DoglegParams))\n      wildfireThreshold = boost::get<ISAM2DoglegParams>(isam.params().optimizationParams).wildfireThreshold;\n    else\n      assert(false);\n    ISAM2::Impl::UpdateDoglegDeltas(isam, wildfireThreshold, isam.deltaReplacedMask_, isam.deltaNewton_, isam.RgProd_);\n    isam.deltaDoglegUptodate_ = true;\n    gttoc(UpdateDoglegDeltas);\n  }\n\n  gttic(Compute_Gradient);\n  // Compute gradient (call gradientAtZero function, which is defined for various linear systems)\n  gradientAtZero(isam, grad);\n  double gradientSqNorm = grad.dot(grad);\n  gttoc(Compute_Gradient);\n\n  gttic(Compute_minimizing_step_size);\n  // Compute minimizing step size\n  double RgNormSq = isam.RgProd_.asVector().squaredNorm();\n  double step = -gradientSqNorm / RgNormSq;\n  gttoc(Compute_minimizing_step_size);\n\n  gttic(Compute_point);\n  // Compute steepest descent point\n  scal(step, grad);\n  gttoc(Compute_point);\n}\n\n/* ************************************************************************* */\nVectorValues gradient(const ISAM2& bayesTree, const VectorValues& x0) {\n  return gradient(FactorGraph<JacobianFactor>(bayesTree), x0);\n}\n\n/* ************************************************************************* */\nstatic void gradientAtZeroTreeAdder(const boost::shared_ptr<ISAM2Clique>& root, VectorValues& g) {\n  // Loop through variables in each clique, adding contributions\n  int variablePosition = 0;\n  for(GaussianConditional::const_iterator jit = root->conditional()->begin(); jit != root->conditional()->end(); ++jit) {\n    const int dim = root->conditional()->dim(jit);\n    g[*jit] += root->gradientContribution().segment(variablePosition, dim);\n    variablePosition += dim;\n  }\n\n  // Recursively add contributions from children\n  typedef boost::shared_ptr<ISAM2Clique> sharedClique;\n  BOOST_FOREACH(const sharedClique& child, root->children()) {\n    gradientAtZeroTreeAdder(child, g);\n  }\n}\n\n/* ************************************************************************* */\nvoid gradientAtZero(const ISAM2& bayesTree, VectorValues& g) {\n  // Zero-out gradient\n  g.setZero();\n\n  // Sum up contributions for each clique\n  if(bayesTree.root())\n    gradientAtZeroTreeAdder(bayesTree.root(), g);\n}\n\n}\n/// namespace gtsam\n", "meta": {"hexsha": "2275ec2be1e0a404b414edb64e101dd999800b0f", "size": 49392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/nonlinear/ISAM2.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "gtsam/nonlinear/ISAM2.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/nonlinear/ISAM2.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3602058319, "max_line_length": 176, "alphanum_fraction": 0.6906584062, "num_tokens": 11853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.036769468846346534, "lm_q1q2_score": 0.015395262964615502}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <pthread.h>\n#include <unistd.h>\n#include <boost/unordered_map.hpp>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string/trim.hpp>\n\n#include \"ini.c\"\n#include \"INIReader.cpp\"\n#include \"AdUtil.h\"\n//#include \"Util.h\"\n\nusing namespace boost;\n\nstatic bool isLong(const std::string& str, long* l) {\n  try {\n    string str1(str);\n    boost::trim(str1);\n    *l = boost::lexical_cast<long>(str1);\n  }\n  catch (...) {\n    // DEBUG(LOGNAME,\"not long string: str=%s\", str.c_str());\n    return false;\n  }\n  return true;\n}\nstatic bool isFloat(const std::string& str, float* f) {\n  try {\n    string str1(str);\n    boost::trim(str1);\n    *f = boost::lexical_cast<float>(str1);\n  }\n  catch (...) {\n    // DEBUG(LOGNAME,\"not float string: str=%s\", str.c_str());\n    return false;\n  }\n  return true;\n}\n\ntypedef struct {\n  long node_id;\n  long left, right;\n  float impurity;\n  long feature;\n  float thresh;\n  long feature_type;\n  std::vector<std::string> feature_list;\n  float value;  // only leaf node has value\n} node_t;\n\ntypedef struct {\n  boost::unordered_map<int, float> mTreeWeights;\n  boost::unordered_map<int, std::vector<node_t> > mTrees;\n  boost::unordered_map<int, boost::unordered_map<int, int> > mLeafCodes;\n  float mConstWeight;\n  boost::unordered_map<uint64_t, std::vector<long> > mFeatureMappingKey;\n  boost::unordered_map<uint64_t, boost::unordered_map<long, long> >\n      mFeatureMappingValue;\n} gbdt_coeff_t;\n\nbool parseNodeFromString(const std::string& node_str, int node_id,\n                         node_t& node) {\n  // left_id, right_id, impurity(infomation gain), feature_id/feature_name,\n  // thresh, feature_type(0 value/1 category), value_list(category list),\n  // value(only leaf valid)\n  // 1,2,0.010769,2,575.500000,0,,0.000000\n  if (node_str == \"\") return false;\n\n  vector<string> tmp;\n  AdUtil::Split3(tmp, node_str, ',');\n  long left, right, feature, feature_type;\n  float impurity, thresh, value;\n  if (!isLong(tmp[0], &left) || !isLong(tmp[1], &right) ||\n      !isFloat(tmp[2], &impurity) || !isLong(tmp[3], &feature) ||\n      !isFloat(tmp[4], &thresh) || !isLong(tmp[5], &feature_type) ||\n      !isFloat(tmp[7], &value)) {\n    return false;\n  }\n  node.left = left;\n  node.right = right;\n  node.impurity = impurity;\n  node.feature = feature;\n  node.thresh = thresh;\n  node.feature_type = feature_type;\n  node.value = value;\n  string value_list = tmp[6];\n  tmp.clear();\n  AdUtil::Split3(tmp, value_list, ';');\n  for (int i = 0; i < tmp.size(); i++) {\n    node.feature_list.push_back(tmp[i]);\n  }\n\n  return true;\n}\n\nbool loadModel(gbdt_coeff_t& model, const char* model_file) {\n  ifstream ifs(model_file);\n  if (!ifs) {\n    return false;\n  }\n\n  unordered_map<int, std::vector<node_t> >().swap(model.mTrees);  //释放内存\n  INIReader* gbdt_define = new INIReader(model_file);\n  if (gbdt_define == NULL) {\n    return false;\n  }\n\n  int num_trees = gbdt_define->GetInteger(\"declare\", \"num\", 0);\n  string weights = gbdt_define->Get(\"declare\", \"weights\", \"\");\n  vector<string> tmp;\n  AdUtil::Split3(tmp, weights, ',');\n  for (int i = 0; i < tmp.size(); i++) {\n    float v;\n    if (!isFloat(tmp[i], &v)) {\n      return false;\n    }\n    model.mTreeWeights.insert(make_pair(i, v));\n  }\n\n  char tree_name[256], node_name[256];\n  int max_leaf_index = 0;\n  int leaf_node_code = 0;  // 叶子节点编号，用于做特征变换\n  for (int i = 0; i < num_trees; i++) {\n    sprintf(tree_name, \"tree_%d\", i);\n    string tree_name_str(tree_name);\n\n    int node_id = 0, max_leaf_index = -1;\n    vector<node_t> tree;\n    boost::unordered_map<int, int> leaf_code;\n    while (true) {\n      sprintf(node_name, \"node_%d\", node_id);\n      string node_name_str(node_name);\n\n      string node_str = gbdt_define->Get(tree_name_str, node_name_str, \"\");\n      if (node_str == \"\" && max_leaf_index > node_id) {\n        node_t node;\n        tree.push_back(node);\n        node_id += 1;\n        continue;\n      }\n      if (node_str == \"\" && max_leaf_index <= node_id) {\n        break;\n      }\n\n      // 解析树节点\n      node_t node;\n      node.left = -1;\n      node.right = -1;\n      if (!parseNodeFromString(node_str, node_id, node)) return false;\n      if (max_leaf_index < node.left) max_leaf_index = node.left;\n      if (max_leaf_index < node.right) max_leaf_index = node.right;\n      tree.push_back(node);\n      if (node.left == -1 && node.right == -1) {\n        leaf_code.insert(make_pair(node.node_id, leaf_node_code));\n        leaf_node_code += 1;\n      }\n\n      node_id += 1;\n    }\n    model.mTrees.insert(make_pair(i, tree));\n    model.mLeafCodes.insert(make_pair(i, leaf_code));\n  }\n  delete gbdt_define;\n\n  return true;\n}\n\nbool transform(unordered_map<uint32_t, uint32_t>& features, gbdt_coeff_t& model,\n               unordered_map<uint32_t, uint32_t>& output) {\n  int num_trees = model.mTreeWeights.size();\n\n  for (int i = 0; i < num_trees; i++) {\n    std::vector<node_t>& tree = model.mTrees[i];\n    boost::unordered_map<int, int>& leaf_code = model.mLeafCodes[i];\n\n    int leaf_index = 0;\n    while (tree[leaf_index].left != -1 && tree[leaf_index].right != -1) {\n      int feature_index = tree[leaf_index].feature;\n\n      int feature_value = 0;\n      if (features.find(feature_index) != features.end())\n        feature_value = features[feature_index];\n\n      if (feature_value <= tree[leaf_index].thresh)\n        leaf_index = tree[leaf_index].left;\n      else\n        leaf_index = tree[leaf_index].right;\n    }\n    long feature_idx =\n        leaf_code[leaf_index];  // 经过gbdt叶子节点编号后的叶节点id\n\n    output.insert(make_pair(feature_idx, 1));\n  }\n\n  return true;\n}\n\nint main(int argc, char** argv) {\n  if (argc != 2) {\n    cerr << \"Usage: \" << argv[0] << \" <model-file>\" << endl;\n    return -1;\n  }\n  const char* model_file = argv[1];\n  gbdt_coeff_t model;\n\n  if (!loadModel(model, model_file)) {\n    cerr << \"loadModel error\" << endl;\n    return -1;\n  }\n\n  string line;\n  while (getline(cin, line)) {\n    //-1 1 |f 609:1 3097:1 3769:1 1728:1 4573:1 1293:1 2441:1 4213:1 4201:1\n    unordered_map<uint32_t, uint32_t> input;\n    unordered_map<uint32_t, uint32_t> output;\n\n    vector<string> tmp;\n    AdUtil::Split3(tmp, line, ' ');\n    for (int k = 3; k < tmp.size(); k++) {\n      input.insert(make_pair(k - 3, atoi(tmp[k].c_str())));\n    }\n\n    if (!transform(input, model, output)) {\n      cerr << \"transform error\" << endl;\n      continue;\n    }\n\n    cout << tmp[0] << \"\\t\" << tmp[1] << \"\\t\" << tmp[2] << \"\\t\";\n    for (unordered_map<uint32_t, uint32_t>::iterator iter = output.begin();\n         iter != output.end(); iter++) {\n      cout << iter->first << \":1\"\n           << \"\\t\";\n    }\n    cout << endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "678dff6d63455680ec46fc27e571e2a4149404b2", "size": 6694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Tools/gbdt_encode.cpp", "max_stars_repo_name": "niuchenglei/rankextor", "max_stars_repo_head_hexsha": "342e39dda8347b0986f6d2be9968ee72a90b16c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-01-04T02:07:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T13:46:24.000Z", "max_issues_repo_path": "src/Tools/gbdt_encode.cpp", "max_issues_repo_name": "niuchenglei/rankextor", "max_issues_repo_head_hexsha": "342e39dda8347b0986f6d2be9968ee72a90b16c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tools/gbdt_encode.cpp", "max_forks_repo_name": "niuchenglei/rankextor", "max_forks_repo_head_hexsha": "342e39dda8347b0986f6d2be9968ee72a90b16c2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-04T03:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-04T03:10:08.000Z", "avg_line_length": 27.5473251029, "max_line_length": 80, "alphanum_fraction": 0.6226471467, "num_tokens": 1960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.03514484842196812, "lm_q1q2_score": 0.015387240511944318}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef __BOYER_MYRVOLD_PLANAR_TEST_HPP__\n#define __BOYER_MYRVOLD_PLANAR_TEST_HPP__\n\n#include <boost/graph/planar_detail/boyer_myrvold_impl.hpp>\n#include <boost/parameter.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/mpl/bool.hpp>\n\n\nnamespace boost\n{\n\n  struct no_kuratowski_subgraph_isolation {};\n  struct no_planar_embedding {};\n\n  namespace boyer_myrvold_params\n  {\n    \n    BOOST_PARAMETER_KEYWORD(tag, graph)\n    BOOST_PARAMETER_KEYWORD(tag, embedding)\n    BOOST_PARAMETER_KEYWORD(tag, kuratowski_subgraph)\n    BOOST_PARAMETER_KEYWORD(tag, vertex_index_map)\n    BOOST_PARAMETER_KEYWORD(tag, edge_index_map)\n    \n    typedef parameter::parameters< parameter::required<tag::graph>,\n                                   tag::embedding,\n                                   tag::kuratowski_subgraph,\n                                   tag::vertex_index_map,\n                                   tag::edge_index_map\n                                   > boyer_myrvold_params_t;\n    \n    namespace core\n    {\n        \n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::true_, \n                                    mpl::true_\n                                    )\n      {\n        //Dispatch for no planar embedding, no kuratowski subgraph isolation\n\n        typedef typename remove_const\n                < \n                    typename remove_reference\n                    < typename parameter::binding\n                        < ArgumentPack, tag::graph>::type \n                    >::type \n                >::type graph_t;\n\n        typedef typename parameter::binding\n          < ArgumentPack, \n            tag::vertex_index_map,\n            typename property_map\n              < typename remove_reference<graph_t>::type, \n                vertex_index_t>::const_type\n          >::type vertex_index_map_t;\n\n        boyer_myrvold_impl\n          <graph_t, \n           vertex_index_map_t,\n           graph::detail::no_old_handles,\n           graph::detail::no_embedding\n          >\n          planarity_tester(args[graph], \n                           args[vertex_index_map | \n                                get(vertex_index, args[graph])\n                                ]\n                           );\n\n        return planarity_tester.is_planar() ? true : false;\n      }\n\n\n    \n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::true_, \n                                    mpl::false_\n                                    )\n      {\n        //Dispatch for no planar embedding, kuratowski subgraph isolation\n        typedef typename remove_const\n                < \n                    typename remove_reference\n                    < typename parameter::binding\n                        < ArgumentPack, tag::graph>::type \n                    >::type \n                >::type graph_t;\n        \n        typedef typename parameter::binding\n          < ArgumentPack, \n            tag::vertex_index_map,\n            typename property_map<graph_t, vertex_index_t>::type\n          >::type vertex_index_map_t;\n      \n        boyer_myrvold_impl \n          <graph_t, \n           vertex_index_map_t,\n           graph::detail::store_old_handles,\n           graph::detail::no_embedding\n          >\n          planarity_tester(args[graph], \n                           args[vertex_index_map | \n                                get(vertex_index, args[graph])\n                                ]\n                           );\n\n        if (planarity_tester.is_planar())\n          return true;\n        else\n          {\n            planarity_tester.extract_kuratowski_subgraph\n              (args[kuratowski_subgraph],\n               args[edge_index_map|get(edge_index, args[graph])]\n               );          \n            return false;\n          }\n      }\n\n\n\n    \n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::false_, \n                                    mpl::true_\n                                    )\n      {\n        //Dispatch for planar embedding, no kuratowski subgraph isolation\n        typedef typename remove_const\n                < \n                    typename remove_reference\n                    < typename parameter::binding\n                        < ArgumentPack, tag::graph>::type \n                    >::type \n                >::type graph_t;        \n        \n        typedef typename parameter::binding\n          < ArgumentPack, \n          tag::vertex_index_map,\n          typename property_map<graph_t, vertex_index_t>::type\n          >::type  vertex_index_map_t;\n\n        boyer_myrvold_impl\n          <graph_t, \n           vertex_index_map_t,\n           graph::detail::no_old_handles,\n#ifdef BOOST_GRAPH_PREFER_STD_LIB\n           graph::detail::std_list\n#else\n           graph::detail::recursive_lazy_list\n#endif\n          >\n          planarity_tester(args[graph], \n                           args[vertex_index_map | \n                                get(vertex_index, args[graph])\n                                ]\n                           );\n\n        if (planarity_tester.is_planar())\n          {\n            planarity_tester.make_edge_permutation(args[embedding]);\n            return true;\n          }\n        else\n          return false;\n      }\n    \n\n\n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::false_, \n                                    mpl::false_\n                                    )\n      {\n        //Dispatch for planar embedding, kuratowski subgraph isolation\n        typedef typename remove_const\n                < \n                    typename remove_reference\n                    < typename parameter::binding\n                        < ArgumentPack, tag::graph>::type \n                    >::type \n                >::type graph_t;        \n        \n        typedef typename parameter::binding\n          < ArgumentPack, \n          tag::vertex_index_map, \n          typename property_map<graph_t, vertex_index_t>::type\n          >::type vertex_index_map_t;\n        \n        boyer_myrvold_impl\n          <graph_t, \n          vertex_index_map_t,\n          graph::detail::store_old_handles,\n#ifdef BOOST_BGL_PREFER_STD_LIB\n           graph::detail::std_list\n#else\n           graph::detail::recursive_lazy_list\n#endif\n          >\n          planarity_tester(args[graph], \n                           args[vertex_index_map | \n                                get(vertex_index, args[graph])\n                                ]\n                           );\n\n        if (planarity_tester.is_planar())\n          {\n            planarity_tester.make_edge_permutation(args[embedding]);\n            return true;\n          }\n        else\n          {\n            planarity_tester.extract_kuratowski_subgraph\n              (args[kuratowski_subgraph], \n               args[edge_index_map | get(edge_index, args[graph])]\n               );          \n            return false;\n          } \n      }\n\n\n\n\n      template <typename ArgumentPack>\n      bool boyer_myrvold_planarity_test(ArgumentPack const& args)\n      {\n        \n        typedef typename parameter::binding \n          < ArgumentPack, \n            tag::kuratowski_subgraph,\n            const no_kuratowski_subgraph_isolation&\n          >::type \n          kuratowski_arg_t;\n       \n        typedef typename parameter::binding \n          < ArgumentPack, \n            tag::embedding,\n            const no_planar_embedding&\n          >::type \n          embedding_arg_t;\n      \n         return dispatched_boyer_myrvold\n           (args, \n            boost::is_same\n              <embedding_arg_t, const no_planar_embedding&>(),\n            boost::is_same\n              <kuratowski_arg_t, const no_kuratowski_subgraph_isolation&>() \n            );\n      }\n\n\n\n    } //namespace core\n    \n  } //namespace boyer_myrvold_params\n  \n    \n  template <typename A0>\n  bool boyer_myrvold_planarity_test(A0 const& arg0)\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0));\n  }\n  \n  template <typename A0, typename A1>\n  //  bool boyer_myrvold_planarity_test(A0 const& arg0, A1 const& arg1)\n  bool boyer_myrvold_planarity_test(A0 const& arg0, A1 const& arg1)\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0,arg1));\n  }\n  \n  template <typename A0, typename A1, typename A2>\n  bool boyer_myrvold_planarity_test(A0 const& arg0, \n                                    A1 const& arg1, \n                                    A2 const& arg2\n                                    )\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0,arg1,arg2));\n  }\n    \n  template <typename A0, typename A1, typename A2, typename A3>\n  bool boyer_myrvold_planarity_test(A0 const& arg0,\n                                    A1 const& arg1, \n                                    A2 const& arg2, \n                                    A3 const& arg3\n                                    )\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0,arg1,arg2,arg3));\n  }\n\n  template <typename A0, typename A1, typename A2, typename A3, typename A4>\n  bool boyer_myrvold_planarity_test(A0 const& arg0, \n                                    A1 const& arg1, \n                                    A2 const& arg2, \n                                    A3 const& arg3, \n                                    A4 const& arg4\n                                    )\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()\n       (arg0,arg1,arg2,arg3,arg4)\n       );\n  }\n    \n\n}\n\n#endif //__BOYER_MYRVOLD_PLANAR_TEST_HPP__\n", "meta": {"hexsha": "dc0158687f00511f50dc2090fb2401947dd44eb7", "size": 10396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/boyer_myrvold_planar_test.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "boost/boost/graph/boyer_myrvold_planar_test.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "boost/boost/graph/boyer_myrvold_planar_test.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 32.1857585139, "max_line_length": 76, "alphanum_fraction": 0.5141400539, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.03358950939885924, "lm_q1q2_score": 0.015354998046440792}}
{"text": "//=======================================================================\n// Copyright 2015 Tsinghua University.\n// Authors: Fuan Pu (Pu.Fuan@gmail.com)\n// \n// Dung's abstract argumentation framework\n//=======================================================================\n\n#ifndef ARGUMATRIX_PARSER_HPP\n#define ARGUMATRIX_PARSER_HPP\n\n#include <iostream>\n#include <string>\n#include <utility>   \n#include <algorithm>   \n// #include <regex>\n#include <boost/regex.hpp>\n\n#include \"config/config.hpp\"\n#include \"dung_theory/ArgumentProperty.hpp\"\n#include \"dung_theory/AttackProperty.hpp\"\n#include \"dung_theory/DungAF.hpp\"\n\nnamespace argumatrix{\n\nusing namespace std;\n\nclass parser\n{\npublic:\n\t/**\n\t * @brief Read Aspartix format from a file to DungAF. We have implemented\n\t * three approaches  to read aspartix format. stl::regex, boost::regex and\n\t * the approach from ArgSemSAT.1.0rc3. By testing, we choose boost::regex\n\t * since it is more stable than stl::regex, and slightly faster than ArgSemSAT.\n\t * @param std::string filePath -- the file path of the Aspartix format file.\n\t * @param DungAF& daf -- the output abstract argumentation framework\n\t * @return bool. If the translation is successful return true, else return false.\n\t */\n\tstatic bool Aspartix2DungAF(const std::string& filePath, DungAF& daf);\n\t\n\t/**\n\t * Read Trivial Graph Format from a file to DungAF\n\t * @param std::string filePath -- the file path of the Aspartix format file.\n\t * @param DungAF& daf -- the output abstract argumentation framework\n\t * @return bool. If the translation is successful return true, else return false.\n\t */\n\tstatic bool TrivialGraph2DungAF(const std::string& filePath, DungAF& daf);\n};\n\n\n//bool parser::Aspartix2DungAF(const std::string& fileName, DungAF& daf)\n//{\n//\tbool _is_successful = true;\n//\n//\t// The argument and attack regex expressions of Aspartix format\n//\t// arg(a1).\n//\t// att(a1, a2).\n//\n//\t// Before parsing, we need to clear the daf.\n//\tdaf.clear();\n//\n//\tstd::ifstream _infile;\n//\t_infile.open(fileName, ios_base::in);\n//\n//\t//check the file\n//\tif(!_infile)\n//\t{\n//\t\tcerr << \"Can not open the file: \" << fileName << endl;\n//\t\texit(1);\n//\t}\n//\n//\tsize_type start;  \n//\tsize_type _line_num = 0;\n//\tstd::string _line_str;\n//\n//\twhile ( getline(_infile, _line_str) )\n//\t{\t\n//\t\t// add attacks\n//\t\tif ( (start =_line_str.find(\"att(\") != string::npos) ) \n//\t\t{\n//\t\t\tstart += 3;\n//\n//\t\t\tsize_type comma = _line_str.find(\",\", start);\n//\t\t\tstring arg_src = trim(_line_str.substr(start, comma - start));\n//\t\t\t\n//\t\t\t++comma;\n//\t\t\tsize_type end_ = _line_str.find(\")\", comma);\n//\t\t\tstring arg_tag = trim(_line_str.substr(comma, end_ - comma));\n//\n//\t\t\tdaf.addAttack(arg_src, arg_tag);\n//\t\t\t//cout << arg_src << \"->\" << arg_tag << endl;\n//\t\t} \n//\t\telse if ((start =_line_str.find(\"arg(\") != string::npos))\n//\t\t{\n//\t\t\tstart += 3;\n//\t\t\tsize_type end_ = _line_str.find(\")\", start);\n//\t\t\tstring arg1 = trim(_line_str.substr(start, end_ - start));\n//\n//\t\t\tdaf.addArgument(arg1);\n//\t\t\t//cout << arg1 << endl;\n//\t\t}\n//\t}\n//\n//\t_infile.close();\n//\n//\treturn _is_successful;\n//} // Aspartix2DungAF(const std::string& fileName, DungAF& daf)\n\n\n\n//// The std::regex may result regex_error on linux systems. Thus, we using \n//// boost::regex to substitute.\nbool parser::Aspartix2DungAF(const std::string& fileName, DungAF& daf)\n{\n\tbool _is_successful = true;\n\n\t// The argument and attack regex expressions of Aspartix format\n\t// arg(a1).\n\t// att(a1, a2).\n\tconst boost::regex rgx_arg(\"arg\\\\(\\\\s*([a-zA-Z0-9_]+)\\\\s*\\\\)\");\n\tconst boost::regex rgx_att(\"att\\\\(\\\\s*([a-zA-Z0-9_]+)\\\\s*,\\\\s*([a-zA-Z0-9_]+)\\\\s*\\\\)\");\n\n\t// Before parsing, we need to clear the daf.\n\tdaf.clear();\n\n\tstd::ifstream _infile;\n\t_infile.open(fileName, ios_base::in);\n\n\t//check the file\n\tif(!_infile)\n\t{\n\t\tcerr << \"Can not open the file: \" << fileName << endl;\n\t\texit(1);\n\t}\n\n\tstd::string _line_str;\n\tsize_type   _line_num = 0;\n\tboost::cmatch _result;\n\n\twhile ( getline(_infile, _line_str) )\n\t{\n\t\t//_infile.getline()\n\t\t//_infile >> _line_str;\n\t\t++_line_num;\n\n\t\tif(_line_str.length()<=4)\n\t\t\tcontinue;\n\n\t\tif (boost::regex_search(_line_str.c_str(), _result, rgx_att))  // Find Attack\n\t\t{\n\t\t\tdaf.addAttack(_result[1], _result[2]);\n\t\t\t//cout << \"Adding Attack: (\" << _result[1] << \",\" << _result[2] << \")\" << endl;\n\t\t}\n\t\telse if (boost::regex_search(_line_str.c_str(), _result, rgx_arg)) // Find Argument\n\t\t{\n\t\t\tdaf.addArgument( _result[1] );\n\t\t\t//cout << \"Adding Argument: \" << _result[1] << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"Ignorance: \" << fileName << endl\n\t\t\t\t<< \"     Line number(\" << _line_num << \"): \" << _line_str << endl;\n\t\t\t_is_successful = false;\n\t\t}\n\t}\n\n\t_infile.close();\n\n\treturn _is_successful;\n} // Aspartix2DungAF(const std::string& fileName, DungAF& daf)\n\n\n/////////////////////\n// Implemented by stl::regex\n///////////////////// \n//bool parser::Aspartix2DungAF(const std::string& fileName, DungAF& daf)\n//{\n//\tbool _is_successful = true;\n//\n//\t// The argument and attack regex expressions of Aspartix format\n//\t// arg(a1).\n//\t// att(a1, a2).\n//\tconst std::regex rgx_arg(\"arg\\\\(\\\\s*([a-zA-Z0-9]+)\\\\s*\\\\)\");\n//\tconst std::regex rgx_att(\"att\\\\(\\\\s*([a-zA-Z0-9]+)\\\\s*,\\\\s*([a-zA-Z0-9]+)\\\\s*\\\\)\");\n//\n//\t// Before parsing, we need to clear the daf.\n//\tdaf.clear();\n//\n//\tstd::ifstream _infile;\n//\t_infile.open(fileName);\n//\n//\t//check the file\n//\tif(!_infile)\n//\t{\n//\t\tcerr << \"Can not open the file: \" << fileName << endl;\n//\t\texit(1);\n//\t}\n//\n//\tstd::string _line_str;\n//\tsize_type   _line_num = 0;\n//\tstd::match_results<std::string::const_iterator> _result;\n//\n//\twhile ( getline(_infile, _line_str) )\n//\t{\n//\t\t//_infile.getline()\n//\t\t//_infile >> _line_str;\n//\t\t++_line_num;\n//\n//\t\tif(_line_str.length()<=4)\n//\t\t\tcontinue;\n//\n//\t\tif (std::regex_search(_line_str, _result, rgx_att))  // Find Attack\n//\t\t{\n//\t\t\tdaf.addAttack(_result[1], _result[2]);\n//\t\t\t//cout << \"Adding Attack: (\" << _result[1] << \",\" << _result[2] << \")\" << endl;\n//\t\t}\n//\t\telse if (std::regex_search(_line_str, _result, rgx_arg)) // Find Argument\n//\t\t{\n//\t\t\tdaf.addArgument( _result[1] );\n//\t\t\t//cout << \"Adding Argument: \" << _result[1] << endl;\n//\t\t}\n//\t\telse\n//\t\t{\n//\t\t\tstd::cout << \"Ignorance: \" << fileName << endl\n//\t\t\t\t      << \"     Line number(\" << _line_num << \"): \" << _line_str << endl;\n//\t\t\t_is_successful = false;\n//\t\t}\n//\t}\n//\n//\t_infile.close();\n//\n//\treturn _is_successful;\n//} // Aspartix2DungAF(const std::string& fileName, DungAF& daf)\n\n\nbool parser::TrivialGraph2DungAF(const std::string& fileName, DungAF& daf)\n{\n\tbool _is_successful=true;\n\tstring arg1, arg2;\n\n\t// Before parsing, we need to clear the daf.\n\tdaf.clear();\n\n\tstd::ifstream _infile;\n\t_infile.open(fileName, ios_base::in);\n\n\t//check the file\n\tif(!_infile)\n\t{\n\t\tcerr << \"Can not open the file: \" << fileName << endl;\n\t\texit(1);\n\t}\n\n\t// read arguments\n\twhile(_infile >> arg1) {\t\n\t\tif(arg1==\"#\") {\n\t\t\tbreak;\n\t\t} else {\n\t\t\tdaf.addArgument(arg1);\n\t\t\t// cout << arg1 << endl;\n\t\t}\n\t}\n\n\t// read attackes\n\twhile(_infile >> arg1 >> arg2) {  \n\t\tdaf.addAttack(arg1, arg2);\t\n\t\t// cout << arg1 << \" -> \" << arg2 << endl;\n\t}\n\n\t_infile.close();\n\n\treturn _is_successful;\n} // TrivialGraph2DungAF(const std::string& fileName, DungAF& daf)\n\n} // namespace argumatrix\n\n\n\n#endif  //ARGUMATRIX_PARSER_HPP", "meta": {"hexsha": "0eff2111bcdb9c994428e965ddafd4460ef4cf76", "size": 7202, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "parser/parser.hpp", "max_stars_repo_name": "xixicat/argmat-clpb", "max_stars_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-01-09T21:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-28T05:52:14.000Z", "max_issues_repo_path": "parser/parser.hpp", "max_issues_repo_name": "xixicat/argmat-clpb", "max_issues_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parser/parser.hpp", "max_forks_repo_name": "xixicat/argmat-clpb", "max_forks_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_forks_repo_licenses": ["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.8136200717, "max_line_length": 88, "alphanum_fraction": 0.6133018606, "num_tokens": 2237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.061875986156129166, "lm_q1q2_score": 0.015344466552932888}}
{"text": "/*\n * CubeBoundaryDistribution.cpp\n *\n *  Created on: 22.02.2018\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/utilities.h>\n\n#include <measurements/CubeBoundaryDistribution.h>\n#include <measurements/GridDistribution.h>\n#include <measurements/SensorDistribution.h>\n\n#include <cstdio>\n#include <fstream>\n#include <iostream>\n\nnamespace wavepi {\nnamespace measurements {\nusing namespace dealii;\n\ntemplate <>\nvoid CubeBoundaryDistribution<1>::update_grid(const std::vector<double> &times,\n                                              const std::vector<std::vector<double>> &points_per_dim) {\n  Assert(points_per_dim.size() == 1, ExcInternalError());\n\n  this->points_per_dim = points_per_dim;\n\n  size_t nX = points_per_dim[0].size();\n\n  std::vector<Point<1>> points_each_time;\n  points_each_time.reserve(2);\n\n  points_each_time.emplace_back(points_per_dim[0][0]);\n  points_each_time.emplace_back(points_per_dim[0][nX - 1]);\n\n  std::vector<std::vector<Point<1>>> points_per_time(times.size());\n\n  for (size_t i = 0; i < times.size(); i++)\n    points_per_time[i] = points_each_time;\n\n  update_points(times, points_per_time);\n\n  // update times_per_point and points now (cleared by update_points!)\n  points = points_each_time;\n  times_per_point.reserve(points_each_time.size());\n\n  for (size_t ix = 0; ix < points_each_time.size(); ix++)\n    times_per_point.push_back(times);\n}\n\ntemplate <>\nvoid CubeBoundaryDistribution<2>::update_grid(const std::vector<double> &times,\n                                              const std::vector<std::vector<double>> &points_per_dim) {\n  Assert(points_per_dim.size() == 2, ExcInternalError());\n\n  this->points_per_dim = points_per_dim;\n\n  size_t nX = points_per_dim[0].size();\n  size_t nY = points_per_dim[1].size();\n\n  std::vector<Point<2>> points_each_time;\n  points_each_time.reserve(2 * (nX + nY));\n\n  for (size_t ix = 0; ix < nX; ix++)\n    for (size_t iy = 0; iy < nY; iy++)\n      if (ix == 0 || ix == nX - 1 || iy == 0 || iy == nY - 1)\n        points_each_time.emplace_back(points_per_dim[0][ix], points_per_dim[1][iy]);\n\n  std::vector<std::vector<Point<2>>> points_per_time(times.size());\n\n  for (size_t i = 0; i < times.size(); i++)\n    points_per_time[i] = points_each_time;\n\n  update_points(times, points_per_time);\n\n  // update times_per_point and points now (cleared by update_points!)\n  points = points_each_time;\n  times_per_point.reserve(points_each_time.size());\n\n  for (size_t ix = 0; ix < points_each_time.size(); ix++)\n    times_per_point.push_back(times);\n}\n\ntemplate <>\nvoid CubeBoundaryDistribution<3>::update_grid(const std::vector<double> &times,\n                                              const std::vector<std::vector<double>> &points_per_dim) {\n  Assert(points_per_dim.size() == 3, ExcInternalError());\n\n  this->points_per_dim = points_per_dim;\n\n  size_t nX = points_per_dim[0].size();\n  size_t nY = points_per_dim[1].size();\n  size_t nZ = points_per_dim[2].size();\n\n  std::vector<Point<3>> points_each_time;\n  points_each_time.reserve(2 * (nX * nY + nX * nZ + nY * nZ));\n\n  for (size_t ix = 0; ix < nX; ix++)\n    for (size_t iy = 0; iy < nY; iy++)\n      for (size_t iz = 0; iz < nZ; iz++)\n        if (ix == 0 || ix == nX - 1 || iy == 0 || iy == nY - 1 || iz == 0 || iz == nZ - 1)\n          points_each_time.emplace_back(points_per_dim[0][ix], points_per_dim[1][iy], points_per_dim[2][iz]);\n\n  std::vector<std::vector<Point<3>>> points_per_time(times.size());\n\n  for (size_t i = 0; i < times.size(); i++)\n    points_per_time[i] = points_each_time;\n\n  update_points(times, points_per_time);\n\n  // update times_per_point and points now (cleared by update_points!)\n  points = points_each_time;\n  times_per_point.reserve(points_each_time.size());\n\n  for (size_t ix = 0; ix < points_each_time.size(); ix++)\n    times_per_point.push_back(times);\n}\n\ntemplate <int dim>\nCubeBoundaryDistribution<dim>::CubeBoundaryDistribution(const std::vector<double> &times,\n                                                        const std::vector<std::vector<double>> &points_per_dim) {\n  update_grid(times, points_per_dim);\n}\n\ntemplate <int dim>\nvoid CubeBoundaryDistribution<dim>::declare_parameters(ParameterHandler &prm) {\n  prm.enter_subsection(\"CubeBoundaryDistribution\");\n  {\n    prm.declare_entry(\"points x\", \"-0.9:10:0.9\", Patterns::Anything(),\n                      \"points for the grid in x-direction. Format: '[lb]:[n_points]:[ub]'. Lower bound and upper bound \"\n                      \"are inclusive, so they define the margin to the boundary of the cube.\");\n    prm.declare_entry(\"points y\", \"-0.9:10:0.9\", Patterns::Anything(),\n                      \"points for the grid in y-direction. Format: '[lb]:[n_points]:[ub]'. Lower bound and upper bound \"\n                      \"are inclusive, so they define the margin to the boundary of the cube.\");\n    prm.declare_entry(\"points z\", \"-0.9:10:0.9\", Patterns::Anything(),\n                      \"points for the grid in z-direction. Format: '[lb]:[n_points]:[ub]'. Lower bound and upper bound \"\n                      \"are inclusive, so they define the margin to the boundary of the cube.\");\n    prm.declare_entry(\"points t\", \"0:10:6\", Patterns::Anything(),\n                      \"points for the grid in time. Format: '[lower bound]:[n_points]:[ub]'. Upper bound is inclusive, \"\n                      \"lower bound is exclusive iff it equals 0.0.\");\n  }\n  prm.leave_subsection();\n}\n\ntemplate <int dim>\nvoid CubeBoundaryDistribution<dim>::get_parameters(ParameterHandler &prm) {\n  prm.enter_subsection(\"CubeBoundaryDistribution\");\n  {\n    AssertThrow(0 <= dim && dim <= 3, ExcInternalError());\n\n    std::vector<std::vector<double>> spatial_points;\n    spatial_points.emplace_back(parse_description(prm.get(\"points x\")));\n    if (dim > 1) spatial_points.emplace_back(parse_description(prm.get(\"points y\")));\n    if (dim > 2) spatial_points.emplace_back(parse_description(prm.get(\"points z\")));\n\n    auto temporal_points = parse_description(prm.get(\"points t\"), true);\n    update_grid(temporal_points, spatial_points);\n  }\n  prm.leave_subsection();\n}\n\ntemplate <int dim>\nstd::vector<double> CubeBoundaryDistribution<dim>::parse_description(const std::string description, bool is_time) {\n  double lb, ub;\n  size_t nb;\n\n  AssertThrow(std::sscanf(description.c_str(), \" %lf : %zu : %lf \", &lb, &nb, &ub) == 3,\n              ExcMessage(\"Could not parse points\"));\n  AssertThrow((is_time && nb > 1 && lb < ub && lb >= 0.0) || (!is_time && nb >= 1 && lb <= ub),\n              ExcMessage(\"Illegal interval spec: \" + description));\n\n  std::vector<double> points(nb);\n\n  if (lb == 0.0 && is_time)  // lb excl, ub incl\n    for (size_t i = 0; i < nb; i++)\n      points[i] = lb + (i + 1) * (ub - lb) / nb;\n  else\n    // lb excl, ub excl\n    for (size_t i = 0; i < nb; i++)\n      points[i] = lb + (i + 1) * (ub - lb) / (nb + 1);\n\n  return points;\n}\n\ntemplate <int dim>\nsize_t CubeBoundaryDistribution<dim>::index_times_per_point(size_t point_index, size_t time_index) {\n  return time_index * this->points_per_time[0].size() + point_index;\n}\n\ntemplate <int dim>\nvoid CubeBoundaryDistribution<dim>::write_pvd(const std::vector<double> &values, std::string path, std::string filename,\n                                              std::string name) {\n  GridDistribution<dim> grid(this->times, points_per_dim);\n\n  auto grid_values = spread_to_grid(values);\n  grid.write_pvd(grid_values, path, filename, name);\n}\n\ntemplate <>\nstd::vector<double> CubeBoundaryDistribution<1>::spread_to_grid(const std::vector<double> &values) {\n  size_t nX = points_per_dim[0].size();\n\n  std::vector<double> grid_values;\n  grid_values.reserve(nX);\n  size_t idx = 0;\n\n  for (size_t it = 0; it < times.size(); it++)\n    for (size_t ix = 0; ix < nX; ix++)\n      if (ix == 0 || ix == nX - 1)\n        grid_values.push_back(values[idx++]);\n      else\n        grid_values.push_back(0.0);\n\n  return grid_values;\n}\n\ntemplate <>\nstd::vector<double> CubeBoundaryDistribution<2>::spread_to_grid(const std::vector<double> &values) {\n  size_t nX = points_per_dim[0].size();\n  size_t nY = points_per_dim[1].size();\n\n  std::vector<double> grid_values;\n  grid_values.reserve(nX * nY);\n  size_t idx = 0;\n\n  for (size_t it = 0; it < times.size(); it++)\n    for (size_t ix = 0; ix < nX; ix++)\n      for (size_t iy = 0; iy < nY; iy++)\n        if (ix == 0 || ix == nX - 1 || iy == 0 || iy == nY - 1)\n          grid_values.push_back(values[idx++]);\n        else\n          grid_values.push_back(0.0);\n\n  return grid_values;\n}\n\ntemplate <>\nstd::vector<double> CubeBoundaryDistribution<3>::spread_to_grid(const std::vector<double> &values) {\n  size_t nX = points_per_dim[0].size();\n  size_t nY = points_per_dim[1].size();\n  size_t nZ = points_per_dim[2].size();\n\n  std::vector<double> grid_values;\n  grid_values.reserve(nX * nY * nZ);\n  size_t idx = 0;\n\n  for (size_t it = 0; it < times.size(); it++)\n    for (size_t ix = 0; ix < nX; ix++)\n      for (size_t iy = 0; iy < nY; iy++)\n        for (size_t iz = 0; iz < nZ; iz++)\n          if (ix == 0 || ix == nX - 1 || iy == 0 || iy == nY - 1 || iz == 0 || iz == nZ - 1)\n            grid_values.push_back(values[idx++]);\n          else\n            grid_values.push_back(0.0);\n\n  return grid_values;\n}\n\ntemplate class CubeBoundaryDistribution<1>;\ntemplate class CubeBoundaryDistribution<2>;\ntemplate class CubeBoundaryDistribution<3>;\n\n} /* namespace measurements */\n} /* namespace wavepi */\n", "meta": {"hexsha": "2540b12ccee824d9dfbf667755ec1fbe2f5147c8", "size": 9407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/measurements/CubeBoundaryDistribution.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/measurements/CubeBoundaryDistribution.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/measurements/CubeBoundaryDistribution.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": 35.2322097378, "max_line_length": 120, "alphanum_fraction": 0.64122462, "num_tokens": 2538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625615, "lm_q2_score": 0.04023793859535618, "lm_q1q2_score": 0.01533948949836328}}
{"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) 2018 Blender Foundation.\n * All rights reserved.\n */\n\n#ifndef __EIGEN3_MATRIX_C_API_CC__\n#define __EIGEN3_MATRIX_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_MATRIX_C_API_CC__ /* quiet warning */\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"matrix.h\"\n\nusing Eigen::Map;\nusing Eigen::Matrix4f;\n\nbool EIG_invert_m4_m4(float inverse[4][4], const float matrix[4][4])\n{\n  Map<Matrix4f> M = Map<Matrix4f>((float *)matrix);\n  Matrix4f R;\n  bool invertible = true;\n  M.computeInverseWithCheck(R, invertible, 0.0f);\n  if (!invertible) {\n    R = R.Zero();\n  }\n  memcpy(inverse, R.data(), sizeof(float) * 4 * 4);\n  return invertible;\n}\n\n#endif /* __EIGEN3_MATRIX_C_API_CC__ */\n", "meta": {"hexsha": "2024a1ba59ad7d9ffa60e0c99dfe0a7e03355ebb", "size": 1602, "ext": "cc", "lang": "C++", "max_stars_repo_path": "intern/eigen/intern/matrix.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/matrix.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/matrix.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.2264150943, "max_line_length": 74, "alphanum_fraction": 0.7315855181, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.031143833232534775, "lm_q1q2_score": 0.01532862521792065}}
{"text": "/**\n * @file stomp.cpp\n * @brief This contains the stomp core algorithm\n *\n * @author Jorge Nicho\n * @date March 7, 2016\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2016, 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 <ros/console.h>\n#include <limits.h>\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n#include <math.h>\n#include <stomp_core/utils.h>\n#include <numeric>\n#include \"stomp_core/stomp.h\"\n#include <stomp_core/rosconsole_extras.h>\n\nstatic const double DEFAULT_NOISY_COST_IMPORTANCE_WEIGHT = 1.0; /**< Default noisy cost importance weight */\nstatic const double MIN_COST_DIFFERENCE = 1e-8; /**< Minimum cost difference allowed during probability calculation */\nstatic const double MIN_CONTROL_COST_WEIGHT = 1e-8; /**< Minimum control cost weight allowed */\n\n/**\n * @brief Compute a linear interpolated trajectory given a start and end state\n * @param first             The start position\n * @param last              The final position\n * @param num_timesteps     The number of timesteps\n * @param trajectory_joints The returned linear interpolated trajectory\n */\nstatic void computeLinearInterpolation(const std::vector<double>& first,const std::vector<double>& last,\n                         int num_timesteps,\n                         Eigen::MatrixXd& trajectory_joints)\n{\n  trajectory_joints.setZero(first.size(),num_timesteps);\n  for(int unsigned i = 0; i < first.size(); i++)\n  {\n    double dtheta = (last[i] - first[i])/(num_timesteps - 1);\n    for(unsigned int j = 0; j < num_timesteps; j++)\n    {\n      trajectory_joints(i,j) = first[i] + j * dtheta;\n    }\n  }\n}\n\n/**\n * @brief Compute a cubic interpolated trajectory given a start and end state\n * @param first             The start position\n * @param last              The final position\n * @param num_points        The number of points in the trajectory\n * @param dt                The timestep in seconds\n * @param trajectory_joints The returned cubic interpolated trajectory\n */\nstatic void computeCubicInterpolation(const std::vector<double>& first,const std::vector<double>& last,\n                         int num_points,double dt,\n                         Eigen::MatrixXd& trajectory_joints)\n{\n  std::vector<double> coeffs(4,0);\n  double total_time = (num_points - 1) * dt;\n  for(int unsigned i = 0; i < first.size(); i++)\n  {\n    coeffs[0] = first[i];\n    coeffs[2] = (3/(pow(total_time,2))) * (last[i] - first[i]);\n    coeffs[3] = (-2/(pow(total_time,3))) * (last[i] - first[i]);\n\n    double t;\n    for(unsigned j = 0; j < num_points; j++)\n    {\n      t = j*dt;\n      trajectory_joints(i,j) = coeffs[0] + coeffs[2]*pow(t,2) + coeffs[3]*pow(t,3);\n    }\n  }\n}\n\n/**\n * @brief Compute a minimum cost trajectory given a start and end state\n * @param first                        The start position\n * @param last                         The final position\n * @param control_cost_matrix_R_padded The control cost matrix with padding\n * @param inv_control_cost_matrix_R    The inverse constrol cost matrix\n * @param trajectory_joints            The returned minimum cost trajectory\n * @return True if successful, otherwise false\n */\nbool computeMinCostTrajectory(const std::vector<double>& first,\n                              const std::vector<double>& last,\n                              const Eigen::MatrixXd& control_cost_matrix_R_padded,\n                              const Eigen::MatrixXd& inv_control_cost_matrix_R,\n                              Eigen::MatrixXd& trajectory_joints)\n{\n  using namespace stomp_core;\n\n  if(control_cost_matrix_R_padded.rows() != control_cost_matrix_R_padded.cols())\n  {\n    ROS_ERROR(\"Control Cost Matrix is not square\");\n    return false;\n  }\n\n\n  int timesteps = control_cost_matrix_R_padded.rows() - 2*(FINITE_DIFF_RULE_LENGTH - 1);\n  int start_index_padded = FINITE_DIFF_RULE_LENGTH - 1;\n  int end_index_padded = start_index_padded + timesteps-1;\n  std::vector<Eigen::VectorXd> linear_control_cost(first.size(),Eigen::VectorXd::Zero(timesteps));\n  trajectory_joints.setZero(first.size(),timesteps);\n\n\n  for(unsigned int d = 0; d < first.size(); d++)\n  {\n    linear_control_cost[d].transpose() = first[d] * Eigen::VectorXd::Ones(FINITE_DIFF_RULE_LENGTH - 1).transpose() *\n        control_cost_matrix_R_padded.block(0,start_index_padded,FINITE_DIFF_RULE_LENGTH - 1,timesteps);\n\n    linear_control_cost[d].transpose() += last[d] * Eigen::VectorXd::Ones(FINITE_DIFF_RULE_LENGTH - 1).transpose() *\n        control_cost_matrix_R_padded.block(end_index_padded + 1,start_index_padded,FINITE_DIFF_RULE_LENGTH - 1,\n                                    timesteps);\n\n    linear_control_cost[d] *=2;\n\n    trajectory_joints.row(d) = -0.5*inv_control_cost_matrix_R*linear_control_cost[d];\n    trajectory_joints(d,0) = first[d];\n    trajectory_joints(d,timesteps - 1) = last[d];\n  }\n\n  return true;\n}\n\n/**\n * @brief Compute the parameters control costs\n * @param parameters            The parameters used to compute the control cost\n * @param dt                    The timestep in seconds\n * @param control_cost_weight   The control cost weight\n * @param control_cost_matrix_R The control cost matrix\n * @param control_costs returns The parameters control costs\n */\nvoid computeParametersControlCosts(const Eigen::MatrixXd& parameters,\n                                          double dt,\n                                          double control_cost_weight,\n                                          const Eigen::MatrixXd& control_cost_matrix_R,\n                                          Eigen::MatrixXd& control_costs)\n{\n  std::size_t num_timesteps = parameters.cols();\n  double cost = 0;\n  for(auto d = 0u; d < parameters.rows(); d++)\n  {\n    cost = double(parameters.row(d)*(control_cost_matrix_R*parameters.row(d).transpose()));\n    control_costs.row(d).setConstant( 0.5*(1/dt)*cost );\n  }\n\n  double max_coeff = control_costs.maxCoeff();\n  control_costs /= (max_coeff > 1e-8) ? max_coeff : 1;\n  control_costs *= control_cost_weight;\n}\n\n\nnamespace stomp_core {\n\n\nStomp::Stomp(const StompConfiguration& config,TaskPtr task):\n    config_(config),\n    task_(task)\n{\n\n  resetVariables();\n\n}\n\nbool Stomp::clear()\n{\n  return resetVariables();\n}\n\nvoid Stomp::setConfig(const StompConfiguration& config)\n{\n  config_ = config;\n  resetVariables();\n}\n\nbool Stomp::solve(const std::vector<double>& first,const std::vector<double>& last,\n                  Eigen::MatrixXd& parameters_optimized)\n{\n  // initialize trajectory\n  if(!computeInitialTrajectory(first,last))\n  {\n    ROS_ERROR(\"Unable to generate initial trajectory\");\n  }\n\n  return solve(parameters_optimized_,parameters_optimized);\n}\n\nbool Stomp::solve(const Eigen::VectorXd& first,const Eigen::VectorXd& last,\n                  Eigen::MatrixXd& parameters_optimized)\n{\n  // converting to std vectors\n  std::vector<double> start(first.size());\n  std::vector<double> end(last.size());\n\n  Eigen::VectorXd::Map(&start[0],first.size()) = first;\n  Eigen::VectorXd::Map(&end[0],last.size()) = last;\n\n  return solve(start,end,parameters_optimized);\n}\n\nbool Stomp::solve(const Eigen::MatrixXd& initial_parameters,\n                  Eigen::MatrixXd& parameters_optimized)\n{\n  if(parameters_optimized_.isZero())\n  {\n    parameters_optimized_ = initial_parameters;\n  }\n\n  // check initial trajectory size\n  if(initial_parameters.rows() != config_.num_dimensions || initial_parameters.cols() != config_.num_timesteps)\n  {\n    ROS_ERROR(\"Initial trajectory dimensions is incorrect\");\n    return false;\n  }\n  else\n  {\n    if(initial_parameters.cols() != config_.num_timesteps)\n    {\n      ROS_ERROR(\"Initial trajectory number of time steps is incorrect\");\n      return false;\n    }\n  }\n\n  if(not config_.optimization_enabled)\n  {\n    ROS_YELLOW_STREAM(\"OPTIMIZATION NOT ENABLED, returning initial trajectory as result.\");\n    parameters_optimized = initial_parameters;\n    return true;\n  }\n\n  current_iteration_ = 1;\n  unsigned int valid_iterations = 0;\n  current_lowest_cost_ = std::numeric_limits<double>::max();\n\n  {\n    MeasureTime timer(\"computeOptimizedCost\");\n\n    // computing initialial trajectory cost\n    if(!computeOptimizedCost())\n    {\n      ROS_ERROR(\"Failed to calculate initial trajectory cost\");\n      return false;\n    }\n  }\n\n  while(current_iteration_ <= config_.num_iterations && runSingleIteration())\n  {\n    ROS_WARN(\"STOMP completed iteration %i with cost %f\",current_iteration_,current_lowest_cost_);\n\n\n    if(parameters_valid_)\n    {\n      ROS_INFO(\"Found valid solution, will iterate %i more time(s) \",\n               config_.num_iterations_after_valid - valid_iterations);\n\n      valid_iterations++;\n    }\n    else\n    {\n      valid_iterations = 0;\n    }\n\n    if(valid_iterations > config_.num_iterations_after_valid)\n    {\n      break;\n    }\n\n    current_iteration_++;\n  }\n\n  if(parameters_valid_)\n  {\n    ROS_INFO(\"STOMP found a valid solution with cost %f after %i iterations\",\n             current_lowest_cost_,current_iteration_);\n  }\n  else\n  {\n    if (proceed_)\n      ROS_ERROR(\"STOMP failed to find a valid solution after %i iterations\",current_iteration_);\n    else\n      ROS_ERROR_STREAM(\"Stomp was terminated\");\n  }\n\n  parameters_optimized = parameters_optimized_;\n\n  // notifying task\n  task_->done(parameters_valid_,current_iteration_,current_lowest_cost_,parameters_optimized);\n\n  return parameters_valid_;\n}\n\nbool Stomp::resetVariables()\n{\n  proceed_= true;\n  parameters_total_cost_ = 0;\n  parameters_valid_ = false;\n  num_active_rollouts_ = 0;\n  current_iteration_ = 0;\n\n  // verifying configuration\n  if(config_.max_rollouts <= config_.num_rollouts)\n  {\n    ROS_DEBUG_STREAM(\"'max_rollouts' must be greater than 'num_rollouts_per_iteration'.\");\n    config_.max_rollouts = config_.num_rollouts + 1; // one more to accommodate optimized trajectory\n  }\n\n  // noisy rollouts allocation\n  int d = config_.num_dimensions;\n  num_active_rollouts_ = 0;\n  noisy_rollouts_.resize(config_.max_rollouts);\n  reused_rollouts_.resize(config_.max_rollouts);\n\n  // initializing rollout\n  Rollout rollout;\n  rollout.noise.resize(d, config_.num_timesteps);\n  rollout.noise.setZero();\n\n  rollout.parameters_noise.resize(d, config_.num_timesteps);\n  rollout.parameters_noise.setZero();\n\n  rollout.probabilities.resize(d, config_.num_timesteps);\n  rollout.probabilities.setZero();\n\n  rollout.full_probabilities.clear();\n  rollout.full_probabilities.resize(d);\n\n  rollout.full_costs.clear();\n  rollout.full_costs.resize(d);\n\n  rollout.control_costs.resize(d, config_.num_timesteps);\n  rollout.control_costs.setZero();\n\n  rollout.total_costs.resize(d, config_.num_timesteps);\n  rollout.total_costs.setZero();\n\n  rollout.state_costs.resize(config_.num_timesteps);\n  rollout.state_costs.setZero();\n\n  rollout.importance_weight = DEFAULT_NOISY_COST_IMPORTANCE_WEIGHT;\n\n  for(unsigned int r = 0; r < config_.max_rollouts ; r++)\n  {\n    noisy_rollouts_[r] = rollout;\n    reused_rollouts_[r] = rollout;\n  }\n\n  // parameter updates\n  parameters_updates_.resize(d, config_.num_timesteps);\n  parameters_updates_.setZero();\n\n  parameters_control_costs_.resize(d, config_.num_timesteps);\n  parameters_control_costs_.setZero();\n\n  parameters_state_costs_.resize(config_.num_timesteps);\n  parameters_state_costs_.setZero();\n\n  parameters_optimized_.resize(config_.num_dimensions,config_.num_timesteps);\n  parameters_optimized_.setZero();\n\n  // generate finite difference matrix\n  start_index_padded_ = FINITE_DIFF_RULE_LENGTH-1;\n  num_timesteps_padded_ = config_.num_timesteps + 2*(FINITE_DIFF_RULE_LENGTH-1);\n  generateFiniteDifferenceMatrix(num_timesteps_padded_,DerivativeOrders::STOMP_ACCELERATION,\n                                 config_.delta_t,finite_diff_matrix_A_padded_);\n\n  /* control cost matrix (R = A_transpose * A):\n   * Note: Original code multiplies the A product by the time interval.  However this is not\n   * what was described in the literature\n   */\n  control_cost_matrix_R_padded_ = config_.delta_t*finite_diff_matrix_A_padded_.transpose() * finite_diff_matrix_A_padded_;\n  control_cost_matrix_R_ = control_cost_matrix_R_padded_.block(\n      start_index_padded_,start_index_padded_,config_.num_timesteps,config_.num_timesteps);\n  inv_control_cost_matrix_R_ = control_cost_matrix_R_.fullPivLu().inverse();\n\n  /*\n   * Applying scale factor to ensure that max(R^-1)==1\n   */\n  double maxVal = std::abs(inv_control_cost_matrix_R_.maxCoeff());\n  control_cost_matrix_R_padded_ *= maxVal;\n  control_cost_matrix_R_ *= maxVal;\n  inv_control_cost_matrix_R_ /= maxVal; // used in computing the minimum control cost initial trajectory\n\n  return true;\n}\n\nbool Stomp::computeInitialTrajectory(const std::vector<double>& first,const std::vector<double>& last)\n{\n  bool valid = true;\n\n  switch(config_.initialization_method)\n  {\n    case TrajectoryInitializations::CUBIC_POLYNOMIAL_INTERPOLATION:\n\n      computeCubicInterpolation(first,last,config_.num_timesteps,config_.delta_t,parameters_optimized_);\n      break;\n    case TrajectoryInitializations::LINEAR_INTERPOLATION:\n\n      computeLinearInterpolation(first,last,config_.num_timesteps,parameters_optimized_);\n      break;\n    case TrajectoryInitializations::MININUM_CONTROL_COST:\n\n      valid = computeMinCostTrajectory(first,last,control_cost_matrix_R_padded_,inv_control_cost_matrix_R_,parameters_optimized_);\n      break;\n  }\n\n  return valid;\n}\n\nbool Stomp::cancel()\n{\n  ROS_WARN(\"Interrupting STOMP\");\n  proceed_ = false;\n  return !proceed_;\n}\n\nbool Stomp::runSingleIteration()\n{\n  MeasureTime timer(\"runSingleIteration()\");\n\n  if(!proceed_)\n  {\n    return false;\n  }\n\n  bool proceed = generateNoisyRollouts() &&\n      computeNoisyRolloutsCosts() &&\n      filterNoisyRollouts() &&\n      computeProbabilities() &&\n      updateParameters() &&\n      computeOptimizedCost();\n\n  // notifying end of iteration\n  task_->postIteration(0,config_.num_timesteps,current_iteration_,current_lowest_cost_,parameters_optimized_);\n\n  return proceed;\n}\n\nbool Stomp::generateNoisyRollouts()\n{\n  MeasureTime timer(\"generateNoisyRollouts\");\n  // calculating number of rollouts to reuse from previous iteration\n  std::vector< std::pair<double,int> > rollout_cost_sorter; // Used to sort noisy trajectories in ascending order wrt their total cost\n  double h = config_.exponentiated_cost_sensitivity;\n  int rollouts_stored = num_active_rollouts_-1; // don't take the optimized rollout into account\n  rollouts_stored = rollouts_stored < 0 ? 0 : rollouts_stored;\n  int rollouts_generate = config_.num_rollouts;\n  int rollouts_total = rollouts_generate + rollouts_stored +1;\n  int rollouts_reuse =  rollouts_total < config_.max_rollouts  ? rollouts_stored :  config_.max_rollouts - (rollouts_generate + 1) ; // +1 for optimized params\n\n  // selecting least costly rollouts from previous iteration\n  if(rollouts_reuse > 0)\n  {\n    // find min and max cost for exponential cost scaling\n    double min_cost = std::numeric_limits<double>::max();\n    double max_cost = std::numeric_limits<double>::min();\n    for (int r=1; r<rollouts_stored; ++r)\n    {\n      double c = noisy_rollouts_[r].total_cost;\n      if (c < min_cost)\n        min_cost = c;\n      if (c > max_cost)\n        max_cost = c;\n    }\n\n    double cost_denom = max_cost - min_cost;\n    if (cost_denom < 1e-8)\n      cost_denom = 1e-8;\n\n    // compute weighted cost on all rollouts\n    double cost_prob;\n    double weighted_prob;\n    for (auto r = 0u; r<rollouts_stored; ++r)\n    {\n\n      // Apply noise generated on the previous iteration onto the current trajectory\n      noisy_rollouts_[r].noise = noisy_rollouts_[r].parameters_noise\n          - parameters_optimized_;\n\n      cost_prob = exp(-h*(noisy_rollouts_[r].total_cost - min_cost)/cost_denom);\n      weighted_prob = cost_prob * noisy_rollouts_[r].importance_weight;\n      rollout_cost_sorter.push_back(std::make_pair(-weighted_prob,r));\n    }\n\n\n    std::sort(rollout_cost_sorter.begin(), rollout_cost_sorter.end());\n\n    // use the best ones: (copy them into reused_rollouts)\n    for (auto r = 0u; r<rollouts_stored; ++r)\n    {\n      int reuse_index = rollout_cost_sorter[r].second;\n      reused_rollouts_[r] = noisy_rollouts_[reuse_index];\n    }\n\n    // copy them back from reused_rollouts_ into rollouts_\n    for (auto r = 0u; r<rollouts_reuse; ++r)\n    {\n      noisy_rollouts_[rollouts_generate + r ] = reused_rollouts_[r];\n    }\n  }\n\n  // adding optimized trajectory as the last rollout\n  noisy_rollouts_[rollouts_generate + rollouts_reuse].parameters_noise = parameters_optimized_;\n  noisy_rollouts_[rollouts_generate + rollouts_reuse].noise.setZero();\n  noisy_rollouts_[rollouts_generate + rollouts_reuse].state_costs = parameters_state_costs_;\n  noisy_rollouts_[rollouts_generate + rollouts_reuse].control_costs = parameters_control_costs_;\n\n\n  // generate new noisy rollouts\n  for(auto r = 0u; r < rollouts_generate; r++)\n  {\n    if(!task_->generateNoisyParameters(parameters_optimized_,\n                                      0,config_.num_timesteps,\n                                      current_iteration_,r,\n                                      noisy_rollouts_[r].parameters_noise,\n                                      noisy_rollouts_[r].noise))\n    {\n      ROS_ERROR(\"Failed to generate noisy parameters at iteration %i\",current_iteration_);\n      return false;\n    }\n\n  }\n\n  // update total active rollouts\n  num_active_rollouts_ = rollouts_reuse + rollouts_generate + 1;\n\n  return true;\n}\n\nbool Stomp::filterNoisyRollouts()\n{\n  MeasureTime timer(\"filterNoisyRollouts\");\n  // apply post noise generation filters\n  bool filtered = false;\n  for(auto r = 0u ; r < config_.num_rollouts; r++)\n  {\n    if(!task_->filterNoisyParameters(0,config_.num_timesteps,current_iteration_,r,noisy_rollouts_[r].parameters_noise,filtered))\n    {\n      ROS_ERROR_STREAM(\"Failed to filter noisy parameters\");\n      return false;\n    }\n\n    if(filtered)\n    {\n      noisy_rollouts_[r].noise = noisy_rollouts_[r].parameters_noise - parameters_optimized_;\n    }\n  }\n\n  return true;\n}\n\nbool Stomp::computeNoisyRolloutsCosts()\n{\n  MeasureTime timer(\"computeNoisyRollouts\");\n  // computing state and control costs\n  bool valid = computeRolloutsStateCosts() && computeRolloutsControlCosts();\n\n  if(valid)\n  {\n    // compute total costs\n    double total_state_cost ;\n    double total_control_cost;\n\n    for(auto r = 0u ; r < num_active_rollouts_;r++)\n    {\n      Rollout& rollout = noisy_rollouts_[r];\n      total_state_cost = rollout.state_costs.sum();\n\n      // Compute control + state cost for each joint\n      total_control_cost = 0;\n      double ccost = 0;\n      for(auto d = 0u; d < config_.num_dimensions; d++)\n      {\n        ccost = rollout.control_costs.row(d).sum();\n        total_control_cost += ccost;\n        rollout.full_costs[d] = ccost + total_state_cost;\n      }\n      rollout.total_cost = total_state_cost + total_control_cost;\n\n      // Compute total cost for each time step\n      for(auto d = 0u; d < config_.num_dimensions; d++)\n      {\n        rollout.total_costs.row(d) = rollout.state_costs.transpose() + rollout.control_costs.row(d);\n      }\n    }\n  }\n\n  return valid;\n}\n\nbool Stomp::computeRolloutsStateCosts()\n{\n  MeasureTime timer(\"computeRolloutsStateCosts\");\n  bool all_valid = true;\n  bool proceed = true;\n  for(auto r = 0u ; r < config_.num_rollouts; r++)\n  {\n    if(!proceed_)\n    {\n      proceed = false;\n      break;\n    }\n\n    Rollout& rollout = noisy_rollouts_[r];\n    if(!task_->computeNoisyCosts(rollout.parameters_noise,0,\n                            config_.num_timesteps,\n                            current_iteration_,r,\n                            rollout.state_costs,all_valid))\n    {\n      ROS_ERROR(\"Trajectory cost computation failed for rollout %i.\",r);\n      proceed = false;\n      break;\n    }\n  }\n\n  return proceed;\n}\nbool Stomp::computeRolloutsControlCosts()\n{\n  MeasureTime timer(\"computeRolloutsControlCosts\");\n  Eigen::ArrayXXd Ax; // accelerations\n  for(auto r = 0u ; r < num_active_rollouts_; r++)\n  {\n    Rollout& rollout = noisy_rollouts_[r];\n\n    if(config_.control_cost_weight < MIN_CONTROL_COST_WEIGHT)\n    {\n      for(auto d = 0u; d < config_.num_dimensions; d++)\n      {\n        rollout.control_costs.row(d).setConstant(0);\n      }\n    }\n    else\n    {\n      computeParametersControlCosts(rollout.parameters_noise,\n                                    config_.delta_t,\n                                    config_.control_cost_weight,\n                                    control_cost_matrix_R_,rollout.control_costs);\n    }\n  }\n  return true;\n}\n\nbool Stomp::computeProbabilities()\n{\n  MeasureTime timer(\"computeProbabilities\");\n  double cost;\n  double min_cost;\n  double max_cost;\n  double denom;\n  double numerator;\n  double probl_sum = 0.0; // total probability sum of all rollouts for each joint\n  const double h = config_.exponentiated_cost_sensitivity;\n  double exponent = 0;\n\n  for (auto d = 0u; d<config_.num_dimensions; ++d)\n  {\n\n    for (auto t = 0u; t<config_.num_timesteps; t++)\n    {\n\n      // find min and max cost over all rollouts at timestep 't':\n      min_cost = noisy_rollouts_[0].total_costs(d,t);\n      max_cost = min_cost;\n      for (auto r=0u; r<num_active_rollouts_; ++r)\n      {\n          cost = noisy_rollouts_[r].total_costs(d,t);\n          if (cost < min_cost)\n              min_cost = cost;\n          if (cost > max_cost)\n              max_cost = cost;\n      }\n\n      denom = max_cost - min_cost;\n\n      // prevent division by zero:\n      if (denom < MIN_COST_DIFFERENCE)\n      {\n        denom = MIN_COST_DIFFERENCE;\n      }\n\n      probl_sum = 0.0;\n      for (auto r = 0u; r<num_active_rollouts_; ++r)\n      {\n        // this is the exponential term in the probability calculation described in the literature\n        exponent = -h*(noisy_rollouts_[r].total_costs(d,t) - min_cost)/denom;\n        noisy_rollouts_[r].probabilities(d,t) = noisy_rollouts_[r].importance_weight *\n            exp(exponent);\n\n        probl_sum += noisy_rollouts_[r].probabilities(d,t);\n      }\n\n      // scaling each probability value by the sum of all probabilities corresponding to all rollouts at time \"t\"\n      for (auto r = 0u; r<num_active_rollouts_; ++r)\n      {\n        noisy_rollouts_[r].probabilities(d,t) /= probl_sum;\n      }\n    }\n\n\n    // computing full probabilities\n    min_cost = noisy_rollouts_[0].full_costs[d];\n    max_cost = min_cost;\n    double c = 0.0;\n    for (int r=1; r<num_active_rollouts_; ++r)\n    {\n      c = noisy_rollouts_[r].full_costs[d];\n      if (c < min_cost)\n        min_cost = c;\n      if (c > max_cost)\n        max_cost = c;\n    }\n\n    denom = max_cost - min_cost;\n    denom = denom < MIN_COST_DIFFERENCE ? MIN_COST_DIFFERENCE : denom;\n\n    probl_sum = 0.0;\n    for (int r=0; r<num_active_rollouts_; ++r)\n    {\n      noisy_rollouts_[r].full_probabilities[d] = noisy_rollouts_[r].importance_weight *\n          exp(-h*(noisy_rollouts_[r].full_costs[d] - min_cost)/denom);\n      probl_sum += noisy_rollouts_[r].full_probabilities[d];\n    }\n    for (int r=0; r<num_active_rollouts_; ++r)\n    {\n        noisy_rollouts_[r].full_probabilities[d] /= probl_sum;\n    }\n  }\n\n  return true;\n}\n\nbool Stomp::updateParameters()\n{\n  MeasureTime timer(\"updateParameters\");\n  // computing updates from probabilities using convex combination\n  parameters_updates_.setZero();\n  for(auto d = 0u; d < config_.num_dimensions ; d++)\n  {\n\n    for(auto r = 0u; r < num_active_rollouts_; r++)\n    {\n      auto& rollout = noisy_rollouts_[r];\n      parameters_updates_.row(d) +=  (rollout.noise.row(d).array() * rollout.probabilities.row(d).array()).matrix();\n    }\n\n  }\n\n  // filtering updates\n  if(!task_->filterParameterUpdates(0,config_.num_timesteps,current_iteration_,parameters_optimized_,parameters_updates_))\n  {\n    ROS_ERROR(\"Updates filtering step failed\");\n    return false;\n  }\n\n  // updating parameters\n  parameters_optimized_ += parameters_updates_;\n\n  return true;\n}\n\nbool Stomp::computeOptimizedCost()\n{\n  MeasureTime timer(\"computeOptimizedCosts\");\n  // control costs\n  parameters_total_cost_ = 0;\n  if(config_.control_cost_weight > MIN_CONTROL_COST_WEIGHT)\n  {\n    computeParametersControlCosts(parameters_optimized_,\n                                  config_.delta_t,\n                                  config_.control_cost_weight,\n                                  control_cost_matrix_R_,\n                                  parameters_control_costs_);\n\n    // adding all costs\n    parameters_total_cost_ = parameters_control_costs_.rowwise().sum().sum();\n\n  }\n\n  // state costs\n  if(task_->computeCosts(parameters_optimized_,\n                         0,config_.num_timesteps,current_iteration_,\n                         parameters_state_costs_,parameters_valid_))\n  {\n    parameters_total_cost_ += parameters_state_costs_.sum();\n  }\n  else\n  {\n    return false;\n  }\n\n  if(current_lowest_cost_ > parameters_total_cost_)\n  {\n    current_lowest_cost_ = parameters_total_cost_;\n  }\n  else\n  {\n    // reverting updates as no improvement was made\n    parameters_optimized_ -= parameters_updates_;\n  }\n\n  return true;\n}\n\n} /* namespace stomp */\n", "meta": {"hexsha": "3107679c3165ab144d0ed91c9e39762a924fa130", "size": 25566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stomp_core/src/stomp.cpp", "max_stars_repo_name": "bmagyar/industrial_moveit", "max_stars_repo_head_hexsha": "8ebb0e6e75fe9a229f945f71cda6fe238a68d585", "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": "stomp_core/src/stomp.cpp", "max_issues_repo_name": "bmagyar/industrial_moveit", "max_issues_repo_head_hexsha": "8ebb0e6e75fe9a229f945f71cda6fe238a68d585", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stomp_core/src/stomp.cpp", "max_forks_repo_name": "bmagyar/industrial_moveit", "max_forks_repo_head_hexsha": "8ebb0e6e75fe9a229f945f71cda6fe238a68d585", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-21T02:36:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-21T02:36:19.000Z", "avg_line_length": 31.102189781, "max_line_length": 159, "alphanum_fraction": 0.6814910428, "num_tokens": 6113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.031143832333282648, "lm_q1q2_score": 0.015328624775319422}}
{"text": "/**\n * @file bcsr_matrix_tools.cpp\n * @brief\n * @date 2009-11-24\n */\n#ifdef BSPY_EXPORTING_PLUGIN\n#include <boost/python.hpp>\n#endif\n#include \"bcsr_matrix_tools.h\"\n\n#include <time.h>\n#include <stdlib.h>\n#include <map>\n#include <boost/format.hpp>\n\n//#include \"strategies.h\"\n\nusing namespace std;\nusing namespace boost::python;\n\n\nnamespace blue_sky\n{\n  bcsr_matrix_tools::bcsr_matrix_tools (bs_type_ctor_param)\n        : bcsr_matrix_tools_iface ()\n    {\n    }\n  bcsr_matrix_tools::bcsr_matrix_tools (const bcsr_matrix_tools & /*src*/) : bs_refcounter ()\n     {\n     }\n\n/*!\n  \\brief read matrix from ascii file\n  \\param matrix         -- reference to the BCSR matrix interface\n  \\param file_name -- name of the file\n  \\return 0 if success\n*/\nint\nbcsr_matrix_tools::ascii_read_from_csr_format (sp_bcsr_t matrix, const std::string &file_name) const\n{\n  //locale_keeper lkeeper (\"C\", LC_NUMERIC);\n\n  FILE *fp = 0;\n  char buf[4096];\n  int state = 0;\n  t_long nc, nr, nnz = 0, nbs, b_sqr = 0;\n  t_long row_ind = 0;\n  t_long j_ind = 0, j = 0;\n  t_long *rows_ptr;\n  t_long *cols_ind;\n  t_float *values;\n  char *start_ptr, *end_ptr;\n\n  fp = fopen (file_name.c_str (), \"r\");\n  //BS_ASSERT (fp) (file_name);\n  if (!fp)\n    {\n      //bs_throw_exception (\"Can't open file\");\n      return -1;\n    }\n\n  while (fgets(buf, 4096, fp))\n    {\n      // skip comments\n      if (!strncmp (buf, \"//\", 2))\n        continue;\n      if (state == 0) // read n_rows, n_cols, n_non_zeros\n        {\n          start_ptr = buf;\n          nr = strtol (start_ptr, &end_ptr, 10);\n          if (start_ptr == end_ptr)\n            continue;\n          start_ptr = end_ptr;\n          nc = strtol (start_ptr, &end_ptr, 10);\n          if (start_ptr == end_ptr)\n            continue;\n          start_ptr = end_ptr;\n          nnz = strtol (start_ptr, &end_ptr, 10);\n          if (start_ptr == end_ptr)\n            continue;\n          start_ptr = end_ptr;\n          nbs = strtol (start_ptr, &end_ptr, 10);\n          if (start_ptr == end_ptr)\n            continue;\n\n          if (matrix->init (nr, nc, nbs, nnz))\n            {\n              //bs_throw_exception (\"Can't init matrix\");\n              return -45;\n            }\n\n          //BOSOUT << \"nr = \" << nr << \", nc = \" << nc << \", nbs = \" << nbs << \", nnz = \" << nnz << bs_end;\n\n          state = 1;\n\n          rows_ptr = &(*(matrix->get_rows_ptr ()))[0];\n          cols_ind = &(*(matrix->get_cols_ind ()))[0];\n          values = &(*(matrix->get_values ()))[0];\n\n          rows_ptr[0] = 0;\n          b_sqr = nbs * nbs;\n        }\n      else if (state == 1) // read rows_ptr\n        {\n          t_long n_rows = matrix->get_n_rows ();\n\n          start_ptr = buf;\n          rows_ptr[row_ind + 1] = strtol (start_ptr, &end_ptr, 10);\n          if (start_ptr == end_ptr)\n            continue;\n          ++row_ind;\n          if (row_ind == n_rows)\n            state = 2;\n        }\n      else if (state == 2) // read values\n        {\n          start_ptr = buf;\n          cols_ind[j_ind] = strtol (start_ptr, &end_ptr, 10);\n          if (start_ptr == end_ptr)\n            continue;\n          for (j = 0; j < b_sqr; ++j)\n            {\n              start_ptr = end_ptr;\n              values[j_ind * b_sqr + j] = strtod (start_ptr, &end_ptr);\n              if (start_ptr == end_ptr)\n                continue;\n            }\n          j_ind++;\n          if (j_ind == nnz)\n            break;\n        }\n    }\n\n  //BOSOUT << \"nnz = \" << nnz << bs_end;\n\n  fclose (fp);\n  return 0;\n}\n\n/*!\n  \\brief write matrix to ascii file\n  \\param matrix         -- reference to the BCSR matrix interface\n  \\param file_name -- name of the file\n  \\return 0 if success\n*/\nint\nbcsr_matrix_tools::ascii_write_to_csr_format (const sp_bcsr_t matrix,\n                                              const std::string &file_name,\n                                              const bool sort_cols) const\n{\n  FILE *fp = 0;\n  t_long i, j, j1, j2, jj, jj1, jj2, counter, b_sqr = 0;\n  t_long n_row_cols = 0;\n  spv_long sp_sort_index = BS_KERNEL.create_object (v_long::bs_type ());\n  BS_ASSERT (sp_sort_index);\n  t_long *sort_index = 0;\n\n  t_long *rows_ptr = &(*(matrix->get_rows_ptr ()))[0];\n  t_long *cols_ind = &(*(matrix->get_cols_ind ()))[0];\n  t_float *values = &(*(matrix->get_values ()))[0];\n  t_long n_rows = matrix->get_n_rows ();\n  t_long n_cols = matrix->get_n_cols ();\n  t_long n_block_size = matrix->get_n_block_size ();\n  t_long n_nnz = matrix->get_n_non_zeros ();\n  b_sqr = n_block_size * n_block_size;\n\n  fp = fopen (file_name.c_str (), \"w\");\n  if (!fp)\n    //TODO: write error message\n    return -1;\n  fprintf (fp, \"// N_ROWS\\tN_COLS\\tN_NON_ZEROS\\tN_BLOCK_SIZE\\n\");\n  fprintf (fp,\n      (boost::format(\"%ld\\t%ld\\t%ld\\t%ld\\n\") %\n       n_rows % n_cols % n_nnz % n_block_size).str().c_str());\n\n  fprintf (fp, \"// Rows indexes[1..n_rows] (with out 0)\\n\");\n  for (i = 1; i <= n_rows; ++i)\n    fprintf (fp, (boost::format(\"%ld\\n\") % rows_ptr[i]).str().c_str());\n\n  fprintf (fp, \"// END of Rows indexes\\n\");\n\n\n  fprintf (fp, \"// Values n_non_zeros elements\\n\");\n  fprintf (fp, \"//COLUMN\\tVALUE\\n\");\n  for (i = 0, counter = 0; i < n_rows; ++i)\n    {\n      fprintf (fp, (boost::format(\"// ROW %ld\\n\") % i).str().c_str());\n      j1 = rows_ptr[i];\n      j2 = rows_ptr[i + 1];\n\n      if (sort_cols)\n        {\n          sp_sort_index->resize (j2 - j1);\n          sort_index = &(*(sp_sort_index))[0];\n          for (j = j1, jj = 0; j < j2; ++j, ++jj)\n            {\n              sort_index[jj] = j;\n            }\n\n          n_row_cols = j2 - j1;\n          for (j = 0; j < n_row_cols - 1; ++j)\n            {\n              for (jj = j; jj < n_row_cols; ++jj)\n                {\n                  if (cols_ind[sort_index[j]] > cols_ind[sort_index[jj]])\n                    {\n                      jj1 = sort_index[j];\n                      sort_index[j] = sort_index[jj];\n                      sort_index[jj] = jj1;\n                    }\n                }\n            }\n          for (j = 0; j < n_row_cols; ++j, ++counter)\n            {\n              fprintf (fp, (boost::format(\"%ld\") % cols_ind[sort_index[j]]).str().c_str());\n              jj1 = sort_index[j] * b_sqr;\n              jj2 = jj1 + b_sqr;\n                for (jj = jj1; jj < jj2; ++jj)\n                  fprintf (fp, \"\\t%le\", values[jj]);\n              fprintf (fp, \"\\n\");\n            }\n        }\n      else\n        {\n          for (j = j1; j < j2; ++j, ++counter)\n            {\n              fprintf (fp, (boost::format(\"%ld\") % cols_ind[j]).str().c_str());\n              jj1 = j * b_sqr;\n              jj2 = jj1 + b_sqr;\n                for (jj = jj1; jj < jj2; ++jj)\n                  fprintf (fp, \"\\t%le\", values[jj]);\n              fprintf (fp, \"\\n\");\n            }\n        }\n    }\n  if (counter != n_nnz)\n    return -1;\n  fprintf (fp, \"// END OF FILE\\n\");\n  fclose (fp);\n\n  return 0;\n}\n\nint\nbcsr_matrix_tools::random_init (sp_bcsr_t matrix,\n                                const t_long new_n_rows,\n                                const t_long new_n_block_size,\n                                const t_double rand_value_dispersion,\n                                const t_long elems_in_row\n                               ) const\n{\n  int r_code = 0;\n  t_long i, j, j1, j2, b_sqr;\n  t_long n_non_zeros;\n\n\n  // check input data\n  if (elems_in_row <= 0)\n    // internal error\n    return -1;\n\n  // setup integer vars\n  n_non_zeros = new_n_rows * elems_in_row; // approx value, final nonzeros value can be equal or less\n  b_sqr = new_n_block_size * new_n_block_size;\n\n  r_code = matrix->init (new_n_rows, new_n_rows, new_n_block_size, n_non_zeros);\n\n  if (r_code)\n    //TODO: print error message\n    return -2;\n\n  t_float *values = &(*(matrix->get_values ()))[0];\n  t_long *rows_ptr = &(*(matrix->get_rows_ptr ()))[0];\n  t_long *cols_ind = &(*(matrix->get_cols_ind ()))[0];\n\n  srand ((unsigned)time( NULL ));\n\n  for (i = 0; i < n_non_zeros * b_sqr; ++i)\n    values[i] = (t_float)rand () / (t_float)RAND_MAX * (t_float)rand_value_dispersion;\n\n  rows_ptr[0] = 0;\n  for (i = 0; i < new_n_rows; ++i)\n    {\n      rows_ptr[i + 1] = rows_ptr[i] +  elems_in_row;\n      j1 = rows_ptr[i];\n      j2 = rows_ptr[i + 1];\n      cols_ind[j1++] = i; // diagonal should be the first\n\n      for (j = j1; j < j2; ++j)\n        {\n\n          int cl = rand () % (int)((double)new_n_rows / (double)(j2 - j1)) + (j - j1) * new_n_rows / (j2 - j1);\n          if (cl == i)\n            {\n              --j;\n              continue;\n            }\n          cols_ind[j] = cl;\n        }\n    }\n\n  //n_non_zeros = rows_ptr[new_n_rows];\n  return 0;\n}\n\n\nint\nbcsr_matrix_tools::gen_2d_laplas (sp_bcsr_t matrix, const t_long n) const\n{\n  int r_code = 0;\n  t_long i, j;\n\n  t_long elems_in_row = 5;\n  t_long new_n_block_size = 1;\n\n  // setup integer vars\n  t_long N = n * n;\n  t_long n_non_zeros = N * elems_in_row; // approx value, final nonzeros value can be equal or less\n\n  r_code = matrix->init (N, N, new_n_block_size, n_non_zeros);\n\n  if (r_code)\n    //TODO: print error message\n    return -2;\n\n  t_float *values = &(*(matrix->get_values ()))[0];\n  t_long *rows_ptr = &(*(matrix->get_rows_ptr ()))[0];\n  t_long *cols_ind = &(*(matrix->get_cols_ind ()))[0];\n\n  rows_ptr[0] = 0;\n  for (i = 0, j = 0; i < N; ++i)\n    {\n      values[j] = 4;\n      cols_ind[j] = i;\n      ++j;\n\n      if (i - n >= 0)\n        {\n          values[j] = -1;\n          cols_ind[j] = i - n;\n          ++j;\n        }\n\n      if (i % n)\n        {\n          values[j] = -1;\n          cols_ind[j] = i - 1;\n          ++j;\n        }\n\n      if ((i + 1) % n)\n        {\n          values[j] = -1;\n          cols_ind[j] = i + 1;\n          ++j;\n        }\n\n      if (i + n < N)\n        {\n          values[j] = -1;\n          cols_ind[j] = i + n;\n          ++j;\n        }\n\n      rows_ptr[i + 1] = j;\n    }\n\n  //n_non_zeros = rows_ptr[new_n_rows];\n  return 0;\n}\n\n\nint\nbcsr_matrix_tools::gen_diagonal (sp_bcsr_t matrix, const t_long n,\n                                 const t_long nb, const t_double val) const\n{\n  int r_code = 0;\n  t_long i, k;\n  t_long b_sqr = nb * nb;\n\n  r_code = matrix->init (n, n, nb, n * b_sqr);\n  if (r_code)\n    //TODO: print error message\n    return -2;\n\n  t_float *values = &(*(matrix->get_values ()))[0];\n  t_long *rows_ptr = &(*(matrix->get_rows_ptr ()))[0];\n  t_long *cols_ind = &(*(matrix->get_cols_ind ()))[0];\n\n  rows_ptr[0] = 0;\n  for (i = 0; i < n; ++i)\n    {\n      for (k = 0; k < b_sqr; ++k)\n        {\n          if (k % (nb + 1) == 0)\n            values[i * b_sqr + k] = val;\n          else\n            values[i * b_sqr + k] = 0.0;\n        }\n      cols_ind[i] = i;\n      rows_ptr[i + 1] = i + 1;\n    }\n\n  return 0;\n}\n\nint\nbcsr_matrix_tools::dense_init (sp_bcsr_t matrix,\n                               const t_long n_rows,\n                               const t_long block_size,\n                               const t_double rand_value_dispersion) const\n{\n  int r_code = 0;\n  t_long b_sqr = block_size * block_size;\n\n  srand ((unsigned)time( NULL ));\n\n  r_code = matrix->init (n_rows, n_rows, block_size, n_rows * n_rows);\n  if (r_code)\n    return -2;\n\n  t_float *values = &(*(matrix->get_values ()))[0];\n  t_long *rows_ptr = &(*(matrix->get_rows_ptr ()))[0];\n  t_long *cols_ind = &(*(matrix->get_cols_ind ()))[0];\n  rows_ptr[0] = 0;\n\n\n  for (t_long i = 0; i < n_rows * n_rows * b_sqr; ++i)\n    {\n      values[i] = (t_float)rand () / (t_float)RAND_MAX * (t_float)rand_value_dispersion;\n    }\n  for (t_long i = 0; i < n_rows; ++i)\n    {\n      t_long cl;\n      t_long j1 = rows_ptr[i];\n\n      rows_ptr[i + 1] = j1 + n_rows;\n\n      // diagonal should be the first\n      cols_ind[j1] = i;\n      cl = j1 + 1;\n      for (t_long j = 0; j < n_rows; ++j)\n        {\n          if (j != i)\n            {\n              cols_ind[cl] = j;\n              ++cl;\n            }\n        }\n    }\n  return 0;\n}\n/////////////////////////////////BS Register\n/////////////////////////////////Stuff//////////////////////////\n\n  BLUE_SKY_TYPE_STD_CREATE (bcsr_matrix_tools);\n  BLUE_SKY_TYPE_STD_COPY (bcsr_matrix_tools);\n\n  BLUE_SKY_TYPE_IMPL(bcsr_matrix_tools,  bcsr_matrix_tools_iface, \"bcsr_matrix_tools\", \"Tools for Block CSR Matrix class\", \"Tools realization of Block CSR Matricies\");\n}  // blue_sky namespace\n", "meta": {"hexsha": "c3990f379037114091367352a4fbd7dea54eb909", "size": 12168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bs_mtx/src/bcsr_matrix_tools.cpp", "max_stars_repo_name": "bs-eagle/bs-eagle", "max_stars_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-07-16T22:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T10:16:42.000Z", "max_issues_repo_path": "bs_mtx/src/bcsr_matrix_tools.cpp", "max_issues_repo_name": "bs-eagle/bs-eagle", "max_issues_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bs_mtx/src/bcsr_matrix_tools.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": 26.3947939262, "max_line_length": 167, "alphanum_fraction": 0.5059993425, "num_tokens": 3610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.043365798609362335, "lm_q1q2_score": 0.015273512139884822}}
{"text": "// This file is distributed under the MIT license.\n// See the LICENSE file for details.\n\n#include <common/config.h>\n\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <ostream>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/iostreams/device/mapped_file.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/utility/string_ref.hpp>\n#include <boost/assign.hpp>\n#include <boost/bimap.hpp>\n#include <boost/filesystem.hpp>\n\n#include <rapidjson/document.h>\n#include <rapidjson/filereadstream.h>\n#include <rapidjson/filewritestream.h>\n#include <rapidjson/prettywriter.h>\n\n#include <visionaray/math/constants.h>\n#include <visionaray/math/forward.h>\n#include <visionaray/math/unorm.h>\n#include <visionaray/math/vector.h>\n#include <visionaray/texture/texture.h>\n\n#include \"cfile.h\"\n#include \"model.h\"\n#include \"sg.h\"\n#include \"vsnray_loader.h\"\n\nusing namespace visionaray;\n\n\nnamespace data_file\n{\n\n//-------------------------------------------------------------------------------------------------\n// (included) data file meta data\n//\n\nstruct meta_data\n{\n    enum encoding_t\n    {\n        Ascii,\n        Binary\n    };\n\n    // VecN are binary compatible w/ visionaray::vecN\n    enum data_type_t\n    {\n        U8,\n        Float,\n        Vec2u8,\n        Vec2f,\n        Vec3u8,\n        Vec3f,\n        Vec4u8,\n        Vec4f,\n    };\n\n    static boost::bimap<data_type_t, std::string> data_type_map;\n\n    enum compression_t\n    {\n        Raw\n    };\n\n    std::string   path;\n    encoding_t    encoding    = Binary;\n    data_type_t   data_type   = U8;\n    int           num_items   = 0;\n    compression_t compression = Raw;\n    char          separator   = ' ';\n};\n\nboost::bimap<meta_data::data_type_t, std::string> meta_data::data_type_map\n    = boost::assign::list_of<typename boost::bimap<meta_data::data_type_t, std::string>::relation>\n        ( U8,     \"u8\" )\n        ( Float,  \"float\" )\n        ( Vec2u8, \"vec2u8\" )\n        ( Vec2f,  \"vec2f\" )\n        ( Vec3u8, \"vec3u8\" )\n        ( Vec3f,  \"vec3f\" )\n        ( Vec4u8, \"vec4u8\" )\n        ( Vec4f,  \"vec4f\" );\n\n} // data_file\n\n\n//-------------------------------------------------------------------------------------------------\n// Floating point number parser\n//\n\ntemplate <typename It, typename Vector>\nbool parse_floats(It first, It last, Vector& vec, char separator = ' ')\n{\n    namespace qi = boost::spirit::qi;\n\n    return qi::phrase_parse(\n            first,\n            last,\n            qi::float_ % *qi::char_(separator),\n            qi::ascii::space,\n            vec\n            );\n}\n\ntemplate <size_t N, typename Container>\nbool parse_as_vecN(data_file::meta_data md, Container& vecNs)\n{\n    boost::iostreams::mapped_file_source file(md.path);\n\n    if (md.data_type == data_file::meta_data::Float)\n    {\n        if (md.num_items % N != 0)\n        {\n            return false;\n        }\n\n        std::vector<float> floats;\n\n        if (md.encoding == data_file::meta_data::Ascii)\n        {\n            boost::string_ref text(file.data(), file.size());\n\n            parse_floats(text.cbegin(), text.cend(), floats, md.separator);\n\n            if (static_cast<int>(floats.size()) != md.num_items)\n            {\n                return false;\n            }\n        }\n        else // Binary\n        {\n            floats.resize(md.num_items);\n            std::copy(\n                file.data(),\n                file.data() + file.size(),\n                reinterpret_cast<char*>(floats.data())\n                );\n        }\n\n        vecNs.resize(md.num_items / N);\n        for (size_t i = 0; i < vecNs.size(); ++i)\n        {\n            for (size_t j = 0; j < N; ++j)\n            {\n                vecNs[i][j] = floats[i * N + j];\n            }\n        }\n    }\n    else if (md.data_type == data_file::meta_data::Vec2u8)\n    {\n        if (N != 2)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (md.encoding == data_file::meta_data::Ascii)\n        {\n            // Not implemented yet\n            return false;\n        }\n        else // Binary\n        {\n            vecNs.resize(md.num_items);\n            std::copy(\n                file.data(),\n                file.data() + file.size(),\n                reinterpret_cast<char*>(vecNs.data())\n                );\n        }\n    }\n    else if (md.data_type == data_file::meta_data::Vec2f)\n    {\n        if (N != 2)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (md.encoding == data_file::meta_data::Ascii)\n        {\n            // Not implemented yet\n            return false;\n        }\n        else // Binary\n        {\n            vecNs.resize(md.num_items);\n            std::copy(\n                file.data(),\n                file.data() + file.size(),\n                reinterpret_cast<char*>(vecNs.data())\n                );\n        }\n    }\n    else if (md.data_type == data_file::meta_data::Vec3u8)\n    {\n        if (N != 3)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (md.encoding == data_file::meta_data::Ascii)\n        {\n            // Not implemented yet\n            return false;\n        }\n        else // Binary\n        {\n            vecNs.resize(md.num_items);\n            std::copy(\n                file.data(),\n                file.data() + file.size(),\n                reinterpret_cast<char*>(vecNs.data())\n                );\n        }\n    }\n    else if (md.data_type == data_file::meta_data::Vec3f)\n    {\n        if (N != 3)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (md.encoding == data_file::meta_data::Ascii)\n        {\n            // Not implemented yet\n            return false;\n        }\n        else // Binary\n        {\n            vecNs.resize(md.num_items);\n            std::copy(\n                file.data(),\n                file.data() + file.size(),\n                reinterpret_cast<char*>(vecNs.data())\n                );\n        }\n    }\n    else if (md.data_type == data_file::meta_data::Vec4u8)\n    {\n        if (N != 4)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (md.encoding == data_file::meta_data::Ascii)\n        {\n            // Not implemented yet\n            return false;\n        }\n        else // Binary\n        {\n            vecNs.resize(md.num_items);\n            std::copy(\n                file.data(),\n                file.data() + file.size(),\n                reinterpret_cast<char*>(vecNs.data())\n                );\n        }\n    }\n    else if (md.data_type == data_file::meta_data::Vec4f)\n    {\n        if (N != 4)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (md.encoding == data_file::meta_data::Ascii)\n        {\n            // Not implemented yet\n            return false;\n        }\n        else // Binary\n        {\n            vecNs.resize(md.num_items);\n            std::copy(\n                file.data(),\n                file.data() + file.size(),\n                reinterpret_cast<char*>(vecNs.data())\n                );\n        }\n    }\n\n    return true;\n}\n\ntemplate <typename Container>\nbool parse_as_vec2f(data_file::meta_data md, Container& vec2fs)\n{\n    return parse_as_vecN<2>(md, vec2fs);\n}\n\ntemplate <typename Container>\nbool parse_as_vec3f(data_file::meta_data md, Container& vec3fs)\n{\n    return parse_as_vecN<3>(md, vec3fs);\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Parse tiny objects from json object\n//\n\ntemplate <typename Object>\nvoid parse_optional(float& f, Object const& obj, char const* member)\n{\n    if (obj.HasMember(member))\n    {\n        auto const& val = obj[member];\n\n        if (!val.IsFloat())\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        f = val.GetFloat();\n    }\n}\n\ntemplate <size_t N, typename Object>\nvoid parse_optional(vector<N, float>& v, Object const& obj, char const* member)\n{\n    if (obj.HasMember(member))\n    {\n        auto const& val = obj[member];\n\n        if (!val.IsArray())\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (val.Capacity() != N)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        for (size_t i = 0; i < N; ++i)\n        {\n            v[i] = val[i].GetFloat();\n        }\n    }\n}\n\ntemplate <typename Object>\nvoid parse_optional(recti& r, Object const& obj, char const* member)\n{\n    if (obj.HasMember(member))\n    {\n        auto const& val = obj[member];\n\n        if (!val.IsArray())\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        if (val.Capacity() != 4)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        for (size_t i = 0; i < 4; ++i)\n        {\n            r.data()[i] = val[i].GetFloat();\n        }\n    }\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// .vsnray parser\n//\n\nclass vsnray_parser\n{\npublic:\n\n    vsnray_parser(std::string filename)\n        : filename_(filename)\n    {\n    }\n\n    void parse_children(std::shared_ptr<sg::node> parent, rapidjson::Value const& entries);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_node(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_camera(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_include(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_point_light(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_spot_light(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_reference(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_transform(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_surface_properties(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_triangle_mesh(Object const& obj);\n\n    template <typename Object>\n    std::shared_ptr<sg::node> parse_indexed_triangle_mesh(Object const& obj);\n\n\n    template <typename Object>\n    data_file::meta_data parse_file_meta_data(Object const& obj);\n\nprivate:\n\n    std::string filename_;\n\n};\n\n\n//-------------------------------------------------------------------------------------------------\n// Parse nodes\n//\n\nvoid vsnray_parser::parse_children(std::shared_ptr<sg::node> parent, rapidjson::Value const& entries)\n{\n    if (!entries.IsArray())\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    parent->children().resize(entries.Capacity());\n\n    size_t i = 0;\n    for (auto const& c : entries.GetArray())\n    {\n        auto const& obj = c.GetObject();\n\n        parent->children().at(i++) = parse_node(obj);\n    }\n\n    if (i != entries.Capacity())\n    {\n        throw std::runtime_error(\"\");\n    }\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_node(Object const& obj)\n{\n    std::shared_ptr<sg::node> result = nullptr;\n\n    if (obj.HasMember(\"type\"))\n    {\n        // Parse individual node types\n        auto const& type_string = obj[\"type\"];\n        if (strncmp(type_string.GetString(), \"node\", 4) == 0)\n        {\n            // Empty node, (may still contain children, e.g. root)\n            result = std::make_shared<sg::node>();\n        }\n        else if (strncmp(type_string.GetString(), \"camera\", 6) == 0)\n        {\n            result = parse_camera(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"include\", 6) == 0)\n        {\n            result = parse_include(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"point_light\", 11) == 0)\n        {\n            result = parse_point_light(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"spot_light\", 10) == 0)\n        {\n            result = parse_spot_light(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"reference\", 9) == 0)\n        {\n            result = parse_reference(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"transform\", 9) == 0)\n        {\n            result = parse_transform(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"surface_properties\", 18) == 0)\n        {\n            result = parse_surface_properties(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"triangle_mesh\", 13) == 0)\n        {\n            result = parse_triangle_mesh(obj);\n        }\n        else if (strncmp(type_string.GetString(), \"indexed_triangle_mesh\", 21) == 0)\n        {\n            result = parse_indexed_triangle_mesh(obj);\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        // Parse common node properties\n        if (obj.HasMember(\"name\"))\n        {\n            assert(result != nullptr);\n\n            rapidjson::Value const& name = obj[\"name\"];\n            result->name() = name.GetString();\n        }\n\n        if (obj.HasMember(\"children\"))\n        {\n            assert(result != nullptr);\n\n            rapidjson::Value const& children = obj[\"children\"];\n            parse_children(result, children);\n        }\n    }\n    else\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    return result;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_camera(Object const& obj)\n{\n    auto cam = std::make_shared<sg::camera>();\n\n    vec3 eye(0.0f);\n    parse_optional(eye, obj, \"eye\");\n\n    vec3 center(0.0f);\n    parse_optional(center, obj, \"center\");\n\n    vec3 up(0.0f);\n    parse_optional(up, obj, \"up\");\n\n    float fovy = 45.0f;\n    parse_optional(fovy, obj, \"fovy\");\n\n    float znear = 0.001f;\n    parse_optional(znear, obj, \"znear\");\n\n    float zfar = 1000.0f;\n    parse_optional(zfar, obj, \"zfar\");\n\n    recti viewport(0, 0, 0, 0);\n    parse_optional(viewport, obj, \"viewport\");\n\n    float lens_radius = 0.1f;\n    parse_optional(lens_radius, obj, \"lens_radius\");\n\n    float focal_distance = 10.0f;\n    parse_optional(focal_distance, obj, \"focal_distance\");\n\n    float aspect = viewport.w > 0 && viewport.h > 0\n                 ? viewport.w / static_cast<float>(viewport.h)\n                 : 1;\n\n    cam->perspective(fovy * constants::degrees_to_radians<float>(), aspect, znear, zfar);\n    if (viewport.w > 0 && viewport.h > 0)\n    {\n        cam->set_viewport(viewport);\n    }\n    cam->set_lens_radius(lens_radius);\n    cam->set_focal_distance(focal_distance);\n    cam->look_at(eye, center, up);\n\n    return cam;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_include(Object const& obj)\n{\n    auto inc = std::make_shared<sg::node>();\n\n    if (obj.HasMember(\"path\"))\n    {\n        std::string path_string(obj[\"path\"].GetString());\n\n        boost::filesystem::path p(path_string);\n\n        if (!p.is_absolute())\n        {\n            // Extract base path\n            boost::filesystem::path bp(filename_);\n            bp = bp.parent_path();\n\n            // Append path to base path\n            p = bp / p;\n\n            path_string = p.string();\n        }\n\n        model mod;\n        if (mod.load(path_string))\n        {\n            if (mod.scene_graph == nullptr)\n            {\n                std::unordered_map<std::string, std::shared_ptr<sg::texture2d<vector<4, unorm<8>>>>> texture_map;\n\n                for (auto it = mod.texture_map.begin(); it != mod.texture_map.end(); ++it)\n                {\n                    auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();\n                    tex->name() = it->first;\n                    tex->resize(it->second.width(), it->second.height());\n                    tex->reset(it->second.data());\n                    tex->set_filter_mode(it->second.get_filter_mode());\n                    tex->set_address_mode(it->second.get_address_mode());\n\n                    texture_map.insert(std::make_pair(it->first, tex));\n                }\n\n                if (mod.primitives.size() > 0)\n                {\n                    // Vertices (disassemble triangles..)\n                    for (auto tri : mod.primitives)\n                    {\n                        if (tri.geom_id >= inc->children().size())\n                        {\n                            auto props = std::make_shared<sg::surface_properties>();\n\n                            // Add material\n                            auto obj = std::make_shared<sg::obj_material>();\n                            obj->ca = mod.materials[tri.geom_id].ca;\n                            obj->cd = mod.materials[tri.geom_id].cd;\n                            obj->cs = mod.materials[tri.geom_id].cs;\n                            obj->ce = mod.materials[tri.geom_id].ce;\n                            obj->cr = mod.materials[tri.geom_id].cr;\n                            obj->ior = mod.materials[tri.geom_id].ior;\n                            obj->absorption = mod.materials[tri.geom_id].absorption;\n                            obj->transmission = mod.materials[tri.geom_id].transmission;\n                            obj->specular_exp = mod.materials[tri.geom_id].specular_exp;\n                            obj->illum = mod.materials[tri.geom_id].illum;\n                            props->material() = obj;\n\n                            bool insert_dummy = false;\n\n                            if (tri.geom_id < mod.textures.size())\n                            {\n                                // Find texture in texture_map\n                                bool found = false;\n                                for (auto it = mod.texture_map.begin(); it != mod.texture_map.end(); ++it)\n                                {\n                                    auto ref = texture_ref<vector<4, unorm<8>>, 2>(it->second);\n\n                                    if (ref.data() == mod.textures[tri.geom_id].data())\n                                    {\n                                        std::string name = it->first;\n                                        // Find in local texture map\n                                        auto res = texture_map.find(name);\n                                        if (res != texture_map.end())\n                                        {\n                                            props->add_texture(res->second);\n                                            found = true;\n                                            break;\n                                        }\n                                    }\n                                }\n\n                                if (!found)\n                                {\n                                    insert_dummy = true;\n                                }\n                            }\n                            else\n                            {\n                                insert_dummy = true;\n                            }\n\n                            if (insert_dummy)\n                            {\n                                // Add a dummy texture\n                                vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);\n                                auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();\n                                tex->resize(1, 1);\n                                tex->set_address_mode(Wrap);\n                                tex->set_filter_mode(Nearest);\n                                tex->reset(&dummy_texel);\n                                props->add_texture(tex);\n                            }\n\n                            // Add to scene graph\n                            props->add_child(std::make_shared<sg::triangle_mesh>());\n                            inc->add_child(props);\n                        }\n\n                        auto mesh = std::dynamic_pointer_cast<sg::triangle_mesh>(\n                                inc->children()[tri.geom_id]->children()[0]\n                                );\n\n                        vec3 verts[3] = {\n                            tri.v1,\n                            tri.v1 + tri.e1,\n                            tri.v1 + tri.e2\n                            };\n                        mesh->vertices.insert(mesh->vertices.end(), verts, verts + 3);\n\n                        if (mod.shading_normals.size() > tri.prim_id * 3 + 3)\n                        {\n                            for (int i = 0; i < 3; ++i)\n                            {\n                                mesh->normals.push_back(mod.shading_normals[tri.prim_id * 3 + i]);\n                            }\n                        }\n                        else\n                        {\n                            for (int i = 0; i < 3; ++i)\n                            {\n                                mesh->normals.push_back(normalize(cross(tri.e1, tri.e2)));\n                            }\n                        }\n\n                        if (mod.tex_coords.size() >= tri.prim_id * 3 + 3)\n                        {\n                            for (int i = 0; i < 3; ++i)\n                            {\n                                mesh->tex_coords.push_back(mod.tex_coords[tri.prim_id * 3 + i]);\n                            }\n                        }\n                        else\n                        {\n                            for (int i = 0; i < 3; ++i)\n                            {\n                                mesh->tex_coords.push_back(vec2(0.0f, 0.0f));\n                            }\n                        }\n\n                        if (mod.colors.size() >= tri.prim_id * 3 + 3)\n                        {\n                            for (int i = 0; i < 3; ++i)\n                            {\n                                mesh->colors.push_back(vector<3, unorm<8>>(mod.colors[tri.prim_id * 3 + i]));\n                            }\n                        }\n                        else\n                        {\n                            for (int i = 0; i < 3; ++i)\n                            {\n                                mesh->colors.push_back(vector<3, unorm<8>>(1.0f, 1.0f, 1.0f));\n                            }\n                        }\n                    }\n                }\n                else\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n            else\n            {\n                // TODO: don't allow circular references..\n                inc = mod.scene_graph;\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n    else\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    return inc;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_point_light(Object const& obj)\n{\n    auto light = std::make_shared<sg::point_light>();\n\n    vec3 cl(1.0f);\n    parse_optional(cl, obj, \"cl\");\n\n    float kl = 1.0f;\n    parse_optional(kl, obj, \"kl\");\n\n    vec3 position(0.0f);\n    parse_optional(position, obj, \"position\");\n\n    float constant_attenuation = 1.0f;\n    parse_optional(constant_attenuation, obj, \"constant_attenuation\");\n\n    float linear_attenuation = 0.0f;\n    parse_optional(linear_attenuation, obj, \"linear_attenuation\");\n\n    float quadratic_attenuation = 0.0f;\n    parse_optional(quadratic_attenuation, obj, \"quadratic_attenuation\");\n\n    light->set_cl(cl);\n    light->set_kl(kl);\n    light->set_position(position);\n    light->set_constant_attenuation(constant_attenuation);\n    light->set_linear_attenuation(linear_attenuation);\n    light->set_quadratic_attenuation(quadratic_attenuation);\n\n    return light;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_spot_light(Object const& obj)\n{\n    auto light = std::make_shared<sg::spot_light>();\n\n    vec3 cl(1.0f);\n    parse_optional(cl, obj, \"cl\");\n\n    float kl = 1.0f;\n    parse_optional(kl, obj, \"kl\");\n\n    vec3 position(0.0f);\n    parse_optional(position, obj, \"position\");\n\n    vec3 spot_direction(0.0f, 0.0f, -1.0f);\n    parse_optional(spot_direction, obj, \"spot_direction\");\n    assert(length(spot_direction) == 1.0f);\n\n    float spot_cutoff = 180.0f * constants::degrees_to_radians<float>();\n    parse_optional(spot_cutoff, obj, \"spot_cutoff\");\n\n    float spot_exponent = 0.0f;\n    parse_optional(spot_exponent, obj, \"spot_exponent\");\n\n    float constant_attenuation = 1.0f;\n    parse_optional(constant_attenuation, obj, \"constant_attenuation\");\n\n    float linear_attenuation = 0.0f;\n    parse_optional(linear_attenuation, obj, \"linear_attenuation\");\n\n    float quadratic_attenuation = 0.0f;\n    parse_optional(quadratic_attenuation, obj, \"quadratic_attenuation\");\n\n    light->set_cl(cl);\n    light->set_kl(kl);\n    light->set_position(position);\n    light->set_spot_direction(spot_direction);\n    light->set_spot_cutoff(spot_cutoff);\n    light->set_spot_exponent(spot_exponent);\n    light->set_constant_attenuation(constant_attenuation);\n    light->set_linear_attenuation(linear_attenuation);\n    light->set_quadratic_attenuation(quadratic_attenuation);\n\n    return light;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_reference(Object const& obj)\n{\n    return std::make_shared<sg::node>();\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_transform(Object const& obj)\n{\n    auto transform = std::make_shared<sg::transform>();\n\n    if (obj.HasMember(\"matrix\"))\n    {\n        auto const& mat = obj[\"matrix\"];\n\n        if (mat.Capacity() != 16)\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        for (rapidjson::SizeType i = 0; i < mat.Capacity(); ++i)\n        {\n            transform->matrix().data()[i] = mat[i].GetFloat();\n        }\n    }\n\n    return transform;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_surface_properties(Object const& obj)\n{\n    auto props = std::make_shared<sg::surface_properties>();\n\n    if (obj.HasMember(\"material\"))\n    {\n        auto const& mat = obj[\"material\"];\n\n        if (mat.HasMember(\"type\"))\n        {\n            auto const& type_string = mat[\"type\"];\n            if (strncmp(type_string.GetString(), \"obj\", 3) == 0)\n            {\n                auto obj = std::make_shared<sg::obj_material>();\n\n                parse_optional(obj->ca, mat, \"ca\");\n                parse_optional(obj->cd, mat, \"cd\");\n                parse_optional(obj->cs, mat, \"cs\");\n                parse_optional(obj->ce, mat, \"ce\");\n\n                props->material() = obj;\n            }\n            else if (strncmp(type_string.GetString(), \"glass\", 5) == 0)\n            {\n                auto glass = std::make_shared<sg::glass_material>();\n\n                parse_optional(glass->ct, mat, \"ct\");\n                parse_optional(glass->cr, mat, \"cr\");\n                parse_optional(glass->ior, mat, \"ior\");\n\n                props->material() = glass;\n            }\n            else if (strncmp(type_string.GetString(), \"disney\", 6) == 0)\n            {\n                auto disney = std::make_shared<sg::disney_material>();\n\n                parse_optional(disney->base_color, mat, \"base_color\");\n                parse_optional(disney->spec_trans, mat, \"spec_trans\");\n                parse_optional(disney->sheen, mat, \"sheen\");\n                parse_optional(disney->sheen_tint, mat, \"sheen_tint\");\n                parse_optional(disney->ior, mat, \"ior\");\n                parse_optional(disney->refractive, mat, \"refractive\");\n                parse_optional(disney->roughness, mat, \"roughness\");\n\n                props->material() = disney;\n            }\n            else\n            {\n                throw std::runtime_error(\"\");\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n    else\n    {\n        // Set default material (wavefront obj)\n        auto obj = std::make_shared<sg::obj_material>();\n        props->material() = obj;\n    }\n\n    if (obj.HasMember(\"diffuse\"))\n    {\n        // TODO: load from file\n#if 1\n        vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);\n        auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();\n        tex->resize(1, 1);\n        tex->set_address_mode(Wrap);\n        tex->set_filter_mode(Nearest);\n        tex->reset(&dummy_texel);\n\n        props->add_texture(tex);\n#endif\n    }\n    else\n    {\n        // Set a dummy texture\n        vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);\n        auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>();\n        tex->resize(1, 1);\n        tex->set_address_mode(Wrap);\n        tex->set_filter_mode(Nearest);\n        tex->reset(&dummy_texel);\n\n        props->add_texture(tex);\n    }\n\n    return props;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_triangle_mesh(Object const& obj)\n{\n    auto mesh = std::make_shared<sg::triangle_mesh>();\n\n    if (obj.HasMember(\"vertices\"))\n    {\n        auto const& verts = obj[\"vertices\"];\n\n        if (verts.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < verts.Capacity(); i += 3)\n            {\n                mesh->vertices.emplace_back(\n                    verts[i].GetFloat(),\n                    verts[i + 1].GetFloat(),\n                    verts[i + 2].GetFloat()\n                    );\n            }\n        }\n        else if (verts.IsObject())\n        {\n            auto const& type_string = verts[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(verts);\n\n                if (!parse_as_vec3f(md, mesh->vertices))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n\n    if (obj.HasMember(\"normals\"))\n    {\n        auto const& normals = obj[\"normals\"];\n\n        if (normals.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < normals.Capacity(); i += 3)\n            {\n                mesh->normals.emplace_back(\n                    normals[i].GetFloat(),\n                    normals[i + 1].GetFloat(),\n                    normals[i + 2].GetFloat()\n                    );\n            }\n        }\n        else if (normals.IsObject())\n        {\n            auto const& type_string = normals[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(normals);\n\n                if (!parse_as_vec3f(md, mesh->normals))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n    else\n    {\n        for (size_t i = 0; i < mesh->vertices.size(); i += 3)\n        {\n            vec3 v1 = mesh->vertices[i];\n            vec3 v2 = mesh->vertices[i + 1];\n            vec3 v3 = mesh->vertices[i + 2];\n\n            vec3 e1 = v2 - v1;\n            vec3 e2 = v3 - v1;\n\n            vec3 gn = normalize(cross(e1, e2));\n\n            mesh->normals.emplace_back(gn);\n            mesh->normals.emplace_back(gn);\n            mesh->normals.emplace_back(gn);\n        }\n    }\n\n    if (obj.HasMember(\"tex_coords\"))\n    {\n        auto const& tex_coords = obj[\"tex_coords\"];\n\n        if (tex_coords.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < tex_coords.Capacity(); i += 2)\n            {\n                mesh->tex_coords.emplace_back(\n                    tex_coords[i].GetFloat(),\n                    tex_coords[i + 1].GetFloat()\n                    );\n            }\n        }\n        else if (tex_coords.IsObject())\n        {\n            auto const& type_string = tex_coords[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(tex_coords);\n\n                if (!parse_as_vec2f(md, mesh->tex_coords))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n    else\n    {\n        for (size_t i = 0; i < mesh->vertices.size(); i += 3)\n        {\n            mesh->tex_coords.emplace_back(0.0f, 0.0f);\n            mesh->tex_coords.emplace_back(0.0f, 0.0f);\n            mesh->tex_coords.emplace_back(0.0f, 0.0f);\n        }\n    }\n\n    if (obj.HasMember(\"colors\"))\n    {\n        auto const& colors = obj[\"colors\"];\n\n        if (colors.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < colors.Capacity(); i += 3)\n            {\n                mesh->colors.emplace_back(\n                    colors[i].GetFloat(),\n                    colors[i + 1].GetFloat(),\n                    colors[i + 2].GetFloat()\n                    );\n            }\n        }\n        else if (colors.IsObject())\n        {\n            auto const& type_string = colors[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(colors);\n\n                if (!parse_as_vec3f(md, mesh->colors))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n    else\n    {\n        for (size_t i = 0; i < mesh->vertices.size(); i += 3)\n        {\n            mesh->colors.emplace_back(1.0f, 1.0f, 1.0f);\n            mesh->colors.emplace_back(1.0f, 1.0f, 1.0f);\n            mesh->colors.emplace_back(1.0f, 1.0f, 1.0f);\n        }\n    }\n\n    return mesh;\n}\n\ntemplate <typename Object>\nstd::shared_ptr<sg::node> vsnray_parser::parse_indexed_triangle_mesh(Object const& obj)\n{\n    auto mesh = std::make_shared<sg::indexed_triangle_mesh>();\n\n    if (obj.HasMember(\"vertex_indices\"))\n    {\n        auto const& vertex_indices = obj[\"vertex_indices\"];\n\n        for (auto const& item : vertex_indices.GetArray())\n        {\n            mesh->vertex_indices.push_back(item.GetInt());\n        }\n    }\n\n    if (obj.HasMember(\"normal_indices\"))\n    {\n        auto const& normal_indices = obj[\"normal_indices\"];\n\n        for (auto const& item : normal_indices.GetArray())\n        {\n            mesh->normal_indices.push_back(item.GetInt());\n        }\n    }\n\n    if (obj.HasMember(\"tex_coord_indices\"))\n    {\n        auto const& tex_coord_indices = obj[\"tex_coord_indices\"];\n\n        for (auto const& item : tex_coord_indices.GetArray())\n        {\n            mesh->tex_coord_indices.push_back(item.GetInt());\n        }\n    }\n\n    if (obj.HasMember(\"color_indices\"))\n    {\n        auto const& color_indices = obj[\"color_indices\"];\n\n        for (auto const& item : color_indices.GetArray())\n        {\n            mesh->color_indices.push_back(item.GetInt());\n        }\n    }\n\n    if (obj.HasMember(\"vertices\"))\n    {\n        mesh->vertices = std::make_shared<aligned_vector<vec3>>();\n\n        auto const& verts = obj[\"vertices\"];\n\n        if (verts.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < verts.Capacity(); i += 3)\n            {\n                mesh->vertices->emplace_back(\n                    verts[i].GetFloat(),\n                    verts[i + 1].GetFloat(),\n                    verts[i + 2].GetFloat()\n                    );\n            }\n        }\n        else if (verts.IsObject())\n        {\n            auto const& type_string = verts[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(verts);\n\n                if (!parse_as_vec3f(md, *mesh->vertices))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n    }\n\n    if (obj.HasMember(\"normals\"))\n    {\n        mesh->normals = std::make_shared<aligned_vector<vec3>>();\n\n        auto const& normals = obj[\"normals\"];\n\n        if (normals.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < normals.Capacity(); i += 3)\n            {\n                mesh->normals->emplace_back(\n                    normals[i].GetFloat(),\n                    normals[i + 1].GetFloat(),\n                    normals[i + 2].GetFloat()\n                    );\n            }\n        }\n        else if (normals.IsObject())\n        {\n            auto const& type_string = normals[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(normals);\n\n                if (!parse_as_vec3f(md, *mesh->normals))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n\n    if (obj.HasMember(\"tex_coords\"))\n    {\n        mesh->tex_coords = std::make_shared<aligned_vector<vec2>>();\n\n        auto const& tex_coords = obj[\"tex_coords\"];\n\n        if (tex_coords.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < tex_coords.Capacity(); i += 2)\n            {\n                mesh->tex_coords->emplace_back(\n                    tex_coords[i].GetFloat(),\n                    tex_coords[i + 1].GetFloat()\n                    );\n            }\n        }\n        else if (tex_coords.IsObject())\n        {\n            auto const& type_string = tex_coords[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(tex_coords);\n\n                if (!parse_as_vec2f(md, *mesh->tex_coords))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n\n    if (obj.HasMember(\"colors\"))\n    {\n        mesh->colors = std::make_shared<aligned_vector<vector<3, unorm<8>>>>();\n\n        auto const& colors = obj[\"colors\"];\n\n        if (colors.IsArray())\n        {\n            for (rapidjson::SizeType i = 0; i < colors.Capacity(); i += 3)\n            {\n                mesh->colors->emplace_back(\n                    colors[i].GetFloat(),\n                    colors[i + 1].GetFloat(),\n                    colors[i + 2].GetFloat()\n                    );\n            }\n        }\n        else if (colors.IsObject())\n        {\n            auto const& type_string = colors[\"type\"];\n            if (strncmp(type_string.GetString(), \"file\", 4) == 0)\n            {\n                auto md = parse_file_meta_data(colors);\n\n                if (!parse_as_vec3f(md, *mesh->colors))\n                {\n                    throw std::runtime_error(\"\");\n                }\n            }\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n\n    return mesh;\n}\n\ntemplate <typename Object>\ndata_file::meta_data vsnray_parser::parse_file_meta_data(Object const& obj)\n{\n    data_file::meta_data result;\n\n    if (obj.HasMember(\"path\"))\n    {\n        result.path = obj[\"path\"].GetString();\n    }\n    else\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    if (obj.HasMember(\"encoding\"))\n    {\n        std::string encoding = obj[\"encoding\"].GetString();\n        if (encoding == \"ascii\")\n        {\n            result.encoding = data_file::meta_data::Ascii;\n        }\n        else if (encoding == \"binary\")\n        {\n            result.encoding = data_file::meta_data::Binary;\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n    else\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    if (obj.HasMember(\"data_type\"))\n    {\n        std::string data_type = obj[\"data_type\"].GetString();\n\n        auto& data_type_map = data_file::meta_data::data_type_map;\n\n        auto it = data_type_map.right.find(data_type);\n\n        if (it != data_type_map.right.end())\n        {\n            result.data_type = it->second;\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n    else\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    if (obj.HasMember(\"num_items\"))\n    {\n        result.num_items = obj[\"num_items\"].GetInt();\n    }\n    else\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    if (obj.HasMember(\"compression\"))\n    {\n        std::string compression = obj[\"compression\"].GetString();\n        if (compression == \"none\" || compression == \"raw\")\n        {\n            result.compression = data_file::meta_data::Raw;\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n\n    if (obj.HasMember(\"separator\"))\n    {\n        std::string separator = obj[\"separator\"].GetString();\n        result.separator = separator[0];\n    }\n\n    return result;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// .vsnray writer\n//\n\nclass vsnray_writer\n{\npublic:\n\n    vsnray_writer(rapidjson::Document& doc, std::string filename)\n        : document_(doc)\n        , filename_(filename)\n    {\n    }\n\n    template <typename Object>\n    void write_node(Object obj, std::shared_ptr<sg::node> const& n);\n\n    template <typename Object>\n    void write_transform(Object obj, std::shared_ptr<sg::transform> const& tr);\n\n    template <typename Object>\n    void write_surface_properties(Object obj, std::shared_ptr<sg::surface_properties> const& sp);\n\n    template <typename Object>\n    void write_triangle_mesh(Object obj, std::shared_ptr<sg::triangle_mesh> const& tm);\n\n    template <typename Object>\n    void write_indexed_triangle_mesh(Object obj, std::shared_ptr<sg::indexed_triangle_mesh> const& tm);\n\n\n    template <typename Object, typename Container>\n    void write_data_file(Object obj, data_file::meta_data md, Container const& cont);\n\nprivate:\n\n    std::string make_inline_filename(std::string node_name, std::string suffix);\n\n    rapidjson::Document& document_;\n\n    std::string filename_;\n\n};\n\n//-------------------------------------------------------------------------------------------------\n// Write nodes\n//\n\ntemplate <typename Object>\nvoid vsnray_writer::write_node(Object obj, std::shared_ptr<sg::node> const& n)\n{\n    if (n == nullptr)\n    {\n        return;\n    }\n\n    auto& allocator = document_.GetAllocator();\n\n    rapidjson::Value name(n->name().c_str(), allocator);\n    obj.AddMember(\n        rapidjson::StringRef(\"name\"),\n        name,\n        allocator\n        );\n\n    if (auto tr = std::dynamic_pointer_cast<sg::transform>(n))\n    {\n        obj.AddMember(\n            rapidjson::StringRef(\"type\"),\n            rapidjson::StringRef(\"transform\"),\n            allocator\n            );\n\n        write_transform(obj, tr);\n    }\n    else if (auto sp = std::dynamic_pointer_cast<sg::surface_properties>(n))\n    {\n        obj.AddMember(\n            rapidjson::StringRef(\"type\"),\n            rapidjson::StringRef(\"surface_properties\"),\n            allocator\n            );\n\n        write_surface_properties(obj, sp);\n    }\n    else if (auto tm = std::dynamic_pointer_cast<sg::triangle_mesh>(n))\n    {\n        if (tm->flags() == 0)\n        {\n            obj.AddMember(\n                rapidjson::StringRef(\"type\"),\n                rapidjson::StringRef(\"triangle_mesh\"),\n                allocator\n                );\n\n            write_triangle_mesh(obj, tm);\n\n            tm->flags() = 1;\n        }\n    }\n    else if (auto itm = std::dynamic_pointer_cast<sg::indexed_triangle_mesh>(n))\n    {\n        obj.AddMember(\n            rapidjson::StringRef(\"type\"),\n            rapidjson::StringRef(\"indexed_triangle_mesh\"),\n            allocator\n            );\n\n        write_indexed_triangle_mesh(obj, itm);\n    }\n    else\n    {\n        obj.AddMember(\n            rapidjson::StringRef(\"type\"),\n            rapidjson::StringRef(\"node\"),\n            allocator\n            );\n    }\n\n    if (n->children().size() > 0)\n    {\n        rapidjson::Value arr(rapidjson::kArrayType);\n\n        for (auto& c : n->children())\n        {\n            rapidjson::Value child;\n            child.SetObject();\n            write_node(child.GetObject(), c);\n\n            arr.PushBack(child, allocator);\n        }\n\n        obj.AddMember(\"children\", arr, allocator);\n    }\n}\n\ntemplate <typename Object>\nvoid vsnray_writer::write_transform(Object obj, std::shared_ptr<sg::transform> const& tr)\n{\n    auto& allocator = document_.GetAllocator();\n\n    rapidjson::Value mat(rapidjson::kArrayType);\n\n    for (int i = 0; i < 16; ++i)\n    {\n        rapidjson::Value val;\n        val.SetDouble(tr->matrix().data()[i]);\n        mat.PushBack(val, allocator);\n    }\n\n    obj.AddMember(\"matrix\", mat, allocator);\n}\n\ntemplate <typename Object>\nvoid vsnray_writer::write_surface_properties(Object obj, std::shared_ptr<sg::surface_properties> const& sp)\n{\n    auto& allocator = document_.GetAllocator();\n\n    if (sp->material() != nullptr)\n    {\n        rapidjson::Value name(sp->material()->name().c_str(), allocator);\n        obj.AddMember(\n            rapidjson::StringRef(\"name\"),\n            name,\n            allocator\n            );\n\n        rapidjson::Value jmat;\n        jmat.SetObject();\n\n        if (auto mat = std::dynamic_pointer_cast<sg::obj_material>(sp->material()))\n        {\n            jmat.AddMember(\n                rapidjson::StringRef(\"type\"),\n                rapidjson::StringRef(\"obj\"),\n                allocator\n                );\n\n            rapidjson::Value ca(rapidjson::kArrayType);\n            rapidjson::Value cd(rapidjson::kArrayType);\n            rapidjson::Value cs(rapidjson::kArrayType);\n            rapidjson::Value ce(rapidjson::kArrayType);\n\n            for (int i = 0; i < 3; ++i)\n            {\n                ca.PushBack(rapidjson::Value().SetFloat(mat->ca[i]), allocator);\n                cd.PushBack(rapidjson::Value().SetFloat(mat->cd[i]), allocator);\n                cs.PushBack(rapidjson::Value().SetFloat(mat->cs[i]), allocator);\n                ce.PushBack(rapidjson::Value().SetFloat(mat->ce[i]), allocator);\n            }\n\n            jmat.AddMember(rapidjson::StringRef(\"ca\"), ca, allocator);\n            jmat.AddMember(rapidjson::StringRef(\"cd\"), cd, allocator);\n            jmat.AddMember(rapidjson::StringRef(\"cs\"), cs, allocator);\n            jmat.AddMember(rapidjson::StringRef(\"ce\"), ce, allocator);\n        }\n        else if (auto mat = std::dynamic_pointer_cast<sg::glass_material>(sp->material()))\n        {\n            jmat.AddMember(\n                rapidjson::StringRef(\"type\"),\n                rapidjson::StringRef(\"glass\"),\n                allocator\n                );\n\n            rapidjson::Value ct(rapidjson::kArrayType);\n            rapidjson::Value cr(rapidjson::kArrayType);\n            rapidjson::Value ior(rapidjson::kArrayType);\n\n            for (int i = 0; i < 3; ++i)\n            {\n                ct.PushBack(rapidjson::Value().SetFloat(mat->ct[i]), allocator);\n                cr.PushBack(rapidjson::Value().SetFloat(mat->cr[i]), allocator);\n                ior.PushBack(rapidjson::Value().SetFloat(mat->ior[i]), allocator);\n            }\n\n            jmat.AddMember(rapidjson::StringRef(\"ct\"), ct, allocator);\n            jmat.AddMember(rapidjson::StringRef(\"cr\"), cr, allocator);\n            jmat.AddMember(rapidjson::StringRef(\"ior\"), ior, allocator);\n        }\n        else if (auto mat = std::dynamic_pointer_cast<sg::disney_material>(sp->material()))\n        {\n            jmat.AddMember(\n                rapidjson::StringRef(\"type\"),\n                rapidjson::StringRef(\"disney\"),\n                allocator\n                );\n\n            rapidjson::Value base_color(rapidjson::kArrayType);\n\n            for (int i = 0; i < 4; ++i)\n            {\n                base_color.PushBack(rapidjson::Value().SetFloat(mat->base_color[i]), allocator);\n            }\n\n            jmat.AddMember(rapidjson::StringRef(\"base_color\"), base_color, allocator);\n            jmat.AddMember(\n                rapidjson::StringRef(\"spec_trans\"),\n                rapidjson::Value().SetFloat(mat->spec_trans),\n                allocator\n                );\n            jmat.AddMember(\n                rapidjson::StringRef(\"sheen\"),\n                rapidjson::Value().SetFloat(mat->sheen),\n                allocator\n                );\n            jmat.AddMember(\n                rapidjson::StringRef(\"sheen_tint\"),\n                rapidjson::Value().SetFloat(mat->sheen_tint),\n                allocator\n                );\n            jmat.AddMember(\n                rapidjson::StringRef(\"ior\"),\n                rapidjson::Value().SetFloat(mat->ior),\n                allocator\n                );\n            jmat.AddMember(\n                rapidjson::StringRef(\"refractive\"),\n                rapidjson::Value().SetFloat(mat->refractive),\n                allocator\n                );\n            jmat.AddMember(\n                rapidjson::StringRef(\"roughness\"),\n                rapidjson::Value().SetFloat(mat->roughness),\n                allocator\n                );\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n\n        obj.AddMember(\n            rapidjson::StringRef(\"material\"),\n            jmat,\n            allocator\n            );\n    }\n\n    for (auto& t : sp->textures())\n    {\n        std::string channel_name = t.first;\n\n        rapidjson::Value jtex;\n        jtex.SetObject();\n\n        if (auto tex = std::dynamic_pointer_cast<sg::texture2d<vector<4, unorm<8>>>>(t.second))\n        {\n            // Not implemented yet\n        }\n#if VSNRAY_COMMON_HAVE_PTEX\n        else if (auto tex = std::dynamic_pointer_cast<sg::ptex_texture>(t.second))\n        {\n            jtex.AddMember(\n                rapidjson::StringRef(\"type\"),\n                rapidjson::StringRef(\"ptex\"),\n                allocator\n                );\n\n            rapidjson::Value filename(tex->filename().c_str(), allocator);\n            jtex.AddMember(\n                rapidjson::StringRef(\"filename\"),\n                filename,\n                allocator\n                );\n        }\n#endif // VSNRAY_COMMON_HAVE_PTEX\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n}\n\ntemplate <typename Object>\nvoid vsnray_writer::write_triangle_mesh(Object obj, std::shared_ptr<sg::triangle_mesh> const& tm)\n{\n    auto& allocator = document_.GetAllocator();\n\n    // Write binary files\n\n    if (!tm->vertices.empty())\n    {\n        data_file::meta_data md;\n        md.path = make_inline_filename(tm->name(), \"vert\");\n        md.encoding = data_file::meta_data::Binary;\n        md.data_type = data_file::meta_data::Vec3f;\n        md.num_items = tm->vertices.size();\n\n        rapidjson::Value verts;\n        verts.SetObject();\n\n        write_data_file(verts.GetObject(), md, tm->vertices);\n\n        obj.AddMember(\"vertices\", verts, allocator);\n    }\n\n    if (!tm->normals.empty())\n    {\n        data_file::meta_data md;\n        md.path = make_inline_filename(tm->name(), \"norm\");\n        md.encoding = data_file::meta_data::Binary;\n        md.data_type = data_file::meta_data::Vec3f;\n        md.num_items = tm->normals.size();\n\n        rapidjson::Value norms;\n        norms.SetObject();\n\n        write_data_file(norms.GetObject(), md, tm->normals);\n\n        obj.AddMember(\"normals\", norms, allocator);\n    }\n\n    if (!tm->tex_coords.empty())\n    {\n        data_file::meta_data md;\n        md.path = make_inline_filename(tm->name(), \"texc\");\n        md.encoding = data_file::meta_data::Binary;\n        md.data_type = data_file::meta_data::Vec2f;\n        md.num_items = tm->tex_coords.size();\n\n        rapidjson::Value tcs;\n        tcs.SetObject();\n\n        write_data_file(tcs.GetObject(), md, tm->tex_coords);\n\n        obj.AddMember(\"tex_coords\", tcs, allocator);\n    }\n\n    if (!tm->colors.empty())\n    {\n        data_file::meta_data md;\n        md.path = make_inline_filename(tm->name(), \"colo\");\n        md.encoding = data_file::meta_data::Binary;\n        md.data_type = data_file::meta_data::Vec3u8;\n        md.num_items = tm->colors.size();\n\n        rapidjson::Value cols;\n        cols.SetObject();\n\n        write_data_file(cols.GetObject(), md, tm->colors);\n\n        obj.AddMember(\"colors\", cols, allocator);\n    }\n}\n\ntemplate <typename Object>\nvoid vsnray_writer::write_indexed_triangle_mesh(Object obj, std::shared_ptr<sg::indexed_triangle_mesh> const& itm)\n{\n}\n\ntemplate <typename Object, typename Container>\nvoid vsnray_writer::write_data_file(Object obj, data_file::meta_data md, Container const& cont)\n{\n    // First try to write the actual data file\n\n    // Don't overwrite\n    if (boost::filesystem::exists(md.path))\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    // Check for consistency\n    if (static_cast<int>(cont.size()) != md.num_items)\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    std::ofstream file(md.path, std::ios::binary);\n\n    if (!file.good())\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    // Write data\n    try\n    {\n        file.write(reinterpret_cast<char const*>(cont.data()), cont.size() * sizeof(typename Container::value_type));\n    }\n    catch (std::ios_base::failure)\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    assert(boost::filesystem::exists(md.path));\n\n\n    // Now store a JSON node containing meta data to the document\n    auto& allocator = document_.GetAllocator();\n\n    std::string data_type = \"\";\n\n    auto& data_type_map = data_file::meta_data::data_type_map;\n\n    auto it = data_type_map.left.find(md.data_type);\n\n    if (it != data_type_map.left.end())\n    {\n        data_type = it->second;\n    }\n    else\n    {\n        throw std::runtime_error(\"\");\n    }\n\n    assert(!data_type.empty());\n\n    if (md.encoding == data_file::meta_data::Binary)\n    {\n        obj.AddMember(\n            rapidjson::StringRef(\"type\"),\n            rapidjson::StringRef(\"file\"),\n            allocator\n            );\n\n        rapidjson::Value path(md.path.c_str(), allocator);\n        obj.AddMember(\n            rapidjson::StringRef(\"path\"),\n            path,\n            allocator\n            );\n\n        obj.AddMember(\n            rapidjson::StringRef(\"encoding\"),\n            rapidjson::StringRef(\"binary\"),\n            allocator\n            );\n\n        rapidjson::Value dt(data_type.c_str(), allocator);\n        obj.AddMember(\n            rapidjson::StringRef(\"data_type\"),\n            dt,\n            allocator\n            );\n\n        rapidjson::Value num_items;\n        num_items.SetInt(md.num_items);\n        obj.AddMember(\"num_items\", num_items, allocator);\n\n        obj.AddMember(\n            rapidjson::StringRef(\"compression\"),\n            rapidjson::StringRef(\"none\"),\n            allocator\n            );\n    }\n    else\n    {\n        // Not implemented yet\n        throw std::runtime_error(\"\");\n    }\n}\n\nstd::string vsnray_writer::make_inline_filename(std::string node_name, std::string suffix)\n{\n    std::string result;\n\n    std::string insert = node_name;\n\n    int inc = 0;\n\n    for (;;)\n    {\n        std::string fn = filename_;\n\n        if (!node_name.empty())\n        {\n            fn.append(std::string(\".\") + node_name);\n        }\n        else\n        {\n            std::string inc_str = std::to_string(inc);\n\n            while (inc_str.length() < 8)\n            {\n                inc_str = std::string(\"0\") + inc_str;\n            }\n\n            fn.append(std::string(\".\") + inc_str);\n\n            ++inc;\n        }\n\n        if (!suffix.empty())\n        {\n            if (suffix[0] != '.')\n            {\n                fn.append(\".\");\n            }\n\n            fn.append(suffix);\n        }\n\n        if (!boost::filesystem::exists(fn))\n        {\n            result = fn;\n            break;\n        }\n        else\n        {\n            if (!node_name.empty())\n            {\n                throw std::runtime_error(\"\");\n            }\n        }\n    }\n\n    return result;\n}\n\n\nnamespace visionaray\n{\n\n//-------------------------------------------------------------------------------------------------\n// Interface\n//\n\nvoid load_vsnray(std::string const& filename, model& mod)\n{\n    std::vector<std::string> filenames(1);\n\n    filenames[0] = filename;\n\n    load_vsnray(filenames, mod);\n}\n\nvoid save_vsnray(std::string const& filename, model const& mod, file_base::save_options const& options)\n{\n    cfile file(filename, \"w+\");\n    if (!file.good())\n    {\n        std::cerr << \"Cannot open \" << filename << '\\n';\n        return;\n    }\n\n    rapidjson::Document doc;\n    doc.SetObject();\n\n    vsnray_writer writer(doc, filename);\n    writer.write_node(doc.GetObject(), mod.scene_graph);\n\n    char buffer[65536];\n    rapidjson::FileWriteStream fws(file.get(), buffer, sizeof(buffer));\n\n    rapidjson::PrettyWriter<rapidjson::FileWriteStream> w(fws);\n    doc.Accept(w);\n}\n\nvoid load_vsnray(std::vector<std::string> const& filenames, model& mod)\n{\n    auto root = std::make_shared<sg::node>();\n\n    for (auto filename : filenames)\n    {\n        cfile file(filename, \"r\");\n        if (!file.good())\n        {\n            std::cerr << \"Cannot open \" << filename << '\\n';\n            return;\n        }\n\n        char buffer[65536];\n        rapidjson::FileReadStream frs(file.get(), buffer, sizeof(buffer));\n        rapidjson::Document doc;\n        doc.ParseStream(frs);\n\n        if (doc.IsObject())\n        {\n            vsnray_parser parser(filename);\n            root = parser.parse_node(doc.GetObject());\n        }\n        else\n        {\n            throw std::runtime_error(\"\");\n        }\n    }\n\n    if (mod.scene_graph == nullptr)\n    {\n        mod.scene_graph = root;\n    }\n    else\n    {\n        mod.scene_graph->add_child(root);\n    }\n}\n\n} // visionaray\n", "meta": {"hexsha": "1dbab1123bbbe10777bdc011debd449044c183c0", "size": 57256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/vsnray_loader.cpp", "max_stars_repo_name": "sylvainbouxin/visionaray", "max_stars_repo_head_hexsha": "39aba3605ca92b6b086852d3524b762ac259ed43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/vsnray_loader.cpp", "max_issues_repo_name": "sylvainbouxin/visionaray", "max_issues_repo_head_hexsha": "39aba3605ca92b6b086852d3524b762ac259ed43", "max_issues_repo_licenses": ["MIT"], "max_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/vsnray_loader.cpp", "max_forks_repo_name": "sylvainbouxin/visionaray", "max_forks_repo_head_hexsha": "39aba3605ca92b6b086852d3524b762ac259ed43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T20:21:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T20:21:23.000Z", "avg_line_length": 27.606557377, "max_line_length": 117, "alphanum_fraction": 0.4946206511, "num_tokens": 12828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.033085981487302796, "lm_q1q2_score": 0.015253192625663244}}
{"text": "/*\n * Software License Agreement (New BSD License)\n *\n * Copyright (c) 2013, Keith Leung, Felipe Inostroza\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Advanced Mining Technology Center (AMTC), the\n *       Universidad de Chile, nor the names of its contributors may be \n *       used to endorse or promote products derived from this software without \n *       specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AMTC, UNIVERSIDAD DE CHILE, OR THE COPYRIGHT \n * HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE \n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT \n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF \n * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef PARTICLE_FILTER_HPP\n#define PARTICLE_FILTER_HPP\n\n#include <boost/thread/thread.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/condition.hpp>\n#include \"Particle.hpp\"\n#include \"ProcessModel.hpp\"\n#include \"MeasurementModel.hpp\"\n#include <vector>\n\n/** \n * \\class ParticleFilter\n * \\brief A class containing functions for implementing the particle filter\n * \\tparam ProcessModel class for the process model for propagating particles\n * \\tparam MeasurementModel class for the measurement model for updateing particles\n * \\author Keith Leung\n */\ntemplate< class ProcessModel, class MeasurementModel>\nclass ParticleFilter\n{\npublic:\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  typedef typename ProcessModel::TState TPose;\n  typedef typename ProcessModel::TInput TInput;\n  typedef typename MeasurementModel::TMeasurement TMeasure;\n  typedef Particle<TPose>* pParticle;\n  typedef std::vector<pParticle> TParticleSet;\n\n\n  /** \n   * \\brief Configurations for this ParticleFilter\n   */\n  struct Config{\n    /** Number of threads to use for computations. \n     *  Right now, the overheads of multithreading\n     *  does not make it worth-while \n     */\n    unsigned int nThreadsPropagationStep_; \n  }PFconfig;\n\n\n  /** Defailt constructor */\n  ParticleFilter();\n\n  /** \n   * Constructor \n   * \\param[in] n number of particles\n   * \\param[in] initState if not NULL, all particles will take this initial state\n   */ \n  ParticleFilter(int n, TPose* initState = NULL);\n\n  /** Default destructor */\n  ~ParticleFilter();\n\n  /** \n   * Get the process model pointer\n   * \\return pointer to process model\n   */\n  ProcessModel* getProcessModel();\n\n  /** \n   * Get the measurement model pointer\n   * \\return pointer to measurement model\n   */\n  MeasurementModel* getMeasurementModel();\n\n  /** \n   * Set the measurements for use in importance weight calculations\n   * \\note The input vector gets cleared\n   * \\param[in] Z vector container of measurements\n   */\n  void setMeasurements(std::vector<TMeasure> &Z);\n\n  /** \n   * Propagate particles using the process model\n   * \\param[in] input to the process model\n   * \\param[in] dT time-step of input (not used by all process models)\n   */\n  void propagate( TInput &input, double const dt = 0);\n\n  /**\n   * Calculate and update importance weights for all particles;\n   * Derived class needs to implement this method\n   */\n  virtual void importanceWeighting();\n\n  /** \n   * Get the number of particles\n   * \\return count\n   */\n  int getParticleCount();\n\n  /** \n   * Get the pointer to the particle container\n   * \\retrun a pointer\n   */\n  TParticleSet* getParticleSet(){return &particleSet_;}\n\n  /** \n   * Set the effective particle count below which we initiate resampling\n   * \\param[in] t threshold\n   */\n  void setEffectiveParticleCountThreshold(double t);\n\n  /**\n   * Get the effective particle count threshold\n   * \\return threshold\n   */ \n  double getEffectiveParticleCountThreshold();\n\n  /**\n   * Particle resampling using a low variance sampling. \n   * Sampling will not occur if number of effective particles is above effNParticles_t_.\n   * \\param[in] n number of particles in the resampled set.\n   *        The default value of 0 will keep the same number of particles \n   * \\return true if resampling occured\n   */\n  bool resample( unsigned int n = 0 );\n  \n\nprotected:\n\n  int nParticles_; /**< number of particles */\n  TParticleSet particleSet_; /**< container for particle pointers */\n\n  ProcessModel* pProcessModel_; /**< Process model pointer */\n  MeasurementModel* pMeasurementModel_; /**< Measurement model pointer */\n  \n  double effNParticles_t_; /**< Effective particle count threshold for resampling */\n\n  std::vector<TMeasure> measurements_; /**< Container for measurements to use for update of particle weight */\n\n  /** \n   * Normalize particle weights so that they sum to 1\n   */\n  void normalizeWeights();\n  \n};\n\n////////// Implementation //////////\n\ntemplate< class ProcessModel, class MeasurementModel>\nParticleFilter<ProcessModel, MeasurementModel>::\nParticleFilter(){\n  nParticles_ = 0;\n  pProcessModel_ =  new ProcessModel;\n  pMeasurementModel_ =  new MeasurementModel;\n}\n\n\ntemplate< class ProcessModel, class MeasurementModel>\nParticleFilter<ProcessModel, MeasurementModel>::\nParticleFilter(int n, TPose* initState){\n  \n  // initiate particles\n  nParticles_ = n;\n  particleSet_.resize(nParticles_);\n \n  bool noInitState = true; \n  if(initState == NULL){\n    typename TPose::Vec x0;\n    x0.setZero();  \n    initState = new TPose(x0, 0);\n  }else{\n    noInitState = false;\n  }\n\n  double newParticleWeight = 1;\n  for( int i = 0 ; i < nParticles_ ; i++ ){\n    particleSet_[i] = new Particle<TPose>(i, *initState, newParticleWeight);\n  }\n\n  pProcessModel_ =  new ProcessModel;\n  pMeasurementModel_ =  new MeasurementModel;\n\n  effNParticles_t_ = double(nParticles_)/4.0; // default is 1/4 of n\n\n  // set random seed for particle resampling\n  srand48((unsigned int)time(NULL));\n\n  if( noInitState ){\n    delete initState;\n  }\n}\n\n\ntemplate< class ProcessModel, class MeasurementModel>\nParticleFilter<ProcessModel, MeasurementModel>::~ParticleFilter(){\n  \n  for( int i = 0 ; i < nParticles_ ; i++ ){\n    delete particleSet_[i];\n  }\n  delete pProcessModel_;\n  delete pMeasurementModel_;\n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nProcessModel* ParticleFilter<ProcessModel, MeasurementModel>::\ngetProcessModel(){\n  return pProcessModel_; \n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nMeasurementModel* ParticleFilter<ProcessModel, MeasurementModel>::\ngetMeasurementModel(){\n  return pMeasurementModel_; \n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nvoid ParticleFilter<ProcessModel, MeasurementModel>::setMeasurements(std::vector<TMeasure> &Z){\n  measurements_.swap(Z);\n  Z.clear();\n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nvoid ParticleFilter<ProcessModel, MeasurementModel>::propagate( TInput &input, \n\t\t\t\t\t\t\t\tdouble const dt){\n  TPose x_km, x_k;\n  for( int i = 0 ; i < nParticles_ ; i++ ){\n    particleSet_[i]->getPose( x_km );\n    pProcessModel_->sample( x_k, x_km, input, dt);\n    particleSet_[i]->setPose( x_k );\n  } \n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nvoid ParticleFilter<ProcessModel, MeasurementModel>::importanceWeighting(){\n  return;\n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nvoid ParticleFilter<ProcessModel, MeasurementModel>::normalizeWeights(){\n  \n  double sum = 0;\n  for( int i = 0; i < nParticles_; i++ ){\n    sum += particleSet_[i]->getWeight();\n  }\n  for( int i = 0; i < nParticles_; i++ ){\n    particleSet_[i]->setWeight( particleSet_[i]->getWeight() / sum );\n  }\n\n}\n\n\ntemplate< class ProcessModel, class MeasurementModel>\nint ParticleFilter<ProcessModel, MeasurementModel>::getParticleCount(){\n  return nParticles_;\n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nvoid ParticleFilter<ProcessModel, MeasurementModel>::\nsetEffectiveParticleCountThreshold(double t){\n  effNParticles_t_ = t;\n}\n\ntemplate< class ProcessModel, class MeasurementModel>\ndouble ParticleFilter<ProcessModel, MeasurementModel>::\ngetEffectiveParticleCountThreshold(){\n  return effNParticles_t_;\n}\n\ntemplate< class ProcessModel, class MeasurementModel>\nbool ParticleFilter<ProcessModel, MeasurementModel>::resample( unsigned int n ){\n\n  // Check effective number of particles\n  double sum_of_weight_squared = 0;\n  normalizeWeights(); // sum of all particle weights is now 1\n  for( int i = 0; i < nParticles_; i++ ){\n    double w_i = particleSet_[i]->getWeight();\n    sum_of_weight_squared += (w_i * w_i); // and divide by 1\n  }\n  double nEffParticles_ = 1.0 / sum_of_weight_squared;\n  if( nEffParticles_ > effNParticles_t_ ){\n    return false; // no resampling\n  }\n\n  if( n == 0 )\n    n = nParticles_; // number of particles to sample\n\n  // Sampler settings\n  double randomNum_0_to_1 = drand48();\n  unsigned int idx = 0;\n  const double sample_interval = 1.0 / double(n); \n  const double sampler_offset = sample_interval * randomNum_0_to_1;\n  double sample_point = sampler_offset;\n  double cumulative_weight = particleSet_[idx]->getWeight();\n\n  // book-keeping\n  std::vector<char> flag_particle_sampled (nParticles_, 0); \n  std::vector<unsigned int> sampled_idx (n, 0);\n  \n  // Sample\n  for( int i = 0; i < n; i++ ){\n\n    while( sample_point > cumulative_weight ){\n      // particle[idx] not sampled\n      idx++;\n      cumulative_weight += particleSet_[idx]->getWeight();\n    }\n    // particle[idx] sampled\n    sampled_idx[i] = idx;\n    flag_particle_sampled[idx] = 1;\n    sample_point += sample_interval;\n  }\n\n  // Do the actual data copying\n  unsigned int idx_prev = 0;\n  unsigned int next_unsampled_idx = 0;\n  for( int i = 0; i < n; i++ ){\n    \n    bool firstTime = true;\n    idx = sampled_idx[i]; // particle[idx] was sampled \n    \n    if(i > 0 && idx == idx_prev ){\n      firstTime = false;\n    }\n    idx_prev = idx;\n\n    // cases:\n    // 1. idx < n AND idx appears for first time -> do nothing\n    // 2. idx < n AND it is not the first time that idx appears -> make copy\n    // 3. idx > n AND idx appears for first time -> make copy\n    // 4. idx > n AND it is not first time that idx appears -> make copy\n\n    if( idx < n && firstTime){ // case 1\n      particleSet_[idx]->setParentId( particleSet_[idx]->getId() );\n    }else{ // case 2, 3, 4\n\n      if( next_unsampled_idx < nParticles_ ){\n\twhile( flag_particle_sampled[next_unsampled_idx] == 1)\n\t  next_unsampled_idx++;\n      }\n\n      particleSet_[next_unsampled_idx]->setParentId( particleSet_[idx]->getId() );\n      particleSet_[idx]->copyStateTo( particleSet_[next_unsampled_idx] );\n\n      next_unsampled_idx++;\n    }      \n  }\n\n  // Delete all particles with idx >= n\n  for( int i = n; i < nParticles_; i++ ){\n    delete particleSet_[i];\n  }\n  nParticles_ = n;\n\n  // Reset weight of all particles\n  for( int i = 0; i < n; i++ ){\n    particleSet_[i]->setWeight(1);\n  }\n  \n  return true;\n\n}\n\n\n#endif\n", "meta": {"hexsha": "4acd3adbeb35a0034e3b891f500d2a39153fec28", "size": 11659, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ParticleFilter.hpp", "max_stars_repo_name": "szma/RFS-SLAM", "max_stars_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T04:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T04:15:16.000Z", "max_issues_repo_path": "include/ParticleFilter.hpp", "max_issues_repo_name": "szma/RFS-SLAM", "max_issues_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ParticleFilter.hpp", "max_forks_repo_name": "szma/RFS-SLAM", "max_forks_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8184143223, "max_line_length": 110, "alphanum_fraction": 0.707264774, "num_tokens": 2847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.03567855446651359, "lm_q1q2_score": 0.01521053815995645}}
{"text": "/*\n * Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/PlayRho\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 *\n * @brief Units file.\n *\n * @details This file establishes quantity aliases, unit constants, and associated code\n *   for the expression of physical quantities using recognizably named units of those\n *   quantities. Quantities, as used herein, are types associated with physical quantities\n *   like time and length. Conceptually a given quantity is only expressable in units that\n *   relate to that quantity. For every quantity defined herein, there's typically at least\n *   one conceptually typed unit asscociated with it.\n *\n * @note In the simplest way that the PlayRho library can be configured, there's no compiler\n *   enforcement on the usage of the units for their associated quantities beyond the usage\n *   of the Real type.\n */\n\n#ifndef PLAYRHO_COMMON_UNITS_HPP\n#define PLAYRHO_COMMON_UNITS_HPP\n\n#include <PlayRho/Common/RealConstants.hpp>\n#include <PlayRho/Common/Templates.hpp>\n#include <type_traits>\n#include <cmath>\n\n// #define USE_BOOST_UNITS\n#if defined(USE_BOOST_UNITS)\n#include <boost/units/io.hpp>\n#include <boost/units/limits.hpp>\n#include <boost/units/cmath.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 // defined(USE_BOOST_UNITS)\n\n// Define quantity and unit related macros to abstract away C-preprocessor definitions\n#if defined(USE_BOOST_UNITS)\n#define PLAYRHO_QUANTITY(BoostDimension) boost::units::quantity<BoostDimension, Real>\n#define PLAYRHO_UNIT(Quantity, BoostUnit) Quantity{BoostUnit * Real{1}}\n#define PLAYRHO_DERIVED_UNIT(Quantity, BoostUnit, Ratio) Quantity{BoostUnit * Real{Ratio}}\n#else // defined(USE_BOOST_UNITS)\n#define PLAYRHO_QUANTITY(BoostDimension) Real\n#define PLAYRHO_UNIT(Quantity, BoostUnit) Real{1}\n#define PLAYRHO_DERIVED_UNIT(Quantity, BoostUnit, Ratio) Real{Ratio}}\n#endif // defined(USE_BOOST_UNITS)\n\nnamespace playrho\n{\n    /// @defgroup PhysicalQuantities Physical Quantity Types\n    /// @brief Types for physical quantities.\n    /// @details These are the type aliases for physical quantities like time and length\n    ///   that are used by the PlayRho library.\n    ///   Conceptually a given quantity is only expressable in the units that are defined\n    ///   for that quantity.\n    /// @see PhysicalUnits\n    /// @see https://en.wikipedia.org/wiki/List_of_physical_quantities\n    /// @{\n    \n    /// @brief Time quantity.\n    /// @details This is the type alias for the time base quantity.\n    /// @note This quantity's dimension is: time (<code>T</code>).\n    /// @note The SI unit of time is the second.\n    /// @see Second.\n    /// @see https://en.wikipedia.org/wiki/Time_in_physics\n    using Time = PLAYRHO_QUANTITY(boost::units::si::time);\n    \n    /// @brief Frequency quantity.\n    /// @details This is the type alias for the frequency quantity. It's a derived quantity\n    ///   that's the inverse of time.\n    /// @note This quantity's dimension is: inverse time (<code>T^-1</code>).\n    /// @note The SI unit of frequency is the hertz.\n    /// @see Time.\n    /// @see Hertz.\n    /// @see https://en.wikipedia.org/wiki/Frequency\n    using Frequency = PLAYRHO_QUANTITY(boost::units::si::frequency);\n    \n    /// @brief Length quantity.\n    /// @details This is the type alias for the length base quantity.\n    /// @note This quantity's dimension is: length (<code>L</code>).\n    /// @note The SI unit of length is the meter.\n    /// @see Meter.\n    /// @see https://en.wikipedia.org/wiki/Length\n    using Length = PLAYRHO_QUANTITY(boost::units::si::length);\n    \n    /// @brief Linear velocity quantity.\n    /// @details This is the type alias for the linear velocity derived quantity.\n    /// @note This quantity's dimensions are: length over time (<code>L T^-1</code>).\n    /// @note The SI unit of linear velocity is meters per second.\n    /// @see Length, Time.\n    /// @see MeterPerSecond.\n    /// @see https://en.wikipedia.org/wiki/Speed\n    using LinearVelocity = PLAYRHO_QUANTITY(boost::units::si::velocity);\n    \n    /// @brief Linear acceleration quantity.\n    /// @details This is the type alias for the linear acceleration derived quantity.\n    /// @note This quantity's dimensions are: length over time squared (<code>L T^-2</code>).\n    /// @note The SI unit of linear acceleration is meters per second squared.\n    /// @see Length, Time, LinearVelocity.\n    /// @see MeterPerSquareSecond.\n    /// @see https://en.wikipedia.org/wiki/Acceleration\n    using LinearAcceleration = PLAYRHO_QUANTITY(boost::units::si::acceleration);\n    \n    /// @brief Mass quantity.\n    /// @details This is the type alias for the mass base quantity.\n    /// @note This quantity's dimension is: mass (<code>M</code>).\n    /// @note The SI unit of mass is the kilogram.\n    /// @see Kilogram.\n    /// @see https://en.wikipedia.org/wiki/Mass\n    using Mass = PLAYRHO_QUANTITY(boost::units::si::mass);\n    \n    /// @brief Inverse mass quantity.\n    /// @details This is the type alias for the inverse mass quantity. It's a derived quantity\n    ///   that's the inverse of mass.\n    /// @note This quantity's dimension is: inverse mass (<code>M^-1</code>).\n    /// @see Mass.\n    using InvMass = PLAYRHO_QUANTITY(boost::units::si::inverse_mass);\n    \n    /// @brief Area quantity.\n    /// @details This is the type alias for the area quantity. It's a derived quantity.\n    /// @note This quantity's dimension is: length squared (<code>L^2</code>).\n    /// @note The SI unit of area is the square-meter.\n    /// @see Length.\n    /// @see SquareMeter.\n    /// @see https://en.wikipedia.org/wiki/Area\n    using Area = PLAYRHO_QUANTITY(boost::units::si::area);\n    \n    /// @brief Area (surface) density quantity.\n    /// @details This is the type alias for the area density quantity. It's a derived quantity.\n    /// @note This quantity's dimensions are: mass per area (<code>M L^-2</code>).\n    /// @note The SI derived unit of area density is kilogram per meter-squared.\n    /// @see Mass, Area.\n    /// @see KilogramPerSquareMeter.\n    /// @see https://en.wikipedia.org/wiki/Area_density\n    using AreaDensity = PLAYRHO_QUANTITY(boost::units::si::surface_density);\n    \n    /// @brief Angle quantity.\n    /// @details This is the type alias for the plane angle base quantity.\n    /// @note This quantity's dimension is: plane angle (<code>QP</code>).\n    /// @see Radian, Degree.\n    using Angle = PLAYRHO_QUANTITY(boost::units::si::plane_angle);\n    \n    /// @brief Angular velocity quantity.\n    /// @details This is the type alias for the plane angular velocity quantity. It's a\n    ///   derived quantity.\n    /// @note This quantity's dimensions are: plane angle per time (<code>QP T^-1</code>).\n    /// @note The SI derived unit of angular velocity is the radian per second.\n    /// @see Angle, Time.\n    /// @see RadianPerSecond, DegreePerSecond.\n    /// @see https://en.wikipedia.org/wiki/Angular_velocity\n    using AngularVelocity = PLAYRHO_QUANTITY(boost::units::si::angular_velocity);\n    \n    /// @brief Angular acceleration quantity.\n    /// @details This is the type alias for the angular acceleration quantity. It's a\n    ///   derived quantity.\n    /// @note This quantity's dimensions are: plane angle per time squared (<code>QP T^-2</code>).\n    /// @note The SI derived unit of angular acceleration is the radian per second-squared.\n    /// @see Angle, Time, AngularVelocity.\n    /// @see RadianPerSquareSecond, DegreePerSquareSecond.\n    /// @see https://en.wikipedia.org/wiki/Angular_acceleration\n    using AngularAcceleration = PLAYRHO_QUANTITY(boost::units::si::angular_acceleration);\n\n    /// @brief Force quantity.\n    /// @details This is the type alias for the force quantity. It's a derived quantity.\n    /// @note This quantity's dimensions are: length mass per time squared (<code>L M T^-2</code>).\n    /// @note The SI derived unit of force is the newton.\n    /// @see Length, Mass, Time.\n    /// @see Newton.\n    /// @see https://en.wikipedia.org/wiki/Force\n    using Force = PLAYRHO_QUANTITY(boost::units::si::force);\n    \n    /// @brief Torque quantity.\n    /// @details This is the type alias for the torque quantity. It's a derived quantity\n    ///   that's a rotational force.\n    /// @note This quantity's dimensions are: length-squared mass per time-squared per\n    ///   angle (<code>L^2 M T^-2 QP^-1</code>).\n    /// @note The SI derived unit of torque is the newton meter.\n    /// @see Length, Mass, Time, Angle.\n    /// @see NewtonMeter.\n    /// @see https://en.wikipedia.org/wiki/Torque\n    using Torque = PLAYRHO_QUANTITY(boost::units::si::torque);\n    \n    /// @brief Second moment of area quantity.\n    /// @details This is the type alias for the second moment of area quantity. It's a\n    ///   derived quantity.\n    /// @note This quantity's dimensions are: length-squared-squared (<code>L^4</code>).\n    /// @see Length.\n    /// @see https://en.wikipedia.org/wiki/Second_moment_of_area\n    using SecondMomentOfArea = PLAYRHO_QUANTITY(boost::units::si::second_moment_of_area);\n    \n    /// @brief Rotational inertia quantity.\n    /// @details This is the type alias for the rotational inertia quantity. It's a\n    ///   derived quantity that's also called the moment of inertia or angular mass.\n    /// @note This quantity's dimensions are: length-squared mass per angle-squared\n    ///   (<code>L^2 M QP^-2</code>).\n    /// @note The SI derived unit of rotational inertia is the kilogram meter-squared\n    ///   (<code>kg * m^2</code>).\n    /// @see Length, Mass, Angle, InvRotInertia.\n    /// @see https://en.wikipedia.org/wiki/Moment_of_inertia\n    using RotInertia = PLAYRHO_QUANTITY(boost::units::si::moment_of_inertia);\n    \n    /// @brief Inverse rotational inertia quantity.\n    /// @details This is the type alias for the inverse rotational inertia quantity. It's\n    ///   a derived quantity.\n    /// @note This quantity's dimensions are: angle-squared per length-squared per mass\n    ///    (<code>L^-2 M^-1 QP^2</code>).\n    /// @see Length, Mass, Angle, RotInertia.\n    using InvRotInertia = PLAYRHO_QUANTITY(boost::units::si::inverse_moment_of_inertia);\n    \n    /// @brief Momentum quantity.\n    /// @details This is the type alias for the momentum quantity. It's a derived quantity.\n    /// @note This quantity's dimensions are: length mass per time (<code>L M T^-1</code>).\n    /// @note The SI derived unit of momentum is the kilogram meter per second.\n    /// @note If <code>p</code> is momentum, <code>m</code> is mass, and <code>v</code> is\n    ///   velocity, then <code>p = m * v</code>.\n    /// @see Length, Mass, Time.\n    /// @see NewtonSecond.\n    /// @see https://en.wikipedia.org/wiki/Momentum\n    using Momentum = PLAYRHO_QUANTITY(boost::units::si::momentum);\n    \n    /// @brief Angular momentum quantity.\n    /// @details This is the type alias for the angular momentum quantity. It's a derived\n    ///   quantity.\n    /// @note This quantity's dimensions are: length-squared mass per time per angle\n    ///    (<code>L^2 M T^-1 QP^-1</code>).\n    /// @note The SI derived unit of angular momentum is the kilogram meter-squared per second.\n    /// @see Length, Mass, Time, Angle, Momentum.\n    /// @see NewtonMeterSecond.\n    /// @see https://en.wikipedia.org/wiki/Angular_momentum\n    using AngularMomentum = PLAYRHO_QUANTITY(boost::units::si::angular_momentum);\n    \n    /// @}\n\n    /// @defgroup PhysicalUnits Units For Physical Quantities\n    /// @brief Units for expressing physical quantities like time and length.\n    /// @details These are the unit definitions for expressing physical quantities like time\n    ///   and length. Conceptually a given unit is only usable with the quantities that are\n    ///   made up of the dimensions which the unit is associated with.\n    /// @see PhysicalQuantities.\n    /// @{\n\n    /// @brief Second unit of time.\n    /// @note This is the SI base unit of time.\n    /// @see Time.\n    /// @see https://en.wikipedia.org/wiki/Second\n    constexpr auto Second = PLAYRHO_UNIT(Time, boost::units::si::second);\n\n    /// @brief Square second unit.\n    /// @see Second\n    constexpr auto SquareSecond = Second * Second;\n\n    /// @brief Hertz unit of Frequency.\n    /// @details Represents the hertz unit of frequency (Hz).\n    /// @see Frequency.\n    /// @see https://en.wikipedia.org/wiki/Hertz\n    constexpr auto Hertz = PLAYRHO_UNIT(Frequency, boost::units::si::hertz);\n\n    /// @brief Meter unit of Length.\n    /// @details A unit of the length quantity.\n    /// @note This is the SI base unit of length.\n    /// @see Length.\n    /// @see https://en.wikipedia.org/wiki/Metre\n    constexpr auto Meter = PLAYRHO_UNIT(Length, boost::units::si::meter);\n\n    /// @brief Meter per second unit of linear velocity.\n    /// @see LinearVelocity.\n    constexpr auto MeterPerSecond = PLAYRHO_UNIT(LinearVelocity,\n        boost::units::si::meter_per_second);\n\n    /// @brief Meter per square second unit of linear acceleration.\n    /// @see LinearAcceleration.\n    constexpr auto MeterPerSquareSecond = PLAYRHO_UNIT(LinearAcceleration,\n        boost::units::si::meter_per_second_squared);\n\n    /// @brief Kilogram unit of mass.\n    /// @note This is the SI base unit of mass.\n    /// @see Mass.\n    /// @see https://en.wikipedia.org/wiki/Kilogram\n    constexpr auto Kilogram = PLAYRHO_UNIT(Mass, boost::units::si::kilogram);\n\n    /// @brief Square meter unit of area.\n    /// @see Area.\n    constexpr auto SquareMeter = PLAYRHO_UNIT(Area, boost::units::si::square_meter);\n\n    /// @brief Cubic meter unit of volume.\n    constexpr auto CubicMeter = Meter * Meter * Meter;\n\n    /// @brief Kilogram per square meter unit of area density.\n    /// @see AreaDensity.\n    constexpr auto KilogramPerSquareMeter = PLAYRHO_UNIT(AreaDensity,\n        boost::units::si::kilogram_per_square_meter);\n\n    /// @brief Radian unit of angle.\n    /// @see Angle.\n    /// @see Degree.\n    constexpr auto Radian = PLAYRHO_UNIT(Angle, boost::units::si::radian);\n    \n    /// @brief Degree unit of angle quantity.\n    /// @see Angle.\n    /// @see Radian.\n    constexpr auto Degree = Angle{Radian * Pi / Real{180}};\n    \n    /// @brief Square radian unit type.\n    /// @see Angle.\n    /// @see Radian.\n    constexpr auto SquareRadian = Radian * Radian;\n\n    /// @brief Radian per second unit of angular velocity.\n    /// @see AngularVelocity.\n    /// @see Radian, Second.\n    constexpr auto RadianPerSecond = PLAYRHO_UNIT(AngularVelocity,\n        boost::units::si::radian_per_second);\n    \n    /// @brief Degree per second unit of angular velocity.\n    /// @see AngularVelocity.\n    /// @see Degree, Second.\n    constexpr auto DegreePerSecond = AngularVelocity{RadianPerSecond * Degree / Radian};\n\n    /// @brief Radian per square second unit of angular acceleration.\n    /// @see AngularAcceleration.\n    /// @see Radian, Second.\n    constexpr auto RadianPerSquareSecond = Radian / (Second * Second);\n\n    /// @brief Degree per square second unit of angular acceleration.\n    /// @see AngularAcceleration.\n    /// @see Degree, Second.\n    constexpr auto DegreePerSquareSecond = Degree / (Second * Second);\n\n    /// @brief Newton unit of force.\n    /// @see Force.\n    constexpr auto Newton = PLAYRHO_UNIT(Force, boost::units::si::newton);\n\n    /// @brief Newton meter unit of torque.\n    /// @see Torque.\n    /// @see Newton, Meter.\n    constexpr auto NewtonMeter = PLAYRHO_UNIT(Torque, boost::units::si::newton_meter);\n\n    /// @brief Newton second unit of momentum.\n    /// @see Momentum.\n    /// @see Newton, Second.\n    constexpr auto NewtonSecond = Newton * Second;\n    \n    /// @brief Newton meter second unit of angular momentum.\n    /// @see AngularMomentum.\n    /// @see Newton, Meter, Second.\n    constexpr auto NewtonMeterSecond = NewtonMeter * Second;\n    \n    /// @brief Revolutions per minute units of angular velocity.\n    /// @see AngularVelocity, Time\n    /// @see Minute.\n    constexpr auto RevolutionsPerMinute = 2 * Pi * Radian / (Real{60} * Second);\n    \n    /// @}\n    \n    /// @defgroup Unitsymbols Literals For Unit Symbols\n    /// @brief User defined literals for more conveniently setting the value of physical\n    ///   quantities.\n    /// @see PhysicalQuantities\n    /// @see PhysicalUnits\n    /// @{\n\n    /// @brief SI unit symbol for a gram unit of Mass.\n    /// @see https://en.wikipedia.org/wiki/Gram\n    constexpr Mass operator\"\" _g(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * (Kilogram / Kilo);\n    }\n    \n    /// @brief SI unit symbol for a gram unit of Mass.\n    /// @see https://en.wikipedia.org/wiki/Gram\n    constexpr Mass operator\"\" _g(long double v) noexcept\n    {\n        return static_cast<Real>(v) * (Kilogram / Kilo);\n    }\n\n    /// @brief SI unit symbol for a kilogram unit of Mass.\n    /// @see Kilogram\n    /// @see https://en.wikipedia.org/wiki/Kilogram\n    constexpr Mass operator\"\" _kg(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Kilogram;\n    }\n    \n    /// @brief SI unit symbol for a kilogram unit of Mass.\n    /// @see Kilogram\n    /// @see https://en.wikipedia.org/wiki/Kilogram\n    constexpr Mass operator\"\" _kg(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Kilogram;\n    }\n    \n    /// @brief SI unit symbol for a petagram unit of Mass.\n    /// @see https://en.wikipedia.org/wiki/Orders_of_magnitude_(mass)\n    constexpr Mass operator\"\" _Pg(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Peta * (Kilogram / Kilo);\n    }\n\n    /// @brief SI unit symbol for a petagram unit of Mass.\n    /// @see https://en.wikipedia.org/wiki/Orders_of_magnitude_(mass)\n    constexpr Mass operator\"\" _Pg(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Peta * (Kilogram / Kilo);\n    }\n\n    /// @brief SI unit symbol for a yottagram unit of Mass.\n    /// @see https://en.wikipedia.org/wiki/Orders_of_magnitude_(mass)\n    constexpr Mass operator\"\" _Yg(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Yotta * (Kilogram / Kilo);\n    }\n    \n    /// @brief SI unit symbol for a yottagram unit of Mass.\n    /// @see https://en.wikipedia.org/wiki/Orders_of_magnitude_(mass)\n    constexpr Mass operator\"\" _Yg(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Yotta * (Kilogram / Kilo);\n    }\n    \n    /// @brief SI unit symbol for a meter of Length.\n    /// @see Meter\n    /// @see https://en.wikipedia.org/wiki/Metre\n    constexpr Length operator\"\" _m(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Meter;\n    }\n    \n    /// @brief SI unit symbol for a meter of Length.\n    /// @see Meter\n    /// @see https://en.wikipedia.org/wiki/Metre\n    constexpr Length operator\"\" _m(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Meter;\n    }\n    \n    /// @brief SI unit symbol for a decimeter of Length.\n    /// @see https://en.wikipedia.org/wiki/Decimetre\n    constexpr Length operator\"\" _dm(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Deci * Meter;\n    }\n    \n    /// @brief SI unit symbol for a decimeter of Length.\n    /// @see https://en.wikipedia.org/wiki/Decimetre\n    constexpr Length operator\"\" _dm(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Deci * Meter;\n    }\n    \n    /// @brief SI unit symbol for a centimeter of Length.\n    /// @see https://en.wikipedia.org/wiki/Centimetre\n    constexpr Length operator\"\" _cm(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Centi * Meter;\n    }\n    \n    /// @brief SI unit symbol for a centimeter of Length.\n    /// @see https://en.wikipedia.org/wiki/Centimetre\n    constexpr Length operator\"\" _cm(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Centi * Meter;\n    }\n    \n    /// @brief SI unit symbol for a gigameter unit of Length.\n    /// @see https://en.wikipedia.org/wiki/Gigametre\n    constexpr Length operator\"\" _Gm (unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Giga * Meter;\n    }\n    \n    /// @brief SI unit symbol for a gigameter unit of Length.\n    /// @see https://en.wikipedia.org/wiki/Gigametre\n    constexpr Length operator\"\" _Gm (long double v) noexcept\n    {\n        return static_cast<Real>(v) * Giga * Meter;\n    }\n    \n    /// @brief SI unit symbol for a megameter unit of Length.\n    /// @see https://en.wikipedia.org/wiki/Megametre\n    constexpr Length operator\"\" _Mm (unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Mega * Meter;\n    }\n\n    /// @brief SI unit symbol for a megameter unit of Length.\n    /// @see https://en.wikipedia.org/wiki/Megametre\n    constexpr Length operator\"\" _Mm (long double v) noexcept\n    {\n        return static_cast<Real>(v) * Mega * Meter;\n    }\n\n    /// @brief SI symbol for a kilometer unit of Length.\n    /// @see https://en.wikipedia.org/wiki/Kilometre\n    constexpr Length operator\"\" _km (unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Kilo * Meter;\n    }\n    \n    /// @brief SI symbol for a kilometer unit of Length.\n    /// @see https://en.wikipedia.org/wiki/Kilometre\n    constexpr Length operator\"\" _km (long double v) noexcept\n    {\n        return static_cast<Real>(v) * Kilo * Meter;\n    }\n    \n    /// @brief SI symbol for a second unit of Time.\n    /// @see Second\n    /// @see https://en.wikipedia.org/wiki/Second\n    constexpr Time operator\"\" _s(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Second;\n    }\n    \n    /// @brief SI symbol for a second unit of Time.\n    /// @see Second\n    /// @see https://en.wikipedia.org/wiki/Second\n    constexpr Time operator\"\" _s(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Second;\n    }\n    \n    /// @brief SI symbol for a minute unit of Time.\n    /// @see https://en.wikipedia.org/wiki/Minute\n    constexpr Time operator\"\" _min(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * 60 * Second;\n    }\n    \n    /// @brief SI symbol for a minute unit of Time.\n    /// @see https://en.wikipedia.org/wiki/Minute\n    constexpr Time operator\"\" _min(long double v) noexcept\n    {\n        return static_cast<Real>(v) * 60 * Second;\n    }\n    \n    /// @brief Symbol for an hour unit of Time.\n    /// @see https://en.wikipedia.org/wiki/Hour\n    constexpr Time operator\"\" _h(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * 60 * 60 * Second;\n    }\n    \n    /// @brief Symbol for an hour unit of Time.\n    /// @see https://en.wikipedia.org/wiki/Hour\n    constexpr Time operator\"\" _h(long double v) noexcept\n    {\n        return static_cast<Real>(v) * 60 * 60 * Second;\n    }\n    \n    /// @brief Symbol for a day unit of Time.\n    /// @see https://en.wikipedia.org/wiki/Day\n    constexpr Time operator\"\" _d(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * 60 * 60 * 24 * Second;\n    }\n    \n    /// @brief Symbol for a day unit of Time.\n    /// @see https://en.wikipedia.org/wiki/Day\n    constexpr Time operator\"\" _d(long double v) noexcept\n    {\n        return static_cast<Real>(v) * 60 * 60 * 24 * Second;\n    }\n\n    /// @brief SI symbol for a radian unit of Angle.\n    /// @see Radian.\n    /// @see https://en.wikipedia.org/wiki/Radian\n    constexpr Angle operator\"\" _rad(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Radian;\n    }\n\n    /// @brief SI symbol for a radian unit of Angle.\n    /// @see Radian.\n    /// @see https://en.wikipedia.org/wiki/Radian\n    constexpr Angle operator\"\" _rad(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Radian;\n    }\n\n    /// @brief Abbreviation for a degree unit of Angle.\n    /// @see Degree.\n    /// @see https://en.wikipedia.org/wiki/Degree_(angle)\n    constexpr Angle operator\"\" _deg(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Degree;\n    }\n    \n    /// @brief Abbreviation for a degree unit of Angle.\n    /// @see Degree.\n    /// @see https://en.wikipedia.org/wiki/Degree_(angle)\n    constexpr Angle operator\"\" _deg(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Degree;\n    }\n\n    /// @brief SI symbol for a newton unit of Force.\n    /// @see Newton\n    /// @see https://en.wikipedia.org/wiki/Newton_(unit)\n    constexpr Force operator\"\" _N(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Newton;\n    }\n    \n    /// @brief SI symbol for a newton unit of Force.\n    /// @see Newton\n    /// @see https://en.wikipedia.org/wiki/Newton_(unit)\n    constexpr Force operator\"\" _N(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Newton;\n    }\n    \n    /// @brief Abbreviation for meter squared unit of Area.\n    /// @see SquareMeter\n    constexpr Area operator\"\" _m2(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * SquareMeter;\n    }\n    \n    /// @brief Abbreviation for meter squared unit of Area.\n    /// @see SquareMeter\n    constexpr Area operator\"\" _m2(long double v) noexcept\n    {\n        return static_cast<Real>(v) * SquareMeter;\n    }\n    \n    /// @brief Abbreviation for meter per second.\n    /// @see https://en.wikipedia.org/wiki/Metre_per_second\n    /// @see Meter\n    /// @see Second\n    /// @see MeterPerSecond\n    constexpr LinearVelocity operator\"\" _mps(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * MeterPerSecond;\n    }\n\n    /// @brief Abbreviation for meter per second.\n    /// @see https://en.wikipedia.org/wiki/Metre_per_second\n    /// @see Meter\n    /// @see Second\n    /// @see MeterPerSecond\n    constexpr LinearVelocity operator\"\" _mps(long double v) noexcept\n    {\n        return static_cast<Real>(v) * MeterPerSecond;\n    }\n    \n    /// @brief Abbreviation for kilometer per second.\n    /// @see https://en.wikipedia.org/wiki/Metre_per_second\n    /// @see Second\n    constexpr LinearVelocity operator\"\" _kps(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Kilo * MeterPerSecond;\n    }\n    \n    /// @brief Abbreviation for kilometer per second.\n    /// @see https://en.wikipedia.org/wiki/Metre_per_second\n    /// @see Second\n    constexpr LinearVelocity operator\"\" _kps(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Kilo * MeterPerSecond;\n    }\n    \n    /// @brief Abbreviation for meter per second squared.\n    /// @see https://en.wikipedia.org/wiki/Metre_per_second_squared\n    /// @see MeterPerSquareSecond\n    constexpr LinearAcceleration operator\"\" _mps2(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * MeterPerSquareSecond;\n    }\n    \n    /// @brief Abbreviation for meter per second squared.\n    /// @see https://en.wikipedia.org/wiki/Metre_per_second_squared\n    /// @see MeterPerSquareSecond\n    constexpr LinearAcceleration operator\"\" _mps2(long double v) noexcept\n    {\n        return static_cast<Real>(v) * MeterPerSquareSecond;\n    }\n    \n    /// @brief SI symbol for a hertz unit of Frequency.\n    /// @see Hertz\n    /// @see https://en.wikipedia.org/wiki/Hertz\n    constexpr Frequency operator\"\" _Hz(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * Hertz;\n    }\n    \n    /// @brief SI symbol for a hertz unit of Frequency.\n    /// @see Hertz\n    /// @see https://en.wikipedia.org/wiki/Hertz\n    constexpr Frequency operator\"\" _Hz(long double v) noexcept\n    {\n        return static_cast<Real>(v) * Hertz;\n    }\n    \n    /// @brief Abbreviation for newton-meter unit of torque.\n    /// @see NewtonMeter\n    /// @see https://en.wikipedia.org/wiki/Newton_metre\n    constexpr Torque operator\"\" _Nm(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * NewtonMeter;\n    }\n    \n    /// @brief Abbreviation for newton-meter unit of torque.\n    /// @see NewtonMeter\n    /// @see https://en.wikipedia.org/wiki/Newton_metre\n    constexpr Torque operator\"\" _Nm(long double v) noexcept\n    {\n        return static_cast<Real>(v) * NewtonMeter;\n    }\n    \n    /// @brief SI symbol for a newton second of impulse.\n    /// @see NewtonSecond\n    /// @see https://en.wikipedia.org/wiki/Newton_second\n    constexpr Momentum operator\"\" _Ns(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * NewtonSecond;\n    }\n    \n    /// @brief SI symbol for a newton second of impulse.\n    /// @see NewtonSecond\n    /// @see https://en.wikipedia.org/wiki/Newton_second\n    constexpr Momentum operator\"\" _Ns(long double v) noexcept\n    {\n        return static_cast<Real>(v) * NewtonSecond;\n    }\n    \n    /// @brief Abbreviation for kilogram per square meter.\n    constexpr AreaDensity operator\"\" _kgpm2(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * KilogramPerSquareMeter;\n    }\n    \n    /// @brief Abbreviation for kilogram per square meter.\n    constexpr AreaDensity operator\"\" _kgpm2(long double v) noexcept\n    {\n        return static_cast<Real>(v) * KilogramPerSquareMeter;\n    }\n\n    /// @brief Abbreviation for revolutions per minute.\n    /// @see RevolutionsPerMinute\n    constexpr AngularVelocity operator\"\" _rpm(unsigned long long int v) noexcept\n    {\n        return static_cast<Real>(v) * RevolutionsPerMinute;\n    }\n\n    /// @brief Abbreviation for revolutions per minute.\n    /// @see RevolutionsPerMinute\n    constexpr AngularVelocity operator\"\" _rpm(long double v) noexcept\n    {\n        return static_cast<Real>(v) * RevolutionsPerMinute;\n    }\n\n    /// @}\n    \n    /// @brief Strips the units off of the given value.\n    constexpr Real StripUnit(const Real value)\n    {\n        return value;\n    }\n\n    /// @defgroup UnitConstants Physical Constants\n    /// @brief Definitions of universal and Earthly physical constants.\n    /// @see PhysicalQuantities\n    /// @see PhysicalUnits\n    /// @{\n\n    /// @brief Earthly gravity.\n    /// @details An approximation of the average acceleration of Earthly objects towards\n    ///   the Earth due to the Earth's gravity.\n    /// @note This constant is only appropriate for use for objects of low mass and close\n    ///   distance relative to the Earth.\n    /// @see https://en.wikipedia.org/wiki/Gravity_of_Earth\n    constexpr auto EarthlyLinearAcceleration = Real{-9.8f} * MeterPerSquareSecond;\n    \n    /// @brief Big \"G\".\n    /// @details Gravitational constant used in calculating the attractive force on a mass\n    ///   to another mass at a given distance due to gravity.\n    /// @see https://en.wikipedia.org/wiki/Gravitational_constant\n    constexpr auto BigG = Real{6.67408e-11f} * CubicMeter / (Kilogram * SquareSecond);\n    \n    /// @}\n\n#if defined(USE_BOOST_UNITS)\n    using boost::units::isfinite;\n    using boost::units::isnormal;\n    using boost::units::cos;\n    using boost::units::sin;\n    \n    // Don't use boost's hypot since it does type promotion which is problematic.\n    // using boost::units::hypot;\n    \n    /// @brief Gets the hypotenuse.\n    /// @note Don't use boost's hypot since it does type promotion which is problematic.\n    /// @see https://en.cppreference.com/w/cpp/numeric/math/hypot\n    /// @see https://en.wikipedia.org/wiki/Hypotenuse\n    template<class Unit>\n    inline auto\n    hypot(const boost::units::quantity<Unit,Real>& x, const boost::units::quantity<Unit,Real>& y)\n    {\n        using std::hypot;\n        return boost::units::quantity<Unit,Real>::from_value(hypot(x.value(), y.value()));\n    }\n    \n    /// @brief Square roots the given value.\n    /// @note Don't use boost's sqrt implementation as it promotes the quantity's given\n    ///   underlying floating-point type which seems contrary in this case to the\n    ///   specification of <code>std::sqrt</code>.\n    /// @see https://en.cppreference.com/w/cpp/numeric/math/sqrt\n    template<class Unit>\n    inline auto\n    sqrt(const boost::units::quantity<Unit,Real>& q)\n    {\n        using std::sqrt;\n        using quantity_type = typename boost::units::root_typeof_helper<\n            boost::units::quantity<Unit,Real>,\n            boost::units::static_rational<2>\n            >::type;\n        using unit_type = typename quantity_type::unit_type;\n        \n        return boost::units::quantity<unit_type, Real>::from_value(sqrt(q.value()));\n    }\n    \n    /// @brief Almost zero.\n    template <class Y>\n    inline auto AlmostZero(const boost::units::quantity<Y, Real> v)\n    {\n        return abs(v) < std::numeric_limits<boost::units::quantity<Y, Real>>::min();\n    }\n\n    /// @brief Strips the units off of the given value.\n    template<class Unit,class Y>\n    constexpr auto StripUnit(const boost::units::quantity<Unit, Y> source)\n    {\n        return source.value();\n    }\n\n    /// @brief Gets an invalid value for the Angle type.\n    template <>\n    constexpr Angle GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Radian;\n    }\n    \n    /// @brief Gets an invalid value for the Frequency type.\n    template <>\n    constexpr Frequency GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Hertz;\n    }\n    \n    /// @brief Gets an invalid value for the AngularVelocity type.\n    template <>\n    constexpr AngularVelocity GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * RadianPerSecond;\n    }\n    \n    /// @brief Gets an invalid value for the Time type.\n    template <>\n    constexpr Time GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Second;\n    }\n    \n    /// @brief Gets an invalid value for the Length type.\n    template <>\n    constexpr Length GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Meter;\n    }\n    \n    /// @brief Gets an invalid value for the Mass type.\n    template <>\n    constexpr Mass GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Kilogram;\n    }\n    \n    /// @brief Gets an invalid value for the InvMass type.\n    template <>\n    constexpr InvMass GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() / Kilogram;\n    }\n    \n    /// @brief Gets an invalid value for the Momentum type.\n    template <>\n    constexpr Momentum GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Kilogram * MeterPerSecond;\n    }\n    \n    /// @brief Gets an invalid value for the Force type.\n    template <>\n    constexpr Force GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * Newton;\n    }\n    \n    /// @brief Gets an invalid value for the Torque type.\n    template <>\n    constexpr Torque GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * NewtonMeter;\n    }\n    \n    /// @brief Gets an invalid value for the LinearVelocity type.\n    template <>\n    constexpr LinearVelocity GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * MeterPerSecond;\n    }\n    \n    /// @brief Gets an invalid value for the LinearAcceleration type.\n    template <>\n    constexpr LinearAcceleration GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * MeterPerSquareSecond;\n    }\n    \n    /// @brief Gets an invalid value for the AngularAcceleration type.\n    template <>\n    constexpr AngularAcceleration GetInvalid() noexcept\n    {\n        return GetInvalid<Real>() * RadianPerSquareSecond;\n    }\n    \n    /// @brief Gets an invalid value for the RotInertia type.\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#endif // defined(USE_BOOST_UNITS)\n\n} // namespace playrho\n\n#if defined(USE_BOOST_UNITS)\nnamespace boost {\nnamespace units {\n\n// Define division and multiplication templated operators in boost::units namespace since\n//   boost::units is the consistent namespace of operands for these and this aids with\n//   argument dependent lookup (ADL).\n//\n// Note that while boost::units already defines division and multiplication operator support,\n//   that's only for division or multiplication with the same type that the quantity is based\n//   on. For example when Real is float, Length{0.0f} * 2.0f is already supported but\n//   Length{0.0f} * 2 is not.\n\n/// @brief Division operator.\n///\n/// @details Supports the division of a playrho::Real based boost::units::quantity\n///   by any arithmetic type except playrho::Real.\n/// @note This intentionally excludes the playrho::Real type since the playrho::Real\n///   type is already supported and supporting it again in this template causes\n///   ambiguous overload support.\n///\ntemplate <class Dimension, typename X, typename = std::enable_if_t<\n    playrho::IsArithmetic<X>::value && !std::is_same<X, playrho::Real>::value &&\n    std::is_same<decltype(playrho::Real{} / X{}), playrho::Real>::value >\n>\nconstexpr auto operator/ (quantity<Dimension, playrho::Real> lhs, X rhs)\n{\n    return lhs / playrho::Real(rhs);\n}\n\ntemplate <class Dimension, typename X, typename = std::enable_if_t<\n    playrho::IsArithmetic<X>::value && !std::is_same<X, playrho::Real>::value &&\n    std::is_same<decltype(X{} / playrho::Real{}), playrho::Real>::value >\n>\nconstexpr auto operator/ (X lhs, quantity<Dimension, playrho::Real> rhs)\n{\n    return playrho::Real(lhs) / rhs;\n}\n\n/// @brief Multiplication operator.\n///\n/// @details Supports the multiplication of a playrho::Real based boost::units::quantity\n///   by any arithmetic type except playrho::Real.\n/// @note This intentionally excludes the playrho::Real type since the playrho::Real\n///   type is already supported and supporting it again in this template causes\n///   ambiguous overload support.\n///\ntemplate <class Dimension, typename X, typename = std::enable_if_t<\n    playrho::IsArithmetic<X>::value && !std::is_same<X, playrho::Real>::value &&\n    std::is_same<decltype(playrho::Real{} * X{}), playrho::Real>::value> >\nconstexpr auto operator* (quantity<Dimension, playrho::Real> lhs, X rhs)\n{\n    return lhs * playrho::Real(rhs);\n}\n\n/// @brief Multiplication operator.\n///\n/// @details Supports the multiplication of a playrho::Real based boost::units::quantity\n///   by any arithmetic type except playrho::Real.\n/// @note This intentionally excludes the playrho::Real type since the playrho::Real\n///   type is already supported and supporting it again in this template causes\n///   ambiguous overload support.\n///\ntemplate <class Dimension, typename X, typename = std::enable_if_t<\n    playrho::IsArithmetic<X>::value && !std::is_same<X, playrho::Real>::value &&\n    std::is_same<decltype(playrho::Real{} * X{}), playrho::Real>::value> >\nconstexpr auto operator* (X lhs, quantity<Dimension, playrho::Real> rhs)\n{\n    return playrho::Real(lhs) * rhs;\n}\n\n} // namespace units\n} // namespace boost\n#endif // defined(USE_BOOST_UNITS)\n\n#undef PLAYRHO_QUANTITY\n#undef PLAYRHO_UNIT\n\n#endif // PLAYRHO_COMMON_UNITS_HPP\n", "meta": {"hexsha": "cb56732efe69bf012fe368fb2290094aae53734f", "size": 40537, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PlayRho/Common/Units.hpp", "max_stars_repo_name": "shybovycha/PlayRho", "max_stars_repo_head_hexsha": "eb4319022d324ebd6ada458b3410b00d00daac2c", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PlayRho/Common/Units.hpp", "max_issues_repo_name": "shybovycha/PlayRho", "max_issues_repo_head_hexsha": "eb4319022d324ebd6ada458b3410b00d00daac2c", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PlayRho/Common/Units.hpp", "max_forks_repo_name": "shybovycha/PlayRho", "max_forks_repo_head_hexsha": "eb4319022d324ebd6ada458b3410b00d00daac2c", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4236966825, "max_line_length": 99, "alphanum_fraction": 0.6625798653, "num_tokens": 9969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.03567855241578037, "lm_q1q2_score": 0.015210537285684597}}
{"text": "/*\n *  Copyright (c) 2015 Evgeny Proydakov <lord.tiran@gmail.com>\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a copy\n *  of this software and associated documentation files (the \"Software\"), to deal\n *  in the Software without restriction, including without limitation the rights\n *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n *  copies of the Software, and to permit persons to whom the Software is\n *  furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in\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 <cmath>\n#include <chrono>\n#include <fstream>\n#include <iostream>\n\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/adjacency_list.hpp>\n\ntypedef float distance_t;\n\nstruct vertex_property\n{\n    size_t x;\n    size_t y;\n};\n\ntypedef boost::property<boost::edge_weight_t, distance_t> edge_property;\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_property, edge_property> grid;\n\ntypedef boost::graph_traits<grid>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<grid>::vertices_size_type vertices_size_type;\n\nclass vertex_hash;\n\ntypedef std::vector<vertex_descriptor> vertex_vector;\ntypedef boost::unordered_set<vertex_descriptor, vertex_hash> vertex_set;\n\ntypedef std::vector<std::string> name_vector;\n\n// Exception thrown when the goal vertex is found\nstruct found_goal {};\n\n///////////////////////////////////////////////////////////////////////////////\n\n// A hash function for vertices.\nclass vertex_hash\n{\npublic:\n    vertex_hash(const grid& graph) : m_graph(graph) {}\n\n    std::size_t operator()(const vertex_descriptor& v) const\n    {   \n        std::size_t seed = 0;\n        boost::hash_combine(seed, m_graph[v].x);\n        boost::hash_combine(seed, m_graph[v].y);\n        return seed;\n    }\n\nprivate:\n    const grid& m_graph;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\n//\n// Euclidean heuristic for a grid\n//\n// This calculates the Euclidean distance between a vertex and a goal\n// vertex.\n//\nclass euclidean_heuristic : public boost::astar_heuristic<grid, distance_t>\n{\npublic:\n    euclidean_heuristic(const grid& graph, const vertex_descriptor& goal) : m_graph(graph), m_goal(goal) {}\n\n    distance_t operator() (vertex_descriptor v) {\n        distance_t x = static_cast<distance_t>(std::fabs(m_graph[m_goal].x - m_graph[v].x));\n        distance_t y = static_cast<distance_t>(std::fabs(m_graph[m_goal].y - m_graph[v].y));\n        return static_cast<distance_t>(std::sqrt(std::pow(x, 2) + std::pow(y, 2)));\n    }\n\nprivate:\n    const grid& m_graph;\n    vertex_descriptor m_goal;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\n// Visitor that terminates when we find the goal vertex\nstruct astar_goal_visitor : public boost::default_astar_visitor\n{\n    astar_goal_visitor(const vertex_descriptor& goal) : m_goal(goal) {}\n\n    void examine_vertex(const vertex_descriptor& u, const grid&) {\n        if (u == m_goal) {\n            throw found_goal();\n        }\n    }\n\nprivate:\n    vertex_descriptor m_goal;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nclass grid_map\n{\npublic:\n    grid_map(size_t width, size_t height) : m_width(width), m_height(height)\n    {\n        const size_t size = width * height;\n        m_name.resize(size);\n\n        // init horizontal edge\n        const distance_t horizontal_size = 1;\n        for(size_t x = 0; x < width - 1; x++) {\n            for(size_t y = 0; y < height; y++) {\n                const size_t index = calc_vertex_index(x, y);\n                boost::add_edge(index, index + 1, horizontal_size, m_grid);\n            }\n        }\n\n        // init vertical edge\n        const distance_t vertical_size = 1;\n        for(size_t x = 0; x < width; x++) {\n            for(size_t y = 0; y < height - 1; y++) {\n                const size_t index = calc_vertex_index(x, y);\n                boost::add_edge(index, index + width, vertical_size, m_grid);\n            }\n        }\n\n        // init diagonal edge\n        const distance_t diagonal_size = static_cast<distance_t>(std::sqrt(2));\n        for(size_t x = 0; x < width - 1; x++) {\n            for(size_t y = 0; y < height - 1; y++) {\n                const size_t index = calc_vertex_index(x, y);\n                boost::add_edge(index, index + width + 1, diagonal_size, m_grid);\n                boost::add_edge(index + 1, index + width, diagonal_size, m_grid);\n            }\n        }\n\n        // fill name and vertex descriptin\n        for(size_t x = 0; x < width; x++) {\n            for(size_t y = 0; y < height; y++) {\n                const size_t index = calc_vertex_index(x, y);\n                vertex_descriptor descriptor(index);\n                m_grid[descriptor].x = x;\n                m_grid[descriptor].y = y;\n                std::stringstream sstream;\n                sstream << \"(\" << x << \", \" << y << \")\";\n                m_name[index] = sstream.str();\n            }\n        }\n    }\n\n    size_t calc_vertex_index(size_t x, size_t y)\n    {\n        return x + y * m_width;\n    }\n\n    const grid::vertex_bundled& get_vertex_property(vertex_descriptor vertex) const\n    {\n        return m_grid[vertex];\n    }\n\n    bool search_path(const vertex_descriptor& source, const vertex_descriptor& goal, vertex_vector& solution)\n    {\n        const size_t solution_assessment_size = m_width + m_height;\n        vertex_hash hash(m_grid);\n\n        // The predecessor map is a vertex-to-vertex mapping.\n        typedef boost::unordered_map<vertex_descriptor, vertex_descriptor, vertex_hash> pred_map;\n        pred_map predecessor(solution_assessment_size, hash);\n        boost::associative_property_map<pred_map> pred_pmap(predecessor);\n\n        // The distance map is a vertex-to-distance mapping.\n        typedef boost::unordered_map<vertex_descriptor, distance_t, vertex_hash> dist_map;\n        dist_map distance(solution_assessment_size, hash);\n        boost::associative_property_map<dist_map> dist_pmap(distance);\n\n        euclidean_heuristic heuristic(m_grid, goal);\n        astar_goal_visitor  visitor  (goal);\n\n        bool result = false;\n        const int iters = 10;\n\n        std::chrono::high_resolution_clock clock;\n        auto start = clock.now();\n\n        for(int i = 0; i < iters; i++) {\n            solution.clear();\n            predecessor.clear();\n            distance.clear();\n            try {\n                boost::astar_search(m_grid, source, heuristic,\n                                    boost::visitor(visitor).\n                                    predecessor_map(pred_pmap).\n                                    distance_map(dist_pmap)\n                                    );\n            }\n            catch(const found_goal&) {\n                // Walk backwards from the goal through the predecessor chain adding\n                // vertices to the solution path.\n                for (vertex_descriptor u = goal; u != source; u = predecessor[u]) {\n                    solution.push_back(u);\n                }\n                solution.push_back(source);\n                std::reverse(solution.begin(), solution.end());\n                result = true;\n            }\n        }\n        auto end = clock.now();\n\n        distance_t dist = distance[goal];\n        std::cout << \"solve. result: \" << result << \" size: \" << dist << \" process time: \"\n                  << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / iters << \" us\"\n                  << std::endl;\n\n        return result;\n    }\n\n    void dump_to_dot()\n    {\n        std::ofstream dot(\"graph.dot\");\n        boost::write_graphviz(dot, m_grid, boost::make_label_writer(&m_name[0]));\n        dot.close();\n    }\n\nprivate:\n    grid        m_grid;\n    name_vector m_name;\n\n    size_t m_width;\n    size_t m_height;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nint main()\n{\n    const size_t w = 5;\n    const size_t h = 5;\n\n    grid_map map(w, h);\n\n    vertex_descriptor source = map.calc_vertex_index(0, 0);\n    vertex_descriptor goal = map.calc_vertex_index(w - 1, h - 1);\n\n    auto property_source = map.get_vertex_property(source);\n    std::cout << \"search from: (\" << property_source.x << \", \" << property_source.y << \")\";\n\n    auto property_goal = map.get_vertex_property(goal);\n    std::cout << \" to: (\" << property_goal.x << \", \" << property_goal.y << \")\" << std::endl;\n\n    vertex_vector solution;\n    map.search_path(source, goal, solution);\n\n    map.dump_to_dot();\n\n    return 0;\n}\n", "meta": {"hexsha": "2cc68d3d92b01cca16e110a76ec29528984f5a58", "size": 9251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/graph/main.cpp", "max_stars_repo_name": "proydakov/cppzone", "max_stars_repo_head_hexsha": "2cee5523df8fadbd087746c16bbf386360c8114a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-02-16T12:34:13.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-14T20:12:17.000Z", "max_issues_repo_path": "boost/graph/main.cpp", "max_issues_repo_name": "proydakov/cpplabs", "max_issues_repo_head_hexsha": "8f958e00a3bd3f9594a57b39c02fbf964749f2a3", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "proydakov/cpplabs", "max_forks_repo_head_hexsha": "8f958e00a3bd3f9594a57b39c02fbf964749f2a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-17T09:25:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-08T13:56:33.000Z", "avg_line_length": 33.3971119134, "max_line_length": 113, "alphanum_fraction": 0.5947465139, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.0311438294107134, "lm_q1q2_score": 0.015207014767177411}}
{"text": "// Copyright (C) 2014 National ICT Australia (NICTA)\n// \n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\n// -------------------------------------------------------------------\n// \n// Written by Conrad Sanderson - http://conradsanderson.id.au\n// Written by George Yammine\n\n\n// Connector for Mex files to use Armadillo for calculation\n// Version 0.5\n\n\n#include <armadillo>\n#include <mex.h>\n#include <mat.h>\n#include <cstring>\n\nusing namespace std;\nusing namespace arma;\n\n\n// Get scalar value from Matlab/Octave\ntemplate<class Type>\ninline\nType\narmaGetScalar(const mxArray *matlabScalar)\n  {\n  if(mxGetData(matlabScalar) != NULL)\n    {\n    return (Type)mxGetScalar(matlabScalar);\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return 0;\n    }\n  }\n\n\n// To keep with Matlab/Octave mex functions since functions for double are usually defined in conjunction with the general functions.\ninline\ndouble\narmaGetDouble(const mxArray *matlabScalar) \n  {\n  return armaGetScalar<double>(matlabScalar);\n  }\n\n\n// Get non-double real matrix from Matlab/Octave. Type should be case according to input. \n// Use mxGetClassID inside main program to test for type.\ntemplate<class Type>\ninline\nMat<Type>\narmaGetData(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true)\n  {\n  if(mxGetData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n    \n    if(n_dim == 2)\n      {\n      return Mat<Type>((Type *)mxGetData(matlabMatrix), mxGetM(matlabMatrix), mxGetN(matlabMatrix), copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 2.\");\n      return Mat<Type>();\n      }\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Mat<Type>();\n    }\n  }\n\n\n// Get double real matrix from Matlab/Octave.\ninline\nMat<double>\narmaGetPr(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true)\n  {\n  if(mxGetData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n    \n    if(n_dim == 2)\n      {\n      return Mat<double>(mxGetPr(matlabMatrix), mxGetM(matlabMatrix), mxGetN(matlabMatrix), copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 2.\");\n      return Mat<double>();\n      }\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Mat<double>();\n    }\n  }\n\n\n// Get non-double imaginary matrix from Matlab/Octave. Type should be case according to input. \n// Use mxGetClassID inside main program to test for type.\ntemplate<class Type>\ninline\nMat<Type>\narmaGetImagData(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true)\n  {\n  if(mxGetImagData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n    \n    if(n_dim == 2)\n      {\n      return Mat<Type>((Type *)mxGetImagData(matlabMatrix), mxGetM(matlabMatrix), mxGetN(matlabMatrix), copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 2.\");\n      return Mat<Type>();\n      }\n    }      \n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Mat<Type>();\n    }\n  }\n\n\n// Get double imaginary matrix from Matlab/Octave.\ninline\nMat<double>\narmaGetPi(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true) \n  {\n  if(mxGetImagData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n    \n    if(n_dim == 2)\n      {\n      return Mat<double>(mxGetPi(matlabMatrix), mxGetM(matlabMatrix), mxGetN(matlabMatrix), copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 2.\");\n      return Mat<double>();\n      }\n    }      \n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Mat<double>();\n    }\n  }\n\n\n// Get complex matrix from Matlab/Octave\ninline\ncx_mat\narmaGetCx(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true) \n  {\n  if( (mxGetPr(matlabMatrix) != NULL) && (mxGetPi(matlabMatrix) != NULL) )\n    {\n    return cx_mat(armaGetPr(matlabMatrix, copy_aux_mem, strict), armaGetPi(matlabMatrix, copy_aux_mem, strict));\n    }\n  else if( (mxGetPr(matlabMatrix) != NULL) && (mxGetPi(matlabMatrix) == NULL) )\n    {\n    return cx_mat(armaGetPr(matlabMatrix, copy_aux_mem, strict), zeros(mxGetM(matlabMatrix),mxGetN(matlabMatrix)));\n    }\n  else if( (mxGetPr(matlabMatrix) == NULL) && (mxGetPi(matlabMatrix) != NULL) )\n    {\n    return cx_mat(zeros(mxGetM(matlabMatrix), mxGetN(matlabMatrix)), armaGetPi(matlabMatrix, copy_aux_mem, strict));\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return cx_mat();\n    }\n  }\n\n\n// Return non-double real valued matrix to Matlab/Octave\ntemplate<class Type>\ninline\nvoid\narmaSetData(mxArray *matlabMatrix, const Mat<Type>& armaMatrix)\n  {\n        Type *dst_pointer = (Type*)mxGetData(matlabMatrix);\n  const Type *src_pointer = (Type*)armaMatrix.memptr();\n    \n  std::memcpy(dst_pointer, src_pointer, sizeof(Type)*armaMatrix.n_elem); \n  }\n\n\n// Return double real valued matrix to Matlab/Octave\ninline\nvoid\narmaSetPr(mxArray *matlabMatrix, const Mat<double>& armaMatrix)\n  {\n        double *dst_pointer = mxGetPr(matlabMatrix);\n  const double *src_pointer = armaMatrix.memptr();\n  \n  std::memcpy(dst_pointer, src_pointer, sizeof(double)*armaMatrix.n_elem); \n  }\n\n\n// Return imaginary valued matrix to Matlab/Octave.\ntemplate<class Type>\ninline\nvoid\narmaSetImagData(mxArray *matlabMatrix, const Mat<Type>& armaMatrix)\n  {\n        Type *dst_pointer = (Type*)mxGetImagData(matlabMatrix);\n  const Type *src_pointer = (Type*)armaMatrix.memptr();\n  \n  std::memcpy(dst_pointer, src_pointer, sizeof(Type)*armaMatrix.n_elem); \n  }\n\n\n// Return double complex valued matrix to Matlab/Octave\ninline\nvoid\narmaSetPi(mxArray *matlabMatrix, const Mat<double>& armaMatrix)\n  {\n        double *dst_pointer = mxGetPi(matlabMatrix);\n  const double *src_pointer = armaMatrix.memptr();\n  \n  std::memcpy(dst_pointer, src_pointer, sizeof(double)*armaMatrix.n_elem); \n  }\n\n\n// Return complex matrix to Matlab/Octave. Requires Matlab/Octave matrix to be mxCOMPLEX\ninline\nvoid\narmaSetCx(mxArray *matlabMatrix, const cx_mat& armaMatrix) \n  {\n  armaSetPr(matlabMatrix, real(armaMatrix));\n  armaSetPi(matlabMatrix, imag(armaMatrix));\n  }\n\n\n// Cube functions\n\n// Get non-double real cube from Matlab/Octave. Type should be case according to input. \n// Use mxGetClassID inside main program to test for type.\ntemplate<class Type>\ninline\nCube<Type>\narmaGetCubeData(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true)\n  {  \n  if(mxGetData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n  \n    if(n_dim == 3)\n      {\n      const mwSize *dims = mxGetDimensions(matlabMatrix);\n      return Cube<Type>((Type *)mxGetData(matlabMatrix), dims[0], dims[1], dims[2], copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 3.\");\n      return Cube<Type>();\n      }\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Cube<Type>();\n    }\n  }\n\n\n// Get double cube from Matlab/Octave.   \ninline\nCube<double>\narmaGetCubePr(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true)\n  {\n  if(mxGetData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n  \n    if(n_dim == 3)\n      {\n      const mwSize *dims = mxGetDimensions(matlabMatrix);\n      return Cube<double>(mxGetPr(matlabMatrix), dims[0], dims[1], dims[2], copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 3.\");\n      return Cube<double>();\n      }\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Cube<double>();\n    }\n  }\n\n\n// Get non-double imaginary cube from Matlab/Octave. Type should be case according to input. \n// Use mxGetClassID inside main program to test for type.\ntemplate<class Type>\ninline\nCube<Type>\narmaGetCubeImagData(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true)\n  {\n  if(mxGetImagData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n  \n    if(n_dim == 3)\n      {\n      const mwSize *dims = mxGetDimensions(matlabMatrix);\n      return Cube<Type>((Type *)mxGetImagData(matlabMatrix), dims[0], dims[1], dims[2], copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 3.\");\n      return Cube<Type>();\n      }\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Cube<Type>();\n    }\n  }\n\n\n// Get double cube from Matlab/Octave.   \ninline\nCube<double>\narmaGetCubePi(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true)\n  {\n  if(mxGetImagData(matlabMatrix) != NULL)\n    {\n    const mwSize n_dim = mxGetNumberOfDimensions(matlabMatrix);\n  \n    if(n_dim == 3)\n      {\n      const mwSize *dims = mxGetDimensions(matlabMatrix);\n      return Cube<double>(mxGetPi(matlabMatrix), dims[0], dims[1], dims[2], copy_aux_mem, strict);\n      }\n    else\n      {\n      mexErrMsgTxt(\"Number of dimensions must be 3.\");\n      return Cube<double>();\n      }\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return Cube<double>();\n    }\n  }  \n  \n  \n// Get complex cube from Matlab/Octave\ninline\ncx_cube\narmaGetCubeCx(const mxArray *matlabMatrix, bool copy_aux_mem = false, bool strict = true) \n  {\n  if( (mxGetPr(matlabMatrix) != NULL) && (mxGetPi(matlabMatrix) != NULL) )\n    {\n    return cx_cube(armaGetCubePr(matlabMatrix, copy_aux_mem, strict), armaGetCubePi(matlabMatrix, copy_aux_mem, strict));\n    }\n  else if( (mxGetPr(matlabMatrix) != NULL) && (mxGetPi(matlabMatrix) == NULL) )\n    {\n    const mwSize *dims = mxGetDimensions(matlabMatrix);\n    return cx_cube(armaGetCubePr(matlabMatrix, copy_aux_mem, strict), zeros(dims[0], dims[1], dims[2]));\n    }\n  else if( (mxGetPr(matlabMatrix) == NULL) && (mxGetPi(matlabMatrix) != NULL) )\n    {\n    const mwSize *dims = mxGetDimensions(matlabMatrix);\n    return cx_cube(zeros(dims[0], dims[1], dims[2]), armaGetCubePi(matlabMatrix, copy_aux_mem, strict));\n    }\n  else\n    {\n    mexErrMsgTxt(\"No data available.\");\n    return cx_cube();\n    }\n  }  \n  \n// return real valued cube to Matlab/Octave\ntemplate<class Type>\ninline\nvoid\narmaSetCubeData(mxArray *matlabMatrix, const Cube<Type>& armaCube) \n  {\n        Type *dst_pointer = (Type*)mxGetData(matlabMatrix);\n  const Type *src_pointer = (Type*)armaCube.memptr();\n    \n  std::memcpy(dst_pointer, src_pointer, sizeof(Type)*armaCube.n_elem); \n  }\n\n  \n// Return double real valued cube to Matlab/Octave\ninline\nvoid\narmaSetCubePr(mxArray *matlabMatrix, const Cube<double>& armaCube) \n  {\n        double *dst_pointer = mxGetPr(matlabMatrix);\n  const double *src_pointer = armaCube.memptr();\n    \n  std::memcpy(dst_pointer, src_pointer, sizeof(double)*armaCube.n_elem); \n  }\n\n  \n// Return imaginary valued cube to Matlab/Octave.\ntemplate<class Type>\ninline\nvoid\narmaSetImagCubeData(mxArray *matlabMatrix, const Cube<Type>& armaCube)\n  {\n        Type *dst_pointer = (Type*)mxGetImagData(matlabMatrix);\n  const Type *src_pointer = (Type*)armaCube.memptr();\n  \n  std::memcpy(dst_pointer, src_pointer, sizeof(Type)*armaCube.n_elem);\n  }\n\n  \n// Return double imaginary valued matrix to Matlab/Octave\ninline\nvoid\narmaSetCubePi(mxArray *matlabMatrix, const Cube<double>& armaCube)\n  {\n        double *dst_pointer = mxGetPi(matlabMatrix);\n  const double *src_pointer = armaCube.memptr();\n    \n  std::memcpy(dst_pointer, src_pointer, sizeof(double)*armaCube.n_elem); \n  }\n\n// Return double complex cube to Matlab/Octave.\nvoid\narmaSetCubeCx(mxArray *matlabMatrix, const cx_cube& armaCube)\n  {\n  armaSetCubePr(matlabMatrix, real(armaCube));\n  armaSetCubePi(matlabMatrix, imag(armaCube));\n  }\n\n\n// Sparse matrices\n\n\n// Get sparse matrix from Matlab/Octave.\ntemplate<class Type>\ninline\nSpMat<Type>\narmaGetSparseData(const mxArray *matlabMatrix, bool sort_locations = false)\n  {\n  if(!mxIsSparse(matlabMatrix))\n    {\n    mexErrMsgTxt(\"Matrix is not sparse.\");\n    return SpMat<Type>();\n    }\n  else\n    {\n    Type *pr = (Type *)mxGetData(matlabMatrix);\n    \n    if(pr == NULL)\n      {\n      mexErrMsgTxt(\"No data available.\");\n      return SpMat<Type>();\n      }\n    \n    mwIndex *jc = mxGetJc(matlabMatrix);\n    mwIndex *ir = mxGetIr(matlabMatrix);\n\n    mwSize  m = mxGetM(matlabMatrix);\n    mwSize  n = mxGetN(matlabMatrix);\n    \n    mwSize  non_zero = mxGetNzmax(matlabMatrix);\n\n    umat locations = zeros<umat>(2,non_zero);\n    Col<Type> values = zeros< Col<Type> >(non_zero);\n    mwSize  row = 0;\n    \n    for(mwSize col = 0; col < n ; col++) \n      {\n\n      mwIndex starting_row_index = jc[col]; \n      mwIndex stopping_row_index = jc[col+1]; \n      \n      if (starting_row_index == stopping_row_index) \n        {\n        // End of matrix when jc[col] == jc[col+1]\n        continue;\n        }\n      else \n        {\n        for (mwIndex current_row_index = starting_row_index; current_row_index < stopping_row_index; current_row_index++) \n          {\n          values[row]=pr[row];\n          locations.at(0,row)=ir[current_row_index];\n          locations.at(1,row)=col;\n          row++;\n          }\n        }\n      }\n    \n    return SpMat<Type>(locations, values, m, n, sort_locations);\n    }\n  }\n\n\n// Get double valued sparse matrix from Matlab/Octave.\ninline\nSpMat<double>\narmaGetSparseMatrix(const mxArray *matlabMatrix, bool sort_locations = false)\n  {\n  if(!mxIsSparse(matlabMatrix))\n    {\n    mexErrMsgTxt(\"Matrix is not sparse.\");\n    return SpMat<double>();\n    }\n  else\n    {\n    double  *pr = mxGetPr(matlabMatrix);\n    \n    if(pr == NULL)\n      {\n      mexErrMsgTxt(\"No data available.\");\n      return SpMat<double>();\n      }\n    \n    mwIndex *jc = mxGetJc(matlabMatrix);\n    mwIndex *ir = mxGetIr(matlabMatrix);\n\n    mwSize  m = mxGetM(matlabMatrix);\n    mwSize  n = mxGetN(matlabMatrix);\n    \n    mwSize  non_zero = mxGetNzmax(matlabMatrix);\n\n    umat locations = zeros<umat>(2,non_zero);\n    Col<double> values = zeros< Col<double> >(non_zero);\n\n    mwSize  row = 0;\n     \n    for(mwSize col = 0; col < n ; col++) \n      {\n     \n      mwIndex starting_row_index = jc[col]; \n      mwIndex stopping_row_index = jc[col+1]; \n      \n      if (starting_row_index == stopping_row_index) \n        {\n        // End of matrix when jc[col] == jc[col+1]\n        continue;\n        }\n      else \n        {\n        for (mwIndex current_row_index = starting_row_index; current_row_index < stopping_row_index ; current_row_index++) \n          {\n          values[row]=pr[row];\n          locations.at(0,row)=ir[current_row_index];\n          locations.at(1,row)=col;\n          row++;\n          }\n        }\n\n      }\n    return SpMat<double>(locations, values, m, n, sort_locations);\n    }\n  }\n  \n  \n// Get imaginary sparse matrix from Matlab/Octave.\ntemplate<class Type>\ninline\nSpMat<Type>\narmaGetSparseImagData(const mxArray *matlabMatrix, bool sort_locations = false)\n  {\n  if(!mxIsSparse(matlabMatrix))\n    {\n    mexErrMsgTxt(\"Matrix is not sparse.\");\n    return SpMat<Type>();\n    }\n  else\n    {\n    Type *pi = (Type *)mxGetImagData(matlabMatrix);\n    \n    if(pi == NULL)\n      {\n      mexErrMsgTxt(\"No data available.\");\n      return SpMat<Type>();\n      }\n    \n    mwIndex *jc = mxGetJc(matlabMatrix);\n    mwIndex *ir = mxGetIr(matlabMatrix);\n\n    mwSize  m = mxGetM(matlabMatrix);\n    mwSize  n = mxGetN(matlabMatrix);\n    \n    mwSize  non_zero = mxGetNzmax(matlabMatrix);\n\n    umat locations = zeros<umat>(2,non_zero);\n    Col<Type> values = zeros< Col<Type> >(non_zero);\n    mwSize row = 0;\n    \n    for(mwSize col = 0; col < n ; col++) \n      {\n      mwIndex starting_row_index = jc[col]; \n      mwIndex stopping_row_index = jc[col+1]; \n      \n      if (starting_row_index == stopping_row_index) \n        {\n        // End of matrix when jc[col] == jc[col+1]\n        continue;\n        }\n      else \n        {\n        for (mwIndex current_row_index = starting_row_index; current_row_index < stopping_row_index; current_row_index++) \n          {\n          values[row]=pi[row];\n          locations.at(0,row)=ir[current_row_index];\n          locations.at(1,row)=col;\n          row++;\n          }\n        }\n      }\n    \n    return SpMat<Type>(locations, values, m, n, sort_locations);\n    }\n  }\n\n\n// Get imaginary double valued sparse matrix from Matlab/Octave.\ninline\nSpMat<double>\narmaGetSparseImagMatrix(const mxArray *matlabMatrix, bool sort_locations = false)\n  {\n  if(!mxIsSparse(matlabMatrix))\n    {\n    mexErrMsgTxt(\"Matrix is not sparse.\");\n    return SpMat<double>();\n    }\n  else\n    {\n    double  *pi = mxGetPi(matlabMatrix);\n    \n    if(pi == NULL)\n      {\n      mexErrMsgTxt(\"No data available.\");\n      return SpMat<double>();\n      }\n    \n    mwIndex *jc = mxGetJc(matlabMatrix);\n    mwIndex *ir = mxGetIr(matlabMatrix);\n\n    mwSize  m = mxGetM(matlabMatrix);\n    mwSize  n = mxGetN(matlabMatrix);\n    \n    mwSize  non_zero = mxGetNzmax(matlabMatrix);\n\n    umat locations = zeros<umat>(2,non_zero);\n    Col<double> values = zeros< Col<double> >(non_zero);\n     \n    mwSize row = 0;\n    \n    for(mwSize col = 0; col < n ; col++) \n      {\n      mwIndex starting_row_index = jc[col]; \n      mwIndex stopping_row_index = jc[col+1]; \n      \n      if (starting_row_index == stopping_row_index) \n        {\n        // End of matrix when jc[col] == jc[col+1]\n        continue;\n        }\n      else \n        {\n        for (mwIndex current_row_index = starting_row_index; current_row_index < stopping_row_index; current_row_index++) \n          {\n          values[row]=pi[row];\n          locations.at(0,row)=ir[current_row_index];\n          locations.at(1,row)=col;\n          row++;\n          }\n        }\n      }\n    \n    return SpMat<double>(locations, values, m, n, sort_locations);\n    }\n  }  \n  \n  \n// Return sparse matrix to matlab\ninline\nvoid\narmaSetSparsePr(mxArray *matlabMatrix, const SpMat<double>& armaMatrix)\n  {\n  double  *sr  = mxGetPr(matlabMatrix);\n  mwIndex *irs = mxGetIr(matlabMatrix);\n  mwIndex *jcs = mxGetJc(matlabMatrix);\n    \n  mwSize n_nonzero = armaMatrix.n_nonzero;\n  mwSize n_cols    = armaMatrix.n_cols;\n\n  for (mwIndex j = 0; j < n_nonzero; j++)\n    {\n    sr[j]  = armaMatrix.values[j];\n    irs[j] = armaMatrix.row_indices[j];\n    }\n  for (mwIndex j = 0; j <= n_cols; j++)\n    {\n    jcs[j] = armaMatrix.col_ptrs[j];\n    }\n  }\n\n\n// Return sparse matrix to matlab as imaginary part\ninline\nvoid\narmaSetSparsePi(mxArray *matlabMatrix, const SpMat<double>& armaMatrix)\n  {\n  double  *si  = mxGetPi(matlabMatrix);\n  mwIndex *irs = mxGetIr(matlabMatrix);\n  mwIndex *jcs = mxGetJc(matlabMatrix);\n    \n  mwSize n_nonzero = armaMatrix.n_nonzero;\n  mwSize n_cols    = armaMatrix.n_cols;\n\n  for (mwIndex j = 0; j < n_nonzero; j++)\n    {\n    si[j]  = armaMatrix.values[j];\n    irs[j] = armaMatrix.row_indices[j];\n    }\n  for (mwIndex j = 0; j <= n_cols; j++)\n    {\n    jcs[j] = armaMatrix.col_ptrs[j];\n    }\n  }\n\n\n// Create matlab side matrices\n\n\n// Create 2-D Matlab/Octave matrix\ninline\nmxArray*\narmaCreateMxMatrix(const mwSize n_rows, const mwSize n_cols, const mxClassID mx_type = mxDOUBLE_CLASS, const mxComplexity mx_complexity = mxREAL)\n  {\n  mxArray *temp = mxCreateNumericMatrix(n_rows, n_cols, mx_type, mx_complexity);\n  \n  if(temp == NULL)\n    {\n    mexErrMsgTxt(\"Could not create array.\");\n    return NULL;\n    }\n  else\n    {\n    return temp;\n    }\n  }\n\n\n// Create 3-D Matlab/Octave matrix (cube)\ninline\nmxArray*\narmaCreateMxMatrix(const mwSize n_rows, const mwSize n_cols, const mwSize n_slices, const mxClassID mx_type = mxDOUBLE_CLASS, const mxComplexity mx_complexity = mxREAL)\n  {\n  mwSize dims[3] = { n_rows, n_cols, n_slices };\n  \n  const mwSize n_dim = 3;\n  \n  mxArray *temp = mxCreateNumericArray(n_dim, dims, mx_type, mx_complexity);\n  \n  if(temp == NULL)\n    {\n    mexErrMsgTxt(\"Could not create array.\");\n    return NULL;\n    }\n  else\n    {\n    return temp;\n    }\n  }\n\n\ninline\nmxArray*\narmaCreateMxSparseMatrix(const mwSize n_rows,const mwSize n_cols,const mwSize n_nonzero,const mxComplexity mx_complexity = mxREAL)\n  {\n  mxArray *temp = mxCreateSparse(n_rows, n_cols, n_nonzero, mx_complexity);\n  \n  if(temp == NULL)\n    {\n    mexErrMsgTxt(\"Could not create array.\");\n    return NULL;\n    }\n  else\n    {\n    return temp;\n    }\n  }\n\n\n//Functions to write MAT files\ninline\nint\narmaWriteMatToFile(const char *filename, mat &armaMatrix, const char *name)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"wz\");\n  \n  int result;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not create MAT file.\");\n    return 0;\n    }\n  else\n    {\n    mxArray *temp = mxCreateDoubleMatrix(armaMatrix.n_rows, armaMatrix.n_cols, mxREAL);\n    armaSetPr(temp, armaMatrix);\n    result = matPutVariable(file, name, temp);\n    mxDestroyArray(temp); //Cleanup after writing MAT file\n    }\n  \n  matClose(file);\n  \n  return result;\n  }\n\n\ninline\nint\narmaWriteCxMatToFile(const char *filename, cx_mat &armaMatrix, const char *name)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"wz\");\n  \n  int result;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not create MAT file.\");\n    return 0;\n    }\n  else\n    {\n    mxArray *temp = mxCreateDoubleMatrix(armaMatrix.n_rows, armaMatrix.n_cols, mxCOMPLEX);\n    armaSetCx(temp, armaMatrix);\n    result = matPutVariable(file, name, temp);\n    mxDestroyArray(temp); //Cleanup after writing MAT file\n    }\n  \n  matClose(file);\n  \n  return result;\n  }\n\n\ninline\nint\narmaWriteCubeToFile(const char *filename, cube &armaCube, const char *name)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"wz\");\n  \n  int result;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not create MAT file.\");\n    return 0;\n    }\n  else\n    {\n    mxArray *temp = armaCreateMxMatrix(armaCube.n_rows, armaCube.n_cols, armaCube.n_slices, mxDOUBLE_CLASS, mxREAL);\n    armaSetCubePr(temp, armaCube);\n    result = matPutVariable(file, name, temp);\n    mxDestroyArray(temp); //Cleanup after writing MAT file\n    }\n  \n  matClose(file);\n  \n  return result;\n  }\n\n\ninline\nint\narmaWriteCxCubeToFile(const char *filename, cx_cube &armaCube, const char *name)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"wz\");\n  \n  int result;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not create MAT file.\");\n    return 0;\n    }\n  else\n    {\n    mxArray *temp = armaCreateMxMatrix(armaCube.n_rows, armaCube.n_cols, armaCube.n_slices, mxDOUBLE_CLASS, mxCOMPLEX);\n    armaSetCubeCx(temp, armaCube);\n    result = matPutVariable(file, name, temp);\n    mxDestroyArray(temp); //Cleanup after writing MAT file\n    }\n  \n  matClose(file);\n  \n  return result;\n  }\n\n\n//Functions to read and write matrices and cubes in MAT file format\ninline\nmat\narmaReadMatFromFile(const char *filename)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"r\");\n  \n  char buffer[64];\n  const char *name;\n  name = buffer;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not open MAT file.\");\n    return mat();\n    }\n  else\n    {\n    mat tmp = armaGetPr(matGetNextVariable(file,&name));\n    matClose(file);\n    \n    return tmp;\n    }\n  }\n\n\ninline\ncx_mat\narmaReadCxMatFromFile(const char *filename)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"r\");\n  \n  char buffer[64];\n  const char *name;\n  name = buffer;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not open MAT file.\");\n    return cx_mat();\n    }\n  else\n    {\n    cx_mat tmp = armaGetCx(matGetNextVariable(file, &name));\n    matClose(file);\n    \n    return tmp;\n    }\n  }\n\n\ninline\ncube\narmaReadCubeFromFile(const char *filename)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"r\");\n  \n  char buffer[64];\n  const char *name;\n  name = buffer;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not open MAT file.\");\n    return cube();\n    }\n  else\n    {\n    cube tmp = armaGetCubePr(matGetNextVariable(file,&name));\n    matClose(file);\n    \n    return tmp;\n    }\n  }\n\n\ninline\ncx_cube\narmaReadCxCubeFromFile(const char *filename)\n  {\n  MATFile *file;\n  file = matOpen(filename,\"r\");\n  \n  char buffer[64];\n  const char *name;\n  name = buffer;\n  \n  if(file == NULL)\n    {\n    mexErrMsgTxt(\"Could not open MAT file.\");\n    return cx_cube();\n    }\n  else\n    {\n    cx_cube tmp = armaGetCubeCx(matGetNextVariable(file,&name));\n    matClose(file);\n    \n    return tmp;\n    }\n  }\n", "meta": {"hexsha": "233c019bb55132ddac04bb335f0ab0340c6d3734", "size": 24361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/armadillo-6.600.5/mex_interface/armaMex.hpp", "max_stars_repo_name": "CRL-Technion/Variable-speed-Dubins-with-wind", "max_stars_repo_head_hexsha": "4c0cf8bb1ae11bcd78bffbba5392b892fee53608", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external/armadillo-6.600.5/mex_interface/armaMex.hpp", "max_issues_repo_name": "CRL-Technion/Variable-speed-Dubins-with-wind", "max_issues_repo_head_hexsha": "4c0cf8bb1ae11bcd78bffbba5392b892fee53608", "max_issues_repo_licenses": ["MIT"], "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/armadillo-6.600.5/mex_interface/armaMex.hpp", "max_forks_repo_name": "CRL-Technion/Variable-speed-Dubins-with-wind", "max_forks_repo_head_hexsha": "4c0cf8bb1ae11bcd78bffbba5392b892fee53608", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T13:26:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:26:17.000Z", "avg_line_length": 23.8132942326, "max_line_length": 168, "alphanum_fraction": 0.6466072821, "num_tokens": 6602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.037326884399142314, "lm_q1q2_score": 0.01520448673542403}}
{"text": "/* Copyright (c) 2016 - 2020, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#ifndef THERMAL_OPERATOR_HH\n#define THERMAL_OPERATOR_HH\n\n#include <MaterialProperty.hh>\n#include <ThermalOperatorBase.hh>\n\n#include <deal.II/matrix_free/matrix_free.h>\n\nnamespace adamantine\n{\n/**\n * This class is the operator associated with the heat equation, i.e., vmult\n * performs \\f$ dst = -\\nabla k \\nabla src \\f$.\n */\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nclass ThermalOperator final : public ThermalOperatorBase<dim, MemorySpaceType>\n{\npublic:\n  ThermalOperator(MPI_Comm const &communicator,\n                  std::shared_ptr<MaterialProperty<dim>> material_properties);\n\n  /**\n   * Associate the AffineConstraints<double> and the MatrixFree objects to the\n   * underlying Triangulation.\n   */\n  void reinit(dealii::DoFHandler<dim> const &dof_handler,\n              dealii::AffineConstraints<double> const &affine_constraints,\n              dealii::QGaussLobatto<1> const &quad) override;\n\n  void reinit(dealii::DoFHandler<dim> const &dof_handler,\n              dealii::AffineConstraints<double> const &affine_constraints,\n              dealii::QGauss<1> const &quad) override;\n\n  /**\n   * Compute the inverse of the mass matrix and update the material properties.\n   */\n  void compute_inverse_mass_matrix(\n      dealii::DoFHandler<dim> const &dof_handler,\n      dealii::AffineConstraints<double> const &affine_constraints) override;\n\n  /**\n   * Clear the MatrixFree object and resize the inverse of the mass matrix to\n   * zero.\n   */\n  void clear();\n\n  dealii::types::global_dof_index m() const override;\n\n  dealii::types::global_dof_index n() const override;\n\n  /**\n   * Return a shared pointer to the inverse of the mass matrix.\n   */\n  std::shared_ptr<dealii::LA::distributed::Vector<double, MemorySpaceType>>\n  get_inverse_mass_matrix() const override;\n\n  /**\n   * Return a shared pointer to the underlying MatrixFree object.\n   */\n  dealii::MatrixFree<dim, double> const &get_matrix_free() const;\n\n  void vmult(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n             dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                 &src) const override;\n\n  void Tvmult(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n              dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                  &src) const override;\n\n  void vmult_add(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n                 dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                     &src) const override;\n\n  void Tvmult_add(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n                  dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                      &src) const override;\n\n  void\n  jacobian_vmult(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n                 dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                     &src) const override;\n\n  void initialize_dof_vector(\n      dealii::LA::distributed::Vector<double, MemorySpaceType> &vector)\n      const override;\n\n  /**\n   * Evaluate the material properties for a given state field.\n   */\n  void evaluate_material_properties(\n      dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> const\n          &state) override;\n\n  /**\n   * Return the value of \\f$ \\frac{1}{\\rho C_p} \\f$ for a given cell.\n   */\n  double get_inv_rho_cp(\n      typename dealii::DoFHandler<dim>::cell_iterator const &) const override;\n\nprivate:\n  /**\n   * Apply the operator on a given set of quadrature points.\n   */\n  void 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  /**\n   * MPI communicator.\n   */\n  MPI_Comm const &_communicator;\n  /**\n   * Data to configure the MatrixFree object.\n   */\n  typename dealii::MatrixFree<dim, double>::AdditionalData _matrix_free_data;\n  /**\n   * Store the \\f$ \\frac{1}{\\rho C_p}\\f$ coefficient.\n   */\n  dealii::Table<2, dealii::VectorizedArray<double>> _inv_rho_cp;\n  /**\n   * Table of thermal conductivity coefficient.\n   */\n  dealii::Table<2, dealii::VectorizedArray<double>> _thermal_conductivity;\n  /**\n   * Material properties associated with the domain.\n   */\n  std::shared_ptr<MaterialProperty<dim>> _material_properties;\n  /**\n   * Underlying MatrixFree object.\n   */\n  dealii::MatrixFree<dim, double> _matrix_free;\n  /**\n   * The inverse of the mass matrix is computed using an inexact Gauss-Lobatto\n   * quadrature. This inexact quadrature makes the mass matrix and therefore\n   * also its inverse, a diagonal matrix.\n   */\n  std::shared_ptr<dealii::LA::distributed::Vector<double, MemorySpaceType>>\n      _inverse_mass_matrix;\n  /**\n   * Map between the cell iterator and the position in _inv_rho_cp table.\n   */\n  std::map<typename dealii::DoFHandler<dim>::cell_iterator,\n           std::pair<unsigned int, unsigned int>>\n      _cell_it_to_mf_cell_map;\n};\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline dealii::types::global_dof_index\nThermalOperator<dim, fe_degree, MemorySpaceType>::m() const\n{\n  return _matrix_free.get_vector_partitioner()->size();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline dealii::types::global_dof_index\nThermalOperator<dim, fe_degree, MemorySpaceType>::n() const\n{\n  return _matrix_free.get_vector_partitioner()->size();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline std::shared_ptr<dealii::LA::distributed::Vector<double, MemorySpaceType>>\nThermalOperator<dim, fe_degree, MemorySpaceType>::get_inverse_mass_matrix()\n    const\n{\n  return _inverse_mass_matrix;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline dealii::MatrixFree<dim, double> const &\nThermalOperator<dim, fe_degree, MemorySpaceType>::get_matrix_free() const\n{\n  return _matrix_free;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline void ThermalOperator<dim, fe_degree, MemorySpaceType>::jacobian_vmult(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  vmult(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline void\nThermalOperator<dim, fe_degree, MemorySpaceType>::initialize_dof_vector(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &vector) const\n{\n  _matrix_free.initialize_dof_vector(vector);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline double ThermalOperator<dim, fe_degree, MemorySpaceType>::get_inv_rho_cp(\n    typename dealii::DoFHandler<dim>::cell_iterator const &cell) const\n{\n  auto cell_comp_pair = _cell_it_to_mf_cell_map.find(cell);\n  ASSERT(cell_comp_pair != _cell_it_to_mf_cell_map.end(), \"Internal error\");\n\n  return _inv_rho_cp(cell_comp_pair->second.first,\n                     0)[cell_comp_pair->second.second];\n}\n\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "4a76f4023f56f2b30cdb17ae20df841b9589f445", "size": 7346, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/ThermalOperator.hh", "max_stars_repo_name": "stvdwtt/adamantine", "max_stars_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/ThermalOperator.hh", "max_issues_repo_name": "stvdwtt/adamantine", "max_issues_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/ThermalOperator.hh", "max_forks_repo_name": "stvdwtt/adamantine", "max_forks_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1674418605, "max_line_length": 80, "alphanum_fraction": 0.7161720664, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.031618770804652654, "lm_q1q2_score": 0.015192145197719265}}
{"text": "//============================================================================\n// Name         : dnatransformationparameters.hpp\n// Author       : Roger Fraser\n// Contributors : Joshua Batchelor\n// Version      : 1.00\n// Copyright    : Copyright 2017 Geoscience Australia\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// Description  : Declaration/definition of 7/14 parameters\n//============================================================================\n\n#ifndef DNATRANSFORM_PARAM_H_\n#define DNATRANSFORM_PARAM_H_\n\n#if defined(_MSC_VER)\n\t#if defined(LIST_INCLUDES_ON_BUILD) \n\t\t#pragma message(\"  \" __FILE__)\n\t#endif\n#endif\n\n#include <string>\n#include <iomanip>\n#include <sstream>\n#include <boost/exception_ptr.hpp>\n\n#include <include/parameters/dnaepsg.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nusing namespace dynadjust::epsg;\n\nnamespace dynadjust {\nnamespace datum_parameters {\n\ntypedef enum\n{\n\t__paramForward__ = 0,\n\t__paramReverse__ = 1\n} transformationDirection;\n\ntypedef enum\n{\n\t__static_to_static__ =   0,\n\t__static_to_dynamic__ =  1,\n\t__static_to_step__ =     2,\n\t__dynamic_to_step__ =    3,\n\t__dynamic_to_static__ =  4,\n\t__dynamic_to_dynamic__ = 5,\n\t__step_to_dynamic__ =    6,\n\t__step_to_static__ =     7,\n\t__plate_motion_model__ = 8\n} transformationType;\n\ntypedef enum\n{\n\t__frame_frame_same__ = 0,\n\t__frame_frame_diff__ = 1\n} frameSimilarity;\n\ntypedef enum\n{\n\t__epoch_epoch_same__ = 0,\n\t__epoch_epoch_diff__ = 1\n} epochSimilarity;\n\n\ntypedef struct transformation_parameter_set_ {\n\tuint32_uint32_pair\t\t\tfrom_to_;\t\t\t\t// integer epsg codes for 'from' and 'to' datums\n\tdouble\t\t\t\t\t\tparameters_[14];\t\t// the transformation parameters\n\tdouble\t\t\t\t\t\treference_epoch_;\t\t// reference epoch for the parameters\n\tUINT32\t\t\t\t\t\treference_frame_;\t\t// reference frame for the parameters\n\ttransformationDirection\t\tparamDirection_;\t\t// the direction of the current set\n\tvoid reverse() {\n\t\tparameters_[0] *= -1.;\n\t\tparameters_[1] *= -1.;\n\t\tparameters_[2] *= -1.;\n\t\tparameters_[3] *= -1.;\n\t\tparameters_[4] *= -1.;\n\t\tparameters_[5] *= -1.;\n\t\tparameters_[6] *= -1.;\n\t\tparameters_[7] *= -1.;\n\t\tparameters_[8] *= -1.;\n\t\tparameters_[9] *= -1.;\n\t\tparameters_[10] *= -1.;\n\t\tparameters_[11] *= -1.;\n\t\tparameters_[12] *= -1.;\n\t\tparameters_[13] *= -1.;\n\t}\n\tvoid add(const double* parameters) {\n\t\tparameters_[0] += parameters[0];\n\t\tparameters_[1] += parameters[1];\n\t\tparameters_[2] += parameters[2];\n\t\tparameters_[3] += parameters[3];\n\t\tparameters_[4] += parameters[4];\n\t\tparameters_[5] += parameters[5];\n\t\tparameters_[6] += parameters[6];\n\t\tparameters_[7] += parameters[7];\n\t\tparameters_[8] += parameters[8];\n\t\tparameters_[9] += parameters[9];\n\t\tparameters_[10] += parameters[10];\n\t\tparameters_[11] += parameters[11];\n\t\tparameters_[12] += parameters[12];\n\t\tparameters_[13] += parameters[13];\n\t}\n} transformation_parameter_set;\n\ntypedef vector<transformation_parameter_set> vtransparams;\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// TODO - This file uses hard-coded values for defining transformation parameters!\n// The most suitable approach is to load transformation parameters from an\n// authoritative file.\n////////////////////////////////////////////////////////////////////////////////////\n\n////////////////////////////////////////////////////////////////////////////////////\n//             SPECIAL NOTE ON ROTATION RATES FOR IERS PARAMETERS\n//         ----------------------------------------------------------\n//\n// There are two different ways of applying the sign conventions for the rotations.\n// In both cases a positive rotation is an anti-clockwise rotation, when viewed along\n// the positive axis towards the origin but:\n//\n//   1. The IERS assumes the rotations to be of the points around the \n//      cartesian axes, while;\n//   2. The method historically used in Australia assumes the rotations \n//      to be of the Cartesian axes around the points.\n//\n// Although these two conventions exist, to enforce the property that all rotations \n// describe anticlockwise rotation as positive when viewed along the axis towards the \n// origin, the rotation of the coordinate axes around the points should be a \n// skew-symmetric matrix with the opposite sign to the rotation of the point(s)\n// around the coordinate axis.\n//\n// To avoid confusion and to achieve consistency in the implementation of the \n// transformation functions, all published IERS rotations and associated rotation rates\n// have been reversed.\n//\n////////////////////////////////////////////////////////////////////////////////////\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// ITRF2000 <-> ITRF...\n// http://itrf.ensg.ign.fr/doc_ITRF/Transfo-ITRF2000_ITRFs.txt\n\n////////////////////////////////////////////////////////////////////////////////////\n//             SPECIAL NOTE ON IERS PARAMETERS for ITRF2000 -> ITRFxx\n//         ----------------------------------------------------------\n//\n// Despite what the website says, the linear values for translation are in centimetres,\n// not millimetres.\n//\n// To avoid confusion and to achieve consistency in the implementation of the \n// transformation functions, all published IERS translations and associated \n// translation rates have been converted to millimetres.\n//\n////////////////////////////////////////////////////////////////////////////////////\n\n// ITRF 2000 -> ITRF 1997\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1997_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1997_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1997_<T, U>::reference_epoch = 1997.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1997_<T, U>::transformationParameters[14] =\n{\n\t  6.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t  6.1,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-18.5,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 1.55,\t\t// scale (ppb)\n\t  0.0,\t\t// x rotation (milli-arc-seconds)\n\t  0.0,\t\t// y rotation (milli-arc-seconds)\n\t  0.0,\t\t// z rotation (milli-arc-seconds)\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1997 : public _itrf2000_to_itrf1997_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1996\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1996_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1996_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1996_<T, U>::reference_epoch = 1997.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1996_<T, U>::transformationParameters[14] =\n{\n\t  6.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t  6.1,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-18.5,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 1.55,\t\t// scale (ppb)\n\t  0.0,\t\t// x rotation (milli-arc-seconds)\n\t  0.0,\t\t// y rotation (milli-arc-seconds)\n\t  0.0,\t\t// z rotation (milli-arc-seconds)\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1996 : public _itrf2000_to_itrf1996_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1994\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1994_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1994_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1994_<T, U>::reference_epoch = 1997.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1994_<T, U>::transformationParameters[14] =\n{\n\t  6.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t  6.1,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-18.5,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 1.55,\t\t// scale (ppb)\n\t  0.0,\t\t// x rotation (milli-arc-seconds)\n\t  0.0,\t\t// y rotation (milli-arc-seconds)\n\t  0.0,\t\t// z rotation (milli-arc-seconds)\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1994 : public _itrf2000_to_itrf1994_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1993\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1993_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1993_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1993_<T, U>::reference_epoch = 1988.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1993_<T, U>::transformationParameters[14] =\n{\n\t 12.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t  6.5,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-20.9,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 1.95,\t\t// scale (ppb)\n\t 0.39,\t\t// x rotation (milli-arc-seconds) - REVERSED\n\t-0.80,\t\t// y rotation (milli-arc-seconds) - REVERSED\n\t 1.14,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t -2.9,\t\t// x translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -0.2,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -0.6,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.11,\t\t// x rotation rate (milli-arc-seconds p/yr) - REVERSED\n\t 0.19,\t\t// y rotation rate (milli-arc-seconds p/yr) - REVERSED\n\t-0.07\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1993 : public _itrf2000_to_itrf1993_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1992\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1992_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1992_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1992_<T, U>::reference_epoch = 1988.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1992_<T, U>::transformationParameters[14] =\n{\n\t 14.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t 13.5,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-13.9,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 0.75,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.18,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1992\t: public _itrf2000_to_itrf1992_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1991\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1991_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1991_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1991_<T, U>::reference_epoch = 1988.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1991_<T, U>::transformationParameters[14] =\n{\n\t 26.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t 27.5,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-19.9,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 2.15,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.18,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1991\t: public _itrf2000_to_itrf1991_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1990\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1990_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1990_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1990_<T, U>::reference_epoch = 1988.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1990_<T, U>::transformationParameters[14] =\n{\n\t 24.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t 23.5,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-35.9,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 2.45,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.18,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1990 : public _itrf2000_to_itrf1990_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1989\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1989_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1989_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1989_<T, U>::reference_epoch = 1988.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1989_<T, U>::transformationParameters[14] =\n{\n\t 29.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t 47.5,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-73.9,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 5.85,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.18,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1989 : public _itrf2000_to_itrf1989_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> ITRF 1988\ntemplate <class T, class U>\nstruct _itrf2000_to_itrf1988_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_itrf1988_<T, U>::reference_frame = ITRF2000_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1988_<T, U>::reference_epoch = 1988.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_itrf1988_<T, U>::transformationParameters[14] =\n{\n\t 24.7,\t\t// x translation (millimetres) - CONVERTED FROM CM\n\t 11.5,\t\t// y translation (millimetres) - CONVERTED FROM CM\n\t-97.9,\t\t// z translation (millimetres) - CONVERTED FROM CM\n\t 8.95,\t\t// scale (ppb)\n\t-0.10,\t\t// x rotation (milli-arc-seconds) - REVERSED\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.18,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t -0.6,\t\t// y translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t -1.4,\t\t// z translation rate (millimetres p/yr) - CONVERTED FROM CM\n\t 0.01,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2000_ITRF1988 : public _itrf2000_to_itrf1988_<T, U>\n{\npublic:\n};\n\n////////////////////////////////////////////////////////////////////////////////////\n\n////////////////////////////////////////////////////////////////////////////////////\n// ITRF2005 <-> ITRF2000\n// http://itrf.ensg.ign.fr/doc_ITRF/Transfo-ITRF2005_ITRF2000.txt\n\n// ITRF 2005 -> ITRF 2000\ntemplate <class T, class U>\nstruct _itrf2005_to_itrf2000_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2005_to_itrf2000_<T, U>::reference_frame = ITRF2005_i;\n\ntemplate <class T, class U>\nconst T _itrf2005_to_itrf2000_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2005_to_itrf2000_<T, U>::transformationParameters[14] =\n{\n\t  0.1,\t\t// x translation (millimetres)\n\t -0.8,\t\t// y translation (millimetres)\n\t -5.8,\t\t// z translation (millimetres)\n\t 0.40,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.00,\t\t// z rotation (milli-arc-seconds)\n\n\t -0.2,\t\t// x translation rate (millimetres p/yr)\n\t  0.1,\t\t// y translation rate (millimetres p/yr)\n\t -1.8,\t\t// z translation rate (millimetres p/yr)\n\t 0.08,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t 0.00\t\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2005_ITRF2000 : public _itrf2005_to_itrf2000_<T, U>\n{\npublic:\n};\n////////////////////////////////////////////////////////////////////////////////////\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// ITRF2008 <-> ITRF...\n// http://itrf.ensg.ign.fr/doc_ITRF/Transfo-ITRF2008_ITRFs.txt\n\n// ITRF 2008 -> ITRF 2005\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf2005_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf2005_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf2005_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf2005_<T, U>::transformationParameters[14] =\n{\n\t -2.0,\t\t// x translation (millimetres). Note this differs from Zuheir's JOG paper DOI 10.1007/s00190-011-0444-4\n\t -0.9,\t\t// y translation (millimetres)\n\t -4.7,\t\t// z translation (millimetres)\n\t 0.94,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.00,\t\t// z rotation (milli-arc-seconds)\n\n\t  0.3,\t\t// x translation rate (millimetres p/yr)\n\t  0.0,\t\t// y translation rate (millimetres p/yr)\n\t  0.0,\t\t// z translation rate (millimetres p/yr)\n\t 0.00,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t 0.00\t\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF2005 : public _itrf2008_to_itrf2005_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 2000\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf2000_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf2000_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf2000_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf2000_<T, U>::transformationParameters[14] =\n{\n\t -1.9,\t\t// x translation (millimetres)\n\t -1.7,\t\t// y translation (millimetres)\n\t-10.5,\t\t// z translation (millimetres)\n\t 1.34,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.00,\t\t// z rotation (milli-arc-seconds)\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t  0.1,\t\t// y translation rate (millimetres p/yr)\n\t -1.8,\t\t// z translation rate (millimetres p/yr)\n\t 0.08,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t 0.00\t\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF2000 : public _itrf2008_to_itrf2000_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1997\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1997_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1997_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1997_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1997_<T, U>::transformationParameters[14] =\n{\n\t  4.8,\t\t// x translation (millimetres)\n\t  2.6,\t\t// y translation (millimetres)\n\t-33.2,\t\t// z translation (millimetres)\n\t 2.92,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1997 : public _itrf2008_to_itrf1997_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1996\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1996_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1996_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1996_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1996_<T, U>::transformationParameters[14] =\n{\n\t  4.8,\t\t// x translation (millimetres)\n\t  2.6,\t\t// y translation (millimetres)\n\t-33.2,\t\t// z translation (millimetres)\n\t 2.92,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1996 : public _itrf2008_to_itrf1996_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1994\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1994_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1994_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1994_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1994_<T, U>::transformationParameters[14] =\n{\n\t  4.8,\t\t// x translation (millimetres)\n\t  2.6,\t\t// y translation (millimetres)\n\t-33.2,\t\t// z translation (millimetres)\n\t 2.92,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1994 : public _itrf2008_to_itrf1994_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1993\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1993_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1993_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1993_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1993_<T, U>::transformationParameters[14] =\n{\n\t-24.0,\t\t// x translation (millimetres)\n\t  2.4,\t\t// y translation (millimetres)\n\t-38.6,\t\t// z translation (millimetres)\n\t 3.41,\t\t// scale (ppb)\n\t 1.71,\t\t// x rotation (milli-arc-seconds) - REVERSED\n\t 1.48,\t\t// y rotation (milli-arc-seconds) - REVERSED\n\t 0.30,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t -2.8,\t\t// x translation rate (millimetres p/yr)\n\t -0.1,\t\t// y translation rate (millimetres p/yr)\n\t -2.4,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.11,\t\t// x rotation rate (milli-arc-seconds p/yr) - REVERSED\n\t 0.19,\t\t// y rotation rate (milli-arc-seconds p/yr) - REVERSED\n\t-0.07\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1993 : public _itrf2008_to_itrf1993_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1992\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1992_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1992_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1992_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1992_<T, U>::transformationParameters[14] =\n{\n\t 12.8,\t\t// x translation (millimetres)\n\t  4.6,\t\t// y translation (millimetres)\n\t-41.2,\t\t// z translation (millimetres)\n\t 2.21,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1992 : public _itrf2008_to_itrf1992_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1991\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1991_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1991_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1991_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1991_<T, U>::transformationParameters[14] =\n{\n\t 24.8,\t\t// x translation (millimetres)\n\t 18.6,\t\t// y translation (millimetres)\n\t-47.2,\t\t// z translation (millimetres)\n\t 3.61,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1991 : public _itrf2008_to_itrf1991_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1990\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1990_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1990_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1990_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1990_<T, U>::transformationParameters[14] =\n{\n\t 22.8,\t\t// x translation (millimetres)\n\t 14.6,\t\t// y translation (millimetres)\n\t-63.2,\t\t// z translation (millimetres)\n\t 3.91,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1990 : public _itrf2008_to_itrf1990_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1989\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1989_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1989_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1989_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1989_<T, U>::transformationParameters[14] =\n{\n\t 27.8,\t\t// x translation (millimetres)\n\t 38.6,\t\t// y translation (millimetres)\n   -101.2,\t\t// z translation (millimetres)\n\t 7.31,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1989 : public _itrf2008_to_itrf1989_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> ITRF 1988\ntemplate <class T, class U>\nstruct _itrf2008_to_itrf1988_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_itrf1988_<T, U>::reference_frame = ITRF2008_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1988_<T, U>::reference_epoch = 2000.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_itrf1988_<T, U>::transformationParameters[14] =\n{\n\t 22.8,\t\t// x translation (millimetres)\n\t  2.6,\t\t// y translation (millimetres)\n   -125.2,\t\t// z translation (millimetres)\n\t10.41,\t\t// scale (ppb)\n\t-0.10,\t\t// x rotation (milli-arc-seconds) - REVERSED\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.06,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.2,\t\t// z translation rate (millimetres p/yr)\n\t 0.09,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2008_ITRF1988 : public _itrf2008_to_itrf1988_<T, U>\n{\npublic:\n};\n\n////////////////////////////////////////////////////////////////////////////////////\n\n////////////////////////////////////////////////////////////////////////////////////\n// ITRF2014 <-> ITRF2008\n// http://itrf.ensg.ign.fr/doc_ITRF/Transfo-ITRF2014_ITRFs.txt\n\n// ITRF 2014 -> ITRF 2008\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf2008_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf2008_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf2008_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf2008_<T, U>::transformationParameters[14] =\n{\n\t  1.6,\t\t// x translation (millimetres)\n\t  1.9,\t\t// y translation (millimetres)\n\t  2.4,\t\t// z translation (millimetres)\n\t-0.02,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.00,\t\t// z rotation (milli-arc-seconds)\n\t\n\t  0.0,\t\t// x translation rate (millimetres p/yr)\n\t  0.0,\t\t// y translation rate (millimetres p/yr)\n\t -0.1,\t\t// z translation rate (millimetres p/yr)\n\t 0.03,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t 0.00\t\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF2008 : public _itrf2014_to_itrf2008_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 2005\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf2005_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf2005_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf2005_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf2005_<T, U>::transformationParameters[14] =\n{\n\t  2.6,\t\t// x translation (millimetres)\n\t  1.0,\t\t// y translation (millimetres)\n\t -2.3,\t\t// z translation (millimetres)\n\t 0.92,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.00,\t\t// z rotation (milli-arc-seconds)\n\t \n\t  0.3,\t\t// x translation rate (millimetres p/yr)\n\t  0.0,\t\t// y translation rate (millimetres p/yr)\n\t -0.1,\t\t// z translation rate (millimetres p/yr)\n\t 0.03,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t 0.00\t\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF2005 : public _itrf2014_to_itrf2005_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 2000\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf2000_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf2000_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf2000_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf2000_<T, U>::transformationParameters[14] =\n{\n\t  0.7,\t\t// x translation (millimetres)\n\t  1.2,\t\t// y translation (millimetres)\n\t-26.1,\t\t// z translation (millimetres)\n\t 2.12,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t 0.00,\t\t// z rotation (milli-arc-seconds)\n\t \n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t  0.1,\t\t// y translation rate (millimetres p/yr)\n\t -1.9,\t\t// z translation rate (millimetres p/yr)\n\t 0.11,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t 0.00\t\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF2000 : public _itrf2014_to_itrf2000_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1997\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1997_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1997_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1997_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1997_<T, U>::transformationParameters[14] =\n{\n\t  7.4,\t\t// x translation (millimetres)\n\t -0.5,\t\t// y translation (millimetres)\n\t-62.8,\t\t// z translation (millimetres)\n\t 3.80,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.3,\t\t// z translation rate (millimetres p/yr)\n\t 0.12,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1997 : public _itrf2014_to_itrf1997_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1996\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1996_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1996_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1996_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1996_<T, U>::transformationParameters[14] =\n{\n\t  7.4,\t\t// x translation (millimetres)\n\t -0.5,\t\t// y translation (millimetres)\n\t-62.8,\t\t// z translation (millimetres)\n\t 3.80,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t \n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.3,\t\t// z translation rate (millimetres p/yr)\n\t 0.12,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1996 : public _itrf2014_to_itrf1996_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1994\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1994_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1994_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1994_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1994_<T, U>::transformationParameters[14] =\n{\n\t  7.4,\t\t// x translation (millimetres)\n\t -0.5,\t\t// y translation (millimetres)\n\t-62.8,\t\t// z translation (millimetres)\n\t 3.80,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t \n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.3,\t\t// z translation rate (millimetres p/yr)\n\t 0.12,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1994 : public _itrf2014_to_itrf1994_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1993\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1993_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1993_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1993_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1993_<T, U>::transformationParameters[14] =\n{\n\t-50.4,\t\t// x translation (millimetres)\n\t  3.3,\t\t// y translation (millimetres)\n\t-60.2,\t\t// z translation (millimetres)\n\t 4.29,\t\t// scale (ppb)\n\t 2.81,\t\t// x rotation (milli-arc-seconds) - REVERSED\n\t 3.38,\t\t// y rotation (milli-arc-seconds) - REVERSED\n\t-0.40,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t \n\t -2.8,\t\t// x translation rate (millimetres p/yr)\n\t -0.1,\t\t// y translation rate (millimetres p/yr)\n\t -2.5,\t\t// z translation rate (millimetres p/yr)\n\t 0.12,\t\t// scale rate (ppb p/yr)\n\t 0.11,\t\t// x rotation rate (milli-arc-seconds p/yr) - REVERSED\n\t 0.19,\t\t// y rotation rate (milli-arc-seconds p/yr) - REVERSED\n\t-0.07\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1993 : public _itrf2014_to_itrf1993_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1992\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1992_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1992_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1992_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1992_<T, U>::transformationParameters[14] =\n{\n\t 15.4,\t\t// x translation (millimetres)\n\t  1.5,\t\t// y translation (millimetres)\n\t-70.8,\t\t// z translation (millimetres)\n\t 3.09,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t \n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.3,\t\t// z translation rate (millimetres p/yr)\n\t 0.12,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1992\t : public _itrf2014_to_itrf1992_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1991\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1991_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1991_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1991_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1991_<T, U>::transformationParameters[14] =\n{\n\t 27.4,\t\t// x translation (millimetres)\n\t 15.5,\t\t// y translation (millimetres)\n\t-76.8,\t\t// z translation (millimetres)\n\t 4.49,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t \n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.3,\t\t// z translation rate (millimetres p/yr)\n\t 0.12,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1991 : public _itrf2014_to_itrf1991_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1990\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1990_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1990_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1990_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1990_<T, U>::transformationParameters[14] =\n{\n\t 25.4,\t\t// x translation (millimetres)\n\t 11.5,\t\t// y translation (millimetres)\n\t-92.8,\t\t// z translation (millimetres)\n\t 4.79,\t\t// scale (ppb)\n\t 0.00,\t\t// x rotation (milli-arc-seconds)\n\t 0.00,\t\t// y rotation (milli-arc-seconds)\n\t-0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t \n\t  0.1,\t\t// x translation rate (millimetres p/yr)\n\t -0.5,\t\t// y translation rate (millimetres p/yr)\n\t -3.3,\t\t// z translation rate (millimetres p/yr)\n\t 0.12,\t\t// scale rate (ppb p/yr)\n\t 0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t 0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t-0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1990 : public _itrf2014_to_itrf1990_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1989\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1989_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1989_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1989_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1989_<T, U>::transformationParameters[14] =\n{\n\t  30.4,\t\t// x translation (millimetres)\n\t  35.5,\t\t// y translation (millimetres)\n\t-130.8,\t\t// z translation (millimetres)\n\t  8.19,\t\t// scale (ppb)\n\t  0.00,\t\t// x rotation (milli-arc-seconds)\n\t  0.00,\t\t// y rotation (milli-arc-seconds)\n\t -0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t  \n\t   0.1,\t\t// x translation rate (millimetres p/yr)\n\t  -0.5,\t\t// y translation rate (millimetres p/yr)\n\t  -3.3,\t\t// z translation rate (millimetres p/yr)\n\t  0.12,\t\t// scale rate (ppb p/yr)\n\t  0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t  0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t -0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1989 : public _itrf2014_to_itrf1989_<T, U>\n{\npublic:\n};\n\n// ITRF 2014 -> ITRF 1988\ntemplate <class T, class U>\nstruct _itrf2014_to_itrf1988_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_itrf1988_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1988_<T, U>::reference_epoch = 2010.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_itrf1988_<T, U>::transformationParameters[14] =\n{\n\t  25.4,\t\t// x translation (millimetres)\n\t  -0.5,\t\t// y translation (millimetres)\n\t-154.8,\t\t// z translation (millimetres)\n\t 11.29,\t\t// scale (ppb)\n\t -0.10,\t\t// x rotation (milli-arc-seconds) - REVERSED\n\t  0.00,\t\t// y rotation (milli-arc-seconds)\n\t -0.26,\t\t// z rotation (milli-arc-seconds) - REVERSED\n\t  \n\t   0.1,\t\t// x translation rate (millimetres p/yr)\n\t  -0.5,\t\t// y translation rate (millimetres p/yr)\n\t  -3.3,\t\t// z translation rate (millimetres p/yr)\n\t  0.12,\t\t// scale rate (ppb p/yr)\n\t  0.00,\t\t// x rotation rate (milli-arc-seconds p/yr)\n\t  0.00,\t\t// y rotation rate (milli-arc-seconds p/yr)\n\t -0.02\t\t// z rotation rate (milli-arc-seconds p/yr) - REVERSED\n};\n\ntemplate <class T, class U>\nclass ITRF2014_ITRF1988 : public _itrf2014_to_itrf1988_<T, U>\n{\npublic:\n};\n\n////////////////////////////////////////////////////////////////////////////////////\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// ITRF2014 <-> GDA2020\n// PCG In-confidence PowerPoint (Perth PGC FTF March 2016)\n// file://C:\\Data\\GEODESY\\ICSM\\DATUM\\2016-03-09-pcg-perth\\GDA94toGDA2020Transformation.pptx\n//\n// Replaced by ICSM Release note (March 2017)\n// 'file://C:\\Data\\GEODESY\\ICSM\\DATUM\\GDA2020 media\\GDA2020 Release Note.docx'\n\n// ITRF2014 -> GDA2020\ntemplate <class T, class U>\nstruct _itrf2014_to_gda2020_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_gda2020_<T, U>::reference_frame = ITRF2014_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_gda2020_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_gda2020_<T, U>::transformationParameters[14] =\n{\n\t    0.0,\t// x translation (millimetres)\n\t    0.0,\t// y translation (millimetres)\n\t    0.0,\t// z translation (millimetres)\n\t    0.0,\t// scale (ppb)\n\t    0.0,\t// x rotation (milli-arc-seconds)\n\t    0.0,\t// y rotation (milli-arc-seconds)\n\t    0.0,\t// z rotation (milli-arc-seconds)\n\t    \n\t    0.0,\t// x translation rate (millimetres p/yr)\n\t    0.0,\t// y translation rate (millimetres p/yr)\n\t    0.0,\t// z translation rate (millimetres p/yr)\n\t    0.0,\t// scale rate (ppb p/yr)\n\t1.50379,\t// x rotation rate (milli-arc-seconds p/yr)\n\t1.18346,\t// y rotation rate (milli-arc-seconds p/yr)\n\t1.20716\t\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2014_GDA2020 : public _itrf2014_to_gda2020_<T, U>\n{\npublic:\n};\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// PLATE MOTION MODELS\n\n// AUS\ntemplate <class T, class U>\nclass AUS_PLATE_MOTION_MODEL : public _itrf2014_to_gda2020_<T, U>\n{\npublic:\n};\n\n\n////////////////////////////////////////////////////////////////////////////////////\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// ITRFxxxx <-> GDA2020\n// Dawson Fraser\n// file://C:\\Data\\GEODESY\\ICSM\\DATUM\\gda2020-itrf-transformation-parameters.xlsx\n\n// ITRF1996 -> GDA2020\ntemplate <class T, class U>\nstruct _itrf1996_to_gda2020_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf1996_to_gda2020_<T, U>::reference_frame = GDA2020_i;\n\ntemplate <class T, class U>\nconst T _itrf1996_to_gda2020_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _itrf1996_to_gda2020_<T, U>::transformationParameters[14] =\n{\n\t-480.710,\t// x translation (millimetres)\n\t  75.160,\t// y translation (millimetres)\n\t 574.710,\t// z translation (millimetres)\n\t  6.9950,\t// scale (ppb)\n\t 10.2995,\t// x rotation (milli-arc-seconds)\n\t 21.7458,\t// y rotation (milli-arc-seconds)\n\t  9.8292,\t// z rotation (milli-arc-seconds)\n\n\t -21.800,\t// x translation rate (millimetres p/yr)\n\t   4.710,\t// y translation rate (millimetres p/yr)\n\t  26.270,\t// z translation rate (millimetres p/yr)\n\t  0.3880,\t// scale rate (ppb p/yr)\n\t  2.0203,\t// x rotation rate (milli-arc-seconds p/yr)\n\t  2.1735,\t// y rotation rate (milli-arc-seconds p/yr)\n\t  1.6290\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF1996_GDA2020 : public _itrf1996_to_gda2020_<T, U>\n{\npublic:\n};\n\n// ITRF1997 -> GDA2020\ntemplate <class T, class U>\nstruct _itrf1997_to_gda2020_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf1997_to_gda2020_<T, U>::reference_frame = GDA2020_i;\n\ntemplate <class T, class U>\nconst T _itrf1997_to_gda2020_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _itrf1997_to_gda2020_<T, U>::transformationParameters[14] =\n{\n\t-176.680,\t// x translation (millimetres)\n\t -29.130,\t// y translation (millimetres)\n\t 226.990,\t// z translation (millimetres)\n\t -3.1170,\t// scale (ppb)\n\t  1.3427,\t// x rotation (milli-arc-seconds)\n\t  6.1880,\t// y rotation (milli-arc-seconds)\n\t  3.9809,\t// z rotation (milli-arc-seconds)\n\n\t  -8.600,\t// x translation rate (millimetres p/yr)\n\t   0.360,\t// y translation rate (millimetres p/yr)\n\t  11.250,\t// z translation rate (millimetres p/yr)\n\t  0.0070,\t// scale rate (ppb p/yr)\n\t  1.6394,\t// x rotation rate (milli-arc-seconds p/yr)\n\t  1.5198,\t// y rotation rate (milli-arc-seconds p/yr)\n\t  1.3801\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF1997_GDA2020 : public _itrf1997_to_gda2020_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> GDA2020\ntemplate <class T, class U>\nstruct _itrf2000_to_gda2020_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_gda2020_<T, U>::reference_frame = GDA2020_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_gda2020_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_gda2020_<T, U>::transformationParameters[14] =\n{\n    -105.520,\t// x translation (millimetres)\n      51.580,\t// y translation (millimetres)\n     231.680,\t// z translation (millimetres)\n      3.5500,\t// scale (ppb)\n      4.2175,\t// x rotation (milli-arc-seconds)\n      6.3941,\t// y rotation (milli-arc-seconds)\n      0.8617,\t// z rotation (milli-arc-seconds)\n    \n      -4.660,   // x translation rate (millimetres p/yr) \n       3.550,\t// y translation rate (millimetres p/yr)\n      11.240,\t// z translation rate (millimetres p/yr)\n      0.2490,\t// scale rate (ppb p/yr)\n      1.7454,\t// x rotation rate (milli-arc-seconds p/yr)\n      1.4868,\t// y rotation rate (milli-arc-seconds p/yr)\n      1.2240\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2000_GDA2020 : public _itrf2000_to_gda2020_<T, U>\n{\npublic:\n};\n\n// ITRF 2005 -> GDA2020\ntemplate <class T, class U>\nstruct _itrf2005_to_gda2020_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2005_to_gda2020_<T, U>::reference_frame = GDA2020_i;\n\ntemplate <class T, class U>\nconst T _itrf2005_to_gda2020_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _itrf2005_to_gda2020_<T, U>::transformationParameters[14] =\n{\n      40.320,\t// x translation (millimetres)\n     -33.850,\t// y translation (millimetres)\n     -16.720,\t// z translation (millimetres)\n      4.2860,\t// scale (ppb)\n     -1.2893,\t// x rotation (milli-arc-seconds)\n     -0.8492,\t// y rotation (milli-arc-seconds)\n     -0.3342,\t// z rotation (milli-arc-seconds)\n    \n       2.250,\t// x translation rate (millimetres p/yr) \n      -0.620,\t// y translation rate (millimetres p/yr)\n      -0.560,\t// z translation rate (millimetres p/yr)\n      0.2940,\t// scale rate (ppb p/yr)\n      1.4707,\t// x rotation rate (milli-arc-seconds p/yr)\n      1.1443,\t// y rotation rate (milli-arc-seconds p/yr)\n      1.1701\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2005_GDA2020 : public _itrf2005_to_gda2020_<T, U>\n{\npublic:\n};\n\n// ITRF 2008 -> GDA2020\ntemplate <class T, class U>\nstruct _itrf2008_to_gda2020_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_gda2020_<T, U>::reference_frame = GDA2020_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_gda2020_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_gda2020_<T, U>::transformationParameters[14] =\n{\n      13.790,\t// x translation (millimetres)\n       4.550,\t// y translation (millimetres)\n      15.220,\t// z translation (millimetres)\n      2.5500,\t// scale (ppb)\n      0.2808,\t// x rotation (milli-arc-seconds)\n      0.2677,\t// y rotation (milli-arc-seconds)\n     -0.4638,\t// z rotation (milli-arc-seconds)\n      \n       1.420,   // x translation rate (millimetres p/yr) \n       1.340,\t// y translation rate (millimetres p/yr)\n       0.900,\t// z translation rate (millimetres p/yr)\n      0.1090,\t// scale rate (ppb p/yr)\n      1.5461,\t// x rotation rate (milli-arc-seconds p/yr)\n      1.1820,\t// y rotation rate (milli-arc-seconds p/yr)\n      1.1551\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2008_GDA2020 : public _itrf2008_to_gda2020_<T, U>\n{\npublic:\n};\n\n////////////////////////////////////////////////////////////////////////////////////\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// GDA94 <-> GDA2020\n// PCG In-confidence PowerPoint (Perth PGC FTF March 2016)\n// file://C:\\Data\\GEODESY\\ICSM\\DATUM\\2016-03-09-pcg-perth\\GDA94toGDA2020Transformation.pptx\n//\n// Replaced by ICSM Release note (March 2017)\n// 'file://C:\\onedrive\\GEODESY\\ICSM\\DATUM\\GDA2020%20media\\GDA2020%20Release%20Note.docx'\n\n// GDA94 -> GDA2020\ntemplate <class T, class U>\nstruct _gda94_to_gda2020_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _gda94_to_gda2020_<T, U>::reference_frame = GDA2020_i;\n\ntemplate <class T, class U>\nconst T _gda94_to_gda2020_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _gda94_to_gda2020_<T, U>::transformationParameters[14] =\n{\n\t   61.55,\t// x translation (millimetres)\n\t  -10.87,\t// y translation (millimetres)\n\t  -40.19,\t// z translation (millimetres)\n\t  -9.994,\t// scale (ppb)\n\t-39.4924,\t// x rotation (milli-arc-seconds)\n\t-32.7221,\t// y rotation (milli-arc-seconds)\n\t-32.8979,\t// z rotation (milli-arc-seconds)\n\n\t\t 0.0,\t// x translation rate (millimetres p/yr)\n\t\t 0.0,\t// y translation rate (millimetres p/yr)\n\t\t 0.0,\t// z translation rate (millimetres p/yr)\n\t\t 0.0,\t// scale rate (ppb p/yr)\n\t\t 0.0,\t// x rotation rate (milli-arc-seconds p/yr)\n\t\t 0.0,\t// y rotation rate (milli-arc-seconds p/yr)\n\t\t 0.0\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass GDA94_GDA2020 : public _gda94_to_gda2020_<T, U>\n{\npublic:\n};\n\n// ITRF2014 at epoch 2020.0 -> GDA94.  \n// Effectively, these are the same as GDA2020 -> GDA94 parameters, plus\n// the rotation rates from the Australian Plate Motion Model.\ntemplate <class T, class U>\nstruct _itrf2014_to_gda94_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2014_to_gda94_<T, U>::reference_frame = GDA94_i;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_gda94_<T, U>::reference_epoch = 2020.0;\n\ntemplate <class T, class U>\nconst T _itrf2014_to_gda94_<T, U>::transformationParameters[14] =\n{\n\t  -61.55,\t// x translation (millimetres)\n\t   10.87,\t// y translation (millimetres)\n\t   40.19,\t// z translation (millimetres)\n\t   9.994,\t// scale (ppb)\n\t 39.4924,\t// x rotation (milli-arc-seconds)\n\t 32.7221,\t// y rotation (milli-arc-seconds)\n\t 32.8979,\t// z rotation (milli-arc-seconds)\n\n\t\t 0.0,\t// x translation rate (millimetres p/yr)\n\t\t 0.0,\t// y translation rate (millimetres p/yr)\n\t\t 0.0,\t// z translation rate (millimetres p/yr)\n\t\t 0.0,\t// scale rate (ppb p/yr)\n\t 1.50379,\t// x rotation rate (milli-arc-seconds p/yr)\n\t 1.18346,\t// y rotation rate (milli-arc-seconds p/yr)\n\t 1.20716\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2014_GDA94 : public _itrf2014_to_gda94_<T, U>\n{\npublic:\n};\n////////////////////////////////////////////////////////////////////////////////////\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// GDA94 <-> ITRF... (Dawson and Woods)\n// http://www.ga.gov.au/webtemp/image_cache/GA19050.pdf\n\n// ITRF 2008 -> GDA94\ntemplate <class T, class U>\nstruct _itrf2008_to_gda94_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2008_to_gda94_<T, U>::reference_frame = GDA94_i;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_gda94_<T, U>::reference_epoch = 1994.0;\n\ntemplate <class T, class U>\nconst T _itrf2008_to_gda94_<T, U>::transformationParameters[14] =\n{\n\t  -84.68,\t// x translation (millimetres)\n\t  -19.42,\t// y translation (millimetres)\n\t   32.01,\t// z translation (millimetres)\n\t  9.7100,\t// scale (ppb)\n\t -0.4254,\t// x rotation (milli-arc-seconds)\n\t  2.2578,\t// y rotation (milli-arc-seconds)\n\t  2.4015,\t// z rotation (milli-arc-seconds)\n\n\t   1.420,\t// x translation rate (millimetres p/yr)\n\t   1.340,\t// y translation rate (millimetres p/yr)\n\t   0.900,\t// z translation rate (millimetres p/yr)\n\t  0.1090,\t// scale rate (ppb p/yr)\n\t  1.5461,\t// x rotation rate (milli-arc-seconds p/yr)\n\t  1.1820,\t// y rotation rate (milli-arc-seconds p/yr)\n\t  1.1551 \t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2008_GDA94 : public _itrf2008_to_gda94_<T, U>\n{\npublic:\n};\n\n// ITRF 2005 -> GDA94\ntemplate <class T, class U>\nstruct _itrf2005_to_gda94_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2005_to_gda94_<T, U>::reference_frame = GDA94_i;\n\ntemplate <class T, class U>\nconst T _itrf2005_to_gda94_<T, U>::reference_epoch = 1994.0;\n\ntemplate <class T, class U>\nconst T _itrf2005_to_gda94_<T, U>::transformationParameters[14] =\n{\n\t  -79.73,\t// x translation (millimetres)\n\t   -6.86,\t// y translation (millimetres)\n\t   38.03,\t// z translation (millimetres)\n\t  6.6360,\t// scale (ppb)\n\t -0.0351,\t// x rotation (milli-arc-seconds)\n\t  2.1211,\t// y rotation (milli-arc-seconds)\n\t  2.1411,\t// z rotation (milli-arc-seconds)\n\n\t    2.25,\t// x translation rate (millimetres p/yr)\n\t   -0.62,\t// y translation rate (millimetres p/yr)\n\t   -0.56,\t// z translation rate (millimetres p/yr)\n\t  0.2940,\t// scale rate (ppb p/yr)\n\t  1.4707,\t// x rotation rate (milli-arc-seconds p/yr)\n\t  1.1443,\t// y rotation rate (milli-arc-seconds p/yr)\n\t  1.1701 \t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2005_GDA94 : public _itrf2005_to_gda94_<T, U>\n{\npublic:\n};\n\n// ITRF 2000 -> GDA94\ntemplate <class T, class U>\nstruct _itrf2000_to_gda94_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf2000_to_gda94_<T, U>::reference_frame = GDA94_i;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_gda94_<T, U>::reference_epoch = 1994.0;\n\ntemplate <class T, class U>\nconst T _itrf2000_to_gda94_<T, U>::transformationParameters[14] =\n{\n\t  -45.91,\t// x translation (millimetres)\n\t  -29.85,\t// y translation (millimetres)\n\t  -20.37,\t// z translation (millimetres)\n\t  7.0700,\t// scale (ppb)\n\t -1.6705,\t// x rotation (milli-arc-seconds)\n\t  0.4594,\t// y rotation (milli-arc-seconds)\n\t  1.9356,\t// z rotation (milli-arc-seconds)\n\n\t   -4.66,\t// x translation rate (millimetres p/yr)\n\t    3.55,\t// y translation rate (millimetres p/yr)\n\t   11.24,\t// z translation rate (millimetres p/yr)\n\t  0.2490,\t// scale rate (ppb p/yr)\n\t  1.7454,\t// x rotation rate (milli-arc-seconds p/yr)\n\t  1.4868,\t// y rotation rate (milli-arc-seconds p/yr)\n\t  1.2240 \t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF2000_GDA94 : public _itrf2000_to_gda94_<T, U>\n{\npublic:\n};\n\n// ITRF 1997 -> GDA94\ntemplate <class T, class U>\nstruct _itrf1997_to_gda94_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf1997_to_gda94_<T, U>::reference_frame = GDA94_i;\n\ntemplate <class T, class U>\nconst T _itrf1997_to_gda94_<T, U>::reference_epoch = 1994.0;\n\ntemplate <class T, class U>\nconst T _itrf1997_to_gda94_<T, U>::transformationParameters[14] =\n{\n\t  -14.63,\t// x translation (millimetres)\n\t  -27.62,\t// y translation (millimetres)\n\t  -25.32,\t// z translation (millimetres)\n\t  6.6950,\t// scale (ppb)\n\t -1.7893,\t// x rotation (milli-arc-seconds)\n\t -0.6047,\t// y rotation (milli-arc-seconds)\n\t  0.9962,\t// z rotation (milli-arc-seconds)\n\n\t   -8.60,\t// x translation rate (millimetres p/yr)\n\t    0.36,\t// y translation rate (millimetres p/yr)\n\t   11.25,\t// z translation rate (millimetres p/yr)\n\t  0.0070,\t// scale rate (ppb p/yr)\n\t  1.6394,\t// x rotation rate (milli-arc-seconds p/yr)\n\t  1.5198,\t// y rotation rate (milli-arc-seconds p/yr)\n\t  1.3801\t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF1997_GDA94 : public _itrf1997_to_gda94_<T, U>\n{\npublic:\n};\n\n// ITRF 1996 -> GDA94\ntemplate <class T, class U>\nstruct _itrf1996_to_gda94_\n{\n\tstatic const U reference_frame;\n\tstatic const T reference_epoch;\n\tstatic const T transformationParameters[14];\n};\n\ntemplate <class T, class U>\nconst U _itrf1996_to_gda94_<T, U>::reference_frame = GDA94_i;\n\ntemplate <class T, class U>\nconst T _itrf1996_to_gda94_<T, U>::reference_epoch = 1994.0;\n\ntemplate <class T, class U>\nconst T _itrf1996_to_gda94_<T, U>::transformationParameters[14] =\n{\n\t   24.54,\t// x translation (millimetres)\n\t  -36.43,\t// y translation (millimetres)\n\t  -68.12,\t// z translation (millimetres)\n\t  6.9010,\t// scale (ppb)\n\t -2.7359,\t// x rotation (milli-arc-seconds)\n\t -2.0431,\t// y rotation (milli-arc-seconds)\n\t  0.3731,\t// z rotation (milli-arc-seconds)\n\n\t  -21.80,\t// x translation rate (millimetres p/yr)\n\t    4.71,\t// y translation rate (millimetres p/yr)\n\t   26.27,\t// z translation rate (millimetres p/yr)\n\t  0.3880,\t// scale rate (ppb p/yr)\n\t  2.0203,\t// x rotation rate (milli-arc-seconds p/yr)\n\t  2.1735,\t// y rotation rate (milli-arc-seconds p/yr)\n\t  1.6290 \t// z rotation rate (milli-arc-seconds p/yr)\n};\n\ntemplate <class T, class U>\nclass ITRF1996_GDA94 : public _itrf1996_to_gda94_<T, U>\n{\npublic:\n};\n\n\n\n\n}\t// namespace datum_parameters\n}\t// namespace dynadjust\n\n#endif /* DNATRANSFORM_PARAM_H_ */\n", "meta": {"hexsha": "6e9e102efb6c6db60336b4c5f47e739b6711987d", "size": 66724, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dynadjust/include/parameters/dnatransformationparameters.hpp", "max_stars_repo_name": "ccrook/DynAdjust", "max_stars_repo_head_hexsha": "d8e5c3c441c3a7065807915d83fe623af0add2b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T04:49:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T04:49:13.000Z", "max_issues_repo_path": "dynadjust/include/parameters/dnatransformationparameters.hpp", "max_issues_repo_name": "ccrook/DynAdjust", "max_issues_repo_head_hexsha": "d8e5c3c441c3a7065807915d83fe623af0add2b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dynadjust/include/parameters/dnatransformationparameters.hpp", "max_forks_repo_name": "ccrook/DynAdjust", "max_forks_repo_head_hexsha": "d8e5c3c441c3a7065807915d83fe623af0add2b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.296435272, "max_line_length": 112, "alphanum_fraction": 0.6701636593, "num_tokens": 23684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478692926354, "lm_q2_score": 0.0316187688655519, "lm_q1q2_score": 0.015192144736460873}}
{"text": "#include \"ext/lda/lda.h\"\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\nldaModel::ldaModel(const Corpus& training, const Corpus& test):\ntfile(test),\ndfile(training)\n{\n    if (test.size() > 0)\n        testing_type = SEPARATE_TEST;\n    else\n        testing_type = SELF_TEST;\n\n    M = 0;\n    V = 0;\n    K = 100;\n\n    alpha = 50.0 / K;\n    beta = 0.1;\n\n    z = NULL;\n    n_wk.clear(); \n    n_k.clear();\n\n    p = NULL;\n    nd_m = NULL;\n    rev_mapper = NULL;\n\n    n_iters = 1000;\n    n_save = 200;\n    n_topWords = 0;\n\n    test_n_iters = 10;\n    test_M = 0;\n    test_z = NULL;\n    test_n_wk = NULL;\n    test_n_mk = NULL;\n    test_n_k = NULL;\n\n    time_ellapsed.reserve(50);\n    likelihood.reserve(50);\n\n    ddir = \"./\";\n    mdir = \"./\";\n}\n\nldaModel::~ldaModel()\n{\n\n    if (z)\n    {\n        for (int m = 0; m < M; m++)\n        {\n            if (z[m])\n            {\n                delete[] z[m];\n            }\n        }\n        delete[] z;\n    }\n\n    n_wk.clear(); \n    n_k.clear(); \n    \n    if (p)\t\tdelete[] p;\n    if (nd_m)\tdelete[] nd_m;\n    if (rev_mapper)\tdelete[] rev_mapper;\n\n\n    if (test_z)\n    {\n        for (int m = 0; m < test_M; m++)\n        {\n            if (test_z[m])\n            {\n                delete[] test_z[m];\n            }\n        }\n        delete[] test_z;\n        test_z = nullptr;\n    }\n\n    if (test_n_wk)\n    {\n        for (int w = 0; w < V; w++)\n        {\n            if (test_n_wk[w])\n            {\n                delete[] test_n_wk[w];\n            }\n        }\n        delete[] test_n_wk;\n        test_n_wk = nullptr;\n    }\n\n    if (test_n_mk)\n    {\n        for (int m = 0; m < test_M; m++)\n        {\n            if (test_n_mk[m])\n            {\n                delete[] test_n_mk[m];\n            }\n        }\n        delete[] test_n_mk;\n        test_n_mk = nullptr;\n    }\n\n    if (test_n_k)\tdelete[] test_n_k;\n\n}\n\nldaModel* ldaModel::init(variables_map vm)\n{\n    double _alpha = -1.0;\n\n    mdir = vm[\"lda-model\"].as<string>();\n    alpha = vm[\"lda-alpha\"].as<cnn::real>();\n    beta = vm[\"lda-beta\"].as<cnn::real>();\n    K = vm[\"lda-num-topics\"].as<int>();\n    n_iters = vm[\"lda-num-iterations\"].as<int>();\n    n_save = vm[\"lda-output-state-interval\"].as<int>();\n    n_topWords = vm[\"lda-num-top-words\"].as<int>();\n\n    //Check specific parameter    \n    if (testing_type == SEPARATE_TEST)\n    {\n        if (tfile.size() == 0)\n        {\n            throw(\"Error: test corpus is empty\"); \n        }\n    }\n\n    std::cout << \"data dir = \" << ddir << std::endl;\n    std::cout << \"ldaModel dir = \" << mdir << std::endl;\n    std::cout << \"n_iters = \" << n_iters << std::endl;\n    std::cout << \"alpha = \" << alpha << std::endl;\n    std::cout << \"beta = \" << beta << std::endl;\n    std::cout << \"K = \" << K << std::endl;\n\n    return this;\n}\n\nint ldaModel::train()\n{\n    std::chrono::high_resolution_clock::time_point ts, tn;\n    std::cout << \"Sampling \" << n_iters << \" iterations!\" << std::endl;\n\n    init_train();\n\n    for (int iter = 1; iter <= n_iters; ++iter)\n    {\n        std::cout << \"Iteration \" << iter << \" ...\" << std::endl;\n        ts = std::chrono::high_resolution_clock::now();\n\n        // for each document\n        for (int m = 0; m < M; ++m)\n            sampling(m);\n\n        tn = std::chrono::high_resolution_clock::now();\n        time_ellapsed.push_back(std::chrono::duration_cast<std::chrono::milliseconds>(tn - ts).count());\n\n#if COMP_LLH\n        test(sd);\n#endif\n\n        if (n_save > 0)\n        {\n            if (iter % n_save == 0)\n            {\n                // saving the ldaModel\n                std::cout << \"Saving the ldaModel at iteration \" << iter << \"...\" << std::endl;\n                save_ldaModel(iter);\n            }\n        }\n    }\n\n    std::cout << \"Gibbs sampling completed!\" << std::endl;\n    std::cout << \"Saving the final ldaModel!\" << std::endl;\n    save_ldaModel(-1);\n\n    return 0;\n}\n\nint ldaModel::test(Dict& sd)\n{\n    init_test();\n\n    if (testing_type == SELF_TEST)\n    {\n        // just do MAP estimates\n        likelihood.push_back(llhw());\n        std::cout << \"Likelihood on training documents: \" << likelihood.back() << \" at time \" << time_ellapsed.back() << std::endl;\n    }\n    else if (testing_type == SEPARATE_TEST)\n    {\n        for (int iter = 1; iter <= test_n_iters; ++iter)\n        {\n            // for each doc\n            for (int m = 0; m < test_M; m++)\n                vanilla_sampling(m);\n        }\n        likelihood.push_back(newllhw());\n        std::cout << \"Likelihood on held out documents: \" << likelihood.back() << std::endl;\n\n        /// compute the topic of each test sentence\n        for (int m = 0; m < test_M; m++)\n        {\n            int this_topic = topic_of(m);\n            string ostr = \"\";\n            for (int n = 0; n < testdata[m].size(); n++)\n            {\n                int w = testdata[m][n];\n                string wrd = sd.Convert(w);\n                ostr = ostr + wrd + \" \";\n            }\n            cout << ostr << \" ||| topic \" << this_topic;\n            if (testresponses.size() > 0)\n            {\n                string ostr = \"\";\n                for (auto & w : testresponses[m])\n                {\n                    string wrd = sd.Convert(w);\n                    ostr = ostr + wrd + \" \";\n                }\n                cout << \" ||| \" << ostr << endl;\n            }\n        }\n    }\n    return 0;\n}\n\nint ldaModel::test(Dict& sd, const SentencePair& obs)\n{\n    init_test();\n\n    memset(test_n_wk, 0, sizeof(int)* V * K);\n    memset(test_n_mk, 0, sizeof(int)* K);\n    memset(test_n_k, 0, sizeof(int)* K);\n    for (int n = 0; n < obs.first.size(); n++)\n    {\n        int w = obs.first[n];\n        test_z[0][n] = rand0n_uniform(K - 1);\n\n        int topic = test_z[0][n];\n\n        // number of instances of word i assigned to topic j\n        test_n_wk[w][topic] += 1;\n        // number of words in document i assigned to topic j\n        test_n_mk[0][topic] += 1;\n        // total number of words assigned to topic j\n        test_n_k[topic] += 1;\n    }\n\n    for (int iter = 1; iter <= test_n_iters; ++iter)\n    {\n        // for each doc\n        for (int m = 0; m < test_M; m++)\n            vanilla_sampling(obs.first);\n    }\n    likelihood.push_back(newllhw());\n    std::cout << \"Likelihood on held out documents: \" << likelihood.back() << std::endl;\n\n    /// compute the topic of each test sentence\n    for (int m = 0; m < test_M; m++)\n    {\n        int this_topic = topic_of(m);\n        string ostr = \"\";\n        for (int n = 0; n < testdata[m].size(); n++)\n        {\n            int w = testdata[m][n];\n            string wrd = sd.Convert(w);\n            ostr = ostr + wrd + \" \";\n        }\n        cout << ostr << \" ||| topic \" << this_topic;\n        if (testresponses.size() > 0)\n        {\n            string ostr = \"\";\n            for (auto & w : testresponses[m])\n            {\n                string wrd = sd.Convert(w);\n                ostr = ostr + wrd + \" \";\n            }\n            cout << \" ||| \" << ostr << endl;\n        }\n    }\n    return 0;\n}\n\nint ldaModel::read_data(const Corpus & training, const Dict& sd, const Corpus& testing)\n{\n    flatten_corpus(training, trngdata, trngresponses);\n    V = sd.size();\n    M = trngdata.size();\n    \n    flatten_corpus(testing, testdata, testresponses);\n    test_M = testdata.size();\n\n    return training.size();\n}\n\nint ldaModel::init_train()\n{\n    Vbeta = V * beta;\n\n    // allocate heap memory for ldaModel variables\n    n_wk.resize(V);\n    for (int w = 0; w < V; w++)\n    {\n        n_wk[w] = vector<int>(K, 0); \n    }\n    \n    n_mks.resize(M);\n\n    n_k.resize(K, 0); \n\n    // random consistent assignment for ldaModel variables\n    z = new int*[M];\n    for (int m = 0; m < trngdata.size(); m++)\n    {\n        int N = trngdata[m].size();\n        std::map<int, int > map_nd_m;\n        z[m] = new int[N];\n\n        // initialize for z\n        for (int n = 0; n < N; n++)\n        {\n            int topic = rand0n_uniform(K - 1); \n            z[m][n] = topic;\n            int w = trngdata[m][n];\n\n            // number of instances of word i assigned to topic j\n            n_wk[w][topic] += 1;\n            // number of words in document i assigned to topic j\n            map_nd_m[topic] += 1;\n            // total number of words assigned to topic j\n            n_k[topic] += 1; \n        }\n        // transfer to sparse representation\n        for (auto myc : map_nd_m)\n            n_mks[m].push_back(myc);\n    }\n\n    time_ellapsed.reserve(n_iters);\n    likelihood.reserve(n_iters);\n\n    // allocate heap memory for temporary variables\n    p = new double[K];\n    nd_m = new int[K];\n    rev_mapper = new int[K];\n    for (int k = 0; k < K; ++k)\n    {\n        nd_m[k] = 0;\n        rev_mapper[k] = -1;\n    }\n\n    return 0;\n}\n\nint ldaModel::init_test()\n{\n    // initialise variables for testing\n    Vbeta = V * beta;\n    if (test_n_wk == nullptr)\n    {\n        test_n_wk = new int*[V];\n        for (int w = 0; w < V; w++)\n        {\n            test_n_wk[w] = new int[K];\n            for (int k = 0; k < K; k++)\n            {\n                test_n_wk[w][k] = 0;\n            }\n        }\n    }\n\n    if (test_n_mk == nullptr)\n    {\n        test_n_mk = new int*[test_M];\n        for (int m = 0; m < test_M; m++)\n        {\n            test_n_mk[m] = new int[K];\n            for (int k = 0; k < K; k++)\n            {\n                test_n_mk[m][k] = 0;\n            }\n        }\n    }\n\n    if (test_n_k == nullptr)\n    {\n        test_n_k = new int[K];\n        for (int k = 0; k < K; k++)\n        {\n            test_n_k[k] = 0;\n        }\n    }\n\n    if (test_z == nullptr)\n    {\n        test_z = new int*[test_M];\n        for (int m = 0; m < testdata.size(); m++)\n        {\n            int N = testdata[m].size();\n            test_z[m] = new int[N];\n\n            // assign values for n_wk, n_mk, n_k\n            for (int n = 0; n < N; n++)\n            {\n                int w = testdata[m][n];\n                int topic = rand0n_uniform(K - 1);\n                test_z[m][n] = topic;\n\n                // number of instances of word i assigned to topic j\n                test_n_wk[w][topic] += 1;\n                // number of words in document i assigned to topic j\n                test_n_mk[m][topic] += 1;\n                // total number of words assigned to topic j\n                test_n_k[topic] += 1;\n            }\n        }\n    }\n\n    // allocate heap memory for temporary variables\n    if (p == nullptr)\n        p = new double[K];\n    if (nd_m == nullptr)\n        nd_m = new int[K];\n    if (rev_mapper == nullptr)\n        rev_mapper = new int[K];\n    for (int k = 0; k < K; ++k)\n    {\n        nd_m[k] = 0;\n        rev_mapper[k] = -1;\n    }\n\n    return 0;\n}\n\nint ldaModel::sampling(int m)\n{\n    int kc = 0;\n    for (const auto& k : n_mks[m])\n    {\n        nd_m[k.first] = k.second;\n        rev_mapper[k.first] = kc++;\n    }\n    for (int n = 0; n < trngdata[m].size(); ++n)\n    {\n        int w = trngdata[m][n];\n\n        // remove z_ij from the count variables\n        int topic = z[m][n]; int old_topic = topic;\n        remove_from_topic(w, m, topic);\n\n        // do multinomial sampling via cumulative method\n        double temp = 0;\n        for (int k = 0; k < K; k++)\n        {\n            temp += (nd_m[k] + alpha) * (n_wk[w][k]  + beta) / (n_k[k] + Vbeta);\n            p[k] = temp;\n        }\n\n        // scaled sample because of unnormalized p[]\n        double u = rand01() * temp;\n\n        // Do a binary search instead!\n        topic = std::lower_bound(p, p + K, u) - p;\n\n        // add newly estimated z_i to count variables\n        add_to_topic(w, m, topic, old_topic);\n        nd_m[topic] += 1;\n        z[m][n] = topic;\n    }\n    for (const auto& k : n_mks[m])\n    {\n        nd_m[k.first] = 0;\n        rev_mapper[k.first] = -1;\n    }\n    return 0;\n}\n\nint ldaModel::vanilla_sampling(int m)\n{\n    for (int n = 0; n < testdata[m].size(); n++)\n    {\n        int w = testdata[m][n];\n\n        // remove z_i from the count variables\n        int topic = test_z[m][n];\n        test_n_wk[w][topic] -= 1;\n        test_n_mk[m][topic] -= 1;\n        test_n_k[topic] -= 1;\n\n        double psum = 0;\n        // do multinomial sampling via cumulative method\n        for (int k = 0; k < K; k++)\n        {\n            psum += (test_n_mk[m][k] + alpha) * (n_wk[w][k] + test_n_wk[w][k] + beta) / (n_k[k]+ test_n_k[k] + Vbeta);\n            p[k] = psum;\n        }\n\n        // scaled sample because of unnormalized p[]\n        double u = rand01() * psum;\n        topic = std::lower_bound(p, p + K, u) - p;\n\n        // add newly estimated z_i to count variables\n        test_n_wk[w][topic] += 1;\n        test_n_mk[m][topic] += 1;\n        test_n_k[topic] += 1;\n        test_z[m][n] = topic;\n    }\n\n    return 0;\n}\n\nint ldaModel::vanilla_sampling(const Sentence& obs)\n{\n    int n = 0;\n    for (auto & w : obs)\n    {\n        // remove z_i from the count variables\n        int topic = test_z[0][n];\n        test_n_wk[w][topic] -= 1;\n        test_n_mk[0][topic] -= 1;\n        test_n_k[topic] -= 1;\n\n        double psum = 0;\n        // do multinomial sampling via cumulative method\n        for (int k = 0; k < K; k++)\n        {\n            psum += (test_n_mk[0][k] + alpha) * (n_wk[w][k] + test_n_wk[w][k] + beta) / (n_k[k] + test_n_k[k] + Vbeta);\n            p[k] = psum;\n        }\n\n        // scaled sample because of unnormalized p[]\n        double u = rand01() * psum;\n        topic = std::lower_bound(p, p + K, u) - p;\n\n        // add newly estimated z_i to count variables\n        test_n_wk[w][topic] += 1;\n        test_n_mk[0][topic] += 1;\n        test_n_k[topic] += 1;\n        test_z[0][n] = topic;\n\n        n++;\n    }\n\n    return 0;\n}\n\n/// get the majority topic of document m\nint ldaModel::topic_of(int m)\n{\n    vanilla_sampling(m);\n    std::vector<int> v(K,0);\n\n    for (int n = 0; n < testdata[m].size(); n++)\n    {\n        int topic = test_z[m][n];\n        v[topic] ++;\n    }\n\n    std::vector<int>::iterator idx = std::max_element(v.begin(), v.end());\n    int topic = std::distance(v.begin(), idx);\n    return topic;\n}\n\ndouble ldaModel::newllhw() const\n{\n    double sum = 0;\n    int num_tokens = 0;\n    for (int m = 0; m < test_M; ++m)\n    {\n        double dsum = 0;\n        num_tokens += testdata[m].size();\n        for (int n = 0; n < testdata[m].size(); n++)\n        {\n            double wsum = 0;\n            int w = testdata[m][n];\n            for (int k = 0; k<K; k++)\n            {\n                wsum += (test_n_mk[m][k] + alpha) * (n_wk[w][k] + test_n_wk[w][k] + beta) / (n_k[k]+ test_n_k[k] + Vbeta);\n            }\n            dsum += log(wsum);\n        }\n        sum += dsum - testdata[m].size()*log(testdata[m].size() + K * alpha);\n    }\n    return sum / num_tokens;\n}\n\ndouble ldaModel::llhw() const\n{\n    double sum = 0;\n    int num_tokens = 0;\n    for (int m = 0; m < M; m++)\n    {\n        for (auto k = n_mks[m].begin(); k != n_mks[m].end(); ++k)\n        {\n            nd_m[k->first] = k->second;\n        }\n\n        double dsum = 0;\n        num_tokens += trngdata[m].size();\n        for (int n = 0; n < trngdata[m].size(); n++)\n        {\n            double wsum = 0;\n            int w = trngdata[m][n];\n            for (int k = 0; k<K; k++)\n            {\n                wsum += (nd_m[k] + alpha) * (n_wk[w][k] + beta) / (n_k[k]+ Vbeta);\n            }\n            wsum /= (trngdata[m].size() + K * alpha);\n            dsum += log(wsum);\n        }\n        sum += dsum;\n        for (auto k = n_mks[m].begin(); k != n_mks[m].end(); ++k)\n        {\n            nd_m[k->first] = 0;\n        }\n    }\n    return sum / num_tokens;\n}\n\nint ldaModel::save_ldaModel(int iter) const\n{\n    std::string ldaModel_name = mdir + \"-\";\n    if (iter >= 0)\n    {\n        std::ostringstream sstr1;\n        sstr1 << std::setw(5) << std::setfill('0') << iter;\n        ldaModel_name += sstr1.str();\n    }\n    else\n    {\n        ldaModel_name += \"final\";\n    }\n\n    if (save_ldaModel_time(ldaModel_name + \".time\"))\n    {\n        return 1;\n    }\n    std::cout << \"time done\" << std::endl;\n    if (save_ldaModel_llh(ldaModel_name + \".llh\"))\n    {\n        return 1;\n    }\n    std::cout << \"llh done\" << std::endl;\n\n    string fname = ldaModel_name + \".mdl\";\n    ofstream on(fname);\n    boost::archive::text_oarchive oa(on);\n    oa << *this;\n\n    std::cout << \"others done\" << std::endl;\n    if (n_topWords > 0)\n    {\n        //if (save_ldaModel_twords(mdir + ldaModel_name + \".twords\")) \n        //ff{\n        //\treturn 1;\n        //}\n        //std::cout << \"twords done\" << std::endl;\n    }\n    //if (ldaModel_status == ldaModel_SELF_TEST)\n    //{\n    //\tif (save_ldaModel_phi(mdir + ldaModel_name + \".phi\"))\n    //\t{\n    //\t\treturn 1;\n    //\t}\n    //\tstd::cout << \"phi done\" << std::endl;\n    //}\n    return 0;\n}\n\nint ldaModel::load_ldaModel(int iter)\n{\n    std::string ldaModel_name = mdir + \"-\";\n    if (iter >= 0)\n    {\n        std::ostringstream sstr1;\n        sstr1 << std::setw(5) << std::setfill('0') << iter;\n        ldaModel_name += sstr1.str();\n    }\n    else\n    {\n        ldaModel_name += \"final\";\n    }\n\n    string fname = ldaModel_name + \".mdl\";\n    ifstream in(fname);\n    boost::archive::text_iarchive ia(in);\n    ia >> *this;\n\n    return 0;\n}\n\nint ldaModel::load_ldaModel(const string & filename)\n{\n    string fname = filename;\n    ifstream in(fname);\n    if (!in.is_open())\n    {\n        cerr << \"cannot open \" << fname << endl;\n        throw(\"cannot open \" + fname);\n    }\n    boost::archive::text_iarchive ia(in);\n    ia >> *this;\n\n    return 0;\n}\n\nint ldaModel::save_ldaModel_time(std::string filename) const\n{\n    std::ofstream fout(filename);\n    if (!fout)\n    {\n        std::cout << \"Error: Cannot open file to save: \" << filename << std::endl;\n        return 1;\n    }\n\n    for (unsigned r = 0; r < time_ellapsed.size(); ++r)\n    {\n        fout << time_ellapsed[r] << std::endl;\n    }\n\n    fout.close();\n\n    return 0;\n}\n\nint ldaModel::save_ldaModel_llh(std::string filename) const\n{\n    std::ofstream fout(filename);\n    if (!fout)\n    {\n        std::cout << \"Error: Cannot open file to save: \" << filename << std::endl;\n        return 1;\n    }\n\n    for (unsigned r = 0; r < likelihood.size(); ++r)\n    {\n        fout << likelihood[r] << std::endl;\n    }\n\n    fout.close();\n\n    return 0;\n}\n\nint ldaModel::save_ldaModel_topWords(std::string filename, Dict& sd) const\n{\n    std::ofstream fout(filename);\n    if (!fout)\n    {\n        std::cout << \"Error: Cannot open file to save: \" << filename << std::endl;\n        return 1;\n    }\n\n    int _n_topWords = n_topWords;\n    if (_n_topWords > V)\t_n_topWords = V;\n\n    std::map<int, std::string>::const_iterator it;\n\n    for (int k = 0; k < K; k++)\n    {\n        std::vector<std::pair<int, int> > words_probs(V);\n        std::pair<int, int> word_prob;\n        for (int w = 0; w < V; w++)\n        {\n            word_prob.first = w;\n            word_prob.second = n_wk[w][k];\n            words_probs[w] = word_prob;\n        }\n\n        // quick sort to sort word-topic probability\n        std::sort(words_probs.begin(), words_probs.end());\n\n        fout << \"Topic \" << k << \"th:\" << std::endl;\n        for (int i = 0; i < _n_topWords; i++)\n        {\n            string it = sd.Convert(words_probs[i].first);\n            fout << \"\\t\" << it << \"   \" << words_probs[i].second << std::endl;\n        }\n    }\n\n    fout.close();\n\n    return 0;\n}\n\nint ldaModel::save_ldaModel_phi(std::string filename) const\n{\n    std::ofstream fout(filename);\n    if (!fout)\n    {\n        std::cout << \"Error: Cannot open file to save: \" << filename << std::endl;\n        return 1;\n    }\n\n    for (int k = 0; k < K; k++)\n    {\n        for (int w = 0; w < V; w++)\n        {\n            fout << (n_wk[w][k] + beta) / (n_k[k]+ Vbeta) << \" \";\n        }\n        fout << std::endl;\n    }\n\n    fout.close();\n\n    return 0;\n}\n\nint ldaModel::sanity() const\n{\n    long tott = 0;\n    for (int m = 0; m < M; ++m)\n    {\n        int sumd = 0;\n        for (const auto &t : n_mks[m])\n            sumd += t.second;\n        if (sumd == trngdata[m].size())\n            tott += sumd;\n        else\n            std::cout << \"Length mismatch at doc: \" << m << std::endl;\n    }\n    std::cout << \"Total number of training tokens: \" << tott << std::endl;\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "84b71b9d62114b3387cf54579b077797d154e324", "size": 20174, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ext/lda/lda.cc", "max_stars_repo_name": "kaishengyao/cnn", "max_stars_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-09-10T07:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-17T03:02:38.000Z", "max_issues_repo_path": "ext/lda/lda.cc", "max_issues_repo_name": "kaishengyao/cnn", "max_issues_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/lda/lda.cc", "max_forks_repo_name": "kaishengyao/cnn", "max_forks_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T12:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T07:32:47.000Z", "avg_line_length": 24.218487395, "max_line_length": 131, "alphanum_fraction": 0.4780410429, "num_tokens": 5851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.04023794535707827, "lm_q1q2_score": 0.015191460237549076}}
{"text": "﻿/***\r\n十：模板模板参数\r\n英文名：Template Template Parameters。就是：让模板参数本身成为模板。\r\na)int：类型，简单类型/内部类型\r\nb)vector,list：是C++标准库中的容器，类模板（类名），vector<int>或者list<double>就属于模板被实例化了的参数，称呼为类型（类类型）。\r\n创建myclass的类模板，成员变量myc，是个容器，\r\n复习一下：a）类型模板参数，b)非类型模板参数，c)模板模板参数。\r\n十一：共用体模板（联合模板）\r\nunion\r\n可以把联合理解成一种类类型（不要理解成类）。联合也支持模板化。\r\n共用体模板的英文名：Union Templates。\r\n***/\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <list>\r\n\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\nnamespace _nmsp1\r\n{\r\n\t//T：类型模板参数，代表容器中元素类型。\r\n\t//Container：代表的不是一个类型（不能是一个类型模板参数），而是一个类模板（类名）\r\n\t//Container，不叫做类型模板参数，而叫做 模板 模板参数,表示这个模板参数本身又是一个模板。\r\n\ttemplate <typename T,\r\n\t\t      //typename Container = std::vector\r\n\t\t      //template <class> class Container = std::vector          //这就是一个模板模板参数，写法比较固定，这里的名字叫Container，叫U也可以。\r\n\t\t      template <typename W> typename  Container = std::vector>  //也要理解这种写法,W可以省略，Container如果myclass类模板中不使用，也可以省略，从而出现了typename后面直接接=的写法。\r\n\t    \r\n\tclass myclass\r\n\t{\r\n\tpublic:\r\n\t\tContainer<T> myc;\r\n\r\n\tpublic:\r\n\t\tvoid func();                     \r\n\t\tmyclass()                        //构造函数\r\n\t\t{\r\n\t\t\tfor (int i = 0; i < 10; ++i)\r\n\t\t\t{\r\n\t\t\t\tmyc.push_back(i);        //这几行代码是否正确取决于实例化该类模板时所提供的模板参数类型。\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\t//成员函数在类外定义\r\n\ttemplate <typename T,\r\n\t\t      template <typename W> typename  Container>\r\n\tvoid myclass<T, Container>::func()\r\n\t{\r\n\t\tcout << \"good!\" << endl;\r\n\t}\r\n\r\n\r\n\t//模模参数的模板参数\r\n\ttemplate <//.....\r\n\t\t      template <typename W, W* point> typename  Container>\r\n\tclass myclass2\r\n\t{\r\n\t\t//W* m_p;  //错误，不可以在这里使用W（W叫做：模板模板参数Container的模板参数）\r\n\t};\r\n\r\n\t//省略Container\r\n\ttemplate <\r\n\t\t     //......\r\n\t\t     template <typename W> typename  = std::vector>\r\n\tclass myclass3\r\n\t{\r\n\r\n\t};\r\n}\r\n\r\nnamespace _nmsp2\r\n{\r\n\ttemplate<typename T,typename U>\r\n\tunion myuni\r\n\t{\r\n\t\tT carnum;    //轿车编号，4个字节。\r\n\t\tU cartype;   //轿车的类型，比如微型车，小型车，中，中大。1个字节。\r\n\t\tU cname[60]; //轿车名，60个字节\r\n\t};\r\n}\r\n\r\nint main()\r\n{\r\n\t//测试_nmsp1\r\n\t_nmsp1::myclass<int, vector> myvectorobj;    //int是容器中的元素类型,vector是容器类型。\r\n\t_nmsp1::myclass<double, list> mylistobj;     //double是容器中的元素类型，list是容器类型。\r\n\r\n\t_nmsp1::myclass<double, list> mylistobj2;    //double是容器中的元素类型，list是容器类型\r\n\tmylistobj2.func(); \r\n\r\n\t//测试_nmsp2\r\n\t_nmsp2::myuni<int, char> myu;\r\n\tmyu.carnum = 156;\r\n\tcout << myu.carnum << endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "5a6aea17b1779f7089aa08fabcaa5d4067343915", "size": 2284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/210.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/210.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/210.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 22.1747572816, "max_line_length": 139, "alphanum_fraction": 0.630910683, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436782035217445, "lm_q2_score": 0.07807815817295459, "lm_q1q2_score": 0.015175881421189499}}
{"text": "#pragma once\r\n//=====================================================================//\r\n/*!\t@file\r\n\t@brief\tArithmetic クラス（ヘッダー）@n\r\n\t\t\t※テキストの数式を展開して、実計算結果を得る。@n\r\n\t\t\t簡易演算式解析 @n\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*/\r\n//=====================================================================//\r\n#include <string>\r\n#include <bitset>\r\n#include <boost/unordered_map.hpp>\r\n\r\nnamespace utils {\r\n\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t/*!\r\n\t\t@brief\tArithmetic クラス\r\n\t*/\r\n\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\tstruct arith {\r\n\r\n\t\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t\t/*!\r\n\t\t\t@brief\tエラー・タイプ\r\n\t\t*/\r\n\t\t//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\r\n\t\tstruct error {\r\n\t\t\tenum type {\r\n\t\t\t\tnone,\t\t\t\t///< エラー無\r\n\r\n\t\t\t\tfatal,\t\t\t\t///< エラー\r\n\t\t\t\tnumber_fatal,\t\t///< 数字の変換に関するエラー\r\n\t\t\t\tzero_divide,\t\t///< ０除算エラー\r\n\t\t\t\tbinary_fatal,\t\t///< ２進データの変換に関するエラー\r\n\t\t\t\toctal_fatal,\t\t///< ８進データの変換に関するエラー\r\n\t\t\t\thexdecimal_fatal,\t///< １６進データの変換に関するエラー\r\n\t\t\t\tinteger_fatal,\t\t///< 整数データの変換に関するエラー\r\n\t\t\t\tfloat_fatal,\t\t///< 浮動小数点データの変換に関するエラー\r\n\t\t\t\tdouble_fatal,\t\t///< 倍精度浮動小数点データの変換に関するエラー\r\n\t\t\t\tsymbol_fatal,\t\t///< シンボルデータの変換に関するエラー\r\n\r\n\t\t\t\tlimit_\r\n\t\t\t};\r\n\t\t};\r\n\r\n\tprivate:\r\n\t\tconst char*\t\ttx_;\r\n\t\tchar\t\t\tch_;\r\n\r\n\t\tclass value {\r\n\t\tpublic:\r\n\t\t\tstd::bitset<error::limit_>\terror_;\r\n\r\n\t\t\tbool\thex_value_;\r\n\t\t\tlong\tinteger_;\r\n\r\n\t\t\tbool\tpoint_;\r\n\r\n\t\t\tfloat\tfloat_;\r\n\t\t\tfloat\tf_scale_;\r\n\r\n\t\t\tbool\tdbe_;\r\n\t\t\tdouble\tdouble_;\r\n\t\t\tdouble\td_scale_;\r\n\r\n\t\t\tvalue() : hex_value_(false), integer_(0), point_(false),\r\n\t\t\t\t\t  float_(0.0f), f_scale_(1.0f),\r\n\t\t\t\t\t  dbe_(false), double_(0.0), d_scale_(1.0) { }\r\n\r\n\t\t\tvoid sum(char c);\r\n\t\t\tvoid neg();\r\n\t\t\tvoid inv();\r\n\r\n\t\t\tvalue& operator += (const value& v) {\r\n\t\t\t\tinteger_ += v.integer_;\r\n\t\t\t\tfloat_ += v.float_;\r\n\t\t\t\tif(dbe_) double_ += v.double_;\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator -= (const value& v) {\r\n\t\t\t\tinteger_ -= v.integer_;\r\n\t\t\t\tfloat_ -= v.float_;\r\n\t\t\t\tif(dbe_) double_ -= v.double_;\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator &= (const value& v) {\r\n\t\t\t\tinteger_ &= v.integer_;\r\n\t\t\t\terror_.set(error::float_fatal);\r\n\t\t\t\tif(dbe_) error_.set(error::double_fatal);\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator ^= (const value& v) {\r\n\t\t\t\tinteger_ ^= v.integer_;\r\n\t\t\t\terror_.set(error::float_fatal);\r\n\t\t\t\tif(dbe_) error_.set(error::double_fatal);\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator |= (const value& v) {\r\n\t\t\t\tinteger_ |= v.integer_;\r\n\t\t\t\terror_.set(error::float_fatal);\r\n\t\t\t\tif(dbe_) error_.set(error::double_fatal);\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator *= (const value& v) {\r\n\t\t\t\tinteger_ *= v.integer_;\r\n\t\t\t\tfloat_ *= v.float_;\r\n\t\t\t\tif(dbe_) double_ *= v.double_;\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator /= (const value& v) {\r\n\t\t\t\tif(v.integer_ == 0 || v.float_ == 0.0f || v.double_ == 0.0) {\r\n\t\t\t\t\terror_.set(error::zero_divide);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tinteger_ /= v.integer_;\r\n\t\t\t\t\tfloat_ /= v.float_;\r\n\t\t\t\t\tif(dbe_) double_ /= v.double_;\r\n\t\t\t\t}\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator %= (const value& v) {\r\n\t\t\t\tif(v.integer_ == 0 || v.float_ == 0.0f || v.double_ == 0.0) {\r\n\t\t\t\t\terror_.set(error::zero_divide);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tinteger_ %= v.integer_;\r\n\t\t\t\t\terror_.set(error::float_fatal);\r\n\t\t\t\t\tif(dbe_) error_.set(error::double_fatal);\r\n\t\t\t\t}\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator <<= (const value& v) {\r\n\t\t\t\tinteger_ <<= v.integer_;\r\n\t\t\t\terror_.set(error::float_fatal);\r\n\t\t\t\tif(dbe_) error_.set(error::double_fatal);\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tvalue& operator >>= (const value& v) {\r\n\t\t\t\tinteger_ >>= v.integer_;\r\n\t\t\t\terror_.set(error::float_fatal);\r\n\t\t\t\tif(dbe_) error_.set(error::double_fatal);\r\n\t\t\t\tif(v.point_) point_ = v.point_;\r\n\t\t\t\terror_ |= v.error_;\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\tvalue\t\tvalue_;\r\n\r\n\t\ttypedef boost::unordered_map<std::string, value>\t\t\t\t\tsymbol_map;\r\n\t\ttypedef boost::unordered_map<std::string, value>::iterator\t\t\tsymbol_map_it;\r\n\t\ttypedef boost::unordered_map<std::string, value>::const_iterator\tsymbol_map_cit;\r\n\t\tsymbol_map\tsymbol_;\r\n\r\n\t\tvalue number_();\r\n\t\tvalue factor_();\r\n\t\tvalue term_();\r\n\t\tvalue expression_();\r\n\tpublic:\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\tコンストラクター\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tarith() : tx_(0), ch_(0) { }\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\tデストラクター\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t~arith() { }\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\tシンボルに値を登録\r\n\t\t\t@param[in]\tname\tシンボル名\r\n\t\t\t@param[in]\tval\t\t整数値\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tvoid set_symbol(const std::string& name, long val);\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\tシンボルに値を登録\r\n\t\t\t@param[in]\tname\tシンボル名\r\n\t\t\t@param[in]\tval\t\t浮動小数点\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tvoid set_symbol(const std::string& name, float val);\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\tシンボルに値を登録\r\n\t\t\t@param[in]\tname\tシンボル名\r\n\t\t\t@param[in]\tval\t\t倍精度浮動小数点\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tvoid set_symbol(const std::string& name, double val);\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\t解析を開始\r\n\t\t\t@param[in]\ttext\t解析テキスト\r\n\t\t\t@return\t文法にエラーがあった場合、「false」\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tbool analize(const std::string& text);\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\tエラーを受け取る\r\n\t\t\t@param[in]\ttype\tエラーの種類\r\n\t\t\t@return エラーがある場合「true」\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tbool get_error(error::type t) const { return value_.error_[t]; }\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\t小数点表記か検査する\r\n\t\t\t@return 小数点表記なら「true」\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tbool is_point() const { return value_.point_; }\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\t整数を取得\r\n\t\t\t@return 解析結果（整数）を受け取る\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tint get_integer() const { return value_.integer_; }\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\t整数を取得\r\n\t\t\t@return 解析結果（32 ビット浮動小数点）を受け取る\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tfloat get_float() const { return value_.float_; }\r\n\r\n\r\n\t\t//-----------------------------------------------------------------//\r\n\t\t/*!\r\n\t\t\t@brief\t整数を取得\r\n\t\t\t@return 解析結果（64 ビット浮動小数点）を受け取る\r\n\t\t*/\r\n\t\t//-----------------------------------------------------------------//\r\n\t\tdouble get_double() const { return value_.double_; }\r\n\r\n\t};\r\n\r\n}\r\n", "meta": {"hexsha": "90172c3eb7daa8768c779b3c0ae44c9bc80f0d5e", "size": 7688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "glfw3_app/common/utils/arith.hpp", "max_stars_repo_name": "hirakuni45/glfw3_app", "max_stars_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-09-22T21:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-01T09:16:53.000Z", "max_issues_repo_path": "glfw3_app/common/utils/arith.hpp", "max_issues_repo_name": "hirakuni45/glfw3_app", "max_issues_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glfw3_app/common/utils/arith.hpp", "max_forks_repo_name": "hirakuni45/glfw3_app", "max_forks_repo_head_hexsha": "d9ceeef6d398229fda4849afe27f8b48d1597fcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T04:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T17:24:32.000Z", "avg_line_length": 26.4192439863, "max_line_length": 83, "alphanum_fraction": 0.4245577523, "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.036220058986007886, "lm_q1q2_score": 0.015165226228671872}}
{"text": "// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-\n\n// -- BEGIN LICENSE BLOCK ----------------------------------------------\n// Copyright (c) 2018, FZI Forschungszentrum Informatik\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n// -- END LICENSE BLOCK ------------------------------------------------\n\n//----------------------------------------------------------------------\n/*!\\file\n *\n * \\author  Philipp Bender <philipp.bender@fzi.de>\n * \\date    2014-01-01\n *\n */\n//----------------------------------------------------------------------\n\n#pragma once\n\n#include <boost/math/special_functions.hpp>\n#include <cmath>\n#include <boost/tuple/tuple.hpp>\n#include <boost/variant/get.hpp>\n#include \"LocalGeographicCS.hpp\"\n#include \"normalize_angle.hpp\"\n#include \"Attribute.hpp\"\n\nnamespace LLet\n{\n\n\nenum LATLON_COORDS\n{\n    LAT = 0,\n    LON = 1,\n    ID = 2\n};\n\nenum XY_COORDS\n{\n    X = 0,\n    Y = 1\n};\n\nclass point_with_id_t : public boost::tuple<double, double, int64_t>, public HasAttributes {\npublic:\n  point_with_id_t(const boost::tuple<double, double, int64_t> &tuple = boost::tuple<double, double, int64_t>(0.0, 0.0, -1)) :\n    boost::tuple<double, double, int64_t>(tuple)\n  {\n    // nothing to do\n  }\n\n#ifdef _WIN32 // The tuple implementation of MSVC10 fails on the auto-generated copy ctor\n    point_with_id_t(const point_with_id_t &other) :\n      HasAttributes(other)\n    {\n        boost::get<LLet::LAT>(*this) = boost::get<LLet::LAT>(other);\n        boost::get<LLet::LON>(*this) = boost::get<LLet::LON>(other);\n        boost::get<LLet::ID>(*this) = boost::get<LLet::ID>(other);\n    }\n#endif\n\n};\n\ninline bool operator==(const point_with_id_t& lhs, const point_with_id_t& rhs)\n{\n  return boost::get<0>(lhs) == boost::get<0>(rhs)\n      && boost::get<1>(lhs) == boost::get<1>(rhs)\n      && boost::get<2>(lhs) == boost::get<2>(rhs);\n}\ninline bool operator!=(const point_with_id_t& lhs, const point_with_id_t& rhs){return !(lhs == rhs);}\n\ntypedef boost::tuple< double, double > point_xy_t;\ntypedef std::vector<point_xy_t> vertex_container_t;\n\ninline\nboost::tuple< double, double > vec( const point_with_id_t& a, const point_with_id_t& b )\n{\n    using boost::get;\n\n    LocalGeographicCS cs(get<LAT>(a), get<LON>(a));\n\n    double ax, ay, bx, by;\n    boost::tie(ax, ay) = cs.ll2xy(get<LAT>(a), get<LON>(a));\n    boost::tie(bx, by) = cs.ll2xy(get<LAT>(b), get<LON>(b));\n\n    double dx = bx -  ax;\n    double dy = by -  ay;\n\n    return boost::make_tuple(dx, dy);\n}\n\n//! Calculate the absolute point from absolute point \\a a with relative offset \\a vec and the given id \\a id\ninline point_with_id_t from_vec(const point_with_id_t& a, const point_xy_t& vec, const int64_t id = -1)\n{\n  using boost::get;\n\n  LocalGeographicCS cs(get<LAT>(a), get<LON>(a));\n  const boost::tuple<double, double>& ll = cs.xy2ll(get<X>(vec), get<Y>(vec));\n  return boost::make_tuple(get<LAT>(ll), get<LON>(ll), id);\n}\n\ninline\ndouble abs( const boost::tuple< double, double > &v )\n{\n    using boost::get;\n    using boost::math::hypot;\n    return hypot( get<X>(v), get<Y>(v) );\n}\n\n//! Calculate the distance between (metric) a and b\ninline double dist(const point_xy_t& a, const point_xy_t& b)\n{\n  using boost::get;\n  return abs(boost::make_tuple(get<X>(b) - get<X>(a), get<Y>(b) - get<Y>(a)));\n}\n\n//! Normalize the vector \\a vec\ninline void normalize(boost::tuple<double, double>& vec)\n{\n  using boost::get;\n  const double length = abs(vec);\n  assert(length != 0 && \"The given vector's length is 0.\");\n  vec = boost::make_tuple(get<X>(vec) / length, get<Y>(vec) / length);\n}\n\n//! Calculate the distance between (gnss) a and b\ninline double dist( const point_with_id_t& a, const point_with_id_t& b )\n{\n    return abs(vec(a, b));\n}\n\ninline\ndouble scalar_product( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b )\n{\n    using boost::get;\n    return get<X>(a) * get<X>(b) + get<Y>(a) * get<Y>(b);\n}\n\n//! Project p on line\ninline\npoint_xy_t projected(const point_xy_t& p, const vertex_container_t &line, double* angle=0, std::size_t* index=0, std::size_t* previous_index=0, std::size_t* subsequent_index=0)\n{\n  double min_distance = -1.0;\n  double const px = boost::get<LLet::X>(p);\n  double const py = boost::get<LLet::Y>(p);\n  point_xy_t min_point = p;\n  size_t const size = line.size();\n  for (std::size_t i=1; i<size; ++i)\n  {\n    const double& ax = boost::get<LLet::X>(line[i-1]);\n    const double& ay = boost::get<LLet::Y>(line[i-1]);\n    const double& bx = boost::get<LLet::X>(line[i]);\n    const double& by = boost::get<LLet::Y>(line[i]);\n\n    point_xy_t const AP = point_xy_t(px-ax, py-ay);\n    point_xy_t const AB = point_xy_t(bx-ax, by-ay);\n    double const scalar_product_ab = scalar_product(AB, AB);\n    double const lambda = scalar_product(AP, AB) / ( scalar_product_ab == 0.0 ? 1.0 : scalar_product_ab );\n\n    double distance = 0.0;\n    point_xy_t c;\n    if (lambda <= 0.0)\n    {\n      c = line[i-1];\n    }\n    else if (lambda < 1.0)\n    {\n      c = point_xy_t(ax + lambda*(bx-ax), ay + lambda*(by-ay));\n    }\n    else\n    {\n      c = line[i];\n    }\n    distance = dist(p, c);\n    if (min_distance < 0.0 || distance < min_distance)\n    {\n      min_distance = distance;\n      min_point = c;\n      if (angle)\n      {\n        *angle = atan2(boost::get<Y>(line[i])-boost::get<Y>(line[i-1]), boost::get<X>(line[i])-boost::get<X>(line[i-1]));\n      }\n      if (index)\n      {\n        *index = lambda < 0.5? i-1 : i;\n      }\n      if (subsequent_index)\n      {\n        *subsequent_index = i;\n      }\n      if (previous_index)\n      {\n        *previous_index = i-1;\n      }\n    }\n  }\n\n  return min_point;\n}\n\ninline\ndouble angle( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b )\n{\n    using boost::get;\n\n    double sp = scalar_product(a, b);\n    double cos_phi = sp / (abs(a) * abs(b));\n\n    // sign for angle: test cross product\n    double crossp_z = get<X>(a) * get<Y>(b) - get<Y>(a) * get<X>(b);\n    double signum = boost::math::sign(crossp_z);\n    double phi = normalize_angle(signum * std::acos(cos_phi));\n    return phi;\n}\n\n\ntemplate< typename T1, typename T2 >\ninline\nbool inrange(const T1& val, const T2& lo, const T2& hi)\n{\n    return val >= lo && val <= hi;\n}\n\n/*! Interpolate the given points using a Catmull-Rom polygon.\n *  Any \\a ratio between 0 and 1 will interpolate in between \\a p1 and \\a p2.\n */\ninline point_xy_t interpolate_spline(const point_xy_t& p0, const point_xy_t& p1,\n                                     const point_xy_t& p2, const point_xy_t& p3, double ratio)\n{\n  /* Catmull-Rom coefficients:\n   *\n   * a0 = -0.5*p0 + 1.5*p1 - 1.5*p2 + 0.5*p3\n   * a1 = p0 - 2.5*p1 + 2*p2 - 0.5*p3\n   * a2 = -0.5*p0 + 0.5*p2\n   */\n\n  const point_xy_t a0 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 1.5 * boost::get<X>(p1) - 1.5 * boost::get<X>(p2) + 0.5 * boost::get<X>(p3),\n                                       -0.5 * boost::get<Y>(p0) + 1.5 * boost::get<Y>(p1) - 1.5 * boost::get<Y>(p2) + 0.5 * boost::get<Y>(p3));\n\n  const point_xy_t a1 = boost::make_tuple(boost::get<X>(p0) - 2.5 * boost::get<X>(p1) + 2. * boost::get<X>(p2) - 0.5 * boost::get<X>(p3),\n                                       boost::get<Y>(p0) - 2.5 * boost::get<Y>(p1) + 2. * boost::get<Y>(p2) - 0.5 * boost::get<Y>(p3));\n\n  const point_xy_t a2 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 0.5 * boost::get<X>(p2),\n                                       -0.5 * boost::get<Y>(p0) + 0.5 * boost::get<Y>(p2));\n  const double ratio_square = ratio * ratio;\n\n  // Catmull-Rom polynom: result = a0 * ratio³ + a1 * ratio² + a2 * ratio + p1\n  return boost::make_tuple(boost::get<X>(a0) * ratio * ratio_square + boost::get<X>(a1) * ratio_square + boost::get<X>(a2) * ratio + boost::get<X>(p1),\n                        boost::get<Y>(a0) * ratio * ratio_square + boost::get<Y>(a1) * ratio_square + boost::get<Y>(a2) * ratio + boost::get<Y>(p1));\n}\n\n//! Calculate the dot product for vector \\a and vector \\b\ninline double dot(const point_xy_t& a, const point_xy_t& b)\n{\n  return boost::get<LLet::X>(a) * boost::get<LLet::X>(b) +\n      boost::get<LLet::Y>(a) * boost::get<LLet::Y>(b);\n}\n\n}\n", "meta": {"hexsha": "132b753443e1d4475bc08a149c635bec49733ecc", "size": 9588, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/liblanelet/lanelet_point.hpp", "max_stars_repo_name": "brand666/liblanelet", "max_stars_repo_head_hexsha": "252e436ae9f705f8004d86b504be6a5f0c8bcc19", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T12:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T12:45:52.000Z", "max_issues_repo_path": "src/liblanelet/lanelet_point.hpp", "max_issues_repo_name": "brand666/liblanelet", "max_issues_repo_head_hexsha": "252e436ae9f705f8004d86b504be6a5f0c8bcc19", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-11-02T09:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T20:03:17.000Z", "max_forks_repo_path": "src/liblanelet/lanelet_point.hpp", "max_forks_repo_name": "brand666/liblanelet", "max_forks_repo_head_hexsha": "252e436ae9f705f8004d86b504be6a5f0c8bcc19", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-10-26T08:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T12:45:52.000Z", "avg_line_length": 34.0, "max_line_length": 176, "alphanum_fraction": 0.6184814351, "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.03789242988908073, "lm_q1q2_score": 0.015149834565571016}}
{"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/Galois.h\"\n#include \"galois/graphs/LCGraph.h\"\n\n#include \"llvm/Support/CommandLine.h\"\n#include \"Lonestar/BoilerPlate.h\"\n\n#include <boost/iterator/filter_iterator.hpp>\n\n#include <iomanip>\n#include <fstream>\n\nstatic const char* name = \"Betweenness Centrality\";\nstatic const char* desc = \"Computes the betweenness centrality of all nodes in \"\n                          \"a graph\";\nstatic const char* url = \"betweenness_centrality\";\n\nstatic llvm::cl::opt<std::string> filename(llvm::cl::Positional,\n                                           llvm::cl::desc(\"<input file>\"),\n                                           llvm::cl::Required);\nstatic llvm::cl::opt<int> iterLimit(\"limit\",\n                                    llvm::cl::desc(\"Limit number of iterations \"\n                                                   \"to value (0 is all nodes)\"),\n                                    llvm::cl::init(0));\nstatic llvm::cl::opt<unsigned int> startNode(\"startNode\",\n                                             llvm::cl::desc(\"Node to start \"\n                                                            \"search from\"),\n                                             llvm::cl::init(0));\nstatic llvm::cl::opt<bool> forceVerify(\"forceVerify\",\n                                       llvm::cl::desc(\"Abort if not verified; \"\n                                                      \"only makes sense for \"\n                                                      \"torus graphs\"));\nstatic llvm::cl::opt<bool> printAll(\"printAll\",\n                                    llvm::cl::desc(\"Print betweenness values \"\n                                                   \"for all nodes\"));\n\nusing Graph = galois::graphs::LC_CSR_Graph<void, void>::with_no_lockable<\n    true>::type ::with_numa_alloc<true>::type;\nusing GNode = Graph::GraphNode;\n\nclass BCOuter {\n  Graph* G;\n  int NumNodes;\n\n  galois::substrate::PerThreadStorage<double*> CB; // betweeness measure\n  galois::substrate::PerThreadStorage<double*> perThreadSigma;\n  galois::substrate::PerThreadStorage<int*> perThreadD;\n  galois::substrate::PerThreadStorage<double*> perThreadDelta;\n  galois::substrate::PerThreadStorage<galois::gdeque<GNode>*> perThreadSucc;\n\npublic:\n  /**\n   * Constructor initializes thread local storage.\n   */\n  BCOuter(Graph& g) : G(&g), NumNodes(g.size()) { InitializeLocal(); }\n\n  /**\n   * Constructor destroys thread local storage.\n   */\n  ~BCOuter(void) { DeleteLocal(); }\n\n  /**\n   * Runs betweeness-centrality proper.\n   *\n   * @tparam Cont type of the data structure that holds the nodes to treat\n   * as a source during betweeness-centrality.\n   *\n   * @param v Data structure that holds nodes to treat as a source during\n   * betweeness-centrality\n   */\n  template <typename Cont>\n  void run(const Cont& v) {\n    // Each thread works on an individual source node\n    galois::do_all(\n        galois::iterate(v),\n        [&](const GNode& curSource) {\n          galois::gdeque<GNode> SQ;\n\n          double* sigma               = *perThreadSigma.getLocal();\n          int* d                      = *perThreadD.getLocal();\n          double* delta               = *perThreadDelta.getLocal();\n          galois::gdeque<GNode>* succ = *perThreadSucc.getLocal();\n\n          sigma[curSource] = 1;\n          d[curSource]     = 1;\n\n          SQ.push_back(curSource);\n\n          // Do bfs while computing number of shortest paths (saved into sigma)\n          // and successors of nodes;\n          // Note this bfs makes it so source has distance of 1 instead of 0\n          for (auto qq = SQ.begin(), eq = SQ.end(); qq != eq; ++qq) {\n            int src = *qq;\n\n            for (auto edge : G->edges(src, galois::MethodFlag::UNPROTECTED)) {\n              int dest = G->getEdgeDst(edge);\n\n              if (!d[dest]) {\n                SQ.push_back(dest);\n                d[dest] = d[src] + 1;\n              }\n\n              if (d[dest] == d[src] + 1) {\n                sigma[dest] = sigma[dest] + sigma[src];\n                succ[src].push_back(dest);\n              }\n            }\n          }\n\n          // Back-propogate the dependency values (delta) along the BFS DAG\n          // ignore the source (hence SQ.size > 1 and not SQ.empty)\n          while (SQ.size() > 1) {\n            int leaf = SQ.back();\n            SQ.pop_back();\n\n            double sigma_leaf = sigma[leaf]; // has finalized short path value\n            double delta_leaf = delta[leaf];\n            auto& succ_list   = succ[leaf];\n\n            for (auto succ = succ_list.begin(), succ_end = succ_list.end();\n                 succ != succ_end; ++succ) {\n              delta_leaf += (sigma_leaf / sigma[*succ]) * (1.0 + delta[*succ]);\n            }\n            delta[leaf] = delta_leaf;\n          }\n\n          // save result of this source's BC, reset all local values for next\n          // source\n          double* Vec = *CB.getLocal();\n          for (int i = 0; i < NumNodes; ++i) {\n            Vec[i] += delta[i];\n            delta[i] = 0;\n            sigma[i] = 0;\n            d[i]     = 0;\n            succ[i].clear();\n          }\n        },\n        galois::steal(), galois::loopname(\"Main\"));\n  }\n\n  /**\n   * Verification for reference torus graph inputs.\n   * All nodes should have the same betweenness value up to\n   * some tolerance.\n   */\n  void verify() {\n    double sampleBC = 0.0;\n    bool firstTime  = true;\n    for (int i = 0; i < NumNodes; ++i) {\n      double bc = (*CB.getRemote(0))[i];\n\n      for (unsigned j = 1; j < galois::getActiveThreads(); ++j)\n        bc += (*CB.getRemote(j))[i];\n\n      if (firstTime) {\n        sampleBC = bc;\n        galois::gInfo(\"BC: \", sampleBC);\n        firstTime = false;\n      } else {\n        // check if over some tolerance value\n        if ((bc - sampleBC) > 0.0001) {\n          galois::gInfo(\"If torus graph, verification failed \",\n                        (bc - sampleBC));\n          if (forceVerify)\n            abort();\n          return;\n        }\n      }\n    }\n  }\n\n  /**\n   * Print betweeness-centrality measures.\n   *\n   * @param begin first node to print BC measure of\n   * @param end iterator after last node to print\n   * @param out stream to output to\n   * @param precision precision of the floating points outputted by the function\n   */\n  void printBCValues(size_t begin, size_t end, std::ostream& out,\n                     int precision = 6) {\n    for (; begin != end; ++begin) {\n      double bc = (*CB.getRemote(0))[begin];\n\n      for (unsigned j = 1; j < galois::getActiveThreads(); ++j)\n        bc += (*CB.getRemote(j))[begin];\n\n      out << begin << \" \" << std::setiosflags(std::ios::fixed)\n          << std::setprecision(precision) << bc << \"\\n\";\n    }\n  }\n\n  /**\n   * Print all betweeness centrality values in the graph.\n   */\n  void printBCcertificate() {\n    std::stringstream foutname;\n    foutname << \"outer_certificate_\" << galois::getActiveThreads();\n\n    std::ofstream outf(foutname.str().c_str());\n    galois::gInfo(\"Writing certificate...\");\n\n    printBCValues(0, NumNodes, outf, 9);\n\n    outf.close();\n  }\n\nprivate:\n  /**\n   * Initialize an array at some provided address.\n   *\n   * @param addr Address to initialize array at\n   */\n  template <typename T>\n  void initArray(T** addr) {\n    *addr = new T[NumNodes]();\n  }\n\n  /**\n   * Destroy an array at some provided address.\n   *\n   * @param addr Address to destroy array at\n   */\n  template <typename T>\n  void deleteArray(T** addr) {\n    delete[] * addr;\n  }\n\n  /**\n   * Initialize local thread storage.\n   */\n  void InitializeLocal(void) {\n    galois::on_each([this](unsigned, unsigned) {\n      this->initArray(CB.getLocal());\n      this->initArray(perThreadSigma.getLocal());\n      this->initArray(perThreadD.getLocal());\n      this->initArray(perThreadDelta.getLocal());\n      this->initArray(perThreadSucc.getLocal());\n    });\n  }\n\n  /**\n   * Destroy local thread storage.\n   */\n  void DeleteLocal(void) {\n    galois::on_each([this](unsigned, unsigned) {\n      this->deleteArray(CB.getLocal());\n      this->deleteArray(perThreadSigma.getLocal());\n      this->deleteArray(perThreadD.getLocal());\n      this->deleteArray(perThreadDelta.getLocal());\n      this->deleteArray(perThreadSucc.getLocal());\n    });\n  }\n};\n\n/**\n * Functor that indicates if a node contains outgoing edges\n */\nstruct HasOut : public std::unary_function<GNode, bool> {\n  Graph* graph;\n  HasOut(Graph* g) : graph(g) {}\n\n  bool operator()(const GNode& n) const {\n    return graph->edge_begin(n) != graph->edge_end(n);\n  }\n};\n\nint main(int argc, char** argv) {\n  galois::SharedMemSys Gal;\n  LonestarStart(argc, argv, name, desc, url);\n\n  Graph g;\n  galois::graphs::readGraph(g, filename);\n\n  BCOuter bcOuter(g);\n\n  size_t NumNodes = g.size();\n\n  // preallocate pages for use in algorithm\n  galois::reportPageAlloc(\"MeminfoPre\");\n  galois::preAlloc(galois::getActiveThreads() * NumNodes / 1650);\n  galois::reportPageAlloc(\"MeminfoMid\");\n\n  // preprocessing: find the nodes with out edges we will process and skip\n  // over nodes with no out edges\n\n  // find first node with out edges\n  boost::filter_iterator<HasOut, Graph::iterator> begin =\n      boost::make_filter_iterator(HasOut(&g), g.begin(), g.end());\n  boost::filter_iterator<HasOut, Graph::iterator> end =\n      boost::make_filter_iterator(HasOut(&g), g.end(), g.end());\n  // adjustedEnd = last node we will process based on how many iterations\n  // (i.e. sources) we want to do\n  boost::filter_iterator<HasOut, Graph::iterator> adjustedEnd =\n      iterLimit ? galois::safe_advance(begin, end, (int)iterLimit) : end;\n\n  size_t iterations = std::distance(begin, adjustedEnd);\n\n  // vector of nodes we want to process\n  std::vector<GNode> v(begin, adjustedEnd);\n\n  galois::gPrint(\"Num Nodes: \", NumNodes, \" Start Node: \", startNode,\n                 \" Iterations: \", iterations, \"\\n\");\n\n  // execute algorithm\n  galois::StatTimer T;\n  T.start();\n  bcOuter.run(v);\n  T.stop();\n\n  bcOuter.printBCValues(0, std::min(10ul, NumNodes), std::cout, 6);\n\n  if (printAll)\n    bcOuter.printBCcertificate();\n  if (forceVerify || !skipVerify)\n    bcOuter.verify();\n\n  galois::reportPageAlloc(\"MeminfoPost\");\n\n  return 0;\n}\n", "meta": {"hexsha": "215912f067e284f8b595e9596d28302793473a25", "size": 11234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/betweennesscentrality/BetweennessCentralityOuter.cpp", "max_stars_repo_name": "rohankadekodi/compilers_project", "max_stars_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "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/betweennesscentrality/BetweennessCentralityOuter.cpp", "max_issues_repo_name": "rohankadekodi/compilers_project", "max_issues_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-02-27T19:24:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T21:04:28.000Z", "max_forks_repo_path": "lonestar/betweennesscentrality/BetweennessCentralityOuter.cpp", "max_forks_repo_name": "rohankadekodi/compilers_project", "max_forks_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T22:00:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T10:18:02.000Z", "avg_line_length": 33.0411764706, "max_line_length": 85, "alphanum_fraction": 0.5891935197, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.033085980772241536, "lm_q1q2_score": 0.015124816623240118}}
{"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\n#include <boost/graph/graph_traits.hpp>\n\nnamespace boost {\n\n// r_c_shortest_paths_label struct\ntemplate<class Graph, class Resource_Container>\nstruct r_c_shortest_paths_label\n{\n  r_c_shortest_paths_label\n  ( const unsigned long n, \n    const Resource_Container& rc = Resource_Container(), \n    const r_c_shortest_paths_label* const pl = 0, \n    const typename graph_traits<Graph>::edge_descriptor& ed = \n      graph_traits<Graph>::edge_descriptor(), \n    const typename graph_traits<Graph>::vertex_descriptor& vd = \n      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  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 r_c_shortest_paths_label* const 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\nnamespace detail {\n\n// ks_smart_pointer class\n// from:\n// Kuhlins, S.; Schader, M. (1999):\n// Die C++-Standardbibliothek\n// Springer, Berlin\n// p. 333 f.\ntemplate<class T>\nclass ks_smart_pointer\n{\npublic:\n  ks_smart_pointer( T* ptt = 0 ) : pt( ptt ) {}\n  ks_smart_pointer( const ks_smart_pointer& other ) : pt( other.pt ) {}\n  ks_smart_pointer& operator=( const ks_smart_pointer& other )\n    { pt = other.pt; return *this; }\n  ~ks_smart_pointer() {}\n  T& operator*() const { return *pt; }\n  T* operator->() const { return pt; }\n  T* get() const { return pt; }\n  operator T*() const { return pt; }\n  friend bool operator==( const ks_smart_pointer& t, \n                          const ks_smart_pointer& u )\n    { return *t.pt == *u.pt; }\n  friend bool operator!=( const ks_smart_pointer& t, \n                          const ks_smart_pointer& u )\n    { return *t.pt != *u.pt; }\n  friend bool operator<( const ks_smart_pointer& t, \n                         const ks_smart_pointer& u )\n    { return *t.pt < *u.pt; }\n  friend bool operator>( const ks_smart_pointer& t, \n                         const ks_smart_pointer& u )\n    { return *t.pt > *u.pt; }\n  friend bool operator<=( const ks_smart_pointer& t, \n                          const ks_smart_pointer& u )\n    { return *t.pt <= *u.pt; }\n  friend bool operator>=( const ks_smart_pointer& t, \n                          const ks_smart_pointer& u )\n    { return *t.pt >= *u.pt; }\nprivate:\n  T* pt;\n}; // ks_smart_pointer\n\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  unsigned long i_label_num = 0;\n  typedef \n    typename \n      Label_Allocator::template rebind\n        <r_c_shortest_paths_label\n          <Graph, Resource_Container> >::other LAlloc;\n  LAlloc l_alloc;\n  typedef \n    ks_smart_pointer\n      <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  r_c_shortest_paths_label<Graph, Resource_Container>* first_label = \n    l_alloc.allocate( 1 );\n  l_alloc.construct\n    ( first_label, \n      r_c_shortest_paths_label\n        <Graph, Resource_Container>( i_label_num++, \n                                     rc, \n                                     0, \n                                     typename graph_traits<Graph>::\n                                       edge_descriptor(), \n                                     s ) );\n\n  Splabel splabel_first_label = Splabel( first_label );\n  unprocessed_labels.push( splabel_first_label );\n  std::vector<std::list<Splabel> > vec_vertex_labels( num_vertices( g ) );\n  vec_vertex_labels[vertex_index_map[s]].push_back( splabel_first_label );\n  std::vector<typename std::list<Splabel>::iterator> \n    vec_last_valid_positions_for_dominance( num_vertices( g ) );\n  for( int i = 0; i < static_cast<int>( num_vertices( g ) ); ++i )\n    vec_last_valid_positions_for_dominance[i] = vec_vertex_labels[i].begin();\n  std::vector<int> vec_last_valid_index_for_dominance( num_vertices( g ), 0 );\n  std::vector<bool> \n    b_vec_vertex_already_checked_for_dominance( num_vertices( g ), false );\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      int i_cur_resident_vertex_num = cur_label->resident_vertex;\n      std::list<Splabel>& list_labels_cur_vertex = \n        vec_vertex_labels[i_cur_resident_vertex_num];\n      if( static_cast<int>( list_labels_cur_vertex.size() ) >= 2 \n          && vec_last_valid_index_for_dominance[i_cur_resident_vertex_num] \n               < static_cast<int>( 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                   vec_last_valid_positions_for_dominance\n                     [i_cur_resident_vertex_num] )\n            b_outer_iter_at_or_beyond_last_valid_pos_for_dominance = true;\n          if( !b_vec_vertex_already_checked_for_dominance\n                [i_cur_resident_vertex_num] \n              || b_outer_iter_at_or_beyond_last_valid_pos_for_dominance )\n          {\n            ++inner_iter;\n          }\n          else\n          {\n            inner_iter = \n              vec_last_valid_positions_for_dominance\n                [i_cur_resident_vertex_num];\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                l_alloc.destroy( cur_inner_splabel.get() );\n                l_alloc.deallocate( cur_inner_splabel.get(), 1 );\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                l_alloc.destroy( cur_outer_splabel.get() );\n                l_alloc.deallocate( cur_outer_splabel.get(), 1 );\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( static_cast<int>( list_labels_cur_vertex.size() ) > 1 )\n          vec_last_valid_positions_for_dominance[i_cur_resident_vertex_num] = \n            (--(list_labels_cur_vertex.end()));\n        else\n          vec_last_valid_positions_for_dominance[i_cur_resident_vertex_num] = \n            list_labels_cur_vertex.begin();\n        b_vec_vertex_already_checked_for_dominance\n          [i_cur_resident_vertex_num] = true;\n        vec_last_valid_index_for_dominance[i_cur_resident_vertex_num] = \n          static_cast<int>( 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        l_alloc.destroy( cur_label.get() );\n        l_alloc.deallocate( cur_label.get(), 1 );\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_alloc.destroy( l.get() );\n          l_alloc.deallocate( l.get(), 1 );\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        r_c_shortest_paths_label<Graph, Resource_Container>* new_label = \n          l_alloc.allocate( 1 );\n        l_alloc.construct( new_label, \n                           r_c_shortest_paths_label\n                             <Graph, Resource_Container>\n                               ( i_label_num++, \n                                 cur_label->cumulated_resource_consumption, \n                                 cur_label.get(), \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          l_alloc.destroy( new_label );\n          l_alloc.deallocate( new_label, 1 );\n        }\n        else\n        {\n          const r_c_shortest_paths_label<Graph, Resource_Container>& \n            ref_new_label = *new_label;\n          vis.on_label_feasible( ref_new_label, g );\n          Splabel new_sp_label( new_label );\n          vec_vertex_labels[vertex_index_map[new_sp_label->resident_vertex]].\n            push_back( new_sp_label );\n          unprocessed_labels.push( new_sp_label );\n        }\n      }\n    }\n    else\n    {\n      vis.on_label_dominated( *cur_label, g );\n      l_alloc.destroy( cur_label.get() );\n      l_alloc.deallocate( cur_label.get(), 1 );\n    }\n  }\n  std::list<Splabel> dsplabels = vec_vertex_labels[vertex_index_map[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      const r_c_shortest_paths_label<Graph, Resource_Container>* p_cur_label = \n        (*csi).get();\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      pareto_optimal_solutions.push_back( cur_pareto_optimal_path );\n      if( !b_all_pareto_optimal_solutions )\n        break;\n    }\n  }\n\n  int i_size = static_cast<int>( vec_vertex_labels.size() );\n  for( int i = 0; i < i_size; ++i )\n  {\n    const std::list<Splabel>& list_labels_cur_vertex = vec_vertex_labels[i];\n    csi_end = list_labels_cur_vertex.end();\n    for( csi = list_labels_cur_vertex.begin(); csi != csi_end; ++csi )\n    {\n      l_alloc.destroy( (*csi).get() );\n      l_alloc.deallocate( (*csi).get(), 1 );\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  int i_size_ed_vec_path = static_cast<int>( 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( int i = i_size_ed_vec_path - 1; i >= 0; --i )\n        buf_path.push_back( ed_vec_path[i] );\n    for( int 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( int 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": "28755d8724a8b5685c7fc9996054ebfc8c1208bf", "size": 27829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extlibs/miniBoost/boost/graph/r_c_shortest_paths.hpp", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-12-05T19:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T09:07:09.000Z", "max_issues_repo_path": "boost/graph/r_c_shortest_paths.hpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_issues_repo_licenses": ["BSL-1.0"], "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/graph/r_c_shortest_paths.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T00:09:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T10:47:11.000Z", "avg_line_length": 37.8111413043, "max_line_length": 83, "alphanum_fraction": 0.6366739732, "num_tokens": 6348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.0330859781503504, "lm_q1q2_score": 0.015124814935281141}}
{"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) 2004, 2005, 2006 Ferdinando Ametrano\n Copyright (C) 2006 Katiuscia Manzoni\n Copyright (C) 2015 Maddalena Zanzi\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/time/asx.hpp>\n#include \"ql_settings.hpp\"\n#include \"ql_utilities_dataparsers.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/algorithm/string/case_conv.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n//using boost::algorithm::to_upper_copy;\n//using std::string;\n\nnamespace QuantLib {\n    template <class ExtDate> inline\n    bool ASX<ExtDate>::isASXdate(const ExtDate& dat, bool mainCycle) {\n        auto date = to_DateLike(dat);\n        auto s = date.serialNumber();\n        if (date.weekday(s)!=Friday)\n            return false;\n\n        Day d = date.dayOfMonth(s);\n        if (d<8 || d>14)\n            return false;\n\n        if (!mainCycle) return true;\n\n        switch (date.month(s)) {\n          case March:\n          case June:\n          case September:\n          case December:\n            return true;\n          default:\n            return false;\n        }\n    }\n    template <class ExtDate> inline\n    bool ASX<ExtDate>::isASXcode(const std::string& in, bool mainCycle) {\n        if (in.length() != 2)\n            return false;\n\n        std::string str1(\"0123456789\");\n        std::string::size_type loc = str1.find(in.substr(1, 1), 0);\n        if (loc == std::string::npos)\n            return false;\n\n        if (mainCycle) str1 = \"hmzuHMZU\";\n        else           str1 = \"fghjkmnquvxzFGHJKMNQUVXZ\";\n        loc = str1.find(in.substr(0,1), 0);\n        return loc != std::string::npos;\n    }\n    template <class ExtDate> inline\n    std::string ASX<ExtDate>::code(const ExtDate& date) {\n        QL_REQUIRE(isASXdate(date, false),\n                   \"{} is not an ASX date\",date);\n\n        std::ostringstream ASXcode;\n        unsigned int y = to_DateLike(date).year() % 10;\n        switch(to_DateLike(date).month()) {\n          case January:\n            ASXcode << 'F' << y;\n            break;\n          case February:\n            ASXcode << 'G' << y;\n            break;\n          case March:\n            ASXcode << 'H' << y;\n            break;\n          case April:\n            ASXcode << 'J' << y;\n            break;\n          case May:\n            ASXcode << 'K' << y;\n            break;\n          case June:\n            ASXcode << 'M' << y;\n            break;\n          case July:\n            ASXcode << 'N' << y;\n            break;\n          case August:\n            ASXcode << 'Q' << y;\n            break;\n          case September:\n            ASXcode << 'U' << y;\n            break;\n          case October:\n            ASXcode << 'V' << y;\n            break;\n          case November:\n            ASXcode << 'X' << y;\n            break;\n          case December:\n            ASXcode << 'Z' << y;\n            break;\n          default:\n            QL_FAIL(\"not an ASX month (and it should have been)\");\n        }\n\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_ENSURE(isASXcode(ASXcode.str(), false),\n                  \"the result {} is an invalid ASX code\", ASXcode.str() );\n        #endif\n        return ASXcode.str();\n    }\n    template <class ExtDate> inline\n    ExtDate ASX<ExtDate>::date(const std::string& asxCode,\n                   const ExtDate& refExtDate) {\n        QL_REQUIRE(isASXcode(asxCode, false), \"{} is not a valid ASX code\", asxCode );\n\n        DateLike<ExtDate> referenceExtDate{\n            (to_DateLike(refExtDate) != ExtDate() ?\n                 refExtDate :\n                 ExtDate(Settings<ExtDate>::instance().evaluationDate()))};\n        auto to_upper_copy = [](const std::string& s) { std::string res; for (auto i:s) res.push_back(std::toupper(i)); return res;};\n        std::string code = to_upper_copy(asxCode);\n        std::string ms = code.substr(0,1);\n        QuantLib::Month m;\n        if (ms==\"F\")      m = January;\n        else if (ms==\"G\") m = February;\n        else if (ms==\"H\") m = March;\n        else if (ms==\"J\") m = April;\n        else if (ms==\"K\") m = May;\n        else if (ms==\"M\") m = June;\n        else if (ms==\"N\") m = July;\n        else if (ms==\"Q\") m = August;\n        else if (ms==\"U\") m = September;\n        else if (ms==\"V\") m = October;\n        else if (ms==\"X\") m = November;\n        else if (ms==\"Z\") m = December;\n        else QL_FAIL(\"invalid ASX month letter\");\n\n//        Year y = boost::lexical_cast<Year>(); // lexical_cast causes compilation errors with x64\n\n        Year y= io::to_integer(code.substr(1,1));\n        /* year<1900 are not valid QuantLib years: to avoid a run-time\n           exception few lines below we need to add 10 years right away */\n        if (y==0 && referenceExtDate.year()<=1909) y+=10;\n        Year referenceYear = (referenceExtDate.year() % 10);\n        y += referenceExtDate.year() - referenceYear;\n        ExtDate result = ASX<ExtDate>::nextDate(DateAdaptor<ExtDate>::Date(1, m, y), false);\n        if (result<referenceExtDate)\n            return ASX<ExtDate>::nextDate(DateAdaptor<ExtDate>::Date(1, m, y + 10), false);\n\n        return result;\n    }\n    template <class ExtDate> inline\n    ExtDate ASX<ExtDate>::nextDate(const ExtDate& date, bool mainCycle) {\n        DateLike<ExtDate> refExtDate{(to_DateLike(date) == ExtDate() ?\n                                          ExtDate(Settings<ExtDate>::instance().evaluationDate()) :\n                                          date)};\n        Year y = refExtDate.year();\n        QuantLib::Month m = refExtDate.month();\n\n        Size offset = mainCycle ? 3 : 1;\n        Size skipMonths = offset-(m%offset);\n        if (skipMonths != offset || refExtDate.dayOfMonth() > 14) {\n            skipMonths += Size(m);\n            if (skipMonths<=12) {\n                m = QuantLib::Month(skipMonths);\n            } else {\n                m = QuantLib::Month(skipMonths-12);\n                y += 1;\n            }\n        }\n\n        ExtDate result = DateLike<ExtDate>::nthWeekday(2, Friday, m, y);\n        if (result<=refExtDate)\n            result = nextDate(DateAdaptor<ExtDate>::Date(15, m, y), mainCycle);\n        return result;\n    }\n    template <class ExtDate> inline\n    ExtDate ASX<ExtDate>::nextDate(const std::string& ASXcode,\n                       bool mainCycle,\n                       const ExtDate& referenceExtDate)  {\n        ExtDate asxExtDate = date(ASXcode, referenceExtDate);\n        return nextDate(asxExtDate+1, mainCycle);\n    }\n    template <class ExtDate> inline\n    std::string ASX<ExtDate>::nextCode(const ExtDate& d,\n                              bool mainCycle) {\n        ExtDate date = nextDate(d, mainCycle);\n        return code(date);\n    }\n    template <class ExtDate> inline\n    std::string ASX<ExtDate>::nextCode(const std::string& asxCode,\n                              bool mainCycle,\n                              const ExtDate& referenceExtDate) {\n        ExtDate date = nextDate(asxCode, mainCycle, referenceExtDate);\n        return code(date);\n    }\n\n}\n", "meta": {"hexsha": "3710803432774acea86189f8f34dd4d1b4a5d083", "size": 7996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/time/asx.cpp", "max_stars_repo_name": "reder2000/QuantLib", "max_stars_repo_head_hexsha": "1d58c3859a0872722aa570283c6571aeb64f6f39", "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/time/asx.cpp", "max_issues_repo_name": "reder2000/QuantLib", "max_issues_repo_head_hexsha": "1d58c3859a0872722aa570283c6571aeb64f6f39", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T06:52:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:41:08.000Z", "max_forks_repo_path": "ql/time/asx.cpp", "max_forks_repo_name": "reder2000/QuantLib", "max_forks_repo_head_hexsha": "1d58c3859a0872722aa570283c6571aeb64f6f39", "max_forks_repo_licenses": ["BSD-3-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.3454545455, "max_line_length": 133, "alphanum_fraction": 0.5591545773, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.0481367731649316, "lm_q1q2_score": 0.015117379228508017}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n#include <tudat/basics/testMacros.h>\n\n#include <tudat/simulation/simulation.h>\n#include <tudat/io/basicInputOutput.h>\n#include <tudat/io/applicationOutput.h>\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionHodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsHodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsSphericalShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionSphericalShaping.h\"\n#include \"tudat/astro/LowThrustTrajectories/ShapeBasedMethods/sphericalShaping.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/simulation/simulation.h\"\n#include \"tudat/interface/spice/spiceEphemeris.h\"\n\nusing namespace tudat;\nusing namespace tudat::input_output;\nusing namespace tudat::simulation_setup;\nusing namespace tudat::shape_based_methods;\n\nSystemOfBodies getBetBodyMap( )\n{\n    // Create central, departure and arrival bodies.\n    std::vector< std::string > bodiesToCreate;\n    bodiesToCreate.push_back( \"Sun\" );\n    bodiesToCreate.push_back( \"Earth\" );\n    bodiesToCreate.push_back( \"Mars\" );\n    bodiesToCreate.push_back( \"Jupiter\" );\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[ \"Sun\" ]->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[ \"Sun\" ]->ephemerisSettings->resetFrameOrientation( frameOrientation );\n    bodySettings[ \"Sun\" ]->rotationModelSettings->resetOriginalFrame( frameOrientation );\n\n\n    // Create system of bodies.\n    simulation_setup::SystemOfBodies bodies = createBodies( bodySettings );\n\n    bodies[ \"Borzi\" ] = std::make_shared< simulation_setup::Body >( );\n    bodies.at( \"Borzi\" )->setSuppressDependentOrientationCalculatorWarning( true );\n    bodies.at( \"Borzi\" )->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(\n                                                         std::shared_ptr< interpolators::OneDimensionalInterpolator\n                                                         < double, Eigen::Vector6d > >( ), frameOrigin, frameOrientation ) );\n\n    // Create radiation pressure settings\n    double referenceAreaRadiation = 4.0;\n    double radiationPressureCoefficient = 1.2;\n    std::vector< std::string > occultingBodies;\n    occultingBodies.push_back( \"Earth\" );\n    std::shared_ptr< RadiationPressureInterfaceSettings > asterixRadiationPressureSettings =\n            std::make_shared< CannonBallRadiationPressureInterfaceSettings >(\n                \"Sun\", referenceAreaRadiation, radiationPressureCoefficient, occultingBodies );\n\n    // Create and set radiation pressure settings\n    bodies[ \"Borzi\" ]->setRadiationPressureInterface(\n                \"Sun\", createRadiationPressureInterface(\n                    asterixRadiationPressureSettings, \"Borzi\", bodies ) );\n\n    setGlobalFrameBodyEphemerides( bodies, frameOrigin, frameOrientation );\n\n    return bodies;\n}\n\nint main( )\n{\n\n    std::string outputSubFolder = \"ShapeBasedTrajectoriesExample/\";\n    spice_interface::loadStandardSpiceKernels( );\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////           DEFINE TRAJECTORY GLOBAL PARAMETERS      ////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    int numberOfRevolutions = 1;\n    double julianDateAtDeparture = 8174.5 * physical_constants::JULIAN_DAY;\n    double timeOfFlight = 580.0 * physical_constants::JULIAN_DAY;\n    double vehicleInitialMass = 2000.0;\n    double specificImpulse = 3000.0;\n\n    std::function< double( const double ) > specificImpulseFunction = [ = ]( const double ){ return specificImpulse; };\n\n    // Retrieve cartesian state at departure and arrival.\n    ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );\n    ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );\n    Eigen::Vector6d cartesianStateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( julianDateAtDeparture );\n    Eigen::Vector6d cartesianStateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState( julianDateAtDeparture + timeOfFlight );\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////////////             DEFINE HODOGRAPHIC SHAPING LEG          ////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    double frequency = 2.0 * mathematical_constants::PI / timeOfFlight;\n    double scaleFactor = 1.0 / timeOfFlight;\n\n    // Create base function settings for the components of 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< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\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( scaledPower, 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< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );\n\n    // Create components of the normal velocity composite 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( scaledPower, 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    // Create components for the axial velocity composite 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    // Initialize free coefficients vector for radial velocity function (empty here, only 3 base functions).\n    Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Initialize free coefficients vector for normal velocity function (empty here, only 3 base functions).\n    Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Initialize free coefficients vector for axial velocity function (empty here, only 3 base functions).\n    Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );\n\n    // Create hodographic-shaping object with defined velocity functions and boundary conditions.\n    shape_based_methods::HodographicShaping hodographicShaping(\n                cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ), 1,\n                radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,\n                freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,\n                vehicleInitialMass );\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ///////////////////////////////             DEFINE SPHERICAL SHAPING LEG            ////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).\n    std::shared_ptr< root_finders::RootFinderSettings > rootFinderSettings =\n            std::make_shared< root_finders::RootFinderSettings >( root_finders::bisection_root_finder, 1.0e-6, 30 );\n\n    // Compute shaped trajectory.\n    shape_based_methods::SphericalShaping sphericalShaping = shape_based_methods::SphericalShaping(\n                cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,\n                spice_interface::getBodyGravitationalParameter( \"Sun\" ),\n                numberOfRevolutions, 0.000703,\n                rootFinderSettings, 1.0e-6, 1.0e-1, vehicleInitialMass );\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //////////////////////////////         CREATE ENVIRONMENT                              /////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n    // Set vehicle mass.\n    SystemOfBodies bodies = getBetBodyMap( );\n    bodies[ \"Borzi\" ]->setConstantBodyMass( vehicleInitialMass );\n\n\n    // Define body to propagate and central body.\n    std::vector< std::string > bodiesToPropagate;\n    std::vector< std::string > centralBodies;\n    bodiesToPropagate.push_back( \"Borzi\" );\n    centralBodies.push_back( \"Sun\" );\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////                 DEFINE PROPAGATION SETTINGS                   /////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Define integrator settings.\n    double stepSize = timeOfFlight / static_cast< double >( 8000.0 );\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    // Define list of dependent variables to save.\n    std::vector< std::shared_ptr< propagators::SingleDependentVariableSaveSettings > > dependentVariablesList;\n\n    // Create object with list of dependent variables\n    std::shared_ptr< propagators::DependentVariableSaveSettings > dependentVariablesToSave =\n            std::make_shared< propagators::DependentVariableSaveSettings >( dependentVariablesList, false );\n\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////       NUMERICALLY PROPAGATE THE SIMPLIFIED PROBLEM            /////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n    std::map< double, Eigen::VectorXd > hodographicShapingPropagationUnperturbedCase;\n    std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResults;\n    std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistory;\n\n    // Create propagator settings for hodographic shaping.\n    std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >\n            hodographicShapingPropagatorSettings = hodographicShaping.createLowThrustPropagatorSettings(\n                bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,\n                basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );\n\n    // Compute shaped trajectory and propagated trajectory.\n    hodographicShaping.computeSemiAnalyticalAndFullPropagation(\n                bodies, integratorSettings, hodographicShapingPropagatorSettings, hodographicShapingPropagationUnperturbedCase,\n                hodographicShapingAnalyticalResults, hodographicShapingDependentVariablesHistory );\n\n\n    std::map< double, Eigen::VectorXd > sphericalShapingPropagationUnperturbedCase;\n    std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResults;\n    std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistory;\n\n    // Create propagator settings for spherical shaping.\n    std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >\n            sphericalShapingPropagatorSettings = sphericalShaping.createLowThrustPropagatorSettings(\n                bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,\n                basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );\n\n    // Compute shaped trajectory and propagated trajectory.\n    sphericalShaping.computeSemiAnalyticalAndFullPropagation(\n                bodies, integratorSettings, sphericalShapingPropagatorSettings, sphericalShapingPropagationUnperturbedCase,\n                sphericalShapingAnalyticalResults, sphericalShapingDependentVariablesHistory );\n\n    input_output::writeDataMapToTextFile( hodographicShapingAnalyticalResults,\n                                          \"hodographicShapingAnalyticalResults.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( sphericalShapingAnalyticalResults,\n                                          \"sphericalShapingAnalyticalResults.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( hodographicShapingPropagationUnperturbedCase,\n                                          \"hodographicShapingPropagationUnperturbedCase.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( sphericalShapingPropagationUnperturbedCase,\n                                          \"sphericalShapingPropagationUnperturbedCase.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    ////////////////////         RETRIEVE TRAJECTORY, MASS, THRUST AND THRUST ACCELERATION PROFILES           //////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // Hodographic shaping\n    std::vector< double > epochsVectorHodographicShaping;\n    for ( std::map< double, Eigen::Vector6d >::iterator itr = hodographicShapingAnalyticalResults.begin( ) ;\n          itr != hodographicShapingAnalyticalResults.end( ) ; itr++ )\n    {\n        epochsVectorHodographicShaping.push_back( itr->first );\n    }\n\n    std::map< double, Eigen::VectorXd > hodographicShapingMassProfile;\n    std::map< double, Eigen::VectorXd > hodographicShapingThrustProfile;\n    std::map< double, Eigen::VectorXd > hodographicShapingThrustAccelerationProfile;\n\n    hodographicShaping.getMassProfile(\n                epochsVectorHodographicShaping, hodographicShapingMassProfile, specificImpulseFunction, integratorSettings );\n    hodographicShaping.getThrustForceProfile(\n                epochsVectorHodographicShaping, hodographicShapingThrustProfile, specificImpulseFunction, integratorSettings );\n    hodographicShaping.getThrustAccelerationProfile(\n                epochsVectorHodographicShaping, hodographicShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );\n\n\n    // Spherical shaping\n    std::vector< double > epochsVectorSphericalShaping;\n    for ( std::map< double, Eigen::Vector6d >::iterator itr = sphericalShapingAnalyticalResults.begin( ) ;\n          itr != sphericalShapingAnalyticalResults.end( ) ; itr++ )\n    {\n        epochsVectorSphericalShaping.push_back( itr->first );\n    }\n\n    std::map< double, Eigen::VectorXd > sphericalShapingMassProfile;\n    std::map< double, Eigen::VectorXd > sphericalShapingThrustProfile;\n    std::map< double, Eigen::VectorXd > sphericalShapingThrustAccelerationProfile;\n\n    sphericalShaping.getMassProfile(\n                epochsVectorSphericalShaping, sphericalShapingMassProfile, specificImpulseFunction, integratorSettings );\n    sphericalShaping.getThrustForceProfile(\n                epochsVectorSphericalShaping, sphericalShapingThrustProfile, specificImpulseFunction, integratorSettings );\n    sphericalShaping.getThrustAccelerationProfile(\n                epochsVectorSphericalShaping, sphericalShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //////////////////////////////         DEFINE PERTURBED DYNAMICAL ENVIRONMENT          /////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n    // Define propagation settings.\n    std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationSettingsPerturbedProblem;\n    accelerationSettingsPerturbedProblem[ \"Earth\" ].push_back( std::make_shared< AccelerationSettings >(\n                                                     basic_astrodynamics::central_gravity ) );\n    accelerationSettingsPerturbedProblem[ \"Mars\" ].push_back( std::make_shared< AccelerationSettings >(\n                                                     basic_astrodynamics::central_gravity ) );\n    accelerationSettingsPerturbedProblem[ \"Jupiter\" ].push_back( std::make_shared< AccelerationSettings >(\n                                                     basic_astrodynamics::central_gravity ) );\n    accelerationSettingsPerturbedProblem[ \"Sun\" ].push_back( std::make_shared< AccelerationSettings >(\n                                                     basic_astrodynamics::cannon_ball_radiation_pressure ) );\n\n    SelectedAccelerationMap accelerationMap;\n\n    accelerationMap[ \"Borzi\" ] = accelerationSettingsPerturbedProblem;\n    bodiesToPropagate.push_back( \"Borzi\" );\n    centralBodies.push_back( \"Sun\" );\n\n    basic_astrodynamics::AccelerationMap perturbingAccelerationsMapPertubedProblem = createAccelerationModelsMap(\n                bodies, accelerationMap, bodiesToPropagate, centralBodies );\n\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    //////////////////////////////         PROPAGATE THE FULLY PERTURBED PROBLEM           /////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    std::map< double, Eigen::VectorXd > hodographicShapingPropagationPerturbedCase;\n    std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResultsPerturbedCase;\n    std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistoryPerturbedCase;\n\n    std::map< double, Eigen::VectorXd > sphericalShapingPropagationPerturbedCase;\n    std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResultsPerturbedCase;\n    std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistoryPerturbedCase;\n\n    // Create propagator settings for hodographic shaping.\n    std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >\n            hodographicShapingPropagatorSettingsPerturbedCase = hodographicShaping.createLowThrustPropagatorSettings(\n                bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,\n                perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );\n\n    // Compute shaped trajectory and propagated trajectory.\n    hodographicShaping.computeSemiAnalyticalAndFullPropagation(\n                bodies, integratorSettings, hodographicShapingPropagatorSettingsPerturbedCase, hodographicShapingPropagationPerturbedCase,\n                hodographicShapingAnalyticalResultsPerturbedCase, hodographicShapingDependentVariablesHistoryPerturbedCase );\n\n    // Create propagator settings for spherical shaping.\n    std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >\n            sphericalShapingPropagatorSettingsPerturbedCase = sphericalShaping.createLowThrustPropagatorSettings(\n                bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,\n                perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );\n\n    // Compute shaped trajectory and propagated trajectory.\n    sphericalShaping.computeSemiAnalyticalAndFullPropagation(\n                bodies, integratorSettings, sphericalShapingPropagatorSettingsPerturbedCase, sphericalShapingPropagationPerturbedCase,\n                sphericalShapingAnalyticalResultsPerturbedCase, sphericalShapingDependentVariablesHistoryPerturbedCase );\n\n\n\n    input_output::writeDataMapToTextFile( hodographicShapingPropagationPerturbedCase,\n                                          \"hodographicShapingPropagationPerturbedCase.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( sphericalShapingPropagationPerturbedCase,\n                                          \"sphericalShapingPropagationPerturbedCase.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\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_applications::getOutputPath( ) + outputSubFolder,\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_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( hodographicShapingThrustAccelerationProfile,\n                                          \"hodographicShapingThrustAccelerationProfile.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( sphericalShapingMassProfile,\n                                          \"sphericalShapingMassProfile.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( sphericalShapingThrustProfile,\n                                          \"sphericalShapingThrustProfile.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    input_output::writeDataMapToTextFile( sphericalShapingThrustAccelerationProfile,\n                                          \"sphericalShapingThrustAccelerationProfile.dat\",\n                                          tudat_applications::getOutputPath( ) + outputSubFolder,\n                                          \"\",\n                                          std::numeric_limits< double >::digits10,\n                                          std::numeric_limits< double >::digits10,\n                                          \",\" );\n\n    std::cout << \"deltaV hodographic shaping: \" << hodographicShaping.computeDeltaV( ) << \"\\n\\n\";\n    std::cout << \"deltaV spherical shaping: \" << sphericalShaping.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": "c85bb28c08356971479658838a517e22bf5cbf98", "size": 31037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.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": 63.4703476483, "max_line_length": 142, "alphanum_fraction": 0.6099494152, "num_tokens": 5950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.03676946422843365, "lm_q1q2_score": 0.015116326400152464}}
{"text": "#pragma once\n\n#if defined(_MSC_VER)\n/* Disable some warnings on MSVC++ */\n#pragma warning(disable : 4127 4702 4100 4515 4800 4146 4512 4819 4334)\n#define WIN32_LEAN_AND_MEAN     /* Don't ever include MFC on Windows */\n#define NOMINMAX                /* Don't override Min/max */\n#endif\n\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <memory>\n#include <map>\n#include <cstdint>\n#include <thread>\n#include <stdexcept>\n#include <limits>\n#include <iomanip>\n#include <time.h>\n\n#include <Eigen\\Core>\n#include <Eigen\\Geometry>\n#include <Eigen\\Lu>\n#include <glog\\logging.h>\n#include <tinyformat.h>\n#include <ImathPlatform.h>\n#include <filesystem\\resolver.h>\n\n#define NAMESPACE_BEGIN namespace Hikari {\n#define NAMESPACE_END }\n\n#if defined(MACOS)\n\t#define __PLATFORM_MACOS__\n#elif defined(LINUX)\n\t#define __PLATFORM_LINUX__\n#elif defined(WIN32)\n\t#define __PLATFORM_WINDOWS__\n#endif\n\n/* \"Ray epsilon\": relative error threshold for ray intersection computations */\n#define Epsilon 1e-4\n\n/* Used for BSDF::Eval() or BSDF::PDF() for the delta distribution. */\n#define DeltaEpsilon 1e-3\n\n/* To avoid the numerical error in computation */\n#define MIN_ALPHA 5e-4\n#define MAX_ALPHA 1.0\n\n/* A few useful constants */\n#undef M_PI\n\n#define M_PI         3.14159265358979323846\n#define INV_PI       0.31830988618379067154\n#define INV_TWOPI    0.15915494309189533577\n#define INV_FOURPI   0.07957747154594766788\n#define SQRT_TWO     1.41421356237309504880\n#define INV_SQRT_TWO 0.70710678118654752440\n\n/* XML fields name */\n#define XML_TYPE(Field)     Field##_XmlType\n#define XML_VALUE(Field)    Field##_XmlValue\n\n#define XML_TRANSFORM_TRANSLATE                  \"translate\"\n#define XML_TRANSFORM_MATRIX                     \"matrix\"\n#define XML_TRANSFORM_ROTATE                     \"rotate\"\n#define XML_TRANSFORM_ANGLE                      \"angle\"\n#define XML_TRANSFORM_AXIS                       \"axis\"\n#define XML_TRANSFORM_SCALE                      \"scale\"\n#define XML_TRANSFORM_LOOKAT                     \"lookat\"\n#define XML_TRANSFORM_ORIGIN                     \"origin\"\n#define XML_TRANSFORM_TARGET                     \"target\"\n#define XML_TRANSFORM_UP                         \"up\"\n\n#define XML_INTEGRATOR                           \"integrator\"\n#define XML_INTEGRATOR_NORMAL                    \"normals\"\n#define XML_INTEGRATOR_SIMPLE                    \"simple\"\n#define XML_INTEGRATOR_SIMPLE_POSITION           \"position\"\n#define XML_INTEGRATOR_SIMPLE_POWER              \"power\"\n#define XML_INTEGRATOR_AO                        \"ao\"\n#define XML_INTEGRATOR_AO_ALPHA                  \"alpha\"\n#define XML_INTEGRATOR_AO_SAMPLE_COUNT           \"sampleCount\"\n#define XML_INTEGRATOR_WHITTED                   \"whitted\"\n#define XML_INTEGRATOR_WHITTED_DEPTH             \"depth\"\n#define XML_INTEGRATOR_PATH_EMS                  \"pathEMS\"\n#define XML_INTEGRATOR_PATH_EMS_DEPTH            \"depth\"\n#define XML_INTEGRATOR_PATH_MATS                 \"pathMATS\"\n#define XML_INTEGRATOR_PATH_MATS_DEPTH           \"depth\"\n#define XML_INTEGRATOR_PATH_MIS                  \"pathMIS\"\n#define XML_INTEGRATOR_PATH_MIS_DEPTH            \"depth\"\n\n#define XML_EMITTER                              \"emitter\"\n#define XML_EMITTER_AREA_LIGHT                   \"area\"\n#define XML_EMITTER_AREA_LIGHT_RADIANCE          \"radiance\"\n#define XML_EMITTER_POINT_LIGHT                  \"point\"\n#define XML_EMITTER_POINT_LIGHT_POSITION         \"position\"\n#define XML_EMITTER_POINT_LIGHT_POWER            \"power\"\n#define XML_EMITTER_ENVIRONMENT_LIGHT            \"env\"\n#define XML_EMITTER_ENVIRONMENT_LIGHT_FILENAME   \"filename\"\n#define XML_EMITTER_ENVIRONMENT_LIGHT_SCALE      \"scale\"\n#define XML_EMITTER_ENVIRONMENT_LIGHT_TO_WORLD   \"toWorld\"\n#define XML_EMITTER_DIRECTIONAL_LIGHT            \"directional\"\n#define XML_EMITTER_DIRECTIONAL_LIGHT_IRRADIANCE \"irradiance\"\n#define XML_EMITTER_DIRECTIONAL_LIGHT_DIRECTION  \"direction\"\n#define XML_EMITTER_CONSTANT_LIGHT               \"constant\"\n#define XML_EMITTER_CONSTANT_LIGHT_RADIANCE      \"radiance\"\n\n#define XML_TEXTURE                              \"texture\"\n#define XML_TEXTURE_BITMAP                       \"bitmap\"\n#define XML_TEXTURE_BITMAP_FILENAME              \"filename\"\n#define XML_TEXTURE_BITMAP_GAMMA                 \"gamma\"\n#define XML_TEXTURE_BITMAP_WRAP_MODE             \"wrapMode\"\n#define XML_TEXTURE_BITMAP_WRAP_MODE_U           \"uWrapMode\"\n#define XML_TEXTURE_BITMAP_WRAP_MODE_V           \"vWrapMode\"\n#define XML_TEXTURE_BITMAP_WRAP_MODE_REPEAT      \"repeat\"\n#define XML_TEXTURE_BITMAP_WRAP_MODE_CLAMP       \"clamp\"\n#define XML_TEXTURE_BITMAP_WRAP_MODE_BLACK       \"black\"\n#define XML_TEXTURE_BITMAP_FILTER_TYPE           \"filterType\"\n#define XML_TEXTURE_BITMAP_FILTER_TYPE_NEAREST   \"nearest\"\n#define XML_TEXTURE_BITMAP_FILTER_TYPE_BILINEAR  \"bilinear\"\n#define XML_TEXTURE_BITMAP_FILTER_TYPE_TRILINEAR \"trilinear\"\n#define XML_TEXTURE_BITMAP_FILTER_TYPE_EWA       \"ewa\"\n#define XML_TEXTURE_BITMAP_MAX_ANISOTROPY        \"maxAnisotropy\"\n#define XML_TEXTURE_BITMAP_OFFSE_U               \"uOffset\"\n#define XML_TEXTURE_BITMAP_OFFSE_V               \"vOffset\"\n#define XML_TEXTURE_BITMAP_SCALE_U               \"uScale\"\n#define XML_TEXTURE_BITMAP_SCALE_V               \"vScale\"\n#define XML_TEXTURE_BITMAP_CHANNEL               \"channel\"\n#define XML_TEXTURE_BITMAP_CHANNEL_R             \"r\"\n#define XML_TEXTURE_BITMAP_CHANNEL_RGB           \"rgb\"\n#define XML_TEXTURE_CHECKERBOARD                 \"checkerboard\"\n#define XML_TEXTURE_CHECKERBOARD_BLOCKS          \"blocks\"\n#define XML_TEXTURE_CHECKERBOARD_COLOR_A         \"colorA\"\n#define XML_TEXTURE_CHECKERBOARD_COLOR_B         \"colorB\"\n#define XML_TEXTURE_CHECKERBOARD_OFFSE_U         \"uOffset\"\n#define XML_TEXTURE_CHECKERBOARD_OFFSE_V         \"vOffset\"\n#define XML_TEXTURE_CHECKERBOARD_SCALE_U         \"uScale\"\n#define XML_TEXTURE_CHECKERBOARD_SCALE_V         \"vScale\"\n#define XML_TEXTURE_WIREFRAME                    \"wireframe\"\n#define XML_TEXTURE_WIREFRAME_INTERIOR_COLOR     \"interiorColor\"\n#define XML_TEXTURE_WIREFRAME_EDGE_COLOR         \"edgeColor\"\n#define XML_TEXTURE_WIREFRAME_EDGE_WIDTH         \"edgeWidth\"\n#define XML_TEXTURE_WIREFRAME_TRANSITION_WIDTH   \"transitionWidth\"\n#define XML_TEXTURE_WIREFRAME_OFFSE_U            \"uOffset\"\n#define XML_TEXTURE_WIREFRAME_OFFSE_V            \"vOffset\"\n#define XML_TEXTURE_WIREFRAME_SCALE_U            \"uScale\"\n#define XML_TEXTURE_WIREFRAME_SCALE_V            \"vScale\"\n#define XML_TEXTURE_GRID                         \"grid\"\n#define XML_TEXTURE_GRID_COLOR_BACKGROUND        \"backgroundColor\"\n#define XML_TEXTURE_GRID_COLOR_LINE              \"lineColor\"\n#define XML_TEXTURE_GRID_LINE_WIDTH              \"lineWidth\"\n#define XML_TEXTURE_GRID_LINES                   \"lines\"\n#define XML_TEXTURE_GRID_OFFSE_U                 \"uOffset\"\n#define XML_TEXTURE_GRID_OFFSE_V                 \"vOffset\"\n#define XML_TEXTURE_GRID_SCALE_U                 \"uScale\"\n#define XML_TEXTURE_GRID_SCALE_V                 \"vScale\"\n#define XML_TEXTURE_CURVATURE                    \"curvature\"\n#define XML_TEXTURE_CURVATURE_POSITIVE_COLOR     \"positiveColor\"\n#define XML_TEXTURE_CURVATURE_NEGATIVE_COLOR     \"negativeColor\"\n#define XML_TEXTURE_CURVATURE_SCALE              \"scale\"\n#define XML_TEXTURE_CURVATURE_TYPE               \"curvatureType\"\n#define XML_TEXTURE_CURVATURE_OFFSE_U            \"uOffset\"\n#define XML_TEXTURE_CURVATURE_OFFSE_V            \"vOffset\"\n#define XML_TEXTURE_CURVATURE_SCALE_U            \"uScale\"\n#define XML_TEXTURE_CURVATURE_SCALE_V            \"vScale\"\n#define XML_TEXTURE_SCALE                        \"scale\"\n#define XML_TEXTURE_SCALE_SCALE                  \"scale\"\n\n#define XML_ACCELERATION                         \"acceleration\"\n#define XML_ACCELERATION_BRUTO_LOOP              \"bruto\"\n#define XML_ACCELERATION_BVH                     \"bvh\"\n#define XML_ACCELERATION_BVH_LEAF_SIZE           \"leafSize\"\n#define XML_ACCELERATION_BVH_SPLIT_METHOD        \"splitMethod\"\n#define XML_ACCELERATION_BVH_SPLIT_METHOD_CENTER \"center\"\n#define XML_ACCELERATION_BVH_SPLIT_METHOD_SAH    \"sah\"\n#define XML_ACCELERATION_HLBVH                   \"hlbvh\"\n#define XML_ACCELERATION_HLBVH_LEAF_SIZE         \"leafSize\"\n\n#define XML_SCENE                                \"scene\"\n#define XML_SCENE_BACKGROUND                     \"background\"\n#define XML_SCENE_FORCE_BACKGROUND               \"forceBackground\"\n\n#define XML_MESH                                 \"mesh\"\n#define XML_MESH_WAVEFRONG_OBJ                   \"obj\"\n#define XML_MESH_WAVEFRONG_OBJ_FILENAME          \"filename\"\n#define XML_MESH_WAVEFRONG_OBJ_TO_WORLD          \"toWorld\"\n\n#define XML_BSDF                                 \"bsdf\"\n#define XML_BSDF_GGX                             \"ggx\"\n#define XML_BSDF_BECKMANN                        \"beckmann\"\n#define XML_BSDF_DIELECTRIC                      \"dielectric\"\n#define XML_BSDF_DIELECTRIC_INT_IOR              \"intIOR\"\n#define XML_BSDF_DIELECTRIC_EXT_IOR              \"extIOR\"\n#define XML_BSDF_DIELECTRIC_KS_REFLECT           \"ksReflect\"\n#define XML_BSDF_DIELECTRIC_KS_REFRACT           \"ksRefract\"\n#define XML_BSDF_DIFFUSE                         \"diffuse\"\n#define XML_BSDF_DIFFUSE_ALBEDO                  \"albedo\"\n#define XML_BSDF_MIRROR                          \"mirror\"\n#define XML_BSDF_MICROFACET                      \"microfacet\"\n#define XML_BSDF_MICROFACET_ALPHA                \"alpha\"\n#define XML_BSDF_MICROFACET_INT_IOR              \"intIOR\"\n#define XML_BSDF_MICROFACET_EXT_IOR              \"extIOR\"\n#define XML_BSDF_MICROFACET_KD                   \"kd\"\n#define XML_BSDF_CONDUCTOR                       \"conductor\"\n#define XML_BSDF_CONDUCTOR_INT_IOR               \"intIOR\"\n#define XML_BSDF_CONDUCTOR_EXT_IOR               \"extIOR\"\n#define XML_BSDF_CONDUCTOR_K                     \"k\"\n#define XML_BSDF_CONDUCTOR_KS                    \"ks\"\n#define XML_BSDF_PLASTIC                         \"plastic\"\n#define XML_BSDF_PLASTIC_INT_IOR                 \"intIOR\"\n#define XML_BSDF_PLASTIC_EXT_IOR                 \"extIOR\"\n#define XML_BSDF_PLASTIC_KS                      \"ks\"\n#define XML_BSDF_PLASTIC_KD                      \"kd\"\n#define XML_BSDF_PLASTIC_NONLINEAR               \"nonlinear\"\n#define XML_BSDF_ROUGH_CONDUCTOR                 \"roughConductor\"\n#define XML_BSDF_ROUGH_CONDUCTOR_INT_IOR         \"intIOR\"\n#define XML_BSDF_ROUGH_CONDUCTOR_EXT_IOR         \"extIOR\"\n#define XML_BSDF_ROUGH_CONDUCTOR_K               \"k\"\n#define XML_BSDF_ROUGH_CONDUCTOR_KS              \"ks\"\n#define XML_BSDF_ROUGH_CONDUCTOR_ALPHA           \"alpha\"\n#define XML_BSDF_ROUGH_CONDUCTOR_ALPHA_U         \"alphaU\"\n#define XML_BSDF_ROUGH_CONDUCTOR_ALPHA_V         \"alphaV\"\n#define XML_BSDF_ROUGH_CONDUCTOR_TYPE            \"type\"\n#define XML_BSDF_ROUGH_CONDUCTOR_AS              \"as\"\n#define XML_BSDF_ROUGH_DIELECTRIC                \"roughDielectric\"\n#define XML_BSDF_ROUGH_DIELECTRIC_INT_IOR        \"intIOR\"\n#define XML_BSDF_ROUGH_DIELECTRIC_EXT_IOR        \"extIOR\"\n#define XML_BSDF_ROUGH_DIELECTRIC_KS_REFLECT     \"ksReflect\"\n#define XML_BSDF_ROUGH_DIELECTRIC_KS_REFRACT     \"ksRefract\"\n#define XML_BSDF_ROUGH_DIELECTRIC_ALPHA          \"alpha\"\n#define XML_BSDF_ROUGH_DIELECTRIC_ALPHA_U        \"alphaU\"\n#define XML_BSDF_ROUGH_DIELECTRIC_ALPHA_V        \"alphaV\"\n#define XML_BSDF_ROUGH_DIELECTRIC_TYPE           \"type\"\n#define XML_BSDF_ROUGH_DIELECTRIC_AS             \"as\"\n#define XML_BSDF_ROUGH_DIFFUSE                   \"roughDiffuse\"\n#define XML_BSDF_ROUGH_DIFFUSE_ALBEDO            \"albedo\"\n#define XML_BSDF_ROUGH_DIFFUSE_ALPHA             \"alpha\"\n#define XML_BSDF_ROUGH_DIFFUSE_FAST_APPROX       \"fastApprox\"\n#define XML_BSDF_ROUGH_PLASTIC                   \"roughPlastic\"\n#define XML_BSDF_ROUGH_PLASTIC_INT_IOR           \"intIOR\"\n#define XML_BSDF_ROUGH_PLASTIC_EXT_IOR           \"extIOR\"\n#define XML_BSDF_ROUGH_PLASTIC_KS                \"ks\"\n#define XML_BSDF_ROUGH_PLASTIC_KD                \"kd\"\n#define XML_BSDF_ROUGH_PLASTIC_NONLINEAR         \"nonlinear\"\n#define XML_BSDF_ROUGH_PLASTIC_TYPE              \"type\"\n#define XML_BSDF_ROUGH_PLASTIC_ALPHA             \"alpha\"\n#define XML_BSDF_ROUGH_PLASTIC_BECKMANN_RFT_DATA \"data\\\\BeckmannRFTData.bin\"\n#define XML_BSDF_ROUGH_PLASTIC_GGX_RFT_DATA      \"data\\\\GGXRFTData.bin\"\n#define XML_BSDF_COATING                         \"coating\"\n#define XML_BSDF_COATING_INT_IOR                 \"intIOR\"\n#define XML_BSDF_COATING_EXT_IOR                 \"extIOR\"\n#define XML_BSDF_COATING_THICKNESS               \"thickness\"\n#define XML_BSDF_COATING_SIGMA_A                 \"sigmaA\"\n#define XML_BSDF_COATING_KS                      \"ks\"\n#define XML_BSDF_ROUGH_COATING                   \"roughCoating\"\n#define XML_BSDF_ROUGH_COATING_INT_IOR           \"intIOR\"\n#define XML_BSDF_ROUGH_COATING_EXT_IOR           \"extIOR\"\n#define XML_BSDF_ROUGH_COATING_THICKNESS         \"thickness\"\n#define XML_BSDF_ROUGH_COATING_SIGMA_A           \"sigmaA\"\n#define XML_BSDF_ROUGH_COATING_KS                \"ks\"\n#define XML_BSDF_ROUGH_COATING_ALPHA             \"alpha\"\n#define XML_BSDF_ROUGH_COATING_TYPE              \"type\"\n#define XML_BSDF_ROUGH_COATING_BECKMANN_RFT_DATA \"data\\\\BeckmannRFTData.bin\"\n#define XML_BSDF_ROUGH_COATING_GGX_RFT_DATA      \"data\\\\GGXRFTData.bin\"\n#define XML_BSDF_TWO_SIDED                       \"twoSided\"\n#define XML_BSDF_BUMP_MAP                        \"bumpMap\"\n#define XML_BSDF_NORMAL_MAP                      \"normalMap\"\n\n#define XML_MEDIUM                               \"medium\"\n\n#define XML_PHASE                                \"phase\"\n\n#define XML_CAMERA                               \"camera\"\n#define XML_CAMERA_PERSPECTIVE                   \"perspective\"\n#define XML_CAMERA_PERSPECTIVE_WIDTH             \"width\"\n#define XML_CAMERA_PERSPECTIVE_HEIGHT            \"height\"\n#define XML_CAMERA_PERSPECTIVE_TO_WORLD          \"toWorld\"\n#define XML_CAMERA_PERSPECTIVE_FOV               \"fov\"\n#define XML_CAMERA_PERSPECTIVE_NEAR_CLIP         \"nearClip\"\n#define XML_CAMERA_PERSPECTIVE_FAR_CLIP          \"farClip\"\n\n#define XML_TEST                                 \"test\"\n#define XML_TEST_STUDENT_T                       \"ttest\"\n#define XML_TEST_STUDENT_T_SIGNIFICANCE_LEVEL    \"significanceLevel\"\n#define XML_TEST_STUDENT_T_ANGLES                \"angles\"\n#define XML_TEST_STUDENT_T_REFERENCES            \"references\"\n#define XML_TEST_STUDENT_T_SAMPLE_COUNT          \"sampleCount\"\n#define XML_TEST_CHI2                            \"chi2test\"\n#define XML_TEST_CHI2_SIGNIFICANCE_LEVEL         \"significanceLevel\"\n#define XML_TEST_CHI2_RESOLUTION                 \"resolution\"\n#define XML_TEST_CHI2_MIN_EXP_FREQUENCY          \"minExpFrequency\"\n#define XML_TEST_CHI2_SAMPLE_COUNT               \"sampleCount\"\n#define XML_TEST_CHI2_TEST_COUNT                 \"testCount\"\n\n#define XML_FILTER                               \"rfilter\"\n#define XML_FILTER_BOX                           \"box\"\n#define XML_FILTER_GAUSSION                      \"gaussian\"\n#define XML_FILTER_GAUSSION_RADIUS               \"radius\"\n#define XML_FILTER_GAUSSION_STDDEV               \"stddev\"\n#define XML_FILTER_MITCHELL_NETRAVALI            \"mitchell\"\n#define XML_FILTER_MITCHELL_NETRAVALI_RADIUS     \"radius\"\n#define XML_FILTER_MITCHELL_NETRAVALI_B          \"B\"\n#define XML_FILTER_MITCHELL_NETRAVALI_C          \"C\"\n#define XML_FILTER_TENT                          \"tent\"\n\n#define XML_SAMPLER                              \"sampler\"\n#define XML_SAMPLER_INDEPENDENT                  \"independent\"\n#define XML_SAMPLER_INDEPENDENT_SAMPLE_COUNT     \"sampleCount\"\n\n#define XML_SHAPE                                \"shape\"\n\n/* Default setting */\n#define DEFAULT_ACCELERATION_BVH_LEAF_SIZE         10\n#define DEFAULT_ACCELERATION_BVH_SPLIT_METHOD      XML_ACCELERATION_BVH_SPLIT_METHOD_SAH\n\n#define DEFAULT_ACCELERATION_HLBVH_LEAF_SIZE       10\n\n#define DEFAULT_SCENE_ACCELERATION                 XML_ACCELERATION_BRUTO_LOOP\n\n#define DEFAULT_SCENE_SAMPLER                      XML_SAMPLER_INDEPENDENT\n\n#define DEFAULT_CAMERA_OUTPUTSIZE_X                1280\n#define DEFAULT_CAMERA_OUTPUTSIZE_Y                720\n#define DEFAULT_CAMERA_CAMERA_TO_WORLD             Transform()\n#define DEFAULT_CAMERA_FOV                         30.0f\n#define DEFAULT_CAMERA_NEAR_CLIP                   1e-4f\n#define DEFAULT_CAMERA_FAR_CLIP                    1e4f\n#define DEFAULT_CAMERA_FAR_CLIP                    1e4f\n#define DEFAULT_CAMERA_RFILTER                     XML_FILTER_GAUSSION\n\n#define DEFAULT_BSDF_DIELECTRIC_INT_IOR            1.5046f\n#define DEFAULT_BSDF_DIELECTRIC_EXT_IOR            1.000277f /* Air */\n#define DEFAULT_BSDF_DIELECTRIC_KS_REFLECT         Color3f(1.0f) \n#define DEFAULT_BSDF_DIELECTRIC_KS_REFRACT         Color3f(1.0f) \n#define DEFAULT_BSDF_DIFFUSE_ALBEDO                Color3f(0.5f)\n#define DEFAULT_BSDF_MICROFACET_ALPHA              0.1f\n#define DEFAULT_BSDF_MICROFACET_INT_IOR            1.5046f\n#define DEFAULT_BSDF_MICROFACET_EXT_IOR            1.000277f /* Air */\n#define DEFAULT_BSDF_MICROFACET_ALBEDO             Color3f(0.5f)\n#define DEFAULT_BSDF_CONDUCTOR_INT_IOR             1.5046f\n#define DEFAULT_BSDF_CONDUCTOR_EXT_IOR             1.000277f /* Air */\n#define DEFAULT_BSDF_CONDUCTOR_K                   Color3f(1.0f)\n#define DEFAULT_BSDF_CONDUCTOR_KS                  Color3f(1.0f)\n#define DEFAULT_BSDF_PLASTIC_INT_IOR               1.5046f\n#define DEFAULT_BSDF_PLASTIC_EXT_IOR               1.000277f /* Air */\n#define DEFAULT_BSDF_PLASTIC_KS                    Color3f(1.0f)\n#define DEFAULT_BSDF_PLASTIC_KD                    Color3f(0.5f)\n#define DEFAULT_BSDF_PLASTIC_NONLINEAR             false\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_INT_IOR       1.5046f\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_EXT_IOR       1.000277f /* Air */\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_K             Color3f(1.0f)\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_KS            Color3f(1.0f)\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_ALPHA         0.1f\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_ALPHA_U       0.1f\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_ALPHA_V       0.1f\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_TYPE          XML_BSDF_BECKMANN\n#define DEFAULT_BSDF_ROUGH_CONDUCTOR_AS            false\n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_INT_IOR      1.5046f\n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_EXT_IOR      1.000277f /* Air */\n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_KS_REFLECT   Color3f(1.0f) \n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_KS_REFRACT   Color3f(1.0f) \n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_ALPHA        0.1f\n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_ALPHA_U      0.1f\n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_ALPHA_V      0.1f\n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_TYPE         XML_BSDF_BECKMANN\n#define DEFAULT_BSDF_ROUGH_DIELECTRIC_AS           false\n#define DEFAULT_BSDF_ROUGH_DIFFUSE_ALBEDO          Color3f(0.5f)\n#define DEFAULT_BSDF_ROUGH_DIFFUSE_ALPHA           0.2f\n#define DEFAULT_BSDF_ROUGH_DIFFUSE_FAST_APPROX     false\n#define DEFAULT_BSDF_ROUGH_PLASTIC_INT_IOR         1.49f\n#define DEFAULT_BSDF_ROUGH_PLASTIC_EXT_IOR         1.000277f /* Air */\n#define DEFAULT_BSDF_ROUGH_PLASTIC_KS              Color3f(1.0f)\n#define DEFAULT_BSDF_ROUGH_PLASTIC_KD              Color3f(0.5f)\n#define DEFAULT_BSDF_ROUGH_PLASTIC_NONLINEAR       false\n#define DEFAULT_BSDF_ROUGH_PLASTIC_TYPE            XML_BSDF_BECKMANN\n#define DEFAULT_BSDF_ROUGH_PLASTIC_ALPHA           0.1f\n#define DEFAULT_BSDF_COATING_INT_IOR               1.49f\n#define DEFAULT_BSDF_COATING_EXT_IOR               1.000277f /* Air */\n#define DEFAULT_BSDF_COATING_THICKNESS             1.0f\n#define DEFAULT_BSDF_COATING_SIGMA_A               Color3f(0.0f)\n#define DEFAULT_BSDF_COATING_KS                    Color3f(1.0f)\n#define DEFAULT_BSDF_ROUGH_COATING_INT_IOR         1.49f\n#define DEFAULT_BSDF_ROUGH_COATING_EXT_IOR         1.000277f /* Air */\n#define DEFAULT_BSDF_ROUGH_COATING_THICKNESS       1.0f\n#define DEFAULT_BSDF_ROUGH_COATING_SIGMA_A         Color3f(0.0f)\n#define DEFAULT_BSDF_ROUGH_COATING_KS              Color3f(1.0f)\n#define DEFAULT_BSDF_ROUGH_COATING_ALPHA           0.1f\n#define DEFAULT_BSDF_ROUGH_COATING_TYPE            XML_BSDF_BECKMANN\n\n#define DEFAULT_FILTER_GAUSSIAN_RADIUS             2.0f\n#define DEFAULT_FILTER_GAUSSIAN_STDDEV             0.5f\n#define DEFAULT_FILTER_MITCHELL_RADIUS             2.0f\n#define DEFAULT_FILTER_MITCHELL_B                  (1.0f / 3.0f)\n#define DEFAULT_FILTER_MITCHELL_C                  (1.0f / 3.0f)\n\n#define DEFAULT_MESH_TO_WORLD                      Transform()\n\n#define DEFAULT_INTEGRATOR_AO_ALPHA                1e6f\n#define DEFAULT_INTEGRATOR_AO_SAMPLE_COUNT         16\n#define DEFAULT_INTEGRATOR_WHITTED_DEPTH           -1\n\n#define DEFAULT_SAMPLER_INDEPENDENT_SAMPLE_COUNT   1\n\n#define DEFAULT_MESH_BSDF                          XML_BSDF_DIFFUSE\n\n#define DEFAULT_EMITTER_ENVIRONMENT_SCALE          1.0f\n#define DEFAULT_EMITTER_ENVIRONMENT_TO_WORLD       Transform()\n\n#define DEFAULT_TEST_STUDENT_T_SIGNIFICANCE_LEVEL  0.01f\n#define DEFAULT_TEST_STUDENT_T_ANGLES              \"\"\n#define DEFAULT_TEST_STUDENT_T_REFERENCES          \"\"\n#define DEFAULT_TEST_STUDENT_T_SAMPLE_COUNT        100000\n\n#define DEFAULT_TEST_CHI2_SIGNIFICANCE_LEVEL       0.01f\n#define DEFAULT_TEST_CHI2_RESOLUTION               10\n#define DEFAULT_TEST_CHI2_MIN_EXP_FREQUENCY        5\n#define DEFAULT_TEST_CHI2_SAMPLE_COUNT             -1\n#define DEFAULT_TEST_CHI2_TEST_COUNT               5\n\n#define DEFAULT_SCENE_BACKGROUND                   Color3f(0.0f)\n#define DEFAULT_SCENE_FORCE_BACKGROUND             false\n\n#define DEFAULT_TEXTURE_BITMAP_GAMMA               1.0f\n#define DEFAULT_TEXTURE_BITMAP_WRAP_MODE           XML_TEXTURE_BITMAP_WRAP_MODE_REPEAT\n#define DEFAULT_TEXTURE_BITMAP_WRAP_MODE_U         XML_TEXTURE_BITMAP_WRAP_MODE_REPEAT\n#define DEFAULT_TEXTURE_BITMAP_WRAP_MODE_V         XML_TEXTURE_BITMAP_WRAP_MODE_REPEAT\n#define DEFAULT_TEXTURE_BITMAP_FILTER_TYPE         XML_TEXTURE_BITMAP_FILTER_TYPE_EWA\n#define DEFAULT_TEXTURE_BITMAP_MAX_ANISOTROPY      20.0f\n#define DEFAULT_TEXTURE_BITMAP_OFFSET_U            0.0f\n#define DEFAULT_TEXTURE_BITMAP_OFFSET_V            0.0f\n#define DEFAULT_TEXTURE_BITMAP_SCALE_U             1.0f\n#define DEFAULT_TEXTURE_BITMAP_SCALE_V             1.0f\n#define DEFAULT_TEXTURE_BITMAP_CHANNEL             XML_TEXTURE_BITMAP_CHANNEL_RGB\n#define DEFAULT_TEXTURE_CHECKERBOARD_BLOCKS        10\n#define DEFAULT_TEXTURE_CHECKERBOARD_COLOR_A       Color3f(0.4f)\n#define DEFAULT_TEXTURE_CHECKERBOARD_COLOR_B       Color3f(0.2f)\n#define DEFAULT_TEXTURE_CHECKERBOARD_OFFSET_U      0.0f\n#define DEFAULT_TEXTURE_CHECKERBOARD_OFFSET_V      0.0f\n#define DEFAULT_TEXTURE_CHECKERBOARD_SCALE_U       1.0f\n#define DEFAULT_TEXTURE_CHECKERBOARD_SCALE_V       1.0f\n#define DEFAULT_TEXTURE_WIREFRAME_INTERIOR_COLOR   Color3f(0.5f)\n#define DEFAULT_TEXTURE_WIREFRAME_EDGE_COLOR       Color3f(0.1f)\n#define DEFAULT_TEXTURE_WIREFRAME_EDGE_WIDTH       0.0f\n#define DEFAULT_TEXTURE_WIREFRAME_TRANSITION_WIDTH 0.5f\n#define DEFAULT_TEXTURE_WIREFRAME_OFFSET_U         0.0f\n#define DEFAULT_TEXTURE_WIREFRAME_OFFSET_V         0.0f\n#define DEFAULT_TEXTURE_WIREFRAME_SCALE_U          1.0f\n#define DEFAULT_TEXTURE_WIREFRAME_SCALE_V          1.0f\n#define DEFAULT_TEXTURE_GRID_COLOR_BACKGROUND      Color3f(0.2f)\n#define DEFAULT_TEXTURE_GRID_COLOR_LINE            Color3f(0.4f)\n#define DEFAULT_TEXTURE_GRID_LINE_WIDTH            0.01f\n#define DEFAULT_TEXTURE_GRID_LINES                 10\n#define DEFAULT_TEXTURE_GRID_OFFSET_U              0.0f\n#define DEFAULT_TEXTURE_GRID_OFFSET_V              0.0f\n#define DEFAULT_TEXTURE_GRID_SCALE_U               1.0f\n#define DEFAULT_TEXTURE_GRID_SCALE_V               1.0f\n#define DEFAULT_TEXTURE_CURVATURE_SCALE            1.0f\n#define DEFAULT_TEXTURE_CURVATURE_POSITIVE_COLOR   Color3f(1.0f, 0.0f, 0.0f)\n#define DEFAULT_TEXTURE_CURVATURE_NEGATIVE_COLOR   Color3f(0.0f, 0.0f, 1.0f)\n#define DEFAULT_TEXTURE_CURVATURE_OFFSET_U         0.0f\n#define DEFAULT_TEXTURE_CURVATURE_OFFSET_V         0.0f\n#define DEFAULT_TEXTURE_CURVATURE_SCALE_U          1.0f\n#define DEFAULT_TEXTURE_CURVATURE_SCALE_V          1.0f\n\nNAMESPACE_BEGIN\n\n/* Counting the time between TIMER_START and TIMER_END */\n#define TIMER_START(Var) clock_t __Start##Var, __Finish##Var; double Var; __Start##Var = clock();\n#define TIMER_END(Var) __Finish##Var = clock();  Var = double(__Finish##Var - __Start##Var) / (CLOCKS_PER_SEC);\n\n/* Import cout, cerr, endl for debugging purposes */\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n/* Forward declarations */\ntemplate <typename TScalar, int TDimension>  struct TVector;\ntemplate <typename TScalar, int TDimension>  struct TPoint;\ntemplate <typename TPoint, typename TVector> struct TRay;\ntemplate <typename TPoint>                   struct TBoundingBox;\ntemplate <typename T>                        class MipMap;\n\nclass Acceleration;\nclass Bitmap;\nclass ImageBlock;\nclass BlockGenerator;\nclass BSDF;\nstruct BSDFQueryRecord;\nclass Camera;\nstruct Color3f;\nstruct Color4f;\nstruct DiscretePDF1D;\nstruct DiscretePDF2D;\nclass Emitter;\nstruct Frame;\nclass Integrator;\nclass Mesh;\nstruct Intersection;\nclass Object;\nclass ObjectFactory;\nclass PropertyList;\nclass ReconstructionFilter;\nclass Sampler;\nclass Sampling;\nclass Scene;\nclass Timer;\nclass Shape;\nclass MicrofacetDistribution;\nclass Texture;\nclass Texture2D;\nclass ConstantColor3fTexture;\nclass ConstantFloatTexture;\nclass Color3fAdditionTexture;\nclass Color3fSubtractionTexture;\nclass Color3fProductTexture;\nstruct RoughTransmittance;\n\n/* Basic data structures (vectors, points, rays, bounding boxes,\nkd-trees) are oblivious to the underlying data type and dimension.\nThe following list of typedefs establishes some convenient aliases\nfor specific types. */\nusing Vector1f      = TVector<float, 1>;\nusing Vector2f      = TVector<float, 2>;\nusing Vector3f      = TVector<float, 3>;\nusing Vector4f      = TVector<float, 4>;\nusing Vector1d      = TVector<double, 1>;\nusing Vector2d      = TVector<double, 2>;\nusing Vector3d      = TVector<double, 3>;\nusing Vector4d      = TVector<double, 4>;\nusing Vector1i      = TVector<int, 1>;\nusing Vector2i      = TVector<int, 2>;\nusing Vector3i      = TVector<int, 3>;\nusing Vector4i      = TVector<int, 4>;\nusing Point1f       = TPoint<float, 1>;\nusing Point2f       = TPoint<float, 2>;\nusing Point3f       = TPoint<float, 3>;\nusing Point4f       = TPoint<float, 4>;\nusing Point1d       = TPoint<double, 1>;\nusing Point2d       = TPoint<double, 2>;\nusing Point3d       = TPoint<double, 3>;\nusing Point4d       = TPoint<double, 4>;\nusing Point1i       = TPoint<int, 1>;\nusing Point2i       = TPoint<int, 2>;\nusing Point3i       = TPoint<int, 3>;\nusing Point4i       = TPoint<int, 4>;\nusing BoundingBox1f = TBoundingBox<Point1f>;\nusing BoundingBox2f = TBoundingBox<Point2f>;\nusing BoundingBox3f = TBoundingBox<Point3f>;\nusing BoundingBox4f = TBoundingBox<Point4f>;\nusing BoundingBox1d = TBoundingBox<Point1d>;\nusing BoundingBox2d = TBoundingBox<Point2d>;\nusing BoundingBox3d = TBoundingBox<Point3d>;\nusing BoundingBox4d = TBoundingBox<Point4d>;\nusing BoundingBox1i = TBoundingBox<Point1i>;\nusing BoundingBox2i = TBoundingBox<Point2i>;\nusing BoundingBox3i = TBoundingBox<Point3i>;\nusing BoundingBox4i = TBoundingBox<Point4i>;\nusing Ray2f         = TRay<Point2f, Vector2f>;\nusing Ray3f         = TRay<Point3f, Vector3f>;\nusing MatrixXf      = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;\nusing MatrixXu      = Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic>;\nusing MipMap3f      = MipMap<Color3f>;\nusing MipMap1f      = MipMap<float>;\n\n/* Simple exception class, which stores a human-readable error description */\nclass HikariException : public std::runtime_error \n{\npublic:\n\t// Variadic template constructor to support printf-style arguments\n\ttemplate <typename... Args>\n\tHikariException(const char * pFmt, const Args &... Arg) : std::runtime_error(tfm::format(pFmt, Arg...)) { }\n};\n\n/* Check whether \"Value\" is in the range (Min, Max). Exception will be throw\nwith info \"Msg\" if it is not in the range. */\ntemplate <typename T, typename... Args>\nvoid CheckOO(\n\tT Value,\n\tT Min,\n\tT Max,\n\tconst char * pFmt,\n\tconst Args &... Arg\n)\n{\n\tif (Value <= Min || Value >= Max)\n\t{\n\t\tthrow HikariException(pFmt, Arg...);\n\t}\n}\n\n/* Check whether \"Value\" is in the range (Min, Max]. Exception will be throw\nwith info \"Msg\" if it is not in the range. */\ntemplate <typename T, typename... Args>\nvoid CheckOC(\n\tT Value,\n\tT Min,\n\tT Max,\n\tconst char * pFmt,\n\tconst Args &... Arg\n)\n{\n\tif (Value <= Min || Value > Max)\n\t{\n\t\tthrow HikariException(pFmt, Arg...);\n\t}\n}\n\n/* Check whether \"Value\" is in the range [Min, Max). Exception will be throw\nwith info \"Msg\" if it is not in the range. */\ntemplate <typename T, typename... Args>\nvoid CheckCO(\n\tT Value,\n\tT Min,\n\tT Max,\n\tconst char * pFmt,\n\tconst Args &... Arg\n)\n{\n\tif (Value < Min || Value >= Max)\n\t{\n\t\tthrow HikariException(pFmt, Arg...);\n\t}\n}\n\n/* Check whether \"Value\" is in the range [Min, Max]. Exception will be throw\nwith info \"Msg\" if it is not in the range. */\ntemplate <typename T, typename... Args>\nvoid CheckCC(\n\tT Value,\n\tT Min,\n\tT Max,\n\tconst char * pFmt,\n\tconst Args &... Arg\n)\n{\n\tif (Value < Min || Value > Max)\n\t{\n\t\tthrow HikariException(pFmt, Arg...);\n\t}\n}\n\n/// Return the number of cores (real and virtual)\nint GetCoreCount();\n\n/// Indent a string by the specified number of spaces\nstd::string Indent(const std::string & String, int Amount = 2);\n\n/// Convert a string to lower case\nstd::string ToLower(const std::string & String);\n\n/// Convert a string into an boolean value\nbool ToBool(const std::string & String);\n\n/// Convert a string into a signed integer value\nint ToInt(const std::string & String);\n\n/// Convert a string into an unsigned integer value\nunsigned int ToUInt(const std::string & String);\n\n/// Convert a string into a floating point value\nfloat ToFloat(const std::string & String);\n\n/// Convert a string into a 3D vector\nEigen::Vector3f ToVector3f(const std::string & String);\n\n/// Tokenize a string into a list by splitting at 'delim'\nstd::vector<std::string> Tokenize(const std::string & String, const std::string & Delim = \", \", bool bIncludeEmpty = false);\n\n/// Check if a string ends with another string\nbool EndsWith(const std::string & String, const std::string & Ending);\n\n/// Convert a time value in milliseconds into a human-readable string\nstd::string TimeString(double Time, bool bPrecise = false);\n\n/// Convert a memory amount in bytes into a human-readable string\nstd::string MemString(size_t Size, bool bPrecise = false);\n\n/// Measures associated with probability distributions\nenum class EMeasure\n{\n\tEUnknownMeasure = 0,\n\tESolidAngle     = 1,\n\tEDiscrete       = 2\n};\n\n/// Type of the emitter\nenum class EEmitterType\n{\n\tEUnknown = 0,\n\tEPoint = 1,\n\tEArea = 2,\n\tEEnvironment = 3,\n\tEDirectional = 4\n};\n\n/// Type of the light transport. Currently not used, so set it to ERadiance now. \nenum class ETransportMode\n{\n\tEUnknown = 0,\n\tERadiance = 1,\n\tEImportance = 2\n};\n\n/// Wrap mode of the texture, which decides the behavior when u > 1 or v > 1.\nenum class EWrapMode\n{\n\tERepeat = 0,\n\tEBlack = 1,\n\tEClamp = 2\n};\n\n/// Filter type of the sampler\nenum class EFilterType\n{\n\tENearest = 0,\n\tEBilinear = 1,\n\tETrilinear = 2,\n\tEEWA = 3\n};\n\n/// Lobe type of the BSDF\nenum EBSDFType\n{\n\tENull                = 0x001,\n\tEDiffuseReflection   = 0x002,\n\tEDiffuseTransmission = 0x004,\n\tEGlossyReflection    = 0x008,\n\tEGlossyTransmission  = 0x010,\n\tEDeltaReflection     = 0x020,\n\tEDeltaTransmission   = 0x040,\n\n\tEExtraSampling       = 0x080,\n\tEUVDependent         = 0x100,\n};\n\n/// Convert radians to degrees\ninline float RadToDeg(float Value) { return Value * (180.0f / float(M_PI)); }\n\n/// Convert degrees to radians\ninline float DegToRad(float Value) { return Value * (float(M_PI) / 180.0f); }\n\n/// Emulate sincosf using sinf() and cosf()\ninline void SinCos(float Theta, float * pSin, float * pCos)\n{\n\t*pSin = sinf(Theta);\n\t*pCos = cosf(Theta);\n}\n\n/// Simple floating point clamping function\ninline float Clamp(float Value, float Min, float Max)\n{\n\tif (Value < Min)\n\t{\n\t\treturn Min;\n\t}\n\telse if (Value > Max)\n\t{\n\t\treturn Max;\n\t}\n\telse\n\t{\n\t\treturn Value;\n\t}\n}\n\n/// Simple integer clamping function\ninline int Clamp(int Value, int Min, int Max)\n{\n\tif (Value < Min)\n\t{\n\t\treturn Min;\n\t}\n\telse if (Value > Max)\n\t{\n\t\treturn Max;\n\t}\n\telse\n\t{\n\t\treturn Value;\n\t}\n}\n\nColor3f Clamp(Color3f Value, Color3f Min, Color3f Max);\nColor4f Clamp(Color4f Value, Color4f Min, Color4f Max);\n\n/// Linearly interpolate between two values\ninline float Lerp(float T, float V1, float V2)\n{\n\treturn (1.0f - T) * V1 + T * V2;\n}\n\n/// Linearly interpolate between two Color\nColor3f Lerp(float T, const Color3f & V1, const Color3f & V2);\nColor4f Lerp(float T, const Color4f & V1, const Color4f & V2);\n\n/// Always-positive modulo operation\ninline int Mod(int A, int B)\n{\n\tint R = A % B;\n\treturn (R < 0) ? R + B : R;\n}\n\n/// Arcsine variant that gracefully handles arguments > 1 that are due to roundoff errors\ninline float SafeAsin(float Value)\n{\n\treturn std::asin(std::min(1.0f, std::max(-1.0f, Value)));\n}\n\n/// Arcsine variant that gracefully handles arguments > 1 that are due to roundoff errors\ninline double SafeAsin(double Value)\n{\n\treturn std::asin(std::min(1.0, std::max(-1.0, Value)));\n}\n\n/// Arccosine variant that gracefully handles arguments > 1 that are due to roundoff errors\ninline float SafeAcos(float Value)\n{\n\treturn std::acos(std::min(1.0f, std::max(-1.0f, Value)));\n}\n\n/// Arccosine variant that gracefully handles arguments > 1 that are due to roundoff errors\ninline double SafeAcos(double Value)\n{\n\treturn std::acos(std::min(1.0, std::max(-1.0, Value)));\n}\n\n/// Square root variant that gracefully handles arguments < 0 that are due to roundoff errors\ninline float SafeSqrt(float Value)\n{\n\treturn std::sqrt(std::max(0.0f, Value));\n}\n\n/// Square root variant that gracefully handles arguments < 0 that are due to roundoff errors\ninline double SafeSqrt(double Value)\n{\n\treturn std::sqrt(std::max(0.0, Value));\n}\n\ninline float Hypot2(float A, float B)\n{\n\tfloat Result;\n\tif (std::abs(A) > std::abs(B))\n\t{\n\t\tResult = B / A;\n\t\tResult = std::abs(A) * std::sqrt(1.0f + Result * Result);\n\t}\n\telse if (B != 0.0f)\n\t{\n\t\tResult = A / B;\n\t\tResult = std::abs(B) * std::sqrt(1.0f + Result * Result);\n\t}\n\telse\n\t{\n\t\tResult = 0.0f;\n\t}\n\treturn Result;\n}\n\ninline double Hypot2(double A, double B)\n{\n\tdouble Result;\n\tif (std::abs(A) > std::abs(B))\n\t{\n\t\tResult = B / A;\n\t\tResult = std::abs(A) * std::sqrt(1.0 + Result * Result);\n\t}\n\telse if (B != 0.0)\n\t{\n\t\tResult = A / B;\n\t\tResult = std::abs(B) * std::sqrt(1.0 + Result * Result);\n\t}\n\telse\n\t{\n\t\tResult = 0.0;\n\t}\n\treturn Result;\n}\n\ninline bool SolveLinearSystem2x2(const float A[2][2], const float B[2], float X[2])\n{\n\tfloat Det = A[0][0] * A[1][1] - A[0][1] * A[1][0];\n\n\tconstexpr float InvOverflow = 1.0f / std::numeric_limits<float>::max();\n\n\tif (std::abs(Det) <= InvOverflow)\n\t{\n\t\treturn false;\n\t}\n\n\tfloat InvDet = 1.0f / Det;\n\n\tX[0] = (A[1][1] * B[0] - A[0][1] * B[1]) * InvDet;\n\tX[1] = (A[0][0] * B[1] - A[1][0] * B[0]) * InvDet;\n\n\treturn true;\n}\n\n/// Simple signum function -- note that it returns the FP sign of the input (and never zero)\ninline float Signum(float Value)\n{\n#if defined(__PLATFORM_WINDOWS__)\n\treturn float(_copysign(1.0f, Value));\n#elif\n\treturn float(copysign(1.0f, Value));\n#endif\n}\n\ntemplate <typename T>\ninline constexpr bool IsPowerOf2(T Value)\n{\n\treturn Value && !(Value & (Value - 1));\n}\n\ninline int32_t RoundUpPow2(int32_t Value)\n{\n\tValue--;\n\tValue |= Value >> 1;\n\tValue |= Value >> 2;\n\tValue |= Value >> 4;\n\tValue |= Value >> 8;\n\tValue |= Value >> 16;\n\treturn Value + 1;\n}\n\ninline int64_t RoundUpPow2(int64_t Value)\n{\n\tValue--;\n\tValue |= Value >> 1;\n\tValue |= Value >> 2;\n\tValue |= Value >> 4;\n\tValue |= Value >> 8;\n\tValue |= Value >> 16;\n\tValue |= Value >> 32;\n\treturn Value + 1;\n}\n\ninline int Log2Int(uint32_t V)\n{\n#if defined(__PLATFORM_WINDOWS__)\n\tunsigned long LZ = 0;\n\tif (_BitScanReverse(&LZ, V)) { return LZ; }\n\treturn 0;\n#else\n\treturn 31 - __builtin_clz(V);\n#endif\n}\n\ninline int Log2Int(int32_t V)\n{\n\treturn Log2Int(uint32_t(V));\n}\n\ninline int Log2Int(uint64_t V)\n{\n#if defined(__PLATFORM_WINDOWS__)\n\tunsigned long LZ = 0;\n#if defined(_WIN64)\n\t_BitScanReverse64(&LZ, V);\n#else\n\tif (_BitScanReverse(&LZ, V >> 32))\n\t{\n\t\tLZ += 32;\n\t}\n\telse\n\t{\n\t\t_BitScanReverse(&LZ, V & 0xffffffff);\n\t}\n#endif\n\treturn LZ;\n#else \n\treturn 63 - __builtin_clzll(V);\n#endif\n}\n\ninline int Log2Int(int64_t V)\n{\n\treturn Log2Int(uint64_t(V));\n}\n\ninline float GammaCorrect(float Value, float InvGamma)\n{\n\treturn InvGamma == 1.0f ? Value : std::pow(Value, InvGamma);\n}\n\ninline int ModPositive(int A, int B)\n{\n\tint R = A % B;\n\treturn (R < 0) ? R + B : R;\n}\n\n/// S-shape interpolation between two values\ninline float SmoothStep(float Min, float Max, float Value)\n{\n\tfloat V = Clamp((Value - Min) / (Max - Min), 0.0f, 1.0f);\n\treturn V * V * (-2.0f * V + 3.0f);\n}\n\n/**\n * \\brief Evaluate a cubic spline interpolant of a uniformly sampled 1D function\n *\n * This implementation relies on Catmull-Rom splines, i.e. it uses finite\n * differences to approximate the derivatives at the endpoints of each spline\n * segment.\n *\n * \\param X\n *      Evaluation point\n * \\param pValues\n *      Floating point array containing size regularly spaced evaluations\n *      in the range [Min, Max] of the function to be approximated.\n * \\param Size\n *      Denotes the size of the pValues array\n * \\param Min\n *      Position of the first knot\n * \\param Max\n *      Position of the last knot\n * \\param bExtrapolate\n *      Extrapolate values when X is out of range?\n * \\return\n *      The interpolated value or zero when bExtrapolate = false\n *      and X lies outside of [Min, Max]\n */\nfloat EvalCubicInterpolate1D(\n\tfloat X,\n\tconst float * pValues,\n\tint Size,\n\tfloat Min,\n\tfloat Max,\n\tbool bExtrapolate = false\n);\n\n/**\n * \\brief Evaluate a cubic spline interpolant of a uniformly sampled 2D function\n *\n * This implementation relies on a tensor product of Catmull-Rom splines, i.e. it uses\n * finite differences to approximate the derivatives at the endpoints of each spline\n * patch.\n *\n * \\param P\n *      Evaluation point\n * \\param pValues\n *      A 2D floating point array of Size.x * Size.y cells containing regularly\n *      spaced evaluations of the function to be interpolated on the domain [Min, Max].\n *      Consecutive entries of this array correspond to increments in the 'x' coordinate.\n * \\param Size\n *      Denotes the size of the pValues array (along each dimension)\n * \\param Min\n *      Position of the first knot on each dimension\n * \\param Max\n *      Position of the last knot on each dimension\n * \\param bExtrapolate\n *      Extrapolate values when P is out of range?\n * \\return\n *      The interpolated value or zero when bExtrapolate=false and\n *      P lies outside of the knot range\n */\nfloat EvalCubicInterpolate2D(\n\tconst Point2f & P,\n\tconst float * pValues,\n\tconst Point2i & Size,\n\tconst Point2f & Min,\n\tconst Point2f & Max,\n\tbool bExtrapolate = false\n);\n\n/**\n * \\brief Evaluate a cubic spline interpolant of a uniformly sampled 3D function\n *\n * This implementation relies on a tensor product of Catmull-Rom splines, i.e. it uses\n * finite differences to approximate the derivatives at the endpoints of each spline\n * region.\n *\n * \\param P\n *      Evaluation point of the interpolant\n * \\param pValues\n *      A 3D floating point array of Size.x * Size.y * Size.z cells containing regularly\n *      spaced evaluations of the function to be interpolated on the domain [Min, Max].\n *      Consecutive entries of this array correspond to increments in the 'x' coordinate,\n *      then 'y', and finally 'z' increments.\n * \\param Size\n *      Denotes the size of the pValues array (along each dimension)\n * \\param Min\n *      Position of the first knot on each dimension\n * \\param Max\n *      Position of the last knot on each dimension\n * \\param bExtrapolate\n *      Extrapolate values when P is out of range?\n * \\return\n *      The interpolated value or zero when bExtrapolate=false and\n *      P lies outside of the knot range\n */\nfloat EvalCubicInterpolate3D(\n\tconst Point3f & P,\n\tconst float * pValues,\n\tconst Point3i & Size,\n\tconst Point3f & Min,\n\tconst Point3f & Max, \n\tbool bExtrapolate = false\n);\n\n/// Compute a direction for the given coordinates in spherical coordinates\nVector3f SphericalDirection(float Theta, float Phi);\n\n/// Compute a direction for the given coordinates in spherical coordinates\nPoint2f SphericalCoordinates(const Vector3f & Dir);\n\n/// Fresnel coefficient for dielectric material. Eta = IntIOR / ExtIOR\nfloat FresnelDielectric(float CosThetaI, float Eta, float InvEta, float & CosThetaT);\n\n/// Fresnel coefficient for conductor material. Eta = IntIOR / ExtIOR, EtaK = K / ExtIOR\nColor3f FresnelConductor(float CosThetaI, const Color3f & Eta, const Color3f & EtaK);\n\n/**\n* Approximating the diffuse Frensel reflectance \n* for the Eta < 1.0 and Eta > 1.0 cases.\n*/\nfloat ApproxFresnelDiffuseReflectance(float Eta);\n\n/// Complete the set {a} to an orthonormal base\nvoid CoordinateSystem(const Vector3f & Va, Vector3f & Vb, Vector3f & Vc);\n\n/// Reflection in local coordinates\nVector3f Reflect(const Vector3f & Wi);\n\n/// Refraction in local coordinates\nVector3f Refract(const Vector3f & Wi, float CosThetaT, float Eta, float InvEta);\n\n/// Reflection in global coordinates\nVector3f Reflect(const Vector3f & Wi, const Vector3f & M);\n\n/// Refraction in global coordinates\nVector3f Refract(const Vector3f & Wi, const Vector3f & M, float CosThetaT, float Eta, float InvEta);\n\n/**\n* \\brief Return the global file resolver instance\n*\n* This class is used to locate resource files (e.g. mesh or\n* texture files) referenced by a scene being loaded\n*/\nfilesystem::resolver * GetFileResolver();\n\nNAMESPACE_END", "meta": {"hexsha": "1f9754d1aed04576d38240218318598e8d5e7064", "size": 41459, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/core/Common.hpp", "max_stars_repo_name": "BlauHimmel/Hikari", "max_stars_repo_head_hexsha": "38746e5d03a8e106a346a6f792f3093034a576bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-22T03:07:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:51:29.000Z", "max_issues_repo_path": "include/core/Common.hpp", "max_issues_repo_name": "BlauHimmel/Hikari", "max_issues_repo_head_hexsha": "38746e5d03a8e106a346a6f792f3093034a576bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:05:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-26T06:07:13.000Z", "max_forks_repo_path": "include/core/Common.hpp", "max_forks_repo_name": "BlauHimmel/Hikari", "max_forks_repo_head_hexsha": "38746e5d03a8e106a346a6f792f3093034a576bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-12-18T12:40:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:51:31.000Z", "avg_line_length": 36.2720909886, "max_line_length": 124, "alphanum_fraction": 0.6933597048, "num_tokens": 10706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.030214583683520604, "lm_q1q2_score": 0.015107291841760302}}
{"text": "#ifndef VEXCL_SPARSE_ELL_HPP\n#define VEXCL_SPARSE_ELL_HPP\n\n/*\nThe MIT License\n\nCopyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n/**\n * \\file   vexcl/sparse/ell.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief  Sparse matrix in ELL format.\n */\n\n#include <vector>\n#include <type_traits>\n#include <utility>\n\n#include <boost/foreach.hpp>\n#include <boost/range.hpp>\n\n#include <vexcl/util.hpp>\n#include <vexcl/operations.hpp>\n#include <vexcl/vector.hpp>\n#include <vexcl/sparse/product.hpp>\n#include <vexcl/element_index.hpp>\n#include <vexcl/tagged_terminal.hpp>\n#include <vexcl/reductor.hpp>\n\n#include <vexcl/reductor.hpp>\n#include <vexcl/vector_view.hpp>\n#include <vexcl/element_index.hpp>\n#include <vexcl/function.hpp>\n#include <vexcl/eval.hpp>\n#include <vexcl/vector_pointer.hpp>\n#include <vexcl/scan.hpp>\n#include <vexcl/sparse/spmv_ops.hpp>\n\nnamespace vex {\nnamespace sparse {\n\ntemplate <typename Val, typename Col = int, typename Ptr = Col>\nclass ell {\n    public:\n        typedef Val value_type;\n\n        typedef Val val_type;\n        typedef Col col_type;\n        typedef Ptr ptr_type;\n\n        template <class PtrRange, class ColRange, class ValRange>\n        ell(\n                const std::vector<backend::command_queue> &q,\n                size_t nrows, size_t ncols,\n                const PtrRange &ptr,\n                const ColRange &col,\n                const ValRange &val,\n                bool fast = true\n           ) :\n            q(q[0]), n(nrows), m(ncols), nnz(boost::size(val)),\n            ell_pitch(alignup(nrows, 16U)), csr_nnz(0)\n        {\n            precondition(q.size() == 1,\n                    \"sparse::ell is only supported for single-device contexts\");\n\n            if (fast) {\n                convert(ptr, col, val);\n                return;\n            }\n\n            /* 1. Get optimal ELL widths for local and remote parts. */\n            // Speed of ELL relative to CSR:\n            const double ell_vs_csr = 3.0;\n\n            // Find maximum widths for local and remote parts:\n            int max_width = 0;\n            for(size_t i = 0; i < n; ++i)\n                max_width = std::max(max_width, static_cast<int>(ptr[i+1] - ptr[i]));\n\n            // Build width distribution histogram.\n            std::vector<size_t> hist(max_width + 1, 0);\n            for(size_t i = 0; i < n; ++i)\n                ++hist[ptr[i+1] - ptr[i]];\n\n            // Estimate optimal width for ELL part of the matrix.\n            ell_width = max_width;\n            {\n                size_t rows = n;\n                for(int i = 0; i < max_width; ++i) {\n                    rows -= hist[i]; // Number of rows wider than i.\n                    if (ell_vs_csr * rows < n) {\n                        ell_width = i;\n                        break;\n                    }\n                }\n            }\n\n            if (ell_width == 0) {\n                csr_nnz = nnz;\n\n                csr_ptr = backend::device_vector<Col>(q[0], n + 1,   &ptr[0]);\n                csr_col = backend::device_vector<Col>(q[0], csr_nnz, &col[0]);\n                csr_val = backend::device_vector<Val>(q[0], csr_nnz, &val[0]);\n\n                return;\n            }\n\n            // Count nonzeros in CSR part of the matrix.\n            for(int i = ell_width + 1; i <= max_width; ++i)\n                csr_nnz += hist[i] * (i - ell_width);\n\n            /* 3. Split the input matrix into ELL and CSR submatrices. */\n            std::vector<Col> _ell_col(ell_pitch * ell_width, static_cast<Col>(-1));\n            std::vector<Val> _ell_val(ell_pitch * ell_width);\n            std::vector<Ptr> _csr_ptr;\n            std::vector<Col> _csr_col;\n            std::vector<Val> _csr_val;\n\n            if (csr_nnz) {\n                _csr_ptr.resize(n + 1);\n                _csr_col.resize(csr_nnz);\n                _csr_val.resize(csr_nnz);\n\n                _csr_ptr[0] = 0;\n                for(size_t i = 0; i < n; ++i) {\n                    Ptr w = ptr[i+1] - ptr[i];\n                    _csr_ptr[i+1] = _csr_ptr[i] + static_cast<Ptr>(w > ell_width ? w - ell_width : 0);\n                }\n            }\n\n\n            for(size_t i = 0; i < n; ++i) {\n                int w = 0;\n                Ptr csr_head = csr_nnz ? _csr_ptr[i] : 0;\n                for(Ptr j = ptr[i], e = ptr[i+1]; j < e; ++j, ++w) {\n                    Col c = col[j];\n                    Val v = val[j];\n\n                    if (w < ell_width) {\n                        _ell_col[i + w * ell_pitch] = c;\n                        _ell_val[i + w * ell_pitch] = v;\n                    } else {\n                        _csr_col[csr_head] = c;\n                        _csr_val[csr_head] = v;\n                        ++csr_head;\n                    }\n                }\n            }\n\n            ell_col = backend::device_vector<Col>(q[0], ell_pitch * ell_width, _ell_col.data());\n            ell_val = backend::device_vector<Val>(q[0], ell_pitch * ell_width, _ell_val.data());\n\n            if (csr_nnz) {\n                csr_ptr = backend::device_vector<Col>(q[0], n + 1,   _csr_ptr.data());\n                csr_col = backend::device_vector<Col>(q[0], csr_nnz, _csr_col.data());\n                csr_val = backend::device_vector<Val>(q[0], csr_nnz, _csr_val.data());\n            }\n        }\n\n        // Dummy matrix; used internally to pass empty parameters to kernels.\n        ell(const backend::command_queue &q)\n            : q(q), n(0), m(0), nnz(0), ell_pitch(0), csr_nnz(0), ell_width(0)\n        {}\n\n        template <class Expr>\n        friend\n        typename std::enable_if<\n            boost::proto::matches<\n                typename boost::proto::result_of::as_expr<Expr>::type,\n                vector_expr_grammar\n            >::value,\n            matrix_vector_product<ell, Expr>\n        >::type\n        operator*(const ell &A, const Expr &x) {\n            return matrix_vector_product<ell, Expr>(A, x);\n        }\n\n        template <class Vector>\n        static void terminal_preamble(const Vector &x, backend::source_generator &src,\n            const backend::command_queue &q, const std::string &prm_name,\n            detail::kernel_generator_state_ptr state)\n        {\n            detail::output_terminal_preamble tp(src, q, prm_name + \"_x\", state);\n            boost::proto::eval(boost::proto::as_child(x), tp);\n        }\n\n        template <class Vector>\n        static void local_terminal_init(const Vector &x, backend::source_generator &src,\n            const backend::command_queue &q, const std::string &prm_name,\n            detail::kernel_generator_state_ptr state)\n        {\n            typedef typename detail::return_type<Vector>::type x_type;\n            typedef spmv_ops_impl<Val, x_type> spmv_ops;\n\n            spmv_ops::decl_accum_var(src, prm_name + \"_sum\");\n            src.open(\"{\");\n\n            // ELL part\n            src.new_line() << \"for(size_t j = 0; j < \" << prm_name << \"_ell_width; ++j)\";\n            src.open(\"{\");\n            src.new_line() << type_name<Col>() << \" nnz_idx = idx + j * \" << prm_name << \"_ell_pitch;\";\n            src.new_line() << type_name<Col>() << \" c = \" << prm_name << \"_ell_col[nnz_idx];\";\n            src.new_line() << \"if (c != (\" << type_name<Col>() << \")(-1))\";\n            src.open(\"{\");\n\n            src.new_line() << type_name<Col>() << \" idx = c;\";\n\n            {\n                detail::output_local_preamble init_x(src, q, prm_name + \"_x\", state);\n                boost::proto::eval(boost::proto::as_child(x), init_x);\n\n                backend::source_generator vec_value;\n                detail::vector_expr_context expr_x(vec_value, q, prm_name + \"_x\", state);\n                boost::proto::eval(boost::proto::as_child(x), expr_x);\n\n                spmv_ops::append_product(src, prm_name + \"_sum\", prm_name + \"_ell_val[nnz_idx]\", vec_value.str());\n            }\n\n            src.close(\"} else break;\");\n            src.close(\"}\");\n\n            // CSR part\n            src.new_line() << \"if (\" << prm_name << \"_csr_ptr)\";\n            src.open(\"{\");\n            src.new_line() << type_name<Ptr>() << \" csr_beg = \" << prm_name << \"_csr_ptr[idx];\";\n            src.new_line() << type_name<Ptr>() << \" csr_end = \" << prm_name << \"_csr_ptr[idx+1];\";\n            src.new_line() << \"for(\" << type_name<Ptr>() << \" j = csr_beg; j < csr_end; ++j)\";\n            src.open(\"{\");\n\n            src.new_line() << type_name<Col>() << \" idx = \" << prm_name << \"_csr_col[j];\";\n\n            {\n                detail::output_local_preamble init_x(src, q, prm_name + \"_x\", state);\n                boost::proto::eval(boost::proto::as_child(x), init_x);\n\n                backend::source_generator vec_value;\n                detail::vector_expr_context expr_x(vec_value, q, prm_name + \"_x\", state);\n                boost::proto::eval(boost::proto::as_child(x), expr_x);\n\n                spmv_ops::append_product(src, prm_name + \"_sum\", prm_name + \"_csr_val[j]\", vec_value.str());\n            }\n\n            src.close(\"}\");\n            src.close(\"}\");\n            src.close(\"}\");\n        }\n\n        template <class Vector>\n        static void kernel_param_declaration(const Vector &x, backend::source_generator &src,\n            const backend::command_queue &q, const std::string &prm_name,\n            detail::kernel_generator_state_ptr state)\n        {\n            src.parameter< int >(prm_name + \"_ell_width\");\n            src.parameter< size_t >(prm_name + \"_ell_pitch\");\n\n            src.parameter< global_ptr<Col> >(prm_name + \"_ell_col\");\n            src.parameter< global_ptr<Val> >(prm_name + \"_ell_val\");\n            src.parameter< global_ptr<Ptr> >(prm_name + \"_csr_ptr\");\n            src.parameter< global_ptr<Col> >(prm_name + \"_csr_col\");\n            src.parameter< global_ptr<Val> >(prm_name + \"_csr_val\");\n\n            detail::declare_expression_parameter decl_x(src, q, prm_name + \"_x\", state);\n            detail::extract_terminals()(boost::proto::as_child(x), decl_x);\n        }\n\n        template <class Vector>\n        static void partial_vector_expr(const Vector &, backend::source_generator &src,\n            const backend::command_queue&, const std::string &prm_name,\n            detail::kernel_generator_state_ptr)\n        {\n            src << prm_name << \"_sum\";\n        }\n\n        template <class Vector>\n        void kernel_arg_setter(const Vector &x,\n            backend::kernel &kernel, unsigned part, size_t index_offset,\n            detail::kernel_generator_state_ptr state) const\n        {\n            kernel.push_arg(ell_width);\n            kernel.push_arg(ell_pitch);\n            if (ell_width) {\n                kernel.push_arg(ell_col);\n                kernel.push_arg(ell_val);\n            } else {\n                kernel.push_arg(static_cast<size_t>(0));\n                kernel.push_arg(static_cast<size_t>(0));\n            }\n            if (csr_nnz) {\n                kernel.push_arg(csr_ptr);\n                kernel.push_arg(csr_col);\n                kernel.push_arg(csr_val);\n            } else {\n                kernel.push_arg(static_cast<size_t>(0));\n                kernel.push_arg(static_cast<size_t>(0));\n                kernel.push_arg(static_cast<size_t>(0));\n            }\n\n            detail::set_expression_argument x_args(kernel, part, index_offset, state);\n            detail::extract_terminals()( boost::proto::as_child(x), x_args);\n        }\n\n        template <class Vector>\n        void expression_properties(const Vector &x,\n            std::vector<backend::command_queue> &queue_list,\n            std::vector<size_t> &partition,\n            size_t &size) const\n        {\n            queue_list = std::vector<backend::command_queue>(1, q);\n            partition  = std::vector<size_t>(2, 0);\n            partition.back() = size = n;\n        }\n\n        size_t rows()     const { return n; }\n        size_t cols()     const { return m; }\n        size_t nonzeros() const { return nnz; }\n    private:\n        backend::command_queue q;\n\n        size_t n, m, nnz, ell_pitch, csr_nnz;\n        int ell_width;\n\n        backend::device_vector<Col> ell_col;\n        backend::device_vector<Val> ell_val;\n\n        backend::device_vector<Ptr> csr_ptr;\n        backend::device_vector<Col> csr_col;\n        backend::device_vector<Val> csr_val;\n\n        backend::kernel& csr2ell_kernel() const {\n            using namespace vex::detail;\n            static kernel_cache cache;\n\n            auto kernel = cache.find(q);\n            if (kernel == cache.end()) {\n                backend::source_generator src(q);\n\n                src.begin_kernel(\"convert_csr2ell\");\n                src.begin_kernel_parameters();\n                src.template parameter<size_t>(\"n\");\n                src.template parameter<int>(\"ell_width\");\n                src.template parameter<size_t>(\"ell_pitch\");\n                src.template parameter< global_ptr<const ptr_type> >(\"ptr\");\n                src.template parameter< global_ptr<const col_type> >(\"col\");\n                src.template parameter< global_ptr<const val_type> >(\"val\");\n                src.template parameter< global_ptr<col_type> >(\"ell_col\");\n                src.template parameter< global_ptr<val_type> >(\"ell_val\");\n                src.template parameter< global_ptr<const ptr_type> >(\"csr_ptr\");\n                src.template parameter< global_ptr<col_type> >(\"csr_col\");\n                src.template parameter< global_ptr<val_type> >(\"csr_val\");\n                src.end_kernel_parameters();\n                src.grid_stride_loop().open(\"{\");\n\n                src.new_line() << type_name<int>() << \" w = 0;\";\n                src.new_line() << type_name<ptr_type>() << \" csr_head = 0;\";\n                src.new_line() << \"if (csr_ptr) csr_head = csr_ptr[idx];\";\n                src.new_line() << \"for(\" << type_name<ptr_type>() << \" j = ptr[idx], e = ptr[idx+1]; j < e; ++j, ++w)\";\n                src.open(\"{\");\n                src.new_line() << type_name<col_type>() << \" c = col[j];\";\n                src.new_line() << type_name<val_type>() << \" v = val[j];\";\n                src.new_line() << \"if (w < ell_width) {\";\n                src.new_line() << \"  ell_col[idx + w * ell_pitch] = c;\";\n                src.new_line() << \"  ell_val[idx + w * ell_pitch] = v;\";\n                src.new_line() << \"} else {\";\n                src.new_line() << \"  csr_col[csr_head] = c;\";\n                src.new_line() << \"  csr_val[csr_head] = v;\";\n                src.new_line() << \"  ++csr_head;\";\n                src.new_line() << \"}\";\n                src.close(\"}\");\n                //src.new_line() << \"for(; w < ell_width; ++w)\";\n                //src.new_line() << \"  ell_col[idx + w * ell_pitch] = (\" << type_name<col_type>() << \")(-1);\";\n                src.close(\"}\");\n                src.end_kernel();\n\n                kernel = cache.insert(q, backend::kernel(q, src.str(), \"convert_csr2ell\"));\n            }\n\n            return kernel->second;\n        }\n\n        template <class PtrRange, class ColRange, class ValRange>\n        void convert(\n                const PtrRange &host_ptr,\n                const ColRange &host_col,\n                const ValRange &host_val\n                )\n        {\n            size_t nnz = host_ptr[n];\n\n            backend::device_vector<Ptr> Aptr(q, n+1, &host_ptr[0]);\n            backend::device_vector<Col> Acol(q, nnz, &host_col[0]);\n            backend::device_vector<Val> Aval(q, nnz, &host_val[0]);\n\n            /* 1. Get optimal ELL widths for local and remote parts. */\n            // Speed of ELL relative to CSR:\n            const double ell_vs_csr = 3.0;\n\n            // Find maximum widths for local and remote parts:\n            std::vector<backend::command_queue> ctx(1, q);\n            Reductor<int, MAX> max(ctx);\n\n            vex::vector<Ptr> ptr(q, Aptr);\n\n            VEX_FUNCTION(ptr_type, row_width, (size_t, i)(const ptr_type*, ptr),\n                    return ptr[i+1] - ptr[i];\n                    );\n\n            int max_width = max(row_width(element_index(0, n), raw_pointer(ptr)));\n\n            // Build width distribution histogram.\n            vex::vector<int> hist(ctx, max_width + 1);\n            hist = 0;\n            eval(atomic_add(&permutation(row_width(element_index(0, n), raw_pointer(ptr)))(hist), 1));\n\n            // Estimate optimal width for ELL part of the matrix,\n            // count nonzeros in CSR part of the matrix\n            ell_width = max_width;\n            {\n                auto h = hist.map(0);\n\n                for(int i = 0, rows = static_cast<int>(n); i < max_width; ++i) {\n                    rows -= h[i]; // Number of rows wider than i.\n                    if (ell_vs_csr * rows < n) {\n                        ell_width = i;\n                        break;\n                    }\n                }\n\n                for(int i = ell_width + 1; i <= max_width; ++i)\n                    csr_nnz += h[i] * (i - ell_width);\n            }\n\n            if (ell_width == 0) {\n                assert(csr_nnz == nnz);\n\n                csr_ptr = Aptr;\n                csr_col = Acol;\n                csr_val = Aval;\n\n                return;\n            }\n\n            if (csr_nnz) {\n                VEX_FUNCTION(int, csr_width, (int, ell_width)(size_t, i)(const ptr_type*, ptr),\n                        if (i == 0) return 0;\n                        int w = ptr[i] - ptr[i-1];\n                        return (w > ell_width) ? (w - ell_width) : 0;\n                        );\n\n                vex::vector<ptr_type> csr_w(ctx, n+1);\n\n                csr_ptr = backend::device_vector<Ptr>(q, n + 1);\n                csr_col = backend::device_vector<Col>(q, csr_nnz);\n                csr_val = backend::device_vector<Val>(q, csr_nnz);\n\n                csr_w = csr_width(ell_width, element_index(), raw_pointer(ptr));\n                vector<ptr_type> csr_p(q, csr_ptr);\n                inclusive_scan(csr_w, csr_p);\n            }\n\n\n            /* 3. Split the input matrix into ELL and CSR submatrices. */\n            ell_col = backend::device_vector<Col>(q, ell_pitch * ell_width);\n            ell_val = backend::device_vector<Val>(q, ell_pitch * ell_width);\n\n            vex::vector<Col>(q, ell_col) = -1;\n\n            auto &convert = csr2ell_kernel();\n\n            convert.push_arg(n);\n            convert.push_arg(ell_width);\n            convert.push_arg(ell_pitch);\n            convert.push_arg(Aptr);\n            convert.push_arg(Acol);\n            convert.push_arg(Aval);\n            convert.push_arg(ell_col);\n            convert.push_arg(ell_val);\n            if (csr_nnz) {\n                convert.push_arg(csr_ptr);\n                convert.push_arg(csr_col);\n                convert.push_arg(csr_val);\n            } else {\n                convert.push_arg(static_cast<size_t>(0));\n                convert.push_arg(static_cast<size_t>(0));\n                convert.push_arg(static_cast<size_t>(0));\n            }\n            convert(q);\n        }\n\n};\n\n} // namespace sparse\n} // namespace vex\n\n#endif\n", "meta": {"hexsha": "0f9ff5935a0e581f719e6c8cf3c28a8b594e973e", "size": 19923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/vexcl/sparse/ell.hpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/vexcl/sparse/ell.hpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/vexcl/sparse/ell.hpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 38.7607003891, "max_line_length": 119, "alphanum_fraction": 0.5278321538, "num_tokens": 4678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.03846618981375452, "lm_q1q2_score": 0.015091702980134762}}
{"text": "// Copyright (c) 2016-2017, Philipp Sebastian Ruppel\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 Universität Hamburg 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#include \"bio_ik/ik_gradient.hpp\"\n\n#include <Eigen/Core>          // For NumTraits\n#include <bio_ik/ik_base.hpp>  // for IKSolver\n#include <bio_ik/problem.hpp>  // for Problem, Problem::GoalInfo\n#include <bio_ik/utils.hpp>    // for FNPROFILER\n#include <cmath>               // for isfinite\n#include <cstddef>             // for size_t\n#include <ext/alloc_traits.h>  // for __alloc_traits<>::value_type\n#include <kdl/frames.hpp>      // for Twist, Vector\n#include <memory>\n#include <optional>\n#include <vector>  // for vector, allocator\n\n#include \"bio_ik/frame.hpp\"       // for Frame, frameTwist\n#include \"bio_ik/robot_info.hpp\"  // for RobotInfo\n\nnamespace bio_ik {\n\n// simple gradient descent\ntemplate <int IF_STRUCK, size_t N_THREADS>\nvoid IKGradientDescent<IF_STRUCK, N_THREADS>::initialize(\n    const Problem& problem) {\n  IKSolver::initialize(problem);\n  solution_ = problem_.initial_guess;\n  if (thread_index_ > 0)\n    for (auto& vi : problem_.active_variables)\n      solution_[vi] = random(modelInfo_.getMin(vi), modelInfo_.getMax(vi));\n  best_solution_ = solution_;\n  reset_ = false;\n}\n\ntemplate <int IF_STRUCK, size_t N_THREADS>\nvoid IKGradientDescent<IF_STRUCK, N_THREADS>::step() {\n  // random reset if stuck\n  if (reset_) {\n    reset_ = false;\n    for (auto& vi : problem_.active_variables)\n      solution_[vi] = random(modelInfo_.getMin(vi), modelInfo_.getMax(vi));\n  }\n\n  // compute gradient_ direction\n  temp_ = solution_;\n  double jd = 0.0001;\n  gradient_.resize(solution_.size(), 0);\n  for (auto ivar : problem_.active_variables) {\n    temp_[ivar] = solution_[ivar] - jd;\n    double p1 = computeFitness(temp_);\n\n    temp_[ivar] = solution_[ivar] + jd;\n    double p3 = computeFitness(temp_);\n\n    temp_[ivar] = solution_[ivar];\n\n    gradient_[ivar] = p3 - p1;\n  }\n\n  // normalize gradient direction\n  double sum = 0.0001;\n  for (auto ivar : problem_.active_variables) sum += fabs(gradient_[ivar]);\n  double f = 1.0 / sum * jd;\n  for (auto ivar : problem_.active_variables) gradient_[ivar] *= f;\n\n  // initialize line search\n  temp_ = solution_;\n\n  for (auto ivar : problem_.active_variables)\n    temp_[ivar] = solution_[ivar] - gradient_[ivar];\n  double p1 = computeFitness(temp_);\n\n  // for(auto ivar : problem_.active_variables) temp_[ivar] = solution_[ivar];\n  // double p2 = computeFitness(temp_);\n\n  for (auto ivar : problem_.active_variables)\n    temp_[ivar] = solution_[ivar] + gradient_[ivar];\n  double p3 = computeFitness(temp_);\n\n  double p2 = (p1 + p3) * 0.5;\n\n  // linear step size estimation\n  double cost_diff = (p3 - p1) * 0.5;\n  double joint_diff = p2 / cost_diff;\n\n  // in case cost_diff is 0\n  if (!std::isfinite(joint_diff)) joint_diff = 0.0;\n\n  // apply optimization step\n  // (move along gradient direction by estimated step size)\n  for (auto ivar : problem_.active_variables)\n    temp_[ivar] =\n        modelInfo_.clip(solution_[ivar] - gradient_[ivar] * joint_diff, ivar);\n\n  if (IF_STRUCK == 'c') {\n    // always accept solution and continue\n    solution_ = temp_;\n  } else {\n    // has solution improved?\n    if (computeFitness(temp_) < computeFitness(solution_)) {\n      // solution improved -> accept solution\n      solution_ = temp_;\n    } else {\n      if (IF_STRUCK == 'r') {\n        // reset if stuck\n        reset_ = true;\n      }\n    }\n  }\n\n  // update best solution\n  if (computeFitness(solution_) < computeFitness(best_solution_))\n    best_solution_ = solution_;\n}\n\n// pseudoinverse jacobian solver\ntemplate <class BASE>\nvoid IKJacobianBase<BASE>::optimizeJacobian(std::vector<double>& solution) {\n  FNPROFILER();\n\n  Eigen::Index tip_count =\n      static_cast<Eigen::Index>(problem_.tip_link_indices.size());\n  tip_diffs_.resize(tip_count * 6);\n  joint_diffs_.resize(\n      static_cast<Eigen::Index>(problem_.active_variables.size()));\n\n  // compute fk\n  model_.applyConfiguration(solution);\n\n  double translational_scale = 1;\n  double rotational_scale = 1;\n\n  // compute goal diffs\n  tip_frames_temp_ = model_.getTipFrames();\n  for (Eigen::Index itip = 0; itip < tip_count; ++itip) {\n    auto twist = frameTwist(tip_frames_temp_[static_cast<size_t>(itip)],\n                            tipObjectives_[static_cast<size_t>(itip)]);\n    tip_diffs_(itip * 6 + 0) = twist.vel.x() * translational_scale;\n    tip_diffs_(itip * 6 + 1) = twist.vel.y() * translational_scale;\n    tip_diffs_(itip * 6 + 2) = twist.vel.z() * translational_scale;\n    tip_diffs_(itip * 6 + 3) = twist.rot.x() * rotational_scale;\n    tip_diffs_(itip * 6 + 4) = twist.rot.y() * rotational_scale;\n    tip_diffs_(itip * 6 + 5) = twist.rot.z() * rotational_scale;\n  }\n\n  // compute jacobian\n  {\n    model_.computeJacobian(problem_.active_variables, jacobian_);\n    Eigen::Index icol = 0;\n    for (auto __attribute__((unused)) _ : problem_.active_variables) {\n      for (Eigen::Index itip = 0; itip < tip_count; ++itip) {\n        jacobian_(itip * 6 + 0, icol) *= translational_scale;\n        jacobian_(itip * 6 + 1, icol) *= translational_scale;\n        jacobian_(itip * 6 + 2, icol) *= translational_scale;\n        jacobian_(itip * 6 + 3, icol) *= rotational_scale;\n        jacobian_(itip * 6 + 4, icol) *= rotational_scale;\n        jacobian_(itip * 6 + 5, icol) *= rotational_scale;\n      }\n      icol++;\n    }\n  }\n\n  // get pseudoinverse and multiply\n  joint_diffs_ = jacobian_.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV)\n                     .solve(tip_diffs_);\n  // joint_diffs_ = (jacobian_.transpose() *\n  // jacobian_).ldlt().solve(jacobian_.transpose() * tip_diffs_);\n\n  // apply joint deltas and clip\n  {\n    int icol = 0;\n    for (auto ivar : problem_.active_variables) {\n      auto v = solution[ivar] + joint_diffs_(icol);\n      if (!std::isfinite(v)) continue;\n      v = modelInfo_.clip(v, ivar);\n      solution[ivar] = v;\n      icol++;\n    }\n  }\n}\n\n// pseudoinverse jacobian only\ntemplate <size_t N_THREADS>\nvoid IKJacobian<N_THREADS>::initialize(const Problem& problem) {\n  IKJacobianBase<IKSolver>::initialize(problem);\n  solution_ = problem_.initial_guess;\n  if (thread_index_ > 0)\n    for (auto& vi : problem_.active_variables)\n      solution_[vi] = random(modelInfo_.getMin(vi), modelInfo_.getMax(vi));\n}\n\nstd::optional<std::unique_ptr<IKSolver>> makeGradientDecentSolver(\n    const IKParams& params) {\n  const auto& name = params.ros_params.mode;\n  if (name == \"gd\")\n    return std::make_unique<IKGradientDescent<' ', 1>>(params);\n  else if (name == \"gd_2\")\n    return std::make_unique<IKGradientDescent<' ', 2>>(params);\n  else if (name == \"gd_4\")\n    return std::make_unique<IKGradientDescent<' ', 4>>(params);\n  else if (name == \"gd_8\")\n    return std::make_unique<IKGradientDescent<' ', 8>>(params);\n  else if (name == \"gd_r\")\n    return std::make_unique<IKGradientDescent<'r', 1>>(params);\n  else if (name == \"gd_r_2\")\n    return std::make_unique<IKGradientDescent<'r', 2>>(params);\n  else if (name == \"gd_r_4\")\n    return std::make_unique<IKGradientDescent<'r', 4>>(params);\n  else if (name == \"gd_r_8\")\n    return std::make_unique<IKGradientDescent<'r', 8>>(params);\n  else if (name == \"gd_c\")\n    return std::make_unique<IKGradientDescent<'c', 1>>(params);\n  else if (name == \"gd_c_2\")\n    return std::make_unique<IKGradientDescent<'c', 2>>(params);\n  else if (name == \"gd_c_4\")\n    return std::make_unique<IKGradientDescent<'c', 4>>(params);\n  else if (name == \"gd_c_8\")\n    return std::make_unique<IKGradientDescent<'c', 8>>(params);\n  else if (name == \"jac\")\n    return std::make_unique<IKJacobian<1>>(params);\n  else if (name == \"jac_2\")\n    return std::make_unique<IKJacobian<2>>(params);\n  else if (name == \"jac_4\")\n    return std::make_unique<IKJacobian<4>>(params);\n  else if (name == \"jac_8\")\n    return std::make_unique<IKJacobian<8>>(params);\n  else\n    return std::nullopt;\n}\n\n}  // namespace bio_ik\n", "meta": {"hexsha": "081fbd2928b6f56ed45171899f850fba89728f2a", "size": 9354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ik_gradient.cpp", "max_stars_repo_name": "SammyRamone/bio_ik", "max_stars_repo_head_hexsha": "f903cd3190f4acf15342aef70cddcef6cbbf8819", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T09:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T09:26:46.000Z", "max_issues_repo_path": "src/ik_gradient.cpp", "max_issues_repo_name": "SammyRamone/bio_ik", "max_issues_repo_head_hexsha": "f903cd3190f4acf15342aef70cddcef6cbbf8819", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2022-01-03T18:59:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T20:06:22.000Z", "max_forks_repo_path": "src/ik_gradient.cpp", "max_forks_repo_name": "SammyRamone/bio_ik", "max_forks_repo_head_hexsha": "f903cd3190f4acf15342aef70cddcef6cbbf8819", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-01-11T23:57:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T10:27:02.000Z", "avg_line_length": 36.2558139535, "max_line_length": 79, "alphanum_fraction": 0.6806713705, "num_tokens": 2583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.03567855331297613, "lm_q1q2_score": 0.015074354138197526}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2011-2014, Willow Garage, Inc.\n *  Copyright (c) 2014-2015, Open Source Robotics Foundation\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 Open Source Robotics Foundation 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 Jia Pan */\n\n#include <hpp/fcl/narrowphase/narrowphase.h>\n\n#include <vector>\n#include <boost/math/constants/constants.hpp>\n\n#include <hpp/fcl/shape/geometric_shapes_utility.h>\n#include <hpp/fcl/internal/intersect.h>\n#include \"details.h\"\n\nnamespace hpp\n{\nnamespace fcl\n{\n// Shape intersect algorithms based on:\n// - built-in function: 0\n// - GJK:               1\n//\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// |            | box | sphere | capsule | cone | cylinder | plane | half-space | triangle |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | box        |  0  |   0    |    1    |   1  |    1     |   0   |      0     |    1     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | sphere     |/////|   0    |    0    |   1  |    1     |   0   |      0     |    0     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | capsule    |/////|////////|    1    |   1  |    1     |   0   |      0     |    1     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | cone       |/////|////////|/////////|   1  |    1     |   0   |      0     |    1     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | cylinder   |/////|////////|/////////|//////|    1     |   0   |      0     |    1     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | plane      |/////|////////|/////////|//////|//////////|   0   |      0     |    0     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | half-space |/////|////////|/////////|//////|//////////|///////|      0     |    0     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | triangle   |/////|////////|/////////|//////|//////////|///////|////////////|    1     |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Sphere, Capsule>(const Sphere &s1, const Transform3f& tf1,\n                                                      const Capsule &s2, const Transform3f& tf2,\n                                                      Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  return details::sphereCapsuleIntersect(s1, tf1, s2, tf2, contact_points, penetration_depth, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Capsule, Sphere>(const Capsule &s1, const Transform3f& tf1,\n                                                      const Sphere &s2, const Transform3f& tf2,\n                                                      Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  const bool res = details::sphereCapsuleIntersect(s2, tf2, s1, tf1, contact_points, penetration_depth, normal);\n  if (normal) (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Sphere, Sphere>(const Sphere& s1, const Transform3f& tf1,\n                                                     const Sphere& s2, const Transform3f& tf2,\n                                                     Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  return details::sphereSphereIntersect(s1, tf1, s2, tf2, contact_points, penetration_depth, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Box, Sphere>(const Box   & s1, const Transform3f& tf1,\n                                                  const Sphere& s2, const Transform3f& tf2,\n                                                  Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL dist;\n  Vec3f ps, pb, n;\n  bool intersect = details::boxSphereDistance (s1, tf1, s2, tf2, dist, ps, pb, n);\n  if (!intersect) return false;\n  if (penetration_depth) *penetration_depth = dist;\n  if (normal)            *normal = n;\n  if (contact_points)    *contact_points = pb;\n  return true;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Sphere, Box>(const Sphere& s1, const Transform3f& tf1,\n                                                  const Box   & s2, const Transform3f& tf2,\n                                                  Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL dist;\n  Vec3f ps, pb, n;\n  bool intersect = details::boxSphereDistance (s2, tf2, s1, tf1, dist, ps, pb, n);\n  if (!intersect) return false;\n  if (penetration_depth) *penetration_depth = dist;\n  if (normal)            *normal = -n;\n  if (contact_points)    *contact_points = pb;\n  return true;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Box, Box>(const Box& s1, const Transform3f& tf1,\n                                               const Box& s2, const Transform3f& tf2,\n                                               Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  return details::boxBoxIntersect(s1, tf1, s2, tf2, contact_points, penetration_depth, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Sphere, Halfspace>\n(const Sphere& s1, const Transform3f& tf1,\n const Halfspace& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::sphereHalfspaceIntersect(s1, tf1, s2, tf2, distance, p1,\n                                               p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Halfspace, Sphere>(const Halfspace& s1, const Transform3f& tf1,\n                                                        const Sphere& s2, const Transform3f& tf2,\n                                                        Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::sphereHalfspaceIntersect(s2, tf2, s1, tf1, distance, p1,\n                                               p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Box, Halfspace>\n(const Box& s1, const Transform3f& tf1,\n const Halfspace& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::boxHalfspaceIntersect(s1, tf1, s2, tf2, distance, p1,\n                                            p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Halfspace, Box>\n(const Halfspace& s1, const Transform3f& tf1,\n const Box& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::boxHalfspaceIntersect(s2, tf2, s1, tf1, distance, p1,\n                                            p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Capsule, Halfspace>\n(const Capsule& s1, const Transform3f& tf1,\n const Halfspace& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res =  details::capsuleHalfspaceIntersect\n    (s1, tf1, s2, tf2, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Halfspace, Capsule>\n(const Halfspace& s1, const Transform3f& tf1,\n const Capsule& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res =  details::capsuleHalfspaceIntersect\n    (s2, tf2, s1, tf1, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Cylinder, Halfspace>\n(const Cylinder& s1, const Transform3f& tf1,\n const Halfspace& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res =  details::cylinderHalfspaceIntersect\n    (s1, tf1, s2, tf2, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Halfspace, Cylinder>\n(const Halfspace& s1, const Transform3f& tf1,\n const Cylinder& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res =  details::cylinderHalfspaceIntersect\n    (s2, tf2, s1, tf1, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Cone, Halfspace>\n(const Cone& s1, const Transform3f& tf1,\n const Halfspace& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res =  details::coneHalfspaceIntersect\n    (s1, tf1, s2, tf2, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Halfspace, Cone>\n(const Halfspace& s1, const Transform3f& tf1,\n const Cone& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res =  details::coneHalfspaceIntersect\n    (s2, tf2, s1, tf1, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Halfspace, Halfspace>(const Halfspace& s1, const Transform3f& tf1,\n                                                           const Halfspace& s2, const Transform3f& tf2,\n                                                           Vec3f* /*contact_points*/, FCL_REAL* /*penetration_depth*/, Vec3f* /*normal*/) const\n{\n  Halfspace s;\n  Vec3f p, d;\n  FCL_REAL depth;\n  int ret;\n  return details::halfspaceIntersect(s1, tf1, s2, tf2, p, d, s, depth, ret);\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Plane, Halfspace>(const Plane& s1, const Transform3f& tf1,\n                                                       const Halfspace& s2, const Transform3f& tf2,\n                                                       Vec3f* /*contact_points*/, FCL_REAL* /*penetration_depth*/, Vec3f* /*normal*/) const\n{\n  Plane pl;\n  Vec3f p, d;\n  FCL_REAL depth;\n  int ret;\n  return details::planeHalfspaceIntersect(s1, tf1, s2, tf2, pl, p, d, depth, ret);\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Halfspace, Plane>(const Halfspace& s1, const Transform3f& tf1,\n                                                       const Plane& s2, const Transform3f& tf2,\n                                                       Vec3f* /*contact_points*/, FCL_REAL* /*penetration_depth*/, Vec3f* /*normal*/) const\n{\n  Plane pl;\n  Vec3f p, d;\n  FCL_REAL depth;\n  int ret;\n  return details::halfspacePlaneIntersect(s1, tf1, s2, tf2, pl, p, d, depth, ret);\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Sphere, Plane>\n(const Sphere& s1, const Transform3f& tf1,\n const Plane& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::spherePlaneIntersect(s1, tf1, s2, tf2, distance, p1,\n                                           p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Plane, Sphere>\n(const Plane& s1, const Transform3f& tf1,\n const Sphere& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::spherePlaneIntersect(s2, tf2, s1, tf1, distance, p1,\n                                           p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Box, Plane>\n(const Box& s1, const Transform3f& tf1,\n const Plane& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::boxPlaneIntersect\n    (s1, tf1, s2, tf2, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Plane, Box>\n(const Plane& s1, const Transform3f& tf1,\n const Box& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::boxPlaneIntersect\n    (s2, tf2, s1, tf1, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Capsule, Plane>\n(const Capsule& s1, const Transform3f& tf1,\n const Plane& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::capsulePlaneIntersect(s1, tf1, s2, tf2, distance, p1,\n                                            p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Plane, Capsule>\n(const Plane& s1, const Transform3f& tf1,\n const Capsule& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::capsulePlaneIntersect(s2, tf2, s1, tf1, distance, p1,\n                                            p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Cylinder, Plane>\n(const Cylinder& s1, const Transform3f& tf1,\n const Plane& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::cylinderPlaneIntersect\n    (s1, tf1, s2, tf2, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Plane, Cylinder>\n(const Plane& s1, const Transform3f& tf1,\n const Cylinder& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::cylinderPlaneIntersect\n    (s2, tf2, s1, tf1, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Cone, Plane>\n(const Cone& s1, const Transform3f& tf1,\n const Plane& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::conePlaneIntersect\n    (s1, tf1, s2, tf2, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Plane, Cone>\n(const Plane& s1, const Transform3f& tf1,\n const Cone& s2, const Transform3f& tf2,\n Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  FCL_REAL distance;\n  Vec3f p1, p2;\n  bool res = details::conePlaneIntersect\n    (s2, tf2, s1, tf1, distance, p1, p2, *normal);\n  *contact_points = p1;\n  *penetration_depth = -distance;\n  (*normal) *= -1.0;\n  return res;\n}\n\ntemplate<>\nbool GJKSolver::shapeIntersect<Plane, Plane>(const Plane& s1, const Transform3f& tf1,\n                                                   const Plane& s2, const Transform3f& tf2,\n                                                   Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal) const\n{\n  return details::planeIntersect(s1, tf1, s2, tf2, contact_points, penetration_depth, normal);\n}\n\n\n\n\ntemplate<>\nbool GJKSolver::shapeTriangleInteraction\n(const Sphere& s, const Transform3f& tf1, const Vec3f& P1, const Vec3f& P2,\n const Vec3f& P3, const Transform3f& tf2, FCL_REAL& distance,\n Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::sphereTriangleIntersect\n    (s, tf1, tf2.transform(P1), tf2.transform(P2), tf2.transform(P3),\n     distance, p1, p2, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeTriangleInteraction\n(const Halfspace& s, const Transform3f& tf1, const Vec3f& P1, const Vec3f& P2,\n const Vec3f& P3, const Transform3f& tf2, FCL_REAL& distance,\n Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::halfspaceTriangleIntersect\n    (s, tf1, P1, P2, P3, tf2, distance, p1, p2, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeTriangleInteraction\n(const Plane& s, const Transform3f& tf1, const Vec3f& P1, const Vec3f& P2,\n const Vec3f& P3, const Transform3f& tf2, FCL_REAL& distance,\n Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::planeTriangleIntersect\n    (s, tf1, P1, P2, P3, tf2, distance, p1, p2, normal);\n}\n\n// Shape distance algorithms not using built-in GJK algorithm\n//\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// |            | box | sphere | capsule | cone | cylinder | plane | half-space | triangle |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | box        |     |   O    |         |      |          |       |            |          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | sphere     |/////|   O    |    O    |      |          |       |            |          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | capsule    |/////|////////|    O    |      |          |       |            |          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | cone       |/////|////////|/////////|      |          |       |            |          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | cylinder   |/////|////////|/////////|//////|          |       |            |          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | plane      |/////|////////|/////////|//////|//////////|       |            |          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | half-space |/////|////////|/////////|//////|//////////|///////|            |          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n// | triangle   |/////|////////|/////////|//////|//////////|///////|////////////|          |\n// +------------+-----+--------+---------+------+----------+-------+------------+----------+\n\ntemplate<>\nbool GJKSolver::shapeDistance<Sphere, Capsule>\n(const Sphere& s1, const Transform3f& tf1,\n const Capsule& s2, const Transform3f& tf2,\n FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::sphereCapsuleDistance(s1, tf1, s2, tf2, dist, p1, p2, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeDistance<Capsule, Sphere>\n(const Capsule& s1, const Transform3f& tf1,\n const Sphere& s2, const Transform3f& tf2,\n FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::sphereCapsuleDistance(s2, tf2, s1, tf1, dist, p2, p1, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeDistance<Sphere, Cylinder>\n(const Sphere& s1, const Transform3f& tf1,\n const Cylinder& s2, const Transform3f& tf2,\n FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::sphereCylinderDistance\n    (s1, tf1, s2, tf2, dist, p1, p2, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeDistance<Box, Sphere>\n(const Box   & s1, const Transform3f& tf1,\n const Sphere& s2, const Transform3f& tf2,\n FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return !details::boxSphereDistance (s1, tf1, s2, tf2, dist, p1, p2, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeDistance<Sphere, Box>\n(const Sphere& s1, const Transform3f& tf1,\n const Box   & s2, const Transform3f& tf2,\n FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  bool collide = details::boxSphereDistance (s2, tf2, s1, tf1, dist, p2, p1, normal);\n  normal *= -1;\n  return !collide;\n}\n\ntemplate<>\nbool GJKSolver::shapeDistance<Cylinder, Sphere>\n(const Cylinder& s1, const Transform3f& tf1,\n const Sphere& s2, const Transform3f& tf2,\n FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::sphereCylinderDistance\n    (s2, tf2, s1, tf1, dist, p2, p1, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeDistance<Sphere, Sphere>\n(const Sphere& s1, const Transform3f& tf1,\n const Sphere& s2, const Transform3f& tf2,\n FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n{\n  return details::sphereSphereDistance(s1, tf1, s2, tf2, dist, p1, p2, normal);\n}\n\ntemplate<>\nbool GJKSolver::shapeDistance<Capsule, Capsule>\n(const Capsule& /*s1*/, const Transform3f& /*tf1*/,\n const Capsule& /*s2*/, const Transform3f& /*tf2*/,\n FCL_REAL& /*dist*/, Vec3f& /*p1*/, Vec3f& /*p2*/, Vec3f& /*normal*/) const\n{\n  abort ();\n}\n\n  template<>\n    bool GJKSolver::shapeDistance<TriangleP, TriangleP>\n    (const TriangleP& s1, const Transform3f& tf1,\n     const TriangleP& s2, const Transform3f& tf2,\n     FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal) const\n  {\n    const TriangleP\n      t1 (tf1.transform(s1.a), tf1.transform(s1.b), tf1.transform(s1.c)),\n      t2 (tf2.transform(s2.a), tf2.transform(s2.b), tf2.transform(s2.c));\n\n    Vec3f guess;\n    if(enable_cached_guess) guess = cached_guess;\n    else guess = (t1.a + t1.b + t1.c - t2.a - t2.b - t2.c) / 3;\n    bool enable_penetration (true);\n\n    details::MinkowskiDiff shape;\n    shape.set (&t1, &t2);\n\n    details::GJK gjk((unsigned int) gjk_max_iterations, gjk_tolerance);\n    details::GJK::Status gjk_status = gjk.evaluate(shape, -guess);\n    if(enable_cached_guess) cached_guess = gjk.getGuessFromSimplex();\n\n    details::GJK::getClosestPoints (*gjk.getSimplex(), p1, p2);\n\n    if((gjk_status == details::GJK::Valid) ||\n       (gjk_status == details::GJK::Failed))\n    {\n      // TODO On degenerated case, the closest point may be wrong\n      // (i.e. an object face normal is colinear to gjk.ray\n      // assert (dist == (w0 - w1).norm());\n      dist = gjk.distance;\n\n      return true;\n    }\n    else if (gjk_status == details::GJK::Inside)\n    {\n      if (enable_penetration) {\n        FCL_REAL penetrationDepth = details::computePenetration\n          (t1.a, t1.b, t1.c, t2.a, t2.b, t2.c, normal);\n        dist = -penetrationDepth;\n        assert (dist <= 1e-6);\n        // GJK says Inside when below GJK.tolerance. So non intersecting\n        // triangle may trigger \"Inside\" and have no penetration.\n        return penetrationDepth < 0;\n      }\n      dist = 0;\n      return false;\n    }\n    assert (false && \"should not reach this point\");\n    return false;\n  }\n} // fcl\n\n} // namespace hpp\n", "meta": {"hexsha": "829855fbf5eaddd55deb8529d8f01229e21ce851", "size": 25041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/narrowphase/narrowphase.cpp", "max_stars_repo_name": "rstrudel/hpp-fcl", "max_stars_repo_head_hexsha": "9e4d930b5af2b699475af1483c6dbe5a672bbab8", "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/narrowphase/narrowphase.cpp", "max_issues_repo_name": "rstrudel/hpp-fcl", "max_issues_repo_head_hexsha": "9e4d930b5af2b699475af1483c6dbe5a672bbab8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/narrowphase/narrowphase.cpp", "max_forks_repo_name": "rstrudel/hpp-fcl", "max_forks_repo_head_hexsha": "9e4d930b5af2b699475af1483c6dbe5a672bbab8", "max_forks_repo_licenses": ["BSD-3-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.9336283186, "max_line_length": 143, "alphanum_fraction": 0.5794497025, "num_tokens": 7308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.03567855280029284, "lm_q1q2_score": 0.01507435392158646}}
{"text": "/*\n * Copyright (C) 2015 INRA\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 *    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 *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n * OR 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 SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <algorithm>\n#include <iterator>\n#include <boost/progress.hpp>\n#include <vle/dsde/qss1.hpp>\n#include <vle/vle.hpp>\n\nusing state_type = std::array <double, 5>;\n\nenum FirePosition {\n    NORTH = 1, SOUTH, EAST, WEST\n};\n\nstruct NoStorage {\n    using input_type = vle::dsde::qss1::inputport <5>;\n    using output_type = vle::dsde::qss1::doubleport;\n\n    inline void push(std::size_t, double, const input_type&) {}\n    inline void push(std::size_t, double, const output_type&) {}\n    inline void resize(std::size_t) {}\n};\n\nstruct Storage {\n    using input_type = vle::dsde::qss1::inputport <5>;\n    using output_type = vle::dsde::qss1::doubleport;\n\n    using input_data = std::vector <input_type>;\n    using output_data = std::vector <output_type>;\n\n    struct Event {\n        Event(const input_type &input)\n        {\n            in.emplace_back(input);\n        }\n\n        Event(const output_type &output)\n        {\n            out.emplace_back(output);\n        }\n\n        input_data in;\n        output_data out;\n    };\n\n    ~Storage()\n    {\n        try {\n            std::cout << \"Storage in progress:\\n\" << std::flush;\n\n            for (auto i = 0ul, e = vector.size(); i != e; ++i) {\n                std::string filename(vle::stringf(\"model-%lu.dat\", i));\n                std::ofstream ofs(filename);\n                std::cout << \"\\rWrite: \" << filename << std::flush;\n\n                for (const auto &event : vector[i]) {\n                    ofs << event.first << ' ';\n\n                    if (event.second.in.empty())\n                        ofs << \"nan nan nan nan nan \";\n                    else\n                        for (const auto &in : event.second.in)\n                            ofs << in[0] << ' ' << in[1] << ' ' << in[2] << ' '\n                                << in[3] << ' ' << in[4] << ' ';\n\n                    if (event.second.out.empty())\n                        ofs << \"nan\";\n                    else\n                        for (const auto &out : event.second.out)\n                            ofs << out[0];\n\n                    ofs << '\\n';\n                }\n\n                ofs << '\\n';\n            }\n        } catch (...) {\n            std::cerr << \"failure\\n\";\n        }\n    }\n\n    void push(std::size_t id, double time, const input_type &data)\n    {\n        auto ret = vector.at(id).emplace(time, data);\n\n        if (ret.second == false)\n            ret.first->second.in.emplace_back(data);\n    }\n\n    void push(std::size_t id, double time, const output_type &data)\n    {\n        auto ret = vector.at(id).emplace(time, data);\n\n        if (ret.second == false)\n            ret.first->second.out.emplace_back(data);\n    }\n\n    void resize(std::size_t size)\n    {\n        vector.resize(size);\n    }\n\n    std::vector <std::map <double, Event>> vector;\n};\n\nclass Fire\n{\npublic:\n    Fire(double alpha, double K, double k, double enthalpy,\n         double mass, double surrounding, double dx, double dy)\n        : coeff_n(K / (dy * dy))\n        , coeff_s(K / (dy * dy))\n        , coeff_e(K / (dx * dx))\n        , coeff_w(K / (dx * dx))\n        , coeff_c(- k - 2.0 * K * (1.0 / (dx * dx) + 1.0 / (dy * dy)))\n        , coeff_cste(k * surrounding)\n        , alpha(alpha)\n        , f_t0(enthalpy * mass * alpha)\n        , t0(0.0)\n        , fire(false)\n    {}\n\n    double operator()(const state_type &variables, const double t)\n    {\n        if (!fire && variables[0] > 400.0) {\n            fire = true;\n            t0 = t;\n        }\n\n        if (fire && variables[0] < 333.0) {\n            fire = false;\n        }\n\n        double ret = coeff_n * ((variables[NORTH] > 0.) ?\n                                variables[NORTH] : variables[0]) +\n                     coeff_s * ((variables[SOUTH] > 0.) ?\n                                variables[SOUTH] : variables[0]) +\n                     coeff_e * ((variables[EAST] > 0.) ?\n                                variables[EAST] : variables[0]) +\n                     coeff_w * ((variables[WEST] > 0.) ?\n                                variables[WEST] : variables[0]) +\n                     coeff_c * variables[0] +\n                     coeff_cste;\n\n        if (fire) {\n            double f_t = f_t0 * std::exp(alpha * (t0 - t));\n            f_t0 = f_t;\n            t0 = t;\n            ret += f_t;\n        }\n\n        return ret;\n    }\n\nprivate:\n    const double coeff_n, coeff_s, coeff_e, coeff_w, coeff_c, coeff_cste;\n    const double alpha;\n    double f_t0, t0;\n    bool fire;\n};\n\ntemplate <typename StoragePolicy>\nclass FireForrest : public vle::dsde::CoupledModel <\n    vle::DoubleTime, vle::PortList <double>, vle::PortList <double>,\n    vle::dsde::qss1::inputport <5>,\n    vle::dsde::qss1::doubleport,\n    vle::dsde::TransitionPolicyDefault <vle::DoubleTime >>\n{\npublic:\n    using parent_type = vle::dsde::CoupledModel <\n                        vle::DoubleTime, vle::PortList <double>, vle::PortList <double>,\n                        vle::dsde::qss1::inputport <5>,\n                        vle::dsde::qss1::doubleport,\n                        vle::dsde::TransitionPolicyDefault <vle::DoubleTime >>;\n    using children_t = parent_type::children_t;\n    using child_type = parent_type::child_type;\n\n    FireForrest(const vle::Context &ctx,\n                std::size_t width, std::size_t height,\n                double alpha, double K, double k, double enthalpy,\n                double mass, double surrounding, double dx, double dy,\n                double dq, double epsilon)\n        : parent_type(ctx)\n        , m_width(width)\n        , m_height(height)\n    {\n        m_storage.resize(m_width * m_height);\n        m_models.reserve(width * height);\n\n        for (auto y = 0ul; y != height; ++y) {\n            for (auto x = 0ul; x != width; ++x) {\n                double init = (x == width / 4 && y == height / 4) ? 600 : 300;\n                double localmass = (x > width / 2 && y > height / 2) ? mass /\n                                   10 : mass;\n                m_models.emplace_back(\n                    ctx, dq, epsilon, init, 0u,\n                    Fire(alpha, K, k, enthalpy, localmass, surrounding, dx, dy));\n            }\n        }\n    }\n\n    FireForrest(const vle::Context &ctx,\n                std::ifstream &ifs,\n                double alpha, double K, double k, double enthalpy,\n                double mass, double surrounding, double dx, double dy,\n                double dq, double epsilon)\n        : parent_type(ctx)\n        , m_time(0)\n    {\n        ifs.exceptions(std::ios_base::failbit | std::ios_base::badbit);\n        ifs >> m_width >> m_height;\n\n        if (m_width == 0 or m_height == 0)\n            return;\n\n        m_storage.resize(m_width * m_height);\n        m_models.reserve(m_width * m_height);\n        std::vector <int> type(m_width * m_height, 0);\n        std::vector <double> init(m_width * m_height, 0);\n        std::copy_n(std::istream_iterator <int>(ifs),\n                    m_width * m_height,\n                    type.begin());\n        std::copy_n(std::istream_iterator <double>(ifs),\n                    m_width * m_height,\n                    init.begin());\n        std::cout << m_width << \"x\" << m_height << \"→\"\n                  << m_height *m_width << '\\n';\n\n        for (auto i = 0ul; i != (m_height * m_width); ++i) {\n            switch (type[i]) {\n            case 2:\n                std::cout << ((init[i] <= 300) ? \". \" : \"⚡ \");\n                m_models.emplace_back(\n                    ctx, dq, epsilon, init[i], 0u,\n                    Fire(alpha, K, k, enthalpy, mass / 4.0, surrounding, dx, dy));\n                break;\n            default:\n                std::cout << ((init[i] <= 300) ? \": \" : \"⚡ \");\n                m_models.emplace_back(\n                    ctx, dq, epsilon, init[i], 0u,\n                    Fire(alpha, K, k, enthalpy, mass, surrounding, dx, dy));\n                break;\n            }\n\n            if (((1 + i) % m_width) == 0)\n                std::cout << '\\n';\n        }\n    }\n\n    virtual children_t children(const vle::Common &) override final\n    {\n        children_t ret(m_models.size(), nullptr);\n\n        for (auto i = 0ul, e = m_models.size(); i != e; ++i)\n            ret[i] = &m_models[i];\n\n        return ret;\n    }\n\n    virtual void post(const UpdatedPort &out,\n                      UpdatedPort &in) const override final\n    {\n        for (auto *mdl : out) {\n            auto tmp = static_cast <const decltype(&m_models[0])>(mdl) - &m_models[0];\n            std::size_t position = boost::numeric_cast<std::size_t>(tmp);\n            auto x = position % m_width;\n            auto y = position / m_width;\n            m_storage.push(position, CoupledModel::tn, mdl->y);\n\n            if (x > 0) {\n                m_models[y * m_width + (x - 1)].x[EAST] = mdl->y[0];\n                in.emplace(&m_models[y * m_width + (x - 1)]);\n            }\n\n            if (x + 1 < m_width) {\n                m_models[y * m_width + (x + 1)].x[WEST] = mdl->y[0];\n                in.emplace(&m_models[y * m_width + (x + 1)]);\n            }\n\n            if (y > 0) {\n                m_models[(y - 1) * m_width + x].x[NORTH] = mdl->y[0];\n                in.emplace(&m_models[(y - 1) * m_width + x]);\n            }\n\n            if (y + 1 < m_height) {\n                m_models[(y + 1) * m_width + x].x[SOUTH] = mdl->y[0];\n                in.emplace(&m_models[(y + 1) * m_width + x]);\n            }\n        }\n\n        for (auto *mdl : in)\n            m_storage.push(\n                boost::numeric_cast<std::size_t>(\n                    static_cast <const decltype(&m_models[0])>(mdl) - &m_models[0]),\n                CoupledModel::tn,\n                mdl->x);\n    }\n\n    void value(std::ostream &os)\n    {\n        for (auto i = 0ul, e = m_models.size(); i != e; ++i) {\n            os << m_models[i].value();\n\n            if ((i + 1) % m_width == 0)\n                os << \"\\n\";\n            else\n                os << \" \";\n        }\n\n        os << \"\\n\";\n    }\n\n    std::vector <vle::dsde::qss1::Equation<vle::DoubleTime, 5>> m_models;\n    std::size_t m_width;\n    std::size_t m_height;\n    double m_time;\n    mutable StoragePolicy m_storage;\n};\n\ntemplate <typename StoragePolicy>\nvoid run(FireForrest <StoragePolicy> &model, vle::Context &ctx)\n{\n    constexpr const double finish = 200.0;\n    constexpr const unsigned int tostore = 40u;\n    vle::dsde::Engine <vle::DoubleTime> dsde_engine;\n    vle::SimulationStep <vle::dsde::Engine <vle::DoubleTime>> sim(ctx, dsde_engine);\n    double current = sim.init(model, 0.0);\n    double before = current;\n    auto step = 0u;\n    {\n        boost::progress_timer timer;\n        boost::progress_display progress(tostore);\n\n        while (sim.step(model, current, finish)) {\n            if ((current - before) >= (finish / tostore)) {\n                std::ofstream ofs(vle::stringf(\"fire-%u.dat\", step));\n                model.value(ofs);\n                before = current;\n                ++step;\n                ++progress;\n            }\n        }\n\n        progress += (progress.expected_count() - progress.count());\n    }\n    std::ofstream ofs(\"fireforrest.gnuplot\");\n    ofs << \"set terminal png nocrop enhanced size 4000,3000 font \\\"arial,9\\\"\\n\"\n        << \"set output 'fireforrest.png'\\n\"\n        << \"set multiplot layout \"\n        << 4u + (((step % 4u) > 0) ? 1u : 0u) << ','\n        << step / 4u << \" rowsfirst\\n\"\n        << \"set size ratio 1\\n\"\n        << \"set palette model XYZ rgbformulae 7,5,15\\n\"\n        << \"set xrange[-0.5:\" << model.m_width << \".5]\\n\"\n        << \"set yrange[-0.5:\" << model.m_height << \".5]\\n\"\n        << \"set cbrange[150.0:800.0]\\n\"\n        << \"set xtics 0,2,\" << model.m_width << \"\\n\"\n        << \"set ytics 0,2,\" << model.m_height << \"\\n\"\n        << \"set xtics offset -0.5,0\\n\";\n\n    for (auto i = 0ul; i < step; ++i)\n        ofs << \"set title \\\"fire-\" << i << \".dat\" << \"\\\"\\n\"\n            << \"plot \\\"fire-\" << i << \".dat\\\" matrix w image noti\\n\";\n\n    ofs << \"unset multiplot\\n\";\n}\n\nint main(int argc, char **argv)\n{\n    vle::Context ctx = std::make_shared <vle::ContextImpl>();\n    constexpr const std::size_t width = 30u;\n    constexpr const std::size_t height = 30u;\n    constexpr const double dq = 0.5;\n    constexpr const double epsilon = 0.5;\n    constexpr const double alpha = 0.19;\n    constexpr const double K = 0.000031;\n    constexpr const double k = 0.071;\n    constexpr const double enthalpy = 3605;\n    constexpr const double mass = 2;\n    constexpr const double surrounding = 300;\n    constexpr const double dx = 1. / 20.;\n    constexpr const double dy = 1. / 20.;\n    bool withstorage = false;\n    std::vector <char *> files;\n    files.reserve(4);\n\n    for (int i = 1; i < argc; ++i)\n        if (std::strcmp(argv[i], \"-s\") == 0)\n            withstorage = true;\n        else\n            files.push_back(argv[i]);\n\n    if (files.empty()) {\n        std::cout << \"Default simulation\\n\";\n        FireForrest <NoStorage> model(ctx, width, height,\n                                      alpha, K, k, enthalpy, mass,\n                                      surrounding,  dx,  dy, dq, epsilon);\n        run(model, ctx);\n    } else {\n        for (auto *str : files) {\n            std::cout << str << \" simulation\\n\";\n            std::ifstream ifs(str);\n\n            if (ifs.is_open()) {\n                if (withstorage) {\n                    FireForrest <Storage> model(ctx, ifs, alpha, K, k,\n                                                enthalpy, mass, surrounding,\n                                                dx,  dy, dq, epsilon);\n                    run(model, ctx);\n                } else {\n                    FireForrest <NoStorage> model(ctx, ifs, alpha, K, k,\n                                                  enthalpy, mass, surrounding,\n                                                  dx,  dy, dq, epsilon);\n                    run(model, ctx);\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "93711763bcc938e6b26b3b90047b36a1e430fa38", "size": 15175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dsde-qss1-fireforrest.cpp", "max_stars_repo_name": "vle-forge/Echll", "max_stars_repo_head_hexsha": "f3895dc721ec891b5828fcd17aec0d37be07fb60", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/dsde-qss1-fireforrest.cpp", "max_issues_repo_name": "vle-forge/Echll", "max_issues_repo_head_hexsha": "f3895dc721ec891b5828fcd17aec0d37be07fb60", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dsde-qss1-fireforrest.cpp", "max_forks_repo_name": "vle-forge/Echll", "max_forks_repo_head_hexsha": "f3895dc721ec891b5828fcd17aec0d37be07fb60", "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.0246636771, "max_line_length": 88, "alphanum_fraction": 0.5021416804, "num_tokens": 3846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624163, "lm_q2_score": 0.03410042914796971, "lm_q1q2_score": 0.015061238535016187}}
{"text": "#include <boost/config.hpp>\n#include <iostream>\n#include <fstream>\n\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\nusing namespace boost;\n\n\n#define LINEMAX 1024\n//get a line from file, return -1 if failed\n// lineptr is the line string, it is allocated inside but need to be free outside\n// n is the number of chars in string(not includ the last \"\\0\")\nint mygetline(char** lineptr, size_t* n, FILE* stream)\n{\n    char* buffer = *lineptr;\n    char* relocate_buffer = buffer;\n\n    buffer = static_cast<char *>(malloc(LINEMAX + 1));\n\n    if (buffer == NULL)\n    {\n        printf(\"allocate memory failed in getline!\\n\");\n        return -1;\n    }\n    size_t linemax = LINEMAX + 1;\n    size_t numread = 0;\n    char c;\n    while (numread< linemax)\n    {\n        c = (char)fgetc(stdin);\n        if (c == EOF)break;// end of file\n        buffer[numread] = c;\n        numread++;\n        if (c == '\\n')// end of line\n            break;\n        if (numread == linemax-1) {\n            //try to extend memory to 2 times\n            relocate_buffer = static_cast<char *>(realloc(buffer, 2 * linemax));\n            if (relocate_buffer == NULL) {\n                free(buffer);\n                printf(\"Error when extend memory in getline!\\n\");\n                return -1;\n            }else {\n                buffer = relocate_buffer;\n                linemax *= 2;\n            }\n        }\n\n    }\n    buffer[numread] = '\\0';\n    *lineptr = buffer;\n    *n = numread;\n    return 0;\n}\n\n\n\n\n//parse adjacency matrix,read a line string, get the a row of matrix, return the number of column\n// return -1 if failed. if the char is 'x' the value in matrix will be -1\n// the matrx_row_ptr must be already allocated;\nint ParseWeight(char* lineptr, int* matrx_row) {\n    size_t offset = 0;// line str parse offset\n    size_t conlumn = 0; //conlumn index of this row\n    while (lineptr[offset] != '\\n')\n    {\n        if (lineptr[offset] == ' ')\n        {\n            offset++;\n            continue;\n        }\n\n        if (lineptr[offset] == 'x')\n        {\n            offset++; // update str offset\n            //do something\n            // /*Debug*/printf(\"%c\\n\", 'x');\n            matrx_row[conlumn] = -1;\n            conlumn++;// update conlumn index\n            continue;\n        }\n        char* nextchar;\n        int weight = (int)strtol(&lineptr[offset], &nextchar, 10);// try to get the number\n        if (weight == 0) {\n            perror(\"ParseWeight failed!\\n\");\n            return -1; }// farse failed\n        offset = nextchar - lineptr;// update offset\n\n        ///*Debug*/printf(\"%d\\n\", weight);\n        matrx_row[conlumn] = weight;\n        conlumn++;// update conlumn index\n    }\n    return conlumn;\n}\n\n\n\nint main(int, char*[])\n{\n\n    char* lineptr = NULL;\n    size_t linelength = 0;\n    //read number of cities\n    int rt = -1;\n    rt=mygetline(&lineptr, &linelength, stdin);\n    if (rt == -1)\n    {\n        printf(\"Read number of city failed!\");\n        return -1;\n    }\n    char* nextchar;\n    int ncity = (int)strtol(lineptr, &nextchar, 10);// try to get the number\n    free(lineptr);\n    if( ncity < 1) {\n        printf(\"INPUT ERROR, please input city number N first\\n\");\n        return -1;\n    }\n\n    // now read the adjacency matrix(should be n-1 lines)\n\n    //adjacency matrix\n    int** adj_matrix = static_cast<int **>(malloc(sizeof(int *) * (ncity - 1)));\n    if (adj_matrix == NULL) {\n        perror(\"Adjacency matrix allocation failed!\\n\");\n        return -1;\n    }\n\n    for (int i = 0; i < ncity-1; i++)\n    {\n        //printf(\"int i: %d \",i);\n        rt=mygetline(&lineptr, &linelength, stdin);\n        if (rt == -1)\n        {\n            printf(\"Read adjacency lines failed!\");\n            return -1;\n        }\n        // allocate memory for adj_matrix[i]\n        adj_matrix[i] = static_cast<int *>(malloc(sizeof(int) * (i + 1)));\n        if (adj_matrix[i] == NULL) {\n            printf(\"Adjacency matrix row %d allocation failed!\\n\", i);\n            return -1;\n        }\n\n        rt=ParseWeight(lineptr, adj_matrix[i]);\n        if (rt==-1)\n        {\n            printf(\"Adjacency matrix row %d ParseWeight failed!\\n\", i);\n            return -1;\n        }\n        free(lineptr);//lineptr allocated inside getline\n    }\n\n\n\n\n\n\n\n\n    typedef adjacency_list< listS, vecS, undirectedS, no_property,\n            property< edge_weight_t, int > >\n            graph_t;\n    typedef graph_traits< graph_t >::vertex_descriptor vertex_descriptor;\n    typedef std::pair< int, int > Edge;\n\n\n    std::vector<Edge> edge_array;\n    std::vector<int> weights;\n    // add edges\n    for (int irow = 0; irow < ncity-1; irow++)\n    {\n        for (int jcol = 0; jcol <= irow; jcol++)\n        {\n            if(adj_matrix[irow][jcol]==-1)continue;\n            edge_array.emplace_back(irow + 1, jcol);\n            weights.push_back(adj_matrix[irow][jcol]);\n\n            /*// add w->v too, as we can reach cities from both directions\n            edge_array.emplace_back(jcol, irow+1);\n            weights.push_back(adj_matrix[irow][jcol]);*/\n\n            ///*debug*/printf(\"%d--%d-->%d......%d--%d-->%d\\n\", irow+1, adj_matrix[irow][jcol], jcol, jcol,\n            //               adj_matrix[irow][jcol], irow+1);\n        }\n    }\n\n\n    int num_arcs = edge_array.size();\n    graph_t g(edge_array.data(), edge_array.data()+num_arcs, weights.data(), ncity);\n    property_map< graph_t, edge_weight_t >::type weightmap\n            = get(edge_weight, g);\n    std::vector< vertex_descriptor > p(num_vertices(g));\n    std::vector< int > d(num_vertices(g));\n    vertex_descriptor s = vertex(0, g);\n\n    /*dijkstra_shortest_paths(g, s,\n                            predecessor_map(boost::make_iterator_property_map(\n                                    p.begin(), get(boost::vertex_index, g)))\n                                    .distance_map(boost::make_iterator_property_map(\n                                            d.begin(), get(boost::vertex_index, g))));*/\n\n    dijkstra_shortest_paths(g, s,\n                            distance_map(boost::make_iterator_property_map(\n                                            d.begin(), get(boost::vertex_index, g))));\n\n    //std::cout << \"distances and parents:\" << std::endl;\n    graph_traits< graph_t >::vertex_iterator vi, vend;\n    std::vector<int> dist[100];\n    /*for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi)\n    {\n        std::cout << \"distance(\" << *vi << \") = \" << d[*vi] << \", \";\n        std::cout << \"parent(\" << *vi << \") = \" << p[*vi]\n                  << std::endl;\n    }*/\n    auto max=*std::max_element(d.begin(),d.end());\n    std::cout << max << std::endl;\n\n\n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "bfc25743c36ab7094568ae7a033cb5c778d4db13", "size": 6752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/boost-graph/main.cpp", "max_stars_repo_name": "eddyxzc/shortest-path-tree", "max_stars_repo_head_hexsha": "de11bc7d9c7c262f50bb8cc6d4e197d1d0d9ef98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/boost-graph/main.cpp", "max_issues_repo_name": "eddyxzc/shortest-path-tree", "max_issues_repo_head_hexsha": "de11bc7d9c7c262f50bb8cc6d4e197d1d0d9ef98", "max_issues_repo_licenses": ["MIT"], "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/boost-graph/main.cpp", "max_forks_repo_name": "eddyxzc/shortest-path-tree", "max_forks_repo_head_hexsha": "de11bc7d9c7c262f50bb8cc6d4e197d1d0d9ef98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1428571429, "max_line_length": 107, "alphanum_fraction": 0.5426540284, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.033085978507880996, "lm_q1q2_score": 0.014996611761879488}}
{"text": "#include \"itkTractsToVectorImageFilter.h\"\n\n// VTK\n#include <vtkPolyLine.h>\n#include <vtkCellArray.h>\n#include <vtkCellData.h>\n\n// ITK\n#include <itkTimeProbe.h>\n#include <itkImageRegionIterator.h>\n\n// misc\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <boost/progress.hpp>\n#include <mitkDiffusionFunctionCollection.h>\n\nnamespace itk{\n\nstatic inline bool CompareVectorLengths(const vnl_vector_fixed< double, 3 >& v1, const vnl_vector_fixed< double, 3 >& v2)\n{\n  return (v1.magnitude()>v2.magnitude());\n}\n\ntemplate< class PixelType >\nTractsToVectorImageFilter< PixelType >::TractsToVectorImageFilter():\n  m_NormalizationMethod(GLOBAL_MAX),\n  m_AngularThreshold(0.7),\n  m_Epsilon(0.999),\n  m_MaxNumDirections(3),\n  m_SizeThreshold(0.3),\n  m_OnlyUseMaskGeometry(false)\n{\n  this->SetNumberOfRequiredOutputs(1);\n}\n\n\ntemplate< class PixelType >\nTractsToVectorImageFilter< PixelType >::~TractsToVectorImageFilter()\n{\n}\n\n\ntemplate< class PixelType >\nvnl_vector_fixed<double, 3> TractsToVectorImageFilter< PixelType >::GetVnlVector(double point[])\n{\n  vnl_vector_fixed<double, 3> vnlVector;\n  vnlVector[0] = point[0];\n  vnlVector[1] = point[1];\n  vnlVector[2] = point[2];\n  return vnlVector;\n}\n\ntemplate< class PixelType >\nvoid TractsToVectorImageFilter< PixelType >::GenerateData()\n{\n  mitk::BaseGeometry::Pointer geometry = m_FiberBundle->GetGeometry();\n\n  // calculate new image parameters\n  itk::Vector<double> spacing3;\n  itk::Point<double> origin3;\n  itk::Matrix<double, 3, 3> direction3;\n  ImageRegion<3> imageRegion3;\n  if (!m_MaskImage.IsNull())\n  {\n    spacing3 = m_MaskImage->GetSpacing();\n    imageRegion3 = m_MaskImage->GetLargestPossibleRegion();\n    origin3 = m_MaskImage->GetOrigin();\n    direction3 = m_MaskImage->GetDirection();\n  }\n  else\n  {\n    spacing3 = geometry->GetSpacing();\n    origin3 = geometry->GetOrigin();\n    mitk::BaseGeometry::BoundsArrayType bounds = geometry->GetBounds();\n    origin3[0] += bounds.GetElement(0);\n    origin3[1] += bounds.GetElement(2);\n    origin3[2] += bounds.GetElement(4);\n\n    for (int i=0; i<3; i++)\n      for (int j=0; j<3; j++)\n        direction3[j][i] = geometry->GetMatrixColumn(i)[j];\n    imageRegion3.SetSize(0, geometry->GetExtent(0)+1);\n    imageRegion3.SetSize(1, geometry->GetExtent(1)+1);\n    imageRegion3.SetSize(2, geometry->GetExtent(2)+1);\n\n\n    m_MaskImage = ItkUcharImgType::New();\n    m_MaskImage->SetSpacing( spacing3 );\n    m_MaskImage->SetOrigin( origin3 );\n    m_MaskImage->SetDirection( direction3 );\n    m_MaskImage->SetRegions( imageRegion3 );\n    m_MaskImage->Allocate();\n    m_MaskImage->FillBuffer(1);\n  }\n  OutputImageType::RegionType::SizeType outImageSize = imageRegion3.GetSize();\n  m_OutImageSpacing = m_MaskImage->GetSpacing();\n  m_ClusteredDirectionsContainer = ContainerType::New();\n\n  // initialize num directions image\n  m_NumDirectionsImage = ItkUcharImgType::New();\n  m_NumDirectionsImage->SetSpacing( spacing3 );\n  m_NumDirectionsImage->SetOrigin( origin3 );\n  m_NumDirectionsImage->SetDirection( direction3 );\n  m_NumDirectionsImage->SetRegions( imageRegion3 );\n  m_NumDirectionsImage->Allocate();\n  m_NumDirectionsImage->FillBuffer(0);\n\n  itk::Vector<double, 4> spacing4;\n  itk::Point<float, 4> origin4;\n  itk::Matrix<double, 4, 4> direction4;\n  itk::ImageRegion<4> imageRegion4;\n\n  spacing4[0] = spacing3[0]; spacing4[1] = spacing3[1]; spacing4[2] = spacing3[2]; spacing4[3] = 1;\n  origin4[0] = origin3[0]; origin4[1] = origin3[1]; origin4[2] = origin3[2]; origin3[3] = 0;\n  for (int r=0; r<3; r++)\n    for (int c=0; c<3; c++)\n      direction4[r][c] = direction3[r][c];\n  direction4[3][3] = 1;\n  imageRegion4.SetSize(0, imageRegion3.GetSize()[0]);\n  imageRegion4.SetSize(1, imageRegion3.GetSize()[1]);\n  imageRegion4.SetSize(2, imageRegion3.GetSize()[2]);\n  imageRegion4.SetSize(3, m_MaxNumDirections*3);\n\n  m_DirectionImage = ItkDirectionImageType::New();\n  m_DirectionImage->SetSpacing( spacing4 );\n  m_DirectionImage->SetOrigin( origin4 );\n  m_DirectionImage->SetDirection( direction4 );\n  m_DirectionImage->SetRegions( imageRegion4 );\n  m_DirectionImage->Allocate();\n  m_DirectionImage->FillBuffer(0.0);\n\n  // iterate over all fibers\n  vtkSmartPointer<vtkPolyData> fiberPolyData = m_FiberBundle->GetFiberPolyData();\n  int numFibers = m_FiberBundle->GetNumFibers();\n  m_DirectionsContainer = ContainerType::New();\n\n  VectorContainer< unsigned int, std::vector< double > >::Pointer peakLengths = VectorContainer< unsigned int, std::vector< double > >::New();\n\n  MITK_INFO << \"Generating directions from tractogram\";\n  boost::progress_display disp(numFibers);\n  for( int i=0; i<numFibers; i++ )\n  {\n    ++disp;\n    vtkCell* cell = fiberPolyData->GetCell(i);\n    int numPoints = cell->GetNumberOfPoints();\n    vtkPoints* points = cell->GetPoints();\n    if (numPoints<2)\n      continue;\n\n    vnl_vector_fixed<double, 3> dir;\n    vnl_vector<double> v;\n\n    float fiberWeight = m_FiberBundle->GetFiberWeight(i);\n\n    for( int j=0; j<numPoints-1; j++)\n    {\n      itk::Point<float, 3> startVertex = mitk::imv::GetItkPoint(points->GetPoint(j));\n      itk::Index<3> startIndex;\n      itk::ContinuousIndex<float, 3> startIndexCont;\n      m_MaskImage->TransformPhysicalPointToIndex(startVertex, startIndex);\n      m_MaskImage->TransformPhysicalPointToContinuousIndex(startVertex, startIndexCont);\n\n      itk::Point<float, 3> endVertex = mitk::imv::GetItkPoint(points->GetPoint(j + 1));\n      itk::Index<3> endIndex;\n      itk::ContinuousIndex<float, 3> endIndexCont;\n      m_MaskImage->TransformPhysicalPointToIndex(endVertex, endIndex);\n      m_MaskImage->TransformPhysicalPointToContinuousIndex(endVertex, endIndexCont);\n\n      dir[0] = endVertex[0]-startVertex[0];\n      dir[1] = endVertex[1]-startVertex[1];\n      dir[2] = endVertex[2]-startVertex[2];\n      if (dir.is_zero())\n        continue;\n      dir.normalize();\n\n      std::vector< std::pair< itk::Index<3>, double > > segments = mitk::imv::IntersectImage(spacing3, startIndex, endIndex, startIndexCont, endIndexCont);\n      for (std::pair< itk::Index<3>, double > segment : segments)\n      {\n        if (!m_MaskImage->GetLargestPossibleRegion().IsInside(segment.first) || (!m_OnlyUseMaskGeometry && m_MaskImage->GetPixel(segment.first)==0))\n          continue;\n\n        // add direction to container\n        unsigned int idx = segment.first[0] + outImageSize[0]*(segment.first[1] + outImageSize[1]*segment.first[2]);\n        DirectionContainerType::Pointer dirCont;\n        if (m_DirectionsContainer->IndexExists(idx))\n        {\n          peakLengths->ElementAt(idx).push_back(fiberWeight*segment.second);\n\n          dirCont = m_DirectionsContainer->GetElement(idx);\n          if (dirCont.IsNull())\n          {\n            dirCont = DirectionContainerType::New();\n            dirCont->push_back(dir);\n            m_DirectionsContainer->InsertElement(idx, dirCont);\n          }\n          else\n            dirCont->push_back(dir);\n        }\n        else\n        {\n          dirCont = DirectionContainerType::New();\n          dirCont->push_back(dir);\n          m_DirectionsContainer->InsertElement(idx, dirCont);\n\n          std::vector< double > lengths; lengths.push_back(fiberWeight*segment.second);\n          peakLengths->InsertElement(idx, lengths);\n        }\n      }\n\n    }\n  }\n\n  itk::ImageRegionIterator<ItkUcharImgType> dirIt(m_NumDirectionsImage, m_NumDirectionsImage->GetLargestPossibleRegion());\n\n  MITK_INFO << \"Clustering directions\";\n  float max_dir_mag = 0;\n  boost::progress_display disp2(outImageSize[0]*outImageSize[1]*outImageSize[2]);\n  while(!dirIt.IsAtEnd())\n  {\n    ++disp2;\n    OutputImageType::IndexType idx3 = dirIt.GetIndex();\n    int idx_lin = idx3[0]+(idx3[1]+idx3[2]*outImageSize[1])*outImageSize[0];\n\n    itk::Index<4> idx4; idx4[0] = idx3[0]; idx4[1] = idx3[1]; idx4[2] = idx3[2];\n\n    if (!m_DirectionsContainer->IndexExists(idx_lin))\n    {\n      ++dirIt;\n      continue;\n    }\n    DirectionContainerType::Pointer dirCont = m_DirectionsContainer->GetElement(idx_lin);\n    if (dirCont.IsNull() || dirCont->empty())\n    {\n      ++dirIt;\n      continue;\n    }\n\n    DirectionContainerType::Pointer directions;\n    if (m_MaxNumDirections>0)\n    {\n      directions = FastClustering(dirCont, peakLengths->GetElement(idx_lin));\n      std::sort( directions->begin(), directions->end(), CompareVectorLengths );\n    }\n    else\n      directions = dirCont;\n\n    unsigned int numDir = directions->size();\n    if (m_MaxNumDirections>0 && numDir>m_MaxNumDirections)\n      numDir = m_MaxNumDirections;\n\n    float voxel_max_mag = 0;\n    for (unsigned int i=0; i<numDir; i++)\n    {\n      DirectionType dir = directions->at(i);\n      float mag = dir.magnitude();\n\n      if (mag>voxel_max_mag)\n        voxel_max_mag = mag;\n      if (mag>max_dir_mag)\n        max_dir_mag = mag;\n    }\n\n    int count = 0;\n    for (unsigned int i=0; i<numDir; i++)\n    {\n      DirectionType dir = directions->at(i);\n      count++;\n\n      float mag = dir.magnitude();\n      if (m_NormalizationMethod==MAX_VEC_NORM && voxel_max_mag>mitk::eps)\n        dir /= voxel_max_mag;\n      else if (m_NormalizationMethod==SINGLE_VEC_NORM && mag>mitk::eps)\n        dir.normalize();\n\n      for (unsigned int j = 0; j<3; j++)\n      {\n        idx4[3] = i*3 + j;\n        m_DirectionImage->SetPixel(idx4, dir[j]);\n      }\n    }\n    dirIt.Set(count);\n    ++dirIt;\n  }\n\n  if (m_NormalizationMethod==GLOBAL_MAX && max_dir_mag>0)\n  {\n    itk::ImageRegionIterator<ItkDirectionImageType> dirImgIt(m_DirectionImage, m_DirectionImage->GetLargestPossibleRegion());\n    while(!dirImgIt.IsAtEnd())\n    {\n      dirImgIt.Set(dirImgIt.Get()/max_dir_mag);\n      ++dirImgIt;\n    }\n  }\n}\n\n\ntemplate< class PixelType >\nTractsToVectorImageFilter< PixelType >::DirectionContainerType::Pointer TractsToVectorImageFilter< PixelType >::FastClustering(DirectionContainerType::Pointer inDirs, std::vector< double > lengths)\n{\n  DirectionContainerType::Pointer outDirs = DirectionContainerType::New();\n  if (inDirs->size()<2)\n  {\n    if (inDirs->size()==1)\n      inDirs->SetElement(0, inDirs->at(0)*lengths.at(0));\n    return inDirs;\n  }\n\n  DirectionType oldMean, currentMean;\n  std::vector< int > touched;\n\n  // initialize\n  touched.resize(inDirs->size(), 0);\n  bool free = true;\n  currentMean = inDirs->at(0);  // initialize first seed\n  currentMean.normalize();\n  double length = lengths.at(0);\n  touched[0] = 1;\n  std::vector< double > newLengths;\n  bool meanChanged = false;\n\n  double max = 0;\n  while (free)\n  {\n    oldMean.fill(0.0);\n\n    // start mean-shift clustering\n    double angle = 0;\n\n    while (fabs(dot_product(currentMean, oldMean))<0.99)\n    {\n      oldMean = currentMean;\n      currentMean.fill(0.0);\n      for (unsigned int i=0; i<inDirs->size(); i++)\n      {\n        angle = dot_product(oldMean, inDirs->at(i));\n        if (angle>=m_AngularThreshold)\n        {\n          currentMean += inDirs->at(i);\n          if (meanChanged)\n            length += lengths.at(i);\n          touched[i] = 1;\n          meanChanged = true;\n        }\n        else if (-angle>=m_AngularThreshold)\n        {\n          currentMean -= inDirs->at(i);\n          if (meanChanged)\n            length += lengths.at(i);\n          touched[i] = 1;\n          meanChanged = true;\n        }\n      }\n      if(!meanChanged)\n        currentMean = oldMean;\n      else\n        currentMean.normalize();\n    }\n\n    // found stable mean\n    outDirs->push_back(currentMean);\n    newLengths.push_back(length);\n    if (length>max)\n      max = length;\n\n    // find next unused seed\n    free = false;\n    for (unsigned int i=0; i<touched.size(); i++)\n      if (touched[i]==0)\n      {\n        currentMean = inDirs->at(i);\n        free = true;\n        meanChanged = false;\n        length = lengths.at(i);\n        touched[i] = 1;\n        break;\n      }\n  }\n\n  if (inDirs->size()==outDirs->size())\n  {\n    if (max>0)\n    {\n      for (unsigned int i=0; i<outDirs->size(); i++)\n        outDirs->SetElement(i, outDirs->at(i)*newLengths.at(i));\n    }\n    return outDirs;\n  }\n  else\n    return FastClustering(outDirs, newLengths);\n}\n\n}\n\n\n\n", "meta": {"hexsha": "091edea23431a7a7a05ff86474b145d70ddcdeda", "size": 11999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/FiberTracking/Algorithms/itkTractsToVectorImageFilter.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/FiberTracking/Algorithms/itkTractsToVectorImageFilter.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/FiberTracking/Algorithms/itkTractsToVectorImageFilter.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": 30.2241813602, "max_line_length": 197, "alphanum_fraction": 0.6597216435, "num_tokens": 3385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.030214584775092625, "lm_q1q2_score": 0.01498926906694944}}
{"text": "#include \"factor_graph_initializer.h\"\n#include \"srrg_solver/variables_and_factors/types_2d/all_types.h\"\n#include \"srrg_solver/variables_and_factors/types_3d/all_types.h\"\n#include \"srrg_solver/variables_and_factors/types_projective/all_types.h\"\n#include <Eigen/Eigenvalues>\n\nnamespace srrg2_solver {\n\n  void FactorGraphInitializer::setGraph(FactorGraphInterface& graph_) {\n    _graph = &graph_;\n    _entries.clear();\n    _initialized_variables.clear();\n    _queue = FactorGraphVisitEntryQueue();\n    // populate the entry structure to hold the visit\n    // populate the queue with all fixed variables\n    for (auto it = _graph->variables().begin(); it != _graph->variables().end(); ++it) {\n      VariableBase* variable    = it.value();\n      if (variable->status() == VariableBase::NonActive)\n        continue;\n      VariableVisitEntry* entry = _entries.add(VariableVisitEntry(variable));\n      if (variable->status() == VariableBase::Fixed) {\n        entry->cost = 0;\n        if (! _parameter_ids.count(variable->graphId()))\n          _queue.push(*entry);\n        _initialized_variables.insert(variable->graphId());\n      } else {\n        entry->cost = -1;\n      }\n    }\n    if (verbose)\n      std::cerr << \"queue.size()\" << _queue.size() << std::endl;\n  }\n\n  float FactorGraphInitializer::getCost(VariableBase* v) {\n    VariableVisitEntry* ne = _entries.at(v->graphId());\n    if (! ne)\n      throw std::runtime_error(\"getCost on non visited variable\");\n    std::set<VariableBase*> neighbors;\n    for (auto f_it: _graph->factors(ne->variable)) {\n      FactorBase* f=f_it.second;\n      if (! f->enabled())\n        continue;\n      if (param_level.value()!=-1 && f->level()!=param_level.value())\n        continue;\n      for (int i=0; i<f->numVariables(); ++i) {\n        int v_id=f->variableId(i);\n        if (_parameter_ids.count(v_id))\n          continue;\n        VariableBase* v_other=_graph->variable(v_id);\n        neighbors.insert(v_other);\n      }\n    }\n    float min_cost=std::numeric_limits<float>::max();\n    for (auto v_other: neighbors) {\n      VariableVisitEntry* e_other=_entries.at(v_other->graphId());\n      if (! e_other)\n        continue;\n      if (e_other->cost<0)\n        continue;\n      min_cost=std::min(e_other->cost, min_cost);\n    }\n    return min_cost;\n  }\n\n  void FactorGraphInitializer::updateGraph() {\n    // populate the queue with all variables that are fixed\n    // and all the ones that were not in the graph before\n    _queue = FactorGraphVisitEntryQueue();\n    for (auto it = _graph->variables().begin(); it != _graph->variables().end(); ++it) {\n      VariableBase* variable    = it.value();\n      if (variable->status() == VariableBase::NonActive) \n        continue;\n      VariableVisitEntry* entry = _entries.at(variable->graphId());\n      if (! entry) {\n        entry = _entries.add(VariableVisitEntry(variable));\n        if (variable->status() == VariableBase::Fixed) {\n          entry->cost = 0;\n          _initialized_variables.insert(variable->graphId());\n          if (! _parameter_ids.count(variable->graphId()))\n              _queue.push(*entry);\n        } else {\n          entry->cost=-1;\n        }\n      } else {\n        _queue.push(*entry);\n      }\n        \n    }\n    //std::cerr << \"queue.size()\" << _queue.size() << std::endl;\n  }\n  using namespace std;\n  \n  void FactorGraphInitializer::compute() {\n    if (verbose) \n      cerr << \"init [ \";\n    while (!_queue.empty()) {\n      VariableVisitEntry e = _queue.top();\n      VariableVisitEntry* e_other=_entries.at(e.variable->graphId());\n      if (verbose ) std::cerr << \"pop: \" << e.variable->graphId() << \" \" << e.cost << std::endl;\n      _queue.pop();\n      if (e_other->cost<e.cost)\n        continue;\n      if (param_max_cost.value()>-1 && e.cost>param_max_cost.value())\n        return;\n      VariableBase* v = e.variable;\n      if (! _graph->variable(v->graphId()))\n          throw std::runtime_error(\"FactorGraphInitializer, bookkeping error\");\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        int v_pos          = -1;\n        FactorBase* f = f_it.second;\n        if (! f->enabled()) {\n          continue;\n        }\n        for (int i = 0; i < f->numVariables(); ++i) {\n          if (f->variable(i) == v) {\n            e.var_pos = i;\n            v_pos      = i;\n            break;\n          }\n        }\n\n        // scan all variables\n        for (int nv_pos = 0; nv_pos < f->numVariables(); ++nv_pos) {\n          if (nv_pos == v_pos)\n            continue;\n          VariableBase* nv       = f->variable(nv_pos);\n          if (_parameter_ids.count(nv->graphId()))\n            continue;\n\n          VariableVisitEntry* ne = _entries.at(nv->graphId());\n          //std::cerr << \"\\t nv:\" << nv->graphId() << std::endl;\n          //std::cerr << \"ne: \" << ne << std::endl;\n          if (! ne)\n            continue;\n          \n          //assert(ne && \"bookkeeping error 2\");\n          // if variable already initialized\n          if (ne->cost >= 0)\n            continue;\n          if (initVariable(nv)) {\n            if (verbose) {\n              cerr << \"(\" << v->graphId() << \"-\" << nv->graphId() << \") \" ;\n            }\n            _initialized_variables.insert(nv->graphId());\n            //ne->cost = e.cost + 1;\n            ne->cost = getCost(nv) + 1;\n            _queue.push(*ne);\n            //std::cerr << \"push: \" << ne->variable->graphId() << \" \" << ne->cost << std::endl;\n          }\n        }\n      }\n    }\n    if (verbose) \n      cerr << \"]\";\n  }\n\n  bool FactorGraphInitializer::initVariable(VariableBase* variable) {\n    for (auto it = _rules.begin(); it != _rules.end(); ++it) {\n      if ((*it)->init(variable))\n        return true;\n    }\n    return false;\n  }\n\n  bool FactorGraphInitializer::isInit(VariableBase* v) {\n    VariableVisitEntry* ne = _entries.at(v->graphId());\n    if (! ne)\n      return false;\n    return ne->cost >= 0;\n  }\n\n  float FactorGraphInitializer::maxCost() {\n    float max_cost=-1;\n    for (auto v_id: _initialized_variables) {\n      auto entry=_entries.at(v_id);\n      if (! entry)\n        continue;\n      max_cost=std::max(entry->cost, max_cost);\n    }\n    return max_cost;\n  }\n\n  struct SE2toSE2InitializerRule : public FactorGraphInitializerRule_<VariableSE2Base> {\n    SE2toSE2InitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariableSE2Base>(initializer_) {\n    }\n\n    bool doInit(VariableSE2Base* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        \n        SE2PosePoseGeodesicErrorFactor* this_factor =\n          dynamic_cast<SE2PosePoseGeodesicErrorFactor*>(f);\n        if (!this_factor)\n          continue;\n        bool direct             = true;\n        VariableSE2Base* root_v = this_factor->variables().at<0>();\n        if (root_v == v) {\n          root_v = this_factor->variables().at<1>();\n          direct = false;\n        }\n        if (!_initializer->isInit(root_v))\n          continue;\n\n        if (direct) {\n          v->setEstimate(root_v->estimate() * this_factor->measurement());\n        } else {\n          v->setEstimate(root_v->estimate() * this_factor->measurement().inverse());\n        }\n        //std::cerr << \"se2 pose_pose init\" << root_v->graphId() << \" \" << v->graphId() << std::endl;\n        return true;\n      }\n      return false;\n    }\n  };\n\n  struct SE2toPoint2InitializerRule : public FactorGraphInitializerRule_<VariablePoint2> {\n    SE2toPoint2InitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariablePoint2>(initializer_) {\n    }\n\n    bool doInit(VariablePoint2* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        SE2PosePointErrorFactor* this_factor =\n          dynamic_cast<SE2PosePointErrorFactor*>(f);\n        if (!this_factor) {\n          continue;\n        }\n        VariableSE2Base* root_v = this_factor->variables().at<0>();\n        if (!_initializer->isInit(root_v))\n          continue;\n        v->setEstimate(root_v->estimate() * this_factor->measurement());\n        //std::cerr << \"se2 pose_point init\" << root_v->graphId() << \" \" << v->graphId() << std::endl;\n        return true;\n      }\n      return false;\n    }\n  };\n\n  struct SE2toPoint2BearingInitializerRule : public FactorGraphInitializerRule_<VariablePoint2> {\n    SE2toPoint2BearingInitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariablePoint2>(initializer_) {\n    }\n\n    bool doInit(VariablePoint2* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n      std::list<SE2PosePointBearingErrorFactor*> active_factors;\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        SE2PosePointBearingErrorFactor* this_factor =\n          dynamic_cast<SE2PosePointBearingErrorFactor*>(f);\n        if (!this_factor) {\n          continue;\n        }\n        VariableSE2Base* root_v = this_factor->variables().at<0>();\n        if (!_initializer->isInit(root_v))\n          continue;\n        active_factors.push_back(this_factor);\n      }\n      if (active_factors.size() < 2)\n        return false;\n      // do a triangulation with the factors\n      Matrix2f H = Matrix2f::Zero();\n      Vector2f b = Vector2f::Zero();\n      Vector2f x = v->estimate();\n      for (auto it = active_factors.begin(); it != active_factors.end(); ++it) {\n        SE2PosePointBearingErrorFactor* f = *it;\n        VariableSE2Base* pose                    = f->variables().at<0>();\n        float theta                              = f->measurement()(0);\n        Vector2f n        = pose->estimate().linear() * Vector2f(cos(theta), sin(theta));\n        n                 = Vector2f(n.y(), -n.x());\n        const Vector2f& p = pose->estimate().translation();\n        float e           = n.dot(x - p);\n        H += n * n.transpose();\n        b += n * e;\n      }\n      x -= (H).ldlt().solve(b);\n      v->setEstimate(x);\n      // todo: check for consistency of solution, otherwise disable variable\n      //std::cerr << \"se2 pose point bearinf :\" << x.transpose() << std::endl;\n      return true;\n    }\n  };\n\n  struct SE3toSE3InitializerRule : public FactorGraphInitializerRule_<VariableSE3Base> {\n    SE3toSE3InitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariableSE3Base>(initializer_) {\n    }\n\n    bool doInit(VariableSE3Base* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        SE3PosePoseGeodesicErrorFactor* this_factor =\n          dynamic_cast<SE3PosePoseGeodesicErrorFactor*>(f);\n        if (!this_factor)\n          continue;\n        bool direct             = true;\n        VariableSE3Base* root_v = this_factor->variables().at<0>();\n        if (root_v == v) {\n          root_v = this_factor->variables().at<1>();\n          direct = false;\n        }\n        if (!_initializer->isInit(root_v))\n          continue;\n\n        if (direct) {\n          v->setEstimate(root_v->estimate() * this_factor->measurement());\n        } else {\n          v->setEstimate(root_v->estimate() * this_factor->measurement().inverse());\n        }\n        //std::cerr << \"se3 pose_pose init\" << root_v->graphId() << \" \" << v->graphId() << std::endl;\n        return true;\n      }\n      return false;\n    }\n  };\n\n  struct Sim3toSim3InitializerRule : public FactorGraphInitializerRule_<VariableSim3Base> {\n    Sim3toSim3InitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariableSim3Base>(initializer_) {\n    }\n\n    bool doInit(VariableSim3Base* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        Sim3PosePoseErrorFactorAD* this_factor =\n          dynamic_cast<Sim3PosePoseErrorFactorAD*>(f);\n        if (!this_factor)\n          continue;\n        bool direct             = true;\n        VariableSim3Base* root_v = this_factor->variables().at<0>();\n        if (root_v == v) {\n          root_v = this_factor->variables().at<1>();\n          direct = false;\n        }\n        if (!_initializer->isInit(root_v))\n          continue;\n\n        if (direct) {\n          v->setEstimate(root_v->estimate() * this_factor->measurement());\n        } else {\n          v->setEstimate(root_v->estimate() * this_factor->measurement().inverse());\n        }\n        //std::cerr << \"se3 pose_pose init\" << root_v->graphId() << \" \" << v->graphId() << std::endl;\n        return true;\n      }\n      return false;\n    }\n  };\n\n  struct SE3toPoint3InitializerRule : public FactorGraphInitializerRule_<VariablePoint3> {\n    SE3toPoint3InitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariablePoint3>(initializer_) {\n    }\n\n    bool doInit(VariablePoint3* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n        for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n\n        if (level!=-1 && f->level()!=level)\n          continue;\n        SE3PosePointErrorFactor* this_factor =\n          dynamic_cast<SE3PosePointErrorFactor*>(f);\n        if (!this_factor)\n          continue;\n        VariableSE3Base* root_v = this_factor->variables().at<0>();\n        if (!_initializer->isInit(root_v))\n          continue;\n        v->setEstimate(root_v->estimate() * this_factor->measurement());\n        //std::cerr << \"se3 pose_point init\" << root_v->graphId() << \" \" << v->graphId() << std::endl;\n        return true;\n      }\n      return false;\n    }\n  };\n\n  struct SE3toPoint3OffsetInitializerRule : public FactorGraphInitializerRule_<VariablePoint3> {\n    SE3toPoint3OffsetInitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariablePoint3>(initializer_) {\n    }\n\n    bool doInit(VariablePoint3* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        SE3PosePointOffsetErrorFactor* this_factor =\n          dynamic_cast<SE3PosePointOffsetErrorFactor*>(f);\n        if (!this_factor)\n          continue;\n        VariableSE3Base* offset_v = this_factor->variables().at<2>();\n        if (!_initializer->isInit(offset_v))\n          continue;\n        VariableSE3Base* root_v = this_factor->variables().at<0>();\n        if (!_initializer->isInit(root_v))\n          continue;\n\n        v->setEstimate(root_v->estimate() * offset_v->estimate() * this_factor->measurement());\n        //std::cerr << \"se3 pose_point_offset init\" << root_v->graphId() << \" \" << v->graphId() << std::endl;\n        return true;\n      }\n      return false;\n    }\n  };\n\n\n  struct SE3toPoint3OmniBAInitializerRule : public FactorGraphInitializerRule_<VariablePoint3> {\n    SE3toPoint3OmniBAInitializerRule(FactorGraphInitializer* initializer_) :\n      FactorGraphInitializerRule_<VariablePoint3>(initializer_) {\n    }\n\n    bool doInit(VariablePoint3* v) override {\n      std::list<SE3PosePointOmniBAErrorFactor*> active_factors;\n      FactorGraphInterface* _graph = _initializer->_graph;\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        SE3PosePointOmniBAErrorFactor* this_factor =\n          dynamic_cast<SE3PosePointOmniBAErrorFactor*>(f);\n        if (!this_factor) {\n          continue;\n        }\n        VariableSE3Base* root_v = this_factor->variables().at<0>();\n        if (!_initializer->isInit(root_v))\n          continue;\n        active_factors.push_back(this_factor);\n      }\n      if (active_factors.size() < 3)\n        return false;\n      // do a triangulation with the factors\n      Matrix3f H = Matrix3f::Zero();\n      Vector3f b = Vector3f::Zero();\n      Vector3f x = v->estimate();\n      for (auto it = active_factors.begin(); it != active_factors.end(); ++it) {\n        SE3PosePointOmniBAErrorFactor* f = *it;\n        VariableSE3Base* pose                    = f->variables().at<0>();\n        VariableSE3Base* offset                  = f->variables().at<2>();\n        Vector3f d        = pose->estimate().linear()*offset->estimate().linear()*f->measurement();\n        Matrix3f J=geometry3d::skew(d);\n        const Vector3f& p = pose->estimate()*offset->estimate().translation();\n        Vector3f e        = J*(x - p);\n        H += J.transpose() * J;\n        b += J.transpose() * e;\n      }\n      x -= (H).ldlt().solve(b);\n      v->setEstimate(x);\n      Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f>  es;\n      es.compute(H);\n      float lambda_min=es.eigenvalues()(0);\n      float lambda_max=es.eigenvalues()(2);\n      if (lambda_min/lambda_max<1e-1)\n        return false;\n      // todo: check for consistency of solution, otherwise disable variable\n      //std::cerr << \"se3 pose point omni ba:\" << x.transpose() << std::endl;\n      return true;\n    }\n  };\n\n    struct Point3toSE3InitializerRule : public FactorGraphInitializerRule_<VariableSE3Base> {\n\n      Point3toSE3InitializerRule(FactorGraphInitializer* initializer_)\n        : FactorGraphInitializerRule_<VariableSE3Base>(initializer_) {\n      }\n\n    bool doInit(VariableSE3Base* v) override {\n      FactorGraphInterface* _graph = _initializer->_graph;\n      std::list<SE3PosePointErrorFactor*> active_factors;\n      for (auto f_it: _graph->FactorGraphInterface::factors(v)) {\n        FactorBase* f = f_it.second;\n        if (level!=-1 && f->level()!=level)\n          continue;\n        SE3PosePointErrorFactor* this_factor =\n          dynamic_cast<SE3PosePointErrorFactor*>(f);\n        if (!this_factor) {\n          continue;\n        }\n        VariablePoint3* root_v = this_factor->variables().at<1>();\n        if (!_initializer->isInit(root_v))\n          continue;\n        active_factors.push_back(this_factor);\n      }\n      if (active_factors.size() < 4)\n        return false;\n      const int iterations=10;\n      //tiny ICP;\n      Matrix6f H;\n      Vector6f b;\n      Vector6f dx;\n      Isometry3f X=v->estimate().inverse();\n      float last_chi =0;\n      //cerr << \"init : [\";\n      for (int i=0; i<iterations; ++i) {\n        last_chi=0;\n        H.setZero();\n        b.setZero();\n        dx.setZero();\n        Matrix3_6f J;\n        J.setZero();\n        J.block<3,3>(0,0).setIdentity();\n        // do a triangulation with the factors\n        for (auto it = active_factors.begin(); it != active_factors.end(); ++it) {\n          auto f = *it;\n          auto p = f->variables().at<1>()->estimate();\n          auto z = f->measurement();\n          auto z_hat=X*p;\n          J.block<3,3>(0,3)=-geometry3d::skew(z_hat);\n          auto e = z_hat-z;\n          H += J.transpose() * f->informationMatrix() * J;\n          b += J.transpose() * f->informationMatrix() * e;\n          last_chi+=e.transpose()*f->informationMatrix()*e;\n        }\n        //cerr << last_chi/active_factors.size() << \" \";\n        dx -= (H).ldlt().solve(b);\n        X=geometry3d::ta2t(dx)*X;\n      }\n      //cerr << \"] \" << endl;\n      \n      Eigen::SelfAdjointEigenSolver<Matrix6f>  es;\n      es.compute(H);\n      float lambda_min=es.eigenvalues()(0);\n      //float lambda_max=es.eigenvalues()(5);\n      if (lambda_min<1e-1) { //gg: sucks big times. more times. can't stop sucking\n        return false;\n      }\n      v->setEstimate(X.inverse());\n      // todo: check for consistency of solution, otherwise disable variable\n      //std::cerr << \"se3 pose point omni ba:\" << x.transpose() << std::endl;\n      //cerr << \"init!\";\n      return true;\n    }\n  };\n\n  FactorGraphInitializer::FactorGraphInitializer() {\n    _rules.push_back(FactorGraphInitializerRulePtr(new SE2toSE2InitializerRule(this)));\n    _rules.push_back(FactorGraphInitializerRulePtr(new SE3toSE3InitializerRule(this)));\n    _rules.push_back(FactorGraphInitializerRulePtr(new Sim3toSim3InitializerRule(this)));\n    _rules.push_back(FactorGraphInitializerRulePtr(new SE2toPoint2InitializerRule(this)));\n    _rules.push_back(FactorGraphInitializerRulePtr(new SE3toPoint3InitializerRule(this)));\n    _rules.push_back(FactorGraphInitializerRulePtr(new SE3toPoint3OffsetInitializerRule(this)));\n    _rules.push_back(FactorGraphInitializerRulePtr(new SE2toPoint2BearingInitializerRule(this)));\n    _rules.push_back(FactorGraphInitializerRulePtr(new SE3toPoint3OmniBAInitializerRule(this))); \n    _rules.push_back(FactorGraphInitializerRulePtr(new Point3toSE3InitializerRule(this)));\n }\n\n} // namespace srrg2_solver\n", "meta": {"hexsha": "d726a88acfc160ffbb93923fefd46b62ce1df86b", "size": 21140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/src/srrg_solver/utils/factor_graph_initializer.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/src/srrg_solver/utils/factor_graph_initializer.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/srrg2_solver/srrg2_solver/src/srrg_solver/utils/factor_graph_initializer.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4159292035, "max_line_length": 109, "alphanum_fraction": 0.601986755, "num_tokens": 5304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.03514484854829155, "lm_q1q2_score": 0.014983008315275444}}
{"text": "#include <boost/asio.hpp>\n#include <boost/asio/ip/tcp.hpp>\n#include <HElib/FHE.h>\n#include <HElib/FHEContext.h>\n#include <HElib/EncryptedArray.h>\n#include <iostream>\n#include <fstream>\n\nvoid run_client() {\n    FHEcontext context(1024, 1031, 1);\n    buildModChain(context, 4);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n    std::ofstream of(\"pk.pk\", std::ios::binary);\n    FHEPubKey pk(sk);\n    // pk.makeSymmetric();\n    of << pk;\n    of.close();\n\n    Ctxt ctx(sk);\n    sk.Encrypt(ctx, NTL::to_ZZX(3));\n\n    using boost::asio::ip::tcp;\n    tcp::iostream connect(\"127.0.0.1\", \"12345\");\n    if (!connect) {\n        std::cerr << \"Can not connect:\" << \n             connect.error().message() << std::endl;\n        return;\n    }\n    writeContextBase(connect, context);\n    connect << context;\n    connect << ctx;\n    connect.flush();\n    Ctxt ctx_2(sk);\n    connect >> ctx_2;\n    NTL::ZZX dec_2;\n    sk.Decrypt(dec_2, ctx_2);\n    NTL::ZZX dec;\n    sk.Decrypt(dec, ctx);\n    if (dec[0] != dec_2[0])\n        std::cout << \"IO ERRR\" << std::endl;\n    connect.close();\n}\n\nvoid run_server() {\n    using boost::asio::ip::tcp;\n    boost::asio::io_service ios;\n    tcp::endpoint endpoint(tcp::v4(), 12345);\n    tcp::acceptor acceptor(ios, endpoint);\n\n    for (;;) {\n        tcp::iostream client;\n        boost::system::error_code err;\n        acceptor.accept(*client.rdbuf(), err);\n        if (!err) {\n            std::cout << \"connected\" << std::endl;\n            unsigned long m, p, r;\n            std::vector<long> gens, ords;\n            readContextBase(client, m, p, r, gens, ords);\n            FHEcontext context(m, p, r, gens, ords);\n            client >> context;\n            std::ifstream ifs(\"pk.pk\", std::ios::binary);\n            FHEPubKey pk(context);\n            ifs >> pk;\n            ifs.close();\n\n            Ctxt ctx(pk);\n            client >> ctx;\n            //ctx.multiplyBy(ctx);\n            //ctx.modDownToLevel(1);\n            client << ctx;\n            client.close();\n            break;\n        } else {\n            std::cerr << \"Error \" << err << std::endl;\n        }\n    }\n}\n\nint main(int argc, char *argv[]) {\n    if (argc > 1) {\n        run_client();\n    } else {\n        run_server();\n    }\n}\n", "meta": {"hexsha": "99808687ad31df516680cd0c2e949e2a9aa7f016", "size": 2216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_net_io.cpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_net_io.cpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_net_io.cpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4712643678, "max_line_length": 57, "alphanum_fraction": 0.5257220217, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583475, "lm_q2_score": 0.030675799606029914, "lm_q1q2_score": 0.014978483585046916}}
{"text": "//   Copyright 2019 <Huawei Technologies Co., Ltd>\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 SWAPPING_HPP\n#define SWAPPING_HPP\n\n#include <glog/logging.h>\n\n#include <boost/format.hpp>\n#include <cstdint>\n#include <vector>\n\n#include \"funcs.hpp\"\n#include \"simulator-mpi/SwapArrays.hpp\"\n\nnamespace swapping\n{\ntemplate <size_t n_bits>\nstruct SwappingBase\n{\n     template <class T, class Iterator>\n     static size_t doCalc(const Iterator state_vector, uint64_t n,\n                          size_t start_free_idx, T* svalues, uint64_t* indices,\n                          const std::vector<uint64_t>& swap_bits)\n     {\n          size_t free_idx_end = start_free_idx + n;\n          for (size_t free_idx = start_free_idx; free_idx < free_idx_end;\n               ++free_idx) {\n               size_t res_free_idx = free_idx;\n               for (size_t bit_idx = 0; bit_idx < n_bits; ++bit_idx) {\n                    uint64_t sw_bit = swap_bits[bit_idx];\n                    uint64_t l = res_free_idx & (sw_bit - 1);\n                    uint64_t r = res_free_idx - l;\n\n                    res_free_idx = 2 * r + l;\n               }\n\n               for (size_t swap_idx = 0; swap_idx < (1ul << n_bits);\n                    ++swap_idx) {\n                    size_t res_idx = res_free_idx;\n                    size_t res_swap_idx = 0;\n                    for (size_t bi = 0; bi < n_bits; ++bi) {\n                         bool bv = swap_idx & (1ul << bi);\n                         res_swap_idx\n                             |= bv * (swap_bits[swap_bits[n_bits + bi]]);\n                    }\n\n                    res_idx += res_swap_idx;\n                    size_t idx = n * swap_idx + free_idx - start_free_idx;\n                    indices[idx] = res_idx;\n                    svalues[idx] = state_vector[res_idx];\n               }\n          }\n\n          return free_idx_end;\n     }\n};\n\ntemplate <size_t n_bits_max>\nstruct Swapping\n{\n     template <class T, class Iterator>\n     static size_t calcSwap(uint64_t n_bits, const Iterator state_vector,\n                            uint64_t n, size_t start_free_idx, T* svalues,\n                            uint64_t* indices,\n                            const std::vector<uint64_t>& swap_bits)\n     {\n          if (n_bits == n_bits_max) {\n               return SwappingBase<n_bits_max>::doCalc(state_vector, n,\n                                                       start_free_idx, svalues,\n                                                       indices, swap_bits);\n          }\n          else {\n               return Swapping<n_bits_max - 1>::calcSwap(\n                   n_bits, state_vector, n, start_free_idx, svalues, indices,\n                   swap_bits);\n          }\n     }\n};\n\ntemplate <>\nstruct Swapping<0>\n{\n     template <class T, class Iterator>\n     static size_t calcSwap(uint64_t, const Iterator, uint64_t, size_t, T*,\n                            uint64_t*, const std::vector<uint64_t>&)\n     {\n          return 0;\n     }\n};\n\n}  // namespace swapping\n\n#endif  // SWAPPING_HPP\n", "meta": {"hexsha": "71eb7c06c988d1b70a507ca4bae8d45e540d1efe", "size": 3560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simulator-mpi/swapping.hpp", "max_stars_repo_name": "thexdesk/HiQsimulator", "max_stars_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T01:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T14:51:01.000Z", "max_issues_repo_path": "src/simulator-mpi/swapping.hpp", "max_issues_repo_name": "thexdesk/HiQsimulator", "max_issues_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T01:45:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T02:37:32.000Z", "max_forks_repo_path": "src/simulator-mpi/swapping.hpp", "max_forks_repo_name": "thexdesk/HiQsimulator", "max_forks_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2019-07-10T20:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T14:51:20.000Z", "avg_line_length": 33.5849056604, "max_line_length": 79, "alphanum_fraction": 0.5421348315, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.04084571707752515, "lm_q1q2_score": 0.014973620653339485}}
{"text": "#include <config.h>\n\n#include \"error_calc.hh\"\n\n#include <assert.h>\n#include <boost/filesystem/fstream.hpp>\n#include <iostream>\n#include <map>\n#include <unordered_map>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include <dune/gdt/assembler/system.hh>\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/products/l2.hh>\n#include <dune/gdt/products/h1.hh>\n#include <dune/gdt/operators/prolongations.hh>\n\n#include <dune/multiscale/common/traits.hh>\n#include <dune/multiscale/common/grid_creation.hh>\n#include <dune/multiscale/problems/base.hh>\n#include <dune/multiscale/msfem/localsolution_proxy.hh>\n#include <dune/multiscale/msfem/proxygridview.hh>\n#include <dune/multiscale/msfem/fem_solver.hh>\n#include <dune/multiscale/problems/selector.hh>\n#include <dune/multiscale/tools/misc/outputparameter.hh>\n#include <dune/xt/common/parallel/partitioner.hh>\n#include <dune/grid/utility/partitioning/seedlist.hh>\n#include <dune/stuff/grid/information.hh>\n#include <dune/xt/common/filesystem.hh>\n#include <dune/xt/common/configuration.hh>\n#include <dune/multiscale/common/heterogenous.hh>\n#include <dune/multiscale/msfem/fem_solver.hh>\n\nusing namespace Dune::Multiscale;\nnamespace DGP = Dune::GDT::Products;\ntypedef DSFu::Difference<Problem::ExactSolutionType, CommonTraits::ConstDiscreteFunctionType> DifferenceType;\ntypedef DSFu::Difference<CommonTraits::ConstDiscreteFunctionType, CommonTraits::ConstDiscreteFunctionType>\n    DiscreteDifferenceType;\ntypedef DGP::L2Localizable<CommonTraits::InteriorGridViewType, DifferenceType> L2ErrorAnalytical;\ntypedef DGP::L2Localizable<CommonTraits::InteriorGridViewType, DiscreteDifferenceType> L2ErrorDiscrete;\ntypedef DGP::H1SemiLocalizable<CommonTraits::InteriorGridViewType, DifferenceType> H1sErrorAnalytical;\ntypedef DGP::H1SemiLocalizable<CommonTraits::InteriorGridViewType, DiscreteDifferenceType> H1sErrorDiscrete;\ntypedef DGP::L2Localizable<CommonTraits::InteriorGridViewType, CommonTraits::ConstDiscreteFunctionType> DiscreteL2;\n\n\ndouble surface_flow_gdt(const CommonTraits::GridType& grid,\n                        const CommonTraits::ConstDiscreteFunctionType& solution,\n                        const DMP::ProblemContainer& problem);\n\nvoid solution_output(const DMP::ProblemContainer& problem,\n                     const CommonTraits::ConstDiscreteFunctionType& solution,\n                     std::string name = \"msfem_solution_\")\n{\n  using namespace Dune;\n\n  Dune::Multiscale::OutputParameters outputparam(problem.config().get(\"global.datadir\", \"data\"));\n  outputparam.set_prefix(name);\n  solution.visualize(outputparam.fullpath(solution.name()));\n}\ntemplate <typename L, typename R>\nvoid solution_output(const DMP::ProblemContainer& problem,\n                     const DSFu::Difference<L, R>& solution,\n                     const CommonTraits::GridViewType& view,\n                     std::string name)\n{\n  using namespace Dune;\n\n  Dune::Multiscale::OutputParameters outputparam(problem.config().get(\"global.datadir\", \"data\"));\n  outputparam.set_prefix(name);\n  solution.visualize(view, outputparam.fullpath(solution.name()));\n}\nvoid data_output(const DMP::ProblemContainer& problem, const CommonTraits::GridViewType& gridPart)\n{\n  using namespace Dune;\n  Dune::Multiscale::OutputParameters outputparam(problem.config().get(\"global.datadir\", \"data\"));\n\n  if (problem.getModelData().hasExactSolution()) {\n    const auto& u = problem.getExactSolution();\n    outputparam.set_prefix(\"exact_solution\");\n    u.visualize(gridPart, outputparam.fullpath(u.name()));\n  }\n}\n\nDune::Multiscale::ErrorCalculator::ErrorCalculator(const DMP::ProblemContainer& problem,\n                                                   const std::unique_ptr<LocalsolutionProxy>& msfem_solution,\n                                                   CommonTraits::ConstDiscreteFunctionType* fem_solution)\n  : problem_(problem)\n  , msfem_solution_(msfem_solution)\n  , fem_solution_(fem_solution)\n  , timing_(\"error.fem+msfem\")\n{\n  assert(fem_solution_);\n}\n\nErrorCalculator::ErrorCalculator(const DMP::ProblemContainer& problem,\n                                 const std::unique_ptr<LocalsolutionProxy>& msfem_solution)\n  : problem_(problem)\n  , msfem_solution_(msfem_solution)\n  , fem_solution_(nullptr)\n  , timing_(\"error.msfem\")\n{\n  assert(msfem_solution_);\n  if (problem.config().get(\"msfem.fem_comparison\", false)) {\n    fem_solver_ = Dune::XT::Common::make_unique<Elliptic_FEM_Solver>(problem);\n    try {\n      fem_solution_ = &fem_solver_->solve();\n    } catch (Dune::Exception& e) {\n      MS_LOG_ERROR << \"fine CGFEM solution failed: \" << e.what();\n      fem_solution_ = nullptr;\n    }\n  }\n}\n\nvoid match_check(const CommonTraits::GridType& coarse_grid, const CommonTraits::GridType& fine_grid)\n{\n  const auto fine_view = fine_grid.leafGridView<CommonTraits::InteriorBorderPartition>();\n  const auto coarse_view = coarse_grid.leafGridView<CommonTraits::InteriorBorderPartition>();\n  const auto coarse_dimensions = DSG::dimensions(coarse_view);\n  const auto fine_dimensions = DSG::dimensions(fine_view);\n  for (const auto i : Dune::XT::Common::value_range(CommonTraits::world_dim)) {\n    const bool match =\n        Dune::XT::Common::FloatCmp::eq(coarse_dimensions.coord_limits[i].min(), fine_dimensions.coord_limits[i].min())\n        && Dune::XT::Common::FloatCmp::eq(coarse_dimensions.coord_limits[i].max(),\n                                          fine_dimensions.coord_limits[i].max());\n    if (!match) {\n      DUNE_THROW(Dune::InvalidStateException,\n                 \"Coarse and fine mesh do not match after load balancing, do \\\n                 you use different refinements in different spatial dimensions?\\n\"\n                     << coarse_dimensions.coord_limits[i]\n                     << \" | \"\n                     << fine_dimensions.coord_limits[i]);\n    }\n  }\n}\n\nstd::map<std::string, double> Dune::Multiscale::ErrorCalculator::print(std::ostream& out)\n{\n  using namespace std;\n  using namespace DSC;\n  out << std::endl << \"The L2 errors:\" << std::endl << std::endl;\n\n  const size_t over_integrate = problem_.config().get(\"global.error.over_integrate\", 0u);\n\n  auto grids = make_grids(problem_);\n  const auto coarse_grid = grids.first;\n  const auto fine_grid = grids.second;\n  if (!fem_solution_)\n    assert(fine_grid);\n  const auto fine_space =\n      fem_solution_ ? fem_solution_->space() : CommonTraits::SpaceChooserType::make_space(*fine_grid);\n  const auto fine_interior_view =\n      fine_space.grid_view().grid().template leafGridView<CommonTraits::InteriorBorderPartition>();\n  Dune::XT::Common::IndexSetPartitioner<CommonTraits::InteriorGridViewType> ip(fine_interior_view.indexSet());\n  SeedListPartitioning<typename CommonTraits::InteriorGridViewType::Grid, 0> partitioning(fine_interior_view, ip);\n  GDT::SystemAssembler<CommonTraits::SpaceType, CommonTraits::InteriorGridViewType> system_assembler(\n      fine_space, fine_interior_view);\n  const auto& grid_view = fine_space.grid_view();\n\n  CommonTraits::DiscreteFunctionType projected_coarse_fem_solution(fine_space);\n  Elliptic_FEM_Solver coarse_fem_solver(problem_, coarse_grid);\n  try {\n    auto& coarse_fem_solution = coarse_fem_solver.solve();\n    const Dune::GDT::Operators::LagrangeProlongation<CommonTraits::GridViewType> prolongation_operator(\n        fine_space.grid_view());\n    prolongation_operator.apply(coarse_fem_solution, projected_coarse_fem_solution);\n    if (problem_.config().get(\"global.vtk_output\", false))\n      solution_output(problem_, coarse_fem_solution, \"coarse-cg-fem_solution_\");\n  } catch (Dune::Exception& e) {\n    MS_LOG_ERROR << \"coarse CGFEM solution failed: \" << e.what();\n    fem_solution_ = nullptr;\n  }\n\n  CommonTraits::DiscreteFunctionType fine_msfem_solution(fine_space, \"MsFEM_Solution\");\n  if (msfem_solution_) {\n    match_check(*coarse_grid, *fine_grid);\n    MsFEMProjection::project(*msfem_solution_, fine_msfem_solution);\n    if (problem_.config().get(\"global.vtk_output\", false)) {\n      MS_LOG_INFO_0 << \"Solution output for MsFEM Solution.\" << std::endl;\n      data_output(problem_, fine_space.grid_view());\n      solution_output(problem_, fine_msfem_solution);\n    }\n    const auto space = CommonTraits::SpaceChooserType::make_space(*coarse_grid);\n    CommonTraits::DiscreteFunctionType coarse_fun(space, \"MsFEM_Solution_coarse\");\n    const auto flow = surface_flow_gdt(*coarse_grid, coarse_fun, problem_);\n    MS_LOG_ERROR_0 << \"FLOW \" << flow << std::endl;\n  }\n\n  const string msfem_exact = \"msfem_exact\", fem_exact = \"fem_exact\", coarse_fem_exact = \"coarse_fem_exact\",\n               msfem_fem = \"msfem_fem\", msfem_coarse_fem = \"msfem_coarse_fem\";\n  unordered_map<string, DifferenceType> differences;\n  unordered_map<string, DiscreteDifferenceType> discrete_differences;\n  unordered_map<string, L2ErrorAnalytical> l2_analytical_errors;\n  unordered_map<string, H1sErrorAnalytical> h1s_analytical_errors;\n  unordered_map<string, L2ErrorDiscrete> l2_discrete_errors;\n  unordered_map<string, H1sErrorDiscrete> h1s_discrete_errors;\n  std::unique_ptr<DiscreteL2> l2_msfem;\n  constexpr auto pcw = std::piecewise_construct_t();\n\n  //! ----------------- compute L2- and H1- errors -------------------\n  if (problem_.getModelData().hasExactSolution()) {\n    const auto& u = problem_.getExactSolution();\n\n    if (msfem_solution_) {\n      const auto name = forward_as_tuple(msfem_exact);\n      const auto& difference =\n          map_emplace(differences, pcw, name, forward_as_tuple(u, fine_msfem_solution)).first->second;\n      const auto product_args = forward_as_tuple(fine_interior_view, difference, over_integrate);\n      system_assembler.add(map_emplace(l2_analytical_errors, pcw, name, product_args).first->second);\n      system_assembler.add(map_emplace(h1s_analytical_errors, pcw, name, product_args).first->second);\n    }\n\n    if (fem_solution_) {\n      const auto name = forward_as_tuple(fem_exact);\n      const auto& difference = map_emplace(differences, pcw, name, forward_as_tuple(u, *fem_solution_)).first->second;\n      const auto product_args = forward_as_tuple(fine_interior_view, difference, over_integrate);\n      system_assembler.add(map_emplace(l2_analytical_errors, pcw, name, product_args).first->second);\n      system_assembler.add(map_emplace(h1s_analytical_errors, pcw, name, product_args).first->second);\n    }\n    const auto name = forward_as_tuple(coarse_fem_exact);\n    const auto& difference =\n        map_emplace(differences, pcw, name, forward_as_tuple(u, projected_coarse_fem_solution)).first->second;\n    const auto product_args = forward_as_tuple(fine_interior_view, difference, over_integrate);\n    system_assembler.add(map_emplace(l2_analytical_errors, pcw, name, product_args).first->second);\n    system_assembler.add(map_emplace(h1s_analytical_errors, pcw, name, product_args).first->second);\n  }\n\n  if (msfem_solution_) {\n    l2_msfem = Dune::XT::Common::make_unique<DiscreteL2>(fine_interior_view, fine_msfem_solution, over_integrate);\n    system_assembler.add(*l2_msfem);\n    {\n      const auto name = forward_as_tuple(msfem_coarse_fem);\n      const auto& difference =\n          map_emplace(\n              discrete_differences, pcw, name, forward_as_tuple(fine_msfem_solution, projected_coarse_fem_solution))\n              .first->second;\n      const auto product_args = forward_as_tuple(fine_interior_view, difference, over_integrate);\n      system_assembler.add(map_emplace(l2_discrete_errors, pcw, name, product_args).first->second);\n      system_assembler.add(map_emplace(h1s_discrete_errors, pcw, name, product_args).first->second);\n    }\n    if (fem_solution_) {\n      const auto name = forward_as_tuple(msfem_fem);\n      const auto& difference =\n          map_emplace(discrete_differences, pcw, name, forward_as_tuple(fine_msfem_solution, *fem_solution_))\n              .first->second;\n      const auto product_args = forward_as_tuple(fine_interior_view, difference, over_integrate);\n      system_assembler.add(map_emplace(l2_discrete_errors, pcw, name, product_args).first->second);\n      system_assembler.add(map_emplace(h1s_discrete_errors, pcw, name, product_args).first->second);\n    }\n  }\n\n  system_assembler.assemble(partitioning);\n\n  std::map<std::string, double> csv;\n  if (problem_.getModelData().hasExactSolution()) {\n    if (msfem_solution_) {\n      const auto msfem_error = std::sqrt(l2_analytical_errors.at(msfem_exact).apply2());\n      out << \"|| u_msfem - u_exact ||_L2 =  \" << msfem_error << std::endl;\n      const auto h1_msfem_error = std::sqrt(h1s_analytical_errors.at(msfem_exact).apply2());\n      out << \"|| u_msfem - u_exact ||_H1s =  \" << h1_msfem_error << std::endl << std::endl;\n\n      csv[msfem_exact + \"_L2\"] = msfem_error;\n      csv[msfem_exact + \"_H1s\"] = h1_msfem_error;\n    }\n\n    if (fem_solution_) {\n      const auto fem_error = std::sqrt(l2_analytical_errors.at(fem_exact).apply2());\n      out << \"|| u_fem_h - u_exact ||_L2 =  \" << fem_error << std::endl;\n      const auto h1_fem_error = std::sqrt(h1s_analytical_errors.at(fem_exact).apply2());\n      out << \"|| u_fem_h - u_exact ||_H1s =  \" << h1_fem_error << std::endl << std::endl;\n\n      csv[fem_exact + \"_L2\"] = fem_error;\n      csv[fem_exact + \"_H1s\"] = h1_fem_error;\n    }\n    const auto fem_error = std::sqrt(l2_analytical_errors.at(coarse_fem_exact).apply2());\n    out << \"|| u_fem_H - u_exact ||_L2 =  \" << fem_error << std::endl;\n    const auto h1_fem_error = std::sqrt(h1s_analytical_errors.at(coarse_fem_exact).apply2());\n    out << \"|| u_fem_H - u_exact ||_H1s =  \" << h1_fem_error << std::endl << std::endl;\n\n    csv[coarse_fem_exact + \"_L2\"] = fem_error;\n    csv[coarse_fem_exact + \"_H1s\"] = h1_fem_error;\n  }\n\n  if (msfem_solution_) {\n    const auto norm = std::sqrt(l2_msfem->apply2());\n    out << \"|| u_msfem ||_L2 =  \" << norm << std::endl;\n    csv[\"msfem_L2\"] = norm;\n    const auto fem_error = std::sqrt(l2_discrete_errors.at(msfem_coarse_fem).apply2());\n    out << \"|| u_fem_H - u_msfem ||_L2 =  \" << fem_error << std::endl;\n    out << \"|| u_fem_H - u_msfem ||_L2 / || u_msfem ||_L2 =  \" << fem_error / norm << std::endl;\n    const auto h1_fem_error = std::sqrt(h1s_discrete_errors.at(msfem_coarse_fem).apply2());\n    out << \"|| u_fem_H - u_msfem ||_H1s =  \" << h1_fem_error << std::endl << std::endl;\n\n    csv[msfem_coarse_fem + \"_L2\"] = fem_error;\n    csv[msfem_coarse_fem + \"_H1s\"] = h1_fem_error;\n\n    if (fem_solution_) {\n      const auto approx_msfem_error = std::sqrt(l2_discrete_errors.at(msfem_fem).apply2());\n      if (std::abs(norm) > 1e-12)\n        out << \"|| u_msfem - u_fem ||_L2 / || u_msfem ||_L2 =  \" << approx_msfem_error / norm << std::endl;\n      else\n        out << \"|| u_msfem - u_fem ||_L2 =  \" << approx_msfem_error << std::endl;\n\n      const auto h1_approx_msfem_error = std::sqrt(h1s_discrete_errors.at(msfem_fem).apply2());\n      out << \"|| u_msfem - u_fem ||_H1s =  \" << h1_approx_msfem_error << std::endl << std::endl;\n\n      csv[msfem_fem + \"_L2\"] = approx_msfem_error;\n      csv[msfem_fem + \"_H1s\"] = h1_approx_msfem_error;\n    }\n  }\n\n  if (problem_.config().get(\"global.vtk_output\", false)) {\n    MS_LOG_INFO_0 << \"Differences output for MsFEM Solution.\" << std::endl;\n    for (const auto& mpair : differences)\n      solution_output(problem_, mpair.second, grid_view, mpair.first);\n    for (const auto& mpair : discrete_differences)\n      solution_output(problem_, mpair.second, grid_view, mpair.first);\n    if (fem_solution_)\n      solution_output(problem_, *fem_solution_, \"fine-cg-fem_solution_\");\n  }\n\n  std::unique_ptr<boost::filesystem::ofstream> csvfile(Dune::XT::Common::make_ofstream(\n      std::string(problem_.config().get(\"global.datadir\", \"data/\")) + std::string(\"/errors.csv\")));\n  const std::string sep(\",\");\n  for (const auto& key_val : csv) {\n    *csvfile << key_val.first << sep;\n  }\n  *csvfile << std::endl;\n  for (const auto& key_val : csv) {\n    *csvfile << key_val.second << sep;\n  }\n  *csvfile << std::endl;\n  return csv;\n}\n\ndouble surface_flow_gdt(const Dune::Multiscale::CommonTraits::GridType& grid,\n                        const Dune::Multiscale::CommonTraits::ConstDiscreteFunctionType& solution,\n                        const DMP::ProblemContainer& problem)\n{\n  using namespace Dune::Multiscale;\n  const auto gv = grid.leafGridView();\n\n  // Constants and types\n  constexpr auto dim = CommonTraits::world_dim;\n  typedef double REAL; // TODO read from input\n  typedef typename Dune::FieldVector<REAL, dim> FV; // point on cell\n  typedef typename Dune::FieldMatrix<REAL, dim, dim> FM; // point on cell\n  typedef typename Dune::FieldMatrix<REAL, 1, dim> Grad; // point on cell\n  typedef typename Dune::QuadratureRule<REAL, dim - 1> QR;\n  typedef typename Dune::QuadratureRules<REAL, dim - 1> QRS;\n\n  const auto& diffusion = problem.getDiffusion();\n\n  // Quadrature rule\n  auto iCell = gv.template begin<0, Dune::Interior_Partition>();\n  auto iFace = gv.ibegin(*iCell);\n  const QR& rule = QRS::rule(iFace->geometry().type(), 2); // TODO order as para\n\n  // Loop over cells\n  REAL localFlux(0);\n  for (iCell = gv.template begin<0, Dune::Interior_Partition>();\n       iCell != gv.template end<0, Dune::Interior_Partition>();\n       ++iCell) {\n    // Loop over interfaces\n    const auto local_solution = solution.local_function(*iCell);\n    for (iFace = gv.ibegin(*iCell); iFace != gv.iend(*iCell); ++iFace) {\n      if (iFace->boundary() && iFace->geometry().center()[0] == 0) {\n        double area = iFace->geometry().volume();\n        // Loop over gauss points\n        for (auto iGauss = rule.begin(); iGauss != rule.end(); ++iGauss) {\n          FV pos = iFace->geometry().global(iGauss->position());\n          Grad grad;\n          FM diff;\n          diffusion.evaluate(pos, diff);\n          local_solution->jacobian(pos, grad);\n          localFlux -= iGauss->weight() * area * diff[0][0] * grad[0][0];\n        }\n      }\n    }\n  }\n  localFlux = grid.comm().sum(localFlux);\n  return localFlux;\n}\n", "meta": {"hexsha": "067cec0af4e929793db59c15c934b9b475d9366a", "size": 17869, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dune/multiscale/common/error_calc.cc", "max_stars_repo_name": "wwu-numerik/DUNE-Multiscale", "max_stars_repo_head_hexsha": "db7c4520c87d61bccdc05b05c54e7e50bdfd8d14", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-17T12:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T08:54:32.000Z", "max_issues_repo_path": "dune/multiscale/common/error_calc.cc", "max_issues_repo_name": "wwu-numerik/DUNE-Multiscale", "max_issues_repo_head_hexsha": "db7c4520c87d61bccdc05b05c54e7e50bdfd8d14", "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/multiscale/common/error_calc.cc", "max_forks_repo_name": "wwu-numerik/DUNE-Multiscale", "max_forks_repo_head_hexsha": "db7c4520c87d61bccdc05b05c54e7e50bdfd8d14", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T12:00:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-17T12:00:04.000Z", "avg_line_length": 46.412987013, "max_line_length": 118, "alphanum_fraction": 0.7031171302, "num_tokens": 4821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.03114382738739638, "lm_q1q2_score": 0.014963945012448415}}
{"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_IEXP_IEXP_COPY_HPP\n#define AMA_TENSOR_IEXP_IEXP_COPY_HPP 1\n\n#include <ama/tensor/detail/copy.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/inserter.hpp>\n#include <boost/mpl/map/map0.hpp>\n#include <boost/mpl/pair.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/transform.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    namespace mpl = ::boost::mpl;\n\n    /* from two list create a map*/\n    template <\n          typename I1 /* index name */\n        , typename I2 /* index value */\n        >\n    struct make_imap:\n        mpl::transform<\n              I1\n            , I2\n            , mpl::pair<mpl::_1, mpl::_2>\n            , mpl::inserter<\n                    mpl::map0<>\n                  , mpl::insert<mpl::_1, mpl::_2>\n                  >\n            > { };\n\n    /* this struct implement the copy */\n     template <\n           typename D               /* the dimensione of tensor */\n         , typename O               /* the order of tensor */\n         , typename I = first<O>    /* the first multi-index */\n         , typename R = mpl::false_ /* this type is true for the last multi-index */\n         >\n     struct iexp_copy\n     {\n       template <typename SRC, typename DST>\n       static\n       void apply(SRC const & src, DST & dst)\n       {\n         typedef typename make_imap<typename DST::index_list, I>::type imap;\n         dst.template at<imap>() = src.template at<imap>();\n\n         /* increment the multi-index */\n         typedef typename increment<D,I>::type increment_type;\n\n         /* the first is the multi-index incremented */\n         typedef typename mpl::first<increment_type>::type i;\n         /* the second is a boolean flag toidentify the last multi-index */\n         typedef typename mpl::second<increment_type>::type r;\n\n         /* iterative call */\n         iexp_copy<D,O,i,r>::apply(src,dst);\n       }\n     };\n\n\n     /* partial specialization, end the iterative call */\n     template <typename D, typename O, typename I>\n     struct iexp_copy<D,O,I,mpl::true_>\n     {\n       template <typename SRC, typename DST>\n       static void apply(SRC const &, DST &) { }\n     };\n\n  }\n}\n\n#endif /* AMA_TENSOR_IEXP_IEXP_COPY_HPP */\n", "meta": {"hexsha": "7c6ff4f1f9b08ad910dba8fdf41ec1537d8fb717", "size": 3865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/iexp/iexp_copy.hpp", "max_stars_repo_name": "mattiapenati/amanita", "max_stars_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ama/tensor/iexp/iexp_copy.hpp", "max_issues_repo_name": "mattiapenati/amanita", "max_issues_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ama/tensor/iexp/iexp_copy.hpp", "max_forks_repo_name": "mattiapenati/amanita", "max_forks_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4622641509, "max_line_length": 84, "alphanum_fraction": 0.6501940492, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861804086755836, "lm_q2_score": 0.038466195049607896, "lm_q1q2_score": 0.014948657359807993}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019-2020, LAAS-CNRS, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n#define CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n\n#include <stdexcept>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"crocoddyl/core/fwd.hpp\"\n#include \"crocoddyl/core/state-base.hpp\"\n#include \"crocoddyl/core/utils/to-string.hpp\"\n#include \"crocoddyl/core/utils/math.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Abstract class for differential action model\n *\n * A differential action model is the time-continuous version of an action model, i.e.\n * \\f[\n * \\begin{aligned}\n * &\\dot{\\mathbf{v}} = \\mathbf{f}(\\mathbf{q}, \\mathbf{v}, \\mathbf{u}), &\\textrm{(dynamics)}\\\\\n * &l(\\mathbf{x},\\mathbf{u}) = \\int_0^{\\delta t} a(\\mathbf{r}(\\mathbf{x},\\mathbf{u}))\\,dt, &\\textrm{(cost)}\n * \\end{aligned}\n * \\f]\n * where the configuration \\f$\\mathbf{q}\\in\\mathcal{Q}\\f$ lies in the configuration manifold described with a\n * `nq`-tuple, the velocity \\f$\\mathbf{v}\\in T_{\\mathbf{q}}\\mathcal{Q}\\f$ its a tangent vector to this manifold with\n * `nv` dimension, \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$ is the input commands, \\f$\\mathbf{r}\\f$ and \\f$a\\f$ is a residual\n * and activation functions (see `ActivationModelAbstractTpl`). Both configuration and velocity describe the system\n * space \\f$\\mathbf{x}\\in\\mathbf{X}\\f$ which lies in the state manifold. Note that the acceleration\n * \\f$\\dot{\\mathbf{v}}\\in T_{\\mathbf{q}}\\mathcal{Q}\\f$ lies also in the tangent space of the configuration manifold.\n *\n * The main computations are carrying out in `calc` and `calcDiff`. `calc` computes the acceleration and cost and\n * `calcDiff` computes the derivatives of the dynamics and cost function. Concretely speaking, `calcDiff` builds a\n * linear-quadratic approximation of the differential action, where the dynamics and cost functions have linear and\n * quadratic forms, respectively. \\f$\\mathbf{f_x}\\in\\mathbb{R}^{nv\\times ndx}\\f$,\n * \\f$\\mathbf{f_u}\\in\\mathbb{R}^{nv\\times nu}\\f$ are the Jacobians of the dynamics;\n * \\f$\\mathbf{l_x}\\in\\mathbb{R}^{ndx}\\f$, \\f$\\mathbf{l_u}\\in\\mathbb{R}^{nu}\\f$,\n * \\f$\\mathbf{l_{xx}}\\in\\mathbb{R}^{ndx\\times ndx}\\f$, \\f$\\mathbf{l_{xu}}\\in\\mathbb{R}^{ndx\\times nu}\\f$,\n * \\f$\\mathbf{l_{uu}}\\in\\mathbb{R}^{nu\\times nu}\\f$ are the Jacobians and Hessians of the cost function, respectively.\n * Additionally, it is important remark that `calcDiff()` computes the derivates using the latest stored values by\n * `calc()`. Thus, we need to run first `calc()`.\n *\n * \\sa `calc()`, `calcDiff()`, `createData()`\n */\ntemplate <typename _Scalar>\nclass DifferentialActionModelAbstractTpl {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef DifferentialActionDataAbstractTpl<Scalar> DifferentialActionDataAbstract;\n  typedef StateAbstractTpl<Scalar> StateAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  /**\n   * @brief Initialize the differential action model\n   *\n   * @param[in] state  State description\n   * @param[in] nu     Dimension of control vector\n   * @param[in] nr     Dimension of cost-residual vector\n   */\n  DifferentialActionModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t& nu,\n                                     const std::size_t& nr = 0);\n  virtual ~DifferentialActionModelAbstractTpl();\n\n  /**\n   * @brief Compute the system acceleration and cost value\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   * @param[in] u     Control input\n   */\n  virtual void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                    const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Compute the derivatives of the dynamics and cost functions\n   *\n   * It computes the partial derivatives of the dynamical system and the cost function. It assumes that `calc()` has\n   * been run first. This function builds a quadratic approximation of the time-continuous action model (i.e. dynamical\n   * system and cost function).\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   * @param[in] u     Control input\n   */\n  virtual void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data,\n                        const Eigen::Ref<const VectorXs>& x, const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Create the differential action data\n   *\n   * @return the differential action data\n   */\n  virtual boost::shared_ptr<DifferentialActionDataAbstract> createData();\n\n  /**\n   * @brief Checks that a specific data belongs to this model\n   */\n  virtual bool checkData(const boost::shared_ptr<DifferentialActionDataAbstract>& data);\n\n  /**\n   * @copybrief calc()\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   */\n  void calc(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @copybrief calcDiff()\n   *\n   * @param[in] data  Differential action data\n   * @param[in] x     State point\n   */\n  void calcDiff(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief Computes the quasic static commands\n   *\n   * The quasic static commands are the ones produced for a the reference posture as an equilibrium point, i.e.\n   * for \\f$\\mathbf{f}(\\mathbf{q},\\mathbf{v}=\\mathbf{0},\\mathbf{u})=\\mathbf{0}\\f$\n   *\n   * @param[in] data    Differential action data\n   * @param[out] u      Quasic static commands\n   * @param[in] x       State point (velocity has to be zero)\n   * @param[in] maxiter Maximum allowed number of iterations\n   * @param[in] tol     Tolerance\n   */\n  virtual void quasiStatic(const boost::shared_ptr<DifferentialActionDataAbstract>& data, Eigen::Ref<VectorXs> u,\n                           const Eigen::Ref<const VectorXs>& x, const std::size_t& maxiter = 100,\n                           const Scalar& tol = Scalar(1e-9));\n\n  /**\n   * @copybrief quasicStatic()\n   *\n   * @copydetails quasicStatic()\n   *\n   * @param[in] data    Differential action data\n   * @param[in] x       State point (velocity has to be zero)\n   * @param[in] maxiter Maximum allowed number of iterations\n   * @param[in] tol     Tolerance\n   * @return Quasic static commands\n   */\n  VectorXs quasiStatic_x(const boost::shared_ptr<DifferentialActionDataAbstract>& data, const VectorXs& x,\n                         const std::size_t& maxiter = 100, const Scalar& tol = Scalar(1e-9));\n\n  /**\n   * @brief Return the dimension of the control input\n   */\n  const std::size_t& get_nu() const;\n\n  /**\n   * @brief Return the dimension of the cost-residual vector\n   */\n  const std::size_t& get_nr() const;\n\n  /**\n   * @brief Return the state\n   */\n  const boost::shared_ptr<StateAbstract>& get_state() const;\n\n  /**\n   * @brief Return the control lower bound\n   */\n  const VectorXs& get_u_lb() const;\n\n  /**\n   * @brief Return the control upper bound\n   */\n  const VectorXs& get_u_ub() const;\n\n  /**\n   * @brief Indicates if there are defined control limits\n   */\n  bool const& get_has_control_limits() const;\n\n  /**\n   * @brief Modify the control lower bounds\n   */\n  void set_u_lb(const VectorXs& u_lb);\n\n  /**\n   * @brief Modify the control upper bounds\n   */\n  void set_u_ub(const VectorXs& u_ub);\n\n protected:\n  std::size_t nu_;                          //!< Control dimension\n  std::size_t nr_;                          //!< Dimension of the cost residual\n  boost::shared_ptr<StateAbstract> state_;  //!< Model of the state\n  VectorXs unone_;                          //!< Neutral state\n  VectorXs u_lb_;                           //!< Lower control limits\n  VectorXs u_ub_;                           //!< Upper control limits\n  bool has_control_limits_;                 //!< Indicates whether any of the control limits is finite\n\n  void update_has_control_limits();\n};\n\ntemplate <typename _Scalar>\nstruct DifferentialActionDataAbstractTpl {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  template <template <typename Scalar> class Model>\n  explicit DifferentialActionDataAbstractTpl(Model<Scalar>* const model)\n      : cost(0.),\n        xout(model->get_state()->get_nv()),\n        Fx(model->get_state()->get_nv(), model->get_state()->get_ndx()),\n        Fu(model->get_state()->get_nv(), model->get_nu()),\n        r(model->get_nr()),\n        Lx(model->get_state()->get_ndx()),\n        Lu(model->get_nu()),\n        Lxx(model->get_state()->get_ndx(), model->get_state()->get_ndx()),\n        Lxu(model->get_state()->get_ndx(), model->get_nu()),\n        Luu(model->get_nu(), model->get_nu()) {\n    xout.setZero();\n    r.setZero();\n    Fx.setZero();\n    Fu.setZero();\n    Lx.setZero();\n    Lu.setZero();\n    Lxx.setZero();\n    Lxu.setZero();\n    Luu.setZero();\n  }\n  virtual ~DifferentialActionDataAbstractTpl() {}\n\n  Scalar cost;    //!< cost value\n  VectorXs xout;  //!< evolution state\n  MatrixXs Fx;    //!< Jacobian of the dynamics\n  MatrixXs Fu;    //!< Jacobian of the dynamics\n  VectorXs r;     //!< Cost residual\n  VectorXs Lx;    //!< Jacobian of the cost function\n  VectorXs Lu;    //!< Jacobian of the cost function\n  MatrixXs Lxx;   //!< Hessian of the cost function\n  MatrixXs Lxu;   //!< Hessian of the cost function\n  MatrixXs Luu;   //!< Hessian of the cost function\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/diff-action-base.hxx\"\n\n#endif  // CROCODDYL_CORE_DIFF_ACTION_BASE_HPP_\n", "meta": {"hexsha": "445da9f1c1db6e7e14e6baceb19f7a5148aec611", "size": 10180, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/diff-action-base.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/diff-action-base.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/diff-action-base.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": 38.7072243346, "max_line_length": 119, "alphanum_fraction": 0.6461689587, "num_tokens": 2670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.037326887210266405, "lm_q1q2_score": 0.014923724019245882}}
{"text": "﻿/***\r\n第三节类模板中的友元\r\n(1)友元类：\r\n让某个类B称为另外一个类A的友元类，这样的话，类B就可以在其成员函数中访问类A的所有成员，\r\n而不管这些成员在类A中是用什么（public,protected,private）来修饰的。\r\n如果现在类A和类B都变成了类模板，那么能否让类模板B成为类模板A的友元类模板呢？\r\n1.1：让类模板的某个实例成为友元类\r\n1.2：让类模板成为友元类模板\r\n1.3：让类型模板参数成为友元类:C++11新标准中引入：如果传递进来的类型模板参数是一个类类型，则这个类类型可以成为当前类模板的友元类。\r\na)代码行A2<CF> aobj1; 的效果是让CF类成为了A2<CF>类的友元类；\r\nb)于是，在CF类的成员函数中，可以直接访问aobj1这个A2<CF>类对象的data私有成员变量。\r\n如果传递给类模板A2的类型模板参数不是一个类类型，那么代码行friend T;就会被忽略。\r\n***/\r\n\r\n#include <iostream>\r\n\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\nnamespace _nmsp1\r\n{\r\n\t//template <typename U> class B;       //类模板B的声明\r\n\r\n\ttemplate <typename T>\r\n\tclass A\r\n\t{\r\n\t\t//friend class B<long>;            //不需要任何public,private等修饰符。\r\n\t\ttemplate<typename> friend class B; //类模板B作为类模板A的友元\r\n\tprivate:\r\n\t\tint data;\r\n\t};\r\n\r\n\ttemplate <typename U>\r\n\tclass B\r\n\t{\r\n\tpublic:\r\n\t\tvoid callBAF()                     //在类模板B中访问类模板A的私有成员\r\n\t\t{\r\n\t\t\tA<int> atmpobj;\r\n\t\t\tatmpobj.data = 5;\r\n\t\t\tcout << atmpobj.data << endl;\r\n\t\t}\r\n\t};\r\n}\r\n\r\nnamespace _nmsp2\r\n{\r\n\ttemplate <typename T>\r\n\tclass A2\r\n\t{\r\n\t\tfriend T;                       //类T成为类模板A2的友元\r\n\t\tfriend  class CF;\r\n\r\n\tprivate:\r\n\t\tint data;\r\n\t};\r\n\r\n\tclass CF\r\n\t{\r\n\tpublic:\r\n\t\tvoid callCFAF()\r\n\t\t{\r\n\t\t\tA2<CF> aobj1;                //让CF类成为了A2<CF>类的友元类\r\n\t\t\taobj1.data = 12;\r\n\t\t\tcout << aobj1.data << endl;\r\n\r\n\t\t\tA2<int> aobj2;               //因为CF类并不是A2<int>的友元类，自然不能在这里访问aobj2这个A2<int>类对象的data私有成员变量。\r\n\t\t\taobj2.data = 15;\r\n\t\t\tcout << aobj2.data << endl;\r\n\t\t}\r\n\t};\r\n}\r\n\r\nint main()\r\n{\r\n\t//测试nmsp1\r\n\t//_nmsp1::B<long> bobj;\r\n\t_nmsp1::B<int> bobj;\r\n\tbobj.callBAF();\r\n\r\n\t//测试nmsp2\r\n\t_nmsp2::CF mycfobj;\r\n\tmycfobj.callCFAF();\r\n\r\n\t/*_nmsp2::A2<_nmsp2::CF> aobj1;\r\n\taobj1.data = 12;*/\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "fbaaa80c9322c700e0a282e4b74129d52c778e97", "size": 1715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/211.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/211.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/211.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 18.8461538462, "max_line_length": 93, "alphanum_fraction": 0.6221574344, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706247, "lm_q2_score": 0.06853749493457365, "lm_q1q2_score": 0.014895769247855836}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2009 Scientific Computing and Imaging Institute,\n   University of Utah.\n\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#include <Core/Math/MiscMath.h>\n#include <Core/Algorithms/BrainStimulator/ModelGenericCoilAlgorithm.h>\n#include <Core/Algorithms/BrainStimulator/BiotSavartSolverAlgorithm.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/Datatypes/Legacy/Field/FieldInformation.h>\n#include <Core/GeometryPrimitives/Vector.h>\n#include <Core/GeometryPrimitives/Transform.h>\n#include <Core/GeometryPrimitives/Point.h>\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n\n//#include <cassert>\n//#include <exception>\n\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::Geometry;\nusing namespace SCIRun::Core::Utility;\nusing namespace SCIRun;\n\nALGORITHM_PARAMETER_DEF(BrainStimulator, Type);\nALGORITHM_PARAMETER_DEF(BrainStimulator, FigureOf8CoilShape);\nALGORITHM_PARAMETER_DEF(BrainStimulator, Rings);\nALGORITHM_PARAMETER_DEF(BrainStimulator, WingsAngle);\nALGORITHM_PARAMETER_DEF(BrainStimulator, Current);\nALGORITHM_PARAMETER_DEF(BrainStimulator, Radius);\nALGORITHM_PARAMETER_DEF(BrainStimulator, InnerRadius);\nALGORITHM_PARAMETER_DEF(BrainStimulator, OuterRadius);\nALGORITHM_PARAMETER_DEF(BrainStimulator, Distance);\nALGORITHM_PARAMETER_DEF(BrainStimulator, Layers);\nALGORITHM_PARAMETER_DEF(BrainStimulator, LayerStepSize);\nALGORITHM_PARAMETER_DEF(BrainStimulator, LevelOfDetail);\n\n\n\n\n\n\t\tclass BaseSegments\n\t\t{\n\t\t\tpublic:\n\t\t\t\tBaseSegments(\n\t\t\t\t\tstd::vector<Vector>& p,\n\t\t\t\t\tstd::vector<size_t>& i,\n\t\t\t\t\tstd::vector<double>& v):\n\t\t\t\t\tpoints(p),\n\t\t\t\t\tindices(i),\n\t\t\t\t\tvalues(v),\n\t\t\t\t\tpc(0),\n\t\t\t\t\tstart_idx(0),\n\t\t\t\t\tend_idx(0)\n\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\tvirtual ~BaseSegments()\n\t\t\t\t{\n\t\t\t\t\tthis->Terminate();\n\t\t\t\t}\n\n\t\t\t\tvoid AddPoint(Vector point, double value)\n\t\t\t\t{\n\t\t\t\t\tpoints.push_back(point);\n\n\t\t\t\t\tsize_t psize = points.size();\n\n\t\t\t\t\tif( pc > 0)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tindices.push_back(psize-2);\n\t\t\t\t\t\tindices.push_back(psize-1);\n\t\t\t\t\t\tvalues.push_back(value);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tstart_idx = psize - 1;\n\t\t\t\t\t}\n\n\t\t\t\t\t++pc;\n\t\t\t\t}\n\n\t\t\t\tvoid Transform(Transform& t)\n\t\t\t\t{\n\t\t\t\t\tfor(size_t i = start_idx; i < start_idx + pc; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tpoints[i] = t * points[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvirtual void Terminate()\n\t\t\t\t{\n\t\t\t\t\tpc = 0;\n\t\t\t\t}\n\n\t\t\t\tstd::vector<Vector>& points;\n\t\t\t\tstd::vector<size_t>& indices;\n\t\t\t\tstd::vector<double>& values;\n\t\t\t\tsize_t pc;\n\t\t\t\tsize_t start_idx;\n\t\t\t\tsize_t end_idx;\n\n\t\t\tprivate:\n\n\t\t\t\t//! Prevent copying\n    \t\t\tBaseSegments & operator = (const BaseSegments & other);\n    \t\t\tBaseSegments(const BaseSegments & other);\n\t\t};\n\n\t\tclass ClosedSegments : public BaseSegments\n\t\t{\n\t\t\tpublic:\n\t\t\t\tClosedSegments(\n\t\t\t\t\tstd::vector<Vector>& p,\n\t\t\t\t\tstd::vector<size_t>& i,\n\t\t\t\t\tstd::vector<double>& v)\n\t\t\t\t\t\t:BaseSegments(p,i,v)\n\t\t\t\t{\n\n\t\t\t\t}\n\t\t\t\tvirtual ~ClosedSegments()\n\t\t\t\t{\n\t\t\t\t\tif(pc)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->Terminate();\n\t\t\t\t\t}\n\n\t\t\t\t\t//std::cout << \"~ClosedSegments() Points Indices Values: \" <<  points.size() << \" \" << indices.size() << \" \" << values.size() << std::endl;\n\n\t\t\t\t\t//assert(points.size() > 0);\n\t\t\t\t\t//assert(points.size() == values.size());\n\t\t\t\t\t//assert(points.size()*2 == indices.size());\n\t\t\t\t}\n\n\t\t\t\tvoid Terminate()\n\t\t\t\t{\n\t\t\t\t\tsize_t psize = points.size();\n\n\t\t\t\t\t//close the segments and make a circle\n\t\t\t\t\tindices.push_back(psize-1);\n\t\t\t\t\tindices.push_back(psize-pc);\n\n\t\t\t\t\tvalues.push_back(values[values.size()-1]);\n\n\t\t\t\t\t//std::cout << \"ClosedSegment-Teminate-> psize:\" << psize << \" pc:\" << pc << \"    \" << std::endl;\n\n\t\t\t\t\tpc = 0;\n\t\t\t\t}\n\t\t};\n\n\t\tclass OpenSegments : public BaseSegments\n\t\t{\n\t\t\tpublic:\n\t\t\t\tOpenSegments(\n\t\t\t\t\tstd::vector<Vector>& p,\n\t\t\t\t\tstd::vector<size_t>& i,\n\t\t\t\t\tstd::vector<double>& v)\n\t\t\t\t\t\t:BaseSegments(p,i,v)\n\t\t\t\t{}\n\t\t\t\t~OpenSegments()\n\t\t\t\t{\n\t\t\t\t\t//assert(points.size() > 0);\n\t\t\t\t\t//assert(indices.size() == values.size()*2);\n\t\t\t\t}\n\t\t};\n\n\t\t//--------------------------------------------------------------\n\n\t\tclass BaseCoilgen\n\t\t{\n\t\t\tpublic:\n\t\t\t\tBaseCoilgen(const AlgorithmBase* algo, ModelTMSCoilAlgorithm::Args& args) :\n\t\t\t\t  ref_cnt(0),\n\t\t\t\t  algo(algo),\n\n\t\t\t\t  coilLOD(args.coilLevelDetails),\n\t\t\t\t  coilType(args.type),\n\t\t\t\t  coilLayers(args.coilLayers),\n\t\t\t\t  rings(args.rings),\n\n\t\t\t\t  coilLayersStep(args.coilLayersStep),\n\t\t\t\t  wingsAngle(args.wingsAngle),\n\t\t\t\t  current(args.current),\n\t\t\t\t  innerR(args.coilRadiusInner),\n\t\t\t\t  outerR(args.coilRadiusOuter),\n\t\t\t\t  outerD(args.coilDistance)\n\n\t\t\t\t{\n\n\t\t\t\t}\n\n\t\t\t\tvirtual ~BaseCoilgen()\n\t\t\t\t{\n\t\t\t\t}\n\n\n\n\t\t\t\tvoid Execute(FieldHandle& meshFieldHandle) const\n\t\t\t\t{\n\n\t\t\t\t\tstd::vector<Vector> coilPoints;\n\t\t\t\t\tstd::vector<size_t> coilIndices;\n\n\t\t\t\t\tthis->Generate(meshFieldHandle);\n\t\t\t\t}\n\n\t\t\t\t//! Global reference counting\n\t\t\t\tint ref_cnt;\n\n\t\t\tprotected:\n\n\t\t\t\t//! ref to the executing algorithm context\n\t\t\t\tconst AlgorithmBase* algo;\n\t\t\t\tsize_t coilLOD;\n\t\t\t\tsize_t coilType;\n\t\t\t\tsize_t coilLayers;\n\t\t\t\tconst size_t rings;\n\t\t\t\tdouble coilLayersStep;\n\t\t\t\tdouble wingsAngle;\n\t\t\t\tdouble current;\n\t\t\t\tconst double innerR;\n\t\t\t\tconst double outerR;\n\t\t\t\tconst double outerD;\n\n\t\t\t\t//! Local entry function, must be implemented by each specific kernel\n\t\t\t\tvirtual void Generate(FieldHandle& meshHandle) const = 0;\n\n\t\t\t\tvoid GenPointsCircular(\n\t\t\t\t\tBaseSegments& segments,\n\t\t\t\t\tVector origin,\n\t\t\t\t\tdouble radius,\n\t\t\t\t\tdouble value,\n\t\t\t\t\tdouble fromPI,\n\t\t\t\t\tdouble toPI,\n\t\t\t\t\tdouble extLOD = 0.0) const\n\t\t\t\t{\n\n\t\t\t\t\tdouble dPI = fabs(toPI - fromPI);\n\n\t\t\t\t\tdouble minPI = M_PI /  ( 8.0 * coilLOD + coilLOD * extLOD );\n\n\t\t\t\t\tassert(dPI > minPI);\n\n\t\t\t\t\tsize_t nsegments = 2;\n\t\t\t\t\tdouble iPI = dPI / nsegments;\n\n\t\t\t\t\twhile(iPI > minPI)\n\t\t\t\t\t{\n\t\t\t\t\t\tnsegments++;\n\t\t\t\t\t\tiPI = dPI / nsegments;\n\t\t\t\t\t}\n\n\t\t\t\t\t//algo->remark(\"#Segments(LOD):  \" +  boost::lexical_cast<std::string>(nsegments) );\n\n\t\t\t\t\tdPI = toPI - fromPI;\n\n\t\t\t\t\tiPI = dPI / nsegments;\n\n\t\t\t\t\tfor(size_t i = 0; i < nsegments; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector point(origin.x() + radius * cos(fromPI + iPI*i), origin.y() + radius * sin(fromPI + iPI*i), origin.z());\n\t\t\t\t\t\tsegments.AddPoint(point,value);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvoid BuildScirunMesh(\n\t\t\t\t\t\tconst std::vector<Vector>& points,\n\t\t\t\t\t\tconst std::vector<size_t>& indices,\n\t\t\t\t\t\tconst std::vector<double>& values,\n\t\t\t\t\t\tFieldHandle& meshHandle) const\n\t\t\t\t{\n\n\t\t\t\t\tVMesh* mesh = meshHandle->vmesh();\n\n\n\t\t\t\t\t//! add nodes to the new mesh\n\t\t\t\t\tfor(size_t i = 0; i < points.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Point p(points[i]);\n\t\t\t\t\t\tmesh->add_point(p);\n\t\t\t\t\t}\n\n\t\t\t\t\t//! add edges to mesh\n\t\t\t\t\tVMesh::Node::array_type edge;\n\n\t\t\t\t\tfor(size_t i = 0; i < indices.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t  VMesh::Node::index_type p = indices[i];\n\t\t\t\t\t  edge.push_back(p);\n\n\t\t\t\t\t  if(edge.size() == 2)\n\t\t\t\t\t  {\n\t\t\t\t\t\tmesh->add_elem(edge);\n\t\t\t\t\t\tedge.clear();\n\t\t\t\t\t  }\n\t\t\t\t\t}\n\n\t\t\t\t\t//! add data to mesh\n\n\t\t\t\t\tVField* field = meshHandle->vfield();\n\n\t\t\t\t\tfield->resize_values();\n\t\t\t\t\tfield->set_values(values);\n\t\t\t\t}\n\n\n\t\t};\n\n\t\t//! piece-wise wire discretization\n\t\tclass CircularWireCoilgen : public BaseCoilgen\n\t\t{\n\n\t\t\tpublic:\n\n\t\t\t\tCircularWireCoilgen(\n\t\t\t\t\tconst AlgorithmBase* algo,\n\t\t\t\t\tModelTMSCoilAlgorithm::Args& args )\n\t\t\t\t\t:\n\t\t\t\t\tBaseCoilgen( algo, args )\n\t\t\t\t{\n\t\t\t\t\tcoilLayers = coilLayers == 0 ? 1 : coilLayers;\n\t\t\t\t}\n\n\t\t\t\t~CircularWireCoilgen()\n\t\t\t\t{\n\t\t\t\t}\n\n\n\t\t\t\tvirtual void Generate(FieldHandle& meshHandle) const\n\t\t\t\t{\n\t\t\t\t\tstd::vector<Vector> coilPoints;\n\t\t\t\t\tstd::vector<size_t> coilIndices;\n\t\t\t\t\tstd::vector<double> coilValues;\n\n\n\n\t\t\t\t\tVector step(0,0,coilLayersStep);\n\n\t\t\t\t\tdouble dr = 0.0;\n\t\t\t\t\tif(rings > 1)\n\t\t\t\t\t\tdr = (outerR - innerR) / (rings - 1);\n\n\t\t\t\t\tif(coilType == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t//Vector origin(0, 0, -0.5*(1.0/coilLayers));\n\t\t\t\t\t\tVector origin(0, 0, -coilLayersStep*(coilLayers/2) );\n\n\t\t\t\t\t\tfor(size_t l = 0; l < coilLayers; l++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (size_t i = 0; i < rings; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tClosedSegments segments(coilPoints,coilIndices,coilValues);\n\t\t\t\t\t\t\t\tGenPointsCircular(segments, origin, innerR + i*dr, current, 0.0 , 2*M_PI );\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\torigin += step;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\telse if(coilType == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector originLeft ( -outerR - (outerD/2), 0.0, -coilLayersStep*(coilLayers/2) );\n\t\t\t\t\t\tVector originRight(  outerR + (outerD/2), 0.0, -coilLayersStep*(coilLayers/2) );\n\n\t\t\t\t\t\tauto transLeft = Transform::Identity();\n\t\t\t\t\t\ttransLeft.post_rotate(M_PI*(wingsAngle/180),{0,1,0});\n\n\t\t\t\t\t\tauto transRight = Transform::Identity();\n\t\t\t\t\t\ttransRight.post_rotate(M_PI*(-wingsAngle/180),{0,1,0});\n\n\n\t\t\t\t\t\tfor(size_t l = 0; l < coilLayers; l++)\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tfor (size_t i = 0; i < rings; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tClosedSegments segments(coilPoints,coilIndices,coilValues);\n\t\t\t\t\t\t\t\tGenPointsCircular(segments, originLeft, innerR + i*dr, current, 0.0 , 2*M_PI );\n\t\t\t\t\t\t\t\tsegments.Transform(transLeft);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\toriginLeft += step;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor(size_t l = coilLayers; l < 2*coilLayers; l++)\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tfor (size_t i = 0; i < rings; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tClosedSegments segments(coilPoints,coilIndices,coilValues);\n\t\t\t\t\t\t\t\tGenPointsCircular(segments, originRight, innerR + i*dr, -current, 0.0 , 2*M_PI);\n\t\t\t\t\t\t\t\tsegments.Transform(transRight);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\toriginRight += step;\n\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\talgo->error(\"coil type value expeced: 1/2 (0-shape/8-shape)\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\n\t\t\t\t\t//SCIrun API creating a new mesh\n\t\t\t\t\t//0 data on elements; 1 data on nodes\n\t\t\t\t\tFieldInformation fi(\"CurveMesh\",0,\"double\");\n\t\t\t\t\tfi.make_curvemesh();\n\t\t\t\t\tfi.make_constantdata();\n\t\t\t\t\tfi.make_scalar();\n\n\t\t\t\t\tmeshHandle = CreateField(fi);\n\n\t\t\t\t\tBuildScirunMesh(coilPoints,coilIndices,coilValues,meshHandle);\n\t\t\t\t}\n\n\t\t};\n\n\t\t//! piece-wise wire discretization\n\t\tclass MultiloopsCoilgen : public BaseCoilgen\n\t\t{\n\t\t\tpublic:\n\n\t\t\t\tMultiloopsCoilgen(\n\t\t\t\t\tconst AlgorithmBase* algo,\n\t\t\t\t\tModelTMSCoilAlgorithm::Args args )\n\t\t\t\t\t:\n\t\t\t\t\tBaseCoilgen( algo, args )\n\t\t\t\t{\n\t\t\t\t\tcoilLayers = coilLayers == 0 ? 1 : coilLayers;\n\n\t\t\t\t\t//no auto current adjustment for each layer\n\t\t\t\t\t//hidden functionality (rather be explicit up front)\n\t\t\t\t\t//leave it up to users judgment\n\n\t\t\t\t}\n\n\t\t\t\t~MultiloopsCoilgen()\n\t\t\t\t{\n\t\t\t\t}\n\n\t\t\t\tvirtual void Generate(FieldHandle& meshHandle) const\n\t\t\t\t{\n\t\t\t\t\tstd::vector<Vector> coilPoints;\n\t\t\t\t\tstd::vector<size_t> coilIndices;\n\t\t\t\t\tstd::vector<double> coilValues;\n\n\t\t\t\t\tVector step(0,0,coilLayersStep);\n\n\n\n\t\t\t\t\tif(coilType == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t//Vector origin(0, 0, -0.5*(1.0/coilLayers));\n\t\t\t\t\t\tVector origin(0, 0, -coilLayersStep*(coilLayers/2) );\n\n\t\t\t\t\t\tfor(size_t l = 0; l < coilLayers; l++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tOpenSegments segments( coilPoints, coilIndices, coilValues );\n\n\t\t\t\t\t\t\t///SINGLE coil\n\t\t\t\t\t\t\tGenPointsSpiralLeft(segments, origin);\n\t\t\t\t\t\t\torigin += step;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\telse if(coilType == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector originLeft ( -outerR - (outerD/2), 0.0, -coilLayersStep*(coilLayers/2) );\n\t\t\t\t\t\tVector originRight(  outerR + (outerD/2), 0.0, -coilLayersStep*(coilLayers/2) );\n\n\t\t\t\t\t\tfor(size_t l = 0; l < coilLayers; l++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tOpenSegments segments( coilPoints, coilIndices, coilValues );\n\n\t\t\t\t\t\t\t//LEFT coil\n\t\t\t\t\t\t\tGenPointsSpiralLeft(segments, originLeft);\n\n\t\t\t\t\t\t\toriginLeft += step;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor(size_t l = coilLayers; l < 2*coilLayers; l++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tOpenSegments segments( coilPoints, coilIndices, coilValues );\n\n\t\t\t\t\t\t\t//RIGHT coil\n\t\t\t\t\t\t\tGenPointsSpiralRight(segments, originRight);\n\n\t\t\t\t\t\t\toriginRight += step;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\talgo->error(\"coil type value expeced: 1/2 (0-shape/8-shape)\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\n\n\t\t\t\t\t//SCIrun API creating a new mesh\n\t\t\t\t\t//0 data on elements; 1 data on nodes\n\t\t\t\t\tFieldInformation fi(\"CurveMesh\",0,\"double\");\n\t\t\t\t\tfi.make_curvemesh();\n\t\t\t\t\tfi.make_constantdata();\n\t\t\t\t\tfi.make_scalar();\n\n\t\t\t\t\tmeshHandle = CreateField(fi);\n\n\t\t\t\t\tBuildScirunMesh(coilPoints,coilIndices,coilValues,meshHandle);\n\t\t\t\t}\n\n\t\t\tprotected:\n\n\t\t\t\tvoid GenPointsSpiralLeft(OpenSegments& segments, Vector center) const\n\n\t\t\t\t{\n\t\t\t\t\tdouble dr = (outerR - innerR) / rings;\n\n\t\t\t\t\tVector center_offset (center.x() + dr/2, center.y(), center.z() );\n\n\t\t\t\t\tfor (size_t i = 0; i < rings; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tGenPointsCircular(segments, center, innerR + i*dr, current, 0   , M_PI, i );\n\n\t\t\t\t\t\tGenPointsCircular(segments, center_offset, innerR + i*dr + dr/2, current, M_PI, 2*M_PI, i );\n\t\t\t\t\t}\n\n\t\t\t\t\t//TODO refactor to avoid this\n\t\t\t\t\tVector endp(center.x() + outerR * cos(2*M_PI), center.y() + outerR * sin(2*M_PI), center.z());\n\t\t\t\t\tsegments.AddPoint(endp, current);\n\t\t\t\t}\n\n\t\t\t\tvoid GenPointsSpiralRight(OpenSegments& segments, Vector center) const\n\t\t\t\t{\n\t\t\t\t\tdouble dr = (outerR - innerR) / rings;\n\n\t\t\t\t\tVector center_offset( center.x() + dr/2, center.y(), center.z() );\n\n\t\t\t\t\tfor (size_t i = rings; i > 0; i--)\n\t\t\t\t\t{\n\t\t\t\t\t\tGenPointsCircular(segments, center, innerR + i*dr, -current, M_PI, 2*M_PI, i );\n\n\t\t\t\t\t\tGenPointsCircular(segments, center_offset, innerR + i*dr - dr/2, -current, 0, M_PI, i );\n\t\t\t\t\t}\n\n\t\t\t\t\t//TODO refactor to avoid this\n\t\t\t\t\tVector endp(center.x() + innerR * cos(M_PI), center.y() + innerR * sin(M_PI), center.z());\n\t\t\t\t\tsegments.AddPoint(endp, -current);\n\t\t\t\t}\n\n\t\t\t\t/// this is tricky but doable, the idea is to distribute the current along each coil winding\n\t\t\t\t/// so that the top surface flux is not linear but curved (bell shaped like)\n\t\t\t\t/// this is required since in the AC profile there is inter-winding coupling increasing the resistivity of the net\n\t\t\t\t/// please see: https://en.wikipedia.org/wiki/Proximity_effect_%28electromagnetism%29\n\t\t\t\tvoid AdjustForProximityEffect()\n\t\t\t\t{\n\n\t\t\t\t}\n\n\t\t};\n\n\n\n\t\t//! dipoles domain discretization\n\t\t// (replicating paper doi:10.1006/nimg.2002.1282)\n\t\tclass DipolesCoilgen : public BaseCoilgen\n\t\t{\n\t\t\tpublic:\n\n\t\t\t\tDipolesCoilgen(\n\t\t\t\t\tconst AlgorithmBase* algo,\n\t\t\t\t\tModelTMSCoilAlgorithm::Args args )\n\t\t\t\t\t:\n\t\t\t\t\tBaseCoilgen( algo, args )\n\n\t\t\t\t{\n\t\t\t\t\tcoilLayers = coilLayers == 0 ? 1 : coilLayers;\n\n\t\t\t\t}\n\n\t\t\t\t~DipolesCoilgen()\n\t\t\t\t{\n\t\t\t\t}\n\n\t\t\t\tvirtual void Generate(FieldHandle& meshHandle) const\n\t\t\t\t{\n\t\t\t\t\tstd::vector<Vector> dipolePoints;\n\t\t\t\t\tstd::vector<Vector> dipoleValues;\n\t\t\t\t\t//std::vector<size_t> coilIndices;\n\n\t\t\t\t\t//std::vector<double> radiiInner = preRadiiInner();\n\t\t\t\t\t//std::vector<double> radiiOuter = preRadiiOuter();\n\t\t\t\t\t//std::vector<double> numElements = preNumElem(radiiInner);\n\t\t\t\t\t//std::vector<double> numCoupling = preNumAdjElem(radiiInner);\n\n\n\t\t\t\t\t//print_vector(radiiInner);\n\t\t\t\t\t//print_vector(radiiOuter);\n\n\t\t\t\t\t//print_vector(numElements);\n\t\t\t\t\t//print_vector(numCoupling);\n\n\t\t\t\t\t//assert(radiiInner.size() == radiiOuter.size());\n\n\n\t\t\t\t\t//algo->remark(\"#Rings:  \" +  boost::lexical_cast<std::string>(radiiOuter.size()) + \" ring-step:\" + boost::lexical_cast<std::string>(lod_step_m));\n\n\t\t\t\t\tVector step(0,0,coilLayersStep);\n\n\t\t\t\t\tdouble dr = 0.0;\n\t\t\t\t\tif(rings > 1)\n\t\t\t\t\t\tdr = (outerR - innerR) / (rings - 1);\n\n\n\t\t\t\t\tif(coilType == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector origin(0, 0, -coilLayersStep*(coilLayers/2) );\n\n\t\t\t\t\t\tfor(size_t l = 0; l < coilLayers; l++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble dipoleMoment = 0;\n\t\t\t\t\t\t\tfor (size_t i = 0; i < rings; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdouble ringArea = M_PI * (innerR + i*dr) * (innerR + i*dr);\n\t\t\t\t\t\t\t\tdipoleMoment += current * ringArea;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tVector dipoleNormL(0,0,1.0*dipoleMoment);\n\t\t\t\t\t\t\tdipolePoints.push_back(origin);\n\t\t\t\t\t\t\tdipoleValues.push_back(dipoleNormL);\n\n\t\t\t\t\t\t\torigin += step;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(coilType == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector originLeft ( -outerR - (outerD/2), 0.0, -coilLayersStep*(coilLayers/2) );\n\t\t\t\t\t\tVector originRight(  outerR + (outerD/2), 0.0, -coilLayersStep*(coilLayers/2) );\n\n\t\t\t\t\t\tauto transLeft = Transform::Identity();\n\t\t\t\t\t\ttransLeft.post_rotate(M_PI*(wingsAngle/180),{0,1,0});\n\n\t\t\t\t\t\tauto transRight = Transform::Identity();\n\t\t\t\t\t\ttransRight.post_rotate(M_PI*(-wingsAngle/180),{0,1,0});\n\n\t\t\t\t\t\tfor(size_t l = 0; l < coilLayers; l++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble dipoleMoment = 0;\n\t\t\t\t\t\t\tfor (size_t i = 0; i < rings; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdouble ringArea = M_PI * (innerR + i*dr) * (innerR + i*dr);\n\t\t\t\t\t\t\t\tdipoleMoment += current * ringArea;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tVector dipoleNormL(0,0,1.0*dipoleMoment);\n\t\t\t\t\t\t\tdipoleNormL = transLeft * dipoleNormL;\n\t\t\t\t\t\t\tVector originLeftTrans = transLeft * originLeft;\n\t\t\t\t\t\t\tdipolePoints.push_back(originLeftTrans);\n\t\t\t\t\t\t\tdipoleValues.push_back(dipoleNormL);\n\n\t\t\t\t\t\t\toriginLeft += step;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor(size_t l = 0; l < coilLayers; l++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdouble dipoleMoment = 0;\n\t\t\t\t\t\t\tfor (size_t i = 0; i < rings; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdouble ringArea = M_PI * (innerR + i*dr) * (innerR + i*dr);\n\t\t\t\t\t\t\t\tdipoleMoment += current * ringArea;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tVector dipoleNormR(0,0,-1.0*dipoleMoment);\n\t\t\t\t\t\t\tdipoleNormR = transRight * dipoleNormR;\n\t\t\t\t\t\t\tVector originRightTrans = transRight * originRight;\n\t\t\t\t\t\t\tdipolePoints.push_back(originRightTrans);\n\t\t\t\t\t\t\tdipoleValues.push_back(dipoleNormR);\n\n\t\t\t\t\t\t\toriginRight += step;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\talgo->error(\"coil type value expeced: 1/2 (0-shape/8-shape)\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\n\t\t\t\t\t///basic topoly assumptions needs to be correct\n\t\t\t\t\tassert(dipolePoints.size() > 0);\n\t\t\t\t\tassert(dipolePoints.size() == dipoleValues.size());\n\n\n\t\t\t\t\t///SCIrun API creating a new mesh\n\t\t\t\t\t///0 data on elements; 1 data on nodes\n\t\t\t\t\tFieldInformation fi(\"PointCloudMesh\",1,\"vector\");\n\t\t\t\t\tfi.make_pointcloudmesh();\n\t\t\t\t\tfi.make_lineardata();\n\t\t\t\t\tfi.make_vector();\n\n\t\t\t\t\tmeshHandle = CreateField(fi);\n\n\t\t\t\t\tBuildScirunMesh(dipolePoints,dipoleValues,meshHandle);\n\t\t\t\t}\n\n\t\tprotected:\n\n\n\t\t\t\tvoid print_vector(const std::vector<double>& v) const\n\t\t\t\t{\n\t\t\t\t\tstd::cout << std::endl;\n\t\t\t\t\tfor(int i=0;i<v.size();++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << v[i] << \" \";\n\t\t\t\t\t}\n\t\t\t\t\tstd::cout << std::endl;\n\t\t\t\t}\n\n\t\t\t\tconst std::vector<double> preRadiiInner() const\n\t\t\t\t{\n\t\t\t\t\tstd::vector<double> preRadii;\n\n\t\t\t\t\tdouble step = (outerR - innerR) / rings;\n\n\t\t\t\t\tdouble d = innerR;\n\n\t\t\t\t\t//add first element\n\t\t\t\t\t//preRadii.push_back(0.00d);\n\n\t\t\t\t\twhile( d < outerR)\n\t\t\t\t\t{\n\t\t\t\t\t\tpreRadii.push_back(d);\n\t\t\t\t\t\td += step;\n\t\t\t\t\t}\n\n\n\t\t\t\t\t//const double vals[16] = {0.00d, 0.003d, 0.007d, 0.011d, 0.015d, 0.019d, 0.023d, 0.026d, 0.028d, 0.030d, 0.032d, 0.034d, 0.036d, 0.038d, 0.040d, 0.042d};\n\t\t\t\t\t//std::vector<double> preRadii(vals,vals+16);\n\t\t\t\t\treturn preRadii;\n\t\t\t\t}\n\n\t\t\t\tconst std::vector<double> preRadiiOuter() const\n\t\t\t\t{\n\t\t\t\t\tstd::vector<double> preRadii;\n\n\t\t\t\t\tdouble step = (outerR - innerR) / rings;\n\n\t\t\t\t\tdouble d = innerR;\n\n\t\t\t\t\t//add first element\n\t\t\t\t\t//preRadii.push_back(d);\n\n\t\t\t\t\twhile( d < outerR)\n\t\t\t\t\t{\n\t\t\t\t\t\td += step;\n\t\t\t\t\t\tpreRadii.push_back(d);\n\t\t\t\t\t}\n\n\t\t\t\t\t//add last\n\t\t\t\t\t//preRadii.push_back(outerR);\n\n\t\t\t\t\t//override last to fill to exacct outer radius\n\t\t\t\t\tpreRadii[preRadii.size()-1u] = outerR;\n\n\n\t\t\t\t\t//const double vals[16] = {0.003d, 0.007d, 0.011d, 0.015d, 0.019d, 0.023d, 0.026d, 0.028d, 0.030d, 0.032d, 0.034d, 0.036d, 0.038d, 0.040d, 0.042d, 0.044d};\n\t\t\t\t\t//std::vector<double> preRadii(vals,vals+16);\n\t\t\t\t\treturn preRadii;\n\t\t\t\t}\n\n\t\t\t\tconst std::vector<double> preNumElem(std::vector<double>& radii) const\n\t\t\t\t{\n\t\t\t\t\tstd::vector<double> preNumElem;\n\n\t\t\t\t\tfor(size_t i = 1; i <= radii.size(); ++i)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tsize_t n = M_PI_2 / (1.0 / ( radii[i]* coilLOD ) );\n\n\t\t\t\t\t\t//size_t n = segments +  ( pow(i,1.5) / coilLOD );\n\t\t\t\t\t\tpreNumElem.push_back(n);\n\t\t\t\t\t}\n\n\t\t\t\t\t//const double vals[16] = {3.0d, 9.0d, 12.0d, 16.0d, 20.0d, 24.0d, 28.0d, 30.0d, 32.0d, 34.0d, 36.0d, 38.0d, 40.0d, 42.0d, 44.0d, 44.0d};\n\t\t\t\t\t//std::vector<double> preNumElem(vals,vals+16);\n\t\t\t\t\treturn preNumElem;\n\n\t\t\t\t}\n\n\t\t\t\tconst std::vector<double> preNumAdjElem(std::vector<double>& radii) const\n\t\t\t\t{\n\t\t\t\t\tstd::vector<double> preNumAdjElem;\n\n\t\t\t\t\tfor(size_t i = 1; i <= radii.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tpreNumAdjElem.push_back(1.0);\n\t\t\t\t\t}\n\n\t\t\t\t\t//const double vals[16] = {9.0d, 9.0d, 9.0d, 9.0d, 9.0d, 9.0d, 9.0d, 9.0d, 8.0d, 7.0d, 6.0d, 5.0d, 4.0d, 3.0d, 2.0d, 1.0d};\n\t\t\t\t\t//std::vector<double> preNumAdjElem(vals,vals+16);\n\t\t\t\t\treturn preNumAdjElem;\n\t\t\t\t}\n\n\t\t\t\tvoid GenSegmentValues(const std::vector<Vector>& points, std::vector<Vector>& values, Vector val) const\n\t\t\t\t{\n\t\t\t\t\tassert(points.size() > 0);\n\n\t\t\t\t\tfor(size_t i = values.size(); i < points.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tvalues.push_back(val);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsize_t GenPointsCircular2(\n\t\t\t\t\tstd::vector<Vector>& points,\n\t\t\t\t\tVector origin,\n\t\t\t\t\tdouble radius,\n\t\t\t\t\tdouble fromPI,\n\t\t\t\t\tdouble toPI,\n\t\t\t\t\tdouble extLOD) const\n\t\t\t\t{\n\n\t\t\t\t\tdouble dPI = fabs(toPI - fromPI);\n\n\t\t\t\t\tdouble minPI = M_PI /  ( 8.0 * coilLOD + coilLOD * extLOD );\n\n\t\t\t\t\tassert(dPI > minPI);\n\n\t\t\t\t\tsize_t nsegments = 2;\n\t\t\t\t\tdouble iPI = dPI / nsegments;\n\n\t\t\t\t\twhile(iPI > minPI)\n\t\t\t\t\t{\n\t\t\t\t\t\tnsegments++;\n\t\t\t\t\t\tiPI = dPI / nsegments;\n\t\t\t\t\t}\n\n\t\t\t\t\t//algo->remark(\"#Segments(LOD):  \" +  boost::lexical_cast<std::string>(nsegments) );\n\n\t\t\t\t\tdPI = toPI - fromPI;\n\n\t\t\t\t\tiPI = dPI / nsegments;\n\n\t\t\t\t\tfor(size_t i = 0; i < nsegments; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector point(origin.x() + radius * cos(fromPI + iPI*i), origin.y() + radius * sin(fromPI + iPI*i), origin.z());\n\t\t\t\t\t\t//segments.AddPoint(point,value);\n\t\t\t\t\t\tpoints.push_back(point);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn nsegments;\n\t\t\t\t}\n\n\t\t\t\tvoid BuildScirunMesh(const std::vector<Vector>& points,\n\t\t\t\t\t\tconst std::vector<Vector>& values,\n\t\t\t\t\t\tFieldHandle& meshHandle) const\n\t\t\t\t{\n\n\t\t\t\t\tVMesh* mesh = meshHandle->vmesh();\n\n\t\t\t\t\t//! add nodes to the new mesh\n\t\t\t\t\tfor(size_t i = 0; i < points.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Point p(points[i]);\n\t\t\t\t\t\tmesh->add_point(p);\n\t\t\t\t\t}\n\n\t\t\t\t\t//! add data to mesh\n\t\t\t\t\tVField* field = meshHandle->vfield();\n\t\t\t\t\tfield->resize_values();\n\t\t\t\t\tfield->set_values(values);\n\t\t\t\t}\n\t\t};\n\n\nint ResolveAlgoName(std::string& name)\n{\n\tif(name == \"Thin Circular Wires\")\n\t{\n\t\treturn 0;\n\t}\n\n\tif(name == \"Thin Spiral Wires\")\n\t{\n\t\treturn 1;\n\t}\n\n\tif(name == \"Magnetic Dipoles\")\n\t{\n\t\treturn 2;\n\t}\n\n\treturn 0;\n\n}\n\n\nstd::unique_ptr<BaseCoilgen> AlgoSelector(int idx,const AlgorithmBase* scirunAlgoBase, ModelTMSCoilAlgorithm::Args args)\n{\n\tswitch(idx)\n\t{\n\t\tcase 0: return std::unique_ptr<BaseCoilgen>(new CircularWireCoilgen(scirunAlgoBase,args));\n\t\tcase 1: return std::unique_ptr<BaseCoilgen>(new MultiloopsCoilgen(scirunAlgoBase,args));\n\t\tcase 2: return std::unique_ptr<BaseCoilgen>(new DipolesCoilgen(scirunAlgoBase,args));\n\t\tdefault: return std::unique_ptr<BaseCoilgen>(new CircularWireCoilgen(scirunAlgoBase,args));\n\t}\n\n}\n\n\nAlgorithmOutput ModelTMSCoilAlgorithm::run(const AlgorithmInput& input) const\n{\n\tAlgorithmOutput output;\n\tFieldHandle ofield;\n\n\tstd::string model_type = static_cast<std::string>(get(Parameters::Type).toString());\n\t//int model_type = static_cast<int>(get(Parameters::Type).toInt());\n\t//remark(\"model_type:  \" +  boost::lexical_cast<std::string>(model_type) );\n\n\tModelTMSCoilAlgorithm::Args algoArgs;\n\talgoArgs.current = static_cast<double>(get(Parameters::Current).toDouble())*1e6; ///MD: here is the unit scaling, wire current module input is in [megaA/s]\n\talgoArgs.rings = static_cast<size_t>(get(Parameters::Rings).toInt());\n\talgoArgs.wingsAngle = static_cast<double>(get(Parameters::WingsAngle).toDouble());\n\talgoArgs.coilRadiusInner = static_cast<double>(get(Parameters::InnerRadius).toDouble());\n\talgoArgs.coilRadiusOuter = static_cast<double>(get(Parameters::OuterRadius).toDouble());\n\talgoArgs.coilLayers = static_cast<size_t>(get(Parameters::Layers).toInt());\n\talgoArgs.coilLevelDetails = static_cast<size_t>(get(Parameters::LevelOfDetail).toInt());\n\talgoArgs.coilLayersStep = static_cast<double>(get(Parameters::LayerStepSize).toDouble());\n\talgoArgs.coilDistance = static_cast<double>(get(Parameters::Distance).toDouble());\n\talgoArgs.type = get(Parameters::FigureOf8CoilShape).toInt() ? 2 : 1;\n\n\tauto algo = AlgoSelector(ResolveAlgoName(model_type),this,algoArgs);\n\t//auto algo = AlgoSelector(model_type,this,algoArgs);\n\n\talgo->Execute(ofield);\n\n\toutput[Parameters::Mesh] = ofield;\n\treturn output;\n}\n", "meta": {"hexsha": "b4c25a94ba55f2cb11a00dfb50c90b938889f6f5", "size": 24973, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/BrainStimulator/ModelGenericCoilAlgorithm.cc", "max_stars_repo_name": "Nahusa/SCIRun", "max_stars_repo_head_hexsha": "c54e714d4c7e956d053597cf194e07616e28a498", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T06:00:15.000Z", "max_issues_repo_path": "src/Core/Algorithms/BrainStimulator/ModelGenericCoilAlgorithm.cc", "max_issues_repo_name": "manual123/SCIRun", "max_issues_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/BrainStimulator/ModelGenericCoilAlgorithm.cc", "max_forks_repo_name": "manual123/SCIRun", "max_forks_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7188465499, "max_line_length": 160, "alphanum_fraction": 0.6241941297, "num_tokens": 7422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.03021458892306662, "lm_q1q2_score": 0.014871262193614362}}
{"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 <algorithm>\n#include <stdexcept>\n#include <map>\n#include <utility>\n#include <algorithm>\n#include <string>\n#include <iostream>\n#include <time.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <hashclash/saveload_gz.hpp>\n#include <hashclash/md5detail.hpp>\n#include <hashclash/rng.hpp>\n#include <hashclash/differentialpath.hpp>\n#include <hashclash/progress_display.hpp>\n\n#include \"main.hpp\"\n\nusing namespace hashclash;\nusing namespace std;\n\nvoid random_permutation(vector<differentialpath>& paths)\n{\n\t// use a pseudo-random permutation fixed by the number of paths\n\tseed(paths.size());\n\tfor (unsigned i = 0; i < paths.size(); ++i)\n\t{\n\t\tunsigned k = xrng64() % paths.size();\n\t\tpaths[i].swap(paths[k]);\n\t}\n\taddseed(time(NULL));\n}\n\ninline std::string pathsstring(const std::string& basepath, unsigned modi, unsigned modn)\n{\n\treturn workdir +  \"/\"  + basepath \n\t\t+ \"_\" + boost::lexical_cast<std::string>(modi) \n\t\t+ \"of\" + boost::lexical_cast<std::string>(modn);\n}\n\n\n\n\n\n\n\n// map: (dQ1, dF1) => (count, Q1_set0, Q1_set1)\ntypedef map< pair<sdr,sdr>, pair<unsigned, pair<uint32, uint32> > > step1diffs_type;\nvoid generate_step1diffs(step1diffs_type& step1diffs, const path_container_autobalance& container)\n{\n\tconst unsigned m = container.modn;\n\tconst unsigned i = container.modi;\n\tconst uint32* m_diff = container.m_diff;\n\n\tuint32 Q1[4], Q2[4];\n\tQ1[0] = container.IHV1[0]; Q1[1] = container.IHV1[3]; Q1[2] = container.IHV1[2]; Q1[3] = container.IHV1[1];\n\tQ2[0] = container.IHV2[0]; Q2[1] = container.IHV2[3]; Q2[2] = container.IHV2[2]; Q2[3] = container.IHV2[1];\n\n\tstep1diffs_type::iterator step1diffs_it, step1diffs_it2;\n\tuint32 Ta = md5_ff(Q1[3], Q1[2], Q1[1]) + Q1[0] + md5_ac[0];\n\tuint32 Tb = md5_ff(Q2[3], Q2[2], Q2[1]) + Q2[0] + md5_ac[0] + m_diff[0];\n\n\tuint64 endcount = uint64(1)<<32;\n\tuint64 count = 0;\n\tunsigned k = 0;\n\tprogress_display show_progress(endcount, true, cout, \"t=0:  \", \"      \", \"      \");\n\tuint32 Q1a, Fa, Q1b, Fb;\n\tsdr dQ1, dF;\n\tpair<sdr,sdr> index;\t\n\tfor (uint64 count = 0; count < endcount; ++count,++show_progress,++Ta,++Tb)\n\t{\n\t\t++k;\n\t\tif (k == m) k = 0;\n\t\tif (k != i) continue;\n\t\t\n\t\tQ1a = rotate_left(Ta, 7) + Q1[Qoff+0];\n\t\tFa = md5_ff(Q1a, Q1[Qoff+0], Q1[Qoff-1]);\n\t\tQ1b = rotate_left(Tb, 7) + Q2[Qoff+0];\n\t\tFb = md5_ff(Q1b, Q2[Qoff+0], Q2[Qoff-1]);\n\t\tdQ1.set(Q1a, Q1b);\n\t\tdF.set(Fa, Fb);\n\n\t\tindex.first = dQ1; index.second = dF;\n\t\tstep1diffs_it = step1diffs.find(index);\n\t\tif (step1diffs_it == step1diffs.end()) {\n\t\t\tpair<unsigned, pair<uint32, uint32> > tmp;\n\t\t\ttmp.first = 1;\n\t\t\ttmp.second.first = Q1a;\n\t\t\ttmp.second.second = Q1a;\n\t\t\tstep1diffs[index] = tmp;\n\t\t} else {\n\t\t\t++step1diffs_it->second.first;\n\t\t\tstep1diffs_it->second.second.first |= Q1a;\n\t\t\tstep1diffs_it->second.second.second &= Q1a;\n\t\t}\n\t}\t\t\n}\n\nvoid combine_step1diffs(step1diffs_type& global_step1diffs, const step1diffs_type& step1diffs)\n{\n\tstep1diffs_type::const_iterator step1diffs_it;\n\tstep1diffs_type::iterator step1diffs_it2;\n\tfor (step1diffs_it = step1diffs.begin(); step1diffs_it != step1diffs.end(); ++step1diffs_it)\n\t{\n\t\tstep1diffs_it2 = global_step1diffs.find(step1diffs_it->first);\n\t\tif (step1diffs_it2 == global_step1diffs.end())\n\t\t\tglobal_step1diffs.insert(*step1diffs_it);\n\t\telse {\n\t\t\tstep1diffs_it2->second.first += step1diffs_it->second.first;\n\t\t\tstep1diffs_it2->second.second.first |= step1diffs_it->second.second.first;\n\t\t\tstep1diffs_it2->second.second.second &= step1diffs_it->second.second.second;\n\t\t}\n\t}\n}\n\nvoid dostep0(const path_container_autobalance& container)\n{\n\t// map: (dQ1, dF1) => (count, Q1_set0, Q1_set1)\n\tmap< pair<sdr,sdr>, pair<unsigned, pair<uint32, uint32> > >\t\t\tstep1diffs;\n\tmap< pair<sdr,sdr>, pair<unsigned, pair<uint32, uint32> > >::iterator\tstep1diffs_it, step1diffs_it2;\n\n\tcout << \"Searching first step differentials: \" << endl;\n\tgenerate_step1diffs(step1diffs, container);\n\thashclash::save_gz(step1diffs, pathsstring(\"paths0\", container.modi, container.modn), binary_archive);\n\tcout << \"Saved \" << step1diffs.size() << \" first step differentials.\" << endl;\n}\n\nvoid dostep1(const path_container_autobalance& container)\n{\n\tconst unsigned modn = container.modn;\n\tconst unsigned modi = container.modi;\n\n\tmap< pair<sdr,sdr>, pair<unsigned, pair<uint32, uint32> > >\tstep1diffs, step1diffs2;\n\tmap< pair<sdr,sdr>, pair<unsigned, pair<uint32, uint32> > >::iterator\tstep1diffs_it, step1diffs_it2;\n\t\n\tif (modi != 0) return;\n\tfor (unsigned j = 0; j < modn; ++j)\n\t{\n\t\tcout << \"Loading \" << pathsstring(\"paths0\", j, modn) << \"...\" << flush;\n\t\thashclash::load_gz(step1diffs2, pathsstring(\"paths0\", j, modn), binary_archive);\n\t\tcout << \"done.\" << endl;\n\t\tcombine_step1diffs(step1diffs, step1diffs2);\n\t}\n\n\tunsigned count_max = 0;\n\tunsigned count_good = 0;\n\n\tstep1diffs_it2 = step1diffs.begin();\n\tvector<unsigned> countvec;\n\tfor (step1diffs_it = step1diffs.begin(); step1diffs_it != step1diffs.end(); ++step1diffs_it)\n\t{\n\t\tcountvec.push_back(step1diffs_it->second.first);\n\t\tif (step1diffs_it->second.first > count_max)\n\t\t\tcount_max = step1diffs_it->second.first;\n\t}\n\tstd::sort(countvec.begin(), countvec.end());\n\tint countindex = int(countvec.size()) - int(65536);\n\tif (countindex < 0) countindex = 0;\n\tunsigned count_min = countvec[countindex];\n\t\t\n\tuint32 Q1[4], Q2[4];\n\tQ1[0] = container.IHV1[0]; Q1[1] = container.IHV1[3]; Q1[2] = container.IHV1[2]; Q1[3] = container.IHV1[1];\n\tQ2[0] = container.IHV2[0]; Q2[1] = container.IHV2[3]; Q2[2] = container.IHV2[2]; Q2[3] = container.IHV2[1];\n\tdifferentialpath tmp;\n\tfor (int i = -3; i <= 0; ++i)\n\t\ttmp[i].set(Q2[3+i]-Q1[3+i], Q1[3+i], Q1[3+i]);\n\n\tvector< differentialpath > goodpaths;\t\n\tfor (step1diffs_it = step1diffs.begin(); step1diffs_it != step1diffs.end(); ++step1diffs_it)\n\t{\n\t\tif (step1diffs_it->second.first >= count_min)\n\t\t{\n\t\t\t++count_good;\n\t\t\tuint32 dQ1 = step1diffs_it->first.first.adddiff();\n\t\t\tuint32 dF1 = step1diffs_it->first.second.adddiff();\n\t\t\tuint32 dT1 = dF1 + (Q2[Qoff-2]-Q1[Qoff-2]) + container.m_diff[1];\n\t\t\tuint32 dR1 = best_rotated_difference(dT1, 12);\n\t\t\tuint32 dQ2 = dQ1 + dR1;\n\n\t\t\ttmp[1].set( dQ1, step1diffs_it->second.second.first, step1diffs_it->second.second.second );\n\t\t\ttmp[2] = naf(dQ2);\n\t\t\tgoodpaths.push_back(tmp);\n\t\t}\n\t}\n\tcout << \"Saving \" << goodpaths.size() << \" paths...\" << flush;\n\tsave_gz(goodpaths, pathsstring(\"paths1\", modi, modn), binary_archive);\n\tcout << \"done.\" << endl;\n\tif (goodpaths.size() > 0)\n\t\tshow_path(goodpaths[0], container.m_diff);\n}\n\n\n\nprogress_display* dostep_progress = 0;\nunsigned dostep_index = 0;\nstruct dostep_thread {\n\tdostep_thread(vector<differentialpath>& in, path_container_autobalance& out)\n\t\t: pathsin(in), container(out)   \n\t{}\n\tvector<differentialpath>& pathsin;\n\tpath_container_autobalance& container;\n\tmd5_forward_thread worker;\n\tvoid operator()() {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tmut.lock();\n\t\t\t\tunsigned i = dostep_index;\n\t\t\t\tunsigned iend = i + (unsigned(pathsin.size() - dostep_index)>>4);\n\t\t\t\tif (iend > i+4) iend = i+4;\n\t\t\t\tif (iend == i && i < pathsin.size())\n\t\t\t\t\tiend = i+1;\n\t\t\t\tif (iend != i)\n\t\t\t\t\t(*dostep_progress) += iend-i;\n\t\t\t\tdostep_index = iend;\n\t\t\t\tmut.unlock();\n\t\t\t\tif (i >= pathsin.size())\n\t\t\t\t\tbreak;\n\t\t\t\tfor (; i < iend; ++i)\n\t\t\t\t\tworker.md5_forward_differential_step(pathsin[i], container);\n\t\t\t}\n\t\t} catch (std::exception & e) { cerr << \"Worker thread: caught exception:\" << endl << e.what() << endl; } catch (...) {}\n\t}       \n};\nvoid dostep_threaded(vector<differentialpath>& in, path_container_autobalance& out)\n{\n\tdostep_index = 0;\n\tstd::string tstring = \"t=\" + boost::lexical_cast<std::string>(out.t) + \": \";\n\tif (tstring.size() == 5) tstring += \" \";\n\tif (out.estimatefactor)\n\t\tdostep_progress = new progress_display(in.size(), true, cout, tstring, \"      \", \"e     \");\n\telse\n\t\tdostep_progress = new progress_display(in.size(), true, cout, tstring, \"      \", \"      \");\n\tboost::thread_group mythreads;\n\tfor (unsigned i = 0; i < out.threads; ++i)\n\t\tmythreads.create_thread(dostep_thread(in,out));\n\tmythreads.join_all();\n\tif (dostep_progress->expected_count() != dostep_progress->count())\n\t\t*dostep_progress += dostep_progress->expected_count() - dostep_progress->count();\n\tdelete dostep_progress;\n}\n\n\n\n\n\n\n\nvector<differentialpath> pathscache;\nvoid dostep(path_container_autobalance& container, bool savetocache)\n{\n\tconst unsigned t = container.t;\n\tconst unsigned modn = container.modn;\n\tconst unsigned modi = container.modi;\n\n\tif (t == 0 && !container.normalt01) {\n\t\tdostep0(container);\n\t\treturn;\n\t}\n\tif (t == 1 && !container.normalt01) {\n\t\tdostep1(container);\n\t\treturn;\n\t}\n\t\n\tvector< differentialpath > pathsin, pathstmp, pathsout;\n\tif (pathscache.size() != 0) {\n\t\tpathsin.swap(pathscache);\n\t\trandom_permutation(pathsin);\n\t} else if (container.inputfile.size() == 0) {\n\t\tfor (unsigned k = 0; k < modn; ++k)\n\t\t{\n\t\t\ttry {\n\t\t\t\tstd::string filename = pathsstring(\"paths\" + boost::lexical_cast<std::string>(t-1), k, modn);\n\t\t\t\tcout << \"Loading \" << filename << \"...\" << flush;\n\t\t\t\tload_gz(pathstmp, filename, binary_archive);\n\t\t\t\trandom_permutation(pathstmp);\n\t\t\t\tfor (unsigned j = modi; j < pathstmp.size(); j += modn)\n\t\t\t\t\tpathsin.push_back(pathstmp[j]);\n\t\t\t\tcout << \"done: \" << pathstmp.size() << \" (work:\" << pathsin.size() << \").\" << endl;\n\t\t\t} catch(...) {\n\t\t\t\tcout << \"failed.\" << endl;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbool failed = false;\n\t\ttry {\n\t\t\tcout << \"Loading \" << container.inputfile << \"...\" << flush;\n\t\t\tload_gz(pathstmp, binary_archive, container.inputfile);\n\t\t\trandom_permutation(pathstmp);\n\t\t\tfor (unsigned j = modi; j < pathstmp.size(); j += modn)\n\t\t\t\tpathsin.push_back(pathstmp[j]);\n\t\t\tcout << \"done: \" << pathsin.size() << \".\" << endl;\n\t\t} catch(...) {\n\t\t\tfailed = true;\n\t\t\tcout << \"failed.\" << endl;\n\t\t}\n\t\tif (failed) {\n\t\t\ttry {\n\t\t\t\tcout << \"Loading (text) \" << container.inputfile << \"...\" << flush;\n\t\t\t\tload_gz(pathstmp, text_archive, container.inputfile);\n\t\t\t\trandom_permutation(pathstmp);\n\t\t\t\tfor (unsigned j = modi; j < pathstmp.size(); j += modn)\n\t\t\t\t\tpathsin.push_back(pathstmp[j]);\n\t\t\t\tcout << \"done: \" << pathsin.size() << \".\" << endl;\n\t\t\t} catch(...) {\n\t\t\t\tcout << \"failed.\" << endl;\n\t\t\t}\n\t\t}\n\t}\n\tif (container.showinputpaths)\n\t\tfor (unsigned r = 0; r < pathsin.size(); ++r)\n\t\t\tshow_path(pathsin[r], container.m_diff);\n\n\tstd::string tstring = \"t=\" + boost::lexical_cast<std::string>(t) + \": \";\n\tif (tstring.size() == 5) tstring += \" \";\n\t\n\tif (container.estimatefactor != 0) {\n\t\tcout << \"Estimating maxcond for upper bound \" << unsigned(double(container.ubound)*container.estimatefactor)\n\t\t\t<< \" (=\" << container.ubound << \" * \" << container.estimatefactor << \")...\" << endl;\n\t\tdostep_threaded(pathsin, container);\n//\t\tprogress_display show_progress(pathsin.size(), true, cout, tstring, \"      \", \"e     \");\n//\t\tfor (unsigned k = 0; k < pathsin.size(); ++k,++show_progress)\n//\t\t\tmd5_forward_differential_step(pathsin[k], container);\n\t\tcontainer.finish_estimate();\n\t\tcout << \"Found maxcond = \" << container.maxcond << endl;\n\t}\n\n\tdostep_threaded(pathsin, container);\n//\tprogress_display show_progress(pathsin.size(), true, cout, tstring, \"      \", \"      \");\n//\tfor (unsigned k = 0; k < pathsin.size(); ++k,++show_progress)\n//\t\tmd5_forward_differential_step(pathsin[k], container);\n\n\tpathstmp.swap(pathsout);\t\n\tcontainer.export_results(pathsout);\n\t\n\tif (pathsout.size() > 0)\n\t\tshow_path(pathsout[0], container.m_diff);\n\telse\n\t\tthrow std::runtime_error(\"No valid differential paths found!\");\n\tstd::string filenameout = pathsstring(\"paths\" + boost::lexical_cast<std::string>(t), modi, modn);\n\tcout << \"Saving \" << pathsout.size() << \" paths...\" << flush;\n\tif (savetocache)\n\t\tpathscache.swap(pathsout);\n\telse\n\t\tsave_gz(pathsout, filenameout, binary_archive);\n\tcout << \"done.\" << endl;\n}\n", "meta": {"hexsha": "07c88873c97653194e897982d6c9381b894a23ee", "size": 12459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/md5forward/dostep.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/md5forward/dostep.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/md5forward/dostep.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": 33.8559782609, "max_line_length": 121, "alphanum_fraction": 0.6589613934, "num_tokens": 3895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.03067580215375711, "lm_q1q2_score": 0.014858747632500967}}
{"text": "// Written by Angjoo Kanazawa & Abhishek Sharma 2013\n// Implementation of Transformation Invariant Convolution Layer\n// The transformation parameter are set in the transformation variable in layer\n// parameters.\n\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#include <cstdio>\n\n#include \"caffe/layer.hpp\"\n#include \"caffe/vision_layers.hpp\"\n#include \"caffe/util/im2col.hpp\"\n#include \"caffe/filler.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/imshow.hpp\"\n\n#include <opencv2/highgui/highgui.hpp>\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid\nTiedConvolutionLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype> *> &bottom,\n                                        vector<Blob<Dtype> *> *top) {\n  ConvolutionParameter conv_param = this->layer_param_.convolution_param();\n  CHECK(!conv_param.has_kernel_size() !=\n        !(conv_param.has_kernel_h() && conv_param.has_kernel_w()))\n      << \"Filter size is kernel_size OR kernel_h and kernel_w; not both\";\n  CHECK(conv_param.has_kernel_size() ||\n        (conv_param.has_kernel_h() && conv_param.has_kernel_w()))\n      << \"For non-square filters both kernel_h and kernel_w are required.\";\n  CHECK((!conv_param.has_pad() && conv_param.has_pad_h() &&\n         conv_param.has_pad_w()) ||\n        (!conv_param.has_pad_h() && !conv_param.has_pad_w()))\n      << \"pad is pad OR pad_h and pad_w are required.\";\n  CHECK((!conv_param.has_stride() && conv_param.has_stride_h() &&\n         conv_param.has_stride_w()) ||\n        (!conv_param.has_stride_h() && !conv_param.has_stride_w()))\n      << \"Stride is stride OR stride_h and stride_w are required.\";\n  if (conv_param.has_kernel_size()) {\n    kernel_h_ = kernel_w_ = conv_param.kernel_size();\n  } else {\n    kernel_h_ = conv_param.kernel_h();\n    kernel_w_ = conv_param.kernel_w();\n  }\n  CHECK_GT(kernel_h_, 0) << \"Filter dimensions cannot be zero.\";\n  CHECK_GT(kernel_w_, 0) << \"Filter dimensions cannot be zero.\";\n  if (!conv_param.has_pad_h()) {\n    pad_h_ = pad_w_ = conv_param.pad();\n  } else {\n    pad_h_ = conv_param.pad_h();\n    pad_w_ = conv_param.pad_w();\n  }\n  if (!conv_param.has_stride_h()) {\n    stride_h_ = stride_w_ = conv_param.stride();\n  } else {\n    stride_h_ = conv_param.stride_h();\n    stride_w_ = conv_param.stride_w();\n  }\n  // Configure output channels and groups.\n  channels_ = bottom[0]->channels();\n  num_output_ = conv_param.num_output();\n  CHECK_GT(num_output_, 0);\n  group_ = conv_param.group();\n  CHECK_EQ(channels_ % group_, 0);\n  CHECK_EQ(num_output_ % group_, 0)\n      << \"Number of output should be multiples of group.\";\n\n  // Handle the parameters: weights and biases.\n  // - blobs_[0] holds the filter weights\n  // - blobs_[1] holds the biases (optional)\n  bias_term_ = conv_param.bias_term();\n  if (this->blobs_.size() > 0) {\n    LOG(INFO) << \"Skipping parameter initialization\";\n  } else {\n    if (bias_term_) {\n      this->blobs_.resize(2);\n    } else {\n      this->blobs_.resize(1);\n    }\n    // Intialize the weight\n    // output channels x input channels per-group x kernel height x kernel width\n    this->blobs_[0].reset(\n        new Blob<Dtype>(num_output_, channels_ / group_, kernel_h_, kernel_w_));\n    // fill the weights\n    shared_ptr<Filler<Dtype> > weight_filler(\n        GetFiller<Dtype>(conv_param.weight_filler()));\n    weight_filler->Fill(this->blobs_[0].get());\n    // If necessary, intiialize and fill the biases:\n    // 1 x 1 x 1 x output channels.\n    if (bias_term_) {\n      this->blobs_[1].reset(new Blob<Dtype>(1, 1, 1, num_output_));\n      shared_ptr<Filler<Dtype> > bias_filler(GetFiller<Dtype>(\n          conv_param.bias_filler()));\n      bias_filler->Fill(this->blobs_[1].get());\n    }\n  }\n  // Propagate gradients to the parameters (as directed by backward pass).\n  this->param_propagate_down_.resize(this->blobs_.size(), true);\n};\n\ntemplate <typename Dtype>\nvoid TiedConvolutionLayer<Dtype>::Reshape(const vector<Blob<Dtype> *> &bottom,\n                                          vector<Blob<Dtype> *> *top) {\n  num_in_ = bottom.size();           // total number of data to convolve\n  num_ = bottom[0]->num();           // batch\n  CHECK_EQ(bottom[0]->channels(), channels_) << \"Input size incompatible with\"\n    \" convolution kernel.\";\n  height_.resize(num_in_);\n  width_.resize(num_in_);\n  N_.resize(num_in_);\n\n  for (int i = 0; i < num_in_; ++i) {\n    CHECK_EQ(channels_, bottom[i]->channels())\n        << \"channels has to be the same for all bottoms\";\n    CHECK_EQ(num_, bottom[i]->num())\n        << \"batch size has to be the same for all bottoms\";\n    height_[i] = bottom[i]->height();\n    width_[i] = bottom[i]->width();\n  }\n  // Prepare the matrix multiplication computation.\n  M_ = num_output_ / group_;\n  K_ = channels_ * kernel_h_ * kernel_w_ / group_;\n  col_buffers_.resize(num_in_);\n  if (bias_term_) {\n    bias_multipliers_.resize(num_in_);\n  }\n  for (int i = 0; i < num_in_; ++i) {\n    // The im2col result buffer would only hold one image at a time to avoid\n    // overly large memory usage.\n    int height_out = (height_[i] + 2 * pad_h_ - kernel_h_) / stride_h_ + 1;\n    int width_out = (width_[i] + 2 * pad_w_ - kernel_w_) / stride_w_ + 1;\n    // AJ: Conserve on memory by not making diff on col_buffer.\n    this->col_buffers_[i].reset(new Blob<Dtype>(\n        1, channels_ * kernel_h_ * kernel_w_, height_out, width_out, false));\n    // Figure out the dimensions for individual gemms.\n    N_[i] = height_out * width_out;\n    (*top)[i]->Reshape(num_, num_output_, height_out, width_out);\n\n    if (bias_term_) {\n      // Set up the all ones \"bias multiplier\" for adding biases by BLAS\n      // bias_multipliers_[i].reset(new Blob<Dtype>(1, 1, 1, N_[i], false));\n      // caffe_set(N_[i], Dtype(1), bias_multipliers_[i].mutable_cpu_data());\n      bias_multipliers_[i].reset(new SyncedMemory(N_[i] * sizeof(Dtype)));\n      Dtype *bias_multiplier_data =\n          reinterpret_cast<Dtype *>(bias_multipliers_[i]->mutable_cpu_data());\n      for (int j = 0; j < N_[i]; ++j) {\n        bias_multiplier_data[j] = 1.;\n      }\n    }\n  }\n}\n\ntemplate <typename Dtype>\nvoid\nTiedConvolutionLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype> *> &bottom,\n                                         vector<Blob<Dtype> *> *top) {\n  const Dtype *weight = this->blobs_[0]->cpu_data();\n  const int weight_offset = M_ * K_; // number of filter parameters in a group\n  for (int i = 0; i < num_in_; ++i) {\n    //-----Same concept as Forward_cpu of convolutionlayer-----\n    const Dtype *bottom_data = bottom[i]->cpu_data();\n    const int col_offset = K_ * N_[i];\n    const int top_offset = M_ * N_[i];\n    Dtype *top_data = (*top)[i]->mutable_cpu_data();\n    Dtype *col_data = this->col_buffers_[i]->mutable_cpu_data();\n    for (int n = 0; n < num_; ++n) {\n      // im2col transformation: unroll input regions for filtering\n      // into column matrix for multplication.\n      im2col_cpu(bottom_data + bottom[i]->offset(n), channels_, height_[i],\n                 width_[i], kernel_h_, kernel_w_, pad_h_, pad_w_, stride_h_,\n                 stride_w_, col_data);\n      // Take innerproduct for groups.\n      for (int g = 0; g < group_; ++g) {\n        caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, M_, N_[i], K_,\n                              (Dtype)1., weight + weight_offset * g,\n                              col_data + col_offset * g, (Dtype)0.,\n                              top_data + (*top)[i]->offset(n) + top_offset * g);\n      }\n      // Add bias.\n      if (bias_term_) {\n        caffe_cpu_gemm<Dtype>(\n            CblasNoTrans, CblasNoTrans, num_output_, N_[i], 1, (Dtype)1.,\n            this->blobs_[1]->cpu_data(),\n            reinterpret_cast<const Dtype *>(bias_multipliers_[i]->cpu_data()),\n            (Dtype)1., top_data + (*top)[i]->offset(n));\n      }\n    }\n    //---------------------------------------------------------\n  }\n}\n\ntemplate <typename Dtype>\nvoid\nTiedConvolutionLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype> *> &bottom,\n                                         vector<Blob<Dtype> *> *top) {\n\n  const Dtype *weight = this->blobs_[0]->gpu_data();\n  const int weight_offset = M_ * K_;\n  for (int i = 0; i < num_in_; ++i) {\n    //-----Same concept as Forward_gpu of convolutionlayer-----\n    const Dtype *bottom_data = bottom[i]->gpu_data();\n    const int col_offset = K_ * N_[i];\n    const int top_offset = M_ * N_[i];\n    Dtype *top_data = (*top)[i]->mutable_gpu_data();\n    Dtype *col_data = this->col_buffers_[i]->mutable_gpu_data();\n    for (int n = 0; n < num_; ++n) {\n      // First, im2col\n      im2col_gpu(bottom_data + bottom[i]->offset(n), channels_, height_[i],\n                 width_[i], kernel_h_, kernel_w_, pad_h_, pad_w_, stride_h_,\n                 stride_w_, col_data);\n      // Second, innerproduct with groups.\n      for (int g = 0; g < group_; ++g) {\n        caffe_gpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, M_, N_[i], K_,\n                              (Dtype)1., weight + weight_offset * g,\n                              col_data + col_offset * g, (Dtype)0.,\n                              top_data + (*top)[i]->offset(n) + top_offset * g);\n      }\n      // third, add bias\n      if (bias_term_) {\n        caffe_gpu_gemm<Dtype>(\n            CblasNoTrans, CblasNoTrans, num_output_, N_[i], 1, (Dtype)1.,\n            this->blobs_[1]->gpu_data(),\n            reinterpret_cast<const Dtype *>(bias_multipliers_[i]->gpu_data()),\n            (Dtype)1., top_data + (*top)[i]->offset(n));\n      }\n    }\n    //---------------------------------------------------------\n  }\n  // montage(this->blobs_[0].get(), \"tconv\" +\n  // boost::lexical_cast<std::string>(M_));\n}\n\ntemplate <typename Dtype>\nvoid\nTiedConvolutionLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype> *> &top,\n                                          const vector<bool> &propagate_down,\n                                          vector<Blob<Dtype> *> *bottom) {\n  //-----Same concept as Backward_cpu of convolutionlayer-----\n  // but multiple times for each bottom-top pair, and accumulating dW\n  const Dtype *weight = NULL;\n  Dtype *weight_diff = NULL;\n  if (this->param_propagate_down_[0]) {\n    weight = this->blobs_[0]->cpu_data();\n    weight_diff = this->blobs_[0]->mutable_cpu_diff();\n    // Init weight diff to all 0s.\n    caffe_set(this->blobs_[0]->count(), Dtype(0), weight_diff);\n  }\n  // bias gradient if necessary\n  Dtype *bias_diff = NULL;\n  if (bias_term_ && this->param_propagate_down_[1]) {\n    bias_diff = this->blobs_[1]->mutable_cpu_diff();\n    caffe_set(this->blobs_[1]->count(), Dtype(0), bias_diff);\n  }\n\n  const int weight_offset = M_ * K_;\n  for (int i = 0; i < num_in_; ++i) {\n    const Dtype *top_diff = NULL;\n    // Bias gradient if necessary.\n    if (bias_term_ && this->param_propagate_down_[1]) {\n      top_diff = top[i]->cpu_diff();\n      for (int n = 0; n < num_; ++n) {\n        caffe_cpu_gemv<Dtype>(\n            CblasNoTrans, num_output_, N_[i], 1., top_diff + top[i]->offset(n),\n            reinterpret_cast<const Dtype *>(bias_multipliers_[i]->cpu_data()),\n            1., bias_diff);\n      }\n    }\n    if (this->param_propagate_down_[0] || propagate_down[i]) {\n      if (!top_diff) {\n        top_diff = top[i]->cpu_diff();\n      }\n      Dtype* col_data = this->col_buffers_[i]->mutable_cpu_data();\n      const Dtype* bottom_data = (*bottom)[i]->cpu_data();\n      Dtype* bottom_diff = (*bottom)[i]->mutable_cpu_diff();\n\n      const int col_offset = K_ * N_[i];\n      const int top_offset = M_ * N_[i];\n      for (int n = 0; n < num_; ++n) {\n\t// Since we saved memory in the forward pass by not storing all col\n\t// data, we will need to recompute them.\n\tim2col_cpu(bottom_data + (*bottom)[i]->offset(n), channels_, height_[i],\n\t\t   width_[i], kernel_h_, kernel_w_, pad_h_, pad_w_, stride_h_,\n\t\t   stride_w_, col_data);\n\t// gradient w.r.t. weight. Note that we will accumulate diffs.\n\t// AJ: propagate error Delta W_ij = error from above * this_activation^T\n        if (this->param_propagate_down_[0]) {\n\t  for (int g = 0; g < group_; ++g) {\n\t    caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, M_, K_, N_[i],\n\t\t\t\t  (Dtype)1.,\n\t\t\t\t  top_diff + top[i]->offset(n) + top_offset * g,\n\t\t\t\t  col_data + col_offset * g, (Dtype)1.,\n\t\t\t\t  weight_diff + weight_offset * g);\n\t  }\n\t}\n\t// gradient w.r.t. bottom data, if necessary\n\t// AJ: error here = W*error from above\n\tif (propagate_down[i]) {\n          if (weight == NULL) {\n            weight = this->blobs_[0]->cpu_data();\n          }\n\t  for (int g = 0; g < group_; ++g) {\n\t    caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans, K_, N_[i], M_,\n\t\t\t\t  (Dtype)1., weight + weight_offset * g,\n\t\t\t\t  top_diff + top[i]->offset(n) + top_offset * g,\n\t\t\t\t  (Dtype)0., col_data + col_offset * g);\n\t  }\n\t  // col2im back to the data\n\t  col2im_cpu(col_data, channels_, height_[i], width_[i], kernel_h_,\n\t\t     kernel_w_, pad_h_, pad_w_, stride_h_, stride_w_,\n\t\t     bottom_diff + (*bottom)[i]->offset(n));\n\t}\n      }\n    }\n    //---------------------------------------------------------\n  }\n}\n\ntemplate <typename Dtype>\nvoid\nTiedConvolutionLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype> *> &top,\n                                          const vector<bool> &propagate_down,\n                                          vector<Blob<Dtype> *> *bottom) {\n  const Dtype *weight = NULL;\n  Dtype *weight_diff = NULL;\n  if (this->param_propagate_down_[0]) {\n    weight = this->blobs_[0]->gpu_data();\n    weight_diff = this->blobs_[0]->mutable_gpu_diff();\n    // Init weight diffs to all 0s.\n    caffe_gpu_set(this->blobs_[0]->count(), Dtype(0), weight_diff);\n  }\n  Dtype *bias_diff = NULL;\n  if (bias_term_ && this->param_propagate_down_[1]) {\n    bias_diff = this->blobs_[1]->mutable_gpu_diff();\n    caffe_gpu_set(this->blobs_[1]->count(), Dtype(0), bias_diff);\n  }\n\n  const int weight_offset = M_ * K_;\n  for (int i = 0; i < num_in_; ++i) {\n    //-----Same concept as Backward_cpu of convolutionlayer-----\n    const Dtype* top_diff = NULL;\n    // Bias gradient if necessary\n    if (bias_term_ && this->param_propagate_down_[1]) {\n      top_diff = top[i]->gpu_diff();\n      for (int n = 0; n < num_; ++n) {\n        caffe_gpu_gemv<Dtype>(\n            CblasNoTrans, num_output_, N_[i], 1., top_diff + top[i]->offset(n),\n            reinterpret_cast<const Dtype *>(bias_multipliers_[i]->gpu_data()),\n            1., bias_diff);\n      }\n    }\n    if (this->param_propagate_down_[0] || propagate_down[i]) {\n      if (!top_diff) {\n        top_diff = top[i]->gpu_diff();\n      }\n      Dtype* col_data = this->col_buffers_[i]->mutable_gpu_data();\n      const Dtype* bottom_data = (*bottom)[i]->gpu_data();\n      Dtype* bottom_diff = (*bottom)[i]->mutable_gpu_diff();\n\n      const int col_offset = K_ * N_[i];\n      const int top_offset = M_ * N_[i];\n      for (int n = 0; n < num_; ++n) {\n\t// Since we saved memory in the forward pass by not storing all col data,\n\t// we will need to recompute them.\n\tim2col_gpu(bottom_data + (*bottom)[i]->offset(n), channels_, height_[i],\n                   width_[i], kernel_h_, kernel_w_, pad_h_, pad_w_,\n                   stride_h_, stride_w_, col_data);\n\t// gradient w.r.t. weight. Note that we will accumulate diffs.\n        if (this->param_propagate_down_[0]) {\n\t  for (int g = 0; g < group_; ++g) {\n\t    caffe_gpu_gemm<Dtype>(CblasNoTrans, CblasTrans, M_, K_, N_[i],\n\t\t\t\t  (Dtype)1.,\n\t\t\t\t  top_diff + top[i]->offset(n) + top_offset * g,\n\t\t\t\t  col_data + col_offset * g, (Dtype)1.,\n\t\t\t\t  weight_diff + weight_offset * g);\n\t  }\n\t}\n\t// gradient w.r.t. bottom data, if necessary\n\tif (propagate_down[i]) {\n          if (weight == NULL) {\n            weight = this->blobs_[0]->gpu_data();\n          }\n\t  for (int g = 0; g < group_; ++g) {\n\t    caffe_gpu_gemm<Dtype>(CblasTrans, CblasNoTrans, K_, N_[i], M_,\n\t\t\t\t  (Dtype)1., weight + weight_offset * g,\n\t\t\t\t  top_diff + top[i]->offset(n) + top_offset * g,\n\t\t\t\t  (Dtype)0., col_data + col_offset * g);\n\t  }\n\t  // col2im back to the data\n\t  col2im_gpu(col_data, channels_, height_[i], width_[i], kernel_h_,\n\t\t     kernel_w_, pad_h_, pad_w_, stride_h_, stride_w_,\n\t\t     bottom_diff + (*bottom)[i]->offset(n));\n\t}\n      }\n    }\n    // montage_channels(this->blobs_[0].get(),\n    // boost::lexical_cast<std::string>(M_) + \" tconv bprop \" +\n    // boost::lexical_cast<std::string>(i) , true);\n    //// make sure to give back the pointer to gpu after visualization\n    // weight_diff = this->blobs_[0]->mutable_gpu_diff();\n  } // end for each input\n    // montage_channels(this->blobs_[0].get(), \"final tconv bprop \" +\n    // boost::lexical_cast<std::string>(M_), true);\n    // cv::waitKey(0);\n}\n\ntemplate <typename Dtype>\nvoid TiedConvolutionLayer<Dtype>::Report(const std::string &name) {\n  // montage(this->blobs_[0].get(), name + \" tconv\");\n  // montage(this->blobs_[0].get(), name + \" tconv bprop\", true);\n  // // cv::waitKey(0);\n  // fprintf(stderr, \"%s tied-conv W_diff:\\n\", name.c_str());\n  // Blob<Dtype>* W = this->blobs_[0].get();\n  // for (int h = 0; h < W->height(); ++h) {\n  //   for (int w = 0; w < W->width(); ++w) {\n  //     fprintf(stderr, \"%.2g \", (W->diff_at(0, 0, h, w)));\n  //   }\n  //   fprintf(stderr, \"\\n\");\n  // }\n}\n\nINSTANTIATE_CLASS(TiedConvolutionLayer);\n} // namespace caffe\n", "meta": {"hexsha": "294d844ee136c9a48813dfddf153342d92fa0bae", "size": 17120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/1-si-convnet/src/caffe/layers/tiedconv_layer.cpp", "max_stars_repo_name": "wsgdrfz/Scale-invariant-CNNs", "max_stars_repo_head_hexsha": "4c136b45213ce1d5568b501791ff694868bfc4ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T10:52:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T01:50:37.000Z", "max_issues_repo_path": "src/caffe/1-si-convnet/src/caffe/layers/tiedconv_layer.cpp", "max_issues_repo_name": "wsgdrfz/Antialiased-SSCNN", "max_issues_repo_head_hexsha": "4c136b45213ce1d5568b501791ff694868bfc4ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-24T09:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-29T06:37:30.000Z", "max_forks_repo_path": "src/caffe/1-si-convnet/src/caffe/layers/tiedconv_layer.cpp", "max_forks_repo_name": "wsgdrfz/SIE-CNN", "max_forks_repo_head_hexsha": "4c136b45213ce1d5568b501791ff694868bfc4ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-23T13:31:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T05:56:11.000Z", "avg_line_length": 40.4728132388, "max_line_length": 80, "alphanum_fraction": 0.6040303738, "num_tokens": 4708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.03161876897961665, "lm_q1q2_score": 0.014822582992425629}}
{"text": "//\n//  Copyright (c) 2003\n//  Gunter Winkler, Joerg Walter\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_OF_VECTOR_\n#define _BOOST_UBLAS_VECTOR_OF_VECTOR_\n\n#include <boost/type_traits.hpp>\n\n#include <boost/numeric/ublas/storage_sparse.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n\n// Iterators based on ideas of Jeremy Siek\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    // uBLAS sparse vector based sparse matrix class\n    // FIXME outer vector can be sparse type but it is completely filled\n    template<class T, class L, class A>\n    class generalized_vector_of_vector:\n        public matrix_container<generalized_vector_of_vector<T, L, A> > {\n\n        typedef T &true_reference;\n        typedef T *pointer;\n        typedef const T *const_pointer;\n        typedef L layout_type;\n        typedef generalized_vector_of_vector<T, L, A> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_container<self_type>::operator ();\n#endif\n        typedef typename A::size_type size_type;\n        typedef typename A::difference_type difference_type;\n        typedef T value_type;\n        typedef const T &const_reference;\n#ifndef BOOST_UBLAS_STRICT_VECTOR_SPARSE\n        typedef T &reference;\n#else\n        typedef sparse_matrix_element<self_type> reference;\n#endif\n        typedef A array_type;\n        typedef const matrix_reference<const self_type> const_closure_type;\n        typedef matrix_reference<self_type> closure_type;\n        typedef typename A::value_type vector_data_value_type;\n        typedef vector_data_value_type vector_temporary_type;\n        typedef self_type matrix_temporary_type;\n        typedef sparse_tag storage_category;\n        typedef typename L::orientation_category orientation_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector ():\n            matrix_container<self_type> (),\n            size1_ (0), size2_ (0), data_ (1) {\n            const size_type sizeM = layout_type::size_M (size1_, size2_);\n             // create size1+1 empty vector elements\n            data_.insert_element (sizeM, vector_data_value_type ());\n            storage_invariants ();\n        }\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector (size_type size1, size_type size2, size_type non_zeros = 0):\n            matrix_container<self_type> (),\n            size1_ (size1), size2_ (size2), data_ (layout_type::size_M (size1_, size2_) + 1) {\n            const size_type sizeM = layout_type::size_M (size1_, size2_);\n            const size_type sizem = layout_type::size_m (size1_, size2_);\n            for (size_type i = 0; i < sizeM; ++ i) // create size1 vector elements\n                data_.insert_element (i, vector_data_value_type ()) .resize (sizem, false);\n            data_.insert_element (sizeM, vector_data_value_type ());\n            storage_invariants ();\n        }\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector (const generalized_vector_of_vector &m):\n            matrix_container<self_type> (),\n            size1_ (m.size1_), size2_ (m.size2_), data_ (m.data_) {\n            storage_invariants ();\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector (const matrix_expression<AE> &ae, size_type non_zeros = 0):\n            matrix_container<self_type> (),\n            size1_ (ae ().size1 ()), size2_ (ae ().size2 ()), data_ (layout_type::size_M (size1_, size2_) + 1) {\n            const size_type sizeM = layout_type::size_M (size1_, size2_);\n            const size_type sizem = layout_type::size_m (size1_, size2_);\n            for (size_type i = 0; i < sizeM; ++ i) // create size1 vector elements\n                data_.insert_element (i, vector_data_value_type ()) .resize (sizem, false);\n            data_.insert_element (sizeM, vector_data_value_type ());\n            storage_invariants ();\n            matrix_assign<scalar_assign> (*this, ae);\n        }\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return size1_;\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return size2_;\n        }\n        BOOST_UBLAS_INLINE\n        size_type nnz_capacity () const {\n            size_type non_zeros = 0;\n            for (const_vectoriterator_type itv = data_.begin (); itv != data_.end (); ++ itv)\n                non_zeros += (*itv).nnz_capacity ();\n            return non_zeros;\n        }\n        BOOST_UBLAS_INLINE\n        size_type nnz () const {\n            size_type non_zeros = 0;\n            for (const_vectoriterator_type itv = data_.begin (); itv != data_.end (); ++ itv)\n                non_zeros += (*itv).nnz ();\n            return non_zeros;\n        }\n\n        // Storage accessors\n        BOOST_UBLAS_INLINE\n        const array_type &data () const {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        array_type &data () {\n            return data_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size1, size_type size2, bool preserve = true) {\n            const size_type oldM = layout_type::size_M (size1_, size2_);\n            size1_ = size1;\n            size2_ = size2;\n            const size_type sizeM = layout_type::size_M (size1_, size2_);\n            const size_type sizem = layout_type::size_m (size1_, size2_);\n            data ().resize (sizeM + 1, preserve);\n            if (preserve) {\n                for (size_type i = 0; (i <= oldM) && (i < sizeM); ++ i)\n                    ref (data () [i]).resize (sizem, preserve);\n                for (size_type i = oldM+1; i < sizeM; ++ i) // create new vector elements\n                    data_.insert_element (i, vector_data_value_type ()) .resize (sizem, false);\n                if (sizeM > oldM) {\n                    data_.insert_element (sizeM, vector_data_value_type ());\n                } else {\n                    ref (data () [sizeM]).resize (0, false);\n                }\n            } else {\n                for (size_type i = 0; i < sizeM; ++ i)\n                    data_.insert_element (i, vector_data_value_type ()) .resize (sizem, false);\n                data_.insert_element (sizeM, vector_data_value_type ());\n            }\n            storage_invariants ();\n        }\n\n        // Element support\n        BOOST_UBLAS_INLINE\n        pointer find_element (size_type i, size_type j) {\n            return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i, j));\n        }\n        BOOST_UBLAS_INLINE\n        const_pointer find_element (size_type i, size_type j) const {\n            const size_type elementM = layout_type::index_M (i, j);\n            const size_type elementm = layout_type::index_m (i, j);\n            // optimise: check the storage_type and index directly if element always exists\n            if (boost::is_convertible<typename array_type::storage_category, packed_tag>::value) {\n                return & (data () [elementM] [elementm]);\n            }\n            else {\n                const typename array_type::value_type *pv = data ().find_element (elementM);\n                if (!pv)\n                    return 0;\n                return pv->find_element (elementm);\n            }\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            const_pointer p = find_element (i, j);\n            // optimise: check the storage_type and index directly if element always exists\n            if (boost::is_convertible<typename array_type::storage_category, packed_tag>::value) {\n                BOOST_UBLAS_CHECK (p, internal_logic () );\n                return *p;\n            }\n            else {\n                if (p)\n                    return *p;\n                else\n                    return zero_;\n            }\n        }\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i, size_type j) {\n#ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE\n            return at_element (i, j);\n#else\n            return reference (*this, i, j);\n#endif\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector &operator = (const generalized_vector_of_vector &m) {\n            if (this != &m) {\n                size1_ = m.size1_;\n                size2_ = m.size2_;\n                data () = m.data ();\n            }\n            storage_invariants ();\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector &assign_temporary (generalized_vector_of_vector &m) {\n            swap (m);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector &operator = (const matrix_expression<AE> &ae) {\n            self_type temporary (ae);\n            return assign_temporary (temporary);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector &assign (const matrix_expression<AE> &ae) {\n            matrix_assign<scalar_assign> (*this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector& operator += (const matrix_expression<AE> &ae) {\n            self_type temporary (*this + ae);\n            return assign_temporary (temporary);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector &plus_assign (const matrix_expression<AE> &ae) {\n            matrix_assign<scalar_plus_assign> (*this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector& operator -= (const matrix_expression<AE> &ae) {\n            self_type temporary (*this - ae);\n            return assign_temporary (temporary);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector &minus_assign (const matrix_expression<AE> &ae) {\n            matrix_assign<scalar_minus_assign> (*this, ae);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector& operator *= (const AT &at) {\n            matrix_assign_scalar<scalar_multiplies_assign> (*this, at);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        generalized_vector_of_vector& operator /= (const AT &at) {\n            matrix_assign_scalar<scalar_divides_assign> (*this, at);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (generalized_vector_of_vector &m) {\n            if (this != &m) {\n                std::swap (size1_, m.size1_);\n                std::swap (size2_, m.size2_);\n                data ().swap (m.data ());\n            }\n            storage_invariants ();\n        }\n        BOOST_UBLAS_INLINE\n        friend void swap (generalized_vector_of_vector &m1, generalized_vector_of_vector &m2) {\n            m1.swap (m2);\n        }\n\n        // Sorting\n        void sort () {\n            vectoriterator_type itv (data ().begin ());\n            vectoriterator_type itv_end (data ().end ());\n            while (itv != itv_end) {\n                (*itv).sort ();\n                ++ itv;\n            }\n        }\n\n        // Element insertion and erasure\n        BOOST_UBLAS_INLINE\n        true_reference insert_element (size_type i, size_type j, const_reference t) {\n            const size_type elementM = layout_type::index_M (i, j);\n            const size_type elementm = layout_type::index_m (i, j);\n            vector_data_value_type& vd (ref (data () [elementM]));\n            storage_invariants ();\n            return vd.insert_element (elementm, t);\n        }\n        BOOST_UBLAS_INLINE\n        void append_element (size_type i, size_type j, const_reference t) {\n            const size_type elementM = layout_type::index_M (i, j);\n            const size_type elementm = layout_type::index_m (i, j);\n            vector_data_value_type& vd (ref (data () [elementM]));\n            storage_invariants ();\n            return vd.append_element (elementm, t);\n        }\n        BOOST_UBLAS_INLINE\n        void erase_element (size_type i, size_type j) {\n            vectoriterator_type itv (data ().find (layout_type::index_M (i, j)));\n            if (itv == data ().end ())\n                return;\n            (*itv).erase_element (layout_type::index_m (i, j));\n            storage_invariants ();\n        }\n        BOOST_UBLAS_INLINE\n        void clear () {\n            const size_type sizeM = layout_type::size_M (size1_, size2_);\n            // FIXME should clear data () if this is done via value_type/*zero*/() then it is not size preserving\n            for (size_type i = 0; i < sizeM; ++ i)\n                ref (data () [i]).clear ();\n            storage_invariants ();\n        }\n\n        // Iterator types\n    private:\n        // Use vector iterator\n        typedef typename A::const_iterator const_vectoriterator_type;\n        typedef typename A::iterator vectoriterator_type;\n        typedef typename A::value_type::const_iterator const_subiterator_type;\n        typedef typename A::value_type::iterator subiterator_type;\n\n        BOOST_UBLAS_INLINE\n        true_reference at_element (size_type i, size_type j) {\n            return ref (ref (data () [layout_type::index_M (i, j)]) [layout_type::index_m (i, j)]);\n        }\n\n    public:\n        class const_iterator1;\n        class iterator1;\n        class const_iterator2;\n        class iterator2;\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base1<iterator1> reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n        typedef reverse_iterator_base2<iterator2> reverse_iterator2;\n\n        // Element lookup\n        // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n        const_iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) const {\n            for (;;) {\n                const_vectoriterator_type itv (data ().find (layout_type::index_M (i, j)));\n                const_vectoriterator_type itv_end (data ().end ());\n                if (itv == itv_end)\n                    return const_iterator1 (*this, rank, i, j, itv_end, (*(-- itv)).end ());\n\n                const_subiterator_type it ((*itv).find (layout_type::index_m (i, j)));\n                const_subiterator_type it_end ((*itv).end ());\n                if (rank == 0)\n                    return const_iterator1 (*this, rank, i, j, itv, it);\n                if (it != it_end && it.index () == layout_type::index_m (i, j))\n                    return const_iterator1 (*this, rank, i, j, itv, it);\n                if (direction > 0) {\n                    if (layout_type::fast_i ()) {\n                        if (it == it_end)\n                            return const_iterator1 (*this, rank, i, j, itv, it);\n                        i = it.index ();\n                    } else {\n                        if (i >= size1_)\n                            return const_iterator1 (*this, rank, i, j, itv, it);\n                        ++ i;\n                    }\n                } else /* if (direction < 0)  */ {\n                    if (layout_type::fast_i ()) {\n                        if (it == (*itv).begin ())\n                            return const_iterator1 (*this, rank, i, j, itv, it);\n                        --it;\n                        i = it.index ();\n                    } else {\n                        if (i == 0)\n                            return const_iterator1 (*this, rank, i, j, itv, it);\n                        -- i;\n                    }\n                }\n            }\n        }\n        // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n        iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) {\n            for (;;) {\n                vectoriterator_type itv (data ().find (layout_type::index_M (i, j)));\n                vectoriterator_type itv_end (data ().end ());\n                if (itv == itv_end)\n                    return iterator1 (*this, rank, i, j, itv_end, (*(-- itv)).end ());\n\n                subiterator_type it ((*itv).find (layout_type::index_m (i, j)));\n                subiterator_type it_end ((*itv).end ());\n                if (rank == 0)\n                    return iterator1 (*this, rank, i, j, itv, it);\n                if (it != it_end && it.index () == layout_type::index_m (i, j))\n                    return iterator1 (*this, rank, i, j, itv, it);\n                if (direction > 0) {\n                    if (layout_type::fast_i ()) {\n                        if (it == it_end)\n                            return iterator1 (*this, rank, i, j, itv, it);\n                        i = it.index ();\n                    } else {\n                        if (i >= size1_)\n                            return iterator1 (*this, rank, i, j, itv, it);\n                        ++ i;\n                    }\n                } else /* if (direction < 0)  */ {\n                    if (layout_type::fast_i ()) {\n                        if (it == (*itv).begin ())\n                            return iterator1 (*this, rank, i, j, itv, it);\n                        --it;\n                        i = it.index ();\n                    } else {\n                        if (i == 0)\n                            return iterator1 (*this, rank, i, j, itv, it);\n                        -- i;\n                    }\n                }\n            }\n        }\n        // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n        const_iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) const {\n            for (;;) {\n                const_vectoriterator_type itv (data ().find (layout_type::index_M (i, j)));\n                const_vectoriterator_type itv_end (data ().end ());\n                if (itv == itv_end)\n                    return const_iterator2 (*this, rank, i, j, itv_end, (*(-- itv)).end ());\n\n                const_subiterator_type it ((*itv).find (layout_type::index_m (i, j)));\n                const_subiterator_type it_end ((*itv).end ());\n                if (rank == 0)\n                    return const_iterator2 (*this, rank, i, j, itv, it);\n                if (it != it_end && it.index () == layout_type::index_m (i, j))\n                    return const_iterator2 (*this, rank, i, j, itv, it);\n                if (direction > 0) {\n                    if (layout_type::fast_j ()) {\n                        if (it == it_end)\n                            return const_iterator2 (*this, rank, i, j, itv, it);\n                        j = it.index ();\n                    } else {\n                        if (j >= size2_)\n                            return const_iterator2 (*this, rank, i, j, itv, it);\n                        ++ j;\n                    }\n                } else /* if (direction < 0)  */ {\n                    if (layout_type::fast_j ()) {\n                        if (it == (*itv).begin ())\n                            return const_iterator2 (*this, rank, i, j, itv, it);\n                        --it;\n                        j = it.index ();\n                    } else {\n                        if (j == 0)\n                            return const_iterator2 (*this, rank, i, j, itv, it);\n                        -- j;\n                    }\n                }\n            }\n        }\n        // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it.\n        iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) {\n            for (;;) {\n                vectoriterator_type itv (data ().find (layout_type::index_M (i, j)));\n                vectoriterator_type itv_end (data ().end ());\n                if (itv == itv_end)\n                    return iterator2 (*this, rank, i, j, itv_end, (*(-- itv)).end ());\n\n                subiterator_type it ((*itv).find (layout_type::index_m (i, j)));\n                subiterator_type it_end ((*itv).end ());\n                if (rank == 0)\n                    return iterator2 (*this, rank, i, j, itv, it);\n                if (it != it_end && it.index () == layout_type::index_m (i, j))\n                    return iterator2 (*this, rank, i, j, itv, it);\n                if (direction > 0) {\n                    if (layout_type::fast_j ()) {\n                        if (it == it_end)\n                            return iterator2 (*this, rank, i, j, itv, it);\n                        j = it.index ();\n                    } else {\n                        if (j >= size2_)\n                            return iterator2 (*this, rank, i, j, itv, it);\n                        ++ j;\n                    }\n                } else /* if (direction < 0)  */ {\n                    if (layout_type::fast_j ()) {\n                        if (it == (*itv).begin ())\n                            return iterator2 (*this, rank, i, j, itv, it);\n                        --it;\n                        j = it.index ();\n                    } else {\n                        if (j == 0)\n                            return iterator2 (*this, rank, i, j, itv, it);\n                        -- j;\n                    }\n                }\n            }\n        }\n\n\n        class const_iterator1:\n            public container_const_reference<generalized_vector_of_vector>,\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\n                                               const_iterator1, value_type> {\n        public:\n            typedef typename generalized_vector_of_vector::difference_type difference_type;\n            typedef typename generalized_vector_of_vector::value_type value_type;\n            typedef typename generalized_vector_of_vector::const_reference reference;\n            typedef const typename generalized_vector_of_vector::pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &m, int rank, size_type i, size_type j, const const_vectoriterator_type &itv, const const_subiterator_type &it):\n                container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const iterator1 &it):\n                container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                if (rank_ == 1 && layout_type::fast_i ())\n                    ++ it_;\n                else {\n                    const self_type &m = (*this) ();\n                    i_ = index1 () + 1;\n                    if (rank_ == 1 && ++ itv_ == m.end1 ().itv_)\n                        *this = m.find1 (rank_, i_, j_, 1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index2 () != j_)\n                            *this = m.find1 (rank_, i_, j_, 1);\n                    }\n                }\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                if (rank_ == 1 && layout_type::fast_i ())\n                    -- it_;\n                else {\n                    const self_type &m = (*this) ();\n                    i_ = index1 () - 1;\n                    if (rank_ == 1 && -- itv_ == m.end1 ().itv_)\n                        *this = m.find1 (rank_, i_, j_, -1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index2 () != j_)\n                            *this = m.find1 (rank_, i_, j_, -1);\n                    }\n                }\n                return *this;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ());\n                BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ());\n                if (rank_ == 1) {\n                    return *it_;\n                } else {\n                    return (*this) () (i_, j_);\n                }\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                const self_type &m = (*this) ();\n                return m.find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                const self_type &m = (*this) ();\n                return m.find2 (1, index1 (), m.size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_M (itv_.index (), it_.index ()) < (*this) ().size1 (), bad_index ());\n                    return layout_type::index_M (itv_.index (), it_.index ());\n                } else {\n                    return i_;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_m (itv_.index (), it_.index ()) < (*this) ().size2 (), bad_index ());\n                    return layout_type::index_m (itv_.index (), it_.index ());\n                } else {\n                    return j_;\n                }\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                rank_ = it.rank_;\n                i_ = it.i_;\n                j_ = it.j_;\n                itv_ = it.itv_;\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ());\n                if (rank_ == 1 || it.rank_ == 1) {\n                    return it_ == it.it_;\n                } else {\n                    return i_ == it.i_ && j_ == it.j_;\n                }\n            }\n\n        private:\n            int rank_;\n            size_type i_;\n            size_type j_;\n            const_vectoriterator_type itv_;\n            const_subiterator_type it_;\n        };\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1_, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n        class iterator1:\n            public container_reference<generalized_vector_of_vector>,\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\n                                               iterator1, value_type> {\n        public:\n            typedef typename generalized_vector_of_vector::difference_type difference_type;\n            typedef typename generalized_vector_of_vector::value_type value_type;\n            typedef typename generalized_vector_of_vector::true_reference reference;\n            typedef typename generalized_vector_of_vector::pointer pointer;\n\n            typedef iterator2 dual_iterator_type;\n            typedef reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            iterator1 ():\n                container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {}\n            BOOST_UBLAS_INLINE\n            iterator1 (self_type &m, int rank, size_type i, size_type j, const vectoriterator_type &itv, const subiterator_type &it):\n                container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            iterator1 &operator ++ () {\n                if (rank_ == 1 && layout_type::fast_i ())\n                    ++ it_;\n                else {\n                    self_type &m = (*this) ();\n                    i_ = index1 () + 1;\n                    if (rank_ == 1 && ++ itv_ == m.end1 ().itv_)\n                        *this = m.find1 (rank_, i_, j_, 1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index2 () != j_)\n                            *this = m.find1 (rank_, i_, j_, 1);\n                    }\n                }\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator1 &operator -- () {\n                if (rank_ == 1 && layout_type::fast_i ())\n                    -- it_;\n                else {\n                    self_type &m = (*this) ();\n                    i_ = index1 () - 1;\n                    if (rank_ == 1 && -- itv_ == m.end1 ().itv_)\n                        *this = m.find1 (rank_, i_, j_, -1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index2 () != j_)\n                            *this = m.find1 (rank_, i_, j_, -1);\n                    }\n                }\n                return *this;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            true_reference operator * () const {\n                BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ());\n                BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ());\n                if (rank_ == 1) {\n                    return *it_;\n                } else {\n                    return (*this) ().at_element (i_, j_);\n                }\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            iterator2 begin () const {\n                self_type &m = (*this) ();\n                return m.find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            iterator2 end () const {\n                self_type &m = (*this) ();\n                return m.find2 (1, index1 (), m.size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            reverse_iterator2 rbegin () const {\n                return reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            reverse_iterator2 rend () const {\n                return reverse_iterator2 (begin ());\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_M (itv_.index (), it_.index ()) < (*this) ().size1 (), bad_index ());\n                    return layout_type::index_M (itv_.index (), it_.index ());\n                } else {\n                    return i_;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_m (itv_.index (), it_.index ()) < (*this) ().size2 (), bad_index ());\n                    return layout_type::index_m (itv_.index (), it_.index ());\n                } else {\n                    return j_;\n                }\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            iterator1 &operator = (const iterator1 &it) {\n                container_reference<self_type>::assign (&it ());\n                rank_ = it.rank_;\n                i_ = it.i_;\n                j_ = it.j_;\n                itv_ = it.itv_;\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const iterator1 &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ());\n                if (rank_ == 1 || it.rank_ == 1) {\n                    return it_ == it.it_;\n                } else {\n                    return i_ == it.i_ && j_ == it.j_;\n                }\n            }\n\n        private:\n            int rank_;\n            size_type i_;\n            size_type j_;\n            vectoriterator_type itv_;\n            subiterator_type it_;\n\n            friend class const_iterator1;\n        };\n\n        BOOST_UBLAS_INLINE\n        iterator1 begin1 () {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        iterator1 end1 () {\n            return find1 (0, size1_, 0);\n        }\n\n        class const_iterator2:\n            public container_const_reference<generalized_vector_of_vector>,\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\n                                               const_iterator2, value_type> {\n        public:\n            typedef typename generalized_vector_of_vector::difference_type difference_type;\n            typedef typename generalized_vector_of_vector::value_type value_type;\n            typedef typename generalized_vector_of_vector::const_reference reference;\n            typedef const typename generalized_vector_of_vector::pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &m, int rank, size_type i, size_type j, const const_vectoriterator_type &itv, const const_subiterator_type &it):\n                container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const iterator2 &it):\n                container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                if (rank_ == 1 && layout_type::fast_j ())\n                    ++ it_;\n                else {\n                    const self_type &m = (*this) ();\n                    j_ = index2 () + 1;\n                    if (rank_ == 1 && ++ itv_ == m.end2 ().itv_)\n                        *this = m.find2 (rank_, i_, j_, 1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index1 () != i_)\n                            *this = m.find2 (rank_, i_, j_, 1);\n                    }\n                }\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                if (rank_ == 1 && layout_type::fast_j ())\n                    -- it_;\n                else {\n                    const self_type &m = (*this) ();\n                    j_ = index2 () - 1;\n                    if (rank_ == 1 && -- itv_ == m.end2 ().itv_)\n                        *this = m.find2 (rank_, i_, j_, -1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index1 () != i_)\n                            *this = m.find2 (rank_, i_, j_, -1);\n                    }\n                }\n                return *this;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ());\n                BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ());\n                if (rank_ == 1) {\n                    return *it_;\n                } else {\n                    return (*this) () (i_, j_);\n                }\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                const self_type &m = (*this) ();\n                return m.find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                const self_type &m = (*this) ();\n                return m.find1 (1, m.size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_M (itv_.index (), it_.index ()) < (*this) ().size1 (), bad_index ());\n                    return layout_type::index_M (itv_.index (), it_.index ());\n                } else {\n                    return i_;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_m (itv_.index (), it_.index ()) < (*this) ().size2 (), bad_index ());\n                    return layout_type::index_m (itv_.index (), it_.index ());\n                } else {\n                    return j_;\n                }\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                rank_ = it.rank_;\n                i_ = it.i_;\n                j_ = it.j_;\n                itv_ = it.itv_;\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ());\n                if (rank_ == 1 || it.rank_ == 1) {\n                    return it_ == it.it_;\n                } else {\n                    return i_ == it.i_ && j_ == it.j_;\n                }\n            }\n\n        private:\n            int rank_;\n            size_type i_;\n            size_type j_;\n            const_vectoriterator_type itv_;\n            const_subiterator_type it_;\n        };\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2_);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        class iterator2:\n            public container_reference<generalized_vector_of_vector>,\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\n                                               iterator2, value_type> {\n        public:\n            typedef typename generalized_vector_of_vector::difference_type difference_type;\n            typedef typename generalized_vector_of_vector::value_type value_type;\n            typedef typename generalized_vector_of_vector::true_reference reference;\n            typedef typename generalized_vector_of_vector::pointer pointer;\n\n            typedef iterator1 dual_iterator_type;\n            typedef reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            iterator2 ():\n                container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {}\n            BOOST_UBLAS_INLINE\n            iterator2 (self_type &m, int rank, size_type i, size_type j, const vectoriterator_type &itv, const subiterator_type &it):\n                container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            iterator2 &operator ++ () {\n                if (rank_ == 1 && layout_type::fast_j ())\n                    ++ it_;\n                else {\n                    self_type &m = (*this) ();\n                    j_ = index2 () + 1;\n                    if (rank_ == 1 && ++ itv_ == m.end2 ().itv_)\n                        *this = m.find2 (rank_, i_, j_, 1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index1 () != i_)\n                            *this = m.find2 (rank_, i_, j_, 1);\n                    }\n                }\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator2 &operator -- () {\n                if (rank_ == 1 && layout_type::fast_j ())\n                    -- it_;\n                else {\n                    self_type &m = (*this) ();\n                    j_ = index2 () - 1;\n                    if (rank_ == 1 && -- itv_ == m.end2 ().itv_)\n                        *this = m.find2 (rank_, i_, j_, -1);\n                    else if (rank_ == 1) {\n                        it_ = (*itv_).begin ();\n                        if (it_ == (*itv_).end () || index1 () != i_)\n                            *this = m.find2 (rank_, i_, j_, -1);\n                    }\n                }\n                return *this;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            true_reference operator * () const {\n                BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ());\n                BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ());\n                if (rank_ == 1) {\n                    return *it_;\n                } else {\n                    return (*this) ().at_element (i_, j_);\n                }\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            iterator1 begin () const {\n                self_type &m = (*this) ();\n                return m.find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            iterator1 end () const {\n                self_type &m = (*this) ();\n                return m.find1 (1, m.size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            reverse_iterator1 rbegin () const {\n                return reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            reverse_iterator1 rend () const {\n                return reverse_iterator1 (begin ());\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_M (itv_.index (), it_.index ()) < (*this) ().size1 (), bad_index ());\n                    return layout_type::index_M (itv_.index (), it_.index ());\n                } else {\n                    return i_;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ());\n                if (rank_ == 1) {\n                    BOOST_UBLAS_CHECK (layout_type::index_m (itv_.index (), it_.index ()) < (*this) ().size2 (), bad_index ());\n                    return layout_type::index_m (itv_.index (), it_.index ());\n                } else {\n                    return j_;\n                }\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            iterator2 &operator = (const iterator2 &it) {\n                container_reference<self_type>::assign (&it ());\n                rank_ = it.rank_;\n                i_ = it.i_;\n                j_ = it.j_;\n                itv_ = it.itv_;\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const iterator2 &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ());\n                if (rank_ == 1 || it.rank_ == 1) {\n                    return it_ == it.it_;\n                } else {\n                    return i_ == it.i_ && j_ == it.j_;\n                }\n            }\n\n        private:\n            int rank_;\n            size_type i_;\n            size_type j_;\n            vectoriterator_type itv_;\n            subiterator_type it_;\n\n            friend class const_iterator2;\n        };\n\n        BOOST_UBLAS_INLINE\n        iterator2 begin2 () {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        iterator2 end2 () {\n            return find2 (0, 0, size2_);\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator1 rbegin1 () {\n            return reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator1 rend1 () {\n            return reverse_iterator1 (begin1 ());\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator2 rbegin2 () {\n            return reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator2 rend2 () {\n            return reverse_iterator2 (begin2 ());\n        }\n\n         // Serialization\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int /* file_version */){\n\n            // we need to copy to a collection_size_type to get a portable\n            // and efficient serialization\n            serialization::collection_size_type s1 (size1_);\n            serialization::collection_size_type s2 (size2_);\n\n            // serialize the sizes\n            ar & serialization::make_nvp(\"size1\",s1)\n               & serialization::make_nvp(\"size2\",s2);\n\n            // copy the values back if loading\n            if (Archive::is_loading::value) {\n                size1_ = s1;\n                size2_ = s2;\n            }\n\n            ar & serialization::make_nvp(\"data\", data_);\n\n            storage_invariants();\n        }\n\n    private:\n        void storage_invariants () const\n        {\n            BOOST_UBLAS_CHECK (layout_type::size_M (size1_, size2_) + 1 == data_.size (), internal_logic ());\n            BOOST_UBLAS_CHECK (data ().begin () != data ().end (), internal_logic ());\n\n        }\n        size_type size1_;\n        size_type size2_;\n        array_type data_;\n        static const value_type zero_;\n    };\n\n    template<class T, class L, class A>\n    const typename generalized_vector_of_vector<T, L, A>::value_type generalized_vector_of_vector<T, L, A>::zero_ = value_type/*zero*/();\n\n}}}\n\n#endif\n", "meta": {"hexsha": "29dfe68f177893e92e78e0f82f23be364f67ff4d", "size": 53215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/vector_of_vector.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/vector_of_vector.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/vector_of_vector.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 39.4770029674, "max_line_length": 157, "alphanum_fraction": 0.5000093958, "num_tokens": 11790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.043365799227540074, "lm_q1q2_score": 0.014812998090283377}}
{"text": "//\r\n//  Copyright (c) 2018-2019, Cem Bassoy, cem.bassoy@gmail.com\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//  The authors gratefully acknowledge the support of\r\n//  Fraunhofer IOSB, Ettlingen, Germany\r\n//\r\n\r\n#ifndef BOOST_UBLAS_TENSOR_EXPRESSIONS_HPP\r\n#define BOOST_UBLAS_TENSOR_EXPRESSIONS_HPP\r\n\r\n#include <cstddef>\r\n#include <boost/numeric/ublas/expression_types.hpp>\r\n\r\n\r\nnamespace boost   {\r\nnamespace numeric {\r\nnamespace ublas   {\r\n\r\n\r\ntemplate<class element_type, class storage_format, class storage_type>\r\nclass tensor;\r\n\r\ntemplate<class size_type>\r\nclass basic_extents;\r\n\r\n\r\n//TODO: put in fwd.hpp\r\nstruct tensor_tag {};\r\n\r\n}\r\n}\r\n}\r\n\r\nnamespace boost   {\r\nnamespace numeric {\r\nnamespace ublas   {\r\nnamespace detail  {\r\n\r\n/** @\\brief base class for tensor expressions\r\n *\r\n * \\note implements crtp - no use of virtual function calls\r\n *\r\n * \\tparam T type of the tensor\r\n * \\tparam E type of the derived expression (crtp)\r\n *\r\n **/\r\ntemplate<class T, class E>\r\nstruct tensor_expression\r\n    : public ublas_expression<E>\r\n{\r\n\t//\tstatic const unsigned complexity = 0;\r\n\tusing expression_type = E;\r\n\tusing type_category = tensor_tag;\r\n\tusing tensor_type = T;\r\n\r\n\tBOOST_UBLAS_INLINE\r\n\tauto const& operator()() const { return *static_cast<const expression_type*> (this); }\r\n\r\nprotected :\r\n\texplicit tensor_expression() = default;\r\n\ttensor_expression(const tensor_expression&) = delete;\r\n\ttensor_expression& operator=(const tensor_expression&) = delete;\r\n};\r\n\r\n\r\ntemplate<class T, class EL, class ER, class OP>\r\nstruct binary_tensor_expression\r\n    : public tensor_expression <T, binary_tensor_expression<T,EL,ER,OP>>\r\n{\r\n\tusing self_type = binary_tensor_expression<T,EL,ER,OP>;\r\n\tusing tensor_type  = T;\r\n\tusing binary_operation = OP;\r\n\tusing expression_type_left  = EL;\r\n\tusing expression_type_right = ER;\r\n\tusing derived_type =  tensor_expression <tensor_type,self_type>;\r\n\r\n\tusing size_type = typename tensor_type::size_type;\r\n\r\n\texplicit binary_tensor_expression(expression_type_left  const& l, expression_type_right const& r, binary_operation o)\r\n\t  : el(l) , er(r) , op(o) {}\r\n\tbinary_tensor_expression() = delete;\r\n\tbinary_tensor_expression(const binary_tensor_expression& l) = delete;\r\n\tbinary_tensor_expression(binary_tensor_expression&& l)\r\n\t  : el(l.el), er(l.er), op(l.op) {}\r\n\r\n\tBOOST_UBLAS_INLINE\r\n\tdecltype(auto)  operator()(size_type i) const { return op(el(i), er(i)); }\r\n\r\n\texpression_type_left const& el;\r\n\texpression_type_right const& er;\r\n\tbinary_operation op;\r\n};\r\n\r\n/// @brief helper function to simply instantiation of lambda proxy class\r\ntemplate<class T, class EL, class ER, class OP>\r\nauto make_binary_tensor_expression( tensor_expression<T,EL> const& el, tensor_expression<T,ER> const& er, OP op)\r\n{\r\n\treturn binary_tensor_expression<T,EL,ER,OP>( el(), er(), op) ;\r\n}\r\n\r\ntemplate<class T, class EL, class ER, class OP>\r\nauto make_binary_tensor_expression( matrix_expression<EL> const& el, tensor_expression<T,ER> const& er, OP op)\r\n{\r\n\treturn binary_tensor_expression<T,EL,ER,OP>( el(), er(), op) ;\r\n}\r\n\r\ntemplate<class T, class EL, class ER, class OP>\r\nauto make_binary_tensor_expression( tensor_expression<T,EL> const& el, matrix_expression<ER> const& er, OP op)\r\n{\r\n\treturn binary_tensor_expression<T,EL,ER,OP>( el(), er(), op) ;\r\n}\r\n\r\ntemplate<class T, class EL, class ER, class OP>\r\nauto make_binary_tensor_expression( vector_expression<EL> const& el, tensor_expression<T,ER> const& er, OP op)\r\n{\r\n\treturn binary_tensor_expression<T,EL,ER,OP>( el(), er(), op) ;\r\n}\r\n\r\ntemplate<class T, class EL, class ER, class OP>\r\nauto make_binary_tensor_expression( tensor_expression<T,EL> const& el, vector_expression<ER> const& er, OP op)\r\n{\r\n\treturn binary_tensor_expression<T,EL,ER,OP>( el(), er(), op) ;\r\n}\r\n\r\n\r\n\r\ntemplate<class T, class E, class OP>\r\nstruct unary_tensor_expression\r\n    : public tensor_expression <T, unary_tensor_expression<T,E,OP>>\r\n{\r\n\r\n\tusing self_type = unary_tensor_expression<T,E,OP>;\r\n\tusing tensor_type  = T;\r\n\tusing expression_type = E;\r\n\r\n\tusing derived_type = tensor_expression <T, unary_tensor_expression<T,E,OP>>;\r\n\r\n\tusing size_type = typename tensor_type::size_type;\r\n\r\n\texplicit unary_tensor_expression(E const& ee, OP o) : e(ee) , op(o) {}\r\n\tunary_tensor_expression() = delete;\r\n\tunary_tensor_expression(const unary_tensor_expression& l) = delete;\r\n\tunary_tensor_expression(unary_tensor_expression&& l)\r\n\t  : e(l.e), op(op.l) {}\r\n\r\n\tBOOST_UBLAS_INLINE\r\n\tdecltype(auto) operator()(size_type i) const { return op(e(i)); }\r\n\r\n\tE const& e;\r\n\tOP op;\r\n};\r\n\r\n// \\brief helper function to simply instantiation of lambda proxy class\r\ntemplate<class T, class E, class OP>\r\nauto make_unary_tensor_expression( tensor_expression<T,E> const& e, OP op)\r\n{\r\n\treturn unary_tensor_expression<T,E,OP>( e() , op);\r\n}\r\n\r\ntemplate<class T, class E, class OP>\r\nauto make_unary_tensor_expression( matrix_expression<E> const& e, OP op)\r\n{\r\n\treturn unary_tensor_expression<T,E,OP>( e() , op);\r\n}\r\n\r\ntemplate<class T, class E, class OP>\r\nauto make_unary_tensor_expression( vector_expression<E> const& e, OP op)\r\n{\r\n\treturn unary_tensor_expression<T,E,OP>( e() , op);\r\n}\r\n\r\n\r\n}\r\n}\r\n}\r\n}\r\n#endif\r\n", "meta": {"hexsha": "a9ca24edd6ccb07f602af5eaa9ed7fc74dca59a9", "size": 5263, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/numeric/ublas/tensor/expression.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": 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": "deps/boost/include/boost/numeric/ublas/tensor/expression.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": 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": "deps/boost/include/boost/numeric/ublas/tensor/expression.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": 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": 28.9175824176, "max_line_length": 119, "alphanum_fraction": 0.7191715751, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.05033063224135805, "lm_q1q2_score": 0.014808025563836784}}
{"text": "// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#if !BOOST_PP_IS_ITERATING\n\n#ifndef CPPQEDCORE_QUANTUMOPERATOR_TRIDIAGONAL_TCC_INCLUDED\n#define CPPQEDCORE_QUANTUMOPERATOR_TRIDIAGONAL_TCC_INCLUDED\n\n#include \"Tridiagonal.h\"\n\n#include \"ComplexArrayExtensions.h\"\n\n#include <boost/lambda/lambda.hpp>\n#include <boost/mpl/for_each.hpp>\n#include <boost/range/algorithm_ext/for_each.hpp>\n\n#include <boost/preprocessor/iteration/iterate.hpp>\n#include <boost/preprocessor/repetition/enum.hpp>\n\n#include <algorithm>\n\n\n\nnamespace quantumoperator {\n\n\nnamespace details {\n\n\ntemplate<bool IS_MULTIPLICATION, int RANK1, int RANK2> // if not multiply then sum\nconst typename Tridiagonal<RANK1+RANK2>::Diagonals\ndirectDiagonals(const typename Tridiagonal<RANK1>::Diagonals& ds1,\n                const typename Tridiagonal<RANK2>::Diagonals& ds2) \n{\n  using namespace blitzplusplus; // implies blitz\n  using namespace linalg       ;\n\n  typedef Tridiagonal<RANK1+RANK2> TridiagonalRes;\n  typedef Tridiagonal<RANK1> Tridiagonal1;\n  typedef Tridiagonal<RANK2> Tridiagonal2;\n\n\n  typename TridiagonalRes::Diagonals res;\n  size_t length=ds2.numElements();\n\n  for (size_t i=0; i<ds1.numElements(); ++i) for (size_t j=0; j<length; ++j) {\n      const typename Tridiagonal1::Diagonal& d1=ds1(i);\n      const typename Tridiagonal2::Diagonal& d2=ds2(j);\n      typename TridiagonalRes::Diagonal& d=res(i*length+j);\n\n      d.reference(doDirect<IS_MULTIPLICATION,RANK1,RANK2>(d1,d2));\n\n    }\n\n  return res;\n\n} // NEEDS_WORK this is now runtime, but (a smaller) part of it could be done compile-time. Ugh. Ouch.\n\n\n} // details\n\n\ntemplate<int RANK> template<int RANK2>\nTridiagonal<RANK>::Tridiagonal(const Tridiagonal<RANK2>& t1, const Tridiagonal<RANK-RANK2>& t2)\n  : Base(blitzplusplus::concatenateTinies(t1.getDimensions(),t2.getDimensions())),\n    diagonals_(blitzplusplus::ShallowCopy(),details::directDiagonals<true,RANK2,RANK-RANK2>(t1.get(),t2.get())),\n    differences_(blitzplusplus::concatenateTinies(t1.getDifferences(),t2.getDifferences())),\n    tCurrent_(t1.getTime()),\n    freqs_(blitzplusplus::ShallowCopy(),details::directDiagonals<false,RANK2,RANK-RANK2>(t1.getFreqs(),t2.getFreqs()))\n{\n  if (t1.getTime()!=t2.getTime()) throw std::runtime_error(\"Tridiagonal time mismatch\");\n}\n\n\ntemplate<int RANK>\nTridiagonal<RANK>&\nTridiagonal<RANK>::operator*=(dcomp dc)\n{\n  boost::for_each(diagonals_,boost::lambda::_1*=dc); \n  return *this;\n}\n\n\n\n\ntemplate<int RANK>\nconst Tridiagonal<RANK> Tridiagonal<RANK>::hermitianConjugate() const\n{\n  struct helper {\n\n    static int transposeIndex(int ind)\n    {\n      int res=0;\n      // std::cout<<ind<<' ';\n      for (int k=RANK-1; k>=0; k--) {\n        int threeToK=int(floor(pow(3.,k)));\n        int ik=int(floor(ind/double(threeToK)));\n        res+=((3-ik)%3)*threeToK;\n        ind-=ik*threeToK;\n      }\n      // std::cout<<res<<std::endl;\n      return res;\n    }\n\n  };\n\n  Tridiagonal res(*this,Diagonals(),differences_,tCurrent_,freqs_);\n\n  for (int ind=0; ind<LENGTH; ind++)\n    res.diagonals_(helper::transposeIndex(ind)).reference(Diagonal(conj(diagonals_(ind))));\n  // Here a new copy of the conjugated diagonal gets created & referenced.\n\n  // freqs_ at any moment stores the correct transposed values as well\n\n  return res;\n\n}\n\n\ntemplate<int RANK>\nTridiagonal<RANK>&\nTridiagonal<RANK>::operator+=(const Tridiagonal& tridiag)\n{\n  boost::for_each(tridiag.differences_,differences_,[](size_t otherDifference, size_t& difference) {\n    if (!difference) difference=otherDifference;\n    else if (otherDifference && difference!=otherDifference) throw std::invalid_argument(\"Tridiagonal structure mismatch is binOp1\");\n  });\n  \n  boost::for_each(tridiag.diagonals_,diagonals_,[](const typename Tridiagonal<RANK>::Diagonal& from, typename Tridiagonal<RANK>::Diagonal& to) {\n    if (from.size()) {\n      if (!to.size()) {\n        to.resize(from.shape());\n        to=from;\n      }\n      else to+=from; // This will check for the compatibility of shapes\n    }\n  });\n  \n  boost::for_each(tridiag.freqs_,freqs_,[](const typename Tridiagonal<RANK>::Diagonal& from, typename Tridiagonal<RANK>::Diagonal& to) {\n    if (from.size()) {\n      if (to.size() && all(to!=from)) throw std::runtime_error(\"Tridiagonal structure mismatch is operator+=\");\n      else {\n        to.resize(from.shape());\n        to=from;\n      }\n    }\n  });\n\n  return *this;\n\n}\n\n\n\ntemplate<int RANK>\nTridiagonal<RANK>& Tridiagonal<RANK>::propagate(double t)\n{\n  // Diagonal (i=0) left out\n  if (double dt=t-tCurrent_)\n    for (int i=1; i<LENGTH; i++)\n      if (diagonals_(i).size() && freqs_(i).size())\n        diagonals_(i)*=exp(dt*freqs_(i));\n  tCurrent_=t;\n  return *this;\n}\n\n\ntemplate<int RANK>\nTridiagonal<RANK>\nfurnishWithFreqs(const Tridiagonal<RANK>& tridiag, const typename Tridiagonal<RANK>::Diagonal& mainDiagonal)\n{\n  Tridiagonal<RANK> res(tridiag);\n  return res.furnishWithFreqs(mainDiagonal);\n}\n\n\ntemplate<int RANK>\nstd::ostream& operator<<(std::ostream& os, const Tridiagonal<RANK>& tridiag)\n{\n  using namespace std;\n  os<<tridiag.get()<<endl<<tridiag.getFreqs()<<endl<<tridiag.getDifferences()<<endl<<tridiag.getDimensions()<<endl;\n  return os;\n}\n\n\n} // quantumoperator\n\n\n#ifndef DO_CONSIDER_EXPLICITLY_SPECIALIZED_TRIDIAGONAL_APPLIES\n\n\nnamespace quantumoperator {\n\n\ntemplate<int RANK> template<typename ICW>\nvoid Tridiagonal<RANK>::FillRangesHelper::operator()(ICW)\n{\n  using blitz::Range;\n\n  static const int i=ICW::value;\n  \n  ranges_(i)(0)=Range(0,ubound_(i));\n  ranges_(i)(2)=((\n                  ranges_(i)(1)=Range(0,ubound_(i)-int(k_(i)))\n                  )+int(k_(i)));\n\n}\n\n\n\ntemplate<int RANK>\nconst typename Tridiagonal<RANK>::Ranges Tridiagonal<RANK>::fillRanges(const typename StateVectorLow::T_index& ubound) const\n{\n  Ranges res;\n  \n  mpl::for_each<tmptools::Ordinals<RANK> >(FillRangesHelper(res,ubound,differences_));\n  return res;\n}\n\n\n\ntemplate<int RANK>\nvoid Tridiagonal<RANK>::apply(const StateVectorLow& psi, StateVectorLow& dpsidt) const\n{\n  static const int step=tmptools::Power_v<3,RANK-1>;\n\n  using tmptools::Vector, tmptools::integral_c;\n\n  const Ranges ranges(fillRanges(psi.ubound()));\n\n  doApply<0*step,Vector<0>,Vector<0>,Vector<0> >(integral_c<RANK-1>(),ranges,psi,dpsidt);\n  doApply<1*step,Vector<2>,Vector<1>,Vector<1> >(integral_c<RANK-1>(),ranges,psi,dpsidt);\n  doApply<2*step,Vector<1>,Vector<1>,Vector<2> >(integral_c<RANK-1>(),ranges,psi,dpsidt);\n\n}\n\n\n\ntemplate<int RANK> template<int START, typename V_DPSIDT, typename V_A, typename V_PSI, int REMAINING>\nvoid Tridiagonal<RANK>::doApply(tmptools::integral_c<REMAINING>,\n                                const Ranges& ranges, const StateVectorLow& psi, StateVectorLow& dpsidt) const\n{\n  static const int step=tmptools::Power_v<3,REMAINING-1>;\n\n  using mpl::push_back, tmptools::integral_c;\n\n  doApply<START+0*step,\n          typename push_back<V_DPSIDT,integral_c<0> >::type,\n          typename push_back<V_A     ,integral_c<0> >::type,\n          typename push_back<V_PSI   ,integral_c<0> >::type>\n    (integral_c<REMAINING-1>(),ranges,psi,dpsidt);\n\n  doApply<START+1*step,\n          typename push_back<V_DPSIDT,integral_c<2> >::type,\n          typename push_back<V_A     ,integral_c<1> >::type,\n          typename push_back<V_PSI   ,integral_c<1> >::type>\n    (integral_c<REMAINING-1>(),ranges,psi,dpsidt);\n\n  doApply<START+2*step,\n          typename push_back<V_DPSIDT,integral_c<1> >::type,\n          typename push_back<V_A     ,integral_c<1> >::type,\n          typename push_back<V_PSI   ,integral_c<2> >::type>\n    (integral_c<REMAINING-1>(),ranges,psi,dpsidt);\n\n}\n\n\n} // quantumoperator\n\n\n#define BOOST_PP_ITERATION_LIMITS (1,QUANTUMOPERATOR_TRIDIAGONAL_MAX_RANK)\n#define BOOST_PP_FILENAME_1 \"Tridiagonal.tcc\"\n\n#include BOOST_PP_ITERATE()\n\n#undef BOOST_PP_FILENAME_1\n#undef BOOST_PP_ITERATION_LIMITS\n\n\n#else // DO_CONSIDER_EXPLICITLY_SPECIALIZED_TRIDIAGONAL_APPLIES\n\nnamespace quantumoperator {\n\n\ntemplate<>\nvoid Tridiagonal<1>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<2>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<3>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<4>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<5>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<6>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<7>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<8>::apply(const StateVectorLow&, StateVectorLow&) const;\n\ntemplate<>\nvoid Tridiagonal<9>::apply(const StateVectorLow&, StateVectorLow&) const;\n\n\n} // quantumoperator\n\n\n#endif // DO_CONSIDER_EXPLICITLY_SPECIALIZED_TRIDIAGONAL_APPLIES\n\n\n#endif // CPPQEDCORE_QUANTUMOPERATOR_TRIDIAGONAL_TCC_INCLUDED\n\n\n#else  // BOOST_PP_IS_ITERATING\n\n\n#define rank BOOST_PP_ITERATION()\n\n#define AT_helper(V,i) ranges(i)(at_c<V,i>::type::value)\n\n#define DPSIDT_print(z,m,data) AT_helper(V_DPSIDT,m)\n#define      A_print(z,m,data) AT_helper(V_A     ,m)\n#define    PSI_print(z,m,data) AT_helper(V_PSI   ,m)\n\n\ntemplate<> template<int START, typename V_DPSIDT, typename V_A, typename V_PSI>\nvoid quantumoperator::Tridiagonal<rank>::doApply(tmptools::integral_c<0>,\n                                                 const Ranges& ranges, const StateVectorLow& psi, StateVectorLow& dpsidt) const\n{\n  using mpl::at_c;\n\n  if (diagonals_(START).size()) \n    dpsidt             (BOOST_PP_ENUM(rank,DPSIDT_print,~))\n      +=\n      diagonals_(START)(BOOST_PP_ENUM(rank,     A_print,~))\n      *\n      psi              (BOOST_PP_ENUM(rank,   PSI_print,~))\n      ;\n\n}\n\n#undef    PSI_print\n#undef      A_print\n#undef DPSIDT_print\n\n#undef AT_helper\n\n#undef rank\n\n\n#endif // BOOST_PP_IS_ITERATING\n", "meta": {"hexsha": "c0fe36548f0ef144995f08c673716acde8131c3b", "size": 9854, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "CPPQEDcore/quantumoperator/Tridiagonal.tcc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "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/quantumoperator/Tridiagonal.tcc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "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/quantumoperator/Tridiagonal.tcc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "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": 27.5251396648, "max_line_length": 144, "alphanum_fraction": 0.7060077126, "num_tokens": 2813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.03567855228760954, "lm_q1q2_score": 0.014802990680079398}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RWLIBS_PATHPLANNERS_PRMPLANNER_HPP\n#define RWLIBS_PATHPLANNERS_PRMPLANNER_HPP\n\n#include \"PartialIndexTable.hpp\"\n\n#include <rw/common/Timer.hpp>\n#include <rw/core/Ptr.hpp>\n#include <rw/math/Metric.hpp>\n#include <rw/pathplanning/QToQPlanner.hpp>\n#include <rwlibs/algorithms/kdtree/KDTreeQ.hpp>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <memory>\n\nnamespace rw { namespace kinematics {\n    class State;\n}}    // namespace rw::kinematics\nnamespace rw { namespace pathplanning {\n    class QConstraint;\n}}    // namespace rw::pathplanning\nnamespace rw { namespace pathplanning {\n    class QEdgeConstraint;\n}}    // namespace rw::pathplanning\nnamespace rw { namespace pathplanning {\n    class QSampler;\n}}    // namespace rw::pathplanning\nnamespace rw { namespace proximity {\n    class CollisionDetector;\n}}    // namespace rw::proximity\n\nnamespace rwlibs { namespace pathplanners {\n    /** @addtogroup pathplanners */\n    /*@{*/\n\n    /**\n     * @brief Implements a probabilistic roadmap (PRM) planner.\n     *\n     * The PRMPlanner is implemented freely after [1], and has a number of options:\n     *\n     * - Lazy Collision Checking: Using lazy collision checking as in [2], the\n     * planner can be used for single as well as multiple queries.\n     *\n     * - Nearest Neighbor Search: The algorithm can either use a partial index\n     * table [3] or a simple brute force method to do the nearest neighbor\n     * search.\n     *\n     * - Shortest Path Algorithm: Using the Boost Graph Library, both A* and\n     * Dijkstra's Algorithm may be used for finding the shortest path.\n     *\n     * As default the algorithm runs with lazy collision checking, brute force\n     * neighbor search and with A* for shortest path search.\n     *\n     * As metric the PRMPlanner uses a WeightedEuclideanMetric for which it\n     * estimates the weights such that it provides a worst-case estimate of the\n     * Cartesian motion of the robots given a change in the configuration.\n     *\n     * Example of use\n     * \\code\n     *      PRMPlanner* prm = new PRMPlanner(device, workcell, state, collisionDetector,\n     * resolution); prm->setCollisionCheckingStrategy(PRMPlanner::LAZY);\n     *      prm->setNeighSearchStrategy(PRMPlanner::BRUTE_FORCE);\n     *      prm->setShortestPathSearchStrategy(PRMPlanner::A_STAR);\n     *      prm->buildRoadmap(1000);\n     *      Path path;\n     *      bool pathFound = prm->query(qstart, qgoal, path, maxtime);\n     * \\endcode\n     *\n     * [1]: Probabilistic Roadmaps for Path Planning in High-Dimensional\n     *      Configuration Spaces, L.E. Kavraki, P. Svestka, J-C. Latombe, M.H.\n     *      Overmars. IEEE Transactions on Robotics and Automation, Vol. 12, pages\n     *      566-580, 1996\n     *\n     * [2]: Path Planning using Lazy PRM, R. Bohlin, L.E. Kavraki. Proceedings\n     *      of the IEEE International Conference on Robotics and Automation, Vol. 1,\n     *      pages 521-528, 2000\n     *\n     * [3]: On Delaying Collision Checking in PRM Planning - Application to\n     *      Multi-Robot Coordination, G. Sanchez, J.C. Latombe. The International\n     *      Journal of Robotics Research, Vol. 21, No. 1, pages 5-26, 2002\n     */\n    class PRMPlanner : public rw::pathplanning::QToQPlanner\n    {\n      public:\n        //! @brief smart pointer type to this class\n        typedef rw::core::Ptr< PRMPlanner > Ptr;\n\n        /**\n         * @brief Constructs PRMPlanner\n         *\n         * Constructs a PRMPlanner with a given setup. This method does NOT build the roadmap.\n         * The method estimates the movements of the robot to construct a weighted metric as\n         * explained in the general introduction.\n         *\n         * @param device [in] Device to plan for\n         * @param state [in] State giving the setup of the workcell\n         * @param collisionDetector [in] CollisionDetector to use\n         *\n         * @param resolution [in] Cartesian distance the robot is allowed to move\n         * between collision checks.\n         */\n        PRMPlanner (rw::models::Device* device, const rw::kinematics::State& state,\n                    rw::proximity::CollisionDetector* collisionDetector, double resolution);\n\n        /**\n           @brief Constructs PRMPlanner\n\n           @param constraint [in] Collision constraint\n           @param sampler [in] Configuration space sampler\n           @param resolution [in] Collision checking resolution\n           @param device [in] Device characteristics\n           @param state [in] State of rest of the workcell\n        */\n        PRMPlanner (rw::core::Ptr< rw::pathplanning::QConstraint > constraint,\n                    rw::core::Ptr< rw::pathplanning::QSampler > sampler, double resolution,\n                    const rw::models::Device& device, const rw::kinematics::State& state);\n\n        /**\n         * @brief Destructor\n         */\n        virtual ~PRMPlanner ();\n\n        /**\n         * @brief Build the roadmap with the setup specified\n         * @param nodecount [in] Number of nodes to insert\n         */\n        void buildRoadmap (size_t nodecount);\n\n        /**\n         * @brief Sets the desired average number of neighbors. Default value is 20.\n         * @param n [in] Desired average number of neighbors\n         */\n        void setNeighborCount (size_t n);\n\n        /**\n         * @brief Enumeration for selecting the node neighbor search strategy\n         */\n        enum NeighborSearchStrategy {\n            BRUTE_FORCE = 0,     /*!< Run through all node and look a which a sufficient close. */\n            PARTIAL_INDEX_TABLE, /*!< Use a partial index table to make an more efficient lookup. */\n            KDTREE               /*!< Use KD tree for neighbor search */\n        };\n\n        /**\n         * @brief Sets up the nearest neighbor search strategy\n         *\n         * @param neighborSearchStrategy [in] The nearest neighbor search strategy\n         */\n        void setNeighSearchStrategy (NeighborSearchStrategy neighborSearchStrategy);\n\n        /**\n         * @brief Sets up the number of dimensions for the partial index table\n         *\n         * This setting only applies when using the PARTIAL_INDEX_TABLE strategy for nearest\n         * neighbor search.\n         *\n         * \\b dimensions should be within \\f$[1; _device->getDOF()]\\f$. The optimal\n         * value of \\b dimensions is a tradeoff between memory usage and time.\n         * Selecting a value too high compared to the number of nodes in the roadmap\n         * may introduce an increase in time due to additional bookkeeping.\n         *\n         * The default value is set to 4, which is found suitable for most devices\n         * with 6 or 7 degrees of freedom.\n         *\n         * @param dimensions [in] Number of dimensions, which should be\n         */\n        void setPartialIndexTableDimensions (size_t dimensions);\n\n        /**\n         * @brief Enumeration for selecting the collision checking strategy\n         */\n        enum CollisionCheckingStrategy {\n            LAZY = 0,  /*!< Perform a Lazy collision checking (no checking on construction).*/\n            NODECHECK, /*!< Only check node on construction, leave edges unchecked. */\n            FULL       /*!<Perform a full check of both nodes and edges. */\n        };\n\n        /**\n         * @brief Sets up the collision checking strategy\n         *\n         * Note: Do not call this after the buildRoadmap as it may result in paths with collisions\n         * @param collisionCheckingStrategy [in] The collision checking strategy\n         */\n        void setCollisionCheckingStrategy (CollisionCheckingStrategy collisionCheckingStrategy);\n\n        /**\n         * @brief Enumeration for selecing the shortest path search strategy\n         */\n        enum ShortestPathSearchStrategy {\n            A_STAR = 0, /*!< Use A* to search for shortest path. */\n            DIJKSTRA    /*!< Use Dijkstra to search for shortest path. */\n        };\n\n        /**\n         * @brief Sets up the shortest path search strategy\n         *\n         * Generally A* is the fastest algorithm, but given a small roadmap Dijkstra may\n         * perform better.\n         *\n         * @param shortestPathSearchStrategy [in] shortestPathSearchStrategy\n         */\n        void setShortestPathSearchStrategy (ShortestPathSearchStrategy shortestPathSearchStrategy);\n\n        /**\n         * @brief Sets the max time of A* before terminating and calling dijkstra\n         *\n         * The A* implementation in the boost graph library has a reported bug, which on\n         * some platforms in rare occasions may cause it to loop infinitely. If A* uses\n         * more than this specified time it will break off and call dijkstra instead.\n         *\n         * Default value for this timeout is 1second.\n         *\n         * @param timeout [in] Timeout time.\n         */\n        void setAStarTimeOutTime (double timeout);\n\n        /**\n         * @brief print timing stats from previous run.\n         */\n        void printTimeStats ();\n\n      private:\n        bool doQuery (const rw::math::Q& qInit, const rw::math::Q& qGoal,\n                      rw::trajectory::QPath& path, const rw::pathplanning::StopCriteria& stop);\n\n      private:\n        bool _roadmap_initialized;\n        rw::core::Ptr< rw::pathplanning::QConstraint > _constraint;\n        rw::core::Ptr< rw::pathplanning::QSampler > _sampler;\n        double _resolution;\n\n        rw::core::Ptr< rw::pathplanning::QEdgeConstraint > _edge;\n\n        std::pair< rw::math::Q, rw::math::Q > _bounds;\n\n        rw::math::Q _metricWeights;\n        rw::math::QMetric::Ptr _metric;\n\n        double _Rneighbor;\n        size_t _Nneighbor;\n        NeighborSearchStrategy _neighborSearchStrategy;\n        size_t _partialIndexTableDimensions;\n        CollisionCheckingStrategy _collisionCheckingStrategy;\n\n        ShortestPathSearchStrategy _shortestPathSearchStrategy;\n        double _astarTimeOutTime;\n\n        // for stats testing\n        rw::common::Timer collisionTimer;\n        rw::common::Timer roadmapBuildTimer;\n        rw::common::Timer queryTimer;\n        rw::common::Timer shortestPathTimer;\n        rw::common::Timer neighborTimer;\n        rw::common::Timer enhanceTimer;\n\n        /**\n         * @brief The data contained in the PRM graph node\n         */\n        class NodeData\n        {\n          public:\n            //! Joint configuration\n            rw::math::Q q;\n\n            //! Has the node been checked for collision\n            bool checked;\n\n          private:\n            friend class boost::serialization::access;\n            // When the class Archive corresponds to an output archive, the\n            // & operator is defined similar to <<.  Likewise, when the class Archive\n            // is a type of input archive the & operator is defined similar to >>.\n            template< class Archive > void serialize (Archive& ar, const unsigned int version)\n            {\n                ar& q;\n                ar& checked;\n            }\n        };\n\n        /**\n         * @brief The data contained in the PRM graph edge\n         */\n        class EdgeData\n        {\n          public:\n            //! The edge-weight (defined as pPath(left, right))\n            double weight;\n\n            /**\n             * @brief The resolution to which this node has been checked\n             * (if resolution < _resolution then the edge is considered checked)\n             */\n            double resolution;\n\n            rw::math::Q q1;\n            rw::math::Q q2;\n\n          private:\n            friend class boost::serialization::access;\n            // When the class Archive corresponds to an output archive, the\n            // & operator is defined similar to <<.  Likewise, when the class Archive\n            // is a type of input archive the & operator is defined similar to >>.\n            template< class Archive > void serialize (Archive& ar, const unsigned int version)\n            {\n                ar& weight;\n                ar& resolution;\n                ar& q1;\n                ar& q2;\n            }\n        };\n\n        /**\n         * @brief The PRM (Probabilistic RoadMap)\n         */\n        typedef boost::adjacency_list< boost::listS, boost::listS, boost::undirectedS, NodeData,\n                                       EdgeData >\n            PRM;\n\n        //! The roadmap\n        PRM _graph;\n\n        //! List of seeds for the enhancement step\n        std::vector< rw::math::Q > _seeds;\n\n        //! A PRM node\n        typedef PRM::vertex_descriptor Node;\n\n        //! A PRM edge\n        typedef PRM::edge_descriptor Edge;\n\n        std::shared_ptr< prm::PartialIndexTable< Node > > _partialIndexTable;\n        rwlibs::algorithms::KDTreeQ< Node >::Ptr _kdtree;\n        std::list< const rwlibs::algorithms::KDTreeQ< Node >::KDNode* > _kdnodesSearchResult;\n\n        void initialize (const rw::models::Device& device, const rw::kinematics::State& state);\n\n        bool inCollision (const rw::math::Q& a, const rw::math::Q& b) const;\n        bool addEdge (Node n1, Node n2, double dist);\n\n        void addEdges (Node node);\n\n        Node addNode (const rw::math::Q& q, bool checked);\n\n        double estimateRneighbor (size_t roadmapsize);\n\n        bool searchForShortestPathDijkstra (const Node& nInit, const Node& nGoal,\n                                            std::list< Node >& result);\n        bool searchForShortestPathAstar (const Node& nInit, const Node& nGoal,\n                                         std::list< Node >& result);\n\n        bool inCollision (std::list< Node >& path);\n\n        bool enhanceEdgeCheck (Edge& e);\n        void removeCollidingNode (Node node);\n        void removeCollidingEdge (Edge edge);\n\n        void enhanceAround (const rw::math::Q& q);\n        void enhanceRoadmap ();\n\n        size_t _enhanceAroundSeedCount;\n        size_t _enhanceRandomFromSeedsCnt;\n        size_t _enhanceRandomCnt;\n\n        class EdgeCompare\n        {\n          private:\n            PRM* _prm;\n\n          public:\n            EdgeCompare (PRM* prm) : _prm (prm) {}\n\n            bool operator() (const Edge& e1, const Edge& e2) const\n            {\n                // return 1;\n                return (*_prm)[e1].resolution > (*_prm)[e2].resolution;\n            }\n        };\n\n        /**\n         * @brief The heuristic distance meassure used by the A* shortest path search\n         */\n        class PathHeuristic : public boost::astar_heuristic< PRM, double >\n        {\n          public:\n            /**\n             * @brief Creates object\n             * @param lazy [in] the lazy PRM path planner\n             * @param nGoal [in] the goal node\n             */\n            PathHeuristic (PRM& prm, const rw::math::QMetric* metric, const Node& nGoal) :\n                _prm (prm), _metric (metric), _qGoal (prm[nGoal].q)\n            {}\n\n            /**\n             * @brief Calculates distance from n to goal\n             * @param n [in] the node n\n             * @return the distance\n             */\n            double operator() (const Node& n) { return _metric->distance (_qGoal, _prm[n].q); }\n\n          private:\n            PRM& _prm;\n            //! Controlling pathplanner\n            const rw::math::QMetric* _metric;\n            //! Goal configuration\n            rw::math::Q _qGoal;\n        };\n    };\n\n    /* @} */\n}}    // namespace rwlibs::pathplanners\n\n#endif    // end include guard\n", "meta": {"hexsha": "7ee0cfb2d598061b10cb4f8287817f823ab4bb73", "size": 16301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/pathplanners/prm/PRMPlanner.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rwlibs/pathplanners/prm/PRMPlanner.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rwlibs/pathplanners/prm/PRMPlanner.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6466512702, "max_line_length": 100, "alphanum_fraction": 0.5979387768, "num_tokens": 3653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.03210070810595668, "lm_q1q2_score": 0.014798965064652902}}
{"text": "// Copyright 2018 Ulf Adams\n//\n// The contents of this file may be used under the terms of the Apache License,\n// Version 2.0.\n//\n//    (See accompanying file LICENSE-Apache or copy at\n//     http://www.apache.org/licenses/LICENSE-2.0)\n//\n// Alternatively, the contents of this file may be used under the terms of\n// the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE-Boost or copy at\n//     https://www.boost.org/LICENSE_1_0.txt)\n//\n// Unless required by applicable law or agreed to in writing, this software\n// is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied.\n\n/*\n    This is a derivative work\n*/\n\n#ifndef BOOST_JSON_DETAIL_RYU_DETAIL_D2S_INTRINSICS_HPP\n#define BOOST_JSON_DETAIL_RYU_DETAIL_D2S_INTRINSICS_HPP\n\n#include <boost/json/config.hpp>\n\n// This sets BOOST_JSON_RYU_32_BIT_PLATFORM as a side effect if applicable.\n#include <boost/json/detail/ryu/detail/common.hpp>\n\n#if defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)\n#include <intrin.h>\n#endif\n\nnamespace boost {\nnamespace json {\nnamespace detail {\n\nnamespace ryu {\nnamespace detail {\n\n#if defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)\n\ninline uint64_t umul128(const uint64_t a, const uint64_t b, uint64_t* const productHi) {\n  return _umul128(a, b, productHi);\n}\n\ninline uint64_t shiftright128(const uint64_t lo, const uint64_t hi, const uint32_t dist) {\n  // For the __shiftright128 intrinsic, the shift value is always\n  // modulo 64.\n  // In the current implementation of the double-precision version\n  // of Ryu, the shift value is always < 64. (In the case\n  // RYU_OPTIMIZE_SIZE == 0, the shift value is in the range [49, 58].\n  // Otherwise in the range [2, 59].)\n  // Check this here in case a future change requires larger shift\n  // values. In this case this function needs to be adjusted.\n  BOOST_JSON_ASSERT(dist < 64);\n  return __shiftright128(lo, hi, (unsigned char) dist);\n}\n\n#else // defined(HAS_64_BIT_INTRINSICS)\n\ninline uint64_t umul128(const uint64_t a, const uint64_t b, uint64_t* const productHi) {\n  // The casts here help MSVC to avoid calls to the __allmul library function.\n  const uint32_t aLo = (uint32_t)a;\n  const uint32_t aHi = (uint32_t)(a >> 32);\n  const uint32_t bLo = (uint32_t)b;\n  const uint32_t bHi = (uint32_t)(b >> 32);\n\n  const uint64_t b00 = (uint64_t)aLo * bLo;\n  const uint64_t b01 = (uint64_t)aLo * bHi;\n  const uint64_t b10 = (uint64_t)aHi * bLo;\n  const uint64_t b11 = (uint64_t)aHi * bHi;\n\n  const uint32_t b00Lo = (uint32_t)b00;\n  const uint32_t b00Hi = (uint32_t)(b00 >> 32);\n\n  const uint64_t mid1 = b10 + b00Hi;\n  const uint32_t mid1Lo = (uint32_t)(mid1);\n  const uint32_t mid1Hi = (uint32_t)(mid1 >> 32);\n\n  const uint64_t mid2 = b01 + mid1Lo;\n  const uint32_t mid2Lo = (uint32_t)(mid2);\n  const uint32_t mid2Hi = (uint32_t)(mid2 >> 32);\n\n  const uint64_t pHi = b11 + mid1Hi + mid2Hi;\n  const uint64_t pLo = ((uint64_t)mid2Lo << 32) | b00Lo;\n\n  *productHi = pHi;\n  return pLo;\n}\n\ninline uint64_t shiftright128(const uint64_t lo, const uint64_t hi, const uint32_t dist) {\n  // We don't need to handle the case dist >= 64 here (see above).\n  BOOST_JSON_ASSERT(dist < 64);\n#if defined(RYU_OPTIMIZE_SIZE) || !defined(RYU_32_BIT_PLATFORM)\n  BOOST_JSON_ASSERT(dist > 0);\n  return (hi << (64 - dist)) | (lo >> dist);\n#else\n  // Avoid a 64-bit shift by taking advantage of the range of shift values.\n  BOOST_JSON_ASSERT(dist >= 32);\n  return (hi << (64 - dist)) | ((uint32_t)(lo >> 32) >> (dist - 32));\n#endif\n}\n\n#endif // defined(HAS_64_BIT_INTRINSICS)\n\n#ifdef RYU_32_BIT_PLATFORM\n\n// Returns the high 64 bits of the 128-bit product of a and b.\ninline uint64_t umulh(const uint64_t a, const uint64_t b) {\n  // Reuse the umul128 implementation.\n  // Optimizers will likely eliminate the instructions used to compute the\n  // low part of the product.\n  uint64_t hi;\n  umul128(a, b, &hi);\n  return hi;\n}\n\n// On 32-bit platforms, compilers typically generate calls to library\n// functions for 64-bit divisions, even if the divisor is a constant.\n//\n// E.g.:\n// https://bugs.llvm.org/show_bug.cgi?id=37932\n// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=17958\n// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=37443\n//\n// The functions here perform division-by-constant using multiplications\n// in the same way as 64-bit compilers would do.\n//\n// NB:\n// The multipliers and shift values are the ones generated by clang x64\n// for expressions like x/5, x/10, etc.\n\ninline uint64_t div5(const uint64_t x) {\n  return umulh(x, 0xCCCCCCCCCCCCCCCDu) >> 2;\n}\n\ninline uint64_t div10(const uint64_t x) {\n  return umulh(x, 0xCCCCCCCCCCCCCCCDu) >> 3;\n}\n\ninline uint64_t div100(const uint64_t x) {\n  return umulh(x >> 2, 0x28F5C28F5C28F5C3u) >> 2;\n}\n\ninline uint64_t div1e8(const uint64_t x) {\n  return umulh(x, 0xABCC77118461CEFDu) >> 26;\n}\n\ninline uint64_t div1e9(const uint64_t x) {\n  return umulh(x >> 9, 0x44B82FA09B5A53u) >> 11;\n}\n\ninline uint32_t mod1e9(const uint64_t x) {\n  // Avoid 64-bit math as much as possible.\n  // Returning (uint32_t) (x - 1000000000 * div1e9(x)) would\n  // perform 32x64-bit multiplication and 64-bit subtraction.\n  // x and 1000000000 * div1e9(x) are guaranteed to differ by\n  // less than 10^9, so their highest 32 bits must be identical,\n  // so we can truncate both sides to uint32_t before subtracting.\n  // We can also simplify (uint32_t) (1000000000 * div1e9(x)).\n  // We can truncate before multiplying instead of after, as multiplying\n  // the highest 32 bits of div1e9(x) can't affect the lowest 32 bits.\n  return ((uint32_t) x) - 1000000000 * ((uint32_t) div1e9(x));\n}\n\n#else // RYU_32_BIT_PLATFORM\n\ninline uint64_t div5(const uint64_t x) {\n  return x / 5;\n}\n\ninline uint64_t div10(const uint64_t x) {\n  return x / 10;\n}\n\ninline uint64_t div100(const uint64_t x) {\n  return x / 100;\n}\n\ninline uint64_t div1e8(const uint64_t x) {\n  return x / 100000000;\n}\n\ninline uint64_t div1e9(const uint64_t x) {\n  return x / 1000000000;\n}\n\ninline uint32_t mod1e9(const uint64_t x) {\n  return (uint32_t) (x - 1000000000 * div1e9(x));\n}\n\n#endif // RYU_32_BIT_PLATFORM\n\ninline uint32_t pow5Factor(uint64_t value) {\n  uint32_t count = 0;\n  for (;;) {\n    BOOST_JSON_ASSERT(value != 0);\n    const uint64_t q = div5(value);\n    const uint32_t r = ((uint32_t) value) - 5 * ((uint32_t) q);\n    if (r != 0) {\n      break;\n    }\n    value = q;\n    ++count;\n  }\n  return count;\n}\n\n// Returns true if value is divisible by 5^p.\ninline bool multipleOfPowerOf5(const uint64_t value, const uint32_t p) {\n  // I tried a case distinction on p, but there was no performance difference.\n  return pow5Factor(value) >= p;\n}\n\n// Returns true if value is divisible by 2^p.\ninline bool multipleOfPowerOf2(const uint64_t value, const uint32_t p) {\n  BOOST_JSON_ASSERT(value != 0);\n  // return __builtin_ctzll(value) >= p;\n  return (value & ((1ull << p) - 1)) == 0;\n}\n\n\n} // detail\n} // ryu\n\n} // detail\n} // json\n} // boost\n\n#endif\n", "meta": {"hexsha": "fda090e6b5dd8615411e5fa8f9874178fa904259", "size": 6915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/json/detail/ryu/detail/d2s_intrinsics.hpp", "max_stars_repo_name": "Vicfred/json", "max_stars_repo_head_hexsha": "cdd6d769bfe8351c8869fe3571a90b38cef024be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-24T03:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T03:29:23.000Z", "max_issues_repo_path": "include/boost/json/detail/ryu/detail/d2s_intrinsics.hpp", "max_issues_repo_name": "Vicfred/json", "max_issues_repo_head_hexsha": "cdd6d769bfe8351c8869fe3571a90b38cef024be", "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/json/detail/ryu/detail/d2s_intrinsics.hpp", "max_forks_repo_name": "Vicfred/json", "max_forks_repo_head_hexsha": "cdd6d769bfe8351c8869fe3571a90b38cef024be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-18T04:50:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-18T04:50:43.000Z", "avg_line_length": 29.8060344828, "max_line_length": 90, "alphanum_fraction": 0.707736804, "num_tokens": 2165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.04813676684935012, "lm_q1q2_score": 0.014795221197121827}}
{"text": "//---------------------------------------------------------------------------------------------------------------------\n// Copyright 2017, 2018 Purdue University, Ignacio Garcia Dorado, Daniel Aliaga\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 \n// following 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 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\n#include \"misctools.h\"\n#include \"qstringlist.h\"\n//#include \"client_global_variables.h\"\n#ifndef Q_MOC_RUN\n#include <boost/random.hpp>\n#endif\n#include <qtimer.h>\n#include <qfile>\n\nnamespace LC {\n\tnamespace misctools {\n\n\t\t//#define MISCTOOLS_TIMER\n\n#define _PI 3.14159265\n\n\n\t\tconst QVector3D perp(const QVector3D &v) {\n\t\t\tqreal min = fabs(v.x());\n\t\t\tQVector3D cardinalAxis(1.0, 0.0, 0.0);\n\n\t\t\tif(fabs(v.y()) < min) {\n\t\t\t\tmin = fabs(v.y());\n\t\t\t\tcardinalAxis = QVector3D(0.0, 1.0, 0.0);\n\t\t\t}\n\n\t\t\tif(fabs(v.z()) < min) {\n\t\t\t\tcardinalAxis = QVector3D(0.0, 0.0, 1.0);\n\t\t\t}\n\n\t\t\treturn QVector3D::crossProduct(v, cardinalAxis);\n\t\t}//\n\n\t\t/** \n\t\t\tdrawCone Funtion to draw a cone\n\t\t\td--> axis vector of the cone (direction)\n\t\t\ta--> apex (end of cone)\n\t\t\th--> height\n\t\t\tr--> radious\n\t\t\tn--> number of divisions\n\t\t**/\n\t\tvoid drawCone(const QVector3D &d, const QVector3D &a,\n\t\t\tconst qreal h, const qreal rd, const int n) {\n\t\t\t\tQVector3D c = a + (-d * h);\n\t\t\t\tQVector3D e0 = perp(d);\n\t\t\t\tQVector3D e1 = QVector3D::crossProduct(e0, d);\n\t\t\t\tqreal angInc = 360.0 / n * (M_PI/180.0f);//M_PI_DIV180;\n\n\t\t\t\t// draw cone top\n\t\t\t\tglBegin(GL_TRIANGLE_FAN);\n\t\t\t\tglVertex3f(a.x(), a.y(), a.z());\n\t\t\t\tfor(int i = 0; i <= n; i++) {\n\t\t\t\t\tqreal rad = angInc * i;\n\t\t\t\t\tQVector3D p = c + (((e0 * cos(rad)) + (e1 * sin(rad))) * rd);\n\t\t\t\t\tglVertex3f(p.x(), p.y(), p.z());\n\t\t\t\t}\n\t\t\t\tglEnd();\n\n\t\t\t\t// draw cone bottom\n\t\t\t\tglBegin(GL_TRIANGLE_FAN);\n\t\t\t\tglVertex3f(c.x(), c.y(), c.z());\n\t\t\t\tfor(int i = n-1; i >= 0; i--) {\n\t\t\t\t\tqreal rad = angInc * i;\n\t\t\t\t\tQVector3D p = c + (((e0 * cos(rad)) + (e1 * sin(rad))) * rd);\n\t\t\t\t\tglVertex3f(p.x(), p.y(), p.z());\n\t\t\t\t}\n\t\t\t\tglEnd();\n\t\t}//\n\n\t\tfloat deg2rad(float deg)\n\t\t{\n\t\t\treturn ((deg*_PI)/180.0f);\n\t\t}\n\n\t\tfloat rad2deg(float rad)\n\t\t{\n\t\t\treturn ((rad*180.0f)/_PI);\n\t\t}\n\n\n\t\tbool isIdxWithinBMatrix(int r, int c, tBoostMatrix &m)\n\t\t{\n\t\t\treturn (r < m.size1() && c < m.size2() && r>=0 && c>=0);\n\t\t}\n\n\t\tdouble sumElementsinRow(int r, LC::misctools::tBoostMatrix &m)\n\t\t{\n\t\t\tassert(r < m.size1());\n\t\t\tdouble sum = 0.0f;\n\n\t\t\tfor(int i=0; i<m.size2(); ++i){\n\t\t\t\tsum += (m(r,i));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\n\t\tdouble sumElementsinColumn(int c, LC::misctools::tBoostMatrix &m)\n\t\t{\n\t\t\tassert(c < m.size2());\n\t\t\tdouble sum = 0.0f;\n\n\t\t\tfor(int i=0; i<m.size1(); ++i){\n\t\t\t\tsum += (m(i,c));\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\n\t\tvoid printBMatrix(tBoostMatrix &m)\n\t\t{\t\n\t\t\tfor(int i=0; i<m.size1(); ++i){\t\t\t\t\n\t\t\t\tfor(int j=0; j<m.size2(); ++j){\n\t\t\t\t\tstd::cout << m(i,j) << \" \";\n\t\t\t\t}\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\n\t\tvoid printQMatrix4x4(QMatrix4x4 &m)\n\t\t{\t\n\t\t\tfor(int i=0; i<4; ++i){\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t\tfor(int j=0; j<4; ++j){\n\t\t\t\t\tstd::cout << m(i,j) << \"\\t\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\n\t\tvoid initBMatrix(tBoostMatrix &m)\n\t\t{\n\t\t\tfor(int i=0; i<m.size1(); ++i){\n\t\t\t\tfor(int j=0; j<m.size2(); ++j){\n\t\t\t\t\tm(i,j) = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\t//********************\n\t\t// Geometry.\n\t\t// Classes and functions for geometric data\n\t\t//********************\n\n\t\t/**\n\t\t* Returns index of the point in pointArray that is closest to point\n\t\t**/\n\t\tfloat getClosestPointInArray(std::vector<QVector3D> &pointArray, QVector3D &point, int &idx)\n\t\t{\n\t\t\tidx = -1;\n\t\t\tfloat minDist = FLT_MAX;\n\t\t\tfloat curDist;\n\t\t\tfor(int i=0; i<pointArray.size(); ++i){\n\t\t\t\tcurDist = (point-pointArray[i]).lengthSquared();\n\t\t\t\tif( curDist < minDist ){\n\t\t\t\t\tminDist = curDist;\n\t\t\t\t\tidx = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn sqrt(minDist);\n\t\t}\n\n\t\tfloat getClosestPointInArrayXY(std::vector<QVector3D> &pointArray, QVector3D &point, int &idx){\n\t\t\tidx = -1;\n\t\t\tfloat minDist = FLT_MAX;\n\t\t\tfloat curDist;\n\t\t\tfor(int i=0; i<pointArray.size(); ++i){\n\t\t\t\tcurDist = (point.x()-pointArray[i].x())*(point.x()-pointArray[i].x())+(point.y()-pointArray[i].y())*(point.y()-pointArray[i].y());\n\t\t\t\tif( curDist < minDist ){\n\t\t\t\t\tminDist = curDist;\n\t\t\t\t\tidx = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn sqrt(minDist);\n\t\t}\n\n\t\tQVector3D calculateNormal(QVector3D& p0,QVector3D& p1,QVector3D& p2)\n\t\t{\n\t\t\treturn (QVector3D::normal((p1-p0),(p2-p1)));\n\t\t}\n\n\t\tbool isPointWithinLoop(std::vector<QVector3D> &loop, QVector3D &pt)\n\t\t{\n\t\t\t/*boost::geometry::ring_2d bg_loop;\n\t\t\tboost::geometry::point_2d bg_testPt;\n\n\t\t\tboost::geometry::assign(bg_loop, loop);\n\t\t\tboost::geometry::correct(bg_loop);\n\t\t\tbg_testPt.x(pt.x());\n\t\t\tbg_testPt.y(pt.y());\n\n\t\t\treturn boost::geometry::within(bg_testPt, bg_loop);*/\n\n\t\t\tint i, j, c = 0;\n\t\t\tfor (i = 0, j = loop.size()-1; i < loop.size(); j = i++) {\n\t\t\t\tif ( ((loop[i].y()>pt.y()) != (loop[j].y()>pt.y())) &&\n\t\t\t\t\t(pt.x() < (loop[j].x()-loop[i].x()) * (pt.y()-loop[i].y()) / (loop[j].y()-loop[i].y()) + loop[i].x()) )\n\t\t\t\t\tc = !c;\n\t\t\t}\n\t\t\treturn c;\n\n\t\t}\n\n\t\t/*bool isPointWithinLoop(boost::geometry::ring_type<LC::misctools::Polygon3D>::type &bg_loop, QVector3D &pt)\n\t\t{\t\n\t\t\tboost::geometry::ring_type<LC::misctools::Polygon3D>::type bg_testPt;\n\n\t\t\tbg_testPt.x(pt.x());\n\t\t\tbg_testPt.y(pt.y());\n\n\t\t\treturn boost::geometry::within(bg_testPt, bg_loop);\n\t\t}*/\n\n\t\t//Distance from segment ab to point c\n\t\tfloat pointSegmentDistanceXY(QVector3D &a, QVector3D &b, QVector3D &c, QVector3D &closestPtInAB)\n\t\t{\n\t\t\tfloat dist;\t\t\n\n\t\t\tfloat r_numerator = (c.x()-a.x())*(b.x()-a.x()) + (c.y()-a.y())*(b.y()-a.y());\n\t\t\tfloat r_denomenator = (b.x()-a.x())*(b.x()-a.x()) + (b.y()-a.y())*(b.y()-a.y());\n\t\t\tfloat r = r_numerator / r_denomenator;\n\t\t\t//\n\t\t\tfloat px = a.x() + r*(b.x()-a.x());\n\t\t\tfloat py = a.y() + r*(b.y()-a.y());\n\t\t\t//    \n\t\t\tfloat s =  ((a.y()-c.y())*(b.x()-a.x())-(a.x()-c.x())*(b.y()-a.y()) ) / r_denomenator;\n\n\t\t\tfloat distanceLine = fabs(s)*sqrt(r_denomenator);\n\n\t\t\t//\n\t\t\t// (xx,yy) is the point on the lineSegment closest to (cx,cy)\n\t\t\t//\n\t\t\tclosestPtInAB.setX(px);\n\t\t\tclosestPtInAB.setY(py);\n\t\t\tclosestPtInAB.setZ(0.0f);\n\n\t\t\tif ( (r >= 0) && (r <= 1) )\n\t\t\t{\n\t\t\t\tdist = distanceLine;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat dist1 = (c.x()-a.x())*(c.x()-a.x()) + (c.y()-a.y())*(c.y()-a.y());\n\t\t\t\tfloat dist2 = (c.x()-b.x())*(c.x()-b.x()) + (c.y()-b.y())*(c.y()-b.y());\n\t\t\t\tif (dist1 < dist2)\n\t\t\t\t{\t\n\t\t\t\t\tdist = sqrt(dist1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdist = sqrt(dist2);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn abs(dist);\n\t\t}\n\n\n\t\tfloat pointSegmentDistanceXY(QVector3D &a, QVector3D &b, QVector3D &c)\n\t\t{\n\t\t\tQVector3D closestPt;\n\t\t\treturn pointSegmentDistanceXY(a, b, c, closestPt);\n\n\t\t}\n\n\t\t/**\n\t\t* Computes the intersection between two line segments on the XY plane\n\t\t* Segments must intersect within their extents for the intersection to be valid\n\t\t* z coordinate is ignored\n\t\t**/\n\t\tbool segmentSegmentIntersectXY(QVector2D &a, QVector2D &b, QVector2D &c, QVector2D &d,\n\t\t\tfloat *tab, float *tcd, bool segmentOnly, QVector2D &intPoint)\n\t\t{\n\t\t\tQVector2D u = b - a;\n\t\t\tQVector2D v = d - c;\n\n\t\t\tif( u.lengthSquared() < MTC_FLOAT_TOL  ||  v.lengthSquared() < MTC_FLOAT_TOL )\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfloat numer = v.x()*(c.y()-a.y()) + v.y()*(a.x()-c.x());\n\t\t\tfloat denom = u.y()*v.x() - u.x()*v.y();\n\n\t\t\tif (denom == 0.0f)  {\n\t\t\t\t// they are parallel\n\t\t\t\t*tab = 0.0f;\n\t\t\t\t*tcd = 0.0f;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfloat t0 = numer / denom;\n\n\t\t\tQVector2D ipt = a + t0*u;\n\t\t\tQVector2D tmp = ipt - c;\n\t\t\tfloat t1;\n\t\t\tif (QVector2D::dotProduct(tmp, v) > 0.0f){\n\t\t\t\tt1 = tmp.length() / v.length();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tt1 = -1.0f * tmp.length() / v.length();\n\t\t\t}\n\n\t\t\t//Check if intersection is within segments\n\t\t\tif( !( (t0 >= MTC_FLOAT_TOL) && (t0 <= 1.0f-MTC_FLOAT_TOL) && (t1 >= MTC_FLOAT_TOL) && (t1 <= 1.0f-MTC_FLOAT_TOL) ) ){\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t*tab = t0;\n\t\t\t*tcd = t1;\n\t\t\tQVector2D dirVec = b-a;\n\n\t\t\tintPoint = a+(*tab)*dirVec;\n\t\t\treturn true;\n\t\t}\n\n\n\t\tbool rayTriangleIntersect(QVector3D &rayPivot, QVector3D &rayDirection,\n\t\t\tQVector3D &p0, QVector3D &p1, QVector3D &p2, QVector3D &intPt)\n\t\t{\n\t\t\t//int rayIntersectsTriangle(float *p, float *d, float *v0, float *v1, float *v2) {\n\n\t\t\tQVector3D e1, e2, h, s, q;\n\t\t\tfloat a,f,u,v;\n\n\t\t\t//vector(e1,v1,v0);\n\t\t\t//vector(e2,v2,v0);\n\t\t\te1 = p1-p0;\n\t\t\te2 = p2-p0;\n\n\t\t\t//crossProduct(h,d,e2);\n\t\t\th = QVector3D::crossProduct(rayDirection, e2);\t\t\t\t\n\t\t\t//a = innerProduct(e1,h);\n\t\t\ta = QVector3D::dotProduct(e1,h);\n\n\t\t\tif (a > -0.00001 && a < 0.00001)\n\t\t\t\treturn(false);\n\n\t\t\tf = 1/a;\n\n\t\t\t//vector(s,p,v0);\n\t\t\ts = rayPivot - p0;\n\n\t\t\t//u = f * (innerProduct(s,h));\n\t\t\tu = f * (QVector3D::dotProduct(s,h));\n\n\t\t\tif (u < 0.0 || u > 1.0)\n\t\t\t\treturn(false);\n\n\t\t\t//crossProduct(q,s,e1);\n\t\t\tq = QVector3D::crossProduct(s, e1);\n\t\t\t//v = f * innerProduct(d,q);\n\t\t\tv = f * QVector3D::dotProduct(rayDirection, q);\n\n\t\t\tif (v < 0.0 || u + v > 1.0)\n\t\t\t\treturn(false);\n\n\t\t\t// at this stage we can compute t to find out where\n\t\t\t// the intersection point is on the line\n\t\t\t//t = f * innerProduct(e2,q);\n\t\t\tfloat t = f * QVector3D::dotProduct(e2,q);\n\n\t\t\tif (t > 0.00001) // ray intersection\n\t\t\t\treturn(true);\n\n\t\t\telse // this means that there is a line intersection\n\t\t\t\t// but not a ray intersection\n\t\t\t\treturn (false);\n\t\t}\n\n\t\tbool rayTriangleIntersect(QVector3D &rayPivot, QVector3D &rayDirection,\n\t\t\tQVector3D &p0, QVector3D &p1, QVector3D &p2)\n\t\t{\n\t\t\tQVector3D intPt;\t\t\t\n\t\t\treturn rayTriangleIntersect(rayPivot, rayDirection, p0, p1, p2, intPt);\n\t\t}\n\n\t\t/**\n\t\t* Angle between 3 points A-B-C\n\t\t**/\n\t\tfloat angleThreePoints(QVector3D &pa, QVector3D &pb, QVector3D &pc)\n\t\t{\n\t\t\tfloat a = (pb-pc).length();\n\t\t\tfloat b = (pa-pc).length();\n\t\t\tfloat c = (pa-pb).length();\n\t\t\treturn acos( 0.999f*(a*a + c*c - b*b) / (2.0f*a*c) );\n\t\t}\n\n\t\tQVector3D getColorFromIdx(int i)\n\t\t{\n\t\t\tQVector3D colorOut;\n\t\t\tcolorOut.setX( ((float)((i*300) %255)) / 255.0f  );\n\t\t\tcolorOut.setY( ((float)((i*400) %255)) / 255.0f  );\n\t\t\tcolorOut.setZ( ((float)((i*500)  %255)) / 255.0f  );\n\n\t\t\treturn colorOut;\n\t\t}\n\n\t\tint planeIntersectWithLine(QVector3D &p1, QVector3D &p2, QVector3D &n,QVector3D &p0, double &t, QVector3D &x){\n\t\t\tdouble num, den, p21[3];\n\t\t\tdouble fabsden, fabstolerance;\n\n\t\t\t// Compute line vector\n\t\t\tp21[0] = p2.x() - p1.x();\n\t\t\tp21[1] = p2.y() - p1.y();\n\t\t\tp21[2] = p2.z() - p1.z();\n\n\t\t\t// Compute denominator.  If ~0, line and plane are parallel.\n\t\t\tnum = QVector3D::dotProduct(n,p0) - ( n.x()*p1.x() + n.y()*p1.y() + n.z()*p1.z() ) ;\n\t\t\tden = n.x()*p21[0] + n.y()*p21[1] + n.z()*p21[2];\n\n\t\t\t// If denominator with respect to numerator is \"zero\", then the line and\n\t\t\t// plane are considered parallel.\n\n\t\t\t// trying to avoid an expensive call to fabs()\n\t\t\tif (den < 0.0)\n\t\t\t\tfabsden = -den;\n\t\t\telse\n\t\t\t\tfabsden = den;\n\t\t\tif (num < 0.0)\n\t\t\t\tfabstolerance = -num*1.0e-06;\n\t\t\telse\n\t\t\t\tfabstolerance = num*1.0e-06;\n\t\t\tif ( fabsden <= fabstolerance ){\n\t\t\t\tt = DBL_MAX;\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\t// valid intersection\n\t\t\tt = num / den;\n\n\t\t\tx.setX(p1.x() + t*p21[0]);\n\t\t\tx.setY(p1.y() + t*p21[1]);\n\t\t\tx.setZ(p1.z() + t*p21[2]);\n\n\t\t\tif ( t >= 0.0 && t <= 1.0 )\n\t\t\t\treturn 1;\n\t\t\telse\n\t\t\t\treturn 0;\n\t}//\n\n\n\t\tdouble angleBetweenVectors(QVector3D &vec1, QVector3D &vec2)\n\t\t{\t\n\t\t\treturn acos( 0.999*(QVector3D::dotProduct(vec1, vec2)) / ( vec1.length() * vec2.length() ) );\n\t\t}\n\n\n\t\t/**\n\t\t* Given three non colinear points p0, p1, p2, this function computes\n\t\t* the intersection between the lines A and B. Line A is the line parallel to the segment p0-p1\n\t\t* and at a distance d01 from that segment. Line B is the line parallel to the segment\n\t\t* p1-p2 at a distance d12 from that segment.\n\t\t* Returns true if point is successfully computed\n\t\t**/\n\n\t\tbool getIrregularBisector(QVector3D &p0,\n\t\t\tQVector3D &p1, QVector3D &p2, float d01, float d12,\n\t\t\tQVector3D &intPt)\n\t\t{\n\t\t\tdouble alpha;\n\t\t\tdouble theta;\n\t\t\tdouble L;\n\n\t\t\tQVector3D p1_p0;\n\t\t\tQVector3D p1_p2;\n\t\t\tQVector3D p1_p2_perp;\n\t\t\tQVector3D crossP;\n\n\t\t\tp1_p0 = p0 - p1;\n\t\t\tp1_p0.setZ(0.0f);\n\n\t\t\tp1_p2 = p2 - p1;\n\t\t\tp1_p2.setZ(0.0f);\n\n\t\t\tp1_p2_perp.setX( -p1_p2.y() );\n\t\t\tp1_p2_perp.setY(  p1_p2.x() );\n\t\t\tp1_p2_perp.setZ( 0.0f );\n\n\t\t\talpha = angleBetweenVectors(p1_p0, p1_p2);\t\t\t\t\n\n\t\t\tif( !(alpha == alpha) ){\n\t\t\t\treturn false;\n\t\t\t}\t\t\t\t\n\n\t\t\ttheta = atan2( sin(alpha), (d01 / d12) + cos(alpha) );\t\t\t\t\n\t\t\tL = d12 / sin(theta);\n\n\t\t\t//This is done to handle convex vs. concave angles in polygon\n\t\t\tcrossP = QVector3D::crossProduct(p1_p2, p1_p0);\n\n\t\t\tif(crossP.z() > 0){\n\t\t\t\t//CCW polygon (A + B + C)\n\t\t\t\t//CW  polygon (A - B - C)\n\t\t\t\tintPt = p1 + (p1_p2.normalized())*L*cos(theta) +\n\t\t\t\t\t(p1_p2_perp.normalized())*d12;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//CCW polygon (A - B + C)\n\t\t\t\t//CW  polygon (A + B - C)\n\t\t\t\tintPt = p1 - (p1_p2.normalized())*L*cos(theta) +\n\t\t\t\t\t(p1_p2_perp.normalized())*d12;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t/**\n\t\t* Checks if contour A is within contour B\n\t\t**/\n\t\tbool is2DRingWithin2DRing( boost::geometry::ring_type<LC::misctools::Polygon3D>::type &contourA, boost::geometry::ring_type<LC::misctools::Polygon3D>::type &contourB)\n\t\t{\n\t\t\tfor(int i=0; i<contourA.size(); ++i){\n\t\t\t\tif( !boost::geometry::within( contourA[i], contourB) ){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\n\t\t/**\n\t\t* @brief: Merge consecutive vertices that are within a distance threshold to each other\n\t\t**/\n\t\tint Polygon3D::cleanLoop(Loop3D &pin, Loop3D &pout, float threshold=1.0f)\n\t\t{\t\n\t\t\tfloat thresholdSq = threshold*threshold;\n\n\t\t\tif(pin.size()<3){\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tboost::geometry::ring_type<LC::misctools::Polygon3D>::type bg_pin;\n\t\t\tboost::geometry::ring_type<LC::misctools::Polygon3D>::type bg_pout;\n\t\t\tboost::geometry::assign(bg_pin, pin);\n\t\t\tboost::geometry::correct(bg_pin);\n\t\t\tboost::geometry::simplify(bg_pin, bg_pout, threshold);\n\n\t\t\t//strategy::simplify::douglas_peucker\n\n\t\t\t//copy points back\n\t\t\tQVector3D tmpPt;\n\t\t\tfor(size_t i=0; i< bg_pout.size(); ++i){\t\t\t\t\t\t\n\t\t\t\ttmpPt.setX( bg_pout[i].x() );\n\t\t\t\ttmpPt.setY( bg_pout[i].y() );\n\t\t\t\tpout.push_back(tmpPt);\t\t\t\t\t\t\n\t\t\t}\n\n\t\t\t//remove last point\n\t\t\tif( (pout[0] - pout[pout.size()-1]).lengthSquared() < thresholdSq ){\n\t\t\t\tpout.pop_back();\t\t\t\t\n\t\t\t}\n\n\t\t\t//clean angles\n\t\t\tint next, prev;\n\t\t\tQVector3D cur_prev, cur_next;\n\t\t\tfloat ang;\n\t\t\tfloat angleThreshold = 0.01f;\n\t\t\tfor(size_t i=0; i<pout.size(); ++i){\n\t\t\t\tnext = (i+1)%pout.size();\n\t\t\t\tprev = (i-1+pout.size())%pout.size();\n\t\t\t\tcur_prev = pout[prev]-pout[i];\n\t\t\t\tcur_next = pout[next]-pout[i];\n\n\t\t\t\tang = angleBetweenVectors(cur_prev, cur_next);\n\t\t\t\tif( (fabs(ang) < angleThreshold) \n\t\t\t\t\t|| (fabs(ang - _PI ) < angleThreshold)\n\t\t\t\t\t|| (!(ang==ang) ) )\n\t\t\t\t{\n\t\t\t\t\t//std::cout << ang << \" \";\n\t\t\t\t\tpout.erase(pout.begin() + i);\n\t\t\t\t\t--i;\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tfloat Polygon3D::computeInset(std::vector<float> &offsetDistances, Loop3D &pgonInset, bool computeArea)\n\t\t{\n\t\t\tLoop3D cleanPgon;\n\t\t\tdouble tol = 0.01f;\n\n\t\t\tcleanPgon = this->contour;\n\n\t\t\tint prev, next;\n\t\t\tint cSz = cleanPgon.size();\n\n\t\t\tif(cSz < 3){\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\n\t\t\tif(reorientFace(cleanPgon)){\t\t\t\t\n\t\t\t\tstd::reverse(offsetDistances.begin(), offsetDistances.end() - 1);\n\t\t\t}\n\n\t\t\t//if offsets are zero, add a small epsilon just to avoid division by zero\n\t\t\tfor(size_t i=0; i<offsetDistances.size(); ++i){\n\t\t\t\tif(fabs(offsetDistances[i]) < tol){\n\t\t\t\t\toffsetDistances[i] = tol;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpgonInset.resize(cSz);\n\n\t\t\tQVector3D intPt;\n\n\n\t\t\tfor(int cur=0; cur<cSz; ++cur){\n\t\t\t\t//Some geometry and trigonometry\n\n\t\t\t\t//point p1 is the point with index cur\n\t\t\t\tprev = (cur-1+cSz)%cSz; //point p0\n\t\t\t\tnext = (cur+1)%cSz;\t  //point p2\n\n\t\t\t\tgetIrregularBisector(cleanPgon[prev], cleanPgon[cur], cleanPgon[next],\n\t\t\t\t\toffsetDistances[prev], offsetDistances[cur], intPt);\n\n\t\t\t\tpgonInset[cur] = intPt;\n\t\t\t}\n\n\t\t\t//temp\n\t\t\t//pgonInset = cleanPgon;\n\n\t\t\t//Compute inset area\n\t\t\tif(computeArea){\n\n\t\t\t\tboost::geometry::ring_type<LC::misctools::Polygon3D>::type bg_contour;\n\t\t\t\tboost::geometry::ring_type<LC::misctools::Polygon3D>::type bg_contour_inset;\n\t\t\t\tfloat contArea;\n\t\t\t\tfloat contInsetArea;\n\n\t\t\t\tif(pgonInset.size()>0){\n\t\t\t\t\tboost::geometry::assign(bg_contour_inset, pgonInset);\n\t\t\t\t\tboost::geometry::correct(bg_contour_inset);\n\n\t\t\t\t\tif(boost::geometry::intersects(bg_contour_inset)){\n\t\t\t\t\t\tpgonInset.clear();\n\t\t\t\t\t\treturn 0.0f;\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tboost::geometry::assign(bg_contour, cleanPgon);\n\t\t\t\t\t\tboost::geometry::correct(bg_contour);\n\t\t\t\t\t\t//if inset is not within polygon\n\t\t\t\t\t\tif( !is2DRingWithin2DRing(bg_contour_inset, bg_contour) ){\n\t\t\t\t\t\t\tpgonInset.clear();\n\t\t\t\t\t\t\treturn 0.0f;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontArea = fabs(boost::geometry::area(bg_contour));\n\t\t\t\t\t\t\tcontInsetArea = fabs(boost::geometry::area(bg_contour_inset));\n\n\t\t\t\t\t\t\tif(contInsetArea < contArea){\n\t\t\t\t\t\t\t\t//return boost::geometry::area(bg_contour_inset);\n\t\t\t\t\t\t\t\treturn contInsetArea;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tpgonInset.clear();\n\t\t\t\t\t\t\t\treturn 0.0f;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpgonInset.clear();\n\t\t\t\t\treturn 0.0f;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0.0f;\n\n\t\t}\n\n\t\tbool Polygon3D::isSelfIntersecting(void)\n\t\t{\n\t\t\tboost::geometry::ring_type<LC::misctools::Polygon3D>::type bg_pgon;\n\t\t\tboost::geometry::assign(bg_pgon, this->contour);\n\t\t\tboost::geometry::correct(bg_pgon);\n\t\t\treturn boost::geometry::intersects(bg_pgon);\n\t\t}\n\n\t\t//===================================================================\n\t\t// area3D_Polygon(): computes the area of a 3D planar polygon\n\t\t//    Input:  int n = the number of vertices in the polygon\n\t\t//            Point* V = an array of n+2 vertices in a plane\n\t\t//                       with V[n]=V[0] and V[n+1]=V[1]\n\t\t//            Point N = unit normal vector of the polygon's plane\n\t\t//    Return: the (float) area of the polygon\n\t\t//===================================================================\n\t\t//float area3D_Polygon( int n, Point* V, Point N )\n\t\tfloat area3D_Polygon( Loop3D &pin )\t\t\n\t\t{\n\t\t\tint n = pin.size();\n\n\t\t\tif(n < 3){\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\n\t\t\tQVector3D normVec = Polygon3D::getLoopNormalVector(pin);\n\n\t\t\tfloat area = 0.0f;\n\t\t\tfloat an, ax, ay, az;  // abs value of normal and its coords\n\t\t\tint   coord;           // coord to ignore: 1=x, 2=y, 3=z\n\t\t\tint   i, j, k;         // loop indices\n\n\t\t\t// select largest abs coordinate to ignore for projection\n\t\t\tax = (normVec.x()>0 ? normVec.x() : -normVec.x());     // abs x-coord\n\t\t\tay = (normVec.y()>0 ? normVec.y() : -normVec.y());     // abs y-coord\n\t\t\taz = (normVec.z()>0 ? normVec.z() : -normVec.z());     // abs z-coord\n\n\t\t\tcoord = 3;                     // ignore z-coord\n\t\t\tif (ax > ay) {\n\t\t\t\tif (ax > az) coord = 1;    // ignore x-coord\n\t\t\t}\n\t\t\telse if (ay > az) coord = 2;   // ignore y-coord\n\n\t\t\t// compute area of the 2D projection\n\t\t\t//for (i=1, j=2, k=0; i<=n; i++, j++, k++)\n\t\t\tfor (k=0; k<n; ++k){\n\t\t\t\ti = (k+1)%n;\n\t\t\t\tj = (k+2)%n;\n\t\t\t\tswitch (coord) {\n\t\t\t\tcase 1:\n\t\t\t\t\tarea += (pin[i].y() * (pin[j].z() - pin[k].z()));\n\t\t\t\t\tcontinue;\n\t\t\t\tcase 2:\n\t\t\t\t\tarea += (pin[i].x() * (pin[j].z() - pin[k].z()));\n\t\t\t\t\tcontinue;\n\t\t\t\tcase 3:\n\t\t\t\t\tarea += (pin[i].x() * (pin[j].y() - pin[k].y()));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// scale to get area before projection\n\t\t\tan = sqrt( ax*ax + ay*ay + az*az);  // length of normal vector\n\t\t\tswitch (coord) {\n\t\t\tcase 1:\n\t\t\t\tarea *= (an / (2*ax));\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tarea *= (an / (2*ay));\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tarea *= (an / (2*az));\n\t\t\t}\n\t\t\treturn fabs(area);\n\t\t}\n\t\t//===================================================================\n\n\n\t\tfloat Polygon3D::computeLoopArea(Loop3D &pin, bool parallelToXY)\n\t\t{\n\t\t\tfloat _area = 0.0f;\n\t\t\t//if polygon is parallel to XY plane\n\t\t\tif(parallelToXY){\n\t\t\t\tboost::geometry::ring_type<LC::misctools::Polygon3D>::type bg_pgon;\n\t\t\t\tboost::geometry::assign(bg_pgon, pin);\n\t\t\t\t_area =  fabs(boost::geometry::area(bg_pgon));\n\t\t\t} else {\t\t\t\t\n\t\t\t\t_area = fabs(area3D_Polygon(pin));\n\t\t\t}\n\t\t\treturn _area;\n\t\t}\n\n\t\t//density: number of points to be generated per square meter\n\t\tvoid Polygon3D::sampleTriangularLoopInterior(Loop3D &pin, std::vector<QVector3D> &pts, float density)\n\t\t{\n\t\t\tif(pin.size()==3)\n\t\t\t{\n\n\t\t\t\tQVector3D tmpPt;\n\t\t\t\tQVector3D v1_minus_v0;\n\t\t\t\tQVector3D v2_minus_v0;\t\t\t\t\n\t\t\t\tQVector3D crossP;\n\n\t\t\t\tv1_minus_v0 = pin.at(1) - pin.at(0);\n\t\t\t\tv2_minus_v0 = pin.at(2) - pin.at(0);\n\n\t\t\t\t//float loopArea = computeLoopArea(pin);\n\t\t\t\tfloat loopArea = 0.5f*(QVector3D::crossProduct(v1_minus_v0, v2_minus_v0).length());\n\n\t\t\t\tint numSamples = (int)(density*loopArea);\n\n\t\t\t\t//std::cout << numSamples << \" \";\n\n\t\t\t\tfloat rand1, rand2;\n\n\t\t\t\tfor (int i=0; i<numSamples; ++i){\n\t\t\t\t\trand1 = LC::misctools::genRand();\n\t\t\t\t\trand2 = LC::misctools::genRand();\n\t\t\t\t\tif(rand1 + rand2 > 1.0f){\n\t\t\t\t\t\trand1 = 1.0 - rand1;\n\t\t\t\t\t\trand2 = 1.0 - rand2;\n\t\t\t\t\t}\n\n\t\t\t\t\ttmpPt = pin.at(0) + rand1*v1_minus_v0 + rand2*v2_minus_v0;\n\n\t\t\t\t\tpts.push_back(tmpPt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfloat Polygon3D::computeArea(bool parallelToXY)\n\t\t{\n\t\t\treturn Polygon3D::computeLoopArea(this->contour, parallelToXY);\n\t\t}\n\n\t\t/**\n\t\t* @brief: Get polygon axis aligned bounding box\n\t\t* @return: The dimensions of the AABB \n\t\t**/\n\t\tQVector3D Polygon3D::getLoopAABB(Loop3D &pin, QVector3D &minCorner, QVector3D &maxCorner)\n\t\t{\n\t\t\tmaxCorner = QVector3D(-FLT_MAX, -FLT_MAX, -FLT_MAX);\n\t\t\tminCorner = QVector3D( FLT_MAX,  FLT_MAX,  FLT_MAX);\n\n\t\t\tQVector3D curPt;\n\n\t\t\tfor(int i=0; i<pin.size(); ++i){\n\t\t\t\tcurPt = pin.at(i);\n\t\t\t\tif( curPt.x() > maxCorner.x() ){\n\t\t\t\t\tmaxCorner.setX(curPt.x());\n\t\t\t\t}\n\t\t\t\tif( curPt.y() > maxCorner.y() ){\n\t\t\t\t\tmaxCorner.setY(curPt.y());\n\t\t\t\t}\n\t\t\t\tif( curPt.z() > maxCorner.z() ){\n\t\t\t\t\tmaxCorner.setZ(curPt.z());\n\t\t\t\t}\n\t\t\t\t//------------\n\t\t\t\tif( curPt.x() < minCorner.x() ){\n\t\t\t\t\tminCorner.setX(curPt.x());\n\t\t\t\t}\n\t\t\t\tif( curPt.y() < minCorner.y() ){\n\t\t\t\t\tminCorner.setY(curPt.y());\n\t\t\t\t}\n\t\t\t\tif( curPt.z() < minCorner.z() ){\n\t\t\t\t\tminCorner.setZ(curPt.z());\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn QVector3D(maxCorner - minCorner);\n\t\t}\n\n\t\tvoid Polygon3D::transformLoop(Loop3D &pin, Loop3D &pout, QMatrix4x4 &transformMat)\n\t\t{\n\t\t\tpout = pin;\n\t\t\tfor(int i=0; i<pin.size(); ++i){\n\t\t\t\tpout.at(i) = transformMat*pin.at(i);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t* Get polygon oriented bounding box\n\t\t**/\n\t\tvoid Polygon3D::getLoopOBB(Loop3D &pin, QVector3D &size, QMatrix4x4 &xformMat)\n\t\t{\n\t\t\tfloat alpha = 0.0f;\t\t\t\n\t\t\tfloat deltaAlpha = 0.05*_PI;\n\t\t\tfloat bestAlpha;\n\n\t\t\tLC::misctools::Loop3D rotLoop;\n\t\t\tQMatrix4x4 rotMat;\n\t\t\tQVector3D minPt, maxPt;\n\t\t\tQVector3D origMidPt;\n\t\t\tQVector3D boxSz;\n\t\t\tQVector3D bestBoxSz;\n\t\t\tfloat curArea;\n\t\t\tfloat minArea = FLT_MAX;\n\n\t\t\trotLoop = pin;\n\t\t\tPolygon3D::getLoopAABB(rotLoop, minPt, maxPt);\n\t\t\torigMidPt = 0.5f*(minPt + maxPt);\n\n\t\t\t//while(alpha < 0.5f*_PI){\n\t\t\tint cSz = pin.size();\n\t\t\tQVector3D difVec;\n\t\t\tfor(int i=0; i<pin.size(); ++i){\n\t\t\t\tdifVec = (pin.at((i+1)%cSz) - pin.at(i)).normalized();\n\t\t\t\talpha = atan2(difVec.x(), difVec.y());\n\t\t\t\trotMat.setToIdentity();\t\t\t\t\n\t\t\t\trotMat.rotate(rad2deg(alpha), 0.0f, 0.0f, 1.0f);\t\t\t\t\n\n\t\t\t\ttransformLoop(pin, rotLoop, rotMat);\n\t\t\t\tboxSz = Polygon3D::getLoopAABB(rotLoop, minPt, maxPt);\n\t\t\t\tcurArea = boxSz.x() * boxSz.y();\n\t\t\t\tif(curArea < minArea){\n\t\t\t\t\tminArea = curArea;\n\t\t\t\t\tbestAlpha = alpha;\n\t\t\t\t\tbestBoxSz = boxSz;\n\t\t\t\t}\n\t\t\t\t//alpha += deltaAlpha;\n\t\t\t}\n\n\t\t\txformMat.setToIdentity();\t\t\t\t\t\t\t\t\t\t\t\n\t\t\txformMat.rotate(rad2deg(bestAlpha), 0.0f, 0.0f, 1.0f);\n\t\t\txformMat.setRow(3, QVector4D(origMidPt.x(), origMidPt.y(), origMidPt.z(), 1.0f));\t\t\t\n\t\t\tsize = bestBoxSz;\n\t\t}\n\n\n\t\tvoid Polygon3D::getMyOBB(QVector3D &size, QMatrix4x4 &xformMat)\n\t\t{\n\t\t\tPolygon3D::getLoopOBB(this->contour, size, xformMat);\n\t\t}\n\n\n\n\t\tvoid Polygon3D::extrudePolygon(LC::misctools::Polygon3D &basePgon, float height,\n\t\t\tstd::vector<LC::misctools::Polygon3D> &pgonExtrusion)\n\t\t{\t\n\t\t\tQVector3D zTransV(0.0f, 0.0f, height);\n\t\t\tint iNext;\n\t\t\tint pgonContourSz = basePgon.contour.size();\n\t\t\tfor(int i=0; i<pgonContourSz; ++i){\n\t\t\t\tiNext = (i+1)%pgonContourSz;\n\n\t\t\t\t//construct face\n\t\t\t\tLC::misctools::Polygon3D tmpPgon1;\n\t\t\t\tLC::misctools::Polygon3D tmpPgon2;\n\n\t\t\t\ttmpPgon1.contour.reserve(3); //pre allocate capacity for polygon contour\n\t\t\t\ttmpPgon1.contour.push_back(basePgon.contour[i]);\n\t\t\t\ttmpPgon1.contour.push_back(basePgon.contour[iNext]);\n\t\t\t\ttmpPgon1.contour.push_back(basePgon.contour[iNext] + zTransV);\n\n\t\t\t\ttmpPgon2.contour.reserve(3); //pre allocate capacity for polygon contour\n\t\t\t\ttmpPgon2.contour.push_back(basePgon.contour[i]);\n\t\t\t\ttmpPgon2.contour.push_back(basePgon.contour[iNext] + zTransV);\n\t\t\t\ttmpPgon2.contour.push_back(basePgon.contour[i]   + zTransV);\t\t\n\n\t\t\t\t//add two triangular faces to solid\n\t\t\t\tpgonExtrusion.push_back(tmpPgon1);\n\t\t\t\tpgonExtrusion.push_back(tmpPgon2);\n\t\t\t}\n\t\t}\n\n\n\t\t//Shortest distance from a point to a polygon\n\t\tfloat Polygon3D::distanceXYToPoint(Loop3D &pin, QVector3D &pt)\n\t\t{\n\t\t\tfloat minDist = FLT_MAX;\n\t\t\tfloat dist;\n\t\t\tint idxNext;\n\n\t\t\tfor(size_t i=0; i<pin.size(); ++i){\n\t\t\t\tidxNext = (i+1)%(pin.size());\n\t\t\t\tdist = pointSegmentDistanceXY(pin.at(i), pin.at(idxNext), pt);\n\t\t\t\tif(dist < minDist){\n\t\t\t\t\tminDist = dist;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn minDist;\n\t\t}\n\n\t\t//this function measures the minimum distance from the vertices of a contour A\n\t\t//\tto the edges of a contour B, i.e., it measures the distances from each vertex of A\n\t\t//  to all the edges in B, and returns the minimum of such distances\n\t\tfloat Polygon3D::distanceXYfromContourAVerticesToContourB(Loop3D &pA, Loop3D &pB)\n\t\t{\n\t\t\tfloat minDist = FLT_MAX;\n\t\t\tfloat dist;\n\n\t\t\tfor(size_t i=0; i<pA.size(); ++i){\n\t\t\t\tdist = Polygon3D::distanceXYToPoint(pB, pA.at(i));\n\t\t\t\tif(dist < minDist){\n\t\t\t\t\tminDist = dist;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn minDist;\n\t\t}\n\n\n\t\t//********************\n\t\t// Random numbers.\t\t\n\t\t//********************\n\n\t\tfloat genRand(void)\n\t\t{\n\t\t\treturn (rand()/(float(RAND_MAX)+1));\n\t\t}\n\n\t\tfloat genRand(float a, float b)\n\t\t{\n\t\t\treturn (genRand())*(b-a)+a;\n\t\t}\n\n\t\tfloat genRandNormal(float mean, float variance)\n\t\t{\n\n\t\t\tfloat m = mean;\n\t\t\tfloat s = sqrt(variance);\n\n\t\t\t/* mean m, standard deviation s */\n\t\t\tfloat x1, x2, w, y1;\n\t\t\tstatic float y2;\n\t\t\tstatic int use_last = 0;\n\n\t\t\tif (use_last)\t\t        /* use value from previous call */\n\t\t\t{\n\t\t\t\ty1 = y2;\n\t\t\t\tuse_last = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdo {\n\t\t\t\t\tx1 = 2.0 * genRand(0.0f, 1.0f) - 1.0;\n\t\t\t\t\tx2 = 2.0 * genRand(0.0f, 1.0f) - 1.0;\n\t\t\t\t\tw = x1 * x1 + x2 * x2;\n\t\t\t\t} while ( w >= 1.0 );\n\n\t\t\t\tw = sqrt( (-2.0 * log( w ) ) / w );\n\t\t\t\ty1 = x1 * w;\n\t\t\t\ty2 = x2 * w;\n\t\t\t\tuse_last = 1;\n\t\t\t}\n\n\t\t\treturn( m + y1 * s );\n\n\t\t}\n\n\n\t\t//********************\n\t\t// Rendering of geometric primitives\n\t\t//********************\n\n\t\t/**\n\t\t* Render circle parallel to XY plane, centered in X, Y, Z, and with radius r\n\t\t**/\n\t\tvoid renderCircle(float x, float y, float z, float radius)\n\t\t{\t\n\t\t\tint circle_points = 100;\n\t\t\tfloat angle;\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\t\t\t\n\n\t\t\tglBegin(GL_POLYGON);\t\t\n\t\t\tfor (int i = 0; i < circle_points; i++) {    \n\t\t\t\tangle = 2*_PI*i/circle_points; \n\t\t\t\tglVertex3f(x+radius*cos(angle), y+radius*sin(angle), z); \n\t\t\t}\t\n\t\t\tglEnd();\t\n\n\t\t\tglLineWidth(1.0);\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\t\t}\n\n\t\tvoid renderPolyline(Loop3D &loopIn, bool closed = true)\n\t\t{\n\t\t\tif(closed){\n\t\t\t\tglBegin(GL_LINE_LOOP);\n\t\t\t} else {\n\t\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\t}\n\n\t\t\tfor(int i=0; i<loopIn.size(); ++i){\n\t\t\t\tglVertex3f(\tloopIn.at(i).x(),\n\t\t\t\t\tloopIn.at(i).y(),\n\t\t\t\t\tloopIn.at(i).z() );\n\t\t\t}\t\t\t\n\t\t\tglEnd();\t\n\t\t}\n\n\n\t\t//http://www.concentric.net/~Ttwang/tech/inthash.htm\n\t\tunsigned long mix(unsigned long a, unsigned long b, unsigned long c)\n\t\t{\n\t\t\ta=a-b;  a=a-c;  a=a^(c >> 13);\n\t\t\tb=b-c;  b=b-a;  b=b^(a << 8);\n\t\t\tc=c-a;  c=c-b;  c=c^(b >> 13);\n\t\t\ta=a-b;  a=a-c;  a=a^(c >> 12);\n\t\t\tb=b-c;  b=b-a;  b=b^(a << 16);\n\t\t\tc=c-a;  c=c-b;  c=c^(b >> 5);\n\t\t\ta=a-b;  a=a-c;  a=a^(c >> 3);\n\t\t\tb=b-c;  b=b-a;  b=b^(a << 10);\n\t\t\tc=c-a;  c=c-b;  c=c^(b >> 15);\n\t\t\treturn c;\n\t\t}\n\n\n\t\t//********************\n\t\t// Color maps\n\t\t//********************\n\n\t\t/**\n\t\t* Convert Colors\n\t\t**/\n\t\t//cs.rit.edu/~ncs/color/t_convert.html\n\t\t// r,g,b values are from 0 to 1\n\t\t// h = [0,360], s = [0,1], v = [0,1]\n\t\t//\t\tif s == 0, then h = -1 (undefined)\n\t\tvoid HSVtoRGB( float *r, float *g, float *b, float h, float s, float v )\n\t\t{\n\t\t\tint i;\n\t\t\tfloat f, p, q, t;\n\t\t\tif( s == 0 ) {\n\t\t\t\t// achromatic (grey)\n\t\t\t\t*r = *g = *b = v;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\th /= 60;\t\t\t// sector 0 to 5\n\t\t\ti = floor( h );\n\t\t\tf = h - i;\t\t\t// factorial part of h\n\t\t\tp = v * ( 1 - s );\n\t\t\tq = v * ( 1 - s * f );\n\t\t\tt = v * ( 1 - s * ( 1 - f ) );\n\t\t\tswitch( i ) {\n\t\t\tcase 0:\n\t\t\t\t*r = v;\n\t\t\t\t*g = t;\n\t\t\t\t*b = p;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t*r = q;\n\t\t\t\t*g = v;\n\t\t\t\t*b = p;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t*r = p;\n\t\t\t\t*g = v;\n\t\t\t\t*b = t;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t*r = p;\n\t\t\t\t*g = q;\n\t\t\t\t*b = v;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\t*r = t;\n\t\t\t\t*g = p;\n\t\t\t\t*b = v;\n\t\t\t\tbreak;\n\t\t\tdefault:\t\t// case 5:\n\t\t\t\t*r = v;\n\t\t\t\t*g = p;\n\t\t\t\t*b = q;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapRainbowGet(float value, float minVal, float maxVal,\n\t\t\tfloat &r, float &g, float &b, bool invert, int flag)\n\t\t{\n\t\t\tfloat rangeVal;\n\t\t\trangeVal = maxVal - minVal;\n\t\t\tvalue = value-minVal;\n\n\t\t\tif(flag != LINEAR_SCL){\n\t\t\t\tswitch(flag){\t\t\n\t\t\t\tcase SQRT_SCL:\n\t\t\t\t\tvalue = sqrt(value);\n\t\t\t\t\trangeVal = sqrt(rangeVal);\n\t\t\t\t\tbreak;\t\t\n\t\t\t\tcase LOG_SCL:\t\t\t\n\t\t\t\t\tvalue = log(value);\n\t\t\t\t\trangeVal = log(rangeVal);\n\t\t\t\t\tbreak;\t\t\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\tvalue = value/rangeVal;\t\n\t\t\tif(invert){value = 1.0 - value;}\n\n\t\t\tif(value < 0.0){value = 0.0;}\n\t\t\telse if(value > 1.0){value = 1.0;}\n\n\t\t\tconst float dx=0.8;    \n\t\t\tvalue = (6-2*dx)*value+dx;\n\t\t\t\n\t\t\tr = std::max<float>(0.0,(3-fabs(value-4)-fabs(value-5))/2);\n\t\t\tg = std::max<float>(0.0,(4-fabs(value-2)-fabs(value-4))/2);\n\t\t\tb = std::max<float>(0.0,(3-fabs(value-1)-fabs(value-2))/2);\t\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapHotGet(float value, float min, float max,\n\t\t\tfloat &r, float &g, float &b, bool invert, int flag)\n\t\t{\n\t\t\tfloat max3=(max-min)/3.0;\n\t\t\tvalue-=min;\n\t\t\tif(value==FLT_MAX)\n\t\t\t{r=g=b=255;}\n\t\t\telse if(value<0)\n\t\t\t{r=g=b=0;}\n\t\t\telse if(value<max3)\n\t\t\t{r=(255*value/max3);g=0;b=0;}\n\t\t\telse if(value<2*max3)\n\t\t\t{r=255;g=(255*(value-max3)/max3);b=0;}\n\t\t\telse if(value<max)\n\t\t\t{r=255;g=255;b=(255*(value-2*max3)/max3);}\n\t\t\telse {r=g=b=255;}\n\t\t\tr/=255.0;  g/=255.0;  b/=255.0;\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapJetGet(float value, float min, float max,\n\t\t\tfloat &r, float &g, float &b, bool invert, int flag)\n\t\t{\n\t\t\tif(flag != LINEAR_SCL){\n\t\t\t\tswitch(flag){\t\t\n\t\t\t\tcase SQRT_SCL:\n\t\t\t\t\tvalue = sqrt(value);\n\t\t\t\t\tmax = sqrt(max);\n\t\t\t\t\tbreak;\t\t\n\t\t\t\tcase LOG_SCL:\t\t\t\n\t\t\t\t\tvalue = log(value);\n\t\t\t\t\tmax = log(max);\n\t\t\t\t\tbreak;\t\t\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tunsigned char c1=144;\n\t\t\tfloat max4=(max-min)/4;\n\t\t\tvalue-=min;\n\t\t\tif(value==FLT_MAX)\n\t\t\t{r=g=b=255;}\n\t\t\telse if(value<0)\n\t\t\t{r=g=b=0;}\n\t\t\telse if(value<max4)\n\t\t\t{r=0;g=0;b=c1+(float)((255-c1)*value/max4);}\n\t\t\telse if(value<2*max4)\n\t\t\t{r=0;g=(float)(255*(value-max4)/max4);b=255;}\n\t\t\telse if(value<3*max4)\n\t\t\t{r=(unsigned char)(255*(value-2*max4)/max4);g=255;b=255-r;}\n\t\t\telse if(value<max)\n\t\t\t{r=255;g=(float)(255-255*(value-3*max4)/max4);b=0;}\n\t\t\telse {r=255;g=b=0;}\n\t\t\tr/=255.0;  g/=255.0;  b/=255.0;\n\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapColdGet(float value, float min, float max,\n\t\t\tfloat &r, float &g, float &b, bool invert, int flag)\n\t\t{\n\t\t\tfloat max3=(max-min)/3;\n\t\t\tvalue-=min;\n\t\t\tif(value==FLT_MAX)\n\t\t\t{r=g=b=255;}\n\t\t\telse if(value<0)\n\t\t\t{r=g=b=0;}\n\t\t\telse if(value<max3)\n\t\t\t{r=0;g=0;b=(float)(255*value/max3);}\n\t\t\telse if(value<2*max3)\n\t\t\t{r=0;g=(float)(255*(value-max3)/max3);b=255;}\n\t\t\telse if(value<max)\n\t\t\t{r=(float)(255*(value-2*max3)/max3);g=255;b=255;}\n\t\t\telse {r=g=b=255;}\n\t\t\tr/=255.0;  g/=255.0;  b/=255.0;\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapHotPathGet(float value, float min, float max,\n\t\t\tfloat &r, float &g, float &b, bool invert, int flag)\n\t\t{ \n\n\t\t\tfloat rangeVal;\n\t\t\trangeVal = max - min;\n\t\t\tvalue = value-min;\n\n\t\t\tif(flag != LINEAR_SCL){\n\t\t\t\tswitch(flag){\t\t\n\t\t\t\tcase SQRT_SCL:\n\t\t\t\t\tvalue = sqrt(value);\n\t\t\t\t\trangeVal = sqrt(rangeVal);\n\t\t\t\t\tbreak;\t\t\n\t\t\t\tcase LOG_SCL:\t\t\t\n\t\t\t\t\tvalue = log(value);\n\t\t\t\t\trangeVal = log(rangeVal);\n\t\t\t\t\tbreak;\t\t\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\tvalue = value/rangeVal;\t\n\n\t\t\tif(invert){value = 1.0 - value;}\n\n\t\t\tif(value < 0.0f){\n\t\t\t\tr = 1.0f;\n\t\t\t\tg = b = r;\n\t\t\t} else if(value < 0.5f) {\n\t\t\t\tr = 2.0f*(0.5f - value);\n\t\t\t\tg = b = r;\n\t\t\t} else if(value < 1.0f) {\n\t\t\t\tr = value - 0.5f;\n\t\t\t\tg = b = 0.0f;\n\t\t\t} else {\n\t\t\t\tr = 1.0f;\n\t\t\t\tg = b = 0.0f;\n\t\t\t}\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapGoogleMapsGet( float pop, float elev, float &r, float &g, float &b){\n\t\t\tif(pop > 200.0){\n\t\t\t\tr = 235.0/255.0; g = 230.0/255.0; b = 220.0/255.0;\t\t\t\t\n\t\t\t}\n\t\t\telse if(pop > 25.0){\n\n\t\t\t\tr = 242.0/255.0; g = 239.0/255.0; b = 233.0/255.0;\t\t\t\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\tr = 167.0/255.0; g = 204.0/255.0; b = 149.0/255.0;\n\t\t\t}\n\t\t\t//render water\n\t\t\tif(elev == 0.0){\n\t\t\t\tr = 153.0/255.0; g = 179.0/255.0; b = 204.0/255.0;\n\t\t\t}\t\t\t\n\t\t}\n\n\t\tvoid colorMapYiGnBuGet(float value, float min, float max,\n\t\t\tfloat &r, float &g, float &b, bool invert, int flag)\n\t\t{\t\n\n\t\t\tint numIntervals = 9;\t\n\t\t\tfloat delta = (max-min)/((float)numIntervals);\n\t\t\t//value = value-min;\n\t\t\tvalue = max-(value-min);\n\n\t\t\t//float x;\n\t\t\t//x = 255.0*((value-min)/(max-min));\n\n\t\t\tif(value==FLT_MAX)\n\t\t\t{r=g=b=255;}\n\t\t\telse if(value<=0){\n\t\t\t\tr=0.0; g=0.0; b=0.0;\n\t\t\t}\n\t\t\telse if(value<1.0*delta){\n\t\t\t\tr=8.0, g=29.0, b=88.0;\n\t\t\t}\n\t\t\telse if(value<2.0*delta){\n\t\t\t\tr=37.0, g=52.0, b=148.0;\n\t\t\t}\n\t\t\telse if(value<3.0*delta){\n\t\t\t\tr=34.0, g=94.0, b=168.0;\n\t\t\t}\n\t\t\telse if(value<4.0*delta){\n\t\t\t\tr=29.0, g=145.0, b=192.0;\n\t\t\t}\n\t\t\telse if(value<5.0*delta){\n\t\t\t\tr=65.0, g=182.0, b=196.0;\n\t\t\t}\n\t\t\telse if(value<6.0*delta){\n\t\t\t\tr=127.0, g=205.0, b=187.0;\n\t\t\t}\n\t\t\telse if(value<7.0*delta){\n\t\t\t\tr=199.0, g=233.0, b=180.0;\n\t\t\t}\n\t\t\telse if(value<8.0*delta){\n\t\t\t\tr=237.0, g=248.0, b=177.0;\n\t\t\t}\n\t\t\telse if(value<FLT_MAX)\n\t\t\t{\n\t\t\t\tr=255.0, g=255.0, b=217.0;\n\t\t\t}\n\t\t\t//else{r=g=b=x;}\n\n\t\t\tr/=255.0;  g/=255.0;  b/=255.0;\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapTerrainGet(float value, float min, float max,\n\t\t\tfloat &r, float &g, float &b, bool isPark, int flag)\n\t\t{\t\n\t\t\tint numIntervals = 14;\t\n\t\t\tfloat delta = (max-min)/((float)numIntervals);\n\t\t\t//float delta = (MAX_TERRAIN_HEIGHT-MIN_TERRAIN_HEIGHT)/((float)numIntervals);\n\t\t\tvalue-=min;\n\n\t\t\tif(value==FLT_MAX)\n\t\t\t{r=g=b=255;}\n\t\t\telse if(value<=0.0f){\n\t\t\t\tr=60.0; g=80.0; b=100.0;\n\t\t\t}\n\t\t\telse if(value<1.0*delta){\n\t\t\t\tr=139.0, g=146.0, b=112.0;\n\t\t\t}\n\t\t\telse if(value<2.0*delta){\n\t\t\t\tr=158.0, g=159.0, b=117.0;\n\t\t\t}\n\t\t\telse if(value<3.0*delta){\n\t\t\t\tr=177.0, g=173.0, b=123.0;\n\t\t\t}\n\t\t\telse if(value<4.0*delta){\n\t\t\t\tr=196.0, g=186.0, b=129.0;\n\t\t\t}\n\t\t\telse if(value<5.0*delta){\n\t\t\t\tr=215.0, g=200, b=135.0;\n\t\t\t}\n\t\t\telse if(value<6.0*delta){\n\t\t\t\tr=208.0, g=190.0, b=128.0;\n\t\t\t}\n\t\t\telse if(value<7.0*delta){\n\t\t\t\tr=202.0, g=180.0, b=121.0;\n\t\t\t}\n\t\t\telse if(value<8.0*delta){\n\t\t\t\tr=195.0, g=170.0, b=114.0;\n\t\t\t}\n\t\t\telse if(value<9.0*delta){\n\t\t\t\tr=189.0, g=160.0, b=107.0;\n\t\t\t}\n\t\t\telse if(value<10.0*delta){\n\t\t\t\tr=183.0, g=150.0, b=101.0;\n\t\t\t}\n\t\t\telse if(value<11.0*delta){\n\t\t\t\tr=179.0, g=154.0, b=113.0;\n\t\t\t}\n\t\t\telse if(value<12.0*delta){\n\t\t\t\tr=175.0, g=158.0, b=126.0;\n\t\t\t}\n\t\t\telse if(value<13.0*delta){\n\t\t\t\tr=171.0, g=162.0, b=138.0;\n\t\t\t}\n\t\t\telse if(value<FLT_MAX)\n\t\t\t{\n\t\t\t\tr=167.0, g=167.0, b=151.0;\n\t\t\t}\n\t\t\tr/=255.0;  g/=255.0;  b/=255.0;\t\n\t\t}\n\n\t\t/*****************************************************************************\n\t\t*****************************************************************************/\n\t\tvoid colorMapGrayscaleGet(float value, float min, float max,\n\t\t\tfloat &r, float &g, float &b, int flag)\n\t\t{\t\n\t\t\tr = 1.0f - (value-min)/(max-min);\n\t\t\tg = r;\n\t\t\tb = r;\n\t\t}\n\n\n\t\tbool readSegmentsFromFile(QString filename, std::vector<QVector3D> &pts, std::vector< std::vector<int> > &idxsSets)\n\t\t{\n\t\t\t//read initial edges from file\n\t\t\tQFile initialEdgesFile(filename);\n\t\t\tif (!initialEdgesFile.open(QIODevice::ReadOnly | QIODevice::Text))\t\t\t{\n\t\t\t\tstd::cout << \"ERROR: Cannot open the file \" << filename.toLocal8Bit().data() << \" for reading\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tidxsSets.clear();\n\t\t\tpts.clear();\n\n\t\t\tQTextStream stream( &initialEdgesFile );\n\n\t\t\tQString line;\n\n\t\t\tint numVertices;\n\t\t\tint numEdges;\n\t\t\tint numObjects;\n\n\t\t\t//read number of objects\n\t\t\tline = stream.readLine();\n\t\t\tif(!line.isNull()){\n\t\t\t\tnumObjects = line.toInt();\n\t\t\t}\n\n\t\t\tfor(int objIdx = 0; objIdx < numObjects; ++objIdx){\n\n\t\t\t\tstd::vector<int> tmpIdxVector;\n\n\t\t\t\t//read number of vertices\n\t\t\t\tline = stream.readLine();\t\n\t\t\t\tif(!line.isNull()){\n\t\t\t\t\tnumVertices = line.toInt();\n\t\t\t\t}\n\n\t\t\t\t//read number of edges\n\t\t\t\tline = stream.readLine();\t\n\t\t\t\tif(!line.isNull()){\n\t\t\t\t\tnumEdges = line.toInt();\n\t\t\t\t}\t\t\t\n\n\t\t\t\t//read in the vertices\t\n\t\t\t\tfor(int i=0; i<numVertices; ++i){\t\t\t\t\n\t\t\t\t\tline = stream.readLine();\t\n\t\t\t\t\tif(!line.isNull()){\n\t\t\t\t\t\tQStringList attList = line.split(\" \");\n\t\t\t\t\t\tif(attList.size() != 4){\n\t\t\t\t\t\t\tstd::cout << \"ERROR: Point entry must contain point index and three coordinates\\n\";\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint pointIdx = attList.at(0).toInt();\n\n\t\t\t\t\t\tQVector3D tmpPt;\n\t\t\t\t\t\ttmpPt = QVector3D(attList.at(1).toFloat(),\n\t\t\t\t\t\t\tattList.at(2).toFloat(),\n\t\t\t\t\t\t\tattList.at(3).toFloat());\t\n\n\t\t\t\t\t\tpts.push_back(tmpPt);\n\t\t\t\t\t}\n\t\t\t\t}\t\n\n\t\t\t\t//read in the edges\n\t\t\t\tint vtxAIdx, vtxBIdx;\t\t\t\n\t\t\t\tfor(int i=0; i<numEdges; ++i){\t\t\t\t\n\t\t\t\t\tline = stream.readLine();\t\n\t\t\t\t\tif(!line.isNull()){\n\t\t\t\t\t\tQStringList attList = line.split(\" \");\n\t\t\t\t\t\tif(attList.size() != 2){\n\t\t\t\t\t\t\tstd::cout << \"ERROR: Edges must be defined by two vertex indexes\\n\";\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\t\t\t\n\t\t\t\t\t\tvtxAIdx = attList.at(0).toInt();\n\t\t\t\t\t\tvtxBIdx = attList.at(1).toInt();\t\t\t\t\t\n\n\t\t\t\t\t\ttmpIdxVector.push_back(vtxAIdx);\n\t\t\t\t\t\ttmpIdxVector.push_back(vtxBIdx);\n\t\t\t\t\t}\n\t\t\t\t}\t\n\n\t\t\t\tif(tmpIdxVector.size()%2 != 0){\n\t\t\t\t\tstd::cout << \"ERROR reading file \" << filename.toLocal8Bit().data() << \". Number of segment indexes must be even.\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tidxsSets.push_back(tmpIdxVector);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool loadPolygonsFromFile(QString filename, std::vector<Polygon3D> &polygons)\n\t\t{\n\t\t\tstd::vector<QVector3D> pts;\n\t\t\tstd::vector< std::vector<int> > idxs;\n\n\t\t\tint numPgons;\n\n\t\t\tif(!readSegmentsFromFile(filename, pts, idxs)){\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tnumPgons = idxs.size();\n\t\t\t\tif( (pts.size() < 1) || (numPgons < 1) ){\n\t\t\t\t\tstd::cout << \"ERROR reading file \" << filename.toLocal8Bit().data() << \". Not enough points or polygons.\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\t\t\t\n\n\t\t\tfor(int i=0; i<numPgons; ++i){\n\t\t\t\tint numPts = (idxs.at(i).size())/2;\t\t\t\t\n\t\t\t\tif(numPts < 3){\n\t\t\t\t\tstd::cout << \"WARNING reading file \" << filename.toLocal8Bit().data() << \". Polygon contains fewer than 2 points and has been ignored.\\n\";\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPolygon3D tmpPgon;\n\t\t\t\tQVector3D tmpPt;\n\t\t\t\tfor(int j=0; j<numPts; ++j){\n\t\t\t\t\ttmpPt = pts.at( idxs.at(i).at(2*j) );\n\t\t\t\t\ttmpPgon.contour.push_back(tmpPt);\n\t\t\t\t}\n\n\t\t\t\tpolygons.push_back(tmpPgon);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\t//**\n\t\t// Returns only the first polygon in the file\n\t\t//**\n\t\tbool loadPolygonFromFile(QString filename, Polygon3D &polygon)\n\t\t{\n\t\t\tstd::vector<Polygon3D> tmpPolygons;\n\t\t\tif(!loadPolygonsFromFile(filename, tmpPolygons)){\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif(tmpPolygons.size() < 1){\n\t\t\t\tstd::cout << \"ERROR: file \" << filename.toLocal8Bit().data() << \" does not contain any polygons.\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpolygon = tmpPolygons.at(0);\n\t\t\treturn true;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "673e37e89b7bee765822ceae2bb0fc6e0db6a438", "size": 41314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "traffic-simulator-extended/LivingCity/misctools/misctools.cpp", "max_stars_repo_name": "ual/DOE-repo-deliverable", "max_stars_repo_head_hexsha": "4bafdd9a702a9a6466dd32ae62f440644d735d3c", "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": "traffic-simulator-extended/LivingCity/misctools/misctools.cpp", "max_issues_repo_name": "ual/DOE-repo-deliverable", "max_issues_repo_head_hexsha": "4bafdd9a702a9a6466dd32ae62f440644d735d3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "traffic-simulator-extended/LivingCity/misctools/misctools.cpp", "max_forks_repo_name": "ual/DOE-repo-deliverable", "max_forks_repo_head_hexsha": "4bafdd9a702a9a6466dd32ae62f440644d735d3c", "max_forks_repo_licenses": ["BSD-3-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.6768178993, "max_line_length": 168, "alphanum_fraction": 0.5548482355, "num_tokens": 14175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.03258974676266964, "lm_q1q2_score": 0.01477168884400109}}
{"text": "#include \"Network.hpp\"\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <boost/numeric/ublas/matrix.hpp>\n\nvoid Network::loadNetwork(const char *filename) {\n\t// Unused variables\n\tunsigned short A;\n\tfern_real massExcess;\n\tfern_real pf;\n\tfern_real Y;\n\n\tFILE *file = fopen(filename, \"r\");\n\n\t// Exit if the file doesn't exist or can't be read\n\n\tif (!file) {\n\t\tfprintf(stderr, \"Could not read file '%s'\\n\", filename);\n\t\texit(1);\n\t}\n\n\t// Read 4 lines at a time\n\tisotopeLabel = (char **) malloc(sizeof(char *) * species);\n\tunsigned int * zData = Z.data();\n\tunsigned int * nData = N.data();\n\tfor (int n = 0; n < species; n++) {\n\t\tisotopeLabel[n] = (char *) malloc(sizeof(char) * 10);\n\t\tint status;\n\n\t\t// Line #1\n\n#ifdef FERN_SINGLE\n\t\tstatus = fscanf(file, \"%s %hu %i %hhu %f %f\\n\",\n\t\t\t\tisotopeLabel[n], &A, &zData[n], &nData[n], &Y, &massExcess);\n#else\n\t\tstatus = fscanf(file, \"%s %hu %i %hhu %lf %lf\\n\", isotopeLabel[n], &A,\n\t\t\t\t&zData[n], &nData[n], &Y, &massExcess);\n#endif\n\n\t\tif (status == EOF)\n\t\t\tbreak;\n\n\t\t// Line #2...4\n\n\t\tfor (int i = 0; i < 8 * 3; i++) {\n#ifdef FERN_SINGLE\n\t\t\tstatus = fscanf(file, \"%f\", &pf);\n#else\n\t\t\tstatus = fscanf(file, \"%lf\", &pf);\n#endif\n\t\t}\n\t}\n\n\treturn;\n}\n\nvoid Network::loadReactions(const char *filename) {\n\tstatic const bool displayInput = false;\n\tstatic const bool displayPEInput = false;\n\n\t// Unused variables\n\tint reaclibClass;\n\tint isEC;\n\n\t// Allocate the host-only memory to be used by parseFlux()\n\tint numProducts[reactions];\n\tint RGclass[reactions];\n\n\t// Each element of these dynamic arrays are pointers to static arrays of size 4.\n\tvec_4i reactantZ[reactions]; // [reactions]\n\tvec_4i reactantN[reactions]; // [reactions]\n\tvec_4i productZ[reactions]; // [reactions]\n\tvec_4i productN[reactions]; // [reactions]\n\n\tFILE *file = fopen(filename, \"r\");\n\n\t// Exit if the file doesn't exist or can't be read\n\n\tif (!file) {\n\t\tfprintf(stderr, \"File Input Error: No readable file named %s\\n\",\n\t\t\t\tfilename);\n\t\texit(1);\n\t}\n\n\t// Read eight lines at a time\n\tnumRG = 0;\n\treactionLabel = (char **) malloc(sizeof(char *) * reactions);\n\tusing namespace boost::numeric::ublas;\n\tmatrix<int> reacVector (reactions,species);\n\tfor (int n = 0; n < reactions; n++) {\n\t\treactionLabel[n] = (char *) malloc(sizeof(char) * 50);\n\t\tint status;\n\n\t\t// Line #1\n\n#ifdef FERN_SINGLE\n\t\tstatus = fscanf(file, \"%s %d %d %d %hhu %d %d %d %f %f\",\n\t\t\t\treactionLabel[n], &RGclass[n], &RGmemberIndex[n], &reaclibClass,\n\t\t\t\t&numReactingSpecies[n], &numProducts[n], &isEC, &isReverseR[n],\n\t\t\t\t&statFac[n], &Q[n]);\n#else\n\t\tstatus = fscanf(file, \"%s %d %d %d %hhu %d %d %d %lf %lf\",\n\t\t\t\treactionLabel[n], &RGclass[n], &RGmemberIndex[n], &reaclibClass,\n\t\t\t\t&numReactingSpecies[n], &numProducts[n], &isEC, &isReverseR[n],\n\t\t\t\t&statFac[n], &Q[n]);\n#endif\n\n\t\tif (status == EOF)\n\t\t\tbreak;\n\n\t\tif (displayInput) {\n\t\t\tprintf(\"Reaction Index = %d\\n\", n);\n\t\t\tprintf(\"isReverseR = %d reaclibIndex = %d\\n\", isReverseR[n],\n\t\t\t\t\treaclibClass);\n\t\t\tprintf(\"%s %d %d %d %d %d %d %d %f %f\\n\", reactionLabel[n],\n\t\t\t\t\tRGclass[n], RGmemberIndex[n], reaclibClass,\n\t\t\t\t\tnumReactingSpecies[n], numProducts[n], isEC, isReverseR[n],\n\t\t\t\t\tstatFac[n], Q[n]);\n\t\t}\n\t\t//Reset isReverseR to zero so I can determine if Reverse by reaction vector\n\t\tisReverseR[n] = 0;\n\t\t// Line #2\n\n\t\tif (displayInput)\n\t\t\tprintf(\"P: { \");\n\n\t\tfor (int i = 0; i < 7; i++) {\n#ifdef FERN_SINGLE\n\t\t\tstatus = fscanf(file, \"%f\", &P[i][n]);\n#else\n\t\t\tstatus = fscanf(file, \"%lf\", &P[i][n]);\n#endif\n\n\t\t\tif (displayInput)\n\t\t\t\tprintf(\"%f, \", P[i][n]);\n\t\t}\n\n\t\tif (displayInput)\n\t\t\tprintf(\"}\\n\");\n\n\t\t// Line #3\n\n\t\tfor (int mm = 0; mm < numReactingSpecies[n]; mm++) {\n\t\t\tstatus = fscanf(file, \"%d\", &reactantZ[n][mm]);\n\n\t\t\tif (displayInput)\n\t\t\t\tprintf(\"\\tReactant[%d]: Z=%d\\n\", mm, reactantZ[n][mm]);\n\t\t}\n\n\t\t// Line #4\n\n\t\tfor (int mm = 0; mm < numReactingSpecies[n]; mm++) {\n\t\t\tstatus = fscanf(file, \"%d\", &reactantN[n][mm]);\n\n\t\t\tif (displayInput)\n\t\t\t\tprintf(\"\\tReactant[%d]: N=%d\\n\", mm, reactantN[n][mm]);\n\t\t}\n\n\t\t// Line #5\n\n\t\tfor (int mm = 0; mm < numProducts[n]; mm++) {\n\t\t\tstatus = fscanf(file, \"%d\", &productZ[n][mm]);\n\n\t\t\tif (displayInput)\n\t\t\t\tprintf(\"\\tProduct[%d]: Z=%d\\n\", mm, productZ[n][mm]);\n\t\t}\n\n\t\t// Line #6\n\n\t\tfor (int mm = 0; mm < numProducts[n]; mm++) {\n\t\t\tstatus = fscanf(file, \"%d\", &productN[n][mm]);\n\n\t\t\tif (displayInput)\n\t\t\t\tprintf(\"\\tProduct[%d]: N=%d\\n\", mm, productN[n][mm]);\n\t\t}\n\n\t\t// Line #7\n\n\t\tfor (int mm = 0; mm < numReactingSpecies[n]; mm++) {\n\t\t\tstatus = fscanf(file, \"%d\", &reactant[mm][n]);\n\t\t\t//\"subtract\" reactants from reacVector (PE)\n\t\t\tfor (int i = 0; i < species; i++) {\n\t\t\t\tif (i == reactant[mm][n]) {\n\t\t\t\t\treacVector(n,i)--;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (displayInput)\n\t\t\t\tprintf(\"\\treactant[%d]: N=%d\\n\", mm, reactant[mm][n]);\n\t\t}\n\n\t\t// Line #8\n\n\t\tfor (int mm = 0; mm < numProducts[n]; mm++) {\n\t\t\tstatus = fscanf(file, \"%d\", &product[mm][n]);\n\t\t\t//\"add\" products to reacVector (PE)\n\t\t\tfor (int i = 0; i < species; i++) {\n\t\t\t\tif (i == product[mm][n]) {\n\t\t\t\t\treacVector(n,i)++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (displayInput)\n\t\t\t\tprintf(\"\\tProductIndex[%d]: N=%d\\n\", mm, product[mm][n]);\n\t\t}\n\t\tPEnumProducts[n] = numProducts[n];\n\t}\n\t//PartialEquilibrium: define Reaction Groups based on ReacVector\n\t//reworked so parsing to reaction groups does not depend on the reaction input\n\t//file having RG members in order\n\t//embedded loop over all reactions to compare to all other reactions\n\t//and group them if the absolute value of their reaction vectors are equivalent.\n\tint isRGmember = 0;\n\tint RGmemberID = 0;\n\t//each reaction's home RGParent\n\tint reacPlaced[reactions];\n\t// initialize reacPlaced for logic below. This indicates whether a reaction has been placed into a reaction group yet... If not, it will be the parent of a new RG.\n\tfor (int i = 0; i < reactions; i++) {\n\t\treacPlaced[i] = 0;\n\t}\n\t//member ID within this reaction's RG\n\tint RGmemID[reactions];\n\tint RGnumMembers[numRG];\n\tfor (int j = 0; j < reactions; j++) {\n\n\t\t//if this reaction doesn't yet have an RG home of its own...\n\t\tif (reacPlaced[j] == 0) {\n\t\t\tRGmemberID = 0;\n\t\t\tRGmemID[j] = RGmemberID;\n\t\t\tReacParent[j] = j;\n\t\t\tRGclassByRG[numRG] = RGclass[j];\n\t\t\tRGParent[numRG] = j;\n\t\t\tReacRG[j] = numRG;\n\t\t\tif (displayPEInput) {\n\t\t\t\tprintf(\"\\nRG #%d: %s\\n\", numRG, reactionLabel[ReacParent[j]]);\n\t\t\t\tprintf(\"Reaction %s ID[%d]\\nReaction Vector: \",\n\t\t\t\t\t\treactionLabel[j], j);\n\t\t\t\tfor (int q = 0; q < species; q++) {\n\t\t\t\t\tprintf(\"%d \", reacVector(j,q));\n\t\t\t\t}\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n\t\t\tfor (int n = 0; n < reactions; n++) {\n\t\t\t\tfor (int i = 0; i < species; i++) {\n\t\t\t\t\t//if reaction j has a different species than reaction n, check n+1\n\t\t\t\t\t//also if n = j, skip it\n\t\t\t\t\tif (abs(reacVector(j,i)) != abs(reacVector(n,i))\n\t\t\t\t\t\t\t|| j == n) {\n\t\t\t\t\t\tisRGmember = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisRGmember = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//if reac n was determined to have same species as reac j,\n\t\t\t\tif (isRGmember == 1) {\n\t\t\t\t\tfor (int b = 0; b < species; b++) {\n\t\t\t\t\t\tif (reacVector(j,b) != (reacVector(n,b))\n\t\t\t\t\t\t\t\t&& abs(reacVector(j,b))\n\t\t\t\t\t\t\t\t\t\t== abs(reacVector(n,b))) {\n\t\t\t\t\t\t\tisReverseR[n] = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//give reac n the current reaction group ID.\n\t\t\t\t\treacPlaced[n] = 1;\n\t\t\t\t\tRGmemberID++;\n\t\t\t\t\tRGmemID[n] = RGmemberID;\n\t\t\t\t\tReacParent[n] = j;\n\t\t\t\t\tReacRG[n] = numRG;\n\t\t\t\t\tif (displayPEInput) {\n\t\t\t\t\t\tprintf(\"Reac: %d, Class: %d\\n\", j, RGclassByRG[j]);\n\t\t\t\t\t\tprintf(\n\t\t\t\t\t\t\t\t\"RGParent: %d, ReacParent: %d,  RGmemID: %d, isReverseR: %d\\n\",\n\t\t\t\t\t\t\t\tRGParent[numRG], ReacParent[n], RGmemID[n],\n\t\t\t\t\t\t\t\tisReverseR[n]);\n\t\t\t\t\t\tprintf(\"Reaction %s ID[%d]\\nReaction Vector: \",\n\t\t\t\t\t\t\t\treactionLabel[n], n);\n\t\t\t\t\t\tfor (int q = 0; q < species; q++) {\n\t\t\t\t\t\t\tprintf(\"%d \", reacVector(n,q));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//indicates number of members in each reaction group\n\t\t\tRGnumMembers[numRG] = RGmemberID + 1;\n\t\t\tif (displayPEInput) {\n\t\t\t\tprintf(\"Number Members: %d\\n\", RGnumMembers[numRG]);\n\t\t\t}\n\t\t\tnumRG++;\n\t\t}\n\t}\n\tif (displayPEInput) {\n\t\tprintf(\"numRG: %d\\n\", numRG);\n\t\tfor (int i = 0; i < numRG; i++) {\n\t\t\tprintf(\"ReacParent for each RG[%d]: %d\\n\", i, RGParent[i]);\n\t\t}\n\t}\n\tfclose(file);\n\n\t// We're not done yet. Finally parse the flux.\n\tparseFlux(numProducts, reactantZ, reactantN, productZ, productN);\n\n\treturn;\n}\n\nvoid Network::parseFlux(int *numProducts, vec_4i *reactantZ, vec_4i *reactantN,\n\t\tvec_4i *productZ, vec_4i *productN) {\n\tconst static bool showParsing = false;\n\n\t// These tempInt blocks will become MapFPlus and MapFMinus eventually.\n\tsize_t tempIntSize = species * reactions / 2;\n\tunsigned short tempInt1 [tempIntSize];\n\tunsigned short tempInt2 [tempIntSize];\n\n\t// Access elements by reacMask[speciesIndex + species * reactionIndex].\n\tint reacMask [species * reactions]; // [species][reactions]\n\tint numFluxPlus [species];\n\tint numFluxMinus[species];\n\n\t// Start of Guidry's original parseF() code\n\n\tif (showParsing)\n\t\tprintf(\n\t\t\t\t\"Use parseF() to find F+ and F- flux components for each species:\\n\");\n\n\tint incrementPlus = 0;\n\tint incrementMinus = 0;\n\n\ttotalFplus = 0;\n\ttotalFminus = 0;\n\n\t// Loop over all isotopes in the network\n\tfor (int i = 0; i < species; i++) {\n\t\tint total = 0;\n\t\tint numFplus = 0;\n\t\tint numFminus = 0;\n\n\t\t// Loop over all possible reactions for this isotope, finding those that\n\t\t// change its population up (contributing to F+) or down (contributing\n\t\t// to F-).\n\n\t\tfor (int j = 0; j < reactions; j++) {\n\t\t\tint totalL = 0;\n\t\t\tint totalR = 0;\n\n\t\t\t// Loop over reactants for this reaction\n\t\t\tfor (int k = 0; k < numReactingSpecies[j]; k++) {\n\t\t\t\tif (Z[i] == reactantZ[j][k] && N[i] == reactantN[j][k])\n\t\t\t\t\ttotalL++;\n\t\t\t}\n\n\t\t\t// Loop over products for this reaction\n\t\t\tfor (int k = 0; k < numProducts[j]; k++) {\n\t\t\t\tif (Z[i] == productZ[j][k] && N[i] == productN[j][k])\n\t\t\t\t\ttotalR++;\n\t\t\t}\n\n\t\t\ttotal = totalL - totalR;\n\n\t\t\tif (total > 0)       // Contributes to F- for this isotope\n\t\t\t\t\t{\n\t\t\t\tnumFminus++;\n\t\t\t\treacMask[i + species * j] = -total;\n\t\t\t\ttempInt2[incrementMinus + numFminus - 1] = j;\n\t\t\t\tif (showParsing)\n\t\t\t\t\tprintf(\n\t\t\t\t\t\t\t\"%s reacIndex=%d %s nReac=%d nProd=%d totL=%d totR=%d tot=%d F-\\n\",\n\t\t\t\t\t\t\tisotopeLabel[i], j, reactionLabel[j],\n\t\t\t\t\t\t\tnumReactingSpecies[j], numProducts[j], totalL,\n\t\t\t\t\t\t\ttotalR, total);\n\t\t\t} else if (total < 0)  // Contributes to F+ for this isotope\n\t\t\t\t\t{\n\t\t\t\tnumFplus++;\n\t\t\t\treacMask[i + species * j] = -total;\n\t\t\t\ttempInt1[incrementPlus + numFplus - 1] = j;\n\t\t\t\tif (showParsing)\n\t\t\t\t\tprintf(\n\t\t\t\t\t\t\t\"%s reacIndex=%d %s nReac=%d nProd=%d totL=%d totR=%d tot=%d F+\\n\",\n\t\t\t\t\t\t\tisotopeLabel[i], j, reactionLabel[j],\n\t\t\t\t\t\t\tnumReactingSpecies[j], numProducts[j], totalL,\n\t\t\t\t\t\t\ttotalR, total);\n\t\t\t} else               // Does not contribute to flux for this isotope\n\t\t\t{\n\t\t\t\treacMask[i + species * j] = 0;\n\t\t\t}\n\t\t}\n\n\t\t// Keep track of the total number of F+ and F- terms in the network for all isotopes\n\t\ttotalFplus += numFplus;\n\t\ttotalFminus += numFminus;\n\n\t\tnumFluxPlus[i] = numFplus;\n\t\tnumFluxMinus[i] = numFminus;\n\n\t\tincrementPlus += numFplus;\n\t\tincrementMinus += numFminus;\n\n\t\t// if (showParsing == 1)\n\t\t// \tprintf(\"%d %s numF+ = %d numF- = %d\\n\", i, isoLabel[i], numFplus, numFminus);\n\t}\n\n\t// Display some cases\n\n\tprintf(\"\\n\");\n\tprintf(\n\t\t\t\"PART OF FLUX-ISOTOPE COMPONENT ARRAY (-n --> F-; +n --> F+ for given isotope):\\n\");\n\n\tprintf(\"\\n\");\n\tprintf(\n\t\t\t\"FLUX SPARSENESS: Non-zero F+ = %d; Non-zero F- = %d, out of %d x %d = %d possibilities.\\n\",\n\t\t\ttotalFplus, totalFminus, reactions, species, reactions * species);\n\n\t// Create 1D arrays that will be used to map finite F+ and F- to the Flux array.\n\n\tint FplusIsotopeCut[species];\n\tint FminusIsotopeCut[species];\n\n\tint FplusIsotopeIndex[totalFplus];\n\tint FminusIsotopeIndex[totalFminus];\n\n\tFplusIsotopeCut[0] = numFluxPlus[0];\n\tFminusIsotopeCut[0] = numFluxMinus[0];\n\tfor (int i = 1; i < species; i++) {\n\t\tFplusIsotopeCut[i] = numFluxPlus[i] + FplusIsotopeCut[i - 1];\n\t\tFminusIsotopeCut[i] = numFluxMinus[i] + FminusIsotopeCut[i - 1];\n\t}\n\n\tint currentIso = 0;\n\tfor (int i = 0; i < totalFplus; i++) {\n\t\tFplusIsotopeIndex[i] = currentIso;\n\t\tif (i == (FplusIsotopeCut[currentIso] - 1))\n\t\t\tcurrentIso++;\n\t}\n\n\tcurrentIso = 0;\n\tfor (int i = 0; i < totalFminus; i++) {\n\t\tFminusIsotopeIndex[i] = currentIso;\n\t\tif (i == (FminusIsotopeCut[currentIso] - 1))\n\t\t\tcurrentIso++;\n\t}\n\n\tMapFplus.resize(totalFplus);\n\tfor (int i = 0; i < totalFplus; i++) {\n\t\tMapFplus[i] = tempInt1[i];\n\t}\n\tMapFminus.resize(totalFminus);\n\tfor (int i = 0; i < totalFminus; i++) {\n\t\tMapFminus[i] = tempInt2[i];\n\t}\n\n\t// Populate the FplusMin and FplusMax arrays\n\tunsigned short FplusMin [species];\n\tunsigned short FminusMin [species];\n\n\tFplusMin[0] = 0;\n\tFplusMax[0] = numFluxPlus[0] - 1;\n\tfor (int i = 1; i < species; i++) {\n\t\tFplusMin[i] = FplusMax[i - 1] + 1;\n\t\tFplusMax[i] = FplusMin[i] + numFluxPlus[i] - 1;\n\t}\n\t// Populate the FminusMin and FminusMax arrays\n\tFminusMin[0] = 0;\n\tFminusMax[0] = numFluxMinus[0] - 1;\n\tfor (int i = 1; i < species; i++) {\n\t\tFminusMin[i] = FminusMax[i - 1] + 1;\n\t\tFminusMax[i] = FminusMin[i] + numFluxMinus[i] - 1;\n\t}\n\n\t// Allocate the flux vectors\n\tFplusFac = std::vector<fern_real>(species*reactions);\n\tFminusFac = std::vector<fern_real>(species*reactions);\n\n\t// Populate the FplusFac and FminusFac arrays that hold the factors counting the\n\t// number of occurences of the species in the reaction.  Note that this can only\n\t// be done after parseF() has been run to give reacMask[i][j].\n\tint tempCountPlus = 0;\n\tint tempCountMinus = 0;\n\tfor (int i = 0; i < species; i++) {\n\t\tfor (int j = 0; j < reactions; j++) {\n\t\t\tif (reacMask[i + species * j] > 0) {\n\t\t\t\tFplusFac[tempCountPlus] = (fern_real) reacMask[i + species * j];\n\t\t\t\ttempCountPlus++;\n\t\t\t} else if (reacMask[i + species * j] < 0) {\n\t\t\t\tFminusFac[tempCountMinus] = -(fern_real) reacMask[i\n\t\t\t\t\t\t+ species * j];\n\t\t\t\ttempCountMinus++;\n\t\t\t}\n\t\t}\n\t} // If you run this through the debugger, it is a lot of work to calculate 0!\n\n\treturn;\n}\n\nvoid Network::allocate() {\n\t// Allocate the network data\n\n\tZ = std::vector<unsigned int>(species);\n\tN = std::vector<unsigned int>(species);\n\n\tFplusMax = new unsigned short[species];\n\tFminusMax = new unsigned short[species];\n\n\t// Allocate the reaction data\n\n\tfor (int i = 0; i < 7; i++) {\n\t\tP[i] = new fern_real[reactions];\n\t}\n\n\tnumReactingSpecies = new unsigned char[reactions];\n\tstatFac = new fern_real[reactions];\n\tQ = new fern_real[reactions];\n\tRGclassByRG = new int[numRG];\n\tRGmemberIndex = new int[reactions];\n\tisReverseR = new int[reactions];\n\tPEnumProducts = new int[reactions];\n\tReacParent = new int[reactions];\n\n\tfor (int i = 0; i < 3; i++) {\n\t\tproduct[i] = new int[reactions];\n\t}\n\n\tfor (int i = 0; i < 3; i++) {\n\t\treactant[i] = new int[reactions];\n\t}\n\n\tpEquilbyRG = new int[numRG];\n\tpEquilbyReac = new int[reactions];\n\tReacRG = new int[reactions];\t//holds each reaction's RGid\n\tRGParent = new int[numRG];\n}\n\nvoid Network::setSizes(const Network &source) {\n\tspecies = source.species;\n\treactions = source.reactions;\n\ttotalFplus = source.totalFplus;\n\ttotalFminus = source.totalFminus;\n\tnumRG = source.numRG;\n}\n\nvoid Network::print() {\n\t// Network data\n\n\tprintf(\"species: %d\\n\", species);\n\n\tprintf(\"Z: { \");\n\tfor (int i = 0; i < species; i++)\n\t\tprintf(\"%4d \", Z[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"N: { \");\n\tfor (int i = 0; i < species; i++)\n\t\tprintf(\"%4d \", N[i]);\n\tprintf(\"}\\n\");\n\n\t// Reaction data\n\n\tprintf(\"\\n\");\n\n\tprintf(\"reactions: %d\\n\", reactions);\n\n\tfor (int n = 0; n < 7; n++) {\n\t\tprintf(\"P[%d]: { \", n);\n\t\tfor (int i = 0; i < reactions; i++)\n\t\t\tprintf(\"%e \", P[n][i]);\n\t\t;\n\t\tprintf(\"\\n\");\n\t}\n\n\tprintf(\"numReactingSpecies: { \");\n\tfor (int i = 0; i < reactions; i++)\n\t\tprintf(\"%4d \", numReactingSpecies[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"statFac: { \");\n\tfor (int i = 0; i < reactions; i++)\n\t\tprintf(\"%e \", statFac[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"Q: { \");\n\tfor (int i = 0; i < reactions; i++)\n\t\tprintf(\"%e \", Q[i]);\n\tprintf(\"}\\n\");\n\n\tfor (int n = 0; n < 3; n++) {\n\t\tprintf(\"reactant[%d]: { \", n);\n\t\tfor (int i = 0; i < reactions; i++)\n\t\t\tprintf(\"%4d \", reactant[n][i]);\n\t\tprintf(\"}\\n\");\n\t}\n\n\tprintf(\"totalFplus: %d\\n\", totalFplus);\n\tprintf(\"totalFminus: %d\\n\", totalFminus);\n\n\tprintf(\"FplusFac: { \");\n\tfor (int i = 0; i < totalFplus; i++)\n\t\tprintf(\"%e \", FplusFac[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"FminusFac: { \");\n\tfor (int i = 0; i < totalFminus; i++)\n\t\tprintf(\"%e \", FminusFac[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"MapFplus: { \");\n\tfor (int i = 0; i < totalFplus; i++)\n\t\tprintf(\"%4u \", MapFplus[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"MapFminus: { \");\n\tfor (int i = 0; i < totalFminus; i++)\n\t\tprintf(\"%4u \", MapFminus[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"FplusMax: { \");\n\tfor (int i = 0; i < species; i++)\n\t\tprintf(\"%4u \", FplusMax[i]);\n\tprintf(\"}\\n\");\n\n\tprintf(\"FminusMax: { \");\n\tfor (int i = 0; i < species; i++)\n\t\tprintf(\"%4u \", FminusMax[i]);\n\tprintf(\"}\\n\");\n}\n", "meta": {"hexsha": "19ecab7928fba0d00c459be98bead87b67e0ffe4", "size": 16618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Network.cpp", "max_stars_repo_name": "jayjaybillings/fern", "max_stars_repo_head_hexsha": "1dfb067ae346e8b997265ffd27eb7e929cecb513", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T04:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T04:04:31.000Z", "max_issues_repo_path": "src/Network.cpp", "max_issues_repo_name": "jayjaybillings/fern", "max_issues_repo_head_hexsha": "1dfb067ae346e8b997265ffd27eb7e929cecb513", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-11-03T20:30:18.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-01T15:58:07.000Z", "max_forks_repo_path": "src/Network.cpp", "max_forks_repo_name": "jayjaybillings/fern", "max_forks_repo_head_hexsha": "1dfb067ae346e8b997265ffd27eb7e929cecb513", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-17T20:23:11.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-17T20:23:11.000Z", "avg_line_length": 26.5888, "max_line_length": 164, "alphanum_fraction": 0.6075339993, "num_tokens": 5544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.0346188370961675, "lm_q1q2_score": 0.014758757762980261}}
{"text": "/*\nCopyright (c) by respective owners including Yahoo!, Microsoft, and\nindividual contributors. All rights reserved.  Released under a BSD (revised)\nlicense as described in the file LICENSE.\n */\n#include <fstream>\n#include <vector>\n#include <float.h>\n#ifdef _WIN32\n#include <winsock2.h>\n#else\n#include <netdb.h>\n#endif\n#include <string.h>\n#include <stdio.h>\n#include <assert.h>\n#include \"constant.h\"\n#include \"gd.h\"\n#include \"simple_label.h\"\n#include \"rand48.h\"\n#include \"reductions.h\"\n\nusing namespace LEARNER;\nusing namespace std;\n\nnamespace LDA {\n\nclass index_feature {\npublic:\n  uint32_t document;\n  feature f;\n  bool operator<(const index_feature b) const { return f.weight_index < b.f.weight_index; }\n};\n\n  struct lda {\n    uint32_t topics;\n    float lda_alpha;\n    float lda_rho;\n    float lda_D;\n    float lda_epsilon;\n    size_t minibatch;\n\n    v_array<float> Elogtheta;\n    v_array<float> decay_levels;\n    v_array<float> total_new;\n    v_array<example* > examples;\n    v_array<float> total_lambda;\n    v_array<int> doc_lengths;\n    v_array<float> digammas;\n    v_array<float> v;\n    vector<index_feature> sorted_features;\n\n    bool total_lambda_init;\n    \n    double example_t;\n    vw* all;\n  };\n  \n#ifdef _WIN32\ninline float fmax(float f1, float f2) { return (f1 < f2 ? f2 : f1); }\ninline float fmin(float f1, float f2) { return (f1 > f2 ? f2 : f1); }\n#endif\n\n#define MINEIRO_SPECIAL\n#ifdef MINEIRO_SPECIAL\n\nnamespace {\n\ninline float \nfastlog2 (float x)\n{\n  union { float f; uint32_t i; } vx = { x };\n  union { uint32_t i; float f; } mx = { (vx.i & 0x007FFFFF) | (0x7e << 23) };\n  float y = (float)vx.i;\n  y *= 1.0f / (float)(1 << 23);\n\n  return \n    y - 124.22544637f - 1.498030302f * mx.f - 1.72587999f / (0.3520887068f + mx.f);\n}\n\ninline float\nfastlog (float x)\n{\n  return 0.69314718f * fastlog2 (x);\n}\n\ninline float\nfastpow2 (float p)\n{\n  float offset = (p < 0) ? 1.0f : 0.0f;\n  float clipp = (p < -126) ? -126.0f : p;\n  int w = (int)clipp;\n  float z = clipp - w + offset;\n  union { uint32_t i; float f; } v = { (uint32_t)((1 << 23) * (clipp + 121.2740838f + 27.7280233f / (4.84252568f - z) - 1.49012907f * z)) };\n\n  return v.f;\n}\n \ninline float\nfastexp (float p)\n{\n  return fastpow2 (1.442695040f * p);\n}\n\ninline float\nfastpow (float x,\n         float p)\n{\n  return fastpow2 (p * fastlog2 (x));\n}\n\ninline float\nfastlgamma (float x)\n{\n  float logterm = fastlog (x * (1.0f + x) * (2.0f + x));\n  float xp3 = 3.0f + x;\n\n  return \n    -2.081061466f - x + 0.0833333f / xp3 - logterm + (2.5f + x) * fastlog (xp3);\n}\n\ninline float\nfastdigamma (float x)\n{\n  float twopx = 2.0f + x;\n  float logterm = fastlog (twopx);\n\n  return - (1.0f + 2.0f * x) / (x * (1.0f + x)) \n         - (13.0f + 6.0f * x) / (12.0f * twopx * twopx) \n         + logterm;\n}\n\n#define log fastlog\n#define exp fastexp\n#define powf fastpow\n#define mydigamma fastdigamma\n#define mylgamma fastlgamma\n\n#if defined(__SSE2__) && !defined(VW_LDA_NO_SSE)\n\n#include <emmintrin.h>\n\ntypedef __m128 v4sf;\ntypedef __m128i v4si;\n\n#define v4si_to_v4sf _mm_cvtepi32_ps\n#define v4sf_to_v4si _mm_cvttps_epi32\n\nstatic inline float\nv4sf_index (const v4sf x,\n            unsigned int i)\n{\n  union { v4sf f; float array[4]; } tmp = { x };\n\n  return tmp.array[i];\n}\n\nstatic inline const v4sf\nv4sfl (float x)\n{\n  union { float array[4]; v4sf f; } tmp = { { x, x, x, x } };\n\n  return tmp.f;\n}\n\nstatic inline const v4si\nv4sil (uint32_t x)\n{\n  uint64_t wide = (((uint64_t) x) << 32) | x;\n  union { uint64_t array[2]; v4si f; } tmp = { { wide, wide } };\n\n  return tmp.f;\n}\n\nstatic inline v4sf\nvfastpow2 (const v4sf p)\n{\n  v4sf ltzero = _mm_cmplt_ps (p, v4sfl (0.0f));\n  v4sf offset = _mm_and_ps (ltzero, v4sfl (1.0f));\n  v4sf lt126 = _mm_cmplt_ps (p, v4sfl (-126.0f));\n  v4sf clipp = _mm_andnot_ps (lt126, p) + _mm_and_ps (lt126, v4sfl (-126.0f));\n  v4si w = v4sf_to_v4si (clipp);\n  v4sf z = clipp - v4si_to_v4sf (w) + offset;\n\n  const v4sf c_121_2740838 = v4sfl (121.2740838f);\n  const v4sf c_27_7280233 = v4sfl (27.7280233f);\n  const v4sf c_4_84252568 = v4sfl (4.84252568f);\n  const v4sf c_1_49012907 = v4sfl (1.49012907f);\n  union { v4si i; v4sf f; } v = {\n    v4sf_to_v4si (\n      v4sfl (1 << 23) * \n      (clipp + c_121_2740838 + c_27_7280233 / (c_4_84252568 - z) - c_1_49012907 * z)\n    )\n  };\n\n  return v.f;\n}\n\ninline v4sf\nvfastexp (const v4sf p)\n{\n  const v4sf c_invlog_2 = v4sfl (1.442695040f);\n\n  return vfastpow2 (c_invlog_2 * p);\n}\n\ninline v4sf\nvfastlog2 (v4sf x)\n{\n  union { v4sf f; v4si i; } vx = { x };\n  union { v4si i; v4sf f; } mx = { (vx.i & v4sil (0x007FFFFF)) | v4sil (0x3f000000) };\n  v4sf y = v4si_to_v4sf (vx.i);\n  y *= v4sfl (1.1920928955078125e-7f);\n\n  const v4sf c_124_22551499 = v4sfl (124.22551499f);\n  const v4sf c_1_498030302 = v4sfl (1.498030302f);\n  const v4sf c_1_725877999 = v4sfl (1.72587999f);\n  const v4sf c_0_3520087068 = v4sfl (0.3520887068f);\n\n  return y - c_124_22551499\n           - c_1_498030302 * mx.f \n           - c_1_725877999 / (c_0_3520087068 + mx.f);\n}\n\ninline v4sf\nvfastlog (v4sf x)\n{\n  const v4sf c_0_69314718 = v4sfl (0.69314718f);\n\n  return c_0_69314718 * vfastlog2 (x);\n}\n\ninline v4sf\nvfastdigamma (v4sf x)\n{\n  v4sf twopx = v4sfl (2.0f) + x;\n  v4sf logterm = vfastlog (twopx);\n\n  return (v4sfl (-48.0f) + x * (v4sfl (-157.0f) + x * (v4sfl (-127.0f) - v4sfl (30.0f) * x))) /\n         (v4sfl (12.0f) * x * (v4sfl (1.0f) + x) * twopx * twopx)\n         + logterm;\n}\n\nvoid\nvexpdigammify (vw& all, float* gamma)\n{\n  unsigned int n = all.lda;\n  float extra_sum = 0.0f;\n  v4sf sum = v4sfl (0.0f);\n  size_t i;\n\n  for (i = 0; i < n && ((uintptr_t) (gamma + i)) % 16 > 0; ++i)\n    { \n      extra_sum += gamma[i];\n      gamma[i] = fastdigamma (gamma[i]);\n    }\n\n  for (; i + 4 < n; i += 4)\n    { \n      v4sf arg = _mm_load_ps (gamma + i);\n      sum += arg;\n      arg = vfastdigamma (arg);\n      _mm_store_ps (gamma + i, arg);\n    }\n\n  for (; i < n; ++i)\n    { \n      extra_sum += gamma[i];\n      gamma[i] = fastdigamma (gamma[i]);\n    } \n\n  extra_sum += v4sf_index (sum, 0) + v4sf_index (sum, 1) +\n               v4sf_index (sum, 2) + v4sf_index (sum, 3);\n  extra_sum = fastdigamma (extra_sum);\n  sum = v4sfl (extra_sum);\n\n  for (i = 0; i < n && ((uintptr_t) (gamma + i)) % 16 > 0; ++i)\n    { \n      gamma[i] = fmaxf (1e-10f, fastexp (gamma[i] - v4sf_index (sum, 0)));\n    }\n\n  for (; i + 4 < n; i += 4)\n    { \n      v4sf arg = _mm_load_ps (gamma + i);\n      arg -= sum;\n      arg = vfastexp (arg);\n      arg = _mm_max_ps (v4sfl (1e-10f), arg);\n      _mm_store_ps (gamma + i, arg);\n    }\n\n  for (; i < n; ++i)\n    {\n      gamma[i] = fmaxf (1e-10f, fastexp (gamma[i] - v4sf_index (sum, 0)));\n    } \n}\n\nvoid vexpdigammify_2(vw& all, float* gamma, const float* norm)\n{\n  size_t n = all.lda;\n  size_t i;\n\n  for (i = 0; i < n && ((uintptr_t) (gamma + i)) % 16 > 0; ++i)\n    { \n      gamma[i] = fmaxf (1e-10f, fastexp (fastdigamma (gamma[i]) - norm[i]));\n    }\n\n  for (; i + 4 < n; i += 4)\n    {\n      v4sf arg = _mm_load_ps (gamma + i);\n      arg = vfastdigamma (arg);\n      v4sf vnorm = _mm_loadu_ps (norm + i);\n      arg -= vnorm;\n      arg = vfastexp (arg);\n      arg = _mm_max_ps (v4sfl (1e-10f), arg);\n      _mm_store_ps (gamma + i, arg);\n    }\n\n  for (; i < n; ++i)\n    {\n      gamma[i] = fmaxf (1e-10f, fastexp (fastdigamma (gamma[i]) - norm[i]));\n    }\n}\n\n#define myexpdigammify vexpdigammify\n#define myexpdigammify_2 vexpdigammify_2\n\n#else\n#ifndef _WIN32\n#warning \"lda IS NOT using sse instructions\"\n#endif\n#define myexpdigammify expdigammify\n#define myexpdigammify_2 expdigammify_2\n\n#endif // __SSE2__\n\n} // end anonymous namespace\n\n#else \n\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nusing namespace boost::math::policies;\n\n#define mydigamma boost::math::digamma\n#define mylgamma boost::math::lgamma\n#define myexpdigammify expdigammify\n#define myexpdigammify_2 expdigammify_2\n\n#endif // MINEIRO_SPECIAL\n\nfloat decayfunc(float t, float old_t, float power_t) {\n  float result = 1;\n  for (float i = old_t+1; i <= t; i += 1)\n    result *= (1-powf(i, -power_t));\n  return result;\n}\n\nfloat decayfunc2(float t, float old_t, float power_t) \n{\n  float power_t_plus_one = 1.f - power_t;\n  float arg =  - ( powf(t, power_t_plus_one) -\n                   powf(old_t, power_t_plus_one));\n  return exp ( arg\n               / power_t_plus_one);\n}\n\nfloat decayfunc3(double t, double old_t, double power_t) \n{\n  double power_t_plus_one = 1. - power_t;\n  double logt = log((float)t);\n  double logoldt = log((float)old_t);\n  return (float)((old_t / t) * exp((float)(0.5*power_t_plus_one*(-logt*logt + logoldt*logoldt))));\n}\n\nfloat decayfunc4(double t, double old_t, double power_t)\n{\n  if (power_t > 0.99)\n    return decayfunc3(t, old_t, power_t);\n  else\n    return (float)decayfunc2((float)t, (float)old_t, (float)power_t);\n}\n\nvoid expdigammify(vw& all, float* gamma)\n{\n  float sum=0;\n  for (size_t i = 0; i<all.lda; i++)\n    {\n      sum += gamma[i];\n      gamma[i] = mydigamma(gamma[i]);\n    }\n  sum = mydigamma(sum);\n  for (size_t i = 0; i<all.lda; i++)\n    gamma[i] = fmax(1e-6f, exp(gamma[i] - sum));\n}\n\nvoid expdigammify_2(vw& all, float* gamma, float* norm)\n{\n  for (size_t i = 0; i<all.lda; i++)\n    {\n      gamma[i] = fmax(1e-6f, exp(mydigamma(gamma[i]) - norm[i]));\n    }\n}\n\nfloat average_diff(vw& all, float* oldgamma, float* newgamma)\n{\n  float sum = 0.;\n  float normalizer = 0.;\n  for (size_t i = 0; i<all.lda; i++) {\n    sum += fabsf(oldgamma[i] - newgamma[i]);\n    normalizer += newgamma[i];\n  }\n  return sum / normalizer;\n}\n\n// Returns E_q[log p(\\theta)] - E_q[log q(\\theta)].\n  float theta_kl(lda& l, v_array<float>& Elogtheta, float* gamma)\n{\n  float gammasum = 0;\n  Elogtheta.erase();\n  for (size_t k = 0; k < l.topics; k++) {\n    Elogtheta.push_back(mydigamma(gamma[k]));\n    gammasum += gamma[k];\n  }\n  float digammasum = mydigamma(gammasum);\n  gammasum = mylgamma(gammasum);\n  float kl = -(l.topics*mylgamma(l.lda_alpha));\n  kl += mylgamma(l.lda_alpha*l.topics) - gammasum;\n  for (size_t k = 0; k < l.topics; k++) {\n    Elogtheta[k] -= digammasum;\n    kl += (l.lda_alpha - gamma[k]) * Elogtheta[k];\n    kl += mylgamma(gamma[k]);\n  }\n\n  return kl;\n}\n\nfloat find_cw(lda& l, float* u_for_w, float* v)\n{\n  float c_w = 0;\n  for (size_t k =0; k<l.topics; k++)\n    c_w += u_for_w[k]*v[k];\n\n  return 1.f / c_w;\n}\n\n  v_array<float> new_gamma = v_init<float>();\n  v_array<float> old_gamma = v_init<float>();\n// Returns an estimate of the part of the variational bound that\n// doesn't have to do with beta for the entire corpus for the current\n// setting of lambda based on the document passed in. The value is\n// divided by the total number of words in the document This can be\n// used as a (possibly very noisy) estimate of held-out likelihood.\n  float lda_loop(lda& l, v_array<float>& Elogtheta, float* v,weight* weights,example* ec, float power_t)\n{\n  new_gamma.erase();\n  old_gamma.erase();\n  \n  for (size_t i = 0; i < l.topics; i++)\n    {\n      new_gamma.push_back(1.f);\n      old_gamma.push_back(0.f);\n    }\n  size_t num_words =0;\n  for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)\n    num_words += ec->atomics[*i].end - ec->atomics[*i].begin;\n\n  float xc_w = 0;\n  float score = 0;\n  float doc_length = 0;\n  do\n    {\n      memcpy(v,new_gamma.begin,sizeof(float)*l.topics);\n      myexpdigammify(*l.all, v);\n\n      memcpy(old_gamma.begin,new_gamma.begin,sizeof(float)*l.topics);\n      memset(new_gamma.begin,0,sizeof(float)*l.topics);\n\n      score = 0;\n      size_t word_count = 0;\n      doc_length = 0;\n      for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)\n\t{\n\t  feature *f = ec->atomics[*i].begin;\n\t  for (; f != ec->atomics[*i].end; f++)\n\t    {\n\t      float* u_for_w = &weights[(f->weight_index & l.all->reg.weight_mask)+l.topics+1];\n\t      float c_w = find_cw(l, u_for_w,v);\n\t      xc_w = c_w * f->x;\n              score += -f->x*log(c_w);\n\t      size_t max_k = l.topics;\n\t      for (size_t k =0; k<max_k; k++) {\n\t\tnew_gamma[k] += xc_w*u_for_w[k];\n\t      }\n\t      word_count++;\n              doc_length += f->x;\n\t    }\n\t}\n      for (size_t k =0; k<l.topics; k++)\n\tnew_gamma[k] = new_gamma[k]*v[k]+l.lda_alpha;\n    }\n  while (average_diff(*l.all, old_gamma.begin, new_gamma.begin) > l.lda_epsilon);\n\n  ec->topic_predictions.erase();\n  ec->topic_predictions.resize(l.topics);\n  memcpy(ec->topic_predictions.begin,new_gamma.begin,l.topics*sizeof(float));\n\n  score += theta_kl(l, Elogtheta, new_gamma.begin);\n\n  return score / doc_length;\n}\n\nsize_t next_pow2(size_t x) {\n  int i = 0;\n  x = x > 0 ? x - 1 : 0;\n  while (x > 0) {\n    x >>= 1;\n    i++;\n  }\n  return ((size_t)1) << i;\n}\n\nvoid save_load(lda& l, io_buf& model_file, bool read, bool text)\n{\n  vw* all = l.all;\n  uint32_t length = 1 << all->num_bits;\n  uint32_t stride = 1 << all->reg.stride_shift;\n  \n  if (read)\n    {\n      initialize_regressor(*all);\n      for (size_t j = 0; j < stride*length; j+=stride)\n\t{\n\t  for (size_t k = 0; k < all->lda; k++) {\n\t    if (all->random_weights) {\n\t      all->reg.weight_vector[j+k] = (float)(-log(frand48()) + 1.0f);\n\t      all->reg.weight_vector[j+k] *= (float)(l.lda_D / all->lda / all->length() * 200);\n\t    }\n\t  }\n\t  all->reg.weight_vector[j+all->lda] = all->initial_t;\n\t}\n    }\n    \n  if (model_file.files.size() > 0)\n    {\n      uint32_t i = 0;\n      uint32_t text_len;\n      char buff[512];\n      size_t brw = 1;\n      do \n\t{\n\t  brw = 0;\n\t  size_t K = all->lda;\n\t  \n\t  text_len = sprintf(buff, \"%d \", i);\n\t  brw += bin_text_read_write_fixed(model_file,(char *)&i, sizeof (i),\n\t\t\t\t\t   \"\", read,\n\t\t\t\t\t   buff, text_len, text);\n\t  if (brw != 0)\n\t    for (uint32_t k = 0; k < K; k++)\n\t      {\n\t\tuint32_t ndx = stride*i+k;\n\t\t\n\t\tweight* v = &(all->reg.weight_vector[ndx]);\n\t\ttext_len = sprintf(buff, \"%f \", *v + l.lda_rho);\n\t\t\n\t\tbrw += bin_text_read_write_fixed(model_file,(char *)v, sizeof (*v),\n\t\t\t\t\t\t \"\", read,\n\t\t\t\t\t\t buff, text_len, text);\n\t\t\n\t      }\n\t  if (text)\n\t    brw += bin_text_read_write_fixed(model_file,buff,0,\n\t\t\t\t\t     \"\", read,\n\t\t\t\t\t     \"\\n\",1,text);\n\t  \n\t  if (!read)\n\t    i++;\n\t}  \n      while ((!read && i < length) || (read && brw >0));\n    }\n}\n\n  void learn_batch(lda& l)\n  {\n    if (l.sorted_features.empty()) {\n      // This can happen when the socket connection is dropped by the client.\n      // If l.sorted_features is empty, then l.sorted_features[0] does not\n      // exist, so we should not try to take its address in the beginning of\n      // the for loops down there. Since it seems that there's not much to\n      // do in this case, we just return.\n      for (size_t d = 0; d < l.examples.size(); d++)\n\treturn_simple_example(*l.all, NULL, *l.examples[d]);\n      l.examples.erase();\n      return;\n    }\n\n    float eta = -1;\n    float minuseta = -1;\n\n    if (l.total_lambda.size() == 0)\n      {\n\tfor (size_t k = 0; k < l.all->lda; k++)\n\t  l.total_lambda.push_back(0.f);\n\t\n\tsize_t stride = 1 << l.all->reg.stride_shift;\n\tfor (size_t i =0; i <= l.all->reg.weight_mask;i+=stride)\n\t  for (size_t k = 0; k < l.all->lda; k++)\n\t    l.total_lambda[k] += l.all->reg.weight_vector[i+k];\n      }\n\n    l.example_t++;\n    l.total_new.erase();\n    for (size_t k = 0; k < l.all->lda; k++)\n      l.total_new.push_back(0.f);\n    \n    size_t batch_size = l.examples.size();\n    \n    sort(l.sorted_features.begin(), l.sorted_features.end());\n    \n    eta = l.all->eta * powf((float)l.example_t, - l.all->power_t);\n    minuseta = 1.0f - eta;\n    eta *= l.lda_D / batch_size;\n    l.decay_levels.push_back(l.decay_levels.last() + log(minuseta));\n    \n    l.digammas.erase();\n    float additional = (float)(l.all->length()) * l.lda_rho;\n    for (size_t i = 0; i<l.all->lda; i++) {\n      l.digammas.push_back(mydigamma(l.total_lambda[i] + additional));\n    }\n    \n    \n    weight* weights = l.all->reg.weight_vector;\n    \n    size_t last_weight_index = -1;\n    for (index_feature* s = &l.sorted_features[0]; s <= &l.sorted_features.back(); s++)\n      {\n\tif (last_weight_index == s->f.weight_index)\n\t  continue;\n\tlast_weight_index = s->f.weight_index;\n\tfloat* weights_for_w = &(weights[s->f.weight_index & l.all->reg.weight_mask]);\n\tfloat decay = fmin(1.0, exp(l.decay_levels.end[-2] - l.decay_levels.end[(int)(-1 - l.example_t+weights_for_w[l.all->lda])]));\n\tfloat* u_for_w = weights_for_w + l.all->lda+1;\n\t\n\tweights_for_w[l.all->lda] = (float)l.example_t;\n\tfor (size_t k = 0; k < l.all->lda; k++)\n\t  {\n\t    weights_for_w[k] *= decay;\n\t    u_for_w[k] = weights_for_w[k] + l.lda_rho;\n\t  }\n\tmyexpdigammify_2(*l.all, u_for_w, l.digammas.begin);\n      }\n    \n    for (size_t d = 0; d < batch_size; d++)\n      {\n\tfloat score = lda_loop(l, l.Elogtheta, &(l.v[d*l.all->lda]), weights, l.examples[d],l.all->power_t);\n\tif (l.all->audit)\n\t  GD::print_audit_features(*l.all, *l.examples[d]);\n\t// If the doc is empty, give it loss of 0.\n\tif (l.doc_lengths[d] > 0) {\n\t  l.all->sd->sum_loss -= score;\n\t  l.all->sd->sum_loss_since_last_dump -= score;\n\t}\n\treturn_simple_example(*l.all, NULL, *l.examples[d]);\n      }\n    \n    for (index_feature* s = &l.sorted_features[0]; s <= &l.sorted_features.back();)\n      {\n\tindex_feature* next = s+1;\n\twhile(next <= &l.sorted_features.back() && next->f.weight_index == s->f.weight_index)\n\t  next++;\n\t\n\tfloat* word_weights = &(weights[s->f.weight_index & l.all->reg.weight_mask]);\n\tfor (size_t k = 0; k < l.all->lda; k++) {\n\t  float new_value = minuseta*word_weights[k];\n\t  word_weights[k] = new_value;\n\t}\n\t\n\tfor (; s != next; s++) {\n\t  float* v_s = &(l.v[s->document*l.all->lda]);\n\t  float* u_for_w = &weights[(s->f.weight_index & l.all->reg.weight_mask) + l.all->lda + 1];\n\t  float c_w = eta*find_cw(l, u_for_w, v_s)*s->f.x;\n\t  for (size_t k = 0; k < l.all->lda; k++) {\n\t    float new_value = u_for_w[k]*v_s[k]*c_w;\n\t    l.total_new[k] += new_value;\n\t    word_weights[k] += new_value;\n\t  }\n\t}\n      }\n    for (size_t k = 0; k < l.all->lda; k++) {\n      l.total_lambda[k] *= minuseta;\n      l.total_lambda[k] += l.total_new[k];\n    }\n\n    l.sorted_features.resize(0);\n    \n    l.examples.erase();\n    l.doc_lengths.erase();\n  }\n  \n  void learn(lda& l, base_learner& base, example& ec) \n  {\n    size_t num_ex = l.examples.size();\n    l.examples.push_back(&ec);\n    l.doc_lengths.push_back(0);\n    for (unsigned char* i = ec.indices.begin; i != ec.indices.end; i++) {\n      feature* f = ec.atomics[*i].begin;\n      for (; f != ec.atomics[*i].end; f++) {\n\tindex_feature temp = {(uint32_t)num_ex, *f};\n\tl.sorted_features.push_back(temp);\n\tl.doc_lengths[num_ex] += (int)f->x;\n      }\n    }\n    if (++num_ex == l.minibatch)\n      learn_batch(l);\n  }\n\n  // placeholder\n  void predict(lda& l, base_learner& base, example& ec)\n  {\n    learn(l, base, ec);\n  }\n\n  void end_pass(lda& l)\n  {\n    if (l.examples.size())\n      learn_batch(l);\n  }\n\nvoid end_examples(lda& l)\n{\n  for (size_t i = 0; i < l.all->length(); i++) {\n    weight* weights_for_w = & (l.all->reg.weight_vector[i << l.all->reg.stride_shift]);\n    float decay = fmin(1.0, exp(l.decay_levels.last() - l.decay_levels.end[(int)(-1- l.example_t +weights_for_w[l.all->lda])]));\n    for (size_t k = 0; k < l.all->lda; k++) \n      weights_for_w[k] *= decay;\n  }\n}\n\n  void finish_example(vw& all, lda&, example& ec)\n{}\n\n  void finish(lda& ld)\n  {\n    ld.sorted_features.~vector<index_feature>();\n    ld.Elogtheta.delete_v();\n    ld.decay_levels.delete_v();\n    ld.total_new.delete_v();\n    ld.examples.delete_v();\n    ld.total_lambda.delete_v();\n    ld.doc_lengths.delete_v();\n    ld.digammas.delete_v();\n    ld.v.delete_v();\n  }\n\n\nbase_learner* setup(vw&all)\n{\n  new_options(all, \"Lda options\")\n      (\"lda\", po::value<uint32_t>(), \"Run lda with <int> topics\")\n      (\"lda_alpha\", po::value<float>()->default_value(0.1f), \"Prior on sparsity of per-document topic weights\")\n      (\"lda_rho\", po::value<float>()->default_value(0.1f), \"Prior on sparsity of topic distributions\")\n      (\"lda_D\", po::value<float>()->default_value(10000.), \"Number of documents\")\n      (\"lda_epsilon\", po::value<float>()->default_value(0.001f), \"Loop convergence threshold\")\n      (\"minibatch\", po::value<size_t>()->default_value(1), \"Minibatch size, for LDA\");\n    add_options(all);\n    po::variables_map& vm= all.vm;\n    if(!vm.count(\"lda\"))\n      return NULL;\n    else\n      all.lda = vm[\"lda\"].as<uint32_t>();\n    \n      lda& ld = calloc_or_die<lda>();\n    \n    ld.topics = all.lda;\n    ld.lda_alpha = vm[\"lda_alpha\"].as<float>();\n    ld.lda_rho = vm[\"lda_rho\"].as<float>();\n    ld.lda_D = vm[\"lda_D\"].as<float>();\n    ld.lda_epsilon = vm[\"lda_epsilon\"].as<float>();\n    ld.minibatch = vm[\"minibatch\"].as<size_t>();\n    ld.sorted_features = vector<index_feature>();\n    ld.total_lambda_init = 0;\n    ld.all = &all;\n    ld.example_t = all.initial_t;\n    \n    float temp = ceilf(logf((float)(all.lda*2+1)) / logf (2.f));\n    all.reg.stride_shift = (size_t)temp;\n    all.random_weights = true;\n    all.add_constant = false;\n    \n  *all.file_options << \" --lda \" << all.lda;\n    \n    if (all.eta > 1.)\n      {\n\tcerr << \"your learning rate is too high, setting it to 1\" << endl;\n\tall.eta = min(all.eta,1.f);\n      }\n    \n    if (vm.count(\"minibatch\")) {\n      size_t minibatch2 = next_pow2(ld.minibatch);\n      all.p->ring_size = all.p->ring_size > minibatch2 ? all.p->ring_size : minibatch2;\n    }\n    \n  ld.v.resize(all.lda*ld.minibatch);\n  \n  ld.decay_levels.push_back(0.f);\n\n  learner<lda>& l = init_learner(&ld, learn, 1 << all.reg.stride_shift);\n  l.set_predict(predict);\n  l.set_save_load(save_load);\n  l.set_finish_example(finish_example);\n  l.set_end_examples(end_examples);  \n  l.set_end_pass(end_pass);  \n  l.set_finish(finish);\n  \n  return make_base(l);\n}\n}\n", "meta": {"hexsha": "e616ab25e622e62bc12ac2f9f70170e25cf1e144", "size": 21525, "ext": "cc", "lang": "C++", "max_stars_repo_path": "vowpalwabbit/lda_core.cc", "max_stars_repo_name": "moses-smt/vowpal_wabbit", "max_stars_repo_head_hexsha": "e7e8f97a7faf5d51f1b7f078567b8a983e6afb06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-02-23T22:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T09:04:21.000Z", "max_issues_repo_path": "vowpalwabbit/lda_core.cc", "max_issues_repo_name": "moses-smt/vowpal_wabbit", "max_issues_repo_head_hexsha": "e7e8f97a7faf5d51f1b7f078567b8a983e6afb06", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vowpalwabbit/lda_core.cc", "max_forks_repo_name": "moses-smt/vowpal_wabbit", "max_forks_repo_head_hexsha": "e7e8f97a7faf5d51f1b7f078567b8a983e6afb06", "max_forks_repo_licenses": ["BSD-3-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.2820512821, "max_line_length": 140, "alphanum_fraction": 0.6073867596, "num_tokens": 7322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.030214588704752188, "lm_q1q2_score": 0.014753281960223574}}
{"text": "/*\n * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP.\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the Free\n * Software Foundation; either version 2 of the License, or (at your option)\n * any later version.\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\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n * more details. You should have received a copy of the GNU 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 * HP designates this particular file as subject to the \"Classpath\" exception\n * as provided by HP in the LICENSE.txt file that accompanied this code.\n */\n/**\n * @file foedus/graphlda/lda.cpp\n * @brief Latent-Dirichlet Allocation experiment for Topic Modeling\n * @author kimurhid\n * @date 2014/11/22\n * @details\n * This is a port of Fei Chen's LDA topic modeling program to FOEDUS.\n */\n#include <stdint.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"foedus/engine.hpp\"\n#include \"foedus/engine_options.hpp\"\n#include \"foedus/error_stack.hpp\"\n#include \"foedus/debugging/debugging_supports.hpp\"\n#include \"foedus/debugging/stop_watch.hpp\"\n#include \"foedus/fs/filesystem.hpp\"\n#include \"foedus/memory/engine_memory.hpp\"\n#include \"foedus/proc/proc_manager.hpp\"\n#include \"foedus/soc/shared_memory_repo.hpp\"\n#include \"foedus/soc/soc_manager.hpp\"\n#include \"foedus/storage/storage_id.hpp\"\n#include \"foedus/storage/storage_manager.hpp\"\n#include \"foedus/storage/array/array_storage.hpp\"\n#include \"foedus/thread/numa_thread_scope.hpp\"\n#include \"foedus/thread/thread.hpp\"\n#include \"foedus/thread/thread_pool.hpp\"\n#include \"foedus/thread/thread_pool_pimpl.hpp\"\n#include \"foedus/xct/xct_id.hpp\"\n#include \"foedus/xct/xct_manager.hpp\"\n\nnamespace foedus {\nnamespace graphlda {\n\nDEFINE_string(dictionary_fname, \"dictionary.txt\", \"Dictionary file\");\nDEFINE_string(counts_fname, \"counts.tsv\", \"Counts file\");\nDEFINE_int32(ntopics, 50, \"Number of topics\");\nDEFINE_int32(nburnin, 50, \"Number of burnin iterations\");\nDEFINE_int32(nsamples, 10, \"Number of sampling iterations\");\nDEFINE_int32(nthreads, 16, \"Total number of threads\");\nDEFINE_double(alpha, 1.0, \"Alpha prior\");\nDEFINE_double(beta, 0.1, \"Beta prior\");\nDEFINE_bool(fork_workers, false, \"Whether to fork(2) worker threads in child processes rather\"\n    \" than threads in the same process. This is required to scale up to 100+ cores.\");\nDEFINE_bool(profile, false, \"Whether to profile the execution with gperftools.\");\n\ntypedef uint32_t WordId;\ntypedef uint32_t DocId;\ntypedef uint16_t TopicId;\ntypedef uint32_t Count;\nconst TopicId kNullTopicId = -1;\n\n/** Used for overflow check */\nconst Count kUnreasonablyLargeUint32 = (0xFFFF0000U);\ninline Count check_overflow(Count count) {\n  if (count > kUnreasonablyLargeUint32) {\n    return 0;\n  } else {\n    return count;\n  }\n}\n\n// storage names\n/**\n * n_td(t,d) [1d: d * ntopics + t] Number of occurences of topic t in document d.\n * As an array storage, it's d records of ntopics Count.\n */\nconst char* kNtd = \"n_td\";\n/**\n * n_tw(t,w) [1d: w * ntopics + t] Number of occurences of word w in topic t.\n * As an array storage, it's w records of ntopics Count.\n */\nconst char* kNtw = \"n_tw\";\n/**\n * n_t(t) [1d: t] The total number of words assigned to topic t.\n * As an array storage, it's 1 record of ntopics Count.\n */\nconst char* kNt = \"n_t\";\n\nstruct Token {\n  WordId word;\n  DocId doc;\n  Token(WordId word = 0, DocId doc = 0) : word(word), doc(doc) { }\n};\nstd::ostream& operator<<(std::ostream& out, const Token& tok) {\n  return out << \"(\" << tok.word << \", \" << tok.doc << \")\";\n}\n\n/** This object is held only by the driver thread. Individual worker uses SharedInputs. */\nstruct Corpus {\n  size_t nwords, ndocs, ntokens;\n  std::vector< Token > tokens;\n  std::vector<std::string> dictionary;\n\n  Corpus(const fs::Path& dictionary_fname, const fs::Path& counts_fname)\n    : nwords(0), ndocs(0), ntokens(0) {\n    dictionary.reserve(20000);\n    tokens.reserve(100000);\n    load_dictionary(dictionary_fname);\n    load_counts(counts_fname);\n  }\n  void load_dictionary(const fs::Path& fname) {\n    std::ifstream fin(fname.c_str());\n    std::string str;\n    while (fin.good()) {\n      std::getline(fin, str);\n      if (fin.good()) {\n        dictionary.push_back(str);\n        nwords++;\n      }\n    }\n    fin.close();\n  }\n\n  void load_counts(const fs::Path& fname)  {\n    std::ifstream fin(fname.c_str());\n    while (fin.good()) {\n      // Read a collection of tokens\n      const size_t NULL_VALUE(-1);\n      size_t word = NULL_VALUE, doc = NULL_VALUE, count = NULL_VALUE;\n      fin >> doc >> word >> count;\n      if (fin.good()) {\n        ASSERT_ND(word != NULL_VALUE && doc != NULL_VALUE && count != NULL_VALUE);\n        // update the doc counter\n        ndocs = std::max(ndocs, doc + 1);\n        // Assert valid word\n        ASSERT_ND(word < nwords);\n        // Update the words in document counter\n        // Add all the tokens\n        Token tok; tok.word = word; tok.doc = doc;\n        for (size_t i = 0; i < count; ++i) {\n            tokens.push_back(tok);\n        }\n      }\n    }\n    fin.close();\n    ntokens = tokens.size();\n  }\n};\n\n/** A copy of essential parts of Corpus, which can be placed in shared memory. No vector/string */\nstruct SharedInputs {\n  uint32_t  nwords;\n  uint32_t  ndocs;\n  uint32_t  ntokens;\n  uint32_t  ntopics;\n  uint32_t  niterations;\n  double    alpha;\n  double    beta;\n  /**\n   * Actually \"Token tokens[ntokens]\" and then \"TopicId topics[ntokens]\".\n   * Note that you can't do sizeof(SharedCorpus).\n   */\n  char      dynamic_data[8];\n\n  static uint64_t get_object_size(uint32_t ntokens) {\n    return sizeof(SharedInputs) + (sizeof(Token) + sizeof(TopicId)) * ntokens;\n  }\n\n  void init(const Corpus& original) {\n    nwords = original.nwords;\n    ndocs = original.ndocs;\n    ntokens = original.ntokens;\n    ntopics = FLAGS_ntopics;\n    niterations = 0;  // set separately\n    alpha = FLAGS_alpha;\n    beta = FLAGS_beta;\n    std::memcpy(get_tokens_data(), &(original.tokens[0]), sizeof(Token) * ntokens);\n    std::memset(get_topics_data(), 0xFFU, sizeof(TopicId) * ntokens);  // null topic ID\n  }\n\n  Token* get_tokens_data() {\n    return reinterpret_cast<Token*>(dynamic_data);\n  }\n  TopicId* get_topics_data() {\n    return reinterpret_cast<TopicId*>(dynamic_data + sizeof(Token) * ntokens);\n  }\n};\n\n/** Core implementation of LDA experiment. */\nclass LdaWorker {\n public:\n  enum Constant {\n    kIntNormalizer = 1 << 24,\n    kNtApplyBatch = 1 << 8,\n  };\n  explicit LdaWorker(const proc::ProcArguments& args) {\n    engine = args.engine_;\n    context = args.context_;\n    shared_inputs = reinterpret_cast<SharedInputs*>(\n      engine->get_soc_manager()->get_shared_memory_repo()->get_global_user_memory());\n    *args.output_used_ = 0;\n  }\n  ErrorStack on_lda_worker_task() {\n    uint16_t thread_id = context->get_thread_global_ordinal();\n    LOG(INFO) << \"Thread-\" << thread_id << \" started\";\n    unirand.set_current_seed(thread_id);\n\n\n    Token* shared_tokens = shared_inputs->get_tokens_data();\n    ntopics = shared_inputs->ntopics;\n    ntopics_aligned = assorted::align8(ntopics);\n    numwords = shared_inputs->nwords;\n\n    TopicId* shared_topics = shared_inputs->get_topics_data();\n    const uint32_t numtokens = shared_inputs->ntokens;\n    const uint32_t niterations = shared_inputs->niterations;\n    const uint16_t all_threads = engine->get_options().thread_.get_total_thread_count();\n    tokens_per_core = numtokens / all_threads;\n    int_a = static_cast<uint64_t>(shared_inputs->alpha * kIntNormalizer);\n    int_b = static_cast<uint64_t>(shared_inputs->beta * kIntNormalizer);\n\n    // allocate tmp memory on local NUMA node.\n    // These are the only memory that need dynamic allocation in main_loop\n    uint64_t tmp_memory_size = ntopics_aligned * sizeof(uint64_t)  // conditional\n        + tokens_per_core * sizeof(Token)  // assigned_tokens\n        + ntopics_aligned * sizeof(Count)  // record_td\n        + ntopics_aligned * sizeof(Count)  // record_tw\n        + ntopics_aligned * sizeof(Count)  // record_t\n        + ntopics_aligned * sizeof(Count)  // record_t_diff\n        + tokens_per_core * sizeof(TopicId);  // topics_tmp\n    tmp_memory.alloc(\n      tmp_memory_size,\n      1 << 21,\n      memory::AlignedMemory::kNumaAllocOnnode,\n      context->get_numa_node());\n    char* tmp_block = reinterpret_cast<char*>(tmp_memory.get_block());\n\n    int_conditional = reinterpret_cast<uint64_t*>(tmp_block);\n    tmp_block += ntopics_aligned * sizeof(uint64_t);\n\n    assigned_tokens = reinterpret_cast<Token*>(tmp_block);\n    tmp_block += tokens_per_core * sizeof(Token);\n\n    record_td = reinterpret_cast<Count*>(tmp_block);\n    tmp_block += ntopics_aligned * sizeof(Count);\n\n    record_tw = reinterpret_cast<Count*>(tmp_block);\n    tmp_block += ntopics_aligned * sizeof(Count);\n\n    record_t = reinterpret_cast<Count*>(tmp_block);\n    tmp_block += ntopics_aligned * sizeof(Count);\n\n    record_t_diff = reinterpret_cast<Count*>(tmp_block);\n    tmp_block += ntopics_aligned * sizeof(Count);\n\n    topics_tmp = reinterpret_cast<TopicId*>(tmp_block);\n    tmp_block += tokens_per_core * sizeof(TopicId);\n\n    uint64_t size_check = tmp_block - reinterpret_cast<char*>(tmp_memory.get_block());\n    ASSERT_ND(size_check == tmp_memory_size);\n\n    // initialize with previous result (if this is burnin, all null-topic)\n    uint64_t assign_pos = tokens_per_core * thread_id;\n    std::memcpy(topics_tmp, shared_topics + assign_pos, tokens_per_core * sizeof(TopicId));\n    std::memcpy(assigned_tokens, shared_tokens + assign_pos, tokens_per_core * sizeof(Token));\n\n    n_td = storage::array::ArrayStorage(engine, kNtd);\n    n_tw = storage::array::ArrayStorage(engine, kNtw);\n    n_t = storage::array::ArrayStorage(engine, kNt);\n    ASSERT_ND(n_td.exists());\n    ASSERT_ND(n_tw.exists());\n    ASSERT_ND(n_t.exists());\n\n    nchanges = 0;\n    std::memset(int_conditional, 0, sizeof(uint64_t) * ntopics_aligned);\n    std::memset(record_td, 0, sizeof(Count) * ntopics_aligned);\n    std::memset(record_tw, 0, sizeof(Count) * ntopics_aligned);\n    std::memset(record_t, 0, sizeof(Count) * ntopics_aligned);\n    std::memset(record_t_diff, 0, sizeof(Count) * ntopics_aligned);\n\n    // Loop over all the tokens\n    for (size_t gn = 0; gn < niterations; ++gn) {\n      LOG(INFO) << \"Thread-\" << thread_id << \" iteration \" << gn << \"/\" << niterations;\n      WRAP_ERROR_CODE(main_loop());\n    }\n\n    // copy back the topics to shared. it's per-core, so this is the only thread that modifies it.\n    std::memcpy(shared_topics + assign_pos, topics_tmp, tokens_per_core * sizeof(TopicId));\n\n    const uint64_t ntotal = niterations * tokens_per_core;\n    LOG(INFO) << \"Thread-\" << thread_id << \" done. nchanges/ntotal=\"\n      << nchanges << \"/\" << ntotal << \"=\" << (static_cast<double>(nchanges) / ntotal);\n    return kRetOk;\n  }\n\n private:\n  Engine* engine;\n  thread::Thread* context;\n  SharedInputs* shared_inputs;\n  uint16_t ntopics;\n  uint16_t ntopics_aligned;\n  uint32_t numwords;\n  uint32_t tokens_per_core;\n  uint64_t nchanges;\n  uint64_t int_a;\n  uint64_t int_b;\n  storage::array::ArrayStorage n_td;  // d records of ntopics Count\n  storage::array::ArrayStorage n_tw;  // w records of ntopics Count\n  storage::array::ArrayStorage n_t;  // 1 record of ntopics Count\n  assorted::UniformRandom unirand;\n\n  /** local memory to back the followings */\n  memory::AlignedMemory tmp_memory;\n  uint64_t* int_conditional;  // [ntopics]\n  Token* assigned_tokens;  // [tokens_per_core]\n  Count* record_td;  // [ntopics]\n  Count* record_tw;  // [ntopics]\n  Count* record_t;  // [ntopics]\n  Count* record_t_diff;  // [ntopics]. This batches changes to n_t, which is so contentious.\n  TopicId* topics_tmp;  // [tokens_per_core]\n\n  ErrorCode main_loop() {\n    xct::XctManager* xct_manager = engine->get_xct_manager();\n    uint16_t batched_t = 0;\n    for (size_t i = 0; i < tokens_per_core; ++i) {\n      // Get the word and document for the ith token\n      const WordId w = assigned_tokens[i].word;\n      const DocId d = assigned_tokens[i].doc;\n      const TopicId old_topic = topics_tmp[i];\n\n      CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead));\n\n      // First, read from the global arrays\n      CHECK_ERROR_CODE(n_td.get_record(context, d, record_td));\n      CHECK_ERROR_CODE(n_tw.get_record(context, w, record_tw));\n\n      // Construct the conditional\n      uint64_t normalizer = 0;\n      // We do the following calculation without double/float to speed up.\n      // Notation: int_x := x * N (eg, int_ntd := ntd * N, int_alpha = alpha * N)\n      //           where N is some big number, such as 2^24\n      //      conditional[t] = (a + ntd) * (b + ntw) / (b * nwords + nt)\n      // <=>  conditional[t] = (int_a + int_ntd) * (b + ntw) / (int_b * nwords + int_nt)\n      // <=>  int_conditional[t] = (int_a + int_ntd) * (int_b + int_ntw) / (int_b * nwords + int_nt)\n      for (TopicId t = 0; t < ntopics; ++t) {\n        uint64_t int_ntd = record_td[t], int_ntw = record_tw[t], int_nt = record_t[t];\n        if (t == old_topic) {\n          // locally apply the decrements. we apply it to global array\n          // when we are sure that new_topic != old_topic\n          --int_ntd;\n          --int_ntw;\n          --int_nt;\n        }\n        int_ntd = check_overflow(int_ntd) * kIntNormalizer;\n        int_ntw = check_overflow(int_ntw) * kIntNormalizer;\n        int_nt = check_overflow(int_nt) * kIntNormalizer;\n\n        int_conditional[t] = (int_a + int_ntd) * (int_b + int_ntw) / (int_b * numwords + int_nt);\n        normalizer += int_conditional[t];\n      }\n\n      // Draw a new valuez\n      TopicId new_topic = topic_multinomial(normalizer);\n\n      // Update the topic assignment and counters\n      if (new_topic != old_topic) {\n        nchanges++;\n        topics_tmp[i] = new_topic;\n\n        // We apply the inc/dec to global array only in this case.\n        if (old_topic != kNullTopicId) {\n          // Remove the word from the old counters\n          uint16_t offset = old_topic * sizeof(Count);\n          CHECK_ERROR_CODE(n_td.increment_record_oneshot<Count>(context, d, -1, offset));\n          CHECK_ERROR_CODE(n_tw.increment_record_oneshot<Count>(context, w, -1, offset));\n          // change to t are batched. will be applied later\n          --record_t[old_topic];\n          --record_t_diff[old_topic];\n        }\n\n        // Add the word to the new counters\n        uint16_t offset = new_topic * sizeof(Count);\n        CHECK_ERROR_CODE(n_td.increment_record_oneshot<Count>(context, d, 1, offset));\n        CHECK_ERROR_CODE(n_tw.increment_record_oneshot<Count>(context, w, 1, offset));\n        ++record_t[new_topic];\n        ++record_t_diff[new_topic];\n\n        Epoch ep;\n        // because this is not serializable level and the only update is one-shot increment,\n        // no race is possible.\n        CHECK_ERROR_CODE(xct_manager->precommit_xct(context, &ep));\n\n        ++batched_t;\n        if (batched_t >= kNtApplyBatch) {\n          CHECK_ERROR_CODE(sync_record_t());\n          batched_t = 0;\n        }\n      } else {\n        CHECK_ERROR_CODE(xct_manager->abort_xct(context));\n      }\n    }\n\n    CHECK_ERROR_CODE(sync_record_t());\n\n    return kErrorCodeOk;\n  }\n\n  TopicId topic_multinomial(uint64_t normalizer) {\n    uint64_t sample = unirand.next_uint64() % normalizer;\n    uint64_t cur_sum = 0;\n    for (TopicId t = 0; t < ntopics; ++t) {\n      cur_sum += int_conditional[t];\n      if (sample <= cur_sum) {\n        return t;\n      }\n    }\n    return ntopics - 1U;\n  }\n\n\n  ErrorCode sync_record_t() {\n    xct::XctManager* xct_manager = engine->get_xct_manager();\n    Epoch ep;\n    // first, \"flush\" batched increments/decrements to the global n_t\n    // this transactionally applies all the inc/dec.\n    CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead));\n    for (TopicId t = 0; t < ntopics_aligned; t += 4) {\n      // for each uint64_t. we reserved additional size (align8) for simplifying this.\n      uint64_t diff = *reinterpret_cast<uint64_t*>(&record_t_diff[t]);\n      if (diff != 0) {\n        uint16_t offset = t * sizeof(Count);\n        CHECK_ERROR_CODE(n_t.increment_record_oneshot<uint64_t>(context, 0, diff, offset));\n      }\n    }\n    CHECK_ERROR_CODE(xct_manager->precommit_xct(context, &ep));\n\n    // then, retrive a fresh new copy of record_t, which contains updates from other threads.\n    std::memset(record_t, 0, sizeof(Count) * ntopics_aligned);\n    std::memset(record_t_diff, 0, sizeof(Count) * ntopics_aligned);\n    CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead));\n    CHECK_ERROR_CODE(n_t.get_record(context, 0, record_t));\n    CHECK_ERROR_CODE(xct_manager->abort_xct(context));\n    return kErrorCodeOk;\n  }\n};\n\nErrorStack lda_worker_task(const proc::ProcArguments& args) {\n  LdaWorker worker(args);\n  return worker.on_lda_worker_task();\n}\n\nvoid run_workers(Engine* engine, SharedInputs* shared_inputs, uint32_t niterations) {\n  const EngineOptions& options = engine->get_options();\n\n  auto* thread_pool = engine->get_thread_pool();\n  std::vector< thread::ImpersonateSession > sessions;\n\n  shared_inputs->niterations = niterations;\n  for (uint16_t node = 0; node < options.thread_.group_count_; ++node) {\n    for (uint16_t ordinal = 0; ordinal < options.thread_.thread_count_per_group_; ++ordinal) {\n      thread::ImpersonateSession session;\n      bool ret = thread_pool->impersonate_on_numa_node(\n        node,\n        \"worker_task\",\n        nullptr,\n        0,\n        &session);\n      if (!ret) {\n        LOG(FATAL) << \"Couldn't impersonate\";\n      }\n      sessions.emplace_back(std::move(session));\n    }\n  }\n  LOG(INFO) << \"Started running! #iter=\" << niterations;\n  for (uint32_t i = 0; i < sessions.size(); ++i) {\n    LOG(INFO) << \"result[\" << i << \"]=\" << sessions[i].get_result();\n    COERCE_ERROR(sessions[i].get_result());\n    sessions[i].release();\n  }\n  LOG(INFO) << \"Completed\";\n}\n\nErrorStack lda_populate_array_task(const proc::ProcArguments& args) {\n  ASSERT_ND(args.input_len_ == sizeof(storage::StorageId));\n  storage::StorageId storage_id = *reinterpret_cast<const storage::StorageId*>(args.input_buffer_);\n  storage::array::ArrayStorage array(args.engine_, storage_id);\n  ASSERT_ND(array.exists());\n  thread::Thread* context = args.context_;\n\n  uint16_t nodes = args.engine_->get_options().thread_.group_count_;\n  uint16_t node = context->get_numa_node();\n  uint64_t records_per_node = array.get_array_size() / nodes;\n  storage::array::ArrayOffset begin = records_per_node * node;\n  storage::array::ArrayOffset end = records_per_node * (node + 1U);\n  WRAP_ERROR_CODE(array.prefetch_pages(context, true, false, begin, end));\n\n  LOG(INFO) << \"Population of \" << array.get_name() << \" done in node-\" << node;\n  return kRetOk;\n}\n\nvoid create_count_array(\n  Engine* engine,\n  const char* name,\n  uint64_t records,\n  uint64_t counts) {\n  Epoch ep;\n  uint64_t counts_aligned = assorted::align8(counts);\n  storage::array::ArrayMetadata meta(name, counts_aligned * sizeof(Count), records);\n  COERCE_ERROR(engine->get_storage_manager()->create_storage(&meta, &ep));\n  LOG(INFO) << \"Populating empty \" << name << \"(id=\" << meta.id_ << \")...\";\n\n  // populate it with one thread per node.\n  const EngineOptions& options = engine->get_options();\n  auto* thread_pool = engine->get_thread_pool();\n  std::vector< thread::ImpersonateSession > sessions;\n  for (uint16_t node = 0; node < options.thread_.group_count_; ++node) {\n    thread::ImpersonateSession session;\n    bool ret = thread_pool->impersonate_on_numa_node(\n      node,\n      \"populate_array_task\",\n      &meta.id_,\n      sizeof(meta.id_),\n      &session);\n    if (!ret) {\n      LOG(FATAL) << \"Couldn't impersonate\";\n    }\n    sessions.emplace_back(std::move(session));\n  }\n  for (uint32_t i = 0; i < sessions.size(); ++i) {\n    LOG(INFO) << \"populate result[\" << i << \"]=\" << sessions[i].get_result();\n    COERCE_ERROR(sessions[i].get_result());\n    sessions[i].release();\n  }\n  LOG(INFO) << \"Populated empty \" << name;\n}\n\ndouble run_experiment(Engine* engine, const Corpus &corpus) {\n  const EngineOptions& options = engine->get_options();\n\n  // Input information placed in shared memory\n  SharedInputs* shared_inputs = reinterpret_cast<SharedInputs*>(\n    engine->get_soc_manager()->get_shared_memory_repo()->get_global_user_memory());\n  ASSERT_ND(options.soc_.shared_user_memory_size_kb_ * (1ULL << 10)\n    >= SharedInputs::get_object_size(corpus.ntokens));\n  shared_inputs->init(corpus);\n\n  // create empty tables.\n  create_count_array(engine, kNtd, corpus.ndocs, FLAGS_ntopics);\n  create_count_array(engine, kNtw, corpus.nwords, FLAGS_ntopics);\n  create_count_array(engine, kNt, 1, FLAGS_ntopics);\n\n  LOG(INFO) << \"Created arrays\";\n\n  if (FLAGS_profile) {\n    COERCE_ERROR(engine->get_debug()->start_profile(\"lda.prof\"));\n  }\n\n  debugging::StopWatch watch;\n  run_workers(engine, shared_inputs, FLAGS_nburnin);\n  LOG(INFO) << \"Completed burnin!\";\n  run_workers(engine, shared_inputs, FLAGS_nsamples);\n  LOG(INFO) << \"Completed final sampling!\";\n\n  watch.stop();\n\n  LOG(INFO) << \"Experiment ended. Elapsed time=\" << watch.elapsed_sec() << \"sec\";\n  if (FLAGS_profile) {\n    engine->get_debug()->stop_profile();\n    LOG(INFO) << \"Check out the profile result: pprof --pdf lda lda.prof > lda.pdf; okular lda.pdf\";\n  }\n\n  LOG(INFO) << \"Shutting down...\";\n\n  LOG(INFO) << engine->get_memory_manager()->dump_free_memory_stat();\n  return watch.elapsed_sec();\n}\n\n\nint driver_main(int argc, char** argv) {\n  gflags::SetUsageMessage(\"LDA sampler code\");\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n  fs::Path dictionary_fname(FLAGS_dictionary_fname);\n  fs::Path counts_fname(FLAGS_counts_fname);\n\n  if (!fs::exists(dictionary_fname)) {\n    std::cerr << \"The dictionary file doesn't exist: \" << dictionary_fname;\n    return 1;\n  } else if (!fs::exists(counts_fname)) {\n    std::cerr << \"The count file doesn't exist: \" << counts_fname;\n    return 1;\n  }\n\n  fs::Path folder(\"/dev/shm/foedus_lda\");\n  if (fs::exists(folder)) {\n    fs::remove_all(folder);\n  }\n  if (!fs::create_directories(folder)) {\n    std::cerr << \"Couldn't create \" << folder << \". err=\" << assorted::os_error();\n    return 1;\n  }\n\n  EngineOptions options;\n\n  fs::Path savepoint_path(folder);\n  savepoint_path /= \"savepoint.xml\";\n  options.savepoint_.savepoint_path_.assign(savepoint_path.string());\n  ASSERT_ND(!fs::exists(savepoint_path));\n\n  std::cout << \"NUMA node count=\" << static_cast<int>(options.thread_.group_count_) << std::endl;\n  uint16_t thread_count = FLAGS_nthreads;\n  if (thread_count < options.thread_.group_count_) {\n    std::cout << \"nthreads less than socket count. Using subset of sockets\" << std::endl;\n    options.thread_.group_count_ = thread_count;\n    options.thread_.thread_count_per_group_ = 1;\n  } else if (thread_count % options.thread_.group_count_ != 0) {\n    std::cout << \"nthreads not multiply of #sockets. adjusting\" << std::endl;\n    options.thread_.thread_count_per_group_ = thread_count / options.thread_.group_count_;\n  } else {\n    options.thread_.thread_count_per_group_ = thread_count / options.thread_.group_count_;\n  }\n\n  options.snapshot_.folder_path_pattern_ = \"/dev/shm/foedus_lda/snapshot/node_$NODE$\";\n  options.snapshot_.snapshot_interval_milliseconds_ = 100000000U;\n\n  options.log_.folder_path_pattern_ = \"/dev/shm/foedus_lda/log/node_$NODE$/logger_$LOGGER$\";\n  options.log_.loggers_per_node_ = 1;\n  options.log_.flush_at_shutdown_ = false;\n  options.log_.log_file_size_mb_ = 1 << 16;\n  options.log_.emulation_.null_device_ = true;\n\n  options.memory_.page_pool_size_mb_per_node_ = 1 << 8;\n  options.cache_.snapshot_cache_size_mb_per_node_ = 1 << 6;\n\n  if (FLAGS_fork_workers) {\n    std::cout << \"Will fork workers in child processes\" << std::endl;\n    options.soc_.soc_type_ = kChildForked;\n  }\n\n  options.debugging_.debug_log_min_threshold_\n    = debugging::DebuggingOptions::kDebugLogInfo;\n    // = debugging::DebuggingOptions::kDebugLogWarning;\n  options.debugging_.verbose_modules_ = \"\";\n  options.debugging_.verbose_log_level_ = -1;\n\n  std::cout << \"Loading the corpus.\" << std::endl;\n  Corpus corpus(dictionary_fname, counts_fname);\n\n  std::cout << \"Number of words:   \" << corpus.nwords << std::endl\n            << \"Number of docs:    \" << corpus.ndocs << std::endl\n            << \"Number of tokens:  \" << corpus.ntokens << std::endl\n            << \"Number of topics:  \" << FLAGS_ntopics << std::endl\n            << \"Number of threads: \" << options.thread_.get_total_thread_count() << std::endl\n            << \"Alpha:             \" << FLAGS_alpha   << std::endl\n            << \"Beta:              \" << FLAGS_beta    << std::endl;\n\n  options.soc_.shared_user_memory_size_kb_\n    = (SharedInputs::get_object_size(corpus.ntokens) >> 10) + 64;\n\n  double elapsed;\n  {\n    Engine engine(options);\n    engine.get_proc_manager()->pre_register(\"worker_task\", lda_worker_task);\n    engine.get_proc_manager()->pre_register(\"populate_array_task\", lda_populate_array_task);\n    COERCE_ERROR(engine.initialize());\n    {\n      UninitializeGuard guard(&engine);\n      elapsed = run_experiment(&engine, corpus);\n      COERCE_ERROR(engine.uninitialize());\n    }\n  }\n\n  std::cout << \"All done. elapsed time=\" << elapsed << \"sec\" << std::endl;\n\n  return 0;\n}\n\n}  // namespace graphlda\n}  // namespace foedus\n\nint main(int argc, char **argv) {\n  return foedus::graphlda::driver_main(argc, argv);\n}\n\n", "meta": {"hexsha": "e018e31589187c6fc952e9abd3dfc6967b20aa87", "size": 25774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "foedus_code/experiments-core/src/foedus/graphlda/lda.cpp", "max_stars_repo_name": "sam1016yu/cicada-exp-sigmod2017", "max_stars_repo_head_hexsha": "64e582370076b2923d37b279d1c32730babc15f8", "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": "foedus_code/experiments-core/src/foedus/graphlda/lda.cpp", "max_issues_repo_name": "sam1016yu/cicada-exp-sigmod2017", "max_issues_repo_head_hexsha": "64e582370076b2923d37b279d1c32730babc15f8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "foedus_code/experiments-core/src/foedus/graphlda/lda.cpp", "max_forks_repo_name": "sam1016yu/cicada-exp-sigmod2017", "max_forks_repo_head_hexsha": "64e582370076b2923d37b279d1c32730babc15f8", "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.7674750357, "max_line_length": 100, "alphanum_fraction": 0.6803755723, "num_tokens": 6816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.04958902052601327, "lm_q1q2_score": 0.01475124370739552}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS_CODATA_PROTON_CONSTANTS_HPP\n#define BOOST_UNITS_CODATA_PROTON_CONSTANTS_HPP\n\n#include <boost/units/quantity.hpp>\n#include <boost/units/static_constant.hpp>\n\n#include <boost/units/systems/detail/constants.hpp>\n#include <boost/units/systems/si/amount.hpp>\n#include <boost/units/systems/si/area.hpp>\n#include <boost/units/systems/si/electric_charge.hpp>\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/systems/si/frequency.hpp>\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/systems/si/magnetic_flux_density.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/wavenumber.hpp>\n\n#include <boost/units/systems/si/codata/typedefs.hpp>\n\n/// \\file\n/// CODATA recommended values of fundamental atomic and nuclear constants\n/// CODATA 2006 values as of 2007/03/30\n\nnamespace boost {\n\nnamespace units { \n\nnamespace si {\n                            \nnamespace constants {\n\nnamespace codata {\n\n/// CODATA recommended values of the fundamental physical constants: NIST SP 961\n\n/// proton mass\nBOOST_UNITS_PHYSICAL_CONSTANT(m_p,quantity<mass>,1.672621637e-27*kilograms,8.3e-35*kilograms);\n/// proton-electron mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_p_over_m_e,quantity<dimensionless>,1836.15267247*dimensionless(),8.0e-7*dimensionless());\n/// proton-muon mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_p_over_m_mu,quantity<dimensionless>,8.88024339*dimensionless(),2.3e-7*dimensionless());\n/// proton-tau mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_p_over_m_tau,quantity<dimensionless>,0.528012*dimensionless(),8.6e-5*dimensionless());\n/// proton-neutron mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(m_p_over_m_n,quantity<dimensionless>,0.99862347824*dimensionless(),4.6e-10*dimensionless());\n/// proton charge to mass ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(e_over_m_p,quantity<electric_charge_over_mass>,9.57883392e7*coulombs/kilogram,2.4e0*coulombs/kilogram);\n/// proton molar mass\nBOOST_UNITS_PHYSICAL_CONSTANT(M_p,quantity<mass_over_amount>,1.00727646677e-3*kilograms/mole,1.0e-13*kilograms/mole);\n/// proton Compton wavelength\nBOOST_UNITS_PHYSICAL_CONSTANT(lambda_C_p,quantity<length>,1.3214098446e-15*meters,1.9e-24*meters);\n/// proton rms charge radius\nBOOST_UNITS_PHYSICAL_CONSTANT(R_p,quantity<length>,0.8768e-15*meters,6.9e-18*meters);\n/// proton magnetic moment\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_p,quantity<energy_over_magnetic_flux_density>,1.410606662e-26*joules/tesla,3.7e-34*joules/tesla);\n/// proton-Bohr magneton ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_p_over_mu_B,quantity<dimensionless>,1.521032209e-3*dimensionless(),1.2e-11*dimensionless());\n/// proton-nuclear magneton ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_p_over_mu_N,quantity<dimensionless>,2.792847356*dimensionless(),2.3e-8*dimensionless());\n/// proton g-factor\nBOOST_UNITS_PHYSICAL_CONSTANT(g_p,quantity<dimensionless>,5.585694713*dimensionless(),4.6e-8*dimensionless());\n/// proton-neutron magnetic moment ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_p_over_mu_n,quantity<dimensionless>,-1.45989806*dimensionless(),3.4e-7*dimensionless());\n/// shielded proton magnetic moment\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_p_prime,quantity<energy_over_magnetic_flux_density>,1.410570419e-26*joules/tesla,3.8e-34*joules/tesla);\n/// shielded proton-Bohr magneton ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_p_prime_over_mu_B,quantity<dimensionless>,1.520993128e-3*dimensionless(),1.7e-11*dimensionless());\n/// shielded proton-nuclear magneton ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(mu_p_prime_over_mu_N,quantity<dimensionless>,2.792775598*dimensionless(),3.0e-8*dimensionless());\n/// proton magnetic shielding correction\nBOOST_UNITS_PHYSICAL_CONSTANT(sigma_p_prime,quantity<dimensionless>,25.694e-6*dimensionless(),1.4e-8*dimensionless());\n/// proton gyromagnetic ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(gamma_p,quantity<frequency_over_magnetic_flux_density>,2.675222099e8/second/tesla,7.0e0/second/tesla);\n/// shielded proton gyromagnetic ratio\nBOOST_UNITS_PHYSICAL_CONSTANT(gamma_p_prime,quantity<frequency_over_magnetic_flux_density>,2.675153362e8/second/tesla,7.3e0/second/tesla);\n\n} // namespace codata\n\n} // namespace constants    \n\n} // namespace si\n\n} // namespace units\n\n} // namespace boost\n\n#endif // BOOST_UNITS_CODATA_PROTON_CONSTANTS_HPP\n", "meta": {"hexsha": "78cce8c16bc106b3a6e9ddf4bea3c94022c17711", "size": 4676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/units/systems/si/codata/proton_constants.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/units/systems/si/codata/proton_constants.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/units/systems/si/codata/proton_constants.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": 47.2323232323, "max_line_length": 138, "alphanum_fraction": 0.8085970915, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.041462272119190506, "lm_q1q2_score": 0.014751235448038167}}
{"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 \"SiconosMatrix.hpp\"\n#include <assert.h>                                   // for assert\n#include <math.h>                                     // for fabs\n#include <float.h>                                     // for DBL_EPSILON\n#include <algorithm>                                  // for max, min, lower...\n#include <boost/numeric/ublas/detail/config.hpp>      // for noalias, noalia...\n#include <boost/numeric/ublas/detail/iterator.hpp>    // for bidirectional_i...\n#include <boost/numeric/ublas/matrix_expression.hpp>  // for matrix_vector_b...\n#include <boost/numeric/ublas/matrix_proxy.hpp>       // for matrix_range\n#include <boost/numeric/ublas/matrix_sparse.hpp>      // for compressed_matr...\n#include <boost/numeric/ublas/storage.hpp>            // for unbounded_array\n#include <boost/numeric/ublas/vector.hpp>             // for vector\n#include <memory>                                     // for __shared_ptr_ac...\n#include <utility>                                    // for swap\n#include <vector>                                     // for vector, operator==\n#include \"SiconosAlgebra.hpp\"\n#include \"BlockMatrix.hpp\"                            // for BlockMatrix\n#include \"SiconosVector.hpp\"                          // for SiconosVector\n#include \"SimpleMatrixFriends.hpp\"                    // for isComparableTo\n\n#include \"CSparseMatrix_internal.h\"                   // for CSparseMatrix\n#include \"NumericsSparseMatrix.h\"                     // for NSM_fix_csc\n#include \"SiconosException.hpp\"\n\n// Constructor with the type-number\nSiconosMatrix::SiconosMatrix(Siconos::UBLAS_TYPE type): _num(type), _isSymmetric(false), _isPositiveDefinite(false)\n{}\n\nconst SP::Index SiconosMatrix::tabRow() const\n{\n  THROW_EXCEPTION(\"not implemented for this type of matrix (Simple?) reserved to BlockMatrix.\");\n}\n\nconst SP::Index SiconosMatrix::tabCol() const\n{\n  THROW_EXCEPTION(\"not implemented for this type of matrix (Simple?) reserved to BlockMatrix.\");\n}\n\n\n\n//=====================\n// matrices comparison\n//=====================\nSiconosMatrix& operator *=(SiconosMatrix& m, const double& s)\n{\n  if(m._num == Siconos::BLOCK)  // BlockMatrix\n  {\n    BlockMatrix& mB = static_cast<BlockMatrix&>(m);\n    BlocksMat::iterator1 it;\n    BlocksMat::iterator2 it2;\n    for(it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for(it2 = it.begin(); it2 != it.end(); ++it2)\n        (**it2) *= s;\n    }\n  }\n  else if(m._num == Siconos::DENSE)\n    *m.dense() *= s;\n  else if(m._num == Siconos::TRIANGULAR)\n    *m.triang() *= s;\n  else if(m._num == Siconos::SYMMETRIC)\n    *m.sym() *= s;\n  else if(m._num == Siconos::SPARSE)\n    *m.sparse() *= s;\n  else if(m._num == Siconos::SPARSE_COORDINATE)\n    *m.sparseCoordinate() *= s;\n  else if(m._num == Siconos::BANDED)\n    *m.banded() *= s;\n  else if(m._num == Siconos::ZERO) {}  // nothing!\n  else //if(_num == 7)\n    THROW_EXCEPTION(\"invalid type of matrix\");\n\n  return m;\n}\n\nSiconosMatrix& operator /=(SiconosMatrix& m, const double& s)\n{\n  if(m._num == Siconos::BLOCK)  // BlockMatrix\n  {\n    BlockMatrix& mB = static_cast<BlockMatrix&>(m);\n    BlocksMat::iterator1 it;\n    BlocksMat::iterator2 it2;\n    for(it = mB._mat->begin1(); it != mB._mat->end1(); ++it)\n    {\n      for(it2 = it.begin(); it2 != it.end(); ++it2)\n        (**it2) /= s;\n    }\n  }\n  else if(m._num == Siconos::DENSE)\n    *m.dense() /= s;\n  else if(m._num == Siconos::TRIANGULAR)\n    *m.triang() /= s;\n  else if(m._num == Siconos::SYMMETRIC)\n    *m.sym() /= s;\n  else if(m._num == Siconos::SPARSE)\n    *m.sparse() /= s;\n  else if(m._num == Siconos::SPARSE_COORDINATE)\n    *m.sparseCoordinate() /= s;\n  else if(m._num == Siconos::BANDED)\n    *m.banded() /= s;\n  else if(m._num == Siconos::ZERO) {}  // nothing!\n  else //if(_num == 7)\n    THROW_EXCEPTION(\"invalid type of matrix\");\n\n  return m;\n}\n\nsize_t SiconosMatrix::nnz(double tol)\n{\n  size_t nnz = 0;\n  if(_num == Siconos::DENSE)  //dense\n  {\n    double* arr = getArray();\n    for(size_t i = 0; i < size(0)*size(1); ++i)\n    {\n      if(fabs(arr[i]) > tol)\n      {\n        nnz++;\n      }\n    }\n  }\n  else if(_num == Siconos::SPARSE)\n  {\n    nnz = sparse()->nnz();\n  }\n  else\n    THROW_EXCEPTION(\"not implemented for the given matrix type\");\n\n  return nnz;\n\n}\n\nbool SiconosMatrix::fillCSC(CSparseMatrix* csc, size_t row_off, size_t col_off, double tol)\n{\n  assert(csc);\n  double* Mx = csc->x; // data\n  CS_INT* Mi = csc->i; // row indx\n  CS_INT* Mp = csc->p; // column pointers\n\n  assert(Mp[col_off] >= 0);\n  size_t nz = csc->p[col_off];\n\n  size_t nrow = size(0);\n  size_t ncol = size(1);\n\n  CS_INT pval = Mp[col_off];\n\n  if(_num == Siconos::DENSE)  //dense\n  {\n    double* arr = getArray();\n    for(size_t j = 0, joff = col_off; j < ncol; ++j)\n    {\n      for(size_t i = 0; i < nrow; ++i)\n      {\n        // col-major\n        double elt_val = arr[i + j*nrow];\n        // std::cout << \" a(i=\" << i << \",j=\" << j << \") = \"<< elt_val << std::endl;\n        if(fabs(elt_val) > tol)\n        {\n          Mx[pval] = elt_val;\n          Mi[pval] = i + row_off;\n          // std::cout << \"Mx[\" <<pval <<\"] = \" << Mx[pval]<<   std::endl;\n          // std::cout << \"Mp[\" <<pval <<\"] = \" << Mi[pval]<<   std::endl;\n          ++pval;\n        }\n      }\n      // std::cout << \"joff\" << joff << std::endl;\n      Mp[++joff] = pval;\n\n    }\n  }\n  else if(_num == Siconos::SPARSE)\n  {\n    const Index& ptr = sparse()->index1_data();\n    const Index& indx = sparse()->index2_data();\n    const ublas::unbounded_array<double>& vals = sparse()->value_data();\n\n    size_t nnz =  sparse()->nnz();\n\n    assert(ptr.size() == ncol + 1);\n    assert(indx.size() == nnz);\n    assert(vals.size() == nnz);\n\n    for(size_t i = 0; i < nnz; ++i)\n    {\n      Mx[pval] = vals[i];\n      Mi[pval++] = row_off + indx[i];\n    }\n    for(size_t j = 1, joff = col_off + 1; j < ncol+1; ++j, ++joff)\n    {\n      Mp[joff] = nz + ptr[j];\n    }\n  }\n  else\n  {\n    THROW_EXCEPTION(\"not implemented for the given matrix type\");\n  }\n\n  return true;\n}\n\nbool SiconosMatrix::fillCSC(CSparseMatrix* csc, double tol)\n{\n  assert(csc);\n  double* Mx = csc->x; // data\n  CS_INT* Mi = csc->i; // row indx\n  CS_INT* Mp = csc->p; // column pointers\n\n  size_t nrow = size(0);\n  size_t ncol = size(1);\n\n  CS_INT pval = 0;\n\n  if(_num == Siconos::DENSE)  //dense\n  {\n    double* arr = getArray();\n    for(size_t j = 0, joff = 0; j < ncol; ++j)\n    {\n      for(size_t i = 0; i < nrow; ++i)\n      {\n        // col-major\n        double elt_val = arr[i + j*nrow];\n        // std::cout << \" a(i=\" << i << \",j=\" << j << \") = \"<< elt_val << std::endl;\n        if(fabs(elt_val) > tol)\n        {\n          Mx[pval] = elt_val;\n          Mi[pval] = i;\n          // std::cout << \"Mx[\" <<pval <<\"] = \" << Mx[pval]<<   std::endl;\n          // std::cout << \"Mp[\" <<pval <<\"] = \" << Mi[pval]<<   std::endl;\n          ++pval;\n        }\n      }\n      // std::cout << \"joff\" << joff << std::endl;\n      Mp[++joff] = pval;\n\n    }\n  }\n  else if(_num == Siconos::SPARSE)\n  {\n    const Index& ptr = sparse()->index1_data();\n    const Index& indx = sparse()->index2_data();\n    const ublas::unbounded_array<double>& vals = sparse()->value_data();\n\n    size_t nnz =  sparse()->nnz();\n\n    assert(ptr.size() == ncol + 1);\n    assert(indx.size() >= nnz);\n    assert(vals.size() >= nnz);\n\n    for(size_t i = 0; i < nnz; ++i)\n    {\n      Mx[pval] = vals[i];\n      Mi[pval++] = indx[i];\n    }\n    for(size_t j = 0; j < ncol+1; ++j)\n    {\n      Mp[j] = ptr[j];\n    }\n  }\n  else\n  {\n    THROW_EXCEPTION(\"not implemented for the given matrix type\");\n  }\n\n  return true;\n}\n\nbool SiconosMatrix::fromCSC(CSparseMatrix* csc)\n{\n  assert(csc);\n\n  NSM_sort_csc(csc);\n\n  double* Mx = csc->x; // data\n  CS_INT* Mi = csc->i; // row indx\n  CS_INT* Mp = csc->p; // column pointers\n  CS_INT n = csc->n;\n  // CS_INT m = csc->m;\n\n  // size_t nnz = csc->p[n];\n\n  if(_num == Siconos::SPARSE)\n  {\n    sparse()->clear();\n    CS_INT pval=0;\n    // push_back in order should be in constant time\n    // http://www.guwi17.de/ublas/matrix_sparse_usage.html\n    for (CS_INT col =0; col < n; col++)\n    {\n      for (CS_INT p = Mp[col]; p < Mp[col+1];  p++)\n      {\n        sparse()->push_back(Mi[pval], col, Mx[pval]);\n        pval++;\n      }\n    }\n\n    // not able to work directly on the contents of the sparse matrix.\n    // sparse()->resize(m, nnz, false);\n    // //sparse()->set_filled(nnz, n+1);\n    // std::cout << sparse()->size1() << std::endl;\n    // std::cout << sparse()->size2() << std::endl;\n\n    // Index& ptr = sparse()->index1_data();\n    // Index& indx = sparse()->index2_data();\n    // ublas::unbounded_array<double>& vals = sparse()->value_data();\n\n    // // ptr.resize(n+1);\n    // // indx.resize(nnz);\n    // // vals.resize(nnz);\n\n    // std::cout << sparse()->filled1() << std::endl;\n    // std::cout << sparse()->filled2() << std::endl;\n\n    // // CS_INT pval=0;\n\n    // // for(size_t i = 0; i < nnz; ++i)\n    // // {\n    // //   vals[i] = Mx[pval];\n    // //   indx[i] = Mi[pval++];\n    // // }\n    // for(size_t i = 0; i < nnz; ++i)\n    // {\n    //   printf(\"vals[%i] = %e\\t\", i, vals[i]);\n    //   printf(\"indx[%i] = %i\\t\", i, indx[i]);\n    // }\n\n    // // for(size_t j = 0 ; j < n+1; ++j)\n    // // {\n    // //   ptr[j] = Mp[j]  ;\n    // // }\n    // for(size_t j = 0 ; j < n+1; ++j) printf(\"ptr[%i] = %i\\t\", j, ptr[j]);\n  }\n  else if(_num == Siconos::DENSE)\n  {\n    CS_INT pval=0;\n    // push_back in order should be in constant time\n    // http://www.guwi17.de/ublas/matrix_sparse_usage.html\n    for (CS_INT col =0; col < n; col++)\n    {\n      for (CS_INT p = Mp[col]; p < Mp[col+1];  p++)\n      {\n        setValue(Mi[pval], col, Mx[pval]);\n        pval++;\n      }\n    }\n  }\n  else\n  {\n    THROW_EXCEPTION(\"not implemented for the given matrix type\");\n  }\n  return true;\n}\n\n\nbool SiconosMatrix::fillTriplet(CSparseMatrix* triplet, size_t row_off, size_t col_off, double tol)\n{\n  assert(triplet);\n  size_t nrow = size(0);\n  size_t ncol = size(1);\n\n  if(_num == Siconos::DENSE)  //dense\n  {\n    double* arr = getArray();\n    for(size_t j = 0; j < ncol; ++j)\n    {\n      for(size_t i = 0; i < nrow; ++i)\n      {\n        // col-major\n\n        CSparseMatrix_zentry(triplet, i + row_off, j + col_off, arr[i + j*nrow], DBL_EPSILON);\n      }\n    }\n  }\n  else\n  {\n    THROW_EXCEPTION(\"not implemented for the given matrix type\");\n  }\n\n  return true;\n}\n\n\nstd::ostream& operator<<(std::ostream& os, const SiconosMatrix& sm)\n{\n  os << sm.toString();\n  return os;\n}\n\n\nvoid SiconosMatrix::private_prod(unsigned int startRow, const SiconosVector& x, SiconosVector& y, bool init) const\n{\n  assert(!(isFactorized()) && \"A is Factorized in prod !!\");\n\n  // Computes y = subA *x (or += if init = false), subA being a sub-matrix of A, between el. of index (row) startRow and startRow + sizeY\n\n  if(init)  // y = subA * x , else y += subA * x\n    y.zero();\n  private_addprod(startRow, 0, x, y);\n}\n\n/** Computation of y = subA.x\n\n    where subA is a sub-matrix of A, subA[0,0] = A[startRow, startCol]\n */\nvoid SiconosMatrix::private_addprod(unsigned startRow, unsigned int startCol, const SiconosVector& x, SiconosVector& y) const\n{\n  assert(!(isFactorized()) && \"A is Factorized in prod !!\");\n  assert(!isBlock() && \"private_addprod(start,x,y) error: not yet implemented for block matrix.\");\n\n  // we take a submatrix subA of A, starting from row startRow to row (startRow+sizeY) and between columns startCol and (startCol+sizeX).\n  // Then computation of y = subA*x + y.\n  Siconos::UBLAS_TYPE numA = num();\n  Siconos::UBLAS_TYPE numY = y.num();\n  Siconos::UBLAS_TYPE numX = x.num();\n  unsigned int sizeX = x.size();\n  unsigned int sizeY = y.size();\n\n  assert(numX == numY && \"private_addprod(A,start,x,y) error: not yet implemented for x and y of different types.\");\n\n  if(numY == Siconos::DENSE && numX == Siconos::DENSE)\n  {\n\n    assert(y.dense() != x.dense());\n\n    if(numA == Siconos::DENSE)\n      noalias(*y.dense()) += prod(ublas::subrange(*dense(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else if(numA == Siconos::TRIANGULAR)\n      noalias(*y.dense()) += prod(ublas::subrange(*triang(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else if(numA == Siconos::SYMMETRIC)\n      noalias(*y.dense()) += prod(ublas::subrange(*sym(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else if(numA == Siconos::SPARSE)\n      noalias(*y.dense()) += prod(ublas::subrange(*sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n    else //if(numA==Siconos::BANDED)\n      noalias(*y.dense()) += prod(ublas::subrange(*banded(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.dense());\n  }\n  else // x and y sparse\n  {\n    if(numA == Siconos::SPARSE)\n      *y.sparse() += prod(ublas::subrange(*sparse(), startRow, startRow + sizeY, startCol, startCol + sizeX), *x.sparse());\n    else\n      THROW_EXCEPTION(\"not yet implemented for x, y  sparse and A not sparse.\");\n  }\n}\n", "meta": {"hexsha": "040e577b82cd8227833fbcb241b62a81279a2cc9", "size": 13638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosMatrix.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/SiconosMatrix.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/SiconosMatrix.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": 29.5194805195, "max_line_length": 137, "alphanum_fraction": 0.5656987828, "num_tokens": 4225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.03904829062943617, "lm_q1q2_score": 0.014742317759661686}}
{"text": "//=======================================================================\n// Copyright 2014-2015 David Simmons-Duffin.\n// Distributed under the MIT License.\n// (See accompanying file LICENSE or copy at\n//  http://opensource.org/licenses/MIT)\n//=======================================================================\n\n\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include \"omp.h\"\n//Tweak to allow Ubuntu-14.04/gcc-4.8.4 and similar environments to compile\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n#include <boost/filesystem.hpp>\n#undef BOOST_NO_CXX11_SCOPED_ENUMS\n#include \"SDPSolver.h\"\n#include \"Timers.h\"\n\nusing boost::filesystem::path;\nusing boost::timer::nanosecond_type;\nusing std::cout;\n\n// A note on function conventions: For functions which return large\n// objects, we usually use references to the returned objects as\n// arguments to a void function, which are then modified in place:\n//\n// void myFunction(const InputType1 &input1,\n//                 const InputType2 &input2,\n//                 ...\n//                 OutputType1 &output1,\n//                 OutputType2 &output2,\n//                 ...) {\n//   use input1, etc. to modify output1, etc.\n// }\n//\n// We try to mark large inputs as `const' references.  However,\n// several MBLAS and MLAPACK functions are not correctly annotated\n// with `const's, so we occasionally have input arguments which cannot\n// be marked as const because they're used in MBLAS/MLAPACK functions.\n// We try to use comments to distinguish which arguments should be\n// considered inputs and which should be considered outputs.\n\n/***********************************************************************/\n// Create and initialize an SDPSolver for the given SDP and\n// SDPSolverParameters\n\nSDPSolver::SDPSolver(const SDP &sdp, const SDPSolverParameters &parameters):\n  sdp(sdp),\n  parameters(parameters),\n  x(sdp.primalObjective.size(), 0),\n  X(sdp.psdMatrixBlockDims()),\n  y(sdp.dualObjective.size(), 0),\n  Y(X),\n  dx(x),\n  dX(X),\n  dy(y),\n  dY(Y),\n  PrimalResidues(X),\n  dualResidues(x),\n  XCholesky(X),\n  YCholesky(X),\n  Z(X),\n  R(X),\n  BilinearPairingsXInv(sdp.bilinearPairingBlockDims()),\n  BilinearPairingsY(BilinearPairingsXInv),\n  SchurComplement(sdp.schurBlockDims()),\n  SchurComplementCholesky(SchurComplement),\n  SchurOffDiagonal(sdp.FreeVarMatrix),\n  schurStabilizeIndices(SchurComplement.blocks.size()),\n  schurStabilizeLambdas(SchurComplement.blocks.size()),\n  stabilizeBlocks(SchurComplement.blocks.size()),\n  Q(sdp.FreeVarMatrix.cols, sdp.FreeVarMatrix.cols),\n  Qpivots(sdp.FreeVarMatrix.cols),\n  dyExtended(Q.rows),\n  StepMatrixWorkspace(X)\n{\n  // initialize bilinearPairingsWorkspace, eigenvaluesWorkspace, QRWorkspace\n  for (unsigned int b = 0; b < sdp.bilinearBases.size(); b++) {\n    bilinearPairingsWorkspace.push_back(Matrix(X.blocks[b].rows,\n                                               BilinearPairingsXInv.blocks[b].cols));\n    eigenvaluesWorkspace.push_back(Vector(X.blocks[b].rows));\n    QRWorkspace.push_back(Vector(3*X.blocks[b].rows - 1));\n  }\n\n  // X = \\Omega_p I\n  X.addDiagonal(parameters.initialMatrixScalePrimal);\n  // Y = \\Omega_d I\n  Y.addDiagonal(parameters.initialMatrixScaleDual);\n}\n\n/***********************************************************************/\n// Specialized linear algebra helper functions needed for the solver.\n\n\n// Result = Q'^T A Q', where Q' = Q \\otimes 1, where \\otimes denotes\n// tensor product and 1 is an mxm identity matrix.\n// Inputs:\n// - A      : l*m x l*m symmetric matrix\n// - Q      : l   x n   matrix\n// Workspace:\n// - Work   : l*m x n*m matrix, intermediate workspace (overwritten)\n// Output:\n// - Result : n*m x n*m symmetric matrix (overwritten)\n//\n// An explanation of the name: a 'congruence' refers to the action M\n// -> A M A^T.  We use 'transpose congruence' to refer to a congruence\n// with the transposed matrix M -> A^T M A.  'tensor' here refers to\n// the fact that we're performing a congruence with the tensor product\n// Q \\otimes 1.\n//\nvoid tensorTransposeCongruence(const Matrix &A,\n                               const Matrix &Q,\n                               Matrix &Work,\n                               Matrix &Result) {\n  int m = A.rows / Q.rows;\n\n  assert(Result.rows == Q.cols * m);\n  assert(Result.cols == Q.cols * m);\n\n  assert(Work.rows == A.rows);\n  assert(Work.cols == Result.cols);\n\n  // Work = A Q'\n  for (int c = 0; c < Work.cols; c++) {\n    int qCol       = c % Q.cols;\n    int aColOffset = (c / Q.cols) * Q.rows;\n\n    for (int r = 0; r < Work.rows; r++) {\n      Real tmp = 0;\n      for (int k = 0; k < Q.rows; k++) {\n        tmp += A.elt(r, aColOffset + k) * Q.elt(k, qCol);\n      }\n\n      Work.elt(r, c) = tmp;\n    }\n  }\n\n  // Result = Q'^T Work\n  for (int c = 0; c < Result.cols; c++) {\n    // since Result is symmetric, only compute its upper triangle\n    for (int r = 0; r <= c; r++) {\n      int qCol          = r % Q.cols;\n      int workRowOffset = (r / Q.cols) * Q.rows;\n\n      Real tmp = 0;\n      for (int k = 0; k < Q.rows; k++) {\n        tmp += Q.elt(k, qCol) * Work.elt(workRowOffset + k, c);\n      }\n\n      Result.elt(r, c) = tmp;\n\n      // lower triangle is the same as upper triangle\n      if (c != r) {\n        Result.elt(c, r) = tmp;\n      }\n    }\n  }\n}\n\n// Result_b = Q[b]'^T A_b Q[b]' for each block 0 <= b < Q.size()\n// - Result_b, A_b denote the b-th blocks of Result, A, resp.\n// - Q[b]' = Q[b] \\otimes 1, where \\otimes denotes tensor product\n// - for each b, L.blocks[b], Q[b], Work[b], and Result.blocks[b] must\n//   have the structure described above for\n//   `tensorTransposeCongruence'\n//\nvoid blockTensorTransposeCongruence(const BlockDiagonalMatrix &A,\n                                    const vector<Matrix> &Q,\n                                    vector<Matrix> &Work,\n                                    BlockDiagonalMatrix &Result) {\n  #pragma omp parallel for schedule(dynamic)\n  for (unsigned int b = 0; b < Q.size(); b++)\n    tensorTransposeCongruence(A.blocks[b], Q[b], Work[b], Result.blocks[b]);\n}\n\n// Result = Q'^T A^{-1} Q', where Q' = Q \\otimes 1, where \\otimes\n// denotes tensor product and 1 is an mxm idenity matrix.\n// Inputs:\n// - L      : l*m x l*m cholesky decomposition of A\n// - Q      : l   x n   matrix\n// Workspace:\n// - Work   : l*m x n*m matrix, intermediate workspace (overwritten)\n// Output:\n// - Result : n*m x n*m symmetric matrix (overwritten)\n//\nvoid tensorInvTransposeCongruenceWithCholesky(const Matrix &L,\n                                              const Matrix &Q,\n                                              Matrix &Work,\n                                              Matrix &Result) {\n  // Work = L^{-1} (Q \\otimes 1);\n  for (int cw = 0; cw < Work.cols; cw++) {\n    int mc  = cw / Q.cols;\n\n    for (int rw = mc*Q.rows; rw < Work.rows; rw++) {\n      int mr = rw / Q.rows;\n\n      Real tmp = (mr != mc) ? Real(0) : Q.elt(rw % Q.rows, cw % Q.cols);\n      for (int cl = mc*Q.rows; cl < rw; cl++)\n        tmp -= L.elt(rw, cl)*Work.elt(cl, cw);\n\n      Work.elt(rw, cw) = tmp/L.elt(rw, rw);\n    }\n  }\n\n  // Result = Work^T Work\n  for (int cr = 0; cr < Result.cols; cr++) {\n    int mc = cr / Q.cols;\n\n    for (int rr = 0; rr <= cr; rr++) {\n      int mr = rr / Q.cols;\n\n      Real tmp = 0;\n      for (int rw = max(mr, mc)*Q.rows; rw < Work.rows; rw++)\n        tmp += Work.elt(rw, cr)*Work.elt(rw, rr);\n\n      Result.elt(rr, cr) = tmp;\n      if (rr != cr)\n        Result.elt(cr, rr) = tmp;\n    }\n  }\n}\n\n// Result_b = Q[b]'^T A_b^{-1} Q[b]' for each block 0 <= b < Q.size()\n// - Result_b, A_b denote the b-th blocks of Result, A, resp.\n// - Q[b]' = Q[b] \\otimes 1, where \\otimes denotes tensor product\n// - for each b, L.blocks[b], Q[b], Work[b], and Result.blocks[b] must\n//   have the structure described above for\n//   `tensorInvTransposeCongruenceWithCholesky'\n// \nvoid blockTensorInvTransposeCongruenceWithCholesky(const BlockDiagonalMatrix &L,\n                                                   const vector<Matrix> &Q,\n                                                   vector<Matrix> &Work,\n                                                   BlockDiagonalMatrix &Result) {\n  #pragma omp parallel for schedule(dynamic)\n  for (unsigned int b = 0; b < Q.size(); b++)\n    tensorInvTransposeCongruenceWithCholesky(L.blocks[b], Q[b],\n                                             Work[b], Result.blocks[b]);\n}\n\n// Result^(blockRow,blockCol) = V D V^T, where D=diag(d) is a diagonal\n// matrix.\n//\n// Here, we view Result as a matrix on the tensor product\n// R^V.rows \\otimes R^k.  Result^(blockRow,blockCol) refers to the\n// block submatrix of size V.rows x V.rows at position (blockRow,\n// blockCol) in the second tensor factor.\n//\n// Inputs:\n// - d        : pointer to beginning of a length-V.cols vector\n// - V        : V.rows x V.cols Matrix\n// - blockRow : integer < k\n// - blockCol : integer < k\n// Output:\n// - Result   : (k*V.rows) x (k*V.rows) square Matrix (overwritten)\n//\nvoid diagonalCongruence(Real const *d,\n                        const Matrix &V,\n                        const int blockRow,\n                        const int blockCol,\n                        Matrix &Result) {\n  for (int p = 0; p < V.rows; p++) {\n    for (int q = 0; q <= p; q++) {\n      Real tmp = 0;\n\n      for (int n = 0; n < V.cols; n++)\n        tmp += *(d+n) * V.elt(p, n)*V.elt(q, n);\n\n      Result.elt(blockRow*V.rows + p, blockCol*V.rows + q) = tmp;\n      if (p != q)\n        Result.elt(blockRow*V.rows + q, blockCol*V.rows + p) = tmp;\n    }\n  }\n}\n\n// v^T A^(blockRow, blockCol) v, where A^(r,s) is the (r,s)-th dim x\n// dim block inside A.\n//\n// Input:\n// - v        : pointer to the beginning of a vector of length dim\n// - dim      : length of the vector v\n// - A        : (k*dim) x (k*dim) matrix, where k > blockRow, blockCol\n// - blockRow : integer labeling block of A\n// - blockCol : integer labeling block of A\n// Output: v^T A^(blockRow, blockCol) v (returned)\n//\nReal bilinearBlockPairing(const Real *v,\n                          const int dim,\n                          const Matrix &A,\n                          const int blockRow,\n                          const int blockCol) {\n  Real result = 0;\n\n  for (int r = 0; r < dim; r++) {\n    Real tmp = 0;\n\n    for (int c = 0; c < dim; c++)\n      tmp += *(v+c) * A.elt(blockRow*dim + r, blockCol*dim + c);\n    result += *(v+r) * tmp;\n  }\n  return result;\n}\n\n/***********************************************************************/\n// Subroutines needed for each solver iteration\n\n// Compute the SchurComplement matrix using BilinearPairingsXInv and\n// BilinearPairingsY and the formula\n//\n//   S_{(j,r1,s1,k1), (j,r2,s2,k2)} = \\sum_{b \\in blocks[j]}\n//          (1/4) (BilinearPairingsXInv_{ej s1 + k1, ej r2 + k2}*\n//                 BilinearPairingsY_{ej s2 + k2, ej r1 + k1} +\n//                 swaps (r1 <-> s1) and (r2 <-> s2))\n// \n// where ej = d_j + 1.\n//\n// Inputs: sdp, BilinearPairingsXInv, BilinearPairingsY\n// Output: SchurComplement (overwritten) \n//\nvoid computeSchurComplement(const SDP &sdp,\n                            const BlockDiagonalMatrix &BilinearPairingsXInv,\n                            const BlockDiagonalMatrix &BilinearPairingsY,\n                            BlockDiagonalMatrix &SchurComplement) {\n  #pragma omp parallel for schedule(dynamic)\n  for (unsigned int j = 0; j < sdp.dimensions.size(); j++) {\n    const int ej = sdp.degrees[j] + 1;\n\n    for (unsigned int u1 = 0; u1 < sdp.constraintIndices[j].size(); u1++) {\n      const int ej_r1 = sdp.constraintIndices[j][u1].r * ej;\n      const int ej_s1 = sdp.constraintIndices[j][u1].s * ej;\n      const int k1    = sdp.constraintIndices[j][u1].k;\n\n      for (unsigned int u2 = 0; u2 <= u1; u2++) {\n        const int ej_r2 = sdp.constraintIndices[j][u2].r * ej;\n        const int ej_s2 = sdp.constraintIndices[j][u2].s * ej;\n        const int k2    = sdp.constraintIndices[j][u2].k;\n\n        Real tmp = 0;\n        for (vector<int>::const_iterator b = sdp.blocks[j].begin();\n             b != sdp.blocks[j].end(); b++) {\n          tmp += (BilinearPairingsXInv.blocks[*b].elt(ej_s1 + k1, ej_r2 + k2) *\n                  BilinearPairingsY   .blocks[*b].elt(ej_s2 + k2, ej_r1 + k1) +\n                  BilinearPairingsXInv.blocks[*b].elt(ej_r1 + k1, ej_r2 + k2) *\n                  BilinearPairingsY   .blocks[*b].elt(ej_s2 + k2, ej_s1 + k1) +\n                  BilinearPairingsXInv.blocks[*b].elt(ej_s1 + k1, ej_s2 + k2) *\n                  BilinearPairingsY   .blocks[*b].elt(ej_r2 + k2, ej_r1 + k1) +\n                  BilinearPairingsXInv.blocks[*b].elt(ej_r1 + k1, ej_s2 + k2) *\n                  BilinearPairingsY   .blocks[*b].elt(ej_r2 + k2, ej_s1 + k1))/4;\n        }\n        SchurComplement.blocks[j].elt(u1, u2) = tmp;\n        if (u2 != u1)\n          SchurComplement.blocks[j].elt(u2, u1) = tmp;\n      }\n    }\n  }\n}\n\n// dualResidues[p] = primalObjective[p] - Tr(A_p Y) - (FreeVarMatrix y)_p,\n// for 0 <= p < primalObjective.size()\n//\n// The pairings Tr(A_p Y) can be written in terms of BilinearPairingsY:\n//\n//   Tr(A_(j,r,s,k) Y) = \\sum_{b \\in blocks[j]}\n//                       (1/2) (BilinearPairingsY_{ej r + k, ej s + k} +\n//                              swap (r <-> s))\n// where ej = d_j + 1.\n//\n// Inputs: sdp, y, BilinearPairingsY\n// Output: dualResidues (overwriten)\n//\nvoid computeDualResidues(const SDP &sdp,\n                         const Vector &y,\n                         const BlockDiagonalMatrix &BilinearPairingsY,\n                         Vector &dualResidues) {\n  #pragma omp parallel for schedule(dynamic)\n  for (unsigned int j = 0; j < sdp.dimensions.size(); j++) {\n    const int ej = sdp.degrees[j] + 1;\n\n    for (vector<IndexTuple>::const_iterator t = sdp.constraintIndices[j].begin();\n         t != sdp.constraintIndices[j].end();\n         t++) {\n      const int p    = t->p;\n      const int ej_r = t->r * ej;\n      const int ej_s = t->s * ej;\n      const int k    = t->k;\n\n      // dualResidues[p] = -Tr(A_p Y)\n      dualResidues[p] = 0;\n      for (vector<int>::const_iterator b = sdp.blocks[j].begin();\n           b != sdp.blocks[j].end(); b++) {\n        dualResidues[p] -= BilinearPairingsY.blocks[*b].elt(ej_r+k, ej_s+k);\n        dualResidues[p] -= BilinearPairingsY.blocks[*b].elt(ej_s+k, ej_r+k);\n      }\n      dualResidues[p] /= 2;\n\n      // dualResidues[p] = -Tr(A_p Y) - (FreeVarMatrix y)_p\n      for (int n = 0; n < sdp.FreeVarMatrix.cols; n++)\n        dualResidues[p] -= sdp.FreeVarMatrix.elt(p, n)*y[n];\n\n      // dualResidues[p] = primalObjective[p] - Tr(A_p Y) - (FreeVarMatrix y)_p\n      dualResidues[p] += sdp.primalObjective[p];\n    }\n  }\n}\n\n// Result = \\sum_p a[p] A_p,\n//\n// where a[p] is a vector of length primalObjective.size() and the\n// constraint matrices A_p are given by\n//\n//   A_(j,r,s,k) = \\sum_{b \\in blocks[j]}\n//                     Block_b(v_{b,k} v_{b,k}^T \\otimes E^{rs}),\n//\n// where v_{b,k} is the k-th column of bilinearBases[b], as described\n// in SDP.h.\n//\n// Inputs: sdp, a\n// Output: Result (overwritten)\n//\nvoid constraintMatrixWeightedSum(const SDP &sdp,\n                                 const Vector a,\n                                 BlockDiagonalMatrix &Result)  {\n  #pragma omp parallel for schedule(dynamic)\n  for (unsigned int j = 0; j < sdp.dimensions.size(); j++) {\n    const int ej = sdp.degrees[j] + 1;\n\n    // For each j, t points to the first IndexTuple corresponding to j\n    for (vector<IndexTuple>::const_iterator t = sdp.constraintIndices[j].begin();\n         t != sdp.constraintIndices[j].end();\n         t += ej) {\n      const int p = t->p;\n      const int r = t->r;\n      const int s = t->s;\n      assert(t->k == 0);\n\n      for (vector<int>::const_iterator b = sdp.blocks[j].begin();\n           b != sdp.blocks[j].end(); b++) {\n\n        // Result.blocks[b]^(r,s) = V diag(a') V^T, where\n        // V=sdp.bilinearBases[b], a' denotes the subvector of a\n        // corresponding to j, and M^(r,s) denotes the (r,s)-th block\n        // of M.\n        diagonalCongruence(&a[p], sdp.bilinearBases[*b], r, s, Result.blocks[*b]);\n\n        // Result should be symmetric, so if r != s, we must divide\n        // the (r,s)-th block of Result.blocks[b] by 2 and copy its\n        // transpose to the (s,r)-th block.\n        if (r != s) {\n          const int u = sdp.bilinearBases[*b].rows;\n          for (int m = r*u; m < (r+1)*u; m++) {\n            for (int n = s*u; n < (s+1)*u; n++) {\n              Result.blocks[*b].elt(m, n) /= 2;\n              Result.blocks[*b].elt(n, m) = Result.blocks[*b].elt(m, n);\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\n// Compute the vectors r_x and r_y on the right-hand side of the Schur\n// complement equation:\n//\n// {{S, -B}, {B^T, 0}} . {dx, dy} = {r_x, r_y}\n//\n// where S = SchurComplement and B = FreeVarMatrix.  Specifically,\n//\n// r_x[p] = -dualResidues[p] - Tr(A_p Z)              for 0 <= p < P\n// r_y[n] = dualObjective[n] - (FreeVarMatrix^T x)_n  for 0 <= n < N\n//\n// where P = primalObjective.size(), N = dualObjective.size()\n//\n// Inputs:\n// - sdp, an SDP\n// - dualResidues, a Vector of length P\n// - Z = X^{-1} (PrimalResidues Y - R)\n// - x, a vector of length P\n// Outputs:\n// - r_x, a Vector of length P\n// - r_y, a Vector of length N\n//\nvoid computeSchurRHS(const SDP &sdp,\n                     const Vector &dualResidues,\n                     const BlockDiagonalMatrix &Z,\n                     const Vector &x,\n                     Vector &r_x,\n                     Vector &r_y) {\n  // r_x[p] = -dualResidues[p]\n  for (unsigned int p = 0; p < r_x.size(); p++)\n    r_x[p] = -dualResidues[p];\n\n  // r_x[p] = -dualResidues[p] - Tr(A_p Z), where A_p are as described\n  // in SDP.h.  The trace can be computed in terms of bilinearBases\n  // using bilinearBlockPairing.\n  #pragma omp parallel for schedule(dynamic)\n  for (unsigned int j = 0; j < sdp.dimensions.size(); j++) {\n    for (vector<IndexTuple>::const_iterator t = sdp.constraintIndices[j].begin();\n         t != sdp.constraintIndices[j].end();\n         t++) {\n      for (vector<int>::const_iterator b = sdp.blocks[j].begin();\n           b != sdp.blocks[j].end(); b++) {\n        const int h = sdp.bilinearBases[*b].rows;\n        // Pointer to the k-th column of sdp.bilinearBases[*b]\n        const Real *q = &sdp.bilinearBases[*b].elements[(t->k) * h];\n\n        r_x[t->p] -= bilinearBlockPairing(q, h, Z.blocks[*b], t->r, t->s);\n      }\n    }\n  }\n\n  // r_y[n] = dualObjective[n] - (FreeVarMatrix^T x)_n\n  #pragma omp parallel for schedule(static)\n  for (unsigned int n = 0; n < sdp.dualObjective.size(); n++) {\n    r_y[n] = sdp.dualObjective[n];\n    for (int p = 0; p < sdp.FreeVarMatrix.rows; p++) {\n      r_y[n] -= sdp.FreeVarMatrix.elt(p, n)*x[p];\n    }\n  }\n}\n\n// PrimalResidues = \\sum_p A_p x[p] - X\n//\n// Inputs: sdp, x, X\n// Output: PrimalResidues (overwritten)\n//\nvoid computePrimalResidues(const SDP &sdp,\n                           const Vector x,\n                           const BlockDiagonalMatrix &X,\n                           BlockDiagonalMatrix &PrimalResidues) {\n  constraintMatrixWeightedSum(sdp, x, PrimalResidues);\n  PrimalResidues -= X;\n}\n\n// Centering parameter \\beta_p for the predictor step\nReal predictorCenteringParameter(const SDPSolverParameters &parameters,\n                                 const bool isPrimalDualFeasible) {\n  return isPrimalDualFeasible ? Real(0) : parameters.infeasibleCenteringParameter;\n}\n\n// Centering parameter \\beta_c for the corrector step\nReal correctorCenteringParameter(const SDPSolverParameters &parameters,\n                                 const BlockDiagonalMatrix &X,\n                                 const BlockDiagonalMatrix &dX,\n                                 const BlockDiagonalMatrix &Y,\n                                 const BlockDiagonalMatrix &dY,\n                                 const Real &mu,\n                                 const bool isPrimalDualFeasible) {\n  Real r = frobeniusProductOfSums(X, dX, Y, dY) / (mu * X.dim);\n  Real beta = r < 1 ? r*r : r;\n\n  if (isPrimalDualFeasible)\n    return min(max(parameters.feasibleCenteringParameter, beta), Real(1));\n  else\n    return max(parameters.infeasibleCenteringParameter, beta);\n}\n\n// min(gamma \\alpha(M, dM), 1), where \\alpha(M, dM) denotes the\n// largest positive real number such that M + \\alpha dM is positive\n// semidefinite.\n//\n// \\alpha(M, dM) is computed with a Cholesky decomposition M = L L^T.\n// The eigenvalues of M + \\alpha dM are equal to the eigenvalues of 1\n// + \\alpha L^{-1} dM L^{-T}.  The correct \\alpha is then -1/lambda,\n// where lambda is the smallest eigenvalue of L^{-1} dM L^{-T}.\n//\n// Inputs:\n// - MCholesky = L, the Cholesky decomposition of M (M itself is not needed)\n// - dM, a BlockDiagonalMatrix with the same structure as M\n// Workspace:\n// - MInvDM (NB: overwritten when computing minEigenvalue)\n// - eigenvalues, a Vector of eigenvalues for each block of M\n// - workspace, a vector of Vectors needed by the minEigenvalue function\n// Output:\n// - min(\\gamma \\alpha(M, dM), 1) (returned)\n//\nReal stepLength(BlockDiagonalMatrix &MCholesky,\n                BlockDiagonalMatrix &dM,\n                BlockDiagonalMatrix &MInvDM,\n                vector<Vector> &eigenvalues,\n                vector<Vector> &workspace,\n                const Real gamma) {\n  // MInvDM = L^{-1} dM L^{-T}, where M = L L^T\n  MInvDM.copyFrom(dM);\n  lowerTriangularInverseCongruence(MInvDM, MCholesky);\n\n  const Real lambda = minEigenvalue(MInvDM, workspace, eigenvalues);\n  if (lambda > -gamma)\n    return 1;\n  else\n    return -gamma/lambda;\n}\n\n// Compute the quantities needed to solve the Schur complement\n// equation\n//\n// {{S, -B}, {B^T, 0}} . {dx, dy} = {r, s}\n//\n// (where S = SchurComplement, B = FreeVarMatrix), using the method\n// described in the manual:\n//\n// - Compute S using BilinearPairingsXInv and BilinearPairingsY.\n//\n// - Stabilize S by adding a low-rank update S' = S + U U^T and\n//   compute the Cholesky decomposition S' = L' L'^T.\n//\n// - Form B' = (B U) and compute\n//\n//   - SchurOffDiagonal = L'^{-1} B\n//   - L'^{-1} U (this is stored implicitly in the stabilizeBlock* variables)\n//   - Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}\n//\n// - Compute the LU decomposition of Q.\n//\n// This data is sufficient to efficiently solve the above equation for\n// a given r,s.\n//\n// Inputs:\n// - BilinearPairingsXInv, BilinearPairingsY (these are members of\n//   SDPSolver, but we include them as arguments to emphasize that\n//   they must be computed first)\n// - choleskyStabilizeThreshold: the real constant \\theta used in\n//   stabilizing S\n// Workspace (members of SDPSolver which are modified by this method\n// and not used later):\n// - SchurComplement\n// - schurStabilizeIndices\n// - schurStabilizeLambdas\n// Outputs (members of SDPSolver which are modified by this method and\n// used later):\n// - SchurComplementCholesky\n// - SchurOffDiagonal\n// - stabilizeBlockIndices\n// - stabilizeBlockUpdateRow\n// - stabilizeBlockUpdateColumn\n// - stabilizeBlocks\n// - Q, Qpivots\n//\nvoid SDPSolver::initializeSchurComplementSolver(const BlockDiagonalMatrix &BilinearPairingsXInv,\n                                                const BlockDiagonalMatrix &BilinearPairingsY,\n                                                const Real &choleskyStabilizeThreshold) {\n  computeSchurComplement(sdp, BilinearPairingsXInv, BilinearPairingsY, SchurComplement);\n\n  // compute SchurComplementCholesky = L', where\n  //\n  //   L' L'^T = S' = SchurComplement + U U^T\n  //\n  // Here, the 'update' matrix U has columns given by\n  //\n  //   U = ( Lambda_{p_1} e_{p_1}, ..., Lambda_{p_M} e_{p_M} )\n  //\n  // where e_p is a unit vector in the p-th direction and the\n  // Lambda_{p_m} are constants. The p_i are given by\n  // schurStabilizeIndices and the corresponding Lambda_i by\n  // schurStabilizeLambdas.\n  // \n  choleskyDecompositionStabilized(SchurComplement, SchurComplementCholesky,\n                                  schurStabilizeIndices,\n                                  schurStabilizeLambdas,\n                                  cast2double(choleskyStabilizeThreshold));\n\n  // SchurOffDiagonal = L'^{-1} FreeVarMatrix\n  SchurOffDiagonal.copyFrom(sdp.FreeVarMatrix);\n  blockMatrixLowerTriangularSolve(SchurComplementCholesky, SchurOffDiagonal);\n\n  // Next we compute L'^{-1} U, which is stored implicitly in terms of\n  // its nonzero submatrices in the stabilizeBlock* variables.\n\n  // total number of columns in the off-diagonal part B' = (B U)\n  // (currently just B; will accumulate the rest shortly)\n  int offDiagonalColumns = SchurOffDiagonal.cols;\n\n  stabilizeBlockIndices.resize(0);\n  stabilizeBlockUpdateRow.resize(0);\n  stabilizeBlockUpdateColumn.resize(0);\n\n  // j runs over blocks of SchurComplement\n  for (unsigned int j = 0; j < SchurComplement.blocks.size(); j++) {\n    if (schurStabilizeIndices[j].size() > 0) {\n      // the j-th block of S contains stabilized directions. We have a\n      // block submatrix\n      //\n      //   U_j = stabilizeBlocks[j]\n      //\n      // of U for each such j.\n      stabilizeBlockIndices.push_back(j);\n      \n      // index of the first stabilized direction within the j-th block\n      int startIndex = schurStabilizeIndices[j][0];\n\n      // set the dimensions of U_j \n      stabilizeBlocks[j].resize(SchurComplement.blocks[j].rows - startIndex,\n                                schurStabilizeIndices[j].size());\n      // set U_j = 0\n      stabilizeBlocks[j].setZero();\n      // for each column of U_j add Lambda_p in the row (p - startIndex)\n      for (unsigned int c = 0; c < schurStabilizeIndices[j].size(); c++) {\n        int r = schurStabilizeIndices[j][c] - startIndex;\n        stabilizeBlocks[j].elt(r, c) = schurStabilizeLambdas[j][c];\n      }\n\n      // append the row of U corresponding to the top-left of U_j\n      stabilizeBlockUpdateRow.push_back(SchurComplement.blockStartIndices[j] + startIndex);\n      // append the column of U corresponding to the top-left of U_j\n      stabilizeBlockUpdateColumn.push_back(offDiagonalColumns);\n      // update the number of off-diagonal columns\n      offDiagonalColumns += stabilizeBlocks[j].cols;\n    }\n  }\n\n  // Set U = L'^{-1} U\n  //\n  // We do this by modifying the blocks U_j = stabilizeBlocks[j]\n  // in-place, multiplying by the inverse of the appropriate submatrix\n  // of SchurComplementCholesky.  We henceforth refer to L'^{-1} U as\n  // V to avoid confusion.\n  #pragma omp parallel for schedule(dynamic)\n  for (unsigned int j = 0; j < stabilizeBlockIndices.size(); j++) {\n    int b = stabilizeBlockIndices[j];\n    int startIndex = schurStabilizeIndices[b][0];\n    Rtrsm(\"Left\", \"Lower\", \"NoTranspose\", \"NonUnitDiagonal\",\n          stabilizeBlocks[b].rows, stabilizeBlocks[b].cols, 1,\n          &SchurComplementCholesky.blocks[b].elt(startIndex, startIndex),\n          SchurComplementCholesky.blocks[b].rows,\n          &stabilizeBlocks[b].elt(0, 0),\n          stabilizeBlocks[b].rows);\n  }\n\n  // Next, we compute\n  //\n  //   Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}\n  //\n  // Where B' = (B U).  We think of Q as containing four blocks called\n  // Upper/Lower-Left/Right.\n\n  // Set the dimensions of Q\n  Q.resize(offDiagonalColumns, offDiagonalColumns);\n  Q.setZero();\n\n  // Here, SchurOffDiagonal = L'^{-1} B.\n  //\n  // UpperLeft(Q) = SchurOffDiagonal^T SchurOffDiagonal\n  matrixSquareIntoBlock(SchurOffDiagonal, Q, 0, 0);\n\n  // Here, stabilizeBlocks contains the blocks of V = L'^{-1} U.\n  //\n  // LowerRight(Q) = V^T V - 1\n  for (unsigned int j = 0; j < stabilizeBlockIndices.size(); j++) {\n    int b = stabilizeBlockIndices[j];\n    int c = stabilizeBlockUpdateColumn[j];\n    matrixSquareIntoBlock(stabilizeBlocks[b], Q, c, c);\n    // subtract the identity matrix from this block\n    for (int i = c; i < c + stabilizeBlocks[b].cols; i++)\n      Q.elt(i, i) -= 1;\n  }\n\n  // LowerLeft(Q) = V^T SchurOffDiagonal\n  # pragma omp parallel for schedule(dynamic)\n  for (unsigned int j = 0; j < stabilizeBlockIndices.size(); j++) {\n    int b = stabilizeBlockIndices[j];\n    int p = stabilizeBlockUpdateRow[j];\n    int r = stabilizeBlockUpdateColumn[j];\n    Rgemm(\"Transpose\", \"NoTranspose\",\n          stabilizeBlocks[b].cols,\n          SchurOffDiagonal.cols,\n          stabilizeBlocks[b].rows,\n          1,\n          &stabilizeBlocks[b].elements[0],\n          stabilizeBlocks[b].rows,\n          &SchurOffDiagonal.elt(p, 0),\n          SchurOffDiagonal.rows,\n          0,\n          &Q.elt(r, 0),\n          Q.rows);\n  }\n\n  // UpperRight(Q) = LowerLeft(Q)^T\n  # pragma omp parallel for schedule(static)\n  for (int c = 0; c < SchurOffDiagonal.cols; c++)\n    for (int r = SchurOffDiagonal.cols; r < Q.rows; r++)\n      Q.elt(c, r) = Q.elt(r, c);\n\n  // Resize Qpivots appropriately and compute the LU decomposition of Q\n  Qpivots.resize(Q.rows);\n  LUDecomposition(Q, Qpivots);\n}\n\n\n// Solve the Schur complement equation for dx, dy.\n//\n// - As inputs, dx and dy are the residues r_x and r_y on the\n//   right-hand side of the Schur complement equation.\n// - As outputs, dx and dy are overwritten with the solutions of the\n//   Schur complement equation.\n//\n// The equation is solved using the block-decomposition described in\n// the manual.\n//\nvoid SDPSolver::solveSchurComplementEquation(Vector &dx, Vector &dy) {\n  // dx = SchurComplementCholesky^{-1} dx\n  blockMatrixLowerTriangularSolve(SchurComplementCholesky, dx);\n\n  // extend dy by additional coordinates z needed for stabilizing\n  // dyExtended = (dy, z)\n  dyExtended.resize(Q.rows);\n\n  // dy = r_y - SchurOffDiagonal^T dx\n  for (unsigned int n = 0; n < dy.size(); n++)\n    dyExtended[n] = dy[n];\n  vectorScaleMatrixMultiplyTransposeAdd(-1, SchurOffDiagonal, dx, 1, dyExtended);\n\n  // z = -V^T dx\n  for (unsigned int j = 0; j < stabilizeBlockIndices.size(); j++) {\n    int b = stabilizeBlockIndices[j];\n    int pTopLeft = stabilizeBlockUpdateRow[j];\n    int cTopLeft = stabilizeBlockUpdateColumn[j];\n\n    for (int c = 0; c < stabilizeBlocks[b].cols; c++) {\n      dyExtended[cTopLeft + c] = 0;\n      for (int r = 0; r < stabilizeBlocks[b].rows; r++)\n        dyExtended[cTopLeft + c] -= dx[pTopLeft + r] * stabilizeBlocks[b].elt(r, c);\n    }\n  }\n\n  // dyExtended = Q^{-1} dyExtended\n  solveWithLUDecomposition(Q, Qpivots, dyExtended);\n\n  // dx += SchurOffDiagonal dy\n  vectorScaleMatrixMultiplyAdd(1, SchurOffDiagonal, dyExtended, 1, dx);\n\n  // dx += V z\n  for (unsigned int j = 0; j < stabilizeBlockIndices.size(); j++) {\n    int b = stabilizeBlockIndices[j];\n    int pTopLeft = stabilizeBlockUpdateRow[j];\n    int cTopLeft = stabilizeBlockUpdateColumn[j];\n\n    for (int c = 0; c < stabilizeBlocks[b].cols; c++)\n      for (int r = 0; r < stabilizeBlocks[b].rows; r++)\n        dx[pTopLeft + r] += dyExtended[cTopLeft + c] * stabilizeBlocks[b].elt(r, c);\n  }\n\n  // dx = SchurComplementCholesky^{-T} dx\n  blockMatrixLowerTriangularTransposeSolve(SchurComplementCholesky, dx);\n\n  // dy = first few entries of dyExtended\n  for (unsigned int n = 0; n < dy.size(); n++)\n    dy[n] = dyExtended[n];\n}\n\n// Compute the search direction (dx, dX, dy, dY) for the predictor and\n// corrector phases.\n//\n// Inputs:\n// - beta, the centering parameter\n// - mu = Tr(X Y) / X.cols\n// - correctorPhase: boolean indicating whether we're in the corrector\n//   phase or predictor phase.\n// Workspace (members of SDPSolver which are modified in-place but not\n// used elsewhere):\n// - Z, R\n// Outputs (members of SDPSolver which are modified in-place):\n// - dx, dX, dy, dY\n//\nvoid SDPSolver::computeSearchDirection(const Real &beta,\n                                       const Real &mu,\n                                       const bool correctorPhase) {\n  // R = beta mu I - X Y (predictor phase)\n  // R = beta mu I - X Y - dX dY (corrector phase)\n  blockDiagonalMatrixScaleMultiplyAdd(-1, X, Y, 0, R);\n  if (correctorPhase)\n    blockDiagonalMatrixScaleMultiplyAdd(-1, dX, dY, 1, R);\n  R.addDiagonal(beta*mu);\n\n  // Z = Symmetrize(X^{-1} (PrimalResidues Y - R))\n  blockDiagonalMatrixMultiply(PrimalResidues, Y, Z);\n  Z -= R;\n  blockMatrixSolveWithCholesky(XCholesky, Z);\n  Z.symmetrize();\n\n  // r_x[p] = -dualResidues[p] - Tr(A_p Z)\n  // r_y[n] = dualObjective[n] - (FreeVarMatrix^T x)_n\n  // Here, dx = r_x, dy = r_y.\n  computeSchurRHS(sdp, dualResidues, Z, x, dx, dy);\n\n  // Solve for dx, dy in-place\n  solveSchurComplementEquation(dx, dy);\n\n  // dX = PrimalResidues + \\sum_p A_p dx[p]\n  constraintMatrixWeightedSum(sdp, dx, dX);\n  dX += PrimalResidues;\n\n  // dY = Symmetrize(X^{-1} (R - dX Y))\n  blockDiagonalMatrixMultiply(dX, Y, dY);\n  dY -= R;\n  blockMatrixSolveWithCholesky(XCholesky, dY);\n  dY.symmetrize();\n  dY *= -1;\n}\n\n/***********************************************************************/\n// The main solver loop\n\nSDPSolverTerminateReason SDPSolver::run(const path checkpointFile) {\n  Real primalStepLength;\n  Real dualStepLength;\n\n  printHeader();\n\n  for (int iteration = 1;; iteration++) {\n    if (timers[\"Last checkpoint\"].elapsed().wall >= parameters.checkpointInterval * 1000000000LL)\n      saveCheckpoint(checkpointFile);\n    if (timers[\"Solver runtime\"].elapsed().wall >= parameters.maxRuntime * 1000000000LL)\n      return MaxRuntimeExceeded;\n\n    primalObjective = sdp.objectiveConst + dotProduct(sdp.primalObjective, x);\n    dualObjective   = sdp.objectiveConst + dotProduct(sdp.dualObjective, y);\n    dualityGap      = abs(primalObjective - dualObjective) /\n      max(Real(abs(primalObjective) + abs(dualObjective)), Real(1));\n\n    choleskyDecomposition(X, XCholesky);\n    choleskyDecomposition(Y, YCholesky);\n\n    // Compute the bilinear pairings BilinearPairingsXInv and\n    // BilinearPairingsY needed for the dualResidues and the Schur\n    // complement matrix\n    blockTensorInvTransposeCongruenceWithCholesky(XCholesky, sdp.bilinearBases,\n                                                  bilinearPairingsWorkspace,\n                                                  BilinearPairingsXInv);\n    blockTensorTransposeCongruence(Y, sdp.bilinearBases,\n                                   bilinearPairingsWorkspace,\n                                   BilinearPairingsY);\n\n    // dualResidues[p] = primalObjective[p] - Tr(A_p Y) - (FreeVarMatrix y)_p,\n    computeDualResidues(sdp, y, BilinearPairingsY, dualResidues);\n    dualError = maxAbsVector(dualResidues);\n\n    // PrimalResidues = \\sum_p A_p x[p] - X\n    computePrimalResidues(sdp, x, X, PrimalResidues);\n    primalError = PrimalResidues.maxAbs();\n\n    const bool isPrimalFeasible = primalError < parameters.primalErrorThreshold;\n    const bool isDualFeasible   = dualError   < parameters.dualErrorThreshold;\n    const bool isOptimal        = dualityGap  < parameters.dualityGapThreshold;\n\n    if (isPrimalFeasible && isDualFeasible && isOptimal)                   return PrimalDualOptimal;\n    else if (isPrimalFeasible && parameters.findPrimalFeasible)            return PrimalFeasible;\n    else if (isDualFeasible && parameters.findDualFeasible)                return DualFeasible;\n    else if (primalStepLength == 1 && parameters.detectPrimalFeasibleJump) return PrimalFeasibleJumpDetected;\n    else if (dualStepLength == 1 && parameters.detectDualFeasibleJump)     return DualFeasibleJumpDetected;\n    else if (iteration > parameters.maxIterations)                         return MaxIterationsExceeded;\n\n    // Compute SchurComplement and prepare to solve the Schur\n    // complement equation for dx, dy\n    initializeSchurComplementSolver(BilinearPairingsXInv, BilinearPairingsY,\n                                    parameters.choleskyStabilizeThreshold);\n\n    // Compute the complementarity mu = Tr(X Y)/X.dim\n    Real mu = frobeniusProductSymmetric(X, Y)/X.dim;\n    if (mu > parameters.maxComplementarity)\n      return MaxComplementarityExceeded;\n\n    // Compute the predictor solution for (dx, dX, dy, dY)\n    Real betaPredictor =\n      predictorCenteringParameter(parameters, isPrimalFeasible && isDualFeasible);\n    computeSearchDirection(betaPredictor, mu, false);\n\n    // Compute the corrector solution for (dx, dX, dy, dY)\n    Real betaCorrector =\n      correctorCenteringParameter(parameters, X, dX, Y, dY, mu,\n                                  isPrimalFeasible && isDualFeasible);\n    computeSearchDirection(betaCorrector, mu, true);\n\n    // Compute step-lengths that preserve positive definiteness of X, Y\n    primalStepLength = stepLength(XCholesky, dX, StepMatrixWorkspace,\n                                  eigenvaluesWorkspace, QRWorkspace,\n                                  parameters.stepLengthReduction);\n    dualStepLength   = stepLength(YCholesky, dY, StepMatrixWorkspace,\n                                  eigenvaluesWorkspace, QRWorkspace,\n                                  parameters.stepLengthReduction);\n\n    // If our problem is both dual-feasible and primal-feasible,\n    // ensure we're following the true Newton direction.\n    if (isPrimalFeasible && isDualFeasible) {\n      primalStepLength = min(primalStepLength, dualStepLength);\n      dualStepLength = primalStepLength;\n    }\n\n    printIteration(iteration, mu, primalStepLength, dualStepLength, betaCorrector);\n\n    // Update the primal point (x, X) += primalStepLength*(dx, dX)\n    addScaledVector(x, primalStepLength, dx);\n    dX *= primalStepLength;\n    X += dX;\n\n    // Update the dual point (y, Y) += dualStepLength*(dy, dY)\n    addScaledVector(y, dualStepLength, dy);\n    dY *= dualStepLength;\n    Y += dY;\n  }\n\n  // Never reached\n  return MaxIterationsExceeded;\n}\n", "meta": {"hexsha": "2f11f4b1339fba70d37342eeed513b9e56f37f88", "size": 37271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SDPSolver.cpp", "max_stars_repo_name": "rajeeves/sdpb", "max_stars_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SDPSolver.cpp", "max_issues_repo_name": "rajeeves/sdpb", "max_issues_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SDPSolver.cpp", "max_forks_repo_name": "rajeeves/sdpb", "max_forks_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_forks_repo_licenses": ["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.1225099602, "max_line_length": 109, "alphanum_fraction": 0.6051353599, "num_tokens": 10593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.03904828867243206, "lm_q1q2_score": 0.014742317020813049}}
{"text": "/// @file DeconvolverBasisFunction.tcc\n/// @brief Class for a deconvolver based on CLEANing with basis functions.\n/// @details This concrete class defines a deconvolver used to estimate an\n/// image from a residual image, psf optionally using a weights image.\n/// @ingroup Deconvolver\n///\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Tim Cornwell <tim.cornwell@csiro.au>\n///\n\n// ASKAPsoft includes\n#include <askap/AskapLogging.h>\n#include <casacore/casa/aips.h>\n#include <boost/shared_ptr.hpp>\n#include <casacore/casa/Arrays/Array.h>\n#include <casacore/casa/Arrays/MaskArrMath.h>\n#include <casacore/casa/Arrays/ArrayMath.h>\n#include <casacore/casa/Arrays/MatrixMath.h>\n#include <casacore/scimath/Mathematics/MatrixMathLA.h>\n\n// Local package includes\n#include <measurementequation/SynthesisParamsHelper.h>\n#include <deconvolution/DeconvolverBasisFunction.h>\n#include <deconvolution/MultiScaleBasisFunction.h>\n\nASKAP_LOGGER(decbflogger, \".deconvolution.basisfunction\");\n\nnamespace askap {\n\n    namespace synthesis {\n\n        /// @brief Class for a deconvolver based on the BasisFunction Clean\n        /// @details This base class defines a deconvolver used to estimate an\n        /// image from a residual image, psf optionally using a weights image.\n        /// The template argument T is the type, and FT is the transform\n        /// e.g. DeconvolverBasisFunction<Double, DComplex>\n        /// @ingroup Deconvolver\n \n        template<class T, class FT>\n        DeconvolverBasisFunction<T, FT>::DeconvolverBasisFunction(Vector<Array<T> >& dirty,\n                                                                  Vector<Array<T> >& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf),\n                itsUseCrossTerms(true), itsDecouple(true),\n                itsDecouplingAlgorithm(\"diagonal\")\n        {\n        };\n\n        template<class T, class FT>\n        DeconvolverBasisFunction<T, FT>::DeconvolverBasisFunction(Array<T>& dirty,\n                                                                  Array<T>& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf),\n                itsUseCrossTerms(true), itsDecouple(true),\n                itsDecouplingAlgorithm(\"diagonal\")\n        {\n        };\n\n        template<class T, class FT>\n        DeconvolverBasisFunction<T, FT>::~DeconvolverBasisFunction()\n        {\n        };\n\n        template<class T, class FT>\n        void DeconvolverBasisFunction<T, FT>::setBasisFunction(boost::shared_ptr<BasisFunction<T> > bf)\n        {\n            itsBasisFunction = bf;\n        };\n\n        template<class T, class FT>\n        boost::shared_ptr<BasisFunction<T> > DeconvolverBasisFunction<T, FT>::basisFunction()\n        {\n            return itsBasisFunction;\n        };\n\n        template<class T, class FT>\n        void DeconvolverBasisFunction<T, FT>::configure(const LOFAR::ParameterSet& parset)\n        {\n            DeconvolverBase<T, FT>::configure(parset);\n\n            // Make the basis function\n            {\n                std::vector<float> defaultScales(3);\n                defaultScales[0] = 0.0;\n                defaultScales[1] = 10.0;\n                defaultScales[2] = 30.0;\n                const std::vector<float> scales = parset.getFloatVector(\"scales\", defaultScales);\n\n                ASKAPLOG_INFO_STR(decbflogger, \"Constructing Multiscale basis function with scales \" << scales);\n                const Bool orthogonal = parset.getBool(\"orthogonal\", false);\n\n                if (orthogonal) {\n                    ASKAPLOG_DEBUG_STR(decbflogger, \"Multiscale basis functions will be orthogonalised\");\n                }\n\n                itsBasisFunction = BasisFunction<Float>::ShPtr(new MultiScaleBasisFunction<Float>(scales,\n                                   orthogonal));\n            }\n            itsUseCrossTerms = parset.getBool(\"usecrossterms\", true);\n\n            if (itsUseCrossTerms) {\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Will use crossterms in subtraction\");\n            }\n\n            itsDecouplingAlgorithm = parset.getString(\"decouplingalgorithm\", \"diagonal\");\n        }\n\n        template<class T, class FT>\n        void DeconvolverBasisFunction<T, FT>::finalise()\n        {\n            this->updateResiduals(this->itsModel);\n\n            const Array<T> ones(this->itsL1image(0).shape(), 1.0);\n            const T l0Norm(sum(ones(abs(this->itsL1image(0)) > T(0.0))));\n            const T l1Norm(sum(abs(this->itsL1image(0))));\n            ASKAPLOG_INFO_STR(decbflogger, \"L0 norm = \" << l0Norm << \", L1 norm   = \" << l1Norm\n                                  << \", Flux = \" << sum(this->model()));\n\n            for (uInt scale = 0; scale < itsScaleFlux.nelements(); scale++) {\n                ASKAPLOG_INFO_STR(decbflogger, \"   Scale \" << scale << \" Flux = \" << itsScaleFlux(scale));\n            }\n\n        }\n\n        template<class T, class FT>\n        void DeconvolverBasisFunction<T, FT>::initialise()\n        {\n            DeconvolverBase<T, FT>::initialise();\n\n            ASKAPLOG_INFO_STR(decbflogger, \"Initialising Basis Function deconvolver\");\n\n            Int psfWidth = this->model().shape()(0);\n            IPosition subPsfShape(2, 0, 0);\n\n            // Only use the specified psfWidth if it makes sense\n            if ((this->control()->psfWidth() > 0) && (this->control()->psfWidth() < psfWidth)) {\n                psfWidth = this->control()->psfWidth();\n                ASKAPLOG_INFO_STR(decbflogger, \"Using subregion of Psf : size \" << psfWidth\n                                      << \" pixels\");\n                subPsfShape = IPosition(2, psfWidth, psfWidth);\n            } else {\n                subPsfShape = IPosition(2, this->model().shape()(0), this->model().shape()(1));\n            }\n\n            this->itsBasisFunction->initialise(this->model().shape());\n            initialiseResidual();\n            this->itsBasisFunction->initialise(subPsfShape);\n            initialisePSF();\n\n            if (this->itsDecouplingAlgorithm == \"basis\") {\n                // Decoupling using inverse coupling matrix generate orthogonal basis functions\n                ASKAPLOG_INFO_STR(decbflogger, \"Decoupling using inverse coupling matrix generate orthogonal basis functions\");\n                const Matrix<Double> inverseCouplingMatrix(this->itsInverseCouplingMatrix.copy());\n                this->itsBasisFunction->initialise(this->model().shape());\n                itsBasisFunction->multiplyArray(inverseCouplingMatrix);\n                initialiseResidual();\n                this->itsBasisFunction->initialise(subPsfShape);\n                itsBasisFunction->multiplyArray(inverseCouplingMatrix);\n                this->itsBasisFunction->multiplyArray(inverseCouplingMatrix);\n                initialisePSF();\n                //  SynthesisParamsHelper::saveAsCasaImage(\"BasisFunctionAfterInverseDecoupling.tab\",\n                //                         this->itsBasisFunction->basisFunction());\n                //  SynthesisParamsHelper::saveAsCasaImage(\"ResidualsAfterInverseDecoupling.tab\",\n                //                         this->itsResidualBasisFunction);\n            } else if (this->itsDecouplingAlgorithm == \"residuals\") {\n                // Decoupling using inverse coupling matrix applied to basis and residuals\n                ASKAPLOG_INFO_STR(decbflogger, \"Decoupling using inverse coupling matrix applied to basis and residuals\");\n                const Array<T> invBF(applyInverse(this->itsInverseCouplingMatrix, this->itsBasisFunction->basisFunction()));\n                this->itsBasisFunction->basisFunction() = invBF.copy();\n\n                const Array<T> invRes(applyInverse(this->itsInverseCouplingMatrix, this->itsResidualBasisFunction));\n                this->itsResidualBasisFunction = invRes.copy();\n\n                if (itsUseCrossTerms) {\n                    ASKAPLOG_DEBUG_STR(decbflogger, \"Overriding usecrossterms since it makes no sense in this case\");\n                    this->itsUseCrossTerms = false;\n                }\n\n                //  SynthesisParamsHelper::saveAsCasaImage(\"BasisFunctionAfterResidualsDecoupling.tab\",\n                //                         this->itsBasisFunction->basisFunction());\n                //  SynthesisParamsHelper::saveAsCasaImage(\"ResidualsAfterResidualsDecoupling.tab\",\n                //                         this->itsResidualBasisFunction);\n            } else if (this->itsDecouplingAlgorithm == \"inverse\") {\n                // Correcting coupling at subtraction phase with inverse coupling matrix\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Correcting coupling at subtraction phase with inverse coupling matrix\");\n            } else if (this->itsDecouplingAlgorithm == \"sqrtdiagonal\") {\n                // Correcting coupling at subtraction phase with inverse diag(coupling matrix)\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Correcting coupling at subtraction phase with inverse sqrt(diag(coupling matrix))\");\n            } else if (this->itsDecouplingAlgorithm == \"diagonal\") {\n                // Correcting coupling at subtraction phase with inverse diag(coupling matrix)\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Correcting coupling at subtraction phase with inverse diag(coupling matrix)\");\n            } else if (this->itsDecouplingAlgorithm == \"psfscales\") {\n                // Correcting coupling at subtraction phase with inverse psfscales\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Correcting coupling at subtraction phase with inverse psfscales\");\n            } else if (this->itsDecouplingAlgorithm == \"sqrtpsfscales\") {\n                // Correcting coupling at subtraction phase with inverse psfscales\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Correcting coupling at subtraction phase with inverse sqrt(psfscales)\");\n            } else {\n                // Correcting coupling at subtraction phase with inverse diag(coupling matrix)\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Correcting coupling at subtraction phase with inverse diag(coupling matrix)\");\n            }\n\n            const uInt nScales(this->itsBasisFunction->numberBases());\n            const IPosition l1Shape(3, this->model().shape()(0), this->model().shape()(1), nScales);\n\n            this->itsL1image.resize(this->itsNumberTerms);\n            this->itsL1image(0).resize(l1Shape);\n            this->itsL1image(0).set(0.0);\n        }\n\n        template<class T, class FT>\n        void DeconvolverBasisFunction<T, FT>::initialiseResidual()\n        {\n\n            ASKAPCHECK(this->itsBasisFunction, \"Basis function not initialised\");\n\n            this->state()->resetInitialObjectiveFunction();\n\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Calculating cache of images\");\n\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Shape of basis functions \"\n                                   << this->itsBasisFunction->basisFunction().shape());\n\n            const IPosition stackShape(this->itsBasisFunction->basisFunction().shape());\n\n            itsResidualBasisFunction.resize(stackShape);\n\n            Cube<FT> basisFunctionFFT(this->itsBasisFunction->basisFunction().shape());\n            casa::setReal(basisFunctionFFT, this->itsBasisFunction->basisFunction());\n            scimath::fft2d(basisFunctionFFT, true);\n\n            Array<FT> residualFFT(this->dirty().shape().nonDegenerate());\n            residualFFT.set(FT(0.0));\n            casa::setReal(residualFFT, this->dirty().nonDegenerate());\n            scimath::fft2d(residualFFT, true);\n\n            Array<FT> work(this->model().nonDegenerate().shape());\n            ASKAPLOG_DEBUG_STR(decbflogger,\n                               \"Calculating convolutions of residual image with basis functions\");\n\n            for (uInt term = 0; term < this->itsBasisFunction->numberBases(); term++) {\n\n                ASKAPASSERT(basisFunctionFFT.xyPlane(term).nonDegenerate().shape().conform(residualFFT.nonDegenerate().shape()));\n                work = conj(basisFunctionFFT.xyPlane(term).nonDegenerate()) * residualFFT.nonDegenerate();\n                scimath::fft2d(work, false);\n\n                // basis function * residual\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Basis function(\" << term\n                                       << \") * Residual: max = \" << max(real(work))\n                                       << \" min = \" << min(real(work)));\n\n                Cube<T>(itsResidualBasisFunction).xyPlane(term) = real(work);\n\n            }\n        }\n\n        template<class T, class FT>\n        void DeconvolverBasisFunction<T, FT>::initialisePSF()\n        {\n            // For the psf convolutions, we only need a small part of the\n            // basis functions so we recalculate for that size\n            Int psfWidth = this->model(0).shape()(0);\n\n            // Only use the specified psfWidth if it makes sense\n            if ((this->control()->psfWidth() > 0) && (this->control()->psfWidth() < psfWidth)) {\n                psfWidth = this->control()->psfWidth();\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Using subregion of Psf : size \" << psfWidth\n                                       << \" pixels\");\n            }\n\n            IPosition subPsfShape(2, psfWidth, psfWidth);\n\n            Array<FT> work(subPsfShape);\n\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Shape of basis functions \"\n                                   << this->itsBasisFunction->basisFunction().shape());\n\n            const IPosition stackShape(this->itsBasisFunction->basisFunction().shape());\n\n            // Now transform the basis functions\n            Cube<FT> basisFunctionFFT(this->itsBasisFunction->basisFunction().shape());\n            casa::setReal(basisFunctionFFT, this->itsBasisFunction->basisFunction());\n            scimath::fft2d(basisFunctionFFT, true);\n\n            this->itsPSFBasisFunction.resize(stackShape);\n\n            this->itsScaleFlux.resize(stackShape(2));\n            this->itsScaleFlux.set(T(0));\n\n            // Calculate XFR for the subsection only\n            Array<FT> subXFR(subPsfShape);\n\n            const uInt nx(this->psf().shape()(0));\n            const uInt ny(this->psf().shape()(1));\n\n            const IPosition subPsfStart(2, nx / 2 - psfWidth / 2, ny / 2 - psfWidth / 2);\n            const IPosition subPsfEnd(2, nx / 2 + psfWidth / 2 - 1, ny / 2 + psfWidth / 2 - 1);\n            const IPosition subPsfStride(2, 1, 1);\n\n            Slicer subPsfSlicer(subPsfStart, subPsfEnd, subPsfStride, Slicer::endIsLast);\n            casa::IPosition minPos;\n            casa::IPosition maxPos;\n            T minVal, maxVal;\n            casa::minMax(minVal, maxVal, minPos, maxPos, this->psf(0).nonDegenerate()(subPsfSlicer));\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Maximum of PSF(0) = \" << maxVal << \" at \" << maxPos);\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Minimum of PSF(0) = \" << minVal << \" at \" << minPos);\n            this->itsPeakPSFVal = maxVal;\n            this->itsPeakPSFPos(0) = maxPos(0);\n            this->itsPeakPSFPos(1) = maxPos(1);\n\n            const IPosition subPsfPeak(2, this->itsPeakPSFPos(0), this->itsPeakPSFPos(1));\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Peak of PSF subsection at  \" << subPsfPeak);\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Shape of PSF subsection is \" << subPsfShape);\n\n            casa::setReal(subXFR, this->psf().nonDegenerate()(subPsfSlicer));\n            scimath::fft2d(subXFR, true);\n\n            // Now we have all the ingredients to calculate the convolutions\n            // of basis function with psf's, etc.\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Calculating convolutions of Psfs with basis functions\");\n            itsPSFScales.resize(this->itsBasisFunction->numberBases());\n\n            for (uInt term = 0; term < this->itsBasisFunction->numberBases(); term++) {\n                // basis function * psf\n                ASKAPASSERT(basisFunctionFFT.xyPlane(term).nonDegenerate().shape().conform(subXFR.shape()));\n                work = conj(basisFunctionFFT.xyPlane(term).nonDegenerate()) * subXFR;\n                scimath::fft2d(work, false);\n                Cube<T>(this->itsPSFBasisFunction).xyPlane(term) = real(work);\n\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Basis function(\" << term << \") * PSF: max = \" << max(real(work)) << \" min = \" << min(real(work)));\n\n                itsPSFScales(term) = max(real(work));\n            }\n\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Calculating double convolutions of PSF with basis functions\");\n            const IPosition crossTermsShape(4, psfWidth, psfWidth,\n                                            this->itsBasisFunction->numberBases(),\n                                            this->itsBasisFunction->numberBases());\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Shape of cross terms \" << crossTermsShape);\n            itsPSFCrossTerms.resize(crossTermsShape);\n            IPosition crossTermsStart(4, 0);\n            IPosition crossTermsEnd(crossTermsShape - 1);\n            IPosition crossTermsStride(4, 1);\n\n            Array<FT> crossTermsPSFFFT(crossTermsShape);\n            crossTermsPSFFFT.set(T(0));\n\n            for (uInt term = 0; term < this->itsBasisFunction->numberBases(); term++) {\n                crossTermsStart(2) = term;\n                crossTermsEnd(2) = term;\n\n                for (uInt term1 = 0; term1 < this->itsBasisFunction->numberBases(); term1++) {\n                    crossTermsStart(3) = term1;\n                    crossTermsEnd(3) = term1;\n                    casa::Slicer crossTermsSlicer(crossTermsStart, crossTermsEnd, crossTermsStride, Slicer::endIsLast);\n                    crossTermsPSFFFT(crossTermsSlicer).nonDegenerate() =\n                        basisFunctionFFT.xyPlane(term).nonDegenerate() *\n                        conj(basisFunctionFFT.xyPlane(term1)).nonDegenerate() * subXFR;\n                }\n\n            }\n\n            this->itsCouplingMatrix.resize(itsBasisFunction->numberBases(), itsBasisFunction->numberBases());\n            scimath::fft2d(crossTermsPSFFFT, true);\n            this->itsPSFCrossTerms = real(crossTermsPSFFFT) / T(crossTermsShape(0) * crossTermsShape(1));\n\n            for (uInt term = 0; term < this->itsBasisFunction->numberBases(); term++) {\n                crossTermsStart(2) = term;\n                crossTermsEnd(2) = term;\n\n                for (uInt term1 = 0; term1 < this->itsBasisFunction->numberBases(); term1++) {\n                    crossTermsStart(3) = term1;\n                    crossTermsEnd(3) = term1;\n                    casa::Slicer crossTermsSlicer(crossTermsStart, crossTermsEnd, crossTermsStride, Slicer::endIsLast);\n                    casa::IPosition minPos;\n                    casa::IPosition maxPos;\n                    T minVal, maxVal;\n                    casa::minMax(minVal, maxVal, minPos, maxPos, this->itsPSFCrossTerms(crossTermsSlicer));\n                    this->itsCouplingMatrix(term, term1) = Double(maxVal);\n                }\n\n                this->itsCouplingMatrix(term, term) += Double(this->control()->lambda());\n            }\n\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Coupling matrix \" << this->itsCouplingMatrix);\n            this->itsInverseCouplingMatrix.resize(this->itsCouplingMatrix.shape());\n            invertSymPosDef(this->itsInverseCouplingMatrix, this->itsDetCouplingMatrix, this->itsCouplingMatrix);\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Coupling matrix determinant \" << this->itsDetCouplingMatrix);\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Inverse coupling matrix \" << this->itsInverseCouplingMatrix);\n            // Checked that the inverse really is an inverse.\n            Matrix<T> identity(this->itsCouplingMatrix.shape(), 0.0);\n            const uInt nRows(this->itsCouplingMatrix.nrow());\n            const uInt nCols(this->itsCouplingMatrix.ncolumn());\n\n            for (uInt row = 0; row < nRows; row++) {\n                for (uInt col = 0; col < nCols; col++) {\n                    identity(row, col) = sum(this->itsCouplingMatrix.row(row) * this->itsInverseCouplingMatrix.column(col));\n                }\n            }\n\n            ASKAPLOG_DEBUG_STR(decbflogger, \"Coupling matrix * inverse \" << identity);\n\n\n            // Now look at coupling between adjacent scales: this works well if the\n            // scales are ordered.\n            for (uInt term = 0; term < this->itsBasisFunction->numberBases() - 1; term++) {\n                double det = this->itsCouplingMatrix(term, term) * this->itsCouplingMatrix(term + 1, term + 1) -\n                             this->itsCouplingMatrix(term, term + 1) * this->itsCouplingMatrix(term + 1, term);\n                ASKAPLOG_DEBUG_STR(decbflogger, \"Independence between scales \" << term << \" and \"\n                                       << term + 1 << \" = \" << det);\n            }\n        }\n\n        template<class T, class FT>\n        bool DeconvolverBasisFunction<T, FT>::deconvolve()\n        {\n            this->initialise();\n\n            ASKAPLOG_INFO_STR(decbflogger, \"Performing BasisFunction CLEAN for \"\n                                  << this->control()->targetIter() << \" iterations\");\n\n            do {\n                this->oneIteration();\n                this->monitor()->monitor(*(this->state()));\n                this->state()->incIter();\n            } while (!this->control()->terminate(*(this->state())));\n\n            ASKAPLOG_INFO_STR(decbflogger, \"Performed BasisFunction CLEAN for \"\n                                  << this->state()->currentIter() << \" iterations\");\n\n            ASKAPLOG_INFO_STR(decbflogger, this->control()->terminationString());\n\n            this->finalise();\n            return True;\n        }\n\n        // This contains the heart of the BasisFunction Clean algorithm\n        // The residual image and psfs are intrinsically two dimensional\n        // but are expanded by projection onto the basis functions\n        template<class T, class FT>\n        bool DeconvolverBasisFunction<T, FT>::oneIteration()\n        {\n            // Find peak in residual image cube. This cube is full sized.\n            casa::IPosition minPos;\n            casa::IPosition maxPos;\n            T minVal(0.0), maxVal(0.0);\n            // Here the weights image is used as a weight in the determination\n            // of the maximum i.e. it finds the max in weight . residual. The values\n            // returned are without the weight\n            minMaxMaskedScales(minVal, maxVal, minPos, maxPos, this->itsResidualBasisFunction,\n                               this->weight(0));\n            casa::IPosition absPeakPos;\n\n            if (abs(minVal) < abs(maxVal)) {\n                absPeakPos = maxPos;\n            } else {\n                absPeakPos = minPos;\n            }\n\n            // Find the peak values for each scale. Set the stopping criterion\n            // to be the maximum of the maxima. Here we use the weighted\n            // value since that's what we are interested in.\n            const uInt nScales(this->itsBasisFunction->numberBases());\n            Vector<T> peakValues(nScales);\n            IPosition peakPos(absPeakPos);\n            // If we are using residual decoupling, we need to\n            // couple the peakvalues\n            // Apply the inverse of the sqrt(diagonal values) to get the peak values\n            Vector<T> coupledPeakValues(nScales);\n\n            for (uInt scale = 0; scale < nScales; scale++) {\n                peakPos(2) = scale;\n                coupledPeakValues(scale) = this->itsResidualBasisFunction(peakPos);\n            }\n\n            if (itsDecouplingAlgorithm == \"residuals\") {\n                // This is a special case - the residuals are already decoupled.\n                peakValues = coupledPeakValues.copy();\n            } else if (itsDecouplingAlgorithm == \"inverse\") {\n                peakValues = apply(this->itsInverseCouplingMatrix, coupledPeakValues);\n            } else if (itsDecouplingAlgorithm == \"diagonal\") {\n                for (uInt scale = 0; scale < nScales; scale++) {\n                    peakPos(2) = scale;\n                    peakValues(scale) = coupledPeakValues(scale)\n                                        / (this->itsCouplingMatrix(scale, scale));\n                }\n            } else if (itsDecouplingAlgorithm == \"sqrtdiagonal\") {\n                for (uInt scale = 0; scale < nScales; scale++) {\n                    peakPos(2) = scale;\n                    peakValues(scale) = coupledPeakValues(scale)\n                                        / sqrt(this->itsCouplingMatrix(scale, scale));\n                }\n            } else if (itsDecouplingAlgorithm == \"psfscales\") {\n                for (uInt scale = 0; scale < nScales; scale++) {\n                    peakPos(2) = scale;\n                    peakValues(scale) = coupledPeakValues(scale)\n                                        / this->itsPSFScales(scale);\n                }\n            } else if (itsDecouplingAlgorithm == \"sqrtpsfscales\") {\n                for (uInt scale = 0; scale < nScales; scale++) {\n                    peakPos(2) = scale;\n                    peakValues(scale) = coupledPeakValues(scale)\n                                        / sqrt(this->itsPSFScales(scale));\n                }\n            } else {\n                ASKAPTHROW(AskapError, \"Unknown decoupling algorithm \" << itsDecouplingAlgorithm);\n            }\n\n            uInt optimumScale(0);\n            T absPeakVal(0.0);\n\n            for (uInt scale = 0; scale < nScales; scale++) {\n                if (abs(peakValues(scale)) > abs(absPeakVal)) {\n                    absPeakVal = peakValues(scale);\n                    optimumScale = scale;\n                }\n            }\n\n            // If we decoupled by residuals we need to recouple before\n            // subtracting from the residuals\n            if (this->itsDecouplingAlgorithm == \"residuals\") {\n                peakValues = apply(this->itsCouplingMatrix, peakValues);\n            } else {\n                // Only the peak is useful\n                for (uInt scale = 0; scale < nScales; scale++) {\n                    if (scale != optimumScale) {\n                        peakValues(scale) = T(0.0);\n                    }\n                }\n            }\n\n            if (this->state()->initialObjectiveFunction() == 0.0) {\n                this->state()->setInitialObjectiveFunction(abs(absPeakVal));\n            }\n\n            this->state()->setPeakResidual(abs(absPeakVal));\n            this->state()->setObjectiveFunction(abs(absPeakVal));\n            this->state()->setTotalFlux(sum(this->model()));\n\n            const casa::IPosition residualShape(this->itsResidualBasisFunction.shape());\n            const casa::IPosition psfShape(this->itsPSFBasisFunction.shape());\n\n            const casa::uInt ndim(this->itsResidualBasisFunction.shape().size());\n\n            casa::IPosition residualStart(ndim, 0), residualEnd(ndim, 0), residualStride(ndim, 1);\n            casa::IPosition psfStart(ndim, 0), psfEnd(ndim, 0), psfStride(ndim, 1);\n            casa::IPosition psfCrossTermsStart(ndim + 1, 0), psfCrossTermsEnd(ndim + 1, 0), psfCrossTermsStride(ndim + 1, 1);\n\n            const casa::IPosition modelShape(this->model().shape());\n            const casa::uInt modelNdim(this->model().shape().size());\n            casa::IPosition modelStart(modelNdim, 0), modelEnd(modelNdim, 0), modelStride(modelNdim, 1);\n\n            // Wrangle the start, end, and shape into consistent form. It took me\n            // quite a while to figure this out (slow brain day) so it may be\n            // that there are some edge cases for which it fails.\n\n            for (uInt dim = 0; dim < 2; dim++) {\n                residualStart(dim) = max(0, Int(absPeakPos(dim) - psfShape(dim) / 2));\n                residualEnd(dim) = min(Int(absPeakPos(dim) + psfShape(dim) / 2 - 1), Int(residualShape(dim) - 1));\n                // Now we have to deal with the PSF. Here we want to use enough of the\n                // PSF to clean the residual image.\n                psfStart(dim) = max(0, Int(this->itsPeakPSFPos(dim) - (absPeakPos(dim) - residualStart(dim))));\n                psfEnd(dim) = min(Int(this->itsPeakPSFPos(dim) - (absPeakPos(dim) - residualEnd(dim))),\n                                  Int(psfShape(dim) - 1));\n\n                psfCrossTermsStart(dim) = psfStart(dim);\n                psfCrossTermsEnd(dim) = psfEnd(dim);\n\n                modelStart(dim) = residualStart(dim);\n                modelEnd(dim) = residualEnd(dim);\n            }\n\n            casa::Slicer modelSlicer(modelStart, modelEnd, modelStride, Slicer::endIsLast);\n\n            // Add to model\n            // Note that the model is only two dimensional. We could make it three dimensional\n            // and keep the model layers separate\n            // We loop over all terms and ignore those with no flux\n            const casa::uInt nterms(this->itsResidualBasisFunction.shape()(2));\n\n            for (uInt term = 0; term < nterms; term++) {\n                if (abs(peakValues(term)) > 0.0) {\n                    psfStart(2) = psfEnd(2) = term;\n                    casa::Slicer psfSlicer(psfStart, psfEnd, psfStride, Slicer::endIsLast);\n                    typename casa::Array<T> modelSlice = this->model()(modelSlicer).nonDegenerate();\n                    modelSlice += this->control()->gain() * peakValues(term) *\n                                  this->itsBasisFunction->basisFunction()(psfSlicer).nonDegenerate();\n                }\n            }\n\n            // Keep track of strengths and locations of components\n            for (uInt term = 0; term < nterms; term++) {\n                if (abs(peakValues(term)) > 0.0) {\n                    IPosition l1PeakPos(3, absPeakPos(0), absPeakPos(1), term);\n                    casa::Slicer modelSlicer(modelStart, modelEnd, modelStride, Slicer::endIsLast);\n                    this->itsL1image(0)(l1PeakPos) += this->control()->gain() * abs(peakValues(term));\n                    this->itsScaleFlux(term) += this->control()->gain() * peakValues(term);\n                }\n            }\n\n            // Subtract PSFs\n            for (uInt term = 0; term < nterms; term++) {\n                if (abs(peakValues(term)) > 0.0) {\n                    psfStart(2) = psfEnd(2) = term;\n                    casa::Slicer psfSlicer(psfStart, psfEnd, psfStride, Slicer::endIsLast);\n                    residualStart(2) = residualEnd(2) = term;\n                    casa::Slicer residualSlicer(residualStart, residualEnd, residualStride, Slicer::endIsLast);\n                    typename casa::Array<T> residualBFSlice = this->itsResidualBasisFunction(residualSlicer).nonDegenerate();\n                    residualBFSlice -= this->control()->gain() * peakValues(term) * this->itsPSFBasisFunction(psfSlicer).nonDegenerate();\n                }\n            }\n\n            if (itsUseCrossTerms) {\n                for (uInt term1 = 0; term1 < nterms; term1++) {\n                    if (abs(peakValues(term1)) > 0.0) {\n                        for (uInt term = 0; term < nterms; term++) {\n                            if (term != term1) {\n                                residualStart(2) = term;\n                                residualEnd(2) = term;\n                                casa::Slicer residualSlicer(residualStart, residualEnd, residualStride, Slicer::endIsLast);\n\n                                psfCrossTermsStart(2) = term1;\n                                psfCrossTermsEnd(2) = term1;\n                                psfCrossTermsStart(3) = term;\n                                psfCrossTermsEnd(3) = term;\n                                casa::Slicer psfCrossTermsSlicer(psfCrossTermsStart, psfCrossTermsEnd, psfCrossTermsStride, Slicer::endIsLast);\n                                typename casa::Array<T> residualBFSlice = this->itsResidualBasisFunction(residualSlicer).nonDegenerate();\n                                residualBFSlice -= this->control()->gain() * peakValues(term1) *\n                                                   this->itsPSFCrossTerms(psfCrossTermsSlicer).nonDegenerate();\n                            }\n                        }\n                    }\n                }\n            }\n\n            return True;\n        }\n\n        template<class T, class FT>\n        void DeconvolverBasisFunction<T, FT>::minMaxMaskedScales(T& minVal, T& maxVal,\n                IPosition& minPos, IPosition& maxPos,\n                const Array<T>& dataArray,\n                const Array<T>& weightArray)\n        {\n            const Cube<T> data(dataArray);\n            bool isWeighted(weightArray.shape().nonDegenerate().conform(data.xyPlane(0).shape()));\n\n            const uInt nScales = data.shape()(2);\n\n            Vector<T> sMaxVal(nScales);\n            Vector<T> sMinVal(nScales);\n            Vector<IPosition> sMinPos(nScales);\n            Vector<IPosition> sMaxPos(nScales);\n            {\n                if (isWeighted) {\n                    for (uInt scale = 0; scale < nScales; scale++) {\n                        casa::minMaxMasked(sMinVal(scale), sMaxVal(scale), sMinPos(scale), sMaxPos(scale),\n                                           Cube<T>(dataArray).xyPlane(scale), weightArray.nonDegenerate());\n                    }\n                } else {\n                    for (uInt scale = 0; scale < nScales; scale++) {\n                        casa::minMax(sMinVal(scale), sMaxVal(scale), sMinPos(scale), sMaxPos(scale),\n                                     Cube<T>(dataArray).xyPlane(scale));\n                    }\n                }\n            }\n            minPos = IPosition(3, sMinPos(0)(0), sMinPos(0)(1), 0);\n            maxPos = IPosition(3, sMaxPos(0)(0), sMaxPos(0)(1), 0);\n            minVal = sMinVal(0);\n            maxVal = sMaxVal(0);\n\n            for (uInt scale = 1; scale < nScales; scale++) {\n                if (sMinVal(scale) <= minVal) {\n                    minVal = sMinVal(scale);\n                    minPos = IPosition(3, sMinPos(scale)(0), sMinPos(scale)(1), scale);\n                }\n\n                if (sMaxVal(scale) >= maxVal) {\n                    maxVal = sMaxVal(scale);\n                    maxPos = IPosition(3, sMaxPos(scale)(0), sMaxPos(scale)(1), scale);\n                }\n            }\n\n            // If weighting (presumably with weights) was done we need to\n            // look up the original values (without the weights).\n            minVal = data.xyPlane(minPos(2))(minPos);\n            maxVal = data.xyPlane(maxPos(2))(maxPos);\n        }\n        template<class T, class FT>\n        Vector<T> DeconvolverBasisFunction<T, FT>::findCoefficients(const Matrix<Double>& invCoupling,\n                const Vector<T>& peakValues)\n        {\n            const uInt nRows(invCoupling.nrow());\n            const uInt nCols(invCoupling.ncolumn());\n            Vector<T> coefficients(nRows);\n\n            for (uInt row = 0; row < nRows; row++) {\n                coefficients(row) = T(0.0);\n\n                for (uInt col = 0; col < nCols; col++) {\n                    coefficients(row) += T(invCoupling(row, col)) * peakValues(col);\n                }\n            }\n\n            return coefficients;\n        }\n\n        template<class T, class FT>\n        Array<T> DeconvolverBasisFunction<T, FT>::applyInverse(const Matrix<Double>& invCoupling,\n                const Array<T> dataArray)\n        {\n            Array<T> invDataArray(dataArray.shape(), 0.0);\n\n            const uInt nRows(invCoupling.nrow());\n            const uInt nCols(invCoupling.ncolumn());\n            const uInt nx = dataArray.shape()(0);\n            const uInt ny = dataArray.shape()(1);\n\n            for (uInt j = 0; j < ny; j++) {\n                for (uInt i = 0; i < nx; i++) {\n\n                    IPosition currentPosCol(3, i, j, 0);\n                    IPosition currentPosRow(3, i, j, 0);\n\n                    for (uInt row = 0; row < nRows; row++) {\n                        currentPosRow(2) = row;\n\n                        for (uInt col = 0; col < nCols; col++) {\n                            currentPosCol(2) = col;\n                            invDataArray(currentPosRow) += T(invCoupling(row, col)) * dataArray(currentPosCol);\n                        }\n                    }\n\n                }\n            }\n\n            return invDataArray;\n        }\n\n        template<class T, class FT>\n        Array<T> DeconvolverBasisFunction<T, FT>::apply(const Matrix<Double>& coupling,\n                const Vector<T> dataVector)\n        {\n            Vector<T> vecDataVector(dataVector.shape(), 0.0);\n\n            const uInt nRows(coupling.nrow());\n            const uInt nCols(coupling.ncolumn());\n            const uInt nx = dataVector.nelements();\n\n            for (uInt i = 0; i < nx; i++) {\n                for (uInt row = 0; row < nRows; row++) {\n                    for (uInt col = 0; col < nCols; col++) {\n                        vecDataVector(row) += T(coupling(row, col)) * dataVector(col);\n                    }\n                }\n            }\n\n            return vecDataVector;\n        }\n\n    }\n}\n// namespace synthesis\n// namespace askap\n", "meta": {"hexsha": "d396b1f306e6ac6e99d97e4c0931b9b9aa8357ec", "size": 37955, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverBasisFunction.tcc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverBasisFunction.tcc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverBasisFunction.tcc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3503184713, "max_line_length": 147, "alphanum_fraction": 0.5629034383, "num_tokens": 8937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.030675804701484507, "lm_q1q2_score": 0.014739070091025049}}
{"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_COPY_INCLUDE\n#define MTL_COPY_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/detail/index.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/flatcat.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n#include <boost/numeric/mtl/utility/updater_to_assigner.hpp>\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/operation/update.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/crop.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <boost/type_traits/is_same.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <iostream>\n#include <limits>\n\nnamespace mtl {\n\t\n    namespace detail {\n\n\t// Set Destination matrix to zero when source is sparse \n\t// (otherwise everything is overwritten anyway)\n\ttemplate <typename MatrixDest>\n\tinline void zero_with_sparse_src(MatrixDest& dest, tag::flat<tag::sparse>)\n\t{\n\t    set_to_zero(dest);\n\t}\n\t\n\ttemplate <typename MatrixDest>\n\tinline void zero_with_sparse_src(MatrixDest&, tag::universe) {} \n\n\t// Adapt inserter size to operation\n\ttemplate <typename Updater> struct copy_inserter_size {};\n\t\n\t// Specialization for store\n\ttemplate <typename Value>\n\tstruct copy_inserter_size< operations::update_store<Value> >\n\t{\n\t    template <typename MatrixSrc, typename MatrixDest>\n\t    static inline int apply(const MatrixSrc& src, const MatrixDest& dest)\n\t    {\n\t\t// std::cout << \"nnz = \" << src.nnz() << \", dim1 = \" << dest.dim1() << \"\\n\";\n\t\treturn int(src.nnz() * 1.2 / dest.dim1());\n\t    }\n\t};\n\n\tstruct sum_of_sizes\n\t{\n\t    template <typename MatrixSrc, typename MatrixDest>\n\t    static inline int apply(const MatrixSrc& src, const MatrixDest& dest)\n\t    {\treturn int((src.nnz() + dest.nnz()) * 1.2 / dest.dim1()); }\n\t};\n\t    \t\n\t// Specialization for plus and minus\n\ttemplate <typename Value> struct copy_inserter_size< operations::update_plus<Value> > : sum_of_sizes {};\n\ttemplate <typename Value> struct copy_inserter_size< operations::update_minus<Value> > : sum_of_sizes {};\n\n    } // namespace detail\n\n\n    template <typename Updater, typename MatrixSrc, typename MatrixDest>\n    inline void gen_matrix_copy(const MatrixSrc& src, MatrixDest& dest, bool with_reset)\n    {\n\tvampir_trace<3002> tracer;\n\tMTL_THROW_IF(num_rows(src) != num_rows(dest) || num_cols(src) != num_cols(dest), incompatible_size());\n\n\tif (with_reset)\n\t    detail::zero_with_sparse_src(dest, traits::sparsity_flatcat<MatrixSrc>()); \n\t\n\ttypename traits::row<MatrixSrc>::type             row(src); \n\ttypename traits::col<MatrixSrc>::type             col(src); \n\ttypename traits::const_value<MatrixSrc>::type     value(src); \n\ttypedef typename traits::range_generator<tag::major, MatrixSrc>::type  cursor_type;\n\n\t// std::cout << \"Slot size is \" << detail::copy_inserter_size<Updater>::apply(src, dest) << \"\\n\";\n\tmat::inserter<MatrixDest, Updater>   ins(dest, detail::copy_inserter_size<Updater>::apply(src, dest));\n\tfor (cursor_type cursor = mtl::begin<tag::major>(src), cend = mtl::end<tag::major>(src); \n\t     cursor != cend; ++cursor) {\n\t    // std::cout << dest << '\\n';\n\t    \n\t    typedef typename traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\t    for (icursor_type icursor = mtl::begin<tag::nz>(cursor), icend = mtl::end<tag::nz>(cursor); \n\t\t icursor != icend; ++icursor) {\n\t\t//std::cout << \"in \" << row(*icursor) << \", \" << col(*icursor) << \" insert \" << value(*icursor) << '\\n';\n\t\tins(row(*icursor), col(*icursor)) << value(*icursor); }\n\t}\n    }\n\n    // Specialization for multi_vector\n    template <typename Updater, typename MatrixSrc, typename Vector>\n    inline void gen_matrix_copy(const MatrixSrc& src, mtl::mat::multi_vector<Vector>& dest, bool)\n    {\n\tMTL_THROW_IF(num_rows(src) != num_rows(dest) || num_cols(src) != num_cols(dest), incompatible_size());\n\ttypedef typename mtl::traits::updater_to_assigner<Updater>::type Assigner;\n\n\tfor (std::size_t i= 0, n= num_cols(src); i < n; ++i)\n\t    Assigner::first_update(dest.vector(i), src.vector(i));\n    }\n\n    namespace {\n#    ifdef __clang__\n#     pragma clang diagnostic ignored \"-Wunneeded-internal-declaration\"\n#     pragma clang diagnostic ignored \"-Wunused-function\"\n#    endif\n\t\ttemplate <typename T>\n\t\tinline T inc_wo_over(T i) \n\t\t{ return i == std::numeric_limits<T>::max() ? i : i+1; }\n\n\t\ttemplate <typename T>\n\t\tinline T negate_wo_over(T i) \n\t\t{ return i == std::numeric_limits<T>::min() ? std::numeric_limits<T>::max() : -i; }\n    }\n\n    template <typename Updater, typename ValueSrc, typename Para, typename ValueDest>\n    typename boost::enable_if<boost::is_same<Updater, operations::update_store<ValueDest> > >::type\n    inline gen_matrix_copy(const mat::banded_view<mtl::mat::compressed2D<ValueSrc, Para> >& src, mtl::mat::compressed2D<ValueDest, Para>& dest, bool)\n    {\n\tvampir_trace<3061> tracer;\n\ttypedef typename Para::size_type size_type;\n\tdest.change_dim(num_rows(src), num_cols(src)); // contains make_empty\n\tset_to_zero(dest);\n\tconst mtl::mat::compressed2D<ValueSrc, Para>  &sref= src.ref;\n\tconst std::vector<size_type>        &sstarts= sref.ref_major(), &sindices= sref.ref_minor();\n\tlong first, last;\n\tif (traits::is_row_major<Para>::value) {\n\t    first= src.get_begin();\n\t    last= src.get_end();\n\t} else {\n\t    first= inc_wo_over(negate_wo_over(src.get_end()));\n\t    last=  inc_wo_over(negate_wo_over(src.get_begin()));\n\t}\n\n\tlong jd= 0, j_end= long(sstarts[0]);\n\tfor (long i= 0, i_end= long(src.dim1()), f= first, l= last; i < i_end; ++i) {\n\t    dest.ref_major()[i]= jd;\n\t    long j= j_end;\n\t    j_end= long(sstarts[i+1]);\n\t    while (j < j_end && long(sindices[j]) < f) j++;\n\t    while (j < j_end && long(sindices[j]) < l) jd++, j++;\n\t    f= inc_wo_over(f);\n\t    l= inc_wo_over(l);\n\t}\n\tdest.ref_major()[src.dim1()]= jd;\n\tdest.set_nnz(jd); // resizes indices and data\n\n\tfor (long i= 0, i_end= long(src.dim1()), jd= 0, j_end= long(sstarts[0]); i < i_end; ++i) {\n\t    dest.ref_major()[i]= jd;\n\t    long j= j_end;\n\t    j_end= long(sstarts[i+1]);\n\t    while (j < j_end && long(sindices[j]) < first) j++;\n\t    while (j < j_end && long(sindices[j]) < last) {\n\t\tdest.ref_minor()[jd]= sindices[j];\n\t\tdest.data[jd++]= sref.data[j++];\n\t    }\n\t    first= inc_wo_over(first);\n\t    last= inc_wo_over(last);\t    \n\t}\n    }\n\n\t    \n    /// Copy matrix \\p src into matrix \\p dest\n    template <typename MatrixSrc, typename MatrixDest>\n    inline void matrix_copy(const MatrixSrc& src, MatrixDest& dest)\n    {\n\tgen_matrix_copy< operations::update_store<typename MatrixDest::value_type> >(src, dest, true);\n    }\n    \n\n    /// Add matrix \\p src to matrix \\p dest in copy-like style\n    template <typename MatrixSrc, typename MatrixDest>\n    inline void matrix_copy_plus(const MatrixSrc& src, MatrixDest& dest)\n    {\n\tgen_matrix_copy< operations::update_plus<typename MatrixDest::value_type> >(src, dest, false);\n    }\n\t\n    /// Subtract matrix \\p src from matrix \\p dest in copy-like style\n    template <typename MatrixSrc, typename MatrixDest>\n    inline void matrix_copy_minus(const MatrixSrc& src, MatrixDest& dest)\n    {\n\tgen_matrix_copy< operations::update_minus<typename MatrixDest::value_type> >(src, dest, false);\n    }\n\t\n    /// Multiply matrix \\p src element-wise with matrix \\p dest in copy-like style\n    template <typename MatrixSrc, typename MatrixDest>\n    inline void matrix_copy_ele_times(const MatrixSrc& src, MatrixDest& dest)\n    {\n\tvampir_trace<3001> tracer;\n\tMTL_THROW_IF(num_rows(src) != num_rows(dest) || num_cols(src) != num_cols(dest), incompatible_size());\n\n\ttypename traits::row<MatrixDest>::type             row(dest); \n\ttypename traits::col<MatrixDest>::type             col(dest); \n\ttypename traits::value<MatrixDest>::type           value(dest); \n\ttypedef typename traits::range_generator<tag::major, MatrixDest>::type  cursor_type;\n\ttypedef typename traits::range_generator<tag::nz, cursor_type>::type icursor_type;\n\t\n\tfor (cursor_type cursor = begin<tag::major>(dest), cend = end<tag::major>(dest); cursor != cend; ++cursor)\n\t    for (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor)\n\t\tvalue(*icursor, value(*icursor) * src[row(*icursor)][col(*icursor)]);\n#if 0   // copy would result in a*0 = a and 0*b = b!!!!\n\tgen_matrix_copy< operations::update_times<typename MatrixDest::value_type> >(src, dest, false);\n#endif\n\tcrop(dest);\n    }\n\n       \n    template <typename MatrixSrc, typename MatrixDest>\n    inline void copy(const MatrixSrc& src, tag::flat<tag::matrix>, MatrixDest& dest, tag::flat<tag::matrix>)\n\t// inline void copy(const MatrixSrc& src, tag::matrix_expr, MatrixDest& dest, tag::matrix)\n    {\n\treturn matrix_copy(src, dest);\n    }\n\n  \n\n    template <typename Updater, typename VectorSrc, typename VectorDest>\n    inline void gen_vector_copy(const VectorSrc& src, VectorDest& dest, bool with_reset)\n    {\n\t// Works only with dense vectors as dest !!!!! (source could be sparse)\n\t// Needs vector inserter\n\tvampir_trace<2001> tracer;\n\n\tMTL_STATIC_ASSERT((boost::is_same<typename ashape::ashape<VectorSrc>::type,\n\t\t\t\t\t  typename ashape::ashape<VectorDest>::type>::value), \"Source and target must have the same algebraic shape.\");\n\n\tMTL_THROW_IF(size(src) != size(dest), incompatible_size());\n\n\tif (with_reset)\n\t    detail::zero_with_sparse_src(dest, typename traits::category<VectorSrc>::type());\n\t\n\ttypename traits::index<VectorSrc>::type           index(src); \n\ttypename traits::const_value<VectorSrc>::type     value(src); \n\n\ttypedef typename traits::range_generator<tag::nz, VectorSrc>::type  cursor_type;\n\tfor (cursor_type cursor = begin<tag::nz>(src), cend = end<tag::nz>(src); \n\t     cursor != cend; ++cursor)\n\t    Updater()(dest[index(*cursor)], value(*cursor));\n    }\n\t    \n    /// Copy vector \\p src into vector \\p dest\n    template <typename VectorSrc, typename VectorDest>\n    inline void vector_copy(const VectorSrc& src, VectorDest& dest)\n    {\n\tgen_vector_copy< operations::update_store<typename VectorDest::value_type> >(src, dest, true);\n    }\n    \n\n    /// Add vector \\p src to vector \\p dest in copy-like style\n    template <typename VectorSrc, typename VectorDest>\n    inline void vector_copy_plus(const VectorSrc& src, VectorDest& dest)\n    {\n\tgen_vector_copy< operations::update_plus<typename VectorDest::value_type> >(src, dest, false);\n    }\n\t\n    /// Subtract vector \\p src from vector \\p dest in copy-like style\n    template <typename VectorSrc, typename VectorDest>\n    inline void vector_copy_minus(const VectorSrc& src, VectorDest& dest)\n    {\n\tgen_vector_copy< operations::update_minus<typename VectorDest::value_type> >(src, dest, false);\n    }\n\t\n\n       \n    template <typename VectorSrc, typename VectorDest>\n    inline void copy(const VectorSrc& src, tag::flat<tag::vector>, VectorDest& dest, tag::flat<tag::vector>)\t\n    {\n\treturn vector_copy(src, dest);\n    }\n\n\n    template <typename CollSrc, typename CollDest>\n    inline void copy(const CollSrc& src, CollDest& dest)\n    {\n\tvampir_trace<3003> tracer;\n\treturn copy(src, traits::flatcat2<CollSrc, tag::matrix, tag::vector>(),\n\t\t    dest, traits::flatcat2<CollDest, tag::matrix, tag::vector>());\n    }\n\n\n} // namespace mtl\n\n#endif // MTL_COPY_INCLUDE\n", "meta": {"hexsha": "51e533255bc7158b489f4b0c0289699c6e8f10d0", "size": 12011, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/copy.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/operation/copy.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/operation/copy.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": 39.3803278689, "max_line_length": 149, "alphanum_fraction": 0.6919490467, "num_tokens": 3155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894545235253, "lm_q2_score": 0.044018652998225924, "lm_q1q2_score": 0.014728177095536752}}
{"text": "#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP\n#define STAN_IO_ARRAY_VAR_CONTEXT_HPP\n\n#include <stan/util/io/var_context.hpp>\n#include <boost/throw_exception.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <utility>\n\nnamespace stan {\n\n  namespace io {\n\n    template<typename T>\n    T product(std::vector<T> dims) {\n      T y = 1;\n      for (size_t i = 0; i < dims.size(); ++i)\n        y *= dims[i];\n      return y;\n    }\n\n    /**\n     * An array_var_context object represents a named arrays\n     * with dimensions constructed from an array, a vector\n     * of names, and a vector of all dimensions for each element.\n     */\n    class array_var_context : public var_context {\n    private:\n      std::map<std::string,\n               std::pair<std::vector<double>,\n                         std::vector<size_t> > > vars_r_;\n      std::map<std::string,\n               std::pair<std::vector<int>,\n                         std::vector<size_t> > > vars_i_;\n      std::vector<double> const empty_vec_r_;\n      std::vector<int> const empty_vec_i_;\n      std::vector<size_t> const empty_vec_ui_;\n\n      bool contains_r_only(const std::string& name) const {\n        return vars_r_.find(name) != vars_r_.end();\n      }\n\n      /**\n       * Check (1) if the vector size of dimensions is no smaller\n       * than the name vector size; (2) if the size of the input\n       * array is large enough for what is needed.\n       */\n      template <typename T>\n      void validate(const std::vector<std::string>& names,\n                    const T& array,\n                    const std::vector<std::vector<size_t> >& dims) {\n        size_t total = 0;\n        size_t num_par = names.size();\n        if (num_par > dims.size()) {\n          std::stringstream msg;\n          msg << \"size of vector of dimensions (found \" << dims.size() << \") \"\n              << \"should be no smaller than number of parameters (found \"\n              << num_par << \").\";\n          BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n        }\n        for (size_t i = 0; i < num_par; i++)\n          total += stan::io::product(dims[i]);\n        size_t array_len = array.size();\n        if (total > array_len) {\n          std::stringstream msg;\n          msg << \"array is not long enough for all elements: \" << array_len\n              << \" is found, but \"\n              << total << \" is needed.\";\n          BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n        }\n      }\n\n      void add_r(const std::vector<std::string>& names,\n                 const std::vector<double>& values,\n                 const std::vector<std::vector<size_t> >& dims) {\n        validate(names, values, dims);\n        size_t start = 0;\n        size_t end = 0;\n        for (size_t i = 0; i < names.size(); i++) {\n          end += product(dims[i]);\n          std::vector<double> v(values.begin() + start, values.begin() + end);\n          vars_r_[names[i]]\n            = std::pair<std::vector<double>,\n                        std::vector<size_t> >(v, dims[i]);\n          start = end;\n        }\n      }\n\n      void add_r(const std::vector<std::string>& names,\n                 const Eigen::VectorXd& values,\n                 const std::vector<std::vector<size_t> >& dims) {\n        validate(names, values, dims);\n        size_t start = 0;\n        size_t end = 0;\n        for (size_t i = 0; i < names.size(); i++) {\n          end += product(dims[i]);\n          size_t v_len = end - start;\n          std::vector<double> v(v_len);\n          for (size_t i = 0; i < v_len; ++i)\n            v[i] = values(start + i);\n          vars_r_[names[i]]\n            = std::pair<std::vector<double>,\n                        std::vector<size_t> >(v, dims[i]);\n          start = end;\n        }\n      }\n\n      void add_i(const std::vector<std::string>& names,\n                 const std::vector<int>& values,\n                 const std::vector<std::vector<size_t> >& dims) {\n        validate(names, values, dims);\n        size_t start = 0;\n        size_t end = 0;\n        for (size_t i = 0; i < names.size(); i++) {\n          end += product(dims[i]);\n          std::vector<int> v(values.begin() + start, values.begin() + end);\n          vars_i_[names[i]]\n            = std::pair<std::vector<int>,\n                        std::vector<size_t> >(v, dims[i]);\n          start = end;\n        }\n      }\n\n    public:\n      /**\n       * Construct an array_var_context from only real value arrays.\n       *\n       * @param names_r  names for each element\n       * @param values_r a vector of double values for all elements\n       * @param dim_r   a vector of dimensions\n       */\n      array_var_context(const std::vector<std::string>& names_r,\n                        const std::vector<double>& values_r,\n                        const std::vector<std::vector<size_t> >& dim_r) {\n        add_r(names_r, values_r, dim_r);\n      }\n\n      /**\n       * Construct an array_var_context from an Eigen::RowVectorXd.\n       *\n       * @param names_r  names for each element\n       * @param values_r an Eigen RowVector double values for all elements\n       * @param dim_r   a vector of dimensions\n       */\n      array_var_context(const std::vector<std::string>& names_r,\n                        const Eigen::RowVectorXd& values_r,\n                        const std::vector<std::vector<size_t> >& dim_r) {\n        add_r(names_r, values_r, dim_r);\n      }\n\n      /**\n       * Construct an array_var_context from only integer value arrays.\n       *\n       * @param names_i  names for each element\n       * @param values_i a vector of integer values for all elements\n       * @param dim_i   a vector of dimensions\n       */\n      array_var_context(const std::vector<std::string>& names_i,\n                        const std::vector<int>& values_i,\n                        const std::vector<std::vector<size_t> >& dim_i) {\n        add_i(names_i, values_i, dim_i);\n      }\n\n      /**\n       * Construct an array_var_context from arrays of both double\n       * and integer separately\n       *\n       */\n      array_var_context(const std::vector<std::string>& names_r,\n                        const std::vector<double>& values_r,\n                        const std::vector<std::vector<size_t> >& dim_r,\n                        const std::vector<std::string>& names_i,\n                        const std::vector<int>& values_i,\n                        const std::vector<std::vector<size_t> >& dim_i) {\n        add_i(names_i, values_i, dim_i);\n        add_r(names_r, values_r, dim_r);\n      }\n\n      /**\n       * Return <code>true</code> if this dump contains the specified\n       * variable name is defined. This method returns <code>true</code>\n       * even if the values are all integers.\n       *\n       * @param name Variable name to test.\n       * @return <code>true</code> if the variable exists.\n       */\n      bool contains_r(const std::string& name) const {\n        return contains_r_only(name) || contains_i(name);\n      }\n\n      /**\n       * Return <code>true</code> if this dump contains an integer\n       * valued array with the specified name.\n       *\n       * @param name Variable name to test.\n       * @return <code>true</code> if the variable name has an integer\n       * array value.\n       */\n      bool contains_i(const std::string& name) const {\n        return vars_i_.find(name) != vars_i_.end();\n      }\n\n      /**\n       * Return the double values for the variable with the specified\n       * name or null.\n       *\n       * @param name Name of variable.\n       * @return Values of variable.\n       */\n      std::vector<double> vals_r(const std::string& name) const {\n        if (contains_r_only(name)) {\n          return (vars_r_.find(name)->second).first;\n        } else if (contains_i(name)) {\n          std::vector<int> vec_int = (vars_i_.find(name)->second).first;\n          std::vector<double> vec_r(vec_int.size());\n          for (size_t ii = 0; ii < vec_int.size(); ii++) {\n            vec_r[ii] = vec_int[ii];\n          }\n          return vec_r;\n        }\n        return empty_vec_r_;\n      }\n\n      /**\n       * Return the dimensions for the double variable with the specified\n       * name.\n       *\n       * @param name Name of variable.\n       * @return Dimensions of variable.\n       */\n      std::vector<size_t> dims_r(const std::string& name) const {\n        if (contains_r_only(name)) {\n          return (vars_r_.find(name)->second).second;\n        } else if (contains_i(name)) {\n          return (vars_i_.find(name)->second).second;\n        }\n        return empty_vec_ui_;\n      }\n\n      /**\n       * Return the integer values for the variable with the specified\n       * name.\n       *\n       * @param name Name of variable.\n       * @return Values.\n       */\n      std::vector<int> vals_i(const std::string& name) const {\n        if (contains_i(name)) {\n          return (vars_i_.find(name)->second).first;\n        }\n        return empty_vec_i_;\n      }\n\n      /**\n       * Return the dimensions for the integer variable with the specified\n       * name.\n       *\n       * @param name Name of variable.\n       * @return Dimensions of variable.\n       */\n      std::vector<size_t> dims_i(const std::string& name) const {\n        if (contains_i(name)) {\n          return (vars_i_.find(name)->second).second;\n        }\n        return empty_vec_ui_;\n      }\n\n      /**\n       * Return a list of the names of the floating point variables in\n       * the dump.\n       *\n       * @param names Vector to store the list of names in.\n       */\n      virtual void names_r(std::vector<std::string>& names) const {\n        names.resize(0);\n        for (std::map<std::string,\n                      std::pair<std::vector<double>,\n                                std::vector<size_t> > >\n                 ::const_iterator it = vars_r_.begin();\n             it != vars_r_.end(); ++it)\n          names.push_back((*it).first);\n      }\n\n      /**\n       * Return a list of the names of the integer variables in\n       * the dump.\n       *\n       * @param names Vector to store the list of names in.\n       */\n      virtual void names_i(std::vector<std::string>& names) const {\n        names.resize(0);\n        for (std::map<std::string,\n                      std::pair<std::vector<int>,\n                                std::vector<size_t> > >\n                 ::const_iterator it = vars_i_.begin();\n             it != vars_i_.end(); ++it)\n          names.push_back((*it).first);\n      }\n\n      /**\n       * Remove variable from the object.\n       *\n       * @param name Name of the variable to remove.\n       * @return If variable is removed returns <code>true</code>, else\n       *   returns <code>false</code>.\n       */\n      bool remove(const std::string& name) {\n        return (vars_i_.erase(name) > 0)\n          || (vars_r_.erase(name) > 0);\n      }\n    };\n  }\n}\n#endif\n", "meta": {"hexsha": "73cbc17a2b948051b0a56e6c67add9bc118ea784", "size": 10862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/util/io/array_var_context.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/util/io/array_var_context.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/util/io/array_var_context.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1572327044, "max_line_length": 78, "alphanum_fraction": 0.536089118, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.035144842737414125, "lm_q1q2_score": 0.014715037033946946}}
{"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// std_real_concept is an archetype for built-in Real types.\n\n// The main purpose in providing this type is to verify\n// that std lib functions are found via a using declaration\n// bringing those functions into the current scope, and not\n// just because they happen to be in global scope.\n//\n// If ::pow is found rather than std::pow say, then the code\n// will silently compile, but truncation of long doubles to\n// double will cause a significant loss of precision.\n// A template instantiated with std_real_concept will *only*\n// compile if it std::whatever is in scope.\n\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n\n#include <ostream>\n#include <istream>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <math.h> // fmodl\n\n#ifndef BOOST_MATH_STD_REAL_CONCEPT_HPP\n#define BOOST_MATH_STD_REAL_CONCEPT_HPP\n\nnamespace boost{ namespace math{\n\nnamespace concepts\n{\n\n#ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   typedef double std_real_concept_base_type;\n#else\n   typedef long double std_real_concept_base_type;\n#endif\n\nclass std_real_concept\n{\npublic:\n   // Constructors:\n   std_real_concept() : m_value(0){}\n   std_real_concept(char c) : m_value(c){}\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n   std_real_concept(wchar_t c) : m_value(c){}\n#endif\n   std_real_concept(unsigned char c) : m_value(c){}\n   std_real_concept(signed char c) : m_value(c){}\n   std_real_concept(unsigned short c) : m_value(c){}\n   std_real_concept(short c) : m_value(c){}\n   std_real_concept(unsigned int c) : m_value(c){}\n   std_real_concept(int c) : m_value(c){}\n   std_real_concept(unsigned long c) : m_value(c){}\n   std_real_concept(long c) : m_value(c){}\n#if defined(__DECCXX) || defined(__SUNPRO_CC)\n   std_real_concept(unsigned long long c) : m_value(static_cast<std_real_concept_base_type>(c)){}\n   std_real_concept(long long c) : m_value(static_cast<std_real_concept_base_type>(c)){}\n#elif defined(BOOST_HAS_LONG_LONG)\n   std_real_concept(boost::ulong_long_type c) : m_value(static_cast<std_real_concept_base_type>(c)){}\n   std_real_concept(boost::long_long_type c) : m_value(static_cast<std_real_concept_base_type>(c)){}\n#endif\n   std_real_concept(float c) : m_value(c){}\n   std_real_concept(double c) : m_value(c){}\n   std_real_concept(long double c) : m_value(c){}\n#ifdef BOOST_MATH_USE_FLOAT128\n   std_real_concept(BOOST_MATH_FLOAT128_TYPE c) : m_value(c){}\n#endif\n\n   // Assignment:\n   std_real_concept& operator=(char c) { m_value = c; return *this; }\n   std_real_concept& operator=(unsigned char c) { m_value = c; return *this; }\n   std_real_concept& operator=(signed char c) { m_value = c; return *this; }\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n   std_real_concept& operator=(wchar_t c) { m_value = c; return *this; }\n#endif\n   std_real_concept& operator=(short c) { m_value = c; return *this; }\n   std_real_concept& operator=(unsigned short c) { m_value = c; return *this; }\n   std_real_concept& operator=(int c) { m_value = c; return *this; }\n   std_real_concept& operator=(unsigned int c) { m_value = c; return *this; }\n   std_real_concept& operator=(long c) { m_value = c; return *this; }\n   std_real_concept& operator=(unsigned long c) { m_value = c; return *this; }\n#if defined(__DECCXX) || defined(__SUNPRO_CC)\n   std_real_concept& operator=(unsigned long long c) { m_value = static_cast<std_real_concept_base_type>(c); return *this; }\n   std_real_concept& operator=(long long c) { m_value = static_cast<std_real_concept_base_type>(c); return *this; }\n#elif defined(BOOST_HAS_LONG_LONG)\n   std_real_concept& operator=(boost::long_long_type c) { m_value = static_cast<std_real_concept_base_type>(c); return *this; }\n   std_real_concept& operator=(boost::ulong_long_type c) { m_value = static_cast<std_real_concept_base_type>(c); return *this; }\n#endif\n   std_real_concept& operator=(float c) { m_value = c; return *this; }\n   std_real_concept& operator=(double c) { m_value = c; return *this; }\n   std_real_concept& operator=(long double c) { m_value = c; return *this; }\n\n   // Access:\n   std_real_concept_base_type value()const{ return m_value; }\n\n   // Member arithmetic:\n   std_real_concept& operator+=(const std_real_concept& other)\n   { m_value += other.value(); return *this; }\n   std_real_concept& operator-=(const std_real_concept& other)\n   { m_value -= other.value(); return *this; }\n   std_real_concept& operator*=(const std_real_concept& other)\n   { m_value *= other.value(); return *this; }\n   std_real_concept& operator/=(const std_real_concept& other)\n   { m_value /= other.value(); return *this; }\n   std_real_concept operator-()const\n   { return -m_value; }\n   std_real_concept const& operator+()const\n   { return *this; }\n\nprivate:\n   std_real_concept_base_type m_value;\n};\n\n// Non-member arithmetic:\ninline std_real_concept operator+(const std_real_concept& a, const std_real_concept& b)\n{\n   std_real_concept result(a);\n   result += b;\n   return result;\n}\ninline std_real_concept operator-(const std_real_concept& a, const std_real_concept& b)\n{\n   std_real_concept result(a);\n   result -= b;\n   return result;\n}\ninline std_real_concept operator*(const std_real_concept& a, const std_real_concept& b)\n{\n   std_real_concept result(a);\n   result *= b;\n   return result;\n}\ninline std_real_concept operator/(const std_real_concept& a, const std_real_concept& b)\n{\n   std_real_concept result(a);\n   result /= b;\n   return result;\n}\n\n// Comparison:\ninline bool operator == (const std_real_concept& a, const std_real_concept& b)\n{ return a.value() == b.value(); }\ninline bool operator != (const std_real_concept& a, const std_real_concept& b)\n{ return a.value() != b.value();}\ninline bool operator < (const std_real_concept& a, const std_real_concept& b)\n{ return a.value() < b.value(); }\ninline bool operator <= (const std_real_concept& a, const std_real_concept& b)\n{ return a.value() <= b.value(); }\ninline bool operator > (const std_real_concept& a, const std_real_concept& b)\n{ return a.value() > b.value(); }\ninline bool operator >= (const std_real_concept& a, const std_real_concept& b)\n{ return a.value() >= b.value(); }\n\n} // namespace concepts\n} // namespace math\n} // namespace boost\n\nnamespace std{\n\n// Non-member functions:\ninline boost::math::concepts::std_real_concept acos(boost::math::concepts::std_real_concept a)\n{ return std::acos(a.value()); }\ninline boost::math::concepts::std_real_concept cos(boost::math::concepts::std_real_concept a)\n{ return std::cos(a.value()); }\ninline boost::math::concepts::std_real_concept asin(boost::math::concepts::std_real_concept a)\n{ return std::asin(a.value()); }\ninline boost::math::concepts::std_real_concept atan(boost::math::concepts::std_real_concept a)\n{ return std::atan(a.value()); }\ninline boost::math::concepts::std_real_concept atan2(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\n{ return std::atan2(a.value(), b.value()); }\ninline boost::math::concepts::std_real_concept ceil(boost::math::concepts::std_real_concept a)\n{ return std::ceil(a.value()); }\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline boost::math::concepts::std_real_concept fmod(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\n{ return fmodl(a.value(), b.value()); }\n#else\ninline boost::math::concepts::std_real_concept fmod(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\n{ return std::fmod(a.value(), b.value()); }\n#endif\ninline boost::math::concepts::std_real_concept cosh(boost::math::concepts::std_real_concept a)\n{ return std::cosh(a.value()); }\ninline boost::math::concepts::std_real_concept exp(boost::math::concepts::std_real_concept a)\n{ return std::exp(a.value()); }\ninline boost::math::concepts::std_real_concept fabs(boost::math::concepts::std_real_concept a)\n{ return std::fabs(a.value()); }\ninline boost::math::concepts::std_real_concept abs(boost::math::concepts::std_real_concept a)\n{ return std::abs(a.value()); }\ninline boost::math::concepts::std_real_concept floor(boost::math::concepts::std_real_concept a)\n{ return std::floor(a.value()); }\ninline boost::math::concepts::std_real_concept modf(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept* ipart)\n{\n   boost::math::concepts::std_real_concept_base_type ip;\n   boost::math::concepts::std_real_concept_base_type result = std::modf(a.value(), &ip);\n   *ipart = ip;\n   return result;\n}\ninline boost::math::concepts::std_real_concept frexp(boost::math::concepts::std_real_concept a, int* expon)\n{ return std::frexp(a.value(), expon); }\ninline boost::math::concepts::std_real_concept ldexp(boost::math::concepts::std_real_concept a, int expon)\n{ return std::ldexp(a.value(), expon); }\ninline boost::math::concepts::std_real_concept log(boost::math::concepts::std_real_concept a)\n{ return std::log(a.value()); }\ninline boost::math::concepts::std_real_concept log10(boost::math::concepts::std_real_concept a)\n{ return std::log10(a.value()); }\ninline boost::math::concepts::std_real_concept tan(boost::math::concepts::std_real_concept a)\n{ return std::tan(a.value()); }\ninline boost::math::concepts::std_real_concept pow(boost::math::concepts::std_real_concept a, boost::math::concepts::std_real_concept b)\n{ return std::pow(a.value(), b.value()); }\n#if !defined(__SUNPRO_CC)\ninline boost::math::concepts::std_real_concept pow(boost::math::concepts::std_real_concept a, int b)\n{ return std::pow(a.value(), b); }\n#else\ninline boost::math::concepts::std_real_concept pow(boost::math::concepts::std_real_concept a, int b)\n{ return std::pow(a.value(), static_cast<long double>(b)); }\n#endif\ninline boost::math::concepts::std_real_concept sin(boost::math::concepts::std_real_concept a)\n{ return std::sin(a.value()); }\ninline boost::math::concepts::std_real_concept sinh(boost::math::concepts::std_real_concept a)\n{ return std::sinh(a.value()); }\ninline boost::math::concepts::std_real_concept sqrt(boost::math::concepts::std_real_concept a)\n{ return std::sqrt(a.value()); }\ninline boost::math::concepts::std_real_concept tanh(boost::math::concepts::std_real_concept a)\n{ return std::tanh(a.value()); }\n\n} // namespace std\n\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/precision.hpp>\n\nnamespace boost{ namespace math{ namespace concepts{\n\n//\n// Conversion and truncation routines:\n//\ntemplate <class Policy>\ninline int iround(const concepts::std_real_concept& v, const Policy& pol)\n{\n   return boost::math::iround(v.value(), pol);\n}\ninline int iround(const concepts::std_real_concept& v)\n{\n   return boost::math::iround(v.value(), policies::policy<>());\n}\n\ntemplate <class Policy>\ninline long lround(const concepts::std_real_concept& v, const Policy& pol)\n{\n   return boost::math::lround(v.value(), pol);\n}\ninline long lround(const concepts::std_real_concept& v)\n{\n   return boost::math::lround(v.value(), policies::policy<>());\n}\n\n#ifdef BOOST_HAS_LONG_LONG\n\ntemplate <class Policy>\ninline boost::long_long_type llround(const concepts::std_real_concept& v, const Policy& pol)\n{\n   return boost::math::llround(v.value(), pol);\n}\ninline boost::long_long_type llround(const concepts::std_real_concept& v)\n{\n   return boost::math::llround(v.value(), policies::policy<>());\n}\n\n#endif\n\ntemplate <class Policy>\ninline int itrunc(const concepts::std_real_concept& v, const Policy& pol)\n{\n   return boost::math::itrunc(v.value(), pol);\n}\ninline int itrunc(const concepts::std_real_concept& v)\n{\n   return boost::math::itrunc(v.value(), policies::policy<>());\n}\n\ntemplate <class Policy>\ninline long ltrunc(const concepts::std_real_concept& v, const Policy& pol)\n{\n   return boost::math::ltrunc(v.value(), pol);\n}\ninline long ltrunc(const concepts::std_real_concept& v)\n{\n   return boost::math::ltrunc(v.value(), policies::policy<>());\n}\n\n#ifdef BOOST_HAS_LONG_LONG\n\ntemplate <class Policy>\ninline boost::long_long_type lltrunc(const concepts::std_real_concept& v, const Policy& pol)\n{\n   return boost::math::lltrunc(v.value(), pol);\n}\ninline boost::long_long_type lltrunc(const concepts::std_real_concept& v)\n{\n   return boost::math::lltrunc(v.value(), policies::policy<>());\n}\n\n#endif\n\n// Streaming:\ntemplate <class charT, class traits>\ninline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const std_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, std_real_concept& a)\n{\n#if defined(__SGI_STL_PORT) || defined(_RWSTD_VER) || defined(__LIBCOMO__) || defined(_LIBCPP_VERSION)\n   std::string s;\n   std_real_concept_base_type d;\n   is >> s;\n   std::sscanf(s.c_str(), \"%Lf\", &d);\n   a = d;\n   return is;\n#else\n   std_real_concept_base_type v;\n   is >> v;\n   a = v;\n   return is;\n#endif\n}\n\n} // namespace concepts\n}}\n\n#include <boost/math/tools/precision.hpp>\n#include <boost/math/tools/big_constant.hpp>\n\nnamespace boost{ namespace math{\nnamespace tools\n{\n\ntemplate <>\ninline concepts::std_real_concept make_big_value<concepts::std_real_concept>(boost::floatmax_t val, const char*, mpl::false_ const&, mpl::false_ const&)\n{\n   return val;  // Can't use lexical_cast here, sometimes it fails....\n}\n\ntemplate <>\ninline concepts::std_real_concept max_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\n{\n   return max_value<concepts::std_real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::std_real_concept min_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\n{\n   return min_value<concepts::std_real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::std_real_concept log_max_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\n{\n   return log_max_value<concepts::std_real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::std_real_concept log_min_value<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\n{\n   return log_min_value<concepts::std_real_concept_base_type>();\n}\n\ntemplate <>\ninline concepts::std_real_concept epsilon(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\n{\n   return tools::epsilon<concepts::std_real_concept_base_type>();\n}\n\ntemplate <>\ninline int digits<concepts::std_real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::std_real_concept))\n{ // Assume number of significand bits is same as std_real_concept_base_type,\n  // unless std::numeric_limits<T>::is_specialized to provide digits.\n   return digits<concepts::std_real_concept_base_type>();\n}\n\n} // namespace tools\n\n#if BOOST_WORKAROUND(BOOST_MSVC, <= 1310)\nusing concepts::itrunc;\nusing concepts::ltrunc;\nusing concepts::lltrunc;\nusing concepts::iround;\nusing concepts::lround;\nusing concepts::llround;\n#endif\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_STD_REAL_CONCEPT_HPP\n\n\n\n\n", "meta": {"hexsha": "b4f75bcadba62ff0047420b3829252313fa66a10", "size": 15289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/math/concepts/std_real_concept.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/math/concepts/std_real_concept.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/math/concepts/std_real_concept.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": 37.657635468, "max_line_length": 152, "alphanum_fraction": 0.74537249, "num_tokens": 4075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.045352581522041274, "lm_q1q2_score": 0.014704912956910116}}
{"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 *      120521    T. Secretin       File created.\n *      130318    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 *\n */\n\n#include <stdexcept>\n\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/cartesianStateExtractor.h\"\n\nnamespace tudat\n{\nnamespace ephemerides\n{\n\nboost::shared_ptr< basic_mathematics::Vector6d > CartesianStateExtractor::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 CartesianElements object.\n    boost::shared_ptr< Vector6d > cartesianElements\n            = boost::allocate_shared< Vector6d >( Eigen::aligned_allocator< Vector6d >( ) );\n\n    // Find and set Cartesian x coordinate.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::cartesianXCoordinate ) )\n    {\n        ( *cartesianElements )( orbital_element_conversions::xCartesianPositionIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::cartesianXCoordinate );\n    }\n\n    else\n    {\n        boost::throw_exception( boost::enable_error_info(\n                                 std::runtime_error(\n                                        \"No Cartesian x coordinate entry found.\" ) ) );\n    }\n\n    // Find and set Cartesian y coordinate.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::cartesianYCoordinate ) )\n    {\n        ( *cartesianElements )( orbital_element_conversions::yCartesianPositionIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::cartesianYCoordinate );\n    }\n\n    else\n    {\n        boost::throw_exception( boost::enable_error_info(\n                                 std::runtime_error( \"No Cartesian y coordinate entry found.\" ) ) );\n    }\n\n    // Find and set Cartesian z coordinate.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::cartesianZCoordinate ) )\n    {\n        ( *cartesianElements )( orbital_element_conversions::zCartesianPositionIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::cartesianZCoordinate );\n    }\n\n    else\n    {\n        boost::throw_exception( boost::enable_error_info(\n                                 std::runtime_error(\n                                        \"No Cartesian z coordinate entry found.\" ) ) );\n    }\n\n    // Find and set Cartesian x velocity.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::cartesianXVelocity ) )\n    {\n        ( *cartesianElements )( orbital_element_conversions::xCartesianVelocityIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::cartesianXVelocity );\n    }\n    else\n    {\n        boost::throw_exception( boost::enable_error_info(\n                                   std::runtime_error(\n                                        \"No Cartesian x velocity entry found.\" ) ) );\n    }\n\n    // Find and set Cartesian y velocity.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::cartesianYVelocity ) )\n    {\n        ( *cartesianElements )( orbital_element_conversions::yCartesianVelocityIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::cartesianYVelocity );\n    }\n\n    else\n    {\n        boost::throw_exception( boost::enable_error_info(\n                                   std::runtime_error(\n                                        \"No Cartesian y velocity entry found.\" ) ) );\n    }\n\n    // Find and set Cartesian z velocity.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::cartesianZVelocity ) )\n    {\n        ( *cartesianElements )( orbital_element_conversions::zCartesianVelocityIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::cartesianZVelocity );\n    }\n\n    else\n    {\n        boost::throw_exception( boost::enable_error_info(\n                                   std::runtime_error(\n                                        \"No Cartesian z velocity entry found.\" ) ) );\n    }\n\n    return cartesianElements;\n}\n\n} // namespace ephemerides\n} // namespace tudat\n", "meta": {"hexsha": "037a36fe84810af3727a4960c70334f7d0e81cb2", "size": 6778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Ephemerides/cartesianStateExtractor.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/cartesianStateExtractor.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/cartesianStateExtractor.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": 42.3625, "max_line_length": 100, "alphanum_fraction": 0.6345529655, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.03676946765888317, "lm_q1q2_score": 0.014700861193826908}}
{"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/startIdx.hpp\n * @brief Tools to access sub-elements of compound manifolds.\n */\n#ifndef GET_START_INDEX_H_\n#define GET_START_INDEX_H_\n\n#include <Eigen/Core>\n\n#include \"src/SubManifold.hpp\"\n#include \"src/vectview.hpp\"\n\nnamespace MTK {\n\n/**\n * \\defgroup SubManifolds Accessing Submanifolds\n * For compound manifolds constructed using MTK_BUILD_MANIFOLD, member pointers\n * can be used to get sub-vectors or matrix-blocks of a corresponding big matrix.\n * E.g. for a type @a pose consisting of @a orient and @a trans the member pointers\n * @c &pose::orient and @c &pose::trans give all required information and are still\n * valid if the base type gets extended or the actual types of @a orient and @a trans\n * change (e.g. from 2D to 3D).\n *\n * @todo Maybe require manifolds to typedef MatrixType and VectorType, etc.\n */\n//@{\n\n/**\n * Determine the index of a sub-variable within a compound variable.\n */\ntemplate <class Base, class T, int idx, int dim>\nint getStartIdx(MTK::SubManifold<T, idx, dim> Base::*) {\n    return idx;\n}\n\ntemplate <class Base, class T, int idx, int dim>\nint getStartIdx_(MTK::SubManifold<T, idx, dim> Base::*) {\n    return dim;\n}\n\n/**\n * Determine the degrees of freedom of a sub-variable within a compound variable.\n */\ntemplate <class Base, class T, int idx, int dim>\nint getDof(MTK::SubManifold<T, idx, dim> Base::*) {\n    return T::DOF;\n}\ntemplate <class Base, class T, int idx, int dim>\nint getDim(MTK::SubManifold<T, idx, dim> Base::*) {\n    return T::DIM;\n}\n\n/**\n * set the diagonal elements of a covariance matrix corresponding to a sub-variable\n */\ntemplate <class Base, class T, int idx, int dim>\nvoid setDiagonal(Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF>& cov, MTK::SubManifold<T, idx, dim> Base::*,\n                 const typename Base::scalar& val) {\n    cov.diagonal().template segment<T::DOF>(idx).setConstant(val);\n}\n\ntemplate <class Base, class T, int idx, int dim>\nvoid setDiagonal_(Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM>& cov,\n                  MTK::SubManifold<T, idx, dim> Base::*, const typename Base::scalar& val) {\n    cov.diagonal().template segment<T::DIM>(dim).setConstant(val);\n}\n\n/**\n * Get the subblock of corresponding to two members, i.e.\n * \\code\n *  Eigen::Matrix<double, Pose::DOF, Pose::DOF> m;\n *  MTK::subblock(m, &Pose::orient, &Pose::trans) = some_expression;\n *  MTK::subblock(m, &Pose::trans, &Pose::orient) = some_expression.trans();\n * \\endcode\n * lets you modify mixed covariance entries in a bigger covariance matrix.\n */\ntemplate <class Base, class T1, int idx1, int dim1, class T2, int idx2, int dim2>\ntypename MTK::internal::CovBlock<Base, T1, T2>::Type subblock(\n    Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF>& cov, MTK::SubManifold<T1, idx1, dim1> Base::*,\n    MTK::SubManifold<T2, idx2, dim2> Base::*) {\n    return cov.template block<T1::DOF, T2::DOF>(idx1, idx2);\n}\n\ntemplate <class Base, class T1, int idx1, int dim1, class T2, int idx2, int dim2>\ntypename MTK::internal::CovBlock_<Base, T1, T2>::Type subblock_(\n    Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM>& cov, MTK::SubManifold<T1, idx1, dim1> Base::*,\n    MTK::SubManifold<T2, idx2, dim2> Base::*) {\n    return cov.template block<T1::DIM, T2::DIM>(dim1, dim2);\n}\n\ntemplate <typename Base1, typename Base2, typename T1, typename T2, int idx1, int idx2, int dim1, int dim2>\ntypename MTK::internal::CrossCovBlock<Base1, Base2, T1, T2>::Type subblock(\n    Eigen::Matrix<typename Base1::scalar, Base1::DOF, Base2::DOF>& cov, MTK::SubManifold<T1, idx1, dim1> Base1::*,\n    MTK::SubManifold<T2, idx2, dim2> Base2::*) {\n    return cov.template block<T1::DOF, T2::DOF>(idx1, idx2);\n}\n\ntemplate <typename Base1, typename Base2, typename T1, typename T2, int idx1, int idx2, int dim1, int dim2>\ntypename MTK::internal::CrossCovBlock_<Base1, Base2, T1, T2>::Type subblock_(\n    Eigen::Matrix<typename Base1::scalar, Base1::DIM, Base2::DIM>& cov, MTK::SubManifold<T1, idx1, dim1> Base1::*,\n    MTK::SubManifold<T2, idx2, dim2> Base2::*) {\n    return cov.template block<T1::DIM, T2::DIM>(dim1, dim2);\n}\n/**\n * Get the subblock of corresponding to a member, i.e.\n * \\code\n *  Eigen::Matrix<double, Pose::DOF, Pose::DOF> m;\n *  MTK::subblock(m, &Pose::orient) = some_expression;\n * \\endcode\n * lets you modify covariance entries in a bigger covariance matrix.\n */\ntemplate <class Base, class T, int idx, int dim>\ntypename MTK::internal::CovBlock_<Base, T, T>::Type subblock_(\n    Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM>& cov, MTK::SubManifold<T, idx, dim> Base::*) {\n    return cov.template block<T::DIM, T::DIM>(dim, dim);\n}\n\ntemplate <class Base, class T, int idx, int dim>\ntypename MTK::internal::CovBlock<Base, T, T>::Type subblock(\n    Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF>& cov, MTK::SubManifold<T, idx, dim> Base::*) {\n    return cov.template block<T::DOF, T::DOF>(idx, idx);\n}\n\ntemplate <typename Base>\nclass get_cov {\n   public:\n    typedef Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF> type;\n    typedef const Eigen::Matrix<typename Base::scalar, Base::DOF, Base::DOF> const_type;\n};\n\ntemplate <typename Base>\nclass get_cov_ {\n   public:\n    typedef Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM> type;\n    typedef const Eigen::Matrix<typename Base::scalar, Base::DIM, Base::DIM> const_type;\n};\n\ntemplate <typename Base1, typename Base2>\nclass get_cross_cov {\n   public:\n    typedef Eigen::Matrix<typename Base1::scalar, Base1::DOF, Base2::DOF> type;\n    typedef const type const_type;\n};\n\ntemplate <typename Base1, typename Base2>\nclass get_cross_cov_ {\n   public:\n    typedef Eigen::Matrix<typename Base1::scalar, Base1::DIM, Base2::DIM> type;\n    typedef const type const_type;\n};\n\ntemplate <class Base, class T, int idx, int dim>\nvectview<typename Base::scalar, T::DIM> subvector_impl_(vectview<typename Base::scalar, Base::DIM> vec,\n                                                        SubManifold<T, idx, dim> Base::*) {\n    return vec.template segment<T::DIM>(dim);\n}\n\ntemplate <class Base, class T, int idx, int dim>\nvectview<typename Base::scalar, T::DOF> subvector_impl(vectview<typename Base::scalar, Base::DOF> vec,\n                                                       SubManifold<T, idx, dim> Base::*) {\n    return vec.template segment<T::DOF>(idx);\n}\n\n/**\n * Get the subvector corresponding to a sub-manifold from a bigger vector.\n */\ntemplate <class Scalar, int BaseDIM, class Base, class T, int idx, int dim>\nvectview<Scalar, T::DIM> subvector_(vectview<Scalar, BaseDIM> vec, SubManifold<T, idx, dim> Base::*ptr) {\n    return subvector_impl_(vec, ptr);\n}\n\ntemplate <class Scalar, int BaseDOF, class Base, class T, int idx, int dim>\nvectview<Scalar, T::DOF> subvector(vectview<Scalar, BaseDOF> vec, SubManifold<T, idx, dim> Base::*ptr) {\n    return subvector_impl(vec, ptr);\n}\n\n/**\n * @todo This should be covered already by subvector(vectview<typename Base::scalar,Base::DOF> vec,SubManifold<T,idx>\n * Base::*)\n */\ntemplate <class Scalar, int BaseDOF, class Base, class T, int idx, int dim>\nvectview<Scalar, T::DOF> subvector(Eigen::Matrix<Scalar, BaseDOF, 1>& vec, SubManifold<T, idx, dim> Base::*ptr) {\n    return subvector_impl(vectview<Scalar, BaseDOF>(vec), ptr);\n}\n\ntemplate <class Scalar, int BaseDIM, class Base, class T, int idx, int dim>\nvectview<Scalar, T::DIM> subvector_(Eigen::Matrix<Scalar, BaseDIM, 1>& vec, SubManifold<T, idx, dim> Base::*ptr) {\n    return subvector_impl_(vectview<Scalar, BaseDIM>(vec), ptr);\n}\n\ntemplate <class Scalar, int BaseDIM, class Base, class T, int idx, int dim>\nvectview<const Scalar, T::DIM> subvector_(const Eigen::Matrix<Scalar, BaseDIM, 1>& vec,\n                                          SubManifold<T, idx, dim> Base::*ptr) {\n    return subvector_impl_(vectview<const Scalar, BaseDIM>(vec), ptr);\n}\n\ntemplate <class Scalar, int BaseDOF, class Base, class T, int idx, int dim>\nvectview<const Scalar, T::DOF> subvector(const Eigen::Matrix<Scalar, BaseDOF, 1>& vec,\n                                         SubManifold<T, idx, dim> Base::*ptr) {\n    return subvector_impl(vectview<const Scalar, BaseDOF>(vec), ptr);\n}\n\n/**\n * const version of subvector(vectview<typename Base::scalar,Base::DOF> vec,SubManifold<T,idx> Base::*)\n */\ntemplate <class Base, class T, int idx, int dim>\nvectview<const typename Base::scalar, T::DOF> subvector_impl(\n    const vectview<const typename Base::scalar, Base::DOF> cvec, SubManifold<T, idx, dim> Base::*) {\n    return cvec.template segment<T::DOF>(idx);\n}\n\ntemplate <class Base, class T, int idx, int dim>\nvectview<const typename Base::scalar, T::DIM> subvector_impl_(\n    const vectview<const typename Base::scalar, Base::DIM> cvec, SubManifold<T, idx, dim> Base::*) {\n    return cvec.template segment<T::DIM>(dim);\n}\n\ntemplate <class Scalar, int BaseDOF, class Base, class T, int idx, int dim>\nvectview<const Scalar, T::DOF> subvector(const vectview<const Scalar, BaseDOF> cvec,\n                                         SubManifold<T, idx, dim> Base::*ptr) {\n    return subvector_impl(cvec, ptr);\n}\n\n}  // namespace MTK\n\n#endif  // GET_START_INDEX_H_\n", "meta": {"hexsha": "1d5280b06396e115e1a839dacfbdb9898eb28623", "size": 12908, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/IKFoM_toolkit/mtk/startIdx.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/startIdx.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/startIdx.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": 43.0266666667, "max_line_length": 120, "alphanum_fraction": 0.6993337465, "num_tokens": 3495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.03676946409649329, "lm_q1q2_score": 0.014700859243633208}}
{"text": "#include \"Day25-HaltingProblem.h\"\n\n#include \"TuringMachine.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <cassert>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2017\n{\nnamespace Day25\n{\n\nStateModifier createStateModifierFromLines(const std::vector<std::string>& stateModifierLines)\n{\n    assert(stateModifierLines.size() == 3);\n\n    // Parse written value\n    std::vector<std::string> tokens;\n    boost::split(tokens, stateModifierLines[0], boost::is_any_of(\" \"), boost::token_compress_on);\n\n    if (tokens.size() != 4)\n    {\n        throw std::runtime_error(\"Invalid new written value.\");\n    }\n\n    const bool writtenValue = std::stoi(tokens[3]);\n\n    // Parse cursor offset\n    boost::split(tokens, stateModifierLines[1], boost::is_any_of(\" \"), boost::token_compress_on);\n\n    if (tokens.size() != 6)\n    {\n        throw std::runtime_error(\"Invalid cursor offset.\");\n    }\n\n    int cursorOffset{};\n    if (tokens[5] == \"left\")\n    {\n        cursorOffset = -1;\n    }\n    else if (tokens[5] == \"right\")\n    {\n        cursorOffset = 1;\n    }\n    else\n    {\n        throw std::runtime_error(\"Invalid cursor direction.\");\n    }\n\n    // Parse next state\n    boost::split(tokens, stateModifierLines[2], boost::is_any_of(\" \"), boost::token_compress_on);\n\n    if (tokens.size() != 4 || tokens[3].size() != 1)\n    {\n        throw std::runtime_error(\"Invalid next state.\");\n    }\n\n    const StateIDType nextStateID = tokens[3].front();\n\n    return StateModifier{writtenValue, cursorOffset, nextStateID};\n}\n\nTuringMachine::TransitionMap createTransitionMapFromLines(const std::vector<std::string>& transitionMapLines)\n{\n    if (transitionMapLines.size() % 10 != 0)\n    {\n        throw std::runtime_error(\"Invalid number of lines.\");\n    }\n\n    TuringMachine::TransitionMap transitionMap;\n\n    for (unsigned i = 0; i < transitionMapLines.size(); i+=10)\n    {\n        std::vector<std::string> tokens;\n        boost::split(tokens, transitionMapLines[i + 1], boost::is_any_of(\" \"));\n\n        if (tokens.size() != 3 || tokens[2].size() == 0)\n        {\n            throw std::runtime_error(\"Invalid state transition headline.\");\n        }\n\n        StateIDType stateID = tokens[2].front();\n\n        StateModifier valueFalseModifier = createStateModifierFromLines({transitionMapLines.cbegin() + i + 3, transitionMapLines.cbegin() + i + 6});\n        StateModifier valueTrueModifier = createStateModifierFromLines({transitionMapLines.cbegin() + i + 7, transitionMapLines.cbegin() + i + 10});\n\n        StateTransition stateTransition{std::move(valueFalseModifier), std::move(valueTrueModifier)};\n\n        transitionMap.emplace(stateID, std::move(stateTransition));\n    }\n\n    return transitionMap;\n}\n\nTuringMachine createTuringMachineFromLines(std::vector<std::string> turingMachineLines)\n{\n    if (turingMachineLines.size() < 2)\n    {\n        throw std::runtime_error(\"Not enough lines.\");\n    }\n\n    std::for_each(turingMachineLines.begin(), turingMachineLines.end(), [](auto& line)\n                  {\n                      boost::trim_if(line, boost::is_any_of(\"-. \"));\n                  });\n\n    // Parse initial state\n    std::vector<std::string> tokens;\n    boost::split(tokens, turingMachineLines[0], boost::is_any_of(\" \"), boost::token_compress_on);\n\n    if (tokens.size() != 4 || tokens[3].size() != 1)\n    {\n        throw std::runtime_error(\"Invalid initial state.\");\n    }\n\n    const StateIDType startingStateID = tokens[3].front();\n\n    // Parse number of iterations\n    boost::split(tokens, turingMachineLines[1], boost::is_any_of(\" \"), boost::token_compress_on);\n\n    if (tokens.size() != 7)\n    {\n        throw std::runtime_error(\"Invalid number of iterations.\");\n    }\n\n    const unsigned numIterations = boost::lexical_cast<unsigned>(tokens[5]);\n\n    // Parse state transition map\n    TuringMachine::TransitionMap stateIDToTransition = createTransitionMapFromLines({turingMachineLines.cbegin() + 2, turingMachineLines.cend()});\n\n    return TuringMachine{stateIDToTransition, startingStateID, numIterations};\n}\n\nunsigned diagnosticChecksum(const std::vector<std::string>& turingMachineLines)\n{\n    TuringMachine turingMachine = createTuringMachineFromLines(turingMachineLines);\n    turingMachine.run();\n    return turingMachine.getChecksum();\n}\n\n}\n}\n}\n", "meta": {"hexsha": "4af138f3a0eeff9d306a4d44811b1c07ee60aba5", "size": 4413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2017/Day25-HaltingProblem/Day25-HaltingProblem.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AdventOfCode2017/Day25-HaltingProblem/Day25-HaltingProblem.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AdventOfCode2017/Day25-HaltingProblem/Day25-HaltingProblem.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "max_forks_repo_licenses": ["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.0328947368, "max_line_length": 148, "alphanum_fraction": 0.6684794924, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297119360208, "lm_q2_score": 0.053403324150263734, "lm_q1q2_score": 0.014692841189888005}}
{"text": "/*\n * Copyright (c) 2017, Niklas Gürtler\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 *\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 * 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 USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <climits>\n#include <iostream>\n#include <map>\n#include <cstdint>\n#include <algorithm>\n#include <utility>\n#include <map>\n\n#include \"ltl.hh\"\n#include <boost/functional/hash.hpp>\n#include <boost/fusion/include/hash.hpp>\n\n\nstd::ostream& LTL::operator << (std::ostream& os, const LTL::ExpSet& c) {\n\tif (os.iword (Formula::Formula_Xalloc) == 2) os << \"\\\\left\\\\{\";\n\telse os << \"{\";\n\tbool first = true;\n\tfor (auto& exp : c) {\n\t\tif (!first)\n\t\t\tos << \", \";\n\t\telse\n\t\t\tfirst = false;\n\t\tos << *exp;\n\t}\n\tif (os.iword (Formula::Formula_Xalloc) == 2) os << \"\\\\right\\\\}\";\n\telse os << '}';\n\treturn os;\n}\n\nLTL::Algorithm::Algorithm (const Formula::Expression& exp, const TS::TranSys& ts) :formula (exp) {\n\tClosureVisitor visitor { closure, auxExp, &exp};\n\tboost::apply_visitor (visitor, exp);\n\n\tusing Counter = std::uint64_t;\n\n\tif (closure.size () >= sizeof (Counter) * CHAR_BIT)\n\t\tthrow std::runtime_error (\"Too many closure elements!\");\n\n\tconst Counter max = (1 << closure.size ()) - 1;\n\n\tatomExpressions.push_back ({});\n\n\tfor (Counter iComb = 0; iComb < max; ++iComb) {\n\t\tExpSet& atom = atomExpressions.back ();\n\n\t\tCounter mask = 1;\n\t\tfor (auto& cexp : closure) {\n\t\t\tif (iComb & mask) {\n\t\t\t\tatom.insert (cexp);\n\t\t\t}\n\n\t\t\tmask <<= 1;\n\t\t}\n\t\tbool needed = false;\n\t\tfor (auto& state : ts.statesSet) {\n\t\t\tConsistency_ClosureVisitor v (atom, ts, *state);\n\t\t\tbool consistent = std::all_of (closure.begin (), closure.end (), [&](const Formula::ExpRef& elem) { v.m_parentExp = elem; return ::boost::apply_visitor (v, *elem); });\n\n\t\t\tif (consistent) {\n\t\t\t\tneeded = true;\n\t\t\t\tatomMap.insert (std::make_pair<const TS::State*, std::size_t> (state, atoms.size ()));\n\t\t\t\tatoms.emplace_back (state, atomExpressions.size () - 1);\n\t\t\t}\n\t\t}\n\t\tif (needed) {\n\t\t\tatomExpressions.push_back ({});\n\t\t} else {\n\t\t\tatom.clear ();\n\t\t}\n\t}\n\tatomExpressions.pop_back ();\n\n\tfor (std::size_t iStartAtom = 0; iStartAtom < atoms.size (); ++iStartAtom) {\n\t\tAtom& startAtom = atoms [iStartAtom];\n\t\tfor (const TS::State* succ : startAtom.state->successors) {\n\t\t\tauto endRange = atomMap.equal_range (succ);\n\t\t\tfor (auto iter = endRange.first; iter != endRange.second; ++iter) {\n\t\t\t\tstd::size_t iEndAtom = iter->second;\n\t\t\t\tconst Atom& endAtom = atoms [iEndAtom];\n\n\t\t\t\tconst ExpSet& startExp = atomExpressions [startAtom.expressions];\n\t\t\t\tconst ExpSet& endExp = atomExpressions [endAtom.expressions];\n\n\t\t\t\tif (std::all_of (closure.begin (), closure.end (), [&] (const Formula::ExpRef& elem) {\n\t\t\t\t\tif (const Formula::E_Next* next = boost::get<Formula::E_Next> (&*elem)) {\n\t\t\t\t\t\treturn\t(startExp.find (elem) == startExp.end ())\n\t\t\t\t\t\t\t==\t(endExp.find(&next->exp) == endExp.end ());\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t})) {\n\t\t\t\t\tedges.emplace_back (iStartAtom, iEndAtom);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_Label& exp) {\n\tauto iter = m_tranSys.labels.find (exp.name);\n\tif (iter == m_tranSys.labels.end ())\n\t\tthrow std::runtime_error (\"Unknown label: \" + exp.name);\n\n\tconst bool inState = m_state.atomicPropositions.find (const_cast<TS::Label*>(&iter->second)) == m_state.atomicPropositions.end ();\n\tconst bool inAtom = m_atom.find (m_parentExp) == m_atom.end ();\n\treturn inState == inAtom;\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_Literal& exp) {\n\treturn (m_atom.find (m_parentExp) != m_atom.end ()) == exp.value;\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_Negation&) {\n\tthrow std::runtime_error (\"Negation in closure!\");\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_And& exp) {\n\treturn\t(containsConsistent (exp.lhs)\t&&\tcontainsConsistent (exp.rhs))\n\t\t==\t(m_atom.find (m_parentExp) != m_atom.end ());\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_Or& exp) {\n\treturn\t(containsConsistent (exp.lhs)\t||\tcontainsConsistent (exp.rhs))\n\t\t==\t(m_atom.find (m_parentExp) != m_atom.end ());\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_Implication& exp) {\n\treturn\t(!containsConsistent (exp.lhs)\t||\tcontainsConsistent (exp.rhs))\n\t\t==\t(m_atom.find (m_parentExp) != m_atom.end ());\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_Until& exp) {\n\tFormula::Expression next { Formula::E_Next { {}, exp, {}}};\n\treturn\t(m_atom.find (m_parentExp) != m_atom.end ())\n\t\t==\t(\n\t\t\t\tcontainsConsistent (exp.rhs)\n\t\t\t||\t(containsConsistent (exp.lhs) && m_atom.find (&next) != m_atom.end ())\n\t\t\t);\n}\n\nbool LTL::Consistency_ClosureVisitor::operator () (const Formula::E_Next&) {\n\treturn true;\n}\n\nint LTL::ClosureVisitor::operator () (const Formula::E_Negation& exp) {\n\tm_parentExp = &exp.exp;\n\tboost::apply_visitor (*this, exp.exp);\n\treturn 0;\n}\n\nint LTL::ClosureVisitor::operator () (const Formula::E_Until& exp) {\n\tm_closure.insert (m_parentExp);\n\n\tm_auxExp.emplace_back (Formula::E_Next ({}, exp, {}));\n\tm_closure.insert (&m_auxExp.back ());\n\n\tm_parentExp = &exp.lhs;\n\tboost::apply_visitor (*this, exp.lhs);\n\tm_parentExp = &exp.rhs;\n\tboost::apply_visitor (*this, exp.rhs);\n\treturn 0;\n}\n\nint LTL::ClosureVisitor::operator () (const Formula::E_Literal&) {\n\tm_closure.insert (m_parentExp);\n\treturn 0;\n}\n\nint LTL::ClosureVisitor::operator () (const Formula::E_Label&) {\n\tm_closure.insert (m_parentExp);\n\treturn 0;\n}\n", "meta": {"hexsha": "e85f2d4f18021a84b26250164dbc6bdc70a3f09f", "size": 6612, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ltl/ltl.cc", "max_stars_repo_name": "Erlkoenig90/MCheck", "max_stars_repo_head_hexsha": "6c58231500e1b68c19a27ce48a9410cc367d17c1", "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/ltl/ltl.cc", "max_issues_repo_name": "Erlkoenig90/MCheck", "max_issues_repo_head_hexsha": "6c58231500e1b68c19a27ce48a9410cc367d17c1", "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/ltl/ltl.cc", "max_forks_repo_name": "Erlkoenig90/MCheck", "max_forks_repo_head_hexsha": "6c58231500e1b68c19a27ce48a9410cc367d17c1", "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.9076923077, "max_line_length": 170, "alphanum_fraction": 0.6858741682, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.03210070405485706, "lm_q1q2_score": 0.014674410934310846}}
{"text": "/**\n * Copyright (c) 2022 <Daumantas Kavolis>\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#pragma once\n\n#include \"config.hpp\"\n\nMSVC_WARNING_DISABLE(4619)\n#include <boost/container/small_vector.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/range/adaptor/filtered.hpp>\n#include <boost/range/adaptor/indexed.hpp>\nMSVC_WARNING_POP()\n\n#include \"traits.hpp\"\n#include \"utils.hpp\"\n\nnamespace poly {\n\ntemplate <class Real_,\n          class Index = std::conditional_t<std::is_const_v<Real_>, std::size_t const, std::size_t>>\nclass SobolItemView : public view<Index> {\n public:\n  using Base = view<Index>;\n  using IndexType = Index;\n  using Real = Real_;\n\n  SobolItemView(Index* indices, std::size_t count, Real& coefficient) noexcept\n      : Base(indices, count), coefficient_(coefficient) {}\n\n  // NOLINTNEXTLINE(hicpp-explicit-conversions)\n  operator SobolItemView<Real const, Index const>() const noexcept {\n    return {this->data(), this->size(), coefficient_};\n  }\n\n  auto coefficient() const noexcept -> Real& { return coefficient_; }\n\n  template <bool check = true, class Range,\n            typename = std::enable_if_t<detail::is_range<Range>::value>>\n  [[nodiscard]] auto matches_non_zeros(Range const& non_zeros,\n                                       bounds_check<check> /* unused */ = check_bounds) const\n      -> bool {\n    if constexpr (check) {\n      if (boost::size(non_zeros) != this->size())\n        throw std::out_of_range(\"Dimensions do not match\");\n    }\n\n    for (auto&& [index, is_non_zero] : non_zeros | boost::adaptors::indexed())\n      if (((*this)[index] != 0) != static_cast<bool>(is_non_zero)) return false;\n\n    return true;\n  }\n\n  template <bool check = true, class Range,\n            typename = std::enable_if_t<detail::is_range<Range>::value>>\n  [[nodiscard]] auto matches_zeros(Range const& zeros,\n                                   bounds_check<check> /* unused */ = check_bounds) const -> bool {\n    if constexpr (check) {\n      if (boost::size(zeros) != this->size()) throw std::out_of_range(\"Dimensions do not match\");\n    }\n\n    for (auto&& [index, is_zero] : zeros | boost::adaptors::indexed())\n      if (((*this)[index] == 0) != static_cast<bool>(is_zero)) return false;\n\n    return true;\n  }\n\n private:\n  Real& coefficient_;\n};\n\ntemplate <class Real>\nclass SobolIterator : public boost::iterator_facade<\n                          /* Derived = */ SobolIterator<Real>,\n                          /* Value type = */ SobolItemView<Real>,\n                          /* traversal tag = */ boost::random_access_traversal_tag,\n                          /* reference = */ SobolItemView<Real>> {\n public:\n  using Index = typename SobolItemView<Real>::IndexType;\n\n  SobolIterator(Index* indices, Real* coefficients, std::size_t dimensions) noexcept\n      : iterator_(indices), coefficients_(coefficients), dimensions_(dimensions) {}\n\n private:\n  friend class boost::iterator_core_access;\n  template <class>\n  friend class SobolIterator;\n\n  template <class OtherValue>\n  auto equal(SobolIterator<OtherValue> const& other) const noexcept -> bool {\n    return this->coefficients_ == other.coefficients_;\n  }\n\n  void increment() noexcept {\n    iterator_ += dimensions_;\n    ++coefficients_;\n  }\n  void decrement() noexcept {\n    iterator_ -= dimensions_;\n    --coefficients_;\n  }\n\n  void advance(std::ptrdiff_t n) noexcept {\n    iterator_ += n * dimensions_;\n    coefficients_ += n;\n  }\n  auto distance_to(SobolIterator const& other) const noexcept -> std::ptrdiff_t {\n    return other.coefficients_ - coefficients_;\n  }\n\n  auto dereference() const noexcept -> SobolItemView<Real> {\n    return {iterator_, dimensions_, *coefficients_};\n  }\n\n  Index* iterator_;\n  Real* coefficients_;\n  std::size_t dimensions_;\n};\n\n/// \\brief Sobol calculator for orthonormal PCEs. Under such assumption, inner products between\n/// different polynomials are 0, same - 1.\n///\n/// Sudret, B. (2008). Global sensitivity analysis using polynomial chaos expansions.\n/// Reliability Engineering & System Safety, 93(7), 964–979.\n/// https://doi.org/10.1016/j.ress.2007.04.002\n/// \\tparam Real\n/// \\tparam Alloc\ntemplate <class Real, template <class> class Alloc = std::allocator>\nclass Sobol {\n private:\n  using match_vector = boost::container::small_vector<bool, 128>;\n\n public:\n  using indices_vector = std::vector<std::size_t, Alloc<std::size_t>>;\n  using coefficients_vector = std::vector<Real, Alloc<Real>>;\n  using View = SobolItemView<Real, std::size_t>;\n  using ConstView = SobolItemView<Real const, std::size_t const>;\n\n  using iterator = SobolIterator<Real const>;\n  using const_iterator = iterator;\n\n  Sobol(indices_vector indices, coefficients_vector coefficients, std::size_t dimensions)\n      : indices_(std::move(indices)),\n        coefficients_(std::move(coefficients)),\n        dimensions_(dimensions) {\n    calculate_mean_variance();\n  }\n\n  auto operator[](std::size_t index) noexcept -> View {\n    return View{indices_.data() + index * dimensions_, dimensions_, coefficients_[index]};\n  }\n  auto operator[](std::size_t index) const noexcept -> ConstView {\n    return ConstView{indices_.data() + index * dimensions_, dimensions_, coefficients_[index]};\n  }\n\n  auto at(std::size_t index) noexcept -> View {\n    return View{indices_.data() + index * dimensions_, dimensions_, coefficients_.at(index)};\n  }\n  auto at(std::size_t index) const -> ConstView {\n    return ConstView{indices_.data() + index * dimensions_, dimensions_, coefficients_.at(index)};\n  }\n\n  [[nodiscard]] auto size() const noexcept -> std::size_t { return coefficients_.size(); }\n  [[nodiscard]] auto index_count() const noexcept -> std::size_t { return indices_.size(); }\n  [[nodiscard]] auto dimensions() const noexcept -> std::size_t { return dimensions_; }\n  [[nodiscard]] auto variance() const noexcept -> Real { return variance_; }\n  [[nodiscard]] auto mean() const noexcept -> Real { return mean_; }\n  [[nodiscard]] auto indices() const noexcept -> view<std::size_t const> {\n    return {indices_.data(), indices_.size()};\n  }\n  [[nodiscard]] auto coefficients() const noexcept -> view<Real const> {\n    return {coefficients_.data(), coefficients_.size()};\n  }\n\n  auto mutable_indices() noexcept -> view<std::size_t> {\n    return {indices_.data(), indices_.size()};\n  }\n  auto mutable_coefficients() noexcept -> view<Real> {\n    return {coefficients_.data(), coefficients_.size()};\n  }\n  void recalculate() { calculate_mean_variance(); }\n\n  [[nodiscard]] auto begin() const noexcept -> SobolIterator<Real const> {\n    return {indices_.data(), coefficients_.data(), dimensions_};\n  }\n  [[nodiscard]] auto end() const noexcept -> SobolIterator<Real const> {\n    return {indices_.data() + index_count(), coefficients_.data() + size(), dimensions_};\n  }\n  [[nodiscard]] auto mutable_range() noexcept -> boost::iterator_range<SobolIterator<Real>> {\n    using It = SobolIterator<Real>;\n    It begin = {indices_.data(), coefficients_.data(), dimensions_};\n    return boost::make_iterator_range_n(begin, size());\n  }\n\n  template <bool check = true>\n  [[nodiscard]] auto sensitivity(std::size_t index,\n                                 bounds_check<check> /* unused */ = check_bounds) const -> Real {\n    if constexpr (check) {\n      if (index >= dimensions_) throw std::out_of_range(\"Sensitivity index out of range\");\n    }\n    match_vector non_zeros(dimensions_, false);\n    non_zeros[index] = true;\n    return calculate_sensitivity(non_zeros);\n  }\n\n  template <bool check = true>\n  [[nodiscard]] auto sensitivity(std::pair<std::size_t, std::size_t> index,\n                                 bounds_check<check> /* unused */ = check_bounds) const -> Real {\n    if constexpr (check) {\n      if (index.first >= dimensions_ || index.second >= dimensions_)\n        throw std::out_of_range(\"Sensitivity index out of range\");\n    }\n    match_vector non_zeros(dimensions_, false);\n    non_zeros[index.first] = true;\n    non_zeros[index.second] = true;\n    return calculate_sensitivity(non_zeros);\n  }\n\n  template <bool check = true, class Range,\n            typename = std::enable_if_t<detail::is_range<Range>::value>>\n  [[nodiscard]] auto sensitivity(Range const& indices,\n                                 bounds_check<check> /* unused */ = check_bounds) const -> Real {\n    match_vector non_zeros(dimensions_, false);\n    for (auto&& index : indices) {\n      if constexpr (check) {\n        if (index >= dimensions_) throw std::out_of_range(\"Sensitivity index out of range\");\n      }\n      non_zeros[index] = true;\n    }\n    return calculate_sensitivity(non_zeros);\n  }\n\n  template <bool check = true>\n  [[nodiscard]] auto total_sensitivity(std::size_t index,\n                                       bounds_check<check> /* unused */ = check_bounds) const\n      -> Real {\n    if constexpr (check) {\n      if (index >= dimensions_) throw std::out_of_range(\"Sensitivity index out of range\");\n    }\n    return calculate_total_sensitivity(index);\n  }\n\n private:\n  // copying indices and coefficients allows to have precomputed variance and mean\n  indices_vector indices_;\n  coefficients_vector coefficients_;\n  std::size_t dimensions_;\n  Real variance_;\n  Real mean_;\n  Real inverse_variance_;\n\n  void calculate_mean_variance() {\n    if (coefficients_.size() * dimensions_ != indices_.size())\n      throw std::out_of_range(\"Coefficients and indices sizes do not match\");\n\n    // mean is coefficient with all indices 0\n    mean_ = 0;\n    // should have a fake range that always dereferences to true\n    match_vector zeros(dimensions_, true);\n    for (auto&& item : *this) {\n      if (item.matches_zeros(zeros, no_bounds_check)) {\n        mean_ = item.coefficient();\n        break;\n      }\n    }\n\n    // variance is sum of squares of all the other coefficients\n    variance_ = -(mean_ * mean_);\n    for (auto&& coefficient : coefficients_) variance_ += coefficient * coefficient;\n\n    inverse_variance_ = 1.0L / variance_;\n  }\n\n  [[nodiscard]] auto calculate_sensitivity(match_vector const& non_zeros) const -> Real {\n    Real s = 0;\n    for (auto&& item : *this) {\n      if (item.matches_non_zeros(non_zeros, no_bounds_check))\n        s += item.coefficient() * item.coefficient();\n    }\n\n    return s * inverse_variance_;\n  }\n\n  [[nodiscard]] auto calculate_total_sensitivity(std::size_t index) const -> Real {\n    Real s = 0;\n    for (auto&& item : *this) {\n      if (item[index] != 0) s += item.coefficient() * item.coefficient();\n    }\n\n    return s * inverse_variance_;\n  }\n};\n}  // namespace poly\n\nPOLY_TEMPLATE_RANGE(poly::Sobol)\n", "meta": {"hexsha": "2248e2685c3822cd2f12f2890be12c060f393491", "size": 11553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/polynomials/include/sobol.hpp", "max_stars_repo_name": "dkavolis/polynomials", "max_stars_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomials/include/sobol.hpp", "max_issues_repo_name": "dkavolis/polynomials", "max_issues_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomials/include/sobol.hpp", "max_forks_repo_name": "dkavolis/polynomials", "max_forks_repo_head_hexsha": "10abe0ca8bdd3ae7dafc1ecd04142b42e3213af0", "max_forks_repo_licenses": ["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.6761904762, "max_line_length": 99, "alphanum_fraction": 0.6751493119, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.034100429025267616, "lm_q1q2_score": 0.014668209130858584}}
{"text": "/* ----------------------------------------------------------------------- *//**\n * @file matrix_ops.cpp\n *\n * @date May 8, 2013\n *//* ----------------------------------------------------------------------- */\n\n#include <dbconnector/dbconnector.hpp>\n#include <modules/shared/HandleTraits.hpp>\n\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include \"matrix_ops.hpp\"\n\nnamespace madlib {\nnamespace modules {\nnamespace linalg {\n\nusing madlib::dbconnector::postgres::madlib_construct_array;\nusing madlib::dbconnector::postgres::madlib_construct_md_array;\n\n// Use Eigen\nusing namespace dbal::eigen_integration;\n\n\nAnyType matrix_densify_sfunc::run(AnyType & args)\n{\n    int32_t col_dim = args[1].getAs<int32_t>();\n    int32_t col = args[2].getAs<int32_t>();\n    double val = args[3].getAs<double>();\n\n    if(col_dim < 1){\n        std::stringstream errorMsg;\n        errorMsg << \"invalid argument - col (\" << col <<\n                    \") should be positive\";\n        throw std::invalid_argument(errorMsg.str());\n    }\n\n    if(col < 1 || col > col_dim){\n        std::stringstream errorMsg;\n        errorMsg << \"invalid argument - col (\" << col <<\n                    \") should be in the range of [1, \" << col_dim << \"]\";\n        throw std::invalid_argument(errorMsg.str());\n    }\n\n    MutableArrayHandle<double> state(NULL);\n    if (args[0].isNull()){\n        state =  madlib_construct_array(\n            NULL, col_dim, FLOAT8OID, sizeof(double), true, 'd');\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    // we use col - 1 since\n    // database expects col in [1, col_dim]; c++ expects col in [0, col_dim - 1]\n    *(state.ptr() + col - 1) = val;\n\n    return state;\n}\n\nAnyType matrix_mem_sum_sfunc::run(AnyType & args)\n{\n    ArrayHandle<double> m = args[1].getAs<ArrayHandle<double> >();\n\n    if (m.dims() !=2){\n        throw std::invalid_argument(\n            \"invalid argument - 2-d array expected\");\n    }\n\n    int row_m = static_cast<int>(m.sizeOfDim(0));\n    int col_m = static_cast<int>(m.sizeOfDim(1));\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if (args[0].isNull()){\n        int dims[2] = {row_m, col_m};\n        int lbs[2] = {1, 1};\n        state =  madlib_construct_md_array(\n            NULL, NULL, 2, dims, lbs, FLOAT8OID, sizeof(double), true, 'd');\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    for(int i = 0; i < row_m; i++){\n        for(int j = 0; j < col_m; j++){\n            *(state.ptr() + i * col_m + j) += *(m.ptr() + i * col_m + j);\n        }\n    }\n\n    return state;\n}\n\nAnyType matrix_blockize_sfunc::run(AnyType & args)\n{\n    if(args[1].isNull())\n        return args[0];\n\n    int32_t row_id = args[1].getAs<int32_t>();\n    ArrayHandle<double> row_vec  = args[2].getAs<ArrayHandle<double> >();\n    int32_t rsize = args[3].getAs<int32_t>();\n    int32_t csize = static_cast<int32_t>(row_vec.sizeOfDim(0));\n\n    if(rsize < 1){\n        throw std::invalid_argument(\n            \"invalid argument - block size should be positive\");\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if (args[0].isNull()){\n        int32_t dims[2] = {rsize, csize};\n        int lbs[2] = {1, 1};\n        state = madlib_construct_md_array(\n                NULL, NULL, 2, dims, lbs, FLOAT8OID, sizeof(double), true, 'd');\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    // database represents row_id in [1, row_dim]\n    memcpy(state.ptr() + ((row_id - 1) % rsize) * csize,\n           row_vec.ptr(),\n           csize * sizeof(double));\n\n    return state;\n}\n\nAnyType matrix_mem_mult::run(AnyType & args)\n{\n    ArrayHandle<double> a = args[0].getAs<ArrayHandle<double> >();\n    ArrayHandle<double> b = args[1].getAs<ArrayHandle<double> >();\n    bool trans_b = args[2].getAs<bool>();\n\n    if (a.dims() != 2 || b.dims() !=2){\n        throw std::invalid_argument(\n            \"invalid argument - 2-d array expected\");\n    }\n\n    int row_a = static_cast<int>(a.sizeOfDim(0));\n    int col_a = static_cast<int>(a.sizeOfDim(1));\n    int row_b = static_cast<int>(b.sizeOfDim(0));\n    int col_b = static_cast<int>(b.sizeOfDim(1));\n\n    if ((!trans_b && col_a != row_b) || (trans_b && col_a != col_b)){\n        throw std::invalid_argument(\n            \"invalid argument - dimension mismatch\");\n    }\n\n    int dims[2] = {row_a, col_b};\n    if (trans_b)\n        dims[1] = row_b;\n    int lbs[2] = {1, 1};\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> r = madlib_construct_md_array(\n            NULL, NULL, 2, dims, lbs, FLOAT8OID, sizeof(double), true, 'd');\n\n    for (int i = 0; i < row_a; i++){\n        for(int j = 0; j < col_a; j++){\n            for(int k = 0; k < dims[1]; k++){\n                *(r.ptr() + i * dims[1] + k) += trans_b ?\n                    *(a.ptr() + i * col_a + j) * *(b.ptr() + k * col_b + j) :\n                        *(a.ptr() + i * col_a + j) * *(b.ptr() + j * col_b + k);\n            }\n        }\n    }\n    return r;\n}\n\nAnyType matrix_mem_trans::run(AnyType & args)\n{\n    ArrayHandle<double> m = args[0].getAs<ArrayHandle<double> >();\n\n    if (m.dims() != 2){\n        throw std::invalid_argument(\n            \"invalid argument - 2-d array expected\");\n    }\n\n    int row_m = static_cast<int>(m.sizeOfDim(0));\n    int col_m = static_cast<int>(m.sizeOfDim(1));\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    int dims[2] = {col_m, row_m};\n    int lbs[2] = {1, 1};\n    MutableArrayHandle<double> r = madlib_construct_md_array(\n            NULL, NULL, 2, dims, lbs, FLOAT8OID, sizeof(double), true, 'd');\n\n    for (int i = 0; i < row_m; i++){\n        for(int j = 0; j < col_m; j++){\n                *(r.ptr() + j * row_m + i) = *(m.ptr() + i * col_m + j);\n        }\n    }\n    return r;\n}\n\nAnyType rand_vector::run(AnyType & args)\n{\n    int dim = args[0].getAs<int>();\n    if (dim < 1) {\n        throw std::invalid_argument(\"invalid argument - dim should be positive\");\n    }\n    MutableArrayHandle<int> r =  madlib_construct_array(\n            NULL, dim, INT4OID, sizeof(int32_t), true, 'i');\n\n    for (int i = 0; i < dim; i++){\n        *(r.ptr() + i) = (int)(drand48() * 1000);\n    }\n    return r;\n}\n\nAnyType normal_vector::run(AnyType & args)\n{\n    int dim = args[0].getAs<int>();\n    double mu = args[1].getAs<double>();\n    double sigma = args[2].getAs<double>();\n    int seed = args[3].getAs<int>();\n\n    if (dim < 1) {\n        throw std::invalid_argument(\"invalid argument - dim should be positive\");\n    }\n    ColumnVector res(dim);\n    boost::minstd_rand generator(seed);\n    boost::normal_distribution<> nd_dist(mu, sigma);\n    boost::variate_generator<boost::minstd_rand&, boost::normal_distribution<> > nd(generator, nd_dist);\n\n    for (int i = 0; i < dim; i++){\n        res(i) = (double)nd();\n    }\n    return res;\n}\n\nAnyType bernoulli_vector::run(AnyType & args)\n{\n    int dim = args[0].getAs<int>();\n    double upper_val = args[1].getAs<double>();\n    double lower_val = args[2].getAs<double>();\n    double prob = args[3].getAs<double>();\n    int seed = args[4].getAs<int>();\n\n    if (dim < 1) {\n        throw std::invalid_argument(\"invalid argument - dim should be positive\");\n    }\n    if (prob > 1 || prob < 0) {\n        throw std::invalid_argument(\"invalid argument - probability should be in [0,1]\");\n    }\n\n    ColumnVector res(dim);\n    boost::minstd_rand generator(seed);\n    boost::bernoulli_distribution<> bn_dist(prob);\n    boost::variate_generator<boost::minstd_rand&, boost::bernoulli_distribution<> > bn(generator, bn_dist);\n\n    for (int i = 0; i < dim; i++) {\n        res(i) = bn() ? upper_val : lower_val;\n    }\n    return res;\n}\n\nAnyType uniform_vector::run(AnyType & args)\n{\n    int dim = args[0].getAs<int>();\n    double min_ = args[1].getAs<double>();\n    double max_ = args[2].getAs<double>();\n    int seed = args[3].getAs<int>();\n\n    if (dim < 1) {\n        throw std::invalid_argument(\"invalid argument - dim should be positive\");\n    }\n    ColumnVector res(dim);\n    boost::minstd_rand generator(seed);\n    boost::uniform_real<> uni_dist(min_, max_);\n    boost::variate_generator<boost::minstd_rand&, boost::uniform_real<> > uni(generator, uni_dist);\n    for (int i = 0; i < dim; i++){\n        res(i) = (double)uni();\n    }\n    return res;\n}\n\nAnyType matrix_vec_mult_in_mem_2d::run(AnyType & args){\n    MappedColumnVector vec = args[0].getAs<MappedColumnVector>();\n    MappedMatrix mat = args[1].getAs<MappedMatrix>();\n\n    // Note mat is constructed in the column-first order\n    // which means that mat is actually transposed\n    if(vec.size() != mat.cols()){\n        throw std::invalid_argument(\n            \"dimensions mismatch: vec.size() != matrix.rows()\");\n    };\n\n    // trans(vec) * trans(mat) = mat * vec\n    Matrix r = mat * vec;\n    ColumnVector v = r.col(0);\n    return v;\n}\n\nAnyType matrix_vec_mult_in_mem_1d::run(AnyType & args){\n    MappedColumnVector vec1 = args[0].getAs<MappedColumnVector>();\n    // matrix stored as a 1-d array\n    MappedColumnVector vec2 = args[1].getAs<MappedColumnVector>();\n\n    if(vec2.size() % vec1.size() != 0){\n        throw std::invalid_argument(\n            \"dimensions mismatch: matrix.size() is not multiples of vec.size()\");\n    };\n\n    MappedMatrix mat;\n    // the rebinding happens in column-major\n    mat.rebind(vec2.memoryHandle(), vec1.size(), vec2.size()/vec1.size());\n    Matrix r = trans(mat) * vec1;\n    ColumnVector v = r.col(0);\n    return v;\n}\n\nAnyType row_fold::run(AnyType & args){\n    MappedColumnVector vec = args[0].getAs<MappedColumnVector>();\n    MappedIntegerVector pat = args[1].getAs<MappedIntegerVector>();\n\n    if (vec.size() != pat.sum()) {\n        throw std::invalid_argument(\n            \"dimensions mismatch: row_in.size() != pattern.sum()\");\n    }\n\n    ColumnVector r(pat.size());\n    for (int i = 0, j = 0; i < pat.size(); j += pat[i++])\n        r[i] = vec.segment(j, pat[i]).prod();\n\n    return r;\n}\n\nAnyType rand_block::run(AnyType & args)\n{\n    int row_dim = args[0].getAs<int>();\n    int col_dim = args[1].getAs<int>();\n    if (row_dim < 1 || col_dim < 1) {\n        throw std::invalid_argument(\"invalid argument - row_dim and col_dim \\\n        should be positive\");\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    int dims[2] = {row_dim, col_dim};\n    int lbs[2] = {1, 1};\n    MutableArrayHandle<int32_t> r = madlib_construct_md_array(\n            NULL, NULL, 2, dims, lbs, INT4OID, sizeof(int32_t), true, 'i');\n\n    for (int i = 0; i < row_dim; i++){\n        for(int j = 0; j < col_dim; j++){\n                *(r.ptr() + i * col_dim + j) = (int32_t)(drand48() * 1000);\n        }\n    }\n    return r;\n}\n\ntypedef struct __sr_ctx1{\n    const double * inarray;\n    int32_t dim;\n    int32_t maxcall;\n    int32_t size;\n    int32_t curcall;\n} sr_ctx1;\n\n// @brief: split a vector into multiple vectors\nvoid * row_split::SRF_init(AnyType &args)\n{\n    // vector to be split\n    ArrayHandle<double> inarray = args[0].getAs<ArrayHandle<double> >();\n    // size of each split\n    int32_t size = args[1].getAs<int32_t>();\n\n    if (size < 1) {\n        // throw std::invalid_argument will cause crash\n        elog(ERROR, \"invalid argument - the spliting size should be positive\");\n    }\n\n    sr_ctx1 * ctx = new sr_ctx1;\n    ctx->inarray = inarray.ptr();\n    // length of inarray\n    ctx->dim = static_cast<int32_t>(inarray.sizeOfDim(0));\n    ctx->size = size;\n    // max number of splits to be formed\n    ctx->maxcall = static_cast<int32_t>(\n        ceil(static_cast<double>(ctx->dim) / size));\n    // current split index\n    ctx->curcall = 0;\n\n    return ctx;\n}\n\n/**\n * @brief The function is used to return the next row by the SRF.\n **/\nAnyType row_split::SRF_next(void *user_fctx, bool *is_last_call)\n{\n    sr_ctx1 * ctx = (sr_ctx1 *) user_fctx;\n    if (ctx->maxcall == 0) {\n        *is_last_call = true;\n        return Null();\n    }\n\n    int32_t size = ctx->size;\n    if (ctx->maxcall == 1 && ctx->dim % ctx->size != 0) {\n        // for last split we might not have enough elements to fill the whole split\n        // in this case we update size to the number of residual elements in last split\n        size = ctx->dim % ctx->size;\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> outarray(\n        madlib_construct_array(\n            NULL, size, FLOAT8OID, sizeof(double), true, 'd'));\n    memcpy(outarray.ptr(), ctx->inarray + ctx->curcall * ctx->size,\n           size * sizeof(double));\n\n    ctx->curcall++;\n    ctx->maxcall--;\n    *is_last_call = false;\n\n    return outarray;\n}\n\nAnyType matrix_unblockize_sfunc::run(AnyType & args)\n{\n    if (args[1].isNull() || args[2].isNull() || args[3].isNull())\n        return args[0];\n\n    int32_t total_col_dim = args[1].getAs<int32_t>();\n    int32_t col_id = args[2].getAs<int32_t>();\n    ArrayHandle<double> row_vec = args[3].getAs<ArrayHandle<double> >();\n    int32_t col_dim = static_cast<int32_t>(row_vec.sizeOfDim(0));\n\n    if(total_col_dim < 1){\n        throw std::invalid_argument(\n            \"invalid argument - total_col_dim should be positive\");\n    }\n\n    if(col_id <= 0){\n        throw std::invalid_argument(\n            \"invalid argument - col_id should be positive\");\n    }\n\n    if(col_id > total_col_dim){\n        throw std::invalid_argument(\n            \"invalid argument - col_id should be in the range of [1, total_col_dim]\");\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if (args[0].isNull()){\n        state =  madlib_construct_array(\n            NULL, total_col_dim, FLOAT8OID, sizeof(double), true, 'd');\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    memcpy(state.ptr() + col_id - 1, row_vec.ptr(), col_dim * sizeof(double));\n\n    return state;\n}\n\ntypedef struct __sr_ctx2{\n    const double * inarray;\n    int32_t maxcall;\n    int32_t dim;\n    int32_t curcall;\n} sr_ctx2;\n\nvoid * unnest_block::SRF_init(AnyType &args)\n{\n    ArrayHandle<double> inarray = args[0].getAs<ArrayHandle<double> >();\n    if(inarray.dims() != 2)\n        throw std::invalid_argument(\"invalid dimension\");\n\n    sr_ctx2 * ctx = new sr_ctx2;\n    ctx->inarray = inarray.ptr();\n    ctx->maxcall = static_cast<int32_t>(inarray.sizeOfDim(0));\n    ctx->dim = static_cast<int32_t>(inarray.sizeOfDim(1));\n    ctx->curcall = 0;\n\n    return ctx;\n}\n\nAnyType unnest_block::SRF_next(void *user_fctx, bool *is_last_call)\n{\n    sr_ctx2 * ctx = (sr_ctx2 *) user_fctx;\n    if (ctx->maxcall == 0) {\n        *is_last_call = true;\n        return Null();\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> outarray(\n        madlib_construct_array(\n            NULL, ctx->dim, FLOAT8OID, sizeof(double), true, 'd'));\n    memcpy(\n        outarray.ptr(), ctx->inarray + ctx->curcall * ctx->dim, ctx->dim *\n        sizeof(double));\n\n    ctx->curcall++;\n    ctx->maxcall--;\n    *is_last_call = false;\n\n    return outarray;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "02908ad4c96eefb26175a13cd28618a5d273098e", "size": 16066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/linalg/matrix_ops.cpp", "max_stars_repo_name": "iyerr3/madlib", "max_stars_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-01T17:58:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-01T17:58:05.000Z", "max_issues_repo_path": "src/modules/linalg/matrix_ops.cpp", "max_issues_repo_name": "iyerr3/madlib", "max_issues_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/linalg/matrix_ops.cpp", "max_forks_repo_name": "iyerr3/madlib", "max_forks_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 30.8961538462, "max_line_length": 107, "alphanum_fraction": 0.6040707083, "num_tokens": 4347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.034100422522057784, "lm_q1q2_score": 0.014668206333520116}}
{"text": "// Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.\n\n// Boost Software License - Version 1.0 - August 17th, 2003\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//  Authors: Thejaka Kanewala\n//           Marcin Zalewski\n//           Andrew Lumsdaine\n\n//======== SSSP (AGM/EAGM) Hand-coded Algortihms================//\n// Driver for SSSP family of algorithms.\n//===========================================================//\n\n#include \"common/sssp_params.hpp\"\n\n#define LIB_CDS 1\n\n#include <boost/graph/distributed/thread_pq_def.hpp>\n//delta eagms\n#include <boost/graph/distributed/delta_stepping_shortest_paths.hpp>\n#include <boost/graph/distributed/delta_stepping_shortest_paths_node.hpp>\n#include <boost/graph/distributed/delta_stepping_shortest_paths_numa.hpp>\n#include <boost/graph/distributed/delta_stepping_shortest_paths_thread.hpp>\n//kla eagms\n#include <boost/graph/distributed/kla_sssp_buffer.hpp>\n#include <boost/graph/distributed/kla_sssp_numa.hpp>\n#include <boost/graph/distributed/kla_sssp_node.hpp>\n#include <boost/graph/distributed/kla_sssp_thread.hpp>\n//chaotic agms\n#include <boost/graph/distributed/distributed_control.hpp>\n#include <boost/graph/distributed/distributed_control_node.hpp>\n#include <boost/graph/distributed/distributed_control_chaotic.hpp>\n\n#define NODE_PRIORITY_Q_GEN boost::graph::distributed::node_priority_queue_gen\n#define NUMA_PRIORITY_Q_GEN boost::graph::distributed::numa_priority_queue_gen\n#define THREAD_PRIORITY_Q_GEN boost::graph::distributed::thread_priority_queue_gen\n\nclass SSSPExecutor {\n\nprivate:\n  template <typename Graph, typename DistMap, typename WeightMap>\n  bool verify_sssp(amplusplus::transport& trans,  Graph& g, DistMap& distance, WeightMap& weight) {\n    distance.set_consistency_model(boost::parallel::cm_forward);\n    distance.set_max_ghost_cells(0);\n\n    if (trans.rank() == 0) std::cout<<\"[INFO] Verifying results......\";\n\n    {\n      amplusplus::scoped_epoch epoch(g.transport());\n\t  \n      BGL_FORALL_VERTICES_T(v, g, Graph) {\n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t  get(distance, target(e, g));\n\t}\n      }\n    }\n\t    \n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n#ifdef PRINT_DEBUG\n\tif (get(distance, target(e, g)) > \n\t    boost::closed_plus<weight_type>()(get(distance, source(e, g)), get(weight, e)))\n\t  std::cout << get(get(vertex_local, g), source(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), source(e, g)) << \"->\"\n\t\t    << get(get(vertex_local, g), target(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), target(e, g)) << \"  weight = \"\n\t\t    << get(weight, e)\n\t\t    << \"  distance(\" << get(get(vertex_local, g), source(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), source(e, g))\n\t\t    << \") = \" << get(distance, source(e, g)) << \"  distance(\" \n\t\t    << get(get(vertex_local, g), target(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), target(e, g)) << \") = \" \n\t\t    << get(distance, target(e, g)) << std::endl;\n#else\n\tif(get(distance, target(e, g)) > boost::closed_plus<weight_type>()(get(distance, v), get(weight, e))) std::abort();\n#endif\n      }\n    }\n\n    if (trans.rank() == 0) std::cout << \"Verified.\" << std::endl;\n    distance.clear(); // Clear memory used by ghost cells\n\n    return true;\n  }\n\n\n  template <typename Graph, \n\t    typename DistanceMap>\n  uint64_t count_visited_edges(Graph& g, DistanceMap& distance) {\n\n    uint64_t vedges = 0;\n    weight_type dist;\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      dist = boost::get(distance, v);\n      if(dist < std::numeric_limits<weight_type>::max()) {\n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t  // check whether this is a self loop; if self loop dont count it\n\t  if (target(e,g) == v)\n\t    continue;\n\n\t  vedges+=1;\n\t}\n      }\n    }\n\n    uint64_t totaledges = 0;\n    MPI_Allreduce(&vedges, &totaledges, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD);\n    // Graph is undirected, Therefore, divide by two\n    return (totaledges/2);\n  }\n\n  template <typename Graph, \n\t    typename DistanceMap>\n  uint64_t count_visited_vertices(Graph& g, DistanceMap& distance) {\n    uint64_t vvertices = 0;\n    weight_type dist;\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      dist = boost::get(distance, v);\n      if(dist < std::numeric_limits<weight_type>::max()) {\n\tvvertices+=1;\n      }\n    }\n\n    uint64_t totalverts = 0;\n    MPI_Allreduce(&vvertices, &totalverts, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD);\n    return totalverts;\n  }\n\n  void init_cds() {\n#ifdef LIB_CDS\n    // LIBCDS Stuff goes here\n    if (_RANK == 0)\n      std::cout << \"[INFO] Initializing LIBCDS .... \" << std::endl;\n\n    cds::Initialize();\n    // Initialize Hazard Pointer singleton\n    cds::gc::HP hpGC;\n    // Attach for the main thread\n    cds::threading::Manager::attachThread();\n#endif\n  }\n\n  void terminate_cds() {\n    if (_RANK == 0)\n      std::cout << \"[INFO] Termminating LIBCDS .... \" << std::endl;\n\n    cds::Terminate();\n  }\n\n  \n\npublic:\n\n  SSSPExecutor() {\n  }\n\n  template <typename Graph, \n\t    typename Algorithm,\n\t    typename WeightMap,\n\t    typename DistanceMap,\n\t    typename graph_create_params>\n  time_type\n  run_algorithm(amplusplus::transport& trans, \n\t\tamplusplus::transport& barrier_trans, \n\t\tGraph& g, \n\t\tAlgorithm& D,\n\t\tWeightMap& weight,\n\t\tDistanceMap& distance,\n\t\tgraph_create_params& gparam,\n\t\tinstance_params& runtime_param,\n\t\tsssp_instance_params& ssspparam) {\n#ifdef CLONE\n    amplusplus::transport trans = trans.clone(); // Clone transport for this run\n#endif\n\n    trans.set_nthreads(1);\n    \n    { amplusplus::scoped_epoch epoch(barrier_trans); }\n\n#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS  \n    epoch_times.clear();\n    clear_buffer_stats();\n#endif\n    \n    // Many threads now\n    trans.set_nthreads(runtime_param.threads);\n\n    boost::scoped_array<boost::thread> threads(new boost::thread[runtime_param.threads - 1]);\n    for (int i = 0; i < runtime_param.threads - 1; ++i) {\n      boost::thread thr(boost::ref(D), i + 1);\n      threads[i].swap(thr);\n    }\n\t  \n    D(0);\n    \n    for (int i = 0; i < runtime_param.threads - 1; ++i)\n      threads[i].join();\n    \n    time_type end = get_time();\n    time_type start = D.get_start_time();\n\n    // Back to one thread\n    trans.set_nthreads(1);\n    clear_thread_core_data();\n\n    // Verification\n    if (ssspparam.verify) {\n      verify_sssp(trans, g, distance, weight); \n    }\n\n    uint64_t total_vertices = count_visited_vertices(g, distance);\n    if (total_vertices < ssspparam.visited_threshold) { \n      ssspparam.work_stats.reset();\n      return -1.;\n    }\n\n    time_type exec_time = end-start;\n    ssspparam.work_stats.reduce_stats(exec_time);\n\n    // Stats\n#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS\n    print_and_clear_epoch_times();\n    print_buffer_stats();\n#endif\n\n    uint64_t edges_in_comp =  count_visited_edges(g, distance);\n\n    if (trans.rank() == 0) {\n      std::cout << \"[INFO] Edge traversals should be : \" << edges_in_comp\n\t\t<< \", vertices visited : \" << total_vertices\n\t\t<< \", Time : \" << exec_time \n\t\t<< \" sec.\" << std::endl;\n    }\n\n    return exec_time;\n  }\n\n\npublic:\n  template <typename Graph, typename MessageGenerator,\n\t    typename graph_create_params>\n  time_type operator()(Graph& g, \n\t\t       amplusplus::transport& trans, \n\t\t       MessageGenerator& msg_gen,\n\t\t       graph_create_params& gparams,\n\t\t       instance_params& runtime_params,\n\t\t       sssp_instance_params& sssp_params) { \n\n    amplusplus::transport barrier_trans = trans.clone();\n\n    // g must be weighted graph\n    typedef boost::compressed_sparse_row_graph<boost::directedS, \n\t\t\t\t\t       boost::no_property, \n\t\t\t\t\t       WeightedEdge, \n\t\t\t\t\t       boost::no_property, \n\t\t\t\t\t       boost::distributedS<unsigned long long> > WGraph;\n    //    static_assert(std::is_same<Graph,WGraph>::value, \"Graph must be a weighted graph\");\n    // bad way of casting!\n    WGraph& weightedgraph = (WGraph&)(g);\n\n    typedef typename boost::graph_traits<WGraph>::vertex_descriptor Vertex;\n    typedef typename boost::graph_traits<WGraph>::vertices_size_type vertices_size_type;\n    typedef typename boost::property_map<WGraph, weight_type WeightedEdge::*>::type WeightMap;\n    typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMap;\n\n    WeightMap weight = boost::get(&WeightedEdge::weight, weightedgraph);\n\n    // Distance map\n    std::vector<weight_type> distanceS(boost::num_vertices(weightedgraph), std::numeric_limits<weight_type>::max());\n    typedef boost::iterator_property_map<std::vector<weight_type>::iterator, VertexIndexMap>  DistanceMap;\n    DistanceMap distance(distanceS.begin(), get(boost::vertex_index, g));\n\n    typedef typename boost::property_traits<WeightMap>::value_type Dist;\n\n    time_type t = -1;\n    while(t == -1) {\n\n      Vertex current_source = boost::vertex(sssp_params.get_source(gparams.n), weightedgraph);    \n      // we need this as some algorithms retrive threads from the transport\n      // we need this here incase if we hit a t=-1\n      trans.set_nthreads(runtime_params.threads);\n\n      if (_RANK == 0)\n\tstd::cout << \"[INFO] Executing SSSP for source : \" << current_source << std::endl;\n\n      if (sssp_params.agm == delta) {\n\tif (sssp_params.eagm == global) {\n\n\t  boost::graph::distributed::delta_stepping_shortest_paths<WGraph, \n\t\t\t\t\t\t\t\t   DistanceMap, \n\t\t\t\t\t\t\t\t   WeightMap,\n\t\t\t\t\t\t\t\t   agm_work_stats,\n\t\t\t\t\t\t\t\t   append_buffer<Vertex, \n\t\t\t\t\t\t\t\t\t\t 10u>, \n\t\t\t\t\t\t\t\t   MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      (Dist)sssp_params.delta_val, \n\t      sched_getcpu(), \n\t      sssp_params.work_stats,\n\t      msg_gen);\n\n\t  D.set_source(current_source);\n\n\t  if (sssp_params.level_sync)\n\t    D.set_level_sync();\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n        }\n\n\tif (sssp_params.eagm == node) {\n\n\t  init_cds();\n\t  boost::graph::distributed::delta_stepping_shortest_paths_node<WGraph, \n\t\t\t\t\t\t\t\t\tDistanceMap, \n\t\t\t\t\t\t\t\t\tWeightMap,\n\t\t\t\t\t\t\t\t\tagm_work_stats,\n\t\t\t\t\t\t\t\t\tNODE_PRIORITY_Q_GEN, \n\t\t\t\t\t\t\t\t\tMessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      (Dist)sssp_params.delta_val, \n\t      sched_getcpu(),\n\t      sssp_params.work_stats,\n\t      runtime_params.flush, \n\t      msg_gen);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n\t  terminate_cds();\n\t} \n\n\tif (sssp_params.eagm == numa) {\n\t  init_cds();\n\t  boost::graph::distributed::delta_stepping_shortest_paths_numa<WGraph, \n\t\t\t\t\t\t\t\t\tDistanceMap, \n\t\t\t\t\t\t\t\t\tWeightMap,\n\t\t\t\t\t\t\t\t\tagm_work_stats,\n\t\t\t\t\t\t\t\t\tNUMA_PRIORITY_Q_GEN, \n\t\t\t\t\t\t\t\t\tMessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      (Dist)sssp_params.delta_val, \n\t      sched_getcpu(),\n\t      sssp_params.work_stats,\n\t      runtime_params.flush, \n\t      msg_gen);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n\n\t  terminate_cds();\n\t} \n\n\tif (sssp_params.eagm == thread) {\n\n\t  boost::graph::distributed::delta_stepping_shortest_paths_thread<WGraph, \n\t\t\t\t\t\t\t\t\t  DistanceMap, \n\t\t\t\t\t\t\t\t\t  WeightMap,\n\t\t\t\t\t\t\t\t\t  agm_work_stats,\n\t\t\t\t\t\t\t\t\t  THREAD_PRIORITY_Q_GEN, \n\t\t\t\t\t\t\t\t\t  MessageGenerator>\n\t    D(weightedgraph, distance, weight, trans, (Dist)sssp_params.delta_val, \n\t      sched_getcpu(), \n\t      sssp_params.work_stats,\n\t      runtime_params.flush,  msg_gen);\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n\t} \n      } // end of delta EAGMs\n\n\n      if (sssp_params.agm == kla) {\n\tif (sssp_params.eagm == global) {\n\n\t  boost::graph::distributed::kla_shortest_paths_buffer<WGraph, \n\t\t\t\t\t\t\t       DistanceMap, \n\t\t\t\t\t\t\t       WeightMap,\n\t\t\t\t\t\t\t       agm_work_stats,\n\t\t\t\t\t\t\t       append_buffer<std::pair<Vertex, std::pair<Dist, size_t> >, 10u>,\n\t\t\t\t\t\t\t       MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      (size_t)sssp_params.k_val,\n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n\t      msg_gen);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n\t} \n\n\tif (sssp_params.eagm == node) {\n\t  init_cds();\n\t  boost::graph::distributed::kla_shortest_paths_node<WGraph, \n\t\t\t\t\t\t\t     DistanceMap, \n\t\t\t\t\t\t\t     WeightMap,\n\t\t\t\t\t\t\t     agm_work_stats,\n\t\t\t\t\t\t\t     NODE_PRIORITY_Q_GEN,\n\t\t\t\t\t\t\t     MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      (size_t)sssp_params.k_val,\n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n              runtime_params.flush,\n\t      msg_gen);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n\n          terminate_cds();\n        }\n\n\tif (sssp_params.eagm == numa) {\n\t  init_cds();\n\t  boost::graph::distributed::kla_shortest_paths_numa<WGraph, \n\t\t\t\t\t\t\t     DistanceMap, \n\t\t\t\t\t\t\t     WeightMap,\n\t\t\t\t\t\t\t     agm_work_stats,\n\t\t\t\t\t\t\t     NUMA_PRIORITY_Q_GEN,\n\t\t\t\t\t\t\t     MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      (size_t)sssp_params.k_val,\n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n              runtime_params.flush,\n\t      msg_gen);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n          terminate_cds();\n        }\n\n\tif (sssp_params.eagm == thread) {\n\n\t  boost::graph::distributed::kla_shortest_paths_thread<WGraph, \n\t\t\t\t\t\t\t       DistanceMap, \n\t\t\t\t\t\t\t       WeightMap,\n\t\t\t\t\t\t\t       agm_work_stats,\n\t\t\t\t\t\t\t       THREAD_PRIORITY_Q_GEN,\n\t\t\t\t\t\t\t       MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      (size_t)sssp_params.k_val,\n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n              runtime_params.flush,\n\t      msg_gen);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n        }\n      } // end of kla EAGMs\n\n\n\n      if (sssp_params.agm == chaotic) {\n\tif (sssp_params.eagm == global) {\n\n\t  boost::graph::distributed::distributed_control_chaotic<WGraph, \n\t\t\t\t\t\t\t\t DistanceMap, \n\t\t\t\t\t\t\t\t WeightMap,\n\t\t\t\t\t\t\t\t agm_work_stats,\n\t\t\t\t\t\t\t\t MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n\t      msg_gen,\n              runtime_params.flush);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n\t} \n\n\tif (sssp_params.eagm == node) {\n\t  init_cds();\n\t  boost::graph::distributed::distributed_control_node<WGraph, \n\t\t\t\t\t\t\t      DistanceMap, \n\t\t\t\t\t\t\t      WeightMap,\n\t\t\t\t\t\t\t      agm_work_stats,\n\t\t\t\t\t\t\t      NODE_PRIORITY_Q_GEN,\n\t\t\t\t\t\t\t      MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n\t      msg_gen,\n              runtime_params.flush,\n              false);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n          terminate_cds();\n        }\n\n\tif (sssp_params.eagm == numa) {\n\t  init_cds();\n\t  boost::graph::distributed::distributed_control_node<WGraph, \n\t\t\t\t\t\t\t      DistanceMap, \n\t\t\t\t\t\t\t      WeightMap,\n\t\t\t\t\t\t\t      agm_work_stats,\n\t\t\t\t\t\t\t      NUMA_PRIORITY_Q_GEN,\n\t\t\t\t\t\t\t      MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n\t      msg_gen,\n              runtime_params.flush,\n              true); //NUMA\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n          terminate_cds();\n\n        }\n\n\tif (sssp_params.eagm == thread) {\n\n\t  boost::graph::distributed::distributed_control<WGraph, \n\t\t\t\t\t\t\t DistanceMap, \n\t\t\t\t\t\t\t WeightMap,\n\t\t\t\t\t\t\t agm_work_stats,\n\t\t\t\t\t\t\t boost::graph::distributed::default_priority_queue_gen,\n\t\t\t\t\t\t\t MessageGenerator>\n\t    D(weightedgraph, \n\t      distance, \n\t      weight, \n\t      trans, \n\t      sched_getcpu(),\n\t      sssp_params.work_stats, \n              msg_gen,\n              runtime_params.flush);\n\n\t  D.set_source(current_source);\n\n\t  t = run_algorithm(trans,\n\t\t\t    barrier_trans,\n\t\t\t    weightedgraph,\n\t\t\t    D,\n\t\t\t    weight,\n\t\t\t    distance,\n\t\t\t    gparams,\n\t\t\t    runtime_params,\n\t\t\t    sssp_params);\n\t}\n      } // end of Chaotic EAGMs\n\n\n      if (t == -1) {\n\tif (_RANK == 0)\n\t  std::cout << \"[WARNING] Execution did not traversed threshold amount of vertices.\"\n\t\t    << \" Threshold : \" << sssp_params.visited_threshold \n\t\t    << \". Continuing...\"\n\t\t    << std::endl;\n      } else\n\treturn t;\n    } // end of while(t == -1) \n\n  }\n\n};\n\n\nint main(int argc, char* argv[]) {\n  std::cout << \"printing core id for process ...\" << std::endl;\n  print_core_id();\n\n  executor<SSSPExecutor, sssp_params, sssp_instance_params> sssp_executor;\n  sssp_executor.execute(argc, argv);  \n  amplusplus::clear_mpi_datatype_map();\n}\n", "meta": {"hexsha": "73452e91dd0e0b6bcfd3680dc65fffd9fb513386", "size": 19374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph_parallel/drivers/sssp_family.cpp", "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": "libs/graph_parallel/drivers/sssp_family.cpp", "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": "libs/graph_parallel/drivers/sssp_family.cpp", "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": 27.0965034965, "max_line_length": 116, "alphanum_fraction": 0.6275936823, "num_tokens": 4779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416623541848, "lm_q2_score": 0.04813676872695534, "lm_q1q2_score": 0.014635583184102437}}
{"text": "/*\n Copyright (c) 2015 Siyu Lei, Silviu Maniu, Luyi Mo\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 __oim__CELFEvaluator__\n#define __oim__CELFEvaluator__\n\n#include <boost/heap/fibonacci_heap.hpp>\n\n#include \"common.hpp\"\n#include \"Evaluator.hpp\"\n\nclass CELFEvaluator : public Evaluator {\n private:\n  struct celf_node_type {\n    unode_int id;\n    double spr;\n    bool operator<(const celf_node_type &a) const {\n      return (spr < a.spr) ? true : ((spr > a.spr) ? false : id > a.id);\n    }\n  };\n  unsigned int samples_;\n\n public:\n  CELFEvaluator(unsigned int samples) : samples_(samples) {}\n\n  std::unordered_set<unode_int> select(\n      const Graph& graph, Sampler& sampler,\n      const std::unordered_set<unode_int>& activated, unsigned int k) {\n    boost::heap::fibonacci_heap<celf_node_type> queue;\n    std::unordered_map<unode_int,\n      boost::heap::fibonacci_heap<celf_node_type>::handle_type> queue_nodes;\n    std::unordered_set<unode_int> set;\n\n    // Initial loop\n    for (unode_int node : graph.get_nodes()) {\n      celf_node_type u;\n      u.id = node;\n      std::unordered_set<unode_int> seeds;\n      seeds.insert(node);\n      u.spr = sampler.sample(graph, activated, seeds, samples_);\n      queue_nodes[node] = queue.push(u);\n    }\n\n    // Main loop\n    set.insert(queue.top().id);\n    queue.pop();\n    while ((set.size() < k) && (queue.size() > 0)) {\n      bool found = false;\n      while (!found) {\n        celf_node_type u = queue.top();\n        queue.pop();\n        std::unordered_set<unode_int> seeds;\n        for (unode_int node : set) seeds.insert(node);\n        seeds.insert(u.id);\n        double prev_val = u.spr;\n        u.spr = sampler.sample(graph, activated, seeds, samples_) - prev_val;\n        if (u.spr >= queue.top().spr) {\n          set.insert(u.id);\n          found = true;\n        } else {\n          queue_nodes[u.id] = queue.push(u);\n        }\n      }\n    }\n    return set;\n  }\n};\n\n#endif /* defined(__oim__CELFEvaluator__) */\n", "meta": {"hexsha": "0971669d4bb12092a66468fe430e0d5862f73050", "size": 2965, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CELFEvaluator.hpp", "max_stars_repo_name": "smaniu/oim", "max_stars_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-05-21T13:54:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T11:47:17.000Z", "max_issues_repo_path": "src/CELFEvaluator.hpp", "max_issues_repo_name": "smaniu/oim", "max_issues_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-30T03:34:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-25T18:28:38.000Z", "max_forks_repo_path": "src/CELFEvaluator.hpp", "max_forks_repo_name": "smaniu/oim", "max_forks_repo_head_hexsha": "312b02e74ce916cb8c7172e76726db9b8f2fb13f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T08:45:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-17T04:36:22.000Z", "avg_line_length": 33.3146067416, "max_line_length": 78, "alphanum_fraction": 0.6819561551, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.03461883896367643, "lm_q1q2_score": 0.0146266199140393}}
{"text": "#include \"ExpressionGraph.hpp\"\n#include \"RandomUniform.hpp\"\n#include <boost/functional/hash.hpp>\n#include <deque>\n#include <cassert>\n#include <stack>\n\nnamespace sdo\n{\n\nbool ExpressionGraph::structural_node_eq::operator()( const Node *a, const Node *b ) const\n{\n   if( a->op != b->op )\n   {\n      switch( a->op )\n      {\n      case G:\n         return b->op == LE && a->child1 == b->child2 && a->child2 == b->child1;\n\n      case GE:\n         return b->op == L && a->child1 == b->child2 && a->child2 == b->child1;\n\n      case L:\n         return b->op == GE && a->child1 == b->child2 && a->child2 == b->child1;\n\n      case LE:\n         return b->op == G && a->child1 == b->child2 && a->child2 == b->child1;\n\n      default:\n         return false;\n      }\n   }\n\n   switch( a->op )\n   {\n   case LOOKUP_TABLE:\n      return a->lookup_table == b->lookup_table;\n\n   case CONSTANT:\n      return a->value == b->value;\n\n   case TIME:\n      return true;\n\n   case RANDOM_UNIFORM:\n      return false;\n\n   case IF:\n   case DELAY_FIXED:\n   case PULSE_TRAIN:\n   case RAMP:\n      return a->child1 == b->child1 && a->child2 == b->child2 && a->child3 == b->child3;\n\n   case MULT:\n   case PLUS:\n   case MIN:\n   case MAX:\n   case EQ:\n   case NEQ:\n   case OR:\n   case AND:\n      return ( a->child1 == b->child1 && a->child2 == b->child2 ) ||\n             ( a->child2 == b->child1 && a->child1 == b->child2 );\n\n   case MINUS:\n   case DIV:\n   case G:\n   case GE:\n   case L:\n   case LE:\n   case POWER:\n   case LOG:\n   case MODULO:\n   case INTEG:\n   case ACTIVE_INITIAL:\n   case PULSE:\n   case STEP:\n   case APPLY_LOOKUP:\n      return a->child1 == b->child1 && a->child2 == b->child2;\n\n   case UMINUS:\n   case SQRT:\n   case EXP:\n   case LN:\n   case ABS:\n   case INTEGER:\n   case NOT:\n   case SIN:\n   case COS:\n   case TAN:\n   case ARCSIN:\n   case ARCCOS:\n   case ARCTAN:\n   case SINH:\n   case COSH:\n   case TANH:\n   case INITIAL:\n      return a->child1 == b->child1;\n\n   case CONTROL:\n   case NIL:\n      return a == b;\n   }\n\n   assert( false );\n   return false;\n}\n\nstd::size_t ExpressionGraph::structural_node_hash::operator()( const Node *node ) const\n{\n   switch( node->op )\n   {\n   case LOOKUP_TABLE:\n      return hash_value( *( node->lookup_table ) );\n\n   case CONSTANT:\n      return boost::hash_value( node->value );\n\n   case TIME:\n      return boost::hash_value( TIME );\n\n   case RANDOM_UNIFORM:\n      return 0;\n\n   case IF:\n   case DELAY_FIXED:\n   case PULSE_TRAIN:\n   case RAMP:\n   {\n      std::size_t hash = boost::hash_value( node->op );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child1 ) );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child2 ) );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child3 ) );\n      return hash;\n   }\n\n   case MULT:\n   case PLUS:\n   case MIN:\n   case MAX:\n   case EQ:\n   case NEQ:\n   case OR:\n   case AND:\n   {\n      std::size_t hash = boost::hash_value( node->op );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child1 ) ^\n                           reinterpret_cast<uintptr_t>( node->child2 ) );\n      return hash;\n   }\n\n   case G:\n   case LE:\n   {\n      std::size_t hash = boost::hash_value( G );\n      boost::hash_combine( hash, boost::hash_value( LE ) );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child1 ) ^\n                           reinterpret_cast<uintptr_t>( node->child2 ) );\n   }\n\n   case L:\n   case GE:\n   {\n      std::size_t hash = boost::hash_value( L );\n      boost::hash_combine( hash, boost::hash_value( GE ) );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child1 ) ^\n                           reinterpret_cast<uintptr_t>( node->child2 ) );\n   }\n\n   case MINUS:\n   case DIV:\n   case POWER:\n   case LOG:\n   case MODULO:\n   case INTEG:\n   case APPLY_LOOKUP:\n   case ACTIVE_INITIAL:\n   case PULSE:\n   case STEP:\n   {\n      std::size_t hash = boost::hash_value( node->op );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child1 ) );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child2 ) );\n      return hash;\n   }\n\n   case UMINUS:\n   case SQRT:\n   case EXP:\n   case LN:\n   case ABS:\n   case INTEGER:\n   case NOT:\n   case SIN:\n   case COS:\n   case TAN:\n   case ARCSIN:\n   case ARCCOS:\n   case ARCTAN:\n   case SINH:\n   case COSH:\n   case TANH:\n   case INITIAL:\n   {\n      std::size_t hash = boost::hash_value( node->op );\n      boost::hash_combine( hash, reinterpret_cast<uintptr_t>( node->child1 ) );\n      return hash;\n   }\n\n   case CONTROL:\n   case NIL:\n      return boost::hash_value( reinterpret_cast<uintptr_t>( node ) );\n   }\n\n   assert( false );\n\n   return -1;\n}\n\n\nvoid ExpressionGraph::addSymbol( const Symbol &s, ExpressionGraph::Node *node )\n{\n   auto sym = symbol_table.find( s );\n\n   if( sym != symbol_table.end() )\n   {\n      //if node is not previously undefined do not change it instead return\n      if( sym->second->op != NIL )\n         return;\n\n      auto eq_range = node_table.equal_range( sym->second );\n      std::vector<Symbol> prev_symbols;\n\n      for( auto it = eq_range.first; it != eq_range.second; ++it )\n      {\n         if( it->second != s )\n         {\n            prev_symbols.emplace_back( it->second );\n            symbol_table[it->second] = node;\n         }\n      }\n\n      node_table.erase( eq_range.first, eq_range.second );\n\n      for( auto & sym : prev_symbols )\n      {\n         node_table.emplace( node, std::move( sym ) );\n      }\n\n      substituteTmpNode( sym->second, node );\n   }\n\n   symbol_table[s] = node;\n   node_table.emplace( node, s );\n}\n\nExpressionGraph::Node *ExpressionGraph::getNode( const Symbol &s )\n{\n   auto i = symbol_table.find( s );\n\n   if( i != symbol_table.end() )\n      return i->second;\n\n   Node *n = createTmpNode();\n   symbol_table[s] = n;\n   node_table.emplace( n, s );\n   return n;\n}\n\nExpressionGraph::Node *ExpressionGraph::getNode( Operator op, Node *child )\n{\n   Node *a = node_pool_.construct();\n   a->child1 = child;\n   a->op     = op;\n   auto b = nodes_.find( a );\n\n   if( b != nodes_.end() )\n   {\n      node_pool_.free( a );\n      return *b;\n   }\n\n   if( child->op == NIL )\n      temp_node_usages_.emplace( child, &( a->child1 ) );\n\n   nodes_.emplace( a );\n   return a;\n}\n\nExpressionGraph::Node *ExpressionGraph::getNode( Operator op, Node *child1, Node *child2 )\n{\n   Node *a = node_pool_.construct();\n   a->child1 = child1;\n   a->child2 = child2;\n   a->op     = op;\n   auto b = nodes_.find( a );\n\n   if( b != nodes_.end() )\n   {\n      node_pool_.free( a );\n      return *b;\n   }\n\n   if( child1->op == NIL )\n      temp_node_usages_.emplace( child1, &( a->child1 ) );\n\n   if( child2->op == NIL )\n      temp_node_usages_.emplace( child2, &( a->child2 ) );\n\n   nodes_.emplace( a );\n   return a;\n}\n\nExpressionGraph::Node *ExpressionGraph::getNode( Operator op, Node *child1, Node *child2, Node *child3 )\n{\n   Node *a = node_pool_.construct();\n   a->child1 = child1;\n   a->child2 = child2;\n   a->child3 = child3;\n   a->op     = op;\n   auto b = nodes_.find( a );\n\n   if( b != nodes_.end() )\n   {\n      node_pool_.free( a );\n      return *b;\n   }\n\n   if( child1 && child1->op == NIL )\n      temp_node_usages_.emplace( child1, &( a->child1 ) );\n\n   if( child2 && child2->op == NIL )\n      temp_node_usages_.emplace( child2, &( a->child2 ) );\n\n   if( child3 && child3->op == NIL )\n      temp_node_usages_.emplace( child3, &( a->child3 ) );\n\n   nodes_.emplace( a );\n   return a;\n}\n\nExpressionGraph::Node *ExpressionGraph::getNode( double val )\n{\n   Node *a = node_pool_.construct();\n   a->op    = CONSTANT;\n   a->value = val;\n   a->type  = CONSTANT_NODE;\n   a->init = CONSTANT_INIT;\n   a->level = 0;\n\n   if( !unique_constants )\n   {\n      auto b = nodes_.find( a );\n\n      if( b != nodes_.end() )\n      {\n         node_pool_.free( a );\n         return *b;\n      }\n   }\n\n   nodes_.emplace( a );\n   return a;\n}\n\nExpressionGraph::Node *ExpressionGraph::getTimeNode()\n{\n   Node *a = node_pool_.construct();\n   a->op = TIME;\n   auto b = nodes_.find( a );\n\n   if( b != nodes_.end() )\n   {\n      node_pool_.free( a );\n      return *b;\n   }\n\n   nodes_.emplace( a );\n   return a;\n}\n\nLookupTable *ExpressionGraph::createLookupTable()\n{\n   return lookup_pool_.construct();\n}\n\nExpressionGraph::Node *ExpressionGraph::createTmpNode()\n{\n   Node *n = node_pool_.construct();\n   n->op = NIL;\n   return n;\n}\n\nvoid ExpressionGraph::analyze()\n{\n   std::deque<Node *> node_deque;\n   Node *initial_time_node = getNode( Symbol( \"INITIAL TIME\" ) );\n   Node *final_time_node   = getNode( Symbol( \"FINAL TIME\" ) );\n   Node *time_step_node    = getNode( Symbol( \"TIME STEP\" ) );\n\n   for( std::pair<const Symbol, Node *> &p : symbol_table )\n   {\n      if( p.second->op == INTEG )\n      {\n         node_deque.push_back( p.second );\n      }\n      else if( p.second != initial_time_node && p.second != final_time_node && p.second != time_step_node )\n      {\n         node_deque.push_front( p.second );\n      }\n   }\n\n   node_deque.push_back( initial_time_node );\n   node_deque.push_back( final_time_node );\n   node_deque.push_back( time_step_node );\n   node_deque.push_back( getTimeNode() );\n\n   while( !node_deque.empty() )\n   {\n      Node *node = node_deque.back();\n\n      if( node->type != UNKNOWN )\n      {\n         node_deque.pop_back();\n         continue;\n      }\n\n      switch( node->op )\n      {\n      case INTEG:\n         if( node->child2->init == UNKNOWN_INIT )\n         {\n            node_deque.push_back( node->child2 );\n            continue;\n         }\n\n         node->type  = DYNAMIC_NODE;\n         node->level = node->child2->level + 1;\n         node->init  = node->child2->init;\n\n         if( node->init == CONSTANT_INIT )\n         {\n            node->value = node->child2->value;\n         }\n\n         node_deque.pop_back();\n         node_deque.push_front( node->child1 );\n         continue;\n\n      case IF:\n      {\n         node->type  = NodeType( node->child1->type | node->child2->type | node->child3->type );\n         node->init  = InitialType( node->child1->init | node->child2->init | node->child3->init );\n         node->level = std::max( {node->child1->level, node->child2->level, node->child3->level} ) + 1;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value ? node->child2->value : node->child3->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child3 );\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n         }\n\n         continue;\n      }\n\n      case ACTIVE_INITIAL:\n      {\n         node->type  = NodeType( node->child2->type | node->child1->type );\n         node->init  = node->child2->init;\n         node->level = node->child2->level;\n\n         if( node->init == UNKNOWN_INIT )\n         {\n            node_deque.push_back( node->child2 );\n            continue;\n         }\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            if( node->init == CONSTANT_INIT )\n            {\n               node->value = node->child2->value;\n            }\n\n            node->level = std::max( node->child1->level + 1, node->child2->level );\n            node_deque.pop_back();\n            continue;\n\n         case CONSTANT_NODE:\n            error( node->usages, \"Use of ACTIVE INITIAL while active equation is constant.\" );\n            node->level = std::max( node->child1->level + 1, node->child2->level );\n            node->value = node->child1->value;\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.pop_back();\n            node_deque.push_front( node->child1 );\n            node_deque.push_front( node );\n         }\n\n         continue;\n      }\n\n      case INITIAL:\n         if( node->child1->init == UNKNOWN_INIT )\n         {\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n\n         node->level = node->child1->level;\n\n         if( node->child1->init == CONSTANT_INIT )\n         {\n            node->type  = CONSTANT_NODE;\n            node->init  = CONSTANT_INIT;\n            node->value = node->child1->value;\n         }\n         else\n         {\n            node->type = DYNAMIC_NODE;\n            node->init = CONTROLED_INIT;\n         }\n\n         node_deque.pop_back();\n         continue;\n\n      case DELAY_FIXED:\n      {\n         if( node->child3->type == UNKNOWN )\n            node->type = UNKNOWN;\n         else\n            node->type = NodeType( node->child1->type | node->child2->type | STATIC_NODE );\n\n         if( node->type != UNKNOWN )\n         {\n            node->init = node->child3->init;\n\n            if( node->child1->type == CONSTANT_NODE )\n               warning( node->usages,\n                        \"DELAY FIXED used with constant input. Consider using STEP instead.\" );\n\n            if( node->child2->type != CONSTANT_NODE )\n               warning( node->usages,\n                        \"DELAY FIXED used with non constant delay time. Only initial value will be used.\" );\n         }\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level     = std::max( {node->child1->level, node->child2->level, node->child3->level, getTimeNode()->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n               node->value = node->child3->value;\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child3 );\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         case CONSTANT_NODE:\n            assert( false );\n         }\n\n         continue;\n      }\n\n      case PULSE:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type | STATIC_NODE );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n            error( node->usages, \"Using PULSE with non constant arguments\" );\n\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level, getTimeNode()->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n               double initial_time = initial_time_node->value;\n               double time_step    = time_step_node->value;\n               double time_plus    = initial_time + 0.5 * time_step;\n               double start        = node->child1->value;\n               double width        = node->child2->value;\n               node->value          = time_plus > start && time_plus < start + width ? 1. : 0.;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         case CONSTANT_NODE:\n            assert( false );\n         }\n\n         continue;\n      }\n\n      case PULSE_TRAIN:\n      {\n         node->type = NodeType(\n                         node->child1->child1->type | node->child1->child2->type | node->child2->type | node->child3->type | STATIC_NODE );\n         node->init = InitialType(\n                         node->child1->child1->init | node->child1->child2->init | node->child2->init | node->child3->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n            error( node->usages, \"Using PULSE TRAIN with non constant arguments\" );\n\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->child1->level, node->child1->child2->level, node->child2->level,\n                                     node->child3->level, getTimeNode()->level\n                                    } ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n               double initial_time = initial_time_node->value;\n               double time_step    = time_step_node->value;\n               double time_plus    = initial_time + 0.5 * time_step;\n               double start        = node->child1->child1->value;\n               double width        = node->child1->child2->value;\n               double tbetween     = node->child2->value;\n               double end          = node->child3->value;\n\n               if( tbetween < width )\n               {\n                  node->value = time_plus > start && time_plus < end ? 1. : 0.;\n               }\n               else\n               {\n                  node->value = time_plus > start && time_plus < start + width ? 1. : 0.;\n               }\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child3 );\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1->child2 );\n            node_deque.push_back( node->child1->child1 );\n            continue;\n\n         case CONSTANT_NODE:\n            assert( false );\n         }\n\n         continue;\n      }\n\n      case STEP:\n      {\n         node->type           = NodeType( node->child1->type | node->child2->type | STATIC_NODE );\n         double initial_time = initial_time_node->value;\n\n         if( node->type != UNKNOWN )\n         {\n            if( node->child2->type != CONSTANT_NODE )\n            {\n               error( node->usages, \"STEP used with non constant step time\" );\n            }\n            else if( node->child2->value <= initial_time )\n            {\n               warning( node->usages,\n                        \"Usage of STEP has no effect because step time is at or before initial time\" );\n               node->init = node->child1->init;\n\n               if( node->init == CONSTANT_INIT )\n               {\n                  node->value = node->child1->value;\n               }\n            }\n            else\n            {\n               node->init  = CONSTANT_INIT;\n               node->value = 0.0;\n            }\n         }\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level, getTimeNode()->level} ) + 1;\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         case CONSTANT_NODE:\n            assert( false );\n         }\n\n         continue;\n      }\n\n      case RAMP:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type | node->child3->type | STATIC_NODE );\n\n         if( node->type != UNKNOWN )\n         {\n            int non_const_count = ( node->child1->type != CONSTANT_NODE ) +\n                                  ( node->child2->type != CONSTANT_NODE ) +\n                                  ( node->child3->type != CONSTANT_NODE );\n\n            if( non_const_count )\n            {\n               std::string msg {\"Use of RAMP with \"};\n\n               switch( non_const_count )\n               {\n               case 3:\n                  msg += \"arguments one, two and three\";\n                  break;\n\n               case 2:\n               {\n                  msg += \"arguments \";\n\n                  if( node->child1->type == CONSTANT_NODE )\n                     msg += \"two and three\";\n\n                  if( node->child2->type == CONSTANT_NODE )\n                     msg += \"one and three\";\n\n                  if( node->child3->type == CONSTANT_NODE )\n                     msg += \"one and two\";\n\n                  break;\n               }\n\n               case 1:\n               {\n                  msg += \"argument \";\n\n                  if( node->child1->type != CONSTANT_NODE )\n                     msg += \"one\";\n\n                  if( node->child2->type != CONSTANT_NODE )\n                     msg += \"two\";\n\n                  if( node->child3->type != CONSTANT_NODE )\n                     msg += \"three\";\n               }\n               }\n\n               msg += \" not constant\";\n               error( node->usages, msg );\n            }\n\n            node->init  = CONSTANT_INIT;\n            node->value = 0.0;\n            node->level = std::max( {node->child1->level, node->child2->level, node->child3->level, getTimeNode()->level} ) + 1;;\n            node_deque.pop_back();\n            continue;\n         }\n\n         node_deque.push_back( node->child3 );\n         node_deque.push_back( node->child2 );\n         node_deque.push_back( node->child1 );\n         continue;\n      }\n\n      case RANDOM_UNIFORM:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type | STATIC_NODE );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n            error( node->usages, \"RANDOM UNIFORM used with non constant arguments.\" );\n\n         case STATIC_NODE:\n            node->init  = CONSTANT_INIT;\n            node->value = sdo::random_uniform( node->child1->value, node->child2->value );\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         case CONSTANT_NODE:\n            assert( false );\n         }\n      };\n\n      case PLUS:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value + node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case MINUS:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value - node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case MULT:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value * node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case DIV:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value / node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case G:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value > node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case GE:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value >= node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case L:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value < node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case LE:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value <= node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case EQ:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value == node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case NEQ:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value != node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case AND:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value && node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case OR:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value || node->child2->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case POWER:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::pow( node->child1->value, node->child2->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case LOG:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::log( node->child1->value ) / std::log( node->child2->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case MIN:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::min( node->child1->value, node->child2->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case MAX:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::max( node->child1->value, node->child2->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n\n         }\n      }\n\n      case MODULO:\n      {\n         node->type = NodeType( node->child1->type | node->child2->type );\n         node->init = InitialType( node->child1->init | node->child2->init );\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = std::max( {node->child1->level, node->child2->level} ) + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->value -\n                             node->child2->value * std::floor( node->child1->value / node->child2->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case UMINUS:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = -node->child1->value;\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case SQRT:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::sqrt( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case EXP:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::exp( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case LN:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::log( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case ABS:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::abs( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case INTEGER:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::floor( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case NOT:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = !( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case SIN:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::sin( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case COS:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::cos( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case TAN:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::tan( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case ARCSIN:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::asin( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case ARCCOS:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::acos( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case ARCTAN:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::atan( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case SINH:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::sinh( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case COSH:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::cosh( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case TANH:\n      {\n         node->type = node->child1->type;\n         node->init = node->child1->init;\n\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child1->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = std::tanh( node->child1->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child1 );\n            continue;\n         }\n      }\n\n      case TIME:\n      {\n         node->type  = STATIC_NODE;\n         node->init  = CONSTANT_INIT;\n         node->level = 1;\n         node->value = initial_time_node->value;\n         node_deque.pop_back();\n         continue;\n      }\n\n      case CONSTANT:\n      {\n         assert( false );\n         node_deque.pop_back();\n         continue;\n      }\n\n      case CONTROL:\n      {\n         node->type  = DYNAMIC_NODE;\n         node->init = CONTROLED_INIT;\n         node->level = 0;\n         node_deque.pop_back();\n         continue;\n      }\n\n      case APPLY_LOOKUP:\n      {\n         if( node->child1->op != LOOKUP_TABLE )\n         {\n            error( node->child1->usages, \"Symbol not a lookup table\" );\n         }\n\n         node->type = node->child2->type;\n         node->init = node->child2->init;\n\n         bool yConst = true;\n\n         auto yVals = node->child1->lookup_table->getYvals();\n         double oldYval = yVals[0];\n         double eps = 1e-9;\n         for (auto yVal : yVals)\n         {\n            if( oldYval - eps >= yVal || yVal >= oldYval + eps)\n            {\n               yConst = false;\n               break;\n            }\n            oldYval = yVal;\n         }\n         if (yConst == true)\n         {\n            printf(\"Detected constant lookup with value %f\\n\", oldYval);\n\n            node->value = oldYval;\n            node->type = CONSTANT_NODE;\n            node->init = CONSTANT_INIT;\n            continue;\n         }\n         switch( node->type )\n         {\n         case DYNAMIC_NODE:\n         case STATIC_NODE:\n            node->level = node->child2->level + 1;\n\n            if( node->init == CONSTANT_INIT )\n            {\n            case CONSTANT_NODE:\n               node->value = node->child1->lookup_table->operator()( node->child2->value );\n            }\n\n            node_deque.pop_back();\n            continue;\n\n         case UNKNOWN:\n            node_deque.push_back( node->child2 );\n            continue;\n         }\n      }\n\n      case LOOKUP_TABLE:\n      {\n         assert( false );\n         node_deque.pop_back();\n         continue;\n      }\n\n      case NIL:\n      {\n         auto s = getSymbol( node );\n         std::string msg;\n\n         if( !s.empty() )\n         {\n            msg += \"Use of undefined symbol '\";\n            msg += s.begin()->second.get();\n            msg += \"'\";\n         }\n         else\n         {\n            msg += \"Something has gone terribly wrong. NIL node found but it has no symbol attached\";\n         }\n\n         error( node->usages, msg );\n         node->type  = CONSTANT_NODE;\n         node->value = 0.0;\n         node->init  = CONSTANT_INIT;\n         node->level = 0;\n         node_deque.pop_back();\n         continue;\n      }\n      }\n   }\n\n\n   if( initial_time_node->type != CONSTANT_NODE )\n      error( initial_time_node->usages, \"INITIAL TIME is not constant\" );\n\n   if( time_step_node->type != CONSTANT_NODE )\n      error( time_step_node->usages, \"TIME STEP is not constant\" );\n\n   if( final_time_node->type != CONSTANT_NODE )\n      error( final_time_node->usages, \"FINAL TIME is not constant\" );\n\n   if( hasErrors() )\n      throw parse_error( *this );\n}\n\nvoid ExpressionGraph::useUniqueConstants( bool val )\n{\n   unique_constants = val;\n}\n\nvoid ExpressionGraph::substituteTmpNode( ExpressionGraph::Node *tmp, ExpressionGraph::Node *subst )\n{\n   auto eq_range = temp_node_usages_.equal_range( tmp );\n   subst->usages.insert( subst->usages.end(), tmp->usages.begin(), tmp->usages.end() );\n\n   if( eq_range.first != eq_range.second )\n   {\n      if( subst->op == NIL )\n      {\n         std::vector<Node **> usages;\n\n         for( auto i = eq_range.first; i != eq_range.second; ++i )\n         {\n            *( i->second ) = subst;\n            usages.emplace_back( i->second );\n         }\n\n         temp_node_usages_.erase( eq_range.first, eq_range.second );\n\n         for( Node **usg : usages )\n            temp_node_usages_.emplace( subst, usg );\n      }\n      else\n      {\n         for( auto i = eq_range.first; i != eq_range.second; ++i )\n            *( i->second ) = subst;\n\n         temp_node_usages_.erase( eq_range.first, eq_range.second );\n      }\n\n      node_pool_.free( tmp );\n   }\n}\n\nExpressionGraph::Node *ExpressionGraph::getNode( LookupTable *table )\n{\n   Node *a = node_pool_.construct();\n   a->op           = LOOKUP_TABLE;\n   a->lookup_table = table;\n   a->type         = CONSTANT_NODE;\n   a->level        = 0;\n   auto b = nodes_.find( a );\n\n   if( b != nodes_.end() )\n   {\n      node_pool_.free( a );\n      lookup_pool_.destroy( table );\n      return *b;\n   }\n\n   nodes_.emplace( a );\n   return a;\n}\n\ndouble ExpressionGraph::evaluateNode( const Node *node, double time, bool initial ) const\n{\n   assert( node->type == STATIC_NODE || node->type == CONSTANT_NODE );\n   std::stack<const Node *> nodes;\n   nodes.push( nullptr );\n   std::stack<double> vals;\n   std::stack<int> valsoffset;\n   valsoffset.push(0);\n\n   auto push_ternary = [&]()\n   {\n      nodes.push( node );\n      valsoffset.push(vals.size() + 2);\n      nodes.push( node->child1 );\n      valsoffset.push(vals.size() + 1);\n      nodes.push( node->child2 );\n      valsoffset.push(vals.size());\n      node = node->child3;\n   };\n\n   auto push_binary = [&]()\n   {\n      nodes.push( node );\n      valsoffset.push(vals.size() + 1);\n      nodes.push( node->child1 );\n      valsoffset.push(vals.size());\n      node = node->child2;\n   };\n\n   auto push_unary = [&]()\n   {\n      nodes.push( node );\n      valsoffset.push(vals.size());\n      node = node->child1;\n   };\n\n   auto pop_node = [&]()\n   {\n      node = nodes.top();\n      valsoffset.pop();\n      nodes.pop();\n   };\n\n   double time_step = symbol_table.find( Symbol( \"TIME STEP\" ) )->second->value;\n   double time_plus = time + time_step / 2;\n   do\n   {\n      if( node->type == CONSTANT_NODE )\n      {\n         vals.push( node->value );\n         pop_node();\n      }\n      else\n      {\n         switch( node->op )\n         {\n         case DELAY_FIXED:\n            //TODO:\n            continue;\n\n         case CONTROL:\n         case LOOKUP_TABLE:\n         case NIL:\n         case CONSTANT:\n         case INTEG:\n            assert( false );\n            continue;\n\n         case SQRT:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::sqrt( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case UMINUS:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = -vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case ACTIVE_INITIAL:\n            if( initial )\n               node = node->child2;\n            else\n               node = node->child1;\n\n            continue;\n\n         case APPLY_LOOKUP:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               nodes.push( node );\n               valsoffset.push(vals.size());\n               node = node->child2;\n            }\n            else\n            {\n               auto &lkptbl = *( node->child1->lookup_table );\n               vals.top() = lkptbl( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case ARCCOS:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::acos( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case ARCSIN:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::asin( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case ARCTAN:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::atan( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case SIN:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::sin( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case COS:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::cos( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case TAN:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::tan( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case COSH:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::cosh( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case SINH:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::sinh( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case TANH:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::tanh( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case DIV:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = ( a / vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case EQ:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = ( a == vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case EXP:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::exp( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case ABS:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::abs( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case AND:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a && vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case G:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a > vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case GE:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a >= vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case IF:\n            if( int(vals.size()) - valsoffset.top() < 3 )\n            {\n               push_ternary();\n            }\n            else\n            {\n               double cond = vals.top();\n               vals.pop();\n               double thenval = vals.top();\n               vals.pop();\n               vals.top() = cond ? thenval : vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case INITIAL:\n            vals.push( node->value );\n            pop_node();\n            continue;\n\n         case TIME:\n            vals.push( time );\n            pop_node();\n            continue;\n\n         case INTEGER:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::floor( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case L:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a < vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case LE:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a <= vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case LN:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = std::log( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case LOG:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = std::log( a ) / std::log( vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case MAX:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = std::max( a, vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case MIN:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = std::min( a, vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case MINUS:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a - vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case MODULO:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = std::fmod( a, vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case MULT:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a * vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case NEQ:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a != vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case NOT:\n            if( int(vals.size()) - valsoffset.top() < 1 )\n            {\n               push_unary();\n            }\n            else\n            {\n               vals.top() = !vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case OR:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a || vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case PLUS:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = a + vals.top();\n               pop_node();\n            }\n\n            continue;\n\n         case POWER:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = std::pow( a, vals.top() );\n               pop_node();\n            }\n\n            continue;\n\n         case PULSE:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double start = vals.top();\n               vals.pop();\n               double width = std::max( time_step, vals.top() );\n               vals.top() = ( time_plus > start ) && ( time_plus < start + width ) ? 1 : 0;\n               pop_node();\n            }\n\n            continue;\n\n         case PULSE_TRAIN:\n            if( int(vals.size()) - valsoffset.top() < 4 )\n            {\n               nodes.push( node );\n               valsoffset.push(vals.size() + 3);\n               nodes.push( node->child1->child1 );\n               valsoffset.push(vals.size() + 2);\n               nodes.push( node->child1->child2 );\n               valsoffset.push(vals.size() + 1);\n               nodes.push( node->child2 );\n               valsoffset.push(vals.size());\n               node = node->child3;\n            }\n            else\n            {\n               pop_node();\n               double start = vals.top();\n               vals.pop();\n               double width = std::max( time_step, vals.top() );\n               vals.pop();\n               double tbetween = vals.top();\n               vals.pop();\n               double end = vals.top();\n\n               if( time_plus < start || end < time_plus )\n               {\n                  vals.top() = 0;\n                  continue;\n               }\n\n               if( tbetween < width )\n               {\n                  vals.top() = 1;\n                  continue;\n               }\n\n               double tmodplus = std::fmod( time_plus, tbetween );\n               double smod = std::fmod( start, tbetween );\n\n               vals.top() = ( tmodplus > smod ) && ( tmodplus < smod + width ) ? 1 : 0;\n            }\n\n            continue;\n\n         case ExpressionGraph::STEP:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double height = vals.top();\n               vals.pop();\n               vals.top() = time_plus > vals.top() ? height : 0;\n               pop_node();\n            }\n\n            continue;\n\n         case ExpressionGraph::RAMP:\n            if( int(vals.size()) - valsoffset.top() < 3 )\n            {\n               push_ternary();\n            }\n            else\n            {\n               double slope = vals.top();\n               vals.pop();\n               double start_time = vals.top();\n               vals.pop();\n               vals.top() = time > start_time ?\n                            ( time < vals.top() ?\n                              slope * ( time - start_time ) :\n                              slope * ( vals.top() - start_time ) )\n                            : 0;\n               pop_node();\n            }\n\n            continue;\n\n         case ExpressionGraph::RANDOM_UNIFORM:\n            if( int(vals.size()) - valsoffset.top() < 2 )\n            {\n               push_binary();\n            }\n            else\n            {\n               double a = vals.top();\n               vals.pop();\n               vals.top() = sdo::random_uniform( a, vals.top() );\n               pop_node();\n            }\n\n            continue;\n         }\n      }\n   }\n   while( node );\n   assert(nodes.empty());\n   assert(vals.size() == 1 && valsoffset.empty());\n   return vals.top();\n}\n\n}\n", "meta": {"hexsha": "3dd8246bc627fb62144d87f90dd59a52f69abb6f", "size": 65446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdo/ExpressionGraph.cpp", "max_stars_repo_name": "rgottwald/libsdo", "max_stars_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdo/ExpressionGraph.cpp", "max_issues_repo_name": "rgottwald/libsdo", "max_issues_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdo/ExpressionGraph.cpp", "max_forks_repo_name": "rgottwald/libsdo", "max_forks_repo_head_hexsha": "6937784258672e3a2d4252107242796b95f026aa", "max_forks_repo_licenses": ["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.2103235747, "max_line_length": 139, "alphanum_fraction": 0.4555969807, "num_tokens": 15114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.031143833682160855, "lm_q1q2_score": 0.014599937307403704}}
{"text": "#include <stdexcept>\n#include <sstream>\n#include <limits>\n#include <iostream>\n#include <cmath>\n#include <stdlib.h>\n#include <boost/lexical_cast.hpp>\n#include <sstream>\n\n#include \"shortest_paths.h\"\n#include \"fheap.h\"\n\nusing namespace std;\n\nshortest_paths::shortest_paths() :\n    sssp(sssp_automatic),\n    apsp(apsp_automatic),\n    integrity_check(true),\n    negative_edge_exists(false),\n    pairwise_computation_done(false),\n    pairwise_tracking_done(false),\n    verbose(true),\n    directed(true){\n\n}\n\nvoid shortest_paths::add_node(unsigned int index){\n\n    node to_add = { index };\n    if(integrity_check){\n        if(node_index_map.find(index) != node_index_map.end()){\n            stringstream error;\n            error << \"node index \" << index\n                << \" occured at least twice\";\n            throw invalid_argument(error.str());\n        }\n    }\n    node_index_map[index] = nodes.size();\n    nodes.push_back(to_add);\n    sparse_adjacency_matrix.push_back(map<unsigned int, unsigned int>());\n    sparse_transposed_adjacency_matrix.push_back(map<unsigned int, unsigned int>());\n    pairwise_computation_done = false;\n    pairwise_tracking_done = false;\n\n}\n\nvoid shortest_paths::add_edge(\n        unsigned int index,\n        unsigned int source,\n        unsigned int target,\n        double weight){\n\n    edge to_add = { index, source, target, weight };\n\n    if(integrity_check){\n        if(edge_index_map.find(index) != edge_index_map.end()){\n            stringstream error;\n            error << \"edge index \" << index\n                << \" occured at least twice\";\n            throw invalid_argument(error.str());\n        }\n        if(node_index_map.find(source) == node_index_map.end()){\n            stringstream error;\n            error << \"source node \" << source << \" does not exist\";\n            throw invalid_argument(error.str());\n        }\n        if(node_index_map.find(target) == node_index_map.end()){\n            stringstream error;\n            error << \"target node \" << target << \" does not exist\";\n            throw invalid_argument(error.str());\n        }\n    }\n\n    unsigned int mapped_source = node_index_map[source];\n    unsigned int mapped_target = node_index_map[target];\n    unsigned int mapped_index = edges.size();\n\n    map<unsigned int, unsigned int>::iterator old_edge =\n        sparse_adjacency_matrix[mapped_source].find(mapped_target);\n\n    // It may be that we have multi edges. In that case, we use the\n    // edge with the lowest weight.\n    if(old_edge == sparse_adjacency_matrix[mapped_source].end() ||\n            edges[old_edge->second].weight > weight){\n\n        sparse_adjacency_matrix[mapped_source][mapped_target] = mapped_index;\n        sparse_transposed_adjacency_matrix[mapped_target][mapped_source] = mapped_index;\n\n        if(weight < 0){\n            negative_edge_exists = true;\n        }\n\n        pairwise_computation_done = false;\n        pairwise_tracking_done = false;\n\n    }\n\n    edge_index_map[index] = mapped_index;\n    edges.push_back(to_add);\n\n}\n\n\nvoid shortest_paths::set_integrity_check(bool integrity_check){\n\n    this->integrity_check = integrity_check;\n\n}\n\nvoid shortest_paths::graph_from_file(\n        const char* filename_nodes,\n        const char* filename_edges){\n\n    ifstream nodes_stream(filename_nodes, ios::in),\n         edges_stream(filename_edges, ios::in);\n\n    unsigned int node_index,\n\n        edge_index,\n        source,\n        target,\n\n        line_in_file;\n\n    float weight;\n\n    string line_buffer;\n\n    // let's do the nodes\n    if(nodes_stream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename_nodes << \"\\\" for reading\";\n        throw invalid_argument(error.str());\n    }\n\n    try{\n        for(line_in_file=1; getline(nodes_stream, line_buffer);\n                line_in_file++){\n\n            // A single whitespace in the template allows any number\n            // of whitespaces in the scanned file, including none,\n            // so don't remove them!\n            if(sscanf(line_buffer.c_str(), \" %u \", &node_index) < 1){\n                stringstream error;\n                error << \"malformed input: missing node index\";\n                throw invalid_argument(error.str());\n            }\n\n            add_node(node_index);\n        }\n\n    }\n\n    catch(exception e){\n\n        stringstream error;\n        error << \"line: \" << line_in_file << \", file: \\\"\"\n            << filename_nodes << \"\\\", \" << e.what();\n        throw invalid_argument(error.str());\n\n    }\n\n    nodes_stream.close();\n\n    if(nodes.size()==0){\n        stringstream error;\n        error << \"file \\\"\" << filename_nodes\n            << \"\\\" did not contain any nodes\";\n        throw invalid_argument(error.str());\n    }\n\n    // let's do the edges\n    if(edges_stream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename_edges << \"\\\" for reading\";\n        throw invalid_argument(error.str());\n    }\n\n    try{\n        for(line_in_file=1; getline(edges_stream, line_buffer);\n                line_in_file++){\n\n            // A single whitespace in the template allows any number\n            // of whitespaces in the scanned file, including none,\n            // so don't remove them!\n            if(sscanf(line_buffer.c_str(), \" %u ; %u ; %u ; %f\",\n                        &edge_index, &source, &target, &weight) < 4){\n                stringstream error;\n                error << \"malformed input: must be like \"\n                    << \"\\\"index; source; target; weight\\\"\";\n                throw invalid_argument(error.str());\n            }\n\n            add_edge(edge_index, source, target, (double)weight);\n        }\n\n    }\n\n    catch(exception e){\n\n        stringstream error;\n        error << \"line: \" << line_in_file << \", file: \\\"\"\n            << filename_edges << \"\\\", \" << e.what();\n        throw invalid_argument(error.str());\n\n    }\n\n    edges_stream.close();\n\n}\n\nvoid shortest_paths::graph_to_file(\n        const char* filename_nodes,\n        const char* filename_edges){\n\n    ofstream nodes_stream(filename_nodes, ios::out),\n         edges_stream(filename_edges, ios::out);\n\n    if(nodes_stream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename_nodes << \"\\\" for writing\";\n        throw invalid_argument(error.str());\n    }\n\n    nodes_stream << \"# node_index\" << endl;\n\n    for(vector<node>::iterator itr = nodes.begin();\n            itr != nodes.end(); itr++){\n\n        nodes_stream << itr->index << endl;\n\n    }\n\n    nodes_stream.close();\n\n    if(edges_stream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename_edges << \"\\\" for writing\";\n        throw invalid_argument(error.str());\n    }\n\n    edges_stream << \"# edge_index; from_node; to_node; weight\" << endl;\n\n    for(vector<edge>::iterator itr = edges.begin();\n            itr != edges.end(); itr++){\n\n        edges_stream << itr->index << \"; \" << itr->source << \"; \"\n            << itr->target << \"; \" << itr->weight << endl;\n\n    }\n\n    edges_stream.close();\n}\n\nvoid shortest_paths::compute_path(\n        unsigned int path_source,\n        unsigned int path_target){\n\n    path_struct tmp = {numeric_limits<double>::infinity(), numeric_limits<unsigned int>::max()};\n\n    d.resize(nodes.size(), vector<path_struct>(nodes.size(), tmp));\n\n    unsigned int mapped_source = node_index_map[path_source];\n\n    if(sssp == sssp_automatic){\n\n        // TODO make differentiation here\n        sssp = dijkstra;\n\n    }\n\n    // This part is taken from Wikipedia, Dijkstra's Algorithm.\n    if(sssp == dijkstra){\n\n        if(integrity_check && negative_edge_exists){\n            stringstream error;\n            error << \"dijkstra method cannot deal with \"\n                << \"negative edges that exist in the graph.\";\n            throw invalid_argument(error.str());\n        }\n\n        d[mapped_source][mapped_source].distance = 0;\n\n        FHeap heap(nodes.size());\n\n        for(unsigned int i=0; i < nodes.size(); i++){\n\n            heap.insert(i, d[mapped_source][i].distance);\n\n        }\n\n        double minimum = 0;\n        unsigned int index = 0;\n\n        for(unsigned int i = 0; i < nodes.size()\n                && minimum != numeric_limits<double>::infinity(); i++){\n\n            // Will overwrite minimum and index\n            index = heap.deleteMin();\n            // if (index == node_index_map[path_target]){\n            //     if (d[mapped_source][index].distance < 0){\n            //         cout << d[mapped_source][index].distance << endl;\n            //       }\n            //     break;\n            // }\n            minimum = d[mapped_source][index].distance;\n\n            for(map<unsigned int, unsigned int>::iterator itr\n                    = sparse_adjacency_matrix[index].begin();\n                    itr != sparse_adjacency_matrix[index].end();\n                    itr++){\n\n                double alt = d[mapped_source][index].distance\n                    + edges[itr->second].weight;\n\n                if(alt < d[mapped_source][itr->first].distance){\n\n                    d[mapped_source][itr->first].distance = alt;\n                    d[mapped_source][itr->first].predecessor = index;\n                    heap.decreaseKey(itr->first, alt);\n\n                }\n\n            }\n\n            if(!directed){\n\n                for(map<unsigned int, unsigned int>::iterator itr\n                        = sparse_transposed_adjacency_matrix[index].begin();\n                        itr != sparse_transposed_adjacency_matrix[index].end();\n                        itr++){\n\n                    double alt = d[mapped_source][index].distance\n                        + edges[itr->second].weight;\n\n                    if(alt < d[mapped_source][itr->first].distance){\n\n                        d[mapped_source][itr->first].distance = alt;\n                        d[mapped_source][itr->first].predecessor = index;\n                        heap.decreaseKey(itr->first, alt);\n                    }\n\n                }\n\n            }\n\n        }\n\n    }\n\n    if(sssp == bellman_ford){\n\n        stringstream error;\n        error << \"bellman_ford not implemented yet\";\n        throw invalid_argument(error.str());\n\n        // TO BE CONTINUED\n\n        for(map<unsigned int, unsigned int>::iterator itr =\n                sparse_adjacency_matrix[path_source].begin();\n                itr != sparse_adjacency_matrix[path_source].end();\n                itr++){\n\n            d[mapped_source][itr->first].distance = edges[itr->second].weight;\n            d[mapped_source][itr->first].predecessor = path_source;\n\n        }\n\n    }\n\n}\n\nvoid shortest_paths::track_path(\n        unsigned int path_source,\n        unsigned int path_target){\n\n    unsigned int mapped_source = node_index_map[path_source];\n    unsigned int mapped_target = node_index_map[path_target];\n\n    double length = 0.0;\n\n    node_paths.resize(nodes.size(), vector<list<unsigned int> >());\n    node_paths[mapped_source].resize(nodes.size(), list<unsigned int>());\n\n    edge_paths.resize(nodes.size(), vector<list<unsigned int> >());\n    edge_paths[mapped_source].resize(nodes.size(), list<unsigned int>());\n\n    if(!directed){\n        node_paths[mapped_target].resize(nodes.size(), list<unsigned int>());\n        edge_paths[mapped_target].resize(nodes.size(), list<unsigned int>());\n    }\n\n    unsigned int predecessor = mapped_target;\n    unsigned int old_predecessor = d[mapped_source][predecessor].predecessor;\n\n    bool path_exists = false;\n\n    while(old_predecessor != numeric_limits<unsigned int>::max()){\n\n        path_exists = true;\n\n        node_paths[mapped_source][mapped_target].push_front(predecessor);\n\n        map<unsigned int, unsigned int>::iterator itr =\n            sparse_adjacency_matrix[old_predecessor].find(predecessor);\n\n        if(!directed && itr == sparse_adjacency_matrix[old_predecessor].end()){\n            itr = sparse_adjacency_matrix[predecessor].find(old_predecessor);\n        }\n\n        edge_paths[mapped_source][mapped_target].push_front(itr->second);\n        length += edges[itr->second].weight;\n\n        predecessor = old_predecessor;\n        old_predecessor = d[mapped_source][predecessor].predecessor;\n\n    }\n\n    if(path_exists){\n\n        node_paths[mapped_source][mapped_target].push_front(predecessor);\n\n    }\n\n    // TODO introduce proper epsilon\n    if(d[mapped_source][mapped_target].distance != numeric_limits<double>::infinity() &&\n            std::abs(length - d[mapped_source][mapped_target].distance) > 0.01){\n        stringstream error;\n        error << \"something is wrong: shortest distance \" <<\n               d[mapped_source][mapped_target].distance\n               << \" not matched by path length \" << length;\n        throw invalid_argument(error.str());\n    }\n\n}\n\nvoid shortest_paths::compute_all_paths(){\n\n\tpaths.resize(nodes.size(), vector<vector<list<unsigned int> > >());\n\tfor(int ii = 0; ii<nodes.size(); ii++){\n\n\t\tpaths[ii].resize(nodes.size(), vector<list<unsigned int> >());\n\n\t\tpaths[ii] = get_all_paths_from(ii);\n\n\t}\n}\n\nvector<vector<list<unsigned int> > > shortest_paths::get_all_paths_from(\n        unsigned int path_source){\n\n\tunsigned int mapped_source = node_index_map[path_source];\n\n        vector<double> min;\n\tmin.reserve(nodes.size());\n\tvector<vector<list<unsigned int> > > path;\n\tpath.resize(nodes.size(), vector<list<unsigned int> >());\n\tvector<bool> visited;\n\tvisited.reserve(nodes.size());\n\n\tfor(unsigned int ii = 0; ii<nodes.size();ii++){\n\t\tvisited[ii] = false;\n\t\tmin[ii] = numeric_limits<double>::infinity();\n\t}\n\n\tmin[mapped_source] = 0;\n\tunsigned int current = mapped_source;\n\n\twhile(true){\n\t\tvisited[current] = true;\n\t\tfor(std::map<unsigned int, unsigned int>::iterator itr = sparse_adjacency_matrix[current].begin(); itr != sparse_adjacency_matrix[current].end(); itr++){\n\t\t\tif(edges[itr->second].weight > 0 && !visited[itr->first]){\n\t\t\t\tif(edges[itr->second].weight + min[current] < min[itr->first]){\n\t\t\t\t\tmin[itr->first] = edges[itr->second].weight + min[current];\n\t\t\t\t\tpath[itr->first].clear();\n\t\t\t\t}\n\t\t\t\tif(edges[itr->second].weight + min[current] == min[itr->first]){\n\t\t\t\t\tif(path[current].size() == 0){\n\t\t\t\t\t\tpath[itr->first].resize(1,list<unsigned int>());\n\t\t\t\t\t\tpath[itr->first].back().push_back(edges[itr->second].index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpath[itr->first].resize(path[current].size(),list<unsigned int>());\n\t\t\t\t\t\tfor(unsigned int ii = 0;ii< path[current].size(); ii++){\n\t\t\t\t\t\t\tpath[itr->first].push_back(path[current][ii]);\n\t\t\t\t\t\t\tpath[itr->first].back().push_back(edges[itr->second].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\t\tfor(map<unsigned int, unsigned int>::iterator itr = sparse_transposed_adjacency_matrix[current].begin(); itr != sparse_transposed_adjacency_matrix[current].end() && !directed; itr++){\n\t\t\tif(edges[itr->second].weight > 0 && !visited[itr->first]){\n\t\t\t\tif(edges[itr->second].weight + min[current] < min[itr->first]){\n\t\t\t\t\tmin[itr->first] = edges[itr->second].weight + min[current];\n\t\t\t\t\tpath[itr->first].clear();\n\t\t\t\t}\n\t\t\t\tif(edges[itr->second].weight + min[current] == min[itr->first]){\n\t\t\t\t\tif(path[current].size() == 0){\n\t\t\t\t\t\tpath[itr->first].resize(1,list<unsigned int>());\n\t\t\t\t\t\tpath[itr->first].back().push_back(edges[itr->second].index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpath[itr->first].resize(path[current].size(),list<unsigned int>());\n\t\t\t\t\t\tfor(unsigned int ii = 0;ii< path[current].size(); ii++){\n\t\t\t\t\t\t\tpath[itr->first].push_back(path[current][ii]);\n\t\t\t\t\t\t\tpath[itr->first].back().push_back(edges[itr->second].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\tdouble least = numeric_limits<double>::infinity();\n\t\tint k = -1;\n\t\tfor(unsigned int nodes_count= 0; nodes_count<nodes.size(); nodes_count++){\n\t\t\tif(!visited[nodes_count] && min[nodes_count]<least){\n\t\t\t\tk = nodes_count;\n\t\t\t\tleast = min[nodes_count];\n\t\t\t}\n\t\t}\n\t\tif(k==-1)break;\n\t\tcurrent = k;\n\t}\n\treturn path;\n}\n\nvector<vector<unsigned int> > shortest_paths::get_all_paths_from_to(\n\tunsigned int path_source,\n\tunsigned int path_target){\n\n\tvector<vector<unsigned int> > all_paths_remapped;\n\n\tall_paths_remapped.reserve(paths[node_index_map[path_source]][node_index_map[path_target]].size());\n\tfor(unsigned int ii = 0; ii<paths[node_index_map[path_source]][node_index_map[path_target]].size();ii++){\n\t\tall_paths_remapped.push_back(edge_indices(paths[path_source][path_target][ii]));\n\t}\n\treturn all_paths_remapped;\n}\n\n\nvector<unsigned int> shortest_paths::edge_indices(const list<unsigned int>& mapped_indices){\n\n    vector<unsigned int> retval;\n    retval.reserve(mapped_indices.size());\n\n    for(list<unsigned int>::const_iterator itr = mapped_indices.begin();\n            itr != mapped_indices.end(); itr++){\n\n        retval.push_back(edges[*itr].index);\n\n    }\n\n    return retval;\n\n}\n\nvector<unsigned int> shortest_paths::node_indices(const list<unsigned int>& mapped_indices){\n\n    vector<unsigned int> retval;\n    retval.reserve(mapped_indices.size());\n\n    for(list<unsigned int>::const_iterator itr = mapped_indices.begin();\n            itr != mapped_indices.end(); itr++){\n\n        retval.push_back(nodes[*itr].index);\n\n    }\n\n    return retval;\n\n}\n\nvoid shortest_paths::compute_pairwise(int start, int end){ // default values of 0 and -1\n    if (end == -1) end = nodes.size();\n    if(pairwise_computation_done || nodes.size() == 0){\n        return;\n    }\n\n    if(apsp == floyd_warshall){\n\n        path_struct tmp = {numeric_limits<double>::infinity(),\n            numeric_limits<unsigned int>::max()};\n\n        d.resize(nodes.size(), vector<path_struct>(nodes.size(), tmp));\n\n        for(unsigned int i=0; i<sparse_adjacency_matrix.size(); i++){\n\n            for(map<unsigned int, unsigned int>::iterator itr2 =\n                    sparse_adjacency_matrix[i].begin();\n                    itr2 != sparse_adjacency_matrix[i].end();\n                    itr2++){\n\n                d[i][itr2->first].distance = edges[itr2->second].weight;\n                d[i][itr2->first].predecessor = i;\n\n                if(!directed){\n                    d[itr2->first][i].distance = edges[itr2->second].weight;\n                    d[itr2->first][i].predecessor = i;\n                }\n\n            }\n\n            d[i][i].distance = 0;\n\n        }\n\n        for(unsigned int k=0; k<nodes.size(); k++){\n\n            if(verbose){\n                if(k % 50 == 0){\n                    cerr << \"node \" << k << \" of \" << nodes.size() << endl;\n                }\n            }\n\n            for(unsigned int i=0; i<nodes.size(); i++){\n\n                for(unsigned int j=0; j<nodes.size(); j++){\n\n                    double alt = d[i][k].distance + d[k][j].distance;\n\n                    if(alt < d[i][j].distance){\n\n                        d[i][j].distance = alt;\n                        d[i][j].predecessor = d[k][j].predecessor;\n\n                    }\n\n                }\n\n            }\n\n        }\n        for(unsigned int i=0; i<nodes.size(); i++){\n\n            if(d[i][i].distance < 0){\n\n                stringstream error;\n                error << \"graph has negative cycles\" << endl;\n                throw invalid_argument(error.str());\n\n            }\n\n        }\n\n    }\n\n    else {\n\n        for(unsigned int i=start; i < end; i++){\n\n            if(verbose){\n                if(i % 50 == 0){\n                    cerr << \"node \" << i - start << \" of \" << end - start  << endl;\n                }\n            }\n            compute_path(i,i);\n\n        }\n\n    }\n\n    pairwise_computation_done = true;\n\n}\n\nvoid shortest_paths::track_pairwise(){\n\n    if(pairwise_tracking_done){\n        return;\n    }\n\n    if(!pairwise_computation_done){\n\n        compute_pairwise();\n\n    }\n\n    for(unsigned int i=0; i<nodes.size(); i++){\n\n        unsigned int startpoint;\n\n        if(directed){\n            startpoint = 0;\n        }\n        else{\n            startpoint = i+1;\n        }\n\n        for(unsigned int j=startpoint; j<nodes.size(); j++){\n\n            track_path(nodes[i].index, nodes[j].index);\n            if(!directed){\n                node_paths[j][i] = node_paths[i][j];\n                edge_paths[j][i] = edge_paths[i][j];\n            }\n\n        }\n\n    }\n\n    pairwise_tracking_done = true;\n\n}\n\nvoid shortest_paths::distance_to_file(\n        const char* filename,\n        unsigned int path_source,\n        unsigned int path_target){\n\n    if(integrity_check){\n        if(node_index_map.find(path_source) == node_index_map.end()){\n            stringstream error;\n            error << \"source node \" << path_source << \" does not exist\";\n            throw invalid_argument(error.str());\n        }\n        if(node_index_map.find(path_target) == node_index_map.end()){\n            stringstream error;\n            error << \"target node \" << path_target << \" does not exist\";\n            throw invalid_argument(error.str());\n        }\n    }\n\n    compute_path(path_source, path_target);\n\n    ofstream filestream(filename, ios::out);\n\n    if(filestream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename << \"\\\" for writing\";\n        throw invalid_argument(error.str());\n    }\n\n    filestream << \"# Automatically created by a shortest_paths object.\"\n        << \"# path_source; path_target; distance\" << endl\n        << path_source << \"; \" << path_target << \"; \" <<\n        d[node_index_map[path_source]][node_index_map[path_target]].distance\n        << endl;\n\n    filestream.close();\n}\n\nvoid shortest_paths::pairwise_distances_to_file(const char* filename) {\n\n    compute_pairwise();\n\n    ofstream filestream(filename, ios::out);\n\n    if(filestream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename << \"\\\" for writing\";\n        throw invalid_argument(error.str());\n    }\n\n    filestream << \"# Automatically created by a shortest_paths object.\"\n        << \"# path_source; path_target; distance\" << endl;\n\n    for(unsigned int i=0; i < nodes.size(); i++){\n\n        unsigned int startpoint;\n\n        if(directed){\n            startpoint = 0;\n        }\n        else{\n            startpoint = i+1;\n        }\n\n        for(unsigned int j=startpoint; j < nodes.size(); j++){\n\n            filestream << nodes[i].index << \"; \"\n                << nodes[j].index << \"; \" << d[i][j].distance << endl;\n\n        }\n\n    }\n\n    filestream.close();\n}\n\nvoid shortest_paths::path_to_file(\n        const char* filename,\n        unsigned int path_source,\n        unsigned int path_target) {\n\n    if(integrity_check){\n        if(node_index_map.find(path_source) == node_index_map.end()){\n            stringstream error;\n            error << \"source node \" << path_source << \" does not exist\";\n            throw invalid_argument(error.str());\n        }\n        if(node_index_map.find(path_target) == node_index_map.end()){\n            stringstream error;\n            error << \"target node \" << path_target << \" does not exist\";\n            throw invalid_argument(error.str());\n        }\n    }\n\n    track_path(path_source, path_target);\n\n    ofstream filestream(filename, ios::out);\n\n    if(filestream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename << \"\\\" for writing\";\n        throw invalid_argument(error.str());\n    }\n\n    filestream << \"# Automatically created by a shortest_paths object.\" << endl;\n\n    if(directed){\n        filestream << \"# edge_source; edge_target; edge_index\" << endl;\n    }\n    else{\n        filestream << \"# edge_left_node; edge_right_node; edge_index\" << endl;\n    }\n\n\n    list<unsigned int> edge_list = edge_paths[\n        node_index_map[path_source]][node_index_map[path_target]];\n\n    for(list<unsigned int>::iterator itr = edge_list.begin();\n            itr != edge_list.end(); itr++){\n\n        filestream << edges[*itr].source << \"; \" << edges[*itr].target << \"; \"\n            << edges[*itr].index << endl;\n\n    }\n\n    filestream.close();\n\n}\n\nvoid shortest_paths::pairwise_paths_to_file(const char* filename) {\n\n    track_pairwise();\n\n    ofstream filestream(filename, ios::out);\n\n    if(filestream.fail()){\n        stringstream error;\n        error << \"unable to open file \\\"\"\n            << filename << \"\\\" for writing\";\n        throw invalid_argument(error.str());\n    }\n\n    filestream << \"# Automatically created by a shortest_paths object.\" << endl;\n\n    if(directed){\n        filestream << \"# path_source; path_target; edge_source; edge_target; edge_index\" << endl;\n    }\n    else{\n        filestream << \"# path_source; path_target; edge_left_node; edge_right_node; edge_index\" << endl;\n    }\n\n    for(unsigned int i=0; i < nodes.size(); i++){\n\n        unsigned int startpoint;\n\n        if(directed){\n            startpoint = 0;\n        }\n        else{\n            startpoint = i+1;\n        }\n\n        for(unsigned int j=startpoint; j < nodes.size(); j++){\n\n            for(list<unsigned int>::iterator\n                    itr = edge_paths[i][j].begin();\n                    itr != edge_paths[i][j].end(); itr++){\n\n                filestream << nodes[i].index << \"; \"\n                    << nodes[j].index << \"; \" << edges[*itr].source << \"; \"\n                    << edges[*itr].target << \"; \" << edges[*itr].index << endl;\n\n            }\n\n        }\n\n    }\n\n    filestream.close();\n\n}\n\ndouble shortest_paths::get_distance(\n        unsigned int path_source,\n        unsigned int path_target) {\n\n    if(!pairwise_computation_done){\n        compute_path(path_source, path_target);\n    }\n\n    return d[node_index_map[path_source]]\n        [node_index_map[path_target]].distance;\n\n}\n\nvector<unsigned int> shortest_paths::get_path_nodes(\n        unsigned int path_source,\n        unsigned int path_target){\n\n    track_path(path_source, path_target);\n\n    return node_indices(node_paths[node_index_map[path_source]][node_index_map[path_target]]);\n\n}\n\nvector<unsigned int> shortest_paths::get_path_edges(\n        unsigned int path_source,\n        unsigned int path_target){\n\n    track_path(path_source, path_target);\n\n    return edge_indices(edge_paths[node_index_map[path_source]][node_index_map[path_target]]);\n\n}\n\nvoid shortest_paths::set_sssp_method_dijkstra(){\n\n    sssp = dijkstra;\n\n}\n\nvoid shortest_paths::set_sssp_method_bellman_ford(){\n\n    sssp = bellman_ford;\n\n}\n\nvoid shortest_paths::set_sssp_method_automatic(){\n\n    sssp = sssp_automatic;\n\n}\n\nvoid shortest_paths::set_apsp_method_floyd_warshall(){\n\n    apsp = floyd_warshall;\n\n}\n\nvoid shortest_paths::set_apsp_method_johnson(){\n\n    apsp = johnson;\n\n}\n\nvoid shortest_paths::set_verbose(bool verbose){\n\n    this->verbose = verbose;\n\n}\n\nvoid shortest_paths::set_directed(bool directed){\n\n    this->directed = directed;\n\n}\n\nvoid shortest_paths::set_apsp_method_automatic(){\n\n    apsp = apsp_automatic;\n\n}\n", "meta": {"hexsha": "90028c55cec58be6366a5a4ee816c33b2723146a", "size": 26625, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/essentials/shortest-paths/shortest_paths.cc", "max_stars_repo_name": "railtoolkit/OpenLinTim", "max_stars_repo_head_hexsha": "27eba8b6038946ce162e9f7bbc0bd23045029d51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/essentials/shortest-paths/shortest_paths.cc", "max_issues_repo_name": "railtoolkit/OpenLinTim", "max_issues_repo_head_hexsha": "27eba8b6038946ce162e9f7bbc0bd23045029d51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/essentials/shortest-paths/shortest_paths.cc", "max_forks_repo_name": "railtoolkit/OpenLinTim", "max_forks_repo_head_hexsha": "27eba8b6038946ce162e9f7bbc0bd23045029d51", "max_forks_repo_licenses": ["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.3919753086, "max_line_length": 185, "alphanum_fraction": 0.5839248826, "num_tokens": 5806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.03114383210846962, "lm_q1q2_score": 0.014599936569672003}}
{"text": "// Copyright 2019 Intel Corporation.\n\n#include \"tile/lang/ast/jacobian.h\"\n\n#include <map>\n#include <memory>\n#include <stack>\n#include <unordered_set>\n\n#include <boost/format.hpp>\n\n#include \"tile/lang/ast/gradient.h\"\n#include \"tile/lang/ast/traversal.h\"\n\nnamespace vertexai {\nnamespace tile {\nnamespace lang {\nnamespace ast {\n\nnamespace {\n\nstruct UseInfo {\n  ExprPtr expr;\n  size_t idx;\n};\n\nclass ComputeUses : public AstVisitor<void> {\n public:\n  explicit ComputeUses(const ExprPtr& src) {\n    stack_.push(src);\n    while (stack_.size()) {\n      auto expr = stack_.top();\n      stack_.pop();\n      if (!seen_.count(expr.get())) {\n        seen_.insert(expr.get());\n        expr->Accept(this);\n      }\n    }\n  }\n\n  const std::vector<UseInfo>& uses(const Expr* expr) const { return uses_.at(expr); }\n\n private:\n  void Visit(const CallExpr& expr) final {\n    for (size_t i = 0; i < expr.args.size(); i++) {\n      Push(expr, expr.args[i], i);\n    }\n  }\n\n  void Visit(const ContractionExpr& expr) final {\n    for (size_t i = 0; i < expr.srcs.size(); i++) {\n      Push(expr, expr.srcs[i]->ref, i);\n    }\n    if (expr.use_default) {\n      Push(expr, expr.use_default, expr.srcs.size());\n    }\n  }\n\n  void Visit(const GradOverrideExpr& expr) final {\n    for (size_t i = 0; i < expr.ins.size(); i++) {\n      Push(expr, expr.ins[i], i);\n    }\n  }\n\n  void Visit(const DimExprExpr& expr) final {}\n  void Visit(const FloatConst& expr) final {}\n  void Visit(const IntConst& expr) final {}\n  void Visit(const ParamExpr& expr) final {}\n\n private:\n  void Push(const Expr& user, const ExprPtr& used, size_t idx) {\n    IVLOG(2, \"ComputeUses::Push> user: \" << &user << \", used: \" << used << \", idx: \" << idx);\n    auto ptr = std::const_pointer_cast<Expr>(user.as_ptr());\n    uses_[used.get()].emplace_back(UseInfo{ptr, idx});\n    stack_.push(used);\n  }\n\n private:\n  std::stack<ExprPtr> stack_;\n  std::unordered_set<const Expr*> seen_;\n  std::unordered_map<const Expr*, std::vector<UseInfo>> uses_;\n};\n\nclass Jacobian {\n public:\n  explicit Jacobian(const ExprPtr& err) : uses_(err) {\n    IVLOG(2, \"Jacobian::Jacobian> err: \" << err);\n\n    // Create identity matrix to represent d(err)/d(err)\n    auto dims = err->shape.dims_as_exprs();\n    orank_ = dims.size();\n\n    auto Ji = std::make_shared<ContractionExpr>();\n    Ji->agg_op = AggregationOp::ASSIGN;\n    Ji->combo_op = CombinationOp::NONE;\n\n    auto src = std::make_shared<FloatConst>(1.0);\n    Ji->srcs.push_back(std::make_shared<IndexMapExpr>(src, std::vector<PolyExprPtr>{}));\n\n    std::vector<PolyExprPtr> Jidxs;\n    std::vector<DimExprPtr> Jdims;\n\n    for (size_t io = 0; io < 2; io++) {\n      for (size_t i = 0; i < orank_; i++) {\n        Jidxs.push_back(std::make_shared<PolyIndex>(i));\n        Jdims.push_back(dims[i]);\n      }\n    }\n\n    Ji->sink_idxs = std::make_shared<IndexMapExpr>(nullptr, Jidxs);\n    Ji->sink_dims = std::make_shared<SizeMapExpr>(Jdims);\n    Ji->ComputeShape(\"\");\n\n    seen_[err.get()] = Ji;\n  }\n\n  ExprPtr GetDerivative(const ExprPtr& expr) {\n    IVLOG(2, \"Jacobian::GetDerivative> \" << expr);\n    auto it = seen_.find(expr.get());\n    if (it != seen_.end()) {\n      IVLOG(2, \"  returning: \" << it->second);\n      return it->second;\n    }\n    ExprPtr total;\n    for (const auto& use : uses_.uses(expr.get())) {\n      ExprPtr dop;\n      auto dout = GetDerivative(use.expr);\n      if (auto grad_override_expr = std::dynamic_pointer_cast<GradOverrideExpr>(use.expr)) {\n        // A gradient override replaces all the derivatives, so set total and exit the loop\n        total = DeriveOverride(dout, grad_override_expr, use.idx);\n        break;\n      }\n      if (auto call_expr = std::dynamic_pointer_cast<CallExpr>(use.expr)) {\n        dop = DeriveCall(dout, call_expr, use.idx);\n      } else if (auto cion_expr = std::dynamic_pointer_cast<ContractionExpr>(use.expr)) {\n        dop = DeriveContraction(dout, cion_expr, use.idx);\n      } else {\n        throw std::runtime_error(\"Invalid operation type in Gradient::GetDerivative\");\n      }\n      if (!total) {\n        total = dop;\n      } else {\n        total = MakeCall(\"add\", {total, dop});\n      }\n    }\n    if (!total) {\n      total = std::make_shared<FloatConst>(0.0);\n    }\n    IVLOG(2, \"  Gradient::GetDerivative, final result -> \" << total);\n    seen_.emplace(expr.get(), total);\n    return total;\n  }\n\n private:\n  ExprPtr DeriveContraction(const ExprPtr& dout, const std::shared_ptr<ContractionExpr>& expr, size_t idx) {\n    if (expr->use_default && idx == expr->srcs.size()) {\n      return dout;\n    }\n    if (expr->combo_op == CombinationOp::EQ) {\n      return std::make_shared<IntConst>(0);\n    }\n    if (expr->agg_op == AggregationOp::SUM || expr->agg_op == AggregationOp::ASSIGN) {\n      return DeriveSum(dout, expr, idx);\n    }\n    if (expr->agg_op == AggregationOp::MIN || expr->agg_op == AggregationOp::MAX) {\n      return DeriveExtreme(dout, expr, idx);\n    }\n    if (expr->agg_op == AggregationOp::PROD) {\n      throw std::runtime_error(\"PROD AggregationOp not implemented for Jacobian\");\n    }\n    throw std::runtime_error(\"Invalid ContractionExpr in DeriveContraction\");\n  }\n\n  // Each of these must compute single-layer Jacobian of op, then combine it with prior Jacobian dout to\n  // produce new total Jacobian\n\n  ExprPtr DeriveCall(const ExprPtr& dout, const std::shared_ptr<CallExpr>& op, size_t idx) {\n    if (op->fn == \"reshape\") {\n      throw std::runtime_error(\"Jacobian not implemented for reshape\");\n    }\n    auto deriv = DerivRegistry::Instance()->Resolve(op->fn);  // Returns elementwise derivative data\n    // Autobroadcasting handles J i/o dims correctly\n    return deriv.fn(op, dout, op->args, deriv.user_fn, deriv.user_ctx)[idx];\n  }\n\n  ExprPtr DeriveSum(const ExprPtr& dout, const std::shared_ptr<ContractionExpr>& op, size_t idx) {\n    // Compute Jacobian for SumContraction Op\n    auto Ji = std::make_shared<ContractionExpr>();\n    Ji->agg_op = AggregationOp::ASSIGN;\n    Ji->constraints = op->constraints;\n\n    std::vector<PolyExprPtr> Jidxs;  // Indexes of new total Jacobian\n    std::vector<DimExprPtr> Jdims;   // Dimensions of new total Jacobian\n\n    // Add dimensions to Ji corresponding to op output dimensions\n    auto odims = op->shape.dims_as_exprs();\n    for (size_t i = 0; i < odims.size(); i++) {\n      Jidxs.push_back(op->sink_idxs->idxs[i]);\n      Jdims.push_back(odims[i]);\n    }\n\n    for (size_t j = 0; j < op->srcs.size(); j++) {\n      if (j == idx) {\n        // Add dimensions to Ji corresponding to op w.r.t. input dimensions\n        auto idims = op->srcs[j]->ref->shape.dims_as_exprs();\n        for (size_t i = 0; i < idims.size(); i++) {\n          Jidxs.push_back(op->srcs[j]->idxs[i]);\n          Jdims.push_back(idims[i]);\n        }\n      } else {\n        switch (op->combo_op) {\n          case CombinationOp::MULTIPLY:\n            // Add non-w.r.t. op inputs as inputs to Ji, set combo op for Ji\n            Ji->srcs.push_back(op->srcs[j]);\n            Ji->combo_op = CombinationOp::MULTIPLY;\n            break;\n          case CombinationOp::PLUS:\n            // Jacobian is identity matrix, broadcast through non-wrt dimensions\n            Ji->srcs.push_back(\n                std::make_shared<IndexMapExpr>(std::make_shared<FloatConst>(1.0), std::vector<PolyExprPtr>{}));\n            Ji->combo_op = CombinationOp::NONE;\n            break;\n          default:\n            throw std::runtime_error(\"Combination Op receieved by DeriveSum in Jacobian not implemented\");\n        }\n      }\n    }\n\n    Ji->sink_idxs = std::make_shared<IndexMapExpr>(nullptr, Jidxs);\n    Ji->sink_dims = std::make_shared<SizeMapExpr>(Jdims);\n    Ji->ComputeShape(\"\");\n\n    return ChainRule(dout, Ji);\n  }\n\n  ExprPtr DeriveOverride(const ExprPtr& dout, const std::shared_ptr<GradOverrideExpr>& op, size_t idx) {\n    throw std::runtime_error(\"DeriveOverride not implemented for Jacobian\");\n  }\n\n  ExprPtr DeriveExtreme(const ExprPtr& dout, const std::shared_ptr<ContractionExpr>& op, size_t idx) {\n    throw std::runtime_error(\"DeriveExtreme not implemented for Jacobian\");\n  }\n\n  ExprPtr ChainRule(const ExprPtr& Jprev, const ExprPtr& Ji) {\n    // Combine current Jacobian with total. Output dimensions are\n    // [first {orank_} dimensions of Jprev, last {Ji_rank - orank} dimensions of Ji]\n    auto Jnew = std::make_shared<ContractionExpr>();\n    Jnew->agg_op = AggregationOp::SUM;\n    Jnew->combo_op = CombinationOp::MULTIPLY;\n\n    std::vector<PolyExprPtr> iidxs;  // Indices for op Jacobian\n    std::vector<PolyExprPtr> pidxs;  // Indices for previous total Jacobian\n    std::vector<PolyExprPtr> nidxs;  // Indices for new total Jacobian\n\n    auto idims = Ji->shape.dims_as_exprs();     // Dimensions for op Jacobian\n    auto pdims = Jprev->shape.dims_as_exprs();  // Dimensions for previous total Jacobian\n    std::vector<DimExprPtr> ndims;              // Dimensions for new total Jacobian\n\n    size_t Jirank = idims.size();\n    size_t Jprank = pdims.size();\n\n    // Add dims/idxs corresponding to output dimensions\n    for (size_t i = 0; i < orank_; i++) {\n      auto idx = std::make_shared<PolyIndex>(i);\n      pidxs.push_back(idx);\n      nidxs.push_back(idx);\n      ndims.push_back(pdims[i]);\n    }\n\n    // Add \"overlapping\" idxs\n    for (size_t i = orank_; i < Jprank; i++) {\n      auto idx = std::make_shared<PolyIndex>(i);\n      pidxs.push_back(idx);\n      iidxs.push_back(idx);\n    }\n\n    // Add dim/idxs corresponding to new input dimensions\n    for (size_t i = Jprank - orank_; i < Jirank; i++) {\n      auto idx = std::make_shared<PolyIndex>(i + orank_);\n      iidxs.push_back(idx);\n      nidxs.push_back(idx);\n      ndims.push_back(idims[i]);\n    }\n\n    // Bind sources\n    Jnew->srcs.push_back(std::make_shared<IndexMapExpr>(Jprev, pidxs));\n    Jnew->srcs.push_back(std::make_shared<IndexMapExpr>(Ji, iidxs));\n\n    // Bind output dims/idxs\n    Jnew->sink_idxs = std::make_shared<IndexMapExpr>(nullptr, nidxs);\n    Jnew->sink_dims = std::make_shared<SizeMapExpr>(ndims);\n    Jnew->ComputeShape(\"\");\n\n    return Jnew;\n  }\n\n private:\n  ComputeUses uses_;\n  std::map<const Expr*, ExprPtr> seen_;\n  size_t orank_;\n};\n\n}  // namespace\n\nstd::vector<ExprPtr> ComputeJacobian(const std::vector<ExprPtr>& wrts, const ExprPtr& loss) {\n  ExprPtr value = loss;\n  Jacobian grad(value);\n  std::vector<ExprPtr> ret(wrts.size());\n  for (size_t i = 0; i < wrts.size(); i++) {\n    auto wrt = wrts[i];\n    ret[i] = grad.GetDerivative(wrts[i]);\n  }\n  return ret;\n}\n\n}  // namespace ast\n}  // namespace lang\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "eb0cc520c82034df3f41b95f9b60adb67677b686", "size": 10497, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/lang/ast/jacobian.cc", "max_stars_repo_name": "ZhouXiaolin/plaidml", "max_stars_repo_head_hexsha": "dac460b6ae19a62299d15eeb17b402d8c26d0c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4535.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T05:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:42:33.000Z", "max_issues_repo_path": "tile/lang/ast/jacobian.cc", "max_issues_repo_name": "ZhouXiaolin/plaidml", "max_issues_repo_head_hexsha": "dac460b6ae19a62299d15eeb17b402d8c26d0c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 984.0, "max_issues_repo_issues_event_min_datetime": "2017-10-20T17:16:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:43:18.000Z", "max_forks_repo_path": "tile/lang/ast/jacobian.cc", "max_forks_repo_name": "ZhouXiaolin/plaidml", "max_forks_repo_head_hexsha": "dac460b6ae19a62299d15eeb17b402d8c26d0c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 492.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T18:22:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:00:05.000Z", "avg_line_length": 32.803125, "max_line_length": 111, "alphanum_fraction": 0.6364675622, "num_tokens": 2933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.468790611783139, "lm_q2_score": 0.031143831096811007, "lm_q1q2_score": 0.014599935633144781}}
{"text": "#ifndef SDM_UTILS_HPP_\n#define SDM_UTILS_HPP_\n\n#include \"fmath.hpp\"\n#include \"alias.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\n#include <cstdarg>\n#include <cstddef>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <random>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace sdm {\n\nstatic inline void\nget_cross_validation_index(const int num_fold, const int num_ins,\n                           std::vector<std::vector<int>> &train_indexs,\n                           std::vector<std::vector<int>> &valid_indexs,\n                           const bool random_flag = false,\n                           const bool seed_flag = false) {\n  train_indexs.clear();\n  train_indexs.resize(num_fold);\n  valid_indexs.clear();\n  valid_indexs.resize(num_fold);\n  std::vector<int> whole_index(num_ins);\n  std::iota(std::begin(whole_index), std::end(whole_index), 0);\n\n  if (random_flag) {\n    std::mt19937 engine;\n    if (seed_flag) {\n      std::random_device rnd;\n      std::vector<std::uint_least32_t> v(10);\n      std::generate(std::begin(v), std::end(v), std::ref(rnd));\n      std::seed_seq seed(std::begin(v), std::end(v));\n      engine.seed(seed);\n    }\n    std::shuffle(std::begin(whole_index), std::end(whole_index), engine);\n  }\n\n  int each_fold_num_ins = num_ins / num_fold;\n  std::vector<int> each_fold_num_ins_vec(num_fold, each_fold_num_ins);\n  int rest = num_ins % num_fold;\n  for (int i = 0; i < rest; ++i)\n    ++each_fold_num_ins_vec[i];\n\n  auto start_it = std::begin(whole_index);\n  auto end_it = std::end(whole_index);\n  for (int i = 0; i < num_fold; ++i) {\n    valid_indexs[i].reserve(each_fold_num_ins_vec[i]);\n    end_it = start_it + each_fold_num_ins_vec[i];\n    valid_indexs[i].insert(std::end(valid_indexs[i]), start_it, end_it);\n    start_it = end_it;\n  }\n\n  for (int i = 0; i < num_fold; ++i) {\n    std::sort(std::begin(valid_indexs[i]), std::end(valid_indexs[i]));\n    train_indexs[i].reserve(num_ins - each_fold_num_ins_vec[i]);\n  }\n\n  for (int i = 0; i < num_fold; ++i)\n    for (int j = 0; j < num_fold; ++j)\n      if (i != j)\n        train_indexs[j].insert(std::end(train_indexs[j]),\n                               std::begin(valid_indexs[i]),\n                               std::end(valid_indexs[i]));\n\n  for (int i = 0; i < num_fold; ++i)\n    std::sort(std::begin(train_indexs[i]), std::end(train_indexs[i]));\n}\n\n// misc\nstatic inline std::vector<std::string> split_string(const std::string &str,\n                                                    const std::string &delim) {\n  std::vector<std::string> res;\n  std::string::size_type current = 0, found, delimlen = delim.size();\n  while ((found = str.find(delim, current)) != std::string::npos) {\n    res.push_back(std::string(str, current, found - current));\n    current = found + delimlen;\n  }\n  res.push_back(std::string(str, current, str.size() - current));\n  return res;\n}\n\nstatic inline int count_lines(const std::string file_name) {\n  int num_lines = 0;\n  std::ifstream data_file;\n  std::string line;\n  data_file.open(file_name);\n  if (data_file.fail()) {\n    std::cerr << \"Unable to open \" << file_name << '\\n';\n    exit(8);\n  }\n  while (std::getline(data_file, line))\n    ++num_lines;\n  data_file.close();\n\n  return num_lines;\n}\n\n// for cygwin(GCC) can't use std::stoi\nstatic inline int str2int(const std::string &s) {\n  int r = 0;\n  bool neg = false;\n  int index = 0;\n  while (s[index] == ' ')\n    ++index;\n  if (s[index] == '-') {\n    neg = true;\n    ++index;\n  } else if (s[index] == '+') {\n    ++index;\n  }\n  while (s[index] >= '0' && s[index] <= '9') {\n    r = (r * 10.0) + (s[index] - '0');\n    ++index;\n  }\n  if (neg) {\n    r = -r;\n  }\n  return r;\n}\n\ntemplate <typename ValueType> ValueType naive_atot(const char *p) {\n  ValueType r = 0.0;\n  bool neg = false;\n  while (*p == ' ')\n    ++p;\n  if (*p == '-') {\n    neg = true;\n    ++p;\n  } else if (*p == '+') {\n    ++p;\n  }\n  while (*p >= '0' && *p <= '9') {\n    r = (r * 10.0) + (*p - '0');\n    ++p;\n  }\n  if (*p == '.') {\n    ValueType f = 0.0;\n    int n = 0;\n    ++p;\n    while (*p >= '0' && *p <= '9') {\n      f = (f * 10.0) + (*p - '0');\n      ++p;\n      ++n;\n    }\n    r += f / std::pow(10.0, n);\n  }\n  if (neg) {\n    r = -r;\n  }\n  return r;\n}\n\ntemplate <typename ValueType> ValueType naive_atot(const std::string &s) {\n  ValueType r = 0.0;\n  bool neg = false;\n  auto it = s.begin();\n  while (*it == ' ')\n    ++it;\n  if (*it == '-') {\n    neg = true;\n    ++it;\n  } else if (*it == '-') {\n    ++it;\n  }\n  while (*it >= '0' && *it <= '9') {\n    r = (r * 10.0) + (*it - '0');\n    ++it;\n  }\n  if (*it == '.') {\n    ++it;\n    ValueType f = 0.0;\n    int n = 0;\n    while (*it >= '0' && *it <= '9') {\n      f = (f * 10.0) + (*it - '0');\n      ++it;\n      ++n;\n    }\n    r += f / std::pow(10.0, n);\n  }\n  if (neg)\n    r = -r;\n  return r;\n}\n\ntemplate <typename RealType1, typename RealType2>\ninline bool lessPair(const std::pair<RealType1, RealType2> &l,\n                     const std::pair<RealType1, RealType2> &r) {\n  return l.second < r.second;\n}\n\ntemplate <typename RealType1, typename RealType2>\ninline bool greaterPair(const std::pair<RealType1, RealType2> &l,\n                        const std::pair<RealType1, RealType2> &r) {\n  return l.second > r.second;\n}\n\ntemplate <typename RealType> inline double norm_cdf(const RealType x) {\n  constexpr double a1 = 0.254829592;\n  constexpr double a2 = -0.284496736;\n  constexpr double a3 = 1.421413741;\n  constexpr double a4 = -1.453152027;\n  constexpr double a5 = 1.061405429;\n  constexpr double p = 0.3275911;\n\n  int sign = 1;\n  if (x < static_cast<RealType>(0.0))\n    sign = -1;\n  double tmp = fabs(x) / sqrt(2.0);\n\n  // A&S formula 7.1.26\n  double t = 1.0 / (1.0 + p * tmp);\n  double y = 1.0 -\n             (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t *\n                 fmath::exp(-tmp * tmp);\n\n  return 0.5 * (1.0 + sign * y);\n}\n\ntemplate <typename RealType> inline double normsinv(const RealType pos) {\n\n  constexpr double A1 = (-3.969683028665376e+01);\n  constexpr double A2 = 2.209460984245205e+02;\n  constexpr double A3 = (-2.759285104469687e+02);\n  constexpr double A4 = 1.383577518672690e+02;\n  constexpr double A5 = (-3.066479806614716e+01);\n  constexpr double A6 = 2.506628277459239e+00;\n\n  constexpr double B1 = (-5.447609879822406e+01);\n  constexpr double B2 = 1.615858368580409e+02;\n  constexpr double B3 = (-1.556989798598866e+02);\n  constexpr double B4 = 6.680131188771972e+01;\n  constexpr double B5 = (-1.328068155288572e+01);\n\n  constexpr double C1 = (-7.784894002430293e-03);\n  constexpr double C2 = (-3.223964580411365e-01);\n  constexpr double C3 = (-2.400758277161838e+00);\n  constexpr double C4 = (-2.549732539343734e+00);\n  constexpr double C5 = 4.374664141464968e+00;\n  constexpr double C6 = 2.938163982698783e+00;\n\n  constexpr double D1 = 7.784695709041462e-03;\n  constexpr double D2 = 3.224671290700398e-01;\n  constexpr double D3 = 2.445134137142996e+00;\n  constexpr double D4 = 3.754408661907416e+00;\n\n  constexpr double P_LOW = 0.02425;\n  /* P_high = 1 - p_low*/\n  constexpr double P_HIGH = 0.97575;\n\n  double x = 0.0;\n  double q, r;\n  if ((0 < pos) && (pos < P_LOW)) {\n    q = sqrt(-2 * fmath::log(pos));\n    x = (((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) /\n        ((((D1 * q + D2) * q + D3) * q + D4) * q + 1);\n  } else {\n    if ((P_LOW <= pos) && (pos <= P_HIGH)) {\n      q = pos - 0.5;\n      r = q * q;\n      x = (((((A1 * r + A2) * r + A3) * r + A4) * r + A5) * r + A6) * q /\n          (((((B1 * r + B2) * r + B3) * r + B4) * r + B5) * r + 1);\n    } else {\n      if ((P_HIGH < pos) && (pos < 1)) {\n        q = sqrt(-2 * fmath::log(1 - pos));\n        x = -(((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) /\n            ((((D1 * q + D2) * q + D3) * q + D4) * q + 1);\n      } else {\n        std::cout << \"CDF position > 1 : \" << pos << std::endl;\n        x = 1.0;\n      }\n    }\n  }\n\n  /*\n  // If you are composiling this under UNIX OR LINUX, you may uncomment this\n  // block for better accuracy.\n  if(( 0 < pos)&&(pos < 1)){\n    e = 0.5 * erfc(-x/sqrt(2)) - pos;\n    u = e * sqrt(2*M_PI) * exp(x*x/2);\n    x = x - u/(1 + x*u/2);\n  }\n  */\n\n  return x;\n}\n\ntemplate <typename ValueType>\nbool compare(const ValueType &lhs, const ValueType &rhs,\n             const ValueType eps = 1e-12) {\n  return (std::abs(lhs - rhs) <= std::max(lhs, rhs) * eps ||\n          std::abs(lhs - rhs) <= eps);\n}\n\ntemplate <typename ValueType, int _Rows, int _Cols, int _Option>\nValueType compare(const Eigen::Matrix<ValueType, _Rows, _Cols, _Option> &mat,\n                  const ValueType value, const ValueType eps = 1e-12) {\n  ValueType v;\n  int num_eq = 0;\n  if (_Option == Eigen::RowMajor) {\n    for (int i = 0; i < mat.rows(); ++i) {\n      for (int j = 0; j < mat.cols(); ++j) {\n        v = mat.coeffRef(i, j);\n        if (compare(v, value, eps))\n          ++num_eq;\n      }\n    }\n  } else {\n    for (int j = 0; j < mat.cols(); ++j) {\n      for (int i = 0; i < mat.rows(); ++i) {\n        v = mat.coeffRef(i, j);\n        if (compare(v, value, eps))\n          ++num_eq;\n      }\n    }\n  }\n  return num_eq;\n}\n\n} // namespace sdm\n\n#endif\n", "meta": {"hexsha": "40fa5fba8b603b39027ee18a4c7f3b3bc5812e65", "size": 9255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdm/lib/utils.hpp", "max_stars_repo_name": "takeuchi-admin/s3fs", "max_stars_repo_head_hexsha": "707976e060b789c6f01364f8161fdbedbad5c7c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-01-15T14:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T08:12:45.000Z", "max_issues_repo_path": "sdm/lib/utils.hpp", "max_issues_repo_name": "takeuchi-admin/s3fs", "max_issues_repo_head_hexsha": "707976e060b789c6f01364f8161fdbedbad5c7c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdm/lib/utils.hpp", "max_forks_repo_name": "takeuchi-admin/s3fs", "max_forks_repo_head_hexsha": "707976e060b789c6f01364f8161fdbedbad5c7c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-26T01:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-23T16:49:26.000Z", "avg_line_length": 27.3008849558, "max_line_length": 79, "alphanum_fraction": 0.5566720692, "num_tokens": 3042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.04272219358530651, "lm_q1q2_score": 0.014593153666356632}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2018-2022.\n// Modifications copyright (c) 2018-2022 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_ALGORITHMS_SIMPLIFY_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_SIMPLIFY_HPP\n\n#include <cstddef>\n#ifdef BOOST_GEOMETRY_DEBUG_DOUGLAS_PEUCKER\n#include <iostream>\n#endif\n#include <set>\n#include <vector>\n\n#include <boost/core/addressof.hpp>\n#include <boost/core/ignore_unused.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/size.hpp>\n#include <boost/range/value_type.hpp>\n\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/clear.hpp>\n#include <boost/geometry/algorithms/convert.hpp>\n#include <boost/geometry/algorithms/detail/dummy_geometries.hpp>\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\n#include <boost/geometry/algorithms/detail/visit.hpp>\n#include <boost/geometry/algorithms/not_implemented.hpp>\n#include <boost/geometry/algorithms/is_empty.hpp>\n#include <boost/geometry/algorithms/perimeter.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n#include <boost/geometry/core/mutable_range.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/core/visit.hpp>\n\n#include <boost/geometry/geometries/adapted/boost_variant.hpp> // For backward compatibility\n#include <boost/geometry/geometries/concepts/check.hpp>\n\n#include <boost/geometry/strategies/concepts/simplify_concept.hpp>\n#include <boost/geometry/strategies/default_strategy.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n#include <boost/geometry/strategies/distance/comparable.hpp>\n#include <boost/geometry/strategies/simplify/cartesian.hpp>\n#include <boost/geometry/strategies/simplify/geographic.hpp>\n#include <boost/geometry/strategies/simplify/spherical.hpp>\n\n#include <boost/geometry/util/type_traits_std.hpp>\n\n#ifdef BOOST_GEOMETRY_DEBUG_DOUGLAS_PEUCKER\n#include <boost/geometry/io/dsv/write.hpp>\n#endif\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace simplify\n{\n\n/*!\n\\brief Small wrapper around a point, with an extra member \"included\"\n\\details\n    It has a const-reference to the original point (so no copy here)\n\\tparam the enclosed point type\n*/\ntemplate <typename Point>\nstruct douglas_peucker_point\n{\n    typedef Point point_type;\n\n    Point const* p;\n    bool included;\n\n    inline douglas_peucker_point(Point const& ap)\n        : p(boost::addressof(ap))\n        , included(false)\n    {}\n};\n\n/*!\n\\brief Implements the simplify algorithm.\n\\details The douglas_peucker policy simplifies a linestring, ring or\n    vector of points using the well-known Douglas-Peucker algorithm.\n\\tparam Point the point type\n\\tparam PointDistanceStrategy point-segment distance strategy to be used\n\\note This strategy uses itself a point-segment-distance strategy which\n    can be specified\n\\author Barend and Maarten, 1995/1996\n\\author Barend, revised for Generic Geometry Library, 2008\n*/\n\n/*\nFor the algorithm, see for example:\n - http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\n - http://www2.dcs.hull.ac.uk/CISRG/projects/Royal-Inst/demos/dp.html\n*/\nclass douglas_peucker\n{\n    template <typename Iterator, typename Distance, typename PSDistanceStrategy>\n    static inline void consider(Iterator begin,\n                                Iterator end,\n                                Distance const& max_dist,\n                                int& n,\n                                PSDistanceStrategy const& ps_distance_strategy)\n    {\n        typedef typename std::iterator_traits<Iterator>::value_type::point_type point_type;\n        typedef decltype(ps_distance_strategy.apply(std::declval<point_type>(),\n                            std::declval<point_type>(), std::declval<point_type>())) distance_type;\n\n        std::size_t size = end - begin;\n\n        // size must be at least 3\n        // because we want to consider a candidate point in between\n        if (size <= 2)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_DOUGLAS_PEUCKER\n            if (begin != end)\n            {\n                std::cout << \"ignore between \" << dsv(*(begin->p))\n                    << \" and \" << dsv(*((end - 1)->p))\n                    << \" size=\" << size << std::endl;\n            }\n            std::cout << \"return because size=\" << size << std::endl;\n#endif\n            return;\n        }\n\n        Iterator last = end - 1;\n\n#ifdef BOOST_GEOMETRY_DEBUG_DOUGLAS_PEUCKER\n        std::cout << \"find between \" << dsv(*(begin->p))\n            << \" and \" << dsv(*(last->p))\n            << \" size=\" << size << std::endl;\n#endif\n\n\n        // Find most far point, compare to the current segment\n        //geometry::segment<Point const> s(begin->p, last->p);\n        distance_type md(-1.0); // any value < 0\n        Iterator candidate = end;\n        for (Iterator it = begin + 1; it != last; ++it)\n        {\n            distance_type dist = ps_distance_strategy.apply(*(it->p), *(begin->p), *(last->p));\n\n#ifdef BOOST_GEOMETRY_DEBUG_DOUGLAS_PEUCKER\n            std::cout << \"consider \" << dsv(*(it->p))\n                << \" at \" << double(dist)\n                << ((dist > max_dist) ? \" maybe\" : \" no\")\n                << std::endl;\n\n#endif\n            if (md < dist)\n            {\n                md = dist;\n                candidate = it;\n            }\n        }\n\n        // If a point is found, set the include flag\n        // and handle segments in between recursively\n        if (max_dist < md && candidate != end)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_DOUGLAS_PEUCKER\n            std::cout << \"use \" << dsv(candidate->p) << std::endl;\n#endif\n\n            candidate->included = true;\n            n++;\n\n            consider(begin, candidate + 1, max_dist, n, ps_distance_strategy);\n            consider(candidate, end, max_dist, n, ps_distance_strategy);\n        }\n    }\n\n    template\n    <\n        typename Range, typename OutputIterator, typename Distance,\n        typename PSDistanceStrategy\n    >\n    static inline OutputIterator apply_(Range const& range,\n                                        OutputIterator out,\n                                        Distance const& max_distance,\n                                        PSDistanceStrategy const& ps_distance_strategy)\n    {\n#ifdef BOOST_GEOMETRY_DEBUG_DOUGLAS_PEUCKER\n            std::cout << \"max distance: \" << max_distance\n                      << std::endl << std::endl;\n#endif\n\n        typedef typename boost::range_value<Range>::type point_type;\n        typedef douglas_peucker_point<point_type> dp_point_type;\n\n        // Copy coordinates, a vector of references to all points\n        std::vector<dp_point_type> ref_candidates(boost::begin(range),\n                                                  boost::end(range));\n\n        // Include first and last point of line,\n        // they are always part of the line\n        int n = 2;\n        ref_candidates.front().included = true;\n        ref_candidates.back().included = true;\n\n        // Get points, recursively, including them if they are further away\n        // than the specified distance\n        consider(boost::begin(ref_candidates), boost::end(ref_candidates), max_distance, n,\n                 ps_distance_strategy);\n\n        // Copy included elements to the output\n        for (auto it = boost::begin(ref_candidates); it != boost::end(ref_candidates); ++it)\n        {\n            if (it->included)\n            {\n                // copy-coordinates does not work because OutputIterator\n                // does not model Point (??)\n                //geometry::convert(*(it->p), *out);\n                *out = *(it->p);\n                ++out;\n            }\n        }\n        return out;\n    }\n\npublic:\n    template <typename Range, typename OutputIterator, typename Distance, typename Strategies>\n    static inline OutputIterator apply(Range const& range,\n                                       OutputIterator out,\n                                       Distance const& max_distance,\n                                       Strategies const& strategies)\n    {\n        typedef typename boost::range_value<Range>::type point_type;\n        typedef decltype(strategies.distance(detail::dummy_point(), detail::dummy_segment())) distance_strategy_type;\n\n        typedef typename strategy::distance::services::comparable_type\n            <\n                distance_strategy_type\n            >::type comparable_distance_strategy_type;\n\n        comparable_distance_strategy_type cstrategy = strategy::distance::services::get_comparable\n            <\n                distance_strategy_type\n            >::apply(strategies.distance(detail::dummy_point(), detail::dummy_segment()));\n\n        return apply_(range, out,\n                      strategy::distance::services::result_from_distance\n                          <\n                              comparable_distance_strategy_type, point_type, point_type\n                          >::apply(cstrategy, max_distance),\n                      cstrategy);\n    }\n};\n\n\ntemplate <typename Range, typename Strategies>\ninline bool is_degenerate(Range const& range, Strategies const& strategies)\n{\n    return boost::size(range) == 2\n        && detail::equals::equals_point_point(geometry::range::front(range),\n                                              geometry::range::back(range),\n                                              strategies);\n}\n\nstruct simplify_range_insert\n{\n    template\n    <\n        typename Range, typename OutputIterator, typename Distance,\n        typename Impl, typename Strategies\n    >\n    static inline void apply(Range const& range, OutputIterator out,\n                             Distance const& max_distance,\n                             Impl const& impl,\n                             Strategies const& strategies)\n    {\n        if (is_degenerate(range, strategies))\n        {\n            std::copy(boost::begin(range), boost::begin(range) + 1, out);\n        }\n        else if (boost::size(range) <= 2 || max_distance < 0)\n        {\n            std::copy(boost::begin(range), boost::end(range), out);\n        }\n        else\n        {\n            impl.apply(range, out, max_distance, strategies);\n        }\n    }\n};\n\n\nstruct simplify_copy_assign\n{\n    template\n    <\n        typename In, typename Out, typename Distance,\n        typename Impl, typename Strategies\n    >\n    static inline void apply(In const& in, Out& out,\n                             Distance const& ,\n                             Impl const& ,\n                             Strategies const& )\n    {\n        out = in;\n    }\n};\n\n\nstruct simplify_copy\n{\n    template\n    <\n        typename RangeIn, typename RangeOut, typename Distance,\n        typename Impl, typename Strategies\n    >\n    static inline void apply(RangeIn const& range, RangeOut& out,\n                             Distance const& ,\n                             Impl const& ,\n                             Strategies const& )\n    {\n        std::copy(boost::begin(range), boost::end(range),\n                  geometry::range::back_inserter(out));\n    }\n};\n\n\ntemplate <std::size_t MinimumToUseStrategy>\nstruct simplify_range\n{\n    template\n    <\n        typename RangeIn, typename RangeOut, typename Distance,\n        typename Impl, typename Strategies\n    >\n    static inline void apply(RangeIn const& range, RangeOut& out,\n                             Distance const& max_distance,\n                             Impl const& impl,\n                             Strategies const& strategies)\n    {\n        // For a RING:\n        // Note that, especially if max_distance is too large,\n        // the output ring might be self intersecting while the input ring is\n        // not, although chances are low in normal polygons\n\n        if (boost::size(range) <= MinimumToUseStrategy || max_distance < 0)\n        {\n            simplify_copy::apply(range, out, max_distance, impl, strategies);\n        }\n        else\n        {\n            simplify_range_insert::apply(range, geometry::range::back_inserter(out),\n                                         max_distance, impl, strategies);\n        }\n\n        // Verify the two remaining points are equal. If so, remove one of them.\n        // This can cause the output being under the minimum size\n        if (is_degenerate(out, strategies))\n        {\n            range::resize(out, 1);\n        }\n    }\n};\n\nstruct simplify_ring\n{\nprivate :\n    template <typename Area>\n    static inline int area_sign(Area const& area)\n    {\n        return area > 0 ? 1 : area < 0 ? -1 : 0;\n    }\n\n    template <typename Ring, typename Strategies>\n    static std::size_t get_opposite(std::size_t index, Ring const& ring,\n                                    Strategies const& strategies)\n    {\n        // TODO: Instead of calling the strategy call geometry::comparable_distance() ?\n\n        auto const cdistance_strategy = strategies::distance::detail::make_comparable(strategies)\n            .distance(detail::dummy_point(), detail::dummy_point());\n\n        using point_type = typename geometry::point_type<Ring>::type;\n        using cdistance_type = decltype(cdistance_strategy.apply(\n            std::declval<point_type>(), std::declval<point_type>()));\n\n        // Verify if it is NOT the case that all points are less than the\n        // simplifying distance. If so, output is empty.\n        cdistance_type max_cdistance(-1);\n\n        point_type const& point = range::at(ring, index);\n        std::size_t i = 0;\n        for (auto it = boost::begin(ring); it != boost::end(ring); ++it, ++i)\n        {\n            cdistance_type const cdistance = cdistance_strategy.apply(*it, point);\n            if (cdistance > max_cdistance)\n            {\n                max_cdistance = cdistance;\n                index = i;\n            }\n        }\n        return index;\n    }\n\npublic :\n    template <typename Ring, typename Distance, typename Impl, typename Strategies>\n    static inline void apply(Ring const& ring, Ring& out, Distance const& max_distance,\n                             Impl const& impl, Strategies const& strategies)\n    {\n        std::size_t const size = boost::size(ring);\n        if (size == 0)\n        {\n            return;\n        }\n\n        bool const is_closed = closure<Ring>::value == closed;\n\n        // TODO: instead of area() use calculate_point_order() ?\n\n        int const input_sign = area_sign(geometry::area(ring, strategies));\n\n        std::set<std::size_t> visited_indexes;\n\n        // Rotate it into a copied vector\n        // (vector, because source type might not support rotation)\n        // (duplicate end point will be simplified away)\n        typedef typename geometry::point_type<Ring>::type point_type;\n\n        std::vector<point_type> rotated;\n        rotated.reserve(size + 1); // 1 because open rings are closed\n\n        // Closing point (but it will not start here)\n        std::size_t index = 0;\n\n        // Iterate (usually one iteration is enough)\n        for (std::size_t iteration = 0; iteration < 4u; iteration++)\n        {\n            // Always take the opposite. Opposite guarantees that no point\n            // \"halfway\" is chosen, creating an artefact (very narrow triangle)\n            // Iteration 0: opposite to closing point (1/2, = on convex hull)\n            //              (this will start simplification with that point\n            //               and its opposite ~0)\n            // Iteration 1: move a quarter on that ring, then opposite to 1/4\n            //              (with its opposite 3/4)\n            // Iteration 2: move an eight on that ring, then opposite (1/8)\n            // Iteration 3: again move a quarter, then opposite (7/8)\n            // So finally 8 \"sides\" of the ring have been examined (if it were\n            // a semi-circle). Most probably, there are only 0 or 1 iterations.\n            switch (iteration)\n            {\n                case 1 : index = (index + size / 4) % size; break;\n                case 2 : index = (index + size / 8) % size; break;\n                case 3 : index = (index + size / 4) % size; break;\n            }\n            index = get_opposite(index, ring, strategies);\n\n            if (visited_indexes.count(index) > 0)\n            {\n                // Avoid trying the same starting point more than once\n                continue;\n            }\n\n            // Do not duplicate the closing point\n            auto rot_end = boost::end(ring);\n            std::size_t rot_index = index;\n            if (is_closed && size > 1)\n            {\n                --rot_end;\n                if (rot_index == size - 1) { rot_index = 0; }\n            }\n\n            std::rotate_copy(boost::begin(ring), range::pos(ring, rot_index),\n                             rot_end, std::back_inserter(rotated));\n\n            // Close the rotated copy\n            rotated.push_back(range::at(ring, rot_index));\n\n            simplify_range<0>::apply(rotated, out, max_distance, impl, strategies);\n\n            // Open output if needed\n            if (! is_closed && boost::size(out) > 1)\n            {\n                range::pop_back(out);\n            }\n\n            // TODO: instead of area() use calculate_point_order() ?\n\n            // Verify that what was positive, stays positive (or goes to 0)\n            // and what was negative stays negative (or goes to 0)\n            int const output_sign = area_sign(geometry::area(out, strategies));\n            if (output_sign == input_sign)\n            {\n                // Result is considered as satisfactory (usually this is the\n                // first iteration - only for small rings, having a scale\n                // similar to simplify_distance, next iterations are tried\n                return;\n            }\n\n            // Original is simplified away. Possibly there is a solution\n            // when another starting point is used\n            geometry::clear(out);\n\n            if (iteration == 0\n                && geometry::perimeter(ring, strategies) < 3 * max_distance)\n            {\n                // Check if it is useful to iterate. A minimal triangle has a\n                // perimeter of a bit more than 3 times the simplify distance\n                return;\n            }\n\n            // Prepare next try\n            visited_indexes.insert(index);\n            rotated.clear();\n        }\n    }\n};\n\n\nstruct simplify_polygon\n{\nprivate:\n\n    template\n    <\n        typename IteratorIn,\n        typename InteriorRingsOut,\n        typename Distance,\n        typename Impl,\n        typename Strategies\n    >\n    static inline void iterate(IteratorIn begin, IteratorIn end,\n                               InteriorRingsOut& interior_rings_out,\n                               Distance const& max_distance,\n                               Impl const& impl, Strategies const& strategies)\n    {\n        typedef typename boost::range_value<InteriorRingsOut>::type single_type;\n        for (IteratorIn it = begin; it != end; ++it)\n        {\n            single_type out;\n            simplify_ring::apply(*it, out, max_distance, impl, strategies);\n            if (! geometry::is_empty(out))\n            {\n                range::push_back(interior_rings_out, std::move(out));\n            }\n        }\n    }\n\n    template\n    <\n        typename InteriorRingsIn,\n        typename InteriorRingsOut,\n        typename Distance,\n        typename Impl,\n        typename Strategies\n    >\n    static inline void apply_interior_rings(InteriorRingsIn const& interior_rings_in,\n                                            InteriorRingsOut& interior_rings_out,\n                                            Distance const& max_distance,\n                                            Impl const& impl, Strategies const& strategies)\n    {\n        range::clear(interior_rings_out);\n\n        iterate(boost::begin(interior_rings_in), boost::end(interior_rings_in),\n                interior_rings_out,\n                max_distance,\n                impl, strategies);\n    }\n\npublic:\n    template <typename Polygon, typename Distance, typename Impl, typename Strategies>\n    static inline void apply(Polygon const& poly_in, Polygon& poly_out,\n                             Distance const& max_distance,\n                             Impl const& impl, Strategies const& strategies)\n    {\n        // Note that if there are inner rings, and distance is too large,\n        // they might intersect with the outer ring in the output,\n        // while it didn't in the input.\n        simplify_ring::apply(exterior_ring(poly_in), exterior_ring(poly_out),\n                             max_distance, impl, strategies);\n\n        apply_interior_rings(interior_rings(poly_in), interior_rings(poly_out),\n                             max_distance, impl, strategies);\n    }\n};\n\n\ntemplate<typename Policy>\nstruct simplify_multi\n{\n    template <typename MultiGeometry, typename Distance, typename Impl, typename Strategies>\n    static inline void apply(MultiGeometry const& multi, MultiGeometry& out,\n                             Distance const& max_distance,\n                             Impl const& impl, Strategies const& strategies)\n    {\n        range::clear(out);\n\n        typedef typename boost::range_value<MultiGeometry>::type single_type;\n\n        for (typename boost::range_iterator<MultiGeometry const>::type\n                it = boost::begin(multi); it != boost::end(multi); ++it)\n        {\n            single_type single_out;\n            Policy::apply(*it, single_out, max_distance, impl, strategies);\n            if (! geometry::is_empty(single_out))\n            {\n                range::push_back(out, std::move(single_out));\n            }\n        }\n    }\n};\n\n\n}} // namespace detail::simplify\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 simplify: not_implemented<Tag>\n{};\n\ntemplate <typename Point>\nstruct simplify<Point, point_tag>\n{\n    template <typename Distance, typename Impl, typename Strategy>\n    static inline void apply(Point const& point, Point& out, Distance const& ,\n                             Impl const& , Strategy const& )\n    {\n        geometry::convert(point, out);\n    }\n};\n\ntemplate <typename Segment>\nstruct simplify<Segment, segment_tag>\n    : detail::simplify::simplify_copy_assign\n{};\n\ntemplate <typename Box>\nstruct simplify<Box, box_tag>\n    : detail::simplify::simplify_copy_assign\n{};\n\n\n// Linestring, keep 2 points (unless those points are the same)\ntemplate <typename Linestring>\nstruct simplify<Linestring, linestring_tag>\n    : detail::simplify::simplify_range<2>\n{};\n\ntemplate <typename Ring>\nstruct simplify<Ring, ring_tag>\n    : detail::simplify::simplify_ring\n{};\n\ntemplate <typename Polygon>\nstruct simplify<Polygon, polygon_tag>\n    : detail::simplify::simplify_polygon\n{};\n\n\ntemplate\n<\n    typename Geometry,\n    typename Tag = typename tag<Geometry>::type\n>\nstruct simplify_insert: not_implemented<Tag>\n{};\n\n\ntemplate <typename Linestring>\nstruct simplify_insert<Linestring, linestring_tag>\n    : detail::simplify::simplify_range_insert\n{};\n\ntemplate <typename Ring>\nstruct simplify_insert<Ring, ring_tag>\n    : detail::simplify::simplify_range_insert\n{};\n\ntemplate <typename MultiPoint>\nstruct simplify<MultiPoint, multi_point_tag>\n    : detail::simplify::simplify_copy\n{};\n\n\ntemplate <typename MultiLinestring>\nstruct simplify<MultiLinestring, multi_linestring_tag>\n    : detail::simplify::simplify_multi<detail::simplify::simplify_range<2> >\n{};\n\n\ntemplate <typename MultiPolygon>\nstruct simplify<MultiPolygon, multi_polygon_tag>\n    : detail::simplify::simplify_multi<detail::simplify::simplify_polygon>\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy\n{\n\ntemplate\n<\n    typename Strategies,\n    bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategies>::value\n>\nstruct simplify\n{\n    template <typename Geometry, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             Strategies const& strategies)\n    {\n        dispatch::simplify\n            <\n                Geometry\n            >::apply(geometry, out, max_distance,\n                     detail::simplify::douglas_peucker(),\n                     strategies);\n    }\n};\n\ntemplate <typename Strategy>\nstruct simplify<Strategy, false>\n{\n    template <typename Geometry, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        using strategies::simplify::services::strategy_converter;\n\n        simplify\n            <\n                decltype(strategy_converter<Strategy>::get(strategy))\n            >::apply(geometry, out, max_distance,\n                     strategy_converter<Strategy>::get(strategy));\n    }\n};\n\ntemplate <>\nstruct simplify<default_strategy, false>\n{\n    template <typename Geometry, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             default_strategy)\n    {\n        typedef typename strategies::simplify::services::default_strategy\n            <\n                Geometry\n            >::type strategy_type;\n\n        simplify\n            <\n                strategy_type\n            >::apply(geometry, out, max_distance, strategy_type());\n    }\n};\n\ntemplate\n<\n    typename Strategies,\n    bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategies>::value\n>\nstruct simplify_insert\n{\n    template<typename Geometry, typename OutputIterator, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             OutputIterator& out,\n                             Distance const& max_distance,\n                             Strategies const& strategies)\n    {\n        dispatch::simplify_insert\n            <\n                Geometry\n            >::apply(geometry, out, max_distance,\n                     detail::simplify::douglas_peucker(),\n                     strategies);\n    }\n};\n\ntemplate <typename Strategy>\nstruct simplify_insert<Strategy, false>\n{\n    template<typename Geometry, typename OutputIterator, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             OutputIterator& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        using strategies::simplify::services::strategy_converter;\n\n        simplify_insert\n            <\n                decltype(strategy_converter<Strategy>::get(strategy))\n            >::apply(geometry, out, max_distance,\n                     strategy_converter<Strategy>::get(strategy));\n    }\n};\n\ntemplate <>\nstruct simplify_insert<default_strategy, false>\n{\n    template <typename Geometry, typename OutputIterator, typename Distance>\n    static inline void apply(Geometry const& geometry,\n                             OutputIterator& out,\n                             Distance const& max_distance,\n                             default_strategy)\n    {\n        typedef typename strategies::simplify::services::default_strategy\n            <\n                Geometry\n            >::type strategy_type;\n        \n        simplify_insert\n            <\n                strategy_type\n            >::apply(geometry, out, max_distance, strategy_type());\n    }\n};\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_dynamic {\n\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct simplify\n{\n    template <typename Distance, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        resolve_strategy::simplify<Strategy>::apply(geometry, out, max_distance, strategy);\n    }\n};\n\ntemplate <typename Geometry>\nstruct simplify<Geometry, dynamic_geometry_tag>\n{\n    template <typename Distance, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        traits::visit<Geometry>::apply([&](auto const& g)\n        {\n            using geom_t = util::remove_cref_t<decltype(g)>;\n            geom_t o;\n            simplify<geom_t>::apply(g, o, max_distance, strategy);\n            out = std::move(o);\n        }, geometry);\n    }\n};\n\ntemplate <typename Geometry>\nstruct simplify<Geometry, geometry_collection_tag>\n{\n    template <typename Distance, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             Geometry& out,\n                             Distance const& max_distance,\n                             Strategy const& strategy)\n    {\n        detail::visit_breadth_first([&](auto const& g)\n        {\n            using geom_t = util::remove_cref_t<decltype(g)>;\n            geom_t o;\n            simplify<geom_t>::apply(g, o, max_distance, strategy);\n            traits::emplace_back<Geometry>::apply(out, std::move(o));\n            return true;\n        }, geometry);\n    }\n};\n\n} // namespace resolve_dynamic\n\n\n/*!\n\\brief Simplify a geometry using a specified strategy\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\tparam Distance A numerical distance measure\n\\tparam Strategy A type fulfilling a SimplifyStrategy concept\n\\param strategy A strategy to calculate simplification\n\\param geometry input geometry, to be simplified\n\\param out output geometry, simplified version of the input geometry\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\\param strategy simplify strategy to be used for simplification, might\n    include point-distance strategy\n\n\\image html svg_simplify_country.png \"The image below presents the simplified country\"\n\\qbk{distinguish,with strategy}\n*/\ntemplate<typename Geometry, typename Distance, typename Strategy>\ninline void simplify(Geometry const& geometry, Geometry& out,\n                     Distance const& max_distance, Strategy const& strategy)\n{\n    concepts::check<Geometry>();\n\n    geometry::clear(out);\n\n    resolve_dynamic::simplify<Geometry>::apply(geometry, out, max_distance, strategy);\n}\n\n\n\n\n/*!\n\\brief Simplify a geometry\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\tparam Distance \\tparam_numeric\n\\note This version of simplify simplifies a geometry using the default\n    strategy (Douglas Peucker),\n\\param geometry input geometry, to be simplified\n\\param out output geometry, simplified version of the input geometry\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\n\\qbk{[include reference/algorithms/simplify.qbk]}\n */\ntemplate<typename Geometry, typename Distance>\ninline void simplify(Geometry const& geometry, Geometry& out,\n                     Distance const& max_distance)\n{\n    concepts::check<Geometry>();\n\n    geometry::simplify(geometry, out, max_distance, default_strategy());\n}\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace simplify\n{\n\n\n/*!\n\\brief Simplify a geometry, using an output iterator\n    and a specified strategy\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\param geometry input geometry, to be simplified\n\\param out output iterator, outputs all simplified points\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\\param strategy simplify strategy to be used for simplification,\n    might include point-distance strategy\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/simplify.qbk]}\n*/\ntemplate<typename Geometry, typename OutputIterator, typename Distance, typename Strategy>\ninline void simplify_insert(Geometry const& geometry, OutputIterator out,\n                            Distance const& max_distance, Strategy const& strategy)\n{\n    concepts::check<Geometry const>();\n\n    resolve_strategy::simplify_insert<Strategy>::apply(geometry, out, max_distance, strategy);\n}\n\n/*!\n\\brief Simplify a geometry, using an output iterator\n\\ingroup simplify\n\\tparam Geometry \\tparam_geometry\n\\param geometry input geometry, to be simplified\n\\param out output iterator, outputs all simplified points\n\\param max_distance distance (in units of input coordinates) of a vertex\n    to other segments to be removed\n\n\\qbk{[include reference/algorithms/simplify_insert.qbk]}\n */\ntemplate<typename Geometry, typename OutputIterator, typename Distance>\ninline void simplify_insert(Geometry const& geometry, OutputIterator out,\n                            Distance const& max_distance)\n{\n    // Concept: output point type = point type of input geometry\n    concepts::check<Geometry const>();\n    concepts::check<typename point_type<Geometry>::type>();\n\n    simplify_insert(geometry, out, max_distance, default_strategy());\n}\n\n}} // namespace detail::simplify\n#endif // DOXYGEN_NO_DETAIL\n\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_SIMPLIFY_HPP\n", "meta": {"hexsha": "c8093d22e75cc30bf0448631aab5526ac1424e9b", "size": 34056, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/algorithms/simplify.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/algorithms/simplify.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/algorithms/simplify.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": 33.2578125, "max_line_length": 117, "alphanum_fraction": 0.6153100775, "num_tokens": 6949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.03789242554311634, "lm_q1q2_score": 0.014585254775498688}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include \"Evolution/DiscontinuousGalerkin/Limiters/Minmod.hpp\"\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstdlib>\n#include <iterator>\n#include <limits>\n#include <memory>\n#include <pup.h>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Tags.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/OrientationMap.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodType.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/Literals.hpp\"\n#include \"Utilities/Numeric.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace Limiters {\nnamespace Minmod_detail {\n\n// Implements the minmod limiter for one Tensor<DataVector> at a time.\ntemplate <size_t VolumeDim, typename Tag, typename PackagedData>\nbool limit_one_tensor(\n    const gsl::not_null<DataVector*> u_lin_buffer,\n    const gsl::not_null<BufferWrapper<VolumeDim>*> buffer,\n    const gsl::not_null<typename Tag::type*> tensor,\n    const Limiters::MinmodType minmod_type, const double tvb_constant,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const tnsr::I<DataVector, VolumeDim, Frame::Logical>& logical_coords,\n    const std::array<double, VolumeDim>& element_size,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) noexcept {\n  // True if the mesh is linear-order in every direction\n  const bool mesh_is_linear = (mesh.extents() == Index<VolumeDim>(2));\n  const bool minmod_type_is_linear =\n      (minmod_type != Limiters::MinmodType::LambdaPiN);\n  const bool using_linear_limiter_on_non_linear_mesh =\n      minmod_type_is_linear and not mesh_is_linear;\n\n  // In each direction, average the size of all different neighbors in that\n  // direction. Note that only the component of neighor_size that is normal\n  // to the face is needed (and, therefore, computed). Note that this average\n  // does not depend on the solution on the neighboring elements, so could be\n  // precomputed outside of `limit_one_tensor`. Changing the code to\n  // precompute the average may or may not be a measurable optimization.\n  const auto effective_neighbor_sizes =\n      compute_effective_neighbor_sizes(element, neighbor_data);\n\n  bool some_component_was_limited = false;\n  for (size_t i = 0; i < tensor->size(); ++i) {\n    // In each direction, average the mean of the i'th tensor component over\n    // all different neighbors in that direction. This produces one effective\n    // neighbor per direction.\n    const auto effective_neighbor_means =\n        compute_effective_neighbor_means<Tag>(i, element, neighbor_data);\n\n    DataVector& u = (*tensor)[i];\n    double u_mean = std::numeric_limits<double>::signaling_NaN();\n    std::array<double, VolumeDim> u_limited_slopes{};\n    const bool reduce_slopes = minmod_limited_slopes(\n        u_lin_buffer, buffer, make_not_null(&u_mean),\n        make_not_null(&u_limited_slopes), minmod_type, tvb_constant, u, mesh,\n        element, element_size, effective_neighbor_means,\n        effective_neighbor_sizes);\n\n    if (reduce_slopes or using_linear_limiter_on_non_linear_mesh) {\n      u = u_mean;\n      for (size_t d = 0; d < VolumeDim; ++d) {\n        u += logical_coords.get(d) * gsl::at(u_limited_slopes, d);\n      }\n      some_component_was_limited = true;\n    }\n  }  // end for loop over tensor components\n\n  return some_component_was_limited;\n}\n\n}  // namespace Minmod_detail\n\ntemplate <size_t VolumeDim, typename... Tags>\nMinmod<VolumeDim, tmpl::list<Tags...>>::Minmod(\n    const MinmodType minmod_type, const double tvb_constant,\n    const bool disable_for_debugging) noexcept\n    : minmod_type_(minmod_type),\n      tvb_constant_(tvb_constant),\n      disable_for_debugging_(disable_for_debugging) {\n  ASSERT(tvb_constant >= 0.0, \"The TVB constant must be non-negative.\");\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nvoid Minmod<VolumeDim, tmpl::list<Tags...>>::pup(PUP::er& p) noexcept {\n  p | minmod_type_;\n  p | tvb_constant_;\n  p | disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nvoid Minmod<VolumeDim, tmpl::list<Tags...>>::package_data(\n    const gsl::not_null<PackagedData*> packaged_data,\n    const typename Tags::type&... tensors, const Mesh<VolumeDim>& mesh,\n    const std::array<double, VolumeDim>& element_size,\n    const OrientationMap<VolumeDim>& orientation_map) const noexcept {\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not initialize packaged_data\n    return;\n  }\n\n  const auto wrap_compute_means = [&mesh, &packaged_data](\n                                      auto tag, const auto tensor) noexcept {\n    for (size_t i = 0; i < tensor.size(); ++i) {\n      // Compute the mean using the local orientation of the tensor and mesh:\n      // this avoids the work of reorienting the tensor while giving the same\n      // result.\n      get<::Tags::Mean<decltype(tag)>>(packaged_data->means)[i] =\n          mean_value(tensor[i], mesh);\n    }\n    return '0';\n  };\n  expand_pack(wrap_compute_means(Tags{}, tensors)...);\n  packaged_data->element_size =\n      orientation_map.permute_from_neighbor(element_size);\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nbool Minmod<VolumeDim, tmpl::list<Tags...>>::operator()(\n    const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const tnsr::I<DataVector, VolumeDim, Frame::Logical>& logical_coords,\n    const std::array<double, VolumeDim>& element_size,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) const noexcept {\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not modify input tensors\n    return false;\n  }\n\n  DataVector u_lin_buffer(mesh.number_of_grid_points());\n  Minmod_detail::BufferWrapper<VolumeDim> buffer(mesh);\n\n  bool limiter_activated = false;\n  const auto wrap_limit_one_tensor = [this, &limiter_activated, &element, &mesh,\n                                      &logical_coords, &element_size,\n                                      &neighbor_data, &u_lin_buffer, &buffer](\n                                         auto tag, const auto tensor) noexcept {\n    limiter_activated =\n        Minmod_detail::limit_one_tensor<VolumeDim, decltype(tag)>(\n            &u_lin_buffer, &buffer, tensor, minmod_type_, tvb_constant_, mesh,\n            element, logical_coords, element_size, neighbor_data) or\n        limiter_activated;\n    return '0';\n  };\n  expand_pack(wrap_limit_one_tensor(Tags{}, tensors)...);\n  return limiter_activated;\n}\n\ntemplate <size_t LocalDim, typename LocalTagList>\nbool operator==(const Minmod<LocalDim, LocalTagList>& lhs,\n                const Minmod<LocalDim, LocalTagList>& rhs) noexcept {\n  return lhs.minmod_type_ == rhs.minmod_type_ and\n         lhs.tvb_constant_ == rhs.tvb_constant_ and\n         lhs.disable_for_debugging_ == rhs.disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename TagList>\nbool operator!=(const Minmod<VolumeDim, TagList>& lhs,\n                const Minmod<VolumeDim, TagList>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n\n}  // namespace Limiters\n", "meta": {"hexsha": "ab1272385936bb2ee37e131acb12abeb79acbb3d", "size": 7852, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Minmod.tpp", "max_stars_repo_name": "Ambrou/spectre", "max_stars_repo_head_hexsha": "a819ebbcca607d8af9683db3683bea14bf4ac23c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Minmod.tpp", "max_issues_repo_name": "Ambrou/spectre", "max_issues_repo_head_hexsha": "a819ebbcca607d8af9683db3683bea14bf4ac23c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T18:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:30:39.000Z", "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Minmod.tpp", "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": 40.4742268041, "max_line_length": 80, "alphanum_fraction": 0.7161232807, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.03514484501123562, "lm_q1q2_score": 0.014581555122339933}}
{"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\n/** \\file FeSpaceMapping.h */\n\n#ifndef AMDIS_FE_SPACE_MAPPING_H\n#define AMDIS_FE_SPACE_MAPPING_H\n\n#include <mpi.h>\n#include <vector>\n#include <map>\n#include <set>\n#include <boost/container/flat_map.hpp>\n#include <boost/container/flat_set.hpp>\n\n#ifndef HAVE_PARALLEL_MTL4\n#include <petsc.h>\n#include <petscis.h>\n#endif\n\n#include \"AMDiS_fwd.h\"\n#include \"parallel/DofComm.hpp\"\n#include \"parallel/MpiHelper.hpp\"\n#include \"parallel/ParallelTypes.hpp\"\n#include \"parallel/StdMpi.hpp\"\n\nnamespace AMDiS\n{\n  namespace Parallel\n  {\n\n    /** \\brief\n     * Is used to store matrix indices to all DOFs in rank's subdomain. Thus, the\n     * class defines a mapping from component number and DOF index to a global\n     * matrix index. This class does not calculate the indices by itself!\n     */\n    class DofToMatIndex\n    {\n    public:\n      typedef boost::container::flat_map<DegreeOfFreedom, int> MapType;\n\n      DofToMatIndex() {}\n\n      /// Reset the data structure.\n      inline void clear()\n      {\n        data.clear();\n      }\n\n      inline void clear(int component)\n      {\n        data[component].clear();\n      }\n\n      /** Add a new mapping for a given DOF.\n       *\n       * \\param[in]   component       Component number for which the mapping\n       *                              is defined.\n       * \\param[in]   dof             DOF index\n       * \\param[in]   globalMatIndex  Global matrix index.\n       */\n      inline void add(int component, DegreeOfFreedom dof, int globalMatIndex)\n      {\n        data[component][dof] = globalMatIndex;\n      }\n\n      /// Maps a global DOF index to the global matrix index for a specific\n      /// system component number.\n      inline int get(int component, DegreeOfFreedom dof) const\n      {\n        FUNCNAME_DBG(\"DofToMatIndex::get()\");\n\n        std::map<int, MapType>::const_iterator it_component = data.find(component);\n        TEST_EXIT_DBG(it_component != data.end())\n        (\"No mapping data for component %d available!\\n\", component);\n\n        MapType::const_iterator it_dof = (it_component->second).find(dof);\n        TEST_EXIT_DBG(it_dof != (it_component->second).end())\n        (\"Mapping for DOF %d in component %d does not exist!\\n\",\n         dof, component);\n\n        return it_dof->second;\n      }\n\n      /// Returns the number of DOF mappings in one component\n      inline int getSize(int component) const\n      {\n        FUNCNAME_DBG(\"DofToMatIndex::getSize()\");\n\n        std::map<int, MapType>::const_iterator it_component = data.find(component);\n        TEST_EXIT_DBG(it_component != data.end())\n        (\"No mapping data for component %d available!\\n\", component);\n        return (it_component->second).size();\n      }\n\n      /// Returns the whole mapping for one component\n      inline MapType& getData(int component)\n      {\n        FUNCNAME_DBG(\"DofToMatIndex::getData()\");\n\n        std::map<int, MapType>::iterator it_component = data.find(component);\n        TEST_EXIT_DBG(it_component != data.end())\n        (\"No mapping data for component %d available!\\n\", component);\n        return it_component->second;\n      }\n\n      /// Returns for a given matrix index the component and (local or global) DOF\n      /// index. As the data structure is not made for this kind of reverse\n      /// search, this is very slow and should be only used for debugging.\n      void getReverse(int rowIndex, int& component, int& dofIndex) const;\n\n    private:\n      /// The mapping data. For each system component there is a specific map that\n      /// maps global DOF indices to global matrix indices.\n      std::map<int, MapType> data;\n    };\n\n\n    /// This class defines the parallel mapping of DOFs for one FE space. It is\n    /// used by the class \\ref ParallelDofMapping to specifiy the mapping for a\n    /// set of  FE spaces.\n    class ComponentDofMap\n    {\n    public:\n      /// Constructor.\n      ComponentDofMap();\n\n      /// Clears all data of the mapping.\n      void clear();\n\n      /// Maps a DOF index to both, the local and global index of the mapping. The\n      /// global index must not be set.\n      MultiIndex& operator[](DegreeOfFreedom d)\n      {\n        TEST_EXIT_DBG(dofMap.count(d))(\"DOF %d is not in map!\\n\", d);\n\n        return dofMap[d];\n      }\n\n      /** \\brief\n       * Searchs the map for a given DOF. It does not fail, if the DOF is not\n       * mapped by this mapping. In this case, it returns false. If the DOF is\n       * mapped, the result is stored and the function returns true.\n       *\n       * \\param[in]    dof     DOF index for which a mapping is searched.\n       * \\param[out]   index   In the case that the DOF is mapped, the result\n       *                       is stored here.\n       */\n      inline bool find(DegreeOfFreedom dof, MultiIndex& index)\n      {\n        DofMap::iterator it = dofMap.find(dof);\n        if (it == dofMap.end())\n          return false;\n\n        index = it->second;\n        return true;\n      }\n\n      /// Inserts a new DOF to rank's mapping. The DOF is assumed to be owend by\n      /// the rank.\n      inline void insertRankDof(DegreeOfFreedom dof0,\n                                DegreeOfFreedom dof1 = -1)\n      {\n        FUNCNAME(\"ComponentDofMap::insertRankDof()\");\n\n        TEST_EXIT_DBG(dofMap.count(dof0) == 0)\n        (\"DOF %d is already defined in mapping!\\n\", dof0);\n\n        dofMap[dof0].local = dof1;\n        nLocalDofs++;\n        if (dof1 != -1)\n          nRankDofs++;\n      }\n\n      /// Inserts a new DOF to rank's mapping. The DOF exists in rank's subdomain\n      /// but is owned by a different rank, thus it is part of an interior boundary.\n      inline void insertNonRankDof(DegreeOfFreedom dof0,\n                                   DegreeOfFreedom dof1 = -1)\n      {\n        FUNCNAME(\"ComponentDofMap::insertNonRankDof()\");\n\n        TEST_EXIT_DBG(dofMap.count(dof0) == 0)\n        (\"DOF %d is already in mapping!\\n\", dof0);\n\n        dofMap[dof0].local = dof1;\n        nLocalDofs++;\n        nonRankDofs.insert(dof0);\n      }\n\n      /// Checks if a given DOF is in the DOF mapping.\n      bool isSet(DegreeOfFreedom dof)\n      {\n        return static_cast<bool>(dofMap.count(dof));\n      }\n\n      /// Checks if a given DOF is a rank owned DOF of the DOF mapping. The DOF\n      /// must be a DOF of the mapping (this is not checked here), otherwise the\n      /// result is meaningsless.\n      bool isRankDof(DegreeOfFreedom dof)\n      {\n        return !(static_cast<bool>(nonRankDofs.count(dof)));\n      }\n\n      bool isRankGlobalDof(int dof)\n      {\n        return (dof >= rStartDofs && dof < rStartDofs + nRankDofs);\n      }\n\n      /// Returns number of DOFs in the mapping.\n      unsigned int size()\n      {\n        return dofMap.size();\n      }\n\n      /// Returns the raw data of the mapping.\n      DofMap& getMap()\n      {\n        return dofMap;\n      }\n\n      const FiniteElemSpace* getFeSpace() const\n      {\n        return feSpace;\n      }\n\n      const Mesh* getMesh() const\n      {\n        return mesh;\n      }\n\n      DofComm& getDofComm()\n      {\n        FUNCNAME(\"ComponentDofMap::getDofComm()\");\n\n        TEST_EXIT_DBG(dofComm)(\"No DOF communicator object defined!\\n\");\n\n        return *dofComm;\n      }\n\n      DofMap::iterator begin()\n      {\n        return dofMap.begin();\n      }\n\n      DofMap::iterator end()\n      {\n        return dofMap.end();\n      }\n\n      /// Recomputes the mapping.\n      void update();\n\n      /// Sets the FE space this mapping corresponds to.\n      void setFeSpace(const FiniteElemSpace* fe)\n      {\n        feSpace = fe;\n      }\n\n      void setMesh(Mesh* mesh_)\n      {\n        mesh = mesh_;\n      }\n\n      /// Informs the mapping whether a global index must be computed.\n      void setGlobalMapping(bool b)\n      {\n        globalMapping = b;\n      }\n\n      /// Sets the DOF communicator.\n      void setDofComm(DofComm& dc)\n      {\n        dofComm = &dc;\n      }\n\n      void setMpiComm(MPI::Intracomm& m)\n      {\n        mpiComm = m;\n      }\n\n    private:\n      /// Computes a global mapping from the local one.\n      void computeGlobalMapping();\n\n      /// Computes the global indices of all DOFs in the mapping that are not owned\n      /// by the rank.\n      void computeNonLocalIndices();\n\n    private:\n      /// DOF communicator for all DOFs on interior boundaries.\n      DofComm* dofComm;\n\n      MPI::Intracomm mpiComm;\n\n      /// The FE space this mapping belongs to. This is used only the get the\n      /// correct DOF communicator in \\ref dofComm.\n      const FiniteElemSpace* feSpace;\n\n      const Mesh* mesh;\n\n      /// Mapping data from DOF indices to local and global indices.\n      DofMap dofMap;\n\n      /// Set of all DOFs that are in mapping but are not owned by the rank.\n      boost::container::flat_set<DegreeOfFreedom> nonRankDofs;\n\n      /// If true, a global index mapping will be computed for all DOFs.\n      bool globalMapping;\n\n    public:\n      ///\n      int nRankDofs, nLocalDofs, nOverallDofs, rStartDofs;\n    };\n\n\n    /// Abstract iterator interface to access containrs containing values of\n    /// type \\ref ComponentDofMap.\n    class ComponentIterator\n    {\n    public:\n      virtual ComponentDofMap& operator*() = 0;\n\n      virtual ComponentDofMap* operator->() = 0;\n\n      virtual bool end() = 0;\n\n      virtual void next() = 0;\n\n      virtual void reset() = 0;\n    };\n\n\n    /// Abstract interface to acces DOF mapping data for each component. Allows\n    /// to hide specific implementations, which allow, e.g., to efficiently map\n    /// all components having the same FE space to the same DOF mapping.\n    class ComponentDataInterface\n    {\n    public:\n      virtual ~ComponentDataInterface() {};\n      /// Access via component number\n      virtual ComponentDofMap& operator[](int compNumber) = 0;\n\n      /// Acess via FE space pointer\n      virtual ComponentDofMap& operator[](const FiniteElemSpace* feSpace) = 0;\n\n      /// Checks whether the DOF mapping is defined for a specific\n      /// component number.\n      virtual bool isDefinedFor(int compNumber) const = 0;\n\n      /// Returns iterator which iterates over all DOF mappings.\n      virtual ComponentIterator& getIteratorData() = 0;\n\n      /// Returns iterator which iterates over the DOF mappings of all\n      /// components. If the data is defined for each FE space and more than\n      /// one commponent is defined on the same FE space, the iterative will\n      /// also iterative multple times over the same DOF mapping object.\n      virtual ComponentIterator& getIteratorComponent() = 0;\n\n      /** \\brief\n       * Initialization of the object.\n       *\n       * \\param[in]   componentSpaces   Set of the FE spaces for each component.\n       * \\param[in]   feSpaces          Set of all different FE spaces.\n       * \\param[in]   globalMapping     Mapping is parallel (true) or only\n       *                                local (false).\n       */\n      virtual void init(std::vector<const FiniteElemSpace*>& componentSpaces,\n                        std::vector<const FiniteElemSpace*>& feSpaces,\n                        bool globalMapping) = 0;\n\n    protected:\n      /// The FE spaces for all components.\n      std::vector<const FiniteElemSpace*> componentSpaces;\n\n      /// The set of all FE spaces. It uniquly contains all different FE spaces\n      /// from \\ref feSpaces.\n      std::vector<const FiniteElemSpace*> feSpaces;\n    };\n\n\n    /// This class concretizes the interface class \\ref ComponentDataInterface. A\n    /// DOF mapping is implemented for each component.\n    class ComponentData : public ComponentDataInterface\n    {\n    public:\n      ComponentData()\n        : iter(this)\n      {}\n\n      /// Returns DOF mapping for a given component number.\n      ComponentDofMap& operator[](int compNumber)\n      {\n        TEST_EXIT_DBG(componentData.count(compNumber))\n        (\"No data for component %d!\\n\", compNumber);\n\n        return componentData.find(compNumber)->second;\n      }\n\n      /// Just to implement the corresponding virtual function in \\ref\n      /// ComponentDataInterface. Of course it does not work as we have data for\n      /// each component. Thus there may be different mappings for the same\n      /// FE space.\n      ComponentDofMap& operator[](const FiniteElemSpace* feSpace)\n      {\n        ERROR_EXIT(\"FE Space access is not possible for component wise defined DOF mappings\\n\");\n        return componentData.find(0)->second;\n      }\n\n      /// Return data iterator.\n      ComponentIterator& getIteratorData()\n      {\n        iter.reset();\n        return iter;\n      }\n\n      /// Return component iterator.\n      ComponentIterator& getIteratorComponent()\n      {\n        iter.reset();\n        return iter;\n      }\n\n      /// Checks whether the DOF mapping is defined for a specific\n      /// component number.\n      bool isDefinedFor(int compNumber) const\n      {\n        return (static_cast<unsigned int>(compNumber) < componentData.size());\n      }\n\n      /// Initialization\n      void init(std::vector<const FiniteElemSpace*>& f0,\n                std::vector<const FiniteElemSpace*>& f1,\n                bool globalMapping);\n\n    protected:\n\n      /// Iterator class to iterate over all parallel DOF mappings.\n      class Iterator : public ComponentIterator\n      {\n      public:\n        Iterator(ComponentData* d)\n          : data(d),\n            componentCounter(-1)\n        {}\n\n        ComponentDofMap& operator*()\n        {\n          return (*data)[componentCounter];\n        }\n\n        ComponentDofMap* operator->()\n        {\n          return &((*data)[componentCounter]);\n        }\n\n\n        bool end()\n        {\n          return (it == data->componentSpaces.end());\n        }\n\n        void next()\n        {\n          ++it;\n          ++componentCounter;\n\n          if (it == data->componentSpaces.end())\n            componentCounter = -1;\n        }\n\n        void reset()\n        {\n          it = data->componentSpaces.begin();\n          componentCounter = 0;\n        }\n\n      protected:\n        /// Pointer to data class over which the iterator must iterate.\n        ComponentData* data;\n\n        /// Internal iterator of the internal data from \\ref ComponentData.\n        std::vector<const FiniteElemSpace*>::iterator it;\n\n        /// Component number of current iteration.\n        int componentCounter;\n      };\n\n\n      /// Data mapping from component numbers to DOF mapping objects.\n      std::map<unsigned int, ComponentDofMap> componentData;\n\n      /// Iterator object.\n      Iterator iter;\n\n\n\n      friend class Iterator;\n    };\n\n\n\n    /// This class concretizes the interface class \\ref ComponentDataInterface. A\n    /// DOF mapping is implemented for each finite element space. Thus, different\n    /// components sharing the same FE space are handled by the same DOF mapping.\n    class FeSpaceData : public ComponentDataInterface\n    {\n    public:\n      FeSpaceData()\n        : iterData(this),\n          iterComponent(this)\n      {}\n\n      /// Returns DOF mapping for a given component number.\n      ComponentDofMap& operator[](int compNumber)\n      {\n        const FiniteElemSpace* feSpace = componentSpaces[compNumber];\n        return componentData.find(feSpace)->second;\n      }\n\n      /// Returns DOF mapping for a given FE space.\n      ComponentDofMap& operator[](const FiniteElemSpace* feSpace)\n      {\n        TEST_EXIT_DBG(componentData.count(feSpace))(\"No data for FE space!\\n\");;\n\n        return componentData.find(feSpace)->second;\n      }\n\n      /// Checks whether the DOF mapping is defined for a specific\n      /// component number.\n      bool isDefinedFor(int compNumber) const\n      {\n        const FiniteElemSpace* feSpace = componentSpaces[compNumber];\n        return static_cast<bool>(componentData.count(feSpace));\n      }\n\n      /// Return data iterator.\n      ComponentIterator& getIteratorData()\n      {\n        iterData.reset();\n        return iterData;\n      }\n\n      /// Return component iterator.\n      ComponentIterator& getIteratorComponent()\n      {\n        iterComponent.reset();\n        return iterComponent;\n      }\n\n      /// Initialization\n      void init(std::vector<const FiniteElemSpace*>& f0,\n                std::vector<const FiniteElemSpace*>& f1,\n                bool globalMapping);\n\n\n    protected:\n\n      /// Iterator class to iterate over all parallel DOF mappings.\n      class IteratorData : public ComponentIterator\n      {\n      public:\n        IteratorData(FeSpaceData* d)\n          : data(d)\n        {}\n\n        ComponentDofMap& operator*()\n        {\n          return (*data)[*it];\n        }\n\n        ComponentDofMap* operator->()\n        {\n          return &((*data)[*it]);\n        }\n\n        bool end()\n        {\n          return (it == data->feSpaces.end());\n        }\n\n        void next()\n        {\n          ++it;\n        }\n\n        void reset()\n        {\n          it = data->feSpaces.begin();\n        }\n\n      protected:\n        FeSpaceData* data;\n\n        std::vector<const FiniteElemSpace*>::iterator it;\n      };\n\n\n      /// Iterator class to iterate over all component DOF mappings.\n      class IteratorComponent : public ComponentIterator\n      {\n      public:\n        IteratorComponent(FeSpaceData* d)\n          : data(d)\n        {}\n\n        ComponentDofMap& operator*()\n        {\n          return (*data)[*it];\n        }\n\n        ComponentDofMap* operator->()\n        {\n          return &((*data)[*it]);\n        }\n\n        bool end()\n        {\n          return (it == data->componentSpaces.end());\n        }\n\n        void next()\n        {\n          ++it;\n        }\n\n        void reset()\n        {\n          it = data->componentSpaces.begin();\n        }\n\n      protected:\n        FeSpaceData* data;\n\n        std::vector<const FiniteElemSpace*>::iterator it;\n      };\n\n\n      std::map<const FiniteElemSpace*, ComponentDofMap> componentData;\n\n      IteratorData iterData;\n\n      IteratorComponent iterComponent;\n\n      friend class IteratorData;\n\n      friend class IteratorComponent;\n    };\n\n\n\n    /// Used to specify whether a parallel DOF mapping is defined for each\n    /// specific component or for each FE space.\n    enum DofMappingMode\n    {\n      COMPONENT_WISE,\n      FESPACE_WISE\n    };\n\n    /**\n     * Implements the mapping from sets of distributed DOF indices to local and\n     * global indices. The mapping works for a given set of FE spaces. Furthermore,\n     * this class may compute the matrix indices of the set of DOF indices.\n     */\n    class ParallelDofMapping\n    {\n    public:\n      /** \\brief\n       * Constructur for parallel DOF mapping.\n       *\n       * \\param[in]  mode            Defines if DOF mapping is defined either per\n       *                             component or per FE space.\n       * \\param[in]  matIndexGlobal  If true, the mat index is defined on global\n       *                             DOF indices, otherwise on local ones.\n       */\n      ParallelDofMapping(DofMappingMode mode,\n                         bool matIndexFromGlobal = false);\n\n      ~ParallelDofMapping()\n      {\n        if (data)\n          delete data;\n        data = NULL;\n      }\n\n      /** \\brief\n       * Initialize the parallel DOF mapping.\n       *\n       * \\param[in]  componentSpaces    The FE spaces of all components of the\n       *                                PDE to be solved.\n       * \\param[in]  feSpaces           Unique list of FE spaces. Thus, two\n       *                                arbitrary elements of this list are always\n       *                                different.\n       * \\param[in]  globalMapping      If true, at least one rank's mapping con-\n       *                                taines DOFs that are not owend by the rank.\n       */\n      void init(std::vector<const FiniteElemSpace*>& componentSpaces,\n                std::vector<const FiniteElemSpace*>& feSpaces,\n                bool globalMapping = true);\n\n      /// In the case of having only one FE space, this init function can be used.\n      void init(const FiniteElemSpace* feSpace,\n                bool globalMapping = true)\n      {\n        std::vector<const FiniteElemSpace*> feSpaces;\n        feSpaces.push_back(feSpace);\n        init(feSpaces, feSpaces, globalMapping);\n      }\n\n      void setMpiComm(MPI::Intracomm& m);\n\n      inline MPI::Intracomm& getMpiComm()\n      {\n        return mpiComm;\n      }\n\n      /// Clear all data.\n      void clear(Mesh* mesh = NULL);\n\n      /// Set the DOF communicator objects that are required to exchange information\n      /// about DOFs that are on interior boundaries.\n\n      void setDofComms(std::map<Mesh*, MultiLevelDofComm>& dofComms, int level);\n\n      /// Returns the DOF communicator.\n      DofComm& getDofComm(const FiniteElemSpace* feSpace)\n      {\n        return (*data)[feSpace].getDofComm();\n      }\n\n      inline bool isMatIndexFromGlobal()\n      {\n        return needMatIndexFromGlobal;\n      }\n\n      /// Access the DOF mapping for a given component number.\n      inline ComponentDofMap& operator[](int compNumber)\n      {\n        return (*data)[compNumber];\n      }\n\n      /// Access the DOF mapping for a given FE space\n      inline ComponentDofMap& operator[](const FiniteElemSpace* feSpace)\n      {\n        return (*data)[feSpace];\n      }\n\n      /// Checks whether the DOF mapping is defined for a specific\n      /// component number.\n      inline bool isDefinedFor(int compNumber) const\n      {\n        return data->isDefinedFor(compNumber);\n      }\n\n      /// Returns the number of solution components the mapping is defined on.\n      inline int getNumberOfComponents() const\n      {\n        return static_cast<int>(componentSpaces.size());\n      }\n\n      /// Returns \\ref nRankDofs, thus the number of DOFs owned by the rank.\n      inline int getRankDofs() const\n      {\n        TEST_EXIT_DBG(nRankDofs >= 0)(\"Should not happen!\\n\");\n\n        return nRankDofs;\n      }\n\n      inline int getRankDofs(int component) const\n      {\n        int nDofs = (*data)[component].nRankDofs;\n        TEST_EXIT_DBG(nDofs >= 0)(\"Should not happen!\\n\");\n\n        return nDofs;\n      }\n\n      /// Returns \\ref nLocalDofs, thus the number of DOFs in ranks subdomain.\n      inline int getLocalDofs() const\n      {\n        TEST_EXIT_DBG(nLocalDofs >= 0)(\"Should not happen!\\n\");\n\n        return nLocalDofs;\n      }\n\n      inline int getLocalDofs(int component) const\n      {\n        int nDofs = (*data)[component].nLocalDofs;\n        TEST_EXIT_DBG(nDofs >= 0)(\"Should not happen!\\n\");\n\n        return nDofs;\n      }\n\n      /// Returns \\ref nOverallDofs, thus the number of all DOFs in this mapping.\n      inline int getOverallDofs() const\n      {\n        TEST_EXIT_DBG(nOverallDofs >= 0)(\"Should not happen!\\n\");\n\n        return nOverallDofs;\n      }\n\n      inline int getOverallDofs(int component) const\n      {\n        int nDofs = (*data)[component].nOverallDofs;\n        TEST_EXIT_DBG(nDofs >= 0)(\"Should not happen!\\n\");\n\n        return nDofs;\n      }\n\n      /// Returns \\ref rStartDofs, thus the smallest global index of a DOF that is\n      /// owned by the rank.\n      inline int getStartDofs() const\n      {\n        TEST_EXIT_DBG(rStartDofs >= 0)(\"Should not happen!\\n\");\n\n        return rStartDofs;\n      }\n\n      inline int getStartDofs(int component) const\n      {\n        int nDofs = (*data)[component].rStartDofs;\n        TEST_EXIT_DBG(nDofs >= 0)(\"Should not happen!\\n\");\n\n        return nDofs;\n      }\n\n      /// Update the mapping.\n      void update(Mesh* mesh = NULL);\n\n      /// Updates only the DOF to matrix index mapping\n      void updateMatIndex();\n\n      inline DofToMatIndex::MapType& getMatData(int component)\n      {\n        return dofToMatIndex.getData(component);\n      }\n\n      /// Returns the global matrix index of a given DOF for a given\n      /// component number.\n      inline int getMatIndex(int ithComponent, DegreeOfFreedom d) const\n      {\n        return dofToMatIndex.get(ithComponent, d);\n      }\n\n      /// Returns the component number and local/global DOF index for a given\n      /// matrix row index. Should be used for debugging only!\n      inline void getReverseMatIndex(int index, int& component, int& dofIndex) const\n      {\n        dofToMatIndex.getReverse(index, component, dofIndex);\n      }\n\n      /// Returns the local matrix index of a given DOF for a given\n      /// component number.\n      inline int getLocalMatIndex(int ithComponent, DegreeOfFreedom d) const\n      {\n        return dofToMatIndex.get(ithComponent, d) - rStartDofs;\n      }\n\n      /// Returns the set of unique FE spaces.\n      std::vector<const FiniteElemSpace*> getFeSpaces(Mesh* mesh = NULL)\n      {\n        if (!mesh)\n          return feSpaces;\n\n        std::vector<const FiniteElemSpace*> thisMeshSpaces;\n        for (size_t i = 0; i < feSpaces.size(); i++)\n          if (feSpaces[i]->getMesh() == mesh)\n            thisMeshSpaces.push_back(feSpaces[i]);\n        return thisMeshSpaces;\n      }\n\n      bool hasFeSpace(const FiniteElemSpace* feSpace)\n      {\n        return (std::find(feSpaces.begin(), feSpaces.end(), feSpace)\n                != feSpaces.end());\n      }\n\n      // Writes all data of this object to an output stream.\n      void serialize(std::ostream& out)\n      {\n        ERROR_EXIT(\"MUST BE IMPLEMENTED!\\n\");\n      }\n\n      // Reads the object data from an input stream.\n      void deserialize(std::istream& in)\n      {\n        ERROR_EXIT(\"MUST BE IMPLEMENTED!\\n\");\n      }\n\n      /// Compute local and global matrix indices.\n      void computeMatIndex(bool globalIndex);\n\n#ifndef HAVE_PARALLEL_MTL4\n      void createIndexSet(IS& is,\n                          int firstComponent,\n                          int nComponents);\n#endif\n\n      /// Prints out some information about the mapping. May be used during\n      /// debugging or parallel solver creation.\n      void printInfo();\n\n    protected:\n      /// Compute \\ref nRankDofs.\n      int computeRankDofs();\n\n      /// Compute \\ref nLocalDofs.\n      int computeLocalDofs();\n\n      /// Compute \\ref nOverallDofs.\n      int computeOverallDofs();\n\n      /// Compute \\ref rStartDofs.\n      int computeStartDofs();\n\n    private:\n      MPI::Intracomm mpiComm;\n\n      /// Is true if there are DOFs in at least one subdomain that are not owned\n      /// by the rank. If the value is false, each rank contains only DOFs that\n      /// are also owned by this rank.\n      bool globalMapping;\n\n      /// If matrix indices should be computed, this variable defines if the\n      /// mapping from DOF indices to matrix row indices is defined on local\n      /// or global DOF indices. If true, the mapping is to specify and to use\n      /// on global ones, otherwise on local DOF indices.\n      /// In most scenarios the mapping stored on local DOF indices is what we\n      /// want to have. Only when periodic boundary conditions are used together\n      /// with some global matrix approach, the matrix indices must be stored\n      /// also for DOFs that are not part of the local subdomain. Thus, the\n      /// mapping will be stored on global DOF indices.\n      bool needMatIndexFromGlobal;\n\n      /// Maps from components to DOF mappings.\n      ComponentDataInterface* data;\n\n      /// Number of DOFs owned by rank.\n      int nRankDofs;\n\n      /// Number of DOFs in rank's subdomain.\n      int nLocalDofs;\n\n      /// Number of global DOFs (this value is thus the same on all ranks).\n      int nOverallDofs;\n\n      /// Smallest global index of a DOF owned by the rank.\n      int rStartDofs;\n\n      /// Mapping from global DOF indices to global matrix indices under\n      /// consideration of possibly multiple components.\n      DofToMatIndex dofToMatIndex;\n\n      /// FE spaces of all components.\n      std::vector<const FiniteElemSpace*> componentSpaces;\n\n      /// Set of unique FE spaces.\n      std::vector<const FiniteElemSpace*> feSpaces;\n\n      /// Defines the DOF mapping either. The mapping may be defined either for\n      /// FE spaces or for component numbers.\n      DofMappingMode mode;\n    };\n  }\n}\n\n#endif\n", "meta": {"hexsha": "0535f26e841116cd92cc13727047b39d2ef6afd9", "size": 28547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/parallel/ParallelDofMapping.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "src/parallel/ParallelDofMapping.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parallel/ParallelDofMapping.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": 28.9817258883, "max_line_length": 96, "alphanum_fraction": 0.5988370056, "num_tokens": 6493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.0474258736824553, "lm_q1q2_score": 0.014576722483141968}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <array>\n#include <chrono>\n#include <iostream>\n#include <memory>\n#include <tuple>\n\n// This is a base class for turning a bilinear form into an Eigen matvec.\nnamespace spacetime {\ntemplate <typename DblVecIn, typename DblVecOut = DblVecIn>\nclass BilinearFormBase;\n}\n\n// Define a necessary Eigen trait.\nnamespace Eigen {\nnamespace internal {\ntemplate <typename DblVecIn, typename DblVecOut>\nstruct traits<spacetime::BilinearFormBase<DblVecIn, DblVecOut>>\n    : public Eigen::internal::traits<Eigen::SparseMatrix<double>> {};\n}  // namespace internal\n}  // namespace Eigen\n\nnamespace spacetime {\ntemplate <typename DblVecInType, typename DblVecOutType>\nclass BilinearFormBase\n    : public Eigen::EigenBase<BilinearFormBase<DblVecInType, DblVecOutType>> {\n public:\n  using DblVecIn = DblVecInType;\n  using DblVecOut = DblVecOutType;\n  virtual ~BilinearFormBase() {}\n\n  // These are the BilinearForm functions that must be implemented.\n  virtual Eigen::VectorXd Apply(const Eigen::VectorXd &v) { assert(false); }\n  virtual DblVecIn *vec_in() const { assert(false); }\n  virtual DblVecOut *vec_out() const { assert(false); }\n\n  // These are the functions that must be implemented for Eigen to work.\n  Eigen::Index rows() const { return vec_out()->container().size(); }\n  Eigen::Index cols() const { return vec_in()->container().size(); }\n\n  // Eigen related stuff.\n  using Scalar = double;\n  using RealScalar = double;\n  using StorageIndex = int;\n  enum {\n    ColsAtCompileTime = Eigen::Dynamic,\n    MaxColsAtCompileTime = Eigen::Dynamic,\n    IsRowMajor = false\n  };\n\n  template <typename Rhs>\n  Eigen::VectorXd operator*(const Eigen::MatrixBase<Rhs> &x) const {\n    return const_cast<BilinearFormBase *>(this)->Apply(x);\n  }\n\n  double TimeApply() const { return time_apply_.count(); };\n  double TimePerApply() const {\n    if (num_apply_ == 0) return 0;\n    return time_apply_.count() / num_apply_;\n  };\n  double TimeConstruct() const { return time_construct_.count(); }\n\n protected:\n  // Timing debug information.\n  std::chrono::duration<double> time_construct_{0};\n  std::chrono::duration<double> time_apply_{0};\n  size_t num_apply_ = 0;\n};\n\n// This class represents the adjoint of a bilinear form.\ntemplate <typename BilForm>\nclass TransposeBilinearForm\n    : public BilinearFormBase<typename BilForm::DblVecOut,\n                              typename BilForm::DblVecIn> {\n public:\n  using DblVecIn = typename BilForm::DblVecOut;\n  using DblVecOut = typename BilForm::DblVecIn;\n\n  TransposeBilinearForm(std::shared_ptr<BilForm> bil_form)\n      : bil_form_(bil_form) {}\n\n  Eigen::VectorXd Apply(const Eigen::VectorXd &v) final {\n    // Debug information.\n    auto time_start = std::chrono::steady_clock::now();\n    num_apply_++;\n\n    Eigen::VectorXd result = bil_form_->ApplyTranspose(v);\n\n    // Store timing results.\n    time_apply_ += std::chrono::duration<double>(\n        std::chrono::steady_clock::now() - time_start);\n\n    return result;\n  }\n\n  DblVecIn *vec_in() const final { return bil_form_->vec_out(); }\n  DblVecOut *vec_out() const final { return bil_form_->vec_in(); }\n\n  auto Transpose() { return bil_form_; }\n\n protected:\n  std::shared_ptr<BilForm> bil_form_;\n\n  using BilinearFormBase<DblVecIn, DblVecOut>::time_apply_;\n  using BilinearFormBase<DblVecIn, DblVecOut>::num_apply_;\n};\n\n// This class represents the sum of two bilinear forms.\ntemplate <typename BilFormA, typename BilFormB>\nclass SumBilinearForm : public BilinearFormBase<typename BilFormA::DblVecIn,\n                                                typename BilFormA::DblVecOut> {\n public:\n  using DblVecIn = typename BilFormA::DblVecIn;\n  using DblVecOut = typename BilFormA::DblVecOut;\n\n  SumBilinearForm(std::shared_ptr<BilFormA> a, std::shared_ptr<BilFormB> b)\n      : a_(a), b_(b) {\n    assert(a->vec_in() == b->vec_in());\n    assert(a->vec_out() == b->vec_out());\n  }\n\n  Eigen::VectorXd Apply(const Eigen::VectorXd &v) final {\n    // Debug information.\n    auto time_start = std::chrono::steady_clock::now();\n    num_apply_++;\n\n    Eigen::VectorXd result = a_->Apply(v) + b_->Apply(v);\n\n    // Store timing results.\n    time_apply_ += std::chrono::duration<double>(\n        std::chrono::steady_clock::now() - time_start);\n\n    return result;\n  }\n  DblVecIn *vec_in() const final { return a_->vec_in(); }\n  DblVecOut *vec_out() const final { return a_->vec_out(); }\n  auto sigma() { return a_->sigma(); }\n  auto theta() { return a_->theta(); }\n\n  auto Transpose() {\n    auto a_t = a_->Transpose();\n    auto b_t = b_->Transpose();\n    return std::make_shared<\n        SumBilinearForm<typename decltype(a_t)::element_type,\n                        typename decltype(b_t)::element_type>>(a_t, b_t);\n  }\n\n protected:\n  std::shared_ptr<BilFormA> a_;\n  std::shared_ptr<BilFormB> b_;\n\n  using BilinearFormBase<DblVecIn, DblVecOut>::time_apply_;\n  using BilinearFormBase<DblVecIn, DblVecOut>::num_apply_;\n};\n\n// This class represents a negative bilinear form (-BilForm).\ntemplate <typename BilForm>\nclass NegativeBilinearForm\n    : public BilinearFormBase<typename BilForm::DblVecIn,\n                              typename BilForm::DblVecOut> {\n public:\n  using DblVecIn = typename BilForm::DblVecIn;\n  using DblVecOut = typename BilForm::DblVecOut;\n  NegativeBilinearForm(std::shared_ptr<BilForm> bil_form)\n      : bil_form_(bil_form) {}\n\n  Eigen::VectorXd Apply(const Eigen::VectorXd &v) final {\n    return -bil_form_->Apply(v);\n  }\n  DblVecIn *vec_in() const final { return bil_form_->vec_in(); }\n  DblVecOut *vec_out() const final { return bil_form_->vec_out(); }\n\n  auto Transpose() {\n    auto b_t = bil_form_->Transpose();\n    return std::make_shared<\n        NegativeBilinearForm<typename decltype(b_t)::element_type>>(bil_form_);\n  }\n\n protected:\n  std::shared_ptr<BilForm> bil_form_;\n};\n\n/**\n * The Schur complement operator for the matrix [A B; B^t G].\n * x \\mapsto (B.T A^{-1} B + G) x.\n */\ntemplate <typename Ainv, typename B, typename BT, typename G>\nclass SchurBilinearForm\n    : public BilinearFormBase<typename B::DblVecIn, typename BT::DblVecOut> {\n public:\n  using DblVecIn = typename B::DblVecIn;\n  using DblVecOut = typename BT::DblVecOut;\n  SchurBilinearForm(std::shared_ptr<Ainv> a_inv, std::shared_ptr<B> b,\n                    std::shared_ptr<BT> bt, std::shared_ptr<G> g)\n      : a_inv_(a_inv), b_(b), bt_(bt), g_(g) {\n    assert(b_->vec_in() == g_->vec_in());\n    assert(a_inv_->vec_in() == b_->vec_out());\n    assert(bt_->vec_in() == a_inv_->vec_out());\n    assert(bt_->vec_out() == g_->vec_out());\n  }\n\n  Eigen::VectorXd Apply(const Eigen::VectorXd &v) final {\n    // Debug information.\n    auto time_start = std::chrono::steady_clock::now();\n    num_apply_++;\n\n    Eigen::VectorXd result;\n    result = b_->Apply(v);\n    result = a_inv_->Apply(result);\n    result = bt_->Apply(result);\n\n    result += g_->Apply(v);\n\n    // Store timing results.\n    time_apply_ += std::chrono::duration<double>(\n        std::chrono::steady_clock::now() - time_start);\n\n    return result;\n  }\n\n  DblVecIn *vec_in() const final { return b_->vec_in(); }\n  DblVecOut *vec_out() const final { return bt_->vec_out(); }\n\n protected:\n  std::shared_ptr<Ainv> a_inv_;\n  std::shared_ptr<B> b_;\n  std::shared_ptr<BT> bt_;\n  std::shared_ptr<G> g_;\n\n  using BilinearFormBase<DblVecIn, DblVecOut>::time_apply_;\n  using BilinearFormBase<DblVecIn, DblVecOut>::num_apply_;\n};\n}  // namespace spacetime\n", "meta": {"hexsha": "0d5197c12adefe7b70cec6fe57dd019cc8470fd1", "size": 7432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spacetime/bilinear_form_linalg.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/spacetime/bilinear_form_linalg.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/spacetime/bilinear_form_linalg.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": 31.4915254237, "max_line_length": 79, "alphanum_fraction": 0.6851453175, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.03676946502007582, "lm_q1q2_score": 0.01456321510961306}}
{"text": "/*\n*\nCOPYRIGHT AND LICENSE\n\nCopyright (c) 2011 The Regents of the University of California.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or\nwithout modification, are permitted provided that the following\nconditions are met:\n\n1. Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following\ndisclaimer in the documentation and/or other materials provided\nwith the distribution.\n\n3. All advertising materials mentioning features or use of this\nsoftware must display the following acknowledgement: This product\nincludes software developed by the San Diego Supercomputer Center.\n\n4. Neither the names of the Centers nor the names of the contributors\nmay be used to endorse or promote products derived from this\nsoftware without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS\nOR 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\nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\nAND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\nANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n*\n*\n* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)\n* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)\n*\n*/\n\n#include <points2grid/config.h>\n#include <points2grid/Interpolation.hpp>\n#include <points2grid/Global.hpp>\n\n#include <string.h>\n#include <math.h>\n#include <float.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n\n#include <points2grid/lasfile.hpp>\n\n#include <boost/scoped_ptr.hpp>\n\n\n#include <fstream>  // std::ifstream\n#include <iostream> // std::cerr\n#include <string.h>\n\n/////////////////////////////////////////////////////////////\n// Public Methods\n/////////////////////////////////////////////////////////////\n\nInterpolation::Interpolation(double x_dist, double y_dist, double radius,\n                             int _window_size, int _interpolation_mode = INTERP_AUTO) : GRID_DIST_X (x_dist), GRID_DIST_Y(y_dist),\n                                                                                        filter_returns(false), keep_first_return(false), interp(NULL)\n{\n    las_point_count = 0;\n\n    data_count = 0;\n    radius_sqr = radius * radius;\n    window_size = _window_size;\n    interpolation_mode = _interpolation_mode;\n\n    min_x = DBL_MAX;\n    min_y = DBL_MAX;\n\n    max_x = -DBL_MAX;\n    max_y = -DBL_MAX;\n}\n\nInterpolation::~Interpolation()\n{\n    delete interp;\n}\n\nint Interpolation::init(const std::string& inputName, int inputFormat)\n{\n    //unsigned int i;\n\n    //struct tms tbuf;\n    clock_t t0, t1;\n\n\n    //////////////////////////////////////////////////////////////////////\n    // MIN/MAX SEARCHING\n    // TODO: the size of data, min, max of each coordinate\n    //       are required to implement streaming processing....\n    //\n    // This code can be eliminated if database can provide these values\n    //////////////////////////////////////////////////////////////////////\n\n    //t0 = times(&tbuf);\n    t0 = clock();\n\n    printf(\"inputName: '%s'\\n\", inputName.c_str());\n\n    if (inputFormat == INPUT_ASCII) {\n        FILE *fp;\n        char line[1024];\n        double data_x, data_y;\n        //double data_z;\n\n        if((fp = fopen(inputName.c_str(), \"r\")) == NULL)\n        {\n            cerr << \"file open error\" << endl;\n            return -1;\n        }\n\n        // throw the first line away - it contains the header\n        fgets(line, sizeof(line), fp);\n\n        // read the data points to find min and max values\n        while(fgets(line, sizeof(line), fp) != NULL)\n        {\n            data_x = atof(strtok(line, \",\\n\"));\n            if(min_x > data_x) min_x = data_x;\n            if(max_x < data_x) max_x = data_x;\n\n            data_y = atof(strtok(NULL, \",\\n\"));\n            if(min_y > data_y) min_y = data_y;\n            if(max_y < data_y) max_y = data_y;\n\n            data_count++;\n\n\n            /*\n            // tokenizing\n            string strLine(line);\n\n            // first token\n            string::size_type pos = strLine.find_first_of(\",\",0);\n            string::size_type lastPos = strLine.find_first_not_of(\",\",0);\n\n            string strX = strLine.substr(lastPos, pos - lastPos);\n\n            // second token\n            lastPos = strLine.find_first_not_of(\",\", pos);\n            pos = strLine.find_first_of(\",\", lastPos);\n\n            string strY = strLine.substr(lastPos, pos - lastPos);\n\n            // third token\n            lastPos = strLine.find_first_not_of(\",\", pos);\n            pos = strLine.find_first_of(\"\\n\", lastPos);\n\n            string strZ = strLine.substr(lastPos, pos - lastPos);\n\n            // data conversion\n            arrX[data_count] = atof(strX.c_str());\n            if(min_x > arrX[data_count]) min_x = arrX[data_count];\n            if(max_x < arrX[data_count]) max_x = arrX[data_count];\n\n            arrY[data_count] = atof(strY.c_str());\n            if(min_y > arrY[data_count]) min_y = arrY[data_count];\n            if(max_y < arrY[data_count]) max_y = arrY[data_count];\n\n            arrZ[data_count++] = atof(strZ.c_str());\n            */\n        }\n\n        fclose(fp);\n    } else { // las input\n\n        las_file las;\n        las.open(inputName);\n\n        min_x = las.minimums()[0];\n        min_y = las.minimums()[1];\n        max_x = las.maximums()[0];\n        max_y = las.maximums()[1];\n        data_count = las.points_count();\n        \n        las.close();\n\n    }\n\n    t1 = clock();\n    printf(\"Min/Max searching time: %10.2f\\n\", (double)(t1 - t0)/CLOCKS_PER_SEC);\n\n\n    //t0 = times(&tbuf);\n\n    //////////////////////////////////////////////////////////////////////\n    // Intialization Step excluding min/max searching\n    //////////////////////////////////////////////////////////////////////\n    /*\n      for(i = 0; i < data_count; i++)\n      {\n      arrX[i] -= min_x;\n      arrY[i] -= min_y;\n      //printf(\"%f,%f,%f\\n\", arrX[i] , arrY[i] ,arrZ[i]);\n      }\n    */\n\n    cerr << \"min_x: \" << min_x << \", max_x: \" << max_x << \", min_y: \" << min_y << \", max_y: \" << max_y << endl;\n\n    GRID_SIZE_X = (int)(ceil((max_x - min_x)/GRID_DIST_X)) + 1;\n    GRID_SIZE_Y = (int)(ceil((max_y - min_y)/GRID_DIST_Y)) + 1;\n\n    cerr << \"GRID_SIZE_X \" << GRID_SIZE_X << endl;\n    cerr << \"GRID_SIZE_Y \" << GRID_SIZE_Y << endl;\n\n    if (interpolation_mode == INTERP_AUTO) {\n        // if the size is too big to fit in memory,\n        // then construct out-of-core structure\n        if(GRID_SIZE_X * GRID_SIZE_Y > MEM_LIMIT) {\n            interpolation_mode= INTERP_OUTCORE;\n        } else {\n            interpolation_mode = INTERP_INCORE;\n        }\n    }\n\n    if (interpolation_mode == INTERP_OUTCORE) {\n        cerr << \"Using out of core interp code\" << endl;;\n\n        interp = new OutCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);\n        if(interp == NULL)\n        {\n            cerr << \"OutCoreInterp construction error\" << endl;\n            return -1;\n        }\n\n        cerr << \"Interpolation uses out-of-core algorithm\" << endl;\n\n    } else {\n        cerr << \"Using incore interp code\" << endl;\n\n        interp = new InCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);\n\n        cerr << \"Interpolation uses in-core algorithm\" << endl;\n    }\n\n    if(interp->init() < 0)\n    {\n        cerr << \"inter->init() error\" << endl;\n        return -1;\n    }\n\n    cerr << \"Interpolation::init() done successfully\" << endl;\n\n    return 0;\n}\n\nint Interpolation::init(const std::string& inputName, double n, double s, double e, double w)\n{\n    printf(\"inputName: '%s'\\n\", inputName.c_str());\n    printf(\"Grid Bounds:\\nNorth: %f\\nSouth: %f\\nEast: %f\\nWest: %f\\n\", n, s, e, w);\n\n    // Check that the bounding box is properly defined\n    if (n-s >= GRID_DIST_Y && e-w >= GRID_DIST_X)\n    {\n        // The user defines the edges of the bounding box, here we want the min/max values\n        // to represent the centers of the edge cells\n        min_x = w + GRID_DIST_X/2.0;\n        min_y = s + GRID_DIST_Y/2.0;\n        max_x = e - GRID_DIST_X/2.0;\n        max_y = n - GRID_DIST_Y/2.0;\n\n    } else {\n        cerr << \"Error in bounding box definition\" << endl;\n        return -1;\n    }\n\n    GRID_SIZE_X = (int)(ceil((max_x - min_x)/GRID_DIST_X)) + 1;\n    GRID_SIZE_Y = (int)(ceil((max_y - min_y)/GRID_DIST_Y)) + 1;\n\n    cerr << \"GRID_SIZE_X \" << GRID_SIZE_X << endl;\n    cerr << \"GRID_SIZE_Y \" << GRID_SIZE_Y << endl;\n\n    if (interpolation_mode == INTERP_AUTO) {\n        // if the size is too big to fit in memory,\n        // then construct out-of-core structure\n        if(GRID_SIZE_X * GRID_SIZE_Y > MEM_LIMIT) {\n            interpolation_mode= INTERP_OUTCORE;\n        } else {\n            interpolation_mode = INTERP_INCORE;\n        }\n    }\n\n    if (interpolation_mode == INTERP_OUTCORE) {\n        cerr << \"Using out of core interp code\" << endl;;\n\n        OutCoreInterp *ointerp = new OutCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);\n        if(ointerp == NULL)\n        {\n            cerr << \"OutCoreInterp construction error\" << endl;\n            return -1;\n        }\n        ointerp->isUserDefinedGrid(true);\n        interp = ointerp;\n\n        cerr << \"Interpolation uses out-of-core algorithm\" << endl;\n\n    } else {\n        cerr << \"Using incore interp code\" << endl;\n\n        interp = new InCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);\n\n        cerr << \"Interpolation uses in-core algorithm\" << endl;\n    }\n\n    if(interp->init() < 0)\n    {\n        cerr << \"inter->init() error\" << endl;\n        return -1;\n    }\n\n    cerr << \"Interpolation::init() done successfully\" << endl;\n\n    return 0;\n}\n\nint Interpolation::interpolation(const std::string& inputName,\n                                 const std::string& outputName,\n                                 int inputFormat,\n                                 int outputFormat,\n                                 unsigned int outputType)\n{\n    int rc;\n    //unsigned int i;\n    double data_x, data_y;\n    double data_z;\n    int data_class, data_return_number, data_max_return;\n\n    //struct tms tbuf;\n    //clock_t t0, t1;\n\n    printf(\"Interpolation Starts\\n\");\n\n    //t0 = times(&tbuf);\n\n    //cerr << \"data_count: \" << data_count << endl;\n\n    /*\n      if((rc = interp->init()) < 0)\n      {\n      cerr << \"inter->init() error\" << endl;\n      return -1;\n      }\n    */\n\n    if (inputFormat == INPUT_ASCII) {\n        FILE *fp;\n        char line[1024];\n\n        if((fp = fopen(inputName.c_str(), \"r\")) == NULL)\n        {\n            printf(\"file open error\\n\");\n            return -1;\n        }\n\n        // throw the first line away - it contains the header\n        fgets(line, sizeof(line), fp);\n\n        // read every point and generate DEM\n        while(fgets(line, sizeof(line), fp) != NULL)\n        {\n            data_x = atof(strtok(line, \",\\n\"));\n            data_y = atof(strtok(NULL, \",\\n\"));\n            data_z = atof(strtok(NULL, \",\\n\"));\n\n            data_x -= min_x;\n            data_y -= min_y;\n\n            //if((rc = interp->update(arrX[i], arrY[i], arrZ[i])) < 0)\n            if((rc = interp->update(data_x, data_y, data_z)) < 0)\n            {\n                cerr << \"interp->update() error while processing \" << endl;\n                return -1;\n            }\n        }\n\n        fclose(fp);\n    } \n\n    else { // input format is LAS\n\n        las_file las;\n        las.open(inputName);\n    \n        \n        size_t count = las.points_count();\n        size_t index(0);\n        while (index < count) {\n            data_x = las.getX(index);\n            data_y = las.getY(index);\n            data_z = las.getZ(index);\n            data_class = las.getClassification(index);\n            data_return_number = las.getReturnNumber(index);\n            data_max_return = las.getNumberOfReturns(index);\n            \n            data_x -= min_x;\n            data_y -= min_y;\n\n            // If exclude point is true then point should be skipped\n            if (!exclude_point_class(data_class) && !exclude_point_return(data_return_number, data_max_return)) {\n                las_point_count++;\n\t\t\t\tif ((rc = interp->update(data_x, data_y, data_z)) < 0) {\n\t\t\t\t\tcerr << \"interp->update() error while processing \" << endl;\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n            index++;\n        }\n        \n\n    }\n\n    if((rc = interp->finish(outputName, outputFormat, outputType)) < 0)\n    {\n        cerr << \"interp->finish() error\" << endl;\n        return -1;\n    }\n\n    cerr << \"Interpolation::interpolation() done successfully\" << endl;\n\n    return 0;\n}\n\nvoid Interpolation::setRadius(double r)\n{\n    radius_sqr = r * r;\n}\n\nvoid Interpolation::setLasExcludeClassification(std::vector<int> classification)\n{\n\tlas_exclude_classification = classification;\n}\n\nvoid Interpolation::setLasExcludeReturn(bool keep_first_return)\n{\n    filter_returns = true;\n    this->keep_first_return = keep_first_return;\n}\n\nbool Interpolation::exclude_point_class(int classification)\n{\n    // This checks if the classification vector contains the current classification, if it does return true\n    // to exclude point. Otherwise return false to include point\n    return std::find(las_exclude_classification.begin(), las_exclude_classification.end(), classification) != las_exclude_classification.end();\n}\n\nbool Interpolation::exclude_point_return(int current_return, int max_returns)\n{\n    // keeping the first return return false when the current return is not equal to 1 (as we include point by returning false)\n    // keeping last return return false when current return is not equal to max_returns\n    if(filter_returns) {\n        if(keep_first_return)\n        {\n            return current_return != 1;\n        } else {\n            return current_return != max_returns; // if the current return == the max numbers of returns\n        }\n    }\n\n    return false; // return false to include the point\n}\n\n\n\n\n\n\n\n\nunsigned int Interpolation::getDataCount()\n{\n    return data_count;\n}\n\nunsigned int Interpolation::getGridSizeX()\n{\n    return GRID_SIZE_X;\n}\n\nunsigned int Interpolation::getGridSizeY()\n{\n    return GRID_SIZE_Y;\n}\n\n", "meta": {"hexsha": "4899088fcff50f2541e8e31635456886367a04aa", "size": 14886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Interpolation.cpp", "max_stars_repo_name": "HongqiangWei/points2grid", "max_stars_repo_head_hexsha": "52a36fb8f564d335796ed75050e3cf7e6340ab52", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2015-04-06T21:29:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T03:19:44.000Z", "max_issues_repo_path": "src/Interpolation.cpp", "max_issues_repo_name": "HongqiangWei/points2grid", "max_issues_repo_head_hexsha": "52a36fb8f564d335796ed75050e3cf7e6340ab52", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T13:23:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-16T03:56:58.000Z", "max_forks_repo_path": "src/Interpolation.cpp", "max_forks_repo_name": "HongqiangWei/points2grid", "max_forks_repo_head_hexsha": "52a36fb8f564d335796ed75050e3cf7e6340ab52", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2015-01-20T16:44:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T01:46:34.000Z", "avg_line_length": 29.772, "max_line_length": 156, "alphanum_fraction": 0.586524251, "num_tokens": 3557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.03210070683275389, "lm_q1q2_score": 0.014550025701614164}}
{"text": "#include \"RGeometry.h\"\n\n#include <QtGlobal>\n#include <QDebug>\n\n//#include <iostream>\n//#include <iomanip>\n\n#include <Eigen/Geometry>\n\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/video/video.hpp>\n\n#include \"rce/core/RCppTweaks.h\"\n\n#define RCE_USE_OPENCV3_ALGORITHM (true)\n\n#define RCE_USE_EIGEN_EULER_ANGLES (1)\n\nnamespace rce {\n    namespace geometry {\n\n        RGeometry::RGeometry()\n        {\n        }\n\n        cv::Mat get4x4TransformMatrix(const cv::Mat &input)\n        {\n            if((input.cols == 4) && (input.rows == 4))\n                return input;\n            else\n            {\n                cv::Mat identity = cv::Mat::eye(cv::Size(4,4), input.type());\n\n                cv::Rect cutRect(0,0,\n                                 qMin(input.size().width, 4),\n                                 qMin(input.size().height, 4));\n\n                cv::Mat roi(identity, cutRect);\n                input.copyTo(roi);\n\n                return identity;\n            }\n        }\n\n        cv::Mat get3x3TransformMatrix(const cv::Mat &input)\n        {\n            if(input.empty())\n            {\n                return  cv::Mat::eye(cv::Size(3,3), CV_64FC1);\n            }\n            else if((input.cols == 3) && (input.rows == 3))\n                return input;\n            else\n            {\n                cv::Mat identity = cv::Mat::eye(cv::Size(3,3), input.type());\n\n                cv::Rect cutRect(0,0,\n                                 qMin(input.size().width, 3),\n                                 qMin(input.size().height, 3));\n\n                cv::Mat roi(identity, cutRect);\n                input.copyTo(roi);\n\n                return identity;\n            }\n        }\n\n\n        cv::Mat\n        estimatePoseFromHomography(const cv::Mat &homography,\n                                   const cv::Mat &invCameraMatrix)\n        {\n//            if(RCE_USE_OPENCV3_ALGORITHM)\n//            {\n//                // based upon implementation in https://github.com/Itseez/opencv/blob/7d4d28605087ec2d3878f9467aea313a2acdfd49/modules/calib3d/src/homography_decomp.cpp\n\n//            }\n//            else\n//            {\n                cv::Mat pose = cv::Mat::eye(3, 4, homography.type());\n                cv::Mat h = invCameraMatrix * homography;\n\n\n                // dumbest version based on http://dsp.stackexchange.com/questions/2736/step-by-step-camera-pose-estimation-for-visual-tracking-and-planar-markers\n                // for another versions, see older revisions of this file in svn\n                {\n                    h.col(0).copyTo(pose.col(0));\n                    h.col(1).copyTo(pose.col(1));\n                    cv::Mat v3 = pose.col(0).cross(pose.col(1));\n                    double norm1 = cv::norm(h.col(0));\n                    double norm2 = cv::norm(h.col(1));\n                    double tnorm = (norm1 + norm2) / 2.0;\n                    //dDebug() << \"Rotnorms\"<< norm1 << norm2 << cv::norm(v3);\n                    v3 = v3 / tnorm;\n                    v3.copyTo(pose.col(2));\n\n                    h.col(2).copyTo(pose.col(3));\n\n                    return pose / tnorm;/*/ pose.at<double>(2,3)*/;\n\n                }\n//            }\n        }\n\n        double getAngleAverageDeg(double angle1,\n                                  double angle2)\n        {\n            double angle1Norm = normalizeAngleDeg(angle1);\n            double angle2Norm = normalizeAngleDeg(angle2);\n\n            double angleAvg = normalizeAngleDeg((angle1Norm + angle2Norm) / 2.0);\n            if(angleAbsDiff(angleAvg,\n                            angle1Norm) > 90.0)\n            {\n                angleAvg = normalizeAngleDeg(angleAvg + 180.0);\n            }\n\n            return angleAvg;\n\n        }\n\n        double normalizeAngleDeg(double angle)\n        {\n            while(angle < 0.0)\n            {\n                angle += 360.0;\n            }\n\n            while(angle >= 360.0)\n            {\n                angle -= 360.0;\n            }\n\n            return angle;\n        }\n\n        double angleAbsDiff(double angle1,\n                            double angle2)\n        {\n//            double angle1 = normalizeAngleDeg(angle1);\n//            double angle2 = normalizeAngleDeg(angle2);\n//            if(angle1 < angle2)\n//            {\n//                std::swap(angle1, angle2);\n//            }\n\n            double diff = normalizeAngleDeg(angle1 - angle2);\n\n            if(diff > 180.0)\n            {\n                diff = 360 - diff;\n            }\n\n            return diff;\n\n        }\n\n        cv::Mat\n        getHomographyFromPose(const cv::Mat &cameraPosition,\n                              const cv::Mat &projectionMatrix)\n        {\n             cv::Mat homography3d = projectionMatrix * cameraPosition;\n             cv::Mat homography(cv::Size(3,3), homography3d.type());\n             homography3d.col(0).copyTo(homography.col(0));\n             homography3d.col(1).copyTo(homography.col(1));\n             homography3d.col(3).copyTo(homography.col(2));\n\n             return homography;\n        }\n\n        QTransform\n        cvMatToQTransform(const cv::Mat &cvTransformIn)\n        {\n            if(cvTransformIn.empty())\n                return QTransform();\n            else\n            {\n\n                double h[3][3];\n                h[0][0] = 1;\n                h[0][1] = 0;\n                h[0][2] = 0;\n\n                h[1][0] = 0;\n                h[1][1] = 1;\n                h[1][2] = 0;\n\n                h[2][0] = 0;\n                h[2][1] = 0;\n                h[2][2] = 1;\n\n                if(cvTransformIn.type() == CV_64FC1)\n                { // doubles\n\n                    cv::Mat cvTransform = cvTransformIn * (1.0 / cvTransformIn.at<double>(2,2));\n                    for(int rowIdx = 0;\n                        rowIdx < qMin(cvTransform.rows, 3);\n                        ++rowIdx)\n                    {\n                        for(int colIdx = 0;\n                            colIdx < qMin(cvTransform.cols, 3);\n                            ++colIdx)\n                        {\n                            h[rowIdx][colIdx] = cvTransform.at<double>(rowIdx,\n                                                                       colIdx);\n                        }\n                    }\n                }\n                else if(cvTransformIn.type() == CV_32FC1)\n                { // floats\n\n                    cv::Mat cvTransform = cvTransformIn * (1.0 / cvTransformIn.at<float>(2,2));\n                    for(int rowIdx = 0;\n                        rowIdx < qMin(cvTransform.rows, 3);\n                        ++rowIdx)\n                    {\n                        for(int colIdx = 0;\n                            colIdx < qMin(cvTransform.cols, 3);\n                            ++colIdx)\n                        {\n                            h[rowIdx][colIdx] = cvTransform.at<float>(rowIdx,\n                                                                       colIdx);\n                        }\n                    }\n                }\n                else\n                {\n                    throw \"Unsupported transformation type\";\n                }\n\n                QTransform transform(h[0][0],h[1][0],h[2][0],\n                                     h[0][1],h[1][1],h[2][1],\n                                     h[0][2],h[1][2],h[2][2]);\n\n                return transform;\n            }\n\n        }\n\n        cv::Rect\n        getRectangleInsideImage(const cv::Size &imageSize,\n                                const cv::Rect &rect)\n        {\n            cv::Rect result = rect;\n            result.width = qMax(0,\n                                qMin(result.width,\n                                  imageSize.width - result.x));\n            result.height = qMax(0,\n                                 qMin(result.height,\n                                      imageSize.height - result.y));\n            result.x = qBound(0,result.x,imageSize.width - 1);\n            result.y = qBound(0,result.y,imageSize.height - 1);\n\n            return result;\n        }\n\n        QPointF\n        transformPoint(const cv::Mat &transform,\n                       const QPointF &pt)\n        {\n            cv::Vec3d cvPt(pt.x(),\n                           pt.y(),\n                           1.0);\n\n            cvPt = cv::Mat(transform * cv::Mat(cvPt));\n\n            return QPointF(cvPt(0) / cvPt(2),\n                           cvPt(1) / cvPt(2));\n        }\n\n        cv::Mat\n        rotationMatrixFromVectors(const cv::Vec2d &vecFrom,\n                                  const cv::Vec2d &vecTo)\n        {\n//            if(vecFrom == vecTo)\n//            {\n//                return cv::Mat::eye(2,2,CV_64FC1);\n//            }\n//            else if(vecFrom == (vecTo * -1))\n//            {\n//                return cv::Matx<double,2,2>(-1,0,\n//                                            0,-1); // just flipping around\n//            }\n//            // derived from http://math.stackexchange.com/a/476311/161840\n//            cv::Vec2d a = vecFrom / cv::norm(vecFrom);\n//            cv::Vec2d b = vecFrom / cv::norm(vecTo);\n//            cv::Vec2d v = a(0) * b(1) - a(1) * b(0);\n//            double s = cv::norm(v);\n//            double c = a.dot(b);\n\n\n            //based upon http://stackoverflow.com/a/2946536/1603969\n            if(areVecsEqual(vecFrom, vecTo))\n            {\n                return cv::Mat::eye(2,2,CV_64FC1);\n            }\n            else if(areVecsEqual(vecFrom,\n                                 (vecTo * -1)))\n            {\n                return cv::Mat(cv::Matx<double,2,2>(-1,0,\n                                            0,-1)).clone(); // just flipping around\n            }\n            else\n            {\n                double angle = angleFromVectors(vecFrom,\n                                                vecTo);\n                double cosAngle = std::cos(angle);\n                double sinAngle = std::sin(angle);\n\n                return cv::Mat(cv::Matx<double,2,2>(cosAngle,-sinAngle,\n                                                   sinAngle,cosAngle)).clone();\n            }\n\n\n        }\n\n        double\n        angleFromVectors(const cv::Vec2d &vecFrom,\n                        const cv::Vec2d &vecTo)\n        {\n            if(vecFrom == vecTo)\n            {\n                return 0;\n\n            }\n            else if(vecFrom == (vecTo * -1))\n            {\n                return M_PI;\n            }\n            else\n            {\n\n                return std::atan2(vecTo(1),\n                                  vecTo(0)) -\n                        std::atan2(vecFrom(1),\n                                   vecFrom(0));\n            }\n        }\n\n        cv::Mat\n        transformFromLineSegments(const cv::Vec2d &line1start,\n                                       const cv::Vec2d &line1end,\n                                       const cv::Vec2d &line2start,\n                                       const cv::Vec2d &line2end)\n        {\n            Eigen::Affine2d transform = Eigen::Affine2d::Identity();\n\n            // transform to origin\n            transform.pretranslate(Eigen::Vector2d(-line1start(0),\n                                                   -line1start(1)));\n\n            // find rotation\n            cv::Vec2d vec1 = line1end - line1start;\n            cv::Vec2d vec2 = line2end - line2start;\n            double angle = angleFromVectors(vec1,\n                                            vec2);\n            transform.prerotate(Eigen::Rotation2Dd(angle));\n\n            // find scale\n            double scale = cv::norm(vec2) / cv::norm(vec1);\n            transform.prescale(scale);\n\n            // now transform to start of the line 2\n            transform.pretranslate(Eigen::Vector2d(line2start(0),\n                                                   line2start(1)));\n\n            cv::Mat transformCV;\n            cv::eigen2cv(transform.matrix(),\n                         transformCV);\n//            std::cerr << \"transformFromLineSegments\" <<\n//                      line1start <<\n//                         line2start <<\n//                         angle << scale << std::endl <<\n//                         transformCV << std::endl;\n\n            return transformCV;\n\n        }\n\n        cv::Point2d\n        getNormalVector(const cv::Point2d &pt1,\n                        const cv::Point2d &pt2)\n        {\n            return cv::Point2d(pt1.y - pt2.y,\n                               pt2.x - pt1.x);\n        }\n\n        cv::Point2d\n        getUnitNormalVector(const cv::Point2d &pt1,\n                            const cv::Point2d &pt2)\n        {\n            if(pt1 == pt2)\n            {\n               return cv::Point2d(0,0);\n            }\n            else\n            {\n                cv::Point2d result = getNormalVector(pt1,\n                                                     pt2);\n                double norm = cv::norm(result);\n                return cv::Point2d(result.x / norm,\n                                   result.y / norm);\n            }\n        }\n\n        cv::Point2d\n        getNearestPointOnLineSegment(const cv::Point2d &pt1,\n                                     const cv::Point2d &pt2,\n                                     const cv::Point2d &testPoint)\n        {\n            // based on http://www.ogre3d.org/tikiwiki/Nearest+point+on+a+line\n            const cv::Point2d result = getNearestPointOnLine(pt1,\n                                                    pt2,\n                                                    testPoint);\n            const double lineLength = squaredNorm(pt1 -\n                                               pt2);\n\n            const double p1R = squaredNorm(pt1 -\n                                        result);\n            const double p2R = squaredNorm(pt2 -\n                                        result);\n                //R                R p1 R p2 R                R\n            if ( p1R > lineLength )\n            {\n                if ( p2R > p1R )\n                    return pt1; //pt 1 is closer to result\n                else\n                    return pt2;\n            }\n            else if ( p2R > lineLength )\n                return pt1;\n\n            return result;\n        }\n\n        cv::Point2d\n        getNearestPointOnLine(const cv::Point2d &linePt1,\n                              const cv::Point2d &linePt2,\n                              const cv::Point2d &testPoint)\n        {\n            // based on http://www.ogre3d.org/tikiwiki/Nearest+point+on+a+line\n            const cv::Point2d A = testPoint  - linePt1;\n            const cv::Point2d u = (linePt2 - linePt1);\n\n            return linePt1 + (A.dot(u) * u);\n        }\n\n\n        cv::Mat\n        estimateProjectiveTransform(const std::vector<cv::Point2d> &src,\n                                    const std::vector<cv::Point2d> &dst)\n        {\n            assert(src.size() == dst.size());\n\n            if(src.size() == 0)\n            {\n                return cv::Mat::eye(3,3,\n                                    CV_64FC1);\n            }\n            else if(src.size() == 1)\n            {\n                // just shift\n                Eigen::Affine2d transform = Eigen::Affine2d::Identity();\n                transform.pretranslate(Eigen::Vector2d(dst[0].x - src[0].x,\n                                                       dst[0].y - src[0].y));\n\n                cv::Mat transformCV;\n                cv::eigen2cv(transform.matrix(),\n                             transformCV);\n    //            std::cerr << \"transformFromLineSegments\" <<\n    //                      line1start <<\n    //                         line2start <<\n    //                         angle << scale << std::endl <<\n    //                         transformCV << std::endl;\n\n                return transformCV;\n            }\n            else if(src.size() == 2)\n            {\n                // transform of line segments\n                return transformFromLineSegments(cv::Vec2d(src[0].x, src[0].y),\n                        cv::Vec2d(src[1].x, src[1].y),\n                        cv::Vec2d(dst[0].x, dst[0].y),\n                        cv::Vec2d(dst[1].x, dst[1].y));\n            }\n            else if(src.size() == 3)\n            {\n                // estimate affine transform\n                return get3x3TransformMatrix(cv::estimateRigidTransform(src, dst,\n                                                  true));\n            }\n            else\n            {\n                // estimate perspective\n                return cv::findHomography(src, dst);\n            }\n        }\n\n\n\n        cv::Point2d\n        getCentroid(const std::vector<cv::Point2d> &src)\n        {\n            cv::Point2d sumPoint(0,0);\n            for(int i = 0;\n                i < src.size();\n                ++i)\n            {\n                sumPoint += src[i];\n            }\n\n            return sumPoint * (1.0 / src.size());\n        }\n\n        double\n        linearInterpolate(double x0,\n                          double x1,\n                          double fx0,\n                          double fx1,\n                          double x)\n        {\n            assert(x0 != x1);\n\n            return fx0 + ((fx1 - fx0)/(x1 - x0)) * (x - x0);\n        }\n\n        cv::Mat\n        alignUnitVectorsByRotation(const cv::Vec3d &a,\n                                   const cv::Vec3d &b)\n        {\n            // derived from Kuba Ober answer at http://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d/180436\n            if(a == b)\n            {\n                return cv::Mat::eye(3,3,\n                                    CV_64FC1);\n            }\n            else\n            {\n                double dotAB = a.dot(b);\n                cv::Vec3d crossAB = a.cross(b);\n                cv::Vec3d crossBA = -crossAB;//b.cross(a);\n                double normCrossAb = cv::norm(crossAB,\n                                              cv::NORM_L2);\n\n                if(normCrossAb <= std::numeric_limits<double>::epsilon())\n                {\n                    return calculateVectorOpositeRotation(a);\n                }\n                else\n                {\n\n                    cv::Vec3d v = b - ((dotAB) * a);\n                    double normV = cv::norm(v,\n                                            cv::NORM_L2);\n                    v = v * (1.0 / normV);\n\n                    cv::Mat GG = cv::Mat::eye(3,3,\n                                              CV_64FC1);\n\n                    GG.at<double>(0,0) = dotAB;\n                    GG.at<double>(0,1) = -normCrossAb;\n                    GG.at<double>(1,0) = normCrossAb;\n                    GG.at<double>(1,1) = dotAB;\n\n                    cv::Mat FFi(3,3,\n                                CV_64FC1);\n                    FFi.at<double>(0,0) = a(0);\n                    FFi.at<double>(1,0) = a(1);\n                    FFi.at<double>(2,0) = a(2);\n\n                    FFi.at<double>(0,1) = v(0);\n                    FFi.at<double>(1,1) = v(1);\n                    FFi.at<double>(2,1) = v(2);\n\n                    FFi.at<double>(0,2) = crossBA(0);\n                    FFi.at<double>(1,2) = crossBA(1);\n                    FFi.at<double>(2,2) = crossBA(2);\n\n                    return FFi * GG * FFi.inv();\n                }\n            }\n        }\n\n        cv::Vec3d calculateEulerAnglesFromRotation(const cv::Mat &rotationMatrix)\n        {\n\n#ifdef RCE_USE_EIGEN_EULER_ANGLES\n            Eigen::Matrix3d mat;\n            cv::cv2eigen(rotationMatrix,\n                         mat);\n            Eigen::Vector3d ea = mat.eulerAngles(2,1,0);\n            return cv::Vec3d(ea(2),\n                             ea(1),\n                             ea(0));\n#else\n            // based upon http://www.staff.city.ac.uk/~sbbh653/publications/euler.pdf\n            if((rotationMatrix.at<double>(2,0) != 1) &&\n               (rotationMatrix.at<double>(2,0) != -1))\n            {\n                double theta1 = std::asin(rotationMatrix.at<double>(2,0));\n                double theta2 = M_PI - theta1;\n                double cosTheta1 = cos(theta1);\n                double cosTheta2 = cos(theta2);\n                double psi1 = atan2(rotationMatrix.at<double>(2,1) / cosTheta1,\n                                    rotationMatrix.at<double>(2,2) / cosTheta1);\n                double psi2 = atan2(rotationMatrix.at<double>(2,1) / cosTheta2,\n                                    rotationMatrix.at<double>(2,2) / cosTheta2);\n                double phi1 = atan2(rotationMatrix.at<double>(1,0) / cosTheta1,\n                                    rotationMatrix.at<double>(0,0) / cosTheta1);\n                double phi2 = atan2(rotationMatrix.at<double>(1,0) / cosTheta2,\n                                    rotationMatrix.at<double>(0,0) / cosTheta2);\n\n                double sol1Rank = std::abs(psi1) +\n                                  std::abs(phi1) +\n                                  std::abs(theta1);\n                double sol2Rank = std::abs(psi2) +\n                                  std::abs(phi2) +\n                                  std::abs(theta2);\n                if(sol2Rank > sol1Rank)\n                {\n                    return cv::Vec3d(psi1,\n                                     theta1,\n                                     phi1);\n                }\n                else\n                {\n                    return cv::Vec3d(psi2,\n                                     theta2,\n                                     phi2);\n                }\n            }\n            else\n            {\n                double phi = 0;\n\n                if(rotationMatrix.at<double>(2,0) != -1)\n                {\n                    double theta = M_PI / 2.0;\n                    double psi = phi + atan2(rotationMatrix.at<double>(0,1),\n                                             rotationMatrix.at<double>(0,2));\n                    return cv::Vec3d(psi,\n                                     theta,\n                                     phi);\n                }\n                else\n                {\n                    double theta = -M_PI / 2.0;\n                    double psi = -phi + atan2(-rotationMatrix.at<double>(0,1),\n                                             -rotationMatrix.at<double>(0,2));\n                    return cv::Vec3d(psi,\n                                     theta,\n                                     phi);\n\n                }\n            }\n#endif\n        }\n\n        cv::Mat\n        buildRotationMatrixFromEulerAngles(const cv::Vec3d &eulerAngles)\n        {\n            double psi = eulerAngles(0);\n            double theta = eulerAngles(1);\n            double phi = eulerAngles(2);\n\n            Eigen::Matrix3d m;\n            m = Eigen::AngleAxisd(phi,\n                                  Eigen::Vector3d::UnitZ()) *\n                Eigen::AngleAxisd(theta,\n                                                  Eigen::Vector3d::UnitY()) *\n                Eigen::AngleAxisd(psi,\n                                                  Eigen::Vector3d::UnitX());\n\n            cv::Mat result;\n            cv::eigen2cv(m, result);\n            return result;\n\n\n        }\n\n        cv::Mat\n        calculateVectorOpositeRotation(const cv::Vec3d &vec)\n        {\n            cv::Vec3d orthogonalVector;\n            if(vec(0) != 0)\n            {\n                orthogonalVector(0) = -vec(1);\n                orthogonalVector(1) = vec(0);\n                orthogonalVector(2) = 0;\n            }\n            else\n            {\n\n                orthogonalVector(0) = 0;\n                orthogonalVector(1) = -vec(2);\n                orthogonalVector(2) = vec(1);\n            }\n\n            // now rotate stuff around this orthogonal vector\n            Eigen::Matrix3d m;\n            m = Eigen::AngleAxisd(M_PI,\n                                  Eigen::Vector3d(orthogonalVector(0),\n                                                  orthogonalVector(1),\n                                                  orthogonalVector(2))).matrix();\n\n            cv::Mat result;\n            cv::eigen2cv(m, result);\n            return result;\n        }\n\n        cv::Mat\n        composeRotationMatrix(const cv::Vec3d &r1,\n                              const cv::Vec3d &r2,\n                              const cv::Vec3d &r3)\n        {\n            Eigen::Matrix3d r;\n            r(0,0) = r1(0);\n            r(1,0) = r1(1);\n            r(2,0) = r1(2);\n            r(0,1) = r2(0);\n            r(1,1) = r2(1);\n            r(2,1) = r2(2);\n            r(0,2) = r3(0);\n            r(1,2) = r3(1);\n            r(2,2) = r3(2);\n\n            Eigen::Projective3d t = Eigen::Projective3d::Identity();\n            t.linear() = r;\n            r = t.rotation(); // calculates rotation using SVD\n\n            cv::Mat rCv;\n            cv::eigen2cv(r, rCv);\n            return rCv;\n        }\n\n        void\n        invertTranslationAndRotation(const cv::Point3d &t,\n                                     const cv::Mat &r,\n                                     cv::Point3d &tInv,\n                                     cv::Mat &rInv)\n        {\n            // according to: http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/teche53.html\n            rInv = r.t();\n            cv::Vec3d tVec(t.x,\n                           t.y,\n                           t.z);\n            cv::Vec3d tInvVec = cv::Mat(-rInv * cv::Mat(tVec));\n            tInv.x = tInvVec(0);\n            tInv.y = tInvVec(1);\n            tInv.z = tInvVec(2);\n        }\n\n        cv::Point3d\n        transformPoint(const cv::Point3d &p,\n                       const cv::Point3d &t,\n                       const cv::Mat &rot)\n        {\n            cv::Vec3d resVec = transformVector(cv::Vec3d(p.x,\n                                                         p.y,\n                                                         p.z),\n                                               cv::Vec3d(t.x,\n                                                         t.y,\n                                                         t.z),\n                                               rot);\n            return cv::Point3d(resVec(0),\n                               resVec(1),\n                               resVec(2));\n        }\n\n        cv::Vec3d\n        transformVector(const cv::Vec3d &v,\n                        const cv::Vec3d &t,\n                        const cv::Mat &rot)\n        {\n            cv::Vec3d res = cv::Mat(rot * cv::Mat(v));\n            return res + t;\n        }\n\n        cv::Point2d\n        transformPoint(const cv::Point2d &p,\n                       const cv::Point2d &t,\n                       const cv::Mat &rot)\n        {\n            cv::Vec2d resVec = transformVector(cv::Vec2d(p.x,\n                                                         p.y),\n                                               cv::Vec2d(t.x,\n                                                         t.y),\n                                               rot);\n            return cv::Point2d(resVec(0),\n                               resVec(1));\n        }\n\n        cv::Vec2d\n        transformVector(const cv::Vec2d &v,\n                        const cv::Vec2d &t,\n                        const cv::Mat &rot)\n        {\n            cv::Vec2d res = cv::Mat(rot * cv::Mat(v));\n            return res + t;\n        }\n\n        cv::Mat\n        get2DRotationMatrix(double angle)\n        {\n            cv::Mat_<double> rot(2,2);\n            double angleCos = std::cos(angle);\n            double angleSin = std::sin(angle);\n            rot(0,0) = angleCos;\n            rot(0,1) = -angleSin;\n            rot(1,0) = angleSin;\n            rot(1,1) = angleCos;\n\n            return rot;\n        }\n\n        cv::Point2d\n        rotatePointAround(const cv::Point2d &pt,\n                          const cv::Mat &rotation,\n                          const cv::Point2d &pivot)\n        {\n            return transformPoint(pt - pivot,\n                                  pivot,\n                                  rotation);\n        }\n\n        double normalizeAngle(double angle)\n        {\n            while(angle < 0.0)\n            {\n                angle += 2 * M_PI;\n            }\n\n            while(angle >= (2 * M_PI))\n            {\n                angle -= 2 * M_PI;\n            }\n\n            return angle;\n        }\n\n        QPainterPath\n        calculateIntersectionProjective(const QPainterPath &thisViewPath,\n                                        const QPainterPath &otherViewPath,\n                                        const QTransform &otherTransform)\n        {\n            if(otherTransform.isIdentity())\n            {\n                return thisViewPath.united(otherViewPath);\n            }\n            else\n            {\n                cv::Mat transform = qTransform2CV(otherTransform);\n                return calculateIntersectionProjective(thisViewPath,\n                                                otherViewPath,\n                                                transform);\n            }\n        }\n\n\n        QPainterPath\n        calculateIntersectionProjective(const QPainterPath &thisViewPath,\n                                        const QPainterPath &otherViewPath,\n                                        const cv::Mat &otherTransform)\n        {\n            if(otherTransform.empty())\n            {\n                return thisViewPath.united(otherViewPath);\n            }\n\n            QList<QPolygonF> polygons = otherViewPath.toFillPolygons();\n            // here should come something like frustum clipping\n            /*\n             * Do it like this:\n             * We know that horizon is at place where w in homogeneous coordinates is 0,\n             * therefore, the line of horizon is given as h31*x + h32*y + h33 = 0.\n             *\n             * Now we may assume that some point (i.e. at the bottom of the view) is ground.\n             * So we try to transform it, and see the sign of W. All valid points have the same\n             * sign. (are on the correct side of the horizon)\n             *\n             * */\n            QPainterPath result;\n            for(int i = 0;\n                i < polygons.size();\n                ++i)\n            {\n                for(int j = 0;\n                    j < polygons[i].size();\n                    ++j)\n                {\n                    cv::Vec3d v(polygons[i][j].x(),\n                                polygons[i][j].y(),\n                                1);\n                    v = cv::Mat(otherTransform * cv::Mat(otherTransform));\n                    polygons[i][j].setX(v(0) / v(2));\n                    polygons[i][j].setY(v(1) / v(2));\n                }\n                result.addPolygon(polygons[i]);\n            }\n\n            return result;\n        }\n\n        cv::Mat qTransform2CV(const QTransform &trans)\n        {\n            cv::Mat result(3,3,\n                           CV_64FC1);\n            result.at<double>(0,0) = trans.m11();\n            result.at<double>(0,1) = trans.m21();\n            result.at<double>(0,2) = trans.m31();\n            result.at<double>(1,0) = trans.m12();\n            result.at<double>(1,1) = trans.m22();\n            result.at<double>(1,2) = trans.m32();\n            result.at<double>(2,0) = trans.m13();\n            result.at<double>(2,1) = trans.m23();\n            result.at<double>(2,2) = trans.m33();\n\n            return result;\n        }\n\n        bool\n        getHorizonFromTransformation(const cv::Mat &transform,\n                                     double &a,\n                                     double &b,\n                                     double &c)\n        {\n            if(transform.empty())\n            {\n                return false;\n            }\n            else\n            {\n                a = transform.at<double>(2,0);\n                b = transform.at<double>(2,1);\n                c = transform.at<double>(2,2);\n                if((a == 0) && (b == 0))\n                { // there is no horizon line (so it is an affine transform)\n                    return false;\n                }\n                else\n                {\n                    return true;\n                }\n            }\n        }\n\n        bool\n        cutRectangleByLine(const QRectF &rectangle,\n                           double a,\n                           double b,\n                           double c,\n                           QPolygonF &part1,\n                           QPolygonF &part2)\n        {\n            part1.clear();\n            part2.clear();\n            if(a == 0)\n            {\n                // the line as at coordinate y = -b/c\n                double lineY = -b/c;\n                if((rectangle.top() > lineY) &&\n                   (rectangle.bottom() < lineY))\n                {\n\n                    part1.push_back(rectangle.bottomLeft());\n                    part1.push_back(rectangle.bottomRight());\n                    part1.push_back(QPointF(rectangle.right(),\n                                            lineY));\n                    part1.push_back(QPointF(rectangle.left(),\n                                            lineY));\n\n                    part2.push_back(part1[3]);\n                    part2.push_back(part1[2]);\n                    part2.push_back(rectangle.topRight());\n                    part2.push_back(rectangle.topLeft());\n\n\n                    return true;\n\n                }\n                else\n                {\n                    return false;\n                }\n            }\n            else // a is nonzero, lets use it!\n            {\n                double topCrossX = getLineX(rectangle.top(),\n                                          a,b,c);\n                double bottomCrossX = getLineX(rectangle.bottom(),\n                                              a,b,c);\n                if((topCrossX <= rectangle.left()) && (bottomCrossX <= rectangle.left()))\n                {  // line is to the left\n                    return false;\n                }\n                if((topCrossX >= rectangle.right()) && (bottomCrossX >= rectangle.right()))\n                { // line is to the right\n                    return false;\n                }\n\n\n                // there must be two crossings\n                bool appendToPart1 = true;\n                part1.append(rectangle.bottomLeft()); // start at bottom left\n                // check crossing bottom line\n                if((bottomCrossX > rectangle.left()) && (bottomCrossX <= rectangle.right()))\n                {\n                    // there is crossing!\n                    part1.push_back(QPointF(bottomCrossX,\n                                            rectangle.bottom()));\n                    appendToPart1 = false;\n                    part2.push_back(QPointF(bottomCrossX,\n                                            rectangle.bottom()));\n                }\n\n                if(appendToPart1)\n                {\n                    part1.push_back(rectangle.bottomRight());\n                }\n                else\n                {\n                    part2.push_back(rectangle.bottomRight());\n                }\n                // check crossing right line\n                if((((bottomCrossX - rectangle.right()) * (topCrossX - rectangle.right())) <= 0) && // this will be smaller than/equal 0, if line is crossed\n                   (bottomCrossX != rectangle.right())) // just check to not identify the same crossing twice.\n                {\n                    part1.push_back(QPointF(rectangle.right(),\n                                    getLineY(rectangle.right(),\n                                             a,b,c)));\n                    part2.push_back(part1.last());\n                    appendToPart1 = !appendToPart1;\n                }\n\n                if(appendToPart1)\n                {\n                    part1.push_back(rectangle.topRight());\n                }\n                else\n                {\n                    part2.push_back(rectangle.topRight());\n                }\n                // check crossing top\n                if((topCrossX >= rectangle.left()) && (topCrossX < rectangle.right()))\n                {\n                    part1.push_back(QPointF(topCrossX,\n                                            rectangle.top()));\n                    appendToPart1 = !appendToPart1;\n                    part2.push_back(QPointF(topCrossX,\n                                            rectangle.top()));\n\n                }\n\n                if(appendToPart1)\n                {\n                    part1.push_back(rectangle.topLeft());\n                }\n                else\n                {\n                    part2.push_back(rectangle.topLeft());\n                }\n\n                // check crossing left line\n                if((((bottomCrossX - rectangle.left()) * (topCrossX - rectangle.left())) <= 0) && // this will be smaller than/equal 0, if line is crossed\n                   (topCrossX != rectangle.left())) // just check to not identify the same crossing twice.\n                {\n                    part1.push_back(QPointF(rectangle.left(),\n                                    getLineY(rectangle.left(),\n                                             a,b,c)));\n                    part2.push_back(part1.last());\n                    appendToPart1 = !appendToPart1;\n                }\n\n                return true;\n\n            }\n        }\n\n        double\n        getLineY(double x,\n                 double a,\n                 double b,\n                 double c)\n        {\n            // ax + yb +c = 0\n            // y = -(ax + c)/b\n            return -(a*x + c) / b;\n        }\n\n        double\n        getLineX(double y,\n                 double a,\n                 double b,\n                 double c)\n        {\n            // ax + yb +c = 0\n            // x = -(yb + c)/a\n            return -(y*b + c) / a;\n        }\n\n        QPointF\n        getPolygonApproxCentre(const QPolygonF &polygon)\n        {\n            if(polygon.size() == 0)\n            {\n                return QPointF();\n            }\n            else\n            {\n                QPointF result(0,0);\n                foreach(QPointF pt, polygon)\n                {\n                    result += pt;\n                }\n\n                return result * (1.0 / polygon.size());\n            }\n        }\n\n        QPolygonF\n        simplePolylineIntersection(const QPolygonF &polyline,\n                                   const QPolygonF &polygon)\n        {\n            if(polyline.isEmpty())\n            {\n                return QPolygonF();\n            }\n\n            QPolygonF result;\n            bool isInside = polygon.containsPoint(polyline.first(),\n                                                  Qt::OddEvenFill);\n            if(isInside)\n            {\n                result.push_back(polyline.first());\n            }\n            QPointF intersectionPoint;\n            for(int i = 1;\n                i < polyline.size();\n                ++i)\n            {\n                QLineF lineSeg(polyline[i-1],\n                        polyline[i]);\n                QVector<QPointF> crossings;\n                for(int j = 1;\n                    j < polygon.size();\n                    ++j)\n                {\n                    QLineF polSeg(polygon[j-1],\n                            polygon[j]);\n                    switch(lineSeg.intersect(polSeg,\n                                      &intersectionPoint))\n                    {\n                        case QLineF::NoIntersection:\n                            break;\n                        case QLineF::BoundedIntersection:\n                            if(intersectionPoint != lineSeg.p1())\n                            {\n                                crossings.push_back(intersectionPoint);\n                            }\n                            break;\n                        case QLineF::UnboundedIntersection:\n                            break;\n\n                    }\n                }\n\n                for(int k = 0;\n                    k < crossings.size();\n                    ++k)\n                {\n                    result.push_back(crossings[k]);\n                    if(isInside)\n                    {\n                        return result;\n                    }\n                }\n\n\n                if(isInside)\n                {\n                    result.push_back(polyline[i]);\n                }\n            }\n\n            return result;\n        }\n\n        QPolygonF\n        simplePolygonIntersection(const QPolygonF &polygon,\n                                  const QPainterPath &path)\n        {\n            QPainterPath pOther;\n            pOther.addPolygon(polygon);\n            return pOther.intersected(path).toFillPolygon();\n        }\n\n        cv::Point2d\n        calculateNadirPoint(const cv::Mat &fromWorldToNormImgTransform,\n                            const cv::Mat &_fromNormImgToWorldTransform)\n        {\n            // see https://bitbucket.org/hermandav/datafromsky/wiki/Nadir%20point%20calculation for explanation\n            // prepare params\n            cv::Mat fromNormImgToWorldTransform;\n            if(_fromNormImgToWorldTransform.empty())\n            {\n                fromNormImgToWorldTransform = fromWorldToNormImgTransform.inv();\n            }\n            else\n            {\n                fromNormImgToWorldTransform = _fromNormImgToWorldTransform;\n            }\n            // firstly, check, whether there is a horizon in image and world space\n            // horizon line is: (ax + by + c = 0)\n            double iA, iB, iC, wA,wB,wC;\n            if((!getHorizonFromTransformation(fromNormImgToWorldTransform,\n                                             iA,iB,iC)) ||\n               (!getHorizonFromTransformation(fromWorldToNormImgTransform,\n                                              wA, wB, wC)))\n            {\n                // there is no horizon, therefore, it is affine transform\n                // which means, camera is looking straigth down\n                cv::Vec3d pp(0,0,1);\n                cv::Vec3d result = cv::Mat(fromNormImgToWorldTransform * cv::Mat(pp));\n                return cv::Point2d(result(0) / result(2),\n                                   result(1) / result(2));\n            }\n\n            // so, there is a horizon\n            // check, whether PP is at horizon (ergo, 0 *a + 0 * b + c ?==? 0)\n            if(iC == 0)\n            {\n                // PP is at horizon\n                // so nadir is at intersection of horizon in world space and line that\n                // is projection of line that is perpendicular to image horizon and passes through PP\n\n                // get perpendicular line that goes through PP (0,0).\n                double perpA = -iB;\n                double perpB = iA;\n                double perpC = 0; // To cross 0,0, it must be that c = 0;\n\n                // transform this line to world (see Multiple View Geometry, equation (2.6))\n                cv::Vec3d perpLine(perpA, perpB, perpC);\n                cv::Vec3d worldPerpLine = cv::Mat(fromWorldToNormImgTransform.t() * cv::Mat(perpLine));\n\n                // find intersection (cross product)\n                cv::Vec3d worldHorizon(wA, wB, wC);\n                cv::Vec3d result = worldHorizon.cross(worldPerpLine);\n\n                // and that is nadir point\n                return cv::Point2d(result(0) / result(2),\n                                   result(1) / result(2));\n\n            }\n            else\n            {\n                // PP is not at horizon\n                // normal vector\n                cv::Point2d horizNormal(iA,\n                                        iB);\n                if(iC < 0)\n                {\n                    // flipping normal, if the line is on the other side of (0,0)\n                    horizNormal = horizNormal * (-1);\n                }\n\n                // normalises the length of the vector\n                horizNormal = horizNormal * (1.0 / cv::norm(horizNormal));\n\n                // distance of PP from horizon\n                double distPP2H = getDistanceFromLine(iA,iB,iC,\n                                                      0,0);\n\n                double distPP2NADIR = 1 / distPP2H;\n                cv::Point2d nadirImage = horizNormal * distPP2NADIR;\n\n                // now transform the image to world coordinates\n                cv::Vec3d nadirImageVec(nadirImage.x,\n                                        nadirImage.y,\n                                        1);\n                cv::Vec3d result = cv::Mat(fromNormImgToWorldTransform * cv::Mat(nadirImageVec));\n\n                // and that is nadir point\n                return cv::Point2d(result(0) / result(2),\n                                   result(1) / result(2));\n            }\n\n        }\n\n        double\n        getDistanceFromLine(double a, double b, double c,\n                            double x0, double y0)\n        {\n            // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line\n            return (std::abs(a * x0 + b * y0 + c)/ (std::sqrt(a*a + b*b)));\n        }\n\n        cv::Mat\n        composeProjectionMatrix(const cv::Mat &cameraMatrix,\n                                const cv::Mat &rotation,\n                                const cv::Point3d &translation,\n                                const cv::Mat &residualTransform,\n                                bool leftHandedCS)\n        {\n            cv::Mat rotInv;\n            cv::Point3d translInv;\n            invertTranslationAndRotation(translation, rotation,\n                                         translInv, rotInv);\n\n            cv::Mat Rt(3,4, CV_64FC1);\n            rotInv.copyTo(Rt.colRange(0,3));\n            Rt.at<double>(0,3) = translInv.x;\n            Rt.at<double>(1,3) = translInv.y;\n            Rt.at<double>(2,3) = translInv.z;\n\n            if(!residualTransform.empty())\n            {\n                Rt = residualTransform * Rt;\n            }\n\n            cv::Mat P = cameraMatrix * Rt;\n\n\n            if(leftHandedCS)\n            {\n                // we assume that final image is flipped\n                P.row(1) = P.row(1) * (-1);\n            }\n\n            return P;\n        }\n\n        cv::Mat\n        getResidualTransform(const cv::Mat &cameraMatrixInv,\n                             const cv::Mat &rotation,\n                             const cv::Point3d &translation,\n                             const cv::Mat &homography,\n                             bool leftHandedCS)\n        {\n            cv::Mat rotInv;\n            cv::Point3d translInv;\n            invertTranslationAndRotation(translation, rotation,\n                                         translInv, rotInv);\n\n            cv::Mat cleanH(3,3, CV_64FC1);\n            rotInv.col(0).copyTo(cleanH.col(0));\n            rotInv.col(1).copyTo(cleanH.col(1));\n            cleanH.at<double>(0,2) = translInv.x;\n            cleanH.at<double>(1,2) = translInv.y;\n            cleanH.at<double>(2,2) = translInv.z;\n\n\n            cv::Mat dirtyH = homography.clone();\n            if(leftHandedCS)\n            {\n                // we assume that final image is flipped\n                dirtyH.row(1) = dirtyH.row(1) * (-1);\n            }\n            dirtyH = cameraMatrixInv * dirtyH;\n\n            return cleanH.inv() * dirtyH;\n\n        }\n\n        double calculatePolygonArea(const QPolygonF &polygon)\n        {\n            if(polygon.size() < 3)\n            {\n                 return 0;\n            }\n            // based on http://alienryderflex.com/polygon_area/\n            double area = 0;\n            int i, j=polygon.size()-1  ;\n\n            for (i=0; i<polygon.size(); i++)\n            {\n                area+=(polygon[j].x()+polygon[i].x())\n                      *(polygon[j].y()-polygon[i].y());\n                j=i;\n            }\n\n            return std::abs(area*0.5);\n        }\n\n        cv::Mat createTranslationTransform(double x, double y)\n        {\n            cv::Mat result = cv::Mat::eye(3,3, CV_64FC1);\n            result.at<double>(0,2) = x;\n            result.at<double>(1,2) = y;\n\n            return result;\n\n        }\n\n        cv::Mat createRotationTransform(double angle, double xPivot, double yPivot)\n        {\n            if((xPivot == 0) && (yPivot == 0))\n            {\n                return createRotationTransform(angle);\n            }\n            else\n            {\n                return createTranslationTransform(xPivot, yPivot) *\n                        createRotationTransform(angle) *\n                        createTranslationTransform(-xPivot, -yPivot);\n            }\n        }\n\n        cv::Mat createRotationTransform(double angle)\n        {\n            Eigen::Isometry2d rotationFix = Eigen::Isometry2d::Identity();\n            rotationFix.rotate(angle);\n            cv::Mat result;\n            cv::eigen2cv(rotationFix.matrix(),\n                         result);\n\n            return result;\n\n        }\n\n        cv::Mat\n        createScaleTransform(double xScale,\n                             double yScale)\n        {\n            cv::Mat result = cv::Mat::eye(3,3, CV_64FC1);\n            result.at<double>(0,0) = xScale;\n            result.at<double>(1,1) = yScale;\n\n            return result;\n        }\n\n        QPointF\n        calculatePrespectiveRectangleCenter(const QPolygonF &poly)\n        {\n            QLineF diag0(poly[0],\n                    poly[2]);\n            QLineF diag1(poly[1],\n                    poly[3]);\n\n            QPointF result;\n            diag0.intersect(diag1, &result);\n            return result;\n        }\n\n\n\n//        void\n//        calculateGridPoints(const cv::Point2d &pt1,\n//                            const cv::Point2d &pt2,\n//                            std::vector<cv::Point2d> &gridPoints)\n//        {\n//            gridPoints.clear();\n//            if(pt1 == pt2)\n//            {\n//                return;\n//            }\n//            else\n//            {\n//                double diffX = pt2.x - pt1.x;\n//                double diffY = pt2.y - pt1.y;\n//                double absDiffX = abs(diffX);\n//                double absDiffY = abs(diffY);\n\n//                if(absDiffX > absDiffY)\n//                {\n//                    double deltaY = diffY / diffX;\n//                    double firstXStep;\n//                    double deltaX;\n//                    if(diffX > 0)\n//                    {\n//                        deltaX = 1;\n//                        firstXStep = std::ceil(pt1.x) - pt1.x;\n//                    }\n//                    else\n//                    {\n//                        deltaX = -1;\n//                        firstXStep = std::floor(pt1.x) - pt1.x;\n//                    }\n\n//                    if(abs(firstXStep) < 0.5)\n//                    {\n//                        firstXStep += deltaX;\n//                    }\n\n//                    double xF = firstXStep;\n//                    double yF = firstXStep * deltaY;\n//                    double xEnd = qRound(pt2.x) - 0.5 * deltaX;\n//                    for(double x = qRound(pt1.x + deltaX);\n//                        x < xEnd;\n//                        x += deltaX)\n//                    {\n\n\n//                        xF += deltaX;\n//                        yF += deltaY;\n//                    }\n\n\n//                }\n//            }\n//        }\n\n    } // namespace geometry\n} // namespace rce\n", "meta": {"hexsha": "de51c10dcc19b7e684509cb50bb480dfee52d194", "size": 51010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RCE/Geometry/rce/geometry/RGeometry.cpp", "max_stars_repo_name": "Timie/PositionEstimationAccuracy", "max_stars_repo_head_hexsha": "9e88597c271ccc2a1a8442db6fa62236b7178296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:46:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-15T09:46:40.000Z", "max_issues_repo_path": "src/RCE/Geometry/rce/geometry/RGeometry.cpp", "max_issues_repo_name": "Timie/PositionEstimationAccuracy", "max_issues_repo_head_hexsha": "9e88597c271ccc2a1a8442db6fa62236b7178296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RCE/Geometry/rce/geometry/RGeometry.cpp", "max_forks_repo_name": "Timie/PositionEstimationAccuracy", "max_forks_repo_head_hexsha": "9e88597c271ccc2a1a8442db6fa62236b7178296", "max_forks_repo_licenses": ["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.8487060385, "max_line_length": 170, "alphanum_fraction": 0.3936875123, "num_tokens": 10698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.029312232447288752, "lm_q1q2_score": 0.014541617645117218}}
{"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_svx.hxx\"\n#include \"svx/EnhancedCustomShape2d.hxx\"\n#include <rtl/ustring.hxx>\n#include <tools/fract.hxx>\n\n// Makes parser a static resource,\n// we're synchronized externally.\n// But watch out, the parser might have\n// state not visible to this code!\n\n#define BOOST_SPIRIT_SINGLE_GRAMMAR_INSTANCE\n#if defined(VERBOSE) && defined(DBG_UTIL)\n#include <typeinfo>\n#define BOOST_SPIRIT_DEBUG\n#endif\n#include <boost/spirit/include/classic_core.hpp>\n\n#if (OSL_DEBUG_LEVEL > 0)\n#include <iostream>\n#endif\n#include <functional>\n#include <algorithm>\n#include <stack>\n\n#include <math.h> // fabs, sqrt, sin, cos, tan, atan, atan2\nusing namespace EnhancedCustomShape;\nusing namespace com::sun::star;\nusing namespace com::sun::star::drawing;\n\nvoid EnhancedCustomShape::FillEquationParameter( const EnhancedCustomShapeParameter& rSource, const sal_Int32 nDestPara, EnhancedCustomShapeEquation& rDest )\n{\n\tsal_Int32 nValue = 0;\n\tif ( rSource.Value.getValueTypeClass() == uno::TypeClass_DOUBLE )\n\t{\n\t\tdouble fValue;\n\t\tif ( rSource.Value >>= fValue )\n\t\t\tnValue = (sal_Int32)fValue;\n\t}\n\telse\n\t\trSource.Value >>= nValue;\n\n\tswitch( rSource.Type )\n\t{\n\t\tcase com::sun::star::drawing::EnhancedCustomShapeParameterType::EQUATION :\n\t\t{\n\t\t\tif ( nValue & 0x40000000 )\n\t\t\t{\n\t\t\t\tnValue ^= 0x40000000;\n\t\t\t\trDest.nOperation |= 0x20000000 << nDestPara;\t// the bit is indicating that this value has to be adjusted later\n\t\t\t}\n\t\t\tnValue |= 0x400;\n\t\t}\n\t\tbreak;\n\t\tcase com::sun::star::drawing::EnhancedCustomShapeParameterType::ADJUSTMENT : nValue += DFF_Prop_adjustValue; break;\n\t\tcase com::sun::star::drawing::EnhancedCustomShapeParameterType::BOTTOM : nValue = DFF_Prop_geoBottom; break;\n\t\tcase com::sun::star::drawing::EnhancedCustomShapeParameterType::RIGHT : nValue = DFF_Prop_geoRight; break;\n\t\tcase com::sun::star::drawing::EnhancedCustomShapeParameterType::TOP : nValue = DFF_Prop_geoTop;\tbreak;\n\t\tcase com::sun::star::drawing::EnhancedCustomShapeParameterType::LEFT : nValue = DFF_Prop_geoLeft; break;\n\t}\n\tif ( rSource.Type != com::sun::star::drawing::EnhancedCustomShapeParameterType::NORMAL )\n\t\trDest.nOperation |= ( 0x2000 << nDestPara );\n\trDest.nPara[ nDestPara ] = nValue;\n}\n\nExpressionNode::~ExpressionNode()\n{}\n\nnamespace\n{\n\n//////////////////////\n//////////////////////\n// EXPRESSION NODES\n//////////////////////\n//////////////////////\nclass ConstantValueExpression : public ExpressionNode\n{\n    double\tmaValue;\n\npublic:\n\n\tConstantValueExpression( double rValue ) :\n        maValue( rValue )\n    {\n    }\n    virtual double operator()() const\n    {\n        return maValue;\n    }\n    virtual bool isConstant() const\n    {\n        return true;\n    }\n\tvirtual ExpressionFunct getType() const\n\t{\n\t\treturn FUNC_CONST;\n\t}\n\tvirtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /* pOptionalArg */, sal_uInt32 /* nFlags */ )\n\t{\n\t\tEnhancedCustomShapeParameter aRet;\n\t\tFraction aFract( maValue );\n\t\tif ( aFract.GetDenominator() == 1 )\n\t\t{\n\t\t\taRet.Type = EnhancedCustomShapeParameterType::NORMAL;\n\t\t\taRet.Value <<= (sal_Int32)aFract.GetNumerator();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEnhancedCustomShapeEquation aEquation;\n\t\t\taEquation.nOperation = 1;\n\t\t\taEquation.nPara[ 0 ] = 1;\n\t\t\taEquation.nPara[ 1 ] = (sal_Int16)aFract.GetNumerator();\n\t\t\taEquation.nPara[ 2 ] = (sal_Int16)aFract.GetDenominator();\n\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\trEquations.push_back( aEquation );\n\t\t}\n\t\treturn aRet;\n\t}\n};\n\nclass AdjustmentExpression : public ExpressionNode\n{\n    sal_Int32\t\t\t\t\t\tmnIndex;\n\tconst EnhancedCustomShape2d&\tmrCustoShape;\n\npublic:\n\n\tAdjustmentExpression( const EnhancedCustomShape2d& rCustoShape, sal_Int32 nIndex )\n\t: mnIndex\t\t( nIndex )\n\t, mrCustoShape( rCustoShape )\n\n    {\n    }\n    virtual double operator()() const\n    {\n\t\treturn mrCustoShape.GetAdjustValueAsDouble( mnIndex );\n    }\n    virtual bool isConstant() const\n    {\n        return false;\n    }\n\tvirtual ExpressionFunct getType() const\n\t{\n\t\treturn ENUM_FUNC_ADJUSTMENT;\n\t}\n\tvirtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& /*rEquations*/, ExpressionNode* /*pOptionalArg*/, sal_uInt32 /*nFlags*/ )\n\t{\n\t\tEnhancedCustomShapeParameter aRet;\n\t\taRet.Type = EnhancedCustomShapeParameterType::ADJUSTMENT;\n\t\taRet.Value <<= mnIndex;\n\t\treturn aRet;\n\t}\n};\n\nclass EquationExpression : public ExpressionNode\n{\n    sal_Int32\t\t\t\t\t\tmnIndex;\n\tconst EnhancedCustomShape2d&\tmrCustoShape;\n\npublic:\n\n\tEquationExpression( const EnhancedCustomShape2d& rCustoShape, sal_Int32 nIndex )\n\t\t: mnIndex\t\t( nIndex )\n        , mrCustoShape( rCustoShape )\n    {\n    }\n    virtual double operator()() const\n    {\n\t\treturn mrCustoShape.GetEquationValueAsDouble( mnIndex );\n    }\n    virtual bool isConstant() const\n    {\n        return false;\n    }\n\tvirtual ExpressionFunct getType() const\n\t{\n\t\treturn ENUM_FUNC_EQUATION;\n\t}\n\tvirtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& /*rEquations*/, ExpressionNode* /*pOptionalArg*/, sal_uInt32 /*nFlags*/ )\n\t{\n\t\tEnhancedCustomShapeParameter aRet;\n\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\taRet.Value <<= mnIndex | 0x40000000;\t\t\t\t\t\t// the bit is indicating that this equation needs to be adjusted later\n\t\treturn aRet;\n\t}\n};\n\nclass EnumValueExpression : public ExpressionNode\n{\n    const ExpressionFunct\t\t\tmeFunct;\n\tconst EnhancedCustomShape2d&\tmrCustoShape;\n\npublic:\n\n\tEnumValueExpression( const EnhancedCustomShape2d& rCustoShape, const ExpressionFunct eFunct )\n\t\t: meFunct\t\t( eFunct )\n\t\t, mrCustoShape\t( rCustoShape )\n    {\n    }\n\tstatic double getValue( const EnhancedCustomShape2d& rCustoShape, const ExpressionFunct eFunc )\n\t{\n\t\tEnhancedCustomShape2d::EnumFunc eF;\n\t\tswitch( eFunc )\n\t\t{\n\t\t\tcase ENUM_FUNC_PI :\t\t\teF = EnhancedCustomShape2d::ENUM_FUNC_PI; break;\n\t\t\tcase ENUM_FUNC_LEFT :\t\teF = EnhancedCustomShape2d::ENUM_FUNC_LEFT; break;\n\t\t\tcase ENUM_FUNC_TOP :\t\teF = EnhancedCustomShape2d::ENUM_FUNC_TOP; break;\n\t\t\tcase ENUM_FUNC_RIGHT :\t\teF = EnhancedCustomShape2d::ENUM_FUNC_RIGHT; break;\n\t\t\tcase ENUM_FUNC_BOTTOM :\t\teF = EnhancedCustomShape2d::ENUM_FUNC_BOTTOM; break;\n\t\t\tcase ENUM_FUNC_XSTRETCH :\teF = EnhancedCustomShape2d::ENUM_FUNC_XSTRETCH; break;\n\t\t\tcase ENUM_FUNC_YSTRETCH :\teF = EnhancedCustomShape2d::ENUM_FUNC_YSTRETCH; break;\n\t\t\tcase ENUM_FUNC_HASSTROKE :\teF = EnhancedCustomShape2d::ENUM_FUNC_HASSTROKE; break;\n\t\t\tcase ENUM_FUNC_HASFILL :\teF = EnhancedCustomShape2d::ENUM_FUNC_HASFILL; break;\n\t\t\tcase ENUM_FUNC_WIDTH :\t\teF = EnhancedCustomShape2d::ENUM_FUNC_WIDTH; break;\n\t\t\tcase ENUM_FUNC_HEIGHT :\t\teF = EnhancedCustomShape2d::ENUM_FUNC_HEIGHT; break;\n\t\t\tcase ENUM_FUNC_LOGWIDTH :\teF = EnhancedCustomShape2d::ENUM_FUNC_LOGWIDTH; break;\n\t\t\tcase ENUM_FUNC_LOGHEIGHT :\teF = EnhancedCustomShape2d::ENUM_FUNC_LOGHEIGHT; break;\n\n\t\t\tdefault :\n\t\t\t\treturn 0.0;\n\t\t}\n\t\treturn rCustoShape.GetEnumFunc( eF );\n\t}\n    virtual double operator()() const\n    {\n\t\treturn getValue( mrCustoShape, meFunct );\n    }\n    virtual bool isConstant() const\n    {\n\t\treturn false;\n    }\n\tvirtual ExpressionFunct getType() const\n\t{\n\t\treturn meFunct;\n\t}\n\tvirtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /*pOptionalArg*/, sal_uInt32 nFlags )\n\t{\n\t\tEnhancedCustomShapeParameter aRet;\n\n\t\tsal_Int32 nDummy = 1;\n\t\taRet.Value <<= nDummy;\n\n\t\tswitch( meFunct )\n\t\t{\n\t\t\tcase ENUM_FUNC_WIDTH :\t// TODO: do not use this as constant value\n\t\t\tcase ENUM_FUNC_HEIGHT :\n\t\t\tcase ENUM_FUNC_LOGWIDTH :\n\t\t\tcase ENUM_FUNC_LOGHEIGHT :\n\t\t\tcase ENUM_FUNC_PI :\n\t\t\t{\n\t\t\t\tConstantValueExpression aConstantValue( getValue( mrCustoShape, meFunct ) );\n\t\t\t\taRet = aConstantValue.fillNode( rEquations, NULL, nFlags );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase ENUM_FUNC_LEFT :\taRet.Type = EnhancedCustomShapeParameterType::LEFT; break;\n\t\t\tcase ENUM_FUNC_TOP :\taRet.Type = EnhancedCustomShapeParameterType::TOP; break;\n\t\t\tcase ENUM_FUNC_RIGHT :\taRet.Type = EnhancedCustomShapeParameterType::RIGHT; break;\n\t\t\tcase ENUM_FUNC_BOTTOM :\taRet.Type = EnhancedCustomShapeParameterType::BOTTOM; break;\n\n\t\t\t// not implemented so far\n\t\t\tcase ENUM_FUNC_XSTRETCH :\n\t\t\tcase ENUM_FUNC_YSTRETCH :\n\t\t\tcase ENUM_FUNC_HASSTROKE :\n\t\t\tcase ENUM_FUNC_HASFILL : aRet.Type = EnhancedCustomShapeParameterType::NORMAL; break;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\treturn aRet;\n\t}\n};\n\n/** ExpressionNode implementation for unary\n    function over one ExpressionNode\n    */\nclass UnaryFunctionExpression : public ExpressionNode\n{\n    const ExpressionFunct\tmeFunct;\n    ExpressionNodeSharedPtr\tmpArg;\n\npublic:\n    UnaryFunctionExpression( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rArg ) :\n        meFunct( eFunct ),\n        mpArg( rArg )\n    {\n    }\n\tstatic double getValue( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rArg )\n\t{\n\t\tdouble fRet = 0;\n\t\tswitch( eFunct )\n\t\t{\n\t\t\tcase UNARY_FUNC_ABS : fRet = fabs( (*rArg)() ); break;\n\t\t\tcase UNARY_FUNC_SQRT: fRet = sqrt( (*rArg)() ); break;\n\t\t\tcase UNARY_FUNC_SIN : fRet = sin( (*rArg)() );  break;\n\t\t\tcase UNARY_FUNC_COS : fRet = cos( (*rArg)() );  break;\n\t\t\tcase UNARY_FUNC_TAN : fRet = tan( (*rArg)() );  break;\n\t\t\tcase UNARY_FUNC_ATAN: fRet = atan( (*rArg)() ); break;\n\t\t\tcase UNARY_FUNC_NEG : fRet = ::std::negate<double>()( (*rArg)() ); break;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\treturn fRet;\n\t}\n    virtual double operator()() const\n    {\n\t\treturn getValue( meFunct, mpArg );\n    }\n    virtual bool isConstant() const\n    {\n        return mpArg->isConstant();\n    }\n\tvirtual ExpressionFunct getType() const\n\t{\n\t\treturn meFunct;\n\t}\n\tvirtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* pOptionalArg, sal_uInt32 nFlags )\n\t{\n\t\tEnhancedCustomShapeParameter aRet;\n\t\tswitch( meFunct )\n\t\t{\n\t\t\tcase UNARY_FUNC_ABS :\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 3;\n\t\t\t\tFillEquationParameter( mpArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase UNARY_FUNC_SQRT:\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 13;\n\t\t\t\tFillEquationParameter( mpArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase UNARY_FUNC_SIN :\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 9;\n\t\t\t\tif ( pOptionalArg )\n\t\t\t\t\tFillEquationParameter( pOptionalArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\telse\n\t\t\t\t\taEquation.nPara[ 0 ] = 1;\n\n\t\t\t\tEnhancedCustomShapeParameter aSource( mpArg->fillNode( rEquations, NULL, nFlags | EXPRESSION_FLAG_SUMANGLE_MODE ) );\n\t\t\t\tif ( aSource.Type == EnhancedCustomShapeParameterType::NORMAL )\n\t\t\t\t{\t// sumangle needed :-(\n\t\t\t\t\tEnhancedCustomShapeEquation\t_aEquation;\n\t\t\t\t\t_aEquation.nOperation |= 0xe;\t// sumangle\n\t\t\t\t\tFillEquationParameter( aSource, 1, _aEquation );\n\t\t\t\t\taSource.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\taSource.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\trEquations.push_back( _aEquation );\n\t\t\t\t}\n\t\t\t\tFillEquationParameter( aSource, 1, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase UNARY_FUNC_COS :\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 10;\n\t\t\t\tif ( pOptionalArg )\n\t\t\t\t\tFillEquationParameter( pOptionalArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\telse\n\t\t\t\t\taEquation.nPara[ 0 ] = 1;\n\n\t\t\t\tEnhancedCustomShapeParameter aSource( mpArg->fillNode( rEquations, NULL, nFlags | EXPRESSION_FLAG_SUMANGLE_MODE ) );\n\t\t\t\tif ( aSource.Type == EnhancedCustomShapeParameterType::NORMAL )\n\t\t\t\t{\t// sumangle needed :-(\n\t\t\t\t\tEnhancedCustomShapeEquation\taTmpEquation;\n\t\t\t\t\taTmpEquation.nOperation |= 0xe;\t// sumangle\n\t\t\t\t\tFillEquationParameter( aSource, 1, aTmpEquation );\n\t\t\t\t\taSource.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\taSource.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\trEquations.push_back( aTmpEquation );\n\t\t\t\t}\n\t\t\t\tFillEquationParameter( aSource, 1, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase UNARY_FUNC_TAN :\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 16;\n\t\t\t\tif ( pOptionalArg )\n\t\t\t\t\tFillEquationParameter( pOptionalArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\telse\n\t\t\t\t\taEquation.nPara[ 0 ] = 1;\n\n\t\t\t\tEnhancedCustomShapeParameter aSource( mpArg->fillNode( rEquations, NULL, nFlags | EXPRESSION_FLAG_SUMANGLE_MODE ) );\n\t\t\t\tif ( aSource.Type == EnhancedCustomShapeParameterType::NORMAL )\n\t\t\t\t{\t// sumangle needed :-(\n\t\t\t\t\tEnhancedCustomShapeEquation\taTmpEquation;\n\t\t\t\t\taTmpEquation.nOperation |= 0xe;\t// sumangle\n\t\t\t\t\tFillEquationParameter( aSource, 1, aTmpEquation );\n\t\t\t\t\taSource.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\taSource.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\trEquations.push_back( aTmpEquation );\n\t\t\t\t}\n\t\t\t\tFillEquationParameter( aSource, 1, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase UNARY_FUNC_ATAN:\n\t\t\t{\n// TODO:\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::NORMAL;\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase UNARY_FUNC_NEG:\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 1;\n\t\t\t\taEquation.nPara[ 1 ] = -1;\n\t\t\t\taEquation.nPara[ 2 ] = 1;\n\t\t\t\tFillEquationParameter( mpArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\treturn aRet;\n\t}\n};\n\n/** ExpressionNode implementation for unary\n    function over two ExpressionNodes\n    */\nclass BinaryFunctionExpression : public ExpressionNode\n{\n    const ExpressionFunct\tmeFunct;\n    ExpressionNodeSharedPtr\tmpFirstArg;\n    ExpressionNodeSharedPtr\tmpSecondArg;\n\npublic:\n\n    BinaryFunctionExpression( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rFirstArg, const ExpressionNodeSharedPtr& rSecondArg ) :\n        meFunct( eFunct ),\n        mpFirstArg( rFirstArg ),\n        mpSecondArg( rSecondArg )\n    {\n    }\n\tstatic double getValue( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rFirstArg, const ExpressionNodeSharedPtr& rSecondArg )\n\t{\n\t\tdouble fRet = 0;\n\t\tswitch( eFunct )\n\t\t{\n\t\t\tcase BINARY_FUNC_PLUS : fRet = (*rFirstArg)() + (*rSecondArg)(); break;\n\t\t\tcase BINARY_FUNC_MINUS: fRet = (*rFirstArg)() - (*rSecondArg)(); break;\n\t\t\tcase BINARY_FUNC_MUL :  fRet = (*rFirstArg)() * (*rSecondArg)(); break;\n\t\t\tcase BINARY_FUNC_DIV :  fRet = (*rFirstArg)() / (*rSecondArg)(); break;\n\t\t\tcase BINARY_FUNC_MIN :  fRet = ::std::min( (*rFirstArg)(), (*rSecondArg)() ); break;\n\t\t\tcase BINARY_FUNC_MAX :  fRet = ::std::max( (*rFirstArg)(), (*rSecondArg)() ); break;\n\t\t\tcase BINARY_FUNC_ATAN2: fRet = atan2( (*rFirstArg)(), (*rSecondArg)() ); break;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\treturn fRet;\n\t}\n    virtual double operator()() const\n    {\n\t\treturn getValue( meFunct, mpFirstArg, mpSecondArg );\n    }\n    virtual bool isConstant() const\n    {\n\t\treturn mpFirstArg->isConstant() && mpSecondArg->isConstant();\n    }\n\tvirtual ExpressionFunct getType() const\n\t{\n\t\treturn meFunct;\n\t}\n\tvirtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /*pOptionalArg*/, sal_uInt32 nFlags )\n\t{\n\t\tEnhancedCustomShapeParameter aRet;\n\t\tswitch( meFunct )\n\t\t{\n\t\t\tcase BINARY_FUNC_PLUS :\n\t\t\t{\n\t\t\t\tif ( nFlags & EXPRESSION_FLAG_SUMANGLE_MODE )\n\t\t\t\t{\n\t\t\t\t\tif ( mpFirstArg->getType() == ENUM_FUNC_ADJUSTMENT )\n\t\t\t\t\t{\n\t\t\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\t\t\taEquation.nOperation |= 0xe;\t// sumangle\n\t\t\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );\n\t\t\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\t\trEquations.push_back( aEquation );\n\t\t\t\t\t}\n\t\t\t\t\telse if ( mpSecondArg->getType() == ENUM_FUNC_ADJUSTMENT )\n\t\t\t\t\t{\n\t\t\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\t\t\taEquation.nOperation |= 0xe;\t// sumangle\n\t\t\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );\n\t\t\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\t\trEquations.push_back( aEquation );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tEnhancedCustomShapeEquation\taSumangle1;\n\t\t\t\t\t\taSumangle1.nOperation |= 0xe;\t// sumangle\n\t\t\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags &~EXPRESSION_FLAG_SUMANGLE_MODE ), 1, aSumangle1 );\n\t\t\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\t\trEquations.push_back( aSumangle1 );\n\n\t\t\t\t\t\tEnhancedCustomShapeEquation\taSumangle2;\n\t\t\t\t\t\taSumangle2.nOperation |= 0xe;\t// sumangle\n\t\t\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags &~EXPRESSION_FLAG_SUMANGLE_MODE ), 1, aSumangle2 );\n\t\t\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\t\trEquations.push_back( aSumangle2 );\n\n\t\t\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\t\t\taEquation.nOperation |= 0;\n\t\t\t\t\t\taEquation.nPara[ 0 ] = ( rEquations.size() - 2 ) | 0x400;\n\t\t\t\t\t\taEquation.nPara[ 1 ] = ( rEquations.size() - 1 ) | 0x400;\n\t\t\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\t\trEquations.push_back( aEquation );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsal_Bool bFirstIsEmpty = mpFirstArg->isConstant() && ( (*mpFirstArg)() == 0 );\n\t\t\t\t\tsal_Bool bSecondIsEmpty = mpSecondArg->isConstant() && ( (*mpSecondArg)() == 0 );\n\n\t\t\t\t\tif ( bFirstIsEmpty )\n\t\t\t\t\t\taRet = mpSecondArg->fillNode( rEquations, NULL, nFlags );\n\t\t\t\t\telse if ( bSecondIsEmpty )\n\t\t\t\t\t\taRet = mpFirstArg->fillNode( rEquations, NULL, nFlags );\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\t\t\taEquation.nOperation |= 0;\n\t\t\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );\n\t\t\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\t\trEquations.push_back( aEquation );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase BINARY_FUNC_MINUS:\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 0;\n\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 2, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase BINARY_FUNC_MUL :\n\t\t\t{\n\t\t\t\t// in the dest. format the cos function is using integer as result :-(\n\t\t\t\t// so we can't use the generic algorithm\n\t\t\t\tif ( ( mpFirstArg->getType() == UNARY_FUNC_SIN ) || ( mpFirstArg->getType() == UNARY_FUNC_COS ) || ( mpFirstArg->getType() == UNARY_FUNC_TAN ) )\n\t\t\t\t\taRet = mpFirstArg->fillNode( rEquations, mpSecondArg.get(), nFlags );\n\t\t\t\telse if ( ( mpSecondArg->getType() == UNARY_FUNC_SIN ) || ( mpSecondArg->getType() == UNARY_FUNC_COS ) || ( mpSecondArg->getType() == UNARY_FUNC_TAN ) )\n\t\t\t\t\taRet = mpSecondArg->fillNode( rEquations, mpFirstArg.get(), nFlags );\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif ( mpFirstArg->isConstant() && (*mpFirstArg)() == 1 )\n\t\t\t\t\t\taRet = mpSecondArg->fillNode( rEquations, NULL, nFlags );\n\t\t\t\t\telse if ( mpSecondArg->isConstant() && (*mpSecondArg)() == 1 )\n\t\t\t\t\t\taRet = mpFirstArg->fillNode( rEquations, NULL, nFlags );\n\t\t\t\t\telse if ( ( mpFirstArg->getType() == BINARY_FUNC_DIV )\t\t// don't care of (pi/180)\n\t\t\t\t\t\t&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpFirstArg.get())->mpFirstArg.get())->getType() == ENUM_FUNC_PI )\n\t\t\t\t\t\t&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpFirstArg.get())->mpSecondArg.get())->getType() == FUNC_CONST ) )\n\t\t\t\t\t{\n\t\t\t\t\t\taRet = mpSecondArg->fillNode( rEquations, NULL, nFlags );\n\t\t\t\t\t}\n\t\t\t\t\telse if ( ( mpSecondArg->getType() == BINARY_FUNC_DIV )\t\t// don't care of (pi/180)\n\t\t\t\t\t\t&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpSecondArg.get())->mpFirstArg.get())->getType() == ENUM_FUNC_PI )\n\t\t\t\t\t\t&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpSecondArg.get())->mpSecondArg.get())->getType() == FUNC_CONST ) )\n\t\t\t\t\t{\n\t\t\t\t\t\taRet = mpFirstArg->fillNode( rEquations, NULL, nFlags );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\t\t\taEquation.nOperation |= 1;\n\t\t\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );\n\t\t\t\t\t\taEquation.nPara[ 2 ] = 1;\n\t\t\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\t\t\trEquations.push_back( aEquation );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase BINARY_FUNC_DIV :\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 1;\n\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\taEquation.nPara[ 1 ] = 1;\n\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 2, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase BINARY_FUNC_MIN :\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 4;\n\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase BINARY_FUNC_MAX :\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 5;\n\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase BINARY_FUNC_ATAN2:\n\t\t\t{\n\t\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\t\taEquation.nOperation |= 8;\n\t\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );\n\t\t\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\t\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t\t\trEquations.push_back( aEquation );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\treturn aRet;\n\t}\n};\n\nclass IfExpression : public ExpressionNode\n{\n    ExpressionNodeSharedPtr\tmpFirstArg;\n    ExpressionNodeSharedPtr mpSecondArg;\n    ExpressionNodeSharedPtr mpThirdArg;\n\npublic:\n\n\tIfExpression( const ExpressionNodeSharedPtr& rFirstArg,\n\t\t\t\t  const ExpressionNodeSharedPtr& rSecondArg,\n\t\t\t\t  const ExpressionNodeSharedPtr& rThirdArg ) :\n        mpFirstArg(  rFirstArg ),\n        mpSecondArg( rSecondArg ),\n\t\tmpThirdArg(  rThirdArg )\n    {\n    }\n    virtual bool isConstant() const\n    {\n        return\n            mpFirstArg->isConstant() &&\n            mpSecondArg->isConstant() &&\n\t\t\tmpThirdArg->isConstant();\n    }\n    virtual double operator()() const\n    {\n\t\treturn (*mpFirstArg)() > 0 ? (*mpSecondArg)() : (*mpThirdArg)();\n    }\n\tvirtual ExpressionFunct getType() const\n\t{\n\t\treturn TERNARY_FUNC_IF;\n\t}\n\tvirtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /*pOptionalArg*/, sal_uInt32 nFlags )\n\t{\n\t\tEnhancedCustomShapeParameter aRet;\n\t\taRet.Type = EnhancedCustomShapeParameterType::EQUATION;\n\t\taRet.Value <<= (sal_Int32)rEquations.size();\n\t\t{\n\t\t\tEnhancedCustomShapeEquation\taEquation;\n\t\t\taEquation.nOperation |= 6;\n\t\t\tFillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );\n\t\t\tFillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags  ), 1, aEquation );\n\t\t\tFillEquationParameter( mpThirdArg->fillNode( rEquations, NULL, nFlags ), 2, aEquation );\n\t\t\trEquations.push_back( aEquation );\n\t\t}\n\t\treturn aRet;\n\t}\n};\n\n////////////////////////\n////////////////////////\n// FUNCTION PARSER\n////////////////////////\n////////////////////////\n\ntypedef const sal_Char* StringIteratorT;\n\nstruct ParserContext\n{\n    typedef ::std::stack< ExpressionNodeSharedPtr > OperandStack;\n\n    // stores a stack of not-yet-evaluated operands. This is used\n    // by the operators (i.e. '+', '*', 'sin' etc.) to pop their\n    // arguments from. If all arguments to an operator are constant,\n    // the operator pushes a precalculated result on the stack, and\n    // a composite ExpressionNode otherwise.\n    OperandStack\t\t\t\tmaOperandStack;\n\n\tconst EnhancedCustomShape2d* mpCustoShape;\n\n};\n\ntypedef ::boost::shared_ptr< ParserContext > ParserContextSharedPtr;\n\n/** Generate apriori constant value\n    */\n\nclass ConstantFunctor\n{\n    const double\t\t\t\t\tmnValue;\n    ParserContextSharedPtr\t\t\tmpContext;\n\npublic:\n\n\tConstantFunctor( double rValue, const ParserContextSharedPtr& rContext ) :\n        mnValue( rValue ),\n        mpContext( rContext )\n\t{\n\t}\n    void operator()( StringIteratorT /*rFirst*/, StringIteratorT /*rSecond*/ ) const\n    {\n        mpContext->maOperandStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( mnValue ) ) );\n    }\n};\n\n/** Generate parse-dependent-but-then-constant value\n    */\nclass DoubleConstantFunctor\n{\n    ParserContextSharedPtr\tmpContext;\n\npublic:\n    DoubleConstantFunctor( const ParserContextSharedPtr& rContext ) :\n        mpContext( rContext )\n    {\n    }\n    void operator()( double n ) const\n    {\n        mpContext->maOperandStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( n ) ) );\n\t}\n};\n\nclass EnumFunctor\n{\n\tconst ExpressionFunct\t\t\tmeFunct;\n    double\t\t\t\t\t\t\tmnValue;\n    ParserContextSharedPtr\t\t\tmpContext;\n\npublic:\n\n\tEnumFunctor( const ExpressionFunct eFunct, const ParserContextSharedPtr& rContext )\n\t: meFunct( eFunct )\n\t, mnValue( 0 )\n\t, mpContext( rContext )\n\t{\n\t}\n    void operator()( StringIteratorT rFirst, StringIteratorT rSecond ) const\n    {\n\t\t/*double nVal = mnValue;*/\n\t\tswitch( meFunct )\n\t\t{\n\t\t\tcase ENUM_FUNC_ADJUSTMENT :\n\t\t\t{\n\t\t\t\trtl::OUString aVal( rFirst + 1, rSecond - rFirst, RTL_TEXTENCODING_UTF8 );\n\t\t\t\tmpContext->maOperandStack.push( ExpressionNodeSharedPtr( new AdjustmentExpression( *mpContext->mpCustoShape, aVal.toInt32() ) ) );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase ENUM_FUNC_EQUATION :\n\t\t\t\t{\n\t\t\t\trtl::OUString aVal( rFirst + 1, rSecond - rFirst, RTL_TEXTENCODING_UTF8 );\n\t\t\t\tmpContext->maOperandStack.push( ExpressionNodeSharedPtr( new EquationExpression( *mpContext->mpCustoShape, aVal.toInt32() ) ) );\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tmpContext->maOperandStack.push( ExpressionNodeSharedPtr( new EnumValueExpression( *mpContext->mpCustoShape, meFunct ) ) );\n\t\t}\n    }\n};\n\nclass UnaryFunctionFunctor\n{\n    const ExpressionFunct\tmeFunct;\n    ParserContextSharedPtr\tmpContext;\n\npublic :\n\n\tUnaryFunctionFunctor( const ExpressionFunct eFunct, const ParserContextSharedPtr& rContext ) :\n\t\tmeFunct( eFunct ),\n\t\tmpContext( rContext )\n\t{\n\t}\n\tvoid operator()( StringIteratorT, StringIteratorT ) const\n\t{\n\t\tParserContext::OperandStack& rNodeStack( mpContext->maOperandStack );\n\n\t\tif( rNodeStack.size() < 1 )\n\t\t\tthrow ParseError( \"Not enough arguments for unary operator\" );\n\n\t\t// retrieve arguments\n\t\tExpressionNodeSharedPtr pArg( rNodeStack.top() );\n\t\trNodeStack.pop();\n\n\t\tif( pArg->isConstant() )\t// check for constness\n\t\t\trNodeStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( UnaryFunctionExpression::getValue( meFunct, pArg ) ) ) );\n\t\telse\t\t\t\t\t\t// push complex node, that calcs the value on demand\n\t\t\trNodeStack.push( ExpressionNodeSharedPtr( new UnaryFunctionExpression( meFunct, pArg ) ) );\n\t}\n};\n\n/** Implements a binary function over two ExpressionNodes\n\n    @tpl Generator\n    Generator functor, to generate an ExpressionNode of\n    appropriate type\n\n    */\nclass BinaryFunctionFunctor\n{\n    const ExpressionFunct\tmeFunct;\n    ParserContextSharedPtr\tmpContext;\n\npublic:\n\n\tBinaryFunctionFunctor( const ExpressionFunct eFunct, const ParserContextSharedPtr& rContext ) :\n        meFunct( eFunct ),\n        mpContext( rContext )\n    {\n    }\n\n    void operator()( StringIteratorT, StringIteratorT ) const\n    {\n        ParserContext::OperandStack& rNodeStack( mpContext->maOperandStack );\n\n\t\tif( rNodeStack.size() < 2 )\n\t\t\tthrow ParseError( \"Not enough arguments for binary operator\" );\n\n        // retrieve arguments\n        ExpressionNodeSharedPtr pSecondArg( rNodeStack.top() );\n        rNodeStack.pop();\n        ExpressionNodeSharedPtr pFirstArg( rNodeStack.top() );\n        rNodeStack.pop();\n\n        // create combined ExpressionNode\n\t\tExpressionNodeSharedPtr pNode = ExpressionNodeSharedPtr( new BinaryFunctionExpression( meFunct, pFirstArg, pSecondArg ) );\n        // check for constness\n        if( pFirstArg->isConstant() && pSecondArg->isConstant() )\t// call the operator() at pNode, store result in constant value ExpressionNode.\n            rNodeStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( (*pNode)() ) ) );\n        else\t\t\t\t\t\t\t\t\t\t\t\t\t\t// push complex node, that calcs the value on demand\n            rNodeStack.push( pNode );\n    }\n};\n\nclass IfFunctor\n{\n    ParserContextSharedPtr\tmpContext;\n\npublic :\n\n\tIfFunctor( const ParserContextSharedPtr& rContext ) :\n        mpContext( rContext )\n    {\n    }\n    void operator()( StringIteratorT, StringIteratorT ) const\n    {\n        ParserContext::OperandStack& rNodeStack( mpContext->maOperandStack );\n\n\t\tif( rNodeStack.size() < 3 )\n\t\t\tthrow ParseError( \"Not enough arguments for ternary operator\" );\n\n        // retrieve arguments\n        ExpressionNodeSharedPtr pThirdArg( rNodeStack.top() );\n        rNodeStack.pop();\n        ExpressionNodeSharedPtr pSecondArg( rNodeStack.top() );\n        rNodeStack.pop();\n        ExpressionNodeSharedPtr pFirstArg( rNodeStack.top() );\n        rNodeStack.pop();\n\n        // create combined ExpressionNode\n        ExpressionNodeSharedPtr pNode( new IfExpression( pFirstArg, pSecondArg, pThirdArg ) );\n        // check for constness\n        if( pFirstArg->isConstant() && pSecondArg->isConstant() && pThirdArg->isConstant() )\n            rNodeStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( (*pNode)() ) ) );\t// call the operator() at pNode, store result in constant value ExpressionNode.\n        else\n            rNodeStack.push( pNode );\t\t\t\t\t\t\t\t\t\t// push complex node, that calcs the value on demand\n    }\n};\n\n// Workaround for MSVC compiler anomaly (stack trashing)\n//\n// The default ureal_parser_policies implementation of parse_exp\n// triggers a really weird error in MSVC7 (Version 13.00.9466), in\n// that the real_parser_impl::parse_main() call of parse_exp()\n// overwrites the frame pointer _on the stack_ (EBP of the calling\n// function gets overwritten while lying on the stack).\n//\n// For the time being, our parser thus can only read the 1.0E10\n// notation, not the 1.0e10 one.\n//\n// TODO(F1): Also handle the 1.0e10 case here.\ntemplate< typename T > struct custom_real_parser_policies : public ::boost::spirit::ureal_parser_policies<T>\n{\n    template< typename ScannerT >\n\t    static typename ::boost::spirit::parser_result< ::boost::spirit::chlit<>, ScannerT >::type\n    parse_exp(ScannerT& scan)\n    {\n        // as_lower_d somehow breaks MSVC7\n        return ::boost::spirit::ch_p('E').parse(scan);\n    }\n};\n\n/* This class implements the following grammar (more or\n    less literally written down below, only slightly\n    obfuscated by the parser actions):\n\n    identifier = '$'|'pi'|'e'|'X'|'Y'|'Width'|'Height'\n\n    function = 'abs'|'sqrt'|'sin'|'cos'|'tan'|'atan'|'acos'|'asin'|'exp'|'log'\n\n    basic_expression =\n               \t\tnumber |\n               \t\tidentifier |\n               \t\tfunction '(' additive_expression ')' |\n               \t\t'(' additive_expression ')'\n\n    unary_expression =\n               \t\t'-' basic_expression |\n                    basic_expression\n\n    multiplicative_expression =\n               \t\tunary_expression ( ( '*' unary_expression )* |\n                                \t\t( '/' unary_expression )* )\n\n    additive_expression =\n               \t\tmultiplicative_expression ( ( '+' multiplicative_expression )* |\n               \t\t\t\t\t\t\t\t\t( '-' multiplicative_expression )* )\n\n    */\n\nclass ExpressionGrammar : public ::boost::spirit::grammar< ExpressionGrammar >\n{\npublic:\n    /** Create an arithmetic expression grammar\n\n        @param rParserContext\n        Contains context info for the parser\n        */\n    ExpressionGrammar( const ParserContextSharedPtr& rParserContext ) :\n        mpParserContext( rParserContext )\n    {\n    }\n\n    template< typename ScannerT > class definition\n    {\n    public:\n        // grammar definition\n        definition( const ExpressionGrammar& self )\n        {\n            using ::boost::spirit::str_p;\n            using ::boost::spirit::range_p;\n            using ::boost::spirit::lexeme_d;\n            using ::boost::spirit::real_parser;\n            using ::boost::spirit::chseq_p;\n\n            identifier =\n\t\t\t\t\t\t\tstr_p( \"pi\"\t\t\t)[ EnumFunctor(ENUM_FUNC_PI,\t\tself.getContext() ) ]\n\t\t\t\t\t|\t\tstr_p( \"left\"\t\t)[ EnumFunctor(ENUM_FUNC_LEFT,\t\tself.getContext() ) ]\n                    |\t\tstr_p( \"top\"\t\t)[ EnumFunctor(ENUM_FUNC_TOP,\t\tself.getContext() ) ]\n                    |\t\tstr_p( \"right\"\t\t)[ EnumFunctor(ENUM_FUNC_RIGHT,\t\tself.getContext() ) ]\n                    |\t\tstr_p( \"bottom\"\t\t)[ EnumFunctor(ENUM_FUNC_BOTTOM,\tself.getContext() ) ]\n                    |\t\tstr_p( \"xstretch\"\t)[ EnumFunctor(ENUM_FUNC_XSTRETCH,\tself.getContext() ) ]\n                    |\t\tstr_p( \"ystretch\"\t)[ EnumFunctor(ENUM_FUNC_YSTRETCH,\tself.getContext() ) ]\n                    |\t\tstr_p( \"hasstroke\"\t)[ EnumFunctor(ENUM_FUNC_HASSTROKE,\tself.getContext() ) ]\n                    |\t\tstr_p( \"hasfill\"\t)[ EnumFunctor(ENUM_FUNC_HASFILL,\tself.getContext() ) ]\n                    |\t\tstr_p( \"width\"\t\t)[ EnumFunctor(ENUM_FUNC_WIDTH,\t\tself.getContext() ) ]\n                    |\t\tstr_p( \"height\"\t\t)[ EnumFunctor(ENUM_FUNC_HEIGHT,\tself.getContext() ) ]\n                    |\t\tstr_p( \"logwidth\"\t)[ EnumFunctor(ENUM_FUNC_LOGWIDTH,\tself.getContext() ) ]\n                    |\t\tstr_p( \"logheight\"\t)[ EnumFunctor(ENUM_FUNC_LOGHEIGHT,\tself.getContext() ) ]\n                    ;\n\n            unaryFunction =\n                    (str_p( \"abs\"  ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_ABS,  self.getContext()) ]\n                |\t(str_p( \"sqrt\" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_SQRT, self.getContext()) ]\n                |\t(str_p( \"sin\"  ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_SIN,  self.getContext()) ]\n                |\t(str_p( \"cos\"  ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_COS,  self.getContext()) ]\n                |\t(str_p( \"tan\"  ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_TAN,  self.getContext()) ]\n                |\t(str_p( \"atan\" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_ATAN, self.getContext()) ]\n                ;\n\n            binaryFunction =\n\t                (str_p( \"min\"  ) >> '(' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ BinaryFunctionFunctor( BINARY_FUNC_MIN,  self.getContext()) ]\n                |\t(str_p( \"max\"  ) >> '(' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ BinaryFunctionFunctor( BINARY_FUNC_MAX,  self.getContext()) ]\n                |\t(str_p( \"atan2\") >> '(' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ BinaryFunctionFunctor( BINARY_FUNC_ATAN2,self.getContext()) ]\n                ;\n\n            ternaryFunction =\n\t                (str_p( \"if\"  ) >> '(' >> additiveExpression >> ',' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ IfFunctor( self.getContext() ) ]\n                ;\n\n\t\t\tfuncRef_decl =\n\t\t\t\tlexeme_d[ +( range_p('a','z') | range_p('A','Z') | range_p('0','9') ) ];\n\n\t\t\tfunctionReference =\n\t\t\t\t(str_p( \"?\" ) >> funcRef_decl )[ EnumFunctor( ENUM_FUNC_EQUATION, self.getContext() ) ];\n\n\t\t\tmodRef_decl =\n\t\t\t\tlexeme_d[ +( range_p('0','9') ) ];\n\n\t\t\tmodifierReference =\n\t\t\t\t(str_p( \"$\" ) >> modRef_decl )[ EnumFunctor( ENUM_FUNC_ADJUSTMENT, self.getContext() ) ];\n\n\t\t\tbasicExpression =\n                    real_parser<double, custom_real_parser_policies<double> >()[ DoubleConstantFunctor(self.getContext()) ]\n                |\tidentifier\n\t\t\t\t|\tfunctionReference\n\t\t\t\t|\tmodifierReference\n                |\tunaryFunction\n                |\tbinaryFunction\n\t\t\t\t|\tternaryFunction\n                |\t'(' >> additiveExpression >> ')'\n                ;\n\n\t\t\tunaryExpression =\n                    ('-' >> basicExpression)[ UnaryFunctionFunctor( UNARY_FUNC_NEG, self.getContext()) ]\n                |\tbasicExpression\n                ;\n\n            multiplicativeExpression =\n                    unaryExpression\n                >> *( ('*' >> unaryExpression)[ BinaryFunctionFunctor( BINARY_FUNC_MUL, self.getContext()) ]\n                    | ('/' >> unaryExpression)[ BinaryFunctionFunctor( BINARY_FUNC_DIV, self.getContext()) ]\n                    )\n                ;\n\n            additiveExpression =\n                    multiplicativeExpression\n                >> *( ('+' >> multiplicativeExpression)[ BinaryFunctionFunctor( BINARY_FUNC_PLUS,  self.getContext()) ]\n                    | ('-' >> multiplicativeExpression)[ BinaryFunctionFunctor( BINARY_FUNC_MINUS, self.getContext()) ]\n                    )\n                ;\n\n            BOOST_SPIRIT_DEBUG_RULE(additiveExpression);\n            BOOST_SPIRIT_DEBUG_RULE(multiplicativeExpression);\n\t        BOOST_SPIRIT_DEBUG_RULE(unaryExpression);\n            BOOST_SPIRIT_DEBUG_RULE(basicExpression);\n            BOOST_SPIRIT_DEBUG_RULE(unaryFunction);\n            BOOST_SPIRIT_DEBUG_RULE(binaryFunction);\n            BOOST_SPIRIT_DEBUG_RULE(ternaryFunction);\n            BOOST_SPIRIT_DEBUG_RULE(identifier);\n        }\n\n        const ::boost::spirit::rule< ScannerT >& start() const\n        {\n            return additiveExpression;\n        }\n\n    private:\n        // the constituents of the Spirit arithmetic expression grammar.\n        // For the sake of readability, without 'ma' prefix.\n        ::boost::spirit::rule< ScannerT >\tadditiveExpression;\n\t\t::boost::spirit::rule< ScannerT >\tmultiplicativeExpression;\n\t\t::boost::spirit::rule< ScannerT >\tunaryExpression;\n\t\t::boost::spirit::rule< ScannerT >\tbasicExpression;\n\t\t::boost::spirit::rule< ScannerT >\tunaryFunction;\n\t\t::boost::spirit::rule< ScannerT >\tbinaryFunction;\n\t\t::boost::spirit::rule< ScannerT >\tternaryFunction;\n\t\t::boost::spirit::rule< ScannerT >\tfuncRef_decl;\n\t\t::boost::spirit::rule< ScannerT >\tfunctionReference;\n\t\t::boost::spirit::rule< ScannerT >\tmodRef_decl;\n\t\t::boost::spirit::rule< ScannerT >\tmodifierReference;\n\t\t::boost::spirit::rule< ScannerT >\tidentifier;\n    };\n\n    const ParserContextSharedPtr& getContext() const\n    {\n        return mpParserContext;\n    }\n\nprivate:\n    ParserContextSharedPtr\t\t\tmpParserContext; // might get modified during parsing\n};\n\n#ifdef BOOST_SPIRIT_SINGLE_GRAMMAR_INSTANCE\nconst ParserContextSharedPtr& getParserContext()\n{\n    static ParserContextSharedPtr lcl_parserContext( new ParserContext() );\n\n    // clear node stack (since we reuse the static object, that's\n    // the whole point here)\n    while( !lcl_parserContext->maOperandStack.empty() )\n        lcl_parserContext->maOperandStack.pop();\n\n    return lcl_parserContext;\n}\n#endif\n\n}\n\nnamespace EnhancedCustomShape  {\n\n\n\nExpressionNodeSharedPtr FunctionParser::parseFunction( const ::rtl::OUString& rFunction, const EnhancedCustomShape2d& rCustoShape )\n{\n    // TODO(Q1): Check if a combination of the RTL_UNICODETOTEXT_FLAGS_*\n    // gives better conversion robustness here (we might want to map space\n    // etc. to ASCII space here)\n    const ::rtl::OString& rAsciiFunction(\n        rtl::OUStringToOString( rFunction, RTL_TEXTENCODING_ASCII_US ) );\n\n    StringIteratorT aStart( rAsciiFunction.getStr() );\n    StringIteratorT aEnd( rAsciiFunction.getStr()+rAsciiFunction.getLength() );\n\n    ParserContextSharedPtr pContext;\n\n#ifdef BOOST_SPIRIT_SINGLE_GRAMMAR_INSTANCE\n    // static parser context, because the actual\n    // Spirit parser is also a static object\n    pContext = getParserContext();\n#else\n    pContext.reset( new ParserContext() );\n#endif\n\tpContext->mpCustoShape = &rCustoShape;\n\n    ExpressionGrammar aExpressionGrammer( pContext );\n    const ::boost::spirit::parse_info<StringIteratorT> aParseInfo(\n            ::boost::spirit::parse( aStart,\n                                    aEnd,\n                                    aExpressionGrammer >> ::boost::spirit::end_p,\n                                    ::boost::spirit::space_p ) );\n    OSL_DEBUG_ONLY(::std::cout.flush()); // needed to keep stdout and cout in sync\n\n\n\n    // input fully congested by the parser?\n\tif( !aParseInfo.full )\n\t\tthrow ParseError( \"EnhancedCustomShapeFunctionParser::parseFunction(): string not fully parseable\" );\n\n    // parser's state stack now must contain exactly _one_ ExpressionNode,\n    // which represents our formula.\n\tif( pContext->maOperandStack.size() != 1 )\n\t\tthrow ParseError( \"EnhancedCustomShapeFunctionParser::parseFunction(): incomplete or empty expression\" );\n\n\n    return pContext->maOperandStack.top();\n}\n\n\n}\n\n", "meta": {"hexsha": "a085760f6cbc758fcc9384cd02c381d72e8f1323", "size": 43446, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "main/svx/source/customshapes/EnhancedCustomShapeFunctionParser.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/svx/source/customshapes/EnhancedCustomShapeFunctionParser.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/svx/source/customshapes/EnhancedCustomShapeFunctionParser.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": 35.935483871, "max_line_length": 180, "alphanum_fraction": 0.6768862496, "num_tokens": 11580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.029312227465487513, "lm_q1q2_score": 0.014541615173676364}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_VANDG_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_VANDG_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace vandg\n    {\n\n            static const double TOL = 1.e-10;\n            static const double THIRD = .33333333333333333333;\n            static const double TWO_THRD = .66666666666666666666;\n            static const double C2_27 = .07407407407407407407;\n            static const double PI4_3 = 4.18879020478639098458;\n            static const double PISQ = 9.86960440108935861869;\n            static const double TPISQ = 19.73920880217871723738;\n            static const double HPISQ = 4.93480220054467930934;\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_vandg_spheroid : public base_t_fi<base_vandg_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n\n                inline base_vandg_spheroid(const Parameters& par)\n                    : base_t_fi<base_vandg_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double  al, al2, g, g2, p2;\n\n                    p2 = fabs(lp_lat / geometry::math::half_pi<double>());\n                    if ((p2 - TOL) > 1.) throw proj_exception();;\n                    if (p2 > 1.)\n                        p2 = 1.;\n                    if (fabs(lp_lat) <= TOL) {\n                        xy_x = lp_lon;\n                        xy_y = 0.;\n                    } else if (fabs(lp_lon) <= TOL || fabs(p2 - 1.) < TOL) {\n                        xy_x = 0.;\n                        xy_y = geometry::math::pi<double>() * tan(.5 * asin(p2));\n                        if (lp_lat < 0.) xy_y = -xy_y;\n                    } else {\n                        al = .5 * fabs(geometry::math::pi<double>() / lp_lon - lp_lon / geometry::math::pi<double>());\n                        al2 = al * al;\n                        g = sqrt(1. - p2 * p2);\n                        g = g / (p2 + g - 1.);\n                        g2 = g * g;\n                        p2 = g * (2. / p2 - 1.);\n                        p2 = p2 * p2;\n                        xy_x = g - p2; g = p2 + al2;\n                        xy_x = geometry::math::pi<double>() * (al * xy_x + sqrt(al2 * xy_x * xy_x - g * (g2 - p2))) / g;\n                        if (lp_lon < 0.) xy_x = -xy_x;\n                        xy_y = fabs(xy_x / geometry::math::pi<double>());\n                        xy_y = 1. - xy_y * (xy_y + 2. * al);\n                        if (xy_y < -TOL) throw proj_exception();;\n                        if (xy_y < 0.)    xy_y = 0.;\n                        else        xy_y = sqrt(xy_y) * (lp_lat < 0. ? -geometry::math::pi<double>() : geometry::math::pi<double>());\n                    }\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    double t, c0, c1, c2, c3, al, r2, r, m, d, ay, x2, y2;\n\n                    x2 = xy_x * xy_x;\n                    if ((ay = fabs(xy_y)) < TOL) {\n                        lp_lat = 0.;\n                        t = x2 * x2 + TPISQ * (x2 + HPISQ);\n                        lp_lon = fabs(xy_x) <= TOL ? 0. :\n                           .5 * (x2 - PISQ + sqrt(t)) / xy_x;\n                            return;\n                    }\n                    y2 = xy_y * xy_y;\n                    r = x2 + y2;    r2 = r * r;\n                    c1 = - geometry::math::pi<double>() * ay * (r + PISQ);\n                    c3 = r2 + geometry::math::two_pi<double>() * (ay * r + geometry::math::pi<double>() * (y2 + geometry::math::pi<double>() * (ay + geometry::math::half_pi<double>())));\n                    c2 = c1 + PISQ * (r - 3. *  y2);\n                    c0 = geometry::math::pi<double>() * ay;\n                    c2 /= c3;\n                    al = c1 / c3 - THIRD * c2 * c2;\n                    m = 2. * sqrt(-THIRD * al);\n                    d = C2_27 * c2 * c2 * c2 + (c0 * c0 - THIRD * c2 * c1) / c3;\n                    if (((t = fabs(d = 3. * d / (al * m))) - TOL) <= 1.) {\n                        d = t > 1. ? (d > 0. ? 0. : geometry::math::pi<double>()) : acos(d);\n                        lp_lat = geometry::math::pi<double>() * (m * cos(d * THIRD + PI4_3) - THIRD * c2);\n                        if (xy_y < 0.) lp_lat = -lp_lat;\n                        t = r2 + TPISQ * (x2 - y2 + HPISQ);\n                        lp_lon = fabs(xy_x) <= TOL ? 0. :\n                           .5 * (r - PISQ + (t <= 0. ? 0. : sqrt(t))) / xy_x;\n                    } else\n                        throw proj_exception();;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"vandg_spheroid\";\n                }\n\n            };\n\n            // van der Grinten (I)\n            template <typename Parameters>\n            void setup_vandg(Parameters& par)\n            {\n                par.es = 0.;\n            }\n\n        }} // namespace detail::vandg\n    #endif // doxygen\n\n    /*!\n        \\brief van der Grinten (I) projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n        \\par Example\n        \\image html ex_vandg.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct vandg_spheroid : public detail::vandg::base_vandg_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline vandg_spheroid(const Parameters& par) : detail::vandg::base_vandg_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::vandg::setup_vandg(this->m_par);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class vandg_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<vandg_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void vandg_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"vandg\", new vandg_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_VANDG_HPP\n\n", "meta": {"hexsha": "78a4e6f187d49e20f959527d3cd7e477f34d3877", "size": 9643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/vandg.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/vandg.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/vandg.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": 45.2723004695, "max_line_length": 186, "alphanum_fraction": 0.5485844654, "num_tokens": 2350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.03258974805461601, "lm_q1q2_score": 0.01451969481796826}}
{"text": "#ifndef STAN_VARIATIONAL_ADVI_HPP\n#define STAN_VARIATIONAL_ADVI_HPP\n\n#include <stan/math.hpp>\n#include <stan/analyze/mcmc/autocovariance.hpp>\n#include <stan/analyze/mcmc/compute_effective_sample_size.hpp>\n#include <stan/analyze/mcmc/compute_potential_scale_reduction.hpp>\n#include <stan/analyze/mcmc/estimate_gpd_params.hpp>\n#include <stan/callbacks/logger.hpp>\n#include <stan/callbacks/writer.hpp>\n#include <stan/callbacks/stream_writer.hpp>\n#include <stan/io/dump.hpp>\n#include <stan/services/error_codes.hpp>\n#include <stan/variational/print_progress.hpp>\n#include <stan/variational/families/normal_fullrank.hpp>\n#include <stan/variational/families/normal_meanfield.hpp>\n#include <stan/variational/families/normal_lowrank.hpp>\n#include <boost/circular_buffer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <algorithm>\n#include <chrono>\n#include <limits>\n#include <numeric>\n#include <ostream>\n#include <queue>\n#include <string>\n#include <vector>\n#include <cmath>\n\nnamespace stan {\n\nnamespace variational {\n\n/**\n * Automatic Differentiation Variational Inference\n *\n * Implements \"black box\" variational inference using stochastic gradient\n * ascent to maximize the Evidence Lower Bound for a given model\n * and variational family. This base class encapsulates the mean-field,\n * low-rank, and full-rank variational posterior classes.\n *\n * @tparam Model class of model\n * @tparam Q class of variational distribution\n * @tparam BaseRNG class of random number generator\n */\ntemplate <class Model, class Q, class BaseRNG>\nclass advi_base {\n public:\n  /**\n   * Constructor\n   *\n   * @param[in] m stan model\n   * @param[in] cont_params initialization of continuous parameters\n   * @param[in,out] rng random number generator\n   * @param[in] n_monte_carlo_grad number of samples for gradient computation\n   * @param[in] n_monte_carlo_elbo number of samples for ELBO computation\n   * @param[in] n_posterior_samples number of samples to draw from posterior\n   * @throw std::runtime_error if n_monte_carlo_grad is not positive\n   * @throw std::runtime_error if n_monte_carlo_elbo is not positive\n   * @throw std::runtime_error if n_posterior_samples is not positive\n   */\n  advi_base(Model& m, Eigen::VectorXd& cont_params, BaseRNG& rng,\n       int n_monte_carlo_grad, int n_monte_carlo_elbo,\n       int n_posterior_samples)\n      : model_(m),\n        cont_params_(cont_params),\n        rng_(rng),\n        n_monte_carlo_grad_(n_monte_carlo_grad),\n        n_monte_carlo_elbo_(n_monte_carlo_elbo),\n        n_posterior_samples_(n_posterior_samples) {\n    static const char* function = \"stan::variational::advi\";\n    math::check_positive(function,\n                         \"Number of Monte Carlo samples for gradients\",\n                         n_monte_carlo_grad_);\n    math::check_positive(function, \"Number of Monte Carlo samples for ELBO\",\n                         n_monte_carlo_elbo_);\n    math::check_positive(function, \"Number of posterior samples for output\",\n                         n_posterior_samples_);\n  }\n\n  /**\n   * Calculates the Evidence Lower BOund (ELBO) by sampling from\n   * the variational distribution and then evaluating the log joint,\n   * adjusted by the entropy term of the variational distribution.\n   *\n   * @param[in] variational variational approximation at which to evaluate\n   * the ELBO.\n   * @param logger logger for messages\n   * @return the evidence lower bound.\n   * @throw std::domain_error If, after n_monte_carlo_elbo_ number of draws\n   * from the variational distribution all give non-finite log joint\n   * evaluations. This means that the model is severely ill conditioned or\n   * that the variational distribution has somehow collapsed.\n   */\n  double calc_ELBO(const Q& variational, callbacks::logger& logger) const {\n    static const char* function = \"stan::variational::advi::calc_ELBO\";\n\n    double elbo = 0.0;\n    int dim = variational.dimension();\n    Eigen::VectorXd zeta(dim);\n\n    int n_dropped_evaluations = 0;\n    for (int i = 0; i < n_monte_carlo_elbo_;) {\n      variational.sample(rng_, zeta);\n      try {\n        std::stringstream ss;\n        double log_prob = model_.template log_prob<false, true>(zeta, &ss);\n        if (ss.str().length() > 0)\n          logger.info(ss);\n        stan::math::check_finite(function, \"log_prob\", log_prob);\n        elbo += log_prob;\n        ++i;\n      } catch (const std::domain_error& e) {\n        ++n_dropped_evaluations;\n        if (n_dropped_evaluations >= n_monte_carlo_elbo_) {\n          const char* name = \"The number of dropped evaluations\";\n          const char* msg1 = \"has reached its maximum amount (\";\n          const char* msg2\n              = \"). Your model may be either severely \"\n                \"ill-conditioned or misspecified.\";\n          stan::math::throw_domain_error(function, name, n_monte_carlo_elbo_,\n                                         msg1, msg2);\n        }\n      }\n    }\n    elbo /= n_monte_carlo_elbo_;\n    elbo += variational.entropy();\n    return elbo;\n  }\n\n  /**\n   * Calculates the \"black box\" gradient of the ELBO.\n   *\n   * @param[in] variational variational approximation at which to evaluate\n   * the ELBO.\n   * @param[out] elbo_grad gradient of ELBO with respect to variational\n   * approximation.\n   * @param logger logger for messages\n   */\n  void calc_ELBO_grad(const Q& variational, Q& elbo_grad,\n                      callbacks::logger& logger) const {\n    static const char* function = \"stan::variational::advi::calc_ELBO_grad\";\n\n    stan::math::check_size_match(\n        function, \"Dimension of elbo_grad\", elbo_grad.dimension(),\n        \"Dimension of variational q\", variational.dimension());\n    stan::math::check_size_match(\n        function, \"Dimension of variational q\", variational.dimension(),\n        \"Dimension of variables in model\", cont_params_.size());\n\n    variational.calc_grad(elbo_grad, model_, cont_params_, n_monte_carlo_grad_,\n                          rng_, logger);\n  }\n\n  /**\n   * Heuristic grid search to adapt eta to the scale of the problem.\n   *\n   * @param[in] variational initial variational distribution.\n   * @param[in] adapt_iterations number of iterations to spend doing stochastic\n   * gradient ascent at each proposed eta value.\n   * @param[in,out] logger logger for messages\n   * @return adapted (tuned) value of eta via heuristic grid search\n   * @throw std::domain_error If either (a) the initial ELBO cannot be\n   * computed at the initial variational distribution, (b) all step-size\n   * proposals in eta_sequence fail.\n   */\n  double adapt_eta(Q& variational, int adapt_iterations,\n                   callbacks::logger& logger) const {\n    static const char* function = \"stan::variational::advi::adapt_eta\";\n\n    stan::math::check_positive(function, \"Number of adaptation iterations\",\n                               adapt_iterations);\n\n    logger.info(\"Begin eta adaptation.\");\n\n    // Sequence of eta values to try during adaptation\n    const int eta_sequence_size = 5;\n    double eta_sequence[eta_sequence_size] = {100, 10, 1, 0.1, 0.01};\n\n    // Initialize ELBO tracking variables\n    double elbo = -std::numeric_limits<double>::max();\n    double elbo_best = -std::numeric_limits<double>::max();\n    double elbo_init;\n    try {\n      elbo_init = calc_ELBO(variational, logger);\n    } catch (const std::domain_error& e) {\n      const char* name\n          = \"Cannot compute ELBO using the initial \"\n            \"variational distribution.\";\n      const char* msg1\n          = \"Your model may be either \"\n            \"severely ill-conditioned or misspecified.\";\n      stan::math::throw_domain_error(function, name, \"\", msg1);\n    }\n\n    // Variational family to store gradients\n    Q elbo_grad = init_variational(model_.num_params_r());\n\n    // Adaptive step-size sequence\n    Q history_grad_squared = init_variational(model_.num_params_r());\n    double tau = 1.0;\n    double pre_factor = 0.9;\n    double post_factor = 0.1;\n\n    double eta_best = 0.0;\n    double eta;\n    double eta_scaled;\n\n    bool do_more_tuning = true;\n    int eta_sequence_index = 0;\n    while (do_more_tuning) {\n      // Try next eta\n      eta = eta_sequence[eta_sequence_index];\n\n      int print_progress_m;\n      for (int iter_tune = 1; iter_tune <= adapt_iterations; ++iter_tune) {\n        print_progress_m = eta_sequence_index * adapt_iterations + iter_tune;\n        variational ::print_progress(print_progress_m, 0,\n                                     adapt_iterations * eta_sequence_size,\n                                     adapt_iterations, true, \"\", \"\", logger);\n\n        // (ROBUST) Compute gradient of ELBO. It's OK if it diverges.\n        // We'll try a smaller eta.\n        try {\n          calc_ELBO_grad(variational, elbo_grad, logger);\n        } catch (const std::domain_error& e) {\n          elbo_grad.set_to_zero();\n        }\n\n        // Update step-size\n        if (iter_tune == 1) {\n          history_grad_squared += elbo_grad.square();\n        } else {\n          history_grad_squared = pre_factor * history_grad_squared\n                                 + post_factor * elbo_grad.square();\n        }\n        eta_scaled = eta / sqrt(static_cast<double>(iter_tune));\n        // Stochastic gradient update\n        variational\n            += eta_scaled * elbo_grad / (tau + history_grad_squared.sqrt());\n      }\n\n      // (ROBUST) Compute ELBO. It's OK if it has diverged.\n      try {\n        elbo = calc_ELBO(variational, logger);\n      } catch (const std::domain_error& e) {\n        elbo = -std::numeric_limits<double>::max();\n      }\n\n      // Check if:\n      // (1) ELBO at current eta is worse than the best ELBO\n      // (2) the best ELBO hasn't gotten worse than the initial ELBO\n      if (elbo < elbo_best && elbo_best > elbo_init) {\n        std::stringstream ss;\n        ss << \"Success!\"\n           << \" Found best value [eta = \" << eta_best << \"]\";\n        if (eta_sequence_index < eta_sequence_size - 1)\n          ss << (\" earlier than expected.\");\n        else\n          ss << \".\";\n        logger.info(ss);\n        logger.info(\"\");\n        do_more_tuning = false;\n      } else {\n        if (eta_sequence_index < eta_sequence_size - 1) {\n          // Reset\n          elbo_best = elbo;\n          eta_best = eta;\n        } else {\n          // No more eta values to try, so use current eta if it\n          // didn't diverge or fail if it did diverge\n          if (elbo > elbo_init) {\n            std::stringstream ss;\n            ss << \"Success!\"\n               << \" Found best value [eta = \" << eta_best << \"].\";\n            logger.info(ss);\n            logger.info(\"\");\n            eta_best = eta;\n            do_more_tuning = false;\n          } else {\n            const char* name = \"All proposed step-sizes\";\n            const char* msg1\n                = \"failed. Your model may be either \"\n                  \"severely ill-conditioned or misspecified.\";\n            stan::math::throw_domain_error(function, name, \"\", msg1);\n          }\n        }\n        // Reset\n        history_grad_squared.set_to_zero();\n      }\n      ++eta_sequence_index;\n      variational = init_variational(cont_params_);\n    }\n    return eta_best;\n  }\n\n  /**\n   * Run Robust Variational Inference.\n   * A. Dhaka et al., 2020\n   *\n   * @param[in] eta eta parameter of stepsize sequence\n   * @param[in] adapt_engaged boolean flag for eta adaptation\n   * @param[in] adapt_iterations number of iterations for eta adaptation\n   * @param[in] max_iterations max number of iterations to run algorithm\n   * @param[in] eval_window Interval to calculate termination conditions\n   * @param[in] window_size Proportion of eval_window samples to calculate\n   * Rhat for termination condition\n   * @param[in] rhat_cut Rhat termination criteria\n   * @param[in] mcse_cut MCSE termination criteria\n   * @param[in] ess_cut effective sample size termination criteria\n   * @param[in] num_chains Number of VI chains to run\n   * @param[in,out] logger logger for messages\n   * @param[in,out] parameter_writer writer for parameters\n   *   (typically to file)\n   * @param[in,out] diagnostic_writer writer for diagnostic information\n   */\n  int run(double eta, bool adapt_engaged, int adapt_iterations,\n          int max_iterations, int eval_window, double window_size,\n          double rhat_cut, double mcse_cut, double ess_cut, int num_chains,\n\t        callbacks::logger& logger,\n          callbacks::writer& parameter_writer,\n          callbacks::writer& diagnostic_writer) const {\n    diagnostic_writer(\"iter,time_in_seconds,ELBO\");\n\n    // Initialize variational approximation\n    Q variational = init_variational(cont_params_);\n    std::stringstream ss;\n\n    if (adapt_engaged) {\n      eta = adapt_eta(variational, adapt_iterations, logger);\n      parameter_writer(\"Stepsize adaptation complete.\");      \n      ss << \"eta = \" << eta << \" \";\n      parameter_writer(ss.str());\n    }\n\n    ///////////////////\n\n    double khat, ess, mcse, max_rhat, rhat, eta_scaled;\n    int T0 = max_iterations - 1;\n\n    const int dim = variational.dimension();\n    const int n_approx_params = variational.num_approx_params();\n\n    std::vector<Q> variational_obj_vec;\n    std::vector<Q> elbo_grad_vec;\n    std::vector<Q> elbo_grad_square_vec;\n\n    // for each chain, save variational parameter values on matrix\n    // of dim (n_params, n_iters)\n    typedef Eigen::Matrix<double, Eigen::Dynamic, \n                          Eigen::Dynamic, Eigen::RowMajor> histMat;\n    std::vector<histMat> hist_vector;\n    hist_vector.reserve(num_chains);\n    variational_obj_vec.reserve(num_chains);\n    elbo_grad_vec.reserve(num_chains);\n    elbo_grad_square_vec.reserve(num_chains);\n\n    for(int i = 0; i < num_chains; i++){\n      hist_vector.push_back(histMat(n_approx_params, max_iterations));\n      variational_obj_vec.push_back(init_variational(cont_params_));\n      elbo_grad_vec.push_back(init_variational(dim));\n      elbo_grad_square_vec.push_back(init_variational(dim));\n    }\n\n    for (int n_iter = 0; n_iter < max_iterations; n_iter++){\n      eta_scaled = eta / sqrt(static_cast<double>(n_iter + 1));\n      for (int n_chain = 0; n_chain < num_chains; n_chain++){\n        calc_ELBO_grad(variational_obj_vec[n_chain], elbo_grad_vec[n_chain], logger);\n        if (n_iter == 0) {\n          elbo_grad_square_vec[n_chain] += elbo_grad_vec[n_chain].square();\n        }\n        else {\n          elbo_grad_square_vec[n_chain] = 0.9 * elbo_grad_square_vec[n_chain]\n                                          + 0.1 * elbo_grad_vec[n_chain].square();\n        }\n        variational_obj_vec[n_chain] += eta_scaled * elbo_grad_vec[n_chain] / (1.0 + elbo_grad_square_vec[n_chain].sqrt());\n\n        hist_vector[n_chain].col(n_iter) = variational_obj_vec[n_chain].return_approx_params();\n      }\n\n      if ((n_iter % eval_window == 0 && n_iter > 0) || n_iter == max_iterations - 1){\n        max_rhat = std::numeric_limits<double>::lowest();\n        for(int k = 0; k < n_approx_params; k++) {\n          std::vector<const double*> hist_ptrs;\n          std::vector<size_t> chain_length;\n          const int split_point = n_iter * (1.0 - window_size); // iteration index to start calculating rhat\n          // so Rhat should be calculated for iters [split_point, n_iter]\n          if(num_chains == 1){\n            // use split rhat\n            chain_length.assign(2, static_cast<size_t>((n_iter - split_point + 1) / 2));\n            hist_ptrs.push_back(hist_vector[0].row(k).data() + split_point);\n            hist_ptrs.push_back(hist_ptrs[0] + chain_length[0]);\n          }\n          else{\n            for(int i = 0; i < num_chains; i++){\n              //chain_length.push_back(static_cast<size_t>(n_iter * window_size));\n              //hist_ptrs.push_back(hist_vector[i].row(k).data());\n\n              // multi-chain split rhat (split each chain into 2)\n              chain_length.insert(chain_length.end(), 2, static_cast<size_t>((n_iter - split_point + 1) / 2));\n              hist_ptrs.push_back(hist_vector[i].row(k).data() + split_point);\n              hist_ptrs.push_back(hist_vector[i].row(k).data() +  split_point + chain_length[0]);\n            }\n          }\n          rhat = stan::analyze::compute_potential_scale_reduction(hist_ptrs, chain_length);\n          max_rhat = std::max<double>(max_rhat, rhat);\n        }\n\n        if (max_rhat < rhat_cut) {\n          T0 = n_iter;\n          ss << \"Preliminary iterations terminated by rhat condition at iteration # \" << T0 <<\n                \" with max reported Rhat value of \" << max_rhat << \"\\n\";\n          break;\n        }\n      }\n    }\n\n    bool khat_failed = false;\n    for(int k = 0; k < num_chains; k++){\n      Eigen::VectorXd lw_vec(n_posterior_samples_);\n      lr(variational_obj_vec[k], lw_vec);\n      double sigma, max_lw;\n      int n_tail;\n      if(n_posterior_samples_ < 225) {\n        n_tail = int(lw_vec.size() * 0.2);\n      }\n      else{\n        n_tail = 3 * sqrt(lw_vec.size()); // if more than 225 samples 3 * sqrt(lw_vec.size())\n      }\n      max_lw = lw_vec.maxCoeff();\n      lw_vec = lw_vec.array() - max_lw;\n      lw_vec = lw_vec.array().exp() - std::exp(lw_vec(n_tail));\n      lw_vec = lw_vec.head(n_tail);\n      stan::analyze::gpdfit(lw_vec, khat, sigma);\n\n      ss << \"Chain \" << k << \" khat: \" << khat << \"\\n\";\n      if(khat > 1.0) { \n        khat_failed = true;\n        break;\n      }\n    }\n    if (khat_failed || max_rhat > rhat_cut) {\n      logger.warn(\"Optimization may have not converged\");\n      ss << \" max_rhat: \" << max_rhat << \" rhat_cut: \" << rhat_cut << \"\\n\";\n      // avarage parameters from the last eval_window param iterations\n      for(int i = 0; i < num_chains; i++){\n        variational_obj_vec[i].set_approx_params(\n          hist_vector[i].block(0, T0 - eval_window + 1, n_approx_params, eval_window).rowwise().mean());\n      }\n    }\n    else {\n      ss << \"Start secondary iteration at step #: \" << T0 << \"\\n\";\n      for(int n_post_iter = T0; n_post_iter < max_iterations; n_post_iter++){\n        eta_scaled = eta / sqrt(static_cast<double>(n_post_iter + 1));\n        for (int n_chain = 0; n_chain < num_chains; n_chain++){\n          calc_ELBO_grad(variational_obj_vec[n_chain], elbo_grad_vec[n_chain], logger);\n          elbo_grad_square_vec[n_chain] = 0.9 * elbo_grad_square_vec[n_chain]\n                                          + 0.1 * elbo_grad_vec[n_chain].square();\n\n          variational_obj_vec[n_chain] += eta_scaled * elbo_grad_vec[n_chain] / \n                                          elbo_grad_square_vec[n_chain].sqrt();\n\n          hist_vector[n_chain].col(n_post_iter) = variational_obj_vec[n_chain].return_approx_params();\n        }\n        if ((n_post_iter - T0) % eval_window == 0 && (n_post_iter - T0) > 0) {\n          double min_ess = std::numeric_limits<double>::infinity(), max_mcse = std::numeric_limits<double>::lowest();\n          for(int k = 0; k < n_approx_params; k++){\n            std::vector<const double*> hist_ptrs;\n            std::vector<size_t> chain_length;\n            if(num_chains == 1){\n              // split chain calculation\n              chain_length.assign(2, static_cast<size_t>((n_post_iter - T0 + 1) / 2));\n              hist_ptrs.push_back(hist_vector[0].row(k).data() + T0);\n              hist_ptrs.push_back(hist_ptrs[0] + chain_length[0]); \n            }\n            else {\n              for(int i = 0; i < num_chains; i++){\n                chain_length.push_back(static_cast<size_t>(n_post_iter - T0 + 1));\n                hist_ptrs.push_back(hist_vector[i].row(k).data() + T0);\n              }\n            }\n            double ess, mcse;\n            ESS_MCSE(ess, mcse, hist_ptrs, chain_length);\n            min_ess = std::min<double>(min_ess, ess);\n            max_mcse = std::max<double>(max_mcse, mcse);\n          }\n          if(max_mcse < mcse_cut && min_ess > ess_cut){\n            ss << \"Second iteration break condition reached at iteration # \"\n               << n_post_iter << \"\\n\";\n            ss << \"min ESS: \" << min_ess << \" max MCSE: \" << max_mcse << \"\\n\";\n            for(int i = 0; i < num_chains; i++){\n                variational_obj_vec[i].set_approx_params(\n                hist_vector[i].block(0, T0, n_approx_params, n_post_iter - T0 + 1).rowwise().mean());\n            }\n            break;\n          }\n        }\n      }\n    }\n    variational.set_to_zero();\n    for(int i = 0; i < num_chains; i++){\n      variational += 1.0 / num_chains * variational_obj_vec[i];\n    }\n    ss << \"Finished optimization\" << \"\\n\";\n\n    for(int i = 0; i < num_chains; i++){\n      ss << \"Chain \" << i << \" mean:\\n\" << variational_obj_vec[i].mean() << \"\\n\";\n    }\n    ss << \"----\\nQ variational:\\n\" << variational.mean() << \"\\n----\\n\";\n    ss << \"Num of Model params: \" << dim << \"\\n\";\n    ss << \"Num of Approx params: \" << n_approx_params << \"\\n\";\n    logger.info(ss);\n    ///////////////////\n\n    // Write posterior mean of variational approximations.\n    cont_params_ = variational.mean();\n    std::vector<double> cont_vector(cont_params_.size());\n    for (int i = 0; i < cont_params_.size(); ++i)\n      cont_vector.at(i) = cont_params_(i);\n    std::vector<int> disc_vector;\n    std::vector<double> values;\n\n    /*std::stringstream msg;\n    model_.write_array(rng_, cont_vector, disc_vector, values, true, true,\n                       &msg);\n    if (msg.str().length() > 0)\n      logger.info(msg);\n\n    // The first row of lp_, log_p, log_g, and chain_id.\n    values.insert(values.begin(), {0, 0, 0, -1});\n    parameter_writer(values);*/\n\n    // Draw more from posterior and write on subsequent lines\n    logger.info(\"\");\n    std::stringstream ss2;\n    ss2 << \"Drawing a sample of size \" << n_posterior_samples_\n       << \" from the approximate posterior... \";\n    logger.info(ss2);\n    double log_p = 0;\n    double log_g = 0;\n    // Draw posterior sample. log_g is the log normal densities.\n    Eigen::VectorXd chain_params(cont_params_.size());\n    for (int n = 0; n < n_posterior_samples_; ++n) {\n      for (int k = 0; k < num_chains; k++){\n        chain_params = variational_obj_vec[k].mean();\n        variational_obj_vec[k].sample_log_g(rng_, chain_params, log_g);\n        for (int i = 0; i < chain_params.size(); ++i) {\n          cont_vector.at(i) = chain_params(i);\n        }\n        std::stringstream msg2;\n        model_.write_array(rng_, cont_vector, disc_vector, values, true, true,\n                          &msg2);\n        //  log_p: Log probability in the unconstrained space\n        log_p = model_.template log_prob<false, true>(chain_params, &msg2);\n        if (msg2.str().length() > 0)\n          logger.info(msg2);\n        // Write lp__, log_p, log_g, and chain_id.\n        values.insert(values.begin(), {0.0, log_p, log_g, static_cast<double>(k)});\n        parameter_writer(values);\n        }\n    }\n    logger.info(\"COMPLETED.\");\n    return stan::services::error_codes::OK;\n  }\n\n  /**\n  * RVI Diagnostics: Calculates log importance weights\n  *\n  * @param[in] variational_obj variational family object\n  * @param[in, out] weight_vector An Eigen\n  * dynamic vector of weights, sorted in descending order\n  */\n  void lr(const Q& variational_obj, Eigen::VectorXd& weight_vector) \n          const {\n    // Need to check the vector is empty\n    weight_vector.resize(n_posterior_samples_);\n    double log_p, log_g;\n    std::stringstream msg2;\n    Eigen::VectorXd draws(variational_obj.dimension());\n    // Draw posterior sample. log_g is the log normal densities.\n    for (int n = 0; n < n_posterior_samples_; ++n) {\n      variational_obj.sample_log_g(rng_, draws, log_g);\n      //  log_p: Log probability in the unconstrained space\n      log_p = model_.template log_prob<false, true>(draws, &msg2);\n      weight_vector(n) = log_p - log_g;\n    }\n    // sort descending order\n    std::sort(weight_vector.data(), weight_vector.data() + weight_vector.size(),\n              std::greater<double>());\n  }\n \n  /**\n   * RVI Diagnostics\n   * Estimate the Effective Sample Size and Monte Carlo Standard Error of posterior samples where\n   * MCSE = sqrt( var(parmas) / ess)\n   * @param[in] samples An Eigen::VectorXd containing posterior samples @TODO rewrite from here\n   * @param[in] ess If specified, will be used as effective sample size instead\n   * of calling compute_effective_sample_size()\n   * \n   * @return Calculated MCSE\n   */\n  static double ESS_MCSE(double &ess, double &mcse,\n                        const std::vector<const double*> draws,\n                        const std::vector<size_t> sizes) {\n    int num_chains = sizes.size();\n    size_t num_draws = sizes[0];\n    for (int chain = 1; chain < num_chains; ++chain) {\n      num_draws = std::min(num_draws, sizes[chain]);\n    }\n\n    if (num_draws < 4) {\n      ess = std::numeric_limits<double>::quiet_NaN();\n      mcse = std::numeric_limits<double>::quiet_NaN();\n      return std::numeric_limits<double>::quiet_NaN();\n    }\n\n    // check if chains are constant; all equal to first draw's value\n    bool are_all_const = false;\n    Eigen::VectorXd init_draw = Eigen::VectorXd::Zero(num_chains);\n\n    for (int chain_idx = 0; chain_idx < num_chains; chain_idx++) {\n      Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(\n              draws[chain_idx], sizes[chain_idx]);\n\n      for (int n = 0; n < num_draws; n++) {\n        if (!std::isfinite(draw(n))) {\n          ess = std::numeric_limits<double>::quiet_NaN();\n          mcse = std::numeric_limits<double>::quiet_NaN();\n          return std::numeric_limits<double>::quiet_NaN();\n        }\n      }\n\n      init_draw(chain_idx) = draw(0);\n\n      if (draw.isApproxToConstant(draw(0))) {\n        are_all_const |= true;\n      }\n    }\n\n    if (are_all_const) {\n      // If all chains are constant then return NaN\n      // if they all equal the same constant value\n      if (init_draw.isApproxToConstant(init_draw(0))) {\n        ess = std::numeric_limits<double>::quiet_NaN();;\n        mcse = std::numeric_limits<double>::quiet_NaN();\n        return std::numeric_limits<double>::quiet_NaN();\n      }\n    }\n\n    Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains);\n    Eigen::VectorXd chain_mean(num_chains);\n    Eigen::VectorXd chain_sq_mean(num_chains);\n    Eigen::VectorXd chain_var(num_chains);\n    for (int chain = 0; chain < num_chains; ++chain) {\n      Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(\n              draws[chain], sizes[chain]);\n      stan::analyze::autocovariance<double>(draw, acov(chain));\n      chain_mean(chain) = draw.mean();\n      chain_sq_mean(chain) = draw.array().square().mean();\n      chain_var(chain) = acov(chain)(0) * num_draws / (num_draws - 1);\n    }\n\n    double mean_var = chain_var.mean();\n    double var_plus = mean_var * (num_draws - 1) / num_draws;\n    if (num_chains > 1)\n      var_plus += math::variance(chain_mean);\n    Eigen::VectorXd rho_hat_s(num_draws);\n    rho_hat_s.setZero();\n    Eigen::VectorXd acov_s(num_chains);\n    for (int chain = 0; chain < num_chains; ++chain)\n      acov_s(chain) = acov(chain)(1);\n    double rho_hat_even = 1.0;\n    rho_hat_s(0) = rho_hat_even;\n    double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;\n    rho_hat_s(1) = rho_hat_odd;\n\n    // Convert raw autocovariance estimators into Geyer's initial\n    // positive sequence. Loop only until num_draws - 4 to\n    // leave the last pair of autocorrelations as a bias term that\n    // reduces variance in the case of antithetical chains.\n    size_t s = 1;\n    while (s < (num_draws - 4) && (rho_hat_even + rho_hat_odd) > 0) {\n      for (int chain = 0; chain < num_chains; ++chain)\n        acov_s(chain) = acov(chain)(s + 1);\n      rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus;\n      for (int chain = 0; chain < num_chains; ++chain)\n        acov_s(chain) = acov(chain)(s + 2);\n      rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;\n      if ((rho_hat_even + rho_hat_odd) >= 0) {\n        rho_hat_s(s + 1) = rho_hat_even;\n        rho_hat_s(s + 2) = rho_hat_odd;\n      }\n      s += 2;\n    }\n\n    int max_s = s;\n    // this is used in the improved estimate, which reduces variance\n    // in antithetic case -- see tau_hat below\n    if (rho_hat_even > 0)\n      rho_hat_s(max_s + 1) = rho_hat_even;\n\n    // Convert Geyer's initial positive sequence into an initial\n    // monotone sequence\n    for (int s = 1; s <= max_s - 3; s += 2) {\n      if (rho_hat_s(s + 1) + rho_hat_s(s + 2) > rho_hat_s(s - 1) + rho_hat_s(s)) {\n        rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2;\n        rho_hat_s(s + 2) = rho_hat_s(s + 1);\n      }\n    }\n\n    double num_total_draws = num_chains * num_draws;\n    // Geyer's truncated estimator for the asymptotic variance\n    // Improved estimate reduces variance in antithetic case\n    double tau_hat = -1 + 2 * rho_hat_s.head(max_s).sum() + rho_hat_s(max_s + 1);\n    double ess_val = num_total_draws / tau_hat;\n    ess = ess_val;\n    mcse = std::sqrt((chain_sq_mean.mean() - chain_mean.mean() * chain_mean.mean())/ess_val);\n    return 0;\n  }\n\n protected:\n  Model& model_;\n  Eigen::VectorXd& cont_params_;\n  BaseRNG& rng_;\n  int n_monte_carlo_grad_;\n  int n_monte_carlo_elbo_;\n  int n_posterior_samples_;\n\n private:\n  virtual Q init_variational(Eigen::VectorXd& cont_params) const = 0;\n  virtual Q init_variational(size_t dimension) const = 0;\n};\n\n/**\n * The ADVI implementation used for meanfield and full-rank approximations.\n *\n * @tparam Model Class of model\n * @tparam Q Class of variational distribution, either mean-field or low-rank.\n * @tparam BaseRNG Class of random number generator\n */\ntemplate <class Model, class Q, class BaseRNG>\nclass advi : public advi_base<Model, Q, BaseRNG> {\n public:\n  advi(Model& m, Eigen::VectorXd& cont_params, BaseRNG& rng,\n       int n_monte_carlo_grad, int n_monte_carlo_elbo,\n       int n_posterior_samples)\n      : advi_base<Model, Q, BaseRNG>(m, cont_params, rng, n_monte_carlo_grad,\n                                     n_monte_carlo_elbo,\n                                     n_posterior_samples) {}\n\n private:\n  Q init_variational(Eigen::VectorXd& cont_params) const {\n    return Q(cont_params);\n  }\n\n  Q init_variational(size_t dimension) const { return Q(dimension); }\n};\n\n/**\n * The ADVI implementation used only for low-rank approximations.\n *\n * @tparam Model Class of model.\n * @tparam BaseRNG Class of random number generator.\n */\ntemplate <class Model, class BaseRNG>\nclass advi_lowrank\n    : public advi_base<Model, stan::variational::normal_lowrank, BaseRNG> {\n public:\n  /**\n   * Constructor\n   *\n   * @param[in] m stan model\n   * @param[in] cont_params initialization of continuous parameters\n   * @param[in,out] rng random number generator\n   * @param[in] rank rank of approximation\n   * @param[in] n_monte_carlo_grad number of samples for gradient computation\n   * @param[in] n_monte_carlo_elbo number of samples for ELBO computation\n   * @param[in] eval_elbo evaluate ELBO at every \"eval_elbo\" iters\n   * @param[in] n_posterior_samples number of samples to draw from posterior\n   * @throw std::runtime_error if n_monte_carlo_grad is not positive\n   * @throw std::runtime_error if n_monte_carlo_elbo is not positive\n   * @throw std::runtime_error if eval_elbo is not positive\n   * @throw std::runtime_error if n_posterior_samples is not positive\n   */\n  advi_lowrank(Model& m, Eigen::VectorXd& cont_params, BaseRNG& rng,\n               size_t rank, int n_monte_carlo_grad, int n_monte_carlo_elbo,\n               int n_posterior_samples)\n      : advi_base<Model, stan::variational::normal_lowrank, BaseRNG>(\n            m, cont_params, rng, n_monte_carlo_grad, n_monte_carlo_elbo,\n            n_posterior_samples),\n        rank_(rank) {\n    static const char* function = \"stan::variational::advi_lowrank\";\n    math::check_positive(function, \"Approximation rank\", rank_);\n  }\n\n protected:\n  size_t rank_;\n\n private:\n  stan::variational::normal_lowrank init_variational(\n      Eigen::VectorXd& cont_params) const {\n    return stan::variational::normal_lowrank(cont_params, rank_);\n  }\n\n  stan::variational::normal_lowrank init_variational(size_t dimension) const {\n    return stan::variational::normal_lowrank(dimension, rank_);\n  }\n};\n}  // namespace variational\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "b08c0100270b982a4b65a7e84c7e1c9bac8fe402", "size": 32043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/variational/advi.hpp", "max_stars_repo_name": "stephensrmmartin/stan", "max_stars_repo_head_hexsha": "e95c7bc9814792204ae8d900a1b47dfd17d88c0b", "max_stars_repo_licenses": ["CC-BY-3.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": "src/stan/variational/advi.hpp", "max_issues_repo_name": "stephensrmmartin/stan", "max_issues_repo_head_hexsha": "e95c7bc9814792204ae8d900a1b47dfd17d88c0b", "max_issues_repo_licenses": ["CC-BY-3.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/stan/variational/advi.hpp", "max_forks_repo_name": "stephensrmmartin/stan", "max_forks_repo_head_hexsha": "e95c7bc9814792204ae8d900a1b47dfd17d88c0b", "max_forks_repo_licenses": ["CC-BY-3.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": 39.4618226601, "max_line_length": 123, "alphanum_fraction": 0.6334612864, "num_tokens": 8170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.03258974265193152, "lm_q1q2_score": 0.014519692890774382}}
{"text": "/**\n * ****************************************************************************\n * Copyright (c) 2015, Robert Lukierski.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n * ****************************************************************************\n * Common types and functions.\n * ****************************************************************************\n */\n\n#ifndef CAMERA_MODEL_UTILS_HPP\n#define CAMERA_MODEL_UTILS_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/AutoDiff>\n\n#include <sophus/so2.hpp>\n#include <sophus/se2.hpp>\n#include <sophus/so3.hpp>\n#include <sophus/se3.hpp>\n\n// For future Eigen + CUDA\n#ifndef EIGEN_DEVICE_FUNC\n#define EIGEN_DEVICE_FUNC\n#endif // EIGEN_DEVICE_FUNC\n\n// If Cereal serializer is preferred\n#ifdef CAMERA_MODELS_SERIALIZER_CEREAL\n#define CAMERA_MODELS_HAVE_SERIALIZER\n#define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE(cereal::make_nvp(NAME,VAR))\n#endif // CAMERA_MODELS_SERIALIZER_CEREAL\n\n// If Boost serializer is preferred\n#ifdef CAMERA_MODELS_SERIALIZER_BOOST\n#define CAMERA_MODELS_HAVE_SERIALIZER\n#define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE & boost::serialization::make_nvp(NAME,VAR)\n#endif // CAMERA_MODELS_SERIALIZER_BOOST \n\n#ifndef VISIONCORE_EIGEN_MISSING_BITS_HPP\n#define VISIONCORE_EIGEN_MISSING_BITS_HPP\nnamespace Eigen \n{\n\nnamespace numext\n{\n  \ntemplate<typename T>\nEIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE\nT atan2(const T& y, const T &x) {\n  EIGEN_USING_STD_MATH(atan2);\n  return atan2(y,x);\n}\n\n#ifdef __CUDACC__\ntemplate<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE\nfloat atan2(const float& y, const float &x) { return ::atan2f(y,x); }\n\ntemplate<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE\ndouble atan2(const double& y, const double &x) { return ::atan2(y,x); }\n#endif\n  \n}\n\ntemplate<typename DerType> \ninline const Eigen::AutoDiffScalar<EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(typename Eigen::internal::remove_all<DerType>::type, typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar, product)> \natan(const Eigen::AutoDiffScalar<DerType>& x) \n{ \n  using namespace Eigen; \n  EIGEN_UNUSED typedef typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar Scalar; \n  using numext::atan;\n  return Eigen::MakeAutoDiffScalar(atan(x.value()),x.derivatives() * ( Scalar(1) / (Scalar(1) + x.value() * x.value()) ));\n}\n\n}\n#endif // VISIONCORE_EIGEN_MISSING_BITS_HPP\n\nnamespace cammod\n{\n\n/**\n * Camera Models\n */\nenum class CameraModelType\n{\n    PinholeDistance = 0,\n    PinholeDistanceDistorted,\n    PinholeDisparity,\n    PinholeDisparityDistorted,\n    Generic,\n    GenericDistorted,\n    Spherical,\n    SphericalPovRay,\n    Fisheye,\n    FisheyeDistorted,\n    PinholeDisparityBrownConrady\n};\n\ntemplate<CameraModelType cmt>\nstruct CameraModelToTypeAndName;\n\n/**\n * Collection of common 2D/3D types.\n */\ntemplate<typename T>\nstruct ComplexTypes\n{\n    typedef Sophus::SO3<T> RotationT;\n    typedef Sophus::SE3<T> TransformT;\n    typedef Eigen::Map<TransformT> TransformMapT;\n    typedef Eigen::Map<const TransformT> ConstTransformMapT;\n    typedef Eigen::Map<RotationT> RotationMapT;\n    typedef Eigen::Map<const RotationT> ConstRotationMapT;\n    \n    typedef Sophus::SO2<T> Rotation2DT;\n    typedef Sophus::SE2<T> Transform2DT;\n    typedef Eigen::Map<Transform2DT> Transform2DMapT;\n    typedef Eigen::Map<const Transform2DT> ConstTransform2DMapT;\n    typedef Eigen::Map<Rotation2DT> Rotation2DMapT;\n    typedef Eigen::Map<const Rotation2DT> ConstRotation2DMapT;\n    \n    typedef typename Sophus::SE3<T>::Tangent TangentTransformT;\n    typedef Eigen::Map<typename Sophus::SE3<T>::Tangent> TangentTransformMapT;\n    typedef Eigen::Map<const typename Sophus::SE3<T>::Tangent> ConstTangentTransformMapT;\n    \n    typedef typename Sophus::SE2<T>::Tangent TangentTransform2DT;\n    typedef Eigen::Map<typename Sophus::SE2<T>::Tangent> TangentTransform2DMapT;\n    typedef Eigen::Map<const typename Sophus::SE2<T>::Tangent> ConstTangentTransform2DMapT;\n    \n    typedef typename Sophus::SO3<T>::Tangent TangentRotationT;\n    typedef Eigen::Map<typename Sophus::SO3<T>::Tangent> TangentRotationMapT;\n    typedef Eigen::Map<const typename Sophus::SO3<T>::Tangent> ConstTangentRotationMapT;\n    \n    typedef typename Sophus::SO2<T>::Tangent TangentRotation2DT;\n    typedef Eigen::Map<typename Sophus::SO2<T>::Tangent> TangentRotation2DMapT;\n    typedef Eigen::Map<const typename Sophus::SO2<T>::Tangent> ConstTangentRotation2DMapT;\n    \n    typedef Eigen::Matrix<T,2,1> PixelT;\n    typedef Eigen::Map<PixelT> PixelMapT;\n    typedef Eigen::Map<const PixelT> ConstPixelMapT;\n    \n    typedef typename TransformT::Point PointT;\n    typedef Eigen::Map<PointT> PointMapT;\n    typedef Eigen::Map<const PointT> ConstPointMapT;\n    \n    typedef typename Transform2DT::Point Point2DT;\n    typedef Eigen::Map<Point2DT> Point2DMapT;\n    typedef Eigen::Map<const Point2DT> ConstPoint2DMapT;\n    \n    typedef Eigen::Quaternion<T> QuaternionT;\n    typedef Eigen::Map<QuaternionT> QuaternionMapT;\n    typedef Eigen::Map<const QuaternionT> ConstQuaternionMapT;\n    \n    typedef Eigen::Matrix<T,2,3> ForwardPointJacobianT;\n    typedef Eigen::Map<ForwardPointJacobianT> ForwardPointJacobianMapT;\n    typedef Eigen::Map<const ForwardPointJacobianT> ConstForwardPointJacobianMapT;\n    \n    typedef Eigen::Matrix<T,3,2> InversePointJacobianT;\n    typedef Eigen::Map<InversePointJacobianT> InversePointJacobianMapT;\n    typedef Eigen::Map<const InversePointJacobianT> ConstInversePointJacobianMapT;\n    \n    typedef Eigen::Matrix<T,2,2> DistortionJacobianT;\n    typedef Eigen::Map<DistortionJacobianT> DistortionJacobianMapT;\n    typedef Eigen::Map<const DistortionJacobianT> ConstDistortionJacobianMapT;\n    \n    template<int ParametersToOptimize>\n    using ForwardParametersJacobianT = Eigen::Matrix<T,2,ParametersToOptimize>;\n    template<int ParametersToOptimize>\n    using ForwardParametersJacobianMapT = Eigen::Map<ForwardParametersJacobianT<ParametersToOptimize>>;\n    template<int ParametersToOptimize>\n    using ConstForwardParametersJacobianMapT = Eigen::Map<const ForwardParametersJacobianT<ParametersToOptimize>>;\n};\n\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline T getFieldOfView(T focal, T width)\n{\n    using Eigen::numext::atan;\n    return T(2.0) * atan(width / (T(2.0) * focal));\n}\n\ntemplate<typename T>\nEIGEN_DEVICE_FUNC static inline T getFocalLength(T fov, T width)\n{\n    using Eigen::numext::tan;\n    return width / (T(2.0) * tan(fov / T(2.0)));\n}\n\n/**\n * Runtime polymorphic interface if one prefers that.\n */\ntemplate<typename T>\nclass CameraInterface\n{\npublic:\n    virtual ~CameraInterface() { }\n    \n    virtual CameraModelType getModelType() const = 0;\n    virtual const char* getModelName() const = 0;\n    virtual bool pointValid(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0;\n    virtual bool pixelValid(T x, T y) const = 0;\n    virtual bool pixelValidSquare(T x, T y) const = 0;\n    virtual bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const = 0;\n    virtual bool pixelValidCircular(T x, T y) const = 0;\n    virtual bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const = 0;\n    virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0;\n    virtual typename ComplexTypes<T>::PointT inverse(T x, T y) const = 0;\n    virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose, \n                                                     const typename ComplexTypes<T>::PointT& pt) const = 0;\n    virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose, \n                                                    const typename ComplexTypes<T>::PointT& pt) const = 0;\n    virtual typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const = 0;\n    virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0;\n    virtual typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const = 0;\n    virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, \n                                                               const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0;\n    virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, \n                                                               T x, T y, T dist) const = 0;\n    virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, \n                                                             const typename ComplexTypes<T>::PixelT& pix, T dist, \n                                                             const typename ComplexTypes<T>::TransformT& pose2) const = 0;\n    virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, \n                                                             T x, T y, T dist, const typename ComplexTypes<T>::TransformT& pose2) const = 0;\n};\n\n/**\n * Functions / methods shared by all the camera models.\n */\ntemplate<typename Derived>\nclass CameraFunctions \n{\n    static constexpr unsigned int ParametersToOptimize = Eigen::internal::traits<Derived>::ParametersToOptimize;\n    static constexpr bool HasForwardPointJacobian = Eigen::internal::traits<Derived>::HasForwardPointJacobian;\n    static constexpr bool HasForwardParametersJacobian = Eigen::internal::traits<Derived>::HasForwardParametersJacobian;\n    static constexpr bool HasInversePointJacobian = Eigen::internal::traits<Derived>::HasInversePointJacobian;\n    static constexpr bool HasInverseParametersJacobian = Eigen::internal::traits<Derived>::HasInverseParametersJacobian;\npublic:\n    typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;\n\n    // ------------------- statics ---------------------    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) \n    {\n        return pose.inverse() * pt; // why!\n    }\n\n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) \n    {\n        return pose * pt; // why!\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) \n    {\n        return pose.inverse() * pt; // why!\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) \n    {\n        return pose * pt; // why!\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)\n    {\n        return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)\n    {\n        return Derived::template pixelValidCircular<T>(ccd, pt(0), pt(1));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)\n    {\n        return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)\n    {\n        Derived::template resizeViewport<T>(ccd, pt(0), pt(1));\n    }\n\n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd, \n                                                                                          const typename ComplexTypes<T>::TransformT& pose, \n                                                                                          const typename ComplexTypes<T>::PointT& pt)\n    {\n        return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd, \n                                                                                          const typename ComplexTypes<T>::RotationT& pose, \n                                                                                          const typename ComplexTypes<T>::PointT& pt)\n    {\n        return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const Derived& ccd, \n                                                                                          const typename ComplexTypes<T>::PixelT& pix)\n    {\n        return Derived::template inverse<T>(ccd, pix(0), pix(1));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pix, T dist)\n    {\n        return Derived::template inverse<T>(ccd, pix(0), pix(1)) * dist;\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, T x, T y, T dist)\n    {\n        return Derived::template inverse<T>(ccd, x, y) * dist;\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, \n                                                                                                    const typename ComplexTypes<T>::TransformT& pose, \n                                                                                                    const typename ComplexTypes<T>::PixelT& pix, T dist)\n    {\n        return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,pix)) * dist));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, \n                                                                                                    const typename ComplexTypes<T>::TransformT& pose, \n                                                                                                    T x, T y, T dist)\n    {\n        return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,x,y)) * dist));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd, \n                                                                                                  const typename ComplexTypes<T>::TransformT& pose1, \n                                                                                                  const typename ComplexTypes<T>::PixelT& pix, \n                                                                                                  T dist, \n                                                                                                  const typename ComplexTypes<T>::TransformT& pose2)\n    {\n        return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, pix, dist));\n    }\n    \n    template<typename T = Scalar>\n    static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd, \n                                                                                                  const typename ComplexTypes<T>::TransformT& pose1, \n                                                                                                  T x, T y, T dist, \n                                                                                                  const typename ComplexTypes<T>::TransformT& pose2)\n    {\n        return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, x, y, dist));\n    }\n    \n    // ------------------- non statics ---------------------\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(T x, T y)\n    {\n        Derived::template resizeViewport<T>(*static_cast<Derived*>(this), x, y);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(const typename ComplexTypes<T>::PixelT& pt)\n    {\n        Derived::template resizeViewport<T>(*static_cast<Derived*>(this), pt(0), pt(1));\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pointValid(const typename ComplexTypes<T>::PointT& pt) const\n    {\n        return Derived::template pointValid<T>(*static_cast<const Derived*>(this), pt);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(T x, T y) const\n    {\n        return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(T x, T y) const\n    {\n        return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const\n    {\n        return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), pt(0), pt(1));\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(T x, T y) const\n    {\n        return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), x, y);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const\n    {\n        return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), pt(0), pt(1));\n    }\n        \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const\n    {\n        return Derived::template forward<T>(*static_cast<const Derived*>(this), tmp_pt);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(T x, T y) const\n    {\n        return Derived::template inverse<T>(*static_cast<const Derived*>(this), x, y);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) const\n    {\n        return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) const\n    {\n        return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardPointJacobian, typename ComplexTypes<T>::ForwardPointJacobianT>::type forwardPointJacobian(const typename ComplexTypes<T>::PointT& pt) const\n    {\n        return Derived::template forwardPointJacobian<T>(*static_cast<const Derived*>(this), pt);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardParametersJacobian, typename ComplexTypes<T>::template ForwardParametersJacobianT<ParametersToOptimize> >::type forwardParametersJacobian(const typename ComplexTypes<T>::PointT& pt) const\n    {\n        return Derived::template forwardParametersJacobian<T>(*static_cast<const Derived*>(this), pt);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const\n    {\n        return CameraFunctions::inverse<T>(*static_cast<const Derived*>(this), pix);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const\n    {\n        return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pix, dist); \n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const\n    {\n        return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), x, y, dist);\n    }\n    \n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, \n                                                                                const typename ComplexTypes<T>::PixelT& pix, T dist) const\n    {\n        return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, pix, dist);\n    }\n\n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, T x, T y, T dist) const\n    {\n        return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, x, y, dist);\n    }\n\n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, const typename ComplexTypes<T>::PixelT& pix, T dist, \n                                                                                           const typename ComplexTypes<T>::TransformT& pose2) const\n    {\n        return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, pix, dist, pose2);\n    }\n\n    template<typename T = Scalar>\n    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, T x, T y, T dist, \n                                                                                           const typename ComplexTypes<T>::TransformT& pose2) const\n    {\n        return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, x, y, dist, pose2);\n    }\n};\n\n/**\n * Wraps templated typed camera model into a polymorphic class.\n */\ntemplate <typename ModelT>\nclass CameraFromCRTP : public ModelT, public CameraInterface<typename ModelT::Scalar>\n{\npublic:\n    typedef ModelT Derived;\n    typedef typename Derived::Scalar Scalar;\n    \n    CameraFromCRTP() = default;\n    CameraFromCRTP(const Derived& d) : Derived(d) { }\n    CameraFromCRTP(const CameraFromCRTP& other) = default;\n    \n    virtual ~CameraFromCRTP() { }\n    \n    virtual CameraModelType getModelType() const \n    { \n        return Derived::ModelType; \n    } \n    \n    virtual const char* getModelName() const\n    {\n        return CameraModelToTypeAndName<Derived::ModelType>::Name;\n    }\n    \n    virtual bool pointValid(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const\n    {\n        return Derived::template pointValid<Scalar>(tmp_pt); \n    }\n    \n    virtual bool pixelValid(Scalar x, Scalar y) const \n    { \n        return Derived::template pixelValid<Scalar>(x,y); \n    }\n    \n    virtual bool pixelValidSquare(Scalar x, Scalar y) const \n    { \n        return Derived::template pixelValidSquare<Scalar>(x,y); \n    }\n    \n    virtual bool pixelValidSquare(const typename ComplexTypes<Scalar>::PixelT& pt) const \n    { \n        return Derived::template pixelValidSquare<Scalar>(pt); \n    }\n    \n    virtual bool pixelValidCircular(Scalar x, Scalar y) const \n    { \n        return Derived::template pixelValidCircular<Scalar>(x,y); \n    }\n    \n    virtual bool pixelValidCircular(const typename ComplexTypes<Scalar>::PixelT& pt) const \n    { \n        return Derived::template pixelValidCircular<Scalar>(pt); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const \n    { \n        return Derived::template forward<Scalar>(tmp_pt); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PointT inverse(Scalar x, Scalar y) const \n    { \n        return Derived::template inverse<Scalar>(x,y); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::TransformT& pose, \n                                                          const typename ComplexTypes<Scalar>::PointT& pt) const \n    { \n        return Derived::template forward<Scalar>(pose, pt); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::RotationT& pose, \n                                                          const typename ComplexTypes<Scalar>::PointT& pt) const \n    { \n        return Derived::template forward<Scalar>(pose, pt); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PointT inverse(const typename ComplexTypes<Scalar>::PixelT& pix) const \n    { \n        return Derived::template inverse<Scalar>(pix); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::PixelT& pix, \n                                                                    Scalar dist) const \n    { \n        return Derived::template inverseAtDistance<Scalar>(pix,dist); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(Scalar x, Scalar y, Scalar dist) const \n    { \n        return Derived::template inverseAtDistance<Scalar>(x,y,dist); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose, \n                                                                    const typename ComplexTypes<Scalar>::PixelT& pix, \n                                                                    Scalar dist) const \n    { \n        return Derived::template inverseAtDistance<Scalar>(pose,pix,dist); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose, \n                                                                    Scalar x, Scalar y, Scalar dist) const \n    { \n        return Derived::template inverseAtDistance<Scalar>(pose,x,y,dist); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1, \n                                                                  const typename ComplexTypes<Scalar>::PixelT& pix, \n                                                                  Scalar dist, \n                                                                  const typename ComplexTypes<Scalar>::TransformT& pose2) const \n    { \n        return Derived::template twoFrameProject<Scalar>(pose1,pix,dist,pose2); \n    }\n    \n    virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1, \n                                                                  Scalar x, Scalar y, Scalar dist, \n                                                                  const typename ComplexTypes<Scalar>::TransformT& pose2) const \n    { \n        return Derived::template twoFrameProject<Scalar>(pose1,x,y,dist,pose2); \n    }\n};\n\n}\n\n#endif // CAMERA_MODEL_UTILS_HPP\n", "meta": {"hexsha": "d88f5accbe4168ea1013c8b0dca216ac0573e7fd", "size": 29740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/CameraModels/CameraModelUtils.hpp", "max_stars_repo_name": "lukier/camera_models", "max_stars_repo_head_hexsha": "90196141fa4749148b6a7b0adc7af19cb1971039", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2016-11-13T22:17:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T19:59:25.000Z", "max_issues_repo_path": "include/CameraModels/CameraModelUtils.hpp", "max_issues_repo_name": "lukier/camera_models", "max_issues_repo_head_hexsha": "90196141fa4749148b6a7b0adc7af19cb1971039", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/CameraModels/CameraModelUtils.hpp", "max_forks_repo_name": "lukier/camera_models", "max_forks_repo_head_hexsha": "90196141fa4749148b6a7b0adc7af19cb1971039", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-02T11:56:50.000Z", "avg_line_length": 46.3239875389, "max_line_length": 263, "alphanum_fraction": 0.6488567586, "num_tokens": 6576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.030675799606029917, "lm_q1q2_score": 0.014499943605889925}}
{"text": "// Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.\n\n// Boost Software License - Version 1.0 - August 17th, 2003\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//  Authors: Thejaka Kanewala\n//           Andrew Lumsdaine\n\n#ifndef __AGM_SSSP_HPP\n#define __AGM_SSSP_HPP\n\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\n#include <boost/graph/agm/util/stat.hpp>\n#include <boost/graph/agm/model/agm.hpp>\n#include <boost/graph/agm/runtime/runtime.hpp>\n#include <boost/graph/agm/model/general_orderings.hpp>\n\n#define VISITED_THRESHOLD 100\n\nnamespace boost { namespace graph { namespace agm {\n      \n// definition of the SSSP work item set\ntypedef uint32_t Distance;\ntypedef uint32_t Weight;\n\ntemplate<typename Graph>\nclass sssp_family {\n\n  typedef typename boost::graph_traits < Graph >::vertex_descriptor Vertex;\n\n  // work item set definition\n  // Every work item must have the time\n  // destination, source, distance\n  typedef std::tuple<Vertex, Distance> WorkItem;\n\n  // For level ordering, redifining the work item\n  typedef int Level;\n  // work item set definition\n  // Every work item must have the time\n  // destination, distance\n  typedef std::tuple<Vertex, Distance, Level> LevelWorkItem;\n\n  //===================================================================================\n  // Pair of processing functions : post order pf and pre-order pf\n  //===================================================================================\n  // the processing function  \n  template<typename WeightState,\n           typename DistanceState>\n  struct post_order_sssp_pf {\n    \n  public:\n    post_order_sssp_pf(const Graph& _rg,\n                       WeightState& _vweight,\n                       DistanceState& _dist,\n                       agm_work_stats& _sr) : g(_rg),\n                                              vdistance(_dist),\n                                              vweight(_vweight),\n                                              stats(_sr){}\n    \n  private:\n    const Graph& g;\n    DistanceState& vdistance;\n    WeightState& vweight;\n    agm_work_stats& stats;    \n\n  public:\n    template<typename outset>\n    void operator()(const WorkItem& w,\n                    int tid,\n                    outset& out) {\n      Vertex v = std::get<0>(w);\n      Distance d = std::get<1>(w);\n\n      Distance vd;\n      __atomic_load(&vdistance[v], &vd, __ATOMIC_SEQ_CST);\n      if (vd == d) {\n        BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n          Vertex u = boost::target(e, g);\n          Distance we = boost::get(vweight, e);\n#ifdef PBGL2_PRINT_WORK_STATS\n          stats.increment_edges(tid);\n#endif          \n          WorkItem generated(u, (d+we));\n          out.push(generated, tid);\n        }\n      }\n#ifdef PBGL2_PRINT_WORK_STATS\n      else {\n        stats.increment_invalidated_cancels(tid);\n      }\n#endif                \n    }\n\n    // for level work items\n    template<typename outset>\n    void operator()(const LevelWorkItem& w,\n                    int tid,\n                    outset& out) {\n      Vertex v = std::get<0>(w);\n      Distance d = std::get<1>(w);\n      Level level = std::get<2>(w);            \n\n      if (vdistance[v] == d) {\n        BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n          Vertex u = boost::target(e, g);\n          Distance we = boost::get(vweight, e);\n#ifdef PBGL2_PRINT_WORK_STATS\n          stats.increment_edges(tid);\n#endif          \n          LevelWorkItem generated(u, (d+we), (level+1));\n          out.push(generated, tid);\n        }\n      }\n#ifdef PBGL2_PRINT_WORK_STATS\n      else {\n        stats.increment_invalidated_cancels(tid);\n      }\n#endif      \n    }    \n  };  \n  \n  // the pre-order processing function  \n  template<typename WeightState,\n           typename DistanceState>\n  struct pre_order_sssp_pf {\n\n  public:\n    pre_order_sssp_pf(const Graph& _rg,\n            WeightState& _weight,\n            DistanceState& _dist,\n            agm_work_stats& _sr) : g(_rg),\n                                   vweight(_weight),\n                                   vdistance(_dist),\n                                   stats(_sr){}\n\n  private:\n    const Graph& g;\n    WeightState& vweight;        \n    DistanceState& vdistance;\n    agm_work_stats& stats;\n\n  public:\n\n    template<typename work_item, typename buckets>\n    void operator()(const work_item& wi,\n                    int tid,\n\t\t    buckets& outset) {\n      Vertex v = std::get<0>(wi);\n      Distance d = std::get<1>(wi);\n\n      Distance old_dist = vdistance[v], last_old_dist;\n\n      while (d < old_dist) {\n        last_old_dist = old_dist;\n        old_dist = boost::parallel::val_compare_and_swap(&vdistance[v], old_dist, d);\n        if (last_old_dist == old_dist) {\n#ifdef PBGL2_PRINT_WORK_STATS        \n          if (old_dist < std::numeric_limits<weight_type>::max()) {\n            stats.increment_invalidated(tid);\n          } else\n            stats.increment_useful(tid);            \n#endif\n          outset.push(wi, tid);          \n          return;\n        }\n      }\n      \n#ifdef PBGL2_PRINT_WORK_STATS                \n      stats.increment_rejected(tid);\n#endif      \n    }\n  };\n\n  //=====================================================================\n  // The general processing function that can be used as the\n  // pre-order processing function or post-order processing\n  // function.\n  //=====================================================================\n  // the processing function  \n  template<typename WeightState,\n           typename DistanceState>\n  struct sssp_pf {\n\n  public:\n    sssp_pf(const Graph& _rg,\n            WeightState& _weight,\n            DistanceState& _dist,\n            agm_work_stats& _sr) : g(_rg),\n                                   vweight(_weight),\n                                   vdistance(_dist),\n                                   stats(_sr){}\n\n  private:\n    const Graph& g;\n    WeightState& vweight;        \n    DistanceState& vdistance;\n    agm_work_stats& stats;\n\n  public:\n\n    template<typename buckets>\n    void operator()(const WorkItem& wi,\n                    int tid,\n\t\t    buckets& outset) {\n\n      Vertex v = std::get<0>(wi);\n      Distance d = std::get<1>(wi);\n\n      Distance old_dist = vdistance[v], last_old_dist;\n\n      while (d < old_dist) {\n        last_old_dist = old_dist;\n        old_dist = boost::parallel::val_compare_and_swap(&vdistance[v], old_dist, d);\n        if (last_old_dist == old_dist) {\n#ifdef PBGL2_PRINT_WORK_STATS        \n          if (old_dist < std::numeric_limits<weight_type>::max()) {\n            stats.increment_invalidated(tid);\n          } else\n            stats.increment_useful(tid);            \n#endif\n          \n          BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n            Vertex u = boost::target(e, g);\n            Distance we = boost::get(vweight, e);\n#ifdef PBGL2_PRINT_WORK_STATS\n            stats.increment_edges(tid);\n#endif\n            WorkItem generated(u, (d+we));\n            outset.push(generated, tid);\n          }\n\n          return;\n        }\n      }\n      \n#ifdef PBGL2_PRINT_WORK_STATS                \n      stats.increment_rejected(tid);\n#endif      \n    }\n\n\n    // For level ordering\n    template<typename buckets>\n    void operator()(const LevelWorkItem& wi,\n                    int tid,\n\t\t    buckets& outset) {\n      \n      Vertex v = std::get<0>(wi);\n      Distance d = std::get<1>(wi);\n      Level l = std::get<2>(wi);      \n\n      Distance old_dist = vdistance[v], last_old_dist;\n      \n      while (d < old_dist) {\n        last_old_dist = old_dist;\n        old_dist = boost::parallel::val_compare_and_swap(&vdistance[v], old_dist, d);\n        if (last_old_dist == old_dist) {\n#ifdef PBGL2_PRINT_WORK_STATS        \n          if (old_dist < std::numeric_limits<weight_type>::max()) {\n            stats.increment_invalidated(tid);\n          } else\n            stats.increment_useful(tid);            \n#endif\n          \n          BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n            Vertex u = boost::target(e, g);\n            Distance we = boost::get(vweight, e);\n#ifdef PBGL2_PRINT_WORK_STATS\n            stats.increment_edges(tid);\n#endif            \n            LevelWorkItem generated(u, (d+we), (l+1));\n            outset.push(generated, tid);\n          }\n\n          return;\n        }\n      }\n      \n#ifdef PBGL2_PRINT_WORK_STATS                \n      stats.increment_rejected(tid);\n#endif      \n    }\n  };\n  \n\npublic:\n\n  template <typename DistMap, typename WeightMap>\n  bool verify(const Graph& g, DistMap& distance, WeightMap& weight) {\n    distance.set_consistency_model(boost::parallel::cm_forward);\n    distance.set_max_ghost_cells(0);\n\n    { amplusplus::scoped_epoch epoch(g.transport()); }\n    \n    if (g.transport().rank() == 0) std::cout<<\"[INFO] Verifying results......\";\n\n    {\n      amplusplus::scoped_epoch epoch(g.transport());\n\t  \n      BGL_FORALL_VERTICES_T(v, g, Graph) {\n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t  get(distance, target(e, g));\n\t}\n      }\n    }\n\t    \n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n        //#ifdef 1 //PRINT_DEBUG\n\tif (get(distance, target(e, g)) > \n\t    boost::closed_plus<Distance>()(get(distance, v), get(weight, e))) {\n\t  std::cout << get(get(vertex_local, g), source(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), source(e, g)) << \"->\"\n\t\t    << get(get(vertex_local, g), target(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), target(e, g)) << \"  weight = \"\n\t\t    << get(weight, e)\n\t\t    << \"  distance(\" << get(get(vertex_local, g), source(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), source(e, g))\n\t\t    << \") = \" << get(distance, source(e, g)) << \"  distance(\" \n\t\t    << get(get(vertex_local, g), target(e, g)) << \"@\" \n\t\t    << get(get(vertex_owner, g), target(e, g)) << \") = \" \n\t\t    << get(distance, target(e, g)) << std::endl;\n          \n          std::cout << \"[ERROR] Verification failed.\" << std::endl;\n          assert(false);\n        }\n      }\n    }\n\n    if (g.transport().rank() == 0) std::cout << \"Verified.\" << std::endl;\n    distance.clear(); // Clear memory used by ghost cells\n\n    return true;\n  }\n\n  template <typename DistanceMap>\n  uint64_t count_visited_vertices(Graph& g, DistanceMap& distance) {\n    uint64_t vvertices = 0;\n    weight_type dist;\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      dist = boost::get(distance, v);\n      if(dist < std::numeric_limits<Distance>::max()) {\n\tvvertices+=1;\n      }\n    }\n\n    uint64_t totalverts = 0;\n    MPI_Allreduce(&vvertices, &totalverts, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD);\n    return totalverts;\n  }\n  \n\n  template<typename WeightMap,\n           typename DistMap,\n           typename RuntimeModelGen,\n           typename EAGMConfig,\n           typename WorkItemType>\n  time_type execute_split_pf(Graph& g,\n                             WeightMap& weights,\n                             DistMap& distance_state,\n                             RuntimeModelGen rtmodelgen,\n                             EAGMConfig& config,\n                             WorkItemType sw,\n                             instance_params& runtime_params,\n                             agm_work_stats& sr, \n                             bool _verify=true) {\n    \n    info(\"Setting the initial work item set ...\");\n    // Initial work item set\n    typedef append_buffer<WorkItemType, 10u> InitialWorkItems;\n    InitialWorkItems initial;\n    auto s = std::get<0>(sw);\n    if (get(get(vertex_owner, g), s) == _RANK) {      \n      distance_state[s] = 0;\n      initial.push_back(sw);\n      \n#ifdef PBGL2_PRINT_WORK_STATS        \n      sr.increment_useful(0);            \n#endif\n      \n    }\n    \n    // Processing funcion\n    typedef pre_order_sssp_pf<WeightMap, DistMap> ProcessingFunction;\n    ProcessingFunction pf(g, weights, distance_state, sr);\n\n    //Send predicate\n    typedef post_order_sssp_pf<WeightMap, DistMap> PostOrderProcessingFunction;\n    PostOrderProcessingFunction sendpf(g, weights, distance_state, sr);\n    \n    // SSSP algorithm\n    typedef eagm<Graph,\n                 WorkItemType,\n                 ProcessingFunction,\n                 EAGMConfig,\n                 RuntimeModelGen,\n                 PostOrderProcessingFunction> sssp_eagm_t;\n\n    sssp_eagm_t ssspalgo(rtmodelgen,\n                         config,\n                         pf,\n                         sendpf,\n                         initial);\n    \n    info(\"Invoking SSSP algorithm with split processing functions ...\");\n    time_type elapsed = ssspalgo(runtime_params);\n\n#ifdef PBGL2_PRINT_WORK_STATS\n    ssspalgo.print_stats();\n#endif    \n    \n    return elapsed;    \n  }\n  \n  template<typename WeightMap,\n           typename DistMap,\n           typename RuntimeModelGen,\n           typename EAGMConfig,\n           typename WorkItemType>\n  time_type execute_pre_order_pf(Graph& g,\n                                 WeightMap& weights,\n                                 DistMap& distance_state,\n                                 RuntimeModelGen rtmodelgen,\n                                 EAGMConfig& config,\n                                 WorkItemType sw,\n                                 instance_params& runtime_params,\n                                 agm_work_stats& sr, \n                                 bool _verify=true) {\n    \n    info(\"Setting the initial work item set ...\");\n    // Initial work item set\n    typedef append_buffer<WorkItemType, 10u> InitialWorkItems;\n    InitialWorkItems initial;\n    auto s = std::get<0>(sw);\n    if (get(get(vertex_owner, g), s) == _RANK) {\n      initial.push_back(sw);\n    }\n    \n    // Processing funcion\n    typedef sssp_pf<WeightMap, DistMap> ProcessingFunction;\n    ProcessingFunction pf(g, weights, distance_state, sr);    \n    \n    // SSSP algorithm\n    typedef eagm<Graph,\n                 WorkItemType,\n                 ProcessingFunction,\n                 EAGMConfig,\n                 RuntimeModelGen,\n                 EMPTY_PF> sssp_eagm_t;\n\n    sssp_eagm_t ssspalgo(rtmodelgen,\n                         config,\n                         pf,\n                         initial);\n    \n    info(\"Invoking SSSP algorithm with preorder processing functions ...\");\n    time_type elapsed = ssspalgo(runtime_params);\n\n#ifdef PBGL2_PRINT_WORK_STATS\n    ssspalgo.print_stats();\n#endif    \n    \n    return elapsed;    \n  }  \n\n  \n  template<typename WeightMap,\n           typename DistMap,\n           typename RuntimeModelGen,\n           typename EAGMConfig,\n           typename WorkItemType>  \n  time_type execute_post_order_pf(Graph& g,\n                                 WeightMap& weights,\n                                 DistMap& distance_state,\n                                 RuntimeModelGen rtmodelgen,\n                                 EAGMConfig& config,\n                                 WorkItemType sw,\n                                 instance_params& runtime_params,\n                                 agm_work_stats& sr, \n                                 bool _verify=true) {\n    \n    info(\"Setting the initial work item set ...\");\n    // Initial work item set\n    typedef append_buffer<WorkItemType, 10u> InitialWorkItems;\n    InitialWorkItems initial;\n    auto s = std::get<0>(sw);\n    if (get(get(vertex_owner, g), s) == _RANK) {\n      initial.push_back(sw);\n    }\n    \n    // Processing funcion\n    typedef sssp_pf<WeightMap, DistMap> ProcessingFunction;\n    ProcessingFunction pf(g, weights, distance_state, sr);\n    \n    // SSSP algorithm\n    typedef eagm<Graph,\n                 WorkItemType,\n                 EMPTY_PF,\n                 EAGMConfig,\n                 RuntimeModelGen,\n                 ProcessingFunction> sssp_eagm_t;\n\n    sssp_eagm_t ssspalgo(rtmodelgen,\n                         config,\n                         pf,\n                         initial);\n    \n    info(\"Invoking SSSP algorithm with post-processing functions ...\");\n    time_type elapsed = ssspalgo(runtime_params);\n    \n#ifdef PBGL2_PRINT_WORK_STATS\n    ssspalgo.print_stats();\n#endif    \n\n    return elapsed;        \n  }\n  \n  template<typename WeightMap,\n           typename RuntimeModelGen,\n           typename EAGMConfig,\n           typename WorkItemType,\n           typename agm_param_type>\n  time_type execute_eagm_common(Graph& g,\n                                WeightMap& weights,\n                                RuntimeModelGen rtmodelgen,\n                                EAGMConfig& config,\n                                WorkItemType sw,\n                                agm_param_type& agm_params,\n                                instance_params& runtime_params,\n                                agm_work_stats& sr, \n                                bool _verify=true) {\n\n    info(\"Creating the state ...\");\n    // State\n    typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMap;\n    std::vector<Distance> distmap(num_vertices(g), std::numeric_limits<Distance>::max());\n    typedef boost::iterator_property_map<typename std::vector<Distance>::iterator, VertexIndexMap> DistMap;\n    DistMap distance_state(distmap.begin(), get(boost::vertex_index, g));\n    time_type elapsed = -1;\n\n    if (agm_params.pf_mode == agm_pf_splitted) {\n      elapsed = execute_split_pf(g,\n                                 weights,\n                                 distance_state,\n                                 rtmodelgen,\n                                 config,\n                                 sw,\n                                 runtime_params,\n                                 sr,\n                                 _verify);\n    } else if (agm_params.pf_mode == agm_pf_preorder) {\n      elapsed = execute_pre_order_pf(g,\n                                     weights,\n                                     distance_state,\n                                     rtmodelgen,\n                                     config,\n                                     sw,\n                                     runtime_params,\n                                     sr,\n                                     _verify);      \n    } else if (agm_params.pf_mode == agm_pf_postorder) {\n      elapsed = execute_post_order_pf(g,\n                                     weights,\n                                     distance_state,\n                                     rtmodelgen,\n                                     config,\n                                     sw,\n                                     runtime_params,\n                                     sr,\n                                     _verify);      \n      \n    } else {\n      error(\"Invalid processing function invocation mode!\");\n      assert(false);\n    }\n    \n    if (_verify) {\n      verify(g, distance_state, weights);\n    }\n\n    //visited vertices threshold\n    // if the number if visited vertices are less than\n    // visited threshold repeat the run\n    auto visited = count_visited_vertices(g, distance_state);\n    if (boost::num_vertices(g) > VISITED_THRESHOLD) {\n      if (visited < VISITED_THRESHOLD)\n        elapsed = -1;\n    }\n\n    return elapsed;\n  }\n\n  template<typename WeightMap,\n           typename RuntimeModelGen,\n           typename EAGMConfig,\n           typename agm_param_type>\n  time_type execute_eagm(Graph& g,\n                         WeightMap& weights,\n                         RuntimeModelGen rtmodelgen,\n                         EAGMConfig& config,\n                         agm_param_type& agm_param,\n                         Vertex source,\n                         instance_params& runtime_params,\n                         agm_work_stats& sr, \n                         bool _verify=true) {\n\n    WorkItem w(source, 0);\n\n    return execute_eagm_common(g,\n                               weights,\n                               rtmodelgen,\n                               config,\n                               w,\n                               agm_param,\n                               runtime_params,\n                               sr,\n                               _verify);\n  }  \n\n  template<typename WeightMap,\n           typename RuntimeModelGen,\n           typename EAGMConfig,\n           typename agm_param_type>\n  time_type execute_klevel_eagm(Graph& g,\n                                WeightMap& weights,\n                                RuntimeModelGen rtmodelgen,\n                                EAGMConfig& config,\n                                agm_param_type& agm_param,\n                                Vertex source,\n                                instance_params& runtime_params,\n                                agm_work_stats& sr, \n                                bool _verify=true) {\n    \n    LevelWorkItem w(source, 0, 0);\n\n    return execute_eagm_common(g,\n                               weights,\n                               rtmodelgen,\n                               config,\n                               w,\n                               agm_param,\n                               runtime_params,\n                               sr,\n                               _verify);\n  }  \n\n  \n};\n\n}}}\n#endif\n", "meta": {"hexsha": "b91c9b81be9b6f402baaee15e830bf81d0736daa", "size": 22356, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/agm/algorithms/sssp.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": "boost/graph/agm/algorithms/sssp.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": "boost/graph/agm/algorithms/sssp.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": 33.0221565731, "max_line_length": 107, "alphanum_fraction": 0.5298801217, "num_tokens": 4651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.04603390648912335, "lm_q1q2_score": 0.01445697401209564}}
{"text": "/*\n\n\n\tThis file is part of PEST++.\n\n\tPEST++ is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tPEST++ is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with PEST++.  If not, see<http://www.gnu.org/licenses/>.\n*/\n\n#include \"RunManagerPanther.h\" //needs to be first because it includes winsock2.h\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iomanip>\n#include \"config_os.h\"\n#include \"MorrisMethod.h\"\n#include \"sobol.h\"\n//#include \"TornadoPlot.h\"\n#include \"Pest.h\"\n#include \"Transformable.h\"\n#include \"Transformation.h\"\n#include \"ParamTransformSeq.h\"\n#include \"utilities.h\"\n#include \"pest_error.h\"\n#include \"ModelRunPP.h\"\n#include \"FileManager.h\"\n#include \"RunManagerSerial.h\"\n#include \"OutputFileWriter.h\"\n#include \"PantherAgent.h\"\n#include \"Serialization.h\"\n#include \"system_variables.h\"\n\n\n\nusing namespace std;\nusing namespace pest_utils;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n\nint main(int argc, char* argv[])\n{\n#ifndef _DEBUG\n\ttry\n\t{\n#endif\n\tstring version = PESTPP_VERSION;\n\tcout << endl << endl;\n\tcout << \"             pestpp-sen: a tool for global sensitivity analysis\" << endl << endl;\n\tcout << \"                       by The PEST++ Development Team\" << endl;\n\tcout << endl << endl << \"version: \" << version << endl;\n\tcout << \"binary compiled on \" << __DATE__ << \" at \" << __TIME__ << endl << endl;\n\t\n\t// build commandline\n\tstring commandline = \"\";\n\tfor(int i=0; i<argc; ++i)\n\t{\n\t\tcommandline.append(\" \");\n\t\tcommandline.append(argv[i]);\n\t}\n\n\tvector<string> cmd_arg_vec(argc);\n\tcopy(argv, argv + argc, cmd_arg_vec.begin());\n\tfor (vector<string>::iterator it = cmd_arg_vec.begin(); it != cmd_arg_vec.end(); ++it)\n\t{\n\t\ttransform(it->begin(), it->end(), it->begin(), ::tolower);\n\t}\n\n\tstring complete_path;\n\tenum class RunManagerType {SERIAL, PANTHER, GENIE};\n\n\tif (argc >=2) {\n\t\tcomplete_path = argv[1];\n\t}\n\telse {\n\t\tcerr << \"--------------------------------------------------------\" << endl;\n\t\tcerr << \"usage:\" << endl << endl;\n\t\tcerr << \"    serial run manager:\" << endl;\n\t\tcerr << \"        gsa pest_ctl_file.pst\" << endl << endl;\n\t\tcerr << \"    PANTHER master:\" << endl;\n\t\tcerr << \"        gsa control_file.pst /H :port\" << endl;\n\t\tcerr << \"    PANTHER worker:\" << endl;\n\t\tcerr << \"        gsa control_file.pst /H hostname:port \" << endl << endl;\n\t\tcerr << \" additional options can be found in the PEST++ manual\" << endl;\n\t\tcerr << \"--------------------------------------------------------\" << endl;\n\t\texit(0);\n\t}\n\n\tFileManager file_manager;\n\tstring filename = complete_path;\n\tstring pathname = \".\";\n\tfile_manager.initialize_path(get_filename_without_ext(filename), pathname);\n\n\t//by default use the serial run manager.  This will be changed later if another\n\t//run manger is specified on the command line.\n\tRunManagerType run_manager_type = RunManagerType::SERIAL;\n\t//Check for PANTHER worker\n\tvector<string>::const_iterator it_find, it_find_next;\n\tstring next_item;\n\tstring socket_str = \"\";\n\tit_find = find(cmd_arg_vec.begin(), cmd_arg_vec.end(), \"/h\");\n\tnext_item.clear();\n\tif (it_find != cmd_arg_vec.end() && it_find + 1 != cmd_arg_vec.end())\n\t{\n\t\tnext_item = *(it_find + 1);\n\t\tstrip_ip(next_item);\n\t}\n\tif (it_find != cmd_arg_vec.end() && !next_item.empty() && next_item[0] != ':')\n\t{\n\t\t// This is a PANTHER worker, start PEST++ as a PANTHER worker\n\t\tvector<string> sock_parts;\n\t\tvector<string>::const_iterator it_find_yamr_ctl;\n\t\tstring file_ext = get_filename_ext(filename);\n\t\ttokenize(next_item, sock_parts, \":\");\n\t\ttry\n\t\t{\n\t\t\tif (sock_parts.size() != 2)\n\t\t\t{\n\t\t\t\tcerr << \"PANTHER worker requires the master be specified as /H hostname:port\" << endl << endl;\n\t\t\t\tthrow(PestCommandlineError(commandline));\n\t\t\t}\n\t\t\tPANTHERAgent yam_agent;\n\t\t\tstring ctl_file = \"\";\n\t\t\ttry {\n\t\t\t\tstring ctl_file;\n\t\t\t\tif (upper_cp(file_ext) == \"YMR\")\n\t\t\t\t{\n\t\t\t\t\tctl_file = file_manager.build_filename(\"ymr\");\n\t\t\t\t\tyam_agent.process_panther_ctl_file(ctl_file);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// process traditional PEST control file\n\t\t\t\t\tctl_file = file_manager.build_filename(\"pst\");\n\t\t\t\t\tyam_agent.process_ctl_file(ctl_file);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (PestError e)\n\t\t\t{\n\t\t\t\tcerr << \"Error prococessing control file: \" << ctl_file << endl << endl;\n\t\t\t\tcerr << e.what() << endl << endl;\n\t\t\t\tthrow(e);\n\t\t\t}\n\n\t\t\tyam_agent.start(sock_parts[0], sock_parts[1]);\n\t\t}\n\t\tcatch (PestError &perr)\n\t\t{\n\t\t\tcerr << perr.what();\n\t\t\tthrow(perr);\n\t\t}\n\t\tcout << endl << \"Simulation Complete...\" << endl;\n\t\texit(0);\n\t}\n\t//Check for PANTHER master\n\telse if (it_find != cmd_arg_vec.end())\n\t{\n\t\t// using PANTHER run manager\n\t\trun_manager_type = RunManagerType::PANTHER;\n\t\tsocket_str = next_item;\n\t}\n\n\tit_find = find(cmd_arg_vec.begin(), cmd_arg_vec.end(), \"/g\");\n\tnext_item.clear();\n\tit_find = find(cmd_arg_vec.begin(), cmd_arg_vec.end(), \"/g\");\n\tnext_item.clear();\n\tif (it_find != cmd_arg_vec.end())\n\t{\n\t\tcerr << \"Genie run manager ('/g') no longer supported, please use PANTHER instead\" << endl;\n\t\treturn 1;\n\n\t}\n\n\tofstream &fout_rec = file_manager.open_ofile_ext(\"rec\");\n\tfout_rec << \"             pestpp-sen: a tool for global sensitivity analysis\" << endl << endl;\n\tfout_rec << \"                         by The PEST++ Development Team\" << endl << endl;\n\tfout_rec << endl << endl << \"version: \" << version << endl;\n\tfout_rec << \"binary compiled on \" << __DATE__ << \" at \" << __TIME__ << endl << endl;\n\tfout_rec << \"using control file: \\\"\" << complete_path << \"\\\"\" << endl;\n\tfout_rec << \"in directory: \\\"\" << OperSys::getcwd() << \"\\\"\" << endl << endl;\n\n\t\n\tcout << endl;\n\tcout << \"using control file: \\\"\" << complete_path << \"\\\"\" << endl;\n\tcout << \"in directory: \\\"\" << OperSys::getcwd() << \"\\\"\" << endl << endl;\n\n\t// create pest run and process control file to initialize it\n\tPest pest_scenario;\n\tpest_scenario.set_defaults();\n\ttry {\n\t\tpest_scenario.process_ctl_file(file_manager.open_ifile_ext(\"pst\"), file_manager.build_filename(\"pst\"),fout_rec);\n\t\tfile_manager.close_file(\"pst\");\n\t\tpest_scenario.check_inputs(fout_rec);\n\t}\n\tcatch(PestError e)\n\t{\n\t\tcerr << \"Error prococessing control file: \" << filename << endl << endl;\n\t\tcerr << e.what() << endl << endl;\n\t\tfout_rec << \"Error prococessing control file: \" << filename << endl << endl;\n\t\tfout_rec << e.what() << endl;\n\t\tfout_rec.close();\n\t\t//throw(e);\n\t\treturn 1;\n\t}\n\n\n\tRunManagerAbstract *run_manager_ptr;\n\tif (run_manager_type == RunManagerType::PANTHER)\n\t{\n\t\tstring port = argv[3];\n\t\tstrip_ip(port);\n\t\tstrip_ip(port, \"front\", \":\");\n\t\tconst ModelExecInfo &exi = pest_scenario.get_model_exec_info();\n\t\trun_manager_ptr = new RunManagerPanther (\n\t\t\tfile_manager.build_filename(\"rns\"), port,\n\t\t\tfile_manager.open_ofile_ext(\"rmr\"),\n\t\t\tpest_scenario.get_pestpp_options().get_max_run_fail(),\n\t\t\tpest_scenario.get_pestpp_options().get_overdue_reched_fac(),\n\t\t\tpest_scenario.get_pestpp_options().get_overdue_giveup_fac(),\n\t\t\tpest_scenario.get_pestpp_options().get_overdue_giveup_minutes());\n\t}\n\telse\n\t{\n\t\tconst ModelExecInfo &exi = pest_scenario.get_model_exec_info();\n\t\trun_manager_ptr = new RunManagerSerial(exi.comline_vec,\n\t\texi.tplfile_vec, exi.inpfile_vec, exi.insfile_vec, exi.outfile_vec,\n\t\tfile_manager.build_filename(\"rns\"), pathname);\n\t}\n\n\tcout << endl;\n\tfout_rec << endl;\n\tcout << \"using control file: \\\"\" <<  complete_path << \"\\\"\" << endl;\n\tfout_rec << \"using control file: \\\"\" <<  complete_path << \"\\\"\" << endl;\n\n\n\tenum class GSA_RESTART { NONE, RESTART };\n\tGSA_RESTART gsa_restart = GSA_RESTART::NONE;\n\t//process restart and  reuse jacibian directives\n\tvector<string>::const_iterator it_find_r = find(cmd_arg_vec.begin(), cmd_arg_vec.end(), \"/r\");\n\tif (it_find_r != cmd_arg_vec.end())\n\t{\n\t\tgsa_restart = GSA_RESTART::RESTART;\n\t}\n\telse\n\t{\n\t\tgsa_restart = GSA_RESTART::NONE;\n\t}\n\t//OutputFileWriter(FileManager &_file_manager, Pest &_pest_scenario, bool restart_flag = false, bool _save_rei = true, int _eigenwrite = 0);\n\tOutputFileWriter output_writer(file_manager, pest_scenario, false, false);\n\tofstream &frec = file_manager.rec_ofstream();\n\toutput_writer.scenario_report(frec);\n\toutput_writer.scenario_io_report(frec);\n\toutput_writer.scenario_par_report(frec);\n\toutput_writer.scenario_obs_report(frec);\n\n\tpest_scenario.check_inputs(frec);\n\tpest_scenario.check_io();\n\n\t//map<string, string> gsa_opt_map;\n\t//process .gsa file\n\tstring gsa_filename = file_manager.get_base_filename() + \".gsa\";\n\t/*if (!check_exist_in(gsa_filename))\n\t{\n\t\tcout << \"WARNING: \" << gsa_filename << \" not found, using standard settings and Method of Morris:\" << endl;\n\t\tcout << \"     MORRIS_P: 4\" << endl;\n\t\tcout << \"     MORRIS_R: 4\" << endl;\n\t\tcout << \"     MORRIS_DELTA: 0.666\" << endl;\n\t\tgsa_opt_map[\"METHOD\"] = \"MORRIS\";\n\t\tgsa_opt_map[\"MORRIS_DELTA\"] = \".666666\";\n\t\tgsa_opt_map[\"MORRIS_P\"] = \"4\";\n\t\tgsa_opt_map[\"MORRIS_R\"] = \"4\";\n\t\tgsa_opt_map[\"RAND_SEED\"] = \"2\";\n\t}\n\telse\n\t{\n\t\ttry\n\t\t{\n\t\t\tgsa_opt_map = GsaAbstractBase::process_gsa_file(file_manager.open_ifile_ext(\"gsa\"), file_manager);\n\t\t\tfile_manager.close_file(\"gsa\");\n\t\t}\n\t\tcatch (PestError e)\n\t\t{\n\t\t\tcerr << \"Error prococessing .gsa file: \" << file_manager.build_filename(\"gsa\") << endl << endl;\n\t\t\tcerr << e.what() << endl << endl;\n\t\t\tthrow(e);\n\t\t}\n\t}*/\n\tif (check_exist_in(gsa_filename))\n\t{\n\t\tcout << \"WARNING: use of .gsa files is deprecated - .gsa file '\" << gsa_filename << \"' is being ignored, please use '++' args\";\n\t\treturn 1;\n\t}\n\n\tPestppOptions *pp_ptr = pest_scenario.get_pestpp_options_ptr();\n\tmap<string, string> gsa_opt_map = pp_ptr->get_arg_map();\n\t/*gsa_opt_map[\"METHOD\"] = pp_ptr->get_gsa_method();\n\tgsa_opt_map[\"MORRIS_DELTA\"] = pp_ptr->get_gsa_morris_delta();\n\tgsa_opt_map[\"MORRIS_P\"] = pp_ptr->get_gsa_morris_p();\n\tgsa_opt_map[\"MORRIS_R\"] = pp_ptr->get_gsa_morris_r;\n\tgsa_opt_map[\"MORRIS_OBS_SEN\"] = pp_ptr->get_gsa_morris_obs_sen();\n*/\n\t//Build Transformation with ctl_2_numberic\n\tParamTransformSeq base_partran_seq(pest_scenario.get_base_par_tran_seq());\n\tParameters ctl_par = pest_scenario.get_ctl_parameters();\n\n\n\t//Build Transformation with ctl_2_numberic\n\tObjectiveFunc obj_func(&(pest_scenario.get_ctl_observations()), &(pest_scenario.get_ctl_observation_info()), &(pest_scenario.get_prior_info()));\n\tModelRun model_run(&obj_func, pest_scenario.get_ctl_observations());\n\tconst set<string> &log_trans_pars = base_partran_seq.get_log10_ptr()->get_items();\n\tauto method = gsa_opt_map.find(\"GSA_METHOD\");\n\n\tGsaAbstractBase* gsa_method = nullptr;\n\tif (method == gsa_opt_map.end() || method->second == \"MORRIS\")\n\t{\n\t\tint morris_r = 4;\n\t\tint morris_p = 4;\n\n\t\tdouble morris_delta = .666;\n\t\tbool default_delta = true;\n\t\tbool calc_pooled_obs = false;\n\t\tbool calc_morris_obs_sen = true;\n\t\tauto morris_r_it = gsa_opt_map.find(\"GSA_MORRIS_R\");\n\t\tif (morris_r_it != gsa_opt_map.end())\n\t\t{\n\t\t\tconvert_ip(morris_r_it->second, morris_r);\n\t\t}\n\t\tauto morris_p_it = gsa_opt_map.find(\"GSA_MORRIS_P\");\n\t\tif (morris_p_it != gsa_opt_map.end())\n\t\t{\n\t\t\tconvert_ip(morris_p_it->second, morris_p);\n\t\t}\n\t\tauto morris_d_it = gsa_opt_map.find(\"GSA_MORRIS_DELTA\");\n\t\tif (morris_d_it != gsa_opt_map.end())\n\t\t{\n\t\t\t\n\t\t\tconvert_ip(morris_d_it->second, morris_delta);\n\t\t\tdefault_delta = false;\n\t\t}\n\t\tauto morris_pool_it = gsa_opt_map.find(\"GSA_MORRIS_POOLED_OBS\");\n\t\tif (morris_pool_it != gsa_opt_map.end())\n\t\t{\n\t\t\tstring pooled_obs_flag = morris_pool_it->second;\n\t\t\tupper_ip(pooled_obs_flag);\n\t\t\tif (pooled_obs_flag == \"TRUE\") calc_pooled_obs = true;\n\t\t}\n\n\t\tauto morris_obs_sen_it = gsa_opt_map.find(\"GSA_MORRIS_OBS_SEN\");\n\t\tif (morris_obs_sen_it != gsa_opt_map.end())\n\t\t{\n\t\t\tstring obs_sen_flag = morris_obs_sen_it->second;\n\t\t\tupper_ip(obs_sen_flag);\n\t\t\tif (obs_sen_flag == \"FALSE\") calc_morris_obs_sen = false;\n\t\t}\n\n\t\tif (default_delta) morris_delta = morris_p / (2.0 * (morris_p - 1));\n\n\t\tMorrisMethod *m_ptr = new MorrisMethod(pest_scenario, file_manager, &obj_func,\n\t\t\tbase_partran_seq, morris_p, morris_r, morris_delta, calc_pooled_obs,\n\t\t\tcalc_morris_obs_sen, GsaAbstractBase::PARAM_DIST::uniform, 1.0);\n\t\tgsa_method = m_ptr;\n\t\tm_ptr->process_pooled_var_file();\n\t\t\n\t\tfrec << endl << endl << endl << \"Method of Morris settings:\" << endl;\n\n\t\tfrec << scientific << left << setw(30) << \" morris_r \" << morris_r << endl;\n\t\tfrec << scientific << left << setw(30) << \" morris_p \" << morris_p << endl;\n\t\tfrec << scientific << left << setw(30) << \" morris_delta \" << morris_delta << endl << endl;\n\t\t\n\n\t}\n\t\n\telse if (method != gsa_opt_map.end() && method->second == \"SOBOL\")\n\t{\n\t\tGsaAbstractBase::PARAM_DIST par_dist = GsaAbstractBase::PARAM_DIST::uniform;\n\t\tstring par_dist_str = \"UNIFORM\";\n\t\tint n_sample = 100;\n\t\tauto sob_n_sam_it = gsa_opt_map.find(\"GSA_SOBOL_SAMPLES\");\n\t\tif (sob_n_sam_it != gsa_opt_map.end())\n\t\t{\n\t\t\tconvert_ip(sob_n_sam_it->second, n_sample);\n\t\t}\n\t\tauto sob_p_dist_it = gsa_opt_map.find(\"GSA_SOBOL_PAR_DIST\");\n\t\tif (sob_p_dist_it != gsa_opt_map.end())\n\t\t{\n\t\t\tpar_dist_str = sob_p_dist_it->second;\n\t\t\tupper_ip(par_dist_str);\n\t\t\tif (par_dist_str == \"NORM\") par_dist = GsaAbstractBase::PARAM_DIST::normal;\n\t\t\telse if (par_dist_str == \"UNIF\") par_dist = GsaAbstractBase::PARAM_DIST::uniform;\n\t\t\telse\n\t\t\t{\n\t\t\t\tostringstream str;\n\t\t\t\tstr << \"SOBOL_PAR_DIST(\" << par_dist_str << \"):  \\\"\" << par_dist_str << \"\\\" is an invalid distribuation type\";\n\t\t\t\tthrow PestError(str.str());\n\t\t\t}\n\t\t}\n\n\t\tgsa_method = new Sobol(pest_scenario, file_manager, &obj_func,\n\t\t\tbase_partran_seq, n_sample, par_dist, 1.0);\n\n\t\tfrec << endl << endl << endl << \"Method of Sobol settings:\" << endl;\n\n\t\tfrec << scientific << left << setw(30) << \" n_sample \" << n_sample << endl;\n\t\tfrec << scientific << left << setw(30) << \" sobol par dist \" <<par_dist_str << endl;\n\t\t\n\t}\n\telse\n\t{\n\t\tthrow PestError(\"A valid method for computing the sensitivity must be specified in the control file\");\n\t}\n\n\tauto morris_r_it = gsa_opt_map.find(\"RAND_SEED\");\n\tif (morris_r_it != gsa_opt_map.end())\n\t{\n\t\tunsigned int seed = convert_cp<unsigned int>(morris_r_it->second);\n\t\tgsa_method->set_seed(seed);\n\t}\n\tfrec << scientific << left << setw(30) << \" gsa random seed \" << gsa_method->get_seed() << endl;\n\t// make model runs\n\tif (gsa_restart == GSA_RESTART::NONE)\n\t{\n\t\t//Allocates Space for Run Manager.  This initializes the model parameter names and observations names.\n\t\t//Neither of these will change over the course of the simulation\n\t\tcout << endl;\n\t\tcout << \"Building model run parameter sets...\" << endl;\n\t\trun_manager_ptr->initialize(base_partran_seq.ctl2model_cp(ctl_par), pest_scenario.get_ctl_observations());\n\n\t\tParameters model_pars = base_partran_seq.ctl2model_cp(ctl_par);\n\t\trun_manager_ptr->reinitialize();\n\t\tgsa_method->assemble_runs(*run_manager_ptr);\n\t}\n\telse\n\t{\n\t\trun_manager_ptr->initialize_restart(file_manager.build_filename(\"rns\"));\n\t}\n\tcout << endl;\n\tcout << \"Performing model runs...\" << endl;\n\trun_manager_ptr->run();\n\n\tcout << \"Calculating sensitivities...\" << endl;\n\tgsa_method->calc_sen(*run_manager_ptr, model_run);\n\tfile_manager.close_file(\"srw\");\n\tfile_manager.close_file(\"msn\");\n\tfile_manager.close_file(\"orw\");\n\tdelete run_manager_ptr;\n\tcout << endl << endl << \"Simulation Complete...\" << endl;\n\t//cout << endl << \"Simulation Complete - Press RETURN to close window\" << endl;\n\t//char buf[256];\n\t//OperSys::gets_s(buf, sizeof(buf));\n#ifndef _DEBUG\n\t}\n\tcatch (exception &e)\n\t{\n\t\tcout << \"Error condition prevents further execution: \" << endl << e.what() << endl;\n\t\t//cout << \"press enter to continue\" << endl;\n\t\t//char buf[256];\n\t\t//OperSys::gets_s(buf, sizeof(buf));\n\t}\n#endif\n}\n", "meta": {"hexsha": "3e835764bb1759434b2c63d208f23ea3a786000c", "size": 15714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src_pestpp/programs/gsa/main.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/main.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/main.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": 33.2923728814, "max_line_length": 145, "alphanum_fraction": 0.6820033092, "num_tokens": 4439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.03514484867461498, "lm_q1q2_score": 0.014448428780506485}}
{"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/// Definitions of the basic data-handling classes in ALMA.\n\n#include <map>\n#include <array>\n#include <vector>\n#include <utility>\n#include <numeric>\n#include <limits>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/mpi.hpp>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <cmakevars.hpp>\n#include <constants.hpp>\n#include <utilities.hpp>\n#include <exceptions.hpp>\n#include <periodic_table.hpp>\n\nnamespace alma {\n// Forward declarations placed here for convenience.\nclass Symmetry_operations;\nclass Gamma_grid;\nclass Threeph_process;\n\n/// Convenient shorthand for an array of three ints.\nusing Triple_int = std::array<int, 3>;\n\n/// Specialized version of map whose keys are of class Triple_int.\ntemplate <typename T>\nusing Triple_int_map =\n    std::map<Triple_int, T, Container_comparator<Triple_int>>;\n\n/// Hold information about a crystal structure.\nclass Crystal_structure {\npublic:\n    /// Lattice vectors in nm.\n    const Eigen::Matrix3d lattvec;\n    /// Atomic positions in lattice coordinates.\n    const Eigen::Matrix<double, 3, Eigen::Dynamic> positions;\n    /// Elements present in the structure.\n    const std::vector<std::string> elements;\n    /// Volume of the unit cell.\n    const double V;\n    /// Lattice vectors of the reciprocal lattice.\n    const Eigen::MatrixXd rlattvec;\n    /// Number of atoms of each element.\n    ///\n    /// The first numbers[0] atoms belong to elements[0], the next\n    /// numbers[1] atoms belong to elements[1], etc.\n    const std::vector<int> numbers;\n    /// Basic constructor.\n    Crystal_structure(Eigen::Matrix3d _lattvec,\n                      Eigen::Matrix<double, 3, Eigen::Dynamic> _positions,\n                      std::vector<std::string> _elements,\n                      std::vector<int> _numbers)\n        : lattvec(std::move(_lattvec)), positions(std::move(_positions)),\n          elements(std::move(_elements)),\n          V(std::fabs(this->lattvec.determinant())),\n          rlattvec(2. * constants::pi * this->lattvec.inverse().transpose()),\n          numbers(std::move(_numbers)) {\n        std::partial_sum(this->numbers.begin(),\n                         this->numbers.end(),\n                         std::back_inserter(this->partsums));\n\n        for (int i = 0; i < this->get_natoms(); ++i) {\n            this->masses.emplace_back(alma::get_mass(this->get_element(i)));\n            this->gfactors.emplace_back(\n                alma::get_gfactor(this->get_element(i)));\n        }\n    }\n\n    /// Specialized constructor allowing for custom masses.\n    Crystal_structure(Eigen::Matrix3d _lattvec,\n                      Eigen::Matrix<double, 3, Eigen::Dynamic> _positions,\n                      std::vector<std::string> _elements,\n                      std::vector<int> _numbers,\n                      std::vector<double> _masses)\n        : Crystal_structure(_lattvec, _positions, _elements, _numbers) {\n        if (_masses.size() != static_cast<std::size_t>(this->get_natoms())) {\n            throw value_error(\"one mass per atom must be provided\");\n        }\n        for (int i = 0; i < this->get_natoms(); ++i) {\n            if (_masses[i] <= 0.) {\n                throw value_error(\"all masses must be positive\");\n            }\n            this->masses[i] = _masses[i];\n        }\n    }\n\n    /// Return the number of elements in the structure.\n    inline std::vector<std::string>::size_type get_nelements() const {\n        return this->elements.size();\n    }\n\n\n    /// Return the number of atoms in the motif.\n    inline int get_natoms() const {\n        return this->positions.cols();\n    }\n    /// Return the chemical symbol for an atom.\n    ///\n    /// @param[in] i - atom number\n    /// @return the chemical symbol\n    inline std::string get_element(int i) const {\n        if (i >= this->get_natoms())\n            throw value_error(\"invalid atom number\");\n        return this->elements[std::distance(\n            this->partsums.begin(),\n            std::lower_bound(\n                this->partsums.begin(), this->partsums.end(), i + 1))];\n    }\n\n\n    /// Return the mass of the i-th atom.\n    ///\n    /// @param[in] i - atom number\n    /// @return the mass in a.m.u\n    inline double get_mass(int i) const {\n        if (i >= this->get_natoms())\n            throw value_error(\"invalid atom number\");\n        return this->masses[i];\n    }\n\n\n    /// Return the g factor of the i-th atom.\n    ///\n    /// @param[in] i - atom number\n    /// @return the Pearson deviation coefficient of the i-th atom's\n    /// mass\n    inline double get_gfactor(int i) const {\n        if (i >= this->get_natoms())\n            throw value_error(\"invalid atom number\");\n        return this->gfactors[i];\n    }\n\n\n    /// Check if any atom belongs to a virtual element.\n    ///\n    /// @return true is the structure describes an alloy, or\n    /// false otherwise.\n    inline bool is_alloy() const {\n        for (auto& e : this->elements)\n            if (e.find(\";\") != std::string::npos)\n                return true;\n\n        return false;\n    }\n\n    /// Find all images of a q point in the first Brillouin zone.\n    ///\n    /// A point on the surface of the first BZ will have more than\n    /// one possible image.\n    /// @param[in] - original q point in Cartesian coordinates\n    /// @return the Cartesian coordinates of all images of the point\n    /// in the first Brillouin zone, as columns of a matrix.\n    inline Eigen::MatrixXd map_to_firstbz(\n        const Eigen::Ref<const Eigen::Vector3d>& q) const {\n        constexpr int sbound = 3;\n        // Step 1: find a single image using a standard approach\n        Eigen::Vector3d qbz{this->rlattvec.colPivHouseholderQr().solve(q)};\n        Eigen::Vector3d qbz_min;\n        qbz -= qbz.array().round().matrix().eval();\n        qbz = (this->rlattvec * qbz).eval();\n        double n2 = qbz.squaredNorm();\n        qbz_min = qbz;\n        for (int i = -sbound; i <= sbound; ++i) {\n            for (int j = -sbound; j <= sbound; ++j) {\n                for (int k = -sbound; k <= sbound; ++k) {\n                    Eigen::Vector3d qbzp{qbz + i * this->rlattvec.col(0) +\n                                         j * this->rlattvec.col(1) +\n                                         k * this->rlattvec.col(2)};\n                    double n2p = qbzp.squaredNorm();\n                    if (n2p < n2) {\n                        n2 = n2p;\n                        qbz_min = qbzp;\n                    }\n                }\n            }\n        }\n        qbz = qbz_min;\n        // Step 2: perform a search to find equivalent images.\n        std::size_t found = 0;\n        int ncols = boost::math::pow<3>(2 * sbound + 1);\n        Eigen::MatrixXd nruter(3, ncols);\n        for (int i = -sbound; i <= sbound; ++i) {\n            for (int j = -sbound; j <= sbound; ++j) {\n                for (int k = -sbound; k <= sbound; ++k) {\n                    Eigen::Vector3d qbzp{qbz + i * this->rlattvec.col(0) +\n                                         j * this->rlattvec.col(1) +\n                                         k * this->rlattvec.col(2)};\n                    double n2p = qbzp.squaredNorm();\n                    if (alma::almost_equal(n2, n2p)) {\n                        nruter.col(found) = qbzp;\n                        ++found;\n                    }\n                }\n            }\n        }\n        return nruter.leftCols(found);\n    }\n\n\nprivate:\n    /// partsums[i] contains sum(numbers[0:i+1]).\n    std::vector<int> partsums;\n    /// Masses of each atom. Cached here to avoid costly\n    /// calculations in the case of virtual elements.\n    std::vector<double> masses;\n    /// Pearson deviation coefficients of the atomic masses. Cached\n    /// here to avoid costly calculations in the case of virtual\n    /// elements.\n    std::vector<double> gfactors;\n};\n\n/// Hold information about the harmonic interactions between atoms.\n/// Normally T will be Eigen::MatrixXd since force constants are\n/// real, but it might be useful to change it to Eigen::MatrixXcd\n/// in order to operate in mixed real/reciprocal space.\ntemplate <class T> class General_harmonic_ifcs {\npublic:\n    /// Coordinates of each unit cell for which constants\n    /// are available.\n    const std::vector<Triple_int> pos;\n    /// Force constants between unit cell 0 and each unit cell.\n    const std::vector<T> ifcs;\n    /// Dimension of the supercell originally used for the IFC\n    /// calculations along the first axis.\n    const int na;\n    /// Dimension of the supercell originally used for the IFC\n    /// calculations along the second axis.\n    const int nb;\n    /// Dimension of the supercell originally used for the IFC\n    /// calculations along the third axis.\n    const int nc;\n    /// Basic constructor.\n    General_harmonic_ifcs(std::vector<Triple_int> _pos,\n                          std::vector<T> _ifcs,\n                          int _na,\n                          int _nb,\n                          int _nc)\n        : pos(std::move(_pos)), ifcs(std::move(_ifcs)), na(_na), nb(_nb),\n          nc(_nc) {\n    }\n\n\n    // Return the number of unit cells.\n    inline std::vector<std::string>::size_type get_ncells() const {\n        return this->pos.size();\n    }\n};\n\n/// Specialization of General_harmonic_ifcs for the most common\n/// use case.\nusing Harmonic_ifcs = General_harmonic_ifcs<Eigen::MatrixXd>;\n\n/// Hold information about the polarization properties of the\n/// structure.\nclass Dielectric_parameters {\npublic:\n    /// Born charges.\n    const std::vector<Eigen::MatrixXd> born;\n    /// Dielectric tensor.\n    const Eigen::Matrix3d epsilon;\n    /// Basic constructor.\n    Dielectric_parameters(std::vector<Eigen::MatrixXd> _born,\n                          Eigen::Matrix3d _epsilon)\n        : born(std::move(_born)), epsilon(std::move(_epsilon)) {\n    }\n\n\n    /// Default constructor. Create an empty object.\n    Dielectric_parameters() {\n    }\n};\n\n/// Phonopy-style atom index represented both as a single integer\n/// and as four indices.\n///\n/// Objects from this class are not intended to be built\n/// directly. Use a Supercell_index_builder instead.\nclass Supercell_index {\npublic:\n    /// Atom index within the supercell.\n    const int index;\n    /// Unit cell index along the first axis.\n    const int ia;\n    /// Unit cell index along the second axis.\n    const int ib;\n    /// Unit cel index along the third axis.\n    const int ic;\n    /// Atom index within the unit cell.\n    const int iatom;\n    // Basic constructor.\n    Supercell_index(const int _index,\n                    const int _ia,\n                    const int _ib,\n                    const int _ic,\n                    const int _iatom)\n        : index(_index), ia(_ia), ib(_ib), ic(_ic), iatom(_iatom) {\n    }\n\n\n    /// Return an array of three integers {ia, ib, ic}.\n    inline const Triple_int get_pos() const {\n        return Triple_int({{this->ia, this->ib, this->ic}});\n    }\n};\n\n/// Builder for Supercell_index objects sharing the same na, nb, nc.\nclass Supercell_index_builder {\npublic:\n    /// Supercell dimension along the first axis.\n    const int na;\n    /// Supercell dimension along the second axis.\n    const int nb;\n    /// Supercell dimension along the third axis.\n    const int nc;\n    /// Number of atoms in the unit cell.\n    const int natoms;\n    /// Basic constructor.\n    Supercell_index_builder(const int _na,\n                            const int _nb,\n                            const int _nc,\n                            const int _natoms);\n    /// Create a Supercell_index from a single integer.\n    Supercell_index create_index(const int index) const;\n\n    /// Create a Supercell_index from four integers.\n    Supercell_index create_index(const int ia,\n                                 const int ib,\n                                 const int ic,\n                                 const int iatom) const;\n\n    /// Perform a bounds check and create a Supercell_index from a\n    /// single integer.\n    Supercell_index create_index_safely(const int index) const;\n\n    /// Perform a bounds check and create a Supercell_index from\n    /// four integers.\n    Supercell_index create_index_safely(const int ia,\n                                        const int ib,\n                                        const int ic,\n                                        const int iatom) const;\n};\n\n/// Class representing the anharmonic (third-order)\n/// interaction between two atoms atoms.\n///\n/// Note that, since third-order IFCs tend to be expressed\n/// in sparse formats, it is more natural to store each tensor\n/// individually. There is no third-order equivalent to the\n/// Harmonic_ifcs class. Vectors of Thirdorder_ifcs can be used\n/// instead.\n/// The first atom, i, is always assumed to be part of the first\n/// unit cell, that is, R_i = {0., 0., 0.}.\nclass Thirdorder_ifcs {\npublic:\n    /// Cartesian coordinates of the second unit cell.\n    const Eigen::VectorXd rj;\n    /// Cartesian coordinates of the third unit cell.\n    const Eigen::VectorXd rk;\n    /// Index of the first atom.\n    const std::size_t i;\n    /// Index of the second atom.\n    const std::size_t j;\n    /// Index of the third atom.\n    const std::size_t k;\n    /// Access a particular ifc using three indexes.\n    ///\n    /// Note that all indices must be positive and lower than 3,\n    /// but that this condition is not checked.\n    /// @param[in] alpha - first axis index\n    /// @param[in] beta - second axis index\n    /// @param[in] gamma - third axis index\n    /// @return a mutable reference to the element\n    double& ifc(std::size_t alpha, std::size_t beta, std::size_t gamma) {\n        return this->ifcs[gamma + 3 * (beta + 3 * alpha)];\n    }\n\n\n    /// Access a particular ifc using three indexes.\n    ///\n    /// Note that all indices must be positive and lower than 3,\n    /// but that this condition is not checked.\n    /// @param[in] alpha - first axis index\n    /// @param[in] beta - second axis index\n    /// @param[in] gamma - third axis index\n    /// @return a const reference to the element\n    const double& ifc(std::size_t alpha,\n                      std::size_t beta,\n                      std::size_t gamma) const {\n        return this->ifcs[gamma + 3 * (beta + 3 * alpha)];\n    }\n\n\n    /// Basic constructor. It does not initialize the ifcs\n    /// member variable.\n    Thirdorder_ifcs(const Eigen::VectorXd& _rj,\n                    const Eigen::VectorXd& _rk,\n                    std::size_t _i,\n                    std::size_t _j,\n                    std::size_t _k)\n        : rj(std::move(_rj)), rk(std::move(_rk)), i(_i), j(_j), k(_k) {\n    }\n\n\nprivate:\n    /// All third-order force constants between the three atoms.\n    std::array<double, 27> ifcs;\n};\n} // namespace alma\n", "meta": {"hexsha": "c7d3da4463979b29584113f3e8fb7b8836cd03db", "size": 15291, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/structures.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/structures.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/structures.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": 35.6433566434, "max_line_length": 77, "alphanum_fraction": 0.59172062, "num_tokens": 3619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.029312230963347865, "lm_q1q2_score": 0.014427132311667564}}
{"text": "//\r\n//=======================================================================\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//\r\n#ifndef BOOST_GRAPH_MST_KRUSKAL_HPP\r\n#define BOOST_GRAPH_MST_KRUSKAL_HPP\r\n\r\n/*\r\n *Minimum Spanning Tree\r\n *         Kruskal Algorithm\r\n *\r\n *Requirement:\r\n *      undirected graph\r\n */\r\n\r\n#include <vector>\r\n#include <queue>\r\n#include <functional>\r\n\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/pending/disjoint_sets.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/concept/assert.hpp>\r\n\r\nnamespace boost\r\n{\r\n\r\n// Kruskal's algorithm for Minimum Spanning Tree\r\n//\r\n// This is a greedy algorithm to calculate the Minimum Spanning Tree\r\n// for an undirected graph with weighted edges. The output will be a\r\n// set of edges.\r\n//\r\n\r\nnamespace detail\r\n{\r\n\r\n    template < class Graph, class OutputIterator, class Rank, class Parent,\r\n        class Weight >\r\n    void kruskal_mst_impl(const Graph& G, OutputIterator spanning_tree_edges,\r\n        Rank rank, Parent parent, Weight weight)\r\n    {\r\n        if (num_vertices(G) == 0)\r\n            return; // Nothing to do in this case\r\n        typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n        typedef typename graph_traits< Graph >::edge_descriptor Edge;\r\n        BOOST_CONCEPT_ASSERT((VertexListGraphConcept< Graph >));\r\n        BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< Graph >));\r\n        BOOST_CONCEPT_ASSERT((OutputIteratorConcept< OutputIterator, Edge >));\r\n        BOOST_CONCEPT_ASSERT((ReadWritePropertyMapConcept< Rank, Vertex >));\r\n        BOOST_CONCEPT_ASSERT((ReadWritePropertyMapConcept< Parent, Vertex >));\r\n        BOOST_CONCEPT_ASSERT((ReadablePropertyMapConcept< Weight, Edge >));\r\n        typedef typename property_traits< Weight >::value_type W_value;\r\n        typedef typename property_traits< Rank >::value_type R_value;\r\n        typedef typename property_traits< Parent >::value_type P_value;\r\n        BOOST_CONCEPT_ASSERT((ComparableConcept< W_value >));\r\n        BOOST_CONCEPT_ASSERT((ConvertibleConcept< P_value, Vertex >));\r\n        BOOST_CONCEPT_ASSERT((IntegerConcept< R_value >));\r\n\r\n        disjoint_sets< Rank, Parent > dset(rank, parent);\r\n\r\n        typename graph_traits< Graph >::vertex_iterator ui, uiend;\r\n        for (boost::tie(ui, uiend) = vertices(G); ui != uiend; ++ui)\r\n            dset.make_set(*ui);\r\n\r\n        typedef indirect_cmp< Weight, std::greater< W_value > > weight_greater;\r\n        weight_greater wl(weight);\r\n        std::priority_queue< Edge, std::vector< Edge >, weight_greater > Q(wl);\r\n        /*push all edge into Q*/\r\n        typename graph_traits< Graph >::edge_iterator ei, eiend;\r\n        for (boost::tie(ei, eiend) = edges(G); ei != eiend; ++ei)\r\n            Q.push(*ei);\r\n\r\n        while (!Q.empty())\r\n        {\r\n            Edge e = Q.top();\r\n            Q.pop();\r\n            Vertex u = dset.find_set(source(e, G));\r\n            Vertex v = dset.find_set(target(e, G));\r\n            if (u != v)\r\n            {\r\n                *spanning_tree_edges++ = e;\r\n                dset.link(u, v);\r\n            }\r\n        }\r\n    }\r\n\r\n} // namespace detail\r\n\r\n// Named Parameters Variants\r\n\r\ntemplate < class Graph, class OutputIterator >\r\ninline void kruskal_minimum_spanning_tree(\r\n    const Graph& g, OutputIterator spanning_tree_edges)\r\n{\r\n    typedef typename graph_traits< Graph >::vertices_size_type size_type;\r\n    typedef typename graph_traits< Graph >::vertex_descriptor vertex_t;\r\n    if (num_vertices(g) == 0)\r\n        return; // Nothing to do in this case\r\n    typename graph_traits< Graph >::vertices_size_type n = num_vertices(g);\r\n    std::vector< size_type > rank_map(n);\r\n    std::vector< vertex_t > pred_map(n);\r\n\r\n    detail::kruskal_mst_impl(g, spanning_tree_edges,\r\n        make_iterator_property_map(\r\n            rank_map.begin(), get(vertex_index, g), rank_map[0]),\r\n        make_iterator_property_map(\r\n            pred_map.begin(), get(vertex_index, g), pred_map[0]),\r\n        get(edge_weight, g));\r\n}\r\n\r\ntemplate < class Graph, class OutputIterator, class P, class T, class R >\r\ninline void kruskal_minimum_spanning_tree(const Graph& g,\r\n    OutputIterator spanning_tree_edges,\r\n    const bgl_named_params< P, T, R >& params)\r\n{\r\n    typedef typename graph_traits< Graph >::vertices_size_type size_type;\r\n    typedef typename graph_traits< Graph >::vertex_descriptor vertex_t;\r\n    if (num_vertices(g) == 0)\r\n        return; // Nothing to do in this case\r\n    typename graph_traits< Graph >::vertices_size_type n;\r\n    n = is_default_param(get_param(params, vertex_rank)) ? num_vertices(g) : 1;\r\n    std::vector< size_type > rank_map(n);\r\n    n = is_default_param(get_param(params, vertex_predecessor))\r\n        ? num_vertices(g)\r\n        : 1;\r\n    std::vector< vertex_t > pred_map(n);\r\n\r\n    detail::kruskal_mst_impl(g, spanning_tree_edges,\r\n        choose_param(get_param(params, vertex_rank),\r\n            make_iterator_property_map(rank_map.begin(),\r\n                choose_pmap(get_param(params, vertex_index), g, vertex_index),\r\n                rank_map[0])),\r\n        choose_param(get_param(params, vertex_predecessor),\r\n            make_iterator_property_map(pred_map.begin(),\r\n                choose_const_pmap(\r\n                    get_param(params, vertex_index), g, vertex_index),\r\n                pred_map[0])),\r\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight));\r\n}\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_MST_KRUSKAL_HPP\r\n", "meta": {"hexsha": "edd10e56b62da439e9f117e00ac71bec97e67143", "size": 5895, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/kruskal_min_spanning_tree.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/kruskal_min_spanning_tree.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/kruskal_min_spanning_tree.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 38.5294117647, "max_line_length": 80, "alphanum_fraction": 0.6386768448, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.044018649706182404, "lm_q1q2_score": 0.014423516731656328}}
{"text": "/// OpenGM. Copyright (c) 2010 by Bjoern Andres and Joerg Hendrik Kappes.\r\n///\r\n/// This software was developed by Bjoern Andres and Joerg Hendrik Kappes.\r\n/// Enquiries shall be directed to:\r\n/// bjoern.andres@iwr.uni-heidelberg.de, kappes@math.uni-heidelberg.de\r\n///\r\n/// Author(s) of this file: Bjoern Andres\r\n///\r\n/// All advertising materials mentioning features or use of this software must\r\n/// display the following acknowledgement: ``This product includes the OpenGM\r\n/// library developed by Bjoern Andres and Joerg Hendrik Kappes. Please direct \r\n/// enquiries concerning OpenGM to bjoern.andres@iwr.uni-heidelberg.de,\r\n/// kappes@math.uni-heidelberg.de''.\r\n///\r\n/// Redistribution and use in source and binary forms, with or without\r\n/// modification, are permitted provided that the following conditions are met:\r\n///\r\n/// - Redistributions of source code must retain the above copyright notice,\r\n///   this list of conditions and the following disclaimer.\r\n/// - Redistributions in binary form must reproduce the above copyright notice, \r\n///   this list of conditions and the following disclaimer in the documentation\r\n///   and/or other materials provided with the distribution.\r\n/// - All advertising materials mentioning features or use of this software must \r\n///   display the following acknowledgement: ``This product includes the OpenGM\r\n///   library developed by Bjoern Andres and Joerg Hendrik Kappes. Please direct \r\n///   enquiries concerning OpenGM to bjoern.andres@iwr.uni-heidelberg.de,\r\n///   kappes@math.uni-heidelberg.de''.\r\n/// - The names of the authors must not be used to endorse or promote products \r\n///   derived from this software without specific prior written permission.\r\n///\r\n/// THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED \r\n/// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \r\n/// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO \r\n/// EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n/// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\n/// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \r\n/// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \r\n/// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \r\n/// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \r\n/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n/// \r\n#pragma once\r\n#ifndef OPENGM_GRAPHCUT_HXX\r\n#define OPENGM_GRAPHCUT_HXX\r\n\r\n#include <queue>\r\n\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/edmonds_karp_max_flow.hpp>\r\n#include <boost/graph/push_relabel_max_flow.hpp>\r\n#include <boost/graph/kolmogorov_max_flow.hpp>\r\n\r\n#include \"opengm/explicitfactor.hxx\"\r\n#include \"opengm/graphicalmodel.hxx\"\r\n#include \"opengm/adder.hxx\"\r\n#include \"opengm/minimizer.hxx\"\r\n#include \"opengm/inference/inference.hxx\"\r\n\r\nnamespace opengm {\r\n\r\n// Graph Cut Optimizer.\r\n//\r\n// This optimizer minimizes the value of a graphical model\r\n// of the type GraphicalModel<Factor, opengm::Adder>\r\n// \r\ntemplate<class Factor>\r\nclass GraphCut \r\n: Inference<GraphicalModel<Factor, opengm::Adder>, \r\n            opengm::Minimizer> \r\n{\r\npublic:\r\n    typedef Factor factor_type;\r\n    typedef typename factor_type::space_type space_type; \r\n    typedef typename factor_type::value_type value_type;\r\n    typedef typename space_type::state_type state_type;\r\n    typedef GraphicalModel<Factor, opengm::Adder> gm_type;\r\n    enum MaxFlowAlgorithm { PUSH_RELABEL, EDMONDS_KARP, KOLMOGOROV };\r\n\r\n    // construction\r\n    GraphCut(const gm_type&, const MaxFlowAlgorithm& = PUSH_RELABEL);\r\n\r\n    // query\r\n    std::string name() const;\r\n    const gm_type& graphicalModel() const;\r\n\r\n    // manipulation\r\n    void setMaxFlowAlgorithm(const MaxFlowAlgorithm&);\r\n\r\n    // inference\r\n    InferenceTermination infer();\r\n    InferenceTermination arg(std::vector<state_type>&, const size_t& = 1) const;\r\n\r\nprivate:\r\n    // boost graph library\r\n    typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> graph_traits;\r\n    typedef graph_traits::edge_descriptor edge_descriptor;\r\n    typedef graph_traits::vertex_descriptor vertex_descriptor;\r\n    struct Edge {\r\n        Edge() : capacity(value_type()), residual(value_type()), reverse(edge_descriptor()) {}\r\n        value_type capacity;\r\n        value_type residual;\r\n        edge_descriptor reverse;\r\n    };\r\n    typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, size_t, Edge> graph_type;\r\n    typedef typename boost::graph_traits<graph_type>::edge_iterator edge_iterator;\r\n    typedef typename boost::graph_traits<graph_type>::out_edge_iterator out_edge_iterator;\r\n\r\n    void constructGraph();\r\n    void printGraph();\r\n    void cutPushRelabel();\r\n    void cutEdmondsKarp();\r\n    void cutKolmogorov();\r\n\r\n    const gm_type& gm_;\r\n    MaxFlowAlgorithm maxFlowAlgorithm_;\r\n    graph_type graph_;\r\n    std::vector<state_type> state_;\r\n};\r\n\r\n// public interface\r\n\r\ntemplate<class Factor>\r\nGraphCut<Factor>::GraphCut\r\n(\r\n    const typename GraphCut::gm_type& gm,\r\n    const MaxFlowAlgorithm& maxFlowAlgorithm\r\n)\r\n: gm_(gm),\r\n  maxFlowAlgorithm_(maxFlowAlgorithm)\r\n{\r\n    for(size_t j=0; j<gm_.space().dimension(); ++j) {\r\n        if(gm_.space().numberOfStates(j) != 2) {\r\n            throw std::runtime_error(\"This implementation of the graph cut optimizer supports only binary variables.\");\r\n        }\r\n    }\r\n    for(size_t j=0; j<gm_.numberOfFactors(); ++j) {\r\n        if(gm_[j].numberOfVariables() > 2) {\r\n            throw std::runtime_error(\"This implementation of the graph cut optimizer supports only factors of order <= 2.\");\r\n        }\r\n        if(!gm_[j].isSubmodular()) {\r\n            throw std::runtime_error(\"This implementation of the graph cut optimizer supports only submodular factors.\");\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<class Factor>\r\ninline std::string \r\nGraphCut<Factor>::name() const\r\n{\r\n    return \"GraphCut\";\r\n}\r\n\r\ntemplate<class Factor>\r\ninline const typename GraphCut<Factor>::gm_type& \r\nGraphCut<Factor>::graphicalModel() const\r\n{\r\n    return gm_;\r\n}\r\n\r\ntemplate<class Factor>\r\ninline void \r\nGraphCut<Factor>::setMaxFlowAlgorithm\r\n(\r\n    const MaxFlowAlgorithm& maxFlowAlgorithm\r\n)\r\n{\r\n    maxFlowAlgorithm_ = maxFlowAlgorithm;\r\n}\r\n\r\ntemplate<class Factor>\r\ninline InferenceTermination \r\nGraphCut<Factor>::infer()\r\n{\r\n    constructGraph();\r\n    if(maxFlowAlgorithm_ == PUSH_RELABEL) {\r\n        cutPushRelabel();\r\n    }\r\n    else if(maxFlowAlgorithm_ == EDMONDS_KARP) {\r\n        cutEdmondsKarp();\r\n    }\r\n    else if(maxFlowAlgorithm_ == KOLMOGOROV) {\r\n        cutKolmogorov();\r\n    }\r\n    return NORMAL;\r\n}\r\n\r\ntemplate<class Factor>\r\ninline InferenceTermination \r\nGraphCut<Factor>::arg\r\n(\r\n    std::vector<state_type>& arg, \r\n    const size_t& n\r\n) const\r\n{\r\n    if(n > 1) {\r\n        return UNKNOWN;\r\n    }\r\n    else {\r\n        // skip source and sink\r\n        arg.resize(state_.size() - 2);\r\n        for(size_t j=2; j<state_.size(); ++j) {\r\n            arg[j-2] = state_[j];\r\n        }\r\n        return NORMAL;\r\n    }\r\n}\r\n\r\n// private member functions\r\n\r\ntemplate<class Factor>\r\nvoid\r\nGraphCut<Factor>::constructGraph()\r\n{\r\n    graph_ = graph_type(gm_.space().dimension()+2); \r\n    // add source and sink vertex\r\n    for(size_t j=0; j<gm_.numberOfFactors(); ++j) {\r\n        const factor_type& factor = gm_[j];\r\n        if(factor.numberOfVariables() == 0) {\r\n            // constant factors\r\n            // ignoring\r\n        }\r\n        else if(factor.numberOfVariables() == 1) {\r\n            // 1st order factor\r\n            if(factor(0) <= factor(1)) {\r\n                // edge\r\n                std::pair<edge_descriptor, bool> e =\r\n                    add_edge(0, factor.variableIndex(0)+2, graph_); // from source\r\n                graph_[e.first].capacity = factor(1) - factor(0); // cost\r\n                // reverse edge\r\n                std::pair<edge_descriptor, bool> er =\r\n                    add_edge(factor.variableIndex(0)+2, 0, graph_); \r\n                graph_[e.first].reverse = er.first;\r\n                graph_[er.first].reverse = e.first; \r\n            }\r\n            else {\r\n                // edge\r\n                std::pair<edge_descriptor, bool> e =\r\n                    add_edge(factor.variableIndex(0)+2, 1, graph_); // to sink\r\n                graph_[e.first].capacity = factor(0) - factor(1); // cost\r\n                // reverse edge\r\n                std::pair<edge_descriptor, bool> er =\r\n                    add_edge(1, factor.variableIndex(0)+2, graph_); \r\n                graph_[e.first].reverse = er.first;\r\n                graph_[er.first].reverse = e.first; \r\n            }\r\n        }\r\n        else if(factor.numberOfVariables() == 2) {\r\n            // 2nd order factor\r\n            const value_type& A = factor(0,0);\r\n            const value_type& B = factor(0,1);\r\n            const value_type& C = factor(1,0);\r\n            const value_type& D = factor(1,1);\r\n            // first variabe\r\n            if(C > A) {\r\n                // edge\r\n                std::pair<edge_descriptor, bool> e =\r\n                    add_edge(0, factor.variableIndex(0)+2, graph_); // from source\r\n                graph_[e.first].capacity = C - A; // cost\r\n                // reverse edge\r\n                std::pair<edge_descriptor, bool> er =\r\n                    add_edge(factor.variableIndex(0)+2, 0, graph_); \r\n                graph_[e.first].reverse = er.first;\r\n                graph_[er.first].reverse = e.first; \r\n            }\r\n            else if(C < A) {\r\n                // edge\r\n                std::pair<edge_descriptor, bool> e = \r\n                    add_edge(factor.variableIndex(0)+2, 1, graph_); // to sink\r\n                graph_[e.first].capacity = A - C; // cost\r\n                // reverse edge\r\n                std::pair<edge_descriptor, bool> er = \r\n                    add_edge(1, factor.variableIndex(0)+2, graph_); \r\n                graph_[e.first].reverse = er.first;\r\n                graph_[er.first].reverse = e.first; \r\n            }\r\n            // second variable\r\n            if(D > C) {\r\n                // edge\r\n                std::pair<edge_descriptor, bool> e = \r\n                    add_edge(0, factor.variableIndex(1)+2, graph_); // from source\r\n                graph_[e.first].capacity = D - C; // cost\r\n                // reverse edge\r\n                std::pair<edge_descriptor, bool> er = \r\n                    add_edge(factor.variableIndex(1)+2, 0, graph_); \r\n                graph_[e.first].reverse = er.first;\r\n                graph_[er.first].reverse = e.first; \r\n            }\r\n            else if(D < C) {\r\n                // edge\r\n                std::pair<edge_descriptor, bool> e = \r\n                    add_edge(factor.variableIndex(1)+2, 1, graph_); // to sink\r\n                graph_[e.first].capacity = C - D; // cost\r\n                // reverse edge\r\n                std::pair<edge_descriptor, bool> er = \r\n                    add_edge(1, factor.variableIndex(1)+2, graph_); \r\n                graph_[e.first].reverse = er.first;\r\n                graph_[er.first].reverse = e.first; \r\n            }\r\n            // submodular term\r\n            if(B + C - A - D > 0) {\r\n                // edge\r\n                std::pair<edge_descriptor, bool> e = \r\n                    add_edge(factor.variableIndex(0)+2, factor.variableIndex(1)+2, graph_); \r\n                graph_[e.first].capacity = B + C - A - D; // cost\r\n                // reverse edge\r\n                std::pair<edge_descriptor, bool> er = \r\n                    add_edge(factor.variableIndex(1)+2, factor.variableIndex(0)+2, graph_); \r\n                graph_[e.first].reverse = er.first;\r\n                graph_[er.first].reverse = e.first; \r\n            }\r\n        }\r\n        else {\r\n            // higher order factor\r\n            throw std::runtime_error(\"This implementation of the graph cut optimizer does not support factors of order >2.\");\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<class Factor>\r\nvoid GraphCut<Factor>::cutEdmondsKarp()\r\n{\r\n    // compute max flow\r\n    std::vector<boost::default_color_type> color(num_vertices(graph_));\r\n    std::vector<edge_descriptor> pred(num_vertices(graph_));\r\n    /*T flow = */edmonds_karp_max_flow(graph_, 0, 1,\r\n        get(&Edge::capacity, graph_),\r\n        get(&Edge::residual, graph_),\r\n        get(&Edge::reverse, graph_),\r\n        &color[0], &pred[0]\r\n    );\r\n\r\n    // find (s,t)-cut set\r\n    state_ = std::vector<state_type>(num_vertices(graph_));\r\n    for(size_t j=2; j<num_vertices(graph_); ++j) {\r\n        if(color[j] == boost::black_color) {\r\n            state_[j] = 0;\r\n        }\r\n        else if(color[j] == boost::white_color) {\r\n            state_[j] = 1;\r\n        }\r\n        else {\r\n            throw std::runtime_error(\"At least one vertex is labeled neither black nor white.\");\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<class Factor>\r\nvoid GraphCut<Factor>::cutPushRelabel()\r\n{\r\n    // compute max flow\r\n    /*T flow = */push_relabel_max_flow(graph_, 0, 1, \r\n        get(&Edge::capacity, graph_), get(&Edge::residual, graph_),\r\n        get(&Edge::reverse, graph_), get(boost::vertex_index_t(), graph_));\r\n\r\n    // find (s,t)-cut set\r\n    state_ = std::vector<state_type>(num_vertices(graph_), 1);\r\n    state_[0] = 0; // source\r\n    state_[1] = 0; // sink\r\n    typedef typename boost::property_map<graph_type, boost::vertex_index_t>::type VertexIndexMap;\r\n    VertexIndexMap vertexIndexMap = get(boost::vertex_index, graph_);\r\n    std::queue<vertex_descriptor> q;\r\n    q.push(*(vertices(graph_).first)); // source\r\n    while(!q.empty()) {\r\n        out_edge_iterator current, end;\r\n        tie(current, end) = out_edges(q.front(), graph_); \r\n        q.pop();\r\n        while(current != end) {\r\n            if(graph_[*current].residual > 0) {\r\n                vertex_descriptor v = target(*current, graph_);\r\n                if(vertexIndexMap[v] > 1 && state_[vertexIndexMap[v]] == 1) {\r\n                    state_[vertexIndexMap[v]] = 0;\r\n                    q.push(v);\r\n                }\r\n            }\r\n            ++current;\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<class Factor>\r\nvoid GraphCut<Factor>::cutKolmogorov() {\r\n    // compute max flow\r\n    std::vector<boost::default_color_type> color(num_vertices(graph_));\r\n    std::vector<edge_descriptor> pred(num_vertices(graph_));\r\n    std::vector<vertex_descriptor> dist(num_vertices(graph_));\r\n    /*T flow = */kolmogorov_max_flow(graph_,\r\n        get(&Edge::capacity, graph_),\r\n        get(&Edge::residual, graph_),\r\n        get(&Edge::reverse, graph_),\r\n        &pred[0],\r\n        &color[0],\r\n        &dist[0],\r\n        get(boost::vertex_index, graph_),\r\n        0, 1\r\n        );\r\n\r\n    // find (s,t)-cut set\r\n    state_ = std::vector<state_type>(num_vertices(graph_));\r\n    for(size_t j=2; j<num_vertices(graph_); ++j) {\r\n        if(color[j] == boost::black_color || color[j] == boost::gray_color) {\r\n            state_[j] = 0;\r\n        }\r\n        else if(color[j] == boost::white_color) {\r\n            state_[j] = 1;\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<class Factor>\r\nvoid\r\nGraphCut<Factor>::printGraph()\r\n{\r\n    edge_iterator it, end;\r\n    for(tie(it, end) = edges(graph_); it != end; ++it) {\r\n        std::cout << '(' << source(*it, graph_) << \", \" << target(*it, graph_) << \"): \"\r\n            << \"capacity=\" << graph_[*it].capacity << \", residual=\" << graph_[*it].residual << '.' << std::endl;\r\n    }\r\n}\r\n\r\n} // namespace opengm\r\n\r\n#endif // #ifndef OPENGM_GRAPHCUT_HXX\r\n", "meta": {"hexsha": "3e9a685abb0a15d36ae86e20837653e76654f964", "size": 15525, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/opengm/inference/graphcut.hxx", "max_stars_repo_name": "clementfarabet/lua---opengm", "max_stars_repo_head_hexsha": "9d3bf0d5aa181bc59340f76fb462673c83c91ed1", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-02-05T21:36:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-09T21:47:04.000Z", "max_issues_repo_path": "include/opengm/inference/graphcut.hxx", "max_issues_repo_name": "clementfarabet/lua---opengm", "max_issues_repo_head_hexsha": "9d3bf0d5aa181bc59340f76fb462673c83c91ed1", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-18T02:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-09T00:43:45.000Z", "max_forks_repo_path": "include/opengm/inference/graphcut.hxx", "max_forks_repo_name": "clementfarabet/lua---opengm", "max_forks_repo_head_hexsha": "9d3bf0d5aa181bc59340f76fb462673c83c91ed1", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7021276596, "max_line_length": 126, "alphanum_fraction": 0.5921417069, "num_tokens": 3700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766828768970435, "lm_q2_score": 0.044018650803530214, "lm_q1q2_score": 0.014423515935203773}}
{"text": "// #include \"nabo/nabo.h\"\n#include \"helpers.hpp\"\n#include <pcl/io/ply_io.h>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <pcl/io/io.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/registration/icp.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/common/transforms.h>\n#include <omp.h>\n#include <iostream>\n#include <unordered_map>\n#include <gdcpp.h>\n#include <fstream>\n#include <pcl/sample_consensus/ransac.h>\n#include <pcl/sample_consensus/sac_model_plane.h>\n#include <pcl/sample_consensus/sac_model_sphere.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/visualization/cloud_viewer.h>\n\n// using namespace Nabo;\nusing namespace Eigen;\nusing namespace std;\nusing namespace TransformationUtilities;\nusing namespace InputUtilities;\nusing namespace InterfaceUtilities;\n\ntypedef pcl::PointXYZRGB PointT;\ntypedef pcl::PointCloud<PointT> PointCloudT;\n\nstd::ofstream outfile;\nstd::ofstream errorfile;\n\nclass Optimizer\n{\n    private:\n        string config_file;\n        vector<double> getTransVector(boost::property_tree::ptree &pt,string s);\n    public:\n        vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> clouds;\n        vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> cloud_downsampled;\n        vector<MatrixXd> inverse_kinematics;\n        std::vector<double> flange_transformation_initial;\n        std::vector<double> flange_transformation;\n        Eigen::Vector4f plane;\n        Optimizer(string filename);\n        Optimizer(){};\n        void getInputs();\n        double getError(vector<double>);\n        void printError(vector<double>);\n        double getError(vector<double>,vector<double>);\n        unordered_map<int,int> mapping;\n};\n\nOptimizer::Optimizer(string filename)\n{\n    config_file = filename;\n    flange_transformation = std::vector<double>(6,0);\n    flange_transformation_initial = std::vector<double>(6,0);\n}\n\nvector<double> Optimizer::getTransVector(boost::property_tree::ptree &pt,string s)\n{\n    string angle_metric = pt.get<std::string>(s+\".angle\",\"radian\");\n    string camera_approx_trans_metric = pt.get<std::string>(s+\".metric\",\"m\");\n    double cam_approx_scale = 1.0;\n    if(camera_approx_trans_metric==\"cm\")\n        cam_approx_scale = 100.0;\n    else if(camera_approx_trans_metric==\"mm\")\n        cam_approx_scale=1000.0;\n    string approx_transformation = pt.get<std::string>(s+\".value\",\"0,0,0,0,0,0\");\n    cout<<approx_transformation<<endl;\n    vector<string> coords_str;\n    boost::split(coords_str, approx_transformation , boost::is_any_of(\",\"));\n    vector<double> coords;\n    for(int i=0;i<coords_str.size();i++)\n        if(i<3)\n            coords.push_back(stof(coords_str[i])/cam_approx_scale);\n        else\n        {\n            double value = stof(coords_str[i]);\n            if(angle_metric==\"degree\")\n                value=degreeToRadian(value);\n            coords.push_back(value);\n        }\n    for(auto x:coords)\n        cout<<x<<\" \";\n    cout<<endl;\n    return coords;\n}\n\nEigen::Vector4f fitPlane(const pcl::PointCloud<pcl::PointXYZ>::Ptr cloud)\n{\n  Eigen::MatrixXd lhs (cloud->size(), 3);\n  Eigen::VectorXd rhs (cloud->size());\n  for (size_t i = 0; i < cloud->size(); ++i)\n  {\n    const auto& pt = cloud->points[i];\n    lhs(i, 0) = pt.x;\n    lhs(i, 1) = pt.y;\n    lhs(i, 2) = 1.0;\n\n    rhs(i) = -1.0 * pt.z;\n  }\n  Eigen::Vector3d params = lhs.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(rhs);\n  Eigen::Vector3d normal (params(0), params(1), 1.0);\n  auto length = normal.norm();\n  normal /= length;\n  params(2) /= length;\n  return {normal(0), normal(1), normal(2), params(2)};\n}\n\ndouble pointToPlaneDistance(Eigen::Vector4f plane, vector<double> pt)\n{\n    return fabs(plane(0)*pt[0]+plane(1)*pt[1]+plane(2)*pt[2]+plane(3))/(sqrt(pow(plane(0),2)+pow(plane(1),2)+pow(plane(2),2)));\n}\n\ndouble pointToPlaneDistance(vector<double> plane, vector<double> pt)\n{\n    return fabs(plane[0]*pt[0]+plane[1]*pt[1]+plane[2]*pt[2]+plane[3])/(sqrt(pow(plane[0],2)+pow(plane[1],2)+pow(plane[2],2)));\n}\n\nstring getSplit(string name, string character,int id)\n{\n    vector<string> values;\n    boost::split(values,name,boost::is_any_of(character));\n    if(id<0)\n        id = values.size()+id;\n    return values[id];\n}\n\nint getFileId(string filename)\n{\n    string file = getSplit(filename,\"/\",-1);\n    file = getSplit(file,\".\",0);\n    int number = stoi(getSplit(file,\"_\",1));\n    return number;\n}\n\nvoid Optimizer::getInputs()\n{\n    ifstream file;\n    std::cout<<\"Config File: \"<<config_file<<endl;\n    file.open(config_file);\n    using boost::property_tree::ptree;\n    ptree pt;\n    read_xml(file, pt);\n    string camera_metric = pt.get<std::string>(\"data.camera.metric\",\"m\");\n    int counter = 0;\n    for (const auto &cloud : pt.get_child(\"data.camera.clouds\"))\n    {\n        string filename = cloud.second.data();\n        int cloud_id = getFileId(filename); \n        cout<<\"Cloud Number: \"<<cloud_id<<endl;\n        mapping[counter++] = cloud_id-1;\n        PointCloudT::Ptr temp_cloud_t(new PointCloudT);\n        InputUtilities::readPointCloud(filename,temp_cloud_t,camera_metric);\n        PointCloudT::Ptr temp_cloud(new PointCloudT);\n        for(auto pts:temp_cloud_t->points)\n            if(pts.z<=0.8)\n                temp_cloud->points.push_back(pts);\n        // ifstream file(filename);\n        // string line;\n        // for(int c=0;c<14&&getline(file,line);c++);\n        // PointCloudT::Ptr pointcloud(new PointCloudT);\n        // while(getline(file,line))\n        // {\n        //     vector<string> values_from_file;\n        //     boost::split(values_from_file, line, boost::is_any_of(\" \"));\n        //     pcl::PointXYZRGB pt;\n        //     pt.x = stof(values_from_file[0]);\n        //     pt.y = stof(values_from_file[1]);\n        //     pt.z = stof(values_from_file[2]);\n        //     pt.r = stof(values_from_file[3]);\n        //     pt.g = stof(values_from_file[4]);\n        //     pt.b = stof(values_from_file[5]);\n        //     pointcloud->points.push_back(pt);\n        // }\n        // PointCloudT::Ptr temp_cloud(new PointCloudT);\n        // for(int i=0;i<pointcloud->points.size();i++)\n        // {\n        //     auto pt = pointcloud->points[i];\n        //     if(pt.x==0.0&&pt.y==0.0&&pt.z==0.0)\n        //         continue;\n        //     temp_cloud->points.push_back(pt);\n        // }\n        clouds.push_back(temp_cloud);\n        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_bw_temp(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::copyPointCloud(*temp_cloud,*cloud_bw_temp);\n        pcl::VoxelGrid<pcl::PointXYZ> sor;\n        sor.setInputCloud (cloud_bw_temp);\n        constexpr double leaf = 0.02f;\n        sor.setLeafSize (leaf, leaf, leaf);\n        sor.filter (*cloud_filtered);\n        cout<<\"Filtered Clouds Size: \"<<cloud_filtered->points.size()<<endl;\n        cloud_downsampled.push_back(cloud_filtered);\n    }\n    string ik_filename  = pt.get<std::string>(\"data.camera.transformations.inverse_kinematics.location\");\n    cout<<ik_filename<<endl;\n    string transformation_metric = pt.get<std::string>(\"data.camera.transformations.inverse_kinematics.metric\",\"m\");\n    inverse_kinematics = readTransformations(ik_filename,true,transformation_metric);\n    // string touch_points_file = pt.get<std::string>(\"data.plane.file\",\"\");\n    // pcl::PointCloud<pcl::PointXYZ>::Ptr touch_points(new pcl::PointCloud<pcl::PointXYZ>);\n    // ifstream file_h(touch_points_file);\n    // string line;\n    // while(getline(file_h,line)&&line.size())\n    // {\n    //     vector<string> v;\n    //     split(v,line,boost::is_any_of(\",\"));\n    //     pcl::PointXYZ pt;\n    //     pt.x = stof(v[0])/1000.0;\n    //     pt.y = stof(v[1])/1000.0;\n    //     pt.z = stof(v[2])/1000.0;\n    //     touch_points->points.push_back(pt);\n    // }\n    // cout<<\"Size of touch points: \"<<touch_points->points.size()<<endl;\n    // plane = fitPlane(touch_points);\n    // cout<<\"Plane Equation: \"<<endl;\n    // for(int i=0;i<4;i++)\n        // cout<<plane(i)<<\" \";\n    // cout<<endl;\n    // cout<<\"Transformations Read\"<<endl;\n    auto transformation_initial_flange= getTransVector(pt,\"data.camera.transformations.approximate_transformation\");\n    for(int i=0;i<transformation_initial_flange.size();i++)\n    {\n        flange_transformation[i]=transformation_initial_flange[i];\n        flange_transformation_initial[i]=transformation_initial_flange[i];\n    }\n\n    cout<<\"Plane Equation 2: \"<<endl;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_combined (new pcl::PointCloud<pcl::PointXYZ>);\n    int cl = 0;\n    for(auto cloud:clouds)\n    {\n        for(int i=0;i<cloud->points.size();i++)\n        {\n            pcl::PointXYZ pt;\n            pt.x = cloud->points[i].x;\n            pt.y = cloud->points[i].y;\n            pt.z = cloud->points[i].z;\n            if(pt.z>0.8)\n                continue;\n\n            Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(flange_transformation);\n            Eigen::MatrixXd transformation_temp = inverse_kinematics[mapping[cl]]*cam_T_flange;\n            Eigen::Affine3d transformation;\n            for(int a=0;a<3;a++)\n                for(int b=0;b<4;b++)\n                    transformation(a,b) = transformation_temp(a,b);\n\n            float src[3];\n            float out[3];\n            src[0] = pt.x;\n            src[1] = pt.y;\n            src[2] = pt.z;\n            apply_transformation_optimized(src,out,transformation);\n            pt.x = out[0];\n            pt.y = out[1];\n            pt.z = out[2];\n            cloud_combined->points.push_back(pt);\n        }\n        cl++;\n    }\n    auto new_plane = fitPlane(cloud_combined);\n    plane = new_plane;\n    for(int i=0;i<4;i++)\n        cout<<new_plane(i)<<\" \";\n    cout<<endl;\n}\n\ndouble Optimizer::getError(vector<double> transformation)\n{\n    double error = 0.0;\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    // vector<double> error_vec(clouds.size(),0);\n    for(int j=0;j<clouds.size();j++)\n    {\n        double average = 0.0;\n        double error_mx = -1e9;\n        Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(transformation);\n        Eigen::MatrixXd transformation = inverse_kinematics[mapping[j]]*cam_T_flange;\n        Eigen::Affine3d trans;\n        for(int a=0;a<3;a++)\n            for(int b=0;b<4;b++)\n                trans(a,b) = transformation(a,b);\n        for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n        {\n            auto pt = cloud_downsampled[j]->points[i];\n            float src[3];\n            float out[3];\n            src[0] = pt.x;\n            src[1] = pt.y;\n            src[2] = pt.z;\n            apply_transformation_optimized(src,out,trans);\n            double distance = pointToPlaneDistance(plane,{out[0],out[1],out[2]});\n            average+=distance;\n            if(distance>error_mx)\n                error_mx = distance;\n        }\n        error+=average/cloud_downsampled[j]->points.size();\n        // error+=error_mx;\n    }\n    return error/clouds.size();\n}\ndouble Optimizer::getError(vector<double> transformation,vector<double> plane_local)\n{\n    double error = 0.0;\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    // vector<double> error_vec(clouds.size(),0);\n    for(int j=0;j<clouds.size();j++)\n    {\n        double average = 0.0;\n        double error_mx = -1e9;\n        Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(transformation);\n        Eigen::MatrixXd transformation = inverse_kinematics[mapping[j]]*cam_T_flange;\n        Eigen::Affine3d trans;\n        for(int a=0;a<3;a++)\n            for(int b=0;b<4;b++)\n                trans(a,b) = transformation(a,b);\n        for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n        {\n            auto pt = cloud_downsampled[j]->points[i];\n            float src[3];\n            float out[3];\n            src[0] = pt.x;\n            src[1] = pt.y;\n            src[2] = pt.z;\n            apply_transformation_optimized(src,out,trans);\n            double distance = pointToPlaneDistance(plane_local,{out[0],out[1],out[2]});\n            average+=distance;\n            if(distance>error_mx)\n                error_mx = distance;\n        }\n        error+=average/cloud_downsampled[j]->points.size();\n        // error+=error_mx;\n    }\n    return error/clouds.size();\n}\nvoid Optimizer::printError(vector<double> transformation)\n{\n    Eigen::MatrixXd pts=Eigen::MatrixXd::Zero(1,3);\n    for(int j=0;j<clouds.size();j++)\n    {\n        double average = 0.0;\n        double error_mx = -1e9;\n        Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(transformation);\n        Eigen::MatrixXd transformation = inverse_kinematics[mapping[j]]*cam_T_flange;\n        Eigen::Affine3d trans;\n        for(int a=0;a<3;a++)\n            for(int b=0;b<4;b++)\n                trans(a,b) = transformation(a,b);\n        for(int i=0;i<cloud_downsampled[j]->points.size();i++)\n        {\n            auto pt = cloud_downsampled[j]->points[i];\n            float src[3];\n            float out[3];\n            src[0] = pt.x;\n            src[1] = pt.y;\n            src[2] = pt.z;\n            apply_transformation_optimized(src,out,trans);\n            double distance = pointToPlaneDistance(plane,{out[0],out[1],out[2]});\n            average+=distance;\n            if(distance>error_mx)\n                error_mx = distance;\n        }\n        // error+=average/cloud_downsampled[j]->points.size();\n        errorfile<<\"Downsampled No: \"<<j<<\" Error Avg: \"<<average/cloud_downsampled[j]->points.size()*1000.0<<\" Errom Max: \"<<error_mx*1000.0<<endl;\n    }\n    \n    for(int j=0;j<clouds.size();j++)\n    {\n        double average = 0.0;\n        double error_mx = -1e9;\n        Eigen::MatrixXd cam_T_flange = vectorToTransformationMatrix(transformation);\n        Eigen::MatrixXd transformation = inverse_kinematics[mapping[j]]*cam_T_flange;\n        Eigen::Affine3d trans;\n        for(int a=0;a<3;a++)\n            for(int b=0;b<4;b++)\n                trans(a,b) = transformation(a,b);\n        for(int i=0;i<clouds[j]->points.size();i++)\n        {\n            auto pt = clouds[j]->points[i];\n            float src[3];\n            float out[3];\n            src[0] = pt.x;\n            src[1] = pt.y;\n            src[2] = pt.z;\n            apply_transformation_optimized(src,out,trans);\n            double distance = pointToPlaneDistance(plane,{out[0],out[1],out[2]});\n            average+=distance;\n            if(distance>error_mx)\n                error_mx = distance;\n        }\n        // error+=average/cloud_downsampled[j]->points.size();\n        errorfile<<\"Real No: \"<<j<<\" Error Avg: \"<<average/clouds[j]->points.size()*1000.0<<\" Errom Max: \"<<error_mx*1000.0<<endl;\n    }\n    errorfile<<\"--------------------------------------------\"<<endl;\n}\n\nOptimizer opti;\n\nvoid gradientDescent()\n{\n    struct Functor\n    {\n        Functor()\n        { \n        }\n\n        double operator()(const Eigen::VectorXd &xval, Eigen::VectorXd &) const\n        {\n            vector<double> trans(6);\n            for(int i=0;i<6;i++){\n                trans[i]=xval(i);\n            }\n            return opti.getError(trans);\n        }\n    };\n    gdc::GradientDescent<double, Functor,\n        gdc::WolfeBacktracking<double>> optimizer;\n\n    optimizer.setMaxIterations(10000);\n    optimizer.setMinGradientLength(1e-6);\n    optimizer.setMinStepLength(1e-6);\n    optimizer.setMomentum(0.4);\n    optimizer.setVerbosity(4);\n    Eigen::VectorXd initialGuess = Eigen::VectorXd::Zero(6);\n    for(int i=0;i<6;i++)\n    {\n        initialGuess(i) = opti.flange_transformation[i];\n    }\n    cout<<\"Plane Value\"<<endl;\n    for(int i=0;i<4;i++)\n        cout<<opti.plane(i)<<\" \";\n    cout<<endl;\n    auto result = optimizer.minimize(initialGuess);\n    std::cout << \"Done! Converged: \" << (result.converged ? \"true\" : \"false\")\n        << \" Iterations: \" << result.iterations << std::endl;\n    std::cout << \"Final fval: \" << result.fval << std::endl;\n    std::cout << \"Final xval: \" << result.xval.transpose() << std::endl;\n    std::cout<<\"---------------------------------------------------------\"<<endl;\n    outfile<<\"Gradient Descent on Flange Transformation...\"<<endl;\n    outfile<<\"Iterations: \"<<result.iterations<<\" Converged: \"<<(result.converged ? \"true\" : \"false\")<<\" Final fval: \"<<result.fval<<endl;\n    outfile<<\"Flange Transformation\"<<endl;\n    auto result_flange_trans = result.xval.transpose().head(6);\n    for(int i=0;i<5;i++)\n        outfile<<result_flange_trans(i)<<\", \";\n    outfile<<result_flange_trans(5)<<endl;\n    outfile<<\"Plane Equation\"<<endl;\n    for(int i=0;i<3;i++)\n        outfile<<opti.plane(i)<<\", \";\n    outfile<<opti.plane(3)<<endl;\n    for(int i=0;i<6;i++)\n        opti.flange_transformation[i] = result_flange_trans(i);\n    opti.printError({result_flange_trans(0),result_flange_trans(1),result_flange_trans(2),result_flange_trans(3),result_flange_trans(4),result_flange_trans(5)});\n}\nvoid gradientDescentWithPlane()\n{\n    struct Functor\n    {\n        Functor()\n        { \n        }\n\n        double operator()(const Eigen::VectorXd &xval, Eigen::VectorXd &) const\n        {\n            vector<double> trans(6);\n            vector<double> plane(4);\n            for(int i=0;i<6;i++){\n                trans[i]=xval(i);\n            }\n            for(int i=6;i<10;i++)\n                plane[i-6]=xval(i);\n            return opti.getError(trans,plane);\n        }\n    };\n    gdc::GradientDescent<double, Functor,\n        gdc::WolfeBacktracking<double>> optimizer;\n\n    optimizer.setMaxIterations(10000);\n    optimizer.setMinGradientLength(1e-6);\n    optimizer.setMinStepLength(1e-6);\n    optimizer.setMomentum(0.4);\n    optimizer.setVerbosity(4);\n    Eigen::VectorXd initialGuess = Eigen::VectorXd::Zero(10);\n    for(int i=0;i<6;i++)\n    {\n        initialGuess(i) = opti.flange_transformation[i];\n    }\n    cout<<\"Plane Value\"<<endl;\n    for(int i=0;i<4;i++)\n        cout<<opti.plane(i)<<\" \";\n    cout<<endl;\n    for(int i=0;i<4;i++)\n        initialGuess(i+6) = opti.plane(i);\n    auto result = optimizer.minimize(initialGuess);\n    std::cout << \"Done! Converged: \" << (result.converged ? \"true\" : \"false\")\n        << \" Iterations: \" << result.iterations << std::endl;\n    std::cout << \"Final fval: \" << result.fval << std::endl;\n    std::cout << \"Final xval: \" << result.xval.transpose() << std::endl;\n    std::cout<<\"---------------------------------------------------------\"<<endl;\n    outfile<<\"Gradient Descent on Plane...\"<<endl;\n    outfile<<\"Iterations: \"<<result.iterations<<\" Converged: \"<<(result.converged ? \"true\" : \"false\")<<\" Final fval: \"<<result.fval<<endl;\n    outfile<<\"Flange Transformation\"<<endl;\n    auto result_flange_trans = result.xval.transpose().head(6);\n    for(int i=0;i<5;i++)\n        outfile<<result_flange_trans(i)<<\", \";\n    outfile<<result_flange_trans(5)<<endl;\n    outfile<<\"Plane Equation\"<<endl;\n    auto result_plane = result.xval.transpose().tail(4);\n    for(int i=0;i<3;i++)\n        outfile<<result_plane(i)<<\", \";\n    outfile<<result_plane(3)<<endl;\n    opti.printError({result_flange_trans(0),result_flange_trans(1),result_flange_trans(2),result_flange_trans(3),result_flange_trans(4),result_flange_trans(5)});\n}\n\nvoid discreteCombinatorialOptimization()\n{\n    vector<double> transformation = opti.flange_transformation;\n    cout<<\"True: \"<<opti.getError(transformation);\n    vector<double> transformation_best = opti.flange_transformation;\n    double error_min = 1e9;\n    double t_min = -20, t_max = 20, r_min = -5, r_max = 5;\n    for(double x = t_min;x<=t_max;x+=4)\n        for(double y = t_min;y<=t_max;y+=4)\n            for(double z = t_min;z<=t_max;z+=4)\n                for(double zt=r_min;zt<=r_max;zt++)\n                    for(double yt=r_min;yt<=r_max;yt++)\n                        for(double xt=r_min;xt<=r_max;xt++)\n                        {\n                            vector<double> temp_transformation = {transformation[0]+x/1000.0,transformation[1]+y/1000.0,transformation[2]+z/1000.0,transformation[3]+degreeToRadian(zt),transformation[4]+degreeToRadian(yt),transformation[5]+degreeToRadian(xt)};\n                            double total_error = opti.getError(temp_transformation);\n                            if(total_error<error_min)\n                            {\n                                cout<<\"Error: \"<<total_error<<endl;\n                                transformation_best = temp_transformation;\n                                error_min = total_error;\n                            }\n                        }\n    cout<<\"Best Transformation:\"<<endl;\n    for(auto x:transformation_best)\n        cout<<x<<\" \";\n    cout<<endl;\n    outfile<<\"Flange Transformation From Discrete Optimization\"<<endl;\n    for(int i=0;i<5;i++)\n        outfile<<transformation_best[i]<<\", \";\n    outfile<<transformation_best[5]<<endl;\n    opti.flange_transformation = transformation_best;\n}\n\nint main(int argc, char** argv)\n{\n    if(argc<2)\n    {\n        std::cout<<\"Usage: optimizer_test <config file>\"<<endl;\n        exit(-1);\n    }\n    outfile.open(\"results.txt\", std::ios_base::app); // append instead of overwrite\n    string config_filename = argv[1];\n    errorfile.open(\"new_experiments_errors.txt\", std::ios_base::app); // append instead of overwrite\n    config_filename = argv[1];\n    outfile<<\"Results: \"<<config_filename<<endl;\n    errorfile<<\"Results: \"<<config_filename<<endl;\n    opti = Optimizer(config_filename);\n    opti.getInputs();\n    cout<<\"Starting optimization\"<<endl;\n    discreteCombinatorialOptimization();\n    gradientDescent();\n    gradientDescentWithPlane();\n    outfile<<\"------------------------------------------------------\"<<endl;\n    return 0;\n}\n\n", "meta": {"hexsha": "c677d379575f80be383bab16bc5f072fff456313", "size": 21885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camera_calibration_optimization.cpp", "max_stars_repo_name": "REXJJ/CameraCalibration", "max_stars_repo_head_hexsha": "6c35d88f64846e5d7e74b4156a75080a9a5f1adf", "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/camera_calibration_optimization.cpp", "max_issues_repo_name": "REXJJ/CameraCalibration", "max_issues_repo_head_hexsha": "6c35d88f64846e5d7e74b4156a75080a9a5f1adf", "max_issues_repo_licenses": ["Apache-2.0"], "max_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_calibration_optimization.cpp", "max_forks_repo_name": "REXJJ/CameraCalibration", "max_forks_repo_head_hexsha": "6c35d88f64846e5d7e74b4156a75080a9a5f1adf", "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.538593482, "max_line_length": 259, "alphanum_fraction": 0.5963445282, "num_tokens": 5593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.030214590014638817, "lm_q1q2_score": 0.014399658766208596}}
{"text": "/************************************************************************/\n/*                                                                      */\n/*               Copyright 2007-2019 by Hans Meine                      */\n/*                                                                      */\n/*    Permission is hereby granted, free of charge, to any person       */\n/*    obtaining a copy of this software and associated documentation    */\n/*    files (the \"Software\"), to deal in the Software without           */\n/*    restriction, including without limitation the rights to use,      */\n/*    copy, modify, merge, publish, distribute, sublicense, and/or      */\n/*    sell copies of the Software, and to permit persons to whom the    */\n/*    Software is furnished to do so, subject to the following          */\n/*    conditions:                                                       */\n/*                                                                      */\n/*    The above copyright notice and this permission notice shall be    */\n/*    included in all copies or substantial portions of the             */\n/*    Software.                                                         */\n/*                                                                      */\n/*    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND    */\n/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   */\n/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          */\n/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       */\n/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      */\n/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      */\n/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     */\n/*    OTHER DEALINGS IN THE SOFTWARE.                                   */\n/*                                                                      */\n/************************************************************************/\n\n#include \"mydebug.hxx\"\n#include \"debugimage.hxx\"\n#include \"crop.hxx\"\n\n#include \"foureightsegmentation.hxx\"\n#include \"cellconfigurations.hxx\"\n\n#include <boost/format.hpp>\n\n#include <iostream>\n#include <algorithm>\n#include <set>\n\n#if !defined(NDEBUG) && !defined(_MSC_VER)\n#  warning Consistency checks will be done after every Euler operation!\n#endif\n\nnamespace vigra {\n\nnamespace cellimage {\n\n#ifndef NDEBUG\ninline void validateDart(const GeoMap::DartTraverser &dart)\n{\n    vigra_precondition(dart.neighborCirculator().center()->type() == CellTypeVertex,\n                       \"dart is not attached to a node\");\n    vigra_precondition(dart.startNode().initialized(),\n                       \"dart's startNode is not valid (initialized())\");\n    if(!dart.isSingular())\n        vigra_precondition(dart.edge().initialized(),\n                           \"dart's edge is not valid (initialized())\");\n}\n#else\n// separate def. to prevent compiler warning due to unused param:\ninline void validateDart(const GeoMap::DartTraverser &) {}\n#endif\n\nstruct FindMaxLabel\n{\n    CellLabel maxLabel_;\n\n    FindMaxLabel() : maxLabel_(0) {}\n\n    void operator()(const CellPixel &p)\n    {\n        if(p.label() > maxLabel_)\n            maxLabel_ = p.label();\n    }\n\n    CellLabel operator()() const\n    { return maxLabel_; }\n};\n\nGeoMap::GeoMap(const CellImage &importImage)\n: initialized_(false)\n{\n    cellImage.resize(importImage.size());\n    copyImage(srcImageRange(importImage), destImage(cellImage));\n\n    cells = cellImage.upperLeft() + Diff2D(2, 2);\n\n    FindMaxLabel findMaxNodeLabel;\n    inspectImageIf(srcImageRange(cellImage),\n                   maskImage(cellImage, CellTypeEquals<CellTypeVertex>()),\n                   findMaxNodeLabel);\n    CellLabel maxNodeLabel = findMaxNodeLabel();\n    std::cerr << \"  found maxNodeLabel: \" << maxNodeLabel << \"\\n\";\n\n    FindMaxLabel findMaxEdgeLabel;\n    inspectImageIf(srcImageRange(cellImage),\n                   maskImage(cellImage, CellTypeEquals<CellTypeLine>()),\n                   findMaxEdgeLabel);\n    CellLabel maxEdgeLabel = findMaxEdgeLabel();\n    std::cerr << \"  found maxEdgeLabel: \" << maxEdgeLabel << \"\\n\";\n\n    FindMaxLabel findMaxFaceLabel;\n    inspectImageIf(srcImageRange(cellImage),\n                   maskImage(cellImage, CellTypeEquals<CellTypeRegion>()),\n                   findMaxFaceLabel);\n    CellLabel maxFaceLabel = findMaxFaceLabel();\n    std::cerr << \"  found maxFaceLabel: \" << maxFaceLabel << \"\\n\";\n\n    nodeCount_ = edgeCount_ = faceCount_ = 0;\n\n//    if(maxNodeLabel+maxEdgeLabel+maxFaceLabel>25000)\n//        std::cerr << maxNodeLabel/nodeCount_;\n\n    std::cerr << \"  initializing nodeList..\\n\";\n    initNodeList(maxNodeLabel);\n    std::cerr << \"  initializing edgeList..\\n\";\n    initEdgeList(maxEdgeLabel);\n\n    std::cerr << \"  creating temporary contourImage..\\n\";\n    BImage contourImage(cellImage.size());\n    contourImage = 1;\n    initImageIf(destImageRange(contourImage),\n                maskImage(cellImage, CellTypeEquals<CellTypeRegion>()),\n                0);\n    std::cerr << \"  initializing faceList..\\n\";\n    initFaceList(contourImage, maxFaceLabel);\n\n    initialized_ = true;\n}\n\nunsigned int GeoMap::findComponentAnchor(\n    const FaceInfo &face, const DartTraverser & dart)\n{\n    unsigned int result = 0;\n    const ContourComponents &contours = face.contours;\n\n    if(contours.size() == 1)\n        return result;\n\n    if(dart.isSingular())\n    {\n        // look for startNodeLabel\n        for(ConstContourComponentsIterator contour= contours.begin();\n            contour != contours.end(); ++contour, ++result)\n            if(contour->startNodeLabel() == dart.startNodeLabel())\n                return result;\n    }\n    else\n    {\n        // look for edgeLabel\n        for(ConstContourComponentsIterator contour= contours.begin();\n            contour != contours.end(); ++contour, ++result)\n            if(!contour->isSingular() &&\n               (contour->edgeLabel() == dart.edgeLabel()))\n                return result;\n\n        // we have to circulate through all contours now.. :-(\n        result = 0;\n        for(ConstContourComponentsIterator contour= contours.begin();\n            contour != contours.end(); ++contour, ++result)\n        {\n            DartTraverser dart2(*contour);\n            while(dart2.nextPhi() != *contour)\n            {\n                if(dart2.edgeLabel() == dart.edgeLabel())\n                    return result;\n            }\n        }\n    }\n\n    std::cerr << \"DART NOT FOUND IN CONTOURS OF FACE \" << face.label\n              << \": \" << dart << \"\\n\";\n    result = 1;\n    for(ConstContourComponentsIterator contour= contours.begin();\n        contour != contours.end(); ++contour, ++result)\n    {\n        std::cerr << \"contour \" << result << \":\\n\";\n        DartTraverser dart2(*contour);\n        do {\n            std::cerr << \"  \" << dart2 << \"\\n\";\n        } while(dart2.nextPhi() != *contour);\n    }\n\n    vigra_fail(\"findComponentAnchor: dart not found in any contour\");\n    return 0;\n}\n\nvoid GeoMap::removeNodeFromContours(ContourComponents &contours,\n                                    CellLabel nodeLabel)\n{\n    // find contour anchor to be changed if it points to this edge\n    for(ContourComponentsIterator contour= contours.begin();\n        contour != contours.end(); ++contour)\n        if(contour->startNodeLabel() == nodeLabel)\n            contour->nextPhi();\n}\n\nGeoMap::FaceInfo &GeoMap::removeIsolatedNode(const DartTraverser & dart)\n{\n    //std::cerr << \"removeIsolatedNode(\" << dart << \")\\n\";\n    validateDart(dart);\n    vigra_precondition(dart.isSingular(),\n                       \"removeIsolatedNode: node is not singular\");\n\n    NodeInfo &node= dart.startNode();\n    FaceInfo &face= dart.leftFace();\n\n    face.contours.erase(face.contours.begin() + findComponentAnchor(face, dart));\n\n    for(CellScanIterator it= nodeScanIterator(node.label, cells, false);\n        it.inRange(); ++it)\n        *it= CellPixel(CellTypeRegion, face.label);\n\n    // updating bounds not necessary since all of the node's neighbors\n    // are already face pixels, so the bounds should not change\n    face.size += node.size;\n\n    node.uninitialize();\n    --nodeCount_;\n#ifndef NDEBUG\n    try\n    {\n        checkConsistency();\n    }\n    catch(vigra::StdException &)\n    {\n        std::cerr << \"OPERATION: removeIsolatedNode(\" << dart << \")\\n\";\n        throw;\n    }\n#endif\n    return face;\n}\n\nGeoMap::FaceInfo &GeoMap::mergeFaces(const DartTraverser & dart)\n{\n    //std::cerr << \"mergeFaces(\" << dart << \")\\n\";\n    validateDart(dart);\n    // merge smaller face into larger one:\n    DartTraverser removedDart = dart;\n    if(dart.leftFace().bounds.area() < dart.rightFace().bounds.area())\n        removedDart.nextAlpha();\n\n    EdgeInfo &mergedEdge= removedDart.edge();\n    FaceInfo &survivor= removedDart.leftFace();\n    FaceInfo &mergedFace= removedDart.rightFace();\n    NodeInfo &node1= mergedEdge.start.startNode();\n    NodeInfo &node2= mergedEdge.end.startNode();\n\n    vigra_precondition(survivor.label != mergedFace.label,\n        \"GeoMap::mergeFaces(): dart is singular or edge is a bridge\");\n\n    // find indices of contour components to be merged\n    const unsigned int contour1(findComponentAnchor(survivor, removedDart));\n    const unsigned int contour2(findComponentAnchor(mergedFace, removedDart));\n\n    // re-use an old anchor for the merged contour\n    if(survivor.contours[contour1].edgeLabel() == mergedEdge.label)\n    {\n        survivor.contours[contour1].nextPhi();\n        if(survivor.contours[contour1].edgeLabel() == mergedEdge.label)\n        {\n            survivor.contours[contour1] = mergedFace.contours[contour2];\n            if(survivor.contours[contour1].edgeLabel() == mergedEdge.label)\n                survivor.contours[contour1].nextPhi();\n        }\n    }\n    vigra_postcondition(\n        (survivor.contours[contour1].edgeLabel() != mergedEdge.label)\n        || (node1.label == node2.label),\n        \"did not find an anchor for merged contour!\\n\");\n\n    // update contours\n    for(unsigned int i = 0; i < mergedFace.contours.size(); ++i)\n        if(i != contour2)\n            survivor.contours.push_back(mergedFace.contours[i]);\n\n    // relabel cells in cellImage:\n    for(CellScanIterator it= edgeScanIterator(mergedEdge.label, cells, false);\n        it.inRange(); ++it)\n        *it= CellPixel(CellTypeRegion, survivor.label);\n    for(CellScanIterator it= faceScanIterator(mergedFace.label, cells, false);\n        it.inRange(); ++it)\n        *it= CellPixel(CellTypeRegion, survivor.label);\n\n    // turn node anchors if they pointed to the removed edge and\n    // there's another left\n    if(--node1.degree && node1.anchor.isSingular())\n        node1.anchor.carefulNextSigma();\n    if(--node2.degree && node2.anchor.isSingular())\n        node2.anchor.carefulNextSigma();\n\n    // update bounds and sizes:\n    survivor.bounds |= mergedEdge.bounds;\n    survivor.size += mergedEdge.size;\n    survivor.bounds |= mergedFace.bounds;\n    survivor.size += mergedFace.size;\n\n    mergedEdge.uninitialize();\n    --edgeCount_;\n    mergedFace.uninitialize();\n    --faceCount_;\n    // FIXME: also update maxFaceLabel / maxEdgeLabel\n#ifndef NDEBUG\n    try\n    {\n        checkConsistency();\n    }\n    catch(vigra::StdException &)\n    {\n        std::cerr << \"OPERATION: mergeFaces(\" << dart << \")\\n\";\n        throw;\n    }\n#endif\n    return survivor;\n}\n\nGeoMap::FaceInfo &GeoMap::removeBridge(const DartTraverser & dart)\n{\n    //std::cerr << \"removeBridge(\" << dart << \")\\n\";\n    validateDart(dart);\n    vigra_precondition(!dart.isSingular(), \"removeBridge: dart does not point to any edge\");\n    EdgeInfo &edge= dart.edge();\n    FaceInfo &face= dart.leftFace();\n    NodeInfo &node1= edge.start.startNode();\n    NodeInfo &node2= edge.end.startNode();\n\n    vigra_precondition(face.label == dart.rightFaceLabel(),\n                       \"GeoMap::removeBridge(): edge is not a bridge\");\n\n    // prepare new anchors\n    DartTraverser newAnchor1(edge.start);\n    newAnchor1.prevSigma();\n    DartTraverser newAnchor2(edge.end);\n    newAnchor2.prevSigma();\n\n    const unsigned int contourIndex(findComponentAnchor(face, dart));\n\n#ifndef NDEBUG\n    vigra_invariant(\n        (newAnchor1 != newAnchor2) &&\n        (newAnchor1.startNodeLabel() == node1.label) &&\n        (newAnchor2.startNodeLabel() == node2.label),\n        \"GeoMap::removeBridge(): new anchors unusable\");\n\n#endif // NDEBUG\n\n    // update anchors\n    face.contours[contourIndex] = newAnchor1;\n    face.contours.push_back(newAnchor2);\n\n    // relabel cell in cellImage:\n    for(CellScanIterator it= edgeScanIterator(edge.label, cells, false);\n        it.inRange(); ++it)\n        *it= CellPixel(CellTypeRegion, face.label);\n\n    // turn node anchors if they pointed to the removed edge and\n    // there's another one left\n    if(--node1.degree && node1.anchor.isSingular())\n        node1.anchor.carefulNextSigma();\n    if(--node2.degree && node2.anchor.isSingular())\n        node2.anchor.carefulNextSigma();\n\n    // update bounds and size:\n    face.bounds |= edge.bounds;\n    face.size += edge.size;\n\n    edge.uninitialize();\n    --edgeCount_;\n#ifndef NDEBUG\n    try\n    {\n        checkConsistency();\n    }\n    catch(vigra::StdException &)\n    {\n        std::cerr << \"OPERATION: removeBridge(\" << dart << \")\\n\";\n        throw;\n    }\n#endif\n    return face;\n}\n\nGeoMap::EdgeInfo &GeoMap::mergeEdges(const DartTraverser & dart)\n{\n    //std::cerr << \"mergeEdges(\" << dart << \")\\n\";\n    // merge smaller edge (mergedEdge) into larger one (survivor):\n    validateDart(dart);\n    DartTraverser dart1(dart);\n    dart1.nextSigma();\n    bool firstIsSmaller =\n        dart.edge().bounds.area() < dart1.edge().bounds.area();\n\n    if(firstIsSmaller)\n        dart1.nextSigma(); // dart1 _temporarily_ points to smaller one\n\n    DartTraverser dart2(dart1);\n    EdgeInfo &mergedEdge = dart2.edge();\n    NodeInfo &node = dart1.startNode();\n    dart1.nextSigma();\n    EdgeInfo &survivor = dart1.edge();\n\n    vigra_precondition((firstIsSmaller ? dart2 : dart1) == dart,\n        \"GeoMap::mergeEdges(): node has degree > 2\");\n    vigra_precondition(survivor.label != mergedEdge.label,\n        \"GeoMap::mergeEdges(): node has degree one or is loop\");\n\n    // update contours of neighbored faces if necessary\n    removeNodeFromContours(dart1.leftFace().contours, dart1.startNodeLabel());\n    if(dart1.leftFaceLabel() != dart1.rightFaceLabel())\n        removeNodeFromContours(dart1.rightFace().contours, dart1.startNodeLabel());\n\n    // update start, end\n    dart1.nextAlpha();\n    dart2.nextAlpha();\n    survivor.start = dart1;\n    survivor.end = dart2;\n\n    // relabel cells in cellImage:\n    for(CellScanIterator it= nodeScanIterator(node.label, cells, false);\n        it.inRange(); ++it)\n        *it= CellPixel(CellTypeLine, survivor.label);\n    for(CellScanIterator it= edgeScanIterator(mergedEdge.label, cells, false);\n        it.inRange(); ++it)\n        *it= CellPixel(CellTypeLine, survivor.label);\n\n    // update bounds:\n    survivor.bounds |= node.bounds;\n    survivor.size += node.size;\n    survivor.bounds |= mergedEdge.bounds;\n    survivor.size += mergedEdge.size;\n\n    node.uninitialize();\n    --nodeCount_;\n    mergedEdge.uninitialize();\n    --edgeCount_;\n#ifndef NDEBUG\n    try\n    {\n        checkConsistency();\n    }\n    catch(vigra::StdException &)\n    {\n        std::cerr << \"OPERATION: mergeEdges(\" << dart << \")\\n\";\n        throw;\n    }\n#endif\n    return survivor;\n}\n\n/********************************************************************/\n\nGeoMap &GeoMap::deepCopy(const GeoMap &other)\n{\n    cellImage = other.cellImage;\n    cells = cellImage.upperLeft() + Diff2D(2,2);\n\n    nodeList_ = other.nodeList_;\n    nodeCount_ = other.nodeCount_;\n    edgeList_ = other.edgeList_;\n    edgeCount_ = other.edgeCount_;\n    faceList_ = other.faceList_;\n    faceCount_ = other.faceCount_;\n\n    for(NodeIterator it= nodesBegin(); it.inRange(); ++it)\n    {\n        it->anchor.reparent(this);\n    }\n\n    for(EdgeIterator it= edgesBegin(); it.inRange(); ++it)\n    {\n        it->start.reparent(this);\n        it->end.reparent(this);\n    }\n\n    for(FaceIterator it= facesBegin(); it.inRange(); ++it)\n    {\n        for(ContourComponentsIterator contour= it->contours.begin();\n            contour != it->contours.end(); ++contour)\n        {\n            contour->reparent(this);\n        }\n    }\n\n    initialized_ = other.initialized_; // should be always true\n\n    return *this;\n}\n\n/********************************************************************/\n\nvoid GeoMap::checkConsistency()\n{\n    bool consistent = true;\n    // std::cerr << \"checking nodes...\\n\";\n    for(NodeIterator it= nodesBegin(); it != nodesEnd(); ++it)\n    {\n        // std::cerr << \"  node \" << it->label << \"\\r\";\n        unsigned int realDegree = 0;\n        if(it->anchor.neighborCirculator().center()->type() != CellTypeVertex)\n        {\n            consistent = false;\n            std::cerr << \"node \" << it->label << \"'s anchor is broken: \"\n\t\t\t\t\t  << it->anchor << \"\\n\";\n        }\n        if(!it->anchor.isSingular())\n        {\n            DartTraverser dart(it->anchor);\n            do { ++realDegree; }\n            while(dart.nextSigma() != it->anchor);\n        }\n        if(realDegree != it->degree)\n        {\n            consistent = false;\n            std::cerr << \"node \" << it->label << \" has degree stored as \"\n                      << it->degree << \" but seems to be of degree \"\n                      << realDegree << \"\\n  anchor:\"\n\t\t\t\t\t  << it->anchor << \"\\n\";\n            std::cerr << \"  sigma-successors:\\n\";\n            for(DartTraverser dart(it->anchor); dart.nextSigma() != it->anchor; )\n            {\n                std::cerr << \"   \" << dart << \"\\n\";\n            }\n        }\n\n        FindBoundingRectangle actualBounds;\n        Point2D coord(0, 0);\n        inspectCell(nodeScanIterator(it->label, coord, false), actualBounds);\n        Rect2D ab(actualBounds.upperLeft, actualBounds.lowerRight);\n        if(ab != it->bounds)\n        {\n            consistent = false;\n            std::cerr << \"node \" << it->label << \"'s bounds are stored as \"\n                      << it->bounds << \" but seem to be \" << ab << \"\\n\";\n        }\n    }\n\n    // std::cerr << \"checking edges...\\n\";\n    for(EdgeIterator it= edgesBegin(); it != edgesEnd(); ++it)\n    {\n        // std::cerr << \"  edge \" << it->label << \"\\r\";\n        FindBoundingRectangle actualBounds;\n        Point2D coord(0, 0);\n        inspectCell(edgeScanIterator(it->label, coord, false), actualBounds);\n        Rect2D ab(actualBounds.upperLeft, actualBounds.lowerRight);\n        if(ab != it->bounds)\n        {\n            consistent = false;\n            std::cerr << \"edge \" << it->label << \"'s bounds are stored as \"\n                      << it->bounds << \" but seem to be \" << ab << \"\\n\";\n        }\n        if(it->start.neighborCirculator().center()->type() != CellTypeVertex)\n        {\n            consistent = false;\n            std::cerr << \"edge \" << it->label << \"'s start is broken: \"\n\t\t\t\t\t  << it->start << \"\\n\";\n        }\n        if(it->start.edgeLabel() != it->label)\n        {\n            consistent = false;\n            std::cerr << \"edge \" << it->label << \"'s start points to edge \"\n                      << it->start.edgeLabel() << \"\\n\";\n        }\n        if(it->end.neighborCirculator().center()->type() != CellTypeVertex)\n        {\n            consistent = false;\n            std::cerr << \"edge \" << it->label << \"'s end is broken: \"\n\t\t\t\t\t  << it->end << \"\\n\";\n        }\n        if(it->end.edgeLabel() != it->label)\n        {\n            consistent = false;\n            std::cerr << \"edge \" << it->label << \"'s end points to edge \"\n                      << it->end.edgeLabel() << \"\\n\";\n        }\n    }\n\n    // std::cerr << \"checking faces...\\n\";\n    for(FaceIterator it= facesBegin(); it != facesEnd(); ++it)\n    {\n        // std::cerr << \"  face \" << it->label << \"\\r\";\n        FindBoundingRectangle actualBounds;\n        Point2D coord(0, 0);\n        inspectCell(faceScanIterator(it->label, coord, false), actualBounds);\n        Rect2D ab(actualBounds.upperLeft, actualBounds.lowerRight);\n        if(ab != it->bounds)\n        {\n            consistent = false;\n            std::cerr << \"face \" << it->label << \"'s bounds are stored as \"\n                      << it->bounds << \" but seem to be \" << ab << \"\\n\";\n        }\n\n        for(ContourComponentsIterator cc(it->contours.begin());\n            cc != it->contours.end(); ++cc)\n        {\n            if((cc->neighborCirculator().center()->type() != CellTypeVertex)\n               || (cc->isSingular() && (cc->startNode().degree > 0)))\n            {\n                consistent = false;\n                std::cerr << \"face \" << it->label << \"'s anchor at position \"\n                          << (cc - it->contours.begin()) << \" is broken: \"\n\t\t\t\t\t\t  << *cc << \"\\n\";\n            }\n            DartTraverser dart(*cc);\n            dart.nextSigma();\n            dart.prevSigma();\n            if(dart != *cc)\n            {\n                consistent = false;\n                std::cerr << \"face \" << it->label << \"'s contours are broken:\\n\"\n                          << \"  anchor:  \" << *cc << \"\\n\"\n\t\t\t\t\t\t  << \"  becomes: \" << dart << \"\\n\";\n            }\n            int maxSteps= 10000;\n            do\n            {\n                if(dart.leftFaceLabel() != it->label)\n                {\n                    std::cerr << \"dart.leftFace() is no longer our face!\\n\";\n                    maxSteps = 0;\n                    break;\n                }\n            }\n            while((dart.nextPhi() != *cc) && --maxSteps);\n            if(!maxSteps)\n            {\n                consistent = false;\n                std::cerr << \"face \" << it->label << \"'s contours are broken:\\n\"\n                          << \"  anchor: \" << *cc << \"\\n\"\n\t\t\t\t\t\t  << \"  did not return after \" << maxSteps << \" steps: \"\n\t\t\t\t\t\t  << dart << \"\\n\";\n            }\n\n//  for(unsigned int i = 1; i < face.contours.size(); ++i)\n//      for(unsigned int j = 0; j < i; ++j)\n//          if(face.contours[i] == face.contours[j])\n//          {\n//                 consistent = false;\n//                 std::cerr << \"face \" << face.label << \"'s contours contains one dart twice:\\n  \";\n//              debugDart(face.contours[i]);\n//          }\n        }\n    }\n\n    vigra_postcondition(consistent, \"consistency check failed\");\n}\n\n\n/********************************************************************/\n\nstruct ChooseCellConfiguration\n{\n    CellType * cornerTypeLut_;\n    static CellType preferVertex[6], preferEdge[6];\n\n    ChooseCellConfiguration(CellType cornerType)\n    : cornerTypeLut_(cornerType == CellTypeVertex ? preferVertex : preferEdge)\n    {}\n\n    CellType operator()(CellType c) const\n    {\n        return cornerTypeLut_[c];\n    }\n};\n\nCellType ChooseCellConfiguration::preferVertex[6] = {\n    CellTypeRegion, CellTypeLine, CellTypeVertex, CellTypeError, CellTypeVertex, CellTypeError };\nCellType ChooseCellConfiguration::preferEdge[6] = {\n    CellTypeRegion, CellTypeLine, CellTypeVertex, CellTypeError, CellTypeLine, CellTypeLine };\n\nvoid GeoMap::initCellImage(BImage & contourImage, CellType cornerType)\n{\n    CellType cellConf[256];\n    std::transform(cellConfigurations, cellConfigurations+256, cellConf,\n                   ChooseCellConfiguration(cornerType));\n\n    CellPixel regionPixel(CellTypeRegion, 0);\n\n    BImage::traverser rawLine = contourImage.upperLeft();\n    CellImage::traverser cellLine = cellImage.upperLeft();\n    for(int y=-2; y < cellImage.height()-2; ++y, ++rawLine.y, ++cellLine.y)\n    {\n        BImage::traverser raw = rawLine;\n        CellImage::traverser cell = cellLine;\n        for(int x=-2; x < cellImage.width()-2; ++x, ++raw.x, ++cell.x)\n        {\n            if(*raw == 0)\n            {\n                *cell = regionPixel;\n            }\n            else\n            {\n                vigra::NeighborhoodCirculator<BImage::traverser, EightNeighborCode>\n                    neighbors(raw, EightNeighborCode::SouthEast);\n                vigra::NeighborhoodCirculator<BImage::traverser, EightNeighborCode>\n                    end = neighbors;\n                int conf = 0;\n                do\n                {\n                    conf = (conf << 1) | *neighbors;\n                }\n                while(--neighbors != end);\n\n                if(cellConf[conf] == CellTypeError)\n                {\n                    debugImage(crop(srcImageRange(contourImage),\n                                    Rect2D(x, y, x+5, y+5)),\n                               std::cerr);\n                    vigra_precondition(0, (boost::format(\n                        \"GeoMap::init(): Configuration at (%1%, %2%) must be thinned further \"\n                        \"(found configuration %3%)\") % x % y % conf).str());\n                }\n\n                cell->setType(cellConf[conf], 0);\n            }\n        }\n    }\n\n    // FIXME: this special-handling of the boundary is only necessary\n    // because the containment hierarchy is determined in a strange\n    // way (faceList_[0].anchor is directly initialized from this\n    // position)\n    cellImage(1, 1).setType(CellTypeVertex, 0);\n#ifndef NDEBUG\n    std::cerr << \"*** RUN-TIME WARNING: slowness results from missing NDEBUG flag during compilation of foureightsegmentation.cxx! ***\\n\";\n#endif\n}\n\n/********************************************************************/\n\nCellLabel GeoMap::labelNodes()\n{\n    BImage nodeImage(cellImage.size());\n    BImage::traverser nodes = nodeImage.upperLeft() + Diff2D(2,2);\n\n    for(int y=-2; y < cellImage.height()-2; ++y)\n    {\n        CellImage::traverser cell = cells + Diff2D(-2, y);\n\n        for(int x=-2; x < cellImage.width()-2; ++x, ++cell.x)\n        {\n            if(cell->type() != CellTypeVertex)\n            {\n                nodes(x,y) = 0;\n            }\n            else\n            {\n                nodes(x,y) = 1;\n#if 0\n                // test for forbidden configuration\n                CellImageEightCirculator n(cell);\n                CellImageEightCirculator nend = n;\n\n                do\n                {\n                    vigra_precondition((n->type() != CellTypeLine || n[1].type() || CellTypeLine),\n                                       (boost::format(\"labelNodes(): Node at (%1%, %2%) has two \"\n                                                      \"incident edgels from the same edge (direction: %3%)\")\n                                        % x % y % (n - nend)).str());\n                }\n                while(++n != nend);\n#endif\n            }\n        }\n    }\n\n    return labelImageWithBackground(\n        srcImageRange(nodeImage),\n        destImage(cellImage, LabelWriter<CellTypeVertex>()), true, 0);\n}\n\n/********************************************************************/\n\nCellLabel GeoMap::labelEdges(CellLabel maxNodeLabel)\n{\n    std::vector<bool> nodeProcessed(maxNodeLabel + 1, false);\n\n    CellLabel maxEdgeLabel = 0;\n\n    for(int y=-1; y < cellImage.height()-3; ++y)\n    {\n        CellImage::traverser cell = cells + Diff2D(-1, y);\n\n        for(int x=-1; x < cellImage.width()-3; ++x, ++cell.x)\n        {\n            if(cell->type() != CellTypeVertex)\n                continue;\n            if(nodeProcessed[cell->label()])\n                continue;\n\n            nodeProcessed[cell->label()] = true;\n\n            DartTraverser dart(\n                this, CellImageEightCirculator(cell, EightNeighborCode::West));\n            DartTraverser dend = dart;\n\n            if(dart.isSingular())\n                continue;\n\n            do\n            {\n                if(dart.edgeLabel() != 0)\n                    continue;\n\n                labelEdge(dart.neighborCirculator(), ++maxEdgeLabel);\n            }\n            while(dart.nextSigma() != dend);\n        }\n    }\n\n    return maxEdgeLabel;\n}\n\n/********************************************************************/\n\nCellLabel GeoMap::labelFaces(BImage & contourImage)\n{\n    // labelImageWithBackground() starts with label 1, so don't\n    // include outer border (infinite regions shall have label 0)\n    return labelImageWithBackground(\n        srcIterRange(contourImage.upperLeft() + Diff2D(1,1),\n                     contourImage.lowerRight() - Diff2D(1,1)),\n        destIter(cellImage.upperLeft() + Diff2D(1,1),\n                 LabelWriter<CellTypeRegion>()),\n        false, // eight_neighbors = false -> 4-neighborhood\n        1);    // background: contour value\n}\n\n/********************************************************************/\n\nvoid GeoMap::labelSelfLoops(CellLabel & maxNodeLabel, CellLabel & maxEdgeLabel)\n{\n    for(int y=-1; y < cellImage.height()-3; ++y)\n    {\n        CellImage::traverser cell = cells + Diff2D(-1, y);\n\n        for(int x=-1; x < cellImage.width()-3; ++x, ++cell.x)\n        {\n            if(cell->label() != 0)\n                continue;\n\n            // found a circle (not labeled by previous steps)\n\n            // mark first point as node\n            (*cell) = CellPixel(CellTypeVertex, ++maxNodeLabel);\n\n            CellImageEightCirculator circ(cell);\n            CellImageEightCirculator circEnd = circ;\n\n            do\n            {\n                if(circ->type() != CellTypeLine)\n                    continue;\n                if(circ->label() != 0)\n                    continue;\n\n                labelEdge(circ, ++maxEdgeLabel);\n            }\n            while(++circ != circEnd);\n        }\n    }\n}\n\n/********************************************************************/\n\nvoid GeoMap::labelEdge(CellImageEightCirculator circ,\n                       CellLabel newLabel)\n{\n    EdgelIterator edge(circ);\n\n    // follow the edge and relabel it\n    for(; !edge.atEnd(); ++edge)\n    {\n        edge->setLabel(newLabel, CellTypeLine);\n    }\n}\n\n/********************************************************************/\n\nstruct HoleRemover\n{\n    const CellPixel &p_;\n    mutable unsigned int size_;\n\n    HoleRemover(const CellPixel &p) : p_(p), size_(0) {}\n\n    const CellPixel &operator()(const CellPixel &) const\n    {\n        ++size_;\n        return p_;\n    }\n\n    unsigned int size() const\n    {\n        return size_;\n    }\n};\n\nvoid GeoMap::initNodeList(CellLabel maxNodeLabel)\n{\n    nodeList_.resize(maxNodeLabel + 1);\n    std::vector<unsigned int> crackCirculatedAreas(maxNodeLabel + 1, 0);\n\n    for(Point2D pos= Point2D(-1, -1); pos.y < cellImage.height()-3; ++pos.y)\n    {\n        CellImage::traverser cell = cells + Diff2D(-1, pos.y);\n\n        for(pos.x=-1; pos.x < cellImage.width()-3; ++pos.x, ++cell.x)\n        {\n            if(cell->type() != CellTypeVertex)\n                continue;\n\n            CellLabel nodeLabel = cell->label();\n            vigra_precondition(nodeLabel < nodeList_.size(),\n                               \"nodeList_ must be large enough\");\n\n            if(!nodeList_[nodeLabel].initialized())\n            {\n                nodeList_[nodeLabel].label = nodeLabel;\n                ++nodeCount_;\n\n                nodeList_[nodeLabel].degree = 0;\n                nodeList_[nodeLabel].anchor = DartTraverser(\n                    this, CellImageEightCirculator(cell,\n                                                   EightNeighborCode::West));\n                if(!nodeList_[nodeLabel].anchor.isSingular())\n                {\n                    DartTraverser dart(nodeList_[nodeLabel].anchor);\n                    do\n                    {\n                        ++nodeList_[nodeLabel].degree;\n                    }\n                    while(dart.nextSigma() != nodeList_[nodeLabel].anchor);\n                }\n\n                // calculate area from following the outer contour of the node\n                CrackContourCirculator<CellImage::traverser> crack(cell);\n                CrackContourCirculator<CellImage::traverser> crackend(crack);\n                do\n                {\n                    crackCirculatedAreas[nodeLabel] += crack.diff().x * crack.pos().y -\n                                                   crack.diff().y * crack.pos().x;\n                }\n                while(++crack != crackend);\n\n                crackCirculatedAreas[nodeLabel] /= 2;\n            }\n\n            nodeList_[nodeLabel].bounds |= pos;\n            ++nodeList_[nodeLabel].size;\n        }\n    }\n\n    for(NodeIterator node= nodesBegin(); node.inRange(); ++node)\n    {\n        // methods to calculate the area must yield identical values\n        if(crackCirculatedAreas[node->label] != node->size)\n        {\n//             std::cerr << \"GeoMap::initNodeList(): \"\n//                       << \"Node \" << node->label << \" has a \"\n//                       << (crackCirculatedAreas[node->label] - node->size)\n//                       << \"-pixel hole, stuffing..\\n\";\n\n            CellImage::traverser bul(cells + node->bounds.upperLeft());\n            CellImage::traverser blr(cells + node->bounds.lowerRight());\n\n            CellImage::traverser anchor(bul);\n            CellPixel nodePixel(CellTypeVertex, node->label);\n            while(*anchor != nodePixel)\n                ++anchor.x;\n\n            std::set<CellLabel> outerRegions;\n\n            CrackContourCirculator<CellImage::traverser> crack(anchor);\n            CrackContourCirculator<CellImage::traverser> crackend(crack);\n            do\n            {\n                if(crack.outerPixel()->type() == CellTypeRegion)\n                    outerRegions.insert(crack.outerPixel()->label());\n            }\n            while(++crack != crackend);\n\n//             std::cerr << \"found \" << outerRegions.size() << \" outer regions:\\n\";\n//             for(std::set<CellLabel>::iterator it= outerRegions.begin();\n//                 it != outerRegions.end(); ++it)\n//             {\n//                 std::cerr << *it << \", \";\n//             }\n//             std::cerr << \"\\n\";\n//             debugImage(crop(srcIterRange(cells, cells), node->bounds),\n//                        std::cerr, 4);\n\n            for(bul = cells + node->bounds.upperLeft(); bul.y < blr.y; ++bul.y)\n            {\n                for(anchor= bul; anchor.x < blr.x-1; ++anchor.x)\n                {\n                    if(*anchor == nodePixel)\n                    {\n                        ++anchor.x;\n                        if((anchor->type() == CellTypeRegion) &&\n                           !outerRegions.count(anchor->label()))\n                        {\n//                             std::cerr << \"found hole label: \" << *anchor;\n                            HoleRemover holeRemover(nodePixel);\n                            transformImageIf(crop(srcIterRange(cells, cells), node->bounds),\n                                             crop(maskIter(cells, CellMask(*anchor)), node->bounds),\n                                             crop(destIter(cells), node->bounds),\n                                             holeRemover);\n\n                            node->size += holeRemover.size();\n//                             std::cerr << \" (\" << holeRemover.size() << \" pixels)\\n\";\n\n                            if(crackCirculatedAreas[node->label] == node->size)\n                                goto HolesStuffed; // double break\n                        }\n                        else\n                            --anchor.x;\n                    }\n                }\n            }\n\n        HolesStuffed:\n            ;\n        }\n    }\n}\n\n/********************************************************************/\n\nvoid GeoMap::initEdgeList(CellLabel maxEdgeLabel)\n{\n    edgeList_.resize(maxEdgeLabel + 1);\n\n    for(NodeIterator n = nodesBegin(); n.inRange(); ++n)\n    {\n        DartTraverser dart = n->anchor;\n        if(dart.isSingular())\n            continue;\n        DartTraverser dartEnd = dart;\n\n        int debugCount = 0;\n        do\n        {\n            CellLabel label = dart.edgeLabel();\n            vigra_precondition(label < edgeList_.size(),\n                               \"edgeList_ must be large enough\");\n            if(!edgeList_[label].initialized())\n            {\n                edgeList_[label].label = label;\n                ++edgeCount_;\n                edgeList_[label].start = dart;\n                edgeList_[label].end = dart;\n                edgeList_[label].end.nextAlpha();\n                // correct size and bounds will be collected by initFaceList()\n                edgeList_[label].size = 0;\n            }\n\n            if(++debugCount == 40)\n            {\n                std::cerr << \"node \" << n->label << \" has degree > 40??\\n\"\n                          << \"  bounds: \" << n->bounds << \"\\n\";\n                Rect2D dr(n->bounds);\n                dr |= Point2D(dartEnd.neighborCirculator().base() - cells);\n                dr |= Point2D(dart.neighborCirculator().base() - cells);\n                std::cerr << \"debugging rect \" << dr << \" including \"\n                          << Point2D(dartEnd.neighborCirculator().base() - cells) << \"\\n\";\n                debugImage(crop(srcIterRange(cells, cells), dr),\n                           std::cerr, 4);\n                std::cerr << \"dartEnd: \" << dartEnd << \"\\n\";\n                std::cerr << \"dart:    \" << dart << \"\\n\";\n            }\n        }\n        while(dart.nextSigma() != dartEnd);\n    }\n}\n\n/********************************************************************/\n\nvoid GeoMap::initFaceList(BImage & contourImage, CellLabel maxFaceLabel)\n{\n    faceList_.resize(maxFaceLabel + 1);\n\n    IImage contourLabelImage(cellImage.size());\n    contourLabelImage = 0;\n    int contourComponentsCount =\n        labelImageWithBackground(srcImageRange(contourImage),\n                                 destImage(contourLabelImage), true, 0);\n    IImage::traverser contourLabel =\n        contourLabelImage.upperLeft() + Diff2D(2, 2);\n\n    std::vector<bool> contourProcessed(contourComponentsCount + 1, false);\n\n    // process outer face\n    faceList_[0].label= 0;\n    ++faceCount_;\n    faceList_[0].bounds |= Point2D(-2, -2);\n    faceList_[0].bounds |= Point2D(-2, -2) + cellImage.size() - Diff2D(1, 1);\n    faceList_[0].size = NumericTraits<unsigned int>::max();\n    DartTraverser anchor(this, CellImageEightCirculator(cells + Diff2D(-1, -1),\n                                                        EightNeighborCode::West));\n    faceList_[0].contours.push_back(anchor.prevSigma());\n    contourProcessed[contourLabel(-1, -1)] = true;\n\n    for(Point2D pos= Point2D(-1, -1); pos.y < cellImage.height()-3; ++pos.y)\n    {\n        pos.x= -1;\n        CellImage::traverser cell = cells + pos;\n        CellImage::traverser leftNeighbor = cell - Diff2D(1, 0);\n\n        for(; pos.x < cellImage.width()-3; ++pos.x, ++cell.x, ++leftNeighbor.x)\n        {\n            if(cell->type() != CellTypeRegion)\n            {\n                if(cell->type() == CellTypeLine)\n                {\n                    edgeList_[cell->label()].bounds |= pos;\n                    edgeList_[cell->label()].size += 1;\n                }\n                continue;\n            }\n\n            CellLabel faceLabel = cell->label();\n            vigra_precondition(faceLabel < faceList_.size(),\n                               \"faceList_ must be large enough\");\n\n            if(!faceList_[faceLabel].initialized())\n            {\n                //std::cerr << \"found face \" << faceLabel << \" at \" << pos.x << \",\" << pos.y << \"\\n\";\n                faceList_[faceLabel].label = faceLabel;\n                ++faceCount_;\n\n                // determine anchor (either via node or via edge):\n                if(leftNeighbor->type() == CellTypeVertex)\n                {\n                    DartTraverser anchor(this,\n                                         CellImageEightCirculator(leftNeighbor));\n                    anchor.prevSigma();\n\n                    vigra_invariant(anchor.leftFaceLabel() == faceLabel,\n                                    \"GeoMap::initFaceList()\");\n\n                    faceList_[faceLabel].contours.push_back(anchor);\n                }\n                else\n                {\n                    vigra_precondition(leftNeighbor->type() == CellTypeLine,\n                                       \"leftNeighbor expected to be an edge\");\n\n                    CellLabel edgeIndex = leftNeighbor->label();\n\n                    vigra_precondition(edgeList_[edgeIndex].initialized(),\n                                       (boost::format(\"EdgeInfo %1% expected to be initialized\") % edgeIndex).str());\n\n                    DartTraverser anchor = edgeList_[edgeIndex].start;\n                    if(anchor.leftFaceLabel() != faceLabel)\n                        anchor.nextAlpha();\n\n                    vigra_invariant(anchor.leftFaceLabel() == faceLabel,\n                                    \"GeoMap::initFaceList()\");\n\n                    faceList_[faceLabel].contours.push_back(anchor);\n                }\n            }\n            else // faceLabel seen before\n            {\n                // look for inner contours\n                CellImageEightCirculator neighbor(cell);\n                CellImageEightCirculator nend = neighbor;\n\n                do\n                {\n                    int contourIndex = contourLabel[neighbor.base() - cells];\n                    if(contourIndex == 0 || contourProcessed[contourIndex])\n                        continue;\n\n                    // found an inner contour\n                    contourProcessed[contourIndex] = true;\n\n                    // find incident node\n                    if(neighbor->type() == CellTypeVertex)\n                    {\n                        // this is the node\n                        CellImageEightCirculator n = neighbor;\n                        n.swapCenterNeighbor();\n\n                        DartTraverser anchor(this, n);\n                        anchor.prevSigma();\n\n                        vigra_invariant(anchor.leftFaceLabel() == faceLabel,\n                                        \"GeoMap::initFaceList()\");\n\n                        faceList_[faceLabel].contours.push_back(anchor);\n                    }\n                    else\n                    {\n                        vigra_precondition(neighbor->type() == CellTypeLine,\n                                           \"neighbor expected to be an edge\");\n\n                        CellLabel edgeIndex = neighbor->label();\n\n                        vigra_precondition(edgeList_[edgeIndex].initialized(),\n                                           (boost::format(\"EdgeInfo %1% should be initialized\") % edgeIndex).str());\n\n                        DartTraverser anchor = edgeList_[edgeIndex].start;\n                        if(anchor.leftFaceLabel() != faceLabel)\n                            anchor.nextAlpha();\n\n                        vigra_invariant(anchor.leftFaceLabel() == faceLabel,\n                                        \"GeoMap::initFaceList()\");\n\n                        faceList_[faceLabel].contours.push_back(anchor);\n                    }\n                }\n                while(++neighbor != nend);\n            }\n\n            faceList_[faceLabel].bounds |= pos;\n            ++faceList_[faceLabel].size;\n        }\n    }\n}\n\nstd::ostream &\noperator<<(std::ostream & out,\n\t\t   const vigra::cellimage::GeoMap::DartTraverser & d)\n{\n    static const char * const dirStr[] = {\n        \" E\",\n        \"NE\",\n        \" N\",\n        \"NW\",\n        \" W\",\n        \"SW\",\n        \" S\",\n        \"SE\"\n    };\n\n    vigra::Point2D pos(d.neighborCirculator().center() -\n                       d.segmentation()->cells);\n\n    out << \"DartTraverser[\"\n        << dirStr[(int)d.neighborCirculator().direction()]\n        << \" from \" << pos.x << \", \" << pos.y;\n\n    bool singularDart = false;\n    if(d.neighborCirculator().center()->type() == CellTypeVertex)\n    {\n        CellLabel nodeLabel(d.neighborCirculator().center()->label());\n        out << \" (node \" << nodeLabel;\n        if(nodeLabel > d.segmentation()->maxNodeLabel())\n            out << \", LABEL INVALID!\";\n        else\n        {\n            const GeoMap::NodeInfo &node(d.segmentation()->node(nodeLabel));\n            if(!node.initialized())\n                out << \", UNINITIALIZED\";\n            out << \", \" << node.size << \" pixels, deg. \" << node.degree;\n            singularDart = (node.degree == 0);\n        }\n        out << \")\";\n    }\n    else\n    {\n        if(d.neighborCirculator().center()->type() == CellTypeLine)\n            out << \" (*EDGE* \";\n        else\n            out << \" (*FACE* \";\n        out << d.neighborCirculator().center()->label() << \")\";\n    }\n\n    out << \" to \"; /*****************************************************/\n\n    if(d.neighborCirculator().base()->type() == CellTypeLine)\n    {\n        CellLabel edgeLabel(d.neighborCirculator().base()->label());\n        out << \"edge \" << edgeLabel;\n        if(edgeLabel > d.segmentation()->maxEdgeLabel())\n            out << \", LABEL INVALID!\";\n        else\n        {\n            const GeoMap::EdgeInfo &edge(d.segmentation()->edge(edgeLabel));\n            if(!edge.initialized())\n                out << \", UNINITIALIZED\";\n            out << \", \" << edge.size << \" pixels\";\n        }\n    }\n    else\n    {\n        if(d.neighborCirculator().base()->type() == CellTypeVertex)\n            out << \"*NODE* \";\n        else\n            out << (singularDart ? \"face \" : \"*FACE* \");\n        out << d.neighborCirculator().base()->label();\n    }\n\n    out << \"]\";\n    return out;\n}\n\n} // namespace cellimage\n\n} // namespace vigra\n", "meta": {"hexsha": "d89924f6c94a258fb8212b2b3cf24edd8439e751", "size": 45179, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/cellimage/foureightsegmentation.cxx", "max_stars_repo_name": "hmeine/geomap", "max_stars_repo_head_hexsha": "66463aaad5ff9132b017cd019cc428a910590334", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-11-29T03:13:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T03:11:19.000Z", "max_issues_repo_path": "src/cellimage/foureightsegmentation.cxx", "max_issues_repo_name": "hmeine/geomap", "max_issues_repo_head_hexsha": "66463aaad5ff9132b017cd019cc428a910590334", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-15T14:26:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-27T10:03:15.000Z", "max_forks_repo_path": "src/cellimage/foureightsegmentation.cxx", "max_forks_repo_name": "hmeine/geomap", "max_forks_repo_head_hexsha": "66463aaad5ff9132b017cd019cc428a910590334", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-27T12:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T12:45:03.000Z", "avg_line_length": 34.6464723926, "max_line_length": 138, "alphanum_fraction": 0.5182053609, "num_tokens": 10165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491215859561845, "lm_q2_score": 0.0373268857377728, "lm_q1q2_score": 0.014367572162978131}}
{"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 \"transposition_based_synthesis.hpp\"\n\n#include <limits.h>\n\n#include <iostream>\n#include <iterator>   // for std::distance\n#include <string>\n\n#include <boost/assign/std/set.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/dynamic_bitset.hpp>\n\n#include <core/functor.hpp>\n#include <core/utils/timer.hpp>\n\n#include <reversible/circuit.hpp>\n#include <reversible/gate.hpp>\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/functions/add_circuit.hpp>\n#include <reversible/functions/copy_metadata.hpp>\n#include <reversible/functions/transposition_to_circuit.hpp>\n#include <reversible/io/read_realization.hpp>\n#include <reversible/io/print_circuit.hpp>\n\n#include \"synthesis_utils_p.hpp\"\n\nusing namespace boost::assign;\n\nnamespace cirkit\n{\n\n  bool transposition_based_synthesis( circuit& circ, const binary_truth_table& spec,\n      properties::ptr settings, properties::ptr statistics )\n  {\n    // Settings parsing\n    // Run-time measuring\n    properties_timer t( statistics );\n\n    unsigned bw = spec.num_outputs();\n    circ.set_lines( bw );\n    copy_metadata( spec, circ );\n\n    std::map<unsigned, unsigned> values_map;\n\n    for ( binary_truth_table::const_iterator it = spec.begin(); it != spec.end(); ++it )\n    {\n      binary_truth_table::cube_type in( it->first.first, it->first.second );\n      binary_truth_table::cube_type out( it->second.first, it->second.second );\n\n      values_map.insert( std::make_pair( truth_table_cube_to_number( in ), truth_table_cube_to_number( out ) ) );\n    }\n\n    // Set of cycles\n    std::vector<std::vector<unsigned> > cycles;\n\n    while ( !values_map.empty() )\n    {\n      unsigned start_value = values_map.begin()->first; // first key in values_map\n\n      std::vector<unsigned> cycle;\n      unsigned target = start_value;\n\n      do\n      {\n        cycle += target;\n        unsigned old_target = target;\n        target = values_map[target];\n        values_map.erase( old_target ); // erase this entry\n      } while ( target != start_value );\n\n      cycles += cycle;\n    }\n\n    for ( auto& cycle : cycles )\n    {\n      unsigned max_distance = 0u;\n      unsigned max_index = 0u;\n\n      for ( unsigned i = 0u; i < cycle.size(); ++i )\n      {\n        unsigned first = cycle.at(i);\n        unsigned second = cycle.at( (i + 1u) % cycle.size() );\n\n        unsigned distance = hamming_distance( first, second );\n\n        if ( distance > max_distance )\n        {\n          max_distance = distance;\n          max_index = i;\n        }\n      }\n\n      std::vector<unsigned> tmp;\n      std::copy( cycle.begin() + ( max_index + 1u ), cycle.end(), std::back_inserter( tmp ) );\n      std::copy( cycle.begin(), cycle.begin() + ( max_index + 1u ), std::back_inserter( tmp ) );\n      std::copy( tmp.begin(), tmp.end(), cycle.begin() );\n      std::reverse( cycle.begin(), cycle.end() );\n    }\n\n    // TODO create transpositions function\n    for ( auto& cycle : cycles )\n    {\n      for ( unsigned i = 0u; i < cycle.size() - 1; ++i )\n      {\n        circuit transposition_circ( spec.num_inputs() );\n\n        unsigned first = cycle.at(i);\n        unsigned second = cycle.at( (i + 1) % cycle.size() );\n\n        boost::dynamic_bitset<> first_bits( spec.num_inputs(), first );\n        boost::dynamic_bitset<> second_bits( spec.num_inputs(), second );\n\n        transposition_to_circuit( transposition_circ, first_bits, second_bits );\n\n        append_circuit( circ, transposition_circ);\n      }\n    }\n\n    return true;\n  }\n\n  truth_table_synthesis_func transposition_based_synthesis_func( properties::ptr settings, properties::ptr statistics )\n  {\n    truth_table_synthesis_func f = [&settings, &statistics]( circuit& circ, const binary_truth_table& spec ) {\n      return transposition_based_synthesis( circ, spec, settings, statistics );\n    };\n    f.init( settings, statistics );\n    return f;\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": "4975fd85b21abfa990e32ff04f63700a7daddeb9", "size": 5177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/transposition_based_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/transposition_based_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/transposition_based_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": 31.5670731707, "max_line_length": 119, "alphanum_fraction": 0.674715086, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.034618841827190314, "lm_q1q2_score": 0.014363317516922164}}
{"text": "/***************************************************************************\n * Copyright (C) 2012, Naomasa Matsubayashi\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 * 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 ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT 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 OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n ***************************************************************************/\n\n\n#include <boost/cstdint.hpp>\n#include <vector>\n#include <string>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/lexical_cast.hpp>\n#include <tommath.h>\n\n#include <hermit/mpint.hpp>\n\nnamespace hermit {\n  boost::optional< std::string > is_hex( const std::string &temp ) {\n    using boost::spirit::qi::parse;\n    using boost::spirit::ascii::char_;\n    using boost::spirit::ascii::space;\n    using boost::spirit::ascii::digit;\n    auto iter = temp.begin();\n    std::vector< char > result;\n    if( parse( iter, temp.end(), -( char_('-')|char_('+') ) >> \"0x\" >> +( digit|char_( \"a-fA-F\" ) ), result ) && iter == temp.end() )\n      return std::string( result.begin(), result.end() );\n    return boost::optional< std::string >();\n  }\n  boost::optional< std::string > is_dec( const std::string temp ) {\n    using boost::spirit::qi::parse;\n    using boost::spirit::ascii::char_;\n    using boost::spirit::ascii::space;\n    using boost::spirit::ascii::digit;\n    auto iter = temp.begin();\n    std::vector< char > result;\n    if( parse( iter, temp.end(), -( char_('-')|char_('+') ) >> +digit, result ) && iter == temp.end() ) {\n      return std::string( result.begin(), result.end() );\n    }\n    return boost::optional< std::string >();\n\n  }\n  boost::optional< std::string > is_oct( const std::string temp ) {\n    using boost::spirit::qi::parse;\n    using boost::spirit::ascii::char_;\n    using boost::spirit::ascii::space;\n    using boost::spirit::ascii::digit;\n    auto iter = temp.begin();\n    std::vector< char > result;\n    if( parse( iter, temp.end(), -( char_('-')|char_('+') ) >> '0' >> +char_( \"0-7\" ), result ) && iter == temp.end() )\n      return std::string( result.begin(), result.end() );\n    return boost::optional< std::string >();\n  }\n\n  mpint::mpint( const std::string &value_ ) {\n    MPINT_SAFE_CALL( mp_init( &value ) );\n    mp_zero( &value );\n    boost::optional< std::string > transformed = is_oct( value_ );\n    if( transformed ) {\n      from_string( value_, 8 );\n    }\n    else {\n      transformed = is_hex( value_ );\n      if( transformed ) {\n        from_string( *transformed, 16 );\n      }\n      else {\n        transformed = is_dec( value_ );\n        if( transformed ) {\n          std::string foo = *transformed;\n          from_string( *transformed, 10 );\n        }\n        else\n          throw std::runtime_error( \"Invalid integer format\" );\n      }\n    }\n  }\n  std::string mpint::to_string( int radix ) const {\n    int length;\n    MPINT_SAFE_CALL( mp_radix_size( const_cast< mp_int* >( &value ), radix, &length ) );\n    std::vector< char > temp( length );\n    std::fill( temp.begin(), temp.end(), 0 );\n    MPINT_SAFE_CALL( mp_toradix_n( const_cast< mp_int* >( &value ), &temp.front(), radix, length ) );\n    std::string str( &temp.front() );\n    return str;\n  }\n\n  std::ostream &operator<<( std::ostream &stream, const mpint &mp_value ) {\n    if( stream.flags() & std::ios_base::dec )\n      stream << mp_value.to_string( 10 );\n    else if( stream.flags() & std::ios_base::hex )\n      stream << mp_value.to_string( 16 );\n    else if( stream.flags() & std::ios_base::oct )\n      stream << mp_value.to_string( 8 );\n    else\n      stream << mp_value.to_string( 10 );\n    return stream;\n  }\n\n  std::istream &operator>>( std::istream &stream, mpint &mp_value ) {\n    using boost::spirit::qi::parse;\n    using boost::spirit::ascii::char_;\n    using boost::spirit::ascii::space;\n    using boost::spirit::ascii::digit;\n    if( stream.flags() & std::ios_base::dec ) {\n      while( stream.good() && !stream.eof() ) {\n        std::string temp;\n        stream >> temp;\n        auto iter = temp.begin();\n        std::vector< char > result;\n        if( parse( iter, temp.end(), -( char_('-')|char_('+') ) >> +digit, result ) && iter == temp.end() ) {\n          mp_value.from_string( temp, 10 );\n          break;\n        }\n      }\n    }\n    else if( stream.flags() & std::ios_base::hex ) {\n      while( stream.good() && !stream.eof() ) {\n        std::string temp;\n        stream >> temp;\n        auto iter = temp.begin();\n        std::vector< char > result;\n        if( parse( iter, temp.end(), -( char_('-')|char_('+') ) >> +( digit|char_( \"a-fA-F\" ) ), result ) && iter == temp.end() ) {\n          mp_value.from_string( temp, 16 );\n          break;\n        }\n      }\n    }\n    else if( stream.flags() & std::ios_base::oct ) {\n      while( stream.good() && !stream.eof() ) {\n        std::string temp;\n        stream >> temp;\n        auto iter = temp.begin();\n        std::vector< char > result;\n        if( parse( iter, temp.end(), -( char_('-')|char_('+') ) >> +char_( \"0-7\" ), result ) && iter == temp.end() ) {\n          mp_value.from_string( temp, 8 );\n          break;\n        }\n      }\n    }\n    else {\n      while( stream.good() && !stream.eof() ) {\n        std::string temp;\n        stream >> temp;\n        auto iter = temp.begin();\n        std::vector< char > result;\n        if( parse( iter, temp.end(), -( char_('-')|char_('+') ) >> +digit, result ) && iter == temp.end() ) {\n          mp_value.from_string( temp, 10 );\n          break;\n        }\n      }\n    }\n    return stream;\n  }\n\n  mpint sqrt( const mpint &value ) {\n    mpint temp;\n    MPINT_SAFE_CALL( mp_sqrt( const_cast< mp_int* >( &value.get_raw() ), const_cast< mp_int* >( &temp.get_raw() ) ) );\n    return temp;\n  }\n\n  void swap( mpint &left, mpint &right ) {\n    mp_exch( const_cast< mp_int* >( &left.get_raw() ), const_cast< mp_int* >( &right.get_raw() ) );\n  }\n\n}\n\n", "meta": {"hexsha": "beba329088fe2b8fdbcbd1fa915c6dfa182dbd17", "size": 6925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mpint.cpp", "max_stars_repo_name": "Fadis/hermit", "max_stars_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T05:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-09T05:54:01.000Z", "max_issues_repo_path": "src/mpint.cpp", "max_issues_repo_name": "Fadis/hermit", "max_issues_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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/mpint.cpp", "max_forks_repo_name": "Fadis/hermit", "max_forks_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0320855615, "max_line_length": 133, "alphanum_fraction": 0.5838267148, "num_tokens": 1786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.03461883809217225, "lm_q1q2_score": 0.014363315967267483}}
{"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 <boost/assert.hpp>\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_of.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n\nnamespace boost\n{\n\ntemplate < typename RandomGenerator, typename Graph >\nclass erdos_renyi_iterator\n: public iterator_facade< erdos_renyi_iterator< RandomGenerator, Graph >,\n      std::pair< typename graph_traits< Graph >::vertices_size_type,\n          typename graph_traits< Graph >::vertices_size_type >,\n      std::input_iterator_tag,\n      const std::pair< typename graph_traits< Graph >::vertices_size_type,\n          typename graph_traits< Graph >::vertices_size_type >& >\n{\n    typedef typename graph_traits< Graph >::directed_category directed_category;\n    typedef\n        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(bool,\n        is_undirected\n        = (is_base_of< undirected_tag, directed_category >::value));\n\npublic:\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(n)\n    , edges(edges_size_type(fraction * n * n))\n    , allow_self_loops(allow_self_loops)\n    {\n        if (is_undirected)\n            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), allow_self_loops(allow_self_loops)\n    {\n        next();\n    }\n\n    const std::pair< vertices_size_type, vertices_size_type >&\n    dereference() const\n    {\n        return current;\n    }\n\n    void increment()\n    {\n        --edges;\n        next();\n    }\n\n    bool equal(const erdos_renyi_iterator& other) const\n    {\n        return edges == other.edges;\n    }\n\nprivate:\n    void next()\n    {\n        uniform_int< vertices_size_type > rand_vertex(0, n - 1);\n        current.first = rand_vertex(*gen);\n        do\n        {\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    std::pair< vertices_size_type, vertices_size_type > current;\n};\n\ntemplate < typename RandomGenerator, typename Graph >\nclass sorted_erdos_renyi_iterator\n: public iterator_facade< sorted_erdos_renyi_iterator< RandomGenerator, Graph >,\n      std::pair< typename graph_traits< Graph >::vertices_size_type,\n          typename graph_traits< Graph >::vertices_size_type >,\n      std::input_iterator_tag,\n      const std::pair< typename graph_traits< Graph >::vertices_size_type,\n          typename graph_traits< Graph >::vertices_size_type >& >\n{\n    typedef typename graph_traits< Graph >::directed_category directed_category;\n    typedef\n        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(bool,\n        is_undirected\n        = (is_base_of< undirected_tag, directed_category >::value));\n\npublic:\n    sorted_erdos_renyi_iterator()\n    : gen()\n    , rand_vertex(0.5)\n    , n(0)\n    , allow_self_loops(false)\n    , src((std::numeric_limits< vertices_size_type >::max)())\n    , tgt_index(vertices_size_type(-1))\n    , prob(.5)\n    {\n    }\n\n    // NOTE: The default probability has been changed to be the same as that\n    // used by the geometic distribution. It was previously 0.0, which would\n    // cause an assertion.\n    sorted_erdos_renyi_iterator(RandomGenerator& gen, vertices_size_type n,\n        double prob = 0.5, bool loops = false)\n    : gen()\n    , rand_vertex(1. - prob)\n    , n(n)\n    , allow_self_loops(loops)\n    , src(0)\n    , tgt_index(vertices_size_type(-1))\n    , prob(prob)\n    {\n        this->gen.reset(new uniform_01< RandomGenerator* >(&gen));\n\n        if (prob == 0.0)\n        {\n            src = (std::numeric_limits< vertices_size_type >::max)();\n            return;\n        }\n        next();\n    }\n\n    const std::pair< vertices_size_type, vertices_size_type >&\n    dereference() const\n    {\n        return current;\n    }\n\n    bool equal(const sorted_erdos_renyi_iterator& o) const\n    {\n        return src == o.src && tgt_index == o.tgt_index;\n    }\n\n    void increment() { next(); }\n\nprivate:\n    void next()\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_index) pair.  Because\n        // of the O(|V|^2) cost of that, a geometric distribution is used.  The\n        // geometric distribution tells how many times the\n        // bernoulli_distribution would need to be run until it returns true.\n        // Thus, this distribution can be used to step through the edges\n        // which are actually present.\n        BOOST_ASSERT(src != (std::numeric_limits< vertices_size_type >::max)()\n            && src != n);\n        while (src != n)\n        {\n            vertices_size_type increment = rand_vertex(*gen);\n            size_t tgt_index_limit\n                = (is_undirected ? src + 1 : n) + (allow_self_loops ? 0 : -1);\n            if (tgt_index + increment >= tgt_index_limit)\n            {\n                // Overflowed this source; go to the next one and try again.\n                ++src;\n                // This bias is because the geometric distribution always\n                // returns values >=1, and we want to allow 0 as a valid target.\n                tgt_index = vertices_size_type(-1);\n                continue;\n            }\n            else\n            {\n                tgt_index += increment;\n                current.first = src;\n                current.second = tgt_index\n                    + (!allow_self_loops && !is_undirected && tgt_index >= src\n                            ? 1\n                            : 0);\n                break;\n            }\n        }\n        if (src == n)\n            src = (std::numeric_limits< vertices_size_type >::max)();\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_index;\n    std::pair< vertices_size_type, vertices_size_type > current;\n    double prob;\n};\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_ERDOS_RENYI_GENERATOR_HPP\n", "meta": {"hexsha": "f5e33c9632c2720e9132a6c412db3ba7e5958c8e", "size": 7257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/erdos_renyi_generator.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/erdos_renyi_generator.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/erdos_renyi_generator.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": 32.6891891892, "max_line_length": 80, "alphanum_fraction": 0.6417252308, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.031143833007721743, "lm_q1q2_score": 0.014357829588660474}}
{"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_\n#define _BOOST_UBLAS_VECTOR_\n\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/detail/vector_assign.hpp>\n#include <boost/serialization/collection_size_type.hpp>\n#include <boost/serialization/nvp.hpp>\n\n// Iterators based on ideas of Jeremy Siek\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    // Array based vector class\n    template<class T, class A>\n    class vector:\n        public vector_container<vector<T, A> > {\n\n        typedef vector<T, A> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using vector_container<self_type>::operator ();\n#endif\n        typedef typename A::size_type size_type;\n        typedef typename A::difference_type difference_type;\n        typedef T value_type;\n        typedef typename type_traits<T>::const_reference const_reference;\n        typedef T &reference;\n        typedef T *pointer;\n        typedef const T *const_pointer;\n        typedef A array_type;\n        typedef const vector_reference<const self_type> const_closure_type;\n        typedef vector_reference<self_type> closure_type;\n        typedef self_type vector_temporary_type;\n        typedef dense_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        vector ():\n            vector_container<self_type> (),\n            data_ () {}\n        explicit BOOST_UBLAS_INLINE\n        vector (size_type size):\n            vector_container<self_type> (),\n            data_ (size) {\n        }\n        BOOST_UBLAS_INLINE\n        vector (size_type size, const array_type &data):\n            vector_container<self_type> (),\n            data_ (data) {}\n        BOOST_UBLAS_INLINE\n        vector (size_type size, const value_type &init):\n            vector_container<self_type> (),\n            data_ (size, init) {}\n        BOOST_UBLAS_INLINE\n        vector (const vector &v):\n            vector_container<self_type> (),\n            data_ (v.data_) {}\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector (const vector_expression<AE> &ae):\n            vector_container<self_type> (),\n            data_ (ae ().size ()) {\n            vector_assign<scalar_assign> (*this, ae);\n        }\n\n        // Random Access Container\n        BOOST_UBLAS_INLINE\n        size_type max_size () const {\n            return data_.max_size ();\n        }\n        \n        BOOST_UBLAS_INLINE\n        bool empty () const {\n            return data_.size () == 0;\n        }\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return data_.size ();\n        }\n\n        // Storage accessors\n        BOOST_UBLAS_INLINE\n        const array_type &data () const {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        array_type &data () {\n            return data_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size, bool preserve = true) {\n            if (preserve)\n                data ().resize (size, typename A::value_type ());\n            else\n                data ().resize (size);\n        }\n\n        // Element support\n        BOOST_UBLAS_INLINE\n        pointer find_element (size_type i) {\n            return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i));\n        }\n        BOOST_UBLAS_INLINE\n        const_pointer find_element (size_type i) const {\n            return & (data () [i]);\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            return data () [i];\n        }\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i) {\n            return data () [i];\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const {\n            return (*this) (i);\n        }\n        BOOST_UBLAS_INLINE\n        reference operator [] (size_type i) {\n            return (*this) (i);\n        }\n\n        // Element assignment\n        BOOST_UBLAS_INLINE\n        reference insert_element (size_type i, const_reference t) {\n            return (data () [i] = t);\n        }\n        BOOST_UBLAS_INLINE\n        void erase_element (size_type i) {\n            data () [i] = value_type/*zero*/();\n        }\n        \n        // Zeroing\n        BOOST_UBLAS_INLINE\n        void clear () {\n            std::fill (data ().begin (), data ().end (), value_type/*zero*/());\n        }\n\n        // Assignment\n#ifdef BOOST_UBLAS_MOVE_SEMANTICS\n\n        /*! @note \"pass by value\" the key idea to enable move semantics */\n        BOOST_UBLAS_INLINE\n        vector &operator = (vector v) {\n            assign_temporary(v);\n            return *this;\n        }\n#else\n        BOOST_UBLAS_INLINE\n        vector &operator = (const vector &v) {\n            data () = v.data ();\n            return *this;\n        }\n#endif\n        template<class C>          // Container assignment without temporary\n        BOOST_UBLAS_INLINE\n        vector &operator = (const vector_container<C> &v) {\n            resize (v ().size (), false);\n            assign (v);\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        vector &assign_temporary (vector &v) {\n            swap (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &operator = (const vector_expression<AE> &ae) {\n            self_type temporary (ae);\n            return assign_temporary (temporary);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &assign (const vector_expression<AE> &ae) {\n            vector_assign<scalar_assign> (*this, ae);\n            return *this;\n        }\n\n        // Computed assignment\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &operator += (const vector_expression<AE> &ae) {\n            self_type temporary (*this + ae);\n            return assign_temporary (temporary);\n        }\n        template<class C>          // Container assignment without temporary\n        BOOST_UBLAS_INLINE\n        vector &operator += (const vector_container<C> &v) {\n            plus_assign (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &plus_assign (const vector_expression<AE> &ae) {\n            vector_assign<scalar_plus_assign> (*this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &operator -= (const vector_expression<AE> &ae) {\n            self_type temporary (*this - ae);\n            return assign_temporary (temporary);\n        }\n        template<class C>          // Container assignment without temporary\n        BOOST_UBLAS_INLINE\n        vector &operator -= (const vector_container<C> &v) {\n            minus_assign (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        vector &minus_assign (const vector_expression<AE> &ae) {\n            vector_assign<scalar_minus_assign> (*this, ae);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        vector &operator *= (const AT &at) {\n            vector_assign_scalar<scalar_multiplies_assign> (*this, at);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        vector &operator /= (const AT &at) {\n            vector_assign_scalar<scalar_divides_assign> (*this, at);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (vector &v) {\n            if (this != &v) {\n                data ().swap (v.data ());\n            }\n        }\n        BOOST_UBLAS_INLINE\n        friend void swap (vector &v1, vector &v2) {\n            v1.swap (v2);\n        }\n\n        // Iterator types\n    private:\n        // Use the storage array iterator\n        typedef typename A::const_iterator const_subiterator_type;\n        typedef typename A::iterator subiterator_type;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_iterator<self_type, dense_random_access_iterator_tag> iterator;\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\n#else\n        class const_iterator;\n        class iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator (*this, data ().begin () + i);\n#else\n            return const_iterator (*this, i);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        iterator find (size_type i) {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return iterator (*this, data ().begin () + i);\n#else\n            return iterator (*this, i);\n#endif\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               const_iterator, value_type, difference_type> {\n        public:\n            typedef typename vector::difference_type difference_type;\n            typedef typename vector::value_type value_type;\n            typedef typename vector::const_reference reference;\n            typedef const typename vector::pointer pointer;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &v, const const_subiterator_type &it):\n                container_const_reference<self_type> (v), it_ (it) {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const typename self_type::iterator &it):  // ISSUE vector:: stops VC8 using std::iterator here\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\n                return *it_;\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(it_ + n);\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\n                return it_ - (*this) ().begin ().it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_subiterator_type it_;\n\n            friend class iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find (data_.size ());\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class iterator:\n            public container_reference<vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               iterator, value_type, difference_type> {\n        public:\n            typedef typename vector::difference_type difference_type;\n            typedef typename vector::value_type value_type;\n            typedef typename vector::reference reference;\n            typedef typename vector::pointer pointer;\n\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            iterator ():\n                container_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            iterator (self_type &v, const subiterator_type &it):\n                container_reference<self_type> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_ , bad_index ());\n                return *it_;\n            }\n            BOOST_UBLAS_INLINE\n            reference operator [] (difference_type n) const {\n                return *(it_ + n);\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_ , bad_index ());\n                return it_ - (*this) ().begin ().it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            iterator &operator = (const iterator &it) {\n                container_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            subiterator_type it_;\n\n            friend class const_iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        iterator begin () {\n            return find (0);\n        }\n        BOOST_UBLAS_INLINE\n        iterator end () {\n            return find (data_.size ());\n        }\n\n        // Reverse iterator\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n        typedef reverse_iterator_base<iterator> reverse_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rbegin () {\n            return reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rend () {\n            return reverse_iterator (begin ());\n        }\n\n        // Serialization\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int /* file_version */){\n            ar & serialization::make_nvp(\"data\",data_);\n        }\n\n    private:\n        array_type data_;\n    };\n\n\n    // Bounded vector class\n    template<class T, std::size_t N>\n    class bounded_vector:\n        public vector<T, bounded_array<T, N> > {\n\n        typedef vector<T, bounded_array<T, N> > vector_type;\n    public:\n        typedef typename vector_type::size_type size_type;\n        static const size_type max_size = N;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        bounded_vector ():\n            vector_type (N) {}\n        BOOST_UBLAS_INLINE\n        bounded_vector (size_type size):\n            vector_type (size) {}\n        BOOST_UBLAS_INLINE\n        bounded_vector (const bounded_vector &v):\n            vector_type (v) {}\n        template<class A2>              // Allow vector<T,bounded_array<N> construction\n        BOOST_UBLAS_INLINE\n        bounded_vector (const vector<T, A2> &v):\n            vector_type (v) {}\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        bounded_vector (const vector_expression<AE> &ae):\n            vector_type (ae) {}\n        BOOST_UBLAS_INLINE\n        ~bounded_vector () {}\n\n        // Assignment\n#ifdef BOOST_UBLAS_MOVE_SEMANTICS\n\n        /*! @note \"pass by value\" the key idea to enable move semantics */\n        BOOST_UBLAS_INLINE\n        bounded_vector &operator = (bounded_vector v) {\n            vector_type::operator = (v);\n            return *this;\n        }\n#else\n        BOOST_UBLAS_INLINE\n        bounded_vector &operator = (const bounded_vector &v) {\n            vector_type::operator = (v);\n            return *this;\n        }\n#endif\n        template<class A2>         // Generic vector assignment\n        BOOST_UBLAS_INLINE\n        bounded_vector &operator = (const vector<T, A2> &v) {\n            vector_type::operator = (v);\n            return *this;\n        }\n        template<class C>          // Container assignment without temporary\n        BOOST_UBLAS_INLINE\n        bounded_vector &operator = (const vector_container<C> &v) {\n            vector_type::operator = (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        bounded_vector &operator = (const vector_expression<AE> &ae) {\n            vector_type::operator = (ae);\n            return *this;\n        }\n    };\n\n\n    // Zero vector class\n    template<class T, class ALLOC>\n    class zero_vector:\n        public vector_container<zero_vector<T, ALLOC> > {\n\n        typedef const T *const_pointer;\n        typedef zero_vector<T, ALLOC> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using vector_container<self_type>::operator ();\n#endif\n        typedef typename ALLOC::size_type size_type;\n        typedef typename ALLOC::difference_type difference_type;\n        typedef T value_type;\n        typedef const T &const_reference;\n        typedef T &reference;\n        typedef const vector_reference<const self_type> const_closure_type;\n        typedef vector_reference<self_type> closure_type;\n        typedef sparse_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        zero_vector ():\n            vector_container<self_type> (),\n            size_ (0) {}\n        explicit BOOST_UBLAS_INLINE\n        zero_vector (size_type size):\n            vector_container<self_type> (),\n            size_ (size) {}\n        BOOST_UBLAS_INLINE\n        zero_vector (const zero_vector &v):\n            vector_container<self_type> (),\n            size_ (v.size_) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size, bool /*preserve*/ = true) {\n            size_ = size;\n        }\n\n        // Element support\n        BOOST_UBLAS_INLINE\n        const_pointer find_element (size_type i) const {\n            return & zero_;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type /* i */) const {\n            return zero_;\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const {\n            return (*this) (i);\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        zero_vector &operator = (const zero_vector &v) {\n            size_ = v.size_;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        zero_vector &assign_temporary (zero_vector &v) {\n            swap (v);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (zero_vector &v) {\n            if (this != &v) {\n                std::swap (size_, v.size_);\n            }\n        }\n        BOOST_UBLAS_INLINE\n        friend void swap (zero_vector &v1, zero_vector &v2) {\n            v1.swap (v2);\n        }\n\n        // Iterator types\n    public:\n        class const_iterator;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type /*i*/) const {\n            return const_iterator (*this);\n        }\n\n        class const_iterator:\n            public container_const_reference<zero_vector>,\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef typename zero_vector::difference_type difference_type;\n            typedef typename zero_vector::value_type value_type;\n            typedef typename zero_vector::const_reference reference;\n            typedef typename zero_vector::const_pointer pointer;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &v):\n                container_const_reference<self_type> (v) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                BOOST_UBLAS_CHECK_FALSE (bad_index ());\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                BOOST_UBLAS_CHECK_FALSE (bad_index ());\n                return *this;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                BOOST_UBLAS_CHECK_FALSE (bad_index ());\n                return zero_;   // arbitary return value\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                BOOST_UBLAS_CHECK_FALSE (bad_index ());\n                return 0;   // arbitary return value\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                detail::ignore_unused_variable_warning(it);\n                return true;\n            }\n        };\n\n        typedef const_iterator iterator;\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return const_iterator (*this);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return const_iterator (*this);\n        }\n\n        // Reverse iterator\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n         // Serialization\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int /* file_version */){\n            serialization::collection_size_type s (size_);\n            ar & serialization::make_nvp(\"size\",s);\n            if (Archive::is_loading::value) {\n                size_ = s;\n            }\n        }\n\n    private:\n        size_type size_;\n        typedef const value_type const_value_type;\n        static const_value_type zero_;\n    };\n\n    template<class T, class ALLOC>\n    typename zero_vector<T, ALLOC>::const_value_type zero_vector<T, ALLOC>::zero_ = T(/*zero*/);\n\n\n    // Unit vector class\n    template<class T, class ALLOC>\n    class unit_vector:\n        public vector_container<unit_vector<T, ALLOC> > {\n\n        typedef const T *const_pointer;\n        typedef unit_vector<T, ALLOC> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using vector_container<self_type>::operator ();\n#endif\n        typedef typename ALLOC::size_type size_type;\n        typedef typename ALLOC::difference_type difference_type;\n        typedef T value_type;\n        typedef const T &const_reference;\n        typedef T &reference;\n        typedef const vector_reference<const self_type> const_closure_type;\n        typedef vector_reference<self_type> closure_type;\n        typedef sparse_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        unit_vector ():\n            vector_container<self_type> (),\n            size_ (0), index_ (0) {}\n        BOOST_UBLAS_INLINE\n        explicit unit_vector (size_type size, size_type index = 0):\n            vector_container<self_type> (),\n            size_ (size), index_ (index) {}\n        BOOST_UBLAS_INLINE\n        unit_vector (const unit_vector &v):\n            vector_container<self_type> (),\n            size_ (v.size_), index_ (v.index_) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n        BOOST_UBLAS_INLINE\n        size_type index () const {\n            return index_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size, bool /*preserve*/ = true) {\n            size_ = size;\n        }\n\n        // Element support\n        BOOST_UBLAS_INLINE\n        const_pointer find_element (size_type i) const {\n            if (i == index_)\n                return & one_;\n            else\n                return & zero_;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            if (i == index_)\n                return one_;\n            else\n                return zero_;\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const {\n            return (*this) (i);\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        unit_vector &operator = (const unit_vector &v) {\n            size_ = v.size_;\n            index_ = v.index_;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        unit_vector &assign_temporary (unit_vector &v) {\n            swap (v);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (unit_vector &v) {\n            if (this != &v) {\n                std::swap (size_, v.size_);\n                std::swap (index_, v.index_);\n            }\n        }\n        BOOST_UBLAS_INLINE\n        friend void swap (unit_vector &v1, unit_vector &v2) {\n            v1.swap (v2);\n        }\n\n        // Iterator types\n    private:\n        // Use bool to indicate begin (one_ as value)\n        typedef bool const_subiterator_type;\n    public:\n        class const_iterator;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n            return const_iterator (*this, i <= index_);\n        }\n\n        class const_iterator:\n            public container_const_reference<unit_vector>,\n            public bidirectional_iterator_base<sparse_bidirectional_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef typename unit_vector::difference_type difference_type;\n            typedef typename unit_vector::value_type value_type;\n            typedef typename unit_vector::const_reference reference;\n            typedef typename unit_vector::const_pointer pointer;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<unit_vector> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const unit_vector &v, const const_subiterator_type &it):\n                container_const_reference<unit_vector> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                BOOST_UBLAS_CHECK (it_, bad_index ());\n                it_ = !it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                BOOST_UBLAS_CHECK (!it_, bad_index ());\n                it_ = !it_;\n                return *this;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                BOOST_UBLAS_CHECK (it_, bad_index ());\n                return one_;\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                BOOST_UBLAS_CHECK (it_, bad_index ());\n                return (*this) ().index_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<unit_vector>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n\n        private:\n            const_subiterator_type it_;\n        };\n\n        typedef const_iterator iterator;\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return const_iterator (*this, true);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return const_iterator (*this, false);\n        }\n\n        // Reverse iterator\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n         // Serialization\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int /* file_version */){\n            serialization::collection_size_type s (size_);\n            ar & serialization::make_nvp(\"size\",s);\n            if (Archive::is_loading::value) {\n                size_ = s;\n            }\n            ar & serialization::make_nvp(\"index\", index_);\n        }\n\n    private:\n        size_type size_;\n        size_type index_;\n        typedef const value_type const_value_type;\n        static const_value_type zero_;\n        static const_value_type one_;\n    };\n\n    template<class T, class ALLOC>\n    typename unit_vector<T, ALLOC>::const_value_type unit_vector<T, ALLOC>::zero_ = T(/*zero*/);\n    template<class T, class ALLOC>\n    typename unit_vector<T, ALLOC>::const_value_type unit_vector<T, ALLOC>::one_ (1);  // ISSUE: need 'one'-traits here\n\n\n    // Scalar vector class\n    template<class T, class ALLOC>\n    class scalar_vector:\n        public vector_container<scalar_vector<T, ALLOC> > {\n\n        typedef const T *const_pointer;\n        typedef scalar_vector<T, ALLOC> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using vector_container<self_type>::operator ();\n#endif\n        typedef typename ALLOC::size_type size_type;\n        typedef typename ALLOC::difference_type difference_type;\n        typedef T value_type;\n        typedef const T &const_reference;\n        typedef T &reference;\n        typedef const vector_reference<const self_type> const_closure_type;\n        typedef vector_reference<self_type> closure_type;\n        typedef dense_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        scalar_vector ():\n            vector_container<self_type> (),\n            size_ (0), value_ () {}\n        BOOST_UBLAS_INLINE\n        explicit scalar_vector (size_type size, const value_type &value = value_type(1)):\n            vector_container<self_type> (),\n            size_ (size), value_ (value) {}\n        BOOST_UBLAS_INLINE\n        scalar_vector (const scalar_vector &v):\n            vector_container<self_type> (),\n            size_ (v.size_), value_ (v.value_) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size, bool /*preserve*/ = true) {\n            size_ = size;\n        }\n\n        // Element support\n        BOOST_UBLAS_INLINE\n        const_pointer find_element (size_type /*i*/) const {\n            return & value_;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type /*i*/) const {\n            return value_;\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type /*i*/) const {\n            return value_;\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        scalar_vector &operator = (const scalar_vector &v) {\n            size_ = v.size_;\n            value_ = v.value_;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        scalar_vector &assign_temporary (scalar_vector &v) {\n            swap (v);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (scalar_vector &v) {\n            if (this != &v) {\n                std::swap (size_, v.size_);\n                std::swap (value_, v.value_);\n            }\n        }\n        BOOST_UBLAS_INLINE\n        friend void swap (scalar_vector &v1, scalar_vector &v2) {\n            v1.swap (v2);\n        }\n\n        // Iterator types\n    private:\n        // Use an index\n        typedef size_type const_subiterator_type;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> iterator;\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\n#else\n        class const_iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n            return const_iterator (*this, i);\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<scalar_vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef typename scalar_vector::difference_type difference_type;\n            typedef typename scalar_vector::value_type value_type;\n            typedef typename scalar_vector::const_reference reference;\n            typedef typename scalar_vector::const_pointer pointer;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<scalar_vector> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const scalar_vector &v, const const_subiterator_type &it):\n                container_const_reference<scalar_vector> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\n                return (*this) () (index ());\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());\n                return it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<scalar_vector>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_subiterator_type it_;\n        };\n\n        typedef const_iterator iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find (size_);\n        }\n\n        // Reverse iterator\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n         // Serialization\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int /* file_version */){\n            serialization::collection_size_type s (size_);\n            ar & serialization::make_nvp(\"size\",s);\n            if (Archive::is_loading::value) {\n                size_ = s;\n            }\n            ar & serialization::make_nvp(\"value\", value_);\n        }\n\n    private:\n        size_type size_;\n        value_type value_;\n    };\n\n\n    // Array based vector class\n    template<class T, std::size_t N>\n    class c_vector:\n        public vector_container<c_vector<T, N> > {\n\n        typedef c_vector<T, N> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using vector_container<self_type>::operator ();\n#endif\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef T value_type;\n        typedef const T &const_reference;\n        typedef T &reference;\n        typedef value_type array_type[N];\n        typedef T *pointer;\n        typedef const T *const_pointer;\n        typedef const vector_reference<const self_type> const_closure_type;\n        typedef vector_reference<self_type> closure_type;\n        typedef self_type vector_temporary_type;\n        typedef dense_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        c_vector ():\n            size_ (N) /* , data_ () */ {}\n        explicit BOOST_UBLAS_INLINE\n        c_vector (size_type size):\n            size_ (size) /* , data_ () */ {\n            if (size_ > N)\n                bad_size ().raise ();\n        }\n        BOOST_UBLAS_INLINE\n        c_vector (const c_vector &v):\n            size_ (v.size_) /* , data_ () */ {\n            if (size_ > N)\n                bad_size ().raise ();\n            assign(v);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector (const vector_expression<AE> &ae):\n            size_ (ae ().size ()) /* , data_ () */ {\n            if (size_ > N)\n                bad_size ().raise ();\n            vector_assign<scalar_assign> (*this, ae);\n        }\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n        BOOST_UBLAS_INLINE\n        const_pointer data () const {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        pointer data () {\n            return data_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size, bool preserve = true) {\n            if (size > N)\n                bad_size ().raise ();\n            size_ = size;\n        }\n\n        // Element support\n        BOOST_UBLAS_INLINE\n        pointer find_element (size_type i) {\n            return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i));\n        }\n        BOOST_UBLAS_INLINE\n        const_pointer find_element (size_type i) const {\n            return & data_ [i];\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            BOOST_UBLAS_CHECK (i < size_,  bad_index ());\n            return data_ [i];\n        }\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i) {\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\n            return data_ [i];\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (size_type i) const {\n            return (*this) (i);\n        }\n        BOOST_UBLAS_INLINE\n        reference operator [] (size_type i) {\n            return (*this) (i);\n        }\n\n        // Element assignment\n        BOOST_UBLAS_INLINE\n        reference insert_element (size_type i, const_reference t) {\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\n            return (data_ [i] = t);\n        }\n        BOOST_UBLAS_INLINE\n        void erase_element (size_type i) {\n            BOOST_UBLAS_CHECK (i < size_, bad_index ());\n            data_ [i] = value_type/*zero*/();\n        }\n        \n        // Zeroing\n        BOOST_UBLAS_INLINE\n        void clear () {\n            std::fill (data_, data_ + size_, value_type/*zero*/());\n        }\n\n        // Assignment\n#ifdef BOOST_UBLAS_MOVE_SEMANTICS\n\n        /*! @note \"pass by value\" the key idea to enable move semantics */\n        BOOST_UBLAS_INLINE\n        c_vector &operator = (c_vector v) {\n            assign_temporary(v);\n            return *this;\n        }\n#else\n        BOOST_UBLAS_INLINE\n        c_vector &operator = (const c_vector &v) {\n            size_ = v.size_;\n            std::copy (v.data_, v.data_ + v.size_, data_);\n            return *this;\n        }\n#endif\n        template<class C>          // Container assignment without temporary\n        BOOST_UBLAS_INLINE\n        c_vector &operator = (const vector_container<C> &v) {\n            resize (v ().size (), false);\n            assign (v);\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        c_vector &assign_temporary (c_vector &v) {\n            swap (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &operator = (const vector_expression<AE> &ae) {\n            self_type temporary (ae);\n            return assign_temporary (temporary);\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &assign (const vector_expression<AE> &ae) {\n            vector_assign<scalar_assign> (*this, ae);\n            return *this;\n        }\n\n        // Computed assignment\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &operator += (const vector_expression<AE> &ae) {\n            self_type temporary (*this + ae);\n            return assign_temporary (temporary);\n        }\n        template<class C>          // Container assignment without temporary\n        BOOST_UBLAS_INLINE\n        c_vector &operator += (const vector_container<C> &v) {\n            plus_assign (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &plus_assign (const vector_expression<AE> &ae) {\n            vector_assign<scalar_plus_assign> ( *this, ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &operator -= (const vector_expression<AE> &ae) {\n            self_type temporary (*this - ae);\n            return assign_temporary (temporary);\n        }\n        template<class C>          // Container assignment without temporary\n        BOOST_UBLAS_INLINE\n        c_vector &operator -= (const vector_container<C> &v) {\n            minus_assign (v);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        c_vector &minus_assign (const vector_expression<AE> &ae) {\n            vector_assign<scalar_minus_assign> (*this, ae);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        c_vector &operator *= (const AT &at) {\n            vector_assign_scalar<scalar_multiplies_assign> (*this, at);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        c_vector &operator /= (const AT &at) {\n            vector_assign_scalar<scalar_divides_assign> (*this, at);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (c_vector &v) {\n            if (this != &v) {\n                BOOST_UBLAS_CHECK (size_ == v.size_, bad_size ());\n                std::swap (size_, v.size_);\n                std::swap_ranges (data_, data_ + size_, v.data_);\n            }\n        }\n        BOOST_UBLAS_INLINE\n        friend void swap (c_vector &v1, c_vector &v2) {\n            v1.swap (v2);\n        }\n\n        // Iterator types\n    private:\n        // Use pointers for iterator\n        typedef const_pointer const_subiterator_type;\n        typedef pointer subiterator_type;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_iterator<self_type, dense_random_access_iterator_tag> iterator;\n        typedef indexed_const_iterator<self_type, dense_random_access_iterator_tag> const_iterator;\n#else\n        class const_iterator;\n        class iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator (*this, &data_ [i]);\n#else\n            return const_iterator (*this, i);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        iterator find (size_type i) {\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return iterator (*this, &data_ [i]);\n#else\n            return iterator (*this, i);\n#endif\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<c_vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               const_iterator, value_type> {\n        public:\n            typedef typename c_vector::difference_type difference_type;\n            typedef typename c_vector::value_type value_type;\n            typedef typename c_vector::const_reference reference;\n            typedef typename c_vector::const_pointer pointer;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &v, const const_subiterator_type &it):\n                container_const_reference<self_type> (v), it_ (it) {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const typename self_type::iterator &it):  // ISSUE self_type:: stops VC8 using std::iterator here\n                container_const_reference<self_type> (it ()), it_ (it.it_) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\n                return *it_;\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(it_ + n);\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\n                const self_type &v = (*this) ();\n                return it_ - v.begin ().it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_subiterator_type it_;\n\n            friend class iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find (size_);\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class iterator:\n            public container_reference<c_vector>,\n            public random_access_iterator_base<dense_random_access_iterator_tag,\n                                               iterator, value_type> {\n        public:\n            typedef typename c_vector::difference_type difference_type;\n            typedef typename c_vector::value_type value_type;\n            typedef typename c_vector::reference reference;\n            typedef typename c_vector::pointer pointer;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            iterator ():\n                container_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            iterator (self_type &v, const subiterator_type &it):\n                container_reference<self_type> (v), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            iterator &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            iterator &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            reference operator * () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\n                return *it_;\n            }\n            BOOST_UBLAS_INLINE\n            reference operator [] (difference_type n) const {\n                return *(it_ + n);\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                BOOST_UBLAS_CHECK (it_ >= (*this) ().begin ().it_ && it_ < (*this) ().end ().it_, bad_index ());\n                // EDG won't allow const self_type it doesn't allow friend access to it_\n                self_type &v = (*this) ();\n                return it_ - v.begin ().it_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            iterator &operator = (const iterator &it) {\n                container_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const iterator &it) const {\n                BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            subiterator_type it_;\n\n            friend class const_iterator;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        iterator begin () {\n            return find (0);\n        }\n        BOOST_UBLAS_INLINE\n        iterator end () {\n            return find (size_);\n        }\n\n        // Reverse iterator\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n        typedef reverse_iterator_base<iterator> reverse_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rbegin () {\n            return reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rend () {\n            return reverse_iterator (begin ());\n        }\n\n        // Serialization\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int /* file_version */){\n            serialization::collection_size_type s (size_);\n            ar & serialization::make_nvp(\"size\",s);\n            \n            // copy the value back if loading\n            if (Archive::is_loading::value) {\n              if (s > N) bad_size(\"too large size in bounded_vector::load()\\n\").raise();\n              size_ = s;\n            }\n            // ISSUE: this writes the full array\n            ar & serialization::make_nvp(\"data\",data_);\n        }\n\n    private:\n        size_type size_;\n        array_type data_;\n    };\n\n}}}\n\n#endif\n", "meta": {"hexsha": "29366fb3b69c8436f09f25af52e857c6084084ce", "size": 57528, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/boost/numeric/ublas/vector.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": 55.0, "max_stars_repo_stars_event_min_datetime": "2015-04-11T17:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T17:52:22.000Z", "max_issues_repo_path": "src/lib/boost/numeric/ublas/vector.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": 17.0, "max_issues_repo_issues_event_min_datetime": "2017-11-22T13:31:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T08:30:43.000Z", "max_forks_repo_path": "src/lib/boost/numeric/ublas/vector.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": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-05-21T08:27:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T21:42:36.000Z", "avg_line_length": 32.5016949153, "max_line_length": 125, "alphanum_fraction": 0.5469684328, "num_tokens": 11963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.036220059246094, "lm_q1q2_score": 0.014345612447937599}}
{"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/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/bse.h\"\n#include \"votca/xtp/ecpbasisset.h\"\n#include \"votca/xtp/gwbse.h\"\n#include \"votca/xtp/logger.h\"\n#include \"votca/xtp/orbitals.h\"\n#include \"votca/xtp/vxc_grid.h\"\n#include \"votca/xtp/vxc_potential.h\"\n\nusing boost::format;\nusing namespace boost::filesystem;\nusing std::flush;\nnamespace votca {\nnamespace xtp {\n\nIndex GWBSE::CountCoreLevels() {\n  Index ignored_corelevels = 0;\n  if (!_orbitals.hasECPName()) {\n    ECPBasisSet basis;\n    basis.Load(\"corelevels\");\n    Index coreElectrons = 0;\n    for (const auto& atom : _orbitals.QMAtoms()) {\n      coreElectrons += basis.getElement(atom.getElement()).getNcore();\n    }\n    ignored_corelevels = coreElectrons / 2;\n  }\n  return ignored_corelevels;\n}\n\nvoid GWBSE::Initialize(tools::Property& options) {\n\n  std::string key = Identify();\n\n  // getting level ranges\n  Index rpamax = 0;\n  Index rpamin = 0;  // never changes\n  Index qpmin = 0;\n  Index qpmax = 0;\n  Index bse_vmin = 0;\n  Index bse_cmax = 0;\n\n  Index homo = _orbitals.getHomo();  // indexed from 0\n  Index num_of_levels = _orbitals.getBasisSetSize();\n  Index num_of_occlevels = _orbitals.getNumberOfAlphaElectrons();\n\n  std::string ranges = options.get(key + \".ranges\").as<std::string>();\n\n  // now check validity, and get rpa, qp, and bse level ranges accordingly\n\n  if (ranges == \"factor\") {\n\n    double rpamaxfactor = options.get(key + \".rpamax\").as<double>();\n    rpamax = Index(rpamaxfactor * double(num_of_levels)) -\n             1;  // total number of levels\n\n    double qpminfactor = options.get(key + \".qpmin\").as<double>();\n    qpmin =\n        num_of_occlevels - Index(qpminfactor * double(num_of_occlevels)) - 1;\n\n    double qpmaxfactor = options.get(key + \".qpmax\").as<double>();\n    qpmax =\n        num_of_occlevels + Index(qpmaxfactor * double(num_of_occlevels)) - 1;\n\n    double bseminfactor = options.get(key + \".bsemin\").as<double>();\n    bse_vmin =\n        num_of_occlevels - Index(bseminfactor * double(num_of_occlevels)) - 1;\n\n    double bsemaxfactor = options.get(key + \".bsemax\").as<double>();\n    bse_cmax =\n        num_of_occlevels + Index(bsemaxfactor * double(num_of_occlevels)) - 1;\n\n  } else if (ranges == \"explicit\") {\n    // get explicit numbers\n    rpamax = options.get(key + \".rpamax\").as<Index>();\n    qpmin = options.get(key + \".qpmin\").as<Index>();\n    qpmax = options.get(key + \".qpmax\").as<Index>();\n    bse_vmin = options.get(key + \".bsemin\").as<Index>();\n    bse_cmax = options.get(key + \".bsemax\").as<Index>();\n  } else if (ranges == \"default\") {\n    rpamax = num_of_levels - 1;\n    qpmin = 0;\n    qpmax = 3 * homo + 1;\n    bse_vmin = 0;\n    bse_cmax = 3 * homo + 1;\n  } else if (ranges == \"full\") {\n    rpamax = num_of_levels - 1;\n    qpmin = 0;\n    qpmax = num_of_levels - 1;\n    bse_vmin = 0;\n    bse_cmax = num_of_levels - 1;\n  }\n  std::string ignore_corelevels =\n      options.get(key + \".ignore_corelevels\").as<std::string>();\n\n  if (ignore_corelevels == \"RPA\" || ignore_corelevels == \"GW\" ||\n      ignore_corelevels == \"BSE\") {\n    Index ignored_corelevels = CountCoreLevels();\n    if (ignore_corelevels == \"RPA\") {\n      rpamin = ignored_corelevels;\n    }\n    if (ignore_corelevels == \"GW\" || ignore_corelevels == \"RPA\") {\n      if (qpmin < ignored_corelevels) {\n        qpmin = ignored_corelevels;\n      }\n    }\n    if (ignore_corelevels == \"GW\" || ignore_corelevels == \"RPA\" ||\n        ignore_corelevels == \"BSE\") {\n      if (bse_vmin < ignored_corelevels) {\n        bse_vmin = ignored_corelevels;\n      }\n    }\n\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Ignoring \" << ignored_corelevels\n        << \" core levels for \" << ignore_corelevels << \" and beyond.\" << flush;\n  }\n\n  // check maximum and minimum sizes\n  if (rpamax > num_of_levels) {\n    rpamax = num_of_levels - 1;\n  }\n  if (qpmax > num_of_levels) {\n    qpmax = num_of_levels - 1;\n  }\n  if (bse_cmax > num_of_levels) {\n    bse_cmax = num_of_levels - 1;\n  }\n  if (bse_vmin < 0) {\n    bse_vmin = 0;\n  }\n  if (qpmin < 0) {\n    qpmin = 0;\n  }\n\n  _gwopt.homo = homo;\n  _gwopt.qpmin = qpmin;\n  _gwopt.qpmax = qpmax;\n  _gwopt.rpamin = rpamin;\n  _gwopt.rpamax = rpamax;\n\n  _bseopt.vmin = bse_vmin;\n  _bseopt.cmax = bse_cmax;\n  _bseopt.homo = homo;\n  _bseopt.qpmin = qpmin;\n  _bseopt.qpmax = qpmax;\n  _bseopt.rpamin = rpamin;\n  _bseopt.rpamax = rpamax;\n\n  _orbitals.setRPAindices(rpamin, rpamax);\n  _orbitals.setGWindices(qpmin, qpmax);\n  _orbitals.setBSEindices(bse_vmin, bse_cmax);\n  _orbitals.SetFlagUseHqpOffdiag(_bseopt.use_Hqp_offdiag);\n\n  Index bse_vmax = homo;\n  Index bse_cmin = homo + 1;\n  Index bse_vtotal = bse_vmax - bse_vmin + 1;\n  Index bse_ctotal = bse_cmax - bse_cmin + 1;\n  Index bse_size = bse_vtotal * bse_ctotal;\n\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" RPA level range [\" << rpamin\n                              << \":\" << rpamax << \"]\" << flush;\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" GW  level range [\" << qpmin\n                              << \":\" << qpmax << \"]\" << flush;\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" BSE level range occ[\" << bse_vmin << \":\" << bse_vmax\n      << \"]  virt[\" << bse_cmin << \":\" << bse_cmax << \"]\" << flush;\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" BSE Hamiltonian has size \"\n                              << bse_size << \"x\" << bse_size << flush;\n\n  _gwopt.reset_3c = options.get(key + \".rebuild_threecenter_freq\").as<Index>();\n\n  _bseopt.nmax = options.get(key + \".exctotal\").as<Index>();\n  if (_bseopt.nmax > bse_size || _bseopt.nmax < 0) {\n    _bseopt.nmax = bse_size;\n  }\n\n  // eigensolver options\n  _bseopt.davidson = options.get(key + \".eigensolver.dodavidson\").as<bool>();\n\n  if (_bseopt.davidson) {\n\n    _bseopt.matrixfree =\n        options.get(key + \".eigensolver.domatrixfree\").as<bool>();\n\n    _bseopt.davidson_correction =\n        options.get(key + \".eigensolver.davidson_correction\").as<std::string>();\n\n    _bseopt.davidson_ortho =\n        options.get(key + \".eigensolver.davidson_ortho\").as<std::string>();\n\n    _bseopt.davidson_tolerance =\n        options.get(key + \".eigensolver.davidson_tolerance\").as<std::string>();\n\n    _bseopt.davidson_update =\n        options.get(key + \".eigensolver.davidson_update\").as<std::string>();\n\n    _bseopt.davidson_maxiter =\n        options.get(key + \".eigensolver.davidson_maxiter\").as<Index>();\n\n    // check size\n    if (_bseopt.nmax > bse_size / 4) {\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp()\n          << \" Warning : Too many eigenvalues required for Davidson. Default \"\n             \"to Lapack diagonalization\"\n          << flush;\n      _bseopt.davidson = false;\n    }\n  }\n\n  _bseopt.useTDA = options.get(key + \".useTDA\").as<bool>();\n  _orbitals.setTDAApprox(_bseopt.useTDA);\n  if (!_bseopt.useTDA) {\n    XTP_LOG(Log::error, *_pLog) << \" BSE type: full\" << flush;\n  } else {\n    XTP_LOG(Log::error, *_pLog) << \" BSE type: TDA\" << flush;\n  }\n\n  _bseopt.use_Hqp_offdiag = options.get(key + \".use_Hqp_offdiag\").as<bool>();\n\n  if (!_bseopt.use_Hqp_offdiag) {\n    XTP_LOG(Log::error, *_pLog)\n        << \" BSE without Hqp offdiagonal elements\" << flush;\n  } else {\n    XTP_LOG(Log::error, *_pLog)\n        << \" BSE with Hqp offdiagonal elements\" << flush;\n  }\n\n  _functional = options.get(key + \".vxc.functional\").as<std::string>();\n  _grid = options.get(key + \".vxc.grid\").as<std::string>();\n\n  _auxbasis_name = options.get(key + \".auxbasisset\").as<std::string>();\n  _dftbasis_name = options.get(key + \".basisset\").as<std::string>();\n  if (_dftbasis_name != _orbitals.getDFTbasisName()) {\n    throw std::runtime_error(\n        \"Name of the Basisset from .orb file: \" + _orbitals.getDFTbasisName() +\n        \" and from GWBSE optionfile \" + _dftbasis_name + \" do not agree.\");\n  }\n\n  std::string mode = options.get(key + \".mode\").as<std::string>();\n  if (mode == \"G0W0\") {\n    _gwopt.gw_sc_max_iterations = 1;\n  } else if (mode == \"evGW\") {\n    _gwopt.g_sc_limit = 0.1 * _gwopt.gw_sc_limit;\n    _gwopt.eta = 0.1;\n  }\n  XTP_LOG(Log::error, *_pLog) << \" Running GW as: \" << mode << flush;\n  _gwopt.ScaHFX = _orbitals.getScaHFX();\n\n  _gwopt.shift = options.get(key + \".scissor_shift\").as<double>();\n  _gwopt.g_sc_limit =\n      options.get(key + \".g_sc_limit\").as<double>();  // convergence criteria\n                                                      // for qp iteration\n                                                      // [Hartree]]\n  _gwopt.g_sc_max_iterations =\n      options.get(key + \".g_sc_max_iterations\").as<Index>();  // convergence\n                                                              // criteria for qp\n                                                              // iteration\n                                                              // [Hartree]]\n\n  if (mode == \"evGW\") {\n    _gwopt.gw_sc_max_iterations =\n        options.get(key + \".gw_sc_max_iterations\").as<Index>();\n  }\n\n  _gwopt.gw_sc_limit =\n      options.get(key + \".gw_sc_limit\").as<double>();  // convergence criteria\n                                                       // for shift it\n  XTP_LOG(Log::error, *_pLog)\n      << \" g_sc_limit [Hartree]: \" << _gwopt.g_sc_limit << flush;\n  if (_gwopt.gw_sc_max_iterations > 1) {\n    XTP_LOG(Log::error, *_pLog)\n        << \" gw_sc_limit [Hartree]: \" << _gwopt.gw_sc_limit << flush;\n  }\n  _bseopt.min_print_weight =\n      options.get(key + \".bse_print_weight\").as<double>();\n  // print exciton WF composition weight larger than minimum\n\n  // possible tasks\n  std::string tasks_string = options.get(key + \".tasks\").as<std::string>();\n  boost::algorithm::to_lower(tasks_string);\n  if (tasks_string.find(\"all\") != std::string::npos) {\n    _do_gw = true;\n    _do_bse_singlets = true;\n    _do_bse_triplets = true;\n  }\n  if (tasks_string.find(\"gw\") != std::string::npos) {\n    _do_gw = true;\n  }\n  if (tasks_string.find(\"singlets\") != std::string::npos) {\n    _do_bse_singlets = true;\n  }\n  if (tasks_string.find(\"triplets\") != std::string::npos) {\n    _do_bse_triplets = true;\n  }\n\n  XTP_LOG(Log::error, *_pLog) << \" Tasks: \" << flush;\n  if (_do_gw) {\n    XTP_LOG(Log::error, *_pLog) << \" GW \" << flush;\n  }\n  if (_do_bse_singlets) {\n    XTP_LOG(Log::error, *_pLog) << \" singlets \" << flush;\n  }\n  if (_do_bse_triplets) {\n    XTP_LOG(Log::error, *_pLog) << \" triplets \" << flush;\n  }\n  XTP_LOG(Log::error, *_pLog) << \" Store: \" << flush;\n  if (_do_gw) {\n    XTP_LOG(Log::error, *_pLog) << \" GW \" << flush;\n  }\n\n  if (options.exists(key + \".fragments\")) {\n    std::vector<tools::Property*> prop_region =\n        options.Select(key + \".fragments.fragment\");\n    Index index = 0;\n    for (tools::Property* prop : prop_region) {\n      std::string indices =\n          prop->ifExistsReturnElseThrowRuntimeError<std::string>(\"indices\");\n      _fragments.push_back(QMFragment<BSE_Population>(index, indices));\n      index++;\n    }\n  }\n\n  _gwopt.sigma_integration =\n      options.get(key + \".sigma_integrator\").as<std::string>();\n  XTP_LOG(Log::error, *_pLog)\n      << \" Sigma integration: \" << _gwopt.sigma_integration << flush;\n  _gwopt.eta = options.get(key + \".eta\").as<double>();\n  if (_gwopt.sigma_integration == \"exact\") {\n    XTP_LOG(Log::error, *_pLog)\n        << \" RPA Hamiltonian size: \" << (homo + 1 - rpamin) * (rpamax - homo)\n        << flush;\n  }\n  XTP_LOG(Log::error, *_pLog) << \" eta: \" << _gwopt.eta << flush;\n\n  _gwopt.qp_solver = options.get(key + \".qp_solver\").as<std::string>();\n  _gwopt.qp_grid_steps = options.get(key + \".qp_grid_steps\").as<Index>();\n  _gwopt.qp_grid_spacing = options.get(key + \".qp_grid_spacing\").as<double>();\n  XTP_LOG(Log::error, *_pLog) << \" QP solver: \" << _gwopt.qp_solver << flush;\n  if (_gwopt.qp_solver == \"grid\") {\n    XTP_LOG(Log::error, *_pLog)\n        << \" QP grid steps: \" << _gwopt.qp_grid_steps << flush;\n    XTP_LOG(Log::error, *_pLog)\n        << \" QP grid spacing: \" << _gwopt.qp_grid_spacing << flush;\n  }\n  _gwopt.gw_mixing_order =\n      options.get(key + \".gw_mixing_order\").as<Index>();  // max history in\n                                                          // mixing (0: plain,\n                                                          // 1: linear, >1\n                                                          // Anderson)\n\n  _gwopt.gw_mixing_alpha = options.get(key + \".gw_mixing_alpha\").as<double>();\n\n  if (mode == \"evGW\") {\n    if (_gwopt.gw_mixing_order == 0) {\n      XTP_LOG(Log::error, *_pLog) << \" evGW with plain update \" << std::flush;\n    } else if (_gwopt.gw_mixing_order == 1) {\n      XTP_LOG(Log::error, *_pLog) << \" evGW with linear update using alpha \"\n                                  << _gwopt.gw_mixing_alpha << std::flush;\n    } else {\n      XTP_LOG(Log::error, *_pLog) << \" evGW with Anderson update with history \"\n                                  << _gwopt.gw_mixing_order << \" using alpha \"\n                                  << _gwopt.gw_mixing_alpha << std::flush;\n    }\n  }\n\n  _sigma_plot_states =\n      options.get(key + \".sigma_plot_states\").as<std::string>();\n  _sigma_plot_steps = options.get(key + \".sigma_plot_steps\").as<Index>();\n  _sigma_plot_spacing = options.get(key + \".sigma_plot_spacing\").as<double>();\n  _sigma_plot_filename =\n      options.get(key + \".sigma_plot_filename\").as<std::string>();\n  if (!_sigma_plot_states.empty()) {\n    XTP_LOG(Log::error, *_pLog)\n        << \" Sigma plot states: \" << _sigma_plot_states << flush;\n    XTP_LOG(Log::error, *_pLog)\n        << \" Sigma plot steps: \" << _sigma_plot_steps << flush;\n    XTP_LOG(Log::error, *_pLog)\n        << \" Sigma plot spacing: \" << _sigma_plot_spacing << flush;\n    XTP_LOG(Log::error, *_pLog)\n        << \" Sigma plot filename: \" << _sigma_plot_filename << flush;\n  }\n}\n\nvoid GWBSE::addoutput(tools::Property& summary) {\n\n  const double hrt2ev = tools::conv::hrt2ev;\n  tools::Property& gwbse_summary = summary.add(\"GWBSE\", \"\");\n  if (_do_gw) {\n    gwbse_summary.setAttribute(\"units\", \"eV\");\n    gwbse_summary.setAttribute(\n        \"DFTEnergy\",\n        (format(\"%1$+1.6f \") % (_orbitals.getDFTTotalEnergy() * hrt2ev)).str());\n\n    tools::Property& dft_summary = gwbse_summary.add(\"dft\", \"\");\n    dft_summary.setAttribute(\"HOMO\", _gwopt.homo);\n    dft_summary.setAttribute(\"LUMO\", _gwopt.homo + 1);\n\n    for (Index state = 0; state < _gwopt.qpmax + 1 - _gwopt.qpmin; state++) {\n      tools::Property& level_summary = dft_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + _gwopt.qpmin);\n      level_summary.add(\n          \"dft_energy\",\n          (format(\"%1$+1.6f \") %\n           (_orbitals.MOs().eigenvalues()(state + _gwopt.qpmin) * hrt2ev))\n              .str());\n      level_summary.add(\n          \"gw_energy\",\n          (format(\"%1$+1.6f \") % (_orbitals.QPpertEnergies()(state) * hrt2ev))\n              .str());\n\n      level_summary.add(\"qp_energy\",\n                        (format(\"%1$+1.6f \") %\n                         (_orbitals.QPdiag().eigenvalues()(state) * hrt2ev))\n                            .str());\n    }\n  }\n  if (_do_bse_singlets) {\n    tools::Property& singlet_summary = gwbse_summary.add(\"singlets\", \"\");\n    for (Index state = 0; state < _bseopt.nmax; ++state) {\n      tools::Property& level_summary = singlet_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + 1);\n      level_summary.add(\n          \"omega\", (format(\"%1$+1.6f \") %\n                    (_orbitals.BSESinglets().eigenvalues()(state) * hrt2ev))\n                       .str());\n      if (_orbitals.hasTransitionDipoles()) {\n\n        const Eigen::Vector3d& dipoles = (_orbitals.TransitionDipoles())[state];\n        double f = 2 * dipoles.squaredNorm() *\n                   _orbitals.BSESinglets().eigenvalues()(state) / 3.0;\n\n        level_summary.add(\"f\", (format(\"%1$+1.6f \") % f).str());\n        tools::Property& dipol_summary = level_summary.add(\n            \"Trdipole\", (format(\"%1$+1.4f %2$+1.4f %3$+1.4f\") % dipoles.x() %\n                         dipoles.y() % dipoles.z())\n                            .str());\n        dipol_summary.setAttribute(\"unit\", \"e*bohr\");\n        dipol_summary.setAttribute(\"gauge\", \"length\");\n      }\n    }\n  }\n  if (_do_bse_triplets) {\n    tools::Property& triplet_summary = gwbse_summary.add(\"triplets\", \"\");\n    for (Index state = 0; state < _bseopt.nmax; ++state) {\n      tools::Property& level_summary = triplet_summary.add(\"level\", \"\");\n      level_summary.setAttribute(\"number\", state + 1);\n      level_summary.add(\n          \"omega\", (format(\"%1$+1.6f \") %\n                    (_orbitals.BSETriplets().eigenvalues()(state) * hrt2ev))\n                       .str());\n    }\n  }\n  return;\n}\n\n/*\n *    Many-body Green's fuctions theory implementation\n *\n *  data required from orbitals file\n *  - atomic coordinates\n *  - DFT molecular orbitals (energies and coeffcients)\n *  - DFT exchange-correlation potential matrix in atomic orbitals\n *  - number of electrons, number of levels\n */\n\nEigen::MatrixXd GWBSE::CalculateVXC(const AOBasis& dftbasis) {\n  if (_orbitals.getXCFunctionalName().empty()) {\n    _orbitals.setXCFunctionalName(_functional);\n  } else {\n    if (!(_functional == _orbitals.getXCFunctionalName())) {\n      throw std::runtime_error(\"Functionals from DFT \" +\n                               _orbitals.getXCFunctionalName() + \" GWBSE \" +\n                               _functional + \" differ!\");\n    }\n  }\n\n  double ScaHFX_temp = Vxc_Potential<Vxc_Grid>::getExactExchange(_functional);\n  if (ScaHFX_temp != _orbitals.getScaHFX()) {\n    throw std::runtime_error(\n        (boost::format(\"GWBSE exact exchange a=%s differs from qmpackage \"\n                       \"exact exchange a=%s, probably your functionals are \"\n                       \"inconsistent\") %\n         ScaHFX_temp % _orbitals.getScaHFX())\n            .str());\n  }\n\n  Vxc_Grid grid;\n  grid.GridSetup(_grid, _orbitals.QMAtoms(), dftbasis);\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Setup grid for integration with gridsize: \" << _grid\n      << \" with \" << grid.getGridSize() << \" points, divided into \"\n      << grid.getBoxesSize() << \" boxes\" << flush;\n  Vxc_Potential<Vxc_Grid> vxcpotential(grid);\n  vxcpotential.setXCfunctional(_functional);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Integrating Vxc in VOTCA with functional \"\n      << _functional << flush;\n  Eigen::MatrixXd DMAT = _orbitals.DensityMatrixGroundState();\n  Mat_p_Energy e_vxc_ao = vxcpotential.IntegrateVXC(DMAT);\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Calculated Vxc in VOTCA\" << flush;\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Set hybrid exchange factor: \" << _orbitals.getScaHFX()\n      << flush;\n  Index qptotal = _gwopt.qpmax - _gwopt.qpmin + 1;\n  Index basissize = Index(_orbitals.MOs().eigenvectors().rows());\n  Eigen::MatrixXd mos =\n      _orbitals.MOs().eigenvectors().block(0, _gwopt.qpmin, basissize, qptotal);\n\n  Eigen::MatrixXd vxc = mos.transpose() * e_vxc_ao.matrix() * mos;\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Calculated exchange-correlation expectation values \"\n      << flush;\n\n  return vxc;\n}\n\nbool GWBSE::Evaluate() {\n\n  // set the parallelization\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Using \"\n                              << OPENMP::getMaxThreads() << \" threads\" << flush;\n\n  if (XTP_HAS_MKL_OVERLOAD()) {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Using MKL overload for Eigen \" << flush;\n  } else {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp()\n        << \" Using native Eigen implementation, no BLAS overload \" << flush;\n  }\n\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Molecule Coordinates [A] \" << flush;\n  for (QMAtom& atom : _orbitals.QMAtoms()) {\n    std::string output =\n        (boost::format(\"  %1$s\"\n                       \"   %2$+1.4f %3$+1.4f %4$+1.4f\") %\n         atom.getElement() % (atom.getPos().x() * tools::conv::bohr2ang) %\n         (atom.getPos().y() * tools::conv::bohr2ang) %\n         (atom.getPos().z() * tools::conv::bohr2ang))\n            .str();\n\n    XTP_LOG(Log::error, *_pLog) << output << flush;\n  }\n\n  std::string dft_package = _orbitals.getQMpackage();\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" DFT data was created by \" << dft_package << flush;\n\n  BasisSet dftbs;\n  dftbs.Load(_dftbasis_name);\n\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Loaded DFT Basis Set \" << _dftbasis_name << flush;\n\n  // fill DFT AO basis by going through all atoms\n  AOBasis dftbasis;\n  dftbasis.Fill(dftbs, _orbitals.QMAtoms());\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Filled DFT Basis of size \"\n                              << dftbasis.AOBasisSize() << flush;\n\n  // load auxiliary basis set (element-wise information) from xml file\n  BasisSet auxbs;\n  auxbs.Load(_auxbasis_name);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Loaded Auxbasis Set \" << _auxbasis_name << flush;\n\n  // fill auxiliary AO basis by going through all atoms\n  AOBasis auxbasis;\n  auxbasis.Fill(auxbs, _orbitals.QMAtoms());\n  _orbitals.setAuxbasisName(_auxbasis_name);\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Filled Auxbasis of size \"\n                              << auxbasis.AOBasisSize() << flush;\n\n  if ((_do_bse_singlets || _do_bse_triplets) && _fragments.size() > 0) {\n    for (const auto& frag : _fragments) {\n      XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Fragment \" << frag.getId()\n                                  << \" size:\" << frag.size() << flush;\n    }\n  }\n\n  if (!_do_gw && !_orbitals.hasQPdiag()) {\n    throw std::runtime_error(\n        \"You want no GW calculation but the orb file has no QPcoefficients for \"\n        \"BSE\");\n  }\n  TCMatrix_gwbse Mmn(*_pLog);\n  // rpamin here, because RPA needs till rpamin\n  Index max_3c = std::max(_bseopt.cmax, _gwopt.qpmax);\n  Mmn.Initialize(auxbasis.AOBasisSize(), _gwopt.rpamin, max_3c, _gwopt.rpamin,\n                 _gwopt.rpamax);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp()\n      << \" Calculating Mmn_beta (3-center-repulsion x orbitals)  \" << flush;\n  Mmn.Fill(auxbasis, dftbasis, _orbitals.MOs().eigenvectors());\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Removed \" << Mmn.Removedfunctions()\n      << \" functions from Aux Coulomb matrix to avoid near linear dependencies\"\n      << flush;\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Calculated Mmn_beta (3-center-repulsion x orbitals)  \"\n      << flush;\n\n  Eigen::MatrixXd Hqp;\n  if (_do_gw) {\n    Eigen::MatrixXd vxc = CalculateVXC(dftbasis);\n    GW gw = GW(*_pLog, Mmn, vxc, _orbitals.MOs().eigenvalues());\n    gw.configure(_gwopt);\n    gw.CalculateGWPerturbation();\n\n    if (!_sigma_plot_states.empty()) {\n      gw.PlotSigma(_sigma_plot_filename, _sigma_plot_steps, _sigma_plot_spacing,\n                   _sigma_plot_states);\n    }\n\n    // store perturbative QP energy data in orbitals object (DFT, S_x,S_c, V_xc,\n    // E_qp)\n    _orbitals.QPpertEnergies() = gw.getGWAResults();\n    _orbitals.RPAInputEnergies() = gw.RPAInputEnergies();\n\n    XTP_LOG(Log::info, *_pLog)\n        << TimeStamp() << \" Calculating offdiagonal part of Sigma  \" << flush;\n    gw.CalculateHQP();\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Calculated offdiagonal part of Sigma  \" << flush;\n\n    Hqp = gw.getHQP();\n\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =\n        gw.DiagonalizeQPHamiltonian();\n    if (es.info() == Eigen::ComputationInfo::Success) {\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" Diagonalized QP Hamiltonian  \" << flush;\n    }\n\n    _orbitals.QPdiag().eigenvectors() = es.eigenvectors();\n    _orbitals.QPdiag().eigenvalues() = es.eigenvalues();\n  } else {\n    if (_orbitals.getGWAmax() != _gwopt.qpmax ||\n        _orbitals.getGWAmin() != _gwopt.qpmin ||\n        _orbitals.getRPAmax() != _gwopt.rpamax ||\n        _orbitals.getRPAmin() != _gwopt.rpamin) {\n      throw std::runtime_error(\n          \"The ranges for GW and RPA do not agree with the ranges from the \"\n          \".orb file, rerun your GW calculation\");\n    }\n    const Eigen::MatrixXd& qpcoeff = _orbitals.QPdiag().eigenvectors();\n\n    Hqp = qpcoeff * _orbitals.QPdiag().eigenvalues().asDiagonal() *\n          qpcoeff.transpose();\n  }\n\n  // proceed only if BSE requested\n  if (_do_bse_singlets || _do_bse_triplets) {\n\n    BSE bse = BSE(*_pLog, Mmn);\n    bse.configure(_bseopt, _orbitals.RPAInputEnergies(), Hqp);\n    if (_do_bse_triplets) {\n      bse.Solve_triplets(_orbitals);\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" Solved BSE for triplets \" << flush;\n      bse.Analyze_triplets(_fragments, _orbitals);\n    }\n\n    if (_do_bse_singlets) {\n      bse.Solve_singlets(_orbitals);\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" Solved BSE for singlets \" << flush;\n      bse.Analyze_singlets(_fragments, _orbitals);\n    }\n  }\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" GWBSE calculation finished \" << flush;\n  return true;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "d48ed71f27d149e95401017ed74b3e0aed73a428", "size": 25687, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gwbse/gwbse.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/gwbse/gwbse.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/gwbse/gwbse.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": 36.2810734463, "max_line_length": 80, "alphanum_fraction": 0.602950909, "num_tokens": 7577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.03622005885596484, "lm_q1q2_score": 0.014345611777018813}}
{"text": "//---------------------------------------------------------------------------\n//\n//    FCST: Fuel Cell Simulation Toolbox\n//\n//    Copyright (C) 2009-13 by Energy Systems Design Laboratory, University of Alberta\n//\n//    This software is distributed under the MIT License.\n//    For more information, see the README file in /doc/LICENSE\n//\n//    - Class: newton_w_line_search.cc\n//    - Description: Variant of the Newton-Raphson solver\n//    - Developers: Marc Secanell\n//\n//---------------------------------------------------------------------------\n\n#include <solvers/newton_w_line_search.h>\n#include <deal.II/base/data_out_base.h>\n#include <deal.II/lac/block_vector.h>\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <cmath>\n\nusing namespace FuelCell::ApplicationCore;\n\n//---------------------------------------------------------------------------\nconst Event NewtonLineSearch::bad_derivative = Event::assign(\"Newton\");\n\n//---------------------------------------------------------------------------\nNewtonLineSearch::NewtonLineSearch(ApplicationBase& app)\n    : newtonBase(app)\n{\n  FcstUtilities::log << \"->NewtonLineSearch\";\n}\n\n//---------------------------------------------------------------------------\nvoid\nNewtonLineSearch::declare_parameters(ParameterHandler& param)\n{\n    param.enter_subsection(\"Newton\");\n    {\n        param.declare_entry(\"Line search\",\n                            \"false\", \n                            Patterns::Bool(),\n                            \"A line search is performed at each step.\");\n        param.declare_entry(\"Initial Overrelaxation\", \n                            \"1.\", \n                            Patterns::Double(),\n                            \"This value multiplies the step size in the first iteration, e.g., if the Newton update is 0.25, \"\n                            \"the applied update would be the value in Initial Overrelaxation times 0.25\");\n        param.declare_entry(\"Number of iterations with overrelaxation\",\n                            \"1\",\n                            Patterns::Integer(),\n                            \"Step during which overrelaxation is applied. At each step the Netwon step is multiplied by\"\n                            \"the step times Initial overrelaxation, e.g., step one is 0.1, then step to is 0.2 and so on until 1 (no overrelaxation).\");\n        param.declare_entry(\"Solution variable not allowed to be negative\",\n                            \"0\", \n                            Patterns::Integer(),\n                            \"This enforces a given solution variable to be positive. If it goes negative, step size is reduced.\");        \n    }\n    param.leave_subsection();\n\n    newtonBase::declare_parameters(param);\n}\n\n//---------------------------------------------------------------------------\nvoid\nNewtonLineSearch::_initialize (ParameterHandler& param)\n{\n    param.enter_subsection(\"Newton\");\n    line_search = param.get_bool(\"Line search\");\n    overrelax = param.get_double(\"Initial Overrelaxation\");\n    overrelax_steps = param.get_integer(\"Number of iterations with overrelaxation\");\n    block_to_fix = param.get_integer(\"Solution variable not allowed to be negative\");    \n    param.leave_subsection ();\n}\n\n//---------------------------------------------------------------------------\nvoid\nNewtonLineSearch::initialize (ParameterHandler& param)\n{\n    newtonBase::initialize(param);\n    _initialize(param);\n}\n\n//---------------------------------------------------------------------------\nvoid\nNewtonLineSearch::solve (FuelCell::ApplicationCore::FEVector& u, const FuelCell::ApplicationCore::FEVectors& in_vectors)\n{\n    this->step = 0;\n\n    if (debug>2)\n        FcstUtilities::log << \"u: \" << u.l2_norm() << std::endl;\n\n    FEVector Du;\n    FEVector res;\n\n    res.reinit(u);\n    Du.reinit(u);\n    FEVectors src1;\n    FEVectors src2;\n    src1.add_vector(u, \"Newton iterate\");\n    src1.merge(in_vectors);\n    src2.add_vector(res, \"Newton residual\");\n    src2.merge(src1);\n\n    // fill res with (f(u), v)\n    double residual = app->residual(res, src1);\n    FcstUtilities::log << \"Overall residual at iteration \"<<this->step<<\" = \" << residual << std::endl;\n    double old_residual = residual;\n\n    // Output the solution at the Newton iteration if residual debug is on\n    this->debug_output(u, Du, res);\n\n    //\n    while (control.check(this->step++, residual) == SolverControl::iterate)\n    {\n        // assemble (Df(u), v)\n        if (residual/old_residual >= assemble_threshold)\n            app->notify (bad_derivative);\n\n        Du.reinit(u);\n\n        try\n        {\n            app->solve (Du, src2);\n        }\n        catch (SolverControl::NoConvergence& e)\n        {\n            FcstUtilities::log << \"Inner iteration failed after \"\n            << e.last_step << \" steps with residual \"\n            << e.last_residual << std::endl;\n        }\n\n        ////////////////////////////////////////////////////////////\n        //-- Step size control\n        ////////////////////////////////////////////////////////////\n        if (line_search)\n        {\n            FcstUtilities::log << \"Line Search\" << std::endl;\n            // -- Use a line search to increase robustness\n            double min_residual = residual;\n            double opt_alpha = -0.25;\n            unsigned int num_points = 1;\n            const double* ref = get_data()->scalar(\"Refinement\");\n            if (this->step < 10 &&  *ref < 1)\n                num_points = 20;\n            else if ((this->step >=10 && this->step < 20) &&  *ref < 1)\n                num_points = 10;\n            else\n                num_points = 5;\n\n            // ------------ GEOMETRIC LINE SEARCH\n\n            // Scale: I will look at 2^0, 2^-1, 2^-2, ..., 2^{-num_points}\n            double scale = 2;\n            for (unsigned int alpha = 1; alpha < num_points + 1; ++alpha)\n            {\n                // scale u\n                u.add(-pow(scale,-double(alpha-1)), Du);\n                residual = app->residual(res, src1);\n\n                if ((residual < min_residual) && !(std::isnan(residual)))\n                {\n                    opt_alpha = -pow(scale,-double(alpha-1));\n                    min_residual = residual;\n                }\n                //  FcstUtilities::log<<\"Residual for \"<<pow(scale,-double(alpha-1))<<\" is: \"<<residual<<std::endl;\n                //\n                //  scale back u\n                u.add(pow(scale,-double(alpha-1)), Du);\n            }\n            /*\n            // ------ LINEAR LINE SEARCH (Not tested) -------------\n            for (unsigned int alpha = 1; alpha < num_points; ++alpha)\n            {\n                u.add(-1.0/num_points, *Du);\n                residual = app->residual(*res, u);\n                if (residual < min_residual && !std::isnan(residual))\n                {\n                    opt_alpha = alpha*(1.0/num_points);\n                    min_residual = residual;\n                }\n            }\n            // unscale u\n            u.add(1.0, *Du);\n            */\n            //FcstUtilities::log<<\"Norm of change in solution: \"<<Du->l2_norm()<<std::endl;\n            //FcstUtilities::log<<\"Line search with \"<<num_points<<\" number of points. Optimal alpha: \"<<opt_alpha<<std::endl;\n            FcstUtilities::log << \"Step size = \" << -opt_alpha << std::endl;\n            u.add(opt_alpha, Du);\n            residual = app->residual(res, src1);\n\n        }\n        else // No line search\n        {\n            ////////////////////////////////////////////////////////////\n            // a) First, use overrelaxation during the initial\n            // iterations because Newton's algorithm tends to overshoot:\n            double alpha = 1.0;\n            const double* ref = get_data()->scalar(\"Refinement\");\n\n            if (this->step < overrelax_steps &&  *ref < 1)\n            {\n                alpha = overrelax*this->step;\n                alpha = (alpha <= 1) ? alpha : 1;\n                FcstUtilities::log << \"Step size = \" << alpha << std::endl;\n            }\n\n\n            // Update solution\n            u.add(-alpha,Du);\n\n            // Update residual\n            old_residual = residual;\n            residual = app->residual(res, src1);\n\n            // b) Next, make sure that the chosen step reduces the residual\n            // overwise reduce the residual further:\n            unsigned int step_size = 0;\n            \n            //-- Make sure none of the values are negative:\n            bool negative_values = find_negative_values(u);\n\n            //--\n            while (residual >= old_residual || std::isnan(residual) || negative_values)\n            {                \n                ++step_size;\n\n                u.add(alpha*pow(2.0,-double(step_size)), Du);\n                residual = app->residual(res, src1);\n                \n                //-- Make sure none of the values are negative:\n                negative_values = find_negative_values(u);\n                \n                // -- Some output:                    \n                if (control.log_history())\n                    FcstUtilities::log << \"Step size: 2^{-\" << step_size << \"}\" << std::endl;\n                if (step_size > 15)\n                {\n                    if (control.log_history())\n                        FcstUtilities::log << \"Step size too small!\" << std::endl;\n                    break;\n                }\n            }\n        }\n\n        // Output the global residual and the equation specific residual:\n        for (unsigned int i = 0; i<res.n_blocks(); i++)\n            FcstUtilities::log << \"Residual for equation \"<<i<<\" is: \"<<res.block(i).l2_norm() << std::endl;\n        FcstUtilities::log << \"Overall residual at iteration \"<<this->step<<\" = \" << residual << std::endl;\n\n        // Debug output options:\n        this->debug_output(u, Du, res);\n\n    }\n    \n    // in case of failure: throw exception\n    if (control.last_check() != SolverControl::success)\n        AssertThrow (false, ExcMessage (\"No convergence in Newton solver\"));\n\n}\n\n//---------------------------------------------------------------------------\nbool\nNewtonLineSearch::find_negative_values(const FEVector& u)\n{\n    bool negative_values = false;\n    /*\n    if (block_to_fix >= -1.0e-5)\n    {\n        for(unsigned int i = 0; i < u.block(block_to_fix).size(); ++i)\n            if( u.block(block_to_fix)(i) < -1.0e-6)\n            {\n                negative_values = true;\n                FcstUtilities::log << \"Negative value... u(\"<<i<<\")=\"<<u.block(block_to_fix)(i)<<\"resize...\"<<std::endl;\n                break;                   \n            }\n    }\n    */\n    return negative_values;\n    \n}", "meta": {"hexsha": "1d67469d16852ed6174121b0160c44a5fae22d23", "size": 10639, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/fcst/source/solvers/newton_w_line_search.cc", "max_stars_repo_name": "jeremyjiezhou/Learn-PyTorch", "max_stars_repo_head_hexsha": "7e4404609bacd2ec796f6ca3ea118e8e34ab4a22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-04T20:49:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T19:07:10.000Z", "max_issues_repo_path": "src/fcst/source/solvers/newton_w_line_search.cc", "max_issues_repo_name": "jeremyjiezhou/Learn-PyTorch", "max_issues_repo_head_hexsha": "7e4404609bacd2ec796f6ca3ea118e8e34ab4a22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fcst/source/solvers/newton_w_line_search.cc", "max_forks_repo_name": "jeremyjiezhou/Learn-PyTorch", "max_forks_repo_head_hexsha": "7e4404609bacd2ec796f6ca3ea118e8e34ab4a22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-12-11T22:15:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T13:51:05.000Z", "avg_line_length": 37.1993006993, "max_line_length": 152, "alphanum_fraction": 0.4878278034, "num_tokens": 2231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606815201671963, "lm_q2_score": 0.03622005417441522, "lm_q1q2_score": 0.014345609922806108}}
{"text": "/*!\n  * \\author     Zakwan Zainuddin (zz260) && Gustavo Leon (gl413)\n  * \\file       swp_kmc_simulator.cpp\n  *\n  * \\brief      Implementation for swp_kmc_simulator.h\n  *\n  Project:      sweep (gas-phase chemistry solver).\n  Sourceforge:  http://sourceforge.net/projects/mopssuite\n  Copyright (C) 2010 Zakwan Zainuddin 2020 Gustavo Leon\n\n  File purpose:\n    Simulator for the kMC Model.\n\n  Licence:\n    This file is part of \"sweep\".\n\n    Sweep is free software; you can redistribute it and/or\n    modify it under the terms of the GNU General Public License\n    as published by the Free Software Foundation; either version 2\n    of the License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_cell.h\"\n\n#include \"gpc_mech.h\"\n#include \"gpc_mech_io.h\"\n\n#include \"csv_io.h\"\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <time.h>\n#include <math.h>\n#include <cstdlib>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/filesystem.hpp>\n\n#include \"string_functions.h\"\n#include \"swp_kmc_simulator.h\"\n\n\nusing namespace std;\nusing namespace Sweep;\nusing namespace Sweep::KMC_ARS;\nusing namespace Strings;\n\n// Default names for CSV outputs if not specified\nstd::string default_timer_csv = \"KMC_Model/PAH_loop_timer.csv\";\nstd::string default_rxncount_csv = \"KMC_Model/PAH_reaction_count.csv\";\nstd::string default_pahlist_csv = \"KMC_Model/PAH_CH_site_list.csv\";\nstd::string default_pahlist_after_csv = \"KMC_Model/PAH_CH_site_list_after.csv\";\nstd::string default_rates_csv = \"KMC_Model/PAH_jump_process_rates.csv\";\nstd::string default_testrates_csv = \"KMC_Model/PAH_jump_process_testrates.csv\";\n\n// Vector of all site types\nstatic std::vector<kmcSiteType> allSiteType = vectSiteType();\n\n//! Default Constructor\nKMCSimulator::KMCSimulator():\n     m_gasprof(), m_mech(), m_gas(), m_simPAH(), m_t(), m_fromfile(false), m_kmcmech(),m_simPAHp()\n{\n}\n\n//! Constructor from chemkin and gasphase files\nKMCSimulator::KMCSimulator(const std::string gasphase, const std::string chemfile, const std::string thermfile)\n{\n    m_t=0;\n    m_gasprof = new Sweep::GasProfile();\n    LoadGasProfiles(gasphase, chemfile, thermfile);\n    m_fromfile = true;\n}\n//! Constructor from a GasProfile object\nKMCSimulator::KMCSimulator(Sweep::GasProfile& gprofile):\n\tm_gasprof(), m_mech(), m_gas(), m_simPAH(), m_t(0.0), m_fromfile(false), m_kmcmech(), m_simPAHp()\n{\n    std::cout << this << endl;\n    m_gasprof = &gprofile;\n    m_gas = new KMCGasPoint(gprofile, *gprofile[0].Gas.Species());\n    m_mech = NULL;\n}\n\n//! Copy Constructor\nKMCSimulator::KMCSimulator(KMCSimulator& s):\n\t\tm_gasprof(), m_mech(), m_gas(), m_simPAH(), m_t(s.m_t), m_fromfile(false),\n\t\tm_kmcmech(s.m_kmcmech),m_simPAHp()\n\n{\n    m_gasprof = s.m_gasprof;\n    m_gas = new KMCGasPoint(*s.m_gas);\n    //m_simPAH = new PAHStructure(*(s.m_simPAH));\n    m_simPAHp = PAHProcess(*m_simPAH);\n}\n\n//! Default Destructor\nKMCSimulator::~KMCSimulator() {\n    //delete m_simPAH;\n    if(m_fromfile) {\n        delete m_gasprof;\n        delete m_mech;\n    }\n    delete m_gas;\n}\n\n//! Set PAH to be simulated\nvoid KMCSimulator::targetPAH(PAHStructure& pah) {\n    m_simPAH = &pah;\n    m_simPAHp = PAHProcess(*m_simPAH);\n\tsetDebugPAH(save_pah_detail);\n}\n\n/*!\n * @param[in,out]    pah             PAH structure KMC-ARS jump process will be performed on.\n * @param[in]        tsart           The latest time the PAH was updated.\n * @param[in]        dt              The time over which the PAH is to be updated.\n * @param[in]        waitingSteps    Adjusts the size of dt. The larger it is the smaller dt is. Results were found to be insensitive to waitingSteps therefore it was hardcoded as 1 (tests by Dongping, dc516@cam.ac.uk).\n * @param[in]        rng             Random number generator.\n * @param[in]        r_factor        Model parameter: Growth factor, a multiplier that is applied to the growth rate of PAHs within primary particles when the number of PAHs exceeds a critical number of PAHs.\n * @param[in]        PAH_ID          \"Unique\" identification number attached to this PAH.\n */\ndouble KMCSimulator::updatePAH(PAHStructure* pah, \n                            const double tstart, \n                            const double dt,  \n                            const int waitingSteps,  \n\t\t\t\t\t\t\tconst int maxloops,\n                            rng_type &rng,\n                            double r_factor,\n                            int PAH_ID,\n\t\t\t\t\t\t\tbool calcrates,\n\t\t\t\t\t\t\tdouble ratefactor) {\n\t// wjm34: remove call to initReaction count to save time in updating.\n\tm_t = tstart;\n\tdouble t_max = m_t + dt;\n    targetPAH(*pah);\n\tif (m_rxn_count.size() == 0) {\n\t\t//initCSVIO();\n\t\tinitReactionCount();\n\t\treadTrackedPAH();\n\t};\n\t\n    // Checks if information will be saved for this PAH.\n    auto finder = std::find(std::begin(m_tracked_pahs), std::end(m_tracked_pahs), PAH_ID);\n    bool tracked_csv = false;\n    auto fix_finder = std::find(std::begin(m_tracked_pahs_fixed), std::end(m_tracked_pahs_fixed), PAH_ID);\n    if (fix_finder != m_tracked_pahs_fixed.end()) {\n        opentrackedPAHCSV(PAH_ID); //Opens the csv file for tracked PAH\n        tracked_csv = true;\n    }\n    \n    /*if(m_simPAHp.checkCoordinates())\n        cout<<\"Coordinates of structure OK. Commencing updatePAH..\\n\";\n    else {\n        cout<<\"Coordinates of structure did not pass test. Aborting..\\n\";\n        std::ostringstream msg;\n        msg << \"ERROR: Trying updatePAH on a structure which did not pass PAHProcess::checkCoordinates.\"\n            << \" (Sweep::KMC_ARS::KMCSimulator::updatePAH)\";\n        throw std::runtime_error(msg.str());\n        assert(false);\n    }\n    if(m_simPAHp.checkSiteContinuity())\n        cout<<\"Site continuity of structure OK. Commencing updatePAH..\\n\";\n    else {\n        cout<<\"Structure has uncontinuous site. Aborting..\\n\";\n        std::ostringstream msg;\n        msg << \"ERROR: Trying updatePAH on a structure which did not pass PAHProcess::checkSiteContinuity.\"\n            << \" (Sweep::KMC_ARS::KMCSimulator::updatePAH)\";\n        throw std::runtime_error(msg.str());\n        assert(false);\n    }*/\n    double t_next = m_t;\n    double t_step_max = dt/waitingSteps;\n    //double oldtnext;\n    int loopcount=0;\n\tbool proceed = true;\n\tcalcrates = true;\n    //Local variable to control the number of migration steps between non-migration steps.\n    int migr_steps = 0;\n\n    //double time_migration = 0.0;\n    //clock_t timerStart, timerEnd;\n\t\n    while (m_t < t_max && proceed) {\n        //this->m_simPAHp.printStruct();// print out structure of this pah on the screen\n        //m_simGas.interpolateProfiles(m_t, true, r_factor);\n        loopcount++;\n\n        // Calculate rates of each jump process\n\t\tif (calcrates){\n\t\t\t//m_gas->Interpolate(m_t, r_factor);\n\t\t\t//m_kmcmech.calculateRates(*m_gas, m_simPAHp, m_t);\n\t\t\t//rates = m_kmcmech.Rates();\n\t\t\t//writeRatesCSV(m_t, rates);\n\t\t\t//writeCHSiteCountCSV();\n\t\t\t//writetimestep(m_t);\n\t\t\t//writeRxnCountCSV();\n\t\t}\n\n        // Calculate time step, update time\n\t\t//Interpolate gas phase species and temperature.\n\n\t\tm_gas->Interpolate(m_t, r_factor);\n\t\t\n\t\t//Calculate jump process rates\n\t\tm_kmcmech.calculateRates(*m_gas, m_simPAHp, m_t);\n        typedef boost::exponential_distribution<double> exponential_distrib;\n\t\t\n\t\t//Generate exponentially distributed waiting time\n        exponential_distrib waitingTimeDistrib(m_kmcmech.TotalRate());\n        boost::variate_generator<rng_type &, exponential_distrib> waitingTimeGenerator(rng, waitingTimeDistrib);\n        double t_step = waitingTimeGenerator();\n        t_next = m_t+t_step;\n\n        //Artificially fix that a PAH with 4 or less sites has rate 0\n\t\tsize_t site_size = m_simPAHp.SiteListSize();\n\t\tif ( (int)site_size <=6 && std::get<0>(m_simPAHp.getRingsCount()) > 1) {\n            std::cout << \"PAH \" << PAH_ID << \" reached to \" << site_size << \" sites. Freezing and saving structure.\" << std::endl;\n            addTrackedPAH(PAH_ID);\n            //m_simPAHp.printSites();\n            std::string xyzname = (\"KMC_DEBUG/\");\n            xyzname.append(std::to_string(PAH_ID));\n            xyzname.append(\"/\");\n            xyzname.append(std::to_string(m_t*1000.0));\n            xyzname.append(\"_frozen\");\n            savePAH(PAH_ID, xyzname); \n            t_next = t_max;\n        }\n\t\t\n\t\t//If time + waiting time < time at the next grid element then perform process.\n        if(t_next < t_max && t_step < t_step_max) {\n\n            // Choose jump according to rates\n            ChosenProcess jp_perf = m_kmcmech.chooseReaction(rng);\n\t\t\t\n\t\t\t/*if (save_pah_detail){\n\t\t\t\t//Add PAH to tracked list on the fly. These are the conditions in which the user wants to save files. They need to be adjusted manually.\n\t\t\t\tint R5R7 = (m_simPAHp.getR5EmbeddedCount() + m_simPAHp.getR7EmbeddedCount());\n\t\t\t\tif (R5R7 >= 2) addTrackedPAH(PAH_ID); \t\n\t\t\t\t//if (R5R7 >= 1 || std::get<0>(m_simPAHp.getRingsCount()) >= 7) addTrackedPAH(PAH_ID); \t\n\t\t\t\telse if (jp_perf.first->getID() == 23 || jp_perf.first->getID() == 35 || jp_perf.first->getID() == 36 || jp_perf.first->getID() == 38 \n\t\t\t\t\t\t|| jp_perf.first->getID() == 41 || (jp_perf.first->getID() >= 44 && jp_perf.first->getID() < 54) || m_simPAHp.numberOfMethyl() >= 3) addTrackedPAH(PAH_ID); \n            }*/\n            //Save information for a single PAH\n            if (finder != m_tracked_pahs.end() && !m_migrate){\n                std::string xyzname = (\"KMC_DEBUG/\");\n                xyzname.append(std::to_string(PAH_ID));\n                xyzname.append(\"/\");\n                xyzname.append(std::to_string(m_t*1000000.0));\n                xyzname.append(\"_A\");\n                savePAH(PAH_ID, xyzname); \n                cout << \"PAH ID = \" << PAH_ID << \", Jump process -> \" << jp_perf.first->getName()<< \", Time = \" << m_t<<\"\\n\";\n                //m_simPAHp.printSites();\n                //printRates(m_t, m_kmcmech.Rates());\n                if (tracked_csv) writetrackedPAHCSV();\n            }\n\n            m_rxn_count[jp_perf.second]++;\n            //Commented out and moved to the end of the simulation loop.\n\t\t\t/*writeRxnCountCSV();\n\t\t\twriteCHSiteCountCSV(PAH_ID);\n\t\t\t//writeTimerCSV();\n\t\t\trates = m_kmcmech.Rates();\n\t\t\twriteRatesCSV(m_t, rates);*/\n\n            //Saves the site list to file. Used to verify that migration by both methods gives same results\n            /*std::vector<std::string> temp = m_simPAHp.SiteVectorString();\n            temp.push_back(std::to_string(PAH_ID));\n            std::ostringstream streamObj;\n            streamObj << std::setprecision(7);\n            streamObj << m_t;\n            std::string streamObj_string = streamObj.str();\n            temp.push_back(streamObj_string);\n            m_pah_sitelist_csv.Write(temp);*/\n            // Update data structure -- Perform jump process\n\t\t\t//printRates(m_t, m_kmcmech.Rates());\n            //cout << m_t << std::endl;\n            if (jp_perf.first->getID() == 24 || jp_perf.first->getID() == 34 || jp_perf.first->getID() == 66 ) {\n                //timerStart = clock();\n                //Migration jump processes. Set flag m_migrate to true.\n                if (!m_migrate) {\n                    m_simPAHp.startMigrationProcess();\n                    migr_steps = 0;\n                    m_migrate = true; \n                }\n                //savePAH(PAH_ID,\"KMC_DEBUG/BEFOREJPPERFORM\");\n                m_simPAHp.performProcess(*jp_perf.first, rng, PAH_ID);\n                migr_steps++;\n                //savePAH(PAH_ID,\"KMC_DEBUG/AFTERJPPERFORM\");\n            }\n            else {\n                if (m_migrate){\n                    //First update the multiple migration transformation\n                    //savePAH(PAH_ID,\"KMC_DEBUG/BEFOREMIGRATION\");\n                    m_simPAHp.performMigrationProcess();\n                    //savePAH(PAH_ID,\"KMC_DEBUG/AFTERMIGRATION\");\n                    m_migrate = false;\n                    //timerEnd = clock();\n                    //time_migration += (timerEnd - timerStart) / double(CLOCKS_PER_SEC);\n                }\n                if (finder != m_tracked_pahs.end()) std::cout << \"PAH ID = \" << PAH_ID << \", Jump process -> \" << jp_perf.first->getName()<< \", Time = \" << m_t<<\" Migr. steps = \"<<migr_steps<<std::endl;\n                migr_steps = 0;\n                if (finder != m_tracked_pahs.end() && !m_migrate){\n                    std::string xyzname = (\"KMC_DEBUG/\");\n                    xyzname.append(std::to_string(PAH_ID));\n                    xyzname.append(\"/\");\n                    xyzname.append(std::to_string(m_t*1000000.0));\n                    xyzname.append(\"_B\");\n                    savePAH(PAH_ID, xyzname); \n                    //cout << \"PAH ID = \" << PAH_ID << \", Jump process -> \" << jp_perf.first->getName()<< \", Time = \" << m_t<<\"\\n\";\n                }\n                m_simPAHp.performProcess(*jp_perf.first, rng, PAH_ID);\n                if (finder != m_tracked_pahs.end() && !m_migrate){\n                    std::string xyzname = (\"KMC_DEBUG/\");\n                    xyzname.append(std::to_string(PAH_ID));\n                    xyzname.append(\"/\");\n                    xyzname.append(std::to_string(m_t*1000000.0));\n                    xyzname.append(\"_C\");\n                    savePAH(PAH_ID, xyzname); \n                }\n            }\n\t\t\t//writeCHSiteCountCSV_after(PAH_ID);\n\n\t\t\t//Hard cut-off for PAHs. Cannot have less than one ring. Set number of carbons to 1 so that it will be invalidated\n\t\t\t//Set t_next to t_max so the updatePAH routine will be exited\n\t\t\t//if (pah->numofRings() < 4){\n\t\t\t//\tproceed = false;\n\t\t\t//\t//t_next = t_max;\n\t\t\t//}\n\t\t\t\n            //oldtnext = t_next;\n            //t_next = t_max;\n            if (loopcount == maxloops) proceed = false; //If maxloops is set to 0, this condition will never be true\n            m_t = t_next;\n        }else{\n            if (m_migrate){\n                //savePAH(PAH_ID,\"KMC_DEBUG/BEFOREMIGRATION\");\n                m_simPAHp.performMigrationProcess();\n                //savePAH(PAH_ID,\"KMC_DEBUG/AFTERMIGRATION\");\n                m_migrate = false;\n            }\n            t_next = t_max;\n            m_t = t_next;\n        }\n    }\n\n    //writeRxnCountCSV();\n    writeCHSiteCountCSV(PAH_ID);\n    //std::cout << \"Wall time used for PAH_ID \" << PAH_ID << \" = \" << time_migration << \"s.\" << std::endl;\n    \n    if (tracked_csv) closetrackedPAHCSV();\n    if (finder != m_tracked_pahs.end()){\n        std::string xyzname = (\"KMC_DEBUG/\");\n        xyzname.append(std::to_string(PAH_ID));\n        xyzname.append(\"/\");\n        xyzname.append(std::to_string(m_t*1000000.0));\n        xyzname.append(\"_D\");\n        savePAH(PAH_ID, xyzname); \n    }\n\treturn m_t;\n}\n\n//! Outputs rates into a csv file (assuming all site counts as 1)\nvoid KMCSimulator::TestRates(const double tstart, const double tstop, const int intervals) {\n    // set name of output file\n    //setCSVratesName(filename);\n    //std::cout << \"Saving Rates...\\n\";\n    rvector rates(m_kmcmech.JPList().size(), 0);\n    double dt = (tstop-tstart)/intervals;\n    m_simPAHp.m_rates_save = true;\n    // for each interval\n    for(double t=tstart+dt; t<= tstop; t+=dt) {\n        // interpolate & calculate rates\n        m_gas->Interpolate(t);\n        m_kmcmech.calculateRates(*m_gas, m_simPAHp, t);\n        rates = m_kmcmech.Rates();\n        writeTestRatesCSV(t, rates);\n    }\n    m_simPAHp.m_rates_save = false;\n    //std::cout<<\"Finished calculating rates for kMC mechanism. Results are saved in \"\n    //    <<m_testrates_name<<\"\\n\\n\";\n}\n\n//! Obtains rates of PAH reactions with the current structure\nrvector KMCSimulator::CurrentRates(PAHStructure* pah, double t) {\n    m_simPAHp.setPAH(*pah);\n    rvector rates(m_kmcmech.JPList().size(), 0);\n    m_gas->Interpolate(t);\n    m_kmcmech.calculateRates(*m_gas, m_simPAHp, t);\n    rates = m_kmcmech.Rates();\n    return rates;\n}\n//! Outputs gas concentrations into a csv file\nvoid KMCSimulator::TestConc(const double& t_start, const double& t_stop, const int intervals, const std::string& filename) {\n    CSV_IO csvio(filename, true);\n    double dt = (t_stop-t_start)/intervals;\n    std::vector<string> species(m_gas->m_total-2);\n    rvector temp(m_gas->m_total-2); //exclude T & P\n    for(size_t i=1; i<(temp.size()); i++) {\n        species[i] = m_gas->SpNames()[i+1];\n    }\n    csvio.Write(species);\n    for(double t=t_start; t<=t_stop; t+=dt) {\n        temp[0] = t;\n        m_gas->Interpolate(t);\n        for(size_t i=1; i<(temp.size()-1); i++) {\n            temp[i] = (*m_gas)[i+1];\n        }\n        csvio.Write(temp);\n        \n    }\n}\n\n/*void KMCSimulator::testSimulation(PAHStructure& pah, const unsigned long seed, int totalruns) {\n    for(int run=1; run<=totalruns; run++) {\n        clock_t timerStart = clock();\n        int total_interval = 10;\n        double maxtime = 0.0222029;\n        double step = maxtime/total_interval;\n        double tnow=0;\n        // loop counts\n        int count = 0;\n        // Start timer\n        initReactionCount();\n        m_simPAHp.initialise(PYRENE);\n        while(tnow<maxtime) {\n            //tnow = i*step;\n            tnow = updatePAH(pah, tnow, step, m_simGas, 10, count);\n        }\n        //updatePAH(pah, tnow, maxtime, m_simGas);\n        m_simPAHp.saveDOT(std::string(\"DOT files/Test_update_PAH.dot\"));\n        // calculate time elapsed\n        clock_t timerStop = clock();\n        double timerElapsed = double(timerStop-timerStart)/CLOCKS_PER_SEC;\n        writeTimerCSV(count, timerElapsed);\n        writeRxnCountCSV(m_rxn_count);\n        writeCHSiteCountCSV();\n        cout<<\"\\nSimulator ran for run \"<<run<<\" looping \"<<count<<\" number of times...\\n\";\n        cout<<\"Ran for \"<<timerElapsed<<\" seconds.\\n\\n\";\n    }\n    \n    m_timer_csv.Close();\n    m_rxn_csv.Close();\n    m_pah_csv.Close();\n}*/\n\n//! Set csv filename for gas profiles\nvoid KMCSimulator::setCSVinputName(const std::string& filename) {\n    m_csv_in = filename;\n}\n\n//! Set output DOT file name \"filename\"_runs_finalloopnum.dot\nvoid KMCSimulator::setDOToutputName(const std::string& filename) {\n    m_dot_out = filename;\n}\n//! Set output CSV file name to keep track of timer counts\nvoid KMCSimulator::setCSVtimerName(const std::string& filename) {\n    m_timer_name = filename;\n}\n//! Set output CSV file name to keep track of reaction counts\nvoid KMCSimulator::setCSVreactioncountName(const std::string& filename) {\n    m_rxncount_name = filename;\n}\n//! Set output CSV file name to keep track of CH and site counts\nvoid KMCSimulator::setCSVpahlistName(const std::string &filename) {\n    m_pahlist_name = filename;\n}\n//! Set output CSV file name to keep track of CH and site counts after jump process\nvoid KMCSimulator::setCSVpahlist_afterName(const std::string &filename) {\n    m_pahlist_after_name = filename;\n}\n\n//! Set output CSV file name to keep track of time step//##\nvoid KMCSimulator::setCSVtimestep(const std::string &filename) {\n    m_timestep_name = filename;\n}\n//! Set output CSV file name to keep track of jump process rates\nvoid KMCSimulator::setCSVratesName(const std::string &filename) {\n    m_rates_name = filename;\n}\n//! Set output CSV file name to keep track of jump process rates assuming 1 of each site\nvoid KMCSimulator::setCSVtestratesName(const std::string &filename) {\n    m_testrates_name = filename;\n}\n//! Writes data for timeCount.csv\nvoid KMCSimulator::writeTimerCSV(const int& loop, const double& elapsedTime) {\n    vector<double> temp;\n    // writes: | Total Loop | Total time elapsed |\n    temp.push_back((double)loop);\n    temp.push_back(elapsedTime);\n    m_timer_csv.Write(temp);\n}\nvoid KMCSimulator::writetimestep(const std::vector<double>& timestep){\n    m_timestep_csv.Write(timestep);\n}\n//! Writes data for reaction_count.csv\nvoid KMCSimulator::writeRxnCountCSV() {\n    // change int vector to float\n    std::vector<std::string> temp;\n\t\n    for(size_t i=0; i<m_rxn_count.size(); i++)\n        temp.push_back(Strings::cstr(m_rxn_count[i]));\n    m_rxn_csv.Write(temp);\n    m_rxn_csv.flush_file();\n}\n//! Writes data for CH_site_list.csv\nvoid KMCSimulator::writeCHSiteCountCSV(int ID) {\n    std::vector<int> temp;\n\t// write PAH_ID number\n\ttemp.push_back(ID);\n    // get CH count\n    intpair CH = m_simPAHp.getCHCount();\n    temp.push_back(CH.first);\n    temp.push_back(CH.second);\n    // get counts for all site types\n    for(int i=0; i<(int)allSiteType.size(); i++) {\n        int scount = m_simPAHp.getSiteCount(allSiteType[i]);\n        temp.push_back(scount);\n    }\n\tstd::tuple <int, int, int> rings = m_simPAHp.getRingsCount();\n\ttemp.push_back(std::get<0>(rings));\n\ttemp.push_back((std::get<1>(rings) - m_simPAHp.getR5EmbeddedCount()));\n\ttemp.push_back(m_simPAHp.getR5EmbeddedCount());\n\ttemp.push_back((std::get<2>(rings) - m_simPAHp.getR7EmbeddedCount()));\n\ttemp.push_back(m_simPAHp.getR7EmbeddedCount());\n    m_pah_csv.Write(temp);\n}\n//! Writes data for CH_site_list.csv\nvoid KMCSimulator::writeCHSiteCountCSV_after(int ID) {\n    std::vector<int> temp;\n\t// write PAH_ID number\n\ttemp.push_back(ID);\n    // get CH count\n    intpair CH = m_simPAHp.getCHCount();\n    temp.push_back(CH.first);\n    temp.push_back(CH.second);\n    // get counts for all site types\n    for(int i=0; i<(int)allSiteType.size(); i++) {\n        int scount = m_simPAHp.getSiteCount(allSiteType[i]);\n        temp.push_back(scount);\n    }\n\tstd::tuple <int, int, int> rings = m_simPAHp.getRingsCount();\n\ttemp.push_back(std::get<0>(rings));\n\ttemp.push_back((std::get<1>(rings) - m_simPAHp.getR5EmbeddedCount()));\n\ttemp.push_back(m_simPAHp.getR5EmbeddedCount());\n\ttemp.push_back((std::get<2>(rings) - m_simPAHp.getR7EmbeddedCount()));\n\ttemp.push_back(m_simPAHp.getR7EmbeddedCount());\n    m_pah_after_csv.Write(temp);\n}\n//! Writes data for rates count (csv)\nvoid KMCSimulator::writeRatesCSV(double& time, rvector& v_rates) {\n\tstd::vector<std::string> temp;\n\ttemp.push_back(Strings::cstr(time));\n\tstd::string temperature = Strings::cstr(((*m_gas)[m_gas->T]));\n\ttemp.push_back(temperature);\n\tfor (size_t i = 0; i<v_rates.size(); i++)\n\t\ttemp.push_back(Strings::cstr(v_rates[i]));\n\tm_rates_csv.Write(temp);\n    /*int convC[] = {1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35, 36};\n    //int convM[] = {1, 2,14,15, 8,10,11,12,13, 3, 7, 9, 5, 4, 6,22,24,16,21};\n    int ID;\n    //if(runNo==1) {\n    int total_jp = 35;\n    std::vector<double> temp(total_jp+1,0);\n    temp[0] = time;\n    for(int i=0; i!=(int)v_rates.size(); i++) {\n        ID = m_kmcmech.JPList()[i]->getID();\n        temp[convC[ID-1]] = v_rates[i];\n    }\n    m_rates_csv.Write(temp);\n    //}*/\n}\n//! Writes data for rates count (csv)\nvoid KMCSimulator::writeTestRatesCSV(double& time, rvector& v_rates) {\n\tstd::vector<std::string> temp;\n\ttemp.push_back(Strings::cstr(time));\n\tstd::string temperature = Strings::cstr(((*m_gas)[m_gas->T]));\n\ttemp.push_back(temperature);\n\tfor (size_t i = 0; i<v_rates.size(); i++)\n\t\ttemp.push_back(Strings::cstr(v_rates[i]));\n\tm_testrates_csv.Write(temp);\n}\n\n//! Initialise CSV_IOs\nvoid KMCSimulator::initCSVIO() {\n    // Check if CSV file names specified, if not put them as default\n    if(m_timer_name.length() == 0) {\n        cout<<\"WARNING: Output CSV name for time count is not specified. Defaulting to \"<<default_timer_csv<<\"\\n\";\n        m_timer_name = default_timer_csv;\n    }\n    if(m_rxncount_name.length() == 0) {\n        cout<<\"WARNING: Output CSV name for reaction count is not specified. Defaulting to \"<<default_rxncount_csv<<\"\\n\";\n        m_rxncount_name = default_rxncount_csv;\n    }\n    if(m_pahlist_name.length() == 0) {\n        cout<<\"WARNING: Output CSV name for CH and site counts is not specified. Defaulting to \"<<default_pahlist_csv<<\"\\n\";\n        m_pahlist_name = default_pahlist_csv;\n    }\n\tif(m_pahlist_after_name.length() == 0) {\n        cout<<\"WARNING: Output CSV name for CH and site counts after is not specified. Defaulting to \"<<default_pahlist_after_csv<<\"\\n\";\n        m_pahlist_after_name = default_pahlist_after_csv;\n    }\n\tif (m_rates_name.length() == 0) {\n\t\tcout << \"WARNING: Output CSV name for PAH rates is not specified. Defaulting to \" << default_rates_csv << \"\\n\";\n\t\tm_rates_name = default_rates_csv;\n\t}\n\tif (m_testrates_name.length() == 0) {\n\t\tcout << \"WARNING: Output CSV name for PAH rates is not specified. Defaulting to \" << default_testrates_csv << \"\\n\";\n\t\tm_testrates_name = default_testrates_csv;\n\t}\n\n    // Open csv file\n    m_timer_csv.Open(m_timer_name, true);\n    m_rxn_csv.Open(m_rxncount_name, true);\n    m_pah_csv.Open(m_pahlist_name, true);\n\tm_pah_after_csv.Open(m_pahlist_after_name, true);\t\t\t\t\t\t\t\t\t\t\t  \n    m_rates_csv.Open(m_rates_name, true);\n\tm_testrates_csv.Open(m_testrates_name, true);\n    m_timestep_csv.Open(m_timestep_name, true);//##\n    //m_pah_sitelist_csv.Open(\"KMC_Model/Site_list_arrange.csv\",true);\n    // Write column headings for CSV files\n    writeCSVlabels();\n}\n//! Initialise reaction count\nvoid KMCSimulator::initReactionCount() {\n    m_rxn_count.assign(m_kmcmech.JPList().size(), 0);\n}\n\n//! Prints rates to command line\nvoid KMCSimulator::printRates(double& time, const std::vector<double>& v_rates) {\n\tcout << \"Rates calculated at Time = \" << time << \"\\n\";\n    for(size_t i=0; i<m_kmcmech.JPList().size(); i++) {\n        // gets name of each jump process and puts them in a row\n\t\tcout << (m_kmcmech.JPList()[i]->getName()) << \"\\t ->\" << v_rates[i] << \"\\n\";\n    }\n\tcout << \"\\n\";\n}\n\t\n//! Reads chemical mechanism / profile (if not obtained from Mops)\n//! Similar function as Sweep::Flamesolver::LoadGasProfile\nvoid KMCSimulator::LoadGasProfiles(const std::string gasphase, const std::string chemfile, const std::string thermfile) {\n    m_mech = new Sprog::Mechanism();\n    Sprog::IO::MechanismParser::ReadChemkin(chemfile, *m_mech, thermfile, 0);\n    map<double,double> alpha_prof;\n\n    // Clear the current gas-phase profile.\n    m_gasprof->clear();\n\n    // Open the file to read.\n    ifstream fin(gasphase.c_str(), ios::in);\n    if (!fin.good()) {\n        throw runtime_error(\"Unable to open gas profile input \"\n                            \"file (Sweep, KMCSimulator::LoadGasProfile).\");\n    }\n\n    // Variables read from file.\n    vector<string> subs;\n    string delim = \",\\t \\r\"; // Possible file delimiters (comma, tab and space).\n    string line;\n\n    // Get the first line (should be the header defining the columns).\n    if (!getline(fin, line).eof()) {\n\n        // Split the line to get the column headings.\n        split(line, subs, delim);\n\n        // Get important column indices (time, temperature and pressure).\n        int tcol=-1, Tcol=-1, Pcol=-1;\n        tcol = findinlist(string(\"Time\"), subs);\n\n        Tcol = findinlist(string(\"T\"), subs);\n        if(Tcol < 0)\n            Tcol = findinlist(string(\"T[K]\"), subs);\n\n        Pcol = findinlist(string(\"P\"), subs);\n\n        // Columns to ignore, but which are useful to have in files for brush compatibility\n        int Xcol = findinlist(string(\"X[cm]\"), subs);\n        int Dcol = findinlist(string(\"RHO[g/cm3]\"), subs);\n        int Vcol = findinlist(string(\"V[cm/s]\"), subs);\n        int Gcol = findinlist(string(\"GradT\"), subs);\n        int Acol = findinlist(string(\"Alpha\"), subs);\n        int Rcol = findinlist(string(\"wdotA4\"), subs);\n\n\n        // Check that the file contains required columns.\n        if (tcol < 0) {\n            fin.close();\n            throw runtime_error(\"Gas-phase profile contains no Time \"\n                                \"column (Sweep::KMCSimulator::LoadGasProfiles).\");\n        }\n        if (Tcol < 0) {\n            fin.close();\n            throw runtime_error(\"Gas-phase profile contains no temperature \"\n                                \"column (Sweep::KMCSimulator::LoadGasProfiles).\");\n        }\n        if (Pcol < 0) {\n            fin.close();\n            throw runtime_error(\"Gas-phase profile contains no pressure \"\n                                \"column (Sweep::KMCSimulator::LoadGasProfiles).\");\n        }\n\n        // All other columns are chemical species.  Add them, and note\n        // their columns.\n        map<unsigned int,int> spcols;\n        for (int i=0; (unsigned)i!=subs.size(); ++i) {\n            if ((i!=tcol) && (i!=Tcol) && (i!=Pcol) && (i!=Acol) && (i!=Rcol) &&\n                (i!=Xcol) && (i!=Dcol) && (i!=Vcol) && (i!=Gcol)) {\n                // Try to find this species in the mechanism\n                const int speciesMechIndex = m_mech->FindSpecies(subs[i]);\n\n                if(speciesMechIndex < 0) {\n                    std::ostringstream msg(\"Failed to find species \");\n                    msg << subs[i] << \" in mechanism (Sweep::KMCSimulator::LoadGasProfiles).\";\n                    throw std::runtime_error(msg.str());\n                }\n                // Found species\n                spcols[i] = speciesMechIndex;\n            }\n        }\n\n        // Now we can read the profile.\n        while(!getline(fin, line).eof()) {\n            // Set t=0 and create a new IdealGas object.\n            double t = 0.0;\n            double T = 0.0;\n            double P = 0.0;\n            double alpha = 0.0;\n            double PAHRate = 0.0;\n            GasPoint gpoint(m_mech->Species());\n\n            // Split the line by columns.\n            split(line, subs, delim);\n\n            // Check that the mole fractions sum to 1\n            double checkSum = 0.0;\n\n            // Loop over all the elements in the line and save them\n            // to the correct gas-phase variable.\n            for (int i=0; (unsigned)i!=subs.size(); ++i) {\n                if (i==tcol) {\n                    // This is the Time column.\n                    t = cdble(subs[i]);\n                    gpoint.Time = t;\n                } else if (i==Tcol) {\n                    // This is the temperature column.\n                    T = cdble(subs[i]);\n                } else if (i==Pcol) {\n                    // This is the pressure column.\n                    P = cdble(subs[i]);\n                } else if (i==Acol) {\n                    alpha = cdble(subs[i]);\n                } else if (i==Rcol) {\n                    PAHRate = cdble(subs[i]);\n                } else {\n                    // This is a gas-phase species column.\n                    map<unsigned int,int>::iterator isp = spcols.find(i);\n                    if (isp != spcols.end()) {\n                        const double frac = cdble(subs[i]);\n                        assert(isp->second >= 0);\n                        gpoint.Gas.RawData()[isp->second] = frac;\n                        checkSum += frac;\n                    }\n                }\n            }\n\n            if((checkSum < 0.997) || checkSum > 1.003) {\n                std::ostringstream msg;\n                msg << \"Mole fractions sum to \" << checkSum\n                    << \", but should sum to 1.000 (KMCSimulator::LoadGasProfiles)\";\n                throw std::runtime_error(msg.str());\n            }\n\n            // Set up the gas-phase by setting temperature, pressure and\n            // normalising the mixture fractions.\n            // TODO:  This will give the wrong component densities\n            //        unless all species are specified!\n            gpoint.Gas.SetTemperature(T);\n            gpoint.Gas.SetPressure(P*1.0e5);\n            gpoint.Gas.Normalise();\n            gpoint.Gas.SetPAHFormationRate(PAHRate*1E6);\n\n            // Add the profile point.\n            alpha_prof[t] = alpha;\n            m_gasprof->push_back(gpoint);\n        }\n\n        // Close the input file.\n        fin.close();\n\n        // Sort the profile by time.\n        SortGasProfile(*m_gasprof);\n        m_gas = new KMCGasPoint(*m_gasprof, m_mech->Species());\n    } else {\n        // There was no data in the file.\n        fin.close();\n        throw runtime_error(\"Input file contains no data \"\n                            \"(Sweep::KMCSimulator::LoadGasProfiles).\");\n    }\n}\n//! Write column headings for CSV files\nvoid KMCSimulator::writeCSVlabels() {\n    // Write headings for timer\n    std::vector<string> timer_headings;\n    timer_headings.push_back(\"Total Loops\"); timer_headings.push_back(\"Time Elapsed\");\n    m_timer_csv.Write(timer_headings);\n    // Write headings for reaction count\n    std::vector<string> rxn_headings;\n\trxn_headings.push_back(\"Time\");\n\trxn_headings.push_back(\"Temperature\");\n\tstd::vector<string> rxn_count_headings;\n    for(size_t i=0; i<m_kmcmech.JPList().size(); i++) {\n        // gets name of each jump process and puts them in a row\n        rxn_headings.push_back(m_kmcmech.JPList()[i]->getName());\n\t\trxn_count_headings.push_back(m_kmcmech.JPList()[i]->getName());\n    }\n    m_rxn_csv.Write(rxn_count_headings);\n    // Write headings for CH and site list\n    std::vector<string> pah_headings;\n\t// write headings for PAH number\n\tpah_headings.push_back(\"PAH_ID\");\n    // write headings for N_C and N_H\n    pah_headings.push_back(\"N_C\");\n    pah_headings.push_back(\"N_H\");\n    // write headings for number of sites for all site types \"N(sitetype)\"\n    for(int i=0; i<(int) allSiteType.size(); i++) {\n        std::string header = \"N(\";\n        header = header.append(kmcSiteName(allSiteType[i]));\n        header = header.append(\")\");\n        pah_headings.push_back(header);\n    }\n\tpah_headings.push_back(\"R6\");\n\tpah_headings.push_back(\"Edge R5\");\n\tpah_headings.push_back(\"Embedded R5\");\n\tpah_headings.push_back(\"Edge R7\");\n\tpah_headings.push_back(\"Embedded R7\");\n    m_pah_csv.Write(pah_headings);\n\tm_pah_after_csv.Write(pah_headings);\t\t\t\t\t\t\t\t \n    // Write headings for rates\n    std::vector<std::string> rates_header;\n    rates_header.push_back(\"Time\");\n    /*for(size_t i=0; i<m_kmcmech.JPList().size()+1; i++) {\n        std::ostringstream ID_name(\"ID\");\n        ID_name << (i+1);\n        rates_header.push_back(ID_name.str());\n    }*/\n\t//m_rates_csv.Write(rates_header);\n\tm_rates_csv.Write(rxn_headings);\n\t//m_testrates_csv.Write(rates_header);\n\tm_testrates_csv.Write(rxn_headings);\n}\n//! Save the structure DOT file after every X loops\nvoid KMCSimulator::saveDOTperXLoops(int X, int &loopcount, int& runcount) {\n    int m = loopcount % X;\n    if(m==0) {\n        string filename = \"KMC_DEBUG/Run_\";\n        filename.append(Strings::cstr(runcount));\n        filename.append(\"_Loop_\");\n        filename.append(Strings::cstr(loopcount));\n        filename.append(\".dot\");\n        m_simPAHp.saveDOT(filename);\n    }\n}\n\nvoid KMCSimulator::saveDOTperLoop(int LOOPcount,int loopcount, int PAH_ID) {\n        string filename = \"KMC_DEBUG/ID_\";\n        filename.append(Strings::cstr(PAH_ID));\n        filename.append(\"_Run_\");\n        filename.append(Strings::cstr(LOOPcount));\n        filename.append(\"_Loop_\");\n        filename.append(Strings::cstr(loopcount));\n        filename.append(\".dot\");\n        m_simPAHp.saveDOT(filename);\n}\n//! Save the structure DOT file after every X simulation sec interval\nvoid KMCSimulator::saveDOTperXsec(const double& X, const int& seed, const double &time, const double &time_max, KMCMechanism& copyMod, int& intervalcount) {\n    int interval = (int) ceil(time/X);\n    std::string graphTitle;\n    if(intervalcount == -1) {\n        m_gas->Interpolate(0, 0);\n        std::string temp = Strings::cstr((int)ceil((*m_gas)[m_gas->T]))+\"K\";\n        string filename = \"KMC_DEBUG/\";\n        //filename.append(Strings::cstr(runcount));\n        filename = filename+Strings::cstr(seed)+\"-0.00000_s__\"+temp+\".dot\";\n        //graphTitle = \"0.00000s\";\n        m_simPAHp.saveDOT(filename);\n        intervalcount = 0;\n    }\n    while(interval > intervalcount || time == time_max) {\n        double timenow = intervalcount * X;\n        int sec = (int) floor(timenow);\n        int dec = (int) (floor((timenow - (double) sec)*100000));\n        std::string dec_str;\n        if(dec<10) dec_str = \"0000\";\n        else if(dec<100) dec_str = \"000\";\n        else if(dec<1000) dec_str = \"00\";\n        else if(dec<10000) dec_str = \"0\";\n        else dec_str = \"\";\n        dec_str = dec_str.append(Strings::cstr(dec));\n        string filename = \"KMC_DEBUG/\";\n        //filename.append(Strings::cstr(runcount));\n        //filename.append(\"_\");\n        m_gas->Interpolate(timenow, 0);\n        std::string temp = Strings::cstr((int)ceil((*m_gas)[m_gas->T]))+\"K\";\n        filename = filename+Strings::cstr(seed)+\"-\"+Strings::cstr(sec)+\".\"+dec_str+\"_s__\"+temp+\".dot\";\n        //graphTitle = Strings::cstr(sec)+\".\"+dec_str+\"s\";\n        m_simPAHp.saveDOT(filename);\n        intervalcount++;\n        if(time==time_max) break;\n    }\n}\n\n// CSV data ----\nCSV_data::CSV_data(KMCSimulator& st):\n\t\tm_sim(NULL), m_name(), m_dataC(), m_dataH(), m_time(), m_T(),\n\t\tm_intervalcount(0), m_dt(0.0) {\n    m_sim = &st;\n}\nCSV_data::~CSV_data() {}\nvoid CSV_data::initData(int max_runs, int no_of_interv, double max_time, intpair N_CH_initial, KMCGasPoint& gp) {\n    cout<<\"Initialising CH_data vector...\\n\";\n    // vector of zeros for each run\n    intvector zeros(no_of_interv+1, 0);\n    m_time.clear();\n    m_T.clear();\n    m_dataC.clear();\n    m_dataH.clear();\n    // calculate length of an interval\n    m_dt = max_time/no_of_interv;\n    // initialising time values\n    for(int i=0; i<=no_of_interv; i++){\n        double timetemp = m_dt*i;\n        m_time.push_back(timetemp);\n        gp.Interpolate(timetemp);\n        double Ttemp = gp[gp.T];\n        m_T.push_back(Ttemp);\n    }\n    // setting all values to zero for all runs\n    for(int i=0; i<max_runs; i++) {\n        m_dataC.push_back(zeros);\n        m_dataH.push_back(zeros);\n        // to include t = 0\n        m_dataC[i][0] = N_CH_initial.first;\n        m_dataH[i][0] = N_CH_initial.second;\n    }\n    m_intervalcount = 0;\n    \n    cout<<\"CH_data initialised!!\\n\";\n}\n// Compares time and adds data if interval reached\nvoid CSV_data::addData(intpair N_CH, double time, int runNo, PAHProcess& pp, bool savedot) {\n    // Zakwan's code\n    int& c = m_intervalcount;\n    // how many intervals have passed\n    int interv_now = (int) floor(time/m_dt);\n    // check if new interval has reached\n    if(interv_now > c) {\n        // to find how many data points skipped if time step larger than interval\n        int intervals_jumped = 0;\n        double Temp;\n        if((interv_now-c) > 1) {\n            \n            intervals_jumped = interv_now - c -1;\n            // fill skipped data points with last data point before jump\n            for(int i=1; i<=intervals_jumped; i++) {\n                Temp = m_T[c+i];\n                m_dataC[runNo-1][c+i] = m_dataC[runNo-1][c+i-1];\n                m_dataH[runNo-1][c+i] = m_dataH[runNo-1][c+i-1];\n                if(savedot) {\n                std::string filename = \"KMC_DEBUG/\";\n                double timenow = (c+i)*m_dt;\n                int sec = (int) floor(timenow);\n                int dec = (int) (floor((timenow - (double) sec)*100000));\n                std::string dec_str;\n                if(dec<10) dec_str = \"0000\";\n                else if(dec<100) dec_str = \"000\";\n                else if(dec<1000) dec_str = \"00\";\n                else if(dec<10000) dec_str = \"0\";\n                else dec_str = \"\";\n                dec_str = dec_str.append(Strings::cstr(dec));\n                filename = filename+Strings::cstr(sec)+\".\"+dec_str+\"s__\"+Strings::cstr(Temp)+\"K.dot\";\n                pp.saveDOT(filename);\n                }\n            }\n            // update current data point\n            c = interv_now;\n            \n\n            Temp = m_T[c];\n            m_dataC[runNo-1][c] = N_CH.first;\n            m_dataH[runNo-1][c] = N_CH.second;\n            if(savedot){\n            std::string filename = \"KMC_DEBUG/\";\n            int sec = (int) floor(time);\n            int dec = (int) (floor((time - (double) sec)*100000));\n            std::string dec_str;\n            if(dec<10) dec_str = \"0000\";\n            else if(dec<100) dec_str = \"000\";\n            else if(dec<1000) dec_str = \"00\";\n            else if(dec<10000) dec_str = \"0\";\n            else dec_str = \"\";\n            dec_str = dec_str.append(Strings::cstr(dec));\n            filename = filename+Strings::cstr(sec)+\".\"+dec_str+\"s__\"+Strings::cstr(Temp)+\"K.dot\";\n                pp.saveDOT(filename);\n            }\n        }else {\n            // update current data point\n            c = interv_now;\n            \n            Temp = m_T[c];\n            m_dataC[runNo-1][c] = N_CH.first;\n            m_dataH[runNo-1][c] = N_CH.second;\n            if(savedot) {\n            std::string filename = \"KMC_DEBUG/\";\n            int sec = (int) floor(time);\n            int dec = (int) (floor((time - (double) sec)*100000));\n            std::string dec_str;\n            if(dec<10) dec_str = \"0000\";\n            else if(dec<100) dec_str = \"000\";\n            else if(dec<1000) dec_str = \"00\";\n            else if(dec<10000) dec_str = \"0\";\n            else dec_str = \"\";\n            dec_str = dec_str.append(Strings::cstr(dec));\n            filename = filename+Strings::cstr(sec)+\".\"+dec_str+\"s__\"+Strings::cstr(Temp)+\"K.dot\";\n                pp.saveDOT(filename);\n            }\n        }\n    }else return;\n    /* Abhijeet's\n    double c = m_intervalcount*m_dt;\n    // how many intervals have passed\n    //int interv_now = (int) floor(time/m_dt);\n    if(time >= c) {\n        m_dataC[runNo-1][m_intervalcount] = N_CH.first;\n        m_dataH[runNo-1][m_intervalcount] = N_CH.second;\n        m_intervalcount++;\n    }*/\n}\n// delete data of run\nvoid CSV_data::delData(int runNo) {\n    int s = (int) m_dataC[runNo-1].size();\n    for(int i=1; i!=s; i++) { // exclude first data point\n        m_dataC[runNo-1][i] = 0;\n        m_dataH[runNo-1][i] = 0;\n    }\n}\n// Set name of output csv file containing C-H values\nvoid CSV_data::setName(const std::string filename){\n    m_name = filename;\n    //std::string num = Strings::cstr(runNo);\n    //m_name = m_name.append(num);\n    //m_name = m_name.append(\".csv\");\n}\n// write CSV file of data. Option is given to write PAH data in columns\n// or rows (since prior to Excel 2007 only 256 columns can be viewed in an Excel spreadsheet)\nvoid CSV_data::writeCSV(bool col, bool keep_data) {\n    CSV_IO csvfile(m_name, true);\n    std::vector<std::string> tempLine;\n    // writes data in columns\n    if(col) {\n        for(int i=0; i<(int)m_time.size(); i++) {\n            tempLine.clear();\n            tempLine.push_back(Strings::cstr(m_time[i]));\n            tempLine.push_back(Strings::cstr(m_T[i]));\n            //m_time.erase(m_time.begin());\n            for(int runNo=0; runNo<(int) m_dataC.size(); runNo++) {\n                tempLine.push_back(Strings::cstr(m_dataC[runNo][i]));\n                tempLine.push_back(Strings::cstr(m_dataH[runNo][i]));\n                //m_dataC[runNo].erase(m_dataC[runNo].begin());\n                //m_dataH[runNo].erase(m_dataH[runNo].begin());\n            }\n            csvfile.Write(tempLine);\n        }\n    } else{ // writes data in rows\n        std::vector<std::string> tempLine2;\n        csvfile.Write(m_time);\n        csvfile.Write(m_T);\n        for(int runNo=0; runNo<(int) m_dataC.size(); runNo++) {\n            tempLine.clear();\n            tempLine2.clear();\n            // CSV_IO class is not able to write ints (maybe an addition should be made to the template?)\n            // so convert ints into strings first\n            for(int i=0; i<(int) m_dataC[runNo].size(); i++) {\n                tempLine.push_back(Strings::cstr(m_dataC[runNo][i]));\n                tempLine2.push_back(Strings::cstr(m_dataH[runNo][i]));\n            }\n            csvfile.Write(tempLine);\n            csvfile.Write(tempLine2);\n        }\n    }\n    // option to keep C-H data after completed writing\n    if(!keep_data) {\n        m_time.clear();\n        m_dataC.clear();\n        m_dataH.clear();\n    }\n}\n\n// Test KMCGasPoint object. Linear interpolates values at 5 points from t = 0 to 0.005s\n// and writes values of profile on console.\nvoid KMCSimulator::TestGP() {\n    cout<<endl<<\"---(Sweep, KMC_ARS::KMCSimulator) Testing KMCGasPoint---\"<<endl;\n    for(double t=0; t<0.005; t+=0.001) {\n        cout << \"--At time \"<<t <<\"--\"<<endl;\n        m_gas->Interpolate(t);\n        for(int i=0; i<m_gas->m_total; i++) {\n            cout<<m_gas->SpNames()[i]<<\"\\t\"<<(*m_gas)[i]<<endl;\n        }\n        cout<<endl;\n    }\n    cout<<\"---(Sweep, KMC_ARS::KMCSimulator) Finished testing...\"<<endl<<endl;\n}\n\n//Save DEBUG information for a single PAH\nvoid KMCSimulator::savePAH(int PAH_number, const std::string &filename, bool optimise){\n\tstd::string xyzname = filename;\n\tm_simPAHp.saveXYZ(xyzname, optimise);\n    //m_simPAHp.save_formatfile(xyzname, \"pdb\", optimise);\n\t//m_simPAHp.printSites();\n}\n\n//Read PAHs to be tracked through the simulation from file.\nvoid KMCSimulator::readTrackedPAH(const std::string &filename){\n\tstd::ifstream src(filename);\n\tint PAH_number;\n\twhile (src >> PAH_number){\n\t\taddTrackedPAH(PAH_number);\n\t\tm_tracked_pahs_fixed.push_back(PAH_number);\n\t\t//m_tracked_pahs.push_back(PAH_number);\n        std::string temp_name = \"KMC_DEBUG/\";\n        temp_name.append(std::to_string(PAH_number));\n        temp_name.append(\"/\");\n        temp_name.append(std::to_string(PAH_number));\n        temp_name.append(\"_tracker.csv\");\n        CSV_IO temp_file;\n        temp_file.Open(temp_name,true);\n        // Write headings for CH and site list\n        std::vector<string> pah_headings;\n        // write headings for PAH number\n        pah_headings.push_back(\"Time\");\n        // write headings for N_C and N_H\n        pah_headings.push_back(\"N_C\");\n        pah_headings.push_back(\"N_H\");\n        pah_headings.push_back(\"R6\");\n        pah_headings.push_back(\"Edge R5\");\n        pah_headings.push_back(\"Embedded R5\");\n        pah_headings.push_back(\"Edge R7\");\n        pah_headings.push_back(\"Embedded R7\");\n        // write headings for number of sites for all site types \"N(sitetype)\"\n        for(int i=0; i<(int) allSiteType.size(); i++) {\n            std::string header = \"N(\";\n            header = header.append(kmcSiteName(allSiteType[i]));\n            header = header.append(\")\");\n            pah_headings.push_back(header);\n        }\n        temp_file.Write(pah_headings);\n        temp_file.Close();\n\t}\n}\n\n//! Open csv file for tracked PAH\nvoid KMCSimulator::opentrackedPAHCSV(int ID) {\n    std::string temp_name = \"KMC_DEBUG/\";\n    temp_name.append(std::to_string(ID));\n    temp_name.append(\"/\");\n    temp_name.append(std::to_string(ID));\n    temp_name.append(\"_tracker.csv\");\n    m_trackedpah_csv.Open(temp_name, false);\n    std::vector<std::string> n_vec;\n    n_vec.push_back(\" \");\n    m_trackedpah_csv.Write(n_vec);\n}\n\n//! Writes data for tracked PAH to csv file\nvoid KMCSimulator::writetrackedPAHCSV() {\n    //Values to write\n    std::vector<double> temp;\n\t// write PAH_ID number\n\ttemp.push_back(m_t);\n    // get CH count\n    intpair CH = m_simPAHp.getCHCount();\n    temp.push_back(CH.first);\n    temp.push_back(CH.second);\n    // get rings count\n    std::tuple <int, int, int> rings = m_simPAHp.getRingsCount();\n\ttemp.push_back(std::get<0>(rings));\n\ttemp.push_back((std::get<1>(rings) - m_simPAHp.getR5EmbeddedCount()));\n\ttemp.push_back(m_simPAHp.getR5EmbeddedCount());\n\ttemp.push_back((std::get<2>(rings) - m_simPAHp.getR7EmbeddedCount()));\n\ttemp.push_back(m_simPAHp.getR7EmbeddedCount());\n    // get counts for all site types\n    for(int i=0; i<(int)allSiteType.size(); i++) {\n        int scount = m_simPAHp.getSiteCount(allSiteType[i]);\n        temp.push_back(scount);\n    }\n    m_trackedpah_csv.Write(temp);\n}\n\n//! Writes data for tracked PAH to csv file\nvoid KMCSimulator::closetrackedPAHCSV() {\n    m_trackedpah_csv.Close();\n}\n\n//Add PAH to the tracked list on the fly.\nvoid KMCSimulator::addTrackedPAH(int PAH_number){\n\t// Check if PAH_number is already tracked.\n\tauto finder = std::find(std::begin(m_tracked_pahs), std::end(m_tracked_pahs), PAH_number); \n\tif (finder == m_tracked_pahs.end()){\n\t\tstd::cout << \"Adding PAH number \" << PAH_number << \" to tracked list. \\n\";\n\t\tm_tracked_pahs.push_back(PAH_number);\n\t}\n\telse{\n\t\tstd::cout << \"PAH number \" << PAH_number << \" already existed in tracked list. \\n\";\n\t}\n\t// Check if saving folder exists.\n\tstd::string dir_path = \"KMC_DEBUG/\";\n\tdir_path.append(std::to_string(PAH_number));\n\tboost::filesystem::path dir(dir_path);\n\tif (boost::filesystem::exists(dir)){\n\t\t// Folder already existed.\n\t\tstd::cout << \"Folder \" << dir << \" already existed. \\n\";\n\t}\n\telse {\n\t\tif(boost::filesystem::create_directory(dir)) {\n\t\t\tstd::cout << \"Creating folder \" << dir << \". \\n\";\n\t\t}\n\t\telse{\n\t\t\tstd::cout << \"Error creating folder \" << dir << \". \\n Continuing simulation. PAH coordinates may not be saved. \\n\";\n\t\t}\n\t}\n}\n\n//Remove PAH from the tracked list on the fly.\nvoid KMCSimulator::removeTrackedPAH(int PAH_number){\n\t// Find PAH_number.\n\tauto finder = std::find(std::begin(m_tracked_pahs), std::end(m_tracked_pahs), PAH_number); \n\tif (finder == std::end(m_tracked_pahs)){\n\t\tstd::cout << \"Trying to remove PAH number \" << PAH_number << \", but it was not found in tracked list. \\n\";\n\t}\n\telse{\n\t\t//Checks that PAH is not in the fixed tracked PAH list.\n\t\tauto fix_finder = std::find(std::begin(m_tracked_pahs_fixed), std::end(m_tracked_pahs_fixed), PAH_number); \n\t\tif (fix_finder == std::end(m_tracked_pahs_fixed)){\n\t\t\tstd::cout << \"Removing PAH number \" << PAH_number << \" from tracked list. \\n\";\n\t\t\tm_tracked_pahs.erase(finder);\n\t\t\t// Check if saving folder exists.\n\t\t\tstd::string dir_path = \"KMC_DEBUG/\";\n\t\t\tdir_path.append(std::to_string(PAH_number));\n\t\t\tboost::filesystem::path dir(dir_path);\n\t\t\tif (boost::filesystem::exists(dir)){\n\t\t\t\t// Folder already existed.\n\t\t\t\tstd::cout << \"Deleting folder \" << dir << \". \\n\";\n\t\t\t\tboost::filesystem::remove_all(dir);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstd::cout << \"Trying to remove folder \" << dir << \", but it did not exist. Continuing simulation. \\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n\n//! Sets the debug flag for PAHProcess.\nvoid KMCSimulator::setDebugPAH(const bool debug_pah) {\n    m_simPAHp.m_debug_pah = debug_pah;\n}\n", "meta": {"hexsha": "15580cae645c0d5aa413e308295bae350802bced", "size": 50336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_kmc_simulator.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_kmc_simulator.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_kmc_simulator.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 39.1111111111, "max_line_length": 219, "alphanum_fraction": 0.6113517165, "num_tokens": 13503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.03358950395711786, "lm_q1q2_score": 0.014319930330224466}}
{"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_UNARY_HPP\n#define AMA_TENSOR_DETAIL_TENSOR_CWISE_UNARY_HPP 1\n\n#include <ama/tensor/detail/tensor_base.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 OPERAND, typename OPERATOR> class tensor_cwise_unary;\n\n\n    /* specialization of tensor_traits */\n    template <typename OPERAND, typename OPERATOR>\n    struct tensor_traits< tensor_cwise_unary<OPERAND, OPERATOR> >\n    {\n      typedef typename OPERATOR::result_type value_type;\n\n      typedef typename OPERAND::dimension_type dimension_type;\n\n      typedef typename OPERAND::controvariant_type controvariant_type;\n      typedef typename OPERAND::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 OPERAND, typename OPERATOR>\n    class tensor_cwise_unary:\n        public tensor_base< tensor_cwise_unary<OPERAND, OPERATOR> >\n    {\n    protected:\n      typedef tensor_base< tensor_cwise_unary<OPERAND, OPERATOR> > base_type;\n      typedef tensor_cwise_unary<OPERAND, OPERATOR> derived_type;\n\n    protected:\n      typedef OPERAND 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      explicit\n      tensor_cwise_unary(operand_type const & operand,\n                         operator_type const & op = operator_type())\n          : m_operand(operand),\n            m_operator(op) { }\n\n    public:\n      /* retrieve the value */\n      template <typename ILIST>\n      value_type at() const { return m_operator(m_operand.template at<ILIST>()); }\n\n    protected:\n      /* if the operand is temporary we save a copy, otherwise a reference */\n      typedef typename OPERAND::is_temporary operand_is_temporary;\n      typedef typename ::boost::mpl::if_<\n            operand_is_temporary\n          , operand_type const\n          , operand_type const &\n          >::type const_operand_type;\n\n      /* members */\n      const_operand_type m_operand;\n      operator_type const m_operator;\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_DETAIL_TENSOR_CWISE_UNARY_HPP */\n", "meta": {"hexsha": "c5aacb3447137fba1b7e6a6b2007e276c2dd1f2e", "size": 3952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/detail/tensor_cwise_unary.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_unary.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_unary.hpp", "max_forks_repo_name": "mattiapenati/amanita", "max_forks_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5925925926, "max_line_length": 83, "alphanum_fraction": 0.7196356275, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.035144847158733825, "lm_q1q2_score": 0.014315670087261598}}
{"text": "/** $Id: MuonPropagator.cxx 176172 2019-10-16 16:45:58Z jsoedingrekso $\n * @file\n * @author Jakob van Santen <vansanten@wisc.edu>\n *\n * $Revision: 176172 $\n * $Date: 2019-10-16 10:45:58 -0600 (Wed, 16 Oct 2019) $\n */\n\n#include <boost/assign.hpp>\n#include <boost/foreach.hpp>\n#include <boost/bimap.hpp>\n\n#include \"MuonGun/MuonPropagator.h\"\n\nnamespace I3MuonGun {\n\nMuonPropagator::MuonPropagator(const std::string& medium, double ecut, double vcut, double rho)\n    : propagator_(NULL)\n{\n    PROPOSAL::Sector::Definition sec_def;\n\n    sec_def.cut_settings.SetEcut(ecut);\n    sec_def.cut_settings.SetVcut(vcut);\n    bool cont_rand = false;\n    if (ecut < 0 && vcut > 0)\n    {\n        cont_rand = true;\n    }\n    sec_def.do_continuous_randomization = cont_rand;\n\n    sec_def.SetMedium(*PROPOSAL::MediumFactory::Get().CreateMedium(medium, rho));\n\n    PROPOSAL::Sphere detector(PROPOSAL::Vector3D(0.0, 0.0, 0.0), 1e18, 0.0);\n    sec_def.SetGeometry(detector);\n\n    std::vector<PROPOSAL::Sector::Definition> sector_definitions;\n    sector_definitions.push_back(sec_def);\n\n    PROPOSAL::InterpolationDef interpol_def;\n\n    std::ostringstream prefix;\n    prefix << getenv(\"I3_BUILD\") << \"/MuonGun/resources/tables/\";\n\n    interpol_def.path_to_tables = prefix.str();\n\n    propagator_ = new PROPOSAL::Propagator(PROPOSAL::MuMinusDef::Get(),\n                                           sector_definitions,\n                                           detector,\n                                           interpol_def);\n}\n\nMuonPropagator::~MuonPropagator()\n{\n    delete propagator_;\n}\n\nvoid MuonPropagator::SetSeed(int seed)\n{\n    PROPOSAL::RandomGenerator::Get().SetSeed(seed);\n}\n\ninline std::string GetMMCName(I3Particle::ParticleType pt)\n{\n    std::string name;\n\n    if (pt == I3Particle::MuMinus)\n        name = \"mu-\";\n    else if (pt == I3Particle::MuPlus)\n        name = \"mu+\";\n\n    return name;\n}\n\nstd::string MuonPropagator::GetName(const I3Particle& p)\n{\n    return GetMMCName(p.GetType());\n}\n\n\n/** Differential stochastic rate: d^2N/dv/dx [1/m] */\ndouble MuonPropagator::GetStochasticRate(double energy, double fraction, I3Particle::ParticleType type) const\n{\n    // the propagator_ is always initialised with a Muon\n    // there is no need to specify the type of the particle\n    // this input parameter is historic and can be vanished\n    // it just exist for backward compatibility\n    (void)type;\n\n    // Check kinematics\n    if (fraction <= 0 || energy*(1-fraction) <= propagator_->GetParticle().GetMass()*I3Units::MeV)\n        return 0.;\n\n    double contrib;\n    double rate = 0.0;\n\n    const std::vector<PROPOSAL::CrossSection*>& crosssections = propagator_->GetCurrentSector()->GetUtility().GetCrosssections();\n\n    for (std::vector<PROPOSAL::CrossSection*>::const_iterator iter = crosssections.begin(); iter != crosssections.end(); ++iter)\n    {\n        if((*iter)->GetTypeId() == PROPOSAL::DynamicData::Brems || \n            (*iter)->GetTypeId() == PROPOSAL::DynamicData::Epair || \n            (*iter)->GetTypeId() == PROPOSAL::DynamicData::NuclInt)\n        {\n            for (int i = 0; i < propagator_->GetCurrentSector()->GetUtility().GetMedium().GetNumComponents(); ++i)\n            {\n                (*iter)->GetParametrization().SetCurrentComponent(i);\n                contrib = (*iter)->GetParametrization().DifferentialCrossSection(energy, fraction);\n                if(std::isfinite(contrib) && contrib > 0)\n                    rate += contrib;\n            }\n        }\n        else // if((*iter)->GetTypeId() == PROPOSAL::DynamicData::DeltaE)\n        {\n            contrib = (*iter)->GetParametrization().DifferentialCrossSection(energy, fraction);\n            if(std::isfinite(contrib) && contrib > 0)\n                rate += contrib;\n        }\n    }\n    return rate / I3Units::cm;\n}\n\n/** total stochastic rate: dN/dx [1/m] */\ndouble MuonPropagator::GetTotalStochasticRate(double energy, I3Particle::ParticleType type) const\n{\n    // the propagator_ is always initialised with a Muon\n    // there is no need to specify the type of the particle\n    // this input parameter is historic and can be vanished\n    // it just exist for backward compatibility\n    (void)type;\n\n    double rate = 0.0;\n    const std::vector<PROPOSAL::CrossSection*>& crosssections = propagator_->GetCurrentSector()->GetUtility().GetCrosssections();\n\n    for (std::vector<PROPOSAL::CrossSection*>::const_iterator iter = crosssections.begin(); iter != crosssections.end(); ++iter)\n    {\n        rate += (*iter)->CalculatedNdx(energy);\n    }\n    return rate / I3Units::cm;\n}\n\nI3Particle MuonPropagator::propagate(const I3Particle& p,\n                                     double distance,\n                                     boost::shared_ptr<std::vector<I3Particle> > losses)\n{\n    I3Particle endpoint(p);\n\n    double x, y, z, theta, phi;\n\n    PROPOSAL::Particle& pp = propagator_->GetParticle();\n    pp.SetParentParticleId(0);\n    pp.SetParticleId(0);\n\n    x = p.GetPos().GetX() / I3Units::cm;\n    y = p.GetPos().GetY() / I3Units::cm;\n    z = p.GetPos().GetZ() / I3Units::cm;\n\n    theta = p.GetDir().CalcTheta() / I3Units::radian;\n    phi   = p.GetDir().CalcPhi() / I3Units::radian;\n\n    pp.SetPosition(PROPOSAL::Vector3D(x, y, z));\n\n    PROPOSAL::Vector3D direction;\n    direction.SetSphericalCoordinates(1.0, phi, theta);\n    direction.CalculateCartesianFromSpherical();\n    pp.SetDirection(direction);\n\n    pp.SetEnergy(p.GetEnergy() / I3Units::MeV);\n    pp.SetTime(p.GetTime() / I3Units::second);\n    \n    double length = p.GetLength() / I3Units::cm;\n    if (!std::isfinite(length))\n    {\n        length = 0.;\n    }\n    pp.SetPropagatedDistance(length);\n\n    propagator_->Propagate(distance / I3Units::cm);\n\n    x = pp.GetPosition().GetX() * I3Units::cm;\n    y = pp.GetPosition().GetY() * I3Units::cm;\n    z = pp.GetPosition().GetZ() * I3Units::cm;\n\n    theta = pp.GetDirection().GetTheta() * I3Units::radian;\n    phi   = pp.GetDirection().GetPhi() * I3Units::radian;\n\n    endpoint.SetPos(x, y, z);\n    endpoint.SetThetaPhi(theta, phi);\n\n    endpoint.SetEnergy(pp.GetEnergy() * I3Units::MeV);\n    endpoint.SetLength(pp.GetPropagatedDistance() * I3Units::cm);\n    endpoint.SetTime(pp.GetTime() * I3Units::second);\n\n    if (losses)\n    {\n        std::vector<PROPOSAL::DynamicData*> history = PROPOSAL::Output::getInstance().GetSecondarys();\n        for (unsigned int i = 0; i < history.size(); i++)\n        {\n            losses->push_back(GenerateI3Particle(*history[i]));\n        }\n    }\n\n    PROPOSAL::Output::getInstance().ClearSecondaryVector();\n\n    return endpoint;\n}\n\ntypedef boost::bimap<I3Particle::ParticleType, std::string> bimap_ParticleType;\nstatic const bimap_ParticleType I3_PROPOSAL_ParticleType_bimap =\n    boost::assign::list_of<bimap_ParticleType::relation>\n        (I3Particle::MuMinus, \"MuMinus\")\n        (I3Particle::MuPlus, \"MuPlus\")\n        (I3Particle::TauMinus, \"TauMinus\")\n        (I3Particle::TauPlus, \"TauPlus\")\n        (I3Particle::EMinus, \"EMinus\")\n        (I3Particle::EPlus, \"EPlus\")\n        (I3Particle::NuMu, \"NuMu\")\n        (I3Particle::NuMuBar, \"NuMuBar\")\n        (I3Particle::NuE, \"NuE\")\n        (I3Particle::NuEBar, \"NuEBar\")\n        (I3Particle::NuTau, \"NuTau\")\n        (I3Particle::NuTauBar, \"NuTauBar\")\n        (I3Particle::Brems, \"Brems\")\n        (I3Particle::DeltaE, \"DeltaE\")\n        (I3Particle::PairProd, \"EPair\")\n        (I3Particle::NuclInt, \"NuclInt\")\n        (I3Particle::MuPair, \"MuPair\")\n        (I3Particle::Hadrons, \"Hadrons\")\n        (I3Particle::Monopole, \"Monopole\")\n        (I3Particle::STauMinus, \"STauMinus\")\n        (I3Particle::STauPlus, \"STauPlus\")\n        (I3Particle::Gamma, \"Gamma\")\n        (I3Particle::Pi0, \"Pi0\")\n        (I3Particle::PiPlus, \"PiPlus\")\n        (I3Particle::PiMinus, \"PiMinus\")\n        (I3Particle::K0_Short, \"K0\") // TODO(mario):  Fri 2017/11/17\n        (I3Particle::KPlus, \"KPlus\")\n        (I3Particle::KMinus, \"KMinus\")\n        (I3Particle::PPlus, \"PPlus\")\n        (I3Particle::PMinus, \"PMinus\");\n\n// ------------------------------------------------------------------------- //\nI3Particle::ParticleType MuonPropagator::GenerateI3Type(const PROPOSAL::DynamicData& secondary)\n{\n    PROPOSAL::DynamicData::Type type = secondary.GetTypeId();\n\n    switch (type)\n    {\n        case PROPOSAL::DynamicData::Particle:\n        {\n            const PROPOSAL::Particle& particle = static_cast<const PROPOSAL::Particle&>(secondary);\n            PROPOSAL::ParticleDef particle_def = particle.GetParticleDef();\n\n            I3Particle::ParticleType ptype_I3;\n\n            bimap_ParticleType::right_const_iterator proposal_iterator =\n                I3_PROPOSAL_ParticleType_bimap.right.find(particle_def.name);\n            if (proposal_iterator == I3_PROPOSAL_ParticleType_bimap.right.end())\n            {\n                log_fatal(\"The PROPOSALParticle '%s' can not be converted to a I3Particle\", particle_def.name.c_str());\n            } else\n            {\n                return proposal_iterator->second;\n            }\n            break;\n        }\n        case PROPOSAL::DynamicData::Brems:\n            return I3Particle::Brems;\n            break;\n        case PROPOSAL::DynamicData::Epair:\n            return I3Particle::PairProd;\n            break;\n        case PROPOSAL::DynamicData::DeltaE:\n            return I3Particle::DeltaE;\n            break;\n        case PROPOSAL::DynamicData::NuclInt:\n            return I3Particle::NuclInt;\n            break;\n        case PROPOSAL::DynamicData::ContinuousEnergyLoss:\n            return I3Particle::ContinuousEnergyLoss;\n            break;\n        default:\n            log_fatal(\"PROPOSAL Particle can not be converted to a I3Particle\");\n    }\n    return I3Particle::unknown;\n}\n\n// ------------------------------------------------------------------------- //\nI3Particle MuonPropagator::GenerateI3Particle(const PROPOSAL::DynamicData& pp)\n{\n    double x = pp.GetPosition().GetX() * I3Units::cm;\n    double y = pp.GetPosition().GetY() * I3Units::cm;\n    double z = pp.GetPosition().GetZ() * I3Units::cm;\n\n    double theta = pp.GetDirection().GetTheta() * I3Units::radian;\n    double phi   = pp.GetDirection().GetPhi() * I3Units::radian;\n\n    I3Particle i3_particle;\n    i3_particle.SetType(GenerateI3Type(pp));\n    i3_particle.SetLocationType(I3Particle::InIce);\n\n    i3_particle.SetPos(x, y, z);\n    i3_particle.SetThetaPhi(theta, phi);\n\n    i3_particle.SetLength(pp.GetPropagatedDistance() * I3Units::cm);\n    i3_particle.SetTime(pp.GetTime() * I3Units::second);\n    i3_particle.SetEnergy(pp.GetEnergy() * I3Units::MeV);\n    \n    log_trace(\"MMC DEBUG SEC \\n  pos=(%g,%g,%g) ang=(%g,%g)  e=%g t=%g  l=%g\",\n        x, y, z, theta, phi,\n        pp.GetEnergy() * I3Units::MeV,\n        pp.GetTime() * I3Units::second,\n        pp.GetPropagatedDistance() * I3Units::cm);\n\n    return i3_particle;\n}\n\n\nvoid Crust::AddLayer(I3Surfaces::SurfacePtr s, boost::shared_ptr<MuonPropagator> p)\n{\n    boundaries_.push_back(s);\n    propagators_.push_back(p);\n}\n\nI3Particle Crust::Ingest(const I3Particle& p)\n{\n    I3Particle propped(p);\n    double l = 0;\n    for (unsigned i = 0; (propped.GetEnergy() > 0) && (i < boundaries_.size()); i++)\n    {\n        double dx = boundaries_[i]->GetIntersection(propped.GetPos(), propped.GetDir()).first;\n        if (dx > 0)\n            propped = (i > 0 ? propagators_[i - 1] : defaultPropagator_)->propagate(propped, dx);\n        // Force lengths to measure the distance back to the outermost surface\n        if (i > 0)\n            l += std::min(dx, propped.GetLength());\n    }\n    propped.SetLength(l);\n\n    return propped;\n}\n\n} // namespace I3MuonGun\n", "meta": {"hexsha": "5406fc98277ead4d7da206f2f6cbe3e80e6bd849", "size": 11581, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MuonGun/private/MuonGun/MuonPropagator.cxx", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "MuonGun/private/MuonGun/MuonPropagator.cxx", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MuonGun/private/MuonGun/MuonPropagator.cxx", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 33.7638483965, "max_line_length": 129, "alphanum_fraction": 0.6182540368, "num_tokens": 3157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.03514484627446984, "lm_q1q2_score": 0.014315669727071347}}
{"text": "///////////////////////////////////////////////////////////////\r\n//  Copyright 2012 John Maddock. 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_\r\n\r\n#ifndef BOOST_MATH_FLOAT_BACKEND_HPP\r\n#define BOOST_MATH_FLOAT_BACKEND_HPP\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <sstream>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/math/concepts/real_concept.hpp>\r\n#include <boost/multiprecision/number.hpp>\r\n#include <boost/math/common_factor_rt.hpp>\r\n\r\nnamespace boost{\r\nnamespace multiprecision{\r\nnamespace backends{\r\n\r\n#ifdef BOOST_MSVC\r\n#  pragma warning(push)\r\n#  pragma warning(disable:4389 4244 4018 4244 4127)\r\n#endif\r\n\r\ntemplate <class Arithmetic>\r\nstruct arithmetic_backend\r\n{\r\n   typedef mpl::list<short, int, long, long long>                                      signed_types;\r\n   typedef mpl::list<unsigned short, unsigned, unsigned long, unsigned long long>      unsigned_types;\r\n   typedef mpl::list<float, double, long double>                                       float_types;\r\n   typedef int                                                                         exponent_type;\r\n\r\n   arithmetic_backend(){}\r\n   arithmetic_backend(const arithmetic_backend& o)\r\n   {\r\n      m_value = o.m_value;\r\n   }\r\n   template <class A>\r\n   arithmetic_backend(const A& o, const typename enable_if<is_arithmetic<A> >::type* = 0) : m_value(o) {}\r\n   template <class A>\r\n   arithmetic_backend(const arithmetic_backend<A>& o) : m_value(o.data()) {}\r\n   arithmetic_backend& operator = (const arithmetic_backend& o)\r\n   {\r\n      m_value = o.m_value;\r\n      return *this;\r\n   }\r\n   template <class A>\r\n   typename enable_if<is_arithmetic<A>, arithmetic_backend&>::type operator = (A i)\r\n   {\r\n      m_value = i;\r\n      return *this;\r\n   }\r\n   template <class A>\r\n   arithmetic_backend& operator = (const arithmetic_backend<A>& i)\r\n   {\r\n      m_value = i.data();\r\n      return *this;\r\n   }\r\n   arithmetic_backend& operator = (const char* s)\r\n   {\r\n#ifndef BOOST_NO_EXCEPTIONS\r\n      try\r\n      {\r\n#endif\r\n         m_value = boost::lexical_cast<Arithmetic>(s);\r\n#ifndef BOOST_NO_EXCEPTIONS\r\n      }\r\n      catch(const bad_lexical_cast&)\r\n      {\r\n         throw std::runtime_error(std::string(\"Unable to interpret the string provided: \\\"\") + s + std::string(\"\\\" as a compatible number type.\"));\r\n      }\r\n#endif\r\n      return *this;\r\n   }\r\n   void swap(arithmetic_backend& o)\r\n   {\r\n      std::swap(m_value, o.m_value);\r\n   }\r\n   std::string str(std::streamsize digits, std::ios_base::fmtflags f)const\r\n   {\r\n      std::stringstream ss;\r\n      ss.flags(f);\r\n      ss << std::setprecision(digits ? digits : std::numeric_limits<Arithmetic>::digits10 + 4) << m_value;\r\n      return ss.str();\r\n   }\r\n   void do_negate(const mpl::true_&)\r\n   {\r\n      m_value = 1 + ~m_value;\r\n   }\r\n   void do_negate(const mpl::false_&)\r\n   {\r\n      m_value = -m_value;\r\n   }\r\n   void negate()\r\n   {\r\n      do_negate(is_unsigned<Arithmetic>());\r\n   }\r\n   int compare(const arithmetic_backend& o)const\r\n   {\r\n      return m_value > o.m_value ? 1 : (m_value < o.m_value ? -1 : 0);\r\n   }\r\n   template <class A>\r\n   typename enable_if<is_arithmetic<A>, int>::type compare(A i)const\r\n   {\r\n      return m_value > static_cast<Arithmetic>(i) ? 1 : (m_value < static_cast<Arithmetic>(i) ? -1 : 0);\r\n   }\r\n   Arithmetic& data() { return m_value; }\r\n   const Arithmetic& data()const { return m_value; }\r\nprivate:\r\n   Arithmetic m_value;\r\n};\r\n\r\ntemplate <class R, class Arithmetic>\r\ninline void eval_convert_to(R* result, const arithmetic_backend<Arithmetic>& backend)\r\n{\r\n   *result = backend.data();\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline bool eval_eq(const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   return a.data() == b.data();\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2>, bool>::type eval_eq(const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   return a.data() == static_cast<Arithmetic>(b);\r\n}\r\ntemplate <class Arithmetic>\r\ninline bool eval_lt(const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   return a.data() < b.data();\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2>, bool>::type eval_lt(const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   return a.data() < static_cast<Arithmetic>(b);\r\n}\r\ntemplate <class Arithmetic>\r\ninline bool eval_gt(const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   return a.data() > b.data();\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2>, bool>::type eval_gt(const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   return a.data() > static_cast<Arithmetic>(b);\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_add(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   result.data() += o.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline void eval_subtract(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   result.data() -= o.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline void eval_multiply(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   result.data() *= o.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline typename enable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   result.data() /= o.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline typename disable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   if(!o.data())\r\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\r\n   result.data() /= o.data();\r\n}\r\n\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2> >::type eval_add(arithmetic_backend<Arithmetic>& result, const A2& o)\r\n{\r\n   result.data() += o;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2> >::type eval_subtract(arithmetic_backend<Arithmetic>& result, const A2& o)\r\n{\r\n   result.data() -= o;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2> >::type eval_multiply(arithmetic_backend<Arithmetic>& result, const A2& o)\r\n{\r\n   result.data() *= o;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if_c<(is_arithmetic<A2>::value && !std::numeric_limits<Arithmetic>::has_infinity)>::type\r\n   eval_divide(arithmetic_backend<Arithmetic>& result, const A2& o)\r\n{\r\n   if(!o)\r\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\r\n   result.data() /= o;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if_c<(is_arithmetic<A2>::value && std::numeric_limits<Arithmetic>::has_infinity)>::type\r\n   eval_divide(arithmetic_backend<Arithmetic>& result, const A2& o)\r\n{\r\n   result.data() /= o;\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_add(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   result.data() = a.data() + b.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline void eval_subtract(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   result.data() = a.data() - b.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline void eval_multiply(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   result.data() = a.data() * b.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline typename enable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   result.data() = a.data() / b.data();\r\n}\r\ntemplate <class Arithmetic>\r\ninline typename disable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   if(!b.data())\r\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\r\n   result.data() = a.data() / b.data();\r\n}\r\n\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2> >::type eval_add(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   result.data() = a.data() + b;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2> >::type eval_subtract(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   result.data() = a.data() - b;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if<is_arithmetic<A2> >::type eval_multiply(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   result.data() = a.data() * b;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if_c<(is_arithmetic<A2>::value && !std::numeric_limits<Arithmetic>::has_infinity)>::type\r\n   eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   if(!b)\r\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\r\n   result.data() = a.data() / b;\r\n}\r\ntemplate <class Arithmetic, class A2>\r\ninline typename enable_if_c<(is_arithmetic<A2>::value && std::numeric_limits<Arithmetic>::has_infinity)>::type\r\n   eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\r\n{\r\n   result.data() = a.data() / b;\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline bool eval_is_zero(const arithmetic_backend<Arithmetic>& val)\r\n{\r\n   return val.data() == 0;\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline typename enable_if_c<\r\n      (!std::numeric_limits<Arithmetic>::is_specialized\r\n      || std::numeric_limits<Arithmetic>::is_signed), int>::type\r\n   eval_get_sign(const arithmetic_backend<Arithmetic>& val)\r\n{\r\n   return val.data() == 0 ? 0 : val.data() < 0 ? -1 : 1;\r\n}\r\ntemplate <class Arithmetic>\r\ninline typename disable_if_c<\r\n      (std::numeric_limits<Arithmetic>::is_specialized\r\n      || std::numeric_limits<Arithmetic>::is_signed), int>::type\r\n   eval_get_sign(const arithmetic_backend<Arithmetic>& val)\r\n{\r\n   return val.data() == 0 ? 0 : 1;\r\n}\r\n\r\ntemplate <class T>\r\ninline typename enable_if<is_unsigned<T>, T>::type abs(T v) { return v; }\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_abs(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   using std::abs;\r\n   using boost::multiprecision::backends::abs;\r\n   result.data() = abs(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_fabs(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   result.data() = std::abs(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_floor(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = floor(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_ceil(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = ceil(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_sqrt(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = sqrt(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline int eval_fpclassify(const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   return (boost::math::fpclassify)(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_trunc(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = trunc(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_round(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = round(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_frexp(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, int* v)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = frexp(a.data(), v);\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_ldexp(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, int v)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = ldexp(a.data(), v);\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_exp(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = exp(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_log(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = log(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_log10(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = log10(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_sin(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = sin(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_cos(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = cos(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_tan(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = tan(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_acos(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = acos(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_asin(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = asin(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_atan(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = atan(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_sinh(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = sinh(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_cosh(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = cosh(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_tanh(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = tanh(o.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_fmod(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = fmod(a.data(), b.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_pow(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = pow(a.data(), b.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_atan2(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   result.data() = atan2(a.data(), b.data());\r\n}\r\n\r\ntemplate <class Arithmetic, class I>\r\ninline void eval_left_shift(arithmetic_backend<Arithmetic>& result, I val)\r\n{\r\n   result.data() <<= val;\r\n}\r\n\r\ntemplate <class Arithmetic, class I>\r\ninline void eval_right_shift(arithmetic_backend<Arithmetic>& result, I val)\r\n{\r\n   result.data() >>= val;\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_modulus(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\r\n{\r\n   result.data() %= a.data();\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_bitwise_and(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\r\n{\r\n   result.data() &= a.data();\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_bitwise_or(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\r\n{\r\n   result.data() |= a.data();\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_bitwise_xor(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\r\n{\r\n   result.data() ^= a.data();\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_complement(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\r\n{\r\n   result.data() = ~a.data();\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_gcd(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   result.data() = boost::math::gcd(a.data(), b.data());\r\n}\r\n\r\ntemplate <class Arithmetic>\r\ninline void eval_lcm(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\r\n{\r\n   result.data() = boost::math::lcm(a.data(), b.data());\r\n}\r\n\r\n#ifdef BOOST_MSVC\r\n#  pragma warning(pop)\r\n#endif\r\n\r\n} // namespace backends\r\n\r\nusing boost::multiprecision::backends::arithmetic_backend;\r\n\r\ntemplate <class Arithmetic>\r\nstruct number_category<arithmetic_backend<Arithmetic> > : public mpl::int_<is_integral<Arithmetic>::value ? number_kind_integer : number_kind_floating_point>{};\r\n\r\nnamespace detail{\r\n\r\ntemplate <class Backend>\r\nstruct double_precision_type;\r\n\r\ntemplate<class Arithmetic, boost::multiprecision::expression_template_option ET>\r\nstruct double_precision_type<number<arithmetic_backend<Arithmetic>, ET> >\r\n{\r\n   typedef number<arithmetic_backend<typename double_precision_type<Arithmetic>::type>, ET> type;\r\n};\r\ntemplate<>\r\nstruct double_precision_type<arithmetic_backend<boost::int32_t> >\r\n{\r\n   typedef arithmetic_backend<boost::int64_t> type;\r\n};\r\n\r\n}\r\n\r\n}} // namespaces\r\n#if !(defined(__SGI_STL_PORT) || defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS))\r\n//\r\n// We shouldn't need these to get code to compile, however for the sake of\r\n// \"level playing field\" performance comparisons they avoid the very slow\r\n// lexical_cast's that would otherwise take place.  Definition has to be guarded\r\n// by the inverse of pp-logic in real_concept.hpp which defines these as a workaround\r\n// for STLPort plus some other old/broken standartd libraries.\r\n//\r\nnamespace boost{ namespace math{ namespace tools{\r\n\r\n   template <>\r\n   inline unsigned int real_cast<unsigned int, concepts::real_concept>(concepts::real_concept r)\r\n   {\r\n      return static_cast<unsigned int>(r.value());\r\n   }\r\n\r\n   template <>\r\n   inline int real_cast<int, concepts::real_concept>(concepts::real_concept r)\r\n   {\r\n      return static_cast<int>(r.value());\r\n   }\r\n\r\n   template <>\r\n   inline long real_cast<long, concepts::real_concept>(concepts::real_concept r)\r\n   {\r\n      return static_cast<long>(r.value());\r\n   }\r\n\r\n   // Converts from T to narrower floating-point types, float, double & long double.\r\n\r\n   template <>\r\n   inline float real_cast<float, concepts::real_concept>(concepts::real_concept r)\r\n   {\r\n      return static_cast<float>(r.value());\r\n   }\r\n   template <>\r\n   inline double real_cast<double, concepts::real_concept>(concepts::real_concept r)\r\n   {\r\n      return static_cast<double>(r.value());\r\n   }\r\n   template <>\r\n   inline long double real_cast<long double, concepts::real_concept>(concepts::real_concept r)\r\n   {\r\n      return r.value();\r\n   }\r\n\r\n}}}\r\n#endif\r\n\r\nnamespace std{\r\n\r\ntemplate <class Arithmetic, boost::multiprecision::expression_template_option ExpressionTemplates>\r\nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::arithmetic_backend<Arithmetic>, ExpressionTemplates > > : public std::numeric_limits<Arithmetic>\r\n{\r\n   typedef std::numeric_limits<Arithmetic> base_type;\r\n   typedef boost::multiprecision::number<boost::multiprecision::arithmetic_backend<Arithmetic>, ExpressionTemplates> number_type;\r\npublic:\r\n   BOOST_STATIC_CONSTEXPR number_type (min)() BOOST_NOEXCEPT { return (base_type::min)(); }\r\n   BOOST_STATIC_CONSTEXPR number_type (max)() BOOST_NOEXCEPT { return (base_type::max)(); }\r\n   BOOST_STATIC_CONSTEXPR number_type lowest() BOOST_NOEXCEPT { return -(max)(); }\r\n   BOOST_STATIC_CONSTEXPR number_type epsilon() BOOST_NOEXCEPT { return base_type::epsilon(); }\r\n   BOOST_STATIC_CONSTEXPR number_type round_error() BOOST_NOEXCEPT { return epsilon() / 2; }\r\n   BOOST_STATIC_CONSTEXPR number_type infinity() BOOST_NOEXCEPT { return base_type::infinity(); }\r\n   BOOST_STATIC_CONSTEXPR number_type quiet_NaN() BOOST_NOEXCEPT { return base_type::quiet_NaN(); }\r\n   BOOST_STATIC_CONSTEXPR number_type signaling_NaN() BOOST_NOEXCEPT { return base_type::signaling_NaN(); }\r\n   BOOST_STATIC_CONSTEXPR number_type denorm_min() BOOST_NOEXCEPT { return base_type::denorm_min(); }\r\n};\r\n\r\ntemplate<>\r\nclass numeric_limits<boost::math::concepts::real_concept> : public std::numeric_limits<long double>\r\n{\r\n   typedef std::numeric_limits<long double> base_type;\r\n   typedef boost::math::concepts::real_concept number_type;\r\npublic:\r\n   static const number_type (min)() BOOST_NOEXCEPT { return (base_type::min)(); }\r\n   static const number_type (max)() BOOST_NOEXCEPT { return (base_type::max)(); }\r\n   static const number_type lowest() BOOST_NOEXCEPT { return -(max)(); }\r\n   static const number_type epsilon() BOOST_NOEXCEPT { return base_type::epsilon(); }\r\n   static const number_type round_error() BOOST_NOEXCEPT { return epsilon() / 2; }\r\n   static const number_type infinity() BOOST_NOEXCEPT { return base_type::infinity(); }\r\n   static const number_type quiet_NaN() BOOST_NOEXCEPT { return base_type::quiet_NaN(); }\r\n   static const number_type signaling_NaN() BOOST_NOEXCEPT { return base_type::signaling_NaN(); }\r\n   static const number_type denorm_min() BOOST_NOEXCEPT { return base_type::denorm_min(); }\r\n};\r\n\r\n}\r\n\r\n#include <boost/multiprecision/detail/integer_ops.hpp>\r\n\r\n#endif\r\n", "meta": {"hexsha": "848c7b603ff3bc5fdaa628e69c0a230718aed568", "size": 22437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "thirdparty-cpp/boost_1_62_0/libs/multiprecision/performance/arithmetic_backend.hpp", "max_stars_repo_name": "nxplatform/nx-mobile", "max_stars_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/multiprecision/performance/arithmetic_backend.hpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/multiprecision/performance/arithmetic_backend.hpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "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.9485981308, "max_line_length": 216, "alphanum_fraction": 0.714043767, "num_tokens": 5258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897501624599, "lm_q2_score": 0.03904829482301672, "lm_q1q2_score": 0.014314704643439776}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n/// \\file period_sums.hpp\r\n/// Calculate the sums within fixed-width ranges in a series\r\n//\r\n//  Copyright 2006 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_TIME_SERIES_NUMERIC_PERIOD_SUMS_EAN_06_12_2006\r\n#define BOOST_TIME_SERIES_NUMERIC_PERIOD_SUMS_EAN_06_12_2006\r\n\r\n#include <boost/implicit_cast.hpp>\r\n#include <boost/concept/requires.hpp>\r\n#include <boost/assert.hpp>\r\n#include <boost/mpl/assert.hpp>\r\n#include <boost/type_traits/is_integral.hpp>\r\n#include <boost/range_run_storage/traits/is_unit_run.hpp>\r\n#include <boost/range_run_storage/algorithm/copy.hpp>\r\n#include <boost/time_series/concepts.hpp>\r\n#include <boost/time_series/sparse_series.hpp>\r\n#include <boost/time_series/ordered_inserter.hpp>\r\n#include <boost/time_series/numeric/detail/find_period.hpp>\r\n\r\nnamespace boost { namespace time_series\r\n{\r\n\r\n    namespace detail\r\n    {\r\n        namespace rrs = range_run_storage;\r\n\r\n        // period_sums_inserter\r\n        template<typename Out, typename Series, typename Offset, typename Length>\r\n        struct period_sums_inserter\r\n        {\r\n            typedef typename concepts::TimeSeries<Series>::value_type value_type;\r\n\r\n            typedef Offset offset_type;\r\n            typedef Length length_type;\r\n            typedef std::pair<offset_type, offset_type> period_type;\r\n\r\n            period_sums_inserter(Out const &out, Series const &series, offset_type start, length_type length)\r\n              : out_(out)\r\n              , zero_(implicit_cast<value_type const &>(rrs::zero(series)))\r\n              , value_(implicit_cast<value_type const &>(rrs::zero(series)))\r\n              , period_(start, static_cast<offset_type>(start + length))\r\n              , start_(start)\r\n              , length_(length)\r\n            {}\r\n\r\n            template<typename Run>\r\n            void set_at(Run const &run, value_type const &value)\r\n            {\r\n                if(this->start_ < rrs::end_offset(run))\r\n                {\r\n                    if(rrs::less(this->period_, run))\r\n                    {\r\n                        this->out_(this->value_, this->period_.first);\r\n                        this->value_ = this->zero_;\r\n                        this->period_ = detail::find_period(run, this->start_, this->length_);\r\n                    }\r\n                    this->set_at_(run, value, rrs::traits::is_unit_run<Run>());\r\n                }\r\n            }\r\n\r\n            Out const &finalize()\r\n            {\r\n                this->out_(this->value_, this->period_.first);\r\n                return this->out_;\r\n            }\r\n        private:\r\n            template<typename Run>\r\n            void set_at_(Run const &, value_type const &value, mpl::true_)\r\n            {\r\n                this->value_ += value;\r\n            }\r\n\r\n            template<typename Run>\r\n            void set_at_(Run const &run, value_type const &value, mpl::false_)\r\n            {\r\n                typedef typename result_of<rrs::op::subrun(Run)>::type subrun_type;\r\n                typedef typename result_of<rrs::op::overlap(subrun_type, period_type)>::type overlap_type;\r\n                subrun_type subrun(rrs::subrun(run));\r\n\r\n                for(;;)\r\n                {\r\n                    overlap_type overlap(rrs::overlap(subrun, this->period_));\r\n                    this->value_ += value * rrs::length(overlap);\r\n                    rrs::advance_to(subrun, rrs::end_offset(overlap));\r\n\r\n                    if(!rrs::has_leftover(subrun))\r\n                        break;\r\n\r\n                    this->out_(this->value_, this->period_.first);\r\n                    this->value_ = this->zero_;\r\n                    this->period_.first = this->period_.second;\r\n                    this->period_.second += this->length_;\r\n                }\r\n            }\r\n\r\n            Out out_;\r\n            value_type zero_;\r\n            value_type value_;\r\n            period_type period_;\r\n            offset_type start_;\r\n            length_type length_;\r\n        };\r\n    }\r\n\r\n    /// \\brief Calculate the sums within fixed-width ranges in a series and store\r\n    ///     the results at the start of each range.\r\n    ///\r\n    /// Calculate the sums within fixed-width ranges in a series and store\r\n    ///     the results at the start of each range.\r\n    ///\r\n    /// This function assumes that zero value of the series does not contribute to the\r\n    /// sums, that \\c start is not \\c -inf and that the series does not have a non-zero\r\n    /// positive infinite run.\r\n    ///\r\n    /// The input series is allowed to use floating point offsets, but the periods as\r\n    /// specified by the \\c start and \\c length parameters must be integral. As a result,\r\n    /// the output series will necessarily have integral offsets.\r\n    ///\r\n    /// \\param series The input series.\r\n    /// \\param start The offset of the first period. Must be integral.\r\n    /// \\param length The length of the periods. Must be integral.\r\n    /// \\param out The ordered inserter to receive the adjacent difference result.\r\n    ///\r\n    /// \\pre \\c Series is a model of the \\c TimeSeries concept.\r\n    /// \\pre \\c Out is a model of the \\c OrderedInserter concept.\r\n    /// \\pre \\c Offset is integral.\r\n    /// \\pre \\c Length is integral.\r\n    /// \\pre For variaibles \\c x and \\c y of the series' \\c value_type, and \\c l of\r\n    ///     type \\c Length, the expression \\c (x+=y*l) must be convertible to \r\n    ///     \\c value_type.\r\n    /// \\pre For a variable \\c x of the series' value_type, \r\n    ///     <tt>x == (x + range_run_storage::zero(series))</tt>.\r\n    /// \\pre <tt>start != -inf</tt>\r\n    /// \\pre <tt>series[inf] == range_run_storage::zero(series)</tt>\r\n    /// \\return A \\c sparse_series\\<\\> if no ordered inserter is specified;\r\n    ///     otherwise, the ordered inserter.\r\n    /// \\attention If using the version that takes an \\c OrderedInserter, you must call\r\n    ///     <tt>.commit()</tt> on the returned \\c OrderedInserter when you are done with it.\r\n    template<typename Series, typename Offset, typename Length, typename Out>\r\n    BOOST_CONCEPT_REQUIRES(\r\n        ((concepts::TimeSeries<Series const>)),\r\n    (ordered_inserter<Out>))\r\n    period_sums(Series const &series, Offset start, Length length, ordered_inserter<Out> out)\r\n    {\r\n        BOOST_MPL_ASSERT((is_integral<Offset>));\r\n        BOOST_MPL_ASSERT((is_integral<Length>));\r\n\r\n        detail::period_sums_inserter<ordered_inserter<Out>, Series, Offset, Length>\r\n            o(out, series, start, length);\r\n\r\n        return range_run_storage::copy(series, o).finalize();\r\n    }\r\n\r\n\r\n    /// \\overload\r\n    ///\r\n    template<typename Series, typename Offset, typename Length>\r\n    BOOST_CONCEPT_REQUIRES(\r\n        ((concepts::TimeSeries<Series const>)),\r\n    (sparse_series<\r\n        typename concepts::TimeSeries<Series const>::value_type\r\n      , typename concepts::TimeSeries<Series const>::discretization_type\r\n      , Offset\r\n    >))\r\n    period_sums(Series const &series, Offset start, Length length)\r\n    {\r\n        typedef typename concepts::TimeSeries<Series const>::value_type value_type;\r\n        typedef typename concepts::TimeSeries<Series const>::discretization_type discretization_type;\r\n\r\n        // The periodic sums are held in a sparse array. The sums are\r\n        // stored at the start of their associated periods.\r\n        sparse_series<value_type, discretization_type, Offset> result(\r\n            time_series::discretization = series.discretization()\r\n        );\r\n\r\n        time_series::period_sums(\r\n            series\r\n          , start\r\n          , length\r\n          , time_series::make_ordered_inserter(result)\r\n        ).commit();\r\n\r\n        return result;\r\n    }\r\n\r\n}}\r\n\r\n#endif // BOOST_TIME_SERIES_NUMERIC_PERIOD_SUMS_EAN_06_12_2006\r\n", "meta": {"hexsha": "9b7f34df2da028f21a32c1256a8eb4f05d6cfe30", "size": 7932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/time_series/numeric/period_sums.hpp", "max_stars_repo_name": "ericniebler/time_series", "max_stars_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T11:23:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T03:39:29.000Z", "max_issues_repo_path": "boost/time_series/numeric/period_sums.hpp", "max_issues_repo_name": "ericniebler/time_series", "max_issues_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "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/time_series/numeric/period_sums.hpp", "max_forks_repo_name": "ericniebler/time_series", "max_forks_repo_head_hexsha": "4040119366cc21f25c7734bb355e4a647296a96d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-05-09T02:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-02T13:39:29.000Z", "avg_line_length": 41.0984455959, "max_line_length": 110, "alphanum_fraction": 0.5925365608, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.029312229267415522, "lm_q1q2_score": 0.01431267483038359}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_StandardElectronPhotonRelaxationDataGenerator.hpp\n//! \\author Alex Robinson\n//! \\brief  The standard electron-photon-relaxation data generator class def.\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"DataGen_StandardElectronPhotonRelaxationDataGenerator.hpp\"\n#include \"DataGen_OccupationNumberEvaluator.hpp\"\n#include \"MonteCarlo_ComptonProfileHelpers.hpp\"\n#include \"MonteCarlo_ComptonProfileSubshellConverterFactory.hpp\"\n#include \"MonteCarlo_SubshellType.hpp\"\n#include \"Utility_GridGenerator.hpp\"\n#include \"Utility_ExceptionTestMacros.hpp\"\n#include \"Utility_ContractException.hpp\"\n#include \"MonteCarlo_SubshellType.hpp\"\n\nnamespace DataGen{\n\n// Initialize the static member data\nconst double StandardElectronPhotonRelaxationDataGenerator::s_threshold_energy_nudge_factor = 1.0001;\n\n// Constructor\nStandardElectronPhotonRelaxationDataGenerator::StandardElectronPhotonRelaxationDataGenerator( \n        const unsigned atomic_number,\n        const Teuchos::RCP<const Data::XSSEPRDataExtractor>& ace_epr_data,\n        const Teuchos::RCP<Data::ENDLFileHandler>& eedl_file_handler,\n        const double min_photon_energy,\n        const double max_photon_energy,\n        const double min_electron_energy,\n        const double max_electron_energy,\n        const double cutoff_angle,\n        const double occupation_number_evaluation_tolerance,\n        const double subshell_incoherent_evaluation_tolerance,\n        const double grid_convergence_tol,\n        const double grid_absolute_diff_tol,\n        const double grid_distance_tol )\n  : ElectronPhotonRelaxationDataGenerator( atomic_number ),\n    d_ace_epr_data( ace_epr_data ),\n    d_eedl_file_handler( eedl_file_handler ),\n    d_min_photon_energy( min_photon_energy ),\n    d_max_photon_energy( max_photon_energy ),\n    d_min_electron_energy( min_electron_energy ),\n    d_max_electron_energy( max_electron_energy ),\n    d_cutoff_angle( cutoff_angle ),\n    d_occupation_number_evaluation_tolerance( occupation_number_evaluation_tolerance ),\n    d_subshell_incoherent_evaluation_tolerance( subshell_incoherent_evaluation_tolerance ),\n    d_grid_convergence_tol( grid_convergence_tol ),\n    d_grid_absolute_diff_tol( grid_absolute_diff_tol ),\n    d_grid_distance_tol( grid_distance_tol )\n{\n  // Make sure the atomic number is valid\n  testPrecondition( atomic_number <= 100u );\n  // Make sure the ace data is valid\n  testPrecondition( !ace_epr_data.is_null() );\n  // Make sure the photon energy limits are valid\n  testPrecondition( min_photon_energy > 0.0 );\n  testPrecondition( min_photon_energy < max_photon_energy );\n  // Make sure the electron energy limits are valid\n  testPrecondition( min_electron_energy > 0.0 );\n  testPrecondition( min_electron_energy < max_electron_energy );\n  // Make sure the cutoff angle is valid\n  testPrecondition( cutoff_angle >= 0.0 );\n  testPrecondition( cutoff_angle < 2.0 );\n}\n\n// Populate the electron-photon-relaxation data container\nvoid StandardElectronPhotonRelaxationDataGenerator::populateEPRDataContainer(\n\t\t\t   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  // Set the atomic number\n  this->setAtomicNumber( data_container );\n\n  // Set cutoff angle\n  data_container.setCutoffAngle( d_cutoff_angle );\n\n  // Set the relaxation data\n  std::cout << \"Setting the relaxation data...\";\n  std::cout.flush();\n  this->setRelaxationData( data_container );\n  std::cout << \"done.\" << std::endl;\n\n  // Set the Compton profile data\n  std::cout << \"Setting the Compton profile data...\";\n  std::cout.flush();\n  this->setComptonProfileData( data_container );\n  std::cout << \"done.\" << std::endl;\n\n  // Set the occupation number data\n  std::cout << \"Setting the occupation number data...\";\n  std::cout.flush();\n  this->setOccupationNumberData( data_container );\n  std::cout << \"done.\" << std::endl;\n\n  // Set the Waller-Hartree scattering function data\n  std::cout << \"Setting the Waller-Hartree scattering function data...\";\n  std::cout.flush();\n  this->setWallerHartreeScatteringFunctionData( data_container );\n  std::cout << \"done.\" << std::endl;\n\n  // Set the Waller-Hartree atomic form factor data\n  std::cout << \"Setting the Waller-Hartree atomic form factor data...\";\n  this->setWallerHartreeAtomicFormFactorData( data_container );\n  std::cout << \"done.\" << std::endl;\n\n  // Set the photon data\n  std::cout << \"Setting the photon cross section data: \" << std::endl;\n  this->setPhotonData( data_container );\n\n  // Set the electron data\n  std::cout << \"Setting the electron data: \" << std::endl;\n  this->setElectronData( data_container );\n  std::cout << \"done.\" << std::endl;\n\n}\n\n// Set the relaxation data\nvoid StandardElectronPhotonRelaxationDataGenerator::setRelaxationData( \n\t\t\t   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  // Extract the subshell ENDF designators \n  Teuchos::ArrayView<const double> subshell_designators = \n    d_ace_epr_data->extractSubshellENDFDesignators();\n  \n  // Assign the set of all subshells\n  {\n    std::set<unsigned> subshells;\n\n    for( unsigned i = 0; i < subshell_designators.size(); ++i )\n      subshells.insert( (unsigned)subshell_designators[i] );\n\n    data_container.setSubshells( subshells );\n  }\n\n  // Extract the subshell occupancies\n  Teuchos::ArrayView<const double> subshell_occupancies = \n    d_ace_epr_data->extractSubshellOccupancies();\n\n  // Extract the subshell binding energies\n  Teuchos::ArrayView<const double> subshell_binding_energies = \n    d_ace_epr_data->extractSubshellBindingEnergies();\n\n  // Extract the number of subshell vacancy transitions\n  Teuchos::ArrayView<const double> subshell_vacancy_transitions =\n    d_ace_epr_data->extractSubshellVacancyTransitionPaths();\n\n  // Extract the relo block\n  Teuchos::ArrayView<const double> relo_block = \n    d_ace_epr_data->extractRELOBlock();\n\n  // Assign the subshell data\n  for( unsigned i = 0; i < subshell_designators.size(); ++i )\n  {\n    data_container.setSubshellOccupancy( subshell_designators[i],\n\t\t\t\t\t subshell_occupancies[i] );\n    \n    data_container.setSubshellBindingEnergy( subshell_designators[i],\n\t\t\t\t\t     subshell_binding_energies[i] );\n    \n    unsigned transitions = (unsigned)subshell_vacancy_transitions[i];\n    \n    if( transitions > 0 )\n    {\n      data_container.setSubshellRelaxationTransitions( subshell_designators[i],\n\t\t\t\t\t\t       transitions );\n      \n      this->setTransitionData( subshell_designators[i],\n\t\t\t       transitions,\n\t\t\t       (unsigned)relo_block[i],\n\t\t\t       data_container );\n    }\n  }\n}\n\n// Set the transition data\nvoid StandardElectronPhotonRelaxationDataGenerator::setTransitionData(\n\t\t\t  const unsigned subshell,\n\t\t\t  const unsigned transitions,\n\t\t\t  const unsigned subshell_data_start_index,\n\t\t\t  Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t  data_container ) const\n{\n  // Make sure the number of transitions is valid\n  testPrecondition( transitions > 0 );\n\n  // Extract the xprob block\n  Teuchos::ArrayView<const double> xprob_block = \n    d_ace_epr_data->extractXPROBBlock();\n\n  std::vector<std::pair<unsigned,unsigned> > relaxation_vacancies( \n\t\t\t\t\t\t\t\t transitions );\n  std::vector<double> relaxation_particle_energies( transitions );\n  std::vector<double> relaxation_probabilities( transitions );\n  std::vector<double> relaxation_cdf( transitions );\n\n  for( unsigned j = 0; j < transitions; ++j )\n  {\n    // Extract the primary transition subshell vacancy\n    relaxation_vacancies[j].first = \n      (unsigned)xprob_block[subshell_data_start_index+j*4];\n\t\n    // Extract the secondary transition subshell vacancy\n    relaxation_vacancies[j].second = \n      (unsigned)xprob_block[subshell_data_start_index+j*4+1];\n    \n    // Extract the outgoing particle energies\n    relaxation_particle_energies[j] = \n      xprob_block[subshell_data_start_index+j*4+2];\n    \n    // Extract the transition cdf\n    relaxation_cdf[j] = xprob_block[subshell_data_start_index+j*4+3];\n    \n    // Convert the cdf value to a pdf value\n    if( j != 0 )\n      relaxation_probabilities[j] = relaxation_cdf[j]-relaxation_cdf[j-1];\n    else // j == 0\n      relaxation_probabilities[j] = relaxation_cdf[j];\n  }\n  \n  data_container.setSubshellRelaxationVacancies( subshell,\n\t\t\t\t\t\t relaxation_vacancies );\n  \n  data_container.setSubshellRelaxationParticleEnergies( \n\t\t\t\t\t\tsubshell,\n\t\t\t\t\t\trelaxation_particle_energies );\n\n  data_container.setSubshellRelaxationProbabilities(subshell,\n\t\t\t\t\t\t    relaxation_probabilities );\n}\n\n// Set the Compton profile data\nvoid StandardElectronPhotonRelaxationDataGenerator::setComptonProfileData( \n\t\t\t   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  const std::set<unsigned>& subshells = data_container.getSubshells();\n\n  std::set<unsigned>::const_iterator subshell = subshells.begin();\n  \n  while( subshell != subshells.end() )\n  {\n    // Extract the half profile from the ACE data\n    std::vector<double> half_momentum_grid, half_profile;\n\n    this->extractHalfComptonProfile( *subshell, \n\t\t\t\t     half_momentum_grid, \n\t\t\t\t     half_profile );\n\n    std::vector<double> full_momentum_grid, full_profile;\n    \n    MonteCarlo::createFullProfileFromHalfProfile( half_momentum_grid.begin(),\n\t\t\t\t\t\t  half_momentum_grid.end(),\n\t\t\t\t\t\t  half_profile.begin(),\n\t\t\t\t\t\t  half_profile.end(),\n\t\t\t\t\t\t  full_momentum_grid,\n\t\t\t\t\t\t  full_profile,\n\t\t\t\t\t\t  true,\n\t\t\t\t\t\t  true );\n    \n    MonteCarlo::convertMomentumGridToMeCUnits( full_momentum_grid.begin(),\n\t\t\t\t\t       full_momentum_grid.end() );\n\n    MonteCarlo::convertProfileToInverseMeCUnits( full_profile.begin(), \n\t\t\t\t\t\t full_profile.end());\n    \n    data_container.setComptonProfileMomentumGrid( *subshell,\n\t\t\t\t\t\t  full_momentum_grid );\n    \n    data_container.setComptonProfile( *subshell, full_profile );\n\n    ++subshell;\n  }\n}\n\n// Set the Occupation number data\nvoid StandardElectronPhotonRelaxationDataGenerator::setOccupationNumberData( \n\t\t\t   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  const std::set<unsigned>& subshells = data_container.getSubshells();\n\n  std::set<unsigned>::const_iterator subshell = subshells.begin();\n  \n  while( subshell != subshells.end() )\n  {\n    const std::vector<double>& momentum_grid = \n      data_container.getComptonProfileMomentumGrid( *subshell );\n\n    const std::vector<double>& compton_profile = \n      data_container.getComptonProfile( *subshell );\n    \n    // Create the occupation number evaluator\n    OccupationNumberEvaluator occupation_number_evaluator( \n\t\t\t\t    momentum_grid,\n\t\t\t\t    compton_profile,\n\t\t\t\t    d_occupation_number_evaluation_tolerance );\n\n    // Create the occupation number grid\n    boost::function<double (double pz)> grid_function = \n      boost::bind( &OccupationNumberEvaluator::evaluateOccupationNumber,\n\t\t   boost::cref( occupation_number_evaluator ),\n\t\t   _1,\n\t\t   d_occupation_number_evaluation_tolerance );\n\n    std::vector<double> occupation_number_momentum_grid( 3 ), \n      occupation_number;\n    occupation_number_momentum_grid[0] = -1.0;\n    occupation_number_momentum_grid[1] = 0.0;\n    occupation_number_momentum_grid[2] = 1.0;\n\n    Utility::GridGenerator<Utility::LinLin> occupation_number_grid_generator(\n\t\t\t\t\t\t      d_grid_convergence_tol,\n\t\t\t\t\t\t      d_grid_absolute_diff_tol,\n\t\t\t\t\t\t      d_grid_distance_tol );\n\n    occupation_number_grid_generator.generateAndEvaluateInPlace(\n\t\t\t\t\t       occupation_number_momentum_grid,\n\t\t\t\t\t       occupation_number,\n\t\t\t\t\t       grid_function );\n\n    // Fix the grid rounding errors\n    std::vector<double>::iterator unity_occupation = \n      std::find_if( occupation_number.begin(),\n\t\t    occupation_number.end(),\n\t\t    greaterThanOrEqualToOne );\n\n    while( unity_occupation != occupation_number.end() )\n    {\n      *unity_occupation = 1.0;\n\n      ++unity_occupation;\n    }\n\n    data_container.setOccupationNumberMomentumGrid( \n\t\t\t\t\t     *subshell, \n\t\t\t\t\t     occupation_number_momentum_grid );\n    data_container.setOccupationNumber( *subshell, occupation_number );\n    \n    ++subshell;\n  }\n}\n\n// Set the Waller-Hartree scattering function data\nvoid StandardElectronPhotonRelaxationDataGenerator::setWallerHartreeScatteringFunctionData(\n\t\t\t   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  Teuchos::ArrayView<const double> jince_block = \n    d_ace_epr_data->extractJINCEBlock();\n\n  unsigned scatt_func_size = jince_block.size()/2;\n\n  Teuchos::ArrayView<const double> raw_recoil_momentum(\n\t\t\t\t\t jince_block( 1, scatt_func_size-1 ) );\n\n  Teuchos::ArrayView<const double> raw_scattering_function(\n\t\t\t jince_block( scatt_func_size+1, scatt_func_size-1 ) );\n\n  std::vector<double> scaled_recoil_momentum;\n  \n  scaled_recoil_momentum.assign( raw_recoil_momentum.begin(),\n\t\t\t\t raw_recoil_momentum.end() );\n  \n  // Convert from inverse Angstroms to inverse cm\n  for( unsigned i = 0; i < scaled_recoil_momentum.size(); ++i )\n    scaled_recoil_momentum[i] *= 1e8;\n\n  Teuchos::RCP<Utility::OneDDistribution> scattering_function_dist( \n              new Utility::TabularDistribution<Utility::LogLog>( \n\t\t\t\t\t\t   scaled_recoil_momentum,\n\t\t\t\t\t\t   raw_scattering_function ) );\n\n  boost::function<double (double x)> grid_function = \n    boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t boost::cref( *scattering_function_dist ),\n\t\t _1 );\n\n  Utility::GridGenerator<Utility::LinLin> \n    scattering_func_grid_generator( d_grid_convergence_tol,\n\t\t\t\t    d_grid_absolute_diff_tol,\n\t\t\t\t    d_grid_distance_tol );\n\n  std::list<double> recoil_momentum_grid, scattering_function;\n  recoil_momentum_grid.push_back( scaled_recoil_momentum.front() );\n  recoil_momentum_grid.push_back( scaled_recoil_momentum.back() );\n\n  scattering_func_grid_generator.generateAndEvaluateInPlace( \n\t\t\t\t\t\t\t  recoil_momentum_grid,\n\t\t\t\t\t\t\t  scattering_function,\n\t\t\t\t\t\t\t  grid_function );\n\n  recoil_momentum_grid.push_front( jince_block[0]*1e8 );\n  scattering_function.push_front( jince_block[scatt_func_size] );\n\n  std::vector<double> refined_recoil_momentum, refined_scattering_function;\n  \n  refined_recoil_momentum.assign( recoil_momentum_grid.begin(),\n\t\t\t\t  recoil_momentum_grid.end() );\n\n  refined_scattering_function.assign( scattering_function.begin(),\n\t\t\t\t      scattering_function.end() );\n\n  data_container.setWallerHartreeScatteringFunctionMomentumGrid(\n\t\t\t\t\t\t     refined_recoil_momentum );\n  data_container.setWallerHartreeScatteringFunction( \n\t\t\t\t\t\t refined_scattering_function );\n}\n\n// Set the Waller-Hartree atomic form factor data\nvoid StandardElectronPhotonRelaxationDataGenerator::setWallerHartreeAtomicFormFactorData(\n\t\t\t   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  Teuchos::ArrayView<const double> jcohe_block = \n    d_ace_epr_data->extractJCOHEBlock();\n  \n  unsigned form_factor_size = jcohe_block.size()/3;\n\n  Teuchos::ArrayView<const double> raw_recoil_momentum( \n\t\t\t\t\tjcohe_block( 1, form_factor_size-1 ) );\n\n  Teuchos::ArrayView<const double> raw_form_factor(\n\t\t     jcohe_block( 2*form_factor_size+1, form_factor_size-1 ) );\n  \n  std::vector<double> scaled_recoil_momentum;\n\n  scaled_recoil_momentum.assign( raw_recoil_momentum.begin(),\n\t\t\t\t raw_recoil_momentum.end() );\n\n  // Convert from inverse Angstroms to inverse cm\n  for( unsigned i = 0; i < scaled_recoil_momentum.size(); ++i )\n    scaled_recoil_momentum[i] *= 1e8;\n\n  Teuchos::RCP<Utility::OneDDistribution> form_factor_dist(\n\t\t\t    new Utility::TabularDistribution<Utility::LogLog>(\n\t\t\t\t\t\t        scaled_recoil_momentum,\n\t\t\t\t\t\t\traw_form_factor ) );\n\n  boost::function<double (double x)> grid_function = \n    boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t boost::cref( *form_factor_dist ),\n\t\t _1 );\n\n  Utility::GridGenerator<Utility::LinLin>\n    form_factor_grid_generator( d_grid_convergence_tol,\n\t\t\t\td_grid_absolute_diff_tol,\n\t\t\t\td_grid_distance_tol );\n\n  std::list<double> recoil_momentum_grid, form_factor;\n  recoil_momentum_grid.push_back( scaled_recoil_momentum.front() );\n  recoil_momentum_grid.push_back( scaled_recoil_momentum.back() );\n\n  form_factor_grid_generator.generateAndEvaluateInPlace( recoil_momentum_grid,\n\t\t\t\t\t\t\t form_factor,\n\t\t\t\t\t\t\t grid_function );\n\n  recoil_momentum_grid.push_front( jcohe_block.front()*1e8 );\n  recoil_momentum_grid.push_back( jcohe_block[form_factor_size-1]*1e8 );\n  \n  form_factor.push_front( jcohe_block[2*form_factor_size] );\n  form_factor.push_back( jcohe_block.back() );\n\n  std::vector<double> refined_recoil_momentum, refined_form_factor;\n\n  refined_recoil_momentum.assign( recoil_momentum_grid.begin(),\n\t\t\t\t  recoil_momentum_grid.end() );\n\n  refined_form_factor.assign( form_factor.begin(),\n\t\t\t      form_factor.end() );\n  \n  data_container.setWallerHartreeAtomicFormFactorMomentumGrid(\n\t\t\t\t\t\t     refined_recoil_momentum );\n  data_container.setWallerHartreeAtomicFormFactor( refined_form_factor );\n}\n\n// Set the photon data\nvoid StandardElectronPhotonRelaxationDataGenerator::setPhotonData( \n\t\t\t   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  // Extract the heating numbers\n  Teuchos::RCP<const Utility::OneDDistribution> heating_numbers;\n\n  this->extractCrossSection<Utility::LinLog>( \n\t\t\t\t     d_ace_epr_data->extractPhotonEnergyGrid(),\n\t\t\t\t     d_ace_epr_data->extractLHNMBlock(),\n\t\t\t\t     heating_numbers );\n\n  // Extract the Waller-Hartree incoherent cross section\n  Teuchos::RCP<const Utility::OneDDistribution> waller_hartree_incoherent_cs;\n\n  this->extractCrossSection<Utility::LogLog>( \n\t\t\t       d_ace_epr_data->extractPhotonEnergyGrid(),\n\t\t\t       d_ace_epr_data->extractIncoherentCrossSection(),\n\t\t\t       waller_hartree_incoherent_cs );\n\n  // Extract the Waller-Hartree coherent cross section\n  Teuchos::RCP<const Utility::OneDDistribution> waller_hartree_coherent_cs;\n\n  this->extractCrossSection<Utility::LogLog>( \n\t\t\t\t d_ace_epr_data->extractPhotonEnergyGrid(),\n\t\t\t\t d_ace_epr_data->extractCoherentCrossSection(),\n\t\t\t\t waller_hartree_coherent_cs );\n\n  // Extract the pair production cross section\n  Teuchos::RCP<const Utility::OneDDistribution> pair_production_cs;\n\n  this->extractCrossSection<Utility::LogLog>(\n\t\t\t   d_ace_epr_data->extractPhotonEnergyGrid(),\n\t\t\t   d_ace_epr_data->extractPairProductionCrossSection(),\n\t\t\t   pair_production_cs );\n\n  // Extract the subshell photoelectric effect cross sections\n  Teuchos::Array<std::pair<unsigned,Teuchos::RCP<const Utility::OneDDistribution> > >\n    subshell_photoelectric_effect_css;\n\n  this->extractSubshellPhotoelectricCrossSections( \n\t\t\t\t\t   subshell_photoelectric_effect_css );\n  \n  // Create the impulse approx. incoherent cross section evaluators\n  Teuchos::Array<std::pair<unsigned,Teuchos::RCP<const MonteCarlo::SubshellIncoherentPhotonScatteringDistribution> > > \n    impulse_approx_incoherent_cs_evaluators;\n  \n  this->createSubshellImpulseApproxIncoherentCrossSectionEvaluators(\n\t\t\t\t     data_container,\n\t\t\t\t     impulse_approx_incoherent_cs_evaluators );\n\n  // Create the union energy grid\n  std::cout << \" Creating union energy grid\";\n  std::cout.flush();\n  std::list<double> union_energy_grid;\n  \n  this->initializePhotonUnionEnergyGrid( data_container, union_energy_grid );\n\n  Utility::GridGenerator<Utility::LinLin> \n    union_energy_grid_generator( d_grid_convergence_tol,\n\t\t\t\t d_grid_absolute_diff_tol,\n\t\t\t\t d_grid_distance_tol );\n  \n  // Calculate the union energy grid\n  boost::function<double (double pz)> grid_function = \n    boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t boost::cref( *heating_numbers ),\n\t\t _1 );\n\n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n\t\t\t\t\t       grid_function );\n  std::cout << \".\";\n  std::cout.flush();\n  \n  grid_function = boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t\t       boost::cref( *waller_hartree_incoherent_cs ),\n\t\t\t       _1 );\n\n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n\t\t\t\t\t       grid_function );\n  std::cout << \".\";\n  std::cout.flush();\n  \n  grid_function = boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t\t       boost::cref( *waller_hartree_coherent_cs ),\n\t\t\t       _1 );\n  \n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n\t\t\t\t\t       grid_function );\n  std::cout << \".\";\n  std::cout.flush();\n  \n  grid_function = boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t\t       boost::cref( *pair_production_cs ),\n\t\t\t       _1 );\n\n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n\t\t\t\t\t       grid_function );\n  std::cout << \".\";\n  std::cout.flush();\n  \n  for( unsigned i = 0; i < subshell_photoelectric_effect_css.size(); ++i )\n  {\n    grid_function = boost::bind( \n\t\t   &Utility::OneDDistribution::evaluate,\n\t\t   boost::cref( *subshell_photoelectric_effect_css[i].second ),\n\t\t   _1 );\n\n    union_energy_grid_generator.generateInPlace( union_energy_grid,\n\t\t\t\t\t\t grid_function );\n    std::cout << \".\";\n    std::cout.flush();\n  }\n\n  for( unsigned i = 0; i < impulse_approx_incoherent_cs_evaluators.size(); ++i)\n  {\n    grid_function = boost::bind(\n\t     &MonteCarlo::SubshellIncoherentPhotonScatteringDistribution::evaluateIntegratedCrossSection,\n\t     boost::cref( *impulse_approx_incoherent_cs_evaluators[i].second ),\n\t     _1,\n\t     d_subshell_incoherent_evaluation_tolerance );\n\n    union_energy_grid_generator.generateInPlace( union_energy_grid,\n\t\t\t\t\t\t grid_function );\n    std::cout << \".\";\n    std::cout.flush();\n  }\n  \n  std::cout << \"done.\" << std::endl;\n\n  // Set the union energy grid\n  std::vector<double> energy_grid;\n  energy_grid.assign( union_energy_grid.begin(),\n\t\t      union_energy_grid.end() );\n  \n  data_container.setPhotonEnergyGrid( energy_grid );\n\n  // Create and set the cross sections\n  std::vector<double> cross_section;\n  unsigned threshold;\n\n  std::cout << \" Setting the average heating numbers...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n\t\t\t\t\t     heating_numbers,\n\t\t\t\t\t     cross_section,\n\t\t\t\t\t     threshold );\n\n  data_container.setAveragePhotonHeatingNumbers( cross_section );\n  std::cout << \"done.\" << std::endl;\n  \n  std::cout << \" Setting the Waller-Hartree incoherent cross section...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n\t\t\t\t\t     waller_hartree_incoherent_cs,\n\t\t\t\t\t     cross_section,\n\t\t\t\t\t     threshold );\n  \n  data_container.setWallerHartreeIncoherentCrossSection( cross_section );\n  data_container.setWallerHartreeIncoherentCrossSectionThresholdEnergyIndex( \n\t\t\t\t\t\t\t\t   threshold );\n  std::cout << \"done.\" << std::endl;\n\n  std::cout << \" Setting the Waller-Hartree coherent cross section...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n\t\t\t\t\t     waller_hartree_coherent_cs,\n\t\t\t\t\t     cross_section,\n\t\t\t\t\t     threshold );\n\n  data_container.setWallerHartreeCoherentCrossSection( cross_section );\n  data_container.setWallerHartreeCoherentCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t\t\t   threshold );\n  std::cout << \"done.\" << std::endl;\n\n  std::cout << \" Setting the pair production cross section...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n\t\t\t\t\t     pair_production_cs,\n\t\t\t\t\t     cross_section,\n\t\t\t\t\t     threshold );\n\n  data_container.setPairProductionCrossSection( cross_section );\n  data_container.setPairProductionCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t\t\t   threshold );\n  std::cout << \"done.\" << std::endl;\n  \n  for( unsigned i = 0; i < subshell_photoelectric_effect_css.size(); ++i )\n  {\n    std::cout << \" Setting subshell \" \n\t      << subshell_photoelectric_effect_css[i].first \n\t      << \" photoelectric cross section...\";\n    std::cout.flush();\n    this->createCrossSectionOnUnionEnergyGrid( \n\t\t\t\t   union_energy_grid,\n\t\t\t\t   subshell_photoelectric_effect_css[i].second,\n\t\t\t\t   cross_section,\n\t\t\t\t   threshold );\n\n    data_container.setSubshellPhotoelectricCrossSection( \n\t\t\t\t    subshell_photoelectric_effect_css[i].first,\n\t\t\t\t    cross_section );\n    data_container.setSubshellPhotoelectricCrossSectionThresholdEnergyIndex(\n\t\t\t\t    subshell_photoelectric_effect_css[i].first,\n\t\t\t\t    threshold );\n    std::cout << \"done.\" << std::endl;\n  }\n  \n  for( unsigned i = 0; i < impulse_approx_incoherent_cs_evaluators.size(); ++i)\n  {\n    std::cout << \" Setting subshell \"\n\t      << impulse_approx_incoherent_cs_evaluators[i].first\n\t      << \" impusle approx incoherent cross section...\";\n    std::cout.flush();\n    this->createCrossSectionOnUnionEnergyGrid(\n\t\t\t     union_energy_grid,\n\t\t\t     impulse_approx_incoherent_cs_evaluators[i].second,\n\t\t\t     cross_section,\n\t\t\t     threshold );\n\n    data_container.setImpulseApproxSubshellIncoherentCrossSection(\n\t\t\t      impulse_approx_incoherent_cs_evaluators[i].first,\n\t\t\t      cross_section );\n    data_container.setImpulseApproxSubshellIncoherentCrossSectionThresholdEnergyIndex(\n\t\t\t      impulse_approx_incoherent_cs_evaluators[i].first,\n\t\t\t      threshold );\n    std::cout << \"done.\" << std::endl;\n  }\n  \n  std::cout << \" Setting the total photoelectric cross section...\";\n  std::cout.flush();\n  this->calculateTotalPhotoelectricCrossSection( data_container );\n  std::cout << \"done.\" << std::endl;\n  \n  std::cout << \" Setting the impulse approx total incoherent cross section...\";\n  std::cout.flush();\n  this->calculateImpulseApproxTotalIncoherentCrossSection( data_container );\n  std::cout << \"done.\" << std::endl;\n\n  std::cout << \" Setting the Waller-Hartree total cross section...\";\n  std::cout.flush();\n  this->calculateWallerHartreeTotalCrossSection( data_container );\n  std::cout << \"done.\" << std::endl;\n\n  std::cout << \" Setting the impulse approx total cross section...\";\n  std::cout.flush();\n  this->calculateImpulseApproxTotalCrossSection( data_container );\n  std::cout << \"done.\" << std::endl;\n}\n\n\n// Process EEDL file\n/*! \\details This function uses the Data::ENDLFileHandler to read the\n * EEDL data file. The data that is read is then processed into an appropriate\n * format and finally stored in the necessary HDF5 file. \n */\nvoid StandardElectronPhotonRelaxationDataGenerator::setElectronData( \n    Data::ElectronPhotonRelaxationVolatileDataContainer& data_container ) const\n{ \n  // Information in first header of the EEDL file\n  int atomic_number_in_table, \n      outgoing_particle_designator, \n      interpolation_flag;\n  double atomic_weight;\n\n  // Information in the second header of the EEDL file\n  int reaction_type, electron_shell;\n  unsigned subshell_endf;\n\n  // array of all the subshells read\n  std::set<unsigned> endf_subshells = data_container.getSubshells();\n\n  // cross sections in the file\n  Teuchos::RCP<const Utility::OneDDistribution>  \n        bremsstrahlung_cross_section, atomic_excitation_cross_section,\n        cutoff_elastic_cross_section, total_elastic_cross_section;\n\n  Teuchos::Array<std::pair<unsigned,Teuchos::RCP<const Utility::OneDDistribution> > >\n        electroionization_cross_section;\n\n  // The elastic angular distribution energy grid and pdf\n  std::vector<double> elastic_energy_grid;\n  std::map<double,std::vector<double> > elastic_pdf;\n\n  // Initialize union energy grid\n  std::list<double> union_energy_grid;\n  union_energy_grid.push_back( d_min_electron_energy );\n  union_energy_grid.push_back( d_max_electron_energy );\n\n\n  std::cout << \" Reading EEDL Data file\";\n  std::cout.flush();\n\n  // Process every table in the EEDL file\n  while( d_eedl_file_handler->validFile() && !d_eedl_file_handler->endOfFile() )\n  {\n    // Read first table header and determine which element is being processed\n    d_eedl_file_handler->readFirstTableHeader( atomic_number_in_table,\n                                              outgoing_particle_designator,\n                                              atomic_weight,\n                                              interpolation_flag );\n    \n    // Check that the EEDL file is still valid (eof has not been reached)\n    if( d_eedl_file_handler->endOfFile() )\n    {\n\t  continue;\n    }\n      \n    testPostcondition( atomic_number_in_table == \n                       data_container.getAtomicNumber() );\n\n    // Read second table header and determine the reaction type\n    d_eedl_file_handler->readSecondTableHeader( reaction_type,\n                                                electron_shell );\n\n    if ( electron_shell > 0 )\n    {\n      // Convert subshell number to endf number\n      subshell_endf = \n        MonteCarlo::convertEADLDesignatorToENDFDesignator( electron_shell );\n\n      // Check that subshell is valid\n      testPrecondition( endf_subshells.count( subshell_endf ) );\n      \n    }\n\n    // Read and process the data in the current table, then store in the HDF5\n    // file\n    switch( reaction_type )\n    {\n  \n    case 7000:\n      // Integrated elastic transport cross section data - ignored\n      \n      d_eedl_file_handler->skipTable();\n\n      std::cout << \".\";\n      std::cout.flush();   \n      break;\n\n    case 8000:\n    {\n      // Interpolation should always be LogLog = 5 \n      testPrecondition( interpolation_flag == 5 )\n\n      // Extract in the integrated large angle scattering cross section data\n      std::vector<double> raw_energy_grid, raw_cross_section;\n      d_eedl_file_handler->processTwoColumnTable( raw_energy_grid, \n                                                  raw_cross_section );\n\n      this->extractElectronCrossSection<Utility::LogLog>( \n                raw_energy_grid,\n                raw_cross_section,\n                cutoff_elastic_cross_section );\n\n      // merge raw energy grid with the union energy grid\n      mergeElectronUnionEnergyGrid( raw_energy_grid, union_energy_grid );\n\n\n      std::cout << \".\";\n      std::cout.flush();     \n      break;\n    }\n    case 8011:\n      // Average energy to residual atom from elastic scattering - ignored\n      \n      d_eedl_file_handler->skipTable();\n\n      std::cout << \".\";\n      std::cout.flush(); \n      break;\n\n    case 8010:\n      // Average energy of scattered electron from elastic scattering - ignored\n      \n      d_eedl_file_handler->skipTable();\n\n      std::cout << \".\";\n      std::cout.flush();    \n      break;\n\n\n    case 8022:\n    {\n      // Read in the elastic angular distribution of the scattered electron data\n\n      // Interpolation should always be LinLin = 0 \n      testPrecondition( interpolation_flag == 0 )\n\n      std::map<double,std::vector<double> > elastic_angle;\n\n      d_eedl_file_handler->processThreeColumnTable( \n            elastic_energy_grid, \n            elastic_angle,\n            elastic_pdf );\n\n      data_container.setElasticAngularEnergyGrid( elastic_energy_grid );\n      data_container.setAnalogElasticAngles( elastic_angle );\n      data_container.setAnalogElasticPDF( elastic_pdf ); \n\n      std::cout << \".\";\n      std::cout.flush(); \n      break;\n    }\n    case 10000:\n    {\n      // Extract in the integrated total elastic cross section data\n\n      // Interpolation should always be LogLog = 5 \n      testPrecondition( interpolation_flag == 5 )\n\n      std::vector<double> raw_energy_grid, raw_cross_section;\n      d_eedl_file_handler->processTwoColumnTable( raw_energy_grid, \n                                                  raw_cross_section );\n\n      this->extractElectronCrossSection<Utility::LogLog>( \n                raw_energy_grid,\n                raw_cross_section,\n                total_elastic_cross_section );\n\n      // merge raw energy grid with the union energy grid\n      mergeElectronUnionEnergyGrid( raw_energy_grid, union_energy_grid );\n\n      std::cout << \".\";\n      std::cout.flush(); \n      break;\n    }\n    case 81000:\n    {\n      // Extract the integrated ionization cross section\n\n      // Interpolation should always be LinLin = 0 \n      testPrecondition( interpolation_flag == 0 )\n\n      std::vector<double> raw_energy_grid, raw_cross_section;\n      d_eedl_file_handler->processTwoColumnTable( raw_energy_grid, \n                                                  raw_cross_section );\n\n      Teuchos::RCP<const Utility::OneDDistribution> subshell_cross_section;\n\n      this->extractElectronCrossSection<Utility::LinLin>( \n                raw_energy_grid,\n                raw_cross_section,\n                subshell_cross_section );\n\n      // merge raw energy grid with the union energy grid\n      mergeElectronUnionEnergyGrid( raw_energy_grid, union_energy_grid );\n\n      std::pair<unsigned,Teuchos::RCP<const Utility::OneDDistribution> >\n        cross_section_pair( subshell_endf, subshell_cross_section );\n\n      electroionization_cross_section.push_back( cross_section_pair );\n\n\n      std::cout << \".\";\n      std::cout.flush();     \n      break;\n    }\n    case 81010:\n\n      // Average energy of electron from ionization - ignored\n      // ( Yo == 9 )\n      // Average energy of secondary electron from ionization - ignored\n      // ( Yo == 19 )\n\n      d_eedl_file_handler->skipTable();\n\n      std::cout << \".\";\n      std::cout.flush(); \n      break;\n\n    case 81021:\n    {\n      // Interpolation should always be LinLin = 0 \n      testPrecondition( interpolation_flag == 0 )\n      // The outgoing particle designator should be electron as recoil (19)\n      testPrecondition( outgoing_particle_designator == 19 );\n\n      std::vector<double> electron_energy_grid;\n      std::map<double,std::vector<double> > electroionization_recoil_energy,\n                                            electroionization_recoil_pdf;\n\n      // Read the recoil electron spectrum from ionization for a subshell\n      // If electron_shell == 0 then no subshell data only total\n\n      d_eedl_file_handler->processThreeColumnTable( \n            electron_energy_grid, \n            electroionization_recoil_energy,\n            electroionization_recoil_pdf );  \n\n\n      data_container.setElectroionizationEnergyGrid( \n                        subshell_endf,\n                        electron_energy_grid );\n\n      data_container.setElectroionizationRecoilEnergy( \n                        subshell_endf,\n                        electroionization_recoil_energy );\n\n      data_container.setElectroionizationRecoilPDF( \n                        subshell_endf,\n                        electroionization_recoil_pdf );\n\n      std::cout << \".\";\n      std::cout.flush(); \n      break;\n    }\n    case 82000:\n    {\n      // Interpolation should always be LinLin = 0 \n      testPrecondition( interpolation_flag == 0 )\n\n      // Extract the integrated bremsstrahlung cross section\n      std::vector<double> raw_energy_grid, raw_cross_section;\n      d_eedl_file_handler->processTwoColumnTable( raw_energy_grid, \n                                                  raw_cross_section );\n\n      this->extractElectronCrossSection<Utility::LinLin>( \n                raw_energy_grid,\n                raw_cross_section,\n                bremsstrahlung_cross_section );\n\n      // merge raw energy grid with the union energy grid\n      mergeElectronUnionEnergyGrid( raw_energy_grid, union_energy_grid );\n\n      std::cout << \".\";\n      std::cout.flush();     \n      break;\n    }\n    case 82010:\n      // Average energy of secondary photon from bremsstrahlung - ignored\n      // ( Yo == 7 )\n      // Average energy of secondary electron from bremsstrahlung - ignored\n      // ( Yo == 9 )\n      \n      d_eedl_file_handler->skipTable();\n\n      std::cout << \".\";\n      std::cout.flush(); \n      break;\n\n    case 82021:\n    {\n      // Read the sprectrum of the secondary photon from bremsstrahlung\n\n      // Interpolation should always be LinLin = 0 \n      testPrecondition( interpolation_flag == 0 )\n      // The outgoing particle designator should be photon (7)\n      testPrecondition( outgoing_particle_designator == 7 );\n\n      std::vector<double> electron_energy_grid;\n      std::map<double,std::vector<double> > bremsstrahlung_photon_energy,\n                                            bremsstrahlung_photon_pdf;\n\n      d_eedl_file_handler->processThreeColumnTable( \n            electron_energy_grid, \n            bremsstrahlung_photon_energy,\n            bremsstrahlung_photon_pdf );  \n\n      data_container.setBremsstrahlungEnergyGrid( electron_energy_grid );\n\n      data_container.setBremsstrahlungPhotonEnergy( \n                        bremsstrahlung_photon_energy );\n\n      data_container.setBremsstrahlungPhotonPDF( \n                        bremsstrahlung_photon_pdf );\n\n      std::cout << \".\";\n      std::cout.flush();    \n      break;\n    }\n    case 83000:\n    {\n      // Extract the integrated excitation cross section\n\n      // Interpolation should always be LinLin = 0 \n      testPrecondition( interpolation_flag == 0 )\n\n      std::vector<double> raw_energy_grid, raw_cross_section;\n      d_eedl_file_handler->processTwoColumnTable( raw_energy_grid, \n                                                  raw_cross_section );\n\n      this->extractElectronCrossSection<Utility::LinLin>( \n                raw_energy_grid,\n                raw_cross_section,\n                atomic_excitation_cross_section );\n\n      // merge raw energy grid with the union energy grid\n      mergeElectronUnionEnergyGrid( raw_energy_grid, union_energy_grid );\n\n      std::cout << \".\";\n      std::cout.flush(); \n      break;\n    }\n    case 83011:\n    {\n      // Read the average energy loss from excitation\n      testPrecondition( interpolation_flag == 0 );\n\n      std::vector<double> atomic_excitation_energy_grid, \n                          atomic_excitation_energy_loss; \n\n      d_eedl_file_handler->processTwoColumnTable( \n            atomic_excitation_energy_grid, \n            atomic_excitation_energy_loss );\n\n      data_container.setAtomicExcitationEnergyGrid( \n            atomic_excitation_energy_grid );\n\n      data_container.setAtomicExcitationEnergyLoss( \n            atomic_excitation_energy_loss );\n\n      std::cout << \".\";\n      std::cout.flush();     \n      break;\n    }\n    default:\n      // Unknown reaction type found\n      {\n\tbool known_reaction_type = false;\n\tstd::cout << known_reaction_type <<\n    \" Fatal Error: An unknown reaction type was encountered while processing the EEDL file.\";\n    std::cout.flush();\n      }\n      break;\n    }\n  }\n  // Close the EEDL file\n  d_eedl_file_handler->closeENDLFile();\n\n  std::cout << \"done.\" << std::endl;\n\n/*\n  // Set the screened Rutherford cross section data\n  setScreenedRutherfordData( cutoff_elastic_cross_section, \n                             total_elastic_cross_section,\n                             elastic_energy_grid, \n                             elastic_pdf,\n                             data_container );\n*/\n  // Create the union energy grid\n  std::cout << \" Creating union energy grid\";\n  std::cout.flush();\n\n\n  Utility::GridGenerator<Utility::LinLin> \n    union_energy_grid_generator( d_grid_convergence_tol,\n                                 d_grid_absolute_diff_tol,\n                                 d_grid_distance_tol );\n  \n  // Calculate the union energy grid\n  boost::function<double (double pz)> grid_function = \n    boost::bind( &Utility::OneDDistribution::evaluate,\n                 boost::cref( *cutoff_elastic_cross_section ),\n                 _1 );\n\n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n                                               grid_function );\n\n  std::cout << \".\";\n  std::cout.flush(); \n  \n  grid_function = boost::bind( \n        &Utility::OneDDistribution::evaluate,\n        boost::cref( *total_elastic_cross_section ),\n        _1 );\n  \n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n                                               grid_function );\n  std::cout << \".\";\n  std::cout.flush(); \n\n  grid_function = boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t\t                   boost::cref( *bremsstrahlung_cross_section ),\n\t\t\t                   _1 );\n  \n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n                                               grid_function );\n  std::cout << \".\";\n  std::cout.flush();\n\n  grid_function = boost::bind( &Utility::OneDDistribution::evaluate,\n\t\t\t                   boost::cref( *atomic_excitation_cross_section ),\n\t\t\t                   _1 );\n\n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n                                               grid_function );\n  std::cout << \".\";\n  std::cout.flush(); \n\n  for( unsigned i = 0; i < electroionization_cross_section.size(); ++i )\n  {\n    grid_function = boost::bind( \n\t\t   &Utility::OneDDistribution::evaluate,\n\t\t   boost::cref( *electroionization_cross_section[i].second ),\n\t\t   _1 );\n\n  union_energy_grid_generator.generateInPlace( union_energy_grid,\n                                               grid_function );\n    std::cout << \".\";\n    std::cout.flush();\n  }\n\n  std::cout << \"done.\" << std::endl;\n\n  // Set the union energy grid\n  std::vector<double> energy_grid;\n  energy_grid.assign( union_energy_grid.begin(),\n                      union_energy_grid.end() );\n  \n  data_container.setElectronEnergyGrid( energy_grid );\n\n\n  // Create and set the cross sections\n  std::vector<double> cross_section;\n  unsigned threshold;\n\n  {\n  // Set Elastic cross section data\n  std::vector<double> cutoff_cross_section, total_cross_section;\n\n  std::cout << \" Setting the cutoff elastic cross section...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n                                             cutoff_elastic_cross_section,\n                                             cutoff_cross_section,\n                                             threshold );\n  data_container.setCutoffElasticCrossSection( cutoff_cross_section );\n  data_container.setCutoffElasticCrossSectionThresholdEnergyIndex( threshold ); \n  std::cout << \"done.\" << std::endl;\n\n\n  std::cout << \" Setting the screened Rutherford elastic cross section...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n                                             total_elastic_cross_section,\n                                             total_cross_section,\n                                             threshold );\n\n  std::vector<double> raw_cross_section( total_cross_section.size() );\n  for ( int i = 0; i < total_cross_section.size(); ++i )\n  {\n    raw_cross_section[i] = total_cross_section[i] - cutoff_cross_section[i];\n\n    double relative_difference = raw_cross_section[i]/total_cross_section[i];\n    \n    // Check for roundoff error and reduce to zero if needed\n    if ( relative_difference < 1.0e-6 )\n    {\n      raw_cross_section[i] = 0.0;\n \n      // Update threshold index\n      threshold = i+1;\n    } \n  }\n\n  std::vector<double>::iterator start = raw_cross_section.begin();\n  std::advance( start, threshold );\n\n  cross_section.assign( start, raw_cross_section.end() );\n\n  data_container.setScreenedRutherfordElasticCrossSection( cross_section );\n  data_container.setScreenedRutherfordElasticCrossSectionThresholdEnergyIndex( \n    threshold ); \n  std::cout << \"done.\" << std::endl;\n  }\n\n\n  std::cout << \" Setting the bremsstrahlung cross section...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n                                             bremsstrahlung_cross_section,\n                                             cross_section,\n                                             threshold );\n\n  data_container.setBremsstrahlungCrossSection( cross_section );\n  data_container.setBremsstrahlungCrossSectionThresholdEnergyIndex( threshold ); \n  std::cout << \"done.\" << std::endl;\n\n\n  std::cout << \" Setting the atomic excitation cross section...\";\n  std::cout.flush();\n  this->createCrossSectionOnUnionEnergyGrid( union_energy_grid,\n                                             atomic_excitation_cross_section,\n                                             cross_section,\n                                             threshold );\n\n  data_container.setAtomicExcitationCrossSection( cross_section );\n  data_container.setAtomicExcitationCrossSectionThresholdEnergyIndex( \n                    threshold ); \n  std::cout << \"done.\" << std::endl;\n  \n\n  for( unsigned i = 0; i < electroionization_cross_section.size(); ++i )\n  {\n    std::cout << \" Setting subshell \" \n\t      << electroionization_cross_section[i].first \n\t      << \" electroionization cross section...\";\n    std::cout.flush();\n    this->createCrossSectionOnUnionEnergyGrid( \n\t\t\t\t   union_energy_grid,\n\t\t\t\t   electroionization_cross_section[i].second,\n\t\t\t\t   cross_section,\n\t\t\t\t   threshold );\n\n    data_container.setElectroionizationCrossSection( \n\t\t\t\t    electroionization_cross_section[i].first,\n\t\t\t\t    cross_section );\n    data_container.setElectroionizationCrossSectionThresholdEnergyIndex(\n\t\t\t\t    electroionization_cross_section[i].first,\n\t\t\t\t    threshold );\n    std::cout << \"done.\" << std::endl;\n  }\n}\n\n\n// Set the screened rutherford data\nvoid StandardElectronPhotonRelaxationDataGenerator::setScreenedRutherfordData( \n    const Teuchos::RCP<const Utility::OneDDistribution>& \n        cutoff_elastic_cross_section, \n    const Teuchos::RCP<const Utility::OneDDistribution>& \n        total_elastic_cross_section,\n    const std::vector<double>& elastic_energy_grid,\n    const std::map<double,std::vector<double> >& elastic_pdf,\n    Data::ElectronPhotonRelaxationVolatileDataContainer& data_container ) const\n{\n  // Calculate Moliere's screening constant and the screened rutherford normalization constant\n  std::vector<double> moliere_screening_constant, \n                      screened_rutherford_normalization_constant;\n  \n  // iterate through all angular energy bins\n  for ( int i = 0; i < elastic_energy_grid.size(); ++i )\n  {\n    // get the angular energy bin\n    double energy = elastic_energy_grid[i];\n\n    // get the screened rutherford cross section\n    double sr_cross_section = \n        ( total_elastic_cross_section->evaluate( energy ) -\n        cutoff_elastic_cross_section->evaluate( energy ) );\n\n    if ( sr_cross_section == 0.0 )\n    {\n    /* in order to not calculate negative the screened Rutherford cross section\n     * must be greater than ( cutoff_pdf*cutoff_angle ). It should also be small\n     * enough to give a negligable contribution to the overall cross section.\n     * This can be accomplished by setting eta slightly greater then the cutoff\n     * angle.\n     */\n    // get the pdf value at the cutoff angle for the given energy\n    double cutoff_pdf = elastic_pdf.find( energy )->second.front(); \n\n    // calculate Moliere's screening constant\n    moliere_screening_constant.push_back( 1.01*d_cutoff_angle );\n\n    // calculate the screened rutherford normalization constant\n    screened_rutherford_normalization_constant.push_back( cutoff_pdf*\n        ( 2.01*d_cutoff_angle )*( 2.01*d_cutoff_angle ) );\n    }\n    else\n    {\n    // get the pdf value at the cutoff angle for the given energy\n    double cutoff_pdf = elastic_pdf.find( energy )->second.front(); \n\n    // calculate Moliere's screening constant\n    moliere_screening_constant.push_back( d_cutoff_angle/( \n        sr_cross_section/( d_cutoff_angle*cutoff_pdf ) - 1.0 ) );\n\n    // calculate the screened rutherford normalization constant\n    screened_rutherford_normalization_constant.push_back( cutoff_pdf*( \n        ( d_cutoff_angle + moliere_screening_constant.back() )* \n        ( d_cutoff_angle + moliere_screening_constant.back() ) ) );\n    }\n  }\n  // Set Moliere's screening constant\n  data_container.setMoliereScreeningConstant( moliere_screening_constant );\n\n  // Set the screened rutherford normalization constant\n  data_container.setScreenedRutherfordNormalizationConstant( \n    screened_rutherford_normalization_constant );  \n}\n\n// Extract the half Compton profile from the ACE table\nvoid StandardElectronPhotonRelaxationDataGenerator::extractHalfComptonProfile( \n\t\t\t\t      const unsigned subshell,\n\t\t\t\t      std::vector<double>& half_momentum_grid,\n\t\t\t\t      std::vector<double>& half_profile ) const\n{\n  // Extract the raw Compton profile data\n  Teuchos::ArrayView<const double> lswd_block = \n    d_ace_epr_data->extractLSWDBlock();\n\n  Teuchos::ArrayView<const double> swd_block = \n    d_ace_epr_data->extractSWDBlock();\n  \n  // Create the Compton profile subshell converter for this\n  Teuchos::RCP<MonteCarlo::ComptonProfileSubshellConverter> converter;\n  \n  MonteCarlo::ComptonProfileSubshellConverterFactory::createConverter(\n\t\t\t\t\t\t     converter,\n\t\t\t\t\t\t     this->getAtomicNumber() );\n  \n  unsigned compton_subshell_index = converter->convertSubshellToIndex(\n\t\t\t      MonteCarlo::convertENDFDesignatorToSubshellEnum( \n\t\t\t\t\t\t\t\t  subshell ) );\n    \n  unsigned profile_index = lswd_block[compton_subshell_index];\n  \n  unsigned grid_size = swd_block[profile_index];\n  \n  // Extract the profile\n  Teuchos::ArrayView<const double> raw_compton_profile_momentum_grid = \n    swd_block( profile_index + 1, grid_size );\n  \n  Teuchos::ArrayView<const double> raw_compton_profile = \n    swd_block( profile_index + 1 + grid_size, grid_size );\n  \n  // Make sure the ACE data has the expected properties\n  TEST_FOR_EXCEPTION( raw_compton_profile_momentum_grid.front() != 0.0,\n\t\t      std::runtime_error,\n\t\t      \"Error: The Compton profile momentum grid extracted \"\n\t\t      \"from the ACE table does not have the expected \"\n\t\t      \"properties (grid.front() == 0.0)!\" );\n  \n  TEST_FOR_EXCEPTION( raw_compton_profile_momentum_grid.back() >=\n\t\t      Utility::PhysicalConstants::inverse_fine_structure_constant,\n\t\t      std::runtime_error,\n\t\t      \"Error: The Compton profile momentum grid extracted \"\n\t\t      \"from the ACE table does not have the expected \"\n\t\t      \"properties (grid.back() < IFSC)!\" );\n  \n  half_momentum_grid.assign( raw_compton_profile_momentum_grid.begin(),\n\t\t\t     raw_compton_profile_momentum_grid.end() );\n  half_profile.assign( raw_compton_profile.begin(),\n\t\t       raw_compton_profile.end() );\n}\n\n// Extract the subshell photoelectric effect cross section\nvoid StandardElectronPhotonRelaxationDataGenerator::extractSubshellPhotoelectricCrossSections(\n\t  Teuchos::Array<std::pair<unsigned,Teuchos::RCP<const Utility::OneDDistribution> > >& cross_sections ) const\n{\n  Teuchos::ArrayView<const double> subshell_ordering = \n    d_ace_epr_data->extractSubshellENDFDesignators();\n\n  Teuchos::ArrayView<const double> energy_grid = \n      d_ace_epr_data->extractPhotonEnergyGrid();\n\n  Teuchos::ArrayView<const double> raw_subshell_pe_cross_sections = \n    d_ace_epr_data->extractSPHELBlock();\n\n  cross_sections.resize( subshell_ordering.size() );\n\n  for( unsigned i = 0; i < subshell_ordering.size(); ++i )\n  {\n    cross_sections[i].first = (unsigned)subshell_ordering[i];\n\n    Teuchos::ArrayView<const double> raw_subshell_pe_cross_section = \n      raw_subshell_pe_cross_sections( i*energy_grid.size(), \n\t\t\t\t      energy_grid.size() );\n\n    this->extractCrossSection<Utility::LogLog>( energy_grid,\n\t\t\t\t\t\traw_subshell_pe_cross_section,\n\t\t\t\t\t\tcross_sections[i].second );\n  }\n}\n\n// Create the subshell impulse approx incoherent cross section evaluators\nvoid StandardElectronPhotonRelaxationDataGenerator::createSubshellImpulseApproxIncoherentCrossSectionEvaluators(\n     const Data::ElectronPhotonRelaxationVolatileDataContainer& data_container,\n     Teuchos::Array<std::pair<unsigned,Teuchos::RCP<const MonteCarlo::SubshellIncoherentPhotonScatteringDistribution> > >& evaluators ) const\n{\n  Teuchos::ArrayView<const double> subshell_ordering = \n    d_ace_epr_data->extractSubshellENDFDesignators();\n\n  evaluators.resize( subshell_ordering.size() );\n\n  for( unsigned i = 0; i < subshell_ordering.size(); ++i )\n  {\n    unsigned subshell = (unsigned)subshell_ordering[i];\n    \n    evaluators[i].first = subshell;\n\n    const std::vector<double>& momentum_grid = \n      data_container.getOccupationNumberMomentumGrid( subshell );\n\n    const std::vector<double>& occupation_number = \n      data_container.getOccupationNumber( subshell );\n\n    Teuchos::RCP<const Utility::OneDDistribution> occupation_number_dist(\n       new Utility::TabularDistribution<Utility::LinLin>( momentum_grid,\n\t\t\t\t\t\t\t  occupation_number ) );\n\n    evaluators[i].second.reset( new MonteCarlo::SubshellIncoherentPhotonScatteringDistribution( \n\t\t   MonteCarlo::convertENDFDesignatorToSubshellEnum( subshell ),\n\t\t   data_container.getSubshellOccupancy( subshell ),\n\t\t   data_container.getSubshellBindingEnergy( subshell ),\n\t\t   occupation_number_dist ) );\n  }\n}\n\n// Initialize the photon union energy grid\nvoid StandardElectronPhotonRelaxationDataGenerator::initializePhotonUnionEnergyGrid( \n     const Data::ElectronPhotonRelaxationVolatileDataContainer& data_container,\n     std::list<double>& union_energy_grid ) const\n{\n  // Add the min photon energy to the union energy grid\n  union_energy_grid.push_back( d_min_photon_energy );\n  \n  const std::set<unsigned>& subshells = data_container.getSubshells();\n\n  std::set<unsigned>::const_iterator subshell = subshells.begin();\n\n  // Add the subshell binding energies\n  while( subshell != subshells.end() )\n  {\n    double binding_energy = \n      data_container.getSubshellBindingEnergy( *subshell );\n\n    if( binding_energy > d_min_photon_energy )\n    {\n      union_energy_grid.push_back( binding_energy );\n      union_energy_grid.push_back( binding_energy*\n\t\t\t\t   s_threshold_energy_nudge_factor );\n    }\n\n    ++subshell;\n  }\n\n  // Add the pair production threshold\n  double pp_threshold = \n    2*Utility::PhysicalConstants::electron_rest_mass_energy;\n\n  if( pp_threshold > d_min_photon_energy )\n  {\n    union_energy_grid.push_back( pp_threshold );\n    union_energy_grid.push_back( pp_threshold*\n\t\t\t\t s_threshold_energy_nudge_factor );\n  }\n\n  // Add the max photon energy\n  union_energy_grid.push_back( d_max_photon_energy );\n\n  // Sort the union energy grid\n  union_energy_grid.sort();\n}\n\n\n// Merge a secondary energy grid with the electron union energy grid\nvoid StandardElectronPhotonRelaxationDataGenerator::mergeElectronUnionEnergyGrid( \n     const std::vector<double>& energy_grid,\n     std::list<double>& union_energy_grid ) const\n{\n  // Assign the new grid to the union grid\n  union_energy_grid.insert( union_energy_grid.begin(),\n                            energy_grid.begin(), \n                            energy_grid.end() );\n\n  // Sort the union energy grid\n  union_energy_grid.sort();\n\n  // Remove all energies less than the min\n  while ( *union_energy_grid.begin() < d_min_electron_energy )\n  {\n      union_energy_grid.pop_front();\n  }\n\n  // Make sure the union energy grid values are unique\n  union_energy_grid.unique();\n}\n\n// Create the cross section on the union energy grid\nvoid StandardElectronPhotonRelaxationDataGenerator::createCrossSectionOnUnionEnergyGrid(\n   const std::list<double>& union_energy_grid,\n   const Teuchos::RCP<const Utility::OneDDistribution>& original_cross_section,\n   std::vector<double>& cross_section,\n   unsigned& threshold_index ) const\n{\n  std::vector<double> raw_cross_section( union_energy_grid.size() );\n  \n  std::list<double>::const_iterator energy_grid_pt = union_energy_grid.begin();\n  \n  unsigned index = 0u;\n  \n  while( energy_grid_pt != union_energy_grid.end() )\n  {\n    raw_cross_section[index] = \n      original_cross_section->evaluate( *energy_grid_pt );\n\n    ++energy_grid_pt;\n    ++index;\n  }\n\n  std::vector<double>::iterator start = \n    std::find_if( raw_cross_section.begin(),\n\t\t  raw_cross_section.end(),\n\t\t  notEqualZero );\n\n  cross_section.assign( start, raw_cross_section.end() );\n\n  threshold_index = std::distance( raw_cross_section.begin(), start );\n}\n\n// Create the cross section on the union energy grid\nvoid StandardElectronPhotonRelaxationDataGenerator::createCrossSectionOnUnionEnergyGrid(\n\t     const std::list<double>& union_energy_grid,\n\t     const Teuchos::RCP<const MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>&\n\t     original_cross_section,\n\t     std::vector<double>& cross_section,\n\t     unsigned& threshold_index ) const\n{\n  std::vector<double> raw_cross_section( union_energy_grid.size() );\n  \n  std::list<double>::const_iterator energy_grid_pt = union_energy_grid.begin();\n  \n  unsigned index = 0u;\n  \n  while( energy_grid_pt != union_energy_grid.end() )\n  {\n    raw_cross_section[index] = \n      original_cross_section->evaluateIntegratedCrossSection( \n\t\t\t\t  *energy_grid_pt, \n\t\t\t\t  d_subshell_incoherent_evaluation_tolerance );\n    \n    ++energy_grid_pt;\n    ++index;\n  }\n  \n  std::vector<double>::iterator start = \n    std::find_if( raw_cross_section.begin(),\n\t\t  raw_cross_section.end(),\n\t\t  notEqualZero );\n\n  cross_section.assign( start, raw_cross_section.end() );\n\n  threshold_index = std::distance( raw_cross_section.begin(), start );\n}\n\n// Calculate the total photoelectric cross section\nvoid StandardElectronPhotonRelaxationDataGenerator::calculateTotalPhotoelectricCrossSection( \n\t                   Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  const std::vector<double>& energy_grid = \n    data_container.getPhotonEnergyGrid();\n\n  std::vector<double> raw_cross_section( energy_grid.size(), 0.0 );\n  \n  const std::set<unsigned>& subshells = data_container.getSubshells();\n\n  std::set<unsigned>::const_iterator subshell = subshells.begin();\n\n  while( subshell != subshells.end() )\n  {\n    const std::vector<double>& subshell_photoelectric_cs = \n      data_container.getSubshellPhotoelectricCrossSection( *subshell );\n\n    unsigned start_index = \n      energy_grid.size() - subshell_photoelectric_cs.size();\n    \n    for( unsigned i = 0; i < subshell_photoelectric_cs.size(); ++i )\n      raw_cross_section[start_index+i] += subshell_photoelectric_cs[i];\n        \n    ++subshell;\n  }\n\n  std::vector<double>::iterator start = \n    std::find_if( raw_cross_section.begin(),\n\t\t  raw_cross_section.end(),\n\t\t  notEqualZero );\n\n  std::vector<double> cross_section;\n  cross_section.assign( start, raw_cross_section.end() );\n\n  unsigned threshold = std::distance( raw_cross_section.begin(), start );\n\n  data_container.setPhotoelectricCrossSection( cross_section );\n  data_container.setPhotoelectricCrossSectionThresholdEnergyIndex( threshold );\n}\n\n// Calculate the total impulse approx. incoherent cross section\nvoid StandardElectronPhotonRelaxationDataGenerator::calculateImpulseApproxTotalIncoherentCrossSection(\n\t\t           Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t   data_container ) const\n{\n  const std::vector<double>& energy_grid = \n    data_container.getPhotonEnergyGrid();\n\n  std::vector<double> raw_cross_section( energy_grid.size(), 0.0 );\n  \n  const std::set<unsigned>& subshells = data_container.getSubshells();\n\n  std::set<unsigned>::const_iterator subshell = subshells.begin();\n\n  while( subshell != subshells.end() )\n  {\n    const std::vector<double>& subshell_incoherent_cs = \n      data_container.getImpulseApproxSubshellIncoherentCrossSection(*subshell);\n    \n    unsigned start_index = energy_grid.size() - subshell_incoherent_cs.size();\n\n    for( unsigned i = 0; i < subshell_incoherent_cs.size(); ++i )\n      raw_cross_section[start_index+i] += subshell_incoherent_cs[i];\n        \n    ++subshell;\n  }\n\n  std::vector<double>::iterator start = \n    std::find_if( raw_cross_section.begin(),\n\t\t  raw_cross_section.end(),\n\t\t  notEqualZero );\n\n  std::vector<double> cross_section;\n  cross_section.assign( start, raw_cross_section.end() );\n\n  unsigned threshold = std::distance( raw_cross_section.begin(), start );\n\n  data_container.setImpulseApproxIncoherentCrossSection( cross_section );\n  data_container.setImpulseApproxIncoherentCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t\t\t   threshold );\n}\n\n// Calculate the Waller-Hartree total cross section\nvoid StandardElectronPhotonRelaxationDataGenerator::calculateWallerHartreeTotalCrossSection(\n\t\t          Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t  data_container ) const\n{\n  const std::vector<double>& energy_grid = \n    data_container.getPhotonEnergyGrid();\n\n  std::vector<double> cross_section( energy_grid.size(), 0.0 );\n  \n  const std::vector<double>& incoherent_cs = \n    data_container.getWallerHartreeIncoherentCrossSection();\n\n  unsigned start_index = energy_grid.size() - incoherent_cs.size();\n\n  for( unsigned i = 0; i < incoherent_cs.size(); ++i )\n    cross_section[start_index+i] += incoherent_cs[i];\n  \n  const std::vector<double>& coherent_cs = \n    data_container.getWallerHartreeCoherentCrossSection();\n\n  start_index = energy_grid.size() - coherent_cs.size();\n\n  for( unsigned i = 0; i < coherent_cs.size(); ++i )\n    cross_section[start_index+i] += coherent_cs[i];\n  \n  const std::vector<double>& pair_production_cs = \n    data_container.getPairProductionCrossSection();\n\n  start_index = energy_grid.size() - pair_production_cs.size();\n\n  for( unsigned i = 0; i < pair_production_cs.size(); ++i )\n    cross_section[start_index+i] += pair_production_cs[i];\n\n  const std::vector<double>& photoelectric_cs = \n    data_container.getPhotoelectricCrossSection();\n\n  start_index = energy_grid.size() - photoelectric_cs.size();\n\n  for( unsigned i = 0; i < photoelectric_cs.size(); ++i )\n    cross_section[start_index+i] += photoelectric_cs[i];\n  \n  data_container.setWallerHartreeTotalCrossSection( cross_section );\n}\n\n// Calculate the impulse approx total cross section\nvoid StandardElectronPhotonRelaxationDataGenerator::calculateImpulseApproxTotalCrossSection(\n\t\t          Data::ElectronPhotonRelaxationVolatileDataContainer&\n\t\t\t  data_container ) const\n{\n  const std::vector<double>& energy_grid = \n    data_container.getPhotonEnergyGrid();\n\n  std::vector<double> cross_section( energy_grid.size(), 0.0 );\n  \n  const std::vector<double>& incoherent_cs = \n    data_container.getImpulseApproxIncoherentCrossSection();\n\n  unsigned start_index = energy_grid.size() - incoherent_cs.size();\n  \n  for( unsigned i = 0; i < incoherent_cs.size(); ++i )\n    cross_section[start_index+i] += incoherent_cs[i];\n  \n  const std::vector<double>& coherent_cs = \n    data_container.getWallerHartreeCoherentCrossSection();\n\n  start_index = energy_grid.size() - coherent_cs.size();\n\n  for( unsigned i = 0; i < coherent_cs.size(); ++i )\n    cross_section[start_index+i] += coherent_cs[i];\n  \n  const std::vector<double>& pair_production_cs = \n    data_container.getPairProductionCrossSection();\n\n  start_index = energy_grid.size() - pair_production_cs.size();\n\n  for( unsigned i = 0; i < pair_production_cs.size(); ++i )\n    cross_section[start_index+i] += pair_production_cs[i];\n\n  const std::vector<double>& photoelectric_cs = \n    data_container.getPhotoelectricCrossSection();\n\n  start_index = energy_grid.size() - photoelectric_cs.size();\n\n  for( unsigned i = 0; i < photoelectric_cs.size(); ++i )\n    cross_section[start_index+i] += photoelectric_cs[i];\n  \n  data_container.setImpulseApproxTotalCrossSection( cross_section );\n}\n\n} // end DataGen namespace\n\n//---------------------------------------------------------------------------//\n// end DataGen_StandardElectronPhotonRelaxationDataGenerator.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "0f3a42396d1ec8494c98de3bbb0a8af069e8adc7", "size": 62866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/electron_photon/src/DataGen_StandardElectronPhotonRelaxationDataGenerator.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/data_gen/electron_photon/src/DataGen_StandardElectronPhotonRelaxationDataGenerator.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/data_gen/electron_photon/src/DataGen_StandardElectronPhotonRelaxationDataGenerator.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.9061632426, "max_line_length": 141, "alphanum_fraction": 0.6965927528, "num_tokens": 14376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.03210070972639667, "lm_q1q2_score": 0.014301814278841798}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include <numpy/ndarrayobject.h>\n#include \"boost/tuple/tuple.hpp\"\n#include \"boost/python/object.hpp\"\n#include <boost/tuple/tuple_comparison.hpp>\n#include <limits>\n#include <map>\n\nnamespace bp = boost::python;\nnamespace ei = Eigen;\nnamespace bpn = boost::python::numpy;\n\ntypedef ei::Matrix<float, 3, 3> Matrix3f;\ntypedef ei::Matrix<float, 3, 1> Vector3f;\n\ntypedef boost::tuple< std::vector< std::vector<float> >, std::vector< std::vector<uint8_t> >, std::vector<std::vector<uint32_t> > > Custom_tuple;\ntypedef boost::tuple< uint32_t, uint32_t, uint32_t > Space_tuple;\n\nstruct VecToArray\n{//converts a vector<uint32_t> to a numpy array\n    static PyObject * convert(const std::vector<uint8_t> & vec) {\n    npy_intp dims = vec.size();\n    PyObject * obj = PyArray_SimpleNew(1, &dims, NPY_UINT8);\n    void * arr_data = PyArray_DATA((PyArrayObject*)obj);\n    memcpy(arr_data, &vec[0], dims * sizeof(uint8_t));\n    return obj;\n    }\n};\n\ntemplate <class T>\nstruct VecvecToArray\n{//converts a vector< vector<uint32_t> > to a numpy 2d array\n    static PyObject * convert(const std::vector< std::vector<T> > & vecvec)\n    {\n        npy_intp dims[2];\n        dims[0] = vecvec.size();\n        dims[1] = vecvec[0].size();\n        PyObject * obj;\n        if (typeid(T) == typeid(uint8_t))\n            obj = PyArray_SimpleNew(2, dims, NPY_UINT8);\n        else if (typeid(T) == typeid(float))\n            obj = PyArray_SimpleNew(2, dims, NPY_FLOAT32);\n        else if (typeid(T) == typeid(uint32_t))\n            obj = PyArray_SimpleNew(2, dims, NPY_UINT32);\n        void * arr_data = PyArray_DATA((PyArrayObject*)obj);\n        std::size_t cell_size = sizeof(T);\n        for (std::size_t i = 0; i < dims[0]; i++)\n        {\n            memcpy(arr_data + i * dims[1] * cell_size, &(vecvec[i][0]), dims[1] * cell_size);\n        }\n        return obj;\n    }\n};\n\nstruct to_py_tuple\n{//converts to a python tuple\n    static PyObject* convert(const Custom_tuple & c_tuple){\n        bp::list values;\n\n        PyObject * pyo1 = VecvecToArray<float>::convert(c_tuple.get<0>());\n        PyObject * pyo2 = VecvecToArray<uint8_t>::convert(c_tuple.get<1>());\n        PyObject * pyo3 = VecvecToArray<uint32_t>::convert(c_tuple.get<2>());\n\n        values.append(bp::handle<>(bp::borrowed(pyo1)));\n        values.append(bp::handle<>(bp::borrowed(pyo2)));\n        values.append(bp::handle<>(bp::borrowed(pyo3)));\n\n        return bp::incref( bp::tuple( values ).ptr() );\n    }\n};\n\nclass AttributeGrid {\n//voxelization of the space, allows to accumulate the position, the color and labels\n    std::map<Space_tuple, uint64_t> space_tuple_to_index;//associate eeach non-empty voxel to an index\n    uint64_t index;\n    std::vector<uint32_t> bin_count;//count the number of point in each non-empty voxel\n    std::vector< std::vector<float> > acc_xyz;//accumulate the position of the points\n    std::vector< std::vector<uint32_t> > acc_rgb;//accumulate the color of the points\n    std::vector< std::vector<uint32_t> > acc_labels;//accumulate the label of the points\n  public:\n    AttributeGrid():\n       index(0)\n    {}\n    //---methods for the occurence grid---\n    uint64_t n_nonempty_voxels()\n    {\n        return this->index;\n    }\n    uint32_t get_index(uint32_t x_bin, uint32_t  y_bin, uint32_t z_bin)\n    {\n        return space_tuple_to_index.at(Space_tuple(x_bin, y_bin, z_bin));\n    }\n    bool add_occurence(uint32_t x_bin, uint32_t  y_bin, uint32_t z_bin)\n    {\n        Space_tuple st(x_bin, y_bin, z_bin);\n        auto inserted = space_tuple_to_index.insert(std::pair<Space_tuple, uint64_t>(st, index));\n        if (inserted.second)\n        {\n            this->index++;\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n    std::map<Space_tuple,uint64_t>::iterator begin()\n    {\n        return this->space_tuple_to_index.begin();\n    }\n    std::map<Space_tuple,uint64_t>::iterator end()\n    {\n        return this->space_tuple_to_index.end();\n    }\n    //---methods for accumulating atributes---\n    void initialize(uint8_t n_class)\n    {//must be run once space_tuple_to_index is complete and the number of non-empty voxels is known\n        bin_count  = std::vector<uint32_t>(this->index, 0);\n        acc_xyz    = std::vector< std::vector<float> >(this->index, std::vector <float>(3,0));\n        acc_rgb    = std::vector< std::vector<uint32_t> >(this->index, std::vector <uint32_t>(3,0));\n        acc_labels = std::vector< std::vector<uint32_t> >(this->index, std::vector <uint32_t>(n_class+1,0));\n    }\n    uint32_t get_count(uint64_t voxel_index)\n    {\n        return bin_count.at(voxel_index);\n    }\n    std::vector<float> get_pos(uint64_t voxel_index)\n    {\n        return acc_xyz.at(voxel_index);\n    }\n    std::vector<uint32_t> get_rgb(uint64_t voxel_index)\n    {\n        return acc_rgb.at(voxel_index);\n    }\n    std::vector<uint32_t> get_acc_labels(uint64_t voxel_index)\n    {\n        return acc_labels.at(voxel_index);\n    }\n    uint8_t get_label(uint64_t voxel_index)\n    {//return the majority label from ths voxel\n     //ignore the unlabeled points (0), unless all points are unlabeled\n        std::vector<uint32_t> label_hist = acc_labels.at(voxel_index);\n        std::vector<uint32_t>::iterator chosen_label = std::max_element(label_hist.begin() + 1, label_hist.end());\n        if (*chosen_label == 0)\n        {\n            return 0;\n        }\n        else\n        {\n            return (uint8_t)std::distance(label_hist.begin(), chosen_label);\n        }\n    }\n    void add_attribute(uint32_t x_bin, uint32_t  y_bin, uint32_t z_bin, float x, float y, float z, uint8_t r, uint8_t g, uint8_t b)\n    {//add a point x y z in voxel x_bin y_bin z_bin\n        uint64_t bin = get_index(x_bin, y_bin, z_bin);\n        bin_count.at(bin) = bin_count.at(bin) + 1;\n        acc_xyz.at(bin).at(0) = acc_xyz.at(bin).at(0) + x;\n        acc_xyz.at(bin).at(1) = acc_xyz.at(bin).at(1) + y;\n        acc_xyz.at(bin).at(2) = acc_xyz.at(bin).at(2) + z;\n        acc_rgb.at(bin).at(0) = acc_rgb.at(bin).at(0) + r;\n        acc_rgb.at(bin).at(1) = acc_rgb.at(bin).at(1) + g;\n        acc_rgb.at(bin).at(2) = acc_rgb.at(bin).at(2) + b;\n    }\n    void add_attribute(uint32_t x_bin, uint32_t  y_bin, uint32_t z_bin, float x, float y, float z, uint8_t r, uint8_t g, uint8_t b, uint8_t label)\n    {//add a point x y z in voxel x_bin y_bin z_bin - with label\n        uint32_t bin =get_index(x_bin, y_bin, z_bin);\n        bin_count.at(bin) = bin_count.at(bin) + 1;\n        acc_xyz.at(bin).at(0) = acc_xyz.at(bin).at(0) + x;\n        acc_xyz.at(bin).at(1) = acc_xyz.at(bin).at(1) + y;\n        acc_xyz.at(bin).at(2) = acc_xyz.at(bin).at(2) + z;\n        acc_rgb.at(bin).at(0) = acc_rgb.at(bin).at(0) + r;\n        acc_rgb.at(bin).at(1) = acc_rgb.at(bin).at(1) + g;\n        acc_rgb.at(bin).at(2) = acc_rgb.at(bin).at(2) + b;\n        acc_labels.at(bin).at(label) = acc_labels.at(bin).at(label) + 1;\n    }\n};\n\nPyObject *  prune(const bpn::ndarray & xyz ,float voxel_size, const bpn::ndarray & rgb, const bpn::ndarray & labels, const int n_classes)\n{//prune the point cloud xyz with a regular voxel grid\n    std::cout << \"=========================\" << std::endl;\n    std::cout << \"======== pruning ========\" << std::endl;\n    std::cout << \"=========================\" << std::endl;\n    uint64_t n_ver = bp::len(xyz);\n    bool have_labels = n_classes>0;\n    //---read the numpy arrays data---\n    const float * xyz_data = reinterpret_cast<float*>(xyz.get_data());\n    const uint8_t * rgb_data = reinterpret_cast<uint8_t*>(rgb.get_data());\n    const uint8_t * label_data;\n    if (have_labels)\n        label_data = reinterpret_cast<uint8_t*>(labels.get_data());\n    //---find min max of xyz----\n    float x_max = std::numeric_limits<float>::lowest(), x_min = std::numeric_limits<float>::max();\n    float y_max = std::numeric_limits<float>::lowest(), y_min = std::numeric_limits<float>::max();\n    float z_max = std::numeric_limits<float>::lowest(), z_min = std::numeric_limits<float>::max();\n    #pragma omp parallel for reduction(max : x_max, y_max, z_max), reduction(min : x_min, y_min, z_min)\n    for (std::size_t i_ver = 0; i_ver < n_ver; i_ver ++)\n    {\n        if (x_max < xyz_data[3 * i_ver]){           x_max = xyz_data[3 * i_ver];}\n        if (y_max < xyz_data[3 * i_ver + 1]){       y_max = xyz_data[3 * i_ver + 1];}\n        if (z_max < xyz_data[3 * i_ver + 2]){       z_max = xyz_data[3 * i_ver + 2];}\n        if (x_min > xyz_data[3 * i_ver]){           x_min = xyz_data[3 * i_ver];}\n        if (y_min > xyz_data[3 * i_ver + 1]){       y_min = xyz_data[3 * i_ver + 1];}\n        if (z_min > xyz_data[3 * i_ver + 2 ]){      z_min = xyz_data[3 * i_ver + 2];}\n    }\n    //---compute the voxel grid size---\n    uint32_t n_bin_x = std::ceil((x_max - x_min) / voxel_size);\n    uint32_t n_bin_y = std::ceil((y_max - y_min) / voxel_size);\n    uint32_t n_bin_z = std::ceil((z_max - z_min) / voxel_size);\n    std::cout << \"Voxelization into \" << n_bin_x << \" x \" << n_bin_y << \" x \" << n_bin_z << \" grid\" << std::endl;\n    //---detect non-empty voxels----\n    AttributeGrid vox_grid;\n    for (std::size_t i_ver = 0; i_ver < n_ver; i_ver ++)\n    {\n        uint32_t bin_x = std::floor((xyz_data[3 * i_ver] - x_min) / voxel_size);\n        uint32_t bin_y = std::floor((xyz_data[3 * i_ver + 1] - y_min) / voxel_size);\n        uint32_t bin_z = std::floor((xyz_data[3 * i_ver + 2] - z_min) / voxel_size);\n        vox_grid.add_occurence(bin_x, bin_y, bin_z);\n    }\n    std::cout << \"Reduced from \" << n_ver << \" to \" << vox_grid.n_nonempty_voxels() << \" points (\"\n              << std::ceil(10000 * vox_grid.n_nonempty_voxels() / n_ver)/100 << \"%)\" << std::endl;\n    vox_grid.initialize(n_classes);\n    //---accumulate points in the voxel map----\n    for (std::size_t i_ver = 0; i_ver < n_ver; i_ver ++)\n    {\n        uint32_t bin_x = std::floor((xyz_data[3 * i_ver    ] - x_min) / voxel_size);\n        uint32_t bin_y = std::floor((xyz_data[3 * i_ver + 1] - y_min) / voxel_size);\n        uint32_t bin_z = std::floor((xyz_data[3 * i_ver + 2] - z_min) / voxel_size);\n        if (have_labels)\n            vox_grid.add_attribute(bin_x, bin_y, bin_z\n                    , xyz_data[3 * i_ver], xyz_data[3 * i_ver + 1], xyz_data[3 * i_ver + 2]\n                    , rgb_data[3 * i_ver], rgb_data[3 * i_ver + 1], rgb_data[3 * i_ver + 2], label_data[i_ver]);\n        else\n            vox_grid.add_attribute(bin_x, bin_y, bin_z\n                    , xyz_data[3 * i_ver], xyz_data[3 * i_ver + 1], xyz_data[3 * i_ver + 2]\n                    , rgb_data[3 * i_ver], rgb_data[3 * i_ver + 1], rgb_data[3 * i_ver + 2]);\n    }\n    //---compute pruned cloud----\n    std::vector< std::vector< float > > pruned_xyz(vox_grid.n_nonempty_voxels(), std::vector< float >(3, 0.f));\n    std::vector< std::vector< uint8_t > > pruned_rgb(vox_grid.n_nonempty_voxels(), std::vector< uint8_t >(3, 0));\n    std::vector< std::vector< uint32_t > > pruned_labels(vox_grid.n_nonempty_voxels(), std::vector< uint32_t >(n_classes + 1, 0));\n    for (std::map<Space_tuple,uint64_t>::iterator it_vox=vox_grid.begin(); it_vox!=vox_grid.end(); ++it_vox)\n    {//loop over the non-empty voxels and compute the average posiition/color + majority label\n        uint64_t voxel_index = it_vox->second; //\n        float count = (float)vox_grid.get_count(voxel_index);\n        std::vector<float> pos = vox_grid.get_pos(voxel_index);\n        pos.at(0) = pos.at(0) / count;\n        pos.at(1) = pos.at(1) / count;\n        pos.at(2) = pos.at(2) / count;\n        pruned_xyz.at(voxel_index) = pos;\n        std::vector<uint32_t> col = vox_grid.get_rgb(voxel_index);\n        std::vector<uint8_t> col_uint8_t(3);\n        col_uint8_t.at(0) = (uint8_t)((float) col.at(0) / count);\n        col_uint8_t.at(1) = (uint8_t)((float) col.at(1) / count);\n        col_uint8_t.at(2) = (uint8_t)((float) col.at(2) / count);\n        pruned_rgb.at(voxel_index) = col_uint8_t;\n        pruned_labels.at(voxel_index) = vox_grid.get_acc_labels(voxel_index);\n    }\n    return to_py_tuple::convert(Custom_tuple(pruned_xyz,pruned_rgb, pruned_labels));\n}\n\n\n\nPyObject * compute_geof(const bpn::ndarray & xyz ,const bpn::ndarray & target, int k_nn)\n{//compute the following geometric features (geof) features of a point cloud:\n //linearity planarity scattering verticality\n    std::size_t n_ver = bp::len(xyz);\n    std::vector< std::vector< float > > geof(n_ver, std::vector< float >(4,0));\n    //--- read numpy array data---\n    const uint32_t * target_data = reinterpret_cast<uint32_t*>(target.get_data());\n    const float * xyz_data = reinterpret_cast<float*>(xyz.get_data());\n    std::size_t s_ver = 0;\n    #pragma omp parallel for schedule(static)\n    for (std::size_t i_ver = 0; i_ver < n_ver; i_ver++)\n    {//each point can be treated in parallell independently\n        //--- compute 3d covariance matrix of neighborhood ---\n        ei::MatrixXf position(k_nn+1,3);\n        std::size_t i_edg = k_nn * i_ver;\n        std::size_t ind_nei;\n        position(0,0) = xyz_data[3 * i_ver];\n        position(0,1) = xyz_data[3 * i_ver + 1];\n        position(0,2) = xyz_data[3 * i_ver + 2];\n        for (std::size_t i_nei = 0; i_nei < k_nn; i_nei++)\n        {\n                //add the neighbors to the position matrix\n            ind_nei = target_data[i_edg];\n            position(i_nei+1,0) = xyz_data[3 * ind_nei];\n            position(i_nei+1,1) = xyz_data[3 * ind_nei + 1];\n            position(i_nei+1,2) = xyz_data[3 * ind_nei + 2];\n            i_edg++;\n        }\n        // compute the covariance matrix\n        ei::MatrixXf centered_position = position.rowwise() - position.colwise().mean();\n        ei::Matrix3f cov = (centered_position.adjoint() * centered_position) / float(k_nn + 1);\n        ei::EigenSolver<Matrix3f> es(cov);\n        //--- compute the eigen values and vectors---\n        std::vector<float> ev = {es.eigenvalues()[0].real(),es.eigenvalues()[1].real(),es.eigenvalues()[2].real()};\n        std::vector<int> indices(3);\n        std::size_t n(0);\n        std::generate(std::begin(indices), std::end(indices), [&]{ return n++; });\n        std::sort(std::begin(indices),std::end(indices),\n                       [&](int i1, int i2) { return ev[i1] > ev[i2]; } );\n        std::vector<float> lambda = {(std::max(ev[indices[0]],0.f)),\n                                    (std::max(ev[indices[1]],0.f)),\n                                    (std::max(ev[indices[2]],0.f))};\n        std::vector<float> v1 = {es.eigenvectors().col(indices[0])(0).real()\n                               , es.eigenvectors().col(indices[0])(1).real()\n                               , es.eigenvectors().col(indices[0])(2).real()};\n        std::vector<float> v2 = {es.eigenvectors().col(indices[1])(0).real()\n                               , es.eigenvectors().col(indices[1])(1).real()\n                               , es.eigenvectors().col(indices[1])(2).real()};\n        std::vector<float> v3 = {es.eigenvectors().col(indices[2])(0).real()\n                               , es.eigenvectors().col(indices[2])(1).real()\n                               , es.eigenvectors().col(indices[2])(2).real()};\n        //--- compute the dimensionality features---\n        float linearity  = (sqrtf(lambda[0]) - sqrtf(lambda[1])) / sqrtf(lambda[0]);\n        float planarity  = (sqrtf(lambda[1]) - sqrtf(lambda[2])) / sqrtf(lambda[0]);\n        float scattering =  sqrtf(lambda[2]) / sqrtf(lambda[0]);\n        //--- compute the verticality feature---\n        std::vector<float> unary_vector =\n            {lambda[0] * fabsf(v1[0]) + lambda[1] * fabsf(v2[0]) + lambda[2] * fabsf(v3[0])\n            ,lambda[0] * fabsf(v1[1]) + lambda[1] * fabsf(v2[1]) + lambda[2] * fabsf(v3[1])\n            ,lambda[0] * fabsf(v1[2]) + lambda[1] * fabsf(v2[2]) + lambda[2] * fabsf(v3[2])};\n        float norm = sqrt(unary_vector[0] * unary_vector[0] + unary_vector[1] * unary_vector[1]\n                        + unary_vector[2] * unary_vector[2]);\n        float verticality = unary_vector[2] / norm;\n        //---fill the geof vector---\n        geof[i_ver][0] = linearity;\n        geof[i_ver][1] = planarity;\n        geof[i_ver][2] = scattering;\n        geof[i_ver][3] = verticality;\n        //---progression---\n        s_ver++;//if run in parellel s_ver behavior is udnefined, but gives a good indication of progress\n        if (s_ver % 10000 == 0)\n        {\n            std::cout << s_ver << \"% done          \\r\" << std::flush;\n            std::cout << ceil(s_ver*100/n_ver) << \"% done          \\r\" << std::flush;\n        }\n    }\n    std::cout <<  std::endl;\n    return VecvecToArray<float>::convert(geof);\n}\n\nusing namespace boost::python;\nBOOST_PYTHON_MODULE(libply_c)\n{\n    _import_array();\n    bp::to_python_converter<std::vector<std::vector<float>, std::allocator<std::vector<float> > >, VecvecToArray<float> >();\n    bp::to_python_converter< Custom_tuple, to_py_tuple>();\n    Py_Initialize();\n    bpn::initialize();\n    def(\"compute_geof\", compute_geof);\n    def(\"prune\", prune);\n}\n", "meta": {"hexsha": "446cb00346c550e3a92778a85ed24a366d4a8efd", "size": 17102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "partition/ply_c/ply_c.cpp", "max_stars_repo_name": "Pandinosaurus/superpoint_graph", "max_stars_repo_head_hexsha": "7584941a60054d88593e26fef690bfd9a9f67a6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "partition/ply_c/ply_c.cpp", "max_issues_repo_name": "Pandinosaurus/superpoint_graph", "max_issues_repo_head_hexsha": "7584941a60054d88593e26fef690bfd9a9f67a6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "partition/ply_c/ply_c.cpp", "max_forks_repo_name": "Pandinosaurus/superpoint_graph", "max_forks_repo_head_hexsha": "7584941a60054d88593e26fef690bfd9a9f67a6d", "max_forks_repo_licenses": ["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.5055555556, "max_line_length": 146, "alphanum_fraction": 0.5988773243, "num_tokens": 5005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.03210070324463719, "lm_q1q2_score": 0.014301811391026509}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/* boosting_generator.cc\n   Jeremy Barnes, 15 March 2006\n   Copyright (c) 2006 Jeremy Barnes  All rights reserved.\n   $Source$\n\n   Generator for boosted stumps.\n*/\n\n#include \"boosting_generator.h\"\n#include \"mldb/plugins/jml/jml/registry.h\"\n#include <boost/timer.hpp>\n#include <boost/progress.hpp>\n#include \"training_index.h\"\n#include \"weighted_training.h\"\n#include \"mldb/plugins/jml/jml/committee.h\"\n#include \"mldb/plugins/jml/sgi_numeric.h\"\n#include \"boosting_training.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"boosting_core.h\"\n#include \"boosting_core_parallel.h\"\n\n#include \"binary_symmetric.h\"\n#include \"mldb/base/parallel.h\"\n#include \"mldb/base/scope.h\"\n#include <boost/scoped_ptr.hpp>\n\n\nusing namespace std;\n\n\nnamespace ML {\n\n/*****************************************************************************/\n/* BOOSTING_GENERATOR                                                        */\n/*****************************************************************************/\n\nBoosting_Generator::\nBoosting_Generator()\n{\n    defaults();\n}\n\nBoosting_Generator::~Boosting_Generator()\n{\n}\n\nvoid\nBoosting_Generator::\nconfigure(const Configuration & config, vector<string> & unparsedKeys)\n{\n    Early_Stopping_Generator::configure(config, unparsedKeys);\n\n    config.findAndRemove(max_iter, \"max_iter\", unparsedKeys);\n    config.findAndRemove(min_iter, \"min_iter\", unparsedKeys);\n    config.findAndRemove(cost_function, \"cost_function\", unparsedKeys);\n    config.findAndRemove(short_circuit_window, \"short_circuit_window\", unparsedKeys);\n    config.findAndRemove(trace_training_acc, \"trace_training_acc\", unparsedKeys);\n\n    weak_learner = get_trainer(\"weak_learner\", config);\n}\n\nvoid\nBoosting_Generator::\ndefaults()\n{\n    Early_Stopping_Generator::defaults();\n    max_iter = 500;\n    min_iter = 10;\n    cost_function = CF_EXPONENTIAL;\n    short_circuit_window = 0;\n    weak_learner.reset();\n    trace_training_acc = false;\n}\n\nConfig_Options\nBoosting_Generator::\noptions() const\n{\n    Config_Options result = Early_Stopping_Generator::options();\n    result\n        .add(\"min_iter\", min_iter, \"1-max_iter\",\n             \"minimum number of training iterations to run\")\n        .add(\"max_iter\", max_iter, \">=min_iter\",\n             \"maximum number of training iterations to run\")\n        .add(\"cost_function\", cost_function,\n             \"select cost function for boosting weight update\")\n        .add(\"short_circuit_window\", short_circuit_window, \"0-\",\n             \"short circuit (stop) training if no improvement for N iter \"\n             \"(0 off)\")\n        .add(\"trace_training_acc\", trace_training_acc,\n             \"trace the accuracy of the training set as well as validation\")\n        .subconfig(\"weak_leaner\", weak_learner,\n                   \"weak learner that produces each bag\");\n\n    if (weak_learner) result.add(weak_learner->options());\n    \n    return result;\n}\n\nvoid\nBoosting_Generator::\ninit(std::shared_ptr<const Feature_Space> fs, Feature predicted)\n{\n    Classifier_Generator::init(fs, predicted);\n    weak_learner->init(fs, predicted);\n}\n\nstd::shared_ptr<Classifier_Impl>\nBoosting_Generator::\ngenerate(Thread_Context & context,\n         const Training_Data & training_set,\n         const Training_Data & validation_set,\n         const distribution<float> & training_ex_weights,\n         const distribution<float> & validate_ex_weights,\n         const std::vector<Feature> & features_, int) const\n{\n    vector<Feature> features = features_;\n\n    boost::timer timer;\n\n    unsigned nl = training_set.label_count(predicted);\n\n    float best_acc = 0.0;\n    int best_iter = 0;\n\n    bool validate_is_train = false;\n    if (validation_set.example_count() == 0\n        || ((&validation_set == &training_set)\n            && (training_ex_weights.size() == validate_ex_weights.size())\n            && !(training_ex_weights != validate_ex_weights).any()))\n        validate_is_train = true;\n\n    boost::multi_array<float, 2> training_output\n        (boost::extents[training_set.example_count()][nl]);\n\n    boost::multi_array<float, 2> validation_output\n        (boost::extents[validation_set.example_count()][nl]);\n    \n    boost::multi_array<float, 2> weights\n        = expand_weights(training_set, training_ex_weights, predicted);\n\n    boost::multi_array<float, 2> last_weights = weights;\n\n    std::unique_ptr<boost::progress_display> progress;\n\n    if (verbosity == 1 || verbosity == 2) {\n        cerr << \"training \" << max_iter << \" iterations...\" << endl;\n        progress.reset(new boost::progress_display(max_iter, cerr));\n    }\n    \n    if (min_iter > max_iter)\n        throw Exception(\"min_iter is greater than max_iter\");\n\n    if (verbosity > 2) {\n        cerr << \"  it   \";\n        if (trace_training_acc) cerr << \"train     \";\n        cerr << \"val   Z    Classifier\" << endl;\n    }\n    \n    vector<std::shared_ptr<Classifier_Impl> > classifiers;\n\n    double validate_acc = 0.0;\n    double train_acc = 0.0;\n\n    for (unsigned i = 0;  i < max_iter;  ++i) {\n\n        if (progress) ++(*progress);\n\n        float Z;\n\n        std::shared_ptr<Classifier_Impl> weak_classifier;\n        Optimization_Info opt_info;\n\n        if (validate_is_train || trace_training_acc)\n            weak_classifier\n                = train_iteration(context, training_set, weights, features,\n                                  training_output, training_ex_weights,\n                                  train_acc, Z, opt_info);\n        else\n            weak_classifier\n                = train_iteration(context, training_set, weights, features,\n                                  Z, opt_info);\n        \n        if (validate_is_train) validate_acc = train_acc;\n        else\n            validate_acc\n                = update_accuracy(context, *weak_classifier, opt_info,\n                                  validation_set, features,\n                                  validation_output, validate_ex_weights);\n\n#if 0\n        float min_weight = 1.0, max_weight = 0.0, max_diff = 0.0;\n        int where_max_diff = -1, where_max_weight = -1;\n\n        int nx = training_set.example_count();\n\n        double total = 0.0;\n\n        for (unsigned x = 0;  x < nx;  ++x) {\n            float old_w = last_weights[x][0];\n            float new_w = weights[x][0];\n\n            min_weight = std::min(min_weight, new_w);\n\n            if (new_w > max_weight) {\n                max_weight = new_w;\n                where_max_weight = x;\n            }\n\n            float diff = fabs(old_w - new_w);\n            if (diff > max_diff) {\n                where_max_diff = x;\n                max_diff = diff;\n            }\n\n            total += new_w;\n        }\n\n        cerr << \"total = \" << total << endl;\n\n        cerr << \"min_weight \" << min_weight << \" max_weight \"\n             << max_weight << \" where \" << where_max_weight\n             << \" old \" << last_weights[where_max_weight][0]\n             << \" new \" << weights[where_max_weight][0]\n             << \" pred \" << weak_classifier->predict(0,\n                                                     training_set[where_max_weight])\n             << endl;\n\n        cerr << \"max_diff \" << max_diff << \" where \" << where_max_diff\n             << \" old \" << last_weights[where_max_diff][0]\n             << \" new \" << weights[where_max_diff][0]\n             << \" pred \" << weak_classifier->predict(0,\n                                                     training_set[where_max_diff])\n             << endl;\n\n        cerr << \"ratio = \" << max_weight / min_weight << endl;\n\n        last_weights.resize(boost::extents[weights.shape()[0]][weights.shape()[1]]);\n        last_weights = weights;\n#endif\n\n        if (verbosity > 2) {\n            cerr << format(\"%4d\", i);\n            if (trace_training_acc)\n                cerr << format(\" %6.2f%%\", train_acc * 100.0);\n            cerr << format(\" %6.2f%% %5.3f \", validate_acc * 100.0, Z);\n            cerr << weak_classifier->summary();\n            cerr << endl;\n        }\n\n        classifiers.push_back(weak_classifier);\n\n        if (validate_acc > best_acc && i >= min_iter) {\n            best_iter = i;\n            best_acc = validate_acc;\n        }\n\n        if (Z == 1.0f) {\n            cerr << \"Z = \" << format(\"%12f\", Z) << endl;\n            cerr << \"stopping due to perfect learning\" << endl;\n            break;  // too much capacity; we've learned non-zero weights\n                    // perfectly\n        }\n    }\n\n    if (verbosity > 0) {\n        cerr << format(\"best was %6.2f%% on iteration %d\", best_acc * 100.0,\n                       best_iter)\n             << endl;\n    }\n\n    if (profile)\n        cerr << \"training time: \" << timer.elapsed() << \"s\" << endl;\n    \n    std::shared_ptr<Committee>\n        result(new Committee(feature_space, predicted));\n    \n    for (int i = 0;  i <= best_iter;  ++i)\n        result->add(classifiers[i]);\n    \n    return result;\n}\n\nstd::shared_ptr<Classifier_Impl>\nBoosting_Generator::\ngenerate_and_update(Thread_Context & context,\n                    const Training_Data & training_set,\n                    boost::multi_array<float, 2> & weights,\n                    const std::vector<Feature> & features_) const\n{\n    vector<Feature> features = features_;\n\n    boost::timer timer;\n\n    unsigned nl = training_set.label_count(predicted);\n\n    float best_acc = 0.0;\n    int best_iter = 0;\n\n    boost::multi_array<float, 2> training_output\n        (boost::extents[training_set.example_count()][nl]);\n\n    if (weights.shape()[0] != training_set.example_count()\n        || weights.shape()[1] != nl)\n        throw Exception(\"Boosting_Generator::generate_and_update(): \"\n                        \"weights have the wrong shape\");\n\n    distribution<float> training_ex_weights(training_set.example_count(), 1.0);\n\n    std::unique_ptr<boost::progress_display> progress;\n\n    if (verbosity == 1 || verbosity == 2) {\n        cerr << \"training \" << max_iter << \" iterations...\" << endl;\n        progress.reset(new boost::progress_display(max_iter, cerr));\n    }\n    \n    if (verbosity > 2)\n        cerr << \"  it   train     Z    Classifier\" << endl;\n    \n    vector<std::shared_ptr<Classifier_Impl> > classifiers;\n\n    double train_acc = 0.0;\n\n    for (unsigned i = 0;  i < max_iter;  ++i) {\n\n        if (progress) ++(*progress);\n\n        float Z;\n\n        Optimization_Info opt_info;\n\n        std::shared_ptr<Classifier_Impl> weak_classifier\n            = train_iteration(context, training_set, weights, features,\n                              training_output, training_ex_weights,\n                              train_acc, Z, opt_info);\n        \n        if (verbosity > 2) {\n            cerr << format(\"%4d\", i);\n            cerr << format(\" %6.2f%% %5.3f \", train_acc * 100.0, Z);\n            cerr << weak_classifier->summary();\n            cerr << endl;\n        }\n        \n        classifiers.push_back(weak_classifier);\n\n        if (train_acc > best_acc && i >= min_iter) {\n            best_iter = i;\n            best_acc = train_acc;\n        }\n\n        if (1.0 - Z <= 1e-5)\n            break;  // too much capacity; we've learned non-zero weights\n                    // perfectly\n    }\n    \n    if (verbosity > 0) {\n        cerr << format(\"best was %6.2f%% on iteration %d\", best_acc * 100.0,\n                       best_iter)\n             << endl;\n    }\n    \n    if (profile)\n        cerr << \"training time: \" << timer.elapsed() << \"s\" << endl;\n    \n    std::shared_ptr<Committee>\n        result(new Committee(feature_space, predicted));\n    \n    for (int i = 0;  i <= best_iter;  ++i)\n        result->add(classifiers[i]);\n    \n    return result;\n}\n\nstd::shared_ptr<Classifier_Impl>\nBoosting_Generator::\ntrain_iteration(Thread_Context & context,\n                const Training_Data & data,\n                boost::multi_array<float, 2> & weights,\n                vector<Feature> & features,\n                float & Z,\n                Optimization_Info & opt_info) const\n{\n    bool bin_sym = convert_bin_sym(weights, data, predicted, features);\n\n    /* Make sure we have some features. */\n    if (features.empty()) features = data.all_features();\n\n    Z = 0.0;\n    \n    /* Find the best stump */\n    std::shared_ptr<Classifier_Impl> weak_classifier\n        = weak_learner->generate(context, data, weights, features, Z);\n    \n    const Feature_Space & fs = *data.feature_space();\n\n    if (fs.type() == DENSE)\n        opt_info = weak_classifier->optimize(fs.dense_features());\n\n    /* Update the d distribution. */\n    double total = 0.0;\n    \n    size_t nl = weights.shape()[1];\n    \n    if (cost_function == CF_EXPONENTIAL) {\n        typedef Boosting_Loss Loss;\n        if (bin_sym) {\n            if (true /* use parallel */) {\n                typedef Binsym_Updater<Loss> Updater;\n                typedef Update_Weights_Parallel<Updater> Update;\n                Update update;\n                \n                update(*weak_classifier, opt_info, 1.0, weights, data, total);\n            }\n            else {\n                typedef Binsym_Updater<Loss> Updater;\n                typedef Update_Weights<Updater> Update;\n                Update update;\n                \n                total = update(*weak_classifier, opt_info, 1.0, weights, data);\n            }\n        }\n        else {\n            typedef Normal_Updater<Loss> Updater;\n            typedef Update_Weights_Parallel<Updater> Update;\n            Updater updater(nl);\n            Update update(updater);\n\n            update(*weak_classifier, opt_info, 1.0, weights, data, total);\n        }\n    }\n    else if (cost_function == CF_LOGISTIC) {\n        throw Exception(\"Boosting_Generator::train_iteration(): \"\n                        \"what is Z for logistic loss?\");\n#if 0\n        typedef Logistic_Loss Loss;\n        Loss loss(Z);\n\n        if (bin_sym) {\n            typedef Binsym_Updater<Loss> Updater;\n            typedef Update_Weights_Parallel<Updater> Update;\n            Updater updater(loss);\n            Update update(updater);\n\n            update(*weak_classifier, opt_info, 1.0, weights, data, total);\n        }\n        else {\n            //PROFILE_FUNCTION(t_update);\n            typedef Normal_Updater<Loss> Updater;\n            typedef Update_Weights_Parallel<Updater> Update;\n            Updater updater(nl, loss);\n            Update update(updater);\n\n            update(*weak_classifier, opt_info, 1.0, weights, data, total);\n        }\n#endif\n    }\n    else throw Exception(\"Boosting_Generator::train_iteration: \"\n                         \"unknown cost function\");\n\n    //cerr << \"total = \" << total << \" Z = \" << Z << endl;\n\n    if (Z == 0.0) Z = total;\n\n    if (Z > 1.0) {\n        //cerr << \"weak learner returned Z of \" << Z << endl;\n        //cerr << weak_classifier->print() << endl;\n    }\n    \n    float * start = weights.data();\n    float * finish = start + weights.num_elements();\n    SIMD::vec_scale(start, 1.0 / total, start, finish - start);\n    \n    return weak_classifier;\n}\n\n/* This does the following: \n   - Trains a stump\n   - Updates the weights\n   - Updates the output weights\n   - Calculates the accuracy over the training set\n\n   all in one pass (which saves on execution time as less memory is used).\n*/\n\nstd::shared_ptr<Classifier_Impl>\nBoosting_Generator::\ntrain_iteration(Thread_Context & context,\n                const Training_Data & data,\n                boost::multi_array<float, 2> & weights,\n                std::vector<Feature> & features,\n                boost::multi_array<float, 2> & output,\n                const distribution<float> & ex_weights,\n                double & training_accuracy, float & Z,\n                Optimization_Info & opt_info) const\n{\n    bool bin_sym\n        = convert_bin_sym(weights, data, predicted, features);\n\n    //cerr << \"bin_sym = \" << bin_sym << endl;\n\n    convert_bin_sym(output, data, predicted, features);\n\n    Z = 0.0;\n    \n    /* Find the best weak learner */\n    std::shared_ptr<Classifier_Impl> weak_classifier\n        = weak_learner->generate(context, data, weights, features, Z);\n\n    const Feature_Space & fs = *data.feature_space();\n\n    if (fs.type() == DENSE)\n        opt_info = weak_classifier->optimize(fs.dense_features());\n\n    /* Update the d distribution. */\n    double total = 0.0;\n    double correct = 0.0;\n\n    size_t nx = data.example_count();\n    if (nx != output.shape()[0])\n        throw Exception(\"update_scores: example counts don't match\");\n\n    typedef Normal_Updater<Boosting_Predict> Output_Updater;\n    Output_Updater output_updater(nl);\n\n    if (cost_function == CF_EXPONENTIAL) {\n        typedef Boosting_Loss Loss;\n        if (bin_sym) {\n            typedef Binsym_Updater<Loss> Weights_Updater;\n            typedef Update_Weights_And_Scores_Parallel\n                <Weights_Updater, Output_Updater, Binsym_Scorer>\n                Update;\n            Weights_Updater weights_updater;\n            Update update(weights_updater, output_updater);\n            \n            update(*weak_classifier, opt_info,\n                   1.0, weights, output, data, ex_weights,\n                   correct, total);\n        }\n        else {\n            typedef Normal_Updater<Loss> Weights_Updater;\n            typedef Update_Weights_And_Scores_Parallel\n                <Weights_Updater, Output_Updater, Normal_Scorer>\n                Update;\n            Weights_Updater weights_updater(nl);\n            Update update(weights_updater, output_updater);\n\n            update(*weak_classifier, opt_info,\n                   1.0, weights, output, data, ex_weights,\n                   correct, total);\n        }\n    }\n    else if (cost_function == CF_LOGISTIC) {\n        throw Exception(\"Boosting_Generator::train_iteration(): \"\n                        \"what is Z for logistic loss?\");\n#if 0\n        typedef Logistic_Loss Loss;\n        Loss loss(stump.Z);\n\n        if (bin_sym) {\n            typedef Binsym_Updater<Loss> Weights_Updater;\n            typedef Update_Weights_And_Scores_Parallel\n                <Weights_Updater, Output_Updater, Binsym_Scorer>\n                Update;\n            Weights_Updater weights_updater(loss);\n            Update update(weights_updater, output_updater);\n\n            update(stump, opt_info,\n                   1.0, weights, output, data, ex_weights,\n                   correct, total);\n        }\n        else {\n            typedef Normal_Updater<Loss> Weights_Updater;\n            typedef Update_Weights_And_Scores_Parallel\n                <Weights_Updater, Output_Updater, Normal_Scorer>\n                Update;\n            Weights_Updater weights_updater(nl, loss);\n            Update update(weights_updater, output_updater);\n\n            update(stump, opt_info,\n                   1.0, weights, output, data, ex_weights,\n                   correct, total);\n        }\n#endif\n    }\n    else throw Exception(\"Boosted_Stumps_Generator::train_iteration: \"\n                         \"unknown cost function\");\n\n    if (Z == 0.0) Z = total;\n\n    //cerr << \"total = \" << total << \" Z = \" << Z << endl;\n\n    training_accuracy = correct / ex_weights.total();\n\n    float * start = weights.data();\n    float * finish = start + weights.num_elements();\n    SIMD::vec_scale(start, 1.0 / total, start, finish - start);\n    \n    return weak_classifier;\n}\n\n\n/* This does the following: \n   - Trains a stump\n   - Updates the weights\n   - Updates the output weights\n   - Calculates the accuracy over the training set\n\n   all in one pass (which saves on execution time as less memory is used).\n*/\n\ndouble\nBoosting_Generator::\nupdate_accuracy(Thread_Context & context,\n                const Classifier_Impl & weak_classifier,\n                const Optimization_Info & opt_info,\n                const Training_Data & data,\n                const vector<Feature> & features,\n                boost::multi_array<float, 2> & output,\n                const distribution<float> & ex_weights) const\n{\n    bool bin_sym\n        = convert_bin_sym(output, data, predicted, features);\n\n    double correct = 0.0;\n\n    if (bin_sym) {\n        typedef Binsym_Updater<Boosting_Predict> Output_Updater;\n        Output_Updater output_updater;\n        \n        typedef Update_Scores_Parallel<Output_Updater, Binsym_Scorer> Update;\n        Update update(output_updater);\n        \n        update(weak_classifier, opt_info,\n               1.0, output, data, ex_weights, correct);\n    }\n    else {\n        typedef Normal_Updater<Boosting_Predict> Output_Updater;\n        Output_Updater output_updater(nl);\n        \n        typedef Update_Scores_Parallel<Output_Updater, Normal_Scorer> Update;\n        Update update(output_updater);\n        \n        update(weak_classifier, opt_info,\n               1.0, output, data, ex_weights, correct);\n    }\n    \n    return correct / ex_weights.total();\n}\n\n\n/*****************************************************************************/\n/* REGISTRATION                                                              */\n/*****************************************************************************/\n\nnamespace {\n\nRegister_Factory<Classifier_Generator, Boosting_Generator>\n    BOOSTING_REGISTER(\"boosting\");\n\n} // file scope\n\n} // namespace ML\n", "meta": {"hexsha": "6b1e9e753d3fa4a627ebbf71e5b136cebe1d3931", "size": 21081, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/jml/boosting_generator.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": "plugins/jml/jml/boosting_generator.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": "plugins/jml/jml/boosting_generator.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": 31.7007518797, "max_line_length": 85, "alphanum_fraction": 0.5762534984, "num_tokens": 4738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.030675800159883637, "lm_q1q2_score": 0.014261227697465944}}
{"text": "//\r\n//=======================================================================\r\n// Copyright 2007 Stanford University\r\n// Authors: David Gleich\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 BOOST_GRAPH_CORE_NUMBERS_HPP\r\n#define BOOST_GRAPH_CORE_NUMBERS_HPP\r\n\r\n#include <boost/graph/detail/d_ary_heap.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include <boost/iterator/reverse_iterator.hpp>\r\n#include <boost/concept/assert.hpp>\r\n\r\n/*\r\n * core_numbers\r\n *\r\n * Requirement: IncidenceGraph\r\n */\r\n\r\n// History\r\n//\r\n// 30 July 2007\r\n// Added visitors to the implementation\r\n//\r\n// 8 February 2008\r\n// Fixed headers and missing typename\r\n\r\nnamespace boost\r\n{\r\n\r\n// A linear time O(m) algorithm to compute the indegree core number\r\n// of a graph for unweighted graphs.\r\n//\r\n// and a O((n+m) log n) algorithm to compute the in-edge-weight core\r\n// numbers of a weighted graph.\r\n//\r\n// The linear algorithm comes from:\r\n// Vladimir Batagelj and Matjaz Zaversnik, \"An O(m) Algorithm for Cores\r\n// Decomposition of Networks.\"  Sept. 1 2002.\r\n\r\ntemplate < typename Visitor, typename Graph > struct CoreNumbersVisitorConcept\r\n{\r\n    void constraints()\r\n    {\r\n        BOOST_CONCEPT_ASSERT((CopyConstructibleConcept< Visitor >));\r\n        vis.examine_vertex(u, g);\r\n        vis.finish_vertex(u, g);\r\n        vis.examine_edge(e, g);\r\n    }\r\n    Visitor vis;\r\n    Graph g;\r\n    typename graph_traits< Graph >::vertex_descriptor u;\r\n    typename graph_traits< Graph >::edge_descriptor e;\r\n};\r\n\r\ntemplate < class Visitors = null_visitor >\r\nclass core_numbers_visitor : public bfs_visitor< Visitors >\r\n{\r\npublic:\r\n    core_numbers_visitor() {}\r\n    core_numbers_visitor(Visitors vis) : bfs_visitor< Visitors >(vis) {}\r\n\r\nprivate:\r\n    template < class Vertex, class Graph >\r\n    void initialize_vertex(Vertex, Graph&)\r\n    {\r\n    }\r\n\r\n    template < class Vertex, class Graph > void discover_vertex(Vertex, Graph&)\r\n    {\r\n    }\r\n\r\n    template < class Vertex, class Graph > void gray_target(Vertex, Graph&) {}\r\n\r\n    template < class Vertex, class Graph > void black_target(Vertex, Graph&) {}\r\n\r\n    template < class Edge, class Graph > void tree_edge(Edge, Graph&) {}\r\n\r\n    template < class Edge, class Graph > void non_tree_edge(Edge, Graph&) {}\r\n};\r\n\r\ntemplate < class Visitors >\r\ncore_numbers_visitor< Visitors > make_core_numbers_visitor(Visitors vis)\r\n{\r\n    return core_numbers_visitor< Visitors >(vis);\r\n}\r\n\r\ntypedef core_numbers_visitor<> default_core_numbers_visitor;\r\n\r\nnamespace detail\r\n{\r\n\r\n    // implement a constant_property_map to simplify compute_in_degree\r\n    // for the weighted and unweighted case\r\n    // this is based on dummy property map\r\n    template < typename ValueType >\r\n    class constant_value_property_map\r\n    : public boost::put_get_helper< ValueType,\r\n          constant_value_property_map< ValueType > >\r\n    {\r\n    public:\r\n        typedef void key_type;\r\n        typedef ValueType value_type;\r\n        typedef const ValueType& reference;\r\n        typedef boost::readable_property_map_tag category;\r\n        inline constant_value_property_map(ValueType cc) : c(cc) {}\r\n        inline constant_value_property_map(\r\n            const constant_value_property_map< ValueType >& x)\r\n        : c(x.c)\r\n        {\r\n        }\r\n        template < class Vertex > inline reference operator[](Vertex) const\r\n        {\r\n            return c;\r\n        }\r\n\r\n    protected:\r\n        ValueType c;\r\n    };\r\n\r\n    // the core numbers start as the indegree or inweight.  This function\r\n    // will initialize these values\r\n    template < typename Graph, typename CoreMap, typename EdgeWeightMap >\r\n    void compute_in_degree_map(Graph& g, CoreMap d, EdgeWeightMap wm)\r\n    {\r\n        typename graph_traits< Graph >::vertex_iterator vi, vi_end;\r\n        typename graph_traits< Graph >::out_edge_iterator ei, ei_end;\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            put(d, *vi, 0);\r\n        }\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            for (boost::tie(ei, ei_end) = out_edges(*vi, g); ei != ei_end; ++ei)\r\n            {\r\n                put(d, target(*ei, g), get(d, target(*ei, g)) + get(wm, *ei));\r\n            }\r\n        }\r\n    }\r\n\r\n    // the version for weighted graphs is a little different\r\n    template < typename Graph, typename CoreMap, typename EdgeWeightMap,\r\n        typename MutableQueue, typename Visitor >\r\n    typename property_traits< CoreMap >::value_type core_numbers_impl(\r\n        Graph& g, CoreMap c, EdgeWeightMap wm, MutableQueue& Q, Visitor vis)\r\n    {\r\n        typename property_traits< CoreMap >::value_type v_cn = 0;\r\n        typedef typename graph_traits< Graph >::vertex_descriptor vertex;\r\n        while (!Q.empty())\r\n        {\r\n            // remove v from the Q, and then decrease the core numbers\r\n            // of its successors\r\n            vertex v = Q.top();\r\n            vis.examine_vertex(v, g);\r\n            Q.pop();\r\n            v_cn = get(c, v);\r\n            typename graph_traits< Graph >::out_edge_iterator oi, oi_end;\r\n            for (boost::tie(oi, oi_end) = out_edges(v, g); oi != oi_end; ++oi)\r\n            {\r\n                vis.examine_edge(*oi, g);\r\n                vertex u = target(*oi, g);\r\n                // if c[u] > c[v], then u is still in the graph,\r\n                if (get(c, u) > v_cn)\r\n                {\r\n                    // remove the edge\r\n                    put(c, u, get(c, u) - get(wm, *oi));\r\n                    if (Q.contains(u))\r\n                        Q.update(u);\r\n                }\r\n            }\r\n            vis.finish_vertex(v, g);\r\n        }\r\n        return (v_cn);\r\n    }\r\n\r\n    template < typename Graph, typename CoreMap, typename EdgeWeightMap,\r\n        typename IndexMap, typename CoreNumVisitor >\r\n    typename property_traits< CoreMap >::value_type core_numbers_dispatch(\r\n        Graph& g, CoreMap c, EdgeWeightMap wm, IndexMap im, CoreNumVisitor vis)\r\n    {\r\n        typedef typename property_traits< CoreMap >::value_type D;\r\n        typedef std::less< D > Cmp;\r\n        // build the mutable queue\r\n        typedef typename graph_traits< Graph >::vertex_descriptor vertex;\r\n        std::vector< std::size_t > index_in_heap_data(num_vertices(g));\r\n        typedef iterator_property_map< std::vector< std::size_t >::iterator,\r\n            IndexMap >\r\n            index_in_heap_map_type;\r\n        index_in_heap_map_type index_in_heap_map(\r\n            index_in_heap_data.begin(), im);\r\n        typedef d_ary_heap_indirect< vertex, 4, index_in_heap_map_type, CoreMap,\r\n            Cmp >\r\n            MutableQueue;\r\n        MutableQueue Q(c, index_in_heap_map, Cmp());\r\n        typename graph_traits< Graph >::vertex_iterator vi, vi_end;\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            Q.push(*vi);\r\n        }\r\n        return core_numbers_impl(g, c, wm, Q, vis);\r\n    }\r\n\r\n    // the version for the unweighted case\r\n    // for this functions CoreMap must be initialized\r\n    // with the in degree of each vertex\r\n    template < typename Graph, typename CoreMap, typename PositionMap,\r\n        typename Visitor >\r\n    typename property_traits< CoreMap >::value_type core_numbers_impl(\r\n        Graph& g, CoreMap c, PositionMap pos, Visitor vis)\r\n    {\r\n        typedef typename graph_traits< Graph >::vertices_size_type size_type;\r\n        typedef typename graph_traits< Graph >::degree_size_type degree_type;\r\n        typedef typename graph_traits< Graph >::vertex_descriptor vertex;\r\n        typename graph_traits< Graph >::vertex_iterator vi, vi_end;\r\n\r\n        // store the vertex core numbers\r\n        typename property_traits< CoreMap >::value_type v_cn = 0;\r\n\r\n        // compute the maximum degree (degrees are in the coremap)\r\n        typename graph_traits< Graph >::degree_size_type max_deg = 0;\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            max_deg = (std::max<\r\n                typename graph_traits< Graph >::degree_size_type >)(max_deg,\r\n                get(c, *vi));\r\n        }\r\n\r\n        // store the vertices in bins by their degree\r\n        // allocate two extra locations to ease boundary cases\r\n        std::vector< size_type > bin(max_deg + 2);\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            ++bin[get(c, *vi)];\r\n        }\r\n\r\n        // this loop sets bin[d] to the starting position of vertices\r\n        // with degree d in the vert array for the bucket sort\r\n        size_type cur_pos = 0;\r\n        for (degree_type cur_deg = 0; cur_deg < max_deg + 2; ++cur_deg)\r\n        {\r\n            degree_type tmp = bin[cur_deg];\r\n            bin[cur_deg] = cur_pos;\r\n            cur_pos += tmp;\r\n        }\r\n\r\n        // perform the bucket sort with pos and vert so that\r\n        // pos[0] is the vertex of smallest degree\r\n        std::vector< vertex > vert(num_vertices(g));\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            vertex v = *vi;\r\n            size_type p = bin[get(c, v)];\r\n            put(pos, v, p);\r\n            vert[p] = v;\r\n            ++bin[get(c, v)];\r\n        }\r\n        // we ``abused'' bin while placing the vertices, now,\r\n        // we need to restore it\r\n        std::copy(boost::make_reverse_iterator(bin.end() - 2),\r\n            boost::make_reverse_iterator(bin.begin()),\r\n            boost::make_reverse_iterator(bin.end() - 1));\r\n        // now simulate removing the vertices\r\n        for (size_type i = 0; i < num_vertices(g); ++i)\r\n        {\r\n            vertex v = vert[i];\r\n            vis.examine_vertex(v, g);\r\n            v_cn = get(c, v);\r\n            typename graph_traits< Graph >::out_edge_iterator oi, oi_end;\r\n            for (boost::tie(oi, oi_end) = out_edges(v, g); oi != oi_end; ++oi)\r\n            {\r\n                vis.examine_edge(*oi, g);\r\n                vertex u = target(*oi, g);\r\n                // if c[u] > c[v], then u is still in the graph,\r\n                if (get(c, u) > v_cn)\r\n                {\r\n                    degree_type deg_u = get(c, u);\r\n                    degree_type pos_u = get(pos, u);\r\n                    // w is the first vertex with the same degree as u\r\n                    // (this is the resort operation!)\r\n                    degree_type pos_w = bin[deg_u];\r\n                    vertex w = vert[pos_w];\r\n                    if (u != v)\r\n                    {\r\n                        // swap u and w\r\n                        put(pos, u, pos_w);\r\n                        put(pos, w, pos_u);\r\n                        vert[pos_w] = u;\r\n                        vert[pos_u] = w;\r\n                    }\r\n                    // now, the vertices array is sorted assuming\r\n                    // we perform the following step\r\n                    // start the set of vertices with degree of u\r\n                    // one into the future (this now points at vertex\r\n                    // w which we swapped with u).\r\n                    ++bin[deg_u];\r\n                    // we are removing v from the graph, so u's degree\r\n                    // decreases\r\n                    put(c, u, get(c, u) - 1);\r\n                }\r\n            }\r\n            vis.finish_vertex(v, g);\r\n        }\r\n        return v_cn;\r\n    }\r\n\r\n} // namespace detail\r\n\r\n// non-named parameter version for the unweighted case\r\ntemplate < typename Graph, typename CoreMap, typename CoreNumVisitor >\r\ntypename property_traits< CoreMap >::value_type core_numbers(\r\n    Graph& g, CoreMap c, CoreNumVisitor vis)\r\n{\r\n    typedef typename graph_traits< Graph >::vertices_size_type size_type;\r\n    detail::compute_in_degree_map(g, c,\r\n        detail::constant_value_property_map<\r\n            typename property_traits< CoreMap >::value_type >(1));\r\n    return detail::core_numbers_impl(g, c,\r\n        make_iterator_property_map(\r\n            std::vector< size_type >(num_vertices(g)).begin(),\r\n            get(vertex_index, g)),\r\n        vis);\r\n}\r\n\r\n// non-named paramter version for the unweighted case\r\ntemplate < typename Graph, typename CoreMap >\r\ntypename property_traits< CoreMap >::value_type core_numbers(\r\n    Graph& g, CoreMap c)\r\n{\r\n    return core_numbers(g, c, make_core_numbers_visitor(null_visitor()));\r\n}\r\n\r\n// non-named parameter version for the weighted case\r\ntemplate < typename Graph, typename CoreMap, typename EdgeWeightMap,\r\n    typename VertexIndexMap, typename CoreNumVisitor >\r\ntypename property_traits< CoreMap >::value_type core_numbers(Graph& g,\r\n    CoreMap c, EdgeWeightMap wm, VertexIndexMap vim, CoreNumVisitor vis)\r\n{\r\n    detail::compute_in_degree_map(g, c, wm);\r\n    return detail::core_numbers_dispatch(g, c, wm, vim, vis);\r\n}\r\n\r\n// non-named parameter version for the weighted case\r\n//    template <typename Graph, typename CoreMap, typename EdgeWeightMap>\r\n//    typename property_traits<CoreMap>::value_type\r\n//    core_numbers(Graph& g, CoreMap c, EdgeWeightMap wm)\r\n//    {\r\n//        typedef typename graph_traits<Graph>::vertices_size_type size_type;\r\n//        detail::compute_in_degree_map(g,c,wm);\r\n//        return detail::core_numbers_dispatch(g,c,wm,get(vertex_index,g),\r\n//            make_core_numbers_visitor(null_visitor()));\r\n//    }\r\n\r\ntemplate < typename Graph, typename CoreMap >\r\ntypename property_traits< CoreMap >::value_type weighted_core_numbers(\r\n    Graph& g, CoreMap c)\r\n{\r\n    return weighted_core_numbers(\r\n        g, c, make_core_numbers_visitor(null_visitor()));\r\n}\r\n\r\ntemplate < typename Graph, typename CoreMap, typename CoreNumVisitor >\r\ntypename property_traits< CoreMap >::value_type weighted_core_numbers(\r\n    Graph& g, CoreMap c, CoreNumVisitor vis)\r\n{\r\n    return core_numbers(g, c, get(edge_weight, g), get(vertex_index, g), vis);\r\n}\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_CORE_NUMBERS_HPP\r\n", "meta": {"hexsha": "f37cf263a9184b0999a8cbc584b2e99ce88922ac", "size": 14038, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/core_numbers.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/core_numbers.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/core_numbers.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": 37.335106383, "max_line_length": 81, "alphanum_fraction": 0.5864083203, "num_tokens": 3089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.04084571897483595, "lm_q1q2_score": 0.014240661772670233}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Alexander Sokolov <asokolov@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_IMPLODER_HPP\n#define CRYPTO3_DETAIL_IMPLODER_HPP\n\n#include <nil/crypto3/detail/stream_endian.hpp>\n#include <nil/crypto3/detail/unbounded_shift.hpp>\n#include <nil/crypto3/detail/reverser.hpp>\n\n#include <boost/static_assert.hpp>\n\nnamespace nil {\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 nil\n\n#endif    // CRYPTO3_DETAIL_IMPLODER_HPP", "meta": {"hexsha": "73204e43cb70a9c9f1ccd0bc35269afe94ad84c7", "size": 7840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/imploder.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-23T02:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T02:25:55.000Z", "max_issues_repo_path": "include/nil/crypto3/detail/imploder.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/imploder.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": 49.3081761006, "max_line_length": 119, "alphanum_fraction": 0.6179846939, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.03461883672266573, "lm_q1q2_score": 0.014232180056861608}}
{"text": "// FILE: src/misc.cpp  Date Modified: March 17, 2015\n// PacketGenie\n// Copyright 2014 The Regents of the University of Michigan\n// Dong-Hyeon Park, Ritesh Parikh, Valeria Bertacco\n// \n// PacketGenie is licensed under the Apache License, Version 2.0\n// (the \"License\"); you may not use this file except in compliance\n// with the License. You may obtain a copy of the License at\n//     http://www.apache.org/licenses/LICENSE-2.0\n//     \n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n\n\n\n#ifndef _MISC_CPP_\n#define _MISC_CPP_\n\n\n#include <list>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <ostream>\n#include <sstream>\n#include <fstream>\n#include <cstdlib>\n#include \"globals.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <boost/regex.hpp>\n\nstatic const boost::regex\n    range_specifier( \"^(\\\\d+)-(\\\\d+)$\" );\nstatic const boost::regex\n    valid_idx(\"^\\\\d+$\");\nstatic const boost::regex\n    keyword_syntax(\"^[A-Z]+$\");\n\n\nstatic int factorial(int n)\n{\n  return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;\n}\n\n// Allow printing of vector data.\ntemplate<typename T>\nostream& operator<< (ostream& out, const vector<T> v) {\n    int last = v.size() - 1;\n    out << \"[\";\n    for(int i = 0; i < last; i++)\n        out << v[i] << \", \";\n    out << v[last] << \"]\";\n    return out;\n}\n\nstatic bool lessThan(const int& num1, const int& num2)\n{\n      return num1 < num2;\n}\n\nstatic int strvec_to_intlist(vector<string> *strvec, list<int> *intlist)\n{\n    try\n    {\n        for (vector<string>::iterator it = strvec->begin();\n             it != strvec->end(); ++it)\n        {\n            intlist->push_back(boost::lexical_cast<int>(*it));\n        }\n        return SUCCESS;\n    }\n    catch (const boost::bad_lexical_cast &)\n    {\n        cerr << \"ERROR: BAD CASTING\" << endl;\n        return ERROR;\n    }\n}\n\nstatic int strvec_to_doubvec(vector<string> *strvec, vector<double> *doubvec)\n{\n    try\n    {\n        for (vector<string>::iterator it = strvec->begin();\n             it != strvec->end(); ++it)\n        {\n            doubvec->push_back(boost::lexical_cast<double>(*it));\n        }\n        return SUCCESS;\n    }\n    catch (const boost::bad_lexical_cast &)\n    {\n        cerr << \"ERROR: BAD CASTING\" << endl;\n        return ERROR;\n    }\n}\n\n\nstatic int write_output(string &filename, string &write_data)\n{\n      ofstream outfile;\n      outfile.open(filename.c_str());\n      outfile << write_data;\n      outfile.close();\n\n      return 0;\n\n}\n\nstatic int process_keyword(string token, list<int> *intlist, int ntwk_size)\n{\n\n      int init, term, step;\n      if (token == \"ALL\")\n      {\n          init = 0;\n          term = ntwk_size;\n          step = 1;\n      }\n      else if (token == \"EVEN\")\n      {\n          init = 0;\n          term =  ntwk_size;\n          step = 2;\n      }\n      else if (token == \"ODD\")\n      {\n          init = 1;\n          term = ntwk_size;\n          step = 2;\n      }\n      else\n          return ERROR;\n\n      for (int i = init; i < term; i += step)\n          intlist->push_back(i);\n\n      return SUCCESS;\n}\n\nstatic int interpret_range(string token, list<int> *intlist)\n{\n      int split_pos = token.find_first_of('-');\n      int init = boost::lexical_cast<int>(token.substr(0, split_pos));\n      int last = boost::lexical_cast<int>(token.substr(split_pos+1));\n\n      for (int i = init; i <= last ; ++i)\n           intlist->push_back(i);\n\n\n      return SUCCESS;\n\n}\n\n//Extract string that are between { }\nstatic\tint extract_idxstr(vector<string> *strvec,  vector<string> &node_idxs)\n{\n      vector<string>::iterator first, last;\n      bool brk_found = false;\n      bool done = false;\n\n      for ( vector<string>::iterator it = strvec->begin(); it != strvec->end();\n            ++it)\n      { \n            if (*it == \"{\")\n            {\n                if (brk_found)\n                    return ERROR;\n                first = it;\n                ++first; // Exclude the bracket\n                brk_found = true;\n            }\n\n            if (*it == \"}\")\n            {\n                if (!brk_found)\n                    return ERROR;\n                last = it;\n                done = true;\n                break;\n            }\n      }\n\n      if (!done)\n          return ERROR;\n\n      node_idxs = vector<string>(first, last);\n      return SUCCESS;\n}\n\n\n// Extract strings that are between < >\nstatic\tint extract_str(vector<string> *strvec,  vector<string> &extracted)\n{\n      vector<string>::iterator first, last;\n      bool brk_found = false;\n      bool done = false;\n\n      for ( vector<string>::iterator it = strvec->begin(); it != strvec->end();\n            ++it)\n      { \n            if (*it == \"<\")\n            {\n                if (brk_found)\n                    return ERROR;\n                first = it;\n                ++first; // Exclude the bracket\n                brk_found = true;\n            }\n\n            if (*it == \">\")\n            {\n                if (!brk_found)\n                    return ERROR;\n                last = it;\n                done = true;\n                break;\n            }\n      }\n\n      if (!done)\n          return ERROR;\n\n      extracted = vector<string>(first, last);\n      return SUCCESS;\n\n}\n\n\n// Looks at a string vector and parse out the node index values inside\n// { } into an integer list \nstatic int process_strvec(vector<string> *raw_strvec, \n                          list<int> *intlist, int ntwk_size)\n{\n\n      vector<string> str_vec;\n\n\n      boost::smatch str_matches;\n      size_t size_max = ntwk_size;\n      int error;\n\n      error = extract_idxstr(raw_strvec, str_vec);\n      if (error)\n          return error;\n\n      // Look for any special keyword\n      vector<string>::iterator it = str_vec.begin();\n      if ( boost::regex_match(*it, str_matches, keyword_syntax) )\n      {\n            // Process Keyword\n            process_keyword(*it, intlist, ntwk_size);\n            ++it;\n      }\n\n      unsigned int idx;\n      string idx_str;\n\n      // NEED TO LOOP THROUGH AND CHECK FOR RANGE. \n      while(it != str_vec.end())\n      {\n          idx_str = *it;\n\n          if ( boost::regex_match(idx_str, str_matches, range_specifier) )\n          {\n                // Process range syntax\n                interpret_range(idx_str, intlist);\n\n          }\n          else if (boost::regex_match(idx_str, str_matches, valid_idx) )\n          {\n              // Process a regular single integer index\n              idx = boost::lexical_cast<int>(idx_str);\n\n              if ( idx <  size_max )\n              {\n                    intlist->push_back(idx);\n              }\n              else\n              {\n                  cerr << \"ERROR node index out of bounds \" << endl\n                       << \"Index parsed: \" << idx  \n                       << \"Max allowed: \" << size_max <<endl;\n                  return ERROR;\n              }\n          }\n          else\n          {\n              cerr << \"ERROR: Invalid node index - \" << idx_str << endl;\n              return ERROR;\n          }\n          ++it;\n    }\n   \n    // Sort the list from smallest to largest.\n    intlist->sort(lessThan);\n    // Remove duplicates\n    intlist->unique(); \n    return SUCCESS;\n  \n}\n\nstatic vector<string>& get_strvec(multimap< string,vector<string> > &mmap, \n                                  const string &key)\n{\n      return mmap.find(key)->second;\n\n}\n\n/*\nstatic int generate_node_prob(string name, size_t m, list<double> *prob_dist)\n{\n    double temp;\n\n    if (prob_dist->size() != 0)\n        return ERROR;\n\n    if ( name == \"uniform\")\n    {\n        temp = 1.0;\n        for (size_t i = 0; i < m; ++i)\n            prob_dist->push_back(temp);\n        \n        return SUCCESS;\n    }\n\n    return ERROR;\n}\n*/\n\n// Give random number between 0 and 1. (1 not included)\nstatic double get_rand_decimal()\n{\n    return rand() / (RAND_MAX+1.0); \n}\n\n\nstatic double factorial(size_t val)\n{\n    size_t ret = 1;\n    for (size_t i = 1; i <= val; ++i)\n        ret *= i;\n    return ret;\n}\n\n// For s=1\nstatic double erlang_delay_constant(double arrival_rate, \n                                    double service_time)\n{\n    double a, util_fac;\n//          size_t num_server, s_fac;\n          \n//          num_server = 1;\n//          s_fac = factorial(num_server);\n\n    a = arrival_rate * service_time;\n    if (a >= 1)\n        return 1; // Utilization factor becomes 1.\n\n    util_fac = a;\n\n    return (a/(1-util_fac)) / ( a + a/(1-util_fac));\n}\n\nstatic double erlang_delay_constant(size_t num,\n                                    double arrival_rate, \n                                    double service_time)\n{\n    double numerator, denominator;\n    double a, a_pow_s, util_fac;\n    int num_factorial = factorial(num);\n\n    a = arrival_rate * service_time;\n    a_pow_s = pow(a,num);\n    if (a >= 1)\n        return 1; // Utilization factor becomes 1.\n\n    util_fac = a;\n\n    numerator = a_pow_s/(num_factorial*(1-util_fac));\n    denominator = numerator;\n    for (size_t k=0; k<num; k++)\n        denominator += pow(a,k)/factorial(k);\n\n    return (numerator /denominator);\n}\n\nstatic double erlang_prob_wait(size_t wait_time, \n                               double arrival_rate,\n                               double service_time,\n                               double erlangC)\n{\n    double a, util_fac;\n    a = arrival_rate * service_time;\n    if (a >= 1)\n        return erlangC;\n\n    util_fac = a;\n    return erlangC*exp(-1*(1-util_fac)*(1/service_time)*wait_time);\n}\n\nstatic double erlang_prob_wait(size_t wait_time, \n                               size_t num,\n                               double arrival_rate,\n                               double service_time,\n                               double erlangC)\n{\n    double a, util_fac;\n    a = arrival_rate * service_time;\n    if (a >= 1)\n        return erlangC;\n\n    util_fac = a;\n    return erlangC*exp(-1*(1-util_fac)*(num/service_time)*wait_time);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "302954376c7ce4f6e5dd823d8e23e93d38a92b24", "size": 10128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/misc.cpp", "max_stars_repo_name": "packetgenie/PacketGenie", "max_stars_repo_head_hexsha": "cf09d39f53b9e6119c0ebe77134a032a082c81fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-20T12:31:02.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-20T12:31:02.000Z", "max_issues_repo_path": "src/misc.cpp", "max_issues_repo_name": "packetgenie/PacketGenie", "max_issues_repo_head_hexsha": "cf09d39f53b9e6119c0ebe77134a032a082c81fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/misc.cpp", "max_forks_repo_name": "packetgenie/PacketGenie", "max_forks_repo_head_hexsha": "cf09d39f53b9e6119c0ebe77134a032a082c81fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-08-19T14:47:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-30T15:58:07.000Z", "avg_line_length": 23.2293577982, "max_line_length": 79, "alphanum_fraction": 0.5282385466, "num_tokens": 2414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.033085976362697465, "lm_q1q2_score": 0.014231845007788185}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_OB_TRAN_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// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/shared_ptr.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 srs { namespace par4\r\n{\r\n    //struct ob_tran_oblique {};\r\n    //struct ob_tran_transverse {};\r\n    struct ob_tran {};\r\n\r\n}} //namespace srs::par4\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail {\r\n    \r\n        // fwd declaration needed below\r\n        template <typename CalculationType>\r\n        inline detail::base_v<CalculationType, parameters<CalculationType> >*\r\n            create_new(parameters<CalculationType> const& parameters);\r\n\r\n    } // namespace detail\r\n\r\n    namespace detail { namespace ob_tran\r\n    {\r\n\r\n            static const double TOL = 1e-10;\r\n\r\n            template <typename Parameters>\r\n            inline Parameters o_proj_parameters(Parameters const& par)\r\n            {\r\n                Parameters pj;\r\n\r\n                /* get name of projection to be translated */\r\n                pj.name = pj_param(par.params, \"so_proj\").s;\r\n                /* copy existing header into new */\r\n                pj.params = par.params;\r\n                pj.over = par.over;\r\n                pj.geoc = par.geoc;\r\n                pj.a = par.a;\r\n                pj.es = par.es;\r\n                pj.ra = par.ra;\r\n                pj.lam0 = par.lam0;\r\n                pj.phi0 = par.phi0;\r\n                pj.x0 = par.x0;\r\n                pj.y0 = par.y0;\r\n                pj.k0 = par.k0;\r\n                /* force spherical earth */\r\n                pj.one_es = pj.rone_es = 1.;\r\n                pj.es = pj.e = 0.;\r\n\r\n                return pj;\r\n            }\r\n\r\n            template <typename CalculationType, typename Parameters>\r\n            struct par_ob_tran\r\n            {\r\n                par_ob_tran(Parameters const& par)\r\n                    : link(projections::detail::create_new(o_proj_parameters(par)))\r\n                {\r\n                    if (! link.get())\r\n                        BOOST_THROW_EXCEPTION( projection_exception(-26) );\r\n                }\r\n\r\n                template <typename T>\r\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    link->fwd(lp_lon, lp_lat, xy_x, xy_y);\r\n                }\r\n\r\n                template <typename T>\r\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    link->inv(xy_x, xy_y, lp_lon, lp_lat);\r\n                }\r\n\r\n                boost::shared_ptr<base_v<CalculationType, Parameters> > link;\r\n                CalculationType lamp;\r\n                CalculationType cphip, sphip;\r\n            };\r\n\r\n            template <typename StaticParameters, typename CalculationType, typename Parameters>\r\n            struct par_ob_tran_static\r\n            {\r\n                typedef typename srs::par4::detail::pick_o_proj_tag\r\n                    <\r\n                        StaticParameters\r\n                    >::type o_proj_tag;\r\n\r\n                typedef typename projections::detail::static_projection_type\r\n                    <\r\n                        o_proj_tag,\r\n                        srs_sphere_tag, // force spherical\r\n                        StaticParameters,\r\n                        CalculationType,\r\n                        Parameters\r\n                    >::type projection_type;\r\n\r\n                par_ob_tran_static(Parameters const& par)\r\n                    : link(o_proj_parameters(par))\r\n                {}\r\n\r\n                template <typename T>\r\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    link.fwd(lp_lon, lp_lat, xy_x, xy_y);\r\n                }\r\n\r\n                template <typename T>\r\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    link.inv(xy_x, xy_y, lp_lon, lp_lat);\r\n                }\r\n\r\n                projection_type link;\r\n                CalculationType lamp;\r\n                CalculationType cphip, sphip;\r\n            };\r\n\r\n            template <typename T, typename Par>\r\n            inline void o_forward(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y, Par const& proj_parm)\r\n            {\r\n                T coslam, sinphi, cosphi;\r\n                \r\n                coslam = cos(lp_lon);\r\n                sinphi = sin(lp_lat);\r\n                cosphi = cos(lp_lat);\r\n                lp_lon = adjlon(aatan2(cosphi * sin(lp_lon), proj_parm.sphip * cosphi * coslam +\r\n                    proj_parm.cphip * sinphi) + proj_parm.lamp);\r\n                lp_lat = aasin(proj_parm.sphip * sinphi - proj_parm.cphip * cosphi * coslam);\r\n\r\n                proj_parm.fwd(lp_lon, lp_lat, xy_x, xy_y);\r\n            }\r\n\r\n            template <typename T, typename Par>\r\n            inline void o_inverse(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat, Par const& proj_parm)\r\n            {\r\n                T coslam, sinphi, cosphi;\r\n\r\n                proj_parm.inv(xy_x, xy_y, lp_lon, lp_lat);\r\n                if (lp_lon != HUGE_VAL) {\r\n                    coslam = cos(lp_lon -= proj_parm.lamp);\r\n                    sinphi = sin(lp_lat);\r\n                    cosphi = cos(lp_lat);\r\n                    lp_lat = aasin(proj_parm.sphip * sinphi + proj_parm.cphip * cosphi * coslam);\r\n                    lp_lon = aatan2(cosphi * sin(lp_lon), proj_parm.sphip * cosphi * coslam -\r\n                        proj_parm.cphip * sinphi);\r\n                }\r\n            }\r\n\r\n            template <typename T, typename Par>\r\n            inline void t_forward(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y, Par const& proj_parm)\r\n            {\r\n                T cosphi, coslam;\r\n\r\n                cosphi = cos(lp_lat);\r\n                coslam = cos(lp_lon);\r\n                lp_lon = adjlon(aatan2(cosphi * sin(lp_lon), sin(lp_lat)) + proj_parm.lamp);\r\n                lp_lat = aasin(- cosphi * coslam);\r\n                proj_parm.fwd(lp_lon, lp_lat, xy_x, xy_y);\r\n            }\r\n\r\n            template <typename T, typename Par>\r\n            inline void t_inverse(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat, Par const& proj_parm)\r\n            {\r\n                T cosphi, t;\r\n\r\n                proj_parm.inv(xy_x, xy_y, lp_lon, lp_lat);\r\n                if (lp_lon != HUGE_VAL) {\r\n                    cosphi = cos(lp_lat);\r\n                    t = lp_lon - proj_parm.lamp;\r\n                    lp_lon = aatan2(cosphi * sin(t), - sin(lp_lat));\r\n                    lp_lat = aasin(cosphi * cos(t));\r\n                }\r\n            }\r\n\r\n            // General Oblique Transformation\r\n            template <typename CalculationType, typename Parameters, typename ProjParameters>\r\n            inline CalculationType setup_ob_tran(Parameters & par, ProjParameters& proj_parm)\r\n            {\r\n                static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\r\n\r\n                CalculationType phip;\r\n\r\n                par.es = 0.; /* force to spherical */\r\n\r\n                // proj_parm.link should be created at this point\r\n\r\n                if (pj_param(par.params, \"to_alpha\").i) {\r\n                    CalculationType lamc, phic, alpha;\r\n\r\n                    lamc    = pj_param(par.params, \"ro_lon_c\").f;\r\n                    phic    = pj_param(par.params, \"ro_lat_c\").f;\r\n                    alpha    = pj_param(par.params, \"ro_alpha\").f;\r\n            /*\r\n                    if (fabs(phic) <= TOL ||\r\n                        fabs(fabs(phic) - HALFPI) <= TOL ||\r\n                        fabs(fabs(alpha) - HALFPI) <= TOL)\r\n            */\r\n                    if (fabs(fabs(phic) - HALFPI) <= TOL)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(-32) );\r\n                    proj_parm.lamp = lamc + aatan2(-cos(alpha), -sin(alpha) * sin(phic));\r\n                    phip = aasin(cos(phic) * sin(alpha));\r\n                } else if (pj_param(par.params, \"to_lat_p\").i) { /* specified new pole */\r\n                    proj_parm.lamp = pj_param(par.params, \"ro_lon_p\").f;\r\n                    phip = pj_param(par.params, \"ro_lat_p\").f;\r\n                } else { /* specified new \"equator\" points */\r\n                    CalculationType lam1, lam2, phi1, phi2, con;\r\n\r\n                    lam1 = pj_param(par.params, \"ro_lon_1\").f;\r\n                    phi1 = pj_param(par.params, \"ro_lat_1\").f;\r\n                    lam2 = pj_param(par.params, \"ro_lon_2\").f;\r\n                    phi2 = pj_param(par.params, \"ro_lat_2\").f;\r\n                    if (fabs(phi1 - phi2) <= TOL ||\r\n                        (con = fabs(phi1)) <= TOL ||\r\n                        fabs(con - HALFPI) <= TOL ||\r\n                        fabs(fabs(phi2) - HALFPI) <= TOL)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(-33) );\r\n                    proj_parm.lamp = atan2(cos(phi1) * sin(phi2) * cos(lam1) -\r\n                        sin(phi1) * cos(phi2) * cos(lam2),\r\n                        sin(phi1) * cos(phi2) * sin(lam2) -\r\n                        cos(phi1) * sin(phi2) * sin(lam1));\r\n                    phip = atan(-cos(proj_parm.lamp - lam1) / tan(phi1));\r\n                }\r\n                if (fabs(phip) > TOL) { /* oblique */\r\n                    proj_parm.cphip = cos(phip);\r\n                    proj_parm.sphip = sin(phip);\r\n                } else { /* transverse */\r\n                }\r\n                // return phip to choose model\r\n                return phip;\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_ob_tran_oblique : public base_t_fi<base_ob_tran_oblique<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_ob_tran<CalculationType, Parameters> m_proj_parm;\r\n\r\n                inline base_ob_tran_oblique(Parameters const& par,\r\n                                            par_ob_tran<CalculationType, Parameters> const& proj_parm)\r\n                    : base_t_fi\r\n                        <\r\n                            base_ob_tran_oblique<CalculationType, Parameters>, CalculationType, Parameters\r\n                        >(*this, par)\r\n                    , m_proj_parm(proj_parm)\r\n                {}\r\n\r\n                // FORWARD(o_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    o_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\r\n                }\r\n\r\n                // INVERSE(o_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    o_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"ob_tran_oblique\";\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_ob_tran_transverse : public base_t_fi<base_ob_tran_transverse<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_ob_tran<CalculationType, Parameters> m_proj_parm;\r\n\r\n                inline base_ob_tran_transverse(Parameters const& par,\r\n                                               par_ob_tran<CalculationType, Parameters> const& proj_parm)\r\n                    : base_t_fi\r\n                        <\r\n                            base_ob_tran_transverse<CalculationType, Parameters>, CalculationType, Parameters\r\n                        >(*this, par)\r\n                    , m_proj_parm(proj_parm)\r\n                {}\r\n\r\n                // FORWARD(t_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    t_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\r\n                }\r\n\r\n                // INVERSE(t_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    t_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"ob_tran_transverse\";\r\n                }\r\n\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename StaticParameters, typename CalculationType, typename Parameters>\r\n            struct base_ob_tran_static : public base_t_fi<base_ob_tran_static<StaticParameters, 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_ob_tran_static<StaticParameters, CalculationType, Parameters> m_proj_parm;\r\n                bool m_is_oblique;\r\n\r\n                inline base_ob_tran_static(Parameters const& par)\r\n                    : base_t_fi<base_ob_tran_static<StaticParameters, CalculationType, Parameters>, CalculationType, Parameters>(*this, par)\r\n                    , m_proj_parm(par)\r\n                {}\r\n\r\n                // FORWARD(o_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    if (m_is_oblique) {\r\n                        o_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\r\n                    } else {\r\n                        t_forward(lp_lon, lp_lat, xy_x, xy_y, this->m_proj_parm);\r\n                    }\r\n                }\r\n\r\n                // INVERSE(o_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    if (m_is_oblique) {\r\n                        o_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\r\n                    } else {\r\n                        t_inverse(xy_x, xy_y, lp_lon, lp_lat, this->m_proj_parm);\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"ob_tran\";\r\n                }\r\n\r\n            };\r\n\r\n    }} // namespace detail::ob_tran\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief General Oblique Transformation 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         - o_proj (string)\r\n         - Plus projection parameters\r\n         - o_lat_p (degrees)\r\n         - o_lon_p (degrees)\r\n         - New pole\r\n         - o_alpha: Alpha (degrees)\r\n         - o_lon_c (degrees)\r\n         - o_lat_c (degrees)\r\n         - o_lon_1 (degrees)\r\n         - o_lat_1: Latitude of first standard parallel (degrees)\r\n         - o_lon_2 (degrees)\r\n         - o_lat_2: Latitude of second standard parallel (degrees)\r\n        \\par Example\r\n        \\image html ex_ob_tran.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct ob_tran_oblique : public detail::ob_tran::base_ob_tran_oblique<CalculationType, Parameters>\r\n    {\r\n        inline ob_tran_oblique(Parameters const& par,\r\n                               detail::ob_tran::par_ob_tran<CalculationType, Parameters> const& proj_parm)\r\n            : detail::ob_tran::base_ob_tran_oblique<CalculationType, Parameters>(par, proj_parm)\r\n        {\r\n            // already done\r\n            //detail::ob_tran::setup_ob_tran(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief General Oblique Transformation 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         - o_proj (string)\r\n         - Plus projection parameters\r\n         - o_lat_p (degrees)\r\n         - o_lon_p (degrees)\r\n         - New pole\r\n         - o_alpha: Alpha (degrees)\r\n         - o_lon_c (degrees)\r\n         - o_lat_c (degrees)\r\n         - o_lon_1 (degrees)\r\n         - o_lat_1: Latitude of first standard parallel (degrees)\r\n         - o_lon_2 (degrees)\r\n         - o_lat_2: Latitude of second standard parallel (degrees)\r\n        \\par Example\r\n        \\image html ex_ob_tran.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct ob_tran_transverse : public detail::ob_tran::base_ob_tran_transverse<CalculationType, Parameters>\r\n    {\r\n        inline ob_tran_transverse(Parameters const& par,\r\n                                  detail::ob_tran::par_ob_tran<CalculationType, Parameters> const& proj_parm)\r\n            : detail::ob_tran::base_ob_tran_transverse<CalculationType, Parameters>(par, proj_parm)\r\n        {\r\n            // already done\r\n            //detail::ob_tran::setup_ob_tran(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief General Oblique Transformation 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         - o_proj (string)\r\n         - Plus projection parameters\r\n         - o_lat_p (degrees)\r\n         - o_lon_p (degrees)\r\n         - New pole\r\n         - o_alpha: Alpha (degrees)\r\n         - o_lon_c (degrees)\r\n         - o_lat_c (degrees)\r\n         - o_lon_1 (degrees)\r\n         - o_lat_1: Latitude of first standard parallel (degrees)\r\n         - o_lon_2 (degrees)\r\n         - o_lat_2: Latitude of second standard parallel (degrees)\r\n        \\par Example\r\n        \\image html ex_ob_tran.gif\r\n    */\r\n    template <typename StaticParameters, typename CalculationType, typename Parameters>\r\n    struct ob_tran_static : public detail::ob_tran::base_ob_tran_static<StaticParameters, CalculationType, Parameters>\r\n    {\r\n        inline ob_tran_static(const Parameters& par)\r\n            : detail::ob_tran::base_ob_tran_static<StaticParameters, CalculationType, Parameters>(par)\r\n        {\r\n            CalculationType phip = detail::ob_tran::setup_ob_tran<CalculationType>(this->m_par, this->m_proj_parm);\r\n            this->m_is_oblique = fabs(phip) > detail::ob_tran::TOL;\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::ob_tran, srs_sphere_tag, BGP, CT, P>\r\n        {\r\n            typedef ob_tran_static<BGP, CT, P> type;\r\n        };\r\n        template <typename BGP, typename CT, typename P>\r\n        struct static_projection_type<srs::par4::ob_tran, srs_spheroid_tag, BGP, CT, P>\r\n        {\r\n            typedef ob_tran_static<BGP, CT, P> type;\r\n        };\r\n\r\n        // Factory entry(s)\r\n        template <typename CalculationType, typename Parameters>\r\n        class ob_tran_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                    Parameters params = par;\r\n                    detail::ob_tran::par_ob_tran<CalculationType, Parameters> proj_parm(params);\r\n                    CalculationType phip = detail::ob_tran::setup_ob_tran<CalculationType>(params, proj_parm);\r\n\r\n                    if (fabs(phip) > detail::ob_tran::TOL)\r\n                        return new base_v_fi<ob_tran_oblique<CalculationType, Parameters>, CalculationType, Parameters>(params, proj_parm);\r\n                    else\r\n                        return new base_v_fi<ob_tran_transverse<CalculationType, Parameters>, CalculationType, Parameters>(params, proj_parm);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void ob_tran_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"ob_tran\", new ob_tran_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_OB_TRAN_HPP\r\n\r\n", "meta": {"hexsha": "c2454917a9a61a5b965cbcda753590b35c8c0d8a", "size": 24193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/ob_tran.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/ob_tran.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/ob_tran.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0017361111, "max_line_length": 143, "alphanum_fraction": 0.5479270863, "num_tokens": 5093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.04208773167037179, "lm_q1q2_score": 0.014228899285116415}}
{"text": "//headers in this package\n#include <driving_force_controller.h>\n#include <ros_ship_visualization/PlotCharacteristicCurve.h>\n\n//headers for controller_interface\n#include <controller_interface/controller.h>\n\n//headers for pluginlib\n#include <pluginlib/class_list_macros.h>\n\n//headers for realtime_tools\n#include <realtime_tools/realtime_publisher.h>\n#include <realtime_tools/realtime_buffer.h>\n\n//headers for boost\n#include <boost/shared_ptr.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/thread/condition.hpp>\n#include <boost/thread.hpp>\n#include <boost/algorithm/clamp.hpp>\n\n//headers for ROS\n#include <ros/package.h>\n\n//headers for STL\n#include <vector>\n\nnamespace driving_force_controller\n{\n  DrivingForceController::DrivingForceController()\n  {\n\n  }\n\n  DrivingForceController::~DrivingForceController()\n  {\n\n  }\n\n  void DrivingForceController::drivingForceCallback(const std_msgs::Float64& msg)\n  {\n    if (isRunning())\n    {\n      driving_force_struct.value = msg.data;\n      driving_force.writeFromNonRT(driving_force_struct);\n    }\n    else\n    {\n      ROS_WARN_STREAM(\"Can't accept new commands. Controller is not running.\");\n    }\n  }\n\n  void DrivingForceController::twistCallback(const geometry_msgs::Twist& msg)\n  {\n    if (isRunning())\n    {\n      twist_struct.ang_x = msg.angular.x;\n      twist_struct.ang_y = msg.angular.y;\n      twist_struct.ang_z = msg.angular.z;\n      twist_struct.lin_x = msg.linear.x;\n      twist_struct.lin_y = msg.linear.y;\n      twist_struct.lin_z = msg.linear.z;\n      twist_struct.stamp = ros::Time::now();\n      twist.writeFromNonRT(twist_struct);\n    }\n    else\n    {\n      ROS_WARN_STREAM(\"Can't accept new commands. Controller is not running.\");\n    }\n  }\n\n  double DrivingForceController::get_thrust(double rotational_speed,double inflow_rate)\n  {\n    if(rotational_speed == 0)\n    {\n      return 0;\n    }\n    if(rotational_speed > 0)\n    {\n      double Js = inflow_rate/rotational_speed*turning_radius;\n      double Kt = k2*Js*Js + k1*Js + k0;\n      double thrust = fluid_density*std::pow(rotational_speed,2)*std::pow(turning_radius,4)*Kt;\n      return thrust;\n    }\n    if(rotational_speed < 0)\n    {\n      double Js = inflow_rate/rotational_speed*turning_radius;\n      double Kt = k2*Js*Js + k1*Js + k0;\n      double thrust = -fluid_density*std::pow(rotational_speed,2)*std::pow(turning_radius,4)*Kt;\n      return thrust;\n    }\n  }\n\n  bool DrivingForceController::init(hardware_interface::VelocityJointInterface* hw,ros::NodeHandle& controller_nh)\n  {\n    controller_nh.getParam(\"twist_topic\",twist_topic);\n    controller_nh.getParam(\"motor_command_topic\",motor_command_topic);\n    controller_nh.getParam(\"driving_force_command_topic\",driving_force_command_topic);\n    controller_nh.getParam(\"propeller/turning_radius\",turning_radius);\n    controller_nh.getParam(\"propeller/k2\",k2);\n    controller_nh.getParam(\"propeller/k1\",k1);\n    controller_nh.getParam(\"propeller/k0\",k0);\n    controller_nh.getParam(\"propeller/fluid_density\",  fluid_density);\n    controller_nh.getParam(\"characteristic_curve_file_name\",characteristic_curve_file_name);\n    controller_nh.getParam(\"gradient_descent/tolerance\",tolerance);\n    controller_nh.getParam(\"gradient_descent/alpha\",alpha);\n    controller_nh.getParam(\"max_rotational_speed\",max_rotational_speed);\n    controller_nh.getParam(\"min_rotational_speed\",min_rotational_speed);\n    //plot_characteristic_curve(0,30,1,0,30,5);\n    //boost::thread plot_thread(boost::bind(&DrivingForceController::plot_characteristic_curve,this,0,30,1,0,30,5));\n    plot_client = controller_nh.serviceClient<ros_ship_visualization::PlotCharacteristicCurve>(\"/plot_characteristic_curve\");\n    ros_ship_visualization::PlotCharacteristicCurve plot_service_message;\n    plot_service_message.request.fluid_density = fluid_density;\n    plot_service_message.request.turning_radius = turning_radius;\n    plot_service_message.request.k0 = k0;\n    plot_service_message.request.k1 = k1;\n    plot_service_message.request.k2 = k2;\n    plot_service_message.request.file_name = characteristic_curve_file_name;\n    plot_service_message.request.min_inflow_rate = 0;\n    plot_service_message.request.max_inflow_rate = 3;\n    plot_service_message.request.resolution_inflow_rate = 1;\n    plot_service_message.request.min_rotational_speed = min_rotational_speed;\n    plot_service_message.request.max_rotational_speed = max_rotational_speed;\n    plot_service_message.request.resolution_rotational_speed = 0.01;\n    plot_client.call(plot_service_message);\n    motor_command_publisher.reset(new realtime_tools::RealtimePublisher<std_msgs::Float64>(controller_nh, motor_command_topic, 1));\n    twist_sub = controller_nh.subscribe(twist_topic, 1, &DrivingForceController::twistCallback, this);\n    driving_force_sub = controller_nh.subscribe(driving_force_command_topic, 1, &DrivingForceController::drivingForceCallback, this);\n  }\n\n  double DrivingForceController::get_rotational_speed(double thrust,double inflow_rate)\n  {\n    double rotational_speed = 0;\n    double error = 0;\n    error = thrust-get_thrust(rotational_speed,inflow_rate);\n    while(std::fabs(error) > tolerance)\n    {\n      rotational_speed = rotational_speed+error*alpha;\n      error = thrust-get_thrust(rotational_speed,inflow_rate);\n    }\n    return rotational_speed;\n  }\n\n  void DrivingForceController::starting(const ros::Time& time)\n  {\n    twist_struct.ang_x = 0;\n    twist_struct.ang_y = 0;\n    twist_struct.ang_z = 0;\n    twist_struct.lin_x = 0;\n    twist_struct.lin_y = 0;\n    twist_struct.lin_z = 0;\n    twist.initRT(twist_struct);\n    driving_force_struct.value = 0;\n    driving_force.initRT(driving_force_struct);\n  }\n\n  void DrivingForceController::update(const ros::Time& time, const ros::Duration& period)\n  {\n    driving_force_struct = *(driving_force.readFromRT());\n    twist_struct = *(twist.readFromRT());\n    if(motor_command_publisher && motor_command_publisher->trylock())\n    {\n      double target_rotational_speed = get_rotational_speed(driving_force_struct.value,twist_struct.lin_x);\n      target_rotational_speed = boost::algorithm::clamp(target_rotational_speed,min_rotational_speed,max_rotational_speed);\n      motor_command_publisher->msg_.data = target_rotational_speed;\n      motor_command_publisher->unlockAndPublish();\n    }\n  }\n  void DrivingForceController::stopping(const ros::Time& time)\n  {\n\n  }\n}\n\nPLUGINLIB_EXPORT_CLASS(driving_force_controller::DrivingForceController, controller_interface::ControllerBase);\n", "meta": {"hexsha": "3a78afafe54441ba327d986dbe9d1bca951eb30f", "size": 6465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_ship_control/src/driving_force_controller.cpp", "max_stars_repo_name": "weilunwc/ros_ship_packages", "max_stars_repo_head_hexsha": "3abc92020cf338f1ecc1b85d216d67e7d4543fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2017-12-07T11:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:01:41.000Z", "max_issues_repo_path": "ros_ship_control/src/driving_force_controller.cpp", "max_issues_repo_name": "qycqycqyc/ros_ship_packages", "max_issues_repo_head_hexsha": "3abc92020cf338f1ecc1b85d216d67e7d4543fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-12-10T14:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T07:51:28.000Z", "max_forks_repo_path": "ros_ship_control/src/driving_force_controller.cpp", "max_forks_repo_name": "qycqycqyc/ros_ship_packages", "max_forks_repo_head_hexsha": "3abc92020cf338f1ecc1b85d216d67e7d4543fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T14:40:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:27:37.000Z", "avg_line_length": 36.7329545455, "max_line_length": 133, "alphanum_fraction": 0.7551430781, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.028436035309096674, "lm_q1q2_score": 0.014218017654548337}}
{"text": "\n//此源码被清华学神尹成大魔王专业翻译分析并修改\n//尹成QQ77025077\n//尹成微信18510341407\n//尹成所在QQ群721929980\n//尹成邮箱 yinc13@mails.tsinghua.edu.cn\n//尹成毕业于清华大学,微软区块链领域全球最有价值专家\n//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620\n//————————————————————————————————————————————————————————————————————————————————————————————————————————————————\n/*\n    此文件是Rippled的一部分：https://github.com/ripple/rippled\n    版权所有（c）2012，2013 Ripple Labs Inc.\n\n    使用、复制、修改和/或分发本软件的权限\n    特此授予免费或不收费的目的，前提是\n    版权声明和本许可声明出现在所有副本中。\n\n    本软件按“原样”提供，作者不作任何保证。\n    关于本软件，包括\n    适销性和适用性。在任何情况下，作者都不对\n    任何特殊、直接、间接或后果性损害或任何损害\n    因使用、数据或利润损失而导致的任何情况，无论是在\n    合同行为、疏忽或其他侵权行为\n    或与本软件的使用或性能有关。\n**/\n\n//==============================================================\n\n#include <ripple/app/paths/impl/Steps.h>\n#include <ripple/app/paths/Credit.h>\n#include <ripple/app/paths/NodeDirectory.h>\n#include <ripple/app/tx/impl/OfferStream.h>\n#include <ripple/basics/contract.h>\n#include <ripple/basics/Log.h>\n#include <ripple/ledger/Directory.h>\n#include <ripple/ledger/PaymentSandbox.h>\n#include <ripple/protocol/Book.h>\n#include <ripple/protocol/Feature.h>\n#include <ripple/protocol/IOUAmount.h>\n#include <ripple/protocol/Quality.h>\n#include <ripple/protocol/XRPAmount.h>\n\n#include <boost/container/flat_set.hpp>\n\n#include <numeric>\n#include <sstream>\n\nnamespace ripple {\n\ntemplate<class TIn, class TOut, class TDerived>\nclass BookStep : public StepImp<TIn, TOut, BookStep<TIn, TOut, TDerived>>\n{\nprotected:\n    uint32_t const maxOffersToConsume_;\n    Book book_;\n    AccountID strandSrc_;\n    AccountID strandDst_;\n//上一步赎回时收取过户费\n    Step const* const prevStep_ = nullptr;\n    bool const ownerPaysTransferFee_;\n//如果消费了太多的产品，请标记为不活动（干燥）\n    bool inactive_ = false;\n    beast::Journal j_;\n\n    struct Cache\n    {\n        TIn in;\n        TOut out;\n\n        Cache (TIn const& in_, TOut const& out_)\n            : in (in_), out (out_)\n        {\n        }\n    };\n\n    boost::optional<Cache> cache_;\n\n    static\n    uint32_t getMaxOffersToConsume(StrandContext const& ctx)\n    {\n        if (ctx.view.rules().enabled(fix1515))\n            return 1000;\n        return 2000;\n    }\n\npublic:\n    BookStep (StrandContext const& ctx,\n        Issue const& in,\n        Issue const& out)\n        : maxOffersToConsume_ (getMaxOffersToConsume(ctx))\n        , book_ (in, out)\n        , strandSrc_ (ctx.strandSrc)\n        , strandDst_ (ctx.strandDst)\n        , prevStep_ (ctx.prevStep)\n        , ownerPaysTransferFee_ (ctx.ownerPaysTransferFee)\n        , j_ (ctx.j)\n    {\n    }\n\n    Book const& book() const\n    {\n        return book_;\n    }\n\n    boost::optional<EitherAmount>\n    cachedIn () const override\n    {\n        if (!cache_)\n            return boost::none;\n        return EitherAmount (cache_->in);\n    }\n\n    boost::optional<EitherAmount>\n    cachedOut () const override\n    {\n        if (!cache_)\n            return boost::none;\n        return EitherAmount (cache_->out);\n    }\n\n    bool\n    redeems (ReadView const& sb, bool fwd) const override\n    {\n        return !ownerPaysTransferFee_;\n    }\n\n    boost::optional<Book>\n    bookStepBook () const override\n    {\n        return book_;\n    }\n\n    boost::optional<Quality>\n    qualityUpperBound(ReadView const& v, bool& redeems) const override;\n\n    std::pair<TIn, TOut>\n    revImp (\n        PaymentSandbox& sb,\n        ApplyView& afView,\n        boost::container::flat_set<uint256>& ofrsToRm,\n        TOut const& out);\n\n    std::pair<TIn, TOut>\n    fwdImp (\n        PaymentSandbox& sb,\n        ApplyView& afView,\n        boost::container::flat_set<uint256>& ofrsToRm,\n        TIn const& in);\n\n    std::pair<bool, EitherAmount>\n    validFwd (\n        PaymentSandbox& sb,\n        ApplyView& afView,\n        EitherAmount const& in) override;\n\n//检查冻结约束是否有错误。\n    TER check(StrandContext const& ctx) const;\n\n    bool inactive() const override {\n        return inactive_;\n    }\n\nprotected:\n    std::string logStringImpl (char const* name) const\n    {\n        std::ostringstream ostr;\n        ostr <<\n            name << \": \" <<\n            \"\\ninIss: \" << book_.in.account <<\n            \"\\noutIss: \" << book_.out.account <<\n            \"\\ninCur: \" << book_.in.currency <<\n            \"\\noutCur: \" << book_.out.currency;\n        return ostr.str ();\n    }\n\nprivate:\n    friend bool operator==(BookStep const& lhs, BookStep const& rhs)\n    {\n        return lhs.book_ == rhs.book_;\n    }\n\n    friend bool operator!=(BookStep const& lhs, BookStep const& rhs)\n    {\n        return ! (lhs == rhs);\n    }\n\n    bool equal (Step const& rhs) const override;\n\n//在一本书中以最佳的质量反复阅读这些产品。\n//未提供资金的报价和不好的报价被跳过（并被退回）。\n//回电是通过提供SLE来调用的，接受方付费，接受方付费。\n//如果回调返回false，则不再处理任何报价。\n//返回未提供资金和坏报价以及消耗的报价数量。\n    template <class Callback>\n    std::pair<boost::container::flat_set<uint256>, std::uint32_t>\n    forEachOffer (\n        PaymentSandbox& sb,\n        ApplyView& afView,\n        bool prevStepRedeems,\n        Callback& callback) const;\n\n    void consumeOffer (PaymentSandbox& sb,\n        TOffer<TIn, TOut>& offer,\n        TAmounts<TIn, TOut> const& ofrAmt,\n        TAmounts<TIn, TOut> const& stepAmt,\n        TOut const& ownerGives) const;\n};\n\n//————————————————————————————————————————————————————————————————————————————————————————————————————————————————\n\n//在两种不同的情况下，流动用于转移资金：\n//付款，以及\n//o提供交叉路口。\n//在这两种情况下，处理资金的规则几乎是，但不是\n//完全一样。\n\n//付款bookstep模板类（不提供交叉）。\ntemplate<class TIn, class TOut>\nclass BookPaymentStep\n    : public BookStep<TIn, TOut, BookPaymentStep<TIn, TOut>>\n{\npublic:\n    explicit BookPaymentStep() = default;\n\n    using BookStep<TIn, TOut, BookPaymentStep<TIn, TOut>>::BookStep;\n    using BookStep<TIn, TOut, BookPaymentStep<TIn, TOut>>::qualityUpperBound;\n\n//不要限制付款的自交叉质量。\n    bool limitSelfCrossQuality (AccountID const&, AccountID const&,\n        TOffer<TIn, TOut> const& offer, boost::optional<Quality>&,\n        FlowOfferStream<TIn, TOut>&, bool) const\n    {\n        return false;\n    }\n\n//付款可以查看任何质量的报价。\n    bool checkQualityThreshold(TOffer<TIn, TOut> const& offer) const\n    {\n        return true;\n    }\n\n//因为RinRate的付款总是和Trin一样的。\n    std::uint32_t getOfrInRate (\n        Step const*, TOffer<TIn, TOut> const&, std::uint32_t trIn) const\n    {\n        return trIn;\n    }\n\n//因为Routrate的付款总是和Trout一样的。\n    std::uint32_t getOfrOutRate (Step const*, TOffer<TIn, TOut> const&,\n        AccountID const&, std::uint32_t trOut) const\n    {\n        return trOut;\n    }\n\n    Quality\n    qualityUpperBound(ReadView const& v,\n        Quality const& ofrQ,\n        bool prevStepRedeems) const\n    {\n//向发盘人收费，而不是向发盘人收费\n//即使所有者与发行人相同，也要收取费用。\n//（旧代码不收费）\n//计算到接受者的金额和收取的金额\n//发盘人\n        auto rate = [&](AccountID const& id) {\n            if (isXRP(id) || id == this->strandDst_)\n                return parityRate;\n            return transferRate(v, id);\n        };\n\n        auto const trIn =\n            prevStepRedeems ? rate(this->book_.in.account) : parityRate;\n//始终收取转让费，即使所有人是发行人\n        auto const trOut =\n            this->ownerPaysTransferFee_\n            ? rate(this->book_.out.account)\n            : parityRate;\n\n        Quality const q1{getRate(STAmount(trOut.value), STAmount(trIn.value))};\n        return composed_quality(q1, ofrQ);\n    }\n\n    std::string logString () const override\n    {\n        return this->logStringImpl (\"BookPaymentStep\");\n    }\n};\n\n//提供交叉bookstep模板类（不是付款）。\ntemplate<class TIn, class TOut>\nclass BookOfferCrossingStep\n    : public BookStep<TIn, TOut, BookOfferCrossingStep<TIn, TOut>>\n{\n    using BookStep<TIn, TOut, BookOfferCrossingStep<TIn, TOut>>::qualityUpperBound;\nprivate:\n//如果可选参数传递给构造函数，则引发的helper函数\n//一个也没有。\n    static Quality getQuality (boost::optional<Quality> const& limitQuality)\n    {\n//如果质量不好，那真是一个编程错误。\n        assert (limitQuality);\n        if (!limitQuality)\n            Throw<FlowException> (tefINTERNAL, \"Offer requires quality.\");\n        return *limitQuality;\n    }\n\npublic:\n    BookOfferCrossingStep (\n        StrandContext const& ctx, Issue const& in, Issue const& out)\n    : BookStep<TIn, TOut, BookOfferCrossingStep<TIn, TOut>> (ctx, in, out)\n    , defaultPath_ (ctx.isDefaultPath)\n    , qualityThreshold_ (getQuality (ctx.limitQuality))\n    {\n    }\n\n    bool limitSelfCrossQuality (AccountID const& strandSrc,\n        AccountID const& strandDst, TOffer<TIn, TOut> const& offer,\n        boost::optional<Quality>& ofrQ, FlowOfferStream<TIn, TOut>& offers,\n        bool const offerAttempted) const\n    {\n//这个方法支持一些正确但有点令人吃惊的方法\n//报价交叉行为。情景：\n//\n//o Alice已经创建了一个或多个报价。\n//o Alice创建了另一个可以直接交叉（而不是\n//由她以前创建的一个或多个报价自动完成。\n//\n//交叉报价有什么作用？\n//\n//o报价交叉口可以继续进行，交叉报价离开。\n//一个减价（部分交叉）或零报价\n//（精确交叉）在分类帐中。我们不这样做。而且，真的，\n//报价创建者可能不想让我们这么做。\n//\n//o我们可以跳过书中的自我介绍，只需交叉\n//不是我们自己的报价。这很有道理，\n//但我们不这么做。部分理由是我们只能\n//操作订单的顶部。我们不能留下报价\n//在后面——它会坐在顶端，阻止其他人进入。\n//提供。\n//\n//o我们可以从\n//预订并继续报价交叉。我们就是这么做的。\n//\n//为了支持这个场景，提供交叉有一个特殊的规则。如果：\n//A.我们提供使用默认路径的交叉（无自动桥接），以及\n//B.报盘的质量至少和我们的质量一样好，而且\n//C.那我们就要越过自己的报价了。\n//d.从分类帐中删除旧报价。\n        if (defaultPath_ && offer.quality() >= qualityThreshold_ &&\n            strandSrc == offer.owner() && strandDst == offer.owner())\n        {\n//即使没有交叉，也要取消此报价。\n            offers.permRmOffer (offer.key());\n\n//如果还没有尝试过提供服务，那么可以转到\n//不同的品质。\n            if (!offerAttempted)\n                ofrQ = boost::none;\n\n//返回true，以便删除当前报价。\n            return true;\n        }\n        return false;\n    }\n\n//offer crossing可以用\n//质量阈值。\n    bool checkQualityThreshold(TOffer<TIn, TOut> const& offer) const\n    {\n        return !defaultPath_ || offer.quality() >= qualityThreshold_;\n    }\n\n//如果艾丽丝付钱给艾丽丝，交叉报价不付过户费。\n//定期（非报价交叉）付款不适用此规则。\n    std::uint32_t getOfrInRate (Step const* prevStep,\n        TOffer<TIn, TOut> const& offer, std::uint32_t trIn) const\n    {\n        auto const srcAcct = prevStep ?\n            prevStep->directStepSrcAcct() :\n            boost::none;\n\nreturn                                        //如果报价交叉\nsrcAcct &&                                //上一步是直接的（&&P）\noffer.owner() == *srcAcct                 //&&SRC是报价所有者\n? QUALITY_ONE : trIn;                     //那么比率=质量\n    }\n\n//请参见GetOfrinRate（）上的注释。\n    std::uint32_t getOfrOutRate (\n        Step const* prevStep, TOffer<TIn, TOut> const& offer,\n        AccountID const& strandDst, std::uint32_t trOut) const\n    {\nreturn                                        //如果报价交叉\nprevStep && prevStep->bookStepBook() &&   //上一步是bookstep（&&P）\noffer.owner() == strandDst                //&&dest是报价所有者\n? QUALITY_ONE : trOut;                    //那么比率=质量\n    }\n\n    Quality\n    qualityUpperBound(ReadView const& v,\n        Quality const& ofrQ,\n        bool prevStepRedeems) const\n    {\n//优惠X-ing不收取转让费，当优惠的所有者\n//与链DST相同。“质量上界”很重要\n//是质量的上界（用于忽略股）\n//其质量不能达到最低阈值）。计算时\n//质量假设不收取费用，否则估计将不再\n//做一个上界。\n        return ofrQ;\n    }\n\n    std::string logString () const override\n    {\n        return this->logStringImpl (\"BookOfferCrossingStep\");\n    }\n\nprivate:\n    bool const defaultPath_;\n    Quality const qualityThreshold_;\n};\n\n//————————————————————————————————————————————————————————————————————————————————————————————————————————————————\n\ntemplate <class TIn, class TOut, class TDerived>\nbool BookStep<TIn, TOut, TDerived>::equal (Step const& rhs) const\n{\n    if (auto bs = dynamic_cast<BookStep<TIn, TOut, TDerived> const*>(&rhs))\n        return book_ == bs->book_;\n    return false;\n}\n\ntemplate <class TIn, class TOut, class TDerived>\nboost::optional<Quality>\nBookStep<TIn, TOut, TDerived>::qualityUpperBound(\n    ReadView const& v, bool& redeems) const\n{\n    auto const prevStepRedeems = redeems;\n    redeems = this->redeems(v, true);\n\n//如果目录从不为空，则可以简化（并加快速度）。\n    Sandbox sb(&v, tapNONE);\n    BookTip bt(sb, book_);\n    if (!bt.step(j_))\n        return boost::none;\n\n    return static_cast<TDerived const*>(this)->qualityUpperBound(\n        v, bt.quality(), prevStepRedeems);\n}\n\n//根据给定的输入限制调整报价金额和步进金额\ntemplate <class TIn, class TOut>\nstatic\nvoid limitStepIn (Quality const& ofrQ,\n    TAmounts<TIn, TOut>& ofrAmt,\n    TAmounts<TIn, TOut>& stpAmt,\n    TOut& ownerGives,\n    std::uint32_t transferRateIn,\n    std::uint32_t transferRateOut,\n    TIn const& limit)\n{\n    if (limit < stpAmt.in)\n    {\n        stpAmt.in = limit;\n        auto const inLmt = mulRatio (\n            /*amt.in，quality_one，transferratein，/*roundup*/false）；\n        oframt=ofrq.ceil_in（oframt，inlmt）；\n        stpamt.out=oframt.out；\n        所有者给出=多重比率（\n            oframt.out、transferrateout、quality_one、/*roundu*/ false);\n\n    }\n}\n\n//根据给定的输出限制调整报价金额和步进金额\ntemplate <class TIn, class TOut>\nstatic\nvoid limitStepOut (Quality const& ofrQ,\n    TAmounts<TIn, TOut>& ofrAmt,\n    TAmounts<TIn, TOut>& stpAmt,\n    TOut& ownerGives,\n    std::uint32_t transferRateIn,\n    std::uint32_t transferRateOut,\n    TOut const& limit)\n{\n    if (limit < stpAmt.out)\n    {\n        stpAmt.out = limit;\n        ownerGives = mulRatio (\n            /*amt.out、transferrateout、quality_one、/*roundup*/false）；\n        oframt=ofrq.ceil-out（oframt，stpamt.out）；\n        stpamt.in=多比率（\n            oframt.in，transferratein，quality_one，/*roundu*/ true);\n\n    }\n}\n\ntemplate <class TIn, class TOut, class TDerived>\ntemplate <class Callback>\nstd::pair<boost::container::flat_set<uint256>, std::uint32_t>\nBookStep<TIn, TOut, TDerived>::forEachOffer (\n    PaymentSandbox& sb,\n    ApplyView& afView,\n    bool prevStepRedeems,\n    Callback& callback) const\n{\n//向发盘人收费，而不是向发盘人收费\n//即使所有者与发行人相同，也要收取费用。\n//（旧代码不收费）\n//计算给接受者的金额和报价所有者收取的金额\n    auto rate = [this, &sb](AccountID const& id)->std::uint32_t\n    {\n        if (isXRP (id) || id == this->strandDst_)\n            return QUALITY_ONE;\n        return transferRate (sb, id).value;\n    };\n\n    std::uint32_t const trIn = prevStepRedeems\n        ? rate (book_.in.account)\n        : QUALITY_ONE;\n//始终收取转让费，即使所有人是发行人\n    std::uint32_t const trOut = ownerPaysTransferFee_\n        ? rate (book_.out.account)\n        : QUALITY_ONE;\n\n    typename FlowOfferStream<TIn, TOut>::StepCounter\n        counter (maxOffersToConsume_, j_);\n\n    FlowOfferStream<TIn, TOut> offers (\n        sb, afView, book_, sb.parentCloseTime (), counter, j_);\n\n    bool const flowCross = afView.rules().enabled(featureFlowCross);\n    bool offerAttempted = false;\n    boost::optional<Quality> ofrQ;\n    while (offers.step ())\n    {\n        auto& offer = offers.tip ();\n\n//请注意，offer.quality（）返回（非可选）质量。所以\n//OFRQ在循环的这个点以下使用总是安全的。\n        if (!ofrQ)\n            ofrQ = offer.quality ();\n        else if (*ofrQ != offer.quality ())\n            break;\n\n        if (static_cast<TDerived const*>(this)->limitSelfCrossQuality (\n            strandSrc_, strandDst_, offer, ofrQ, offers, offerAttempted))\n                continue;\n\n//确保要约所有人有权拥有发行人的借据。\n//帐户可以始终拥有XRP或其自己的IOU。\n        if (flowCross &&\n            (!isXRP (offer.issueIn().currency)) &&\n            (offer.owner() != offer.issueIn().account))\n        {\n            auto const& issuerID = offer.issueIn().account;\n            auto const issuer = afView.read (keylet::account (issuerID));\n            if (issuer && ((*issuer)[sfFlags] & lsfRequireAuth))\n            {\n//颁发者需要授权。看看报价人是否有。\n                auto const& ownerID = offer.owner();\n                auto const authFlag =\n                    issuerID > ownerID ? lsfHighAuth : lsfLowAuth;\n\n                auto const line = afView.read (keylet::line (\n                    ownerID, issuerID, offer.issueIn().currency));\n\n                if (!line || (((*line)[sfFlags] & authFlag) == 0))\n                {\n//要约所有人未被授权持有发行人的IOU。\n//即使没有交叉，也要取消此报价。\n                    offers.permRmOffer (offer.key());\n                    if (!offerAttempted)\n//只有在以前没有尝试过的情况下才能更改质量。\n                        ofrQ = boost::none;\n//此继续操作将导致offers.step（）删除该offere。\n                    continue;\n                }\n            }\n        }\n\n        if (! static_cast<TDerived const*>(this)->checkQualityThreshold(offer))\n            break;\n\n        auto const ofrInRate =\n            static_cast<TDerived const*>(this)->getOfrInRate (\n                prevStep_, offer, trIn);\n\n        auto const ofrOutRate =\n            static_cast<TDerived const*>(this)->getOfrOutRate (\n                prevStep_, offer, strandDst_, trOut);\n\n        auto ofrAmt = offer.amount ();\n        auto stpAmt = make_Amounts (\n            /*比率（oframt.in，ofrinrate，quality_one，/*roundup*/true）\n            OfRAMT；out；\n\n        //业主支付过户费。\n        自动所有者给出=\n            多重比率（OFRAmt.out，OFROUTRATE，Quality_One，/*Roundu*/ false);\n\n\n        auto const funds =\n            (offer.owner () == offer.issueOut ().account)\n? ownerGives //要约所有人是发行人；他们有无限的资金\n            : offers.ownerFunds ();\n\n        if (funds < ownerGives)\n        {\n//我们已经知道了offer.owner（）！=offer.issueout（）。帐户\n            ownerGives = funds;\n            stpAmt.out = mulRatio (\n                /*Ergives，Quality_One，Ofroutrate，/*Roundup*/false）；\n            oframt=ofrq->ceil_out（oframt，stpamt.out）；\n            stpamt.in=多比率（\n                Oframt.in，Ofrinrate，Quality_One，/*圆形*/ true);\n\n        }\n\n        offerAttempted = true;\n        if (!callback (\n            offer, ofrAmt, stpAmt, ownerGives, ofrInRate, ofrOutRate))\n            break;\n    }\n\n    return {offers.permToRemove (), counter.count()};\n}\n\ntemplate <class TIn, class TOut, class TDerived>\nvoid BookStep<TIn, TOut, TDerived>::consumeOffer (\n    PaymentSandbox& sb,\n    TOffer<TIn, TOut>& offer,\n    TAmounts<TIn, TOut> const& ofrAmt,\n    TAmounts<TIn, TOut> const& stepAmt,\n    TOut const& ownerGives) const\n{\n//报价的所有者得到了Oframt。oframt和stepamt的区别\n//是转到book\\in.帐户的转账费\n    {\n        auto const dr = accountSend (sb, book_.in.account, offer.owner (),\n            toSTAmount (ofrAmt.in, book_.in), j_);\n        if (dr != tesSUCCESS)\n            Throw<FlowException> (dr);\n    }\n\n//要约所有人支付“所有者赠予”。所有者与\n//stepamt是一笔转到book_uuu.out.account的转账费用。\n    {\n        auto const cr = accountSend (sb, offer.owner (), book_.out.account,\n            toSTAmount (ownerGives, book_.out), j_);\n        if (cr != tesSUCCESS)\n            Throw<FlowException> (cr);\n    }\n\n    offer.consume (sb, ofrAmt);\n}\n\ntemplate<class TCollection>\nstatic\nauto sum (TCollection const& col)\n{\n    using TResult = std::decay_t<decltype (*col.begin ())>;\n    if (col.empty ())\n        return TResult{beast::zero};\n    return std::accumulate (col.begin () + 1, col.end (), *col.begin ());\n};\n\ntemplate<class TIn, class TOut, class TDerived>\nstd::pair<TIn, TOut>\nBookStep<TIn, TOut, TDerived>::revImp (\n    PaymentSandbox& sb,\n    ApplyView& afView,\n    boost::container::flat_set<uint256>& ofrsToRm,\n    TOut const& out)\n{\n    cache_.reset ();\n\n    TAmounts<TIn, TOut> result (beast::zero, beast::zero);\n\n    auto remainingOut = out;\n\n    boost::container::flat_multiset<TIn> savedIns;\n    savedIns.reserve(64);\n    boost::container::flat_multiset<TOut> savedOuts;\n    savedOuts.reserve(64);\n\n    /*联邦金额将由业主资金调整（可能与报价不同）\n      金额-tho始终<=）\n      返回“真”继续接收报价，返回“假”停止接收报价。\n    **/\n\n    auto eachOffer =\n        [&](TOffer<TIn, TOut>& offer,\n            TAmounts<TIn, TOut> const& ofrAmt,\n            TAmounts<TIn, TOut> const& stpAmt,\n            TOut const& ownerGives,\n            std::uint32_t transferRateIn,\n            std::uint32_t transferRateOut) mutable -> bool\n    {\n        if (remainingOut <= beast::zero)\n            return false;\n\n        if (stpAmt.out <= remainingOut)\n        {\n            savedIns.insert(stpAmt.in);\n            savedOuts.insert(stpAmt.out);\n            result = TAmounts<TIn, TOut>(sum (savedIns), sum(savedOuts));\n            remainingOut = out - result.out;\n            this->consumeOffer (sb, offer, ofrAmt, stpAmt, ownerGives);\n//即使付款满意，也要退回真实的信用证。\n//我们需要接受这个提议\n            return true;\n        }\n        else\n        {\n            auto ofrAdjAmt = ofrAmt;\n            auto stpAdjAmt = stpAmt;\n            auto ownerGivesAdj = ownerGives;\n            limitStepOut (offer.quality (), ofrAdjAmt, stpAdjAmt, ownerGivesAdj,\n                transferRateIn, transferRateOut, remainingOut);\n            remainingOut = beast::zero;\n            savedIns.insert (stpAdjAmt.in);\n            savedOuts.insert (remainingOut);\n            result.in = sum(savedIns);\n            result.out = out;\n            this->consumeOffer (sb, offer, ofrAdjAmt, stpAdjAmt, ownerGivesAdj);\n\n//如果两个借据金额的尾数相差不到十，那么\n//减去它们会得到零的结果。这可能导致支票\n//（stpamt.out>remainingout）错误地认为报价将得到资助\n//减去Remainingin后。\n            if (fix1298(sb.parentCloseTime()))\n                return offer.fully_consumed();\n            else\n                return false;\n        }\n    };\n\n    {\n        auto const prevStepRedeems = prevStep_ && prevStep_->redeems (sb, false);\n        auto const r = forEachOffer (sb, afView, prevStepRedeems, eachOffer);\n        boost::container::flat_set<uint256> toRm = std::move(std::get<0>(r));\n        std::uint32_t const offersConsumed = std::get<1>(r);\n        ofrsToRm.insert (boost::container::ordered_unique_range_t{},\n            toRm.begin (), toRm.end ());\n\n        if (offersConsumed >= maxOffersToConsume_)\n        {\n//迭代太多，将此链标记为非活动\n            if (!afView.rules().enabled(fix1515))\n            {\n//不要使用流动性\n                cache_.emplace(beast::zero, beast::zero);\n                return {beast::zero, beast::zero};\n            }\n\n//使用流动性，但使用它将链标记为不活动，因此\n//它不用了\n            inactive_ = true;\n        }\n    }\n\n    switch(remainingOut.signum())\n    {\n        case -1:\n        {\n//出了大问题\n            JLOG (j_.error ())\n                << \"BookStep remainingOut < 0 \" << to_string (remainingOut);\n            assert (0);\n            cache_.emplace (beast::zero, beast::zero);\n            return {beast::zero, beast::zero};\n        }\n        case 0:\n        {\n//由于标准化，remainingout可以为零\n//result.out==输出。force result.out==在这种情况下为out\n            result.out = out;\n        }\n    }\n\n    cache_.emplace (result.in, result.out);\n    return {result.in, result.out};\n}\n\ntemplate<class TIn, class TOut, class TDerived>\nstd::pair<TIn, TOut>\nBookStep<TIn, TOut, TDerived>::fwdImp (\n    PaymentSandbox& sb,\n    ApplyView& afView,\n    boost::container::flat_set<uint256>& ofrsToRm,\n    TIn const& in)\n{\n    assert(cache_);\n\n    TAmounts<TIn, TOut> result (beast::zero, beast::zero);\n\n    auto remainingIn = in;\n\n    boost::container::flat_multiset<TIn> savedIns;\n    savedIns.reserve(64);\n    boost::container::flat_multiset<TOut> savedOuts;\n    savedOuts.reserve(64);\n\n//联邦金额将由业主资金调整（可能与报价不同）\n//金额-tho始终<=）\n    auto eachOffer =\n        [&](TOffer<TIn, TOut>& offer,\n            TAmounts<TIn, TOut> const& ofrAmt,\n            TAmounts<TIn, TOut> const& stpAmt,\n            TOut const& ownerGives,\n            std::uint32_t transferRateIn,\n            std::uint32_t transferRateOut) mutable -> bool\n    {\n        assert(cache_);\n\n        if (remainingIn <= beast::zero)\n            return false;\n\n        bool processMore = true;\n        auto ofrAdjAmt = ofrAmt;\n        auto stpAdjAmt = stpAmt;\n        auto ownerGivesAdj = ownerGives;\n\n        typename boost::container::flat_multiset<TOut>::const_iterator lastOut;\n        if (stpAmt.in <= remainingIn)\n        {\n            savedIns.insert(stpAmt.in);\n            lastOut = savedOuts.insert(stpAmt.out);\n            result = TAmounts<TIn, TOut>(sum (savedIns), sum(savedOuts));\n//即使stepamt.in==remainingin，也要接受报价\n            processMore = true;\n        }\n        else\n        {\n            limitStepIn (offer.quality (), ofrAdjAmt, stpAdjAmt, ownerGivesAdj,\n                transferRateIn, transferRateOut, remainingIn);\n            savedIns.insert (remainingIn);\n            lastOut = savedOuts.insert (stpAdjAmt.out);\n            result.out = sum (savedOuts);\n            result.in = in;\n\n            processMore = false;\n        }\n\n        if (result.out > cache_->out && result.in <= cache_->in)\n        {\n//这一步在向前通过时产生的输出比\n//使用相同的输入（或更少）时反向通过。如果我们\n//计算生成缓存输出所需的输入\n//（在反向步骤中产生）且输入等于\n//在前进步骤中消耗的输入，然后消耗\n//向前步骤中提供的输入并生成输出\n//从反向步骤请求。\n            auto const lastOutAmt = *lastOut;\n            savedOuts.erase(lastOut);\n            auto const remainingOut = cache_->out - sum (savedOuts);\n            auto ofrAdjAmtRev = ofrAmt;\n            auto stpAdjAmtRev = stpAmt;\n            auto ownerGivesAdjRev = ownerGives;\n            limitStepOut (offer.quality (), ofrAdjAmtRev, stpAdjAmtRev,\n                ownerGivesAdjRev, transferRateIn, transferRateOut,\n                remainingOut);\n\n            if (stpAdjAmtRev.in == remainingIn)\n            {\n                result.in = in;\n                result.out = cache_->out;\n\n                savedIns.clear();\n                savedIns.insert(result.in);\n                savedOuts.clear();\n                savedOuts.insert(result.out);\n\n                ofrAdjAmt = ofrAdjAmtRev;\n                stpAdjAmt.in = remainingIn;\n                stpAdjAmt.out = remainingOut;\n                ownerGivesAdj = ownerGivesAdjRev;\n            }\n            else\n            {\n//这很可能是个问题，会被抓住的\n//以后再检查\n                savedOuts.insert (lastOutAmt);\n            }\n        }\n\n        remainingIn = in - result.in;\n        this->consumeOffer (sb, offer, ofrAdjAmt, stpAdjAmt, ownerGivesAdj);\n\n//如果两个借据金额的尾数相差不到十，那么\n//减去它们会得到零的结果。这可能导致支票\n//（stpamt.in>remainingin）错误地认为报价将得到资助\n//减去Remainingin后。\n        if (fix1298(sb.parentCloseTime()))\n            processMore = processMore || offer.fully_consumed();\n\n        return processMore;\n    };\n\n    {\n        auto const prevStepRedeems = prevStep_ && prevStep_->redeems (sb, true);\n        auto const r = forEachOffer (sb, afView, prevStepRedeems, eachOffer);\n        boost::container::flat_set<uint256> toRm = std::move(std::get<0>(r));\n        std::uint32_t const offersConsumed = std::get<1>(r);\n        ofrsToRm.insert (boost::container::ordered_unique_range_t{},\n            toRm.begin (), toRm.end ());\n\n        if (offersConsumed >= maxOffersToConsume_)\n        {\n//迭代次数太多，将此股标记为不活动（干）\n            if (!afView.rules().enabled(fix1515))\n            {\n//不要使用流动性\n                cache_.emplace(beast::zero, beast::zero);\n                return {beast::zero, beast::zero};\n            }\n\n//使用流动性，但使用它将链标记为不活动，因此\n//它不用了\n            inactive_ = true;\n        }\n    }\n\n    switch(remainingIn.signum())\n    {\n        case -1:\n        {\n//出了大问题\n            JLOG (j_.error ())\n                << \"BookStep remainingIn < 0 \" << to_string (remainingIn);\n            assert (0);\n            cache_.emplace (beast::zero, beast::zero);\n            return {beast::zero, beast::zero};\n        }\n        case 0:\n        {\n//由于标准化，remainingin可以为零\n//result.in==英寸。对于这种情况，force result.in==in\n            result.in = in;\n        }\n    }\n\n    cache_.emplace (result.in, result.out);\n    return {result.in, result.out};\n}\n\ntemplate<class TIn, class TOut, class TDerived>\nstd::pair<bool, EitherAmount>\nBookStep<TIn, TOut, TDerived>::validFwd (\n    PaymentSandbox& sb,\n    ApplyView& afView,\n    EitherAmount const& in)\n{\n    if (!cache_)\n    {\n        JLOG (j_.trace()) << \"Expected valid cache in validFwd\";\n        return {false, EitherAmount (TOut (beast::zero))};\n    }\n\n    auto const savCache = *cache_;\n\n    try\n    {\n        boost::container::flat_set<uint256> dummy;\nfwdImp (sb, afView, dummy, get<TIn> (in));  //更改缓存\n    }\n    catch (FlowException const&)\n    {\n        return {false, EitherAmount (TOut (beast::zero))};\n    }\n\n    if (!(checkNear (savCache.in, cache_->in) &&\n            checkNear (savCache.out, cache_->out)))\n    {\n        JLOG (j_.error()) <<\n            \"Strand re-execute check failed.\" <<\n            \" ExpectedIn: \" << to_string (savCache.in) <<\n            \" CachedIn: \" << to_string (cache_->in) <<\n            \" ExpectedOut: \" << to_string (savCache.out) <<\n            \" CachedOut: \" << to_string (cache_->out);\n        return {false, EitherAmount (cache_->out)};\n    }\n    return {true, EitherAmount (cache_->out)};\n}\n\ntemplate<class TIn, class TOut, class TDerived>\nTER\nBookStep<TIn, TOut, TDerived>::check(StrandContext const& ctx) const\n{\n    if (book_.in == book_.out)\n    {\n        JLOG (j_.debug()) << \"BookStep: Book with same in and out issuer \" << *this;\n        return temBAD_PATH;\n    }\n    if (!isConsistent (book_.in) || !isConsistent (book_.out))\n    {\n        JLOG (j_.debug()) << \"Book: currency is inconsistent with issuer.\" << *this;\n        return temBAD_PATH;\n    }\n\n//不允许两本书输出同一期。这可能导致\n//一步到位，另一步到位。\n    if (!ctx.seenBookOuts.insert (book_.out).second ||\n        ctx.seenDirectIssues[0].count (book_.out))\n    {\n        JLOG (j_.debug()) << \"BookStep: loop detected: \" << *this;\n        return temBAD_PATH_LOOP;\n    }\n\n    if (ctx.view.rules().enabled(fix1373) &&\n        ctx.seenDirectIssues[1].count(book_.out))\n    {\n        JLOG(j_.debug()) << \"BookStep: loop detected: \" << *this;\n        return temBAD_PATH_LOOP;\n    }\n\n    if (fix1443(ctx.view.info().parentCloseTime))\n    {\n        if (ctx.prevStep)\n        {\n            if (auto const prev = ctx.prevStep->directStepSrcAcct())\n            {\n                auto const& view = ctx.view;\n                auto const& cur = book_.in.account;\n\n                auto sle =\n                    view.read(keylet::line(*prev, cur, book_.in.currency));\n                if (!sle)\n                    return terNO_LINE;\n                if ((*sle)[sfFlags] &\n                    ((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple))\n                    return terNO_RIPPLE;\n            }\n        }\n    }\n\n    return tesSUCCESS;\n}\n\n//————————————————————————————————————————————————————————————————————————————————————————————————————————————————\n\nnamespace test\n{\n//测试所需\n\ntemplate <class TIn, class TOut, class TDerived>\nstatic\nbool equalHelper (Step const& step, ripple::Book const& book)\n{\n    if (auto bs = dynamic_cast<BookStep<TIn, TOut, TDerived> const*> (&step))\n        return book == bs->book ();\n    return false;\n}\n\nbool bookStepEqual (Step const& step, ripple::Book const& book)\n{\n    bool const inXRP = isXRP (book.in.currency);\n    bool const outXRP = isXRP (book.out.currency);\n    if (inXRP && outXRP)\n        return equalHelper<XRPAmount, XRPAmount,\n            BookPaymentStep<XRPAmount, XRPAmount>> (step, book);\n    if (inXRP && !outXRP)\n        return equalHelper<XRPAmount, IOUAmount,\n            BookPaymentStep<XRPAmount, IOUAmount>> (step, book);\n    if (!inXRP && outXRP)\n        return equalHelper<IOUAmount, XRPAmount,\n            BookPaymentStep<IOUAmount, XRPAmount>> (step, book);\n    if (!inXRP && !outXRP)\n        return equalHelper<IOUAmount, IOUAmount,\n            BookPaymentStep<IOUAmount, IOUAmount>> (step, book);\n    return false;\n}\n}\n\n//————————————————————————————————————————————————————————————————————————————————————————————————————————————————\n\ntemplate <class TIn, class TOut>\nstatic\nstd::pair<TER, std::unique_ptr<Step>>\nmake_BookStepHelper (\n    StrandContext const& ctx,\n    Issue const& in,\n    Issue const& out)\n{\n    TER ter = tefINTERNAL;\n    std::unique_ptr<Step> r;\n    if (ctx.offerCrossing)\n    {\n        auto offerCrossingStep =\n            std::make_unique<BookOfferCrossingStep<TIn, TOut>> (ctx, in, out);\n        ter = offerCrossingStep->check (ctx);\n        r = std::move (offerCrossingStep);\n    }\nelse //付款\n    {\n        auto paymentStep =\n            std::make_unique<BookPaymentStep<TIn, TOut>> (ctx, in, out);\n        ter = paymentStep->check (ctx);\n        r = std::move (paymentStep);\n    }\n    if (ter != tesSUCCESS)\n        return {ter, nullptr};\n\n    return {tesSUCCESS, std::move(r)};\n}\n\nstd::pair<TER, std::unique_ptr<Step>>\nmake_BookStepII (\n    StrandContext const& ctx,\n    Issue const& in,\n    Issue const& out)\n{\n    return make_BookStepHelper<IOUAmount, IOUAmount> (ctx, in, out);\n}\n\nstd::pair<TER, std::unique_ptr<Step>>\nmake_BookStepIX (\n    StrandContext const& ctx,\n    Issue const& in)\n{\n    return make_BookStepHelper<IOUAmount, XRPAmount> (ctx, in, xrpIssue());\n}\n\nstd::pair<TER, std::unique_ptr<Step>>\nmake_BookStepXI (\n    StrandContext const& ctx,\n    Issue const& out)\n{\n    return make_BookStepHelper<XRPAmount, IOUAmount> (ctx, xrpIssue(), out);\n}\n\n} //涟漪\n", "meta": {"hexsha": "b4eba02396cb990438671355a10672538158f115", "size": 31600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ripple/app/paths/impl/BookStep.cpp", "max_stars_repo_name": "yinchengtsinghua/RippleCPPChinese", "max_stars_repo_head_hexsha": "a32a38a374547bdc5eb0fddcd657f45048aaad6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:36:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T07:10:39.000Z", "max_issues_repo_path": "src/ripple/app/paths/impl/BookStep.cpp", "max_issues_repo_name": "yinchengtsinghua/RippleCPPChinese", "max_issues_repo_head_hexsha": "a32a38a374547bdc5eb0fddcd657f45048aaad6a", "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/ripple/app/paths/impl/BookStep.cpp", "max_forks_repo_name": "yinchengtsinghua/RippleCPPChinese", "max_forks_repo_head_hexsha": "a32a38a374547bdc5eb0fddcd657f45048aaad6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-14T07:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T07:25:01.000Z", "avg_line_length": 27.8169014085, "max_line_length": 114, "alphanum_fraction": 0.5886075949, "num_tokens": 10084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.03622005417441523, "lm_q1q2_score": 0.014210461243271012}}
{"text": "\r\n// (C) Copyright Tobias Schwinger\r\n//\r\n// Use modification and distribution are subject to the boost Software License,\r\n// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt).\r\n\r\n//------------------------------------------------------------------------------\r\n//\r\n// This example implements a utility to accept a type expression, that may\r\n// contain commas to a macro.\r\n//\r\n// \r\n// Detailed description\r\n// ====================\r\n//\r\n// Accepting a type as macro argument can cause problems if the type expression\r\n// contains commas:\r\n//\r\n//    #define MY_MACRO(a_type)\r\n//    ...\r\n//    MY_MACRO(std::map<int,int>)  // ERROR (wrong number of macro arguments)\r\n//\r\n// This problem can be solved by pasing using a parenthesized type\r\n//\r\n//    MY_MACRO((std::map<int,int>) // OK\r\n//\r\n// but then there is no way to remove the parentheses in the macro argument\r\n// with the preprocessor.\r\n// We can, however, form a pointer to a function with a single argument (the\r\n// parentheses become part of the type) and extract the argument with template\r\n// metaprogramming:\r\n//\r\n//   // Inside the macro definition\r\n//\r\n//   typename mpl::front< parameter_types<void(*)a_type> >::type \r\n//\r\n// This code snippet does not read too expressive so we use another macro\r\n// to encapsulate the solution:\r\n//\r\n//   // Inside the macro definition\r\n//\r\n//   BOOST_EXAMPLE_MACRO_TYPE_ARGUMENT(a_type)\r\n// \r\n// As a generalization of this technique we can accept a comma-separated list of\r\n// types. Omitting the mpl::front invocation gives us an MPL-sequence.\r\n//\r\n// \r\n// Limitations\r\n// ===========\r\n//\r\n// - only works for types that are valid function arguments\r\n//\r\n// Acknowledgments\r\n// ===============\r\n//\r\n// Thanks go to Dave Abrahams for letting me know this technique.\r\n\r\n#ifndef BOOST_EXAMPLE_MACRO_TYPE_ARGUMENT_HPP_INCLUDED\r\n#define BOOST_EXAMPLE_MACRO_TYPE_ARGUMENT_HPP_INCLUDED\r\n\r\n#include <boost/function_types/parameter_types.hpp>\r\n#include <boost/mpl/front.hpp>\r\n\r\n#define BOOST_EXAMPLE_MACRO_TYPE_ARGUMENT(parenthesized_type)                  \\\r\n    boost::mpl::front<                                                         \\\r\n        BOOST_EXAMPLE_MACRO_TYPE_LIST_ARGUMENT(parenthesized_type) >::type\r\n\r\n#define BOOST_EXAMPLE_MACRO_TYPE_LIST_ARGUMENT(parenthesized_types)            \\\r\n  ::boost::function_types::parameter_types< void(*) parenthesized_types >\r\n\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "ed45015c9fcdb8b9105e3db9d8ba6631b56b6523", "size": 2387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/function_types/example/macro_type_args.hpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 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/function_types/example/macro_type_args.hpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 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/function_types/example/macro_type_args.hpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 32.2567567568, "max_line_length": 81, "alphanum_fraction": 0.6489317134, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434190962774393, "lm_q2_score": 0.06954175173725283, "lm_q1q2_score": 0.01421029434884872}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"bempp/common/config_trilinos.hpp\"\n\n#include \"synthetic_integral_operator.hpp\"\n\n#include \"abstract_boundary_operator_pseudoinverse.hpp\"\n#include \"boundary_operator.hpp\"\n#include \"context.hpp\"\n#include \"discrete_boundary_operator.hpp\"\n#include \"discrete_sparse_boundary_operator.hpp\"\n#include \"identity_operator.hpp\"\n#include \"sparse_inverse.hpp\"\n#include \"transposed_discrete_boundary_operator.hpp\"\n\n#include \"../common/boost_make_shared_fwd.hpp\"\n#include \"../common/shared_ptr.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n\n#ifdef WITH_TRILINOS\n\n#include <boost/make_shared.hpp>\n#endif\n\n#include <Epetra_CrsGraph.h>\n#include <Epetra_CrsMatrix.h>\n#include <EpetraExt_MatrixMatrix.h>\n\n#include <tbb/tick_count.h>\n\nnamespace Bempp {\n\nnamespace {\n\ntemplate <typename T> const T &vectorFirstElement(const std::vector<T> &v) {\n  if (v.empty())\n    throw std::invalid_argument(\n        \"SyntheticIntegralOperator::SyntheticIntegralOperator(): \"\n        \"lists of test and trial-side operators must not be empty\");\n  return v.front();\n}\n\ntemplate <typename ResultType>\nstd::vector<shared_ptr<const DiscreteBoundaryOperator<ResultType>>>\ncoalesceTestOperators(\n    const std::vector<shared_ptr<const DiscreteBoundaryOperator<ResultType>>> &\n        discreteLocalOps,\n    const shared_ptr<const Epetra_CrsMatrix> &idInverse) {\n  typedef DiscreteBoundaryOperator<ResultType> DiscreteOp;\n  typedef DiscreteSparseBoundaryOperator<ResultType> SparseOp;\n  std::vector<shared_ptr<const DiscreteOp>> result(discreteLocalOps.size());\n\n  for (size_t i = 0; i < discreteLocalOps.size(); ++i) {\n    if (!discreteLocalOps[i])\n      throw std::runtime_error(\n          \"coalesceTrialOperators(): null pointer to operator detected\");\n    shared_ptr<const SparseOp> op =\n        boost::dynamic_pointer_cast<const SparseOp>(discreteLocalOps[i]);\n    if (op) {\n      shared_ptr<const Epetra_CrsMatrix> opMat = op->epetraMatrix();\n      shared_ptr<Epetra_CrsMatrix> composition(\n          new Epetra_CrsMatrix(Copy, opMat->Graph()));\n      int err = EpetraExt::MatrixMatrix::Multiply(\n          *opMat, false /* transpose */, *idInverse, false, *composition);\n      if (err != 0)\n        throw std::runtime_error(\n            \"SyntheticIntegralOperator::assembleWeakFormImpl(): \"\n            \"Epetra matrix-matrix multiplication (1) failed\");\n      result[i].reset(new SparseOp(composition));\n    } else\n      throw std::runtime_error(\n          \"SyntheticIntegralOperator::coalesceTestOperators(): \"\n          \"local operator not represented by a sparse matrix\");\n  }\n  return result;\n}\n\ntemplate <typename ResultType>\nstd::vector<shared_ptr<const DiscreteBoundaryOperator<ResultType>>>\ncoalesceTrialOperators(\n    const std::vector<shared_ptr<const DiscreteBoundaryOperator<ResultType>>> &\n        discreteLocalOps,\n    const shared_ptr<const Epetra_CrsMatrix> &idInverse) {\n  typedef DiscreteBoundaryOperator<ResultType> DiscreteOp;\n  typedef DiscreteSparseBoundaryOperator<ResultType> SparseOp;\n  std::vector<shared_ptr<const DiscreteOp>> result(discreteLocalOps.size());\n\n  for (size_t i = 0; i < discreteLocalOps.size(); ++i) {\n    if (!discreteLocalOps[i])\n      throw std::runtime_error(\n          \"coalesceTrialOperators(): null pointer to operator detected\");\n    shared_ptr<const SparseOp> op =\n        boost::dynamic_pointer_cast<const SparseOp>(discreteLocalOps[i]);\n    if (op) {\n      shared_ptr<const Epetra_CrsMatrix> opMat = op->epetraMatrix();\n      shared_ptr<Epetra_CrsMatrix> composition(\n          new Epetra_CrsMatrix(Copy, opMat->Graph()));\n      int err = EpetraExt::MatrixMatrix::Multiply(\n          *idInverse, true /* transpose */, *opMat, false, *composition);\n      if (err != 0)\n        throw std::runtime_error(\n            \"SyntheticIntegralOperator::assembleWeakFormImpl(): \"\n            \"Epetra matrix-matrix multiplication (1) failed\");\n      result[i].reset(new SparseOp(composition));\n    } else\n      throw std::runtime_error(\n          \"SyntheticIntegralOperator::coalesceTrialOperators(): \"\n          \"local operator not represented by a sparse matrix\");\n  }\n  return result;\n}\n\ntemplate <typename ResultType>\nstd::vector<shared_ptr<const DiscreteBoundaryOperator<ResultType>>>\ntransposeTestOperators(\n    const std::vector<shared_ptr<const DiscreteBoundaryOperator<ResultType>>> &\n        discreteLocalOps,\n    bool hermitian) {\n  typedef DiscreteBoundaryOperator<ResultType> DiscreteOp;\n  typedef DiscreteSparseBoundaryOperator<ResultType> SparseOp;\n  std::vector<shared_ptr<const DiscreteOp>> result(discreteLocalOps.size());\n\n  for (size_t i = 0; i < discreteLocalOps.size(); ++i) {\n    if (!discreteLocalOps[i])\n      throw std::runtime_error(\n          \"coalesceTrialOperators(): null pointer to operator detected\");\n    shared_ptr<const SparseOp> op =\n        boost::dynamic_pointer_cast<const SparseOp>(discreteLocalOps[i]);\n    if (op) {\n      int mode = op->transpositionMode();\n      if (mode & TRANSPOSE)\n        mode &= ~TRANSPOSE;\n      else\n        mode |= TRANSPOSE;\n      result[i].reset(new SparseOp(op->epetraMatrix(), op->symmetryMode(),\n                                   static_cast<TranspositionMode>(mode)));\n    } else\n      result[i].reset(new TransposedDiscreteBoundaryOperator<ResultType>(\n          hermitian ? CONJUGATE_TRANSPOSE : TRANSPOSE, discreteLocalOps[i]));\n  }\n  return result;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const Space<BasisFunctionType>> determineDomain(\n    const std::vector<BoundaryOperator<BasisFunctionType, ResultType>> &\n        testLocalOps,\n    const BoundaryOperator<BasisFunctionType, ResultType> &integralOp,\n    const std::vector<BoundaryOperator<BasisFunctionType, ResultType>> &\n        trialLocalOps,\n    int symmetry) {\n  if (trialLocalOps.empty())\n    if (testLocalOps.empty())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::SyntheticIntegralOperator(): \"\n          \"testLocalOps and trialLocalOps must not both be empty.\");\n    else {\n      if (symmetry & (SYMMETRIC | HERMITIAN))\n        return testLocalOps[0].dualToRange();\n      else\n        return integralOp.domain();\n    }\n  else\n    return trialLocalOps[0].domain();\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const Space<BasisFunctionType>> determineRange(\n    const std::vector<BoundaryOperator<BasisFunctionType, ResultType>> &\n        testLocalOps,\n    const BoundaryOperator<BasisFunctionType, ResultType> &integralOp) {\n  if (testLocalOps.empty())\n    return integralOp.range();\n  else\n    return testLocalOps[0].range();\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const Space<BasisFunctionType>> determineDualToRange(\n    const std::vector<BoundaryOperator<BasisFunctionType, ResultType>> &\n        testLocalOps,\n    const BoundaryOperator<BasisFunctionType, ResultType> &integralOp) {\n  if (testLocalOps.empty())\n    return integralOp.dualToRange();\n  else\n    return testLocalOps[0].dualToRange();\n}\n\n} // namespace\n\ntemplate <typename BasisFunctionType, typename ResultType>\nSyntheticIntegralOperator<BasisFunctionType, ResultType>::\n    SyntheticIntegralOperator(\n        const std::vector<BoundaryOperator<BasisFunctionType, ResultType>> &\n            testLocalOps,\n        const BoundaryOperator<BasisFunctionType, ResultType> &integralOp,\n        const std::vector<BoundaryOperator<BasisFunctionType, ResultType>> &\n            trialLocalOps,\n        const std::string &label, int syntheseSymmetry)\n    : Base(determineDomain(testLocalOps, integralOp, trialLocalOps,\n                           syntheseSymmetry),\n           determineRange(testLocalOps, integralOp),\n           determineDualToRange(testLocalOps, integralOp), label,\n           syntheseSymmetry & integralOp.abstractOperator()->symmetry()),\n      m_integralOp(integralOp), m_testLocalOps(testLocalOps),\n      m_trialLocalOps(trialLocalOps), m_syntheseSymmetry(syntheseSymmetry) {\n  // Note: the code does not at present distinguish properly between symmetric\n  // and/or hermitian operators (in fact symmetry handling is, frankly, a\n  // mess). We get away with this because sparse operators can only contain\n  // real entries anyway. To be fixed in future.\n\n  checkIntegralOperator();\n  if (m_testLocalOps.size() > 0 && m_trialLocalOps.size() > 0 &&\n      m_testLocalOps.size() != m_trialLocalOps.size())\n    throw std::invalid_argument(\n        \"SyntheticIntegralOperator::SyntheticIntegralOperator(): \"\n        \"if both testLocalOps and trialLocalOps are non-empty, \"\n        \"both must have the same number of elements\");\n  checkTestLocalOperators();\n  if ((syntheseSymmetry & SYMMETRIC) || (syntheseSymmetry & HERMITIAN)) {\n    if (m_testLocalOps.empty())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::SyntheticIntegralOperator(): \"\n          \"symmetric operator requested but testLocalOps empty\");\n    m_trialLocalOps.clear();\n  } else\n    checkTrialLocalOperators();\n  if (m_testLocalOps.empty() && m_trialLocalOps.empty())\n    throw std::invalid_argument(\n        \"SyntheticIntegralOperator::SyntheticIntegralOperator(): \"\n        \"testLocalOps and trialLocalOps must not both be empty.\");\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nbool SyntheticIntegralOperator<BasisFunctionType, ResultType>::isLocal() const {\n  return false;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid SyntheticIntegralOperator<BasisFunctionType,\n                               ResultType>::checkIntegralOperator() const {\n  if (!m_integralOp.isInitialized())\n    throw std::invalid_argument(\n        \"SyntheticIntegralOperator::checkIntegralOperator(): \"\n        \"all operators must be initialized\");\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid SyntheticIntegralOperator<BasisFunctionType,\n                               ResultType>::checkTestLocalOperators() const {\n  size_t localOperatorCount = m_testLocalOps.size();\n  for (size_t i = 0; i < localOperatorCount; ++i)\n    if (!m_testLocalOps[i].isInitialized())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTestLocalOperators(): \"\n          \"all operators must be initialized\");\n  for (size_t i = 0; i < localOperatorCount; ++i)\n    if (!m_testLocalOps[i].abstractOperator()->isLocal())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTestLocalOperators(): \"\n          \"all test operators must be local\");\n  for (size_t i = 0; i < localOperatorCount; ++i)\n    if (m_testLocalOps[i].domain() != m_integralOp.dualToRange())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTestLocalOperators(): \"\n          \"domain of all test operators must be identical with the dual \"\n          \"to range of the integral operator\");\n  for (size_t i = 1; i < localOperatorCount; ++i)\n    if (m_testLocalOps[i].domain() != m_testLocalOps[0].domain() ||\n        m_testLocalOps[i].range() != m_testLocalOps[0].range() ||\n        m_testLocalOps[i].dualToRange() != m_testLocalOps[0].dualToRange())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTestLocalOperators(): \"\n          \"test operators have inconsistent spaces\");\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid SyntheticIntegralOperator<BasisFunctionType,\n                               ResultType>::checkTrialLocalOperators() const {\n  size_t localOperatorCount = m_trialLocalOps.size();\n  for (size_t i = 0; i < localOperatorCount; ++i)\n    if (!m_trialLocalOps[i].isInitialized())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTrialLocalOperators(): \"\n          \"all operators must be initialized\");\n  for (size_t i = 0; i < localOperatorCount; ++i)\n    if (!m_trialLocalOps[i].abstractOperator()->isLocal())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTrialLocalOperators(): \"\n          \"all test operators must be local\");\n  for (size_t i = 0; i < localOperatorCount; ++i)\n    if (m_trialLocalOps[i].dualToRange() != m_integralOp.domain())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTrialLocalOperators(): \"\n          \"dual to range of all trial operators must be identical with the \"\n          \"domain of the integral operator\");\n  for (size_t i = 1; i < localOperatorCount; ++i)\n    if (m_trialLocalOps[i].domain() != m_trialLocalOps[0].domain() ||\n        m_trialLocalOps[i].range() != m_trialLocalOps[0].range() ||\n        m_trialLocalOps[i].dualToRange() != m_trialLocalOps[0].dualToRange())\n      throw std::invalid_argument(\n          \"SyntheticIntegralOperator::checkTrialLocalOperators(): \"\n          \"trial operators have inconsistent spaces\");\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<DiscreteBoundaryOperator<ResultType>>\nSyntheticIntegralOperator<BasisFunctionType, ResultType>::assembleWeakFormImpl(\n    const Context<BasisFunctionType, ResultType> &context) const {\n  bool verbose =\n      (context.assemblyOptions().verbosityLevel() >= VerbosityLevel::DEFAULT);\n  if (verbose)\n    std::cout << \"Assembling the weak form of operator '\" << this->label()\n              << \"'...\" << std::endl;\n\n  tbb::tick_count start = tbb::tick_count::now();\n\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n  typedef DiscreteBoundaryOperator<ResultType> DiscreteLinOp;\n\n  bool symmetricMode =\n      m_syntheseSymmetry & SYMMETRIC || m_syntheseSymmetry & HERMITIAN;\n  // std::cout << \"symmetricMode: \" << symmetricMode << std::endl;\n\n  // We don't need a persistent shared pointer\n  shared_ptr<const Context<BasisFunctionType, ResultType>> internalContext,\n      auxContext;\n  getContextsForInternalAndAuxiliaryOperators(make_shared_from_ref(context),\n                                              internalContext, auxContext);\n\n  shared_ptr<const DiscreteLinOp> discreteIntegralOp = m_integralOp.weakForm();\n  std::vector<shared_ptr<const DiscreteLinOp>> discreteTestLocalOps(\n      m_testLocalOps.size()),\n      discreteTrialLocalOps(m_trialLocalOps.size());\n  for (size_t i = 0; i < m_testLocalOps.size(); ++i)\n    discreteTestLocalOps[i] = m_testLocalOps[i].weakForm();\n  // doesn't do any harm if the list of trial operators is empty\n  for (size_t i = 0; i < m_trialLocalOps.size(); ++i)\n    discreteTrialLocalOps[i] = m_trialLocalOps[i].weakForm();\n\n  // Calculate the inverse mass matrices\n  typedef DiscreteSparseBoundaryOperator<ResultType> SparseOp;\n  shared_ptr<const SparseOp> discreteTestId, discreteTrialId;\n  shared_ptr<Epetra_CrsMatrix> testInverse, trialInverse;\n  if (!discreteTestLocalOps.empty()) {\n    BoundaryOp testId = identityOperator(\n        // We don't need a persistent shared_ptr since identityOperator\n        // will go out of scope at the end of this function anyway.\n        // All we need is a weak form.\n        auxContext, m_integralOp.dualToRange(), m_integralOp.dualToRange(),\n        m_integralOp.dualToRange(), \"(\" + this->label() + \")_test_id\");\n    discreteTestId = dynamic_pointer_cast<const SparseOp>(testId.weakForm());\n    if (!discreteTestId)\n      throw std::runtime_error(\n          \"SyntheticIntegralOperator::SyntheticIntegralOperator(): \"\n          \"identity operator must be represented by a sparse matrix\");\n\n    // NOTE: here we form the explicit inverse of the mass matrix. Of\n    // course it is not the right way to do it and we'd be better off using\n    // Cholesky decomposition and triangular solves. However, implementing\n    // this for sparse matrices would be relatively hard. Moreover, in\n    // practice the mass matrix will be block diagonal (since the internal\n    // domain and dual to range spaces will be discontinuous), so we only\n    // form explicit inverses of very small (e.g. 3 x 3) blocks, and mass\n    // matrices are usually well conditioned. So explicit inversion\n    // shouldn't cause any significant loss of accuracy.\n    testInverse = sparseInverse(*discreteTestId->epetraMatrix());\n  }\n\n  if (!discreteTrialLocalOps.empty()) {\n    if (m_integralOp.domain() == m_integralOp.dualToRange() && discreteTestId) {\n      discreteTrialId = discreteTestId;\n      //            discreteTrialInvId = discreteTestInvId;\n      trialInverse = testInverse;\n    } else {\n      BoundaryOp trialId = identityOperator(\n          auxContext, m_integralOp.domain(), m_integralOp.domain(),\n          m_integralOp.domain(), \"(\" + this->label() + \")_trial_id\");\n      discreteTrialId =\n          dynamic_pointer_cast<const SparseOp>(trialId.weakForm());\n      if (!discreteTrialId)\n        throw std::runtime_error(\n            \"SyntheticIntegralOperator::SyntheticIntegralOperator(): \"\n            \"identity operator must be represented by a sparse matrix\");\n      trialInverse = sparseInverse(*discreteTrialId->epetraMatrix());\n    }\n  }\n\n  // Coalesce sparse operators\n  discreteTestLocalOps =\n      coalesceTestOperators(discreteTestLocalOps, testInverse);\n  if (discreteTrialLocalOps.empty()) {\n    if (symmetricMode)\n      discreteTrialLocalOps = transposeTestOperators(\n          discreteTestLocalOps, m_syntheseSymmetry & HERMITIAN);\n  } else\n    discreteTrialLocalOps =\n        coalesceTrialOperators(discreteTrialLocalOps, trialInverse);\n\n  // Now join all the pieces together\n  shared_ptr<DiscreteLinOp> result;\n  if (discreteTestLocalOps.empty()) {\n    result = mul<ResultType>(discreteIntegralOp, discreteTrialLocalOps[0]);\n    for (size_t i = 1; i < discreteTestLocalOps.size(); ++i)\n      result =\n          sum<ResultType>(result, mul<ResultType>(discreteIntegralOp,\n                                                  discreteTrialLocalOps[i]));\n  } else if (discreteTrialLocalOps.empty()) {\n    result = mul<ResultType>(discreteTestLocalOps[0], discreteIntegralOp);\n    for (size_t i = 1; i < discreteTestLocalOps.size(); ++i)\n      result = sum<ResultType>(\n          result, mul<ResultType>(discreteTestLocalOps[i], discreteIntegralOp));\n  } else {\n    result = mul<ResultType>(\n        mul<ResultType>(discreteTestLocalOps[0], discreteIntegralOp),\n        discreteTrialLocalOps[0]);\n    for (size_t i = 1; i < discreteTestLocalOps.size(); ++i)\n      result = sum<ResultType>(\n          result, mul<ResultType>(mul<ResultType>(discreteTestLocalOps[i],\n                                                  discreteIntegralOp),\n                                  discreteTrialLocalOps[i]));\n  }\n\n  tbb::tick_count end = tbb::tick_count::now();\n\n  if (verbose)\n    std::cout << \"Assembly of the weak form of operator '\" << this->label()\n              << \"' took \" << (end - start).seconds() << \" s\" << std::endl;\n  return result;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid SyntheticIntegralOperator<BasisFunctionType, ResultType>::\n    getContextsForInternalAndAuxiliaryOperators(\n        const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n        shared_ptr<const Context<BasisFunctionType, ResultType>> &\n            internalContext,\n        shared_ptr<const Context<BasisFunctionType, ResultType>> &auxContext) {\n  typedef Context<BasisFunctionType, ResultType> Ctx;\n  AssemblyOptions assemblyOptions = context->assemblyOptions();\n  AcaOptions acaOptions = assemblyOptions.acaOptions();\n  acaOptions.mode = AcaOptions::GLOBAL_ASSEMBLY;\n  if (assemblyOptions.assemblyMode() == AssemblyOptions::ACA)\n    assemblyOptions.switchToAcaMode(acaOptions);\n  internalContext.reset(new Ctx(context->quadStrategy(), assemblyOptions));\n  auxContext = internalContext;\n  if (assemblyOptions.verbosityLevel() < VerbosityLevel::HIGH) {\n    // Suppress timing messages from auxiliary operators\n    assemblyOptions.setVerbosityLevel(VerbosityLevel::LOW);\n    auxContext.reset(new Ctx(context->quadStrategy(), assemblyOptions));\n  }\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(\n    SyntheticIntegralOperator);\n\n} // namespace Bempp\n", "meta": {"hexsha": "5a0ddf0207913530544300b1a79723c23b967315", "size": 20994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/synthetic_integral_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/synthetic_integral_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/synthetic_integral_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": 44.1050420168, "max_line_length": 80, "alphanum_fraction": 0.7090120987, "num_tokens": 4877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.02931223276527609, "lm_q1q2_score": 0.014198261777191015}}
{"text": "/**\n * Copyright Soramitsu Co., Ltd. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n#ifndef KAGOME_STROBE_HPP\n#define KAGOME_STROBE_HPP\n\n#include <array>\n#include <cstdint>\n#include <cstring>\n#include <gsl/span>\n#include <tuple>\n#include <type_traits>\n\n#include <boost/assert.hpp>\n\n#include \"crypto/keccak/keccak.h\"\n#include \"primitives/math.hpp\"\n\nnamespace kagome::primitives {\n\n  /**\n   * C++ implementation(Alexander 'iceseer' Lednev) of\n   * https://strobe.sourceforge.io/\n   */\n  class Strobe final {\n    static constexpr size_t kBufferSize = 200ull;\n    static constexpr size_t kAlignment = 8ull;\n    static constexpr uint8_t kStrobeR = 166;\n\n    using Flags = uint8_t;\n    using Position = uint8_t;\n\n    static constexpr Flags kFlag_NU = 0x00;  // NU = No Use\n    static constexpr Flags kFlag_I = 0x01;\n    static constexpr Flags kFlag_A = 0x02;\n    static constexpr Flags kFlag_C = 0x04;\n    static constexpr Flags kFlag_T = 0x08;\n    static constexpr Flags kFlag_M = 0x10;\n    static constexpr Flags kFlag_K = 0x20;\n\n    uint8_t raw_data[kBufferSize + kAlignment - 1ull + 3ull];\n    uint8_t *const buffer_;\n    Position &current_position_;\n    Position &begin_position_;\n    Flags &current_state_;\n\n    template <typename T, size_t kOffset = 0ull>\n    constexpr T *as() {\n      static_assert(kOffset < count<T>(), \"Overflow!\");\n      return (reinterpret_cast<T *>(buffer_) + kOffset);  // NOLINT\n    }\n\n    template <typename T, size_t kOffset = 0ull>\n    constexpr const T *as() const {\n      static_assert(kOffset < count<T>(), \"Overflow!\");\n      return (reinterpret_cast<const T *>(buffer_) + kOffset);  // NOLINT\n    }\n\n    template <typename T>\n    T *as(Position offset) {\n      BOOST_ASSERT(static_cast<size_t>(offset) < count<T>());\n      return (as<T>() + offset);\n    }\n\n    template <typename T>\n    static constexpr size_t count() {\n      static_assert(!std::is_reference_v<T>, \"Can not be a reference type.\");\n      static_assert(!std::is_pointer_v<T>, \"Can not be a pointer.\");\n      static_assert(std::is_integral_v<T>, \"Cast to non integral type.\");\n      return kBufferSize / sizeof(T);\n    }\n\n    template <size_t kOffset, typename T, size_t N>\n    void load(const T (&data)[N]) {  // NOLINT\n      static_assert(kOffset + N <= count<T>(), \"Load overflows!\");\n      std::memcpy(as<T, kOffset>(), data, N);\n    }\n\n    template <typename T, size_t N>\n    void absorb(const T (&src)[N]) {\n      for (const auto i : src) {\n        *as<uint8_t>(current_position_++) ^= static_cast<uint8_t>(i);\n        if (kStrobeR == current_position_) {\n          runF();\n        }\n      }\n    }\n\n    template <typename T, size_t N>\n    void overwrite(const T (&src)[N]) {\n      for (const auto i : src) {\n        *as<uint8_t>(current_position_++) = static_cast<uint8_t>(i);\n        if (kStrobeR == current_position_) {\n          runF();\n        }\n      }\n    }\n\n    template <typename T, size_t N>\n    void squeeze(T (&src)[N]) {\n      for (auto &i : src) {\n        i = static_cast<T>(*as<uint8_t>(current_position_));\n        *as<uint8_t>(current_position_++) = 0;\n        if (kStrobeR == current_position_) {\n          runF();\n        }\n      }\n    }\n\n    template <bool kMore, Flags kFlags>\n    void beginOp() {\n      static_assert((kFlags & kFlag_T) == 0, \"T flag doesn't support\");\n      if constexpr (kMore) {\n        BOOST_ASSERT(current_state_ == kFlags);\n        return;\n      }\n\n      const auto old_begin = begin_position_;\n      begin_position_ = current_position_ + 1;\n      current_state_ = kFlags;\n      absorb({old_begin, kFlags});\n\n      if constexpr (0 != (kFlags & (kFlag_C | kFlag_K))) {\n        if (current_position_ != 0) {\n          runF();\n        }\n      }\n    }\n\n    void runF() {\n      *as<uint8_t>(current_position_) ^= begin_position_;\n      *as<uint8_t>(current_position_ + 1) ^= 0x04;\n      *as<uint8_t>(kStrobeR + 1) ^= 0x80;\n      keccakf(as<uint64_t>());\n\n      current_position_ = 0;\n      begin_position_ = 0;\n    }\n\n   public:\n    Strobe()\n        : buffer_{reinterpret_cast<uint8_t *>(\n            math::roundUp<kAlignment>(reinterpret_cast<uintptr_t>(raw_data)))},\n          current_position_{*(buffer_ + kBufferSize)},\n          begin_position_{*(buffer_ + kBufferSize + 1ull)},\n          current_state_{*(buffer_ + kBufferSize + 2ull)} {}\n\n    Strobe(const Strobe &other) : Strobe() {\n      std::copy(std::begin(other.raw_data),\n                std::end(other.raw_data),\n                std::begin(raw_data));\n    };\n\n    Strobe &operator=(const Strobe &other) {\n      std::copy(std::begin(other.raw_data),\n                std::end(other.raw_data),\n                std::begin(raw_data));\n      return *this;\n    }\n\n    Strobe(Strobe &&) = delete;\n    Strobe &operator=(Strobe &&) = delete;\n\n    template <typename T, size_t N>\n    void initialize(const T (&label)[N]) {\n      constexpr bool kUseRuntimeCalculation = false;\n\n      if constexpr (kUseRuntimeCalculation) {\n        std::memset(as<uint8_t>(), 0, count<uint8_t>());\n        load<0ull>((uint8_t[6]){1, kStrobeR + 2, 1, 0, 1, 96});\n        load<6ull>(\"STROBEv1.0.2\");\n        keccakf(as<uint64_t>());\n      } else {\n        load<0ull>((uint8_t[kBufferSize]){\n            0x9c, 0x6d, 0x16, 0x8f, 0xf8, 0xfd, 0x55, 0xda, 0x2a, 0xa7, 0x3c,\n            0x23, 0x55, 0x65, 0x35, 0x63, 0xdc, 0xc,  0x47, 0x5c, 0x55, 0x15,\n            0x26, 0xf6, 0x73, 0x3b, 0xea, 0x22, 0xf1, 0x6c, 0xb5, 0x7c, 0xd3,\n            0x1f, 0x68, 0x2e, 0x66, 0xe,  0xe9, 0x12, 0x82, 0x4a, 0x77, 0x22,\n            0x1,  0xee, 0x13, 0x94, 0x22, 0x6f, 0x4a, 0xfc, 0xb6, 0x2d, 0x33,\n            0x12, 0x93, 0xcc, 0x92, 0xe8, 0xa6, 0x24, 0xac, 0xf6, 0xe1, 0xb6,\n            0x0,  0x95, 0xe3, 0x22, 0xbb, 0xfb, 0xc8, 0x45, 0xe5, 0xb2, 0x69,\n            0x95, 0xfe, 0x7d, 0x7c, 0x84, 0x13, 0x74, 0xd1, 0xff, 0x58, 0x98,\n            0xc9, 0x2e, 0xe0, 0x63, 0x6b, 0x6,  0x72, 0x73, 0x21, 0xc9, 0x2a,\n            0x60, 0x39, 0x7,  0x3,  0x53, 0x49, 0xcc, 0xbb, 0x1b, 0x92, 0xb7,\n            0xb0, 0x5,  0x7e, 0x8f, 0xa8, 0x7f, 0xce, 0xbc, 0x7e, 0x88, 0x65,\n            0x6f, 0xcb, 0x45, 0xae, 0x4,  0xbc, 0x34, 0xca, 0xbe, 0xae, 0xbe,\n            0x79, 0xd9, 0x17, 0x50, 0xc0, 0xe8, 0xbf, 0x13, 0xb9, 0x66, 0x50,\n            0x4d, 0x13, 0x43, 0x59, 0x72, 0x65, 0xdd, 0x88, 0x65, 0xad, 0xf9,\n            0x14, 0x9,  0xcc, 0x9b, 0x20, 0xd5, 0xf4, 0x74, 0x44, 0x4,  0x1f,\n            0x97, 0xb6, 0x99, 0xdd, 0xfb, 0xde, 0xe9, 0x1e, 0xa8, 0x7b, 0xd0,\n            0x9b, 0xf8, 0xb0, 0x2d, 0xa7, 0x5a, 0x96, 0xe9, 0x47, 0xf0, 0x7f,\n            0x5b, 0x65, 0xbb, 0x4e, 0x6e, 0xfe, 0xfa, 0xa1, 0x6a, 0xbf, 0xd9,\n            0xfb, 0xf6});\n      }\n\n      current_position_ = 0;\n      current_state_ = kFlag_NU;\n      begin_position_ = 0;\n\n      metaAd<false>(label);\n    }\n\n    template <bool kMore, typename T, size_t N>\n    void ad(const T (&src)[N]) {\n      beginOp<kMore, kFlag_A>();\n      absorb(src);\n    }\n\n    template <bool kMore, typename T, size_t N>\n    void metaAd(const T (&label)[N]) {\n      beginOp<kMore, kFlag_M | kFlag_A>();\n      absorb(label);\n    }\n\n    template <bool kMore, typename T, size_t N>\n    void prf(T (&data)[N]) {\n      beginOp<kMore, kFlag_I | kFlag_A | kFlag_C>();\n      squeeze(data);\n    }\n\n    template <bool kMore, typename T, size_t N>\n    void key(const T (&data)[N]) {\n      beginOp<kMore, kFlag_A | kFlag_C>();\n      overwrite(data);\n    }\n\n    auto data() {\n      return gsl::make_span(as<const uint8_t>(), count<uint8_t>() + 3ull);\n    }\n\n    auto data() const {\n      return gsl::make_span(as<const uint8_t>(), count<uint8_t>() + 3ull);\n    }\n  };\n\n}  // namespace kagome::primitives\n\n#endif  // KAGOME_STROBE_HPP\n", "meta": {"hexsha": "741728b3858eabd530d10cb321f31ce6b40683e6", "size": 7637, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/primitives/strobe.hpp", "max_stars_repo_name": "igor-egorov/kagome", "max_stars_repo_head_hexsha": "b2a77061791aa7c1eea174246ddc02ef5be1b605", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 110.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T13:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T11:54:42.000Z", "max_issues_repo_path": "core/primitives/strobe.hpp", "max_issues_repo_name": "igor-egorov/kagome", "max_issues_repo_head_hexsha": "b2a77061791aa7c1eea174246ddc02ef5be1b605", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 890.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T21:33:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:31:22.000Z", "max_forks_repo_path": "core/primitives/strobe.hpp", "max_forks_repo_name": "igor-egorov/kagome", "max_forks_repo_head_hexsha": "b2a77061791aa7c1eea174246ddc02ef5be1b605", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2019-06-25T06:21:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T14:12:10.000Z", "avg_line_length": 31.6887966805, "max_line_length": 79, "alphanum_fraction": 0.590284143, "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796361952087, "lm_q2_score": 0.029760092224914082, "lm_q1q2_score": 0.014183053925685413}}
{"text": "/*\n * MIT License\n * \n * Copyright (c) 2015 Alexis LE GOADEC\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#include <boost/program_options/cmdline.hpp>\n#include <boost/program_options/config.hpp>\n#include <boost/program_options/environment_iterator.hpp>\n#include <boost/program_options/eof_iterator.hpp>\n#include <boost/program_options/errors.hpp>\n#include <boost/program_options/option.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/positional_options.hpp>\n#include <boost/program_options/value_semantic.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/version.hpp>\n#include <fstream>\n#include <iostream>\n\n#include \"include/Client.hh\"\n#include \"include/RandomHypergraphe.hh\"\n\n#include \"../include/Hypergraph/model/LibType.hh\"\n#include \"../include/Hypergraph/model/Hypergraphe.hh\"\n#include \"../include/Hypergraph/model/HyperFactory.hh\"\n#include \"../include/Hypergraph/model/HyperVertex.hh\"\n#include \"../include/Hypergraph/model/HyperEdge.hh\"\n#include \"../include/Hypergraph/model/MotorAlgorithm.hh\"\n\n#include \"../include/Hypergraph/algorithm/Dual.hh\"\n#include \"../include/Hypergraph/algorithm/Path.hh\"\n#include \"../include/Hypergraph/algorithm/Helly.hh\"\n#include \"../include/Hypergraph/algorithm/kRegular.hh\"\n#include \"../include/Hypergraph/algorithm/kUniform.hh\"\n#include \"../include/Hypergraph/algorithm/Simple.hh\"\n#include \"../include/Hypergraph/algorithm/Linear.hh\"\n#include \"../include/Hypergraph/algorithm/Connected.hh\"\n#include \"../include/Hypergraph/algorithm/HyperGraphStat.hh\"\n#include \"../include/Hypergraph/algorithm/Isomorph.hh\"\n\n#include \"../include/Hypergraph/io/WriterFile.hh\"\n#include \"../include/Hypergraph/io/ReaderFile.hh\"\n\n\nint main(int argc, char *argv[]) {\n\n\tboost::program_options::options_description desc(\"Paramètres\");\n\tdesc.add_options()\n\t\t\t\t\t(\"version\", \"Afficher la version\")\n\t\t\t\t\t(\"help\", \"Afficher l'aide\")\n\t\t\t\t\t(\"inputfile\", boost::program_options::value<std::string>(), \"Fichier d'entrée\")\n\t\t\t\t\t(\"random\", boost::program_options::value<int>(), \"Hypergraphe aléatoire de n vertex\")\n\t\t\t\t\t(\"adjacence\", \"Affiche la matrice d'adjacence de l'hypergraphe\")\n\t\t\t\t\t(\"dual\", \"Produit le Dual de l'hypergraphe\")\n\t\t\t\t\t(\"kuniform\", boost::program_options::value<int>(), \"Décide si l'hypergraphe est k-uniforme\")\n\t\t\t\t\t(\"linear\", \"Décide si l'hypergraphe est linéaire\")\n\t\t\t\t\t(\"kregular\", \"Décide si l'hypergraphe est k-regulier\")\n\t\t\t\t\t(\"simple\", \"Décide si l'hypergraphe est simple\")\n\t\t\t\t\t(\"helly\", \"Décide si un hypergraphe possède la propriété de Helly\")\n\t\t\t\t\t(\"connexe\", \"Décide si l'hypergraphe est connexe\")\n\t\t\t\t\t(\"isomorph\", boost::program_options::value<std::string>(), \"Décide si deux hypergraphes sont isomorphe\")\n\t\t\t\t\t(\"stat\", \"Retourne les statistiques de l'hypergraphe\")\n\t\t\t\t\t(\"path\", \"Retourne le chemins\")\n\t\t\t\t\t(\"source\", boost::program_options::value<int>(), \"Source de la reherche de chemins\")\n\t\t\t\t\t(\"destination\", boost::program_options::value<int>(), \"Destination de la recherche de chemins\");\n\n\tboost::program_options::variables_map vm;\n\tboost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n\tboost::program_options::notify(vm);\n\n\tif (vm.count(\"help\") || vm.empty()) {\n\t    std::cout << desc << \"\\n\";\n\t    return !vm.empty();\n\t}\n\n\tif( vm.count(\"version\") ) {\n\t\tstd::cout << \"HypergraphLib \"\n\t\t\t\t  << VERSION_MAJOR << \".\"\n\t\t\t\t  << VERSION_MINOR << \"-\"\n\t\t\t\t  << VERSION_BUILD\n\t\t\t\t  << std::endl\n\t\t\t\t  << \"Université de Caen Basse-Normandie, 2015 - Alexis LE GOADEC.\"\n\t\t\t\t  << std::endl\n\t\t\t\t  << \"Boost version: \" << BOOST_VERSION << std::endl\n\t\t\t\t  << \"GCC version: \" << __VERSION__ << std::endl\n#ifdef __x86_64\n\t\t\t\t  << \"x86_64: \" << __x86_64 << std::endl\n#endif\n\t\t\t\t  << \"---\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tboost::shared_ptr<HypergrapheAbstrait> ptrHpg;\n\n\tif( vm.count(\"inputfile\") && vm.count(\"random\")==0 ) {\n\t\tstd::ifstream ifs(vm[\"inputfile\"].as<std::string>(), std::ifstream::in);\n\n\t\tReaderFile fReader;\n\t\tfReader.readHypergraphe( ifs );\n\t\tifs.close();\n\n\t\tptrHpg = fReader.getHypergraphe();\n\n\t} else if( vm.count(\"inputfile\")==0 && vm.count(\"random\")==0) {\n\t\tReaderFile fReader;\n\t\tfReader.readHypergraphe( std::cin );\n\t\tptrHpg = fReader.getHypergraphe();\n\t}\n\n\t// Isomorphism special parameters configuration\n\tif( vm.count(\"isomorph\") && vm.count(\"inputfile\") ) {\n\n\t\tboost::shared_ptr<HypergrapheAbstrait> ptrHpg2;\n\n\t\tstd::ifstream ifs(vm[\"isomorph\"].as<std::string>(), std::ifstream::in);\n\n\t\tReaderFile fReader;\n\t\tfReader.readHypergraphe( ifs );\n\t\tifs.close();\n\n\t\tptrHpg2 = fReader.getHypergraphe();\n\n\t\tNewAlgorithm2(isomorphHpg, Isomorph, ptrHpg, ptrHpg2);\n\n\t\tMotorAlgorithm::setAlgorithme( isomorphHpg );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( isomorphHpg->getResult() );\n\n\t\tif( r.getBooleanResult() ) {\n\t\t\tstd::cout << \"L'hypergraphe est isomorphe.\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"L'hypergraphe n'est pas isomorphe.\" << std::endl;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"random\") ) {\n\t\tRandomHypergraphe rHyp;\n\t\trHyp.generateHypergraphe(vm[\"random\"].as<int>(), vm[\"random\"].as<int>());\n\t\tptrHpg = rHyp.getHypergraphe();\n\t}\n\n\tif( vm.count(\"stat\") ) {\n\t\tNewAlgorithm(statHpg, HyperGraphStat, ptrHpg);\n\n\t\tMotorAlgorithm::setAlgorithme( statHpg );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tboost::shared_ptr<HyperGraphStat> s = boost::static_pointer_cast<HyperGraphStat>( statHpg );\n\n\t\tstd::cout << \"Hyper-vertex : \" << s->getNbrHyperVertex() << std::endl\n\t\t\t\t  << \"Hyper-edge   : \" << s->getNbrHyperEdge()   << std::endl\n\t\t\t\t  << \"Nbr. links   : \" << s->getNbrLinks()       << std::endl\n\t\t\t\t  << \"Rang         : \" << s->getRang()           << std::endl\n\t\t\t\t  << \"Co-rang      : \" << s->getCoRang()         << std::endl;\n\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"dual\") ) {\n\n\t\tNewAlgorithm(dualAlgo, Dual, ptrHpg);\n\n\t\tMotorAlgorithm::setAlgorithme( dualAlgo );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( dualAlgo->getResult() );\n\n\t\tWriterFile w(r.getHypergrapheResult());\n\t\tif( vm.count(\"adjacence\") ) {\n\t\t\tw.writeAdjacentMatrix( std::cout );\n\t\t} else {\n\t\t\tw.writeHypergraph( std::cout );\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"kuniform\") ) {\n\t\tboost::shared_ptr<AlgorithmeAbstrait> kuniformAlgo( new kUniform( ptrHpg, vm[\"kuniform\"].as<int>() ) );\n\t\tMotorAlgorithm::setAlgorithme( kuniformAlgo );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( kuniformAlgo->getResult() );\n\t\tif( r.getBooleanResult() ) {\n\t\t\tstd::cout << \"L'hypergraphe est \" << vm[\"kuniform\"].as<int>() << \"-uniforme.\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"L'hypergraphe n'est pas \" << vm[\"kuniform\"].as<int>() << \"-uniforme.\" << std::endl;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"linear\") ) {\n\n\t\tNewAlgorithm(linearAlgo, Linear, ptrHpg);\n\n\t\tMotorAlgorithm::setAlgorithme( linearAlgo );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( linearAlgo->getResult() );\n\t\tif( r.getBooleanResult() ) {\n\t\t\tstd::cout << \"L'hypergraphe est Linéaire.\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"L'hypergraphe n'est pas Linéaire.\" << std::endl;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"helly\") ) {\n\t\tNewAlgorithm(hellyAlgo, Helly, ptrHpg);\n\n\t\tMotorAlgorithm::setAlgorithme( hellyAlgo );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( hellyAlgo->getResult() );\n\t\tif( r.getBooleanResult() ) {\n\t\t\tstd::cout << \"L'hypergraphe est Helly.\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"L'hypergraphe n'est pas Helly.\" << std::endl;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"kregular\") ) {\n\t\tNewAlgorithm(kregularAlgo, kRegular, ptrHpg);\n\n\t\tMotorAlgorithm::setAlgorithme( kregularAlgo );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( kregularAlgo->getResult() );\n\t\tif( r.getBooleanResult() ) {\n\t\t\tstd::cout << \"L'hypergraphe est k-regulier.\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"L'hypergraphe n'est pas k-regulier.\" << std::endl;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"simple\") ) {\n\t\tNewAlgorithm(simpleAlgo, Simple, ptrHpg);\n\n\t\tMotorAlgorithm::setAlgorithme( simpleAlgo );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( simpleAlgo->getResult() );\n\t\tif( r.getBooleanResult() ) {\n\t\t\tstd::cout << \"L'hypergraphe est simple.\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"L'hypergraphe n'est pas simple.\" << std::endl;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif(vm.count(\"path\") ) {\n\t\tboost::shared_ptr<Path> pathAlgo( new Path( ptrHpg ) );\n\n\t\tpathAlgo->setHyperVertex(\n\t\t\t\tptrHpg->getHyperVertexById(vm[\"source\"].as<int>()),\n\t\t\t\tptrHpg->getHyperVertexById(vm[\"destination\"].as<int>() )\n\t\t\t);\n\n\t\tboost::shared_ptr<AlgorithmeAbstrait> algoPathAbstrait( pathAlgo );\n\n\t\tMotorAlgorithm::setAlgorithme( algoPathAbstrait );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructurePath r( pathAlgo->getPathResult() );\n\n\t\tfor(unsigned int i=0; i<r.getPathResult()->size(); i++) {\n\t\t\tLibType::ListHyperVertex hvl( r.getPathResult()->at(i) );\n\t\t\tfor(unsigned int j=0; j<hvl.size(); j++) {\n\t\t\t\tstd::cout << hvl.at(j)->getIdentifier() << \" \";\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t}\n\n\tif( vm.count(\"connexe\") ) {\n\t\tNewAlgorithm(algoConnected, Connected, ptrHpg);\n\n\t\tMotorAlgorithm::setAlgorithme( algoConnected );\n\t\tMotorAlgorithm::runAlgorithme();\n\n\t\tRStructure r( algoConnected->getResult() );\n\t\tif( r.getBooleanResult() ) {\n\t\t\tstd::cout << \"L'hypergraphe est connexe.\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"L'hypergraphe n'est pas connexe.\" << std::endl;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif( vm.count(\"adjacence\") ) {\n\t\tWriterFile w( ptrHpg );\n\t\tw.writeAdjacentMatrix( std::cout );\n\t} else {\n\t\tWriterFile w( ptrHpg );\n\t\tw.writeHypergraph( std::cout );\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "33a2c35641f4fc87f7a963ce4eafb9178c940e8f", "size": 10563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/Client.cpp", "max_stars_repo_name": "ehzawad/HyperGraphLib", "max_stars_repo_head_hexsha": "a1424437a01ad5a9e0efa71d723d32fd58ca589c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2016-05-25T06:25:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T09:15:38.000Z", "max_issues_repo_path": "demo/Client.cpp", "max_issues_repo_name": "ehzawad/HyperGraphLib", "max_issues_repo_head_hexsha": "a1424437a01ad5a9e0efa71d723d32fd58ca589c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-05-08T15:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T07:25:19.000Z", "max_forks_repo_path": "demo/Client.cpp", "max_forks_repo_name": "ehzawad/HyperGraphLib", "max_forks_repo_head_hexsha": "a1424437a01ad5a9e0efa71d723d32fd58ca589c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-02-12T23:12:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T06:34:55.000Z", "avg_line_length": 31.5313432836, "max_line_length": 109, "alphanum_fraction": 0.6784057559, "num_tokens": 3109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478897, "lm_q2_score": 0.040237941904283876, "lm_q1q2_score": 0.014171874844628238}}
{"text": "/*    Copyright (c) 2010-2018, 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#include <map>\r\n#include <string>\r\n#include <iostream>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/algorithm/string/trim.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/bind.hpp>\r\n\r\n#include \"Tudat/Astrodynamics/Aerodynamics/aerodynamicCoefficientInterface.h\"\r\n#include \"Tudat/Astrodynamics/Aerodynamics/customAerodynamicCoefficientInterface.h\"\r\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createFlightConditions.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace simulation_setup\r\n{\r\n\r\n//! Function to create an atmospheric flight conditions object\r\nstd::shared_ptr< aerodynamics::AtmosphericFlightConditions > createAtmosphericFlightConditions(\r\n        const std::shared_ptr< Body > bodyWithFlightConditions,\r\n        const std::shared_ptr< Body > centralBody,\r\n        const std::string& nameOfBodyUndergoingAcceleration,\r\n        const std::string& nameOfBodyExertingAcceleration,\r\n        const std::function< double( ) > angleOfAttackFunction,\r\n        const std::function< double( ) > angleOfSideslipFunction,\r\n        const std::function< double( ) > bankAngleFunction,\r\n        const std::function< void( const double ) > angleUpdateFunction )\r\n{\r\n    // Check whether all required environment models are set.\r\n    if( centralBody->getAtmosphereModel( ) == nullptr )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no atmosphere model.\" );\r\n    }\r\n\r\n    if( centralBody->getShapeModel( ) == nullptr )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no shape model.\" );\r\n    }\r\n\r\n    if( centralBody->getRotationalEphemeris( ) == nullptr )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no rotation model.\" );\r\n    }\r\n\r\n    if( bodyWithFlightConditions->getAerodynamicCoefficientInterface( ) == nullptr )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyUndergoingAcceleration +\r\n                    \" has no aerodynamic coefficients.\" );\r\n    }\r\n\r\n\r\n    // Create function to rotate state from intertial to body-fixed frame.\r\n    std::function< Eigen::Quaterniond( ) > rotationToFrameFunction =\r\n            std::bind( &Body::getCurrentRotationToLocalFrame, centralBody );\r\n    std::function< Eigen::Matrix3d( ) > rotationMatrixToFrameDerivativeFunction =\r\n            std::bind( &Body::getCurrentRotationMatrixDerivativeToLocalFrame, centralBody );\r\n\r\n    std::function< Eigen::Matrix< double, 6, 1 >( ) > bodyStateFunction = std::bind( &Body::getState, bodyWithFlightConditions );\r\n    std::function< Eigen::Matrix< double, 6, 1 >( ) > centralBodyStateFunction = std::bind( &Body::getState, centralBody );\r\n\r\n    std::function< Eigen::Matrix< double, 6, 1 >( ) > relativeBodyFixedStateFunction =\r\n            std::bind( &ephemerides::transformRelativeStateToFrame< double >,\r\n                         bodyStateFunction, centralBodyStateFunction,\r\n                         rotationToFrameFunction,\r\n                         rotationMatrixToFrameDerivativeFunction );\r\n\r\n    // Create aerodynamic angles calculator and set in flight conditions.\r\n    std::shared_ptr< reference_frames::AerodynamicAngleCalculator > aerodynamicAngleCalculator =\r\n            std::make_shared< reference_frames::AerodynamicAngleCalculator >(\r\n                relativeBodyFixedStateFunction,\r\n                std::bind( &simulation_setup::Body::getCurrentRotationToGlobalFrame, centralBody ),\r\n                nameOfBodyExertingAcceleration, 1,\r\n                angleOfAttackFunction, angleOfSideslipFunction, bankAngleFunction, angleUpdateFunction );\r\n\r\n    // Add wind model if present\r\n    if( centralBody->getAtmosphereModel( )->getWindModel( ) != nullptr )\r\n    {\r\n        if( centralBody->getShapeModel( ) == nullptr )\r\n        {\r\n            std::cerr << \"Warnning, body \" << nameOfBodyExertingAcceleration << \" has wind model, but no shape model, cannot compute wind as function of altitude \" << std::endl;\r\n        }\r\n        else\r\n        {\r\n           aerodynamicAngleCalculator->setWindModel(\r\n                        centralBody->getAtmosphereModel( )->getWindModel( ), centralBody->getShapeModel( ) );\r\n        }\r\n    }\r\n\r\n\r\n    // Create flight conditions.\r\n    std::function< double( const std::string& )> controlSurfaceDeflectionFunction;\r\n    if( bodyWithFlightConditions->getVehicleSystems( ) != nullptr )\r\n    {\r\n        controlSurfaceDeflectionFunction = std::bind(\r\n                    &system_models::VehicleSystems::getCurrentControlSurfaceDeflection,\r\n                    bodyWithFlightConditions->getVehicleSystems( ), std::placeholders::_1 );\r\n    }\r\n    std::shared_ptr< aerodynamics::AtmosphericFlightConditions > flightConditions =\r\n            std::make_shared< aerodynamics::AtmosphericFlightConditions >(\r\n                centralBody->getAtmosphereModel( ), centralBody->getShapeModel( ),\r\n                bodyWithFlightConditions->getAerodynamicCoefficientInterface( ), aerodynamicAngleCalculator,\r\n                controlSurfaceDeflectionFunction );\r\n\r\n    return flightConditions;\r\n\r\n\r\n}\r\n\r\n//! Function to create a flight conditions object\r\nstd::shared_ptr< aerodynamics::FlightConditions >  createFlightConditions(\r\n        const std::shared_ptr< Body > bodyWithFlightConditions,\r\n        const std::shared_ptr< Body > centralBody,\r\n        const std::string& nameOfBodyUndergoingAcceleration,\r\n        const std::string& nameOfBodyExertingAcceleration )\r\n{\r\n    // Check whether all required environment models are set.\r\n    if( centralBody->getShapeModel( ) == nullptr )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no shape model.\" );\r\n    }\r\n\r\n    if( centralBody->getRotationalEphemeris( ) == nullptr )\r\n    {\r\n        throw std::runtime_error(\r\n                    \"Error when making flight conditions, body \" + nameOfBodyExertingAcceleration +\r\n                    \" has no rotation model.\" );\r\n    }\r\n\r\n    // Create function to rotate state from intertial to body-fixed frame.\r\n    std::function< Eigen::Quaterniond( ) > rotationToFrameFunction =\r\n            std::bind( &Body::getCurrentRotationToLocalFrame, centralBody );\r\n    std::function< Eigen::Matrix3d( ) > rotationMatrixToFrameDerivativeFunction =\r\n            std::bind( &Body::getCurrentRotationMatrixDerivativeToLocalFrame, centralBody );\r\n\r\n    std::function< Eigen::Matrix< double, 6, 1 >( ) > bodyStateFunction = std::bind( &Body::getState, bodyWithFlightConditions );\r\n    std::function< Eigen::Matrix< double, 6, 1 >( ) > centralBodyStateFunction = std::bind( &Body::getState, centralBody );\r\n\r\n    std::function< Eigen::Matrix< double, 6, 1 >( ) > relativeBodyFixedStateFunction =\r\n            std::bind( &ephemerides::transformRelativeStateToFrame< double >,\r\n                         bodyStateFunction, centralBodyStateFunction,\r\n                         rotationToFrameFunction,\r\n                         rotationMatrixToFrameDerivativeFunction );\r\n\r\n    // Create aerodynamic angles calculator and set in flight conditions.\r\n    std::shared_ptr< reference_frames::AerodynamicAngleCalculator > aerodynamicAngleCalculator =\r\n            std::make_shared< reference_frames::AerodynamicAngleCalculator >(\r\n                relativeBodyFixedStateFunction,\r\n                std::bind( &simulation_setup::Body::getCurrentRotationToGlobalFrame, centralBody ),\r\n                nameOfBodyExertingAcceleration, 1 );\r\n\r\n    return std::make_shared< aerodynamics::FlightConditions >(\r\n                centralBody->getShapeModel( ), aerodynamicAngleCalculator );\r\n\r\n}\r\n\r\n\r\n//! Function to set the angle of attack to trimmed conditions.\r\nstd::shared_ptr< aerodynamics::TrimOrientationCalculator > setTrimmedConditions(\r\n        const std::shared_ptr< aerodynamics::AtmosphericFlightConditions > flightConditions )\r\n{\r\n    // Create trim object.\r\n    std::shared_ptr< aerodynamics::TrimOrientationCalculator > trimOrientation =\r\n            std::make_shared< aerodynamics::TrimOrientationCalculator >(\r\n                flightConditions->getAerodynamicCoefficientInterface( ) );\r\n\r\n    // Create angle-of-attack function from trim object.\r\n    std::function< std::vector< double >( ) > untrimmedIndependentVariablesFunction =\r\n            std::bind( &aerodynamics::AtmosphericFlightConditions::getAerodynamicCoefficientIndependentVariables,\r\n                         flightConditions );\r\n    std::function< std::map< std::string, std::vector< double > >( ) > untrimmedControlSurfaceIndependentVariableFunction =\r\n            std::bind( &aerodynamics::AtmosphericFlightConditions::getControlSurfaceAerodynamicCoefficientIndependentVariables,\r\n                         flightConditions );\r\n\r\n    flightConditions->getAerodynamicAngleCalculator( )->setOrientationAngleFunctions(\r\n                std::bind( &aerodynamics::TrimOrientationCalculator::findTrimAngleOfAttackFromFunction, trimOrientation,\r\n                             untrimmedIndependentVariablesFunction, untrimmedControlSurfaceIndependentVariableFunction ) );\r\n\r\n    return trimOrientation;\r\n}\r\n\r\n//! Function to set the angle of attack to trimmed conditions.\r\nstd::shared_ptr< aerodynamics::TrimOrientationCalculator > setTrimmedConditions(\r\n        const std::shared_ptr< Body > bodyWithFlightConditions )\r\n{\r\n    if( std::dynamic_pointer_cast< aerodynamics::AtmosphericFlightConditions >(\r\n                bodyWithFlightConditions->getFlightConditions( ) ) == nullptr )\r\n    {\r\n        throw std::runtime_error( \"Error, body does not have FlightConditions when setting trim conditions.\" );\r\n    }\r\n\r\n    return setTrimmedConditions( std::dynamic_pointer_cast< aerodynamics::AtmosphericFlightConditions >(\r\n                                     bodyWithFlightConditions->getFlightConditions( ) ));\r\n}\r\n\r\n//! Function that must be called to link the AerodynamicGuidance object to the simulation\r\nvoid setGuidanceAnglesFunctions(\r\n        const std::shared_ptr< aerodynamics::AerodynamicGuidance > aerodynamicGuidance,\r\n        const std::shared_ptr< reference_frames::AerodynamicAngleCalculator > angleCalculator )\r\n{\r\n    angleCalculator->setOrientationAngleFunctions(\r\n                std::bind( &aerodynamics::AerodynamicGuidance::getCurrentAngleOfAttack, aerodynamicGuidance ),\r\n                std::bind( &aerodynamics::AerodynamicGuidance::getCurrentAngleOfSideslip, aerodynamicGuidance ),\r\n                std::bind( &aerodynamics::AerodynamicGuidance::getCurrentBankAngle, aerodynamicGuidance ),\r\n                std::bind( &aerodynamics::AerodynamicGuidance::updateGuidance, aerodynamicGuidance, std::placeholders::_1 ) );\r\n}\r\n\r\n//! Function that must be called to link the AerodynamicGuidance object to the simulation\r\nvoid setGuidanceAnglesFunctions(\r\n        const std::shared_ptr< aerodynamics::AerodynamicGuidance > aerodynamicGuidance,\r\n        const std::shared_ptr< simulation_setup::Body > bodyWithAngles )\r\n{\r\n    std::shared_ptr< reference_frames::DependentOrientationCalculator >  orientationCalculator =\r\n            bodyWithAngles->getDependentOrientationCalculator( );\r\n    std::shared_ptr< reference_frames::AerodynamicAngleCalculator > angleCalculator =\r\n            std::dynamic_pointer_cast< reference_frames::AerodynamicAngleCalculator >( orientationCalculator );\r\n\r\n    if( angleCalculator == nullptr )\r\n    {\r\n        throw std::runtime_error( \"Error, body does not have AerodynamicAngleCalculator when setting aerodynamic guidance\" );\r\n    }\r\n    else\r\n    {\r\n        setGuidanceAnglesFunctions( aerodynamicGuidance, angleCalculator );\r\n    }\r\n}\r\n\r\n} // namespace simulation_setup\r\n\r\n} // namespace tudat\r\n", "meta": {"hexsha": "b97a1d8e068b383d82e22ebf05232ddd22cd3cc0", "size": 12411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createFlightConditions.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/SimulationSetup/EnvironmentSetup/createFlightConditions.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/SimulationSetup/EnvironmentSetup/createFlightConditions.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": 49.4462151394, "max_line_length": 178, "alphanum_fraction": 0.6814922246, "num_tokens": 2600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478896, "lm_q2_score": 0.04023793888308902, "lm_q1q2_score": 0.01417187378055802}}
{"text": "// ======================================================================\n/*!\n * \\file\n * \\brief Implementation of namespace Imagine::NFmiColorReduce\n */\n// ======================================================================\n/*!\n * \\namespace Imagine::NFmiColorReduce\n *\n * \\brief Tools for reducing the number of colors in an image\n *\n * The main idea in reducing colors in an image is to make it\n * smaller so that the image can be downloaded faster. Typically\n * one sets a maximum number of allowed colors, but often a better\n * alternative might be to reduce colors until the error would become\n * too great.\n *\n */\n// ======================================================================\n\n#include \"NFmiColorReduce.h\"\n#include \"NFmiColorTools.h\"\n#include \"NFmiImage.h\"\n#include <macgyver/Exception.h>\n\n#include <boost/shared_ptr.hpp>\n\n#include <iomanip>\n#include <map>\n#include <vector>\n\n// std version not available in RHEL5, must use boost instead\n\n#include <boost/unordered_map.hpp>\nusing namespace std;\n\n// The actual public interfaces\n\nnamespace Imagine\n{\n// ======================================================================\n// Local subroutines\n// ======================================================================\n\nnamespace\n{\n//! Histogram data\nstruct ColorInfo\n{\n  ColorInfo(NFmiColorTools::Color c) : color(c), count(0), keeper(false) {}\n  NFmiColorTools::Color color;\n  int count;\n  bool keeper;\n\n  ColorInfo& operator++()\n  {\n    ++count;\n    return *this;\n  }\n  void keep() { keeper = true; }\n};\n\n//! Histogram information\ntypedef boost::unordered_map<NFmiColorTools::Color, ColorInfo> Counter;\n\n//! Internal histogram\ntypedef std::vector<ColorInfo> ColorHistogram;\n\n//! Colormap transformation\ntypedef map<NFmiColorTools::Color, NFmiColorTools::Color> ColorMap;\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Initialize the given gamma correction table\n */\n// ----------------------------------------------------------------------\n\nvoid init_gamma_table(vector<float>& theTable, bool& theFlag)\n{\n  try\n  {\n    const float gamma = 2.2f;\n    const float coeff = 255 / (pow(255.f, gamma));\n\n    for (int i = 0; i < 256; i++)\n      theTable[i] = coeff * pow(static_cast<float>(i), gamma);\n\n    theFlag = true;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Calculate the occurrance count of each color in the given image\n *\n * \\param theImage The image\n * \\return The colormap with occurrance counts\n */\n// ----------------------------------------------------------------------\n\nCounter calc_counts(const NFmiImage& theImage)\n{\n  try\n  {\n    // The default bucket size in SGI is 100, which is quite\n    // small for the typical number of colours we encounter\n    // in images.\n\n#ifdef UNIX\n    Counter counter(4096);\n#else  // #ifdef _MSC_VER  // MSVisualC++ k��nt�j�n mukana tulleessa hash_map -koodissa\n    // ei ollut buckettien m��r�n s��t� mahdollisuutta.\n    Counter counter;\n#endif\n\n    // Safety check\n\n    if (theImage.Height() * theImage.Width() == 0)\n      return counter;\n\n    // Insert the first color so that we can initialize the iterator cache\n    // Note that we insert count 0, but the first loop will fix the number\n\n    counter.insert(Counter::value_type(theImage(0, 0), ColorInfo(theImage(0, 0))));\n\n    Counter::iterator last1 = counter.begin();\n    Counter::iterator last2 = counter.begin();\n\n    for (int j = 0; j < theImage.Height(); j++)\n    {\n      for (int i = 0; i < theImage.Width(); i++)\n      {\n        NFmiColorTools::Color color = theImage(i, j);\n\n        if (last1->first == color)\n        {\n          ++last1->second;\n          // test if the color is the same in a 3x3 box and is hence a new color to be kept\n          if (!last1->second.keeper && i > 1 && j > 1)\n          {\n            // Note: theImage(i-1,j) is already known to have the same color (last1 points to it)\n            if (theImage(i - 2, j) == color && theImage(i, j - 1) == color &&\n                theImage(i - 1, j - 1) == color && theImage(i - 2, j - 1) == color &&\n                theImage(i, j - 2) == color && theImage(i - 1, j - 2) == color &&\n                theImage(i - 2, j - 2) == color)\n            {\n              last1->second.keep();\n            }\n          }\n        }\n        else if (last2->first == color)\n        {\n          ++last2->second;\n          swap(last1, last2);\n        }\n        else\n        {\n          pair<Counter::iterator, bool> result =\n              counter.insert(Counter::value_type(color, ColorInfo(color)));\n          last2 = last1;\n          last1 = result.first;\n          ++last1->second;\n        }\n      }\n    }\n    return counter;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief A near-tree of colors and their occurrance counts\n *\n * The idea is to feed in colors in the order of their popularity\n * and then use the near-tree maximum distance information\n * to group colors for color reduction.\n */\n// ----------------------------------------------------------------------\n\nclass ColorTree\n{\n public:\n  typedef NFmiColorTools::Color value_type;\n\n  ColorTree();\n  void insert(value_type theColor);\n  int size() const;\n  void clear();\n  bool empty() const;\n  value_type nearest(value_type theColor);\n\n  static float distance(value_type theColor1, value_type theColor2);\n\n private:\n  ColorTree(const ColorTree& theTree);\n  ColorTree& operator=(const ColorTree& theTree);\n\n  bool nearest(value_type theColor, value_type& theNearest, float& theRadius) const;\n\n  boost::shared_ptr<value_type> itsLeftObject;\n  boost::shared_ptr<value_type> itsRightObject;\n  float itsMaxLeft;\n  float itsMaxRight;\n  boost::shared_ptr<ColorTree> itsLeftBranch;\n  boost::shared_ptr<ColorTree> itsRightBranch;\n  int itsCount;\n};\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Default constructor\n */\n// ----------------------------------------------------------------------\n\nColorTree::ColorTree()\n    : itsLeftObject(),\n      itsRightObject(),\n      itsMaxLeft(-1.0),\n      itsMaxRight(-1.0),\n      itsLeftBranch(),\n      itsRightBranch(),\n      itsCount(0)\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Euclidian distance between two colors\n *\n * See http://www.compuphase.com/cmetric.htm\n */\n// ----------------------------------------------------------------------\n\nfloat ColorTree::distance(ColorTree::value_type theColor1, ColorTree::value_type theColor2)\n{\n  try\n  {\n    static vector<float> gamma(256, 0);\n    static bool initialized = false;\n\n    if (!initialized)\n      init_gamma_table(gamma, initialized);\n\n    const float r =\n        (gamma[NFmiColorTools::GetRed(theColor1)] - gamma[NFmiColorTools::GetRed(theColor2)]);\n    const float g =\n        (gamma[NFmiColorTools::GetGreen(theColor1)] - gamma[NFmiColorTools::GetGreen(theColor2)]);\n    const float b =\n        (gamma[NFmiColorTools::GetBlue(theColor1)] - gamma[NFmiColorTools::GetBlue(theColor2)]);\n    const float a = static_cast<float>(NFmiColorTools::GetAlpha(theColor1) -\n                                       NFmiColorTools::GetAlpha(theColor2));\n\n    return sqrt(3.0f * r * r + 4.0f * g * g + 2.0f * b * b + a * a);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Test whether the tree is empty\n */\n// ----------------------------------------------------------------------\n\nbool ColorTree::empty() const\n{\n  try\n  {\n    return (itsLeftObject.get() == 0);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return number of colours in the tree.\n */\n// ----------------------------------------------------------------------\n\nint ColorTree::size() const\n{\n  return itsCount;\n}\n\nvoid ColorTree::clear()\n{\n  try\n  {\n    itsRightBranch.reset(new ColorTree);\n    itsLeftBranch.reset(new ColorTree);\n    itsCount = 0;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Insert a color into the color tree\n *\n * Algorithm:\n *\n *  -# If left position is free, put the color there\n *  -# If right position is free, put the color there\n *  -# Insert into subtree whose root is closer to the color\n */\n// ----------------------------------------------------------------------\n\nvoid ColorTree::insert(ColorTree::value_type theColor)\n{\n  try\n  {\n    if (itsLeftObject.get() == 0)\n      itsLeftObject.reset(new value_type(theColor));\n\n    else if (itsRightObject.get() == 0)\n      itsRightObject.reset(new value_type(theColor));\n\n    else\n    {\n      const float dist_left = distance(theColor, *itsLeftObject);\n      const float dist_right = distance(theColor, *itsRightObject);\n\n      if (dist_left > dist_right)\n      {\n        if (itsRightBranch.get() == 0)\n          itsRightBranch.reset(new ColorTree);\n\n        // note that constructor sets itsMaxRight to be negative\n\n        itsMaxRight = max(itsMaxRight, dist_right);\n\n        itsRightBranch->insert(theColor);\n        itsCount++;\n      }\n      else\n      {\n        if (itsLeftBranch.get() == 0)\n          itsLeftBranch.reset(new ColorTree);\n\n        // note that constructor sets itsMaxLeft to be negative\n\n        itsMaxLeft = max(itsMaxLeft, dist_left);\n\n        itsLeftBranch->insert(theColor);\n        itsCount++;\n      }\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Find the nearest color\n *\n * \\param theColor The color for which to find the nearest color\n * \\return The nearest color\n */\n// ----------------------------------------------------------------------\n\nColorTree::value_type ColorTree::nearest(ColorTree::value_type theColor)\n{\n  try\n  {\n    value_type bestcolor;\n    float radius = -1;\n    if (!nearest(theColor, bestcolor, radius))\n      throw Fmi::Exception(BCP, \"Invalid use of color reduction tables\");\n\n    return bestcolor;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Recursively find nearest color\n *\n * This is only intended to be used by the public nearest method\n */\n// ----------------------------------------------------------------------\n\nbool ColorTree::nearest(ColorTree::value_type theColor,\n                        ColorTree::value_type& theNearest,\n                        float& theRadius) const\n{\n  try\n  {\n    float left_dist = -1;\n    float right_dist = -1;\n    bool found = false;\n\n    // first test each of the left and right positions to see if\n    // one holds a color nearer than the nearest so far discovered\n\n    if (itsLeftObject.get() != 0)\n    {\n      left_dist = distance(theColor, *itsLeftObject);\n      if (theRadius < 0 || left_dist <= theRadius)\n      {\n        theRadius = left_dist;\n        theNearest = *itsLeftObject;\n        found = true;\n      }\n    }\n\n    if (itsRightObject.get() != 0)\n    {\n      right_dist = distance(theColor, *itsRightObject);\n      if (theRadius < 0 || right_dist <= theRadius)\n      {\n        theRadius = right_dist;\n        theNearest = *itsRightObject;\n        found = true;\n      }\n    }\n\n    // if theRadius is negative at this point, the tree is empty\n    // on the other hand, if the radius is zero, we found a match\n\n    if (theRadius <= 0)\n      return found;\n\n    // Now we test to see if the branches below might hold an object\n    // nearer than the best so far found. The triangle rule is used\n    // to test whether it's even necessary to descend. We may be\n    // able to skip skanning both branches if we can guess which\n    // branch is most likely to contain the nearest match. We simply\n    // guess, that it is the branch which is nearer. Note that\n    // the first and third if-clauses are mutually exclusive,\n    // hence only parts 1-2 or 2-3 will be executed.\n\n    const bool left_closer = (left_dist < right_dist);\n\n    if (!left_closer && (itsRightBranch.get() != 0) && ((theRadius + itsMaxRight) >= right_dist))\n      found |= itsRightBranch->nearest(theColor, theNearest, theRadius);\n\n    if ((itsLeftBranch.get() != 0) && ((theRadius + itsMaxLeft) >= left_dist))\n      found |= itsLeftBranch->nearest(theColor, theNearest, theRadius);\n\n    if (left_closer && (itsRightBranch.get() != 0) && ((theRadius + itsMaxRight) >= right_dist))\n      found |= itsRightBranch->nearest(theColor, theNearest, theRadius);\n\n    return found;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Perform color replacement\n */\n// ----------------------------------------------------------------------\n\nvoid replace_colors(NFmiImage& theImage, const ColorMap& theMap)\n{\n  try\n  {\n    boost::unordered_map<NFmiColorTools::Color, NFmiColorTools::Color> colormap(256);\n\n    for (ColorMap::const_iterator it = theMap.begin(); it != theMap.end(); ++it)\n    {\n      colormap[it->first] = it->second;\n    }\n\n    NFmiColorTools::Color last_color1 = NFmiColorTools::NoColor;\n    NFmiColorTools::Color last_choice1 = NFmiColorTools::NoColor;\n    NFmiColorTools::Color last_color2 = NFmiColorTools::NoColor;\n    NFmiColorTools::Color last_choice2 = NFmiColorTools::NoColor;\n\n    for (int j = 0; j < theImage.Height(); j++)\n    {\n      for (int i = 0; i < theImage.Width(); i++)\n      {\n        if (theImage(i, j) == last_color1)\n          theImage(i, j) = last_choice1;\n        else if (theImage(i, j) == last_color2)\n        {\n          theImage(i, j) = last_choice2;\n          swap(last_color1, last_color2);\n          swap(last_choice1, last_choice2);\n        }\n        else\n        {\n          last_color2 = last_color1;\n          last_choice2 = last_choice1;\n          last_color1 = theImage(i, j);\n          last_choice1 = colormap[theImage(i, j)];\n          theImage(i, j) = last_choice1;\n        }\n      }\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Build a color tree and a colormap\n */\n// ----------------------------------------------------------------------\n\nvoid build_tree(const NFmiImage& theImage,\n                const ColorHistogram& theHistogram,\n                ColorTree& theTree,\n                ColorMap& theMap,\n                float theQuality)\n{\n  try\n  {\n    const float ratio = static_cast<float>(1.0 / (theImage.Width() * theImage.Height()));\n    const float factor = -theQuality / log(10.0f);\n\n    for (ColorHistogram::const_iterator it = theHistogram.begin(); it != theHistogram.end(); ++it)\n    {\n      if (theTree.empty() || it->keeper)\n      {\n        theTree.insert(it->color);\n        theMap.insert(ColorMap::value_type(it->color, it->color));\n      }\n      else\n      {\n        NFmiColorTools::Color nearest = theTree.nearest(it->color);\n        float dist = theTree.distance(nearest, it->color);\n\n        float limit = factor * log(ratio * it->count);\n\n        if (dist < limit)\n        {\n          theMap.insert(ColorMap::value_type(it->color, nearest));\n        }\n        else\n        {\n          theTree.insert(it->color);\n          theMap.insert(ColorMap::value_type(it->color, it->color));\n        }\n      }\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Build a color tree and a colormap\n */\n// ----------------------------------------------------------------------\n\nvoid build_tree(const NFmiImage& theImage,\n                const ColorHistogram& theHistogram,\n                ColorTree& theTree,\n                ColorMap& theMap,\n                float theQuality,\n                int theMaxCount,\n                float theErrorFactor)\n{\n  try\n  {\n    const float ratio = static_cast<float>(1.0 / (theImage.Width() * theImage.Height()));\n\n    bool done = false;\n    while (!done)\n    {\n      done = true;\n      const float factor = -theQuality / log(10.0f);\n\n      for (ColorHistogram::const_iterator it = theHistogram.begin(); it != theHistogram.end(); ++it)\n      {\n        if (theTree.empty() || it->keeper)\n        {\n          theTree.insert(it->color);\n          theMap.insert(ColorMap::value_type(it->color, it->color));\n        }\n        else\n        {\n          NFmiColorTools::Color nearest = theTree.nearest(it->color);\n          float dist = theTree.distance(nearest, it->color);\n\n          const float limit = factor * log(ratio * it->count);\n          if (dist < limit)\n            theMap.insert(ColorMap::value_type(it->color, nearest));\n          else if (theTree.size() < theMaxCount)\n          {\n            theTree.insert(it->color);\n            theMap.insert(ColorMap::value_type(it->color, it->color));\n          }\n          else\n          {\n            theTree.clear();\n            theMap.clear();\n            done = false;\n            theQuality *= theErrorFactor;\n            break;\n          }\n        }\n      }\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nbool colorcmp(const ColorInfo& c1, const ColorInfo& c2)\n{\n  try\n  {\n    if (c1.keeper == c2.keeper)\n      return (c2.count < c1.count);\n\n    return c1.keeper;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Calculate the histogram for color reduction\n *\n * \\param theImage The image\n * \\return The histogram object\n */\n// ----------------------------------------------------------------------\n\nconst ColorHistogram CalcColorHistogram(const NFmiImage& theImage)\n{\n  try\n  {\n    Counter counter = calc_counts(theImage);\n\n    ColorHistogram histogram;\n\n    Counter::const_iterator end = counter.end();\n    for (Counter::const_iterator it = counter.begin(); it != end; ++it)\n    {\n      histogram.push_back(it->second);\n    }\n    sort(histogram.begin(), histogram.end(), &colorcmp);\n\n    return histogram;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace\n\n// ======================================================================\n// The actual public interfaces\n// ======================================================================\n\nnamespace NFmiColorReduce\n{\n// ----------------------------------------------------------------------\n/*!\n * \\brief Calculate the occurrance count of each color in the given image\n *\n * \\param theImage The image\n * \\return The histogram object\n */\n// ----------------------------------------------------------------------\n\nconst Histogram CalcHistogram(const NFmiImage& theImage)\n{\n  try\n  {\n    Counter counter = calc_counts(theImage);\n\n    NFmiColorReduce::Histogram histogram;\n\n    Counter::const_iterator end = counter.end();\n    for (Counter::const_iterator it = counter.begin(); it != end; ++it)\n    {\n      histogram.insert(NFmiColorReduce::Histogram::value_type(it->second.count, it->first));\n    }\n\n    return histogram;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Reduce colors from the image adaptively\n *\n * Algorithm:\n *\n *  -# Calculate the histogram\n *  -# In order of popularity, feed the colors into a color tree\n *     which discards colors which are close enough to a color\n *     chosen earlier.\n *  -# For each color, ask the color tree which is the nearest\n *     color for it.\n *  -# Replace the original colors with the colors found in the previous\n *     step.\n *\n * Note that this is very very close to the common popularity based\n * algorithm. However, the twist is that we have an adaptive error\n * criteria, we are not aiming for a fixed number of colors. Hence\n * we get the benefit of the speed of the popularity based algorithm\n * but will never get too big errors.\n *\n * An algorithm which might produce better quality results would\n * be to aim for color diversity as follows:\n *\n *  -# Perform the insertion phase as in algorithm 1, but\n *     with the error limit doubled.\n *  -# Perform the insertion phase as in algorithm 1, now\n *     with a normal error limit\n *  -# Continue by asking the nearest color for all colors\n *\n * However, we require best possible speed and thus do everything\n * in a single pass. What we could do is to find a way to quickly\n * reorder the histogram to produce more diversity in the colors.\n *\n * \\param theImage The image to modify\n * \\param theQuality The quality ratio, 10 = good, 20 = poor and so on\n */\n// ----------------------------------------------------------------------\n\nvoid AdaptiveReduce(NFmiImage& theImage, float theQuality)\n{\n  try\n  {\n    using namespace Imagine::NFmiColorTools;\n\n    // A sanity check on the maximum error\n\n    if (theQuality < 1)\n      return;\n\n    // Calculate the histogram\n\n    ColorHistogram histogram = CalcColorHistogram(theImage);\n\n    // Select the colors\n\n    ColorTree tree;\n    ColorMap colormap;\n\n    build_tree(theImage, histogram, tree, colormap, theQuality);\n\n    // Now perform the replacements. Since we expect to encounter\n    // sequences of color, we speed of the searches by caching\n    // the last replacement.\n\n    replace_colors(theImage, colormap);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nvoid AdaptiveReduce(NFmiImage& theImage, float theQuality, int theMaxColors, float theErrorFactor)\n{\n  try\n  {\n    using namespace Imagine::NFmiColorTools;\n\n    if (theQuality < 1)\n      throw Fmi::Exception(BCP, \"Quality was too low.\");\n\n    // Calculate the histogram\n\n    ColorHistogram histogram = CalcColorHistogram(theImage);\n\n    // Select the colors\n\n    ColorTree tree;\n    ColorMap colormap;\n\n    build_tree(theImage, histogram, tree, colormap, theQuality, theMaxColors, theErrorFactor);\n\n    // Now perform the replacements. Since we expect to encounter\n    // sequences of color, we speed of the searches by caching\n    // the last replacement.\n\n    replace_colors(theImage, colormap);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n}  // namespace NFmiColorReduce\n}  // namespace Imagine\n\n// ======================================================================\n", "meta": {"hexsha": "821863f0914a3cdcb9fc5ca1f17cc74f8c4bf5ec", "size": 22902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imagine/NFmiColorReduce.cpp", "max_stars_repo_name": "fmidev/smartmet-library-imagine", "max_stars_repo_head_hexsha": "365dfcd940075b63b4fd2606256820f054bed00a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "imagine/NFmiColorReduce.cpp", "max_issues_repo_name": "fmidev/smartmet-library-imagine", "max_issues_repo_head_hexsha": "365dfcd940075b63b4fd2606256820f054bed00a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-09-20T04:40:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-20T07:24:51.000Z", "max_forks_repo_path": "imagine/NFmiColorReduce.cpp", "max_forks_repo_name": "fmidev/smartmet-library-imagine", "max_forks_repo_head_hexsha": "365dfcd940075b63b4fd2606256820f054bed00a", "max_forks_repo_licenses": ["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.5927710843, "max_line_length": 100, "alphanum_fraction": 0.546939132, "num_tokens": 5217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.03258974276938117, "lm_q1q2_score": 0.014143344304638301}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include <numpy/ndarrayobject.h>\n#include \"boost/tuple/tuple.hpp\"\n#include \"boost/python/object.hpp\"\n#include <../include/API.h>\n\nnamespace bpn = boost::python::numpy;\nnamespace bp =  boost::python;\n\ntypedef boost::tuple< std::vector< std::vector<uint32_t> >, std::vector<uint32_t> > Custom_tuple;\n\nstruct VecToArray\n{//converts a vector<uint32_t> to a numpy array\n    static PyObject * convert(const std::vector<uint32_t> & vec) {\n    npy_intp dims = vec.size();\n    PyObject * obj = PyArray_SimpleNew(1, &dims, NPY_UINT32);\n    void * arr_data = PyArray_DATA((PyArrayObject*)obj);\n    memcpy(arr_data, &vec[0], dims * sizeof(uint32_t));\n    return obj;\n    }\n};\n\nstruct FloatVecToArray\n{//converts a vector<uint32_t> to a numpy array\n    static PyObject * convert(const std::vector<float> & vec, uint32_t n_ver, uint32_t n_obs) {\n    npy_intp dims[2];\n    dims[0] = (npy_intp)n_ver;\n    dims[1] = (npy_intp)n_obs;\n    PyObject * obj = PyArray_SimpleNew(2, dims, NPY_FLOAT32);\n    void * arr_data = PyArray_DATA((PyArrayObject*)obj);\n    memcpy(arr_data, &vec[0], n_ver * n_obs * sizeof(float));\n    return obj;\n    }\n};\n\ntemplate<class T>\nstruct VecvecToList\n{//converts a vector< vector<T> > to a list\n        static PyObject* convert(const std::vector< std::vector<T> > & vecvec)\n    {\n        boost::python::list* pylistlist = new boost::python::list();\n        for(size_t i = 0; i < vecvec.size(); i++)\n        {\n            boost::python::list* pylist = new boost::python::list();\n            for(size_t j = 0; j < vecvec[i].size(); j++)\n            {\n                pylist->append(vecvec[i][j]);\n            }\n            pylistlist->append((pylist, pylist[0]));\n        }\n        return pylistlist->ptr();\n    }\n};\n\nstruct to_py_tuple\n{//converts output to a python tuple\n    static PyObject* convert(const Custom_tuple& c_tuple){\n        bp::list values;\n        //add all c_tuple items to \"values\" list\n\n        PyObject * vecvec_pyo = VecvecToList<uint32_t>::convert(c_tuple.get<0>());\n        PyObject * vec_pyo = VecToArray::convert(c_tuple.get<1>());\n\n        values.append(bp::handle<>(bp::borrowed(vecvec_pyo)));\n        values.append(bp::handle<>(bp::borrowed(vec_pyo)));\n\n        return bp::incref( bp::tuple( values ).ptr() );\n    }\n};\n\nPyObject * cutpursuit_seg(const bpn::ndarray & obs, const bpn::ndarray & source, const bpn::ndarray & target,const bpn::ndarray & edge_weight,  float lambda)\n{//read data and run the L0-cut pursuit partition algorithm\n    const uint32_t n_ver = bp::len(obs);\n    const uint32_t n_edg = bp::len(source);\n    const uint32_t n_obs = bp::len(obs[0]);\n    const float * obs_data = reinterpret_cast<float*>(obs.get_data());\n    const uint32_t * source_data = reinterpret_cast<uint32_t*>(source.get_data());\n    const uint32_t * target_data = reinterpret_cast<uint32_t*>(target.get_data());\n    const float * edge_weight_data = reinterpret_cast<float*>(edge_weight.get_data());\n//    float solution [n_ver * n_obs];\n    std::vector<float> solution(n_ver * n_obs, 0.0f);\n    std::vector<float> node_weight(n_ver, 1.0f);\n    std::vector<uint32_t> in_component(n_ver,0);\n    std::vector< std::vector<uint32_t> > components(1,std::vector<uint32_t>(1,0.f));\n    CP::cut_pursuit<float>(n_ver, n_edg, n_obs, obs_data, source_data, target_data, edge_weight_data, &node_weight[0]\n             , solution.data(), in_component, components, lambda, 1.f, 2.f, 2.f);\n//    delete[]solution\n    return to_py_tuple::convert(Custom_tuple(components, in_component));\n}\n\nPyObject * cutpursuit_reg(const bpn::ndarray & obs, const bpn::ndarray & source, const bpn::ndarray & target,const bpn::ndarray & edge_weight,  float lambda)\n{//read data and run the L0-cut pursuit partition algorithm\n    const uint32_t n_ver = bp::len(obs);\n    const uint32_t n_edg = bp::len(source);\n    const uint32_t n_obs = bp::len(obs[0]);\n    const float * obs_data = reinterpret_cast<float*>(obs.get_data());\n    const uint32_t * source_data = reinterpret_cast<uint32_t*>(source.get_data());\n    const uint32_t * target_data = reinterpret_cast<uint32_t*>(target.get_data());\n    const float * edge_weight_data = reinterpret_cast<float*>(edge_weight.get_data());\n//    float solution [n_ver * n_obs];\n    std::cout << n_ver << \" \" << n_obs << std::endl;\n    std::vector<float> solution(n_ver * n_obs, 0.0f);\n    std::vector<float> node_weight(n_ver, 1.0f);\n    std::vector< std::vector<uint32_t> > components(1,std::vector<uint32_t>(1,0.f));\n    CP::cut_pursuit<float>(n_ver, n_edg, n_obs, obs_data, source_data, target_data, edge_weight_data, &node_weight[0]\n             , solution.data(), lambda, 1.f, 2.f, 2.f);\n//    delete[]solution\n    return FloatVecToArray::convert(solution, n_ver, n_obs);\n}\n\nBOOST_PYTHON_MODULE(libcp)\n{\n    _import_array();\n    Py_Initialize();\n    bpn::initialize();\n    bp::to_python_converter< Custom_tuple, to_py_tuple>();\n    def(\"cutpursuit\", cutpursuit_seg);\n    def(\"cutpursuit_reg\", cutpursuit_reg);\n}\n\n", "meta": {"hexsha": "5043784ed5464aefd0e38c5ba5561a56175f7de9", "size": 5070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cutpursuit.cpp", "max_stars_repo_name": "bw4sz/cut-pursuit", "max_stars_repo_head_hexsha": "e95df520a4e55c2bc8b96062d03e212890e4df98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cutpursuit.cpp", "max_issues_repo_name": "bw4sz/cut-pursuit", "max_issues_repo_head_hexsha": "e95df520a4e55c2bc8b96062d03e212890e4df98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cutpursuit.cpp", "max_forks_repo_name": "bw4sz/cut-pursuit", "max_forks_repo_head_hexsha": "e95df520a4e55c2bc8b96062d03e212890e4df98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-18T14:05:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-18T14:05:50.000Z", "avg_line_length": 40.56, "max_line_length": 157, "alphanum_fraction": 0.66765286, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.030675800602966617, "lm_q1q2_score": 0.014142058796806467}}
{"text": "#include <cstring>\n#include <fstream>\n#include <unistd.h>\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\nCtxt FHE_Add(Ctxt Ea, Ctxt Eb)\n{\n    Ctxt ctSum = Ea;\n    ctSum += Eb;\n    return ctSum;\n}\n\nint main(int argc, char *argv[]) {\n    ArgMapping amap;\n\n    string owner = \"owner\";\n    string firstCtxtFileName = \"data/candidate/owner-0.txt\";\n    string secondCtxtFileName = \"data/candidate/owner-1.txt\";\n    string resultCtxtFileName = \"data/owner-result.txt\";\n\n    amap.arg(\"o\", owner, \"owner's address\");\n    amap.arg(\"f\", firstCtxtFileName, \"first Ctxt file's name\");\n    amap.arg(\"s\", secondCtxtFileName, \"second Ctxt file's name\");\n    amap.arg(\"r\", resultCtxtFileName, \"result Ctxt file's name\");\n    amap.parse(argc, argv);\n\n    // file names\n    const string secretKeyBinaryFileName = \"data/secretKey/\" + owner + \".bin\";\n\n    ifstream secretBinFile(secretKeyBinaryFileName.c_str(), ios::binary);\n    ifstream firstCtxtFile(firstCtxtFileName.c_str(), ios::binary);\n    ifstream secondCtxtFile(secondCtxtFileName.c_str(), ios::binary);\n    ofstream resultCtxtFile(resultCtxtFileName.c_str(), ios::binary);\n\n    // check open file\n    assert(secretBinFile.is_open());\n    assert(firstCtxtFile.is_open());\n    assert(secondCtxtFile.is_open());\n    assert(resultCtxtFile.is_open());\n\n    // Read in context,\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    secretBinFile.close();\n\n    cout << \"read PublicKey & SecretKey successful.\\n\" << flush;\n\n    // ready to add two Ctxts\n    Ctxt firstCtxt(*pubKey);\n    Ctxt secondCtxt(*pubKey);\n\n    // get Ctxt to file\n    firstCtxtFile >> firstCtxt;\n    secondCtxtFile >> secondCtxt;\n\n    // add two Ctxt\n    Ctxt resultCtxt = FHE_Add(firstCtxt, secondCtxt);\n\n    // show result\n    ZZX ptSum;\n    secKey->Decrypt(ptSum, resultCtxt);\n    cout << \"result : \" << ptSum <<endl;\n\n    // save resultCtxt\n    resultCtxtFile << resultCtxt << endl;\n}", "meta": {"hexsha": "b1c6bb264e5c409cc6208819bc7c1bb420a96243", "size": 2357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/addPolyTest.cpp", "max_stars_repo_name": "HanBae/voting-HElib-script", "max_stars_repo_head_hexsha": "bfd88ef6fc42d3a1b8f5383d0db4f36ca24a515a", "max_stars_repo_licenses": ["MIT"], "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/addPolyTest.cpp", "max_issues_repo_name": "HanBae/voting-HElib-script", "max_issues_repo_head_hexsha": "bfd88ef6fc42d3a1b8f5383d0db4f36ca24a515a", "max_issues_repo_licenses": ["MIT"], "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/addPolyTest.cpp", "max_forks_repo_name": "HanBae/voting-HElib-script", "max_forks_repo_head_hexsha": "bfd88ef6fc42d3a1b8f5383d0db4f36ca24a515a", "max_forks_repo_licenses": ["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.743902439, "max_line_length": 80, "alphanum_fraction": 0.6792532881, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.02843603006016763, "lm_q1q2_score": 0.01410693904749874}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_PairProductionPhotoatomicReaction.hpp\n//! \\author Alex Robinson\n//! \\brief  The pair production photoatomic reaction class decl.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_PAIR_PRODUCTION_PHOTOATOMIC_REACTION_HPP\n#define MONTE_CARLO_PAIR_PRODUCTION_PHOTOATOMIC_REACTION_HPP\n\n// Boost Includes\n#include <boost/function.hpp>\n\n// Trilinos Includes\n#include <Teuchos_RCP.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_StandardPhotoatomicReaction.hpp\"\n\nnamespace MonteCarlo{\n\n//! The pair production photoatomic reaction class\ntemplate<typename InterpPolicy, bool processed_cross_section = true>\nclass PairProductionPhotoatomicReaction : public StandardPhotoatomicReaction<InterpPolicy,processed_cross_section>\n{\n\npublic:\n\n  //! Basic constructor\n  PairProductionPhotoatomicReaction(\n\t\tconst Teuchos::ArrayRCP<const double>& incoming_energy_grid,\n\t\tconst Teuchos::ArrayRCP<const double>& cross_section,\n\t\tconst unsigned threshold_energy_index,\n\t\tconst bool use_detailed_electron_emission_physics = true );\n\n  //! Constructor\n  PairProductionPhotoatomicReaction(\n       const Teuchos::ArrayRCP<const double>& incoming_energy_grid,\n       const Teuchos::ArrayRCP<const double>& cross_section,\n       const unsigned threshold_energy_index,\n       const Teuchos::RCP<const Utility::HashBasedGridSearcher>& grid_searcher,\n       const bool use_detailed_electron_emission_physics = true );\n\n  //! Destructor\n  ~PairProductionPhotoatomicReaction()\n  { /* ... */ }\n\n  //! Return the number of photons emitted from the rxn at the given energy\n  unsigned getNumberOfEmittedPhotons( const double energy ) const;\n\n  //! Return the reaction type\n  PhotoatomicReactionType getReactionType() const;\n\n  //! Simulate the reaction\n  void react( PhotonState& photon, \n\t      ParticleBank& bank,\n\t      SubshellType& shell_of_interaction ) const;\n    \nprivate:\n\n  // The basic pair production model\n  static void basicInteraction( PhotonState& photon,\n\t\t\t\tParticleBank& bank );\n  \n  // The detailed pair production model\n  static void detailedInteraction( PhotonState& photon,\n\t\t\t\t   ParticleBank& bank );\n\n  // The number of photons emitted from pair production using simple model\n  static unsigned basicInteractionPhotonEmission();\n\n  // The number of photons emitted from pair production using detailed model\n  static unsigned detailedInteractionPhotonEmission();\n  \n  // The pair production model\n  boost::function<void (PhotonState&,ParticleBank&)> d_interaction_model;\n\n  // The number of photons emitted from the interaction (model dependent)\n  boost::function<unsigned (void)> d_interaction_model_emission;\n};\n\n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes.\n//---------------------------------------------------------------------------//\n\n#include \"MonteCarlo_PairProductionPhotoatomicReaction_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end MONTE_CARLO_PAIR_PRODUCTION_PHOTOATOMIC_REACTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_PairProductionPhotoatomicReaction.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "c6e31f1ba7a0d076aab956cb882bf1724503d3d6", "size": 3407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_PairProductionPhotoatomicReaction.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_PairProductionPhotoatomicReaction.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_PairProductionPhotoatomicReaction.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": 34.7653061224, "max_line_length": 114, "alphanum_fraction": 0.6539477546, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.038466194774036656, "lm_q1q2_score": 0.014101312199530942}}
{"text": "/*\n * MIT License\n *\n * Alexandria.org\n *\n * Copyright (c) 2021 Josef Cullhed, <info@alexandria.org>, et al.\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 \"Counter.h\"\n\n#include <iostream>\n#include <future>\n#include <vector>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <boost/filesystem.hpp>\n#include \"config.h\"\n#include \"parser/URL.h\"\n#include \"link/Link.h\"\n#include \"link/LinkCounter.h\"\n#include \"transfer/Transfer.h\"\n#include \"algorithm/hyper_log_log.h\"\n#include \"algorithm/algorithm.h\"\n#include \"urlstore/UrlStore.h\"\n\nusing namespace std;\n\nnamespace Tools {\n\n\talgorithm::hyper_log_log<size_t> *count_urls(const vector<string> &warc_paths) {\n\n\t\talgorithm::hyper_log_log<size_t> *counter = new algorithm::hyper_log_log<size_t>();\n\n\t\tsize_t idx = 0;\n\t\tfor (const string &warc_path : warc_paths) {\n\t\t\tifstream infile(warc_path);\n\t\t\tboost::iostreams::filtering_istream decompress_stream;\n\t\t\tdecompress_stream.push(boost::iostreams::gzip_decompressor());\n\t\t\tdecompress_stream.push(infile);\n\n\t\t\tstring line;\n\t\t\twhile (getline(decompress_stream, line)) {\n\t\t\t\tconst URL url(line.substr(0, line.find(\"\\t\")));\n\t\t\t\tcounter->insert_hash(url.hash());\n\t\t\t}\n\n\t\t\tif (idx % 100 == 0) {\n\t\t\t\tcout << warc_path << \" done \" << idx << \"/\" << warc_paths.size() << endl;\n\t\t\t} \n\n\t\t\tidx++;\n\t\t}\n\n\t\treturn counter;\n\t}\n\n\talgorithm::hyper_log_log<size_t> *count_links(const vector<string> &warc_paths) {\n\n\t\talgorithm::hyper_log_log<size_t> *counter = new algorithm::hyper_log_log<size_t>();\n\n\t\tsize_t idx = 0;\n\t\tfor (const string &warc_path : warc_paths) {\n\t\t\tifstream infile(warc_path);\n\t\t\tboost::iostreams::filtering_istream decompress_stream;\n\t\t\tdecompress_stream.push(boost::iostreams::gzip_decompressor());\n\t\t\tdecompress_stream.push(infile);\n\n\t\t\tstring line;\n\t\t\twhile (getline(decompress_stream, line)) {\n\t\t\t\tconst Link::Link link(line);\n\t\t\t\tcounter->insert_hash(link.target_url().hash());\n\t\t\t}\n\n\t\t\tif (idx % 100 == 0) {\n\t\t\t\tcout << warc_path << \" done \" << idx << \"/\" << warc_paths.size() << endl;\n\t\t\t} \n\n\t\t\tidx++;\n\t\t}\n\n\t\treturn counter;\n\t}\n\n\tvoid run_counter() {\n\n\t\tconst size_t num_threads = 12;\n\n\t\tvector<string> files;\n\t\tvector<string> link_files;\n\n\t\tfor (const string &batch : Config::batches) {\n\n\t\t\tconst string file_name = string(\"/mnt/crawl-data/\") + batch + \"/warc.paths.gz\";\n\n\t\t\tifstream infile(file_name);\n\n\t\t\tboost::iostreams::filtering_istream decompress_stream;\n\t\t\tdecompress_stream.push(boost::iostreams::gzip_decompressor());\n\t\t\tdecompress_stream.push(infile);\n\n\t\t\tstring line;\n\t\t\twhile (getline(decompress_stream, line)) {\n\t\t\t\tstring warc_path = string(\"/mnt/\") + line;\n\t\t\t\tconst size_t pos = warc_path.find(\".warc.gz\");\n\t\t\t\tif (pos != string::npos) {\n\t\t\t\t\twarc_path.replace(pos, 8, \".gz\");\n\t\t\t\t}\n\n\t\t\t\tfiles.push_back(warc_path);\n\t\t\t}\n\t\t}\n\n\t\tfor (const string &batch : Config::link_batches) {\n\n\t\t\tconst string file_name = string(\"/mnt/crawl-data/\") + batch + \"/warc.paths.gz\";\n\n\t\t\tifstream infile(file_name);\n\n\t\t\tboost::iostreams::filtering_istream decompress_stream;\n\t\t\tdecompress_stream.push(boost::iostreams::gzip_decompressor());\n\t\t\tdecompress_stream.push(infile);\n\n\t\t\tstring line;\n\t\t\twhile (getline(decompress_stream, line)) {\n\t\t\t\tstring warc_path = string(\"/mnt/\") + line;\n\t\t\t\tconst size_t pos = warc_path.find(\".warc.gz\");\n\n\t\t\t\tif (pos != string::npos) {\n\t\t\t\t\twarc_path.replace(pos, 8, \".links.gz\");\n\t\t\t\t}\n\n\t\t\t\tlink_files.push_back(warc_path);\n\t\t\t}\n\t\t}\n\n\t\tvector<vector<string>> thread_input;\n\t\talgorithm::vector_chunk(files, ceil((double)files.size() / num_threads), thread_input);\n\n\t\tvector<vector<string>> link_thread_input;\n\t\talgorithm::vector_chunk(link_files, ceil((double)link_files.size() / num_threads), link_thread_input);\n\n\t\tmutex write_file_mutex;\n\n\t\t/*\n\t\tRun url counters\n\t\t*/\n\t\tvector<future<algorithm::hyper_log_log<size_t> *>> futures;\n\t\tfor (size_t i = 0; i < num_threads && i < thread_input.size(); i++) {\n\t\t\tfutures.emplace_back(std::async(launch::async, count_urls, thread_input[i]));\n\t\t}\n\n\t\talgorithm::hyper_log_log<size_t> url_counter;\n\t\tfor (auto &future : futures) {\n\t\t\talgorithm::hyper_log_log<size_t> *result = future.get();\n\t\t\turl_counter += *(result);\n\t\t\tdelete result;\n\t\t}\n\n\t\tfutures.clear();\n\n\t\t/*\n\t\tRun link counters\n\t\t*/\n\t\tfor (size_t i = 0; i < num_threads && i < link_thread_input.size(); i++) {\n\t\t\tfutures.emplace_back(std::async(launch::async, count_links, link_thread_input[i]));\n\t\t}\n\n\t\talgorithm::hyper_log_log<size_t> link_counter;\n\t\tfor (auto &future : futures) {\n\t\t\talgorithm::hyper_log_log<size_t> *result = future.get();\n\t\t\tlink_counter += *(result);\n\t\t\tdelete result;\n\t\t}\n\n\t\tcout << \"Uniq urls: \" << url_counter.size() << endl;\n\t\tcout << \"Uniq links: \" << link_counter.size() << endl;\n\t}\n\n\tvector<string> download_link_batch(const string &batch, size_t limit, size_t offset) {\n\t\t\n\t\tFile::TsvFileRemote warc_paths_file(string(\"crawl-data/\") + batch + \"/warc.paths.gz\");\n\t\tvector<string> warc_paths;\n\t\twarc_paths_file.read_column_into(0, warc_paths);\n\n\t\tvector<string> files_to_download;\n\t\tfor (size_t i = offset; i < warc_paths.size() && i < (offset + limit); i++) {\n\t\t\tstring warc_path = warc_paths[i];\n\t\t\tconst size_t pos = warc_path.find(\".warc.gz\");\n\t\t\tif (pos != string::npos) {\n\t\t\t\twarc_path.replace(pos, 8, \".links.gz\");\n\t\t\t}\n\t\t\tfiles_to_download.push_back(warc_path);\n\t\t}\n\n\t\treturn Transfer::download_gz_files_to_disk(files_to_download);\n\t}\n\n\tvoid count_link_batch(const SubSystem *sub_system, const string &batch, size_t sub_batch, const vector<string> &files,\n\t\t\tmap<string, map<size_t, float>> &counter) {\n\n\t\tconst size_t chunk_size = 500;\n\n\t\tvector<vector<string>> chunks;\n\t\talgorithm::vector_chunk(files, chunk_size, chunks);\n\n\t\tfor (const vector<string> &chunk : chunks) {\n\t\t\tLink::run_link_counter(sub_system, batch, sub_batch, chunk, counter);\n\t\t}\n\n\t}\n\n\tvoid count_all_links() {\n\n\t\tSubSystem *sub_system = new SubSystem();\n\n\t\tfor (const string &batch : Config::link_batches) {\n\n\t\t\tvector<string> files = download_link_batch(batch, 50000, 0);\n\n\t\t\tfor (size_t sub_batch = 0; sub_batch < 5; sub_batch++) {\n\n\t\t\t\tmap<string, map<size_t, float>> counter;\n\t\t\t\tcount_link_batch(sub_system, batch, sub_batch, files, counter);\n\t\t\t\t// Upload link counts.\n\t\t\t\tLink::upload_link_counts(batch, sub_batch, counter);\n\t\t\t}\n\n\t\t\tTransfer::delete_downloaded_files(files);\n\t\t}\n\t\tdelete sub_system;\n\t}\n}\n\n", "meta": {"hexsha": "2183c5ad3d7b8b587311aa3ca55f00c6e5973b65", "size": 7345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/Counter.cpp", "max_stars_repo_name": "jozo-123/alexandria", "max_stars_repo_head_hexsha": "ef5cd5548b34f8782b0674441d8db1ed46470011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/Counter.cpp", "max_issues_repo_name": "jozo-123/alexandria", "max_issues_repo_head_hexsha": "ef5cd5548b34f8782b0674441d8db1ed46470011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/Counter.cpp", "max_forks_repo_name": "jozo-123/alexandria", "max_forks_repo_head_hexsha": "ef5cd5548b34f8782b0674441d8db1ed46470011", "max_forks_repo_licenses": ["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.1468253968, "max_line_length": 119, "alphanum_fraction": 0.6973451327, "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.031618770234328894, "lm_q1q2_score": 0.014087096001023631}}
{"text": "/*\n\nCopyright (c) 2005-2021, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef ABSTRACTRUSHLARSENCARDIACCELL_HPP_\n#define ABSTRACTRUSHLARSENCARDIACCELL_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"ClassIsAbstract.hpp\"\n\n#include \"AbstractCardiacCell.hpp\"\n#include \"PetscTools.hpp\"\n\n/**\n * This is the base class for cardiac cells solved using the Rush-Larsen method.\n * It is based on code contributed by Megan Lewis, University of Saskatchewan\n *\n * The basic approach to solving such models is:\n *  \\li Compute alpha & beta values for gating variables, and derivatives for\n *      other state variables.\n *  \\li Update the transmembrane potential, either from solving an external PDE,\n *      or using a forward Euler step.\n *  \\li Update any eligible gating variables (or similar) with Rush-Larsen scheme.\n *  \\li Update the remaining state variables using a forward Euler step.\n */\nclass AbstractRushLarsenCardiacCell : 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     * Some notes for future reference:\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    AbstractRushLarsenCardiacCell(\n        unsigned numberOfStateVariables,\n        unsigned voltageIndex,\n        boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);\n\n    /** Virtual destructor */\n    virtual ~AbstractRushLarsenCardiacCell();\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     * but the other state variables are updated.\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     * Update the values of elligible gating variables using the Rush-Larsen method,\n     * and of other non-V variables using forward Euler, for a single timestep.\n     *\n     * \\note This method must be provided by subclasses.\n     *\n     * @param rDY  vector containing dy/dt values\n     * @param rAlphaOrTau  vector containing alpha or tau values, depending on the formulation\n     * @param rBetaOrInf  vector containing beta or inf values, depending on the formulation\n     */\n    virtual void ComputeOneStepExceptVoltage(const std::vector<double> &rDY,\n                                             const std::vector<double> &rAlphaOrTau,\n                                             const std::vector<double> &rBetaOrInf)=0;\n\n    /**\n     * Perform a forward Euler step to update the transmembrane potential.\n     *\n     * @param rDY  vector containing dy/dt values\n     */\n    void UpdateTransmembranePotential(const std::vector<double> &rDY);\n\n     /**\n     * Compute dy/dt and alpha and beta values.\n     *\n     * \\note This method must be provided by subclasses.\n     *\n     * @param time  start of this timestep\n     * @param rDY  vector to fill in with dy/dt values\n     * @param rAlphaOrTau  vector to fill in with alpha or tau values, depending on the formulation\n     * @param rBetaOrInf  vector to fill in with beta or inf values, depending on the formulation\n     */\n    virtual void EvaluateEquations(double time,\n                                   std::vector<double> &rDY,\n                                   std::vector<double> &rAlphaOrTau,\n                                   std::vector<double> &rBetaOrInf)=0;\n};\n\nCLASS_IS_ABSTRACT(AbstractRushLarsenCardiacCell)\n\n#endif // ABSTRACTRUSHLARSENCARDIACCELL_HPP_\n", "meta": {"hexsha": "86d147e07e0203e3c08ac44aa254a72f767d1d29", "size": 7587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/odes/AbstractRushLarsenCardiacCell.hpp", "max_stars_repo_name": "mdp19pn/Chaste", "max_stars_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T08:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T11:39:26.000Z", "max_issues_repo_path": "heart/src/odes/AbstractRushLarsenCardiacCell.hpp", "max_issues_repo_name": "mdp19pn/Chaste", "max_issues_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-06-14T13:48:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:42:07.000Z", "max_forks_repo_path": "heart/src/odes/AbstractRushLarsenCardiacCell.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": 40.1428571429, "max_line_length": 99, "alphanum_fraction": 0.7040991169, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.029312232023305632, "lm_q1q2_score": 0.014083902493191419}}
{"text": "// This alternative to numpy is not currently being used\r\n// but is retained in CVS for possible future use.\r\n// In particular, information about array objects such\r\n// as curve cannot currently be cached because we don't\r\n// know when a numpy pos array has been changed.\r\n\r\n// Copyright (c) 2000, 2001, 2002, 2003 by David Scherer and others.\r\n// See the file license.txt for complete license terms.\r\n// See the file authors.txt for a complete list of contributors.\r\n\r\n#include <boost/python/class.hpp>\r\n#include <boost/python/object.hpp>\r\n#include <boost/python/overloads.hpp>\r\n#include <boost/python/init.hpp>\r\n#include <boost/python/operators.hpp>\r\n#include <boost/python/def.hpp>\r\n#include <boost/python/return_value_policy.hpp>\r\n#include <boost/python/copy_const_reference.hpp>\r\n#include <boost/python/return_internal_reference.hpp>\r\n#include <boost/python/iterator.hpp>\r\n#include <boost/python/extract.hpp>\r\n#include <boost/python/module.hpp>\r\n\r\n#include \"python/vector_array.hpp\"\r\n#include \"python/scalar_array.hpp\"\r\n\r\n// TODO: Figure out what to do with this...\r\n#define PY_ARRAY_UNIQUE_SYMBOL visual_PyArrayHandle\r\n#define NO_IMPORT_ARRAY\r\n#include <numpy/arrayobject.h>\r\n\r\n#include <iostream>\r\n#include <stdexcept>\r\n\r\nnamespace cvisual {namespace python {\r\n\r\n\t\tvector_array::vector_array( const boost::python::list& sequence)\r\n\t\t: data( boost::python::extract<int>( sequence.attr(\"__len__\")()))\r\n\t\t{\r\n\t\t\titerator i = data.begin();\r\n\t\t\tfor (int s_i = 0; s_i < sequence.attr(\"__len__\")(); ++s_i, ++i) {\r\n\t\t\t\tboost::python::extract<vector> v_extractor( sequence[s_i]);\r\n\t\t\t\tif (v_extractor.check()) {\r\n\t\t\t\t\t*i = v_extractor();\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tboost::python::object elem = sequence[s_i];\r\n\t\t\t\t\t*i = vector();\r\n\t\t\t\t\tswitch (boost::python::extract<int>(elem.attr(\"__len__\")())) {\r\n\t\t\t\t\t\tcase 3:\r\n\t\t\t\t\t\ti->z = boost::python::extract<double>(elem[2]);\r\n\t\t\t\t\t\tcase 2:\r\n\t\t\t\t\t\ti->y = boost::python::extract<double>(elem[1]);\r\n\t\t\t\t\t\ti->x = boost::python::extract<double>(elem[0]);\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\tthrow std::invalid_argument(\r\n\t\t\t\t\t\t\t\t\"Can only construct a vector from a \"\r\n\t\t\t\t\t\t\t\t\"sequence of 2 or 3 doubles.\");\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\tvector_array::vector_array( boost::python::numeric::array sequence)\r\n\t\t: data( ((PyArrayObject*)sequence.ptr())->dimensions[0])\r\n\t\t{\r\n\t\t\tconst PyArrayObject* seq_ptr = (const PyArrayObject*)sequence.ptr();\r\n\r\n\t\t\tif (!( seq_ptr->nd == 2\r\n\t\t\t\t\t\t\t&& seq_ptr->dimensions[1] == 3\r\n\t\t\t\t\t\t\t&& seq_ptr->descr->type_num == PyArray_DOUBLE)) {\r\n\t\t\t\tthrow std::invalid_argument( \"Must construct a vector_array from an Nx3 array of type Float64.\");\r\n\t\t\t}\r\n\r\n\t\t\tconst double* seq_i = (const double*)seq_ptr->data;\r\n\t\t\titerator i = this->begin();\r\n\t\t\tfor (; i != this->end(); ++i, seq_i += 3) {\r\n\t\t\t\t*i = vector( seq_i[0], seq_i[1], seq_i[2]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::append( const vector& v)\r\n\t\t{\r\n\t\t\tdata.push_back( v);\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::append( const vector_array& va)\r\n\t\t{\r\n\t\t\tdata.insert( data.end(), va.data.begin(), va.data.end());\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::prepend( const vector& v)\r\n\t\t{\r\n\t\t\tdata.push_front( v);\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::head_clip()\r\n\t\t{\r\n\t\t\tdata.pop_front();\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::head_crop( int i_)\r\n\t\t{\r\n\t\t\tif (i_ < 0)\r\n\t\t\tthrow std::invalid_argument( \"Cannot crop a negative amount.\");\r\n\t\t\tsize_t i = (size_t)i_;\r\n\t\t\tif (i >= data.size())\r\n\t\t\tthrow std::invalid_argument( \"Cannot crop greater than the array's length.\");\r\n\r\n\t\t\titerator begin = data.begin();\r\n\t\t\tdata.erase( begin, begin+i);\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::tail_clip()\r\n\t\t{\r\n\t\t\tdata.pop_back();\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::tail_crop( int i_)\r\n\t\t{\r\n\t\t\tif (i_ < 0)\r\n\t\t\tthrow std::invalid_argument( \"Cannot crop a negative amount.\");\r\n\t\t\tsize_t i = (size_t)i_;\r\n\t\t\tif (i >= data.size())\r\n\t\t\tthrow std::invalid_argument( \"Cannot crop greater than the array's length.\");\r\n\r\n\t\t\titerator end = data.end();\r\n\t\t\tdata.erase( end-i, end);\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator*( double s) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = *i * s;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\t// Possibly dangerous, this provides block multiplication elementwise, not to be\r\n\t\t// confused with dot() or cross().\r\n\t\tvector_array\r\n\t\tvector_array::operator*( vector v) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\tvector v_i = *i;\r\n\t\t\t\t*r_i = vector( v_i[0]*v[0], v_i[1]*v[1], v_i[2]*v[2]);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator*( const scalar_array& s) const\r\n\t\t{\r\n\t\t\tif (data.size() != s.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array multiplication.\");\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\tscalar_array::const_iterator s_i = s.begin();\r\n\t\t\titerator r_i = ret.begin();\r\n\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i, ++s_i) {\r\n\t\t\t\t*r_i = *i * *s_i;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator/( double s) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = *i / s;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator/( const scalar_array& s) const\r\n\t\t{\r\n\t\t\tif (data.size() != s.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array division.\");\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\tscalar_array::const_iterator s_i = s.begin();\r\n\t\t\titerator r_i = ret.begin();\r\n\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i, ++s_i) {\r\n\t\t\t\t*r_i = *i / *s_i;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator-() const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = -(*i);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator*=( double s)\r\n\t\t{\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i) {\r\n\t\t\t\t*i *= s;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator*=( const scalar_array& s)\r\n\t\t{\r\n\t\t\tif (data.size() != s.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array multiplication.\");\r\n\r\n\t\t\tscalar_array::const_iterator s_i = s.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++s_i) {\r\n\t\t\t\t*i *= *s_i;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator/=( double s)\r\n\t\t{\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i) {\r\n\t\t\t\t*i /= s;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator/=( const scalar_array& s)\r\n\t\t{\r\n\t\t\tif (data.size() != s.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array multiplication.\");\r\n\r\n\t\t\tscalar_array::const_iterator s_i = s.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++s_i) {\r\n\t\t\t\t*i /= *s_i;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator+( const vector& v) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = *i + v;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator+( const vector_array& v) const\r\n\t\t{\r\n\t\t\tif (data.size() != v.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array addition.\");\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tconst_iterator v_i = v.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = *i + *v_i;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator-( const vector& v) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i ) {\r\n\t\t\t\t*r_i = *i - v;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator-( const vector_array& v) const\r\n\t\t{\r\n\t\t\tif (data.size() != v.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array subtraction.\");\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tconst_iterator v_i = v.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = *i - *v_i;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator+=( const vector& v)\r\n\t\t{\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i) {\r\n\t\t\t\t*i += v;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator+=( const vector_array& v)\r\n\t\t{\r\n\t\t\tif (data.size() != v.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array addition.\");\r\n\r\n\t\t\tconst_iterator v_i = v.data.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++v_i) {\r\n\t\t\t\t*i += *v_i;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator-=( const vector& v)\r\n\t\t{\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i) {\r\n\t\t\t\t*i -= v;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tconst vector_array&\r\n\t\tvector_array::operator-=( const vector_array& v)\r\n\t\t{\r\n\t\t\tif (data.size() != v.data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector array subtraction.\");\r\n\r\n\t\t\tconst_iterator v_i = v.data.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++v_i) {\r\n\t\t\t\t*i -= *v_i;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::cross( const vector& v)\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->cross(v);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::cross( const vector_array& v)\r\n\t\t{\r\n\t\t\tif (v.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array types.\" );\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tconst_iterator v_i = v.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = i->cross( *v_i);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::norm() const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->norm();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::fabs() const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->fabs();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::proj( const vector& v)\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.data.begin();\r\n\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->proj( v);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::proj( const vector_array& v)\r\n\t\t{\r\n\t\t\tif (v.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array types.\" );\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.data.begin();\r\n\t\t\tconst_iterator v_i = v.data.begin();\r\n\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = i->proj( *v_i);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::mag() const\r\n\t\t{\r\n\t\t\tscalar_array ret( data.size());\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tfor ( const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->mag();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::mag2() const\r\n\t\t{\r\n\t\t\tscalar_array ret( data.size());\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tfor ( const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->mag2();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::rotate( const double& d, vector axis)\r\n\t\t{\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i) {\r\n\t\t\t\ti->rotate( d, axis);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvector&\r\n\t\tvector_array::py_getitem( int index)\r\n\t\t{\r\n\t\t\tif (index < 0) {\r\n\t\t\t\t// Negative indexes are counted from the end of the array in Python.\r\n\t\t\t\tindex += data.size();\r\n\t\t\t}\r\n\r\n\t\t\treturn data.at(index);\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::py_setitem( int index, vector value)\r\n\t\t{\r\n\t\t\tif (index < 0)\r\n\t\t\tindex += data.size();\r\n\r\n\t\t\tdata.at(index) = value;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::dot( const vector& v)\r\n\t\t{\r\n\t\t\tscalar_array ret( data.size());\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tfor ( const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->dot( v);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::dot( const vector_array& v)\r\n\t\t{\r\n\t\t\tif (v.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array types.\" );\r\n\r\n\t\t\tscalar_array ret( data.size());\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tconst_iterator v_i = v.begin();\r\n\r\n\t\t\tfor ( const_iterator i = data.begin(); i != data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = i->dot( *v_i);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::comp( const vector& v)\r\n\t\t{\r\n\t\t\tscalar_array ret( data.size());\r\n\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->comp( v);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::comp( const vector_array& v)\r\n\t\t{\r\n\t\t\tif ( data.size() != v.data.size() )\r\n\t\t\tthrow std::out_of_range( \"Incompatible array scalar projection.\");\r\n\r\n\t\t\tscalar_array ret( data.size());\r\n\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tconst_iterator v_i = v.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i !=data.end(); ++i, ++v_i, ++r_i) {\r\n\t\t\t\t*r_i = i->comp( *v_i);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::get_x() const\r\n\t\t{\r\n\t\t\tscalar_array ret( data.size());\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->get_x();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::get_y() const\r\n\t\t{\r\n\t\t\tscalar_array ret( data.size());\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->get_y();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tscalar_array\r\n\t\tvector_array::get_z() const\r\n\t\t{\r\n\t\t\tscalar_array ret( data.size());\r\n\t\t\tscalar_array::iterator r_i = ret.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = i->get_z();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_x( const scalar_array& x)\r\n\t\t{\r\n\t\t\tif (data.empty()) {\r\n\t\t\t\t// In case we are building this thing up from single columns\r\n\t\t\t\tdata = std::deque<vector>( x.size());\r\n\t\t\t}\r\n\t\t\tif (x.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible array assignment.\");\r\n\r\n\t\t\tscalar_array::const_iterator x_i = x.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++x_i) {\r\n\t\t\t\ti->set_x( *x_i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_y( const scalar_array& y)\r\n\t\t{\r\n\t\t\tif (data.empty()) {\r\n\t\t\t\t// In case we are building this thing up from single columns\r\n\t\t\t\tdata = std::deque<vector>( y.size());\r\n\t\t\t}\r\n\t\t\tif (y.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible array assignment.\");\r\n\r\n\t\t\tscalar_array::const_iterator y_i = y.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++y_i) {\r\n\t\t\t\ti->set_y( *y_i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_z( const scalar_array& z)\r\n\t\t{\r\n\t\t\tif (data.empty()) {\r\n\t\t\t\t// In case we are building this thing up from single columns\r\n\t\t\t\tdata = std::deque<vector>( z.size());\r\n\t\t\t}\r\n\t\t\tif (z.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible array assignment.\");\r\n\r\n\t\t\tscalar_array::const_iterator z_i = z.begin();\r\n\t\t\tfor (iterator i = data.begin(); i != data.end(); ++i, ++z_i) {\r\n\t\t\t\ti->set_z( *z_i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_x( const boost::python::list& sequence)\r\n\t\t{\r\n\t\t\tthis->set_x( scalar_array( sequence));\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_y( const boost::python::list& sequence)\r\n\t\t{\r\n\t\t\tthis->set_y( scalar_array( sequence));\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_z( const boost::python::list& sequence)\r\n\t\t{\r\n\t\t\tthis->set_z( scalar_array( sequence));\r\n\t\t}\r\n\r\n\t\tvector\r\n\t\tvector_array::sum() const\r\n\t\t{\r\n\t\t\tvector ret;\r\n\t\t\tfor (const_iterator i = data.begin(); i != data.end(); ++i) {\r\n\t\t\t\tret += *i;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\t// Evaluate expression vector - vector_array\r\n\t\tvector_array\r\n\t\tvector_array::lhs_sub( const vector& v) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tfor ( const_iterator i = data.begin(); i != data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = v - *i;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator>=( const double& s) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i!= data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = vector( (i->x >= s) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->y >= s) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->z >= s) ? 1.0: 0.0);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator>=( const scalar_array& s) const\r\n\t\t{\r\n\t\t\tif (s.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array to scalar_array comparison.\" );\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tscalar_array::const_iterator s_i = s.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i!= data.end(); ++i, ++r_i, ++s_i) {\r\n\t\t\t\t*r_i = vector( (i->x >= *s_i) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->y >= *s_i) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->z >= *s_i) ? 1.0: 0.0);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator>=( const vector_array& v) const\r\n\t\t{\r\n\t\t\tif (v.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array to vector_array comparison\" );\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tconst_iterator v_i = v.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i!= data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = vector( (i->x >= v_i->x) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->y >= v_i->y) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->z >= v_i->z) ? 1.0: 0.0);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator<=( const double& s) const\r\n\t\t{\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i!= data.end(); ++i, ++r_i) {\r\n\t\t\t\t*r_i = vector( (i->x <= s) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->y <= s) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->z <= s) ? 1.0: 0.0);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator<=( const scalar_array& s) const\r\n\t\t{\r\n\t\t\tif (s.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array comparison.\" );\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tscalar_array::const_iterator s_i = s.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i!= data.end(); ++i, ++r_i, ++s_i) {\r\n\t\t\t\t*r_i = vector( (i->x <= *s_i) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->y <= *s_i) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->z <= *s_i) ? 1.0: 0.0);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator<=( const vector_array& v) const\r\n\t\t{\r\n\t\t\tif (v.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array comparison.\" );\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tconst_iterator v_i = v.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i!= data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = vector( (i->x <= v_i->x) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->y <= v_i->y) ? 1.0: 0.0\r\n\t\t\t\t\t\t, (i->z <= v_i->z) ? 1.0: 0.0);\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvector_array\r\n\t\tvector_array::operator*( const vector_array& v) const\r\n\t\t{\r\n\t\t\tif (v.data.size() != data.size())\r\n\t\t\tthrow std::out_of_range( \"Incompatible vector_array multiplication.\" );\r\n\r\n\t\t\tvector_array ret( data.size());\r\n\t\t\titerator r_i = ret.begin();\r\n\t\t\tconst_iterator v_i = v.begin();\r\n\t\t\tfor (const_iterator i = data.begin(); i!= data.end(); ++i, ++r_i, ++v_i) {\r\n\t\t\t\t*r_i = vector( (i->x * v_i->x)\r\n\t\t\t\t\t\t, (i->y * v_i->y)\r\n\t\t\t\t\t\t, (i->z * v_i->z));\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_x( boost::python::numeric::array x)\r\n\t\t{\r\n\t\t\tthis->set_x( scalar_array( x));\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_y( boost::python::numeric::array y)\r\n\t\t{\r\n\t\t\tthis->set_y( scalar_array( y));\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_z( boost::python::numeric::array z)\r\n\t\t{\r\n\t\t\tthis->set_z( scalar_array( z));\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_x( double x)\r\n\t\t{\r\n\t\t\tthis->set_x( scalar_array( size(), x));\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_y( double y)\r\n\t\t{\r\n\t\t\tthis->set_y( scalar_array( size(), y));\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\tvector_array::set_z( double z)\r\n\t\t{\r\n\t\t\tthis->set_z( scalar_array( size(), z));\r\n\t\t}\r\n\r\n\t\tboost::python::handle<PyObject>\r\n\t\tvector_array::as_array() const\r\n\t\t{\r\n\t\t\t// Make space for the returned array\r\n\t\t\tint dims[] = {size(), 3};\r\n\t\t\tboost::python::handle<> ret( PyArray_FromDims( 2, dims, PyArray_DOUBLE));\r\n\r\n\t\t\t// A direct pointer to the PyArrayObject\r\n\t\t\tPyArrayObject* ret_ptr = (PyArrayObject *)ret.get();\r\n\r\n\t\t\t// Iterable pointers to copy the data.\r\n\t\t\tdouble* r_i = (double *) ret_ptr->data;\r\n\t\t\tconst_iterator i = this->begin();\r\n\t\t\t// Copy the data.\r\n\t\t\tfor (; i != this->end(); ++i, r_i += 3) {\r\n\t\t\t\tr_i[0] = i->get_x();\r\n\t\t\t\tr_i[1] = i->get_y();\r\n\t\t\t\tr_i[2] = i->get_z();\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\t// This algorithm is failing to recognize all of the collisions...\r\n\t\tboost::python::list\r\n\t\tsphere_collisions( const vector_array& pos, const scalar_array& radius)\r\n\t\t{\r\n\t\t\tif (pos.size() != radius.size())\r\n\t\t\tthrow std::out_of_range( \"Unequal array lengths.\");\r\n\t\t\tassert( pos.size());\r\n\r\n\t\t\tboost::python::list ret;\r\n\t\t\tvector_array::const_iterator pos_i = pos.begin();\r\n\t\t\tscalar_array::const_iterator r_i = radius.begin();\r\n\t\t\t// In spite of using two iterators and a counter, this is a two-pointer\r\n\t\t\t// search: i, and j.\r\n\t\t\tfor ( int i = 0; pos_i != pos.end(); ++pos_i, ++r_i, ++i) {\r\n\t\t\t\tvector_array::const_iterator pos_j = pos_i + 1;\r\n\t\t\t\tscalar_array::const_iterator r_j = r_i + 1;\r\n\t\t\t\tfor ( int j = i+1; pos_j != pos.end(); ++pos_j, ++r_j, ++j) {\r\n\t\t\t\t\t// If the magnitude of the differential distance is smaller\r\n\t\t\t\t\t// than the radius between them, a collision!\r\n\t\t\t\t\tif ((*pos_i - *pos_j).mag() < (*r_i + *r_j)) {\r\n\t\t\t\t\t\t// A collision\r\n\t\t\t\t\t\tret.append( boost::python::make_tuple( i, j));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\t// Return a list of integers for those spheres which have collided with\r\n\t\t// the plane specified by a normal vector 'normal' and point on the plane 'origin'\r\n\t\tboost::python::list\r\n\t\tsphere_to_plane_collisions( const vector_array& pos\r\n\t\t\t\t, const scalar_array& radius\r\n\t\t\t\t, vector normal\r\n\t\t\t\t, vector origin)\r\n\t\t{\r\n\t\t\tboost::python::list ret;\r\n\t\t\tvector_array::const_iterator p_i = pos.begin();\r\n\t\t\tscalar_array::const_iterator r_i = radius.begin();\r\n\t\t\tfor( int i = 0; p_i != pos.end(); ++p_i, ++r_i, ++i) {\r\n\t\t\t\t// Compute the scalar projection of a vector from the origin to pos\r\n\t\t\t\t// to the normal vector of the plane.\r\n\t\t\t\tdouble dist = (*p_i - origin).comp( normal);\r\n\t\t\t\tif ( dist < *r_i) {\r\n\t\t\t\t\tret.append( i);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\t/************************ python interface code ******************************/\r\n\r\n\t\tnamespace {\r\n\t\t\tBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( vector_array_rotate, vector_array::rotate, 1, 2)\r\n\t\t}\r\n\r\n\t\tvoid\r\n\t\twrap_vector_array()\r\n\t\t{\r\n\t\t\tusing namespace boost::python;\r\n\t\t\t// For the uninitiated (and sane), these are member function pointers.\r\n\t\t\t// They have the following syntax:\r\n\t\t\t// return-type (class-type::* pointer-name)(argument-list) = &class-type::member-function;\r\n\r\n\r\n\t\t\tvector_array (vector_array::* proj_vector)(const vector&) = &vector_array::proj;\r\n\t\t\tvector_array (vector_array::* proj_vector_array)( const vector_array&) = &vector_array::proj;\r\n\t\t\tvector_array (vector_array::* cross_vector)(const vector&) = &vector_array::cross;\r\n\t\t\tvector_array (vector_array::* cross_vector_array)(const vector_array&) = &vector_array::cross;\r\n\r\n\t\t\tscalar_array (vector_array::* dot_vector)(const vector&) = &vector_array::dot;\r\n\t\t\tscalar_array (vector_array::* dot_vector_array)(const vector_array&) = &vector_array::dot;\r\n\t\t\tscalar_array (vector_array::* comp_vector) (const vector&) = &vector_array::comp;\r\n\t\t\tscalar_array (vector_array::* comp_vector_array)(const vector_array&) = &vector_array::comp;\r\n\r\n\t\t\tvoid (vector_array::* append_vector)(const vector&) = &vector_array::append;\r\n\t\t\tvoid (vector_array::* prepend_vector)(const vector&) = &vector_array::prepend;\r\n\r\n\t\t\t// Overloaded setters for 'x', 'y', and 'z' properties\r\n\t\t\tvoid (vector_array::* set_x_s)(const scalar_array&) = &vector_array::set_x;\r\n\t\t\tvoid (vector_array::* set_x_n)(numeric::array) = &vector_array::set_x;\r\n\t\t\tvoid (vector_array::* set_x_d)(double) = &vector_array::set_x;\r\n\t\t\tvoid (vector_array::* set_y_s)(const scalar_array&) = &vector_array::set_y;\r\n\t\t\tvoid (vector_array::* set_y_n)(numeric::array) = &vector_array::set_y;\r\n\t\t\tvoid (vector_array::* set_y_d)(double) = &vector_array::set_y;\r\n\t\t\tvoid (vector_array::* set_z_s)(const scalar_array&) = &vector_array::set_z;\r\n\t\t\tvoid (vector_array::* set_z_n)(numeric::array) = &vector_array::set_z;\r\n\t\t\tvoid (vector_array::* set_z_d)(double) = &vector_array::set_z;\r\n\r\n\t\t\tvector_array (vector_array::* truediv_double)( double) const = &vector_array::operator/;\r\n\t\t\tvector_array (vector_array::* truediv_scalar_array)(const scalar_array&) const = &vector_array::operator/;\r\n\t\t\tconst vector_array& (vector_array::* itruediv_double)(double) = &vector_array::operator/=;\r\n\t\t\tconst vector_array& (vector_array::* itruediv_scalar_array)(const scalar_array&) = &vector_array::operator/=;\r\n\r\n\t\t\tclass_<vector_array> vector_array_wrapper( \"vector_array\", init< optional<int, vector> >( args(\"size\", \"fill\")));\r\n\t\t\tvector_array_wrapper.def( init<const list&>())\r\n\t\t\t.def( init<numeric::array>())\r\n\t\t\t.def( self * double())\r\n\t\t\t.def( double() * self)\r\n\t\t\t.def( self * other<scalar_array>())\r\n\t\t\t.def( other<scalar_array>() * self)\r\n\t\t\t.def( self * other<vector_array>())\r\n\t\t\t.def( other<vector_array>() * self)\r\n\t\t\t.def( self * other<vector>())\r\n\t\t\t.def( self / double())\r\n\t\t\t.def( self / other<scalar_array>())\r\n\t\t\t.def( -self)\r\n\t\t\t.def( self *= double())\r\n\t\t\t.def( self *= other<scalar_array>())\r\n\t\t\t.def( self /= double())\r\n\t\t\t.def( self /= other<scalar_array>())\r\n\t\t\t.def( self + self)\r\n\t\t\t.def( self + other<vector>())\r\n\t\t\t.def( other<vector>() + self)\r\n\t\t\t.def( self - self)\r\n\t\t\t.def( self - other<vector>())\r\n\t\t\t.def( other<vector>() - self)\r\n\t\t\t.def( self += self)\r\n\t\t\t.def( self += other<vector>())\r\n\t\t\t.def( self -= self)\r\n\t\t\t.def( self -= other<vector>())\r\n\t\t\t.def( self >= self)\r\n\t\t\t.def( self >= other<scalar_array>())\r\n\t\t\t.def( self >= other<double>())\r\n\t\t\t.def( self <= self)\r\n\t\t\t.def( self <= other<scalar_array>())\r\n\t\t\t.def( self <= other<double>())\r\n\t\t\t.def( \"__truediv__\", truediv_double)\r\n\t\t\t.def( \"__truediv__\", truediv_scalar_array)\r\n\t\t\t.def( \"__itruediv__\", itruediv_double, return_value_policy<copy_const_reference>())\r\n\t\t\t.def( \"__itruediv__\", itruediv_scalar_array, return_value_policy<copy_const_reference>())\r\n\t\t\t.def( \"proj\", proj_vector)\r\n\t\t\t.def( \"proj\", proj_vector_array, \"Returns a vector_array of vector projections of this array\"\r\n\t\t\t\t\t\" to a vector, or another vector_array of identical length.\")\r\n\t\t\t.def( \"cross\", cross_vector)\r\n\t\t\t.def( \"cross\", cross_vector_array, \"Returns a vector_array of cross products of this array\"\r\n\t\t\t\t\t\" and a vector, or another vector_array of identical length.\")\r\n\t\t\t.def( \"size\", &vector_array::size, \"Get the number of elements in the array.\")\r\n\t\t\t.def( \"rotate\", &vector_array::rotate, vector_array_rotate( args(\"angle\", \"axis\"), \"Rotate a vector_array about an axis vector through an angle.\"))\r\n\t\t\t.def( \"append\", append_vector, \"Add an element to the end of the array.\")\r\n\t\t\t.def( \"prepend\", prepend_vector, \"Add an element to the beginning of the array.\")\r\n\t\t\t.def( \"head_clip\", &vector_array::head_clip, \"Remove an element from the beginning of the arrray.\")\r\n\t\t\t.def( \"head_crop\", &vector_array::head_crop, \"Remove n elements from the beginning of the array.\")\r\n\t\t\t.def( \"tail_clip\", &vector_array::tail_clip, \"Remove an element from the end of the array.\")\r\n\t\t\t.def( \"tail_crop\", &vector_array::tail_crop, \"Remove n elements from the end of the array.\")\r\n\t\t\t.def( \"dot\", dot_vector)\r\n\t\t\t.def( \"dot\", dot_vector_array, \"Returns a scalar_array of dot products of this array\"\r\n\t\t\t\t\t\" and a vector, or another vector_array of identical length.\")\r\n\t\t\t.def( \"comp\", comp_vector)\r\n\t\t\t.def( \"comp\", comp_vector_array, \"Returns a scalar_array of scalar projections of this array\"\r\n\t\t\t\t\t\" to a vector, or another vector_array of identical length.\")\r\n\t\t\t.def( \"mag\", &vector_array::mag, \"Returns a scalar_array of the magnitudes of every element in this array.\")\r\n\t\t\t.def( \"mag2\", &vector_array::mag2, \"Equivalant to x.mag() * x.mag(), but faster.\")\r\n\t\t\t.def( \"norm\", &vector_array::norm, \"Returns a vector_array of the unit vectors of this array.\")\r\n\t\t\t.def( \"abs\", &vector_array::fabs, \"Returns a vector_array of absolute values of the vectors in the array.\")\r\n\t\t\t// Fancy C++ -> python iterator access\r\n\t\t\t.def( \"__iter__\", iterator<vector_array>())\r\n\t\t\t.def( \"__len__\", &vector_array::size)\r\n\t\t\t.def( \"__getitem__\", &vector_array::py_getitem, return_internal_reference<>(), \"Index this array by a single integer.\\n\"\r\n\t\t\t\t\t\"Returns a reference to the indexed vector.\")\r\n\t\t\t.def( \"__setitem__\", &vector_array::py_setitem)\r\n\t\t\t.def( \"get_x\", &vector_array::get_x)\r\n\t\t\t.def( \"set_x\", set_x_s)\r\n\t\t\t.def( \"set_x\", set_x_n)\r\n\t\t\t.def( \"set_x\", set_x_d)\r\n\t\t\t.def( \"get_y\", &vector_array::get_y)\r\n\t\t\t.def( \"set_y\", set_y_s)\r\n\t\t\t.def( \"set_y\", set_y_n)\r\n\t\t\t.def( \"set_y\", set_y_d)\r\n\t\t\t.def( \"get_z\", &vector_array::get_z)\r\n\t\t\t.def( \"set_z\", set_z_s)\r\n\t\t\t.def( \"set_z\", set_z_n)\r\n\t\t\t.def( \"set_z\", set_z_d)\r\n\t\t\t.def( \"sum\", &vector_array::sum, \"Returns the sum of all elements in the array.\")\r\n\t\t\t.def( \"as_array\", &vector_array::as_array, \"Create a self.__len__() x 3 Numeric.array from this vector_array.\")\r\n\t\t\t;\r\n\r\n\t\t\tvector_array_wrapper.add_property( \"x\", vector_array_wrapper.attr(\"get_x\"),\r\n\t\t\t\t\tvector_array_wrapper.attr(\"set_x\"));\r\n\t\t\tvector_array_wrapper.add_property( \"y\", vector_array_wrapper.attr(\"get_y\"),\r\n\t\t\t\t\tvector_array_wrapper.attr(\"set_y\"));\r\n\t\t\tvector_array_wrapper.add_property( \"z\", vector_array_wrapper.attr(\"get_z\"),\r\n\t\t\t\t\tvector_array_wrapper.attr(\"set_z\"));\r\n\r\n\t\t\tdef( \"sphere_intercollisions\", &sphere_collisions, args( \"pos\", \"radius\"),\r\n\t\t\t\t\t\"Evaluate collisions between spheres with centers == pos, and radii == radius.\\n\"\r\n\t\t\t\t\t\"Returns a list of two-integer tuple indexes.\\n\"\r\n\t\t\t\t\t\"The indexes corrispond to collision pairs indexed by pos.\");\r\n\t\t\tdef( \"sphere_to_plane_collisions\", &sphere_to_plane_collisions\r\n\t\t\t\t\t, args( \"pos\", \"radius\", \"normal\", \"origin\")\r\n\t\t\t\t\t, \"Evaluate collisions between spheres with centers == pos, and radii == radius with\\n\"\r\n\t\t\t\t\t\"a plane specified by a normal vector == normal, and a point on the plane == origin.\\n\"\r\n\t\t\t\t\t\"Returns a list of integers corrisponding to colliding spheres' indexed into pos.\" );\r\n\r\n\t\t}\r\n\r\n\t}} // !namespace cvisual::python\r\n", "meta": {"hexsha": "8e208d44f135343221285f5318981949e4481bbe", "size": 31348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/vector_array.cpp", "max_stars_repo_name": "lebarsfa/vpython-wx", "max_stars_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 68.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T05:41:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:35:24.000Z", "max_issues_repo_path": "src/python/vector_array.cpp", "max_issues_repo_name": "lebarsfa/vpython-wx", "max_issues_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-09T21:01:25.000Z", "max_forks_repo_path": "src/python/vector_array.cpp", "max_forks_repo_name": "lebarsfa/vpython-wx", "max_forks_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2015-02-04T04:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T03:24:41.000Z", "avg_line_length": 30.1713185756, "max_line_length": 151, "alphanum_fraction": 0.6029092765, "num_tokens": 9137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894545235253, "lm_q2_score": 0.04208772671409797, "lm_q1q2_score": 0.014082109523405242}}
{"text": "/**\n \\file\n Implementation of the Corsika shower reader\n \n \\author Lukas Nellen\n \\version $Id$\n \\date 29 Jan 2004\n */\n\n#include <corsika/Constants.h>\n#include <corsika/LongFile.h>\n#include <corsika/IOException.h>\n\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\nusing namespace corsika;\n\n\ntypedef boost::tokenizer<boost::char_separator<char> > mytok;\n\nstatic void log(const std::string& mess)\n{\n    std::cout << mess << std::endl;\n}\nstatic void log(const std::ostringstream& mess)\n{\n    std::cout << mess.str() << std::endl;\n}\n\n#define INFO(mess) log(mess);\n#define ERROR(mess) log(mess);\n#define FATAL(mess) log(mess);\n\nnamespace\n{\n    bool SplitLine(string l, vector<string>& vec, string s = \" \")\n    {\n        boost::char_separator<char> sep(s.c_str());\n        mytok tok(l,sep);\n        vec.clear();\n        for (mytok::const_iterator titer=tok.begin();titer!=tok.end();++titer) {\n            vec.push_back(*titer);\n        }\n        return true;\n    }\n    \n    string particleProfileStr = \" LONGITUDINAL DISTRIBUTION IN\";\n    string dEdX_ProfileStr = \" LONGITUDINAL ENERGY DEPOSIT\";\n    string GHFit_Str = \" FIT OF THE HILLAS CURVE\";\n    \n}\n\nLongFile::LongFile(string filename, double zenith):\n    fFilename(filename),\n    fCosZenith(cos(zenith)),\n    fIsSlantDepthProfile(false),\n    event_count(0),\n    fDx(0.),\n    fNBinsParticles(0),\n    fNBinsEnergyDeposit(0),\n    fLongDataFile(new std::ifstream(fFilename.c_str()))\n{\n    // check if file exists and is readable here\n    Scan();\n}\n\n\nLongProfile LongFile::GetProfile(size_t event)\n{\n    if (event >= event_count)\n    {\n        ostringstream msg;\n        msg << \"Trying to get event \" << event << \", but file \" << fFilename << \" has only \" << event_count << \" events (starting at zero).\";\n        throw IOException(msg.str());\n    }\n    return FetchProfile(event);\n}\n\nvoid LongFile::Scan()\n{\n    // scan for number of bins and dX,\n    // also check if there are energy deposit profiles\n    \n    //static const double g = 1;\n    //static const double cm = 1;\n    //static const double cm2 = cm*cm;\n    //static const double deg = 3.14159/180;\n    \n    // Read CORSIKA profile if available\n    if (!fLongDataFile->is_open()) return;\n    \n    string line;\n    while (getline(*fLongDataFile.get(), line) && (fPartProfiles.size()==0 || fdEdXProfiles.size()==0))\n    {\n        \n        if (line.find(particleProfileStr) != string::npos)\n        {\n            fPartProfiles.push_back(fLongDataFile->tellg());\n            char s1[50], s2[50], s3[50], isVertOrSlant[50];\n            sscanf(line.c_str(), \"%s %s %s %zu %s\", s1, s2, s3, &fNBinsParticles, isVertOrSlant);\n            string testStr(isVertOrSlant);\n            if (testStr == \"VERTICAL\")\n                fIsSlantDepthProfile = false;\n            else if (testStr == \"SLANT\")\n                fIsSlantDepthProfile = true;\n            else {\n                ostringstream err;\n                err << \"Corsika longitunal file \\\"\" << fFilename << \"\\\" is invalid:\\n\"\n                \"line: \\\"\" << line << \"\\\" \"\n                \"contains invalid string at                ^^^^^^^\\n\"\n                \"which is neither VERTICAL nor SLANT !\";\n                ERROR(err);\n                throw IOException(err.str());\n            }\n        }\n        \n        if (line.find(dEdX_ProfileStr) != string::npos)\n        {\n            fdEdXProfiles.push_back(fLongDataFile->tellg());\n            char s1[50], s2[50], s3[50], s4[50], isVertOrSlant[50], s5 [50], s6 [50];\n            sscanf(line.c_str(),\n                   \"%s %s %s %s %zu %s %s %s %f\",\n                   s1, s2, s3, s4, &fNBinsEnergyDeposit, isVertOrSlant, s5, s6, &fDx);\n            string testStr(isVertOrSlant);\n            if (testStr == \"VERTICAL\")\n            {\n                fIsSlantDepthProfile = false;\n                fDx /= fCosZenith;\n            }\n            else if (testStr == \"SLANT\")\n            {\n                fIsSlantDepthProfile = true;\n            }\n            else\n            {\n                ostringstream err;\n                err << \"Corsika longitunal file \\\"\" << fFilename << \"\\\" is invalid:\\n\"\n                \"line: \\\"\" << line << \"\\\" \"\n                \"contains invalid string at                ^^^^^^^\\n\"\n                \" which is neither VERTICAL nor SLANT !\";\n                ERROR(err);\n                throw IOException(err.str());\n            }\n        }\n    } // --  end scan file  ---\n    while (getline(*fLongDataFile.get(), line))\n    {\n        if (line.find(particleProfileStr) != string::npos)\n            fPartProfiles.push_back(fLongDataFile->tellg());\n\n        if (line.find(dEdX_ProfileStr) != string::npos)\n            fdEdXProfiles.push_back(fLongDataFile->tellg());\n    }\n    event_count = (fPartProfiles.size()?fPartProfiles.size():fdEdXProfiles.size());\n}\n\n\nLongProfile LongFile::FetchProfile(size_t findShower)\n{\n    bool aux_flag = false;\n    size_t i = 0;\n    size_t j = 0;\n    string line;\n    \n    vector<double> auxDepth(fNBinsParticles);\n    vector<double> auxCharge(fNBinsParticles);\n    vector<double> auxMuons(fNBinsParticles);\n    vector<double> auxAntiMuons(fNBinsParticles);\n    vector<double> auxGammas(fNBinsParticles);\n    vector<double> auxElectrons(fNBinsParticles);\n    vector<double> auxPositrons(fNBinsParticles);\n    vector<double> auxHadrons(fNBinsParticles);\n    vector<double> auxNuclei(fNBinsParticles);\n    vector<double> auxCherenkov(fNBinsParticles);\n    \n    vector<double> auxDepth_dE (fNBinsEnergyDeposit);\n    vector<double> auxDeltaEn (fNBinsEnergyDeposit);\n    \n    GaisserHillasParameter gh;\n    double energyDepositSum = 0.;\n    \n    // Read CORSIKA profile if available\n    if (!fLongDataFile->is_open())\n    {\n        ERROR(\"Reading failed for some reason.\");\n        return LongProfile();\n    }\n    fLongDataFile->clear();\n    fLongDataFile->seekg(fPartProfiles[findShower]);\n    \n    vector<string> tokens;\n    while (getline(*fLongDataFile.get(), line))\n    {\n        SplitLine(line, tokens);\n        if (line.find(particleProfileStr) != string::npos)\n        {\n            getline(*fLongDataFile.get(), line);\n            SplitLine(line, tokens);\n        }\n        if (line.find(dEdX_ProfileStr) != string::npos || aux_flag)\n        {\n            if (line.find(dEdX_ProfileStr) != string::npos)\n            {\n                getline(*fLongDataFile.get(), line);\n                SplitLine(line, tokens);\n            }\n            if (tokens.size() > 1 && tokens[0] == string(\"DEPTH\") && tokens[1] == string(\"GAMMA\"))\n            {\n                aux_flag = true;\n                getline(*fLongDataFile.get(), line);\n                SplitLine(line, tokens);\n            }\n            if (line.find(GHFit_Str) != string::npos) break;\n            \n            if (aux_flag && j < fNBinsParticles)\n            {\n                \n                float xdepth = 0.0;\n                float gamma = 0.0;\n                float emIoniz = 0.0;\n                float emCut = 0.0;\n                float muonIoniz = 0.0;\n                float muonCut = 0.0;\n                float hadronIoniz = 0.0;\n                float hadronCut = 0.0;\n                float neutrino = 0.0;\n                float sumEnergy = 0.0;\n                \n                sscanf(line.c_str(), \"%f %f %f %f %f %f %f %f %f %f\",\n                       &xdepth, &gamma, &emIoniz, &emCut, &muonIoniz, &muonCut,\n                       &hadronIoniz, &hadronCut, &neutrino, &sumEnergy);\n                \n                if (!fIsSlantDepthProfile)\n                    xdepth /= fCosZenith;\n                \n                // dEdX profile has slightly different depth-bins\n                auxDepth_dE[j] = xdepth;\n                //cout << j << \" \" << hadroncut  << \" \" << muoncut\n                //   << \" \" << neutrino << \" \" << sumenergy << endl;\n                // Subtracting neutrino energy\n                // and take fraction for muons and hadrons from\n                //     Barbosa et al Astro. Part. Phys. 22, (2004) p. 159\n                static float muonFraction = 0.575;\n                static float hadronFraction = 0.261;\n                static float hadronGroundFraction = 0.390;\n                auxDeltaEn[j] = sumEnergy - neutrino -\n                muonFraction * muonCut -\n                hadronFraction * hadronCut;\n                \n                if ( j+1 < fNBinsEnergyDeposit )\n                    energyDepositSum += auxDeltaEn[j];\n                else\n                {\n                    double groundEnergy = (1.-hadronGroundFraction)*hadronCut + hadronIoniz + muonIoniz + emIoniz+emCut + gamma;\n                    energyDepositSum += groundEnergy;\n                }\n                \n                auxDeltaEn[j] /= fDx;\n                \n                ++j;\n            }\n        }\n        \n        if (line.find(dEdX_ProfileStr) == string::npos || (tokens[0] == \"DEPTH\" && tokens[1] == \"GAMMAS\" && i < fNBinsParticles))\n        {\n            if (aux_flag) continue;\n            \n            float xdepth = 0.0;\n            float chargedparticles = 0.0;\n            float gammas, positrons, electrons, muplus, muminus, hadrons;\n            float nuclei, cerenkov;\n            sscanf(line.c_str(), \"%f %f %f %f %f %f %f %f %f %f\",\n                   &xdepth, &gammas, &positrons, &electrons, &muplus, &muminus,\n                   &hadrons, &chargedparticles, &nuclei, &cerenkov);\n            \n            if (xdepth > 0)\n            {\n                //BRD 17/2/05 CORSIKA depths are vertical assuming a flat\n                //Earth.  So apply cosTheta correction here.\n                // RU Wed Jun 13 14:46:44 CEST 2007\n                // if SLANT was used in CORSIKA, don't do the fCosZenith correction\n                if (!fIsSlantDepthProfile)\n                    xdepth /= fCosZenith;\n                auxDepth[i] = xdepth;\n                auxCharge[i] = chargedparticles;\n                auxMuons[i] =  muminus;\n                auxAntiMuons[i] =  muminus;\n                auxGammas[i] = gammas;\n                auxElectrons[i] = electrons;\n                auxPositrons[i] = positrons;\n                auxHadrons[i] = hadrons;\n                auxNuclei[i] = nuclei;\n                auxCherenkov[i] = cerenkov;\n                ++i;\n            }\n        }\n    }\n    \n    float anmax;\n    float ax0;\n    float axmax;\n    float achi;\n    while (getline(*fLongDataFile.get(), line))\n    {\n        if (line.find(\" PARAMETERS         = \") != string::npos)\n        {\n            \n            float aapar, abpar, acpar;\n            sscanf(line.c_str(), \" PARAMETERS         =   %f %f %f %f %f %f\", &anmax,\n                   &ax0, &axmax, &aapar, &abpar, &acpar);\n            getline(*fLongDataFile.get(), line);\n            sscanf(line.c_str(), \" CHI**2/DOF         = %f\", &achi);\n            \n            const bool hasValidGHfit = (achi>0) && (achi*fNBinsParticles<1e15);\n            \n            double A = aapar * (g/cm2);\n            double B = abpar;\n            double C = acpar / (g/cm2);\n            \n            if (!fIsSlantDepthProfile)\n            {\n                A /= fCosZenith;\n                B /= fCosZenith;\n                C /= fCosZenith;\n                axmax /= fCosZenith;\n            }\n            \n            // GaisserHillas6Parameter gh;\n            if (hasValidGHfit)\n            {\n                gh.SetXMax(axmax*(g/cm2), 0);\n                gh.SetNMax(anmax, 0);\n                gh.SetXZero(ax0*(g/cm2), 0);\n                gh.SetChiSquare(fNBinsParticles*achi, fNBinsParticles);\n                gh.SetA(A, 0.);\n                gh.SetB(B, 0.);\n                gh.SetC(C, 0.);\n            }\n            \n            break;\n        }\n    }\n    \n    LongProfile profile;\n    profile.fChargeProfile = auxCharge;\n    profile.fGammaProfile = auxGammas;\n    profile.fElectronProfile = auxElectrons;\n    profile.fPositronProfile = auxPositrons;\n    profile.fMuonProfile = auxMuons;\n    profile.fAntiMuonProfile = auxAntiMuons;\n    profile.fDepth = auxDepth;\n    profile.fHadronProfile = auxHadrons;\n    profile.fNucleiProfile = auxNuclei;\n    profile.fCherenkovProfile = auxCherenkov;\n    //profile.fdEdX = auxDeltaEn;\n    //profile.fDepth_dE = auxDepth_dE;\n    \n    profile.fCalorimetricEnergy = energyDepositSum;\n    profile.fGaisserHillas = gh;\n    return profile;\n}\n\n\nvoid CorrectProfile(LongProfile& profile, double dX)\n{\n    // This code is quarantined because is mostly dead code, very\n    // specific for other purposes, so maybe it should not be here at\n    // all.\n    //\n    // CORSIKA writes into the last bin of the dEdX profile not only\n    // the energy deposit in the atmosphere, but also the energy hitting\n    // the ground (observation level). For vertical event this can be\n    // remarkable, and should not be used for FD simulations !\n    //\n    // - Fix this by replacing the entries in the last bin by GH fitted\n    //   extrapolations.\n    // - Add one more bin in depth (extrapolation) to make sure\n    //   that also for a different atmospheric profile model the\n    //   shower will hit the ground, and does not just disappear\n    //   somewhere in the middle of the atmosphere !\n    \n    \n    vector<double> auxDepth = profile.fDepth;\n    vector<double> auxCharge = profile.fChargeProfile;\n    vector<double> auxMuons = profile.fMuonProfile;\n    vector<double> auxAntiMuons = profile.fAntiMuonProfile;\n    vector<double> auxGammas = profile.fGammaProfile;\n    vector<double> auxElectrons = profile.fElectronProfile;\n    vector<double> auxPositrons = profile.fPositronProfile;\n    vector<double> auxHadrons = profile.fHadronProfile;\n    vector<double> auxNuclei = profile.fNucleiProfile;\n    vector<double> auxCherenkov = profile.fCherenkovProfile;\n    \n    vector<double> auxDepth_dE = profile.fDepth_dE;\n    vector<double> auxDeltaEn = profile.fdEdX;\n    size_t i = auxDepth.size();\n    \n    size_t nBinsEnergyDeposit = auxDepth_dE.size();\n    //size_t nBinsParticles = auxDepth.size();\n    \n    // go three bins back, since CORSIKA sometimes has a funny second-last bin\n    //const double normDepth_dedx = auxDepth_dE[nBinsEnergyDeposit-3];\n    const double normN_dedx = 1;\n    // const double normN_dedx =\n    //   theShower.HasGHParameters() ?\n    //     theShower.GetGHParameters().Eval(normDepth_dedx * g/cm2) : 1;\n    const double normdEdX = auxDeltaEn[i-3];\n    \n    // const double normDepth_part = auxDepth[nBinsEnergyDeposit-1];\n    const double normN_part = 1.;\n    // const double normN_part =\n    //   theShower.HasGHParameters() ?\n    //     theShower.GetGHParameters().Eval(normDepth_part * g/cm2) : 1.;\n    const double normCharge = auxCharge[i-1];\n    const double normMuons = auxMuons[i-1];\n    const double normGammas = auxGammas[i-1];\n    const double normElectrons = auxElectrons[i-1];\n    \n    const double lastBinDepth_dEdX = auxDepth_dE[profile.fDepth_dE.size()-1];\n    const double lastBinDepth_part = auxDepth[profile.fDepth.size()-1];\n    \n    // recalculate last dedx bins\n    for (size_t iCorrect = 0; iCorrect < 2; ++iCorrect)\n    {\n        size_t binCorrect = nBinsEnergyDeposit - 2 + iCorrect;\n        //const double binDepth = auxDepth_dE[binCorrect];\n        auxDeltaEn[binCorrect] = normdEdX / normN_dedx;\n        // auxDeltaEn[binCorrect] = normdEdX / normN_dedx *\n        //   (theShower.HasGHParameters() ?\n        //      theShower.GetGHParameters().Eval(binDepth*g/cm2) : 1);\n    }\n    \n    // prolongate profiles by some bins\n    for (size_t iBinAdd = 0; iBinAdd < 2; ++iBinAdd)\n    {\n        const double addDepth_dEdX = lastBinDepth_dEdX + dX * (iBinAdd+1);\n        const double addDepth_part = lastBinDepth_part + dX * (iBinAdd+1);\n        const double Nch_dedx = 1;\n        // const double Nch_dedx =\n        //   theShower.HasGHParameters() ?\n        //     theShower.GetGHParameters().Eval(addDepth_dEdX * g/cm2) : 1;\n        const double Nch_part = 1;\n        // const double Nch_part =\n        //   theShower.HasGHParameters() ?\n        //     theShower.GetGHParameters().Eval(addDepth_part * g/cm2) : 1;\n        const double adddEdX = normdEdX / normN_dedx * Nch_dedx;\n        \n        auxDepth_dE.push_back(addDepth_dEdX);\n        auxDeltaEn.push_back(adddEdX);\n        \n        const double fac = Nch_part / normN_part;\n        const double addCharge = normCharge * fac;\n        const double addMuons = normMuons * fac;\n        const double addGammas = normGammas * fac;\n        const double addElectrons = normElectrons * fac;\n        \n        auxDepth.push_back(addDepth_part);\n        auxCharge.push_back(addCharge);\n        auxMuons.push_back(addMuons);\n        auxGammas.push_back(addGammas);\n        auxElectrons.push_back(addElectrons);\n        \n    }\n    \n    profile.fChargeProfile = auxCharge;\n    profile.fGammaProfile = auxGammas;\n    profile.fElectronProfile = auxElectrons;\n    profile.fPositronProfile = auxPositrons;\n    profile.fMuonProfile = auxMuons;\n    profile.fAntiMuonProfile = auxAntiMuons;\n    profile.fDepth = auxDepth;\n    profile.fHadronProfile = auxHadrons;\n    profile.fNucleiProfile = auxNuclei;\n    profile.fCherenkovProfile = auxCherenkov;\n    //profile.fdEdX = auxDeltaEn;\n    //profile.fDepth_dE = auxDepth_dE;\n}\n", "meta": {"hexsha": "c0ef59559d6d66cd8b40c84103071d97acff616d", "size": 17224, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/corsika/LongFile.cxx", "max_stars_repo_name": "afedynitch/corsika_reader", "max_stars_repo_head_hexsha": "984425bf2573667f1d36f7fcc218dca55283bac4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-19T14:02:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T20:22:22.000Z", "max_issues_repo_path": "src/corsika/LongFile.cxx", "max_issues_repo_name": "afedynitch/corsika_reader", "max_issues_repo_head_hexsha": "984425bf2573667f1d36f7fcc218dca55283bac4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-20T22:13:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T21:32:37.000Z", "max_forks_repo_path": "src/corsika/LongFile.cxx", "max_forks_repo_name": "icecube/corsika_reader", "max_forks_repo_head_hexsha": "839ca0c8da686489bb647ef48c00d56fccc3d562", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-05T16:08:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-05T16:08:30.000Z", "avg_line_length": 35.4403292181, "max_line_length": 141, "alphanum_fraction": 0.5648513702, "num_tokens": 4476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.032100707527228135, "lm_q1q2_score": 0.014054444564553584}}
{"text": "/*! \\file PhotonMap.inl\n *  \\author Jared Hoberock\n *  \\brief Inline file for PhotonMap.h.\n */\n\n#include \"PhotonMap.h\"\n#include <limits>\n#include <iostream>\n#include <boost/progress.hpp>\n\nPhotonMap\n  ::PhotonMap(void)\n{\n  ;\n} // end PhotonMap::PhotonMap()\n\nPhotonMap\n  ::PhotonMap(const std::vector<Point> &positions,\n              const std::vector<Vector> &wi,\n              const std::vector<Spectrum> &power)\n{\n  clear();\n\n  size_t num = std::min(positions.size(), std::min(wi.size(), power.size()));\n  for(size_t i = 0; i != num; ++i)\n  {\n    resize(size() + 1);\n    back().mPoint = positions[i];\n    back().mWi    = wi[i];\n    back().mPower = power[i];\n  } // end for i\n} // end PhotonMap::PhotonMap()\n\nvoid PhotonMap\n  ::sort(void)\n{\n  mNodes.resize(size());\n  sort(begin(), end());\n  //sort(0, size());\n} // end PhotonMap::sort()\n\nbool PhotonMap::PhotonSorter\n  ::operator()(const Photon &lhs, const Photon &rhs) const\n{\n  return lhs.mPoint[mAxis] < rhs.mPoint[mAxis];\n} // end PhotonSorter::operator()()\n\nvoid PhotonMap\n  ::sort(const size_t b, const size_t e)\n{\n  if(b >= e) return;\n\n  // find the bounds of the range\n  Point m, M;\n  findBounds(begin() + b, begin() + e, m, M);\n\n  // choose the largest axis to split\n  Vector diag = M - m;\n  diag *= diag;\n\n  unsigned int axis = 4;\n  float val = -1.0;\n  for(unsigned int i = 0; i < 3; ++i)\n  {\n    if(diag[i] > val)\n    {\n      val = diag[i];\n      axis = i;\n    } // end if\n  } // end for i\n\n  // sort on that axis\n  PhotonSorter sorter = {axis};\n  size_t mid = (e + b) / 2;\n  std::nth_element(&(*this)[b], &(*this)[mid], &(*this)[e], sorter);\n\n  // set the kd-node data\n  mNodes[mid].mSplitAxis = axis;\n  mNodes[mid].mSplitValue = (*this)[mid].mPoint[axis];\n\n  // recurse\n  sort(b, mid);\n  sort(mid + 1,e);\n} // end PhotonMap::sort()\n\nvoid PhotonMap\n  ::sort(const iterator &b, const iterator &e)\n{\n  int diff = static_cast<unsigned int>(e-b);\n  if(diff <= 0) return;\n\n  // find the bounds of the range\n  Point m, M;\n  findBounds(b, e, m, M);\n\n  // choose the largest axis to split\n  Vector diag = M - m;\n  diag *= diag;\n\n  unsigned int axis = 4;\n  float val = -1.0;\n  for(unsigned int i = 0; i < 3; ++i)\n  {\n    if(diag[i] > val)\n    {\n      val = diag[i];\n      axis = i;\n    } // end if\n  } // end for i\n\n  // sort on that axis\n  PhotonSorter sorter = {axis};\n  iterator mid = b + diff/2;\n  std::nth_element(b, mid, e, sorter);\n\n  // set the kd-node data\n  mNodes[static_cast<unsigned int>(mid - begin())].mSplitAxis = axis;\n  mNodes[static_cast<unsigned int>(mid - begin())].mSplitValue = mid->mPoint[axis];\n\n  // recurse\n  sort(b, mid);\n  sort(mid + 1,e);\n} // end PhotonMap::sort()\n\nvoid PhotonMap\n  ::findBounds(const iterator &b, const iterator &e,\n               Point &m, Point &M)\n{\n  float inf = std::numeric_limits<float>::infinity();\n  m = Point(inf,inf,inf);\n  M = -m;\n\n  for(iterator i = b;\n      i != e;\n      ++i)\n  {\n    for(unsigned int j = 0;\n        j != 3;\n        ++j)\n    {\n      if(i->mPoint[j] > m[j])\n      {\n        m[j] = i->mPoint[j];\n      } // end if\n      if(i->mPoint[j] < M[j])\n      {\n        M[j] = i->mPoint[j];\n      } // end if\n    } // end for j\n  } // end for i\n} // end PhotonMap::findBounds()\n\ntemplate<typename Visitor>\n  void PhotonMap\n    ::rangeQuery(const Point &p,\n                 float &maxDist2,\n                 Visitor &visitor) const\n{\n  rangeQuery(0, static_cast<unsigned int>(size()),\n             p, maxDist2,\n             visitor);\n} // end PhotonMap::rangeQuery()\n\ntemplate<typename Visitor>\n  void PhotonMap\n    ::rangeQuery(const unsigned int b,\n                 const unsigned int e,\n                 const Point &p,\n                 float &maxDist2,\n                 Visitor &visitor) const\n{\n  int diff = static_cast<int>(e-b);\n  if(diff <= 1) return;\n\n  unsigned int node = b + diff/2;\n\n  unsigned int axis = mNodes[node].mSplitAxis;\n  float splitValue = mNodes[node].mSplitValue;\n\n  float d2 = p[axis] - splitValue;\n  d2 *= d2;\n\n  if(p[axis] <= splitValue)\n  {\n    // go down the left side\n    rangeQuery(b, node, p, maxDist2, visitor);\n    if(d2 < maxDist2)\n    {\n      // the right side is close enough go down it\n      rangeQuery(node + 1, e, p, maxDist2, visitor);\n    } // end if\n  } // end if\n  else\n  {\n    // go down the right side\n    rangeQuery(node + 1, e, p, maxDist2, visitor);\n    if(d2 < maxDist2)\n    {\n      // the left side is close enough go down it\n      rangeQuery(b, node, p, maxDist2, visitor);\n    } // end if\n  } // end else\n\n  // visit the photon\n  d2 = (p - operator[](node).mPoint).norm2();\n  if(d2 <= maxDist2)\n  {\n    visitor(operator[](node), d2, maxDist2);\n  } // end if\n} // end PhotonMap::rangeQuery()\n\nstd::ostream &operator<<(std::ostream &os, const PhotonMap &pm)\n{\n  boost::progress_display progress(3 * pm.size());\n\n  os << \"Photons(\";\n\n  os << \"(\";\n  for(PhotonMap::const_iterator p = pm.begin();\n      p != pm.end();\n      ++p)\n  {\n    os << p->mPoint[0] << \",\";\n    os << p->mPoint[1] << \",\";\n\n    if(p + 1 == pm.end())\n    {\n      os << p->mPoint[2];\n    } // end if\n    else\n    {\n      os << p->mPoint[2] << \",\";\n    } // end else\n    ++progress;\n  } // end for p\n  os << \"),\";\n\n  os << \"(\";\n  for(PhotonMap::const_iterator p = pm.begin();\n      p != pm.end();\n      ++p)\n  {\n    os << p->mWi[0] << \",\";\n    os << p->mWi[1] << \",\";\n\n    if(p + 1 == pm.end())\n    {\n      os << p->mWi[2];\n    } // end if\n    else\n    {\n      os << p->mWi[2] << \",\";\n    } // end else\n\n    ++progress;\n  } // end for p\n  os << \"),\";\n\n  os << \"(\";\n  for(PhotonMap::const_iterator p = pm.begin();\n      p != pm.end();\n      ++p)\n  {\n    os << p->mPower[0] << \",\";\n    os << p->mPower[1] << \",\";\n\n    if(p + 1 == pm.end())\n    {\n      os << p->mPower[2];\n    } // end if\n    else\n    {\n      os << p->mPower[2] << \",\";\n    } // end else\n\n    ++progress;\n  } // end for p\n  os << \")\";\n\n  os << \")\";\n\n  // flush the stream\n  os.flush();\n  return os;\n} // end operator<<()\n\n", "meta": {"hexsha": "0b15c32ae372c3e04a5b11f8535a1c973801cf06", "size": 5926, "ext": "inl", "lang": "C++", "max_stars_repo_path": "records/PhotonMap.inl", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "records/PhotonMap.inl", "max_issues_repo_name": "jaredhoberock/gotham", "max_issues_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "records/PhotonMap.inl", "max_forks_repo_name": "jaredhoberock/gotham", "max_forks_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6480836237, "max_line_length": 83, "alphanum_fraction": 0.5296996288, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.035144850316819645, "lm_q1q2_score": 0.014051320268722167}}
{"text": "/*\n *  perfectphylotree.cpp\n *\n *   Created on: 28-sep-2015\n *       Author: M. El-Kebir\n */\n\n#include \"perfectphylotree.h\"\n#include \"perfectphylograph.h\"\n#include <lemon/connectivity.h>\n#include <boost/range/adaptor/reversed.hpp>\n\nnamespace gm {\n\nPerfectPhyloTree::PerfectPhyloTree(const PerfectPhyloMatrix& A,\n                                   const StateTreeVector& S)\n  : _A(A)\n  , _S(S)\n  , _T()\n  , _root(lemon::INVALID)\n  , _charStateToNode(_A.n(), NodeVector(_A.k(), lemon::INVALID))\n  , _nodeToCharState(_T, std::make_pair(-1, -1))\n  , _label(_T)\n{\n  const int n = _A.n();\n  const int k = _A.k();\n  \n  // add root node\n  _root = _T.addNode();\n  _nodeToCharState[_root] = std::make_pair(0, 0);\n  for (int c = 0; c < n; ++c)\n  {\n    _charStateToNode[c][0] = _root;\n  }\n  \n  // add the other n(k-1) nodes\n  for (int c = 0; c < n; ++c)\n  {\n    for (int i = 1; i < k; ++i)\n    {\n      if (_A.defined(c, i))\n      {\n        Node v_ci = _T.addNode();\n        _charStateToNode[c][i] = v_ci;\n        _nodeToCharState[v_ci] = std::make_pair(c, i);\n      }\n    }\n  }\n  \n  // add edges\n  PerfectPhyloGraph G(_A);\n//  G.writeDOT(std::cout);\n  PerfectPhyloGraph::BoolNodeMap visited(G.G(), false);\n  initArcs(G, G.root(), visited);\n}\n  \nPerfectPhyloTree::PerfectPhyloTree(const PerfectPhyloTree& other)\n  : _A(other._A)\n  , _S(other._S)\n  , _T()\n  , _root(lemon::INVALID)\n  , _charStateToNode(_A.n(), NodeVector(_A.k(), lemon::INVALID))\n  , _nodeToCharState(_T, std::make_pair(-1, -1))\n  , _label(_T)\n{\n  lemon::digraphCopy(other._T, _T)\n    .nodeMap(other._nodeToCharState, _nodeToCharState)\n    .nodeMap(other._label, _label)\n    .node(other._root, _root)\n    .run();\n  \n  for (NodeIt v_ci(_T); v_ci != lemon::INVALID; ++v_ci)\n  {\n    const IntPair& ci = _nodeToCharState[v_ci];\n    _charStateToNode[ci.first][ci.second] = v_ci;\n  }\n}\n  \nvoid PerfectPhyloTree::setLabels(const RealTensor& F)\n{\n  char buf[1024];\n  for (NodeIt v_ci(_T); v_ci != lemon::INVALID; ++v_ci)\n  {\n    const IntPair& ci = _nodeToCharState[v_ci];\n    if (ci.first == 0 && ci.second == 0)\n    {\n      snprintf(buf, 1024, \"(*,%s)\",\n               _S[ci.first].label(ci.second).c_str());\n    }\n    else\n    {\n      snprintf(buf, 1024, \"(%s,%s)\",\n               F.getColLabel(ci.first).c_str(),\n               _S[ci.first].label(ci.second).c_str());\n    }\n    _label[v_ci] = buf;\n  }\n}\n  \nint PerfectPhyloTree::edgeRecall(const PerfectPhyloTree& otherTree) const\n{\n  int recall = 0;\n  for (NodeIt v_dj(_T); v_dj != lemon::INVALID; ++v_dj)\n  {\n    const std::string& label_v_dj = _label[v_dj];\n    Node v_parent_dj = parent(v_dj);\n    if (v_parent_dj != lemon::INVALID)\n    {\n      const std::string& label_v_parent_dj = _label[v_parent_dj];\n      for (NodeIt u_dj(otherTree.T()); u_dj != lemon::INVALID; ++u_dj)\n      {\n        const std::string label_u_dj = otherTree.label(u_dj);\n        if (label_v_dj == label_u_dj)\n        {\n          Node u_parent_dj = otherTree.parent(u_dj);\n          \n          if (u_parent_dj != lemon::INVALID &&\n              otherTree.label(u_parent_dj) == label_v_parent_dj)\n          {\n            ++recall;\n          }\n        }\n      }\n    }\n  }\n  return recall;\n}\n  \nvoid PerfectPhyloTree::initArcs(const PerfectPhyloGraph& G,\n                                PerfectPhyloGraph::Node v_ci,\n                                PerfectPhyloGraph::BoolNodeMap& visited)\n{\n  assert(!visited[v_ci]);\n  \n  const IntPair& ci = G.nodeToCharState(v_ci);\n  \n  visited[v_ci] = true;\n  \n  typedef std::vector<IntPair> IntPairVector;\n  typedef std::vector<IntPairVector> IntPairMatrix;\n  \n  for (PerfectPhyloGraph::IncEdgeIt e(G.G(), v_ci); e != lemon::INVALID; ++e)\n  {\n    PerfectPhyloGraph::Node v_dj = G.G().oppositeNode(v_ci, e);\n    if (visited[v_dj])\n      continue;\n    \n    const IntPair& dj = G.nodeToCharState(v_dj);\n\n    // find lowest ancestor v_dl of v_dj\n    Node v_dl = _charStateToNode[ci.first][ci.second];\n    while (v_dl != _root)\n    {\n      if (_nodeToCharState[v_dl].first == dj.first)\n      {\n        break;\n      }\n      else\n      {\n        v_dl = _T.source(InArcIt(_T, v_dl));\n      }\n    }\n    \n    if (v_dl == _root)\n    {\n      if (_S[dj.first].isParent(0, dj.second))\n      {\n        _T.addArc(_charStateToNode[ci.first][ci.second], _charStateToNode[dj.first][dj.second]);\n        initArcs(G, v_dj, visited);\n      }\n    }\n    else\n    {\n      const IntPair& dl = _nodeToCharState[v_dl];\n      if (_S[dl.first].isParent(dl.second, dj.second))\n      {\n        _T.addArc(_charStateToNode[ci.first][ci.second], _charStateToNode[dj.first][dj.second]);\n        initArcs(G, v_dj, visited);\n      }\n    }\n  }\n}\n\nvoid PerfectPhyloTree::writeDOT(const RealTensor& F,\n                                const RealMatrix& U,\n                                const StringToStringMap& label2color,\n                                std::ostream& out) const\n{\n  out << \"digraph T {\" << std::endl;\n  \n  // collapse, assign representative\n  typedef Digraph::NodeMap<Node> NodeNodeMap;\n  NodeNodeMap representative(_T, lemon::INVALID);\n  BoolNodeMap used(_T, false);\n  \n  for (NodeIt v_ci(_T); v_ci != lemon::INVALID; ++v_ci)\n  {\n    const IntPair& ci =_nodeToCharState[v_ci];\n    const int row_idx = ci.first == 0 && ci.second == 0 ? 0 : F.n() * (ci.second - 1) + ci.first + 1;\n    \n    for (int p = 0; p < F.m(); ++p)\n    {\n      if (U(p, row_idx) >= 0.05)\n      {\n        used[v_ci] = true;\n        representative[v_ci] = v_ci;\n        break;\n      }\n    }\n    \n    if (lemon::countOutArcs(_T, v_ci) > 1)\n    {\n      representative[v_ci] = v_ci;\n    }\n  }\n  \n  for (NodeIt v_ci(_T); v_ci != lemon::INVALID; ++v_ci)\n  {\n    if (v_ci == _root)\n      continue;\n    \n    if (representative[v_ci] != lemon::INVALID)\n    {\n      // assign v_ci as the representative of all direct ancestors, with out-deg 1\n      Node v_dj = _T.source(InArcIt(_T, v_ci));\n      while (representative[v_dj] == lemon::INVALID)\n      {\n        representative[v_dj] = v_ci;\n        v_dj = _T.source(InArcIt(_T, v_dj));\n      }\n    }\n  }\n  \n  for (NodeIt v_ci(_T); v_ci != lemon::INVALID; ++v_ci)\n  {\n    if (representative[v_ci] != v_ci)\n      continue;\n    \n    StringVector label_v_ci;\n    bool mutation = false;\n    std::string color = \"black\";\n    Node v_dj = v_ci;\n    while (representative[v_dj] == v_ci)\n    {\n      if (v_dj == _root)\n      {\n        label_v_ci.push_back(\"*  (1,1,0)\");\n        mutation = true;\n        break;\n      }\n      else\n      {\n        const IntPair& dj =_nodeToCharState[v_dj];\n        if (!isMutationVertex(v_dj))\n        {\n          label_v_ci.push_back(\"<font color=\\\"maroon\\\">\" + F.getColLabel(dj.first) + \"  \" + _S[dj.first].label(dj.second) + \"</font>\");\n        }\n        else\n        {\n          label_v_ci.push_back(F.getColLabel(dj.first) + \"  \" + _S[dj.first].label(dj.second));\n          mutation = true;\n          auto label_it = label2color.find(F.getColLabel(dj.first));\n          if (label_it != label2color.end())\n          {\n            color = label_it->second;\n          }\n        }\n      }\n      v_dj = _T.source(InArcIt(_T, v_dj));\n    }\n    \n    out << \"\\t\" << _T.id(v_ci) << \" [label=<\";\n    bool first = true;\n    for (const std::string& label : boost::adaptors::reverse(label_v_ci))\n    {\n      if (first)\n        first = false;\n      else\n        out << \"<BR/>\";\n      \n      out << label;\n    }\n    out << \">\";\n    \n    if (mutation)\n    {\n      out << \",penwidth=5,color=\" << color;\n    }\n    else\n    {\n      out << \",penwidth=3,style=dashed\";\n    }\n\n//    const IntPair& ci =_nodeToCharState[v_ci];\n//    if (v_ci == _root)\n//    {\n//      out << \"\\t\" << _T.id(v_ci) << \" [label=\\\"*\\\\n\" << _S[ci.first].label(ci.second) << \"\\\",penwidth=5\";\n//    }\n//    else\n//    {\n//      out << \"\\t\" << _T.id(v_ci) << \" [label=\\\"\" << F.getColLabel(ci.first) << \"  \" << _S[ci.first].label(ci.second) << \"\\\"\";\n//      \n//      if (!isMutationVertex(v_ci))\n//      {\n//        out << \",fontcolor=maroon,penwidth=3,style=dashed\";\n//      }\n//      else\n//      {\n//        auto label_it = label2color.find(F.getColLabel(ci.first));\n//        if (label_it != label2color.end())\n//        {\n//          out << \",penwidth=5,color=\" << label_it->second;\n//        }\n//      }\n//    }\n//    \n//    if (!used[v_ci])\n//    {\n//      out << \",shape=box\";\n//    }\n    \n    out << \"]\" << std::endl;\n  }\n  \n  for (ArcIt a_cidj(_T); a_cidj != lemon::INVALID; ++a_cidj)\n  {\n    Node v_ci = _T.source(a_cidj);\n    if (representative[v_ci] != v_ci)\n      continue;\n    \n    Node v_dj = _T.target(a_cidj);\n    out << \"\\t\" << _T.id(v_ci) << \" -> \" << _T.id(representative[v_dj]) << std::endl;\n//    out << \"\\t\" << _T.id(v_ci) << \" -> \" << _T.id(v_dj) << std::endl;\n  }\n  \n  out << \"}\" << std::endl;\n}\n  \nvoid PerfectPhyloTree::writeDOT(std::ostream& out) const\n{\n  out << \"digraph T {\" << std::endl;\n  \n  for (NodeIt v_ci(_T); v_ci != lemon::INVALID; ++v_ci)\n  {\n    const IntPair& ci =_nodeToCharState[v_ci];\n    if (v_ci == _root)\n    {\n      out << \"\\t\" << _T.id(v_ci) << \" [label=\\\"*\\\\n\" << _S[ci.first].label(ci.second) << \"\\\",penwidth=5\";\n    }\n    else\n    {\n      out << \"\\t\" << _T.id(v_ci) << \" [label=\\\"\" << ci.first << \"\\\\n\" << _S[ci.first].label(ci.second) << \"\\\"\";\n      \n      if (!isMutationVertex(v_ci))\n      {\n        out << \",color=red\";\n      }\n    }\n    \n    out << \"]\" << std::endl;\n  }\n  \n  for (ArcIt a_cidj(_T); a_cidj != lemon::INVALID; ++a_cidj)\n  {\n    Node v_ci = _T.source(a_cidj);\n    Node v_dj = _T.target(a_cidj);\n    out << \"\\t\" << _T.id(v_ci) << \" -> \" << _T.id(v_dj) << std::endl;\n  }\n  \n  out << \"}\" << std::endl;\n}\n  \nstd::ostream& operator<<(std::ostream& out, const PerfectPhyloTree& T)\n{\n  out << T.A();\n  for (int c = 0; c < T.A().n(); ++c)\n  {\n    out << T.S(c);\n  }\n  return out;\n}\n  \nstd::istream& operator>>(std::istream& in, PerfectPhyloTree& T)\n{\n  PerfectPhyloMatrix A;\n  in >> A;\n  \n  // who's owning S? T is.\n  return in;\n}\n  \n} // namespace gm\n", "meta": {"hexsha": "7770b33c30193dfe5e4d185f48c9de983efe8593", "size": 9894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spruce/perfectphylotree.cpp", "max_stars_repo_name": "elkebir-group/machina", "max_stars_repo_head_hexsha": "822330bdd26819d861b7dda1f9e97a5ca0f6bb38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-04-14T18:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T14:06:11.000Z", "max_issues_repo_path": "src/spruce/perfectphylotree.cpp", "max_issues_repo_name": "elkebir-group/machina", "max_issues_repo_head_hexsha": "822330bdd26819d861b7dda1f9e97a5ca0f6bb38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2018-04-24T09:42:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T16:59:27.000Z", "max_forks_repo_path": "src/spruce/perfectphylotree.cpp", "max_forks_repo_name": "elkebir-group/machina", "max_forks_repo_head_hexsha": "822330bdd26819d861b7dda1f9e97a5ca0f6bb38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-07-18T11:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T14:06:14.000Z", "avg_line_length": 25.1755725191, "max_line_length": 135, "alphanum_fraction": 0.5355771174, "num_tokens": 3153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.03021458641245071, "lm_q1q2_score": 0.014046808701545368}}
{"text": "/** ////////////////////////////////////////////////////////////////\r\n\r\n    *** Hyper C++ - A simplified C++ experience ***\r\n\r\n        Yet (another) open source library for C++\r\n\r\n        Original Copyright (C) Damian Tran 2019\r\n\r\n        By aiFive Technologies, Inc. for developers\r\n\r\n    Copying and redistribution of this code is freely permissible.\r\n    Inclusion of the above notice is preferred but not required.\r\n\r\n    This software is provided AS IS without any expressed or implied\r\n    warranties.  By using this code, and any modifications and\r\n    variants arising thereof, you are assuming all liabilities and\r\n    risks that may be thus associated.\r\n\r\n////////////////////////////////////////////////////////////////  **/\r\n\r\n#pragma once\r\n\r\n#ifndef HYPER_ALGORITHM\r\n#define HYPER_ALGORITHM\r\n\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <iostream>\r\n#include <cmath>\r\n#include <chrono>\r\n#include <ctime>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include <limits.h>\r\n#include <math.h>\r\n#include <cmath>\r\n#include <typeinfo>\r\n#include <unistd.h>\r\n#include <sstream>\r\n#include <cstdarg>\r\n#include <exception>\r\n#include <random>\r\n#include <array>\r\n#include <map>\r\n\r\n#if defined WIN32 || defined _WIN32\r\n#include <thread>\r\n#include <mutex>\r\n#else\r\n#include <thread>\r\n#include <mutex>\r\n#endif\r\n\r\n#include <boost/math/distributions/students_t.hpp>\r\n#include <boost/predef.h>\r\n\r\ninline constexpr std::uint8_t operator\"\" _U8(unsigned long long uint)\r\n{\r\n    return static_cast<std::uint8_t>(uint);\r\n}\r\ninline constexpr std::uint8_t operator\"\" _BIT(unsigned long long uint)\r\n{\r\n    return static_cast<std::uint8_t>(uint);\r\n}\r\ninline constexpr unsigned char operator\"\" _BYTE(unsigned long long uint)\r\n{\r\n    return static_cast<unsigned char>(uint);\r\n}\r\n\r\n#define OBJ_CLASS_VOID              0_U8\r\n#define OBJ_CLASS_INT_8             1_U8\r\n#define OBJ_CLASS_INT_16            2_U8\r\n#define OBJ_CLASS_INT_32            3_U8\r\n#define OBJ_CLASS_INT_64            4_U8\r\n#define OBJ_CLASS_UINT_8            5_U8\r\n#define OBJ_CLASS_UINT_16           6_U8\r\n#define OBJ_CLASS_UINT_32           7_U8\r\n#define OBJ_CLASS_UINT_64           8_U8\r\n#define OBJ_CLASS_FLOAT             9_U8\r\n#define OBJ_CLASS_DOUBLE            10_U8\r\n#define OBJ_CLASS_CHAR              11_U8\r\n#define OBJ_CLASS_UCHAR             12_U8\r\n#define OBJ_CLASS_STRING            13_U8\r\n#define OBJ_CLASS_WCHAR             14_U8\r\n\r\n#define GET_VARIABLE_NAME(var)      (#var)\r\n\r\n#define NULLBYTE                    0_BYTE\r\n#define FULLBYTE                    255_BYTE\r\n\r\n#define ALPHABET        \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n#define DIGITS          \"0123456789\"\r\n#define PUNCTUATION     \".,;\\\"'()!&\\\\/-?\"\r\n#define CODE_CHAR       \"<>[]{}\"\r\n#define OPERATOR_CHAR   \"-+/\\\\*\"\r\n#define HASH_CHAR       \"@#$%\"\r\n#define MISC_CHAR       \"^`\"\r\n\r\n#define TIME_NOW                    std::chrono::high_resolution_clock::now()\r\n#define REFRESH_4_FPS               1.0f/4U\r\n#define REFRESH_6_FPS               1.0f/6U\r\n#define REFRESH_12_FPS              1.0f/12U\r\n#define REFRESH_24_FPS              1.0f/24U\r\n#define REFRESH_30_FPS              1.0f/30U\r\n#define REFRESH_60_FPS              1.0f/60U\r\n#define REFRESH_100_FPS             1.0f/100U\r\n#define REFRESH_120_FPS             1.0f/120U\r\n\r\n#define MONITOR_STATE_NONE          NULLBYTE\r\n#define MONITOR_STATE_MAX           0b1\r\n#define MONITOR_STATE_MIN           0b10\r\n#define MONITOR_STATE_ZERO          0b100\r\n#define MONITOR_STATE_STOCHASTIC    0b10000\r\n#define MONITOR_STATE_RECORD        0b100000\r\n#define MONITOR_STATE_VERBOSE       0b1000000\r\n#define MONITOR_STATE_ACTIVE        0b10000000\r\n\r\n#define OPERATOR_EQUAL              0b1\r\n#define OPERATOR_GREATER            0b10\r\n#define OPERATOR_LESS               0b100\r\n#define OPERATOR_INCREASING         0b1000\r\n#define OPERATOR_DECREASING         0b10000\r\n#define OPERATOR_EXTREME            0b100000\r\n\r\n#define DATA_TYPE_UNKNOWN           0\r\n#define DATA_TYPE_NUMERIC           1\r\n#define DATA_TYPE_VERBAL            2\r\n#define DATA_TYPE_IMAGE             3\r\n#define DATA_TYPE_VIDEO             4\r\n#define DATA_TYPE_SOUND             5\r\n\r\n#define STATS_TWO_TAILED        0_BIT\r\n#define STATS_UPPER_TAIL        1_BIT\r\n#define STATS_LOWER_TAIL        2_BIT\r\n\r\n#define PI                          acos(-1.0L)\r\n#define MIN_PRECISION               1e-16f\r\n#define SQRT2                       1.4142135623730950\r\n#define SQRT2PI                     2,5066282746310005\r\n\r\n// Typedefs\r\n\r\nnamespace hyperC\r\n{\r\n\r\ntypedef unsigned char BYTE;\r\n\r\ntypedef uint8_t UINT8;\r\ntypedef uint8_t ByteNum;\r\n\r\ntypedef uint16_t UINT16;\r\n\r\ntemplate<class T> using vMatrix = std::vector<std::vector<T>>;\r\ntemplate<class T> using vMatrix3D = std::vector<std::vector<std::vector<T>>>;\r\ntemplate<class T> using itr = typename std::vector<T>::iterator;\r\ntemplate<class T> using c_itr = typename std::vector<T>::const_iterator;\r\n\r\ntypedef vMatrix<float> numVector;\r\ntypedef vMatrix<float> numMatrix;\r\n\r\n// Input/Output\r\n\r\ntemplate<typename T> void writeData(const T& data, FILE* output)\r\n{\r\n    fwrite(&data, 1, sizeof(T), output);\r\n}\r\n\r\ntemplate<typename T> void writeVector(const std::vector<T>& V, FILE* output)\r\n{\r\n    uint64_t L = V.size();\r\n    fwrite(&L, 1, sizeof(L), output);\r\n    fwrite(V.data(), V.size(), sizeof(T), output);\r\n}\r\n\r\ntemplate<typename T> void writeMatrix(const std::vector<T>& M, FILE* output)\r\n{\r\n    uint64_t L = M.size();\r\n    fwrite(&L, 1, sizeof(L), output);\r\n    for(auto& V : M)\r\n    {\r\n        writeVector(V, output);\r\n    }\r\n}\r\n\r\ninline void writeString(const std::string& s, FILE* output)\r\n{\r\n    uint64_t string_size = s.size();\r\n    fwrite(&string_size, 1, sizeof(string_size), output);\r\n    fwrite(s.c_str(), 1, s.size(), output);\r\n}\r\n\r\ntemplate<> inline void writeData<std::string>(const std::string& data, FILE* output)\r\n{\r\n    writeString(data, output);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid writeData(const std::vector<T>& data, FILE* output)\r\n{\r\n    writeVector(data, output);\r\n}\r\n\r\ntemplate<typename T> void readData(T& inputVar, FILE* inputFile)\r\n{\r\n    fread(&inputVar, 1, sizeof(T), inputFile);\r\n}\r\n\r\ntemplate<typename T> void readVector(std::vector<T>& output, FILE* inputFile)\r\n{\r\n    uint64_t inSIZE;\r\n    fread(&inSIZE, 1, sizeof(inSIZE), inputFile);\r\n    T* inputData = new T[inSIZE];\r\n    fread(inputData, inSIZE, sizeof(T), inputFile);\r\n    output.reserve(output.size() + inSIZE);\r\n    for(size_t i = 0; i < inSIZE; ++i)\r\n    {\r\n        output.push_back(inputData[i]);\r\n    }\r\n    delete[] inputData;\r\n}\r\n\r\n\r\n\r\ninline void readString(std::string& output, FILE* inFILE)\r\n{\r\n    output.clear();\r\n    uint64_t inSIZE;\r\n    fread(&inSIZE, 1, sizeof(inSIZE), inFILE);\r\n    char* inputData = new char[inSIZE+1];\r\n    inputData[inSIZE] = '\\0';\r\n    fread(inputData, 1, inSIZE, inFILE);\r\n    output = inputData;\r\n    delete[] inputData;\r\n}\r\n\r\ntemplate<> inline void readData<std::string>(std::string& inputVar, FILE* inputFile)\r\n{\r\n    readString(inputVar, inputFile);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid readData(std::vector<T>& inputVar, FILE* inputFILE)\r\n{\r\n    readVector(inputVar, inputFILE);\r\n}\r\n\r\ninline void readVector(std::vector<std::string>& output, FILE* inFILE)\r\n{\r\n    output.clear();\r\n    uint64_t inSIZE;\r\n    fread(&inSIZE, 1, sizeof(inSIZE), inFILE);\r\n    output.reserve(output.size() + inSIZE);\r\n    for(size_t i = 0; i < inSIZE; ++i)\r\n    {\r\n        output.emplace_back();\r\n        readString(output.back(), inFILE);\r\n    }\r\n}\r\n\r\ntemplate<typename T>\r\nvoid readMatrix(std::vector<std::vector<T>>& M, FILE* inFILE)\r\n{\r\n    uint64_t L;\r\n    fread(&L, 1, sizeof(L), inFILE);\r\n    M.resize(L);\r\n    for(auto& V : M)\r\n    {\r\n        readVector(V, inFILE);\r\n    }\r\n}\r\n\r\ninline void writeVector(const std::vector<std::string>& V, FILE* output)\r\n{\r\n    uint64_t L = V.size();\r\n    fwrite(&L, 1, sizeof(L), output);\r\n    const c_itr<std::string> itEND = V.end();\r\n    for(c_itr<std::string> it = V.begin(); it != itEND; ++it)\r\n    {\r\n        writeString(*it, output);\r\n    }\r\n}\r\n\r\ntemplate<typename key_t, typename value_t> void writeMap(const std::map<key_t, value_t>& M, FILE* outFILE)\r\n{\r\n\r\n    uint64_t L = M.size();\r\n    fwrite(&L, sizeof(L), 1, outFILE);\r\n    if(L == 0) return;\r\n\r\n    auto endIT = M.end();\r\n    for(auto IT = M.begin(); IT != endIT; ++IT)\r\n    {\r\n\r\n        writeData(IT->first, outFILE);\r\n        writeData(IT->second, outFILE);\r\n\r\n    }\r\n}\r\n\r\ntemplate<typename key_t, typename value_t>\r\nvoid readMap(std::map<key_t, value_t>& M, FILE* inFILE)\r\n{\r\n\r\n    uint64_t L;\r\n    fread(&L, sizeof(L), 1, inFILE);\r\n\r\n    if(L == 0) return;\r\n\r\n    M.clear();\r\n\r\n    key_t tmp_key;\r\n    value_t tmp_value;\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        readData(tmp_key, inFILE);\r\n        readData(tmp_value, inFILE);\r\n\r\n        M.emplace(tmp_key, tmp_value);\r\n    }\r\n\r\n}\r\n\r\n// File manipulation\r\n\r\ninline size_t file_size(FILE* file)\r\n{\r\n    fpos_t pos;\r\n    fgetpos(file, &pos);\r\n\r\n    fseek(file, 0, SEEK_END);\r\n    size_t output = ftell(file);\r\n    fsetpos(file, &pos);\r\n\r\n    return output;\r\n}\r\n\r\ninline bool check_hash(FILE* file, const std::string& hash)\r\n{\r\n    if(hash.empty()) return true;\r\n\r\n    // Checks the hash code and sets the stream pointer to the position following\r\n    size_t fileSIZE = file_size(file);\r\n    if(fileSIZE < (2*hash.size()))\r\n    {\r\n        return false;\r\n    }\r\n\r\n    char newHash[hash.size() + 1];\r\n    newHash[hash.size()] = '\\0';\r\n    fread(newHash, sizeof(char), hash.size(), file);\r\n    if(std::string(newHash) != hash)\r\n    {\r\n        fclose(file);\r\n        return false;\r\n    }\r\n\r\n    fpos_t initPos;\r\n    fgetpos(file, &initPos);\r\n\r\n    fseek(file, 0, SEEK_END);\r\n    fseek(file, hash.size(), SEEK_SET);\r\n\r\n    fread(newHash, sizeof(char), hash.size(), file);\r\n    if(std::string(newHash) != hash)\r\n    {\r\n        fclose(file);\r\n        return false;\r\n    }\r\n\r\n    fsetpos(file, &initPos);\r\n\r\n    return true;\r\n}\r\n\r\n// Classes\r\n\r\ntemplate<class T> constexpr char getTypeID(const T& item)\r\n{\r\n    return typeid(item).name()[0];\r\n}\r\n\r\ntemplate<class T> constexpr char getTypeID()\r\n{\r\n    return typeid(T).name()[0];\r\n}\r\n\r\nstruct GenDataVar\r\n{\r\n\r\n    void* data;\r\n    char dataClass;\r\n    UINT16 dataSize;\r\n\r\n    GenDataVar():\r\n        dataClass(getTypeID<void>()),\r\n        dataSize(0) { }\r\n    GenDataVar(const uint32_t& val)\r\n    {\r\n        uint32_t* newVal = new uint32_t(val);\r\n        data = (void*)newVal;\r\n        dataClass = getTypeID(val);\r\n        dataSize = sizeof(val);\r\n    }\r\n    GenDataVar(const int32_t& val)\r\n    {\r\n        int32_t* newVal = new int32_t(val);\r\n        data = (void*)newVal;\r\n        dataClass = getTypeID(val);\r\n        dataSize = sizeof(val);\r\n    }\r\n    GenDataVar(const bool& val)\r\n    {\r\n        bool* newVal = new bool(val);\r\n        data = (void*)newVal;\r\n        dataClass = getTypeID(val);\r\n        dataSize = sizeof(val);\r\n    }\r\n    GenDataVar(const float& val)\r\n    {\r\n        float* newVal = new float(val);\r\n        data = (void*)newVal;\r\n        dataClass = getTypeID(val);\r\n        dataSize = sizeof(val);\r\n    }\r\n    GenDataVar(const std::string& val)\r\n    {\r\n        dataSize = val.size() + 1;\r\n        char* newStr = new char[dataSize];\r\n        newStr[dataSize-1] = '\\0';\r\n        memcpy(newStr, val.c_str(), dataSize-1);\r\n        dataClass = getTypeID<char>();\r\n        data = (void*)newStr;\r\n    }\r\n    GenDataVar(const char* val)\r\n    {\r\n        dataSize = 1;\r\n        while(val[dataSize-1] != '\\0')\r\n        {\r\n            ++dataSize;\r\n        }\r\n        char* newStr = new char[dataSize];\r\n        memcpy(newStr, val, dataSize);\r\n        dataClass = getTypeID<char>();\r\n        data = (void*)newStr;\r\n    }\r\n\r\n    inline size_t size() const\r\n    {\r\n        return (size_t)dataSize;\r\n    }\r\n\r\n    GenDataVar& operator=(const char* str)\r\n    {\r\n        if(dataSize > 0) clear();\r\n        dataSize = 1;\r\n        while(str[dataSize-1] != '\\0')\r\n        {\r\n            ++dataSize;\r\n        }\r\n        char* newStr = new char[dataSize];\r\n        memcpy(newStr, str, dataSize);\r\n        dataClass = getTypeID<char>();\r\n        data = (void*)newStr;\r\n        return *this;\r\n    }\r\n\r\n    GenDataVar& operator=(const std::string& other)\r\n    {\r\n        return (*this = other.c_str());\r\n    }\r\n\r\n    template<typename T> GenDataVar& operator=(const T& other)\r\n    {\r\n        if(dataClass != getTypeID(other))\r\n        {\r\n            T* newVal = new T(other);\r\n            this->data = (void*)newVal;\r\n            this->dataClass = getTypeID<T>();\r\n        }\r\n        else\r\n        {\r\n            *((T*)data) = other;\r\n        }\r\n        dataSize = sizeof(other);\r\n\r\n        return *this;\r\n    }\r\n\r\n    GenDataVar& operator=(const GenDataVar& other)\r\n    {\r\n        clear();\r\n        dataClass = other.dataClass;\r\n        dataSize = other.dataSize;\r\n        if(dataClass == getTypeID<char>())\r\n        {\r\n            char* newStr = new char[dataSize];\r\n            memcpy(newStr, other.data, dataSize);\r\n            data = (void*)newStr;\r\n        }\r\n        else if(dataClass == getTypeID<uint32_t>())\r\n        {\r\n            uint32_t* newVal = new uint32_t(other.getValue<uint32_t>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<float>())\r\n        {\r\n            float* newVal = new float(other.getValue<float>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<bool>())\r\n        {\r\n            bool* newVal = new bool(other.getValue<bool>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<int32_t>())\r\n        {\r\n            int32_t* newVal = new int32_t(other.getValue<int32_t>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<uint8_t>())\r\n        {\r\n            uint8_t* newVal = new uint8_t(other.getValue<uint8_t>());\r\n            data = (void*)newVal;\r\n        }\r\n        return *this;\r\n    }\r\n\r\n    inline void write(FILE* outFILE) const\r\n    {\r\n        fwrite(&dataClass, 1, sizeof(char), outFILE);\r\n        fwrite(&dataSize, 1, sizeof(uint16_t), outFILE);\r\n        if(dataSize > 0)\r\n        {\r\n            fwrite(data, 1, dataSize, outFILE);\r\n        }\r\n    }\r\n\r\n    inline void read(FILE* inFILE)\r\n    {\r\n        if(dataSize > 0) clear();\r\n        fread(&dataClass, 1, sizeof(char), inFILE);\r\n        fread(&dataSize, 1, sizeof(uint16_t), inFILE);\r\n        if(dataSize > 0)\r\n        {\r\n            char* newData = new char[dataSize];\r\n            fread(newData, 1, dataSize, inFILE);\r\n            data = (void*)newData;\r\n        }\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream& output, const GenDataVar& other)\r\n    {\r\n        if(other.dataClass == getTypeID<uint32_t>()) output << (*(uint32_t*)other.data);\r\n        else if(other.dataClass == getTypeID<float>()) output << (*(float*)other.data);\r\n        else if(other.dataClass == getTypeID<bool>())\r\n        {\r\n            if(*(bool*)other.data) output << \"TRUE\";\r\n            else output << \"FALSE\";\r\n        }\r\n        else if(other.dataClass == getTypeID<char>()) output << ((char*)other.data);\r\n        else if(other.dataClass == getTypeID<int32_t>()) output << (*(int32_t*)other.data);\r\n        else if(other.dataClass == getTypeID<double>()) output << (*(double*)other.data);\r\n        else if(other.dataClass == getTypeID<int8_t>()) output << (*(int8_t*)other.data);\r\n        else if(other.dataClass == getTypeID<int16_t>()) output << (*(int16_t*)other.data);\r\n        else if(other.dataClass == getTypeID<int64_t>()) output << (*(int64_t*)other.data);\r\n        else if(other.dataClass == getTypeID<uint8_t>()) output << (*(uint8_t*)other.data);\r\n        else if(other.dataClass == getTypeID<uint16_t>()) output << (*(uint16_t*)other.data);\r\n        else if(other.dataClass == getTypeID<uint64_t>()) output << (*(uint64_t*)other.data);\r\n        else if(other.dataClass == getTypeID<wchar_t>()) output << ((wchar_t*)other.data);\r\n        return output;\r\n    }\r\n\r\n    inline void clear()\r\n    {\r\n        if(dataClass == getTypeID<uint32_t>()) delete((uint32_t*)data);\r\n        else if(dataClass == getTypeID<float>()) delete((float*)data);\r\n        else if(dataClass == getTypeID<bool>()) delete((bool*)data);\r\n        else if(dataClass == getTypeID<int32_t>()) delete((int32_t*)data);\r\n        else if(dataClass == getTypeID<double>()) delete((double*)data);\r\n        else if(dataClass == getTypeID<int8_t>()) delete((int8_t*)data);\r\n        else if(dataClass == getTypeID<int16_t>()) delete((int16_t*)data);\r\n        else if(dataClass == getTypeID<int64_t>()) delete((int64_t*)data);\r\n        else if(dataClass == getTypeID<uint8_t>()) delete((uint8_t*)data);\r\n        else if(dataClass == getTypeID<uint16_t>()) delete((uint16_t*)data);\r\n        else if(dataClass == getTypeID<uint64_t>()) delete((uint64_t*)data);\r\n        else if(dataClass == getTypeID<char>()) delete((char*)data);\r\n        else if(dataClass == getTypeID<wchar_t>()) delete((wchar_t*)data);\r\n        dataClass = getTypeID<void>();\r\n        dataSize = 0;\r\n    }\r\n\r\n    inline std::string getString() const\r\n    {\r\n        return std::string((char*)data);    // MUST use for strings\r\n    }\r\n    template<typename T> inline T getValue() const\r\n    {\r\n        if(dataSize < 1) return T();\r\n        return *((T*)data);\r\n    }\r\n    template<typename T> inline void putValue(T& item)\r\n    {\r\n        item = getValue<T>();\r\n    }\r\n\r\n    GenDataVar(const GenDataVar& other):\r\n        dataClass(other.dataClass),\r\n        dataSize(other.dataSize)\r\n    {\r\n        if(dataClass == getTypeID<uint32_t>())\r\n        {\r\n            uint32_t* newVal = new uint32_t(other.getValue<uint32_t>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<float>())\r\n        {\r\n            float* newVal = new float(other.getValue<float>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<bool>())\r\n        {\r\n            bool* newVal = new bool(other.getValue<bool>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<char>())\r\n        {\r\n            char* newStr = new char[dataSize];\r\n            memcpy(newStr, other.data, dataSize);\r\n            data = (void*)newStr;\r\n        }\r\n        else if(dataClass == getTypeID<int32_t>())\r\n        {\r\n            int32_t* newVal = new int32_t(other.getValue<int32_t>());\r\n            data = (void*)newVal;\r\n        }\r\n        else if(dataClass == getTypeID<uint8_t>())\r\n        {\r\n            uint8_t* newVal = new uint8_t(other.getValue<uint8_t>());\r\n            data = (void*)newVal;\r\n        }\r\n    }\r\n\r\n    ~GenDataVar()\r\n    {\r\n        clear();\r\n    }\r\n};\r\n\r\nstd::string capitalized(std::string s);\r\nstd::string non_capitalized(std::string s);\r\n\r\ntemplate<typename T, typename N> bool anyEqual(const T& item, const std::vector<N> &V)\r\n{\r\n    for(auto& x : V)\r\n    {\r\n        if(x == item) return true;\r\n    }\r\n    return false;\r\n}\r\n\r\nclass GenDataStruct\r\n{\r\nprotected:\r\n\r\n    std::vector<std::string> tags;\r\n    std::vector<GenDataVar> data;\r\n\r\npublic:\r\n\r\n    template<typename T> void addEntry(const std::string& tag, const T& newData)\r\n    {\r\n        if(anyEqual(tag, tags))\r\n        {\r\n            (*this)[tag] = newData;\r\n        }\r\n        else\r\n        {\r\n            tags.push_back(tag);\r\n            data.emplace_back();\r\n            data.back() = newData;\r\n        }\r\n    }\r\n    inline bool entryExists(const std::string& tag) const\r\n    {\r\n        for(auto& t : tags)\r\n        {\r\n            if(t == tag) return true;\r\n        }\r\n        return false;\r\n    }\r\n\r\n    inline void setEntries(const std::vector<std::string>& entries)\r\n    {\r\n        tags = entries;\r\n        data.resize(entries.size());\r\n    }\r\n\r\n    inline bool save(const std::string& filename, const std::string& hash = \"\") const\r\n    {\r\n        if(!access(filename.c_str(), F_OK))\r\n        {\r\n            if(access(filename.c_str(), W_OK)) return false;\r\n        }\r\n\r\n        FILE* outFILE = fopen(filename.c_str(), \"wb\");\r\n\r\n        if(!hash.empty())\r\n        {\r\n            fwrite(hash.c_str(), hash.size(), sizeof(char), outFILE);\r\n        }\r\n\r\n        write(outFILE);\r\n\r\n        if(!hash.empty())\r\n        {\r\n            fwrite(hash.c_str(), hash.size(), sizeof(char), outFILE);\r\n        }\r\n\r\n        fclose(outFILE);\r\n\r\n        return true;\r\n    }\r\n\r\n    inline void write(FILE* outFILE) const\r\n    {\r\n        size_t L = data.size();\r\n        fwrite(&L, 1, sizeof(size_t), outFILE);\r\n        for(size_t i = 0; i < L; ++i)\r\n        {\r\n            writeString(tags[i], outFILE);\r\n            data[i].write(outFILE);\r\n        }\r\n    }\r\n\r\n    bool load(const std::string& filename, const std::string& hash = \"\")\r\n    {\r\n        if(access(filename.c_str(), F_OK))\r\n        {\r\n            std::cout << \"Load from \" << filename << \" failed\\n\";\r\n            std::cout << \"Error: \" << std::strerror(errno) << '\\n';\r\n            return false;\r\n        }\r\n\r\n        FILE* inFILE = fopen(filename.c_str(), \"rb\");\r\n\r\n        if(!check_hash(inFILE, hash)) return false;\r\n\r\n        read(inFILE);\r\n\r\n        fclose(inFILE);\r\n\r\n        return true;\r\n    }\r\n\r\n    inline void read(FILE* inFILE)\r\n    {\r\n        size_t L, matchIndex, j = 0;\r\n        fread(&L, 1, sizeof(size_t), inFILE);\r\n        for(size_t i = 0; i < L; ++i)\r\n        {\r\n            std::string varName;\r\n            readString(varName, inFILE);\r\n\r\n            matchIndex = UINT_MAX;\r\n            j = 0;\r\n\r\n            for(auto& tag : tags)\r\n            {\r\n                if(tag == varName) matchIndex = j;\r\n                ++j;\r\n            }\r\n\r\n            if(matchIndex != UINT_MAX)\r\n            {\r\n                data[matchIndex].read(inFILE);\r\n            }\r\n            else\r\n            {\r\n                tags.push_back(varName);\r\n                data.emplace_back();\r\n                data.back().read(inFILE);\r\n            }\r\n        }\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream& output, const GenDataStruct& other)\r\n    {\r\n        size_t L = other.size();\r\n        for(size_t i = 0; i < L; ++i)\r\n        {\r\n            output << std::left << '\\t' << std::setw(25) << capitalized(other.tags[i]) << '\\t' << other.data[i] << '\\n';\r\n        }\r\n        return output;\r\n    }\r\n\r\n    inline GenDataStruct& operator=(const std::vector<std::string>& variables)\r\n    {\r\n        tags = variables;\r\n        data.clear();\r\n        data.resize(tags.size());\r\n        return *this;\r\n    }\r\n\r\n    template<typename value_t> inline value_t getValue(const std::string& tag) const\r\n    {\r\n        unsigned int index = 0;\r\n        for(auto& T : tags)\r\n        {\r\n            if(T == tag)\r\n            {\r\n                return data[index].getValue<value_t>();\r\n            }\r\n            ++index;\r\n        }\r\n        throw std::invalid_argument(\"Parameter \\\"\" + tag + \"\\\" does not exist\");\r\n    }\r\n    inline std::string getString(const std::string& tag) const\r\n    {\r\n        unsigned int index = 0;\r\n        for(auto& T : tags)\r\n        {\r\n            if(T == tag)\r\n            {\r\n                return data[index].getString();\r\n            }\r\n            ++index;\r\n        }\r\n        throw std::invalid_argument(\"Parameter \\\"\" + tag + \"\\\" does not exist\");\r\n    }\r\n\r\n    inline GenDataVar& operator[](const unsigned int& index)\r\n    {\r\n        return data[index];\r\n    }\r\n    inline GenDataVar& operator[](const std::string& tag)\r\n    {\r\n        unsigned int index = 0;\r\n        for(auto& T : tags)\r\n        {\r\n            if(T == tag)\r\n            {\r\n                return data[index];\r\n            }\r\n            ++index;\r\n        }\r\n        throw std::invalid_argument(\"INVALID TAG: tag does not exist in generic data struct\");\r\n    }\r\n\r\n    inline std::string& getTag(const unsigned int& index)\r\n    {\r\n        return tags[index];\r\n    }\r\n    inline const std::vector<std::string>& params() const\r\n    {\r\n        return tags;\r\n    }\r\n\r\n    inline size_t size() const\r\n    {\r\n        return tags.size();\r\n    }\r\n    inline void clear()\r\n    {\r\n        tags.clear();\r\n        data.clear();\r\n    }\r\n\r\n    GenDataStruct() { }\r\n    GenDataStruct(const std::vector<std::string>& variables):\r\n        tags(variables),\r\n        data(variables.size()) { }\r\n\r\n    ~GenDataStruct() = default;\r\n\r\n};\r\n\r\ntemplate<class T>\r\nstruct Vector2\r\n{\r\n    T x, y;\r\n\r\n    friend std::ostream& operator<<(std::ostream& output, const Vector2<T>& other)\r\n    {\r\n        output << other.x << '\\t' << other.y;\r\n        return output;\r\n    }\r\n\r\n    template<typename T2>\r\n    inline bool operator==(const Vector2<T2>& other)\r\n    {\r\n        return ((this->x == other.x) && (this->y == other->y));\r\n    }\r\n    template<typename T2>\r\n    inline bool operator!=(const Vector2<T2>& other)\r\n    {\r\n        return !(this == other);\r\n    }\r\n    template<typename T2>\r\n    inline bool operator<(const Vector2<T2>& other)\r\n    {\r\n        return (x < other.x) && (y < other.y);\r\n    }\r\n    template<typename T2>\r\n    inline bool operator>(const Vector2<T2>& other)\r\n    {\r\n        return (x > other.x) && (y > other.y);\r\n    }\r\n    template<typename T2>\r\n    inline bool operator<=(const Vector2<T2>& other)\r\n    {\r\n        return !(*this > other);\r\n    }\r\n    template<typename T2>\r\n    inline bool operator>=(const Vector2<T2>& other)\r\n    {\r\n        return !(*this < other);\r\n    }\r\n\r\n    template<typename T2>\r\n    Vector2<T> operator+(const Vector2<T2>& other) const\r\n    {\r\n        return Vector2(x + other.x, y + other.y);\r\n    }\r\n    template<typename T2>\r\n    Vector2<T> operator-(const Vector2<T2>& other) const\r\n    {\r\n        return Vector2(x - other.x, y - other.y);\r\n    }\r\n    template<typename T2>\r\n    Vector2<T> operator*(const Vector2<T2>& other) const\r\n    {\r\n        return Vector2(x * other.x, y * other.y);\r\n    }\r\n    template<typename T2>\r\n    Vector2<T> operator/(const Vector2<T2>& other) const\r\n    {\r\n        return Vector2(x / other.x, y / other.y);\r\n    }\r\n\r\n    template<typename T2>\r\n    Vector2<T> operator+(const T2& other) const\r\n    {\r\n        return Vector2(x + other, y + other);\r\n    }\r\n    template<typename T2>\r\n    Vector2<T> operator-(const T2& other) const\r\n    {\r\n        return Vector2(x - other, y - other);\r\n    }\r\n    template<typename T2>\r\n    Vector2<T> operator*(const T2& other) const\r\n    {\r\n        return Vector2(x * other, y * other);\r\n    }\r\n    template<typename T2>\r\n    Vector2<T> operator/(const T2& other) const\r\n    {\r\n        return Vector2(x / other, y / other);\r\n    }\r\n\r\n    template<typename T2>\r\n    void operator+=(const Vector2<T2>& other)\r\n    {\r\n        x += other.x;\r\n        y += other.y;\r\n    }\r\n    template<typename T2>\r\n    void operator-=(const Vector2<T2>& other)\r\n    {\r\n        x -= other.x;\r\n        y -= other.y;\r\n    }\r\n    template<typename T2>\r\n    void operator*=(const Vector2<T2>& other)\r\n    {\r\n        x *= other.x;\r\n        y *= other.y;\r\n    }\r\n    template<typename T2>\r\n    void operator/=(const Vector2<T2>& other)\r\n    {\r\n        x /= other.x;\r\n        y /= other.y;\r\n    }\r\n\r\n    template<typename T2>\r\n    void operator+=(const T2& other)\r\n    {\r\n        x += other;\r\n        y += other;\r\n    }\r\n    template<typename T2>\r\n    void operator-=(const T2& other)\r\n    {\r\n        x -= other;\r\n        y -= other;\r\n    }\r\n    template<typename T2>\r\n    void operator*=(const T2& other)\r\n    {\r\n        x *= other;\r\n        y *= other;\r\n    }\r\n    template<typename T2>\r\n    void operator/=(const T2& other)\r\n    {\r\n        x /= other;\r\n        y /= other;\r\n    }\r\n\r\n    template <typename T2>\r\n    Vector2<T>& operator=(const Vector2<T2>& other)\r\n    {\r\n        x = other.x;\r\n        y = other.y;\r\n        return *this;\r\n    }\r\n    template <typename T2>\r\n    Vector2<T>& operator=(const T2& other)\r\n    {\r\n        x = other;\r\n        y = other;\r\n        return *this;\r\n    }\r\n\r\n    inline T& in()\r\n    {\r\n        return x;\r\n    }\r\n    inline T& out()\r\n    {\r\n        return y;\r\n    }\r\n\r\n    Vector2() { }\r\n    Vector2(T x, T y):x(x), y(y) { }\r\n    Vector2(std::vector<T>& xy): x(xy[0]), y(xy[1]) { }\r\n};\r\n\r\ntypedef Vector2<int> Vector2i;\r\ntypedef Vector2<unsigned int> Vector2u;\r\ntypedef Vector2<float> Vector2f;\r\n\r\ntemplate<typename T> void fwrite(const Vector2<T>& coords, FILE* outFILE)\r\n{\r\n    fwrite(&coords.x, 1, sizeof(T), outFILE);\r\n    fwrite(&coords.y, 1, sizeof(T), outFILE);\r\n}\r\n\r\ntemplate<typename T> void fread(const Vector2<T>& coords, FILE* inFILE)\r\n{\r\n    fread(&coords.x, 1, sizeof(T), inFILE);\r\n    fread(&coords.y, 1, sizeof(T), inFILE);\r\n}\r\n\r\ntemplate<class T>\r\nclass VectorPair\r\n{\r\npublic:\r\n\r\n    std::vector<T> x, y;\r\n\r\n    inline bool empty() const\r\n    {\r\n        return x.empty() || y.empty();\r\n    }\r\n\r\n    inline unsigned int size() const\r\n    {\r\n        return x.size() < y.size() ? x.size() : y.size();\r\n    }\r\n\r\n    inline void push_back(const Vector2<T>& newPair)\r\n    {\r\n        x.push_back(newPair.x);\r\n        y.push_back(newPair.y);\r\n    }\r\n    inline void push_back(const T& newX, const T& newY)\r\n    {\r\n        x.push_back(newX);\r\n        y.push_back(newY);\r\n    }\r\n\r\n    template<typename other_t>\r\n    void emplace_back(const Vector2<other_t>& newPair)\r\n    {\r\n        x.emplace_back(newPair.x);\r\n        y.emplace_back(newPair.y);\r\n    }\r\n\r\n    template<typename other_t>\r\n    void emplace_back(const other_t& newX, const other_t& newY)\r\n    {\r\n        x.emplace_back(newX);\r\n        y.emplace_back(newY);\r\n    }\r\n\r\n    inline void erase(const unsigned int index)\r\n    {\r\n        x.erase(x.begin() + index);\r\n        y.erase(y.begin() + index);\r\n    }\r\n    inline Vector2<T> operator[](const unsigned int index) const\r\n    {\r\n        return Vector2<T>(x[index], y[index]);\r\n    }\r\n    inline Vector2<T> back() const\r\n    {\r\n        return Vector2<T>(x.back(), y.back());\r\n    }\r\n    inline Vector2<T> front() const\r\n    {\r\n        return Vector2<T>(x.front(), y.front());\r\n    }\r\n\r\n    inline void clear()\r\n    {\r\n        x.clear();\r\n        y.clear();\r\n    }\r\n\r\n    inline void resize(const size_t& newSize, const T& new_template = T())\r\n    {\r\n\r\n        x.resize(newSize, new_template);\r\n        y.resize(newSize, new_template);\r\n\r\n    }\r\n\r\n    inline void insert(const unsigned int& index, const T& newX, const T& newY)\r\n    {\r\n        x.insert(x.begin() + index, newX);\r\n        y.insert(y.begin() + index, newY);\r\n    }\r\n\r\n    inline void remove(const Vector2<T>& ref)\r\n    {\r\n        size_t L = this->size();\r\n        for(size_t i = 0; i < L;)\r\n        {\r\n            if((x[i] == ref.x) && (y[i] == ref.y))\r\n            {\r\n                erase(i);\r\n                --L;\r\n            }\r\n            else ++i;\r\n        }\r\n    }\r\n\r\n    VectorPair() {}\r\n    VectorPair(const std::vector<T>& x, const std::vector<T>& y): x(x), y(y) { }\r\n\r\n};\r\n\r\ntemplate<typename T1, typename T2>\r\nvoid append(VectorPair<T1>& output, const VectorPair<T2>& input)\r\n{\r\n\r\n    size_t L = output.size();\r\n    output.resize(output.size() + input.size());\r\n\r\n    for(size_t i = L, j = 0; i < output.size(); ++i, ++j)\r\n    {\r\n\r\n        output.x[i] = input.x[j];\r\n        output.y[i] = input.y[j];\r\n\r\n    }\r\n\r\n}\n\n\r\n\r\ntypedef VectorPair<unsigned int> VectorPairU;\r\n\r\ntemplate<typename T> std::ostream& operator<<(std::ostream& output, const VectorPair<T>& vP)\r\n{\r\n    output << \"x: \" << vP.x << \"\\ny: \" << vP.y;\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> T rand(const T& i, const T& f)\r\n{\r\n//    srand(time(NULL));\r\n    return (double(std::rand()) / (RAND_MAX) * (f - i) + i);\r\n}\r\n\r\n//template<typename T> T rand(T i, T f){\r\n//    std::array<int, std::mt19937::state_size> seed_data;\r\n//    std::random_device r;\r\n//\r\n//    std::generate(seed_data.begin(), seed_data.end(), std::ref(r));\r\n//    std::seed_seq seq(std::begin(seed_data), std::end(seed_data));\r\n//    std::mt19937 eng(seq);\r\n//\r\n//    std::uniform_real_distribution<> randU(i, f);\r\n//\r\n//    return randU(eng);\r\n//}\r\n\r\ninline bool draw(const float& chance)\r\n{\r\n    return rand(0.0f, 1.0f) < chance;\r\n}\r\n\r\ninline bool randSwitch(const float& threshold = 0.5f)\r\n{\r\n    return rand(0.0f,1.0f) < threshold;\r\n}\r\n\r\n// Functions\r\n\r\ntemplate<typename T>\r\nT nround(const T& value)\r\n{\r\n    if(value < 0)\r\n    {\r\n        return nearbyint(value);\r\n    }\r\n    return round(value);\r\n}\r\n\r\ninline void timed_sleep(float sleepTime)\r\n{\r\n    std::this_thread::sleep_for(std::chrono::duration<float>(sleepTime));\r\n}\r\n\r\nstd::string loadingIndicator(unsigned int barWidth, unsigned int progress);\r\n\r\ntemplate<typename T> void vprint(std::vector<T> &V)\r\n{\r\n    size_t L = V.size();\r\n    std::cout << '[';\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        std::cout << V[i];\r\n        if((L > 1) & (i < L - 1)) std::cout << ',';\r\n    }\r\n    std::cout << ']';\r\n}\r\n\r\ntemplate<typename T, typename out_type> out_type& printColumn(const std::vector<T>& V, const unsigned int indent = 0,\r\n        out_type& outstream = std::cout)\r\n{\r\n    for(auto& it : V)\r\n    {\r\n        size_t i = 0;\r\n        while(i < indent)\r\n        {\r\n            outstream << '\\t';\r\n            ++i;\r\n        }\r\n        outstream << it << '\\n';\r\n    }\r\n    return outstream;\r\n}\r\n\r\nstruct targetList\r\n{\r\n    std::vector<std::vector<unsigned int>> targetMatrix;\r\n    std::vector<std::string> tags;\r\n\r\n    template<typename T> friend T& operator<<(T& output, targetList& item)\r\n    {\r\n        output << \">> Targets:\\n\";\r\n        for(size_t i = 0; i < item.targetMatrix.size(); ++i)\r\n        {\r\n            output << \"\\t* \" << item.tags[i] << \": \";\r\n            output << item.targetMatrix[i];\r\n            output << '\\n';\r\n        }\r\n        return output;\r\n    }\r\n};\r\n\r\nclass rotatingIndicator\r\n{\r\nprivate:\r\n    unsigned int orientation;\r\npublic:\r\n    inline void rotateRight()\r\n    {\r\n        if(orientation < 7) ++orientation;\r\n        else orientation = 0;\r\n    }\r\n    inline void rotateLeft()\r\n    {\r\n        if(orientation > 0) --orientation;\r\n        else orientation = 7;\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream &output, rotatingIndicator &rotator)\r\n    {\r\n        switch(rotator.orientation)\r\n        {\r\n        case 0:\r\n        {\r\n            output << '|';\r\n            break;\r\n        }\r\n        case 1:\r\n        {\r\n            output << '/';\r\n            break;\r\n        }\r\n        case 2:\r\n        {\r\n            output << '-';\r\n            break;\r\n        }\r\n        case 3:\r\n        {\r\n            output << '\\\\';\r\n            break;\r\n        }\r\n        case 4:\r\n        {\r\n            output << '|';\r\n            break;\r\n        }\r\n        case 5:\r\n        {\r\n            output << '/';\r\n            break;\r\n        }\r\n        case 6:\r\n        {\r\n            output << '-';\r\n            break;\r\n        }\r\n        case 7:\r\n        {\r\n            output << '\\\\';\r\n            break;\r\n        }\r\n        default:\r\n        {\r\n            output << '|';\r\n            break;\r\n        }\r\n        }\r\n        return output;\r\n    }\r\n\r\n    rotatingIndicator(): orientation(0) { }\r\n    ~rotatingIndicator() { }\r\n};\r\n\r\nclass numberBox\r\n{\r\npublic:\r\n    std::vector<std::vector<unsigned int>> indexBox;\r\n    std::vector<unsigned int> indArray;\r\n    bool repeat;\r\n\r\n    void init(const unsigned int combo, const unsigned int depth, bool random);\r\n\r\n    bool increment();\r\n    void randIndex();\r\n\r\n    std::vector<unsigned int> pull(const unsigned int index = 0);\r\n\r\n    numberBox() { }\r\n    numberBox(const unsigned int combo, const unsigned int depth, bool random = false, bool repeat = false):\r\n        indArray(combo, 0),\r\n        repeat(repeat)\r\n    {\r\n        init(combo, depth, random);\r\n    }\r\n\r\n    ~numberBox() { }\r\n};\r\n\r\n// Basic operations\r\n\r\ntemplate<typename T> inline T absolute(const T& item)\r\n{\r\n    return (item >= 0) ? item : -item;\r\n}\r\n\r\ntemplate<typename T> T min(const std::vector<T> &V)\r\n{\r\n    size_t L = V.size();\r\n    if(L < 1) return T(0);\r\n    T minV(V[0]);\r\n    for(size_t i = 1; i < L; ++i)\r\n    {\r\n        if(isnan(V[i]) || (V[i] == UINT_MAX)) continue;\r\n        if(isnan(minV) || (minV == UINT_MAX))\r\n        {\r\n            minV = V[i];\r\n            continue;\r\n        }\r\n        if(V[i] < minV) minV = V[i];\r\n    }\r\n    return minV;\r\n}\r\n\r\n/** @brief Get the index of the minimum value in vector [V]. */\r\ntemplate<typename T>\r\nunsigned int minIndex(const std::vector<T>& V)\r\n{\r\n\r\n    T minV(V[0]);\r\n    size_t L = V.size();\r\n    unsigned int minI = UINT_MAX;\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(V[i])) continue;\r\n\r\n        if(isnan(minV))\r\n        {\r\n            minV = V[i];\r\n            minI = i;\r\n        }\r\n        else if(V[i] < minV)\r\n        {\r\n            minV = V[i];\r\n            minI = i;\r\n        }\r\n        else if(minI == UINT_MAX)\r\n        {\r\n            minI = i;\r\n        }\r\n\r\n    }\r\n\r\n    return minI;\r\n}\r\n\r\n/** @brief Obtain the maximum value of vector [V]. */\r\ntemplate<typename T>\r\nT max(const std::vector<T>& V)\r\n{\r\n\r\n    if(V.empty())\r\n    {\r\n        return T(0);\r\n    }\r\n\r\n    size_t L = V.size();\r\n    T maxV(V[0]);\r\n\r\n    for(size_t i = 1; i < L; ++i)\r\n    {\r\n        if(isnan(V[i]) || (V[i] == UINT_MAX)) continue;\r\n        if(isnan(maxV) || (maxV == UINT_MAX))\r\n        {\r\n            maxV = V[i];\r\n            continue;\r\n        }\r\n        if(V[i] > maxV) maxV = V[i];\r\n    }\r\n\r\n    return maxV;\r\n}\r\n\r\n/** @brief Obtain the maximum value of matrix [M]. */\r\ntemplate<typename T> T max(const std::vector<std::vector<T>>& M)\r\n{\r\n\r\n    if(M.empty())\r\n    {\r\n        return T(0);\r\n    }\r\n\r\n    T maxV = M.front().front();\r\n    for(auto& V : M)\r\n    {\r\n        for(auto& val : V)\r\n        {\r\n            if(isnan(val) || (val == UINT_MAX)) continue;\r\n            if(isnan(maxV) || (maxV == UINT_MAX))\r\n            {\r\n                maxV = val;\r\n                continue;\r\n            }\r\n            if(val > maxV) maxV = val;\r\n        }\r\n    }\r\n\r\n    return maxV;\r\n}\r\n\r\n// R-style indexing operators\r\n\r\ntemplate<typename T, typename index> std::vector<T> indexVector(std::vector<T>& V, const std::vector<index>& indexV)\r\n{\r\n    std::vector<T> output;\r\n    size_t L = indexV.size(), VL = V.size();\r\n    if((VL < 1) || (L < 1)) return output;\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(indexV[i] < VL)\r\n        {\r\n            output.push_back(V[indexV[i]]);\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T1, typename T2> unsigned int findIndex(std::vector<T1>& V, T2 query)\r\n{\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(V[i] == query) return i;\r\n    }\r\n    return UINT_MAX;\r\n}\r\n\r\ntemplate<typename T> unsigned int numDuplicated(std::vector<T> &V)\r\n{\r\n    size_t L = V.size(), count(0);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        for(size_t j = 0; j < L; ++j)\r\n        {\r\n            if(i == j) continue;\r\n            if(V[i] == V[j]) ++count;\r\n        }\r\n    }\r\n    return count;\r\n}\r\n\r\ntemplate<typename T> bool anyDuplicated(std::vector<T> &V)\r\n{\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        for(size_t j = 0; j < L; ++j)\r\n        {\r\n            if(i == j) continue;\r\n            if(V[i] == V[j]) return true;\r\n        }\r\n    }\r\n    return false;\r\n}\r\n\r\ntemplate<typename T1, typename T2> std::vector<T1> vseq(T1 i, const T2& f, const unsigned int& length = 0)\r\n{\r\n    std::vector<T1> output;\r\n    if(length == 0)\r\n    {\r\n        output.reserve((size_t)(f-i+T1(1)));\r\n        for(; i <= f; ++i)\r\n        {\r\n            output.push_back(i);\r\n        }\r\n        return output;\r\n    }\r\n\r\n    if(length == 1)\r\n    {\r\n        output.emplace_back(i);\r\n        return output;\r\n    }\r\n\r\n    T1 inc = (f-i)/(length - 1);\r\n    output.resize(length);\r\n\r\n    for(size_t x = 0; x < length; ++x, i += inc)\r\n    {\r\n        if(x == length - 1)\r\n        {\r\n            output[x] = f;\r\n        }\r\n        else\r\n        {\r\n            output[x] = i;\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> std::vector<T> collapse(const std::vector<std::vector<T>>& matrix)\r\n{\r\n    std::vector<T> output;\r\n    for(auto& V : matrix)\r\n    {\r\n        for(auto& item : V)\r\n        {\r\n            output.push_back(item);\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> size_t maxSize(const std::vector<std::vector<T>>& matrix)\r\n{\r\n    size_t L(matrix.size());\r\n    if(L < 1) return 0;\r\n    size_t maxSize(0);\r\n    const typename std::vector<std::vector<T>>::const_iterator itEND = matrix.end();\r\n    for(typename std::vector<std::vector<T>>::const_iterator it = matrix.begin(); it != itEND; ++it)\r\n    {\r\n        if(it->size() > maxSize) maxSize = it->size();\r\n    }\r\n    return maxSize;\r\n}\r\n\r\ntemplate<typename T> size_t minSize(const std::vector<std::vector<T>>& matrix)\r\n{\r\n    size_t L(matrix.size());\r\n    if(L < 1) return 0;\r\n    size_t minSize(matrix.front().size());\r\n    const typename std::vector<std::vector<T>>::const_iterator itEND = matrix.end();\r\n    for(typename std::vector<std::vector<T>>::const_iterator it = matrix.begin(); it != itEND; ++it)\r\n    {\r\n        if(it->size() < minSize) minSize = it->size();\r\n    }\r\n    return minSize;\r\n}\r\n\r\ntemplate<typename T> size_t validSize(const std::vector<std::vector<T>>& matrix)\r\n{\r\n    size_t output = 0;\r\n    if(matrix.size() < 1) return output;\r\n    for(auto& y : matrix)\r\n    {\r\n        for(auto& x : y)\r\n        {\r\n            if(!isnan(x) && !isinf(x)) ++output;\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> size_t validSize(const std::vector<T>& V)\r\n{\r\n    size_t output = 0;\r\n    for(auto& x : V)\r\n    {\r\n        if(!isnan(x) && !isinf(x)) ++output;\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> std::vector<T> getCrossSection(const unsigned int& index, const std::vector<std::vector<T>>& matrix)\r\n{\r\n    std::vector<T> output;\r\n    size_t L = matrix.size();\r\n    output.reserve(L);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        output.push_back(matrix[i][index]);\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> unsigned int minSizeIndex(std::vector<std::vector<T>>& matrix)\r\n{\r\n    size_t L(matrix.size());\r\n    if(L < 1) return 0;\r\n    size_t minSize(matrix[0].size()), minIndex;\r\n    for(size_t i = 1; i < L; ++i)\r\n    {\r\n        if(matrix[i].size() < minSize)\r\n        {\r\n            minSize = matrix[i].size();\r\n            minIndex = i;\r\n        }\r\n    }\r\n    return minIndex;\r\n}\r\n\r\ntemplate<typename T1, typename T2> bool operator==(std::vector<T1>& V1, std::vector<T2>& V2)\r\n{\r\n    size_t L1 = V1.size(), L2 = V2.size();\r\n    if(L1 != L2) return false;\r\n    for(size_t i = 0; i < L1; ++i)\r\n    {\r\n        if(V1[i] != V2[i]) return false;\r\n    }\r\n    return true;\r\n}\r\n\r\ntemplate<typename T1, typename T2> bool operator!=(std::vector<T1>& V1, std::vector<T2>& V2)\r\n{\r\n    return !(V1 == V2);\r\n}\r\ntemplate<typename T1, typename T2> unsigned int match(const T1& item, const std::vector<T2>& V)\r\n{\r\n    unsigned int index = 0;\r\n    for(auto& it : V)\r\n    {\r\n        if(it == item) return index;\r\n        ++index;\r\n    }\r\n    return UINT_MAX;\r\n}\r\n\r\ntemplate<typename T1, typename T2> const T2& closest(const T1& item, const std::vector<T2>& V)\r\n{\r\n    std::vector<T2> dist(V.size(), 0);\r\n    size_t L = V.size();\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        dist[i] = absolute(V[i]-item);\r\n    }\r\n\r\n    return V[minIndex(dist)];\r\n}\r\n\r\ntemplate<typename T1, typename T2> unsigned int closest_index(const T1& item, const std::vector<T2>& V)\r\n{\r\n    std::vector<T2> dist(V.size(), 0);\r\n    size_t L = V.size();\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        dist[i] = absolute(V[i]-item);\r\n    }\r\n\r\n    return minIndex(dist);\r\n}\r\n\r\ntemplate<typename T1, typename T2> void remove(const T1& item, std::vector<T2>& V)\r\n{\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i < L;)\r\n    {\r\n        if(V[i] == item)\r\n        {\r\n            V.erase(V.begin() + i);\r\n            --L;\r\n        }\r\n        else ++i;\r\n    }\r\n}\r\n\r\n// Vector operations\r\n\r\ntemplate<typename T1, typename T2>\r\nstd::vector<T2>& coerce(const std::vector<T1>& V1, std::vector<T2>& V2)\r\n{\r\n    V2.resize(V1.size());\r\n    for(size_t i = 0; i < V2.size(); ++i)\r\n    {\r\n        V2[i] = V1[i];\r\n    }\r\n    return V2;\r\n}\r\n\r\n// Vector selection\r\n\r\ntemplate<typename T> T& last(const std::vector<T>& V)\r\n{\r\n    return V.back();\r\n}\r\n\r\ntemplate<typename T> T& last(const std::vector<std::vector<T>>& M)\r\n{\r\n    return M.back().back();\r\n}\r\n\r\ntemplate<typename T> T& first(const std::vector<T>& V)\r\n{\r\n    return V.front();\r\n}\r\n\r\ntemplate <typename T> T& first(const std::vector<std::vector<T>>& M)\r\n{\r\n    return M.front().front();\r\n}\r\n\r\ntemplate<typename T1, typename T2> bool vExclusive(std::vector<T1>& V, std::vector<T2>& other)\r\n{\r\n    size_t L1 = V.size(), L2 = other.size();\r\n    if((L1 < 1) || (L2 < 1)) return true;\r\n    for(size_t i = 0; i < L1; ++i)\r\n    {\r\n        for(size_t j = 0; j < L2; ++j)\r\n        {\r\n            if(V[i] == other[j]) return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\n\r\ntemplate<typename T1, typename T2> std::vector<T1> shared(const std::vector<T1>& V1, const std::vector<T2>& V2)\r\n{\r\n    size_t L1 = V1.size(), L2 = V2.size();\r\n    std::vector<T1> output;\r\n    for(size_t i = 0; i < L1; ++i)\r\n    {\r\n        for(size_t j = 0; j < L2; ++j)\r\n        {\r\n            if(V1[i] == V2[j])\r\n            {\r\n                output.push_back(V1[i]);\r\n                break; // Add shared entry once only\r\n            }\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T1, typename T2> std::vector<T1> without(const std::vector<T1>& V1, const std::vector<T2>& V2)\r\n{\r\n    std::vector<T1> output;\r\n    for(auto& item : V1)\r\n    {\r\n        if(!anyEqual(item, V2))\r\n        {\r\n            output.push_back(item);\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> std::vector<T> at_index(const std::vector<T>& V,\r\n        const std::vector<unsigned int>& index)\r\n{\r\n\r\n    std::vector<T> output;\r\n    output.reserve(index.size());\r\n    for(auto& idx : index)\r\n    {\r\n        if(idx < V.size()) output.push_back(V[idx]);\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> std::vector<T> not_index(const std::vector<T>& V, const std::vector<unsigned int>& index)\r\n{\r\n    size_t L = index.size();\r\n    std::vector<T> output;\r\n    output.reserve(L);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(!anyEqual(i, index)) output.push_back(V[i]);\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> void select(std::vector<T>& V, const std::vector<unsigned int>& index)\r\n{\r\n    unsigned int vIdx = 0;\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i < L; ++vIdx)\r\n    {\r\n        if(!anyEqual(vIdx, index))\r\n        {\r\n            V.erase(V.begin() + i);\r\n            --L;\r\n        }\r\n        else ++i;\r\n    }\r\n}\r\n\r\ntemplate<typename T>\r\nstruct IndexPair\r\n{\r\n    T data;\r\n    unsigned int index;\r\n\r\n    IndexPair():\r\n        data(0),\r\n        index(UINT_MAX) { }\r\n    IndexPair(const unsigned int& index, const T& data):\r\n        data(data),\r\n        index(index) { }\r\n};\r\n\r\ntemplate<typename T>\r\nstruct SubsetInfo\r\n{\r\n    std::vector<unsigned int> indices;\r\n    std::vector<T> data;\r\n\r\n    inline const unsigned int& index(const unsigned int& i) const\r\n    {\r\n        return indices[i];\r\n    }\r\n    inline const T& item(const unsigned int& i) const\r\n    {\r\n        return data[i];\r\n    }\r\n\r\n    inline unsigned int size() const\r\n    {\r\n        return indices.size();\r\n    }\r\n\r\n    inline void emplace_back(const unsigned int& index, const T& newValue)\r\n    {\r\n        indices.emplace_back(index);\r\n        data.emplace_back(newValue);\r\n    }\r\n    inline void push_back(const unsigned int& index, const T& newValue)\r\n    {\r\n        indices.push_back(index);\r\n        data.push_back(newValue);\r\n    }\r\n\r\n    inline IndexPair<T> operator[](const unsigned int& i) const\r\n    {\r\n        return IndexPair<T>(indices[i], data[i]);\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream& output, const SubsetInfo<T>& other)\r\n    {\r\n        unsigned int L = other.size();\r\n        if(L < 1) return output;\r\n\r\n        output << \"[\";\r\n        for(size_t i = 0; i < L; ++i)\r\n        {\r\n            output << other.indices[i] << ':' << other.data[i];\r\n            if(i < L-1) output << ',';\r\n        }\r\n        output << \"]\";\r\n        return output;\r\n    }\r\n};\r\n\r\ntemplate<typename T1, typename T2> SubsetInfo<T1> select_subset(const std::vector<T1>& V,\r\n        const BYTE& operators,\r\n        const T2& metric)\r\n{\r\n    SubsetInfo<T1> output;\r\n    unsigned int index = 0;\r\n    if(operators & OPERATOR_GREATER)\r\n    {\r\n        if(operators & OPERATOR_EQUAL)\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(item >= metric)\r\n                {\r\n                    output.emplace_back(index, item);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(item > metric)\r\n                {\r\n                    output.emplace_back(index, item);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n    }\r\n    else if(operators & OPERATOR_LESS)\r\n    {\r\n        if(operators & OPERATOR_EQUAL)\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(item <= metric)\r\n                {\r\n                    output.emplace_back(index, item);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(item < metric)\r\n                {\r\n                    output.emplace_back(index, item);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\ntemplate<typename T1, typename T2> std::vector<unsigned int> select_subset_idx(const std::vector<T1>& V,\r\n        const BYTE& operators,\r\n        const T2& metric)\r\n{\r\n    std::vector<unsigned int> output;\r\n    unsigned int index = 0;\r\n    if(operators & OPERATOR_GREATER)\r\n    {\r\n        if(operators & OPERATOR_EQUAL)\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(!isnan(item) && (item >= metric))\r\n                {\r\n                    output.emplace_back(index);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(!isnan(item) && (item > metric))\r\n                {\r\n                    output.emplace_back(index);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n    }\r\n    else if(operators & OPERATOR_LESS)\r\n    {\r\n        if(operators & OPERATOR_EQUAL)\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(!isnan(item) && (item <= metric))\r\n                {\r\n                    output.emplace_back(index);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            for(auto& item : V)\r\n            {\r\n                if(!isnan(item) && (item < metric))\r\n                {\r\n                    output.emplace_back(index);\r\n                }\r\n                ++index;\r\n            }\r\n        }\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\n/** @brief Store a random vector in output containing numerics from ri - rf.\r\n  *\r\n  * @param output   Vector to store output in.\r\n  * @param ri       Lower bound of random values.\r\n  * @param rf       Upper bound of random values.\r\n  * @param length   Length of the vector.\r\n  * @param repeat   Allow repeated values.\r\n*/\r\ntemplate<typename T> void vrand(std::vector<T>& output,\r\n                                const T& ri,\r\n                                const T& rf,\r\n                                const unsigned int& length,\r\n                                const bool& repeat)  // No copy\r\n{\r\n    output.resize(length);\r\n\r\n    if(repeat)\r\n    {\r\n        for(size_t i = 0; i < length; ++i)\r\n        {\r\n            output[i] = rand<T>(ri, rf);\r\n        }\r\n        return;\r\n    }\r\n\r\n    std::vector<T> possibilities = vseq(ri, rf);\r\n    size_t i = 0, randIndex;\r\n\r\n    while((i < length) && !possibilities.empty())\r\n    {\r\n        randIndex = rand(size_t(0), possibilities.size());\r\n\r\n        if(randIndex >= possibilities.size())\r\n        {\r\n            randIndex = possibilities.size() - 1;\r\n        }\r\n\r\n        output[i] = possibilities[randIndex];\r\n        possibilities.erase(possibilities.begin() + randIndex);\r\n        ++i;\r\n    }\r\n}\r\n\r\ntemplate<typename T> std::vector<T> vrand(const T& ri,\r\n                                          const T& rf,\r\n                                          const unsigned int& length,\r\n                                          const bool& repeat)\r\n{\r\n    std::vector<T> output;\r\n    output.resize(length);\r\n\r\n    if(repeat)\r\n    {\r\n        for(size_t i = 0; i < length; ++i)\r\n        {\r\n            output[i] = rand<T>(ri, rf);\r\n        }\r\n        return output;\r\n    }\r\n\r\n    for(size_t i = 0; i < length; ++i)\r\n    {\r\n        T randValue = rand<T>(ri, rf);\r\n        while(anyEqual(randValue, output))\r\n        {\r\n            randValue = rand<T>(ri, rf);\r\n        }\r\n        output[i] = randValue;\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\ntemplate<typename T>\r\nstd::vector<T> pickRand(std::vector<T>& output,\r\n                        const std::vector<T>& V,\r\n                        const unsigned int& length)\r\n{\r\n    size_t L = V.size();\r\n    std::vector<size_t> randIndex = vrand(size_t(0), L-1, length, false);\r\n    output.clear();\r\n    output.reserve(L);\r\n\r\n    for(size_t i = 0; i < length; ++i)\r\n    {\r\n        output.push_back(V[randIndex[i]]);\r\n    }\r\n    return output;\r\n}\r\n\r\ninline std::string rand_hash(const unsigned int& length, const std::string& allowed = \"\")\r\n{\r\n\r\n    std::string output;\r\n\r\n    if(allowed.empty())\r\n    {\r\n        std::string allowed = std::string(ALPHABET) + DIGITS + HASH_CHAR;\r\n        while(output.size() < length)\r\n        {\r\n            output += allowed[rand(size_t(0),allowed.size()-1)];\r\n        }\r\n    }\r\n    else\r\n    {\r\n        while(output.size() < length)\r\n        {\r\n            output += allowed[rand(size_t(0),allowed.size()-1)];\r\n        }\r\n    }\r\n\r\n    return output;\r\n\r\n}\r\n\r\ntemplate<typename T> void randomize(std::vector<T>& V)\r\n{\r\n    size_t L = V.size();\r\n    std::vector<size_t> newIndex;\r\n    vrand(newIndex, size_t(0), L-1, L, false);\r\n\r\n    std::vector<T> output(L);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        output[i] = V[newIndex[i]];\r\n    }\r\n    V = output;\r\n}\r\n\r\ntemplate<typename T> std::vector<T> pickRange(std::vector<T>& V,\r\n                                              const unsigned int& first,\r\n                                              const unsigned int& last)\r\n{\r\n    std::vector<T> output;\r\n    if(first < last)\r\n    {\r\n        output.reserve(last - first + 1);\r\n        for(unsigned int i = first; i <= last; ++i)\r\n        {\r\n            output.push_back(i);\r\n        }\r\n        return output;\r\n    }\r\n    else if(first > last)\r\n    {\r\n        output.reserve(first - last + 1);\r\n        for(unsigned int i = first+1; i > last; --i)\r\n        {\r\n            output.push_back(i-1);\r\n        }\r\n        return output;\r\n    }\r\n    output.push_back(V[first]);\r\n    return output;\r\n}\r\n\r\ntemplate<typename T, typename N> unsigned int numEqual(const T& item,\r\n                                                       const std::vector<N>& V)\r\n{\r\n    unsigned int count = 0;\r\n\r\n    for(auto& element : V)\r\n    {\r\n        if(element == item)\r\n        {\r\n            ++count;\r\n        }\r\n    }\r\n\r\n    return count;\r\n}\r\n\r\ntemplate<typename T1, typename T2> unsigned int numEqual(const std::vector<T1>& V1,\r\n                                                         const std::vector<T2>& V2)\r\n{\r\n    unsigned int count(0);\r\n\r\n    for(auto& i1 : V1)\r\n    {\r\n        for(auto& i2 : V2)\r\n        {\r\n            if(i1 == i2)\r\n            {\r\n                ++count;\r\n            }\r\n        }\r\n    }\r\n\r\n    return count;\r\n}\r\n\r\ntemplate<typename T> unsigned int maxSizeIndex(const std::vector<std::vector<T>>& matrix)\r\n{\r\n    size_t L = matrix.size();\r\n    unsigned int maxInd(0), maxL(0);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(matrix[i].size() > maxL)\r\n        {\r\n            maxL = matrix[i].size();\r\n            maxInd = i;\r\n        }\r\n    }\r\n    return maxInd;\r\n}\r\n\r\n/** @brief Calculates the mean value in vector [V]. */\r\ntemplate<typename T>\r\nT average(const std::vector<T>& V)\r\n{\r\n    size_t L = V.size();\r\n    if(L < 1) return T();\r\n    if(L == 1) return V.front();\r\n\r\n    T output(0);\r\n    size_t N = 0;\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(V[i])) continue;\r\n        output += V[i];\r\n        ++N;\r\n    }\r\n    return output/N;\r\n}\r\n\r\n/** @brief Calculates the mean value in matrix [V]. */\r\ntemplate<typename T>\r\nT average(const std::vector<std::vector<T>>& V)\r\n{\r\n    size_t tSIZE = 0;\r\n    if(V.size() < 1) return T();\r\n\r\n    T output(0);\r\n    for(auto& y : V)\r\n    {\r\n        for(auto& x : y)\r\n        {\r\n            if(isnan(x)) continue;\r\n            output += x;\r\n            ++tSIZE;\r\n        }\r\n    }\r\n\r\n    return output/tSIZE;\r\n}\r\n\r\ntemplate<typename T>\r\nbool nan_sort(const T& first, const T& second)\r\n{\r\n    if(isnan(first))\r\n    {\r\n        return false;\r\n    }\r\n    else if(isnan(second))\r\n    {\r\n        return true;\r\n    }\r\n    return second > first;\r\n}\r\n\r\n/** @brief Order the members of vector [V] in ascending or descending order.\r\n  *\r\n  * For efficiency, performs the ordering on the original vector. */\r\ntemplate<typename T>\r\nvoid order(std::vector<T>& V, const bool& ascending = true)\r\n{\r\n    if(ascending)\r\n    {\r\n        std::sort(V.begin(), V.end());\r\n    }\r\n    else\r\n    {\r\n        std::sort(V.rbegin(), V.rend());\r\n    }\r\n}\r\n\r\ninline void order(std::vector<float>& V, const bool& ascending = true)\r\n{\r\n    if(ascending)\r\n    {\r\n        std::sort(V.begin(), V.end(), nan_sort<float>);\r\n    }\r\n    else\r\n    {\r\n        std::sort(V.rbegin(), V.rend(), nan_sort<float>);\r\n    }\r\n}\r\n\r\ninline void order(std::vector<double>& V, const bool& ascending = true)\r\n{\r\n    if(ascending)\r\n    {\r\n        std::sort(V.begin(), V.end(), nan_sort<double>);\r\n    }\r\n    else\r\n    {\r\n        std::sort(V.rbegin(), V.rend(), nan_sort<double>);\r\n    }\r\n}\r\n\r\ntemplate<typename T> void bringToFront(const T& item, std::vector<T>& V)\r\n{\r\n    if(V.size() < 2) return;\r\n    size_t matchIndex = match(item, V);\r\n    if((matchIndex == UINT_MAX) || (matchIndex < 1)) return;\r\n\r\n    V.insert(V.begin(), item);\r\n    V.erase(V.begin() + matchIndex + 1);\r\n}\r\n\r\ntemplate<typename T> void sendToBack(const T& item, std::vector<T>& V)\r\n{\r\n    if(V.size() < 2) return;\r\n    size_t matchIndex = match(item, V);\r\n    if(matchIndex >= V.size() - 1) return;\r\n\r\n    V.insert(V.end(), item);\r\n    V.erase(V.begin() + matchIndex);\r\n}\r\n\r\ntemplate<typename T> void bringForward(const T& item, std::vector<T>& V)\r\n{\r\n    if(V.size() < 2) return;\r\n    size_t matchIndex = match(item, V);\r\n    if((matchIndex == UINT_MAX) || (matchIndex < 1)) return;\r\n\r\n    T tmp;\r\n    tmp = V[matchIndex - 1];\r\n    V[matchIndex - 1] = V[matchIndex];\r\n    V[matchIndex] = tmp;\r\n}\r\n\r\ntemplate<typename T> void sendBackward(const T& item, std::vector<T>& V)\r\n{\r\n    if(V.size() < 2) return;\r\n    size_t matchIndex = match(item, V);\r\n    if(matchIndex >= V.size() - 1) return;\r\n\r\n    T tmp;\r\n    tmp = V[matchIndex + 1];\r\n    V[matchIndex + 1] = V[matchIndex];\r\n    V[matchIndex] = tmp;\r\n}\r\n\r\n/** @brief Calculate the median value of vector [V]. */\r\ntemplate<typename T>\r\nT median(std::vector<T> V)\r\n{\r\n    size_t L = V.size();\r\n    if(L < 1) return NAN;\r\n    if(L == 1) return V.front();\r\n\r\n    order(V);\r\n\r\n    for(size_t i = 0; i < L;)\r\n    {\r\n        if(isnan(V[i]))\r\n        {\r\n            V.erase(V.begin() + i);\r\n            --L;\r\n        }\r\n        else ++i;\r\n    }\r\n\r\n    if((L % 2) == 0) return (V[L/2-1]+V[L/2])/2;\r\n    return V[L/2];\r\n}\r\n\r\n/** @brief Calculate the median of matrix [M]. */\r\ntemplate<typename T>\r\nT median(const std::vector<std::vector<T>>& M)\r\n{\r\n    std::vector<T> V;\r\n    for(auto& row : M)\r\n    {\r\n        V.insert(V.end(), row.begin(), row.end());\r\n    }\r\n    return median(V);\r\n}\r\n\r\n/** @brief Calculate the 1st quartile value of vector [V]. */\r\ntemplate<typename T>\r\nT Q1(std::vector<T> V)\r\n{\r\n    order(V);\r\n    size_t L = V.size();\r\n    while((L > 2) && (V.size() > L/2))\r\n    {\r\n        V.pop_back();\r\n    }\r\n    return median(V);\r\n}\r\n\r\n/** @brief Calculate the 3rd quartile value of vector [V]. */\r\ntemplate<typename T> T Q3(std::vector<T> V)\r\n{\r\n    order(V);\r\n    size_t L = V.size();\r\n    while((L > 2) && (V.size() > L/2))\r\n    {\r\n        V.erase(V.begin());\r\n    }\r\n    return median(V);\r\n}\r\n\r\ntemplate<class T>\r\nstruct DataSummary\r\n{\r\n    T lowerOutlierRange,\r\n    Q1, median, Q3,\r\n    upperOutlierRange;\r\n\r\n    DataSummary() { }\r\n    DataSummary(std::vector<T> data):\r\n        lowerOutlierRange(0),\r\n        Q1(0),\r\n        median(0),\r\n        Q3(0),\r\n        upperOutlierRange(0)\r\n    {\r\n\r\n        order(data);\r\n        size_t L = data.size();\r\n\r\n        for(size_t i = 0; i < L;)\r\n        {\r\n            if(isnan(data[i]) || isinf(data[i]))\r\n            {\r\n                data.erase(data.begin() + i);\r\n                --L;\r\n            }\r\n            ++i;\r\n        }\r\n\r\n        if(!L) return;\r\n        if(L == 1)\r\n        {\r\n            Q3 = median = Q1 = data.front();\r\n            return;\r\n        }\r\n        else if(L < 4)\r\n        {\r\n            Q1 = data.front();\r\n            Q3 = data.back();\r\n            if(L == 2) median = average(data);\r\n            else median = data[1];\r\n            return;\r\n        }\r\n\r\n\r\n        size_t initL = L;\r\n\r\n        std::vector<T> Q3data = data;\r\n\r\n        if((L % 2) == 0) this->median = (data[L/2-1]+data[L/2])/2;\r\n        else this->median = data[L/2];\r\n\r\n        while(data.size() > initL/2)\r\n        {\r\n            data.pop_back();\r\n        }\r\n\r\n        L = data.size();\r\n\r\n        if((L % 2) == 0) this->Q1 = (data[L/2-1]+data[L/2])/2;\r\n        else this->Q1 = data[L/2];\r\n\r\n        while(Q3data.size() > initL/2)\r\n        {\r\n            Q3data.erase(Q3data.begin());\r\n        }\r\n\r\n        L = Q3data.size();\r\n\r\n        if((L % 2) == 0) this->Q3 = (Q3data[L/2-1]+Q3data[L/2])/2;\r\n        else this->Q3 = Q3data[L/2];\r\n\r\n        this->lowerOutlierRange = this->median - 1.5*(this->Q3 - this->Q1);\r\n        this->upperOutlierRange = this->median + 1.5*(this->Q3 - this->Q1);\r\n    }\r\n\r\n    void getSummary(const std::vector<T>& data)\r\n    {\r\n        *this = summary(data);\r\n    }\r\n\r\n    friend std::ostream& operator<<(std::ostream& output, const DataSummary& other)\r\n    {\r\n        output << \"Data summary:\\n\";\r\n        output << \"\\nLower outlier range:\\t\" << other.lowerOutlierRange\r\n               << \"\\nLower quartile:\\t\" << other.Q1\r\n               << \"\\nMedian:\\t\" << other.median\r\n               << \"\\nUpper Quartile:\\t\" << other.Q3\r\n               << \"\\nUpper Outlier Range:\\t\" << other.upperOutlierRange;\r\n        return output;\r\n    }\r\n\r\n};\r\n\r\ntemplate<typename T> DataSummary<T> summary(std::vector<T> data)\r\n{\r\n\r\n    DataSummary<T> output;\r\n\r\n    order(data);\r\n    size_t L = data.size();\r\n    for(size_t i = 0; i < L;)\r\n    {\r\n        if(isnan(data[i]) || isinf(data[i]))\r\n        {\r\n            data.erase(data.begin() + i);\r\n            --L;\r\n        }\r\n        ++i;\r\n    }\r\n\r\n    size_t initL = L;\r\n    std::vector<T> Q3data = data;\r\n\r\n    if((L % 2) == 0) output.median = (data[L/2-1]+data[L/2])/2;\r\n    else output.median = data[L/2];\r\n\r\n    while(data.size() > initL/2)\r\n    {\r\n        data.pop_back();\r\n    }\r\n\r\n    L = data.size();\r\n\r\n    if((L % 2) == 0) output.Q1 = (data[L/2-1]+data[L/2])/2;\r\n    else output.Q1 = data[L/2];\r\n\r\n    while(Q3data.size() > initL/2)\r\n    {\r\n        Q3data.erase(Q3data.begin());\r\n    }\r\n\r\n    L = Q3data.size();\r\n\r\n    if((L % 2) == 0) output.Q3 = (Q3data[L/2-1]+Q3data[L/2])/2;\r\n    else output.Q3 = Q3data[L/2];\r\n\r\n    output.lowerOutlierRange = output.median - 1.5f*(output.Q3 - output.Q1);\r\n    output.upperOutlierRange = output.median + 1.5f*(output.Q3 - output.Q1);\r\n\r\n    return output;\r\n\r\n}\r\n\r\n/** @brief Obtain the value occuring at percentile [percentile] in vector [V].\r\n  *\r\n  * Calculates the index occuring at [percentile] in either ascending or descending\r\n  * order dictated by the [ascending] parameter, and rounds down before returning.\r\n  *\r\n  * @param percentile   The percentile (0.0f - 1.0f) cutoff.\r\n  * @param V    The vector to calculate the percentile index for.\r\n  * @param ascending    TRUE to calculate the highest percentile, FALSE to calculate\r\n  * the lowest percentile.\r\n  */\r\ntemplate<typename T>\r\nT& percentileValue(const float& percentile,\r\n                   const std::vector<T>& V,\r\n                   const bool& ascending = true)\r\n{\r\n    if(V.empty())\r\n    {\r\n        return T();\r\n    }\r\n\r\n    order(V, ascending);\r\n\r\n    unsigned int position = (V.size() - 1)*percentile;\r\n\r\n    return V[position];\r\n\r\n}\r\n\r\n/** @brief Obtain the sum of vector [V]. */\r\ntemplate<typename T> T sum(const std::vector<T>& V)\r\n{\r\n    if(V.empty()) return NAN;\r\n    T output(NAN);\r\n    for(auto& num : V)\r\n    {\r\n        if(isnan(output)) output = num;\r\n        else if(isnan(num)) continue;\r\n        else output += num;\r\n    }\r\n    return output;\r\n}\r\n\r\n/** @brief Obtain the sum of matrix [M]. */\r\ntemplate<typename T>\r\nT sum(const vMatrix<T>& M)\r\n{\r\n    if(M.empty()) return NAN;\r\n    T output(NAN);\r\n    for(auto& row : M)\r\n    {\r\n        for(auto& num : row)\r\n        {\r\n            if(isnan(output)) output = num;\r\n            else if(isnan(num)) continue;\r\n            else output += num;\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\n/** @brief Obtain the cumulative product of vector [V]. */\r\ntemplate<typename T>\r\nT cumprod(const std::vector<T> &V)\r\n{\r\n    if(V.empty()) return T(0);\r\n\r\n    T output(V.front());\r\n    size_t L = V.size();\r\n    for(size_t i = 1; i < L; ++i)\r\n    {\r\n        output *= V[i];\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\n/** @brief Obtain the index of the maximum value in vector [V].\r\n  *\r\n  * Obtains the maximum index, or returns UINT_MAX upon failure.\r\n  */\r\ntemplate<typename T>\r\nunsigned int maxIndex(const std::vector<T>& V)\r\n{\r\n\r\n    if(V.empty())\r\n    {\r\n        return UINT_MAX;\r\n    }\r\n\r\n    T maxV(V[0]);\r\n    size_t L = V.size();\r\n    unsigned int maxI = UINT_MAX;\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(V[i]) || isinf(V[i])) continue;\r\n        if(isnan(maxV) || isinf(maxV))\r\n        {\r\n            maxV = V[i];\r\n            maxI = i;\r\n            continue;\r\n        }\r\n        if(V[i] > maxV)\r\n        {\r\n            maxV = V[i];\r\n            maxI = i;\r\n        }\r\n        else if(maxI == UINT_MAX)\r\n        {\r\n            maxI = i;\r\n        }\r\n    }\r\n\r\n    return maxI;\r\n}\r\n\r\n/** @brief Obtain the most frequent value (mode) in vector [V]. */\r\ntemplate<typename T>\r\nT mode(const std::vector<T>& V)\r\n{\r\n\r\n    if(V.empty()) return T();\r\n    if(V.size() == 1) return V.front();\r\n\r\n    std::map<T, unsigned int> counts;\r\n\r\n    for(auto& item : V)\r\n    {\r\n        ++counts[item];\r\n    }\r\n\r\n    unsigned int maxCount = 0, i = 0;\r\n\r\n    for(auto& p : counts)\r\n    {\r\n\r\n        if(p.second > maxCount)\r\n        {\r\n\r\n            maxCount = p.second;\r\n\r\n        }\r\n\r\n        ++i;\r\n\r\n    }\r\n\r\n    i = 0;\r\n\r\n    for(auto& p : counts)\r\n    {\r\n\r\n        if(p.second == maxCount)\r\n        {\r\n\r\n            return p.first;\r\n\r\n        }\r\n\r\n        ++i;\r\n\r\n    }\r\n\r\n    return T();\r\n}\r\n\r\n/** @brief Obtain the minimum value between elements of vector [V]. */\r\ntemplate<typename T>\r\nT minDist(const std::vector<T>& V)\r\n{\r\n    size_t L = V.size();\r\n    if(L < 2) return T(0);\r\n    T minD = abs(V[1] - V[0]);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        for(size_t j = i+1; j < L-1; ++j)\r\n        {\r\n            if(abs(V[i] - V[j]) < minD) minD = abs(V[i] - V[j]);\r\n        }\r\n    }\r\n    return minD;\r\n}\r\n\r\ntemplate<typename T1, typename T2>\r\nT1 minDist(const T1& value, const std::vector<T2>& V)\r\n{\r\n    if(V.empty())\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    T1 minDistance = absolute(V.front() - value);\r\n\r\n    for(size_t i = 1; i < V.size(); ++i)\r\n    {\r\n        if(absolute(V[i] - value) < minDistance)\r\n        {\r\n            minDistance = absolute(V[i] - value);\r\n\r\n            if(!minDistance)\r\n            {\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    return minDistance;\r\n}\r\n\r\ntemplate<typename T1, typename T2>\r\nsize_t minDistIndex(const T1& value, const std::vector<T2>& V)\r\n{\r\n    if(V.empty())\r\n    {\r\n        return UINT_MAX;\r\n    }\r\n\r\n    size_t minIndex = 0;\r\n    T1 minDistance = absolute(V.front() - value);\r\n\r\n    for(size_t i = 1; i < V.size(); ++i)\r\n    {\r\n        if(absolute(V[i] - value) < minDistance)\r\n        {\r\n            minDistance = absolute(V[i] - value);\r\n            minIndex = i;\r\n\r\n            if(!minDistance)\r\n            {\r\n                return minIndex;\r\n            }\r\n        }\r\n    }\r\n\r\n    return minIndex;\r\n}\r\n\r\n/** @brief Obtain the largest distance between elements in vector [V]. */\r\ntemplate<typename T>\r\nT maxDist(const std::vector<T>& V)\r\n{\r\n    size_t L = V.size();\r\n    if(L < 2) return T(0);\r\n    T maxD = abs(V[1] - V[0]);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        for(size_t j = i+1; j < L-1; ++j)\r\n        {\r\n            if(abs(V[i] - V[j]) > maxD) maxD = abs(V[i] - V[j]);\r\n        }\r\n    }\r\n    return maxD;\r\n}\r\n\r\n/** @brief Obtain the value in vector [V] ranked [rank] from the highest value.\r\n  *\r\n  * @param rank The rank of the value to be obtained.\r\n  * @param V    The vector containing values to be ranked.\r\n  */\r\ntemplate<typename T>\r\nT rankedMax(const unsigned int& rank, const std::vector<T>& V)\r\n{\r\n    T highVal;\r\n    T minVal = min(V);\r\n\r\n    unsigned int highIdx;\r\n\r\n    std::vector<unsigned int> highIndices;\r\n\r\n    size_t L = V.size();\r\n\r\n    for(size_t i = 0; i <= rank; ++i)\r\n    {\r\n        highVal = minVal;\r\n        for(size_t j = 0; j < L; ++j)\r\n        {\r\n            if(anyEqual(j, highIndices)) continue;\r\n            if(V[j] > highVal)\r\n            {\r\n                highVal = V[j];\r\n                highIdx = j;\r\n            }\r\n        }\r\n        highIndices.push_back(highIdx);\r\n    }\r\n    return V[highIndices.back()];\r\n}\r\n\r\n/** @brief Obtain the index of the value in vector [V] ranked [rank] from the highest.\r\n  *\r\n  * @param rank The rank of the index to be obtained.\r\n  * @param V    The vector containing values to be ranked.\r\n  */\r\ntemplate<typename T>\r\nunsigned int rankedMaxIndex(const unsigned int rank, const std::vector<T>& V)\r\n{\r\n    T highVal, minVal = min(V);\r\n    unsigned int highIdx;\r\n    std::vector<unsigned int> highIndices;\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i <= rank; ++i)\r\n    {\r\n        highVal = minVal;\r\n        for(size_t j = 0; j < L; ++j)\r\n        {\r\n            if(anyEqual(j, highIndices)) continue;\r\n            if(V[j] > highVal)\r\n            {\r\n                highVal = V[j];\r\n                highIdx = j;\r\n            }\r\n        }\r\n        highIndices.push_back(highIdx);\r\n    }\r\n    return highIndices.back();\r\n}\r\n\r\n/** @brief Obtain the value in vector [V] ranked [rank] from the lowest value.\r\n  *\r\n  * @param rank The rank of the value to be obtained.\r\n  * @param V    The vector containing values to be ranked.\r\n  */\r\ntemplate<typename T>\r\nT rankedMin(const unsigned int rank, const std::vector<T>& V)\r\n{\r\n    T lowVal, maxVal = max(V);\r\n    unsigned int lowIdx;\r\n    std::vector<unsigned int> lowIndices;\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i <= rank; ++i)\r\n    {\r\n        lowVal = maxVal;\r\n        for(size_t j = 0; j < L; ++j)\r\n        {\r\n            if(anyEqual(j, lowIndices)) continue;\r\n            if(V[j] < lowVal)\r\n            {\r\n                lowVal = V[j];\r\n                lowIdx = j;\r\n            }\r\n        }\r\n        lowIndices.push_back(lowIdx);\r\n    }\r\n    return V[lowIndices.back()];\r\n}\r\n\r\n/** @brief Obtain the index of the value in vector [V] ranked [rank] from the lowest.\r\n  *\r\n  * @param rank The rank of the index to be obtained.\r\n  * @param V    The vector containing values to be ranked.\r\n  */\r\ntemplate<typename T>\r\nunsigned int rankedMinIndex(const unsigned int rank, const std::vector<T>& V)\r\n{\r\n    T lowVal, maxVal = max(V);\r\n    unsigned int lowIdx;\r\n    std::vector<unsigned int> lowIndices;\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i <= rank; ++i)\r\n    {\r\n        lowVal = maxVal;\r\n        for(size_t j = 0; j < L; ++j)\r\n        {\r\n            if(anyEqual(j, lowIndices)) continue;\r\n            if(V[j] < lowVal)\r\n            {\r\n                lowVal = V[j];\r\n                lowIdx = j;\r\n            }\r\n        }\r\n        lowIndices.push_back(lowIdx);\r\n    }\r\n    return lowIndices.back();\r\n}\r\n\r\n/** @brief Obtain the minimum value in matrix [M]. */\r\ntemplate<typename T>\r\nT min(const std::vector<std::vector<T>>& M)\r\n{\r\n\r\n    if(M.empty())\r\n    {\r\n        throw std::invalid_argument(\"Min: attempted minimum value fetch for empty metrix\");\r\n    }\r\n\r\n    T minV = M.front().front();\r\n    for(auto& V : M)\r\n    {\r\n        for(auto& val : V)\r\n        {\r\n            if(isnan(minV) || (val == UINT_MAX))\r\n            {\r\n                minV = val;\r\n                continue;\r\n            }\r\n\r\n            if(isnan(val) || (minV == UINT_MAX)) continue;\r\n            if(val < minV) minV = val;\r\n        }\r\n    }\r\n\r\n    return minV;\r\n}\r\n\r\n/** @brief Obtain the range of vector [V] (max - min). */\r\ntemplate<typename T>\r\nT range(const std::vector<T>& V)\r\n{\r\n    return max(V) - min(V);\r\n}\r\n\r\n/** @brief Get the standard deviation of vector [V].\r\n  *\r\n  * Obtained via square root of MSE from the vector mean.\r\n  */\r\ntemplate<typename T>\r\nT stdev(const std::vector<T>& V)\r\n{\r\n    T vMean = average(V);\r\n    T output(0);\r\n    unsigned int N = 0;\r\n    for(const auto& num : V)\r\n    {\r\n        if(isnan(num) || isinf(num)) continue;\r\n        output += pow(num - vMean, 2);\r\n        ++N;\r\n    }\r\n    return sqrt(output/N);\r\n}\r\n\r\n/** @brief Obtain the standard deviation for elements in matrix [M].\r\n  *\r\n  * Obtained via square root of MSE from the matrix mean.\r\n  */\r\ntemplate<typename T>\r\nT stdev(const std::vector<std::vector<T>>& V)\r\n{\r\n    T vMean = average(V);\r\n    T output(0);\r\n\r\n    unsigned int tSIZE = 0;\r\n    for(const auto& row : V)\r\n    {\r\n        for(const auto& col : row)\r\n        {\r\n            if(isnan(col) || isinf(col)) continue;\r\n            output += pow(col - vMean, 2);\r\n            ++tSIZE;\r\n        }\r\n    }\r\n\r\n    return sqrt(output/tSIZE);\r\n}\r\n\r\ntemplate<typename T>\r\nstruct index_ref\r\n{\r\n\r\n    index_ref(const T& item,\r\n              const size_t& index):\r\n                     item(&item),\r\n                     index(index){ }\r\n\r\n    const T* item;\r\n    size_t index;\r\n\r\n    inline bool operator>(const index_ref& other) const\r\n    {\r\n        return *item > *other.item;\r\n    }\r\n    inline bool operator<(const index_ref& other) const\r\n    {\r\n        return *item < *other.item;\r\n    }\r\n    inline bool operator>=(const index_ref& other) const\r\n    {\r\n        return !(*this < other);\r\n    }\r\n    inline bool operator<=(const index_ref& other) const\r\n    {\r\n        return !(*this > other);\r\n    }\r\n    inline bool operator==(const index_ref& other) const\r\n    {\r\n        return *item == *other.item;\r\n    }\r\n};\r\n\r\ntemplate<typename T>\r\nbool nan_idx_sort(const index_ref<T>& first,\r\n                  const index_ref<T>& second)\r\n{\r\n\r\n    if(isnan(*first.item))\r\n    {\r\n        return false;\r\n    }\r\n    else if(isnan(*second.item))\r\n    {\r\n        return true;\r\n    }\r\n    else\r\n    {\r\n        return second > first;\r\n    }\r\n\r\n}\r\n\r\n/** @brief Obtain a vector analogous to vector[V] containing the order rank of each element.\r\n  *\r\n  * @param V    The vector of values to obtain order ranks for.\r\n  * @param ascending    TRUE to order from least to greatest, FALSE for the converse.\r\n  */\r\ntemplate<typename T>\r\nstd::vector<unsigned int> orderedIndex(const std::vector<T>& V,\r\n                                       const bool& ascending = true)\r\n{\r\n\r\n    if(V.empty())\r\n    {\r\n        return std::vector<unsigned int>();\r\n    }\r\n    else if(V.size() == 1)\r\n    {\r\n        return std::vector<unsigned int>(1, 0);\r\n    }\r\n\r\n    unsigned int L = V.size();\r\n    size_t i;\r\n\r\n    std::vector<index_ref<T>> i_refs;\r\n    std::vector<unsigned int> idx(L);\r\n\r\n    i_refs.reserve(L);\r\n\r\n    for(i = 0; i < L; ++i)\r\n    {\r\n        i_refs.emplace_back(V[i], i);\r\n    }\r\n\r\n    if(ascending)\r\n    {\r\n        std::sort(i_refs.begin(), i_refs.end());\r\n    }\r\n    else\r\n    {\r\n        std::sort(i_refs.rbegin(), i_refs.rend());\r\n    }\r\n\r\n    for(i = 0; i < L; ++i)\r\n    {\r\n        idx[i] = i_refs[i].index;\r\n    }\r\n\r\n    return idx;\r\n}\r\n\r\ninline std::vector<unsigned int> orderedIndex(const std::vector<float>& V,\r\n                                              const bool& ascending = true)\r\n{\r\n\r\n    if(V.empty())\r\n    {\r\n        return std::vector<unsigned int>();\r\n    }\r\n    else if(V.size() == 1)\r\n    {\r\n        return std::vector<unsigned int>(1, 0);\r\n    }\r\n\r\n    unsigned int L = V.size();\r\n    size_t i;\r\n\r\n    std::vector<index_ref<float>> i_refs;\r\n    std::vector<unsigned int> idx(L);\r\n\r\n    i_refs.reserve(L);\r\n\r\n    for(i = 0; i < L; ++i)\r\n    {\r\n        i_refs.emplace_back(V[i], i);\r\n    }\r\n\r\n    if(ascending)\r\n    {\r\n        std::sort(i_refs.begin(), i_refs.end(), nan_idx_sort<float>);\r\n    }\r\n    else\r\n    {\r\n        std::sort(i_refs.rbegin(), i_refs.rend(), nan_idx_sort<float>);\r\n    }\r\n\r\n    for(i = 0; i < L; ++i)\r\n    {\r\n        idx[i] = i_refs[i].index;\r\n    }\r\n\r\n    for(i = 0; i < L;)\r\n    {\r\n        if(isnan(V[idx[i]]))\r\n        {\r\n            idx.erase(idx.begin() + i);\r\n            --L;\r\n        }\r\n        else ++i;\r\n    }\r\n\r\n    return idx;\r\n}\r\n\r\ninline std::vector<unsigned int> orderedIndex(const std::vector<double>& V,\r\n                                              const bool& ascending = true)\r\n{\r\n\r\n    if(V.empty())\r\n    {\r\n        return std::vector<unsigned int>();\r\n    }\r\n    else if(V.size() == 1)\r\n    {\r\n        return std::vector<unsigned int>(1, 0);\r\n    }\r\n\r\n    unsigned int L = V.size();\r\n    size_t i;\r\n\r\n    std::vector<index_ref<double>> i_refs;\r\n    std::vector<unsigned int> idx(L);\r\n\r\n    i_refs.reserve(L);\r\n\r\n    for(i = 0; i < L; ++i)\r\n    {\r\n        i_refs.emplace_back(V[i], i);\r\n    }\r\n\r\n    if(ascending)\r\n    {\r\n        std::sort(i_refs.begin(), i_refs.end(), nan_idx_sort<double>);\r\n    }\r\n    else\r\n    {\r\n        std::sort(i_refs.rbegin(), i_refs.rend(), nan_idx_sort<double>);\r\n    }\r\n\r\n    for(i = 0; i < L; ++i)\r\n    {\r\n        idx[i] = i_refs[i].index;\r\n    }\r\n\r\n    for(i = 0; i < L;)\r\n    {\r\n        if(isnan(V[idx[i]]))\r\n        {\r\n            idx.erase(idx.begin() + i);\r\n            --L;\r\n        }\r\n        else ++i;\r\n    }\r\n\r\n    return idx;\r\n}\r\n\r\n/** @brief Obtain a vector containing only the unique values in vector [V]. */\r\ntemplate<typename T>\r\nstd::vector<T> unique(std::vector<T> V)\r\n{\r\n    size_t L = V.size();\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        for(size_t j = 0; j < L;)\r\n        {\r\n            if(j == i)\r\n            {\r\n                ++j;\r\n                continue;\r\n            }\r\n            else if(V[j] == V[i])\r\n            {\r\n                V.erase(V.begin() + j);\r\n                --L;\r\n            }\r\n            else ++j;\r\n        }\r\n    }\r\n    return V;\r\n}\r\n\r\n/** @brief Get a count of the number of unique values in vector [V]. */\r\ntemplate<typename T>\r\nunsigned int numUnique(const std::vector<T>& V)\r\n{\r\n    if(V.empty()) return 0;\r\n    else if(V.size() == 1) return 1;\r\n\r\n    unsigned int numDuplicated = 0;\r\n    bool duplicated = false;\r\n    std::vector<T> uniqueItems;\r\n    typename std::vector<T>::const_iterator endIT = V.end();\r\n    for(typename std::vector<T>::const_iterator it1 = V.begin(); it1 != endIT - 1; ++it1)\r\n    {\r\n        if(anyEqual(*it1, uniqueItems)) continue;\r\n        for(typename std::vector<T>::const_iterator it2 = it1 + 1; it2 != endIT; ++it2)\r\n        {\r\n            if(*it1 == *it2)\r\n            {\r\n                duplicated = true;\r\n                ++numDuplicated;\r\n            }\r\n        }\r\n        if(duplicated)\r\n        {\r\n            uniqueItems.emplace_back(*it1);\r\n            duplicated = false;\r\n        }\r\n    }\r\n    return V.size() - numDuplicated;\r\n}\r\n\r\ntemplate<typename T> std::vector<unsigned int> getRepeatCounts(const std::vector<T>& V)\r\n{\r\n    size_t L = V.size(), j;\r\n    std::vector<unsigned int> output(L, 1);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        for(j = 0; j < L; ++j)\r\n        {\r\n            if(i == j) continue;\r\n            if(V[i] == V[j]) ++output[i];\r\n        }\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> void rmDuplicates(std::vector<T> &V)\r\n{\r\n    size_t L = V.size();\r\n    if(L < 2) return;\r\n\r\n    for(size_t i = 0; i < L-1; ++i)\r\n    {\r\n        for(size_t j = i+1; j < L;)\r\n        {\r\n            if(V[j] == V[i])\r\n            {\r\n                V.erase(V.begin() + j);\r\n                --L;\r\n            }\r\n            else ++j;\r\n        }\r\n    }\r\n}\r\n\r\ninline unsigned int numValid(const std::vector<float>& V)\r\n{\r\n    unsigned int output = 0;\r\n    for(auto& val : V)\r\n    {\r\n        if(!isnan(val) && !isinf(val)) ++output;\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> void append(std::vector<T>& source, const std::vector<T>& other)\r\n{\r\n    source.insert(source.end(), other.begin(), other.end());\r\n}\r\n\r\ntemplate<typename T1, typename T2> unsigned int rank_in(const T1& item, std::vector<T2> V, bool ascending = false)\r\n{\r\n    if(V.size() < 1) return T1();\r\n    rmDuplicates(V);\r\n    typename std::vector<T2>::const_iterator itEND = V.end();\r\n    unsigned int rank = 0;\r\n    if(!ascending)\r\n    {\r\n        for(typename std::vector<T2>::const_iterator it = V.begin(); it != itEND; ++it)\r\n        {\r\n            if(*it > item) ++rank;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(typename std::vector<T2>::const_iterator it = V.begin(); it != itEND; ++it)\r\n        {\r\n            if(*it < item) ++rank;\r\n        }\r\n    }\r\n    return rank;\r\n}\r\n\r\ntemplate<typename T1, typename T2> void rank_list(std::vector<T1>& outputRanks, const std::vector<T2>& V, bool ascending = false)\r\n{\r\n    if(V.size() < 1) return;\r\n    std::vector<T2> uniqueV = V;\r\n    outputRanks.reserve(outputRanks.size() + V.size());\r\n    rmDuplicates(uniqueV);\r\n    typename std::vector<T2>::const_iterator itEND = V.end(), uniqueEND = uniqueV.end();\r\n    if(!ascending)\r\n    {\r\n        for(typename std::vector<T2>::const_iterator it = V.begin(); it != itEND; ++it)\r\n        {\r\n            unsigned int rank = 0;\r\n            for(typename std::vector<T2>::const_iterator unique = uniqueV.begin(); unique != uniqueEND; ++unique)\r\n            {\r\n                if(*unique > *it) ++rank;\r\n            }\r\n            outputRanks.push_back(rank);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(typename std::vector<T2>::const_iterator it = V.begin(); it != itEND; ++it)\r\n        {\r\n            unsigned int rank = 0;\r\n            for(typename std::vector<T2>::const_iterator unique = uniqueV.begin(); unique != uniqueEND; ++unique)\r\n            {\r\n                if(*unique < *it) ++rank;\r\n            }\r\n            outputRanks.push_back(rank);\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<typename T, typename O> void pairSort(std::vector<T> &V, std::vector<O> &other, bool ascending = true)\r\n{\r\n    size_t L = V.size();\r\n    if(ascending)\r\n    {\r\n        for(size_t i = 0; i < L-1; ++i)\r\n        {\r\n            for(size_t j = i+1; j < L; ++j)\r\n            {\r\n                if(V[j] < V[i])\r\n                {\r\n                    T tmp(V[i]);\r\n                    V[i] = V[j];\r\n                    V[j] = tmp;\r\n                    O otmp(other[i]);\r\n                    other[i] = other[j];\r\n                    other[j] = otmp;\r\n                }\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(size_t i = 0; i < L-1; ++i)\r\n        {\r\n            for(size_t j = i+1; j < L; ++j)\r\n            {\r\n                if(V[j] > V[i])\r\n                {\r\n                    T tmp(V[i]);\r\n                    V[i] = V[j];\r\n                    V[j] = tmp;\r\n                    O otmp(other[i]);\r\n                    other[i] = other[j];\r\n                    other[j] = otmp;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\ntemplate<typename T1, typename T2, typename T3>\r\nT1 gaussian_probability(const T1& obs, const T2& mean, const T3& sd)\r\n{\r\n    T1 var = sd*sd;\r\n    return exp(-pow((obs - mean), 2)/(2*var))/sqrt(2*PI*var);\r\n}\r\n\r\ntemplate<typename T1, typename T2, typename T3>\r\nT1 gaussian_centroid(const T1& obs, const T2& mean, const T3& sd)\r\n{\r\n    return gaussian_probability(obs, mean, sd)/gaussian_probability(mean, mean, sd);\r\n}\r\n\r\ntemplate<typename T> T factorial(T value)\r\n{\r\n    if(value == 0) return T(1);\r\n    if(value >= T(1)) value *= factorial(value-T(1));\r\n    return value;\r\n}\r\n\r\ntemplate<typename T> void to_ptrV(std::vector<T> &V, std::vector<T*>& ptrV)\r\n{\r\n    size_t L = V.size();\r\n    ptrV.reserve(L);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        ptrV.push_back(&V[i]);\r\n    }\r\n}\r\n\r\nbool increment(std::vector<unsigned int>& V, std::vector<unsigned int>& index, unsigned int iMAX);\r\nunsigned int strSum(std::string& s);\r\n\r\n// Matrix functions\r\n\r\ntemplate<typename T> std::vector<T> collapse(std::vector<std::vector<T>>& V)\r\n{\r\n    std::vector<T> output = V[0];\r\n    for(size_t i = 1; i < V.size(); ++i)\r\n    {\r\n        output = shared(output, V[i]);\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T>\r\nsize_t area(const std::vector<std::vector<T>>& M)\r\n{\r\n    size_t output = 0;\r\n    for(auto& row : M)\r\n    {\r\n        output += row.size();\r\n    }\r\n    return output;\r\n}\r\n\r\ntemplate<typename T>\r\nsize_t volume(const std::vector<std::vector<std::vector<T>>>& tensor)\r\n{\r\n    size_t output = 0;\r\n    for(auto& plane : tensor)\r\n    {\r\n        output += area(plane);\r\n    }\r\n    return output;\r\n}\r\n\r\n// Coordinate functions\r\n\r\n//template<typename T>\r\n//bool _2Dpath(vMatrix<T>& output,\r\n//             const std::vector<T>& begin,\r\n//             const std::vector<T>& end){\r\n//\r\n//    output.clear();\r\n//    if((begin.size() < 2) || (end.size() < 2)) return false;\r\n//\r\n//    float distX = end[0]-begin[0];\r\n//    float distY = end[1]-begin[1];\r\n//\r\n//    // Determine straight line distance\r\n//    float dist = sqrt(float(pow(distX, 2) + pow(distY, 2)));\r\n//    float stepX = distX != 0.0 ? distX/distY : 0.0;\r\n//    float stepY = distY != 0.0 ? distY/distX : 0.0;\r\n//\r\n//    std::vector<T> xCoords; xCoords.reserve(dist);\r\n//    std::vector<T> yCoords; yCoords.reserve(dist);\r\n//    xCoords.push_back(begin[0]); yCoords.push_back(begin[1]);\r\n//\r\n//    if(stepX != 0.0) for(float x = begin[0] + stepX; x <= distX; x += stepX){ xCoords.push_back(x); }\r\n//    if(stepY != 0.0) for(float y = begin[1] + stepY; y <= distY; y += stepY){ yCoords.push_back(y); }\r\n//    for(size_t i = 1; i < xCoords.size(); ++i){\r\n//        if(xCoords[i] > xCoords[i-1]+1){\r\n//            xCoords.insert(xCoords.begin() + i, xCoords[i-1]+1);\r\n//        }\r\n//    }\r\n//    for(size_t i = 1; i < yCoords.size(); ++i){\r\n//        if(yCoords[i] > yCoords[i-1]+1){\r\n//            yCoords.insert(yCoords.begin() + i, yCoords[i-1]+1);\r\n//        }\r\n//    }\r\n//\r\n//    while(xCoords.back() < end[0]){\r\n//        xCoords.push_back(xCoords.back() + 1);\r\n//    }\r\n//    while(yCoords.back() < end[1]){\r\n//        yCoords.push_back(yCoords.back() + 1);\r\n//    }\r\n//\r\n//    while(xCoords.size() < yCoords.size()){\r\n//        xCoords.push_back(xCoords.back());\r\n//    }\r\n//    while(yCoords.size() < xCoords.size()){\r\n//        yCoords.push_back(yCoords.back());\r\n//    }\r\n//\r\n//    for(size_t i = 0; i < xCoords.size(); ++i){\r\n//        output.push_back({xCoords[i], yCoords[i]});\r\n//    }\r\n//\r\n//    return output.size() > 0;\r\n//\r\n//}\r\n\r\ntemplate<typename T>\r\nbool _2Dpath(vMatrix<T>& output,\r\n             const std::vector<T>& begin,\r\n             const std::vector<T>& end)\r\n{\r\n\r\n    output.clear();\r\n    if((begin.size() < 2) || (end.size() < 2)) return false;\r\n\r\n    double distX = double(end[0])-double(begin[0]);\r\n    double distY = double(end[1])-double(begin[1]);\r\n\r\n    // Determine straight line distance\r\n\r\n    double xPos = begin[0],\r\n           yPos = begin[1],\r\n           x = 0.0,\r\n           y = 0.0,\r\n           inc,\r\n           xEnd = nround(end[0]),\r\n           yEnd = nround(end[1]);\r\n\r\n    // Determine angle of motion\r\n\r\n    double dist = sqrt(pow(distX,2) + pow(distY, 2)),\r\n           angle;\r\n    if(distY >= 0)\r\n    {\r\n        if(distX >= 0) angle = asin(distY/dist); // Q1\r\n        else angle = PI - asin(distY/dist); // Q2\r\n    }\r\n    else\r\n    {\r\n        if(distX >= 0) angle = 2*PI + asin(distY/dist); // Q4\r\n        else angle = PI - asin(distY/dist); // Q3\r\n    }\r\n\r\n    if(abs(distX) >= abs(distY))\r\n    {\r\n        do\r\n        {\r\n            output.emplace_back(std::vector<T>({T(xPos), T(yPos)}));\r\n\r\n            if(distX >= 0)\r\n            {\r\n                ++xPos;\r\n            }\r\n            else\r\n            {\r\n                --xPos;\r\n            }\r\n\r\n            ++x;\r\n\r\n            inc = 1.0*tan(angle);\r\n            if((inc > 0) ^ (distY > 0))\r\n            {\r\n                inc = -inc;\r\n            }\r\n            yPos += inc;\r\n\r\n        }\r\n        while(x <= abs(distX));\r\n    }\r\n    else\r\n    {\r\n        do\r\n        {\r\n            output.emplace_back(std::vector<T>({T(xPos), T(yPos)}));\r\n\r\n            if(distY >= 0)\r\n            {\r\n                ++yPos;\r\n            }\r\n            else\r\n            {\r\n                --yPos;\r\n            }\r\n\r\n            ++y;\r\n\r\n            inc = 1.0/tan(angle);\r\n            if((inc > 0) ^ (distX > 0))\r\n            {\r\n                inc = -inc;\r\n            }\r\n            xPos += inc;\r\n\r\n        }\r\n        while(y <= abs(distY));\r\n    }\r\n\r\n    return output.size() > 0;\r\n\r\n}\r\n\r\ntemplate<typename T> float horizontal_angle(const T& originX, const T& originY,\r\n        const T& destinationX, const T& destinationY)\r\n{\r\n    float dist = sqrt(pow(destinationX - originX,2) + pow(destinationY - originY, 2));\r\n    float vDist = destinationY - originY;\r\n    return asin(vDist/dist) * 180.0f/PI;\r\n}\r\n\r\ntemplate<typename T> float vertical_angle(const T& originX, const T& originY,\r\n        const T& destinationX, const T& destinationY)\r\n{\r\n    float dist = sqrt(float(pow(destinationX - originX, 2) + pow(destinationY - originY, 2)));\r\n    float hDist = destinationX - originX;\r\n    return acos(hDist/dist) * 180.0f/PI;\r\n}\r\n\r\n// Statistical algorithms\r\n\r\ninline float pearson_coefficient(const std::vector<float>& xV, const std::vector<float>& yV)\r\n{\r\n    float sumX(0.0f), sumY(0.0f), sumXY(0.0f), sumXsq(0.0f), sumYsq(0.0f);\r\n    unsigned int L = (xV.size() <= yV.size()) ? xV.size() : yV.size();\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(xV[i]) || isnan(yV[i])) continue;\r\n        sumX += xV[i];\r\n        sumY += yV[i];\r\n        sumXY += (xV[i]*yV[i]);\r\n        sumXsq += pow(xV[i], 2);\r\n        sumYsq += pow(yV[i], 2);\r\n    }\r\n    return (L*sumXY - (sumX*sumY))/(sqrt(L*sumXsq - pow(sumX, 2))*sqrt(L*sumYsq - pow(sumY, 2)));\r\n}\r\n\r\ninline float spearman_coefficient(const std::vector<float>& xV, const std::vector<float>& yV)\r\n{\r\n    unsigned int L = (xV.size() <= yV.size()) ? xV.size() : yV.size();\r\n    if(L < 1) return NAN;\r\n\r\n    std::vector<float> rankX, rankY;\r\n    rank_list(rankX, xV);\r\n    rank_list(rankY, yV);\r\n\r\n    float sumX(0.0f), sumY(0.0f), sumXY(0.0f), sumXsq(0.0f), sumYsq(0.0f);\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(rankX[i]) || isnan(rankY[i])) continue;\r\n        sumX += rankX[i];\r\n        sumY += rankY[i];\r\n        sumXY += (rankX[i]*rankY[i]);\r\n        sumXsq += pow(rankX[i], 2);\r\n        sumYsq += pow(rankY[i], 2);\r\n    }\r\n    return (L*sumXY - (sumX*sumY))/(sqrt(L*sumXsq - pow(sumX, 2))*sqrt(L*sumYsq - pow(sumY, 2)));\r\n}\r\n\r\ninline float point_biserial_coefficient(const std::vector<float>& data,\r\n                                        const std::vector<unsigned int>& outcomeIndex)\r\n{\r\n    unsigned int L = data.size();\r\n    if(L < 1) return NAN;\r\n\r\n    float posMean = 0.0f, negMean = 0.0f, allMean = 0.0f, MSE = 0.0f;\r\n    unsigned int posSIZE = 0, negSIZE = 0, tSIZE = 0;\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(data[i])) continue;\r\n\r\n        allMean += data[i];\r\n        ++tSIZE;\r\n        if(anyEqual(i, outcomeIndex))\r\n        {\r\n            ++posSIZE;\r\n            posMean += data[i];\r\n        }\r\n        else\r\n        {\r\n            ++negSIZE;\r\n            negMean += data[i];\r\n        }\r\n    }\r\n    if((posSIZE < 1) || (negSIZE < 1)) return NAN;\r\n\r\n    posMean /= posSIZE;\r\n    negMean /= negSIZE;\r\n    allMean /= tSIZE;\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(data[i])) continue;\r\n        MSE += pow(data[i] - allMean, 2);\r\n    }\r\n\r\n    return ((posMean-negMean)/sqrt(MSE/tSIZE))*sqrt(posSIZE*negSIZE/pow(tSIZE, 2));\r\n}\r\n\r\ninline float signal_to_noise(const std::vector<float>& data,\r\n                             const std::vector<unsigned int>& outcomeIndex)\r\n{\r\n    unsigned int L = data.size();\r\n    if(numValid(data) < 2) return NAN;\r\n    if(outcomeIndex.empty()) return NAN;\r\n\r\n    std::vector<float> sample, rem;\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(data[i])) continue;\r\n        else if(!anyEqual(i, outcomeIndex)) rem.push_back(data[i]);\r\n        else\r\n        {\r\n            sample.push_back(data[i]);\r\n        }\r\n    }\r\n\r\n    if(sample.empty() || rem.empty()) return NAN;\r\n\r\n    if(sample.size() == 1)\r\n    {\r\n\r\n        if(rem.size() > 1)\r\n        {\r\n            return (sample.front() - average(rem))/stdev(data);\r\n        }\r\n        else\r\n        {\r\n            return (sample.front() - rem.front())/stdev(data);\r\n        }\r\n\r\n    }\r\n\r\n    return (average(sample) - average(rem))/(stdev(rem) + stdev(sample));\r\n}\r\n\r\n/** @brief Calculate slope/intercept regression using the least squares method.\r\n  *\r\n  * @param xV   Vector of X values.\r\n  * @param yV   Vector of Y Values.\r\n  * @param slopeOutput  Variable to store the slope output in.\r\n  * @param interceptOutput Variable to store the intercept output in. */\r\ntemplate<typename real_t>\r\nvoid least_squares_fit(const std::vector<real_t>& xV, const std::vector<real_t>& yV,\r\n                              real_t& slopeOutput, real_t& interceptOutput)\r\n{\r\n\r\n    real_t sumX(0.0f);\r\n    real_t sumY(0.0f);\r\n    real_t sumXY(0.0f);\r\n    real_t sumXsq(0.0f);\r\n    real_t sumDev = 0.0f;\r\n    real_t avgX = (average(xV));\r\n\r\n    unsigned int L = (xV.size() <= yV.size()) ? xV.size() : yV.size(), N = 0;\r\n\r\n    for(size_t i = 0; i < L; ++i)\r\n    {\r\n        if(isnan(xV[i]) || isnan(yV[i])) continue;\r\n\r\n        sumX += xV[i];\r\n        sumY += yV[i];\r\n        sumXY += (xV[i]*yV[i]);\r\n        sumXsq += pow(xV[i], 2);\r\n        sumDev += pow((xV[i] - avgX), 2);\r\n        ++N;\r\n    }\r\n\r\n    slopeOutput = (N*sumXY - sumX*sumY)/(N*sumDev);\r\n    interceptOutput = (sumXsq*sumY - sumX*sumXY)/(N*sumDev);\r\n\r\n}\r\n\r\ninline bool isValid(const std::vector<float>& V)\r\n{\r\n    for(auto val : V)\r\n    {\r\n        if(!isnan(val) && !isinf(val)) return true;\r\n    }\r\n    return false;\r\n}\r\n\r\ninline float chisq_p(float F, int df)\r\n{\r\n    if((df < 1) || F < 0.0f) return 0.0f;\r\n\r\n    float X = F/2;\r\n    if(df == 2)\r\n    {\r\n        return exp(-X);\r\n    }\r\n\r\n    float K = (float(df)/2);\r\n\r\n    float Sc = 1.0f/K * pow(X, K) * exp(-X);\r\n\r\n    float sum = 1.0f, nom = 1.0f, denom = 1.0f, sK = K;\r\n\r\n    for(unsigned int i = 0; i < 200; ++i)\r\n    {\r\n        nom *= X;\r\n        ++sK;\r\n        denom *= sK;\r\n        sum += (nom/denom);\r\n    }\r\n\r\n    float p = sum * Sc;\r\n    if(isnan(p) || isinf(p))\r\n    {\r\n        return 1e-14;\r\n    }\r\n\r\n    return 1.0f - p / tgamma(K);\r\n}\r\n\r\ntemplate<typename T> double student_t_test(const std::vector<T>& P1,\r\n        const std::vector<T>& P2,\r\n        const uint8_t& tail = STATS_TWO_TAILED)\r\n{\r\n\r\n    size_t S1 = validSize(P1), S2 = validSize(P2), V = S1 + S2 - 2;\r\n    if((S1 < 3) || (S2 < 3)) return NAN;\r\n\r\n    double SD1 = stdev(P1), SD2 = stdev(P2);\r\n    double Sp = sqrt(((S1-1)*pow(SD1, 2) + (S2-1)*pow(SD2, 2))/(V));\r\n    double t_stat = absolute((average(P1) - average(P2))/(Sp*sqrt(1.0f/S1 + 1.0f/S2)));\r\n\r\n    if(isinf(t_stat) || isnan(t_stat)) return NAN;\r\n\r\n    boost::math::students_t dist(V);\r\n\r\n    double output;\r\n    switch(tail)\r\n    {\r\n    case STATS_UPPER_TAIL:\r\n    {\r\n        output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        if(output < 0.0) return 1.0;\r\n        break;\r\n    }\r\n    case STATS_LOWER_TAIL:\r\n    {\r\n        output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        if(output > 0.0) return 1.0;\r\n        break;\r\n    }\r\n    default:\r\n    {\r\n        output = boost::math::cdf(boost::math::complement(dist, t_stat))*2;\r\n        break;\r\n    }\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> double population_mean_test(const std::vector<T>& sample,\r\n        const std::vector<T>& population,\r\n        const uint8_t& tail = STATS_TWO_TAILED,\r\n        bool bonferroni_correct = true)\r\n{\r\n\r\n    size_t S1 = validSize(sample), S2 = validSize(population), V = S1 + S2 - 2;\r\n    if((S1 < 2) || (S2 < 2)) return NAN;\r\n\r\n    double t_stat = abs(average(sample));\r\n    double Sp = sqrt(((S1-1)*pow(stdev(sample), 2) + (S2-1)*pow(stdev(population), 2))/(V)); // Pooled variation\r\n\r\n    if((Sp == 0.0) || isinf(Sp) || isnan(Sp)) return NAN;\r\n\r\n    boost::math::normal_distribution<double> dist(average(population), Sp);\r\n\r\n    double output;\r\n    switch(tail)\r\n    {\r\n    case STATS_UPPER_TAIL:\r\n    {\r\n        if(t_stat < average(population)) output = 1.0;\r\n        else output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        break;\r\n    }\r\n    case STATS_LOWER_TAIL:\r\n    {\r\n        if(t_stat > average(population)) output = 1.0;\r\n        else output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        break;\r\n    }\r\n    default:\r\n    {\r\n        output = boost::math::cdf(boost::math::complement(dist, t_stat))*2;\r\n        break;\r\n    }\r\n    }\r\n\r\n    if(bonferroni_correct)\r\n    {\r\n        output *= V;\r\n        if(output > 1.0) return 1.0;\r\n    }\r\n\r\n    return output;\r\n\r\n}\r\n\r\ntemplate<typename T> double one_sample_test(const T& sample,\r\n        const std::vector<T>& population,\r\n        const uint8_t& tail = STATS_TWO_TAILED,\r\n        bool bonferroni_correct = true)\r\n{\r\n    if(isnan(sample)) return NAN;\r\n    size_t N = validSize(population);\r\n    double t_stat = abs(sample),\r\n           SD = stdev(population);\r\n\r\n    if((SD == 0.0) || isinf(SD) || isnan(SD)) return NAN;\r\n    boost::math::normal_distribution<double> dist(average(population), SD);\r\n\r\n    double output;\r\n    switch(tail)\r\n    {\r\n    case STATS_UPPER_TAIL:\r\n    {\r\n        if(t_stat < average(population)) output = 1.0;\r\n        else output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        break;\r\n    }\r\n    case STATS_LOWER_TAIL:\r\n    {\r\n        if(t_stat > average(population)) output = 1.0;\r\n        else output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        break;\r\n    }\r\n    default:\r\n    {\r\n        output = boost::math::cdf(boost::math::complement(dist, t_stat))*2;\r\n        break;\r\n    }\r\n    }\r\n\r\n    if(bonferroni_correct)\r\n    {\r\n        output *= N;\r\n        if(output > 1.0) return 1.0;\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> double one_sample_test(const T& sample,\r\n        const std::vector<std::vector<T>>& population,\r\n        const uint8_t& tail = STATS_TWO_TAILED,\r\n        bool bonferroni_correct = true)\r\n{\r\n    if(isnan(sample)) return NAN;\r\n    size_t N = validSize(population);\r\n    double t_stat = abs(sample),\r\n           SD = stdev(population);\r\n\r\n    if((SD == 0.0) || isinf(SD) || isnan(SD)) return NAN;\r\n    boost::math::normal_distribution<double> dist(average(population), SD);\r\n\r\n    double output;\r\n    switch(tail)\r\n    {\r\n    case STATS_UPPER_TAIL:\r\n    {\r\n        if(t_stat < average(population)) output = 1.0;\r\n        else output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        break;\r\n    }\r\n    case STATS_LOWER_TAIL:\r\n    {\r\n        if(t_stat > average(population)) output = 1.0;\r\n        else output = boost::math::cdf(boost::math::complement(dist, t_stat));\r\n        break;\r\n    }\r\n    default:\r\n    {\r\n        output = boost::math::cdf(boost::math::complement(dist, t_stat))*2;\r\n        break;\r\n    }\r\n    }\r\n\r\n    if(bonferroni_correct)\r\n    {\r\n        output *= N;\r\n        if(output > 1.0) return 1.0;\r\n    }\r\n\r\n    return output;\r\n}\r\n\r\ntemplate<typename T> double one_sample_test(const std::vector<T>& sample,\r\n        const std::vector<std::vector<T>>& population,\r\n        const uint8_t& tail = STATS_TWO_TAILED,\r\n        bool bonferroni_correct = true)\r\n{\r\n    return one_sample_test(average(sample), population, tail, bonferroni_correct);\r\n}\r\n\r\ninline float odds_ratio(const int& O, int OT,\r\n                        int N, int T)\r\n{\r\n\r\n    // O = number of outcomes of interest in experimental group\r\n    // OT = number of outcomes of interest in total\r\n    // N = population size of interest\r\n    // T = total population size\r\n\r\n    T -= N;\r\n    OT -= O;\r\n    N -= O;\r\n    T -= OT;\r\n\r\n    return ((float)O/OT)/((float)N/T);\r\n}\r\n\r\ninline float odds_chisq_test(const int& O, int OT, int N, int T)\r\n{\r\n\r\n    float df = OT-1;\r\n    if(df < 1) return NAN;\r\n\r\n    float P = (float)N/T;\r\n\r\n    float EO = (float)OT*P;\r\n    float EOT = (float)OT*(1.0f-P);\r\n    float ET = (float)T-(float)N-EOT;\r\n    float EN = (float)N-EO;\r\n\r\n    T -= N;\r\n    OT -= O;\r\n    N -= O;\r\n    T -= OT;\r\n\r\n    float alpha = pow(((float)O - EO), 2)/EO + pow(((float)OT - EOT), 2)/EOT +\r\n                  pow(((float)N - EN), 2)/EN + pow(((float)T - ET), 2)/ET;\r\n    if(isnan(alpha) || isinf(alpha)) return 1.0f;\r\n\r\n    boost::math::students_t dist(df);\r\n    return boost::math::cdf(boost::math::complement(dist, alpha))*2;\r\n}\r\n\r\ntemplate<typename T> double logFactorial(T N)\r\n{\r\n    double output = 0.0;\r\n    for(; N > 0; --N)\r\n    {\r\n        output += log10(double(N));\r\n    }\r\n    return output;\r\n}\r\n\r\ninline long double hypergeometric_probability(const int& a, const int& b, const int& c, const int& d)\r\n{\r\n    return pow(10, (logFactorial(a+b) +\r\n                    logFactorial(c+d) +\r\n                    logFactorial(a+c) +\r\n                    logFactorial(b+d) -\r\n                    logFactorial(a+b+c+d) -\r\n                    logFactorial(a) -\r\n                    logFactorial(b) -\r\n                    logFactorial(c) -\r\n                    logFactorial(d)));\r\n}\r\n\r\n/** @brief Calculate the Fisher exact P-value for a 2x2 contingency table.\r\n  *\r\n  * Applies the hypergeometric probability to all possible contingency tables\r\n  * to test the hypothesis that the provided table deviates from the possible\r\n  * tables beyond chance.\r\n  *\r\n  * @param O    Number of observed positives.\r\n  * @param OT   Total number of positives.\r\n  * @param N    Sample population size.\r\n  * @param T    Background population size.\r\n  * @param bonferroni_correct Apply the bonferroni correction to the\r\n  * resulting p-value.\r\n  */\r\ninline long double fisher_exact_P(const int& O, int OT, int N, int T,\r\n                                  const bool& bonferroni_correct = false)\r\n{\r\n\r\n    // Total number of possible tables\r\n    int total = T;\r\n\r\n    // Get total number of negatives\r\n    T -= N;\r\n\r\n    // Get number of sample negatives\r\n    OT -= O;\r\n\r\n    // Get number of positives in the background\r\n    N -= O;\r\n\r\n    // Get number of negatives in the background\r\n    T -= OT;\r\n\r\n    // Assess the significance cutoff via hypergeometric distribution\r\n    long double p_cutoff = hypergeometric_probability(O, OT, N, T);\r\n    long double p_value = 0.0L;\r\n\r\n    for(int i = 0; i <= total; ++i)\r\n    {\r\n        if((O + OT - i >= 0) && (O + N - i >= 0) && (T - O + i >= 0))\r\n        {\r\n            long double p = hypergeometric_probability(i, O + OT - i, O + N - i, T - O + i);\r\n            if(p <= p_cutoff) p_value += p;\r\n        }\r\n    }\r\n\r\n    if(bonferroni_correct)\r\n    {\r\n        p_value *= total;\r\n        if(p_value > 1.0L) return 1.0L;\r\n    }\r\n\r\n    return p_value;\r\n\r\n}\r\n\r\n// Time\r\n\r\ninline float getDuration(const std::chrono::high_resolution_clock::time_point& time_point)\r\n{\r\n    return std::chrono::duration<float>(TIME_NOW - time_point).count();\r\n}\r\n\r\n}\r\n\r\n\r\n\r\n#endif // HYPER_ALGORITHM\r\n", "meta": {"hexsha": "c9316ada0e7def98622e4a8555acca1e34ae7cd4", "size": 104023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hyper/algorithm.hpp", "max_stars_repo_name": "DamianTran/hyper", "max_stars_repo_head_hexsha": "8f22d98278a03c9fa07b91cacdf8c298691805d5", "max_stars_repo_licenses": ["MIT"], "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/hyper/algorithm.hpp", "max_issues_repo_name": "DamianTran/hyper", "max_issues_repo_head_hexsha": "8f22d98278a03c9fa07b91cacdf8c298691805d5", "max_issues_repo_licenses": ["MIT"], "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/hyper/algorithm.hpp", "max_forks_repo_name": "DamianTran/hyper", "max_forks_repo_head_hexsha": "8f22d98278a03c9fa07b91cacdf8c298691805d5", "max_forks_repo_licenses": ["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.7144214778, "max_line_length": 130, "alphanum_fraction": 0.5031964085, "num_tokens": 27030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.03410042448529082, "lm_q1q2_score": 0.01401905515133381}}
{"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_STORAGE_SPARSE_H\n#define BOOST_UBLAS_STORAGE_SPARSE_H\n\n#include <algorithm>\n#include <map>\n#include <set>\n\n#include <boost/numeric/ublas/config.hpp>\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/iterator.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    namespace detail {\n\n        template<class I, class T, class C>\n        BOOST_UBLAS_INLINE\n        I lower_bound (const I &begin, const I &end, const T &t, C compare) {\n            // t <= *begin <=> ! (*begin < t)\n            if (begin == end || ! compare (*begin, t))\n                return begin;\n            if (compare (*(end - 1), t))\n                return end;\n            return std::lower_bound (begin, end, t, compare);\n        }\n        template<class I, class T, class C>\n        BOOST_UBLAS_INLINE\n        I upper_bound (const I &begin, const I &end, const T &t, C compare) {\n            if (begin == end || compare (t, *begin))\n                return begin;\n            // (*end - 1) <= t <=> ! (t < *end)\n            if (! compare (t, *(end - 1)))\n                return end;\n            return std::upper_bound (begin, end, t, compare);\n        }\n\n        template<class P>\n        struct less_pair {\n            BOOST_UBLAS_INLINE\n            bool operator () (const P &p1, const P &p2) {\n                return p1.first < p2.first;\n            }\n        };\n        template<class T>\n        struct less_triple {\n            BOOST_UBLAS_INLINE\n            bool operator () (const T &t1, const T &t2) {\n                return t1.first.first < t2.first.first ||\n                       (t1.first.first == t2.first.first && t1.first.second < t2.first.second);\n            }\n        };\n\n    }\n\n#ifdef BOOST_UBLAS_STRICT_STORAGE_SPARSE\n    template<class D>\n    struct sparse_storage_element_traits {\n        typedef typename D::index_type index_type;\n        typedef typename D::data_const_reference data_const_reference;\n        typedef typename D::data_reference data_reference;\n    };\n    template<>\n    struct sparse_storage_element_traits<float> {\n        typedef std::size_t index_type;\n        typedef void data_const_reference;\n        typedef void data_reference;\n    };\n    template<>\n    struct sparse_storage_element_traits<double> {\n        typedef std::size_t index_type;\n        typedef void data_const_reference;\n        typedef void data_reference;\n    };\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\n    template<>\n    struct sparse_storage_element_traits<long double> {\n        typedef std::size_t index_type;\n        typedef void data_const_reference;\n        typedef void data_reference;\n    };\n#endif\n    template<>\n    struct sparse_storage_element_traits<std::complex<float> > {\n        typedef std::size_t index_type;\n        typedef void data_const_reference;\n        typedef void data_reference;\n    };\n    template<>\n    struct sparse_storage_element_traits<std::complex<double> > {\n        typedef std::size_t index_type;\n        typedef void data_const_reference;\n        typedef void data_reference;\n    };\n#ifdef BOOST_UBLAS_USE_LONG_DOUBLE\n    template<>\n    struct sparse_storage_element_traits<std::complex<long double> > {\n        typedef std::size_t index_type;\n        typedef void data_const_reference;\n        typedef void data_reference;\n    };\n#endif\n\n    template<class A>\n    class sparse_storage_element:\n       public container_reference<A> {\n    public:\n        typedef A array_type;\n        typedef typename A::index_type index_type;\n        typedef typename A::data_value_type data_value_type;\n        // typedef const data_value_type &data_const_reference;\n        typedef typename type_traits<data_value_type>::const_reference data_const_reference;\n        typedef data_value_type &data_reference;\n        typedef std::pair<index_type, data_value_type> value_type;\n        typedef std::pair<index_type, data_value_type> *pointer;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        sparse_storage_element (array_type &a, pointer it):\n            container_reference<array_type> (a), it_ (it), i_ (it->first), d_ (it->second) {}\n        BOOST_UBLAS_INLINE\n        sparse_storage_element (array_type &a, index_type i):\n            container_reference<array_type> (a), it_ (), i_ (i), d_ () {\n            pointer it = (*this) ().find (i_);\n            if (it == (*this) ().end ())\n                it = (*this) ().insert ((*this) ().end (), value_type (i_, d_));\n            d_ = it->second;\n        }\n        BOOST_UBLAS_INLINE\n        ~sparse_storage_element () {\n            if (! it_)\n                it_ = (*this) ().find (i_);\n            BOOST_UBLAS_CHECK (it_ != (*this) ().end (), internal_logic ());\n            it_->second = d_;\n        }\n\n        // Element access\n        // FIXME: GCC 3.1 warn's, if enabled\n#ifndef __GNUC__\n        BOOST_UBLAS_INLINE\n        typename sparse_storage_element_traits<data_value_type>::data_const_reference\n        operator [] (typename sparse_storage_element_traits<data_value_type>::index_type i) const {\n            return d_ [i];\n        }\n#endif\n        BOOST_UBLAS_INLINE\n        typename sparse_storage_element_traits<data_value_type>::data_reference\n        operator [] (typename sparse_storage_element_traits<data_value_type>::index_type i) {\n            return d_ [i];\n        }\n\n        // Assignment\n        template<class D>\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator = (const D &d) {\n            d_ = d;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator = (const sparse_storage_element &p) {\n            d_ = p.d_;\n            return *this;\n        }\n        template<class D>\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator += (const D &d) {\n            d_ += d;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator += (const sparse_storage_element &p) {\n            d_ += p.d_;\n            return *this;\n        }\n        template<class D>\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator -= (const D &d) {\n            d_ -= d;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator -= (const sparse_storage_element &p) {\n            d_ -= p.d_;\n            return *this;\n        }\n        template<class D>\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator *= (const D &d) {\n            d_ *= d;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator *= (const sparse_storage_element &p) {\n            d_ *= p.d_;\n            return *this;\n        }\n        template<class D>\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator /= (const D &d) {\n            d_ /= d;\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        sparse_storage_element &operator /= (const sparse_storage_element &p) {\n            d_ /= p.d_;\n            return *this;\n        }\n\n        // Conversion\n        // FIXME: GCC 3.1 warn's, if enabled\n#ifndef __GNUC__\n        BOOST_UBLAS_INLINE\n        operator data_const_reference () const {\n            return d_;\n        }\n#endif\n        BOOST_UBLAS_INLINE\n        operator data_reference () {\n            return d_;\n        }\n\n    private:\n        pointer it_;\n        index_type i_;\n        data_value_type d_;\n    };\n#endif\n\n    // Map array\n    template<class I, class T>\n    class map_array {\n    public:\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef I index_type;\n        typedef T data_value_type;\n        // typedef const T &data_const_reference;\n        typedef typename type_traits<T>::const_reference data_const_reference;\n#ifndef BOOST_UBLAS_STRICT_STORAGE_SPARSE\n        typedef T &data_reference;\n#else\n        typedef sparse_storage_element<map_array> data_reference;\n#endif\n        typedef std::pair<I, T> value_type;\n        typedef const std::pair<I, T> &const_reference;\n        typedef std::pair<I, T> &reference;\n        typedef const std::pair<I, T> *const_pointer;\n        typedef std::pair<I, T> *pointer;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        map_array ():\n            capacity_ (0), data_ (new value_type [0]), size_ (0) {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n        }\n        BOOST_UBLAS_EXPLICIT BOOST_UBLAS_INLINE\n        map_array (size_type size):\n            capacity_ (size), data_ (new value_type [size]), size_ (0) {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n        }\n        BOOST_UBLAS_INLINE\n        map_array (const map_array &a):\n            capacity_ (a.size_), data_ (new value_type [a.size_]), size_ (a.size_) {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n            *this = a;\n        }\n        BOOST_UBLAS_INLINE\n        ~map_array () {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n            delete [] data_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size) {\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n            if (size > capacity_) {\n                pointer data = new value_type [size << 1];\n                // Assuming std compliant allocator as requested during review.\n                // if (! data)\n                //     throw std::bad_alloc ();\n                // if (! data_)\n                //     throw std::bad_alloc ();\n                std::copy (data_, data_ + size_, data);\n                delete [] data_;\n                capacity_ = size << 1;\n                data_ = data;\n            }\n            size_ = size;\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n        }\n\n        // Reserving\n        BOOST_UBLAS_INLINE\n        void reserve (size_type capacity) {\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n            if (capacity > capacity_) {\n                pointer data = new value_type [capacity];\n                // Assuming std compliant allocator as requested during review.\n                // if (! data)\n                //     throw std::bad_alloc ();\n                // if (! data_)\n                //     throw std::bad_alloc ();\n                std::copy (data_, data_ + size_, data);\n                delete [] data_;\n                capacity_ = capacity;\n                data_ = data;\n            }\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n        }\n\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        data_reference operator [] (index_type i) {\n#ifndef BOOST_UBLAS_STRICT_STORAGE_SPARSE\n            pointer it = find (i);\n            if (it == end ())\n                it = insert (end (), value_type (i, data_value_type ()));\n            BOOST_UBLAS_CHECK (it != end (), internal_logic ());\n            return it->second;\n#else\n            return data_reference (*this, i);\n#endif\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        map_array &operator = (const map_array &a) {\n            // Too unusual semantic.\n            // Thanks to Michael Stevens for spotting this.\n            // BOOST_UBLAS_CHECK (this != &a, external_logic ());\n            if (this != &a) {\n                resize (a.size_);\n                std::copy (a.data_, a.data_ + a.size_, data_);\n            }\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        map_array &assign_temporary (map_array &a) {\n            swap (a);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (map_array &a) {\n            // Too unusual semantic.\n            // BOOST_UBLAS_CHECK (this != &a, external_logic ());\n            if (this != &a) {\n                std::swap (capacity_, a.capacity_);\n                std::swap (data_, a.data_);\n                std::swap (size_, a.size_);\n            }\n        }\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\n        BOOST_UBLAS_INLINE\n        friend void swap (map_array &a1, map_array &a2) {\n            a1.swap (a2);\n        }\n#endif\n\n        // Element insertion and deletion\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer push_back (pointer it, const value_type &p) {\n            if (size () == 0 || (it = end () - 1)->first < p.first) {\n                resize (size () + 1);\n                *(it = end () - 1) = p;\n                return it;\n            }\n            // Raising exceptions abstracted as requested during review.\n            // throw external_logic ();\n            external_logic ().raise ();\n            return it;\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer insert (pointer it, const value_type &p) {\n            it = detail::lower_bound (begin (), end (), p, detail::less_pair<value_type> ());\n            difference_type n = it - begin ();\n            BOOST_UBLAS_CHECK (size () == 0 || size () == size_type (n) || it->first != p.first, external_logic ());\n            resize (size () + 1);\n            it = begin () + n;\n            std::copy_backward (it, end () - 1, end ());\n            *it = p;\n            return it;\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void insert (pointer it, pointer it1, pointer it2) {\n#ifdef BOOST_UBLAS_BOUNDS_CHECK\n            while (it1 != it2) {\n                insert (it, *it1);\n                ++ it1;\n            }\n#else\n            difference_type n = it - begin ();\n            resize (size () + it2 - it1);\n            it = begin () + n;\n            std::copy (it1, it2, it);\n            std::sort (begin (), end (), detail::less_pair<value_type> ());\n#endif\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void erase (pointer it) {\n            BOOST_UBLAS_CHECK (begin () <= it && it < end (), bad_index ());\n            // Fixed by George Katsirelos.\n            // (*it).second = data_value_type ();\n            std::copy (it + 1, end (), it);\n            resize (size () - 1);\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void erase (pointer it1, pointer it2) {\n            BOOST_UBLAS_CHECK (begin () <= it1 && it1 < it2 && it2 <= end (), bad_index ());\n            // Fixed by George Katsirelos.\n            // while (it1 != it2) {\n            //     BOOST_UBLAS_CHECK (begin () <= it1 && it1 < end (), bad_index ());\n            //     (*it1).second = data_value_type ();\n            //     ++ it1;\n            // }\n            std::copy (it2, end (), it1);\n            resize (size () - (it2 - it1));\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void clear () {\n            resize (0);\n        }\n\n        // Element lookup\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        const_pointer find (index_type i) const {\n#ifdef BOOST_UBLAS_DEPRECATED\n            std::pair<const_pointer, const_pointer> pit;\n            pit = std::equal_range (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ());\n            if (pit.first->first == i)\n                return pit.first;\n            else if (pit.second->first == i)\n                return pit.second;\n            else\n                return end ();\n#else\n            const_pointer it (detail::lower_bound (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ()));\n            if (it == end () || it->first != i)\n                it = end ();\n            return it;\n#endif\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer find (index_type i) {\n#ifdef BOOST_UBLAS_DEPRECATED\n            std::pair<pointer, pointer> pit;\n            pit = std::equal_range (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ());\n            if (pit.first->first == i)\n                return pit.first;\n            else if (pit.second->first == i)\n                return pit.second;\n            else\n                return end ();\n#else\n            pointer it (detail::lower_bound (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ()));\n            if (it == end () || it->first != i)\n                it = end ();\n            return it;\n#endif\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        const_pointer lower_bound (index_type i) const {\n            return detail::lower_bound (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ());\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer lower_bound (index_type i) {\n            return detail::lower_bound (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ());\n        }\n#ifdef BOOST_UBLAS_DEPRECATED\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        const_pointer upper_bound (index_type i) const {\n            return detail::upper_bound (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ());\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer upper_bound (index_type i) {\n            return detail::upper_bound (begin (), end (), value_type (i, data_value_type ()), detail::less_pair<value_type> ());\n        }\n#endif\n\n        // Iterators simply are pointers.\n\n        typedef const_pointer const_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return data_ + size_;\n        }\n\n        typedef pointer iterator;\n\n        BOOST_UBLAS_INLINE\n        iterator begin () {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        iterator end () {\n            return data_ + size_;\n        }\n\n        // Reverse iterators\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef std::reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator;\n#else\n        typedef std::reverse_iterator<const_iterator> const_reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef std::reverse_iterator<iterator, value_type, reference> reverse_iterator;\n#else\n        typedef std::reverse_iterator<iterator> reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator rbegin () {\n            return reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rend () {\n            return reverse_iterator (begin ());\n        }\n\n    private:\n        size_type capacity_;\n        pointer data_;\n        size_type size_;\n    };\n\n    template<class I, class T>\n    BOOST_UBLAS_INLINE\n    map_array<I, T> &assign_temporary (map_array<I, T> &a1, map_array<I, T> &a2) {\n        return a1.assign_temporary (a2);\n    }\n\n    template<class I, class T, class F>\n    BOOST_UBLAS_INLINE\n    std::map<I, T, F> &assign_temporary (std::map<I, T, F> &a1, std::map<I, T, F> &a2) {\n        // Too unusual semantic.\n        // BOOST_UBLAS_CHECK (&a1 != &a2, external_logic ());\n        if (&a1 != &a2)\n            a1.swap (a2);\n        return  a1;\n    }\n    // This specialization is missing in Dinkumware's STL?!\n    template<class I, class T, class F>\n    BOOST_UBLAS_INLINE\n    void swap (std::map<I, T, F> &a1, std::map<I, T, F> &a2) {\n        // Too unusual semantic.\n        // BOOST_UBLAS_CHECK (&a1 != &a2, external_logic ());\n        if (&a1 != &a2)\n            a1.swap (a2);\n    }\n\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\n    template<class A>\n    struct map_traits {};\n    template<class I, class T>\n    struct map_traits<std::map<I, T> > {\n        typedef typename std::map<I, T>::size_type size_type;\n        typedef typename std::map<I, T>::mapped_type &reference;\n\n        static void reserve (std::map<I, T> &a, size_type capacity) {}\n\n        static reference make_reference (std::map<I, T> &a, typename std::map<I, T>::iterator it) {\n            return (*it).second;\n        }\n    };\n    template<class I, class T>\n    struct map_traits<map_array<I, T> > {\n        typedef typename map_array<I, T>::size_type size_type;\n        typedef typename map_array<I, T>::data_reference reference;\n\n        static void reserve (map_array<I, T> &a, size_type capacity) {\n            a.reserve (capacity);\n        }\n\n        static reference make_reference (map_array<I, T> &a, typename map_array<I, T>::iterator it) {\n            return reference (a, it);\n        }\n    };\n#endif\n\n    // Set array\n    template<class I>\n    class set_array {\n    public:\n        typedef std::size_t size_type;\n        typedef std::ptrdiff_t difference_type;\n        typedef I index_type;\n        typedef I value_type;\n        typedef const I &const_reference;\n        typedef I &reference;\n        typedef const I *const_pointer;\n        typedef I *pointer;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        set_array ():\n            capacity_ (0), data_ (new value_type [0]), size_ (0) {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n        }\n        BOOST_UBLAS_EXPLICIT BOOST_UBLAS_INLINE\n        set_array (size_type size):\n            capacity_ (size), data_ (new value_type [size]), size_ (0) {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n        }\n        BOOST_UBLAS_INLINE\n        set_array (const set_array &a):\n            capacity_ (a.size_), data_ (new value_type [a.size_]), size_ (a.size_) {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n            *this = a;\n        }\n        BOOST_UBLAS_INLINE\n        ~set_array () {\n            // Assuming std compliant allocator as requested during review.\n            // if (! data_)\n            //     throw std::bad_alloc ();\n            delete [] data_;\n        }\n\n        // Resizing\n        BOOST_UBLAS_INLINE\n        void resize (size_type size) {\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n            if (size > capacity_) {\n                pointer data = new value_type [size << 1];\n                // Assuming std compliant allocator as requested during review.\n                // if (! data)\n                //     throw std::bad_alloc ();\n                // if (! data_)\n                //     throw std::bad_alloc ();\n                std::copy (data_, data_ + size_, data);\n                delete [] data_;\n                capacity_ = size << 1;\n                data_ = data;\n            }\n            size_ = size;\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n        }\n\n        // Reserving\n        BOOST_UBLAS_INLINE\n        void reserve (size_type capacity) {\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n            if (capacity > capacity_) {\n                pointer data = new value_type [capacity];\n                // Assuming std compliant allocator as requested during review.\n                // if (! data)\n                //     throw std::bad_alloc ();\n                // if (! data_)\n                //     throw std::bad_alloc ();\n                std::copy (data_, data_ + size_, data);\n                delete [] data_;\n                capacity_ = capacity;\n                data_ = data;\n            }\n            BOOST_UBLAS_CHECK (size_ <= capacity_, internal_logic ());\n        }\n\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return size_;\n        }\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator [] (index_type i) {\n            pointer it = find (i);\n            if (it == end ())\n                it = insert (end (), i);\n            BOOST_UBLAS_CHECK (it != end (), internal_logic ());\n            return *it;\n        }\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        set_array &operator = (const set_array &a) {\n            // Too unusual semantic.\n            // Thanks to Michael Stevens for spotting this.\n            // BOOST_UBLAS_CHECK (this != &a, external_logic ());\n            if (this != &a) {\n                resize (a.size_);\n                std::copy (a.data_, a.data_ + a.size_, data_);\n            }\n            return *this;\n        }\n        BOOST_UBLAS_INLINE\n        set_array &assign_temporary (set_array &a) {\n            swap (a);\n            return *this;\n        }\n\n        // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (set_array &a) {\n            // Too unusual semantic.\n            // BOOST_UBLAS_CHECK (this != &a, external_logic ());\n            if (this != &a) {\n                std::swap (capacity_, a.capacity_);\n                std::swap (data_, a.data_);\n                std::swap (size_, a.size_);\n            }\n        }\n#ifndef BOOST_UBLAS_NO_MEMBER_FRIENDS\n        BOOST_UBLAS_INLINE\n        friend void swap (set_array &a1, set_array &a2) {\n            a1.swap (a2);\n        }\n#endif\n\n        // Element insertion and deletion\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer push_back (pointer it, const value_type &p) {\n            if (size () == 0 || (*(it = end () - 1)) < p) {\n                resize (size () + 1);\n                *(it = end () - 1) = p;\n                return it;\n            }\n            // Raising exceptions abstracted as requested during review.\n            // throw external_logic ();\n            external_logic ().raise ();\n            return it;\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer insert (pointer it, const value_type &p) {\n            it = detail::lower_bound (begin (), end (), p, std::less<value_type> ());\n            difference_type n = it - begin ();\n            BOOST_UBLAS_CHECK (size () == 0 || size () == size_type (n) || *it != p, external_logic ());\n            resize (size () + 1);\n            it = begin () + n;\n            std::copy_backward (it, end () - 1, end ());\n            *it = p;\n            return it;\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void insert (pointer it, pointer it1, pointer it2) {\n#ifdef BOOST_UBLAS_BOUNDS_CHECK\n            while (it1 != it2) {\n                insert (it, *it1);\n                ++ it1;\n            }\n#else\n            difference_type n = it - begin ();\n            resize (size () + it2 - it1);\n            it = begin () + n;\n            std::copy (it1, it2, it);\n            std::sort (begin (), end (), std::less<value_type> ());\n#endif\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void erase (pointer it) {\n            BOOST_UBLAS_CHECK (begin () <= it && it < end (), bad_index ());\n            std::copy (it + 1, end (), it);\n            resize (size () - 1);\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void erase (pointer it1, pointer it2) {\n            BOOST_UBLAS_CHECK (begin () <= it1 && it1 < it2 && it2 <= end (), bad_index ());\n            std::copy (it2, end (), it1);\n            resize (size () - (it2 - it1));\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        void clear () {\n            resize (0);\n        }\n\n        // Element lookup\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        const_pointer find (index_type i) const {\n#ifdef BOOST_UBLAS_DEPRECATED\n            std::pair<const_pointer, const_pointer> pit;\n            pit = std::equal_range (begin (), end (), i, std::less<value_type> ());\n            if (*pit.first == i)\n                return pit.first;\n            else if (*pit.second == i)\n                return pit.second;\n            else\n                return end ();\n#else\n            const_pointer it (detail::lower_bound (begin (), end (), i, std::less<value_type> ()));\n            if (it == end () || *it != i)\n                it = end ();\n            return it;\n#endif\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer find (index_type i) {\n#ifdef BOOST_UBLAS_DEPRECATED\n            std::pair<pointer, pointer> pit;\n            pit = std::equal_range (begin (), end (), i, std::less<value_type> ());\n            if (*pit.first == i)\n                return pit.first;\n            else if (*pit.second == i)\n                return pit.second;\n            else\n                return end ();\n#else\n            pointer it (detail::lower_bound (begin (), end (), i, std::less<value_type> ()));\n            if (it == end () || *it != i)\n                it = end ();\n            return it;\n#endif\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        const_pointer lower_bound (index_type i) const {\n            return detail::lower_bound (begin (), end (), i, std::less<value_type> ());\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer lower_bound (index_type i) {\n            return detail::lower_bound (begin (), end (), i, std::less<value_type> ());\n        }\n#ifdef BOOST_UBLAS_DEPRECATED\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        const_pointer upper_bound (index_type i) const {\n            return detail::upper_bound (begin (), end (), i, std::less<value_type> ());\n        }\n        // This function seems to be big. So we do not let the compiler inline it.\n        // BOOST_UBLAS_INLINE\n        pointer upper_bound (index_type i) {\n            return detail::upper_bound (begin (), end (), i, std::less<value_type> ());\n        }\n#endif\n\n        // Iterators simply are pointers.\n\n        typedef const_pointer const_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return data_ + size_;\n        }\n\n        typedef pointer iterator;\n\n        BOOST_UBLAS_INLINE\n        iterator begin () {\n            return data_;\n        }\n        BOOST_UBLAS_INLINE\n        iterator end () {\n            return data_ + size_;\n        }\n\n        // Reverse iterators\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef std::reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator;\n#else\n        typedef std::reverse_iterator<const_iterator> const_reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n\n#ifdef BOOST_MSVC_STD_ITERATOR\n        typedef std::reverse_iterator<iterator, value_type, reference> reverse_iterator;\n#else\n        typedef std::reverse_iterator<iterator> reverse_iterator;\n#endif\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator rbegin () {\n            return reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator rend () {\n            return reverse_iterator (begin ());\n        }\n\n    private:\n        size_type capacity_;\n        pointer data_;\n        size_type size_;\n    };\n\n    template<class I>\n    BOOST_UBLAS_INLINE\n    set_array<I> &assign_temporary (set_array<I> &a1, set_array<I> &a2) {\n        return a1.assign_temporary (a2);\n    }\n\n    template<class I, class F>\n    BOOST_UBLAS_INLINE\n    std::set<I, F> &assign_temporary (std::set<I, F> &a1, std::set<I, F> &a2) {\n        // Too unusual semantic.\n        // BOOST_UBLAS_CHECK (&a1 != &a2, external_logic ());\n        if (&a1 != &a2)\n            a1.swap (a2);\n        return  a1;\n    }\n    // This specialization is missing in Dinkumware's STL?!\n    template<class I, class F>\n    BOOST_UBLAS_INLINE\n    void swap (std::set<I, F> &a1, std::set<I, F> &a2) {\n        // Too unusual semantic.\n        // BOOST_UBLAS_CHECK (&a1 != &a2, external_logic ());\n        if (&a1 != &a2)\n            a1.swap (a2);\n    }\n\n}}}\n\n#endif\n\n\n", "meta": {"hexsha": "a937de5f5d70711938a73081f2afe41c38fc3b6b", "size": 34782, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rd party/boost/boost/numeric/ublas/storage_sparse.hpp", "max_stars_repo_name": "OLR-xray/OLR-3.0", "max_stars_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "src/3rd party/boost/boost/numeric/ublas/storage_sparse.hpp", "max_issues_repo_name": "OLR-xray/OLR-3.0", "max_issues_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/3rd party/boost/boost/numeric/ublas/storage_sparse.hpp", "max_forks_repo_name": "OLR-xray/OLR-3.0", "max_forks_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 35.1688574317, "max_line_length": 140, "alphanum_fraction": 0.5495371169, "num_tokens": 7932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.03676946990186956, "lm_q1q2_score": 0.014017241367459273}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include <dudley/DomainFactory.h>\n\n#include <escript/index.h>\n#include <escript/SubWorld.h>\n\n#ifdef ESYS_HAVE_NETCDF\n#ifdef NETCDF4\n  #include <ncDim.h>\n  #include <ncVar.h>\n  #include <ncFile.h>  \n  #include <escript/NCHelper.h>  \n#else\n#include <netcdfcpp.h>\n#endif\n#endif\n\n#include <boost/python/extract.hpp>\n#include <boost/scoped_array.hpp>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace escript;\nnamespace bp = boost::python;\n\n#ifdef NETCDF4\nusing namespace netCDF;\n#endif\n\nnamespace dudley {\n\n#ifdef ESYS_HAVE_NETCDF\n#ifdef NETCDF4\n\n// A convenience method to retrieve an integer attribute from a NetCDF file\ntemplate<typename T>\nT ncReadAtt(NcFile& dataFile, const string& fName, const string& attrName)\n{\n    NcGroupAtt attr = dataFile.getAtt(attrName.c_str());\n    if (attr.isNull()) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving integer attribute '\" << attrName\n            << \"' from NetCDF file '\" << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    T value;\n    attr.getValues(&value);\n    return value;\n}\n#else        \n// A convenience method to retrieve an integer attribute from a NetCDF file\ntemplate<typename T>\nT ncReadAtt(NcFile* dataFile, const string& fName, const string& attrName)\n{\n    NcAtt* attr = dataFile->get_att(attrName.c_str());\n    if (!attr) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving integer attribute '\" << attrName\n            << \"' from NetCDF file '\" << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    T value = (sizeof(T) > 4 ? attr->as_long(0) : attr->as_int(0));\n    delete attr;\n    return value;\n}\n#endif\n#endif\n\ninline void cleanupAndThrow(DudleyDomain* dom, string msg)\n{\n    delete dom;\n    string msgPrefix(\"loadMesh: NetCDF operation failed - \");\n    throw IOError(msgPrefix+msg);\n}\n\n#ifdef NETCDF4\n\nDomain_ptr DudleyDomain::load(const string& fileName)\n{\n#ifdef ESYS_HAVE_NETCDF\n    JMPI mpiInfo = makeInfo(MPI_COMM_WORLD);\n    const string fName(mpiInfo->appendRankToFileName(fileName));\n\n    // Open NetCDF file for reading\n    NcGroupAtt attr;\n    NcVar nc_var_temp;\n    NcFile dataFile;\n    if (!openNcFile(dataFile, fileName))\n    {\n        throw IOError(\"load: opening of netCDF file for input failed.\");\n    }        \n\n    // Read NetCDF integer attributes\n\n    // index_size was only introduced with 64-bit index support so fall back\n    // to 32 bits if not found.\n    int index_size;\n    try {\n        index_size = ncReadAtt<int>(dataFile, fName, \"index_size\");\n    } catch (IOError& e) {\n        index_size = 4;\n    }\n    // technically we could cast if reading 32-bit data on 64-bit escript\n    // but cost-benefit analysis clearly favours this implementation for now\n    if (sizeof(index_t) != index_size) {\n        throw IOError(\"loadMesh: size of index types at runtime differ from dump file\");\n    }\n\n    int mpi_size = ncReadAtt<int>(dataFile, fName, \"mpi_size\");\n    int mpi_rank = ncReadAtt<int>(dataFile, fName, \"mpi_rank\");\n    int numDim = ncReadAtt<int>(dataFile, fName, \"numDim\");\n    dim_t numNodes = ncReadAtt<dim_t>(dataFile, fName, \"numNodes\");\n    dim_t num_Elements = ncReadAtt<dim_t>(dataFile, fName, \"num_Elements\");\n    dim_t num_FaceElements = ncReadAtt<dim_t>(dataFile, fName, \"num_FaceElements\");\n    dim_t num_Points = ncReadAtt<dim_t>(dataFile, fName, \"num_Points\");\n    int num_Elements_numNodes = ncReadAtt<int>(dataFile, fName, \"num_Elements_numNodes\");\n    int Elements_TypeId = ncReadAtt<int>(dataFile, fName, \"Elements_TypeId\");\n    int num_FaceElements_numNodes = ncReadAtt<int>(dataFile, fName, \"num_FaceElements_numNodes\");\n    int FaceElements_TypeId = ncReadAtt<int>(dataFile, fName, \"FaceElements_TypeId\");\n    int Points_TypeId = ncReadAtt<int>(dataFile, fName, \"Points_TypeId\");\n    int num_Tags = ncReadAtt<int>(dataFile, fName, \"num_Tags\");\n\n    // Verify size and rank\n    if (mpiInfo->size != mpi_size) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' can only be read on \" << mpi_size\n            << \" CPUs. Currently running: \" << mpiInfo->size;\n        throw DudleyException(msg.str());\n    }\n    if (mpiInfo->rank != mpi_rank) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' should be read on CPU #\" << mpi_rank\n            << \" and NOT on #\" << mpiInfo->rank;\n        throw DudleyException(msg.str());\n    }\n\n    // Read mesh name\n    if ((attr=dataFile.getAtt(\"Name\")), attr.isNull() ) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving mesh name from NetCDF file '\"\n            << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    string name;\n    attr.getValues(name);\n\n    // allocate mesh\n    DudleyDomain* dom = new DudleyDomain(name.c_str(), numDim, mpiInfo);\n\n    // read nodes\n    NodeFile* nodes = dom->getNodes();\n    nodes->allocTable(numNodes);\n    // Nodes_Id\n    if (( nc_var_temp = dataFile.getVar(\"Nodes_Id\")), nc_var_temp.isNull() )\n        cleanupAndThrow(dom, \"get_var(Nodes_Id)\");\n    nc_var_temp.getVar(&nodes->Id[0]);    // numNodes) )\n    // Nodes_Tag\n    if (( nc_var_temp = dataFile.getVar(\"Nodes_Tag\")), nc_var_temp.isNull() )\n        cleanupAndThrow(dom, \"get_var(Nodes_Tag)\");\n    nc_var_temp.getVar(&nodes->Tag[0]);   // numNodes\n    // Nodes_gDOF\n    if (( nc_var_temp = dataFile.getVar(\"Nodes_gDOF\")), nc_var_temp.isNull() )\n        cleanupAndThrow(dom, \"get_var(Nodes_gDOF)\");\n    nc_var_temp.getVar(&nodes->globalDegreesOfFreedom[0]);  // numNodes\n    // Nodes_gNI\n    if (( nc_var_temp = dataFile.getVar(\"Nodes_gNI\")), nc_var_temp.isNull() )\n        cleanupAndThrow(dom, \"get_var(Nodes_gNI)\");\n    nc_var_temp.getVar(&nodes->globalNodesIndex[0]);    // numNodes\n    // Nodes_Coordinates\n    if ((nc_var_temp = dataFile.getVar(\"Nodes_Coordinates\")), nc_var_temp.isNull())\n        cleanupAndThrow(dom, \"get_var(Nodes_Coordinates)\");\n    nc_var_temp.getVar(&nodes->Coordinates[0]); // numNodes, numDim\n\n    nodes->updateTagList();\n\n    // read elements\n    ElementFile* elements = new ElementFile((ElementTypeId)Elements_TypeId, mpiInfo);\n    dom->setElements(elements);\n    elements->allocTable(num_Elements);\n    elements->minColor = 0;\n    elements->maxColor = num_Elements-1;\n    if (num_Elements > 0) {\n       // Elements_Id\n       if (( nc_var_temp = dataFile.getVar(\"Elements_Id\")), nc_var_temp.isNull() )\n           cleanupAndThrow(dom, \"get_var(Elements_Id)\");\n       nc_var_temp.getVar(&elements->Id[0]);    // num_Elements\n       // Elements_Tag\n       if (( nc_var_temp = dataFile.getVar(\"Elements_Tag\")), nc_var_temp.isNull())\n           cleanupAndThrow(dom, \"get_var(Elements_Tag)\");\n       nc_var_temp.getVar(&elements->Tag[0]);   // num_Elements\n       // Elements_Owner\n       if (( nc_var_temp = dataFile.getVar(\"Elements_Owner\")), nc_var_temp.isNull() )\n           cleanupAndThrow(dom, \"get_var(Elements_Owner)\");\n       nc_var_temp.getVar(&elements->Owner[0]); // num_Elements\n       // Elements_Color\n       if (( nc_var_temp = dataFile.getVar(\"Elements_Color\")), nc_var_temp.isNull() )\n           cleanupAndThrow(dom, \"get_var(Elements_Color)\");\n       nc_var_temp.getVar(&elements->Color[0]); // num_Elements\n       // Elements_Nodes\n       int* Elements_Nodes = new int[num_Elements*num_Elements_numNodes];\n       if ((nc_var_temp = dataFile.getVar(\"Elements_Nodes\")), nc_var_temp.isNull()) {\n           delete[] Elements_Nodes;\n           cleanupAndThrow(dom, \"get_var(Elements_Nodes)\");\n       }\n       nc_var_temp.getVar(&Elements_Nodes[0]);  // num_Elements, num_Elements_numNodes\n       // Copy temp array into elements->Nodes\n       for (index_t i = 0; i < num_Elements; i++) {\n           for (int j = 0; j < num_Elements_numNodes; j++) {\n               elements->Nodes[INDEX2(j,i,num_Elements_numNodes)]\n                    = Elements_Nodes[INDEX2(j,i,num_Elements_numNodes)];\n           }\n       }\n       delete[] Elements_Nodes;\n    } // num_Elements > 0\n    elements->updateTagList();\n\n    // get the face elements\n    ElementFile* faces = new ElementFile((ElementTypeId)FaceElements_TypeId, mpiInfo);\n    dom->setFaceElements(faces);\n    faces->allocTable(num_FaceElements);\n    faces->minColor = 0;\n    faces->maxColor = num_FaceElements-1;\n    if (num_FaceElements > 0) {\n        // FaceElements_Id\n        if (( nc_var_temp = dataFile.getVar(\"FaceElements_Id\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Id)\");\n        nc_var_temp.getVar(&faces->Id[0]);  // num_FaceElements\n        // FaceElements_Tag\n        if (( nc_var_temp = dataFile.getVar(\"FaceElements_Tag\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Tag)\");\n        nc_var_temp.getVar(&faces->Tag[0]); // num_FaceElements) )\n        // FaceElements_Owner\n        if (( nc_var_temp = dataFile.getVar(\"FaceElements_Owner\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Owner)\");\n        nc_var_temp.getVar(&faces->Owner[0]);   //, num_FaceElements) )\n        // FaceElements_Color\n        if (( nc_var_temp = dataFile.getVar(\"FaceElements_Color\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Color)\");\n        nc_var_temp.getVar(&faces->Color[0]);   //, num_FaceElements) )\n        // FaceElements_Nodes\n        int* FaceElements_Nodes = new int[num_FaceElements*num_FaceElements_numNodes];\n        if ((nc_var_temp = dataFile.getVar(\"FaceElements_Nodes\")), nc_var_temp.isNull()) {\n            delete[] FaceElements_Nodes;\n            cleanupAndThrow(dom, \"get_var(FaceElements_Nodes)\");\n        }\n        nc_var_temp.getVar(&(FaceElements_Nodes[0]));   // num_FaceElements, num_FaceElements_numNodes\n        // Copy temp array into faces->Nodes\n        for (index_t i = 0; i < num_FaceElements; i++) {\n            for (int j = 0; j < num_FaceElements_numNodes; j++) {\n                faces->Nodes[INDEX2(j,i,num_FaceElements_numNodes)] = FaceElements_Nodes[INDEX2(j,i,num_FaceElements_numNodes)];\n            }\n        }\n        delete[] FaceElements_Nodes;\n    } // num_FaceElements > 0\n    faces->updateTagList();\n\n    // get the Points (nodal elements)\n    ElementFile* points = new ElementFile((ElementTypeId)Points_TypeId, mpiInfo);\n    dom->setPoints(points);\n    points->allocTable(num_Points);\n    points->minColor = 0;\n    points->maxColor = num_Points-1;\n    if (num_Points > 0) {\n        // Points_Id\n        if (( nc_var_temp = dataFile.getVar(\"Points_Id\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Id)\");\n        nc_var_temp.getVar(&points->Id[0]); // num_Points\n        // Points_Tag\n        if (( nc_var_temp = dataFile.getVar(\"Points_Tag\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Tag)\");\n        nc_var_temp.getVar(&points->Tag[0]);    // num_Points\n        // Points_Owner\n        if (( nc_var_temp = dataFile.getVar(\"Points_Owner\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Owner)\");\n        nc_var_temp.getVar(&points->Owner[0]);   // num_Points\n        // Points_Color\n        if (( nc_var_temp = dataFile.getVar(\"Points_Color\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Color)\");\n        nc_var_temp.getVar(&points->Color[0]);  // num_Points\n        // Points_Nodes\n        int* Points_Nodes = new int[num_Points];\n        if ((nc_var_temp = dataFile.getVar(\"Points_Nodes\")), nc_var_temp.isNull()) {\n            delete[] Points_Nodes;\n            cleanupAndThrow(dom, \"get_var(Points_Nodes)\");\n        }\n        nc_var_temp.getVar(&Points_Nodes[0]);   // num_Points\n        // Copy temp array into points->Nodes\n        for (index_t i = 0; i < num_Points; i++) {\n            points->Id[points->Nodes[INDEX2(0,i,1)]] = Points_Nodes[i];\n        }\n        delete[] Points_Nodes;\n    } // num_Points > 0\n    points->updateTagList();\n\n    // get the tags\n    if (num_Tags > 0) {\n        // Temp storage to gather node IDs\n        int *Tags_keys = new int[num_Tags];\n        char name_temp[4096];\n        int i;\n\n        // Tags_keys\n        if (( nc_var_temp = dataFile.getVar(\"Tags_keys\")), nc_var_temp.isNull() ) {\n            delete[] Tags_keys;\n            cleanupAndThrow(dom, \"get_var(Tags_keys)\");\n        }\n        nc_var_temp.getVar(&Tags_keys[0]);  // num_Tags\n        for (i=0; i<num_Tags; i++) {\n          // Retrieve tag name\n          sprintf(name_temp, \"Tags_name_%d\", i);\n          if ((attr=dataFile.getAtt(name_temp)), attr.isNull() ) {\n              delete[] Tags_keys;\n              stringstream msg;\n              msg << \"get_att(\" << name_temp << \")\";\n              cleanupAndThrow(dom, msg.str());\n          }\n          string name;\n          attr.getValues(name);\n          dom->setTagMap(name.c_str(), Tags_keys[i]);\n        }\n        delete[] Tags_keys;\n    }\n\n    // Nodes_DofDistribution\n    IndexVector first_DofComponent(mpi_size+1);\n    if ((nc_var_temp = dataFile.getVar(\"Nodes_DofDistribution\")), nc_var_temp.isNull() ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_DofDistribution)\");\n    }\n    nc_var_temp.getVar(&first_DofComponent[0]); // mpi_size+1\n\n    // Nodes_NodeDistribution\n    IndexVector first_NodeComponent(mpi_size+1);\n    if ((nc_var_temp = dataFile.getVar(\"Nodes_NodeDistribution\")), nc_var_temp.isNull() ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_NodeDistribution)\");\n    }\n    nc_var_temp.getVar(&first_NodeComponent[0]); // mpi_size+1\n    dom->createMappings(first_DofComponent, first_NodeComponent);\n\n    return dom->getPtr();\n#else\n    throw DudleyException(\"loadMesh: not compiled with NetCDF. Please contact your installation manager.\");\n#endif // ESYS_HAVE_NETCDF\n}\n\n#else\n\nDomain_ptr DudleyDomain::load(const string& fileName)\n{\n#ifdef ESYS_HAVE_NETCDF\n    JMPI mpiInfo = makeInfo(MPI_COMM_WORLD);\n    const string fName(mpiInfo->appendRankToFileName(fileName));\n\n    // Open NetCDF file for reading\n    NcAtt *attr;\n    NcVar *nc_var_temp;\n    // netCDF error handler\n    NcError err(NcError::silent_nonfatal);\n    // Create the NetCDF file.\n    NcFile dataFile(fName.c_str(), NcFile::ReadOnly);\n    if (!dataFile.is_valid()) {\n        stringstream msg;\n        msg << \"loadMesh: Opening NetCDF file '\" << fName << \"' for reading failed.\";\n        throw IOError(msg.str());\n    }\n\n    // Read NetCDF integer attributes\n\n    // index_size was only introduced with 64-bit index support so fall back\n    // to 32 bits if not found.\n    int index_size;\n    try {\n        index_size = ncReadAtt<int>(&dataFile, fName, \"index_size\");\n    } catch (IOError& e) {\n        index_size = 4;\n    }\n    // technically we could cast if reading 32-bit data on 64-bit escript\n    // but cost-benefit analysis clearly favours this implementation for now\n    if (sizeof(index_t) != index_size) {\n        throw IOError(\"loadMesh: size of index types at runtime differ from dump file\");\n    }\n\n    int mpi_size = ncReadAtt<int>(&dataFile, fName, \"mpi_size\");\n    int mpi_rank = ncReadAtt<int>(&dataFile, fName, \"mpi_rank\");\n    int numDim = ncReadAtt<int>(&dataFile, fName, \"numDim\");\n    dim_t numNodes = ncReadAtt<dim_t>(&dataFile, fName, \"numNodes\");\n    dim_t num_Elements = ncReadAtt<dim_t>(&dataFile, fName, \"num_Elements\");\n    dim_t num_FaceElements = ncReadAtt<dim_t>(&dataFile, fName, \"num_FaceElements\");\n    dim_t num_Points = ncReadAtt<dim_t>(&dataFile, fName, \"num_Points\");\n    int num_Elements_numNodes = ncReadAtt<int>(&dataFile, fName, \"num_Elements_numNodes\");\n    int Elements_TypeId = ncReadAtt<int>(&dataFile, fName, \"Elements_TypeId\");\n    int num_FaceElements_numNodes = ncReadAtt<int>(&dataFile, fName, \"num_FaceElements_numNodes\");\n    int FaceElements_TypeId = ncReadAtt<int>(&dataFile, fName, \"FaceElements_TypeId\");\n    int Points_TypeId = ncReadAtt<int>(&dataFile, fName, \"Points_TypeId\");\n    int num_Tags = ncReadAtt<int>(&dataFile, fName, \"num_Tags\");\n\n    // Verify size and rank\n    if (mpiInfo->size != mpi_size) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' can only be read on \" << mpi_size\n            << \" CPUs. Currently running: \" << mpiInfo->size;\n        throw DudleyException(msg.str());\n    }\n    if (mpiInfo->rank != mpi_rank) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' should be read on CPU #\" << mpi_rank\n            << \" and NOT on #\" << mpiInfo->rank;\n        throw DudleyException(msg.str());\n    }\n\n    // Read mesh name\n    if (! (attr=dataFile.get_att(\"Name\")) ) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving mesh name from NetCDF file '\"\n            << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    boost::scoped_array<char> name(attr->as_string(0));\n    delete attr;\n\n    // allocate mesh\n    DudleyDomain* dom = new DudleyDomain(name.get(), numDim, mpiInfo);\n\n    // read nodes\n    NodeFile* nodes = dom->getNodes();\n    nodes->allocTable(numNodes);\n    // Nodes_Id\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_Id\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_Id)\");\n    if (! nc_var_temp->get(&nodes->Id[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_Id)\");\n    // Nodes_Tag\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_Tag\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_Tag)\");\n    if (! nc_var_temp->get(&nodes->Tag[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_Tag)\");\n    // Nodes_gDOF\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_gDOF\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_gDOF)\");\n    if (! nc_var_temp->get(&nodes->globalDegreesOfFreedom[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_gDOF)\");\n    // Nodes_gNI\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_gNI\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_gNI)\");\n    if (! nc_var_temp->get(&nodes->globalNodesIndex[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_gNI)\");\n    // Nodes_Coordinates\n    if (!(nc_var_temp = dataFile.get_var(\"Nodes_Coordinates\")))\n        cleanupAndThrow(dom, \"get_var(Nodes_Coordinates)\");\n    if (! nc_var_temp->get(&nodes->Coordinates[0], numNodes, numDim) )\n        cleanupAndThrow(dom, \"get(Nodes_Coordinates)\");\n\n    nodes->updateTagList();\n\n    // read elements\n    ElementFile* elements = new ElementFile((ElementTypeId)Elements_TypeId, mpiInfo);\n    dom->setElements(elements);\n    elements->allocTable(num_Elements);\n    elements->minColor = 0;\n    elements->maxColor = num_Elements-1;\n    if (num_Elements > 0) {\n       // Elements_Id\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Id\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Id)\");\n       if (! nc_var_temp->get(&elements->Id[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Id)\");\n       // Elements_Tag\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Tag\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Tag)\");\n       if (! nc_var_temp->get(&elements->Tag[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Tag)\");\n       // Elements_Owner\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Owner\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Owner)\");\n       if (! nc_var_temp->get(&elements->Owner[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Owner)\");\n       // Elements_Color\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Color\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Color)\");\n       if (! nc_var_temp->get(&elements->Color[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Color)\");\n       // Elements_Nodes\n       int* Elements_Nodes = new int[num_Elements*num_Elements_numNodes];\n       if (!(nc_var_temp = dataFile.get_var(\"Elements_Nodes\"))) {\n           delete[] Elements_Nodes;\n           cleanupAndThrow(dom, \"get_var(Elements_Nodes)\");\n       }\n       if (! nc_var_temp->get(&Elements_Nodes[0], num_Elements, num_Elements_numNodes) ) {\n           delete[] Elements_Nodes;\n           cleanupAndThrow(dom, \"get(Elements_Nodes)\");\n       }\n\n       // Copy temp array into elements->Nodes\n       for (index_t i = 0; i < num_Elements; i++) {\n           for (int j = 0; j < num_Elements_numNodes; j++) {\n               elements->Nodes[INDEX2(j,i,num_Elements_numNodes)]\n                    = Elements_Nodes[INDEX2(j,i,num_Elements_numNodes)];\n           }\n       }\n       delete[] Elements_Nodes;\n    } // num_Elements > 0\n    elements->updateTagList();\n\n    // get the face elements\n    ElementFile* faces = new ElementFile((ElementTypeId)FaceElements_TypeId, mpiInfo);\n    dom->setFaceElements(faces);\n    faces->allocTable(num_FaceElements);\n    faces->minColor = 0;\n    faces->maxColor = num_FaceElements-1;\n    if (num_FaceElements > 0) {\n        // FaceElements_Id\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Id\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Id)\");\n        if (! nc_var_temp->get(&faces->Id[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Id)\");\n        // FaceElements_Tag\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Tag\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Tag)\");\n        if (! nc_var_temp->get(&faces->Tag[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Tag)\");\n        // FaceElements_Owner\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Owner\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Owner)\");\n        if (! nc_var_temp->get(&faces->Owner[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Owner)\");\n        // FaceElements_Color\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Color\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Color)\");\n        if (! nc_var_temp->get(&faces->Color[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Color)\");\n        // FaceElements_Nodes\n        int* FaceElements_Nodes = new int[num_FaceElements*num_FaceElements_numNodes];\n        if (!(nc_var_temp = dataFile.get_var(\"FaceElements_Nodes\"))) {\n            delete[] FaceElements_Nodes;\n            cleanupAndThrow(dom, \"get_var(FaceElements_Nodes)\");\n        }\n        if (! nc_var_temp->get(&(FaceElements_Nodes[0]), num_FaceElements, num_FaceElements_numNodes) ) {\n            delete[] FaceElements_Nodes;\n            cleanupAndThrow(dom, \"get(FaceElements_Nodes)\");\n        }\n        // Copy temp array into faces->Nodes\n        for (index_t i = 0; i < num_FaceElements; i++) {\n            for (int j = 0; j < num_FaceElements_numNodes; j++) {\n                faces->Nodes[INDEX2(j,i,num_FaceElements_numNodes)] = FaceElements_Nodes[INDEX2(j,i,num_FaceElements_numNodes)];\n            }\n        }\n        delete[] FaceElements_Nodes;\n    } // num_FaceElements > 0\n    faces->updateTagList();\n\n    // get the Points (nodal elements)\n    ElementFile* points = new ElementFile((ElementTypeId)Points_TypeId, mpiInfo);\n    dom->setPoints(points);\n    points->allocTable(num_Points);\n    points->minColor = 0;\n    points->maxColor = num_Points-1;\n    if (num_Points > 0) {\n        // Points_Id\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Id\")))\n            cleanupAndThrow(dom, \"get_var(Points_Id)\");\n        if (! nc_var_temp->get(&points->Id[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Id)\");\n        // Points_Tag\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Tag\")))\n            cleanupAndThrow(dom, \"get_var(Points_Tag)\");\n        if (! nc_var_temp->get(&points->Tag[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Tag)\");\n        // Points_Owner\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Owner\")))\n            cleanupAndThrow(dom, \"get_var(Points_Owner)\");\n        if (!nc_var_temp->get(&points->Owner[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Owner)\");\n        // Points_Color\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Color\")))\n            cleanupAndThrow(dom, \"get_var(Points_Color)\");\n        if (!nc_var_temp->get(&points->Color[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Color)\");\n        // Points_Nodes\n        int* Points_Nodes = new int[num_Points];\n        if (!(nc_var_temp = dataFile.get_var(\"Points_Nodes\"))) {\n            delete[] Points_Nodes;\n            cleanupAndThrow(dom, \"get_var(Points_Nodes)\");\n        }\n        if (! nc_var_temp->get(&Points_Nodes[0], num_Points) ) {\n            delete[] Points_Nodes;\n            cleanupAndThrow(dom, \"get(Points_Nodes)\");\n        }\n        // Copy temp array into points->Nodes\n        for (index_t i = 0; i < num_Points; i++) {\n            points->Id[points->Nodes[INDEX2(0,i,1)]] = Points_Nodes[i];\n        }\n        delete[] Points_Nodes;\n    } // num_Points > 0\n    points->updateTagList();\n\n    // get the tags\n    if (num_Tags > 0) {\n        // Temp storage to gather node IDs\n        int *Tags_keys = new int[num_Tags];\n        char name_temp[4096];\n        int i;\n\n        // Tags_keys\n        if (! ( nc_var_temp = dataFile.get_var(\"Tags_keys\")) ) {\n            delete[] Tags_keys;\n            cleanupAndThrow(dom, \"get_var(Tags_keys)\");\n        }\n        if (! nc_var_temp->get(&Tags_keys[0], num_Tags) ) {\n            delete[] Tags_keys;\n            cleanupAndThrow(dom, \"get(Tags_keys)\");\n        }\n        for (i=0; i<num_Tags; i++) {\n          // Retrieve tag name\n          sprintf(name_temp, \"Tags_name_%d\", i);\n          if (! (attr=dataFile.get_att(name_temp)) ) {\n              delete[] Tags_keys;\n              stringstream msg;\n              msg << \"get_att(\" << name_temp << \")\";\n              cleanupAndThrow(dom, msg.str());\n          }\n          boost::scoped_array<char> name(attr->as_string(0));\n          delete attr;\n          dom->setTagMap(name.get(), Tags_keys[i]);\n        }\n        delete[] Tags_keys;\n    }\n\n    // Nodes_DofDistribution\n    IndexVector first_DofComponent(mpi_size+1);\n    if (! (nc_var_temp = dataFile.get_var(\"Nodes_DofDistribution\")) ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_DofDistribution)\");\n    }\n    if (!nc_var_temp->get(&first_DofComponent[0], mpi_size+1)) {\n        cleanupAndThrow(dom, \"get(Nodes_DofDistribution)\");\n    }\n\n    // Nodes_NodeDistribution\n    IndexVector first_NodeComponent(mpi_size+1);\n    if (! (nc_var_temp = dataFile.get_var(\"Nodes_NodeDistribution\")) ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_NodeDistribution)\");\n    }\n    if (!nc_var_temp->get(&first_NodeComponent[0], mpi_size+1)) {\n        cleanupAndThrow(dom, \"get(Nodes_NodeDistribution)\");\n    }\n    dom->createMappings(first_DofComponent, first_NodeComponent);\n\n    return dom->getPtr();\n#else\n    throw DudleyException(\"loadMesh: not compiled with NetCDF. Please contact your installation manager.\");\n#endif // ESYS_HAVE_NETCDF\n}\n#endif\n\nDomain_ptr readMesh(const string& fileName, int /*integrationOrder*/,\n                    int /*reducedIntegrationOrder*/, bool optimize)\n{\n    JMPI mpiInfo = makeInfo(MPI_COMM_WORLD);\n    return DudleyDomain::read(mpiInfo, fileName, optimize);\n}\n\nDomain_ptr readGmsh(const string& fileName, int numDim,\n                    int /*integrationOrder*/, int /*reducedIntegrationOrder*/,\n                    bool optimize)\n{\n    JMPI mpiInfo = makeInfo(MPI_COMM_WORLD);\n    return DudleyDomain::readGmsh(mpiInfo, fileName, numDim, optimize);\n}\n\nDomain_ptr brick(JMPI info, dim_t n0, dim_t n1, dim_t n2, int order,\n                 double l0, double l1, double l2,\n                 bool periodic0, bool periodic1, bool periodic2,\n                 int integrationOrder, int reducedIntegrationOrder,\n                 bool useElementsOnFace, bool useFullElementOrder,\n                 bool optimize)\n{\n    // we don't support periodic boundary conditions\n    if (periodic0 || periodic1)\n        throw ValueError(\"Dudley does not support periodic boundary conditions.\");\n\n    if (integrationOrder > 3 || reducedIntegrationOrder > 1)\n        throw ValueError(\"Dudley does not support the requested integration order.\");\n\n    if (useElementsOnFace || useFullElementOrder)\n        throw ValueError(\"Dudley does not support useElementsOnFace or useFullElementOrder.\");\n\n    if (order > 1)\n        throw ValueError(\"Dudley does not support element order greater than 1.\");\n\n    return DudleyDomain::create3D(n0, n1, n2, l0, l1, l2, optimize, info);\n}\n\nDomain_ptr brick_driver(const bp::list& args)\n{\n    bp::object pworld = args[15];\n    JMPI info;\n    if (!pworld.is_none()) {\n        bp::extract<SubWorld_ptr> ex(pworld);\n        if (!ex.check()) {\n            throw ValueError(\"Invalid escriptWorld parameter.\");\n        }\n        info = ex()->getMPI();\n    } else {\n        info = makeInfo(MPI_COMM_WORLD);\n    }\n    return brick(info, static_cast<dim_t>(bp::extract<float>(args[0])),\n                 static_cast<dim_t>(bp::extract<float>(args[1])),\n                 static_cast<dim_t>(bp::extract<float>(args[2])),\n                 bp::extract<int>(args[3]), bp::extract<double>(args[4]),\n                 bp::extract<double>(args[5]), bp::extract<double>(args[6]),\n                 bp::extract<int>(args[7]), bp::extract<int>(args[8]),\n                 bp::extract<int>(args[9]), bp::extract<int>(args[10]),\n                 bp::extract<int>(args[11]), bp::extract<int>(args[12]),\n                 bp::extract<int>(args[13]), bp::extract<int>(args[14])\n                 );\n}\n\nDomain_ptr rectangle(JMPI info, dim_t n0, dim_t n1, int order,\n                     double l0, double l1, bool periodic0, bool periodic1,\n                     int integrationOrder, int reducedIntegrationOrder,\n                     bool useElementsOnFace, bool useFullElementOrder,\n                     bool optimize)\n{\n    if (periodic0 || periodic1) // we don't support periodic boundary conditions\n        throw ValueError(\"Dudley does not support periodic boundary conditions.\");\n    if (integrationOrder > 3 || reducedIntegrationOrder > 1)\n        throw ValueError(\"Dudley does not support the requested integrationorders.\");\n    if (useElementsOnFace || useFullElementOrder)\n        throw ValueError(\"Dudley does not support useElementsOnFace or useFullElementOrder.\");\n    if (order > 1)\n        throw ValueError(\"Dudley only supports first-order elements.\");\n    return DudleyDomain::create2D(n0, n1, l0, l1, optimize, info);\n}\n\nDomain_ptr rectangle_driver(const bp::list& args)\n{\n    bp::object pworld = args[12];\n    JMPI info;\n    if (!pworld.is_none()) {\n        bp::extract<SubWorld_ptr> ex(pworld);\n        if (!ex.check()) {\n            throw ValueError(\"Invalid escriptWorld parameter.\");\n        }\n        info = ex()->getMPI();\n    } else {\n        info = makeInfo(MPI_COMM_WORLD);\n    }\n\n    return rectangle(info, static_cast<dim_t>(bp::extract<float>(args[0])),\n                     static_cast<dim_t>(bp::extract<float>(args[1])),\n                     bp::extract<int>(args[2]), bp::extract<double>(args[3]),\n                     bp::extract<double>(args[4]), bp::extract<int>(args[5]),\n                     bp::extract<int>(args[6]), bp::extract<int>(args[7]),\n                     bp::extract<int>(args[8]), bp::extract<int>(args[9]),\n                     bp::extract<int>(args[10]), bp::extract<int>(args[11])\n                     );\n}\n\n} // namespace dudley\n", "meta": {"hexsha": "a08dc674492c22d7b90ea61bbe5363d64dcf736e", "size": 31834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dudley/src/DomainFactory.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "dudley/src/DomainFactory.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "dudley/src/DomainFactory.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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.9177377892, "max_line_length": 128, "alphanum_fraction": 0.6272538795, "num_tokens": 8126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808662149067, "lm_q2_score": 0.04813677504253705, "lm_q1q2_score": 0.014006880498669534}}
{"text": "//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology\n//Licensed under the terms of the MIT License, as described in the file:\n//   license.txt   (http://opensource.org/licenses/MIT)\n\n#include \"A_StarPublicTransitShortestPathImpl.hpp\"\n\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/transform_value_property_map.hpp>\n#include <boost/utility.hpp>\n#include <boost/thread.hpp>\n#include <map>\n#include <ostream>\n#include <string>\n#include <vector>\n\n#include \"geospatial/network/Point.hpp\"\n#include \"util/GeomHelpers.hpp\"\n#include \"util/LangHelpers.hpp\"\n#include \"StreetDirectory.hpp\"\n#include \"util/Utils.hpp\"\n\nusing std::map;\nusing std::vector;\nusing std::list;\n\nnamespace {\nvoid printPath(const std::vector<sim_mob::PT_NetworkEdge>& path, double cost, bool addedtoB) {\n    if (addedtoB) {\n        std::cout << \"Added to B: \";\n    } else {\n        std::cout << \"Added to Q: \";\n    }\n    for (std::vector<sim_mob::PT_NetworkEdge>::const_iterator it = path.begin();\n            it != path.end(); it++) {\n        std::cout << it->getEdgeId() << \"-->\";\n    }\n    std::cout << \"pathcost=\" << cost;\n    std::cout << \"\\n\";\n}\n\nstruct TempPathSet {\nprivate:\n    std::vector<std::vector<sim_mob::PT_NetworkEdge> > paths;\n    std::vector<double> pathCosts;\n\npublic:\n    void addPathIfUnavailable(const std::vector<sim_mob::PT_NetworkEdge>& path, double cost) {\n        if (std::find(paths.begin(), paths.end(), path) == paths.end()) {\n            paths.push_back(path);\n            pathCosts.push_back(cost);\n            //printPath(path,cost,true);\n        }\n    }\n\n    void deletePath(size_t index)\n    {\n        paths.erase(paths.begin() + index);\n        pathCosts.erase(pathCosts.begin() + index);\n    }\n\n    uint32_t getMinElementIdx() const\n    {\n        return std::distance(pathCosts.begin(), std::min_element(pathCosts.begin(), pathCosts.end()));\n    }\n\n    const std::vector<sim_mob::PT_NetworkEdge>& getPath(int index) const\n    {\n        if (index >= paths.size()) {\n            throw std::runtime_error(\"invalid index\");\n        }\n        return paths.at(index);\n    }\n\n    bool empty() const\n    {\n        return paths.empty();\n    }\n};\n\n}\n\nsim_mob::A_StarPublicTransitShortestPathImpl::A_StarPublicTransitShortestPathImpl(\n        const std::map<int, PT_NetworkEdge>& ptEdgeMap,\n        const std::map<std::string, PT_NetworkVertex>& ptVertexMap)\n{\n    initPublicNetwork(ptEdgeMap, ptVertexMap);\n}\n\nvoid sim_mob::A_StarPublicTransitShortestPathImpl::initPublicNetwork(\n        const std::map<int, PT_NetworkEdge>& ptEdgeMap, const std::map<std::string, PT_NetworkVertex>& ptVertexMap)\n{\n    for (std::map<std::string, PT_NetworkVertex>::const_iterator itVertex = ptVertexMap.begin(); itVertex != ptVertexMap.end(); ++itVertex) {\n        procAddPublicNetworkVertices(publicTransitMap, (itVertex->second));\n    }\n\n    for (std::map<int, PT_NetworkEdge>::const_iterator itEdge = ptEdgeMap.begin(); itEdge != ptEdgeMap.end(); ++itEdge) {\n        procAddPublicNetworkEdges(publicTransitMap, itEdge->second);\n    }\n}\nvoid sim_mob::A_StarPublicTransitShortestPathImpl::procAddPublicNetworkVertices(\n        StreetDirectory::PublicTransitGraph& graph, const PT_NetworkVertex& ptVertex)\n{\n    StreetDirectory::PT_Vertex v = boost::add_vertex(const_cast<StreetDirectory::PublicTransitGraph &>(graph));\n    boost::put(boost::vertex_name,  const_cast<StreetDirectory::PublicTransitGraph &>(graph), v, ptVertex.getRoadItemId());\n    vertexMap[ptVertex.getRoadItemId()] = v;\n}\n\nvoid sim_mob::A_StarPublicTransitShortestPathImpl::procAddPublicNetworkEdges(\n        StreetDirectory::PublicTransitGraph& graph, const PT_NetworkEdge& ptEdge)\n{\n    StreetDirectory::PT_Vertex from = vertexMap.find(ptEdge.getStartStop())->second;\n    StreetDirectory::PT_Vertex to = vertexMap.find(ptEdge.getEndStop())->second;\n    bool ok;\n    StreetDirectory::PT_Edge edge;\n    boost::tie(edge, ok) = boost::add_edge(from, to, graph);\n    edgeMap[ptEdge.getEdgeId()] = edge;\n    procAddPublicNetworkEdgeWeights(edge, publicTransitMap, ptEdge);\n}\ndouble sim_mob::A_StarPublicTransitShortestPathImpl::getK_ShortestPathCost(const PT_NetworkEdge& ptEdge)\n{\n    return ptEdge.getDayTransitTimeSecs() + ptEdge.getTransferPenaltySecs() + ptEdge.getWalkTimeSecs() + ptEdge.getWaitTimeSecs();\n}\n\ndouble sim_mob::A_StarPublicTransitShortestPathImpl::getLabelingApproachWeights(int Label, PT_NetworkEdge ptEdge)\n{\n    double cost=0.0;\n    switch (Label) {\n    case LabelingApproach1: {\n        ptEdge.setWalkTimeSecs(0);\n        ptEdge.setWaitTimeSecs(0);\n        break;\n    }\n    case LabelingApproach2: {\n        ptEdge.setWalkTimeSecs(0);\n        ptEdge.setWaitTimeSecs(0);\n        ptEdge.setDayTransitTimeSecs(0);\n        ptEdge.setTransferPenaltySecs(1);\n        break;\n    }\n    case LabelingApproach3: {\n        if (ptEdge.getType() == sim_mob::WALK_EDGE) {\n            ptEdge.setWalkTimeSecs(100000000);\n        }\n        break;\n    }\n    case LabelingApproach4: {\n        if (ptEdge.getType() != sim_mob::TRAIN_EDGE) {\n            ptEdge.setTransferPenaltySecs(100000000);\n        }\n        break;\n    }\n    case LabelingApproach5: {\n        if (ptEdge.getType() != sim_mob::BUS_EDGE) {\n            ptEdge.setTransferPenaltySecs(100000000);\n        }\n        break;\n    }\n    case LabelingApproach6: {\n        ptEdge.setDayTransitTimeSecs(0);\n        ptEdge.setWalkTimeSecs(0);\n        break;\n    }\n    case LabelingApproach7:\n        // DO Nothing\n        break;\n    case LabelingApproach8: {\n        double walkTime = ptEdge.getWalkTimeSecs();\n        double waitTime = ptEdge.getWaitTimeSecs();\n        ptEdge.setWalkTimeSecs(5 * walkTime);\n        ptEdge.setWaitTimeSecs(10 * waitTime);\n        break;\n    }\n    case LabelingApproach9: {\n        double walkTime = ptEdge.getWalkTimeSecs();\n        double waitTime = ptEdge.getWaitTimeSecs();\n        ptEdge.setWalkTimeSecs(10 * walkTime);\n        ptEdge.setWaitTimeSecs(10 * waitTime);\n        break;\n    }\n    case LabelingApproach10: {\n        double walkTime = ptEdge.getWalkTimeSecs();\n        double waitTime = ptEdge.getWaitTimeSecs();\n        ptEdge.setWalkTimeSecs(20 * walkTime);\n        ptEdge.setWaitTimeSecs(10 * waitTime);\n        break;\n    }\n    default:\n        // Do Nothing\n        break;\n    }\n    //Cost function for labeling approach. Cost = day_transit_time + walk_time + wait_time + transfer_penalty\n    cost = ptEdge.getDayTransitTimeSecs() + ptEdge.getWalkTimeSecs() + ptEdge.getWaitTimeSecs() + ptEdge.getTransferPenaltySecs();\n    return cost;\n}\n\ndouble sim_mob::A_StarPublicTransitShortestPathImpl::getSimulationApproachWeights(PT_NetworkEdge ptEdge)\n{\n    double cost = ptEdge.getDayTransitTimeSecs() + ptEdge.getWalkTimeSecs() + ptEdge.getWaitTimeSecs() + ptEdge.getTransferPenaltySecs();\n    return abs(Utils::nRandom(cost, 5 * cost));\n}\nvoid sim_mob::A_StarPublicTransitShortestPathImpl::procAddPublicNetworkEdgeWeights( const StreetDirectory::PT_Edge& edge,\n        StreetDirectory::PublicTransitGraph& graph, const PT_NetworkEdge& ptEdge)\n{\n    graph[edge].kShortestPathWeight = getK_ShortestPathCost(ptEdge);\n    graph[edge].labelingApproach1Weight = getLabelingApproachWeights(LabelingApproach1, ptEdge);\n    graph[edge].labelingApproach2Weight = getLabelingApproachWeights(LabelingApproach2, ptEdge);\n    graph[edge].labelingApproach3Weight = getLabelingApproachWeights(LabelingApproach3, ptEdge);\n    graph[edge].labelingApproach4Weight = getLabelingApproachWeights(LabelingApproach4, ptEdge);\n    graph[edge].labelingApproach5Weight = getLabelingApproachWeights(LabelingApproach5, ptEdge);\n    graph[edge].labelingApproach6Weight = getLabelingApproachWeights(LabelingApproach6, ptEdge);\n    graph[edge].labelingApproach7Weight = getLabelingApproachWeights(LabelingApproach7, ptEdge);\n    graph[edge].labelingApproach8Weight = getLabelingApproachWeights(LabelingApproach8, ptEdge);\n    graph[edge].labelingApproach9Weight = getLabelingApproachWeights(LabelingApproach9, ptEdge);\n    graph[edge].labelingApproach10Weight = getLabelingApproachWeights(LabelingApproach10, ptEdge);\n    graph[edge].simulationApproach1Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach2Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach3Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach4Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach5Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach6Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach7Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach8Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach9Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].simulationApproach10Weight = getSimulationApproachWeights(ptEdge);\n    graph[edge].edge_id = ptEdge.getEdgeId();\n}\n\nvector<sim_mob::PT_NetworkEdge> sim_mob::A_StarPublicTransitShortestPathImpl::searchShortestPath(\n        const StreetDirectory::PT_VertexId& fromNode,const StreetDirectory::PT_VertexId& toNode, const PT_CostLabel cost)\n{\n    vector<PT_NetworkEdge> res = vector<sim_mob::PT_NetworkEdge>();\n    StreetDirectory::PT_Vertex from;\n    StreetDirectory::PT_Vertex to;\n    if (vertexMap.find(fromNode) != vertexMap.end()) {\n        from = vertexMap.find(fromNode)->second;\n    } else {\n        std::cout << \"From Node \" << fromNode << \" not found in the graph\\n\";\n        return vector<sim_mob::PT_NetworkEdge>();\n    }\n    if (vertexMap.find(toNode) != vertexMap.end()) {\n        to = vertexMap.find(toNode)->second;\n    } else {\n        std::cout << \"To Node \" << toNode << \" not found in the graph\\n\";\n        return vector<sim_mob::PT_NetworkEdge>();\n    }\n    StreetDirectory::PublicTransitGraph& graph = publicTransitMap;\n    list<StreetDirectory::PT_Vertex> partialRes;\n    vector<StreetDirectory::PT_Vertex> p(boost::num_vertices(graph));\n    vector<double> d(boost::num_vertices(graph));\n    boost::property_map<StreetDirectory::PublicTransitGraph,double (StreetDirectory::PT_EdgeProperties::*)>::type edgeWeightMap;\n\n    switch (cost) {\n    case KshortestPath:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::kShortestPathWeight,graph);\n        break;\n    case LabelingApproach1:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach1Weight,graph);\n        break;\n    case LabelingApproach2:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach2Weight,graph);\n        break;\n    case LabelingApproach3:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach3Weight,graph);\n        break;\n    case LabelingApproach4:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach4Weight,graph);\n        break;\n    case LabelingApproach5:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach5Weight,graph);\n        break;\n    case LabelingApproach6:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach6Weight,graph);\n        break;\n    case LabelingApproach7:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach7Weight,graph);\n        break;\n    case LabelingApproach8:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach8Weight,graph);\n        break;\n    case LabelingApproach9:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach9Weight,graph);\n        break;\n    case LabelingApproach10:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::labelingApproach10Weight,graph);\n        break;\n    case SimulationApproach1:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach1Weight,graph);\n        break;\n    case SimulationApproach2:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach2Weight,graph);\n        break;\n    case SimulationApproach3:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach3Weight,graph);\n        break;\n    case SimulationApproach4:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach4Weight,graph);\n        break;\n    case SimulationApproach5:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach5Weight,graph);\n        break;\n    case SimulationApproach6:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach6Weight,graph);\n        break;\n    case SimulationApproach7:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach7Weight,graph);\n        break;\n    case SimulationApproach8:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach8Weight,graph);\n        break;\n    case SimulationApproach9:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach9Weight,graph);\n        break;\n    case SimulationApproach10:\n        edgeWeightMap = boost::get(&StreetDirectory::PT_EdgeProperties::simulationApproach10Weight, graph);\n        break;\n    }\n    try {\n        boost::astar_search(graph, from, PT_HeuristicGraph(&graph, to),\n                boost::weight_map(edgeWeightMap).predecessor_map(&p[0]).distance_map(&d[0]).visitor(PT_GoalVisitor(to)));\n\n    } catch (PT_FoundGoal& goal) {\n        //Build backwards.\n        for (StreetDirectory::PT_Vertex v = to;; v = p[v]) {\n            partialRes.push_front(v);\n            if (p[v] == v) {\n                break;\n            }\n        }\n        //Now build forwards.\n        std::list<StreetDirectory::PT_Vertex>::const_iterator prev = partialRes.end();\n        for (std::list<StreetDirectory::PT_Vertex>::const_iterator it = partialRes.begin(); it != partialRes.end(); it++) {\n            //Add this edge.\n            if (prev != partialRes.end()) {\n                //This shouldn't fail.\n                std::pair<StreetDirectory::PT_Edge, bool> edge = boost::edge(*prev, *it, graph);\n                if (!edge.second) {\n                    Warn() << \"ERROR: Boost can't find an edge that it should know about.\"\n                            << std::endl;\n                    return vector<sim_mob::PT_NetworkEdge>();\n                }\n                StreetDirectory::PT_EdgeId edge_id = get(&StreetDirectory::PT_EdgeProperties::edge_id, graph,edge.first);\n                res.push_back(PT_NetworkCreater::getInstance().PT_NetworkEdgeMap.find(edge_id)->second);\n            }\n            //Save for later.\n            prev = it;\n        }\n    }\n    return res;\n}\nvector<sim_mob::PT_NetworkEdge> sim_mob::A_StarPublicTransitShortestPathImpl::searchShortestPathWithBlacklist(\n        const StreetDirectory::PT_VertexId& fromNode,const StreetDirectory::PT_VertexId& toNode,const std::set<StreetDirectory::PT_EdgeId>& blacklist,  double &pathCost)\n{\n    StreetDirectory::PublicTransitGraph& graph = publicTransitMap;\n    StreetDirectory::PT_Vertex from;\n    StreetDirectory::PT_Vertex to;\n    if (vertexMap.find(fromNode) != vertexMap.end()) {\n        from = vertexMap.find(fromNode)->second;\n    } else {\n        std::cout << \"From Node not found in the graph\";\n        return vector<sim_mob::PT_NetworkEdge>();\n    }\n    if (vertexMap.find(toNode) != vertexMap.end()) {\n        to = vertexMap.find(toNode)->second;\n    } else {\n        std::cout << \"TO Node not found in the graph\";\n        return vector<sim_mob::PT_NetworkEdge>();\n    }\n    std::set<StreetDirectory::PT_Edge> blEdge = std::set<StreetDirectory::PT_Edge>();\n    for (std::set<StreetDirectory::PT_EdgeId>::const_iterator blIt =blacklist.begin(); blIt != blacklist.end(); blIt++) {\n        blEdge.insert(edgeMap[*blIt]);\n    }\n\n    PT_EdgeConstraint filter(blEdge);\n    boost::filtered_graph<StreetDirectory::PublicTransitGraph, PT_EdgeConstraint> filtered(graph, filter);\n    vector<sim_mob::PT_NetworkEdge> res;\n    list<StreetDirectory::PT_Vertex> partialRes;\n    vector<StreetDirectory::PT_Vertex> p(boost::num_vertices(graph));\n    vector<double> d(boost::num_vertices(graph));\n    try {\n        boost::astar_search(filtered, from, PT_HeuristicGraph(&graph, to),\n                boost::weight_map(get(&StreetDirectory::PT_EdgeProperties::kShortestPathWeight, graph)).predecessor_map(&p[0]).\n                distance_map(&d[0]).visitor(PT_GoalVisitor(to)));\n    } catch (PT_FoundGoal& goal) {\n        pathCost = d[to];\n        //Build backwards.\n        for (StreetDirectory::PT_Vertex v = to;; v = p[v]) {\n            partialRes.push_front(v);\n            if (p[v] == v) {\n                break;\n            }\n        }\n        //Now build forwards.\n        std::list<StreetDirectory::PT_Vertex>::const_iterator prev =partialRes.end();\n        for (std::list<StreetDirectory::PT_Vertex>::const_iterator it = partialRes.begin(); it != partialRes.end(); it++) {\n            //Add this edge.\n            if (prev != partialRes.end()) {\n                //This shouldn't fail.\n                std::pair<StreetDirectory::PT_Edge, bool> edge = boost::edge(*prev, *it, graph);\n                if (!edge.second) {\n                    Warn()  << \"ERROR: Boost can't find an edge that it should know about.\"\n                            << std::endl;\n                    return vector<sim_mob::PT_NetworkEdge>();\n                }\n\n                StreetDirectory::PT_EdgeId edge_id = get(&StreetDirectory::PT_EdgeProperties::edge_id, graph,edge.first);\n                res.push_back(PT_NetworkCreater::getInstance().PT_NetworkEdgeMap.find(edge_id)->second);\n            }\n            //Save for later.\n            prev = it;\n        }\n    }\n    return res;\n}\n\nvoid sim_mob::A_StarPublicTransitShortestPathImpl::searchK_ShortestPaths(uint32_t kPaths, const StreetDirectory::PT_VertexId& from,\n        const StreetDirectory::PT_VertexId& to, vector<vector<sim_mob::PT_NetworkEdge> >& res)\n{\n    StreetDirectory::PublicTransitGraph& graph = publicTransitMap;\n\n    double pathCost = 0.0;\n    // Define Q to hold the k shortest paths\n    vector<vector<sim_mob::PT_NetworkEdge> >& Q = res; //another reference to be consistent with Tan Rui's algorithm specification\n    // Define B to hold the intermediate paths found (Only subset from this set goes to Q)\n    TempPathSet B;\n\n    //step 1: Search shortest path p_0\n    std::set<StreetDirectory::PT_EdgeId> blackList = std::set<StreetDirectory::PT_EdgeId>();\n    std::vector<PT_NetworkEdge> p0 = searchShortestPathWithBlacklist(from, to,blackList, pathCost);\n\n    if (p0.empty()) {\n        return;\n    }\n    Q.push_back(p0);\n    //printPath(p0,pathCost,false);\n\n    //step 2: Each iteration of the below loop gives the kth shortest path\n    // For k in 1:K-1 (K - number of paths required )\n    for (int k = 1; k < kPaths; k++) {\n        //black list first edge from each path found already (p_0,p_1,p_2,...,p_(k-1))\n        blackList.clear();\n        for (int p = 0; p < k; p++) {\n            StreetDirectory::PT_EdgeId firstEdgeId = Q[p].front().getEdgeId();\n            blackList.insert(firstEdgeId);\n        }\n        //Search shortest path, denote p_temp, if p_temp doesn't exist in Q or B, B = (B union {p_temp})\n        std::vector<PT_NetworkEdge> pTemp = searchShortestPathWithBlacklist(from, to, blackList, pathCost);\n        blackList.clear();\n        //Check if p_temp present in Q or B already\n        if (!pTemp.empty() && std::find(Q.begin(), Q.end(), pTemp) == Q.end()) {\n            B.addPathIfUnavailable(pTemp, pathCost);\n        }\n\n        size_t prevPathLength = Q[k - 1].size();\n        if (prevPathLength - 1 >= 1) // Enter loop only if q(k-1) > 1 ;\n        {\n            const vector<PT_NetworkEdge>& prevPath = Q[k - 1];\n            // For i in 1:q(k-1)\n            for (int i = 0; i < prevPathLength - 1; i++) {\n                vector<PT_NetworkEdge> rootpath(prevPath.begin(),prevPath.begin() + (i + 1));\n                // For j in 1:k-1\n                for (int j = 0; j <= k - 1; j++) {\n                    const std::vector<PT_NetworkEdge>& Q_j = Q[j];\n                    // Check if (e_1,e_2,...e_(i))in p_(k-1) is same as (e_1,e_2,...e(i)) in p_j\n                    if (std::equal(Q_j.begin(), Q_j.begin() + (i + 1),  rootpath.begin())) {\n                        // Block e(i+1) from path p_j in graph\n                        if (Q_j.size() > i + 1) {\n                            PT_NetworkEdge removeEdge = Q_j.at(i + 1);\n                            blackList.insert(removeEdge.getEdgeId());\n                        }\n                    }\n                }\n\n                // Denote (e_1,e_2,...e_(i-1)) as S_i. Find the shortest route R_i from ending vertex of e_i and same destination\n                vector<PT_NetworkEdge> S_i(Q[k - 1].begin(),Q[k - 1].begin() + (i));\n                StreetDirectory::PT_VertexId start;\n                //Finding the ending vertex of the edge e_i in Q[k-1]\n                if (S_i.empty()) {\n                    start = from;\n                } else {\n                    StreetDirectory::PT_Vertex startVertex = boost::target(edgeMap[S_i.back().getEdgeId()], graph);\n                    start = boost::get(boost::vertex_name, graph, startVertex);\n                }\n                double s_i_cost = 0.0;\n                for (std::vector<sim_mob::PT_NetworkEdge>::const_iterator itEdge = S_i.begin(); itEdge != S_i.end(); itEdge++) {\n                    s_i_cost += graph[sim_mob::A_StarPublicTransitShortestPathImpl::edgeMap[itEdge->getEdgeId()]].kShortestPathWeight;\n                }\n                vector<PT_NetworkEdge> R_i = searchShortestPathWithBlacklist(start, to, blackList, pathCost);\n                blackList.clear();\n                if (!R_i.empty()) {\n                    // Concatenate S_i and R_i to obtain A_i_k\n                    vector<PT_NetworkEdge> A_i_k;\n                    A_i_k.insert(A_i_k.end(), S_i.begin(), S_i.end());\n                    A_i_k.insert(A_i_k.end(), R_i.begin(), R_i.end());\n                    // If A_i_k not exist in B not in Q\n                    // B = Union(B,A_i_k)\n                    if (std::find(Q.begin(), Q.end(), A_i_k) == Q.end()) {\n                        B.addPathIfUnavailable(A_i_k, (pathCost + s_i_cost));\n                    }\n                }\n            }\n        }\n        // If B is empty Break the whole loop\n        if (B.empty()) {\n            break;\n        }\n\n        // Remove the least cost path A_j in B and put it in Q as p_k\n        uint32_t index = B.getMinElementIdx();\n        Q.push_back(B.getPath(index));\n        //printPath(B.getPath(index),0.0,false);\n        B.deletePath(index);\n    }\n    return;\n}\n", "meta": {"hexsha": "99b7f3ca233110b68d24fada5716ac536f3060cd", "size": 22917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/Basic/shared/geospatial/streetdir/A_StarPublicTransitShortestPathImpl.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/geospatial/streetdir/A_StarPublicTransitShortestPathImpl.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/geospatial/streetdir/A_StarPublicTransitShortestPathImpl.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": 44.2413127413, "max_line_length": 169, "alphanum_fraction": 0.654535934, "num_tokens": 5864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.0280075223300253, "lm_q1q2_score": 0.01400376116501265}}
{"text": "#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <harp.hpp>\n#include <specex_fits.h>\n#include <specex_trace.h>\n#include <specex_gauss_hermite_two_psf.h>\n\nusing namespace std ;\n\nstatic void AddRow1(specex::FitsTable& table,const string& PARAM, double wavemin, double wavemax, harp::vector_double& coeff) {\n  std::vector<specex::FitsTableEntry> row;\n  {specex::FitsTableEntry entry; entry.string_val = PARAM; row.push_back(entry);}\n  {specex::FitsTableEntry entry; entry.double_vals.resize(1); entry.double_vals[0] = wavemin; row.push_back(entry);}\n  {specex::FitsTableEntry entry; entry.double_vals.resize(1); entry.double_vals[0] = wavemax; row.push_back(entry);}\n  {specex::FitsTableEntry entry; entry.double_vals = coeff; row.push_back(entry);}\n  table.data.push_back(row);\n}\n\n\nvoid write_gauss_hermite_two_psf_fits_version_1(const specex::GaussHermite2PSF& psf, fitsfile* fp, int first_hdu) {\n   \n  ////////////////////////////\n  string PSFVER = \"1\";\n  ////////////////////////////\n  \n  int NPIX_X = psf.ccd_image_n_cols;\n  int NPIX_Y = psf.ccd_image_n_rows;\n  int BUNDLMIN = 0;\n  int BUNDLMAX = 0;\n  int FIBERMIN = 0;\n  int FIBERMAX = 0; \n  int NFIBERS=0;\n  for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n      bundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n    \n    if(bundle_it == psf.ParamsOfBundles.begin()) {\n      BUNDLMIN = bundle_it->second.bundle_id;\n      BUNDLMAX = bundle_it->second.bundle_id;\n      FIBERMIN = bundle_it->second.fiber_min;\n      FIBERMAX = bundle_it->second.fiber_max;\n    }\n    \n    BUNDLMIN = min(BUNDLMIN,bundle_it->second.bundle_id);\n    BUNDLMAX = max(BUNDLMAX,bundle_it->second.bundle_id);\n    FIBERMIN = min(FIBERMIN,bundle_it->second.fiber_min);\n    FIBERMAX = max(FIBERMAX,bundle_it->second.fiber_max);\n  \n    NFIBERS += (bundle_it->second.fiber_max-bundle_it->second.fiber_min+1);\n  }\n  \n  int GHDEGX = psf.core_degree;\n  int GHDEGY = psf.core_degree;\n  int GHDEGX2 = psf.second_degree;\n  int GHDEGY2 = psf.second_degree;\n  \n\n  int status = 0;\n  fits_movabs_hdu ( fp, first_hdu, NULL, &status ); harp::fits::check ( status );\n  \n  // get largest legendre degree of all params in all bundles and check param numbers match !!\n  int ncoeff=0;\n  \n  int nparams=psf.LocalNAllPar();\n  int nparams_all = nparams;\n  nparams_all += 2; // X and Y\n  nparams_all += 1; // GH trivial order zero\n#ifdef CONTINUUM\n  nparams_all += 1; // continuum\n#endif\n  \n  for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n      bundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n\n    if( int(bundle_it->second.AllParPolXW.size()) != nparams ) SPECEX_ERROR(\"Fatal inconsistency in number of parameters in psf between bundles: AllParPolXW.size=\" << bundle_it->second.AllParPolXW.size() << \" psf.LocalNAllPar()=\" << nparams);\n\n    for(size_t p=0;p<bundle_it->second.AllParPolXW.size();p++) {\n      ncoeff=max(ncoeff,bundle_it->second.AllParPolXW[p]->ydeg+1);\n    }\n  }\n  \n  ncoeff += 2; // increase degree of legendre polynomials to minimize mapping errors\n  \n  specex::FitsTable table;\n\n  { // column description\n    table.AddColumnDescription(\"PARAM\",\"8A\",\"\",\"\");\n    table.AddColumnDescription(\"WAVEMIN\",\"D\",\"\",\"\");\n    table.AddColumnDescription(\"WAVEMAX\",\"D\",\"\",\"\");\n    char coeff_tform[100];\n    sprintf(coeff_tform,\"%dD\",ncoeff*NFIBERS);\n    vector <int> dim; dim.resize(2);\n    dim[0]=ncoeff;\n    dim[1]=NFIBERS;\n    \n    string sdim = table.encode_dimension(dim);\n    // debug\n    vector <int> dim2 = table.decode_dimension(sdim);\n    if (dim2.size()!=2 || dim2[0]!= dim[0]|| dim2[1]!=dim[1]) {\n      SPECEX_ERROR(\"error encode/decode dimension\");\n    }\n\n    table.AddColumnDescription(\"COEFF\",coeff_tform,sdim,\"\");\n  }\n  \n \n  int LEGWMIN=1000000;\n  int LEGWMAX=0;\n  vector<string> keys;\n  \n  \n\n  { // data\n    \n    \n    // now loop on real psf parameters\n\n    harp::vector_double wave(ncoeff);\n    harp::vector_double values(ncoeff);\n    \n    // get the max range of wavelength and convert to int \n    \n    for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n\t  bundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n      const specex::PSF_Params & params_of_bundle = bundle_it->second;\n      for(int p=0;p<nparams;p++) { \n\tLEGWMIN=min(LEGWMIN,int(floor(params_of_bundle.AllParPolXW[p]->ymin)));\n\tLEGWMAX=max(LEGWMAX,int(floor(params_of_bundle.AllParPolXW[p]->ymax))+1);\n      }\n    }\n    \n    \n    double wavemin = double(LEGWMIN);\n    double wavemax = double(LEGWMAX);\n    {\n      double wavestep = (wavemax-wavemin)/(ncoeff-1);\n      for(int w=0;w<ncoeff;w++) {\n\twave[w]   = wavemin + wavestep*w;\n      }\n    }\n    \n    bool need_to_add_first_gh = true;\n\n    harp::vector_double coeff(ncoeff*NFIBERS);\n\n    // first deal with X and Y\n    {\n      harp::vector_double coeff_y(ncoeff*NFIBERS);\n      harp::vector_double values_y(ncoeff);\n      coeff.clear();\n      coeff_y.clear();\n      int fiber_index=0;\n      \n      for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n\t  bundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n\tconst specex::PSF_Params & params_of_bundle = bundle_it->second;\n\tfor(int fiber=params_of_bundle.fiber_min; fiber<=params_of_bundle.fiber_max; fiber++,fiber_index++) {\n\t  \n\t  const specex::Trace &trace = psf.FiberTraces.find(fiber)->second;\n\t  specex::Legendre1DPol pol1d_x(ncoeff-1,wavemin,wavemax);\n\t  specex::Legendre1DPol pol1d_y(ncoeff-1,wavemin,wavemax);\n\t  for(int w=0;w<ncoeff;w++) {\n\t    values[w]   = trace.X_vs_W.Value(wave[w]);\n\t    values_y[w] = trace.Y_vs_W.Value(wave[w]);\n\t  }\n\t  pol1d_x.Fit(wave,values,0,false);\n\t  pol1d_y.Fit(wave,values_y,0,false);\n\t  for(int w = 0; w < ncoeff ; w++) {\n\t    coeff(fiber_index*ncoeff+w)   =  pol1d_x.coeff(w);\n\t    coeff_y(fiber_index*ncoeff+w) =  pol1d_y.coeff(w);\n\t  }\n\t  \n\t  \n\t} // end of loop on fiber\n      } // end of loop on bundles\n      \n      AddRow1(table,\"X\",LEGWMIN,LEGWMAX,coeff);\n      AddRow1(table,\"Y\",LEGWMIN,LEGWMAX,coeff_y);\n      \n    } // end of X Y context\n\n    // precompute coeffs of GH2-0-0\n    harp::vector_double  gh200coeff;\n    harp::vector_double  gh100coeff;\n    {\n      int gh200_index = psf.ParamIndex(\"GH2-0-0\");\n      int fiber_index=0;\n      gh200coeff.resize(coeff.size());\n      gh200coeff.clear();\n      gh100coeff.resize(coeff.size());\n      gh100coeff.clear();\n      \n      // duplicated code that need to be simplified\n      for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n\t  bundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n\tconst specex::PSF_Params & params_of_bundle = bundle_it->second;\n\tconst specex::Pol_p pol2d = params_of_bundle.AllParPolXW[gh200_index]; // this is the 2D polynomiald of x_ccd and wave for this param and bundle\n      \n\tfor(int fiber=params_of_bundle.fiber_min; fiber<=params_of_bundle.fiber_max; fiber++,fiber_index++) {\n\t  \n\t  const specex::Trace& trace = psf.FiberTraces.find(fiber)->second; // X_vs_W.Value();\n\t  \n\t  // build a Legendre1DPol out of the Legendre2DPol\n\t  specex::Legendre1DPol pol1d(ncoeff-1,wavemin,wavemax);\n\t  for(int w=0;w<ncoeff;w++) {\n\t    values[w] = pol2d->Value(trace.X_vs_W.Value(wave[w]),wave[w]);\n\t  }\n\t  pol1d.Fit(wave,values,0,false);\n\t  \n\t  // now copy parameters;\n\t  \n\t  for(int w = 0; w < ncoeff ; w++) {\n\t    gh200coeff(fiber_index*ncoeff+w) = pol1d.coeff(w); // this is the definition of the ordering, (wave,fiber)\n\t    gh100coeff(fiber_index*ncoeff+w) = -gh200coeff(fiber_index*ncoeff+w); // this is the definition of the ordering, (wave,fiber)\n\t  }\n\t  gh100coeff(fiber_index*ncoeff) += 1;\n\t}\n      }\n    }\n\n    for(int p=0;p<nparams;p++) { \n      \n      coeff.clear();\n      \n      string pname = psf.ParamName(p);\n\n      if(need_to_add_first_gh && pname.find(\"GH-\")<pname.npos) { // insert now GH param 0\n\tAddRow1(table,\"GH-0-0\",LEGWMIN,LEGWMAX,gh100coeff);\n\tneed_to_add_first_gh = false;\n\tcout << \"GH-0-0  : \" << gh100coeff << endl;\n\tcout << \"GH2-0-0 : \" << gh200coeff << endl;\n      }\n\n      \n      int fiber_index=0;\n      for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n\t  bundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n\tconst specex::PSF_Params & params_of_bundle = bundle_it->second;\n\t\n\tconst specex::Pol_p pol2d = params_of_bundle.AllParPolXW[p]; // this is the 2D polynomiald of x_ccd and wave for this param and bundle\n\t\n\n\t\n\tfor(int fiber=params_of_bundle.fiber_min; fiber<=params_of_bundle.fiber_max; fiber++,fiber_index++) {\n\t  \n\t  const specex::Trace& trace = psf.FiberTraces.find(fiber)->second; // X_vs_W.Value();\n\n\t  // build a Legendre1DPol out of the Legendre2DPol\n\t  specex::Legendre1DPol pol1d(ncoeff-1,wavemin,wavemax);\n\t  for(int w=0;w<ncoeff;w++) {\n\t    values[w] = pol2d->Value(trace.X_vs_W.Value(wave[w]),wave[w]);\n\t  }\n\t  pol1d.Fit(wave,values,0,false);\n\n\t  // now copy parameters;\n\t  \n\t  for(int w = 0; w < ncoeff ; w++) {\n\t    coeff(fiber_index*ncoeff+w) = pol1d.coeff(w); // this is the definition of the ordering, (wave,fiber)\n\t  }\n\t  \n\t} // end of loop on fibers of bundle\n\t      \n      } // end of loop on bundles\n\n      AddRow1(table,pname,LEGWMIN,LEGWMAX,coeff);\n      \n    } // end of loop on params\n\n#ifdef CONTINUUM\n    {\n      coeff.clear();\n      int fiber_index=0;\n      for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n\t  bundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n\tconst specex::PSF_Params & params_of_bundle = bundle_it->second;\n\tspecex::Legendre1DPol pol1d(ncoeff-1,wavemin,wavemax);\n\tfor(int w=0;w<ncoeff;w++) {\n\t  values[w]   = params_of_bundle.ContinuumPol.Value(wave[w]);\n\t}\n\tpol1d.Fit(wave,values,0,false);\n\tfor(int fiber=params_of_bundle.fiber_min; fiber<=params_of_bundle.fiber_max; fiber++,fiber_index++) {\n\t  for(int w = 0; w < ncoeff ; w++) {\n\t    coeff(fiber_index*ncoeff+w)   =  pol1d.coeff(w);\n\t  }    \n\t}\n      }\n      AddRow1(table,\"CONT\",LEGWMIN,LEGWMAX,coeff);\n    }\n#endif    \n\n\n  }\n  \n  // write table\n  table.Write(fp);\n  \n \n  // write keywords\n  {\n    \n    fits_write_comment(fp,\"------------------------------------------------------------------------\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"PSF generated by specex, https://github.com/julienguy/specex\",&status); harp::fits::check ( status );\n    \n    {\n      char date_comment[80];\n      time_t t = time(0);   // get time now\n      struct tm * now = localtime( & t );\n      sprintf(date_comment,\"PSF fit date %04d-%02d-%02d\",(now->tm_year + 1900),(now->tm_mon + 1),now->tm_mday);\n      fits_write_comment(fp,date_comment,&status); harp::fits::check ( status );\n    }\n    ///////////////////////xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx////////\n    fits_write_comment(fp,\"-  \",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"Each row of the table contains the data vector of one PSF parameter\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"The size of the vector is ((FIBERMAX-FIBERMIN+1)*(LEGDEG+1))\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"Description of  the NPARAMS parameters : \",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"X        : CCD column coordinate (as a function of fiber and wavelength)\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"Y        : CCD row coordinate (as a function of fiber and wavelength)\",&status); harp::fits::check ( status ); \n    fits_write_comment(fp,\"         (X,Y)=(0,0) means that PSF is centered on center of first pixel\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"GHSIGX   : Sigma of first Gaussian along CCD columns for PSF core\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"GHSIGY   : Sigma of first Gaussian along CCD rows for PSF core\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"GHNSIG   : NxSigma cutoff for first Gaussian\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"GHSIGX2  : Sigma of second Gaussian along CCD columns for PSF wings\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"GHSIGY2  : Sigma of second Gaussian along CCD rows for PSF wings\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"GH-i-j   : Hermite pol. coefficents, i along columns, j along rows,\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"         i is integer from 0 to GHDEGX, j is integer from 0 to GHDEGY,\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"         there are (GHDEGX+1)*(GHDEGY+1) such coefficents.\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"GH2-i-j  : Hermite pol. coefficents for sec. GH psf, i along columns, j along rows,\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"TAILAMP  : Amplitude of PSF tail\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"TAILCORE : Size in pixels of PSF tail saturation in PSF core\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"TAILXSCA : Scaling apply to CCD coordinate along columns for PSF tail\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"TAILYSCA : Scaling apply to CCD coordinate along rows for PSF tail\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"TAILINDE : Asymptotic power law index of PSF tail\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"CONT     : Continuum flux in arc image (not part of PSF)\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"-  \",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"PSF_core(X,Y) = SUM_ij (GH-i-j)*HERM(i,X/GHSIGX)*HERM(j,Y/GHSIGY)\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"               * GAUS(X,GHSIGX)*GAUS(Y,GHSIGY)\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"              +SUM_ij (GH2-i-j)*HERM(i,X/GHSIGX2)*HERM(j,Y/GHSIGY2)\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"                * GAUS(X,GHSIGX2)*GAUS(Y,GHSIGY2)\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"-  \",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"PSF_tail(X,Y) = TAILAMP*R^2/(TAILCORE^2+R^2)^(1+TAILINDE/2)\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"                with R^2=(X*TAILXSCA)^2+(Y*TAILYSCA)^2\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"-  \",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"PSF_core is integrated in pixel\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"PSF_tail is not, it is evaluated at center of pixel\",&status); harp::fits::check ( status );\n    fits_write_comment(fp,\"------------------------------------------------------------------------\",&status); harp::fits::check ( status );   \n    harp::fits::key_write(fp,\"EXTNAME\",\"PSF\",\"\");\n    harp::fits::key_write(fp,\"PSFTYPE\",\"GAUSS-HERMITE2\",\"\");\n    harp::fits::key_write(fp,\"PSFVER\",PSFVER,\"\");\n    \n    harp::fits::key_write(fp,\"MJD\",(long long int)psf.mjd,\"MJD of arc lamp exposure\");\n    harp::fits::key_write(fp,\"PLATEID\",psf.plate_id,\"plate ID of arc lamp exposure\");\n    harp::fits::key_write(fp,\"CAMERA\",psf.camera_id,\"camera ID\");\n    harp::fits::key_write(fp,\"ARCEXP\",psf.arc_exposure_id,\"ID of arc lamp exposure used to fit PSF\");\n    \n    harp::fits::key_write(fp,\"NPIX_X\",(long long int)NPIX_X,\"number of columns in input CCD image\");\n    harp::fits::key_write(fp,\"NPIX_Y\",(long long int)NPIX_Y,\"number of rows in input CCD image\");\n    harp::fits::key_write(fp,\"HSIZEX\",(long long int)psf.hSizeX,\"Half size of PSF in fit, NX=2*HSIZEX+1\");\n    harp::fits::key_write(fp,\"HSIZEY\",(long long int)psf.hSizeY,\"Half size of PSF in fit, NY=2*HSIZEY+1\");\n    harp::fits::key_write(fp,\"BUNDLMIN\",(long long int)BUNDLMIN,\"first bundle of fibers (starting at 0)\");\n    harp::fits::key_write(fp,\"BUNDLMAX\",(long long int)BUNDLMAX,\"last bundle of fibers (included)\");\n    harp::fits::key_write(fp,\"FIBERMIN\",(long long int)FIBERMIN,\"first fiber (starting at 0)\");\n    harp::fits::key_write(fp,\"FIBERMAX\",(long long int)FIBERMAX,\"last fiber (included)\");\n    harp::fits::key_write(fp,\"NPARAMS\",(long long int)nparams_all,\"number of PSF parameters\");\n    harp::fits::key_write(fp,\"LEGDEG\",(long long int)(ncoeff-1),\"degree of Legendre pol.(wave) for parameters\");\n    harp::fits::key_write(fp,\"GHDEGX\",(long long int)GHDEGX,\"degree of Hermite polynomial along CCD columns\");\n    harp::fits::key_write(fp,\"GHDEGY\",(long long int)GHDEGY,\"degree of Hermite polynomial along CCD rows\");\n    harp::fits::key_write(fp,\"GHDEGX2\",(long long int)GHDEGX2,\"degree of Hermite polynomial along CCD columns (sec. term)\");\n    harp::fits::key_write(fp,\"GHDEGY2\",(long long int)GHDEGY2,\"degree of Hermite polynomial along CCD rows (sec. term)\");\n\n    // add chi2\n    harp::fits::key_write(fp,\"PSFERROR\",psf.psf_error,\"assumed PSF fractional error in chi2\");\n    harp::fits::key_write(fp,\"READNOIS\",psf.readout_noise,\"assumed read out noise in chi2\");\n    harp::fits::key_write(fp,\"GAIN\",psf.gain,\"assumed gain in chi2\");\n    \n    for(std::map<int,specex::PSF_Params>::const_iterator bundle_it = psf.ParamsOfBundles.begin();\n\tbundle_it != psf.ParamsOfBundles.end(); ++bundle_it) {\n      \n      const specex::PSF_Params & params_of_bundle = bundle_it->second;\n      \n      \n      int ndf = params_of_bundle.ndata - params_of_bundle.nparams;\n      double chi2pdf = 0;\n      if(ndf>0) chi2pdf = params_of_bundle.chi2/ndf;\n      \n      char key[20];\n      char comment[800];\n\n      \n      sprintf(key,\"B%02dRCHI2\",params_of_bundle.bundle_id);\n      sprintf(comment,\"best fit chi2/ndf for fiber bundle %d\",params_of_bundle.bundle_id);\n      harp::fits::key_write(fp,key,chi2pdf,comment);\n      \n      sprintf(key,\"B%02dNDATA\",params_of_bundle.bundle_id);\n      sprintf(comment,\"number of pixels in fit for fiber bundle %d\",params_of_bundle.bundle_id);   \n      harp::fits::key_write(fp,key,(long long int)params_of_bundle.ndata,comment);\n      \n      sprintf(key,\"B%02dNPAR\",params_of_bundle.bundle_id);\n      sprintf(comment,\"number of parameters in fit for fiber bundle %d\",params_of_bundle.bundle_id);   \n      harp::fits::key_write(fp,key,(long long int)params_of_bundle.nparams,comment);\n      \n    }\n  }\n  \n}\n\n\n", "meta": {"hexsha": "db8c53cbba9d9f218576c37df8bed8da23f8703b", "size": 18411, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/library/specex_psf_io_gauss_hermite_two_psf_fits_1.cc", "max_stars_repo_name": "marcelo-alvarez/specex", "max_stars_repo_head_hexsha": "809c5540e76dc1681453488732d5845078427ad1", "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/library/specex_psf_io_gauss_hermite_two_psf_fits_1.cc", "max_issues_repo_name": "marcelo-alvarez/specex", "max_issues_repo_head_hexsha": "809c5540e76dc1681453488732d5845078427ad1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/library/specex_psf_io_gauss_hermite_two_psf_fits_1.cc", "max_forks_repo_name": "marcelo-alvarez/specex", "max_forks_repo_head_hexsha": "809c5540e76dc1681453488732d5845078427ad1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3472906404, "max_line_length": 242, "alphanum_fraction": 0.6655260442, "num_tokens": 5446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368159568461, "lm_q2_score": 0.0356785507495597, "lm_q1q2_score": 0.013998008999036998}}
{"text": "/*!\n@file\nForward declares `boost::hana::Group`.\n\n@copyright Louis Dionne 2013-2016\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_CONCEPT_GROUP_HPP\n#define BOOST_HANA_FWD_CONCEPT_GROUP_HPP\n\n#include <boost/hana/config.hpp>\n\n\nBOOST_HANA_NAMESPACE_BEGIN\n    //! @ingroup group-concepts\n    //! @defgroup group-Group Group\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    //! 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    //! 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    //! Refined concept\n    //! ---------------\n    //! `Monoid`\n    //!\n    //!\n    //! Concrete models\n    //! ---------------\n    //! `hana::integral_constant`\n    //!\n    //!\n    //! Free model 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    //! 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    template <typename G>\n    struct Group;\nBOOST_HANA_NAMESPACE_END\n\n#endif // !BOOST_HANA_FWD_CONCEPT_GROUP_HPP\n", "meta": {"hexsha": "a7ec238d54b729a62e9cff0255e427c92c5da3c2", "size": 3744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/hana/fwd/concept/group.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 886.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T20:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:47:52.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/hana/fwd/concept/group.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/hana/fwd/concept/group.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 33.4285714286, "max_line_length": 78, "alphanum_fraction": 0.5560897436, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.03846619174275306, "lm_q1q2_score": 0.013962043056232321}}
{"text": "#pragma once\n\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#include <memory>\n#include <functional>\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n\nnamespace Symbolic {\n\n#define DEF_TYPE_PREDICATE_DEFAULT(predicate_name) \\\n    virtual bool predicate_name() const {          \\\n        return false;                              \\\n    }\n\n    struct TypeCheckError {\n        std::string msg;\n    };\n\n    class Type {\n    public:\n        virtual bool is_val() const = 0;\n        virtual bool equal_to(std::shared_ptr<Type> t) const = 0;\n        virtual void print(std::ostream &os) const = 0;\n        virtual int get_bv_width() const {\n            throw TypeCheckError { \"not a bit vector\" };\n        }\n        virtual bool is_bv_type() const {\n            return false;\n        }\n        virtual bool is_func_type() const {\n            return false;\n        }\n    };\n\n    class ValType : public Type {\n    public:\n        enum class T {\n            BITVEC,\n        };\n\n        T type;\n\n        virtual bool is_val() const override {\n            return true;\n        }\n    };\n\n    class BitVecType : public ValType {\n    public:\n        int bitwidth;\n\n        virtual int get_bv_width() const override {\n            return bitwidth;\n        }\n\n        virtual bool is_bv_type() const override {\n            return true;\n        }\n\n        virtual void print(std::ostream &os) const override;\n        virtual bool equal_to(std::shared_ptr<Type> t) const override;\n\n        BitVecType(): bitwidth(0) {}\n        BitVecType(int bw): bitwidth(bw) {}\n    };\n\n    class UFType : public Type {\n    public:\n        std::vector<std::shared_ptr<ValType>> key_types;\n        std::shared_ptr<ValType> val_type;\n\n        UFType(const std::vector<std::shared_ptr<ValType>> &kts,\n               std::shared_ptr<ValType> vt): key_types(kts), val_type(vt) {}\n\n        virtual bool is_val() const override {\n            return false;\n        }\n\n        virtual bool is_func_type() const override {\n            return true;\n        }\n        \n        virtual void print(std::ostream &os) const override;\n        virtual bool equal_to(std::shared_ptr<Type> t) const override;\n    };\n\n    class Expr;\n    class Lambda;\n    class ConcreteBv;\n    class SymbolicVar;\n    class AddExpr;\n    class SubExpr;\n    class MulExpr;\n    class DivExpr;\n    class ModExpr;\n    class UDivExpr;\n    class UModExpr;\n\n    class LAndExpr;\n    class LOrExpr;\n    class LXorExpr;\n    class LNotExpr;\n    class ImpliesExpr;\n\n    class AndExpr;\n    class OrExpr;\n    class XorExpr;\n    class NotExpr;\n    class LshExpr;\n    class LRshExpr;\n    class ARshExpr;\n\n    class EqExpr;\n    class NeqExpr;\n    class LeExpr;\n    class LtExpr;\n    class GeExpr;\n    class GtExpr;\n    class UleExpr;\n    class UltExpr;\n    class UgeExpr;\n    class UgtExpr;\n\n    class ExtractExpr;\n    class SExtExpr;\n    class UExtExpr;\n\n    class IteExpr;\n    class FuncApply;\n    class ConcatExpr;\n\n    class ForallExpr;\n    class ExistsExpr;\n\n#define DECLARE_EXPR_VISITOR(t) virtual void visit_expr(t &expr) { \\\n    this->visit_expr(*(Expr *)&expr);                      \\\n    }\n\n    class ExprVisitor {\n    public:\n        virtual void visit(Expr &expr);\n\n        virtual void visit_expr(Expr &e) {\n        }\n        DECLARE_EXPR_VISITOR(Lambda);\n        DECLARE_EXPR_VISITOR(ConcreteBv);\n        DECLARE_EXPR_VISITOR(SymbolicVar);\n\n        DECLARE_EXPR_VISITOR(AddExpr);\n        DECLARE_EXPR_VISITOR(SubExpr);\n        DECLARE_EXPR_VISITOR(MulExpr);\n        DECLARE_EXPR_VISITOR(DivExpr);\n        DECLARE_EXPR_VISITOR(ModExpr);\n        DECLARE_EXPR_VISITOR(UDivExpr);\n        DECLARE_EXPR_VISITOR(UModExpr);\n\n        DECLARE_EXPR_VISITOR(LAndExpr);\n        DECLARE_EXPR_VISITOR(LOrExpr);\n        DECLARE_EXPR_VISITOR(LXorExpr);\n        DECLARE_EXPR_VISITOR(LNotExpr);\n        DECLARE_EXPR_VISITOR(ImpliesExpr);\n\n        DECLARE_EXPR_VISITOR(AndExpr);\n        DECLARE_EXPR_VISITOR(OrExpr);\n        DECLARE_EXPR_VISITOR(XorExpr);\n        DECLARE_EXPR_VISITOR(NotExpr);\n        DECLARE_EXPR_VISITOR(LshExpr);\n        DECLARE_EXPR_VISITOR(LRshExpr);\n        DECLARE_EXPR_VISITOR(ARshExpr);\n\n        DECLARE_EXPR_VISITOR(EqExpr);\n        DECLARE_EXPR_VISITOR(NeqExpr);\n        DECLARE_EXPR_VISITOR(LeExpr);\n        DECLARE_EXPR_VISITOR(LtExpr);\n        DECLARE_EXPR_VISITOR(GeExpr);\n        DECLARE_EXPR_VISITOR(GtExpr);\n        DECLARE_EXPR_VISITOR(UleExpr);\n        DECLARE_EXPR_VISITOR(UltExpr);\n        DECLARE_EXPR_VISITOR(UgeExpr);\n        DECLARE_EXPR_VISITOR(UgtExpr);\n\n        DECLARE_EXPR_VISITOR(ExtractExpr);\n        DECLARE_EXPR_VISITOR(SExtExpr);\n        DECLARE_EXPR_VISITOR(UExtExpr);\n\n        DECLARE_EXPR_VISITOR(IteExpr);\n        DECLARE_EXPR_VISITOR(FuncApply);\n        DECLARE_EXPR_VISITOR(ConcatExpr);\n\n        DECLARE_EXPR_VISITOR(ForallExpr);\n        DECLARE_EXPR_VISITOR(ExistsExpr);\n    };\n\n    using ExprPtr = std::shared_ptr<Expr>;\n\n#define VISITOR_ACCEPT                                   \\\n    virtual void accept(ExprVisitor &v) override {       \\\n        v.visit_expr(*this);                             \\\n    }\n\n\n    class Expr : public std::enable_shared_from_this<Expr> {\n    public:\n        std::shared_ptr<Type> type;\n        DEF_TYPE_PREDICATE_DEFAULT(is_symbolic);\n        DEF_TYPE_PREDICATE_DEFAULT(is_var);\n\n        Expr();\n\n        virtual std::shared_ptr<Expr> simplify() {\n            return shared_from_this();\n        }\n\n        virtual void accept(ExprVisitor &v) {\n            v.visit_expr(*this);\n        }\n\n        boost::uuids::uuid get_uuid() const { return uuid; }\n\n    protected:\n        boost::uuids::uuid uuid;\n    };\n\n    template <typename T>\n    using PtrList = std::vector<std::shared_ptr<T>>;\n\n    class OpApplyNode : public Expr {\n    public:\n        using ArgList = PtrList<Expr>;\n\n        OpApplyNode(const ArgList &args);\n\n        void type_check(const PtrList<Type> &types);\n\n        virtual bool is_symbolic() const override {\n            return is_symbolic_;\n        }\n\n        ArgList simplify_args() const;\n\n    public:\n        ArgList args_;\n        bool is_symbolic_;\n    };\n\n    class ConcreteVal : public Expr {\n    public:\n\n    };\n\n    class Lambda : public Expr {\n    public:\n        using FuncT = std::function<ExprPtr(OpApplyNode::ArgList)>;\n        FuncT func;\n\n        Lambda(std::shared_ptr<Type> func_type,\n               FuncT func);\n\n        Lambda(const PtrList<Type> &arg_t,\n               std::shared_ptr<Type> ret_t,\n               FuncT func);\n        VISITOR_ACCEPT;\n    };\n\n    class ConcreteBv : public ConcreteVal {\n    public:\n        ConcreteBv(int bv_size, uint64_t val) {\n            auto t = std::make_shared<BitVecType>();\n            t->bitwidth = bv_size;\n            type = std::dynamic_pointer_cast<Type>(t);\n            val_ = val;\n        }\n\n        uint64_t get_val() const {\n            return val_;\n        }\n\n        VISITOR_ACCEPT;\n    protected:\n        uint64_t val_;\n    };\n\n    class SymbolicVar : public Expr {\n    public:\n        SymbolicVar(std::shared_ptr<Type> t, const std::string &n):\n            name(n) { type = t; }\n        virtual bool is_symbolic() const override {\n            return true;\n        }\n        virtual bool is_var() const override {\n            return true;\n        }\n\n        VISITOR_ACCEPT;\n\n        std::string name;\n    };\n\n    class FuncApply : public OpApplyNode {\n    public:\n        FuncApply(ExprPtr func, const ArgList &args);\n        VISITOR_ACCEPT;\n\n        ExprPtr func;\n    };\n\n    class BvBinOpExpr : public OpApplyNode {\n    public:\n        BvBinOpExpr(const ArgList &args);\n        virtual ExprPtr simplify() override;\n        virtual ExprPtr concrete_binop(uint64_t a1, uint64_t a2) {\n            return shared_from_this();\n        }\n    };\n\n    class BvBinPredExpr : public OpApplyNode {\n    public:\n        BvBinPredExpr(const ArgList &args);\n        virtual ExprPtr simplify() override;\n        virtual ExprPtr concrete_binop(uint64_t a1, uint64_t a2) {\n            return shared_from_this();\n        }\n    };\n\n#define DECLARE_OP(class_name) class class_name : public BvBinOpExpr {  \\\n    public:                                                             \\\n    class_name(const ArgList &args);                                    \\\n    VISITOR_ACCEPT;                                                     \\\n    virtual ExprPtr concrete_binop(uint64_t a1, uint64_t a2) override;  \\\n    }\n\n#define DECLARE_PRED(class_name) class class_name : public BvBinPredExpr { \\\n    public:                                                             \\\n    class_name(const ArgList &args);                                    \\\n    VISITOR_ACCEPT;                                                     \\\n    virtual ExprPtr concrete_binop(uint64_t a1, uint64_t a2) override;  \\\n    }\n\n    DECLARE_OP(AddExpr);\n    DECLARE_OP(SubExpr);\n    DECLARE_OP(MulExpr);\n    DECLARE_OP(DivExpr);\n    DECLARE_OP(ModExpr);\n    DECLARE_OP(UDivExpr);\n    DECLARE_OP(UModExpr);\n\n    DECLARE_OP(LAndExpr);\n    DECLARE_OP(LOrExpr);\n    DECLARE_OP(LXorExpr);\n    DECLARE_OP(ImpliesExpr);\n\n    DECLARE_OP(AndExpr);\n    DECLARE_OP(OrExpr);\n    DECLARE_OP(XorExpr);\n    DECLARE_OP(LshExpr);\n    DECLARE_OP(LRshExpr);\n    DECLARE_OP(ARshExpr);\n\n    DECLARE_PRED(EqExpr);\n    DECLARE_PRED(NeqExpr);\n    DECLARE_PRED(LeExpr);\n    DECLARE_PRED(LtExpr);\n    DECLARE_PRED(GeExpr);\n    DECLARE_PRED(GtExpr);\n    DECLARE_PRED(UleExpr);\n    DECLARE_PRED(UltExpr);\n    DECLARE_PRED(UgeExpr);\n    DECLARE_PRED(UgtExpr);\n\n    class ConcatExpr : public OpApplyNode {\n    public:\n        ConcatExpr(const ArgList &args);\n        VISITOR_ACCEPT;\n    };\n    class LNotExpr : public OpApplyNode {\n    public:\n        LNotExpr(ExprPtr e);\n        VISITOR_ACCEPT;\n    };\n\n    class NotExpr : public OpApplyNode {\n    public:\n        NotExpr(ExprPtr e);\n        VISITOR_ACCEPT;\n    };\n\n    class ExtractExpr : public Expr {\n    public:\n        ExtractExpr(ExprPtr e, int start, int end);\n        VISITOR_ACCEPT;\n\n        virtual bool is_symbolic() const override {\n            return true;\n        }\n\n        ExprPtr v;\n        int from, to;\n    };\n\n    class SExtExpr : public Expr {\n    public:\n        SExtExpr(ExprPtr e, int to);\n        VISITOR_ACCEPT;\n\n        virtual bool is_symbolic() const override {\n            return true;\n        }\n\n        ExprPtr v;\n        int to;\n    };\n\n    class UExtExpr : public Expr {\n    public:\n        UExtExpr(ExprPtr e, int to);\n        VISITOR_ACCEPT;\n\n        virtual bool is_symbolic() const override {\n            return true;\n        }\n\n        ExprPtr v;\n        int to;\n    };\n\n    class IteExpr : public Expr {\n    public:\n        IteExpr(ExprPtr cond, ExprPtr t, ExprPtr f);\n        VISITOR_ACCEPT;\n        virtual std::shared_ptr<Expr> simplify() override;\n\n        virtual bool is_symbolic() const override {\n            return true;\n        }\n\n        ExprPtr cond;\n        ExprPtr t_val;\n        ExprPtr f_val;\n    };\n\n    class ForallExpr : public Expr {\n    public:\n        ForallExpr(const std::vector<ExprPtr> &vars, ExprPtr cond);\n        VISITOR_ACCEPT;\n        virtual std::shared_ptr<Expr> simplify() override;\n\n        virtual bool is_symbolic() const override {\n            return true;\n        }\n\n        std::vector<ExprPtr> vars;\n        ExprPtr cond;\n    };\n\n    class ExistsExpr : public Expr {\n    public:\n        ExistsExpr(const std::vector<ExprPtr> &vars, ExprPtr cond);\n        VISITOR_ACCEPT;\n        virtual std::shared_ptr<Expr> simplify() override;\n\n        virtual bool is_symbolic() const override {\n            return true;\n        }\n\n        std::vector<ExprPtr> vars;\n        ExprPtr cond;\n    };\n\n#undef DECLARE_PRED\n#undef DECLARE_OP\n\n    ExprPtr endian_reverse(ExprPtr val);\n\n    uint64_t get_concrete_val(ExprPtr v);\n} \n\n#define mk_expr_ptr(T, ...) std::dynamic_pointer_cast<::Symbolic::Expr>(std::shared_ptr<::Symbolic::T>(new ::Symbolic::T(__VA_ARGS__)))\n\n#define mk_concrete_bv(bw, n) mk_expr_ptr(ConcreteBv, bw, n)\n", "meta": {"hexsha": "d3e2be6b82616f7836ab34cef1e34385fe6da934", "size": 11984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/symbolic-expr.hpp", "max_stars_repo_name": "Kaiyuan-Zhang/Gravel-public", "max_stars_repo_head_hexsha": "ff3f7dc7d5ac63d91e26f03ae4e49a7451c6cb22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-04-11T19:11:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T10:46:39.000Z", "max_issues_repo_path": "include/symbolic-expr.hpp", "max_issues_repo_name": "Kaiyuan-Zhang/Gravel-public", "max_issues_repo_head_hexsha": "ff3f7dc7d5ac63d91e26f03ae4e49a7451c6cb22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-01T20:19:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-01T20:19:43.000Z", "max_forks_repo_path": "include/symbolic-expr.hpp", "max_forks_repo_name": "Kaiyuan-Zhang/Gravel-public", "max_forks_repo_head_hexsha": "ff3f7dc7d5ac63d91e26f03ae4e49a7451c6cb22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-18T03:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-18T03:36:03.000Z", "avg_line_length": 24.8115942029, "max_line_length": 135, "alphanum_fraction": 0.5877837116, "num_tokens": 2794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.03021458455677822, "lm_q1q2_score": 0.013929430460625534}}
{"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 \"PyImathFun.h\"\n#include \"PyImathDecorators.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathAutovectorize.h\"\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 <ImathMatrixAlgo.h>\n#include <ImathFun.h>\n\nnamespace PyImath {\n\nusing namespace boost::python;\nusing namespace PyImath;\n\nnamespace {\n\ntemplate <class T>\nstruct rotationXYZWithUpDir_op\n{\n    static IMATH_NAMESPACE::Vec3<T>\n    apply(const IMATH_NAMESPACE::Vec3<T> &from, const IMATH_NAMESPACE::Vec3<T> &to, \n          const IMATH_NAMESPACE::Vec3<T> &up)\n    {\n        IMATH_NAMESPACE::Vec3<T> retval;\n        IMATH_NAMESPACE::extractEulerXYZ(IMATH_NAMESPACE::rotationMatrixWithUpDir(from,to,up),retval);\n        return retval;\n    }\n};\n\ntemplate <class T>\nstruct abs_op\n{\n    static T\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::abs<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct sign_op\n{\n    static T\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::sign<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct log_op\n{\n    static T\n    apply(T value)\n    {\n        return ::log(value);\n    }\n};\n\ntemplate <class T>\nstruct log10_op\n{\n    static T\n    apply(T value)\n    {\n        return ::log10(value);\n    }\n};\n\ntemplate <class T>\nstruct lerp_op\n{\n    static T\n    apply(T a, T b, T t)\n    {\n        return IMATH_NAMESPACE::lerp<T>(a,b,t);\n    }\n};\n\ntemplate <class T>\nstruct ulerp_op\n{\n    static T\n    apply(T a, T b, T t)\n    {\n        return IMATH_NAMESPACE::ulerp<T>(a,b,t);\n    }\n};\n\ntemplate <class T>\nstruct lerpfactor_op\n{\n    static T\n    apply(T a, T b, T t)\n    {\n        return IMATH_NAMESPACE::lerpfactor<T>(a,b,t);\n    }\n};\n\ntemplate <class T>\nstruct clamp_op\n{\n    static T\n    apply(T value, T low, T high)\n    {\n        return IMATH_NAMESPACE::clamp<T>(value,low,high);\n    }\n};\n\ntemplate <class T>\nstruct cmp_op\n{\n    static T\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::cmp<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct cmpt_op\n{\n    static T\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::cmpt<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct iszero_op\n{\n    static T\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::iszero<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct equal_op\n{\n    static T\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::equal<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct floor_op\n{\n    static int\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::floor<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct ceil_op\n{\n    static int\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::ceil<T>(value);\n    }\n};\n\ntemplate <class T>\nstruct trunc_op\n{\n    static int\n    apply(T value)\n    {\n        return IMATH_NAMESPACE::trunc<T>(value);\n    }\n};\n\nstruct divs_op\n{\n    static int\n    apply(int x, int y)\n    {\n        return IMATH_NAMESPACE::divs(x,y);\n    }\n};\n\nstruct mods_op\n{\n    static int\n    apply(int x, int y)\n    {\n        return IMATH_NAMESPACE::mods(x,y);\n    }\n};\n\nstruct divp_op\n{\n    static int\n    apply(int x, int y)\n    {\n        return IMATH_NAMESPACE::divp(x,y);\n    }\n};\n\nstruct modp_op\n{\n    static int\n    apply(int x, int y)\n    {\n        return IMATH_NAMESPACE::modp(x,y);\n    }\n};\n\nstruct bias_op\n{\n    static inline float\n    apply(float x, float b)\n    {\n        if (b != 0.5f)\n        {\n            static const float inverse_log_half = 1.0f / std::log(0.5f);\n            const float biasPow = std::log(b)*inverse_log_half;\n            return std::pow(x, biasPow);\n        }\n        return x;\n    }\n};\n\nstruct gain_op\n{\n    static inline float\n    apply(float x, float g)\n    {\n        if (x < 0.5f)\n            return 0.5f*bias_op::apply(2.0f*x, 1.0f - g);\n        else\n            return 1.0f - 0.5f*bias_op::apply(2.0f - 2.0f*x, 1.0f - g);\n    }\n};\n\n} // namespace\n\nvoid register_functions()\n{\n    //\n    // Utility Functions\n    //\n\n    // nb: MSVC gets confused about which arg we want (it thinks it\n    // might be boost::arg), so telling it which one explicitly here.\n    typedef boost::python::arg arg;\n\n    PyImath::generate_bindings<abs_op<int>,boost::mpl::true_>(\n        \"abs\",\n        \"return the absolute value of 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<abs_op<float>,boost::mpl::true_>(\n        \"abs\",\n        \"return the absolute value of 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<abs_op<double>,boost::mpl::true_>(\n        \"abs\",\n        \"return the absolute value of 'value'\",\n        (arg(\"value\")));\n    \n    PyImath::generate_bindings<sign_op<int>,boost::mpl::true_>(\n        \"sign\",\n        \"return 1 or -1 based on the sign of 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<sign_op<float>,boost::mpl::true_>(\n        \"sign\",\n        \"return 1 or -1 based on the sign of 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<sign_op<double>,boost::mpl::true_>(\n        \"sign\",\n        \"return 1 or -1 based on the sign of 'value'\",\n        (arg(\"value\")));\n    \n    PyImath::generate_bindings<log_op<float>,boost::mpl::true_>(\n        \"log\",\n        \"return the natural log of 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<log_op<double>,boost::mpl::true_>(\n        \"log\",\n        \"return the natural log of 'value'\",\n        (arg(\"value\")));\n    \n    PyImath::generate_bindings<log10_op<float>,boost::mpl::true_>(\n        \"log10\",\n        \"return the base 10 log of 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<log10_op<double>,boost::mpl::true_>(\n        \"log10\",\n        \"return the base 10 log of 'value'\",\n        (arg(\"value\")));\n    \n    PyImath::generate_bindings<lerp_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"lerp\",\n        \"return the linear interpolation of 'a' to 'b' using parameter 't'\",\n        (arg(\"a\"),arg(\"b\"),arg(\"t\")));\n    PyImath::generate_bindings<lerp_op<double>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"lerp\",\n        \"return the linear interpolation of 'a' to 'b' using parameter 't'\",\n        (arg(\"a\"),arg(\"b\"),arg(\"t\")));\n    \n    PyImath::generate_bindings<lerpfactor_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"lerpfactor\",\n        \"return how far m is between a and b, that is return t such that\\n\"\n        \"if:\\n\"\n        \"    t = lerpfactor(m, a, b);\\n\"\n        \"then:\\n\"\n        \"    m = lerp(a, b, t);\\n\"\n        \"\\n\"\n        \"If a==b, return 0.\\n\",\n        (arg(\"m\"),arg(\"a\"),arg(\"b\")));\n    PyImath::generate_bindings<lerpfactor_op<double>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"lerpfactor\",\n        \"return how far m is between a and b, that is return t such that\\n\"\n        \"    if:\\n\"\n        \"        t = lerpfactor(m, a, b);\\n\"\n        \"    then:\\n\"\n        \"        m = lerp(a, b, t);\\n\"\n        \"    if a==b, return 0.\\n\",\n        (arg(\"m\"),arg(\"a\"),arg(\"b\")));\n    \n    PyImath::generate_bindings<clamp_op<int>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"clamp\",\n        \"return the value clamped to the range [low,high]\",\n        (arg(\"value\"),arg(\"low\"),arg(\"high\")));\n    PyImath::generate_bindings<clamp_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"clamp\",\n        \"return the value clamped to the range [low,high]\",\n        (arg(\"value\"),arg(\"low\"),arg(\"high\")));\n    PyImath::generate_bindings<clamp_op<double>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"clamp\",\n        \"return the value clamped to the range [low,high]\",\n        (arg(\"value\"),arg(\"low\"),arg(\"high\")));\n\n    def(\"cmp\", IMATH_NAMESPACE::cmp<float>);\n    def(\"cmp\", IMATH_NAMESPACE::cmp<double>);   \n\n    def(\"cmpt\", IMATH_NAMESPACE::cmpt<float>);\n    def(\"cmpt\", IMATH_NAMESPACE::cmpt<double>);\n\n    def(\"iszero\", IMATH_NAMESPACE::iszero<float>);\n    def(\"iszero\", IMATH_NAMESPACE::iszero<double>);\n\n    def(\"equal\", IMATH_NAMESPACE::equal<float, float, float>);\n    def(\"equal\", IMATH_NAMESPACE::equal<double, double, double>);    \n\n    PyImath::generate_bindings<floor_op<float>,boost::mpl::true_>(\n        \"floor\",\n        \"return the closest integer less than or equal to 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<floor_op<double>,boost::mpl::true_>(\n        \"floor\",\n        \"return the closest integer less than or equal to 'value'\",\n        (arg(\"value\")));\n\n    PyImath::generate_bindings<ceil_op<float>,boost::mpl::true_>(\n        \"ceil\",\n        \"return the closest integer greater than or equal to 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<ceil_op<double>,boost::mpl::true_>(\n        \"ceil\",\n        \"return the closest integer greater than or equal to 'value'\",\n        (arg(\"value\")));\n\n    PyImath::generate_bindings<trunc_op<float>,boost::mpl::true_>(\n        \"trunc\",\n        \"return the closest integer with magnitude less than or equal to 'value'\",\n        (arg(\"value\")));\n    PyImath::generate_bindings<trunc_op<double>,boost::mpl::true_>(\n        \"trunc\",\n        \"return the closest integer with magnitude less than or equal to 'value'\",\n        (arg(\"value\")));\n\n    PyImath::generate_bindings<divs_op,boost::mpl::true_,boost::mpl::true_>(\n        \"divs\",\n        \"return x/y where the remainder has the same sign as x:\\n\"\n        \"    divs(x,y) == (abs(x) / abs(y)) * (sign(x) * sign(y))\\n\",\n        (arg(\"x\"),arg(\"y\")));\n    PyImath::generate_bindings<mods_op,boost::mpl::true_,boost::mpl::true_>(\n        \"mods\",\n        \"return x%y where the remainder has the same sign as x:\\n\"\n        \"    mods(x,y) == x - y * divs(x,y)\\n\",\n        (arg(\"x\"),arg(\"y\")));\n\n    PyImath::generate_bindings<divp_op,boost::mpl::true_,boost::mpl::true_>(\n        \"divp\",\n        \"return x/y where the remainder is always positive:\\n\"\n        \"    divp(x,y) == floor (double(x) / double (y))\\n\",\n        (arg(\"x\"),arg(\"y\")));\n    PyImath::generate_bindings<modp_op,boost::mpl::true_,boost::mpl::true_>(\n        \"modp\",\n        \"return x%y where the remainder is always positive:\\n\"\n        \"    modp(x,y) == x - y * divp(x,y)\\n\",\n        (arg(\"x\"),arg(\"y\")));\n\n    PyImath::generate_bindings<bias_op,boost::mpl::true_,boost::mpl::true_>(\n         \"bias\",\n         \"bias(x,b) is a gamma correction that remaps the unit interval such that bias(0.5, b) = b.\",\n         (arg(\"x\"),arg(\"b\")));\n\n    PyImath::generate_bindings<gain_op,boost::mpl::true_,boost::mpl::true_>(\n         \"gain\",\n         \"gain(x,g) is a gamma correction that remaps the unit interval with the property that gain(0.5, g) = 0.5.\\n\"\n         \"The gain function can be thought of as two scaled bias curves forming an 'S' shape in the unit interval.\",\n         (arg(\"x\"),arg(\"g\")));\n\n    //\n    // Vectorized utility functions\n    // \n    PyImath::generate_bindings<rotationXYZWithUpDir_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"rotationXYZWithUpDir\",\n        \"return the XYZ rotation vector that rotates 'fromDir' to 'toDir'\"\n        \"using the up vector 'upDir'\",\n        args(\"fromDir\",\"toDir\",\"upDir\"));\n}\n\n} // namespace PyImath\n\n\n", "meta": {"hexsha": "11f5d21e7eba712008126ecba16827132065a819", "size": 12978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathFun.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/PyImathFun.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/PyImathFun.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": 27.9096774194, "max_line_length": 117, "alphanum_fraction": 0.6004777315, "num_tokens": 3496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.030675800935278864, "lm_q1q2_score": 0.013904170221276609}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, University of Oxford\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 names of the copyright holders 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// Authors: Marlin Strub\n\n#include \"ompl/geometric/planners/informedtrees/AITstar.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <string>\n\n#include <boost/range/adaptor/reversed.hpp>\n\n#include \"ompl/base/objectives/PathLengthOptimizationObjective.h\"\n#include \"ompl/util/Console.h\"\n\nusing namespace std::string_literals;\nusing namespace ompl::geometric::aitstar;\n\nnamespace ompl\n{\n    namespace geometric\n    {\n        AITstar::AITstar(const ompl::base::SpaceInformationPtr &spaceInformation)\n          : ompl::base::Planner(spaceInformation, \"AITstar\")\n          , solutionCost_()\n          , graph_(solutionCost_)\n          , forwardQueue_([this](const auto &lhs, const auto &rhs) { return isEdgeBetter(lhs, rhs); })\n          , reverseQueue_([this](const auto &lhs, const auto &rhs) { return isVertexBetter(lhs, rhs); })\n        {\n            // Specify AIT*'s planner specs.\n            specs_.recognizedGoal = base::GOAL_SAMPLEABLE_REGION;\n            specs_.multithreaded = false;\n            specs_.approximateSolutions = true;\n            specs_.optimizingPaths = true;\n            specs_.directed = true;\n            specs_.provingSolutionNonExistence = false;\n            specs_.canReportIntermediateSolutions = true;\n\n            // Register the setting callbacks.\n            declareParam<bool>(\"use_k_nearest\", this, &AITstar::setUseKNearest, &AITstar::getUseKNearest, \"0,1\");\n            declareParam<double>(\"rewire_factor\", this, &AITstar::setRewireFactor, &AITstar::getRewireFactor,\n                                 \"1.0:0.01:3.0\");\n            declareParam<std::size_t>(\"samples_per_batch\", this, &AITstar::setBatchSize, &AITstar::getBatchSize,\n                                      \"1:1:1000\");\n            declareParam<bool>(\"use_graph_pruning\", this, &AITstar::enablePruning, &AITstar::isPruningEnabled, \"0,1\");\n            declareParam<bool>(\"find_approximate_solutions\", this, &AITstar::trackApproximateSolutions,\n                               &AITstar::areApproximateSolutionsTracked, \"0,1\");\n            declareParam<std::size_t>(\"set_max_num_goals\", this, &AITstar::setMaxNumberOfGoals,\n                                      &AITstar::getMaxNumberOfGoals, \"1:1:1000\");\n\n            // Register the progress properties.\n            addPlannerProgressProperty(\"iterations INTEGER\", [this]() { return std::to_string(numIterations_); });\n            addPlannerProgressProperty(\"best cost DOUBLE\", [this]() { return std::to_string(solutionCost_.value()); });\n            addPlannerProgressProperty(\"state collision checks INTEGER\",\n                                       [this]() { return std::to_string(graph_.getNumberOfStateCollisionChecks()); });\n            addPlannerProgressProperty(\"edge collision checks INTEGER\",\n                                       [this]() { return std::to_string(numEdgeCollisionChecks_); });\n            addPlannerProgressProperty(\"nearest neighbour calls INTEGER\",\n                                       [this]() { return std::to_string(graph_.getNumberOfNearestNeighborCalls()); });\n        }\n\n        void AITstar::setup()\n        {\n            // Call the base-class setup.\n            Planner::setup();\n\n            // Check that a problem definition has been set.\n            if (static_cast<bool>(Planner::pdef_))\n            {\n                // Default to path length optimization objective if none has been specified.\n                if (!pdef_->hasOptimizationObjective())\n                {\n                    OMPL_WARN(\"%s: No optimization objective has been specified. Defaulting to path length.\",\n                              Planner::getName().c_str());\n                    Planner::pdef_->setOptimizationObjective(\n                        std::make_shared<ompl::base::PathLengthOptimizationObjective>(Planner::si_));\n                }\n\n                if (static_cast<bool>(pdef_->getGoal()))\n                {\n                    // If we were given a goal, make sure its of appropriate type.\n                    if (!(pdef_->getGoal()->hasType(ompl::base::GOAL_SAMPLEABLE_REGION)))\n                    {\n                        OMPL_ERROR(\"AIT* is currently only implemented for goals that can be cast to \"\n                                   \"ompl::base::GOAL_SAMPLEABLE_GOAL_REGION.\");\n                        setup_ = false;\n                        return;\n                    }\n                }\n\n                // Pull the optimization objective through the problem definition.\n                objective_ = pdef_->getOptimizationObjective();\n\n                // Initialize the solution cost to be infinite.\n                solutionCost_ = objective_->infiniteCost();\n                approximateSolutionCost_ = objective_->infiniteCost();\n                approximateSolutionCostToGoal_ = objective_->infiniteCost();\n\n                // Pull the motion validator through the space information.\n                motionValidator_ = si_->getMotionValidator();\n\n                // Setup a graph.\n                graph_.setup(si_, pdef_, &pis_);\n            }\n            else\n            {\n                // AIT* can't be setup without a problem definition.\n                setup_ = false;\n                OMPL_WARN(\"AIT*: Unable to setup without a problem definition.\");\n            }\n        }\n\n        ompl::base::PlannerStatus::StatusType AITstar::ensureSetup()\n        {\n            // Call the base planners validity check. This checks if the\n            // planner is setup if not then it calls setup().\n            checkValidity();\n\n            // Ensure the planner is setup.\n            if (!setup_)\n            {\n                OMPL_ERROR(\"%s: The planner is not setup.\", name_.c_str());\n                return ompl::base::PlannerStatus::StatusType::ABORT;\n            }\n\n            // Ensure the space is setup.\n            if (!si_->isSetup())\n            {\n                OMPL_ERROR(\"%s: The space information is not setup.\", name_.c_str());\n                return ompl::base::PlannerStatus::StatusType::ABORT;\n            }\n\n            return ompl::base::PlannerStatus::StatusType::UNKNOWN;\n        }\n\n        ompl::base::PlannerStatus::StatusType\n        AITstar::ensureStartAndGoalStates(const ompl::base::PlannerTerminationCondition &terminationCondition)\n        {\n            // If the graph currently does not have a start state, try to get one.\n            if (!graph_.hasAStartState())\n            {\n                graph_.updateStartAndGoalStates(terminationCondition, &pis_);\n\n                // If we could not get a start state, then there's nothing to solve.\n                if (!graph_.hasAStartState())\n                {\n                    OMPL_WARN(\"%s: No solution can be found as no start states are available\", name_.c_str());\n                    return ompl::base::PlannerStatus::StatusType::INVALID_START;\n                }\n            }\n\n            // If the graph currently does not have a goal state, we wait until we get one.\n            if (!graph_.hasAGoalState())\n            {\n                graph_.updateStartAndGoalStates(terminationCondition, &pis_);\n\n                // If the graph still doesn't have a goal after waiting, then there's nothing to solve.\n                if (!graph_.hasAGoalState())\n                {\n                    OMPL_WARN(\"%s: No solution can be found as no goal states are available\", name_.c_str());\n                    return ompl::base::PlannerStatus::StatusType::INVALID_GOAL;\n                }\n            }\n\n            // Would it be worth implementing a 'setup' or 'checked' status type?\n            return ompl::base::PlannerStatus::StatusType::UNKNOWN;\n        }\n\n        void AITstar::clear()\n        {\n            graph_.clear();\n            forwardQueue_.clear();\n            reverseQueue_.clear();\n            solutionCost_ = objective_->infiniteCost();\n            approximateSolutionCost_ = objective_->infiniteCost();\n            approximateSolutionCostToGoal_ = objective_->infiniteCost();\n            numIterations_ = 0u;\n            numInconsistentOrUnconnectedTargets_ = 0u;\n            Planner::clear();\n            setup_ = false;\n        }\n\n        ompl::base::PlannerStatus AITstar::solve(const ompl::base::PlannerTerminationCondition &terminationCondition)\n        {\n            // Ensure that the planner and state space are setup before solving.\n            auto status = ensureSetup();\n\n            // Return early if the planner or state space are not setup.\n            if (status == ompl::base::PlannerStatus::StatusType::ABORT)\n            {\n                return status;\n            }\n\n            // Ensure that the problem has start and goal states before solving.\n            status = ensureStartAndGoalStates(terminationCondition);\n\n            // Return early if the problem cannot be solved.\n            if (status == ompl::base::PlannerStatus::StatusType::INVALID_START ||\n                status == ompl::base::PlannerStatus::StatusType::INVALID_GOAL)\n            {\n                return status;\n            }\n\n            OMPL_INFORM(\"%s: Solving the given planning problem. The current best solution cost is %.4f\", name_.c_str(),\n                        solutionCost_.value());\n\n            // Iterate to solve the problem.\n            while (!terminationCondition && !objective_->isSatisfied(solutionCost_))\n            {\n                iterate(terminationCondition);\n            }\n\n            // Someone might call ProblemDefinition::clearSolutionPaths() between invocations of Planner::sovle(), in\n            // which case previously found solutions are not registered with the problem definition anymore.\n            status = updateSolution();\n\n            // Let the caller know the status.\n            informAboutPlannerStatus(status);\n            return status;\n        }\n\n        ompl::base::Cost AITstar::bestCost() const\n        {\n            return solutionCost_;\n        }\n\n        void AITstar::getPlannerData(base::PlannerData &data) const\n        {\n            // base::PlannerDataVertex takes a raw pointer to a state. I want to guarantee, that the state lives as\n            // long as the program lives.\n            static std::set<std::shared_ptr<Vertex>,\n                            std::function<bool(const std::shared_ptr<Vertex> &, const std::shared_ptr<Vertex> &)>>\n                liveStates([](const auto &lhs, const auto &rhs) { return lhs->getId() < rhs->getId(); });\n\n            // Fill the planner progress properties.\n            Planner::getPlannerData(data);\n\n            // Get the vertices.\n            auto vertices = graph_.getVertices();\n\n            // Add the vertices and edges.\n            for (const auto &vertex : vertices)\n            {\n                // Add the vertex to the live states.\n                liveStates.insert(vertex);\n\n                // Add the vertex as the right kind of vertex.\n                if (graph_.isStart(vertex))\n                {\n                    data.addStartVertex(ompl::base::PlannerDataVertex(vertex->getState(), vertex->getId()));\n                }\n                else if (graph_.isGoal(vertex))\n                {\n                    data.addGoalVertex(ompl::base::PlannerDataVertex(vertex->getState(), vertex->getId()));\n                }\n                else\n                {\n                    data.addVertex(ompl::base::PlannerDataVertex(vertex->getState(), vertex->getId()));\n                }\n\n                // If it has a parent, add the corresponding edge.\n                if (vertex->hasForwardParent())\n                {\n                    data.addEdge(ompl::base::PlannerDataVertex(vertex->getState(), vertex->getId()),\n                                 ompl::base::PlannerDataVertex(vertex->getForwardParent()->getState(),\n                                                               vertex->getForwardParent()->getId()));\n                }\n            }\n        }\n\n        void AITstar::setBatchSize(std::size_t batchSize)\n        {\n            batchSize_ = batchSize;\n        }\n\n        std::size_t AITstar::getBatchSize() const\n        {\n            return batchSize_;\n        }\n\n        void AITstar::setRewireFactor(double rewireFactor)\n        {\n            graph_.setRewireFactor(rewireFactor);\n        }\n\n        double AITstar::getRewireFactor() const\n        {\n            return graph_.getRewireFactor();\n        }\n\n        void AITstar::trackApproximateSolutions(bool track)\n        {\n            trackApproximateSolutions_ = track;\n            if (!trackApproximateSolutions_)\n            {\n                if (static_cast<bool>(objective_))\n                {\n                    approximateSolutionCost_ = objective_->infiniteCost();\n                    approximateSolutionCostToGoal_ = objective_->infiniteCost();\n                }\n            }\n        }\n\n        bool AITstar::areApproximateSolutionsTracked() const\n        {\n            return trackApproximateSolutions_;\n        }\n\n        void AITstar::enablePruning(bool prune)\n        {\n            isPruningEnabled_ = prune;\n        }\n\n        bool AITstar::isPruningEnabled() const\n        {\n            return isPruningEnabled_;\n        }\n\n        void AITstar::setUseKNearest(bool useKNearest)\n        {\n            graph_.setUseKNearest(useKNearest);\n        }\n\n        bool AITstar::getUseKNearest() const\n        {\n            return graph_.getUseKNearest();\n        }\n\n        void AITstar::setMaxNumberOfGoals(unsigned int numberOfGoals)\n        {\n            graph_.setMaxNumberOfGoals(numberOfGoals);\n        }\n\n        unsigned int AITstar::getMaxNumberOfGoals() const\n        {\n            return graph_.getMaxNumberOfGoals();\n        }\n\n        void AITstar::rebuildForwardQueue()\n        {\n            // Get all edges from the queue.\n            std::vector<Edge> edges;\n            forwardQueue_.getContent(edges);\n\n            // Rebuilding the queue invalidates the incoming and outgoing lookup.\n            for (const auto &edge : edges)\n            {\n                edge.getChild()->resetForwardQueueIncomingLookup();\n                edge.getParent()->resetForwardQueueOutgoingLookup();\n            }\n\n            // Clear the queue.\n            forwardQueue_.clear();\n            numInconsistentOrUnconnectedTargets_ = 0u;\n\n            // Insert all edges into the queue if they connect vertices that have been processed, otherwise store\n            // them in the cache of edges that are to be inserted.\n            for (auto &edge : edges)\n            {\n                insertOrUpdateInForwardQueue(\n                    Edge(edge.getParent(), edge.getChild(), computeSortKey(edge.getParent(), edge.getChild())));\n            }\n        }\n\n        void AITstar::clearForwardQueue()\n        {\n            std::vector<Edge> forwardQueue;\n            forwardQueue_.getContent(forwardQueue);\n            for (const auto &element : forwardQueue)\n            {\n                element.getChild()->resetForwardQueueIncomingLookup();\n                element.getParent()->resetForwardQueueOutgoingLookup();\n            }\n            forwardQueue_.clear();\n            numInconsistentOrUnconnectedTargets_ = 0u;\n        }\n\n        void AITstar::rebuildReverseQueue()\n        {\n            // Rebuilding the reverse queue invalidates the reverse queue pointers.\n            std::vector<aitstar::KeyVertexPair> content;\n            reverseQueue_.getContent(content);\n            for (auto &element : content)\n            {\n                element.second->resetReverseQueuePointer();\n            }\n            reverseQueue_.clear();\n\n            for (auto &vertex : content)\n            {\n                // Compute the sort key for the vertex queue.\n                std::pair<std::array<ompl::base::Cost, 2u>, std::shared_ptr<Vertex>> element(\n                    computeSortKey(vertex.second), vertex.second);\n                auto reverseQueuePointer = reverseQueue_.insert(element);\n                element.second->setReverseQueuePointer(reverseQueuePointer);\n            }\n        }\n\n        void AITstar::clearReverseQueue()\n        {\n            std::vector<aitstar::KeyVertexPair> reverseQueue;\n            reverseQueue_.getContent(reverseQueue);\n            for (const auto &element : reverseQueue)\n            {\n                element.second->resetReverseQueuePointer();\n            }\n            reverseQueue_.clear();\n        }\n\n        void AITstar::informAboutNewSolution() const\n        {\n            OMPL_INFORM(\"%s (%u iterations): Found a new exact solution of cost %.4f. Sampled a total of %u states, %u \"\n                        \"of which were valid samples (%.1f \\%). Processed %u edges, %u of which were collision checked \"\n                        \"(%.1f \\%). The forward search tree has %u vertices, %u of which are start states. The reverse \"\n                        \"search tree has %u vertices, %u of which are goal states.\",\n                        name_.c_str(), numIterations_, solutionCost_.value(), graph_.getNumberOfSampledStates(),\n                        graph_.getNumberOfValidSamples(),\n                        graph_.getNumberOfSampledStates() == 0u ?\n                            0.0 :\n                            100.0 * (static_cast<double>(graph_.getNumberOfValidSamples()) /\n                                     static_cast<double>(graph_.getNumberOfSampledStates())),\n                        numProcessedEdges_, numEdgeCollisionChecks_,\n                        numProcessedEdges_ == 0u ? 0.0 :\n                                                   100.0 * (static_cast<float>(numEdgeCollisionChecks_) /\n                                                            static_cast<float>(numProcessedEdges_)),\n                        countNumVerticesInForwardTree(), graph_.getStartVertices().size(),\n                        countNumVerticesInReverseTree(), graph_.getGoalVertices().size());\n        }\n\n        void AITstar::informAboutPlannerStatus(ompl::base::PlannerStatus::StatusType status) const\n        {\n            switch (status)\n            {\n                case ompl::base::PlannerStatus::StatusType::EXACT_SOLUTION:\n                {\n                    OMPL_INFORM(\"%s (%u iterations): Found an exact solution of cost %.4f.\", name_.c_str(),\n                                numIterations_, solutionCost_.value());\n                    break;\n                }\n                case ompl::base::PlannerStatus::StatusType::APPROXIMATE_SOLUTION:\n                {\n                    OMPL_INFORM(\"%s (%u iterations): Did not find an exact solution, but found an approximate \"\n                                \"solution \"\n                                \"of cost %.4f which is %.4f away from a goal (in cost space).\",\n                                name_.c_str(), numIterations_, approximateSolutionCost_.value(),\n                                approximateSolutionCostToGoal_.value());\n                    break;\n                }\n                case ompl::base::PlannerStatus::StatusType::TIMEOUT:\n                {\n                    if (trackApproximateSolutions_)\n                    {\n                        OMPL_INFORM(\"%s (%u iterations): Did not find any solution.\", name_.c_str(), numIterations_);\n                    }\n                    else\n                    {\n                        OMPL_INFORM(\"%s (%u iterations): Did not find an exact solution, and tracking approximate \"\n                                    \"solutions is disabled.\",\n                                    name_.c_str(), numIterations_);\n                    }\n                    break;\n                }\n                case ompl::base::PlannerStatus::StatusType::UNKNOWN:\n                case ompl::base::PlannerStatus::StatusType::INVALID_START:\n                case ompl::base::PlannerStatus::StatusType::INVALID_GOAL:\n                case ompl::base::PlannerStatus::StatusType::UNRECOGNIZED_GOAL_TYPE:\n                case ompl::base::PlannerStatus::StatusType::CRASH:\n                case ompl::base::PlannerStatus::StatusType::ABORT:\n                case ompl::base::PlannerStatus::StatusType::TYPE_COUNT:\n                {\n                    OMPL_INFORM(\"%s (%u iterations): Unable to solve the given planning problem.\", name_.c_str(),\n                                numIterations_);\n                }\n            }\n\n            OMPL_INFORM(\n                \"%s (%u iterations): Sampled a total of %u states, %u of which were valid samples (%.1f \\%). \"\n                \"Processed %u edges, %u of which were collision checked (%.1f \\%). The forward search tree \"\n                \"has %u vertices. The reverse search tree has %u vertices.\",\n                name_.c_str(), numIterations_, graph_.getNumberOfSampledStates(), graph_.getNumberOfValidSamples(),\n                graph_.getNumberOfSampledStates() == 0u ?\n                    0.0 :\n                    100.0 * (static_cast<double>(graph_.getNumberOfValidSamples()) /\n                             static_cast<double>(graph_.getNumberOfSampledStates())),\n                numProcessedEdges_, numEdgeCollisionChecks_,\n                numProcessedEdges_ == 0u ?\n                    0.0 :\n                    100.0 * (static_cast<float>(numEdgeCollisionChecks_) / static_cast<float>(numProcessedEdges_)),\n                countNumVerticesInForwardTree(), countNumVerticesInReverseTree());\n        }\n\n        void AITstar::insertGoalVerticesInReverseQueue()\n        {\n            for (const auto &goal : graph_.getGoalVertices())\n            {\n                // Set the cost to come from the goal to identity and the expanded cost to infinity.\n                goal->setExpandedCostToComeFromGoal(objective_->infiniteCost());\n                goal->setCostToComeFromGoal(objective_->identityCost());\n\n                // Create an element for the queue.\n                aitstar::KeyVertexPair element({computeCostToGoToStartHeuristic(goal), objective_->identityCost()},\n                                               goal);\n\n                // Insert the element into the queue and set the corresponding pointer.\n                auto reverseQueuePointer = reverseQueue_.insert(element);\n                goal->setReverseQueuePointer(reverseQueuePointer);\n            }\n        }\n\n        void AITstar::expandStartVerticesIntoForwardQueue()\n        {\n            for (const auto &start : graph_.getStartVertices())\n            {\n                start->setCostToComeFromStart(objective_->identityCost());\n                insertOrUpdateInForwardQueue(getOutgoingEdges(start));\n            }\n        }\n\n        bool AITstar::continueReverseSearch() const\n        {\n            // Never continue the reverse search if the reverse of forward queue is empty.\n            if (reverseQueue_.empty() || forwardQueue_.empty())\n            {\n                return false;\n            }\n\n            // Get references to the best edge and vertex in the queues.\n            const auto &bestEdge = forwardQueue_.top()->data;\n            const auto &bestVertex = reverseQueue_.top()->data;\n\n            // The reverse search must be continued if the best edge has an inconsistent child state or if the best\n            // vertex can potentially lead to a better solution than the best edge.\n            return !((bestEdge.getChild()->isConsistent() &&\n                      objective_->isCostBetterThan(bestEdge.getSortKey()[0u], bestVertex.first[0u])) ||\n                     numInconsistentOrUnconnectedTargets_ == 0u);\n        }\n\n        bool AITstar::continueForwardSearch()\n        {\n            // Never continue the forward search if its queue is empty.\n            if (forwardQueue_.empty())\n            {\n                return false;\n            }\n\n            // If the best edge in the forward queue has a potential total solution cost of infinity, the forward\n            // search does not need to be continued. This can happen if the reverse search did not reach any target\n            // state of the edges in the forward queue.\n            const auto &bestEdgeCost = forwardQueue_.top()->data.getSortKey()[0u];\n            if (!objective_->isFinite(bestEdgeCost))\n            {\n                return false;\n            }\n\n            // The forward search can be stopped once the resolution optimal solution has been found.\n            return objective_->isCostBetterThan(bestEdgeCost, solutionCost_);\n        }\n\n        std::vector<Edge> AITstar::getEdgesInQueue() const\n        {\n            std::vector<Edge> edges;\n            forwardQueue_.getContent(edges);\n            return edges;\n        }\n\n        std::vector<std::shared_ptr<Vertex>> AITstar::getVerticesInQueue() const\n        {\n            // Get the content from the queue.\n            std::vector<std::pair<std::array<ompl::base::Cost, 2u>, std::shared_ptr<Vertex>>> content;\n            reverseQueue_.getContent(content);\n\n            // Return the vertices.\n            std::vector<std::shared_ptr<Vertex>> vertices;\n            for (const auto &pair : content)\n            {\n                vertices.emplace_back(pair.second);\n            }\n            return vertices;\n        }\n\n        Edge AITstar::getNextEdgeInQueue() const\n        {\n            if (!forwardQueue_.empty())\n            {\n                return forwardQueue_.top()->data;\n            }\n\n            return {};\n        }\n\n        std::shared_ptr<Vertex> AITstar::getNextVertexInQueue() const\n        {\n            if (!reverseQueue_.empty())\n            {\n                return reverseQueue_.top()->data.second;\n            }\n\n            return {};\n        }\n\n        std::vector<std::shared_ptr<Vertex>> AITstar::getVerticesInReverseSearchTree() const\n        {\n            // Get all vertices from the graph.\n            auto vertices = graph_.getVertices();\n\n            // Erase the vertices that are not in the reverse search tree.\n            vertices.erase(std::remove_if(vertices.begin(), vertices.end(),\n                                          [this](const std::shared_ptr<Vertex> &vertex) {\n                                              return !graph_.isGoal(vertex) && !vertex->hasReverseParent();\n                                          }),\n                           vertices.end());\n            return vertices;\n        }\n\n        void AITstar::iterate(const ompl::base::PlannerTerminationCondition &terminationCondition)\n        {\n            // If this is the first time solve is called, populate the queues.\n            if (numIterations_ == 0u)\n            {\n                insertGoalVerticesInReverseQueue();\n                expandStartVerticesIntoForwardQueue();\n            }\n\n            // Keep track of the number of iterations.\n            ++numIterations_;\n\n            // If the reverse search needs to be continued, do that now.\n            if (continueReverseSearch())\n            {\n                iterateReverseSearch();\n            }  // If the reverse search is suspended, check whether the forward search needs to be continued.\n            else if (continueForwardSearch())\n            {\n                iterateForwardSearch();\n            }  // If neither the forward search nor the reverse search needs to be continued, add more samples.\n            else\n            {\n                // Add new samples to the graph, respecting the termination condition.\n                if (graph_.addSamples(batchSize_, terminationCondition))\n                {\n                    // Remove useless samples from the graph.\n                    if (isPruningEnabled_)\n                    {\n                        graph_.prune();\n                    }\n\n                    // Clear the reverse search tree.\n                    for (auto &goal : graph_.getGoalVertices())\n                    {\n                        invalidateCostToComeFromGoalOfReverseBranch(goal);\n                    }\n\n                    // Add new start and goal states if necessary.\n                    if (pis_.haveMoreStartStates() || pis_.haveMoreGoalStates())\n                    {\n                        graph_.updateStartAndGoalStates(ompl::base::plannerAlwaysTerminatingCondition(), &pis_);\n                    }\n\n                    // Reinitialize the queues.\n                    clearReverseQueue();\n                    clearForwardQueue();\n                    insertGoalVerticesInReverseQueue();\n                    expandStartVerticesIntoForwardQueue();\n                }\n            }\n        }\n\n        void AITstar::iterateForwardSearch()\n        {\n            assert(!forwardQueue_.empty());\n\n            // Get the most promising edge.\n            auto parent = forwardQueue_.top()->data.getParent();\n            auto child = forwardQueue_.top()->data.getChild();\n            child->removeFromForwardQueueIncomingLookup(forwardQueue_.top());\n            parent->removeFromForwardQueueOutgoingLookup(forwardQueue_.top());\n            forwardQueue_.pop();\n\n            // Ensure that the child is consistent and the parent isn't the goal.\n            assert(child->isConsistent());\n            assert(!graph_.isGoal(parent));\n\n            // This counts as processing an edge.\n            ++numProcessedEdges_;\n\n            // If this edge is already in the forward tree, it's a freeby.\n            if (child->hasForwardParent() && child->getForwardParent()->getId() == parent->getId())\n            {\n                insertOrUpdateInForwardQueue(getOutgoingEdges(child));\n                return;\n            }  // Check if this edge can possibly improve the current search tree.\n            else if (objective_->isCostBetterThan(objective_->combineCosts(parent->getCostToComeFromStart(),\n                                                                           objective_->motionCostHeuristic(\n                                                                               parent->getState(), child->getState())),\n                                                  child->getCostToComeFromStart()))\n            {\n                // The edge can possibly improve the solution and the path to the child. Let's check it for\n                // collision.\n                if (parent->isWhitelistedAsChild(child) ||\n                    motionValidator_->checkMotion(parent->getState(), child->getState()))\n                {\n                    // Remember that this is a good edge.\n                    if (!parent->isWhitelistedAsChild(child))\n                    {\n                        parent->whitelistAsChild(child);\n                        numEdgeCollisionChecks_++;\n                    }\n\n                    // Compute the edge cost.\n                    const auto edgeCost = objective_->motionCost(parent->getState(), child->getState());\n\n                    // Check if the edge can improve the cost to come to the child.\n                    if (objective_->isCostBetterThan(\n                            objective_->combineCosts(parent->getCostToComeFromStart(), edgeCost),\n                            child->getCostToComeFromStart()))\n                    {\n                        // Rewire the child.\n                        child->setForwardParent(parent, edgeCost);\n\n                        // Add it to the children of the parent.\n                        parent->addToForwardChildren(child);\n\n                        // Share the good news with the whole branch.\n                        child->updateCostOfForwardBranch();\n\n                        // Check if the solution can benefit from this.\n                        updateSolution(child);\n\n                        // Insert the child's outgoing edges into the queue.\n                        insertOrUpdateInForwardQueue(getOutgoingEdges(child));\n                    }\n                }\n                else  // This edge is in collision\n                {\n                    // The edge should be blacklisted in both directions.\n                    parent->blacklistAsChild(child);\n                    child->blacklistAsChild(parent);\n\n                    // Repair the reverse search if this edge was in the reverse search tree.\n                    if (parent->hasReverseParent() && parent->getReverseParent()->getId() == child->getId())\n                    {\n                        // The parent was connected to the child through an invalid edge, so we need to invalidate\n                        // the branch of the reverse search tree starting from the parent.\n                        invalidateCostToComeFromGoalOfReverseBranch(parent);\n                    }\n                }\n            }\n        }\n\n        void AITstar::iterateReverseSearch()\n        {\n            assert(!reverseQueue_.empty());\n\n            // Get the most promising vertex and remove it from the queue.\n            auto vertex = reverseQueue_.top()->data.second;\n            reverseQueue_.pop();\n            vertex->resetReverseQueuePointer();\n\n            // The open queue should not contain consistent vertices.\n            assert(!vertex->isConsistent());\n\n            // Check if the vertex is underconsistent. g[s] < v[s].\n            if (objective_->isCostBetterThan(vertex->getCostToComeFromGoal(), vertex->getExpandedCostToComeFromGoal()))\n            {\n                // Make the vertex consistent and update the vertex.\n                vertex->setExpandedCostToComeFromGoal(vertex->getCostToComeFromGoal());\n                updateReverseSearchNeighbors(vertex);\n\n                // Update the number of inconsistent targets in the forward queue.\n                numInconsistentOrUnconnectedTargets_ -= vertex->getForwardQueueIncomingLookup().size();\n            }\n            else\n            {\n                // Make the vertex overconsistent.\n                vertex->setExpandedCostToComeFromGoal(objective_->infiniteCost());\n\n                // Update the vertex and its neighbors.\n                updateReverseSearchVertex(vertex);\n                updateReverseSearchNeighbors(vertex);\n            }\n        }\n\n        bool AITstar::isEdgeBetter(const Edge &lhs, const Edge &rhs) const\n        {\n            return std::lexicographical_compare(\n                lhs.getSortKey().cbegin(), lhs.getSortKey().cend(), rhs.getSortKey().cbegin(), rhs.getSortKey().cend(),\n                [this](const auto &a, const auto &b) { return objective_->isCostBetterThan(a, b); });\n        }\n\n        bool AITstar::isVertexBetter(const aitstar::KeyVertexPair &lhs, const aitstar::KeyVertexPair &rhs) const\n        {\n            // If the costs of two vertices are equal then we prioritize inconsistent vertices that are targets of\n            // edges in the forward queue.\n            if (objective_->isCostEquivalentTo(lhs.first[0u], rhs.first[0u]) &&\n                objective_->isCostEquivalentTo(lhs.first[1u], rhs.first[1u]))\n            {\n                return !lhs.second->getForwardQueueIncomingLookup().empty() && !lhs.second->isConsistent();\n            }\n            else\n            {\n                // Otherwise it's a regular lexicographical comparison of the keys.\n                return std::lexicographical_compare(\n                    lhs.first.cbegin(), lhs.first.cend(), rhs.first.cbegin(), rhs.first.cend(),\n                    [this](const auto &a, const auto &b) { return objective_->isCostBetterThan(a, b); });\n            }\n        }\n\n        void AITstar::updateReverseSearchVertex(const std::shared_ptr<Vertex> &vertex)\n        {\n            // If the vertex is a goal, there's no updating to do.\n            if (graph_.isGoal(vertex))\n            {\n                assert(objective_->isCostEquivalentTo(vertex->getCostToComeFromGoal(), objective_->identityCost()));\n                return;\n            }\n\n            // Get the best parent for this vertex.\n            auto bestParent = vertex->getReverseParent();\n            auto bestCost = vertex->hasReverseParent() ? vertex->getCostToComeFromGoal() : objective_->infiniteCost();\n\n            // Check all neighbors as defined by the RGG.\n            for (const auto &neighbor : graph_.getNeighbors(vertex))\n            {\n                if (neighbor->getId() != vertex->getId() && !neighbor->isBlacklistedAsChild(vertex) &&\n                    !vertex->isBlacklistedAsChild(neighbor))\n                {\n                    auto edgeCost = objective_->motionCostHeuristic(neighbor->getState(), vertex->getState());\n                    auto parentCost = objective_->combineCosts(neighbor->getExpandedCostToComeFromGoal(), edgeCost);\n                    if (objective_->isCostBetterThan(parentCost, bestCost))\n                    {\n                        bestParent = neighbor;\n                        bestCost = parentCost;\n                    }\n                }\n            }\n\n            // Check all children this vertex holds in the forward search.\n            for (const auto &forwardChild : vertex->getForwardChildren())\n            {\n                auto edgeCost = objective_->motionCostHeuristic(forwardChild->getState(), vertex->getState());\n                auto parentCost = objective_->combineCosts(forwardChild->getExpandedCostToComeFromGoal(), edgeCost);\n\n                if (objective_->isCostBetterThan(parentCost, bestCost))\n                {\n                    bestParent = forwardChild;\n                    bestCost = parentCost;\n                }\n            }\n\n            // Check the parent of this vertex in the forward search.\n            if (vertex->hasForwardParent())\n            {\n                auto forwardParent = vertex->getForwardParent();\n                auto edgeCost = objective_->motionCostHeuristic(forwardParent->getState(), vertex->getState());\n                auto parentCost = objective_->combineCosts(forwardParent->getExpandedCostToComeFromGoal(), edgeCost);\n\n                if (objective_->isCostBetterThan(parentCost, bestCost))\n                {\n                    bestParent = forwardParent;\n                    bestCost = parentCost;\n                }\n            }\n\n            // Set the best cost as the cost-to-come from the goal.\n            vertex->setCostToComeFromGoal(bestCost);\n\n            // What happens next depends on whether the vertex is disconnected or not.\n            if (objective_->isFinite(bestCost))\n            {\n                // The vertex is connected. Update the reverse parent.\n                vertex->setReverseParent(bestParent);\n                bestParent->addToReverseChildren(vertex);\n            }\n            else\n            {\n                // This vertex is now orphaned. Reset the reverse parent if the vertex had one.\n                if (vertex->hasReverseParent())\n                {\n                    vertex->getReverseParent()->removeFromReverseChildren(vertex->getId());\n                    vertex->resetReverseParent();\n                }\n            }\n\n            // If this has made the vertex inconsistent, insert or update it in the open queue.\n            if (!vertex->isConsistent())\n            {\n                insertOrUpdateInReverseQueue(vertex);\n            }\n            else  // Remove this vertex from the queue if it is in the queue if it is consistent.\n            {\n                auto reverseQueuePointer = vertex->getReverseQueuePointer();\n                if (reverseQueuePointer)\n                {\n                    reverseQueue_.remove(reverseQueuePointer);\n                    vertex->resetReverseQueuePointer();\n                }\n            }\n\n            // This vertex now has a changed cost-to-come in the reverse search. All edges in the forward queue that\n            // have this vertex as a target must be updated. This cannot be delayed, as whether the reverse search\n            // can be suspended depends on the best edge in the forward queue.\n            for (const auto &element : vertex->getForwardQueueIncomingLookup())\n            {\n                auto &edge = element->data;\n                edge.setSortKey(computeSortKey(edge.getParent(), edge.getChild()));\n                forwardQueue_.update(element);\n            }\n        }\n\n        void AITstar::updateReverseSearchNeighbors(const std::shared_ptr<Vertex> &vertex)\n        {\n            // Start with the reverse search children, because if this vertex becomes the parent of a neighbor, that\n            // neighbor would be updated again as part of the reverse children.\n            for (const auto &child : vertex->getReverseChildren())\n            {\n                updateReverseSearchVertex(child);\n            }\n\n            // We can now process the neighbors.\n            for (const auto &neighbor : graph_.getNeighbors(vertex))\n            {\n                if (neighbor->getId() != vertex->getId() && !neighbor->isBlacklistedAsChild(vertex) &&\n                    !vertex->isBlacklistedAsChild(neighbor))\n                {\n                    updateReverseSearchVertex(neighbor);\n                }\n            }\n\n            // We also need to update the forward search children.\n            for (const auto &child : vertex->getForwardChildren())\n            {\n                updateReverseSearchVertex(child);\n            }\n\n            // We also need to update the forward search parent if it exists.\n            if (vertex->hasForwardParent())\n            {\n                updateReverseSearchVertex(vertex->getForwardParent());\n            }\n        }\n\n        void AITstar::insertOrUpdateInReverseQueue(const std::shared_ptr<Vertex> &vertex)\n        {\n            // Get the pointer to the element in the queue.\n            auto element = vertex->getReverseQueuePointer();\n\n            // Update it if it is in the queue.\n            if (element)\n            {\n                element->data.first = computeSortKey(vertex);\n                reverseQueue_.update(element);\n            }\n            else  // Insert it into the queue otherwise.\n            {\n                // Compute the sort key for the vertex queue.\n                std::pair<std::array<ompl::base::Cost, 2u>, std::shared_ptr<Vertex>> element(computeSortKey(vertex),\n                                                                                             vertex);\n\n                // Insert the vertex into the queue, storing the corresponding pointer.\n                auto reverseQueuePointer = reverseQueue_.insert(element);\n                vertex->setReverseQueuePointer(reverseQueuePointer);\n            }\n        }\n\n        void AITstar::insertOrUpdateInForwardQueue(const Edge &edge)\n        {\n            // Check if the edge is already in the queue and can be updated.\n            const auto lookup = edge.getChild()->getForwardQueueIncomingLookup();\n            const auto it = std::find_if(lookup.begin(), lookup.end(), [&edge](const auto element) {\n                return element->data.getParent()->getId() == edge.getParent()->getId();\n            });\n\n            if (it != lookup.end())\n            {\n                // We used the incoming lookup of the child. Assert that it is already in the outgoing lookup of the\n                // parent.\n                assert(std::find_if(edge.getParent()->getForwardQueueOutgoingLookup().begin(),\n                                    edge.getParent()->getForwardQueueOutgoingLookup().end(),\n                                    [&edge](const auto element) {\n                                        return element->data.getChild()->getId() == edge.getChild()->getId();\n                                    }) != edge.getParent()->getForwardQueueOutgoingLookup().end());\n\n                // This edge exists in the queue. If the new sort key is better than the old, we update it.\n                if (isEdgeBetter(edge, (*it)->data))\n                {\n                    (*it)->data.setSortKey(edge.getSortKey());\n                    forwardQueue_.update(*it);\n                }\n            }\n            else\n            {\n                auto element = forwardQueue_.insert(edge);\n                edge.getParent()->addToForwardQueueOutgoingLookup(element);\n                edge.getChild()->addToForwardQueueIncomingLookup(element);\n\n                // Incement the counter if the target is inconsistent.\n                if (!edge.getChild()->isConsistent() || !objective_->isFinite(edge.getChild()->getCostToComeFromGoal()))\n                {\n                    ++numInconsistentOrUnconnectedTargets_;\n                }\n            }\n        }\n\n        void AITstar::insertOrUpdateInForwardQueue(const std::vector<Edge> &edges)\n        {\n            for (const auto &edge : edges)\n            {\n                insertOrUpdateInForwardQueue(edge);\n            }\n        }\n\n        std::shared_ptr<ompl::geometric::PathGeometric>\n        AITstar::getPathToVertex(const std::shared_ptr<Vertex> &vertex) const\n        {\n            // Create the reverse path by following the parents to the start.\n            std::vector<std::shared_ptr<Vertex>> reversePath;\n            auto current = vertex;\n            while (!graph_.isStart(current))\n            {\n                reversePath.emplace_back(current);\n                current = current->getForwardParent();\n            }\n            reversePath.emplace_back(current);\n\n            // Reverse the reverse path to get the forward path.\n            auto path = std::make_shared<ompl::geometric::PathGeometric>(Planner::si_);\n            for (const auto &vertex : boost::adaptors::reverse(reversePath))\n            {\n                path->append(vertex->getState());\n            }\n\n            return path;\n        }\n\n        std::array<ompl::base::Cost, 3u> AITstar::computeSortKey(const std::shared_ptr<Vertex> &parent,\n                                                                 const std::shared_ptr<Vertex> &child) const\n        {\n            // Compute the sort key [g_T(start) + c_hat(start, neighbor) + h_hat(neighbor), g_T(start) +\n            // c_hat(start, neighbor), g_T(start)].\n            ompl::base::Cost edgeCostHeuristic = objective_->motionCostHeuristic(parent->getState(), child->getState());\n            return {\n                objective_->combineCosts(objective_->combineCosts(parent->getCostToComeFromStart(), edgeCostHeuristic),\n                                         child->getCostToGoToGoal()),\n                objective_->combineCosts(edgeCostHeuristic, child->getCostToGoToGoal()),\n                parent->getCostToComeFromStart()};\n        }\n\n        std::array<ompl::base::Cost, 2u> AITstar::computeSortKey(const std::shared_ptr<Vertex> &vertex) const\n        {\n            // LPA* sort key is [min(g(x), v(x)) + h(x); min(g(x), v(x))].\n            return {objective_->combineCosts(objective_->betterCost(vertex->getCostToComeFromGoal(),\n                                                                    vertex->getExpandedCostToComeFromGoal()),\n                                             computeCostToGoToStartHeuristic(vertex)),\n                    objective_->betterCost(vertex->getCostToComeFromGoal(), vertex->getExpandedCostToComeFromGoal())};\n        }\n\n        std::vector<Edge> AITstar::getOutgoingEdges(const std::shared_ptr<Vertex> &vertex) const\n        {\n            // Prepare the return variable.\n            std::vector<Edge> outgoingEdges;\n\n            // Insert the edges to the current children.\n            for (const auto &child : vertex->getForwardChildren())\n            {\n                outgoingEdges.emplace_back(vertex, child, computeSortKey(vertex, child));\n            }\n\n            // Insert the edges to the current neighbors.\n            for (const auto &neighbor : graph_.getNeighbors(vertex))\n            {\n                // We do not want self loops.\n                if (vertex->getId() == neighbor->getId())\n                {\n                    continue;\n                }\n\n                // If the neighbor is the reverse parent, it will explicitly be added later.\n                if (vertex->hasReverseParent() && neighbor->getId() == vertex->getReverseParent()->getId())\n                {\n                    continue;\n                }\n\n                // We do not want blacklisted edges.\n                if (neighbor->isBlacklistedAsChild(vertex) || vertex->isBlacklistedAsChild(neighbor))\n                {\n                    continue;\n                }\n\n                // If none of the above tests caught on, we can insert the edge.\n                outgoingEdges.emplace_back(vertex, neighbor, computeSortKey(vertex, neighbor));\n            }\n\n            // Insert the edge to the reverse search parent.\n            if (vertex->hasReverseParent())\n            {\n                const auto &reverseParent = vertex->getReverseParent();\n                outgoingEdges.emplace_back(vertex, reverseParent, computeSortKey(vertex, reverseParent));\n            }\n\n            return outgoingEdges;\n        }\n\n        void AITstar::updateExactSolution()\n        {\n            // Check if any of the goals have a cost to come less than the current solution cost.\n            for (const auto &goal : graph_.getGoalVertices())\n            {\n                // We need to check whether the cost is better, or whether someone has removed the exact solution\n                // from the problem definition.\n                if (objective_->isCostBetterThan(goal->getCostToComeFromStart(), solutionCost_) ||\n                    (!pdef_->hasExactSolution() && objective_->isFinite(goal->getCostToComeFromStart())))\n                {\n                    // Remember the incumbent cost.\n                    solutionCost_ = goal->getCostToComeFromStart();\n\n                    // Create a solution.\n                    ompl::base::PlannerSolution solution(getPathToVertex(goal));\n                    solution.setPlannerName(name_);\n\n                    // Set the optimized flag.\n                    solution.setOptimized(objective_, solutionCost_, objective_->isSatisfied(solutionCost_));\n\n                    // Let the problem definition know that a new solution exists.\n                    pdef_->addSolutionPath(solution);\n\n                    // Let the user know about the new solution.\n                    informAboutNewSolution();\n                }\n            }\n        }\n\n        void AITstar::updateApproximateSolution()\n        {\n            for (auto &start : graph_.getStartVertices())\n            {\n                start->callOnForwardBranch([this](const auto &vertex) -> void { updateApproximateSolution(vertex); });\n            }\n        }\n\n        void AITstar::updateApproximateSolution(const std::shared_ptr<Vertex> &vertex)\n        {\n            assert(trackApproximateSolutions_);\n            if (vertex->hasForwardParent() || graph_.isStart(vertex))\n            {\n                auto costToGoal = computeCostToGoToGoal(vertex);\n\n                // We need to check whether this is better than the current approximate solution or whether someone\n                // has removed all approximate solutions from the problem definition.\n                if (objective_->isCostBetterThan(costToGoal, approximateSolutionCostToGoal_) ||\n                    !pdef_->hasApproximateSolution())\n                {\n                    // Remember the incumbent approximate cost.\n                    approximateSolutionCost_ = vertex->getCostToComeFromStart();\n                    approximateSolutionCostToGoal_ = costToGoal;\n                    ompl::base::PlannerSolution solution(getPathToVertex(vertex));\n                    solution.setPlannerName(name_);\n\n                    // Set the approximate flag.\n                    solution.setApproximate(costToGoal.value());\n\n                    // This solution is approximate and can not satisfy the objective.\n                    solution.setOptimized(objective_, approximateSolutionCost_, false);\n\n                    // Let the problem definition know that a new solution exists.\n                    pdef_->addSolutionPath(solution);\n                }\n            }\n        };\n\n        ompl::base::PlannerStatus::StatusType AITstar::updateSolution()\n        {\n            updateExactSolution();\n            if (objective_->isFinite(solutionCost_))\n            {\n                return ompl::base::PlannerStatus::StatusType::EXACT_SOLUTION;\n            }\n            else if (trackApproximateSolutions_)\n            {\n                updateApproximateSolution();\n                return ompl::base::PlannerStatus::StatusType::APPROXIMATE_SOLUTION;\n            }\n            else\n            {\n                return ompl::base::PlannerStatus::StatusType::TIMEOUT;\n            }\n        }\n\n        ompl::base::PlannerStatus::StatusType AITstar::updateSolution(const std::shared_ptr<Vertex> &vertex)\n        {\n            updateExactSolution();\n            if (objective_->isFinite(solutionCost_))\n            {\n                return ompl::base::PlannerStatus::StatusType::EXACT_SOLUTION;\n            }\n            else if (trackApproximateSolutions_)\n            {\n                updateApproximateSolution(vertex);\n                return ompl::base::PlannerStatus::StatusType::APPROXIMATE_SOLUTION;\n            }\n            else\n            {\n                return ompl::base::PlannerStatus::StatusType::TIMEOUT;\n            }\n        }\n\n        ompl::base::Cost AITstar::computeCostToGoToStartHeuristic(const std::shared_ptr<Vertex> &vertex) const\n        {\n            // We need to loop over all start vertices and see which is the closest one.\n            ompl::base::Cost bestCost = objective_->infiniteCost();\n            for (const auto &start : graph_.getStartVertices())\n            {\n                bestCost = objective_->betterCost(\n                    bestCost, objective_->motionCostHeuristic(vertex->getState(), start->getState()));\n            }\n            return bestCost;\n        }\n\n        ompl::base::Cost AITstar::computeCostToGoToGoalHeuristic(const std::shared_ptr<Vertex> &vertex) const\n        {\n            // We need to loop over all goal vertices and see which is the closest one.\n            ompl::base::Cost bestCost = objective_->infiniteCost();\n            for (const auto &goal : graph_.getGoalVertices())\n            {\n                bestCost = objective_->betterCost(\n                    bestCost, objective_->motionCostHeuristic(vertex->getState(), goal->getState()));\n            }\n            return bestCost;\n        }\n\n        ompl::base::Cost AITstar::computeCostToGoToGoal(const std::shared_ptr<Vertex> &vertex) const\n        {\n            // We need to loop over all goal vertices and see which is the closest one.\n            ompl::base::Cost bestCost = objective_->infiniteCost();\n            for (const auto &goal : graph_.getGoalVertices())\n            {\n                bestCost =\n                    objective_->betterCost(bestCost, objective_->motionCost(vertex->getState(), goal->getState()));\n            }\n            return bestCost;\n        }\n\n        ompl::base::Cost AITstar::computeBestCostToComeFromGoalOfAnyStart() const\n        {\n            // We need to loop over all start vertices and see which is the closest one.\n            ompl::base::Cost bestCost = objective_->infiniteCost();\n            for (const auto &start : graph_.getStartVertices())\n            {\n                bestCost = objective_->betterCost(bestCost, start->getCostToComeFromGoal());\n            }\n            return bestCost;\n        }\n\n        std::size_t AITstar::countNumVerticesInForwardTree() const\n        {\n            std::size_t numVerticesInForwardTree = 0u;\n            auto vertices = graph_.getVertices();\n            for (const auto &vertex : vertices)\n            {\n                if (graph_.isStart(vertex) || vertex->hasForwardParent())\n                {\n                    ++numVerticesInForwardTree;\n                }\n            }\n            return numVerticesInForwardTree;\n        }\n\n        std::size_t AITstar::countNumVerticesInReverseTree() const\n        {\n            std::size_t numVerticesInReverseTree = 0u;\n            auto vertices = graph_.getVertices();\n            for (const auto &vertex : vertices)\n            {\n                if (graph_.isGoal(vertex) || vertex->hasReverseParent())\n                {\n                    ++numVerticesInReverseTree;\n                }\n            }\n            return numVerticesInReverseTree;\n        }\n\n        void AITstar::invalidateCostToComeFromGoalOfReverseBranch(const std::shared_ptr<Vertex> &vertex)\n        {\n            // If this vertex is consistent before invalidation, then all incoming edges now have targets that are\n            // inconsistent.\n            if (vertex->isConsistent())\n            {\n                numInconsistentOrUnconnectedTargets_ += vertex->getForwardQueueIncomingLookup().size();\n            }\n\n            // Reset the cost to come from the goal and the reverse parent unless the vertex is itself a goal.\n            if (!graph_.isGoal(vertex))\n            {\n                // Reset the cost to come from the goal.\n                vertex->resetCostToComeFromGoal();\n\n                // Reset the reverse parent.\n                vertex->getReverseParent()->removeFromReverseChildren(vertex->getId());\n                vertex->resetReverseParent();\n            }\n\n            // Reset the expanded cost to come from goal.\n            vertex->resetExpandedCostToComeFromGoal();\n\n            // Update all affected edges in the forward queue.\n            for (const auto &edge : vertex->getForwardQueueIncomingLookup())\n            {\n                edge->data.setSortKey(computeSortKey(edge->data.getParent(), edge->data.getChild()));\n                forwardQueue_.update(edge);\n            }\n\n            // Remove this vertex from the reverse search queue if it is in it.\n            auto reverseQueuePointer = vertex->getReverseQueuePointer();\n            if (reverseQueuePointer)\n            {\n                reverseQueue_.remove(reverseQueuePointer);\n                vertex->resetReverseQueuePointer();\n            }\n\n            // Update the cost of all reverse children.\n            for (const auto &child : vertex->getReverseChildren())\n            {\n                invalidateCostToComeFromGoalOfReverseBranch(child);\n            }\n\n            // Update the reverse search vertex to ensure that this vertex is placed in open if necessary.\n            updateReverseSearchVertex(vertex);\n        }\n\n    }  // namespace geometric\n}  // namespace ompl\n", "meta": {"hexsha": "29acba1f315e5f3262952600b709ccd2f9315176", "size": 59923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/geometric/planners/informedtrees/src/AITstar.cpp", "max_stars_repo_name": "kopernikusauto/ompl", "max_stars_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 837.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T12:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:42.000Z", "max_issues_repo_path": "src/ompl/geometric/planners/informedtrees/src/AITstar.cpp", "max_issues_repo_name": "kopernikusauto/ompl", "max_issues_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 271.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T22:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:01.000Z", "max_forks_repo_path": "src/ompl/geometric/planners/informedtrees/src/AITstar.cpp", "max_forks_repo_name": "kopernikusauto/ompl", "max_forks_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 452.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T08:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:53:33.000Z", "avg_line_length": 43.9640498899, "max_line_length": 120, "alphanum_fraction": 0.5493716937, "num_tokens": 11535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.03410042595771566, "lm_q1q2_score": 0.013890242448370817}}
{"text": "#pragma once\n\n#include <array>\n#include <vector>\n\n#include \"octotiger/cuda_util/cuda_global_def.hpp\"\n#include \"octotiger/hydro_defs.hpp\"\n#include \"octotiger/unitiger/hydro.hpp\"\n#include \"octotiger/unitiger/safe_real.hpp\"\n\n#include <buffer_manager.hpp>\n#ifdef OCTOTIGER_HAVE_CUDA\n#include <cuda_buffer_util.hpp>\n#include <cuda_runtime.h>\n#include <stream_manager.hpp>\n#include \"octotiger/cuda_util/cuda_helper.hpp\"\n#endif\n\n#include <boost/container/vector.hpp>    // to get non-specialized vector<bool>\n\ntimestep_t flux_kernel_interface(const hydro::recon_type<NDIM>& Q, hydro::flux_type& F,\n    hydro::x_type& X, safe_real omega, const size_t nf_);\n\n// Vc kernels\n#if defined(__x86_64__) && defined(OCTOTIGER_HAVE_VC)\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_);\ntimestep_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#endif\n\n#ifdef OCTOTIGER_HAVE_CUDA\ntimestep_t launch_flux_cuda(\n    stream_interface<hpx::cuda::experimental::cuda_executor, pool_strategy>& executor,\n    double* device_q,\n    std::vector<double, recycler::recycle_allocator_cuda_host<double>>& combined_f,\n    std::vector<double, recycler::recycle_allocator_cuda_host<double>> &combined_x, double* device_x,\n    safe_real omega, const size_t nf_, double dx, size_t device_id);\nvoid launch_flux_cuda_kernel_post(stream_interface<hpx::cuda::experimental::cuda_executor, pool_strategy>& executor,\n    dim3 const grid_spec, dim3 const threads_per_block, void *args[]);\n#endif\n\n// helpers for using vectortype specialization functions\ntemplate <typename double_t, typename cond_t>\nCUDA_GLOBAL_METHOD inline void select_wrapper(\n    double_t& target, const cond_t cond, const double_t& tmp1, const double_t& tmp2) {\n    target = cond ? tmp1 : tmp2;\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline T max_wrapper(const T& tmp1, const T& tmp2) {\n    return max(tmp1, tmp2);\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline T min_wrapper(const T& tmp1, const T& tmp2) {\n    return min(tmp1, tmp2);\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline T sqrt_wrapper(const T& tmp1) {\n    return std::sqrt(tmp1);\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline T pow_wrapper(const T& tmp1, const double& tmp2) {\n    return std::pow(tmp1, tmp2);\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline T asinh_wrapper(const T& tmp1) {\n    return std::asinh(tmp1);\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline bool skippable(const T& tmp1) {\n    return !tmp1;\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline T load_value(const double* data, const size_t index) {\n    return data[index];\n}\ntemplate <typename T>\nCUDA_GLOBAL_METHOD inline void store_value(\n    double* data, const size_t index, const T& value) {\n    data[index] = value;\n}\ntemplate <typename T, typename container_t>\nCUDA_GLOBAL_METHOD inline T load_value(const container_t &data, const size_t index) {\n    return data[index];\n}\ntemplate <typename T, typename container_t>\nCUDA_GLOBAL_METHOD inline void store_value(\n    container_t &data, const size_t index, const T& value) {\n    data[index] = value;\n}\n\nboost::container::vector<bool> create_masks();\n\n#pragma GCC push_options\n#pragma GCC optimize(\"unroll-loops\")\n\ntemplate <typename double_t>\nCUDA_GLOBAL_METHOD inline double_t inner_flux_loop(const double omega, const size_t nf_,\n    const double A_, const double B_, const double_t* __restrict__ UR,\n    const double_t* __restrict__ UL, double_t* __restrict__ this_flux,\n    const double_t* __restrict__ x, const double_t* __restrict__ vg, double_t& ap, double_t& am,\n    const size_t dim, const size_t d, const double dx, const double fgamma,\n    const double de_switch_1) {\n    double_t amr, apr, aml, apl;\n    double_t this_ap, this_am;    // tmps\n    double_t p, v, v0, c;\n\n    auto rho = UR[rho_i];\n    auto rhoinv = (1.) / rho;\n    double_t pdeg = static_cast<double_t>(0.0), edeg = static_cast<double_t>(0.0),\n     dpdeg_drho = static_cast<double_t>(0.0);\n\n    // all workitems choose the same path\n    if (A_ != 0.0) {\n        const auto Binv = 1.0 / B_;\n        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);\n        const auto x_sqr = x * x;\n        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);\n        const auto x_pow_5 = x_sqr * x_sqr * x;\n        const double_t hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);\n\n        const double_t edeg_tmp1 = rho * hdeg - pdeg;\n        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;\n        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asinh_wrapper(x));\n        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;\n        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);\n        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);\n\n        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;\n    }\n    double_t ek = 0.0;\n    for (int dim = 0; dim < NDIM; dim++) {\n        ek += UR[sx_i + dim] * UR[sx_i + dim] * rhoinv * 0.5;\n    }\n    const auto ein1_tmp2 = UR[egas_i] - ek - edeg;\n    const auto ein1_mask = (ein1_tmp2 < (de_switch_1 * UR[egas_i]));\n    double_t ein;\n    if (!skippable(ein1_mask)) {\n        const auto ein1_tmp1 = pow_wrapper(UR[tau_i], fgamma);\n        select_wrapper(ein, ein1_mask, ein1_tmp1, ein1_tmp2);\n    } else {\n        ein = ein1_tmp2;\n    }\n    double_t dp_drho = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;\n    double_t dp_deps = (fgamma - 1.0) * rho;\n    v0 = UR[sx_i + dim] * rhoinv;\n    p = (fgamma - 1.0) * ein + pdeg;\n    c = sqrt_wrapper(p * rhoinv * rhoinv * dp_deps + dp_drho);\n    v = v0 - vg[dim];\n    amr = v - c;\n    apr = v + c;\n\n    rho = UL[rho_i];\n    rhoinv = (1.) / rho;\n    pdeg = static_cast<double_t>(0.0);\n    edeg = static_cast<double_t>(0.0);\n    dpdeg_drho = static_cast<double_t>(0.0);\n\n    // all workitems choose the same path\n    if (A_ != 0.0) {\n        const auto Binv = 1.0 / B_;\n        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);\n        const auto x_sqr = x * x;\n        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);\n        const auto x_pow_5 = x_sqr * x_sqr * x;\n        const double_t hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);\n        const double_t edeg_tmp1 = rho * hdeg - pdeg;\n        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;\n        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asinh_wrapper(x));\n        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;\n        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);\n        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);\n        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;\n    }\n    ek = 0.0;\n    for (int dim = 0; dim < NDIM; dim++) {\n        ek += UL[sx_i + dim] * UL[sx_i + dim] * rhoinv * 0.5;\n    }\n    const auto ein2_tmp2 = UL[egas_i] - ek - edeg;\n    const auto ein2_mask = (ein2_tmp2 < (de_switch_1 * UL[egas_i]));\n    if (!skippable(ein2_mask)) {\n        const auto ein2_tmp1 = pow_wrapper(UL[tau_i], fgamma);\n        select_wrapper(ein, ein2_mask, ein2_tmp1, ein2_tmp2);\n    } else {\n        ein = ein2_tmp2;\n    }\n    const auto dp_drho2 = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;\n    const auto dp_deps2 = (fgamma - 1.0) * rho;\n    const auto v02 = UL[sx_i + dim] * rhoinv;\n    const auto p2 = (fgamma - 1.0) * ein + pdeg;\n    const auto c2 = sqrt_wrapper(p2 * rhoinv * rhoinv * dp_deps2 + dp_drho2);\n    const auto v2 = v02 - vg[dim];\n    aml = v2 - c2;\n    apl = v2 + c2;\n\n    this_ap = max_wrapper(max_wrapper(apr, apl), double_t(0.0));\n    this_am = min_wrapper(min_wrapper(amr, aml), double_t(0.0));\n    const auto amp_mask = (this_ap - this_am == 0.0);\n    for (int f = 0; f < nf_; f++) {\n        double_t fr = v * UR[f];\n        double_t fl = v2 * UL[f];\n\n        if (f == sx_i + dim) {\n            fr += p;\n            fl += p2;\n        } else if (f == egas_i) {\n            fr += v0 * p;\n            fl += v02 * p2;\n        }\n        if (dim == 0) {\n            // levi_civita 1 2 0\n            if (f == lx_i + 1) {\n                fr += x[2] * p;\n                fl += x[2] * p2;\n            } else if (f == lx_i + 2) {\n                // levi_civita 2 1 0\n                fr -= x[1] * p;\n                fl -= x[1] * p2;\n            }\n        } else if (dim == 1) {\n            // levi_civita 0 2 1\n            if (f == lx_i + 0) {\n                fr -= x[2] * p;\n                fl -= x[2] * p2;\n                // 2 0 1\n            } else if (f == lx_i + 2) {\n                fr += x[0] * p;\n                fl += x[0] * p2;\n            }\n        } else if (dim == 2) {\n            if (f == lx_i) {\n                // levi_civita 0 1 2\n                fr += x[1] * p;\n                fl += x[1] * p2;\n                // 1 0 2\n            } else if (f == lx_i + 1) {\n                fr -= x[0] * p;\n                fl -= x[0] * p2;\n            }\n        }\n\n        if (!skippable(amp_mask)) {\n            const double_t flux_tmp1 =\n                (this_ap * fl - this_am * fr + this_ap * this_am * (UR[f] - UL[f])) /\n                (this_ap - this_am);\n            const double_t flux_tmp2 = (fl + fr) / 2.0;\n            select_wrapper(this_flux[f], amp_mask, flux_tmp2, flux_tmp1);\n        } else {\n            this_flux[f] = (this_ap * fl - this_am * fr + this_ap * this_am * (UR[f] - UL[f])) /\n                (this_ap - this_am);\n        }\n    }\n\n    am = min_wrapper(am, this_am);\n    ap = max_wrapper(ap, this_ap);\n    return max_wrapper(ap, double_t(-am));\n}\n\n/*template <typename double_t>\nCUDA_GLOBAL_METHOD inline double_t inner_flux_loop2(const double omega, const size_t nf_,\n    const double A_, const double B_, const double* __restrict__ U,\n    double_t* __restrict__ this_flux, const double_t* __restrict__ x,\n    const double_t* __restrict__ vg, double_t& ap, double_t& am, const size_t dim, const size_t d,\n    const double dx, const double fgamma, const double de_switch_1, const size_t index,\n    const size_t flipped_index, const size_t face_offset) {\n    double_t amr, apr, aml, apl;\n    double_t this_ap, this_am;    // tmps\n\n    auto rho = load_value<double_t>(U, rho_i * face_offset + index);\n    auto rhoinv = (1.) / rho;\n    double_t hdeg = static_cast<double_t>(0.0), pdeg = static_cast<double_t>(0.0),\n             edeg = static_cast<double_t>(0.0), dpdeg_drho = static_cast<double_t>(0.0);\n\n    // all workitems choose the same path\n    if (A_ != 0.0) {\n        const auto Binv = 1.0 / B_;\n        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);\n        const auto x_sqr = x * x;\n        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);\n        const auto x_pow_5 = x_sqr * x_sqr * x;\n        hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);\n\n        const double_t edeg_tmp1 = rho * hdeg - pdeg;\n        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;\n        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asin_wrapper(x));\n        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;\n        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);\n        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);\n\n        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;\n    }\n    double_t ek = 0.0;\n    double_t ein;\n    for (int dim = 0; dim < NDIM; dim++) {\n        ek += load_value<double_t>(U, (sx_i + dim) * face_offset + index) *\n            load_value<double_t>(U, (sx_i + dim) * face_offset + index) * rhoinv * 0.5;\n    }\n    const auto ein1_tmp2 = load_value<double_t>(U, egas_i * face_offset + index) - ek - edeg;\n    const auto ein1_mask =\n        (ein1_tmp2 < (de_switch_1 * load_value<double_t>(U, egas_i * face_offset + index)));\n    if (!skippable(ein1_mask)) {\n        const auto ein1_tmp1 =\n            pow_wrapper(load_value<double_t>(U, tau_i * face_offset + index), fgamma);\n        select_wrapper(ein, ein1_mask, ein1_tmp1, ein1_tmp2);\n    } else {\n        ein = ein1_tmp2;\n    }\n    const auto dp_drho = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;\n    const auto dp_deps = (fgamma - 1.0) * rho;\n    const auto v0 = load_value<double_t>(U, (sx_i + dim) * face_offset + index) * rhoinv;\n    const auto p = (fgamma - 1.0) * ein + pdeg;\n    const auto c = sqrt_wrapper(p * rhoinv * rhoinv * dp_deps + dp_drho);\n    const auto v = v0 - vg[dim];\n    amr = v - c;\n    apr = v + c;\n\n    rho = load_value<double_t>(U, rho_i * face_offset + flipped_index);\n    rhoinv = (1.) / rho;\n    hdeg = static_cast<double_t>(0.0);\n    pdeg = static_cast<double_t>(0.0);\n    edeg = static_cast<double_t>(0.0);\n    dpdeg_drho = static_cast<double_t>(0.0);\n\n    // all workitems choose the same path\n    if (A_ != 0.0) {\n        const auto Binv = 1.0 / B_;\n        const auto x = pow_wrapper(rho * Binv, 1.0 / 3.0);\n        const auto x_sqr = x * x;\n        const auto x_sqr_sqrt = sqrt_wrapper(x_sqr + 1.0);\n        const auto x_pow_5 = x_sqr * x_sqr * x;\n        hdeg = 8.0 * A_ * Binv * (x_sqr_sqrt - 1.0);\n        const double_t edeg_tmp1 = rho * hdeg - pdeg;\n        const double_t edeg_tmp2 = 2.4 * A_ * x_pow_5;\n        const double_t pdeg_tmp1 = A_ * (x * (2 * x_sqr - 3) * x_sqr_sqrt + 3 * asin_wrapper(x));\n        const double_t pdeg_tmp2 = 1.6 * A_ * x_pow_5;\n        select_wrapper(edeg, (x > 0.001), edeg_tmp1, edeg_tmp2);\n        select_wrapper(pdeg, (x > 0.001), pdeg_tmp1, pdeg_tmp2);\n        dpdeg_drho = 8.0 / 3.0 * A_ * Binv * x_sqr / x_sqr_sqrt;\n    }\n    ek = 0.0;\n    for (int dim = 0; dim < NDIM; dim++) {\n        ek += load_value<double_t>(U, (sx_i + dim) * face_offset + flipped_index) *\n            load_value<double_t>(U, (sx_i + dim) * face_offset + flipped_index) * rhoinv * 0.5;\n    }\n    const auto ein2_tmp2 =\n        load_value<double_t>(U, egas_i * face_offset + flipped_index) - ek - edeg;\n    const auto ein2_mask =\n        (ein2_tmp2 < (de_switch_1 * load_value<double_t>(U, egas_i * face_offset + flipped_index)));\n    if (!skippable(ein2_mask)) {\n        const auto ein2_tmp1 =\n            pow_wrapper(load_value<double_t>(U, tau_i * face_offset + flipped_index), fgamma);\n        select_wrapper(ein, ein2_mask, ein2_tmp1, ein2_tmp2);\n    } else {\n        ein = ein2_tmp2;\n    }\n    const auto dp_drho2 = dpdeg_drho + (fgamma - 1.0) * ein * rhoinv;\n    const auto dp_deps2 = (fgamma - 1.0) * rho;\n    const auto v02 = load_value<double_t>(U, (sx_i + dim) * face_offset + flipped_index) * rhoinv;\n    const auto p2 = (fgamma - 1.0) * ein + pdeg;\n    const auto c2 = sqrt_wrapper(p2 * rhoinv * rhoinv * dp_deps2 + dp_drho2);\n    const auto v2 = v02 - vg[dim];\n    aml = v2 - c2;\n    apl = v2 + c2;\n\n    this_ap = max_wrapper(max_wrapper(apr, apl), double_t(0.0));\n    this_am = min_wrapper(min_wrapper(amr, aml), double_t(0.0));\n    const auto amp_mask = (this_ap - this_am == 0.0);\n    for (int f = 0; f < nf_; f++) {\n        double_t fr = v * load_value<double_t>(U, f * face_offset + index);\n        double_t fl = v2 * load_value<double_t>(U, f * face_offset + flipped_index);\n\n        if (f == sx_i + dim) {\n            fr += p;\n            fl += p2;\n        } else if (f == egas_i) {\n            fr += v0 * p;\n            fl += v02 * p2;\n        }\n        if (dim == 0) {\n            // levi_civita 1 2 0\n            if (f == lx_i + 1) {\n                fr += x[2] * p;\n                fl += x[2] * p2;\n            } else if (f == lx_i + 2) {\n                // levi_civita 2 1 0\n                fr -= x[1] * p;\n                fl -= x[1] * p2;\n            }\n        } else if (dim == 1) {\n            // levi_civita 0 2 1\n            if (f == lx_i + 0) {\n                fr -= x[2] * p;\n                fl -= x[2] * p2;\n                // 2 0 1\n            } else if (f == lx_i + 2) {\n                fr += x[0] * p;\n                fl += x[0] * p2;\n            }\n        } else if (dim == 2) {\n            if (f == lx_i) {\n                // levi_civita 0 1 2\n                fr += x[1] * p;\n                fl += x[1] * p2;\n                // 1 0 2\n            } else if (f == lx_i + 1) {\n                fr -= x[0] * p;\n                fl -= x[0] * p2;\n            }\n        }\n\n        if (!skippable(amp_mask)) {\n            const double_t flux_tmp1 =\n                (this_ap * fl - this_am * fr +\n                    this_ap * this_am *\n                        (load_value<double_t>(U, f * face_offset + index) -\n                            load_value<double_t>(U, f * face_offset + flipped_index))) /\n                (this_ap - this_am);\n            const double_t flux_tmp2 = (fl + fr) / 2.0;\n            select_wrapper(this_flux[f], amp_mask, flux_tmp2, flux_tmp1);\n        } else {\n            this_flux[f] = (this_ap * fl - this_am * fr +\n                               this_ap * this_am *\n                                   (load_value<double_t>(U, f * face_offset + index) -\n                                       load_value<double_t>(U, f * face_offset + flipped_index))) /\n                (this_ap - this_am);\n        }\n    }\n\n    am = min_wrapper(am, this_am);\n    ap = max_wrapper(ap, this_ap);\n    return max_wrapper(ap, double_t(-am));\n}*/\n\ntemplate <typename Alloc>\nvoid convert_q_structure(const hydro::recon_type<NDIM>& Q, std::vector<double, Alloc>& combined_q) {\n    auto it = combined_q.begin();\n    auto nf_ = physics<NDIM>::nf_;\n    for (auto field = 0; field < nf_; field++) {\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[field][d].begin() + start_offset,\n                        Q[field][d].begin() + start_offset + 10, it);\n                    start_offset += 14;\n                }\n                start_offset += (2 + 2) * 14;\n            }\n        }\n    }\n}\n\ntemplate <typename Alloc>\nvoid compare_q_structure(const hydro::recon_type<NDIM>& Q, std::vector<double, Alloc>& combined_q) {\n    auto it = combined_q.begin();\n    auto nf_ = physics<NDIM>::nf_;\n    for (auto field = 0; field < nf_; field++) {\n        bool correct = true;\n        for (auto d = 0; d < 27; d++) {\n            auto start_offset = 2 * 14 * 14 + 2 * 14;\n            for (auto ix = 2; ix < 2 + INX + 2; ix++) {\n                for (auto iy = 2; iy < 2 + INX + 2; iy++) {\n                    for (auto line_element = 0; line_element < 10; line_element++) {\n                        if (std::abs(Q[field][d][start_offset + line_element + 2] -\n                                *(it + line_element)) > 1e-7) {\n                            std::cout << \"Orig: \" << Q[field][d][start_offset + line_element + 2]\n                                      << \" vs: \" << *(it + line_element) << std::endl;\n                            std::cout << \"Found error at field \" << field << \" with d \" << d\n                                      << \" and grid element \" << ix << \"/\" << iy << \"/\"\n                                      << line_element + 2 << std::endl;\n                            for (auto line_element = 0; line_element < 10; line_element++) {\n                                std::cout << Q[field][d][start_offset + line_element + 2] << \" \";\n                            }\n                            std::cout << std::endl;\n                            for (auto line_element = 0; line_element < 10; line_element++) {\n                                std::cout << *(it + line_element) << \" \";\n                            }\n                            std::cout << std::endl;\n                            correct = false;\n                        }\n                    }\n                    start_offset += 14;\n                    it += 10;\n                }\n                start_offset += (2 + 2) * 14;\n            }\n        }\n        if (!correct) {\n            std::cout << \" field \" << field << \" is incorrect!\" << std::endl;\n            std::cin.get();\n        }\n    }\n}\n\n#pragma GCC pop_options\n", "meta": {"hexsha": "84e9e45c34fd754c278fcba21945813b79d95c08", "size": 19846, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "octotiger/unitiger/hydro_impl/flux_kernel_interface.hpp", "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": "octotiger/unitiger/hydro_impl/flux_kernel_interface.hpp", "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": "octotiger/unitiger/hydro_impl/flux_kernel_interface.hpp", "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.0120967742, "max_line_length": 116, "alphanum_fraction": 0.5498337196, "num_tokens": 6118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828341018881344, "lm_q2_score": 0.028436031603970194, "lm_q1q2_score": 0.013884842483823441}}
{"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_ABSTRACT_OPERATOR_HPP\n#define NETKET_ABSTRACT_OPERATOR_HPP\n\n#include <Eigen/Dense>\n#include <complex>\n#include <nonstd/span.hpp>\n#include <tuple>\n#include <vector>\n#include \"Hilbert/hilbert.hpp\"\n\nnamespace netket {\n/**\n * This struct represents a non-zero matrix-element H(v,v') of an operator for a\n * given visible state v.\n */\nstruct ConnectorRef {\n  /// The matrix element H(v,v')\n  Complex mel;\n  /// The indices at which v needs to be changed to obtain v'\n  nonstd::span<const int> tochange;\n  /// The new values such that\n  ///    v'(tochange[k]) = newconf[k]\n  /// and v'(i) = v(i) for i ∉ tochange.\n  nonstd::span<const double> newconf;\n};\n\n/**\n      Abstract class for quantum Operators.\n      This class prototypes the methods needed\n      by a class satisfying the Operator concept.\n      Users interested in implementing new quantum Operators should derive they\n   own class from this class.\n*/\nclass AbstractOperator {\n public:\n  using VectorType = Eigen::VectorXd;\n  using VectorRefType = Eigen::Ref<VectorType>;\n  using VectorConstRefType = Eigen::Ref<const VectorType>;\n  using MelType = std::vector<Complex>;\n  using ConnectorsType = std::vector<std::vector<int>>;\n  using NewconfsType = std::vector<std::vector<double>>;\n\n  /**\n  Member function finding the connected elements of the Operator.\n  Starting from a given visible state v, it finds all other visible states v'\n  such that the matrix element O(v,v') is different from zero.\n  In general there will be several different connected visible units satisfying\n  this condition, and they are denoted here v'(k), for k=0,1...N_connected.\n  @param v a constant reference to the visible configuration.\n  @param mel(k) is modified to contain matrix elements O(v,v'(k)).\n  @param connector(k) for each k contains a list of sites that should be changed\n  to obtain v'(k) starting from v.\n  @param newconfs(k) is a vector containing the new values of the visible units\n  on the affected sites, such that: v'(k,connectors(k,j))=newconfs(k,j). For the\n  other sites v'(k)=v, i.e. they are equal to the starting visible\n  configuration.\n  */\n  virtual void FindConn(VectorConstRefType v, MelType &mel,\n                        ConnectorsType &connectors,\n                        NewconfsType &newconfs) const = 0;\n\n  using ConnCallback = std::function<void(ConnectorRef)>;\n\n  virtual std::tuple<MelType, ConnectorsType, NewconfsType> GetConn(\n      VectorConstRefType v) const {\n    std::vector<Complex> mel;\n    std::vector<std::vector<int>> connectors;\n    std::vector<std::vector<double>> newconfs;\n    FindConn(v, mel, connectors, newconfs);\n    return std::make_tuple(mel, connectors, newconfs);\n  }\n  /**\n   * Iterates over all states reachable from a given visible configuration v,\n   * i.e., all states v' such that O(v,v') is non-zero.\n   * @param v The visible configuration.\n   * @param callback Function void callback(ConnectorRef conn) which will be\n   * called once for each reachable configuration v'. The parameter conn\n   * contains the value O(v,v') and the information to obtain v' from v. Note\n   * that the members conn.positions and conn.values are spans that can only be\n   * savely used inside the callback. They will become invalid once callback\n   * returns.\n   */\n  virtual void ForEachConn(VectorConstRefType v, ConnCallback callback) const;\n\n  /**\n  Member function returning the hilbert space associated with this Hamiltonian.\n  @return Hilbert space specifier for this Hamiltonian\n  */\n  virtual const AbstractHilbert &GetHilbert() const noexcept = 0;\n\n  virtual ~AbstractOperator() {}\n};\n\nvoid AbstractOperator::ForEachConn(VectorConstRefType v,\n                                   ConnCallback callback) const {\n  std::vector<Complex> weights;\n  std::vector<std::vector<int>> connectors;\n  std::vector<std::vector<double>> newconfs;\n\n  FindConn(v, weights, connectors, newconfs);\n\n  for (size_t k = 0; k < connectors.size(); k++) {\n    const ConnectorRef conn{weights[k], connectors[k], newconfs[k]};\n    callback(conn);\n  }\n}\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "d931bc61da4e664f10c0d07aca796c21d17720a3", "size": 4695, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Operator/abstract_operator.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/Operator/abstract_operator.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/Operator/abstract_operator.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": 37.56, "max_line_length": 80, "alphanum_fraction": 0.7135250266, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.028870903708419576, "lm_q1q2_score": 0.013871853647869857}}
{"text": "// Copyright (C) 2014 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// BSD 3-Clause License\n\n// Copyright (c) 2020, Chenyu\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\n//    list of conditions and the following disclaimer.\n\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived from\n//    this software without specific prior written permission.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\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 \"rotation_estimation/align_rotations.h\"\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <glog/logging.h>\n\n#include <Eigen/Core>\n#include <vector>\n\nnamespace DAGSfM {\n\nnamespace {\n\n// A cost function whose error is the difference in rotations after the current\n// alignment is applied. That is,\n//    error = unaligned_rotation * rotation_alignment - gt_rotation.\nstruct RotationAlignmentError {\n  RotationAlignmentError(const Eigen::Vector3d& gt_rotation,\n                         const Eigen::Vector3d& unaligned_rotation)\n      : gt_rotation_(gt_rotation) {\n    // Convert the unaligned rotation to rotation matrix.\n    Eigen::Matrix3d unaligned_rotation_mat;\n    ceres::AngleAxisToRotationMatrix(\n        unaligned_rotation.data(),\n        ceres::ColumnMajorAdapter3x3(unaligned_rotation_mat_.data()));\n  }\n\n  // Compute the alignment error of the two rotations after applying the\n  // rotation transformation.\n  template <typename T>\n  bool operator()(const T* rotation, T* residuals) const {\n    // Convert the rotation transformation to a matrix.\n    Eigen::Matrix<T, 3, 3> rotation_mat;\n    ceres::AngleAxisToRotationMatrix(\n        rotation, ceres::ColumnMajorAdapter3x3(rotation_mat.data()));\n\n    // Apply the rotation transformation.\n    const Eigen::Matrix<T, 3, 3> aligned_rotation_mat =\n        unaligned_rotation_mat_.cast<T>() * rotation_mat;\n\n    // Convert back to angle axis.\n    Eigen::Matrix<T, 3, 1> aligned_rotation;\n    ceres::RotationMatrixToAngleAxis(\n        ceres::ColumnMajorAdapter3x3(aligned_rotation_mat.data()),\n        aligned_rotation.data());\n\n    // Compute the error of the aligned rotation to the gt_rotation.\n    residuals[0] = gt_rotation_[0] - aligned_rotation[0];\n    residuals[1] = gt_rotation_[1] - aligned_rotation[1];\n    residuals[2] = gt_rotation_[2] - aligned_rotation[2];\n\n    return true;\n  }\n\n  static ceres::CostFunction* Create(\n      const Eigen::Vector3d& gt_rotation,\n      const Eigen::Vector3d& unaligned_rotation) {\n    return new ceres::AutoDiffCostFunction<RotationAlignmentError, 3, 3>(\n        new RotationAlignmentError(gt_rotation, unaligned_rotation));\n  }\n\n  Eigen::Vector3d gt_rotation_;\n  Eigen::Matrix3d unaligned_rotation_mat_;\n};\n\n// Apply the rotation alignment to all rotations in the vector.\nvoid ApplyRotationTransformation(const Eigen::Vector3d& rotation_alignment,\n                                 std::vector<Eigen::Vector3d>* rotation) {\n  Eigen::Matrix3d rotation_alignment_mat;\n  ceres::AngleAxisToRotationMatrix(\n      rotation_alignment.data(),\n      ceres::ColumnMajorAdapter3x3(rotation_alignment_mat.data()));\n\n  for (int i = 0; i < rotation->size(); i++) {\n    // Convert the current rotation to a rotation matrix.\n    Eigen::Matrix3d rotation_mat;\n    ceres::AngleAxisToRotationMatrix(\n        rotation->at(i).data(),\n        ceres::ColumnMajorAdapter3x3(rotation_mat.data()));\n\n    // Apply the rotation transformation.\n    const Eigen::Matrix3d aligned_rotation =\n        rotation_mat * rotation_alignment_mat;\n\n    // Convert back to angle axis.\n    ceres::RotationMatrixToAngleAxis(\n        ceres::ColumnMajorAdapter3x3(aligned_rotation.data()),\n        rotation->at(i).data());\n  }\n}\n\n}  // namespace\n\n// We solve a nonlinear least squares system to determine a rotation R that will\n// align the rotation to the gt_rotation such that rotation * R = gt_rotation.\n// This could potentially be set up as a linear system, however, that does not\n// guarantee that R will remaind a valid rotation. Instead, we simply use a\n// nonlinear system to ensure that R is a valid rotation.\nvoid AlignRotations(const std::vector<Eigen::Vector3d>& gt_rotation,\n                    std::vector<Eigen::Vector3d>* rotation) {\n  CHECK_EQ(gt_rotation.size(), rotation->size());\n\n  Eigen::Vector3d rotation_alignment = Eigen::Vector3d::Zero();\n\n  // Set up the nonlinear system and adds all residuals.\n  ceres::Problem problem;\n  for (int i = 0; i < gt_rotation.size(); i++) {\n    problem.AddResidualBlock(\n        RotationAlignmentError::Create(gt_rotation[i], rotation->at(i)), NULL,\n        rotation_alignment.data());\n  }\n\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_QR;\n  options.function_tolerance = 0.0;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  VLOG(2) << summary.FullReport();\n\n  // Apply the solved rotation transformation to the rotations.\n  ApplyRotationTransformation(rotation_alignment, rotation);\n}\n\n}  // namespace DAGSfM\n", "meta": {"hexsha": "05bf834cdc4473c47a768bb36b3a13adb7548dfd", "size": 7897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rotation_estimation/align_rotations.cpp", "max_stars_repo_name": "Yzhbuaa/DAGSfM", "max_stars_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 255.0, "max_stars_repo_stars_event_min_datetime": "2018-12-14T05:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T12:15:32.000Z", "max_issues_repo_path": "src/rotation_estimation/align_rotations.cpp", "max_issues_repo_name": "Yzhbuaa/DAGSfM", "max_issues_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2018-12-25T03:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T03:33:25.000Z", "max_forks_repo_path": "src/rotation_estimation/align_rotations.cpp", "max_forks_repo_name": "Yzhbuaa/DAGSfM", "max_forks_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2018-12-14T06:09:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T08:29:31.000Z", "avg_line_length": 41.3455497382, "max_line_length": 80, "alphanum_fraction": 0.7333164493, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.029312231493326745, "lm_q1q2_score": 0.013855407489768627}}
{"text": "/**\n * @file LbfgsSolver.hpp\n * @author Jorge Nocedal\n * @license License BSD-3-Clause\n * @copyright 1990, Jorge Nocedal\n * @copyright 2007-2010 Naoaki Okazaki\n * @date 2019-10-06\n * @brief C library of Limited memory BFGS (L-BFGS).\n * \n * All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n * \n */\n\n#pragma once\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <solver/interface/NlpDescription.hpp>\n\nnamespace solver {\n  /**\n   * Return values of lbfgs().\n   *  Roughly speaking, a negative value indicates an error.\n   */\n  enum {\n    /** L-BFGS reaches convergence. */\n    LBFGS_SUCCESS = 0,\n    LBFGS_STOP,\n    /** The initial variables already minimize the objective function. */\n    LBFGS_ALREADY_MINIMIZED,\n\t/** Unknown error. */\n\tLBFGSERR_UNKNOWNERROR = -1024,\n    /** Logic error. */\n    LBFGSERR_LOGICERROR,\n    /** Insufficient memory. */\n    LBFGSERR_OUTOFMEMORY,\n    /** Invalid number of variables specified. */\n    LBFGSERR_INVALID_N,\n    /** Invalid parameter lbfgs_parameter_t::epsilon specified. */\n    LBFGSERR_INVALID_EPSILON,\n    /** Invalid parameter lbfgs_parameter_t::past specified. */\n    LBFGSERR_INVALID_TESTPERIOD,\n    /** Invalid parameter lbfgs_parameter_t::delta specified. */\n    LBFGSERR_INVALID_DELTA,\n    /** Invalid parameter lbfgs_parameter_t::linesearch specified. */\n    LBFGSERR_INVALID_LINESEARCH,\n    /** Invalid parameter lbfgs_parameter_t::max_step specified. */\n    LBFGSERR_INVALID_MINSTEP,\n    /** Invalid parameter lbfgs_parameter_t::max_step specified. */\n    LBFGSERR_INVALID_MAXSTEP,\n    /** Invalid parameter lbfgs_parameter_t::ftol specified. */\n    LBFGSERR_INVALID_FTOL,\n    /** Invalid parameter lbfgs_parameter_t::wolfe specified. */\n    LBFGSERR_INVALID_WOLFE,\n    /** Invalid parameter lbfgs_parameter_t::gtol specified. */\n    LBFGSERR_INVALID_GTOL,\n    /** Invalid parameter lbfgs_parameter_t::xtol specified. */\n    LBFGSERR_INVALID_XTOL,\n    /** Invalid parameter lbfgs_parameter_t::max_linesearch specified. */\n    LBFGSERR_INVALID_MAXLINESEARCH,\n    /** Invalid parameter lbfgs_parameter_t::orthantwise_c specified. */\n    LBFGSERR_INVALID_ORTHANTWISE,\n    /** Invalid parameter lbfgs_parameter_t::orthantwise_start specified. */\n    LBFGSERR_INVALID_ORTHANTWISE_START,\n    /** Invalid parameter lbfgs_parameter_t::orthantwise_end specified. */\n    LBFGSERR_INVALID_ORTHANTWISE_END,\n    /** The line-search step went out of the interval of uncertainty. */\n    LBFGSERR_OUTOFINTERVAL,\n    /** A logic error occurred; alternatively, the interval of uncertainty became too small. */\n    LBFGSERR_INCORRECT_TMINMAX,\n    /** A rounding error occurred; alternatively, no line-search step\n        satisfies the sufficient decrease and curvature conditions. */\n    LBFGSERR_ROUNDING_ERROR,\n    /** The line-search step became smaller than lbfgs_parameter_t::min_step. */\n    LBFGSERR_MINIMUMSTEP,\n    /** The line-search step became larger than lbfgs_parameter_t::max_step. */\n    LBFGSERR_MAXIMUMSTEP,\n    /** The line-search routine reaches the maximum number of evaluations. */\n    LBFGSERR_MAXIMUMLINESEARCH,\n    /** The algorithm routine reaches the maximum number of iterations. */\n    LBFGSERR_MAXIMUMITERATION,\n    /** Relative width of the interval of uncertainty is at most lbfgs_parameter_t::xtol. */\n    LBFGSERR_WIDTHTOOSMALL,\n    /** A logic error (negative line-search step) occurred. */\n    LBFGSERR_INVALIDPARAMETERS,\n    /** The current search direction increases the objective function value. */\n    LBFGSERR_INCREASEGRADIENT,\n  };\n\n  /**\n   * Line search algorithms.\n   */\n  enum {\n    /** The default algorithm (MoreThuente method). */\n    LBFGS_LINESEARCH_DEFAULT = 0,\n    /** MoreThuente method proposd by More and Thuente. */\n    LBFGS_LINESEARCH_MORETHUENTE = 0,\n    /**\n     * Backtracking method with the Armijo condition.\n     *  The backtracking method finds the step length such that it satisfies\n     *  the sufficient decrease (Armijo) condition,\n     *    - f(x + a * d) <= f(x) + lbfgs_parameter_t::ftol * a * g(x)^T d,\n     *\n     *  where x is the current point, d is the current search direction, and\n     *  a is the step length.\n     */\n    LBFGS_LINESEARCH_BACKTRACKING_ARMIJO = 1,\n    /** The backtracking method with the defualt (regular Wolfe) condition. */\n    LBFGS_LINESEARCH_BACKTRACKING = 2,\n    /**\n     * Backtracking method with regular Wolfe condition.\n     *  The backtracking method finds the step length such that it satisfies\n     *  both the Armijo condition (LBFGS_LINESEARCH_BACKTRACKING_ARMIJO)\n     *  and the curvature condition,\n     *    - g(x + a * d)^T d >= lbfgs_parameter_t::wolfe * g(x)^T d,\n     *\n     *  where x is the current point, d is the current search direction, and\n     *  a is the step length.\n     */\n    LBFGS_LINESEARCH_BACKTRACKING_WOLFE = 2,\n    /**\n     * Backtracking method with strong Wolfe condition.\n     *  The backtracking method finds the step length such that it satisfies\n     *  both the Armijo condition (LBFGS_LINESEARCH_BACKTRACKING_ARMIJO)\n     *  and the following condition,\n     *    - |g(x + a * d)^T d| <= lbfgs_parameter_t::wolfe * |g(x)^T d|,\n     *\n     *  where x is the current point, d is the current search direction, and\n     *  a is the step length.\n     */\n    LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE = 3,\n  };\n\n  /**\n   * L-BFGS optimization parameters.\n   *  Call lbfgs_parameter_init() function to initialize parameters to the\n   *  default values.\n   */\n  typedef struct {\n    /**\n     * The number of corrections to approximate the inverse hessian matrix.\n     *  The L-BFGS routine stores the computation results of previous \\ref m\n     *  iterations to approximate the inverse hessian matrix of the current\n     *  iteration. This parameter controls the size of the limited memories\n     *  (corrections). The default value is \\c 6. Values less than \\c 3 are\n     *  not recommended. Large values will result in excessive computing time.\n     */\n    int m;\n\n    /**\n     * Epsilon for convergence test.\n     *  This parameter determines the accuracy with which the solution is to\n     *  be found. A minimization terminates when\n     *      ||g|| < \\ref epsilon * max(1, ||x||),\n     *  where ||.|| denotes the Euclidean (L2) norm. The default value is\n     *  \\c 1e-5.\n     */\n    double epsilon;\n\n    /**\n     * Distance for delta-based convergence test.\n     *  This parameter determines the distance, in iterations, to compute\n     *  the rate of decrease of the objective function. If the value of this\n     *  parameter is zero, the library does not perform the delta-based\n     *  convergence test. The default value is \\c 0.\n     */\n    int past;\n\n    /**\n     * Delta for convergence test.\n     *  This parameter determines the minimum rate of decrease of the\n     *  objective function. The library stops iterations when the\n     *  following condition is met:\n     *      (f' - f) / f < \\ref delta,\n     *  where f' is the objective value of \\ref past iterations ago, and f is\n     *  the objective value of the current iteration.\n     *  The default value is \\c 0.\n     */\n    double delta;\n\n    /**\n     * The maximum number of iterations.\n     *  The lbfgs() function terminates an optimization process with\n     *  ::LBFGSERR_MAXIMUMITERATION status code when the iteration count\n     *  exceedes this parameter. Setting this parameter to zero continues an\n     *  optimization process until a convergence or error. The default value\n     *  is \\c 0.\n     */\n    int max_iterations;\n\n    /**\n     * The line search algorithm.\n     *  This parameter specifies a line search algorithm to be used by the\n     *  L-BFGS routine.\n     */\n    int linesearch;\n\n    /**\n     * The maximum number of trials for the line search.\n     *  This parameter controls the number of function and gradients evaluations\n     *  per iteration for the line search routine. The default value is \\c 20.\n     */\n    int max_linesearch;\n\n    /**\n     * The minimum step of the line search routine.\n     *  The default value is \\c 1e-20. This value need not be modified unless\n     *  the exponents are too large for the machine being used, or unless the\n     *  problem is extremely badly scaled (in which case the exponents should\n     *  be increased).\n     */\n    double min_step;\n\n    /**\n     * The maximum step of the line search.\n     *  The default value is \\c 1e+20. This value need not be modified unless\n     *  the exponents are too large for the machine being used, or unless the\n     *  problem is extremely badly scaled (in which case the exponents should\n     *  be increased).\n     */\n    double max_step;\n\n    /**\n     * A parameter to control the accuracy of the line search routine.\n     *  The default value is \\c 1e-4. This parameter should be greater\n     *  than zero and smaller than \\c 0.5.\n     */\n    double ftol;\n\n    /**\n     * A coefficient for the Wolfe condition.\n     *  This parameter is valid only when the backtracking line-search\n     *  algorithm is used with the Wolfe condition,\n     *  ::LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE or\n     *  ::LBFGS_LINESEARCH_BACKTRACKING_WOLFE .\n     *  The default value is \\c 0.9. This parameter should be greater\n     *  the \\ref ftol parameter and smaller than \\c 1.0.\n     */\n    double wolfe;\n\n    /**\n     * A parameter to control the accuracy of the line search routine.\n     *  The default value is \\c 0.9. If the function and gradient\n     *  evaluations are inexpensive with respect to the cost of the\n     *  iteration (which is sometimes the case when solving very large\n     *  problems) it may be advantageous to set this parameter to a small\n     *  value. A typical small value is \\c 0.1. This parameter shuold be\n     *  greater than the \\ref ftol parameter (\\c 1e-4) and smaller than\n     *  \\c 1.0.\n     */\n    double gtol;\n\n    /**\n     * The machine precision for floating-point values.\n     *  This parameter must be a positive value set by a client program to\n     *  estimate the machine precision. The line search routine will terminate\n     *  with the status code (::LBFGSERR_ROUNDING_ERROR) if the relative width\n     *  of the interval of uncertainty is less than this parameter.\n     */\n    double xtol;\n  } lbfgs_parameter_t;\n\n\n  /**\n   * Callback interface to provide objective function and gradient evaluations.\n   *\n   *  The lbfgs() function call this function to obtain the values of objective\n   *  function and its gradients when needed. A client program must implement\n   *  this function to evaluate the values of the objective function and its\n   *  gradients, given current values of variables.\n   *  \n   *  @param  instance    The user data sent for lbfgs() function by the client.\n   *  @param  x           The current values of variables.\n   *  @param  g           The gradient vector. The callback function must compute\n   *                      the gradient values for the current variables.\n   *  @param  n           The number of variables.\n   *  @param  step        The current step of the line search routine.\n   *  @retval double The value of the objective function for the current\n   *                          variables.\n   */\n  typedef double (*lbfgs_evaluate_t)(void *instance, const double *x,\n    double *g, const int n, const double step);\n\n  /**\n   * Callback interface to receive the progress of the optimization process.\n   *\n   *  The lbfgs() function call this function for each iteration. Implementing\n   *  this function, a client program can store or display the current progress\n   *  of the optimization process.\n   *\n   *  @param  instance    The user data sent for lbfgs() function by the client.\n   *  @param  x           The current values of variables.\n   *  @param  g           The current gradient values of variables.\n   *  @param  fx          The current value of the objective function.\n   *  @param  xnorm       The Euclidean norm of the variables.\n   *  @param  gnorm       The Euclidean norm of the gradients.\n   *  @param  step        The line-search step used for this iteration.\n   *  @param  n           The number of variables.\n   *  @param  k           The iteration count.\n   *  @param  ls          The number of evaluations called for this iteration.\n   *  @retval int         Zero to continue the optimization process. Returning a\n   *                      non-zero value will cancel the optimization process.\n   */\n  typedef int (*lbfgs_progress_t)(void *instance, const double *x,\n    const double *g, const double fx, const double xnorm,\n    const double gnorm, const double step, int n, int k, int ls);\n\n  /*\n  A user must implement a function compatible with ::lbfgs_evaluate_t (evaluation\n  callback) and pass the pointer to the callback function to lbfgs() arguments.\n  Similarly, a user can implement a function compatible with ::lbfgs_progress_t\n  (progress callback) to obtain the current progress (e.g., variables, function\n  value, ||G||, etc) and to cancel the iteration process if necessary.\n  Implementation of a progress callback is optional: a user can pass \\c NULL if\n  progress notification is not necessary.\n\n  In addition, a user must preserve two requirements:\n    - The number of variables must be multiples of 16 (this is not 4).\n    - The memory block of variable array ::x must be aligned to 16.\n\n  This algorithm terminates an optimization\n  when:\n\n    ||G|| < \\epsilon \\cdot \\max(1, ||x||) .\n\n  In this formula, ||.|| denotes the Euclidean norm.\n  */\n\n  /**\n   * Start a L-BFGS optimization.\n   *\n   *  @param  n           The number of variables.\n   *  @param  x           The array of variables. A client program can set\n   *                      default values for the optimization and receive the\n   *                      optimization result through this array. This array\n   *                      must be allocated by ::lbfgs_malloc function\n   *                      for libLBFGS built with SSE/SSE2 optimization routine\n   *                      enabled. The library built without SSE/SSE2\n   *                      optimization does not have such a requirement.\n   *  @param  ptr_fx      The pointer to the variable that receives the final\n   *                      value of the objective function for the variables.\n   *                      This argument can be set to \\c NULL if the final\n   *                      value of the objective function is unnecessary.\n   *  @param  proc_evaluate   The callback function to provide function and\n   *                          gradient evaluations given a current values of\n   *                          variables. A client program must implement a\n   *                          callback function compatible with \\ref\n   *                          lbfgs_evaluate_t and pass the pointer to the\n   *                          callback function.\n   *  @param  proc_progress   The callback function to receive the progress\n   *                          (the number of iterations, the current value of\n   *                          the objective function) of the minimization\n   *                          process. This argument can be set to \\c NULL if\n   *                          a progress report is unnecessary.\n   *  @param  instance    A user data for the client program. The callback\n   *                      functions will receive the value of this argument.\n   *  @param  param       The pointer to a structure representing parameters for\n   *                      L-BFGS optimization. A client program can set this\n   *                      parameter to \\c NULL to use the default parameters.\n   *                      Call lbfgs_parameter_init() function to fill a\n   *                      structure with the default values.\n   *  @retval int         The status code. This function returns zero if the\n   *                      minimization process terminates without an error. A\n   *                      non-zero value indicates an error.\n   */\n  int lbfgs(int n, double *x, double *ptr_fx,\n    lbfgs_evaluate_t proc_evaluate, lbfgs_progress_t proc_progress,\n    void *instance, lbfgs_parameter_t *param);\n\n  /**\n   * Initialize L-BFGS parameters to the default values.\n   *\n   *  Call this function to fill a parameter structure with the default values\n   *  and overwrite parameter values if necessary.\n   *\n   *  @param  param       The pointer to the parameter structure.\n   */\n  void lbfgs_parameter_init(lbfgs_parameter_t *param);\n\n  /**\n   * Allocate an array for variables.\n   *\n   *  This function allocates an array of variables for the convenience of\n   *  ::lbfgs function; the function has a requreiemt for a variable array\n   *  when libLBFGS is built with SSE/SSE2 optimization routines. A user does\n   *  not have to use this function for libLBFGS built without SSE/SSE2\n   *  optimization.\n   *  \n   *  @param  n           The number of variables.\n   */\n  double* lbfgs_malloc(int n);\n\n  /**\n   * Free an array of variables.\n   *  \n   *  @param  x           The array of variables allocated by ::lbfgs_malloc\n   *                      function.\n   */\n  void lbfgs_free(double *x);\n\n  /*\n   *  LBFGS Interface Class\n   */\n  class LbfgsSolver\n  {\n    public:\n\t  LbfgsSolver();\n      virtual ~LbfgsSolver(){}\n\n      bool initialize(NlpDescription* nlproblem, double constraints_weight = 1.);\n      void optimize();\n\n      bool& verbose() { return verbose_; }\n      lbfgs_parameter_t& opt_params() { return opt_params_; }\n\n    private:\n      // definition of cost evaluation\n      static double delegate_evaluate(void *instance, const double *x, double *g, const int n, const double step );\n      double evaluate(void *instance, const double *x, double *g, const int n, const double step );\n      double evaluate_objective_function(const double* eig_x);\n\n      // definition of how to show progress of the optimization\n      static int delegate_progress(void *instance, const double *x, const double *g, const double fx, const double xnorm,\n  \t\t                           const double gnorm, const double step, int n, int k, int ls );\n      int progress(const double *x, const double *g, double fx, double xnorm, double gnorm, int n, int k );\n\n    private:\n      NlpDescription* nlproblem_;\n      double constraints_weight_;\n      bool verbose_, initialized_;\n      lbfgs_parameter_t opt_params_;\n      int nvars_, ncons_, *user_info_, opt_status_, length_of_address_to_this_;\n  };\n\n}\n/** @} */\n\n/**\n@mainpage libLBFGS: a library of Limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS)\n\n@section intro Introduction\n\nThis library is a C port of the implementation of Limited-memory\nBroyden-Fletcher-Goldfarb-Shanno (L-BFGS) method written by Jorge Nocedal.\nThe original FORTRAN source code is available at:\nhttp://www.ece.northwestern.edu/~nocedal/lbfgs.html\n\nThe L-BFGS method solves the unconstrainted minimization problem,\n\n<pre>\n    minimize F(x), x = (x1, x2, ..., xN),\n</pre>\n\nonly if the objective function F(x) and its gradient G(x) are computable. The\nwell-known Newton's method requires computation of the inverse of the hessian\nmatrix of the objective function. However, the computational cost for the\ninverse hessian matrix is expensive especially when the objective function\ntakes a large number of variables. The L-BFGS method iteratively finds a\nminimizer by approximating the inverse hessian matrix by information from last\nm iterations. This innovation saves the memory storage and computational time\ndrastically for large-scaled problems.\n\nAmong the various ports of L-BFGS, this library provides several features:\n- <b>Optimization with L1-norm (Orthant-Wise Limited-memory Quasi-Newton\n  (OWL-QN) method)</b>:\n  In addition to standard minimization problems, the library can minimize\n  a function F(x) combined with L1-norm |x| of the variables,\n  {F(x) + C |x|}, where C is a constant scalar parameter. This feature is\n  useful for estimating parameters of sparse log-linear models (e.g.,\n  logistic regression and maximum entropy) with L1-regularization (or\n  Laplacian prior).\n- <b>Clean C code</b>:\n  Unlike C codes generated automatically by f2c (Fortran 77 into C converter),\n  this port includes changes based on my interpretations, improvements,\n  optimizations, and clean-ups so that the ported code would be well-suited\n  for a C code. In addition to comments inherited from the original code,\n  a number of comments were added through my interpretations.\n- <b>Callback interface</b>:\n  The library receives function and gradient values via a callback interface.\n  The library also notifies the progress of the optimization by invoking a\n  callback function. In the original implementation, a user had to set\n  function and gradient values every time the function returns for obtaining\n  updated values.\n- <b>Thread safe</b>:\n  The library is thread-safe, which is the secondary gain from the callback\n  interface.\n- <b>Cross platform.</b> The source code can be compiled on Microsoft Visual\n  Studio 2010, GNU C Compiler (gcc), etc.\n- <b>Configurable precision</b>: A user can choose single-precision (float)\n  or double-precision (double) accuracy by changing ::LBFGS_FLOAT macro.\n- <b>SSE/SSE2 optimization</b>:\n  This library includes SSE/SSE2 optimization (written in compiler intrinsics)\n  for vector arithmetic operations on Intel/AMD processors. The library uses\n  SSE for float values and SSE2 for double values. The SSE/SSE2 optimization\n  routine is disabled by default.\n\nThis library is used by:\n- <a href=\"http://www.chokkan.org/software/crfsuite/\">CRFsuite: A fast implementation of Conditional Random Fields (CRFs)</a>\n- <a href=\"http://www.chokkan.org/software/classias/\">Classias: A collection of machine-learning algorithms for classification</a>\n- <a href=\"http://www.public.iastate.edu/~gdancik/mlegp/\">mlegp: an R package for maximum likelihood estimates for Gaussian processes</a>\n- <a href=\"http://infmath.uibk.ac.at/~matthiasf/imaging2/\">imaging2: the imaging2 class library</a>\n\n@section download Download\n\n- <a href=\"https://github.com/downloads/chokkan/liblbfgs/liblbfgs-1.10.tar.gz\">Source code</a>\n- <a href=\"https://github.com/chokkan/liblbfgs\">GitHub repository</a>\n\nlibLBFGS is distributed under the term of the\n<a href=\"http://opensource.org/licenses/mit-license.php\">MIT license</a>.\n\n@section modules Third-party modules\n- <a href=\"http://cran.r-project.org/web/packages/lbfgs/index.html\">lbfgs: Limited-memory BFGS Optimization (a wrapper for R)</a> maintained by Antonio Coppola.\n- <a href=\"http://search.cpan.org/~laye/Algorithm-LBFGS-0.16/\">Algorithm::LBFGS - Perl extension for L-BFGS</a> maintained by Lei Sun.\n- <a href=\"http://www.cs.kuleuven.be/~bernd/yap-lbfgs/\">YAP-LBFGS (an interface to call libLBFGS from YAP Prolog)</a> maintained by Bernd Gutmann.\n\n@section changelog History\n- Version 1.10 (2010-12-22):\n    - Fixed compiling errors on Mac OS X; this patch was kindly submitted by\n      Nic Schraudolph.\n    - Reduced compiling warnings on Mac OS X; this patch was kindly submitted\n      by Tamas Nepusz.\n    - Replaced memalign() with posix_memalign().\n    - Updated solution and project files for Microsoft Visual Studio 2010.\n- Version 1.9 (2010-01-29):\n    - Fixed a mistake in checking the validity of the parameters \"ftol\" and\n      \"wolfe\"; this was discovered by Kevin S. Van Horn.\n- Version 1.8 (2009-07-13):\n    - Accepted the patch submitted by Takashi Imamichi;\n      the backtracking method now has three criteria for choosing the step\n      length:\n        - ::LBFGS_LINESEARCH_BACKTRACKING_ARMIJO: sufficient decrease (Armijo)\n          condition only\n        - ::LBFGS_LINESEARCH_BACKTRACKING_WOLFE: regular Wolfe condition\n          (sufficient decrease condition + curvature condition)\n        - ::LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE: strong Wolfe condition\n    - Updated the documentation to explain the above three criteria.\n- Version 1.7 (2009-02-28):\n    - Improved OWL-QN routines for stability.\n    - Removed the support of OWL-QN method in MoreThuente algorithm because\n      it accidentally fails in early stages of iterations for some objectives.\n      Because of this change, <b>the OW-LQN method must be used with the\n      backtracking algorithm (::LBFGS_LINESEARCH_BACKTRACKING)</b>, or the\n      library returns ::LBFGSERR_INVALID_LINESEARCH.\n    - Renamed line search algorithms as follows:\n        - ::LBFGS_LINESEARCH_BACKTRACKING: regular Wolfe condition.\n        - ::LBFGS_LINESEARCH_BACKTRACKING_LOOSE: regular Wolfe condition.\n        - ::LBFGS_LINESEARCH_BACKTRACKING_STRONG: strong Wolfe condition.\n    - Source code clean-up.\n- Version 1.6 (2008-11-02):\n    - Improved line-search algorithm with strong Wolfe condition, which was\n      contributed by Takashi Imamichi. This routine is now default for\n      ::LBFGS_LINESEARCH_BACKTRACKING. The previous line search algorithm\n      with regular Wolfe condition is still available as\n      ::LBFGS_LINESEARCH_BACKTRACKING_LOOSE.\n    - Configurable stop index for L1-norm computation. A member variable\n      ::lbfgs_parameter_t::orthantwise_end was added to specify the index\n      number at which the library stops computing the L1 norm of the\n      variables. This is useful to prevent some variables from being\n      regularized by the OW-LQN method.\n    - A sample program written in C++ (sample/sample.cpp).\n- Version 1.5 (2008-07-10):\n    - Configurable starting index for L1-norm computation. A member variable\n      ::lbfgs_parameter_t::orthantwise_start was added to specify the index\n      number from which the library computes the L1 norm of the variables.\n      This is useful to prevent some variables from being regularized by the\n      OWL-QN method.\n    - Fixed a zero-division error when the initial variables have already\n      been a minimizer (reported by Takashi Imamichi). In this case, the\n      library returns ::LBFGS_ALREADY_MINIMIZED status code.\n    - Defined ::LBFGS_SUCCESS status code as zero; removed unused constants,\n      LBFGSFALSE and LBFGSTRUE.\n    - Fixed a compile error in an implicit down-cast.\n- Version 1.4 (2008-04-25):\n    - Configurable line search algorithms. A member variable\n      ::lbfgs_parameter_t::linesearch was added to choose either MoreThuente\n      method (::LBFGS_LINESEARCH_MORETHUENTE) or backtracking algorithm\n      (::LBFGS_LINESEARCH_BACKTRACKING).\n    - Fixed a bug: the previous version did not compute psuedo-gradients\n      properly in the line search routines for OWL-QN. This bug might quit\n      an iteration process too early when the OWL-QN routine was activated\n      (0 < ::lbfgs_parameter_t::orthantwise_c).\n    - Configure script for POSIX environments.\n    - SSE/SSE2 optimizations with GCC.\n    - New functions ::lbfgs_malloc and ::lbfgs_free to use SSE/SSE2 routines\n      transparently. It is uncessary to use these functions for libLBFGS built\n      without SSE/SSE2 routines; you can still use any memory allocators if\n      SSE/SSE2 routines are disabled in libLBFGS.\n- Version 1.3 (2007-12-16):\n    - An API change. An argument was added to lbfgs() function to receive the\n      final value of the objective function. This argument can be set to\n      \\c NULL if the final value is unnecessary.\n    - Fixed a null-pointer bug in the sample code (reported by Takashi Imamichi).\n    - Added build scripts for Microsoft Visual Studio 2005 and GCC.\n    - Added README file.\n- Version 1.2 (2007-12-13):\n    - Fixed a serious bug in orthant-wise L-BFGS.\n      An important variable was used without initialization.\n- Version 1.1 (2007-12-01):\n    - Implemented orthant-wise L-BFGS.\n    - Implemented lbfgs_parameter_init() function.\n    - Fixed several bugs.\n    - API documentation.\n- Version 1.0 (2007-09-20):\n    - Initial release.\n\n@section api Documentation\n\n- @ref liblbfgs_api \"libLBFGS API\"\n\n@section sample Sample code\n\n@include sample.c\n\n@section ack Acknowledgements\n\nThe L-BFGS algorithm is described in:\n    - Jorge Nocedal.\n      Updating Quasi-Newton Matrices with Limited Storage.\n      <i>Mathematics of Computation</i>, Vol. 35, No. 151, pp. 773--782, 1980.\n    - Dong C. Liu and Jorge Nocedal.\n      On the limited memory BFGS method for large scale optimization.\n      <i>Mathematical Programming</i> B, Vol. 45, No. 3, pp. 503-528, 1989.\n\nThe line search algorithms used in this implementation are described in:\n    - John E. Dennis and Robert B. Schnabel.\n      <i>Numerical Methods for Unconstrained Optimization and Nonlinear\n      Equations</i>, Englewood Cliffs, 1983.\n    - Jorge J. More and David J. Thuente.\n      Line search algorithm with guaranteed sufficient decrease.\n      <i>ACM Transactions on Mathematical Software (TOMS)</i>, Vol. 20, No. 3,\n      pp. 286-307, 1994.\n\nThis library also implements Orthant-Wise Limited-memory Quasi-Newton (OWL-QN)\nmethod presented in:\n    - Galen Andrew and Jianfeng Gao.\n      Scalable training of L1-regularized log-linear models.\n      In <i>Proceedings of the 24th International Conference on Machine\n      Learning (ICML 2007)</i>, pp. 33-40, 2007.\n\nSpecial thanks go to:\n    - Yoshimasa Tsuruoka and Daisuke Okanohara for technical information about\n      OWL-QN\n    - Takashi Imamichi for the useful enhancements of the backtracking method\n    - Kevin S. Van Horn, Nic Schraudolph, and Tamas Nepusz for bug fixes\n\nFinally I would like to thank the original author, Jorge Nocedal, who has been\ndistributing the effieicnt and explanatory implementation in an open source\nlicence.\n\n@section reference Reference\n\n- <a href=\"http://www.ece.northwestern.edu/~nocedal/lbfgs.html\">L-BFGS</a> by Jorge Nocedal.\n- <a href=\"http://research.microsoft.com/en-us/downloads/b1eb1016-1738-4bd5-83a9-370c9d498a03/default.aspx\">Orthant-Wise Limited-memory Quasi-Newton Optimizer for L1-regularized Objectives</a> by Galen Andrew.\n- <a href=\"http://chasen.org/~taku/software/misc/lbfgs/\">C port (via f2c)</a> by Taku Kudo.\n- <a href=\"http://www.alglib.net/optimization/lbfgs.php\">C#/C++/Delphi/VisualBasic6 port</a> in ALGLIB.\n- <a href=\"http://cctbx.sourceforge.net/\">Computational Crystallography Toolbox</a> includes\n  <a href=\"http://cctbx.sourceforge.net/current_cvs/c_plus_plus/namespacescitbx_1_1lbfgs.html\">scitbx::lbfgs</a>.\n*/\n", "meta": {"hexsha": "98a3ac9de64daa038e5d82995fcbec4954d75935", "size": 31162, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/include/solver/optimizer/LbfgsSolver.hpp", "max_stars_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_stars_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "solver/include/solver/optimizer/LbfgsSolver.hpp", "max_issues_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "solver/include/solver/optimizer/LbfgsSolver.hpp", "max_forks_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_forks_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 46.0295420975, "max_line_length": 209, "alphanum_fraction": 0.6963609524, "num_tokens": 7714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.034618836722665726, "lm_q1q2_score": 0.01384101440574068}}
{"text": "//=======================================================================\n// Copyright (C) 2005-2009 Jongsoo Park <jongsoo.park -at- gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef BOOST_GRAPH_DOMINATOR_HPP\n#define BOOST_GRAPH_DOMINATOR_HPP\n\n#include <boost/config.hpp>\n#include <deque>\n#include <set>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/concept/assert.hpp>\n\n// Dominator tree computation\n\n// NOTE: This file contains modifications from the distributed Boost version to\n// correctly support supplying a vertex index map to the algorithm. To\n// differentiate it, it has been moved into the boost_ue2 namespace.\n\nnamespace boost_ue2 {\n\n  using namespace boost;\n\n  namespace detail {\n    /**\n     * An extended time_stamper which also records vertices for each dfs number\n     */\n    template<class TimeMap, class VertexVector, class TimeT, class Tag>\n    class time_stamper_with_vertex_vector\n      : public base_visitor<\n      time_stamper_with_vertex_vector<TimeMap, VertexVector, TimeT, Tag> >\n    {\n    public :\n      typedef Tag event_filter;\n      time_stamper_with_vertex_vector(TimeMap timeMap, VertexVector& v,\n                                      TimeT& t)\n        : timeStamper_(timeMap, t), v_(v) { }\n\n      template<class Graph>\n      void\n      operator()(const typename property_traits<TimeMap>::key_type& v,\n                 const Graph& g)\n      {\n        timeStamper_(v, g);\n        v_[timeStamper_.m_time] = v;\n      }\n\n    private :\n      time_stamper<TimeMap, TimeT, Tag> timeStamper_;\n      VertexVector& v_;\n    };\n\n    /**\n     * A convenient way to create a time_stamper_with_vertex_vector\n     */\n    template<class TimeMap, class VertexVector, class TimeT, class Tag>\n    time_stamper_with_vertex_vector<TimeMap, VertexVector, TimeT, Tag>\n    stamp_times_with_vertex_vector(TimeMap timeMap, VertexVector& v, TimeT& t,\n                                   Tag)\n    {\n      return time_stamper_with_vertex_vector<TimeMap, VertexVector, TimeT,\n                                             Tag>(timeMap, v, t);\n    }\n\n    template<class Graph, class IndexMap, class TimeMap, class PredMap,\n             class DomTreePredMap>\n    class dominator_visitor\n    {\n      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n      typedef typename graph_traits<Graph>::vertices_size_type VerticesSizeType;\n\n    public :\n      /**\n       * @param g [in] the target graph of the dominator tree\n       * @param entry [in] the entry node of g\n       * @param indexMap [in] the vertex index map for g\n       * @param domTreePredMap [out] the immediate dominator map\n       *                             (parent map in dominator tree)\n       */\n      dominator_visitor(const Graph& g, const Vertex& entry,\n                        const IndexMap& indexMap,\n                        DomTreePredMap domTreePredMap)\n        : semi_(num_vertices(g)),\n          ancestor_(num_vertices(g), graph_traits<Graph>::null_vertex()),\n          samedom_(ancestor_),\n          best_(semi_),\n          semiMap_(make_iterator_property_map(semi_.begin(),\n                                              indexMap)),\n          ancestorMap_(make_iterator_property_map(ancestor_.begin(),\n                                                  indexMap)),\n          bestMap_(make_iterator_property_map(best_.begin(),\n                                              indexMap)),\n          buckets_(num_vertices(g)),\n          bucketMap_(make_iterator_property_map(buckets_.begin(),\n                                                indexMap)),\n          entry_(entry),\n          domTreePredMap_(domTreePredMap),\n          numOfVertices_(num_vertices(g)),\n          samedomMap(make_iterator_property_map(samedom_.begin(),\n                                                indexMap))\n      {\n      }\n\n      void\n      operator()(const Vertex& n, const TimeMap& dfnumMap,\n                 const PredMap& parentMap, const Graph& g)\n      {\n        if (n == entry_) return;\n\n        const Vertex p(get(parentMap, n));\n        Vertex s(p);\n\n        // 1. Calculate the semidominator of n,\n        // based on the semidominator thm.\n        // * Semidominator thm. : To find the semidominator of a node n,\n        //   consider all predecessors v of n in the CFG (Control Flow Graph).\n        //  - If v is a proper ancestor of n in the spanning tree\n        //    (so dfnum(v) < dfnum(n)), then v is a candidate for semi(n)\n        //  - If v is a non-ancestor of n (so dfnum(v) > dfnum(n))\n        //    then for each u that is an ancestor of v (or u = v),\n        //    Let semi(u) be a candidate for semi(n)\n        //   of all these candidates, the one with lowest dfnum is\n        //   the semidominator of n.\n\n        // For each predecessor of n\n        typename graph_traits<Graph>::in_edge_iterator inItr, inEnd;\n        for (boost::tie(inItr, inEnd) = in_edges(n, g); inItr != inEnd; ++inItr)\n          {\n            const Vertex v = source(*inItr, g);\n            // To deal with unreachable nodes\n            if (get(dfnumMap, v) < 0 || get(dfnumMap, v) >= numOfVertices_)\n              continue;\n\n            Vertex s2;\n            if (get(dfnumMap, v) <= get(dfnumMap, n))\n              s2 = v;\n            else\n              s2 = get(semiMap_, ancestor_with_lowest_semi_(v, dfnumMap));\n\n            if (get(dfnumMap, s2) < get(dfnumMap, s))\n              s = s2;\n          }\n        put(semiMap_, n, s);\n\n        // 2. Calculation of n's dominator is deferred until\n        // the path from s to n has been linked into the forest\n        get(bucketMap_, s).push_back(n);\n        get(ancestorMap_, n) = p;\n        get(bestMap_, n) = n;\n\n        // 3. Now that the path from p to v has been linked into\n        // the spanning forest, these lines calculate the dominator of v,\n        // based on the dominator thm., or else defer the calculation\n        // until y's dominator is known\n        // * Dominator thm. : On the spanning-tree path below semi(n) and\n        //   above or including n, let y be the node\n        //   with the smallest-numbered semidominator. Then,\n        //\n        //  idom(n) = semi(n) if semi(y)=semi(n) or\n        //            idom(y) if semi(y) != semi(n)\n        typename std::deque<Vertex>::iterator buckItr;\n        for (buckItr = get(bucketMap_, p).begin();\n             buckItr != get(bucketMap_, p).end();\n             ++buckItr)\n          {\n            const Vertex v(*buckItr);\n            const Vertex y(ancestor_with_lowest_semi_(v, dfnumMap));\n            if (get(semiMap_, y) == get(semiMap_, v))\n              put(domTreePredMap_, v, p);\n            else\n              put(samedomMap, v, y);\n          }\n\n        get(bucketMap_, p).clear();\n      }\n\n    protected :\n\n      /**\n       * Evaluate function in Tarjan's path compression\n       */\n      const Vertex\n      ancestor_with_lowest_semi_(const Vertex& v, const TimeMap& dfnumMap)\n      {\n        const Vertex a(get(ancestorMap_, v));\n\n        if (get(ancestorMap_, a) != graph_traits<Graph>::null_vertex())\n          {\n            const Vertex b(ancestor_with_lowest_semi_(a, dfnumMap));\n\n            put(ancestorMap_, v, get(ancestorMap_, a));\n\n            if (get(dfnumMap, get(semiMap_, b)) <\n                get(dfnumMap, get(semiMap_, get(bestMap_, v))))\n              put(bestMap_, v, b);\n          }\n\n        return get(bestMap_, v);\n      }\n\n      std::vector<Vertex> semi_, ancestor_, samedom_, best_;\n      PredMap semiMap_, ancestorMap_, bestMap_;\n      std::vector< std::deque<Vertex> > buckets_;\n\n      iterator_property_map<typename std::vector<std::deque<Vertex> >::iterator,\n                            IndexMap> bucketMap_;\n\n      const Vertex& entry_;\n      DomTreePredMap domTreePredMap_;\n      const VerticesSizeType numOfVertices_;\n\n    public :\n\n      PredMap samedomMap;\n    };\n\n  } // namespace detail\n\n  /**\n   * @brief Build dominator tree using Lengauer-Tarjan algorithm.\n   *                It takes O((V+E)log(V+E)) time.\n   *\n   * @pre dfnumMap, parentMap and verticesByDFNum have dfs results corresponding\n   *      indexMap.\n   *      If dfs has already run before,\n   *      this function would be good for saving computations.\n   * @pre Unreachable nodes must be masked as\n   *      graph_traits<Graph>::null_vertex in parentMap.\n   * @pre Unreachable nodes must be masked as\n   *      (std::numeric_limits<VerticesSizeType>::max)() in dfnumMap.\n   *\n   * @param domTreePredMap [out] : immediate dominator map (parent map\n   * in dom. tree)\n   *\n   * @note reference Appel. p. 452~453. algorithm 19.9, 19.10.\n   *\n   * @todo : Optimization in Finding Dominators in Practice, Loukas Georgiadis\n   */\n  template<class Graph, class IndexMap, class TimeMap, class PredMap,\n           class VertexVector, class DomTreePredMap>\n  void\n  lengauer_tarjan_dominator_tree_without_dfs\n    (const Graph& g,\n     const typename graph_traits<Graph>::vertex_descriptor& entry,\n     const IndexMap& indexMap,\n     TimeMap dfnumMap, PredMap parentMap, VertexVector& verticesByDFNum,\n     DomTreePredMap domTreePredMap)\n  {\n    // Typedefs and concept check\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::vertices_size_type VerticesSizeType;\n\n    BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph> ));\n\n    const VerticesSizeType numOfVertices = num_vertices(g);\n    if (numOfVertices == 0) return;\n\n    // 1. Visit each vertex in reverse post order and calculate sdom.\n    detail::dominator_visitor<Graph, IndexMap, TimeMap, PredMap, DomTreePredMap>\n      visitor(g, entry, indexMap, domTreePredMap);\n\n    VerticesSizeType i;\n    for (i = 0; i < numOfVertices; ++i)\n      {\n        const Vertex u(verticesByDFNum[numOfVertices - 1 - i]);\n        if (u != graph_traits<Graph>::null_vertex())\n          visitor(u, dfnumMap, parentMap, g);\n      }\n\n    // 2. Now all the deferred dominator calculations,\n    // based on the second clause of the dominator thm., are performed\n    for (i = 0; i < numOfVertices; ++i)\n      {\n        const Vertex n(verticesByDFNum[i]);\n\n        if (n == entry || n == graph_traits<Graph>::null_vertex())\n          continue;\n\n        Vertex u = get(visitor.samedomMap, n);\n        if (u != graph_traits<Graph>::null_vertex())\n          {\n            put(domTreePredMap, n, get(domTreePredMap, u));\n          }\n      }\n  }\n\n  /**\n   * Unlike lengauer_tarjan_dominator_tree_without_dfs,\n   * dfs is run in this function and\n   * the result is written to dfnumMap, parentMap, vertices.\n   *\n   * If the result of dfs required after this algorithm,\n   * this function can eliminate the need of rerunning dfs.\n   */\n  template<class Graph, class IndexMap, class TimeMap, class PredMap,\n           class VertexVector, class DomTreePredMap>\n  void\n  lengauer_tarjan_dominator_tree\n    (const Graph& g,\n     const typename graph_traits<Graph>::vertex_descriptor& entry,\n     const IndexMap& indexMap,\n     TimeMap dfnumMap, PredMap parentMap, VertexVector& verticesByDFNum,\n     DomTreePredMap domTreePredMap)\n  {\n    // Typedefs and concept check\n    typedef typename graph_traits<Graph>::vertices_size_type VerticesSizeType;\n\n    BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph> ));\n\n    // 1. Depth first visit\n    const VerticesSizeType numOfVertices = num_vertices(g);\n    if (numOfVertices == 0) return;\n\n    VerticesSizeType time =\n      (std::numeric_limits<VerticesSizeType>::max)();\n    std::vector<default_color_type>\n      colors(numOfVertices, color_traits<default_color_type>::white());\n    depth_first_visit\n      (g, entry,\n       make_dfs_visitor\n         (make_pair(record_predecessors(parentMap, on_tree_edge()),\n                    detail::stamp_times_with_vertex_vector\n                      (dfnumMap, verticesByDFNum, time, on_discover_vertex()))),\n       make_iterator_property_map(colors.begin(), indexMap));\n\n    // 2. Run main algorithm.\n    lengauer_tarjan_dominator_tree_without_dfs(g, entry, indexMap, dfnumMap,\n                                               parentMap, verticesByDFNum,\n                                               domTreePredMap);\n  }\n\n  /**\n   * Use vertex_index as IndexMap and make dfnumMap, parentMap, verticesByDFNum\n   * internally.\n   * If we don't need the result of dfs (dfnumMap, parentMap, verticesByDFNum),\n   * this function would be more convenient one.\n   */\n  template<class Graph, class DomTreePredMap>\n  void\n  lengauer_tarjan_dominator_tree\n    (const Graph& g,\n     const typename graph_traits<Graph>::vertex_descriptor& entry,\n     DomTreePredMap domTreePredMap)\n  {\n    // typedefs\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::vertices_size_type VerticesSizeType;\n    typedef typename property_map<Graph, vertex_index_t>::const_type IndexMap;\n    typedef\n      iterator_property_map<typename std::vector<VerticesSizeType>::iterator,\n                            IndexMap> TimeMap;\n    typedef\n      iterator_property_map<typename std::vector<Vertex>::iterator, IndexMap>\n      PredMap;\n\n    // Make property maps\n    const VerticesSizeType numOfVertices = num_vertices(g);\n    if (numOfVertices == 0) return;\n\n    const IndexMap indexMap = get(vertex_index, g);\n\n    std::vector<VerticesSizeType> dfnum(numOfVertices, 0);\n    TimeMap dfnumMap(make_iterator_property_map(dfnum.begin(), indexMap));\n\n    std::vector<Vertex> parent(numOfVertices,\n                               graph_traits<Graph>::null_vertex());\n    PredMap parentMap(make_iterator_property_map(parent.begin(), indexMap));\n\n    std::vector<Vertex> verticesByDFNum(parent);\n\n    // Run main algorithm\n    lengauer_tarjan_dominator_tree(g, entry,\n                                   indexMap, dfnumMap, parentMap,\n                                   verticesByDFNum, domTreePredMap);\n  }\n\n  /**\n   * Muchnick. p. 182, 184\n   *\n   * using iterative bit vector analysis\n   */\n  template<class Graph, class IndexMap, class DomTreePredMap>\n  void\n  iterative_bit_vector_dominator_tree\n    (const Graph& g,\n     const typename graph_traits<Graph>::vertex_descriptor& entry,\n     const IndexMap& indexMap,\n     DomTreePredMap domTreePredMap)\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::vertex_iterator vertexItr;\n    typedef typename graph_traits<Graph>::vertices_size_type VerticesSizeType;\n    typedef\n      iterator_property_map<typename std::vector< std::set<Vertex> >::iterator,\n                            IndexMap> vertexSetMap;\n\n    BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph> ));\n\n    // 1. Finding dominator\n    // 1.1. Initialize\n    const VerticesSizeType numOfVertices = num_vertices(g);\n    if (numOfVertices == 0) return;\n\n    vertexItr vi, viend;\n    boost::tie(vi, viend) = vertices(g);\n    const std::set<Vertex> N(vi, viend);\n\n    bool change = true;\n\n    std::vector< std::set<Vertex> > dom(numOfVertices, N);\n    vertexSetMap domMap(make_iterator_property_map(dom.begin(), indexMap));\n    get(domMap, entry).clear();\n    get(domMap, entry).insert(entry);\n\n    while (change)\n      {\n        change = false;\n        for (boost::tie(vi, viend) = vertices(g); vi != viend; ++vi)\n          {\n            if (*vi == entry) continue;\n\n            std::set<Vertex> T(N);\n\n            typename graph_traits<Graph>::in_edge_iterator inItr, inEnd;\n            for (boost::tie(inItr, inEnd) = in_edges(*vi, g); inItr != inEnd; ++inItr)\n              {\n                const Vertex p = source(*inItr, g);\n\n                std::set<Vertex> tempSet;\n                std::set_intersection(T.begin(), T.end(),\n                                      get(domMap, p).begin(),\n                                      get(domMap, p).end(),\n                                      std::inserter(tempSet, tempSet.begin()));\n                T.swap(tempSet);\n              }\n\n            T.insert(*vi);\n            if (T != get(domMap, *vi))\n              {\n                change = true;\n                get(domMap, *vi).swap(T);\n              }\n          } // end of for (boost::tie(vi, viend) = vertices(g)\n      } // end of while(change)\n\n    // 2. Build dominator tree\n    for (boost::tie(vi, viend) = vertices(g); vi != viend; ++vi)\n      get(domMap, *vi).erase(*vi);\n\n    Graph domTree(numOfVertices);\n\n    for (boost::tie(vi, viend) = vertices(g); vi != viend; ++vi)\n      {\n        if (*vi == entry) continue;\n\n        // We have to iterate through copied dominator set\n        const std::set<Vertex> tempSet(get(domMap, *vi));\n        typename std::set<Vertex>::const_iterator s;\n        for (s = tempSet.begin(); s != tempSet.end(); ++s)\n          {\n            typename std::set<Vertex>::iterator t;\n            for (t = get(domMap, *vi).begin(); t != get(domMap, *vi).end(); )\n              {\n        typename std::set<Vertex>::iterator old_t = t;\n        ++t; // Done early because t may become invalid\n                if (*old_t == *s) continue;\n                if (get(domMap, *s).find(*old_t) != get(domMap, *s).end())\n                  get(domMap, *vi).erase(old_t);\n              }\n          }\n      }\n\n    for (boost::tie(vi, viend) = vertices(g); vi != viend; ++vi)\n      {\n        if (*vi != entry && get(domMap, *vi).size() == 1)\n          {\n            Vertex temp = *get(domMap, *vi).begin();\n            put(domTreePredMap, *vi, temp);\n          }\n      }\n  }\n\n  template<class Graph, class DomTreePredMap>\n  void\n  iterative_bit_vector_dominator_tree\n    (const Graph& g,\n     const typename graph_traits<Graph>::vertex_descriptor& entry,\n     DomTreePredMap domTreePredMap)\n  {\n    typename property_map<Graph, vertex_index_t>::const_type\n      indexMap = get(vertex_index, g);\n\n    iterative_bit_vector_dominator_tree(g, entry, indexMap, domTreePredMap);\n  }\n} // namespace boost\n\n#endif // BOOST_GRAPH_DOMINATOR_HPP\n", "meta": {"hexsha": "c8b15886b45e2b1fdc4213ab1eed81275ce66322", "size": 18042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost-patched/graph/dominator_tree.hpp", "max_stars_repo_name": "Mic92/hyperscan", "max_stars_repo_head_hexsha": "64a995bf445d86b74eb0f375624ffc85682eadfe", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 2868.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T02:25:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:24:16.000Z", "max_issues_repo_path": "include/boost-patched/graph/dominator_tree.hpp", "max_issues_repo_name": "Mic92/hyperscan", "max_issues_repo_head_hexsha": "64a995bf445d86b74eb0f375624ffc85682eadfe", "max_issues_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_issues_count": 270.0, "max_issues_repo_issues_event_min_datetime": "2017-10-30T19:53:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:03:17.000Z", "max_forks_repo_path": "include/boost-patched/graph/dominator_tree.hpp", "max_forks_repo_name": "Mic92/hyperscan", "max_forks_repo_head_hexsha": "64a995bf445d86b74eb0f375624ffc85682eadfe", "max_forks_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_forks_count": 403.0, "max_forks_repo_forks_event_min_datetime": "2017-11-02T01:18:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T08:46:20.000Z", "avg_line_length": 35.9402390438, "max_line_length": 86, "alphanum_fraction": 0.6027602261, "num_tokens": 4369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.04401865284146195, "lm_q1q2_score": 0.013824081914666298}}
{"text": "//\r\n//=======================================================================\r\n// Copyright 2012 Fernando Vilas\r\n//           2010 Daniel Trebbien\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\r\n// The maximum adjacency search algorithm was originally part of the\r\n// Stoer-Wagner min cut implementation by Daniel Trebbien. It has been\r\n// broken out into its own file to be a public search algorithm, with\r\n// visitor concepts.\r\n#ifndef BOOST_GRAPH_MAXIMUM_ADJACENCY_SEARCH_H\r\n#define BOOST_GRAPH_MAXIMUM_ADJACENCY_SEARCH_H\r\n\r\n/**\r\n * This is an implementation of the maximum adjacency search on an\r\n * undirected graph. It allows a visitor object to perform some\r\n * operation on each vertex as that vertex is visited.\r\n *\r\n * The algorithm runs as follows:\r\n *\r\n * Initialize all nodes to be unvisited (reach count = 0)\r\n *   and call vis.initialize_vertex\r\n * For i = number of nodes in graph downto 1\r\n *   Select the unvisited node with the highest reach count\r\n *     The user provides the starting node to break the first tie,\r\n *     but future ties are broken arbitrarily\r\n *   Visit the node by calling vis.start_vertex\r\n *   Increment the reach count for all unvisited neighbors\r\n *     and call vis.examine_edge for each of these edges\r\n *   Mark the node as visited and call vis.finish_vertex\r\n *\r\n */\r\n\r\n#include <boost/concept_check.hpp>\r\n#include <boost/concept/assert.hpp>\r\n#include <boost/graph/buffer_concepts.hpp>\r\n#include <boost/graph/exception.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/graph/visitors.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n\r\n#include <set>\r\n\r\nnamespace boost {\r\n  template <class Visitor, class Graph>\r\n  struct MASVisitorConcept {\r\n    void constraints() {\r\n      boost::function_requires< boost::CopyConstructibleConcept<Visitor> >();\r\n      vis.initialize_vertex(u, g);\r\n      vis.start_vertex(u, g);\r\n      vis.examine_edge(e, g);\r\n      vis.finish_vertex(u, g);\r\n    }\r\n    Visitor vis;\r\n    Graph g;\r\n    typename boost::graph_traits<Graph>::vertex_descriptor u;\r\n    typename boost::graph_traits<Graph>::edge_descriptor e;\r\n  };\r\n\r\n  template <class Visitors = null_visitor>\r\n  class mas_visitor {\r\n  public:\r\n    mas_visitor() { }\r\n    mas_visitor(Visitors vis) : m_vis(vis) { }\r\n\r\n    template <class Vertex, class Graph>\r\n    void\r\n    initialize_vertex(Vertex u, Graph& g)\r\n    {\r\n      invoke_visitors(m_vis, u, g, ::boost::on_initialize_vertex());\r\n    }\r\n\r\n    template <class Vertex, class Graph>\r\n    void\r\n    start_vertex(Vertex u, Graph& g)\r\n    {\r\n      invoke_visitors(m_vis, u, g, ::boost::on_start_vertex());\r\n    }\r\n\r\n    template <class Edge, class Graph>\r\n    void\r\n    examine_edge(Edge e, Graph& g)\r\n    {\r\n      invoke_visitors(m_vis, e, g, ::boost::on_examine_edge());\r\n    }\r\n\r\n    template <class Vertex, class Graph>\r\n    void\r\n    finish_vertex(Vertex u, Graph& g)\r\n    {\r\n      invoke_visitors(m_vis, u, g, ::boost::on_finish_vertex());\r\n    }\r\n\r\n    BOOST_GRAPH_EVENT_STUB(on_initialize_vertex,mas)\r\n    BOOST_GRAPH_EVENT_STUB(on_start_vertex,mas)\r\n    BOOST_GRAPH_EVENT_STUB(on_examine_edge,mas)\r\n    BOOST_GRAPH_EVENT_STUB(on_finish_vertex,mas)\r\n\r\n  protected:\r\n    Visitors m_vis;\r\n  };\r\n  template <class Visitors>\r\n  mas_visitor<Visitors>\r\n  make_mas_visitor(Visitors vis) {\r\n    return mas_visitor<Visitors>(vis);\r\n  }\r\n  typedef mas_visitor<> default_mas_visitor;\r\n\r\n  namespace detail {\r\n    template <class Graph, class WeightMap, class MASVisitor, class VertexAssignmentMap, class KeyedUpdatablePriorityQueue>\r\n      void\r\n      maximum_adjacency_search(const Graph& g, WeightMap weights, MASVisitor vis, const typename boost::graph_traits<Graph>::vertex_descriptor start, VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue pq) {\r\n      typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n      typedef typename boost::property_traits<WeightMap>::value_type weight_type;\r\n\r\n     std::set<vertex_descriptor> assignedVertices;\r\n\r\n     // initialize `assignments` (all vertices are initially\r\n     // assigned to themselves)\r\n     BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n       put(assignments, v, v);\r\n     }\r\n\r\n      typename KeyedUpdatablePriorityQueue::key_map keys = pq.keys();\r\n\r\n      // set number of visited neighbors for all vertices to 0\r\n      BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n        if (v == get(assignments, v)) { // foreach u \\in V do\r\n          put(keys, v, weight_type(0));          vis.initialize_vertex(v, g);\r\n\r\n          pq.push(v);\r\n        }\r\n      }\r\n      BOOST_ASSERT(pq.size() >= 2);\r\n\r\n      // Give the starting vertex high priority\r\n      put(keys, start, get(keys, start) + num_vertices(g) + 1);\r\n      pq.update(start);\r\n\r\n      // start traversing the graph\r\n      //vertex_descriptor s, t;\r\n      weight_type w;\r\n      while (!pq.empty()) { // while PQ \\neq {} do\r\n        const vertex_descriptor u = pq.top(); // u = extractmax(PQ)\r\n        w = get(keys, u);                        vis.start_vertex(u, g);\r\n        pq.pop();                  //            vis.start_vertex(u, g);\r\n\r\n        BGL_FORALL_OUTEDGES_T(u, e, g, Graph) { // foreach (u, v) \\in E do\r\n                                                 vis.examine_edge(e, g);\r\n\r\n          const vertex_descriptor v = get(assignments, target(e, g));\r\n\r\n          if (pq.contains(v)) { // if v \\in PQ then\r\n            put(keys, v, get(keys, v) + get(weights, e)); // increasekey(PQ, v, wA(v) + w(u, v))\r\n            pq.update(v);\r\n          }\r\n        }\r\n\r\n        typename std::set<vertex_descriptor>::const_iterator assignedVertexIt, assignedVertexEnd = assignedVertices.end();\r\n        for (assignedVertexIt = assignedVertices.begin(); assignedVertexIt != assignedVertexEnd; ++assignedVertexIt) {\r\n          const vertex_descriptor uPrime = *assignedVertexIt;\r\n\r\n          if (get(assignments, uPrime) == u) {\r\n            BGL_FORALL_OUTEDGES_T(uPrime, e, g, Graph) { // foreach (u, v) \\in E do\r\n                                                 vis.examine_edge(e, g);\r\n\r\n              const vertex_descriptor v = get(assignments, target(e, g));\r\n\r\n              if (pq.contains(v)) { // if v \\in PQ then\r\n                put(keys, v, get(keys, v) + get(weights, e)); // increasekey(PQ, v, wA(v) + w(u, v))\r\n                pq.update(v);\r\n              }\r\n            }\r\n          }\r\n        }\r\n                                                 vis.finish_vertex(u, g);\r\n      }\r\n    }\r\n  } // end namespace detail\r\n\r\n  template <class Graph, class WeightMap, class MASVisitor, class VertexAssignmentMap, class KeyedUpdatablePriorityQueue>\r\n    void\r\nmaximum_adjacency_search(const Graph& g, WeightMap weights, MASVisitor vis, const typename boost::graph_traits<Graph>::vertex_descriptor start, VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue pq) {\r\n    BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<Graph>));\r\n    BOOST_CONCEPT_ASSERT((boost::VertexListGraphConcept<Graph>));\r\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename boost::graph_traits<Graph>::vertices_size_type vertices_size_type;\r\n    typedef typename boost::graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n    BOOST_CONCEPT_ASSERT((boost::Convertible<typename boost::graph_traits<Graph>::directed_category, boost::undirected_tag>));\r\n    BOOST_CONCEPT_ASSERT((boost::ReadablePropertyMapConcept<WeightMap, edge_descriptor>));\r\n    // typedef typename boost::property_traits<WeightMap>::value_type weight_type;\r\n    boost::function_requires< MASVisitorConcept<MASVisitor, Graph> >();\r\n    BOOST_CONCEPT_ASSERT((boost::ReadWritePropertyMapConcept<VertexAssignmentMap, vertex_descriptor>));\r\n    BOOST_CONCEPT_ASSERT((boost::Convertible<vertex_descriptor, typename boost::property_traits<VertexAssignmentMap>::value_type>));\r\n    BOOST_CONCEPT_ASSERT((boost::KeyedUpdatableQueueConcept<KeyedUpdatablePriorityQueue>));\r\n\r\n    vertices_size_type n = num_vertices(g);\r\n    if (n < 2)\r\n      throw boost::bad_graph(\"the input graph must have at least two vertices.\");\r\n    else if (!pq.empty())\r\n      throw std::invalid_argument(\"the max-priority queue must be empty initially.\");\r\n\r\n    detail::maximum_adjacency_search(g, weights,\r\n                                            vis, start,\r\n                                            assignments, pq);\r\n  }\r\n\r\n  namespace graph {\r\n    namespace detail {\r\n      template <typename WeightMap>\r\n      struct mas_dispatch {\r\n        typedef void result_type;\r\n        template <typename Graph, typename ArgPack>\r\n        static result_type apply(const Graph& g, \r\n                          //const bgl_named_params<P,T,R>& params, \r\n                          const ArgPack& params, \r\n                          WeightMap w) {\r\n\r\n          using namespace boost::graph::keywords;\r\n          typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n          typedef typename WeightMap::value_type weight_type;\r\n\r\n          typedef boost::detail::make_priority_queue_from_arg_pack_gen<boost::graph::keywords::tag::max_priority_queue, weight_type, vertex_descriptor, std::greater<weight_type> > default_pq_gen_type;\r\n\r\n          default_pq_gen_type pq_gen(choose_param(get_param(params, boost::distance_zero_t()), weight_type(0)));\r\n\r\n          typename boost::result_of<default_pq_gen_type(const Graph&, const ArgPack&)>::type pq = pq_gen(g, params);\r\n\r\n          boost::maximum_adjacency_search\r\n               (g,\r\n                w,\r\n                params [ _visitor | make_mas_visitor(null_visitor())],\r\n                params [ _root_vertex | *vertices(g).first],\r\n                params [ _vertex_assignment_map | boost::detail::make_property_map_from_arg_pack_gen<boost::graph::keywords::tag::vertex_assignment_map, vertex_descriptor>(vertex_descriptor())(g, params)],\r\n                pq\r\n                );\r\n        }\r\n      };\r\n\r\n      template <>\r\n      struct mas_dispatch<boost::param_not_found> {\r\n        typedef void result_type;\r\n\r\n        template <typename Graph, typename ArgPack>\r\n        static result_type apply(const Graph& g, \r\n                          const ArgPack& params, \r\n                          param_not_found) {\r\n\r\n          using namespace boost::graph::keywords;\r\n          typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n\r\n          // get edge_weight_t as the weight type\r\n          typedef typename boost::property_map<Graph, edge_weight_t> WeightMap;\r\n          typedef typename WeightMap::value_type weight_type;\r\n\r\n          typedef boost::detail::make_priority_queue_from_arg_pack_gen<boost::graph::keywords::tag::max_priority_queue, weight_type, vertex_descriptor, std::greater<weight_type> > default_pq_gen_type;\r\n\r\n          default_pq_gen_type pq_gen(choose_param(get_param(params, boost::distance_zero_t()), weight_type(0)));\r\n\r\n          typename boost::result_of<default_pq_gen_type(const Graph&, const ArgPack&)>::type pq = pq_gen(g, params);\r\n\r\n          boost::maximum_adjacency_search\r\n               (g,\r\n                get(edge_weight, g),\r\n                params [ _visitor | make_mas_visitor(null_visitor())],\r\n                params [ _root_vertex | *vertices(g).first],\r\n                params [ _vertex_assignment_map | boost::detail::make_property_map_from_arg_pack_gen<boost::graph::keywords::tag::vertex_assignment_map, vertex_descriptor>(vertex_descriptor())(g, params)],\r\n                pq\r\n                );\r\n        }\r\n      };\r\n    } // end namespace detail\r\n  } // end namespace graph\r\n\r\n  // Named parameter interface\r\n  //BOOST_GRAPH_MAKE_OLD_STYLE_PARAMETER_FUNCTION(maximum_adjacency_search, 1)\r\n  template <typename Graph, typename P, typename T, typename R>\r\n  void\r\n  maximum_adjacency_search (const Graph& g,\r\n      const bgl_named_params<P,T,R>& params) {\r\n\r\n    typedef bgl_named_params<P, T, R> params_type;\r\n    BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)\r\n\r\n    // do the dispatch based on WeightMap\r\n    typedef typename get_param_type<edge_weight_t, bgl_named_params<P,T,R> >::type W;\r\n    graph::detail::mas_dispatch<W>::apply(g, arg_pack, get_param(params, edge_weight));\r\n  }\r\n\r\n  namespace graph {\r\n    namespace detail {\r\n      template <typename Graph>\r\n      struct maximum_adjacency_search_impl {\r\n        typedef void result_type;\r\n\r\n        template <typename ArgPack>\r\n        void\r\n        operator() (const Graph& g, const ArgPack& arg_pack) const {\r\n          // call the function that does the dispatching\r\n          typedef typename get_param_type<edge_weight_t, ArgPack >::type W;\r\n          graph::detail::mas_dispatch<W>::apply(g, arg_pack, get_param(arg_pack, edge_weight));\r\n        }\r\n      };\r\n    } // end namespace detail\r\n    BOOST_GRAPH_MAKE_FORWARDING_FUNCTION(maximum_adjacency_search,1,5)\r\n  } // end namespace graph\r\n\r\n} // end namespace boost\r\n\r\n#include <boost/graph/iteration_macros_undef.hpp>\r\n\r\n#endif // BOOST_GRAPH_MAXIMUM_ADJACENCY_SEARCH_H\r\n", "meta": {"hexsha": "8d7291df04048f437648f3d941650d003df76649", "size": 13275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/maximum_adjacency_search.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/maximum_adjacency_search.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/maximum_adjacency_search.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 41.484375, "max_line_length": 217, "alphanum_fraction": 0.6453483992, "num_tokens": 2887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.03963883626471279, "lm_q1q2_score": 0.013819886897450707}}
{"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) 2015-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\n#ifndef VTKWRITER_HH\n#define VTKWRITER_HH\n\n#include <algorithm>\n#include <cstring>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <memory> \n#include <sstream>\n#include <type_traits>\n#include <vector>\n\n#include <boost/fusion/include/zip.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <dune/grid/common/grid.hh>\n#include <dune/geometry/referenceelements.hh>\n\n#include \"io/iobase.hh\"\n#include \"utilities/detailed_exception.hh\"\n#undef min\n\n\n\n\n\nnamespace Kaskade\n{\n  /**\n   * \\cond internals\n   */\n\n  namespace FunctionSpace_Detail {\n    // forward declaration\n    template <class> class ToDomainRepresentation;\n  }\n\n  namespace VTKWriterDetail\n  {\n    // returns the textual VTK notation of this system's endianness.\n    std::string vtkEndianness();\n    \n    enum VTKGeometryType\n    {\n      vtkLine = 3,\n      vtkTriangle = 5,\n      vtkQuadrilateral = 9,\n      vtkTetrahedron = 10,\n      vtkHexahedron = 12,\n      vtkPrism = 13,\n      vtkPyramid = 14,\n      vtkquadLine = 21,\n      vtkquadTriangle = 22,\n      vtkquadQuadrilateral = 23,\n      vtkquadTetrahedron = 24,\n      vtkquadHexahedron = 25,\n    };\n    \n    //! mapping from GeometryType to VTKGeometryType\n    VTKGeometryType vtkType(Dune::GeometryType const& t, int order);\n    \n    /**\n     * \\brief Returns the subentity number and codimension for any VTK point in a cell.\n     */\n    std::pair<int,int> vtkPointToDune(Dune::GeometryType const& type, int vtkPoint);\n    \n\n    // forward declaration\n    class Base64Writer;\n    \n    //! base class for VTK data array writers\n    // T  is a scalar type (float,double,int,...)\n    template <class T>\n    class VTKDataArrayWriter\n    {\n    public:\n    /** \n     * @brief Constructor.\n     * \n     * @param s           The stream to write to\n     * @param outputType  ASCII or binary\n     * @param name        The name of the vtk array\n     * \\param ncomps      number of vectorial components (1 or 3)\n     * @param entries     the number of data entries to write\n     */\n      VTKDataArrayWriter(std::ostream &s, IoOptions::OutputType outputType, std::string const& name, int ncomps,\n                         size_t entries, int indentCount, int precision);\n      \n      //! write one data element\n      template <int m>\n      void write (Dune::FieldVector<T,m> const&);\n      \n      void write(T);\n      \n      //!  destructor\n      ~VTKDataArrayWriter();\n      \n    private:\n      std::ostream& s;\n      IoOptions::OutputType outputType;\n      int ncomps;\n      int counter;\n      int numPerLine;\n      int indentCount;\n      int precision;\n      std::unique_ptr<Base64Writer> base64;\n    };\n \n    // ---------------------------------------------------------------------------\n\n    //! write indentation to stream\n    void indent(std::ostream& s, int indentCount);\n    \n    /// This gathers some information about the grid and supports the output of the grid\n    template <class GridView> \n    struct VTKGridInfo\n    {\n      using Cell         = typename GridView::template Codim<0>::Entity;\n      using IndexSet     = typename GridView::IndexSet;\n      using CellIterator = typename GridView::template Codim<0>::Iterator;\n      \n      static int constexpr dim = GridView::dimension;\n      \n      \n      VTKGridInfo(GridView const& gridView_, IoOptions const& options_)\n      : gridView(gridView_),\n        cells(gridView.template begin<0>(),gridView.template end<0>()),\n        ncells(gridView.size(0)),\n        options(options_)\n      {        \n        // For counting the corners (i.e. all corners of all cells) we step through the \n        // cells and count their respective corners (and edges for order two). This is \n        // general enough to treat mixed grids containing different cell types.\n        ncorners = 0;\n        for (auto const& cell: cells) \n        {\n          ncorners += cell.subEntities(dim);\n          if (options.order==2)\n            ncorners += cell.subEntities(dim-1);\n        }\n        \n        // In conforming mode, the number of points is just the number of vertices \n        // (plus edges for oder two). Otherwise, points and corners coincide.\n        if (options.dataMode==IoOptions::conforming)\n        {\n          npoints = gridView.size(dim);\n          if (options.order==2)\n            npoints += gridView.size(dim-1);\n        }\n        else\n          npoints = ncorners;\n      }\n      \n      // returns entity center coordinates\n      template <class Cell>\n      auto center(Cell const& cell, int subindex, int codim) const\n      {\n        return Dune::ReferenceElements<typename GridView::ctype,dim>::general(cell.type()).position(subindex,codim);\n      }\n      \n      // returns a globally unique index for vertices and edges in conforming mode. \n      // Vertices come first, then edges.\n      template <class Cell>\n      int conformingIndex(Cell const& cell, int subindex, int codim) const\n      {\n        // due to the sorting vertices first then edges there is no need to switch between order 1 and 2\n        if (codim==dim)\n          return gridView.indexSet().subIndex(cell,subindex,codim);\n        else\n          return gridView.size(dim) + gridView.indexSet().subIndex(cell,subindex,codim);\n      }\n      \n      // Writes the point coordinates to the VTK XML stream\n      void writeGridPoints (int indentCount, std::ostream& s) const\n      {\n        VTKDataArrayWriter<typename GridView::ctype> p(s, options.outputType, \"Coordinates\", 3, npoints, indentCount, options.precision); \n        \n        if (options.dataMode==IoOptions::conforming)\n        {\n          std::vector<Dune::FieldVector<typename GridView::ctype,GridView::dimensionworld>> xs(npoints);\n          for (auto const& cell: cells)\n          {\n            for (int corner=0; corner<cell.subEntities(dim); ++corner)   // global coordinates of all corners\n              xs[conformingIndex(cell,corner,dim)] = cell.geometry().corner(corner); \n            \n            if (options.order == 2)\n              for (int edge=0; edge<cell.subEntities(dim-1); ++edge)     // global coordinates of all edges\n                xs[conformingIndex(cell,edge,dim-1)] = cell.geometry().global(center(cell,edge,dim-1));\n          }\n          \n          for (auto const& x: xs)\n            p.write(x);\n        }\n        else // nonconforming\n        {\n          for (auto const& cell: cells)\n          {\n            for (int corner=0; corner<cell.subEntities(dim); ++corner)\n              p.write(cell.geometry().corner(corner));\n            \n            if (options.order == 2)\n              for (int edge=0; edge<cell.subEntities(dim-1); ++edge)\n                p.write(cell.geometry().global(center(cell,edge,dim-1)));\n          }\n        }\n      }\n      \n      void writeGridCells (int indentCount, std::ostream& s) const\n      {\n        // connectivity\n        auto p1 = std::make_unique<VTKDataArrayWriter<int>>(s, options.outputType, \"connectivity\", 1, ncorners, indentCount, options.precision);\n        \n        int offset = 0;\n        std::vector<int> offsets; offsets.reserve(ncells);\n        for (auto const& cell: cells)                                             // step through all cells\n        {\n          int const numCorners = cell.subEntities(dim);\n          int const numEdges = cell.subEntities(dim-1);\n          int const numPoints = numCorners + (options.order==2? numEdges: 0);\n          \n          for (int vtkPoint=0; vtkPoint<numPoints; ++vtkPoint)                   // visit each point in that cell\n          {\n            auto subentity = vtkPointToDune(cell.type(),vtkPoint);               // and find its Dune coordinates\n            p1->write( options.dataMode==IoOptions::conforming?\n                          conformingIndex(cell,subentity.first,subentity.second):\n                          offset + (subentity.second==dim? 0: numCorners) + subentity.first );\n          }\n          offset += numPoints;                                                   // in nonconforming mode, the points are stored blockwise,\n          offsets.push_back(offset);\n        }                                                                        // cell by cell, just advance the offset\n        p1.reset(); // write end tag on destruction\n        \n        // write offsets\n        auto p2 = std::make_unique<VTKDataArrayWriter<int>>(s, options.outputType, \"offsets\", 1, ncells, indentCount, options.precision);\n        for (int off: offsets)\n          p2->write(off);\n        p2.reset(); // write end tag on destruction\n        \n        // types only if dimension greater than 1 - there is only one 1D cell type: line\n        if (dim>1)\n        {\n          VTKDataArrayWriter<unsigned char> p(s, options.outputType, \"types\", 1, ncells, indentCount, options.precision);\n          for (auto const& cell: cells)\n            p.write(static_cast<unsigned char>(vtkType(cell.type(),options.order)));\n        }\n      }\n    \n    \n      GridView const& gridView;\n      boost::iterator_range<CellIterator> cells;\n      size_t ncorners;\n      size_t npoints;\n      size_t ncells;\n      IoOptions const& options;\n    };\n    \n    \n    // ----------------------------------------------------------------------------------------\n\n    \n    template <class GridView, class Function, class Names>\n    void writeCellData (VTKGridInfo<GridView> const& gridInfo, Function const& pair, Names const& names, int indentCount, std::ostream& s)\n    {\n      auto const& f = boost::fusion::at_c<0>(pair);\n      \n      // Check whether this is best represented as cell data: only if it is (piecewise) constant.\n      if (f.space().mapper().maxOrder() > 0)\n        return;\n      \n      auto varDesc = boost::fusion::at_c<1>(pair);\n      VTKDataArrayWriter<double> p(s, gridInfo.options.outputType, names[varDesc.id], varDesc.m, gridInfo.ncells, indentCount, gridInfo.options.precision);\n      for (auto const& cell: gridInfo.cells)\n        p.write(f.value(cell,gridInfo.center(cell,0,0)));\n    }\n    \n    \n    \n    template <class GridView, class Function, class Names>\n    void writeVertexData (VTKGridInfo<GridView> const& gridInfo, Function const& pair, Names const& names, int indentCount, std::ostream& s)\n    {\n      auto const& f = boost::fusion::at_c<0>(pair);\n      using ValueType = typename std::remove_reference_t<typename boost::fusion::result_of::value_at_c<Function,0>::type>::ValueType;\n      constexpr int dim = GridView::dimension;\n     \n     // Check whether this is best represented as vertex data: only if it is not (piecewise) constant.\n      if (f.space().mapper().maxOrder() == 0)\n        return;\n\n      auto varDesc = boost::fusion::at_c<1>(pair);\n      VTKDataArrayWriter<double> p(s, gridInfo.options.outputType, names[varDesc.id], varDesc.m, gridInfo.npoints, indentCount, gridInfo.options.precision);\n      \n      if (gridInfo.options.dataMode==Kaskade::IoOptions::conforming)\n      {\n        std::vector<ValueType> fs(gridInfo.npoints,ValueType(0.0));   // function values, in conforming mode average over multiple points\n        std::vector<short> count(gridInfo.npoints,0);                  // count how many points contribute to an entity\n\n        // TODO: Currently boundary FE functions are zero on cells which only touch the boundary by one vertex (or edge in 3D). This will lead to unwanted results when values are averaged.\n        // Therefore, we use the following two lines to transform boundary FE functions to continuous FE functions over the whole domain, then averaging works as expected.\n        // Remove this when not necessary any longer. (And also delete ToDomainRepresetation from functionspace.hh)\n        FunctionSpace_Detail::ToDomainRepresentation<std::remove_const_t<std::remove_reference_t<typename boost::fusion::result_of::value_at_c<Function,0>::type>>> tdr(f);\n        auto const& df = tdr.get();\n\n        for (auto const& cell: gridInfo.cells)\n        {\n          int const numPoints = cell.subEntities(dim) + (gridInfo.options.order==2? cell.subEntities(dim-1): 0);\n          for (int point=0; point<numPoints; ++point)\n          {\n            auto subentity = vtkPointToDune(cell.type(),point);\n            auto xi = gridInfo.center(cell,subentity.first,subentity.second);          // local coordinate of point in current cell\n            int idx = gridInfo.conformingIndex(cell,subentity.first,subentity.second); // global index of point\n            ++count[idx];\n            fs[idx] += df.value(cell,xi);\n          }          \n        }\n        \n        for (int i=0; i<gridInfo.npoints; ++i)          // now write out the values in vertex order\n          p.write(fs[i]/static_cast<double>(count[i])); // and average them on writing\n      }\n      else // nonconforming\n      {\n        for (auto const& cell: gridInfo.cells)\n        {\n          // First write corner values\n          for (int corner=0; corner<cell.subEntities(dim); ++corner)\n            p.write(f.value(cell,gridInfo.center(cell,corner,dim)));\n\n          // If required, write edge midpoint values as well.\n          if (gridInfo.options.order==2)\n            for (int edge=0; edge<cell.subEntities(dim-1); ++edge)\n              p.write(f.value(cell,gridInfo.center(cell,edge,dim-1)));\n        }\n      }      \n    }\n    \n    // The following piece of code defines the \"active\" scalar and vectorial variables (those used to immediately color the output in Paraview). \n    // According to VTK file formats, there need not be any active scalar or vectorial variable. Taking simply the first one as is done here makes little sense. \n    // TODO: make this configurable via IoOptions.\n    template <class Functions, class Names>\n    std::string guessActiveFields(Functions const& functions, Names const& names, bool cellData) \n    {\n      std::string scalar = \"\";\n      std::string vector = \"\";\n      \n      boost::fusion::for_each(functions,[&](auto const& pair) \n      {\n        auto const& f = boost::fusion::at_c<0>(pair);\n        auto varDesc = boost::fusion::at_c<1>(pair);\n      \n        // Check whether this is best represented as cell or point data.\n        if ( (f.space().mapper().maxOrder()==0 && cellData)\n          || (f.space().mapper().maxOrder()>0 && !cellData) )\n        {\n          if (f.components>1 && vector.empty())\n            vector = \" Vectors=\\\"\" + names[varDesc.id] + \"\\\"\";\n          if (f.components==1 && scalar.empty())\n            scalar = \" Scalars=\\\"\" + names[varDesc.id] + \"\\\"\" ;\n        }\n      });\n      return scalar+vector;\n    }\n  \n  }\n  /**\n   * \\endcond\n   */\n  \n  // ---------------------------------------------------------------------------------------------\n  \n  /**\n   * \\ingroup IO\n   * \\brief Writes a set of finite element functions in VTK XML format to a stream.\n   * \\param vars a set of finite element functions to write\n   * \\param options specifies how the data shall be written\n   * \\param s the output stream\n   */\n  template <class VariableSet>\n  void writeVTK(VariableSet const& vars, IoOptions options, std::ostream& s)\n  {\n    using namespace VTKWriterDetail;\n    options.order = std::max(1,std::min(options.order,2));\n    \n    // If data mode \"inferred\" is requested, try to select either conforming or nonconforming\n    // based on rules.\n        \n    \n    \n    int indentCount = 0;\n    constexpr int dim = VariableSet::Descriptions::Grid::dimension;\n    \n    VTKGridInfo<typename VariableSet::Descriptions::GridView> gridInfo(vars.descriptions.gridView,options);\n    \n    // xml header\n    s << \"<?xml version=\\\"1.0\\\"?>\" << std::endl;\n    \n    // VTKFile\n    std::string const gridTag = dim>1? \"UnstructuredGrid\": \"PolyData\";\n    s << \"<VTKFile type=\\\"\" << gridTag << \"\\\" version=\\\"0.1\\\" byte_order=\\\"\" << vtkEndianness() << \"\\\">\" << std::endl;\n    ++indentCount;\n    \n    // UnstructuredGrid \n    indent(s,indentCount);\n    s << \"<\" << gridTag << \">\" << std::endl;\n    ++indentCount;\n    \n    // Piece\n    indent(s,indentCount);\n    if (dim>1)\n      s << \"<Piece NumberOfPoints=\\\"\" << gridInfo.npoints << \"\\\" NumberOfCells=\\\"\" << gridInfo.ncells << \"\\\">\" << std::endl;\n    else\n      s << \"<Piece NumberOfPoints=\\\"\" << gridInfo.npoints << \"\\\" NumberOfVerts=\\\"0\\\" NumberOfLines=\\\"\" << gridInfo.ncells << \"\\\" NumberOfPolys=\\\"0\\\">\" << std::endl;\n    ++indentCount;\n    \n    // Write grid points\n    indent(s,indentCount); s << \"<Points>\" << std::endl;    \n    gridInfo.writeGridPoints(indentCount+1,s);\n    indent(s,indentCount); s << \"</Points>\" << std::endl;\n   \n    // Write grid cells\n    std::string const cellTagName = dim>1? \"Cells\": \"Lines\";        \n    indent(s,indentCount);  s << '<' << cellTagName << '>' << std::endl;\n    gridInfo.writeGridCells(indentCount+1,s);\n    indent(s,indentCount); s << \"</\" << cellTagName << '>' << std::endl;\n    \n    // associate the FE functions with their variable descriptions\n    auto varDesc = typename VariableSet::Descriptions::Variables();\n    auto functions = boost::fusion::zip(vars.data,varDesc);\n    \n    indent(s,indentCount); s << \"<CellData\" << guessActiveFields(functions,vars.descriptions.names,true) << \">\" << std::endl;\n    boost::fusion::for_each(functions,[&](auto const& f) { writeCellData(gridInfo,f,vars.descriptions.names,indentCount+1,s); });\n    indent(s,indentCount); s << \"</CellData>\" << std::endl;\n    \n    indent(s,indentCount); s << \"<PointData\" << guessActiveFields(functions,vars.descriptions.names,false) << \">\" << std::endl;\n    boost::fusion::for_each(functions,[&](auto const& f) { writeVertexData(gridInfo,f,vars.descriptions.names,indentCount+1,s); });\n    indent(s,indentCount); s << \"</PointData>\" << std::endl;\n    \n    // /Piece\n    --indentCount;\n    indent(s,indentCount); s << \"</Piece>\" << std::endl;\n    \n    // /UnstructuredGrid\n    --indentCount;\n    indent(s,indentCount); s << \"</\" << gridTag << \">\" << std::endl;\n    \n    // /VTKFile\n    s << \"</VTKFile>\" << std::endl;\n  }\n  \n  /**\n   * \\ingroup IO\n   * \\brief Writes a set of finite element functions in VTK XML format to a stream.\n   * \\param vars a set of finite element functions\n   * \\param name file name (without trailing .vtu)\n   * \n   * Note that Paraview can create a time line implicitly from numbered files. use paddedString for easy creation \n   * of numbered file names.\n   */\n  template <class VariableSet>\n  void writeVTK(VariableSet const& vars, std::string name, IoOptions const& options)\n  {\n    // generate filename for process data\n    name += (VariableSet::Descriptions::GridView::dimension>1? \".vtu\" : \".vtp\");\n    \n    // write process data\n    std::ofstream file(name);\n    if (!file)\n      throw Kaskade::FileIOException(\"Opening  failed.\\n\",name,__FILE__,__LINE__);\n    writeVTK(vars,options,file);\n    if (!file)\n      throw Kaskade::FileIOException(\"Writing  failed.\\n\",name,__FILE__,__LINE__);\n    file.close();\n  }\n \n}\n\n// --------------------------------------------------------------------------------------------\n\n\n\n#endif\n", "meta": {"hexsha": "2c2d96fd3e9a3e0622e0a2c27f3b15b29b10f25e", "size": 19701, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/io/vtkwriter.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/io/vtkwriter.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/io/vtkwriter.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": 39.8805668016, "max_line_length": 188, "alphanum_fraction": 0.5827115375, "num_tokens": 4660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000708951749934, "lm_q2_score": 0.06278920465107114, "lm_q1q2_score": 0.013814070168400795}}
{"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_2923BE84E16CD6AE529049F1F1BBE9EB\n#define BOOST_QVM_2923BE84E16CD6AE529049F1F1BBE9EB\n\n// This file was generated by a program. Do not edit manually.\n\n#include <boost/qvm/assert.hpp>\n#include <boost/qvm/deduce_mat.hpp>\n#include <boost/qvm/deduce_vec.hpp>\n#include <boost/qvm/error.hpp>\n#include <boost/qvm/gen/mat_assign2.hpp>\n#include <boost/qvm/throw_exception.hpp>\n\nnamespace boost {\nnamespace qvm {\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n        mat_traits<A>::cols == 2 && mat_traits<B>::cols == 2,\n    deduce_mat2<A, B, 2, 2>>::type\noperator+(A const &a, B const &b) {\n  typedef typename deduce_mat2<A, B, 2, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 2);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 2);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) +\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) +\n      mat_traits<B>::template read_element<0, 1>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) +\n      mat_traits<B>::template read_element<1, 0>(b);\n  mat_traits<R>::template write_element<1, 1>(r) =\n      mat_traits<A>::template read_element<1, 1>(a) +\n      mat_traits<B>::template read_element<1, 1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct plus_mm_defined;\n\ntemplate <> struct plus_mm_defined<2, 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    mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n        mat_traits<A>::cols == 1 && mat_traits<B>::cols == 1,\n    deduce_mat2<A, B, 2, 1>>::type\noperator+(A const &a, B const &b) {\n  typedef typename deduce_mat2<A, B, 2, 1>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 2);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 1);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) +\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) +\n      mat_traits<B>::template read_element<1, 0>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct plus_mm_defined;\n\ntemplate <> struct plus_mm_defined<2, 1> { 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    mat_traits<A>::rows == 1 && mat_traits<B>::rows == 1 &&\n        mat_traits<A>::cols == 2 && mat_traits<B>::cols == 2,\n    deduce_mat2<A, B, 1, 2>>::type\noperator+(A const &a, B const &b) {\n  typedef typename deduce_mat2<A, B, 1, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 1);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 2);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) +\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) +\n      mat_traits<B>::template read_element<0, 1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct plus_mm_defined;\n\ntemplate <> struct plus_mm_defined<1, 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    mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n        mat_traits<A>::cols == 2 && mat_traits<B>::cols == 2,\n    deduce_mat2<A, B, 2, 2>>::type\noperator-(A const &a, B const &b) {\n  typedef typename deduce_mat2<A, B, 2, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 2);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 2);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) -\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) -\n      mat_traits<B>::template read_element<0, 1>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) -\n      mat_traits<B>::template read_element<1, 0>(b);\n  mat_traits<R>::template write_element<1, 1>(r) =\n      mat_traits<A>::template read_element<1, 1>(a) -\n      mat_traits<B>::template read_element<1, 1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_mm_defined;\n\ntemplate <> struct minus_mm_defined<2, 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    mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n        mat_traits<A>::cols == 1 && mat_traits<B>::cols == 1,\n    deduce_mat2<A, B, 2, 1>>::type\noperator-(A const &a, B const &b) {\n  typedef typename deduce_mat2<A, B, 2, 1>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 2);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 1);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) -\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) -\n      mat_traits<B>::template read_element<1, 0>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_mm_defined;\n\ntemplate <> struct minus_mm_defined<2, 1> { 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    mat_traits<A>::rows == 1 && mat_traits<B>::rows == 1 &&\n        mat_traits<A>::cols == 2 && mat_traits<B>::cols == 2,\n    deduce_mat2<A, B, 1, 2>>::type\noperator-(A const &a, B const &b) {\n  typedef typename deduce_mat2<A, B, 1, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 1);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 2);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) -\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) -\n      mat_traits<B>::template read_element<0, 1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_mm_defined;\n\ntemplate <> struct minus_mm_defined<1, 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<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         A &>::type\n    operator+=(A &a, B const &b) {\n  mat_traits<A>::template write_element<0, 0>(a) +=\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<A>::template write_element<0, 1>(a) +=\n      mat_traits<B>::template read_element<0, 1>(b);\n  mat_traits<A>::template write_element<1, 0>(a) +=\n      mat_traits<B>::template read_element<1, 0>(b);\n  mat_traits<A>::template write_element<1, 1>(a) +=\n      mat_traits<B>::template read_element<1, 1>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct plus_eq_mm_defined;\n\ntemplate <> struct plus_eq_mm_defined<2, 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<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 1 &&\n                             mat_traits<B>::cols == 1,\n                         A &>::type\n    operator+=(A &a, B const &b) {\n  mat_traits<A>::template write_element<0, 0>(a) +=\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<A>::template write_element<1, 0>(a) +=\n      mat_traits<B>::template read_element<1, 0>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct plus_eq_mm_defined;\n\ntemplate <> struct plus_eq_mm_defined<2, 1> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 1 && mat_traits<B>::rows == 1 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         A &>::type\n    operator+=(A &a, B const &b) {\n  mat_traits<A>::template write_element<0, 0>(a) +=\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<A>::template write_element<0, 1>(a) +=\n      mat_traits<B>::template read_element<0, 1>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator+=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct plus_eq_mm_defined;\n\ntemplate <> struct plus_eq_mm_defined<1, 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<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         A &>::type\n    operator-=(A &a, B const &b) {\n  mat_traits<A>::template write_element<0, 0>(a) -=\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<A>::template write_element<0, 1>(a) -=\n      mat_traits<B>::template read_element<0, 1>(b);\n  mat_traits<A>::template write_element<1, 0>(a) -=\n      mat_traits<B>::template read_element<1, 0>(b);\n  mat_traits<A>::template write_element<1, 1>(a) -=\n      mat_traits<B>::template read_element<1, 1>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_eq_mm_defined;\n\ntemplate <> struct minus_eq_mm_defined<2, 2> {\n  static bool const value = true;\n};\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 1 &&\n                             mat_traits<B>::cols == 1,\n                         A &>::type\n    operator-=(A &a, B const &b) {\n  mat_traits<A>::template write_element<0, 0>(a) -=\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<A>::template write_element<1, 0>(a) -=\n      mat_traits<B>::template read_element<1, 0>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_eq_mm_defined;\n\ntemplate <> struct minus_eq_mm_defined<2, 1> {\n  static bool const value = true;\n};\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 1 && mat_traits<B>::rows == 1 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         A &>::type\n    operator-=(A &a, B const &b) {\n  mat_traits<A>::template write_element<0, 0>(a) -=\n      mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<A>::template write_element<0, 1>(a) -=\n      mat_traits<B>::template read_element<0, 1>(b);\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_eq_mm_defined;\n\ntemplate <> struct minus_eq_mm_defined<1, 2> {\n  static bool const value = true;\n};\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2 && is_scalar<B>::value,\n    deduce_mat<A>>::type\noperator*(A const &a, B b) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) * b;\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) * b;\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) * b;\n  mat_traits<R>::template write_element<1, 1>(r) =\n      mat_traits<A>::template read_element<1, 1>(a) * b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_ms_defined;\n\ntemplate <> struct mul_ms_defined<2, 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 && mat_traits<B>::rows == 2 &&\n                                  mat_traits<B>::cols == 2,\n                              deduce_mat<B>>::type\n    operator*(A a, B const &b) {\n  typedef typename deduce_mat<B>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      a * mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      a * mat_traits<B>::template read_element<0, 1>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      a * mat_traits<B>::template read_element<1, 0>(b);\n  mat_traits<R>::template write_element<1, 1>(r) =\n      a * mat_traits<B>::template read_element<1, 1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_sm_defined;\n\ntemplate <> struct mul_sm_defined<2, 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    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 1 && is_scalar<B>::value,\n    deduce_mat<A>>::type\noperator*(A const &a, B b) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) * b;\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) * b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_ms_defined;\n\ntemplate <> struct mul_ms_defined<2, 1> { 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 && mat_traits<B>::rows == 2 &&\n                                  mat_traits<B>::cols == 1,\n                              deduce_mat<B>>::type\n    operator*(A a, B const &b) {\n  typedef typename deduce_mat<B>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      a * mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      a * mat_traits<B>::template read_element<1, 0>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_sm_defined;\n\ntemplate <> struct mul_sm_defined<2, 1> { 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    mat_traits<A>::rows == 1 && mat_traits<A>::cols == 2 && is_scalar<B>::value,\n    deduce_mat<A>>::type\noperator*(A const &a, B b) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) * b;\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) * b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_ms_defined;\n\ntemplate <> struct mul_ms_defined<1, 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 && mat_traits<B>::rows == 1 &&\n                                  mat_traits<B>::cols == 2,\n                              deduce_mat<B>>::type\n    operator*(A a, B const &b) {\n  typedef typename deduce_mat<B>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      a * mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      a * mat_traits<B>::template read_element<0, 1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_sm_defined;\n\ntemplate <> struct mul_sm_defined<1, 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<mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2 &&\n                             is_scalar<B>::value,\n                         A &>::type\n    operator*=(A &a, B b) {\n  mat_traits<A>::template write_element<0, 0>(a) *= b;\n  mat_traits<A>::template write_element<0, 1>(a) *= b;\n  mat_traits<A>::template write_element<1, 0>(a) *= b;\n  mat_traits<A>::template write_element<1, 1>(a) *= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_eq_ms_defined;\n\ntemplate <> struct mul_eq_ms_defined<2, 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<mat_traits<A>::rows == 2 && mat_traits<A>::cols == 1 &&\n                             is_scalar<B>::value,\n                         A &>::type\n    operator*=(A &a, B b) {\n  mat_traits<A>::template write_element<0, 0>(a) *= b;\n  mat_traits<A>::template write_element<1, 0>(a) *= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_eq_ms_defined;\n\ntemplate <> struct mul_eq_ms_defined<2, 1> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 1 && mat_traits<A>::cols == 2 &&\n                             is_scalar<B>::value,\n                         A &>::type\n    operator*=(A &a, B b) {\n  mat_traits<A>::template write_element<0, 0>(a) *= b;\n  mat_traits<A>::template write_element<0, 1>(a) *= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_eq_ms_defined;\n\ntemplate <> struct mul_eq_ms_defined<1, 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    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2 && is_scalar<B>::value,\n    deduce_mat<A>>::type\noperator/(A const &a, B b) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) / b;\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) / b;\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) / b;\n  mat_traits<R>::template write_element<1, 1>(r) =\n      mat_traits<A>::template read_element<1, 1>(a) / b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_ms_defined;\n\ntemplate <> struct div_ms_defined<2, 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 && mat_traits<B>::rows == 2 &&\n                                  mat_traits<B>::cols == 2,\n                              deduce_mat<B>>::type\n    operator/(A a, B const &b) {\n  typedef typename deduce_mat<B>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      a / mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      a / mat_traits<B>::template read_element<0, 1>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      a / mat_traits<B>::template read_element<1, 0>(b);\n  mat_traits<R>::template write_element<1, 1>(r) =\n      a / mat_traits<B>::template read_element<1, 1>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_sm_defined;\n\ntemplate <> struct div_sm_defined<2, 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    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 1 && is_scalar<B>::value,\n    deduce_mat<A>>::type\noperator/(A const &a, B b) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) / b;\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a) / b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_ms_defined;\n\ntemplate <> struct div_ms_defined<2, 1> { 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 && mat_traits<B>::rows == 2 &&\n                                  mat_traits<B>::cols == 1,\n                              deduce_mat<B>>::type\n    operator/(A a, B const &b) {\n  typedef typename deduce_mat<B>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      a / mat_traits<B>::template read_element<0, 0>(b);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      a / mat_traits<B>::template read_element<1, 0>(b);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_sm_defined;\n\ntemplate <> struct div_sm_defined<2, 1> { 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    mat_traits<A>::rows == 1 && mat_traits<A>::cols == 2 && is_scalar<B>::value,\n    deduce_mat<A>>::type\noperator/(A const &a, B b) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a) / b;\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a) / b;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_ms_defined;\n\ntemplate <> struct div_ms_defined<1, 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<mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2 &&\n                             is_scalar<B>::value,\n                         A &>::type\n    operator/=(A &a, B b) {\n  mat_traits<A>::template write_element<0, 0>(a) /= b;\n  mat_traits<A>::template write_element<0, 1>(a) /= b;\n  mat_traits<A>::template write_element<1, 0>(a) /= b;\n  mat_traits<A>::template write_element<1, 1>(a) /= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_eq_ms_defined;\n\ntemplate <> struct div_eq_ms_defined<2, 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<mat_traits<A>::rows == 2 && mat_traits<A>::cols == 1 &&\n                             is_scalar<B>::value,\n                         A &>::type\n    operator/=(A &a, B b) {\n  mat_traits<A>::template write_element<0, 0>(a) /= b;\n  mat_traits<A>::template write_element<1, 0>(a) /= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_eq_ms_defined;\n\ntemplate <> struct div_eq_ms_defined<2, 1> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 1 && mat_traits<A>::cols == 2 &&\n                             is_scalar<B>::value,\n                         A &>::type\n    operator/=(A &a, B b) {\n  mat_traits<A>::template write_element<0, 0>(a) /= b;\n  mat_traits<A>::template write_element<0, 1>(a) /= b;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator/=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct div_eq_ms_defined;\n\ntemplate <> struct div_eq_ms_defined<1, 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<mat_traits<R>::rows == 2 && mat_traits<A>::rows == 2 &&\n                             mat_traits<R>::cols == 2 &&\n                             mat_traits<A>::cols == 2,\n                         R>::type\n    convert_to(A const &a) {\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a);\n  mat_traits<R>::template write_element<1, 1>(r) =\n      mat_traits<A>::template read_element<1, 1>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::convert_to;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct convert_to_m_defined;\n\ntemplate <> struct convert_to_m_defined<2, 2> {\n  static bool const value = true;\n};\n} // namespace qvm_detail\n\ntemplate <class R, class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<R>::rows == 2 && mat_traits<A>::rows == 2 &&\n                             mat_traits<R>::cols == 1 &&\n                             mat_traits<A>::cols == 1,\n                         R>::type\n    convert_to(A const &a) {\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      mat_traits<A>::template read_element<1, 0>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::convert_to;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct convert_to_m_defined;\n\ntemplate <> struct convert_to_m_defined<2, 1> {\n  static bool const value = true;\n};\n} // namespace qvm_detail\n\ntemplate <class R, class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<R>::rows == 1 && mat_traits<A>::rows == 1 &&\n                             mat_traits<R>::cols == 2 &&\n                             mat_traits<A>::cols == 2,\n                         R>::type\n    convert_to(A const &a) {\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      mat_traits<A>::template read_element<0, 0>(a);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      mat_traits<A>::template read_element<0, 1>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::convert_to;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct convert_to_m_defined;\n\ntemplate <> struct convert_to_m_defined<1, 2> {\n  static bool const value = true;\n};\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         bool>::type\n    operator==(A const &a, B const &b) {\n  return mat_traits<A>::template read_element<0, 0>(a) ==\n             mat_traits<B>::template read_element<0, 0>(b) &&\n         mat_traits<A>::template read_element<0, 1>(a) ==\n             mat_traits<B>::template read_element<0, 1>(b) &&\n         mat_traits<A>::template read_element<1, 0>(a) ==\n             mat_traits<B>::template read_element<1, 0>(b) &&\n         mat_traits<A>::template read_element<1, 1>(a) ==\n             mat_traits<B>::template read_element<1, 1>(b);\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator==;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct eq_mm_defined;\n\ntemplate <> struct eq_mm_defined<2, 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<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 1 &&\n                             mat_traits<B>::cols == 1,\n                         bool>::type\n    operator==(A const &a, B const &b) {\n  return mat_traits<A>::template read_element<0, 0>(a) ==\n             mat_traits<B>::template read_element<0, 0>(b) &&\n         mat_traits<A>::template read_element<1, 0>(a) ==\n             mat_traits<B>::template read_element<1, 0>(b);\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator==;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct eq_mm_defined;\n\ntemplate <> struct eq_mm_defined<2, 1> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 1 && mat_traits<B>::rows == 1 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         bool>::type\n    operator==(A const &a, B const &b) {\n  return mat_traits<A>::template read_element<0, 0>(a) ==\n             mat_traits<B>::template read_element<0, 0>(b) &&\n         mat_traits<A>::template read_element<0, 1>(a) ==\n             mat_traits<B>::template read_element<0, 1>(b);\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator==;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct eq_mm_defined;\n\ntemplate <> struct eq_mm_defined<1, 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<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         bool>::type\n    operator!=(A const &a, B const &b) {\n  return !(mat_traits<A>::template read_element<0, 0>(a) ==\n           mat_traits<B>::template read_element<0, 0>(b)) ||\n         !(mat_traits<A>::template read_element<0, 1>(a) ==\n           mat_traits<B>::template read_element<0, 1>(b)) ||\n         !(mat_traits<A>::template read_element<1, 0>(a) ==\n           mat_traits<B>::template read_element<1, 0>(b)) ||\n         !(mat_traits<A>::template read_element<1, 1>(a) ==\n           mat_traits<B>::template read_element<1, 1>(b));\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator!=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct neq_mm_defined;\n\ntemplate <> struct neq_mm_defined<2, 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<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 1 &&\n                             mat_traits<B>::cols == 1,\n                         bool>::type\n    operator!=(A const &a, B const &b) {\n  return !(mat_traits<A>::template read_element<0, 0>(a) ==\n           mat_traits<B>::template read_element<0, 0>(b)) ||\n         !(mat_traits<A>::template read_element<1, 0>(a) ==\n           mat_traits<B>::template read_element<1, 0>(b));\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator!=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct neq_mm_defined;\n\ntemplate <> struct neq_mm_defined<2, 1> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 1 && mat_traits<B>::rows == 1 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         bool>::type\n    operator!=(A const &a, B const &b) {\n  return !(mat_traits<A>::template read_element<0, 0>(a) ==\n           mat_traits<B>::template read_element<0, 0>(b)) ||\n         !(mat_traits<A>::template read_element<0, 1>(a) ==\n           mat_traits<B>::template read_element<0, 1>(b));\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator!=;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct neq_mm_defined;\n\ntemplate <> struct neq_mm_defined<1, 2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2, deduce_mat<A>>::type\noperator-(A const &a) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      -mat_traits<A>::template read_element<0, 0>(a);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      -mat_traits<A>::template read_element<0, 1>(a);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      -mat_traits<A>::template read_element<1, 0>(a);\n  mat_traits<R>::template write_element<1, 1>(r) =\n      -mat_traits<A>::template read_element<1, 1>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_m_defined;\n\ntemplate <> struct minus_m_defined<2, 2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 1, deduce_mat<A>>::type\noperator-(A const &a) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      -mat_traits<A>::template read_element<0, 0>(a);\n  mat_traits<R>::template write_element<1, 0>(r) =\n      -mat_traits<A>::template read_element<1, 0>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_m_defined;\n\ntemplate <> struct minus_m_defined<2, 1> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    mat_traits<A>::rows == 1 && mat_traits<A>::cols == 2, deduce_mat<A>>::type\noperator-(A const &a) {\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) =\n      -mat_traits<A>::template read_element<0, 0>(a);\n  mat_traits<R>::template write_element<0, 1>(r) =\n      -mat_traits<A>::template read_element<0, 1>(a);\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator-;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct minus_m_defined;\n\ntemplate <> struct minus_m_defined<1, 2> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2,\n                         typename mat_traits<A>::scalar_type>::type\n    determinant(A const &a) {\n  typedef typename mat_traits<A>::scalar_type T;\n  T const a00 = mat_traits<A>::template read_element<0, 0>(a);\n  T const a01 = mat_traits<A>::template read_element<0, 1>(a);\n  T const a10 = mat_traits<A>::template read_element<1, 0>(a);\n  T const a11 = mat_traits<A>::template read_element<1, 1>(a);\n  T det = (a00 * a11 - a01 * a10);\n  return det;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::determinant;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct determinant_defined;\n\ntemplate <> struct determinant_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    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2 && is_scalar<B>::value,\n    deduce_mat<A>>::type\ninverse(A const &a, B det) {\n  typedef typename mat_traits<A>::scalar_type T;\n  BOOST_QVM_ASSERT(det != scalar_traits<B>::value(0));\n  T const a00 = mat_traits<A>::template read_element<0, 0>(a);\n  T const a01 = mat_traits<A>::template read_element<0, 1>(a);\n  T const a10 = mat_traits<A>::template read_element<1, 0>(a);\n  T const a11 = mat_traits<A>::template read_element<1, 1>(a);\n  T const f = scalar_traits<T>::value(1) / det;\n  typedef typename deduce_mat<A>::type R;\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) = f * a11;\n  mat_traits<R>::template write_element<0, 1>(r) = -f * a01;\n  mat_traits<R>::template write_element<1, 0>(r) = -f * a10;\n  mat_traits<R>::template write_element<1, 1>(r) = f * a00;\n  return r;\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    mat_traits<A>::rows == 2 && mat_traits<A>::cols == 2, deduce_mat<A>>::type\ninverse(A const &a) {\n  typedef typename mat_traits<A>::scalar_type T;\n  T det = determinant(a);\n  if (det == scalar_traits<T>::value(0))\n    BOOST_QVM_THROW_EXCEPTION(zero_determinant_error());\n  return inverse(a, det);\n}\n\nnamespace sfinae {\nusing ::boost::qvm::inverse;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct inverse_m_defined;\n\ntemplate <> struct inverse_m_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    mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n        mat_traits<A>::cols == 2 && mat_traits<B>::cols == 2,\n    deduce_mat2<A, B, 2, 2>>::type\noperator*(A const &a, B const &b) {\n  typedef typename mat_traits<A>::scalar_type Ta;\n  typedef typename mat_traits<B>::scalar_type Tb;\n  Ta const a00 = mat_traits<A>::template read_element<0, 0>(a);\n  Ta const a01 = mat_traits<A>::template read_element<0, 1>(a);\n  Ta const a10 = mat_traits<A>::template read_element<1, 0>(a);\n  Ta const a11 = mat_traits<A>::template read_element<1, 1>(a);\n  Tb const b00 = mat_traits<B>::template read_element<0, 0>(b);\n  Tb const b01 = mat_traits<B>::template read_element<0, 1>(b);\n  Tb const b10 = mat_traits<B>::template read_element<1, 0>(b);\n  Tb const b11 = mat_traits<B>::template read_element<1, 1>(b);\n  typedef typename deduce_mat2<A, B, 2, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 2);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 2);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) = a00 * b00 + a01 * b10;\n  mat_traits<R>::template write_element<0, 1>(r) = a00 * b01 + a01 * b11;\n  mat_traits<R>::template write_element<1, 0>(r) = a10 * b00 + a11 * b10;\n  mat_traits<R>::template write_element<1, 1>(r) = a10 * b01 + a11 * b11;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int CR, int C> struct mul_mm_defined;\n\ntemplate <> struct mul_mm_defined<2, 2, 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<mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n                             mat_traits<A>::cols == 2 &&\n                             mat_traits<B>::cols == 2,\n                         A &>::type\n    operator*=(A &a, B const &b) {\n  typedef typename mat_traits<A>::scalar_type Ta;\n  typedef typename mat_traits<B>::scalar_type Tb;\n  Ta const a00 = mat_traits<A>::template read_element<0, 0>(a);\n  Ta const a01 = mat_traits<A>::template read_element<0, 1>(a);\n  Ta const a10 = mat_traits<A>::template read_element<1, 0>(a);\n  Ta const a11 = mat_traits<A>::template read_element<1, 1>(a);\n  Tb const b00 = mat_traits<B>::template read_element<0, 0>(b);\n  Tb const b01 = mat_traits<B>::template read_element<0, 1>(b);\n  Tb const b10 = mat_traits<B>::template read_element<1, 0>(b);\n  Tb const b11 = mat_traits<B>::template read_element<1, 1>(b);\n  mat_traits<A>::template write_element<0, 0>(a) = a00 * b00 + a01 * b10;\n  mat_traits<A>::template write_element<0, 1>(a) = a00 * b01 + a01 * b11;\n  mat_traits<A>::template write_element<1, 0>(a) = a10 * b00 + a11 * b10;\n  mat_traits<A>::template write_element<1, 1>(a) = a10 * b01 + a11 * b11;\n  return a;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*=;\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct mul_eq_mm_defined;\n\ntemplate <> struct mul_eq_mm_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    mat_traits<A>::rows == 2 && mat_traits<B>::rows == 2 &&\n        mat_traits<A>::cols == 2 && mat_traits<B>::cols == 1,\n    deduce_mat2<A, B, 2, 1>>::type\noperator*(A const &a, B const &b) {\n  typedef typename mat_traits<A>::scalar_type Ta;\n  typedef typename mat_traits<B>::scalar_type Tb;\n  Ta const a00 = mat_traits<A>::template read_element<0, 0>(a);\n  Ta const a01 = mat_traits<A>::template read_element<0, 1>(a);\n  Ta const a10 = mat_traits<A>::template read_element<1, 0>(a);\n  Ta const a11 = mat_traits<A>::template read_element<1, 1>(a);\n  Tb const b00 = mat_traits<B>::template read_element<0, 0>(b);\n  Tb const b10 = mat_traits<B>::template read_element<1, 0>(b);\n  typedef typename deduce_mat2<A, B, 2, 1>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 2);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 1);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) = a00 * b00 + a01 * b10;\n  mat_traits<R>::template write_element<1, 0>(r) = a10 * b00 + a11 * b10;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int CR, int C> struct mul_mm_defined;\n\ntemplate <> struct mul_mm_defined<2, 2, 1> { 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    mat_traits<A>::rows == 1 && mat_traits<B>::rows == 2 &&\n        mat_traits<A>::cols == 2 && mat_traits<B>::cols == 2,\n    deduce_mat2<A, B, 1, 2>>::type\noperator*(A const &a, B const &b) {\n  typedef typename mat_traits<A>::scalar_type Ta;\n  typedef typename mat_traits<B>::scalar_type Tb;\n  Ta const a00 = mat_traits<A>::template read_element<0, 0>(a);\n  Ta const a01 = mat_traits<A>::template read_element<0, 1>(a);\n  Tb const b00 = mat_traits<B>::template read_element<0, 0>(b);\n  Tb const b01 = mat_traits<B>::template read_element<0, 1>(b);\n  Tb const b10 = mat_traits<B>::template read_element<1, 0>(b);\n  Tb const b11 = mat_traits<B>::template read_element<1, 1>(b);\n  typedef typename deduce_mat2<A, B, 1, 2>::type R;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows == 1);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols == 2);\n  R r;\n  mat_traits<R>::template write_element<0, 0>(r) = a00 * b00 + a01 * b10;\n  mat_traits<R>::template write_element<0, 1>(r) = a00 * b01 + a01 * b11;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int CR, int C> struct mul_mm_defined;\n\ntemplate <> struct mul_mm_defined<1, 2, 2> { static bool const value = true; };\n} // namespace qvm_detail\n\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "a565853721408cc9bc5eb6dfe339674adefa0db7", "size": 43655, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/gen/mat_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/mat_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/mat_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": 33.8410852713, "max_line_length": 80, "alphanum_fraction": 0.6439583095, "num_tokens": 12743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.03210070382336566, "lm_q1q2_score": 0.013808032637360168}}
{"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_ELE_TIMES_EXPR_INCLUDE\n#define MTL_MAT_MAT_ELE_TIMES_EXPR_INCLUDE\n\n#include <boost/shared_ptr.hpp>\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/linear_algebra/identity.hpp>\n\n\nnamespace mtl { namespace matrix {\n\ntemplate <typename E1, typename E2>\nstruct mat_mat_ele_times_expr \n    : public mat_mat_op_expr< E1, E2, mtl::sfunctor::times<typename E1::value_type, typename E2::value_type> >,\n      public mat_expr< mat_mat_ele_times_expr<E1, E2> >\n{\n    typedef mat_mat_op_expr< E1, E2, mtl::sfunctor::times<typename E1::value_type, typename E2::value_type> > op_base;\n    typedef mat_expr< mat_mat_ele_times_expr<E1, E2> >                                                        crtp_base;\n    typedef mat_mat_ele_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    mat_mat_ele_times_expr( E1 const& v1, E2 const& v2 )\n\t: op_base( v1, v2 ), crtp_base(*this), first(v1), second(v2)\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_ele_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_ele_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_ele_times_expr<E1, E2>& expr) \n{ return num_rows(expr) * num_cols(expr); }\n\n}} // Namespace mtl::matrix\n\n#endif // MTL_MAT_MAT_ELE_TIMES_EXPR_INCLUDE\n", "meta": {"hexsha": "e49e9ba548b0728d2048fa00733c63a465bb9c4d", "size": 2387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/matrix/mat_mat_ele_times_expr.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/matrix/mat_mat_ele_times_expr.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/matrix/mat_mat_ele_times_expr.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.8888888889, "max_line_length": 120, "alphanum_fraction": 0.6912442396, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195521959384, "lm_q2_score": 0.036220059896309276, "lm_q1q2_score": 0.013807795014181088}}
{"text": "// Copyright (c) 2016 Jack Grigg\n// Copyright (c) 2016 The Zcash developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n// Implementation of the Equihash Proof-of-Work algorithm.\n//\n// Reference\n// =========\n// Alex Biryukov and Dmitry Khovratovich\n// Equihash: Asymmetric Proof-of-Work Based on the Generalized Birthday Problem\n// NDSS ’16, 21-24 February 2016, San Diego, CA, USA\n// https://www.internetsociety.org/sites/default/files/blogs-media/equihash-asymmetric-proof-of-work-based-generalized-birthday-problem.pdf\n\n#if defined(HAVE_CONFIG_H)\n#include \"config/bpq-config.h\"\n#endif\n\n#include \"crypto/equihash.h\"\n\n#ifndef NO_UTIL_LOG\n#include \"util.h\"\n#else\n#define LogPrint(...)\n#endif\n\n#include <algorithm>\n#include <iostream>\n#include <stdexcept>\n\n#include <boost/optional.hpp>\n\nEhSolverCancelledException solver_cancelled;\n\ntemplate<unsigned int N, unsigned int K>\nint Equihash<N,K>::InitialiseState(eh_HashState& base_state)\n{\n    uint32_t le_N = htole32(N);\n    uint32_t le_K = htole32(K);\n    unsigned char personalization[crypto_generichash_blake2b_PERSONALBYTES] = {};\n    memcpy(personalization, \"ZcashPoW\", 8);\n    memcpy(personalization+8,  &le_N, 4);\n    memcpy(personalization+12, &le_K, 4);\n    return crypto_generichash_blake2b_init_salt_personal(&base_state,\n                                                         NULL, 0, // No key.\n                                                         (512/N)*N/8,\n                                                         NULL,    // No salt.\n                                                         personalization);\n}\n\nvoid GenerateHash(const eh_HashState& base_state, eh_index g,\n                  unsigned char* hash, size_t hLen)\n{\n    eh_HashState state;\n    state = base_state;\n    eh_index lei = htole32(g);\n    crypto_generichash_blake2b_update(&state, (const unsigned char*) &lei,\n                                      sizeof(eh_index));\n    crypto_generichash_blake2b_final(&state, hash, hLen);\n}\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)\n{\n    assert(bit_len >= 8);\n    assert(8*sizeof(uint32_t) >= 7+bit_len);\n\n    size_t out_width { (bit_len+7)/8 + byte_pad };\n    assert(out_len == 8*out_width*in_len/bit_len);\n\n    uint32_t bit_len_mask { ((uint32_t)1 << bit_len) - 1 };\n\n    // The acc_bits least-significant bits of acc_value represent a bit sequence\n    // in big-endian order.\n    size_t acc_bits = 0;\n    uint32_t acc_value = 0;\n\n    size_t j = 0;\n    for (size_t i = 0; i < in_len; i++) {\n        acc_value = (acc_value << 8) | in[i];\n        acc_bits += 8;\n\n        // When we have bit_len or more bits in the accumulator, write the next\n        // output element.\n        if (acc_bits >= bit_len) {\n            acc_bits -= bit_len;\n            for (size_t x = 0; x < byte_pad; x++) {\n                out[j+x] = 0;\n            }\n            for (size_t x = byte_pad; x < out_width; x++) {\n                out[j+x] = (\n                    // Big-endian\n                    acc_value >> (acc_bits+(8*(out_width-x-1)))\n                ) & (\n                    // Apply bit_len_mask across byte boundaries\n                    (bit_len_mask >> (8*(out_width-x-1))) & 0xFF\n                );\n            }\n            j += out_width;\n        }\n    }\n}\n\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)\n{\n    assert(bit_len >= 8);\n    assert(8*sizeof(uint32_t) >= 7+bit_len);\n\n    size_t in_width { (bit_len+7)/8 + byte_pad };\n    assert(out_len == bit_len*in_len/(8*in_width));\n\n    uint32_t bit_len_mask { ((uint32_t)1 << bit_len) - 1 };\n\n    // The acc_bits least-significant bits of acc_value represent a bit sequence\n    // in big-endian order.\n    size_t acc_bits = 0;\n    uint32_t acc_value = 0;\n\n    size_t j = 0;\n    for (size_t i = 0; i < out_len; i++) {\n        // When we have fewer than 8 bits left in the accumulator, read the next\n        // input element.\n        if (acc_bits < 8) {\n            acc_value = acc_value << bit_len;\n            for (size_t x = byte_pad; x < in_width; x++) {\n                acc_value = acc_value | (\n                    (\n                        // Apply bit_len_mask across byte boundaries\n                        in[j+x] & ((bit_len_mask >> (8*(in_width-x-1))) & 0xFF)\n                    ) << (8*(in_width-x-1))); // Big-endian\n            }\n            j += in_width;\n            acc_bits += bit_len;\n        }\n\n        acc_bits -= 8;\n        out[i] = (acc_value >> acc_bits) & 0xFF;\n    }\n}\n\n// Big-endian so that lexicographic array comparison is equivalent to integer\n// comparison\nvoid EhIndexToArray(const eh_index i, unsigned char* array)\n{\n    BOOST_STATIC_ASSERT(sizeof(eh_index) == 4);\n    eh_index bei = htobe32(i);\n    memcpy(array, &bei, sizeof(eh_index));\n}\n\n// Big-endian so that lexicographic array comparison is equivalent to integer\n// comparison\neh_index ArrayToEhIndex(const unsigned char* array)\n{\n    BOOST_STATIC_ASSERT(sizeof(eh_index) == 4);\n    eh_index bei;\n    memcpy(&bei, array, sizeof(eh_index));\n    return be32toh(bei);\n}\n\neh_trunc TruncateIndex(const eh_index i, const unsigned int ilen)\n{\n    // Truncate to 8 bits\n    BOOST_STATIC_ASSERT(sizeof(eh_trunc) == 1);\n    return (i >> (ilen - 8)) & 0xff;\n}\n\neh_index UntruncateIndex(const eh_trunc t, const eh_index r, const unsigned int ilen)\n{\n    eh_index i{t};\n    return (i << (ilen - 8)) | r;\n}\n\nstd::vector<eh_index> GetIndicesFromMinimal(std::vector<unsigned char> minimal,\n                                            size_t cBitLen)\n{\n    assert(((cBitLen+1)+7)/8 <= sizeof(eh_index));\n    size_t lenIndices { 8*sizeof(eh_index)*minimal.size()/(cBitLen+1) };\n    size_t bytePad { sizeof(eh_index) - ((cBitLen+1)+7)/8 };\n    std::vector<unsigned char> array(lenIndices);\n    ExpandArray(minimal.data(), minimal.size(),\n                array.data(), lenIndices, cBitLen+1, bytePad);\n    std::vector<eh_index> ret;\n    for (size_t i = 0; i < lenIndices; i += sizeof(eh_index)) {\n        ret.push_back(ArrayToEhIndex(array.data()+i));\n    }\n    return ret;\n}\n\nstd::vector<unsigned char> GetMinimalFromIndices(std::vector<eh_index> indices,\n                                                 size_t cBitLen)\n{\n    assert(((cBitLen+1)+7)/8 <= sizeof(eh_index));\n    size_t lenIndices { indices.size()*sizeof(eh_index) };\n    size_t minLen { (cBitLen+1)*lenIndices/(8*sizeof(eh_index)) };\n    size_t bytePad { sizeof(eh_index) - ((cBitLen+1)+7)/8 };\n    std::vector<unsigned char> array(lenIndices);\n    for (size_t i = 0; i < indices.size(); i++) {\n        EhIndexToArray(indices[i], array.data()+(i*sizeof(eh_index)));\n    }\n    std::vector<unsigned char> ret(minLen);\n    CompressArray(array.data(), lenIndices,\n                  ret.data(), minLen, cBitLen+1, bytePad);\n    return ret;\n}\n\ntemplate<size_t WIDTH>\nStepRow<WIDTH>::StepRow(const unsigned char* hashIn, size_t hInLen,\n                        size_t hLen, size_t cBitLen)\n{\n    assert(hLen <= WIDTH);\n    ExpandArray(hashIn, hInLen, hash, hLen, cBitLen);\n}\n\ntemplate<size_t WIDTH> template<size_t W>\nStepRow<WIDTH>::StepRow(const StepRow<W>& a)\n{\n    BOOST_STATIC_ASSERT(W <= WIDTH);\n    std::copy(a.hash, a.hash+W, hash);\n}\n\ntemplate<size_t WIDTH>\nFullStepRow<WIDTH>::FullStepRow(const unsigned char* hashIn, size_t hInLen,\n                                size_t hLen, size_t cBitLen, eh_index i) :\n        StepRow<WIDTH> {hashIn, hInLen, hLen, cBitLen}\n{\n    EhIndexToArray(i, hash+hLen);\n}\n\ntemplate<size_t WIDTH> template<size_t W>\nFullStepRow<WIDTH>::FullStepRow(const FullStepRow<W>& a, const FullStepRow<W>& b, size_t len, size_t lenIndices, size_t trim) :\n        StepRow<WIDTH> {a}\n{\n    assert(len+lenIndices <= W);\n    assert(len-trim+(2*lenIndices) <= WIDTH);\n    for (size_t i = trim; i < len; i++)\n        hash[i-trim] = a.hash[i] ^ b.hash[i];\n    if (a.IndicesBefore(b, len, lenIndices)) {\n        std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim);\n        std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim+lenIndices);\n    } else {\n        std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim);\n        std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim+lenIndices);\n    }\n}\n\ntemplate<size_t WIDTH>\nFullStepRow<WIDTH>& FullStepRow<WIDTH>::operator=(const FullStepRow<WIDTH>& a)\n{\n    std::copy(a.hash, a.hash+WIDTH, hash);\n    return *this;\n}\n\ntemplate<size_t WIDTH>\nbool StepRow<WIDTH>::IsZero(size_t len)\n{\n    // This doesn't need to be constant time.\n    for (size_t i = 0; i < len; i++) {\n        if (hash[i] != 0)\n            return false;\n    }\n    return true;\n}\n\ntemplate<size_t WIDTH>\nstd::vector<unsigned char> FullStepRow<WIDTH>::GetIndices(size_t len, size_t lenIndices,\n                                                          size_t cBitLen) const\n{\n    assert(((cBitLen+1)+7)/8 <= sizeof(eh_index));\n    size_t minLen { (cBitLen+1)*lenIndices/(8*sizeof(eh_index)) };\n    size_t bytePad { sizeof(eh_index) - ((cBitLen+1)+7)/8 };\n    std::vector<unsigned char> ret(minLen);\n    CompressArray(hash+len, lenIndices, ret.data(), minLen, cBitLen+1, bytePad);\n    return ret;\n}\n\ntemplate<size_t WIDTH>\nbool HasCollision(StepRow<WIDTH>& a, StepRow<WIDTH>& b, size_t l)\n{\n    // This doesn't need to be constant time.\n    for (size_t j = 0; j < l; j++) {\n        if (a.hash[j] != b.hash[j])\n            return false;\n    }\n    return true;\n}\n\ntemplate<size_t WIDTH>\nTruncatedStepRow<WIDTH>::TruncatedStepRow(const unsigned char* hashIn, size_t hInLen,\n                                          size_t hLen, size_t cBitLen,\n                                          eh_index i, unsigned int ilen) :\n        StepRow<WIDTH> {hashIn, hInLen, hLen, cBitLen}\n{\n    hash[hLen] = TruncateIndex(i, ilen);\n}\n\ntemplate<size_t WIDTH> template<size_t W>\nTruncatedStepRow<WIDTH>::TruncatedStepRow(const TruncatedStepRow<W>& a, const TruncatedStepRow<W>& b, size_t len, size_t lenIndices, size_t trim) :\n        StepRow<WIDTH> {a}\n{\n    assert(len+lenIndices <= W);\n    assert(len-trim+(2*lenIndices) <= WIDTH);\n    for (size_t i = trim; i < len; i++)\n        hash[i-trim] = a.hash[i] ^ b.hash[i];\n    if (a.IndicesBefore(b, len, lenIndices)) {\n        std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim);\n        std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim+lenIndices);\n    } else {\n        std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim);\n        std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim+lenIndices);\n    }\n}\n\ntemplate<size_t WIDTH>\nTruncatedStepRow<WIDTH>& TruncatedStepRow<WIDTH>::operator=(const TruncatedStepRow<WIDTH>& a)\n{\n    std::copy(a.hash, a.hash+WIDTH, hash);\n    return *this;\n}\n\ntemplate<size_t WIDTH>\nstd::shared_ptr<eh_trunc> TruncatedStepRow<WIDTH>::GetTruncatedIndices(size_t len, size_t lenIndices) const\n{\n    std::shared_ptr<eh_trunc> p (new eh_trunc[lenIndices], std::default_delete<eh_trunc[]>());\n    std::copy(hash+len, hash+len+lenIndices, p.get());\n    return p;\n}\n\ntemplate<unsigned int N, unsigned int K>\nbool Equihash<N,K>::BasicSolve(const eh_HashState& base_state,\n                               const std::function<bool(std::vector<unsigned char>)> validBlock,\n                               const std::function<bool(EhSolverCancelCheck)> cancelled)\n{\n    eh_index init_size { 1 << (CollisionBitLength + 1) };\n    // So, for <200,9>, that’s 2 ^ ( (200 / (9+1) ) + 1), or 2 to the 21st power, or 2,097,152.strings. 2097152 * 1030=2 160 066 560\n    //200x9 = 2097152 * 1030 = 2 160 066 560  // 3m4.064s,  2m56.177s, 5m46.537s\n    //176x7 = 8388608 * 262  = 2 197 815 296   // 2m12.193s, 2m21.114s, 2m20.580s\n    //144x5 = 33554432 * 70  = 2 348 810 240   // 3m39.719s, 3m58.309s, 7m22.785s\n    //168x7 = 4194304 * 262  = 1 098 907 648   // 0m56.635s, 1m0.621s, 0m55.824s\n\n    // 1) Generate first list\n    LogPrint(BCLog::POW, \"Generating first list\\n\");\n    size_t hashLen = HashLength;\n    size_t lenIndices = sizeof(eh_index);\n    std::vector<FullStepRow<FullWidth>> X;\n    X.reserve(init_size);\n    \n    //size_t fullWidth = FullWidth;\n    \n    unsigned char tmpHash[HashOutput];\n    for (eh_index g = 0; X.size() < init_size; g++) {\n        GenerateHash(base_state, g, tmpHash, HashOutput);\n        for (eh_index i = 0; i < IndicesPerHashOutput && X.size() < init_size; i++) {\n            X.emplace_back(tmpHash+(i*N/8), N/8, HashLength,\n                           CollisionBitLength, (g*IndicesPerHashOutput)+i);\n        }\n        if (cancelled(ListGeneration)) throw solver_cancelled;\n    }\n\n    // 3) Repeat step 2 until 2n/(k+1) bits remain\n    for (unsigned int r = 1; r < K && X.size() > 0; r++) {\n        LogPrint(BCLog::POW, \"Round %u:\\n\", r);\n        // 2a) Sort the list\n        LogPrint(BCLog::POW, \"- Sorting list\\n\");\n        std::sort(X.begin(), X.end(), CompareSR(CollisionByteLength));\n        if (cancelled(ListSorting)) throw solver_cancelled;\n\n        LogPrint(BCLog::POW, \"- Finding collisions\\n\");\n        size_t i = 0;\n        size_t posFree = 0;\n        std::vector<FullStepRow<FullWidth>> Xc;\n        while (i < X.size() - 1) {\n            // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits\n            size_t j = 1;\n            while (i+j < X.size() &&\n                    HasCollision(X[i], X[i+j], CollisionByteLength)) {\n                j++;\n            }\n\n            // 2c) Calculate tuples (X_i ^ X_j, (i, j))\n            for (size_t l = 0; l < j - 1; l++) {\n                for (size_t m = l + 1; m < j; m++) {\n                    if (DistinctIndices(X[i+l], X[i+m], hashLen, lenIndices)) {\n                        Xc.emplace_back(X[i+l], X[i+m], hashLen, lenIndices, CollisionByteLength);\n                    }\n                }\n            }\n\n            // 2d) Store tuples on the table in-place if possible\n            while (posFree < i+j && Xc.size() > 0) {\n                X[posFree++] = Xc.back();\n                Xc.pop_back();\n            }\n\n            i += j;\n            if (cancelled(ListColliding)) throw solver_cancelled;\n        }\n\n        // 2e) Handle edge case where final table entry has no collision\n        while (posFree < X.size() && Xc.size() > 0) {\n            X[posFree++] = Xc.back();\n            Xc.pop_back();\n        }\n\n        if (Xc.size() > 0) {\n            // 2f) Add overflow to end of table\n            X.insert(X.end(), Xc.begin(), Xc.end());\n        } else if (posFree < X.size()) {\n            // 2g) Remove empty space at the end\n            X.erase(X.begin()+posFree, X.end());\n            X.shrink_to_fit();\n        }\n\n        hashLen -= CollisionByteLength;\n        lenIndices *= 2;\n        if (cancelled(RoundEnd)) throw solver_cancelled;\n    }\n\n    // k+1) Find a collision on last 2n(k+1) bits\n    LogPrint(BCLog::POW, \"Final round:\\n\");\n    if (X.size() > 1) {\n        LogPrint(BCLog::POW, \"- Sorting list\\n\");\n        std::sort(X.begin(), X.end(), CompareSR(hashLen));\n        if (cancelled(FinalSorting)) throw solver_cancelled;\n        LogPrint(BCLog::POW, \"- Finding collisions\\n\");\n        size_t i = 0;\n        while (i < X.size() - 1) {\n            size_t j = 1;\n            while (i+j < X.size() &&\n                    HasCollision(X[i], X[i+j], hashLen)) {\n                j++;\n            }\n\n            for (size_t l = 0; l < j - 1; l++) {\n                for (size_t m = l + 1; m < j; m++) {\n                    FullStepRow<FinalFullWidth> res(X[i+l], X[i+m], hashLen, lenIndices, 0);\n                    if (DistinctIndices(X[i+l], X[i+m], hashLen, lenIndices)) {\n                        auto soln = res.GetIndices(hashLen, 2*lenIndices, CollisionBitLength);\n                        assert(soln.size() == equihash_solution_size(N, K));\n                        if (validBlock(soln)) {\n                            return true;\n                        }\n                    }\n                }\n            }\n\n            i += j;\n            if (cancelled(FinalColliding)) throw solver_cancelled;\n        }\n    } else\n        LogPrint(BCLog::POW, \"- List is empty\\n\");\n\n    return false;\n}\n\ntemplate<size_t WIDTH>\nvoid CollideBranches(std::vector<FullStepRow<WIDTH>>& X, const size_t hlen, const size_t lenIndices, const unsigned int clen, const unsigned int ilen, const eh_trunc lt, const eh_trunc rt)\n{\n    size_t i = 0;\n    size_t posFree = 0;\n    std::vector<FullStepRow<WIDTH>> Xc;\n    while (i < X.size() - 1) {\n        // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits\n        size_t j = 1;\n        while (i+j < X.size() &&\n                HasCollision(X[i], X[i+j], clen)) {\n            j++;\n        }\n\n        // 2c) Calculate tuples (X_i ^ X_j, (i, j))\n        for (size_t l = 0; l < j - 1; l++) {\n            for (size_t m = l + 1; m < j; m++) {\n                if (DistinctIndices(X[i+l], X[i+m], hlen, lenIndices)) {\n                    if (IsValidBranch(X[i+l], hlen, ilen, lt) && IsValidBranch(X[i+m], hlen, ilen, rt)) {\n                        Xc.emplace_back(X[i+l], X[i+m], hlen, lenIndices, clen);\n                    } else if (IsValidBranch(X[i+m], hlen, ilen, lt) && IsValidBranch(X[i+l], hlen, ilen, rt)) {\n                        Xc.emplace_back(X[i+m], X[i+l], hlen, lenIndices, clen);\n                    }\n                }\n            }\n        }\n\n        // 2d) Store tuples on the table in-place if possible\n        while (posFree < i+j && Xc.size() > 0) {\n            X[posFree++] = Xc.back();\n            Xc.pop_back();\n        }\n\n        i += j;\n    }\n\n    // 2e) Handle edge case where final table entry has no collision\n    while (posFree < X.size() && Xc.size() > 0) {\n        X[posFree++] = Xc.back();\n        Xc.pop_back();\n    }\n\n    if (Xc.size() > 0) {\n        // 2f) Add overflow to end of table\n        X.insert(X.end(), Xc.begin(), Xc.end());\n    } else if (posFree < X.size()) {\n        // 2g) Remove empty space at the end\n        X.erase(X.begin()+posFree, X.end());\n        X.shrink_to_fit();\n    }\n}\n\ntemplate<unsigned int N, unsigned int K>\nbool Equihash<N,K>::OptimisedSolve(const eh_HashState& base_state,\n                                   const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                   const std::function<bool(EhSolverCancelCheck)> cancelled)\n{\n    eh_index init_size { 1 << (CollisionBitLength + 1) };\n    eh_index recreate_size { UntruncateIndex(1, 0, CollisionBitLength + 1) };\n\n    // First run the algorithm with truncated indices\n\n    const eh_index soln_size { 1 << K };\n    std::vector<std::shared_ptr<eh_trunc>> partialSolns;\n    size_t invalidCount = 0;\n    {\n\n        // 1) Generate first list\n        LogPrint(BCLog::POW, \"Generating first list\\n\");\n        size_t hashLen = HashLength;\n        size_t lenIndices = sizeof(eh_trunc);\n        std::vector<TruncatedStepRow<TruncatedWidth>> Xt;\n        Xt.reserve(init_size);\n        unsigned char tmpHash[HashOutput];\n        for (eh_index g = 0; Xt.size() < init_size; g++) {\n            GenerateHash(base_state, g, tmpHash, HashOutput);\n            for (eh_index i = 0; i < IndicesPerHashOutput && Xt.size() < init_size; i++) {\n                Xt.emplace_back(tmpHash+(i*N/8), N/8, HashLength, CollisionBitLength,\n                                (g*IndicesPerHashOutput)+i, CollisionBitLength + 1);\n            }\n            if (cancelled(ListGeneration)) throw solver_cancelled;\n        }\n\n        // 3) Repeat step 2 until 2n/(k+1) bits remain\n        for (size_t r = 1; r < K && Xt.size() > 0; r++) {\n            LogPrint(BCLog::POW, \"Round %zu:\\n\", r);\n            // 2a) Sort the list\n            LogPrint(BCLog::POW, \"- Sorting list\\n\");\n            std::sort(Xt.begin(), Xt.end(), CompareSR(CollisionByteLength));\n            if (cancelled(ListSorting)) throw solver_cancelled;\n\n            LogPrint(BCLog::POW, \"- Finding collisions\\n\");\n            size_t i = 0;\n            size_t posFree = 0;\n            std::vector<TruncatedStepRow<TruncatedWidth>> Xc;\n            while (i < Xt.size() - 1) {\n                // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits\n                size_t j = 1;\n                while (i+j < Xt.size() &&\n                        HasCollision(Xt[i], Xt[i+j], CollisionByteLength)) {\n                    j++;\n                }\n\n                // 2c) Calculate tuples (X_i ^ X_j, (i, j))\n                //bool checking_for_zero = (i == 0 && Xt[0].IsZero(hashLen));\n                for (size_t l = 0; l < j - 1; l++) {\n                    for (size_t m = l + 1; m < j; m++) {\n                        // We truncated, so don't check for distinct indices here\n                        TruncatedStepRow<TruncatedWidth> Xi {Xt[i+l], Xt[i+m],\n                                                             hashLen, lenIndices,\n                                                             CollisionByteLength};\n                        if (!(Xi.IsZero(hashLen-CollisionByteLength) &&\n                              IsProbablyDuplicate<soln_size>(Xi.GetTruncatedIndices(hashLen-CollisionByteLength, 2*lenIndices),\n                                                             2*lenIndices))) {\n                            Xc.emplace_back(Xi);\n                        }\n                    }\n                }\n\n                // 2d) Store tuples on the table in-place if possible\n                while (posFree < i+j && Xc.size() > 0) {\n                    Xt[posFree++] = Xc.back();\n                    Xc.pop_back();\n                }\n\n                i += j;\n                if (cancelled(ListColliding)) throw solver_cancelled;\n            }\n\n            // 2e) Handle edge case where final table entry has no collision\n            while (posFree < Xt.size() && Xc.size() > 0) {\n                Xt[posFree++] = Xc.back();\n                Xc.pop_back();\n            }\n\n            if (Xc.size() > 0) {\n                // 2f) Add overflow to end of table\n                Xt.insert(Xt.end(), Xc.begin(), Xc.end());\n            } else if (posFree < Xt.size()) {\n                // 2g) Remove empty space at the end\n                Xt.erase(Xt.begin()+posFree, Xt.end());\n                Xt.shrink_to_fit();\n            }\n\n            hashLen -= CollisionByteLength;\n            lenIndices *= 2;\n            if (cancelled(RoundEnd)) throw solver_cancelled;\n        }\n\n        // k+1) Find a collision on last 2n(k+1) bits\n        LogPrint(BCLog::POW, \"Final round:\\n\");\n        if (Xt.size() > 1) {\n            LogPrint(BCLog::POW, \"- Sorting list\\n\");\n            std::sort(Xt.begin(), Xt.end(), CompareSR(hashLen));\n            if (cancelled(FinalSorting)) throw solver_cancelled;\n            LogPrint(BCLog::POW, \"- Finding collisions\\n\");\n            size_t i = 0;\n            while (i < Xt.size() - 1) {\n                size_t j = 1;\n                while (i+j < Xt.size() &&\n                        HasCollision(Xt[i], Xt[i+j], hashLen)) {\n                    j++;\n                }\n\n                for (size_t l = 0; l < j - 1; l++) {\n                    for (size_t m = l + 1; m < j; m++) {\n                        TruncatedStepRow<FinalTruncatedWidth> res(Xt[i+l], Xt[i+m],\n                                                                  hashLen, lenIndices, 0);\n                        auto soln = res.GetTruncatedIndices(hashLen, 2*lenIndices);\n                        if (!IsProbablyDuplicate<soln_size>(soln, 2*lenIndices)) {\n                            partialSolns.push_back(soln);\n                        }\n                    }\n                }\n\n                i += j;\n                if (cancelled(FinalColliding)) throw solver_cancelled;\n            }\n        } else\n            LogPrint(BCLog::POW, \"- List is empty\\n\");\n\n    } // Ensure Xt goes out of scope and is destroyed\n\n    LogPrint(BCLog::POW, \"Found %d partial solutions\\n\", partialSolns.size());\n\n    // Now for each solution run the algorithm again to recreate the indices\n    LogPrint(BCLog::POW, \"Culling solutions\\n\");\n    for (std::shared_ptr<eh_trunc> partialSoln : partialSolns) {\n        std::set<std::vector<unsigned char>> solns;\n        size_t hashLen;\n        size_t lenIndices;\n        unsigned char tmpHash[HashOutput];\n        std::vector<boost::optional<std::vector<FullStepRow<FinalFullWidth>>>> X;\n        X.reserve(K+1);\n\n        // 3) Repeat steps 1 and 2 for each partial index\n        for (eh_index i = 0; i < soln_size; i++) {\n            // 1) Generate first list of possibilities\n            std::vector<FullStepRow<FinalFullWidth>> icv;\n            icv.reserve(recreate_size);\n            for (eh_index j = 0; j < recreate_size; j++) {\n                eh_index newIndex { UntruncateIndex(partialSoln.get()[i], j, CollisionBitLength + 1) };\n                if (j == 0 || newIndex % IndicesPerHashOutput == 0) {\n                    GenerateHash(base_state, newIndex/IndicesPerHashOutput,\n                                 tmpHash, HashOutput);\n                }\n                icv.emplace_back(tmpHash+((newIndex % IndicesPerHashOutput) * N/8),\n                                 N/8, HashLength, CollisionBitLength, newIndex);\n                if (cancelled(PartialGeneration)) throw solver_cancelled;\n            }\n            boost::optional<std::vector<FullStepRow<FinalFullWidth>>> ic = icv;\n\n            // 2a) For each pair of lists:\n            hashLen = HashLength;\n            lenIndices = sizeof(eh_index);\n            size_t rti = i;\n            for (size_t r = 0; r <= K; r++) {\n                // 2b) Until we are at the top of a subtree:\n                if (r < X.size()) {\n                    if (X[r]) {\n                        // 2c) Merge the lists\n                        ic->reserve(ic->size() + X[r]->size());\n                        ic->insert(ic->end(), X[r]->begin(), X[r]->end());\n                        std::sort(ic->begin(), ic->end(), CompareSR(hashLen));\n                        if (cancelled(PartialSorting)) throw solver_cancelled;\n                        size_t lti = rti-(1<<r);\n                        CollideBranches(*ic, hashLen, lenIndices,\n                                        CollisionByteLength,\n                                        CollisionBitLength + 1,\n                                        partialSoln.get()[lti], partialSoln.get()[rti]);\n\n                        // 2d) Check if this has become an invalid solution\n                        if (ic->size() == 0)\n                            goto invalidsolution;\n\n                        X[r] = boost::none;\n                        hashLen -= CollisionByteLength;\n                        lenIndices *= 2;\n                        rti = lti;\n                    } else {\n                        X[r] = *ic;\n                        break;\n                    }\n                } else {\n                    X.push_back(ic);\n                    break;\n                }\n                if (cancelled(PartialSubtreeEnd)) throw solver_cancelled;\n            }\n            if (cancelled(PartialIndexEnd)) throw solver_cancelled;\n        }\n\n        // We are at the top of the tree\n        assert(X.size() == K+1);\n        for (FullStepRow<FinalFullWidth> row : *X[K]) {\n            auto soln = row.GetIndices(hashLen, lenIndices, CollisionBitLength);\n            assert(soln.size() == equihash_solution_size(N, K));\n            solns.insert(soln);\n        }\n        for (auto soln : solns) {\n            if (validBlock(soln))\n                return true;\n        }\n        if (cancelled(PartialEnd)) throw solver_cancelled;\n        continue;\n\ninvalidsolution:\n        invalidCount++;\n    }\n    LogPrint(BCLog::POW, \"- Number of invalid solutions found: %zu\\n\", invalidCount);\n\n    return false;\n}\n\ntemplate<unsigned int N, unsigned int K>\nbool Equihash<N,K>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln)\n{\n    if (soln.size() != SolutionWidth) {\n        LogPrint(BCLog::POW, \"Invalid solution length: %d (expected %d)\\n\",\n                 soln.size(), SolutionWidth);\n        return false;\n    }\n\n    std::vector<FullStepRow<FinalFullWidth>> X;\n    X.reserve(1 << K);\n    unsigned char tmpHash[HashOutput];\n    for (eh_index i : GetIndicesFromMinimal(soln, CollisionBitLength)) {\n        GenerateHash(base_state, i/IndicesPerHashOutput, tmpHash, HashOutput);\n        X.emplace_back(tmpHash+((i % IndicesPerHashOutput) * N/8),\n                       N/8, HashLength, CollisionBitLength, i);\n    }\n\n    size_t hashLen = HashLength;\n    size_t lenIndices = sizeof(eh_index);\n    while (X.size() > 1) {\n        std::vector<FullStepRow<FinalFullWidth>> Xc;\n        for (size_t i = 0; i < X.size(); i += 2) {\n            if (!HasCollision(X[i], X[i+1], CollisionByteLength)) {\n                LogPrint(BCLog::POW, \"Invalid solution: invalid collision length between StepRows\\n\");\n                LogPrint(BCLog::POW, \"X[i]   = %s\\n\", X[i].GetHex(hashLen));\n                LogPrint(BCLog::POW, \"X[i+1] = %s\\n\", X[i+1].GetHex(hashLen));\n                return false;\n            }\n            if (X[i+1].IndicesBefore(X[i], hashLen, lenIndices)) {\n                LogPrint(BCLog::POW, \"Invalid solution: Index tree incorrectly ordered\\n\");\n                return false;\n            }\n            if (!DistinctIndices(X[i], X[i+1], hashLen, lenIndices)) {\n                LogPrint(BCLog::POW, \"Invalid solution: duplicate indices\\n\");\n                return false;\n            }\n            Xc.emplace_back(X[i], X[i+1], hashLen, lenIndices, CollisionByteLength);\n        }\n        X = Xc;\n        hashLen -= CollisionByteLength;\n        lenIndices *= 2;\n    }\n\n    assert(X.size() == 1);\n    return X[0].IsZero(hashLen);\n}\n\n// Explicit instantiations for Equihash<96,3>\ntemplate int Equihash<96,3>::InitialiseState(eh_HashState& base_state);\ntemplate bool Equihash<96,3>::BasicSolve(const eh_HashState& base_state,\n                                         const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                         const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<96,3>::OptimisedSolve(const eh_HashState& base_state,\n                                             const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                             const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<96,3>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n\n// Explicit instantiations for Equihash<200,9>\ntemplate int Equihash<200,9>::InitialiseState(eh_HashState& base_state);\ntemplate bool Equihash<200,9>::BasicSolve(const eh_HashState& base_state,\n                                          const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                          const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<200,9>::OptimisedSolve(const eh_HashState& base_state,\n                                              const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                              const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<200,9>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n\n// Explicit instantiations for Equihash<96,5>\ntemplate int Equihash<96,5>::InitialiseState(eh_HashState& base_state);\ntemplate bool Equihash<96,5>::BasicSolve(const eh_HashState& base_state,\n                                         const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                         const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<96,5>::OptimisedSolve(const eh_HashState& base_state,\n                                             const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                             const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<96,5>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n\n// Explicit instantiations for Equihash<48,5>\ntemplate int Equihash<48,5>::InitialiseState(eh_HashState& base_state);\ntemplate bool Equihash<48,5>::BasicSolve(const eh_HashState& base_state,\n                                         const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                         const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<48,5>::OptimisedSolve(const eh_HashState& base_state,\n                                             const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                             const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<48,5>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n\n\n// Explicit instantiations for Equihash<176,7>\ntemplate int Equihash<176,7>::InitialiseState(eh_HashState& base_state);\ntemplate bool Equihash<176,7>::BasicSolve(const eh_HashState& base_state,\n                                         const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                         const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<176,7>::OptimisedSolve(const eh_HashState& base_state,\n                                             const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                             const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<176,7>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n\n// Explicit instantiations for Equihash<144,5>\ntemplate int Equihash<144,5>::InitialiseState(eh_HashState& base_state);\ntemplate bool Equihash<144,5>::BasicSolve(const eh_HashState& base_state,\n                                          const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                          const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<144,5>::OptimisedSolve(const eh_HashState& base_state,\n                                              const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                              const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<144,5>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n\n// Explicit instantiations for Equihash<168,7>\ntemplate int Equihash<168,7>::InitialiseState(eh_HashState& base_state);\ntemplate bool Equihash<168,7>::BasicSolve(const eh_HashState& base_state,\n                                          const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                          const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<168,7>::OptimisedSolve(const eh_HashState& base_state,\n                                              const std::function<bool(std::vector<unsigned char>)> validBlock,\n                                              const std::function<bool(EhSolverCancelCheck)> cancelled);\ntemplate bool Equihash<168,7>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);\n\n", "meta": {"hexsha": "4ff543f64189d38987761f215ff6948f012f7692", "size": 35423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypto/equihash.cpp", "max_stars_repo_name": "bitcoinpostquantum/bitcoinpq", "max_stars_repo_head_hexsha": "28a1f3ce998e5b37b52e0505e1f7ab18a4b785a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T20:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T20:01:39.000Z", "max_issues_repo_path": "src/crypto/equihash.cpp", "max_issues_repo_name": "bitcoinpostquantum/bitcoinpq", "max_issues_repo_head_hexsha": "28a1f3ce998e5b37b52e0505e1f7ab18a4b785a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crypto/equihash.cpp", "max_forks_repo_name": "bitcoinpostquantum/bitcoinpq", "max_forks_repo_head_hexsha": "28a1f3ce998e5b37b52e0505e1f7ab18a4b785a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T03:01:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T08:20:08.000Z", "avg_line_length": 41.625146886, "max_line_length": 188, "alphanum_fraction": 0.5533975101, "num_tokens": 9032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.027585285224643135, "lm_q1q2_score": 0.013792642612321568}}
{"text": "#ifndef PATCHWORK_H\n#define PATCHWORK_H\n\n#include <Eigen/Dense>\n#include <boost/format.hpp>\n\n#define MARKER_Z_VALUE -2.2\n#define UPRIGHT_ENOUGH 0.55\n#define FLAT_ENOUGH 0.2\n#define TOO_HIGH_ELEVATION 0.0\n#define TOO_TILTED 1.0\n\n#define NUM_HEURISTIC_MAX_PTS_IN_PATCH 3000\n\nusing Eigen::MatrixXf;\nusing Eigen::JacobiSVD;\nusing Eigen::VectorXf;\n\nusing namespace std;\n\n\nstatic int64_t gtm() {\n\tstruct timeval tm;\n\tgettimeofday(&tm, 0);\n\t// return ms\n\tint64_t re = (((int64_t) tm.tv_sec) * 1000 * 1000 + tm.tv_usec);\n\treturn re;\n}\n\n/*\n    @brief PathWork ROS Node.\n*/\ntemplate <typename PointT>\nbool point_z_cmp(PointT a, PointT b) {\n    return a.z < b.z;\n}\n\ntemplate <typename PointT>\nclass PatchWork {\n\npublic:\n    typedef std::vector<pcl::PointCloud<PointT> > Ring;\n    typedef std::vector<Ring> Zone;\n\n    PatchWork(){\n\n\tnum_sectors_each_zone_ = {16, 32 ,54, 32};\n\tnum_rings_each_zone_ =  {2, 4, 4, 4};\n\televation_thr_ = {-1.2, -0.9984, -0.851, -0.605};\n\tflatness_thr_ = {0.0, 0.000125, 0.000185, 0.000185};\n\n        if (num_zones_ != 4 || num_sectors_each_zone_.size() != num_rings_each_zone_.size()) {\n            throw invalid_argument(\"Some parameters are wrong! Check the num_zones and num_rings/sectors_each_zone\");\n        }\n        if (elevation_thr_.size() != flatness_thr_.size()) {\n            throw invalid_argument(\"Some parameters are wrong! Check the elevation/flatness_thresholds\");\n        }\n\n        cout << (boost::format(\"Num. sectors: %d, %d, %d, %d\") % num_sectors_each_zone_[0] % num_sectors_each_zone_[1] %\n                 num_sectors_each_zone_[2] %\n                 num_sectors_each_zone_[3]).str() << endl;\n        cout << (boost::format(\"Num. rings: %01d, %01d, %01d, %01d\") % num_rings_each_zone_[0] %\n                 num_rings_each_zone_[1] %\n                 num_rings_each_zone_[2] %\n                 num_rings_each_zone_[3]).str() << endl;\n        cout << (boost::format(\"elevation_thr_: %0.4f, %0.4f, %0.4f, %0.4f \") % elevation_thr_[0] % elevation_thr_[1] %\n                 elevation_thr_[2] %\n                 elevation_thr_[3]).str() << endl;\n        cout << (boost::format(\"flatness_thr_: %0.4f, %0.4f, %0.4f, %0.4f \") % flatness_thr_[0] % flatness_thr_[1] %\n                 flatness_thr_[2] %\n                 flatness_thr_[3]).str() << endl;\n        num_rings_of_interest_ = elevation_thr_.size();\n\n        revert_pc.reserve(NUM_HEURISTIC_MAX_PTS_IN_PATCH);\n        ground_pc_.reserve(NUM_HEURISTIC_MAX_PTS_IN_PATCH);\n        non_ground_pc_.reserve(NUM_HEURISTIC_MAX_PTS_IN_PATCH);\n        regionwise_ground_.reserve(NUM_HEURISTIC_MAX_PTS_IN_PATCH);\n        regionwise_nonground_.reserve(NUM_HEURISTIC_MAX_PTS_IN_PATCH);\n\n\n\n        min_range_z2_ = (7 * min_range_ + max_range_) / 8.0;\n        min_range_z3_ = (3 * min_range_ + max_range_) / 4.0;\n        min_range_z4_ = (min_range_ + max_range_) / 2.0;\n\n        min_ranges = {min_range_, min_range_z2_, min_range_z3_, min_range_z4_};\n        ring_sizes = {(min_range_z2_ - min_range_) / num_rings_each_zone_.at(0),\n                      (min_range_z3_ - min_range_z2_) / num_rings_each_zone_.at(1),\n                      (min_range_z4_ - min_range_z3_) / num_rings_each_zone_.at(2),\n                      (max_range_ - min_range_z4_) / num_rings_each_zone_.at(3)};\n        sector_sizes = {2 * M_PI / num_sectors_each_zone_.at(0), 2 * M_PI / num_sectors_each_zone_.at(1),\n                        2 * M_PI / num_sectors_each_zone_.at(2),\n                        2 * M_PI / num_sectors_each_zone_.at(3)};\n        cout << \"INITIALIZATION COMPLETE\" << endl;\n\n        for (int iter = 0; iter < num_zones_; ++iter) {\n            Zone z;\n            initialize_zone(z, num_sectors_each_zone_.at(iter), num_rings_each_zone_.at(iter));\n            ConcentricZoneModel_.push_back(z);\n        }\n    }\n\n    void estimate_ground(\n            const pcl::PointCloud<PointT> &cloudIn,\n            pcl::PointCloud<PointT> &cloudOut,\n            pcl::PointCloud<PointT> &cloudNonground,\n            double &time_taken);\n\n\nprivate:\n\n    int num_iter_ = 3;\n    int num_lpr_ = 20;\n    int num_min_pts_ = 10;\n    int num_rings_ = 30;\n    int num_sectors_ = 108;\n    int num_zones_ = 4;\n    int num_rings_of_interest_ = 2.7;\n\n    double sensor_height_ = 1.723;\n    double th_seeds_ = 0.5;\n    double th_dist_ = 0.125;\n    double max_range_ = 80.0;\n    double min_range_ = 2.7;\n    double uprightness_thr_ = 0.707;\n    double adaptive_seed_selection_margin_ = -1.1;\n    double min_range_z2_; // 12.3625\n    double min_range_z3_; // 22.025\n    double min_range_z4_; // 41.35\n\n    bool verbose_ = false;\n\n    float d_;\n    MatrixXf normal_;\n    VectorXf singular_values_;\n    float th_dist_d_;\n    Eigen::Matrix3f cov_;\n    Eigen::Vector4f pc_mean_;\n    double ring_size;\n    double sector_size;\n    // For visualization\n    bool visualize_;\n\n    vector<int> num_sectors_each_zone_;\n    vector<int> num_rings_each_zone_;\n\n    vector<double> sector_sizes;\n    vector<double> ring_sizes;\n    vector<double> min_ranges;\n    vector<double> elevation_thr_;\n    vector<double> flatness_thr_;\n\n    vector<Zone> ConcentricZoneModel_;\n\n    pcl::PointCloud<PointT> revert_pc, reject_pc;\n    pcl::PointCloud<PointT> ground_pc_;\n    pcl::PointCloud<PointT> non_ground_pc_;\n\n    pcl::PointCloud<PointT> regionwise_ground_;\n    pcl::PointCloud<PointT> regionwise_nonground_;\n\n    void initialize_zone(Zone &z, int num_sectors, int num_rings);\n\n    void flush_patches_in_zone(Zone &patches, int num_sectors, int num_rings);\n\n    double calc_principal_variance(const Eigen::Matrix3f &cov, const Eigen::Vector4f &centroid);\n\n    double xy2theta(const double &x, const double &y);\n\n    double xy2radius(const double &x, const double &y);\n\n    void pc2czm(const pcl::PointCloud<PointT> &src, std::vector<Zone> &czm);\n\n    void estimate_plane_(const pcl::PointCloud<PointT> &ground);\n\n    void extract_piecewiseground(\n            const int zone_idx, const pcl::PointCloud<PointT> &src,\n            pcl::PointCloud<PointT> &dst,\n            pcl::PointCloud<PointT> &non_ground_dst);\n\n    void estimate_plane_(const int zone_idx, const pcl::PointCloud<PointT> &ground);\n\n    void extract_initial_seeds_(\n            const int zone_idx, const pcl::PointCloud<PointT> &p_sorted,\n            pcl::PointCloud<PointT> &init_seeds);\n\n\n};\n\ntemplate<typename PointT> inline\nvoid PatchWork<PointT>::initialize_zone(Zone &z, int num_sectors, int num_rings) {\n    z.clear();\n    pcl::PointCloud<PointT> cloud;\n    cloud.reserve(1000);\n    Ring ring;\n    for (int i = 0; i < num_sectors; i++) {\n        ring.emplace_back(cloud);\n    }\n    for (int j = 0; j < num_rings; j++) {\n        z.emplace_back(ring);\n    }\n}\n\ntemplate<typename PointT> inline\nvoid PatchWork<PointT>::flush_patches_in_zone(Zone &patches, int num_sectors, int num_rings) {\n    for (int i = 0; i < num_sectors; i++) {\n        for (int j = 0; j < num_rings; j++) {\n            if (!patches[j][i].points.empty()) patches[j][i].points.clear();\n        }\n    }\n}\n\ntemplate<typename PointT> inline\nvoid PatchWork<PointT>::estimate_plane_(const pcl::PointCloud<PointT> &ground) {\n    pcl::computeMeanAndCovarianceMatrix(ground, cov_, pc_mean_);\n    // Singular Value Decomposition: SVD\n    Eigen::JacobiSVD<Eigen::MatrixXf> svd(cov_, Eigen::DecompositionOptions::ComputeFullU);\n    singular_values_ = svd.singularValues();\n\n    // use the least singular vector as normal\n    normal_ = (svd.matrixU().col(2));\n    // mean ground seeds value\n    Eigen::Vector3f seeds_mean = pc_mean_.head<3>();\n\n    // according to normal.T*[x,y,z] = -d\n    d_ = -(normal_.transpose() * seeds_mean)(0, 0);\n    // set distance threhold to `th_dist - d`\n    th_dist_d_ = th_dist_ - d_;\n}\n\ntemplate<typename PointT> inline\nvoid PatchWork<PointT>::extract_initial_seeds_(\n        const int zone_idx, const pcl::PointCloud<PointT> &p_sorted,\n        pcl::PointCloud<PointT> &init_seeds) {\n    init_seeds.points.clear();\n\n    // LPR is the mean of low point representative\n    double sum = 0;\n    int cnt = 0;\n\n    int init_idx = 0;\n    if (zone_idx == 0) {\n        for (int i = 0; i < p_sorted.points.size(); i++) {\n            if (p_sorted.points[i].z < adaptive_seed_selection_margin_ * sensor_height_) {\n                ++init_idx;\n            } else {\n                break;\n            }\n        }\n    }\n\n    // Calculate the mean height value.\n    for (int i = init_idx; i < p_sorted.points.size() && cnt < num_lpr_; i++) {\n        sum += p_sorted.points[i].z;\n        cnt++;\n    }\n    double lpr_height = cnt != 0 ? sum / cnt : 0;// in case divide by 0\n\n    // iterate pointcloud, filter those height is less than lpr.height+th_seeds_\n    for (int i = 0; i < p_sorted.points.size(); i++) {\n        if (p_sorted.points[i].z < lpr_height + th_seeds_) {\n            init_seeds.points.push_back(p_sorted.points[i]);\n        }\n    }\n}\n\n\n/*\n    @brief Velodyne pointcloud callback function. The main GPF pipeline is here.\n    PointCloud SensorMsg -> Pointcloud -> z-value sorted Pointcloud\n    ->error points removal -> extract ground seeds -> ground plane fit mainloop\n*/\n\ntemplate<typename PointT> inline\nvoid PatchWork<PointT>::estimate_ground(\n        const pcl::PointCloud<PointT> &cloud_in,\n        pcl::PointCloud<PointT> &cloud_out,\n        pcl::PointCloud<PointT> &cloud_nonground,\n        double &time_taken) {\n\n    static double start, t0, t1, t2, end;\n\n    double t_total_ground = 0.0;\n    double t_total_estimate = 0.0;\n    // 1.Msg to pointcloud\n    pcl::PointCloud<PointT> laserCloudIn;\n    laserCloudIn = cloud_in;\n\n    start = gtm();\n\n    // 2.Sort on Z-axis value.\n    sort(laserCloudIn.points.begin(), laserCloudIn.end(), point_z_cmp<PointT>);\n\n    t0 = gtm();\n    // 3.Error point removal\n    // As there are some error mirror reflection under the ground,\n    // here regardless point under 1.8* sensor_height\n    // Sort point according to height, here uses z-axis in default\n    auto it = laserCloudIn.points.begin();\n    for (int i = 0; i < laserCloudIn.points.size(); i++) {\n        if (laserCloudIn.points[i].z < -1.8 * sensor_height_) {\n            it++;\n        } else {\n            break;\n        }\n    }\n    laserCloudIn.points.erase(laserCloudIn.points.begin(), it);\n\n    t1 = gtm();\n    // 4. pointcloud -> regionwise setting\n    for (int k = 0; k < num_zones_; ++k) {\n        flush_patches_in_zone(ConcentricZoneModel_[k], num_sectors_each_zone_[k], num_rings_each_zone_[k]);\n    }\n    pc2czm(laserCloudIn, ConcentricZoneModel_);\n\n    t2 =gtm();\n\n    cloud_out.clear();\n    cloud_nonground.clear();\n    revert_pc.clear();\n    reject_pc.clear();\n\n    int concentric_idx = 0;\n    for (int k = 0; k < num_zones_; ++k) {\n        auto zone = ConcentricZoneModel_[k];\n        for (uint16_t ring_idx = 0; ring_idx < num_rings_each_zone_[k]; ++ring_idx) {\n            for (uint16_t sector_idx = 0; sector_idx < num_sectors_each_zone_[k]; ++sector_idx) {\n                if (zone[ring_idx][sector_idx].points.size() > num_min_pts_) {\n                    double t_tmp0 = gtm();\n                    extract_piecewiseground(k, zone[ring_idx][sector_idx], regionwise_ground_, regionwise_nonground_);\n                    double t_tmp1 = gtm();\n                    t_total_ground += t_tmp1 - t_tmp0;\n\n                    // Status of each patch\n                    // used in checking uprightness, elevation, and flatness, respectively\n                    const double ground_z_vec = abs(normal_(2, 0));\n                    const double ground_z_elevation = pc_mean_(2, 0);\n                    const double surface_variable =\n                            singular_values_.minCoeff() /\n                            (singular_values_(0) + singular_values_(1) + singular_values_(2));\n\n                    double t_tmp2 = gtm();\n                    if (ground_z_vec < uprightness_thr_) {\n                        // All points are rejected\n                        cloud_nonground += regionwise_ground_;\n                        cloud_nonground += regionwise_nonground_;\n                    } else { // satisfy uprightness\n                        if (concentric_idx < num_rings_of_interest_) {\n                            if (ground_z_elevation > elevation_thr_[ring_idx + 2 * k]) {\n                                if (flatness_thr_[ring_idx + 2 * k] > surface_variable) {\n                                    if (verbose_) {\n                                        std::cout << \"\\033[1;36m[Flatness] Recovery operated. Check \"\n                                                  << ring_idx + 2 * k\n                                                  << \"th param. flatness_thr_: \" << flatness_thr_[ring_idx + 2 * k]\n                                                  << \" > \"\n                                                  << surface_variable << \"\\033[0m\" << std::endl;\n                                        revert_pc += regionwise_ground_;\n                                    }\n                                    cloud_out += regionwise_ground_;\n                                    cloud_nonground += regionwise_nonground_;\n                                } else {\n                                    if (verbose_) {\n                                        std::cout << \"\\033[1;34m[Elevation] Rejection operated. Check \"\n                                                  << ring_idx + 2 * k\n                                                  << \"th param. of elevation_thr_: \" << elevation_thr_[ring_idx + 2 * k]\n                                                  << \" < \"\n                                                  << ground_z_elevation << \"\\033[0m\" << std::endl;\n                                        reject_pc += regionwise_ground_;\n                                    }\n                                    cloud_nonground += regionwise_ground_;\n                                    cloud_nonground += regionwise_nonground_;\n                                }\n                            } else {\n                                cloud_out += regionwise_ground_;\n                                cloud_nonground += regionwise_nonground_;\n                            }\n                        } else {\n                            cloud_out += regionwise_ground_;\n                            cloud_nonground += regionwise_nonground_;\n                        }\n                    }\n                    double t_tmp3 = gtm();\n                    t_total_estimate += t_tmp3 - t_tmp2;\n                }\n            }\n            ++concentric_idx;\n        }\n    }\n    end =gtm();\n    time_taken = end - start;\n//    ofstream time_txt(\"/home/shapelim/patchwork_time_anal.txt\", std::ios::app);\n//    time_txt<<t0 - start<<\" \"<<t1 - t0 <<\" \"<<t2-t1<<\" \"<<t_total_ground<< \" \"<<t_total_estimate<<\"\\n\";\n//    time_txt.close();\n\n}\n\ntemplate<typename PointT> inline\ndouble PatchWork<PointT>::calc_principal_variance(const Eigen::Matrix3f &cov, const Eigen::Vector4f &centroid) {\n    double angle = atan2(centroid(1, 0), centroid(0, 0)); // y, x\n    double c = cos(angle);\n    double s = sin(angle);\n    double var_x_prime = c * c * cov(0, 0) + s * s * cov(1, 1) + 2 * c * s * cov(0, 1);\n    double var_y_prime = s * s * cov(0, 0) + c * c * cov(1, 1) - 2 * c * s * cov(0, 1);\n    return max(var_x_prime, var_y_prime);\n}\n\n\ntemplate<typename PointT> inline\ndouble PatchWork<PointT>::xy2theta(const double &x, const double &y) { // 0 ~ 2 * PI\n    if (y >= 0) {\n        return atan2(y, x); // 1, 2 quadrant\n    } else {\n        return 2 * M_PI + atan2(y, x);// 3, 4 quadrant\n    }\n}\n\ntemplate<typename PointT> inline\ndouble PatchWork<PointT>::xy2radius(const double &x, const double &y) {\n    return sqrt(pow(x, 2) + pow(y, 2));\n}\n\ntemplate<typename PointT> inline\nvoid PatchWork<PointT>::pc2czm(const pcl::PointCloud<PointT> &src, std::vector<Zone> &czm) {\n\n    for (auto const &pt : src.points) {\n        int ring_idx, sector_idx;\n        double r = xy2radius(pt.x, pt.y);\n        if ((r <= max_range_) && (r > min_range_)) {\n            double theta = xy2theta(pt.x, pt.y);\n\n            if (r < min_range_z2_) { // In First rings\n                ring_idx = min(static_cast<int>(((r - min_range_) / ring_sizes[0])), num_rings_each_zone_[0] - 1);\n                sector_idx = min(static_cast<int>((theta / sector_sizes[0])), num_sectors_each_zone_[0] - 1);\n                czm[0][ring_idx][sector_idx].points.emplace_back(pt);\n            } else if (r < min_range_z3_) {\n                ring_idx = min(static_cast<int>(((r - min_range_z2_) / ring_sizes[1])), num_rings_each_zone_[1] - 1);\n                sector_idx = min(static_cast<int>((theta / sector_sizes[1])), num_sectors_each_zone_[1] - 1);\n                czm[1][ring_idx][sector_idx].points.emplace_back(pt);\n            } else if (r < min_range_z4_) {\n                ring_idx = min(static_cast<int>(((r - min_range_z3_) / ring_sizes[2])), num_rings_each_zone_[2] - 1);\n                sector_idx = min(static_cast<int>((theta / sector_sizes[2])), num_sectors_each_zone_[2] - 1);\n                czm[2][ring_idx][sector_idx].points.emplace_back(pt);\n            } else { // Far!\n                ring_idx = min(static_cast<int>(((r - min_range_z4_) / ring_sizes[3])), num_rings_each_zone_[3] - 1);\n                sector_idx = min(static_cast<int>((theta / sector_sizes[3])), num_sectors_each_zone_[3] - 1);\n                czm[3][ring_idx][sector_idx].points.emplace_back(pt);\n            }\n        }\n\n    }\n}\n\n// For adaptive\ntemplate<typename PointT> inline\nvoid PatchWork<PointT>::extract_piecewiseground(\n        const int zone_idx, const pcl::PointCloud<PointT> &src,\n        pcl::PointCloud<PointT> &dst,\n        pcl::PointCloud<PointT> &non_ground_dst) {\n    // 0. Initialization\n    if (!ground_pc_.empty()) ground_pc_.clear();\n    if (!dst.empty()) dst.clear();\n    if (!non_ground_dst.empty()) non_ground_dst.clear();\n    // 1. set seeds!\n\n    extract_initial_seeds_(zone_idx, src, ground_pc_);\n    // 2. Extract ground\n    for (int i = 0; i < num_iter_; i++) {\n        estimate_plane_(ground_pc_);\n        ground_pc_.clear();\n\n        //pointcloud to matrix\n        Eigen::MatrixXf points(src.points.size(), 3);\n        int j = 0;\n        for (auto &p:src.points) {\n            points.row(j++) << p.x, p.y, p.z;\n        }\n        // ground plane model\n        Eigen::VectorXf result = points * normal_;\n        // threshold filter\n        for (int r = 0; r < result.rows(); r++) {\n            if (i < num_iter_ - 1) {\n                if (result[r] < th_dist_d_) {\n                    ground_pc_.points.push_back(src[r]);\n                }\n            } else { // Final stage\n                if (result[r] < th_dist_d_) {\n                    dst.points.push_back(src[r]);\n                } else {\n                    if (i == num_iter_ - 1) {\n                        non_ground_dst.push_back(src[r]);\n                    }\n                }\n            }\n        }\n    }\n}\n\n\n#endif\n", "meta": {"hexsha": "b5b118dfdb83ef17c6721a672182c16b6ccf42d9", "size": 18829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/patchwork.hpp", "max_stars_repo_name": "asdfghjkl623/Lidar-Segementation-3d-cvc", "max_stars_repo_head_hexsha": "4a15c9533c8f7e191544c8da5463791d3499ba16", "max_stars_repo_licenses": ["MIT"], "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/patchwork.hpp", "max_issues_repo_name": "asdfghjkl623/Lidar-Segementation-3d-cvc", "max_issues_repo_head_hexsha": "4a15c9533c8f7e191544c8da5463791d3499ba16", "max_issues_repo_licenses": ["MIT"], "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/patchwork.hpp", "max_forks_repo_name": "asdfghjkl623/Lidar-Segementation-3d-cvc", "max_forks_repo_head_hexsha": "4a15c9533c8f7e191544c8da5463791d3499ba16", "max_forks_repo_licenses": ["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.658, "max_line_length": 120, "alphanum_fraction": 0.5737957406, "num_tokens": 4899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.027585283126145898, "lm_q1q2_score": 0.013792641563072949}}
{"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/qmiter.h>\n#include <sys/stat.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <votca/tools/constants.h>\n#include <votca/ctp/apolarsite.h>\n\nusing boost::format;\n\nnamespace votca {\n    namespace xtp {\n\n     \nvoid QMMIter::UpdateMPSFromGDMA(std::vector<std::vector<double> > &multipoles, std::vector< ctp::PolarSeg* > &psegs) {\n\n\n            for (unsigned int i = 0, qac = 0; i < psegs.size(); ++i) {\n                ctp::PolarSeg *pseg = psegs[i];\n                for (unsigned int j = 0; j < pseg->size(); ++j, ++qac) {\n\n                    // Retrieve multipole info of this atom\n                    std::vector<double> update = multipoles[qac];\n                    while (update.size() < 9) update.push_back(0.0);\n\n                    // Convert e*(a_0)^k to e*(nm)^k where k = rank\n                   \n                    for (int m = 1; m < 4; m++) {\n                        update[m] *= pow(tools::conv::bohr2nm, 1);\n                    }\n                    for (int m = 4; m < 9; m++) {\n                        update[m] *= pow(tools::conv::bohr2nm, 2);\n                    }\n\n                    ctp::APolarSite *aps = (*pseg)[j];\n                   \n                    aps->setQs(update, 0);\n\n                }\n            }\n\n            return;\n        }\n\n        void QMMIter::UpdatePosChrgFromQMAtoms(std::vector< ctp::QMAtom* > &qmatoms,\n                std::vector< ctp::PolarSeg* > &psegs) {\n\n            double AA_to_NM = tools::conv::ang2nm;\n\n            double dR_RMS = 0.0;\n            double dQ_RMS = 0.0;\n            double dQ_SUM = 0.0;\n\n            for (unsigned int i = 0, qac = 0; i < psegs.size(); ++i) {\n                ctp::PolarSeg *pseg = psegs[i];\n                for (unsigned int j = 0; j < pseg->size(); ++j, ++qac) {\n\n                    // Retrieve info from ctp::QMAtom\n                    ctp::QMAtom *qmatm = qmatoms[qac];\n                    vec upd_r = qmatm->getPos();\n                    upd_r *= AA_to_NM;\n                    double upd_Q00 = qmatm->charge;\n\n\n                    // Compare to previous r, Q00\n                    ctp::APolarSite *aps = (*pseg)[j];\n                    vec old_r = aps->getPos();\n                    double old_Q00 = aps->getQ00();\n                    double dR = abs(upd_r - old_r);\n                    double dQ00 = upd_Q00 - old_Q00;\n\n                    dR_RMS += dR*dR;\n                    dQ_RMS += dQ00*dQ00;\n                    dQ_SUM += dQ00;\n\n                    // Forward updated r, Q00 to APS\n                    aps->setPos(upd_r);\n                    aps->setQ00(upd_Q00, 0);\n                }\n            }\n\n\n            // cout << \" dR_RMS \" << dR_RMS << \"dQ RMS \" << dQ_RMS << endl;\n            dR_RMS /= qmatoms.size();\n            dQ_RMS /= qmatoms.size();\n            dR_RMS = sqrt(dR_RMS);\n            dQ_RMS = sqrt(dQ_RMS);\n\n            // cout << \" dR_RMS \" << dR_RMS << \"dQ RMS \" << dQ_RMS << endl;\n\n\n            this->setdRdQ(dR_RMS, dQ_RMS, dQ_SUM);\n            return;\n        }\n\n        \n\n        void QMMIter::setdRdQ(double dR_RMS, double dQ_RMS, double dQ_SUM) {\n\n            _hasdRdQ = true;\n            _dR_RMS = dR_RMS;\n            _dQ_RMS = dQ_RMS;\n            _dQ_SUM = dQ_SUM;\n            return;\n        }\n\n        void QMMIter::setQMSF(double energy_QM, double energy_SF, double energy_GWBSE) {\n\n            _hasQM = true;\n            _e_QM = energy_QM;\n            _e_SF = energy_SF;\n\n            _hasGWBSE = true;\n            _e_GWBSE = energy_GWBSE;\n\n            return;\n        }\n\n        void QMMIter::setE_FM(double ef00, double ef01, double ef02,\n                double ef11, double ef12, double em0, double em1, double em2, double efm) {\n\n            _hasMM = true;\n            _ef_00 = ef00;\n            _ef_01 = ef01;\n            _ef_02 = ef02;\n            _ef_11 = ef11;\n            _ef_12 = ef12;\n            _em_0_ = em0;\n            _em_1_ = em1;\n            _em_2_ = em2;\n            _e_fm_ = efm;\n            return;\n        }\n\n        double QMMIter::getMMEnergy() {\n\n            assert(_hasMM);\n            return _ef_11 + _ef_12 + _em_1_ + _em_2_;\n        }\n\n        double QMMIter::getQMMMEnergy() {\n\n            assert(_hasQM && _hasMM && _hasGWBSE);\n            return _e_QM + + _e_GWBSE + _ef_11 + _ef_12 + _em_1_ + _em_2_;\n        }\n\n\n\n\n    }\n}\n", "meta": {"hexsha": "0c6a4d6433cd717ca742ee0b1b9f011a5f2bec74", "size": 5125, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/qmiter.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/qmiter.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/qmiter.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": 29.7965116279, "max_line_length": 118, "alphanum_fraction": 0.4844878049, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.028436035309096674, "lm_q1q2_score": 0.01377384917952355}}
{"text": "/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkPBGLRMATGraphSource.cxx\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  Copyright 2008 Sandia Corporation.\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/* \n * Copyright (C) 2008 The Trustees of Indiana University.\n * Use, modification and distribution is subject to the Boost Software\n * License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt)\n */\n#include \"vtkPBGLRMATGraphSource.h\"\n\n#include \"vtkBlockDistribution.h\"\n#include \"vtkCellData.h\"\n#include \"vtkExecutive.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkGraph.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkMath.h\"\n#include \"vtkMPI.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkMutableUndirectedGraph.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPBGLDistributedGraphHelper.h\"\n#include \"vtkPointData.h\"\n#include \"vtkSmartPointer.h\"\n\n#include <vtksys/stl/set>\n#include <vtksys/stl/algorithm>\n#include <vtksys/stl/functional>\n\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/collectives/scan.hpp>\n\nvtkStandardNewMacro(vtkPBGLRMATGraphSource);\n\n// ----------------------------------------------------------------------\nvtkPBGLRMATGraphSource::vtkPBGLRMATGraphSource()\n{\n  int rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  this->NumberOfVertices = 128;\n  this->NumberOfEdges = 512;\n  this->A = 0.25;\n  this->B = 0.25;\n  this->C = 0.25;\n  this->D = 0.25;\n  this->IncludeEdgeWeights = false;\n  this->AllowSelfLoops = false;\n  this->GeneratePedigreeIds = true;\n  this->VertexPedigreeIdArrayName = 0;\n  this->SetVertexPedigreeIdArrayName(\"vertex id\");\n  this->EdgePedigreeIdArrayName = 0;\n  this->SetEdgePedigreeIdArrayName(\"edge id\");\n  this->EdgeWeightArrayName = 0;\n  this->SetEdgeWeightArrayName(\"edge weight\");\n  this->Seed = 1177 + 17 * rank;\n  this->SetNumberOfInputPorts(0);\n  this->SetNumberOfOutputPorts(1);\n}\n\n// ----------------------------------------------------------------------\n\nvtkPBGLRMATGraphSource::~vtkPBGLRMATGraphSource()\n{\n  this->SetVertexPedigreeIdArrayName(0);\n  this->SetEdgePedigreeIdArrayName(0);\n  this->SetEdgeWeightArrayName(0);\n}\n\n// ----------------------------------------------------------------------\n\nvoid \nvtkPBGLRMATGraphSource::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"NumberOfVertices: \" << this->NumberOfVertices << endl;\n  os << indent << \"NumberOfEdges: \" << this->NumberOfEdges << endl;\n  os << indent << \"Probabilities: \" << this->A << \", \" << this->B << \", \" \n     << this->C << \", \" << this->D << endl;\n  os << indent << \"IncludeEdgeWeights: \" << this->IncludeEdgeWeights << endl;\n  os << indent << \"AllowSelfLoops: \" << this->AllowSelfLoops << endl;\n  os << indent << \"GeneratePedigreeIds: \" << this->GeneratePedigreeIds << endl;\n  os << indent << \"VertexPedigreeIdArrayName: \"\n    << (this->VertexPedigreeIdArrayName ? this->VertexPedigreeIdArrayName : \"(null)\") << endl;\n  os << indent << \"EdgePedigreeIdArrayName: \"\n    << (this->EdgePedigreeIdArrayName ? this->EdgePedigreeIdArrayName : \"(null)\") << endl;\n  os << indent << \"EdgeWeightArrayName: \"\n    << (this->EdgeWeightArrayName ? this->EdgeWeightArrayName : \"(null)\") << endl;\n  os << indent << \"Seed: \" << this->Seed << endl;\n}\n\n// ----------------------------------------------------------------------\nvoid vtkPBGLRMATGraphSource::SetNumberOfVertices(vtkIdType value)\n{\n  vtkIdType mask = (vtkIdType) 1 << ((sizeof(vtkIdType) * CHAR_BIT) - 2);\n  while (mask != 0) \n    {\n    if (value & mask)\n      {\n      // We've found the most significant 1-bit.\n      if (value & (mask >> (vtkIdType) 1))\n        {\n        // Round up to the next power of two.\n        mask = mask << (vtkIdType) 1;\n        }\n      break;\n      }\n\n    mask = mask >> (vtkIdType) 1;\n    }\n\n  this->NumberOfVertices = mask;\n}\n\n// ----------------------------------------------------------------------\nvoid \nvtkPBGLRMATGraphSource::SetProbabilities(double A, double B, double C, double D)\n{\n  if (A + B + C + D != 1.0)\n    {\n    vtkErrorMacro(\"R-MAT probabilities do not add up to 1.0.\");\n    return;\n    }\n\n  this->A = A;\n  this->B = B;\n  this->C = C;\n  this->D = D;\n}\n\n// ----------------------------------------------------------------------\nvoid \nvtkPBGLRMATGraphSource::GetProbabilities(double *A, double *B, double *C, double *D)\n{\n  if (A) \n    {\n    *A = this->A;\n    }\n  if (B) \n    {\n    *B = this->B;\n    }\n  if (C) \n    {\n    *C = this->C;\n    }\n  if (D) \n    {\n    *D = this->D;\n    }\n}\n\n\n// ----------------------------------------------------------------------\n\nint \nvtkPBGLRMATGraphSource::RequestData(\n  vtkInformation*, \n  vtkInformationVector**, \n  vtkInformationVector *outputVector)\n{\n  int myRank;\n  int numProcs;\n  MPI_Comm_rank(MPI_COMM_WORLD, &myRank);\n  MPI_Comm_size(MPI_COMM_WORLD, &numProcs);\n\n  // Seed the random number generator so we can produce repeatable results\n  vtkMath::RandomSeed(this->Seed);\n  \n  // Create a mutable, directed graph.\n  vtkSmartPointer<vtkMutableDirectedGraph> dirBuilder =\n    vtkSmartPointer<vtkMutableDirectedGraph>::New();\n    \n  // Create a Parallel BGL distributed graph helper\n  vtkSmartPointer<vtkPBGLDistributedGraphHelper> helper\n    = vtkSmartPointer<vtkPBGLDistributedGraphHelper>::New();\n\n  // Hook the distributed graph helper into the graph to make it a\n  // distributed graph.\n  dirBuilder->SetDistributedGraphHelper(helper);\n\n  // Vertex distribution.\n  vtkBlockDistribution distribution(this->NumberOfVertices, numProcs);\n\n  // Add NumberOfVertices new vertices.\n  vtkIdType myNumberOfVertices = distribution.GetBlockSize(myRank);\n  vtkIdType myStartVertex = distribution.GetFirstGlobalIndexOnProcessor(myRank);\n  vtkIdType myEndVertex = myStartVertex + myNumberOfVertices;\n  for (vtkIdType i = 0; i < myNumberOfVertices; ++i)\n    {\n    dirBuilder->AddVertex();\n    }\n\n  // Make sure everyone has added their own local vertices.\n  helper->Synchronize();\n\n  vtkIdType MaxEdges;\n  if (this->AllowSelfLoops)\n    {\n    MaxEdges = this->NumberOfVertices * this->NumberOfVertices;\n    }\n  else\n    {\n    MaxEdges = (this->NumberOfVertices * (this->NumberOfVertices-1)) / 2;\n    }\n  \n  if (this->NumberOfEdges > MaxEdges)\n    {\n    this->NumberOfEdges = MaxEdges;\n    }\n\n  vtkIdType avgNumberOfEdges = this->NumberOfEdges / numProcs;\n  vtkIdType myNumberOfEdges = avgNumberOfEdges;\n  if (myRank < this->NumberOfEdges % numProcs)\n    {\n    ++myNumberOfEdges;\n    }\n\n  vtkIdType numLevels = (vtkIdType) log2(this->NumberOfVertices) + 1;\n  double AB = this->A + this->B;\n  double CNorm = this->C / (this->C + this->D);\n  double ANorm = this->A / (this->A + this->B);\n  for (vtkIdType i = 0; i < myNumberOfEdges; i++)\n    {\n    bool newEdgeFound = false;\n    while (!newEdgeFound)\n      {\n      vtkIdType s = 0;\n      vtkIdType t = 0;\n\n      for (vtkIdType level = 1; level < numLevels; ++level) \n        {\n        bool sBit = vtkMath::Random() > (this->A + this->B);\n        bool tBit \n          = (vtkMath::Random() > (CNorm * (sBit ? 1 : 0)\n                                  + ANorm * (sBit ? 1 : 0))) ? 1 : 0;\n        s |= ((vtkIdType) 1 << (level-1)) * (sBit ? 1 : 0); \n        t |= ((vtkIdType) 1 << (level-1)) * (tBit ? 1 : 0);\n        }\n\n      if (s == t && (!this->AllowSelfLoops))\n        {\n        continue;\n        }\n\n      // TODO: We should apply some permutation to the s and t vertex\n      // numbers, so that we get some kind of randomized distribution\n      // of the vertices. Otherwise, we'll have a severely imbalanced\n      // distribution, since the high-degree vertices are likely to\n      // all end up on the lower-numbered ranks. Note that this\n      // doesn't change the block distribution (computed below); it\n      // sits on top of the block distribution.\n\n      vtkIdType sVertex \n        = helper->MakeDistributedId(distribution.GetProcessorOfElement(s),\n                                    distribution.GetLocalIndexOfElement(s));\n      vtkIdType tVertex \n        = helper->MakeDistributedId(distribution.GetProcessorOfElement(t),\n                                    distribution.GetLocalIndexOfElement(t));\n\n      vtkDebugMacro(<<\"Adding edge \" << s << \" to \" << t);\n      dirBuilder->LazyAddEdge(sVertex, tVertex);\n      newEdgeFound = true;\n      }\n    }\n\n  // Make sure everybody has added their edges and back-edges.\n  helper->Synchronize();\n\n  // Copy the structure into the output.\n  vtkGraph *output = vtkGraph::GetData(outputVector);\n  if (!output->CheckedShallowCopy(dirBuilder))\n    {\n    vtkErrorMacro(<<\"Invalid structure.\");\n    return 0;\n    }\n\n  if (this->IncludeEdgeWeights)\n    {\n    if (!this->EdgeWeightArrayName)\n      {\n      vtkErrorMacro(\"When generating edge weights, \"\n        << \"edge weights array name must be defined.\");\n      return 0;\n      }\n    vtkFloatArray *weights = vtkFloatArray::New();\n    weights->SetName(this->EdgeWeightArrayName);\n    for (vtkIdType i = 0; i < output->GetNumberOfEdges(); ++i)\n      {\n      weights->InsertNextValue(vtkMath::Random());\n      }\n    output->GetEdgeData()->AddArray(weights);\n    weights->Delete();\n    }\n\n  if (this->GeneratePedigreeIds)\n    {\n    if (!this->VertexPedigreeIdArrayName || !this->EdgePedigreeIdArrayName)\n      {\n      vtkErrorMacro(\"When generating pedigree ids, \"\n        << \"vertex and edge pedigree id array names must be defined.\");\n      return 0;\n      }\n    vtkIdType numVert = output->GetNumberOfVertices();\n    vtkSmartPointer<vtkIdTypeArray> vertIds =\n      vtkSmartPointer<vtkIdTypeArray>::New();\n    vertIds->SetName(this->VertexPedigreeIdArrayName);\n    vertIds->SetNumberOfTuples(numVert);\n    for (vtkIdType i = 0; i < numVert; ++i)\n      {\n      vertIds->SetValue(i, myStartVertex + i);\n      }\n    output->GetVertexData()->SetPedigreeIds(vertIds);\n\n    // Attach a distribution function to the helper that maps these\n    // global vertex numbers back to .  TODO: Actually do it :)\n\n    // Figure out how many edges come before us in the graph.\n    vtkIdType numEdge = output->GetNumberOfEdges();\n    boost::mpi::communicator world;\n    vtkIdType myStartEdge \n      = boost::mpi::scan(world, numEdge, std::plus<vtkIdType>()) - numEdge;\n\n    vtkSmartPointer<vtkIdTypeArray> edgeIds =\n      vtkSmartPointer<vtkIdTypeArray>::New();\n    edgeIds->SetName(this->EdgePedigreeIdArrayName);\n    edgeIds->SetNumberOfTuples(numEdge);\n    for (vtkIdType i = 0; i < numEdge; ++i)\n      {\n      edgeIds->SetValue(i, myStartEdge + i);\n      }\n    output->GetEdgeData()->SetPedigreeIds(edgeIds);\n    }\n\n  return 1;\n}\n\n//----------------------------------------------------------------------------\nint vtkPBGLRMATGraphSource::RequestDataObject(\n  vtkInformation*, \n  vtkInformationVector**, \n  vtkInformationVector* )\n{\n  vtkDataObject *current = this->GetExecutive()->GetOutputData(0);\n  if (!current || !vtkDirectedGraph::SafeDownCast(current))\n    {\n    vtkGraph *output = 0;\n    output = vtkDirectedGraph::New();\n\n    this->GetExecutive()->SetOutputData(0, output);\n    output->Delete();\n    }\n\n  return 1;\n}\n\n\n", "meta": {"hexsha": "a716a8575b0a5e2922e6eb51e1304e94a5c201db", "size": 11718, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Parallel/vtkPBGLRMATGraphSource.cxx", "max_stars_repo_name": "Lin1225/vtk_v5.10.0", "max_stars_repo_head_hexsha": "b54ac74f4716572862365fbff28cd0ecb8d08c3d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T08:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T08:50:23.000Z", "max_issues_repo_path": "Parallel/vtkPBGLRMATGraphSource.cxx", "max_issues_repo_name": "Lin1225/vtk_v5.10.0", "max_issues_repo_head_hexsha": "b54ac74f4716572862365fbff28cd0ecb8d08c3d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Parallel/vtkPBGLRMATGraphSource.cxx", "max_forks_repo_name": "Lin1225/vtk_v5.10.0", "max_forks_repo_head_hexsha": "b54ac74f4716572862365fbff28cd0ecb8d08c3d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T21:13:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T11:15:39.000Z", "avg_line_length": 31.3315508021, "max_line_length": 94, "alphanum_fraction": 0.6097456904, "num_tokens": 3037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438006939036565, "lm_q2_score": 0.028436031809810542, "lm_q1q2_score": 0.013773847061222675}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef __BOYER_MYRVOLD_PLANAR_TEST_HPP__\n#define __BOYER_MYRVOLD_PLANAR_TEST_HPP__\n\n#include <boost/graph/planar_detail/boyer_myrvold_impl.hpp>\n#include <boost/parameter.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/mpl/bool.hpp>\n\n\nnamespace boost\n{\n\n  struct no_kuratowski_subgraph_isolation {};\n  struct no_planar_embedding {};\n\n  namespace boyer_myrvold_params\n  {\n    \n    BOOST_PARAMETER_KEYWORD(tag, graph)\n    BOOST_PARAMETER_KEYWORD(tag, embedding)\n    BOOST_PARAMETER_KEYWORD(tag, kuratowski_subgraph)\n    BOOST_PARAMETER_KEYWORD(tag, vertex_index_map)\n    BOOST_PARAMETER_KEYWORD(tag, edge_index_map)\n    \n    typedef parameter::parameters< parameter::required<tag::graph>,\n                                   tag::embedding,\n                                   tag::kuratowski_subgraph,\n                                   tag::vertex_index_map,\n                                   tag::edge_index_map\n                                   > boyer_myrvold_params_t;\n    \n    namespace core\n    {\n        \n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::true_, \n                                    mpl::true_\n                                    )\n      {\n        //Dispatch for no planar embedding, no kuratowski subgraph isolation\n\n        typedef typename remove_const< \n            typename parameter::value_type<ArgumentPack, tag::graph>::type \n        >::type graph_t;\n\n        typedef typename property_map<\n            graph_t,\n            vertex_index_t\n        >::const_type vertex_default_index_map_t;\n\n        typedef typename parameter::value_type<\n            ArgumentPack, \n            tag::vertex_index_map,\n            vertex_default_index_map_t\n        >::type vertex_index_map_t;\n\n        graph_t const& g = args[graph];\n        vertex_default_index_map_t v_d_map = get(vertex_index, g);\n        vertex_index_map_t v_i_map = args[vertex_index_map | v_d_map];\n        boyer_myrvold_impl\n          <graph_t, \n           vertex_index_map_t,\n           graph::detail::no_old_handles,\n           graph::detail::no_embedding\n          >\n          planarity_tester(g, v_i_map);\n\n        return planarity_tester.is_planar() ? true : false;\n      }\n\n\n    \n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::true_, \n                                    mpl::false_\n                                    )\n      {\n        //Dispatch for no planar embedding, kuratowski subgraph isolation\n        typedef typename remove_const< \n            typename parameter::value_type<ArgumentPack, tag::graph>::type \n        >::type graph_t;\n\n        typedef typename property_map<\n            graph_t,\n            vertex_index_t\n        >::const_type vertex_default_index_map_t;\n\n        typedef typename parameter::value_type<\n            ArgumentPack, \n            tag::vertex_index_map,\n            vertex_default_index_map_t\n        >::type vertex_index_map_t;\n\n        typedef typename property_map<\n            graph_t,\n            edge_index_t\n        >::const_type edge_default_index_map_t;\n\n        typedef typename parameter::value_type<\n            ArgumentPack, \n            tag::edge_index_map,\n            edge_default_index_map_t\n        >::type edge_index_map_t;\n\n        graph_t const& g = args[graph];\n        vertex_default_index_map_t v_d_map = get(vertex_index, g);\n        vertex_index_map_t v_i_map = args[vertex_index_map | v_d_map];\n        edge_default_index_map_t e_d_map = get(edge_index, g);\n        edge_index_map_t e_i_map = args[edge_index_map | e_d_map];\n        boyer_myrvold_impl \n          <graph_t, \n           vertex_index_map_t,\n           graph::detail::store_old_handles,\n           graph::detail::no_embedding\n          >\n          planarity_tester(g, v_i_map);\n\n        if (planarity_tester.is_planar())\n          return true;\n        else\n          {\n            planarity_tester.extract_kuratowski_subgraph\n              (args[kuratowski_subgraph], e_i_map);          \n            return false;\n          }\n      }\n\n\n\n    \n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::false_, \n                                    mpl::true_\n                                    )\n      {\n        //Dispatch for planar embedding, no kuratowski subgraph isolation\n        typedef typename remove_const< \n            typename parameter::value_type<ArgumentPack, tag::graph>::type \n        >::type graph_t;\n\n        typedef typename property_map<\n            graph_t,\n            vertex_index_t\n        >::const_type vertex_default_index_map_t;\n\n        typedef typename parameter::value_type<\n            ArgumentPack, \n            tag::vertex_index_map,\n            vertex_default_index_map_t\n        >::type vertex_index_map_t;\n\n        graph_t const& g = args[graph];\n        vertex_default_index_map_t v_d_map = get(vertex_index, g);\n        vertex_index_map_t v_i_map = args[vertex_index_map | v_d_map];\n        boyer_myrvold_impl\n          <graph_t, \n           vertex_index_map_t,\n           graph::detail::no_old_handles,\n#ifdef BOOST_GRAPH_PREFER_STD_LIB\n           graph::detail::std_list\n#else\n           graph::detail::recursive_lazy_list\n#endif\n          >\n          planarity_tester(g, v_i_map);\n\n        if (planarity_tester.is_planar())\n          {\n            planarity_tester.make_edge_permutation(args[embedding]);\n            return true;\n          }\n        else\n          return false;\n      }\n    \n\n\n      template <typename ArgumentPack>\n      bool dispatched_boyer_myrvold(ArgumentPack const& args, \n                                    mpl::false_, \n                                    mpl::false_\n                                    )\n      {\n        //Dispatch for planar embedding, kuratowski subgraph isolation\n        typedef typename remove_const< \n            typename parameter::value_type<ArgumentPack, tag::graph>::type \n        >::type graph_t;\n\n        typedef typename property_map<\n            graph_t,\n            vertex_index_t\n        >::const_type vertex_default_index_map_t;\n\n        typedef typename parameter::value_type<\n            ArgumentPack, \n            tag::vertex_index_map,\n            vertex_default_index_map_t\n        >::type vertex_index_map_t;\n\n        typedef typename property_map<\n            graph_t,\n            edge_index_t\n        >::const_type edge_default_index_map_t;\n\n        typedef typename parameter::value_type<\n            ArgumentPack, \n            tag::edge_index_map,\n            edge_default_index_map_t\n        >::type edge_index_map_t;\n\n        graph_t const& g = args[graph];\n        vertex_default_index_map_t v_d_map = get(vertex_index, g);\n        vertex_index_map_t v_i_map = args[vertex_index_map | v_d_map];\n        edge_default_index_map_t e_d_map = get(edge_index, g);\n        edge_index_map_t e_i_map = args[edge_index_map | e_d_map];\n        boyer_myrvold_impl\n          <graph_t, \n          vertex_index_map_t,\n          graph::detail::store_old_handles,\n#ifdef BOOST_BGL_PREFER_STD_LIB\n           graph::detail::std_list\n#else\n           graph::detail::recursive_lazy_list\n#endif\n          >\n          planarity_tester(g, v_i_map);\n\n        if (planarity_tester.is_planar())\n          {\n            planarity_tester.make_edge_permutation(args[embedding]);\n            return true;\n          }\n        else\n          {\n            planarity_tester.extract_kuratowski_subgraph\n              (args[kuratowski_subgraph], e_i_map);          \n            return false;\n          } \n      }\n\n\n\n\n      template <typename ArgumentPack>\n      bool boyer_myrvold_planarity_test(ArgumentPack const& args)\n      {\n        \n        typedef typename parameter::binding \n          < ArgumentPack, \n            tag::kuratowski_subgraph,\n            const no_kuratowski_subgraph_isolation&\n          >::type \n          kuratowski_arg_t;\n       \n        typedef typename parameter::binding \n          < ArgumentPack, \n            tag::embedding,\n            const no_planar_embedding&\n          >::type \n          embedding_arg_t;\n      \n         return dispatched_boyer_myrvold\n           (args, \n            boost::is_same\n              <embedding_arg_t, const no_planar_embedding&>(),\n            boost::is_same\n              <kuratowski_arg_t, const no_kuratowski_subgraph_isolation&>() \n            );\n      }\n\n\n\n    } //namespace core\n    \n  } //namespace boyer_myrvold_params\n  \n    \n  template <typename A0>\n  bool boyer_myrvold_planarity_test(A0 const& arg0)\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0));\n  }\n  \n  template <typename A0, typename A1>\n  //  bool boyer_myrvold_planarity_test(A0 const& arg0, A1 const& arg1)\n  bool boyer_myrvold_planarity_test(A0 const& arg0, A1 const& arg1)\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0,arg1));\n  }\n  \n  template <typename A0, typename A1, typename A2>\n  bool boyer_myrvold_planarity_test(A0 const& arg0, \n                                    A1 const& arg1, \n                                    A2 const& arg2\n                                    )\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0,arg1,arg2));\n  }\n    \n  template <typename A0, typename A1, typename A2, typename A3>\n  bool boyer_myrvold_planarity_test(A0 const& arg0,\n                                    A1 const& arg1, \n                                    A2 const& arg2, \n                                    A3 const& arg3\n                                    )\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()(arg0,arg1,arg2,arg3));\n  }\n\n  template <typename A0, typename A1, typename A2, typename A3, typename A4>\n  bool boyer_myrvold_planarity_test(A0 const& arg0, \n                                    A1 const& arg1, \n                                    A2 const& arg2, \n                                    A3 const& arg3, \n                                    A4 const& arg4\n                                    )\n  {\n    return boyer_myrvold_params::core::boyer_myrvold_planarity_test\n      (boyer_myrvold_params::boyer_myrvold_params_t()\n       (arg0,arg1,arg2,arg3,arg4)\n       );\n  }\n    \n\n}\n\n#endif //__BOYER_MYRVOLD_PLANAR_TEST_HPP__\n", "meta": {"hexsha": "111c5ac4a3f786a5ff60effcadad354b61d0c09d", "size": 10931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/boyer_myrvold_planar_test.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 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/boyer_myrvold_planar_test.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 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/boyer_myrvold_planar_test.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 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.8688046647, "max_line_length": 76, "alphanum_fraction": 0.5753361998, "num_tokens": 2370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.032589743239179784, "lm_q1q2_score": 0.013769317565957813}}
{"text": "#ifndef MALABAR_LAYERS_HPP_\n#define MALABAR_LAYERS_HPP_\n\n/**\n *  @file\n *  @brief This header contains all malabar specific layers which have not\n *         yet merged back to upstream caffe.\n *\n *  Layers which are already available in caffe and have been changed\n *  or improved for the malabar project should be mentioned here as well.\n *\n *  Caffe Layer Improvements:\n *   TODO files and layers which have been improved should be listed here\n *\n */\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/random/mersenne_twister.hpp>\n\n#include \"caffe/layer.hpp\"\n#include \"caffe/layers/loss_layer.hpp\"\n#include \"caffe/layers/base_data_layer.hpp\"\n#include \"caffe/layers/concat_layer.hpp\"\n\n#include \"caffe/util/db.hpp\"\n\n#include \"caffe/proto/caffe.pb.h\"\n\n#include \"caffe/layers/neuron_layer.hpp\"\n#include \"caffe/layers/softmax_layer.hpp\"\n\n\nnamespace caffe {\n\n  /**\n   * Permutohedral Feature layer\n   *\n   */\n  template <typename Dtype>\n  class PixelFeatureLayer : public Layer<Dtype> {\n  public:\n    explicit PixelFeatureLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n    virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n                            const vector<Blob<Dtype>*>& top);\n    virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n                         const vector<Blob<Dtype>*>& top);\n\n    virtual inline const char* type() const { return \"PixelFeature\"; }\n    virtual inline int ExactNumBottomBlobs() const { return 1; }\n    virtual inline int ExactNumTopBlobs() const { return 1; }\n\n  protected:\n    virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n        const vector<Blob<Dtype>*>& top);\n    virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n        const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n    virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n        const vector<Blob<Dtype>*>& top);\n    virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n        const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n    // Permutohedral Feature parameters\n    int count_;\n    int num_;\n    int channels_;\n    int height_, width_;\n    bool ran_once;\n  };\n\n  /**\n   * Matrix multiplication layer.\n   *\n   */\n  template <typename Dtype>\n  class MatMulLayer : public Layer<Dtype> {\n  public:\n    explicit MatMulLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {\n      LayerParameter tmp_param;\n      tmp_param.mutable_concat_param()->set_concat_dim(3);\n      concat_layer_.reset(new ConcatLayer<Dtype>(tmp_param));\n    }\n    virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n                            const vector<Blob<Dtype>*>& top);\n    virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n                         const vector<Blob<Dtype>*>& top);\n\n    virtual inline const char* type() const { return \"MatMul\"; }\n    virtual inline int MinNumBottomBlobs() const { return 2; }\n    virtual inline int ExactNumTopBlobs() const { return 1; }\n\n  protected:\n    virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n                             const vector<Blob<Dtype>*>& top);\n    virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n                             const vector<Blob<Dtype>*>& top);\n    virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n                              const vector<bool>& propagate_down,\n                              const vector<Blob<Dtype>*>& bottom);\n    virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n                              const vector<bool>& propagate_down,\n                              const vector<Blob<Dtype>*>& bottom);\n    Blob<Dtype> tmp_k_;\n    boost::shared_ptr<ConcatLayer<Dtype> > concat_layer_;\n  };\n\n\n  /**\n   * Matrix multiplication layer - 2.\n   *\n   */\n  template <typename Dtype>\n  class MatMul2Layer : public Layer<Dtype> {\n  public:\n    explicit MatMul2Layer(const LayerParameter& param)\n      : Layer<Dtype>(param) {};\n    virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n                            const vector<Blob<Dtype>*>& top);\n    virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n                         const vector<Blob<Dtype>*>& top);\n\n    virtual inline const char* type() const { return \"MatMul2\"; }\n    virtual inline int ExactNumBottomBlobs() const { return 2; }\n    virtual inline int ExactNumTopBlobs() const { return 1; }\n\n  protected:\n    virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n                             const vector<Blob<Dtype>*>& top);\n    virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n                             const vector<Blob<Dtype>*>& top);\n    virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n                              const vector<bool>& propagate_down,\n                              const vector<Blob<Dtype>*>& bottom);\n    virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n                              const vector<bool>& propagate_down,\n                              const vector<Blob<Dtype>*>& bottom);\n    int M_;\n    int K_;\n    int N_;\n    int num_kernels_;\n    int channels_;\n    bool bias_term_;\n    Blob<Dtype> bias_multiplier_;\n  };\n\n\n/**\n * @brief Computes a product of two input Blobs, with the shape of the\n *        latter Blob \"broadcast\" to match the shape of the former.\n *        Equivalent to tiling the latter Blob, then computing the elementwise\n *        product.\n * Taken from - caffe ://github.com/jeffdonahue/caffe/commit/b4a5b6abb6272207da83bacde448fa3b2d4c7793?diff=split\n */\ntemplate <typename Dtype>\nclass ScalarLayer: public Layer<Dtype> {\n public:\n  explicit ScalarLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"Scalar\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 2; }\n  virtual inline int ExactNumTopBlobs() const { return 1; }\n\n protected:\n  /**\n   * In the below shape specifications, @f$ i @f$ denotes the value of the\n   * `axis` field given by `this->layer_param_.scalar_param().axis()`, after\n   * canonicalization (i.e., conversion from negative to positive index,\n   * if applicable).\n   *\n   * @param bottom input Blob vector (length 2)\n   *   -# @f$ (d_0 \\times ... \\times\n   *           d_i \\times ... \\times d_j \\times ... \\times d_n) @f$\n   *      the first factor @f$ x @f$\n   *   -# @f$ (d_i \\times ... \\times d_j) @f$\n   *      the second factor @f$ y @f$\n   * @param top output Blob vector (length 1)\n   *   -# @f$ (d_0 \\times ... \\times\n   *           d_i \\times ... \\times d_j \\times ... \\times d_n) @f$\n   *      the product @f$ z = x y @f$ computed after \"broadcasting\" y.\n   *      Equivalent to tiling @f$ y @f$ to have the same shape as @f$ x @f$,\n   *      then computing the elementwise product.\n   */\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  Blob<Dtype> sum_multiplier_;\n  Blob<Dtype> sum_result_;\n  int axis_;\n  int outer_dim_, scalar_dim_, inner_dim_;\n};\n\ntemplate <typename Dtype>\nclass Scalar2Layer: public Layer<Dtype> {\n public:\n  explicit Scalar2Layer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"Scalar2\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 2; }\n  virtual inline int ExactNumTopBlobs() const { return 1; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  Blob<Dtype> tmp_diff_;\n  Blob<Dtype> tmp_sum_;\n};\n\ntemplate <typename Dtype>\nclass Scalar3Layer: public Layer<Dtype> {\n public:\n  explicit Scalar3Layer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"Scalar3\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 2; }\n  virtual inline int ExactNumTopBlobs() const { return 1; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  Blob<Dtype> tmp_sum_;\n};\n\n/**\n * @brief Computes a product of input Blob and parameter blob, with the shape of the\n *        parameter Blob \"broadcast\" to match the shape of the former.\n *        Equivalent to tiling the parameter, then computing the elementwise\n *        product.\n * Adapted from - caffe ://github.com/jeffdonahue/caffe/commit/b4a5b6abb6272207da83bacde448fa3b2d4c7793?diff=split\n */\ntemplate <typename Dtype>\nclass ScalarConvLayer: public Layer<Dtype> {\n public:\n  explicit ScalarConvLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n          const vector<Blob<Dtype>*>& top);\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"ScalarConv\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 1; }\n  virtual inline int ExactNumTopBlobs() const { return 1; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  Blob<Dtype> sum_multiplier_;\n  Blob<Dtype> sum_result_;\n  int axis_;\n  int outer_dim_, scalar_dim_, inner_dim_;\n};\n\n\n/**\n * @brief Computes @f$ y = exp ^ {\\alpha x + \\beta} @f$,\n *        as specified by the parameter @f$ \\alpha @f$, shift @f$ \\beta @f$.\n */\ntemplate <typename Dtype>\nclass ExpScaleLayer : public NeuronLayer<Dtype> {\n public:\n  /**\n   * @param param provides ExpParameter exp_scale_param,\n   *     with ExpScaleLayer options:\n   *   - shift (\\b optional, default 0) the shift @f$ \\beta @f$\n   */\n  explicit ExpScaleLayer(const LayerParameter& param)\n      : NeuronLayer<Dtype>(param) {}\n  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"ExpScale\"; }\n\n protected:\n  /**\n   * @param bottom input Blob vector (length 1)\n   *   -# @f$ (N \\times C \\times H \\times W) @f$\n   *      the inputs @f$ x @f$\n   * @param top output Blob vector (length 1)\n   *   -# @f$ (N \\times C \\times H \\times W) @f$\n   *      the computed outputs @f$\n   *        y = e ^ {\\alpha x + \\beta}\n   *      @f$\n   */\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  /**\n   * @brief Computes the error gradient w.r.t. the exp inputs and\n   * scale parameter.\n   */\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  Dtype outer_scale_;\n};\n\n\n/**\n * @brief Computes @f$ y = \\alpha x  @f$,\n *        as specified by the learnable parameter @f$ \\alpha @f$.\n */\ntemplate <typename Dtype>\nclass Scale2Layer : public NeuronLayer<Dtype> {\n public:\n  explicit Scale2Layer(const LayerParameter& param)\n      : NeuronLayer<Dtype>(param) {}\n  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"Scale2\"; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  /**\n   * @brief Computes the error gradient w.r.t. the inputs and\n   * scale parameter.\n   */\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n};\n\n\ntemplate <typename Dtype>\nclass SmearLayer : public Layer<Dtype> {\n public:\n  explicit SmearLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top);\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"Smear\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 2; }\n  virtual inline int ExactNumTopBlobs() const { return 1; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  int num_;\n  int channels_;\n\n  int out_height_;\n  int out_width_;\n\n  int outer_num_;\n  int inner_num_;\n\n  Dtype ignore_idx_value_;\n  Dtype ignore_feature_value_;\n};\n\n\ntemplate <typename Dtype>\nclass PdistLayer : public Layer<Dtype> {\n public:\n  explicit PdistLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top);\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"Pdist\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 2; }\n  virtual inline int ExactNumTopBlobs() const { return 1; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  int num_;\n  int channels_;\n\n  int out_height_;\n  int out_width_;\n\n  float ignore_value_;\n  float scale_value_;\n};\n\n\ntemplate <typename Dtype>\nclass SpixelFeatureLayer : public Layer<Dtype> {\n public:\n  explicit SpixelFeatureLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top);\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"SpixelFeature\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 2; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  int num_;\n  int in_channels_;\n  int height_;\n  int width_;\n  int out_channels_;\n  int max_spixels_;\n\n  float rgbxy_rgb_scale_;\n  float rgbxy_xy_scale_;\n  float xy_scale_;\n  float rgb_scale_;\n  float ignore_idx_value_;\n  float ignore_feature_value_;\n\n  Blob<Dtype> spixel_counts_;\n};\n\n\ntemplate <typename Dtype>\nclass TransposeLayer: public Layer<Dtype> {\n public:\n  explicit TransposeLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {}\n  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n          const vector<Blob<Dtype>*>& top);\n  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n\n  virtual inline const char* type() const { return \"Transpose\"; }\n  virtual inline int ExactNumBottomBlobs() const { return 1; }\n  virtual inline int ExactNumTopBlobs() const { return 1; }\n\n protected:\n  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n  int num_, channels_, height_, width_;\n};\n\n  /**\n   * @brief Implements the Bilateral Convolution as brute-force but exact.\n   *        K*x with K=exp(-D)\n   *\n   * TODO(pgehler): thorough documentation for Forward, Backward, and proto params.\n   */\n  template <typename Dtype>\n  class BilateralBruteForceLayer : public Layer<Dtype> {\n   public:\n    explicit BilateralBruteForceLayer(const LayerParameter& param)\n      : Layer<Dtype>(param) {};\n    virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top);\n    virtual void Reshape(const vector<Blob<Dtype>*>& bottom,\n        const vector<Blob<Dtype>*>& top);\n\n    virtual inline const char* type() const { return \"BilateralBruteForce\"; }\n    virtual inline int ExactNumBottomBlobs() const { return 4; }\n    virtual inline int ExactNumTopBlobs() const { return 1; }\n\n   protected:\n    virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n        const vector<Blob<Dtype>*>& top);\n    virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,\n        const vector<Blob<Dtype>*>& top);\n    virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,\n        const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n    virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,\n        const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);\n\n    int num_;\n    int channels_;\n    int scales_;\n    int feature_size_;\n    int in_height_, in_width_;\n    int out_height_, out_width_;\n\n    // we need this since we have to accumulate gradients for several scalse\n    Blob<Dtype> bb_bottom_data_; // pixel\n    Blob<Dtype> bb_bottom_f1_;   // pixel\n    Blob<Dtype> bb_bottom_f2_;   // superpixel\n    Blob<Dtype> bb_bottom_s_;    // scales\n\n    Blob<Dtype> bb_top_pdist_;\n    Blob<Dtype> bb_top_scalar_;\n    Blob<Dtype> bb_top_softmax_;\n    Blob<Dtype> bb_top_matmul_;\n\n    // scalar needs only the top for the backward we can exploit that\n    // Blob<Dtype> bb_pdist_full_;\n    Blob<Dtype> bb_scalar_full_;\n    Blob<Dtype> bb_softmax_full_;\n\n    std::vector<Blob<Dtype>*> tmp_bottom_pdist_;\n    std::vector<Blob<Dtype>*> tmp_top_pdist_;\n    boost::shared_ptr<PdistLayer<Dtype> > pdist_layer_;\n    std::vector<Blob<Dtype>*> tmp_bottom_scalar_;\n    std::vector<Blob<Dtype>*> tmp_top_scalar_;\n    boost::shared_ptr<Scalar3Layer<Dtype> > scalar_layer_;\n    std::vector<Blob<Dtype>*> tmp_bottom_softmax_;\n    std::vector<Blob<Dtype>*> tmp_top_softmax_;\n    boost::shared_ptr<SoftmaxLayer<Dtype> > softmax_layer_;\n    std::vector<Blob<Dtype>*> tmp_bottom_matmul_;\n    std::vector<Blob<Dtype>*> tmp_top_matmul_;\n    boost::shared_ptr<MatMul2Layer<Dtype> > matmul_layer_;\n  };\n\n}  // namespace caffe\n\n#endif  // MALABAR_LAYERS_HPP_\n", "meta": {"hexsha": "6f1792ca1374ffff1d0b51107113913b284c4a25", "size": 21219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/caffe/include/caffe/malabar_layers.hpp", "max_stars_repo_name": "varunjampani/video_prop_networks", "max_stars_repo_head_hexsha": "4f4a39842bd9112932abe40bad746c174a242bf6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 99.0, "max_stars_repo_stars_event_min_datetime": "2017-04-19T21:08:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:41:15.000Z", "max_issues_repo_path": "lib/caffe/include/caffe/malabar_layers.hpp", "max_issues_repo_name": "varunjampani/video_prop_networks", "max_issues_repo_head_hexsha": "4f4a39842bd9112932abe40bad746c174a242bf6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-04-29T05:16:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T14:29:56.000Z", "max_forks_repo_path": "lib/caffe/include/caffe/malabar_layers.hpp", "max_forks_repo_name": "varunjampani/video_prop_networks", "max_forks_repo_head_hexsha": "4f4a39842bd9112932abe40bad746c174a242bf6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T00:45:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-19T04:03:34.000Z", "avg_line_length": 36.2717948718, "max_line_length": 114, "alphanum_fraction": 0.6752438852, "num_tokens": 5355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.029760096419973965, "lm_q1q2_score": 0.013719903803560382}}
{"text": "/*ckwg +29\n * Copyright 2014-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 * \\file\n * \\brief Implementation of Necker reversal functions\n */\n\n#include \"necker_reverse.h\"\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n\nnamespace kwiver {\nnamespace arrows {\nnamespace mvg {\n\n\n/// Compute a plane passing through the landmarks\nvital::vector_4d\nlandmark_plane(const vital::landmark_map::map_landmark_t& landmarks)\n{\n  using namespace kwiver::vital;\n  // compute the landmark location mean and covariance\n  vector_3d lc(0.0, 0.0, 0.0);\n  matrix_3x3d covar = matrix_3x3d::Zero();\n  for (auto const& p : landmarks)\n  {\n    vector_3d pt = p.second->loc();\n    lc += pt;\n    covar += pt * pt.transpose();\n  }\n  const double num_lm = static_cast<double>(landmarks.size());\n  lc /= num_lm;\n  covar /= num_lm;\n  covar -= lc * lc.transpose();\n\n  // the plane will pass through the landmark centeroid (lc)\n  // and have a normal vector aligned with the smallest eigenvector of covar\n  Eigen::JacobiSVD<matrix_3x3d> svd(covar, Eigen::ComputeFullV);\n  vector_3d axis = svd.matrixV().col(2);\n  return vector_4d(axis.x(), axis.y(), axis.z(), -(lc.dot(axis)));\n}\n\n\n/// Mirror landmarks about the specified plane\nvital::landmark_map_sptr\nmirror_landmarks(vital::landmark_map const& landmarks,\n                 vital::vector_4d const& plane)\n{\n  using namespace kwiver::vital;\n  landmark_map::map_landmark_t new_lms;\n  const vector_3d axis(plane.x(), plane.y(), plane.z());\n  const double d = plane[3];\n  // mirror landmark locations about the mirroring plane\n  for (auto const& p : landmarks.landmarks())\n  {\n    vector_3d v = p.second->loc();\n    v -= 2.0 * (v.dot(axis) + d) * axis;\n    auto new_lm = std::make_shared<vital::landmark_d>(*p.second);\n    new_lm->set_loc(v);\n    new_lms[p.first] = new_lm;\n  }\n  return std::make_shared<simple_landmark_map>(new_lms);\n}\n\n\n/// Compute the Necker reversal of a camera in place\nvoid\nnecker_reverse_inplace(vital::simple_camera_perspective& camera,\n                       vital::vector_4d const& plane)\n{\n  using namespace kwiver::vital;\n  const vector_3d axis(plane.x(), plane.y(), plane.z());\n  const double d = plane[3];\n  const rotation_d Ra180(vector_4d(axis.x(), axis.y(), axis.z(), 0.0));\n  static const rotation_d Rz180(vector_4d(0.0, 0.0, 1.0, 0.0));\n\n  // extract the camera center\n  const vital::vector_3d cc = camera.center();\n  // extract the camera principal axis\n  const vital::vector_3d pa = camera.rotation().matrix().row(2);\n  // compute the distance from cc along pa until intersection with\n  // the mirroring plane of the points\n  const double dist = -(cc.dot(axis) + d) / pa.dot(axis);\n  // compute the ground point where the principal axis\n  // intersects the mirroring plane\n  const vital::vector_3d gp = cc + dist * pa;\n  // rotate the camera center 180 degrees about the mirroring plane normal\n  // axis centered at gp, also rotate the camera 180 about its principal axis\n  camera.set_center(Ra180 * (cc - gp) + gp);\n  camera.set_rotation(Rz180 * camera.rotation() * Ra180);\n}\n\n\n/// Compute the Necker reversal of the cameras\nvital::camera_map_sptr\nnecker_reverse(vital::camera_map const& cameras,\n               vital::vector_4d const& plane)\n{\n  using namespace kwiver::vital;\n  camera_map::map_camera_t cams;\n  // flip cameras around\n  for (auto & p : cameras.cameras())\n  {\n    // make a clone of this camera as a simple_camera_perspective\n    auto flipped = std::make_shared<vital::simple_camera_perspective>(\n      dynamic_cast<vital::simple_camera_perspective&>(*p.second));\n\n    necker_reverse_inplace(*flipped, plane);\n    cams[p.first] = flipped;\n  }\n  return std::make_shared<simple_camera_map>(cams);\n}\n\n\n/// Compute an approximate Necker reversal of cameras and landmarks\nvoid\nnecker_reverse(vital::camera_map_sptr& cameras,\n               vital::landmark_map_sptr& landmarks,\n               bool reverse_landmarks)\n{\n  using namespace kwiver::vital;\n  const vector_4d plane = landmark_plane(landmarks->landmarks());\n\n  // reverse the cameras\n  cameras = necker_reverse(*cameras, plane);\n\n  if (reverse_landmarks)\n  {\n    // mirror the landmarks\n    landmarks = mirror_landmarks(*landmarks, plane);\n  }\n}\n\n\n} // end namespace mvg\n} // end namespace arrows\n} // end namespace kwiver\n", "meta": {"hexsha": "0f1a26b47d2ca70978091063f805ad8878740a65", "size": 5752, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "arrows/mvg/necker_reverse.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/necker_reverse.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/necker_reverse.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": 34.4431137725, "max_line_length": 81, "alphanum_fraction": 0.71418637, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.02976009190221719, "lm_q1q2_score": 0.0137199017207987}}
{"text": "#ifdef USE_OPENCV\n#include <opencv2/core/core.hpp>\n\n#include <fstream>  // NOLINT(readability/streams)\n#include <iostream>  // NOLINT(readability/streams)\n#include <string>\n#include <utility>\n#include <vector>\n#include <boost/algorithm/string.hpp>\n#include <boost/thread.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n#include \"caffe/layers/bb3txt_data_layer.hpp\"\n#include \"caffe/util/benchmark.hpp\"\n#include \"caffe/util/io.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\n// The maximum number of bounding boxes (annotations) in one image - we set the label blob shape according\n// to this number\n#define MAX_NUM_BBS_PER_IMAGE 20\n\n\nnamespace caffe {\n\nnamespace {\n\n\n    /**\n     * @brief Computes the number of bounding boxes in the annotation\n     * @param labels Annotation of one image (dimensions MAX_NUM_BBS_PER_IMAGE x 12 x 1 x 1)\n     * @param b Image id in the batch\n     * @return Number of bounding boxes in this label\n     */\n    template <typename Dtype>\n    int numBBs (const Blob<Dtype> &labels)\n    {\n        for (int i = 0; i < labels.shape(1); ++i)\n        {\n            // Data are stored like this [label, ...]\n            const Dtype *data = labels.cpu_data() + labels.offset(i);\n            // If the label is -1, there are no more bounding boxes\n            if (data[0] == Dtype(-1.0f)) return i;\n        }\n\n        return labels.shape(1);\n    }\n\n}\n\ntemplate <typename Dtype>\nBB3TXTDataLayer<Dtype>::BB3TXTDataLayer (const LayerParameter &param)\n    : BasePrefetchingDataLayer<Dtype>(param),\n      InternalThreadpool(std::min(int(std::max(int(boost::thread::hardware_concurrency()/2), 1)),\n                                  int(param.image_data_param().batch_size())))\n{\n}\n\n\ntemplate <typename Dtype>\nBB3TXTDataLayer<Dtype>::~BB3TXTDataLayer<Dtype> ()\n{\n    this->StopInternalThreadpool();\n    this->StopInternalThread();\n}\n\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::DataLayerSetUp (const vector<Blob<Dtype>*> &bottom,\n                                            const vector<Blob<Dtype>*> &top)\n{\n    CHECK(this->layer_param_.has_bbtxt_param()) << \"BBTXTParam is mandatory!\";\n    CHECK(this->layer_param_.bbtxt_param().has_height()) << \"Height must be set!\";\n    CHECK(this->layer_param_.bbtxt_param().has_width()) << \"Width must be set!\";\n    CHECK(this->layer_param_.bbtxt_param().has_reference_size_min()) << \"Min reference size must be set!\";\n    CHECK(this->layer_param_.bbtxt_param().has_reference_size_max()) << \"Max reference size must be set!\";\n    CHECK_LT(this->layer_param_.bbtxt_param().reference_size_min(),\n             this->layer_param_.bbtxt_param().reference_size_max()) << \"Min reference must be lower than max\";\n\n    const int height     = this->layer_param_.bbtxt_param().height();\n    const int width      = this->layer_param_.bbtxt_param().width();\n    const int batch_size = this->layer_param_.image_data_param().batch_size();\n\n    this->_rng.reset(new Caffe::RNG(caffe_rng_rand()));\n\n    // Load the BBTXT file with 2D bounding box annotations\n    this->_loadBB3TXTFile();\n    this->_i_global = 0;\n\n    CHECK(!this->_images.empty()) << \"The given BBTXT file is empty!\";\n    LOG(INFO) << \"There are \" << this->_images.size() << \" images in the dataset.\";\n\n\n    // This is the shape of the input blob\n    std::vector<int> top_shape = {batch_size, 3, height, width};\n    this->transformed_data_.Reshape(top_shape);  // For prefetching\n    top[0]->Reshape(top_shape);\n\n    // Label blob\n    std::vector<int> label_shape = {batch_size, MAX_NUM_BBS_PER_IMAGE, 12};\n    this->transformed_label_.Reshape(label_shape);  // For prefetching\n    top[1]->Reshape(label_shape);\n\n\n    // Initialize prefetching\n    // We also have to reshape the prefetching blobs to the correct batch size\n    for (int i = 0; i < this->prefetch_.size(); ++i)\n    {\n        this->prefetch_[i]->data_.Reshape(top_shape);\n        this->prefetch_[i]->label_.Reshape(label_shape);\n    }\n\n    this->StartInternalThreadpool();\n}\n\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::load_batch (Batch<Dtype> *batch)\n{\n    // This function is called on a prefetch thread\n\n    CHECK(batch->data_.count());\n    CHECK(this->transformed_data_.count());\n\n    const int batch_size = this->layer_param_.image_data_param().batch_size();\n\n    Dtype* prefetch_data  = batch->data_.mutable_cpu_data();\n    Dtype* prefetch_label = batch->label_.mutable_cpu_data();\n\n    this->transformed_data_.set_cpu_data(prefetch_data);\n    this->transformed_label_.set_cpu_data(prefetch_label);\n\n    this->_num_processed.reset();\n    for (int b = 0; b < batch_size; ++b) this->_b_queue.push(b);\n    this->_num_processed.waitToCount(batch_size);\n}\n\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::InternalThreadpoolEntry (int t)\n{\n    // This method runs on each thread of the internal threadpool\n\n    std::cout << \"============================= STARTING DATA THREAD \" << t << std::endl;\n\n    try {\n        while (!this->must_stopt(t))\n        {\n            int b = this->_b_queue.pop();\n\n            // Get index of image and bounding box we will crop\n            SelectedBB<Dtype> selbb = this->_getImageAndBB();\n\n            cv::Mat cv_img = cv::imread(selbb.filename, CV_LOAD_IMAGE_COLOR);\n            CHECK(cv_img.data) << \"Could not open \" << selbb.filename;\n\n            // Copy the annotation - we really have to copy it because it will be altered during image\n            // transformations like cropping or scaling\n            caffe_copy(selbb.label->count(), selbb.label->cpu_data(),\n                       this->transformed_label_.mutable_cpu_data() + this->transformed_label_.offset(b));\n\n            // We select a bounding box from the image and then make a crop such that the bounding box is\n            // inside of it and it has the reference size (Training - we select a random bounding box to crop\n            // from each image, Testing - crop all bounding boxes from the image - this way we ensure\n            // the test set is always the same)\n            this->_cropAndTransform(cv_img, b, selbb.bb_id);\n\n            // Raise the counter on processed images\n            this->_num_processed.increase();\n\n        }\n    } catch (boost::thread_interrupted&) {\n        // Interrupted exception is expected on shutdown\n    }\n\n    std::cout << \"============================= KILLING DATA THREAD \" << t << std::endl;\n}\n\n\n// -----------------------------------------  PROTECTED METHODS  ----------------------------------------- //\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::_loadBB3TXTFile ()\n{\n    const std::string& source = this->layer_param_.image_data_param().source();\n\n    std::ifstream infile(source.c_str(), std::ios::in);\n    CHECK(infile.is_open()) << \"BB3TXT file '\" << source << \"' could not be opened!\";\n\n    std::string line;\n    std::vector<std::string> data;\n    std::string current_filename = \"\";\n    int i = 0;\n\n    // Read the whole file and create entries in the _images for all images\n    while (std::getline(infile, line))\n    {\n        // Split the line - entries separated by space:\n        // [filename label confidence fblx fbly fbrx fbry rblx rbly ftly]\n        boost::split(data, line, boost::is_any_of(\" \"));\n        CHECK_EQ(data.size(), 14) << \"Line '\" << line << \"' corrupted!\";\n\n        if (current_filename != data[0])\n        {\n            // This is a label to a new image\n            if (this->_images.size() > 0 && i < MAX_NUM_BBS_PER_IMAGE)\n            {\n                // Finalize the last annotation - we put -1 as next bounding box label to signalize\n                // the end - this is because each image can have a different number of bounding boxes\n                int offset = this->_images.back().second->offset(i);\n                Dtype* bb3_position = this->_images.back().second->mutable_cpu_data() + offset;\n                bb3_position[0] = Dtype(-1.0f);\n            }\n\n            CHECK(boost::filesystem::exists(data[0])) << \"File '\" << data[0] << \"' not found!\";\n\n            // Create new image entry\n            this->_images.emplace_back(data[0], std::make_shared<Blob<Dtype>>(MAX_NUM_BBS_PER_IMAGE, 12, 1, 1));\n            i = 0;\n            current_filename = data[0];\n        }\n\n        // Write the bounding box info into the blob\n        if (i < MAX_NUM_BBS_PER_IMAGE)\n        {\n            int offset = this->_images.back().second->offset(i);\n            Dtype* bb3_position = this->_images.back().second->mutable_cpu_data() + offset;\n\n            bb3_position[0] = Dtype(std::stof(data[1])); // label\n            // xmin, ymin, xmax, ymax, fblx, fbly, fbrx, fbry, rblx, rbly, ftly\n            for (int p = 1; p < 12; ++p) bb3_position[p] = Dtype(std::stof(data[p+2]));\n\n            this->_indices.emplace_back(this->_images.size()-1, i);\n            i++;\n        }\n        else\n        {\n            LOG(WARNING) << \"Skipping bb - max number of bounding boxes per image reached.\";\n        }\n    }\n\n    // Close the last annotation\n    if (i < MAX_NUM_BBS_PER_IMAGE)\n    {\n        int offset = this->_images.back().second->offset(i);\n        Dtype* bb3_position = this->_images.back().second->mutable_cpu_data() + offset;\n        bb3_position[0] = Dtype(-1.0f);\n    }\n}\n\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::_shuffleBoundingBoxes ()\n{\n    caffe::rng_t* prefetch_rng = static_cast<caffe::rng_t*>(_rng->generator());\n    shuffle(this->_indices.begin(), this->_indices.end(), prefetch_rng);\n}\n\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::_cropAndTransform (const cv::Mat &cv_img, int b, int bb_id)\n{\n    CHECK_EQ(cv_img.channels(), 3) << \"Image must have 3 color channels\";\n\n    // Crop this bounding box from the image\n    cv::Mat cv_img_cropped;\n    this->_cropBBFromImage(cv_img, cv_img_cropped, b, bb_id);\n\n    // Mirror\n    // We cannot do it here because we do not have all the needed coordinates - we have to do it externaly\n\n    // Rotate\n\n    // Copy the cropped and transformed image to the input blob\n    this->_applyPixelTransformationsAndCopyOut(cv_img_cropped, b);\n}\n\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::_cropBBFromImage (const cv::Mat &cv_img, cv::Mat &cv_img_cropped_out,\n                                              int b, int bb_id)\n{\n    // Input dimensions of the network\n    const int height             = this->layer_param_.bbtxt_param().height();\n    const int width              = this->layer_param_.bbtxt_param().width();\n    const int reference_size_min = this->layer_param_.bbtxt_param().reference_size_min();\n    const int reference_size_max = this->layer_param_.bbtxt_param().reference_size_max();\n    caffe::rng_t* rng            = static_cast<caffe::rng_t*>(this->_rng->generator());\n\n\n    // Get dimensions of the bounding box - format [label, xmin, ymin, xmax, ymax]\n    const Dtype *bb_data = this->transformed_label_.cpu_data() + this->transformed_label_.offset(b, bb_id);\n    const Dtype x = bb_data[1];\n    const Dtype y = bb_data[2];\n    const Dtype w = bb_data[3] - bb_data[1];\n    const Dtype h = bb_data[4] - bb_data[2];\n\n    int reference_size;\n    if (this->phase_ == TRAIN)\n    {\n        // Choose the reference bounding box size within the given range\n\n        // IMPORTANT! We need larger values to be less probable than small - because an accumulator, which\n        // detects larger objects spans across more \"integer\" sizes. For example accumulator x2 can detect\n        // bbs in [25,60], then x4 detects bbs from [50,120], which has double the size of the interval. The\n        // random distribution needs to be augmented accordingly - we will project the bb sizes to log space\n        double rsl_min = std::log(double(reference_size_min));\n        double rsl_max = std::log(double(reference_size_max));\n\n        boost::random::uniform_real_distribution<double> dists(0.0, 1.0);\n        reference_size = std::round(std::exp(rsl_min + (dists(*rng) * (rsl_max-rsl_min))));\n    }\n    else\n    {\n        // Testing phase - keep the original size\n        reference_size = std::max(w, h);\n\n        if (reference_size < reference_size_min) reference_size = reference_size_min;\n        if (reference_size > reference_size_max) reference_size = reference_size_max;\n    }\n\n    const Dtype size      = std::max(w, h);\n    const int crop_width  = std::ceil(double(width) / reference_size * size);\n    const int crop_height = std::ceil(double(height) / reference_size * size);\n\n    // Select a random position of the crop, but it has to fully contain the bounding box\n    int crop_x, crop_y;\n    if (this->phase_ == TRAIN)\n    {\n        // In training we want to create a random crop around the bounding box\n        boost::random::uniform_int_distribution<> distx(x+w-crop_width, x);\n        boost::random::uniform_int_distribution<> disty(y+h-crop_height, y);\n        crop_x = distx(*rng);\n        crop_y = disty(*rng);\n    }\n    else\n    {\n        // In testing we want to always crop the same crop. Thus we will place the bounding box to the center\n        // of the crop\n        crop_x = x + w/2 - crop_width/2;\n        crop_y = y + h/2 - crop_height/2;\n    }\n\n    // Now if the crop spans outside the image we have to pad the image\n    int border_left   = (crop_x < 0) ? -crop_x : 0;\n    int border_top    = (crop_y < 0) ? -crop_y : 0;\n    int border_right  = (crop_x+crop_width  > cv_img.cols) ? (crop_x+crop_width  - cv_img.cols) : 0;\n    int border_bottom = (crop_y+crop_height > cv_img.rows) ? (crop_y+crop_height - cv_img.rows) : 0;\n\n\n    // -- CROP THE IMAGE -- //\n    // Because we want to save memory we will not use the copyMakeBorder function to create the border, but\n    // instead we will compute an intersection of the crop with the image, crop that intersection, scale it\n    // and then place it on black background to the position in which it would be cropped from\n\n    // Intersection of the crop with the image\n    int ints_width  = crop_width - border_left - border_right;\n    int ints_height = crop_height - border_top - border_bottom;\n    cv::Rect intersection(crop_x+border_left, crop_y+border_top, ints_width, ints_height);\n\n    // Scale the intersection according to the crip scaling ratio (do not round here because the crop could\n    // escape from the network input size - conversion to int will floor it)\n    int ints_width_scaled  = ints_width / size * reference_size;\n    int ints_height_scaled = ints_height / size * reference_size;\n    int border_left_scaled = border_left / size * reference_size;  // x coordinate of the crop\n    int border_top_scaled  = border_top / size * reference_size;   // y coordinate of the crop\n    // Corrections for imprecisions - we have to keep the crop inside of the network input image dimensions\n    if (ints_width_scaled > width) ints_width_scaled = width;\n    if (ints_height_scaled > height) ints_height_scaled = height;\n    if (border_left_scaled+ints_width_scaled > width) border_left_scaled = width - ints_width_scaled;\n    if (border_top_scaled+ints_height_scaled > height) border_top_scaled = height - ints_height_scaled;\n\n    CHECK_GT(ints_width_scaled, 0) << \"Crop does not intersect the image\";\n    CHECK_GT(ints_height_scaled, 0) << \"Crop does not intersect the image\";\n    CHECK_LE(ints_width_scaled, width) << \"Crop larger than width: \" << ints_width_scaled;\n    CHECK_LE(ints_height_scaled, height) << \"Crop larger than height: \" << ints_height_scaled;\n    CHECK_LE(border_left_scaled+ints_width_scaled, width) << \"Moved crop does not fit in the image\";\n    CHECK_LE(border_top_scaled+ints_height_scaled, height) << \"Moved crop does not fit in the image\";\n\n    // Crop and scale down the cropped intersection\n    cv::Mat cv_img_cropped_scaled;\n    cv::resize(cv_img(intersection), cv_img_cropped_scaled, cv::Size(ints_width_scaled, ints_height_scaled));\n\n    // Initialize the network input with black\n    cv_img_cropped_out = cv::Mat::zeros(height, width, CV_8UC3);\n\n    // Place the crop onto black canvas of the size of the network input image\n    cv::Mat cv_img_subcrop = cv_img_cropped_out(cv::Rect(border_left_scaled, border_top_scaled,\n                                                         ints_width_scaled, ints_height_scaled));\n    cv_img_cropped_scaled.copyTo(cv_img_subcrop);\n\n\n    // -- UPDATE THE COORDINATES OF THE BOUNDING BOXES -- //\n    // Update the bounding box coordinates - we need to update all annotations\n    Dtype x_scaling   = float(width) / crop_width;\n    Dtype y_scaling   = float(height) / crop_height;\n    for (int i = 0; i < MAX_NUM_BBS_PER_IMAGE; ++i)\n    {\n        // Data are stored like this [label, xmin, ymin, xmax, ymax, fblx, fbly, fbrx, fbry, rblx, rbly, ftly]\n        Dtype *data = this->transformed_label_.mutable_cpu_data() + this->transformed_label_.offset(b, i);\n\n        if (data[0] == Dtype(-1.0f)) break;\n\n        // Align with x, y of the crop and scale\n        data[1]  = (data[1]-crop_x) * x_scaling; // xmin\n        data[2]  = (data[2]-crop_y) * y_scaling; // ymin\n        data[3]  = (data[3]-crop_x) * x_scaling; // xmax\n        data[4]  = (data[4]-crop_y) * y_scaling; // ymax\n        data[5]  = (data[5]-crop_x) * x_scaling; // fblx\n        data[6]  = (data[6]-crop_y) * y_scaling; // fbly\n        data[7]  = (data[7]-crop_x) * x_scaling; // fbrx\n        data[8]  = (data[8]-crop_y) * y_scaling; // fbry\n        data[9]  = (data[9]-crop_x) * x_scaling; // rblx\n        data[10] = (data[10]-crop_y) * y_scaling; // rbly\n        data[11] = (data[11]-crop_y) * y_scaling; // ftly\n\n//        cv::rectangle(cv_img_cropped_out, cv::Rect(data[1], data[2], data[3]-data[1], data[4]-data[2]), cv::Scalar(0,0,255), 2);\n    }\n//    static int imi = 0;\n//    if(this->phase_ == TRAIN) cv::imwrite(\"cropped\" + std::to_string(imi++) + \".png\", cv_img_cropped_out);\n}\n\n\ntemplate <typename Dtype>\nvoid BB3TXTDataLayer<Dtype>::_applyPixelTransformationsAndCopyOut (const cv::Mat &cv_img_cropped, int b)\n{\n    const int width  = cv_img_cropped.cols;\n    const int height = cv_img_cropped.rows;\n\n    CHECK(cv_img_cropped.data) << \"Something went wrong with cropping!\";\n    CHECK_EQ(height, this->transformed_data_.shape(2)) << \"Wrong crop height! Does not match network!\";\n    CHECK_EQ(width,  this->transformed_data_.shape(3)) << \"Wrong crop width! Does not match network!\";\n\n\n    // Distortions of the image color space - during testing those will be 0\n    Dtype exposure         = Dtype(0.0f);\n    std::vector<Dtype> bgr = {Dtype(0.0f), Dtype(0.0f), Dtype(0.0f)};\n    cv::Mat noise          = cv::Mat::zeros(height, width, CV_32FC3);\n    if (this->phase_ == TRAIN)\n    {\n        // Apply random transformations\n        caffe::rng_t* rng = static_cast<caffe::rng_t*>(this->_rng->generator());\n\n        boost::random::uniform_int_distribution<> diste(-40, 50);  // Exposure\n        exposure = diste(*rng);\n\n        boost::random::uniform_int_distribution<> distbgr(-30, 30);  // Hue\n        bgr[0] = distbgr(*rng);\n        bgr[1] = distbgr(*rng);\n        bgr[2] = distbgr(*rng);\n\n        boost::random::uniform_int_distribution<> distn(0, 25);  // Noise standard deviation\n        cv::randn(noise, 0, distn(*rng));\n    }\n\n    // Normalize to 0 mean and unit variance and copy the image to the transformed_image\n    // + apply exposure, noise, hue, saturation, ...\n    Dtype* transformed_data = this->transformed_data_.mutable_cpu_data() + this->transformed_data_.offset(b);\n    for (int i = 0; i < height; ++i)\n    {\n        const uchar* ptr  = cv_img_cropped.ptr<uchar>(i);\n        const float* ptrn = noise.ptr<float>(i);\n        int img_index = 0;  // Index in the cv_img_cropped\n        for (int j = 0; j < width; ++j)\n        {\n            for (int c = 0; c < 3; ++c)\n            {\n                const int top_index = (c * height + i) * width + j;\n                // Apply exposure change, hue distortion, noise\n                const Dtype val = Dtype(ptr[img_index]) + exposure + bgr[c] + Dtype(ptrn[img_index]);\n                // Zero mean and unit variance\n                transformed_data[top_index] = (std::max(Dtype(0.0f), std::min(Dtype(255.0f), val))\n                        - Dtype(128.0f)) / Dtype(128.0f);\n                img_index++;\n            }\n        }\n    }\n\n//    std::vector<cv::Mat> chnls;\n//    chnls.push_back(cv::Mat(height, width, CV_32FC1, transformed_image.mutable_cpu_data()+transformed_image.offset(0,0)));\n//    chnls.push_back(cv::Mat(height, width, CV_32FC1, transformed_image.mutable_cpu_data()+transformed_image.offset(0,1)));\n//    chnls.push_back(cv::Mat(height, width, CV_32FC1, transformed_image.mutable_cpu_data()+transformed_image.offset(0,2)));\n//    cv::Mat img; cv::merge(chnls, img);\n//    img *= 128.0f;\n//    img += cv::Scalar(128.0f,128.0f,128.0f);\n//    cv::Mat img_u; img.convertTo(img_u, CV_8UC3);\n//    static int imi = 0;\n//    cv::imwrite(\"transfromed\" + std::to_string(imi++) + \".png\", img_u);\n}\n\n\ntemplate <typename Dtype>\nSelectedBB<Dtype> BB3TXTDataLayer<Dtype>::_getImageAndBB()\n{\n    std::lock_guard<std::mutex> lock(this->_i_global_mtx);\n\n    // Get image and bounding box index\n    auto indices = this->_indices[this->_i_global++];\n\n    if (this->_i_global >= this->_indices.size())\n    {\n        this->_i_global = 0;  // Restart\n        if (this->phase_ == TRAIN) this->_shuffleBoundingBoxes();\n    }\n\n    SelectedBB<Dtype> sel;\n    sel.filename = this->_images[indices.first].first;\n    sel.label    = this->_images[indices.first].second;\n    sel.bb_id    = indices.second;\n\n    return sel;\n}\n\n\n// ----------------------------------------  LAYER INSTANTIATION  ---------------------------------------- //\n\nINSTANTIATE_CLASS(BB3TXTDataLayer);\nREGISTER_LAYER_CLASS(BB3TXTData);\n\n\n}  // namespace caffe\n#endif  // USE_OPENCV\n", "meta": {"hexsha": "97441deb9f04fa08e3b16573deb49c9ceca52810", "size": 21768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "caffe/src/caffe/layers/bb3txt_data_layer.cpp", "max_stars_repo_name": "wuzzh/master_thesis_code", "max_stars_repo_head_hexsha": "6eca474ed3cae673afde010caef338cf7349f839", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 206.0, "max_stars_repo_stars_event_min_datetime": "2017-05-24T15:19:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T02:49:41.000Z", "max_issues_repo_path": "caffe/src/caffe/layers/bb3txt_data_layer.cpp", "max_issues_repo_name": "qiaohaijun/master_thesis_code", "max_issues_repo_head_hexsha": "6eca474ed3cae673afde010caef338cf7349f839", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2017-06-21T06:07:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-06T12:45:15.000Z", "max_forks_repo_path": "caffe/src/caffe/layers/bb3txt_data_layer.cpp", "max_forks_repo_name": "qiaohaijun/master_thesis_code", "max_forks_repo_head_hexsha": "6eca474ed3cae673afde010caef338cf7349f839", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2017-06-27T09:00:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T05:05:44.000Z", "avg_line_length": 41.3840304183, "max_line_length": 130, "alphanum_fraction": 0.6410327086, "num_tokens": 5630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.04272219861296326, "lm_q1q2_score": 0.013706191333098095}}
{"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\n// r_c_shortest_paths_label struct\ntemplate < class Graph, class Resource_Container >\nstruct r_c_shortest_paths_label\n: public boost::enable_shared_from_this<\n      r_c_shortest_paths_label< Graph, Resource_Container > >\n{\n    r_c_shortest_paths_label(const unsigned long n,\n        const Resource_Container& rc = Resource_Container(),\n        const boost::shared_ptr<\n            r_c_shortest_paths_label< Graph, Resource_Container > >\n            pl\n        = boost::shared_ptr<\n            r_c_shortest_paths_label< Graph, Resource_Container > >(),\n        const typename graph_traits< Graph >::edge_descriptor& ed\n        = graph_traits< Graph >::edge_descriptor(),\n        const typename graph_traits< Graph >::vertex_descriptor& vd\n        = 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\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<\n        r_c_shortest_paths_label< Graph, Resource_Container > >\n        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 l1.cumulated_resource_consumption\n        == 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 !(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 l1.cumulated_resource_consumption\n        < 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 l2.cumulated_resource_consumption\n        < 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 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<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& t,\n    const boost::shared_ptr<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& u)\n{\n    return *t < *u;\n}\n\ntemplate < typename Graph, typename Resource_Container >\ninline bool operator<=(\n    const boost::shared_ptr<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& t,\n    const boost::shared_ptr<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& u)\n{\n    return *t <= *u;\n}\n\ntemplate < typename Graph, typename Resource_Container >\ninline bool operator>(\n    const boost::shared_ptr<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& t,\n    const boost::shared_ptr<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& u)\n{\n    return *t > *u;\n}\n\ntemplate < typename Graph, typename Resource_Container >\ninline bool operator>=(\n    const boost::shared_ptr<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& t,\n    const boost::shared_ptr<\n        r_c_shortest_paths_label< Graph, Resource_Container > >& u)\n{\n    return *t >= *u;\n}\n\nnamespace detail\n{\n\n    // r_c_shortest_paths_dispatch function (body/implementation)\n    template < class Graph, class VertexIndexMap, class EdgeIndexMap,\n        class Resource_Container, class Resource_Extension_Function,\n        class Dominance_Function, class Label_Allocator, class Visitor >\n    void r_c_shortest_paths_dispatch(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< typename graph_traits< Graph >::edge_descriptor > >&\n            pareto_optimal_solutions,\n        std::vector< 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, Resource_Extension_Function& ref,\n        Dominance_Function& dominance,\n        // to specify the memory management strategy for the labels\n        Label_Allocator /*la*/, 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 typename Label_Allocator::template rebind<\n            r_c_shortest_paths_label< Graph, Resource_Container > >::other\n            LAlloc;\n#else\n        typedef typename std::allocator_traits< Label_Allocator >::\n            template rebind_alloc<\n                r_c_shortest_paths_label< Graph, Resource_Container > >\n                LAlloc;\n        typedef std::allocator_traits< LAlloc > LTraits;\n#endif\n        LAlloc l_alloc;\n        typedef boost::shared_ptr<\n            r_c_shortest_paths_label< Graph, Resource_Container > >\n            Splabel;\n        std::priority_queue< Splabel, std::vector< Splabel >,\n            std::greater< Splabel > >\n            unprocessed_labels;\n\n        bool b_feasible = true;\n        Splabel splabel_first_label = boost::allocate_shared<\n            r_c_shortest_paths_label< Graph, Resource_Container > >(l_alloc,\n            i_label_num++, rc,\n            boost::shared_ptr<\n                r_c_shortest_paths_label< Graph, Resource_Container > >(),\n            typename graph_traits< Graph >::edge_descriptor(), s);\n\n        unprocessed_labels.push(splabel_first_label);\n        std::vector< std::list< Splabel > > vec_vertex_labels_data(\n            num_vertices(g));\n        iterator_property_map<\n            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 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        {\n            put(vec_last_valid_positions_for_dominance, v,\n                vec_vertex_labels[v].begin());\n        }\n        std::vector< size_t > vec_last_valid_index_for_dominance_data(\n            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(),\n                vertex_index_map);\n        std::vector< bool > b_vec_vertex_already_checked_for_dominance_data(\n            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()\n            && 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\n            // Splabel object in the respective list<Splabel> of\n            // vec_vertex_labels share their embedded r_c_shortest_paths_label\n            // object to avoid memory leaks, dominated r_c_shortest_paths_label\n            // objects are marked and deleted when popped from\n            // unprocessed_labels, as they can no longer be deleted at the end\n            // of the function; only the Splabel object in unprocessed_labels\n            // still references the r_c_shortest_paths_label object this is also\n            // for efficiency, because the else branch is executed only if there\n            // is a chance that extending the label leads to new undominated\n            // labels, which in turn is possible only if the label to be\n            // extended is undominated\n            if (!cur_label->b_is_dominated)\n            {\n                typename boost::graph_traits< Graph >::vertex_descriptor\n                    i_cur_resident_vertex\n                    = 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\n                        = 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\n                            = 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\n                                = true;\n                        if (!get(b_vec_vertex_already_checked_for_dominance,\n                                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\n                                    = 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\n                                    = 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,\n                            i_cur_resident_vertex,\n                            (--(list_labels_cur_vertex.end())));\n                    else\n                        put(vec_last_valid_positions_for_dominance,\n                            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,\n                        i_cur_resident_vertex,\n                        list_labels_cur_vertex.size() - 1);\n                }\n            }\n            if (!b_all_pareto_optimal_solutions\n                && 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\n                    // are 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; ++oei)\n                {\n                    b_feasible = true;\n                    Splabel new_label = boost::allocate_shared<\n                        r_c_shortest_paths_label< Graph, Resource_Container > >(\n                        l_alloc, i_label_num++,\n                        cur_label->cumulated_resource_consumption, cur_label,\n                        *oei, target(*oei, g));\n                    b_feasible = 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].push_back(\n                            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<\n                    r_c_shortest_paths_label< Graph, Resource_Container > >\n                    p_cur_label = *csi;\n                pareto_optimal_resource_containers.push_back(\n                    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\n                    // the domination function requires resource levels to be\n                    // 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\n                    // 2-3-4, though the path 3-2-4-5 does not strictly dominate\n                    // 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        {\n            std::list< Splabel >& list_labels_cur_vertex = vec_vertex_labels[i];\n            typename std::list< Splabel >::iterator si\n                = list_labels_cur_vertex.begin();\n            const typename std::list< Splabel >::iterator si_end\n                = 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    {\n    }\n    template < class Label, class Graph >\n    void on_label_feasible(const Label&, const Graph&)\n    {\n    }\n    template < class Label, class Graph >\n    void on_label_not_feasible(const Label&, const Graph&)\n    {\n    }\n    template < class Label, class Graph >\n    void on_label_dominated(const Label&, const Graph&)\n    {\n    }\n    template < class Label, class Graph >\n    void on_label_not_dominated(const Label&, const Graph&)\n    {\n    }\n    template < class Queue, class Graph >\n    bool on_enter_loop(const Queue& queue, const Graph& graph)\n    {\n        return true;\n    }\n}; // default_r_c_shortest_paths_visitor\n\n// default_r_c_shortest_paths_allocator\ntypedef std::allocator< int > default_r_c_shortest_paths_allocator;\n// default_r_c_shortest_paths_allocator\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, class VertexIndexMap, class EdgeIndexMap,\n    class Resource_Container, class Resource_Extension_Function,\n    class Dominance_Function, class Label_Allocator, class Visitor >\nvoid r_c_shortest_paths(const Graph& g, 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< 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, const Resource_Extension_Function& ref,\n    const Dominance_Function& dominance,\n    // to specify the memory management strategy for the labels\n    Label_Allocator la, Visitor vis)\n{\n    r_c_shortest_paths_dispatch(g, vertex_index_map, edge_index_map, s, t,\n        pareto_optimal_solutions, pareto_optimal_resource_containers, true, rc,\n        ref, dominance, la, vis);\n}\n\n// second overload:\n// - return only one pareto-optimal solution\n// - specify Label_Allocator and Visitor arguments\ntemplate < class Graph, class VertexIndexMap, class EdgeIndexMap,\n    class Resource_Container, class Resource_Extension_Function,\n    class Dominance_Function, class Label_Allocator, class Visitor >\nvoid r_c_shortest_paths(const Graph& g, 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, const Resource_Extension_Function& ref,\n    const Dominance_Function& dominance,\n    // to specify the memory management strategy for the labels\n    Label_Allocator la, Visitor vis)\n{\n    // each inner vector corresponds to a pareto-optimal path\n    std::vector<\n        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, vertex_index_map, edge_index_map, s, t,\n        pareto_optimal_solutions, pareto_optimal_resource_containers, false, rc,\n        ref, dominance, la, vis);\n    if (!pareto_optimal_solutions.empty())\n    {\n        pareto_optimal_solution = pareto_optimal_solutions[0];\n        pareto_optimal_resource_container\n            = 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, class VertexIndexMap, class EdgeIndexMap,\n    class Resource_Container, class Resource_Extension_Function,\n    class Dominance_Function >\nvoid r_c_shortest_paths(const Graph& g, 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< 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, const Resource_Extension_Function& ref,\n    const Dominance_Function& dominance)\n{\n    r_c_shortest_paths_dispatch(g, vertex_index_map, edge_index_map, s, t,\n        pareto_optimal_solutions, pareto_optimal_resource_containers, true, rc,\n        ref, dominance, 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, class VertexIndexMap, class EdgeIndexMap,\n    class Resource_Container, class Resource_Extension_Function,\n    class Dominance_Function >\nvoid r_c_shortest_paths(const Graph& g, 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, const Resource_Extension_Function& ref,\n    const Dominance_Function& dominance)\n{\n    // each inner vector corresponds to a pareto-optimal path\n    std::vector<\n        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, vertex_index_map, edge_index_map, s, t,\n        pareto_optimal_solutions, pareto_optimal_resource_containers, false, rc,\n        ref, dominance, default_r_c_shortest_paths_allocator(),\n        default_r_c_shortest_paths_visitor());\n    if (!pareto_optimal_solutions.empty())\n    {\n        pareto_optimal_solution = pareto_optimal_solutions[0];\n        pareto_optimal_resource_container\n            = pareto_optimal_resource_containers[0];\n    }\n}\n// r_c_shortest_paths\n\n// check_r_c_path function\ntemplate < class Graph, class Resource_Container,\n    class Resource_Extension_Function >\nvoid check_r_c_path(const Graph& g,\n    const std::vector< typename graph_traits< Graph >::edge_descriptor >&\n        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, bool& b_is_a_path_at_all,\n    bool& b_feasible, bool& b_correctly_extended,\n    typename graph_traits< Graph >::edge_descriptor& 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, actual_final_resource_levels,\n            current_resource_levels, 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\n            : 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": "03aa09063e5afc8ad0fa7449c22509e5f2780284", "size": 30673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/r_c_shortest_paths.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/r_c_shortest_paths.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/r_c_shortest_paths.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": 42.3660220994, "max_line_length": 86, "alphanum_fraction": 0.6141883741, "num_tokens": 6350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.03021458761318004, "lm_q1q2_score": 0.01369511981857278}}
{"text": "/* Copyright (c) 2016 - 2020, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#include <MaterialProperty.hh>\n#include <instantiation.hh>\n\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/optional.hpp>\n\nnamespace adamantine\n{\n\ntemplate <int dim>\nMaterialProperty<dim>::MaterialProperty(\n    MPI_Comm const &communicator,\n    dealii::parallel::distributed::Triangulation<dim> const &tria,\n    boost::property_tree::ptree const &database)\n    : _communicator(communicator), _fe(0), _mp_dof_handler(tria)\n{\n  // Because deal.II cannot easily attach data to a cell. We store the state\n  // of the material in distributed::Vector. This allows to use deal.II to\n  // compute the new state after refinement of the mesh. However, this\n  // requires to use another DoFHandler.\n  reinit_dofs();\n\n  // Set the material state to the state defined in the geometry.\n  set_state();\n\n  // Fill the _properties map\n  fill_properties(database);\n}\n\ntemplate <int dim>\ndouble MaterialProperty<dim>::get(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n    StateProperty prop) const\n{\n  unsigned int property = static_cast<unsigned int>(prop);\n  double const mp_dof_index = get_dof_index(cell);\n\n  return _property_values[property][mp_dof_index];\n}\n\ntemplate <int dim>\ndouble MaterialProperty<dim>::get(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n    Property prop) const\n{\n  dealii::types::material_id material_id = cell->material_id();\n  unsigned int property = static_cast<unsigned int>(prop);\n\n  return _properties.find(material_id)->second[property];\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::reinit_dofs()\n{\n  _mp_dof_handler.distribute_dofs(_fe);\n  // Initialize the state vectors\n  for (auto &vec : _state)\n    vec.reinit(_mp_dof_handler.locally_owned_dofs(), _communicator);\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::update(\n    dealii::DoFHandler<dim> const &temperature_dof_handler,\n    dealii::LA::distributed::Vector<double> const &temperature)\n{\n  auto temperature_average =\n      compute_average_temperature(temperature_dof_handler, temperature);\n  for (auto &val : _property_values)\n    val.reinit(temperature_average.get_partitioner());\n\n  std::vector<dealii::types::global_dof_index> mp_dof(1);\n  for (auto cell :\n       dealii::filter_iterators(_mp_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    dealii::types::material_id material_id = cell->material_id();\n    auto const tmp = _properties.find(material_id);\n    ASSERT(tmp != _properties.end(), \"Material not found.\");\n\n    unsigned int constexpr liquid =\n        static_cast<unsigned int>(MaterialState::liquid);\n    unsigned int constexpr powder =\n        static_cast<unsigned int>(MaterialState::powder);\n    unsigned int constexpr solid =\n        static_cast<unsigned int>(MaterialState::solid);\n    unsigned int constexpr prop_solidus =\n        static_cast<unsigned int>(Property::solidus);\n    unsigned int constexpr prop_liquidus =\n        static_cast<unsigned int>(Property::liquidus);\n\n    double const solidus = tmp->second[prop_solidus];\n    double const liquidus = tmp->second[prop_liquidus];\n    cell->get_dof_indices(mp_dof);\n    unsigned int const dof = mp_dof[0];\n\n    // First determine the ratio of liquid.\n    double liquid_ratio = -1.;\n    double powder_ratio = -1.;\n    double solid_ratio = -1.;\n    if (temperature_average[dof] < solidus)\n      liquid_ratio = 0.;\n    else if (temperature_average[dof] > liquidus)\n      liquid_ratio = 1.;\n    else\n      liquid_ratio =\n          (temperature_average[dof] - solidus) / (liquidus - solidus);\n    // Because the powder can only become liquid, the solid can only become\n    // liquid, and the liquid can only become solid, the ratio of powder can\n    // only decrease.\n    powder_ratio = std::min(1. - liquid_ratio, _state[powder][dof]);\n    // Use max to make sure that we don't create matter because of round-off.\n    solid_ratio = std::max(1 - liquid_ratio - powder_ratio, 0.);\n\n    // Update the value\n    _state[liquid][dof] = liquid_ratio;\n    _state[powder][dof] = powder_ratio;\n    _state[solid][dof] = solid_ratio;\n\n    if (_use_table)\n    {\n      for (unsigned int property = 0; property < _n_state_properties;\n           ++property)\n      {\n        for (unsigned int material_state = 0;\n             material_state < _n_material_states; ++material_state)\n        {\n          _property_values[property][dof] +=\n              _state[material_state][dof] *\n              compute_property_from_table(\n                  _state_property_tables[material_id][material_state][property],\n                  temperature_average[dof]);\n        }\n      }\n    }\n    else\n    {\n      for (unsigned int property = 0; property < _n_state_properties;\n           ++property)\n      {\n        for (unsigned int material_state = 0;\n             material_state < _n_material_states; ++material_state)\n        {\n          _property_values[property][dof] +=\n              _state[material_state][dof] *\n              compute_property_from_polynomial(\n                  _state_property_polynomials[material_id][material_state]\n                                             [property],\n                  temperature_average[dof]);\n        }\n      }\n    }\n\n    // If we are in the mushy state, i.e., part liquid part solid, we need to\n    // modify the rho C_p to take into account the latent heat.\n    if ((liquid_ratio > 0.) && (liquid_ratio < 1.))\n    {\n      unsigned int specific_heat_prop =\n          static_cast<unsigned int>(StateProperty::specific_heat);\n      unsigned int latent_heat_prop =\n          static_cast<unsigned int>(Property::latent_heat);\n      for (unsigned int material_state = 0; material_state < _n_material_states;\n           ++material_state)\n      {\n        _property_values[specific_heat_prop][dof] +=\n            _state[material_state][dof] *\n            _properties[material_id][latent_heat_prop] / (liquidus - solidus);\n      }\n    }\n  }\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::set_state()\n{\n  // Set the material state to the one defined by the user_index\n  std::vector<dealii::types::global_dof_index> mp_dof(1);\n  for (auto cell :\n       dealii::filter_iterators(_mp_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    cell->get_dof_indices(mp_dof);\n    _state[cell->user_index()][mp_dof[0]] = 1.;\n  }\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::fill_properties(\n    boost::property_tree::ptree const &database)\n{\n  std::array<std::string, _n_material_states> material_state = {\n      {\"powder\", \"solid\", \"liquid\"}};\n  std::array<std::string, _n_properties> properties = {\n      {\"liquidus\", \"solidus\", \"latent_heat\"}};\n  std::array<std::string, _n_state_properties> state_properties = {\n      {\"density\", \"specific_heat\", \"thermal_conductivity\"}};\n\n  std::string property_format = database.get<std::string>(\"property_format\");\n  ASSERT_THROW((property_format == \"table\") ||\n                   (property_format == \"polynomial\"),\n               \"property_format should be table or polynomial.\");\n  _use_table = (property_format == \"table\");\n  unsigned int const n_materials = database.get<unsigned int>(\"n_materials\");\n  dealii::types::material_id next_material_id = 0;\n  for (unsigned int i = 0; i < n_materials; ++i)\n  {\n    // Try to find the material_id by checking every possible number.\n    dealii::types::material_id material_id = next_material_id;\n    while (material_id < dealii::numbers::invalid_material_id)\n    {\n      // If the child exists, exit the loop.\n      if (database.count(\"material_\" + std::to_string(material_id)) != 0)\n        break;\n\n      ++material_id;\n    }\n    ASSERT_THROW(material_id != dealii::numbers::invalid_material_id,\n                 \"Invalid material ID. Choose a smaller number.\");\n    // Update the next possible material id\n    ++next_material_id;\n\n    // Get the material property tree.\n    boost::property_tree::ptree const &material_database =\n        database.get_child(\"material_\" + std::to_string(material_id));\n    // For each material, loop over the possible states.\n    bool valid_state = false;\n    for (unsigned int state = 0; state < _n_material_states; ++state)\n    {\n      // The state may or may not exist for the material.\n      boost::optional<boost::property_tree::ptree const &> state_database =\n          material_database.get_child_optional(material_state[state]);\n      if (state_database)\n      {\n        valid_state = true;\n        // For each state, loop over the possible properties.\n        for (unsigned int p = 0; p < _n_state_properties; ++p)\n        {\n          // The property may or may not exist for that state\n          boost::optional<std::string> const property =\n              state_database.get().get_optional<std::string>(\n                  state_properties[p]);\n          // If the property exists, put it in the map. If the property does not\n          // exist, we have a nullptr.\n          if (property)\n          {\n            // Remove blank spaces\n            std::string property_string = property.get();\n            property_string.erase(\n                std::remove_if(property_string.begin(), property_string.end(),\n                               [](unsigned char x) { return std::isspace(x); }),\n                property_string.end());\n            if (_use_table)\n            {\n              std::vector<std::string> parsed_property;\n              boost::split(parsed_property, property_string,\n                           [](char c) { return c == ';'; });\n              for (auto const &p_property : parsed_property)\n              {\n                std::vector<std::string> t_v;\n                boost::split(t_v, p_property, [](char c) { return c == ','; });\n                ASSERT(t_v.size() == 2, \"Error reading material property.\");\n                _state_property_tables[material_id][state][p].emplace_back(\n                    std::stod(t_v[0]), std::stod(t_v[1]));\n              }\n            }\n            else\n            {\n              std::vector<std::string> parsed_property;\n              boost::split(parsed_property, property_string,\n                           [](char c) { return c == ','; });\n              for (auto const &p_property : parsed_property)\n              {\n                _state_property_polynomials[material_id][state][p].emplace_back(\n                    std::stod(p_property));\n              }\n            }\n          }\n        }\n      }\n    }\n    // Check that there is at least one valid MaterialState\n    ASSERT_THROW(\n        valid_state == true,\n        \"Material without any valid state (solid, powder, or liquid).\");\n\n    // Check for the properties that are associated to a material but that\n    // are independent of an individual state. These properties are duplicated\n    // for every state.\n    for (unsigned int p = 0; p < _n_properties; ++p)\n    {\n      // The property may or may not exist for that state\n      boost::optional<double> const property =\n          material_database.get_optional<double>(properties[p]);\n      // If the property exists, put it in the map. If the property does not\n      // exist, we use the largest. This is useful if the liquidus and the\n      // solidus are not set.\n      _properties[material_id][p] =\n          property ? property.get() : std::numeric_limits<double>::max();\n    }\n  }\n}\n\n// We need to compute the average temperature on the cell because we need the\n// material properties to be uniform over the cell. If there aren't then we have\n// problems with the weak form discretization.\ntemplate <int dim>\ndealii::LA::distributed::Vector<double>\nMaterialProperty<dim>::compute_average_temperature(\n    dealii::DoFHandler<dim> const &temperature_dof_handler,\n    dealii::LA::distributed::Vector<double> const &temperature) const\n{\n  // TODO: this should probably done in a matrix-free fashion.\n  // The triangulation is the same for both DoFHandler\n  dealii::LA::distributed::Vector<double> temperature_average(\n      _mp_dof_handler.locally_owned_dofs(), temperature.get_mpi_communicator());\n  temperature_average = 0.;\n  auto mp_cell = _mp_dof_handler.begin_active();\n  auto mp_end_cell = _mp_dof_handler.end();\n  auto enth_cell = temperature_dof_handler.begin_active();\n  dealii::FiniteElement<dim> const &fe = temperature_dof_handler.get_fe();\n  // We can use a lower degree of quadrature since we are projecting on a\n  // piecewise constant space\n  dealii::QGauss<dim> quadrature(fe.degree);\n  dealii::FEValues<dim> fe_values(\n      fe, quadrature,\n      dealii::UpdateFlags::update_values |\n          dealii::UpdateFlags::update_quadrature_points |\n          dealii::UpdateFlags::update_JxW_values);\n  unsigned int const dofs_per_cell = fe.dofs_per_cell;\n  std::vector<dealii::types::global_dof_index> mp_dof_indices(1);\n  std::vector<dealii::types::global_dof_index> enth_dof_indices(dofs_per_cell);\n  unsigned int const n_q_points = quadrature.size();\n  for (; mp_cell != mp_end_cell; ++enth_cell, ++mp_cell)\n    if (mp_cell->is_locally_owned())\n    {\n      fe_values.reinit(enth_cell);\n      mp_cell->get_dof_indices(mp_dof_indices);\n      dealii::types::global_dof_index const mp_dof_index = mp_dof_indices[0];\n      enth_cell->get_dof_indices(enth_dof_indices);\n      double volume = 0.;\n      for (unsigned int q = 0; q < n_q_points; ++q)\n        for (unsigned int i = 0; i < dofs_per_cell; ++i)\n        {\n          volume += fe_values.shape_value(i, q) * fe_values.JxW(q);\n          temperature_average[mp_dof_index] +=\n              fe_values.shape_value(i, q) * temperature[enth_dof_indices[i]] *\n              fe_values.JxW(q);\n        }\n      temperature_average[mp_dof_index] /= volume;\n    }\n\n  return temperature_average;\n}\n\ntemplate <int dim>\ndouble MaterialProperty<dim>::compute_property_from_table(\n    std::vector<std::pair<double, double>> const &table,\n    double const temperature) const\n{\n  if (table.size() == 0)\n    return 0.;\n  else\n  {\n    if (temperature <= table.front().first)\n      return table.front().second;\n    else if (temperature >= table.back().first)\n      return table.back().second;\n    else\n    {\n      auto it = std::find_if(table.begin(), table.end(),\n                             [=](std::pair<double, double> const &t_v) {\n                               return t_v.first > temperature;\n                             });\n      auto prev_it = it - 1;\n      return prev_it->second + (temperature - prev_it->first) *\n                                   (it->second - prev_it->second) /\n                                   (it->first - prev_it->first);\n    }\n  }\n}\n\ntemplate <int dim>\ndouble MaterialProperty<dim>::compute_property_from_polynomial(\n    std::vector<double> const &coef, double const temperature) const\n{\n  double value = 0.;\n  unsigned int const n_coef = coef.size();\n  for (unsigned int i = 0; i < n_coef; ++i)\n  {\n    value += coef[i] * std::pow(temperature, i);\n  }\n\n  return value;\n}\n} // namespace adamantine\n\nINSTANTIATE_DIM(MaterialProperty)\n", "meta": {"hexsha": "b860d48070a0e174ecd449c80f2c3104358846e4", "size": 15382, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/MaterialProperty.cc", "max_stars_repo_name": "stvdwtt/adamantine", "max_stars_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/MaterialProperty.cc", "max_issues_repo_name": "stvdwtt/adamantine", "max_issues_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/MaterialProperty.cc", "max_forks_repo_name": "stvdwtt/adamantine", "max_forks_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7009803922, "max_line_length": 80, "alphanum_fraction": 0.647900143, "num_tokens": 3586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.0335895062547419, "lm_q1q2_score": 0.01368212778860806}}
{"text": "// Spear: Statistical Platform for Elucidating moleculAr Reactivity\n// Copyright (C) Purdue University -- BSD license\n\n#include \"spear/Molecule.hpp\"\n\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/hawick_circuits.hpp>\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/connected_components.hpp>\n\n#include \"spear/atomtypes/Default.hpp\"\n\n#include \"spear/partialcharges/DefaultPartialCharge.hpp\"\n\n#include \"spear/Geometry.hpp\"\n\n#ifndef M_PI\nstatic const auto M_PI = std::acos(0.0) * 2;\n#endif\n\nusing Eigen::Vector3d;\n\nusing namespace Spear;\n\nsize_t AtomVertex::expected_bonds() const {\n    auto atomic_num = atomic_number();\n\n    switch(atomic_num) {\n        case Element::H:  // Hydrogen\n        case Element::F:  // Fluorine\n        case Element::Cl: // Chlorine\n        case Element::Br: // Bromine\n        case Element::I:  // Iodine\n        return 1;\n        break;\n\n        case Element::B:  // Boron\n        case Element::Al: // Aluminium\n        return 3;\n        break;\n\n        default: break;\n    }\n\n    auto hybridization_state = br_->atomtype()->hybridization(index_);\n\n    if(atomic_num == Element::C) {\n        switch (hybridization_state) {\n            case Hybridization::SP: return 2; break;\n            case Hybridization::SP2: return 3; break;\n            case Hybridization::SP3: return 4; break;\n            default: return 0; break;\n        }\n    }\n\n    if(atomic_num == Element::N) {\n        switch (hybridization_state) {\n            case Hybridization::SP: return 1; break;\n            case Hybridization::SP2: return 2; break;\n            case Hybridization::SP3: return 3; break;\n            default: return 0; break;\n        }\n    }\n\n    if(atomic_num == Element::O) {\n        switch (hybridization_state) {\n            case Hybridization::SP: return 1; break;\n            case Hybridization::SP2: return 1; break;\n            case Hybridization::SP3: return 2; break;\n            default: return 0; break;\n        }\n    }\n\n    if(atomic_num == 15 || atomic_num == 16) { // Phosphorus and Sulfur\n        if (is_aromatic()) return 2;\n        return degree(); // Hard to tell, but things shouldn't be protonated\n    }\n\n    // Give up....\n    return static_cast<size_t>(hybridization_state);\n}\n\n// The cycle_printer is a visitor that will print the path that comprises\n// the cycle. Note that the back() vertex of the path is not the same as\n// the front(). It is implicit in the listing of vertices that the back()\n// vertex is connected to the front().\nstruct cycle_saver {\n\n    cycle_saver(RingSet& counter):\n        found_rings(counter){\n    }\n\n    template <typename Path, typename Graph>\n    void cycle(const Path& p, const Graph& g) {\n        // Get the property map containing the vertex indices that are saved\n        auto indices = boost::get(boost::vertex_index, g);\n\n        // We deal mostly with undirected graphs, so a bond is technically a\n        // cycle. Let's avoid those!\n        if (p.size() <= 2) {\n            return;\n        }\n\n        // We've found a ring, so add it to found rings\n        std::set<size_t> new_ring;\n        for(const auto& i : p) {\n            new_ring.insert(boost::get(indices, i));\n        }\n\n        found_rings.insert(std::move(new_ring));\n    }\n\n    RingSet& found_rings;\n};\n\nMolecule::Molecule() {\n    add_atomtype<Default>();\n    std::vector<double> charges;\n    add_partial_charge<DefaultPartialCharge>(std::move(charges));\n}\n\nvoid Molecule::init_(const chemfiles::Frame& frame) {\n    std::vector<double> charges;\n    charges.reserve(frame.size());\n    for (const auto& atom : frame) {\n        auto atomic_number = atom.atomic_number();\n        if (atomic_number) {\n            auto an = static_cast<Element::Symbol>(*atomic_number);\n            boost::add_vertex(an, graph_);\n        } else {\n            boost::add_vertex(Element::Symbol(0), graph_);\n        }\n        charges.push_back(atom.charge());\n    }\n\n    for (size_t i = 0; i < frame.size(); ++i) {\n        auto& pos = frame.positions()[i];\n        positions_.emplace_back(pos[0], pos[1], pos[2]);\n    }\n\n    // Create the graph representation\n    auto bonds = topology_.bonds();\n    auto bos = topology_.bond_orders();\n    for ( size_t i = 0; i < bonds.size(); ++i) {\n        boost::add_edge(bonds[i][0], bonds[i][1],\n            static_cast<Bond::Order>(bos[i]), graph_);\n    }\n\n    add_partial_charge<DefaultPartialCharge>(std::move(charges));\n}\n\nvoid Molecule::rings_() {\n\n    if (!all_rings_.empty()) {\n        return;\n    }\n\n    bool remove_metal_bonds_ = true;\n    std::vector<std::pair<size_t, size_t>> metal_bonds;\n    if (remove_metal_bonds_) {\n        for (auto bond : bonds()) {\n            if (!bond.source().is_non_metal() ||\n                !bond.target().is_non_metal()) {\n                metal_bonds.push_back({bond.source(), bond.target()});\n            }\n\n            auto res1 = topology_.residue_for_atom(bond.source());\n            auto res2 = topology_.residue_for_atom(bond.target());\n            if (res1 && res2 && res1->name() == \"CYS\" && res2->name() == \"CYS\" &&\n                *res1 != *res2) {\n                metal_bonds.push_back({bond.source(), bond.target()});\n            }\n        }\n        for (auto& rm_bond : metal_bonds) {\n            remove_bond(rm_bond.first, rm_bond.second);\n        }\n    }\n\n    cycle_saver vis(all_rings_);\n    boost::hawick_circuits(graph_, vis);\n\n    for (auto& ring : all_rings_) {\n        for (auto& atom : ring) {\n            atom_to_ring_.insert({atom, ring});\n        }\n    }\n\n    smallest_set_of_smallest_rings_();\n\n    for (auto& rm_bond : metal_bonds) {\n        add_bond(rm_bond.first, rm_bond.second);\n    }\n}\n\nvoid Molecule::smallest_set_of_smallest_rings_() {\n\n    if (!sssr_.empty()) {\n        return;\n    }\n\n    auto all_rings = rings();\n\n    if (all_rings.size() == 0) {\n        return;\n    }\n\n    auto sssr_count = boost::num_edges(graph_) + connected_components() - size();\n\n    if (sssr_count >= all_rings.size()) {\n        sssr_ = all_rings_;\n        return;\n    }\n\n    size_t max_degree = 0;\n    for (auto av : *this) {\n        max_degree = std::max(max_degree, av.degree());\n    }\n\n    auto find_independant_rings_with_degree =\n    [sssr_count, &all_rings, this] (size_t degree) {\n        std::vector<bool> used_nodes(size(), false); // move out for speed?\n\n        // The rings are already sorted by their size, therefor we will\n        // traverse all of the rings from the smallest to largest here.\n        for (auto& current_ring : all_rings) {\n            bool is_independant = false;\n\n            // Have we seen this node before?\n            // ... but only check if the current degree is correct!\n            for (auto atom_id_search : current_ring) {\n                if ((*this)[atom_id_search].degree() != degree ||\n                    used_nodes[atom_id_search]) {\n                    continue;\n                }\n\n                is_independant = true;\n                break;\n            }\n\n            // This ring is completly encircled for the current degree\n            if (!is_independant) {\n                continue;\n            }\n\n            // We found a smallest ring! Mark its atoms as used\n            sssr_.insert(current_ring);\n\n            for (auto atom_id : current_ring) {\n                used_nodes[atom_id] = true;\n            }\n\n            if (sssr_.size() == sssr_count) {\n                break;\n            }\n        }\n    };\n\n    size_t iterations = 0; // I'm really scared of non termination. Let's be safe\n    do {\n        for (size_t i = 2; i <= max_degree; ++i) {\n            find_independant_rings_with_degree(i);\n\n            if (sssr_.size() == sssr_count) { // we're done!\n                for (auto& ring : sssr_) {\n                    for (auto& atom : ring) {\n                        atom_to_sssr_.insert({atom, ring});\n                    }\n                }\n\n                return;\n            }\n        }\n\n        if (sssr_.size() > sssr_count) {\n            break;\n        }\n\n        // things just got really weird - suppress the current SSSRs and try again\n        for (const auto& added : sssr_) {\n            all_rings.erase(added);\n        }\n\n        ++iterations;\n    } while(all_rings.size() != 0 && iterations < 100);\n\n    throw std::runtime_error(std::string(\"Unable to find SSSR: found \") +\n                             std::to_string(sssr_.size()) + \" rings, but expected \" +\n                             std::to_string(sssr_count));\n}\n\nvoid Molecule::add_default_type() {\n    add_atomtype<Default>();\n}\n\nstd::vector<Spear::BondEdge> Molecule::get_bonds_in(const std::set<size_t>& atoms) const {\n    auto all_bonds = bonds();\n\n    std::vector<BondEdge> ret;\n\n    std::copy_if(all_bonds.begin(), all_bonds.end(),\n                 std::back_inserter(ret),\n        [&atoms, this](BondEdge e){\n            auto target = e.target();\n            auto source = e.source();\n            if (atoms.count(target) == 0) {\n                return false;\n            }\n            if (atoms.count(source) == 0) {\n                return false;\n            }\n            return true;\n    });\n\n    return ret;\n}\n\nsize_t Molecule::connected_components() const {\n    std::vector<int> component(size());\n    return static_cast<size_t>(boost::connected_components(graph_, &component[0]));\n}\n\nvoid Molecule::remove_bond(size_t idx1, size_t idx2) {\n    boost::remove_edge(idx1, idx2, graph_);\n    topology_.remove_bond(idx1, idx2);\n}\n\nvoid Molecule::remove_atom(size_t index) {\n    boost::clear_vertex(index, graph_);\n    boost::remove_vertex(index, graph_);\n    topology_.remove(index);\n    positions_.erase(positions_.begin() + static_cast<std::ptrdiff_t>(index));\n    for (const auto& at : atom_types_) {\n         at.second->remove_atom(index);\n    }\n}\n\nvoid Molecule::swap_atoms(size_t idx1, size_t idx2) {\n\n    if (idx1 == idx2) {\n        throw std::logic_error(\"You cannot swap an atom with itself\");\n    }\n\n    std::swap(positions_[idx1], positions_[idx2]);\n\n    for (const auto& at : atom_types_) {\n        at.second->swap(idx1, idx2);\n    }\n\n    std::set<std::tuple<size_t, size_t, Bond::Order>> atom_bonds;\n\n    auto atm1 = (*this)[idx1].atomic_number();\n    auto atm2 = (*this)[idx2].atomic_number();\n\n    boost::get(boost::vertex_name, graph_, idx1) = atm2;\n    boost::get(boost::vertex_name, graph_, idx2) = atm1;\n\n    for (auto bond : (*this)[idx1].bonds()) {\n        if (bond.source() == idx2 || bond.target() == idx2) {\n            atom_bonds.insert({idx1, idx2, bond.order()});\n            remove_bond(bond.source(), bond.target());\n            continue;\n        }\n\n        if (bond.source() == idx1) {\n            atom_bonds.insert({idx2, bond.target(), bond.order()});\n        } else {\n            atom_bonds.insert({bond.source(), idx2, bond.order()});\n        }\n        remove_bond(bond.source(), bond.target());\n    }\n\n    for (auto bond : (*this)[idx2].bonds()) {\n        // The swapped atoms are bonded, only do this re-addition once\n        if (bond.source() == idx1 || bond.target() == idx1) {\n            remove_bond(bond.source(), bond.target());\n            continue;\n        }\n        if (bond.source() == idx2) {\n            atom_bonds.insert({idx1, bond.target(), bond.order()});\n        } else {\n            atom_bonds.insert({bond.source(), idx1, bond.order()});\n        }\n        remove_bond(bond.source(), bond.target());\n    }\n\n    for (auto& bond : atom_bonds) {\n        add_bond(get<0>(bond), get<1>(bond), get<2>(bond));\n    }\n\n    std::swap(topology_[idx1], topology_[idx2]);\n}\n\nvoid Molecule::remove_hydrogens() {\n    auto& mol = *this;\n\n    // Removal of an atom invalidates the vertex descriptors as we are using a\n    // vecS for vertex storage (required to link index to frame).\n    // Therefore we need to restart the search when we remove something.\n    bool has_hydrogens = false;\n    size_t skip_len = 0;\n    do {\n        auto verticies_iter = boost::vertices(graph_);    \n        has_hydrogens = false;\n        for (auto v = verticies_iter.first + static_cast<std::ptrdiff_t>(skip_len);\n                  v != verticies_iter.second; ++v) {\n            auto index = boost::get(boost::vertex_index, graph_, *v);\n            if (mol[index].atomic_number() == Element::H) {\n                skip_len = *v;\n                boost::clear_vertex(*v, graph_);\n                boost::remove_vertex(*v, graph_);\n                topology_.remove(index);\n                positions_.erase(positions_.begin() + static_cast<std::ptrdiff_t>(index));\n                for (const auto& at : atom_types_) {\n                    at.second->remove_atom(index);\n                }\n                has_hydrogens = true;\n                break;\n            }\n        }\n    } while (has_hydrogens);\n}\n\nAtomVertex Molecule::add_atom(Element::Symbol n_atom, const Eigen::Vector3d& pos) {\n    auto desc = boost::add_vertex(n_atom, graph_);\n    positions_.push_back(pos);\n    topology_.add_atom(chemfiles::Atom(Element::Name[n_atom]));\n    for (const auto& at : atom_types_) {\n        at.second->add_atom(desc);\n    }\n    return {this, desc};\n}\n\nBondEdge Molecule::add_bond(size_t idx1, size_t idx2, Bond::Order order) {\n    auto new_edge = boost::add_edge(idx1, idx2, order, graph_);\n    if (!new_edge.second) {\n        throw std::runtime_error(\"Could not add bond between: \" +\n                                 std::to_string(idx1) + \" and \" +\n                                 std::to_string(idx2));\n    }\n    topology_.add_bond(idx1, idx2, static_cast<chemfiles::Bond::BondOrder>(order));\n    for (const auto& at : atom_types_) {\n        at.second->add_bond(idx1, idx2, order);\n    }\n    return {this, new_edge.first};\n}\n\nstatic Eigen::Vector3d perpendicular(const Eigen::Vector3d& other) {\n    Vector3d res(0.0, 0.0, 0.0);\n    if (other[0] != 0.0) {\n        if (other[1] != 0.0) {\n            res[1] = -1 * other[0];\n            res[0] = other[1];\n        } else if (other[2] != 0.0) {\n            res[2] = -1 * other[0];\n            res[0] = other[2];\n        } else {\n            res[1] = 1;\n        }\n    } else if (other[1] != 0.0) {\n        if (other[2] != 0.0) {\n            res[2] = -1 * other[1];\n            res[1] = other[2];\n        } else {\n            res[0] = 1;\n        }\n    } else if (other[2] != 0.0) {\n        res[0] = 1;\n    }\n    res.normalize();\n    return res;\n}\n\n// This code is largely based off of RDkit's code used to generate hydrogen\n// locations. The original version is availible here:\n// https://github.com/rdkit/rdkit/blob/95eeec7b3424f482416aa0c85b77fc73ab3008c1/Code/GraphMol/AddHs.cpp#L45\n\nAtomVertex Molecule::add_atom_to(Element::Symbol n_atom, size_t index) {\n\n    auto av = (*this)[index];\n\n    Vector3d dirVect(0, 0, 0);\n\n    Vector3d heavyPos = av.position();\n\n    Vector3d perpVect, rotnAxis, nbrPerp;\n    Vector3d nbr1Vect, nbr2Vect, nbr3Vect;\n\n    auto dimensional = dimensionality(positions_);\n\n    // All the coordinates are the same, let's ignore this case\n    if (dimensional == 0 && av.degree() >= 1) {\n        auto h_atom = add_atom(n_atom, heavyPos);\n        add_bond(index, h_atom);\n        return h_atom;\n    }\n\n    auto hybrid = atomtype()->hybridization(index);\n\n    if (hybrid == Hybridization::UNKNOWN || hybrid == Hybridization::FORCED) {\n        throw std::runtime_error(\"Cannot add atom to UNKNOWN or FORCED hybridizations\");\n    }\n\n    // Spoof SP2 for planar nitrogens so that atoms are added in the same plane\n    // and we can prevent the loss of conjugation\n    if (av.atomic_number() == Element::N && hybrid == Hybridization::SP3 &&\n        atomtype()->is_planar(index)) {\n        hybrid = Hybridization::SP2;\n    }\n\n    bool is3D = dimensional == 3;\n\n    double bondLength =\n        is3D ?\n            Element::CovalentRadius[n_atom] +\n            Element::CovalentRadius[av.atomic_number()] :\n            1.0;\n\n    if (is3D && av.atomic_number() == Element::C && hybrid == Hybridization::SP2) {\n        bondLength += 0.04;\n    }\n\n    if (is3D && av.atomic_number() == Element::C && hybrid == Hybridization::SP3) {\n        bondLength += 0.07;\n    }\n\n    switch (av.degree()) {\n    case 0: // No other atom neighbors, add position in the z-direction\n        dirVect[2] = 1;\n        break;\n\n    case 1: // One Neighbor present\n        // get a normalized vector pointing away from the neighbor:\n        nbr1Vect = av[0].position() - heavyPos;\n\n        nbr1Vect.normalize();\n        nbr1Vect *= -1;\n\n        // nbr1Vect points away from the other atom, add new H accordingly:\n        switch (hybrid) {\n        case Hybridization::SP3:\n            // get a perpendicular to nbr1Vect:\n            perpVect = perpendicular(nbr1Vect);\n            if (!is3D) {\n                perpVect[0] = 0.0;\n                perpVect[1] = 0.0;\n                perpVect[2] = 1.0;\n            }\n            // and move off it:\n            dirVect = Eigen::AngleAxisd((180 - 109.471) * M_PI / 180.0, perpVect) * nbr1Vect;\n            break;\n        case Hybridization::SP2:\n            // default position is to just take an arbitrary perpendicular:\n            perpVect = perpendicular(nbr1Vect);\n            if (av[0].degree() > 1) {\n                // can we use the neighboring atom to establish a perpendicular?\n                auto nbrBond = *(av.bonds().begin()); // Only one bond, so this has to be the one!\n                if (nbrBond.order() == Bond::AROMATIC ||\n                    nbrBond.order() == Bond::DOUBLE) {\n                    for (auto nbr2 : av[0].neighbors()) {\n                        if (nbr2 != av) {\n                            nbr2Vect = nbr2.position() - av[0].position();\n                            nbr2Vect.normalize();\n                            break;\n                        }\n                    }\n                    perpVect = nbr2Vect.cross(nbr1Vect);\n                }\n            }\n            perpVect.normalize();\n            // rotate the nbr1Vect 60 degrees about perpVect and we're done:\n            dirVect = Eigen::AngleAxisd(60.0 * M_PI / 180.0, perpVect) * nbr1Vect;\n            break;\n        case Hybridization::SP:\n            // just lay the H along the vector:\n            dirVect = nbr1Vect;\n            break;\n        default:\n            // FIX: handle other hybridizations\n            // for now, just lay the H along the vector:\n            dirVect = nbr1Vect;\n        }\n        break;\n    case 2: // Two other neighbors:\n        // start along the average of the two vectors:\n        nbr1Vect = heavyPos - av[0].position();\n        nbr2Vect = heavyPos - av[1].position();\n\n        nbr1Vect.normalize();\n        nbr2Vect.normalize();\n        dirVect = nbr1Vect + nbr2Vect;\n\n        dirVect.normalize();\n        if (is3D) {\n            switch (hybrid) {\n            case Hybridization::SP3:\n                // get the perpendicular to the neighbors:\n                nbrPerp = nbr1Vect.cross(nbr2Vect);\n                // and the perpendicular to that:\n                rotnAxis = nbrPerp.cross(dirVect);\n                // and then rotate about that:\n                rotnAxis.normalize();\n                dirVect = Eigen::AngleAxisd((109.471 / 2) * M_PI / 180., rotnAxis) * dirVect;\n                break;\n            case Hybridization::SP2:\n                // don't need to do anything here, the H atom goes right on the direction vector\n                break;\n            case Hybridization::SP:\n                // Can't add an atom here, the bond is saturated!\n                throw std::runtime_error(\"Cannot add a third atom to SP atoms!\");\n                break;\n            default:\n                // FIX: handle other hybridizations\n                // for now, just lay the H along the neighbor vector;\n                break;\n            }\n        }\n        // don't need to do anything here, the H atom goes right on the direction vector\n        break;\n    case 3: // Three other neighbors:\n\n        if (hybrid == Hybridization::SP2 || hybrid == Hybridization::SP) {\n            throw std::runtime_error(\"Cannot add a fourth atom to planar nitrogens or SP/SP2 atoms!\");\n        }\n\n        // use the average of the three vectors:\n        nbr1Vect = heavyPos - av[0].position();\n        nbr2Vect = heavyPos - av[1].position();\n        nbr3Vect = heavyPos - av[2].position();\n        nbr1Vect.normalize();\n        nbr2Vect.normalize();\n        nbr3Vect.normalize();\n\n        // if three neighboring atoms are more or less planar, this\n        // is going to be in a quasi-random (but almost definitely bad)\n        // direction...\n        if (is3D) {\n            dirVect = nbr1Vect + nbr2Vect + nbr3Vect;\n            dirVect.normalize();\n        } else {\n            // we're in flatland\n            // We're in a 2D conformation, put the H between the two neighbors\n            // that have the widest angle between them:\n            double minDot = nbr1Vect.dot(nbr2Vect);\n            dirVect = nbr1Vect + nbr2Vect;\n            if (nbr2Vect.dot(nbr3Vect) < minDot) {\n                nbr2Vect.dot(nbr3Vect);\n                dirVect = nbr2Vect + nbr3Vect;\n            }\n            if (nbr1Vect.dot(nbr3Vect) < minDot) {\n                nbr1Vect.dot(nbr3Vect);\n                dirVect = nbr1Vect + nbr3Vect;\n            }\n            dirVect *= -1;\n        }\n        break;\n    case 4:\n        if (hybrid == Hybridization::SP3 ||\n            hybrid == Hybridization::SP2 ||\n            hybrid == Hybridization::SP) {\n            throw std::runtime_error(\"Cannot add a fifth atom to SP, SP2, or SP3 atoms!\");\n        }\n\n    default: // Give up!\n        break;\n    }\n\n    dirVect.normalize();\n    auto h_atom = add_atom(n_atom, heavyPos + dirVect * bondLength);\n    add_bond(av, h_atom);\n\n    const auto& res = topology_.residue_for_atom(av);\n    if (res) {\n        chemfiles::Residue res2(res->name());\n        res2.add_atom(h_atom);\n        auto neigh_name = av.name();\n        neigh_name[0] = 'H';\n        topology_.add_residue(res2);\n        topology_[h_atom].set_name(neigh_name);\n    }\n\n    return h_atom;\n}\n\nsize_t Molecule::add_hydrogens() {\n    bool hydrogens_to_add = false;\n    size_t hydrogens_added = 0;\n    do {\n        hydrogens_to_add = false;\n        for (auto atom : *this) {\n            if (atom.implicit_hydrogens() < 1 || atom.atomic_number() == Element::H) {\n                continue;\n            }\n            hydrogens_to_add = true;\n            ++hydrogens_added;\n            add_atom_to(Element::H, atom);\n            break;\n        }\n    } while (hydrogens_to_add);\n\n    return hydrogens_added;\n}\n", "meta": {"hexsha": "e907a1ccc453a0b4f3604f6e2cb811be137f42bf", "size": 22446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molecule.cpp", "max_stars_repo_name": "chopralab/spear", "max_stars_repo_head_hexsha": "d45ffc907ab1730789413dd04afb347a26f35154", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T07:57:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T13:58:37.000Z", "max_issues_repo_path": "src/Molecule.cpp", "max_issues_repo_name": "chopralab/spear", "max_issues_repo_head_hexsha": "d45ffc907ab1730789413dd04afb347a26f35154", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Molecule.cpp", "max_forks_repo_name": "chopralab/spear", "max_forks_repo_head_hexsha": "d45ffc907ab1730789413dd04afb347a26f35154", "max_forks_repo_licenses": ["BSD-3-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.9743589744, "max_line_length": 107, "alphanum_fraction": 0.5555110042, "num_tokens": 5653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660016, "lm_q2_score": 0.03358950637566948, "lm_q1q2_score": 0.013682127354535407}}
{"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_python_interface.hh\"\n#include \"graph_filtering.hh\"\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_properties.hh\"\n\n#include <boost/mpl/push_back.hpp>\n#include <boost/python.hpp>\n\n#include \"graph_community.hh\"\n\nusing namespace std;\nusing namespace boost;\n\nusing namespace graph_tool;\n\n\nvoid community_structure(GraphInterface& g, double gamma, string corr_name,\n                         size_t n_iter, double Tmin, double Tmax, size_t Nspins,\n                         rng_t& rng, bool verbose, string history_file,\n                         boost::any weight, boost::any property)\n{\n    typedef property_map_types::apply<boost::mpl::vector<int32_t,int64_t>,\n                                      GraphInterface::vertex_index_map_t,\n                                      boost::mpl::bool_<false> >::type\n        allowed_spin_properties;\n\n    if (!belongs<allowed_spin_properties>()(property))\n        throw ValueException(\"vertex property is not of integer type int32_t \"\n                             \"or int64_t\");\n\n    typedef DynamicPropertyMapWrap<double,GraphInterface::edge_t> weight_map_t;\n    typedef ConstantPropertyMap<double,GraphInterface::edge_t> no_weight_map_t;\n    typedef boost::mpl::vector<weight_map_t,no_weight_map_t> weight_properties;\n\n    if (weight.empty())\n        weight = no_weight_map_t(1.0);\n    else\n        weight = weight_map_t(weight, edge_scalar_properties());\n\n    comm_corr_t corr;\n    if (corr_name ==  \"erdos\")\n        corr = ERDOS_REYNI;\n    else if (corr_name == \"uncorrelated\")\n        corr = UNCORRELATED;\n    else if (corr_name == \"correlated\")\n        corr = CORRELATED;\n    else\n        throw ValueException(\"invalid correlation type: \" + corr_name);\n\n    run_action<graph_tool::detail::never_directed>()\n        (g, std::bind(get_communities_selector(corr, g.GetVertexIndex()),\n                      placeholders::_1, placeholders::_2, placeholders::_3, gamma, n_iter,\n                      make_pair(Tmin, Tmax), Nspins,\n                      std::ref(rng), make_pair(verbose,history_file)),\n         weight_properties(), allowed_spin_properties())\n        (weight, property);\n}\n\n\ndouble modularity(GraphInterface& g, boost::any weight, boost::any property)\n{\n    double modularity = 0;\n\n    typedef ConstantPropertyMap<int32_t,GraphInterface::edge_t> weight_map_t;\n    typedef boost::mpl::push_back<edge_scalar_properties, weight_map_t>::type\n        edge_props_t;\n\n    if(weight.empty())\n        weight = weight_map_t(1);\n\n    run_action<graph_tool::detail::never_directed>()\n        (g, std::bind(get_modularity(), placeholders::_1, placeholders::_2,\n                      placeholders::_3, std::ref(modularity)),\n         edge_props_t(), vertex_scalar_properties())\n        (weight, property);\n    return modularity;\n}\n\nusing namespace boost::python;\n\n\nextern void community_network(GraphInterface& gi, GraphInterface& cgi,\n                              boost::any community_property,\n                              boost::any condensed_community_property,\n                              boost::any vertex_count, boost::any edge_count,\n                              boost::any vweight, boost::any eweight,\n                              bool self_loops, bool parallel_edges);\n\nvoid community_network_vavg(GraphInterface& gi, GraphInterface& cgi,\n                            boost::any community_property,\n                            boost::any condensed_community_property,\n                            boost::any vweight,\n                            boost::python::list avprops);\n\nvoid community_network_eavg(GraphInterface& gi, GraphInterface& cgi,\n                            boost::any community_property,\n                            boost::any condensed_community_property,\n                            boost::any eweight,\n                            boost::python::list aeprops,\n                            bool self_loops);\n\n\nextern void export_blockmodel();\nextern void export_blockmodel_overlap();\nextern void export_blockmodel_covariate();\n\nBOOST_PYTHON_MODULE(libgraph_tool_community)\n{\n    def(\"community_structure\", &community_structure);\n    def(\"modularity\", &modularity);\n    def(\"community_network\", &community_network);\n    def(\"community_network_vavg\", &community_network_vavg);\n    def(\"community_network_eavg\", &community_network_eavg);\n\n    export_blockmodel();\n    export_blockmodel_overlap();\n    export_blockmodel_covariate();\n}\n", "meta": {"hexsha": "de5ae1201160a3a489bb6e1f2c9b2731c2b9b9f9", "size": 5221, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/community/graph_community.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/community/graph_community.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/community/graph_community.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": 38.1094890511, "max_line_length": 90, "alphanum_fraction": 0.6512162421, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.028007519490434726, "lm_q1q2_score": 0.013675606710603734}}
{"text": "//=======================================================================\n// Copyright 2009 Trustees of Indiana University.\n// Authors: Michael Hansen, Andrew Lumsdaine\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_MCGREGOR_COMMON_SUBGRAPHS_HPP\n#define BOOST_GRAPH_MCGREGOR_COMMON_SUBGRAPHS_HPP\n\n#include <algorithm>\n#include <vector>\n#include <stack>\n\n#include <boost/make_shared.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/property_map/shared_array_property_map.hpp>\n\nnamespace boost\n{\n\nnamespace detail\n{\n\n    // Traits associated with common subgraphs, used mainly to keep a\n    // consistent type for the correspondence maps.\n    template < typename GraphFirst, typename GraphSecond,\n        typename VertexIndexMapFirst, typename VertexIndexMapSecond >\n    struct mcgregor_common_subgraph_traits\n    {\n        typedef typename graph_traits< GraphFirst >::vertex_descriptor\n            vertex_first_type;\n        typedef typename graph_traits< GraphSecond >::vertex_descriptor\n            vertex_second_type;\n\n        typedef shared_array_property_map< vertex_second_type,\n            VertexIndexMapFirst >\n            correspondence_map_first_to_second_type;\n\n        typedef shared_array_property_map< vertex_first_type,\n            VertexIndexMapSecond >\n            correspondence_map_second_to_first_type;\n    };\n\n} // namespace detail\n\n// ==========================================================================\n\n// Binary function object that returns true if the values for item1\n// in property_map1 and item2 in property_map2 are equivalent.\ntemplate < typename PropertyMapFirst, typename PropertyMapSecond >\nstruct property_map_equivalent\n{\n\n    property_map_equivalent(const PropertyMapFirst property_map1,\n        const PropertyMapSecond property_map2)\n    : m_property_map1(property_map1), m_property_map2(property_map2)\n    {\n    }\n\n    template < typename ItemFirst, typename ItemSecond >\n    bool operator()(const ItemFirst item1, const ItemSecond item2)\n    {\n        return (get(m_property_map1, item1) == get(m_property_map2, item2));\n    }\n\nprivate:\n    const PropertyMapFirst m_property_map1;\n    const PropertyMapSecond m_property_map2;\n};\n\n// Returns a property_map_equivalent object that compares the values\n// of property_map1 and property_map2.\ntemplate < typename PropertyMapFirst, typename PropertyMapSecond >\nproperty_map_equivalent< PropertyMapFirst, PropertyMapSecond >\nmake_property_map_equivalent(\n    const PropertyMapFirst property_map1, const PropertyMapSecond property_map2)\n{\n\n    return (property_map_equivalent< PropertyMapFirst, PropertyMapSecond >(\n        property_map1, property_map2));\n}\n\n// Binary function object that always returns true.  Used when\n// vertices or edges are always equivalent (i.e. have no labels).\nstruct always_equivalent\n{\n\n    template < typename ItemFirst, typename ItemSecond >\n    bool operator()(const ItemFirst&, const ItemSecond&)\n    {\n        return (true);\n    }\n};\n\n// ==========================================================================\n\nnamespace detail\n{\n\n    // Return true if new_vertex1 and new_vertex2 can extend the\n    // subgraph represented by correspondence_map_1_to_2 and\n    // correspondence_map_2_to_1.  The vertices_equivalent and\n    // edges_equivalent predicates are used to test vertex and edge\n    // equivalency between the two graphs.\n    template < typename GraphFirst, typename GraphSecond,\n        typename CorrespondenceMapFirstToSecond,\n        typename CorrespondenceMapSecondToFirst,\n        typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate >\n    bool can_extend_graph(const GraphFirst& graph1, const GraphSecond& graph2,\n        CorrespondenceMapFirstToSecond correspondence_map_1_to_2,\n        CorrespondenceMapSecondToFirst /*correspondence_map_2_to_1*/,\n        typename graph_traits< GraphFirst >::vertices_size_type subgraph_size,\n        typename graph_traits< GraphFirst >::vertex_descriptor new_vertex1,\n        typename graph_traits< GraphSecond >::vertex_descriptor new_vertex2,\n        EdgeEquivalencePredicate edges_equivalent,\n        VertexEquivalencePredicate vertices_equivalent,\n        bool only_connected_subgraphs)\n    {\n        typedef typename graph_traits< GraphSecond >::vertex_descriptor\n            VertexSecond;\n\n        typedef typename graph_traits< GraphFirst >::edge_descriptor EdgeFirst;\n        typedef\n            typename graph_traits< GraphSecond >::edge_descriptor EdgeSecond;\n\n        // Check vertex equality\n        if (!vertices_equivalent(new_vertex1, new_vertex2))\n        {\n            return (false);\n        }\n\n        // Vertices match and graph is empty, so we can extend the subgraph\n        if (subgraph_size == 0)\n        {\n            return (true);\n        }\n\n        bool has_one_edge = false;\n\n        // Verify edges with existing sub-graph\n        BGL_FORALL_VERTICES_T(existing_vertex1, graph1, GraphFirst)\n        {\n\n            VertexSecond existing_vertex2\n                = get(correspondence_map_1_to_2, existing_vertex1);\n\n            // Skip unassociated vertices\n            if (existing_vertex2 == graph_traits< GraphSecond >::null_vertex())\n            {\n                continue;\n            }\n\n            // NOTE: This will not work with parallel edges, since the\n            // first matching edge is always chosen.\n            EdgeFirst edge_to_new1, edge_from_new1;\n            bool edge_to_new_exists1 = false, edge_from_new_exists1 = false;\n\n            EdgeSecond edge_to_new2, edge_from_new2;\n            bool edge_to_new_exists2 = false, edge_from_new_exists2 = false;\n\n            // Search for edge from existing to new vertex (graph1)\n            BGL_FORALL_OUTEDGES_T(existing_vertex1, edge1, graph1, GraphFirst)\n            {\n                if (target(edge1, graph1) == new_vertex1)\n                {\n                    edge_to_new1 = edge1;\n                    edge_to_new_exists1 = true;\n                    break;\n                }\n            }\n\n            // Search for edge from existing to new vertex (graph2)\n            BGL_FORALL_OUTEDGES_T(existing_vertex2, edge2, graph2, GraphSecond)\n            {\n                if (target(edge2, graph2) == new_vertex2)\n                {\n                    edge_to_new2 = edge2;\n                    edge_to_new_exists2 = true;\n                    break;\n                }\n            }\n\n            // Make sure edges from existing to new vertices are equivalent\n            if ((edge_to_new_exists1 != edge_to_new_exists2)\n                || ((edge_to_new_exists1 && edge_to_new_exists2)\n                    && !edges_equivalent(edge_to_new1, edge_to_new2)))\n            {\n\n                return (false);\n            }\n\n            bool is_undirected1 = is_undirected(graph1),\n                 is_undirected2 = is_undirected(graph2);\n\n            if (is_undirected1 && is_undirected2)\n            {\n\n                // Edge in both graphs exists and both graphs are undirected\n                if (edge_to_new_exists1 && edge_to_new_exists2)\n                {\n                    has_one_edge = true;\n                }\n\n                continue;\n            }\n            else\n            {\n\n                if (!is_undirected1)\n                {\n\n                    // Search for edge from new to existing vertex (graph1)\n                    BGL_FORALL_OUTEDGES_T(\n                        new_vertex1, edge1, graph1, GraphFirst)\n                    {\n                        if (target(edge1, graph1) == existing_vertex1)\n                        {\n                            edge_from_new1 = edge1;\n                            edge_from_new_exists1 = true;\n                            break;\n                        }\n                    }\n                }\n\n                if (!is_undirected2)\n                {\n\n                    // Search for edge from new to existing vertex (graph2)\n                    BGL_FORALL_OUTEDGES_T(\n                        new_vertex2, edge2, graph2, GraphSecond)\n                    {\n                        if (target(edge2, graph2) == existing_vertex2)\n                        {\n                            edge_from_new2 = edge2;\n                            edge_from_new_exists2 = true;\n                            break;\n                        }\n                    }\n                }\n\n                // Make sure edges from new to existing vertices are equivalent\n                if ((edge_from_new_exists1 != edge_from_new_exists2)\n                    || ((edge_from_new_exists1 && edge_from_new_exists2)\n                        && !edges_equivalent(edge_from_new1, edge_from_new2)))\n                {\n\n                    return (false);\n                }\n\n                if ((edge_from_new_exists1 && edge_from_new_exists2)\n                    || (edge_to_new_exists1 && edge_to_new_exists2))\n                {\n                    has_one_edge = true;\n                }\n\n            } // else\n\n        } // BGL_FORALL_VERTICES_T\n\n        // Make sure new vertices are connected to the existing subgraph\n        if (only_connected_subgraphs && !has_one_edge)\n        {\n            return (false);\n        }\n\n        return (true);\n    }\n\n    // Recursive method that does a depth-first search in the space of\n    // potential subgraphs.  At each level, every new vertex pair from\n    // both graphs is tested to see if it can extend the current\n    // subgraph.  If so, the subgraph is output to subgraph_callback\n    // in the form of two correspondence maps (one for each graph).\n    // Returning false from subgraph_callback will terminate the\n    // search.  Function returns true if the entire search space was\n    // explored.\n    template < typename GraphFirst, typename GraphSecond,\n        typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n        typename CorrespondenceMapFirstToSecond,\n        typename CorrespondenceMapSecondToFirst, typename VertexStackFirst,\n        typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\n        typename SubGraphInternalCallback >\n    bool mcgregor_common_subgraphs_internal(const GraphFirst& graph1,\n        const GraphSecond& graph2, const VertexIndexMapFirst& vindex_map1,\n        const VertexIndexMapSecond& vindex_map2,\n        CorrespondenceMapFirstToSecond correspondence_map_1_to_2,\n        CorrespondenceMapSecondToFirst correspondence_map_2_to_1,\n        VertexStackFirst& vertex_stack1,\n        EdgeEquivalencePredicate edges_equivalent,\n        VertexEquivalencePredicate vertices_equivalent,\n        bool only_connected_subgraphs,\n        SubGraphInternalCallback subgraph_callback)\n    {\n        typedef\n            typename graph_traits< GraphFirst >::vertex_descriptor VertexFirst;\n        typedef typename graph_traits< GraphSecond >::vertex_descriptor\n            VertexSecond;\n        typedef typename graph_traits< GraphFirst >::vertices_size_type\n            VertexSizeFirst;\n\n        // Get iterators for vertices from both graphs\n        typename graph_traits< GraphFirst >::vertex_iterator vertex1_iter,\n            vertex1_end;\n\n        typename graph_traits< GraphSecond >::vertex_iterator vertex2_begin,\n            vertex2_end, vertex2_iter;\n\n        boost::tie(vertex1_iter, vertex1_end) = vertices(graph1);\n        boost::tie(vertex2_begin, vertex2_end) = vertices(graph2);\n        vertex2_iter = vertex2_begin;\n\n        // Iterate until all vertices have been visited\n        BGL_FORALL_VERTICES_T(new_vertex1, graph1, GraphFirst)\n        {\n\n            VertexSecond existing_vertex2\n                = get(correspondence_map_1_to_2, new_vertex1);\n\n            // Skip already matched vertices in first graph\n            if (existing_vertex2 != graph_traits< GraphSecond >::null_vertex())\n            {\n                continue;\n            }\n\n            BGL_FORALL_VERTICES_T(new_vertex2, graph2, GraphSecond)\n            {\n\n                VertexFirst existing_vertex1\n                    = get(correspondence_map_2_to_1, new_vertex2);\n\n                // Skip already matched vertices in second graph\n                if (existing_vertex1\n                    != graph_traits< GraphFirst >::null_vertex())\n                {\n                    continue;\n                }\n\n                // Check if current sub-graph can be extended with the matched\n                // vertex pair\n                if (can_extend_graph(graph1, graph2, correspondence_map_1_to_2,\n                        correspondence_map_2_to_1,\n                        (VertexSizeFirst)vertex_stack1.size(), new_vertex1,\n                        new_vertex2, edges_equivalent, vertices_equivalent,\n                        only_connected_subgraphs))\n                {\n\n                    // Keep track of old graph size for restoring later\n                    VertexSizeFirst old_graph_size\n                        = (VertexSizeFirst)vertex_stack1.size(),\n                        new_graph_size = old_graph_size + 1;\n\n                    // Extend subgraph\n                    put(correspondence_map_1_to_2, new_vertex1, new_vertex2);\n                    put(correspondence_map_2_to_1, new_vertex2, new_vertex1);\n                    vertex_stack1.push(new_vertex1);\n\n                    // Returning false from the callback will cancel iteration\n                    if (!subgraph_callback(correspondence_map_1_to_2,\n                            correspondence_map_2_to_1, new_graph_size))\n                    {\n                        return (false);\n                    }\n\n                    // Depth-first search into the state space of possible\n                    // sub-graphs\n                    bool continue_iteration\n                        = mcgregor_common_subgraphs_internal(graph1, graph2,\n                            vindex_map1, vindex_map2, correspondence_map_1_to_2,\n                            correspondence_map_2_to_1, vertex_stack1,\n                            edges_equivalent, vertices_equivalent,\n                            only_connected_subgraphs, subgraph_callback);\n\n                    if (!continue_iteration)\n                    {\n                        return (false);\n                    }\n\n                    // Restore previous state\n                    if (vertex_stack1.size() > old_graph_size)\n                    {\n\n                        VertexFirst stack_vertex1 = vertex_stack1.top();\n                        VertexSecond stack_vertex2\n                            = get(correspondence_map_1_to_2, stack_vertex1);\n\n                        // Contract subgraph\n                        put(correspondence_map_1_to_2, stack_vertex1,\n                            graph_traits< GraphSecond >::null_vertex());\n\n                        put(correspondence_map_2_to_1, stack_vertex2,\n                            graph_traits< GraphFirst >::null_vertex());\n\n                        vertex_stack1.pop();\n                    }\n\n                } // if can_extend_graph\n\n            } // BGL_FORALL_VERTICES_T (graph2)\n\n        } // BGL_FORALL_VERTICES_T (graph1)\n\n        return (true);\n    }\n\n    // Internal method that initializes blank correspondence maps and\n    // a vertex stack for use in mcgregor_common_subgraphs_internal.\n    template < typename GraphFirst, typename GraphSecond,\n        typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n        typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\n        typename SubGraphInternalCallback >\n    inline void mcgregor_common_subgraphs_internal_init(\n        const GraphFirst& graph1, const GraphSecond& graph2,\n        const VertexIndexMapFirst vindex_map1,\n        const VertexIndexMapSecond vindex_map2,\n        EdgeEquivalencePredicate edges_equivalent,\n        VertexEquivalencePredicate vertices_equivalent,\n        bool only_connected_subgraphs,\n        SubGraphInternalCallback subgraph_callback)\n    {\n        typedef mcgregor_common_subgraph_traits< GraphFirst, GraphSecond,\n            VertexIndexMapFirst, VertexIndexMapSecond >\n            SubGraphTraits;\n\n        typename SubGraphTraits::correspondence_map_first_to_second_type\n            correspondence_map_1_to_2(num_vertices(graph1), vindex_map1);\n\n        BGL_FORALL_VERTICES_T(vertex1, graph1, GraphFirst)\n        {\n            put(correspondence_map_1_to_2, vertex1,\n                graph_traits< GraphSecond >::null_vertex());\n        }\n\n        typename SubGraphTraits::correspondence_map_second_to_first_type\n            correspondence_map_2_to_1(num_vertices(graph2), vindex_map2);\n\n        BGL_FORALL_VERTICES_T(vertex2, graph2, GraphSecond)\n        {\n            put(correspondence_map_2_to_1, vertex2,\n                graph_traits< GraphFirst >::null_vertex());\n        }\n\n        typedef\n            typename graph_traits< GraphFirst >::vertex_descriptor VertexFirst;\n\n        std::stack< VertexFirst > vertex_stack1;\n\n        mcgregor_common_subgraphs_internal(graph1, graph2, vindex_map1,\n            vindex_map2, correspondence_map_1_to_2, correspondence_map_2_to_1,\n            vertex_stack1, edges_equivalent, vertices_equivalent,\n            only_connected_subgraphs, subgraph_callback);\n    }\n\n} // namespace detail\n\n// ==========================================================================\n\n// Enumerates all common subgraphs present in graph1 and graph2.\n// Continues until the search space has been fully explored or false\n// is returned from user_callback.\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs(const GraphFirst& graph1,\n    const GraphSecond& graph2, const VertexIndexMapFirst vindex_map1,\n    const VertexIndexMapSecond vindex_map2,\n    EdgeEquivalencePredicate edges_equivalent,\n    VertexEquivalencePredicate vertices_equivalent,\n    bool only_connected_subgraphs, SubGraphCallback user_callback)\n{\n\n    detail::mcgregor_common_subgraphs_internal_init(graph1, graph2, vindex_map1,\n        vindex_map2, edges_equivalent, vertices_equivalent,\n        only_connected_subgraphs, user_callback);\n}\n\n// Variant of mcgregor_common_subgraphs with all default parameters\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback)\n{\n\n    detail::mcgregor_common_subgraphs_internal_init(graph1, graph2,\n        get(vertex_index, graph1), get(vertex_index, graph2),\n        always_equivalent(), always_equivalent(), only_connected_subgraphs,\n        user_callback);\n}\n\n// Named parameter variant of mcgregor_common_subgraphs\ntemplate < typename GraphFirst, typename GraphSecond, typename SubGraphCallback,\n    typename Param, typename Tag, typename Rest >\nvoid mcgregor_common_subgraphs(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback,\n    const bgl_named_params< Param, Tag, Rest >& params)\n{\n\n    detail::mcgregor_common_subgraphs_internal_init(graph1, graph2,\n        choose_const_pmap(\n            get_param(params, vertex_index1), graph1, vertex_index),\n        choose_const_pmap(\n            get_param(params, vertex_index2), graph2, vertex_index),\n        choose_param(\n            get_param(params, edges_equivalent_t()), always_equivalent()),\n        choose_param(\n            get_param(params, vertices_equivalent_t()), always_equivalent()),\n        only_connected_subgraphs, user_callback);\n}\n\n// ==========================================================================\n\nnamespace detail\n{\n\n    // Binary function object that intercepts subgraphs from\n    // mcgregor_common_subgraphs_internal and maintains a cache of\n    // unique subgraphs.  The user callback is invoked for each unique\n    // subgraph.\n    template < typename GraphFirst, typename GraphSecond,\n        typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n        typename SubGraphCallback >\n    struct unique_subgraph_interceptor\n    {\n\n        typedef typename graph_traits< GraphFirst >::vertices_size_type\n            VertexSizeFirst;\n\n        typedef mcgregor_common_subgraph_traits< GraphFirst, GraphSecond,\n            VertexIndexMapFirst, VertexIndexMapSecond >\n            SubGraphTraits;\n\n        typedef typename SubGraphTraits::correspondence_map_first_to_second_type\n            CachedCorrespondenceMapFirstToSecond;\n\n        typedef typename SubGraphTraits::correspondence_map_second_to_first_type\n            CachedCorrespondenceMapSecondToFirst;\n\n        typedef std::pair< VertexSizeFirst,\n            std::pair< CachedCorrespondenceMapFirstToSecond,\n                CachedCorrespondenceMapSecondToFirst > >\n            SubGraph;\n\n        typedef std::vector< SubGraph > SubGraphList;\n\n        unique_subgraph_interceptor(const GraphFirst& graph1,\n            const GraphSecond& graph2, const VertexIndexMapFirst vindex_map1,\n            const VertexIndexMapSecond vindex_map2,\n            SubGraphCallback user_callback)\n        : m_graph1(graph1)\n        , m_graph2(graph2)\n        , m_vindex_map1(vindex_map1)\n        , m_vindex_map2(vindex_map2)\n        , m_subgraphs(make_shared< SubGraphList >())\n        , m_user_callback(user_callback)\n        {\n        }\n\n        template < typename CorrespondenceMapFirstToSecond,\n            typename CorrespondenceMapSecondToFirst >\n        bool operator()(\n            CorrespondenceMapFirstToSecond correspondence_map_1_to_2,\n            CorrespondenceMapSecondToFirst correspondence_map_2_to_1,\n            VertexSizeFirst subgraph_size)\n        {\n\n            for (typename SubGraphList::const_iterator subgraph_iter\n                 = m_subgraphs->begin();\n                 subgraph_iter != m_subgraphs->end(); ++subgraph_iter)\n            {\n\n                SubGraph subgraph_cached = *subgraph_iter;\n\n                // Compare subgraph sizes\n                if (subgraph_size != subgraph_cached.first)\n                {\n                    continue;\n                }\n\n                if (!are_property_maps_different(correspondence_map_1_to_2,\n                        subgraph_cached.second.first, m_graph1))\n                {\n\n                    // New subgraph is a duplicate\n                    return (true);\n                }\n            }\n\n            // Subgraph is unique, so make a cached copy\n            CachedCorrespondenceMapFirstToSecond new_subgraph_1_to_2\n                = CachedCorrespondenceMapFirstToSecond(\n                    num_vertices(m_graph1), m_vindex_map1);\n\n            CachedCorrespondenceMapSecondToFirst new_subgraph_2_to_1\n                = CorrespondenceMapSecondToFirst(\n                    num_vertices(m_graph2), m_vindex_map2);\n\n            BGL_FORALL_VERTICES_T(vertex1, m_graph1, GraphFirst)\n            {\n                put(new_subgraph_1_to_2, vertex1,\n                    get(correspondence_map_1_to_2, vertex1));\n            }\n\n            BGL_FORALL_VERTICES_T(vertex2, m_graph2, GraphFirst)\n            {\n                put(new_subgraph_2_to_1, vertex2,\n                    get(correspondence_map_2_to_1, vertex2));\n            }\n\n            m_subgraphs->push_back(std::make_pair(subgraph_size,\n                std::make_pair(new_subgraph_1_to_2, new_subgraph_2_to_1)));\n\n            return (m_user_callback(correspondence_map_1_to_2,\n                correspondence_map_2_to_1, subgraph_size));\n        }\n\n    private:\n        const GraphFirst& m_graph1;\n        const GraphFirst& m_graph2;\n        const VertexIndexMapFirst m_vindex_map1;\n        const VertexIndexMapSecond m_vindex_map2;\n        shared_ptr< SubGraphList > m_subgraphs;\n        SubGraphCallback m_user_callback;\n    };\n\n} // namespace detail\n\n// Enumerates all unique common subgraphs between graph1 and graph2.\n// The user callback is invoked for each unique subgraph as they are\n// discovered.\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs_unique(const GraphFirst& graph1,\n    const GraphSecond& graph2, const VertexIndexMapFirst vindex_map1,\n    const VertexIndexMapSecond vindex_map2,\n    EdgeEquivalencePredicate edges_equivalent,\n    VertexEquivalencePredicate vertices_equivalent,\n    bool only_connected_subgraphs, SubGraphCallback user_callback)\n{\n    detail::unique_subgraph_interceptor< GraphFirst, GraphSecond,\n        VertexIndexMapFirst, VertexIndexMapSecond, SubGraphCallback >\n        unique_callback(\n            graph1, graph2, vindex_map1, vindex_map2, user_callback);\n\n    detail::mcgregor_common_subgraphs_internal_init(graph1, graph2, vindex_map1,\n        vindex_map2, edges_equivalent, vertices_equivalent,\n        only_connected_subgraphs, unique_callback);\n}\n\n// Variant of mcgregor_common_subgraphs_unique with all default\n// parameters.\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs_unique(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback)\n{\n    mcgregor_common_subgraphs_unique(graph1, graph2, get(vertex_index, graph1),\n        get(vertex_index, graph2), always_equivalent(), always_equivalent(),\n        only_connected_subgraphs, user_callback);\n}\n\n// Named parameter variant of mcgregor_common_subgraphs_unique\ntemplate < typename GraphFirst, typename GraphSecond, typename SubGraphCallback,\n    typename Param, typename Tag, typename Rest >\nvoid mcgregor_common_subgraphs_unique(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback,\n    const bgl_named_params< Param, Tag, Rest >& params)\n{\n    mcgregor_common_subgraphs_unique(graph1, graph2,\n        choose_const_pmap(\n            get_param(params, vertex_index1), graph1, vertex_index),\n        choose_const_pmap(\n            get_param(params, vertex_index2), graph2, vertex_index),\n        choose_param(\n            get_param(params, edges_equivalent_t()), always_equivalent()),\n        choose_param(\n            get_param(params, vertices_equivalent_t()), always_equivalent()),\n        only_connected_subgraphs, user_callback);\n}\n\n// ==========================================================================\n\nnamespace detail\n{\n\n    // Binary function object that intercepts subgraphs from\n    // mcgregor_common_subgraphs_internal and maintains a cache of the\n    // largest subgraphs.\n    template < typename GraphFirst, typename GraphSecond,\n        typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n        typename SubGraphCallback >\n    struct maximum_subgraph_interceptor\n    {\n\n        typedef typename graph_traits< GraphFirst >::vertices_size_type\n            VertexSizeFirst;\n\n        typedef mcgregor_common_subgraph_traits< GraphFirst, GraphSecond,\n            VertexIndexMapFirst, VertexIndexMapSecond >\n            SubGraphTraits;\n\n        typedef typename SubGraphTraits::correspondence_map_first_to_second_type\n            CachedCorrespondenceMapFirstToSecond;\n\n        typedef typename SubGraphTraits::correspondence_map_second_to_first_type\n            CachedCorrespondenceMapSecondToFirst;\n\n        typedef std::pair< VertexSizeFirst,\n            std::pair< CachedCorrespondenceMapFirstToSecond,\n                CachedCorrespondenceMapSecondToFirst > >\n            SubGraph;\n\n        typedef std::vector< SubGraph > SubGraphList;\n\n        maximum_subgraph_interceptor(const GraphFirst& graph1,\n            const GraphSecond& graph2, const VertexIndexMapFirst vindex_map1,\n            const VertexIndexMapSecond vindex_map2,\n            SubGraphCallback user_callback)\n        : m_graph1(graph1)\n        , m_graph2(graph2)\n        , m_vindex_map1(vindex_map1)\n        , m_vindex_map2(vindex_map2)\n        , m_subgraphs(make_shared< SubGraphList >())\n        , m_largest_size_so_far(make_shared< VertexSizeFirst >(0))\n        , m_user_callback(user_callback)\n        {\n        }\n\n        template < typename CorrespondenceMapFirstToSecond,\n            typename CorrespondenceMapSecondToFirst >\n        bool operator()(\n            CorrespondenceMapFirstToSecond correspondence_map_1_to_2,\n            CorrespondenceMapSecondToFirst correspondence_map_2_to_1,\n            VertexSizeFirst subgraph_size)\n        {\n\n            if (subgraph_size > *m_largest_size_so_far)\n            {\n                m_subgraphs->clear();\n                *m_largest_size_so_far = subgraph_size;\n            }\n\n            if (subgraph_size == *m_largest_size_so_far)\n            {\n\n                // Make a cached copy\n                CachedCorrespondenceMapFirstToSecond new_subgraph_1_to_2\n                    = CachedCorrespondenceMapFirstToSecond(\n                        num_vertices(m_graph1), m_vindex_map1);\n\n                CachedCorrespondenceMapSecondToFirst new_subgraph_2_to_1\n                    = CachedCorrespondenceMapSecondToFirst(\n                        num_vertices(m_graph2), m_vindex_map2);\n\n                BGL_FORALL_VERTICES_T(vertex1, m_graph1, GraphFirst)\n                {\n                    put(new_subgraph_1_to_2, vertex1,\n                        get(correspondence_map_1_to_2, vertex1));\n                }\n\n                BGL_FORALL_VERTICES_T(vertex2, m_graph2, GraphFirst)\n                {\n                    put(new_subgraph_2_to_1, vertex2,\n                        get(correspondence_map_2_to_1, vertex2));\n                }\n\n                m_subgraphs->push_back(std::make_pair(subgraph_size,\n                    std::make_pair(new_subgraph_1_to_2, new_subgraph_2_to_1)));\n            }\n\n            return (true);\n        }\n\n        void output_subgraphs()\n        {\n            for (typename SubGraphList::const_iterator subgraph_iter\n                 = m_subgraphs->begin();\n                 subgraph_iter != m_subgraphs->end(); ++subgraph_iter)\n            {\n\n                SubGraph subgraph_cached = *subgraph_iter;\n                m_user_callback(subgraph_cached.second.first,\n                    subgraph_cached.second.second, subgraph_cached.first);\n            }\n        }\n\n    private:\n        const GraphFirst& m_graph1;\n        const GraphFirst& m_graph2;\n        const VertexIndexMapFirst m_vindex_map1;\n        const VertexIndexMapSecond m_vindex_map2;\n        shared_ptr< SubGraphList > m_subgraphs;\n        shared_ptr< VertexSizeFirst > m_largest_size_so_far;\n        SubGraphCallback m_user_callback;\n    };\n\n} // namespace detail\n\n// Enumerates the largest common subgraphs found between graph1\n// and graph2.  Note that the ENTIRE search space is explored before\n// user_callback is actually invoked.\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs_maximum(const GraphFirst& graph1,\n    const GraphSecond& graph2, const VertexIndexMapFirst vindex_map1,\n    const VertexIndexMapSecond vindex_map2,\n    EdgeEquivalencePredicate edges_equivalent,\n    VertexEquivalencePredicate vertices_equivalent,\n    bool only_connected_subgraphs, SubGraphCallback user_callback)\n{\n    detail::maximum_subgraph_interceptor< GraphFirst, GraphSecond,\n        VertexIndexMapFirst, VertexIndexMapSecond, SubGraphCallback >\n        max_interceptor(\n            graph1, graph2, vindex_map1, vindex_map2, user_callback);\n\n    detail::mcgregor_common_subgraphs_internal_init(graph1, graph2, vindex_map1,\n        vindex_map2, edges_equivalent, vertices_equivalent,\n        only_connected_subgraphs, max_interceptor);\n\n    // Only output the largest subgraphs\n    max_interceptor.output_subgraphs();\n}\n\n// Variant of mcgregor_common_subgraphs_maximum with all default\n// parameters.\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs_maximum(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback)\n{\n    mcgregor_common_subgraphs_maximum(graph1, graph2, get(vertex_index, graph1),\n        get(vertex_index, graph2), always_equivalent(), always_equivalent(),\n        only_connected_subgraphs, user_callback);\n}\n\n// Named parameter variant of mcgregor_common_subgraphs_maximum\ntemplate < typename GraphFirst, typename GraphSecond, typename SubGraphCallback,\n    typename Param, typename Tag, typename Rest >\nvoid mcgregor_common_subgraphs_maximum(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback,\n    const bgl_named_params< Param, Tag, Rest >& params)\n{\n    mcgregor_common_subgraphs_maximum(graph1, graph2,\n        choose_const_pmap(\n            get_param(params, vertex_index1), graph1, vertex_index),\n        choose_const_pmap(\n            get_param(params, vertex_index2), graph2, vertex_index),\n        choose_param(\n            get_param(params, edges_equivalent_t()), always_equivalent()),\n        choose_param(\n            get_param(params, vertices_equivalent_t()), always_equivalent()),\n        only_connected_subgraphs, user_callback);\n}\n\n// ==========================================================================\n\nnamespace detail\n{\n\n    // Binary function object that intercepts subgraphs from\n    // mcgregor_common_subgraphs_internal and maintains a cache of the\n    // largest, unique subgraphs.\n    template < typename GraphFirst, typename GraphSecond,\n        typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n        typename SubGraphCallback >\n    struct unique_maximum_subgraph_interceptor\n    {\n\n        typedef typename graph_traits< GraphFirst >::vertices_size_type\n            VertexSizeFirst;\n\n        typedef mcgregor_common_subgraph_traits< GraphFirst, GraphSecond,\n            VertexIndexMapFirst, VertexIndexMapSecond >\n            SubGraphTraits;\n\n        typedef typename SubGraphTraits::correspondence_map_first_to_second_type\n            CachedCorrespondenceMapFirstToSecond;\n\n        typedef typename SubGraphTraits::correspondence_map_second_to_first_type\n            CachedCorrespondenceMapSecondToFirst;\n\n        typedef std::pair< VertexSizeFirst,\n            std::pair< CachedCorrespondenceMapFirstToSecond,\n                CachedCorrespondenceMapSecondToFirst > >\n            SubGraph;\n\n        typedef std::vector< SubGraph > SubGraphList;\n\n        unique_maximum_subgraph_interceptor(const GraphFirst& graph1,\n            const GraphSecond& graph2, const VertexIndexMapFirst vindex_map1,\n            const VertexIndexMapSecond vindex_map2,\n            SubGraphCallback user_callback)\n        : m_graph1(graph1)\n        , m_graph2(graph2)\n        , m_vindex_map1(vindex_map1)\n        , m_vindex_map2(vindex_map2)\n        , m_subgraphs(make_shared< SubGraphList >())\n        , m_largest_size_so_far(make_shared< VertexSizeFirst >(0))\n        , m_user_callback(user_callback)\n        {\n        }\n\n        template < typename CorrespondenceMapFirstToSecond,\n            typename CorrespondenceMapSecondToFirst >\n        bool operator()(\n            CorrespondenceMapFirstToSecond correspondence_map_1_to_2,\n            CorrespondenceMapSecondToFirst correspondence_map_2_to_1,\n            VertexSizeFirst subgraph_size)\n        {\n\n            if (subgraph_size > *m_largest_size_so_far)\n            {\n                m_subgraphs->clear();\n                *m_largest_size_so_far = subgraph_size;\n            }\n\n            if (subgraph_size == *m_largest_size_so_far)\n            {\n\n                // Check if subgraph is unique\n                for (typename SubGraphList::const_iterator subgraph_iter\n                     = m_subgraphs->begin();\n                     subgraph_iter != m_subgraphs->end(); ++subgraph_iter)\n                {\n\n                    SubGraph subgraph_cached = *subgraph_iter;\n\n                    if (!are_property_maps_different(correspondence_map_1_to_2,\n                            subgraph_cached.second.first, m_graph1))\n                    {\n\n                        // New subgraph is a duplicate\n                        return (true);\n                    }\n                }\n\n                // Subgraph is unique, so make a cached copy\n                CachedCorrespondenceMapFirstToSecond new_subgraph_1_to_2\n                    = CachedCorrespondenceMapFirstToSecond(\n                        num_vertices(m_graph1), m_vindex_map1);\n\n                CachedCorrespondenceMapSecondToFirst new_subgraph_2_to_1\n                    = CachedCorrespondenceMapSecondToFirst(\n                        num_vertices(m_graph2), m_vindex_map2);\n\n                BGL_FORALL_VERTICES_T(vertex1, m_graph1, GraphFirst)\n                {\n                    put(new_subgraph_1_to_2, vertex1,\n                        get(correspondence_map_1_to_2, vertex1));\n                }\n\n                BGL_FORALL_VERTICES_T(vertex2, m_graph2, GraphFirst)\n                {\n                    put(new_subgraph_2_to_1, vertex2,\n                        get(correspondence_map_2_to_1, vertex2));\n                }\n\n                m_subgraphs->push_back(std::make_pair(subgraph_size,\n                    std::make_pair(new_subgraph_1_to_2, new_subgraph_2_to_1)));\n            }\n\n            return (true);\n        }\n\n        void output_subgraphs()\n        {\n            for (typename SubGraphList::const_iterator subgraph_iter\n                 = m_subgraphs->begin();\n                 subgraph_iter != m_subgraphs->end(); ++subgraph_iter)\n            {\n\n                SubGraph subgraph_cached = *subgraph_iter;\n                m_user_callback(subgraph_cached.second.first,\n                    subgraph_cached.second.second, subgraph_cached.first);\n            }\n        }\n\n    private:\n        const GraphFirst& m_graph1;\n        const GraphFirst& m_graph2;\n        const VertexIndexMapFirst m_vindex_map1;\n        const VertexIndexMapSecond m_vindex_map2;\n        shared_ptr< SubGraphList > m_subgraphs;\n        shared_ptr< VertexSizeFirst > m_largest_size_so_far;\n        SubGraphCallback m_user_callback;\n    };\n\n} // namespace detail\n\n// Enumerates the largest, unique common subgraphs found between\n// graph1 and graph2.  Note that the ENTIRE search space is explored\n// before user_callback is actually invoked.\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename VertexIndexMapFirst, typename VertexIndexMapSecond,\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs_maximum_unique(const GraphFirst& graph1,\n    const GraphSecond& graph2, const VertexIndexMapFirst vindex_map1,\n    const VertexIndexMapSecond vindex_map2,\n    EdgeEquivalencePredicate edges_equivalent,\n    VertexEquivalencePredicate vertices_equivalent,\n    bool only_connected_subgraphs, SubGraphCallback user_callback)\n{\n    detail::unique_maximum_subgraph_interceptor< GraphFirst, GraphSecond,\n        VertexIndexMapFirst, VertexIndexMapSecond, SubGraphCallback >\n        unique_max_interceptor(\n            graph1, graph2, vindex_map1, vindex_map2, user_callback);\n\n    detail::mcgregor_common_subgraphs_internal_init(graph1, graph2, vindex_map1,\n        vindex_map2, edges_equivalent, vertices_equivalent,\n        only_connected_subgraphs, unique_max_interceptor);\n\n    // Only output the largest, unique subgraphs\n    unique_max_interceptor.output_subgraphs();\n}\n\n// Variant of mcgregor_common_subgraphs_maximum_unique with all default\n// parameters\ntemplate < typename GraphFirst, typename GraphSecond,\n    typename SubGraphCallback >\nvoid mcgregor_common_subgraphs_maximum_unique(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback)\n{\n\n    mcgregor_common_subgraphs_maximum_unique(graph1, graph2,\n        get(vertex_index, graph1), get(vertex_index, graph2),\n        always_equivalent(), always_equivalent(), only_connected_subgraphs,\n        user_callback);\n}\n\n// Named parameter variant of\n// mcgregor_common_subgraphs_maximum_unique\ntemplate < typename GraphFirst, typename GraphSecond, typename SubGraphCallback,\n    typename Param, typename Tag, typename Rest >\nvoid mcgregor_common_subgraphs_maximum_unique(const GraphFirst& graph1,\n    const GraphSecond& graph2, bool only_connected_subgraphs,\n    SubGraphCallback user_callback,\n    const bgl_named_params< Param, Tag, Rest >& params)\n{\n    mcgregor_common_subgraphs_maximum_unique(graph1, graph2,\n        choose_const_pmap(\n            get_param(params, vertex_index1), graph1, vertex_index),\n        choose_const_pmap(\n            get_param(params, vertex_index2), graph2, vertex_index),\n        choose_param(\n            get_param(params, edges_equivalent_t()), always_equivalent()),\n        choose_param(\n            get_param(params, vertices_equivalent_t()), always_equivalent()),\n        only_connected_subgraphs, user_callback);\n}\n\n// ==========================================================================\n\n// Fills a membership map (vertex -> bool) using the information\n// present in correspondence_map_1_to_2. Every vertex in a\n// membership map will have a true value only if it is not\n// associated with a null vertex in the correspondence map.\ntemplate < typename GraphSecond, typename GraphFirst,\n    typename CorrespondenceMapFirstToSecond, typename MembershipMapFirst >\nvoid fill_membership_map(const GraphFirst& graph1,\n    const CorrespondenceMapFirstToSecond correspondence_map_1_to_2,\n    MembershipMapFirst membership_map1)\n{\n\n    BGL_FORALL_VERTICES_T(vertex1, graph1, GraphFirst)\n    {\n        put(membership_map1, vertex1,\n            get(correspondence_map_1_to_2, vertex1)\n                != graph_traits< GraphSecond >::null_vertex());\n    }\n}\n\n// Traits associated with a membership map filtered graph.  Provided\n// for convenience to access graph and vertex filter types.\ntemplate < typename Graph, typename MembershipMap >\nstruct membership_filtered_graph_traits\n{\n    typedef property_map_filter< MembershipMap > vertex_filter_type;\n    typedef filtered_graph< Graph, keep_all, vertex_filter_type > graph_type;\n};\n\n// Returns a filtered sub-graph of graph whose edge and vertex\n// inclusion is dictated by membership_map.\ntemplate < typename Graph, typename MembershipMap >\ntypename membership_filtered_graph_traits< Graph, MembershipMap >::graph_type\nmake_membership_filtered_graph(\n    const Graph& graph, MembershipMap& membership_map)\n{\n\n    typedef membership_filtered_graph_traits< Graph, MembershipMap > MFGTraits;\n    typedef typename MFGTraits::graph_type MembershipFilteredGraph;\n\n    typename MFGTraits::vertex_filter_type v_filter(membership_map);\n\n    return (MembershipFilteredGraph(graph, keep_all(), v_filter));\n}\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_MCGREGOR_COMMON_SUBGRAPHS_HPP\n", "meta": {"hexsha": "9c2b4b980d1dc1a96ca6cd948b9eea62b56d2ad1", "size": 43470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/mcgregor_common_subgraphs.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/mcgregor_common_subgraphs.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/mcgregor_common_subgraphs.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": 38.8819320215, "max_line_length": 80, "alphanum_fraction": 0.6555325512, "num_tokens": 8921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.028436033662373735, "lm_q1q2_score": 0.013662907863023115}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/BundleAdjustment/ControlNetworkLoader.h>\n#include <vw/Stereo/StereoModel.h>\n\nusing namespace vw;\nusing namespace vw::ba;\n\n#include <boost/filesystem/fstream.hpp>\n\nnamespace fs = boost::filesystem;\n\nstruct ContainsEqualIP {\n  ip::InterestPoint& m_compare;\n  ContainsEqualIP( ip::InterestPoint& comp ) : m_compare(comp) {}\n\n  bool operator()( boost::shared_ptr<IPFeature> in ) {\n    if (  m_compare.x == in->m_ip.x &&\n          m_compare.y == in->m_ip.y )\n      return true;\n    return false;\n  }\n};\n\n// Utility for checking that the point is BA safe\nvoid safe_measurement( ip::InterestPoint& ip ) {\n  if ( ip.scale <= 0 ) ip.scale = 10;\n}\n\nvoid vw::ba::triangulate_control_point( ControlPoint& cp,\n                                        std::vector<boost::shared_ptr<camera::CameraModel> > const& camera_models,\n                                        double const& minimum_angle ) {\n  Vector3 position_sum;\n  double error = 0, error_sum = 0;\n  size_t count = 0;\n\n  // 4.1.) Building a listing of triangulation\n  for ( size_t j = 0, k = 1; k < cp.size(); j++, k++ ) {\n    // Make sure camera centers are not equal\n    size_t j_cam_id = cp[j].image_id();\n    size_t k_cam_id = cp[k].image_id();\n    if ( norm_2( camera_models[j_cam_id]->camera_center( cp[j].position() ) -\n                 camera_models[k_cam_id]->camera_center( cp[k].position() ) ) > 1e-6 ) {\n\n      try {\n        stereo::StereoModel sm( camera_models[ j_cam_id ].get(),\n                                camera_models[ k_cam_id ].get() );\n\n        if ( sm.convergence_angle( cp[j].position(),\n                                   cp[k].position() ) >\n             minimum_angle ) {\n\t  count++;\n\t  position_sum += sm( cp[j].position(), cp[k].position(), error );\n          error_sum += error;\n        }\n      } catch ( const camera::PixelToRayErr& ) { /* Just let it go */ }\n    }\n  }\n\n  // 4.2.) Summing, Averaging, and Storing\n  if ( !count ) {\n    vw_out(WarningMessage,\"ba\") << \"Unable to triangulation position for point!\\n\";\n    // At the very least we can provide a point that is some\n    // distance out from the camera center and is in the 'general'\n    // area.\n    size_t j = cp[0].image_id();\n    try {\n      cp.set_position( camera_models[j]->camera_center(cp[0].position()) +\n                       camera_models[j]->pixel_to_vector(cp[0].position())*10 );\n    } catch ( const camera::PixelToRayErr& ) {\n      cp.set_position( camera_models[j]->camera_center(cp[0].position()) +\n                       camera_models[j]->camera_pose(cp[0].position()).rotate(Vector3(0,0,10)) );\n    }\n  } else {\n    error_sum /= double(count);\n    cp.set_position( position_sum / double(count) );\n  }\n}\n\nvoid vw::ba::build_control_network( ba::ControlNetwork& cnet,\n                                     std::vector<boost::shared_ptr<camera::CameraModel> > const& camera_models,\n                                     std::vector<std::string> const& image_files,\n                                     size_t min_matches,\n                                     std::vector<std::string> const& directories ) {\n  cnet.clear();\n\n  // We can't guarantee that image_files is sorted, so we make a\n  // std::map to give ourselves a sorted list and access to a binary\n  // search.\n  std::map<std::string,size_t> image_prefix_map;\n  size_t count = 0;\n  ba::CameraRelationNetwork<ba::IPFeature> crn;\n  BOOST_FOREACH( std::string const& file, image_files ) {\n    fs::path file_path(file);\n    image_prefix_map[file_path.replace_extension().string()] = count;\n    crn.add_node( ba::CameraNode<ba::IPFeature>( count,\n                                                 file_path.stem() ) );\n    count++;\n  }\n\n  // Searching through the directories available to us.\n  size_t num_load_rejected = 0, num_loaded = 0;\n  BOOST_FOREACH( std::string const& directory, directories ) {\n    vw_out(VerboseDebugMessage,\"ba\") << \"\\tOpening directory \\\"\"\n                                     << directory << \"\\\".\\n\";\n    fs::directory_iterator end_itr;\n    for ( fs::directory_iterator obj( directory ); obj != end_itr; ++obj ) {\n\n      // Skip if not a file\n      if ( !fs::is_regular_file( obj->status() ) ) continue;\n      // Skip if not a match file\n      if ( obj->path().extension() != \".match\" ) continue;\n\n      // Pull out the prefixes that made up that match file\n      std::string match_base = obj->path().stem();\n      size_t split_pt = match_base.find(\"__\");\n      if ( split_pt == std::string::npos ) continue;\n      std::string prefix1 = match_base.substr(0,split_pt);\n      std::string prefix2 = match_base.substr(split_pt+2,match_base.size()-split_pt-2);\n\n      // Extract the image indices that correspond to image prefixes.\n      typedef std::map<std::string,size_t>::iterator MapIterator;\n      MapIterator it1 = image_prefix_map.find( prefix1 );\n      MapIterator it2 = image_prefix_map.find( prefix2 );\n      if ( it1 == image_prefix_map.end() ||\n           it2 == image_prefix_map.end() ) continue;\n\n      // Actually read in the file as it seems we've found something correct\n      std::vector<ip::InterestPoint> ip1, ip2;\n      ip::read_binary_match_file( obj->string(), ip1, ip2 );\n      if ( ip1.size() < min_matches ) {\n        vw_out(VerboseDebugMessage,\"ba\") << \"\\t\" << obj->string() << \"    \"\n                                         << it1->second << \" <-> \" << it2->second << \" : \"\n                                         << ip1.size() << \" matches. [rejected]\\n\";\n        num_load_rejected += ip1.size();\n      } else {\n        vw_out(VerboseDebugMessage,\"ba\") << \"\\t\" << obj->string() << \"    \"\n                                         << it1->second << \" <-> \" << it2->second << \" : \"\n                                         << ip1.size() << \" matches.\\n\";\n        num_loaded += ip1.size();\n\n        // Remove descriptors from interest points and correct scale\n        std::for_each( ip1.begin(), ip1.end(), ip::remove_descriptor );\n        std::for_each( ip2.begin(), ip2.end(), ip::remove_descriptor );\n        std::for_each( ip1.begin(), ip1.end(), safe_measurement );\n        std::for_each( ip2.begin(), ip2.end(), safe_measurement );\n\n        typedef boost::shared_ptr< ba::IPFeature > f_ptr;\n        typedef std::list< f_ptr >::iterator f_itr;\n\n        // Checking to see if features already exist, adding if they\n        // don't, then linking them.\n        for ( size_t k = 0; k < ip1.size(); k++ ) {\n          f_itr ipfeature1 = std::find_if( crn[it1->second].begin(),\n                                           crn[it1->second].end(),\n                                           ContainsEqualIP( ip1[k] ) );\n          f_itr ipfeature2 = std::find_if( crn[it2->second].begin(),\n                                           crn[it2->second].end(),\n                                           ContainsEqualIP( ip2[k] ) );\n          if ( ipfeature1 == crn[it1->second].end() ) {\n            crn[it1->second].relations.push_front( f_ptr( new ba::IPFeature( ip1[k], it1->second ) ) );\n            ipfeature1 = crn[it1->second].begin();\n          }\n          if ( ipfeature2 == crn[it2->second].end() ) {\n            crn[it2->second].relations.push_front( f_ptr( new ba::IPFeature( ip2[k], it2->second ) ) );\n            ipfeature2 = crn[it2->second].begin();\n          }\n\n          // Doubly linking\n          (*ipfeature1)->connection( *ipfeature2, false );\n          (*ipfeature2)->connection( *ipfeature1, false );\n        }\n      }\n    }\n  } // end search through directories\n  if ( num_load_rejected != 0 ) {\n    vw_out(WarningMessage,\"ba\") << \"\\tDidn't load \" << num_load_rejected\n                                << \" matches due to inadequacy.\\n\";\n    vw_out(WarningMessage,\"ba\") << \"\\tLoaded \" << num_loaded << \" matches.\\n\";\n  }\n\n  // Building control network\n  crn.write_controlnetwork( cnet );\n\n  // Triangulating Positions\n  {\n    TerminalProgressCallback progress(\"ba\", \"Triangulating:\");\n    progress.report_progress(0);\n    double inc_prog = 1.0/double(cnet.size());\n    double min_angle = 5.0*M_PI/180.0;\n    BOOST_FOREACH( ba::ControlPoint& cpoint, cnet ) {\n      progress.report_incremental_progress(inc_prog );\n      ba::triangulate_control_point( cpoint, camera_models, min_angle );\n    }\n    progress.report_finished();\n  }\n}\n", "meta": {"hexsha": "9a9dd65d2b9a1283ec141d9e8dfb15c7f71047d6", "size": 8432, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/BundleAdjustment/ControlNetworkLoader.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/BundleAdjustment/ControlNetworkLoader.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/BundleAdjustment/ControlNetworkLoader.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 41.5369458128, "max_line_length": 114, "alphanum_fraction": 0.5748339658, "num_tokens": 2088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.03514484602182299, "lm_q1q2_score": 0.013657921207592849}}
{"text": "/**\n *  This file is part of dvo.\n *\n *  Copyright 2012 Christian Kerl <christian.kerl@in.tum.de> (Technical University of Munich)\n *  For more information see <http://vision.in.tum.de/data/software/dvo>.\n *\n *  dvo 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 *  dvo 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 dvo.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <iomanip>\n\n#include <dvo/dense_tracking.h>\n#include <dvo/dense_tracking_impl.h>\n\n#include <assert.h>\n#include <sophus/se3.hpp>\n\n#include <Eigen/Core>\n\n#include <dvo/core/datatypes.h>\n#include <dvo/core/point_selection_predicates.h>\n#include <dvo/util/revertable.h>\n#include <dvo/util/stopwatch.h>\n#include <dvo/util/id_generator.h>\n#include <dvo/util/histogram.h>\n//#include <dvo/visualization/visualizer.h>\n\nnamespace dvo\n{\n\nusing namespace dvo::core;\nusing namespace dvo::util;\n\nconst DenseTracker::Config& DenseTracker::getDefaultConfig()\n{\n  static Config defaultConfig;\n\n  return defaultConfig;\n}\n\nstatic const Eigen::IOFormat YamlArrayFmt(Eigen::FullPrecision, Eigen::DontAlignCols, \",\", \",\", \"\", \"\", \"[\", \"]\");\n\nDenseTracker::DenseTracker(const Config& config) :\n    itctx_(cfg),\n    weight_calculation_(),\n    selection_predicate_(),\n    reference_selection_(selection_predicate_)\n{\n  configure(config);\n}\n\nDenseTracker::DenseTracker(const DenseTracker& other) :\n  itctx_(cfg),\n  weight_calculation_(),\n  selection_predicate_(),\n  reference_selection_(selection_predicate_)\n{\n  configure(other.configuration());\n}\n\nvoid DenseTracker::configure(const Config& config)\n{\n  assert(config.IsSane());\n\n  cfg = config;\n\n  selection_predicate_.intensity_threshold = cfg.IntensityDerivativeThreshold;\n  selection_predicate_.depth_threshold = cfg.DepthDerivativeThreshold;\n\n  if(cfg.UseWeighting)\n  {\n    weight_calculation_\n      .scaleEstimator(ScaleEstimators::get(cfg.ScaleEstimatorType))\n      .scaleEstimator()->configure(cfg.ScaleEstimatorParam);\n\n    weight_calculation_\n      .influenceFunction(InfluenceFunctions::get(cfg.InfluenceFuntionType))\n      .influenceFunction()->configure(cfg.InfluenceFunctionParam);\n  }\n  else\n  {\n    weight_calculation_\n      .scaleEstimator(ScaleEstimators::get(ScaleEstimators::Unit))\n      .influenceFunction(InfluenceFunctions::get(InfluenceFunctions::Unit));\n  }\n}\n\nbool DenseTracker::match(RgbdImagePyramid& reference, RgbdImagePyramid& current, Eigen::Affine3d& transformation)\n{\n  Result result;\n  result.Transformation = transformation;\n\n  bool success = match(reference, current, result);\n\n  transformation = result.Transformation;\n\n  return success;\n}\n\nbool DenseTracker::match(dvo::core::PointSelection& reference, RgbdImagePyramid& current, Eigen::Affine3d& transformation)\n{\n  Result result;\n  result.Transformation = transformation;\n\n  bool success = match(reference, current, result);\n\n  transformation = result.Transformation;\n\n  return success;\n}\n\nbool DenseTracker::match(dvo::core::RgbdImagePyramid& reference, dvo::core::RgbdImagePyramid& current, dvo::DenseTracker::Result& result)\n{\n  reference.compute(cfg.getNumLevels());\n  reference_selection_.setRgbdImagePyramid(reference);\n\n  return match(reference_selection_, current, result);\n}\n\nbool DenseTracker::match(dvo::core::PointSelection& reference, dvo::core::RgbdImagePyramid& current, dvo::DenseTracker::Result& result)\n{\n  current.compute(cfg.getNumLevels());\n\n  bool success = true;\n\n  if(cfg.UseInitialEstimate)\n  {\n    assert(!result.isNaN() && \"Provided initialization is NaN!\");\n  }\n  else\n  {\n    result.setIdentity();\n  }\n\n  // our first increment is the given guess\n  Sophus::SE3d inc(result.Transformation.rotation(), result.Transformation.translation());\n\n  Revertable<Sophus::SE3d> initial(inc);\n  Revertable<Sophus::SE3d> estimate;\n\n  bool accept = true;\n\n  //static stopwatch_collection sw_level(5, \"l\", 100);\n  //static stopwatch_collection sw_it(5, \"it@l\", 500);\n  //static stopwatch_collection sw_error(5, \"err@l\", 500);\n  //static stopwatch_collection sw_linsys(5, \"linsys@l\", 500);\n  //static stopwatch_collection sw_prep(5, \"prep@l\", 100);\n\n  if(points_error.size() < reference.getMaximumNumberOfPoints(cfg.LastLevel))\n    points_error.resize(reference.getMaximumNumberOfPoints(cfg.LastLevel));\n  if(residuals.size() < reference.getMaximumNumberOfPoints(cfg.LastLevel))\n    residuals.resize(reference.getMaximumNumberOfPoints(cfg.LastLevel));\n  if(weights.size() < reference.getMaximumNumberOfPoints(cfg.LastLevel))\n    weights.resize(reference.getMaximumNumberOfPoints(cfg.LastLevel));\n\n  std::vector<uint8_t> valid_residuals;\n\n  bool debug = false;\n  if(debug)\n  {\n    reference.debug(true);\n    valid_residuals.resize(reference.getMaximumNumberOfPoints(cfg.LastLevel));\n  }\n  /*\n  std::stringstream name;\n  name << std::setiosflags(std::ios::fixed) << std::setprecision(2) << current.timestamp() << \"_error.avi\";\n\n  cv::Size s = reference.getRgbdImagePyramid().level(size_t(cfg.LastLevel)).intensity.size();\n  cv::Mat video_frame(s.height, s.width * 2, CV_32FC1), video_frame_u8;\n  cv::VideoWriter vw(name.str(), CV_FOURCC('P','I','M','1'), 30, video_frame.size(), false);\n  float rgb_max = 0.0;\n  float depth_max = 0.0;\n\n  std::stringstream name1;\n  name1 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << current.timestamp() << \"_ref.png\";\n\n  cv::imwrite(name1.str(), current.level(0).rgb);\n\n  std::stringstream name2;\n  name2 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << current.timestamp() << \"_cur.png\";\n\n  cv::imwrite(name2.str(), reference.getRgbdImagePyramid().level(0).rgb);\n  */\n  Eigen::Vector2f mean;\n  mean.setZero();\n  Eigen::Matrix2f /*first_precision,*/ precision;\n  precision.setZero();\n\n  for(itctx_.Level = cfg.FirstLevel; itctx_.Level >= cfg.LastLevel; --itctx_.Level)\n  {\n    result.Statistics.Levels.push_back(LevelStats());\n    LevelStats& level_stats = result.Statistics.Levels.back();\n\n    mean.setZero();\n    precision.setZero();\n\n    // reset error after every pyramid level? yes because errors from different levels are not comparable\n    itctx_.Iteration = 0;\n    itctx_.Error = std::numeric_limits<double>::max();\n\n    RgbdImage& cur = current.level(itctx_.Level);\n    const IntrinsicMatrix& K = cur.camera().intrinsics();\n\n    Vector8f wcur, wref;\n    // i z idx idy zdx zdy\n    float wcur_id = 0.5f, wref_id = 0.5f, wcur_zd = 1.0f, wref_zd = 0.0f;\n\n    wcur <<  1.0f / 255.0f,  1.0f, wcur_id * K.fx() / 255.0f, wcur_id * K.fy() / 255.0f, wcur_zd * K.fx(), wcur_zd * K.fy(), 0.0f, 0.0f;\n    wref << -1.0f / 255.0f, -1.0f, wref_id * K.fx() / 255.0f, wref_id * K.fy() / 255.0f, wref_zd * K.fx(), wref_zd * K.fy(), 0.0f, 0.0f;\n\n//    sw_prep[itctx_.Level].start();\n\n\n    PointSelection::PointIterator first_point, last_point;\n    reference.select(itctx_.Level, first_point, last_point);\n    cur.buildAccelerationStructure();\n\n    level_stats.Id = itctx_.Level;\n    level_stats.MaxValidPixels = reference.getMaximumNumberOfPoints(itctx_.Level);\n    level_stats.ValidPixels = last_point - first_point;\n\n//    sw_prep[itctx_.Level].stopAndPrint();\n\n    NormalEquationsLeastSquares ls;\n    Matrix6d A;\n    Vector6d x, b;\n    x = inc.log();\n\n    ComputeResidualsResult compute_residuals_result;\n    compute_residuals_result.first_point_error = points_error.begin();\n    compute_residuals_result.first_residual = residuals.begin();\n    compute_residuals_result.first_valid_flag = valid_residuals.begin();\n\n\n//    sw_level[itctx_.Level].start();\n    do\n    {\n      level_stats.Iterations.push_back(IterationStats());\n      IterationStats& iteration_stats = level_stats.Iterations.back();\n      iteration_stats.Id = itctx_.Iteration;\n\n//      sw_it[itctx_.Level].start();\n\n      double total_error = 0.0f;\n//      sw_error[itctx_.Level].start();\n      Eigen::Affine3f transformf;\n\n        inc = Sophus::SE3d::exp(x);\n        initial.update() = inc.inverse() * initial();\n        estimate.update() = inc * estimate();\n\n        transformf = estimate().matrix().cast<float>();\n\n        if(debug)\n        {\n          dvo::core::computeResidualsAndValidFlagsSse(first_point, last_point, cur, K, transformf, wref, wcur, compute_residuals_result);\n        }\n        else\n        {\n          dvo::core::computeResidualsSse(first_point, last_point, cur, K, transformf, wref, wcur, compute_residuals_result);\n        }\n        size_t n = (compute_residuals_result.last_residual - compute_residuals_result.first_residual);\n        iteration_stats.ValidConstraints = n;\n\n        if(n < 6)\n        {\n          initial.revert();\n          estimate.revert();\n\n          level_stats.TerminationCriterion = TerminationCriteria::TooFewConstraints;\n\n          break;\n        }\n\n        if(itctx_.IsFirstIterationOnLevel())\n        {\n          std::fill(weights.begin(), weights.begin() + n, 1.0f);\n        }\n        else\n        {\n          dvo::core::computeWeightsSse(compute_residuals_result.first_residual, compute_residuals_result.last_residual, weights.begin(), mean, precision);\n        }\n\n        precision = dvo::core::computeScaleSse(compute_residuals_result.first_residual, compute_residuals_result.last_residual, weights.begin(), mean).inverse();\n\n        float ll = computeCompleteDataLogLikelihood(compute_residuals_result.first_residual, compute_residuals_result.last_residual, weights.begin(), mean, precision);\n\n        iteration_stats.TDistributionLogLikelihood = -ll;\n        iteration_stats.TDistributionMean = mean.cast<double>();\n        iteration_stats.TDistributionPrecision = precision.cast<double>();\n        iteration_stats.PriorLogLikelihood = cfg.Mu * initial().log().squaredNorm();\n\n        total_error = -ll;//iteration_stats.TDistributionLogLikelihood + iteration_stats.PriorLogLikelihood;\n\n        itctx_.LastError = itctx_.Error;\n        itctx_.Error = total_error;\n\n//      sw_error[itctx_.Level].stopAndPrint();\n\n      // accept the last increment?\n      accept = itctx_.Error < itctx_.LastError;\n\n      if(!accept)\n      {\n        initial.revert();\n        estimate.revert();\n\n        level_stats.TerminationCriterion = TerminationCriteria::LogLikelihoodDecreased;\n\n        break;\n      }\n\n      // now build equation system\n//      sw_linsys[itctx_.Level].start();\n\n      WeightVectorType::iterator w_it = weights.begin();\n\n      Matrix2x6 J, Jw;\n      Eigen::Vector2f Ji;\n      Vector6 Jz;\n      ls.initialize(1);\n      for(PointIterator e_it = compute_residuals_result.first_point_error; e_it != compute_residuals_result.last_point_error; ++e_it, ++w_it)\n      {\n        computeJacobianOfProjectionAndTransformation(e_it->getPointVec4f(), Jw);\n        compute3rdRowOfJacobianOfTransformation(e_it->getPointVec4f(), Jz);\n\n        J.row(0) = e_it->getIntensityDerivativeVec2f().transpose() * Jw;\n        J.row(1) = e_it->getDepthDerivativeVec2f().transpose() * Jw - Jz.transpose();\n\n        ls.update(J, e_it->getIntensityAndDepthVec2f(), (*w_it) * precision);\n      }\n      ls.finish();\n\n      A = ls.A.cast<double>() + cfg.Mu * Matrix6d::Identity();\n      b = ls.b.cast<double>() + cfg.Mu * initial().log();\n      x = A.ldlt().solve(b);\n\n//      sw_linsys[itctx_.Level].stopAndPrint();\n\n      iteration_stats.EstimateIncrement = x;\n      iteration_stats.EstimateInformation = A;\n\n      itctx_.Iteration++;\n//      sw_it[itctx_.Level].stopAndPrint();\n    }\n    while(accept && x.lpNorm<Eigen::Infinity>() > cfg.Precision && !itctx_.IterationsExceeded());\n\n    if(x.lpNorm<Eigen::Infinity>() <= cfg.Precision)\n      level_stats.TerminationCriterion = TerminationCriteria::IncrementTooSmall;\n\n    if(itctx_.IterationsExceeded())\n      level_stats.TerminationCriterion = TerminationCriteria::IterationsExceeded;\n\n//    sw_level[itctx_.Level].stopAndPrint();\n  }\n\n  LevelStats& last_level = result.Statistics.Levels.back();\n  IterationStats& last_iteration = last_level.TerminationCriterion != TerminationCriteria::LogLikelihoodDecreased ? last_level.Iterations[last_level.Iterations.size() - 1] : last_level.Iterations[last_level.Iterations.size() - 2];\n\n  result.Transformation = estimate().inverse().matrix();\n  result.Information = last_iteration.EstimateInformation * 0.008 * 0.008;\n  result.LogLikelihood = last_iteration.TDistributionLogLikelihood + last_iteration.PriorLogLikelihood;\n\n  return success;\n}\n\ncv::Mat DenseTracker::computeIntensityErrorImage(dvo::core::RgbdImagePyramid& reference, dvo::core::RgbdImagePyramid& current, const dvo::core::AffineTransformd& transformation, size_t level)\n{\n  reference.compute(level + 1);\n  current.compute(level + 1);\n  reference_selection_.setRgbdImagePyramid(reference);\n  reference_selection_.debug(true);\n\n  std::vector<uint8_t> valid_residuals;\n\n  if(points_error.size() < reference_selection_.getMaximumNumberOfPoints(level))\n    points_error.resize(reference_selection_.getMaximumNumberOfPoints(level));\n  if(residuals.size() < reference_selection_.getMaximumNumberOfPoints(level))\n    residuals.resize(reference_selection_.getMaximumNumberOfPoints(level));\n\n  valid_residuals.resize(reference_selection_.getMaximumNumberOfPoints(level));\n\n  PointSelection::PointIterator first_point, last_point;\n  reference_selection_.select(level, first_point, last_point);\n\n  RgbdImage& cur = current.level(level);\n  cur.buildAccelerationStructure();\n  const IntrinsicMatrix& K = cur.camera().intrinsics();\n\n  Vector8f wcur, wref;\n  // i z idx idy zdx zdy\n  float wcur_id = 0.5f, wref_id = 0.5f, wcur_zd = 1.0f, wref_zd = 0.0f;\n\n  wcur <<  1.0f / 255.0f,  1.0f, wcur_id * K.fx() / 255.0f, wcur_id * K.fy() / 255.0f, wcur_zd * K.fx(), wcur_zd * K.fy(), 0.0f, 0.0f;\n  wref << -1.0f / 255.0f, -1.0f, wref_id * K.fx() / 255.0f, wref_id * K.fy() / 255.0f, wref_zd * K.fx(), wref_zd * K.fy(), 0.0f, 0.0f;\n\n  ComputeResidualsResult compute_residuals_result;\n  compute_residuals_result.first_point_error = points_error.begin();\n  compute_residuals_result.first_residual = residuals.begin();\n  compute_residuals_result.first_valid_flag = valid_residuals.begin();\n\n  dvo::core::computeResidualsAndValidFlagsSse(first_point, last_point, cur, K, transformation.cast<float>(), wref, wcur, compute_residuals_result);\n\n  cv::Mat result = cv::Mat::zeros(reference.level(level).intensity.size(), CV_32FC1), debug_idx;\n\n  reference_selection_.getDebugIndex(level, debug_idx);\n\n  uint8_t *valid_pixel_it = debug_idx.ptr<uint8_t>();\n  ValidFlagIterator valid_residual_it = compute_residuals_result.first_valid_flag;\n  ResidualIterator residual_it = compute_residuals_result.first_residual;\n\n  float *result_it = result.ptr<float>();\n  float *result_end = result_it + result.total();\n\n  for(; result_it != result_end; ++result_it)\n  {\n    if(*valid_pixel_it == 1)\n    {\n      if(*valid_residual_it == 1)\n      {\n        *result_it = std::abs(residual_it->coeff(0));\n\n        ++residual_it;\n      }\n      ++valid_residual_it;\n    }\n    ++valid_pixel_it;\n  }\n\n  reference_selection_.debug(false);\n\n  return result;\n}\n\n\n// jacobian computation\ninline void DenseTracker::computeJacobianOfProjectionAndTransformation(const Vector4& p, Matrix2x6& j)\n{\n  NumType z = 1.0f / p(2);\n  NumType z_sqr = 1.0f / (p(2) * p(2));\n\n  j(0, 0) =  z;\n  j(0, 1) =  0.0f;\n  j(0, 2) = -p(0) * z_sqr;\n  j(0, 3) = j(0, 2) * p(1);//j(0, 3) = -p(0) * p(1) * z_sqr;\n  j(0, 4) = 1.0f - j(0, 2) * p(0);//j(0, 4) =  (1.0 + p(0) * p(0) * z_sqr);\n  j(0, 5) = -p(1) * z;\n\n  j(1, 0) =  0.0f;\n  j(1, 1) =  z;\n  j(1, 2) = -p(1) * z_sqr;\n  j(1, 3) = -1.0f + j(1, 2) * p(1); //j(1, 3) = -(1.0 + p(1) * p(1) * z_sqr);\n  j(1, 4) = -j(0, 3); //j(1, 4) =  p(0) * p(1) * z_sqr;\n  j(1, 5) =  p(0) * z;\n}\n\ninline void DenseTracker::compute3rdRowOfJacobianOfTransformation(const Vector4& p, Vector6& j)\n{\n  j(0) = 0.0;\n  j(1) = 0.0;\n  j(2) = 1.0;\n  j(3) = p(1);\n  j(4) = -p(0);\n  j(5) = 0.0;\n}\n\n} /* namespace dvo */\n", "meta": {"hexsha": "e01017b2c6a9806afe19860450175e7778bdf7c0", "size": 16153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dvo_core/src/dense_tracking.cpp", "max_stars_repo_name": "uf-reef-avl/dvo_slam", "max_stars_repo_head_hexsha": "1328904fe2039739f03891f28ebde06f0a5174b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 566.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:34:55.000Z", "max_issues_repo_path": "dvo_core/src/dense_tracking.cpp", "max_issues_repo_name": "uf-reef-avl/dvo_slam", "max_issues_repo_head_hexsha": "1328904fe2039739f03891f28ebde06f0a5174b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T08:03:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T16:14:35.000Z", "max_forks_repo_path": "dvo_core/src/dense_tracking.cpp", "max_forks_repo_name": "uf-reef-avl/dvo_slam", "max_forks_repo_head_hexsha": "1328904fe2039739f03891f28ebde06f0a5174b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 291.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T23:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T13:26:17.000Z", "avg_line_length": 33.7223382046, "max_line_length": 230, "alphanum_fraction": 0.6983842011, "num_tokens": 4472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.028870904021761658, "lm_q1q2_score": 0.013646799286181135}}
{"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:47:55\n\n#ifndef NUHMSSM_SLHA_IO_H\n#define NUHMSSM_SLHA_IO_H\n\n#include \"NUHMSSM_two_scale_model_slha.hpp\"\n#include \"NUHMSSM_info.hpp\"\n#include \"NUHMSSM_observables.hpp\"\n#include \"NUHMSSM_physical.hpp\"\n#include \"slha_io.hpp\"\n#include \"ckm.hpp\"\n#include \"ew_input.hpp\"\n#include \"lowe.h\"\n\n#include <Eigen/Core>\n#include <string>\n#include <utility>\n\n#define Pole(p) physical.p\n#define PHYSICAL(p) model.get_physical().p\n#define PHYSICAL_SLHA(p) model.get_physical_slha().p\n#define LOCALPHYSICAL(p) physical.p\n#define MODEL model\n#define MODELPARAMETER(p) model.get_##p()\n#define OBSERVABLES observables\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define SCALES(p) scales.p\n\nnamespace flexiblesusy {\n\nstruct NUHMSSM_input_parameters;\nclass Spectrum_generator_settings;\n\nstruct NUHMSSM_scales {\n   NUHMSSM_scales() : HighScale(0.), SUSYScale(0.), LowScale(0.) {}\n   double HighScale, SUSYScale, LowScale;\n};\n\nclass NUHMSSM_slha_io {\npublic:\n   NUHMSSM_slha_io();\n   ~NUHMSSM_slha_io() {}\n\n   void clear();\n\n   void fill(softsusy::QedQcd& qedqcd) const { slha_io.fill(qedqcd); }\n   void fill(NUHMSSM_input_parameters&) const;\n   void fill(NUHMSSM_mass_eigenstates&) const;\n   template <class T> void fill(NUHMSSM_slha<T>&) const;\n   void fill(Physical_input&) const;\n   void fill(Spectrum_generator_settings&) const;\n   double get_parameter_output_scale() const;\n   const SLHA_io& get_slha_io() const { return slha_io; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   void set_block(const std::string& str, SLHA_io::Position position = SLHA_io::back) { slha_io.set_block(str, position); }\n   void set_blocks(const std::vector<std::string>& vec, SLHA_io::Position position = SLHA_io::back) { slha_io.set_blocks(vec, position); }\n   void set_extpar(const NUHMSSM_input_parameters&);\n   template <class T> void set_extra(const NUHMSSM_slha<T>&, const NUHMSSM_scales&, const NUHMSSM_observables&);\n   void set_minpar(const NUHMSSM_input_parameters&);\n   void set_sminputs(const softsusy::QedQcd&);\n   template <class T> void set_spectrum(const NUHMSSM_slha<T>&);\n   template <class T> void set_spectrum(const NUHMSSM<T>&);\n   void set_spinfo(const Problems<NUHMSSM_info::NUMBER_OF_PARTICLES>&);\n   void set_print_imaginary_parts_of_majorana_mixings(bool);\n   void write_to_file(const std::string&);\n   void write_to_stream(std::ostream& ostr = std::cout) { slha_io.write_to_stream(ostr); }\n\n   static void fill_minpar_tuple(NUHMSSM_input_parameters&, int, double);\n   static void fill_extpar_tuple(NUHMSSM_input_parameters&, int, double);\n\n   template <class T>\n   static void fill_slhaea(SLHAea::Coll&, const NUHMSSM_slha<T>&, const softsusy::QedQcd&, const NUHMSSM_scales&, const NUHMSSM_observables&);\n\n   template <class T>\n   static SLHAea::Coll fill_slhaea(const NUHMSSM_slha<T>&, const softsusy::QedQcd&, const NUHMSSM_scales&, const NUHMSSM_observables&);\n\nprivate:\n   SLHA_io slha_io; ///< SLHA io class\n   bool print_imaginary_parts_of_majorana_mixings;\n   static unsigned const NUMBER_OF_DRBAR_BLOCKS = 14;\n   static char const * const drbar_blocks[NUMBER_OF_DRBAR_BLOCKS];\n\n   void set_mass(const NUHMSSM_physical&, bool);\n   void set_mixing_matrices(const NUHMSSM_physical&, bool);\n   template <class T> void set_model_parameters(const NUHMSSM_slha<T>&);\n   void set_ckm(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   void set_pmns(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   double read_scale() const;\n   void fill_drbar_parameters(NUHMSSM_mass_eigenstates&) const;\n   void fill_physical(NUHMSSM_physical&) const;\n};\n\n/**\n * Reads DR-bar parameters, pole masses and mixing matrices from a\n * SLHA output file.\n */\ntemplate <class T>\nvoid NUHMSSM_slha_io::fill(NUHMSSM_slha<T>& model) const\n{\n   fill(static_cast<NUHMSSM_mass_eigenstates&>(model));\n   fill_physical(model.get_physical_slha());\n}\n\ntemplate <class T>\nvoid NUHMSSM_slha_io::fill_slhaea(\n   SLHAea::Coll& slhaea, const NUHMSSM_slha<T>& model,\n   const softsusy::QedQcd& qedqcd, const NUHMSSM_scales& scales,\n   const NUHMSSM_observables& observables)\n{\n   NUHMSSM_slha_io slha_io;\n   const NUHMSSM_input_parameters& input = model.get_input();\n   const Problems<NUHMSSM_info::NUMBER_OF_PARTICLES>& problems\n      = model.get_problems();\n   const bool error = problems.have_problem();\n\n   slha_io.set_spinfo(problems);\n   slha_io.set_sminputs(qedqcd);\n   slha_io.set_minpar(input);\n   slha_io.set_extpar(input);\n   if (!error) {\n      slha_io.set_spectrum(model);\n      slha_io.set_extra(model, scales, observables);\n   }\n\n   slhaea = slha_io.get_slha_io().get_data();\n}\n\ntemplate <class T>\nSLHAea::Coll NUHMSSM_slha_io::fill_slhaea(\n   const NUHMSSM_slha<T>& model, const softsusy::QedQcd& qedqcd,\n   const NUHMSSM_scales& scales, const NUHMSSM_observables& observables)\n{\n   SLHAea::Coll slhaea;\n   NUHMSSM_slha_io::fill_slhaea(slhaea, model, qedqcd, scales, observables);\n\n   return slhaea;\n}\n\n/**\n * Stores the model (DR-bar) parameters in the SLHA object.\n *\n * @param model model class\n */\ntemplate <class T>\nvoid NUHMSSM_slha_io::set_model_parameters(const NUHMSSM_slha<T>& model)\n{\n   {\n      std::ostringstream block;\n      block << \"Block gauge Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(g1) * 0.7745966692414834), \"gY\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(g2)), \"g2\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(g3)), \"g3\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"Yu\", ToMatrix(MODELPARAMETER(Yu_slha)), \"Yu\", model.get_scale());\n   slha_io.set_block(\"Yd\", ToMatrix(MODELPARAMETER(Yd_slha)), \"Yd\", model.get_scale());\n   slha_io.set_block(\"Ye\", ToMatrix(MODELPARAMETER(Ye_slha)), \"Ye\", model.get_scale());\n   slha_io.set_block(\"Te\", MODELPARAMETER(TYe_slha), \"TYe\", model.get_scale());\n   slha_io.set_block(\"Td\", MODELPARAMETER(TYd_slha), \"TYd\", model.get_scale());\n   slha_io.set_block(\"Tu\", MODELPARAMETER(TYu_slha), \"TYu\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block HMIX Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(Mu)), \"Mu\")\n            << FORMAT_ELEMENT(101, (MODELPARAMETER(BMu)), \"BMu\")\n            << FORMAT_ELEMENT(102, (MODELPARAMETER(vd)), \"vd\")\n            << FORMAT_ELEMENT(103, (MODELPARAMETER(vu)), \"vu\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"MSQ2\", MODELPARAMETER(mq2_slha), \"mq2\", model.get_scale());\n   slha_io.set_block(\"MSE2\", MODELPARAMETER(me2_slha), \"me2\", model.get_scale());\n   slha_io.set_block(\"MSL2\", MODELPARAMETER(ml2_slha), \"ml2\", model.get_scale());\n   slha_io.set_block(\"MSU2\", MODELPARAMETER(mu2_slha), \"mu2\", model.get_scale());\n   slha_io.set_block(\"MSD2\", MODELPARAMETER(md2_slha), \"md2\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block MSOFT Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(21, (MODELPARAMETER(mHd2)), \"mHd2\")\n            << FORMAT_ELEMENT(22, (MODELPARAMETER(mHu2)), \"mHu2\")\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(MassB)), \"MassB\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(MassWB)), \"MassWB\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(MassG)), \"MassG\")\n      ;\n      slha_io.set_block(block);\n   }\n\n   {\n      std::ostringstream block;\n      block << \"Block Phases Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (Re(MODELPARAMETER(PhaseGlu))), \"Re(PhaseGlu)\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block IMPhases Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (Im(MODELPARAMETER(PhaseGlu))), \"Im(PhaseGlu)\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Writes extra SLHA blocks\n *\n * @param model model class\n */\ntemplate <class T>\nvoid NUHMSSM_slha_io::set_extra(\n   const NUHMSSM_slha<T>& model, const NUHMSSM_scales& scales,\n   const NUHMSSM_observables& observables)\n{\n   const NUHMSSM_physical physical(model.get_physical_slha());\n\n\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in BPMZ convention\n */\ntemplate <class T>\nvoid NUHMSSM_slha_io::set_spectrum(const NUHMSSM<T>& model)\n{\n   const NUHMSSM_slha<T> model_slha(model);\n   set_spectrum(model_slha);\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in SLHA convention\n */\ntemplate <class T>\nvoid NUHMSSM_slha_io::set_spectrum(const NUHMSSM_slha<T>& model)\n{\n   const NUHMSSM_physical physical(model.get_physical_slha());\n   const bool write_sm_masses = model.do_calculate_sm_pole_masses();\n\n   set_model_parameters(model);\n   set_mass(physical, write_sm_masses);\n   set_mixing_matrices(physical, write_sm_masses);\n\n   if (slha_io.get_modsel().quark_flavour_violated)\n      set_ckm(model.get_ckm_matrix(), model.get_scale());\n\n   if (slha_io.get_modsel().lepton_flavour_violated)\n      set_pmns(model.get_pmns_matrix(), model.get_scale());\n}\n\n} // namespace flexiblesusy\n\n#undef Pole\n#undef PHYSICAL\n#undef PHYSICAL_SLHA\n#undef LOCALPHYSICAL\n#undef MODEL\n#undef MODELPARAMETER\n#undef OBSERVABLES\n#undef LowEnergyConstant\n#undef SCALES\n\n#endif\n", "meta": {"hexsha": "dcc2c26f9803e6aea170121c45db8977b800ea44", "size": 10238, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_slha_io.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/NUHMSSM/NUHMSSM_slha_io.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/NUHMSSM/NUHMSSM_slha_io.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": 35.3034482759, "max_line_length": 142, "alphanum_fraction": 0.7058019144, "num_tokens": 2890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.031143830759591477, "lm_q1q2_score": 0.01363550141588773}}
{"text": "/* Copyright (C) 2012-2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <NTL/ZZ.h>\n#include \"FHEContext.h\"\n#include \"Ctxt.h\"\n#include \"permutations.h\"\n#include \"EncryptedArray.h\"\n\nnamespace helib {\n\nstd::ostream& operator<< (std::ostream &s, const PermNetwork &net)\n{\n  s << \"[\";\n  for (long i=0; i< net.layers.length(); i++) {\n    const PermNetLayer& lyr = net.layers[i];\n    s << \"[\" << lyr.genIdx << \" \" << lyr.e << \" \" << lyr.isID << \" \"\n      << lyr.shifts << \"]\\n\";\n  }\n  return s << \"]\";\n}\n\n// Compute one or more layers corresponding to one network of one leaf\nvoid PermNetwork::setLayers4Leaf(long lyrIdx, const ColPerm& p,\n\t\t\t\t const NTL::Vec<long>& benesLvls, long gIdx,\n\t\t\t\t const SubDimension& leafData, \n\t\t\t\t const Permut& map2cube)\n{\n#ifdef DEBUG_PRINTOUT\n  std::cerr << \"Layer \"<<lyrIdx<<\", column-permutation=\"<< p << std::endl;\n#endif\n  // Compute the shift amounts for all the layers in this network\n  NTL::Vec<bool> isID;\n  NTL::Vec<Permut> shifts;\n  if (benesLvls.length()==1) {// Special case for a \"trivial\" 1-layer network\n    shifts.SetLength(1);\n    isID.SetLength(1);\n    isID[0] = !p.getShiftAmounts(shifts[0]);\n  }\n  else  // The general case of a multi-layer Benes network\n    p.getBenesShiftAmounts(shifts,isID,benesLvls);\n\n  // Copy the shift amounts to the right place in the bigger network,\n  // renaming the slots from a linear array to the hyper cube\n  for (long i=0; i<benesLvls.length(); i++) {\n    PermNetLayer& lyr = layers[lyrIdx+i];\n    lyr.genIdx = gIdx;\n    lyr.isID = isID[i];\n    lyr.e = leafData.e;\n    if (!lyr.isID) {\n#ifdef DEBUG_PRINTOUT\n      std::cerr << \"layer \"<<lyrIdx+i<<\": \"<<shifts[i]<<std::endl;\n#endif\n      if (leafData.good) // For good leaves, shift by -x is the same as size-x\n\tfor (long k=0; k<shifts[i].length(); k++)\n\t  if (shifts[i][k]<0) shifts[i][k] += leafData.size;\n      applyPermToVec(lyr.shifts, shifts[i], map2cube); // do the renaming\n#ifdef DEBUG_PRINTOUT\n      std::cerr << \"       : \"<<lyr.shifts<<std::endl;\n#endif\n    }\n    //    else std::cerr << \"layer \"<<lyrIdx+i<<\"= identity\\n\";\n  }\n}\n\n// Build a full permutation network\nvoid PermNetwork::buildNetwork(const Permut& pi, const GeneratorTrees& trees)\n{\n  if (trees.numTrees()==0) { // the identity permutation, nothing to do\n    layers.SetLength(0);\n    return;\n  }\n\n  NTL::Vec<long> dims;\n  trees.getCubeSubDims(dims);\n\n  //  std::cerr << \"pi =      \"<<pi<<std::endl;\n  //  std::cerr << \"map2cube =\"<<trees.mapToCube()<<std::endl;\n  //  std::cerr << \"map2array=\"<<trees.mapToArray()<<std::endl;\n\n  // Compute the permutation on the cube, rho = map2cube o pi o map2array\n\n  Permut rho;\n  applyPermsToVec(rho, trees.mapToCube(), pi, trees.mapToArray());\n  //  std::cerr << \"rho =     \"<<rho<<std::endl;\n\n\n  // Break rho along the different dimensions\n  CubeSignature sig(dims); // make a cube-signature object\n  std::vector<ColPerm> perms;\n  breakPermByDim(perms, rho, sig);\n\n  //  for (long i=0; i<(long)perms.size(); i++) { // debugging printouts\n  //    Permut tmp;\n  //    perms[i].makeExplicit(tmp);\n  //    std::cerr << \" prems[\"<<i<<\"]=\"<<tmp<<std::endl;\n  //  }\n\n  layers.SetLength(trees.numLayers()); // allocate space\n\n  // Go over the different permutations and build the corresponding layers\n  long dimIdx =0;\n  long frntLyr=0, backLyr=layers.length();\n  for (long g=0; g<trees.numTrees(); g++) { // go over all the generators/trees\n    const OneGeneratorTree &T = trees[g];\n\n    // In each tree, go over all the leaves\n    for (long leaf=T.firstLeaf(); leaf>=0; leaf=T.nextLeaf(leaf)) {\n      const SubDimension& leafData = T[leaf].getData();\n\n      // This leaf determines layers frntLyer...frntLey+frst.length()-1, and\n      // if it isn't the middle then also backLyr-scnd.length()...backLyr-1\n\n      // handle the first Benes network\n      setLayers4Leaf(/*1st-layer-index=*/frntLyr, \n\t\t     /*permutation    =*/perms[dimIdx],\n\t\t     /*Benes levels   =*/leafData.frstBenes,\n\t\t     /*generator index=*/T.getAuxKey(),\n\t\t     /*(size,good,e)  =*/leafData,\n\t\t     /*hypercube renaming permutation=*/trees.mapToCube());\n      frntLyr += leafData.frstBenes.length(); // how many layers were used\n      dimIdx++;\n\n      if (leafData.scndBenes.length()>0) { // Also a second Benes network\n\tlong dimIdx2 = perms.size() -dimIdx; // dimIdx was incremented above\n\tbackLyr -= leafData.scndBenes.length();\n\tsetLayers4Leaf(/*1st-layer-index=*/backLyr, \n\t\t       /*permutation    =*/perms[dimIdx2],\n\t\t       /*Benes levels   =*/leafData.scndBenes,\n\t\t       /*generator index=*/T.getAuxKey(),\n\t\t       /*(size,good,e)  =*/leafData,\n\t\t       /*hypercube renaming permutation=*/trees.mapToCube());\n      }\n    }\n  }\n}\n\n// Apply a permutation network to a hypercube, used mostly for debugging\nvoid PermNetwork::applyToCube(HyperCube<long>& cube) const\n{\n  if (layers.length()==0) return;\n  long n = cube.getSize();\n  NTL::Vec<long> tmp(NTL::INIT_SIZE, n); // temporary vector\n\n  // Apply the layers, one at a time\n  for (long i=0; i<layers.length(); i++) {\n    const PermNetLayer& lyr = layers[i];\n    if (lyr.isID) continue; // this layer is the identity permutation\n\n    //OLD: assert(lyr.shifts.length()==n);\n    helib::assertEq(lyr.shifts.length(), n, \"layer has incorrect size\");\n\n    // This layer shift elements along the dimension lyr.genIdx\n    long dim = lyr.genIdx;\n\n    // Move elements as dictated by this layer\n    for (long j=0; j<n; j++) {\n      long shamt = lyr.e * lyr.shifts[j]; // how much to shift this slot\n      if (shamt<0) shamt += cube.getDim(dim); // addCoord expects shamt>=0\n      long j2 = cube.addCoord(j, dim, shamt); // new index for this slot\n      tmp[j2] = cube[j];\n    }\n    // Copy back to cube\n    for (long j=0; j<n; j++)\n      cube[j] = tmp[j];\n#ifdef DEBUG_PRINTOUT\n    std::cerr << \" after layer \"<< i << \", cube=\" << cube.getData()<<std::endl;\n#endif\n  }\n}\n\nvoid PermNetwork::applyToPtxt(NTL::ZZX& p, const EncryptedArray& ea) const\n{\n  throw helib::LogicError(\"PermNetwork::applyToPtxt is not implemented\");\n}\n\n// Upon return, mask[i]=1 if haystack[i]=needle, 0 otherwise.\n// Also set to 0 all the entries in haystack where mask[i]=1.\n// Return the index of the first nonzero entry in haystack at the end\n// of the pass (-1 if they are all zero). Also return a flag saying if\n// any entries of the mask are nonzero.\nstatic std::pair<long,bool>\nmakeMask(std::vector<long>& mask, NTL::Vec<long>& haystack, long needle)\n{\n  long found = false;\n  long fstNonZeroIdx = -1;\n  for (long i=0; i<(long)mask.size(); i++) {\n    if (haystack[i] == needle) { // found a needle\n      found = true;\n      mask[i]=1;\n      haystack[i]=0; // remove this needle from haystack\n    } else {         // no needle here\n      mask[i]=0;\n      if (haystack[i]!=0 && fstNonZeroIdx<0)\n\tfstNonZeroIdx = i;       // first nonzero entry in haystack\n    }\n  }\n  return std::make_pair(fstNonZeroIdx,found);\n}\n\n// Apply a permutation network to a ciphertext\nvoid PermNetwork::applyToCtxt(Ctxt& c, const EncryptedArray& ea) const\n{\n  const PAlgebra& al = ea.getPAlgebra();\n\n  // Apply the layers, one at a time\n  for (long i=0; i<layers.length(); i++) {\n    const PermNetLayer& lyr = layers[i];\n    if (lyr.isID) continue; // this layer is the identity permutation\n\n    // This layer is shifted via powers of g^e mod m\n    long g2e = NTL::PowerMod(al.ZmStarGen(lyr.genIdx), lyr.e, al.getM());\n\n    NTL::Vec<long> unused = lyr.shifts; // copy to a new vector\n    std::vector<long> mask(lyr.shifts.length());  // buffer to hold masks\n    Ctxt sum(c.getPubKey(), c.getPtxtSpace()); // an empty ciphertext\n\n    long shamt = 0;\n    bool frst = true;\n    while (true) {\n      std::pair<long,bool> ret=makeMask(mask, unused, shamt); // compute mask\n      if (ret.second) { // non-empty mask\n\tCtxt tmp = c;\n\tNTL::ZZX maskPoly;\n\tea.encode(maskPoly, mask);    // encode mask as polynomial\n\ttmp.multByConstant(maskPoly); // multiply by mask\n\tif (shamt!=0) // rotate if the shift amount is nonzero\n\t  tmp.smartAutomorph(NTL::PowerMod(g2e, shamt, al.getM()));\n\tif (frst) {\n\t  sum = tmp;\n\t  frst = false;\n\t}\n\telse\n\t  sum += tmp;\n      }\n      if (ret.first >= 0)\n\tshamt = unused[ret.first]; // next shift amount to use\n\n      else break; // unused is all-zero, done with this layer\n    }\n    c = sum; // update the cipehrtext c before the next layer\n  }\n}\n\n}\n", "meta": {"hexsha": "590fbbc29a6577b81fa544ca21977aed63372e58", "size": 8862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PermNetwork.cpp", "max_stars_repo_name": "patrick-schwarz/HElib", "max_stars_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-01T07:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T07:18:47.000Z", "max_issues_repo_path": "src/PermNetwork.cpp", "max_issues_repo_name": "wangjinglin0721/HElib", "max_issues_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PermNetwork.cpp", "max_forks_repo_name": "wangjinglin0721/HElib", "max_forks_repo_head_hexsha": "cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59", "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.8897637795, "max_line_length": 79, "alphanum_fraction": 0.6429699842, "num_tokens": 2574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.03114382828664837, "lm_q1q2_score": 0.013635499419369411}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2015 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n#include <Core/Algorithms/Legacy/Fields/Mapping/MapFieldDataFromSourceToDestination.h>\n#include <Core/Algorithms/Base/AlgorithmVariableNames.h>\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Thread/Parallel.h>\n#include <Core/Thread/Barrier.h>\n\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/Datatypes/Matrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/Legacy/Field/FieldInformation.h>\n\n#include <boost/scoped_ptr.hpp>\n\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Utility;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun::Core::Thread;\nusing namespace SCIRun;\n\nALGORITHM_PARAMETER_DEF(Fields, DefaultValue);\nALGORITHM_PARAMETER_DEF(Fields, MappingMethod);\n\nconst AlgorithmOutputName MapFieldDataFromSourceToDestinationAlgo::Remapped_Destination(\"Remapped_Destination\");\n\nMapFieldDataFromSourceToDestinationAlgo::MapFieldDataFromSourceToDestinationAlgo()\n{\n  using namespace Parameters;\n  addParameter(DefaultValue, 0.0);\n  addParameter(MaxDistance, -1.0);\n  addOption(MappingMethod, \"interpolateddata\", \"interpolateddata|closestdata|singledestination\");\n}\n\nnamespace detail\n{\n  class MapFieldDataFromSourceToDestinationPAlgoBase : public Interruptible\n  {\n  public:\n    explicit MapFieldDataFromSourceToDestinationPAlgoBase(const std::string& name, int nproc) :\n      sfield_(0), dfield_(0), smesh_(0), dmesh_(0), maxdist_(0), algo_(0),\n      barrier_(name, nproc), nproc_(nproc) {}\n\n    virtual void parallel(int proc) = 0;\n\n    VField* sfield_;\n    VField* dfield_;\n    VMesh*  smesh_;\n    VMesh*  dmesh_;\n\n    double  maxdist_;\n    const AlgorithmBase* algo_;\n\n  protected:\n    Barrier barrier_;\n    int nproc_;\n  };\n\n\n//------------------------------------------------------------\n// Algorithm - each destination has its closest source\n\nclass MapFieldDataFromSourceToDestinationClosestDataPAlgo : public MapFieldDataFromSourceToDestinationPAlgoBase\n{\n  public:\n    explicit MapFieldDataFromSourceToDestinationClosestDataPAlgo(int nproc) :\n      MapFieldDataFromSourceToDestinationPAlgoBase(\" MapFieldDataFromSourceToDestinationClosestDataPAlgo Barrier\", nproc) {}\n\n    virtual void parallel(int proc) override;\n};\n\nvoid\nMapFieldDataFromSourceToDestinationClosestDataPAlgo::parallel(int proc)\n{\n  // Determine which ones to run\n  VField::size_type num_values = dfield_->num_values();\n  VField::size_type localsize = num_values/nproc_;\n  VField::index_type start = localsize*proc;\n  VField::index_type end = localsize*(proc+1);\n  if (proc == nproc_-1) end = num_values;\n\n  barrier_.wait();\n\n  int cnt = 0;\n\n  if (dfield_->basis_order() == 0 && sfield_->basis_order() == 0)\n  {\n    Point p, r;\n    VMesh::Elem::index_type didx;\n\n    for (VMesh::Elem::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n      double dist;\n      if(smesh_->find_closest_elem(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          dfield_->copy_value(sfield_,didx,idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (dfield_->basis_order() == 1 && sfield_->basis_order() == 0)\n  {\n    Point p, r;\n    VMesh::Elem::index_type didx;\n    for (VMesh::Node::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n      double dist;\n      if(smesh_->find_closest_elem(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          dfield_->copy_value(sfield_,didx,idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (dfield_->basis_order() == 0 && sfield_->basis_order() == 1)\n  {\n    Point p, r;\n    VMesh::Node::index_type didx;\n    for (VMesh::Elem::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n      double dist;\n      if(smesh_->find_closest_node(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          dfield_->copy_value(sfield_,didx,idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (dfield_->basis_order() == 1 && sfield_->basis_order() == 1)\n  {\n    Point p, r;\n    VMesh::Node::index_type didx;\n    for (VMesh::Node::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n      double dist;\n      if(smesh_->find_closest_node(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          dfield_->copy_value(sfield_,didx,idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n\n  barrier_.wait();\n}\n\n\n\n//------------------------------------------------------------\n// Algorithm - each source will map to one destination\n\nclass MapFieldDataFromSourceToDestinationSingleDestinationPAlgo : public MapFieldDataFromSourceToDestinationPAlgoBase\n{\n  public:\n    explicit MapFieldDataFromSourceToDestinationSingleDestinationPAlgo(int nproc) :\n      MapFieldDataFromSourceToDestinationPAlgoBase(\" MapFieldDataFromSourceToDestinationSingleDestinationPAlgo Barrier\", nproc) {}\n\n    virtual void parallel(int proc) override;\n\n    std::vector<index_type> tcc_;\n    std::vector<index_type> cc_;\n};\n\nvoid\nMapFieldDataFromSourceToDestinationSingleDestinationPAlgo::parallel(int proc)\n{\n  // Determine which ones to run\n  VField::size_type num_values = sfield_->num_values();\n  VField::size_type localsize = num_values/nproc_;\n  VField::index_type start = localsize*proc;\n  VField::index_type end = localsize*(proc+1);\n  if (proc == nproc_-1) end = num_values;\n\n  if (proc == 0)\n  {\n    tcc_.resize(dfield_->num_values(),-1);\n    cc_.resize(sfield_->num_values(),-1);\n  }\n\n  barrier_.wait();\n  int cnt = 0;\n\n  if (sfield_->basis_order() == 0 && dfield_->basis_order() == 0)\n  {\n    Point p, r;\n    VMesh::coords_type coords;\n    VMesh::Elem::index_type didx;\n    for (VMesh::Elem::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      smesh_->get_center(p,idx);\n      double dist;\n      if(dmesh_->find_closest_elem(dist,r,coords,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          cc_[idx] = didx;\n        }\n        else cc_[idx] = -1;\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (sfield_->basis_order() == 1 && dfield_->basis_order() == 0)\n  {\n    Point p, r;\n    VMesh::coords_type coords;\n    VMesh::Elem::index_type didx;\n    for (VMesh::Node::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      smesh_->get_center(p,idx);\n      double dist;\n      if(dmesh_->find_closest_elem(dist,r,coords,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          cc_[idx] = didx;\n        }\n        else cc_[idx] = -1;\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (sfield_->basis_order() == 0 && dfield_->basis_order() == 1)\n  {\n    Point p, r;\n    VMesh::Node::index_type didx;\n    for (VMesh::Elem::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      smesh_->get_center(p,idx);\n      double dist;\n      if(dmesh_->find_closest_node(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          cc_[idx] = didx;\n        }\n        else cc_[idx] = -1;\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (sfield_->basis_order() == 1 && dfield_->basis_order() == 1)\n  {\n    Point p, r;\n    VMesh::Node::index_type didx;\n    for (VMesh::Node::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      smesh_->get_center(p,idx);\n      double dist;\n      if(dmesh_->find_closest_node(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          cc_[idx] = didx;\n        }\n        else cc_[idx] = -1;\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n\n  barrier_.wait();\n\n  // Copy the data thread safe\n  if (proc == 0)\n  {\n    VField::size_type num_dvalues = dfield_->num_values();\n\n    for (VMesh::index_type idx=0; idx<num_values;idx++)\n    {\n      if (cc_[idx] >= 0) tcc_[cc_[idx]] = idx;\n    }\n\n    for (VMesh::index_type idx=0; idx<num_dvalues;idx++)\n    {\n      if (tcc_[idx] >= 0)\n      {\n        dfield_->copy_value(sfield_,tcc_[idx],idx);\n      }\n    }\n  }\n}\n\n\n//------------------------------------------------------------\n// Algorithm - get interpolated data\n\n\nclass MapFieldDataFromSourceToDestinationInterpolatedDataPAlgo : public MapFieldDataFromSourceToDestinationPAlgoBase\n{\n  public:\n    explicit MapFieldDataFromSourceToDestinationInterpolatedDataPAlgo(int nproc) :\n      MapFieldDataFromSourceToDestinationPAlgoBase(\" MapFieldDataFromSourceToDestinationInterpolatedDataPAlgo Barrier\", nproc) {}\n\n    virtual void parallel(int proc) override;\n};\n\nvoid\nMapFieldDataFromSourceToDestinationInterpolatedDataPAlgo::parallel(int proc)\n{\n  // Determine which ones to run\n  VField::size_type num_values = dfield_->num_values();\n  VField::size_type localsize = num_values/nproc_;\n  VField::index_type start = localsize*proc;\n  VField::index_type end = localsize*(proc+1);\n  if (proc == nproc_-1) end = num_values;\n\n  barrier_.wait();\n\n  int cnt = 0;\n  if (dfield_->basis_order() == 0 && sfield_->basis_order() == 0)\n  {\n    Point p, r;\n    VMesh::Elem::index_type didx;\n\n    for (VMesh::Elem::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n\n      double dist;\n      if(smesh_->find_closest_elem(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          dfield_->copy_value(sfield_,didx,idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (dfield_->basis_order() == 1 && sfield_->basis_order() == 0)\n  {\n    Point p, r;\n    VMesh::Elem::index_type didx;\n    for (VMesh::Node::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n      double dist;\n      if(smesh_->find_closest_elem(dist,r,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          dfield_->copy_value(sfield_,didx,idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (dfield_->basis_order() == 0 && sfield_->basis_order() == 1)\n  {\n    Point p, r;\n    VMesh::coords_type coords;\n    VMesh::Elem::index_type didx;\n    VMesh::ElemInterpolate interp;\n    for (VMesh::Elem::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n      double dist;\n      if(smesh_->find_closest_elem(dist,r,coords,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          smesh_->get_interpolate_weights(coords,didx,interp,1);\n          dfield_->copy_weighted_value(sfield_,&(interp.node_index[0]),\n              &(interp.weights[0]),interp.node_index.size(),idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n  else if (dfield_->basis_order() == 1 && sfield_->basis_order() == 1)\n  {\n    Point p, r;\n    VMesh::coords_type coords;\n    VMesh::Elem::index_type didx;\n    VMesh::ElemInterpolate interp;\n    for (VMesh::Node::index_type idx=start; idx<end;idx++)\n    {\n      checkForInterruption();\n      dmesh_->get_center(p,idx);\n      double dist;\n      if(smesh_->find_closest_elem(dist,r,coords,didx,p))\n      {\n        if (maxdist_ < 0.0 || dist < maxdist_)\n        {\n          smesh_->get_interpolate_weights(coords,didx,interp,1);\n          dfield_->copy_weighted_value(sfield_,&(interp.node_index[0]),\n              &(interp.weights[0]),interp.node_index.size(),idx);\n        }\n      }\n      if (proc == 0) { cnt++; if (cnt == 200) {cnt = 0; algo_->update_progress_max(idx,end); } }\n    }\n  }\n\n  barrier_.wait();\n}\n\n}\n\nbool\nMapFieldDataFromSourceToDestinationAlgo::runImpl(FieldHandle source, FieldHandle destination, FieldHandle& output) const\n{\n  ScopedAlgorithmStatusReporter asr(this, \"MapFieldDataFromSourceToDestination\");\n  using namespace Parameters;\n\n  if (!source)\n  {\n    error(\"No source field\");\n    return (false);\n  }\n\n  if (!destination)\n  {\n    error(\"No destination field\");\n    return (false);\n  }\n\n  FieldInformation fis(source);\n  FieldInformation fid(destination);\n  fid.set_data_type(fis.get_data_type());\n\n  if (fid.is_nodata()) fid.make_lineardata();\n  output = CreateField(fid,destination->mesh());\n\n  if (!output)\n  {\n    error(\"Could not allocate output field\");\n    return (false);\n  }\n\n  // Determine output type\n\n  VMesh* smesh = source->vmesh();\n  VMesh* dmesh = output->vmesh();\n  VField* sfield = source->vfield();\n  VField* dfield = output->vfield();\n\n  // Make sure output field is all empty and of right size\n  dfield->resize_values();\n  dfield->clear_all_values();\n  dfield->set_all_values(get(DefaultValue).toDouble());\n\n  std::string method = getOption(MappingMethod);\n  int sbasis_order = sfield->basis_order();\n  int dbasis_order = dfield->basis_order();\n\n  if (sbasis_order < 0)\n  {\n    error(\"Source field basis order needs to constant or linear\");\n    return (false);\n  }\n\n  if (dbasis_order < 0)\n  {\n    error(\"Destination field basis order needs to constant or linear\");\n    return (false);\n  }\n\n  if (method == \"closestdata\")\n  {\n    if (sbasis_order == 0) smesh->synchronize(Mesh::FIND_CLOSEST_ELEM_E);\n    else smesh->synchronize(Mesh::FIND_CLOSEST_NODE_E);\n  }\n  else if(method == \"singledestination\")\n  {\n    if (dbasis_order == 0) dmesh->synchronize(Mesh::FIND_CLOSEST_ELEM_E);\n    else dmesh->synchronize(Mesh::FIND_CLOSEST_NODE_E);\n  }\n  else if (method == \"interpolateddata\")\n  {\n    if (smesh->num_elems() > 0)\n    {\n      smesh->synchronize(Mesh::FIND_CLOSEST_ELEM_E);\n    }\n    else\n    {\n      error(\"Source does not have any elements, hence one cannot interpolate data in this field\");\n      error(\"Use a closestdata interpolation scheme for this data\");\n      return (false);\n    }\n  }\n\n  double maxdist = get(MaxDistance).toDouble();\n\n  boost::scoped_ptr<detail::MapFieldDataFromSourceToDestinationPAlgoBase> algoP;\n  int np = Parallel::NumCores();\n  if (method == \"closestdata\")\n  {\n    algoP.reset(new detail::MapFieldDataFromSourceToDestinationClosestDataPAlgo(np));\n  }\n  else if(method == \"singledestination\")\n  {\n    np = 1; //TODO: ???\n    algoP.reset(new detail::MapFieldDataFromSourceToDestinationSingleDestinationPAlgo(np));\n  }\n  else if (method == \"interpolateddata\")\n  {\n    algoP.reset(new detail::MapFieldDataFromSourceToDestinationInterpolatedDataPAlgo(np));\n  }\n\n  if (!algoP)\n    THROW_ALGORITHM_INPUT_ERROR(\"Invalid mapping method\");\n\n  algoP->sfield_ = sfield;\n  algoP->dfield_ = dfield;\n  algoP->smesh_ = smesh;\n  algoP->dmesh_ = dmesh;\n  algoP->maxdist_ = maxdist;\n  algoP->algo_ = this;\n\n  auto task_i = [&algoP,this](int i) { algoP->parallel(i); };\n  Parallel::RunTasks(task_i, np);\n\n  CopyProperties(*destination, *output);\n\n  return (true);\n}\n\nAlgorithmOutput MapFieldDataFromSourceToDestinationAlgo::run(const AlgorithmInput& input) const\n{\n  auto source = input.get<Field>(Variables::Source);\n  auto destination = input.get<Field>(Variables::Destination);\n\n  FieldHandle output_field;\n  if (!runImpl(source, destination, output_field))\n    THROW_ALGORITHM_PROCESSING_ERROR(\"False returned from legacy run call\");\n\n  AlgorithmOutput output;\n  output[Remapped_Destination] = output_field;\n\n  return output;\n}\n", "meta": {"hexsha": "6a15192dd5aaa99ec8ad86df00ae524324da2e94", "size": 17411, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Legacy/Fields/Mapping/MapFieldDataFromSourceToDestination.cc", "max_stars_repo_name": "Nahusa/SCIRun", "max_stars_repo_head_hexsha": "c54e714d4c7e956d053597cf194e07616e28a498", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T06:00:15.000Z", "max_issues_repo_path": "src/Core/Algorithms/Legacy/Fields/Mapping/MapFieldDataFromSourceToDestination.cc", "max_issues_repo_name": "manual123/SCIRun", "max_issues_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/Legacy/Fields/Mapping/MapFieldDataFromSourceToDestination.cc", "max_forks_repo_name": "manual123/SCIRun", "max_forks_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4602368866, "max_line_length": 130, "alphanum_fraction": 0.6493596003, "num_tokens": 4866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702254064929193, "lm_q2_score": 0.03676946818664466, "lm_q1q2_score": 0.013612991305928983}}
{"text": "/*\n    This file is part of Nori, a simple educational ray tracer\n\n    Copyright (c) 2015 by Wenzel Jakob\n\n    Nori 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    Nori 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 <nori/accel.h>\n#include <nori/timer.h>\n#include <tbb/tbb.h>\n#include <Eigen/Geometry>\n#include <atomic>\n\n/*\n * =======================================================================\n *   WARNING    WARNING    WARNING    WARNING    WARNING    WARNING\n * =======================================================================\n *   Remember to put on SAFETY GOGGLES before looking at this file. Youa\n *   are most certainly not expected to read or understand any of it.\n * =======================================================================\n */\n\nNORI_NAMESPACE_BEGIN\n\n/* Bin data structure for counting triangles and computing their bounding box */\nstruct Bins {\n    static const int BIN_COUNT = 16;\n    Bins() { memset(counts, 0, sizeof(uint32_t) * BIN_COUNT); }\n    uint32_t counts[BIN_COUNT];\n    BoundingBox3f bbox[BIN_COUNT];\n};\n\n/**\n * \\brief Build task for parallel BVH construction\n *\n * This class uses the task scheduling system of Intel' Thread Building Blocks\n * to parallelize the divide and conquer BVH build at all levels.\n *\n * The used methodology is roughly that described in\n * \"Fast and Parallel Construction of SAH-based Bounding Volume Hierarchies\"\n * by Ingo Wald (Proc. IEEE/EG Symposium on Interactive Ray Tracing, 2007)\n */\nclass BVHBuildTask : public tbb::task {\nprivate:\n    Accel &bvh;\n    uint32_t node_idx;\n    uint32_t *start, *end, *temp;\n\npublic:\n    /// Build-related parameters\n    enum {\n        /// Switch to a serial build when less than 32 triangles are left\n        SERIAL_THRESHOLD = 32,\n\n        /// Process triangles in batches of 1K for the purpose of parallelization\n        GRAIN_SIZE = 1000,\n\n        /// Heuristic cost value for traversal operations\n        TRAVERSAL_COST = 1,\n\n        /// Heuristic cost value for intersection operations\n        INTERSECTION_COST = 1\n    };\n\npublic:\n    /**\n     * Create a new build task\n     *\n     * \\param bvh\n     *    Reference to the underlying BVH\n     *\n     * \\param node_idx\n     *    Index of the BVH node that should be built\n     *\n     * \\param start\n     *    Start pointer into a list of triangle indices to be processed\n     *\n     * \\param end\n     *    End pointer into a list of triangle indices to be processed\n     *\n     *  \\param temp\n     *    Pointer into a temporary memory region that can be used for\n     *    construction purposes. The usable length is <tt>end-start</tt>\n     *    unsigned integers.\n     */\n    BVHBuildTask(Accel &bvh, uint32_t node_idx, uint32_t *start, uint32_t *end, uint32_t *temp)\n        : bvh(bvh), node_idx(node_idx), start(start), end(end), temp(temp) { }\n\n    task *execute() {\n        uint32_t size = (uint32_t) (end-start);\n        Accel::BVHNode &node = bvh.m_nodes[node_idx];\n\n        /* Switch to a serial build when less than SERIAL_THRESHOLD triangles are left */\n        if (size < SERIAL_THRESHOLD) {\n            execute_serially(bvh, node_idx, start, end, temp);\n            return nullptr;\n        }\n\n        /* Always split along the largest axis */\n        int axis = node.bbox.getLargestAxis();\n        float min = node.bbox.min[axis], max = node.bbox.max[axis],\n              inv_bin_size = Bins::BIN_COUNT / (max-min);\n\n        /* Accumulate all triangles into bins */\n        Bins bins = tbb::parallel_reduce(\n            tbb::blocked_range<uint32_t>(0u, size, GRAIN_SIZE),\n            Bins(),\n            /* MAP: Bin a number of triangles and return the resulting 'Bins' data structure */\n            [&](const tbb::blocked_range<uint32_t> &range, Bins result) {\n                for (uint32_t i = range.begin(); i != range.end(); ++i) {\n                    uint32_t f = start[i];\n                    float centroid = bvh.getCentroid(f)[axis];\n\n                    int index = std::min(std::max(\n                        (int) ((centroid - min) * inv_bin_size), 0),\n                        (Bins::BIN_COUNT - 1));\n\n                    result.counts[index]++;\n                    result.bbox[index].expandBy(bvh.getBoundingBox(f));\n                }\n                return result;\n            },\n            /* REDUCE: Combine two 'Bins' data structures */\n            [](const Bins &b1, const Bins &b2) {\n                Bins result;\n                for (int i=0; i < Bins::BIN_COUNT; ++i) {\n                    result.counts[i] = b1.counts[i] + b2.counts[i];\n                    result.bbox[i] = BoundingBox3f::merge(b1.bbox[i], b2.bbox[i]);\n                }\n                return result;\n            }\n        );\n\n        /* Choose the best split plane based on the binned data */\n        BoundingBox3f bbox_left[Bins::BIN_COUNT];\n        bbox_left[0] = bins.bbox[0];\n        for (int i=1; i<Bins::BIN_COUNT; ++i) {\n            bins.counts[i] += bins.counts[i-1];\n            bbox_left[i] = BoundingBox3f::merge(bbox_left[i-1], bins.bbox[i]);\n        }\n\n        BoundingBox3f bbox_right = bins.bbox[Bins::BIN_COUNT-1], best_bbox_right;\n        int64_t best_index = -1;\n        float best_cost = (float) INTERSECTION_COST * size;\n        float tri_factor = (float) INTERSECTION_COST / node.bbox.getSurfaceArea();\n\n        for (int i=Bins::BIN_COUNT - 2; i >= 0; --i) {\n            uint32_t prims_left = bins.counts[i], prims_right = (uint32_t) (end - start) - bins.counts[i];\n            float sah_cost = 2.0f * TRAVERSAL_COST +\n                tri_factor * (prims_left * bbox_left[i].getSurfaceArea() +\n                              prims_right * bbox_right.getSurfaceArea());\n            if (sah_cost < best_cost) {\n                best_cost = sah_cost;\n                best_index = i;\n                best_bbox_right = bbox_right;\n            }\n            bbox_right = BoundingBox3f::merge(bbox_right, bins.bbox[i]);\n        }\n\n        if (best_index == -1) {\n            /* Could not find a good split plane -- retry with\n               more careful serial code just to be sure.. */\n            execute_serially(bvh, node_idx, start, end, temp);\n            return nullptr;\n        }\n\n        uint32_t left_count = bins.counts[best_index];\n        int node_idx_left = node_idx+1;\n        int node_idx_right = node_idx+2*left_count;\n\n        bvh.m_nodes[node_idx_left ].bbox = bbox_left[best_index];\n        bvh.m_nodes[node_idx_right].bbox = best_bbox_right;\n        node.inner.rightChild = node_idx_right;\n        node.inner.axis = axis;\n        node.inner.flag = 0;\n\n        std::atomic<uint32_t> offset_left(0),\n                              offset_right(bins.counts[best_index]);\n\n        tbb::parallel_for(\n            tbb::blocked_range<uint32_t>(0u, size, GRAIN_SIZE),\n            [&](const tbb::blocked_range<uint32_t> &range) {\n                uint32_t count_left = 0, count_right = 0;\n                for (uint32_t i = range.begin(); i != range.end(); ++i) {\n                    uint32_t f = start[i];\n                    float centroid = bvh.getCentroid(f)[axis];\n                    int index = (int) ((centroid - min) * inv_bin_size);\n                    (index <= best_index ? count_left : count_right)++;\n                }\n                uint32_t idx_l = offset_left.fetch_add(count_left);\n                uint32_t idx_r = offset_right.fetch_add(count_right);\n                for (uint32_t i = range.begin(); i != range.end(); ++i) {\n                    uint32_t f = start[i];\n                    float centroid = bvh.getCentroid(f)[axis];\n                    int index = (int) ((centroid - min) * inv_bin_size);\n                    if (index <= best_index)\n                        temp[idx_l++] = f;\n                    else\n                        temp[idx_r++] = f;\n                }\n            }\n        );\n        memcpy(start, temp, size * sizeof(uint32_t));\n        assert(offset_left == left_count && offset_right == size);\n\n        /* Create an empty parent task */\n        tbb::task& c = *new (allocate_continuation()) tbb::empty_task;\n        c.set_ref_count(2);\n\n        /* Post right subtree to scheduler */\n        BVHBuildTask &b = *new (c.allocate_child())\n            BVHBuildTask(bvh, node_idx_right, start + left_count,\n                         end, temp + left_count);\n        spawn(b);\n\n        /* Directly start working on left subtree */\n        recycle_as_child_of(c);\n        node_idx = node_idx_left;\n        end = start + left_count;\n\n        return this;\n    }\n\n    /// Single-threaded build function\n    static void execute_serially(Accel &bvh, uint32_t node_idx, uint32_t *start, uint32_t *end, uint32_t *temp) {\n        Accel::BVHNode &node = bvh.m_nodes[node_idx];\n        uint32_t size = (uint32_t) (end - start);\n        float best_cost = (float) INTERSECTION_COST * size;\n        int64_t best_index = -1, best_axis = -1;\n        float *left_areas = (float *) temp;\n\n        /* Try splitting along every axis */\n        for (int axis=0; axis<3; ++axis) {\n            /* Sort all triangles based on their centroid positions projected on the axis */\n            std::sort(start, end, [&](uint32_t f1, uint32_t f2) {\n                return bvh.getCentroid(f1)[axis] < bvh.getCentroid(f2)[axis];\n            });\n\n            BoundingBox3f bbox;\n            for (uint32_t i = 0; i<size; ++i) {\n                uint32_t f = *(start + i);\n                bbox.expandBy(bvh.getBoundingBox(f));\n                left_areas[i] = (float) bbox.getSurfaceArea();\n            }\n            if (axis == 0)\n                node.bbox = bbox;\n\n            bbox.reset();\n\n            /* Choose the best split plane */\n            float tri_factor = INTERSECTION_COST / node.bbox.getSurfaceArea();\n            for (uint32_t i = size-1; i>=1; --i) {\n                uint32_t f = *(start + i);\n                bbox.expandBy(bvh.getBoundingBox(f));\n\n                float left_area = left_areas[i-1];\n                float right_area = bbox.getSurfaceArea();\n                uint32_t prims_left = i;\n                uint32_t prims_right = size-i;\n\n                float sah_cost = 2.0f * TRAVERSAL_COST +\n                    tri_factor * (prims_left * left_area +\n                                  prims_right * right_area);\n\n                if (sah_cost < best_cost) {\n                    best_cost = sah_cost;\n                    best_index = i;\n                    best_axis = axis;\n                }\n            }\n        }\n\n        if (best_index == -1) {\n            /* Splitting does not reduce the cost, make a leaf */\n            node.leaf.flag = 1;\n            node.leaf.start = (uint32_t) (start - bvh.m_indices.data());\n            node.leaf.size  = size;\n            return;\n        }\n\n        std::sort(start, end, [&](uint32_t f1, uint32_t f2) {\n            return bvh.getCentroid(f1)[best_axis] < bvh.getCentroid(f2)[best_axis];\n        });\n\n        uint32_t left_count = (uint32_t) best_index;\n        uint32_t node_idx_left = node_idx + 1;\n        uint32_t node_idx_right = node_idx + 2 * left_count;\n        node.inner.rightChild = node_idx_right;\n        node.inner.axis = best_axis;\n        node.inner.flag = 0;\n\n        execute_serially(bvh, node_idx_left, start, start + left_count, temp);\n        execute_serially(bvh, node_idx_right, start+left_count, end, temp + left_count);\n    }\n};\n\nvoid Accel::addMesh(Mesh *mesh) {\n    m_meshes.push_back(mesh);\n    m_meshOffset.push_back(m_meshOffset.back() + mesh->getTriangleCount());\n    m_bbox.expandBy(mesh->getBoundingBox());\n}\n\nvoid Accel::clear() {\n    for (auto mesh : m_meshes)\n        delete mesh;\n    m_meshes.clear();\n    m_meshOffset.clear();\n    m_meshOffset.push_back(0u);\n    m_nodes.clear();\n    m_indices.clear();\n    m_bbox.reset();\n    m_nodes.shrink_to_fit();\n    m_meshes.shrink_to_fit();\n    m_meshOffset.shrink_to_fit();\n    m_indices.shrink_to_fit();\n}\n\nvoid Accel::build() {\n    uint32_t size  = getTriangleCount();\n    if (size == 0)\n        return;\n    //cout << \"Constructing a SAH BVH (\" << m_meshes.size()\n    //    << (m_meshes.size() == 1 ? \" mesh, \" : \" meshes, \")\n    //    << size << \" triangles) .. \";\n    //cout.flush();\n    Timer timer;\n\n    /* Conservative estimate for the total number of nodes */\n    m_nodes.resize(2*size);\n    memset(m_nodes.data(), 0, sizeof(BVHNode) * m_nodes.size());\n    m_nodes[0].bbox = m_bbox;\n    m_indices.resize(size);\n\n    if (sizeof(BVHNode) != 32)\n        throw NoriException(\"BVH Node is not packed! Investigate compiler settings.\");\n\n    for (uint32_t i = 0; i < size; ++i)\n        m_indices[i] = i;\n\n    uint32_t *indices = m_indices.data(), *temp = new uint32_t[size];\n    BVHBuildTask& task = *new(tbb::task::allocate_root())\n        BVHBuildTask(*this, 0u, indices, indices + size , temp);\n    tbb::task::spawn_root_and_wait(task);\n    delete[] temp;\n    std::pair<float, uint32_t> stats = statistics();\n\n    /* The node array was allocated conservatively and now contains\n       many unused entries -- do a compactification pass. */\n    std::vector<BVHNode> compactified(stats.second);\n    std::vector<uint32_t> skipped_accum(m_nodes.size());\n\n    for (int64_t i = stats.second-1, j = m_nodes.size(), skipped = 0; i >= 0; --i) {\n        while (m_nodes[--j].isUnused())\n            skipped++;\n        BVHNode &new_node = compactified[i];\n        new_node = m_nodes[j];\n        skipped_accum[j] = (uint32_t) skipped;\n\n        if (new_node.isInner()) {\n            new_node.inner.rightChild = (uint32_t)\n                (i + new_node.inner.rightChild - j -\n                (skipped - skipped_accum[new_node.inner.rightChild]));\n        }\n    }\n    /*cout << \"done (took \" << timer.elapsedString() << \" and \"\n        << memString(sizeof(BVHNode) * m_nodes.size() + sizeof(uint32_t)*m_indices.size())\n        << \", SAH cost = \" << stats.first\n        << \").\" << endl;*/\n\n    m_nodes = std::move(compactified);\n}\n\nstd::pair<float, uint32_t> Accel::statistics(uint32_t node_idx) const {\n    const BVHNode &node = m_nodes[node_idx];\n    if (node.isLeaf()) {\n        return std::make_pair((float) BVHBuildTask::INTERSECTION_COST * node.leaf.size, 1u);\n    } else {\n        std::pair<float, uint32_t> stats_left = statistics(node_idx + 1u);\n        std::pair<float, uint32_t> stats_right = statistics(node.inner.rightChild);\n        float saLeft = m_nodes[node_idx + 1u].bbox.getSurfaceArea();\n        float saRight = m_nodes[node.inner.rightChild].bbox.getSurfaceArea();\n        float saCur = node.bbox.getSurfaceArea();\n        float sahCost =\n            2 * BVHBuildTask::TRAVERSAL_COST +\n            (saLeft * stats_left.first + saRight * stats_right.first) / saCur;\n        return std::make_pair(\n            sahCost,\n            stats_left.second + stats_right.second + 1u\n        );\n    }\n}\n\nbool Accel::rayIntersect(const Ray3f &_ray, Intersection &its, bool shadowRay) const {\n    uint32_t node_idx = 0, stack_idx = 0, stack[64];\n\n    its.t = std::numeric_limits<float>::infinity();\n\n    /* Use an adaptive ray epsilon */\n    Ray3f ray(_ray);\n    if (ray.mint == Epsilon)\n        ray.mint = std::max(ray.mint, ray.mint * ray.o.array().abs().maxCoeff());\n\n    if (m_nodes.empty() || ray.maxt < ray.mint)\n        return false;\n\n    bool foundIntersection = false;\n    uint32_t f = 0;\n\n    while (true) {\n        const BVHNode &node = m_nodes[node_idx];\n\n        if (!node.bbox.rayIntersect(ray)) {\n            if (stack_idx == 0)\n                break;\n            node_idx = stack[--stack_idx];\n            continue;\n        }\n\n        if (node.isInner()) {\n            stack[stack_idx++] = node.inner.rightChild;\n            node_idx++;\n            assert(stack_idx<64);\n        } else {\n            for (uint32_t i = node.start(), end = node.end(); i < end; ++i) {\n                uint32_t idx = m_indices[i];\n                const Mesh *mesh = m_meshes[findMesh(idx)];\n\n                float u, v, t;\n                if (mesh->rayIntersect(idx, ray, u, v, t)) {\n                    if (shadowRay)\n                        return true;\n                    foundIntersection = true;\n                    ray.maxt = its.t = t;\n                    its.uv = Point2f(u, v);\n                    its.mesh = mesh;\n                    f = idx;\n                }\n            }\n            if (stack_idx == 0)\n                break;\n            node_idx = stack[--stack_idx];\n            continue;\n        }\n    }\n\n    if (foundIntersection) {\n        /* Find the barycentric coordinates */\n        Vector3f bary;\n        bary << 1-its.uv.sum(), its.uv;\n\n        /* References to all relevant mesh buffers */\n        const Mesh *mesh   = its.mesh;\n        const MatrixXf &V  = mesh->getVertexPositions();\n        const MatrixXf &N  = mesh->getVertexNormals();\n        const MatrixXf &UV = mesh->getVertexTexCoords();\n        const MatrixXu &F  = mesh->getIndices();\n\n        /* Vertex indices of the triangle */\n        uint32_t idx0 = F(0, f), idx1 = F(1, f), idx2 = F(2, f);\n\n        Point3f p0 = V.col(idx0), p1 = V.col(idx1), p2 = V.col(idx2);\n\n        /* Compute the intersection positon accurately\n           using barycentric coordinates */\n        its.p = bary.x() * p0 + bary.y() * p1 + bary.z() * p2;\n\n        /* Compute proper texture coordinates if provided by the mesh */\n        if (UV.size() > 0)\n            its.uv = bary.x() * UV.col(idx0),\n                bary.y() * UV.col(idx1),\n                bary.z() * UV.col(idx2);\n\n        /* Compute the geometry frame */\n        its.geoFrame = Frame((p1-p0).cross(p2-p0).normalized());\n\n        if (N.size() > 0) {\n            /* Compute the shading frame. Note that for simplicity,\n               the current implementation doesn't attempt to provide\n               tangents that are continuous across the surface. That\n               means that this code will need to be modified to be able\n               use anisotropic BRDFs, which need tangent continuity */\n\n            its.shFrame = Frame(\n                (bary.x() * N.col(idx0) +\n                 bary.y() * N.col(idx1) +\n                 bary.z() * N.col(idx2)).normalized());\n        } else {\n            its.shFrame = its.geoFrame;\n        }\n    }\n\n    return foundIntersection;\n}\n\nNORI_NAMESPACE_END\n", "meta": {"hexsha": "6375d100f7475744244614a48a914a8687e3d656", "size": 18647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nori-base-2019/src/accel.cpp", "max_stars_repo_name": "TamerMograbi/ShadowNet", "max_stars_repo_head_hexsha": "99a9fb4522546e58817bbdd373f63d6996685e21", "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": "nori-base-2019/src/accel.cpp", "max_issues_repo_name": "TamerMograbi/ShadowNet", "max_issues_repo_head_hexsha": "99a9fb4522546e58817bbdd373f63d6996685e21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nori-base-2019/src/accel.cpp", "max_forks_repo_name": "TamerMograbi/ShadowNet", "max_forks_repo_head_hexsha": "99a9fb4522546e58817bbdd373f63d6996685e21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-22T11:55:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-22T11:55:43.000Z", "avg_line_length": 36.7790927022, "max_line_length": 113, "alphanum_fraction": 0.5560680002, "num_tokens": 4589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.029760092440045342, "lm_q1q2_score": 0.013604430950525076}}
{"text": "#ifndef VEXCL_CONSTANTS_HPP\n#define VEXCL_CONSTANTS_HPP\n\n/*\nThe MIT License\n\nCopyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n/**\n * \\file   vexcl/constants.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief  Constants for use in vector expressions.\n */\n\n#include <sstream>\n#include <iomanip>\n#include <string>\n#include <type_traits>\n\n#include <vexcl/backend.hpp>\n\n#include <vexcl/types.hpp>\n#include <vexcl/operations.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/version.hpp>\n\nnamespace vex {\n\n//---------------------------------------------------------------------------\n// std::integral_constant\n//---------------------------------------------------------------------------\ntemplate <class T, T v>\nstruct is_cl_native< std::integral_constant<T, v> > : std::true_type {};\n\nnamespace traits {\n\ntemplate <class T, T v>\nstruct kernel_param_declaration< std::integral_constant<T, v> >\n{\n    static void get(backend::source_generator&,\n            const std::integral_constant<T, v>&,\n            const backend::command_queue&, const std::string &/*prm_name*/,\n            detail::kernel_generator_state_ptr)\n    { }\n};\n\ntemplate <class T, T v>\nstruct partial_vector_expr< std::integral_constant<T, v> >\n{\n    static void get(backend::source_generator &src,\n            const std::integral_constant<T, v>&,\n            const backend::command_queue&, const std::string &/*prm_name*/,\n            detail::kernel_generator_state_ptr)\n    {\n        src << v;\n    }\n};\n\ntemplate <class T, T v>\nstruct kernel_arg_setter< std::integral_constant<T, v> >\n{\n    static void set(const std::integral_constant<T, v>&,\n            backend::kernel&, unsigned/*part*/, size_t/*index_offset*/,\n            detail::kernel_generator_state_ptr)\n    {\n    }\n};\n\n} // namespace traits\n\n//---------------------------------------------------------------------------\n// boost::math::constants wrappers\n//---------------------------------------------------------------------------\ntemplate <class Impl>\nstruct user_constant {\n    typedef typename Impl::value_type value_type;\n};\n\ntemplate <class Impl>\nstruct is_cl_native< user_constant<Impl> > : std::true_type {};\n\nnamespace traits {\n\ntemplate <class Impl>\nstruct kernel_param_declaration< user_constant<Impl> >\n{\n    static void get(backend::source_generator&,\n            const user_constant<Impl>&,\n            const backend::command_queue&, const std::string &/*prm_name*/,\n            detail::kernel_generator_state_ptr)\n    { }\n};\n\ntemplate <class Impl>\nstruct partial_vector_expr< user_constant<Impl> >\n{\n    static void get(backend::source_generator &src,\n            const user_constant<Impl>&,\n            const backend::command_queue&, const std::string &/*prm_name*/,\n            detail::kernel_generator_state_ptr)\n    {\n        src << Impl::get();\n    }\n};\n\ntemplate <class Impl>\nstruct kernel_arg_setter< user_constant<Impl> >\n{\n    static void set(const user_constant<Impl>&,\n            backend::kernel&, unsigned/*part*/, size_t/*index_offset*/,\n            detail::kernel_generator_state_ptr)\n    {\n    }\n};\n\n} // namespace traits\n\n/**\n * Creates user-defined constan functor for use in VexCL expressions.\n * ``value`` will be copied verbatim into kernel source.\n */\n#define VEX_CONSTANT(name, value)                                              \\\n  struct constant_##name {                                                     \\\n    typedef decltype(value) value_type;                                        \\\n    static std::string get() {                                                 \\\n      static const value_type v = value;                                       \\\n      std::ostringstream s;                                                    \\\n      s << \"( \" << std::scientific << std::setprecision(16) << v << \" )\";      \\\n      return s.str();                                                          \\\n    }                                                                          \\\n    decltype(boost::proto::as_expr<vex::vector_domain>(                        \\\n          vex::user_constant<constant_##name>()))                              \\\n    operator()() const {                                                       \\\n      return boost::proto::as_expr<vex::vector_domain>(                        \\\n          vex::user_constant<constant_##name>());                              \\\n    }                                                                          \\\n    operator value_type() const {                                              \\\n      static const value_type v = value;                                       \\\n      return v;                                                                \\\n    }                                                                          \\\n  };                                                                           \\\n  const constant_##name name = {}\n\n/// Mathematical constants.\nnamespace constants {\n\nVEX_CONSTANT( pi, boost::math::constants::pi<double>() );\nVEX_CONSTANT( root_pi, boost::math::constants::root_pi<double>() );\nVEX_CONSTANT( root_half_pi, boost::math::constants::root_half_pi<double>() );\nVEX_CONSTANT( root_two_pi, boost::math::constants::root_two_pi<double>() );\nVEX_CONSTANT( root_ln_four, boost::math::constants::root_ln_four<double>() );\nVEX_CONSTANT( e, boost::math::constants::e<double>() );\nVEX_CONSTANT( half, boost::math::constants::half<double>() );\nVEX_CONSTANT( euler, boost::math::constants::euler<double>() );\nVEX_CONSTANT( root_two, boost::math::constants::root_two<double>() );\nVEX_CONSTANT( ln_two, boost::math::constants::ln_two<double>() );\nVEX_CONSTANT( ln_ln_two, boost::math::constants::ln_ln_two<double>() );\nVEX_CONSTANT( third, boost::math::constants::third<double>() );\nVEX_CONSTANT( twothirds, boost::math::constants::twothirds<double>() );\nVEX_CONSTANT( pi_minus_three, boost::math::constants::pi_minus_three<double>() );\nVEX_CONSTANT( four_minus_pi, boost::math::constants::four_minus_pi<double>() );\nVEX_CONSTANT( two_pi, boost::math::constants::two_pi<double>() );\nVEX_CONSTANT( half_root_two, boost::math::constants::half_root_two<double>() );\nVEX_CONSTANT( exp_minus_half, boost::math::constants::exp_minus_half<double>() );\n#if (BOOST_VERSION >= 105000) || defined(DOXYGEN)\nVEX_CONSTANT( one_div_two_pi, boost::math::constants::one_div_two_pi<double>() );\nVEX_CONSTANT( catalan, boost::math::constants::catalan<double>() );\nVEX_CONSTANT( cbrt_pi, boost::math::constants::cbrt_pi<double>() );\nVEX_CONSTANT( cosh_one, boost::math::constants::cosh_one<double>() );\nVEX_CONSTANT( cos_one, boost::math::constants::cos_one<double>() );\nVEX_CONSTANT( degree, boost::math::constants::degree<double>() );\nVEX_CONSTANT( e_pow_pi, boost::math::constants::e_pow_pi<double>() );\nVEX_CONSTANT( euler_sqr, boost::math::constants::euler_sqr<double>() );\nVEX_CONSTANT( extreme_value_skewness, boost::math::constants::extreme_value_skewness<double>() );\nVEX_CONSTANT( four_thirds_pi, boost::math::constants::four_thirds_pi<double>() );\nVEX_CONSTANT( glaisher, boost::math::constants::glaisher<double>() );\nVEX_CONSTANT( half_pi, boost::math::constants::half_pi<double>() );\nVEX_CONSTANT( khinchin, boost::math::constants::khinchin<double>() );\nVEX_CONSTANT( ln_phi, boost::math::constants::ln_phi<double>() );\nVEX_CONSTANT( ln_ten, boost::math::constants::ln_ten<double>() );\nVEX_CONSTANT( log10_e, boost::math::constants::log10_e<double>() );\nVEX_CONSTANT( one_div_cbrt_pi, boost::math::constants::one_div_cbrt_pi<double>() );\nVEX_CONSTANT( one_div_euler, boost::math::constants::one_div_euler<double>() );\nVEX_CONSTANT( one_div_ln_phi, boost::math::constants::one_div_ln_phi<double>() );\nVEX_CONSTANT( one_div_log10_e, boost::math::constants::one_div_log10_e<double>() );\nVEX_CONSTANT( one_div_root_pi, boost::math::constants::one_div_root_pi<double>() );\nVEX_CONSTANT( one_div_root_two, boost::math::constants::one_div_root_two<double>() );\nVEX_CONSTANT( one_div_root_two_pi, boost::math::constants::one_div_root_two_pi<double>() );\nVEX_CONSTANT( phi, boost::math::constants::phi<double>() );\nVEX_CONSTANT( pi_cubed, boost::math::constants::pi_cubed<double>() );\nVEX_CONSTANT( pi_pow_e, boost::math::constants::pi_pow_e<double>() );\nVEX_CONSTANT( pi_sqr, boost::math::constants::pi_sqr<double>() );\nVEX_CONSTANT( pi_sqr_div_six, boost::math::constants::pi_sqr_div_six<double>() );\nVEX_CONSTANT( radian, boost::math::constants::radian<double>() );\nVEX_CONSTANT( rayleigh_kurtosis, boost::math::constants::rayleigh_kurtosis<double>() );\nVEX_CONSTANT( rayleigh_kurtosis_excess, boost::math::constants::rayleigh_kurtosis_excess<double>() );\nVEX_CONSTANT( rayleigh_skewness, boost::math::constants::rayleigh_skewness<double>() );\nVEX_CONSTANT( root_e, boost::math::constants::root_e<double>() );\nVEX_CONSTANT( root_one_div_pi, boost::math::constants::root_one_div_pi<double>() );\nVEX_CONSTANT( root_three, boost::math::constants::root_three<double>() );\nVEX_CONSTANT( root_two_div_pi, boost::math::constants::root_two_div_pi<double>() );\nVEX_CONSTANT( sinh_one, boost::math::constants::sinh_one<double>() );\nVEX_CONSTANT( sin_one, boost::math::constants::sin_one<double>() );\nVEX_CONSTANT( sixth_pi, boost::math::constants::sixth_pi<double>() );\nVEX_CONSTANT( third_pi, boost::math::constants::third_pi<double>() );\nVEX_CONSTANT( three_quarters, boost::math::constants::three_quarters<double>() );\nVEX_CONSTANT( three_quarters_pi, boost::math::constants::three_quarters_pi<double>() );\nVEX_CONSTANT( two_div_pi, boost::math::constants::two_div_pi<double>() );\nVEX_CONSTANT( two_thirds, boost::math::constants::two_thirds<double>() );\nVEX_CONSTANT( two_thirds_pi, boost::math::constants::two_thirds_pi<double>() );\nVEX_CONSTANT( zeta_three, boost::math::constants::zeta_three<double>() );\nVEX_CONSTANT( zeta_two, boost::math::constants::zeta_two<double>() );\n#endif\n\n\n} //namespace constants\n\n} // namespace vex\n\n#endif\n", "meta": {"hexsha": "ccedb3152abafafc248cca7c6ca82df42cb57dad", "size": 10947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/vexcl/constants.hpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/vexcl/constants.hpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/vexcl/constants.hpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 45.4232365145, "max_line_length": 101, "alphanum_fraction": 0.6406321367, "num_tokens": 2450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.03308597993800343, "lm_q1q2_score": 0.01360200644914825}}
{"text": "/* \n * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/xtp/kmccalculator.h>\n#include <votca/xtp/gnode.h>\n#include <votca/tools/constants.h>\n#include <boost/format.hpp>\n#include <votca/ctp/topology.h>\n#include <locale>\n\nusing namespace std;\n\nnamespace votca {\n    namespace xtp {\n        \n        KMCCalculator::KMCCalculator(){};\n\n    void KMCCalculator::LoadGraph(ctp::Topology *top) {\n\n        std::vector< ctp::Segment* >& seg = top->Segments();\n        \n        if(seg.size()<1){\n          throw std::runtime_error(\"Your sql file contains no segments!\");\n        }\n        \n        for (unsigned i = 0; i < seg.size(); i++) {\n            GNode *newNode = new GNode();\n            newNode->ReadfromSegment(seg[i], _carriertype);\n            if (tools::wildcmp(_injection_name.c_str(), seg[i]->getName().c_str())) {\n                newNode->injectable = true;\n            } else {\n                newNode->injectable = false;\n            }\n            _nodes.push_back(newNode);\n        }\n\n        ctp::QMNBList &nblist = top->NBList();\n        if(nblist.size()<1){\n          throw std::runtime_error(\"Your sql file contains no pairs!\");    \n        }\n        \n        \n        for (ctp::QMNBList::iterator it = nblist.begin(); it < nblist.end(); ++it) {\n            _nodes[(*it)->Seg1()->getId()-1]->AddEventfromQmPair(*it, _carriertype);\n            _nodes[(*it)->Seg2()->getId()-1]->AddEventfromQmPair(*it, _carriertype);\n        }\n        \n        unsigned events=0;\n        unsigned max=std::numeric_limits<unsigned>::min();\n        unsigned min=std::numeric_limits<unsigned>::max();\n        minlength=std::numeric_limits<double>::max();\n        double maxlength=0;\n        for(const auto& node:_nodes){\n            \n            unsigned size=node->events.size();\n            for( const auto& event:node->events){\n                if(event.decayevent){continue;}\n                double dist=abs(event.dr);\n                if(dist>maxlength){\n                    maxlength=dist;\n                } else if(dist<minlength){\n                    minlength=dist;        \n                }\n            }\n            \n            events+=size;\n            if(size==0){\n                cout<<\"Node \"<<node->id<<\" has 0 jumps\"<<endl;\n            }\n            else if(size<min){\n                min=size;\n            }\n            else if(size>max){\n                max=size;\n            }\n        }\n        double avg=double(events)/double(_nodes.size());\n        double deviation=0.0;\n        for(const auto& node:_nodes){\n            double size=node->events.size();\n            deviation+=(size-avg)*(size-avg);\n        }\n        deviation=std::sqrt(deviation/double(_nodes.size()));\n        \n        cout<<\"Nblist has \"<<nblist.size()<<\" pairs. Nodes contain \"<<events<<\" jump events\"<<endl;\n        cout<<\"with avg=\"<<avg<<\" std=\"<<deviation<<\" max=\"<<max<<\" min=\"<<min<<endl;\n        cout<<\"Minimum jumpdistance =\"<<minlength<<\" nm Maximum distance =\"<<maxlength<<\" nm\"<<endl;\n        cout<<\"Grouping into \"<<lengthdistribution<<\" boxes\"<<endl;\n        lengthresolution=(1.00001*maxlength-minlength)/double(lengthdistribution);\n        cout<<\"Resolution is \"<<lengthresolution<<\" nm\"<<endl;   \n       \n        _jumplengthdistro=std::vector<long unsigned>(lengthdistribution,0);\n        _jumplengthdistro_weighted=std::vector<double>(lengthdistribution,0);\n\n       \n        cout << \"spatial density: \" << _numberofcharges / top->BoxVolume() << \" nm^-3\" << endl;\n\n        for (unsigned int i = 0; i < _nodes.size(); i++) {\n            _nodes[i]->InitEscapeRate();\n        }\n            \n        return;\n    }\n    \n\n        void KMCCalculator::ResetForbiddenlist(std::vector<int> &forbiddenid) {\n            forbiddenid.clear();\n            return;\n        }\n\n        void KMCCalculator::AddtoForbiddenlist(int id, std::vector<int> &forbiddenid) {\n            forbiddenid.push_back(id);\n            return;\n        }\n\n        bool KMCCalculator::CheckForbidden(int id,const std::vector<int> &forbiddenlist) {\n            // cout << \"forbidden list has \" << forbiddenlist.size() << \" entries\" << endl;\n            bool forbidden = false;\n            for (unsigned int i = 0; i < forbiddenlist.size(); i++) {\n                if (id == forbiddenlist[i]) {\n                    forbidden = true;\n                    //cout << \"ID \" << id << \" has been found as element \" << i << \" (\" << forbiddenlist[i]<< \") in the forbidden list.\" << endl;\n                    break;\n                }\n            }\n            return forbidden;\n        }\n\n        bool KMCCalculator::CheckSurrounded(GNode* node,const std::vector<int> & forbiddendests) {\n            bool surrounded = true;\n            for (unsigned  i = 0; i < node->events.size(); i++) {\n                bool thisevent_possible = true;\n                for (unsigned int j = 0; j < forbiddendests.size(); j++) {\n                    if (node->events[i].destination == forbiddendests[j]) {\n                        thisevent_possible = false;\n                        break;\n                    }\n                }\n                if (thisevent_possible == true) {\n                    surrounded = false;\n                    break;\n                }\n            }\n            return surrounded;\n        }\n\n        \n        \n        \n        std::string KMCCalculator::CarrierInttoLongString(int carriertype){\n            std::string name=\"\";\n            if (carriertype==-1){\n                name=\"electron\";\n            }\n            else if(carriertype==1){\n                name=\"hole\";\n            }\n            else if(carriertype==2){\n                name=\"singlet\";\n            }\n            else if(carriertype==3){\n                name=\"triplet\";\n            }\n            else{\n                throw runtime_error((boost::format(\"Carriertype %i not known\") % carriertype).str());\n            }\n            return name;\n        }\n        \n        std::string KMCCalculator::CarrierInttoShortString(int carriertype){\n            std::string name=\"\";\n            if (carriertype==-1){\n                name=\"e\";\n            }\n            else if(carriertype==1){\n                name=\"h\";\n            }\n            else if(carriertype==2){\n                name=\"s\";\n            }\n            else if(carriertype==3){\n                name=\"t\";\n            }\n            else{\n                throw runtime_error((boost::format(\"Carriertype %i not known\") % carriertype).str());\n            }\n            return name;\n        }\n        \n         int KMCCalculator::StringtoCarriertype(std::string name){\n             char firstcharacter=std::tolower(name.at(0), std::locale());\n             int carriertype=0;\n            if (firstcharacter=='e'){\n                carriertype=-1;\n            }\n            else if(firstcharacter=='h'){\n                carriertype=1;\n            }\n            else if(firstcharacter=='s'){\n                carriertype=2;\n            }\n            else if(firstcharacter=='t'){\n                carriertype=3;\n            }\n            else{\n                throw runtime_error((boost::format(\"Carriername %s not known\") % name).str());\n            }\n            return carriertype;\n        }\n         \n         \n         void KMCCalculator::RandomlyCreateCharges(){\n         \n        \n        cout << \"looking for injectable nodes...\" << endl;\n        for (unsigned int i = 0; i < _numberofcharges; i++) {\n            Chargecarrier *newCharge = new Chargecarrier;\n            newCharge->id = i;\n            RandomlyAssignCarriertoSite(newCharge);\n            \n            cout << \"starting position for charge \" << i + 1 << \": segment \" << newCharge->getCurrentNodeId()+1 << endl;\n            _carriers.push_back(newCharge);\n        }\n        return;\n         }\n         \n         void KMCCalculator::RandomlyAssignCarriertoSite(Chargecarrier* Charge){\n            int nodeId_guess=-1;\n            do{\n            nodeId_guess=_RandomVariable.rand_uniform_int(_nodes.size());   \n            }\n            while (_nodes[nodeId_guess]->occupied || _nodes[nodeId_guess]->injectable==false ); // maybe already occupied? or maybe not injectable?\n            if (Charge->hasNode()){\n                Charge->jumpfromCurrentNodetoNode(_nodes[nodeId_guess]);\n            }\n            else{\n            Charge->settoNote(_nodes[nodeId_guess]);\n            }\n             return;\n         }\n        \n        void KMCCalculator::InitialRates() {\n            \n            cout << endl << \"Calculating initial Marcus rates.\" << endl;\n            cout << \"    Temperature T = \" << _temperature << \" K.\" << endl;\n           \n            cout << \"    carriertype: \" << CarrierInttoLongString(_carriertype) << endl;\n            unsigned numberofsites = _nodes.size();\n            cout << \"    Rates for \" << numberofsites << \" sites are computed.\" << endl;\n            double charge=0.0;\n            if (_carriertype == -1)\n            {\n                charge = -1.0;\n            }\n            else if (_carriertype == 1)\n            {\n                charge = 1.0;\n            }\n            cout<<\"electric field =\"<<_field<<\" V/nm\"<<endl;\n            \n            double maxreldiff = 0;\n            double maxrate=0;\n            double minrate=std::numeric_limits<double>::max();\n            int totalnumberofrates = 0;\n            for (unsigned int i = 0; i < numberofsites; i++) {\n                unsigned numberofneighbours = _nodes[i]->events.size();\n                for (unsigned int j = 0; j < numberofneighbours; j++) {\n                    if(_nodes[i]->events[j].decayevent){\n                        //if event is a decay event there is no point in calculating its rate, because it already has that from the reading in.\n                        continue;\n                    }\n\n                    double destindex = _nodes[i]->events[j].destination;\n                    double reorg = _nodes[i]->reorg_intorig + _nodes[destindex]->reorg_intdest + _nodes[i]->events[j].reorg_out;\n                     if(std::abs(reorg)<1e-12){\n                        throw std::runtime_error(\"Reorganisation energy for a pair is extremly close to zero,\\n\"\n                                \" you probably forgot to import reorganisation energies into your sql file.\");\n                    }\n                    double dG_Field =0.0;\n                    if(charge!=0.0){\n                        dG_Field=charge * (_nodes[i]->events[j].dr*_field);\n                    }\n                    double dG_Site = _nodes[destindex]->siteenergy - _nodes[i]->siteenergy;\n                    double dG=dG_Site-dG_Field;\n                    double J2 = _nodes[i]->events[j].Jeff2;\n\n                    double rate = 2 * tools::conv::Pi / tools::conv::hbar * J2 / sqrt(4 * tools::conv::Pi * reorg * tools::conv::kB * _temperature) \n                    * exp(-(dG + reorg)*(dG + reorg) / (4 * reorg * tools::conv::kB * _temperature));\n\n                    // calculate relative difference compared to values in the table\n                    double reldiff = (_nodes[i]->events[j].rate - rate) / _nodes[i]->events[j].rate;\n                    if (reldiff > maxreldiff) {\n                        maxreldiff = reldiff;\n                    }\n                    reldiff = (_nodes[i]->events[j].rate - rate) / rate;\n                    if (reldiff > maxreldiff) {\n                        maxreldiff = reldiff;\n                    }\n\n                    // set rates to calculated values\n                    _nodes[i]->events[j].rate = rate;\n                    _nodes[i]->events[j].initialrate = rate;\n                    \n                    if(rate>maxrate){\n                        maxrate=rate;\n                    }\n                    else if(rate<minrate){\n                        minrate=rate;\n                    }\n\n                    totalnumberofrates++;\n                }\n\n                // Initialise escape rates\n                for (unsigned int i = 0; i < _nodes.size(); i++) {\n                    _nodes[i]->InitEscapeRate();\n                }\n\n            }\n            \n            cout << \"    \" << totalnumberofrates << \" rates have been calculated.\" << endl;\n            cout<< \" Largest rate=\"<<maxrate<<\" 1/s  Smallest rate=\"<<minrate<<\" 1/s\"<<endl;\n            if (maxreldiff < 0.01) {\n                cout << \"    Good agreement with rates in the state file. Maximal relative difference: \" << maxreldiff * 100 << \" %\" << endl;\n            } else {\n                cout << \"    WARNING: Rates differ from those in the state file up to \" << maxreldiff * 100 << \" %.\" << \" If the rates in the state file are calculated for a different temperature/field or if they are not Marcus rates, this is fine. Otherwise something might be wrong here.\" << endl;\n            }\n            \n            return;\n        }\n        \n        \n        \n        \n        double KMCCalculator::Promotetime(double cumulated_rate){\n            double dt = 0;\n                double rand_u = 1 - _RandomVariable.rand_uniform();\n                while (rand_u == 0) {\n                    cout << \"WARNING: encountered 0 as a random variable! New try.\" << endl;\n                    rand_u = 1 - _RandomVariable.rand_uniform();\n                }\n                dt = -1 / cumulated_rate * log(rand_u);\n            return dt;\n        }\n        \n        \n        GLink* KMCCalculator::ChooseHoppingDest(GNode* node){\n            double u = 1 - _RandomVariable.rand_uniform();\n            \n            for (unsigned int j = 0; j < node->events.size(); j++) {\n                u -= node->events[j].rate / node->getEscapeRate();\n                if (u <= 0 || j==node->events.size()-1) {    \n                    return &(node->events[j]);\n                }\n            }\n            throw runtime_error(\"Choose Hopping Destination, somehow no event was found\");\n            return NULL;\n        }\n        \n        Chargecarrier* KMCCalculator::ChooseAffectedCarrier(double cumulated_rate){\n            if(_carriers.size()==1){\n                return _carriers[0];\n            }\n            Chargecarrier* carrier=NULL;\n            double u = 1 - _RandomVariable.rand_uniform();\n            for (unsigned int i = 0; i < _numberofcharges; i++) {\n                u -= _carriers[i]->getCurrentEscapeRate() / cumulated_rate;\n\n                if (u <= 0 || i==_numberofcharges-1) {\n\n                    carrier = _carriers[i];\n                    break;}  \n\n            }\n            return carrier;\n        }\n        \n        void KMCCalculator::AddtoJumplengthdistro(const GLink* event,double dt){\n            if(dolengthdistributon){\n            double dist=abs(event->dr)-minlength;\n            int index=int(dist/lengthresolution);\n           \n            _jumplengthdistro[index]++;\n            _jumplengthdistro_weighted[index]+=dt;\n           \n            \n            }\n            return; \n        }\n        \n        void KMCCalculator::PrintJumplengthdistro(){\n            if(dolengthdistributon){\n            long unsigned noofjumps=0;\n            \n            double weightedintegral=0;\n            for(unsigned i=0;i<_jumplengthdistro.size();++i){\n                noofjumps+=_jumplengthdistro[i];   \n                weightedintegral+=_jumplengthdistro_weighted[i];\n            }\n            double noofjumps_double=double(noofjumps);\n            cout<<\"Total number of jumps: \"<<noofjumps<<endl;\n            cout<<\" distance[nm] |   # of jumps   | # of jumps [%] | .w. by dist [nm] | w. by timestep [%]\"<<endl;\n            cout<<\"------------------------------------------------------------------------------------\"<<endl;\n            for(unsigned i=0;i<_jumplengthdistro.size();++i){\n                double dist=lengthresolution*(i+0.5)+minlength;\n                double percent=_jumplengthdistro[i]/noofjumps_double;\n                double rtimespercent=percent*dist;\n                cout<<(boost::format(\"    %4.3f    | %15d |    %04.2f    |     %4.3e     |     %04.2f\")\n                            % (dist) % (_jumplengthdistro[i]) % (percent*100) %(rtimespercent) % (_jumplengthdistro_weighted[i]/weightedintegral*100)).str()<<endl;                \n            }\n            cout<<\"------------------------------------------------------------------------------------\"<<endl;\n           \n            }\n            return;\n        }\n \n        \n    }\n}\n", "meta": {"hexsha": "0706fec8f9b440ceda9a8b66c36cf55db2cdca07", "size": 16894, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/kmccalculator.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/kmccalculator.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/kmccalculator.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9262672811, "max_line_length": 299, "alphanum_fraction": 0.4870960104, "num_tokens": 3740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473339755162, "lm_q2_score": 0.03161877080465265, "lm_q1q2_score": 0.013600729965204223}}
{"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_DISCRETEPROBLEM_HH\n#define DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH\n\n#include <memory>\n#include <limits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/stuff/common/disable_warnings.hh>\n# include <dune/common/mpihelper.hh>\n# include <dune/common/timer.hh>\n\n# if HAVE_DUNE_FEM\n#   include <dune/fem/misc/mpimanager.hh>\n# endif\n#include <dune/stuff/common/reenable_warnings.hh>\n\n#if HAVE_DUNE_GRID_MULTISCALE\n# include <dune/grid/multiscale/provider.hh>\n#endif\n\n#include <dune/stuff/common/configuration.hh>\n#include <dune/stuff/common/logging.hh>\n#include <dune/stuff/common/string.hh>\n#include <dune/stuff/grid/provider.hh>\n#include <dune/stuff/grid/boundaryinfo.hh>\n#include <dune/stuff/common/configuration.hh>\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/grid/layers.hh>\n#include <dune/stuff/common/memory.hh>\n\n#include \"problems.hh\"\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\n\n\ntemplate< class GridImp >\nclass DiscreteProblem\n{\npublic:\n  typedef GridImp GridType;\n  typedef Stuff::Grid::ProviderInterface< GridType >  GridProviderType;\nprivate:\n  typedef Stuff::GridProviders< GridType > GridProviders;\n  typedef typename GridType::LeafIntersection IntersectionType;\n  typedef Stuff::Grid::BoundaryInfoProvider< IntersectionType > BoundaryInfoProvider;\n  typedef typename GridType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridType::ctype DomainFieldType;\n  static const unsigned int dimDomain = GridType::dimension;\npublic:\n  typedef double RangeFieldType;\n  static const unsigned int dimRange = 1;\n  typedef LinearElliptic::ProblemInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;\n  typedef LinearElliptic::ProblemsProvider< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemsProvider;\n\n  static void write_config(const std::string filename, const std::string id)\n  {\n    std::ofstream file;\n    file.open(filename);\n    file << \"[\" << id << \"]\" << std::endl;\n    write_keys_to_file(\"gridprovider\", GridProviders::available(), file);\n    write_keys_to_file(\"boundaryinfo\", BoundaryInfoProvider::available(), file);\n    write_keys_to_file(\"problem\", ProblemsProvider::available(), file);\n    file << \"[logging]\" << std::endl;\n    file << \"info  = true\" << std::endl;\n    file << \"debug = true\" << std::endl;\n    file << \"file  = false\" << std::endl;\n    file << \"visualize = true\" << std::endl;\n    file << \"[parameter]\" << std::endl;\n    file << \"0.diffusion_factor = [0.1 0.1 1.0 1.0]\" << std::endl;\n    file << \"1.diffusion_factor = [1.0 1.0 0.1 0.1]\" << std::endl;\n    write_config_to_file< GridProviders >(file);\n    write_config_to_file< BoundaryInfoProvider >(file);\n    write_config_to_file< ProblemsProvider >(file);\n    file.close();\n  } // ... write_config(...)\n\n  DiscreteProblem(const std::string id, const std::vector< std::string >& arguments)\n  {\n    // mpi\n    assert(arguments.size() < std::numeric_limits< int >::max());\n    int argc = boost::numeric_cast< int >(arguments.size());\n    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);\n#if HAVE_DUNE_FEM\n    Fem::MPIManager::initialize(argc, argv);\n#else\n    MPIHelper::instance(argc, argv);\n#endif\n\n    // configuration\n    config_ = Stuff::Common::Configuration(argc, argv, id + \".cfg\");\n    if (!config_.has_sub(id))\n      DUNE_THROW(Stuff::Exceptions::configuration_error,\n                 \"Missing sub '\" << id << \"' in the following Configuration:\\n\\n\" << config_);\n    filename_ = config_.get(id + \".filename\", id);\n\n    // logger\n    const Stuff::Common::Configuration logger_config = config_.sub(\"logging\");\n    int log_flags = Stuff::Common::LOG_CONSOLE;\n    debug_logging_ = logger_config.get< bool >(\"debug\", false);\n    if (logger_config.get< bool >(\"info\"))\n      log_flags = log_flags | Stuff::Common::LOG_INFO;\n    if (debug_logging_)\n      log_flags = log_flags | Stuff::Common::LOG_DEBUG;\n    if (logger_config.get< bool >(\"file\", false))\n      log_flags = log_flags | Stuff::Common::LOG_FILE;\n    Stuff::Common::Logger().create(log_flags, id, \"\", \"\");\n    auto& info  = Stuff::Common::Logger().info();\n\n    Timer timer;\n    const std::string griprovider_type = config_.get< std::string >(id + \".gridprovider\");\n    info << \"creating grid with '\" << griprovider_type << \"'... \" << std::flush;\n    grid_provider_ = GridProviders::create(griprovider_type, config_);\n    const auto grid_view = grid_provider_->leaf_view();\n    info << \" done (took \" << timer.elapsed()\n         << \"s, has \" << grid_view.indexSet().size(0) << \" element\";\n    if (grid_view.indexSet().size(0) > 1)\n      info << \"s\";\n    info << \")\" << std::endl;\n\n    const std::string boundary_info_type = config_.get< std::string >(id + \".boundaryinfo\");\n    if (config_.has_sub(boundary_info_type))\n      boundary_info_ = config_.sub(boundary_info_type);\n    else\n      boundary_info_ = Stuff::Common::Configuration(\"type\", boundary_info_type);\n\n    info << \"setting up \";\n    timer.reset();\n    const std::string problem_type = config_.get< std::string >(id + \".problem\");\n    if (!debug_logging_)\n      info << \"'\" << problem_type << \"'... \" << std::flush;\n    problem_ = ProblemsProvider::create(problem_type, config_);\n    if (debug_logging_)\n      info << *problem_ << std::endl;\n    else\n      info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n\n    if (logger_config.get(\"visualize\", true)) {\n      info << \"visualizing grid and problem... \" << std::flush;\n      timer.reset();\n      grid_provider_->visualize(boundary_info_, filename_ + \".grid\");\n      problem_->visualize(grid_view, filename_ + \".problem\");\n      info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n    } // if (visualize)\n  } // DiscreteProblem\n\n  std::string filename() const\n  {\n    return filename_;\n  }\n\n  const Stuff::Common::Configuration& config() const\n  {\n    return config_;\n  }\n\n  bool debug_logging() const\n  {\n    return debug_logging_;\n  }\n\n  GridProviderType& grid_provider()\n  {\n    return *grid_provider_;\n  }\n\n  const GridProviderType& grid_provider() const\n  {\n    return *grid_provider_;\n  }\n\n  const Stuff::Common::Configuration& boundary_info() const\n  {\n    return boundary_info_;\n  }\n\n  const ProblemType& problem() const\n  {\n    return *problem_;\n  }\n\nprivate:\n  static void write_keys_to_file(const std::string name, const std::vector< std::string > keys, std::ofstream& file)\n  {\n    std::string whitespace = Stuff::Common::whitespaceify(name + \" = \");\n    file << name << \" = \" << keys[0] << std::endl;\n    for (size_t ii = 1; ii < keys.size(); ++ii)\n      file << whitespace << keys[ii] << std::endl;\n  } // ... write_keys_to_file(...)\n\n  template< class ConfigProvider >\n  static void write_config_to_file(std::ofstream& file)\n  {\n    for (const auto& type : ConfigProvider::available()) {\n      auto config = ConfigProvider::default_config(type, type);\n      if (!config.empty())\n      file << config;\n    }\n  } // ... write_config_to_file(...)\n\n  std::string filename_;\n  Stuff::Common::Configuration config_;\n  bool debug_logging_;\n  std::unique_ptr< GridProviderType > grid_provider_;\n  Stuff::Common::Configuration boundary_info_;\n  std::unique_ptr< const ProblemType > problem_;\n}; // class DiscreteProblem\n\n\n#if HAVE_DUNE_GRID_MULTISCALE\n\n\ntemplate< class GridImp >\nclass DiscreteBlockProblem\n{\npublic:\n  typedef GridImp GridType;\n  typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType;\n  typedef grid::Multiscale::MsGridProviders< GridType > GridProviders;\n  typedef typename GridType::LeafIntersection IntersectionType;\n  typedef Stuff::Grid::BoundaryInfoProvider< IntersectionType > BoundaryInfoProvider;\n  typedef typename GridType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridType::ctype DomainFieldType;\n  static const unsigned int dimDomain = GridType::dimension;\n  typedef double RangeFieldType;\n  static const unsigned int dimRange = 1;\n  typedef LinearElliptic::ProblemInterface\n      < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;\n  typedef LinearElliptic::ProblemsProvider\n      < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemsProvider;\n\n  static void write_config(const std::string filename,\n                           const std::string id,\n                           const Stuff::Common::Configuration& problem_cfg = Stuff::Common::Configuration(),\n                           const Stuff::Common::Configuration& grid_cfg = Stuff::Common::Configuration(),\n                           const Stuff::Common::Configuration& additional_cfg = Stuff::Common::Configuration())\n  {\n    std::ofstream file;\n    file.open(filename);\n    file << \"[\" << id << \"]\" << std::endl;\n    if (grid_cfg.has_key(\"type\"))\n      file << \"gridprovider = \" << grid_cfg.get< std::string >(\"type\") << std::endl;\n    else\n      write_keys_to_file(\"gridprovider\", GridProviders::available(), file);\n    if (problem_cfg.has_key(\"type\"))\n      file << \"problem = \" << problem_cfg.get< std::string >(\"type\") << std::endl;\n    else\n      write_keys_to_file(\"problem\", ProblemsProvider::available(), file);\n    file << \"[logging]\" << std::endl;\n    file << \"info  = true\" << std::endl;\n    file << \"debug = false\" << std::endl;\n    file << \"file  = false\" << std::endl;\n    file << \"visualize = true\" << std::endl;\n    if (grid_cfg.has_key(\"type\"))\n      file << Stuff::Common::Configuration(grid_cfg, grid_cfg.get< std::string >(\"type\"));\n    else\n      write_config_to_file< GridProviders >(file);\n    if (problem_cfg.has_key(\"type\"))\n      file << Stuff::Common::Configuration(problem_cfg, problem_cfg.get< std::string >(\"type\"));\n    else\n      write_config_to_file< ProblemsProvider >(file);\n    file << additional_cfg;\n    file.close();\n  } // ... write_config(...)\n\n  DiscreteBlockProblem(const std::string id, const std::vector< std::string >& arguments)\n  {\n    // mpi\n    int argc = boost::numeric_cast< int >(arguments.size());\n    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);\n#if HAVE_DUNE_FEM\n    Fem::MPIManager::initialize(argc, argv);\n#else\n    MPIHelper::instance(argc, argv);\n#endif\n\n    // configuration\n    config_ = Stuff::Common::Configuration(argc, argv, id + \".cfg\");\n    if (!config_.has_sub(id))\n      DUNE_THROW(Stuff::Exceptions::configuration_error,\n                 \"Missing sub '\" << id << \"' in the following Configuration:\\n\\n\" << config_);\n    filename_ = config_.get(id + \".filename\", id);\n\n    // logger\n    const Stuff::Common::Configuration logger_config = config_.sub(\"logging\");\n    int log_flags = Stuff::Common::LOG_CONSOLE;\n    debug_logging_ = logger_config.get< bool >(\"debug\", false);\n    if (logger_config.get< bool >(\"info\"))\n      log_flags = log_flags | Stuff::Common::LOG_INFO;\n    if (debug_logging_)\n      log_flags = log_flags | Stuff::Common::LOG_DEBUG;\n    if (logger_config.get< bool >(\"file\", false))\n      log_flags = log_flags | Stuff::Common::LOG_FILE;\n    Stuff::Common::Logger().create(log_flags, id, \"\", \"\");\n    auto& info  = Stuff::Common::Logger().info();\n\n    Timer timer;\n    const std::string griprovider_type = config_.get< std::string >(id + \".gridprovider\");\n    info << \"creating grid with '\" << griprovider_type << \"'...\" << std::flush;\n    grid_provider_ = GridProviders::create(griprovider_type, config_);\n    const auto grid_view = grid_provider_->leaf_view();\n    info << \" done (took \" << timer.elapsed()\n         << \"s, has \" << grid_view.indexSet().size(0) << \" element\";\n    if (grid_view.indexSet().size(0) > 1)\n      info << \"s\";\n    info << \")\" << std::endl;\n\n    boundary_info_ = Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config();\n\n//    info << \"setting up \";\n//    timer.reset();\n    const std::string problem_type = config_.get< std::string >(id + \".problem\");\n//    if (!debug_logging_)\n//      info << \"'\" << problem_type << \"'... \" << std::flush;\n    problem_ = ProblemsProvider::create(problem_type, config_);\n//    if (debug_logging_)\n//      info << *problem_ << std::endl;\n//    else\n//      info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n\n    if (logger_config.get(\"visualize\", true)) {\n      info << \"visualizing grid and problem... \" << std::flush;\n      timer.reset();\n      grid_provider_->visualize(filename_ + \".ms_grid\", false);\n      grid_provider_->visualize(boundary_info_, filename_ + \".grid\");\n      problem_->visualize(grid_view, filename_ + \".problem\");\n      info << \"done (took \" << timer.elapsed() << \"s)\" << std::endl;\n    } // if (visualize)\n  } // DiscreteBlockProblem\n\n  std::string filename() const\n  {\n    return filename_;\n  }\n\n  const Stuff::Common::Configuration& config() const\n  {\n    return config_;\n  }\n\n  bool debug_logging() const\n  {\n    return debug_logging_;\n  }\n\n  GridProviderType& grid_provider()\n  {\n    return *grid_provider_;\n  }\n\n  const GridProviderType& grid_provider() const\n  {\n    return *grid_provider_;\n  }\n\n  const Stuff::Common::Configuration& boundary_info() const\n  {\n    return boundary_info_;\n  }\n\n  const ProblemType& problem() const\n  {\n    return *problem_;\n  }\n\nprivate:\n  static void write_keys_to_file(const std::string name, const std::vector< std::string > keys, std::ofstream& file)\n  {\n    std::string whitespace = Stuff::Common::whitespaceify(name + \" = \");\n    file << name << \" = \" << keys[0] << std::endl;\n    for (size_t ii = 1; ii < keys.size(); ++ii)\n      file << whitespace << keys[ii] << std::endl;\n  } // ... write_keys_to_file(...)\n\n  template< class ConfigProvider >\n  static void write_config_to_file(std::ofstream& file)\n  {\n    for (const auto& type : ConfigProvider::available()) {\n      auto config = ConfigProvider::default_config(type, type);\n      if (!config.empty())\n      file << config;\n    }\n  } // ... write_config_to_file(...)\n\n  std::string filename_;\n  Stuff::Common::Configuration config_;\n  bool debug_logging_;\n  std::unique_ptr< GridProviderType > grid_provider_;\n  Stuff::Common::Configuration boundary_info_;\n  std::unique_ptr< const ProblemType > problem_;\n}; // class DiscreteBlockProblem\n\n\n#endif // HAVE_DUNE_GRID_MULTISCALE\n\n\n} // namespace LinearElliptic\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH\n", "meta": {"hexsha": "c6d16090d4b50170b20214d663036fdd6c2a0041", "size": 14482, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/discreteproblem.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/discreteproblem.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/discreteproblem.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": 35.4083129584, "max_line_length": 128, "alphanum_fraction": 0.6659301201, "num_tokens": 3631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.054198726385852526, "lm_q1q2_score": 0.013599153483106608}}
{"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#ifndef BOOST_GRAPH_UNDIRECTED_DFS_HPP\n#define BOOST_GRAPH_UNDIRECTED_DFS_HPP\n\n#include <boost/graph/depth_first_search.hpp>\n\nnamespace boost {\n\n  namespace detail {\n\n    template <typename IncidenceGraph, typename DFSVisitor, \n              typename VertexColorMap, typename EdgeColorMap>\n    void undir_dfv_impl\n      (const IncidenceGraph& g,\n       typename graph_traits<IncidenceGraph>::vertex_descriptor u, \n       DFSVisitor& vis,  // pass-by-reference here, important!\n       VertexColorMap vertex_color,\n       EdgeColorMap edge_color)\n    {\n      function_requires<IncidenceGraphConcept<IncidenceGraph> >();\n      function_requires<DFSVisitorConcept<DFSVisitor, IncidenceGraph> >();\n      typedef typename graph_traits<IncidenceGraph>::vertex_descriptor Vertex;\n      typedef typename graph_traits<IncidenceGraph>::edge_descriptor Edge;\n      function_requires<ReadWritePropertyMapConcept<VertexColorMap,Vertex> >();\n      function_requires<ReadWritePropertyMapConcept<EdgeColorMap,Edge> >();\n      typedef typename property_traits<VertexColorMap>::value_type ColorValue;\n      typedef typename property_traits<EdgeColorMap>::value_type EColorValue;\n      function_requires< ColorValueConcept<ColorValue> >();\n      function_requires< ColorValueConcept<EColorValue> >();\n      typedef color_traits<ColorValue> Color;\n      typedef color_traits<EColorValue> EColor;\n      typename graph_traits<IncidenceGraph>::out_edge_iterator ei, ei_end;\n\n      put(vertex_color, u, Color::gray());   vis.discover_vertex(u, g);\n      for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {\n        Vertex v = target(*ei, g);           vis.examine_edge(*ei, g);\n        ColorValue v_color = get(vertex_color, v);\n        EColorValue uv_color = get(edge_color, *ei);\n        put(edge_color, *ei, EColor::black());\n        if (v_color == Color::white()) {     vis.tree_edge(*ei, g);\n          undir_dfv_impl(g, v, vis, vertex_color, edge_color);\n        } else if (v_color == Color::gray() && uv_color == EColor::white())\n                                             vis.back_edge(*ei, g);\n      }\n      put(vertex_color, u, Color::black());  vis.finish_vertex(u, g);\n    }\n  } // namespace detail\n\n  template <typename Graph, typename DFSVisitor, \n            typename VertexColorMap, typename EdgeColorMap, \n            typename Vertex>\n  void\n  undirected_dfs(const Graph& g, DFSVisitor vis, \n                 VertexColorMap vertex_color, EdgeColorMap edge_color,\n                 Vertex start_vertex)\n  {\n    function_requires<DFSVisitorConcept<DFSVisitor, Graph> >();\n      function_requires<EdgeListGraphConcept<Graph> >();\n\n    typedef typename property_traits<VertexColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n\n    typename graph_traits<Graph>::vertex_iterator ui, ui_end;\n    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n      put(vertex_color, *ui, Color::white());   vis.initialize_vertex(*ui, g);\n    }\n    typename graph_traits<Graph>::edge_iterator ei, ei_end;\n    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n      put(edge_color, *ei, Color::white());\n\n    if (start_vertex != *vertices(g).first){ vis.start_vertex(start_vertex, g);\n      detail::undir_dfv_impl(g, start_vertex, vis, vertex_color, edge_color);\n    }\n\n    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n      ColorValue u_color = get(vertex_color, *ui);\n      if (u_color == Color::white()) {       vis.start_vertex(*ui, g);\n        detail::undir_dfv_impl(g, *ui, vis, vertex_color, edge_color);\n      }\n    }\n  }\n\n  template <typename Graph, typename DFSVisitor, typename VertexColorMap,\n    typename EdgeColorMap>\n  void\n  undirected_dfs(const Graph& g, DFSVisitor vis, \n                 VertexColorMap vertex_color, EdgeColorMap edge_color)\n  {\n    undirected_dfs(g, vis, vertex_color, edge_color, *vertices(g).first);\n  }\n\n  namespace detail {\n    template <typename VertexColorMap>\n    struct udfs_dispatch {\n\n      template <typename Graph, typename Vertex, \n                typename DFSVisitor, typename EdgeColorMap,\n                typename P, typename T, typename R>\n      static void\n      apply(const Graph& g, DFSVisitor vis, Vertex start_vertex,\n            const bgl_named_params<P, T, R>&,\n            EdgeColorMap edge_color,\n            VertexColorMap vertex_color)\n      {\n        undirected_dfs(g, vis, vertex_color, edge_color, start_vertex);\n      }\n    };\n\n    template <>\n    struct udfs_dispatch<detail::error_property_not_found> {\n      template <typename Graph, typename Vertex, typename DFSVisitor,\n                typename EdgeColorMap,\n                typename P, typename T, typename R>\n      static void\n      apply(const Graph& g, DFSVisitor vis, Vertex start_vertex,\n            const bgl_named_params<P, T, R>& params,\n            EdgeColorMap edge_color,\n            detail::error_property_not_found)\n      {\n        std::vector<default_color_type> color_vec(num_vertices(g));\n        default_color_type c = white_color; // avoid warning about un-init\n        undirected_dfs\n          (g, vis, make_iterator_property_map\n           (color_vec.begin(),\n            choose_const_pmap(get_param(params, vertex_index),\n                              g, vertex_index), c),\n           edge_color,\n           start_vertex);\n      }\n    };\n\n  } // namespace detail\n  \n\n  // Named Parameter Variant\n  template <typename Graph, typename P, typename T, typename R>\n  void\n  undirected_dfs(const Graph& g, \n                 const bgl_named_params<P, T, R>& params)\n  {\n    typedef typename property_value< bgl_named_params<P, T, R>, \n      vertex_color_t>::type C;\n    detail::udfs_dispatch<C>::apply\n      (g,\n       choose_param(get_param(params, graph_visitor),\n                    make_dfs_visitor(null_visitor())),\n       choose_param(get_param(params, root_vertex_t()),\n                    *vertices(g).first),\n       params,\n       get_param(params, edge_color),\n       get_param(params, vertex_color)\n       );\n  }\n  \n\n  template <typename IncidenceGraph, typename DFSVisitor, \n    typename VertexColorMap, typename EdgeColorMap>\n  void undirected_depth_first_visit\n    (const IncidenceGraph& g,\n     typename graph_traits<IncidenceGraph>::vertex_descriptor u, \n     DFSVisitor vis, VertexColorMap vertex_color, EdgeColorMap edge_color)\n  {\n    detail::undir_dfv_impl(g, u, vis, vertex_color, edge_color);\n  }\n\n\n} // namespace boost\n\n\n#endif\n", "meta": {"hexsha": "d549d2b6decaf916ad1df5119aadc4caf4b63282", "size": 7684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rd party/boost/boost/graph/undirected_dfs.hpp", "max_stars_repo_name": "OLR-xray/OLR-3.0", "max_stars_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/undirected_dfs.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/graph/undirected_dfs.hpp", "max_forks_repo_name": "Imperator-Knoedel/Sunset", "max_forks_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 39.2040816327, "max_line_length": 79, "alphanum_fraction": 0.6625455492, "num_tokens": 1758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.04672495763050702, "lm_q1q2_score": 0.01359606864517975}}
{"text": "/*  ==========================================================================================\n    Author: Leonardo Citraro\n    Company:\n    Filename: ext3DLBPpy.cpp\n    Last modifed:   6.1.2019 by Leonardo Citraro\n    Description:    Boost-Python wrappers\n    *\n    Please cite the article:    L. Citraro, S. Mahmoodi, A. Darekar, B. Vollmer,\n                                Extended three-dimensional rotation invariant local binary patterns,\n                                Image and Vision Computing (2017),\n                                http://dx.doi.org/10.1016/j.imavis.2017.03.004\n\n    ==========================================================================================\n    Copyright (c) 2017 Leonardo Citraro <ldo.citraro@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy of this\n    software and associated documentation files (the \"Software\"), to deal in the Software\n    without restriction, including without limitation the rights to use, copy, modify,\n    merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n    permit persons to whom the Software is furnished to do so, subject to the following\n    conditions:\n\n    The above copyright notice and this permission notice shall be included in all copies\n    or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n    INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n    PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\n    FOR ANY CLAIM, 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 USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n    ==========================================================================================\n*/\n#include <Python.h>\n#include <boost/python/numpy.hpp>\n#include <numpy/ndarrayobject.h>\n#include <numpy/arrayobject.h>\n#include \"ext3DLBP.hpp\"\n\nusing namespace std;\nusing namespace ext3DLBP;\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\n/**\n  *   @brief  This function deletes dynamically allocated memory\n  *           from python side when the data is no loguer required.\n  */\ntemplate<typename T>\ninline void CapsuleDestructor(PyObject *ptr){\n    T *tmp = reinterpret_cast<T*>(PyCapsule_GetPointer(ptr, NULL));\n    if(tmp){\n        delete tmp;\n    }\n}\n\ntemplate<typename T>\ninline np::ndarray make_ndarray(T* const ptr, const int H, const int W=0, const int D=0){\n\n    // figuring out the size of the array\n    int L;\n    if(W<=0 && D<=0){\n        L = H;\n    }else if(W<=0 && H<=0){\n        L = D;\n    }else if(H<=0 && D<=0){\n        L = H;\n    }else if(H<=0){\n        L = W*D;\n    }else if(W<=0){\n        L = H*D;\n    }else if(D<=0){\n        L = H*W;\n    }else{\n        L=H*W*D;\n    }\n\n    // The object owner is responsible for deleting the dynamic array from the python side\n    // This is the trick to prevent memory leaks!\n    p::object owner(p::handle<>((PyCapsule_New((void*)ptr, NULL,\n                                (PyCapsule_Destructor)&CapsuleDestructor<T>))));\n\n    // Creates a boost numpy array, this is the actual object we return to python\n    np::ndarray py_array = np::from_data(ptr,\n                                         np::dtype::get_builtin<T>(),\n                                         p::make_tuple(L),\n                                         p::make_tuple(sizeof(T)),\n                                         owner);\n\n    p::tuple shape;\n    if(H<=0){\n        shape = p::make_tuple(W,D);\n    }else if(W<=0){\n        shape = p::make_tuple(H,D);\n    }else if(D<=0){\n        shape = p::make_tuple(H,W);\n    }else{\n        shape = p::make_tuple(H,W,D);\n    }\n\n    py_array = py_array.reshape(shape);\n\n    return py_array;\n}\n\ntemplate<typename T, size_t K>\nArray3D<T,K,K,K> convert_numpy_to_STL(const np::ndarray& py_array) {\n    Array3D<T,K,K,K> array;\n    T* p_vector;\n    for(int k=0; k<K; ++k) {\n        for(int j=0; j<K; ++j) {           \n            for(int i=0; i<K; ++i) {\n                T x = p::extract<T>(py_array[i][j][k]);\n                array[i][j][k] = x;\n            }\n        }\n    }\n    return array;\n}\n\ntemplate<typename T, size_t K>\nArray3D<T,K,K,K> my_slice(const np::ndarray& py_volume, const int istart, const int jstart, const int kstart) {\n    Array3D<T,K,K,K> array;\n    for(int k=0; k<K; ++k) {\n        for(int j=0; j<K; ++j) {\n            for(int i=0; i<K; ++i) {\n                array[i][j][k] = p::extract<T>(py_volume[i+istart][j+jstart][k+kstart]);\n            }\n        }\n    }\n    return array;\n}\n\np::tuple convert_to_tuple(const Array1D<int,2>& data) {\n    return p::make_tuple(data[0], data[1]);\n}\np::tuple convert_to_tuple(const Array1D<int,3>& data) {\n    return p::make_tuple(data[0], data[1], data[2]);\n}\n\n//=========================================================================\n// CI-LBP\n//=========================================================================\nstruct CI_LBP_ : public CI_LBP {\n    const static int bins = CI_LBP::bins;\n    CI_LBP_(const double mur) : CI_LBP(mur) {}\n    // converts a volume of size 3, 5 or 7 voxels\n    auto convert(const np::ndarray py_volume) {\n        int H = py_volume.shape(0);\n        if(H == 3)\n            return CI_LBP::convert(convert_numpy_to_STL<int,3>(py_volume));\n        else if(H == 5)\n            return CI_LBP::convert(convert_numpy_to_STL<int,5>(py_volume));\n        else if(H == 7)\n            return CI_LBP::convert(convert_numpy_to_STL<int,7>(py_volume));\n    }\n    // converts a full volume\n    auto convert_3d_image(const np::ndarray& py_volume) {\n        int H = py_volume.shape(0);\n        int W = py_volume.shape(1);\n        int D = py_volume.shape(2);\n\n        int* out = new int[H*W*D];\n\n        for(int k=0; k<(D); ++k) {\n            for(int j=0; j<(W); ++j) {\n                for(int i=0; i<(H); ++i) {\n                    int chunk = p::extract<int>(py_volume[i][j][k]);\n                    out[k*D*W + j*W + i] = CI_LBP::convert(chunk);\n                }\n            }\n        }\n\n        np::ndarray py_out = make_ndarray(out,H,W,D);\n\n        return py_out;\n    }\n};\nconst int CI_LBP_::bins;\n\n//=========================================================================\n// NI-LBP\n//=========================================================================\n\n#define wrapper_class_1     struct fullname : public parent {\\\n                                const static int P = parent::P;\\\n                                const static int O = parent::O;\\\n                                const static int bins = parent::bins;\\\n                                const static int R = parent::R;\\\n                                const static int K = parent::K;\\\n                                fullname(const double mur, const int V) : parent(mur,V) {}\\\n                                auto convert(const np::ndarray& py_volume) {\\\n                                    return parent::convert(convert_numpy_to_STL<int,K>(py_volume));\\\n                                }\\\n                                auto convert_3d_image(const np::ndarray& py_volume) {\\\n                                    int H = py_volume.shape(0);\\\n                                    int W = py_volume.shape(1);\\\n                                    int D = py_volume.shape(2);\\\n                                    \\\n                                    int H_ = H-2*R;\\\n                                    int W_ = W-2*R;\\\n                                    int D_ = D-2*R;\\\n                                    int* out = new int[H_*W_*D_];\\\n                                    \\\n                                    for(int k=0; k<D_; ++k) {\\\n                                        for(int j=0; j<W_; ++j) {\\\n                                            for(int i=0; i<H_; ++i) {\\\n                                                auto chunk = my_slice<int,K>(py_volume,i,j,k);\\\n                                                out[k*D_*W_ + j*W_ + i] = parent::convert(chunk);\\\n                                            }\\\n                                        }\\\n                                    }\\\n                                    np::ndarray py_out = make_ndarray(out,H_, W_, D_);\\\n                                    return py_out;\\\n                                }\\\n                            };\\\n                            const int fullname::P;\\\n                            const int fullname::bins;\\\n                            const int fullname::O;\\\n                            const int fullname::R;\\\n                            const int fullname::K;\\\n\n#define wrapper_class_2     struct fullname : public parent {\\\n                                const static int P = parent::P;\\\n                                const static int O = parent::O;\\\n                                const static int bins = parent::bins;\\\n                                const static int R = parent::R;\\\n                                const static int K = parent::K;\\\n                                fullname(const double mur, const int V) : parent(mur,V) {}\\\n                                auto convert(const np::ndarray& py_volume) {\\\n                                    return convert_to_tuple(parent::convert(convert_numpy_to_STL<int,K>(py_volume)));\\\n                                }\\\n                                auto convert_3d_image(const np::ndarray& py_volume) {\\\n                                    int H = py_volume.shape(0);\\\n                                    int W = py_volume.shape(1);\\\n                                    int D = py_volume.shape(2);\\\n                                    \\\n                                    int H_ = H-2*R;\\\n                                    int W_ = W-2*R;\\\n                                    int D_ = D-2*R;\\\n                                    int* out1 = new int[H_*W_*D_];\\\n                                    int* out2 = new int[H_*W_*D_];\\\n                                    \\\n                                    for(int k=0; k<D_; ++k) {\\\n                                        for(int j=0; j<W_; ++j) {\\\n                                            for(int i=0; i<H_; ++i) {\\\n                                                auto chunk = my_slice<int,K>(py_volume,i,j,k);\\\n                                                Array1D<int,2> codes = parent::convert(chunk);\\\n                                                out1[k*D_*W_ + j*W_ + i] = codes[0];\\\n                                                out2[k*D_*W_ + j*W_ + i] = codes[1];\\\n                                            }\\\n                                        }\\\n                                    }\\\n                                    np::ndarray py_out1 = make_ndarray(out1, H_, W_, D_);\\\n                                    np::ndarray py_out2 = make_ndarray(out2, H_, W_, D_);\\\n                                    return p::make_tuple(py_out1, py_out2);\\\n                                }\\\n                            };\\\n                            const int fullname::P;\\\n                            const int fullname::bins;\\\n                            const int fullname::O;\\\n                            const int fullname::R;\\\n                            const int fullname::K;\\\n\n#define wrapper_class_3     struct fullname : public parent {\\\n                                const static int P = parent::P;\\\n                                const static int O = parent::O;\\\n                                const static int bins = parent::bins;\\\n                                const static int R = parent::R;\\\n                                const static int K = parent::K;\\\n                                fullname(const double mur, const int V) : parent(mur,V) {}\\\n                                auto convert(const np::ndarray& py_volume) {\\\n                                    return convert_to_tuple(parent::convert(convert_numpy_to_STL<int,K>(py_volume)));\\\n                                }\\\n                                auto convert_3d_image(const np::ndarray& py_volume) {\\\n                                    int H = py_volume.shape(0);\\\n                                    int W = py_volume.shape(1);\\\n                                    int D = py_volume.shape(2);\\\n                                    \\\n                                    int H_ = H-2*R;\\\n                                    int W_ = W-2*R;\\\n                                    int D_ = D-2*R;\\\n                                    int* out1 = new int[H_*W_*D_];\\\n                                    int* out2 = new int[H_*W_*D_];\\\n                                    int* out3 = new int[H_*W_*D_];\\\n                                    \\\n                                    for(int k=0; k<D_; ++k) {\\\n                                        for(int j=0; j<W_; ++j) {\\\n                                            for(int i=0; i<H_; ++i) {\\\n                                                auto chunk = my_slice<int,K>(py_volume,i,j,k);\\\n                                                Array1D<int,3> codes = parent::convert(chunk);\\\n                                                out1[k*D_*W_ + j*W_ + i] = codes[0];\\\n                                                out2[k*D_*W_ + j*W_ + i] = codes[1];\\\n                                                out3[k*D_*W_ + j*W_ + i] = codes[2];\\\n                                            }\\\n                                        }\\\n                                    }\\\n                                    np::ndarray py_out1 = make_ndarray(out1,H_, W_, D_);\\\n                                    np::ndarray py_out2 = make_ndarray(out2,H_, W_, D_);\\\n                                    np::ndarray py_out3 = make_ndarray(out3,H_, W_, D_);\\\n                                    return p::make_tuple(py_out1, py_out2, py_out3);\\\n                                }\\\n                            };\\\n                            const int fullname::P;\\\n                            const int fullname::bins;\\\n                            const int fullname::O;\\\n                            const int fullname::R;\\\n                            const int fullname::K;\\\n\n// P42g\n#define fullname NI_LBP_P42g_R1\n#define parent NI_LBP<P42g, R1>\nwrapper_class_1\n\n#define fullname NI_LBP_P42g_R2\n#define parent NI_LBP<P42g, R2>\nwrapper_class_1\n\n// P92g\n#define fullname NI_LBP_P92g_R1\n#define parent NI_LBP<P92g, R1>\nwrapper_class_1\n\n#define fullname NI_LBP_P92g_R2\n#define parent NI_LBP<P92g, R2>\nwrapper_class_1\n\n#define fullname NI_LBP_P92g_R3\n#define parent NI_LBP<P92g, R3>\nwrapper_class_1\n\n// P252g\n#define fullname NI_LBP_P252g_R2\n#define parent NI_LBP<P252g, R2>\nwrapper_class_1\n\n#define fullname NI_LBP_P252g_R3\n#define parent NI_LBP<P252g, R3>\nwrapper_class_1\n\n//=========================================================================\n// RD-LBP\n//=========================================================================\n// P42g\n#define fullname RD_LBP_P42g_R1\n#define parent RD_LBP<P42g, R1>\nwrapper_class_1\n\n#define fullname RD_LBP_P42g_R2\n#define parent RD_LBP<P42g, R2>\nwrapper_class_1\n\n// P92g\n#define fullname RD_LBP_P92g_R1\n#define parent RD_LBP<P92g, R1>\nwrapper_class_1\n\n#define fullname RD_LBP_P92g_R2\n#define parent RD_LBP<P92g, R2>\nwrapper_class_1\n\n#define fullname RD_LBP_P92g_R3\n#define parent RD_LBP<P92g, R3>\nwrapper_class_1\n\n\n\n// P252g\n#define fullname RD_LBP_P252g_R2\n#define parent RD_LBP<P252g, R2>\nwrapper_class_1\n\n#define fullname RD_LBP_P252g_R3\n#define parent RD_LBP<P252g, R3>\nwrapper_class_1\n\n//=========================================================================\n// NI-RD-LBP\n//=========================================================================\n//P42g\n#define fullname NI_RD_LBP_P42g_R1\n#define parent NI_RD_LBP<P42g, R1>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P42g_R2\n#define parent NI_RD_LBP<P42g, R2>\nwrapper_class_2\n\n//P92g\n#define fullname NI_RD_LBP_P92g_R1\n#define parent NI_RD_LBP<P92g, R1>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P92g_R2\n#define parent NI_RD_LBP<P92g, R2>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P92g_R3\n#define parent NI_RD_LBP<P92g, R3>\nwrapper_class_2\n\n//P252g\n#define fullname NI_RD_LBP_P252g_R2\n#define parent NI_RD_LBP<P252g, R2>\nwrapper_class_2\n\n#define fullname NI_RD_LBP_P252g_R3\n#define parent NI_RD_LBP<P252g, R3>\nwrapper_class_2\n\n//=========================================================================\n// NI-RD-CI-LBP\n//=========================================================================\n//P42g\n#define fullname NI_RD_CI_LBP_P42g_R1\n#define parent NI_RD_CI_LBP<P42g, R1>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P42g_R2\n#define parent NI_RD_CI_LBP<P42g, R2>\nwrapper_class_3\n\n//P92g\n#define fullname NI_RD_CI_LBP_P92g_R1\n#define parent NI_RD_CI_LBP<P92g, R1>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P92g_R2\n#define parent NI_RD_CI_LBP<P92g, R2>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P92g_R3\n#define parent NI_RD_CI_LBP<P92g, R3>\nwrapper_class_3\n\n//P252g\n#define fullname NI_RD_CI_LBP_P252g_R2\n#define parent NI_RD_CI_LBP<P252g, R2>\nwrapper_class_3\n\n#define fullname NI_RD_CI_LBP_P252g_R3\n#define parent NI_RD_CI_LBP<P252g, R3>\nwrapper_class_3\n\nBOOST_PYTHON_MODULE(ext3DLBPpy) {\n    Py_Initialize();\n    np::initialize();\n\n    // CI-LBP\n    p::class_<CI_LBP_>(\"CI_LBP\",p::init<double>())\n        .def_readonly(\"mur\", &CI_LBP_::mur)\n        .def_readonly(\"bins\", &CI_LBP_::bins)\n        .def(\"convert\", &CI_LBP_::convert)\n        .def(\"convert_3d_image\", &CI_LBP_::convert_3d_image);\n\n#define STRINGIZE_NX(A) #A\n#define STRINGIZE(A) STRINGIZE_NX(A)\n#define boost_python_definition p::class_<fullname>(STRINGIZE(fullname),p::init<double, int>())\\\n                                .def_readonly(\"P\", &fullname::P)\\\n                                .def_readonly(\"O\", &fullname::O)\\\n                                .def_readonly(\"bins\", &fullname::bins)\\\n                                .def_readonly(\"R\", &fullname::R)\\\n                                .def_readonly(\"K\", &fullname::K)\\\n                                .def_readonly(\"mur\", &fullname::mur)\\\n                                .def_readonly(\"V\", &fullname::V)\\\n                                .def(\"convert\", &fullname::convert) \\\n                                .def(\"convert_3d_image\", &fullname::convert_3d_image);\n// NI-LBP\n#define fullname NI_LBP_P42g_R1\nboost_python_definition\n\n#define fullname NI_LBP_P42g_R2\nboost_python_definition\n\n\n#define fullname NI_LBP_P92g_R1\nboost_python_definition\n\n#define fullname NI_LBP_P92g_R2\nboost_python_definition\n\n#define fullname NI_LBP_P92g_R3\nboost_python_definition\n\n\n#define fullname NI_LBP_P252g_R2\nboost_python_definition\n\n#define fullname NI_LBP_P252g_R3\nboost_python_definition\n\n// RD-LBP\n#define fullname RD_LBP_P42g_R1\nboost_python_definition\n\n#define fullname RD_LBP_P42g_R2\nboost_python_definition\n\n\n#define fullname RD_LBP_P92g_R1\nboost_python_definition\n\n#define fullname RD_LBP_P92g_R2\nboost_python_definition\n\n#define fullname RD_LBP_P92g_R3\nboost_python_definition\n\n\n#define fullname RD_LBP_P252g_R2\nboost_python_definition\n\n#define fullname RD_LBP_P252g_R3\nboost_python_definition\n\n// NI-RD-LBP\n#define fullname NI_RD_LBP_P42g_R1\nboost_python_definition\n\n#define fullname NI_RD_LBP_P42g_R2\nboost_python_definition\n\n\n#define fullname NI_RD_LBP_P92g_R1\nboost_python_definition\n\n#define fullname NI_RD_LBP_P92g_R2\nboost_python_definition\n\n#define fullname NI_RD_LBP_P92g_R3\nboost_python_definition\n\n\n#define fullname NI_RD_LBP_P252g_R2\nboost_python_definition\n\n#define fullname NI_RD_LBP_P252g_R3\nboost_python_definition\n\n\n// NI-RD-CI-LBP\n#define fullname NI_RD_CI_LBP_P42g_R1\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P42g_R2\nboost_python_definition\n\n\n#define fullname NI_RD_CI_LBP_P92g_R1\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P92g_R2\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P92g_R3\nboost_python_definition\n\n\n\n#define fullname NI_RD_CI_LBP_P252g_R2\nboost_python_definition\n\n#define fullname NI_RD_CI_LBP_P252g_R3\nboost_python_definition\n\n};\n", "meta": {"hexsha": "a8d0e7763a4bbe5ec77f808f9fa1d09585f49f6b", "size": 20150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python_wrapper/ext3DLBPpy.cpp", "max_stars_repo_name": "ejlai/ext3DLBP", "max_stars_repo_head_hexsha": "1f8958842d2a910ab89466cced2a445f58dc6222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python_wrapper/ext3DLBPpy.cpp", "max_issues_repo_name": "ejlai/ext3DLBP", "max_issues_repo_head_hexsha": "1f8958842d2a910ab89466cced2a445f58dc6222", "max_issues_repo_licenses": ["MIT"], "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_wrapper/ext3DLBPpy.cpp", "max_forks_repo_name": "ejlai/ext3DLBP", "max_forks_repo_head_hexsha": "1f8958842d2a910ab89466cced2a445f58dc6222", "max_forks_repo_licenses": ["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.5379188713, "max_line_length": 118, "alphanum_fraction": 0.4936972705, "num_tokens": 4574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.041462273599738315, "lm_q1q2_score": 0.01358587219414829}}
{"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 <algorithm>\n#include <map>\n#include <set>\n\n#include <hashclash/saveload_bz2.hpp>\n#include <hashclash/sha1differentialpath.hpp>\n#include <hashclash/sha1detail.hpp>\n#include <hashclash/sha1messagespace.hpp>\n#include <hashclash/booleanfunction.hpp>\n#include <hashclash/progress_display.hpp>\n#include <hashclash/rng.hpp>\n\n#include <boost/lexical_cast.hpp>\n\n#include \"main.hpp\"\n\nvoid getline(std::istream& ifs)\n{\n\tchar c = 0;\n\twhile (ifs && c != '\\n' && c != '\\r')\n\t\tifs.get(c);\n\twhile (ifs && (c == '\\n' || c == '\\r'))\n\t\tifs.get(c);\n\tif (ifs)\n\t\tifs.putback(c);\n}\n\nint pathfromtext(parameters_type& parameters)\n{\n\tif (parameters.outfile1 == \"\") {\n\t\tcout << \"No outputfile1 given!\" << endl;\n\t\treturn 2;\n\t}\n\tif (parameters.infile1 == \"\") {\n\t\tcout << \"No inputfile1 given!\" << endl;\n\t\treturn 2;\n\t}\n\tparameters.show_mdiffs();\n\tsha1differentialpath path;\n\tvector<sha1differentialpath> vecpath;\n\tifstream ifs(parameters.infile1.c_str());\n\tif (!ifs) {\n\t\tcerr << \"Error: could not open \" << parameters.infile1 << \"!\" << endl;\n\t\treturn 1;\n\t}\n\tcout << \"Parsing inputfile:\";\n\twhile (ifs) {\n\t\tcout << endl;\n\t\tchar c;\n\t\tifs >> c;\n\t\tcout << c << \" \";\n\t\tif (!ifs) break;\n\t\tif (c != 'Q') {\n\t\t\tcout << \"expected 'Q' here, going to next line\";\n\t\t\tgetline(ifs);\n\t\t\tcontinue;\n\t\t}\n\t\tint t;\n\t\tif (!(ifs >> t)) break;\n\t\tcout << t << \" \";\n\t\tif (t < -4 || t > 80) {\n\t\t\tcout << \"expected integer t with -4 <= t <= 80 here, going to next line\";\n\t\t\tgetline(ifs);\n\t\t\tcontinue;\n\t\t}\n\t\twhile (ifs && c != '|') {\n\t\t\tifs >> c;\n\t\t\tcout << c << \" \";\n\t\t}\n\t\tif (c != '|') {\n\t\t\tcout << \"expected '|' here, going to next line\";\n\t\t\tgetline(ifs);\n\t\t\tcontinue;\n\t\t}\n\t\twordconditions wc;\n\t\tifs >> wc.bytes[3] >> wc.bytes[2] >> wc.bytes[1] >> wc.bytes[0] >> c;\n\t\tcout << wc << \" \" << c << \" \";\n\t\tif (!ifs) break;\n\t\tif (c != '|') {\n\t\t\tcout << \"expected '|' here, going to next line\";\n\t\t\tgetline(ifs);\n\t\t\tcontinue;\n\t\t}\n\t\tpath[t] = wc;\n\t\tpath.getme(t).clear();\n\t\tif (t >= 0 && t < 80) {\n\t\t\tsdr met;\n\t\t\tifs >> met;\n\t\t\tif (ifs)\n\t\t\t\tpath.getme(t) = met;\n\t\t}\n\t\tgetline(ifs);\n\t}\n\tcout << endl << \"Parsed path:\" << endl;\n\tshow_path(path);\n\tvecpath.push_back(path);\n\tcout << \"Saving \" << parameters.outfile1 << \"...\" << flush;\n\ttry {\n\t\tsave_bz2(vecpath, binary_archive, parameters.outfile1);\n\t\tcout << \"done.\" << endl;\n\t} catch (...) {\n\t\tcout << \"failed.\" << endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint split(parameters_type& parameters)\n{\n\tvector<sha1differentialpath> vecpath, splitvec;\n\tcout << \"Loading \" << parameters.infile1 << \"...\" << flush;\n\ttry {\n\t\tload_bz2(vecpath, binary_archive, parameters.infile1);\n\t\tcout << \"done (loaded \" << vecpath.size() << \" paths).\" << endl;\n\t} catch (...) {\n\t\tcout << \"failed.\" << endl;\n\t\treturn 1;\n\t}\n\tif (parameters.unique) {\n\t\tsort(vecpath.begin(), vecpath.end());\n\t\tvecpath.erase( unique(vecpath.begin(), vecpath.end()), vecpath.end() );\n\t\tcout << \"Reduced to \" << vecpath.size() << \" unique paths.\" << endl;\n\t}\n\tdouble step = double(vecpath.size()) / double(parameters.split);\n\tuint32 start = 0;\n\tuint32 end = vecpath.size();\n\tfor (unsigned i = 0; i < parameters.split; ++i)\n\t{\n\t\tuint32 iend = uint32(double(step*double(i+1)));\n\t\tif (i+1 == parameters.split || iend > end)\n\t\t\tiend = end;\n\t\tsplitvec.clear();\n\t\tsplitvec.reserve(iend-start);\n\t\tfor (unsigned j = start; j < iend; ++j)\n\t\t\tsplitvec.push_back(vecpath[j]);\n\t\tstart = iend;\n\t\tstring filename = parameters.infile1 + \"_\" \n\t\t\t\t\t+ boost::lexical_cast<string>(i) + \"of\"\n\t\t\t\t\t+ boost::lexical_cast<string>(parameters.split) + \".bin\";\n\t\tcout << \"Saving \" << splitvec.size() << \" paths to \" << filename << \"...\" << flush;\n\t\ttry {\n\t\t\tsave_bz2(splitvec, binary_archive, filename);\n\t\t\tcout << \"done.\" << endl;\n\t\t} catch (...) {\n\t\t\tcout << \"failed.\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint join(parameters_type& parameters)\n{\n\tif (parameters.outfile1 == \"\") {\n\t\tcout << \"No outputfile1 given!\" << endl;\n\t\treturn 2;\n\t}\n\tvector<sha1differentialpath> vecpath, joinvec;\n\tfor (unsigned i = 0; i < parameters.files.size(); ++i)\n\t{\n\t\tjoinvec.clear();\n\t\tcout << \"Loading \" << parameters.files[i] << \"...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(joinvec, binary_archive, parameters.files[i]);\n\t\t\tcout << \"done (loaded \" << joinvec.size() << \" paths).\" << endl;\n\t\t\tfor (unsigned j = 0; j < joinvec.size(); ++j)\n\t\t\t\tvecpath.push_back(joinvec[j]);\n\t\t} catch (...) {\n\t\t\tcout << \"failed.\" << endl;\n\t\t}\n\t}\n\tif (parameters.unique) {\n\t\tfor (unsigned i = 0; i < vecpath.size(); ++i) {\n\t\t\tfor (int t = vecpath[i].tbegin(); t < vecpath[i].tend(); ++t) {\n\t\t\t\tif (!(t-4 >= vecpath[i].tbegin() && t+1 < vecpath[i].tend()))\n\t\t\t\t\tvecpath[i].getme(t) = sdr();\n\t\t\t}\n\t\t}\n\t\tsort(vecpath.begin(), vecpath.end());\n\t\tvecpath.erase( unique(vecpath.begin(), vecpath.end()), vecpath.end() );\n\t\tcout << \"Reduced to \" << vecpath.size() << \" unique paths.\" << endl;\n\t}\n\tcout << \"Saving \" << vecpath.size() << \" paths to \" << parameters.outfile1 << \"...\" << flush;\n\ttry {\n\t\tsave_bz2(vecpath, binary_archive, parameters.outfile1);\n\t\tcout << \"done.\" << endl;\n\t} catch (...) {\n\t\tcout << \"failed.\" << endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint convert(parameters_type& parameters)\n{\t\n\tsha1differentialpath path;\t\n\tvector<sha1differentialpath> vecpath;\n\tset<sha1differentialpath> setpath;\n\tbool failed = true;\n\tif (failed) {\n\t\tcout << \"Trying to read vector of differential paths in binary...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(vecpath, binary_archive, parameters.infile1);\n\t\t\tif (vecpath.size() > 0) {\n\t\t\t\tfailed = false;\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t\tcout << \"Trying to save vector of differential paths in text...\" << flush;\n\t\t\t\tsave_bz2(vecpath, text_archive, parameters.infile1 + \".txt.bz2\");\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t}\n\t\t} catch (std::exception& e) {\n\t\t\tcout << \"failed.\" << e.what() << endl;\n\t\t}\n\t}\n\tif (failed) {\n\t\tcout << \"Trying to read vector of differential paths in text...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(vecpath, text_archive, parameters.infile1);\n\t\t\tif (vecpath.size() > 0) {\n\t\t\t\tfailed = false;\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t\tcout << \"Trying to save vector of differential paths in binary...\" << flush;\n\t\t\t\tsave_bz2(vecpath, binary_archive, parameters.infile1 + \".bin\");\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t}\n\t\t} catch (std::exception& e) {\n\t\t\tcout << \"failed.\" << e.what() << endl;\n\t\t}\n\t}\n\tif (failed) {\n\t\tcout << \"Trying to read set of differential paths in binary...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(setpath, binary_archive, parameters.infile1);\n\t\t\tif (setpath.size() > 0) {\n\t\t\t\tvecpath.assign(setpath.begin(),setpath.end());\n\t\t\t\tfailed = false;\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t\tcout << \"Trying to save vector of differential paths in text and binary...\" << flush;\n\t\t\t\tsave_bz2(vecpath, text_archive, parameters.infile1 + \".txt.bz2\");\n\t\t\t\tsave_bz2(vecpath, binary_archive, parameters.infile1 + \".bin\");\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t}\n\t\t} catch (std::exception& e) {\n\t\t\tcout << \"failed.\" << e.what() << endl;\n\t\t}\n\t}\n\tif (failed) {\n\t\tcout << \"Trying to read set of differential paths in text...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(setpath, text_archive, parameters.infile1);\n\t\t\tif (setpath.size() > 0) {\n\t\t\t\tvecpath.assign(setpath.begin(),setpath.end());\n\t\t\t\tfailed = false;\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t\tcout << \"Trying to save vector of differential paths in text and binary...\" << flush;\n\t\t\t\tsave_bz2(vecpath, text_archive, parameters.infile1 + \".txt.bz2\");\n\t\t\t\tsave_bz2(vecpath, binary_archive, parameters.infile1 + \".bin\");\n\t\t\t\tcout << \"success.\" << endl;\n\t\t\t}\n\t\t} catch (std::exception& e) {\n\t\t\tcout << \"failed.\" << e.what() << endl;\n\t\t}\n\t}\n\tif (failed) {\n\t\tcout << \"Trying to read differential path in binary...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(path, binary_archive, parameters.infile1);\n\t\t\tfailed = false;\n\t\t\tcout << \"success.\" << endl;\n\t\t\tcout << \"Trying to save differential path in text...\" << flush;\n\t\t\tsave_bz2(path, text_archive, parameters.infile1 + \".txt.bz2\");\n\t\t\tcout << \"success.\" << endl;\n\t\t} catch (std::exception& e) {\n\t\t\tcout << \"failed.\" << e.what() << endl;\n\t\t}\n\t}\n\tif (failed) {\n\t\tcout << \"Trying to read differential path in text...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(path, text_archive, parameters.infile1);\n\t\t\tfailed = false;\n\t\t\tcout << \"success.\" << endl;\n\t\t\tcout << \"Trying to save differential path in binary...\" << flush;\n\t\t\tsave_bz2(path, binary_archive, parameters.infile1 + \".bin\");\n\t\t\tcout << \"success.\" << endl;\n\t\t} catch (std::exception& e) {\n\t\t\tcout << \"failed.\" << e.what() << endl;\n\t\t}\n\t}\n\tif (failed)\n\t\treturn 1;\n\treturn 0;\n}\n\n\nstruct dqt_sort {\n\tuint32 data[5];\n\n\tbool operator< (const dqt_sort& r) const\n\t{\n\t\tif (data[4] < r.data[4]) return true;\n\t\tif (data[4] > r.data[4]) return false;\n\t\tif (data[3] < r.data[3]) return true;\n\t\tif (data[3] > r.data[3]) return false;\n\t\tif (data[2] < r.data[2]) return true;\n\t\tif (data[2] > r.data[2]) return false;\n\t\tif (data[1] < r.data[1]) return true;\n\t\tif (data[1] > r.data[1]) return false;\n\t\tif (data[0] < r.data[0]) return true;\n\t\treturn false;\n\t}\n\tbool operator== (const dqt_sort& r) const\n\t{\n\t\tfor (int i = 4; i >= 0; --i)\n\t\t\tif (data[i] != r.data[i]) return false;\n\t\treturn true;\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar, const unsigned int file_version)\n\t{\t\t\t\n\t\tar & boost::serialization::make_nvp(\"data\", data);\n\t}\n};\nvoid analyze_indepsection_prob(sha1messagespace& mespace, int tbegin, const uint32 dmmask[80], vector<dqt_sort>& target_dihvs);\nint showmespaceconditions(parameters_type& parameters)\n{\n\tsha1messagespace space;\n\tvector< vector<uint32> > bitrels;\n\tbool failed = true;\n\tcout << \"Trying to read space in text...\" << flush;\n\ttry {\n\t\tload_bz2(space, text_archive, parameters.infile1);\n\t\tspace.tobitrelations_80(bitrels);\n\t\tsave(bitrels, text_archive, parameters.infile1 + \".bitrel.txt\");\n\t\tfailed = false;\n\t\tcout << \"success.\" << endl;\n\t} catch (...) {\n\t\tcout << \"failed.\" << endl;\n\t}\n\tif (failed) {\n\t\tcout << \"Trying to read space in binary...\" << flush;\n\t\ttry {\n\t\t\tload_bz2(space, binary_archive, parameters.infile1);\n\t\t\tspace.tobitrelations_80(bitrels);\n\t\t\tfailed = false;\n\t\t\tcout << \"success.\" << endl;\n\t\t} catch (...) {\n\t\t\tcout << \"failed.\" << endl;\n\t\t}\n\t}\n\tif (failed) {\n\t\tcout << \"Trying to read bitconditions in text...\" << flush;\n\t\ttry {\n\t\t\tload(bitrels, text_archive, parameters.infile1);\n\t\t\tspace.frombitrelations_80(bitrels);\n\t\t\tfailed = false;\n\t\t\tcout << \"success.\" << endl;\n\t\t\tsave_bz2(space, text_archive, parameters.infile1 + \".mespace.txt.bz2\");\n\t\t} catch (std::exception& e) {\n\t\t\tcout << \"failed:\" << endl << e.what() << endl;\n\t\t} catch (...) {\n\t\t\tcout << \"failed.\" << endl;\n\t\t}\n\t}\n\tif (failed) return 1;\n        for (unsigned i = 0; i < bitrels.size(); ++i) {\n                cout << \" - \";\n                bool firstone = true;\n                for (unsigned t = 0; t < 80; ++t)\n                        for (unsigned b = 0; b < 32; ++b)  \n                                if (bitrels[i][t] & (1<<b)) {\n                                        if (firstone)\n                                                firstone = false;\n                                        else\n                                                cout << \" + \";\n                                        cout << \"M[\" << t << \",\" << b << \"]\";\n                                }\n                cout << \" = \" << (bitrels[i][80]&1) << endl;\n        }\n//        return 0;\n\tint tbegin = 67;\n\tvector<dqt_sort> tmp;\n#if 1\n\tvector<dqt_sort> base(6);\n\tfor (unsigned i = 0; i < 6; ++i) {\n\t\tbase[i].data[0] = 1<<31;\n\t\tbase[i].data[1] = 1<<1;\n\t\tbase[i].data[2] = (i<2) ? (1<<31) : 0;\n\t\tbase[i].data[3] = base[i].data[4] = 0;\n\t\tif (i==1 || i==4 || i==5) base[i].data[3] += 1<<4;\n\t\tif (i==0 || i==1) base[i].data[3] += 1<<6; else base[i].data[3] += 1<<7;\n\t\tif (i==0 || i==1) base[i].data[4] += (1<<11)+(1<<4)-(1<<2); else base[i].data[4] += (1<<12);\n\t\tif (i==1 || i==4 || i==5) base[i].data[4] += (1<<9);\n\t\tif (i==2 || i==4) base[i].data[4] += (1<<1)+(1<<3);\n\t\tif (i==3 || i==5) base[i].data[4] += (1<<4)-(1<<1);\n\t}\n\tfor (unsigned t794 = 0; t794 < 2; ++t794)\n\t for (unsigned t792 = 0; t792 < 2; ++t792)\n  \t  for (unsigned t787 = 0; t787 < 2; ++t787)\n\t   for (unsigned t783 = 0; t783 < 2; ++t783)\n\t    for (unsigned t763778 = 0; t763778 < 2; ++t763778)\n\t     for (unsigned t771772 = 0; t771772 < 2; ++t771772)\n\t     {\n\t   \tfor (unsigned i = 0; i < base.size(); ++i) {\n\t   \t\tdqt_sort tmptmp = base[i];\n\t   \t\tif (t794) tmptmp.data[4] -= (1<<5);\n\t   \t\tif (t792) tmptmp.data[4] += (1<<3);\n\t   \t\tif (t787) { tmptmp.data[3] -= (1<<8); tmptmp.data[4] -= (1<<13); }\n\t   \t\tif (t783) { tmptmp.data[3] -= (1<<4); tmptmp.data[4] -= (1<<9); }\n\t   \t\tif (t763778) tmptmp.data[1] -= (1<<2);\n\t   \t\tif (t771772 && tmptmp.data[2]) { tmptmp.data[3] += (1<<7); tmptmp.data[4] += (1<<12); }\n\t   \t\ttmp.push_back(tmptmp);\n\t   \t}\n\t     }\n\tcout << \"# dIHVs: \" << tmp.size() << endl;\n#endif\n\tanalyze_indepsection_prob(space, tbegin, parameters.m_mask, tmp);\n}\n\nvoid analyze_indepsection_prob(sha1messagespace& mespace, int tbegin, const uint32 dmmask[80], vector<dqt_sort>& target_dihvs)\n{\n\tconst unsigned int tend = 80;\n\tcout << \"Analyzing probability for t=[\" << tbegin << \"-\" << tend << \").\" << endl;\n\n\tvector< vector<uint32> > pathbitrelations16;\n\tvector< vector< vector<uint32> > > pathbitrelationsmatrix;\n\tmespace.tobitrelations_16(pathbitrelations16);\n\tcout << \"Bitrelations: \" << pathbitrelations16.size() << endl;\n\tpathbitrelationsmatrix.resize(16);\n\tfor (unsigned i = 0; i < 16; ++i)\n\t\tpathbitrelationsmatrix[i].resize(32);\n\tfor (unsigned i = 0; i < pathbitrelations16.size(); ++i) {\n\t\tint lastcol = -1;\n\t\tfor (int col = 16*32-1; col >= 0; --col)\n\t\t\tif (pathbitrelations16[i][col>>5]&(1<<(col&31))) {\n\t\t\t\tlastcol = col;\n\t\t\t\tunsigned t = lastcol>>5;\n\t\t\t\tunsigned b = lastcol&31;\n\t\t\t\tpathbitrelationsmatrix[t][b] = pathbitrelations16[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (lastcol == -1) throw;\n\t}\n\n\tconst int offset = 4;\n\tuint32 Q[85];\n\tuint32 Q2[85];\n\tuint32 m[80];\n\tuint32 m2[80];\n\n\tbool forceddihvs = false;\n\tvector<dqt_sort> target_dihvs2;\n\tif (target_dihvs.size()) {\n\t\tforceddihvs = true;\n\t\tsort(target_dihvs.begin(), target_dihvs.end());\n\t\tcout << \"Forcing target dIHVs (#=\" << target_dihvs.size() << \").\" << endl;\n\t}\n\n\tif (0) //target_dihvs.size() == 0)\n\t{\n\t\tcout << \"Determining target dIHVs...\" << endl;\n\t\tuint64 oksize = 1;\n\t\twhile (true) {\n\t\t\tif (oksize >= (1<<28)) break;\n\t\t\tbool oksizeok = true;\n\t\t\ttry {\n\t\t\t\tvector<dqt_sort> tmpdihvs(oksize*2);\n\t\t\t} catch (std::exception&) {oksizeok = false;} catch(...) {oksizeok = false;}\n\t\t\tif (!oksizeok)\n\t\t\t\tbreak;\n\t\t\toksize *= 2;\n\t\t}\n\t\tuint64 bufsize = oksize;\n\t\tcout << \"Maximum size temporary dIHV buffer: \" << bufsize << endl;\n\t\tvector<dqt_sort> dihvs(bufsize);\n\t\tprogress_display pd(dihvs.size());\n\t\tfor (unsigned i = 0; i < dihvs.size(); ++i,++pd) {\n\t\t\tfor (int t = 0; t < 16; ++t) {\n\t\t\t\tuint32 metmask = 0;\n\t\t\t\tuint32 metset1 = 0;\n\t\t\t\tfor (unsigned b = 0; b < 32; ++b) {\n\t\t\t\t\tif (pathbitrelationsmatrix[t][b].size()) {\n\t\t\t\t\t\tmetmask |= pathbitrelationsmatrix[t][b][t];\n\t\t\t\t\t\tuint32 v = pathbitrelationsmatrix[t][b][16]&1;\n\t\t\t\t\t\tfor (int t1 = 0; t1 < t; ++t1)\n\t\t\t\t\t\t\tv ^= m[t1]&pathbitrelationsmatrix[t][b][t1];\n\t\t\t\t\t\tif (hw(v)&1)\n\t\t\t\t\t\t\tmetset1 |= 1<<b;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm[t] = (xrng128() & ~metmask) | metset1;\n\t\t\t\tm2[t] = m[t] ^ dmmask[t];\n\t\t\t}\n\t\t\tfor (int t = 16; t < 80; ++t) {\n\t\t\t\tm[t]=rotate_left(m[t-3] ^ m[t-8] ^ m[t-14] ^ m[t-16], 1);\n\t\t\t\tm2[t]=rotate_left(m2[t-3] ^ m2[t-8] ^ m2[t-14] ^ m2[t-16], 1);\n\t\t\t}\n\t\t\tfor (int t = tbegin-4; t <= tbegin; ++t)\n\t\t\t\tQ2[offset+t] = Q[offset+t] = xrng128();\n\t\t\tfor (int t = tbegin; t < 60; ++t) {\n\t\t\t\tsha1_step_round3(t, Q, m);\n\t\t\t\tsha1_step_round3(t, Q2, m2);\n\t\t\t}\n\t\t\tfor (int t = (tbegin<60?60:tbegin); t < 80; ++t) {\n\t\t\t\tsha1_step_round4(t, Q, m);\n\t\t\t\tsha1_step_round4(t, Q2, m2);\n\t\t\t}\n\t\t\tdihvs[i].data[0] = rotate_left(Q2[offset+80-4],30)-rotate_left(Q[offset+80-4],30);\n\t\t\tdihvs[i].data[1] = rotate_left(Q2[offset+80-3],30)-rotate_left(Q[offset+80-3],30);\n\t\t\tdihvs[i].data[2] = rotate_left(Q2[offset+80-2],30)-rotate_left(Q[offset+80-2],30);\n\t\t\tdihvs[i].data[3] = Q2[offset+80-1]-Q[offset+80-1];\n\t\t\tdihvs[i].data[4] = Q2[offset+80]-Q[offset+80];\n\t\t}\n\t\tsort(dihvs.begin(), dihvs.end());\n\t\tunsigned i = 0;\n\t\tvector<unsigned> bestcnts;\n\t\twhile (i < dihvs.size()) {\n\t\t\tunsigned j = i+1;\n\t\t\twhile (j < dihvs.size() && dihvs[j] == dihvs[i]) ++j;\n\t\t\tbestcnts.push_back(j-i);\n\t\t\ti = j;\n\t\t}\n\t\tcout << \"Prob t=[\" << tbegin << \"-\" << 80 << \"): \" << flush;\n\t\tsort(bestcnts.begin(),bestcnts.end());\n\t\tunsigned bestcnt = bestcnts[bestcnts.size()-1];\n\t\tif (bestcnt == 1) {\n\t\t\tcerr << \"Warning: bestcount = 1: no best dIHVs discernable!\" << endl;\n\t\t\texit(0);\n\t\t}\n\n\t\ti = 0;\n\t\twhile (i < dihvs.size()) {\n\t\t\tunsigned j = i+1;\n\t\t\twhile (j < dihvs.size() && dihvs[j] == dihvs[i]) ++j;\n\t\t\tif (forceddihvs) {\n\t\t\t\tif (binary_search(target_dihvs.begin(), target_dihvs.end(), dihvs[i])) {\n\t\t\t\t\tcout << \"\\tprob=\" << log(double(j-i)/double(dihvs.size()))/log(2.0) << \":\\t\";\n\t\t\t\t\tfor (unsigned k = 0; k < 5; ++k)\n\t\t\t\t\t\tcout << naf(dihvs[i].data[k]) << \" \";\n\t\t\t\t\tcout << endl;\n\t\t\t\t} else if ((j-i)*2 >= bestcnt) {\n\t\t\t\t\tcout << \"N.I.\\tprob=\" << log(double(j-i)/double(dihvs.size()))/log(2.0) << \":\\t\";\n\t\t\t\t\tfor (unsigned k = 0; k < 5; ++k)\n\t\t\t\t\t\tcout << naf(dihvs[i].data[k]) << \" \";\n\t\t\t\t\tcout << endl;\n\t\t\t\t\ttarget_dihvs2.push_back(dihvs[i]);\n\t\t\t\t\tsort(target_dihvs2.begin(), target_dihvs2.end());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ((j-i)*2 >= bestcnt) {\n \t\t\t\t\tcout << \"\\tprob=\" << log(double(j-i)/double(dihvs.size()))/log(2.0) << \":\\t\";\n\t\t\t\t\tfor (unsigned k = 0; k < 5; ++k)\n\t\t\t\t\t\tcout << naf(dihvs[i].data[k]) << \" \";\n\t\t\t\t\tcout << endl;\n\t\t\t\t\ttarget_dihvs.push_back(dihvs[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\ti = j;\n\t\t}\n\t\t{ vector<dqt_sort> tmptmp(1); dihvs.swap(tmptmp); } // free memory\n\t\tsort(target_dihvs.begin(), target_dihvs.end());\n\t}\n\t\n\tcout << \"Checking cumulative probability target dIHVs: \" << flush;\n\tuint64 cnt = 0, okcnt = 0, okcnt2 = 0;\n\tdqt_sort dihv;\n\twhile (true) {\n\t\tfor (int t = 0; t < 16; ++t) {\n\t\t\tuint32 metmask = 0;\n\t\t\tuint32 metset1 = 0;\n\t\t\tfor (unsigned b = 0; b < 32; ++b) {\n\t\t\t\tif (pathbitrelationsmatrix[t][b].size()) {\n\t\t\t\t\tmetmask |= pathbitrelationsmatrix[t][b][t];\n\t\t\t\t\tuint32 v = pathbitrelationsmatrix[t][b][16]&1;\n\t\t\t\t\tfor (int t1 = 0; t1 < t; ++t1)\n\t\t\t\t\t\tv ^= m[t1]&pathbitrelationsmatrix[t][b][t1];\n\t\t\t\t\tif (hw(v)&1)\n\t\t\t\t\t\tmetset1 |= 1<<b;\n\t\t\t\t}\n\t\t\t}\n\t\t\tm[t] = (xrng128() & ~metmask) | metset1;\n\t\t\tm2[t] = m[t] ^ dmmask[t];\n\t\t}\n\t\tfor (int t = 16; t < 80; ++t) {\n\t\t\tm[t]=rotate_left(m[t-3] ^ m[t-8] ^ m[t-14] ^ m[t-16], 1);\n\t\t\tm2[t]=rotate_left(m2[t-3] ^ m2[t-8] ^ m2[t-14] ^ m2[t-16], 1);\n\t\t}\n\t\tfor (int t = tbegin-4; t <= tbegin; ++t)\n\t\t\tQ2[offset+t] = Q[offset+t] = xrng64();\n\t\tfor (int t = tbegin; t < 60; ++t) {\n\t\t\tsha1_step_round3(t, Q, m);\n\t\t\tsha1_step_round3(t, Q2, m2);\n\t\t}\n\t\tfor (int t = (tbegin<60?60:tbegin); t < 80; ++t) {\n\t\t\tsha1_step_round4(t, Q, m);\n\t\t\tsha1_step_round4(t, Q2, m2);\n\t\t}\n\t\tdihv.data[0] = rotate_left(Q2[offset+80-4],30)-rotate_left(Q[offset+80-4],30);\n\t\tdihv.data[1] = rotate_left(Q2[offset+80-3],30)-rotate_left(Q[offset+80-3],30);\n\t\tdihv.data[2] = rotate_left(Q2[offset+80-2],30)-rotate_left(Q[offset+80-2],30);\n\t\tdihv.data[3] = Q2[offset+80-1]-Q[offset+80-1];\n\t\tdihv.data[4] = Q2[offset+80]-Q[offset+80];\n\t\t++cnt;\n\t\tif (binary_search(target_dihvs.begin(), target_dihvs.end(), dihv)) {\n\t\t\t++okcnt;\n\t\t\tif (forceddihvs)\n\t\t\t\t++okcnt2;\n\t\t} else {\n\t\t\tif (forceddihvs && binary_search(target_dihvs2.begin(), target_dihvs2.end(), dihv))\n\t\t\t\t++okcnt2;\n\t\t}\n\t\tif (hw(cnt)+hw(cnt>>32)==1 && okcnt > 1) {\n\t\t\tcout << \"[\" << cnt << \":p=\" << log(double(okcnt)/double(cnt))/log(2.0);\n\t\t\tif (forceddihvs)\n\t\t\t\tcout << \"|p2=\" << log(double(okcnt2)/double(cnt))/log(2.0);\n\t\t\tcout << \"]\" << flush;\n\t\t}\n\t}\n\tcout << endl;\n}\n", "meta": {"hexsha": "8b4839871ac279850a9c2d1fc0e035584828f368", "size": 20381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sha1helper/convert.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/sha1helper/convert.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/sha1helper/convert.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": 31.746105919, "max_line_length": 127, "alphanum_fraction": 0.5703841813, "num_tokens": 6785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.03021458499340703, "lm_q1q2_score": 0.013578211503826548}}
{"text": "#include <iostream>\n#include <boost/algorithm/string.hpp>\n#include <storm/exceptions/WrongFormatException.h>\n#include \"storm/io/file.h\"\n#include \"storm/utility/constants.h\"\n#include \"storm/storage/expressions/Expression.h\"\n#include \"storm/storage/expressions/ExpressionManager.h\"\n#include \"storm-pomdp/analysis/WinningRegion.h\"\n\nnamespace storm {\nnamespace pomdp {\n    WinningRegion::WinningRegion(std::vector<uint64_t> const& observationSizes) : observationSizes(observationSizes)\n    {\n        for (uint64_t i = 0; i < observationSizes.size(); ++i) {\n            winningRegion.push_back(std::vector<storm::storage::BitVector>());\n        }\n    }\n\n    void WinningRegion::setObservationIsWinning(uint64_t observation) {\n        winningRegion[observation] = { storm::storage::BitVector(observationSizes[observation], true) };\n    }\n\n    void WinningRegion::addTargetStates(uint64_t observation, storm::storage::BitVector const& offsets) {\n        assert(!offsets.empty());\n        if(winningRegion[observation].empty()) {\n            winningRegion[observation].push_back(offsets);\n            return;\n        }\n        std::vector<storm::storage::BitVector> newWinningSupport = std::vector<storm::storage::BitVector>();\n\n        for (auto const& support : winningRegion[observation]) {\n            newWinningSupport.push_back(support | offsets);\n        }\n        // TODO it may be worthwhile to check whether something changed. If nothing changed, there is no need for the next routine.\n        // TODO the following code is  bit naive.\n        winningRegion[observation].clear(); // This prevents some overhead.\n        for (auto const& newWinning : newWinningSupport) {\n            update(observation, newWinning);\n        }\n    }\n\n    bool WinningRegion::update(uint64_t observation, storm::storage::BitVector const& winning) {\n        std::vector<storm::storage::BitVector> newWinningSupport = std::vector<storm::storage::BitVector>();\n        bool changed = false;\n        for (auto const& support : winningRegion[observation]) {\n            if (winning.isSubsetOf(support)) {\n                // This new winning support is already covered.\n                return false;\n            }\n            if(support.isSubsetOf(winning)) {\n                // This new winning support extends the previous support, thus the previous support is now spurious\n                changed = true;\n            } else {\n                newWinningSupport.push_back(support);\n            }\n        }\n\n        // only if changed.\n        if (changed) {\n            newWinningSupport.push_back(winning);\n            winningRegion[observation] = newWinningSupport;\n        } else {\n            winningRegion[observation].push_back(winning);\n        }\n        return true;\n\n    }\n\n    bool WinningRegion::query(uint64_t observation, storm::storage::BitVector const& currently) const {\n        for(storm::storage::BitVector winning : winningRegion[observation]) {\n            if(currently.isSubsetOf(winning)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    storm::expressions::Expression WinningRegion::extensionExpression(uint64_t observation, std::vector<storm::expressions::Expression>& varsForStates) const {\n        std::vector<storm::expressions::Expression> expressionForEntry;\n\n        for(auto const& winningForObservation : winningRegion[observation]) {\n            if (winningForObservation.full()) {\n                assert(winningRegion[observation].size() == 1);\n                return varsForStates.front().getManager().boolean(false);\n            }\n            std::vector<storm::expressions::Expression> subexpr;\n            std::vector<storm::expressions::Expression> leftHandSides;\n            assert(varsForStates.size() == winningForObservation.size());\n            for(uint64_t i = 0; i < varsForStates.size(); ++i) {\n                if (winningForObservation.get(i)) {\n                    leftHandSides.push_back(varsForStates[i]);\n                } else {\n                    subexpr.push_back(varsForStates[i]);\n                }\n            }\n            storm::expressions::Expression rightHandSide = storm::expressions::disjunction(subexpr);\n            for(auto const& lhs : leftHandSides) {\n                expressionForEntry.push_back(storm::expressions::implies(lhs,rightHandSide));\n            }\n            expressionForEntry.push_back(storm::expressions::disjunction(varsForStates));\n\n        }\n        return storm::expressions::conjunction(expressionForEntry);\n    }\n\n    /**\n     * If we observe this observation, do we surely win?\n     * @param observation\n     * @return yes, if all supports for this observation are winning.\n     */\n    bool WinningRegion::observationIsWinning(uint64_t observation) const {\n        return winningRegion[observation].size() == 1 && winningRegion[observation].front().full();\n    }\n\n    void WinningRegion::print() const {\n        uint64_t observation = 0;\n        std::vector<uint64_t> winningObservations;\n        std::vector<uint64_t> loosingObservations;\n\n        for (auto const& winningSupport : winningRegion) {\n            if (observationIsWinning(observation)) {\n                winningObservations.push_back(observation);\n            } else if(winningRegion[observation].empty()) {\n                loosingObservations.push_back(observation);\n            } else {\n                std::cout << \"***** observation\" << observation << std::endl;\n                for (auto const& support : winningSupport) {\n                    std::cout << \" \" << support;\n                }\n                std::cout << std::endl;\n            }\n            observation++;\n        }\n        std::cout << \"and  \" << winningObservations.size() << \" winning observations: (\";\n        for (auto const& obs : winningObservations) {\n            std::cout << obs << \" \";\n        }\n        std::cout << \") and \" << loosingObservations.size() << \" loosing observations: (\";\n        for (auto const& obs : loosingObservations) {\n            std::cout << obs << \" \";\n        }\n\n    }\n\n    /**\n     * How many different observations are there?\n     * @return\n     */\n    uint64_t WinningRegion::getNumberOfObservations() const {\n        assert(winningRegion.size() == observationSizes.size());\n        return observationSizes.size();\n    }\n\n    bool WinningRegion::empty() const {\n        for (auto const& ob : winningRegion) {\n            if (!ob.empty()) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    std::vector<storm::storage::BitVector> const& WinningRegion::getWinningSetsPerObservation(uint64_t observation) const {\n\n        assert(observation < getNumberOfObservations());\n        return winningRegion[observation];\n    }\n\n    storm::RationalNumber WinningRegion::beliefSupportStates() const {\n        storm::RationalNumber total = 0;\n        storm::RationalNumber two = storm::utility::convertNumber<storm::RationalNumber>(2);\n        for (auto const& size : observationSizes) {\n            total += carl::pow(two,size) - 1;\n        }\n        return total;\n    }\n\n    std::pair<storm::RationalNumber, storm::RationalNumber> count(std::vector<storm::storage::BitVector> const&  origSets, std::vector<storm::storage::BitVector> const& intersects,\n            std::vector<storm::storage::BitVector> const& intersectsInfo,\n            storm::RationalNumber val,\n            bool plus, uint64_t remdepth) {\n        assert(intersects.size() == intersectsInfo.size());\n        storm::RationalNumber newVal = val;\n        storm::RationalNumber two = storm::utility::convertNumber<storm::RationalNumber>(2);\n        for (uint64_t i = 0; i < intersects.size(); ++i) {\n            if(plus) {\n                newVal += carl::pow(two, intersects[i].getNumberOfSetBits());\n            } else {\n                newVal -= carl::pow(two, intersects[i].getNumberOfSetBits());\n            }\n        }\n\n        storm::RationalNumber diff = val-newVal;\n        storm::RationalNumber max = storm::utility::max(val,newVal);\n\n        diff = storm::utility::abs(diff);\n        if (remdepth == 0 || 20 * diff < max) {\n            if (plus) {\n                return std::make_pair(val, newVal);\n            } else {\n                return std::make_pair(newVal, val);\n            }\n        } else {\n            storm::RationalNumber skipped = 0;\n            uint64_t upperBoundElements =  origSets.size() * intersects.size();\n            STORM_LOG_DEBUG(\"Upper bound on number of elements to be considered \" << upperBoundElements);\n            STORM_LOG_DEBUG(\"Value \" << val << \" newVal \" << newVal);\n            uint64_t oom = 0;\n            uint64_t critoom = 0;\n            storm::RationalNumber n = 1;\n            while (n < max) {\n                oom += 1;\n                n *= 2;\n            }\n            STORM_LOG_DEBUG(\"Order of magnitude = \" << oom);\n\n            critoom = oom - floor(log2(upperBoundElements));\n\n\n            STORM_LOG_DEBUG(\"Crit Order of magnitude = \" << critoom);\n\n\n            uint64_t intersectSetSkip = critoom - floor(log2(origSets.size()));\n\n\n            std::vector<storm::storage::BitVector> useIntersects;\n            std::vector<storm::storage::BitVector> useInfo;\n            for(uint64_t i = 0; i < intersects.size(); ++i) {\n                if (upperBoundElements > 10000 && intersects[i].getNumberOfSetBits() < intersectSetSkip - 3) {\n                    skipped += (carl::pow(two, intersects[i].getNumberOfSetBits()) * origSets.size());\n                    STORM_LOG_DEBUG(\"Skipped \" << skipped);\n                } else {\n                    useIntersects.push_back(intersects[i]);\n                    useInfo.push_back(intersectsInfo[i]);\n                }\n            }\n\n            uint64_t origSetSkip = critoom - floor(log2(useIntersects.size()));\n            STORM_LOG_DEBUG(\"OrigSkip= \" << origSetSkip);\n\n\n            std::vector<storm::storage::BitVector> newIntersects;\n            std::vector<storm::storage::BitVector> newInfo;\n\n            for (uint64_t i = 0; i < origSets.size(); ++i) {\n                if (upperBoundElements > 20000 && origSets[i].getNumberOfSetBits() < origSetSkip - 3) {\n                    skipped += (carl::pow(two, origSets[i].getNumberOfSetBits()) * useIntersects.size());\n                    STORM_LOG_DEBUG(\"Skipped \" << skipped);\n                    continue;\n                }\n                for (uint64_t j = 0; j < useIntersects.size(); ++j ) {\n                    if (useInfo[j].get(i)) {\n                        continue;\n                    }\n                    storm::storage::BitVector newinf = useInfo[j];\n                    newinf.set(i);\n                    if (newinf == useInfo[j]) {\n                        continue;\n                    }\n                    bool exists = false;\n                    for( auto const& entry : newInfo) {\n                        if (entry == newinf) {\n                            exists = true;\n                            break;\n                        }\n                    }\n                    if(!exists) {\n                        newInfo.push_back(newinf);\n                        newIntersects.push_back(origSets[i] & useIntersects[j]);\n                    }\n                }\n            }\n\n            auto res =  count(origSets, newIntersects, newInfo, newVal, !plus, remdepth - 1);\n            if (plus) {\n                storm::RationalNumber tmp = res.first - skipped;\n                return std::make_pair(storm::utility::max(tmp, val), res.second);\n            } else {\n                storm::RationalNumber tmp = res.second + skipped;\n                return std::make_pair(res.first, storm::utility::min(tmp, val));\n            }\n        }\n    }\n\n    std::pair<storm::RationalNumber,storm::RationalNumber> WinningRegion::computeNrWinningBeliefs() const {\n        storm::RationalNumber upper = 0;\n        storm::RationalNumber lower = 0;\n        storm::RationalNumber two = storm::utility::convertNumber<storm::RationalNumber>(2);\n        for (auto const& winningSets : winningRegion) {\n            storm::RationalNumber totalForObs = 0;\n            storm::RationalNumber two = storm::utility::convertNumber<storm::RationalNumber>(2);\n\n            std::vector<storm::storage::BitVector> info; // which intersections are part of this\n            for (uint64_t i = 0; i < winningSets.size(); ++i) {\n                storm::storage::BitVector entry(winningSets.size());\n                entry.set(i);\n                info.push_back(entry);\n            }\n            auto res = count(winningSets, winningSets, info, totalForObs, true, 40);\n            lower += res.first;\n            upper += res.second;\n        }\n        if (lower > 0) {\n            lower -= 1;\n            upper -= 1;\n        }\n        return std::make_pair(lower,upper);\n    }\n\n\n    uint64_t WinningRegion::getStorageSize() const {\n        uint64_t result = 0;\n        for (uint64_t i = 0; i < getNumberOfObservations(); ++i) {\n            result += winningRegion[i].size() * observationSizes[i];\n        }\n        return result;\n    }\n\n    void WinningRegion::storeToFile(std::string const& path, std::string const& preamble, bool append) const {\n        std::ofstream file;\n        storm::utility::openFile(path, file, append);\n        file << \":preamble\" << std::endl;\n        file << preamble << std::endl;\n        file << \":winningregion\" << std::endl;\n        bool firstLine = true;\n        for (auto const& i : observationSizes) {\n            if(!firstLine) {\n                file << \" \";\n            } else {\n                firstLine = false;\n            }\n            file << i;\n        }\n        file << std::endl;\n        for (auto const& obsWr : winningRegion) {\n            for (auto const& bv : obsWr) {\n                bv.store(file);\n                file << \";\";\n            }\n            file << std::endl;\n        }\n        storm::utility::closeFile(file);\n    }\n\n\n    std::pair<WinningRegion,std::string> WinningRegion::loadFromFile(std::string const& path) {\n        std::ifstream file;\n        std::vector<uint64_t> observationSizes;\n        storm::utility::openFile(path, file);\n        std::string line;\n        uint64_t state = 0; // 0 = expect preamble\n        uint64_t observation = 0;\n        WinningRegion wr({1});\n        std::stringstream preamblestream;\n        while (std::getline(file, line))\n        {\n            if (boost::starts_with(line, \"#\")) {\n                continue;\n            }\n            if (state == 0) {\n                STORM_LOG_THROW(line == \":preamble\", storm::exceptions::WrongFormatException, \"Expected to see :preamble\");\n                state = 1; // state = 1: preamble\n            } else if (state == 1) {\n                if (line == \":winningregion\") {\n                    state = 2; // get sizes\n                } else {\n                    preamblestream << line << std::endl;\n                }\n            } else if (state == 2) {\n                std::vector<std::string> entries;\n                boost::split(entries, line, boost::is_space());\n                std::vector<uint64_t> observationSizes;\n                for (auto const &entry : entries) {\n                    observationSizes.push_back(std::stoul(entry));\n                }\n                wr = WinningRegion(observationSizes);\n                state = 3;\n            } else if (state == 3) {\n                std::vector<std::string> entries;\n                boost::split(entries, line, boost::is_any_of(\";\"));\n                entries.pop_back();\n                for (std::string const& bvString : entries) {\n                    wr.update(observation, storm::storage::BitVector::load(bvString));\n                }\n                ++observation;\n            }\n        }\n        storm::utility::closeFile(file);\n        return {wr,preamblestream.str()};\n    }\n\n}\n}", "meta": {"hexsha": "7b872a20a0595de525386c236af87ee9a7065a9d", "size": 15795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "artifact/storm/src/storm-pomdp/analysis/WinningRegion.cpp", "max_stars_repo_name": "glatteis/tacas21-artifact", "max_stars_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "artifact/storm/src/storm-pomdp/analysis/WinningRegion.cpp", "max_issues_repo_name": "glatteis/tacas21-artifact", "max_issues_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "artifact/storm/src/storm-pomdp/analysis/WinningRegion.cpp", "max_forks_repo_name": "glatteis/tacas21-artifact", "max_forks_repo_head_hexsha": "30b4f522bd3bdb4bebccbfae93f19851084a3db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-05T12:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T12:39:53.000Z", "avg_line_length": 40.1908396947, "max_line_length": 180, "alphanum_fraction": 0.552453308, "num_tokens": 3493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.027585282426646856, "lm_q1q2_score": 0.013577148730902941}}
{"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_OPERATOR_HH\n#define THERMAL_OPERATOR_HH\n\n#include <HeatSource.hh>\n#include <MaterialProperty.hh>\n#include <ThermalOperatorBase.hh>\n\n#include <deal.II/matrix_free/matrix_free.h>\n\nnamespace adamantine\n{\n/**\n * This class is the operator associated with the heat equation, i.e., vmult\n * performs \\f$ dst = -\\nabla k \\nabla src \\f$.\n */\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nclass ThermalOperator final : public ThermalOperatorBase<dim, MemorySpaceType>\n{\npublic:\n  ThermalOperator(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\n  /**\n   * Associate the AffineConstraints<double> and the MatrixFree objects to the\n   * underlying Triangulation.\n   */\n  void reinit(dealii::DoFHandler<dim> const &dof_handler,\n              dealii::AffineConstraints<double> const &affine_constraints,\n              dealii::hp::QCollection<1> const &quad) override;\n\n  /**\n   * Compute the inverse of the mass matrix and update the material properties.\n   */\n  void 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) override;\n\n  /**\n   * Clear the MatrixFree object and resize the inverse of the mass matrix to\n   * zero.\n   */\n  void clear();\n\n  dealii::types::global_dof_index m() const override;\n\n  dealii::types::global_dof_index n() const override;\n\n  /**\n   * Return a shared pointer to the inverse of the mass matrix.\n   */\n  std::shared_ptr<dealii::LA::distributed::Vector<double, MemorySpaceType>>\n  get_inverse_mass_matrix() const override;\n\n  /**\n   * Return a shared pointer to the underlying MatrixFree object.\n   */\n  dealii::MatrixFree<dim, double> const &get_matrix_free() const;\n\n  void vmult(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n             dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                 &src) const override;\n\n  void Tvmult(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n              dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                  &src) const override;\n\n  void vmult_add(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n                 dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                     &src) const override;\n\n  void Tvmult_add(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n                  dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                      &src) const override;\n\n  void\n  jacobian_vmult(dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n                 dealii::LA::distributed::Vector<double, MemorySpaceType> const\n                     &src) const override;\n\n  void initialize_dof_vector(\n      dealii::LA::distributed::Vector<double, MemorySpaceType> &vector)\n      const override;\n\n  void get_state_from_material_properties() override;\n\n  void set_state_to_material_properties() override;\n\n  /**\n   * Evaluate the material properties for a given state field.\n   */\n  // This function should be removed once the MaterialProperty for the device\n  // has been reworked and the material properties on the surface is computed\n  // correctly. The current name does not correctly explain what this\n  // function does but the name is still correct for the device.\n  void evaluate_material_properties(\n      dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> const\n          &state) override;\n\n  /**\n   * Return the value of \\f$ \\frac{1}{\\rho C_p} \\f$ for a given cell.\n   */\n  double\n  get_inv_rho_cp(typename dealii::DoFHandler<dim>::cell_iterator const &cell,\n                 unsigned int q) const override;\n\n  void set_time_and_source_height(double t, double height) override;\n\nprivate:\n  /**\n   * Update the ratios of the material state.\n   */\n  void\n  update_state_ratios(unsigned int cell, unsigned int q,\n                      dealii::VectorizedArray<double> temperature,\n                      std::array<dealii::VectorizedArray<double>,\n                                 static_cast<unsigned int>(MaterialState::SIZE)>\n                          &state_ratios) const;\n  /**\n   * Return the value of \\f$ \\frac{1}{\\rho C_p} \\f$ for a given matrix-free cell\n   * and quadrature point.\n   */\n  dealii::VectorizedArray<double>\n  get_inv_rho_cp(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  /**\n   * Apply the operator on a given set of quadrature points.\n   */\n  void 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  /**\n   * MPI communicator.\n   */\n  MPI_Comm const &_communicator;\n  /**\n   * Type of boundary.\n   */\n  BoundaryType _boundary_type;\n  /**\n   * Current time of the simulation.\n   */\n  double _time = 0.;\n  /**\n   * Current height of the heat sources.\n   */\n  double _current_source_height = 0.;\n  /**\n   * Data to configure the MatrixFree object.\n   */\n  typename dealii::MatrixFree<dim, double>::AdditionalData _matrix_free_data;\n  /**\n   * Store the \\f$ \\frac{1}{\\rho C_p}\\f$ coefficient.\n   */\n  mutable dealii::Table<2, dealii::VectorizedArray<double>> _inv_rho_cp;\n  /**\n   * Table of thermal conductivity coefficient.\n   */\n  dealii::Table<2, dealii::VectorizedArray<double>> _thermal_conductivity;\n  /**\n   * Material properties associated with 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   * Underlying MatrixFree object.\n   */\n  dealii::MatrixFree<dim, double> _matrix_free;\n  /**\n   * Non-owning pointer to the AffineConstraints from ThermalPhysics.\n   */\n  dealii::AffineConstraints<double> const *_affine_constraints;\n  /**\n   * The inverse of the mass matrix is computed using an inexact\n   * Gauss-Lobatto quadrature. This inexact quadrature makes the mass matrix\n   * and therefore also its inverse, a diagonal matrix.\n   */\n  std::shared_ptr<dealii::LA::distributed::Vector<double, MemorySpaceType>>\n      _inverse_mass_matrix;\n  /**\n   * Map between the cell iterator and the position in _inv_rho_cp table.\n   */\n  std::map<typename dealii::DoFHandler<dim>::cell_iterator,\n           std::pair<unsigned int, unsigned int>>\n      _cell_it_to_mf_cell_map;\n  /**\n   * Table of the powder fraction, mutable so that it can be changed in\n   * local_apply, which is const.\n   */\n  mutable dealii::Table<2, dealii::VectorizedArray<double>> _liquid_ratio;\n  /**\n   * Table of the powder fraction, mutable so that it can be changed in\n   * local_apply, which is const.\n   */\n  mutable dealii::Table<2, dealii::VectorizedArray<double>> _powder_ratio;\n  /**\n   * Table of the material index, mutable so that it can be changed in\n   * local_apply, which is const.\n   */\n  mutable dealii::Table<2, std::array<dealii::types::material_id,\n                                      dealii::VectorizedArray<double>::size()>>\n      _material_id;\n};\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline double ThermalOperator<dim, fe_degree, MemorySpaceType>::get_inv_rho_cp(\n    typename dealii::DoFHandler<dim>::cell_iterator const &cell,\n    unsigned int q) const\n{\n  auto cell_comp_pair = _cell_it_to_mf_cell_map.find(cell);\n  ASSERT(cell_comp_pair != _cell_it_to_mf_cell_map.end(), \"Internal error\");\n\n  return _inv_rho_cp(cell_comp_pair->second.first,\n                     q)[cell_comp_pair->second.second];\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline dealii::types::global_dof_index\nThermalOperator<dim, fe_degree, MemorySpaceType>::m() const\n{\n  return _matrix_free.get_vector_partitioner()->size();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline dealii::types::global_dof_index\nThermalOperator<dim, fe_degree, MemorySpaceType>::n() const\n{\n  return _matrix_free.get_vector_partitioner()->size();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline std::shared_ptr<dealii::LA::distributed::Vector<double, MemorySpaceType>>\nThermalOperator<dim, fe_degree, MemorySpaceType>::get_inverse_mass_matrix()\n    const\n{\n  return _inverse_mass_matrix;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline dealii::MatrixFree<dim, double> const &\nThermalOperator<dim, fe_degree, MemorySpaceType>::get_matrix_free() const\n{\n  return _matrix_free;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline void ThermalOperator<dim, fe_degree, MemorySpaceType>::jacobian_vmult(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &dst,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &src) const\n{\n  vmult(dst, src);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline void\nThermalOperator<dim, fe_degree, MemorySpaceType>::initialize_dof_vector(\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &vector) const\n{\n  _matrix_free.initialize_dof_vector(vector);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\ninline void\nThermalOperator<dim, fe_degree, MemorySpaceType>::set_time_and_source_height(\n    double t, double height)\n{\n  _time = t;\n  _current_source_height = height;\n}\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "deb26aef56e8b35febef427d8147092e69a9298c", "size": 10091, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/ThermalOperator.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/ThermalOperator.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/ThermalOperator.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": 34.676975945, "max_line_length": 80, "alphanum_fraction": 0.70220989, "num_tokens": 2435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.032100710073633826, "lm_q1q2_score": 0.013562698786936792}}
{"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#include <unordered_map>\n#include <queue>\n#include <arc_utilities/eigen_helpers.hpp>\n#include <omp.h>\n#include <sys/stat.h>\n#include <string.h>\n#include <fcntl.h>\n#include <unistd.h>\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    /*\n     * See: https://stackoverflow.com/questions/3596781/how-to-detect-if-the-current-process-is-being-run-by-gdb\n     */\n    inline bool IsDebuggerPresent()\n    {\n        const int status_fd = open(\"/proc/self/status\", O_RDONLY);\n        if (status_fd == -1)\n        {\n            return false;\n        }\n        char buf[1024];\n        const ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1);\n        if (num_read > 0)\n        {\n            static const char TracerPid[] = \"TracerPid:\";\n            char *tracer_pid;\n            buf[num_read] = 0;\n            tracer_pid = strstr(buf, TracerPid);\n            if (tracer_pid)\n            {\n                if (!!atoi(tracer_pid + sizeof(TracerPid) - 1))\n                {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n\n    inline void InteractiveWaitToContinue()\n    {\n        if (IsDebuggerPresent() == false)\n        {\n            std::cout << \"Press ENTER to continue...\" << std::endl;\n            std::cin.get();\n        }\n        else\n        {\n            std::cout << \"Process is under debugger, use breakpoints for interactive flow control instead\" << std::endl;\n        }\n    }\n\n    inline void ConditionalPrintWaitForInteractiveInput(const std::string& msg, const int32_t msg_level, const int32_t print_level)\n    {\n        if (unlikely(msg_level <= print_level))\n        {\n            const std::string printstr = \"[\" + std::to_string(msg_level) + \"/\" + std::to_string(print_level) + \"] \" + msg + \"\\n\";\n            std::cout << printstr << std::flush;\n            InteractiveWaitToContinue();\n        }\n    }\n\n    template<typename T>\n    inline bool CheckAlignment(const T& item, const uint64_t desired_alignment)\n    {\n        const T* item_ptr = &item;\n        const uintptr_t item_ptr_val = (uintptr_t)item_ptr;\n        if ((item_ptr_val % desired_alignment) == 0)\n        {\n            //std::cout << \"Item @ \" << item_ptr_val << \" aligned to \" << desired_alignment << \" bytes\" << std::endl;\n            return true;\n        }\n        else\n        {\n            //std::cout << \"Item @ \" << item_ptr_val << \" not aligned to \" << desired_alignment << \" bytes\" << std::endl;\n            return false;\n        }\n    }\n\n    template<typename T>\n    inline void RequireAlignment(const T& item, const uint64_t desired_alignment)\n    {\n        if (CheckAlignment(item, desired_alignment) == false)\n        {\n            std::cout << \"Item not aligned at desired alignment of \" << desired_alignment << std::endl;\n            assert(false);\n        }\n    }\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        // Type safety checks are performed in the SetBit() function\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 <typename Key, typename Value, typename Compare=std::less<Key>, typename Allocator=std::allocator<std::pair<const Key, Value>>>\n    inline Value RetrieveOrDefault(const std::map<Key, Value, Compare, Allocator>& map, const Key& key, const Value& default_val)\n    {\n        const auto found_itr = map.find(key);\n        if (found_itr != map.end())\n        {\n            return found_itr->second;\n        }\n        else\n        {\n            return default_val;\n        }\n    }\n\n    template <typename Key, typename Value, typename Hash=std::hash<Key>, typename Predicate=std::equal_to<Key>, typename Allocator=std::allocator<std::pair<const Key, Value>>>\n    inline Value RetrieveOrDefault(const std::unordered_map<Key, Value, Hash, Predicate, Allocator>& map, const Key& key, const Value& default_val)\n    {\n        const auto found_itr = map.find(key);\n        if (found_itr != map.end())\n        {\n            return found_itr->second;\n        }\n        else\n        {\n            return default_val;\n        }\n    }\n\n    template <class T>\n    inline T ClampValue(const T& val, const T& min, const T& max)\n    {\n        assert(min <= max);\n        return std::min(max, std::max(min, val));\n    }\n\n    template <class T>\n    inline T ClampValueAndWarn(const T& val, const T& min, const T& max)\n    {\n        assert(min <= max);\n        if (val < min)\n        {\n            const std::string msg = \"Clamping \" + std::to_string(val) + \" to min \" + std::to_string(min) + \"\\n\";\n            std::cerr << msg << std::flush;\n            return min;\n        }\n        else if (val > max)\n        {\n            const std::string msg = \"Clamping \" + std::to_string(val) + \" to max \" + std::to_string(max) + \"\\n\";\n            std::cerr << msg << std::flush;\n            return max;\n        }\n        return val;\n    }\n\n    // Written to mimic parts of Matlab wthresh(val, 'h', thresh) behavior, spreading the value to teh thresholds instead of setting them to zero\n    // https://www.mathworks.com/help/wavelet/ref/wthresh.html\n    template <class T>\n    inline T SpreadValue(const T& val, const T& low_threshold, const T& midpoint, const T& high_threshold)\n    {\n        assert(low_threshold <= midpoint);\n        assert(midpoint <= high_threshold);\n        if (val >= midpoint && val < high_threshold)\n        {\n            return high_threshold;\n        }\n        else if (val < midpoint && val > low_threshold)\n        {\n            return low_threshold;\n        }\n        return val;\n    }\n\n    // Written to mimic parts of Matlab wthresh(val, 'h', thresh) behavior, spreading the value to teh thresholds instead of setting them to zero\n    // https://www.mathworks.com/help/wavelet/ref/wthresh.html\n    template <class T>\n    inline T SpreadValueAndWarn(const T& val, const T& low_threshold, const T& midpoint, const T& high_threshold)\n    {\n        assert(low_threshold <= midpoint);\n        assert(midpoint <= high_threshold);\n        if (val >= midpoint && val < high_threshold)\n        {\n            const std::string msg = \"Thresholding \" + std::to_string(val) + \" to high threshold \" + std::to_string(high_threshold) + \"\\n\";\n            std::cerr << msg << std::flush;\n            return high_threshold;\n        }\n        else if (val < midpoint && val > low_threshold)\n        {\n            const std::string msg = \"Thresholding \" + std::to_string(val) + \" to low threshold \" + std::to_string(low_threshold) + \"\\n\";\n            std::cerr << msg << std::flush;\n            return low_threshold;\n        }\n        return val;\n    }\n\n    inline constexpr float ColorChannelFromHex(uint8_t hexval)\n    {\n        return (float)hexval / 255.0f;\n    }\n\n    inline float TrimColorValue(const float val)\n    {\n        return ClampValue<float>(val, 0.0f, 1.0f);\n    }\n\n    inline uint8_t ColorChannelToHex(float colorval)\n    {\n        return (uint8_t)round(TrimColorValue(colorval) * 255.0f);\n    }\n\n    class RGBAColor\n    {\n    public:\n\n        float r;\n        float g;\n        float b;\n        float a;\n\n        RGBAColor(const float in_r, const float in_g, const float in_b, const float in_a) : r(TrimColorValue(in_r)), g(TrimColorValue(in_g)), b(TrimColorValue(in_b)), a(TrimColorValue(in_a)) {}\n\n        RGBAColor(const float in_r, const float in_g, const float in_b) : r(TrimColorValue(in_r)), g(TrimColorValue(in_g)), b(TrimColorValue(in_b)), a(1.0f) {}\n\n        RGBAColor(const uint8_t in_r, const uint8_t in_g, const uint8_t in_b, const uint8_t in_a) : r(ColorChannelFromHex(in_r)), g(ColorChannelFromHex(in_g)), b(ColorChannelFromHex(in_b)), a(ColorChannelFromHex(in_a)) {}\n\n        RGBAColor(const uint8_t in_r, const uint8_t in_g, const uint8_t in_b, const float in_a) : r(ColorChannelFromHex(in_r)), g(ColorChannelFromHex(in_g)), b(ColorChannelFromHex(in_b)), a(TrimColorValue(in_a)) {}\n\n        RGBAColor(const uint8_t in_r, const uint8_t in_g, const uint8_t in_b) : r(ColorChannelFromHex(in_r)), g(ColorChannelFromHex(in_g)), b(ColorChannelFromHex(in_b)), a(1.0f) {}\n\n        RGBAColor() : r(0.0f), g(0.0f), b(0.0f), a(0.0f) {}\n\n        inline float GetR() const\n        {\n            return r;\n        }\n\n        inline float GetG() const\n        {\n            return g;\n        }\n\n        inline float GetB() const\n        {\n            return b;\n        }\n\n        inline float GetA() const\n        {\n            return a;\n        }\n\n        inline void SetR(const float new_r)\n        {\n            r = TrimColorValue(new_r);\n        }\n\n        inline void SetG(const float new_g)\n        {\n            g = TrimColorValue(new_g);\n        }\n\n        inline void SetB(const float new_b)\n        {\n            b = TrimColorValue(new_b);\n        }\n\n        inline void SetA(const float new_a)\n        {\n            a = TrimColorValue(new_a);\n        }\n\n        inline uint8_t GetRHex() const\n        {\n            return ColorChannelToHex(r);\n        }\n\n        inline uint8_t GetGHex() const\n        {\n            return ColorChannelToHex(g);\n        }\n\n        inline uint8_t GetBHex() const\n        {\n            return ColorChannelToHex(b);\n        }\n\n        inline uint8_t GetAHex() const\n        {\n            return ColorChannelToHex(a);\n        }\n\n        inline void SetRHex(const uint8_t hex_r)\n        {\n            r = ColorChannelFromHex(hex_r);\n        }\n\n        inline void SetGHex(const uint8_t hex_g)\n        {\n            g = ColorChannelFromHex(hex_g);\n        }\n\n        inline void SetBHex(const uint8_t hex_b)\n        {\n            b = ColorChannelFromHex(hex_b);\n        }\n\n        inline void SetAHex(const uint8_t hex_a)\n        {\n            a = ColorChannelFromHex(hex_a);\n        }\n    };\n\n    template<typename ColorType>\n    class RGBAColorBuilder\n    {\n    private:\n\n        RGBAColorBuilder() {}\n\n    public:\n\n        static inline ColorType MakeFromFloatColors(const float r, const float g, const float b, const float a=1.0f)\n        {\n            ColorType color;\n            color.r = TrimColorValue(r);\n            color.g = TrimColorValue(g);\n            color.b = TrimColorValue(b);\n            color.a = TrimColorValue(a);\n            return color;\n        }\n\n        static inline ColorType MakeFromHexColors(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t a=0xff)\n        {\n            return MakeFromFloatColors(ColorChannelFromHex(r), ColorChannelFromHex(g), ColorChannelFromHex(b), ColorChannelFromHex(a));\n        }\n\n        static inline ColorType MakeFromMixedColors(const uint8_t r, const uint8_t g, const uint8_t b, const float a=1.0f)\n        {\n            return MakeFromFloatColors(ColorChannelFromHex(r), ColorChannelFromHex(g), ColorChannelFromHex(b), TrimColorValue(a));\n        }\n\n        static inline ColorType InterpolateHotToCold(const double value, const double min_value=0.0, const double max_value=1.0)\n        {\n            assert(min_value < max_value);\n            const double real_value = ClampValue(value, min_value, max_value);\n            const double range = max_value - min_value;\n            // Start with white\n            double r = 1.0;\n            double g = 1.0;\n            double b = 1.0;\n            // Interpolate\n            if (real_value < (min_value + (0.25 * range)))\n            {\n                r = 0.0;\n                g = 4.0 * (real_value - min_value) / range;\n            }\n            else if (real_value < (min_value + (0.5 * range)))\n            {\n                r = 0.0;\n                b = 1.0 + 4.0 * (min_value + 0.25 * range - real_value) / range;\n            }\n            else if (real_value < (min_value + (0.75 * range)))\n            {\n                r = 4.0 * (real_value - min_value - 0.5 * range) / range;\n                b = 0.0;\n            }\n            else\n            {\n                g = 1.0 + 4.0 * (min_value + 0.75 * range - real_value) / range;\n                b = 0.0;\n            }\n            return MakeFromFloatColors((float)r, (float)g, (float)b, 1.0f);\n        }\n\n    };\n\n    template<typename ColorTypeA, typename ColorTypeB>\n    inline ColorTypeB ConvertColor(const ColorTypeA& color)\n    {\n        ColorTypeB cvt_color;\n        cvt_color.r = TrimColorValue(color.r);\n        cvt_color.g = TrimColorValue(color.g);\n        cvt_color.b = TrimColorValue(color.b);\n        cvt_color.a = TrimColorValue(color.a);\n        return cvt_color;\n    }\n\n    template<typename ColorType>\n    inline ColorType GenerateUniqueColor(const uint32_t color_code, const float alpha=1.0f)\n    {\n        // For color_code < 22, we pick from a table\n        if (color_code == 0)\n        {\n            return RGBAColorBuilder<ColorType>::MakeFromFloatColors(1.0f, 1.0f, 1.0f, 0.0f);\n        }\n        else if (color_code <= 20)\n        {\n            // CHECK TO MAKE SURE RGB/RBG IS CORRECT!\n            if (color_code == 1)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xff, 0x00, 0xb3, alpha);\n            }\n            else if (color_code == 2)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x80, 0x75, 0x3e, alpha);\n            }\n            else if (color_code == 3)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xff, 0x00, 0x68, alpha);\n            }\n            else if (color_code == 4)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xa6, 0xd7, 0xbd, alpha);\n            }\n            else if (color_code == 5)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xc1, 0x20, 0x00, alpha);\n            }\n            else if (color_code == 6)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xce, 0x62, 0xa2, alpha);\n            }\n            else if (color_code == 7)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x81, 0x66, 0x70, alpha);\n            }\n            else if (color_code == 8)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x00, 0x34, 0x7d, alpha);\n            }\n            else if (color_code == 9)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xf6, 0x8e, 0x76, alpha);\n            }\n            else if (color_code == 10)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x00, 0x8a, 0x53, alpha);\n            }\n            else if (color_code == 11)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xff, 0x5c, 0x7a, alpha);\n            }\n            else if (color_code == 12)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x53, 0x7a, 0x37, alpha);\n            }\n            else if (color_code == 13)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xff, 0x00, 0x8e, alpha);\n            }\n            else if (color_code == 14)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xb3, 0x51, 0x28, alpha);\n            }\n            else if (color_code == 15)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xf4, 0x00, 0xc8, alpha);\n            }\n            else if (color_code == 16)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x7f, 0x0d, 0x18, alpha);\n            }\n            else if (color_code == 17)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x93, 0x00, 0xaa, alpha);\n            }\n            else if (color_code == 18)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x59, 0x15, 0x33, alpha);\n            }\n            else if (color_code == 19)\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0xf1, 0x13, 0x3a, alpha);\n            }\n            else\n            {\n                return RGBAColorBuilder<ColorType>::MakeFromMixedColors(0x23, 0x16, 0x2c, alpha);\n            }\n        }\n        else\n        {\n            return RGBAColorBuilder<ColorType>::MakeFromFloatColors(0.0f, 0.0f, 0.0f, alpha);\n        }\n    }\n\n    inline 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    template<typename Datatype, typename Allocator=std::allocator<Datatype>>\n    inline Eigen::MatrixXd BuildDistanceMatrixParallel(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        #if defined(_OPENMP)\n        #pragma omp parallel for\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                if (idx != 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                else\n                {\n                    distance_matrix((ssize_t)idx, (ssize_t)jdx) = 0.0;\n                    distance_matrix((ssize_t)jdx, (ssize_t)idx) = 0.0;\n                }\n            }\n        }\n        return distance_matrix;\n    }\n\n    template<typename FirstDatatype, typename SecondDatatype, typename FirstAllocator=std::allocator<FirstDatatype>, typename SecondAllocator=std::allocator<SecondDatatype>>\n    inline Eigen::MatrixXd BuildDistanceMatrixParallel(const std::vector<FirstDatatype, FirstAllocator>& data1, const std::vector<SecondDatatype, SecondAllocator>& data2, const std::function<double(const FirstDatatype&, const SecondDatatype&)>& distance_fn)\n    {\n        Eigen::MatrixXd distance_matrix(data1.size(), data1.size());\n        #if defined(_OPENMP)\n        #pragma omp parallel for\n        #endif\n        for (size_t idx = 0; idx < data1.size(); idx++)\n        {\n            for (size_t jdx = 0; jdx < data2.size(); jdx++)\n            {\n                const double distance = distance_fn(data1[idx], data2[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    template<typename Datatype, typename Allocator=std::allocator<Datatype>>\n    inline Eigen::MatrixXd BuildDistanceMatrixSerial(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        for (size_t idx = 0; idx < data.size(); idx++)\n        {\n            for (size_t jdx = idx; jdx < data.size(); jdx++)\n            {\n                if (idx != 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                else\n                {\n                    distance_matrix((ssize_t)idx, (ssize_t)jdx) = 0.0;\n                    distance_matrix((ssize_t)jdx, (ssize_t)idx) = 0.0;\n                }\n            }\n        }\n        return distance_matrix;\n    }\n\n    template<typename FirstDatatype, typename SecondDatatype, typename FirstAllocator=std::allocator<FirstDatatype>, typename SecondAllocator=std::allocator<SecondDatatype>>\n    inline Eigen::MatrixXd BuildDistanceMatrixSerial(const std::vector<FirstDatatype, FirstAllocator>& data1, const std::vector<SecondDatatype, SecondAllocator>& data2, const std::function<double(const FirstDatatype&, const SecondDatatype&)>& distance_fn)\n    {\n        Eigen::MatrixXd distance_matrix(data1.size(), data1.size());\n        for (size_t idx = 0; idx < data1.size(); idx++)\n        {\n            for (size_t jdx = 0; jdx < data2.size(); jdx++)\n            {\n                const double distance = distance_fn(data1[idx], data2[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    template<typename Item, typename Value, typename ItemAlloc=std::allocator<Item>>\n    std::vector<std::pair<int64_t, double>> GetKNearestNeighborsParallel(const std::vector<Item, ItemAlloc>& items, const Value& current, const std::function<double(const Item&, const Value&)>& distance_fn, const size_t K)\n    {\n        if (K == 0)\n        {\n            return std::vector<std::pair<int64_t, double>>();\n        }\n        if (items.size() > K)\n        {\n            std::function<bool(const std::pair<int64_t, double>&, const std::pair<int64_t, double>&)> compare_fn = [] (const std::pair<int64_t, double>& index1, const std::pair<int64_t, double>& index2) { return index1.second < index2.second; };\n            std::vector<std::vector<std::pair<int64_t, double>>> per_thread_nearests(GetNumOMPThreads(), std::vector<std::pair<int64_t, double>>(K, std::make_pair(-1, std::numeric_limits<double>::infinity())));\n            #if defined(_OPENMP)\n            #pragma omp parallel for\n            #endif\n            for (size_t idx = 0; idx < items.size(); idx++)\n            {\n                const Item& item = items[idx];\n                const double distance = distance_fn(item, current);\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                std::vector<std::pair<int64_t, double>>& current_thread_nearests = per_thread_nearests[thread_num];\n                auto itr = std::max_element(current_thread_nearests.begin(), current_thread_nearests.end(), compare_fn);\n                const double worst_distance = itr->second;\n                if (worst_distance > distance)\n                {\n                    itr->first = (int64_t)idx;\n                    itr->second = distance;\n                }\n            }\n            std::vector<std::pair<int64_t, double>> k_nearests;\n            k_nearests.reserve(K);\n            for (size_t thread_idx = 0; thread_idx < per_thread_nearests.size(); thread_idx++)\n            {\n                const std::vector<std::pair<int64_t, double>>& thread_nearests = per_thread_nearests[thread_idx];\n                for (size_t nearest_idx = 0; nearest_idx < thread_nearests.size(); nearest_idx++)\n                {\n                    const std::pair<int64_t, double> current_ith_nearest = thread_nearests[nearest_idx];\n                    if (!std::isinf(current_ith_nearest.second) && current_ith_nearest.first != -1)\n                    {\n                        if (k_nearests.size() < K)\n                        {\n                            k_nearests.push_back(current_ith_nearest);\n                        }\n                        else\n                        {\n                            auto itr = std::max_element(k_nearests.begin(), k_nearests.end(), compare_fn);\n                            const double worst_distance = itr->second;\n                            if (worst_distance > current_ith_nearest.second)\n                            {\n                                itr->first = current_ith_nearest.first;\n                                itr->second = current_ith_nearest.second;\n                            }\n                        }\n                    }\n                }\n            }\n            k_nearests.shrink_to_fit();\n            return k_nearests;\n        }\n        else\n        {\n            std::vector<std::pair<int64_t, double>> k_nearests(items.size(), std::make_pair(-1, std::numeric_limits<double>::infinity()));\n            #if defined(_OPENMP)\n            #pragma omp parallel for\n            #endif\n            for (size_t idx = 0; idx < items.size(); idx++)\n            {\n                const Item& item = items[idx];\n                const double distance = distance_fn(item, current);\n                k_nearests[idx] = std::make_pair((int64_t)idx, distance);\n            }\n            return k_nearests;\n        }\n    }\n\n    template<typename Item, typename Value, typename ItemAlloc=std::allocator<Item>>\n    std::vector<std::pair<int64_t, double>> GetKNearestNeighborsSerial(const std::vector<Item, ItemAlloc>& items, const Value& current, const std::function<double(const Item&, const Value&)>& distance_fn, const size_t K)\n    {\n        if (K == 0)\n        {\n            return std::vector<std::pair<int64_t, double>>();\n        }\n        if (items.size() > K)\n        {\n            std::function<bool(const std::pair<int64_t, double>&, const std::pair<int64_t, double>&)> compare_fn = [] (const std::pair<int64_t, double>& index1, const std::pair<int64_t, double>& index2) { return index1.second < index2.second; };\n            std::vector<std::pair<int64_t, double>> k_nearests(K, std::make_pair(-1, std::numeric_limits<double>::infinity()));\n            for (size_t idx = 0; idx < items.size(); idx++)\n            {\n                const Item& item = items[idx];\n                const double distance = distance_fn(item, current);\n                auto itr = std::max_element(k_nearests.begin(), k_nearests.end(), compare_fn);\n                const double worst_distance = itr->second;\n                if (worst_distance > distance)\n                {\n                    itr->first = (int64_t)idx;\n                    itr->second = distance;\n                }\n            }\n            return k_nearests;\n        }\n        else\n        {\n            std::vector<std::pair<int64_t, double>> k_nearests(items.size(), std::make_pair(-1, std::numeric_limits<double>::infinity()));\n            for (size_t idx = 0; idx < items.size(); idx++)\n            {\n                const Item& item = items[idx];\n                const double distance = distance_fn(item, current);\n                k_nearests[idx] = std::make_pair((int64_t)idx, distance);\n            }\n            return k_nearests;\n        }\n    }\n\n    class AstarPQueueElement\n    {\n    protected:\n\n        int64_t node_id_;\n        int64_t backpointer_;\n        double cost_to_come_;\n        double value_;\n\n    public:\n\n        AstarPQueueElement(const int64_t node_id, const int64_t backpointer, const double cost_to_come, const double value) : node_id_(node_id), backpointer_(backpointer), cost_to_come_(cost_to_come), value_(value) {}\n\n        inline int64_t NodeID() const { return node_id_; }\n\n        inline int64_t Backpointer() const { return backpointer_; }\n\n        inline double CostToCome() const { return cost_to_come_; }\n\n        inline double Value() const { return value_; }\n    };\n\n    class CompareAstarPQueueElementFn\n    {\n        public:\n\n            bool operator()(const AstarPQueueElement& lhs, const AstarPQueueElement& rhs) const\n            {\n                return lhs.Value() > rhs.Value();\n            }\n    };\n\n    // Return is a pair<path, cost>\n    // Path is a vector of node indices in the provided graph\n    // Cost is the computed cost-to-come of the goal node\n    typedef std::pair<std::vector<int64_t>, double> AstarResult;\n\n    inline AstarResult ExtractAstarResult(const std::unordered_map<int64_t, std::pair<int64_t, double>>& explored, const int64_t start_index, const int64_t goal_index)\n    {\n        // Check if a solution was found\n        const auto goal_index_itr = explored.find(goal_index);\n        // If no solution found\n        if (goal_index_itr == explored.end())\n        {\n            return std::make_pair(std::vector<int64_t>(), std::numeric_limits<double>::infinity());\n        }\n        // If a solution was found\n        else\n        {\n            // Extract the path indices in reverse order\n            std::vector<int64_t> solution_path_indices;\n            solution_path_indices.push_back(goal_index);\n            int64_t backpointer = goal_index_itr->second.first;\n            // Any backpointer >= 0 is a valid node in the graph\n            // The backpointer for start_index is -1\n            while (backpointer >= 0)\n            {\n                const int64_t current_index = backpointer;\n                solution_path_indices.push_back(current_index);\n                if (current_index == start_index)\n                {\n                    break;\n                }\n                else\n                {\n                    // Using map.at(key) throws an exception if key not found\n                    // This provides bounds safety check\n                    const auto current_index_data = explored.at(current_index);\n                    backpointer = current_index_data.first;\n                }\n            }\n            // Reverse\n            std::reverse(solution_path_indices.begin(), solution_path_indices.end());\n            // Get the cost of the path\n            const double solution_path_cost = goal_index_itr->second.second;\n            return std::make_pair(solution_path_indices, solution_path_cost);\n        }\n    }\n\n    inline AstarResult GenericAstarSearch(const int64_t start_id, const int64_t goal_id, const std::function<std::vector<int64_t>(const int64_t)>& generate_children_fn, const std::function<bool(const int64_t, const int64_t)>& edge_validity_check_fn, const std::function<double(const int64_t, const int64_t)>& distance_fn, const std::function<double(const int64_t, const int64_t)>& heuristic_fn, const bool limit_pqueue_duplicates)\n    {\n        // Enforced sanity checks\n        if (start_id == goal_id)\n        {\n            throw std::invalid_argument(\"Start and goal ID must be different\");\n        }\n        // Make helper function\n        const auto heuristic_function = [&] (const int64_t node_index) { return heuristic_fn(node_index, goal_id); };\n        // Setup\n        std::priority_queue<AstarPQueueElement, std::vector<AstarPQueueElement>, CompareAstarPQueueElementFn> queue;\n        // Optional map to reduce the number of duplicate items added to the pqueue\n        // Key is the node ID\n        // Value is cost-to-come\n        std::unordered_map<int64_t, double> queue_members_map;\n        // Key is the node ID\n        // Value is a pair<backpointer, cost-to-come>\n        // backpointer is the parent node ID\n        std::unordered_map<int64_t, std::pair<int64_t, double>> explored;\n        // Initialize\n        queue.push(AstarPQueueElement(start_id, -1, 0.0, heuristic_function(start_id)));\n        if (limit_pqueue_duplicates)\n        {\n            queue_members_map[start_id] = 0.0;\n        }\n        // Search\n        while (queue.size() > 0)\n        {\n            // Get the top of the priority queue\n            const 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 node_explored_is_better = (node_in_explored) ? (top_node.CostToCome() >= node_explored_find_itr->second.second) : false;\n            if (!node_explored_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_id)\n                {\n                    break;\n                }\n                // Generate possible children\n                const std::vector<int64_t> candidate_children = generate_children_fn(top_node.NodeID());\n                // Loop through potential child nodes\n                for (const int64_t child_node_id : candidate_children)\n                {\n                    // Check if the top node->child edge is valid\n                    if (edge_validity_check_fn(top_node.NodeID(), child_node_id))\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(top_node.NodeID(), child_node_id);\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_id);\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_id);\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_id);\n                            // Compute the child value\n                            const double child_value = child_cost_to_come + child_heuristic;\n                            queue.push(AstarPQueueElement(child_node_id, top_node.NodeID(), child_cost_to_come, child_value));\n                        }\n                    }\n                }\n            }\n        }\n        return ExtractAstarResult(explored, start_id, goal_id);\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\n    // SEE https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf FOR DETAILS\n    inline double EvaluateGaussianCDF(const double mean, const double std_dev, const double val)\n    {\n        return 0.5 * (1.0 + std::erf( ( (val - mean) / std_dev ) / sqrt(2.0) ) );\n    }\n\n    inline double EvaluateGaussianPDF(const double mean, const double std_dev, const double val)\n    {\n        const double exponent = ((val - mean) * (val - mean)) / (2.0 * std_dev * std_dev);\n        const double fraction = 1.0 / (std_dev * std::sqrt(2.0 * M_PI));\n        const double pdf = fraction * std::exp(-exponent);\n        return pdf;\n    }\n\n    inline double EvaluateTruncatedGaussianCDF(const double mean, const double lower_bound, const double upper_bound, const double std_dev, const double val)\n    {\n        assert(lower_bound <= upper_bound);\n        if (val <= lower_bound)\n        {\n            return 0.0;\n        }\n        else if (val >= upper_bound)\n        {\n            return 1.0;\n        }\n        else\n        {\n            const double cdf_lower_bound = EvaluateGaussianCDF(mean, std_dev, lower_bound);\n            const double numerator = EvaluateGaussianCDF(mean, std_dev, val) - cdf_lower_bound;\n            const double denominator = EvaluateGaussianCDF(mean, std_dev, upper_bound) - cdf_lower_bound;\n            return numerator / denominator;\n        }\n    }\n\n    inline double EvaluateTruncatedGaussianPDF(const double mean, const double lower_bound, const double upper_bound, const double std_dev, const double val)\n    {\n        assert(lower_bound <= upper_bound);\n        if (val <= lower_bound)\n        {\n            return 0.0;\n        }\n        else if (val >= upper_bound)\n        {\n            return 0.0;\n        }\n        else\n        {\n            const double cdf_upper = EvaluateGaussianCDF(mean, std_dev, upper_bound);\n            const double cdf_lower = EvaluateGaussianCDF(mean, std_dev, lower_bound);\n            const double probability_enclosed = cdf_upper - cdf_lower;\n            const double gaussian_pdf = EvaluateGaussianPDF(mean, std_dev, val);\n            const double pdf = gaussian_pdf / probability_enclosed;\n            return pdf;\n        }\n    }\n\n    inline double IntegrateGaussian(const double mean, const double std_dev, const double lower_limit, const double upper_limit)\n    {\n        assert(lower_limit <= upper_limit);\n        const double upper_limit_cdf = EvaluateGaussianCDF(mean, std_dev, upper_limit);\n        const double lower_limit_cdf = EvaluateGaussianCDF(mean, std_dev, lower_limit);\n        const double probability = upper_limit_cdf - lower_limit_cdf;\n        //const std::string msg = \"Integrated Gaussian with mean \" + std::to_string(mean) + \" std.dev. \" + std::to_string(std_dev) + \" over range [\" + std::to_string(lower_limit) + \",\" + std::to_string(upper_limit) + \"] to be \" + std::to_string(probability);\n        //std::cout << msg << std::endl;\n        return probability;\n    }\n\n    inline double IntegrateTruncatedGaussian(const double mean, const double lower_bound, const double upper_bound, const double std_dev, const double lower_limit, const double upper_limit)\n    {\n        assert(lower_bound <= upper_bound);\n        assert(lower_limit <= upper_limit);\n        const double lower_limit_cdf = EvaluateTruncatedGaussianCDF(mean, lower_bound, upper_bound, std_dev, lower_limit);\n        const double upper_limit_cdf = EvaluateTruncatedGaussianCDF(mean, lower_bound, upper_bound, std_dev, upper_limit);\n        const double probability = upper_limit_cdf - lower_limit_cdf;\n        //const std::string msg = \"Integrated truncated Gaussian with mean \" + std::to_string(mean) + \" std.dev. \" + std::to_string(std_dev) + \" and bounds [\" + std::to_string(lower_bound) + \",\" + std::to_string(upper_bound) + \"] over range [\" + std::to_string(lower_limit) + \",\" + std::to_string(upper_limit) + \"] to be \" + std::to_string(probability);\n        //std::cout << msg << std::endl;\n        return probability;\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    public:\n\n        inline RandomRotationGenerator() : uniform_unit_dist_(0.0, 1.0) {}\n\n        // From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III, pg. 124-132\n        static inline Eigen::Quaterniond GenerateUniformRandomQuaternion(const std::function<double()>& uniform_unit_dist)\n        {\n            const double x0 = uniform_unit_dist();\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();\n            const double t2 = 2.0 * M_PI * uniform_unit_dist();\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        static inline Eigen::Vector3d GenerateUniformRandomEulerAngles(const std::function<double()>& uniform_unit_dist)\n        {\n            const double roll = 2.0 * M_PI * uniform_unit_dist() -  M_PI;\n            const double pitch_init = std::acos(1.0 - (2.0 * uniform_unit_dist())) + M_PI_2;\n            const double pitch = (uniform_unit_dist() < 0.5) ? ((pitch_init < M_PI) ? pitch_init + M_PI : pitch_init - M_PI) : pitch_init;\n            const double yaw = 2.0 * M_PI * uniform_unit_dist() -  M_PI;\n            return Eigen::Vector3d(roll, pitch, yaw);\n        }\n\n        template<typename Generator>\n        inline Eigen::Quaterniond GetQuaternion(Generator& prng)\n        {\n            std::function<double()> uniform_rand_fn = [&] () { return uniform_unit_dist_(prng); };\n            return GenerateUniformRandomQuaternion(uniform_rand_fn);\n        }\n\n        template<typename Generator>\n        inline std::vector<double> GetRawQuaternion(Generator& prng)\n        {\n            const Eigen::Quaterniond quat = GetQuaternion(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            std::function<double()> uniform_rand_fn = [&] () { return uniform_unit_dist_(prng); };\n            return GenerateUniformRandomEulerAngles(uniform_rand_fn);\n        }\n\n        template<typename Generator>\n        inline std::vector<double> GetRawEulerAngles(Generator& prng)\n        {\n            const Eigen::Vector3d angles = GetEulerAngles(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 T, typename VectorLike=std::vector<T>>\n    inline uint64_t SerializeVectorLike(const VectorLike& 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 VectorLike=std::vector<T>>\n    inline std::pair<VectorLike, uint64_t> DeserializeVectorLike(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    template<typename T>\n    inline uint64_t SerializeNetworkFixedSizePOD(const T& item_to_serialize, std::vector<uint8_t>& buffer);\n\n    template<typename T>\n    inline std::pair<T, uint64_t> DeserializeNetworkFixedSizePOD(const std::vector<uint8_t>& buffer, const uint64_t current);\n\n    template<typename T, typename Allocator=std::allocator<T>>\n    inline uint64_t SerializeNetworkVector(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> DeserializeNetworkVector(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 SerializeNetworkMap(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> DeserializeNetworkMap(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 SerializeNetworkPair(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> DeserializeNetworkPair(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 CharType>\n    inline uint64_t SerializeString(const std::basic_string<CharType>& str_to_serialize, std::vector<uint8_t>& buffer)\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)str_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 CharType& current = str_to_serialize[idx];\n            SerializeFixedSizePOD<CharType>(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 CharType>\n    inline std::pair<std::basic_string<CharType>, uint64_t> DeserializeString(const std::vector<uint8_t>& buffer, const uint64_t current)\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::basic_string<CharType> deserialized;\n        deserialized.reserve(size);\n        for (uint64_t idx = 0; idx < size; idx++)\n        {\n            const std::pair<CharType, uint64_t> deserialized_char = DeserializeFixedSizePOD<CharType>(buffer, current_position);\n            deserialized.push_back(deserialized_char.first);\n            current_position += deserialized_char.second;\n        }\n        deserialized.shrink_to_fit();\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 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        deserialized.shrink_to_fit();\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 T, typename VectorLike>\n    inline uint64_t SerializeVectorLike(const VectorLike& 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 VectorLike>\n    inline std::pair<VectorLike, uint64_t> DeserializeVectorLike(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        VectorLike 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        deserialized.shrink_to_fit();\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    template<typename T>\n    inline uint64_t SerializeNetworkFixedSizePOD(const T& item_to_serialize, std::vector<uint8_t>& buffer)\n    {\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                       || std::is_same<T, int8_t>::value\n                       || std::is_same<T, int16_t>::value\n                       || std::is_same<T, int32_t>::value\n                       || std::is_same<T, int64_t>::value\n                       || std::is_same<T, float>::value\n                       || std::is_same<T, double>::value),\n                      \"Automatic host<->network serialization only works for 1/2/4/8-byte-sized types - CHANGE TO INTEGRAL + FLOAT/DOUBLE types!\");\n        const uint64_t start_buffer_size = buffer.size();\n        // Fixed-size serialization via memcpy with fixed-size byte swap\n        std::vector<uint8_t> temp_buffer(sizeof(item_to_serialize), 0x00);\n        if (sizeof(T) == 1)\n        {\n            memcpy(&temp_buffer[0], &item_to_serialize, sizeof(item_to_serialize));\n        }\n        else if (sizeof(T) == 2)\n        {\n            uint16_t swap_temp;\n            memcpy(&swap_temp, &item_to_serialize, 2);\n            const uint16_t swapped = htobe16(swap_temp);\n            memcpy(&temp_buffer[0], &swapped, 2);\n        }\n        else if (sizeof(T) == 4)\n        {\n            uint32_t swap_temp;\n            memcpy(&swap_temp, &item_to_serialize, 4);\n            const uint32_t swapped = htobe32(swap_temp);\n            memcpy(&temp_buffer[0], &swapped, 4);\n        }\n        else if (sizeof(T) == 8)\n        {\n            uint64_t swap_temp;\n            memcpy(&swap_temp, &item_to_serialize, 8);\n            const uint64_t swapped = htobe64(swap_temp);\n            memcpy(&temp_buffer[0], &swapped, 8);\n        }\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> DeserializeNetworkFixedSizePOD(const std::vector<uint8_t>& buffer, const uint64_t current)\n    {\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                       || std::is_same<T, int8_t>::value\n                       || std::is_same<T, int16_t>::value\n                       || std::is_same<T, int32_t>::value\n                       || std::is_same<T, int64_t>::value\n                       || std::is_same<T, float>::value\n                       || std::is_same<T, double>::value),\n                      \"Automatic host<->network deserialization only works for 1/2/4/8-byte-sized types\");\n        T temp_item;\n        assert(current <= buffer.size());\n        assert((current + sizeof(temp_item)) <= buffer.size());\n        if (sizeof(T) == 1)\n        {\n            memcpy(&temp_item, &buffer[current], sizeof(temp_item));\n        }\n        else if (sizeof(T) == 2)\n        {\n            uint16_t swap_temp;\n            memcpy(&swap_temp, &buffer[current], 2);\n            const uint16_t swapped = be16toh(swap_temp);\n            memcpy(&temp_item, &swapped, 2);\n        }\n        else if (sizeof(T) == 4)\n        {\n            uint32_t swap_temp;\n            memcpy(&swap_temp, &buffer[current], 4);\n            const uint32_t swapped = be32toh(swap_temp);\n            memcpy(&temp_item, &swapped, 4);\n        }\n        else if (sizeof(T) == 8)\n        {\n            uint64_t swap_temp;\n            memcpy(&swap_temp, &buffer[current], 8);\n            const uint64_t swapped = be64toh(swap_temp);\n            memcpy(&temp_item, &swapped, 8);\n        }\n        return std::make_pair(temp_item, sizeof(temp_item));\n    }\n\n    template<typename CharType>\n    inline uint64_t SerializeNetworkString(const std::basic_string<CharType>& str_to_serialize, std::vector<uint8_t>& buffer)\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)str_to_serialize.size();\n        SerializeNetworkFixedSizePOD<uint64_t>(size, buffer);\n        // Serialize the contained items\n        for (size_t idx = 0; idx < size; idx++)\n        {\n            const CharType& current = str_to_serialize[idx];\n            SerializeNetworkFixedSizePOD<CharType>(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 CharType>\n    inline std::pair<std::basic_string<CharType>, uint64_t> DeserializeNetworkString(const std::vector<uint8_t>& buffer, const uint64_t current)\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 = DeserializeNetworkFixedSizePOD<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::basic_string<CharType> deserialized;\n        deserialized.reserve(size);\n        for (uint64_t idx = 0; idx < size; idx++)\n        {\n            const std::pair<CharType, uint64_t> deserialized_char = DeserializeNetworkFixedSizePOD<CharType>(buffer, current_position);\n            deserialized.push_back(deserialized_char.first);\n            current_position += deserialized_char.second;\n        }\n        deserialized.shrink_to_fit();\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 T, typename Allocator>\n    inline uint64_t SerializeNetworkVector(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        SerializeNetworkFixedSizePOD<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> DeserializeNetworkVector(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 = DeserializeNetworkFixedSizePOD<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        deserialized.shrink_to_fit();\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 SerializeNetworkMap(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        SerializeNetworkFixedSizePOD<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            SerializeNetworkPair<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> DeserializeNetworkMap(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 = DeserializeNetworkFixedSizePOD<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 = DeserializeNetworkPair(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 SerializeNetworkPair(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> DeserializeNetworkPair(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            const std::string printstr = \"[\" + std::to_string(msg_level) + \"/\" + std::to_string(print_level) + \"] \" + msg + \"\\n\";\n            std::cout << printstr << std::flush;\n        }\n    }\n\n    inline void ConditionalError(const std::string& msg, const int32_t msg_level, const int32_t print_level)\n    {\n        if (unlikely(msg_level <= print_level))\n        {\n            const std::string printstr = \"[\" + std::to_string(msg_level) + \"/\" + std::to_string(print_level) + \"] \" + msg + \"\\n\";\n            std::cerr << printstr << std::flush;\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    template <typename Key, typename Value, typename Compare=std::less<Key>, typename Allocator=std::allocator<std::pair<const Key, Value>>>\n    inline std::vector<Key> GetKeys(const std::map<Key, Value, Compare, Allocator>& map)\n    {\n        std::vector<Key> keys;\n        keys.reserve(map.size());\n        typename std::map<Key, Value, Compare, Allocator>::const_iterator itr;\n        for (itr = map.begin(); itr != map.end(); ++itr)\n        {\n            const Key cur_key = itr->first;\n            keys.push_back(cur_key);\n        }\n        keys.shrink_to_fit();\n        return keys;\n    }\n\n    template <typename Key, typename Value, typename Compare=std::less<Key>, typename Allocator=std::allocator<std::pair<const Key, Value>>>\n    inline std::vector<std::pair<const Key, Value>, Allocator> GetKeysAndValues(const std::map<Key, Value, Compare, Allocator>& map)\n    {\n        std::vector<std::pair<const Key, Value>, Allocator> keys_and_values;\n        keys_and_values.reserve(map.size());\n        typename std::map<Key, Value, Compare, Allocator>::const_iterator itr;\n        for (itr = map.begin(); itr != map.end(); ++itr)\n        {\n            const std::pair<Key, Value> cur_pair(itr->first, itr->second);\n            keys_and_values.push_back(cur_pair);\n        }\n        keys_and_values.shrink_to_fit();\n        return keys_and_values;\n    }\n\n    template <typename Key, typename Value, typename Compare=std::less<Key>, typename Allocator=std::allocator<std::pair<const Key, Value>>>\n    inline std::map<Key, Value, Compare, Allocator> MakeFromKeysAndValues(const std::vector<std::pair<const Key, Value>, Allocator>& keys_and_values)\n    {\n        std::map<Key, Value, Compare, Allocator> map;\n        for (size_t idx = 0; idx < keys_and_values.size(); idx++)\n        {\n            const std::pair<Key, Value>& cur_pair = keys_and_values[idx];\n            map[cur_pair.first] = cur_pair.second;\n        }\n        return map;\n    }\n\n    template <typename Key, typename Value, typename Compare=std::less<Key>, typename KeyVectorAllocator=std::allocator<Key>, typename ValueVectorAllocator=std::allocator<Value>, typename PairAllocator=std::allocator<std::pair<const Key, Value>>>\n    inline std::map<Key, Value, Compare, PairAllocator> MakeFromKeysAndValues(const std::vector<Key, KeyVectorAllocator>& keys, const std::vector<Value, ValueVectorAllocator>& values)\n    {\n        assert(keys.size() == values.size());\n        std::map<Key, Value, Compare, PairAllocator> map;\n        for (size_t idx = 0; idx < keys.size(); idx++)\n        {\n            const Key& cur_key = keys[idx];\n            const Value& cur_value = values[idx];\n            map[cur_key] = cur_value;\n        }\n        return map;\n    }\n}\n\n#endif // ARC_HELPERS_HPP\n", "meta": {"hexsha": "11c025642385debeb7839bfa46ddd1cda54c337c", "size": 93287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/arc_helpers.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/arc_helpers.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/arc_helpers.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": 43.5310312646, "max_line_length": 430, "alphanum_fraction": 0.5958922465, "num_tokens": 21483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.03210070579104255, "lm_q1q2_score": 0.01356269697752213}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iterator>\n\n#include <boost/program_options.hpp>\n\n#include <itkImage.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkLabelStatisticsImageFilter.h>\n#include <itkImageRegionIterator.h>\n#include <itkImageRegionConstIterator.h>\n#include <itkMaskImageFilter.h>\n#include <itkImageDuplicator.h>\n\nint main(int argc,char **argv)\n{\n    std::string labelTableFile, labelImageFile, inImageFile, outTableFile, outImageFile;\n    bool\twriteOutTableFile(false), writeOutImageFile(false), startFromInImage(false);\n\n    boost::program_options::options_description optionsDescription(\"Write a file with total and average Jacobians from a given label table, label image and Jacobian image.\");\n    optionsDescription.add_options()\n\t(\"help,h\", \"display help message\")\n\t(\"labelTable,t\", boost::program_options::value< std::string >(&labelTableFile), \"labels in a single column for which sum and average of inImage is to be computed.\")\n\t(\"inImage,i\", boost::program_options::value< std::string >(&inImageFile), \"Input intensity image whose mean regional values are to be computed.\")\n\t(\"labelImage,l\", boost::program_options::value< std::string >(&labelImageFile), \"input label image file from which the regions matching the labels in the table will be extracted\")\n\t(\"outTable,o\",boost::program_options::value< std::string >(&outTableFile), \"[Optional] If given create this table file which contains table with labels, mean values and number of voxels for the given label\")\n\t(\"outImage,u\",boost::program_options::value< std::string >(&outImageFile), \"[Optional]. If given creates this image which has uniformized mean intensity in each ROIs corresponding to the given labels and labelImage. The mean intensity is computed from the given input intensity image. \")\n\t(\"startFromInImage,s\",boost::program_options::bool_switch(&startFromInImage)->default_value(false), \"If given the ouImage copies the intensity values of inImage for all ROIs not covered by the input labels; otherwise all regions not covered by labels will have zero value.\")\n\t;\n\n    boost::program_options::variables_map options;\n    boost::program_options::store(boost::program_options::parse_command_line(argc,argv,optionsDescription),options);\n    boost::program_options::notify(options);\n\n//If help is asked!\n    if(options.count(\"help\")) {\n\tstd::cout<<optionsDescription<<std::endl;\n\treturn EXIT_SUCCESS;\n    }\n//Confirm all the options required are given.\n    if(!options.count(\"labelTable\") || !options.count(\"inImage\") || !options.count(\"labelImage\")\n\t)\n    {\n\tstd::cerr<<\"invalid options! run with --help or -h to see the proper options.\"<<std::endl;\n\treturn EXIT_FAILURE;\n    }\n    if(options.count(\"outTable\"))\n\twriteOutTableFile = true;\n    if(options.count(\"outImage\"))\n\twriteOutImageFile = true;\n    if(!(writeOutTableFile || writeOutImageFile))\n    {\n\tstd::cerr<<\"neither of outTable and outImage given. Nothing to write => I do nothing. Provide at lease one of these filenames to write.\";\n\treturn EXIT_FAILURE;\n\n    }\n    typedef itk::Image<int, 3> LabelImageType;\n    typedef itk::Image<float, 3> ImageType;\n    // Container to put labels.\n    typedef std::vector<LabelImageType::PixelType> LabelsVecType;\n    typedef LabelsVecType::iterator LabelsVecItType;\n\n// Open label table file for reading\n    std::ifstream labelTable(labelTableFile.c_str(),std::ios::in);\n    if (!labelTable.is_open()) {\n\tstd::cerr<<\"could not open file: \"<<labelTableFile<<std::endl;\n\treturn EXIT_FAILURE;\n    }\n    //Read all the numbers and put them into a vector.\n    std::istream_iterator<double> start(labelTable), end;\n    //std::vector<LabelImageType::PixelType> inLabels(start, end);\n    LabelsVecType inLabels(start, end);\n    std::cout << \"Read \" << inLabels.size() << \" labels\" << std::endl;\n    labelTable.close();\n\n    // for (LabelsVecItType it = inLabels.begin(); it != inLabels.end(); ++it) {\n    // \tstd::cout<<*it<<std::endl;\n    // }\n\n// Read input label image\n    LabelImageType::Pointer labelImage;\n    {\n\ttypedef itk::ImageFileReader< LabelImageType > LabelImageReaderType;\n\tLabelImageReaderType::Pointer labelImageReader = LabelImageReaderType::New();\n\tlabelImageReader->SetFileName(labelImageFile);\n\tlabelImageReader->Update();\n\tlabelImage = labelImageReader->GetOutput();\n    }\n\n// Read input intensity image.\n    ImageType::Pointer inImage;\n    {\n\ttypedef itk::ImageFileReader< ImageType > InImageReaderType;\n\tInImageReaderType::Pointer inImageReader = InImageReaderType::New();\n\tinImageReader->SetFileName(inImageFile);\n\tinImageReader->Update();\n\tinImage = inImageReader->GetOutput();\n    }\n\n    //Label Statistics Filter to compute mean of each regions:\n    typedef itk::LabelStatisticsImageFilter< ImageType, LabelImageType > LabelStatsFilterType;\n    LabelStatsFilterType::Pointer labelStats = LabelStatsFilterType::New();\n\n    labelStats->SetLabelInput( labelImage);\n    labelStats->SetInput(inImage);\n    labelStats->Update();\n\n    std::cout << \"Number of labels in the input label image: \" << labelStats->GetNumberOfLabels() << std::endl;\n    typedef LabelStatsFilterType::ValidLabelValuesContainerType ValidLabelValuesType;\n    typedef LabelStatsFilterType::LabelPixelType                LabelPixelType;\n    typedef ImageType::PixelType\t\t\t\tOutPixelType;\n    // for(ValidLabelValuesType::const_iterator vIt=labelStats->GetValidLabelValues().begin();\n    // \tvIt != labelStats->GetValidLabelValues().end();\n    // \t++vIt)\n\n\n    // For writing into a table\n    if(writeOutTableFile)\n    {\n\tstd::ofstream outputFile(outTableFile.c_str());\n\toutputFile<<\"LabelId\\tMeanIntensity\\tNumberOfVoxels\\n\";\n\tfor (LabelsVecItType it = inLabels.begin(); it != inLabels.end(); ++it)\n\t{\n\t    if ( labelStats->HasLabel(*it) )\n\t    {\n\t\tLabelPixelType labelValue = *it;\n\t\tOutPixelType meanValue = labelStats->GetMean(labelValue);\n\t\tunsigned int labelVoxelCount = labelStats->GetCount(labelValue);\n\t\t// std::cout <<\"For Label Id: \"<<labelValue<<std::endl;\n\t\t// std::cout << \"mean: \" << meanValue << std::endl;\n\t\t// std::cout << \"count: \" << labelVoxelCount << std::endl;\n\t\t// std::cout << std::endl;\n\t\toutputFile<<labelValue<<\"\\t\"<<meanValue<<\"\\t\"<<labelVoxelCount<<'\\n';\n\t    }\n\t    else\n\t    {\n\t\tstd::cout<<\" Label Id \"<<*it<<\" not present in the label image\"<<std::endl;\n\t    }\n\t}\n\toutputFile.close();\n    }\n\n    if(writeOutImageFile)\n    { // For writing an image\n        // Output image, initialize with zero.\n\tImageType::Pointer outImage;\n\tif(startFromInImage)\n\t{\n\t    typedef itk::ImageDuplicator< ImageType > DuplicatorType;\n\t    DuplicatorType::Pointer duplicator = DuplicatorType::New();\n\t    duplicator->SetInputImage(inImage);\n\t    duplicator->Update();\n\t    outImage = duplicator->GetModifiableOutput();\n\t}\n\telse\n\t{\n\t    outImage = ImageType::New();\n\t    outImage->SetRegions(inImage->GetLargestPossibleRegion());\n\t    outImage->CopyInformation(inImage);\n\t    outImage->Allocate();\n\t    outImage->FillBuffer(0.);\n\t}\n\n\ttypedef itk::MaskImageFilter<ImageType, LabelImageType, ImageType> MaskImageFilterType;\n\tMaskImageFilterType::Pointer maskImageFilter = MaskImageFilterType::New();\n\tmaskImageFilter->SetMaskImage(labelImage);\n\tfor (LabelsVecItType it = inLabels.begin(); it != inLabels.end(); ++it)\n\t{\n\t    if ( labelStats->HasLabel(*it) )\n\t    {\n\t\tLabelPixelType labelValue = *it;\n\t\tOutPixelType meanValue = labelStats->GetMean(labelValue);\n\t\tmaskImageFilter->SetInput(outImage);\n\t\t//if (pixel_from_mask_image != masking_value)     pixel_output_image = pixel_input_image\n\t\t//else pixel_output_image = outside_value\n\t\tmaskImageFilter->SetMaskingValue(labelValue);\n\t\tmaskImageFilter->SetOutsideValue(meanValue);\n\t\tmaskImageFilter->Update();\n\t\toutImage = maskImageFilter->GetOutput();\n\t\toutImage->DisconnectPipeline();\n\t    }\n\t    else\n\t    {\n\t\tstd::cout<<\" Label Id \"<<*it<<\" not present in the label image\"<<std::endl;\n\t    }\n\t}\n\t// Write the out output.\n\ttypedef itk::ImageFileWriter< ImageType > ValueImageWriterType;\n\tValueImageWriterType::Pointer outImageWriter = ValueImageWriterType::New();\n\toutImageWriter->SetFileName(outImageFile);\n\toutImageWriter->SetInput(outImage);\n\toutImageWriter->Update();\n    }\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "630b1bac0fe36020493fc2f522d6d085be85e77c", "size": 8177, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/uniformizeWithRegionalMeans.cxx", "max_stars_repo_name": "richardbeare/simul-atrophy", "max_stars_repo_head_hexsha": "8d8db3206bd32fe103e4328ff14c38eed01756d6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T14:58:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T06:08:24.000Z", "max_issues_repo_path": "src/uniformizeWithRegionalMeans.cxx", "max_issues_repo_name": "richardbeare/simul-atrophy", "max_issues_repo_head_hexsha": "8d8db3206bd32fe103e4328ff14c38eed01756d6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-08-26T14:37:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-13T09:14:29.000Z", "max_forks_repo_path": "src/uniformizeWithRegionalMeans.cxx", "max_forks_repo_name": "richardbeare/simul-atrophy", "max_forks_repo_head_hexsha": "8d8db3206bd32fe103e4328ff14c38eed01756d6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-02-14T08:15:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-15T03:43:25.000Z", "avg_line_length": 41.0904522613, "max_line_length": 288, "alphanum_fraction": 0.7238596062, "num_tokens": 2024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.028436034897415936, "lm_q1q2_score": 0.013552035589045}}
{"text": "/*\n *            Copyright 2009-2020 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Third party includes\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/aomatrix.h\"\n#include \"votca/xtp/bse.h\"\n#include \"votca/xtp/bse_operator.h\"\n#include \"votca/xtp/bsecoupling.h\"\n\nnamespace votca {\nnamespace xtp {\nusing namespace std;\nusing boost::format;\nusing namespace tools;\n\nvoid BSECoupling::Initialize(Property& options) {\n  string spintype = options.get(\"spin\").as<std::string>();\n  if (spintype == \"all\") {\n    doSinglets_ = true;\n    doTriplets_ = true;\n  } else if (spintype == \"triplet\") {\n    doTriplets_ = true;\n    doSinglets_ = false;\n  } else if (spintype == \"singlet\") {\n    doSinglets_ = true;\n    doTriplets_ = false;\n  } else {\n    throw std::runtime_error(\n        (boost::format(\n             \"Choice % for type not known. Available singlet,triplet,all\") %\n         spintype)\n            .str());\n  }\n  output_perturbation_ = options.get(\"use_perturbation\").as<bool>();\n\n  levA_ = options.get(\"moleculeA.states\").as<Index>();\n  levB_ = options.get(\"moleculeB.states\").as<Index>();\n  occA_ = options.get(\"moleculeA.occLevels\").as<Index>();\n  occB_ = options.get(\"moleculeB.occLevels\").as<Index>();\n  unoccA_ = options.get(\"moleculeA.unoccLevels\").as<Index>();\n  unoccB_ = options.get(\"moleculeB.unoccLevels\").as<Index>();\n}\n\nvoid BSECoupling::WriteToProperty(Property& summary, const QMState& stateA,\n                                  const QMState& stateB) const {\n  Property& coupling_summary = summary.add(\"coupling\", \"\");\n  double JAB_pert = 0;\n  double JAB_diag = 0;\n  if (stateA.Type() == QMStateType::Singlet) {\n    JAB_pert =\n        getSingletCouplingElement(stateA.StateIdx(), stateB.StateIdx(), 0);\n    JAB_diag =\n        getSingletCouplingElement(stateA.StateIdx(), stateB.StateIdx(), 1);\n  } else if (stateA.Type() == QMStateType::Triplet) {\n    JAB_pert =\n        getTripletCouplingElement(stateA.StateIdx(), stateB.StateIdx(), 0);\n    JAB_diag =\n        getTripletCouplingElement(stateA.StateIdx(), stateB.StateIdx(), 1);\n  }\n  coupling_summary.setAttribute(\"stateA\", stateA.ToString());\n  coupling_summary.setAttribute(\"stateB\", stateB.ToString());\n  coupling_summary.setAttribute(\"j_pert\", (format(\"%1$1.6e\") % JAB_pert).str());\n  coupling_summary.setAttribute(\"j_diag\", (format(\"%1$1.6e\") % JAB_diag).str());\n}\n\nvoid BSECoupling::Addoutput(Property& type_summary, const Orbitals&,\n                            const Orbitals&) const {\n  tools::Property& bsecoupling = type_summary.add(Identify(), \"\");\n  string algorithm = \"j_diag\";\n  if (output_perturbation_) {\n    algorithm = \"j_pert\";\n  }\n  if (doSinglets_) {\n    QMStateType singlet = QMStateType(QMStateType::Singlet);\n    Property& singlet_summary = bsecoupling.add(singlet.ToLongString(), \"\");\n    singlet_summary.setAttribute(\"algorithm\", algorithm);\n    for (Index stateA = 0; stateA < levA_; ++stateA) {\n      QMState qmstateA = QMState(singlet, stateA, false);\n      for (Index stateB = 0; stateB < levB_; ++stateB) {\n        QMState qmstateB = QMState(singlet, stateB, false);\n        WriteToProperty(singlet_summary, qmstateA, qmstateB);\n      }\n    }\n  }\n\n  if (doTriplets_) {\n    QMStateType triplet = QMStateType(QMStateType::Triplet);\n    Property& triplet_summary = bsecoupling.add(triplet.ToLongString(), \"\");\n    triplet_summary.setAttribute(\"algorithm\", algorithm);\n    for (Index stateA = 0; stateA < levA_; ++stateA) {\n      QMState qmstateA = QMState(triplet, stateA, false);\n      for (Index stateB = 0; stateB < levB_; ++stateB) {\n        QMState qmstateB = QMState(triplet, stateB, false);\n        WriteToProperty(triplet_summary, qmstateA, qmstateB);\n      }\n    }\n  }\n}\n\ndouble BSECoupling::getSingletCouplingElement(Index levelA, Index levelB,\n                                              Index methodindex) const {\n  return JAB_singlet[methodindex](levelA, levelB + levA_) *\n         votca::tools::conv::hrt2ev;\n}\n\ndouble BSECoupling::getTripletCouplingElement(Index levelA, Index levelB,\n                                              Index methodindex) const {\n  return JAB_triplet[methodindex](levelA, levelB + levA_) *\n         votca::tools::conv::hrt2ev;\n}\n\nEigen::MatrixXd BSECoupling::SetupCTStates(Index bseA_vtotal, Index bseB_vtotal,\n                                           Index bseAB_vtotal,\n                                           Index bseAB_ctotal,\n                                           const Eigen::MatrixXd& A_AB,\n                                           const Eigen::MatrixXd& B_AB) const {\n\n  Index noAB = occA_ * unoccB_;\n  Index noBA = unoccA_ * occB_;\n  Index bseAB_size = bseAB_vtotal * bseAB_ctotal;\n  Eigen::MatrixXd CTstates = Eigen::MatrixXd::Zero(bseAB_size, noAB + noBA);\n\n  auto A_occ = A_AB.middleCols(bseA_vtotal - occA_, occA_);\n  auto A_unocc = A_AB.middleCols(bseA_vtotal, unoccA_);\n  auto B_occ = B_AB.middleCols(bseB_vtotal - occB_, occB_);\n  auto B_unocc = B_AB.middleCols(bseB_vtotal, unoccB_);\n\n  const Eigen::MatrixXd A_occ_occ = A_occ.topRows(bseAB_vtotal);\n  const Eigen::MatrixXd B_unocc_unocc = B_unocc.bottomRows(bseAB_ctotal);\n\n  // notation AB is CT states with A+B-, BA is the counterpart\n  // Setting up CT-states:\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   Setting up CT-states\" << flush;\n\n  // Number of A+B- states\n#pragma omp parallel for\n  for (Index a_occ = 0; a_occ < occA_; a_occ++) {\n    for (Index b_unocc = 0; b_unocc < unoccB_; b_unocc++) {\n      Index index = a_occ * unoccB_ + b_unocc;\n      Eigen::MatrixXd Coeff =\n          B_unocc_unocc.col(b_unocc) * A_occ_occ.col(a_occ).transpose();\n      CTstates.col(index) =\n          Eigen::Map<Eigen::VectorXd>(Coeff.data(), bseAB_size);\n    }\n  }\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"  \" << noBA << \" CT states A+B- created\" << flush;\n\n  const Eigen::MatrixXd A_unocc_unocc = A_unocc.bottomRows(bseAB_ctotal);\n  const Eigen::MatrixXd B_occ_occ = B_occ.topRows(bseAB_vtotal);\n\n#pragma omp parallel for\n  for (Index b_occ = 0; b_occ < occB_; b_occ++) {\n    for (Index a_unocc = 0; a_unocc < unoccA_; a_unocc++) {\n      Index index = b_occ * unoccA_ + a_unocc + noAB;\n      Eigen::MatrixXd Coeff =\n          A_unocc_unocc.col(a_unocc) * B_occ_occ.col(b_occ).transpose();\n      CTstates.col(index) =\n          Eigen::Map<Eigen::VectorXd>(Coeff.data(), bseAB_size);\n    }\n  }\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"  \" << noBA << \" CT states A-B+ created\" << flush;\n  return CTstates;\n}\n\nEigen::MatrixXd BSECoupling::ProjectFrenkelExcitons(\n    const Eigen::MatrixXd& BSE_Coeffs, const Eigen::MatrixXd& X_AB,\n    Index bseX_vtotal, Index bseX_ctotal, Index bseAB_vtotal,\n    Index bseAB_ctotal) const {\n  Index bseAB_size = bseAB_vtotal * bseAB_ctotal;\n  auto X_occ = X_AB.leftCols(bseX_vtotal);\n  auto X_unocc = X_AB.rightCols(bseX_ctotal);\n  const Eigen::MatrixXd X_occ_occ = X_occ.topRows(bseAB_vtotal);\n  const Eigen::MatrixXd X_unocc_unocc = X_unocc.bottomRows(bseAB_ctotal);\n  Eigen::MatrixXd result = Eigen::MatrixXd::Zero(bseAB_size, BSE_Coeffs.cols());\n  // no pragma here because often we will only have one Coeff\n  for (Index i = 0; i < BSE_Coeffs.cols(); i++) {\n    Eigen::VectorXd coeff = BSE_Coeffs.col(i);\n    Eigen::Map<Eigen::MatrixXd> coeffmatrix =\n        Eigen::Map<Eigen::MatrixXd>(coeff.data(), bseX_ctotal, bseX_vtotal);\n    Eigen::MatrixXd proj = X_unocc_unocc * coeffmatrix * X_occ_occ.transpose();\n    result.col(i) = Eigen::Map<Eigen::VectorXd>(proj.data(), proj.size());\n  }\n  return result;\n}\n\nint GetSign(double value) {\n  if (value < 0) {\n    return -1;\n  } else if (value > 0) {\n    return 1;\n  }\n  return 0;\n}\n\nvoid BSECoupling::CalculateCouplings(const Orbitals& orbitalsA,\n                                     const Orbitals& orbitalsB,\n                                     const Orbitals& orbitalsAB) {\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"  Calculating exciton couplings\" << flush;\n  // set the parallelization\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Using \"\n                              << OPENMP::getMaxThreads() << \" threads\" << flush;\n\n  CheckAtomCoordinates(orbitalsA, orbitalsB, orbitalsAB);\n\n  // constructing the direct product orbA x orbB\n  Index basisB = orbitalsB.getBasisSetSize();\n  Index basisA = orbitalsA.getBasisSetSize();\n  if ((basisA == 0) || (basisB == 0)) {\n    throw std::runtime_error(\"Basis set size is not stored in monomers\");\n  }\n  // get exciton information of molecule A\n  Index bseA_cmax = orbitalsA.getBSEcmax();\n  Index bseA_cmin = orbitalsA.getBSEcmin();\n  Index bseA_vmax = orbitalsA.getBSEvmax();\n  Index bseA_vmin = orbitalsA.getBSEvmin();\n  Index bseA_vtotal = bseA_vmax - bseA_vmin + 1;\n  Index bseA_ctotal = bseA_cmax - bseA_cmin + 1;\n  Index bseA_total = bseA_vtotal + bseA_ctotal;\n  Index bseA_size = bseA_vtotal * bseA_ctotal;\n  Index bseA_singlet_exc = orbitalsA.BSESinglets().eigenvectors().cols();\n  Index bseA_triplet_exc = orbitalsA.BSETriplets().eigenvectors().cols();\n\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   molecule A has \" << bseA_singlet_exc\n      << \" singlet excitons with dimension \" << bseA_size << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   molecule A has \" << bseA_triplet_exc\n      << \" triplet excitons with dimension \" << bseA_size << flush;\n\n  // get exciton information of molecule B\n  Index bseB_cmax = orbitalsB.getBSEcmax();\n  Index bseB_cmin = orbitalsB.getBSEcmin();\n  Index bseB_vmax = orbitalsB.getBSEvmax();\n  Index bseB_vmin = orbitalsB.getBSEvmin();\n  Index bseB_vtotal = bseB_vmax - bseB_vmin + 1;\n  Index bseB_ctotal = bseB_cmax - bseB_cmin + 1;\n  Index bseB_total = bseB_vtotal + bseB_ctotal;\n  Index bseB_size = bseB_vtotal * bseB_ctotal;\n  Index bseB_singlet_exc = orbitalsB.BSESinglets().eigenvectors().cols();\n  Index bseB_triplet_exc = orbitalsB.BSETriplets().eigenvectors().cols();\n\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   molecule B has \" << bseB_singlet_exc\n      << \" singlet excitons with dimension \" << bseB_size << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   molecule B has \" << bseB_triplet_exc\n      << \" triplet excitons with dimension \" << bseB_size << flush;\n\n  if (doSinglets_) {\n    if (levA_ > bseA_singlet_exc) {\n      XTP_LOG(Log::error, *pLog_) << TimeStamp()\n                                  << \"  Number of excitons you want is greater \"\n                                     \"than stored for molecule \"\n                                     \"A. Setting to max number available\"\n                                  << flush;\n      levA_ = bseA_singlet_exc;\n    }\n    if (levB_ > bseB_singlet_exc) {\n      XTP_LOG(Log::error, *pLog_) << TimeStamp()\n                                  << \"  Number of excitons you want is greater \"\n                                     \"than stored for molecule \"\n                                     \"B. Setting to max number available\"\n                                  << flush;\n      levB_ = bseB_singlet_exc;\n    }\n  }\n  if (doTriplets_) {\n    if (levA_ > bseA_triplet_exc) {\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp()\n          << \"  Number of Frenkel states you want is greater than stored for \"\n             \"molecule A. Setting to max number available\"\n          << flush;\n      levA_ = bseA_triplet_exc;\n    }\n    if (levB_ > bseB_triplet_exc) {\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp()\n          << \"  Number of Frenkel states you want is greater than stored for \"\n             \"molecule B. Setting to max number available\"\n          << flush;\n      levB_ = bseB_triplet_exc;\n    }\n  }\n  if (unoccA_ > bseA_ctotal || unoccA_ < 0) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp()\n        << \"  Number of unoccupied orbitals in molecule A for CT creation \"\n           \"exceeds number of KS-orbitals in BSE\"\n        << flush;\n    unoccA_ = bseA_ctotal;\n  }\n  if (unoccB_ > bseB_ctotal || unoccB_ < 0) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp()\n        << \"  Number of unoccupied orbitals in molecule B for CT creation \"\n           \"exceeds number of KS-orbitals in BSE\"\n        << flush;\n    unoccB_ = bseB_ctotal;\n  }\n\n  if (occA_ > bseA_vtotal || occA_ < 0) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp()\n        << \"  Number of occupied orbitals in molecule A for CT creation \"\n           \"exceeds number of KS-orbitals in BSE\"\n        << flush;\n    occA_ = bseA_vtotal;\n  }\n  if (occB_ > bseB_vtotal || occB_ < 0) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp()\n        << \"  Number of occupied orbitals in molecule B for CT creation \"\n           \"exceeds number of KS-orbitals in BSE\"\n        << flush;\n    occB_ = bseB_vtotal;\n  }\n\n  // get exciton information of pair AB\n  Index bseAB_cmax = orbitalsAB.getBSEcmax();\n  Index bseAB_cmin = orbitalsAB.getBSEcmin();\n  Index bseAB_vmax = orbitalsAB.getBSEvmax();\n  Index bseAB_vmin = orbitalsAB.getBSEvmin();\n  Index bseAB_vtotal = bseAB_vmax - bseAB_vmin + 1;\n  Index bseAB_ctotal = bseAB_cmax - bseAB_cmin + 1;\n  Index bseAB_total = bseAB_vtotal + bseAB_ctotal;\n  Index bseAB_size = bseAB_vtotal * bseAB_ctotal;\n\n  // DFT levels of monomers can be reduced to those used in BSE\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   levels used for BSE of molA: \" << bseA_vmin\n      << \" to \" << bseA_cmax << \" total: \" << bseA_total << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   levels used for BSE of molB: \" << bseB_vmin\n      << \" to \" << bseB_cmax << \" total: \" << bseB_total << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"   levels used for BSE of dimer AB: \" << bseAB_vmin\n      << \" to \" << bseAB_cmax << \" total: \" << bseAB_total << flush;\n\n  Eigen::MatrixXd MOsA =\n      orbitalsA.MOs().eigenvectors().middleCols(bseA_vmin, bseA_total);\n  Eigen::MatrixXd MOsB =\n      orbitalsB.MOs().eigenvectors().middleCols(bseB_vmin, bseB_total);\n  Eigen::MatrixXd MOsAB =\n      orbitalsAB.MOs().eigenvectors().middleCols(bseAB_vmin, bseAB_total);\n\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Calculating overlap matrix for basisset: \"\n      << orbitalsAB.getDFTbasisName() << flush;\n\n  Eigen::MatrixXd overlap = CalculateOverlapMatrix(orbitalsAB) * MOsAB;\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Projecting monomers onto dimer orbitals\" << flush;\n\n  Eigen::MatrixXd A_AB = overlap.topRows(basisA).transpose() * MOsA;\n  Eigen::MatrixXd B_AB = overlap.bottomRows(basisB).transpose() * MOsB;\n  Eigen::VectorXd mag_A = A_AB.colwise().squaredNorm();\n  if (mag_A.any() < 0.95) {\n    XTP_LOG(Log::error, *pLog_)\n        << \"\\nWarning: \"\n        << \"Projection of orbitals of monomer A on dimer is insufficient,mag=\"\n        << mag_A.minCoeff() << flush;\n  }\n  Eigen::VectorXd mag_B = B_AB.colwise().squaredNorm();\n  if (mag_B.any() < 0.95) {\n    XTP_LOG(Log::error, *pLog_)\n        << \"\\nWarning: \"\n        << \"Projection of orbitals of monomer B on dimer is insufficient,mag=\"\n        << mag_B.minCoeff() << flush;\n  }\n\n  AOBasis dftbasis = orbitalsAB.getDftBasis();\n  AOBasis auxbasis = orbitalsAB.getAuxBasis();\n  TCMatrix_gwbse Mmn;\n  // rpamin here, because RPA needs till rpamin\n  Mmn.Initialize(auxbasis.AOBasisSize(), orbitalsAB.getRPAmin(),\n                 orbitalsAB.getGWAmax(), orbitalsAB.getRPAmin(),\n                 orbitalsAB.getRPAmax());\n  Mmn.Fill(auxbasis, dftbasis, orbitalsAB.MOs().eigenvectors());\n\n  const Eigen::MatrixXd& qpcoeff = orbitalsAB.QPdiag().eigenvectors();\n  Eigen::MatrixXd Hqp = qpcoeff *\n                        orbitalsAB.QPdiag().eigenvalues().asDiagonal() *\n                        qpcoeff.transpose();\n\n  BSE::options opt;\n  opt.cmax = orbitalsAB.getBSEcmax();\n  opt.homo = orbitalsAB.getHomo();\n  opt.qpmin = orbitalsAB.getGWAmin();\n  opt.qpmax = orbitalsAB.getGWAmax();\n  opt.rpamax = orbitalsAB.getRPAmax();\n  opt.rpamin = orbitalsAB.getRPAmin();\n  opt.useTDA = true;\n  opt.vmin = orbitalsAB.getBSEvmin();\n  opt.use_Hqp_offdiag = orbitalsAB.GetFlagUseHqpOffdiag();\n  BSE bse(*pLog_, Mmn);\n  bse.configure(opt, orbitalsAB.RPAInputEnergies(), Hqp);\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Setup BSE operator\" << flush;\n\n  // now the different spin types\n  if (doSinglets_) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \"   Evaluating singlets\" << flush;\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \"   Setup Hamiltonian\" << flush;\n    Eigen::MatrixXd FE_AB = Eigen::MatrixXd::Zero(bseAB_size, levA_ + levB_);\n    const Eigen::MatrixXd bseA =\n        orbitalsA.BSESinglets().eigenvectors().leftCols(levA_);\n    FE_AB.leftCols(levA_) = ProjectFrenkelExcitons(\n        bseA, A_AB, bseA_vtotal, bseA_ctotal, bseAB_vtotal, bseAB_ctotal);\n    const Eigen::MatrixXd bseB =\n        orbitalsB.BSESinglets().eigenvectors().leftCols(levB_);\n    FE_AB.rightCols(levB_) = ProjectFrenkelExcitons(\n        bseB, B_AB, bseB_vtotal, bseB_ctotal, bseAB_vtotal, bseAB_ctotal);\n    Eigen::MatrixXd CTStates = SetupCTStates(\n        bseA_vtotal, bseB_vtotal, bseAB_vtotal, bseAB_ctotal, A_AB, B_AB);\n    JAB_singlet =\n        ProjectExcitons(FE_AB, CTStates, bse.getSingletOperator_TDA());\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \"   calculated singlet couplings \" << flush;\n  }\n  if (doTriplets_) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \"   Evaluating triplets\" << flush;\n    Eigen::MatrixXd FE_AB = Eigen::MatrixXd::Zero(bseAB_size, levA_ + levB_);\n    const Eigen::MatrixXd bseA =\n        orbitalsA.BSETriplets().eigenvectors().leftCols(levA_);\n    FE_AB.leftCols(levA_) = ProjectFrenkelExcitons(\n        bseA, A_AB, bseA_vtotal, bseA_ctotal, bseAB_vtotal, bseAB_ctotal);\n    const Eigen::MatrixXd bseB =\n        orbitalsB.BSETriplets().eigenvectors().leftCols(levB_);\n    FE_AB.rightCols(levB_) = ProjectFrenkelExcitons(\n        bseB, B_AB, bseB_vtotal, bseB_ctotal, bseAB_vtotal, bseAB_ctotal);\n    Eigen::MatrixXd CTStates = SetupCTStates(\n        bseA_vtotal, bseB_vtotal, bseAB_vtotal, bseAB_ctotal, A_AB, B_AB);\n    JAB_triplet =\n        ProjectExcitons(FE_AB, CTStates, bse.getTripletOperator_TDA());\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \"   calculated triplet couplings \" << flush;\n  }\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \"  Done with exciton couplings\" << flush;\n}\n\nEigen::MatrixXd BSECoupling::OrthogonalizeCTs(Eigen::MatrixXd& FE_AB,\n                                              Eigen::MatrixXd& CTStates) const {\n  Index ct = CTStates.cols();\n\n  if (ct > 0) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Orthogonalizing CT-states with respect to FE-states\"\n        << flush;\n    Eigen::MatrixXd correction = FE_AB * (FE_AB.transpose() * CTStates);\n    CTStates -= correction;\n\n    // normalize\n    Eigen::VectorXd norm = CTStates.colwise().norm();\n    for (Index i = 0; i < CTStates.cols(); i++) {\n      CTStates.col(i) /= norm(i);\n    }\n    Index minstateindex = 0;\n    double minnorm = norm.minCoeff(&minstateindex);\n    if (minnorm < 0.95) {\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" WARNING: CT-state \" << minstateindex\n          << \" norm is only \" << minnorm << flush;\n    }\n  }\n  Index bse_exc = levA_ + levB_;\n\n  Index bseAB_size = CTStates.rows();\n  Eigen::MatrixXd projection(bseAB_size, bse_exc + ct);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" merging projections into one vector  \" << flush;\n  projection.leftCols(bse_exc) = FE_AB;\n  FE_AB.resize(0, 0);\n  if (ct > 0) {\n    projection.rightCols(ct) = CTStates;\n  }\n  CTStates.resize(0, 0);\n  return projection;\n}\n\ntemplate <class BSE_OPERATOR>\nEigen::MatrixXd BSECoupling::CalcJ_dimer(BSE_OPERATOR& H,\n                                         Eigen::MatrixXd& projection) const {\n\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \"   Setting up coupling matrix size \"\n      << projection.cols() << flush;\n  // matrix  J_\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  // this only works for hermitian/symmetric H so only in TDA\n\n  Eigen::MatrixXd J_dimer = projection.transpose() * (H * projection).eval();\n\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \"   Setting up overlap matrix size \"\n      << projection.cols() << flush;\n  Eigen::MatrixXd S_dimer = projection.transpose() * projection;\n\n  projection.resize(0, 0);\n  if (projection.cols()) {\n    XTP_LOG(Log::debug, *pLog_)\n        << \"---------------------------------------\" << flush;\n    XTP_LOG(Log::debug, *pLog_) << \" J_dimer_[Ryd]\" << flush;\n\n    XTP_LOG(Log::debug, *pLog_) << J_dimer << flush;\n    XTP_LOG(Log::debug, *pLog_) << \" S_dimer_\" << flush;\n\n    XTP_LOG(Log::debug, *pLog_) << S_dimer << flush;\n    XTP_LOG(Log::debug, *pLog_)\n        << \"---------------------------------------\" << flush;\n  }\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(S_dimer);\n  Eigen::MatrixXd Sm1 = es.operatorInverseSqrt();\n  Eigen::MatrixXd J_ortho = Sm1 * J_dimer * Sm1;\n\n  if (projection.cols()) {\n    XTP_LOG(Log::debug, *pLog_)\n        << \"---------------------------------------\" << flush;\n    XTP_LOG(Log::debug, *pLog_) << \" J_ortho_[Ryd]\" << flush;\n    XTP_LOG(Log::debug, *pLog_) << J_ortho << flush;\n    XTP_LOG(Log::debug, *pLog_) << \" S_-1/2\" << flush;\n    XTP_LOG(Log::debug, *pLog_) << Sm1 << flush;\n    XTP_LOG(Log::debug, *pLog_)\n        << \"---------------------------------------\" << flush;\n  }\n  XTP_LOG(Log::debug, *pLog_)\n      << TimeStamp() << \"   Smallest value of dimer overlapmatrix is \"\n      << es.eigenvalues()(0) << flush;\n  return J_ortho;\n}\n\ntemplate <class BSE_OPERATOR>\nstd::array<Eigen::MatrixXd, 2> BSECoupling::ProjectExcitons(\n    Eigen::MatrixXd& FE_AB, Eigen::MatrixXd& CTStates, BSE_OPERATOR H) const {\n\n  Eigen::MatrixXd projection = OrthogonalizeCTs(FE_AB, CTStates);\n  Eigen::MatrixXd J_ortho = CalcJ_dimer(H, projection);\n\n  std::array<Eigen::MatrixXd, 2> J;\n\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \"   Running Perturbation algorithm\" << flush;\n  J[0] = Perturbation(J_ortho);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \"    Running Projection algorithm\" << flush;\n  J[1] = Fulldiag(J_ortho);\n\n  XTP_LOG(Log::debug, *pLog_)\n      << \"---------------------------------------\" << flush;\n  XTP_LOG(Log::debug, *pLog_) << \"Jeff_pert[Hrt]\" << flush;\n  XTP_LOG(Log::debug, *pLog_) << J[0] << flush;\n  XTP_LOG(Log::debug, *pLog_) << \"Jeff_diag[Hrt]\" << flush;\n  XTP_LOG(Log::debug, *pLog_) << J[1] << flush;\n  XTP_LOG(Log::debug, *pLog_)\n      << \"---------------------------------------\" << flush;\n\n  return J;\n}\n\nEigen::MatrixXd BSECoupling::Perturbation(\n    const Eigen::MatrixXd& J_dimer) const {\n  Index bse_exc = levA_ + levB_;\n  Index ct = J_dimer.rows() - bse_exc;\n  Eigen::MatrixXd J_result = J_dimer;\n  if (ct > 0) {\n    Eigen::MatrixXd transformation =\n        Eigen::MatrixXd::Identity(J_dimer.rows(), J_dimer.cols());\n    Eigen::MatrixXd Ct = J_dimer.bottomRightCorner(ct, ct);\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Ct);\n    transformation.bottomRightCorner(ct, ct) = es.eigenvectors();\n    Ct.resize(0, 0);\n\n    XTP_LOG(Log::debug, *pLog_) << \"FE state hamiltonian\" << flush;\n    XTP_LOG(Log::debug, *pLog_)\n        << J_dimer.topLeftCorner(bse_exc, bse_exc) << flush;\n    if (ct > 0) {\n      XTP_LOG(Log::debug, *pLog_) << \"eigenvalues of CT states\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << es.eigenvalues().transpose() << flush;\n    }\n\n    J_result = transformation.transpose() * J_dimer * transformation;\n    XTP_LOG(Log::debug, *pLog_)\n        << \"---------------------------------------\" << flush;\n    XTP_LOG(Log::debug, *pLog_) << \" J_ortho_[Hrt] CT-state diag\" << flush;\n    XTP_LOG(Log::debug, *pLog_) << J_result << flush;\n    XTP_LOG(Log::debug, *pLog_)\n        << \"---------------------------------------\" << flush;\n  }\n\n  Eigen::MatrixXd Jmatrix = Eigen::MatrixXd::Zero(bse_exc, bse_exc);\n  for (Index stateA = 0; stateA < levA_; stateA++) {\n    double Ea = J_result(stateA, stateA);\n    for (Index stateB = 0; stateB < levB_; stateB++) {\n      Index stateBd = stateB + levA_;\n      XTP_LOG(Log::info, *pLog_)\n          << TimeStamp() << \"   Calculating coupling between exciton A\"\n          << 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 (Index k = bse_exc; k < (bse_exc + ct); k++) {\n        double Eab = J_result(k, k);\n        if (std::abs(Eab - Ea) < 0.001) {\n          XTP_LOG(Log::error, *pLog_)\n              << TimeStamp() << \"Energydifference between state A \"\n              << stateA + 1 << \"and CT state \" << k + 1 << \" is \" << Eab - Ea\n              << \"[Hrt]\" << flush;\n        }\n        if (std::abs(Eab - Eb) < 0.001) {\n          XTP_LOG(Log::error, *pLog_)\n              << TimeStamp() << \"Energydifference between state B \"\n              << stateB + 1 << \"and CT state \" << k + 1 << \" is \" << Eab - Eb\n              << \"[Hrt]\" << flush;\n        }\n        J += 0.5 * J_result(k, stateA) * J_result(k, stateBd) *\n             (1 / (Ea - Eab) + 1 / (Eb - Eab));  // Have no clue why 0.5\n      }\n      Jmatrix(stateA, stateBd) = J;\n      Jmatrix(stateBd, stateA) = J;\n    }\n  }\n  return Jmatrix;\n}\n\nEigen::MatrixXd BSECoupling::Fulldiag(const Eigen::MatrixXd& J_dimer) const {\n  Index bse_exc = levA_ + levB_;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(J_dimer);\n  XTP_LOG(Log::debug, *pLog_)\n      << \"---------------------------------------\" << flush;\n  XTP_LOG(Log::debug, *pLog_) << \"Eigenvectors of J\" << flush;\n  XTP_LOG(Log::debug, *pLog_) << es.eigenvectors() << flush;\n  XTP_LOG(Log::debug, *pLog_) << \"J_eigenvalues[Hrt]\" << flush;\n  XTP_LOG(Log::debug, *pLog_) << es.eigenvalues() << flush;\n  XTP_LOG(Log::debug, *pLog_)\n      << \"---------------------------------------\" << flush;\n  Eigen::MatrixXd Jmat = Eigen::MatrixXd::Zero(bse_exc, bse_exc);\n  // Calculate projection on subspace for every pair of excitons separately\n  for (Index stateA = 0; stateA < levA_; stateA++) {\n    for (Index stateB = 0; stateB < levB_; stateB++) {\n\n      Index stateBd = stateB + levA_;\n      XTP_LOG(Log::info, *pLog_)\n          << TimeStamp() << \"   Calculating coupling between exciton A\"\n          << stateA + 1 << \" and exciton B\" << stateB + 1 << flush;\n\n      std::array<int, 2> indexes;\n      std::array<int, 2> signs;\n\n      // Find the eigenstate state, which in an L2 is closed to A or B\n      // respectively\n      es.eigenvectors().row(stateA).cwiseAbs().maxCoeff(&indexes[0]);\n      es.eigenvectors().row(stateBd).cwiseAbs().maxCoeff(&indexes[1]);\n      if (indexes[0] == indexes[1]) {\n        Eigen::RowVectorXd stateamplitudes =\n            es.eigenvectors().row(stateBd).cwiseAbs();\n        stateamplitudes[indexes[1]] = 0.0;\n        stateamplitudes.maxCoeff(&indexes[1]);\n      }\n\n      signs[0] = GetSign(es.eigenvectors()(stateA, indexes[0]));\n      signs[1] = GetSign(es.eigenvectors()(stateBd, indexes[1]));\n\n      XTP_LOG(Log::info, *pLog_)\n          << TimeStamp() << \"   Order is: [Initial state n->nth eigenvalue]\"\n          << flush;\n      XTP_LOG(Log::info, *pLog_) << \"    A\" << stateA + 1 << \":\" << stateA + 1\n                                 << \"->\" << indexes[0] + 1 << \" \";\n      XTP_LOG(Log::info, *pLog_) << \"    B\" << stateB + 1 << \":\" << stateBd + 1\n                                 << \"->\" << indexes[1] + 1 << \" \" << flush;\n\n      // setting up transformation matrix Tmat and diagonal matrix Emat for the\n      // eigenvalues;\n      Eigen::Matrix2d Emat = Eigen::Matrix2d::Zero();\n      Eigen::Matrix2d Tmat = Eigen::Matrix2d::Zero();\n      // find the eigenvectors which are most similar to the initial states\n      // row\n      for (Index i = 0; i < 2; i++) {\n        Index k = indexes[i];\n        double sign = signs[i];\n        Tmat(0, i) = sign * es.eigenvectors()(stateA, k);\n        Tmat(1, i) = sign * es.eigenvectors()(stateBd, k);\n        Emat(i, i) = es.eigenvalues()(k);\n      }\n      Tmat.colwise().normalize();\n\n      if (Tmat.determinant() < 0) {\n        XTP_LOG(Log::info, *pLog_)\n            << \" Reduced state matrix is not in a right handed basis, \"\n               \"multiplying second eigenvector by -1 \"\n            << flush;\n        Tmat.col(1) *= -1;\n      }\n\n      XTP_LOG(Log::debug, *pLog_)\n          << \"---------------------------------------\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << \" T_\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << Tmat << flush;\n\n      Eigen::Matrix2d S_small = Tmat * Tmat.transpose();\n\n      XTP_LOG(Log::debug, *pLog_) << \"S_small\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << S_small << flush;\n      // orthogonalize that matrix\n\n      Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> ss(S_small);\n      Eigen::Matrix2d sm1 = ss.operatorInverseSqrt();\n      Emat = sm1 * Emat * sm1;\n\n      XTP_LOG(Log::info, *pLog_)\n          << TimeStamp() << \"   Smallest value of dimer overlapmatrix is \"\n          << ss.eigenvalues()(0) << flush;\n\n      XTP_LOG(Log::debug, *pLog_) << \"S-1/2\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << sm1 << flush;\n      XTP_LOG(Log::debug, *pLog_) << \"E_ortho\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << Emat << flush;\n\n      Tmat = Tmat * sm1;\n\n      XTP_LOG(Log::debug, *pLog_) << \"T_ortho\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << Tmat << flush;\n      XTP_LOG(Log::debug, *pLog_)\n          << \"---------------------------------------\" << flush;\n\n      Eigen::Matrix2d J_small = Tmat * Emat * Tmat.transpose();\n      XTP_LOG(Log::debug, *pLog_) << \"T_ortho*E_ortho*T_ortho^T\" << flush;\n      XTP_LOG(Log::debug, *pLog_) << J_small << flush;\n\n      Jmat(stateA, stateBd) = J_small(0, 1);\n      Jmat(stateBd, stateA) = J_small(1, 0);\n    }\n  }\n\n  return Jmat;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "99b633791c49e4fe3e60716c83921681a10ba1dd", "size": 30534, "ext": "cc", "lang": "C++", "max_stars_repo_path": "xtp/src/libxtp/bsecoupling.cc", "max_stars_repo_name": "ipelupessy/votca", "max_stars_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xtp/src/libxtp/bsecoupling.cc", "max_issues_repo_name": "ipelupessy/votca", "max_issues_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xtp/src/libxtp/bsecoupling.cc", "max_forks_repo_name": "ipelupessy/votca", "max_forks_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5006468305, "max_line_length": 80, "alphanum_fraction": 0.6077814895, "num_tokens": 9219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.028436031603970197, "lm_q1q2_score": 0.013552034019455778}}
{"text": "// Copyright (c) Sergiu Dotenco 2010\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n/**\n * @brief Antithetic variates.\n * @file antithetic.hpp\n */\n\n#ifndef ANTITHETIC_HPP\n#define ANTITHETIC_HPP\n\n#include <boost/call_traits.hpp>\n#include <boost/operators.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n\n/**\n * @brief Antithetic variate used for variance reduction.\n *\n * @tparam UniformRandomNumberGenerator The engine that generates uniformly\n *         distributed random numbers.\n */\ntemplate<class UniformRandomNumberGenerator>\nclass Antithetic\n    : boost::equality_comparable\n      <\n          Antithetic<UniformRandomNumberGenerator>,\n          Antithetic<UniformRandomNumberGenerator>\n      >\n{\n    bool toggle_;\n    UniformRandomNumberGenerator generator_;\n\n    typedef typename\n        boost::remove_reference<UniformRandomNumberGenerator>::type Engine;\n\npublic:\n    typedef Engine::result_type result_type;\n\nprivate:\n    result_type value_;\n\npublic:\n    Antithetic(typename\n               boost::call_traits<UniformRandomNumberGenerator>::param_type u)\n        : toggle_(false)\n        , generator_(u)\n    {\n    }\n\n    result_type operator()()\n    {\n        if (!toggle_) {\n            value_ = generator_();\n            toggle_ = true;\n        }\n        else {\n            value_ = max() - value_ + min();\n            toggle_ = false;\n        }\n\n        return value_;\n    }\n\n    result_type min() const\n    {\n        return generator_.min();\n    }\n\n    result_type max() const\n    {\n        return generator_.max();\n    }\n\n    bool operator==(const Antithetic& other) const\n    {\n        return generator_ == generator_ && toggle_ == toggle_ &&\n            value_ == value_;\n    }\n};\n\n/**\n * Returns an antithetic variate for the specified uniform random number\n * generator @a u.\n *\n * @tparam UniformRandomNumberGenerator The engine that generates uniformly\n *         distributed random numbers.\n */\ntemplate<class UniformRandomNumberGenerator>\ninline Antithetic<UniformRandomNumberGenerator>\n    make_antithetic(UniformRandomNumberGenerator& u)\n{\n    return Antithetic<UniformRandomNumberGenerator>(u);\n}\n\n#endif // ANTITHETIC_HPP\n", "meta": {"hexsha": "6a9767566af6001c6db64df8d214757f9d60091a", "size": 2265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "antithetic.hpp", "max_stars_repo_name": "sergiud/random", "max_stars_repo_head_hexsha": "cdd9562656e8e3739c7ee6a468e25c2cf60b64ee", "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": "antithetic.hpp", "max_issues_repo_name": "sergiud/random", "max_issues_repo_head_hexsha": "cdd9562656e8e3739c7ee6a468e25c2cf60b64ee", "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": "antithetic.hpp", "max_forks_repo_name": "sergiud/random", "max_forks_repo_head_hexsha": "cdd9562656e8e3739c7ee6a468e25c2cf60b64ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.112244898, "max_line_length": 79, "alphanum_fraction": 0.6697571744, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824994383169, "lm_q2_score": 0.03963884023547297, "lm_q1q2_score": 0.01353993412246898}}
{"text": "/*\n *  statetree.cpp\n *\n *   Created on: 28-sep-2015\n *       Author: M. El-Kebir\n */\n\n#include \"statetree.h\"\n\n#include <lemon/connectivity.h>\n#include <stdio.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <iomanip>\n\nStateTree::StateTree()\n  : _k(0)\n  , _S()\n  , _root(lemon::INVALID)\n  , _label(_S)\n  , _stateToNode(_k, lemon::INVALID)\n  , _nodeToState(_S)\n  , _D(_S)\n  , _cnState(_S)\n{\n}\n\nStateTree::StateTree(int k)\n  : _k(k)\n  , _S()\n  , _root(lemon::INVALID)\n  , _label(_S)\n  , _stateToNode(_k, lemon::INVALID)\n  , _nodeToState(_S)\n  , _D(_S)\n  , _cnState(_S)\n{\n  IntVector pi(_k, -1);\n  for (int i = 1; i < _k; ++i)\n  {\n    pi[i] = i - 1;\n  }\n  \n  init(pi);\n}\n\nvoid StateTree::writeSummary(const ReadMatrix& R,\n                             const StateTreeVector& sol,\n                             std::ostream& out)\n{\n  const int n = R.getNrCharacters();\n  const int m = R.getNrSamples();\n  \n  out << \"SNV_index\\t\"\n      << \"SNV_label\\t\"\n      << \"sample_index\\t\"\n      << \"sample_label\\t\"\n      << \"ref\\t\"\n      << \"alt\\t\"\n      << \"VAF\\t\"\n      << \"sanger_n_mut\\t\"\n      << \"sanger_CCF\\t\"\n      << \"decifer_CCF\\t\"\n      << \"decifer_DCF\\t\"\n      << \"decifer_cluster_CCF\\t\"\n      << \"decifer_cluster_DCF\\t\"\n//      << \"decifer_cluster_index\\t\"\n//      << \"decifer_state_tree_index\\t\"\n      << \"nr_nonzero_z\"\n      << std::endl;\n\n  for (int i = 0; i < n; ++i)\n  {\n    for (int p = 0; p < m; ++p)\n    {\n      int ref = R.getRef(p, i);\n      int var = R.getVar(p, i);\n      double vaf = R.getVAF(p, i);\n      double purity = 1;\n      auto sanger = R.computeSangerCCF(ref, var,\n                                       purity, R.getCopyNumberStates(p, i));\n      int sanger_n_mut = sanger.first;\n      double sangerCCF = sanger.second;\n      \n      IntSet zSet;\n      IntPairSet mutTumorSet;\n      IntPairSet nonMutTumorSet;\n      const StateTree& T_i = sol[i];\n      for (int j = 0; j != T_i.numVertices(); ++j)\n      {\n        if (T_i.isPresent(j))\n        {\n          int x_j = T_i.x(j);\n          int y_j = T_i.y(j);\n          int z_j = T_i.z(j);\n          if (z_j > 0)\n          {\n            zSet.insert(z_j);\n          }\n          if (x_j != 1 || y_j != 1)\n          {\n            if (z_j > 0)\n            {\n              mutTumorSet.insert(IntPair(x_j, y_j));\n            }\n            else\n            {\n              nonMutTumorSet.insert(IntPair(x_j, y_j));\n            }\n          }\n        }\n      }\n      \n      double deciferCCF = T_i.maxLikelihoodCCF(p, vaf);\n      double deciferDCF = T_i.maxLikelihoodDCF(p, vaf);\n      double deciferClusterDCF = T_i.dcf(p);\n      double deciferClusterCCF = T_i.cf(p);\n      \n      out << i << \"\\t\" << R.indexToCharacter(i) << \"\\t\"\n          << p << \"\\t\" << R.indexToSample(p) << \"\\t\"\n          << ref << \"\\t\" << var << \"\\t\"\n          << R.getVAF(p, i) << \"\\t\"\n          << sanger_n_mut << \"\\t\" << sangerCCF << \"\\t\"\n          << deciferCCF << \"\\t\" << deciferDCF << \"\\t\"\n          << deciferClusterCCF << \"\\t\" << deciferClusterDCF << \"\\t\"\n          << zSet.size()\n          << std::endl;\n    }\n  }\n}\n\nNode StateTree::computeMaxLikelihoodStateProportions(DoubleNodeMap& s,\n                                                     int p,\n                                                     double vaf) const\n{\n  // 1. identify mutation vertex\n  int star = -1;\n  int x_star = -1;\n  int y_star = -1;\n  double mu_star = 0;\n  Node v_star = lemon::INVALID;\n  \n  for (NodeIt v_j(_S); v_j != lemon::INVALID; ++v_j)\n  {\n    const int j = _nodeToState[v_j];\n    if (isPresent(j))\n    {\n      int i = parent(j);\n      if (i == -1 || !isPresent(i)) continue;\n      if (z(i) == 0 && z(j) == 1)\n      {\n        star = j;\n        x_star = x(i);\n        y_star = y(i);\n        v_star = v_j;\n        mu_star = _cnState[_stateToNode[i]]._s[p] + _cnState[v_j]._s[p];\n        break;\n      }\n    }\n  }\n  \n  assert(star != -1);\n  \n  double C = mu_star * (x_star + y_star);\n  double D = 0;\n  for (NodeIt v_j(_S); v_j != lemon::INVALID; ++v_j)\n  {\n    const int j = _nodeToState[v_j];\n    if (isPresent(j) && (x(j) != x_star || y(j) != y_star))\n    {\n      C += _cnState[v_j]._s[p] * (x(j) + y(j));\n      D += _cnState[v_j]._s[p] * z(j);\n    }\n  }\n  \n  for (NodeIt v_j(_S); v_j != lemon::INVALID; ++v_j)\n  {\n    const int j = _nodeToState[v_j];\n    if (x_star == x(j) && y_star == y(j))\n    {\n      if (j == star)\n      {\n        s[v_j] = std::min(mu_star, vaf * C - D);\n      }\n      else\n      {\n        s[v_j] = std::max(0., mu_star - vaf * C + D);\n      }\n    }\n    else\n    {\n      s[v_j] = _cnState[v_j]._s[p];\n    }\n  }\n  \n  return v_star;\n}\n\ndouble StateTree::maxLikelihoodCCF(int p,\n                                   double vaf) const\n{\n  DoubleNodeMap s(_S, 0.);\n  computeMaxLikelihoodStateProportions(s, p, vaf);\n  \n  double ccf = 0;\n  for (NodeIt v_j(_S); v_j != lemon::INVALID; ++v_j)\n  {\n    const int j = _nodeToState[v_j];\n    if (isPresent(j) && z(j) > 0)\n    {\n      ccf += s[v_j];\n    }\n  }\n  \n  return ccf;\n}\n\ndouble StateTree::maxLikelihoodDCF(int p,\n                                   double vaf) const\n{\n  DoubleNodeMap s(_S, 0.);\n  Node v_star = computeMaxLikelihoodStateProportions(s, p, vaf);\n  int star = _nodeToState[v_star];\n  \n  double dcf = 0;\n  for (NodeIt v_j(_S); v_j != lemon::INVALID; ++v_j)\n  {\n    const int j = _nodeToState[v_j];\n//    if (isPresent(j))\n//      std::cout << \"s_{\" << x(j) << \",\" << y(j) << \",\" << z(j) << \"} = \" << s[v_j] << \" \" << _cnState[v_j]._s[p] << std::endl;\n    if (isPresent(j) && isDescendant(j, star))\n    {\n      dcf += s[v_j];\n    }\n  }\n  \n  return dcf;\n}\n\nvoid StateTree::init(const IntVector& pi)\n{\n  // state 0 should be the root\n  assert(pi[0] == -1);\n  char buf[1024];\n  \n  _root = _S.addNode();\n  _stateToNode[0] = _root;\n  _nodeToState[_root] = 0;\n  snprintf(buf, 1024, \"%d\", 0);\n  _label[_root] = buf;\n  \n  // init nodes of S_c\n  for (int i = 1; i < _k; ++i)\n  {\n//    if (0 <= pi[i] && pi[i] < _k)\n//    if (pi[i] != -2)\n    {\n      Node v_i = _S.addNode();\n      _stateToNode[i] = v_i;\n      _nodeToState[v_i] = i;\n      snprintf(buf, 1024, \"%d\", i);\n      _label[v_i] = buf;\n    }\n  }\n  \n  // init edges of S_c\n  for (int i = 1; i < _k; ++i)\n  {\n    int pi_i = pi[i];\n    \n    //assert(0 <= pi_i < _k);\n    if (0 <= pi_i && pi_i < _k)\n    {\n      _S.addArc(_stateToNode[pi_i], _stateToNode[i]);\n    }\n  }\n  \n  initD(_root);\n  \n  assert(lemon::dag(_S));\n}\n  \nStateTree::StateTree(const IntVector& pi)\n  : _k(pi.size())\n  , _S()\n  , _root(lemon::INVALID)\n  , _label(_S, \"\")\n  , _stateToNode(_k, lemon::INVALID)\n  , _nodeToState(_S)\n  , _D(_S)\n  , _cnState(_S)\n{\n  init(pi);\n}\n  \nStateTree::StateTree(const StateTree& other)\n  : _k(other._k)\n  , _S()\n  , _root(lemon::INVALID)\n  , _label(_S)\n  , _stateToNode(_k, lemon::INVALID)\n  , _nodeToState(_S)\n  , _D(_S)\n  , _cnState(_S)\n{\n  lemon::digraphCopy(other._S, _S)\n    .node(other._root, _root)\n    .nodeMap(other._nodeToState, _nodeToState)\n    .nodeMap(other._D, _D)\n    .nodeMap(other._label, _label)\n    .nodeMap(other._cnState, _cnState)\n    .run();\n  \n  for (NodeIt v_i(_S); v_i != lemon::INVALID; ++v_i)\n  {\n    _stateToNode[_nodeToState[v_i]] = v_i;\n  }\n}\n  \nStateTree& StateTree::operator=(const StateTree& other)\n{\n  if (this != &other)\n  {\n    _k = other._k;\n    _stateToNode = NodeVector(_k, lemon::INVALID);\n    \n    lemon::digraphCopy(other._S, _S)\n      .node(other._root, _root)\n      .nodeMap(other._nodeToState, _nodeToState)\n      .nodeMap(other._label, _label)\n      .nodeMap(other._D, _D)\n      .nodeMap(other._cnState, _cnState)\n      .run();\n    \n    for (NodeIt v_i(_S); v_i != lemon::INVALID; ++v_i)\n    {\n      _stateToNode[_nodeToState[v_i]] = v_i;\n    }\n  }\n  return *this;\n}\n  \nvoid StateTree::writeEdgeList(std::ostream& out) const\n{\n  bool first = true;\n  for (ArcIt a_ij(_S); a_ij != lemon::INVALID; ++a_ij)\n  {\n    if (first)\n    {\n      first = false;\n    }\n    else\n    {\n      out << \" ; \";\n    }\n    \n    Node v_i = _S.source(a_ij);\n    Node v_j = _S.target(a_ij);\n    \n    out << _label[v_i] << \" -> \" << _label[v_j];\n  }\n}\n\nvoid StateTree::writeDOT(const int m,\n                         std::ostream& out) const\n{\n  out << \"digraph S {\" << std::endl;\n  out << \"\\tlabel=\\\"VAF =\";\n  for (int p = 0; p < m; ++p)\n  {\n    out << std::setprecision(2) << \" \" << vaf(p);\n  }\n  out << \"\\\\nCF =\";\n  for (int p = 0; p < m; ++p)\n  {\n    out << std::setprecision(2) << \" \" << cf(p);\n  }\n  out << \"\\\\nDCF =\";\n  for (int p = 0; p < m; ++p)\n  {\n    out << std::setprecision(2) << \" \" << dcf(p);\n  }\n  out << \"\\\"\" << std::endl;\n  \n  for (NodeIt v_i(_S); v_i != lemon::INVALID; ++v_i)\n  {\n    int i = _nodeToState[v_i];\n    if (!isPresent(i)) continue;\n    \n    out << \"\\t\" << i << \" [label=\\\"(\"\n        << _cnState[v_i]._x << \",\"\n        << _cnState[v_i]._y << \",\"\n        << _cnState[v_i]._z << \")\";\n    for (double s : _cnState[v_i]._s)\n    {\n      out << std::setprecision(2) << \"\\\\n\" << s;\n    }\n    out << \"\\\"]\" << std::endl;\n  }\n  \n  for (ArcIt a_ij(_S); a_ij != lemon::INVALID; ++a_ij)\n  {\n    int i = _nodeToState[_S.source(a_ij)];\n    int j = _nodeToState[_S.target(a_ij)];\n    \n    out << \"\\t\" << i << \" -> \" << j << std::endl;\n  }\n  \n  out << \"}\" << std::endl;\n}\n  \nvoid StateTree::writeDOT(std::ostream& out) const\n{\n  out << \"digraph S {\" << std::endl;\n  \n  for (NodeIt v_i(_S); v_i != lemon::INVALID; ++v_i)\n  {\n    int i = _nodeToState[v_i];\n    if (!isPresent(i)) continue;\n    \n    out << \"\\t\" << i << \" [label=\\\"\" << _label[v_i];\n    for (double s : _cnState[v_i]._s)\n    {\n      out << std::setprecision(2) << \"\\\\n\" << s;\n    }\n    out << \"\\\"]\" << std::endl;\n  }\n  \n  for (ArcIt a_ij(_S); a_ij != lemon::INVALID; ++a_ij)\n  {\n    int i = _nodeToState[_S.source(a_ij)];\n    int j = _nodeToState[_S.target(a_ij)];\n    \n    out << \"\\t\" << i << \" -> \" << j << std::endl;\n  }\n  \n  out << \"}\" << std::endl;\n}\n  \nvoid StateTree::initD(Node v_i)\n{\n  IntSet& D_i = _D[v_i];\n  D_i.clear();\n  \n  D_i.insert(_nodeToState[v_i]);\n  \n  for (OutArcIt a(_S, v_i); a != lemon::INVALID; ++a)\n  {\n    Node v_j = _S.target(a);\n    \n    initD(v_j);\n    D_i.insert(_D[v_j].begin(), _D[v_j].end());\n  }\n}\n\nvoid StateTree::sampleMixtureProportions(double f, double purity)\n{\n  const int mutState = mutationState();\n  const IntSet& D_mutState = D(mutState);\n  std::gamma_distribution<> gamma_dist(1, 1);\n  \n  NodeSet postMutNodes;\n  NodeSet preMutNodes;\n  double sum_pre = 0;\n  double sum_post = 0;\n  for (NodeIt v_i(_S); v_i != lemon::INVALID; ++v_i)\n  {\n    const int i = _nodeToState[v_i];\n    if (!isPresent(i)) continue;\n\n    _cnState[v_i]._s.push_back(gamma_dist(g_rng));\n    if (D_mutState.count(i) == 1)\n    {\n      postMutNodes.insert(v_i);\n      sum_post += _cnState[v_i]._s.back();\n    }\n    else\n    {\n      preMutNodes.insert(v_i);\n      sum_pre += _cnState[v_i]._s.back();\n    }\n  }\n  \n  // zero out nodes with small weights\n  for (Node v_i : postMutNodes)\n  {\n    if ((_cnState[v_i]._s.back() / sum_post) < 0.05)\n    {\n      sum_post -= _cnState[v_i]._s.back();\n      _cnState[v_i]._s.back() = 0;\n    }\n  }\n  for (Node v_i : preMutNodes)\n  {\n    if ((_cnState[v_i]._s.back() / sum_pre) < 0.05)\n    {\n      sum_pre -= _cnState[v_i]._s.back();\n      _cnState[v_i]._s.back() = 0;\n    }\n  }\n  \n  for (Node v_i : postMutNodes)\n  {\n    _cnState[v_i]._s.back() /= sum_post;\n    _cnState[v_i]._s.back() *= f;\n    if (!g_tol.nonZero(_cnState[v_i]._s.back()))\n    {\n      _cnState[v_i]._s.back() = 0;\n    }\n  }\n  \n  for (Node v_i : preMutNodes)\n  {\n    _cnState[v_i]._s.back() /= sum_pre;\n    _cnState[v_i]._s.back() *= (1 - f - (1 - purity));\n    if (!g_tol.nonZero(_cnState[v_i]._s.back()))\n    {\n      _cnState[v_i]._s.back() = 0;\n    }\n  }\n  \n  _cnState[_root]._s.back() += 1 - purity;\n  if (!g_tol.nonZero(_cnState[_root]._s.back()))\n  {\n    _cnState[_root]._s.back() = 0;\n  }\n}\n\nvoid StateTree::writeClusterDOT(double gamma,\n                                int t,\n                                std::ostream& out) const\n{\n  const int m = getNrSamples();\n  \n  out << \"\\tsubgraph cluster_\" << t << \" {\" << std::endl;\n  out << \"\\t\\tlabel=\\\"gamma = \" << gamma;\n  \n  out << \"\\\\nVAF = \";\n  for (int p = 0; p < m; ++p)\n  {\n    out << std::setprecision(2) << \" \" << vaf(p);\n  }\n  out << \"\\\\nCF =\";\n  for (int p = 0; p < m; ++p)\n  {\n    out << std::setprecision(2) << \" \" << cf(p);\n  }\n  out << \"\\\\nDCF =\";\n  for (int p = 0; p < m; ++p)\n  {\n    out << std::setprecision(2) << \" \" << dcf(p);\n  }\n  out << \"\\\"\" << std::endl;\n  \n  for (NodeIt v_i(_S); v_i != lemon::INVALID; ++v_i)\n  {\n    int i = _nodeToState[v_i];\n    if (!isPresent(i)) continue;\n    \n    out << \"\\t\\t\" << i + t * 100 << \" [label=\\\"(\"\n        << _cnState[v_i]._x << \",\"\n        << _cnState[v_i]._y << \",\"\n        << _cnState[v_i]._z << \")\";\n    for (double s : _cnState[v_i]._s)\n    {\n      out << std::setprecision(2) << \"\\\\n\" << s;\n    }\n    out << \"\\\"]\" << std::endl;\n  }\n  \n  for (ArcIt a_ij(_S); a_ij != lemon::INVALID; ++a_ij)\n  {\n    int i = _nodeToState[_S.source(a_ij)];\n    int j = _nodeToState[_S.target(a_ij)];\n    \n    out << \"\\t\\t\" << i + t * 100 << \" -> \" << j + t * 100 << std::endl;\n  }\n  \n  out << \"\\t}\" << std::endl;\n}\n\nstd::ostream& operator<<(std::ostream& out, const StateTree& S)\n{\n  // output pi\n  out << -1;\n  for (int i = 1; i < S.k(); ++i)\n  {\n    out << \" \" << S.parent(i);\n  }\n  out << std::endl;\n  \n  // output vertices\n  for (int i = 0; i < S.k(); ++i)\n  {\n    Node v_i = S.node(i);\n    out << S._cnState[v_i]._x\n        << \" \" << S._cnState[v_i]._y\n        << \" \" << S._cnState[v_i]._z;\n    for (double s : S._cnState[v_i]._s)\n    {\n      out << \" \" << s;\n    }\n    out << std::endl;\n  }\n  \n  // output labels\n  out << S.label(0);\n  for (int i = 1; i < S.k(); ++i)\n  {\n    out << \" \" << S.label(i);\n  }\n  out << std::endl;\n\n  return out;\n}\n  \nstd::istream& operator>>(std::istream& in, StateTree& S)\n{\n  typedef std::vector<std::string> StringVector;\n  \n  std::string line;\n  getline(in, line);\n  std::stringstream ss(line);\n  \n  StringVector s;\n  boost::split(s, line, boost::is_any_of(\" \\t\"));\n  \n  IntVector pi(s.size(), -1);\n  for (int i = 0; i < s.size(); ++i)\n  {\n    ss >> pi[i];\n  }\n  \n  S = StateTree(pi);\n  \n  for (int i = 0; i < S.k(); ++i)\n  {\n    getline(in, line);\n    ss.clear();\n    ss.str(line);\n    \n    Node v_i = S.node(i);\n    StateTree::CopyNumberState& cnState_i = S._cnState[v_i];\n    \n    boost::split(s, line, boost::is_any_of(\" \"));\n    \n    cnState_i._x = boost::lexical_cast<int>(s[0]);\n    cnState_i._y = boost::lexical_cast<int>(s[1]);\n    cnState_i._z = boost::lexical_cast<int>(s[2]);\n\n    for (int j = 3; j < s.size(); ++j)\n    {\n      cnState_i._s.push_back(boost::lexical_cast<double>(s[j]));\n    }\n  }\n  \n  getline(in, line);\n  ss.clear();\n  ss.str(line);\n  for (int i = 0; i < S.k(); ++i)\n  {\n    ss >> S._label[S._stateToNode[i]];\n  }\n  \n  return in;\n}\n\nstd::ostream& operator<<(std::ostream& out, const StateTreeVector& vecS)\n{\n  out << vecS.size() << \" #state trees\" << std::endl;\n  for (const StateTree& S : vecS)\n  {\n    out << S;\n  }\n  \n  return out;\n}\n\nstd::istream& operator>>(std::istream& in, StateTreeVector& vecS)\n{\n  g_lineNumber = 0;\n  \n  std::string line;\n  getline(in, line);\n  std::stringstream ss(line);\n  \n  int nrStateTrees = -1;\n  ss >> nrStateTrees;\n  \n  if (nrStateTrees < 1)\n  {\n    throw std::runtime_error(getLineNumber() + \"Error: incorrect number of state trees\");\n  }\n  \n  for (int i = 0; i < nrStateTrees; ++i)\n  {\n    StateTree S;\n    in >> S;\n    vecS.push_back(S);\n  }\n  \n  return in;\n}\n", "meta": {"hexsha": "3b28224bba47f99f50da23c8bc36086b228b195b", "size": 15462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/decifer/cpp/statetree.cpp", "max_stars_repo_name": "brian-arnold/decifer", "max_stars_repo_head_hexsha": "35be17f44988f55eb2a1cf71dc27ad2041c7d044", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2019-05-04T10:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T06:17:16.000Z", "max_issues_repo_path": "src/decifer/cpp/statetree.cpp", "max_issues_repo_name": "brian-arnold/decifer", "max_issues_repo_head_hexsha": "35be17f44988f55eb2a1cf71dc27ad2041c7d044", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T09:13:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T22:19:35.000Z", "max_forks_repo_path": "src/decifer/cpp/statetree.cpp", "max_forks_repo_name": "brian-arnold/decifer", "max_forks_repo_head_hexsha": "35be17f44988f55eb2a1cf71dc27ad2041c7d044", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T12:56:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T14:05:34.000Z", "avg_line_length": 21.9630681818, "max_line_length": 128, "alphanum_fraction": 0.5038158065, "num_tokens": 5266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.028870905588472114, "lm_q1q2_score": 0.013534409922086965}}
{"text": "#include \"datadeck.hh\"\n\n#include <armadillo>\n\n#include <iostream>\n\n/**\n * @brief Read table & store table's data\n */\nDatadeck::Datadeck(const char *file_name) {\n    char line_clear[CHARL];\n    char temp[CHARN];   // buffer for table data\n    std::string table_deck_title;\n    int table_count(0);\n    double value(0);\n    int var_dim[3]={1, 1, 1};\n    int tt(0);\n    Table *table;\n    // opening aero-deck file stream\n    std::ifstream tbl_stream(file_name);\n\n    if (tbl_stream.fail()) {\n        std::cerr << \"*** Error: File stream '\" << file_name << \"' failed to open (check spelling) ***\\n\";\n        exit(1);\n    }\n\n    // determing the total # of tbl_stream\n    while (!tbl_stream.eof()) {\n        tbl_stream >> temp;\n        if (!strcmp(temp, \"TITLE\")) {\n            tbl_stream.getline(line_clear, CHARL, '\\n');\n            table_deck_title = line_clear;\n        }\n        if (strstr(temp, \"DIM\"))\n            table_count++;\n    }  // EOF reached of aero_deck\n\n    // removing EOF bit (-1)\n    tbl_stream.clear();\n    // rewinding to beginning\n    tbl_stream.seekg(std::ios::beg);\n\n    // creating pointer array table\n    this->set_title(table_deck_title);\n    this->set_capacity(table_count);\n    this->alloc_mem();\n\n    // discarding all entries until first DIM\n    do {\n        tbl_stream >> temp;\n    }while (!strstr(temp, \"DIM\"));\n\n    // loading tables one at a time\n    for (int t=0; t < table_count; t++) {\n        // creating and allocating memory to object 'table'\n        table = new Table;\n\n        // extracting table dimension\n        // at this point 'temp' is holding xDIM\n        char dim_buff[2];\n        int table_dim(0);\n        strncpy(dim_buff, temp, 1);\n        dim_buff[1] = '\\0';\n        // converting character to integer\n        sscanf(dim_buff, \"%d\", &table_dim);\n        table->set_dim(table_dim);\n\n        // extracting table name\n        tbl_stream >> temp;\n        table->set_name(temp);\n        tbl_stream.getline(line_clear, CHARL, '\\n');\n\n        // extracting dimensions of independent variables\n        var_dim[0] = 1;\n        var_dim[1] = 1;\n        var_dim[2] = 1;\n        for (tt=0; tt < table_dim; tt++) {\n            tbl_stream >> temp;\n            tbl_stream >> var_dim[tt];\n            if (tt == 0)\n                table->set_var1_dim(var_dim[tt]);\n            if (tt == 1)\n                table->set_var2_dim(var_dim[tt]);\n            if (tt == 2)\n                table->set_var3_dim(var_dim[tt]);\n        }\n        tbl_stream.getline(line_clear, CHARL, '\\n');\n\n        // allocating memory for variables and data arrays\n        table->var1_values = std::vector<double>(var_dim[0]);\n        table->var2_values = std::vector<double>(var_dim[1]);\n        table->var3_values = std::vector<double>(var_dim[2]);\n        table->data = std::vector<double>(var_dim[0] * var_dim[1] * var_dim[2]);\n\n        // determining max number of rows of data\n        int num_rows = var_dim[0];\n        if (var_dim[0] < var_dim[1]) num_rows=var_dim[1];\n        if (var_dim[2] > num_rows) num_rows=var_dim[2];\n\n        // reading num_row of data\n        for (tt=0; tt < num_rows; tt++) {\n            // loading 1.variable values\n            if (tt < var_dim[0]) {\n                tbl_stream >> value;\n                table->set_var1_value(tt, value);\n            }\n\n            // loading 2.variable values, but bypass if default dimension one\n            if (tt < var_dim[1]&&var_dim[1] != 1) {\n                tbl_stream >> value;\n                table->set_var2_value(tt, value);\n            }\n\n            // loading 3.variable values, but bypass if default dimension one\n            if (tt < var_dim[2]&&var_dim[2] != 1) {\n                tbl_stream >> value;\n                table->set_var3_value(tt, value);\n            }\n\n            // loading tabular data, which in all cases has only 'var_dim[0]' rows\n            if (tt < var_dim[0]) {\n                // read one row of data\n                for (int ttt=0; ttt < var_dim[1]*var_dim[2]; ttt++) {\n                    tbl_stream >> value;\n                    table->set_data(tt*var_dim[1]*var_dim[2]+ttt, value);\n                }\n            }\n        }  // end of reading data\n\n        // loading table into 'Datadeck' pointer array 'Table **tabel_ptr'\n        this->set_counter(t);\n        this->add_table(*table);\n        tbl_stream >> temp;  // reading next DIM entry\n    }  // end of 'for' loop, finished loading all tables\n}\n\n/**\n * @brief Single independent variable look-up\n * constant extrapolation at the upper end, slope extrapolation at the lower end\n * flag = 1 means if input value hit upper bound use max value \n * @author 030717 Created by Peter H Zipfel\n */\ndouble Datadeck::look_up(std::string name, double value1, unsigned int flag) {\n    // finding slot of table in table pointer array (Table **table_ptr)\n    int slot(-1);\n    std::string tbl_name;\n    do {\n        slot++;\n        tbl_name = get_tbl(slot)->get_name();\n    }while (name != tbl_name);\n\n    // getting table index locater of discrete value just below of variable value\n    int var1_dim = get_tbl(slot)->get_var1_dim();\n    int loc1 = find_index(var1_dim-1, value1, get_tbl(slot)->var1_values);\n    if (flag == 1) {\n        if (loc1 == (var1_dim - 1)) value1 = get_tbl(slot)->var1_values[loc1];\n        if (loc1 == 0) {\n            if (value1 < get_tbl(slot)->var1_values[loc1]) value1 = get_tbl(slot)->var1_values[loc1];\n        }\n    }\n\n    // using max discrete value if value is outside table\n    // if (loc1 == (var1_dim-1)) return get_tbl(slot)->data[loc1];\n    if (loc1 == (var1_dim-1)) return interpolate(loc1-1, loc1, slot, value1);\n\n    return interpolate(loc1, loc1+1, slot, value1);\n}\n\n/**\n * @brief Two independent variables look-up\n * Constant extrapolation at the upper end, slope extrapolation at the lower end\n * flag = 1 means if input value hit upper bound use max value \n * @author 030717 Created by Peter H Zipfel\n */\ndouble Datadeck::look_up(std::string name, double value1, double value2, unsigned int flag) {\n    // finding slot of table in table pointer array (Table **table_ptr)\n    int slot(-1);\n    std::string tbl_name;\n    do {\n        slot++;\n        tbl_name = get_tbl(slot)->get_name();\n    }while (name != tbl_name);\n\n\n    // getting table index (off-set) locater of discrete value just below or equal of the variable value\n    int var1_dim = get_tbl(slot)->get_var1_dim();\n    int loc1 = find_index(var1_dim-1, value1, get_tbl(slot)->var1_values);\n\n    int var2_dim = get_tbl(slot)->get_var2_dim();\n    int loc2 = find_index(var2_dim-1, value2, get_tbl(slot)->var2_values);\n\n    if (flag == 1) {\n        if (loc1 == (var1_dim - 1)) value1 = get_tbl(slot)->var1_values[loc1];\n        if (loc2 == (var2_dim - 1)) value2 = get_tbl(slot)->var2_values[loc2];\n        if (loc1 == 0) {\n            if (value1 < get_tbl(slot)->var1_values[loc1]) value1 = get_tbl(slot)->var1_values[loc1];\n        }\n        if (loc2 == 0) {\n            if (value2 < get_tbl(slot)->var2_values[loc2]) value2 = get_tbl(slot)->var2_values[loc2];\n        }\n    }\n\n    if (loc1 == (var1_dim - 1) && loc2 == (var2_dim - 1)) {\n        return interpolate(loc1 - 1, loc1, loc2 - 1, loc2, slot, value1, value2);\n    } else if (loc2 == (var2_dim - 1)) {\n        return interpolate(loc1, loc1 + 1, loc2 - 1, loc2, slot, value1, value2);\n    } else if (loc1 == (var1_dim - 1)) {\n        return interpolate(loc1 - 1, loc1, loc2, loc2 + 1, slot, value1, value2);\n    } else {\n        return interpolate(loc1, loc1+1, loc2, loc2+1, slot, value1, value2);\n    }\n}\n\n/**\n * @brief Three independent variables look-up\n * constant extrapolation at the upper end, slope extrapolation at the lower end\n * flag = 1 means if input value hit upper bound use max value \n * @author 030723 Created by Peter H Zipfel\n */\ndouble Datadeck::look_up(std::string name, double value1, double value2, double value3, unsigned int flag) {\n    // finding slot of table in table pointer array (Table **table_ptr)\n    int slot(-1);\n    std::string tbl_name;\n    do {\n        slot++;\n        tbl_name = get_tbl(slot)->get_name();\n    }while (name != tbl_name);\n\n\n    // getting table index locater of discrete value just below of variable value\n    int var1_dim = get_tbl(slot)->get_var1_dim();\n    int loc1 = find_index(var1_dim-1, value1, get_tbl(slot)->var1_values);\n\n    int var2_dim = get_tbl(slot)->get_var2_dim();\n    int loc2 = find_index(var2_dim-1, value2, get_tbl(slot)->var2_values);\n\n    int var3_dim = get_tbl(slot)->get_var3_dim();\n    int loc3 = find_index(var3_dim-1, value3, get_tbl(slot)->var3_values);\n\n    if (flag == 1) {\n        if (loc1 == (var1_dim - 1)) value1 = get_tbl(slot)->var1_values[loc1];\n        if (loc2 == (var2_dim - 1)) value2 = get_tbl(slot)->var2_values[loc2];\n        if (loc3 == (var3_dim - 1)) value3 = get_tbl(slot)->var3_values[loc3];\n        if (loc1 == 0) {\n            if (value1 < get_tbl(slot)->var1_values[loc1]) value1 = get_tbl(slot)->var1_values[loc1];\n        }\n        if (loc2 == 0) {\n            if (value2 < get_tbl(slot)->var2_values[loc2]) value2 = get_tbl(slot)->var2_values[loc2];\n        }\n        if (loc3 == 0) {\n            if (value3 < get_tbl(slot)->var3_values[loc3]) value3 = get_tbl(slot)->var3_values[loc3];\n        }\n    }\n\n    if (loc1 == (var1_dim-1) && loc2 == (var2_dim-1) && loc3 == (var3_dim-1)) {\n        return interpolate(loc1-1, loc1, loc2-1, loc2, loc3-1, loc3, slot, value1, value2, value3);\n    } else if (loc3 == (var3_dim-1)) {\n        return interpolate(loc1, loc1+1, loc2, loc2+1, loc3-1, loc3, slot, value1, value2, value3);\n    } else if (loc2 == (var2_dim-1)) {\n        return interpolate(loc1, loc1+1, loc2-1, loc2, loc3, loc3+1, slot, value1, value2, value3);\n    } else if (loc1 == (var1_dim-1)) {\n        return interpolate(loc1-1, loc1, loc2, loc2+1, loc3, loc3+1, slot, value1, value2, value3);\n    } else if (loc3 == (var3_dim-1) && loc2 == (var2_dim-1)) {\n        return interpolate(loc1, loc1+1, loc2-1, loc2, loc3-1, loc3, slot, value1, value2, value3);\n    } else if (loc3 == (var3_dim-1) && loc1 == (var1_dim-1)) {\n        return interpolate(loc1-1, loc1, loc2, loc2+1, loc3-1, loc3, slot, value1, value2, value3);\n    } else if (loc1 == (var1_dim-1) && loc2 == (var2_dim-1)) {\n        return interpolate(loc1-1, loc1, loc2-1, loc2, loc3, loc3+1, slot, value1, value2, value3);\n    } else {\n        return interpolate(loc1, loc1+1, loc2, loc2+1, loc3, loc3+1, slot, value1, value2, value3);\n    }\n}\n\n/**\n * @brief Table index finder\n * This is a binary search method it is O(lgN)\n * \n * @returns array locater of the discrete_variable just below variable\n * Keeps max or min array locater if variable is outside those max or min\n *\n * @author 010628 Created by Peter H Zipfel\n */\nint Datadeck::find_index(int max, double value, std::vector<double> list) {\n    if (value >= list[max]) {\n        return max;\n    } else if (value <= list[0]) {\n        return 0;\n    } else {\n        int index = 0;\n        int mid;\n        while (index <= max) {\n            mid = (index+max)/2;      // integer division\n            if (value < list[mid])\n                max = mid-1;\n            else if (value > list[mid])\n                index = mid+1;\n            else\n                return mid;\n        }\n        return max;\n    }\n}\n\n/**\n * @brief Linear one-dimensional interpolation\n * Data deck must contain table in the following format:\n *\n * X1       Table Values(X1)                            \n *                                                      \n * X11      Y11\n * X12      Y12                                         \n * X13      Y13                                         \n *\n * Constant extrapolation beyond max values of X1\n * Slope extrapolation beyond min values of X1\n *\n * @author 030717 Created by Peter H Zipfel\n */\ndouble Datadeck::interpolate(int ind1, int ind2, int slot, double val) {\n    double dx(0), dy(0);\n    double dumx(0);\n\n    double diff = val-get_tbl(slot)->var1_values[ind1];\n    dx = get_tbl(slot)->var1_values[ind2]-get_tbl(slot)->var1_values[ind1];\n    dy = get_tbl(slot)->data[ind2]-get_tbl(slot)->data[ind1];\n\n    if (fabs(dx) > arma::datum::eps) dumx = diff/dx;\n    dy = dumx*dy;\n\n    return get_tbl(slot)->data[ind1]+dy;\n}\n\n/**\n * @brief Linear, two-dimensional interpolation\n * File must contain table in the following form:\n *\n *  X1  X2  //Table Values(X1-row, X2-column)\n *            ---------------\n *  X11 X21   |Y11  Y12  Y13|\n *  X12 X22   |Y21  Y22  Y23|    <- data\n *  X13 X23   |Y31  Y32  Y33|\n *  X14       |Y41  Y42  Y43|\n *            ---------------\n * Constant extrapolation beyond max values of X1 and X2\n * Slope extrapolation beyond min values of X1 and X2\n *\n * @author 030718 Created by Peter H Zipfel\n */\ndouble Datadeck::interpolate(int ind10, int ind11, int ind20, int ind21, int slot, double value1,\n                    double value2) {\n    double dx1(0), dx2(0);\n    double dumx1(0), dumx2(0);\n\n    int var1_dim = get_tbl(slot)->get_var1_dim();\n    int var2_dim = get_tbl(slot)->get_var2_dim();\n\n    double diff1 = value1-get_tbl(slot)->var1_values[ind10];\n    double diff2 = value2-get_tbl(slot)->var2_values[ind20];\n\n    // if (ind10 == (var1_dim-1))  // Assures constant upper extrapolation of first variable\n    //     ind11 = ind10;\n    // else\n        dx1 = get_tbl(slot)->var1_values[ind11]-get_tbl(slot)->var1_values[ind10];\n\n    // if (ind20 == (var2_dim-1))  // Assures constant upper extrapolation of second variable\n    //     ind21 = ind20;\n    // else\n        dx2 = get_tbl(slot)->var2_values[ind21]-get_tbl(slot)->var2_values[ind20];\n\n    if (fabs(dx1) > arma::datum::eps) dumx1 = diff1/dx1;\n    if (fabs(dx2) > arma::datum::eps) dumx2 = diff2/dx2;\n\n    double y11 = get_tbl(slot)->data[ind10*var2_dim+ind20];\n    double y12 = get_tbl(slot)->data[ind10*var2_dim+ind21];\n    double y21 = get_tbl(slot)->data[ind11*var2_dim+ind20];\n    double y22 = get_tbl(slot)->data[ind11*var2_dim+ind21];\n    double y1 = dumx1*(y21-y11)+y11;\n    double y2 = dumx1*(y22-y12)+y12;\n\n    return dumx2*(y2-y1)+y1;\n}\n/**\n * @brief Linear, three-dimensional interpolation\n * File must contain table in the following form:\n *\n *  X1  X2  X3    Table Values(X1-row, X2-block, X3-column) <- don't type (illustration only)\n *\n *                (X1 x X3) (X1 x X3) (X1 x X3) (X1 x X3)   <- don't type\n *                 for X21   for X22   for X23   for X24    <- don't type\n *               -----------------------------------------\n *  X11 X21 X31  |Y111 Y112|Y121 Y122|Y131 Y132|Y141 Y142|\n *  X12 X22 X32  |Y211 Y212|Y221 Y222|Y231 Y232|Y241 Y242|  <- data; don't type: '|'\n *  X13 X23      |Y311 Y312|Y321 Y322|Y331 Y332|Y341 Y342|\n *      X24      -----------------------------------------\n *\n * Constant extrapolation beyond max values of X1, X2 and X3\n * Slope extrapolation beyond min values of X1, X2 and X3\n *\n * @author 030723 Created and corrected by Peter Zipfel\n */\ndouble Datadeck::interpolate(int ind10, int ind11, int ind20, int ind21, int ind30, int ind31,\n                             int slot, double value1, double value2, double value3) {\n    double dx1(0), dx2(0), dx3(0);\n    double dumx1(0), dumx2(0), dumx3(0);\n\n    int var1_dim = get_tbl(slot)->get_var1_dim();\n    int var2_dim = get_tbl(slot)->get_var2_dim();\n    int var3_dim = get_tbl(slot)->get_var3_dim();\n\n    double diff1 = value1-get_tbl(slot)->var1_values[ind10];\n    double diff2 = value2-get_tbl(slot)->var2_values[ind20];\n    double diff3 = value3-get_tbl(slot)->var3_values[ind30];\n\n    if (ind10 != (var1_dim-1))  // Assures constant upper extrapolation of first variable\n        dx1 = get_tbl(slot)->var1_values[ind11]-get_tbl(slot)->var1_values[ind10];\n\n    if (ind20 == (var2_dim-1))  // Assures constant upper extrapolation of second variable\n        ind21 = ind20;\n    else\n        dx2 = get_tbl(slot)->var2_values[ind21]-get_tbl(slot)->var2_values[ind20];\n\n    if (ind30 == (var3_dim-1))  // Assures constant upper extrapolation of third variable\n        ind31 = ind30;\n    else\n        dx3 = get_tbl(slot)->var3_values[ind31]-get_tbl(slot)->var3_values[ind30];\n\n    if (dx1 > arma::datum::eps) dumx1 = diff1/dx1;\n    if (dx2 > arma::datum::eps) dumx2 = diff2/dx2;\n    if (dx3 > arma::datum::eps) dumx3 = diff3/dx3;\n    // int ind10,int ind11,int ind20,int ind21,int ind30,int ind31\n    //      i        i+1        j         j+1       k        k+1\n    // Use innner x1 and outer variable x3 for 2DIM interpolation, middle variable x2 is parameter\n    // For parameter ind20\n    double y11 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind20*var3_dim+ind30];\n    double y12 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind20*var3_dim+ind30+var2_dim*var3_dim];\n    double y31 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind20*var3_dim+ind31];\n    double y32 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind20*var3_dim+ind31+var2_dim*var3_dim];\n    // 2DIM interpolation\n    double y1 = dumx1*(y12-y11)+y11;\n    double y3 = dumx1*(y32-y31)+y31;\n    double y21 = dumx3*(y3-y1)+y1;\n\n    // For parameter ind21\n    y11 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind21*var3_dim+ind30];\n    y12 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind21*var3_dim+ind30+var2_dim*var3_dim];\n    y31 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind21*var3_dim+ind31];\n    y32 = get_tbl(slot)->data[ind10*var2_dim*var3_dim+ind21*var3_dim+ind31+var2_dim*var3_dim];\n    // 2DIM interpolation\n    y1 = dumx1*(y12-y11)+y11;\n    y3 = dumx1*(y32-y31)+y31;\n    double y22 = dumx3*(y3-y1)+y1;\n\n    // 1DIM interpolation between the middle variable\n    return dumx2*(y22-y21)+y21;\n}\n", "meta": {"hexsha": "d69f701159fdc037c5089b2e434f261581828e9b", "size": 17556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/cad/src/datadeck.cpp", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/cad/src/datadeck.cpp", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/cad/src/datadeck.cpp", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "avg_line_length": 38.5, "max_line_length": 108, "alphanum_fraction": 0.5987126908, "num_tokens": 5234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.029312228419449384, "lm_q1q2_score": 0.013513429140401491}}
{"text": "#include \"gather_scatter.h\"\r\n#include \"config.h\"\r\n#include \"use_lua.h\"\r\n#include \"io_utilities.h\"\r\n#include \"particle_groups.h\"\r\n#include \"particles.h\"\r\n#include \"check_particle.h\"\r\n#include \"call_lua_function.h\"\r\n\r\n#include <boost/format.hpp>\r\n#include <boost/ref.hpp>\r\n#include <luabind/luabind.hpp>\r\n#include <cmath>\r\n#include <iostream>\r\n#include <stdexcept>\r\n\r\nnamespace PIC {\r\n\r\ndouble R(double x, double h)\r\n{\r\n    return ((fabs(x) < h) ? (1.0 - fabs(x)/h) : 0.0);\r\n}\r\n\r\ndouble R(double x, double y, double z, double h)\r\n{\r\n    return (R(x, h)*R(y, h)*R(z, h));\r\n}\r\n\r\n/*****************************************************************************\r\n* Gather edge-centered values.                                               *\r\n*    at_point - specified position                                           *\r\n*    val_x, val_y, val_z - Cell required values                              *\r\n*    ret_vec - result gathered value                                         *\r\n* Used to interpolate Bx, By, Bz for specified position                      *\r\n*****************************************************************************/\r\nvoid gather_edge(const Grid& grid, const DblVector& at_point,\r\n                 CellVectorValue val, DblVector& ret_vec)\r\n{\r\n    ret_vec.x = gather_vector<EdgeXCentering>(grid, at_point, val, &DblVector::x);\r\n    ret_vec.y = gather_vector<EdgeYCentering>(grid, at_point, val, &DblVector::y);\r\n    ret_vec.z = gather_vector<EdgeZCentering>(grid, at_point, val, &DblVector::z);\r\n}\r\n\r\n/*****************************************************************************\r\n* Gather face-centered values: Ex, Ey, Ez, UPx, UPy, UPz, UEx, UEy, UEz      *\r\n*    at_point - specified position                                           *\r\n*    val_x, val_y, val_z - Pointers to cell members required                 *\r\n*    ret_vec - result gathered value                                         *\r\n* Used to interpolate Ex, Ey, Ez, UPx, UPy, UPz, UEx, UEy, UEz values        *\r\n* for specified position.                                                    *\r\n*****************************************************************************/\r\nvoid gather_face(const Grid& grid, const DblVector& at_point,\r\n                 CellVectorValue val, DblVector& ret_vec)\r\n\r\n{\r\n    ret_vec.x = gather_vector<FaceXCentering>(grid, at_point, val, &DblVector::x);\r\n    ret_vec.y = gather_vector<FaceYCentering>(grid, at_point, val, &DblVector::y);\r\n    ret_vec.z = gather_vector<FaceZCentering>(grid, at_point, val, &DblVector::z);\r\n}\r\n\r\n/*****************************************************************************\r\n* Gather cell-centered value.                                                *\r\n*   x, y, z - specified position                                             *\r\n*   val - Pointer to cell member required                                    *\r\n*   ret_val - result gathered value                                          *\r\n* Used to interpolate density NP values for specified position.              *\r\n*                                                                            *\r\n*****************************************************************************/\r\ndouble gather_center(const Grid& grid, const DblVector& at_point, CellScalarValue val)\r\n{\r\n    return gather_scalar<CellCentering>(grid, at_point, val);\r\n}\r\n\r\n/******************************************************\r\n* interpolates grid values to specified point (x,y,z) *\r\n******************************************************/\r\nvoid from_grid_to_point(const Grid& grid, const DblVector& vec_to_point, Grid::NodeType& val_at_point)\r\n{\r\n    // interpolate NP\r\n    val_at_point.NP = gather_center(grid, vec_to_point, &Cell::NP);\r\n\r\n    // interpolate B\r\n    gather_edge(grid, vec_to_point, &Cell::B, val_at_point.B);\r\n\r\n    //interpolate E\r\n    gather_face(grid, vec_to_point, &Cell::E, val_at_point.E);\r\n\r\n    // interpolate UP\r\n    gather_face(grid, vec_to_point, &Cell::UP, val_at_point.UP);\r\n\r\n    // interpolate UE\r\n    gather_face(grid, vec_to_point, &Cell::UE, val_at_point.UE);\r\n}\r\n\r\nvoid set_boundary_conditions(const std::string& lua_func_name)\r\n{\r\n    if (!call_lua_function(lua_func_name.c_str()))\r\n    {\r\n        std::string msg_fmt = \"Please check function \\\"%s\\\" in \\\"%s\\\" and restart.\";\r\n\r\n        std::string msg = str(boost::format(msg_fmt) % lua_func_name\r\n                                                     % PIC::Config::cfg_script_name());\r\n\r\n        throw std::domain_error(msg);\r\n    }\r\n}\r\n\r\nvoid set_boundary_conditions(const std::string& lua_func_name, DensityGrid& dg)\r\n{\r\n    UseLua lua;\r\n\r\n    try\r\n    {\r\n        luabind::call_function<void>(lua, lua_func_name.c_str(), boost::ref(dg));\r\n    }\r\n    catch (...)\r\n    {\r\n        const std::string fmt = \"Error: in function \\\"%s\\\" not defined or invalid in \\\"%s\\\".\";\r\n        std::string msg = str(boost::format(fmt)\r\n                              % lua_func_name\r\n                              % PIC::Config::cfg_script_name());\r\n        throw std::domain_error(msg);\r\n    }\r\n}\r\n\r\nvoid scatter_particle_std(const Particle& particle, DensityGrid& grid, const DblVector& dr)\r\n{\r\n    const double h = Config::h();\r\n\r\n    ParticleGroups part_groups;\r\n    const double q = particle.ni*part_groups[particle.group_name].charge;\r\n\r\n    const index_t pi = static_cast<index_t>((particle.r.x + dr.x)/h);\r\n    const index_t pj = static_cast<index_t>((particle.r.y + dr.y)/h);\r\n    const index_t pk = static_cast<index_t>((particle.r.z + dr.z)/h);\r\n\r\n    typedef DensityGrid::NodeType DensityNode;\r\n\r\n    for (index_t i = pi - 1; i != pi + 2; ++i)\r\n    for (index_t j = pj - 1; j != pj + 2; ++j)\r\n    for (index_t k = pk - 1; k != pk + 2; ++k)\r\n    {\r\n        DensityNode& cell = grid(i, j, k);\r\n\r\n        cell.NP += q*R((i + 0.5)*h - particle.r.x,\r\n                       (j + 0.5)*h - particle.r.y,\r\n                       (k + 0.5)*h - particle.r.z, h);\r\n\r\n        cell.UP.x += q*particle.v.x*R((i)*h       - particle.r.x,\r\n                                      (j + 0.5)*h - particle.r.y,\r\n                                      (k + 0.5)*h - particle.r.z, h);\r\n\r\n        cell.UP.y += q*particle.v.y*R((i + 0.5)*h - particle.r.x,\r\n                                      (j)*h       - particle.r.y,\r\n                                      (k + 0.5)*h - particle.r.z, h);\r\n\r\n        cell.UP.z += q*particle.v.z*R((i + 0.5)*h - particle.r.x,\r\n                                      (j + 0.5)*h - particle.r.y,\r\n                                      (k)*h       - particle.r.z, h);\r\n    }\r\n}\r\n\r\nvoid scatter_particle_zigzag(const Particle& particle, DensityGrid& grid, const DblVector& dr)\r\n{\r\n    const double h = Config::h();\r\n\r\n    const double tau2 = Config::tau_2();\r\n\r\n    const double x1 = particle.r.x;\r\n    const double x2 = x1 + dr.x;\r\n    const index_t i[2] = { static_cast<index_t>(x1/h), static_cast<index_t>(x2/h) };\r\n\r\n    const double y1 = particle.r.y;\r\n    const double y2 = y1 + dr.y;\r\n    const index_t j[2] = { static_cast<index_t>(y1/h), static_cast<index_t>(y2/h) };\r\n\r\n    const double z1 = particle.r.z;\r\n    const double z2 = z1 + dr.z;\r\n    const index_t k[2] = { static_cast<index_t>(z1/h), static_cast<index_t>(z2/h) };\r\n    ParticleGroups part_groups;\r\n    const double q = particle.ni*part_groups[particle.group_name].charge;\r\n\r\n    {\r\n        // scatter charge Q and store it in NP\r\n        const double wi[2] = { (i[1] + 1 - x2/h), (x2/h - i[1]) };\r\n        const double wj[2] = { (j[1] + 1 - y2/h), (y2/h - j[1]) };\r\n        const double wk[2] = { (k[1] + 1 - z2/h), (z2/h - k[1]) };\r\n\r\n        for (int l = 0; l != 2; ++l)\r\n        for (int m = 0; m != 2; ++m)\r\n        for (int n = 0; n != 2; ++n)\r\n        {\r\n            grid(i[1] + l, j[1] + m, k[1] + n).NP += q*wi[l]*wj[m]*wk[n];\r\n        }\r\n    }\r\n\r\n    // scatter currents Jx, Jy, Jz and store them  in UPx, UPy, UPz\r\n    DblVector r(min(min(i[0]*h, i[1]*h) + h, max(max(i[0]*h, i[1]*h), 0.5*(x1 + x2))),\r\n                min(min(j[0]*h, j[1]*h) + h, max(max(j[0]*h, j[1]*h), 0.5*(y1 + y2))),\r\n                min(min(k[0]*h, k[1]*h) + h, max(max(k[0]*h, k[1]*h), 0.5*(z1 + z2))));\r\n\r\n    DblVector F[2] = { DblVector(q*(r.x - x1)/tau2, q*(r.y - y1)/tau2, q*(r.z - z1)/tau2),\r\n                       DblVector(q*(x2 - r.x)/tau2, q*(y2 - r.y)/tau2, q*(z2 - r.z)/tau2) };\r\n\r\n    DblVector W[2] = { DblVector(0.5*(x1 + r.x)/h - i[0], 0.5*(y1 + r.y)/h - j[0], 0.5*(z1 + r.z)/h - k[0]),\r\n                       DblVector(0.5*(r.x + x2)/h - i[1], 0.5*(r.y + y2)/h - j[1], 0.5*(r.z + z2)/h - k[1]) };\r\n\r\n    for (int m = 0; m != 2; ++m)\r\n    {\r\n        grid(i[m], j[m], k[m]).UP.x += F[m].x*(1.0 - W[m].y)*(1.0 - W[m].z);\r\n        grid(i[m], j[m] + 1, k[m]).UP.x += F[m].x*W[m].y*(1.0 - W[m].z);\r\n        grid(i[m], j[m], k[m] + 1).UP.x += F[m].x*(1.0 - W[m].y)*W[m].z;\r\n        grid(i[m], j[m] + 1, k[m] + 1).UP.x += F[m].x*W[m].y*W[m].z;\r\n\r\n        grid(i[m], j[m], k[m]).UP.y += F[m].y*(1.0 - W[m].x)*(1.0 - W[m].z);\r\n        grid(i[m] + 1, j[m], k[m]).UP.y += F[m].y*W[m].x*(1.0 - W[m].z);\r\n        grid(i[m], j[m], k[m] + 1).UP.y += F[m].y*(1.0 - W[m].x)*W[m].z;\r\n        grid(i[m] + 1, j[m], k[m] + 1).UP.y += F[m].y*W[m].x*W[m].z;\r\n\r\n        grid(i[m], j[m], k[m]).UP.z += F[m].z*(1.0 - W[m].x)*(1.0 - W[m].y);\r\n        grid(i[m] + 1, j[m], k[m]).UP.z += F[m].z*W[m].x*(1.0 - W[m].y);\r\n        grid(i[m], j[m] + 1, k[m]).UP.z += F[m].z*(1.0 - W[m].x)*W[m].y;\r\n        grid(i[m] + 1, j[m] + 1, k[m]).UP.z += F[m].z*W[m].x*W[m].y;\r\n    }\r\n}\r\n\r\n} // end of namespace PIC\r\n", "meta": {"hexsha": "42a038faf38cc683fc98f92b6128268d254a45c0", "size": 9505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gather_scatter.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/gather_scatter.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/gather_scatter.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": 41.6885964912, "max_line_length": 111, "alphanum_fraction": 0.4657548659, "num_tokens": 2726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.03410042399448256, "lm_q1q2_score": 0.013506092400662039}}
{"text": "#pragma once\n#include <type_traits>\n#include <Eigen/Dense>\n#include \"math.h\"\n\nnamespace Eigen\n{\n\tnamespace internal\n\t{\n\t\ttemplate<typename PacketType>\n\t\tstruct to_int_packet\n\t\t{\n\t\t\ttypedef PacketType type;\n\t\t};\n\n\t\ttemplate<typename PacketType>\n\t\tstruct to_float_packet\n\t\t{\n\t\t\ttypedef PacketType type;\n\t\t};\n\t}\n}\n\n#ifdef EIGEN_VECTORIZE_AVX\n#include <immintrin.h>\n#include \"avx_gamma.h\"\n\nnamespace Eigen\n{\n\tnamespace internal\n\t{\n\t\ttemplate<> struct to_int_packet<Packet8f>\n\t\t{\n\t\t\ttypedef Packet8i type;\n\t\t};\n\n\t\ttemplate<> struct to_float_packet<Packet8i>\n\t\t{\n\t\t\ttypedef Packet8f type;\n\t\t};\n\n\t\tEIGEN_STRONG_INLINE Packet8f p_to_f32(const Packet8i& a)\n\t\t{\n\t\t\treturn _mm256_cvtepi32_ps(a);\n\t\t}\n\n\t\tEIGEN_STRONG_INLINE Packet8f p_bool2float(const Packet8f& a)\n\t\t{\n\t\t\treturn _mm256_and_ps(_mm256_cmp_ps(a, _mm256_set1_ps(0), _CMP_NEQ_OQ), _mm256_set1_ps(1));\n\t\t}\n\n\t\tEIGEN_STRONG_INLINE Packet8f p_bool2float(const Packet8i& a)\n\t\t{\n\t\t\treturn p_bool2float(_mm256_castsi256_ps(a));\n\t\t}\n\t}\n}\n#endif\n#if defined(EIGEN_VECTORIZE_SSE2)\n#include <xmmintrin.h>\n#include \"sse_gamma.h\"\n\nnamespace Eigen\n{\n\tnamespace internal\n\t{\n\t\ttemplate<> struct to_int_packet<Packet4f>\n\t\t{\n\t\t\ttypedef Packet4i type;\n\t\t};\n\n\t\ttemplate<> struct to_float_packet<Packet4i>\n\t\t{\n\t\t\ttypedef Packet4f type;\n\t\t};\n\n\t\tEIGEN_STRONG_INLINE Packet4f p_to_f32(const Packet4i& a)\n\t\t{\n\t\t\treturn _mm_cvtepi32_ps(a);\n\t\t}\n\t\t\n\t\tEIGEN_STRONG_INLINE Packet4f p_bool2float(const Packet4f& a)\n\t\t{\n\t\t\treturn _mm_and_ps(_mm_cmpneq_ps(a, _mm_set1_ps(0)), _mm_set1_ps(1));\n\t\t}\n\n\t\tEIGEN_STRONG_INLINE Packet4f p_bool2float(const Packet4i& a)\n\t\t{\n\t\t\treturn p_bool2float(_mm_castsi128_ps(a));\n\t\t}\n\t}\n}\n#endif\n\nnamespace Eigen\n{\n\tnamespace internal\n\t{\n\t\ttemplate<typename Scalar, typename Scalar2> struct scalar_lgamma_subt_op {\n\t\t\tEIGEN_EMPTY_STRUCT_CTOR(scalar_lgamma_subt_op)\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& z, const Scalar2& a) const { return tomoto::math::lgammaSubt(z, a); }\n\t\t\ttemplate<typename Packet>\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& z, const Packet& a) const\n\t\t\t{\n\t\t\t\treturn lgamma_subt(z, a);\n\t\t\t}\n\t\t};\n\n\t\ttemplate<typename Scalar, typename Scalar2>\n\t\tstruct functor_traits<scalar_lgamma_subt_op<Scalar, Scalar2> >\n\t\t{\n\t\t\tenum {\n\t\t\t\tCost = HugeCost,\n\t\t\t\tPacketAccess = 1\n\t\t\t};\n\t\t};\n\n\t\ttemplate<>\n\t\tstruct scalar_cast_op<int32_t, float> {\n\t\t\tEIGEN_EMPTY_STRUCT_CTOR(scalar_cast_op)\n\t\t\ttypedef float result_type;\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const float operator() (const int32_t& a) const { return cast<int32_t, float>(a); }\n\t\t\t\n\t\t\ttemplate<typename Packet>\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const typename to_int_packet<typename std::remove_const<Packet>::type>::type& a) const\n\t\t\t{\n\t\t\t\treturn p_to_f32(a);\n\t\t\t}\n\t\t};\n\n\t\ttemplate<>\n\t\tstruct functor_traits<scalar_cast_op<int32_t, float> >\n\t\t{\n\t\t\tenum { Cost = NumTraits<float>::AddCost, PacketAccess = 1 };\n\t\t};\n\n\t\ttemplate<typename ArgType>\n\t\tstruct unary_evaluator<CwiseUnaryOp<scalar_cast_op<int32_t, float>, ArgType>, IndexBased >\n\t\t\t: evaluator_base<CwiseUnaryOp<scalar_cast_op<int32_t, float>, ArgType> >\n\t\t{\n\t\t\ttypedef CwiseUnaryOp<scalar_cast_op<int32_t, float>, ArgType> XprType;\n\n\t\t\tenum {\n\t\t\t\tCoeffReadCost = evaluator<ArgType>::CoeffReadCost + functor_traits<scalar_cast_op<int32_t, float>>::Cost,\n\n\t\t\t\tFlags = evaluator<ArgType>::Flags\n\t\t\t\t& (HereditaryBits | LinearAccessBit | (functor_traits<scalar_cast_op<int32_t, float>>::PacketAccess ? PacketAccessBit : 0)),\n\t\t\t\tAlignment = evaluator<ArgType>::Alignment\n\t\t\t};\n\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n\t\t\t\texplicit unary_evaluator(const XprType& op)\n\t\t\t\t: m_functor(op.functor()),\n\t\t\t\tm_argImpl(op.nestedExpression())\n\t\t\t{\n\t\t\t\tEIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<float>::AddCost);\n\t\t\t\tEIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);\n\t\t\t}\n\n\t\t\ttypedef typename XprType::CoeffReturnType CoeffReturnType;\n\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n\t\t\t\tCoeffReturnType coeff(Index row, Index col) const\n\t\t\t{\n\t\t\t\treturn m_functor(m_argImpl.coeff(row, col));\n\t\t\t}\n\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n\t\t\t\tCoeffReturnType coeff(Index index) const\n\t\t\t{\n\t\t\t\treturn m_functor(m_argImpl.coeff(index));\n\t\t\t}\n\n\t\t\ttemplate<int LoadMode, typename PacketType>\n\t\t\tEIGEN_STRONG_INLINE\n\t\t\t\tPacketType packet(Index row, Index col) const\n\t\t\t{\n\t\t\t\treturn m_functor.packetOp<PacketType>(m_argImpl.template packet<LoadMode, typename to_int_packet<PacketType>::type>(row, col));\n\t\t\t}\n\n\t\t\ttemplate<int LoadMode, typename PacketType>\n\t\t\tEIGEN_STRONG_INLINE\n\t\t\t\tPacketType packet(Index index) const\n\t\t\t{\n\t\t\t\treturn m_functor.packetOp<PacketType>(m_argImpl.template packet<LoadMode, typename to_int_packet<PacketType>::type>(index));\n\t\t\t}\n\n\t\tprotected:\n\t\t\tconst scalar_cast_op<int32_t, float> m_functor;\n\t\t\tevaluator<ArgType> m_argImpl;\n\t\t};\n\n\t\tstruct scalar_bool2float\n\t\t{\n\t\t\tEIGEN_EMPTY_STRUCT_CTOR(scalar_bool2float)\n\t\t\ttypedef float result_type;\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const float operator() (const int32_t& a) const { return a ? 1.f : 0.f; }\n\n\t\t\ttemplate<typename Packet>\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename to_float_packet<Packet>::type packetOp(const Packet& a) const\n\t\t\t{\n\t\t\t\treturn p_bool2float(a);\n\t\t\t}\n\t\t};\n\n\t\ttemplate<>\n\t\tstruct functor_traits<scalar_bool2float>\n\t\t{\n\t\t\tenum { Cost = NumTraits<float>::AddCost, PacketAccess = 1 };\n\t\t};\n\n\t\ttemplate<typename ArgType>\n\t\tstruct unary_evaluator<CwiseUnaryOp<scalar_bool2float, ArgType>, IndexBased >\n\t\t\t: evaluator_base<CwiseUnaryOp<scalar_bool2float, ArgType> >\n\t\t{\n\t\t\ttypedef CwiseUnaryOp<scalar_bool2float, ArgType> XprType;\n\n\t\t\tenum {\n\t\t\t\tCoeffReadCost = evaluator<ArgType>::CoeffReadCost + functor_traits<scalar_bool2float>::Cost,\n\n\t\t\t\tFlags = evaluator<ArgType>::Flags\n\t\t\t\t& (HereditaryBits | LinearAccessBit | (functor_traits<scalar_bool2float>::PacketAccess ? PacketAccessBit : 0)),\n\t\t\t\tAlignment = evaluator<ArgType>::Alignment\n\t\t\t};\n\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n\t\t\t\texplicit unary_evaluator(const XprType& op)\n\t\t\t\t: m_functor(op.functor()),\n\t\t\t\tm_argImpl(op.nestedExpression())\n\t\t\t{\n\t\t\t\tEIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<float>::AddCost);\n\t\t\t\tEIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);\n\t\t\t}\n\n\t\t\ttypedef typename XprType::CoeffReturnType CoeffReturnType;\n\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n\t\t\t\tCoeffReturnType coeff(Index row, Index col) const\n\t\t\t{\n\t\t\t\treturn m_functor(m_argImpl.coeff(row, col));\n\t\t\t}\n\n\t\t\tEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE\n\t\t\t\tCoeffReturnType coeff(Index index) const\n\t\t\t{\n\t\t\t\treturn m_functor(m_argImpl.coeff(index));\n\t\t\t}\n\n\t\t\ttemplate<int LoadMode, typename PacketType>\n\t\t\tEIGEN_STRONG_INLINE\n\t\t\t\tPacketType packet(Index row, Index col) const\n\t\t\t{\n\t\t\t\treturn m_functor.packetOp(m_argImpl.template packet<LoadMode, typename to_int_packet<PacketType>::type>(row, col));\n\t\t\t}\n\n\t\t\ttemplate<int LoadMode, typename PacketType>\n\t\t\tEIGEN_STRONG_INLINE\n\t\t\t\tPacketType packet(Index index) const\n\t\t\t{\n\t\t\t\treturn m_functor.packetOp(m_argImpl.template packet<LoadMode, typename to_int_packet<PacketType>::type>(index));\n\t\t\t}\n\n\t\tprotected:\n\t\t\tconst scalar_bool2float m_functor;\n\t\t\tevaluator<ArgType> m_argImpl;\n\t\t};\n\n\t}\n\n\ttemplate <typename Derived, typename T> EIGEN_DEVICE_FUNC inline \n\t\tconst CwiseBinaryOp<internal::scalar_lgamma_subt_op< typename internal::traits<Derived>::Scalar, T >, const Derived,\n\t\tconst typename internal::plain_constant_type<Derived, T>::type>\n\t\tlgamma_subt(const Eigen::ArrayBase<Derived>& x, const T& scalar)  {\n\t\t\n\t\treturn CwiseBinaryOp<internal::scalar_lgamma_subt_op< typename internal::traits<Derived>::Scalar, T >, const Derived,\n\t\t\tconst typename internal::plain_constant_type<Derived, T>::type>(x.derived(), \n\t\t\t\ttypename internal::plain_constant_type<Derived, T>::type(x.derived().rows(), x.derived().cols(), internal::scalar_constant_op<T>(scalar))\n\t\t\t);\n\t}\n\n\ttemplate<typename Derived, typename Derived2>\n\tinline const CwiseBinaryOp<internal::scalar_lgamma_subt_op<typename Derived::Scalar, typename Derived2::Scalar>, const Derived, const Derived2>\n\t\tlgamma_subt(const Eigen::ArrayBase<Derived>& x, const Eigen::ArrayBase<Derived2>& y)\n\t{\n\t\treturn CwiseBinaryOp<internal::scalar_lgamma_subt_op<typename Derived::Scalar, typename Derived2::Scalar>, const Derived, const Derived2>(\n\t\t\tx.derived(),\n\t\t\ty.derived()\n\t\t);\n\t}\n\n\n\ttemplate<typename Derived>\n\tinline const CwiseUnaryOp<internal::scalar_bool2float, const Derived>\n\t\tbool2float(const Eigen::ArrayBase<Derived>& x)\n\t{\n\t\treturn CwiseUnaryOp<internal::scalar_bool2float, const Derived>(\n\t\t\tx.derived()\n\t\t);\n\t}\n}\n", "meta": {"hexsha": "fe7ca59d6329088ee1d013fc04c9cbcdf18c4e0f", "size": 8530, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/EigenAddonOps.hpp", "max_stars_repo_name": "jonaschn/tomotopy", "max_stars_repo_head_hexsha": "e37878ac3531a13e29317912298bf4b5f457521b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 393.0, "max_stars_repo_stars_event_min_datetime": "2019-05-11T16:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:54:28.000Z", "max_issues_repo_path": "src/Utils/EigenAddonOps.hpp", "max_issues_repo_name": "jonaschn/tomotopy", "max_issues_repo_head_hexsha": "e37878ac3531a13e29317912298bf4b5f457521b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:08:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T11:58:01.000Z", "max_forks_repo_path": "src/Utils/EigenAddonOps.hpp", "max_forks_repo_name": "jonaschn/tomotopy", "max_forks_repo_head_hexsha": "e37878ac3531a13e29317912298bf4b5f457521b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2019-06-05T09:04:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T18:04:20.000Z", "avg_line_length": 28.3388704319, "max_line_length": 149, "alphanum_fraction": 0.7429073857, "num_tokens": 2426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.03161876829522817, "lm_q1q2_score": 0.01347976411493743}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n// __END_LICENSE__\n\n\n#include <boost/algorithm/string.hpp>\n#include <vw/Cartography/Datum.h>\n#include <vw/Math/Functions.h>\n#include <ogr_spatialref.h>\n#include <cpl_string.h>\n\nvw::cartography::Datum::Datum(std::string const& name,\n                              std::string const& spheroid_name,\n                              std::string const& meridian_name,\n                              double semi_major_axis,\n                              double semi_minor_axis,\n                              double meridian_offset)\n  : m_name(name),\n    m_spheroid_name(spheroid_name),\n    m_meridian_name(meridian_name),\n    m_semi_major_axis(semi_major_axis),\n    m_semi_minor_axis(semi_minor_axis),\n    m_meridian_offset(meridian_offset),\n    m_geocentric(false)\n{\n  std::ostringstream strm;\n  strm << \"+a=\" << semi_major_axis << \" +b=\" << semi_minor_axis;\n  m_proj_str = strm.str();\n}\n\n\n// A wrapper around the GDAL/OGR API for setting the datum. Works for Earth datums.\nvoid vw::cartography::Datum::set_datum_from_spatial_ref(OGRSpatialReference const& gdal_spatial_ref) {\n\n  const char* datum_name = gdal_spatial_ref.GetAttrValue(\"DATUM\");\n  if (datum_name)\n    this->name() = datum_name;\n\n  const char* spheroid_name = gdal_spatial_ref.GetAttrValue(\"SPHEROID\");\n  if (spheroid_name)\n    this->spheroid_name() = spheroid_name;\n\n  const char* meridian_name = gdal_spatial_ref.GetAttrValue(\"PRIMEM\");\n  if (meridian_name)\n    this->meridian_name() = meridian_name;\n\n  OGRErr e1, e2;\n  double semi_major = gdal_spatial_ref.GetSemiMajor(&e1);\n  double semi_minor = gdal_spatial_ref.GetSemiMinor(&e2);\n  if (e1 != OGRERR_FAILURE && e2 != OGRERR_FAILURE) {\n    this->set_semi_major_axis(semi_major);\n    this->set_semi_minor_axis(semi_minor);\n  }\n  this->meridian_offset() = gdal_spatial_ref.GetPrimeMeridian();\n\n  char* proj4_str_tmp;\n  gdal_spatial_ref.exportToProj4(&proj4_str_tmp);\n\n  this->proj4_str() = proj4_str_tmp;\n  CPLFree( proj4_str_tmp );\n}\n\n// A wrapper around the GDAL/OGR API for setting the datum. Works for Earth datums.\nvoid vw::cartography::Datum::set_datum_from_proj_str( std::string const& proj_str ) {\n\n  OGRSpatialReference gdal_spatial_ref;\n  if (gdal_spatial_ref.importFromProj4( proj_str.c_str() ))\n    vw_throw( ArgumentErr() << \"Failed to parse: \\\"\" << proj_str << \"\\\".\" );\n\n  set_datum_from_spatial_ref(gdal_spatial_ref);\n  this->proj4_str() = proj_str; // The other call can change the string, don't let it!\n}\n\nvoid vw::cartography::Datum::set_well_known_datum( std::string const& name ) {\n  m_meridian_name   = \"Greenwich\";\n  m_geocentric      = false;\n  m_meridian_offset = 0.0;\n\n  // These numbers will be over-written later. However, we must\n  // still initialize them, otherwise when the set_semi_major_axis()\n  // function is invoked later it will result in un-initialized\n  // variables (since that function sets the semi-major axis but\n  // assumes the semi-minor axis is already set).\n  m_semi_major_axis =  6378137;\n  m_semi_minor_axis = 6356752.3142;\n\n  std::string up_name = boost::to_upper_copy(name);\n\n  if (up_name == \"WGS84\"    || up_name == \"WGS_1984\" ||\n      up_name == \"WGS 1984\" || up_name == \"WGS1984\"   ||\n      up_name == \"WORLD GEODETIC SYSTEM 1984\" || up_name == \"EARTH\") {\n    set_datum_from_proj_str(\"+proj=longlat +datum=WGS84 +no_defs\");\n    return;\n  }\n\n  if (up_name == \"WGS72\" || up_name == \"WGS_1972\") {\n    set_datum_from_proj_str(\"+proj=longlat +ellps=WGS72 +no_defs\");\n    return;\n  }\n\n  if (up_name == \"NAD83\" ||\n      up_name == boost::to_upper_copy(std::string(\"North_American_Datum_1983\"))) {\n    set_datum_from_proj_str(\"+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs\");\n    return;\n  }\n\n  if (up_name == \"NAD27\" ||\n      up_name == boost::to_upper_copy(std::string(\"North_American_Datum_1927\"))) {\n    set_datum_from_proj_str(\"+proj=longlat +datum=NAD27 +no_defs\");\n    return;\n  }\n\n  if (up_name == \"D_MOON\" || up_name == \"MOON\") {\n    m_name            = \"D_MOON\";\n    m_spheroid_name   = \"MOON\";\n    m_meridian_name   = \"Reference Meridian\";\n    m_semi_major_axis = m_semi_minor_axis = 1737400;\n    m_meridian_offset = 0.0;\n    m_proj_str        = \"+a=1737400 +b=1737400\";\n    return;\n  }\n\n  if (up_name == \"D_MARS\" || up_name == \"MARS\") {\n    m_name            = \"D_MARS\";\n    m_spheroid_name   = \"MARS\";\n    m_meridian_name   = \"Reference Meridian\";\n    m_semi_major_axis = m_semi_minor_axis = 3396190;\n    m_meridian_offset = 0.0;\n    m_proj_str        = \"+a=3396190 +b=3396190\";\n    return;\n  }\n\n  if (up_name == \"MOLA\") {\n    m_name            = \"D_MARS\";\n    m_spheroid_name   = \"MARS\";\n    m_meridian_name   = \"Reference Meridian\";\n    m_semi_major_axis = m_semi_minor_axis = 3396000;\n    m_meridian_offset = 0.0;\n    m_proj_str        = \"+a=3396000 +b=3396000\";\n    return;\n  }\n\n  vw::vw_throw( vw::InputErr() << \"Unknown datum: \" << name << \".\");\n}\n\nvoid vw::cartography::Datum::set_semi_major_axis(double val) {\n  m_semi_major_axis = val;\n  std::ostringstream strm;\n  strm << \"+a=\" << m_semi_major_axis << \" +b=\" << m_semi_minor_axis;\n  if (m_geocentric)\n    strm << \" +geoc\";\n  m_proj_str = strm.str();\n}\n\nvoid vw::cartography::Datum::set_semi_minor_axis(double val) {\n  m_semi_minor_axis = val;\n  std::ostringstream strm;\n  strm << \"+a=\" << m_semi_major_axis << \" +b=\" << m_semi_minor_axis;\n  if (m_geocentric)\n    strm << \" +geoc\";\n  m_proj_str = strm.str();\n}\n\n// return meridian radius of curvature.  NOT geocentric radius\ndouble vw::cartography::Datum::radius(double /*lon*/, double lat) const {\n  // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis;\n  }\n\n  // Bi-axial ellpisoid datum\n  double a = m_semi_major_axis;\n  double b = m_semi_minor_axis;\n  double t = atan((a/b) * tan(lat * M_PI / 180.0));\n  double x = a * cos(t);\n  double y = b * sin(t);\n  return sqrt(x*x + y*y);\n}\n\ndouble vw::cartography::Datum::geocentric_latitude(double lat) const {\n   // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis;\n  }\n\n  // Bi-axial ellpisoid datum\n  // http://mathworld.wolfram.com/GeocentricLatitude.html\n  double a  = m_semi_major_axis;\n  double b  = m_semi_minor_axis;\n  double a2 = a * a;\n  double b2 = b * b;\n  double e2 = (a2 - b2) / a2;\n  return atan((1-e2)*tan(lat * M_PI / 180.0));\n\n}\n\ndouble vw::cartography::Datum::radius_of_curvature(double /*lon*/, double lat) const {\n  // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis;\n  }\n\n  // Bi-axial Ellpisoid datum\n  double a    = m_semi_major_axis;\n  double b    = m_semi_minor_axis;\n  double a2   = a * a;\n  double b2   = b * b;\n  double e2   = (a2 - b2) / a2;\n  double slat = sin(M_PI/180*lat);\n  return a / sqrt(1.0 - e2*slat*slat);\n}\n\n// return meridian radius of curvature.  NOT geocentric radius\ndouble vw::cartography::Datum::geocentric_radius(double /*lon*/, double lat, double alt) const {\n  // Optimize in the case of spherical datum\n  if (m_semi_major_axis == m_semi_minor_axis) {\n    return m_semi_major_axis + alt;\n  }\n  double a    = m_semi_major_axis;\n  double b    = m_semi_minor_axis;\n  double a2   = a * a;\n  double b2   = b * b;\n  double e2   = (a2 - b2) / a2;\n  double rlat = lat * (M_PI/180);\n  double slat = sin( rlat );\n  double clat = cos( rlat );\n  double Rn   = a / sqrt(1.0-e2*slat*slat) + alt;\n\n  return sqrt(Rn*Rn*(clat*clat + (1-e2)*(1-e2)*slat*slat));\n}\n\ndouble vw::cartography::Datum::inverse_flattening() const {\n  return 1.0 / (1.0 - m_semi_minor_axis / m_semi_major_axis);\n}\n\nvw::Matrix3x3 vw::cartography::Datum::lonlat_to_ned_matrix( vw::Vector2 const& lonlat) const {\n  double lon = lonlat.x();\n  double lat = lonlat.y();\n  if ( lat < -90 ) lat = -90;\n  if ( lat >  90 ) lat =  90;\n\n  double rlon = (lon + m_meridian_offset) * (M_PI/180);\n  double rlat = lat * (M_PI/180);\n  double slat = sin( rlat );\n  double clat = cos( rlat );\n  double slon = sin( rlon );\n  double clon = cos( rlon );\n\n  Matrix3x3 R;\n\n  R(0,0) = -slat*clon;\n  R(1,0) = -slat*slon;\n  R(2,0) = clat;\n  R(0,1) = -slon;\n  R(1,1) = clon;\n  R(2,1) = 0.0;\n  R(0,2) = -clon*clat;\n  R(1,2) = -slon*clat;\n  R(2,2) = -slat;\n\n  return R;\n}\n\nvw::Vector3 vw::cartography::Datum::geodetic_to_cartesian( vw::Vector3 const& llh ) const {\n  double a  = m_semi_major_axis;\n  double b  = m_semi_minor_axis;\n  double a2 = a * a;\n  double b2 = b * b;\n  double e2 = (a2 - b2) / a2;\n\n  double lat = llh.y();\n  if ( lat < -90 ) lat = -90;\n  if ( lat >  90 ) lat = 90;\n\n  double rlon = (llh.x() + m_meridian_offset) * (M_PI/180);\n  double rlat = lat * (M_PI/180);\n  double slat = sin( rlat );\n  double clat = cos( rlat );\n  double slon = sin( rlon );\n  double clon = cos( rlon );\n  double radius = a / sqrt(1.0-e2*slat*slat);\n\n  return Vector3( (radius+llh.z()) * clat * clon,\n                  (radius+llh.z()) * clat * slon,\n                  (radius*(1-e2)+llh.z()) * slat );\n}\n\n// This algorithm is a non-iterative algorithm from \"An analytical\n// method to transform geocentric into geodetic coordinates\" by Hugues\n// Vermeille, Journal of Geodesy 2011.\n//\n// This is an improvement over the 1988/Proj4's implementation as it's\n// a smidgen faster and it still works near the center of the datum.\nvw::Vector3 vw::cartography::Datum::cartesian_to_geodetic( vw::Vector3 const& xyz ) const {\n  const double a2 = m_semi_major_axis * m_semi_major_axis;\n  const double b2 = m_semi_minor_axis * m_semi_minor_axis;\n  const double e2 = 1 - b2 / a2;\n  const double e4 = e2 * e2;\n\n  double xy_dist = sqrt( xyz[0] * xyz[0] + xyz[1] * xyz[1] );\n  double p  = ( xyz[0] * xyz[0] + xyz[1] * xyz[1] ) / a2;\n  double q  = ( 1 - e2 ) * xyz[2] * xyz[2] / a2;\n  double r  = ( p + q - e4 ) / 6.0;\n  double r3 = r * r * r;\n\n  Vector3 llh;\n\n  double evolute = 8 * r3 + e4 * p * q;\n  double u = std::numeric_limits<double>::quiet_NaN();\n  if ( evolute > 0 ) {\n    // outside the evolute\n    double right_inside_pow = sqrt(e4 * p * q);\n    double sqrt_evolute = sqrt( evolute );\n    u = r + 0.5 * pow(sqrt_evolute + right_inside_pow, 2.0/3.0)\n          + 0.5 * pow(sqrt_evolute - right_inside_pow, 2.0/3.0);\n  } else if ( fabs(xyz[2]) < std::numeric_limits<double>::epsilon() ) {\n    // On the equator plane\n    llh[1] = 0;\n    llh[2] = norm_2( xyz ) - m_semi_major_axis;\n  } else if ( evolute < 0 and fabs(q) > std::numeric_limits<double>::epsilon() ) {\n    // On or inside the evolute\n    double atan_result = atan2( sqrt( e4 * p * q ), sqrt( -evolute ) + sqrt(-8 * r3) );\n    u = -4 * r * sin( 2.0 / 3.0 * atan_result )\n               * cos( M_PI / 6.0 + 2.0 / 3.0 * atan_result );\n  } else if ( fabs(q) < std::numeric_limits<double>::epsilon() and p <= e4 ) {\n    // In the singular disc\n    llh[2] = -m_semi_major_axis * sqrt(1 - e2) * sqrt(e2 - p) / sqrt(e2);\n    llh[1] = 2 * atan2( sqrt(e4 - p), sqrt(e2*(e2 - p)) + sqrt(1-e2) * sqrt(p) );\n  } else {\n    // Near the cusps of the evolute\n    double inside_pow = sqrt(evolute) + sqrt(e4 * p * q);\n    u = r + 0.5   * pow(inside_pow, 2.0/3.0)\n          + 2*r*r * pow(inside_pow,-2.0/3.0);\n  }\n\n  if (!std::isnan(u) ) {\n    double v   = sqrt( u * u + e4 * q );\n    double u_v = u + v;\n    double w   = e2 * ( u_v - q ) / ( 2 * v );\n    double k   = u_v / ( w + sqrt( w * w + u_v ) );\n    double D   = k * xy_dist / ( k + e2 );\n    double dist_2 = D * D + xyz[2] * xyz[2];\n    llh[2] = ( k + e2 - 1 ) * sqrt( dist_2 ) / k;\n    llh[1] = 2 * atan2( xyz[2], sqrt( dist_2 ) + D );\n  }\n\n  if ( xy_dist + xyz[0] > ( sqrt(2) - 1 ) * xyz[1] ) {\n    // Longitude is between -135 and 135\n    llh[0] = 360.0 * atan2( xyz[1], xy_dist + xyz[0] ) / M_PI;\n  } else if ( xy_dist + xyz[1] < ( sqrt(2) + 1 ) * xyz[0] ) {\n    // Longitude is between -225 and 45\n    llh[0] = - 90.0 + 360.0 * atan2( xyz[0], xy_dist - xyz[1] ) / M_PI;\n  } else {\n    // Longitude is between -45 and 225\n    llh[0] = 90.0 - 360.0 * atan2( xyz[0], xy_dist + xyz[1] ) / M_PI;\n  }\n  llh[0] -= m_meridian_offset;\n  llh[1] *= 180.0 / M_PI;\n\n  return llh;\n}\n\nstd::ostream& vw::cartography::operator<<( std::ostream& os, vw::cartography::Datum const& datum ) {\n  std::ostringstream oss; // To use custom precision\n  oss.precision(17);\n  oss << \"Geodetic Datum --> Name: \" << datum.name() << \"  Spheroid: \" << datum.spheroid_name()\n      << \"  Semi-major axis: \" << datum.semi_major_axis()\n      << \"  Semi-minor axis: \" << datum.semi_minor_axis()\n      << \"  Meridian: \"   << datum.meridian_name() << \" at \" << datum.meridian_offset()\n      << \"  Proj4 Str: \"  << datum.proj4_str();\n  os << oss.str();\n  return os;\n}\n\n// Free associated functions\n\nvw::Vector3\nvw::cartography::datum_intersection(double semi_major_axis, double semi_minor_axis,\n                                    vw::Vector3 camera_ctr, vw::Vector3 camera_vec) {\n\n  // The datum is a spheroid. To simplify the calculations, scale\n  // everything in such a way that the spheroid becomes a\n  // sphere. Scale back at the end of computation.\n\n  double z_scale = semi_major_axis / semi_minor_axis;\n  camera_ctr.z() *= z_scale;\n  camera_vec.z() *= z_scale;\n  camera_vec = normalize(camera_vec);\n  double radius_2 = semi_major_axis * semi_major_axis;\n  double alpha = -dot_prod(camera_ctr, camera_vec );\n  vw::Vector3 projection = camera_ctr + alpha*camera_vec;\n  if ( norm_2_sqr(projection) > radius_2 ) {\n    // did not intersect\n    return vw::Vector3();\n  }\n\n  alpha -= sqrt( radius_2 -\n                 norm_2_sqr(projection) );\n  vw::Vector3 intersection = camera_ctr + alpha * camera_vec;\n  intersection.z() /= z_scale;\n  return intersection;\n}\n\n// Intersect the ray back-projected from the camera with the datum.\nvw::Vector3\nvw::cartography::datum_intersection( vw::cartography::Datum const& datum,\n                                     vw::Vector3 camera_ctr, vw::Vector3 camera_vec) {\n  return vw::cartography::datum_intersection(datum.semi_major_axis(), datum.semi_minor_axis(),\n                                             camera_ctr, camera_vec);\n}\n", "meta": {"hexsha": "1ea34c3fae46e161dd76058a39830e87168ab50d", "size": 14718, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Cartography/Datum.cc", "max_stars_repo_name": "maxerbubba/visionworkbench", "max_stars_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 318.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T16:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T07:12:20.000Z", "max_issues_repo_path": "src/vw/Cartography/Datum.cc", "max_issues_repo_name": "maxerbubba/visionworkbench", "max_issues_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-07-30T22:22:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T16:11:55.000Z", "max_forks_repo_path": "src/vw/Cartography/Datum.cc", "max_forks_repo_name": "maxerbubba/visionworkbench", "max_forks_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T00:57:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T13:51:40.000Z", "avg_line_length": 34.7122641509, "max_line_length": 102, "alphanum_fraction": 0.6364995244, "num_tokens": 4747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.03676946805470429, "lm_q1q2_score": 0.013479310107780595}}
{"text": "// Copyright (c) 2015-2021 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef variational_bayes_mixture_model_hpp\n#define variational_bayes_mixture_model_hpp\n\n#include <array>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <iterator>\n#include <cstddef>\n#include <utility>\n#include <cassert>\n#include <limits>\n#include <type_traits>\n\n#include <boost/optional.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"core/models/haplotype_likelihood_array.hpp\"\n#include \"utils/maths.hpp\"\n#include \"utils/memory_footprint.hpp\"\n#include \"utils/parallel_transform.hpp\"\n\n\n/**\n *\n * This file contains an implementation of the Variational Bayes mixture model\n * used by some genotype models. The notation follows the documentation.\n *\n */\n\nnamespace octopus { namespace model {\n\n// Types needed for Variational Bayes model\n\nstruct VariationalBayesParameters\n{\n    double epsilon = 0.05;\n    unsigned max_iterations = 1000;\n    bool save_memory = false;\n    bool parallel_execution = false;\n};\n\nusing ProbabilityVector    = std::vector<double>;\nusing LogProbabilityVector = std::vector<double>;\n\ntemplate <std::size_t K>\nusing VBAlpha = std::array<float, K>;\ntemplate <std::size_t K>\nusing VBAlphaVector = std::vector<VBAlpha<K>>;\n\nclass VBReadLikelihoodArray\n{\npublic:\n    using BaseType = HaplotypeLikelihoodArray::LikelihoodVector;\n    \n    VBReadLikelihoodArray() = default;\n    \n    explicit VBReadLikelihoodArray(const BaseType&);\n    \n    VBReadLikelihoodArray(const VBReadLikelihoodArray&)            = default;\n    VBReadLikelihoodArray& operator=(const VBReadLikelihoodArray&) = default;\n    VBReadLikelihoodArray(VBReadLikelihoodArray&&)                 = default;\n    VBReadLikelihoodArray& operator=(VBReadLikelihoodArray&&)      = default;\n    \n    ~VBReadLikelihoodArray() = default;\n    \n    void operator=(const BaseType&);\n    void operator=(std::reference_wrapper<const BaseType>);\n    std::size_t size() const noexcept;\n    BaseType::const_iterator begin() const noexcept;\n    BaseType::const_iterator end() const noexcept;\n    BaseType::value_type operator[](const std::size_t n) const noexcept;\n\nprivate:\n    const BaseType* likelihoods;\n};\n\ntemplate <std::size_t K>\nusing VBGenotype = std::array<VBReadLikelihoodArray, K>; // One element per haplotype in genotype (i.e. K)\ntemplate <std::size_t K>\nusing VBGenotypeVector = std::vector<VBGenotype<K>>; // Per element per genotype\ntemplate <std::size_t K>\nusing VBReadLikelihoodMatrix = std::vector<VBGenotypeVector<K>>; // One element per sample\n\nusing VBTau = std::vector<VBReadLikelihoodArray::BaseType::value_type>; // One element per read\ntemplate <std::size_t K>\nusing VBResponsibilityVector = std::array<VBTau, K>; // One element per haplotype in genotype (i.e. K)\ntemplate <std::size_t K>\nusing VBResponsibilityMatrix = std::vector<VBResponsibilityVector<K>>; // One element per sample\n\ntemplate <std::size_t K>\nstruct VBLatents\n{\n    ProbabilityVector genotype_posteriors;\n    LogProbabilityVector genotype_log_posteriors;\n    VBAlphaVector<K> alphas;\n    VBResponsibilityMatrix<K> responsibilities;\n};\n\n// Main VB method\n\nnamespace detail {\n\nusing VBExpandedLikelihood = std::vector<float>; // One element per genotype\nusing VBExpandedGenotype = std::vector<VBExpandedLikelihood>; // One element per read\ntemplate <std::size_t K>\nusing VBExpandedGenotypeVector = std::array<VBExpandedGenotype, K>; // One element per haplotype in genotype\ntemplate <std::size_t K>\nusing VBExpandedLikelihoodMatrix = std::vector<VBExpandedGenotypeVector<K>>; // One element per sample\n\ntemplate <std::size_t K>\nauto invert(const VBGenotypeVector<K>& likelihoods)\n{\n    static_assert(K > 0, \"K == 0\");\n    const auto num_genotypes = likelihoods.size();\n    assert(num_genotypes > 0);\n    const auto num_reads = likelihoods.front().front().size();\n    VBExpandedGenotypeVector<K> result {};\n    for (std::size_t k {0}; k < K; ++k) {\n        result[k] = VBExpandedGenotype(num_reads, VBExpandedLikelihood(num_genotypes));\n        for (std::size_t n {0}; n < num_reads; ++n) {\n            for (std::size_t g {0}; g < num_genotypes; ++g) {\n                result[k][n][g] = likelihoods[g][k][n];\n            }\n        }\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto invert(const VBReadLikelihoodMatrix<K>& matrix)\n{\n    VBExpandedLikelihoodMatrix<K> result {};\n    result.reserve(matrix.size());\n    std::transform(std::cbegin(matrix), std::cend(matrix), std::back_inserter(result),\n                   [] (const auto& v) { return invert(v); });\n    return result;\n}\n\ninline ProbabilityVector& exp(const LogProbabilityVector& log_probabilities, ProbabilityVector& result) noexcept\n{\n    std::transform(std::cbegin(log_probabilities), std::cend(log_probabilities), std::begin(result),\n                   [] (const auto lp) noexcept { return std::exp(lp); });\n    return result;\n}\n\ninline ProbabilityVector exp(const LogProbabilityVector& log_probabilities)\n{\n    ProbabilityVector result(log_probabilities.size());\n    return exp(log_probabilities, result);\n}\n\ninline auto sum(const VBAlpha<2>& alpha) noexcept\n{\n    return alpha[0] + alpha[1];\n}\n\ninline auto sum(const VBAlpha<3>& alpha) noexcept\n{\n    return alpha[0] + alpha[1] + alpha[2];\n}\n\ntemplate <std::size_t K>\nauto sum(const VBAlpha<K>& alpha) noexcept\n{\n    using T = typename VBAlpha<K>::value_type;\n    return std::accumulate(std::cbegin(alpha), std::cend(alpha), T {0});\n}\n\ntemplate <typename T, std::size_t K>\nauto compute_digamma_diffs(const std::array<T, K>& alphas)\n{\n    std::array<T, K> result;\n    using boost::math::digamma;\n    const auto digamma_a0 = digamma(sum(alphas));\n    for (unsigned k {0}; k < K; ++k) {\n        result[k] = digamma(alphas[k]) - digamma_a0;\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto count_reads(const VBGenotypeVector<K>& likelihoods) noexcept\n{\n    return likelihoods[0][0].size();\n}\n\ntemplate <std::size_t K>\nauto count_reads(const VBExpandedGenotypeVector<K>& likelihoods) noexcept\n{\n    return likelihoods[0].size();\n}\n\ntemplate <typename ProbabilityVector_, std::size_t K>\nauto marginalise(const ProbabilityVector_& distribution, const VBGenotypeVector<K>& likelihoods,\n                 const unsigned k, const std::size_t n) noexcept\n{\n    using T = typename ProbabilityVector_::value_type;\n    return std::inner_product(std::cbegin(distribution), std::cend(distribution),\n                              std::cbegin(likelihoods), T {0}, std::plus<> {},\n                              [k, n] (const auto p, const auto& haplotype_likelihoods) noexcept {\n                                  return p * haplotype_likelihoods[k][n];\n                              });\n}\n\ntemplate <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 ProbabilityVector_, std::size_t K>\nauto marginalise(const ProbabilityVector_& distribution, const VBExpandedGenotypeVector<K>& likelihoods,\n                 const unsigned k, const std::size_t n) noexcept\n{\n    return inner_product(distribution, likelihoods[k][n]);\n}\n\ntemplate <std::size_t K, typename T, typename ProbabilityVector_, typename VBLikelihoodGenotypeVector>\nvoid\nupdate_responsibilities_helper(VBResponsibilityVector<K>& result,\n                               const std::array<T, K>& al,\n                               const ProbabilityVector_& genotype_probabilities,\n                               const VBLikelihoodGenotypeVector& read_likelihoods,\n                               std::true_type)\n{\n    const auto N = count_reads(read_likelihoods);\n    std::array<T, K> ln_rho;\n    for (std::size_t n {0}; n < N; ++n) {\n        for (unsigned k {0}; k < K; ++k) {\n            ln_rho[k] = al[k] + marginalise(genotype_probabilities, read_likelihoods, k, n);\n        }\n        const auto ln_rho_norm = maths::fast_log_sum_exp(ln_rho);\n        for (unsigned k {0}; k < K; ++k) {\n            result[k][n] = maths::fast_exp(ln_rho[k] - ln_rho_norm);\n        }\n    }\n}\n\ntemplate <std::size_t K, typename T, typename ProbabilityVector_>\nvoid\nupdate_responsibilities_helper(VBResponsibilityVector<K>& result,\n                               const std::array<T, K>& al,\n                               const ProbabilityVector_& genotype_probabilities,\n                               const VBExpandedGenotypeVector<K>& read_likelihoods,\n                               std::false_type)\n{\n    using LikelihoodType = VBExpandedLikelihood::value_type;\n    const std::vector<LikelihoodType> demoted_genotype_probabilities {std::cbegin(genotype_probabilities), std::cend(genotype_probabilities)};\n    update_responsibilities_helper(result, al, demoted_genotype_probabilities, read_likelihoods, std::true_type {});\n}\n\ntemplate <std::size_t K, typename T, typename ProbabilityVector_>\nvoid\nupdate_responsibilities_helper(VBResponsibilityVector<K>& result,\n                               const std::array<T, K>& al,\n                               const ProbabilityVector_& genotype_probabilities,\n                               const VBExpandedGenotypeVector<K>& read_likelihoods)\n{\n    // For the expanded likelihood array, the inner product between likelihoods and genotype\n    // posteriors - a key bottleneck in the responsibility update calculate - can be vectorised.\n    // To ensure optimal execution the floating point types of the genotype probabilities and likelihoods should match.\n    using ProbabilityType = typename ProbabilityVector_::value_type;\n    using LikelihoodType = VBExpandedLikelihood::value_type;\n    update_responsibilities_helper(result, al, genotype_probabilities, read_likelihoods,\n                                   std::is_same<ProbabilityType, LikelihoodType> {});\n}\n\ntemplate <std::size_t K, typename T, typename VBLikelihoodGenotypeVector, typename ProbabilityVector_>\nvoid\nupdate_responsibilities_helper(VBResponsibilityVector<K>& result,\n                               const std::array<T, K>& al,\n                               const ProbabilityVector_& genotype_probabilities,\n                               const VBLikelihoodGenotypeVector& read_likelihoods)\n{\n    update_responsibilities_helper(result, al, genotype_probabilities, read_likelihoods, std::true_type {});\n}\n\ntemplate <std::size_t K, typename VBLikelihoodGenotypeVector>\nvoid update_responsibilities(VBResponsibilityVector<K>& result,\n                             const VBAlpha<K>& posterior_alphas,\n                             const ProbabilityVector& genotype_probabilities,\n                             const VBLikelihoodGenotypeVector& read_likelihoods)\n{\n    const auto al = compute_digamma_diffs(posterior_alphas);\n    update_responsibilities_helper(result, al, genotype_probabilities, read_likelihoods);\n}\n\ntemplate <std::size_t K, typename VBLikelihoodMatrix>\nvoid update_responsibilities(VBResponsibilityMatrix<K>& result,\n                             const VBAlphaVector<K>& posterior_alphas,\n                             const ProbabilityVector& genotype_probabilities,\n                             const VBLikelihoodMatrix& read_likelihoods)\n{\n    const auto S = read_likelihoods.size();\n    for (std::size_t s {0}; s < S; ++s) {\n        update_responsibilities(result[s], posterior_alphas[s], genotype_probabilities, read_likelihoods[s]);\n    }\n}\n\ntemplate <std::size_t K, typename VBLikelihoodVector_>\nVBResponsibilityVector<K>\ninit_responsibilities(const VBAlpha<K>& prior_alphas,\n                      const ProbabilityVector& genotype_probabilities,\n                      const VBLikelihoodVector_& read_likelihoods)\n{\n    const auto N = count_reads(read_likelihoods);\n    VBResponsibilityVector<K> result {};\n    for (auto& tau : result) tau.resize(N);\n    update_responsibilities(result, prior_alphas, genotype_probabilities, read_likelihoods);\n    return result;\n}\n\ntemplate <std::size_t K, typename VBLikelihoodMatrix>\nVBResponsibilityMatrix<K>\ninit_responsibilities(const VBAlphaVector<K>& prior_alphas,\n                      const ProbabilityVector& genotype_probabilities,\n                      const VBLikelihoodMatrix& read_likelihoods)\n{\n    const auto S = read_likelihoods.size(); // num samples\n    VBResponsibilityMatrix<K> result {};\n    result.reserve(S);\n    for (std::size_t s {0}; s < S; ++s) {\n        result.push_back(init_responsibilities(prior_alphas[s], genotype_probabilities, read_likelihoods[s]));\n    }\n    return result;\n}\n\ntemplate <typename T>\ninline auto sum(const std::vector<T>& values) noexcept\n{\n    return std::accumulate(std::cbegin(values), std::cend(values), T {});\n}\n\ntemplate <std::size_t K>\nvoid update_alpha(VBAlpha<K>& alpha, const VBAlpha<K>& prior_alpha,\n                  const VBResponsibilityVector<K>& taus) noexcept\n{\n    for (unsigned k {0}; k < K; ++k) {\n        alpha[k] = prior_alpha[k] + sum(taus[k]);\n    }\n}\n\ntemplate <std::size_t K>\nvoid update_alphas(VBAlphaVector<K>& alphas, const VBAlphaVector<K>& prior_alphas,\n                   const VBResponsibilityMatrix<K>& responsibilities) noexcept\n{\n    const auto S = alphas.size();\n    assert(S == prior_alphas.size() && S == responsibilities.size());\n    for (std::size_t s {0}; s < S; ++s) {\n        update_alpha(alphas[s], prior_alphas[s], responsibilities[s]);\n    }\n}\n\ninline auto marginalise(const VBTau& responsibilities, const VBReadLikelihoodArray& likelihoods) noexcept\n{\n    assert(responsibilities.size() == likelihoods.size()); // num reads\n    return inner_product(responsibilities, likelihoods);\n}\n\ntemplate <std::size_t K>\nauto marginalise(const VBResponsibilityVector<K>& responsibilities,\n                 const VBGenotype<K>& read_likelihoods) noexcept\n{\n    double result {0};\n    for (unsigned k {0}; k < K; ++k) {\n        result += marginalise(responsibilities[k], read_likelihoods[k]);\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto marginalise(const VBResponsibilityMatrix<K>& responsibilities,\n                 const VBReadLikelihoodMatrix<K>& read_likelihoods,\n                 const std::size_t g) noexcept\n{\n    double result {0};\n    const auto S = read_likelihoods.size(); // num samples\n    assert(S == responsibilities.size());\n    for (std::size_t s {0}; s < S; ++s) {\n        result += marginalise(responsibilities[s], read_likelihoods[s][g]);\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nvoid update_genotype_log_posteriors(LogProbabilityVector& result,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const VBResponsibilityMatrix<K>& responsibilities,\n                                    const VBReadLikelihoodMatrix<K>& read_likelihoods)\n{\n    const auto G = result.size();\n    for (std::size_t g {0}; g < G; ++g) {\n        result[g] = genotype_log_priors[g] + marginalise(responsibilities, read_likelihoods, g);\n    }\n    maths::normalise_logs(result);\n}\n\ninline auto entropy(const VBTau& tau) noexcept\n{\n    using T = VBTau::value_type;\n    return -std::accumulate(std::cbegin(tau), std::cend(tau), T {0},\n                            [] (const auto curr, const auto t) noexcept { return curr + (t * std::log(t)); });\n}\n\n// E [ln q(Z_s)]\ntemplate <std::size_t K>\nauto sum_entropies(const VBResponsibilityVector<K>& taus) noexcept\n{\n    using T = VBTau::value_type;\n    return std::accumulate(std::cbegin(taus), std::cend(taus), T {0},\n                           [] (const auto curr, const auto& tau) noexcept { return curr + entropy(tau); });\n}\n\ntemplate <std::size_t K>\nauto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,\n                                    const VBAlphaVector<K>& posterior_alphas,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const ProbabilityVector& genotype_posteriors,\n                                    const LogProbabilityVector& genotype_log_posteriors,\n                                    const VBResponsibilityMatrix<K>& taus,\n                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                    const boost::optional<double> max_posterior_skip = boost::none)\n{\n    const auto G = genotype_log_priors.size();\n    const auto S = log_likelihoods.size();\n    double result {0};\n    for (std::size_t g {0}; g < G; ++g) {\n        if (!max_posterior_skip || genotype_posteriors[g] >= *max_posterior_skip) {\n            auto w = genotype_log_priors[g] - genotype_log_posteriors[g];\n            for (std::size_t s {0}; s < S; ++s) {\n                w += marginalise(taus[s], log_likelihoods[s][g]);\n            }\n            result += genotype_posteriors[g] * w;\n        }\n    }\n    for (std::size_t s {0}; s < S; ++s) {\n        result += (maths::log_beta(posterior_alphas[s]) - maths::log_beta(prior_alphas[s]));\n        result += sum_entropies(taus[s]);\n    }\n    return result;\n}\n\n// Main algorithm - single seed\n\n// Starting iteration with given genotype_log_posteriors\ntemplate <std::size_t K, typename VBLikelihoodMatrix1, typename VBLikelihoodMatrix2>\nVBLatents<K>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBLikelihoodMatrix1& log_likelihoods1,\n                      const VBLikelihoodMatrix2& log_likelihoods2,\n                      LogProbabilityVector genotype_log_posteriors,\n                      const VariationalBayesParameters& params)\n{\n    assert(!prior_alphas.empty());\n    assert(!genotype_log_priors.empty());\n    assert(!log_likelihoods1.empty());\n    assert(log_likelihoods1.size() == log_likelihoods2.size());\n    assert(prior_alphas.size() == log_likelihoods1.size()); // num samples\n    assert(log_likelihoods1.front().size() == genotype_log_priors.size()); // num genotypes\n    assert(params.max_iterations > 0);\n    auto genotype_posteriors = exp(genotype_log_posteriors);\n    auto posterior_alphas = prior_alphas;\n    auto responsibilities = init_responsibilities<K>(posterior_alphas, genotype_posteriors, log_likelihoods2);\n    assert(responsibilities.size() == log_likelihoods1.size()); // num samples\n    auto prev_evidence = std::numeric_limits<double>::lowest();\n    for (unsigned i {0}; i < params.max_iterations; ++i) {\n        update_genotype_log_posteriors(genotype_log_posteriors, genotype_log_priors, responsibilities, log_likelihoods1);\n        exp(genotype_log_posteriors, genotype_posteriors);\n        update_alphas(posterior_alphas, prior_alphas, responsibilities);\n        auto curr_evidence = calculate_evidence_lower_bound(prior_alphas, posterior_alphas, genotype_log_priors,\n                                                            genotype_posteriors, genotype_log_posteriors, responsibilities,\n                                                            log_likelihoods1, 1e-10);\n        if (curr_evidence <= prev_evidence || (curr_evidence - prev_evidence) < params.epsilon) break;\n        prev_evidence = curr_evidence;\n        update_responsibilities(responsibilities, posterior_alphas, genotype_posteriors, log_likelihoods2);\n    }\n    return VBLatents<K> {\n        std::move(genotype_posteriors), std::move(genotype_log_posteriors),\n        std::move(posterior_alphas), std::move(responsibilities)\n    };\n}\n\n// Not using inverted log likelihoods\ntemplate <std::size_t K>\nVBLatents<K>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      LogProbabilityVector genotype_log_posteriors,\n                      const VariationalBayesParameters& params)\n{\n    return run_variational_bayes(prior_alphas, genotype_log_posteriors, log_likelihoods,\n                                 log_likelihoods, genotype_log_posteriors, params);\n}\n\n// Main algorithm - multiple seed\n\ntemplate <std::size_t K>\nbool run_vb_with_matrix_inversion(const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                  const VariationalBayesParameters& params,\n                                  const std::vector<LogProbabilityVector>& seeds) noexcept\n{\n    return !params.save_memory;\n}\n\ntemplate <std::size_t K>\nstd::vector<VBLatents<K>>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector>&& seeds)\n{\n    std::vector<VBLatents<K>> result {};\n    result.reserve(seeds.size());\n    if (run_vb_with_matrix_inversion(log_likelihoods, params, seeds)) {\n        const auto inverted_log_likelihoods = invert(log_likelihoods);\n        const auto func = [&] (auto&& seed) { return detail::run_variational_bayes(prior_alphas, genotype_log_priors, log_likelihoods,\n                                                                                   inverted_log_likelihoods, std::move(seed), params); };\n        if (params.parallel_execution) {\n            parallel_transform(std::make_move_iterator(std::begin(seeds)), std::make_move_iterator(std::end(seeds)),\n                               std::back_inserter(result), func);\n        } else {\n            for (auto& seed : seeds) result.push_back(func(std::move(seed)));\n        }\n    } else {\n        const auto func = [&] (auto&& seed) { return detail::run_variational_bayes(prior_alphas, genotype_log_priors, log_likelihoods,\n                                                                                   std::move(seed), params); };\n        if (params.parallel_execution) {\n            parallel_transform(std::make_move_iterator(std::begin(seeds)), std::make_move_iterator(std::end(seeds)),\n                               std::back_inserter(result), func);\n        } else {\n            for (auto& seed : seeds) result.push_back(func(std::move(seed)));\n        }\n    }\n    return result;\n}\n\n// lower-bound calculation\n\ntemplate <std::size_t K>\nauto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                    const VBLatents<K>& latents)\n{\n    return calculate_evidence_lower_bound(prior_alphas, latents.alphas, genotype_log_priors,\n                                          latents.genotype_posteriors, latents.genotype_log_posteriors,\n                                          latents.responsibilities, log_likelihoods);\n    \n}\n\ninline void check_normalisation(ProbabilityVector& probabilities) noexcept\n{\n    const auto mass = std::accumulate(std::cbegin(probabilities), std::cend(probabilities), 0.0);\n    if (mass > 1.0) for (auto& p : probabilities) p /= mass;\n}\n\ntemplate <std::size_t K>\nvoid check_normalisation(VBLatents<K>& latents) noexcept\n{\n    check_normalisation(latents.genotype_posteriors);\n}\n\ninline std::size_t max_element_index(const ProbabilityVector& probabilities) noexcept\n{\n    return std::distance(std::cbegin(probabilities), std::max_element(std::cbegin(probabilities), std::cend(probabilities)));\n}\n\ntemplate <std::size_t K>\nauto\nfind_map_modes(const std::vector<VBLatents<K>>& latents, \n               const std::vector<double>& log_evidences)\n{\n    const auto num_genotypes = latents.front().genotype_posteriors.size(); \n    std::vector<std::size_t> map_genotypes(num_genotypes, latents.size());\n    for (std::size_t i {0}; i < latents.size(); ++i) {\n        const auto map_genotype_idx = max_element_index(latents[i].genotype_posteriors);\n        if (map_genotypes[map_genotype_idx] == latents.size() || log_evidences[i] > log_evidences[map_genotypes[map_genotype_idx]]) {\n            map_genotypes[map_genotype_idx] = i;\n        }\n    }\n    std::vector<std::size_t> result {};\n    result.reserve(latents.size());\n    for (std::size_t g {0}; g < num_genotypes; ++g) {\n        if (map_genotypes[g] < latents.size()) {\n            result.push_back(map_genotypes[g]);\n        }\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nProbabilityVector\ncompute_evidence_weighted_genotype_posteriors(const std::vector<VBLatents<K>>& latents, \n                                              const std::vector<double>& log_evidences)\n{\n    assert(!latents.empty());\n    assert(latents.size() == log_evidences.size());\n    const auto modes = find_map_modes(latents, log_evidences);\n    std::vector<double> mode_weights(modes.size());\n    std::transform(std::cbegin(modes), std::cend(modes), std::begin(mode_weights), [&] (auto mode) { return log_evidences[mode]; });\n    maths::normalise_exp(mode_weights);\n    const auto num_genotypes = latents.front().genotype_posteriors.size();    \n    ProbabilityVector result(num_genotypes);\n    for (std::size_t i {0}; i < modes.size(); ++i) {\n        const auto mode_weight = mode_weights[i];\n        const auto& mode_genotype_posteriors = latents[modes[i]].genotype_posteriors;\n        std::transform(std::cbegin(mode_genotype_posteriors), std::cend(mode_genotype_posteriors),\n                       std::cbegin(result), std::begin(result), \n                       [mode_weight] (auto seed_posterior, auto curr_posterior) {\n                           return curr_posterior + mode_weight * seed_posterior;\n                       });\n    }\n    check_normalisation(result);\n    return result;\n}\n\ntemplate <std::size_t K>\nstd::vector<double>\ncalculate_log_evidences(const std::vector<VBLatents<K>>& latents,\n                        const VBAlphaVector<K>& prior_alphas,\n                        const LogProbabilityVector& genotype_log_priors,\n                        const VBReadLikelihoodMatrix<K>& log_likelihoods)\n{\n    std::vector<double> result(latents.size());\n    std::transform(std::cbegin(latents), std::cend(latents), std::begin(result),\n                   [&] (const auto& seed_latents) {\n                       return calculate_evidence_lower_bound(prior_alphas, genotype_log_priors, log_likelihoods, seed_latents);\n                   });\n    return result;\n}\n\n} // namespace detail\n\ntemplate <std::size_t K>\nstruct VBResultPacket\n{\n    VBLatents<K> map_latents;\n    double max_log_evidence;\n    ProbabilityVector evidence_weighted_genotype_posteriors;\n};\n\ntemplate <std::size_t K>\nVBResultPacket<K>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector> seeds)\n{\n    assert(!seeds.empty());\n    auto latents = detail::run_variational_bayes(prior_alphas, genotype_log_priors, log_likelihoods, params, std::move(seeds));\n    const auto log_evidences = detail::calculate_log_evidences(latents, prior_alphas, genotype_log_priors, log_likelihoods);\n    auto weighted_genotype_posteriors = detail::compute_evidence_weighted_genotype_posteriors(latents, log_evidences);\n    auto max_evidence_idx = detail::max_element_index(log_evidences);\n    detail::check_normalisation(latents[max_evidence_idx]);\n    return {std::move(latents[max_evidence_idx]), log_evidences[max_evidence_idx], std::move(weighted_genotype_posteriors)};\n}\n\ninline VBReadLikelihoodArray::VBReadLikelihoodArray(const BaseType& underlying_likelihoods)\n: likelihoods{std::addressof(underlying_likelihoods)} {}\n\ninline void VBReadLikelihoodArray::operator=(const BaseType& other)\n{\n    likelihoods = std::addressof(other);\n}\n\ninline void VBReadLikelihoodArray::operator=(std::reference_wrapper<const BaseType> other)\n{\n    likelihoods = std::addressof(other.get());\n}\n\ninline std::size_t VBReadLikelihoodArray::size() const noexcept\n{\n    return likelihoods->size();\n}\n\ninline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::begin() const noexcept\n{\n    return likelihoods->begin();\n}\n\ninline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::end() const noexcept\n{\n    return likelihoods->end();\n}\n\ninline VBReadLikelihoodArray::BaseType::value_type VBReadLikelihoodArray::operator[](const std::size_t n) const noexcept\n{\n    return likelihoods->operator[](n);\n}\n\ntemplate <std::size_t K>\nMemoryFootprint\nestimate_memory_requirement(const std::vector<SampleName>& samples,\n                            const HaplotypeLikelihoodArray& likelihoods,\n                            const std::size_t num_genotypes,\n                            VariationalBayesParameters params)\n{\n    std::size_t bytes {};\n    for (const auto& sample : samples) {\n        bytes += sizeof(VBReadLikelihoodMatrix<K>);\n        bytes += sizeof(VBGenotypeVector<K>) * num_genotypes;\n        bytes += sizeof(VBResponsibilityMatrix<K>);\n        const auto num_likelihoods = likelihoods.num_likelihoods(sample);\n        const auto tau_bytes = num_likelihoods * sizeof(VBTau::value_type);\n        bytes += tau_bytes * K + sizeof(VBResponsibilityVector<K>);\n        if (!params.save_memory) {\n            bytes += sizeof(detail::VBExpandedLikelihoodMatrix<K>);\n            auto inverse_bytes = sizeof(detail::VBExpandedLikelihood::value_type) * num_genotypes + sizeof(detail::VBExpandedLikelihood);\n            inverse_bytes *= num_likelihoods;\n            inverse_bytes += sizeof(detail::VBExpandedGenotype);\n            bytes += K * inverse_bytes + sizeof(detail::VBExpandedGenotypeVector<K>);\n        }\n    }\n    return MemoryFootprint {bytes};\n};\n\n} // namespace model\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "035f83313570638392806069246b34aca02eec1f", "size": 29903, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/variational_bayes_mixture_model.hpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/models/genotype/variational_bayes_mixture_model.hpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/models/genotype/variational_bayes_mixture_model.hpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 40.9069767442, "max_line_length": 142, "alphanum_fraction": 0.6673243487, "num_tokens": 6870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.0271692330126319, "lm_q1q2_score": 0.013478488849024285}}
{"text": "#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/kdtree/kdtree_flann.h>\n\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <GL/freeglut.h>\n#include <boost/algorithm/string.hpp>\n#include <string>\n#include <sstream>\n\n#include <Eigen/Eigen>\n\n#include \"../include/point_to_point_source_to_target_rotated_mirror_tait_bryan_wc_jacobian.h\"\n\ninline double cauchy(double delta, double b){\n\treturn 1.0 / (M_PI * b *( 1.0 + ((delta)/b) * ((delta)/b) ) );\n}\n\nstruct DataStream{\n\tdouble x;\n\tdouble y;\n\tdouble z;\n\tdouble angle_rad;\n\tdouble intensity;\n\tdouble timestamp;\n};\n\nstruct TaitBryanPose\n{\n\tdouble px;\n\tdouble py;\n\tdouble pz;\n\tdouble om;\n\tdouble fi;\n\tdouble ka;\n\n\tTaitBryanPose(){\n\t\tpx = py = pz = om = fi = ka = 0.0;\n\t}\n};\n\nstruct Plane{\n\tdouble a;\n\tdouble b;\n\tdouble c;\n\tdouble d;\n\tEigen::Affine3d m;\n\n\tfloat distance_to_plane(Eigen::Vector3d p){\n\t\treturn a * p.x() + b * p.y() + c * p.z() + d;\n\t}\n\n\tvoid from_m_to_abcd(){\n\t\ta = m(0,2);\n\t\tb = m(1,2);\n\t\tc = m(2,2);\n\t\td = -a * m(0,3) - b * m(1,3) - c * m(2,3);\n\t}\n\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 = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nstd::vector<std::vector<DataStream>> data_streams;\nPlane mirror;\nTaitBryanPose mirror_cal;\nstd::vector<TaitBryanPose> instrument_poses;\nstd::vector<pcl::PointCloud<pcl::PointXYZ>> pcs_global;\nfloat search_radious = 0.3;\npcl::PointCloud<pcl::PointXYZ> ground_truth;\nstd::vector<std::pair<Eigen::Vector3d,Eigen::Vector3d>> nns_to_draw;\nbool shown_nn = false;\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\npcl::PointCloud<pcl::PointXYZ> get_pc_global(const Plane& mirror, const TaitBryanPose& instrument_pose, const std::vector<DataStream>& data_stream);\nstd::vector<std::pair<int,int>> nns(const pcl::PointCloud<pcl::PointXYZ>& pc1, const pcl::PointCloud<pcl::PointXYZ>& pc2, float radius);\n\ninline Eigen::Affine3d affine_matrix_from_pose_tait_bryan(const TaitBryanPose& pose)\n{\n\tEigen::Affine3d m = Eigen::Affine3d::Identity();\n\n\tdouble sx = sin(pose.om);\n\tdouble cx = cos(pose.om);\n\tdouble sy = sin(pose.fi);\n\tdouble cy = cos(pose.fi);\n\tdouble sz = sin(pose.ka);\n\tdouble cz = cos(pose.ka);\n\n\tm(0,0) = cy * cz;\n\tm(1,0) = cz * sx * sy + cx * sz;\n\tm(2,0) = -cx * cz * sy + sx * sz;\n\n\tm(0,1) = -cy * sz;\n\tm(1,1) = cx * cz - sx * sy * sz;\n\tm(2,1) = cz * sx + cx * sy * sz;\n\n\tm(0,2) = sy;\n\tm(1,2) = -cy * sx;\n\tm(2,2) = cx * cy;\n\n\tm(0,3) = pose.px;\n\tm(1,3) = pose.py;\n\tm(2,3) = pose.pz;\n\n\treturn m;\n}\n\ninline TaitBryanPose pose_tait_bryan_from_affine_matrix(Eigen::Affine3d m){\n\tTaitBryanPose pose;\n\n\tpose.px = m(0,3);\n\tpose.py = m(1,3);\n\tpose.pz = m(2,3);\n\n\tif (m(0,2) < 1) {\n\t\tif (m(0,2) > -1) {\n\t\t\t//case 1\n\t\t\tpose.fi = asin(m(0,2));\n\t\t\tpose.om = atan2(-m(1,2), m(2,2));\n\t\t\tpose.ka = atan2(-m(0,1), m(0,0));\n\n\t\t\treturn pose;\n\t\t}\n\t\telse //r02 = −1\n\t\t{\n\t\t\t//case 2\n\t\t\t// not a unique solution: thetaz − thetax = atan2 ( r10 , r11 )\n\t\t\tpose.fi = -M_PI / 2.0;\n\t\t\tpose.om = -atan2(m(1,0), m(1,1));\n\t\t\tpose.ka = 0;\n\t\t\treturn pose;\n\t\t}\n\t}\n\telse {\n\t\t//case 3\n\t\t// r02 = +1\n\t\t// not a unique solution: thetaz + thetax = atan2 ( r10 , r11 )\n\t\tpose.fi = M_PI / 2.0;\n\t\tpose.om = atan2(m(1,0), m(1,1));\n\t\tpose.ka = 0.0;\n\t\treturn pose;\n\t}\n\n\treturn pose;\n}\n\nbool load_data_stream(std::vector<DataStream> &data, const std::string &filename)\n{\n\tstd::ifstream f;\n\tf.open(filename.c_str());\n\tif(f.good()) {\n\t\tstd::string s;\n\t\tgetline(f,s);\n\t\tint counter = 0;\n\t\twhile(!f.eof())\t{\n\t\t\tgetline(f,s);\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() == 6){\n\t\t\t\tDataStream ds;\n\t\t\t\tstd::istringstream(strs[0]) >> ds.x;\n\t\t\t\tstd::istringstream(strs[1]) >> ds.y;\n\t\t\t\tstd::istringstream(strs[2]) >> ds.z;\n\t\t\t\tstd::istringstream(strs[3]) >> ds.angle_rad;\n\t\t\t\tstd::istringstream(strs[4]) >> ds.intensity;\n\t\t\t\tstd::istringstream(strs[5]) >> ds.timestamp;\n\n\t\t\t\tEigen::Vector3d v(ds.x, ds.y, ds.z);\n\t\t\t\tif(v.norm()>3){\n\t\t\t\t\tdata.push_back(ds);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcounter++;\n\t\t}\n\t\tf.close();\n\t}else{\n\t\treturn false;\n\t}\n\n\t////////////////////decimation\n\tTaitBryanPose instrument_pose;\n\tpcl::PointCloud<pcl::PointXYZ> pc = get_pc_global(mirror, instrument_pose, data);\n\n\tpcl::PointCloud<pcl::PointXYZL>::Ptr pre_filteredcloud (new pcl::PointCloud<pcl::PointXYZL>);\n\tpcl::PointCloud<pcl::PointXYZL>::Ptr post_filteredcloud_m (new pcl::PointCloud<pcl::PointXYZL>);\n\n\tpre_filteredcloud->resize(pc.size());\n\tfor (int i =0; i < pc.size(); i++){\n\t\tconst auto & p1 = pc[i];\n\t\tpcl::PointXYZL p2;\n\t\tp2.label = i;\n\t\tp2.getArray3fMap() = Eigen::Vector3f{static_cast<float>(p1.x),\n\t\t\t\t\t\t\t\t\t\t\t static_cast<float>(p1.y),\n\t\t\t\t\t\t\t\t\t\t\t static_cast<float>(p1.z)};\n\t\t(*pre_filteredcloud)[i] = p2;\n\t}\n\n\tpcl::VoxelGrid<pcl::PointXYZL> sor0;\n\tsor0.setInputCloud (pre_filteredcloud);\n\tsor0.setLeafSize (0.1,0.1,0.1);\n\tsor0.filter (*post_filteredcloud_m);\n\n\n\tstd::vector<DataStream> ds2;\n\tds2.resize(post_filteredcloud_m->size());\n\n\tfor (int i =0; i < ds2.size(); i++){\n\t\tconst auto & p1 = (*post_filteredcloud_m)[i];\n\t\tconst auto & p2 = data[p1.label];\n\t\tds2[i] = p2;\n\t}\n\n\tdata = ds2;\n\n\treturn true;\n}\n\nint main(int argc, char *argv[]){\n\n\t//from calibration\n\t//a,b,c,d: -0.795092 -0.419594 0.437916 0.00453302\n\t//pose 0\n\t//27.99 -2.44216 -0.551882 1.5202 -1.47909 1.51403\n\t//pose 1\n\t//37.6979 -2.41142 -0.537749 -1.37268 -1.54515 -1.38618\n\t//mirror_cal: 0 0 0 0 0.0017875 0.00588813\n\n\n\n\tpcl::io::loadPCDFile(\"../data/ground_truth.pcd\", ground_truth);\n\n\tmirror.a =  -0.795092;\n\tmirror.b = -0.419594;\n\tmirror.c = 0.437916;\n\tEigen::Vector3d v(mirror.a, mirror.b, mirror.c);\n\tv=v/v.norm();\n\tmirror.d = 0.00453302;\n\n\n\tmirror_cal.px = 0;\n\tmirror_cal.py = 0;\n\tmirror_cal.pz = 0;\n\tmirror_cal.om = 0;\n\tmirror_cal.fi = 0.0017875;\n\tmirror_cal.ka = 0.00588813;\n\n\tstd::vector<std::string> file_names;\n\tTaitBryanPose pose;\n\n\tfile_names.push_back(\"../data/log1630860661.csv\");\n\tpose.px = 2.60492;\n\tpose.py = -10.2245;\n\tpose.pz = -0.632075;\n\tpose.om = 1.56086;\n\tpose.fi = -1.49079;\n\tpose.ka = 1.56083;\n\tinstrument_poses.push_back(pose);\n\n\tfile_names.push_back(\"../data/log1630860904.csv\");\n\tpose.px = 46.0542;\n\tpose.py = -2.08642;\n\tpose.pz = -0.597237;\n\tpose.om = 1.43695;\n\tpose.fi = -1.49007;\n\tpose.ka = 1.43652;\n\tinstrument_poses.push_back(pose);\n\n\tfile_names.push_back(\"../data/log1630861009.csv\");\n\tpose.px = 65.6144;\n\tpose.py = -7.95168;\n\tpose.pz = -0.617178;\n\tpose.om = -3.10159;\n\tpose.fi = -1.56159;\n\tpose.ka = 3.14159;\n\tinstrument_poses.push_back(pose);\n\n\n\n\tfor(size_t i = 0 ; i < file_names.size(); i++){\n\t\tstd::cout << \"loading \" << i << std::endl;\n\t\tstd::vector<DataStream> data;\n\t\tload_data_stream(data, file_names[i]);\n\t\tdata_streams.push_back(data);\n\t}\n\n\tfor(size_t i = 0; i < data_streams.size(); i++){\n\t\tpcl::PointCloud<pcl::PointXYZ> pc_global = get_pc_global(mirror, instrument_poses[i], data_streams[i]);\n\t\tpcs_global.push_back(pc_global);\n\t}\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n}\n\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(\"validation\");\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\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglBegin(GL_LINES);\n\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\tglVertex3f(0.0f, 0.0f, 0.0f);\n\t\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();\n\n\tglColor3f(1,0,0);\n\tglBegin(GL_POINTS);\n\tfor(size_t i = 0 ; i < pcs_global.size(); i++){\n\t\tfor(size_t j = 0 ; j < pcs_global[i].size(); j++){\n\t\t\tglVertex3f(pcs_global[i][j].x, pcs_global[i][j].y, pcs_global[i][j].z);\n\t\t}\n\t}\n\tglEnd();\n\n\tglColor3f(0,1,0);\n\tglBegin(GL_POINTS);\n\tfor(size_t i = 0 ; i < ground_truth.size(); i++){\n\t\tglVertex3f(ground_truth[i].x, ground_truth[i].y, ground_truth[i].z);\n\t}\n\tglEnd();\n\n\tif(shown_nn){\n\t\tglColor3f(0,0,1);\n\t\tglBegin(GL_LINES);\n\t\tfor (auto &n : nns_to_draw)\n\t\t{\n\t\t\tglVertex3f(n.first.x(),n.first.y(),n.first.z());\n\t\t\tglVertex3f(n.second.x(),n.second.y(),n.second.z());\n\t\t}\n\t\tglEnd();\n\t}\n\n\tglutSwapBuffers();\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\tcase 'x':{\n\t\tfor (int i =0; i< pcs_global.size(); i++){\n\t\t\tpcl::io::savePCDFile(\"site\"+std::to_string(i)+\".pcd\", pcs_global[i]);\n\t\t}\n\t\tbreak;\n\t}\n\n\t\tcase 'v':{\n\n\t\t\tfor(int iter = 0; iter < 50; iter++){\n\n\t\t\t\tstd::cout << \"optimize\" << std::endl;\n\n\t\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\t\tdouble plane_a = mirror.a;\n\t\t\t\tdouble plane_b = mirror.b;\n\t\t\t\tdouble plane_c = mirror.c;\n\t\t\t\tdouble plane_d = mirror.d;\n\n\n\t\t\t\tfor(size_t i = 0 ; i < data_streams.size(); i++){\n\t\t\t\t\tauto nn = nns (pcs_global[i],ground_truth, search_radious);\n\n\t\t\t\t\tfor (auto & n : nn)\n\t\t\t\t\t{\n\t\t\t\t\t\tTaitBryanPose instrument_pose_i = instrument_poses[i];\n\n\t\t\t\t\t\tEigen::Vector3d ray_i(data_streams[i][n.first].x, data_streams[i][n.first].y, data_streams[i][n.first].z);\n\t\t\t\t\t\tdouble ray_i_length = ray_i.norm();\n\t\t\t\t\t\tEigen::Vector3d ray_i_n = ray_i/ray_i.norm();\n\n\t\t\t\t\t\tdouble x_t = ground_truth[n.second].x;\n\t\t\t\t\t\tdouble y_t = ground_truth[n.second].y;\n\t\t\t\t\t\tdouble z_t = ground_truth[n.second].z;\n\n\t\t\t\t\t\tdouble om_mirror = data_streams[i][n.first].angle_rad;\n\n\t\t\t\t\t\tEigen::Matrix<double, 3, 1> delta;\n\t\t\t\t\t\tpoint_to_point_source_to_target_rotated_mirror_tait_bryan_wc(\n\t\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\t\tinstrument_pose_i.px,\n\t\t\t\t\t\t\t\tinstrument_pose_i.py,\n\t\t\t\t\t\t\t\tinstrument_pose_i.pz,\n\t\t\t\t\t\t\t\tinstrument_pose_i.om,\n\t\t\t\t\t\t\t\tinstrument_pose_i.fi,\n\t\t\t\t\t\t\t\tinstrument_pose_i.ka,\n\t\t\t\t\t\t\t\tray_i_n.x(),\n\t\t\t\t\t\t\t\tray_i_n.y(),\n\t\t\t\t\t\t\t\tray_i_n.z(),\n\t\t\t\t\t\t\t\tray_i_length,\n\t\t\t\t\t\t\t\tplane_a,\n\t\t\t\t\t\t\t\tplane_b,\n\t\t\t\t\t\t\t\tplane_c,\n\t\t\t\t\t\t\t\tplane_d,\n\t\t\t\t\t\t\t\tx_t,\n\t\t\t\t\t\t\t\ty_t,\n\t\t\t\t\t\t\t\tz_t,\n\t\t\t\t\t\t\t\tom_mirror,\n\t\t\t\t\t\t\t\tmirror_cal.px,\n\t\t\t\t\t\t\t\tmirror_cal.py,\n\t\t\t\t\t\t\t\tmirror_cal.pz,\n\t\t\t\t\t\t\t\tmirror_cal.om,\n\t\t\t\t\t\t\t\tmirror_cal.fi,\n\t\t\t\t\t\t\t\tmirror_cal.ka);\n\n\t\t\t\t\t\tEigen::Matrix<double, 3, 14, Eigen::RowMajor> jacobian;\n\n\t\t\t\t\t\tpoint_to_point_source_to_target_rotated_mirror_tait_bryan_wc_jacobian(\n\t\t\t\t\t\t\t\tjacobian,\n\t\t\t\t\t\t\t\tinstrument_pose_i.px,\n\t\t\t\t\t\t\t\tinstrument_pose_i.py,\n\t\t\t\t\t\t\t\tinstrument_pose_i.pz,\n\t\t\t\t\t\t\t\tinstrument_pose_i.om,\n\t\t\t\t\t\t\t\tinstrument_pose_i.fi,\n\t\t\t\t\t\t\t\tinstrument_pose_i.ka,\n\t\t\t\t\t\t\t\tray_i_n.x(),\n\t\t\t\t\t\t\t\tray_i_n.y(),\n\t\t\t\t\t\t\t\tray_i_n.z(),\n\t\t\t\t\t\t\t\tray_i_length,\n\t\t\t\t\t\t\t\tplane_a,\n\t\t\t\t\t\t\t\tplane_b,\n\t\t\t\t\t\t\t\tplane_c,\n\t\t\t\t\t\t\t\tplane_d,\n\t\t\t\t\t\t\t\tx_t,\n\t\t\t\t\t\t\t\ty_t,\n\t\t\t\t\t\t\t\tz_t,\n\t\t\t\t\t\t\t\tom_mirror,\n\t\t\t\t\t\t\t\tmirror_cal.px,\n\t\t\t\t\t\t\t\tmirror_cal.py,\n\t\t\t\t\t\t\t\tmirror_cal.pz,\n\t\t\t\t\t\t\t\tmirror_cal.om,\n\t\t\t\t\t\t\t\tmirror_cal.fi,\n\t\t\t\t\t\t\t\tmirror_cal.ka);\n\n\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\tint ic = i * 6;\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic + 0, -jacobian(0,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic + 1, -jacobian(0,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic + 2, -jacobian(0,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic + 3, -jacobian(0,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic + 4, -jacobian(0,4));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic + 5, -jacobian(0,5));\n\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 0, -jacobian(1,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 1, -jacobian(1,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 2, -jacobian(1,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 3, -jacobian(1,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 4, -jacobian(1,4));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 5, -jacobian(1,5));\n\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 0, -jacobian(2,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 1, -jacobian(2,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 2, -jacobian(2,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 3, -jacobian(2,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 4, -jacobian(2,4));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 5, -jacobian(2,5));\n\n\n\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);\n\t\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\t\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  1);\n\n\n\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta(2,0));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tint state_vec_l = data_streams.size() * 6;\n\t\t\t\tstd::cout << \"state_vec_l \" << state_vec_l << std::endl;\n\n\t\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), state_vec_l);\n\t\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\t\tEigen::SparseMatrix<double> AtPA(state_vec_l, state_vec_l);\n\t\t\t\tEigen::SparseMatrix<double> AtPB(state_vec_l, 1);\n\n\t\t\t\t{\n\t\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\t\tAtPA = (AtP) * matA;\n\t\t\t\tAtPB = (AtP) * matB;\n\t\t\t\t}\n\n\t\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\t\tstd::vector<double> h_x;\n\n\t\t\t\th_x.resize(state_vec_l);\n\n\t\t\t\tfor(size_t i = 0 ; i < state_vec_l; i++)h_x[i] = 0;\n\n\t\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\t\th_x[it.row()] = it.value();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstd::cout << \"h_x.size() \" << h_x.size() << std::endl;\n\t\t\t\tstd::cout << \"results\" << std::endl;\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << i << \" \" << h_x[i] << std::endl;\n\t\t\t\t}\n\n\t\t\t\tif(h_x.size() == state_vec_l){\n\t\t\t\t\tint counter = 0;\n\n\n\t\t\t\t\tfor (int i=0; i < instrument_poses.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tinstrument_poses[i].px += h_x[counter++]*0.5;\n\t\t\t\t\t\tinstrument_poses[i].py += h_x[counter++]*0.5;\n\t\t\t\t\t\tinstrument_poses[i].pz += h_x[counter++]*0.5;\n\t\t\t\t\t\tinstrument_poses[i].om += h_x[counter++]*0.5;\n\t\t\t\t\t\tinstrument_poses[i].fi += h_x[counter++]*0.5;\n\t\t\t\t\t\tinstrument_poses[i].ka += h_x[counter++]*0.5;\n\t\t\t\t\t}\n\n\t\t\t\t\tstd::cout << \"a,b,c,d: \" << mirror.a << \" \" << mirror.b << \" \" << mirror.c << \" \" << mirror.d << std::endl;\n\t\t\t\t\tfor (int i=0; i < instrument_poses.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << instrument_poses[i].px << \" \" << instrument_poses[i].py << \" \" << instrument_poses[i].pz << \" \" <<\n\t\t\t\t\t\t\t\tinstrument_poses[i].om << \" \" << instrument_poses[i].fi << \" \" << instrument_poses[i].ka << std::endl;\n\t\t\t\t\t}\n\n\t\t\t\t\tstd::cout << \"mirror_cal: \" << mirror_cal.px << \" \" << mirror_cal.py << \" \" << mirror_cal.pz << \" \" <<\n\t\t\t\t\t\t\tmirror_cal.om << \" \" << mirror_cal.fi << \" \" << mirror_cal.ka << std::endl;\n\n\t\t\t\t\tfor(size_t i = 0; i < data_streams.size(); i++){\n\t\t\t\t\t\tpcl::PointCloud<pcl::PointXYZ> pc_global = get_pc_global(mirror, instrument_poses[i], data_streams[i]);\n\t\t\t\t\t\tpcs_global[i] = pc_global;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tstd::cout << \"OPTIMIZATION FAILED\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\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 << \"v: validate\" << std::endl;\n}\n\n\npcl::PointCloud<pcl::PointXYZ> get_pc_global(const Plane& mirror, const TaitBryanPose& instrument_pose, const std::vector<DataStream>& data_stream)\n{\n\tpcl::PointCloud<pcl::PointXYZ> pc_global;\n\tdouble px = instrument_pose.px;\n\tdouble py = instrument_pose.py;\n\tdouble pz = instrument_pose.pz;\n\tdouble om = instrument_pose.om;\n\tdouble fi = instrument_pose.fi;\n\tdouble ka = instrument_pose.ka;\n\tdouble a = mirror.a;\n\tdouble b = mirror.b;\n\tdouble c = mirror.c;\n\tdouble d = mirror.d;\n\n\tfor(auto &ds:data_stream){\n\t\tdouble x;\n\t\tdouble y;\n\t\tdouble z;\n\t\tEigen::Vector3d ray(ds.x, ds.y, ds.z);\n\t\tdouble length = ray.norm();\n\t\tdouble angle_rad = ds.angle_rad;\n\n\t\tray = ray / ray.norm();\n\n\t\ttransform_point_rotated_mirror_tait_bryan_wc(x, y, z, px, py, pz, om, fi, ka,\n\t\t\t\tray.x(), ray.y(), ray.z(), length,\n\t\t\t\ta, b, c, d, angle_rad, mirror_cal.px, mirror_cal.py, mirror_cal.pz, mirror_cal.om, mirror_cal.fi, mirror_cal.ka);\n\n\t\tpcl::PointXYZ p;\n\t\tp.x = x;\n\t\tp.y = y;\n\t\tp.z = z;\n\t\tpc_global.push_back(p);\n\t}\n\n\treturn pc_global;\n}\n\nstd::vector<std::pair<int,int>> nns(const pcl::PointCloud<pcl::PointXYZ>& pc1, const pcl::PointCloud<pcl::PointXYZ>& pc2, float radius)\n{\n\tnns_to_draw.clear();\n\n    std::vector<std::pair<int,int>> result;\n\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);\n    for(size_t i = 0; i < pc2.size(); i++){\n        cloud->push_back(pc2[i]);\n    }\n    int K = 1;\n\n    std::vector<int> pointIdxRadiusSearch;\n    std::vector<float> pointRadiusSquaredDistance;\n\n    kdtree.setInputCloud (cloud);\n    for(size_t k = 0; k < pc1.size(); k++){\n        if ( kdtree.radiusSearch (pc1[k], radius, pointIdxRadiusSearch, pointRadiusSquaredDistance) > 0 ){\n            for (std::size_t i = 0; i < pointIdxRadiusSearch.size (); ++i){\n\n            \tstd::pair<Eigen::Vector3d,Eigen::Vector3d>  n = std::pair<Eigen::Vector3d,Eigen::Vector3d>(pc2[pointIdxRadiusSearch[i]].getArray3fMap().cast<double>(),\n                        pc1[k].getArray3fMap().cast<double>());\n\n            \t\tEigen::Vector3d n1 = pc1[k].getArray3fMap().cast<double>();\n\t\t\t\t\tEigen::Vector3d n2 = pc2[pointIdxRadiusSearch[i]].getArray3fMap().cast<double>() ;\n\n            \t\tif((n2-n1).norm() > 0.001){\n            \t\t\tresult.emplace_back( k, pointIdxRadiusSearch[i]);\n\t\t\t\t\t\tnns_to_draw.emplace_back(n1, n2);\n            \t\t}\n\n                break;\n            }\n\n        }\n    }\n    std::cout << \"nns.size(): \" << result.size() << std::endl;\n    return result;\n}\n\n\n\n\n", "meta": {"hexsha": "4fd99db1d9714eec265b76b9cdbb27d1c98307e1", "size": 19710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/validation.cpp", "max_stars_repo_name": "michalpelka/lidar_spinning_mirror", "max_stars_repo_head_hexsha": "0ed16b40559b8fee5ce7e23f09d20ef9038a820e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/validation.cpp", "max_issues_repo_name": "michalpelka/lidar_spinning_mirror", "max_issues_repo_head_hexsha": "0ed16b40559b8fee5ce7e23f09d20ef9038a820e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/validation.cpp", "max_forks_repo_name": "michalpelka/lidar_spinning_mirror", "max_forks_repo_head_hexsha": "0ed16b40559b8fee5ce7e23f09d20ef9038a820e", "max_forks_repo_licenses": ["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.9683794466, "max_line_length": 164, "alphanum_fraction": 0.6228817859, "num_tokens": 6538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.027169231634144437, "lm_q1q2_score": 0.013478488165165161}}
{"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 <boost/algorithm/string.hpp>\n#include <cmath>\n\n#include \"Netcdf_interface.h\"\n#include \"Array.h\"\n#include \"Gas_concs.h\"\n#include \"Gas_optics.h\"\n#include \"Optical_props.h\"\n#include \"Source_functions.h\"\n#include \"Fluxes.h\"\n#include \"Rte_lw.h\"\n#include \"Rte_sw.h\"\n\n#ifdef FLOAT_SINGLE_RRTMGP\n#define FLOAT_TYPE float\n#else\n#define FLOAT_TYPE double\n#endif\n\nnamespace\n{\n    std::vector<std::string> get_variable_string(\n            const std::string& var_name,\n            std::vector<int> i_count,\n            Netcdf_handle& input_nc,\n            const int string_len,\n            bool trim=true)\n    {\n        // Multiply all elements in i_count.\n        int total_count = std::accumulate(i_count.begin(), i_count.end(), 1, std::multiplies<>());\n\n        // Add the string length as the rightmost dimension.\n        i_count.push_back(string_len);\n\n        // Multiply all elements in i_count.\n        // int total_count_char = std::accumulate(i_count.begin(), i_count.end(), 1, std::multiplies<>());\n\n        // Read the entire char array;\n        std::vector<char> var_char;\n        var_char = input_nc.get_variable<char>(var_name, i_count);\n\n        std::vector<std::string> var;\n\n        for (int n=0; n<total_count; ++n)\n        {\n            std::string s(var_char.begin()+n*string_len, var_char.begin()+(n+1)*string_len);\n            if (trim)\n                boost::trim(s);\n            var.push_back(s);\n        }\n\n        return var;\n    }\n\n    template<typename TF>\n    Gas_optics<TF> load_and_init_gas_optics(\n            Master& master,\n            const Gas_concs<TF>& gas_concs,\n            const std::string& coef_file)\n    {\n        // READ THE COEFFICIENTS FOR THE OPTICAL SOLVER.\n        Netcdf_file coef_nc(master, coef_file, Netcdf_mode::Read);\n\n        // Read k-distribution information.\n        int n_temps = coef_nc.get_dimension_size(\"temperature\");\n        int n_press = coef_nc.get_dimension_size(\"pressure\");\n        int n_absorbers = coef_nc.get_dimension_size(\"absorber\");\n        int n_char = coef_nc.get_dimension_size(\"string_len\");\n        int n_minorabsorbers = coef_nc.get_dimension_size(\"minor_absorber\");\n        int n_extabsorbers = coef_nc.get_dimension_size(\"absorber_ext\");\n        int n_mixingfracs = coef_nc.get_dimension_size(\"mixing_fraction\");\n        int n_layers = coef_nc.get_dimension_size(\"atmos_layer\");\n        int n_bnds = coef_nc.get_dimension_size(\"bnd\");\n        int n_gpts = coef_nc.get_dimension_size(\"gpt\");\n        int n_pairs = coef_nc.get_dimension_size(\"pair\");\n        int n_minor_absorber_intervals_lower = coef_nc.get_dimension_size(\"minor_absorber_intervals_lower\");\n        int n_minor_absorber_intervals_upper = coef_nc.get_dimension_size(\"minor_absorber_intervals_upper\");\n        int n_contributors_lower = coef_nc.get_dimension_size(\"contributors_lower\");\n        int n_contributors_upper = coef_nc.get_dimension_size(\"contributors_upper\");\n\n        // Read gas names.\n        Array<std::string,1> gas_names(\n                get_variable_string(\"gas_names\", {n_absorbers}, coef_nc, n_char, true), {n_absorbers});\n\n        Array<int,3> key_species(\n                coef_nc.get_variable<int>(\"key_species\", {n_bnds, n_layers, 2}),\n                {2, n_layers, n_bnds});\n        Array<TF,2> band_lims(coef_nc.get_variable<TF>(\"bnd_limits_wavenumber\", {n_bnds, 2}), {2, n_bnds});\n        Array<int,2> band2gpt(coef_nc.get_variable<int>(\"bnd_limits_gpt\", {n_bnds, 2}), {2, n_bnds});\n        Array<TF,1> press_ref(coef_nc.get_variable<TF>(\"press_ref\", {n_press}), {n_press});\n        Array<TF,1> temp_ref(coef_nc.get_variable<TF>(\"temp_ref\", {n_temps}), {n_temps});\n\n        TF temp_ref_p = coef_nc.get_variable<TF>(\"absorption_coefficient_ref_P\");\n        TF temp_ref_t = coef_nc.get_variable<TF>(\"absorption_coefficient_ref_T\");\n        TF press_ref_trop = coef_nc.get_variable<TF>(\"press_ref_trop\");\n\n        Array<TF,3> kminor_lower(\n                coef_nc.get_variable<TF>(\"kminor_lower\", {n_temps, n_mixingfracs, n_contributors_lower}),\n                {n_contributors_lower, n_mixingfracs, n_temps});\n        Array<TF,3> kminor_upper(\n                coef_nc.get_variable<TF>(\"kminor_upper\", {n_temps, n_mixingfracs, n_contributors_upper}),\n                {n_contributors_upper, n_mixingfracs, n_temps});\n\n        Array<std::string,1> gas_minor(get_variable_string(\"gas_minor\", {n_minorabsorbers}, coef_nc, n_char),\n                {n_minorabsorbers});\n\n        Array<std::string,1> identifier_minor(\n                get_variable_string(\"identifier_minor\", {n_minorabsorbers}, coef_nc, n_char), {n_minorabsorbers});\n\n        Array<std::string,1> minor_gases_lower(\n                get_variable_string(\"minor_gases_lower\", {n_minor_absorber_intervals_lower}, coef_nc, n_char),\n                {n_minor_absorber_intervals_lower});\n        Array<std::string,1> minor_gases_upper(\n                get_variable_string(\"minor_gases_upper\", {n_minor_absorber_intervals_upper}, coef_nc, n_char),\n                {n_minor_absorber_intervals_upper});\n\n        Array<int,2> minor_limits_gpt_lower(\n                coef_nc.get_variable<int>(\"minor_limits_gpt_lower\", {n_minor_absorber_intervals_lower, n_pairs}),\n                {n_pairs, n_minor_absorber_intervals_lower});\n        Array<int,2> minor_limits_gpt_upper(\n                coef_nc.get_variable<int>(\"minor_limits_gpt_upper\", {n_minor_absorber_intervals_upper, n_pairs}),\n                {n_pairs, n_minor_absorber_intervals_upper});\n\n        Array<int,1> minor_scales_with_density_lower(\n                coef_nc.get_variable<int>(\"minor_scales_with_density_lower\", {n_minor_absorber_intervals_lower}),\n                {n_minor_absorber_intervals_lower});\n        Array<int,1> minor_scales_with_density_upper(\n                coef_nc.get_variable<int>(\"minor_scales_with_density_upper\", {n_minor_absorber_intervals_upper}),\n                {n_minor_absorber_intervals_upper});\n\n        Array<int,1> scale_by_complement_lower(\n                coef_nc.get_variable<int>(\"scale_by_complement_lower\", {n_minor_absorber_intervals_lower}),\n                {n_minor_absorber_intervals_lower});\n        Array<int,1> scale_by_complement_upper(\n                coef_nc.get_variable<int>(\"scale_by_complement_upper\", {n_minor_absorber_intervals_upper}),\n                {n_minor_absorber_intervals_upper});\n\n        Array<std::string,1> scaling_gas_lower(\n                get_variable_string(\"scaling_gas_lower\", {n_minor_absorber_intervals_lower}, coef_nc, n_char),\n                {n_minor_absorber_intervals_lower});\n        Array<std::string,1> scaling_gas_upper(\n                get_variable_string(\"scaling_gas_upper\", {n_minor_absorber_intervals_upper}, coef_nc, n_char),\n                {n_minor_absorber_intervals_upper});\n\n        Array<int,1> kminor_start_lower(\n                coef_nc.get_variable<int>(\"kminor_start_lower\", {n_minor_absorber_intervals_lower}),\n                {n_minor_absorber_intervals_lower});\n        Array<int,1> kminor_start_upper(\n                coef_nc.get_variable<int>(\"kminor_start_upper\", {n_minor_absorber_intervals_upper}),\n                {n_minor_absorber_intervals_upper});\n\n        Array<TF,3> vmr_ref(\n                coef_nc.get_variable<TF>(\"vmr_ref\", {n_temps, n_extabsorbers, n_layers}),\n                {n_layers, n_extabsorbers, n_temps});\n\n        Array<TF,4> kmajor(\n                coef_nc.get_variable<TF>(\"kmajor\", {n_temps, n_press+1, n_mixingfracs, n_gpts}),\n                {n_gpts, n_mixingfracs, n_press+1, n_temps});\n\n        // Keep the size at zero, if it does not exist.\n        Array<TF,3> rayl_lower;\n        Array<TF,3> rayl_upper;\n\n        if (coef_nc.variable_exists(\"rayl_lower\"))\n        {\n            rayl_lower.set_dims({n_gpts, n_mixingfracs, n_temps});\n            rayl_upper.set_dims({n_gpts, n_mixingfracs, n_temps});\n            rayl_lower = coef_nc.get_variable<TF>(\"rayl_lower\", {n_temps, n_mixingfracs, n_gpts});\n            rayl_upper = coef_nc.get_variable<TF>(\"rayl_upper\", {n_temps, n_mixingfracs, n_gpts});\n        }\n\n        // Is it really LW if so read these variables as well.\n        if (coef_nc.variable_exists(\"totplnk\"))\n        {\n            int n_internal_sourcetemps = coef_nc.get_dimension_size(\"temperature_Planck\");\n\n            Array<TF,2> totplnk(\n                    coef_nc.get_variable<TF>( \"totplnk\", {n_bnds, n_internal_sourcetemps}),\n                    {n_internal_sourcetemps, n_bnds});\n            Array<TF,4> planck_frac(\n                    coef_nc.get_variable<TF>(\"plank_fraction\", {n_temps, n_press+1, n_mixingfracs, n_gpts}),\n                    {n_gpts, n_mixingfracs, n_press+1, n_temps});\n\n            // Construct the k-distribution.\n            return Gas_optics<TF>(\n                    gas_concs,\n                    gas_names,\n                    key_species,\n                    band2gpt,\n                    band_lims,\n                    press_ref,\n                    press_ref_trop,\n                    temp_ref,\n                    temp_ref_p,\n                    temp_ref_t,\n                    vmr_ref,\n                    kmajor,\n                    kminor_lower,\n                    kminor_upper,\n                    gas_minor,\n                    identifier_minor,\n                    minor_gases_lower,\n                    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,\n                    scaling_gas_upper,\n                    scale_by_complement_lower,\n                    scale_by_complement_upper,\n                    kminor_start_lower,\n                    kminor_start_upper,\n                    totplnk,\n                    planck_frac,\n                    rayl_lower,\n                    rayl_upper);\n        }\n        else\n        {\n            Array<TF,1> solar_src(\n                    coef_nc.get_variable<TF>(\"solar_source\", {n_gpts}), {n_gpts});\n\n            return Gas_optics<TF>(\n                    gas_concs,\n                    gas_names,\n                    key_species,\n                    band2gpt,\n                    band_lims,\n                    press_ref,\n                    press_ref_trop,\n                    temp_ref,\n                    temp_ref_p,\n                    temp_ref_t,\n                    vmr_ref,\n                    kmajor,\n                    kminor_lower,\n                    kminor_upper,\n                    gas_minor,\n                    identifier_minor,\n                    minor_gases_lower,\n                    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,\n                    scaling_gas_upper,\n                    scale_by_complement_lower,\n                    scale_by_complement_upper,\n                    kminor_start_lower,\n                    kminor_start_upper,\n                    solar_src,\n                    rayl_lower,\n                    rayl_upper);\n        }\n        // End reading of k-distribution.\n    }\n}\n\ntemplate<typename TF>\nvoid solve_radiation(Master& master)\n{\n    Netcdf_file input_nc(master, \"rrtmgp-inputs-outputs.nc\", Netcdf_mode::Read);\n\n    // READ THE ATMOSPHERIC DATA.\n    int n_lay = input_nc.get_dimension_size(\"lay\");\n    int n_lev = input_nc.get_dimension_size(\"lev\");\n    int n_col = input_nc.get_dimension_size(\"col\");\n\n    Array<TF,2> p_lay(input_nc.get_variable<TF>(\"p_lay\", {n_lay, n_col}), {n_col, n_lay});\n    Array<TF,2> t_lay(input_nc.get_variable<TF>(\"t_lay\", {n_lay, n_col}), {n_col, n_lay});\n    Array<TF,2> p_lev(input_nc.get_variable<TF>(\"p_lev\", {n_lev, n_col}), {n_col, n_lev});\n    Array<TF,2> t_lev(input_nc.get_variable<TF>(\"t_lev\", {n_lev, n_col}), {n_col, n_lev});\n\n    const int top_at_1 = p_lay({1, 1}) < p_lay({1, n_lay});\n\n    Gas_concs<TF> gas_concs;\n    Gas_concs<TF> gas_concs_subset;\n\n    gas_concs.set_vmr(\"h2o\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_h2o\", {n_lay, n_col}), {n_col, n_lay}));\n    gas_concs.set_vmr(\"co2\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_co2\", {n_lay, n_col}), {n_col, n_lay}));\n    gas_concs.set_vmr(\"o3\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_o3\", {n_lay, n_col}), {n_col, n_lay}));\n    gas_concs.set_vmr(\"n2o\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_n2o\", {n_lay, n_col}), {n_col, n_lay}));\n    gas_concs.set_vmr(\"co\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_co\", {n_lay, n_col}), {n_col, n_lay}));\n    gas_concs.set_vmr(\"ch4\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_ch4\", {n_lay, n_col}), {n_col, n_lay}));\n    gas_concs.set_vmr(\"o2\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_o2\", {n_lay, n_col}), {n_col, n_lay}));\n    gas_concs.set_vmr(\"n2\",\n            Array<TF,2>(input_nc.get_variable<TF>(\"vmr_n2\", {n_lay, n_col}), {n_col, n_lay}));\n\n    // Construct the gas optics class.\n    Gas_optics<TF> kdist = load_and_init_gas_optics(master, gas_concs, \"coefficients.nc\");\n\n    // Fetch the col_dry in case present.\n    Array<TF,2> col_dry({n_col, n_lay});\n    if (input_nc.variable_exists(\"col_dry\"))\n        col_dry = input_nc.get_variable<TF>(\"col_dry\", {n_lay, n_col});\n    else\n        kdist.get_col_dry(col_dry, gas_concs.get_vmr(\"h2o\"), p_lev);\n\n    const int n_gpt = kdist.get_ngpt();\n    const int n_bnd = kdist.get_nband();\n\n    // Boundary conditions for longwave.\n    Array<TF,2> emis_sfc;\n    Array<TF,1> t_sfc;\n\n    // Boundary conditions for shortwave.\n    Array<TF,1> sza;\n    Array<TF,1> tsi;\n    Array<TF,2> sfc_alb_dir;\n    Array<TF,2> sfc_alb_dif;\n\n    const int n_col_block = 4;\n\n    std::unique_ptr<Optical_props_arry<TF>> optical_props;\n    std::unique_ptr<Optical_props_arry<TF>> optical_props_subset;\n    std::unique_ptr<Optical_props_arry<TF>> optical_props_left;\n\n    if (kdist.source_is_internal())\n    {\n        ////// SOLVING THE OPTICAL PROPERTIES FOR LONGWAVE RADIATION //////\n        master.print_message(\"STEP 1: Computing optical depths for longwave radiation.\\n\");\n\n        // Download surface boundary conditions for long wave.\n        Array<TF,2> emis_sfc_tmp(\n                input_nc.get_variable<TF>(\n                        \"emis_sfc\", {n_col, n_bnd}), {n_bnd, n_col});\n        Array<TF,1> t_sfc_tmp(\n                input_nc.get_variable<TF>(\n                        \"t_sfc\", {n_col}), {n_col});\n\n        emis_sfc = emis_sfc_tmp;\n        t_sfc = t_sfc_tmp;\n\n        // Read the sources and create containers for the substeps.\n        int n_blocks = n_col / n_col_block;\n        int n_col_block_left = n_col % n_col_block;\n\n        optical_props        = std::make_unique<Optical_props_1scl<TF>>(n_col      , n_lay, kdist);\n        optical_props_subset = std::make_unique<Optical_props_1scl<TF>>(n_col_block, n_lay, kdist);\n\n        Source_func_lw<TF> sources       (n_col      , n_lay, kdist);\n        Source_func_lw<TF> sources_subset(n_col_block, n_lay, kdist);\n\n        auto calc_optical_props_subset = [&](\n                const int col_s_in, const int col_e_in,\n                std::unique_ptr<Optical_props_arry<TF>>& optical_props_subset_in,\n                Source_func_lw<TF>& sources_subset_in)\n        {\n            const int n_col_in = col_e_in - col_s_in + 1;\n            Gas_concs<TF> gas_concs_subset(gas_concs, col_s_in, n_col_in);\n\n            kdist.gas_optics(\n                    p_lay.subset({{ {col_s_in, col_e_in}, {1, n_lay} }}),\n                    p_lev.subset({{ {col_s_in, col_e_in}, {1, n_lev} }}),\n                    t_lay.subset({{ {col_s_in, col_e_in}, {1, n_lay} }}),\n                    t_sfc.subset({{ {col_s_in, col_e_in} }}),\n                    gas_concs_subset,\n                    optical_props_subset_in,\n                    sources_subset_in,\n                    col_dry.subset({{ {col_s_in, col_e_in}, {1, n_lay} }}),\n                    t_lev.subset  ({{ {col_s_in, col_e_in}, {1, n_lev} }}) );\n\n            optical_props->set_subset(optical_props_subset_in, col_s_in, col_e_in);\n            sources.set_subset(sources_subset_in, col_s_in, col_e_in);\n        };\n\n        for (int b=1; b<=n_blocks; ++b)\n        {\n            const int col_s = (b-1) * n_col_block + 1;\n            const int col_e =  b    * n_col_block;\n\n            calc_optical_props_subset(\n                    col_s, col_e,\n                    optical_props_subset,\n                    sources_subset);\n        }\n\n        if (n_col_block_left > 0)\n        {\n            optical_props_left = std::make_unique<Optical_props_1scl<TF>>(n_col_block_left, n_lay, kdist);\n            Source_func_lw<TF> sources_left(n_col_block_left, n_lay, kdist);\n\n            const int col_s = n_col - n_col_block_left + 1;\n            const int col_e = n_col;\n\n            calc_optical_props_subset(\n                    col_s, col_e,\n                    optical_props_left,\n                    sources_left);\n        }\n\n\n        ////// SOLVING THE FLUXES FOR LONGWAVE RADIATION //////\n        master.print_message(\"STEP 2: Computing the longwave radiation fluxes.\\n\");\n\n        const int n_ang = input_nc.get_variable<TF>(\"angle\");\n\n        Array<TF,2> flux_up ({n_col, n_lev});\n        Array<TF,2> flux_dn ({n_col, n_lev});\n        Array<TF,2> flux_net({n_col, n_lev});\n\n        Array<TF,3> bnd_flux_up ({n_col, n_lev, n_bnd});\n        Array<TF,3> bnd_flux_dn ({n_col, n_lev, n_bnd});\n        Array<TF,3> bnd_flux_net({n_col, n_lev, n_bnd});\n\n        auto calc_fluxes_subset = [&](\n                const int col_s_in, const int col_e_in,\n                const std::unique_ptr<Optical_props_arry<TF>>& optical_props_subset_in,\n                const Source_func_lw<TF>& sources_subset_in,\n                const Array<TF,2> emis_sfc_subset_in,\n                std::unique_ptr<Fluxes_broadband<TF>>& fluxes_subset_in)\n        {\n            const int n_col_block_subset = col_e_in - col_s_in + 1;\n\n            Array<TF,3> gpt_flux_up({n_col_block_subset, n_lev, n_gpt});\n            Array<TF,3> gpt_flux_dn({n_col_block_subset, n_lev, n_gpt});\n\n            // CvH: I removed the pointer assignments of the fluxes, as this is unportable Fortran code.\n            Rte_lw<TF>::rte_lw(\n                    optical_props_subset_in,\n                    top_at_1,\n                    sources_subset_in,\n                    emis_sfc_subset_in,\n                    Array<TF,2>(), // Add an empty array, no inc_flux.\n                    gpt_flux_up,\n                    gpt_flux_dn,\n                    n_ang);\n\n            fluxes_subset_in->reduce(\n                    gpt_flux_up, gpt_flux_dn, optical_props, top_at_1);\n\n            // Copy the data to the output.\n            for (int ilev=1; ilev<=n_lev; ++ilev)\n                for (int icol=1; icol<=n_col_block_subset; ++icol)\n                {\n                    flux_up ({icol+col_s_in-1, ilev}) = fluxes_subset_in->get_flux_up ()({icol, ilev});\n                    flux_dn ({icol+col_s_in-1, ilev}) = fluxes_subset_in->get_flux_dn ()({icol, ilev});\n                    flux_net({icol+col_s_in-1, ilev}) = fluxes_subset_in->get_flux_net()({icol, ilev});\n                }\n\n            // Copy the data to the output.\n            for (int ibnd=1; ibnd<=n_bnd; ++ibnd)\n                for (int ilev=1; ilev<=n_lev; ++ilev)\n                    for (int icol=1; icol<=n_col_block_subset; ++icol)\n                    {\n                        bnd_flux_up ({icol+col_s_in-1, ilev, ibnd}) = fluxes_subset_in->get_bnd_flux_up ()({icol, ilev, ibnd});\n                        bnd_flux_dn ({icol+col_s_in-1, ilev, ibnd}) = fluxes_subset_in->get_bnd_flux_dn ()({icol, ilev, ibnd});\n                        bnd_flux_net({icol+col_s_in-1, ilev, ibnd}) = fluxes_subset_in->get_bnd_flux_net()({icol, ilev, ibnd});\n                    }\n        };\n\n        for (int b=1; b<=n_blocks; ++b)\n        {\n            const int col_s = (b-1) * n_col_block + 1;\n            const int col_e =  b    * n_col_block;\n\n            optical_props_subset->get_subset(optical_props, col_s, col_e);\n            sources_subset.get_subset(sources, col_s, col_e);\n\n            Array<TF,2> emis_sfc_subset = emis_sfc.subset({{ {1, n_bnd}, {col_s, col_e} }});\n\n            std::unique_ptr<Fluxes_broadband<TF>> fluxes_subset =\n                    std::make_unique<Fluxes_byband<TF>>(n_col_block, n_lev, n_bnd);\n\n            calc_fluxes_subset(\n                    col_s, col_e,\n                    optical_props_subset,\n                    sources_subset,\n                    emis_sfc_subset,\n                    fluxes_subset);\n        }\n\n        if (n_col_block_left > 0)\n        {\n            const int col_s = n_col - n_col_block_left + 1;\n            const int col_e = n_col;\n\n            // CvH, check for reuse of this field.\n            Source_func_lw<TF> sources_left(n_col_block_left, n_lay, kdist);\n\n            optical_props_left->get_subset(optical_props, col_s, col_e);\n            sources_left.get_subset(sources, col_s, col_e);\n\n            Array<TF,2> emis_sfc_left = emis_sfc.subset({{ {1, n_bnd}, {col_s, col_e} }});\n\n            std::unique_ptr<Fluxes_broadband<TF>> fluxes_left =\n                    std::make_unique<Fluxes_byband<TF>>(n_col_block_left, n_lev, n_bnd);\n\n            calc_fluxes_subset(\n                    col_s, col_e,\n                    optical_props_left,\n                    sources_left,\n                    emis_sfc_left,\n                    fluxes_left);\n        }\n\n\n        ////// SAVING THE MODEL OUTPUT //////\n        master.print_message(\"STEP 3: Saving the output to NetCDF.\\n\");\n\n        // Save the output of the optical solver to disk.\n        Netcdf_file output_nc(master, \"test_rrtmgp_output.nc\", Netcdf_mode::Create);\n        output_nc.add_dimension(\"col\", n_col);\n        output_nc.add_dimension(\"lay\", n_lay);\n        output_nc.add_dimension(\"lev\", n_lev);\n        output_nc.add_dimension(\"gpt\", n_gpt);\n        output_nc.add_dimension(\"band\", n_bnd);\n        output_nc.add_dimension(\"pair\", 2);\n\n        // WARNING: The storage in the NetCDF interface uses C-ordering and indexing.\n        // First, store the optical properties.\n        auto nc_band_lims_wvn = output_nc.add_variable<TF>(\"band_lims_wvn\", {\"band\", \"pair\"});\n        auto nc_band_lims_gpt = output_nc.add_variable<int>   (\"band_lims_gpt\", {\"band\", \"pair\"});\n        auto nc_tau = output_nc.add_variable<TF>(\"tau\", {\"gpt\", \"lay\", \"col\"});\n\n        nc_band_lims_wvn.insert(optical_props->get_band_lims_wavenumber().v(), {0, 0});\n        nc_band_lims_gpt.insert(optical_props->get_band_lims_gpoint().v()    , {0, 0});\n        nc_tau.insert(optical_props->get_tau().v(), {0, 0, 0});\n\n        // Second, store the sources.\n        auto nc_lay_src     = output_nc.add_variable<TF>(\"lay_src\"    , {\"gpt\", \"lay\", \"col\"});\n        auto nc_lev_src_inc = output_nc.add_variable<TF>(\"lev_src_inc\", {\"gpt\", \"lay\", \"col\"});\n        auto nc_lev_src_dec = output_nc.add_variable<TF>(\"lev_src_dec\", {\"gpt\", \"lay\", \"col\"});\n\n        auto nc_sfc_src = output_nc.add_variable<TF>(\"sfc_src\", {\"gpt\", \"col\"});\n\n        nc_lay_src.insert    (sources.get_lay_source().v()    , {0, 0, 0});\n        nc_lev_src_inc.insert(sources.get_lev_source_inc().v(), {0, 0, 0});\n        nc_lev_src_dec.insert(sources.get_lev_source_dec().v(), {0, 0, 0});\n\n        nc_sfc_src.insert(sources.get_sfc_source().v(), {0, 0});\n\n        // Save the output of the flux calculation to disk.\n        auto nc_flux_up  = output_nc.add_variable<TF>(\"flux_up\" , {\"lev\", \"col\"});\n        auto nc_flux_dn  = output_nc.add_variable<TF>(\"flux_dn\" , {\"lev\", \"col\"});\n        auto nc_flux_net = output_nc.add_variable<TF>(\"flux_net\", {\"lev\", \"col\"});\n\n        auto nc_bnd_flux_up  = output_nc.add_variable<TF>(\"bnd_flux_up\" , {\"band\", \"lev\", \"col\"});\n        auto nc_bnd_flux_dn  = output_nc.add_variable<TF>(\"bnd_flux_dn\" , {\"band\", \"lev\", \"col\"});\n        auto nc_bnd_flux_net = output_nc.add_variable<TF>(\"bnd_flux_net\", {\"band\", \"lev\", \"col\"});\n\n        nc_flux_up .insert(flux_up .v(), {0, 0});\n        nc_flux_dn .insert(flux_dn .v(), {0, 0});\n        nc_flux_net.insert(flux_net.v(), {0, 0});\n\n        nc_bnd_flux_up .insert(bnd_flux_up .v(), {0, 0, 0});\n        nc_bnd_flux_dn .insert(bnd_flux_dn .v(), {0, 0, 0});\n        nc_bnd_flux_net.insert(bnd_flux_net.v(), {0, 0, 0});\n    }\n    else\n    {\n        ////// SOLVING THE OPTICAL PROPERTIES FOR SHORTWAVE RADIATION //////\n        master.print_message(\"STEP 1: Computing optical depths for shortwave radiation.\\n\");\n\n        // Read the boundary conditions from disk.\n        sza.set_dims({n_col});\n        tsi.set_dims({n_col});\n        sfc_alb_dir.set_dims({n_bnd, n_col});\n        sfc_alb_dif.set_dims({n_bnd, n_col});\n\n        sza = input_nc.get_variable<TF>(\"solar_zenith_angle\", {n_col});\n        tsi = input_nc.get_variable<TF>(\"total_solar_irradiance\", {n_col});\n        sfc_alb_dir = input_nc.get_variable<TF>(\"sfc_alb_direct\" , {n_col, n_bnd});\n        sfc_alb_dif = input_nc.get_variable<TF>(\"sfc_alb_diffuse\", {n_col, n_bnd});\n\n        TF tsi_scaling = -999.;\n        if (input_nc.variable_exists(\"tsi_scaling\"))\n            tsi_scaling = input_nc.get_variable<TF>(\"tsi_scaling\");\n\n        Array<TF,1> mu0({n_col});\n        for (int icol=1; icol<=n_col; ++icol)\n        {\n            const TF pi = std::atan(1.)*4.;\n            mu0({icol}) = std::cos(sza({icol}) * pi/180.);\n        }\n\n        Array<TF,2> toa_src({n_col, n_gpt});\n\n        // Read the sources and create containers for the substeps.\n        int n_blocks = n_col / n_col_block;\n        int n_col_block_left = n_col % n_col_block;\n\n        optical_props        = std::make_unique<Optical_props_2str<TF>>(n_col      , n_lay, kdist);\n        optical_props_subset = std::make_unique<Optical_props_2str<TF>>(n_col_block, n_lay, kdist);\n\n        auto calc_optical_props_subset = [&](\n                const int col_s_in, const int col_e_in,\n                std::unique_ptr<Optical_props_arry<TF>>& optical_props_subset_in)\n        {\n            const int n_col_in = col_e_in - col_s_in + 1;\n            Gas_concs<TF> gas_concs_subset(gas_concs, col_s_in, n_col_in);\n            Array<TF,2> toa_src_subset({n_col_in, n_gpt});\n\n            kdist.gas_optics(\n                    p_lay.subset({{ {col_s_in, col_e_in}, {1, n_lay} }}),\n                    p_lev.subset({{ {col_s_in, col_e_in}, {1, n_lev} }}),\n                    t_lay.subset({{ {col_s_in, col_e_in}, {1, n_lay} }}),\n                    gas_concs_subset,\n                    optical_props_subset_in,\n                    toa_src_subset,\n                    col_dry.subset({{ {col_s_in, col_e_in}, {1, n_lay} }}) );\n\n            optical_props->set_subset(optical_props_subset_in, col_s_in, col_e_in);\n\n            // Copy the data to the output.\n            for (int igpt=1; igpt<=n_gpt; ++igpt)\n                for (int icol=1; icol<=n_col_in; ++icol)\n                    toa_src({icol+col_s_in-1, igpt}) = toa_src_subset({icol, igpt});\n        };\n\n        for (int b=1; b<=n_blocks; ++b)\n        {\n            const int col_s = (b-1) * n_col_block + 1;\n            const int col_e =  b    * n_col_block;\n\n            calc_optical_props_subset(\n                    col_s, col_e,\n                    optical_props_subset);\n        }\n\n        if (n_col_block_left > 0)\n        {\n            optical_props_left = std::make_unique<Optical_props_2str<TF>>(n_col_block_left, n_lay, kdist);\n\n            const int col_s = n_col - n_col_block_left + 1;\n            const int col_e = n_col;\n\n            calc_optical_props_subset(\n                    col_s, col_e,\n                    optical_props_left);\n        }\n\n\n        ////// SOLVING THE FLUXES FOR SHORTWAVE RADIATION //////\n        master.print_message(\"STEP 2: Computing the shortwave radiation fluxes.\\n\");\n\n        Array<TF,2> flux_up    ({n_col, n_lev});\n        Array<TF,2> flux_dn    ({n_col, n_lev});\n        Array<TF,2> flux_dn_dir({n_col, n_lev});\n        Array<TF,2> flux_net   ({n_col, n_lev});\n\n        Array<TF,3> bnd_flux_up    ({n_col, n_lev, n_bnd});\n        Array<TF,3> bnd_flux_dn    ({n_col, n_lev, n_bnd});\n        Array<TF,3> bnd_flux_dn_dir({n_col, n_lev, n_bnd});\n        Array<TF,3> bnd_flux_net   ({n_col, n_lev, n_bnd});\n\n        auto calc_fluxes_subset = [&](\n                const int col_s_in, const int col_e_in,\n                const std::unique_ptr<Optical_props_arry<TF>>& optical_props_subset_in,\n                const Array<TF,1>& mu0_subset_in,\n                const Array<TF,2>& toa_src_subset_in,\n                const Array<TF,2>& sfc_alb_dir_subset_in,\n                const Array<TF,2>& sfc_alb_dif_subset_in,\n                std::unique_ptr<Fluxes_broadband<TF>>& fluxes_subset_in)\n        {\n            const int n_col_block_subset = col_e_in - col_s_in + 1;\n\n            Array<TF,3> gpt_flux_up    ({n_col_block_subset, n_lev, n_gpt});\n            Array<TF,3> gpt_flux_dn    ({n_col_block_subset, n_lev, n_gpt});\n            Array<TF,3> gpt_flux_dn_dir({n_col_block_subset, n_lev, n_gpt});\n\n            Rte_sw<TF>::rte_sw(\n                    optical_props_subset_in,\n                    top_at_1,\n                    mu0_subset_in,\n                    toa_src_subset_in,\n                    sfc_alb_dir_subset_in,\n                    sfc_alb_dif_subset_in,\n                    Array<TF,2>(), // Add an empty array, no inc_flux.\n                    gpt_flux_up,\n                    gpt_flux_dn,\n                    gpt_flux_dn_dir);\n\n            fluxes_subset_in->reduce(\n                    gpt_flux_up, gpt_flux_dn, gpt_flux_dn,\n                    optical_props_subset_in, top_at_1);\n\n            // Copy the data to the output.\n            for (int ilev=1; ilev<=n_lev; ++ilev)\n                for (int icol=1; icol<=n_col_block_subset; ++icol)\n                {\n                    flux_up    ({icol+col_s_in-1, ilev}) = fluxes_subset_in->get_flux_up    ()({icol, ilev});\n                    flux_dn    ({icol+col_s_in-1, ilev}) = fluxes_subset_in->get_flux_dn    ()({icol, ilev});\n                    flux_dn_dir({icol+col_s_in-1, ilev}) = fluxes_subset_in->get_flux_dn_dir()({icol, ilev});\n                    flux_net   ({icol+col_s_in-1, ilev}) = fluxes_subset_in->get_flux_net   ()({icol, ilev});\n                }\n\n            // Copy the data to the output.\n            for (int ibnd=1; ibnd<=n_bnd; ++ibnd)\n                for (int ilev=1; ilev<=n_lev; ++ilev)\n                    for (int icol=1; icol<=n_col_block_subset; ++icol)\n                    {\n                        bnd_flux_up    ({icol+col_s_in-1, ilev, ibnd}) = fluxes_subset_in->get_bnd_flux_up    ()({icol, ilev, ibnd});\n                        bnd_flux_dn    ({icol+col_s_in-1, ilev, ibnd}) = fluxes_subset_in->get_bnd_flux_dn    ()({icol, ilev, ibnd});\n                        bnd_flux_dn_dir({icol+col_s_in-1, ilev, ibnd}) = fluxes_subset_in->get_bnd_flux_dn_dir()({icol, ilev, ibnd});\n                        bnd_flux_net   ({icol+col_s_in-1, ilev, ibnd}) = fluxes_subset_in->get_bnd_flux_net   ()({icol, ilev, ibnd});\n                    }\n        };\n\n        for (int b=1; b<=n_blocks; ++b)\n        {\n            const int col_s = (b-1) * n_col_block + 1;\n            const int col_e =  b    * n_col_block;\n\n            optical_props_subset->get_subset(optical_props, col_s, col_e);\n\n            Array<TF,1> mu0_subset = mu0.subset({{ {col_s, col_e} }});\n            Array<TF,2> toa_src_subset = toa_src.subset({{ {col_s, col_e}, {1, n_gpt} }});\n            Array<TF,2> sfc_alb_dir_subset = sfc_alb_dir.subset({{ {1, n_bnd}, {col_s, col_e} }});\n            Array<TF,2> sfc_alb_dif_subset = sfc_alb_dif.subset({{ {1, n_bnd}, {col_s, col_e} }});\n\n            std::unique_ptr<Fluxes_broadband<TF>> fluxes_subset =\n                    std::make_unique<Fluxes_byband<TF>>(n_col_block, n_lev, n_bnd);\n\n            calc_fluxes_subset(\n                    col_s, col_e,\n                    optical_props_subset,\n                    mu0_subset,\n                    toa_src_subset,\n                    sfc_alb_dir_subset,\n                    sfc_alb_dif_subset,\n                    fluxes_subset);\n        }\n\n        if (n_col_block_left > 0)\n        {\n            const int col_s = n_col - n_col_block_left + 1;\n            const int col_e = n_col;\n\n            optical_props_left->get_subset(optical_props, col_s, col_e);\n\n            Array<TF,1> mu0_left = mu0.subset({{ {col_s, col_e} }});\n            Array<TF,2> toa_src_left = toa_src.subset({{ {col_s, col_e}, {1, n_gpt} }});\n            Array<TF,2> sfc_alb_dir_left = sfc_alb_dir.subset({{ {1, n_bnd}, {col_s, col_e} }});\n            Array<TF,2> sfc_alb_dif_left = sfc_alb_dif.subset({{ {1, n_bnd}, {col_s, col_e} }});\n\n            std::unique_ptr<Fluxes_broadband<TF>> fluxes_left =\n                    std::make_unique<Fluxes_byband<TF>>(n_col_block_left, n_lev, n_bnd);\n\n            calc_fluxes_subset(\n                    col_s, col_e,\n                    optical_props_left,\n                    mu0_left,\n                    toa_src_left,\n                    sfc_alb_dir_left,\n                    sfc_alb_dif_left,\n                    fluxes_left);\n        }\n\n\n        ////// SAVING THE MODEL OUTPUT //////\n        master.print_message(\"STEP 3: Saving the output to NetCDF.\\n\");\n\n        // Save the output of the optical solver to disk.\n        Netcdf_file output_nc(master, \"test_rrtmgp_output.nc\", Netcdf_mode::Create);\n        output_nc.add_dimension(\"col\", n_col);\n        output_nc.add_dimension(\"lay\", n_lay);\n        output_nc.add_dimension(\"lev\", n_lev);\n        output_nc.add_dimension(\"gpt\", n_gpt);\n        output_nc.add_dimension(\"band\", n_bnd);\n        output_nc.add_dimension(\"pair\", 2);\n\n        // WARNING: The storage in the NetCDF interface uses C-ordering and indexing.\n        // First, store the optical properties.\n        auto nc_band_lims_wvn = output_nc.add_variable<TF> (\"band_lims_wvn\", {\"band\", \"pair\"});\n        auto nc_band_lims_gpt = output_nc.add_variable<int>(\"band_lims_gpt\", {\"band\", \"pair\"});\n        auto nc_tau = output_nc.add_variable<TF>(\"tau\", {\"gpt\", \"lay\", \"col\"});\n        auto nc_ssa = output_nc.add_variable<TF>(\"ssa\", {\"gpt\", \"lay\", \"col\"});\n        auto nc_g   = output_nc.add_variable<TF>(\"g\"  , {\"gpt\", \"lay\", \"col\"});\n\n        nc_band_lims_wvn.insert(optical_props->get_band_lims_wavenumber().v(), {0, 0});\n        nc_band_lims_gpt.insert(optical_props->get_band_lims_gpoint().v()    , {0, 0});\n\n        nc_tau.insert(optical_props->get_tau().v(), {0, 0, 0});\n        nc_ssa.insert(optical_props->get_ssa().v(), {0, 0, 0});\n        nc_g  .insert(optical_props->get_g  ().v(), {0, 0, 0});\n\n        auto nc_toa_src = output_nc.add_variable<TF>(\"toa_src\", {\"gpt\", \"col\"});\n        nc_toa_src.insert(toa_src.v(), {0, 0});\n\n        // Save the output of the flux calculation to disk.\n        auto nc_flux_up     = output_nc.add_variable<TF>(\"flux_up\"    , {\"lev\", \"col\"});\n        auto nc_flux_dn     = output_nc.add_variable<TF>(\"flux_dn\"    , {\"lev\", \"col\"});\n        auto nc_flux_dn_dir = output_nc.add_variable<TF>(\"flux_dn_dir\", {\"lev\", \"col\"});\n        auto nc_flux_net    = output_nc.add_variable<TF>(\"flux_net\"   , {\"lev\", \"col\"});\n\n        auto nc_bnd_flux_up     = output_nc.add_variable<TF>(\"bnd_flux_up\"    , {\"band\", \"lev\", \"col\"});\n        auto nc_bnd_flux_dn     = output_nc.add_variable<TF>(\"bnd_flux_dn\"    , {\"band\", \"lev\", \"col\"});\n        auto nc_bnd_flux_dn_dir = output_nc.add_variable<TF>(\"bnd_flux_dn_dir\", {\"band\", \"lev\", \"col\"});\n        auto nc_bnd_flux_net    = output_nc.add_variable<TF>(\"bnd_flux_net\"   , {\"band\", \"lev\", \"col\"});\n\n        nc_flux_up    .insert(flux_up    .v(), {0, 0});\n        nc_flux_dn    .insert(flux_dn    .v(), {0, 0});\n        nc_flux_dn_dir.insert(flux_dn_dir.v(), {0, 0});\n        nc_flux_net   .insert(flux_net   .v(), {0, 0});\n\n        nc_bnd_flux_up    .insert(bnd_flux_up    .v(), {0, 0, 0});\n        nc_bnd_flux_dn    .insert(bnd_flux_dn    .v(), {0, 0, 0});\n        nc_bnd_flux_dn_dir.insert(bnd_flux_dn_dir.v(), {0, 0, 0});\n        nc_bnd_flux_net   .insert(bnd_flux_net   .v(), {0, 0, 0});\n    }\n}\n\nint main()\n{\n    Master master;\n    try\n    {\n        master.start();\n        master.init();\n\n        solve_radiation<FLOAT_TYPE>(master);\n    }\n\n    // Catch any exceptions and return 1.\n    catch (const std::exception& e)\n    {\n        master.print_message(\"EXCEPTION: %s\\n\", e.what());\n        return 1;\n    }\n    catch (...)\n    {\n        master.print_message(\"UNHANDLED EXCEPTION!\\n\");\n        return 1;\n    }\n\n    // Return 0 in case of normal exit.\n    return 0;\n}\n", "meta": {"hexsha": "092b9f382e68a205924a0b025a3e1634663b7986", "size": 37461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src_test/test_rrtmgp.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_test/test_rrtmgp.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_test/test_rrtmgp.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": 43.4078794902, "max_line_length": 133, "alphanum_fraction": 0.5824190491, "num_tokens": 10144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.033085978865411605, "lm_q1q2_score": 0.013477024265095897}}
{"text": "//   GAMBIT: Global and Modular BSM Inference Tool\n//   *********************************************\n///  \\file\n///\n///  Frontend for CalcHEP Backend\n///\n///  *********************************************\n///\n///  Authors (add name and date if you modify):\n///\n///  \\author Sanjay Bloor\n///          (sanjay.bloor12@imperial.ac.uk)\n///  \\date 2017 May, Oct\n///        2018 Sep\n///\n///  *****************************************\n\n#include <fstream>\n#include <boost/algorithm/string/replace.hpp>\n\n#include \"gambit/Backends/frontend_macros.hpp\"\n#include \"gambit/Models/partmap.hpp\"\n#include \"gambit/Backends/frontends/CalcHEP_3_6_27.hpp\"\n#include \"gambit/Models/SpectrumContents/RegisteredSpectra.hpp\"\n#include \"gambit/Elements/decay_table.hpp\"\n\n#include \"gambit/Utils/mpiwrapper.hpp\"\n\n#include <unistd.h>\n\nBE_INI_FUNCTION\n{\n\n  // Scan-level.\n  static bool scan_level = true;\n\n  if (scan_level)\n  {\n    // Declare backend path variables\n    str BEpath;\n    const char *path;\n    char *modeltoset;\n    std::string model;\n\n    // All decays and xsecs added to a new model\n    std::map< str, std::vector< std::vector<str> > > decays;\n    std::map< std::vector<str>, std::vector< std::vector<str> > > xsecs;\n\n    if (ModelInUse(\"ScalarSingletDM_Z2\"))\n    {\n      // Set model within CalcHEP\n      BEpath = backendDir + \"/../models/ScalarSingletDM_Z2\";\n      path = BEpath.c_str();\n      modeltoset = (char*)malloc(strlen(path)+11);\n      sprintf(modeltoset, \"%s\", path);\n\n      decays[\"h\"] = std::vector< std::vector<str> >{ {\"~S\",\"~S\"} };\n      xsecs[std::vector<str>{\"~S\",\"~S\"}] = std::vector< std::vector<str> >{ {\"d'\", \"D'\"}, {\"u\", \"U\"}, {\"B\", \"b\"}, {\"h\", \"h\"}, {\"e\", \"E\"}, {\"Z\", \"Z\"}, {\"c\", \"C\"}, {\"s'\", \"S'\"}, {\"m\", \"M\"}, {\"t\", \"T\"}, {\"W+\", \"W-\"}, {\"ta+\", \"ta-\"} };\n      model = \"ScalarSingletDM_Z2\";\n    }\n\n    int error = setModel(modeltoset, 1);\n    if (error != 0) backend_error().raise(LOCAL_INFO, \"Unable to set model\" + std::string(modeltoset) +\n          \" in CalcHEP. CalcHEP error code: \" + std::to_string(error) + \". Please check your model files.\\n\");\n\n    // Get the MPI rank, only let the first rank make the processes...\n    int rank = 0;\n    #ifdef WITH_MPI\n      rank = GMPI::Comm().Get_rank();\n    #endif\n\n    // rank 0 can create all the libraries\n    if (rank == 0)\n    {\n      // Decays first\n      for (auto d : decays)\n        for (auto fs : d.second)\n          generate_decay_code(model, d.first, fs);\n\n      // And two to twos\n      for (auto x : xsecs)\n        for (auto fs : x.second)\n          generate_xsec_code(model, x.first, fs);\n    }\n    #ifdef WITH_MPI\n      // Wait here until the first rank has generated all matrix elements.\n      MPI_Barrier(MPI_COMM_WORLD);\n    #endif\n\n    free(modeltoset);\n  }\n\n  // Point-level.\n  scan_level = false;\n\n  if (ModelInUse(\"ScalarSingletDM_Z2\"))\n  {\n    // Obtain model contents\n    static const SpectrumContents::ScalarSingletDM_Z2 ScalarSingletDM_Z2_contents;\n\n    // Obtain list of all parameters within model\n    static const std::vector<SpectrumParameter> ScalarSingletDM_Z2_params = ScalarSingletDM_Z2_contents.all_parameters();\n\n    // Obtain spectrum information to pass to CalcHEP\n    const Spectrum& spec = *Dep::ScalarSingletDM_Z2_spectrum;\n\n    Assign_All_Values(spec, ScalarSingletDM_Z2_params);\n  }\n\n}\nEND_BE_INI_FUNCTION\n\nBE_NAMESPACE\n{\n  /// Create matrix element code for a decay\n  numout* generate_decay_code(str model, str in, std::vector<str> out)\n  {\n    // Generate process from in and out states\n    char *process = new char[(in + \" -> \" + out[0] + \",\" + out[1]).length() + 1];\n    strcpy(process, (in + \" -> \" + out[0] + \",\" + out[1]).c_str());\n\n    std::string incpy = in;\n    std::string out0cpy = out[0];\n    std::string out1cpy = out[1];\n\n    // Replace any instance of a tilde with \"bar\"\n    boost::replace_all(incpy, \"~\", \"bar\");\n    boost::replace_all(out0cpy, \"~\", \"bar\");\n    boost::replace_all(out1cpy, \"~\", \"bar\");\n\n    // Remove all non-alpha numeric characters from the library names\n    incpy.resize(std::remove_if(incpy.begin(), incpy.end(), [](char x) {return !isalnum(x) && !isspace(x);})-incpy.begin());\n    out0cpy.resize(std::remove_if(out0cpy.begin(), out0cpy.end(), [](char x) {return !isalnum(x) && !isspace(x);})-out0cpy.begin());\n    out1cpy.resize(std::remove_if(out1cpy.begin(), out1cpy.end(), [](char x) {return !isalnum(x) && !isspace(x);})-out1cpy.begin());\n\n    // Generate libname from model and process name\n    char *libname = new char[(model + \"_\" + incpy + \"_to_\" + out0cpy + out1cpy).length() + 1];\n    strcpy(libname, (model + \"_\" + incpy + \"_to_\" + out0cpy + out1cpy).c_str());\n\n    char *excludeVirtual = NULL; // Exclude any internal particles\n    char *excludeOut = NULL;     // Exclude any products\n    int twidth = 0;              // T-channel propagator width\n    int UG = 0;                  // Unitary gauge\n\n    // Generates shared object file based on libName - unless it already exists.\n    numout* cc = getMEcode(twidth, UG, process, excludeVirtual, excludeOut, libname);\n\n    // Release all memory allocated by \"new\" before returning\n    delete process;\n    delete libname;\n\n    return cc;\n  }\n\n  /// For cross-sections, just wrap the decay code\n  numout* generate_xsec_code(str model, std::vector<str> in, std::vector<str> out)\n  {\n    str newin = in[0] + \",\" + in[1];\n    return generate_decay_code(model, newin, out);\n  }\n\n  /// Assigns gambit value to parameter, with error-checking.\n  void Assign_Value(char *parameter, double value)\n  {\n    int error;\n    error = assignVal(parameter, value);\n    if (error != 0) backend_error().raise(LOCAL_INFO, \"Unable to set \" + std::string(parameter) +\n          \" in CalcHEP. CalcHEP error code: \" + std::to_string(error) + \". Please check your model files.\\n\");\n  }\n\n  /// Assigns gambit value to parameter, with error-checking, for parameters that may\n  /// have two different names in CalcHEP, such as alphainv : aEWM1 (FeynRules) / aEWinv (SARAH)\n  void Assign_Value(char *parameter1, char *parameter2, double value)\n  {\n    int error;\n    error = assignVal(parameter1, value);\n    // If name 1 is successful, awesome.\n    if (error == 0) return;\n    // If not, then try the second one\n    error = assignVal(parameter2, value);\n    // If that doesn't work, we can throw an error, eh.\n    if (error != 0) backend_error().raise(LOCAL_INFO, \"Unable to set \" + std::string(parameter1) +\n          \" or \" + std::string(parameter2) + \" in CalcHEP. \" +\n          \" CalcHEP error code: \" + std::to_string(error) + \". Please check your model files.\\n\");\n  }\n\n  /// Takes all parameters in a model, and assigns them by\n  /// value to the appropriate CalcHEP parameter names.\n  void Assign_All_Values(const Spectrum& spec, std::vector<SpectrumParameter> params)\n  {\n    // Iterate through the expected spectrum parameters of the model. Pass the value of pole masses\n    // to CalcHEP from the spectrum, by PDG code.\n    for (auto it = params.begin(); it != params.end(); ++it)\n    {\n      // Don't add the SM vev, Gauge couplings, Yukawas,\n      // as CalcHEP computes these internally.\n      std::list<std::string> doNotAssign = {\"g1\", \"g2\", \"g3\", \"v\", \"Yu\", \"Ye\", \"Yd\", \"sinW2\", \"vev\"};\n\n      // Fetch the iterator of element with the parameter name\n      std::list<std::string>::iterator it2 = std::find(doNotAssign.begin(), doNotAssign.end(), it->name());\n\n      // If we find the parameter in the \"do not assign\" list, then don't try and assign it,\n      // or this will throw an error.\n      if (it2 != doNotAssign.end())\n      {\n        continue;\n      }\n\n      // Pole masses\n      if (it->tag() == Par::Pole_Mass)\n      {\n        // Scalar case\n        if (it->shape()[0] == 1)\n        {\n          std::pair<int,int> PDG_code = Models::ParticleDB().partmap::pdg_pair(it->name());\n          Assign_Value(pdg2mass(PDG_code.first), spec.get(Par::Pole_Mass, PDG_code.first, PDG_code.second));\n        }\n        // Vector case\n        else\n        {\n          for (int i=0; i<it->shape()[0]; ++i)\n          {\n            str long_name = it->name() + \"_\" + std::to_string(i+1);\n            std::pair<int,int> PDG_code = Models::ParticleDB().partmap::pdg_pair(long_name);\n            Assign_Value(pdg2mass(PDG_code.first), spec.get(Par::Pole_Mass, PDG_code.first, PDG_code.second));\n          }\n        }\n        // Ignore any matrix cases, as Par::Pole_Mass should only be scalars or vectors\n      }\n      // Otherwise, should all have the right names\n      else\n      {\n        const SubSpectrum& HE = spec.get_HE();\n\n        // Scalar case\n        if (it->shape().size()==1 and it->shape()[0] == 1)\n        {\n          char *chepname = const_cast<char*> ( it->name().c_str() );\n          Assign_Value(chepname, HE.get(it->tag(), it->name()));\n        }\n        // Vector case\n        else if (it->shape().size()==1 and it->shape()[0] > 1)\n        {\n          for (int i=0; i<it->shape()[0]; ++i)\n          {\n            str long_name = it->name() + std::to_string(i+1);\n            char *chepname = const_cast<char*> ( long_name.c_str() );\n            Assign_Value(chepname, HE.get(it->tag(), it->name(), i+1));\n          }\n        }\n        // Matrix\n        else if(it->shape().size()==2)\n        {\n          for (int i=0; i<it->shape()[0]; ++i)\n          {\n            for (int j=0; j<it->shape()[0]; ++j)\n            {\n              str long_name = it->name() + std::to_string(i+1) + \"x\" + std::to_string(j+1);\n              char *chepname = const_cast<char*> ( long_name.c_str() );\n              Assign_Value(chepname, HE.get(it->tag(), it->name(), i+1, j+1));\n            }\n          }\n        }\n      }\n    }\n\n    // Now go through the input parameters of the model. **NOTE**: this structure will only work for the case\n    // where we want to scan over fundamental Lagrangian parameters. This will change post-SpecBit redesign.\n\n    // Create SMInputs struct from spectrum\n    const SMInputs& sminputs = spec.get_SMInputs();\n\n    // Assign SMInputs\n    Assign_Value((char*)\"Gf\", (char*)\"GF\", sminputs.GF);                    // Fermi\n    Assign_Value((char*)\"aS\", sminputs.alphaS);                             // Strong coupling (unspecified scale if SARAH)\n    Assign_Value((char*)\"alfSMZ\", (char*)\"aS\", sminputs.alphaS);            // Strong coupling (mZ) for both.\n    Assign_Value((char*)\"aEWM1\", (char*)\"aEWinv\", sminputs.alphainv);       // Inverse EM coupling\n\n    // Then, SM particle masses (by PDG code)\n    Assign_Value(pdg2mass(1), sminputs.mD);                        // Down\n    Assign_Value(pdg2mass(2), sminputs.mU);                        // Up\n    Assign_Value(pdg2mass(3), sminputs.mS);                        // Strange\n    Assign_Value(pdg2mass(4), sminputs.mCmC);                      // Charm (mC) MSbar\n    Assign_Value(pdg2mass(11), spec.get(Par::Pole_Mass, \"e-\"));    // Electron\n    Assign_Value(pdg2mass(13), spec.get(Par::Pole_Mass, \"mu-\"));   // Muon\n    Assign_Value(pdg2mass(15), spec.get(Par::Pole_Mass, \"tau-\"));  // Tau\n    Assign_Value(pdg2mass(23), spec.get(Par::Pole_Mass, \"Z0\"));    // Z\n    Assign_Value(pdg2mass(5), spec.get(Par::Pole_Mass, \"d_3\"));    // mB(mB) MSbar\n    Assign_Value(pdg2mass(6), spec.get(Par::Pole_Mass, \"u_3\"));    // mT(mT) MSbar\n  }\n\n  /// Passes the width of each BSM particle in the model, from DecayTable to CalcHEP.\n  /// Don't set the widths of anything SM, except the top, which can get BSM contributions.\n  void Assign_Widths(const DecayTable& tbl)\n  {\n    // Obtain all generic pdg codes. We can't set these widths..\n    const std::vector<std::pair<int, int>> generic_particles = Models::ParticleDB().partmap::get_generic_particles();\n    const std::vector<std::pair<int, int>> SM_particles = Models::ParticleDB().partmap::get_SM_particles();\n\n    // Iterate through DecayTable. If it is not in the generic particles, or the SM, then go for it.\n    for (std::map<std::pair<int, int>, Gambit::DecayTable::Entry>::const_iterator it = tbl.particles.begin();\n          it != tbl.particles.end(); ++it)\n    {\n      if (std::find(generic_particles.begin(), generic_particles.end(), it->first) != generic_particles.end())\n      {\n        continue;\n      }\n      if (std::find(SM_particles.begin(), SM_particles.end(), it->first) != SM_particles.end())\n      {\n        continue;\n      }\n      Assign_Value(pdg2width(it->first.first), tbl.at(it->first).width_in_GeV);\n    }\n    // Assign the top separately as they can have BSM contributions e.g. decaying to charged higgses\n    Assign_Value(pdg2width(6), tbl.at(\"t\").width_in_GeV);\n  }\n\n  /// Provides spin-averaged decay width for 2 body decay process in CM frame at tree-level.\n  // TODO: remove dependence on g3 (for alphaS(mZ)).\n  double CH_Decay_Width(str& model, str& in, std::vector<str>& out)\n  {\n    // Check size of in and out states;\n    if (out.size() != 2) backend_error().raise(LOCAL_INFO, \"Output vector\"\n                        \" must have only 2 entries for a 1 to 2 process.\");\n\n    // Calculates and updates all PUBLIC (model-dependent) parameters. These come from $CALCHEP/aux/VandP.c, generated by setModel() in the INI_FUNCTION.\n    int err = calcMainFunc();\n\n    if(err != 0) backend_error().raise(LOCAL_INFO, \"Unable to calculate parameter \" + std::string(varNames[err]) +\n          \" in CalcHEP. Please check your model files.\\n\");\n\n    // Check if channel is kinematically open before doing anything. No need to compile processes that are not relevant.\n    char *inbound = new char[(in).length() + 1];\n    strcpy(inbound, (in).c_str());\n\n    char *outbound_1 = new char[(out[0]).length() + 1];\n    strcpy(outbound_1, (out[0]).c_str());\n\n    char *outbound_2 = new char[(out[1]).length() + 1];\n    strcpy(outbound_2, (out[1]).c_str());\n\n    // Obtain mass of decaying particle\n    double M =  pMass(inbound);\n    double m1 = pMass(outbound_1);\n    double m2 = pMass(outbound_2);\n\n    // If channel is kinematically closed, return 0.\n    if (m1 + m2 > M) { return 0; }\n\n    // Generate process from in and out states\n    char *process = new char[(in + \" -> \" + out[0] + \",\" + out[1]).length() + 1];\n    strcpy(process, (in + \" -> \" + out[0] + \",\" + out[1]).c_str());\n\n    std::string incpy = in;\n    std::string out0cpy = out[0];\n    std::string out1cpy = out[1];\n\n    // Replace any instance of a tilde with \"bar\"\n    boost::replace_all(incpy, \"~\", \"bar\");\n    boost::replace_all(out0cpy, \"~\", \"bar\");\n    boost::replace_all(out1cpy, \"~\", \"bar\");\n\n    // Remove all non-alpha numeric characters from the library names\n    incpy.resize(std::remove_if(incpy.begin(), incpy.end(), [](char x) {return !isalnum(x) && !isspace(x);})-incpy.begin());\n    out0cpy.resize(std::remove_if(out0cpy.begin(), out0cpy.end(), [](char x) {return !isalnum(x) && !isspace(x);})-out0cpy.begin());\n    out1cpy.resize(std::remove_if(out1cpy.begin(), out1cpy.end(), [](char x) {return !isalnum(x) && !isspace(x);})-out1cpy.begin());\n\n\n    // Generate libname from model and process name\n    char *libname = new char[(model + \"_\" + incpy + \"_to_\" + out0cpy + out1cpy).length() + 1];\n    strcpy(libname, (model + \"_\" + incpy + \"_to_\" + out0cpy + out1cpy).c_str());\n\n    char *excludeVirtual = NULL; // Exclude any internal particles\n    char *excludeOut = NULL;     // Exclude any products\n    int twidth = 0;              // T-channel propagator width\n    int UG = 0;                  // Unitary gauge\n\n    // Generates shared object file based on libName - unless it already exists.\n    numout* cc = getMEcode(twidth, UG, process, excludeVirtual, excludeOut, libname);\n\n    // Export numerical values of parameters to link to dynamical code\n    err=passParameters(cc);\n\n    if(err != 0) backend_error().raise(LOCAL_INFO, \"Unable to calculate parameter \" + std::string(varNames[err]) +\n          \" in CalcHEP. Please check your model files.\\n\");\n\n    // Kinematic factors.\n    double m_plus = m1+m2;\n    double m_minus = m1-m2;\n    double Msquared = M*M;\n    double p = sqrt((Msquared - m_plus*m_plus)*(Msquared - m_minus*m_minus))/(2*M); // Magnitude of momentum in CM frame\n    double E_1 = (Msquared + m1*m1 - m2*m2)/(2*M);                                  // Energy of first particle\n\n    // Momentum vector for decay. This is 3 4-vectors, for the decaying particle and the products, respectively. 1 <--- M ---> 2\n    double pvect[12] = {M, 0, 0, 0, E_1, 0, 0, p, (M-E_1), 0, 0, -p};\n\n    // Compute squared matrix element\n    double matElement = cc -> interface -> sqme(1, 0, pvect, NULL, &err);\n\n    if(err != 0) backend_error().raise(LOCAL_INFO, \"Unable to calculate matrix element associated with \" + std::string(process) +\n          \" in CalcHEP. Please check your model files.\\n\");\n\n    // Compute kinematic prefactor for X -> Y, Z decay\n    double prefactor = p/(8*pi*Msquared);\n\n    // Release all memory allocated by \"new\" before returning\n    delete libname;\n    delete inbound;\n    delete outbound_1;\n    delete outbound_2;\n\n    // Return partial width\n    return prefactor*matElement;\n  }\n\n  /// Computes annihilation cross-section for 2->2 process, DM+DMbar -> X + Y at tree level.\n  /// Coannihilations not currently supported; we require the mass of both in states are equal.\n  double CH_Sigma_V(str& model, std::vector<str>& in, std::vector<str>& out, double& v_rel, const DecayTable& decays)\n  {\n    // Check size of in and out states;\n    if (in.size() != 2 or out.size() != 2) backend_error().raise(LOCAL_INFO, \"Input and output vectors\"\n                        \" must have only 2 entries for a 2 to 2 process.\");\n\n    // Calculates and updates all PUBLIC (model-dependent) parameters. These come from $CALCHEP/aux/VandP.c, generated by setModel() in the INI_FUNCTION.\n    int err = calcMainFunc();\n\n    if(err != 0) backend_error().raise(LOCAL_INFO, \"Unable to calculate parameter \" + std::string(varNames[err]) +\n          \" in CalcHEP. Please check your model files.\\n\");\n\n    // Check if channel is kinematically open before doing anything. No need to compile processes that are not relevant.\n    char *inbound_1 = new char[(in[0]).length() + 1];\n    strcpy(inbound_1, (in[0]).c_str());\n\n    char *inbound_2 = new char[(in[1]).length() + 1];\n    strcpy(inbound_2, (in[1]).c_str());\n\n    char *outbound_1 = new char[(out[0]).length() + 1];\n    strcpy(outbound_1, (out[0]).c_str());\n\n    char *outbound_2 = new char[(out[1]).length() + 1];\n    strcpy(outbound_2, (out[1]).c_str());\n\n    // Obtain mass of in & out states\n    double m_DM = pMass(inbound_1);\n    if (pMass(inbound_2) != m_DM) backend_error().raise(LOCAL_INFO, \"Mass for both in states must be identical for CH_Sigma_V. \"\n                                  \"Coannihilations not currently supported.\");\n    double m3 = pMass(outbound_1);\n    double m4 = pMass(outbound_2);\n\n    // Kinematics (in states)\n    double s = 16*m_DM*m_DM/(4-v_rel*v_rel);\n    double E_cm = sqrt(s);\n    double E_1 = E_cm/2;\n    double E_2 = E_1;\n    double p_in = m_DM*v_rel/(sqrt(4-v_rel*v_rel));\n\n    // Not enough energy for the process. Closed.\n    if (m3+m4 > E_cm) { return 0; }\n\n    // Pass particle widths - for propagators.\n    Assign_Widths(decays);\n\n    // Generate process from in and out states\n    char *process = new char[(in[0]+ \",\" + in[1] + \" -> \" + out[0] + \",\" + out[1]).length() + 1];\n    strcpy(process, (in[0] + \",\" + in[1] + \" -> \" + out[0] + \",\" + out[1]).c_str());\n\n    str DM = in[0]; // Create copy of the string, as we are about to manipulate.\n    str DMbar = in[1];\n\n    // Remove all non-alpha numeric characters from the library names\n    DM.resize(std::remove_if(DM.begin(), DM.end(), [](char x) {return !isalnum(x) && !isspace(x);})-DM.begin());\n    DMbar.resize(std::remove_if(DMbar.begin(), DMbar.end(), [](char x) {return !isalnum(x) && !isspace(x);})-DMbar.begin());\n    out[0].resize(std::remove_if(out[0].begin(), out[0].end(), [](char x) {return !isalnum(x) && !isspace(x);})-out[0].begin());\n    out[1].resize(std::remove_if(out[1].begin(), out[1].end(), [](char x) {return !isalnum(x) && !isspace(x);})-out[1].begin());\n\n    // Generate libname from model and process name\n    char *libname = new char[(model + \"_\" + DM + DMbar + \"_to_\" + out[0] + out[1]).length() + 1];\n    strcpy(libname, (model + \"_\" + DM + DMbar + \"_to_\" + out[0] + out[1]).c_str());\n\n    /// TODO: are these options for the function..?\n    char *excludeVirtual = NULL; // Exclude any internal particles\n    char *excludeOut = NULL;     // Exclude any products\n    int twidth = 0;              // T-channel propagator width\n    int UG = 0;                  // Unitary gauge\n\n    // Generates shared object file based on libName - unless it already exists.\n    numout* cc = getMEcode(twidth, UG, process, excludeVirtual, excludeOut, libname);\n\n    // Release all memory allocated by \"new\" before returning\n    delete libname;\n    delete inbound_1;\n    delete inbound_2;\n    delete outbound_1;\n    delete outbound_2;\n\n    // Export numerical values of parameters to link to dynamical code\n    err=passParameters(cc);\n\n    if(err != 0) backend_error().raise(LOCAL_INFO, \"Unable to calculate parameter \" + std::string(varNames[err]) +\n          \" in CalcHEP. Please check your model files.\\n\");\n\n    // Kinematic factors (out states)\n    double E_3 = (s - (m4*m4) + (m3*m3))/(2*E_cm);\n    double E_4 = E_cm - E_3;\n    double m_out_plus = m3+m4;\n    double m_out_minus = m3-m4;\n    double p_out = sqrt((s - m_out_plus*m_out_plus)*(s - m_out_minus*m_out_minus))/(2*E_cm); // Magnitude of outbound momentum in CM frame\n\n    // Momentum vector for 2->2. This is 4 4-vectors, for particles 1->4 respectively.\n    double pvect[16] = {E_1, 0, 0, p_in, E_2, 0, 0, -p_in, E_3, 0, 0, p_out, E_4, 0, 0, -p_out};\n\n    // Kinematic prefactor\n    double prefactor = p_out/(32*pi*m_DM*s/sqrt(4-v_rel*v_rel));\n\n    // Squared matrix element - f(p(theta)) - to be integrated over.\n    double M_squared = 0.0;\n\n    int numsteps = 200;\n    // Integrate between -1 < cos(theta) < 1\n    for (int i=0; i < numsteps; i++)\n    {\n      double dcos = 2. / numsteps;\n      double cosT = -1 + dcos*i;\n      double sinT = sqrt(1-cosT*cosT);\n      pvect[9] = p_out*sinT;\n      pvect[11] = p_out*cosT;\n      pvect[13] = -pvect[9];\n      pvect[15] = -pvect[11];\n      M_squared += dcos*(cc -> interface -> sqme(1, 0, pvect, NULL, &err)); // dcos * dM_squared/dcos\n    }\n\n    // If we get a negative ME (or a NaN), and the relative velocity is zero, then try\n    // putting in an arbitrarily small value for the velocity.\n    if ((M_squared < 0 or std::isnan(M_squared)) and v_rel == 0.)\n    {\n      // Choose velocity to be non-zero (but effectively zero) to avoid\n      // potential unphysical values for p-wave suppressed xsecs.\n      double newvel = 1e-6;\n\n      logger() << \"Square matrix element returned a negative value, but velocity is zero.\" << std::endl;\n      logger() << \"Trying with v = 1e-6 for final states \" << out[0] << \" \" << out[1] << std::endl;\n\n      // Compute new values for the kinematics\n      s = 16*m_DM*m_DM/(4-newvel*newvel);\n      E_cm = sqrt(s);\n      E_1 = E_cm/2;\n      E_2 = E_1;\n      p_in = m_DM*newvel/(sqrt(4-newvel*newvel));\n      E_3 = (s - (m4*m4) + (m3*m3))/(2*E_cm);\n      E_4 = E_cm - E_3;\n      p_out = sqrt((s - m_out_plus*m_out_plus)*(s - m_out_minus*m_out_minus))/(2*E_cm);\n      pvect[0] = E_1;\n      pvect[3] = p_in;\n      pvect[4] = E_2;\n      pvect[7] = -p_in;\n      pvect[8] = E_3;\n      pvect[9] = p_out;\n      pvect[12] = E_4;\n      pvect[15] = -p_out;\n      prefactor = p_out/(32*pi*m_DM*s/sqrt(4-newvel*newvel));\n\n      M_squared = 0.0;\n\n      // Integrate again.\n      for (int i=0; i < numsteps; i++)\n      {\n        double dcos = 2. / numsteps;\n        double cosT = -1 + dcos*i;\n        double sinT = sqrt(1-cosT*cosT);\n        pvect[9] = p_out*sinT;\n        pvect[11] = p_out*cosT;\n        pvect[13] = -pvect[9];\n        pvect[15] = -pvect[11];\n        M_squared += dcos*(cc -> interface -> sqme(1, 0, pvect, NULL, &err)); // dcos * dM_squared/dcos\n\n      }\n    }\n    // If it's a NaN, throw an error\n    else if (std::isnan(M_squared))\n    {\n      std::ostringstream err;\n      err << \"ERROR: CalcHEP returned a NaN matrix element for the process \"\n          << in[0]  << \" \" << in[1]  << \" to \"\n          << out[0] << \" \" << out[1] << \" for relative velocity \" << v_rel << \".\";\n      backend_error().raise(LOCAL_INFO, err.str());\n    }\n\n    // If it's negative, just return 0. We'll conservatively assume it's just numerical noise.\n    else if (M_squared < 0)\n    {\n      logger() << \"Squared matrix element has returned a negative value from CalcHEP.\" << std::endl;\n      logger() << \"Final states are \" << out[0] << \" \" << out[1] << \" for relative velocity \" << v_rel << std::endl;\n      logger() << \"Returning 0 instead, assuming it's numerical noise from the crude integration.\" << EOM;\n      return 0.;\n    }\n\n    // Total sigma_v\n    return prefactor*M_squared;\n  }\n}\nEND_BE_NAMESPACE\n", "meta": {"hexsha": "5d7f4d59282d5922ad3d664faa1f1c6ca5aa5663", "size": 24812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Backends/src/frontends/CalcHEP_3_6_27.cpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "Backends/src/frontends/CalcHEP_3_6_27.cpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "Backends/src/frontends/CalcHEP_3_6_27.cpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 41.2159468439, "max_line_length": 231, "alphanum_fraction": 0.6046670966, "num_tokens": 7259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.03904829538216083, "lm_q1q2_score": 0.013475773084327307}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"bempp/common/config_ahmed.hpp\"\n#include \"bempp/common/config_trilinos.hpp\"\n#ifdef WITH_AHMED\n\n#include \"discrete_aca_boundary_operator.hpp\"\n#include \"../common/shared_ptr.hpp\"\n\n#include \"ahmed_aux.hpp\"\n#include \"aca_approximate_lu_inverse.hpp\"\n\n#include \"../common/chunk_statistics.hpp\"\n#include \"../common/complex_aux.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/serial_blas_region.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <boost/smart_ptr/shared_ptr.hpp>\n#include <boost/type_traits/is_complex.hpp>\n\n#include <tbb/blocked_range.h>\n#include <tbb/concurrent_queue.h>\n#include <tbb/parallel_reduce.h>\n#include <tbb/task_scheduler_init.h>\n\n#ifdef WITH_TRILINOS\n#include <Thyra_SpmdVectorSpaceDefaultBase.hpp>\n#endif\n\nnamespace Bempp\n{\n\nvoid dumpblcluster(const blcluster* bl, const std::string& indent)\n{\n    std::cout << indent << bl << \" \" << bl->getb1() << \" \" << bl->getb2() << \" \"\n              << bl->getn1() << \" \" << bl->getn2() << \"\\n\";\n    std::string sonIndent = indent + \"  \";\n    for (int r = 0; r < bl->getnrs(); ++r)\n        for (int c = 0; c < bl->getncs(); ++c) {\n            blcluster* son = bl->getson(r, c);\n            if (son)\n                dumpblcluster(son, sonIndent);\n            else\n                std::cout << sonIndent << \"0\\n\";\n        }\n}\n\nnamespace\n{\n\ntemplate <typename ValueType>\nclass MblockMultiplicationLoopBody\n{\n    typedef mblock<typename AhmedTypeTraits<ValueType>::Type> AhmedMblock;\npublic:\n    typedef tbb::concurrent_queue<size_t> LeafClusterIndexQueue;\n\n    MblockMultiplicationLoopBody(\n            TranspositionMode trans,\n            ValueType multiplier,\n            arma::Col<ValueType>& x,\n            arma::Col<ValueType>& y,\n            AhmedLeafClusterArray& leafClusters,\n            boost::shared_array<AhmedMblock*> blocks,\n            LeafClusterIndexQueue& leafClusterIndexQueue,\n            std::vector<ChunkStatistics>& stats) :\n        m_trans(trans),\n        m_multiplier(multiplier), m_x(x), m_local_y(y),\n        m_leafClusters(leafClusters), m_blocks(blocks),\n        m_leafClusterIndexQueue(leafClusterIndexQueue),\n        m_stats(stats)\n    {\n        if (trans != NO_TRANSPOSE && trans != TRANSPOSE &&\n            trans != CONJUGATE_TRANSPOSE)\n            throw std::invalid_argument(\n                \"MblockMultiplicationLoopBody::MblockMultiplicationLoopBody(): \"\n                \"unsupported transposition mode\");\n        // m_local_y.fill(static_cast<ValueType>(0.));\n    }\n\n    MblockMultiplicationLoopBody(MblockMultiplicationLoopBody& other, tbb::split) :\n        m_trans(other.m_trans),\n        m_multiplier(other.m_multiplier),\n        m_x(other.m_x), m_local_y(other.m_local_y.n_rows),\n        m_leafClusters(other.m_leafClusters), m_blocks(other.m_blocks),\n        m_leafClusterIndexQueue(other.m_leafClusterIndexQueue),\n        m_stats(other.m_stats)\n    {\n        m_local_y.fill(static_cast<ValueType>(0.));\n    }\n\n    template <typename Range>\n    void operator() (const Range& r) {\n        for (typename Range::const_iterator i = r.begin(); i != r.end(); ++i) {\n            size_t leafClusterIndex = -1;\n            if (!m_leafClusterIndexQueue.try_pop(leafClusterIndex)) {\n                std::cerr << \"MblockMultiplicationLoopBody::operator(): \"\n                             \"Warning: try_pop failed; this shouldn't happen!\"\n                          << std::endl;\n                continue;\n            }\n            m_stats[leafClusterIndex].valid = true;\n            m_stats[leafClusterIndex].chunkStart = r.begin();\n            m_stats[leafClusterIndex].chunkSize = r.size();\n            m_stats[leafClusterIndex].startTime = tbb::tick_count::now();\n\n            blcluster* cluster = m_leafClusters[leafClusterIndex];\n            if (m_trans == NO_TRANSPOSE)\n                m_blocks[cluster->getidx()]->mltaVec(\n                    ahmedCast(m_multiplier),\n                    ahmedCast(&m_x(cluster->getb2())),\n                    ahmedCast(&m_local_y(cluster->getb1())));\n            else if (m_trans == TRANSPOSE)\n                m_blocks[cluster->getidx()]->mltatVec(\n                    ahmedCast(m_multiplier),\n                    ahmedCast(&m_x(cluster->getb1())),\n                    ahmedCast(&m_local_y(cluster->getb2())));\n            else // m_trans == CONJUGATE_TRANSPOSE)\n                m_blocks[cluster->getidx()]->mltahVec(\n                    ahmedCast(m_multiplier),\n                    ahmedCast(&m_x(cluster->getb1())),\n                    ahmedCast(&m_local_y(cluster->getb2())));\n            m_stats[leafClusterIndex].endTime = tbb::tick_count::now();\n        }\n    }\n\n    void join(const MblockMultiplicationLoopBody& other) {\n        m_local_y += other.m_local_y;\n    }\n\nprivate:\n    TranspositionMode m_trans;\n    ValueType m_multiplier;\n    arma::Col<ValueType>& m_x;\npublic:\n    arma::Col<ValueType> m_local_y;\nprivate:\n    AhmedLeafClusterArray& m_leafClusters;\n    boost::shared_array<AhmedMblock*> m_blocks;\n    LeafClusterIndexQueue& m_leafClusterIndexQueue;\n    std::vector<ChunkStatistics>& m_stats;\n};\n\nbool areEqual(const blcluster* op1, const blcluster* op2)\n{\n    if (!op1 || !op2)\n        return (!op1 && !op2);\n    if (op1->getnrs() != op2->getnrs() || op1->getncs() != op2->getncs())\n        return false;\n    if (op1->isleaf())\n        return (op1->getb1() == op2->getb1() && op1->getb2() == op2->getb2() &&\n                op1->getn1() == op2->getn1() && op1->getn2() == op2->getn2());\n    for (unsigned int rs = 0; rs < op1->getnrs(); ++rs)\n        for (unsigned int cs = 0; cs < op1->getncs(); ++cs)\n            if (!areEqual(op1->getson(rs, cs), op2->getson(rs, cs)))\n                return false;\n    return true;\n}\n\ninline void mltaSyHVec(double d, blcluster* bl, mblock<double>** A, double* x,\n                       double* y)\n{\n    mltaHeHVec(d, bl, A, x, y);\n}\n\ninline void mltaSyHVec(float d, blcluster* bl, mblock<float>** A, float* x,\n                       float* y)\n{\n    mltaHeHVec(d, bl, A, x, y);\n}\n\ninline void mltaSyHVec(scomp d, blcluster* bl, mblock<scomp>** A, scomp* x,\n                       scomp* y)\n{\n    throw std::runtime_error(\"mltaSyHVec(): the overload of this function for \"\n                             \"complex single-precision numbers does not exist \"\n                             \"in AHMED\");\n}\n\n// For real types, SyHh = SyH\ninline void mltaSyHhVec(double d, blcluster* bl, mblock<double>** A, double* x,\n                        double* y)\n{\n    mltaSyHVec(d, bl, A, x, y);\n}\n\ninline void mltaSyHhVec(float d, blcluster* bl, mblock<float>** A, float* x,\n                        float* y)\n{\n    mltaSyHVec(d, bl, A, x, y);\n}\n\ninline void mltaSyHhVec(scomp d, blcluster* bl, mblock<scomp>** A, scomp* x,\n                        scomp* y)\n{\n    throw std::runtime_error(\"mltaSyHhVec(): the overload of this function for \"\n                             \"complex single-precision numbers does not exist \"\n                             \"in AHMED\");\n}\n\n} // namespace\n\ntemplate <typename ValueType>\nDiscreteAcaBoundaryOperator<ValueType>::\nDiscreteAcaBoundaryOperator(\n        unsigned int rowCount, unsigned int columnCount,\n        double eps_,\n        int maximumRank_,\n        int symmetry_,\n        const shared_ptr<const AhmedBemBlcluster>& blockCluster_,\n        const AhmedMblockArray& blocks_,\n        const IndexPermutation& domainPermutation_,\n        const IndexPermutation& rangePermutation_,\n        const ParallelizationOptions& parallelizationOptions_,\n        const std::vector<AhmedConstMblockArray>& sharedBlocks_) :\n#ifdef WITH_TRILINOS\n    m_domainSpace(Thyra::defaultSpmdVectorSpace<ValueType>(columnCount)),\n    m_rangeSpace(Thyra::defaultSpmdVectorSpace<ValueType>(rowCount)),\n#else\n    m_rowCount(rowCount), m_columnCount(columnCount),\n#endif\n    m_eps(eps_),\n    m_maximumRank(maximumRank_),\n    m_symmetry(symmetry_),\n    m_blockCluster(blockCluster_), m_blocks(blocks_),\n    m_domainPermutation(domainPermutation_),\n    m_rangePermutation(rangePermutation_),\n    m_parallelizationOptions(parallelizationOptions_),\n    m_sharedBlocks(sharedBlocks_)\n{\n    if (eps_ <= 0 || eps_ > 1)\n        std::cout << \"DiscreteAcaBoundaryOperator::DiscreteAcaBoundaryOperator(): \"\n                     \"warning: suspicious value of eps (\"\n                  << eps_ << \")\" << std::endl;\n    if (maximumRank_ < 0)\n        std::cout << \"DiscreteAcaBoundaryOperator::DiscreteAcaBoundaryOperator(): \"\n                     \"warning: suspicious value of maximumRank (\"\n                  << maximumRank_ << \")\" << std::endl;\n}\n\ntemplate <typename ValueType>\nDiscreteAcaBoundaryOperator<ValueType>::\nDiscreteAcaBoundaryOperator(\n        unsigned int rowCount, unsigned int columnCount,\n        int maximumRank_,\n        int symmetry_,\n        std::auto_ptr<const AhmedBemBlcluster> blockCluster_,\n        AhmedMblockArray blocks_,\n        const IndexPermutation& domainPermutation_,\n        const IndexPermutation& rangePermutation_,\n        const ParallelizationOptions& parallelizationOptions_,\n        const std::vector<AhmedConstMblockArray>& sharedBlocks_) :\n#ifdef WITH_TRILINOS\n    m_domainSpace(Thyra::defaultSpmdVectorSpace<ValueType>(columnCount)),\n    m_rangeSpace(Thyra::defaultSpmdVectorSpace<ValueType>(rowCount)),\n#else\n    m_rowCount(rowCount), m_columnCount(columnCount),\n#endif\n    m_eps(1e-4), // just a guess...\n    m_maximumRank(maximumRank_),\n    m_symmetry(symmetry_),\n    m_blockCluster(blockCluster_.release()), m_blocks(blocks_),\n    m_domainPermutation(domainPermutation_),\n    m_rangePermutation(rangePermutation_),\n    m_parallelizationOptions(parallelizationOptions_),\n    m_sharedBlocks(sharedBlocks_)\n{\n}\n\ntemplate <typename ValueType>\nDiscreteAcaBoundaryOperator<ValueType>::\nDiscreteAcaBoundaryOperator(\n        unsigned int rowCount, unsigned int columnCount,\n        int maximumRank_,\n        int symmetry_,\n        const shared_ptr<const AhmedBemBlcluster>& blockCluster_,\n        const AhmedMblockArray& blocks_,\n        const IndexPermutation& domainPermutation_,\n        const IndexPermutation& rangePermutation_,\n        const ParallelizationOptions& parallelizationOptions_,\n        const std::vector<AhmedConstMblockArray>& sharedBlocks_) :\n#ifdef WITH_TRILINOS\n    m_domainSpace(Thyra::defaultSpmdVectorSpace<ValueType>(columnCount)),\n    m_rangeSpace(Thyra::defaultSpmdVectorSpace<ValueType>(rowCount)),\n#else\n    m_rowCount(rowCount), m_columnCount(columnCount),\n#endif\n    m_eps(1e-4), // just a guess...\n    m_maximumRank(maximumRank_),\n    m_symmetry(symmetry_),\n    m_blockCluster(blockCluster_), m_blocks(blocks_),\n    m_domainPermutation(domainPermutation_),\n    m_rangePermutation(rangePermutation_),\n    m_parallelizationOptions(parallelizationOptions_),\n    m_sharedBlocks(sharedBlocks_)\n{\n}\n\ntemplate <typename ValueType>\narma::Mat<ValueType>\nDiscreteAcaBoundaryOperator<ValueType>::\nasMatrix() const\n{\n    const unsigned int nRows = rowCount();\n    const unsigned int nCols = columnCount();\n    const blcluster* blockCluster = m_blockCluster.get();\n    blcluster* nonconstBlockCluster = const_cast<blcluster*>(blockCluster);\n\n    arma::Mat<ValueType> permutedOutput(nRows, nCols );\n    permutedOutput.fill(0.);\n    arma::Col<ValueType> unit(nCols );\n    unit.fill(0.);\n\n    for (unsigned int col = 0; col < nCols ; ++col)\n    {\n        if (col > 0)\n            unit(col - 1) = 0.;\n        unit(col) = 1.;\n        if (m_symmetry & SYMMETRIC)\n            mltaSyHVec(static_cast<ValueType>(1.), nonconstBlockCluster, m_blocks.get(),\n                       ahmedCast(unit.memptr()),\n                       ahmedCast(permutedOutput.colptr(col)));\n        else if (m_symmetry & HERMITIAN)\n            mltaHeHVec(1., nonconstBlockCluster, m_blocks.get(),\n                       ahmedCast(unit.memptr()),\n                       ahmedCast(permutedOutput.colptr(col)));\n        else\n            mltaGeHVec(1., nonconstBlockCluster, m_blocks.get(),\n                       ahmedCast(unit.memptr()),\n                       ahmedCast(permutedOutput.colptr(col)));\n    }\n\n    arma::Mat<ValueType> output(nRows, nCols );\n    for (unsigned int col = 0; col < nCols ; ++col)\n        for (unsigned int row = 0; row < nRows; ++row)\n            output(row, col) =\n                    permutedOutput(m_rangePermutation.permuted(row),\n                                   m_domainPermutation.permuted(col));\n\n    return output;\n}\n\ntemplate <typename ValueType>\nunsigned int\nDiscreteAcaBoundaryOperator<ValueType>::\nrowCount() const\n{\n#ifdef WITH_TRILINOS\n    return m_rangeSpace->dim();\n#else\n    return m_rowCount;\n#endif\n}\n\ntemplate <typename ValueType>\nunsigned int\nDiscreteAcaBoundaryOperator<ValueType>::\ncolumnCount() const\n{\n#ifdef WITH_TRILINOS\n    return m_domainSpace->dim();\n#else\n    return m_columnCount;\n#endif\n}\n\ntemplate <typename ValueType>\nvoid\nDiscreteAcaBoundaryOperator<ValueType>::\naddBlock(const std::vector<int>& rows,\n         const std::vector<int>& cols,\n         const ValueType alpha,\n         arma::Mat<ValueType>& block) const\n{\n    throw std::runtime_error(\"DiscreteAcaBoundaryOperator::\"\n                             \"addBlock(): not implemented yet\");\n}\n\ntemplate <typename ValueType>\nshared_ptr<const DiscreteBoundaryOperator<ValueType> >\nDiscreteAcaBoundaryOperator<ValueType>::asDiscreteAcaBoundaryOperator(\n        double eps, int maximumRank, bool interleave) const\n{\n    return this->shared_from_this(); // this-> needed for template name resolution.\n}\n\ntemplate <typename ValueType>\nconst DiscreteAcaBoundaryOperator<ValueType>&\nDiscreteAcaBoundaryOperator<ValueType>::castToAca(\n        const DiscreteBoundaryOperator<ValueType>& discreteOperator)\n{\n    return dynamic_cast<const DiscreteAcaBoundaryOperator<ValueType>&>(\n                discreteOperator);\n}\n\ntemplate <typename ValueType>\nshared_ptr<const DiscreteAcaBoundaryOperator<ValueType> >\nDiscreteAcaBoundaryOperator<ValueType>::castToAca(\n        const shared_ptr<const DiscreteBoundaryOperator<ValueType> >&\n        discreteOperator)\n{\n    shared_ptr<const DiscreteAcaBoundaryOperator<ValueType> > result =\n        boost::dynamic_pointer_cast<const DiscreteAcaBoundaryOperator<ValueType> >(\n                discreteOperator);\n    if (result.get()==0 && (discreteOperator.get()!=0)) throw std::bad_cast();\n    return result;\n}\n\n#ifdef WITH_TRILINOS\ntemplate <typename ValueType>\nTeuchos::RCP<const Thyra::VectorSpaceBase<ValueType> >\nDiscreteAcaBoundaryOperator<ValueType>::\ndomain() const\n{\n    return m_domainSpace;\n}\n\ntemplate <typename ValueType>\nTeuchos::RCP<const Thyra::VectorSpaceBase<ValueType> >\nDiscreteAcaBoundaryOperator<ValueType>::\nrange() const\n{\n    return m_rangeSpace;\n}\n\ntemplate <typename ValueType>\nbool\nDiscreteAcaBoundaryOperator<ValueType>::\nopSupportedImpl(Thyra::EOpTransp M_trans) const\n{\n    // TODO: implement remaining variant (conjugate)\n    return (M_trans == Thyra::NOTRANS || M_trans == Thyra::TRANS ||\n            M_trans == Thyra::CONJTRANS);\n}\n#endif // WITH_TRILINOS\n\ntemplate <typename ValueType>\nvoid\nDiscreteAcaBoundaryOperator<ValueType>::\napplyBuiltInImpl(const TranspositionMode trans,\n                 const arma::Col<ValueType>& x_in,\n                 arma::Col<ValueType>& y_inout,\n                 const ValueType alpha,\n                 const ValueType beta) const\n{\n    if (trans != NO_TRANSPOSE && trans != TRANSPOSE && trans != CONJUGATE_TRANSPOSE)\n        throw std::runtime_error(\n                \"DiscreteAcaBoundaryOperator::applyBuiltInImpl(): \"\n                \"transposition modes other than NO_TRANSPOSE, TRANSPOSE and \"\n                \"CONJUGATE_TRANSPOSE are not supported\");\n    bool transposed = (trans & TRANSPOSE);\n\n    const blcluster* blockCluster = m_blockCluster.get();\n    blcluster* nonconstBlockCluster = const_cast<blcluster*>(blockCluster);\n\n    if ((!transposed && (columnCount() != x_in.n_rows ||\n                         rowCount() != y_inout.n_rows)) ||\n            (transposed && (rowCount() != x_in.n_rows ||\n                            columnCount() != y_inout.n_rows)))\n        throw std::invalid_argument(\n                \"DiscreteAcaBoundaryOperator::applyBuiltInImpl(): \"\n                \"incorrect vector length\");\n\n    if (beta == static_cast<ValueType>(0.))\n        y_inout.fill(static_cast<ValueType>(0.));\n    else\n        y_inout *= beta;\n\n    arma::Col<ValueType> permutedArgument;\n    if (!transposed)\n        m_domainPermutation.permuteVector(x_in, permutedArgument);\n    else\n        m_rangePermutation.permuteVector(x_in, permutedArgument);\n\n    arma::Col<ValueType> permutedResult;\n    if (!transposed)\n        m_rangePermutation.permuteVector(y_inout, permutedResult);\n    else\n        m_domainPermutation.permuteVector(y_inout, permutedResult);\n\n    if (m_symmetry & SYMMETRIC) {\n        // TODO: parallelise\n        if (trans == NO_TRANSPOSE || trans == TRANSPOSE)\n            mltaSyHVec(ahmedCast(alpha), nonconstBlockCluster, m_blocks.get(),\n                       ahmedCast(permutedArgument.memptr()),\n                       ahmedCast(permutedResult.memptr()));\n        else // trans == CONJUGATE_TRANSPOSE\n            mltaSyHhVec(ahmedCast(alpha), nonconstBlockCluster, m_blocks.get(),\n                       ahmedCast(permutedArgument.memptr()),\n                       ahmedCast(permutedResult.memptr()));\n    }\n    else if (m_symmetry & HERMITIAN) {\n        // NO_TRANSPOSE and CONJUGATE_TRANSPOSE are equivalent\n        if (trans == NO_TRANSPOSE || trans == CONJUGATE_TRANSPOSE)\n            mltaHeHVec(ahmedCast(alpha), nonconstBlockCluster, m_blocks.get(),\n                       ahmedCast(permutedArgument.memptr()),\n                       ahmedCast(permutedResult.memptr()));\n        else { // trans == TRANSPOSE\n            // alpha A^T x + beta y = (alpha^* A^H x^* + beta^* y^*)^*\n            // = (alpha^* A x^* + beta^* y^*)^*\n            permutedArgument = arma::conj(permutedArgument);\n            permutedResult = arma::conj(permutedResult);\n            ValueType alphaConj = conj(alpha);\n            mltaHeHVec(ahmedCast(alphaConj), nonconstBlockCluster, m_blocks.get(),\n                       ahmedCast(permutedArgument.memptr()),\n                       ahmedCast(permutedResult.memptr()));\n            permutedResult = arma::conj(permutedResult);\n        }\n    }\n    else {\n//        if (trans == NO_TRANSPOSE)\n//            mltaGeHVec(ahmedCast(alpha), nonconstBlockCluster, m_blocks.get(),\n//                       ahmedCast(permutedArgument.memptr()),\n//                       ahmedCast(permutedResult.memptr()));\n//        else // trans == CONJUGATE_TRANSPOSE\n//            mltaGeHhVec(ahmedCast(alpha), nonconstBlockCluster, m_blocks.get(),\n//                        ahmedCast(permutedArgument.memptr()),\n//                        ahmedCast(permutedResult.memptr()));\n\n        AhmedLeafClusterArray leafClusters(nonconstBlockCluster);\n        leafClusters.sortAccordingToClusterSize();\n        const size_t leafClusterCount = leafClusters.size();\n\n        int maxThreadCount = 1;\n        if (!m_parallelizationOptions.isOpenClEnabled()) {\n            if (m_parallelizationOptions.maxThreadCount() ==\n                    ParallelizationOptions::AUTO)\n                maxThreadCount = tbb::task_scheduler_init::automatic;\n            else\n                maxThreadCount = m_parallelizationOptions.maxThreadCount();\n        }\n        tbb::task_scheduler_init scheduler(maxThreadCount);\n\n        std::vector<ChunkStatistics> chunkStats(leafClusterCount);\n\n        typedef MblockMultiplicationLoopBody<ValueType> Body;\n        typename Body::LeafClusterIndexQueue leafClusterIndexQueue;\n        for (size_t i = 0; i < leafClusterCount; ++i)\n            leafClusterIndexQueue.push(i);\n\n        // std::cout << \"----------------------------\\nperm Arg\\n\" << permutedArgument;\n        // std::cout << \"perm Res\\n\" << permutedResult;\n        Body body(trans,\n                  alpha, permutedArgument, permutedResult,\n                  leafClusters, m_blocks,\n                  leafClusterIndexQueue, chunkStats);\n        {\n            Fiber::SerialBlasRegion region;\n            tbb::parallel_reduce(tbb::blocked_range<size_t>(0, leafClusterCount),\n                                 body);\n        }\n        permutedResult = body.m_local_y;\n    }\n    if (!transposed)\n        m_rangePermutation.unpermuteVector(permutedResult, y_inout);\n    else\n        m_domainPermutation.unpermuteVector(permutedResult, y_inout);\n}\n\ntemplate <typename ValueType>\nvoid\nDiscreteAcaBoundaryOperator<ValueType>::\nmakeAllMblocksDense()\n{\n    for (unsigned int i = 0; i < m_blockCluster->nleaves(); ++i)\n        if (m_blocks[i]->isLrM())\n            m_blocks[i]->convLrM_toGeM();\n}\n\ntemplate <typename ValueType>\ndouble\nDiscreteAcaBoundaryOperator<ValueType>::eps() const\n{\n    return m_eps;\n}\n\ntemplate <typename ValueType>\nint\nDiscreteAcaBoundaryOperator<ValueType>::maximumRank() const\n{\n    return m_maximumRank;\n}\n\ntemplate <typename ValueType>\nint\nDiscreteAcaBoundaryOperator<ValueType>::actualMaximumRank() const\n{\n    // const_cast because Ahmed is not const-correct\n    return Hmax_rank(const_cast<AhmedBemBlcluster*>(m_blockCluster.get()),\n                     m_blocks.get());\n}\n\ntemplate <typename ValueType>\nint\nDiscreteAcaBoundaryOperator<ValueType>::symmetry() const\n{\n    return m_symmetry;\n}\n\ntemplate <typename ValueType>\nshared_ptr<const typename DiscreteAcaBoundaryOperator<ValueType>::AhmedBemBlcluster>\nDiscreteAcaBoundaryOperator<ValueType>::blockCluster() const\n{\n    return m_blockCluster;\n}\n\ntemplate <typename ValueType>\ntypename DiscreteAcaBoundaryOperator<ValueType>::AhmedMblockArray\nDiscreteAcaBoundaryOperator<ValueType>::blocks() const\n{\n    return m_blocks;\n}\n\ntemplate <typename ValueType>\nsize_t\nDiscreteAcaBoundaryOperator<ValueType>::blockCount() const\n{\n    return m_blockCluster->nleaves();\n}\n\ntemplate <typename ValueType>\nconst IndexPermutation&\nDiscreteAcaBoundaryOperator<ValueType>::domainPermutation() const\n{\n    return m_domainPermutation;\n}\n\ntemplate <typename ValueType>\nconst IndexPermutation&\nDiscreteAcaBoundaryOperator<ValueType>::rangePermutation() const\n{\n    return m_rangePermutation;\n}\n\ntemplate <typename ValueType>\nconst ParallelizationOptions&\nDiscreteAcaBoundaryOperator<ValueType>::parallelizationOptions() const\n{\n    return m_parallelizationOptions;\n}\n\ntemplate <typename ValueType>\nstd::vector<typename DiscreteAcaBoundaryOperator<ValueType>::AhmedConstMblockArray >\nDiscreteAcaBoundaryOperator<ValueType>::sharedBlocks() const\n{\n    return m_sharedBlocks;\n}\n\n// Global routines\n\ntemplate <typename ValueType>\nshared_ptr<const DiscreteBoundaryOperator<ValueType> > acaOperatorSum(\n        const shared_ptr<const DiscreteBoundaryOperator<ValueType> >& op1,\n        const shared_ptr<const DiscreteBoundaryOperator<ValueType> >& op2,\n        double eps, int maximumRank)\n{\n    if (!op1 || !op2)\n        throw std::invalid_argument(\"acaOperatorSum(): \"\n                                    \"both operands must be non-null\");\n    if (eps <= 0)\n        throw std::invalid_argument(\"acaOperatorSum(): eps must be positive\");\n    if (maximumRank < 1)\n        maximumRank = 1;\n    shared_ptr<const DiscreteAcaBoundaryOperator<ValueType> > acaOp1 =\n            DiscreteAcaBoundaryOperator<ValueType>::castToAca(op1);\n    shared_ptr<const DiscreteAcaBoundaryOperator<ValueType> > acaOp2 =\n            DiscreteAcaBoundaryOperator<ValueType>::castToAca(op2);\n    if (acaOp1->symmetry() != acaOp2->symmetry())\n        throw std::runtime_error(\"acaOperatorSum(): addition of two H-matrices \"\n                                 \"of different symmetry is not supported yet\");\n    if (!areEqual(acaOp1->blockCluster().get(), acaOp2->blockCluster().get()))\n        throw std::invalid_argument(\"acaOperatorSum(): block cluster trees of \"\n                                    \"both operands must be identical\");\n    if (acaOp1->m_domainPermutation != acaOp2->m_domainPermutation ||\n            acaOp1->m_rangePermutation != acaOp2->m_rangePermutation)\n        throw std::invalid_argument(\"acaOperatorSum(): domain and range \"\n                                    \"index permutations of \"\n                                    \"both operands must be identical\");\n\n    typedef typename DiscreteAcaBoundaryOperator<ValueType>::AhmedBemBlcluster\n            AhmedBemBlcluster;\n    typedef typename DiscreteAcaBoundaryOperator<ValueType>::AhmedMblock\n            AhmedMblock;\n\n    shared_ptr<const AhmedBemBlcluster> sumBlockCluster = acaOp1->blockCluster();\n    blcluster* nonConstSumBlockCluster =\n            const_cast<blcluster*>( // AHMED is not const-correct\n                static_cast<const blcluster*>( // safe -- upcast\n                                        sumBlockCluster.get()));\n    boost::shared_array<AhmedMblock*> sumBlocks =\n            allocateAhmedMblockArray<ValueType>(sumBlockCluster.get());\n    copyH(nonConstSumBlockCluster, acaOp1->m_blocks.get(), sumBlocks.get());\n    addGeHGeH(nonConstSumBlockCluster, sumBlocks.get(), acaOp2->m_blocks.get(),\n              eps, maximumRank);\n    shared_ptr<const DiscreteBoundaryOperator<ValueType> > result(\n                new DiscreteAcaBoundaryOperator<ValueType> (\n                    acaOp1->rowCount(), acaOp1->columnCount(), eps,\n                    maximumRank,\n                    acaOp1->m_symmetry & acaOp2->m_symmetry,\n                    sumBlockCluster, sumBlocks,\n                    acaOp1->m_domainPermutation, acaOp2->m_rangePermutation,\n                    acaOp1->m_parallelizationOptions));\n    return result;\n}\n\ntemplate <typename ValueType>\nshared_ptr<const DiscreteBoundaryOperator<ValueType> > scaledAcaOperator(\n        const ValueType& multiplier,\n        const shared_ptr<const DiscreteBoundaryOperator<ValueType> >& op)\n{\n    if (!op)\n        throw std::invalid_argument(\"scaledAcaOperator(): \"\n                                    \"operand must not be null\");\n\n    typedef typename DiscreteAcaBoundaryOperator<ValueType>::AhmedBemBlcluster\n            AhmedBemBlcluster;\n    typedef typename DiscreteAcaBoundaryOperator<ValueType>::AhmedMblock\n            AhmedMblock;\n\n    typedef typename AhmedTypeTraits<ValueType>::Type AhmedValueType;\n    const AhmedValueType ahmedMultiplier = ahmedCast(multiplier);\n\n    shared_ptr<const DiscreteAcaBoundaryOperator<ValueType> > acaOp =\n            DiscreteAcaBoundaryOperator<ValueType>::castToAca(op);\n    const int symmetry = acaOp->symmetry();\n    if (imagPart(multiplier) != 0. &&\n            symmetry & HERMITIAN && !(symmetry & SYMMETRIC))\n        throw std::runtime_error(\n                \"scaledAcaOperator(): multiplication of non-symmetric Hermitian\"\n                \"matrices by scalars with non-zero imaginary part is not \"\n                \"supported yet\");\n    shared_ptr<const AhmedBemBlcluster> scaledBlockCluster = acaOp->blockCluster();\n    blcluster* nonConstScaledBlockCluster =\n            const_cast<blcluster*>( // AHMED is not const-correct\n                static_cast<const blcluster*>( // safe -- upcast\n                                        scaledBlockCluster.get()));\n    boost::shared_array<AhmedMblock*> scaledBlocks =\n            allocateAhmedMblockArray<ValueType>(scaledBlockCluster.get());\n    copyH(nonConstScaledBlockCluster, acaOp->blocks().get(), scaledBlocks.get());\n\n    const size_t blockCount = scaledBlockCluster->nleaves();\n    for (size_t b = 0; b < blockCount; ++b) {\n        AhmedMblock* block = scaledBlocks[b];\n        typename AhmedTypeTraits<ValueType>::Type* data = block->getdata();\n        if (block->isLrM()) // low-rank\n            for (size_t i = 0; i < block->getn1() * block->rank(); ++i)\n                data[i] *= ahmedMultiplier;\n        else {\n             // we don't support complex Hermitian blocks yet\n            assert(!(block->isHeM() && boost::is_complex<ValueType>()));\n            if (!block->isLtM()) // dense, but not lower-triangular\n                for (size_t i = 0; i < block->nvals(); ++i)\n                    data[i] *= ahmedMultiplier;\n            else { // lower-triangular\n                // diagonal entries have special meaning and should not be rescaled\n                size_t size = block->getn1();\n                assert(block->getn2() == size);\n                for (size_t c = 0; c < size; ++c)\n                    for (size_t r = 1; r < size; ++r)\n                        data[c * size + r] *= ahmedMultiplier;\n            }\n        }\n    }\n\n    int scaledSymmetry = symmetry;\n    if (imagPart(multiplier) != 0.)\n        scaledSymmetry &= ~HERMITIAN;\n    shared_ptr<const DiscreteBoundaryOperator<ValueType> > result(\n                new DiscreteAcaBoundaryOperator<ValueType> (\n                    acaOp->rowCount(), acaOp->columnCount(),\n                    acaOp->eps(), acaOp->maximumRank(),\n                    scaledSymmetry,\n                    scaledBlockCluster, scaledBlocks,\n                    acaOp->domainPermutation(), acaOp->rangePermutation(),\n                    acaOp->parallelizationOptions()));\n    return result;\n}\n\ntemplate <typename ValueType>\nshared_ptr<const DiscreteBoundaryOperator<ValueType> > scaledAcaOperator(\n        const shared_ptr<const DiscreteBoundaryOperator<ValueType> >& op,\n        const ValueType& multiplier)\n{\n    return scaledAcaOperator(multiplier, op);\n}\n\ntemplate <typename ValueType>\nshared_ptr<const DiscreteBoundaryOperator<ValueType> > acaOperatorApproximateLuInverse(\n        const shared_ptr<const DiscreteBoundaryOperator<ValueType> >& op,\n        double delta)\n{\n    shared_ptr<const DiscreteAcaBoundaryOperator<ValueType> > acaOp =\n            DiscreteAcaBoundaryOperator<ValueType>::castToAca(op);\n    shared_ptr<const DiscreteBoundaryOperator<ValueType> > result(\n                new AcaApproximateLuInverse<ValueType>(*acaOp, delta));\n    return result;\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_RESULT(DiscreteAcaBoundaryOperator);\n\n#define INSTANTIATE_FREE_FUNCTIONS(RESULT) \\\n    template shared_ptr<const DiscreteBoundaryOperator<RESULT> > \\\n        acaOperatorSum( \\\n            const shared_ptr<const DiscreteBoundaryOperator<RESULT> >& op1, \\\n            const shared_ptr<const DiscreteBoundaryOperator<RESULT> >& op2, \\\n            double eps, int maximumRank); \\\n    template shared_ptr<const DiscreteBoundaryOperator<RESULT> > \\\n        scaledAcaOperator( \\\n            const RESULT& multiplier, \\\n            const shared_ptr<const DiscreteBoundaryOperator<RESULT> >& op); \\\n    template shared_ptr<const DiscreteBoundaryOperator<RESULT> > \\\n        scaledAcaOperator( \\\n            const shared_ptr<const DiscreteBoundaryOperator<RESULT> >& op, \\\n            const RESULT& multiplier); \\\n    template shared_ptr<const DiscreteBoundaryOperator<RESULT> > \\\n        acaOperatorApproximateLuInverse( \\\n            const shared_ptr<const DiscreteBoundaryOperator<RESULT> >& op, \\\n            double delta)\n\n#if defined(ENABLE_SINGLE_PRECISION)\nINSTANTIATE_FREE_FUNCTIONS(float);\n#endif\n\n#if defined(ENABLE_SINGLE_PRECISION) && (defined(ENABLE_COMPLEX_BASIS_FUNCTIONS) || defined(ENABLE_COMPLEX_KERNELS))\nINSTANTIATE_FREE_FUNCTIONS(std::complex<float>);\n#endif\n\n#if defined(ENABLE_DOUBLE_PRECISION)\nINSTANTIATE_FREE_FUNCTIONS(double);\n#endif\n\n#if defined(ENABLE_DOUBLE_PRECISION) && (defined(ENABLE_COMPLEX_BASIS_FUNCTIONS) || defined(ENABLE_COMPLEX_KERNELS))\nINSTANTIATE_FREE_FUNCTIONS(std::complex<double>);\n#endif\n\n} // namespace Bempp\n\n#endif // WITH_AHMED\n", "meta": {"hexsha": "d71816ae2f5a333e2908699392dd91a9fe51750a", "size": 32462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/discrete_aca_boundary_operator.cpp", "max_stars_repo_name": "UCL/bempp", "max_stars_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T13:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T13:35:20.000Z", "max_issues_repo_path": "lib/assembly/discrete_aca_boundary_operator.cpp", "max_issues_repo_name": "UCL/bempp", "max_issues_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/assembly/discrete_aca_boundary_operator.cpp", "max_forks_repo_name": "UCL/bempp", "max_forks_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7904540163, "max_line_length": 116, "alphanum_fraction": 0.6562134188, "num_tokens": 7676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.03067580049219587, "lm_q1q2_score": 0.013430586309622353}}
{"text": "\n\n#include\"main.hpp\"\n#include\"Option.hpp\"\n#include\"Mcmc.hpp\"\n#include\"Pre.hpp\"\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include\"nlopt.hpp\"\n\nboost::mt19937 r;\n\nconst double sigma2_y0 = 10000;\nconst bool bounded=false;\n\n\nvoid Mcmc::loc_RD()\n{\n    double protsum=0,mrnasum=0;\n    int ncount=0;\n    for (unsigned p=0;p<yH().size();p++) for (unsigned q=0;q<yH().at(p).size();q++) for (int j=0;j<op().nrep();j++) for (int t=0;t<op().nt();t++) {\n        protsum+=exp(yH().at(p).at(q).at(j*op().nt()+t));\n        if (op().Mbool()) protsum+=exp(yM().at(p).at(q).at(j*op().nt()+t));\n        mrnasum+=exp(xx().at(p).at(j*op().nt()+t));\n        ncount++;\n    }\n    d_mean_R=0;\n    d_mean_D=0;\n    d_sigma2_RD=op().Mbool() ? .25 : 1;\n}\n\n\nconst double Mcmc::mean_RD(const char c) const\n{\n    if (c!='R' and c!='D') throw runtime_error(\"mean_RD\");\n    return (c=='R'?d_mean_R:d_mean_D);\n}\n\n\ndouble quantile(const vector<double>& data,const double f)\n{\n    vector<double> sorted_data(data);\n    sort(sorted_data.begin(),sorted_data.end());\n    const double index = f * (data.size() - 1) ;\n    const size_t lhs = static_cast<size_t>(index) ;\n    const double delta = index - lhs ;\n    double result;\n    if (data.size() == 0) throw runtime_error(\"quantile\");\n    if (lhs == data.size() - 1) {\n        result = sorted_data.at(lhs) ;\n    } else {\n        result = (1 - delta) * sorted_data.at(lhs) + delta * sorted_data.at(lhs + 1) ;\n    }\n    return result ;\n}\n\n\nbool Mcmc::Ey_fn(const int p, const int j, const vector<double>& y0i,const vector<double>& Ri,const vector<double>& Di, vector<double>& Ey_ij,const Mcmc& mc,const char c)\n{\n    if (c!='M' and c!='H') throw runtime_error(\"Ey_fn\");\n    Ey_ij.at(0) = y0i.at(j);\n    if (not op().Mbool()) for (int t=1;t<mc.op().nt();t++) {\n        Ey_ij.at(t) = Ey_ij.at(t-1) \n            + (mc.op().timep().at(t)-mc.op().timep().at(t-1))*( log(1.+exp(mc.xx().at(p).at(j*mc.op().nt()+t-1))) *Ri.at(t-1)-Ey_ij.at(t-1)*Di.at(t-1) );\n        if (Ey_ij.at(t)<=0) return true;\n    } else if (c=='M') for (int t=1;t<mc.op().nt();t++) {\n        Ey_ij.at(t) = Ey_ij.at(t-1) \n            + (mc.op().timep().at(t)-mc.op().timep().at(t-1))*( -Ey_ij.at(t-1)*Di.at(t-1) );\n        if (Ey_ij.at(t)<=0) return true;\n    } else for (int t=1;t<mc.op().nt();t++) {\n        Ey_ij.at(t) = Ey_ij.at(t-1) \n            + (mc.op().timep().at(t)-mc.op().timep().at(t-1))*( log(1.+exp(mc.xx().at(p).at(j*mc.op().nt()+t-1))) *Ri.at(t-1));\n        if (Ey_ij.at(t)<=0) return true;\n    }\n    return false;\n}\n\n\ndouble Mcmc::sum_sq(const int p, const int j, const vector<double>& y0i, const vector<double>& Ri, const vector<double>& Di,const Mcmc& mc,const char c)\n{\n    if (c!='M' and c!='H') throw runtime_error(\"sum_sqj\");\n    double sum2=0;\n    vector<double> Ey_ij(mc.op().nt()+0);\n    if (Ey_fn(p,j,y0i,Ri,Di,Ey_ij,mc,c)) return NAN;\n    const vector<vector<double> >& y_p=(c=='M'?mc.yM():mc.yH()).at(p);\n    for (int t=0; t<mc.op().nt(); t++) for (unsigned q=0;q<y_p.size();q++) {\n        sum2 += pow(y_p.at(q).at(j*mc.op().nt()+t)-log(Ey_ij.at(t)),2);\n    }\n    return sum2;\n}\n\n\ndouble Mcmc::sum_sq(const int p, const vector<double>& y0i, const vector<double>& Ri, const vector<double>& Di,const Mcmc& mc,const char c,const int s=0)\n{\n    if (c!='M' and c!='H') throw runtime_error(\"sum_sq\");\n    double sum2=0;\n    const vector<vector<double> >& y_p=(c=='M'?mc.yM():mc.yH()).at(p);\n    for (int j=0; j<mc.op().nrep(); j++) {\n        bool flag=false;\n        for (unsigned q=0;q<y_p.size();q++) if (obs(y_p.at(q).at(j*mc.op().nt()))) {\n            flag=true;\n            break;\n        }\n        if (flag) {\n            vector<double> Ey_ij(mc.op().nt()+0);\n            if (Ey_fn(p,j,y0i,Ri,Di,Ey_ij,mc,c)) return NAN;\n            for (int t=s; t<mc.op().nt(); t++) for (unsigned q=0;q<y_p.size();q++) {\n                sum2 += pow(y_p.at(q).at(j*mc.op().nt()+t)-log(Ey_ij.at(t)),2);\n            }\n        }\n    }\n    return sum2;\n}\n\n\n\nboost::random::normal_distribution<> ugaussian(0,1);\nboost::uniform_real<> uniform(0,1);\nvoid Mcmc::update_y0(const int p,const char c)\n{\n    if (c!='M' and c!='H') throw runtime_error(\"update_y0\");\n    const vector<vector<double> >& y_p=(c=='M'?yM():yH()).at(p);\n    const double tau2p=(c=='M'?tau2M():tau2H()).at(p);\n    const vector<double>& y0p=(c=='M'?M0():H0()).at(p);\n    for (int j=0;j<op().nrep();j++) {\n        bool flag=false;\n        for (unsigned q=0;q<y_p.size();q++) if (obs(y_p.at(q).at(j*op().nt()))) {\n            flag=true;\n            break;\n        }\n        if (flag) {\n            vector<double> newy0p(y0p);\n            newy0p.at(j) *= exp(ugaussian(r));\n            double logr = -sum_sq(p,j,newy0p,RR().at(p),DD().at(p),*this,c)/tau2p/2;\n            logr -= -sum_sq(p,j,y0p,RR().at(p),DD().at(p),*this,c)/tau2p/2;\n            logr += -pow(log(newy0p.at(j)),2)/2/sigma2_y0;\n            logr -= -pow(log(y0p.at(j)),2)/2/sigma2_y0;\n            if (logr>0 or uniform(r)<exp(logr)) {\n                (c=='M'?d_M0: d_H0).at(p).at(j) = newy0p.at(j);\n            }\n        }\n    }\n}\n\n\nvoid Mcmc::update_RD(const int p,const char c)\n{\n    if (c!='R' and c!='D') throw runtime_error(\"update_RD\");\n    const vector<int>& CPp=(c=='R'?CPR():CPD()).at(p);\n    const vector<double>& RDp=(c=='R'?RR():DD()).at(p);\n    const double& upl=upRD;\n    vector<double> newRDp;\n    int s=-1;\n    for (int t=0;t<op().nt()-1;t++) {\n        if (/*t==0 or */CPp.at(t)==1) {\n            s = t+1;\n            newRDp = RDp;\n            if (bounded) {\n                newRDp.at(t) = inv_logit(logit(RDp.at(t),upl)+ugaussian(r),upl);\n            } else {\n                newRDp.at(t) *= exp(ugaussian(r));\n            }\n        } else {\n            newRDp.at(t) = newRDp.at(t-1);\n        }\n        if (/*t!=op().nt()-2 and */CPp.at(t+1)==0) continue;\n        double logr = -sum_sq(p,H0().at(p),(c=='R'?newRDp:RR().at(p)),(c=='R'?DD().at(p):newRDp),*this,'H',s)/tau2H().at(p)/2;\n        logr -= -sum_sq(p,H0().at(p),RR().at(p),DD().at(p),*this,'H',s)/tau2H().at(p)/2;\n        if (op().Mbool()) {\n            logr += -sum_sq(p,M0().at(p),(c=='R'?newRDp:RR().at(p)),(c=='R'?DD().at(p):newRDp),*this,'M',s)/tau2M().at(p)/2;\n            logr -= -sum_sq(p,M0().at(p),RR().at(p),DD().at(p),*this,'M',s)/tau2M().at(p)/2;\n        }\n        if (bounded) {\n            logr += log(pq(newRDp.at(t),upl))-log(pq(RDp.at(t),upl));\n        } else {\n            logr += -pow(log(newRDp.at(t))-mean_RD(c),2)/2/sigma2_RD();\n            logr -= -pow(log(RDp.at(t))-mean_RD(c),2)/2/sigma2_RD();\n        }\n        if (logr>0 or uniform(r)<exp(logr)) {\n            (c=='R'?d_RR:d_DD).at(p) = newRDp;\n        }\n    }\n}\n\n\nvoid Mcmc::update_CP(const int p,const char c)\n{\n    if (c!='R' and c!='D') throw runtime_error(\"update_CP\");\n    const vector<double>& RDp=(c=='R'?RR():DD()).at(p);\n    const vector<int>& CPp=(c=='R'?CPR():CPD()).at(p);\n    const vector<vector<double> >& d_varphi=(c=='R'?d_varphiR:d_varphiD);\n    const double& upl=upRD;\n    for (int cp=1;cp<op().nt()-1;cp++) {\n        vector<double> newRDp=RDp;\n        int l_time_index=-1, r_time_index=-1;\n        for (int t=cp-1;l_time_index<0;t--) if (/*t==0 or */CPp.at(t)==1) l_time_index=t;\n        for (int t=cp+1;r_time_index<0;t++) if (/*t==op().nt()-1 or */CPp.at(t)==1) r_time_index=t;\n        const double l_time = op().timep().at(cp)-op().timep().at(l_time_index);\n        const double r_time = op().timep().at(r_time_index)-op().timep().at(cp);\n        const double t_time = op().timep().at(r_time_index)-op().timep().at(l_time_index);\n        double logr=0;\n        if (CPp.at(cp)==0) {\n            const double u = uniform(r);\n            const double newRleft = (bounded ? inv_logit(logit(RDp.at(cp),upl)+r_time/t_time*logit(u,1),upl) : exp(log(RDp.at(cp))+r_time/t_time*logit(u,1)) );\n            const double newRright= (bounded ? inv_logit(logit(RDp.at(cp),upl)-l_time/t_time*logit(u,1),upl) : exp(log(RDp.at(cp))-l_time/t_time*logit(u,1)) );\n            for (int t=l_time_index;t<cp;t++) newRDp.at(t) = newRleft;\n            for (int t=cp;t<r_time_index;t++) newRDp.at(t) = newRright;\n            if (d_prior) logr += d_varphi.at(p).at(cp);\n            if (bounded) {\n                logr += -log(upl);\n                logr += 2*log(newRleft*(upl-newRright)+newRright*(upl-newRleft))-log(pq(RDp.at(cp),upl))-log(upl);\n            } else {\n                logr -= -log(RDp.at(cp))-pow(log(RDp.at(cp))-mean_RD(c),2)/2/sigma2_RD();\n                logr += -log(newRleft)-pow(log(newRleft)-mean_RD(c),2)/2/sigma2_RD();\n                logr += -log(newRright)-pow(log(newRright)-mean_RD(c),2)/2/sigma2_RD();\n                logr += -log(sigma2_RD())-.5*log(2*M_PI);\n                logr += 2*log(newRleft+newRright)-log(RDp.at(cp));\n            }\n        } else {\n            const double mergedR=(bounded ? inv_logit((l_time*logit(RDp.at(cp-1),upl)+r_time*logit(RDp.at(cp),upl))/t_time,upl) : exp((l_time*log(RDp.at(cp-1))+r_time*log(RDp.at(cp)))/t_time) );\n            for (int t=l_time_index;t<r_time_index;t++) newRDp.at(t)=mergedR;\n            if (d_prior) logr -= d_varphi.at(p).at(cp);\n            //if ((not op().Mbool()) and c=='D') logr-=logit(.1,1);\n            if (bounded) {\n                logr -= -log(upl);\n                logr -= 2*log(RDp.at(cp-1)*(upl-RDp.at(cp))+RDp.at(cp)*(upl-RDp.at(cp-1)))-log(pq(mergedR,upl))-log(upl);\n            } else {\n                logr += -log(mergedR)-pow(log(mergedR)-mean_RD(c),2)/2/sigma2_RD();\n                logr -= -log(RDp.at(cp-1))-pow(log(RDp.at(cp-1))-mean_RD(c),2)/2/sigma2_RD();\n                logr -= -log(RDp.at(cp))-pow(log(RDp.at(cp))-mean_RD(c),2)/2/sigma2_RD();\n                logr -= -log(sigma2_RD())-.5*log(2*M_PI);\n                logr -= 2*log(RDp.at(cp-1)+RDp.at(cp))-log(mergedR);\n            }\n        }\n        logr += -sum_sq(p,H0().at(p),(c=='R'?newRDp:RR().at(p)),(c=='R'?DD().at(p):newRDp),*this,'H',l_time_index+1)/tau2H().at(p)/2;\n        logr -= -sum_sq(p,H0().at(p),RR().at(p),DD().at(p),*this,'H',l_time_index+1)/tau2H().at(p)/2;\n        if (op().Mbool()) {\n            logr += -sum_sq(p,M0().at(p),(c=='R'?newRDp:RR().at(p)),(c=='R'?DD().at(p):newRDp),*this,'M',l_time_index+1)/tau2M().at(p)/2;\n            logr -= -sum_sq(p,M0().at(p),RR().at(p),DD().at(p),*this,'M',l_time_index+1)/tau2M().at(p)/2;\n        }\n        if (logr>0 or uniform(r)<exp(logr)) {\n            if (c=='R') {\n                d_RR.at(p) = newRDp;\n                d_CPR.at(p).at(cp)=1-CPp.at(cp);\n            } else {\n                d_DD.at(p) = newRDp;\n                d_CPD.at(p).at(cp)=1-CPp.at(cp);\n            }\n        }\n    }\n}\n\n\nvoid Mcmc::gibbs_tau2(const int p,const char c)\n{\n    if (c!='M' and c!='H') throw runtime_error(\"gibbs_tau2\");\n    const double sumsq=sum_sq(p,(c=='M'?M0():H0()).at(p),RR().at(p),DD().at(p),*this,c);\n    if (obs(sumsq)) {\n        (c=='M'?d_tau2M:d_tau2H).at(p) = 1 / boost::random::gamma_distribution<> ((c=='M'?a_tauM():a_tauH())+.5*d_nobs.at(p)*op().nt(),1/((c=='M'?b_tauM():b_tauH())+sumsq/2))(r);\n    }\n}\n\n\nvoid Mcmc::tau_hyperparams(const char c)\n{\n    if (c!='M' and c!='H') throw runtime_error(\"tau_hyperparams\");\n    double& d_a_tau=(c=='M'?d_a_tauM:d_a_tauH);\n    double& d_b_tau=(c=='M'?d_b_tauM:d_b_tauH);\n    vector<double>& d_tau2=(c=='M'?d_tau2M:d_tau2H);\n    const vector<double>& tau2=d_tau2;\n\n    vector<vector<vector<double> > > yy(yH());\n    if (op().Mbool()) for (unsigned p=0;p<yH().size();p++) for (unsigned q=0;q<yH().at(p).size();q++) for (int j=0;j<op().nrep();j++) for (int t=0;t<op().nt();t++) {\n        yy.at(p).at(q).at(j*op().nt()+t)=log(exp(yM().at(p).at(q).at(j*op().nt()+t))+exp(yH().at(p).at(q).at(j*op().nt()+t)));\n    }\n\n    d_tau2.assign(yy.size(),0);\n    for (unsigned p=0;p<yy.size();p++) {\n        for (unsigned q=0; q<yy.at(p).size(); q++) {\n            for (int j=0;j<op().nrep();j++) {\n                vector<double> mu(op().nt()-1);\n                for (int t=0;t<op().nt()-1;t++) {\n                    mu.at(t)=yy.at(p).at(q).at(j*op().nt()+t)+yy.at(p).at(q).at(j*op().nt()+t+1);\n                    mu.at(t)/=2;\n                }\n                for (int t=1;t<op().nt()-1;t++) {\n                    d_tau2.at(p)+=.5*pow(yy.at(p).at(q).at(j*op().nt()+t)-mu.at(t-1),2);\n                    d_tau2.at(p)+=.5*pow(yy.at(p).at(q).at(j*op().nt()+t)-mu.at(t),2);\n                }\n                d_tau2.at(p)+=pow(yy.at(p).at(q).at(j*op().nt()+0)-mu.at(0),2);\n                const int t=op().nt()-2;\n                d_tau2.at(p)+=pow(yy.at(p).at(q).at(j*op().nt()+t)-mu.at(t),2);\n            }\n        }\n        d_tau2.at(p) /= op().nc()*yy.at(p).size();\n    }\n    const double m=quantile(d_tau2,.1);\n    for (unsigned p=0;p<yy.size();p++) d_tau2.at(p) += m;\n    ofstream var_ofs(\"varc\"+boost::lexical_cast<string>(c)+\".txt\");\n\n    //std::transform(tau2.begin(),tau2.end(),d_tau2.begin(),std::bind1st(std::multiplies<double>(),2.));\n\n    copy(tau2.begin(),tau2.end(),ostream_iterator<double>(var_ofs,\"\\n\"));\n    const double mom1=accumulate(tau2.begin(),tau2.end(),0.)/tau2.size();\n    double mom2=0;\n    for (vector<double>::const_iterator it=tau2.begin();it!=tau2.end();it++) mom2 += (*it)*(*it);\n    mom2 /= tau2.size();\n    d_a_tau=(2*mom2-mom1*mom1)/(mom2-mom1*mom1);//MOM estimates\n    d_b_tau=mom1*mom2/(mom2-mom1*mom1);         //MOM estimates\n}\n\n\nMcmc::Mcmc(const Pre& pr) : d_op(pr.op()),d_prior(false),d_xx(pr.xx()),d_yM(pr.yM()),d_yH(pr.yH()),d_nobs(pr.nobs())\n{\n    Construct();\n}\n\n\nMcmc::Mcmc(const Pre& pr,const vector<vector<double> >& varphiR,const vector<vector<double> >& varphiD) : d_op(pr.op()),d_prior(true),d_varphiR(varphiR),d_varphiD(varphiD),d_xx(pr.xx()),d_yM(pr.yM()),d_yH(pr.yH()),d_nobs(pr.nobs())\n{\n    Construct();\n}\n\n\n\n\nvoid Mcmc::Construct()\n{\n    d_M0.assign(yM().size(),vector<double>(op().nrep()));\n    d_H0.assign(yH().size(),vector<double>(op().nrep()));\n    for (unsigned p=0;p<yM().size();p++) for (int j=0;j<op().nrep();j++) {\n        double sum=0;\n        for (unsigned q=0;q<yM().at(p).size();q++) sum+=yM().at(p).at(q).at(j*op().nt());\n        d_M0.at(p).at(j)=exp(sum/yM().at(p).size());\n    }\n    for (unsigned p=0;p<yH().size();p++) for (int j=0;j<op().nrep();j++) {\n        double sum=0;\n        for (unsigned q=0;q<yH().at(p).size();q++) sum+=yH().at(p).at(q).at(j*op().nt());\n        d_H0.at(p).at(j)=exp(sum/yH().at(p).size());\n    }\n    d_RR.assign(yH().size(),vector<double> (op().nt(),1e-5));\n    d_DD.assign(yH().size(),vector<double> (op().nt(),1e-5));\n\n    loc_RD();\n\n\n    vector<int> setcp(op().nt(),1);setcp.front()=1;setcp.back()=1;\n    d_CPR.assign(yH().size(),setcp);\n    d_CPRum.assign(yH().size(),vector<int> (op().nt()-1));\n    d_CPD.assign(yH().size(),setcp);\n    d_CPDum.assign(yH().size(),vector<int> (op().nt()-1));\n\n    if (op().Mbool()) tau_hyperparams('M');\n    tau_hyperparams('H');\n    ofstream M0_ofs(\"s_M0\");\n    ofstream H0_ofs(\"s_H0\");\n    ofstream RR_ofs(\"s_RR\");\n    ofstream DD_ofs(\"s_DD\");\n    ofstream tau2M_ofs(\"s_tau2M\");\n    ofstream tau2H_ofs(\"s_tau2H\");\n    if (not tau2M_ofs) throw runtime_error(\"can't open s_tau2M\");\n    ofstream CPR_ofs(\"s_CPR\");\n    ofstream CPD_ofs(\"s_CPD\");\n    ofstream etaM_ofs(\"s_etaM\");\n    ofstream etaH_ofs(\"s_etaH\");\n    ofstream loglike_ofs(\"s_loglike\");\n\n    upRD=10;\n\n    for (int iter=0,ns=0; ns<op().ns(); iter++) {\n\n        if (iter%100==0) cout<<'\\r'<<iter<<flush;\n        for (unsigned p=0; p<yH().size(); p++) {\n            if (op().Mbool()) update_y0(p,'M');\n            update_y0(p,'H');\n            update_RD(p,'R');\n            update_RD(p,'D');\n            update_CP(p,'R');\n            update_CP(p,'D');\n        }\n\n        if (iter>op().nburn() and iter%op().nthin()==0) {\n            ns++;\n\n            for (unsigned p=0;p<yH().size();p++) {\n                if (op().Mbool()) tau2M_ofs<<d_tau2M.at(p)<<'\\t';\n                tau2H_ofs<<d_tau2H.at(p)<<'\\t';\n                for (int j=0;j<op().nrep();j++) {\n                    if (op().Mbool()) M0_ofs<<d_M0.at(p).at(j)<<'\\t';\n                    H0_ofs<<d_H0.at(p).at(j)<<'\\t';\n                }\n                for (int t=0;t<op().nt()-1;t++) {\n                    RR_ofs<<d_RR.at(p).at(t)<<'\\t';\n                    DD_ofs<<d_DD.at(p).at(t)<<'\\t';\n                }\n                for (int t=1;t<op().nt()-1;t++) {\n                    CPR_ofs<<d_CPR.at(p).at(t)<<'\\t';\n                    CPD_ofs<<d_CPD.at(p).at(t)<<'\\t';\n                    d_CPRum.at(p).at(t)+=d_CPR.at(p).at(t);\n                    d_CPDum.at(p).at(t)+=d_CPD.at(p).at(t);\n                }\n\n            }\n\n            if (op().Mbool()) {\n                M0_ofs<<'\\n';\n                tau2M_ofs<<'\\n';\n            }\n            H0_ofs<<'\\n';\n            tau2H_ofs<<'\\n';\n            RR_ofs<<'\\n';\n            DD_ofs<<'\\n';\n            CPR_ofs<<'\\n';\n            CPD_ofs<<'\\n';\n\n            double loglike = 0;\n            for (unsigned p=0;p<yH().size();p++) for (unsigned q=0;q<yH().at(p).size();q++) for (int j=0;j<op().nrep();j++) {\n                if (op().Mbool()) {\n                    if (obs(yM().at(p).at(q).at(j*op().nt()))) {\n                        vector<double> Ey_ij(op().nt());\n                        if (Ey_fn(p,j,d_M0.at(p),d_RR.at(p),d_DD.at(p),Ey_ij,*this,'M')) throw runtime_error(\"fit\");\n                        for (int t=0;t<op().nt();t++) {\n                            etaM_ofs << log(Ey_ij.at(t)) << '\\t';\n                            loglike += -log(d_tau2M.at(p))-pow(yM().at(p).at(q).at(j*op().nt()+t)-log(Ey_ij.at(t)),2)/d_tau2M.at(p)/2;\n                        }\n                    } else {\n                        for (int t=0;t<op().nt();t++) etaM_ofs << \"NA\\t\";\n                    }\n                }\n                if (obs(yH().at(p).at(q).at(j*op().nt()))) {\n                    vector<double> Ey_ij(op().nt());\n                    if (Ey_fn(p,j,d_H0.at(p),d_RR.at(p),d_DD.at(p),Ey_ij,*this,'H')) throw runtime_error(\"fit\");\n                    for (int t=0;t<op().nt();t++) {\n                        etaH_ofs << log(Ey_ij.at(t)) << '\\t';\n                        loglike += -log(d_tau2H.at(p))-pow(yH().at(p).at(q).at(j*op().nt()+t)-log(Ey_ij.at(t)),2)/d_tau2H.at(p)/2;\n                    }\n                } else {\n                    for (int t=0;t<op().nt();t++) etaH_ofs << \"NA\\t\";\n                }\n            }\n            if (op().Mbool()) etaM_ofs<<'\\n';\n            etaH_ofs<<'\\n';\n            loglike_ofs << loglike << '\\n';\n        }\n\n    }\n    cout<<'\\n';\n}\n\n\n\n\n\n", "meta": {"hexsha": "249790b0ac6cc008d54b6e078179895c630fb88f", "size": 18541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "peca_R/src/Mcmc.cpp", "max_stars_repo_name": "PECAplus/PECAplus_cmd_line", "max_stars_repo_head_hexsha": "3e84ef1c6e59925bf5a9552beb86c022392b94d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-08T05:45:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-08T05:45:08.000Z", "max_issues_repo_path": "peca_R/src/Mcmc.cpp", "max_issues_repo_name": "PECAplus/PECAplus_cmd_line", "max_issues_repo_head_hexsha": "3e84ef1c6e59925bf5a9552beb86c022392b94d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-07-09T13:20:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T17:22:23.000Z", "max_forks_repo_path": "peca_R/src/Mcmc.cpp", "max_forks_repo_name": "PECAplus/PECAplus_cmd_line", "max_forks_repo_head_hexsha": "3e84ef1c6e59925bf5a9552beb86c022392b94d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-01T09:03:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T13:00:40.000Z", "avg_line_length": 40.6600877193, "max_line_length": 231, "alphanum_fraction": 0.4970605685, "num_tokens": 6315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.028870904126209018, "lm_q1q2_score": 0.013422128695245016}}
{"text": "\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <vector>\r\n#include <string>\r\n#include <exception>\r\n#include <iterator>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n\r\n#include \"biu/OptionParser.hh\"\r\n\r\n#include <sgm/GM_vf2.hh>\r\n#include <sgm/MR_Storing.hh>\r\n#include <sgm/SubGraph.hh>\r\n#include <sgm/RP_Hanser96.hh>\r\n\r\n#include <ggl/Graph.hh>\r\n#include <ggl/Graph_GML_writer.hh>\r\n#include <ggl/Graph_GMLparser.hh>\r\n\r\n\r\n#include \"version.hh\"\r\n\r\n\tusing namespace ggl;\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n#ifndef ARGEXCEPTION_\r\n#define ARGEXCEPTION_\r\n\r\n\t  /*! Exception class for exeptions thrown during argument and input parsing.\r\n\t   */\r\n\tclass ArgException : public std::exception {\r\n\tpublic:\r\n\t\t  //! the error message\r\n\t\tstd::string errorMsg;\r\n\t\tArgException( std::string errorMsg_ ) : errorMsg(errorMsg_) {}\r\n\t\tvirtual ~ArgException() throw (){}\r\n\t\tvirtual const char* what() const throw() {\r\n\t\t\treturn errorMsg.c_str();\r\n\t\t}\r\n\t};\r\n\r\n#endif\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\ttypedef std::vector< Graph > Graph_container;\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\nvoid\r\ninitAllowedArguments( biu::OptionMap & allowedArgs, std::string &infoText );\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nparseGraphs(\tstd::istream & in\r\n\t\t\t\t, Graph_container & toFill\r\n\t\t\t\t, const size_t linesRead ) throw(std::exception);\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n/*!\r\n *\r\n * Dummy aromaticity perception to access rings to predict\r\n *\r\n */\r\nclass RR_list\r\n\t: public sgm::RingReporter\r\n{\r\npublic:\r\n\r\n\ttypedef std::vector< RingList > RingListVec;\r\n\r\nprotected:\r\n\r\n\t  //! container that will hold all rings of the current graph\r\n\tRingListVec allRings;\r\n\r\n\r\n\t  /*!\r\n\t   * Comparison of ring lists based on the ring size.\r\n\t   */\r\n\tclass RingSizeLess {\r\n\tpublic:\r\n\r\n\t\t  /*!\r\n\t\t   * less comparison of two ring descriptors.\r\n\t\t   * @param x the ring to be checked if smaller\r\n\t\t   * @param y the ring to compare to\r\n\t\t   * @return true if x.size < y.size;\r\n\t\t   * \t\tfalse otherwise\r\n\t\t   */\r\n\t\tbool operator () ( const RingList & x\r\n\t\t\t\t\t\t  , const RingList & y )\r\n\t\t{\r\n\t\t\treturn x.size() < y.size();\r\n\t\t}\r\n\t};\r\n\r\n\r\npublic:\r\n\r\n\tRR_list()\r\n\t : allRings()\r\n\t{}\r\n\r\n\tvirtual ~RR_list()\r\n\t{}\r\n\r\n\tvoid\r\n\treportRing(\tconst sgm::Graph_Interface& graph\r\n\t\t\t\t, const RingList & ringList )\r\n\t{\r\n\t\t  // store description\r\n\t\tallRings.push_back( ringList );\r\n\t}\r\n\r\n\r\n\tRingListVec &\r\n\tgetAllRings()\r\n\t{\r\n\t\treturn allRings;\r\n\t}\r\n\r\n\tvoid\r\n\tpruneFusedRings( RR_list::RingListVec & rings );\r\n\r\n\t//////////////////////////////////////////////////////////////////////\r\n\t//////////////////////////////////////////////////////////////////////\r\n};\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n\r\nint main( int argc, char** argv ) {\r\n\r\n\t//////////////////////////////////////////////////////////////\r\n\t// variables\r\n\t//////////////////////////////////////////////////////////////\r\n\r\n\tstd::istream* in = NULL;\r\n\tstd::ifstream* inFile = NULL;\r\n\tsize_t inLine = 0;\r\n\r\n\tstd::ostream* out = &std::cout;\r\n\tstd::ofstream* outFile = NULL;\r\n\r\n\t//////////////////////////////////////////////////////////////\r\n\t// parameter parsing and checking\r\n\t//////////////////////////////////////////////////////////////\r\n\r\n\tbiu::OptionMap allowedArgs;\t//< map of allowed arguments\r\n\tstd::string infoText;\t\t//< info string of the program\r\n\tinitAllowedArguments(allowedArgs,infoText);\t// init\r\n\r\n\t\t// parse programm arguments\r\n\tbiu::COptionParser opts = biu::COptionParser(\tallowedArgs, argc,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\targv, infoText);\r\n\t\t// check arguments parseable and all mandatory arguments given\r\n\t\t// + help output if needed\r\n\tif (opts.argExist(\"help\")) {\r\n\t\topts.coutUsage();\r\n\t\treturn 0;\r\n\t}\r\n\tif (opts.argExist(\"version\")) {\r\n\t\tgiveVersion();\r\n\t\treturn 0;\r\n\t}\r\n\tif (!opts.noErrors()) {\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tint exitValue = 0;\r\n\r\n\ttry {\r\n\r\n\r\n\r\n\t\t  // set graph input stream\r\n\t\tif (boost::iequals(opts.getStrVal(\"graph\"),\"STDIN\")) {\r\n\t\t\t  // read from STDIN\r\n\t\t\tin = &std::cin;\r\n\t\t} else {\r\n\t\t\t  // read from file\r\n\t\t\tinFile = new std::ifstream( opts.getStrVal(\"graph\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t, std::ifstream::in );\r\n\t\t\tif (!inFile->is_open()) {\r\n\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\toss\t<<\"cannot open input file '\" <<opts.getStrVal(\"graph\") <<\"'\";\r\n\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t}\r\n\t\t\tin = inFile;\r\n\t\t}\r\n\t\t  // set output stream\r\n\t\tif (opts.getStrVal(\"out\").size() == 0) {\r\n\t\t\tthrow ArgException(\"no output file given\");\r\n\t\t} else if ( !boost::iequals(opts.getStrVal(\"out\"),\"STDOUT\")) {\r\n\t\t\toutFile = new std::ofstream(\topts.getStrVal(\"out\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t\t, std::ofstream::out );\r\n\t\t\tif (!outFile->is_open()) {\r\n\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\toss\t<<\"cannot open output file '\" <<opts.getStrVal(\"out\") <<\"'\";\r\n\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t}\r\n\t\t\tout = outFile;\r\n\t\t}\r\n\r\n\t\tconst int maxRingSize = opts.getIntVal(\"maxRingSize\");\r\n\t\tif (maxRingSize < 3) {\r\n\t\t\tthrow ArgException(\"'maxRingSize' has to be >= 3\");\r\n\t\t}\r\n\r\n\t\t//////////////////////////////////////////////////////////////\r\n\t\t// parse graphs from input\r\n\t\t//////////////////////////////////////////////////////////////\r\n\r\n\t\t  // get master graph to match onto\r\n\t\tGraph_container parsedGraphs;\r\n\t\tparseGraphs( *in, parsedGraphs, inLine );\r\n\t\tif (parsedGraphs.size() != 1)  {\r\n\t\t\tthrow ArgException(\"could not parse only one graph from 'graph'\");\r\n\t\t}\r\n\t\tGraph & graph = *(parsedGraphs.begin());\r\n\r\n\r\n\t\t//////////////////////   RING ENUMERATION  /////////////////////////////////////\r\n\r\n\r\n\t\t  // store all rings up to the maximally predictable size\r\n\t\tsgm::RP_Hanser96 ringFinder;\r\n\t\t  // setup graph interface\r\n\t\tGraph_boost graphWrapper(graph);\r\n\t\t  // setup ring container\r\n\t\tRR_list reporter;\r\n\t\t  // run ring perception\r\n\t\tringFinder.findRings( graphWrapper, reporter, maxRingSize );\r\n\r\n\t\t  // prune rings if needed\r\n\t\tif (opts.argExist(\"pruneFusedRings\")) {\r\n\t\t\t  // prune rings to remove fused representation\r\n\t\t\treporter.pruneFusedRings( reporter.getAllRings() );\r\n\t\t}\r\n\r\n\t\t//////////////////////   OUTPUT  /////////////////////////////////////\r\n\r\n\t\tconst RR_list::RingListVec & allRings = reporter.getAllRings();\r\n\r\n\t\tfor (size_t i=0; i< allRings.size(); ++i) {\r\n\r\n\t\t\tconst sgm::RingReporter::RingList & nodes = allRings.at(i);\r\n\r\n\t\t\tfor (sgm::RingReporter::RingList::const_iterator n = nodes.begin(); n!= nodes.end(); ++n) {\r\n\t\t\t\t*out <<\" \"<<*n;\r\n\t\t\t}\r\n\t\t\t*out <<std::endl;\r\n\r\n\t\t}\r\n\r\n\r\n\t} catch (std::exception& ex) {\r\n\t\tstd::cerr <<\"\\n\\n ERROR : \" <<ex.what() <<\"\\n\"<<std::endl;\r\n\t\texitValue = -1;\r\n\t}\r\n\r\n\r\n\t//////////////////////////////////////////////////////////////\r\n\t// final stream handling\r\n\t//////////////////////////////////////////////////////////////\r\n\r\n\tin = &std::cin;\r\n\tout = &std::cout;\r\n\tif (inFile != NULL)\t\t{ inFile->close(); delete inFile; }\r\n\tif (outFile != NULL)\t{ outFile->close(); delete outFile; }\r\n\r\n\treturn exitValue;\r\n}\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n/*!\r\n * Initialises allowed parameters and their default values and prepares an\r\n * information string for the tool.\r\n */\r\nvoid\r\ninitAllowedArguments(biu::OptionMap & allowedArgs, std::string &infoText )\r\n{\r\n\tinfoText = \"\\n\"\r\n\t\t\"Enumerates all rings for a given graph.\\n\"\r\n\t\t;\r\n\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"graph\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"The name of the file that holds the graph encoding in GML or 'STDIN' when to read GML from standard input\",\r\n\t\t\t\t\t\t\t\"STDIN\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"maxRingSize\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"The maximal ring size to be considered\",\r\n\t\t\t\t\t\t\t\"15\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"pruneFusedRings\", true, biu::COption::BOOL,\r\n\t\t\t\t\t\t\t\"prunes the outer rings that emerge if two rings share a single edge\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"out\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"Output file name or 'STDOUT' when to write to standard output\",\r\n\t\t\t\t\t\t\t\"STDOUT\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"help\", true, biu::COption::BOOL,\r\n\t\t\t\t\t\t\t\"Displays help on all parameters\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"version\", true, biu::COption::BOOL,\r\n\t\t\t\t\t\t\t\"Version information\"));\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n\tvoid\r\n\tRR_list::\r\n\tpruneFusedRings( RR_list::RingListVec & rings )\r\n\t{\r\n\r\n\t\t  // sort rings by size\r\n\t\tRingSizeLess ringSizeLess;\r\n\r\n\t\tstd::sort( rings.begin(), rings.end(), ringSizeLess );\r\n\r\n\t\t  //! defines an edge; NOTE: use as ordered pairs, i.e. first <= second\r\n\t\ttypedef std::pair< size_t, size_t > Edge;\r\n\t\t  //! container to maintain aromatic edges without duplicates\r\n\t\ttypedef std::set< Edge > EdgeSet;\r\n\r\n\t\ttypedef std::vector< EdgeSet > EdgeSetVec;\r\n\r\n\t\tEdgeSetVec edges(rings.size());\r\n\r\n\t\t  // generate edge list description for each ring\r\n\t\tfor (size_t i=0; i<rings.size(); ++i) {\r\n\t\t\tRingList::const_iterator cur=rings.at(i).begin(), last=rings.at(i).begin();\r\n\t\t\tfor (cur++; cur!=rings.at(i).end(); ++cur,++last) {\r\n\t\t\t\tif (*cur<*last) {\r\n\t\t\t\t\tedges[i].insert( Edge(*cur,*last) );\r\n\t\t\t\t} else {\r\n\t\t\t\t\tedges[i].insert( Edge(*last,*cur) );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n//std::cerr <<\"\\nNEXT\\n\";\r\n\t\t  // prune rings\r\n\t\tsize_t numOfprunedRings = 0;\r\n\t\tfor (int i=rings.size()-1; i>=0; i--) {\r\n//std::cerr <<\"next ring = \";\r\n//for (RingList::const_iterator x=rings.at(i).begin(); x!=rings.at(i).end(); ++x) {\r\n//\tstd::cerr <<*x <<\" \";\r\n//}\r\n//std::cerr <<\"\\n\";\r\n\t\t\tbool canBePruned = false;\r\n\t\t\tfor( size_t c=0; !canBePruned && c < (size_t)i; ++c ) {\r\n//std::cerr <<\"  compare to ring = \";\r\n//for (RingList::const_iterator x=rings.at(c).begin(); x!=rings.at(c).end(); ++x) {\r\n//\tstd::cerr <<*x <<\" \";\r\n//}\r\n//std::cerr <<\"\\n\";\r\n\t\t\t\t  // skip already deleted rings\r\n\t\t\t\tif (edges.at(c).empty()) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\t  // stop if ring is of equal size or larger\r\n\t\t\t\tif (edges.at(c).size() >= edges.at(i).size()) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t  // check for containment of this ring c within ring i\r\n\r\n\t\t\t\t  // get iterators on edge sets to compare\r\n\t\t\t\tEdgeSet::const_iterator largeEdge = edges.at(i).begin(), largeEnd = edges.at(i).end();\r\n\t\t\t\tEdgeSet::const_iterator curEdge = edges.at(c).begin(), curEnd = edges.at(c).end();\r\n\t\t\t\t  // sequential check\r\n\t\t\t\tsize_t curOverlap = 0;\r\n\t\t\t\t  // check only until up to two differences have been found\r\n\t\t\t\twhile(largeEdge != largeEnd && curEdge != curEnd) {\r\n\t\t\t\t\t  // check if overlap\r\n\t\t\t\t\tif (*largeEdge == *curEdge) {\r\n\t\t\t\t\t\t++curOverlap;\r\n\t\t\t\t\t\t++largeEdge;\r\n\t\t\t\t\t\t++curEdge;\r\n\t\t\t\t\t  // check which counter to increase\r\n\t\t\t\t\t} else if (*largeEdge < *curEdge) {\r\n\t\t\t\t\t\t++largeEdge;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t++curEdge;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t  // check if smaller current ring is contained excluding one edge\r\n\t\t\t\t  // if only one edge is left : ring is contained\r\n\t\t\t\tcanBePruned = (curOverlap+1 == edges.at(c).size());\r\n\r\n\t\t\t}\r\n\t\t\t  // prune ring if obsolete\r\n\t\t\tif (canBePruned) {\r\n\t\t\t\t  // remove edge information for ring at position i\r\n\t\t\t\tedges[i].clear();\r\n\t\t\t\t  // count pruning\r\n\t\t\t\tnumOfprunedRings++;\r\n//std::cerr <<\"==> pruned\\n\";\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t  // shift remaining rings to the front\r\n\t\tif (numOfprunedRings>0) {\r\n\t\t\tsize_t fillPos = 0;\r\n\t\t\tfor( size_t i=0; i<rings.size(); ++i ) {\r\n\t\t\t\tif (!edges.at(i).empty()) {\r\n\t\t\t\t\t  // check if overwrite is needed\r\n\t\t\t\t\tif (fillPos < i) {\r\n\t\t\t\t\t\trings[fillPos] = rings[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t\t  // increase overwrite counter\r\n\t\t\t\t\tfillPos++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t  // drop deleted elements\r\n\t\t\trings.resize(fillPos);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n/*!\r\n * Parses the given input stream for graphs in GML format and adds each graph\r\n * to the given container.\r\n *\r\n * Each graph has to be headed by a comment line starting with a '#' character\r\n * that specifies the name of the graph.\r\n *\r\n * @param in the input stream to read from\r\n * @param toFill the container to add the graphs to\r\n * @param linesRead the number of lines already read from input (needed for\r\n *                  error reporting)\r\n *\r\n */\r\nvoid\r\nparseGraphs(\tstd::istream & in\r\n\t\t\t\t, Graph_container & toFill\r\n\t\t\t\t, const size_t linesRead = 0 )  throw(std::exception)\r\n{\r\n\tstd::string line;\r\n\tsize_t lineNumber = linesRead;\r\n\tstd::string graphString = std::string(\"\");\r\n\t  // parse whole input stream\r\n\twhile (in.good()) {\r\n\t\t  // read next line\r\n\t\tstd::getline( in, line );\r\n\t\tlineNumber++;\r\n\r\n\t\t  // check if next rule header or end of file was reached\r\n\t\tif (line[0] == '#' || in.eof()) {\r\n\t\t\t  // convert rule string to rule object\r\n\t\t\tif (graphString.size() > 0) {\r\n\t\t\t\tstd::pair<ggl::Graph, int>\r\n\t\t\t\t\t\tret = ggl::Graph_GMLparser::parseGraph( graphString );\r\n\t\t\t\t  // check for parsing error\r\n\t\t\t\tif (ret.second != -1) {\r\n\t\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\t\toss\t<<\" Graph parsing error in graph specification BEFORE line \"\r\n\t\t\t\t\t\t<<line\r\n\t\t\t\t\t\t<<\" at graph string position \" <<ret.second;\r\n\t\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t\t}\r\n\t\t\t\ttoFill.push_back(ret.first);\r\n\t\t\t}\r\n\t\t\t  // clear processed rule\r\n\t\t\tgraphString.clear();\r\n\t\t} else {\r\n\t\t\t  // append line content to rule string\r\n\t\t\tgraphString.append(line);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n", "meta": {"hexsha": "9896cd25b2b589f0552e658a6a6d9340c83f4a58", "size": 13577, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/gmlRings.cc", "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/bin/gmlRings.cc", "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/bin/gmlRings.cc", "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": 27.0998003992, "max_line_length": 116, "alphanum_fraction": 0.5289828386, "num_tokens": 3303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.03963884236266608, "lm_q1q2_score": 0.01340098583060557}}
{"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:25\n\n#include \"NSM_slha_io.hpp\"\n#include \"NSM_input_parameters.hpp\"\n#include \"NSM_info.hpp\"\n#include \"logger.hpp\"\n#include \"wrappers.hpp\"\n#include \"numerics2.hpp\"\n#include \"config.h\"\n\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <boost/bind.hpp>\n\n#define Pole(p) physical.p\n#define PHYSICAL(p) model.get_physical().p\n#define PHYSICAL_SLHA(p) model.get_physical_slha().p\n#define LOCALPHYSICAL(p) physical.p\n#define MODELPARAMETER(p) model.get_##p()\n#define DEFINE_PHYSICAL_PARAMETER(p) decltype(LOCALPHYSICAL(p)) p;\n#define LowEnergyConstant(p) Electroweak_constants::p\n\nusing namespace softsusy;\n\nnamespace flexiblesusy {\n\nchar const * const NSM_slha_io::drbar_blocks[NUMBER_OF_DRBAR_BLOCKS] =\n   { \"gauge\", \"Yu\", \"Yd\", \"Ye\", \"SM\", \"HMIX\", \"NMSSMRUN\" }\n;\n\nNSM_slha_io::NSM_slha_io()\n   : slha_io()\n   , print_imaginary_parts_of_majorana_mixings(false)\n{\n}\n\nvoid NSM_slha_io::clear()\n{\n   slha_io.clear();\n}\n\nvoid NSM_slha_io::set_print_imaginary_parts_of_majorana_mixings(bool flag)\n{\n   print_imaginary_parts_of_majorana_mixings = flag;\n}\n\n/**\n * Stores the EXTPAR input parameters in the SLHA object.\n *\n * @param input struct of input parameters\n */\nvoid NSM_slha_io::set_extpar(const NSM_input_parameters& input)\n{\n   std::ostringstream extpar;\n\n   extpar << \"Block EXTPAR\\n\";\n   extpar << FORMAT_ELEMENT(0, input.Qin, \"Qin\");\n   slha_io.set_block(extpar);\n\n}\n\n/**\n * Stores the MINPAR input parameters in the SLHA object.\n *\n * @param input struct of input parameters\n */\nvoid NSM_slha_io::set_minpar(const NSM_input_parameters& input)\n{\n   std::ostringstream minpar;\n\n   minpar << \"Block MINPAR\\n\";\n   minpar << FORMAT_ELEMENT(1, input.Lambda1Input, \"Lambda1Input\");\n   minpar << FORMAT_ELEMENT(2, input.Lambda2Input, \"Lambda2Input\");\n   minpar << FORMAT_ELEMENT(3, input.Lambda3Input, \"Lambda3Input\");\n   minpar << FORMAT_ELEMENT(4, input.Lambda4Input, \"Lambda4Input\");\n   minpar << FORMAT_ELEMENT(5, input.Lambda5Input, \"Lambda5Input\");\n   minpar << FORMAT_ELEMENT(6, input.vSInput, \"vSInput\");\n   slha_io.set_block(minpar);\n\n}\n\n/**\n * Stores the SMINPUTS input parameters in the SLHA object.\n *\n * @param qedqcd class of Standard Model parameters\n */\nvoid NSM_slha_io::set_sminputs(const softsusy::QedQcd& qedqcd)\n{\n   slha_io.set_sminputs(qedqcd);\n}\n\n/**\n * Stores the spectrum generator information in the SPINFO block in\n * the SLHA object.\n *\n * @param problems struct with parameter point problems\n */\nvoid NSM_slha_io::set_spinfo(const Problems<NSM_info::NUMBER_OF_PARTICLES>& problems)\n{\n   std::ostringstream spinfo;\n   spinfo << \"Block SPINFO\\n\"\n          << FORMAT_SPINFO(1, PKGNAME)\n          << FORMAT_SPINFO(2, FLEXIBLESUSY_VERSION);\n\n   if (problems.have_warning()) {\n      std::ostringstream warnings;\n      problems.print_warnings(warnings);\n      spinfo << FORMAT_SPINFO(3, warnings.str());\n   }\n\n   if (problems.have_problem()) {\n      std::ostringstream problems_str;\n      problems.print_problems(problems_str);\n      spinfo << FORMAT_SPINFO(4, problems_str.str());\n   }\n\n   spinfo << FORMAT_SPINFO(5, NSM_info::model_name)\n          << FORMAT_SPINFO(9, SARAH_VERSION);\n\n   slha_io.set_block(spinfo, SLHA_io::front);\n}\n\n/**\n * Stores the particle masses in the SLHA object.\n *\n * @param physical struct of physical parameters\n *\n * @param write_sm_masses flag to indicate if Standard Model\n *    particle masses should be written as well\n */\nvoid NSM_slha_io::set_mass(const NSM_physical& physical,\n                                   bool write_sm_masses)\n{\n   std::ostringstream mass;\n\n   mass << \"Block MASS\\n\"\n      << FORMAT_MASS(24, LOCALPHYSICAL(MVWp), \"VWp\")\n      << FORMAT_MASS(25, LOCALPHYSICAL(Mhh(0)), \"hh(1)\")\n      << FORMAT_MASS(35, LOCALPHYSICAL(Mhh(1)), \"hh(2)\")\n   ;\n\n   if (write_sm_masses) {\n      mass\n         << FORMAT_MASS(21, LOCALPHYSICAL(MVG), \"VG\")\n         << FORMAT_MASS(12, LOCALPHYSICAL(MFv(0)), \"Fv(1)\")\n         << FORMAT_MASS(14, LOCALPHYSICAL(MFv(1)), \"Fv(2)\")\n         << FORMAT_MASS(16, LOCALPHYSICAL(MFv(2)), \"Fv(3)\")\n         << FORMAT_MASS(1, LOCALPHYSICAL(MFd(0)), \"Fd(1)\")\n         << FORMAT_MASS(3, LOCALPHYSICAL(MFd(1)), \"Fd(2)\")\n         << FORMAT_MASS(5, LOCALPHYSICAL(MFd(2)), \"Fd(3)\")\n         << FORMAT_MASS(2, LOCALPHYSICAL(MFu(0)), \"Fu(1)\")\n         << FORMAT_MASS(4, LOCALPHYSICAL(MFu(1)), \"Fu(2)\")\n         << FORMAT_MASS(6, LOCALPHYSICAL(MFu(2)), \"Fu(3)\")\n         << FORMAT_MASS(11, LOCALPHYSICAL(MFe(0)), \"Fe(1)\")\n         << FORMAT_MASS(13, LOCALPHYSICAL(MFe(1)), \"Fe(2)\")\n         << FORMAT_MASS(15, LOCALPHYSICAL(MFe(2)), \"Fe(3)\")\n         << FORMAT_MASS(22, LOCALPHYSICAL(MVP), \"VP\")\n         << FORMAT_MASS(23, LOCALPHYSICAL(MVZ), \"VZ\")\n      ;\n   }\n\n   slha_io.set_block(mass);\n\n}\n\n/**\n * Stores the mixing matrices in the SLHA object.\n *\n * @param physical struct of physical parameters\n *\n * @param write_sm_mixing_matrics flag to indicate if Standard Model\n *    particle mixing matrices should be written as well\n */\nvoid NSM_slha_io::set_mixing_matrices(const NSM_physical& physical,\n                                              bool write_sm_mixing_matrics)\n{\n   \n   if (write_sm_mixing_matrics) {\n      slha_io.set_block(\"UULMIX\", LOCALPHYSICAL(Vu), \"Vu\");\n      slha_io.set_block(\"UDLMIX\", LOCALPHYSICAL(Vd), \"Vd\");\n      slha_io.set_block(\"UURMIX\", LOCALPHYSICAL(Uu), \"Uu\");\n      slha_io.set_block(\"UDRMIX\", LOCALPHYSICAL(Ud), \"Ud\");\n      slha_io.set_block(\"UELMIX\", LOCALPHYSICAL(Ve), \"Ve\");\n      slha_io.set_block(\"UERMIX\", LOCALPHYSICAL(Ue), \"Ue\");\n   }\n\n   if (print_imaginary_parts_of_majorana_mixings) {\n   }\n\n}\n\nvoid NSM_slha_io::set_ckm(\n   const Eigen::Matrix<std::complex<double>,3,3>& ckm_matrix,\n   double scale)\n{\n   slha_io.set_block(\"VCKM\"  , ckm_matrix.real(), \"Re(CKM)\", scale);\n   slha_io.set_block(\"IMVCKM\", ckm_matrix.imag(), \"Im(CKM)\", scale);\n}\n\nvoid NSM_slha_io::set_pmns(\n   const Eigen::Matrix<std::complex<double>,3,3>& pmns_matrix,\n   double scale)\n{\n   slha_io.set_block(\"VPMNS\"  , pmns_matrix.real(), \"Re(PMNS)\", scale);\n   slha_io.set_block(\"IMVPMNS\", pmns_matrix.imag(), \"Im(PMNS)\", scale);\n}\n\n/**\n * Write SLHA object to file.\n *\n * @param file_name file name\n */\nvoid NSM_slha_io::write_to_file(const std::string& file_name)\n{\n   slha_io.write_to_file(file_name);\n}\n\n/**\n * Read (DR-bar) model parameter output scale from MODSEL entry 12\n */\ndouble NSM_slha_io::get_parameter_output_scale() const\n{\n   return slha_io.get_modsel().parameter_output_scale;\n}\n\n/**\n * Read SLHA object from file\n *\n * @param file_name file name\n */\nvoid NSM_slha_io::read_from_file(const std::string& file_name)\n{\n   slha_io.read_from_file(file_name);\n   slha_io.read_modsel();\n}\n\n/**\n * Read SLHA object from source\n *\n * calls SLHA_io::read_from_source()\n *\n * @param source source name\n */\nvoid NSM_slha_io::read_from_source(const std::string& source)\n{\n   slha_io.read_from_source(source);\n   slha_io.read_modsel();\n}\n\n/**\n * Read SLHA object from stream\n *\n * @param istr stream name\n */\nvoid NSM_slha_io::read_from_stream(std::istream& istr)\n{\n   slha_io.read_from_stream(istr);\n}\n\n/**\n * Fill struct of model input parameters from SLHA object (MINPAR and\n * EXTPAR blocks)\n *\n * @param input struct of model input parameters\n */\nvoid NSM_slha_io::fill(NSM_input_parameters& input) const\n{\n   SLHA_io::Tuple_processor minpar_processor\n      = boost::bind(&NSM_slha_io::fill_minpar_tuple, boost::ref(input), _1, _2);\n   SLHA_io::Tuple_processor extpar_processor\n      = boost::bind(&NSM_slha_io::fill_extpar_tuple, boost::ref(input), _1, _2);\n\n   slha_io.read_block(\"MINPAR\", minpar_processor);\n   slha_io.read_block(\"EXTPAR\", extpar_processor);\n\n\n}\n\n/**\n * Reads DR-bar parameters from a SLHA output file.\n */\nvoid NSM_slha_io::fill_drbar_parameters(NSM_mass_eigenstates& model) const\n{\n   model.set_g1(slha_io.read_entry(\"gauge\", 1) * 1);\n   model.set_g2(slha_io.read_entry(\"gauge\", 2));\n   model.set_g3(slha_io.read_entry(\"gauge\", 3));\n   {\n      Eigen::Matrix<double,3,3> Yu;\n      slha_io.read_block(\"Yu\", Yu);\n      model.set_Yu(Yu);\n   }\n   {\n      Eigen::Matrix<double,3,3> Yd;\n      slha_io.read_block(\"Yd\", Yd);\n      model.set_Yd(Yd);\n   }\n   {\n      Eigen::Matrix<double,3,3> Ye;\n      slha_io.read_block(\"Ye\", Ye);\n      model.set_Ye(Ye);\n   }\n   model.set_mH2(slha_io.read_entry(\"SM\", 1));\n   model.set_Lambda1(slha_io.read_entry(\"SM\", 2));\n   model.set_vH(slha_io.read_entry(\"HMIX\", 3));\n   model.set_vS(slha_io.read_entry(\"NMSSMRUN\", 5));\n\n\n   model.set_scale(read_scale());\n}\n\n/**\n * Reads DR-bar parameters, pole masses and mixing matrices (in\n * Haber-Kane convention) from a SLHA output file.\n */\nvoid NSM_slha_io::fill(NSM_mass_eigenstates& model) const\n{\n   fill_drbar_parameters(model);\n\n   NSM_physical physical_hk;\n   fill_physical(physical_hk);\n   physical_hk.convert_to_hk();\n   model.get_physical() = physical_hk;\n}\n\n/**\n * Fill struct of extra physical input parameters from SLHA object\n * (FlexibleSUSYInput block)\n *\n * @param settings struct of physical input parameters\n */\nvoid NSM_slha_io::fill(Physical_input& input) const\n{\n   slha_io.fill(input);\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 NSM_slha_io::fill(Spectrum_generator_settings& settings) const\n{\n   slha_io.fill(settings);\n}\n\nvoid NSM_slha_io::fill_minpar_tuple(NSM_input_parameters& input,\n                                                int key, double value)\n{\n   switch (key) {\n   case 1: input.Lambda1Input = value; break;\n   case 2: input.Lambda2Input = value; break;\n   case 3: input.Lambda3Input = value; break;\n   case 4: input.Lambda4Input = value; break;\n   case 5: input.Lambda5Input = value; break;\n   case 6: input.vSInput = value; break;\n   default: WARNING(\"Unrecognized entry in block MINPAR: \" << key); break;\n   }\n\n}\n\nvoid NSM_slha_io::fill_extpar_tuple(NSM_input_parameters& input,\n                                                int key, double value)\n{\n   switch (key) {\n   case 0: input.Qin = value; break;\n   default: WARNING(\"Unrecognized entry in block EXTPAR: \" << key); break;\n   }\n\n}\n\n/**\n * Reads pole masses and mixing matrices from a SLHA output file.\n */\nvoid NSM_slha_io::fill_physical(NSM_physical& physical) const\n{\n   {\n      DEFINE_PHYSICAL_PARAMETER(Vu);\n      slha_io.read_block(\"UULMIX\", Vu);\n      LOCALPHYSICAL(Vu) = Vu;\n   }\n   {\n      DEFINE_PHYSICAL_PARAMETER(Vd);\n      slha_io.read_block(\"UDLMIX\", Vd);\n      LOCALPHYSICAL(Vd) = Vd;\n   }\n   {\n      DEFINE_PHYSICAL_PARAMETER(Uu);\n      slha_io.read_block(\"UURMIX\", Uu);\n      LOCALPHYSICAL(Uu) = Uu;\n   }\n   {\n      DEFINE_PHYSICAL_PARAMETER(Ud);\n      slha_io.read_block(\"UDRMIX\", Ud);\n      LOCALPHYSICAL(Ud) = Ud;\n   }\n   {\n      DEFINE_PHYSICAL_PARAMETER(Ve);\n      slha_io.read_block(\"UELMIX\", Ve);\n      LOCALPHYSICAL(Ve) = Ve;\n   }\n   {\n      DEFINE_PHYSICAL_PARAMETER(Ue);\n      slha_io.read_block(\"UERMIX\", Ue);\n      LOCALPHYSICAL(Ue) = Ue;\n   }\n\n   LOCALPHYSICAL(MVG) = slha_io.read_entry(\"MASS\", 21);\n   LOCALPHYSICAL(MFv)(0) = slha_io.read_entry(\"MASS\", 12);\n   LOCALPHYSICAL(MFv)(1) = slha_io.read_entry(\"MASS\", 14);\n   LOCALPHYSICAL(MFv)(2) = slha_io.read_entry(\"MASS\", 16);\n   LOCALPHYSICAL(MVP) = slha_io.read_entry(\"MASS\", 22);\n   LOCALPHYSICAL(MVZ) = slha_io.read_entry(\"MASS\", 23);\n   LOCALPHYSICAL(MFd)(0) = slha_io.read_entry(\"MASS\", 1);\n   LOCALPHYSICAL(MFd)(1) = slha_io.read_entry(\"MASS\", 3);\n   LOCALPHYSICAL(MFd)(2) = slha_io.read_entry(\"MASS\", 5);\n   LOCALPHYSICAL(MFu)(0) = slha_io.read_entry(\"MASS\", 2);\n   LOCALPHYSICAL(MFu)(1) = slha_io.read_entry(\"MASS\", 4);\n   LOCALPHYSICAL(MFu)(2) = slha_io.read_entry(\"MASS\", 6);\n   LOCALPHYSICAL(MFe)(0) = slha_io.read_entry(\"MASS\", 11);\n   LOCALPHYSICAL(MFe)(1) = slha_io.read_entry(\"MASS\", 13);\n   LOCALPHYSICAL(MFe)(2) = slha_io.read_entry(\"MASS\", 15);\n   LOCALPHYSICAL(Mhh)(0) = slha_io.read_entry(\"MASS\", 25);\n   LOCALPHYSICAL(Mhh)(1) = slha_io.read_entry(\"MASS\", 35);\n   LOCALPHYSICAL(MVWp) = slha_io.read_entry(\"MASS\", 24);\n\n}\n\n/**\n * Reads the renormalization scales from all DR-bar parameter blocks.\n * If blocks with different scales are found the last scale is\n * returned and a warning is printed.\n *\n * @return common renormalization scale\n */\ndouble NSM_slha_io::read_scale() const\n{\n   double scale = 0.;\n\n   for (unsigned i = 0; i < NUMBER_OF_DRBAR_BLOCKS; i++) {\n      const double block_scale = slha_io.read_scale(drbar_blocks[i]);\n      if (!is_zero(block_scale)) {\n         if (!is_zero(scale) && !is_equal(scale, block_scale))\n            WARNING(\"DR-bar parameters defined at different scales\");\n         scale = block_scale;\n      }\n   }\n\n   return scale;\n}\n\n} // namespace flexiblesusy\n", "meta": {"hexsha": "775b05877bad079f427c06c146206403f8c3b66c", "size": 13517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/NSM/NSM_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/models/NSM/NSM_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/models/NSM/NSM_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": 28.6377118644, "max_line_length": 85, "alphanum_fraction": 0.6707109566, "num_tokens": 3938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.029312233083263434, "lm_q1q2_score": 0.013399697994565321}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2019 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_BLOCK_MODE_CIPHER_BLOCK_CHAINING_HPP\n#define CRYPTO3_BLOCK_MODE_CIPHER_BLOCK_CHAINING_HPP\n\n#include <boost/integer.hpp>\n\n#include <nil/crypto3/modes/mode.hpp>\n#include <nil/crypto3/modes/cts.hpp>\n#include <nil/crypto3/modes/padding.hpp>\n\n#include <nil/crypto3/codec/algorithm/encode.hpp>\n\n//#include <nil/crypto3/codec/logic.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace block {\n            namespace modes {\n                namespace detail {\n                    template<typename Cipher, typename Padding, template<typename> class Allocator = std::allocator>\n                    struct ctr_policy {\n                        typedef std::size_t size_type;\n\n                        typedef Cipher cipher_type;\n                        typedef Padding padding_type;\n\n                        constexpr static const size_type block_bits = cipher_type::block_bits;\n                        constexpr static const size_type block_words = cipher_type::block_words;\n                        typedef typename cipher_type::block_type block_type;\n\n                        typedef std::vector<boost::uint_t<CHAR_BIT>, Allocator<boost::uint_t<CHAR_BIT>>> iv_type;\n                    };\n\n                    template<typename Cipher, typename Padding, typename CiphertextStealingMode>\n                    struct ctr_encryption_policy : public ctr_policy<Cipher, Padding> {};\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_encryption_policy<Cipher, Padding, cts<0, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, iv,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, previous,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const block_type &previous = block_type(),\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = {0};\n                            std::array<uint8_t, block_bits / CHAR_BIT> byte_array = {0};\n\n                            pack(plaintext, byte_array);\n\n                            size_type rem = std::count(byte_array.begin(), byte_array.end(), block_type::value_type()) %\n                                            (block_bits / CHAR_BIT);\n                            if (rem || padding_type::always_pad) {\n                                block_type padbuffer = padding_type::pad(plaintext, rem), block;\n                                //                            codec::encode<codec::encoder::logic_xor>(!iv.empty() ? iv\n                                //                            : previous, padbuffer, block .begin());\n                                result = cipher.encrypt(block);\n                            }\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_encryption_policy<Cipher, Padding, cts<1, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, iv,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, previous,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const block_type &previous = block_type(),\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = {0};\n                            std::array<uint8_t, block_bits / CHAR_BIT> byte_array = {0};\n\n                            pack(plaintext, byte_array);\n\n                            size_type rem = std::count(byte_array.begin(), byte_array.end(), block_type::value_type()) %\n                                            (block_bits / CHAR_BIT);\n                            if (rem || padding_type::always_pad) {\n                                block_type padbuffer = padding_type::pad(plaintext, rem), block;\n                                //                            codec::encode<codec::encoder::logic_xor>(!iv.empty() ? iv\n                                //                            : previous, padbuffer, block .begin());\n                                result = cipher.encrypt(block);\n                            }\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_encryption_policy<Cipher, Padding, cts<2, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, iv,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, previous,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const block_type &previous = block_type(),\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = {0};\n                            std::array<uint8_t, block_bits / CHAR_BIT> byte_array = {0};\n\n                            pack(plaintext, byte_array);\n\n                            size_type rem = std::count(byte_array.begin(), byte_array.end(), block_type::value_type()) %\n                                            (block_bits / CHAR_BIT);\n                            if (rem || padding_type::always_pad) {\n                                block_type padbuffer = padding_type::pad(plaintext, rem), block;\n                                //                            codec::encode<codec::encoder::logic_xor>(!iv.empty() ? iv\n                                //                            : previous, padbuffer, block .begin());\n                                result = cipher.encrypt(block);\n                            }\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_encryption_policy<Cipher, Padding, cts<3, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const size_type block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const size_type block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, iv,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type block = {0};\n\n                            //                        codec::encode<codec::encoder::logic_xor>(plaintext, previous,\n                            //                        block.begin());\n\n                            return cipher.encrypt(block);\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const block_type &previous = block_type(),\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = {0};\n                            std::array<uint8_t, block_bits / CHAR_BIT> byte_array = {0};\n\n                            pack(plaintext, byte_array);\n\n                            size_type rem = std::count(byte_array.begin(), byte_array.end(), block_type::value_type()) %\n                                            (block_bits / CHAR_BIT);\n                            if (rem || padding_type::always_pad) {\n                                block_type padbuffer = padding_type::pad(plaintext, rem), block;\n                                //                            codec::encode<codec::encoder::logic_xor>(!iv.empty() ? iv\n                                //                            : previous, padbuffer, block .begin());\n                                result = cipher.encrypt(block);\n                            }\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, typename Padding, typename CiphertextStealingMode>\n                    struct ctr_decryption_policy : public ctr_policy<Cipher, Padding> {};\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_decryption_policy<Cipher, Padding, cts<0, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, previous);\n\n                            return result;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_decryption_policy<Cipher, Padding, cts<1, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, previous);\n\n                            return result;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_decryption_policy<Cipher, Padding, cts<2, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, previous);\n\n                            return result;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Cipher, typename Padding>\n                    struct ctr_decryption_policy<Cipher, Padding, cts<3, Cipher, Padding>>\n                        : public ctr_policy<Cipher, Padding> {\n                        typedef typename ctr_policy<Cipher, Padding>::size_type size_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::cipher_type cipher_type;\n                        typedef typename ctr_policy<Cipher, Padding>::padding_type padding_type;\n\n                        constexpr static const std::size_t block_bits = ctr_policy<Cipher, Padding>::block_bits;\n                        constexpr static const std::size_t block_words = ctr_policy<Cipher, Padding>::block_words;\n                        typedef typename ctr_policy<Cipher, Padding>::block_type block_type;\n\n                        typedef typename ctr_policy<Cipher, Padding>::iv_type iv_type;\n\n                        inline static block_type begin_message(const cipher_type &cipher, const block_type &plaintext,\n                                                               const iv_type &iv = iv_type()) {\n                            block_type block = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(block, iv);\n\n                            return block;\n                        }\n\n                        inline static block_type process_block(const cipher_type &cipher, const block_type &plaintext,\n                                                               const block_type &previous = block_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, previous);\n\n                            return result;\n                        }\n\n                        inline static block_type end_message(const cipher_type &cipher, const block_type &plaintext,\n                                                             const iv_type &iv = iv_type()) {\n                            block_type result = cipher.decrypt(plaintext);\n\n                            //                        codec::encode<codec::encoder::logic_xor>(result, iv);\n\n                            return result;\n                        }\n                    };\n\n                    template<typename Policy>\n                    class counter {\n                        typedef Policy policy_type;\n\n                    public:\n                        typedef typename policy_type::cipher_type cipher_type;\n                        typedef typename policy_type::padding_type padding_type;\n\n                        typedef typename policy_type::size_type size_type;\n\n                        typedef typename cipher_type::key_type key_type;\n                        typedef typename policy_type::iv_type iv_type;\n\n                        constexpr static const size_type block_bits = policy_type::block_bits;\n                        constexpr static const size_type block_words = policy_type::block_words;\n                        typedef typename cipher_type::block_type block_type;\n\n                        counter(const cipher_type &cipher) : cipher(cipher) {\n                        }\n\n                        block_type begin_message(const block_type &plaintext, const iv_type &iv = iv_type()) {\n                            previous = policy_type::begin_message(cipher, plaintext, iv);\n                            return previous;\n                        }\n\n                        block_type process_block(const block_type &plaintext) {\n                            previous = policy_type::process_block(cipher, plaintext, previous);\n                            return previous;\n                        }\n\n                        block_type end_message(const block_type &plaintext, const iv_type &iv = iv_type()) {\n                            return policy_type::end_message(cipher, plaintext, iv);\n                        }\n\n                        inline static size_type required_output_size(size_type inputlen) {\n                            return padding_type::required_output_size(inputlen);\n                        }\n\n                    protected:\n                        block_type previous;\n                        cipher_type cipher;\n                    };\n                }    // namespace detail\n\n                /*!\n                 * @brief Counter Mode (CTR).\n                 * @tparam Cipher\n                 * @tparam Padding\n                 *\n                 * @ingroup block_modes\n                 */\n                template<typename Cipher, template<typename> class Padding,\n                         template<typename, template<typename> class> class CiphertextStealingMode = cts0>\n                struct counter {\n                    typedef Cipher cipher_type;\n                    typedef Padding<Cipher> padding_type;\n                    typedef CiphertextStealingMode<Cipher, Padding> ciphertext_stealing_type;\n\n                    typedef detail::ctr_encryption_policy<cipher_type, padding_type, ciphertext_stealing_type>\n                        encryption_policy;\n                    typedef detail::ctr_decryption_policy<cipher_type, padding_type, ciphertext_stealing_type>\n                        decryption_policy;\n\n                    template<template<typename, typename> class Policy>\n                    struct bind {\n                        typedef detail::counter<Policy<cipher_type, padding_type>> type;\n                    };\n                };\n\n                /*!\n                 * @brief\n                 *\n                 * @tparam Cipher\n                 * @tparam Padding\n                 * @tparam CiphertextStealingMode\n                 *\n                 * @ingroup block_modes\n                 */\n                template<typename Cipher, template<typename> class Padding,\n                         template<typename, template<typename> class> class CiphertextStealingMode>\n                using ctr = counter<Cipher, Padding, CiphertextStealingMode>;\n            }    // namespace modes\n        }        // namespace block\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "95cdca4519b9df2e8911fd84ffc4b74dce6b5dd2", "size": 29304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/modes/ctr.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/modes/ctr.hpp", "max_issues_repo_name": "NilFoundation/crypto3-modes", "max_issues_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:20:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:26:17.000Z", "max_forks_repo_path": "include/nil/crypto3/modes/ctr.hpp", "max_forks_repo_name": "NilFoundation/crypto3-modes", "max_forks_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 54.468401487, "max_line_length": 120, "alphanum_fraction": 0.4848143598, "num_tokens": 4438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.03114382918590039, "lm_q1q2_score": 0.013396435549125443}}
{"text": "﻿/*! \\file readinputfile.cpp\n    \\brief インプットファイルの読み込みを行うクラスの実装\n\n    Copyright ©  2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"readinputfile.h\"\n#include <iostream>                     // for std::cerr\n#include <stdexcept>                    // for std::runtime_error\n#include <boost/algorithm/string.hpp>   // for boost::algorithm\n#include <boost/assert.hpp>             // for BPOOST_ASSERT\n#include <boost/cast.hpp>               // for boost::numeric_cast\n#include <boost/range/algorithm.hpp>    // for boost::find\n\nnamespace schrac {\n    // #region staticメンバ変数\n\n    ci_string const ReadInputFile::CHEMICAL_SYMBOL = \"chemical.symbol\";\n\tci_string const ReadInputFile::EQ_TYPE_DEFAULT = \"sch\";\n\tci_string const ReadInputFile::EQ_TYPE = \"eq.type\";\n    std::array<ci_string, 4> const ReadInputFile::EQ_TYPE_ARRAY =\n    {\n        ci_string(\"sch\"),\n        ci_string(\"sdirac\"),\n        ci_string(\"dirac\")\n    };\n    ci_string const ReadInputFile::ORBITAL = \"orbital\";\n    const std::array<ci_string, 4> ReadInputFile::SOLVER_TYPE_ARRAY =\n    {\n        ci_string(\"adams_bashforth_moulton\"),\n        ci_string(\"bulirsch_stoer\"),\n        ci_string(\"controlled_runge_kutta\")\n    };\n    ci_string const ReadInputFile::SOLVER_TYPE_DEFAULT = \"controlled_runge_kutta\";\n\tci_string const ReadInputFile::SPIN_ORBITAL = \"spin.orbital\";\n\tci_string const ReadInputFile::SPIN_ORBITAL_DEFAULT = \"alpha\";\n\n    // #endregion staticメンバ変数\n\n    // #region コンストラクタ\n\n    ReadInputFile::ReadInputFile(std::pair<std::string, bool> const & arg) :\n        PData([this]() { return std::cref(pdata_); }, nullptr), \n        ifs_(std::get<0>(arg).c_str()),\n        lineindex_(1),\n        pdata_(std::make_shared<Data>())\n    {\n        pdata_->usetbb_ = std::get<1>(arg);\n    }\n\n    // #endregion コンストラクタ\n\n    // #region publicメンバ関数\n        \n    void ReadInputFile::readFile()\n    {\n        if (!ifs_.is_open())\n            throw std::runtime_error(\"インプットファイルが開けませんでした\");\n\n        auto const errorendfunc = []() {\n            throw std::runtime_error(\"インプットファイルが異常です\");\n        };\n\n        if (!readAtom()) {\n            errorendfunc();\n        }\n\n        if (!readEq()) {\n            errorendfunc();\n        }\n\n        // グリッドの最小値を読み込む\n        readValue(\"grid.xmin\", XMIN_DEFAULT, pdata_->xmin_);\n\n        // グリッドの最大値を読み込む\n        readValue(\"grid.xmax\", XMAX_DEFAULT, pdata_->xmax_);\n\n        // グリッドのサイズを読み込む\n        readValue(\"grid.num\", GRID_NUM_DEFAULT, pdata_->grid_num_);\n\n        // 許容誤差を読み込む\n        readValue(\"eps\", EPS_DEFAULT, pdata_->eps_);\n\n        // 解く方程式のタイプを読み込む\n        if (!readSolverType()) {\n            errorendfunc();\n        }\n\n        // 固有値探索をはじめる値を読み込む\n        if (!readValueAuto(\"search.LowerE\", pdata_->search_lowerE_)) {\n            errorendfunc();\n        }\n\n        // 固有値検索の間隔を読み込む\n        readValue(\"num.of.partition\", NUM_OF_PARTITION_DEFAULT, pdata_->num_of_partition_);\n\n        // マッチングポイントを読み込む\n        readValue(\"matching.point.ratio\", MAT_PO_RATIO_DEFAULT, pdata_->mat_po_ratio_);\n\n        // 密度の初期値ρ0(r)のための係数cを読み込む\n        if (!readValueAuto(\"rho0.c\", pdata_->rho0_c_)) {\n            errorendfunc();\n        }\n\n        // 密度の初期値ρ0(r)のための係数alphaを読み込む\n        if (!readValueAuto(\"rho0.alpha\", pdata_->rho0_alpha_)) {\n            errorendfunc();\n        }\n\n        // SCFの最大ループ回数を読み込む\n        readValue(\"scf.maxIter\", SCF_MAXITER_DEFAULT, pdata_->scf_maxiter_);\n\n        // SCFの一次混合の重みを読み込む\n        if (!readScfMixingWeight()) {\n            errorendfunc();\n        }\n        \n        // SCFの収束判定条件の値を読み込む\n        readValue(\"scf.criterion\", SCF_CRITERION_DEFAULT, pdata_->scf_criterion_);\n    }\n    \n    // #endregion publicメンバ関数\n\n    // #region privateメンバ関数\n\n    void ReadInputFile::errorMessage(ci_string const & s) const\n    {\n        std::cerr << \"インプットファイルに\" << s.c_str() << \"の行が見つかりませんでした。\\n\";\n    }\n\n    void ReadInputFile::errorMessage(std::int32_t line, ci_string const & s1, ci_string const & s2) const\n    {\n        std::cerr << \"インプットファイルの[\" << s1.c_str() << \"]の行が正しくありません。\\n\";\n        std::cerr << line << \"行目, 未知のトークン:\" << s2.c_str() << std::endl;\n    }\n\n    std::pair<std::int32_t, std::optional<ReadInputFile::strvec>> ReadInputFile::getToken(ci_string const & article)\n    {\n        using namespace boost::algorithm;\n\n        std::array<char, BUFSIZE> buf;\n        ifs_.getline(buf.data(), BUFSIZE);\n        ci_string const line(buf.data());\n\n        // もし一文字も読めなかったら\n        if (!ifs_.gcount()) {\n            errorMessage(article);\n            return std::make_pair(-1, std::nullopt);\n        }\n\n        // 読み込んだ行が空、あるいはコメント行でないなら\n        if (!line.empty() && (line[0] != '#')) {\n            // トークン分割\n            strvec tokens;\n            split(tokens, line, is_any_of(\" \\t\"), token_compress_on);\n            \n            auto const itr(tokens.begin());\n\n            if (*itr != article) {\n                errorMessage(lineindex_, article, *itr);\n                return std::make_pair(-1, std::nullopt);\n            }\n\n            return std::make_pair(0, std::make_optional<strvec>(std::move(tokens)));\n        }\n        else {\n            return std::make_pair(1, std::nullopt);\n        }\n    }\n\n    bool ReadInputFile::readAtom()\n    {\n        // 原子の種類を読み込む\n        auto const chemsym(readData(ReadInputFile::CHEMICAL_SYMBOL));\n        if (!chemsym) {\n            return false;\n        }\n\n        try {\n            auto const itr(boost::find(Data::Chemical_Symbol, chemsym->c_str()));\n            if (itr == Data::Chemical_Symbol.end()) {\n                throw std::invalid_argument(\"\");\n            }\n\n            pdata_->chemical_symbol_ = *itr;\n            pdata_->Z_ = static_cast<double>(std::distance(Data::Chemical_Symbol.begin(), itr)) + 1.0;\n        }\n        catch (std::invalid_argument const &) {\n            errorMessage(lineindex_ - 1, ReadInputFile::CHEMICAL_SYMBOL, *chemsym);\n            return false;\n        }\n\n        // 軌道を読み込む\n        auto const porbital(readData(ReadInputFile::ORBITAL));\n        if (!porbital) {\n            return false;\n        }\n\n        auto const orbital(*porbital);\n        if (orbital.length() != 2) {\n            errorMessage(lineindex_ - 1, ReadInputFile::ORBITAL, orbital);\n            return false;\n        }\n\n        if (!std::isdigit(orbital[0])) {\n            errorMessage(lineindex_ - 1, ReadInputFile::ORBITAL, orbital);\n            return false;\n        }\n        pdata_->orbital_ = orbital[0];\n        pdata_->n_ = boost::numeric_cast<std::uint8_t>(orbital[0] - '0');\n\n        switch (orbital[1]) {\n        case 's':\n            pdata_->l_ = 0;\n            pdata_->orbital_ += 's';\n            break;\n\n        case 'p':\n            pdata_->l_ = 1;\n            pdata_->orbital_ += 'p';\n            break;\n\n        case 'd':\n            pdata_->l_ = 2;\n            pdata_->orbital_ += 'd';\n            break;\n\n        case 'f':\n            pdata_->l_ = 3;\n            pdata_->orbital_ += 'f';\n            break;\n\n        case 'g':\n            pdata_->l_ = 4;\n            pdata_->orbital_ += 'g';\n            break;\n\n        default:\n            errorMessage(lineindex_ - 1, ReadInputFile::ORBITAL, orbital);\n            return false;\n            break;\n        }\n\n        if (pdata_->n_ - pdata_->l_ < 1) {\n            std::cerr << \"量子数の指定が異常です。\\n\";\n            return false;\n        }\n\n        // スピン軌道を読み込む\n        auto const pspin_orbital(readData(ReadInputFile::SPIN_ORBITAL, ReadInputFile::SPIN_ORBITAL_DEFAULT));\n        if (!pspin_orbital) {\n            return false;\n        }\n\n        pdata_->spin_orbital_ = *pspin_orbital;\n        if (pdata_->spin_orbital_ != Data::ALPHA && pdata_->spin_orbital_ != Data::BETA) {\n            errorMessage(lineindex_ - 1, ReadInputFile::SPIN_ORBITAL, pdata_->spin_orbital_);\n            return false;\n        }\n\n        if (!pdata_->l_) {\n            // s軌道は特別なケース\n            // j = l_ + 1/2\n            pdata_->j_ = 0.5;\n            pdata_->kappa_ = -1.0;\n        }\n        else if (pdata_->spin_orbital_ == Data::ALPHA) {\n            // j = l_ + 1/2に対して\n            pdata_->j_ = static_cast<double>(pdata_->l_) + 0.5;\n            pdata_->kappa_ = -static_cast<double>(pdata_->l_) - 1.0;\n        }\n        else {\n            // j = l_ - 1/2に対して\n            pdata_->j_ = static_cast<double>(pdata_->l_) - 0.5;\n            pdata_->kappa_ = static_cast<double>(pdata_->l_);\n        }\n\n        return true;\n    }\n\n    std::optional<ci_string> ReadInputFile::readData(ci_string const & article)\n    {\n        for (; true; lineindex_++) {\n            auto const ret(getToken(article));\n\n            switch (std::get<0>(ret))\n            {\n            case -1:\n                return std::nullopt;\n                break;\n\n            case 0:\n            {\n                auto const tokens(*(std::get<1>(ret)));\n\n                // 読み込んだトークンの数がもし2個以外だったら\n                if (tokens.size() != 2 || tokens[1].empty()) {\n                    std::cerr << \"インプットファイル\" << lineindex_ << \"行目の、[\" << article.c_str() << \"]の行が正しくありません。\\n\";\n                    return std::nullopt;\n                }\n\n                ++lineindex_;\n                return *(++tokens.begin());\n            }\n            case 1:\n                break;\n\n            default:\n                BOOST_ASSERT(!\"何かがおかしい!\");\n                break;\n            }\n        }\n    }\n\n    std::optional<ci_string> ReadInputFile::readData(ci_string const & article, ci_string const & def)\n    {\n        // グリッドを読み込む\n        for (; true; lineindex_++) {\n            auto const ret(getToken(article));\n\n            switch (std::get<0>(ret))\n            {\n            case -1:\n                return std::nullopt;\n                break;\n\n            case 0:\n            {\n                auto const tokens(*(std::get<1>(ret)));\n                auto itr(++tokens.begin());\n                ++lineindex_;\n\n                // 読み込んだトークンの数をはかる\n                switch (tokens.size()) {\n                case 1:\n                    // デフォルト値を返す\n                    return def;\n                    break;\n\n                case 2:\n                    return *itr == \"DEFAULT\" ? def : *itr;\n                    break;\n\n                default:\n                    {\n                        auto val(*itr);\n\n                        if (val == \"DEFAULT\" || val[0] == '#') {\n                            // デフォルト値を返す\n                            return def;\n                        }\n                        else if ((*(++itr))[0] != '#') {\n                            errorMessage(lineindex_ - 1, article, *itr);\n                            return std::nullopt;\n                        }\n\n                        return val;\n                    }\n                }\n            }\n                break;\n\n            case 1:\n                break;\n\n            default:\n                BOOST_ASSERT(!\"何かがおかしい!\");\n                break;\n            }\n        }\n    }\n\n    std::optional<ci_string> ReadInputFile::readDataAuto(ci_string const & article)\n    {\n        for (; true; lineindex_++) {\n            auto const ret(getToken(article));\n\n            switch (std::get<0>(ret))\n            {\n            case -1:\n                return std::nullopt;\n                break;\n\n            case 0:\n            {\n                auto const tokens(*(std::get<1>(ret)));\n                auto itr(++tokens.begin());\n                ++lineindex_;\n\n                // 読み込んだトークンの数をはかる\n                switch (tokens.size()) {\n                case 1:\n                    return std::nullopt;\n                    break;\n\n                case 2:\n                    return (*itr == \"DEFAULT\" || *itr == \"AUTO\") ?\n                        std::make_optional<ci_string>(ci_string()) : std::make_optional<ci_string>(*itr);\n                    break;\n\n                default:\n                    {\n                        auto val = *itr;\n\n                        if (val == \"DEFAULT\" || val == \"AUTO\" || val[0] == '#') {\n                            // デフォルト値を返す\n                            return std::make_optional<ci_string>(ci_string());\n                        } else if ((*(++itr))[0] != '#') {\n                            errorMessage(lineindex_ - 1, article, *itr);\n\n                            // エラー\n                            return std::nullopt;\n                        }\n\n                        return std::make_optional<ci_string>(std::move(val));\n                    }\n                }\n            }\n                break;\n\n            case 1:\n                break;\n\n            default:\n                BOOST_ASSERT(!\"何かがおかしい!\");\n                break;\n            }\n        }\n    }\n    \n    bool ReadInputFile::readEq()\n    {\n        auto const peqtype(readData(ReadInputFile::EQ_TYPE, ReadInputFile::EQ_TYPE_DEFAULT));\n        if (!peqtype) {\n            return false;\n        }\n\n        auto const eqtype(*peqtype);\n        auto const itr(boost::find(ReadInputFile::EQ_TYPE_ARRAY, eqtype));\n        \n        if (itr == ReadInputFile::EQ_TYPE_ARRAY.end()) {\n            errorMessage(lineindex_ - 1, ReadInputFile::EQ_TYPE, eqtype);\n            return false;\n        }\n        else if (itr != ReadInputFile::EQ_TYPE_ARRAY.begin()) {\n            pdata_->eq_type_ = boost::numeric_cast<Data::Eq_type>(std::distance(ReadInputFile::EQ_TYPE_ARRAY.begin(), itr));\n        }\n\n        if (pdata_->eq_type_ == Data::Eq_type::SDIRAC) {\n            // scalar Dirac方程式の場合\n            // j = l_ + 1/2\n            pdata_->j_ = 0.5;\n            pdata_->kappa_ = -1.0;\n        }\n\n        return true;\n    }\n\n    bool ReadInputFile::readScfMixingWeight()\n    {\n        readValue(\"scf.Mixing.Weight\", SCF_MIXING_WEIGHT_DEFAULT, pdata_->scf_mixing_weight_);\n        if (pdata_->scf_mixing_weight_ <= 0.0 || pdata_->scf_mixing_weight_ > 1.0) {\n            std::cerr << \"インプットファイルの[scf.Mixing.Weight]の行が正しくありません。\\n\";\n            return false;\n        }\n        return true;\n    }\n\n    bool ReadInputFile::readSolverType()\n    {\n        auto const psolvetype(readData(\"solver.type\", ReadInputFile::SOLVER_TYPE_DEFAULT));\n        if (!psolvetype) {\n            return false;\n        }\n\n        auto const solvertype = *psolvetype;\n        auto const itr(boost::find(ReadInputFile::SOLVER_TYPE_ARRAY, solvertype));\n        if (itr == ReadInputFile::SOLVER_TYPE_ARRAY.end()) {\n            errorMessage(lineindex_ - 1, \"solver.type\", solvertype);\n            return false;\n        } else {\n            pdata_->solver_type_ = boost::numeric_cast<Data::Solver_type>(\n                std::distance(ReadInputFile::SOLVER_TYPE_ARRAY.begin(), itr));\n        }\n\n        return true;\n    }\n\n    // #endregion privateメンバ関数\n}\n", "meta": {"hexsha": "9ba4e6ac4c67c2f6ea6b10ac6ada7d4450c0e361", "size": 14616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/readinputfile.cpp", "max_stars_repo_name": "dc1394/Schrac", "max_stars_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T23:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T07:10:30.000Z", "max_issues_repo_path": "src/readinputfile.cpp", "max_issues_repo_name": "dc1394/schrac", "max_issues_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "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/readinputfile.cpp", "max_forks_repo_name": "dc1394/schrac", "max_forks_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "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.7073170732, "max_line_length": 124, "alphanum_fraction": 0.4954844007, "num_tokens": 4016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567817320044, "lm_q2_score": 0.04813676838557257, "lm_q1q2_score": 0.013394382253948317}}
{"text": "/**\n * An implementation of the intrusive AVL tree to store a sequence of elements.\n * The inorder traversal of the tree coincides with the sequence.\n */\n\n#pragma once\n\n#include <iterator>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <utility>\n#include <functional>\n#include <type_traits>\n#include <boost/optional.hpp>\n\nnamespace Snu {\nnamespace Cnrc {\nnamespace AVLSequence {\n\nclass AVLSequenceModule {\n\t\npublic:\n\t\n\ttemplate<class T, class SizeType>\n\tclass AVLSequenceNodeMixin;\n\t\t\n\t/**\n\t * This trait defines an interface for the type `T` to be stored in an intrusive AVL tree.\n\t * If `T` extends AVLSequenceNodeMixin<T>, the default implementation of the trait will just work.\n\t * If not, a specialization of this template for `T` must be provided.\n\t */\n\ttemplate<class T>\n\tclass AVLSequenceNodeTrait {\n\t\n\tprivate:\n\t\t\n\t\tusing NodeMixin = AVLSequenceNodeMixin<T, typename T::Size>;\n\t\t\n\t\tstatic_assert(\n\t\t\tstd::is_base_of<NodeMixin, T>::value, \n\t\t\t\"The default implementation of AVLSequenceNodeTrait<T> requires T extending AVLSequenceNodeMixin. \"\n\t\t\t\"Or you can specialize AVLSequenceNodeTrait for T\"\n\t\t);\n\t\t\n\tpublic:\n\t\t\n\t\tusing Node = T;\n\t\tusing Size = typename Node::Size;\n\t\tusing Height = typename Node::Height;\n\t\n\tpublic:\n\t\t\n\t\tstatic T* parent(const T* const n) {\n\t\t\treturn static_cast<const NodeMixin*>(n)->parent;\n\t\t}\n\t\t\n\t\tstatic void parent(T* const n, T* const p) {\n\t\t\tstatic_cast<NodeMixin*>(n)->parent = p;\n\t\t}\n\t\t\n\t\tstatic T* leftChild(const T* const n) {\n\t\t\treturn static_cast<const NodeMixin*>(n)->leftChild;\n\t\t}\n\t\t\n\t\tstatic void leftChild(T* const n, T* const l) {\n\t\t\tstatic_cast<NodeMixin*>(n)->leftChild = l;\n\t\t}\n\t\n\t\tstatic T* rightChild(const T* n) {\n\t\t\treturn static_cast<const NodeMixin*>(n)->rightChild;\n\t\t}\n\t\t\n\t\tstatic void rightChild(T* const n, T* const r) {\n\t\t\tstatic_cast<NodeMixin*>(n)->rightChild = r;\n\t\t}\n\t\t\n\t\tstatic Height height(const T* const n) {\n\t\t\treturn static_cast<const NodeMixin*>(n)->height;\n\t\t}\n\t\t\n\t\tstatic void height(T* const n, Height h) {\n\t\t\tstatic_cast<NodeMixin*>(n)->height = h;\n\t\t}\n\t\t\n\t\tstatic Size volume(const T* const n) {\n\t\t\treturn static_cast<const NodeMixin*>(n)->volume;\n\t\t}\n\t\t\n\t\tstatic void volume(T* const n, Size v) {\n\t\t\tstatic_cast<NodeMixin*>(n)->volume = v;\n\t\t}\n\t\t\n\t\tstatic void augment(T* const) {\n\t\t}\n\t\t\n\t};\n\t\n\t/**\n\t * This class works as a mixin by CRTP to store a sequence of type `T` objects in \n\t * an AVL tree with the help of `AVLSequenceNodeTrait<T>`.\n\t */\n\ttemplate<class T, class SizeType>\n\tclass AVLSequenceNodeMixin {\n\t\t\n\tpublic:\n\t\t\n\t\tusing Size = SizeType;\n\t\tusing Height = unsigned int;\n\t\n\tpublic:\n\t\t\n\t\tAVLSequenceNodeMixin()\n\t\t: parent(nullptr), leftChild(nullptr), rightChild(nullptr)\n\t\t, height(1), volume(1) {\n\t\t}\n\t\t\n\t\tAVLSequenceNodeMixin(const AVLSequenceNodeMixin&) = delete;\n\t\t\n\t\tAVLSequenceNodeMixin(AVLSequenceNodeMixin&& other) {\n\t\t\t*this = std::move(other);\n\t\t}\n\t\t\n\t\tAVLSequenceNodeMixin& operator=(const AVLSequenceNodeMixin&) = delete;\n\t\t\n\t\tAVLSequenceNodeMixin& operator=(AVLSequenceNodeMixin&& other) {\n\t\t\tparent = other.parent;\n\t\t\tleftChild = other.leftChild;\n\t\t\trightChild = other.rightChild;\n\t\t\theight = other.height;\n\t\t\tvolume = other.volume;\n\t\t\tif(parent != nullptr) {\n\t\t\t\tif(parent->leftChild == &other) {\n\t\t\t\t\tparent->leftChild = static_cast<T*>(this);\n\t\t\t\t} else {\n\t\t\t\t\tparent->rightChild = static_cast<T*>(this);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(leftChild != nullptr) {\n\t\t\t\tleftChild->parent = static_cast<T*>(this);\n\t\t\t}\n\t\t\tif(rightChild != nullptr) {\n\t\t\t\trightChild->parent = static_cast<T*>(this);\n\t\t\t}\n\t\t\tother.parent = nullptr;\n\t\t\tother.leftChild = nullptr;\n\t\t\tother.rightChild = nullptr;\n\t\t\tother.height = 1;\n\t\t\tother.volume = 1;\n\t\t\treturn *this;\n\t\t}\n\t\n\tprivate:\n\t\t\n\t\tT* parent;\n\t\tT* leftChild;\n\t\tT* rightChild;\n\t\tHeight height;\n\t\tSize volume;\n\n\t\tfriend class AVLSequenceNodeTrait<T>;\n\t\t\n\t};\n\t\n\t/**\n\t * This provides operations to store a sequence of instances of `Node` \n\t * in an intrusive AVL tree with the aid of `AVLSequenceNodeTrait<Node>`.\n\t * `Node` must implement the interface defined by the template class `AVLSequenceNodeTrait<Node>`.\n\t * Or you can provide an equivalent trait implementation by specifying the second template paramater.\n\t */\n\ttemplate<class Node, class NodeTrait = AVLSequenceNodeTrait<Node>>\n\tclass AVLSequenceAlgorithm {\n\t\t\n\tpublic:\n\t\t\n\t\tusing Size = typename NodeTrait::Size;\n\t\tusing Height = typename NodeTrait::Height;\n\n\tprivate:\n\n\t\ttemplate<class T>\n\t\tusing optional = boost::optional<std::reference_wrapper<T>>;\n\t\t\n\tprivate:\n\t\t\n\t\tusing T = NodeTrait;\n\t\t\n\tprivate:\n\t\n\t\ttemplate<class CNode>\n\t\tclass IteratorImpl : public std::iterator<std::bidirectional_iterator_tag, CNode> {\n\t\t\t\n\t\tprivate:\n\t\t\t\n\t\t\tusing This = IteratorImpl<CNode>;\n\t\t\n\t\tpublic:\n\t\t\t\n\t\t\tIteratorImpl() \n\t\t\t: p(nullptr), q(nullptr) {\n\t\t\t}\n\t\t\t\n\t\t\tIteratorImpl(CNode* p, CNode* q)\n\t\t\t: p(p), q(q) {\n\t\t\t}\n\t\t\t\n\t\tpublic:\n\t\t\t\n\t\t\tThis& operator++() {\n\t\t\t\tif(! p) {\n\t\t\t\t\tp = q;\n\t\t\t\t\tq = nullptr;\n\t\t\t\t} else if(auto r = next(p)) {\n\t\t\t\t\tp = &(r->get());\n\t\t\t\t} else {\n\t\t\t\t\tq = p;\n\t\t\t\t\tp = nullptr;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t\n\t\t\tThis operator++(int) {\n\t\t\t\tThis tmp(*this);\n\t\t\t\toperator++();\n\t\t\t\treturn tmp;\n\t\t\t}\n\t\t\t\n\t\t\tThis& operator--() {\n\t\t\t\tif(! p) {\n\t\t\t\t\tp = q;\n\t\t\t\t\tq = nullptr;\n\t\t\t\t} else if(auto r = previous(p)) {\n\t\t\t\t\tp = &(r->get());\n\t\t\t\t} else {\n\t\t\t\t\tq = p;\n\t\t\t\t\tp = nullptr;\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t\n\t\t\tThis operator--(int) {\n\t\t\t\tThis tmp(*this);\n\t\t\t\toperator--();\n\t\t\t\treturn tmp;\n\t\t\t}\n\t\t\t\n\t\t\tbool operator==(const This& other) const {\n\t\t\t\treturn p == other.p && q == other.q;\n\t\t\t}\n\t\t\t\n\t\t\tbool operator!=(const This& other) const {\n\t\t\t\treturn p != other.p || q != other.q;\n\t\t\t}\n\t\t\t\n\t\t\tCNode& operator*() const {\n\t\t\t\treturn *p;\n\t\t\t}\n\t\t\t\n\t\t\tCNode* operator->() const {\n\t\t\t\treturn p;\n\t\t\t}\n\t\t\n\t\tprivate:\n\t\t\t\n\t\t\tCNode* p;\n\t\t\tCNode* q;\n\t\t};\n\t\t\n\tpublic:\n\t\t\n\t\tclass ContainerView {\n\t\t\t\n\t\tpublic:\n\t\t\t\n\t\t\tusing iterator = IteratorImpl<Node>;\n\t\t\tusing const_iterator = IteratorImpl<const Node>;\n\t\t\tusing reverse_iterator = std::reverse_iterator<iterator>;\n\t\t\tusing const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\t\t\t\n\t\tpublic:\n\t\t\t\n\t\t\texplicit ContainerView(Node& root)\n\t\t\t: root(&root) {\n\t\t\t}\n\t\t\t\n\t\tpublic:\n\t\t\t\n\t\t\titerator begin() {\n\t\t\t\treturn iterator(findHead(root), nullptr);\n\t\t\t}\n\t\t\t\n\t\t\titerator end() {\n\t\t\t\treturn iterator(nullptr, findTail(root));\n\t\t\t}\n\t\t\t\n\t\t\tconst_iterator begin() const {\n\t\t\t\treturn const_iterator(findHead(root), nullptr);\n\t\t\t}\n\t\t\t\n\t\t\tconst_iterator end() const {\n\t\t\t\treturn const_iterator(nullptr, findTail(root));\n\t\t\t}\n\t\t\t\n\t\t\treverse_iterator rbegin() {\n\t\t\t\treturn std::reverse_iterator<iterator>(end());\n\t\t\t}\n\t\t\t\n\t\t\treverse_iterator rend() {\n\t\t\t\treturn std::reverse_iterator<iterator>(begin());\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator rbegin() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(end());\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator rend() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(begin());\n\t\t\t}\n\t\t\t\n\t\t\tconst_iterator cbegin() const {\n\t\t\t\treturn const_iterator(findHead(root), nullptr);\n\t\t\t}\n\t\t\t\n\t\t\tconst_iterator cend() const {\n\t\t\t\treturn const_iterator(nullptr, findTail(root));\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator crbegin() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(end());\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator crend() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(begin());\n\t\t\t}\n\t\t\t\n\t\tprivate:\n\t\t\t\n\t\t\tNode* const root;\n\t\t};\n\t\t\t\n\t\tclass ConstContainerView {\n\t\t\t\n\t\tpublic:\n\t\t\t\n\t\t\tusing const_iterator = IteratorImpl<const Node>;\n\t\t\tusing const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\t\t\t\n\t\tpublic:\n\t\t\t\n\t\t\texplicit ConstContainerView(const Node& root)\n\t\t\t: root(&root) {\n\t\t\t}\n\t\t\t\n\t\tpublic:\n\t\t\t\n\t\t\tconst_iterator begin() const {\n\t\t\t\treturn const_iterator(findHead(root), nullptr);\n\t\t\t}\n\t\t\t\n\t\t\tconst_iterator end() const {\n\t\t\t\treturn const_iterator(nullptr, findTail(root));\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator rbegin() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(end());\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator rend() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(begin());\n\t\t\t}\n\t\t\t\n\t\t\tconst_iterator cbegin() const {\n\t\t\t\treturn const_iterator(findHead(root), nullptr);\n\t\t\t}\n\t\t\t\n\t\t\tconst_iterator cend() const {\n\t\t\t\treturn const_iterator(nullptr, findTail(root));\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator crbegin() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(end());\n\t\t\t}\n\t\t\t\n\t\t\tconst_reverse_iterator crend() const {\n\t\t\t\treturn std::reverse_iterator<const_iterator>(begin());\n\t\t\t}\n\t\t\t\n\t\tprivate:\n\t\t\t\n\t\t\tconst Node* const root;\n\t\t};\n\t\t\n\tpublic:\n\t\t\n\t\t/**\n\t\t * Returns ContainerView of the sequence whose root is `p`.\n\t\t * ContainerView has an interface for STL compatible iterators.\n\t\t */\n\t\tstatic ContainerView containerView(Node& p) {\n\t\t\treturn ContainerView(p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns ContainerView of the sequence whose root is `p`.\n\t\t * ContainerView has an interface for STL compatible iterators.\n\t\t */\n\t\tstatic ConstContainerView containerView(const Node& p) {\n\t\t\treturn ConstContainerView(p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Inserts node `n` before `p`.\n\t\t */\n\t\tstatic void insertNodeBefore(Node& p, Node& n) {\n\t\t\tinsertNodeBefore(&p, &n);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Inserts node `n` after `p`.\n\t\t */\n\t\tstatic void insertNodeAfter(Node& p, Node& n) {\n\t\t\tinsertNodeAfter(&p, &n);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Isolate `p` from its tree.\n\t\t * `p` becomes a tree of its own.\n\t\t */\n\t\tstatic void removeNode(Node& p) {\n\t\t\tremoveNode(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Joins the sequence whose rightmost element is `p` with \n\t\t * the sequence whose leftmost element is `q`.\n\t\t */\n\t\tstatic void join(Node& p, Node& q) {\n\t\t\tjoin(&p, &q);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Splits `p` and its predecessor.\n\t\t */\n\t\tstatic void splitBefore(Node& p) {\n\t\t\tsplitBefore(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Splits `p` and its successor.\n\t\t */\n\t\tstatic void splitAfter(Node& p) {\n\t\t\tsplitAfter(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the size of the subtree rooted at `p`.\n\t\t */\n\t\tstatic Size size(const Node& p) {\n\t\t\treturn T::volume(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the root of the tree containing `p`.\n\t\t */\n\t\tstatic Node& findRoot(Node& p) {\n\t\t\treturn *findRoot(&p); \n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the root of the tree containing `p`.\n\t\t */\n\t\tstatic const Node& findRoot(const Node& p) {\n\t\t\treturn *findRoot(&p); \n\t\t}\n\t\t\n\t\t/**\n\t\t * Finds the leftmost node of the subtree rooted at `p`.\n\t\t * Call this with the root to get the first element of the whole sequence.\n\t\t */\n\t\tstatic Node& findHead(Node& p) {\n\t\t\treturn *findHead(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Finds the leftmost node of the subtree rooted at `p`.\n\t\t * Call this with the root to get the first element of the whole sequence.\n\t\t */\n\t\tstatic const Node& findHead(const Node& p) {\n\t\t\treturn *findHead(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Finds the rightmost node of the subtree rooted at `p`.\n\t\t * Call this with the root to get the last element of the whole sequence.\n\t\t */\n\t\tstatic Node& findTail(Node& p) {\n\t\t\treturn *findTail(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Finds the rightmost node of the subtree rooted at `p`.\n\t\t * Call this with the root to get the last element of the whole sequence.\n\t\t */\n\t\tstatic const Node& findTail(const Node& p) {\n\t\t\treturn *findTail(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the node next to `p` if `p` is not the last element.\n\t\t */\n\t\tstatic optional<Node> next(Node& p) {\n\t\t\treturn next(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the node next to `p` if `p` is not the last element.\n\t\t */\n\t\tstatic optional<const Node> next(const Node& p) {\n\t\t\treturn next(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the node previous to `p` if `p` is not the first element.\n\t\t */\n\t\tstatic optional<Node> previous(Node& p) {\n\t\t\treturn previous(&p);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the node previous to `p` if `p` is not the first element.\n\t\t */\n\t\tstatic optional<const Node> previous(const Node& p) {\n\t\t\treturn previous(&p);\n\t\t}\n\t\n\tprivate:\n\t\t\n\t\tstatic void transplant(Node* p, Node* q) {\n\t\t\tif(T::parent(p)) {\n\t\t\t\tif(p == T::leftChild(T::parent(p))) {\n\t\t\t\t\tT::leftChild(T::parent(p), q);\n\t\t\t\t} else {\n\t\t\t\t\tT::rightChild(T::parent(p), q);\n\t\t\t\t}\n\t\t\t} //else set q as root (p was old root)\n\t\t\tif(q) {\n\t\t\t\tT::parent(q, T::parent(p));\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void setLeft(Node* const p, Node* const q) {\n\t\t\tif(p) {\n\t\t\t\tT::leftChild(p, q);\n\t\t\t}\n\t\t\tif(q) {\n\t\t\t\tT::parent(q, p);\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void setRight(Node* const p, Node* const q) {\n\t\t\tif(p) {\n\t\t\t\tT::rightChild(p, q);\n\t\t\t}\n\t\t\tif(q) {\n\t\t\t\tT::parent(q, p);\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic Height calcHeight(const Node* const p) {\n\t\t\treturn \n\t\t\t\tstd::max(\n\t\t\t\t\tT::leftChild(p)  ? T::height(T::leftChild(p))  : 0, \n\t\t\t\t\tT::rightChild(p) ? T::height(T::rightChild(p)) : 0\n\t\t\t\t) + 1;\n\t\t}\n\t\t\n\t\tstatic Size calcVolume(const Node* const p) {\n\t\t\treturn \n\t\t\t\t(T::leftChild(p)  ? T::volume(T::leftChild(p))  : 0) + \n\t\t\t\t(T::rightChild(p) ? T::volume(T::rightChild(p)) : 0) + 1;\n\t\t}\n\n\t\tstatic void augment(Node* const p) {\n\t\t\tT::height(p, calcHeight(p));\n\t\t\tT::volume(p, calcVolume(p));\n\t\t\tT::augment(p);\n\t\t}\n\t\t\n\t\tstatic void augmentUp(Node* const p) {\n\t\t\tif(p) {\n\t\t\t\taugment(p);\n\t\t\t\taugmentUp(T::parent(p));//expects TCO\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void rotateRight(Node* const p) {\n\t\t\tNode* const q = T::leftChild(p);\n\t\t\tT::leftChild(p, T::rightChild(q));\n\t\t\tif(T::leftChild(p)) {\n\t\t\t\tT::parent(T::leftChild(p), p);\n\t\t\t}\n\t\t\tT::parent(q, T::parent(p));\n\t\t\tif(Node* qp = T::parent(q)) {\n\t\t\t\tif(T::rightChild(qp) == p) {\n\t\t\t\t\tT::rightChild(qp, q);\n\t\t\t\t} else {\n\t\t\t\t\tT::leftChild(qp, q);\n\t\t\t\t}\n\t\t\t}// else set q as the new root (p was the old root)\n\t\t\tT::rightChild(q, p);\n\t\t\tT::parent(p, q);\n\t\t\taugment(p);\n\t\t\taugment(q);\n\t\t}\n\t\t\n\t\tstatic void rotateLeft(Node* const p) {\n\t\t\tNode* const q = T::rightChild(p);\n\t\t\tT::rightChild(p, T::leftChild(q));\n\t\t\tif(T::rightChild(p)) {\n\t\t\t\tT::parent(T::rightChild(p), p);\n\t\t\t}\n\t\t\tT::parent(q, T::parent(p));\n\t\t\tif(Node* qp = T::parent(q)) {\n\t\t\t\tif(T::leftChild(qp) == p) {\n\t\t\t\t\tT::leftChild(qp, q);\n\t\t\t\t} else {\n\t\t\t\t\tT::rightChild(qp, q);\n\t\t\t\t}\n\t\t\t}// else set q as the new root (p was the old root)\n\t\t\tT::leftChild(q, p);\n\t\t\tT::parent(p, q);\n\t\t\taugment(p);\n\t\t\taugment(q);\n\t\t}\n\t\t\n\t\tstatic int slope(const Node* const p) {\n\t\t\treturn \n\t\t\t\t(T::leftChild(p)  ? T::height(T::leftChild(p))  : 0) - \n\t\t\t\t(T::rightChild(p) ? T::height(T::rightChild(p)) : 0);\n\t\t}\n\t\t\n\t\tstatic void balance(Node* const p) {\n\t\t\tif(! p) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\taugment(p);\n\t\t\tconst int bf = slope(p);\n\t\t\tif(bf > 1) {\n\t\t\t\tif(slope(T::leftChild(p)) == -1) {\n\t\t\t\t\trotateLeft(T::leftChild(p));\n\t\t\t\t}\n\t\t\t\trotateRight(p);\n\t\t\t} else if(bf < -1) {\n\t\t\t\tif(slope(T::rightChild(p)) == 1) {\n\t\t\t\t\trotateRight(T::rightChild(p));\n\t\t\t\t}\n\t\t\t\trotateLeft(p);\n\t\t\t}\n\t\t\tbalance(T::parent(p));//expects TCO\n\t\t}\n\t\t\n\t\ttemplate<class CNode>\n\t\tstatic CNode* findRoot(CNode* p) {\n\t\t\twhile(T::parent(p)) {\n\t\t\t\tp = T::parent(p);\n\t\t\t}\n\t\t\treturn p;\n\t\t}\n\t\t\n\t\ttemplate<class CNode>\n\t\tstatic CNode* findHead(CNode* p) {\n\t\t\twhile(T::leftChild(p)) {\n\t\t\t\tp = T::leftChild(p);\n\t\t\t}\n\t\t\treturn p;\n\t\t}\n\t\t\n\t\ttemplate<class CNode>\n\t\tstatic CNode* findTail(CNode* p) {\n\t\t\twhile(T::rightChild(p)) {\n\t\t\t\tp = T::rightChild(p);\n\t\t\t}\n\t\t\treturn p;\n\t\t}\n\t\t\n\t\tstatic void insertNodeBefore(Node* const p, Node* const q) {\n\t\t\tT::leftChild(q, nullptr);\n\t\t\tT::rightChild(q, nullptr);\n\t\t\tT::height(q, 1);\n\t\t\tT::volume(q, 1);\n\t\t\tif(T::leftChild(p)) {\n\t\t\t\tNode* const r = findTail(T::leftChild(p));\n\t\t\t\tsetRight(r, q);\n\t\t\t\tbalance(r);\n\t\t\t} else {\n\t\t\t\tsetLeft(p, q);\n\t\t\t\tbalance(p);\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void insertNodeAfter(Node* const p, Node* const q) {\n\t\t\tT::leftChild(q, nullptr);\n\t\t\tT::rightChild(q, nullptr);\n\t\t\tT::height(q, 1);\n\t\t\tT::volume(q, 1);\n\t\t\tif(T::rightChild(p)) {\n\t\t\t\tNode* const r = findHead(T::rightChild(p));\n\t\t\t\tsetLeft(r, q);\n\t\t\t\tbalance(r);\n\t\t\t} else {\n\t\t\t\tsetRight(p, q);\n\t\t\t\tbalance(p);\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void removeNode(Node* const p) {\n\t\t\tif(! T::leftChild(p)) {\n\t\t\t\tNode* const b = T::parent(p);\n\t\t\t\ttransplant(p, T::rightChild(p));\n\t\t\t\tbalance(b);\n\t\t\t} else if(! T::rightChild(p)) {\n\t\t\t\tNode* const b = T::parent(p);\n\t\t\t\ttransplant(p, T::leftChild(p));\n\t\t\t\tbalance(b);\n\t\t\t} else {\n\t\t\t\tNode* const q = findHead(T::rightChild(p));\n\t\t\t\tNode* b = q;\n\t\t\t\tif(T::parent(q) != p) {\n\t\t\t\t\tb = T::parent(q);\n\t\t\t\t\tsetLeft(T::parent(q), T::rightChild(q));\n\t\t\t\t\tsetRight(q, T::rightChild(p));\n\t\t\t\t}\n\t\t\t\ttransplant(p, q);\n\t\t\t\tsetLeft(q, T::leftChild(p));\n\t\t\t\tbalance(b);\n\t\t\t}\n\t\t\tT::parent(p, nullptr);\n\t\t\tT::leftChild(p, nullptr);\n\t\t\tT::rightChild(p, nullptr);\n\t\t\tT::height(p, 1);\n\t\t\tT::volume(p, 1);\n\t\t}\n\t\t\n\t\tstatic void embed(Node* const p, Node* const q) {\n\t\t\tconst Height h = T::height(p);\n\t\t\tNode* const n = findTail(p);\n\t\t\tNode* b = n;\n\t\t\tif(T::parent(n)) {\n\t\t\t\tb = T::parent(n);\n\t\t\t\ttransplant(n, T::leftChild(n));\n\t\t\t\taugmentUp(T::parent(n));\n\t\t\t}\n\t\t\tNode* m = q;\n\t\t\twhile(h < T::height(m) && T::leftChild(m)) {\n\t\t\t\tm = T::leftChild(m);\n\t\t\t}\n\t\t\tsetLeft(T::parent(m), n);\n\t\t\tsetRight(n, m);\n\t\t\tif(n != p) {\n\t\t\t\tsetLeft(n, p);\n\t\t\t}\n\t\t\tbalance(b);\n\t\t}\n\t\t\n\t\tstatic void embrace(Node* const p, Node* const q) {\n\t\t\tconst Height h = T::height(q);\n\t\t\tNode* const n = findHead(q);\n\t\t\tNode* b = n;\n\t\t\tif(T::parent(n)) {\n\t\t\t\tb = T::parent(n);\n\t\t\t\ttransplant(n, T::rightChild(n));\n\t\t\t\taugmentUp(b);\n\t\t\t}\n\t\t\tNode* m = p;\n\t\t\twhile(h < T::height(m) && T::rightChild(m)) {\n\t\t\t\tm = T::rightChild(m);\n\t\t\t}\n\t\t\tsetRight(T::parent(m), n);\n\t\t\tsetLeft(n, m);\n\t\t\tif(n != q) {\n\t\t\t\tsetRight(n, q);\n\t\t\t}\n\t\t\tbalance(b);\n\t\t}\n\t\t\n\t\tstatic void join(Node* const p, Node* const q) {\n\t\t\tNode* const rp = findRoot(p);\n\t\t\tNode* const rq = findRoot(q);\n\t\t\tif(T::height(rp) < T::height(rq)) {\n\t\t\t\tembed(rp, rq);\n\t\t\t} else {\n\t\t\t\tembrace(rp, rq);\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void makeRoot(Node* const p) {\n\t\t\tif(T::parent(p)) {\n\t\t\t\tif(T::leftChild(T::parent(p)) == p) {\n\t\t\t\t\trotateRight(T::parent(p));\n\t\t\t\t} else {\n\t\t\t\t\trotateLeft(T::parent(p));\n\t\t\t\t}\n\t\t\t\tmakeRoot(p);//expects TCO\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void augmentHeightUp(Node* const p) {\n\t\t\tif(p) {\n\t\t\t\tHeight h = calcHeight(p);\n\t\t\t\tif(T::height(p) != h) {\n\t\t\t\t\tT::height(p, h);\n\t\t\t\t\taugmentHeightUp(T::parent(p));//expects TCO\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void balanceDown(Node* const p) {\n\t\t\tif(! p) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\taugment(p);\n\t\t\tconst int bf = slope(p);\n\t\t\tif(bf > 1) {\n\t\t\t\tif(slope(T::leftChild(p)) == -1) {\n\t\t\t\t\trotateLeft(T::leftChild(p));\n\t\t\t\t}\n\t\t\t\trotateRight(p);\n\t\t\t\tbalanceDown(p);//expects TCO\n\t\t\t} else if(bf < -1) {\n\t\t\t\tif(slope(T::rightChild(p)) == 1) {\n\t\t\t\t\trotateRight(T::rightChild(p));\n\t\t\t\t}\n\t\t\t\trotateLeft(p);\n\t\t\t\tbalanceDown(p);//expects TCO\n\t\t\t} else {\n\t\t\t\tbalanceDown(T::parent(p));//expects TCO\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatic void splitBefore(Node* const p) {\n\t\t\tmakeRoot(p);\n\t\t\tNode* const q = T::leftChild(p);\n\t\t\tif(q) {\n\t\t\t\tT::leftChild(p, nullptr);\n\t\t\t\tT::parent(q, nullptr);\n\t\t\t\tbalanceDown(findTail(q));\n\t\t\t}\n\t\t\tbalanceDown(p);\n\t\t}\n\t\t\n\t\tstatic void splitAfter(Node* const p) {\n\t\t\tmakeRoot(p);\n\t\t\tNode* const q = T::rightChild(p);\n\t\t\tif(q) {\n\t\t\t\tT::rightChild(p, nullptr);\n\t\t\t\tT::parent(q, nullptr);\n\t\t\t\tbalanceDown(findHead(q));\n\t\t\t}\n\t\t\tbalanceDown(p);\n\t\t}\n\t\t\n\t\tstatic Size size(const Node* const p) {\n\t\t\treturn p ? T::volume(p) : 0;\n\t\t}\n\t\t\n\t\ttemplate<class CNode>\n\t\tstatic Node* aboveRightTop(CNode* p) {\n\t\t\tif(! T::parent(p)) {\n\t\t\t\treturn nullptr;\n\t\t\t} else if(p == T::leftChild(T::parent(p))) {\n\t\t\t\treturn T::parent(p);\n\t\t\t} else {\n\t\t\t\treturn aboveRightTop(T::parent(p));//expects TCO\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class CNode>\n\t\tstatic optional<CNode> next(CNode* p) {\n\t\t\tif(T::rightChild(p)) {\n\t\t\t\tp = findHead(T::rightChild(p));\n\t\t\t} else {\n\t\t\t\tp = aboveRightTop(p);\n\t\t\t}\n\t\t\treturn p ? \n\t\t\t\toptional<CNode>(*p) : \n\t\t\t\toptional<CNode>();\n\t\t}\n\t\t\n\t\ttemplate<class CNode>\n\t\tstatic Node* aboveLeftTop(CNode* p) {\n\t\t\tif(! T::parent(p)) {\n\t\t\t\treturn nullptr;\n\t\t\t} else if(p == T::rightChild(T::parent(p))) {\n\t\t\t\treturn T::parent(p);\n\t\t\t} else {\n\t\t\t\treturn aboveLeftTop(T::parent(p));//expects TCO\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class CNode>\n\t\tstatic optional<CNode> previous(CNode* p) {\n\t\t\tif(T::leftChild(p)) {\n\t\t\t\tp = findTail(T::leftChild(p));\n\t\t\t} else {\n\t\t\t\tp = aboveLeftTop(p);\n\t\t\t}\n\t\t\treturn p ? \n\t\t\t\toptional<CNode>(*p) : \n\t\t\t\toptional<CNode>();\n\t\t}\n\t\t\n\t\n\t#ifdef CNRC_DEBUG_AVL_SEQUENCE // helpers for debugging\n\t\t\n\tpublic:\n\t\t\t\n\t\tstruct Debug {\n\t\t\t/**\n\t\t\t * Checks AVL invariants of the tree rooted at 'p'.\n\t\t\t * Compile with -DDEBUG_CNRC flag to use this.\n\t\t\t */\n\t\t\ttemplate<class ShowNode>\n\t\t\tstatic bool checkSanity(\n\t\t\t\t\tconst Node& p, \n\t\t\t\t\tShowNode showNode\n\t\t\t) {\n\t\t\t\treturn checkSanity(&p, T::parent(&p), showNode);\n\t\t\t}\n\t\t\t\n\t\t\ttemplate<class ShowNode>\n\t\t\tstatic bool checkSanity(\n\t\t\t\tconst Node* const p, \n\t\t\t\tconst Node* const parent, \n\t\t\t\tShowNode showNode\n\t\t\t) {\n\t\t\t\tif(! p) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif(T::parent(p) != parent) {\n\t\t\t\t\tstd::cerr << \n\t\t\t\t\t\t\"AVLSequence sanity check: \" << \n\t\t\t\t\t\t\"invalid parent pointer \" <<\n\t\t\t\t\t\t\"at node \" << showNode(*p) << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(T::height(p) != calcHeight(p)) {\n\t\t\t\t\tstd::cerr << \n\t\t\t\t\t\t\"AVLSequence sanity check: \" << \n\t\t\t\t\t\t\"invalid height value \" <<\n\t\t\t\t\t\t\"at node \" << showNode(*p) << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tconst int b = slope(p);\n\t\t\t\tif(b < -1 || b > 1) {\n\t\t\t\t\tstd::cerr << \n\t\t\t\t\t\t\"AVLSequence sanity check: \" << \n\t\t\t\t\t\t\"violation of the balance condition \" <<\n\t\t\t\t\t\t\"at node \" << showNode(*p) << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(T::volume(p) != calcVolume(p)) {\n\t\t\t\t\tstd::cerr << \n\t\t\t\t\t\t\"AVLSequence sanity check: \" << \n\t\t\t\t\t\t\"invalid branch size value \" <<\n\t\t\t\t\t\t\"at node: \" << showNode(*p) << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn \n\t\t\t\t\tcheckSanity(T::leftChild(p), p, showNode) && \n\t\t\t\t\tcheckSanity(T::rightChild(p), p, showNode);\n\t\t\t}\n\t\t\t\n\t\t\t/**\n\t\t\t * Prints the structure of the tree rootead at 'p'.\n\t\t\t * Compile with -DDEBUG_CNRC flag to use this.\n\t\t\t */\n\t\t\ttemplate<class ShowNode>\n\t\t\tstatic void printTree(\n\t\t\t\tconst Node& p, \n\t\t\t\tShowNode showNode\n\t\t\t) {\n\t\t\t\tprintTree(&p, \"[T]\", 0, showNode);\n\t\t\t}\n\t\t\t\n\t\t\ttemplate<class ShowNode>\n\t\t\tstatic void printTree(\n\t\t\t\tconst Node* const p, \n\t\t\t\tconst std::string head, \n\t\t\t\tconst unsigned int indent, \n\t\t\t\tShowNode showNode\n\t\t\t) {\n\t\t\t\tif(! p) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor(unsigned int i = 0; i < indent; ++i) {\n\t\t\t\t\tstd::cerr << \"\\t\";\n\t\t\t\t}\n\t\t\t\tstd::cerr << \n\t\t\t\t\thead << showNode(*p) << \", \" <<\n\t\t\t\t\t\"height: \" << T::height(p) << \", \" <<\n\t\t\t\t\t\"branch size: \" << T::volume(p) << \", \" <<\n\t\t\t\t\t\"addr: \" << p << \", \" << \n\t\t\t\t\t\"parent addr: \" << T::parent(p) << std::endl;\n\t\t\t\tprintTree(T::leftChild(p), \"[L]\", indent + 1, showNode);\n\t\t\t\tprintTree(T::rightChild(p), \"[R]\", indent + 1, showNode);\n\t\t\t}\n\t\t};\n\t\t\n\t#endif //end CNRC_DEBUG_AVL_SEQUENCE\n\t\t\n\t};\n};\n\t\n\n/**\n * Public interface exported from AVLSequenceModule.\n */\n \ntemplate<class NodeTrait> \nusing AVLSequenceAlgorithm = AVLSequenceModule::AVLSequenceAlgorithm<NodeTrait>;\n\ntemplate<class T>\nusing AVLSequenceNodeTrait = AVLSequenceModule::AVLSequenceNodeTrait<T>;\n\ntemplate<class T, class SizeType = unsigned int>\nusing AVLSequenceNodeMixin = AVLSequenceModule::AVLSequenceNodeMixin<T, SizeType>;\n\n} //end namespace AVLSequence\n} //end namespace Cnrc\n} //end namespace Snu\n", "meta": {"hexsha": "e809bb004f3d04bafbd3401b6037107f4ad4abde", "size": 22785, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Implementation/AVLSequence.hpp", "max_stars_repo_name": "ElsevierSoftwareX/SOFTX-D-17-00066", "max_stars_repo_head_hexsha": "e83ee8053ceb68a5f6e2fa7b4cc2f99eab1b8a8b", "max_stars_repo_licenses": ["MIT"], "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/AVLSequence.hpp", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-17-00066", "max_issues_repo_head_hexsha": "e83ee8053ceb68a5f6e2fa7b4cc2f99eab1b8a8b", "max_issues_repo_licenses": ["MIT"], "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/AVLSequence.hpp", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-17-00066", "max_forks_repo_head_hexsha": "e83ee8053ceb68a5f6e2fa7b4cc2f99eab1b8a8b", "max_forks_repo_licenses": ["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.0999030068, "max_line_length": 102, "alphanum_fraction": 0.5917489576, "num_tokens": 6836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766828768970435, "lm_q2_score": 0.04084571985051788, "lm_q1q2_score": 0.01338384708287256}}
{"text": "/*\n * SettingsManager.cpp\n *\n *  Created on: 22.08.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/utilities.h>\n\n#include <base/DiscretizedFunction.h>\n#include <base/Tuple.h>\n#include <forward/WaveEquationBase.h>\n#include <inversion/InversionProgress.h>\n#include <inversion/NonlinearLandweber.h>\n#include <inversion/REGINN.h>\n#include <measurements/ConvolutionMeasure.h>\n#include <measurements/CubeBoundaryDistribution.h>\n#include <measurements/GridDistribution.h>\n#include <measurements/SensorDistribution.h>\n\n#include <SettingsManager.h>\n\n#include <tgmath.h>\n#include <cstdio>\n#include <utility>\n\nnamespace wavepi {\nusing namespace dealii;\nusing namespace wavepi::forward;\nusing namespace wavepi::inversion;\nusing namespace wavepi::measurements;\n\nconst std::string SettingsManager::KEY_GENERAL            = \"general\";\nconst std::string SettingsManager::KEY_GENERAL_DIMENSION  = \"dimension\";\nconst std::string SettingsManager::KEY_GENERAL_FE_DEGREE  = \"finite element degree\";\nconst std::string SettingsManager::KEY_GENERAL_QUAD_ORDER = \"quadrature order\";\n\nconst std::string SettingsManager::KEY_LOG                = \"log\";\nconst std::string SettingsManager::KEY_LOG_FILE           = \"file\";\nconst std::string SettingsManager::KEY_LOG_FILE_DEPTH     = \"file depth\";\nconst std::string SettingsManager::KEY_LOG_FILE_DEPTH_MPI = \"file depth mpi\";\nconst std::string SettingsManager::KEY_LOG_CONSOLE_DEPTH  = \"console depth\";\n\nconst std::string SettingsManager::KEY_MESH                    = \"mesh\";\nconst std::string SettingsManager::KEY_MESH_END_TIME           = \"end time\";\nconst std::string SettingsManager::KEY_MESH_INITIAL_REFINES    = \"initial refines\";\nconst std::string SettingsManager::KEY_MESH_INITIAL_TIME_STEPS = \"initial time steps\";\nconst std::string SettingsManager::KEY_MESH_SHAPE              = \"shape\";\nconst std::string SettingsManager::KEY_MESH_SHAPE_GENERATOR    = \"generator name\";\nconst std::string SettingsManager::KEY_MESH_SHAPE_OPTIONS      = \"options\";\n\nconst std::string SettingsManager::KEY_PROBLEM                      = \"problem\";\nconst std::string SettingsManager::KEY_PROBLEM_TYPE                 = \"type\";\nconst std::string SettingsManager::KEY_PROBLEM_TRANSFORM            = \"transform\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_DOMAIN          = \"norm of domain\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_CODOMAIN        = \"norm of codomain\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_DOMAIN_P_ENABLE = \"domain lp wrapping\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_DOMAIN_P        = \"domain p\";\n\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H1L2ALPHA         = \"H1L2 alpha\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H2L2ALPHA         = \"H2L2 alpha\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H2L2BETA          = \"H2L2 beta\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H1H1ALPHA         = \"H1H1 alpha\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H1H1GAMMA         = \"H1H1 gamma\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H2L2PLUSL2H1ALPHA = \"H2L2+L2H1 alpha\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H2L2PLUSL2H1BETA  = \"H2L2+L2H1 beta\";\nconst std::string SettingsManager::KEY_PROBLEM_NORM_H2L2PLUSL2H1GAMMA = \"H2L2+L2H1 gamma\";\n\nconst std::string SettingsManager::KEY_PROBLEM_EPSILON           = \"epsilon\";\nconst std::string SettingsManager::KEY_PROBLEM_CONSTANTS         = \"constants\";\nconst std::string SettingsManager::KEY_PROBLEM_GUESS             = \"initial guess\";\nconst std::string SettingsManager::KEY_PROBLEM_PARAM_RHO         = \"parameter rho\";\nconst std::string SettingsManager::KEY_PROBLEM_PARAM_RHO_DYNAMIC = \"parameter rho dynamic\";\nconst std::string SettingsManager::KEY_PROBLEM_PARAM_Q           = \"parameter q\";\nconst std::string SettingsManager::KEY_PROBLEM_PARAM_C           = \"parameter c\";\nconst std::string SettingsManager::KEY_PROBLEM_PARAM_NU          = \"parameter nu\";\nconst std::string SettingsManager::KEY_PROBLEM_PARAM_BACKGROUND  = \"background parameter\";\nconst std::string SettingsManager::KEY_PROBLEM_SHAPE_SCALE       = \"shape scaling\";\n\nconst std::string SettingsManager::KEY_PROBLEM_DATA                       = \"data\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_ADDITIONAL_REFINES    = \"additional refines\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_ADDITIONAL_DEGREE     = \"additional fe degrees\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_COUNT                 = \"number of right hand sides\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_RHS                   = \"right hand sides\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_CONFIG                = \"configurations\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_I                     = \"config \";  // + number\nconst std::string SettingsManager::KEY_PROBLEM_DATA_I_MEASURE             = \"measure\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_I_MASK                = \"mask\";\nconst std::string SettingsManager::KEY_PROBLEM_DATA_I_SENSOR_DISTRIBUTION = \"sensor distribution\";\n\nconst std::string SettingsManager::KEY_INVERSION        = \"inversion\";\nconst std::string SettingsManager::KEY_INVERSION_TAU    = \"tau\";\nconst std::string SettingsManager::KEY_INVERSION_METHOD = \"method\";\n\nvoid SettingsManager::declare_parameters(std::shared_ptr<ParameterHandler> prm) {\n  OutputProgressListener<2, Tuple<DiscretizedFunction<2>>>::declare_parameters(*prm);\n  WatchdogProgressListener<Tuple<DiscretizedFunction<2>>, Tuple<DiscretizedFunction<2>>>::declare_parameters(*prm);\n  StatOutputProgressListener<Tuple<DiscretizedFunction<2>>, Tuple<DiscretizedFunction<2>>>::declare_parameters(*prm);\n  AbstractEquation<2>::declare_parameters(*prm);\n  BoundCheckProgressListener<2, Tuple<DiscretizedFunction<2>>, DiscretizedFunction<2>>::declare_parameters(*prm);\n  LogTransform<2>::declare_parameters(*prm);\n  ArtanhTransform<2>::declare_parameters(*prm);\n\n  prm->enter_subsection(KEY_GENERAL);\n  {\n    prm->declare_entry(KEY_GENERAL_DIMENSION, \"2\", Patterns::Integer(1, 3), \"problem dimension\");\n    prm->declare_entry(KEY_GENERAL_FE_DEGREE, \"1\", Patterns::Integer(1, 4),\n                       \"polynomial degree of finite elements. Note that bound \"\n                       \"checking is currently only implemented for linear \"\n                       \"elements.\");\n    prm->declare_entry(KEY_GENERAL_QUAD_ORDER, \"3\", Patterns::Integer(1, 20),\n                       \"order of quadrature (QGauss, exact in polynomials of \"\n                       \"degree ≤ 2n-1, use at least finite element degree + \"\n                       \"1) \");\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_LOG);\n  {\n    prm->declare_entry(KEY_LOG_FILE, \"wavepi.log\", Patterns::FileName(Patterns::FileName::output), \"external log file\");\n    prm->declare_entry(KEY_LOG_FILE_DEPTH, \"3\", Patterns::Integer(0), \"depth for the log file (root process)\");\n    prm->declare_entry(KEY_LOG_FILE_DEPTH_MPI, \"3\", Patterns::Integer(0), \"depth for the log file (other processes)\");\n    prm->declare_entry(KEY_LOG_CONSOLE_DEPTH, \"2\", Patterns::Integer(0), \"depth for stdout (root process)\");\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_MESH);\n  {\n    prm->declare_entry(KEY_MESH_END_TIME, \"6.28318530718\", Patterns::Double(0), \"time horizon T\");\n    prm->declare_entry(KEY_MESH_INITIAL_REFINES, \"6\", Patterns::Integer(0), \"refines of the (initial) spatial grid\");\n    prm->declare_entry(KEY_MESH_INITIAL_TIME_STEPS, \"256\", Patterns::Integer(2), \"(initial) number of time steps\");\n\n    prm->enter_subsection(KEY_MESH_SHAPE);\n    {\n      prm->declare_entry(KEY_MESH_SHAPE_GENERATOR, \"hyper_cube\",\n                         Patterns::Selection(\"hyper_cube|hyper_L|hyper_ball|cheese\"),\n                         \"generator for the triangulation\");\n      prm->declare_entry(KEY_MESH_SHAPE_OPTIONS, \"left=-1.0, right=1.0\", Patterns::Anything(),\n                         \"options for the generator, in the form `var1=value1, var2=value2, \"\n                         \"...`.\\n Available options: left, right for hyper_cube and hyper_L, \"\n                         \"center_{x,y,z} and radius for hyper_cube, scale for cheese.\");\n    }\n    prm->leave_subsection();\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_PROBLEM);\n  {\n    prm->declare_entry(KEY_PROBLEM_TYPE, \"rho\", Patterns::Selection(\"c|c_constant|nu|rho|rho_constant|q\"),\n                       \"parameter that is reconstructed\");\n\n    prm->declare_entry(KEY_PROBLEM_TRANSFORM, \"Identity\", Patterns::Selection(\"Identity|Log|Artanh\"),\n                       \"transformation to apply to the parameter (e.g. to get rid of constraints)\");\n\n    prm->declare_entry(KEY_PROBLEM_NORM_DOMAIN, \"L2L2\",\n                       Patterns::Selection(\"L2L2|H1L2|H2L2|H1H1|H2L2PlusL2H1|Coefficients\"),\n                       \"norm to use for parameters (incl. the reconstruction)\");\n    prm->declare_entry(KEY_PROBLEM_NORM_CODOMAIN, \"L2L2\",\n                       Patterns::Selection(\"L2L2|H1L2|H2L2|H1H1|H2L2PlusL2H1|Coefficients\"),\n                       \"Set the norm to use for fields. Be aware that this has \"\n                       \"to match the norm that the measurements expect its \"\n                       \"inputs to have.\");\n\n    prm->declare_entry(KEY_PROBLEM_NORM_DOMAIN_P, \"2.0\", Patterns::Double(1),\n                       \"index p for the l^p-norm. See also \" + KEY_PROBLEM_NORM_DOMAIN_P_ENABLE + \".\");\n    prm->declare_entry(KEY_PROBLEM_NORM_DOMAIN_P_ENABLE, \"false\", Patterns::Bool(),\n                       \"Wrap the norm of the parameter space inside a l^p-norm\");\n\n    prm->declare_entry(KEY_PROBLEM_NORM_H1L2ALPHA, \"0.5\", Patterns::Double(0),\n                       \"Factor α in front of derivative term of H¹([0,T], L²(Ω)) dot product\");\n\n    prm->declare_entry(KEY_PROBLEM_NORM_H2L2ALPHA, \"0.5\", Patterns::Double(0),\n                       \"Factor α in front of first derivative term of \"\n                       \"H²([0,T], L²(Ω)) dot product\");\n    prm->declare_entry(KEY_PROBLEM_NORM_H2L2BETA, \"0.25\", Patterns::Double(0),\n                       \"Factor β in front of second derivative term of \"\n                       \"H²([0,T], L²(Ω)) dot product\");\n\n    prm->declare_entry(KEY_PROBLEM_NORM_H1H1ALPHA, \"0.5\", Patterns::Double(0),\n                       \"Factor α in front of time derivative term of H¹([0,T], H¹(Ω)) dot product\");\n    prm->declare_entry(KEY_PROBLEM_NORM_H1H1GAMMA, \"0.5\", Patterns::Double(0),\n                       \"Factor ɣ in front of gradient term of H¹([0,T], H¹(Ω)) dot product\");\n\n    prm->declare_entry(KEY_PROBLEM_NORM_H2L2PLUSL2H1ALPHA, \"0.5\", Patterns::Double(0),\n                       \"Factor α in front of time derivative term of H²([0,T], L²(Ω)) ∩ L²([0,T], H¹(Ω)) dot product\");\n    prm->declare_entry(KEY_PROBLEM_NORM_H2L2PLUSL2H1BETA, \"0.25\", Patterns::Double(0),\n                       \"Factor β in front of second time derivative term of \"\n                       \"H²([0,T], L²(Ω)) ∩ L²([0,T], H¹(Ω)) dot product\");\n    prm->declare_entry(KEY_PROBLEM_NORM_H2L2PLUSL2H1GAMMA, \"0.5\", Patterns::Double(0),\n                       \"Factor ɣ in front of gradient term of H²([0,T], L²(Ω)) ∩ L²([0,T], H¹(Ω)) dot product\");\n\n    prm->declare_entry(KEY_PROBLEM_EPSILON, \"1e-2\", Patterns::Double(0, 1), \"relative noise level ε\");\n\n    prm->declare_entry(KEY_PROBLEM_CONSTANTS, \"\", Patterns::Anything(),\n                       \"constants for the function declarations,\\nin the form \"\n                       \"`var1=value1, var2=value2, ...`.\");\n\n    prm->declare_entry(KEY_PROBLEM_GUESS, \"0.0\", Patterns::Anything(), \"initial guess\");\n\n    prm->declare_entry(KEY_PROBLEM_PARAM_RHO, \"1.0\", Patterns::Anything(), \"parameter ρ\");\n    prm->declare_entry(KEY_PROBLEM_PARAM_RHO_DYNAMIC, \"true\", Patterns::Bool(),\n                       \"parameter ρ time-dependent? (performance)\");\n    prm->declare_entry(KEY_PROBLEM_PARAM_Q, \"0.0\", Patterns::Anything(), \"parameter q\");\n    prm->declare_entry(KEY_PROBLEM_PARAM_C, \"2.0\", Patterns::Anything(), \"parameter c\");\n    prm->declare_entry(KEY_PROBLEM_PARAM_NU, \"0.0\", Patterns::Anything(), \"parameter ν\");\n    prm->declare_entry(KEY_PROBLEM_PARAM_BACKGROUND, \"0.0\", Patterns::Anything(),\n                       \"background parameter (added to all arguments of the forward operator, including exact data)\");\n    prm->declare_entry(KEY_PROBLEM_SHAPE_SCALE, \"1.0\", Patterns::Double(0),\n                       \"scaling parameter applied to all shapes that are used\");\n\n    prm->enter_subsection(KEY_PROBLEM_DATA);\n    {\n      prm->declare_entry(\n          KEY_PROBLEM_DATA_ADDITIONAL_REFINES, \"0\", Patterns::Integer(0),\n          \"Additional global refines to perform in space and time for data synthesis (to avoid inverse crime)\");\n      prm->declare_entry(KEY_PROBLEM_DATA_ADDITIONAL_DEGREE, \"0\", Patterns::Integer(0),\n                         \"Additional finite element degrees to use for data synthesis (to avoid inverse crime)\");\n\n      prm->declare_entry(KEY_PROBLEM_DATA_COUNT, \"1\", Patterns::Integer(1), \"Number of right hand sides\");\n\n      prm->declare_entry(KEY_PROBLEM_DATA_CONFIG, \"0\", Patterns::Anything(),\n                         \"configuration to use for which right hand side, \"\n                         \"separated by semicolons\");\n      prm->declare_entry(KEY_PROBLEM_DATA_RHS, \"if(t<3.14, if(norm{x|y|z} < 0.1, sin(2*t), 0.0), 0.0)\",\n                         Patterns::Anything(), \"right hand sides, separated by semicolons\");\n\n      for (size_t i = 0; i < num_configurations; i++) {\n        prm->enter_subsection(KEY_PROBLEM_DATA_I + Utilities::int_to_string(i, 1));\n\n        ConvolutionMeasure<2>::declare_parameters(*prm);\n        GridDistribution<2>::declare_parameters(*prm);\n        CubeBoundaryDistribution<2>::declare_parameters(*prm);\n\n        prm->declare_entry(KEY_PROBLEM_DATA_I_MEASURE, \"Field\",\n                           Patterns::Selection(\"Field|MaskedField|Convolution|Delta\"), \"type of measurements\");\n\n        prm->declare_entry(KEY_PROBLEM_DATA_I_SENSOR_DISTRIBUTION, \"Grid\", Patterns::Selection(\"Grid|CubeBoundary\"),\n                           \"in case of simulated sensors, their location on the mesh\");\n\n        prm->declare_entry(KEY_PROBLEM_DATA_I_MASK, \"1\", Patterns::Anything(),\n                           \"in case of MaskedField, the mask function\");\n\n        prm->leave_subsection();\n      }\n    }\n    prm->leave_subsection();\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_INVERSION);\n  {\n    prm->declare_entry(KEY_INVERSION_METHOD, \"REGINN\", Patterns::Selection(\"REGINN|NonlinearLandweber\"),\n                       \"solver for the inverse problem\");\n    prm->declare_entry(KEY_INVERSION_TAU, \"2\", Patterns::Double(0), \"parameter τ for discrepancy principle\");\n\n    REGINN<DiscretizedFunction<2>, DiscretizedFunction<2>, Function<2>>::declare_parameters(*prm);\n    NonlinearLandweber<DiscretizedFunction<2>, DiscretizedFunction<2>, Function<2>>::declare_parameters(*prm);\n  }\n  prm->leave_subsection();\n}\n\nvoid SettingsManager::get_parameters(std::shared_ptr<ParameterHandler> prm) {\n  this->prm = prm;\n  AssertThrow(prm, ExcInternalError());\n\n  prm->enter_subsection(KEY_LOG);\n  {\n    log_file           = prm->get(KEY_LOG_FILE);\n    log_file_depth     = prm->get_integer(KEY_LOG_FILE_DEPTH);\n    log_file_depth_mpi = prm->get_integer(KEY_LOG_FILE_DEPTH_MPI);\n    log_console_depth  = prm->get_integer(KEY_LOG_CONSOLE_DEPTH);\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_GENERAL);\n  {\n    fe_degree  = prm->get_integer(KEY_GENERAL_FE_DEGREE);\n    quad_order = prm->get_integer(KEY_GENERAL_QUAD_ORDER);\n    dimension  = prm->get_integer(KEY_GENERAL_DIMENSION);\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_MESH);\n  {\n    end_time           = prm->get_double(KEY_MESH_END_TIME);\n    initial_refines    = prm->get_integer(KEY_MESH_INITIAL_REFINES);\n    initial_time_steps = prm->get_integer(KEY_MESH_INITIAL_TIME_STEPS);\n\n    dt = end_time / (initial_time_steps - 1);\n    times.clear();\n    times.resize(initial_time_steps);\n\n    for (size_t i = 0; i < initial_time_steps; i++)\n      times[i] = i * dt;\n\n    prm->enter_subsection(KEY_MESH_SHAPE);\n    {\n      std::string generator = prm->get(KEY_MESH_SHAPE_GENERATOR);\n\n      std::string options_list                = prm->get(KEY_MESH_SHAPE_OPTIONS);\n      std::vector<std::string> options_listed = Utilities::split_string_list(options_list, ',');\n\n      shape_options.clear();\n\n      for (size_t i = 0; i < options_listed.size(); ++i) {\n        std::vector<std::string> this_c = Utilities::split_string_list(options_listed[i], '=');\n        AssertThrow(this_c.size() == 2, ExcMessage(\"Could not parse generator options\"));\n        double tmp;\n        AssertThrow(std::sscanf(this_c[1].c_str(), \"%lf\", &tmp), ExcMessage(\"Could not parse generator options\"));\n        shape_options[this_c[0]] = tmp;\n      }\n\n      if (generator == \"hyper_cube\") {\n        if (!shape_options.count(\"left\")) shape_options.emplace(\"left\", -5.0);\n        if (!shape_options.count(\"right\")) shape_options.emplace(\"right\", 5.0);\n\n        shape = MeshShape::hyper_cube;\n      } else if (generator == \"hyper_L\") {\n        if (!shape_options.count(\"left\")) shape_options.emplace(\"left\", -5.0);\n        if (!shape_options.count(\"right\")) shape_options.emplace(\"right\", 5.0);\n\n        shape = MeshShape::hyper_l;\n      } else if (generator == \"hyper_ball\") {\n        if (!shape_options.count(\"center_x\")) shape_options.emplace(\"center_x\", 0.0);\n        if (!shape_options.count(\"center_y\")) shape_options.emplace(\"center_y\", 0.0);\n        if (!shape_options.count(\"center_z\")) shape_options.emplace(\"center_z\", 0.0);\n        if (!shape_options.count(\"radius\")) shape_options.emplace(\"radius\", 1.0);\n\n        shape = MeshShape::hyper_ball;\n      } else if (generator == \"cheese\") {\n        if (!shape_options.count(\"scale\")) shape_options.emplace(\"scale\", 1.0);\n\n        AssertThrow(dimension > 1, ExcMessage(\"cheese only makes sense for dim > 1.\"));\n        shape = MeshShape::cheese;\n      } else {\n        AssertThrow(false, ExcMessage(\"Unknown mesh generator:\" + generator));\n      }\n    }\n    prm->leave_subsection();\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_PROBLEM);\n  {\n    epsilon = prm->get_double(KEY_PROBLEM_EPSILON);\n\n    std::string norm_domain_s = prm->get(KEY_PROBLEM_NORM_DOMAIN);\n\n    if (norm_domain_s == \"L2L2\")\n      norm_domain = NormType::l2l2;\n    else if (norm_domain_s == \"H1L2\")\n      norm_domain = NormType::h1l2;\n    else if (norm_domain_s == \"H2L2\")\n      norm_domain = NormType::h2l2;\n    else if (norm_domain_s == \"H1H1\")\n      norm_domain = NormType::h1h1;\n    else if (norm_domain_s == \"H2L2PlusL2H1\")\n      norm_domain = NormType::h2l2plusl2h1;\n    else if (norm_domain_s == \"Coefficients\")\n      norm_domain = NormType::vector;\n    else\n      AssertThrow(false, ExcMessage(\"Cannot parse norm of domain\"));\n\n    std::string norm_codomain_s = prm->get(KEY_PROBLEM_NORM_CODOMAIN);\n\n    if (norm_codomain_s == \"L2L2\")\n      norm_codomain = NormType::l2l2;\n    else if (norm_codomain_s == \"H1L2\")\n      norm_codomain = NormType::h1l2;\n    else if (norm_codomain_s == \"H2L2\")\n      norm_codomain = NormType::h2l2;\n    else if (norm_codomain_s == \"H1H1\")\n      norm_codomain = NormType::h1h1;\n    else if (norm_codomain_s == \"H2L2PlusL2H1\")\n      norm_codomain = NormType::h2l2plusl2h1;\n    else if (norm_codomain_s == \"Coefficients\")\n      norm_codomain = NormType::vector;\n    else\n      AssertThrow(false, ExcMessage(\"Cannot parse norm of codomain\"));\n\n    norm_domain_enable_wrapping = prm->get_bool(KEY_PROBLEM_NORM_DOMAIN_P_ENABLE);\n    norm_domain_p               = prm->get_double(KEY_PROBLEM_NORM_DOMAIN_P);\n\n    norm_h1l2_alpha = prm->get_double(KEY_PROBLEM_NORM_H1L2ALPHA);\n\n    norm_h2l2_alpha = prm->get_double(KEY_PROBLEM_NORM_H2L2ALPHA);\n    norm_h2l2_beta  = prm->get_double(KEY_PROBLEM_NORM_H2L2BETA);\n\n    norm_h1h1_alpha = prm->get_double(KEY_PROBLEM_NORM_H1H1ALPHA);\n    norm_h1h1_gamma = prm->get_double(KEY_PROBLEM_NORM_H1H1GAMMA);\n\n    norm_h2l2plusl2h1_alpha = prm->get_double(KEY_PROBLEM_NORM_H2L2PLUSL2H1ALPHA);\n    norm_h2l2plusl2h1_beta  = prm->get_double(KEY_PROBLEM_NORM_H2L2PLUSL2H1BETA);\n    norm_h2l2plusl2h1_gamma = prm->get_double(KEY_PROBLEM_NORM_H2L2PLUSL2H1GAMMA);\n\n    std::string transform_s = prm->get(KEY_PROBLEM_TRANSFORM);\n\n    if (transform_s == \"Identity\")\n      transform = TransformType::identity;\n    else if (transform_s == \"Log\")\n      transform = TransformType::log;\n    else if (transform_s == \"Artanh\")\n      transform = TransformType::artanh;\n    else\n      AssertThrow(false, ExcMessage(\"Cannot parse transform type\"));\n\n    std::string problem = prm->get(KEY_PROBLEM_TYPE);\n\n    if (problem == \"rho\")\n      problem_type = ProblemType::rho;\n    else if (problem == \"q\")\n      problem_type = ProblemType::q;\n    else if (problem == \"nu\")\n      problem_type = ProblemType::nu;\n    else if (problem == \"c\")\n      problem_type = ProblemType::c;\n    else if (problem == \"rho_constant\")\n      problem_type = ProblemType::rho_constant;\n    else if (problem == \"c_constant\")\n      problem_type = ProblemType::c_constant;\n    else\n      AssertThrow(false, ExcMessage(\"unknown problem type\"));\n\n    std::string constants_list            = prm->get(KEY_PROBLEM_CONSTANTS);\n    std::vector<std::string> const_listed = Utilities::split_string_list(constants_list, ',');\n\n    constants_for_exprs.clear();\n\n    for (size_t i = 0; i < const_listed.size(); ++i) {\n      std::vector<std::string> this_c = Utilities::split_string_list(const_listed[i], '=');\n      AssertThrow(this_c.size() == 2, ExcMessage(\"Invalid format\"));\n      double tmp;\n      AssertThrow(std::sscanf(this_c[1].c_str(), \"%lf\", &tmp), ExcMessage(\"Double number?\"));\n      constants_for_exprs[this_c[0]] = tmp;\n    }\n\n    expr_initial_guess    = prm->get(KEY_PROBLEM_GUESS);\n    expr_param_rho        = prm->get(KEY_PROBLEM_PARAM_RHO);\n    expr_param_nu         = prm->get(KEY_PROBLEM_PARAM_NU);\n    expr_param_c          = prm->get(KEY_PROBLEM_PARAM_C);\n    expr_param_q          = prm->get(KEY_PROBLEM_PARAM_Q);\n    expr_param_background = prm->get(KEY_PROBLEM_PARAM_BACKGROUND);\n\n    shape_scale = prm->get_double(KEY_PROBLEM_SHAPE_SCALE);\n    rho_dynamic = prm->get_bool(KEY_PROBLEM_PARAM_RHO_DYNAMIC);\n\n    prm->enter_subsection(KEY_PROBLEM_DATA);\n    {\n      num_rhs   = prm->get_integer(KEY_PROBLEM_DATA_COUNT);\n      exprs_rhs = Utilities::split_string_list(prm->get(KEY_PROBLEM_DATA_RHS), ';');\n\n      synthesis_additional_refines    = prm->get_integer(KEY_PROBLEM_DATA_ADDITIONAL_REFINES);\n      synthesis_additional_fe_degrees = prm->get_integer(KEY_PROBLEM_DATA_ADDITIONAL_DEGREE);\n\n      configs.clear();\n      measures.clear();\n      sensor_distributions.clear();\n      expr_masks.clear();\n\n      try {\n        for (auto is : Utilities::split_string_list(prm->get(KEY_PROBLEM_DATA_CONFIG), ';')) {\n          size_t ci = std::stoi(is);\n          AssertThrow(ci < num_configurations, ExcIndexRange(ci, 0, num_configurations));\n          configs.push_back(ci);\n        }\n      } catch (std::invalid_argument &e) {\n        AssertThrow(false, ExcMessage(\"could not parse configurations: \" + std::string(e.what())));\n      }\n\n      AssertThrow(num_rhs == exprs_rhs.size(), ExcMessage(\"number of right hand sides != number of expressions given\"));\n      AssertThrow(num_rhs == configs.size(),\n                  ExcMessage(\"number of right hand sides != number of configurations given\"));\n\n      std::vector<MeasureType> measure_types;\n\n      for (size_t i = 0; i < num_configurations; i++) {\n        prm->enter_subsection(KEY_PROBLEM_DATA_I + Utilities::int_to_string(i, 1));\n\n        auto measure_desc = prm->get(KEY_PROBLEM_DATA_I_MEASURE);\n        MeasureType my_measure_type;\n\n        if (measure_desc == \"Field\") {\n          measures.push_back(Measure::field);\n          my_measure_type = MeasureType::discretized_function;\n        } else if (measure_desc == \"MaskedField\") {\n          measures.push_back(Measure::masked_field);\n          my_measure_type = MeasureType::discretized_function;\n        } else if (measure_desc == \"Convolution\") {\n          measures.push_back(Measure::convolution);\n          my_measure_type = MeasureType::vector;\n        } else if (measure_desc == \"Delta\") {\n          measures.push_back(Measure::delta);\n          my_measure_type = MeasureType::vector;\n        } else {\n          AssertThrow(false, ExcMessage(\"Unknown Measure: \" + measure_desc));\n        }\n\n        measure_types.push_back(my_measure_type);\n\n        auto distrib_desc = prm->get(KEY_PROBLEM_DATA_I_SENSOR_DISTRIBUTION);\n\n        if (distrib_desc == \"Grid\") {\n          sensor_distributions.push_back(SettingsManager::SensorDistribution::grid);\n        } else if (distrib_desc == \"CubeBoundary\") {\n          sensor_distributions.push_back(SettingsManager::SensorDistribution::cube_boundary);\n        } else {\n          AssertThrow(false, ExcMessage(\"Unknown sensor distribution: \" + distrib_desc));\n        }\n\n        expr_masks.push_back(prm->get(KEY_PROBLEM_DATA_I_MASK));\n        prm->leave_subsection();\n      }\n\n      for (size_t i = 0; i < num_rhs; i++) {\n        auto my_measure_type = measure_types[configs[i]];\n\n        if (!i) measure_type = my_measure_type;\n\n        AssertThrow(measure_type == my_measure_type, ExcMessage(\"the resulting data types must be the same for \"\n                                                                \"all used measurement configurations!\"))\n      }\n    }\n    prm->leave_subsection();\n  }\n  prm->leave_subsection();\n\n  prm->enter_subsection(KEY_INVERSION);\n  {\n    tau = prm->get_double(KEY_INVERSION_TAU);\n\n    std::string smethod = prm->get(KEY_INVERSION_METHOD);\n\n    if (smethod == \"REGINN\")\n      method = NonlinearMethod::reginn;\n    else if (smethod == \"NonlinearLandweber\")\n      method = NonlinearMethod::nonlinear_landweber;\n    else\n      AssertThrow(false, ExcMessage(\"Unknown Method: \" + smethod));\n  }\n\n  prm->leave_subsection();\n}\n\nvoid SettingsManager::log_parameters() {\n#ifdef WAVEPI_MPI\n  size_t mpi_rank = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n#else\n  size_t mpi_rank = 0;\n#endif\n\n  unsigned int prev_console = mpi_rank > 0 ? 0 : deallog.depth_console(100);\n  unsigned int prev_file    = deallog.depth_file(100);\n\n  prm->log_parameters(deallog);\n\n  deallog.depth_console(prev_console);\n  deallog.depth_file(prev_file);\n}\n\n}  // namespace wavepi\n", "meta": {"hexsha": "2001fb8e545f1bab6fbf9baf14caa40b762bb2c4", "size": 26473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SettingsManager.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/SettingsManager.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/SettingsManager.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": 47.0213143872, "max_line_length": 120, "alphanum_fraction": 0.6755940014, "num_tokens": 6659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.02758528382564496, "lm_q1q2_score": 0.01336176210427044}}
{"text": "// SPDX-License-Identifier: NASA-1.3\n/*******************************************************************************\n *\n * Implementation of Patricia trees based on the algorithms described in\n * C. Okasaki and A. Gill's paper: \"Fast Mergeable Integer Maps\",\n * Workshop on ML, September 1998, pages 77-86.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n *\n * Notices:\n *\n * Copyright (c) 2011 United States Government as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All Rights Reserved.\n *\n * Disclaimers:\n *\n * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED \"AS IS\" WITHOUT ANY WARRANTY OF\n * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED\n * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,\n * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,\n * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE\n * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO\n * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN\n * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,\n * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS\n * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY\n * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,\n * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT \"AS IS.\"\n *\n * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST\n * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL\n * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS\n * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH\n * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,\n * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD\n * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,\n * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.\n * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,\n * UNILATERAL TERMINATION OF THIS AGREEMENT.\n *\n ******************************************************************************/\n\n#pragma once\n\n#include <algorithm>\n#include <memory>\n#include <optional>\n#include <vector>\n\n#include <boost/iterator/iterator_facade.hpp>\n\nnamespace crab {\n\n// Numerical type for indexed objects\nusing index_t = uint64_t;\n\ninline index_t index(index_t i) { return i; }\n\ntemplate <typename T>\ninline index_t index(const T& x) { return x.index(); }\n\nnamespace patricia_trees_impl {\n\ninline index_t highest_bit(index_t x, index_t m) {\n    index_t x_ = x & ~(m - 1);\n    index_t m_ = m;\n\n    while (x_ != m_) {\n        x_ = x_ & ~m_;\n        m_ = 2 * m_;\n    }\n    return m_;\n}\n\ninline index_t compute_branching_bit(index_t p0, index_t m0, index_t p1, index_t m1) {\n    return highest_bit(p0 ^ p1, std::max((index_t)1, 2 * std::max(m0, m1)));\n}\n\ninline index_t mask(index_t k, index_t m) { return (k | (m - 1)) & ~m; }\n\ninline bool zero_bit(index_t k, index_t m) { return (k & m) == 0; }\n\ninline bool match_prefix(index_t k, index_t p, index_t m) { return mask(k, m) == p; }\n\ntemplate <typename Key, typename Value>\nclass tree {\n  public:\n    using tree_t = tree<Key, Value>;\n    using tree_ptr = std::shared_ptr<tree_t>;\n\n    class partial_order_t {\n      public:\n        virtual bool leq(Value, Value) = 0;\n        // True if the default value is the top element for the partial order (false if it is bottom)\n        virtual bool default_is_top() = 0;\n\n        virtual ~partial_order_t() = default;\n\n    }; // class partial_order\n\n    class binary_action_t {\n      public:\n        // if first element of the pair is true then bottom and ignore second element\n        // else if second element of the pair is empty then top\n        // else the value stored in the second element of the pair.\n        // The operation is idempotent: apply(x, x) = x\n        virtual std::pair<bool, std::optional<Value>> apply(const Value&, const Value&) = 0;\n\n        // True if the default value is absorbing (false if it is neutral)\n        virtual bool default_is_absorbing() = 0;\n\n        virtual ~binary_action_t() = default;\n\n    }; // class binary_action\n\n    using binding_t = std::pair<const Key&, const Value&>;\n\n  public:\n    static tree_ptr make_node(index_t, index_t, tree_ptr, tree_ptr);\n    static tree_ptr make_leaf(const Key&, const Value&);\n    static std::pair<bool, tree_ptr> merge(tree_ptr, tree_ptr, binary_action_t&, bool);\n    static tree_ptr join(tree_ptr t0, tree_ptr t1);\n    static std::pair<bool, tree_ptr> insert(tree_ptr, const Key&, const Value&, binary_action_t&, bool);\n    static tree_ptr remove(tree_ptr, const Key&);\n    static bool compare(tree_ptr, tree_ptr, partial_order_t&, bool);\n\n  public:\n    [[nodiscard]] virtual std::size_t size() const = 0;\n    [[nodiscard]] virtual bool is_leaf() const = 0;\n    virtual binding_t binding() const = 0;\n    virtual tree_ptr left_branch() const = 0;\n    virtual tree_ptr right_branch() const = 0;\n    [[nodiscard]] virtual index_t prefix() const = 0;\n    [[nodiscard]] virtual index_t branching_bit() const = 0;\n    virtual std::optional<Value> lookup(const Key&) const = 0;\n\n  public:\n    [[nodiscard]] bool is_node() const { return !is_leaf(); }\n\n    virtual ~tree() = default;\n\n  public:\n    class iterator : public boost::iterator_facade<iterator, binding_t, boost::forward_traversal_tag, binding_t> {\n        friend class boost::iterator_core_access;\n\n      private:\n        using branching_t = std::pair<tree_ptr, int>;\n        using branching_stack_t = std::vector<branching_t>;\n\n      private:\n        tree_ptr _current;\n        branching_stack_t _stack;\n\n      public:\n        iterator() = default;\n\n        explicit iterator(tree_ptr t) { this->look_for_next_leaf(t); }\n\n      private:\n        void look_for_next_leaf(tree_ptr t) {\n            if (t) {\n                if (t->is_leaf()) {\n                    this->_current = t;\n                } else {\n                    branching_t b(t, 0);\n                    this->_stack.push_back(b);\n                    this->look_for_next_leaf(t->left_branch());\n                }\n            } else {\n                if (!this->_stack.empty()) {\n                    branching_t up;\n                    do {\n                        up = this->_stack.back();\n                        this->_stack.pop_back();\n                    } while (!this->_stack.empty() && up.second == 1);\n                    if (!(this->_stack.empty() && up.second == 1)) {\n                        branching_t b(up.first, 1);\n                        this->_stack.push_back(b);\n                        this->look_for_next_leaf(up.first->right_branch());\n                    }\n                }\n            }\n        }\n\n        void increment() {\n            if (this->_current) {\n                this->_current.reset();\n                if (!this->_stack.empty()) {\n                    branching_t up;\n                    do {\n                        up = this->_stack.back();\n                        this->_stack.pop_back();\n                    } while (!this->_stack.empty() && up.second == 1);\n                    if (!(this->_stack.empty() && up.second == 1)) {\n                        this->look_for_next_leaf(up.first->right_branch());\n                    }\n                }\n            } else {\n                CRAB_ERROR(\"Patricia tree: trying to increment an empty iterator\");\n            }\n        }\n\n        bool equal(const iterator& it) const {\n            if (this->_current != it._current) {\n                return false;\n            }\n            if (this->_stack.size() != it._stack.size()) {\n                return false;\n            }\n            typename branching_stack_t::const_iterator s_it1, s_it2;\n            s_it1 = this->_stack.begin();\n            s_it2 = it._stack.begin();\n            while (s_it1 != this->_stack.end()) {\n                if (*s_it1 != *s_it2) {\n                    return false;\n                }\n                ++s_it1;\n                ++s_it2;\n            }\n            return true;\n        }\n\n        binding_t dereference() const {\n            if (this->_current) {\n                return this->_current->binding();\n            } else {\n                CRAB_ERROR(\"Patricia tree: trying to dereference an empty iterator\");\n            }\n        }\n\n    }; // class iterator\n\n}; // class tree\n\ntemplate <typename Key, typename Value>\nclass node final : public tree<Key, Value> {\n  private:\n    using tree_ptr = typename tree<Key, Value>::tree_ptr;\n    using binding_t = typename tree<Key, Value>::binding_t;\n    using node_t = node<Key, Value>;\n\n  private:\n    std::size_t _size;\n    index_t _prefix;\n    index_t _branching_bit;\n    tree_ptr _left_branch;\n    tree_ptr _right_branch;\n\n  public:\n    node() = delete;\n    node(const node_t&) = delete;\n    node_t& operator=(const node_t&) = delete;\n\n  public:\n    node(index_t prefix_, index_t branching_bit_, tree_ptr left_branch_, tree_ptr right_branch_)\n        : _size(0), _prefix(prefix_), _branching_bit(branching_bit_), _left_branch(left_branch_),\n          _right_branch(right_branch_) {\n        if (left_branch_) {\n            this->_size += left_branch_->size();\n        }\n        if (right_branch_) {\n            this->_size += right_branch_->size();\n        }\n    }\n\n    [[nodiscard]] std::size_t size() const { return this->_size; }\n\n    [[nodiscard]] index_t prefix() const { return this->_prefix; }\n\n    [[nodiscard]] index_t branching_bit() const { return this->_branching_bit; }\n\n    [[nodiscard]] bool is_leaf() const { return false; }\n\n    binding_t binding() const { CRAB_ERROR(\"Patricia tree: trying to call binding() on a node\"); }\n\n    tree_ptr left_branch() const { return this->_left_branch; }\n\n    tree_ptr right_branch() const { return this->_right_branch; }\n\n    std::optional<Value> lookup(const Key& key) const {\n        if (index(key) <= this->_prefix) {\n            if (this->_left_branch) {\n                return this->_left_branch->lookup(key);\n            } else {\n                return std::optional<Value>();\n            }\n        } else {\n            if (this->_right_branch) {\n                return this->_right_branch->lookup(key);\n            } else {\n                return std::optional<Value>();\n            }\n        }\n    }\n\n}; // class node\n\ntemplate <typename Key, typename Value>\nclass leaf final : public tree<Key, Value> {\n  private:\n    using tree_ptr = typename tree<Key, Value>::tree_ptr;\n    using binding_t = typename tree<Key, Value>::binding_t;\n    using leaf_t = leaf<Key, Value>;\n\n  private:\n    Key _key;\n    Value _value;\n\n  public:\n    leaf() = delete;\n    leaf(const leaf_t&) = delete;\n    leaf_t& operator=(const leaf_t&) = delete;\n\n  public:\n    leaf(const Key& key_, const Value& value_) : _key(key_), _value(value_) {}\n\n    [[nodiscard]] std::size_t size() const { return 1; }\n\n    [[nodiscard]] index_t prefix() const { return index(this->_key); }\n\n    [[nodiscard]] index_t branching_bit() const { return 0; }\n\n    [[nodiscard]] bool is_leaf() const { return true; }\n\n    binding_t binding() const { return binding_t(this->_key, this->_value); }\n\n    tree_ptr left_branch() const { CRAB_ERROR(\"Patricia tree: trying to call left_branch() on a leaf\"); }\n\n    tree_ptr right_branch() const { CRAB_ERROR(\"Patricia tree: trying to call right_branch() on a leaf\"); }\n\n    std::optional<Value> lookup(const Key& key_) const {\n        if (index(this->_key) == index(key_)) {\n            return std::optional<Value>(this->_value);\n        } else {\n            return std::optional<Value>();\n        }\n    }\n\n}; // class leaf\n\ntemplate <typename Key, typename Value>\nauto tree<Key, Value>::make_node(index_t prefix, index_t branching_bit, tree_ptr left_branch, tree_ptr right_branch) -> tree_ptr {\n    if (left_branch) {\n        if (right_branch) {\n            return\n                typename tree<Key, Value>::tree_ptr(new node<Key, Value>(prefix, branching_bit, left_branch, right_branch));\n        } else {\n            return left_branch;\n        }\n    } else {\n        if (right_branch) {\n            return right_branch;\n        } else {\n            return {}; // both branches are empty\n        }\n    }\n}\n\ntemplate <typename Key, typename Value>\nauto tree<Key, Value>::make_leaf(const Key& key, const Value& value) -> tree_ptr {\n    return typename tree<Key, Value>::tree_ptr(new leaf<Key, Value>(key, value));\n}\n\ntemplate <typename Key, typename Value>\nauto tree<Key, Value>::join(tree_ptr t0, tree_ptr t1) -> tree_ptr {\n    index_t p0 = t0->prefix();\n    index_t p1 = t1->prefix();\n    index_t m = compute_branching_bit(p0, t0->branching_bit(), p1, t1->branching_bit());\n    tree_ptr t;\n\n    if (zero_bit(p0, m)) {\n        t = make_node(mask(p0, m), m, t0, t1);\n    } else {\n        t = make_node(mask(p0, m), m, t1, t0);\n    }\n    return t;\n}\n\ntemplate <typename Key, typename Value>\nauto tree<Key, Value>::insert(tree_ptr t, const Key& key_, const Value& value_, binary_action_t& op,\n                              bool combine_left_to_right) -> std::pair<bool, tree_ptr> {\n    tree_ptr nil;\n    std::pair<bool, tree_ptr> res_lb, res_rb;\n    std::pair<bool, std::optional<Value>> new_value;\n    std::pair<bool, tree_ptr> bottom = {true, nil};\n    if (t) {\n        if (t->is_node()) {\n            index_t branching_bit = t->branching_bit();\n            index_t prefix = t->prefix();\n            if (match_prefix(index(key_), prefix, branching_bit)) {\n                if (zero_bit(index(key_), branching_bit)) {\n                    tree_ptr lb = t->left_branch();\n                    tree_ptr new_lb;\n                    if (lb) {\n                        auto [is_bottom, tree_ptr] = insert(lb, key_, value_, op, combine_left_to_right);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        new_lb = tree_ptr;\n                    } else {\n                        if (!op.default_is_absorbing()) {\n                            new_lb = make_leaf(key_, value_);\n                        }\n                    }\n                    if (new_lb == lb) {\n                        return {false, t};\n                    } else {\n                        return {false, make_node(prefix, branching_bit, new_lb, t->right_branch())};\n                    }\n                } else {\n                    tree_ptr rb = t->right_branch();\n                    tree_ptr new_rb;\n                    if (rb) {\n                        auto [is_bottom, tree_ptr] = insert(rb, key_, value_, op, combine_left_to_right);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        new_rb = tree_ptr;\n                    } else {\n                        if (!op.default_is_absorbing()) {\n                            new_rb = make_leaf(key_, value_);\n                        }\n                    }\n                    if (new_rb == rb) {\n                        return {false, t};\n                    } else {\n                        return {false, make_node(prefix, branching_bit, t->left_branch(), new_rb)};\n                    }\n                }\n            } else {\n                if (op.default_is_absorbing()) {\n                    return {false, t};\n                } else {\n                    return {false, join(make_leaf(key_, value_), t)};\n                }\n            }\n        } else {\n            const auto& [key, value] = t->binding();\n            if (index(key) == index(key_)) {\n                new_value = combine_left_to_right ? op.apply(value, value_) : op.apply(value_, value);\n                if (new_value.first) {\n                    return bottom;\n                }\n                if (new_value.second) {\n                    if (*(new_value.second) == value) {\n                        return {false, t};\n                    } else {\n                        return {false, make_leaf(key_, *(new_value.second))};\n                    }\n                } else {\n                    return {false, nil};\n                }\n            } else {\n                if (op.default_is_absorbing()) {\n                    return {false, t};\n                } else {\n                    return {false, join(make_leaf(key_, value_), t)};\n                }\n            }\n        }\n    } else {\n        if (op.default_is_absorbing()) {\n            return {false, nil};\n        } else {\n            return {false, make_leaf(key_, value_)};\n        }\n    }\n}\n\ntemplate <typename Key, typename Value>\nauto tree<Key, Value>::remove(tree_ptr t, const Key& key_) -> tree_ptr {\n    tree_ptr nil;\n    index_t id = index(key_);\n    if (t) {\n        if (t->is_node()) {\n            index_t branching_bit = t->branching_bit();\n            index_t prefix = t->prefix();\n            if (match_prefix(id, prefix, branching_bit)) {\n                if (zero_bit(id, branching_bit)) {\n                    tree_ptr lb = t->left_branch();\n                    tree_ptr new_lb;\n                    if (lb) {\n                        new_lb = remove(lb, key_);\n                    }\n                    if (new_lb == lb) {\n                        return t;\n                    } else {\n                        return make_node(prefix, branching_bit, new_lb, t->right_branch());\n                    }\n                } else {\n                    tree_ptr rb = t->right_branch();\n                    tree_ptr new_rb;\n                    if (rb) {\n                        new_rb = remove(rb, key_);\n                    }\n                    if (new_rb == rb) {\n                        return t;\n                    } else {\n                        return make_node(prefix, branching_bit, t->left_branch(), new_rb);\n                    }\n                }\n            } else {\n                return t;\n            }\n        } else {\n            binding_t b = t->binding();\n            if (index(b.first) == id) {\n                return nil;\n            } else {\n                return t;\n            }\n        }\n    } else {\n        return nil;\n    }\n}\n\ntemplate <typename Key, typename Value>\nauto tree<Key, Value>::merge(tree_ptr s, tree_ptr t, binary_action_t& op,\n                             bool combine_left_to_right) -> std::pair<bool, tree_ptr> {\n    constexpr tree_ptr nil;\n    constexpr std::pair<bool, tree_ptr> bottom = {true, nil};\n    if (s) {\n        if (t) {\n            if (s == t) {\n                return {false, s};\n            } else if (s->is_leaf()) {\n                auto& [key, old_value] = s->binding();\n                if (op.default_is_absorbing()) {\n                    if (std::optional<Value> value = t->lookup(key, old_value)) {\n                        auto [is_bottom, tree] = combine_left_to_right ? op.apply(old_value, *value) : op.apply(*value, old_value);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        if (tree) {\n                            if (*tree == old_value) {\n                                return {false, s};\n                            } else {\n                                return {false, make_leaf(key, *value)};\n                            }\n                        } else {\n                            return {false, nil};\n                        }\n                    } else {\n                        return {false, nil};\n                    }\n                } else {\n                    return insert(t, key, old_value, op, !combine_left_to_right);\n                }\n            } else if (t->is_leaf()) {\n                auto& [key, old_value] = t->binding();\n                if (op.default_is_absorbing()) {\n                    if (std::optional<Value> value = s->lookup(key)) {\n                        auto [is_bottom, new_value] = combine_left_to_right ? op.apply(*value, old_value) : op.apply(old_value, *value);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        if (new_value) {\n                            if (*new_value == old_value) {\n                                return {false, t};\n                            } else {\n                                return {false, make_leaf(old_value, *new_value)};\n                            }\n                        } else {\n                            return {false, nil};\n                        }\n                    } else {\n                        return {false, nil};\n                    }\n                } else {\n                    return insert(s, key, old_value, op, combine_left_to_right);\n                }\n            } else {\n                if (s->branching_bit() == t->branching_bit() && s->prefix() == t->prefix()) {\n                    auto [is_bottom_lb, new_lb] = merge(s->left_branch(), t->left_branch(), op, combine_left_to_right);\n                    if (is_bottom_lb) {\n                        return bottom;\n                    }\n                    auto [is_bottom_rb, new_rb] = merge(s->right_branch(), t->right_branch(), op, combine_left_to_right);\n                    if (is_bottom_rb) {\n                        return bottom;\n                    }\n                    if (new_lb == s->left_branch() && new_rb == s->right_branch()) {\n                        return {false, s};\n                    } else if (new_lb == t->left_branch() && new_rb == t->right_branch()) {\n                        return {false, t};\n                    } else {\n                        return {false, make_node(s->prefix(), s->branching_bit(), new_lb, new_rb)};\n                    }\n                } else if (s->branching_bit() > t->branching_bit() &&\n                           match_prefix(t->prefix(), s->prefix(), s->branching_bit())) {\n                    if (zero_bit(t->prefix(), s->branching_bit())) {\n                        auto [is_bottom, new_lb] = merge(s->left_branch(), t, op, combine_left_to_right);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        tree_ptr new_rb = op.default_is_absorbing() ? nil : s->right_branch();\n                        if (new_lb == s->left_branch() && new_rb == s->right_branch()) {\n                            return {false, s};\n                        } else {\n                            return {false, make_node(s->prefix(), s->branching_bit(), new_lb, new_rb)};\n                        }\n                    } else {\n                        tree_ptr new_lb = op.default_is_absorbing() ? nil : s->left_branch();\n                        auto [is_bottom, new_rb] = merge(s->right_branch(), t, op, combine_left_to_right);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        if (new_lb == s->left_branch() && new_rb == s->right_branch()) {\n                            return {false, s};\n                        } else {\n                            return {false, make_node(s->prefix(), s->branching_bit(), new_lb, new_rb)};\n                        }\n                    }\n                } else if (s->branching_bit() < t->branching_bit() &&\n                           match_prefix(s->prefix(), t->prefix(), t->branching_bit())) {\n                    if (zero_bit(s->prefix(), t->branching_bit())) {\n                        auto [is_bottom, new_lb] = merge(s, t->left_branch(), op, combine_left_to_right);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        tree_ptr new_rb = op.default_is_absorbing() ? nil : t->right_branch();\n                        if (new_lb == t->left_branch() && new_rb == t->right_branch()) {\n                            return {false, t};\n                        } else {\n                            return {false, make_node(t->prefix(), t->branching_bit(), new_lb, new_rb)};\n                        }\n                    } else {\n                        tree_ptr new_lb = op.default_is_absorbing() ? nil : t->left_branch();\n                        auto [is_bottom, new_rb] = merge(s, t->right_branch(), op, combine_left_to_right);\n                        if (is_bottom) {\n                            return bottom;\n                        }\n                        if (new_lb == t->left_branch() && new_rb == t->right_branch()) {\n                            return {false, t};\n                        } else {\n                            return {false, make_node(t->prefix(), t->branching_bit(), new_lb, new_rb)};\n                        }\n                    }\n                } else {\n                    if (op.default_is_absorbing()) {\n                        return {false, nil};\n                    } else {\n                        return {false, join(s, t)};\n                    }\n                }\n            }\n        } else {\n            if (op.default_is_absorbing()) {\n                return {false, nil};\n            } else {\n                return {false, s};\n            }\n        }\n    } else {\n        if (op.default_is_absorbing()) {\n            return {false, nil};\n        } else {\n            return {false, t};\n        }\n    }\n}\n\ntemplate <typename Key, typename Value>\nbool tree<Key, Value>::compare(tree_ptr s, tree_ptr t, partial_order_t& po,\n                               bool compare_left_to_right) {\n    if (s) {\n        if (t) {\n            if (s != t) {\n                if (s->is_leaf()) {\n                    auto [key, value] = s->binding();\n                    std::optional<Value> value_ = t->lookup(key);\n                    if (value_) {\n                        Value left = compare_left_to_right ? value : *value_;\n                        Value right = compare_left_to_right ? *value_ : value;\n                        if (!po.leq(left, right)) {\n                            return false;\n                        }\n                    } else {\n                        if ((compare_left_to_right && !po.default_is_top()) ||\n                            (!compare_left_to_right && po.default_is_top())) {\n                            return false;\n                        }\n                    }\n                    if (compare_left_to_right && po.default_is_top() && !t->is_leaf()) {\n                        return false;\n                    }\n                    if (!compare_left_to_right && !po.default_is_top() && !t->is_leaf()) {\n                        return false;\n                    }\n                } else if (t->is_leaf()) {\n                    if (!compare(t, s, po, !compare_left_to_right)) {\n                        return false;\n                    }\n                } else {\n                    if (s->branching_bit() == t->branching_bit() && s->prefix() == t->prefix()) {\n                        if (!compare(s->left_branch(), t->left_branch(), po, compare_left_to_right)) {\n                            return false;\n                        }\n                        if (!compare(s->right_branch(), t->right_branch(), po, compare_left_to_right)) {\n                            return false;\n                        }\n                    } else if (s->branching_bit() > t->branching_bit() &&\n                               match_prefix(t->prefix(), s->prefix(), s->branching_bit())) {\n                        if ((compare_left_to_right && !po.default_is_top()) ||\n                            (!compare_left_to_right && po.default_is_top())) {\n                            return false;\n                        }\n                        if (zero_bit(t->prefix(), s->branching_bit())) {\n                            if (!compare(s->left_branch(), t, po, compare_left_to_right)) {\n                                return false;\n                            }\n                        } else {\n                            if (!compare(s->right_branch(), t, po, compare_left_to_right)) {\n                                return false;\n                            }\n                        }\n                    } else if (s->branching_bit() < t->branching_bit() &&\n                               match_prefix(s->prefix(), t->prefix(), t->branching_bit())) {\n                        if ((compare_left_to_right && po.default_is_top()) ||\n                            (!compare_left_to_right && !po.default_is_top())) {\n                            return false;\n                        }\n                        if (zero_bit(s->prefix(), t->branching_bit())) {\n                            if (!compare(s, t->left_branch(), po, compare_left_to_right)) {\n                                return false;\n                            }\n                        } else {\n                            if (!compare(s, t->right_branch(), po, compare_left_to_right)) {\n                                return false;\n                            }\n                        }\n                    } else {\n                        return false;\n                    }\n                }\n            }\n        } else {\n            if ((compare_left_to_right && !po.default_is_top()) || (!compare_left_to_right && po.default_is_top())) {\n                return false;\n            }\n        }\n    } else {\n        if (t) {\n            if ((compare_left_to_right && po.default_is_top()) || (!compare_left_to_right && !po.default_is_top())) {\n                return false;\n            }\n        } else {\n            // s and t are empty\n        }\n    }\n    return true;\n}\n\n} // namespace patricia_trees_impl\n\ntemplate <typename Key, typename Value>\nclass patricia_tree final {\n  private:\n    using tree_t = patricia_trees_impl::tree<Key, Value>;\n    using tree_ptr = typename tree_t::tree_ptr;\n\n  public:\n    using patricia_tree_t = patricia_tree<Key, Value>;\n    using binary_action_t = typename tree_t::binary_action_t;\n    using partial_order_t = typename tree_t::partial_order_t;\n    using binding_t = typename tree_t::binding_t;\n\n  private:\n    tree_ptr _tree;\n\n  public:\n    class iterator : public boost::iterator_facade<iterator, binding_t, boost::forward_traversal_tag, binding_t> {\n        friend class boost::iterator_core_access;\n        friend class patricia_tree<Key, Value>;\n\n      private:\n        typename tree_t::iterator _it;\n\n      public:\n        iterator() = default;\n\n        explicit iterator(const patricia_tree_t& pt) : _it(pt._tree) {}\n\n      private:\n        explicit iterator(tree_ptr t) : _it(t) {}\n\n        void increment() { ++this->_it; }\n\n        bool equal(const iterator& other) const { return this->_it == other._it; }\n\n        binding_t dereference() const { return *this->_it; }\n\n    }; // class iterator\n\n    class insert_op : public binary_action_t {\n        std::pair<bool, std::optional<Value>> apply(const Value& /* old_value */, const Value& new_value) {\n            return {false, std::optional<Value>(new_value)};\n        }\n        bool default_is_absorbing() { return false; }\n    }; // class insert_op\n\n  public:\n    patricia_tree() = default;\n\n    patricia_tree(const patricia_tree_t& t) : _tree(t._tree) {}\n\n    patricia_tree& operator=(const patricia_tree_t& t) {\n        this->_tree = t._tree;\n        return *this;\n    }\n\n    [[nodiscard]] std::size_t size() const {\n        if (this->_tree) {\n            return this->_tree->size();\n        } else {\n            return 0;\n        }\n    }\n\n    iterator begin() const { return iterator(this->_tree); }\n\n    iterator end() const { return iterator(); }\n\n    std::optional<Value> lookup(const Key& key) const {\n        if (this->_tree) {\n            return this->_tree->lookup(key);\n        } else {\n            return std::optional<Value>();\n        }\n    }\n\n    bool merge_with(const patricia_tree_t& t, binary_action_t& op) {\n        auto [is_bottom, tree_ptr] = tree_t::merge(this->_tree, t._tree, op, true);\n        if (is_bottom) {\n            return true; // bottom must be propagated\n        } else {\n            this->_tree = tree_ptr;\n            return false;\n        }\n    }\n\n    void insert(const Key& key, const Value& value) {\n        insert_op op;\n        auto [is_bottom, tree_ptr] = tree_t::insert(this->_tree, key, value, op, true);\n        this->_tree = tree_ptr;\n    }\n\n    void remove(const Key& key) { this->_tree = tree_t::remove(this->_tree, key); }\n\n    void clear() { this->_tree.reset(); }\n\n    [[nodiscard]] bool empty() const { return !this->_tree; }\n\n    bool leq(const patricia_tree_t& t, partial_order_t& po) const {\n        return tree_t::compare(this->_tree, t._tree, po, true);\n    }\n\n}; // class patricia_tree\n\n} // namespace crab\n", "meta": {"hexsha": "3a9207bfe523ce5dede436447fb4b94fc8f7d329", "size": 32665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crab_utils/patricia_trees.hpp", "max_stars_repo_name": "poornagmsft/ebpf-verifier", "max_stars_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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": "src/crab_utils/patricia_trees.hpp", "max_issues_repo_name": "poornagmsft/ebpf-verifier", "max_issues_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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": "src/crab_utils/patricia_trees.hpp", "max_forks_repo_name": "poornagmsft/ebpf-verifier", "max_forks_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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": 37.8505214368, "max_line_length": 136, "alphanum_fraction": 0.4923006276, "num_tokens": 7013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.031618767496774974, "lm_q1q2_score": 0.013359075814499634}}
{"text": "#pragma once\n\n#include <set>\n#include <map>\n#include <vector>\n#include <bitset>\n#include <utility>\n#include <algorithm>\n\n#include <random>\n#include <chrono>\n\n#include <string>\n#include <iostream>\n\n#include <cmath>\n\n#include <boost/math/special_functions/binomial.hpp>\n\n#include <boost/thread.hpp>\n#include <boost/bind/bind.hpp>\n#include <boost/asio/post.hpp>\n#include <boost/asio/thread_pool.hpp>\n#include <boost/thread/mutex.hpp>\n\n#include \"rtuple.hpp\"\n#include \"network.hpp\"\n#include \"diffusionstate.hpp\"\n#include \"sortmap.hpp\"\n#include \"tools.hpp\"\n#include \"macro.hpp\"\n\n// double computeG(DiffusionState_MIC &diffusionState, std::set<int> &S, std::vector<rTuple> &rtup, int n, std::string type, double *result){\n//     int count = 0;\n//     for(rTuple &rt: rtup){\n//         switch(type[0]){\n//         case 'u':\n//             if(intersection(S, rt.upper)) count++;\n//             break;\n//         case 'm':\n//             if(diffusionState.compute_g(S, rt))  count++;\n//             break;\n//         case 'l':\n//             if(intersection(S, rt.lower)) count++;\n//             break;\n//         default:\n//             std::cout << \"invalid type\" << std::endl;\n//         }\n//     }\n//     *result = (double)n*count/rtup.size();\n//     return *result;\n// }\n\nstd::bitset<THREAD> scheduler;\nboost::mutex mt;\n\nResults HighDegree_computeSeedSet(Network &network, DiffusionState_MIC &diffusionState, int k, int span){\n    std::cout << \"========== High degree running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    network.sortByDegree();\n    int node;\n    std::set<int> solution;\n    for(int i = 0;i < network.vertexNum;i++){\n        node = network.sorted_degree[i];\n        if(diffusionState.seed_state[node] == -1 && solution.find(node) == solution.end()){\n            solution.insert(node);\n            if(solution.size() == k){\n                // std::cout << \"========== High degree finish ==========\" << std::endl << std::endl;\n                break;\n            }\n        }\n    }\n    Results result;\n    for(int i = 0;i < k/span;i++){\n        int k = i*span+span;\n        std::set<int> temp_solution;\n        std::set<int>::iterator iter = solution.begin();\n        for(int j = 0;j < k;j++, iter++)\n            temp_solution.insert(*iter);\n        result.seedset[k] = temp_solution;\n        result.supp[k] = 0.;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== High degree finish ==========\" << std::endl << std::endl;\n    return result;\n}\n\nstd::set<int> NaiveGreedy_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, double epsilon_1, double N, int times){\n    std::cout << \"========== Naive greedy running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    std::set<int> solution;\n    int cmaxindex, cindex, *state = new int[network.vertexNum];\n    double cmaxvalue, tempvalue;\n    memcpy(state, diffusionState.seed_state, network.vertexNum*sizeof(int));\n\n    for(int i = 0;i < k;i++){\n        std::cout << \"Naive greedy #\" << i+1 << std::endl;\n        cmaxindex = -1;\n        cmaxvalue = -1.;\n        for(int j = 0;j < network.vertexNum;j++){\n            if(state[j] == -1)  solution.insert(j);\n            cindex = diffusionState.seed(solution);\n            tempvalue = diffusionState.expInfluenceComplete(network, times, cindex);\n            if(tempvalue > cmaxvalue){\n                cmaxvalue = tempvalue;\n                cmaxindex = j;\n            }\n            diffusionState.removeSeed(cindex);\n            solution.erase(j);\n        }\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Naive greedy finish ==========\" << std::endl << std::endl;\n    return solution;\n}\n\nvoid __parallel(DiffusionState_MIC &diffusionState, std::set<int> seed, int v, std::vector<rTuple> &rtup, const std::map<int,int> &coverred, std::set<int> &type1, std::set<int> &type2, std::set<int> &utype1, double *result){\n    int ret, temp = 0;\n    int cmaxindex = -1;\n    int tid = -1;\n    double cmaxvalue = -1.;\n    mt.lock();\n    tid = scheduler._Find_first();\n    scheduler.flip(tid);\n    mt.unlock();\n    type1.clear();\n    type2.clear();\n    utype1.clear();\n    seed.insert(v);\n    for(std::pair<int,int> p: coverred){\n        ret = diffusionState.compute_g(seed, rtup[p.first], \"mid\", nullptr, tid);\n        switch(p.second){\n        case 0:\n            switch(ret){\n            case 2:\n                temp++;\n                type2.insert(p.first);\n                break;\n            case 1:\n                temp++;\n                type1.insert(p.first);\n                break;\n            }\n            break;\n        case 1:\n            switch(ret){\n            case -1:\n                temp--;\n                utype1.insert(p.first);\n                break;\n            }\n            break;\n        }\n    }\n    *result = temp;\n    mt.lock();\n    scheduler.flip(tid);\n    mt.unlock();\n}\n\nvoid Sandwich_greedyMid(const Network &network, DiffusionState_MIC &diffusionState, std::vector<rTuple> &rtup, std::set<int> &solution, int k, double *coverred, bool verbose=true){\n    std::set<int> candidate;\n    std::map<int,int> coverred_state;\n    int tid = 0;\n    for(rTuple &rt: rtup){\n        for(int v: rt.upper)\n            if(candidate.find(v) == candidate.end())\n                candidate.insert(v);\n        coverred_state[tid++] = 0;\n    }\n    double profit = 0.;\n    int candidate_size = candidate.size();\n    double *results = new double[candidate_size];\n    std::vector<std::set<int>> type1s(candidate_size), type2s(candidate_size), utype1s(candidate_size);\n    for(int i = 0;i < k;i++){\n        int cmaxindex = -1, max_id = 0;\n        double cmaxvalue = -1.;\n        tid = 0;\n        boost::asio::thread_pool pool(THREAD);\n        allSet(scheduler);\n        for(int v: candidate){\n            auto bind_fn = boost::bind(__parallel, ref(diffusionState), ref(solution), v, ref(rtup), ref(coverred_state), ref(type1s[tid]), ref(type2s[tid]), ref(utype1s[tid]), results+tid);\n            boost::asio::post(pool, bind_fn);\n            tid++;\n        }\n        pool.join();\n        std::set<int>::iterator it = candidate.begin();\n        for(int j = 0;j < candidate_size;j++, it++){\n            if(cmaxvalue < results[j]){\n                cmaxvalue = results[j];\n                cmaxindex = *it;\n                max_id = j;\n            }\n        }\n        if(cmaxvalue < 0)\n            break;\n        profit += cmaxvalue;\n        if(coverred)    coverred[i] = profit;\n        solution.insert(cmaxindex);\n        candidate.erase(cmaxindex);\n        for(int j: type2s[max_id])\n            coverred_state.erase(j);\n        for(int j: type1s[max_id]){\n            // if(coverred_state[j] != 0){\n            //     std::cout << \"ERROR: setting type 1 wrong, != 0\" << std::endl;\n            //     exit(1);\n            // }\n            coverred_state[j] = 1;\n        }\n        for(int j: utype1s[max_id]){\n            // if(coverred_state[j] != 1){\n            //     std::cout << \"ERROR: setting type 1 wrong, != 1\" << std::endl;\n            //     exit(1);\n            // }\n            coverred_state[j] = 0;\n        }\n        if(verbose) std::cout << \"greedy mid #\" << i+1 << \": \" << profit << std::endl;\n    }\n    delete [] results;\n}\n\nResults ReverseGreedy_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, int l, int span){\n    std::cout << \"========== Reverse greedy running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    std::vector<rTuple> rtup;\n    std::cout << \"l \" << l << \" \" << diffusionState.getRTuples(network, rtup, l) << std::endl;\n    std::set<int> mid_solution;\n    std::cout << \"working on mid-solution...\" << std::endl;\n    Sandwich_greedyMid(network, diffusionState, rtup, mid_solution, k, nullptr);\n    Results result;\n    bool flag = true;\n    for(int i = 0;i < k/span && flag;i++){\n        int nk = i*span+span;\n        std::set<int> solution;\n        std::set<int>::iterator iter = mid_solution.begin();\n        for(int j = 0;j < nk;j++, iter++){\n            if(iter == mid_solution.end()){\n                flag = false;\n                break;\n            }\n            solution.insert(*iter);\n        }\n        result.seedset[nk] = solution;\n        result.supp[nk] = 0.;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Reverse greedy finish ==========\" << std::endl << std::endl;\n    return result;\n}\n\nResults ReverseGreedy_computeSeedSet_noneoutput(const Network &network, DiffusionState_MIC &diffusionState, int k, int l, int span){\n    auto start = std::chrono::high_resolution_clock::now();\n    std::vector<rTuple> rtup;\n    diffusionState.getRTuples(network, rtup, l);\n    std::set<int> mid_solution;\n    Sandwich_greedyMid(network, diffusionState, rtup, mid_solution, k, nullptr, false);\n    Results result;\n    bool flag = true;\n    for(int i = 0;i < k/span && flag;i++){\n        int nk = i*span+span;\n        std::set<int> solution;\n        std::set<int>::iterator iter = mid_solution.begin();\n        for(int j = 0;j < nk;j++, iter++){\n            if(iter == mid_solution.end()){\n                flag = false;\n                break;\n            }\n            solution.insert(*iter);\n        }\n        result.seedset[nk] = solution;\n        result.supp[nk] = 0.;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    return result;\n}\n\nResults ReverseGreedy_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, std::vector<rTuple> &rtup, int span){\n    std::cout << \"========== Reverse greedy running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    std::cout << \"r_tuple size: \" << rtup.size() << std::endl;\n    std::set<int> mid_solution;\n    std::cout << \"working on mid-solution...\" << std::endl;\n    Sandwich_greedyMid(network, diffusionState, rtup, mid_solution, k, nullptr);\n    Results result;\n    bool flag = true;\n    for(int i = 0;i < k/span && flag;i++){\n        int nk = i*span+span;\n        std::set<int> solution;\n        std::set<int>::iterator iter = mid_solution.begin();\n        for(int j = 0;j < nk;j++, iter++){\n            if(iter == mid_solution.end()){\n                flag = false;\n                break;\n            }\n            solution.insert(*iter);\n        }\n        result.seedset[nk] = solution;\n        result.supp[nk] = 0.;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Reverse greedy finish ==========\" << std::endl << std::endl;\n    return result;\n}\n\nResults ReverseGreedy_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, std::vector<rTuple> &rtup){\n    std::cout << \"========== Reverse greedy running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    std::cout << \"r_tuple size: \" << rtup.size() << std::endl;\n    std::set<int> mid_solution;\n    std::cout << \"working on mid-solution...\" << std::endl;\n    Sandwich_greedyMid(network, diffusionState, rtup, mid_solution, k, nullptr);\n    Results result;\n    result.seedset[k] = mid_solution;\n    result.supp[k] = 0.;\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Reverse greedy finish ==========\" << std::endl << std::endl;\n    return result;\n}\n\ndouble Sandwich_greedy(std::vector<rTuple> &rtup, std::set<int> &solution, int k, const std::string &type){\n    std::vector<std::set<int>> rrsets;\n    for(rTuple &rt: rtup){\n        switch(type[0]){\n        case 'u':\n            rrsets.push_back(rt.upper);\n            break;\n        case 'l':\n            rrsets.push_back(rt.lower);\n            break;\n        default:\n            std::cout << \"invalid model\" << std::endl;\n        }\n    }\n    \n    double coverred = 0.;\n    double profit = 0.;\n    std::map<int, std::set<int>> nodes_cover_sets;\n    bool coverred_rrsets[rrsets.size()];\n    for(int i = 0;i < rrsets.size();i++){\n        for(int index: rrsets[i]){\n            if(nodes_cover_sets.find(index) == nodes_cover_sets.end())\n                nodes_cover_sets[index] = std::set<int>();\n            nodes_cover_sets[index].insert(i);\n        }\n        coverred_rrsets[i] = false;\n    }\n    std::vector<std::pair<int,int>> sortPair;\n    for(auto i = nodes_cover_sets.begin();i != nodes_cover_sets.end();i++)\n        sortPair.push_back(std::make_pair(i->first, i->second.size()));\n    std::sort(sortPair.begin(), sortPair.end(), [](const std::pair<int,int> a, const std::pair<int,int> b)-> bool {\n        return a.second > b.second;\n    });\n    sortedMap mymap;\n    for(std::pair<int,int> p: sortPair)\n        mymap.push_back(p.first, p.second);\n\n    int c_bound, t_bound, c_seed;\n    bool sign;\n    std::set<int> c_seed_cover;\n    for(int i = 0;i < k;i++){\n        sign = false;\n        c_bound = mymap.size();\n        while(c_bound > 0){\n            c_seed = mymap.get(0);\n            c_seed_cover = nodes_cover_sets[c_seed];\n            for(auto j = c_seed_cover.begin();j != c_seed_cover.end();){\n                std::set<int>::iterator temp_j = ++j;\n                j--;\n                if(coverred_rrsets[*j]){\n                    c_seed_cover.erase(*j);\n                    j = temp_j;\n                } else  j++;\n            }\n            // std::cout << \"greedy\" << std::endl;\n            // for(int j: c_seed_cover){\n            //     if(coverred_rrsets[j])\n            //         c_seed_cover.erase(j);\n            // }\n            t_bound = mymap.update(c_seed, c_seed_cover.size());\n            if(t_bound == 0){\n                solution.insert(c_seed);\n                sign = true;\n                for(int j: c_seed_cover){\n                    if(coverred_rrsets[j]){\n                        std::cout << \"greedy update may wrong\" << std::endl;\n                        exit(1);\n                    }\n                    else{\n                        coverred_rrsets[j] = true;\n                        coverred += 1.;\n                    }\n                }\n                break;\n            }\n            if(t_bound < c_bound)   c_bound = t_bound;\n        }\n        if(!sign){\n            std::cout << \"greedy lazy: no node selected\" << std::endl;\n            exit(1);\n        }\n    }\n    return coverred;\n}\n\ndouble Sandwich_computeLowerBound(const Network &network, DiffusionState_MIC &diffusionState, int k, double eps1, double N, int p, const std::string &type=\"lower\"){\n    int n = network.vertexNum;\n    std::vector<rTuple> rtup;\n    std::set<int> S;\n    double eps0 = 100 * eps1;\n    // boost::math::binomial_coefficient<double>(n,k)\n    double lambda = (n*(2+eps0)*log(N*k*log(n)*log2(n)))/(eps0*eps0);\n    double x, l, g_lower, pw = p;\n    for(int i = 1;i < (int)log2(n-1.)/log2(p);i++){\n        x = n/pw;\n        l = lambda/x;\n        pw *= p;\n        if(rtup.size() < l)\n            diffusionState.getRTuples(network, rtup, (int)(l-rtup.size()));\n        S.clear();\n        Sandwich_greedy(rtup, S, k, type);\n        g_lower = diffusionState.computeG(S, rtup, n, type, &g_lower);\n        std::cout << g_lower << \" \" << (1+eps0)*x << std::endl;\n        if(g_lower >= (1+eps0)*x)   return g_lower;\n    }\n    std::cout << \"compute lower bound may wrong, opt too small\" << std::endl;\n    exit(1);\n}\n\ndouble Sandwich_decideL(int n, int k, double low_bound, double eps1, double eps2, double N, double *l2){\n    // double l1 = ((2+eps1)*n*(log(N+boost::math::binomial_coefficient<double>(n,k))))/(eps1*eps1);\n    double l1 = ((2+eps1)*n*log(N*k*log(n)))/(eps1*eps1);\n    *l2 = 2*n*log(N)/(eps2*eps2);\n    return (l1>*l2?l1:*l2)/low_bound;\n}\n\nint Sandwich_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, double eps1, double N, std::set<int> &solution, int p, double *l2){\n    // std::cout << \"========== Sandwich running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    double eps0 = eps1, eps2 = (eps1*log(N))/(log(network.vertexNum)+log(N));\n    eps2 = eps1;\n    double low_bound = Sandwich_computeLowerBound(network, diffusionState, k, eps1, N, p);\n    int l = (int)Sandwich_decideL(network.vertexNum, k, low_bound, eps1, eps2, N, l2);\n    *l2 /= low_bound;\n    // std::cout << \"l2  \" << l2 << std::endl;\n    std::vector<rTuple> rtup;\n    // std::cout << \"l \" << l << \" \" << diffusionState.getRTuples(network, rtup, l) << std::endl;\n    diffusionState.getRTuples(network, rtup, l);\n    std::set<int> upper_solution, lower_solution;\n    // std::cout << \"working on upper solution...\" << std::endl;\n    Sandwich_greedy(rtup, upper_solution, k, \"upper\");\n    // std::cout << \"working on lower solution...\" << std::endl;\n    Sandwich_greedy(rtup, lower_solution, k, \"lower\");\n    // std::cout << \"calculating upper G... \" << std::endl;\n    double upper_g = diffusionState.computeG(upper_solution, rtup, network.vertexNum, \"mid\", &upper_g);\n    // std::cout << \"  upper G = \" << upper_g << std::endl;\n    // std::cout << \"calculating lower G... \" << std::endl;\n    double lower_g = diffusionState.computeG(lower_solution, rtup, network.vertexNum, \"mid\", &lower_g);\n    // std::cout << \"  lower G = \" << lower_g << std::endl;\n    if(upper_g > lower_g)\n        for(int upper_v: upper_solution)\n            solution.insert(upper_v);\n    else\n        for(int lower_v: lower_solution)\n            solution.insert(lower_v);\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    // std::cout << \"========== Sandwich finish ==========\" << std::endl << std::endl;\n    return l;\n}\n\nResults Sandwich_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, double eps1, double N, std::vector<rTuple> &rtup, int p, int span, double *l2){\n    std::cout << \"========== Sandwich running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    double eps0 = eps1, eps2 = (eps1*log(N))/(log(network.vertexNum)+log(N));\n    eps2 = eps1;\n    double low_bound = Sandwich_computeLowerBound(network, diffusionState, k, eps1, N, p);\n    int l = (int)Sandwich_decideL(network.vertexNum, k, low_bound, eps1, eps2, N, l2);\n    *l2 /= low_bound;\n    // *l2 = l/log2(network.vertexNum);\n    std::cout << \"l \" << l;\n    std::cout << \" \" << diffusionState.getRTuples(network, rtup, l) << std::endl;\n    // diffusionState.getRTuples(network, rtup, l);\n    std::set<int> upper_solution, lower_solution;\n    std::cout << \"working on upper solution...\" << std::endl;\n    Sandwich_greedy(rtup, upper_solution, k, \"upper\");\n    std::cout << \"working on lower solution...\" << std::endl;\n    Sandwich_greedy(rtup, lower_solution, k, \"lower\");\n    Results result;\n    for(int i = 0;i < k/span;i++){\n        int nk = i*span+span;\n        std::set<int> upper_solution_k, lower_solution_k;\n        std::set<int>::iterator upper_iter = upper_solution.begin();\n        std::set<int>::iterator lower_iter = lower_solution.begin();\n        for(int j = 0;j < nk;j++, upper_iter++, lower_iter++){\n            upper_solution_k.insert(*upper_iter);\n            lower_solution_k.insert(*lower_iter);\n        }\n        double upper_G = diffusionState.computeG(upper_solution_k, rtup, network.vertexNum, \"mid\", nullptr);\n        double lower_G = diffusionState.computeG(lower_solution_k, rtup, network.vertexNum, \"mid\", nullptr);\n        double ratio = upper_G / diffusionState.computeG(upper_solution_k, rtup, network.vertexNum, \"upper\", nullptr);\n\n        result.supp[nk] = ratio;\n        if(upper_G > lower_G)\n            result.seedset[nk] = upper_solution_k;\n        else\n            result.seedset[nk] = lower_solution_k;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Sandwich finish ==========\" << std::endl << std::endl;\n    return result;\n}\n\nResults Sandwich_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, int l, int p, int span){\n    std::cout << \"========== Sandwich running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    std::vector<rTuple> rtup;\n    std::cout << \"l \" << l << \" \" << diffusionState.getRTuples(network, rtup, l) << std::endl;\n    std::set<int> upper_solution, lower_solution;\n    std::cout << \"working on upper solution...\" << std::endl;\n    Sandwich_greedy(rtup, upper_solution, k, \"upper\");\n    std::cout << \"working on lower solution...\" << std::endl;\n    Sandwich_greedy(rtup, lower_solution, k, \"lower\");\n    Results result;\n    for(int i = 0;i < k/span;i++){\n        int nk = i*span+span;\n        std::set<int> upper_solution_k, lower_solution_k;\n        std::set<int>::iterator upper_iter = upper_solution.begin();\n        std::set<int>::iterator lower_iter = lower_solution.begin();\n        for(int j = 0;j < nk;j++, upper_iter++, lower_iter++){\n            upper_solution_k.insert(*upper_iter);\n            lower_solution_k.insert(*lower_iter);\n        }\n        double upper_G = diffusionState.computeG(upper_solution_k, rtup, network.vertexNum, \"mid\", nullptr);\n        double lower_G = diffusionState.computeG(lower_solution_k, rtup, network.vertexNum, \"mid\", nullptr);\n        double ratio = upper_G / diffusionState.computeG(upper_solution_k, rtup, network.vertexNum, \"upper\", nullptr);\n\n        result.supp[nk] = ratio;\n        if(upper_G > lower_G)\n            result.seedset[nk] = upper_solution_k;\n        else\n            result.seedset[nk] = lower_solution_k;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Sandwich finish ==========\" << std::endl << std::endl;\n    return result;\n}\n\nResults Sandwich_computeSeedSet(const Network &network, DiffusionState_MIC &diffusionState, int k, int l, std::vector<rTuple> &rtup){\n    // std::cout << \"========== Sandwich running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    // std::cout << \"l \" << l << \" \" << diffusionState.getRTuples(network, rtup, l) << std::endl;\n    diffusionState.getRTuples(network, rtup, l);\n    std::set<int> upper_solution, lower_solution;\n    // std::cout << \"working on upper solution...\" << std::endl;\n    Sandwich_greedy(rtup, upper_solution, k, \"upper\");\n    // std::cout << \"working on lower solution...\" << std::endl;\n    Sandwich_greedy(rtup, lower_solution, k, \"lower\");\n    Results result;\n    double upper_G = diffusionState.computeG(upper_solution, rtup, network.vertexNum, \"mid\", nullptr);\n    double lower_G = diffusionState.computeG(lower_solution, rtup, network.vertexNum, \"mid\", nullptr);\n    double ratio = upper_G / diffusionState.computeG(upper_solution, rtup, network.vertexNum, \"upper\", nullptr);\n\n    result.supp[k] = ratio;\n    if(upper_G > lower_G)\n        result.seedset[k] = upper_solution;\n    else\n        result.seedset[k] = lower_solution;\n    auto end = std::chrono::high_resolution_clock::now();\n    // printTime(start, end);\n    // std::cout << \"========== Sandwich finish ==========\" << std::endl << std::endl;\n    return result;\n}\n\nResults Sandwich_computeSeedSet_upper(const Network &network, DiffusionState_MIC &diffusionState, int k, double eps1, double N, std::vector<rTuple> &rtup, int p, int span, double *l2){\n    diffusionState.setUpper();\n    std::cout << \"========== Sandwich running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    double eps0 = eps1, eps2 = (eps1*log(N))/(log(network.vertexNum)+log(N));\n    eps2 = eps1;\n    double low_bound = Sandwich_computeLowerBound(network, diffusionState, k, eps1, N, p, \"upper\");\n    int l = (int)Sandwich_decideL(network.vertexNum, k, low_bound, eps1, eps2, N, l2);\n    *l2 /= low_bound;\n    // *l2 = l/log2(network.vertexNum);\n    std::cout << \"l \" << l << \" \" << diffusionState.getRTuples(network, rtup, l) << std::endl;\n    // diffusionState.getRTuples(network, rtup, l);\n    std::set<int> upper_solution;\n    std::cout << \"working on upper solution...\" << std::endl;\n    Sandwich_greedy(rtup, upper_solution, k, \"upper\");\n    // std::cout << \"working on lower solution...\" << std::endl;\n    // Sandwich_greedy(rtup, lower_solution, k, \"lower\");\n    Results result;\n    for(int i = 0;i < k/span;i++){\n        int nk = i*span+span;\n        std::set<int> upper_solution_k;\n        std::set<int>::iterator upper_iter = upper_solution.begin();\n        for(int j = 0;j < nk;j++, upper_iter++)\n            upper_solution_k.insert(*upper_iter);\n        double upper_G = diffusionState.computeG(upper_solution_k, rtup, network.vertexNum, \"mid\", nullptr);\n        result.seedset[nk] = upper_solution_k;\n        // double lower_G = diffusionState.computeG(lower_solution_k, rtup, network.vertexNum, \"mid\", nullptr);\n        // double ratio = upper_G / diffusionState.computeG(upper_solution_k, rtup, network.vertexNum, \"upper\", nullptr);\n\n        // result.supp[nk] = ratio;\n        // if(upper_G > lower_G)\n        //     result.seedset[nk] = upper_solution_k;\n        // else\n        //     result.seedset[nk] = lower_solution_k;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Sandwich finish ==========\" << std::endl << std::endl;\n    diffusionState.setBack();\n    return result;\n}\n\nResults Sandwich_computeSeedSet_lower(const Network &network, DiffusionState_MIC &diffusionState, int k, double eps1, double N, std::vector<rTuple> &rtup, int p, int span, double *l2){\n    diffusionState.setLower();\n    std::cout << \"========== Sandwich running ==========\" << std::endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    double eps0 = eps1, eps2 = (eps1*log(N))/(log(network.vertexNum)+log(N));\n    eps2 = eps1;\n    double low_bound = Sandwich_computeLowerBound(network, diffusionState, k, eps1, N, p);\n    int l = (int)Sandwich_decideL(network.vertexNum, k, low_bound, eps1, eps2, N, l2);\n    *l2 /= low_bound;\n    // *l2 = l/log2(network.vertexNum);\n    std::cout << \"l \" << l << \" \" << diffusionState.getRTuples(network, rtup, l) << std::endl;\n    // diffusionState.getRTuples(network, rtup, l);\n    std::set<int> lower_solution;\n    // std::cout << \"working on upper solution...\" << std::endl;\n    // Sandwich_greedy(rtup, upper_solution, k, \"upper\");\n    std::cout << \"working on lower solution...\" << std::endl;\n    Sandwich_greedy(rtup, lower_solution, k, \"lower\");\n    Results result;\n    for(int i = 0;i < k/span;i++){\n        int nk = i*span+span;\n        std::set<int> lower_solution_k;\n        std::set<int>::iterator lower_iter = lower_solution.begin();\n        for(int j = 0;j < nk;j++, lower_iter++)\n            lower_solution_k.insert(*lower_iter);\n        double lower_G = diffusionState.computeG(lower_solution_k, rtup, network.vertexNum, \"mid\", nullptr);\n        result.seedset[nk] = lower_solution_k;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    printTime(start, end);\n    std::cout << \"========== Sandwich finish ==========\" << std::endl << std::endl;\n    diffusionState.setBack();\n    return result;\n}", "meta": {"hexsha": "c5e10d59d2ca9a9ce1c8dae9721566024de54be6", "size": 27274, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils.hpp", "max_stars_repo_name": "cdslabamotong/CompetitiveCascade", "max_stars_repo_head_hexsha": "3bc6adcae936b159371534f6547339bfbe1f96cd", "max_stars_repo_licenses": ["MIT"], "max_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.hpp", "max_issues_repo_name": "cdslabamotong/CompetitiveCascade", "max_issues_repo_head_hexsha": "3bc6adcae936b159371534f6547339bfbe1f96cd", "max_issues_repo_licenses": ["MIT"], "max_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.hpp", "max_forks_repo_name": "cdslabamotong/CompetitiveCascade", "max_forks_repo_head_hexsha": "3bc6adcae936b159371534f6547339bfbe1f96cd", "max_forks_repo_licenses": ["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.5762195122, "max_line_length": 224, "alphanum_fraction": 0.5799296033, "num_tokens": 7131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.03161876578580389, "lm_q1q2_score": 0.013359075091606422}}
{"text": "//\n//=======================================================================\n// Copyright 2012 Fernando Vilas\n//           2010 Daniel Trebbien\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// The maximum adjacency search algorithm was originally part of the\n// Stoer-Wagner min cut implementation by Daniel Trebbien. It has been\n// broken out into its own file to be a public search algorithm, with\n// visitor concepts.\n#ifndef BOOST_GRAPH_MAXIMUM_ADJACENCY_SEARCH_H\n#define BOOST_GRAPH_MAXIMUM_ADJACENCY_SEARCH_H\n\n/**\n * This is an implementation of the maximum adjacency search on an\n * undirected graph. It allows a visitor object to perform some\n * operation on each vertex as that vertex is visited.\n *\n * The algorithm runs as follows:\n *\n * Initialize all nodes to be unvisited (reach count = 0)\n *   and call vis.initialize_vertex\n * For i = number of nodes in graph downto 1\n *   Select the unvisited node with the highest reach count\n *     The user provides the starting node to break the first tie,\n *     but future ties are broken arbitrarily\n *   Visit the node by calling vis.start_vertex\n *   Increment the reach count for all unvisited neighbors\n *     and call vis.examine_edge for each of these edges\n *   Mark the node as visited and call vis.finish_vertex\n *\n */\n\n#include <boost/concept_check.hpp>\n#include <boost/concept/assert.hpp>\n#include <boost/graph/buffer_concepts.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include <set>\n\nnamespace boost\n{\ntemplate < class Visitor, class Graph > struct MASVisitorConcept\n{\n    void constraints()\n    {\n        boost::function_requires<\n            boost::CopyConstructibleConcept< Visitor > >();\n        vis.initialize_vertex(u, g);\n        vis.start_vertex(u, g);\n        vis.examine_edge(e, g);\n        vis.finish_vertex(u, g);\n    }\n    Visitor vis;\n    Graph g;\n    typename boost::graph_traits< Graph >::vertex_descriptor u;\n    typename boost::graph_traits< Graph >::edge_descriptor e;\n};\n\ntemplate < class Visitors = null_visitor > class mas_visitor\n{\npublic:\n    mas_visitor() {}\n    mas_visitor(Visitors vis) : m_vis(vis) {}\n\n    template < class Vertex, class Graph >\n    void initialize_vertex(Vertex u, Graph& g)\n    {\n        invoke_visitors(m_vis, u, g, ::boost::on_initialize_vertex());\n    }\n\n    template < class Vertex, class Graph > void start_vertex(Vertex u, Graph& g)\n    {\n        invoke_visitors(m_vis, u, g, ::boost::on_start_vertex());\n    }\n\n    template < class Edge, class Graph > void examine_edge(Edge e, Graph& g)\n    {\n        invoke_visitors(m_vis, e, g, ::boost::on_examine_edge());\n    }\n\n    template < class Vertex, class Graph >\n    void finish_vertex(Vertex u, Graph& g)\n    {\n        invoke_visitors(m_vis, u, g, ::boost::on_finish_vertex());\n    }\n\n    BOOST_GRAPH_EVENT_STUB(on_initialize_vertex, mas)\n    BOOST_GRAPH_EVENT_STUB(on_start_vertex, mas)\n    BOOST_GRAPH_EVENT_STUB(on_examine_edge, mas)\n    BOOST_GRAPH_EVENT_STUB(on_finish_vertex, mas)\n\nprotected:\n    Visitors m_vis;\n};\ntemplate < class Visitors >\nmas_visitor< Visitors > make_mas_visitor(Visitors vis)\n{\n    return mas_visitor< Visitors >(vis);\n}\ntypedef mas_visitor<> default_mas_visitor;\n\nnamespace detail\n{\n    template < class Graph, class WeightMap, class MASVisitor,\n        class VertexAssignmentMap, class KeyedUpdatablePriorityQueue >\n    void maximum_adjacency_search(const Graph& g, WeightMap weights,\n        MASVisitor vis,\n        const typename boost::graph_traits< Graph >::vertex_descriptor start,\n        VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue pq)\n    {\n        typedef typename boost::graph_traits< Graph >::vertex_descriptor\n            vertex_descriptor;\n        typedef typename boost::property_traits< WeightMap >::value_type\n            weight_type;\n\n        std::set< vertex_descriptor > assignedVertices;\n\n        // initialize `assignments` (all vertices are initially\n        // assigned to themselves)\n        BGL_FORALL_VERTICES_T(v, g, Graph) { put(assignments, v, v); }\n\n        typename KeyedUpdatablePriorityQueue::key_map keys = pq.keys();\n\n        // set number of visited neighbors for all vertices to 0\n        BGL_FORALL_VERTICES_T(v, g, Graph)\n        {\n            if (v == get(assignments, v))\n            { // foreach u \\in V do\n                put(keys, v, weight_type(0));\n                vis.initialize_vertex(v, g);\n\n                pq.push(v);\n            }\n        }\n        BOOST_ASSERT(pq.size() >= 2);\n\n        // Give the starting vertex high priority\n        put(keys, start, get(keys, start) + num_vertices(g) + 1);\n        pq.update(start);\n\n        // start traversing the graph\n        // vertex_descriptor s, t;\n        // weight_type w;\n        while (!pq.empty())\n        { // while PQ \\neq {} do\n            const vertex_descriptor u = pq.top(); // u = extractmax(PQ)\n            /* weight_type w = */ get(keys, u);\n            vis.start_vertex(u, g);\n            pq.pop(); //            vis.start_vertex(u, g);\n\n            BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\n            { // foreach (u, v) \\in E do\n                vis.examine_edge(e, g);\n\n                const vertex_descriptor v = get(assignments, target(e, g));\n\n                if (pq.contains(v))\n                { // if v \\in PQ then\n                    put(keys, v,\n                        get(keys, v)\n                            + get(weights,\n                                e)); // increasekey(PQ, v, wA(v) + w(u, v))\n                    pq.update(v);\n                }\n            }\n\n            typename std::set< vertex_descriptor >::const_iterator\n                assignedVertexIt,\n                assignedVertexEnd = assignedVertices.end();\n            for (assignedVertexIt = assignedVertices.begin();\n                 assignedVertexIt != assignedVertexEnd; ++assignedVertexIt)\n            {\n                const vertex_descriptor uPrime = *assignedVertexIt;\n\n                if (get(assignments, uPrime) == u)\n                {\n                    BGL_FORALL_OUTEDGES_T(uPrime, e, g, Graph)\n                    { // foreach (u, v) \\in E do\n                        vis.examine_edge(e, g);\n\n                        const vertex_descriptor v\n                            = get(assignments, target(e, g));\n\n                        if (pq.contains(v))\n                        { // if v \\in PQ then\n                            put(keys, v,\n                                get(keys, v)\n                                    + get(weights, e)); // increasekey(PQ, v,\n                                                        // wA(v) + w(u, v))\n                            pq.update(v);\n                        }\n                    }\n                }\n            }\n            vis.finish_vertex(u, g);\n        }\n    }\n} // end namespace detail\n\ntemplate < class Graph, class WeightMap, class MASVisitor,\n    class VertexAssignmentMap, class KeyedUpdatablePriorityQueue >\nvoid maximum_adjacency_search(const Graph& g, WeightMap weights, MASVisitor vis,\n    const typename boost::graph_traits< Graph >::vertex_descriptor start,\n    VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue pq)\n{\n    BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept< Graph >));\n    BOOST_CONCEPT_ASSERT((boost::VertexListGraphConcept< Graph >));\n    typedef typename boost::graph_traits< Graph >::vertex_descriptor\n        vertex_descriptor;\n    typedef typename boost::graph_traits< Graph >::vertices_size_type\n        vertices_size_type;\n    typedef\n        typename boost::graph_traits< Graph >::edge_descriptor edge_descriptor;\n    BOOST_CONCEPT_ASSERT((boost::Convertible<\n        typename boost::graph_traits< Graph >::directed_category,\n        boost::undirected_tag >));\n    BOOST_CONCEPT_ASSERT(\n        (boost::ReadablePropertyMapConcept< WeightMap, edge_descriptor >));\n    // typedef typename boost::property_traits<WeightMap>::value_type\n    // weight_type;\n    boost::function_requires< MASVisitorConcept< MASVisitor, Graph > >();\n    BOOST_CONCEPT_ASSERT(\n        (boost::ReadWritePropertyMapConcept< VertexAssignmentMap,\n            vertex_descriptor >));\n    BOOST_CONCEPT_ASSERT((boost::Convertible< vertex_descriptor,\n        typename boost::property_traits< VertexAssignmentMap >::value_type >));\n    BOOST_CONCEPT_ASSERT(\n        (boost::KeyedUpdatableQueueConcept< KeyedUpdatablePriorityQueue >));\n\n    vertices_size_type n = num_vertices(g);\n    if (n < 2)\n        throw boost::bad_graph(\n            \"the input graph must have at least two vertices.\");\n    else if (!pq.empty())\n        throw std::invalid_argument(\n            \"the max-priority queue must be empty initially.\");\n\n    detail::maximum_adjacency_search(g, weights, vis, start, assignments, pq);\n}\n\nnamespace graph\n{\n    namespace detail\n    {\n        template < typename WeightMap > struct mas_dispatch\n        {\n            typedef void result_type;\n            template < typename Graph, typename ArgPack >\n            static result_type apply(const Graph& g,\n                // const bgl_named_params<P,T,R>& params,\n                const ArgPack& params, WeightMap w)\n            {\n\n                using namespace boost::graph::keywords;\n                typedef typename boost::graph_traits< Graph >::vertex_descriptor\n                    vertex_descriptor;\n                typedef typename WeightMap::value_type weight_type;\n\n                typedef boost::detail::make_priority_queue_from_arg_pack_gen<\n                    boost::graph::keywords::tag::max_priority_queue,\n                    weight_type, vertex_descriptor,\n                    std::greater< weight_type > >\n                    default_pq_gen_type;\n\n                default_pq_gen_type pq_gen(\n                    choose_param(get_param(params, boost::distance_zero_t()),\n                        weight_type(0)));\n\n                typename boost::result_of< default_pq_gen_type(\n                    const Graph&, const ArgPack&) >::type pq\n                    = pq_gen(g, params);\n\n                boost::null_visitor null_vis;\n                boost::mas_visitor< boost::null_visitor > default_visitor(\n                    null_vis);\n                vertex_descriptor v = vertex_descriptor();\n                boost::detail::make_property_map_from_arg_pack_gen<\n                    boost::graph::keywords::tag::vertex_assignment_map,\n                    vertex_descriptor >\n                    map_gen(v);\n                typename boost::detail::map_maker< Graph, ArgPack,\n                    boost::graph::keywords::tag::vertex_assignment_map,\n                    vertex_descriptor >::map_type default_map\n                    = map_gen(g, params);\n                boost::maximum_adjacency_search(g, w,\n                    params[_visitor | default_visitor],\n                    params[_root_vertex | *vertices(g).first],\n                    params[_vertex_assignment_map | default_map], pq);\n            }\n        };\n\n        template <> struct mas_dispatch< boost::param_not_found >\n        {\n            typedef void result_type;\n\n            template < typename Graph, typename ArgPack >\n            static result_type apply(\n                const Graph& g, const ArgPack& params, param_not_found)\n            {\n\n                using namespace boost::graph::keywords;\n                typedef typename boost::graph_traits< Graph >::vertex_descriptor\n                    vertex_descriptor;\n\n                // get edge_weight_t as the weight type\n                typedef typename boost::property_map< Graph, edge_weight_t >\n                    WeightMap;\n                typedef typename WeightMap::value_type weight_type;\n\n                typedef boost::detail::make_priority_queue_from_arg_pack_gen<\n                    boost::graph::keywords::tag::max_priority_queue,\n                    weight_type, vertex_descriptor,\n                    std::greater< weight_type > >\n                    default_pq_gen_type;\n\n                default_pq_gen_type pq_gen(\n                    choose_param(get_param(params, boost::distance_zero_t()),\n                        weight_type(0)));\n\n                typename boost::result_of< default_pq_gen_type(\n                    const Graph&, const ArgPack&) >::type pq\n                    = pq_gen(g, params);\n\n                boost::null_visitor null_vis;\n                boost::mas_visitor< boost::null_visitor > default_visitor(\n                    null_vis);\n                vertex_descriptor v = vertex_descriptor();\n                boost::detail::make_property_map_from_arg_pack_gen<\n                    boost::graph::keywords::tag::vertex_assignment_map,\n                    vertex_descriptor >\n                    map_gen(v);\n                typename boost::detail::map_maker< Graph, ArgPack,\n                    boost::graph::keywords::tag::vertex_assignment_map,\n                    vertex_descriptor >::map_type default_map\n                    = map_gen(g, params);\n                boost::maximum_adjacency_search(g, get(edge_weight, g),\n                    params[_visitor | default_visitor],\n                    params[_root_vertex | *vertices(g).first],\n                    params[_vertex_assignment_map | default_map], pq);\n            }\n        };\n    } // end namespace detail\n} // end namespace graph\n\n// Named parameter interface\n// BOOST_GRAPH_MAKE_OLD_STYLE_PARAMETER_FUNCTION(maximum_adjacency_search, 1)\ntemplate < typename Graph, typename P, typename T, typename R >\nvoid maximum_adjacency_search(\n    const Graph& g, const bgl_named_params< P, T, R >& params)\n{\n\n    typedef bgl_named_params< P, T, R > params_type;\n    BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)\n\n    // do the dispatch based on WeightMap\n    typedef typename get_param_type< edge_weight_t,\n        bgl_named_params< P, T, R > >::type W;\n    graph::detail::mas_dispatch< W >::apply(\n        g, arg_pack, get_param(params, edge_weight));\n}\n\nnamespace graph\n{\n    namespace detail\n    {\n        template < typename Graph > struct maximum_adjacency_search_impl\n        {\n            typedef void result_type;\n\n            template < typename ArgPack >\n            void operator()(const Graph& g, const ArgPack& arg_pack) const\n            {\n                // call the function that does the dispatching\n                typedef\n                    typename get_param_type< edge_weight_t, ArgPack >::type W;\n                graph::detail::mas_dispatch< W >::apply(\n                    g, arg_pack, get_param(arg_pack, edge_weight));\n            }\n        };\n    } // end namespace detail\n    BOOST_GRAPH_MAKE_FORWARDING_FUNCTION(maximum_adjacency_search, 1, 5)\n} // end namespace graph\n\n} // end namespace boost\n\n#include <boost/graph/iteration_macros_undef.hpp>\n\n#endif // BOOST_GRAPH_MAXIMUM_ADJACENCY_SEARCH_H\n", "meta": {"hexsha": "ed4b5578d1e4da2a67627590045700c278c37153", "size": 15125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/maximum_adjacency_search.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/maximum_adjacency_search.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/maximum_adjacency_search.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": 37.8125, "max_line_length": 80, "alphanum_fraction": 0.597553719, "num_tokens": 3085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.039048290909008194, "lm_q1q2_score": 0.013338212284038826}}
{"text": "/**\n * @Author: Maxime Agor (4rzael)\n * @Date:   Sat Aug 18 2018\n * @Email:  maxime.agor23@gmail.com\n * @Project: CUDA-Based Simulator of Quantum Systems\n * @Filename: BasicMeasurementResultsTree.cpp\n * @Last modified by:   4rzael\n * @Last modified time: Sat Aug 18 2018, 23:36:59\n * @License: MIT License\n */\n\n#include <exception>\n#include <optional>\n#include <limits>\n#include <boost/optional.hpp>\n#include \"TaskScheduling/BasicMeasurementResultsTree.hpp\"\n#include \"utils.hpp\"\n#include \"Logger.hpp\"\n\nusing namespace MeasurementResultsTree;\n\nBasicMeasurementResultsTree::BasicMeasurementResultsTree(uint samples): greatestId(MEASUREMENT_NODE_NONE) {\n    root = std::make_shared<MeasurementResultsNode>(this, ++greatestId);\n    root->samples = samples;\n}\n\nstd::shared_ptr<MeasurementResultsNode> BasicMeasurementResultsTree::getRoot() const {\n    return root;\n}\nstd::shared_ptr<MeasurementResultsNode> BasicMeasurementResultsTree::getNodeWithId(NodeId id) const {\n    // Making a recursive helper function\n    const std::function<std::shared_ptr<MeasurementResultsNode>(std::shared_ptr<MeasurementResultsNode>)> helper = \n    [&](std::shared_ptr<MeasurementResultsNode> currentNode) {\n        if (!currentNode) return std::shared_ptr<MeasurementResultsNode>(); // if not a node, abort\n        if (currentNode->id == id) return currentNode; // if found, return self\n        std::shared_ptr<MeasurementResultsNode> res;\n        // try child 0\n        res = helper(currentNode->results[0].node); \n        if (res) return res;\n        // if didn't work, try child 1\n        return helper(currentNode->results[1].node);\n    };\n    // Run the recursive helper from the root node\n    const auto res = helper(root);\n    if (!res) throw std::logic_error(\"Measurement Node not found\");\n    return res;\n}\n\nuint BasicMeasurementResultsTree::getCregValueAtNode(std::string cregName, NodeId id) const {\n    // Making a recursive helper function\n    const std::function<boost::optional<uint>(uint, std::shared_ptr<MeasurementResultsNode>)> helper =\n    [&](uint currentValue, std::shared_ptr<MeasurementResultsNode> node) -> boost::optional<uint> {\n        if (!node) return boost::none; // if not a node, abort\n        if (node->id == id) return currentValue; // if node is self, return the currentValue\n        //try child 0\n        boost::optional<uint> res;\n        res = helper(\n            (node->results[0].measuredCBit.registerName != cregName) // if the current node modifies the good creg, apply modification\n            ? currentValue\n            : (currentValue & (std::numeric_limits<int>::max() - (1 << node->results[0].measuredCBit.element))), // set bit to 0\n            node->results[0].node\n        );\n        if (res) return res;\n        // if didn't work, try child 1\n        return helper(\n            (node->results[1].measuredCBit.registerName != cregName) // if the current node modifies the good creg, apply modification\n            ? currentValue\n            : (currentValue | ((1 << node->results[1].measuredCBit.element))),  // set bit to 1\n            node->results[1].node\n        );\n    };\n    // Run the recursive helper from the root node\n    const auto res = helper(0, root);\n    if (!res) throw std::logic_error(\"Measurement Node not found\");\n    return res.value();\n}\n\n\nstd::vector<std::shared_ptr<MeasurementResultsNode>> BasicMeasurementResultsTree::makeChildrens(NodeId parentId, Circuit::Qubit creg) {\n    auto parent = getNodeWithId(parentId);\n    parent->results[0].node = std::make_shared<MeasurementResultsNode>(this, ++greatestId);\n    parent->results[0].measuredCBit = creg;\n    parent->results[0].value = 0;\n    parent->results[0].probability = 0;\n    parent->results[0].node->samples = 0;\n    parent->results[1].node = std::make_shared<MeasurementResultsNode>(this, ++greatestId);\n    parent->results[1].measuredCBit = creg;\n    parent->results[1].value = 1;\n    parent->results[1].probability = 0;\n    parent->results[1].node->samples = 0;\n    return {parent->results[0].node, parent->results[1].node};\n}\n\nstd::vector<NodeId> BasicMeasurementResultsTree::addMeasurement(NodeId nodeId, double zeroProbability) {\n    auto node = getNodeWithId(nodeId);\n    auto zeroSamples = sampleBinomialDistribution(node->samples, zeroProbability);\n    node->results[0].probability = zeroProbability;\n    node->results[0].node->samples = zeroSamples;\n\n    node->results[1].probability = 1 - zeroProbability;\n    node->results[1].node->samples = node->samples - zeroSamples;\n\n    node->status = MeasurementResultsNodeStatus::COMPLETE;\n    return {node->results[0].node->id, node->results[1].node->id};\n}\n\nvoid BasicMeasurementResultsTree::printResults(std::vector<Circuit::Register> const &cregs) const {\n    LOG(Logger::INFO, \"Sampled \" << getRoot()->samples << \" executions\");\n\n    const std::function<void(std::shared_ptr<MeasurementResultsNode> const &)> helper = [&](std::shared_ptr<MeasurementResultsNode> const &node) {\n        // no childrens => we can print the results for this node\n        if (!(node->results[0].node)) {\n            if (node->samples == 0) return;\n            LOG(Logger::INFO, \"On \" << node->samples << \" samples:\");\n            for (auto const &reg : cregs) {\n                const auto value = getCregValueAtNode(reg.name, node->id);\n                LOG(Logger::INFO, reg.name << \" = \" << value);\n            }\n        } else {\n            helper(node->results[0].node);\n            helper(node->results[1].node);\n        }\n    };\n\n    helper(getRoot());\n}", "meta": {"hexsha": "4a0dcd22ca21ed00a70100fe0952aff22171ce5d", "size": 5505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TaskScheduling/BasicMeasurementResultsTree.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/TaskScheduling/BasicMeasurementResultsTree.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/TaskScheduling/BasicMeasurementResultsTree.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": 43.6904761905, "max_line_length": 146, "alphanum_fraction": 0.6683015441, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208213138121609, "lm_q2_score": 0.041462269898368875, "lm_q1q2_score": 0.013301979902429113}}
{"text": "/*\n * Copyright (c) 2011-2022, 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_CONSTRAINT_BOXEDLCPSOLVER_HPP_\n#define DART_CONSTRAINT_BOXEDLCPSOLVER_HPP_\n\n#include <string>\n\n#include <Eigen/Core>\n\n#include \"dart/common/Castable.hpp\"\n\nnamespace dart {\nnamespace constraint {\n\nclass BoxedLcpSolver : public common::Castable<BoxedLcpSolver>\n{\npublic:\n  /// Destructor\n  virtual ~BoxedLcpSolver() = default;\n\n  /// Returns the type\n  virtual const std::string& getType() const = 0;\n\n  /// Solves constriant impulses for a constrained group. The LCP formulation\n  /// setting that this function solve is A*x = b + w where each x[i], w[i]\n  /// satisfies one of\n  ///   (1) x = lo, w >= 0\n  ///   (2) x = hi, w <= 0\n  ///   (3) lo < x < hi, w = 0\n  ///\n  /// \\param[in] n Dimension of constraints.\n  /// \\param[in] A A term of the LCP formulation.\n  /// \\param[in] x x term of the LCP formulation.\n  /// \\param[in] b b term of the LCP formulation.\n  /// \\param[in] nub Number of the first unbounded constraints.\n  /// \\param[in] lo Lower bound of x where it's restricted to be lo <= 0.\n  /// \\param[in] hi Upper bound of x where it's enforced to be hi >= 0.\n  /// \\param[in] findex Indices to corresponding normal contact constraint. Set\n  /// the index to itself (e.g., findex[k] = k) for normal contacts or\n  /// non-contact constraints. For friction constraint, set the cooresponding\n  /// normal contact constraint.\n  /// \\param[in] earlyTermination Set true to return false as soon as the solver\n  /// find the solution doesn't exist. Otherwise, the solver will continue to\n  /// push hard to solve the problem using some hacks.\n  ///\n  /// \\return Success.\n  // Note: The function signature is ODE specific for now. Consider changing\n  // this to Eigen friendly version once own Dantzig LCP solver is available.\n  virtual bool solve(\n      int n,\n      double* A,\n      double* x,\n      double* b,\n      int nub,\n      double* lo,\n      double* hi,\n      int* findex,\n      bool earlyTermination = false)\n      = 0;\n\n#ifndef NDEBUG\n  virtual bool canSolve(int n, const double* A) = 0;\n#endif\n};\n\n} // namespace constraint\n} // namespace dart\n\n#endif // DART_CONSTRAINT_BOXEDLCPSOLVER_HPP_\n", "meta": {"hexsha": "e79822ee7944d1b9406f42bb0fa8907012dbc108", "size": 3740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/constraint/BoxedLcpSolver.hpp", "max_stars_repo_name": "ibrahiminfinite/dart", "max_stars_repo_head_hexsha": "495c82120c836005f2d136d4a50c8cc997fb879b", "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/constraint/BoxedLcpSolver.hpp", "max_issues_repo_name": "ibrahiminfinite/dart", "max_issues_repo_head_hexsha": "495c82120c836005f2d136d4a50c8cc997fb879b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/constraint/BoxedLcpSolver.hpp", "max_forks_repo_name": "ibrahiminfinite/dart", "max_forks_repo_head_hexsha": "495c82120c836005f2d136d4a50c8cc997fb879b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4, "max_line_length": 80, "alphanum_fraction": 0.7016042781, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.029312229691398597, "lm_q1q2_score": 0.013286115399374798}}
{"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#include \"votca/xtp/orbitals.h\"\n#include \"votca/tools/globals.h\"\n#include \"votca/xtp/elements.h\"\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <map>\n#include <iterator>\n#include <numeric>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n\n\nnamespace votca {\n    namespace xtp {\n\n       \n\n        Orbitals::Orbitals() {\n\n            _basis_set_size = 0;\n            _occupied_levels = 0;\n            _unoccupied_levels = 0;\n            _number_of_electrons = 0;\n            _self_energy = 0.0;\n            _qm_energy = 0.0;\n            _couplingsA = 0;\n            _couplingsB = 0;\n            _ECP = \"\";\n            _bsetype=\"\";\n            //_has_atoms = false;\n\n\n            // GW-BSE\n            _qpmin = 0;\n            _qpmax = 0;\n            _qptotal = 0;\n\n            _rpamin = 0;\n            _rpamax = 0;\n\n            _ScaHFX = 0.0;\n\n            _bse_cmin = 0;\n            _bse_cmax = 0;\n            _bse_vmin = 0;\n            _bse_vmax = 0;\n            _bse_vtotal = 0;\n            _bse_ctotal = 0;\n            _bse_size = 0;\n            _bse_nmax = 0;\n\n        };\n\n        Orbitals::~Orbitals() {\n            _mo_energies.clear();\n            _mo_coefficients.clear();\n            _overlap.clear();\n\n            std::vector< ctp::QMAtom* >::iterator it;\n            for (it = _atoms.begin(); it != _atoms.end(); ++it) delete *it;\n\n        };\n\n        \n\n        void Orbitals::setNumberOfLevels(const int &occupied_levels, const int &unoccupied_levels) {\n            // _has_occupied_levels = true; \n            // _has_unoccupied_levels = true; \n            _occupied_levels = occupied_levels;\n            _unoccupied_levels = unoccupied_levels;\n        }\n      \n\n        /**\n         * \n         * @param _energy_difference [ev] Two levels are degenerate if their energy is smaller than this value\n         * @return A map with key as a level and a vector which is a list of close lying orbitals\n         */\n        bool Orbitals::CheckDegeneracy(double _energy_difference) {\n\n            ub::vector<double>::iterator it1 = _mo_energies.begin();\n            bool _degenerate = false;\n\n            if (tools::globals::verbose) {\n                cout << endl << \"... ... Checking level degeneracy \" << endl;\n            }\n\n            _level_degeneracy.clear();\n\n            while (it1 != _mo_energies.end()) {\n\n                // in all containers counters start with 0; real life - with 1\n                int _level1 = std::distance(_mo_energies.begin(), it1) + 1;\n\n                // add the level itself - it is easier to loo over all levels later\n                _level_degeneracy[_level1].push_back(_level1);\n\n                ub::vector<double>::iterator it2 = it1;\n                it2++;\n\n                while (it2 != _mo_energies.end()) {\n                    //cout << _level1 << \":\" << *it1 << \":\" << *it2 << endl;\n                    double energy1 = *it1;\n                    double energy2 = *it2;\n\n                    // in all containers counters start with 0; real life - with 1\n                    int _level2 = std::distance(_mo_energies.begin(), it2) + 1;\n\n                    if (std::abs(energy1 - energy2) * tools::conv::hrt2ev < _energy_difference) {\n                        _level_degeneracy[_level1].push_back(_level2);\n                        _level_degeneracy[_level2].push_back(_level1);\n                        _degenerate = true;\n                    }\n                    it2++;\n                }\n                it1++;\n            }\n\n            if (tools::globals::verbose) {\n\n                if (_degenerate) {\n                    cout << \"... ... Some levels are degenerate\" << endl;\n                    for (std::map<int, std::vector<int> >::iterator it = _level_degeneracy.begin();\n                            it != _level_degeneracy.end();\n                            ++it) {\n                        // output only degenerate levels\n                        if ((it->second).size() > 1) {\n                            std::cout << \"... ... level  \" << it->first << \" : \";\n                            for (vector<int>::iterator lev = (it->second).begin(); lev != (it->second).end(); lev++)\n                                cout << *lev << \" \";\n                            cout << endl;\n                        }\n                    }\n                } else {\n                    cout << \"... ... No degeneracy found\" << endl;\n                }\n                cout << \"... ... Done checking level degeneracy\" << endl;\n            }\n            return _degenerate;\n        }\n\n        std::vector<int>* Orbitals::getDegeneracy(int level, double _energy_difference) {\n            if (!hasDegeneracy()) {\n                CheckDegeneracy(_energy_difference);\n            }\n\n            return &_level_degeneracy.at(level);\n        }\n\n        std::vector<int> Orbitals::SortEnergies() {\n            if (tools::globals::verbose) cout << \"... ... Sorting energies\" << endl;\n            std::vector<int>index=std::vector<int>(_mo_energies.size());\n            std::iota(index.begin(), index.end(), 0);\n            std::stable_sort(index.begin(), index.end(),[this](int i1, int i2) {return this->MOEnergies()[i1] > this->MOEnergies()[i2];});\n            return index;\n        }\n\n        /// Writes a PDB file\n\n        void Orbitals::WritePDB(FILE *out, string tag) {\n            string tag_extended = \"HEADER ! GENERATED BY VOTCA::XTP::\" + tag + \"\\n\";\n            fprintf(out, \"%s\", tag_extended.c_str());\n            vector < ctp::QMAtom* > ::iterator atom;\n            int id = 0;\n\n\n            for (atom = _atoms.begin(); atom < _atoms.end(); ++atom) {\n                id++;\n                string resname = ((*atom)->from_environment) ? \"MM\" : \"QM\";\n                int resnr = 1;\n\n                fprintf(out, \"ATOM  %5d %4s%1s%3s %1s%4d%1s   %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s  %8.3f\\n\",\n                        id, // Atom serial number           %5d \n                        (*atom)->type.c_str(), // Atom name                    %4s\n                        \" \", // alternate location indicator.%1s\n                        resname.c_str(), // Residue name.                %3s\n                        \"A\", // Chain identifier             %1s\n                        resnr, // Residue sequence number      %4d\n                        \" \", // Insertion of residues.       %1s\n                        (*atom)->x, // X in Angstroms               %8.3f\n                        (*atom)->y, // Y in Angstroms               %8.3f\n                        (*atom)->z, // Z in Angstroms               %8.3f\n                        1.0, // Occupancy                    %6.2f\n                        0.0, // Temperature factor           %6.2f\n                        \" \", // Segment identifier           %4s\n                        (*atom)->type.c_str(), // Element symbol               %2s\n                        (*atom)->charge // Charge on the atom.          %2s\n                        );\n            }\n            return;\n        }\n\n        // reduces the number of virtual orbitals to factor*number_of_occupied_orbitals\n\n        void Orbitals::Trim(int factor) {\n\n            if (hasMOCoefficients()) {\n                _mo_coefficients.resize(factor * _occupied_levels, _basis_set_size, true);\n                _unoccupied_levels = (factor - 1) * _occupied_levels;\n            }\n\n            if (hasMOEnergies()) {\n                _mo_energies.resize(factor * _occupied_levels, true);\n                _unoccupied_levels = (factor - 1) * _occupied_levels;\n            }\n            return;\n        }\n\n\n        // reduces the number of orbitals to [HOMO-degH:LUMO+degL]\n\n        void Orbitals::Trim(int degH, int degL) {\n\n            if (hasMOCoefficients()) {\n                _mo_coefficients = ub::project(_mo_coefficients, ub::range(_occupied_levels - degH, _occupied_levels + degL), ub::range(0, _basis_set_size));\n            }\n\n            if (hasMOEnergies()) {\n                ub::vector<double> _temp(degH + degL);\n                for (int i = 0; i < degH + degL; i++) {\n                    _temp(i) = _mo_energies(_occupied_levels - degH + i);\n                }\n                _mo_energies = _temp;\n            }\n            _occupied_levels = degH;\n            _unoccupied_levels = degL;\n\n            return;\n        }\n\n        bool Orbitals::Load(string file_name) {\n            try {\n                std::ifstream ifs(file_name.c_str());\n                boost::archive::binary_iarchive ia(ifs);\n                ia >> *this;\n                ifs.close();\n            } catch (std::exception &err) {\n                std::cerr << \"Could not load orbitals from \" << file_name << flush;\n                std::cerr << \"An error occurred:\\n\" << err.what() << endl;\n                return false;\n            }\n            return true;\n        }\n\n        /* Save to archive */\n        bool Orbitals::Save(std::string file_name) {\n\n            try {\n                std::ofstream ofs((file_name).c_str());\n                boost::archive::binary_oarchive oa(ofs);\n                oa << *this;\n                ofs.close();\n            } catch (std::exception &err) {\n                std::cerr << \"Could not save orbitals to \" << file_name << flush;\n                std::cerr << \"An error occurred:\\n\" << err.what() << endl;\n                return false;\n            }\n            return true;\n        }\n\n\n\n\n        // Determine ground state density matrix\n\n        ub::matrix<double> Orbitals::DensityMatrixGroundState() {\n            ub::matrix<double> dmatGS = ub::zero_matrix<double>(_basis_set_size, _basis_set_size);\n#pragma omp parallel for\n            for (int _i = 0; _i < _basis_set_size; _i++) {\n                for (int _j = 0; _j < _basis_set_size; _j++) {\n                    for (int _level = 0; _level < _occupied_levels; _level++) {\n\n                        dmatGS(_i, _j) += 2.0 * _mo_coefficients(_level, _i) * _mo_coefficients(_level, _j);\n\n                    }\n                }\n            }\n            return dmatGS;\n        }\n        \n        // Determine QuasiParticle Density Matrix\n        ub::matrix<double> Orbitals::DensityMatrixQuasiParticle( int state){\n            ub::matrix<double> dmatQP = ub::zero_matrix<double>(_basis_set_size, _basis_set_size);\n            //ub::matrix<double> _mos = ub::project(_mo_coefficients, ub::range(_qpmin, _qpmax + 1), ub::range(0, _basis_set_size));\n\n            //ub::matrix<real_gwbse> lambda = ub::prod(_QPdiag_coefficients,_mos);\n\n            ub::matrix<double> lambda = LambdaMatrixQuasiParticle();\n            \n            #pragma omp parallel for\n            for (int _i = 0; _i < _basis_set_size; _i++) {\n                for (int _j = 0; _j < _basis_set_size; _j++) {\n                    dmatQP(_i,_j) = lambda(state,_i)*lambda(state,_j);\n                }\n            }\n            \n            return dmatQP;\n        }\n        \n        \n        // Determine QuasiParticle Lambda Matrix\n        ub::matrix<double> Orbitals::LambdaMatrixQuasiParticle(){\n            ub::matrix<double> _mos = ub::project(_mo_coefficients, ub::range(_qpmin, _qpmax + 1), ub::range(0, _basis_set_size));\n            ub::matrix<double> lambda = ub::prod(_QPdiag_coefficients,_mos);          \n            return lambda;\n        }\n        \n\n        ub::matrix<double> Orbitals::TransitionDensityMatrix(const string& spin, int state) {\n            if(!(spin==\"singlet\" || spin==\"triplet\")){\n                throw runtime_error(\"Spin type not known for density matrix. Available are singlet and triplet\");\n            }\n            ub::matrix<real_gwbse>& _BSECoefs = (spin==\"singlet\") ? _BSE_singlet_coefficients : _BSE_triplet_coefficients;\n            \n            ub::matrix<double> dmatTS = ub::zero_matrix<double>(_basis_set_size);\n            // The Transition dipole is sqrt2 bigger because of the spin, the excited state is a linear combination of 2 slater determinants, where either alpha or beta spin electron is excited\n            double sqrt2 = sqrt(2.0);\n            /*Trying to implement D_{alpha,beta}= sqrt2*sum_{i}^{occ}sum_{j}^{virt}{BSEcoef(i,j)*MOcoef(alpha,i)*MOcoef(beta,j)} */\n            // c stands for conduction band and thus virtual orbitals\n            // v stand for valence band and thus occupied orbitals\n\n            if (_bse_size == 0) {\n                _bse_vtotal = _bse_vmax - _bse_vmin + 1;\n                _bse_ctotal = _bse_cmax - _bse_cmin + 1;\n                _bse_size = _bse_vtotal * _bse_ctotal;\n                // indexing info BSE vector index to occupied/virtual orbital\n                for (unsigned _v = 0; _v < _bse_vtotal; _v++) {\n                    for (unsigned _c = 0; _c < _bse_ctotal; _c++) {\n                        _index2v.push_back(_bse_vmin + _v);\n                        _index2c.push_back(_bse_cmin + _c);\n                    }\n                }\n            }\n            if (_bsetype == \"full\" && spin == \"singlet\") {\n                const ub::matrix<real_gwbse>& _BSECoefs_AR=_BSE_singlet_coefficients_AR;\n#pragma omp parallel for\n                for (unsigned a = 0; a < dmatTS.size1(); a++) {\n                    for (unsigned b = 0; b < dmatTS.size2(); b++) {\n                        for (unsigned i = 0; i < _bse_size; i++) {\n                            int occ = _index2v[i];\n                            int virt = _index2c[i];\n                            dmatTS(a, b) += sqrt2 * (_BSECoefs(i, state) + _BSECoefs_AR(i, state)) * _mo_coefficients(occ, a) * _mo_coefficients(virt, b); //check factor 2??\n                        }\n                    }\n                }\n            } else {\n\n#pragma omp parallel for\n                for (unsigned a = 0; a < dmatTS.size1(); a++) {\n                    for (unsigned b = 0; b < dmatTS.size2(); b++) {\n                        for (unsigned i = 0; i < _bse_size; i++) {\n                            int occ = _index2v[i];\n                            int virt = _index2c[i];\n                            dmatTS(a, b) += sqrt2 * _BSECoefs(i, state) * _mo_coefficients(occ, a) * _mo_coefficients(virt, b); //check factor 2??\n                        }\n                    }\n                }\n\n            }\n            return dmatTS;\n        }\n\n      \n\n        std::vector<ub::matrix<double> > Orbitals::DensityMatrixExcitedState(const string& spin,int state) {\n            \n            \n            std::vector<ub::matrix<double> > dmat = DensityMatrixExcitedState_R(spin,state);\n            if(_bsetype==\"full\" && spin==\"singlet\"){\n                std::vector<ub::matrix<double> > dmat_AR = DensityMatrixExcitedState_AR(spin, state);\n                dmat[0] -= dmat_AR[0];\n                dmat[1] -= dmat_AR[1];\n            }\n            return dmat;\n        }\n\n        // Excited state density matrix\n\n        std::vector<ub::matrix<double> > Orbitals::DensityMatrixExcitedState_R(const string& spin, int state) {\n            if(!(spin==\"singlet\" || spin==\"triplet\")){\n                throw runtime_error(\"Spin type not known for density matrix. Available are singlet and triplet\");\n            }\n            \n            ub::matrix<real_gwbse>& _BSECoefs = (spin==\"singlet\") ? _BSE_singlet_coefficients : _BSE_triplet_coefficients;\n           \n            /****** \n             * \n             *    Density matrix for GW-BSE based excitations\n             * \n             *    - electron contribution\n             *      D_ab = \\sum{vc} \\sum{c'} A_{vc}A_{vc'} mo_a(c)mo_b(c')\n             * \n             *    - hole contribution \n             *      D_ab = \\sum{vc} \\sum{v'} A_{vc}A_{v'c} mo_a(v)mo_b(v')\n             * \n             * \n             *   more efficient:\n             * \n             *   - electron contribution\n             *      D_ab = \\sum{c} \\sum{c'} mo_a(c)mo_b(c') [ \\sum{v} A_{vc}A_{vc'} ]\n             *           = \\sum{c} \\sum{c'} mo_a(c)mo_b(c') A_{cc'} \n             *    \n             *   - hole contribution\n             *      D_ab = \\sum{v} \\sum{v'} mo_a(v)mo_b(v') [ \\sum{c} A_{vc}A_{v'c} ]\n             *           = \\sum{v} \\sum{v'} mo_a(v)mo_b(v') A_{vv'} \n             *  \n             */\n            std::vector<ub::matrix<double> > dmatEX;\n            dmatEX.resize(2);\n            dmatEX[0] = ub::zero_matrix<double>(_basis_set_size, _basis_set_size);\n            dmatEX[1] = ub::zero_matrix<double>(_basis_set_size, _basis_set_size);\n\n            int _vmin = this->_bse_vmin;\n            int _vmax = this->_bse_vmax;\n            int _cmin = this->_bse_cmin;\n            int _cmax = this->_bse_cmax;\n\n            if (_bse_size == 0) {\n                _bse_vtotal = _bse_vmax - _bse_vmin + 1;\n                _bse_ctotal = _bse_cmax - _bse_cmin + 1;\n                _bse_size = _bse_vtotal * _bse_ctotal;\n                // indexing info BSE vector index to occupied/virtual orbital\n                for (unsigned _v = 0; _v < _bse_vtotal; _v++) {\n                    for (unsigned _c = 0; _c < _bse_ctotal; _c++) {\n                        _index2v.push_back(_bse_vmin + _v);\n                        _index2c.push_back(_bse_cmin + _c);\n                    }\n                }\n            }\n\n            // electron assist matrix A_{cc'}\n            ub::matrix<real_gwbse> _Acc = ub::zero_matrix<real_gwbse>(_bse_ctotal, _bse_ctotal);\n            ub::matrix<real_gwbse> _Avv = ub::zero_matrix<real_gwbse>(_bse_vtotal, _bse_vtotal);\n\n            for (unsigned _idx1 = 0; _idx1 < _bse_size; _idx1++) {\n\n                int _v = this->_index2v[_idx1];\n                int _c = this->_index2c[_idx1];\n\n                // electron assist matrix A_{cc'}\n#pragma omp parallel for\n                for (int _c2 = _cmin; _c2 <= _cmax; _c2++) {\n                    int _idx2 = (_cmax - _cmin + 1)*(_v - _vmin)+(_c2 - _cmin);\n\n                    _Acc(_c - _cmin, _c2 - _cmin) += _BSECoefs(_idx1, state) * _BSECoefs(_idx2, state);\n                }\n\n                // hole assist matrix A_{vv'}\n#pragma omp parallel for\n                for (int _v2 = _vmin; _v2 <= _vmax; _v2++) {\n                    int _idx2 = (_cmax - _cmin + 1)*(_v2 - _vmin)+(_c - _cmin);\n\n                    _Avv(_v - _vmin, _v2 - _vmin) += _BSECoefs(_idx1, state) * _BSECoefs(_idx2, state);\n\n                }\n\n            }\n\n            // hole part as matrix products\n            // get slice of MOs of occs only\n            ub::matrix<double> _occlevels = ub::project(_mo_coefficients, ub::range(_vmin, _vmax + 1), ub::range(0, _basis_set_size));\n            ub::matrix<double> _temp = ub::prod(_Avv, _occlevels);\n            dmatEX[0] = ub::prod(ub::trans(_occlevels), _temp);\n\n\n            // electron part as matrix products\n            // get slice of MOs of virts only\n            ub::matrix<double> _virtlevels = ub::project(_mo_coefficients, ub::range(_cmin, _cmax + 1), ub::range(0, _basis_set_size));\n            _temp = ub::prod(_Acc, _virtlevels);\n            dmatEX[1] = ub::prod(ub::trans(_virtlevels), _temp);\n\n            return dmatEX;\n        }\n\n        // Excited state density matrix\n\n        std::vector<ub::matrix<double> > Orbitals::DensityMatrixExcitedState_AR(const string& spin, int state) {\n             if(!(spin==\"singlet\" )){\n                throw runtime_error(\"Spin type not known for density matrix. Available is singlet\");\n            }\n            \n            ub::matrix<real_gwbse>& _BSECoefs_AR = _BSE_singlet_coefficients_AR;\n\n            /****** \n             * \n             *    Density matrix for GW-BSE based excitations\n             * \n             *    - electron contribution\n             *      D_ab = \\sum{vc} \\sum{v'} B_{vc}B_{v'c} mo_a(v)mo_b(v')\n             * \n             *    - hole contribution \n             *      D_ab = \\sum{vc} \\sum{c'} B_{vc}B_{vc'} mo_a(c)mo_b(c')\n             * \n             * \n             *   more efficient:\n             * \n             *   - electron contribution\n             *      D_ab = \\sum{v} \\sum{v'} mo_a(v)mo_b(v') [ \\sum{c} B_{vc}B_{v'c} ]\n             *           = \\sum{v} \\sum{v'} mo_a(v)mo_b(v') B_{vv'} \n             *    \n             *   - hole contribution\n             *      D_ab = \\sum{c} \\sum{c'} mo_a(c)mo_b(c') [ \\sum{v} B_{vc}B_{vc'} ]\n             *           = \\sum{c} \\sum{c'} mo_a(c)mo_b(c') B_{cc'} \n             *  \n             */\n            std::vector<ub::matrix<double> > dmatAR;\n            dmatAR.resize(2);\n            dmatAR[0] = ub::zero_matrix<double>(_basis_set_size, _basis_set_size);\n            dmatAR[1] = ub::zero_matrix<double>(_basis_set_size, _basis_set_size);\n\n            int _vmin = this->_bse_vmin;\n            int _vmax = this->_bse_vmax;\n            int _cmin = this->_bse_cmin;\n            int _cmax = this->_bse_cmax;\n\n            if (_bse_size == 0) {\n                _bse_vtotal = _bse_vmax - _bse_vmin + 1;\n                _bse_ctotal = _bse_cmax - _bse_cmin + 1;\n                _bse_size = _bse_vtotal * _bse_ctotal;\n                // indexing info BSE vector index to occupied/virtual orbital\n                for (unsigned _v = 0; _v < _bse_vtotal; _v++) {\n                    for (unsigned _c = 0; _c < _bse_ctotal; _c++) {\n                        _index2v.push_back(_bse_vmin + _v);\n                        _index2c.push_back(_bse_cmin + _c);\n                    }\n                }\n            }\n\n            // hole assist matrix B_{cc'}\n            ub::matrix<real_gwbse> _Bcc = ub::zero_matrix<real_gwbse>(_bse_ctotal, _bse_ctotal);\n            ub::matrix<real_gwbse> _Bvv = ub::zero_matrix<real_gwbse>(_bse_vtotal, _bse_vtotal);\n\n            for (unsigned _idx1 = 0; _idx1 < _bse_size; _idx1++) {\n\n                int _v = this->_index2v[_idx1];\n                int _c = this->_index2c[_idx1];\n\n                // hole assist matrix B_{cc'}\n#pragma omp parallel for\n                for (int _c2 = _cmin; _c2 <= _cmax; _c2++) {\n                    int _idx2 = (_cmax - _cmin + 1)*(_v - _vmin)+(_c2 - _cmin);\n\n                    _Bcc(_c - _cmin, _c2 - _cmin) += _BSECoefs_AR(_idx1, state) * _BSECoefs_AR(_idx2, state);\n                }\n\n                // electron assist matrix B_{vv'}\n#pragma omp parallel for\n                for (int _v2 = _vmin; _v2 <= _vmax; _v2++) {\n                    int _idx2 = (_cmax - _cmin + 1)*(_v2 - _vmin)+(_c - _cmin);\n\n                    _Bvv(_v - _vmin, _v2 - _vmin) += _BSECoefs_AR(_idx1, state) * _BSECoefs_AR(_idx2, state);\n\n                }\n            }\n\n            //hole part as matrix products\n            // get slice of MOs of virts only\n            ub::matrix<double> _virtlevels = ub::project(_mo_coefficients, ub::range(_cmin, _cmax + 1), ub::range(0, _basis_set_size));\n            ub::matrix<double> _temp = ub::prod(_Bcc, _virtlevels);\n            dmatAR[0] = ub::prod(ub::trans(_virtlevels), _temp);\n\n            // electron part as matrix products\n            // get slice of MOs of occs only\n            ub::matrix<double> _occlevels = ub::project(_mo_coefficients, ub::range(_vmin, _vmax + 1), ub::range(0, _basis_set_size));\n            _temp = ub::prod(_Bvv, _occlevels);\n            dmatAR[1] = ub::prod(ub::trans(_occlevels), _temp);\n\n            return dmatAR;\n        }\n\n        ub::vector<double> Orbitals::LoewdinPopulation(const ub::matrix<double>& _densitymatrix, const ub::matrix<double>& _overlapmatrix, int _frag) {\n\n            ub::vector<double> fragmentCharges = ub::vector<double>(2, 0.0);\n            ub::matrix<double> overlap = _overlapmatrix;\n\n\n            linalg_matrixsqrt(overlap);\n            ub::matrix<double> temp = ub::prod(_densitymatrix, overlap);\n            ub::matrix<double> _prodmat = ub::prod(overlap, temp);\n            for (int _i = 0; _i < _frag; _i++) {\n                fragmentCharges(0) += _prodmat(_i, _i);\n            }\n            for (unsigned _i = _frag; _i < _overlapmatrix.size1(); _i++) {\n                fragmentCharges(1) += _prodmat(_i, _i);\n            }\n\n            return fragmentCharges;\n        }\n\n        std::vector<double> Orbitals::Oscillatorstrengths() {\n            std::vector<double> oscs;\n            unsigned size = _transition_dipoles.size();\n            if (size > _BSE_singlet_energies.size()) {\n                size = _BSE_singlet_energies.size();\n            }\n            for (unsigned i = 0; i < size; ++i) {\n                double osc = (_transition_dipoles[i] * _transition_dipoles[i]) * 2.0 / 3.0 * (_BSE_singlet_energies(i));\n                oscs.push_back(osc);\n            }\n            return oscs;\n        }\n\n        double Orbitals::GetTotalEnergy(string _spintype, int _opt_state) {\n\n            // total energy of the excited state\n            double _total_energy;\n            double _omega = 0.0;\n\n            double _dft_energy = getQMEnergy();\n\n            if (_spintype == \"singlet\") {\n                _omega = BSESingletEnergies()[_opt_state - 1];\n            } else if (_spintype == \"triplet\") {\n                _omega = BSETripletEnergies()[_opt_state - 1];\n            } else {\n                throw std::runtime_error(\"GetTotalEnergy only knows spintypes:singlet,triplet\");\n            }\n\n\n            // DFT total energy is stored in eV\n            // singlet energies are stored in Ryd...\n\n            return _total_energy = _dft_energy * tools::conv::ev2hrt + _omega; //  e.g. hartree\n        }\n\n        ub::vector<double> Orbitals::FragmentNuclearCharges(int _frag) {\n            Elements _elements;\n\n            // go through atoms and count\n            vector < ctp::QMAtom* > ::iterator atom;\n            int id = 0;\n\n            if (_frag < 0) {\n                throw runtime_error(\"Orbitals::FragmentNuclearCharges Fragment index is smaller than zero\");\n            }\n\n            ub::vector<double> fragmentNuclearCharges = ub::vector<double>(2, 0.0);\n\n            for (atom = _atoms.begin(); atom < _atoms.end(); ++atom) {\n                id++;\n                // get element type and determine its nuclear charge\n                double crg;\n                if ( _ECP == \"\"){\n                    crg = _elements.getNucCrg((*atom)->type);\n                }else{\n                    crg = _elements.getNucCrgECP((*atom)->type);\n                }\n                // add to either fragment\n                if (id <= _frag) {\n                    fragmentNuclearCharges(0) += crg;\n                } else {\n                    fragmentNuclearCharges(1) += crg;\n                }\n            }\n            return fragmentNuclearCharges;\n        }\n\n/** \n         * \\brief Guess for a dimer based on monomer orbitals\n         * \n         * Given two monomer orbitals (A and B) constructs a guess for dimer\n         * orbitals: | A 0 | and energies: [EA, EB]\n         *           | 0 B |\n         */\n        void Orbitals::PrepareGuess(Orbitals* _orbitalsA, Orbitals* _orbitalsB, Orbitals* _orbitalsAB) {\n\n            // constructing the direct product orbA x orbB\n            int _basisA = _orbitalsA->getBasisSetSize();\n            int _basisB = _orbitalsB->getBasisSetSize();\n\n            int _levelsA = _orbitalsA->getNumberOfLevels();\n            int _levelsB = _orbitalsB->getNumberOfLevels();\n\n            int _electronsA = _orbitalsA->getNumberOfElectrons();\n            int _electronsB = _orbitalsB->getNumberOfElectrons();\n\n            ub::zero_matrix<double> zeroB(_levelsA, _basisB);\n            ub::zero_matrix<double> zeroA(_levelsB, _basisA);\n\n            ub::matrix<double>& _mo_coefficients = _orbitalsAB->MOCoefficients();\n\n\n            // AxB = | A 0 |  //   A = [EA, EB]  //\n            //       | 0 B |  //                 //\n            _mo_coefficients.resize(_levelsA + _levelsB, _basisA + _basisB);\n            _orbitalsAB->setBasisSetSize(_basisA + _basisB);\n            _orbitalsAB->setNumberOfLevels(_electronsA - _electronsB,\n                    _levelsA + _levelsB - _electronsA - _electronsB);\n            _orbitalsAB->setNumberOfElectrons(_electronsA + _electronsB);\n\n            ub::project(_mo_coefficients, ub::range(0, _levelsA), ub::range(_basisA, _basisA + _basisB)) = zeroB;\n            ub::project(_mo_coefficients, ub::range(_levelsA, _levelsA + _levelsB), ub::range(0, _basisA)) = zeroA;\n            ub::project(_mo_coefficients, ub::range(0, _levelsA), ub::range(0, _basisA)) = _orbitalsA->MOCoefficients();\n            ub::project(_mo_coefficients, ub::range(_levelsA, _levelsA + _levelsB), ub::range(_basisA, _basisA + _basisB)) = _orbitalsB->MOCoefficients();\n\n            ub::vector<double>& _energies = _orbitalsAB->MOEnergies();\n            _energies.resize(_levelsA + _levelsB);\n\n            ub::project(_energies, ub::range(0, _levelsA)) = _orbitalsA->MOEnergies();\n            ub::project(_energies, ub::range(_levelsA, _levelsA + _levelsB)) = _orbitalsB->MOEnergies();\n\n            return;\n        }\n\n        void Orbitals::LoadFromXYZ(std::string filename) {\n\n            string line;\n            std::ifstream in;\n\n\n            string type;\n\n\n            in.open(filename.c_str(), std::ios::in);\n            if (!in) throw runtime_error(string(\"Error reading coordinates from: \")\n                    + filename);\n\n\n            int atomCount = 1;\n\n            if (in.is_open()) {\n                while (in.good()) {\n                    std::getline(in, line);\n\n                    vector< string > split;\n                    Tokenizer toker(line, \" \\t\");\n                    toker.ToVector(split);\n                    if (!split.size() ||\n                            split.size() != 4 ||\n                            split[0] == \"#\" ||\n                            split[0].substr(0, 1) == \"#\") {\n                        continue;\n                    }\n\n                    // Interesting information written here: e.g. 'C 0.000 0.000 0.000'\n                    atomCount++;\n                    string element = split[0];\n                    double x = boost::lexical_cast<double>(split[1]); //°A to NM\n                    double y = boost::lexical_cast<double>(split[2]);\n                    double z = boost::lexical_cast<double>(split[3]);\n                    AddAtom(element, x, y, z);\n\n                }\n            } else {\n                throw std::runtime_error(\"No such file: '\" + filename + \"'.\");\n            }\n            return;\n        }\n\n        \n    }\n}\n", "meta": {"hexsha": "4bfb85ecd350ca2a98ca78db6f7925eb5292ac27", "size": 30881, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/orbitals.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/orbitals.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/orbitals.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": 39.7438867439, "max_line_length": 193, "alphanum_fraction": 0.4973932191, "num_tokens": 8046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.03732688680867723, "lm_q1q2_score": 0.013279969179552476}}
{"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 \"simple_star_ops.h\"\n#include \"backbone_tree_action.h\"\n#include \"edge_types_cost_function.h\"\n#include \"g2o/core/optimization_algorithm_with_hessian.h\"\n#include <iostream>\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n\n\nnamespace g2o{\n\n  using namespace std;\n  using namespace Eigen;\n\n  double activeVertexChi(const OptimizableGraph::Vertex* v){\n    const SparseOptimizer* s = dynamic_cast<const SparseOptimizer*>(v->graph());\n    const OptimizableGraph::EdgeContainer& av = s->activeEdges();\n    double chi = 0;\n    int ne =0;\n    for (HyperGraph::EdgeSet::iterator it = v->edges().begin(); it!=v->edges().end(); it++){\n      OptimizableGraph::Edge* e = dynamic_cast <OptimizableGraph::Edge*> (*it);\n      if (!e)\n\tcontinue;\n      if (s->findActiveEdge(e)!=av.end()) {\n\tchi +=e->chi2();\n\tne++;\n      }\n    }\n    if (! ne)\n      return -1;\n    return chi/ne;\n  }\n\nvoid constructEdgeStarMap(EdgeStarMap& esmap, StarSet& stars, bool low){\n  esmap.clear();\n  for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){\n    Star* s = *it;\n    if (low) {\n      for (HyperGraph::EdgeSet::iterator it = s->lowLevelEdges().begin();\n          it!=s->lowLevelEdges().end(); it++){\n        HyperGraph::Edge* e=*it;\n        esmap.insert(make_pair(e,s));\n      }\n    } else {\n      for (HyperGraph::EdgeSet::iterator it = s->starEdges().begin();\n          it!=s->starEdges().end(); it++){\n        HyperGraph::Edge* e=*it;\n        esmap.insert(make_pair(e,s));\n      }\n    }\n  }\n}\n\nsize_t vertexEdgesInStar(HyperGraph::EdgeSet& eset, HyperGraph::Vertex* v, Star* s, EdgeStarMap& esmap){\n  eset.clear();\n  for (HyperGraph::EdgeSet::iterator it=v->edges().begin(); it!=v->edges().end(); it++){\n    HyperGraph::Edge* e=*it;\n    EdgeStarMap::iterator eit=esmap.find(e);\n    if (eit!=esmap.end() && eit->second == s)\n      eset.insert(e);\n  }\n  return eset.size();\n}\n\nvoid starsInVertex(StarSet& stars, HyperGraph::Vertex* v, EdgeStarMap& esmap){\n  for (HyperGraph::EdgeSet::iterator it=v->edges().begin(); it!=v->edges().end(); it++){\n    HyperGraph::Edge* e=*it;\n    EdgeStarMap::iterator eit=esmap.find(e);\n    if (eit!=esmap.end())\n      stars.insert(eit->second);\n  }\n}\n\nvoid starsInEdge(StarSet& stars, HyperGraph::Edge* e, EdgeStarMap& esmap, HyperGraph::VertexSet& gauge){\n  for (size_t i=0; i<e->vertices().size(); i++){\n    OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)e->vertices()[i];\n    if (gauge.find(v)==gauge.end())\n      starsInVertex(stars, v, esmap);\n  }\n}\n\nvoid assignHierarchicalEdges(StarSet& stars, EdgeStarMap& esmap, EdgeLabeler* labeler, EdgeCreator* creator, SparseOptimizer* optimizer, int minNumEdges, int maxIterations){\n  // now construct the hierarchical edges for all the stars\n  int starNum=0;\n  for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){\n    cerr << \"STAR# \" << starNum << endl;\n    Star* s=*it;\n    std::vector<OptimizableGraph::Vertex*> vertices(2);\n    vertices[0]= (OptimizableGraph::Vertex*) *s->_gauge.begin();\n    cerr << \"eIs\"  << endl;\n    HyperGraph::VertexSet vNew =s->lowLevelVertices();\n    for (HyperGraph::VertexSet::iterator vit=s->_lowLevelVertices.begin(); vit!=s->_lowLevelVertices.end(); vit++){\n      OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)*vit;\n      vertices[1]=v;\n      if (v==vertices[0])\n        continue;\n      HyperGraph::EdgeSet eInSt;\n      int numEdges = vertexEdgesInStar(eInSt, v, s, esmap);\n      if (Factory::instance()->tag(v)==Factory::instance()->tag(vertices[0]) || numEdges>minNumEdges) {\n        OptimizableGraph::Edge* e=creator->createEdge(vertices);\n        //cerr << \"creating edge\" << e << endl;\n        if (e) {\n          e->setLevel(1);\n          optimizer->addEdge(e);\n          s->_starEdges.insert(e);\n        } else {\n          cerr << \"THERE\" << endl;\n          cerr << \"FATAL, cannot create edge\" << endl;\n        }\n      } else {\n        vNew.erase(v);\n        // cerr << numEdges << \" \";\n        // cerr << \"r \" <<  v-> id() << endl;\n        // remove from the star all edges that are not sufficiently connected\n        for (HyperGraph::EdgeSet::iterator it=eInSt.begin(); it!=eInSt.end(); it++){\n          HyperGraph::Edge* e=*it;\n          s->lowLevelEdges().erase(e);\n        }\n      }\n    }\n    s->lowLevelVertices()=vNew;\n    //cerr << endl;\n    cerr <<  \"gauge: \" << (*s->_gauge.begin())->id()\n      << \" edges:\" << s->_lowLevelEdges.size()\n      << \" hedges\" << s->_starEdges.size() << endl;\n\n    const bool debug = false;\n    if (debug){\n      char starLowName[100];\n      sprintf(starLowName, \"star-%04d-low.g2o\", starNum);\n      ofstream starLowStream(starLowName);\n      optimizer->saveSubset(starLowStream, s->_lowLevelEdges);\n    }\n    bool labelOk=s->labelStarEdges(maxIterations, labeler);\n    if (labelOk) {\n      if (debug) {\n        char starHighName[100];\n        sprintf(starHighName, \"star-%04d-high.g2o\", starNum);\n        ofstream starHighStream(starHighName);\n        optimizer->saveSubset(starHighStream, s->_starEdges);\n      }\n    } else {\n      cerr << \"FAILURE\" << endl;\n    }\n    starNum++;\n  }\n}\n\nvoid computeBorder(StarSet& stars, EdgeStarMap& hesmap){\n  cerr << \"computing edges on the border\" << endl;\n  for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){\n    Star* s=*it;\n    for (HyperGraph::EdgeSet::iterator iit=s->_starEdges.begin(); iit!=s->_starEdges.end(); iit++){\n      OptimizableGraph::Edge* e= (OptimizableGraph::Edge*) *iit;\n      StarSet sset;\n      starsInEdge(sset, e, hesmap, s->gauge());\n      //cerr << \"e: \" << e << \" l:\" << e->level() << \" sset.size()=\" << sset.size() << endl;\n      if (sset.size()>1){\n        s->starFrontierEdges().insert(e);\n      }\n    }\n  }\n}\n\n\n  void computeSimpleStars(StarSet& stars,\n\t\t\t  SparseOptimizer* optimizer,\n\t\t\t  EdgeLabeler* labeler,\n\t\t\t  EdgeCreator* creator,\n\t\t\t  OptimizableGraph::Vertex* gauge_,\n\t\t\t  std::string edgeTag,\n\t\t\t  std::string vertexTag,\n\t\t\t  int level,\n\t\t\t  int step,\n\t\t\t  int backboneIterations,\n\t\t\t  int starIterations,\n\t\t\t  double rejectionThreshold,\n\t\t\t  bool debug){\n\n    cerr << \"preforming the tree actions\" << endl;\n    HyperDijkstra d(optimizer);\n    // compute a spanning tree based on the types of edges and vertices in the pool\n    EdgeTypesCostFunction f(edgeTag, vertexTag, level);\n    d.shortestPaths(gauge_,\n        &f,\n        std::numeric_limits< double >::max(),\n        1e-6,\n        false,\n        std::numeric_limits< double >::max()/2);\n\n    HyperDijkstra::computeTree(d.adjacencyMap());\n    // constructs the stars on the backbone\n\n    BackBoneTreeAction bact(optimizer, vertexTag, level, step);\n    bact.init();\n\n    cerr << \"free edges size \" << bact.freeEdges().size() << endl;\n\n    // perform breadth-first visit of the visit tree and create the stars on the backbone\n    d.visitAdjacencyMap(d.adjacencyMap(),&bact,true);\n    stars.clear();\n\n    for (VertexStarMultimap::iterator it=bact.vertexStarMultiMap().begin();\n        it!=bact.vertexStarMultiMap().end(); it++){\n      stars.insert(it->second);\n    }\n    cerr << \"stars.size: \" << stars.size() << endl;\n    cerr << \"size: \" << bact.vertexStarMultiMap().size() << endl;\n\n\n    //  for each star\n\n    //    for all vertices in the backbone, select all edges leading/leaving from that vertex\n    //    that are contained in freeEdges.\n\n    //      mark the corresponding \"open\" vertices and add them to a multimap (vertex->star)\n\n    //    select a gauge in the backbone\n\n    //    push all vertices on the backbone\n\n    //    compute an initial guess on the backbone\n\n    //    one round of optimization backbone\n\n    //    lock all vertices in the backbone\n\n    //    push all \"open\" vertices\n\n    //    for each open vertex,\n    //      compute an initial guess given the backbone\n    //      do some rounds of solveDirect\n    //      if (fail)\n    //        - remove the vertex and the edges in that vertex from the star\n    //   - make the structures consistent\n\n    //    pop all \"open\" vertices\n    //    pop all \"vertices\" in the backbone\n    //    unfix the vertices in the backbone\n\n    int starNum=0;\n    for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){\n      Star* s =*it;\n      HyperGraph::VertexSet backboneVertices = s->_lowLevelVertices;\n      HyperGraph::EdgeSet backboneEdges = s->_lowLevelEdges;\n      if (backboneEdges.empty())\n\tcontinue;\n\n\n      // cerr << \"optimizing backbone\" << endl;\n      // one of these  should be the gauge, to be simple we select the fisrt one in the backbone\n      OptimizableGraph::VertexSet gauge;\n      gauge.insert(*backboneVertices.begin());\n      s->gauge()=gauge;\n      s->optimizer()->push(backboneVertices);\n      s->optimizer()->setFixed(gauge,true);\n      s->optimizer()->initializeOptimization(backboneEdges);\n      s->optimizer()->computeInitialGuess();\n      s->optimizer()->optimize(backboneIterations);\n      s->optimizer()->setFixed(backboneVertices, true);\n\n      // cerr << \"assignind edges.vertices not in bbone\" << endl;\n      HyperGraph::EdgeSet otherEdges;\n      HyperGraph::VertexSet otherVertices;\n      std::multimap<HyperGraph::Vertex*, HyperGraph::Edge*> vemap;\n      for (HyperGraph::VertexSet::iterator bit=backboneVertices.begin(); bit!=backboneVertices.end(); bit++){\n\tHyperGraph::Vertex* v=*bit;\n\tfor (HyperGraph::EdgeSet::iterator eit=v->edges().begin(); eit!=v->edges().end(); eit++){\n\t  OptimizableGraph::Edge* e = (OptimizableGraph::Edge*) *eit;\n\t  HyperGraph::EdgeSet::iterator feit=bact.freeEdges().find(e);\n\t  if (feit!=bact.freeEdges().end()){ // edge is admissible\n\t    otherEdges.insert(e);\n\t    bact.freeEdges().erase(feit);\n\t    for (size_t i=0; i<e->vertices().size(); i++){\n\t      OptimizableGraph::Vertex* ve= (OptimizableGraph::Vertex*)e->vertices()[i];\n\t      if (backboneVertices.find(ve)==backboneVertices.end()){\n\t\totherVertices.insert(ve);\n\t\tvemap.insert(make_pair(ve,e));\n\t      }\n\t    }\n\t  }\n\t}\n      }\n\n      // RAINER TODO maybe need a better solution than dynamic casting here??\n      OptimizationAlgorithmWithHessian* solverWithHessian = dynamic_cast<OptimizationAlgorithmWithHessian*>(s->optimizer()->solver());\n      if (solverWithHessian) {\n        s->optimizer()->push(otherVertices);\n        // cerr << \"optimizing vertices out of bbone\" << endl;\n        // cerr << \"push\" << endl;\n        // cerr << \"init\" << endl;\n        s->optimizer()->initializeOptimization(otherEdges);\n        // cerr << \"guess\" << endl;\n        s->optimizer()->computeInitialGuess();\n        // cerr << \"solver init\" << endl;\n        s->optimizer()->solver()->init();\n        // cerr << \"structure\" << endl;\n        if (!solverWithHessian->buildLinearStructure())\n          cerr << \"FATAL: failure while building linear structure\" << endl;\n        // cerr << \"errors\" << endl;\n        s->optimizer()->computeActiveErrors();\n        // cerr << \"system\" << endl;\n        solverWithHessian->updateLinearSystem();\n        // cerr << \"directSolove\" << endl;\n      } else {\n        cerr << \"FATAL: hierarchical thing cannot be used with a solver that does not support the system structure construction\" << endl;\n      }\n\n\n      // // then optimize the vertices one at a time to check if a solution is good\n      for (HyperGraph::VertexSet::iterator vit=otherVertices.begin(); vit!=otherVertices.end(); vit++){\n        OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)(*vit);\n        v->solveDirect();\n        // cerr << \" \" << d;\n        // if  a solution is found, add a vertex and all the edges in\n        //othervertices that are pointing to that edge to the star\n        s->_lowLevelVertices.insert(v);\n        for (HyperGraph::EdgeSet::iterator eit=v->edges().begin(); eit!=v->edges().end(); eit++){\n          OptimizableGraph::Edge* e = (OptimizableGraph::Edge*) *eit;\n          if (otherEdges.find(e)!=otherEdges.end())\n            s->_lowLevelEdges.insert(e);\n        }\n      }\n      //cerr <<  endl;\n\n      // relax the backbone and optimize it all\n      // cerr << \"relax bbone\" << endl;\n      s->optimizer()->setFixed(backboneVertices, false);\n      //cerr << \"fox gauge bbone\" << endl;\n      s->optimizer()->setFixed(s->gauge(),true);\n\n      //cerr << \"opt init\" << endl;\n      s->optimizer()->initializeOptimization(s->_lowLevelEdges);\n      optimizer->computeActiveErrors();\n      double initialChi = optimizer->activeChi2();\n      int starOptResult = s->optimizer()->optimize(starIterations);\n      //cerr << starOptResult << \"(\" << starIterations << \")  \" << endl;\n      double finalchi=-1.;\n\n      cerr <<  \"computing star: \" << starNum << endl;\n\n      int vKept=0, vDropped=0;\n      if (!starIterations || starOptResult > 0  ){\n\toptimizer->computeActiveErrors();\n\tfinalchi = optimizer->activeChi2();\n\n#if 1\n\n        s->optimizer()->computeActiveErrors();\n        // cerr << \"system\" << endl;\n        solverWithHessian->updateLinearSystem();\n        HyperGraph::EdgeSet prunedStarEdges = backboneEdges;\n        HyperGraph::VertexSet prunedStarVertices = backboneVertices;\n        for (HyperGraph::VertexSet::iterator vit=otherVertices.begin(); vit!=otherVertices.end(); vit++){\n\n\t  //discard the vertices whose error is too big\n\n\n          OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)(*vit);\n          MatrixXd h(v->dimension(), v->dimension());\n          for (int i=0; i<v->dimension(); i++){\n            for (int j=0; j<v->dimension(); j++)\n              h(i,j)=v->hessian(i,j);\n          }\n          EigenSolver<Eigen::MatrixXd> esolver;\n          esolver.compute(h);\n          VectorXcd ev= esolver.eigenvalues();\n          double emin = std::numeric_limits<double>::max();\n          double emax = -std::numeric_limits<double>::max();\n          for (int i=0; i<ev.size(); i++){\n            emin = ev(i).real()>emin ? emin : ev(i).real();\n            emax = ev(i).real()<emax ? emax : ev(i).real();\n          }\n\n          double d=emin/emax;\n\n\n          // cerr << \" \" << d;\n          if (d>rejectionThreshold){\n\t  // if  a solution is found, add a vertex and all the edges in\n\t  //othervertices that are pointing to that edge to the star\n            prunedStarVertices.insert(v);\n            for (HyperGraph::EdgeSet::iterator eit=v->edges().begin(); eit!=v->edges().end(); eit++){\n              OptimizableGraph::Edge* e = (OptimizableGraph::Edge*) *eit;\n              if (otherEdges.find(e)!=otherEdges.end())\n                prunedStarEdges.insert(e);\n            }\n            //cerr << \"K( \" << v->id() << \",\" << d << \")\" ;\n            vKept ++;\n          } else {\n            vDropped++;\n            //cerr << \"R( \" << v->id() << \",\" << d << \")\" ;\n          }\n        }\n        s->_lowLevelEdges=prunedStarEdges;\n        s->_lowLevelVertices=prunedStarVertices;\n\n#endif\n\t//cerr << \"addHedges\" << endl;\n\t//now add to the star the hierarchical edges\n\tstd::vector<OptimizableGraph::Vertex*> vertices(2);\n\tvertices[0]= (OptimizableGraph::Vertex*) *s->_gauge.begin();\n\n\tfor (HyperGraph::VertexSet::iterator vit=s->_lowLevelVertices.begin(); vit!=s->_lowLevelVertices.end(); vit++){\n\t  OptimizableGraph::Vertex* v=(OptimizableGraph::Vertex*)*vit;\n\t  vertices[1]=v;\n\t  if (v==vertices[0])\n\t    continue;\n\t  OptimizableGraph::Edge* e=creator->createEdge(vertices);\n\t  //rr << \"creating edge\" << e <<  Factory::instance()->tag(vertices[0]) << \"->\" <<  Factory::instance()->tag(v) <endl;\n\t  if (e) {\n\t    e->setLevel(level+1);\n\t    optimizer->addEdge(e);\n\t    s->_starEdges.insert(e);\n\t  } else {\n            cerr << \"HERE\" << endl;\n\t    cerr << \"FATAL, cannot create edge\" << endl;\n\t  }\n\t}\n      }\n\n      cerr << \" gauge: \" << (*s->_gauge.begin())->id()\n           << \" kept: \" << vKept\n           << \" dropped: \" << vDropped\n\t   << \" edges:\" << s->_lowLevelEdges.size()\n\t   << \" hedges\" << s->_starEdges.size()\n\t   << \" initial chi \" << initialChi\n\t   << \" final chi \" << finalchi << endl;\n\n      if (debug) {\n\tchar starLowName[100];\n\tsprintf(starLowName, \"star-%04d-low.g2o\", starNum);\n\tofstream starLowStream(starLowName);\n\toptimizer->saveSubset(starLowStream, s->_lowLevelEdges);\n      }\n      bool labelOk=false;\n      if (!starIterations || starOptResult > 0)\n        labelOk = s->labelStarEdges(0, labeler);\n      if (labelOk) {\n        if (debug) {\n          char starHighName[100];\n          sprintf(starHighName, \"star-%04d-high.g2o\", starNum);\n          ofstream starHighStream(starHighName);\n          optimizer->saveSubset(starHighStream, s->_starEdges);\n        }\n      } else {\n\n        cerr << \"FAILURE: \" << starOptResult << endl;\n      }\n      starNum++;\n\n      //label each hierarchical edge\n      s->optimizer()->pop(otherVertices);\n      s->optimizer()->pop(backboneVertices);\n      s->optimizer()->setFixed(s->gauge(),false);\n    }\n\n\n    StarSet stars2;\n    // now erase the stars that have 0 edges. They r useless\n    for (StarSet::iterator it=stars.begin(); it!=stars.end(); it++){\n      Star* s=*it;\n      if (s->lowLevelEdges().size()==0) {\n        delete s;\n      } else\n        stars2.insert(s);\n    }\n    stars=stars2;\n  }\n\n\n}\n", "meta": {"hexsha": "44be98614599fd3bb4f8d4499aba979f47b0b107", "size": 18390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2opy/g2o/apps/g2o_hierarchical/simple_star_ops.cpp", "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T04:41:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:34:41.000Z", "max_issues_repo_path": "thirdparty/g2opy/g2o/apps/g2o_hierarchical/simple_star_ops.cpp", "max_issues_repo_name": "rpng/suo_slam", "max_issues_repo_head_hexsha": "5de01433d177fde5cac4423f05fd554e3c00794e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/g2opy/g2o/apps/g2o_hierarchical/simple_star_ops.cpp", "max_forks_repo_name": "rpng/suo_slam", "max_forks_repo_head_hexsha": "5de01433d177fde5cac4423f05fd554e3c00794e", "max_forks_repo_licenses": ["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.78, "max_line_length": 173, "alphanum_fraction": 0.6145731376, "num_tokens": 4812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.03114382907349389, "lm_q1q2_score": 0.013277286808638744}}
{"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, 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 tools/license/license.mtl.txt in the distribution.\n\n#ifndef MTL_VECTOR_VEC_SCAL_MIXED_EXPR_INCLUDE\n#define MTL_VECTOR_VEC_SCAL_MIXED_EXPR_INCLUDE\n\n#include <boost/numeric/mtl/utility/enable_if.hpp>\n#include <boost/numeric/mtl/vector/map_view.hpp>\n#include <boost/numeric/mtl/operation/tfunctor_mixed.hpp>\n\nnamespace mtl { namespace vector {\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E1, map_view<tfunctor::left_plus<E1, typename E2::value_type>, E2> >::type\ninline operator+(const E1& e1, const vec_expr<E2>& e2)\n{\n    typedef tfunctor::left_plus<E1, typename E2::value_type> ftype;\n    typedef map_view<ftype, E2>                             type;\n\n    return type(ftype(e1), static_cast<const E2&>(e2));\n}\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E2, map_view<tfunctor::right_plus<typename E1::value_type, E2>, E1> >::type\ninline operator+(const vec_expr<E1>& e1, const E2& e2)\n{\n    typedef tfunctor::right_plus<typename E1::value_type, E2>ftype;\n    typedef map_view<ftype, E1>                             type;\n\n    return type(ftype(e2), static_cast<const E1&>(e1));\n}\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E1, map_view<tfunctor::left_minus<E1, typename E2::value_type>, E2> >::type\ninline operator-(const E1& e1, const vec_expr<E2>& e2)\n{\n    typedef tfunctor::left_minus<E1, typename E2::value_type> ftype;\n    typedef map_view<ftype, E2>                             type;\n\n    return type(ftype(e1), static_cast<const E2&>(e2));\n}\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E2, map_view<tfunctor::right_minus<typename E1::value_type, E2>, E1> >::type\ninline operator-(const vec_expr<E1>& e1, const E2& e2)\n{\n    typedef tfunctor::right_minus<typename E1::value_type, E2>ftype;\n    typedef map_view<ftype, E1>                             type;\n\n    return type(ftype(e2), static_cast<const E1&>(e1));\n}\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E1, map_view<tfunctor::left_min<E1, typename E2::value_type>, E2> >::type\ninline min(const E1& e1, const vec_expr<E2>& e2)\n{\n    typedef tfunctor::left_min<E1, typename E2::value_type> ftype;\n    typedef map_view<ftype, E2>                             type;\n\n    return type(ftype(e1), static_cast<const E2&>(e2));\n}\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E2, map_view<tfunctor::right_min<typename E1::value_type, E2>, E1> >::type\ninline min(const vec_expr<E1>& e1, const E2& e2)\n{\n    typedef tfunctor::right_min<typename E1::value_type, E2>ftype;\n    typedef map_view<ftype, E1>                             type;\n\n    return type(ftype(e2), static_cast<const E1&>(e1));\n}\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E1, map_view<tfunctor::left_max<E1, typename E2::value_type>, E2> >::type\ninline max(const E1& e1, const vec_expr<E2>& e2)\n{\n    typedef tfunctor::left_max<E1, typename E2::value_type> ftype;\n    typedef map_view<ftype, E2>                             type;\n\n    return type(ftype(e1), static_cast<const E2&>(e2));\n}\n\ntemplate <typename E1, typename E2>\ntypename mtl::traits::enable_if_scalar<E2, map_view<tfunctor::right_max<typename E1::value_type, E2>, E1> >::type\ninline max(const vec_expr<E1>& e1, const E2& e2)\n{\n    typedef tfunctor::right_max<typename E1::value_type, E2>ftype;\n    typedef map_view<ftype, E1>                             type;\n\n    return type(ftype(e2), static_cast<const E1&>(e1));\n}\n\n}} // namespace mtl::vector\n\n#endif // MTL_VECTOR_VEC_SCAL_MIXED_EXPR_INCLUDE\n", "meta": {"hexsha": "3b6207d113bbcc1251a819615013402f65a95351", "size": 3991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/vector/vec_scal_mixed_expr.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/vector/vec_scal_mixed_expr.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/vector/vec_scal_mixed_expr.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": 38.0095238095, "max_line_length": 115, "alphanum_fraction": 0.6900526184, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.03846618995154013, "lm_q1q2_score": 0.013274884905943248}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////\n// This file is distributed under the University of Illinois/NCSA Open Source License.\n// See LICENSE file in top directory for details.\n//\n// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.\n//\n// File developed by: Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign\n//                    Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign\n//                    Luke Shulenburger, lshulen@sandia.gov, Sandia National Laboratories\n//                    Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign\n//                    Raymond Clay III, j.k.rofling@gmail.com, Lawrence Livermore National Laboratory\n//                    Ye Luo, yeluo@anl.gov, Argonne National Laboratory\n//                    Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory\n//\n// File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign\n//////////////////////////////////////////////////////////////////////////////////////\n    \n    \n\n\n#include \"QMCDrivers/SimpleFixedNodeBranch.h\"\n#include \"QMCDrivers/DMC/WalkerControlFactory.h\"\n#include <numeric>\n#include \"OhmmsData/FileUtility.h\"\n#include \"Utilities/RandomGenerator.h\"\n#include \"QMCDrivers/WalkerControlBase.h\"\n#include \"Estimators/EstimatorManagerBase.h\"\n#include \"QMCDrivers/BranchIO.h\"\n#include \"Particle/Reptile.h\"\n#ifdef HAVE_ADIOS\n#include <adios.h>\n#endif\n\n\n//#include <boost/archive/text_oarchive.hpp>\n\nnamespace qmcplusplus\n{\n\n///enum to yes/no options saved in sParam\nenum {COMBOPT, USETAUOPT, MIXDMCOPT, DUMMYOPT};\n\nSimpleFixedNodeBranch::SimpleFixedNodeBranch(RealType tau, int nideal)\n  : vParam(1.0), WalkerController(0), BackupWalkerController(0),\n    MyEstimator(0)//, PopHist(5), DMCEnergyHist(5)\n{\n  BranchMode.set(B_DMCSTAGE,0); //warmup stage\n  BranchMode.set(B_POPCONTROL,1); //use standard DMC\n  BranchMode.set(B_USETAUEFF,1); //use taueff\n  BranchMode.set(B_CLEARHISTORY,0); //clear history and start with the current average\n  BranchMode.set(B_KILLNODES,0); //when killing walkers at nodes etrial is updated differently\n  vParam[B_TAU]=tau;\n  vParam[B_TAUEFF]=tau;\n  vParam[B_FEEDBACK]=1.0;\n  vParam[B_FILTERSCALE]=10;\n  R2Accepted(1.0e-10);\n  R2Proposed(1.0e-10);\n  //set the default values for integer parameters\n  iParam[B_WARMUPSTEPS]=200;\n  iParam[B_ENERGYUPDATEINTERVAL]=1;\n  iParam[B_BRANCHINTERVAL]=1;\n  iParam[B_TARGETWALKERS]=0;\n  iParam[B_MAXWALKERS]=nideal;\n  iParam[B_MINWALKERS]=nideal;\n  iParam[B_COUNTER]=-1;\n  //default is no\n  sParam.resize(DUMMYOPT,\"no\");\n  //default is classic\n  branching_cutoff_scheme=\"classic\";\n  registerParameters();\n  reset();\n}\n\n/** copy constructor\n *\n * Copy only selected data members and WalkerController is never copied.\n */\nSimpleFixedNodeBranch::SimpleFixedNodeBranch(const SimpleFixedNodeBranch& abranch):\n  BranchMode(abranch.BranchMode),\n  iParam(abranch.iParam),\n  vParam(abranch.vParam),\n  WalkerController(0), MyEstimator(0),\n  sParam(abranch.sParam),\n  branching_cutoff_scheme(abranch.branching_cutoff_scheme)\n{\n  registerParameters();\n  reset();\n}\n\nvoid SimpleFixedNodeBranch::registerParameters()\n{\n  m_param.add(iParam[B_WARMUPSTEPS],\"warmupSteps\",\"int\");\n  m_param.add(iParam[B_WARMUPSTEPS],\"warmupsteps\",\"int\");\n  m_param.add(iParam[B_ENERGYUPDATEINTERVAL],\"energyUpdateInterval\",\"int\");\n  m_param.add(iParam[B_BRANCHINTERVAL],\"branchInterval\",\"int\");\n  m_param.add(iParam[B_TARGETWALKERS],\"targetWalkers\",\"int\");\n  m_param.add(iParam[B_TARGETWALKERS],\"targetwalkers\",\"int\");\n  m_param.add(iParam[B_TARGETWALKERS],\"target_walkers\",\"int\");\n  //trial energy\n  m_param.add(vParam[B_EREF],\"refEnergy\",\"AU\");\n  m_param.add(vParam[B_EREF],\"ref_energy\",\"AU\");\n  m_param.add(vParam[B_EREF],\"en_ref\",\"AU\");\n  m_param.add(vParam[B_TAU],\"tau\",\"AU\");\n  m_param.add(vParam[B_TAU],\"timestep\",\"AU\");\n  m_param.add(vParam[B_TAU],\"timeStep\",\"AU\");\n  m_param.add(vParam[B_TAU],\"TimeStep\",\"AU\");\n  //filterscale:  sets the filtercutoff to sigma*filterscale\n  m_param.add(vParam[B_FILTERSCALE],\"filterscale\",\"double\");\n  //feed back parameter for population control\n  m_param.add(vParam[B_FEEDBACK],\"feedback\",\"double\");\n  //turn on/off effective tau onl for time-step error comparisons\n  m_param.add(sParam[USETAUOPT],\"useBareTau\",\"option\");\n  m_param.add(sParam[MIXDMCOPT],\"warmupByReconfiguration\",\"opt\");\n  m_param.add(branching_cutoff_scheme,\"branching_cutoff_scheme\",\"option\");\n}\n\nvoid SimpleFixedNodeBranch::start(const std::string& froot, bool append)\n{\n  RootName=froot;\n  MyEstimator->RootName=froot;\n  MyEstimator->reset();\n}\n\nint SimpleFixedNodeBranch::initWalkerController(MCWalkerConfiguration& walkers, bool fixW, bool killwalker)\n{\n  BranchMode.set(B_DMC,1);//set DMC\n  BranchMode.set(B_DMCSTAGE,iParam[B_WARMUPSTEPS]==0);//use warmup\n  //this is not necessary\n  //check if tau is different and set the initial values\n  //vParam[B_TAU]=tau;\n  bool fromscratch=false;\n  EstimatorRealType tau=vParam[B_TAU];\n\n  int nwtot_now=walkers.getGlobalNumWalkers();\n\n  //this is the first time DMC is used\n  if(WalkerController == 0)\n  {\n    if(iParam[B_TARGETWALKERS]==0)\n    {\n      Communicate* acomm=MyEstimator->getCommunicator();\n      int ncontexts=acomm->size();\n      std::vector<int> nw(ncontexts,0),nwoff(ncontexts+1,0);\n      nw[acomm->rank()]=walkers.getActiveWalkers();\n      acomm->allreduce(nw);\n      for(int ip=0; ip<ncontexts; ++ip)\n        nwoff[ip+1]=nwoff[ip]+nw[ip];\n      walkers.setGlobalNumWalkers(nwoff[ncontexts]);\n      walkers.setWalkerOffsets(nwoff);\n      iParam[B_TARGETWALKERS]=nwoff[ncontexts];\n    }\n    WalkerController = createWalkerController(iParam[B_TARGETWALKERS], MyEstimator->getCommunicator(), myNode);\n    if(!BranchMode[B_RESTART])\n    {\n      fromscratch=true;\n      app_log() << \"  START ALL OVER \" << std::endl;\n      vParam[B_TAUEFF]=tau;\n      BranchMode.set(B_POPCONTROL,!fixW);//fixW -> 0\n      BranchMode.set(B_KILLNODES,killwalker);\n      iParam[B_MAXWALKERS]=WalkerController->Nmax;\n      iParam[B_MINWALKERS]=WalkerController->Nmin;\n      if(!fixW && sParam[MIXDMCOPT]==\"yes\")\n      {\n        app_log() << \"Warmup DMC is done with a fixed population \" << iParam[B_TARGETWALKERS] << std::endl;\n        BackupWalkerController=WalkerController; //save the main controller\n        WalkerController=createWalkerController(iParam[B_TARGETWALKERS],MyEstimator->getCommunicator(), myNode,true);\n        BranchMode.set(B_POPCONTROL,0);\n      }\n      //PopHist.clear();\n      //PopHist.reserve(std::max(iParam[B_ENERGYUPDATEINTERVAL],5));\n    }\n    WalkerController->setWalkerID(walkers);\n  }\n  //else\n  //{\n  //  BranchMode.set(B_DMCSTAGE,0);//always reset warmup\n  //}\n  MyEstimator->reset();\n  //update the simulation parameters\n  WalkerController->put(myNode);\n  //assign current Eref and a large number for variance\n  WalkerController->setTrialEnergy(vParam[B_ETRIAL]);\n  this->reset();\n  if(fromscratch)\n  {\n    //determine the branch cutoff to limit wild weights based on the sigma and sigmaBound\n    setBranchCutoff(vParam[B_SIGMA2],WalkerController->targetSigma,50,walkers.R.size());\n    vParam[B_TAUEFF]=tau*R2Accepted.result()/R2Proposed.result();\n  }\n  //reset controller\n  WalkerController->reset();\n  if(BackupWalkerController)\n    BackupWalkerController->reset();\n  app_log() << \"  QMC counter      = \" << iParam[B_COUNTER] << std::endl;\n  app_log() << \"  time step        = \" << vParam[B_TAU] << std::endl;\n  app_log() << \"  effective time step = \" << vParam[B_TAUEFF] << std::endl;\n  app_log() << \"  trial energy     = \" << vParam[B_ETRIAL] << std::endl;\n  app_log() << \"  reference energy = \" << vParam[B_EREF] << std::endl;\n  app_log() << \"  Feedback = \" << vParam[B_FEEDBACK] <<  std::endl;\n  app_log() << \"  reference variance = \" << vParam[B_SIGMA2] << std::endl;\n  app_log() << \"  target walkers = \" << iParam[B_TARGETWALKERS] << std::endl;\n  app_log() << \"  branching cutoff scheme \" << branching_cutoff_scheme << std::endl;\n  app_log() << \"  branch cutoff = \" <<  vParam[B_BRANCHCUTOFF] << \" \" << vParam[B_BRANCHMAX] << std::endl;\n  app_log() << \"  Max and minimum walkers per node= \" << iParam[B_MAXWALKERS] << \" \" << iParam[B_MINWALKERS] << std::endl;\n  app_log() << \"  QMC Status (BranchMode) = \" << BranchMode << std::endl;\n\n  return int(round(double(iParam[B_TARGETWALKERS])/double(nwtot_now)));\n}\n\nvoid SimpleFixedNodeBranch::initReptile(MCWalkerConfiguration& W)\n{\n  RealType allowedFlux=50.0;\n  BranchMode.set(B_RMC,1);//set RMC\n  BranchMode.set(B_RMCSTAGE,iParam[B_WARMUPSTEPS]==0);//use warmup\n  //this is not necessary\n  //check if tau is different and set the initial values\n  //vParam[B_TAU]=tau;\n  bool fromscratch=false;\n  EstimatorRealType tau=vParam[B_TAU];\n  //this is the first time DMC is used\n  if(WalkerController == 0)\n  {\n    //  if(iParam[B_TARGETWALKERS]==0)\n    //  {\n    //    Communicate* acomm=MyEstimator->getCommunicator();\n    //    int ncontexts=acomm->size();\n    //    std::vector<int> nw(ncontexts,0),nwoff(ncontexts+1,0);\n    //    nw[acomm->rank()]=W.getActiveWalkers();\n    //   acomm->allreduce(nw);\n    //    for(int ip=0; ip<ncontexts; ++ip)\n    //      nwoff[ip+1]=nwoff[ip]+nw[ip];\n    //    W.setGlobalNumWalkers(nwoff[ncontexts]);\n    //    W.setWalkerOffsets(nwoff);\n    //    iParam[B_TARGETWALKERS]=nwoff[ncontexts];\n    //  }\n    if(!BranchMode[B_RESTART])\n    {\n      fromscratch=true;\n      app_log() << \"  START ALL OVER \" << std::endl;\n      vParam[B_TAUEFF]=tau;\n      //PopHist.clear();\n      //PopHist.reserve(std::max(iParam[B_ENERGYUPDATEINTERVAL],5));\n    }\n  }\n  //else\n  //{\n  //  BranchMode.set(B_DMCSTAGE,0);//always reset warmup\n  //}\n  MyEstimator->reset();\n  this->reset();\n  if(fromscratch)\n  {\n    //determine the branch cutoff to limit wild weights based on the sigma and sigmaBound\n    setBranchCutoff(vParam[B_SIGMA2],allowedFlux,50,W.R.size());\n    vParam[B_TAUEFF]=tau*R2Accepted.result()/R2Proposed.result();\n  }\n  //reset controller\n  app_log() << \"  QMC counter      = \" << iParam[B_COUNTER] << std::endl;\n  app_log() << \"  time step        = \" << vParam[B_TAU] << std::endl;\n  app_log() << \"  effective time step = \" << vParam[B_TAUEFF] << std::endl;\n  app_log() << \"  reference energy = \" << vParam[B_EREF] << std::endl;\n  app_log() << \"  Feedback = \" << vParam[B_FEEDBACK] <<  std::endl;\n  app_log() << \"  reference variance = \" << vParam[B_SIGMA2] << std::endl;\n  app_log() << \"  branching cutoff scheme \" << branching_cutoff_scheme << std::endl;\n  app_log() << \"  branch cutoff = \" <<  vParam[B_BRANCHCUTOFF] << \" \" << vParam[B_BRANCHMAX] << std::endl;\n  app_log() << \"  QMC Status (BranchMode) = \" << BranchMode << std::endl;\n}\n\nvoid SimpleFixedNodeBranch::flush(int counter)\n{\n  if(counter==0 && WalkerController)\n    WalkerController->reset();\n}\n\nvoid SimpleFixedNodeBranch::branch(int iter, MCWalkerConfiguration& walkers)\n{\n  //collect the total weights and redistribute the walkers accordingly, using a fixed tolerance\n  //RealType pop_now= WalkerController->branch(iter,walkers,0.1);\n  EstimatorRealType pop_now;\n  if(BranchMode[B_DMCSTAGE]||iter)\n    pop_now= WalkerController->branch(iter,walkers,0.1);\n  else\n    pop_now = WalkerController->doNotBranch(iter,walkers);//do not branch for the first step of a warmup\n  //population for trial energy modification should not include any released node walkers.\n  pop_now -= WalkerController->EnsembleProperty.RNSamples;\n  //current energy\n  vParam[B_ENOW]=WalkerController->EnsembleProperty.Energy;\n  VarianceHist(WalkerController->EnsembleProperty.Variance);\n  R2Accepted(WalkerController->EnsembleProperty.R2Accepted);\n  R2Proposed(WalkerController->EnsembleProperty.R2Proposed);\n  //PopHist(pop_now);\n  vParam[B_EREF]=EnergyHist.mean();//current mean\n  if(BranchMode[B_USETAUEFF])\n    vParam[B_TAUEFF]=vParam[B_TAU]*R2Accepted.result()/R2Proposed.result();\n  if(BranchMode[B_KILLNODES])\n    EnergyHist(vParam[B_ENOW]-std::log(WalkerController->EnsembleProperty.LivingFraction)/vParam[B_TAUEFF]);\n  else\n    EnergyHist(vParam[B_ENOW]);\n  if(BranchMode[B_DMCSTAGE]) // main stage\n  {\n    if(BranchMode[B_POPCONTROL])\n    {\n      if(ToDoSteps>0)\n        --ToDoSteps;\n      else\n      {\n        vParam[B_ETRIAL]=vParam[B_EREF]+vParam[B_FEEDBACK]*(logN-std::log(pop_now));\n        ToDoSteps=iParam[B_ENERGYUPDATEINTERVAL]-1;\n      }\n    }\n    else\n      vParam[B_ETRIAL]=vParam[B_EREF];\n  }\n  else//warmup\n  {\n    if(BranchMode[B_USETAUEFF])\n      vParam[B_TAUEFF]=vParam[B_TAU]*R2Accepted.result()/R2Proposed.result();\n    if(BranchMode[B_POPCONTROL])\n    {\n      //RealType emix=((iParam[B_WARMUPSTEPS]-ToDoSteps)<100)?(0.25*vParam[B_EREF]+0.75*vParam[B_ENOW]):vParam[B_EREF];\n      //vParam[B_ETRIAL]=emix+Feedback*(logN-std::log(pop_now));\n      //vParam[B_ETRIAL]=vParam[B_EREF]+Feedback*(logN-std::log(pop_now));\n      if(BranchMode[B_KILLNODES])\n        vParam[B_ETRIAL]=(0.00*vParam[B_EREF]+1.0*vParam[B_ENOW])\n                         +vParam[B_FEEDBACK]*(logN-std::log(pop_now))-std::log(WalkerController->EnsembleProperty.LivingFraction)/vParam[B_TAU];\n      else\n        vParam[B_ETRIAL]=vParam[B_ENOW]+(logN-std::log(pop_now))/vParam[B_TAU];\n    }\n    else\n      vParam[B_ETRIAL]=vParam[B_EREF];\n    --ToDoSteps;\n    if(ToDoSteps==0)  //warmup is done\n    {\n      vParam[B_SIGMA2]=VarianceHist.mean();\n      setBranchCutoff(vParam[B_SIGMA2],WalkerController->targetSigma,10,walkers.R.size());\n      app_log() << \"\\n Warmup is completed after \" << iParam[B_WARMUPSTEPS] << std::endl;\n      if(BranchMode[B_USETAUEFF])\n        app_log() << \"\\n  TauEff     = \" << vParam[B_TAUEFF] << \"\\n TauEff/Tau = \" << vParam[B_TAUEFF]/vParam[B_TAU];\n      else\n        app_log() << \"\\n  TauEff proposed   = \" << vParam[B_TAUEFF]*R2Accepted.result()/R2Proposed.result();\n      app_log()  << \"\\n  Etrial     = \" << vParam[B_ETRIAL] << std::endl;\n      app_log() << \" Running average of energy = \" << EnergyHist.mean() << std::endl;\n      app_log() << \"                  Variance = \" << vParam[B_SIGMA2] << std::endl;\n      app_log() << \"branch cutoff = \" <<  vParam[B_BRANCHCUTOFF] << \" \" << vParam[B_BRANCHMAX] << std::endl;\n      ToDoSteps = iParam[B_ENERGYUPDATEINTERVAL]-1;\n      iParam[B_WARMUPSTEPS]=0;\n      BranchMode.set(B_DMCSTAGE,1); //set BranchModex to main stage\n      //reset the histogram\n      EnergyHist.clear();\n      EnergyHist(vParam[B_ENOW]);\n      if(sParam[MIXDMCOPT]==\"yes\")\n      {\n        app_log() << \"Switching to DMC with fluctuating populations\" << std::endl;\n        BranchMode.set(B_POPCONTROL,1); //use standard DMC\n        delete WalkerController;\n        WalkerController=BackupWalkerController;\n        BackupWalkerController=0;\n        vParam[B_ETRIAL]=vParam[B_EREF];\n        app_log()  << \"  Etrial     = \" << vParam[B_ETRIAL] << std::endl;\n        WalkerController->start();\n      }\n      //This is not necessary\n      //EnergyHist(DMCEnergyHist.mean());\n    }\n  }\n  WalkerController->setTrialEnergy(vParam[B_ETRIAL]);\n  //accumulate collectables and energies for scalar.dat\n  EstimatorRealType wgt_inv=WalkerController->NumContexts/WalkerController->EnsembleProperty.Weight;\n  walkers.Collectables *= wgt_inv;\n  MyEstimator->accumulate(walkers);\n}\n\n/**\n *\n */\nvoid SimpleFixedNodeBranch::collect(int iter, MCWalkerConfiguration& W)\n{\n  //Update the current energy and accumulate.\n  MCWalkerConfiguration::Walker_t& head = W.reptile->getHead();\n  MCWalkerConfiguration::Walker_t& tail = W.reptile->getTail();\n  vParam[B_ENOW]=0.5*(head.Properties(LOCALENERGY)+tail.Properties(LOCALENERGY));\n// app_log()<<\"IN SimpleFixedNodeBranch::collect\\n\";\n// app_log()<<\"\\tvParam[B_ENOW]=\"<<vParam[B_ENOW]<< std::endl;\n  EnergyHist(vParam[B_ENOW]);\n  vParam[B_EREF]=EnergyHist.mean();\n// app_log()<<\"\\tvParam[B_EREF]=\"<<vParam[B_EREF]<< std::endl;\n  //Update the energy variance and R2 for effective timestep and filtering.\n  VarianceHist(std::pow(vParam[B_ENOW]-vParam[B_EREF],2));\n  R2Accepted(head.Properties(R2ACCEPTED));\n  R2Proposed(head.Properties(R2PROPOSED));\n// app_log()<<\"\\thead.Properties(R2ACCEPTED)=\"<<head.Properties(R2ACCEPTED)<< std::endl;\n// app_log()<<\"\\thead.Properties(R2PROPOSED)=\"<<head.Properties(R2PROPOSED)<< std::endl;\n//  app_log()<<\"\\tR2Accepted=\"<<R2Accepted.result()<< std::endl;\n// app_log()<<\"\\tR2Proposed=\"<<R2Proposed.result()<< std::endl;\n//  app_log()<<\"\\tR2Accept/R2Prop=\"<<R2Accepted.result()/R2Proposed.result()<< std::endl;\n// app_log()<<\"\\t <E^2> = \"<<VarianceHist.mean()<< std::endl;\n// app_log()<<\"\\t <E>   = \"<<EnergyHist.mean()<< std::endl;\n//  app_log()<<\"\\t <E>^2 = \"<<std::pow(EnergyHist.mean(),2)<< std::endl;\n// app_log()<<\"\\t var = \"<<VarianceHist.mean()-pow(EnergyHist.mean(),2)<< std::endl;\n// app_log()<<\"--------------\\n\";\n  //current mean\n  if(BranchMode[B_USETAUEFF])\n  {\n    //app_log()<<\" BRANCHMODE = \"<<BranchMode[B_USETAUEFF]<< std::endl;\n    vParam[B_TAUEFF]=vParam[B_TAU]*R2Accepted.result()/R2Proposed.result();\n    //  app_log()<<\"\\tvParam[B_TAU]=\"<<vParam[B_TAU]<<\" \"<<vParam[B_TAUEFF]<< std::endl;\n  }\n  /*\n  if(BranchMode[B_RMCSTAGE]) // main stage\n  {\n    if(BranchMode[B_POPCONTROL])\n    {\n      if(ToDoSteps>0)\n        --ToDoSteps;\n      else\n      {\n        vParam[B_ETRIAL]=vParam[B_EREF]+vParam[B_FEEDBACK]*(logN-std::log(pop_now));\n        ToDoSteps=iParam[B_ENERGYUPDATEINTERVAL]-1;\n      }\n    }\n    else\n      vParam[B_ETRIAL]=vParam[B_EREF];\n  }*/\n  //app_log()<<\"BranchMode[B_RMCSTAGE]=\"<<BranchMode[B_RMCSTAGE]<< std::endl;\n  if(!BranchMode[B_RMCSTAGE])//warmup\n  {\n    if(BranchMode[B_USETAUEFF])\n      vParam[B_TAUEFF]=vParam[B_TAU]*R2Accepted.result()/R2Proposed.result();\n    // app_log()<<\"\\t <E^2> = \"<<VarianceHist.mean()<< std::endl;\n// app_log()<<\"\\t <E>   = \"<<EnergyHist.mean()<< std::endl;\n// app_log()<<\"\\t <E>^2 = \"<<std::pow(EnergyHist.mean(),2)<< std::endl;\n    //app_log()<<\"\\t var = \"<<VarianceHist.mean()-std::pow(EnergyHist.mean(),2)<< std::endl;\n// app_log()<<\"\\t var = \"<<VarianceHist.mean()<< std::endl;\n//  app_log()<<\"----\\n\";\n    //app_log()<<\"ToDoSteps=\"<<ToDoSteps<< std::endl;\n    vParam[B_ETRIAL]=vParam[B_EREF];\n    --ToDoSteps;\n    if(ToDoSteps==0)  //warmup is done\n    {\n      vParam[B_TAUEFF]=vParam[B_TAU]*R2Accepted.result()/R2Proposed.result();\n      vParam[B_SIGMA2]=VarianceHist.mean();\n      setBranchCutoff(vParam[B_SIGMA2],vParam[B_FILTERSCALE],vParam[B_FILTERSCALE],W.R.size());\n      app_log() << \"\\n Warmup is completed after \" << iParam[B_WARMUPSTEPS] << \" steps.\"<< std::endl;\n      if(BranchMode[B_USETAUEFF])\n        app_log() << \"\\n  TauEff     = \" << vParam[B_TAUEFF] << \"\\n TauEff/Tau = \" << vParam[B_TAUEFF]/vParam[B_TAU];\n      else\n        app_log() << \"\\n  TauEff proposed   = \" << vParam[B_TAUEFF]*R2Accepted.result()/R2Proposed.result();\n      app_log() << \"\\n Running average of energy = \" << EnergyHist.mean() << std::endl;\n      app_log() << \"\\n                  Variance = \" << vParam[B_SIGMA2] << std::endl;\n      app_log() << \"\\nbranch cutoff = \" <<  vParam[B_BRANCHCUTOFF] << \" \" << vParam[B_BRANCHMAX] << std::endl;\n      ToDoSteps = iParam[B_ENERGYUPDATEINTERVAL]-1;\n      iParam[B_WARMUPSTEPS]=0;\n      BranchMode.set(B_RMCSTAGE,1); //set BranchModex to main stage\n      //reset the histogram\n      EnergyHist.clear();\n      EnergyHist(vParam[B_ENOW]);\n    }\n  }\n  //accumulate collectables and energies for scalar.dat\n  MyEstimator->accumulate(W);\n}\n\n/** Calculates and saves various action components, also does necessary updates for running averages.\n *\n */\nvoid SimpleFixedNodeBranch::reset()\n{\n  //use effective time step of BranchInterval*Tau\n  //Feed = 1.0/(static_cast<RealType>(NumGeneration*BranchInterval)*Tau);\n  //logN = Feed*std::log(static_cast<RealType>(Nideal));\n  //JNKIM passive\n  //BranchMode.set(B_DMC,1);//set DMC\n  //BranchMode.set(B_DMCSTAGE,0);//set warmup\n  if(WalkerController)\n  {\n    //this is to compare the time step errors\n    BranchMode.set(B_USETAUEFF,sParam[USETAUOPT]==\"no\");\n    if(BranchMode[B_DMCSTAGE]) //\n      ToDoSteps = iParam[B_ENERGYUPDATEINTERVAL]-1;\n    else\n      ToDoSteps = iParam[B_WARMUPSTEPS];\n    if(BranchMode[B_POPCONTROL])\n    {\n      //logN = Feedback*std::log(static_cast<RealType>(iParam[B_TARGETWALKERS]));\n      logN = std::log(static_cast<EstimatorRealType>(iParam[B_TARGETWALKERS]));\n      if (vParam[B_FEEDBACK]==0.0) vParam[B_FEEDBACK] = 1.0;\n    }\n    else\n    {\n      //may set Eref to a safe value\n      //if(EnergyHistory.count()<5) Eref -= vParam[EnergyWindowIndex];\n      vParam[B_ETRIAL]=vParam[B_EREF];\n      vParam[B_FEEDBACK]=0.0;\n      logN=0.0;\n    }\n//       vParam(abranch.vParam)\n    WalkerController->start();\n  }\n  if(BranchMode[B_RMC])\n  {\n    //this is to compare the time step errors\n    // BranchMode.set(B_USETAUEFF,sParam[USETAUOPT]==\"no\");\n    if(BranchMode[B_RMCSTAGE]) //\n      ToDoSteps = iParam[B_ENERGYUPDATEINTERVAL]-1;\n    else\n      ToDoSteps = iParam[B_WARMUPSTEPS];\n  }\n}\n\nvoid SimpleFixedNodeBranch::setRN (bool rn)\n{\n  RN=rn;\n  WalkerController->WriteRN = rn;\n  WalkerController->start();\n}\n\n\nint SimpleFixedNodeBranch::resetRun(xmlNodePtr cur)\n{\n  app_log() << \"BRANCH resetRun\" << std::endl;\n  //estimator is always reset\n  MyEstimator->reset();\n  MyEstimator->setCollectionMode(true);\n  std::bitset<B_MODE_MAX> bmode(BranchMode);\n  IParamType iparam_old(iParam);\n  VParamType vparam_old(vParam);\n  myNode=cur;\n  //store old target\n  int nw_target=iParam[B_TARGETWALKERS];\n  m_param.put(cur);\n\n  int target_min=-1;\n  ParameterSet p;\n  p.add(target_min,\"minimumtargetwalkers\",\"int\"); //p.add(target_min,\"minimumTargetWalkers\",\"int\"); \n  p.add(target_min,\"minimumsamples\",\"int\"); //p.add(target_min,\"minimumSamples\",\"int\");\n  p.put(cur);\n\n  if (iParam[B_TARGETWALKERS] < target_min) {\n    iParam[B_TARGETWALKERS] = target_min;\n  }\n\n  bool same_wc=true;\n  if(BranchMode[B_DMC] && WalkerController)\n  {\n    std::string reconfig(\"no\");\n    if(WalkerController->MyMethod) reconfig=\"yes\";\n    std::string reconfig_prev(reconfig);\n    ParameterSet p;\n    p.add(reconfig,\"reconfiguration\",\"string\");\n    p.put(cur);\n    same_wc=(reconfig==reconfig_prev);\n  }\n\n  //everything is the same, do nothing\n  if(same_wc && bmode==BranchMode\n      && std::equal(iParam.begin(),iParam.end(),iparam_old.begin())\n      && std::equal(vParam.begin(),vParam.end(),vparam_old.begin())\n    )\n  {\n    app_log() << \"  Continue with the same input as the previous block.\" << std::endl;\n    app_log().flush();\n    //return 1;\n  }\n  app_log() << \" SimpleFixedNodeBranch::resetRun detected changes in <parameter>'s \" << std::endl;\n  app_log() << \" BranchMode : \" << bmode << \" \" << BranchMode << std::endl;\n\n  //vmc does not need to do anything with WalkerController\n  if(!BranchMode[B_DMC])\n  {\n    app_log() << \" iParam (old): \"  <<iparam_old << std::endl;\n    app_log() << \" iParam (new): \"  <<iParam << std::endl;\n    app_log() << \" vParam (old): \"  <<vparam_old << std::endl;\n    app_log() << \" vParam (new): \"  <<vParam << std::endl;\n    app_log().flush();\n    return 1;\n  }\n\n  if(WalkerController==0)\n  {\n    APP_ABORT(\"SimpleFixedNodeBranch::resetRun cannot initialize WalkerController\");\n  }\n\n  if(!same_wc)\n  {\n    app_log() << \"Destroy WalkerController. Existing method \" << WalkerController->MyMethod << std::endl;;\n    delete WalkerController;\n    WalkerController = createWalkerController(iParam[B_TARGETWALKERS], MyEstimator->getCommunicator(), myNode);\n    app_log().flush();\n\n    BranchMode[B_POPCONTROL]= (WalkerController->MyMethod == 0);\n    if(BranchMode[B_POPCONTROL])\n    {\n      vParam[B_ETRIAL]=vParam[B_EREF];\n      if (vParam[B_FEEDBACK]==0.0) vParam[B_FEEDBACK]=1.0;\n    }\n  }\n\n  //always add a warmup step using default 10 steps\n  R2Accepted.clear();\n  R2Proposed.clear();\n  //R2Accepted(1.0e-12);\n  //R2Proposed(1.0e-12);\n  BranchMode[B_DMCSTAGE]=0;\n  WalkerController->put(myNode);\n  ToDoSteps=iParam[B_WARMUPSTEPS]=(iParam[B_WARMUPSTEPS])?iParam[B_WARMUPSTEPS]:10;\n  setBranchCutoff(vParam[B_SIGMA2],WalkerController->targetSigma,10);\n  WalkerController->reset();\n#ifdef QMC_CUDA\n  reset(); // needed. Ye\n#endif\n  if(BackupWalkerController)\n    BackupWalkerController->reset();\n\n  iParam[B_MAXWALKERS]=WalkerController->Nmax;\n  iParam[B_MINWALKERS]=WalkerController->Nmin;\n\n  app_log() << \" iParam (old): \"  <<iparam_old << std::endl;\n  app_log() << \" iParam (new): \"  <<iParam << std::endl;\n  app_log() << \" vParam (old): \"  <<vparam_old << std::endl;\n  app_log() << \" vParam (new): \"  <<vParam << std::endl;\n\n  app_log() << std::endl << \" Using branching cutoff scheme \" << branching_cutoff_scheme << std::endl;\n\n  app_log().flush();\n\n  //  return static_cast<int>(iParam[B_TARGETWALKERS]*1.01/static_cast<double>(nw_target));\n  return static_cast<int>(round(static_cast<double>(iParam[B_TARGETWALKERS]/static_cast<double>(nw_target))));\n}\n\nvoid SimpleFixedNodeBranch::checkParameters(MCWalkerConfiguration& w)\n{\n  std::ostringstream o;\n  if(!BranchMode[B_DMCSTAGE])\n  {\n    EstimatorRealType e, sigma2;\n    MyEstimator->getCurrentStatistics(w,e,sigma2);\n    vParam[B_ETRIAL]=vParam[B_EREF]=e;\n    vParam[B_SIGMA2]=sigma2;\n    EnergyHist.clear();\n    VarianceHist.clear();\n    //DMCEnergyHist.clear();\n    EnergyHist(vParam[B_EREF]);\n    VarianceHist(vParam[B_SIGMA2]);\n    //DMCEnergyHist(vParam[B_EREF]);\n    o << \"SimpleFixedNodeBranch::checkParameters \" << std::endl;\n    o << \"  Average Energy of a population  = \" << e << std::endl;\n    o << \"  Energy Variance = \" << vParam[B_SIGMA2] << std::endl;\n  }\n  app_log() << o.str() << std::endl;\n  app_log().flush();\n}\n\nvoid SimpleFixedNodeBranch::finalize(MCWalkerConfiguration& w)\n{\n  std::ostringstream o;\n  if(WalkerController)\n  {\n    o << \"====================================================\";\n    o << \"\\n  SimpleFixedNodeBranch::finalize after a DMC block\" ;\n    o << \"\\n    QMC counter                   = \" << iParam[B_COUNTER];\n    o << \"\\n    time step                     = \" << vParam[B_TAU];\n    o << \"\\n    effective time step           = \" << vParam[B_TAUEFF];\n    o << \"\\n    trial energy                  = \" << vParam[B_ETRIAL];\n    o << \"\\n    reference energy              = \" << vParam[B_EREF];\n    o << \"\\n    reference variance            = \" << vParam[B_SIGMA2];\n    o << \"\\n    target walkers                = \" << iParam[B_TARGETWALKERS];\n    o << \"\\n    branch cutoff                 = \" << vParam[B_BRANCHCUTOFF] << \" \" << vParam[B_BRANCHMAX];\n    o << \"\\n    Max and minimum walkers per node= \" << iParam[B_MAXWALKERS] << \" \" << iParam[B_MINWALKERS];\n    o << \"\\n    Feedback                      = \" << vParam[B_FEEDBACK];\n    o << \"\\n    QMC Status (BranchMode)       = \" << BranchMode;\n    o << \"\\n====================================================\";\n  }\n  //running RMC\n  else if (BranchMode[B_RMC])\n  {\n    o << \"====================================================\";\n    o << \"\\n  SimpleFixedNodeBranch::finalize after a RMC block\" ;\n    o << \"\\n    QMC counter                   = \" << iParam[B_COUNTER];\n    o << \"\\n    time step                     = \" << vParam[B_TAU];\n    o << \"\\n    effective time step           = \" << vParam[B_TAUEFF];\n    o << \"\\n    reference energy              = \" << vParam[B_EREF];\n    o << \"\\n    reference variance            = \" << vParam[B_SIGMA2];\n    o << \"\\n    cutoff energy                 = \" << vParam[B_BRANCHCUTOFF] << \" \" << vParam[B_BRANCHMAX];\n    o << \"\\n    QMC Status (BranchMode)       = \" << BranchMode;\n    o << \"\\n====================================================\";\n  }\n  else\n  {\n    //running VMC\n    EstimatorRealType e, sigma2;\n    //MyEstimator->getEnergyAndWeight(e,w,sigma2);\n    MyEstimator->getCurrentStatistics(w,e,sigma2);\n    vParam[B_ETRIAL]=vParam[B_EREF]=e;\n    vParam[B_SIGMA2]=sigma2;\n    //this is just to avoid diving by n-1  == 0\n    EnergyHist(vParam[B_EREF]);\n    //add Eref to the DMCEnergyHistory\n    //DMCEnergyHist(vParam[B_EREF]);\n    o << \"====================================================\";\n    o << \"\\n  SimpleFixedNodeBranch::finalize after a VMC block\" ;\n    o << \"\\n    QMC counter        = \" << iParam[B_COUNTER];\n    o << \"\\n    time step          = \" << vParam[B_TAU];\n    o << \"\\n    reference energy   = \" << vParam[B_EREF];\n    o << \"\\n    reference variance = \" << vParam[B_SIGMA2];\n    o << \"\\n====================================================\";\n  }\n  app_log() << o.str() << std::endl;\n  write(RootName,true);\n}\n\n/**  Parse the xml file for parameters\n *@param cur current xmlNode\n *@param LogOut std::ostream to which the run-time report is sent\n *\n * Few important parameters are:\n * <ul>\n * <li> en_ref: a reference energy\n * <li> num_gen: number of generations \\f$N_G\\f$ to reach  equilibrium, used in the feedback parameter\n * \\f$ feed = \\frac{1}{N_G \\tau} \\f$\n * </ul>\n */\nbool SimpleFixedNodeBranch::put(xmlNodePtr cur)\n{\n  //save it\n  myNode=cur;\n  //check dmc/vmc and decide to create WalkerControllerBase\n  m_param.put(cur);\n  reset();\n  MyEstimator->setCollectionMode(true); //always collect\n  return true;\n}\n\nvoid SimpleFixedNodeBranch::write(const std::string& fname, bool overwrite)\n{\n  RootName=fname;\n  if(MyEstimator->is_manager())\n  {\n    //\\since 2008-06-24\n    vParam[B_ACC_ENERGY]=EnergyHist.result();\n    vParam[B_ACC_SAMPLES]=EnergyHist.count();\n    BranchIO hh(*this,MyEstimator->getCommunicator());\n    bool success= hh.write(fname);\n  }\n}\n\n#ifdef HAVE_ADIOS\nvoid SimpleFixedNodeBranch::save_energy()\n{\n  if(MyEstimator->is_manager())\n  {\n    //\\since 2008-06-24\n    vParam[B_ACC_ENERGY]=EnergyHist.result();\n    vParam[B_ACC_SAMPLES]=EnergyHist.count();\n  }\n}\n#endif\n\n\nvoid SimpleFixedNodeBranch::read(const std::string& fname)\n{\n  BranchMode.set(B_RESTART,0);\n  if(fname.empty())\n    return;\n  vParam[B_ACC_ENERGY]=EnergyHist.result();\n  vParam[B_ACC_SAMPLES]=EnergyHist.count();\n  BranchIO hh(*this,MyEstimator->getCommunicator());\n  BranchModeType bmode(BranchMode);  \n  bool success=hh.read(fname);\n  if(success && R2Proposed.good() && bmode[B_POPCONTROL]==BranchMode[B_POPCONTROL])\n  {\n    BranchMode.set(B_RESTART,1);\n    app_log() << \"    Restarting, cummulative properties:\"\n              << \"\\n      energy     = \" << EnergyHist.mean()\n              << \"\\n      variance   = \" << VarianceHist.mean()\n              << \"\\n      r2accepted = \" << R2Accepted.mean()\n              << \"\\n      r2proposed = \" << R2Proposed.mean()\n              << std::endl;\n  }\n  else\n  {\n    if(BranchMode[B_POPCONTROL]!=bmode[B_POPCONTROL])\n    {\n      app_log() << \"  Population control method has changed from \" << BranchMode[B_POPCONTROL]\n        << \" to \" << bmode[B_POPCONTROL] << std::endl;\n      BranchMode[B_POPCONTROL]=bmode[B_POPCONTROL];\n    }\n  }\n\n  //char fname2[128];\n  //sprintf(fname2,\"%s.p%03d.config\",fname.c_str(),OHMMS::Controller->rank());\n  //ofstream fout(fname2);\n  //fout << \"    Restarting, cummulative properties:\"\n  //          << \"\\n      energy     = \" << EnergyHist.mean()\n  //          << \"\\n      variance   = \" << VarianceHist.mean()\n  //          << \"\\n      r2accepted = \" << R2Accepted.mean()\n  //          << \"\\n      r2proposed = \" << R2Proposed.mean()\n  //          << std::endl;\n  app_log().flush();\n}\n\n//   void SimpleFixedNodeBranch::storeConfigsForForwardWalking(MCWalkerConfiguration& w)\n//   {\n//     WalkerController->storeConfigsForForwardWalking(w);\n//   }\n//\n//   void SimpleFixedNodeBranch::clearConfigsForForwardWalking( )\n//   {\n//     WalkerController->clearConfigsForForwardWalking( );\n//   }\n//\n//   void SimpleFixedNodeBranch::debugFWconfig()\n//   {\n//     std::cout <<\"FW size \"<<WalkerController->sizeOfConfigsForForwardWalking()<< std::endl;\n//     for(int i=0;i<WalkerController->ForwardWalkingHistory.size();i++) {\n//       std::cout <<\" Next Gen \"<<i<< std::endl;\n//       for(int j=0;j<WalkerController->ForwardWalkingHistory[i].size();j++)\n//       {\n//         std::cout <<j<<\" \"<<WalkerController->ForwardWalkingHistory[i][j].ID<<\" \"<<WalkerController->ForwardWalkingHistory[i][j].ParentID<< std::endl;\n//       }\n//     }\n//   }\n\nvoid SimpleFixedNodeBranch::setBranchCutoff(EstimatorRealType variance, EstimatorRealType targetSigma, EstimatorRealType maxSigma, int Nelec)\n{\n  if(branching_cutoff_scheme==\"DRV\")\n  {\n    // eq.(3), J. Chem. Phys. 89, 3629 (1988).\n    // eq.(9), J. Chem. Phys. 99, 2865 (1993).\n    vParam[B_BRANCHCUTOFF]=2.0/std::sqrt(vParam[B_TAU]);\n  }\n  else if(branching_cutoff_scheme==\"ZSGMA\")\n  {\n    // eq.(6), Phys. Rev. B 93, 241118(R) (2016)\n    // do nothing if Nelec is not passed in.\n    if(Nelec>0)\n      vParam[B_BRANCHCUTOFF]=0.2*std::sqrt(Nelec/vParam[B_TAU]);\n  }\n  else if(branching_cutoff_scheme==\"YL\")\n  {\n    // a scheme from Ye Luo.\n    vParam[B_BRANCHCUTOFF]=std::sqrt(variance)*std::min(targetSigma, std::sqrt(1.0/vParam[B_TAU]));\n  }\n  else if(branching_cutoff_scheme==\"classic\")\n  {\n    // default QMCPACK choice which is the same as v3.0.0 and before.\n    vParam[B_BRANCHCUTOFF]=std::min(std::max(variance*targetSigma, maxSigma), 2.5/vParam[B_TAU]);\n  }\n  else\n    APP_ABORT(\"SimpleFixedNodeBranch::setBranchCutoff unknown branching cutoff scheme \"+branching_cutoff_scheme);\n\n  vParam[B_BRANCHMAX]=vParam[B_BRANCHCUTOFF]*1.5;\n  vParam[B_BRANCHFILTER]=1.0/(vParam[B_BRANCHMAX]-vParam[B_BRANCHCUTOFF]);\n}\n\n}\n\n\n", "meta": {"hexsha": "a47ee76bc11ecd477c2dafa49c064b7aaecab4ee", "size": 33159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/QMCDrivers/SimpleFixedNodeBranch.cpp", "max_stars_repo_name": "bwvdg/qmcpack", "max_stars_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/QMCDrivers/SimpleFixedNodeBranch.cpp", "max_issues_repo_name": "bwvdg/qmcpack", "max_issues_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T15:33:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T15:35:59.000Z", "max_forks_repo_path": "src/QMCDrivers/SimpleFixedNodeBranch.cpp", "max_forks_repo_name": "bwvdg/qmcpack", "max_forks_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T17:44:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T17:44:39.000Z", "avg_line_length": 38.6468531469, "max_line_length": 153, "alphanum_fraction": 0.6475165114, "num_tokens": 9554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069437044942166, "lm_q2_score": 0.042722195565898485, "lm_q1q2_score": 0.013273545655563903}}
{"text": "#pragma once\n\n#include \"multibrot_parallel_calculator.h\"\n\n#include <boost/compute.hpp>\n#include <chrono>\n\n#include \"utils/utils.h\"\n\ntemplate <typename P>\nconst Duration MultibrotParallelCalculator<P>::target_execution_time_ =\n    Duration(std::chrono::seconds(1));\n\ntemplate <typename P>\nMultibrotParallelCalculator<P>::MultibrotParallelCalculator(size_t width_pix, size_t height_pix)\n    : partitioner_(width_pix, height_pix, fragment_width_pix_, fragment_height_pix_),\n      width_pix_(width_pix),\n      height_pix_(height_pix) {\n    std::vector<boost::compute::device> devices;\n    {\n        std::vector<boost::compute::device> cpus, gpus;\n        for (const auto& platform : boost::compute::system::platforms()) {\n            if (use_cpus_) {\n                Utils::AppendVectorToVector(cpus, platform.devices(CL_DEVICE_TYPE_CPU));\n            }\n            if (use_gpus_) {\n                Utils::AppendVectorToVector(gpus, platform.devices(CL_DEVICE_TYPE_GPU));\n            }\n        }\n        if (!cpus.empty())  // We have at least one CPU device\n        {\n            if (reserve_1_cpu_thread_) {\n                // Split device into two - the first one contains all minus one compute units,\n                // it is then added to devices list\n                std::vector<boost::compute::device> split_cpu =\n                    cpus[0].partition_by_counts({cpus[0].compute_units() - 1, 1});\n                EXCEPTION_ASSERT(split_cpu.size() == 2);\n                devices.push_back(split_cpu[0]);\n            } else {\n                devices.push_back(cpus[0]);  // Add first CPU device as is\n            }\n            // Add all other CPU devices\n            devices.insert(devices.end(), cpus.begin() + 1, cpus.end());\n        }\n        // Add all GPUs\n        Utils::AppendVectorToVector(devices, gpus);\n    }\n\n    for (auto& device : devices) {\n        // TODO implement automatic resizing of memory buffers?\n        device_states_.emplace(device, DeviceState(device));\n    }\n}\n\ntemplate <typename P>\nstd::complex<double> MultibrotParallelCalculator<P>::CalcComplexVal(\n    std::complex<double> input_min, std::complex<double> input_max, size_t x, size_t y) {\n    return input_min + std::complex<double>{\n        (input_max.real() - input_min.real()) * x / width_pix_,\n        (input_max.imag() - input_min.imag()) * y / height_pix_,\n    };\n}\n\ntemplate <typename P>\nvoid MultibrotParallelCalculator<P>::Calculate(\n    std::complex<double> input_min, std::complex<double> input_max, double power,\n    int max_iterations, Callback cb) {\n    partitioner_.Reset();\n\n    CalculateFirstPhase(input_min, input_max, power, max_iterations, cb);\n\n    // Process all remaining operations\n    for (auto& device_state : device_states_) {\n        if (device_state.second.prev_operation_info) {\n            ProcessOperationResults(device_state, cb);\n        }\n    }\n}\n\ntemplate <typename P>\nvoid MultibrotParallelCalculator<P>::CalculateFirstPhase(\n    std::complex<double> input_min, std::complex<double> input_max, double power,\n    int max_iterations, Callback cb) {\n    // TODO implement some more reliable check to prevent infinite loops?\n    while (1) {\n        for (auto& device_state : device_states_) {\n            if (device_state.second.prev_operation_info) {\n                if (device_state.second.prev_operation_info.value().copy_event.status() ==\n                    CL_COMPLETE) {\n                    ProcessOperationResults(device_state, cb);\n                }\n            } else {\n                size_t fragment_count = starting_fragment_count_;\n                if (device_state.second.prev_operations_duration_sum > Duration()) {\n                    fragment_count =\n                        (device_state.second.processed_pixels / fragment_size_pix_) *\n                        (target_execution_time_ / device_state.second.prev_operations_duration_sum);\n                    fragment_count =\n                        std::min(fragment_count, max_segment_size_pix_ / fragment_size_pix_);\n                }\n                ImagePartitioner::Segment segment = partitioner_.Partition(fragment_count);\n                if (segment.IsEmpty()) {\n                    // No more work to assign, first phase is finished.\n                    return;\n                }\n\n                device_state.second.prev_operation_info =\n                    PrevOperationInfo{boost::compute::event(), boost::compute::event(), segment};\n                std::complex<double> min =\n                    CalcComplexVal(input_min, input_max, segment.x, segment.y);\n                std::complex<double> max = CalcComplexVal(\n                    input_min, input_max, segment.x + segment.width_pix,\n                    segment.y + segment.height_pix);\n                auto future = device_state.second.calculator.Calculate(\n                    min, max, segment.width_pix, segment.height_pix, power, max_iterations,\n                    device_state.second.output_vector.begin(),\n                    &device_state.second.prev_operation_info.value().calc_event);\n                device_state.second.prev_operation_info.value().copy_event = future.get_event();\n            }\n        }\n    }\n}\n\ntemplate <typename P>\nvoid MultibrotParallelCalculator<P>::ProcessOperationResults(\n    std::pair<const boost::compute::device, DeviceState>& device_info, Callback cb) {\n    PrevOperationInfo& info = device_info.second.prev_operation_info.value();\n    // Checking event status is not a synchronization point (OpenCL 2.2. Reference p.196),\n    // so wait until it finishes completely\n    info.copy_event.wait();\n\n    cb(device_info.first, info.segment, device_info.second.output_vector.data());\n\n    // Collect statistics for previous operation\n    device_info.second.prev_operations_duration_sum +=\n        Duration(info.calc_event) + Duration(info.copy_event);\n    device_info.second.processed_pixels += info.segment.width_pix * info.segment.height_pix;\n    device_info.second.prev_operation_info = boost::optional<PrevOperationInfo>();\n}\n", "meta": {"hexsha": "37c0b86a5140f1243a5962bf850b2cd9a74c260e", "size": 6016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multibrot_opencl/multibrot_parallel_calculator.cpp", "max_stars_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_stars_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multibrot_opencl/multibrot_parallel_calculator.cpp", "max_issues_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_issues_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multibrot_opencl/multibrot_parallel_calculator.cpp", "max_forks_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_forks_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9714285714, "max_line_length": 100, "alphanum_fraction": 0.6354720745, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882834101888134, "lm_q2_score": 0.027169234095729244, "lm_q1q2_score": 0.013266286276480858}}
{"text": "/*!\n* \\file Particle.hpp\n* \\brief Particle structure\n* \\author Tycho Tatitscheff\n* \\version 1.0\n* \\date 16 février 2017\n*\n* Define a structure containing all field that a fluid particle may contain.\n */\n\n#pragma once\n\n#include <map>\n#include <memory>\n#include <vector>\n#include <armadillo>\n\n#include \"utils/macros.hpp\"\n#include \"kernel/Kernel.hpp\"\n#include \"kernel/KernelPoly6.hpp\"\n#include \"kernel/KernelSpiky.hpp\"\n#include \"kernel/KernelViscosity.hpp\"\n\n#include \"common/Fluid.hpp\"\n#include \"common/Force.hpp\"\n\nusing namespace arma;\nusing namespace std;\n\n/**\n * \\struct Particle\n * \\brief Particle structure\n *\n * This structure contains all parameter carried by the fluid :\n *  - the position\n *  - the speed\n *  - the accelaration\n *  - the force applied\n *  - the mass\n *  - a pointer to the fluid\n */\nclass Particle {\n  public:\n    Particle(double r,\n             shared_ptr<Fluid> flu,\n             shared_ptr<listForces> f,\n             shared_ptr<KernelPoly6> fKern,\n             shared_ptr<KernelSpiky> pKern,\n             shared_ptr<KernelViscosity> vKern,\n             shared_ptr<KernelPoly6> sKern,\n             int id,\n             VEC pos,\n             VEC spe,\n             VEC acc);\n    Particle(double r,\n             shared_ptr<Fluid> flu,\n             shared_ptr<listForces> f,\n             shared_ptr<KernelPoly6> fKern,\n             shared_ptr<KernelSpiky> pKern,\n             shared_ptr<KernelViscosity> vKern,\n             shared_ptr<KernelPoly6> sKern,\n             int id);\n\n    void updateField(vector<shared_ptr<Particle>> neighb);\n    void updateForce(vector<shared_ptr<Particle>> neighb);\n\n    shared_ptr<Fluid> flu; // réference vers un fluid\n    shared_ptr<KernelPoly6> fieldKernel;\n    shared_ptr<KernelSpiky> pressureKernel;\n    shared_ptr<KernelPoly6> surfaceKernel;\n    shared_ptr<KernelViscosity> viscosityKernel;\n\n    // Particule caracteristic\n    double rad; // rayon\n    double mass; // masse de la particule\n\n    // Pressure related field\n    double density;\n    double pressure;\n\n    // Colour field\n    double colour;\n    double colourLaplacian;\n    VEC colourDirection;\n\n    // Position\n    VEC curr_pos;\n    VEC next_pos;\n\n    // Speed\n    // prev_half and next_half are for leapfrog\n    VEC prev_half_spe;\n    VEC curr_spe;\n    VEC next_half_spe;\n    VEC next_spe;\n\n    // Accélération\n    VEC curr_acc;\n    VEC next_acc;\n\n    // Force\n    VEC result_force;\n    shared_ptr<listForces> ext_forces;\n\n    VEC pressure_force;\n    VEC viscosity_force;\n    VEC surfaceTension_force;\n\n    int id;\n};\n\ninline bool operator<(const Particle& lhs, const Particle& rhs) {\n    return lhs.id < rhs.id;\n}\n\ninline bool operator==(const Particle& lhs, const Particle& rhs) {\n    return lhs.id == rhs.id;\n}", "meta": {"hexsha": "175747f555ec8ecdc86905a25db6c65507ec9000", "size": 2734, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "headers/sph/Particle.hpp", "max_stars_repo_name": "tychota/pje-sph", "max_stars_repo_head_hexsha": "cd0ac42fb2c78fe1b2be263b1141e6bf8e56b19f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "headers/sph/Particle.hpp", "max_issues_repo_name": "tychota/pje-sph", "max_issues_repo_head_hexsha": "cd0ac42fb2c78fe1b2be263b1141e6bf8e56b19f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "headers/sph/Particle.hpp", "max_forks_repo_name": "tychota/pje-sph", "max_forks_repo_head_hexsha": "cd0ac42fb2c78fe1b2be263b1141e6bf8e56b19f", "max_forks_repo_licenses": ["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.1694915254, "max_line_length": 76, "alphanum_fraction": 0.6547183614, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583475, "lm_q2_score": 0.027169233603412266, "lm_q1q2_score": 0.013266285631459828}}
{"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\n#include <vector>\n#include <unordered_map>\n#include <ctime>\n#include <boost/function.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/bind.hpp>\n\n#include \"config/package_revision_autogenerated.hpp\"\n\n#include \"metro/constants.hpp\"\n#include \"metro/ShotgunStochasticSearch.hpp\"\n#include \"metro/regression/Design.hpp\"\n#include \"metro/regression/Logistic.hpp\"\n#include \"metro/IndependentParameterDistribution.hpp\"\n#include \"metro/distributions/LogF.hpp\"\n#include \"metro/distributions/Flat.hpp\"\n#include \"metro/regression/LogUnnormalisedPosterior.hpp\"\n#include \"metro/intersect_ranges.hpp\"\n#include \"metro/fit_model.hpp\"\n#include \"metro/CholeskyStepper.hpp\"\n#include \"metro/SampleRange.hpp\"\n#include \"metro/log_sum_exp.hpp\"\n\n#include \"appcontext/CmdLineOptionProcessor.hpp\"\n#include \"appcontext/ApplicationContext.hpp\"\n\n#include \"genfile/MissingValue.hpp\"\n#include \"genfile/bgen/View.hpp\"\n#include \"genfile/bgen/Query.hpp\"\n#include \"genfile/SNPDataSource.hpp\"\n#include \"genfile/db/Error.hpp\"\n#include \"genfile/ToGP.hpp\"\n#include \"genfile/CrossCohortCovariateValueMapping.hpp\"\n#include \"genfile/CommonSNPFilter.hpp\"\n#include \"genfile/VariantIdentifyingDataFilteringSNPDataSource.hpp\"\n\n#include \"qcdb/FlatFileMultiVariantOutputter.hpp\"\n\nnamespace bfs = boost::filesystem ;\n\n// #define DEBUG 1\n// #define DEBUG_DOSAGESTORE 1\n\nnamespace globals {\n\tstd::string const program_name = \"multifinemap\" ;\n\tstd::string const program_version = package_version ;\n\tstd::string const program_revision =  std::string( package_revision ).substr( 0, 7 ) ;\n}\n\nnamespace {\n\tstd::string print_state( std::size_t N, std::vector< std::size_t > const& states ) {\n\t\tstd::string result = \"[\";\n\t\tstd::size_t begin = 0 ;\n\t\tfor( std::size_t i = 0; i <= states.size(); ++i ) {\n\t\t\tstd::size_t end = (i==states.size()) ? N : states[i] ;\n\t\t\tfor( std::size_t j = begin; j < end; ++j ) {\n\t\t\t\tresult.push_back( '0' ) ;\n\t\t\t}\n\t\t\tif( end != N ) {\n\t\t\t\tresult.push_back( '1' ) ;\n\t\t\t}\n\t\t\tbegin = end+1 ;\n\t\t}\n\t\tresult += ']' ;\n\t\treturn result ;\n\t}\n}\n\nstruct MFMOptions: public appcontext::CmdLineOptionProcessor\n{\npublic:\n\tstd::string get_program_name() const { return globals::program_name ; }\n\n\tvoid declare_options( appcontext::OptionProcessor& options ) {\n\t\t// Meta-options\n\t\toptions.set_help_option( \"-help\" ) ;\n\t\toptions.set_spec_option( \"-spec\" ) ;\n\n\t\t// File options\n\t\toptions.declare_group( \"Input file options\" ) ;\n\t    options[ \"-g\" ]\n\t        .set_description( \t\"Path to BGEN file giving genotypes.\" )\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 1 )\n\t\t\t.set_maximum_multiplicity( 1 ) ;\n\t    options[ \"-filetype\" ]\n\t\t\t.set_description(\n\t\t\t\t\"Specify the filetype of the genotype files specified by -g. \"\n\t\t\t\t\"By default, qctool will guess the file type.  Use this option to override that guess. \"\n\t\t\t\t\"Possible types are: \\\"\" + genfile::string_utils::join( genfile::SNPDataSource::get_file_types(), \"\\\",\\\"\" ) + \"\\\".\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( \"guess\" ) ;\n\n\t    options[ \"-assume-chromosome\" ]\n\t        .set_description( \"Chromosome to assume if not in genetic data.\" )\n\t\t\t.set_takes_single_value() ;\n\t    options[ \"-s\" ]\n\t        .set_description( \"Path of sample file to input.  If specified, this option must occur as often as the -g option\"\n\t\t\t\t\t\t\t\" to specify one sample file per cohort.\" )\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 1 )\n\t\t\t.set_maximum_multiplicity( 1000 ) ;\n\t\toptions[ \"-outcome\" ]\n\t\t\t.set_description( \"Name of column containing outcome.  Currently must be a binary outcome.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_is_required() ;\n\t\t\n\t\toptions.declare_group( \"Input filtering options\" ) ;\n\t\toptions[ \"-incl-range\" ]\n\t\t\t.set_description( \"Specify a range of SNPs (or comma-separated list of ranges of SNPs) to operate on. \"\n\t\t\t\t\"Each range should be in the format CC:xxxx-yyyy where CC is the chromosome and xxxx and yyyy are the \"\n\t\t\t\t\"start and end coordinates, or just xxxx-yyyy which matches that range from all chromosomes. \"\n\t\t\t\t\"You can also omit either of xxxx or yyyy to get all SNPs from the start or to the end of a chromosome.\" )\n\t\t\t.set_takes_values_until_next_option() ;\n\t\toptions[ \"-excl-range\" ]\n\t\t\t.set_description( \"Specify a range of SNPs (or comma-separated list of ranges of SNPs) to exclude from operation. \"\n\t\t\t\t\"Each range should be in the format CC:xxxx-yyyy where CC is the chromosome and xxxx and yyyy are the \"\n\t\t\t\t\"start and end coordinates, or just xxxx-yyyy which matches that range from all chromosomes. \"\n\t\t\t\t\"You can also omit either of xxxx or yyyy to get all SNPs from the start or to the end of a chromosome.\" )\n\t\t\t.set_takes_values_until_next_option() ;\n\t\toptions[ \"-incl-ranges\" ]\n\t\t\t.set_description( \"Like -incl-range, but read the ranges from the specified file.\"\n\t\t\t\t\"The file must contain a whitespace-separated list of genomic ranges to include in the analysis.\" )\n\t\t\t.set_takes_values_until_next_option() ;\n\t\toptions[ \"-excl-ranges\" ]\n\t\t\t.set_description( \"Like -excl-range, but read the ranges from the specified file.\"\n\t\t\t\t\"The file must contain a whitespace-separated list of genomic ranges to exclude from the analysis.\" )\n\t\t\t.set_takes_values_until_next_option() ;\n\t\t\n\t\toptions.declare_group( \"Output file options\" ) ;\n\t\toptions[ \"-o\" ]\n\t\t\t.set_description( \"Path to output file.  Use \\\"-\\\" for stdout.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( \"-\" ) ;\n\n\t\toptions.declare_group( \"Model options\" ) ;\n\t\toptions[ \"-incl-samples\"]\n\t\t\t.set_description( \"Filter out samples whose sample ID does not lie in the given file(s).\")\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-excl-samples\"]\n\t\t\t.set_description( \"Filter out samples whose sample ID lies in the given file.\")\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-incl-samples-where\"]\n\t\t\t.set_description( \"Include samples by specifying conditions on the values of columns in the sample file.\")\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-excl-samples-where\"]\n\t\t\t.set_description( \"Exclude samples by specifying conditions on the values of columns in the sample file.\")\n\t\t\t.set_takes_values( 1 )\n\t\t\t.set_minimum_multiplicity( 0 )\n\t\t\t.set_maximum_multiplicity( 100 ) ;\n\t\toptions[ \"-minimum-allele-count\" ]\n\t\t\t.set_description( \"Skip predictors that have less than this minor allele count\" )\n\t\t\t.set_takes_values(1)\n\t\t\t.set_default_value( 10 ) ;\n\t\toptions[ \"-covariates\" ]\n\t\t\t.set_description( \"Specify the name of one or more covariates to include in the model.\"\n\t\t\t\t\" These must be columns named in the sample file.\" )\n\t\t\t.set_takes_values_until_next_option() ;\n\t\t\t\n\t\toptions.declare_group( \"Model fitting options\" ) ;\n\t\toptions[ \"-tolerance\" ]\n\t\t\t.set_description( \"Tolerance to use when model fitting\" )\n\t\t\t.set_takes_values(1)\n\t\t\t.set_default_value( 0.001 ) ;\n\t\toptions[ \"-max-iterations\" ]\n\t\t\t.set_description( \"Maximum iterations to allow when model fitting\" )\n\t\t\t.set_takes_values(1)\n\t\t\t.set_default_value( 100 ) ;\n\t\toptions[ \"-max-causal-variants\" ]\n\t\t\t.set_description( \"Set the maximum number of variants allowed in a causal configuration\")\n\t\t\t.set_takes_values(1)\n\t\t\t.set_default_value(5)\n\t\t;\n\t\toptions[ \"-additive\" ]\n\t\t\t.set_description( \"Specify that only additive effects are allowed for\" ) ;\n\t\t;\n\t\toptions.declare_group( \"Miscellaneous options\" ) ;\n\t\toptions[ \"-analysis-name\" ]\n\t\t\t.set_description( \"Specify a name to label results from this analysis with.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( \"qctool analysis\" ) ;\n\t\toptions[ \"-analysis-chunk\" ]\n\t\t\t.set_description( \"Specify a name denoting the current genomic region or chunk on which this is run.  This is intended for use in parallel environments.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( genfile::MissingValue() ) ;\n\t\toptions.declare_group( \"Miscellaneous options\" ) ;\n\t\toptions[ \"-debug\" ]\n\t\t\t.set_description( \"Output debugging information.\" ) ;\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} ;\n\nstruct DosageStore {\npublic:\n\ttypedef boost::function< void( std::size_t const, boost::optional< std::size_t > const ) > ProgressCallback ;\n\ttypedef std::unique_ptr< DosageStore > UniquePtr ;\n\n\tstatic UniquePtr create() {\n\t\treturn UniquePtr( new DosageStore() ) ;\n\t}\npublic:\n\tDosageStore() {}\n\t\n\tvoid load( genfile::SNPDataSource::UniquePtr source, ProgressCallback callback ) {\n\t\tload_unsafe( *source, callback ) ;\n\t}\n\t\n\tstd::size_t number_of_samples() const { return m_ploidy[0].size() ; }\n\tstd::size_t number_of_variants() const { return m_variants.size() ; }\n\tgenfile::VariantIdentifyingData const& variant( std::size_t i ) const { return m_variants[i] ; }\n\n\tstd::size_t estimate_memory_usage() const {\n\t\tstd::size_t result = 0 ;\n\t\tfor( std::size_t i = 0; i < m_variants.size(); ++i ) {\n\t\t\tresult += m_variants[i].estimate_bytes_used() ;\n\t\t\tresult += m_ploidy[i].size() ;\n\t\t\tresult += m_AB[i].size() ;\n\t\t\tresult += m_BB[i].size() ;\n\t\t}\n\t\treturn result ;\n\t}\n\t\n\tstd::string get_summary() const {\n\t\tusing boost::format ;\n\t\treturn (\n\t\t\tboost::format( \"DosageStore: %d variants, %d samples, approx %.2fMb memory usage.\\n\" )\n\t\t\t\t% m_variants.size()\n\t\t\t\t% (m_variants.size() > 0 ? m_AB[0].size() : 0 )\n\t\t\t\t% (estimate_memory_usage() / 1000000.0)\n\t\t).str() ;\n\t}\n\t\n\tgenfile::VariantIdentifyingData const get_variant( std::size_t i ) const {\n\t\tassert( i < m_variants.size() ) ;\n\t\treturn m_variants[i] ;\n\t}\n\t\n\ttemplate< typename Callback >\n\tvoid get_dosages( std::size_t i, Callback callback ) const {\n\t\tassert( i < m_variants.size() ) ;\n\t\tdouble const constant = double(0xFFFFFFFF >> 24) ;\n\t\tassert( i < m_variants.size() ) ;\n\t\tfor( std::size_t j = 0; j < m_AB[i].size(); ++j ) {\n\t\t\t// unpack 8 bit bgen encoding\n#if DEBUG_DOSAGESTORE\n\t\t\tif( j < 10 ) {\n\t\t\t\tstd::cerr << \"get_dosages(): \" << j << \": \" << int( m_AB[i][j] ) << \", \" << int( m_BB[i][j] ) << \".\\n\" ;\n\t\t\t}\n#endif\n\t\t\tcallback( j, double( m_AB[i][j] ) / constant, double( m_BB[i][j] ) / constant ) ;\n\t\t}\n\t}\n\t\n\tstd::vector< metro::SampleRange > const nonmissing_samples( std::size_t i ) const {\n\t\tassert( i < m_variants.size() ) ;\n\t\treturn m_nonmissing_samples[i] ;\n\t}\n\nprivate:\n\n\t/* Store genotype probabilities in 8 bit, BGEN-like encoding */\n\tstruct DosageSetter {\n\t\tDosageSetter(\n\t\t\tstd::vector< uint8_t >* ploidy,\n\t\t\tstd::vector< uint8_t >* AB,\n\t\t\tstd::vector< uint8_t >* BB\n\t\t):\n\t\t\tm_ploidy( ploidy ),\n\t\t\tm_AB( AB ),\n\t\t\tm_BB( BB ),\n\t\t\tm_bits(8),\n\t\t\tm_constant( double(0xFFFFFFFF >> (32 - m_bits))),\n\t\t\tm_sample_i(0),\n\t\t\tm_order_type( genfile::eUnknownOrderType )\n\t\t{}\n\t\t\n\t\tvoid initialise( std::size_t nSamples, std::size_t nAlleles ) {\n\t\t\tassert( nAlleles == 2 ) ;\n\t\t\tm_ploidy->resize( nSamples ) ;\n\t\t\tstd::fill( m_ploidy->begin(), m_ploidy->end(), 0x80 ) ;\n\t\t\tm_AB->resize( nSamples ) ;\n\t\t\tstd::fill( m_AB->begin(), m_AB->end(), 0 ) ;\n\t\t\tm_BB->resize( nSamples ) ;\n\t\t\tstd::fill( m_BB->begin(), m_BB->end(), 0 ) ;\n\t\t\tm_last_nonmissing_sample_i = 0 ;\n\t\t}\n\n\t\tbool set_sample( std::size_t n ) {\n\t\t\tm_sample_i = n ;\n\t\t\tm_order_type = genfile::eUnknownOrderType ;\n\t\t\treturn true ;\n\t\t}\n\n\t\tvoid set_number_of_entries(\n\t\t\tuint32_t ploidy, std::size_t n,\n\t\t\tgenfile::OrderType const order_type,\n\t\t\tgenfile::ValueType const value_type\n\t\t) {\n\t\t\tassert( ploidy <= 2 ) ;\n\t\t\tassert( (order_type == genfile::ePerOrderedHaplotype || genfile::ePerUnorderedGenotype) && value_type == genfile::eProbability ) ;\n\t\t\t(*m_ploidy)[m_sample_i] = ploidy ;\n\t\t\tm_order_type = order_type ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, genfile::MissingValue const value ) {\n\t\t\tuint8_t& ploidy = (*m_ploidy)[m_sample_i] ;\n\t\t\tuint8_t& AB = (*m_AB)[m_sample_i] ;\n\t\t\tuint8_t& BB = (*m_BB)[m_sample_i] ;\n\t\t\tploidy |= 0x80 ;\n\t\t\tAB = BB = 0 ;\n\t\t\trecord_missing_sample( m_sample_i ) ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, double const value ) {\n\t\t\tuint8_t& ploidy = (*m_ploidy)[m_sample_i] ;\n\t\t\tuint8_t& AB = (*m_AB)[m_sample_i] ;\n\t\t\tuint8_t& BB = (*m_BB)[m_sample_i] ;\n\n#if DEBUG_DOSAGESTORE\n\t\t\tif( m_sample_i < 10 ) {\n\t\t\t\tstd::cerr << \"DosageSetter::set_value(): \" << m_sample_i << \", \" << entry_i << \": \" << value << \".\\n\" ;\n\t\t\t}\n#endif\n\t\t\tif( !(ploidy & 0x80) ) {\n\t\t\t\tif( entry_i == 1 ) {\n\t\t\t\t\tAB = value * m_constant ;\n\t\t\t\t} else if (entry_i == 2 ) {\n\t\t\t\t\tBB = value * m_constant ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, genfile::Integer const value ) {\n\t\t\tassert(0) ; // expecting GT field\n\t\t}\n\n\t\tvoid finalise() {\n\t\t\t// add the final sample range if needed.\n\t\t\trecord_missing_sample( m_ploidy->size() ) ;\n\t\t}\n\t\t\n\t\tstd::vector< metro::SampleRange > const nonmissing_samples() { return m_nonmissing_samples ; }\n\t\t\n\t\tprivate:\n\t\t\tstd::vector< uint8_t >* m_ploidy ;\n\t\t\tstd::vector< uint8_t >* m_AB ;\n\t\t\tstd::vector< uint8_t >* m_BB ;\n\t\t\tuint32_t m_bits ;\n\t\t\tdouble m_constant ;\n\t\t\tstd::size_t m_sample_i ;\n\t\t\tstd::size_t m_last_nonmissing_sample_i ;\n\t\t\tgenfile::OrderType m_order_type ;\n\t\t\tstd::vector< metro::SampleRange > m_nonmissing_samples ;\n\t\t\t\n\t\tvoid record_missing_sample( std::size_t sample_i ) {\n\t\t\tif( sample_i >= m_last_nonmissing_sample_i ) {\n\t\t\t\tm_nonmissing_samples.push_back(\n\t\t\t\t\tmetro::SampleRange( m_last_nonmissing_sample_i, m_sample_i )\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tm_last_nonmissing_sample_i = sample_i + 1 ;\n\t\t}\n\t} ;\n\n\tvoid load_unsafe( genfile::SNPDataSource& source, ProgressCallback callback ) {\n\t\tif( source.total_number_of_snps() ) {\n\t\t\tstd::size_t N = *source.total_number_of_snps() ;\n\t\t\tm_variants.reserve( N ) ;\n\t\t\tm_ploidy.reserve( N ) ;\n\t\t\tm_AB.reserve( N ) ;\n\t\t\tm_BB.reserve( N ) ;\n\t\t}\n\n\t\tgenfile::VariantIdentifyingData variant ;\n\t\tstd::vector< uint16_t > data ;\n\t\tstd::size_t count = 0 ;\n\t\tstd::vector< uint8_t > ploidy, AB, BB ;\n\t\t\n\t\twhile( source.get_snp_identifying_data( &variant )) {\n\t\t\t// ok, read dosages.\n\t\t\tstd::cerr << \"LOADING \" << variant << \".\\n\" ;\n\t\t\tDosageSetter setter( &ploidy, &AB, &BB ) ;\n\t\t\tsource.read_variant_data()->get( \":genotypes:\", genfile::to_GP_unphased( setter ) ) ;\n\t\t\tm_variants.push_back( variant ) ;\n\t\t\tm_nonmissing_samples.push_back( setter.nonmissing_samples() ) ;\n\t\t\tm_ploidy.push_back( ploidy ) ;\n\t\t\tm_AB.push_back( AB ) ;\n\t\t\tm_BB.push_back( BB ) ;\n\t\t\t//m_data.push_back( data ) ;\n\t\t\tif( callback ) {\n\t\t\t\tcallback( ++count, source.total_number_of_snps() ) ;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tstd::vector< genfile::VariantIdentifyingData > m_variants ;\n\t// To avoid using too much space, we encode dosage data as 16-bit integer\n\t// and expand to required format when requested.\n\tstd::vector< std::vector< metro::SampleRange > > m_nonmissing_samples ;\n\tstd::vector< std::vector< uint8_t > > m_ploidy ;\n\tstd::vector< std::vector< uint8_t > > m_AB ;\n\tstd::vector< std::vector< uint8_t > > m_BB ;\n} ;\n\nstruct MFMApplication: public appcontext::ApplicationContext {\n\tMFMApplication( int argc, char** argv ):\n\t\tappcontext::ApplicationContext(\n\t\t\tglobals::program_name,\n\t\t\t\"version: \" + globals::program_version + \", revision: \" + globals::program_revision,\n\t\t\tstd::auto_ptr< appcontext::OptionProcessor >( new MFMOptions ),\n\t\t\targc,\n\t\t\targv,\n\t\t\t\"-log\"\n\t\t)\n\t{\n\t\tprocess() ;\n\t}\n\t\nprivate:\n\t\n\tvoid process() {\n\t\ttry {\n\t\t\tunsafe_process() ;\n\t\t} catch( genfile::InputError const& e ) {\n\t\t\tui().logger() << \"!! Error (\" << e.what() << \"): \" << e.format_message() << \".\\n\" ;\n\t\t\tthrow appcontext::HaltProgramWithReturnCode( -1 ) ;\n\t\t}\n\t\tcatch( genfile::FileNotFoundError const& e ) {\n\t\t\tui().logger() << \"\\nError: No file matching \\\"\" << e.filespec() << \"\\\" could be found.\\n\" ;\n\t\t\tthrow appcontext::HaltProgramWithReturnCode( -1 ) ;\n\t\t}\n\t\tcatch( genfile::db::Error const& e ) {\n\t\t\tui().logger() << \"!! Error (\" << e.what() << \") with the following statement: \\\"\"\n\t\t\t\t<< e.sql()\n\t\t\t\t<< \"\\\".\\n\" ;\n\t\t\tthrow appcontext::HaltProgramWithReturnCode( -1 ) ;\n\t\t}\n\t}\n\t\n\tvoid unsafe_process() {\n\t\tDosageStore::UniquePtr store = load_genotypes() ;\n\n\t\tgenfile::CohortIndividualSource::UniquePtr\n\t\t\tsamples = genfile::CohortIndividualSource::create( options().get< std::string >( \"-s\" ) ) ;\n\n\t\tmetro::regression::LogLikelihood::UniquePtr\n\t\t\tll = create_loglikelihood( samples->size() ) ;\n\n\t\tif( options().check( \"-covariates\" )) {\n\t\t\tadd_covariates( ll->design(), *samples, options().get_values< std::string >( \"-covariates\" ) ) ;\n\t\t}\n\t\n\t\tset_outcome( *ll, *samples, options().get_value< std::string >( \"-outcome\" )) ;\n\n\t\tstd::cerr << ll->design().get_summary() << \"\\n\" ;\n\n\t\trun_search( *store, *ll ) ;\n\t}\n\t\n\tDosageStore::UniquePtr load_genotypes() {\n\t\tappcontext::UIContext::ProgressContext progress_context = ui().get_progress_context( \"Loading data\" ) ;\n\t\tDosageStore::UniquePtr store = DosageStore::create() ;\n\t\tstore->load(\n\t\t\topen_snp_data_source( options().get< std::string >( \"-g\" ) ),\n\t\t\tprogress_context\n\t\t) ;\n\t\tui().logger() << store->get_summary() ;\n\t\treturn store ;\n\t}\n\t\n\tgenfile::SNPDataSource::UniquePtr\n\topen_snp_data_source( std::string const& filename ) const {\n\t\tgenfile::Chromosome chromosome_hint ;\n\t\tstd::string chromosome_indicator ;\n\t\tif( options().check_if_option_was_supplied( \"-assume-chromosome\" )) {\n\t\t\tchromosome_indicator = options().get_value< std::string >( \"-assume-chromosome\" ) ;\n\t\t}\n\t\tif( chromosome_indicator != \"\" ) {\n\t\t\tchromosome_hint = chromosome_indicator ;\n\t\t}\n\n\t\tgenfile::SNPDataSource::UniquePtr source ;\n\n\t\tstd::pair< std::string, std::string > uf = genfile::uniformise( filename ) ;\n\n\t\t{\n\t\t\tboost::optional< genfile::vcf::MetadataParser::Metadata > metadata ;\n//\t\t\tif( m_options.check( \"-metadata\" )) {\n//\t\t\t\tmetadata = genfile::vcf::StrictMetadataParser(\n//\t\t\t\t\tm_options.get_value< std::string >( \"-metadata\" )\n//\t\t\t\t).get_metadata() ;\n//\t\t\t}\n\t\t\tsource = genfile::SNPDataSource::create(\n\t\t\t\tfilename,\n\t\t\t\tchromosome_hint,\n\t\t\t\tmetadata,\n\t\t\t\toptions().get< std::string >( \"-filetype\" )\n\t\t\t) ;\n\t\t}\n\t\t\n\t\tgenfile::CommonSNPFilter::UniquePtr snp_filter = construct_snp_filter() ;\n\t\t// Filter SNPs if necessary\n\t\tif( snp_filter.get() ) {\n\t\t\tgenfile::VariantIdentifyingDataFilteringSNPDataSource::UniquePtr snp_filtering_source\n\t\t\t\t= genfile::VariantIdentifyingDataFilteringSNPDataSource::create(\n\t\t\t\t\tsource,\n\t\t\t\t\tgenfile::VariantIdentifyingDataTest::UniquePtr( snp_filter.release() )\n\t\t\t\t) ;\n\n\t\t\tsource.reset(\n\t\t\t\tsnp_filtering_source.release()\n\t\t\t) ;\n\t\t}\n\t\t\n\t\treturn source ;\n\t}\n\n\tgenfile::CommonSNPFilter::UniquePtr construct_snp_filter() const {\n\t\tgenfile::CommonSNPFilter::UniquePtr snp_filter ;\n\n\t\tif( options().check_if_option_was_supplied_in_group( \"Input filtering options\" )) {\n\t\t\tsnp_filter.reset( new genfile::CommonSNPFilter ) ;\n\t\t\tif( options().check_if_option_was_supplied( \"-incl-range\" )) {\n\t\t\t\tstd::vector< std::string > specs = options().get_values< std::string >( \"-incl-range\" ) ;\n\t\t\t\tfor ( std::size_t i = 0; i < specs.size(); ++i ) {\n\t\t\t\t\tsnp_filter->include_snps_in_range(\n\t\t\t\t\t\tgenfile::GenomePositionRange::parse( specs[i] )\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( options().check_if_option_was_supplied( \"-excl-range\" )) {\n\t\t\t\tstd::vector< std::string > specs = options().get_values< std::string >( \"-excl-range\" ) ;\n\t\t\t\tfor ( std::size_t i = 0; i < specs.size(); ++i ) {\n\t\t\t\t\tsnp_filter->exclude_snps_in_range(\n\t\t\t\t\t\tgenfile::GenomePositionRange::parse( specs[i] )\n\t\t\t\t\t) ;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( options().check_if_option_was_supplied( \"-incl-ranges\" )) {\n\t\t\t\tstd::vector< std::string > files = options().get_values< std::string >( \"-incl-ranges\" ) ;\n\t\t\t\tfor( std::string const& filename: files ) {\n\t\t\t\t\tstd::auto_ptr< std::istream > in = genfile::open_text_file_for_input( filename ) ;\n\t\t\t\t\tstd::string range ;\n\t\t\t\t\twhile( (*in) >> range ) {\n\t\t\t\t\t\tsnp_filter->include_snps_in_range(\n\t\t\t\t\t\t\tgenfile::GenomePositionRange::parse( range )\n\t\t\t\t\t\t) ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( options().check_if_option_was_supplied( \"-excl-ranges\" )) {\n\t\t\t\tstd::vector< std::string > files = options().get_values< std::string >( \"-excl-ranges\" ) ;\n\t\t\t\tfor( std::string const& filename: files ) {\n\t\t\t\t\tstd::auto_ptr< std::istream > in = genfile::open_text_file_for_input( filename ) ;\n\t\t\t\t\tstd::string range ;\n\t\t\t\t\twhile( (*in) >> range ) {\n\t\t\t\t\t\tsnp_filter->exclude_snps_in_range(\n\t\t\t\t\t\t\tgenfile::GenomePositionRange::parse( range )\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\treturn snp_filter ;\n\t}\n\t\n\tmetro::regression::LogLikelihood::UniquePtr create_loglikelihood( std::size_t number_of_samples ) {\n\t\ttypedef std::vector< std::string > Names ;\n\t\ttypedef std::vector< metro::SampleRange > SampleRanges ;\n\t\tusing namespace metro::regression ;\n\n\t\tEigen::MatrixXd outcome = Eigen::MatrixXd::Zero( number_of_samples, 2 ) ;\n\n\t\tDesign::UniquePtr design = Design::create(\n\t\t\toutcome, SampleRanges(), Names({ \"outcome=0\", \"outcome=1\"} ),\n\t\t\tNames({\n\t\t\t\t\"add1\", \"het1\",\n\t\t\t\t\"add2\", \"het2\",\n\t\t\t\t\"add3\", \"het3\",\n\t\t\t\t\"add4\", \"het4\",\n\t\t\t\t\"add5\", \"het5\"\n\t\t\t})\n\t\t) ;\n\t\tLogLikelihood::UniquePtr ll( metro::regression::Logistic::create( design ).release() ) ;\n\t\treturn ll ;\n\t}\n\t\n\tvoid add_covariates(\n\t\tmetro::regression::Design& design,\n\t\tgenfile::CohortIndividualSource const& samples,\n\t\tstd::vector< std::string > const& covariates\n\t) {\n\t\tui().logger() << \"Adding covariates...\\n\" ;\n\t\t{\n\t\t\tstd::set< std::string > uniqueCovariates( covariates.begin(), covariates.end() ) ;\n\t\t\tif( uniqueCovariates.size() != covariates.size() ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"add_covariates()\",\n\t\t\t\t\t\"covariates=\\\"\" + genfile::string_utils::join( covariates, \" \" ) + \"\\\"\",\n\t\t\t\t\t\"Covariates should not be duplicated.\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t}\n\t\tgenfile::CohortIndividualSource::ColumnSpec const& spec = samples.get_column_spec() ;\n\t\tfor( std::size_t i = 0; i < covariates.size(); ++i ) {\n\t\t\tstd::string const& covariateName = covariates[i] ;\n\t\t\tstd::size_t const column_index = spec.find_column( covariateName ) ;\n\t\t\tgenfile::CohortIndividualSource::SingleColumnSpec columnSpec = spec[ column_index ] ;\n\t\t\tgenfile::CrossCohortCovariateValueMapping::UniquePtr mapping\n\t\t\t\t= genfile::CrossCohortCovariateValueMapping::create( columnSpec, true ) ;\n\t\t\tmapping->add_source( samples ) ;\n\t\t\tif( columnSpec.is_discrete() ) {\n\t\t\t\tdesign.add_discrete_covariate(\n\t\t\t\t\tcovariateName,\n\t\t\t\t\t[&samples, &column_index, &mapping] ( std::size_t sample_index ) {\n\t\t\t\t\t\tint value = -1 ;\n\t\t\t\t\t\tgenfile::VariantEntry entry = samples.get_entry( sample_index, column_index ) ;\n\t\t\t\t\t\tif( !entry.is_missing() ) {\n\t\t\t\t\t\t\tvalue = mapping->get_mapped_value( entry ).as< int >() ;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn value ;\n\t\t\t\t\t},\n\t\t\t\t\t[&mapping]( int level ) {\n\t\t\t\t\t\tgenfile::VariantEntry entry = mapping->get_unmapped_value( level ) ;\n\t\t\t\t\t\treturn entry.as< std::string >() ;\n\t\t\t\t\t},\n\t\t\t\t\tmapping->get_number_of_distinct_mapped_values()\n\t\t\t\t) ;\n\t\t\t} else {\n\t\t\t\tdesign.add_single_covariate(\n\t\t\t\t\tcovariateName,\n\t\t\t\t\t[&samples, &column_index, &mapping]( std::size_t sample_index ) {\n\t\t\t\t\t\tdouble value = metro::NA ;\n\t\t\t\t\t\tgenfile::VariantEntry entry = samples.get_entry( sample_index, column_index ) ;\n\t\t\t\t\t\tif( !entry.is_missing() ) {\n\t\t\t\t\t\t\tvalue = mapping->get_mapped_value( entry ).as< double >() ;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn value ;\n\t\t\t\t\t}\n\t\t\t\t) ;\n\t\t\t}\n\t\t\t\n\t\t\tui().logger()\n\t\t\t\t<< \"++ Added covariate: \\\"\" + covariateName + \"\\\":\\n\"\n\t\t\t\t<<  mapping->get_summary( \"     \" )\n\t\t\t\t<< \"\\n\\n\" ;\n\t\t}\n\t}\n\n\tvoid set_outcome(\n\t\tmetro::regression::LogLikelihood& ll,\n\t\tgenfile::CohortIndividualSource const& samples,\n\t\tstd::string const& column\n\t) const {\n\t\ttypedef std::vector< std::string > Names ;\n\t\ttypedef std::vector< metro::SampleRange > SampleRanges ;\n\t\tEigen::MatrixXd outcome = Eigen::MatrixXd::Zero( samples.size(), 2 ) ;\n\t\tSampleRanges nonmissingness ;\n\t\tget_binary_outcome( samples, column, &outcome, &nonmissingness ) ;\n\t\tll.design().set_outcome(\n\t\t\toutcome, nonmissingness,\n\t\t\tNames({ column + \"=0\", column + \"=1\" })\n\t\t) ;\n\t}\n\n\tvoid get_binary_outcome(\n\t\tgenfile::CohortIndividualSource const& samples,\n\t\tstd::string const& column,\n\t\tEigen::MatrixXd* outcome,\n\t\tstd::vector< metro::SampleRange >* nonmissingness\n\t) const {\n\t\tstd::size_t column_i = samples.get_column_spec().find_column( column ) ;\n\t\tassert( samples.get_column_spec()[ column_i ].is_discrete() ) ;\n\t\tstd::size_t last_nonmissing_sample_i = 0 ;\n\t\toutcome->setZero( samples.size(), 2 ) ;\n\t\tfor( std::size_t i = 0; i < samples.size(); ++i ) {\n\t\t\tgenfile::VariantEntry const& entry = samples.get_entry( i, column_i ) ;\n\t\t\tif( entry.is_missing() ) {\n\t\t\t\tnonmissingness->push_back( metro::SampleRange( last_nonmissing_sample_i, i )) ;\n\t\t\t\tlast_nonmissing_sample_i = i+1 ;\n\t\t\t} else {\n\t\t\t\tint value = entry.as< int >() ;\n\t\t\t\tassert( value == 0 || value == 1 ) ;\n\t\t\t\t(*outcome)(i,value) = 1 ;\n\t\t\t}\n\t\t}\n\t\tif( last_nonmissing_sample_i < samples.size() ) {\n\t\t\tnonmissingness->push_back( metro::SampleRange( last_nonmissing_sample_i, samples.size() )) ;\n\t\t}\n#if DEBUG\n\t\tstd::cerr << \"get_outcome(): outcome is:\\n\"\n\t\t\t<< outcome->block(0,0,10,2 ) << \"\\n\"\n\t\t\t<< \"nonmissingness: \" << *nonmissingness << \"\\n\" ;\n#endif\n\t}\n\n\n\ttypedef std::map< std::vector< metro::SampleRange >, std::pair< Eigen::VectorXd, double > > NullLLStore ;\n\n\tdouble test_variant(\n\t\tmetro::ShotgunStochasticSearch::SelectedStates const& pick,\n\t\tDosageStore const& store,\n\t\tmetro::regression::LogLikelihood& ll,\n\t\tNullLLStore& null_ll_store\n\t) {\n#if DEBUG\n\t\tstd::cerr << \"   TESTING: \" << print_state( store.number_of_variants(), pick ) << \".\\n\" ;\n#endif\n\t\tusing namespace metro::regression ;\n\t\tusing metro::SampleRange ;\n\t\t\n\t\tdouble const minus_infinity = -std::numeric_limits< double >::infinity() ;\n\t\tdouble const log_weight = ( (pick.size() == 0) || (pick.size() > 5) )\n\t\t\t? minus_infinity\n\t\t\t: (pick.size() * std::log( 1.0 / store.number_of_variants() )) ;\n\t\n\t\tif( log_weight == minus_infinity ) {\n\t\t\t// Disallowed state, don't bother fitting.\n\t\t\treturn minus_infinity ;\n\t\t}\n\n\t\tboost::format parameter_format( \"%s%d/%s\" ) ;\n\t\tbool const debug = options().check( \"-debug\" ) ;\n\n\t\tassert( pick.size() < 6 ) ;\n\t\tEigen::MatrixXd predictors = Eigen::MatrixXd::Zero( store.number_of_samples(), 10 ) ;\n\t\tstd::vector< metro::SampleRange > nonmissing_samples( 1, metro::SampleRange( 0, store.number_of_samples() )) ;\n\n\t\tmetro::IndependentParameterDistribution prior( ll.get_parameter_names() ) ;\n\t\tmetro::IndependentParameterDistribution null_prior( ll.get_parameter_names() ) ;\n\n\t\tdouble const add_prior_obs = 32.0 ;\n\t\tdouble const het_prior_obs = options().check( \"-additive\" ) ? 1000.0 : 32.0 ;\n\n\t\tfor( std::size_t i = 0; i < 5; ++i ) {\n\t\t\tnull_prior.set_prior(\n\t\t\t\t(parameter_format % \"add\" % (i+1) % ll.design().get_outcome_name(1) ).str(),\n\t\t\t\tmetro::distributions::LogF::create( 10000.0, 10000.0 )\n\t\t\t) ;\n\t\t\tnull_prior.set_prior(\n\t\t\t\t(parameter_format % \"het\" % (i+1) % ll.design().get_outcome_name(1) ).str(),\n\t\t\t\tmetro::distributions::LogF::create( 10000.0, 10000.0 )\n\t\t\t) ;\n\t\t}\n\t\t\n\t\tfor( std::size_t i = 0; i < pick.size(); ++i ) {\n\t\t\tstore.get_dosages(\n\t\t\t\tpick[i],\n\t\t\t\t[&predictors,i] ( int sample, double ab, double bb ){\n\t\t\t\t\tpredictors( sample, i*2+0) = ab + 2*bb ;\n\t\t\t\t\tpredictors( sample, i*2+1) = ab ;\n\t\t\t\t}\n\t\t\t) ;\n\t\t\tnonmissing_samples = metro::impl::intersect_ranges(\n\t\t\t\tnonmissing_samples,\n\t\t\t\tstore.nonmissing_samples(pick[i])\n\t\t\t) ;\n\t\t\tprior.set_prior(\n\t\t\t\t(parameter_format % \"add\" % (i+1) % ll.design().get_outcome_name(1) ).str(),\n\t\t\t\tmetro::distributions::LogF::create( add_prior_obs, add_prior_obs )\n\t\t\t) ;\n\t\t\tprior.set_prior(\n\t\t\t\t(parameter_format % \"het\" % (i+1) % ll.design().get_outcome_name(1) ).str(),\n\t\t\t\tmetro::distributions::LogF::create( het_prior_obs, het_prior_obs )\n\t\t\t) ;\n\t\t}\n\t\tfor( std::size_t i = pick.size(); i < 5; ++i ) {\n\t\t\tprior.set_prior(\n\t\t\t\t(parameter_format % \"add\" % (i+1) % ll.design().get_outcome_name(1) ).str(),\n\t\t\t\tmetro::distributions::LogF::create( add_prior_obs, add_prior_obs )\n\t\t\t) ;\n\t\t\tprior.set_prior(\n\t\t\t\t(parameter_format % \"het\" % (i+1) % ll.design().get_outcome_name(1) ).str(),\n\t\t\t\tmetro::distributions::LogF::create( het_prior_obs, het_prior_obs )\n\t\t\t) ;\n\t\t}\n\n\t\t// Set up a trace for model fitting iterations.\n\t\tmetro::CholeskyStepper::Tracer tracer ;\n\t\tif( debug ) {\n\t\t\ttracer = [this] ( \n\t\t\t\tint iteration,\n\t\t\t\tdouble ll,\n\t\t\t\tdouble target_ll,\n\t\t\t\tmetro::CholeskyStepper::Vector const& point,\n\t\t\t\tmetro::CholeskyStepper::Vector const& first_derivative,\n\t\t\t\tmetro::CholeskyStepper::Vector const& step,\n\t\t\t\tbool converged\n\t\t\t) {\n\t\t\t\tthis->ui().logger()\n\t\t\t\t\t<< \" ITERATION: \" << iteration << \"\\n\"\n\t\t\t\t\t<< \"        LL: \" << ll << \"\\n\"\n\t\t\t\t\t<< \"    TARGET: \" << target_ll << \"\\n\"\n\t\t\t\t\t<< \"     POINT: \" << point.transpose() << \"\\n\"\n\t\t\t\t\t<< \"DERIVATIVE: \" << first_derivative.transpose() << \"\\n\"\n\t\t\t\t\t<< \"      STEP: \" << step.transpose() << \"\\n\"\n\t\t\t\t\t<< \" CONVERGED: \" << ( converged ? \"yes\" : \"no\" ) << \"\\n\" ;\n\t\t\t} ;\n\t\t}\n\n\t\t// To compute the BF we need the null model.\n\t\t// The null model does not depend on the SNPs, but might depend on the missing samples.\n\t\t// We cache the value for speed if the nonmissing samples don't change.\n\t\tstd::vector< std::string > comments ;\n\t\t// null_ll will be log-marginal likelihood of null model\n\t\t// i.e. logarithm of prior x likelihood, integrated over parameters.\n\t\tdouble null_ll = 0.0 ;\n\t\tEigen::VectorXd null_parameters ;\n\t\t{\n\t\t\tNullLLStore::const_iterator where = null_ll_store.find( nonmissing_samples ) ;\n\t\t\tif( where == null_ll_store.end() ) {\n\t\t\t\tif( debug ) {\n\t\t\t\t\tthis->ui().logger() << \"---> fitting NULL...\\n\" ;\n\t\t\t\t}\n\t\t\t\tll.design().set_predictors( Eigen::MatrixXd::Zero( store.number_of_samples(), 10 ), nonmissing_samples ) ;\n\t\t\t\tLogUnnormalisedPosterior posterior( ll, null_prior ) ;\n\t\t\t\tmetro::CholeskyStepper stopping_condition( 0.01, 100, tracer ) ;\n\t\t\t\tstd::pair< bool, int > fit = metro::fit_model(\n\t\t\t\t\tposterior,\n\t\t\t\t\t\"null\",\n\t\t\t\t\tEigen::VectorXd::Zero( ll.identify_parameters().rows() ),\n\t\t\t\t\tstopping_condition,\n\t\t\t\t\t&comments\n\t\t\t\t) ;\n\t\t\t\t\t\n\t\t\t\tnull_ll = laplace_approximate( posterior ) ;\n\t\t\t\tnull_parameters = posterior.parameters() ;\n\t\t\t\t//null_ll = posterior.get_value_of_function() ;\n\t\t\t\twhere = null_ll_store.insert(\n\t\t\t\t\tNullLLStore::value_type(\n\t\t\t\t\t\tnonmissing_samples,\n\t\t\t\t\t\tNullLLStore::mapped_type(\n\t\t\t\t\t\t\tll.parameters(),\n\t\t\t\t\t\t\tnull_ll\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t).first ;\n\t\t\t} else {\n\t\t\t\tnull_parameters = where->second.first ;\n\t\t\t\tnull_ll = where->second.second ;\n\t\t\t}\n\t\t}\n\n\t\tll.design().set_predictors( predictors, nonmissing_samples ) ;\n\t\tLogUnnormalisedPosterior posterior( ll, prior ) ;\n\n\t\tdouble posterior_weight = minus_infinity ;\n\t\tdouble result = minus_infinity ;\n\n\t\tif( log_weight > minus_infinity ) {\n\t\t\tif( debug ) {\n\t\t\t\tthis->ui().logger() << \"---> fitting full...\\n\" ;\n\t\t\t}\n\t\t\tmetro::CholeskyStepper stopping_condition( 0.01, 100, tracer ) ;\n\t\t\tstd::pair< bool, int > fit = metro::fit_model(\n\t\t\t\tposterior,\n\t\t\t\t\"full\",\n\t\t\t\tnull_parameters,\n\t\t\t\tstopping_condition,\n\t\t\t\t&comments\n\t\t\t) ;\n\t\t\tif( fit.first ) {\n\t\t\t\tresult = laplace_approximate( posterior ) - null_ll + log_weight ;\n\t\t\t\t//result = posterior.get_value_of_function() - null_ll + log_weight ;\n\t\t\t}\n\n#if DEBUG\n\t\t\tstd::cerr << print_state( store.number_of_variants(), pick ) << \".\\n\" ;\n\t\t\t//std::cerr << nonmissing_samples << \".\\n\" ;\n\t\t\t// std::cerr << \"PREDICTORS:\\n\" << predictors.block( 0, 0, 10, predictors.cols() ) << \".\\n\" ;\n\t\t\tstd::cerr << posterior.get_summary() << \"\\n\" ;\n\t\t\tstd::cerr << \"  INCLUDED: \" << posterior.ll().design().nonmissing_samples() << \"\\n\" ;\n\t\t\tstd::cerr << \" CONVERGED: \" << (fit.first ? \"1\" : \"0\") << \"\\n\" ;\n\t\t\tstd::cerr << \"        LL: \" << posterior.get_value_of_function() << \"\\n\" ;\n\t\t\tstd::cerr << \"      NULL: \" << null_ll << \"\\n\" ;\n\t\t\tstd::cerr << \" pick.size: \" << pick.size() << \"\\n\" ;\n\t\t\tstd::cerr << \"LOG WEIGHT: \" << log_weight << \"\\n\" ;\n\t\t\tstd::cerr << \"    RESULT: \" << result << \"\\n\" ;\n\t\t\n\t\t\tstd::cerr << \"\\n+++++++++++++++++++++++++\\n\" ;\n#endif\t\t\n\t\t}\n\t\t\n\t\treturn result ;\n\t}\n\t\n\t// Compute laplace approximation.\n\t// It is assumed that the function has already been maximised.\n\tdouble laplace_approximate( metro::SmoothFunction const& function ) const {\n\t\tdouble const fx = function.get_value_of_function() ;\n\t\tmetro::SmoothFunction::Matrix const& H = function.get_value_of_second_derivative() ;\n\t\tdouble const log_2pi = std::log( 2.0 * 3.1415926535897932384626 ) ;\n\t\tEigen::ColPivHouseholderQR< metro::SmoothFunction::Matrix > solver( -H ) ;\n\t\treturn\n\t\t\tfx + 0.5 * ( function.number_of_parameters() * log_2pi - solver.logAbsDeterminant() ) ;\n\t}\n\n\tvoid run_search( DosageStore& store, metro::regression::LogLikelihood& ll ) {\n\t\t// Do a test search for now\n\t\tNullLLStore null_ll_store ;\n\n\t\tui().logger() << \"Running shotgun stochastic search...\\n\" ;\n\n\t\tmetro::ShotgunStochasticSearch ss(\n\t\t\tstore.number_of_variants(),\n\t\t\t[this, &store, &ll, &null_ll_store]( metro::ShotgunStochasticSearch::SelectedStates const& s ) {\n\t\t\t\treturn this->test_variant( s, store, ll, null_ll_store ) ;\n\t\t\t},\n\t\t\tstatic_cast<std::uint32_t>(std::time(0))\n\t\t) ;\n\n\t\tfor( std::size_t i = 0; i < 100; ++i ) {\n\t\t\tboost::timer::cpu_timer timer ;\n\t\t\tmetro::ShotgunStochasticSearch::SelectedStates const& pick = ss.update() ;\n\t\t\t\n\t\t\tui().logger() << \"Iteration \" << i << \": \"\n\t\t\t\t<< \"took \" << boost::timer::format( timer.elapsed(), 2, \"%ts\" )\n\t\t\t\t<< \", state is: \" << print_state( store.number_of_variants(), pick )\n\t\t\t\t<< \"\\n\" ;\n\t\t}\n\n\t\tui().logger() << \"Outputting search results...\\n\" ;\n\t\toutput_search_results( ss, store ) ;\n\n\t\tui().logger() << \"Fine-mapping complete.\\n\" ;\n\t}\n\t\n\tvoid output_search_results(\n\t\tmetro::ShotgunStochasticSearch const& ss,\n\t\tDosageStore const& store\n\t) {\n\t\tqcdb::MultiVariantStorage::UniquePtr outputter\n\t\t\t= qcdb::MultiVariantStorage::create(\n\t\t\t\toptions().get< std::string >( \"-o\" ),\n\t\t\t\t5,\n\t\t\t\toptions().get< std::string >( \"-analysis-name\" ),\n\t\t\t\toptions().get< std::string >( \"-analysis-chunk\" ),\n\t\t\t\tget_application_metadata()\n\t\t) ;\n\t\toutputter->add_variable( \"loglikelihood\" ) ;\n\t\toutputter->add_variable( \"logposterior\" ) ;\n\t\toutputter->add_variable( \"posterior\" ) ;\n\n\t\tstd::vector< genfile::VariantIdentifyingData > variants ;\n\n\t\tauto comparator = []( double a, double b ) { return a > b ; } ;\n\t\ttypedef std::multimap< double, metro::ShotgunStochasticSearch::SelectedStates, decltype(comparator) > OrderedStates ;\n\t\tOrderedStates ordered_states( comparator ) ;\n\t\tstd::vector< double > posterior_weights ;\n\t\tss.visited_states(\n\t\t\t[&ordered_states, &posterior_weights](\n\t\t\t\tmetro::ShotgunStochasticSearch::SelectedStates const& states,\n\t\t\t\tdouble value\n\t\t\t) {\n\t\t\t\tstd::cerr << \"GOT: \" << states.size() << \", \" << value << \"\\n\" ;\n\t\t\t\tordered_states.insert( std::make_pair( value, states )) ;\n\t\t\t\tposterior_weights.push_back( value ) ;\n\t\t\t}\n\t\t) ;\n\n\t\tdouble const total_log_weight = metro::log_sum_exp( posterior_weights ) ;\n\t\tui().logger() << \"TOTAL LOG WEIGHT:\" << total_log_weight << \"\\n\" ;\n\t\tint count = 0 ;\n\t\tfor( OrderedStates::const_iterator i = ordered_states.begin(); i != ordered_states.end(); ++i, ++count ) {\n\t\t\tmetro::ShotgunStochasticSearch::SelectedStates const& states = i->second ;\n\t\t\tvariants.resize( states.size() ) ;\n\t\t\tfor( std::size_t i = 0; i < states.size(); ++i ) {\n\t\t\t\tvariants[i] = store.variant( states[i] ) ;\n\t\t\t}\n\t\t\toutputter->store_data_for_key(\n\t\t\t\tvariants,\n\t\t\t\t\"rank\",\n\t\t\t\tcount\n\t\t\t) ;\n\t\t\toutputter->store_data_for_key(\n\t\t\t\tvariants,\n\t\t\t\t\"loglikelihood\",\n\t\t\t\ti->first\n\t\t\t) ;\n\t\t\toutputter->store_data_for_key(\n\t\t\t\tvariants,\n\t\t\t\t\"logposterior\",\n\t\t\t\ti->first - total_log_weight\n\t\t\t) ;\n\t\t\toutputter->store_data_for_key(\n\t\t\t\tvariants,\n\t\t\t\t\"posterior\",\n\t\t\t\tstd::exp( i->first - total_log_weight )\n\t\t\t) ;\n\t\t}\n\t\toutputter->finalise() ;\n\t}\n\n#if 0\n\tvoid create_query( genfile::bgen::Query* query ) {\n\t\tif( options().check( \"-incl-range\" )) {\n\t\t\tauto const elts = options().get_values< std::string >( \"-incl-range\" ) ;\n\t\t\tfor( std::string const& elt: elts ) {\n\t\t\t\tquery->include_range( parse_range( elt )) ;\n\t\t\t}\n\t\t}\n\t\tif( options().check( \"-excl-range\" )) {\n\t\t\tauto const elts = options().get_values< std::string >( \"-excl-range\" ) ;\n\t\t\tfor( std::string const& elt: elts ) {\n\t\t\t\tquery->exclude_range( parse_range( elt )) ;\n\t\t\t}\n\t\t}\n\t\tif( options().check( \"-incl-rsids\" )) {\n\t\t\tauto const ids = options().get_values< std::string >( \"-incl-rsids\" ) ;\n\t\t\tquery->include_rsids( ids ) ;\n\t\t}\n\n\t\tif( options().check( \"-excl-rsids\" )) {\n\t\t\tauto const ids = options().get_values< std::string >( \"-excl-rsids\" ) ;\n\t\t\tquery->exclude_rsids( ids ) ;\n\t\t}\n\t}\n\t\n\tgenfile::bgen::IndexQuery::GenomicRange parse_range( std::string const& spec ) const {\n\t\tstd::size_t colon_pos = spec.find( ':' ) ;\n\t\tif ( colon_pos == std::string::npos ) {\n\t\t\tthrow std::invalid_argument( \"spec=\\\"\" + spec + \"\\\"\" ) ;\n\t\t}\n\n\t\tstd::vector< std::string > pieces ;\n\t\tpieces.push_back( spec.substr( 0, colon_pos )) ;\n\t\tpieces.push_back( spec.substr( colon_pos+1, spec.size() )) ;\n\n\t\tif( pieces.size() != 2 ) {\n\t\t\tthrow std::invalid_argument( \"spec=\\\"\" + spec + \"\\\"\" ) ;\n\t\t}\n\n\t\tstd::size_t separator_pos = pieces[1].find( '-' ) ;\n\t\tif ( separator_pos == std::string::npos ) {\n\t\t\tthrow std::invalid_argument( \"spec=\\\"\" + spec + \"\\\"\" ) ;\n\t\t}\n\n\t\tstd::string chromosome( pieces[0] ) ;\n\t\tint pos1 = (separator_pos == 0) ? 0 : std::stoi( pieces[1].substr( 0, separator_pos ) ) ;\n\t\tint pos2 = (separator_pos == (pieces[1].size()-1)) ? std::numeric_limits< int >::max() : std::stoi( pieces[1].substr( separator_pos + 1, pieces[1].size() ) ) ;\n\t\tassert( pos1 >= 0 ) ;\n\t\tassert( pos2 >= pos1 ) ;\n\n\t\treturn genfile::bgen::IndexQuery::GenomicRange( chromosome, pos1, pos2 ) ;\n\t}\n#endif\n} ;\n\nint main( int argc, char** argv ) {\n\ttry {\n\t\tMFMApplication app( argc, argv ) ;\n\t}\n\tcatch( appcontext::HaltProgramWithReturnCode const& e ) {\n\t\treturn e.return_code() ;\n\t}\n\treturn 0 ;\n}\n\n", "meta": {"hexsha": "eb29aa5058754e5130d31b47a80d4e3c6bab6ce4", "size": 37724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/multifinemap.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": "apps/multifinemap.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": "apps/multifinemap.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": 34.865064695, "max_line_length": 161, "alphanum_fraction": 0.6563195843, "num_tokens": 11042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.02758528522464313, "lm_q1q2_score": 0.013254141378310992}}
{"text": "/*!\n@file\nForward declares `boost::hana::Monad`.\n\n@copyright Louis Dionne 2013-2016\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_CONCEPT_MONAD_HPP\n#define BOOST_HANA_FWD_CONCEPT_MONAD_HPP\n\n#include <boost/hana/config.hpp>\n\n\nBOOST_HANA_NAMESPACE_BEGIN\n    //! @ingroup group-concepts\n    //! @defgroup group-Monad Monad\n    //! The `Monad` concept represents `Applicative`s with the ability to\n    //! flatten nested levels of structure.\n    //!\n    //! Historically, Monads are a construction coming from category theory,\n    //! an abstract branch of mathematics. The functional programming\n    //! community eventually discovered how Monads could be used to\n    //! formalize several useful things like side effects, which led\n    //! to the wide adoption of Monads in that community. However, even\n    //! in a multi-paradigm language like C++, there are several constructs\n    //! which turn out to be Monads, like `std::optional`, `std::vector` and\n    //! others.\n    //!\n    //! Everybody tries to introduce `Monad`s with a different analogy, and\n    //! most people fail. This is called the [Monad tutorial fallacy][1]. We\n    //! will try to avoid this trap by not presenting a specific intuition,\n    //! and we will instead present what monads are mathematically.\n    //! For specific intuitions, we will let readers who are new to this\n    //! concept read one of the many excellent tutorials available online.\n    //! Understanding Monads might take time at first, but once you get it,\n    //! a lot of patterns will become obvious Monads; this enlightening will\n    //! be your reward for the hard work.\n    //!\n    //! There are different ways of defining a Monad; Haskell uses a function\n    //! called `bind` (`>>=`) and another one called `return` (it has nothing\n    //! to do with C++'s `return` statement). They then introduce relationships\n    //! that must be satisfied for a type to be a Monad with those functions.\n    //! Mathematicians sometimes use a function called `join` and another one\n    //! called `unit`, or they also sometimes use other category theoretic\n    //! constructions like functor adjunctions and the Kleisli category.\n    //!\n    //! This library uses a composite approach. First, we use the `flatten`\n    //! function (equivalent to `join`) along with the `lift` function from\n    //! `Applicative` (equivalent to `unit`) to introduce the notion of\n    //! monadic function composition. We then write the properties that must\n    //! be satisfied by a Monad using this monadic composition operator,\n    //! because we feel it shows the link between Monads and Monoids more\n    //! clearly than other approaches.\n    //!\n    //! Roughly speaking, we will say that a `Monad` is an `Applicative` which\n    //! also defines a way to compose functions returning a monadic result,\n    //! as opposed to only being able to compose functions returning a normal\n    //! result. We will then ask for this composition to be associative and to\n    //! have a neutral element, just like normal function composition. For\n    //! usual composition, the neutral element is the identity function `id`.\n    //! For monadic composition, the neutral element is the `lift` function\n    //! defined by `Applicative`. This construction is made clearer in the\n    //! laws below.\n    //!\n    //! @note\n    //! Monads are known to be a big chunk to swallow. However, it is out of\n    //! the scope of this documentation to provide a full-blown explanation\n    //! of the concept. The [Typeclassopedia][2] is a nice Haskell-oriented\n    //! resource where more information about Monads can be found.\n    //!\n    //!\n    //! Minimal complete definitions\n    //! ----------------------------\n    //! First, a `Monad` must be both a `Functor` and an `Applicative`.\n    //! Also, an implementation of `flatten` or `chain` satisfying the\n    //! laws below for monadic composition must be provided.\n    //!\n    //! @note\n    //! The `ap` method for `Applicatives` may be derived from the minimal\n    //! complete definition of `Monad` and `Functor`; see below for more\n    //! information.\n    //!\n    //!\n    //! Laws\n    //! ----\n    //! To simplify writing the laws, we use the comparison between functions.\n    //! For two functions `f` and `g`, we define\n    //! @code\n    //!     f == g  if and only if  f(x) == g(x) for all x\n    //! @endcode\n    //!\n    //! With the usual composition of functions, we are given two functions\n    //! @f$ f : A \\to B @f$ and @f$ g : B \\to C @f$, and we must produce a\n    //! new function @f$ compose(g, f) : A \\to C @f$. This composition of\n    //! functions is associative, which means that\n    //! @code\n    //!     compose(h, compose(g, f)) == compose(compose(h, g), f)\n    //! @endcode\n    //!\n    //! Also, this composition has an identity element, which is the identity\n    //! function. This simply means that\n    //! @code\n    //!     compose(f, id) == compose(id, f) == f\n    //! @endcode\n    //!\n    //! This is probably nothing new if you are reading the `Monad` laws.\n    //! Now, we can observe that the above is equivalent to saying that\n    //! functions with the composition operator form a `Monoid`, where the\n    //! neutral element is the identity function.\n    //!\n    //! Given an `Applicative` `F`, what if we wanted to compose two functions\n    //! @f$ f : A \\to F(B) @f$ and @f$ g : B \\to F(C) @f$? When the\n    //! `Applicative` `F` is also a `Monad`, such functions taking normal\n    //! values but returning monadic values are called _monadic functions_.\n    //! To compose them, we obviously can't use normal function composition,\n    //! since the domains and codomains of `f` and `g` do not match properly.\n    //! Instead, we'll need a new operator -- let's call it `monadic_compose`:\n    //! @f[\n    //!     \\mathtt{monadic\\_compose} :\n    //!         (B \\to F(C)) \\times (A \\to F(B)) \\to (A \\to F(C))\n    //! @f]\n    //!\n    //! How could we go about implementing this function? Well, since we know\n    //! `F` is an `Applicative`, the only functions we have are `transform`\n    //! (from `Functor`), and `lift` and `ap` (from `Applicative`). Hence,\n    //! the only thing we can do at this point while respecting the signatures\n    //! of `f` and `g` is to set (for `x` of type `A`)\n    //! @code\n    //!     monadic_compose(g, f)(x) = transform(f(x), g)\n    //! @endcode\n    //!\n    //! Indeed, `f(x)` is of type `F(B)`, so we can map `g` (which takes `B`'s)\n    //! on it. Doing so will leave us with a result of type `F(F(C))`, but what\n    //! we wanted was a result of type `F(C)` to respect the signature of\n    //! `monadic_compose`. If we had a joker of type @f$ F(F(C)) \\to F(C) @f$,\n    //! we could simply set\n    //! @code\n    //!     monadic_compose(g, f)(x) = joker(transform(f(x), g))\n    //! @endcode\n    //!\n    //! and we would be happy. It turns out that `flatten` is precisely this\n    //! joker. Now, we'll want our joker to satisfy some properties to make\n    //! sure this composition is associative, just like our normal composition\n    //! was. These properties are slightly cumbersome to specify, so we won't\n    //! do it here. Also, we'll need some kind of neutral element for the\n    //! composition. This neutral element can't be the usual identity function,\n    //! because it does not have the right type: our neutral element needs to\n    //! be a function of type @f$ X \\to F(X) @f$ but the identity function has\n    //! type @f$ X \\to X @f$. It is now the right time to observe that `lift`\n    //! from `Applicative` has exactly the right signature, and so we'll take\n    //! this for our neutral element.\n    //!\n    //! We are now ready to formulate the `Monad` laws using this composition\n    //! operator. For a `Monad` `M` and functions @f$ f : A \\to M(B) @f$,\n    //! @f$ g : B \\to M(C) @f$ and @f$ h : C \\to M(D) @f$, the following\n    //! must be satisfied:\n    //! @code\n    //!     // associativity\n    //!     monadic_compose(h, monadic_compose(g, f)) == monadic_compose(monadic_compose(h, g), f)\n    //!\n    //!     // right identity\n    //!     monadic_compose(f, lift<M(A)>) == f\n    //!\n    //!     // left identity\n    //!     monadic_compose(lift<M(B)>, f) == f\n    //! @endcode\n    //!\n    //! which is to say that `M` along with monadic composition is a Monoid\n    //! where the neutral element is `lift`.\n    //!\n    //!\n    //! Refined concepts\n    //! ----------------\n    //! 1. `Functor`\n    //! 2. `Applicative` (free implementation of `ap`)\\n\n    //! When the minimal complete definition for `Monad` and `Functor` are\n    //! both satisfied, it is possible to implement `ap` by setting\n    //! @code\n    //!     ap(fs, xs) = chain(fs, [](auto f) {\n    //!         return transform(xs, f);\n    //!     })\n    //! @endcode\n    //!\n    //!\n    //! Concrete models\n    //! ---------------\n    //! `hana::lazy`, `hana::optional`, `hana::tuple`\n    //!\n    //!\n    //! [1]: https://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/\n    //! [2]: https://wiki.haskell.org/Typeclassopedia#Monad\n    template <typename M>\n    struct Monad;\nBOOST_HANA_NAMESPACE_END\n\n#endif // !BOOST_HANA_FWD_CONCEPT_MONAD_HPP\n", "meta": {"hexsha": "1dee78331d71147c90010bb381aff4fa3f0a5719", "size": 9312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/hana/fwd/concept/monad.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 886.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T20:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:47:52.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/hana/fwd/concept/monad.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/hana/fwd/concept/monad.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 46.7939698492, "max_line_length": 107, "alphanum_fraction": 0.6320876289, "num_tokens": 2404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.031618769664005134, "lm_q1q2_score": 0.013238681135948295}}
{"text": "/*\n fcs.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 \"fcs.h\"\n#include \"constants.h\"\n#include \"constraint.h\"\n#include \"error.h\"\n#include \"cluster.h\"\n#include \"mathfunctions.h\"\n#include \"memory.h\"\n#include \"rref.h\"\n#include \"symmetry.h\"\n#include \"timer.h\"\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <cstddef>\n#include <string>\n#include <cmath>\n#include \"../external/combination.hpp\"\n#include <unordered_set>\n#include <boost/algorithm/string/case_conv.hpp>\n\n#if defined(_WIN32) || defined(_WIN64)\n#undef min\n#undef max\n#endif\n\nusing namespace ALM_NS;\n\nFcs::Fcs()\n{\n    set_default_variables();\n};\n\nFcs::~Fcs()\n{\n    deallocate_variables();\n};\n\nvoid Fcs::init(const Cluster *cluster,\n               const Symmetry *symmetry,\n               const Cell &supercell,\n               const int verbosity,\n               Timer *timer)\n{\n    int i;\n    const auto maxorder = cluster->get_maxorder();\n\n    timer->start_clock(\"fcs\");\n\n    if (verbosity > 0) {\n        std::cout << \" FORCE CONSTANT\" << std::endl;\n        std::cout << \" ==============\" << std::endl << std::endl;\n        std::cout << \"  Symmetry is handled in \";\n        if (preferred_basis == \"Lattice\") {\n            std::cout << \"crystallographic (fractional) coordinates.\";\n        } else {\n            std::cout << \"Cartesian coordinates.\";\n        }\n        std::cout << std::endl;\n    }\n\n    if (fc_table) {\n        deallocate(fc_table);\n    }\n    allocate(fc_table, maxorder);\n\n    if (nequiv) {\n        deallocate(nequiv);\n    }\n    allocate(nequiv, maxorder);\n\n    if (fc_zeros) {\n        deallocate(fc_zeros);\n    }\n    allocate(fc_zeros, maxorder);\n\n    // Generate force constants using the information of interacting atom pairs\n    for (i = 0; i < maxorder; ++i) {\n        generate_force_constant_table(i,\n                                      supercell.number_of_atoms,\n                                      cluster->get_cluster_list(i),\n                                      symmetry,\n                                      preferred_basis,\n                                      fc_table[i],\n                                      nequiv[i],\n                                      fc_zeros[i],\n                                      store_zeros);\n    }\n\n    set_basis_conversion_matrix(supercell);\n\n    if (verbosity > 0) {\n        std::cout << std::endl;\n        for (i = 0; i < maxorder; ++i) {\n            std::cout << \"  Number of \" << std::setw(9)\n                << cluster->get_ordername(i)\n                << \" FCs : \" << nequiv[i].size();\n            std::cout << std::endl;\n        }\n        std::cout << std::endl;\n\n\n        timer->print_elapsed();\n        std::cout << \" -------------------------------------------------------------------\" << std::endl;\n        std::cout << std::endl;\n    }\n\n    timer->stop_clock(\"fcs\");\n}\n\nvoid Fcs::set_default_variables()\n{\n    nequiv = nullptr;\n    fc_table = nullptr;\n    fc_zeros = nullptr;\n    fc_cart = nullptr;\n    store_zeros = true;\n\n    // preferred_basis = \"Cartesian\";\n    preferred_basis = \"Lattice\";\n}\n\nvoid Fcs::deallocate_variables()\n{\n    if (nequiv) {\n        deallocate(nequiv);\n    }\n    if (fc_table) {\n        deallocate(fc_table);\n    }\n    if (fc_zeros) {\n        deallocate(fc_zeros);\n    }\n    if (fc_cart) {\n        deallocate(fc_cart);\n    }\n}\n\n\nvoid Fcs::generate_force_constant_table(const int order,\n                                        const size_t nat,\n                                        const std::set<IntList> &pairs,\n                                        const Symmetry *symm_in,\n                                        const std::string basis,\n                                        std::vector<FcProperty> &fc_vec,\n                                        std::vector<size_t> &ndup,\n                                        std::vector<FcProperty> &fc_zeros_out,\n                                        const bool store_zeros_in) const\n{\n    size_t i, j;\n    int i1, i2;\n    int i_prim;\n    int *atmn, *atmn_mapped;\n    int *ind, *ind_mapped;\n    int *ind_tmp, *ind_mapped_tmp;\n    int nxyz;\n    unsigned int isym;\n\n    double c_tmp;\n\n    int **xyzcomponent;\n\n    const auto nsym = symm_in->get_SymmData().size();\n    bool is_zero;\n    bool *is_searched;\n    int **map_sym;\n    double ***rotation;\n    const bool use_compatible = true;\n\n    if (order < 0) return;\n\n    allocate(rotation, nsym, 3, 3);\n    allocate(map_sym, nat, nsym);\n    int nsym_in_use = 0;\n\n    get_available_symmop(nat,\n                         symm_in,\n                         basis,\n                         nsym_in_use,\n                         map_sym,\n                         rotation,\n                         use_compatible);\n\n    allocate(atmn, order + 2);\n    allocate(atmn_mapped, order + 2);\n    allocate(ind, order + 2);\n    allocate(ind_mapped, order + 2);\n    allocate(ind_tmp, order);\n    allocate(ind_mapped_tmp, order + 2);\n    allocate(is_searched, 3 * nat);\n\n    fc_vec.clear();\n    ndup.clear();\n    fc_zeros_out.clear();\n    size_t nmother = 0;\n\n    nxyz = static_cast<int>(std::pow(3.0, order + 2));\n\n    allocate(xyzcomponent, nxyz, order + 2);\n    get_xyzcomponent(order + 2, xyzcomponent);\n\n    std::unordered_set<IntList> list_found;\n\n    for (const auto &pair : pairs) {\n\n        for (i = 0; i < order + 2; ++i) atmn[i] = pair.iarray[i];\n\n        for (i1 = 0; i1 < nxyz; ++i1) {\n            for (i = 0; i < order + 2; ++i) ind[i] = 3 * atmn[i] + xyzcomponent[i1][i];\n\n            if (!is_ascending(order + 2, ind)) continue;\n\n            i_prim = get_minimum_index_in_primitive(order + 2, ind, nat,\n                                                    symm_in->get_nat_prim(),\n                                                    symm_in->get_map_p2s());\n            std::swap(ind[0], ind[i_prim]);\n            sort_tail(order + 2, ind);\n\n            is_zero = false;\n\n            if (list_found.find(IntList(order + 2, ind)) != list_found.end()) continue; // Already exits!\n\n            // Search symmetrically-dependent parameter set\n\n            size_t ndeps = 0;\n\n            for (isym = 0; isym < nsym_in_use; ++isym) {\n\n                for (i = 0; i < order + 2; ++i) atmn_mapped[i] = map_sym[atmn[i]][isym];\n\n                if (!is_inprim(order + 2,\n                               atmn_mapped,\n                               symm_in->get_nat_prim(),\n                               symm_in->get_map_p2s()))\n                    continue;\n\n                for (i2 = 0; i2 < nxyz; ++i2) {\n\n                    c_tmp = coef_sym(order + 2,\n                                     rotation[isym],\n                                     xyzcomponent[i1],\n                                     xyzcomponent[i2]);\n\n                    if (std::abs(c_tmp) > eps12) {\n                        for (i = 0; i < order + 2; ++i)\n                            ind_mapped[i] = 3 * atmn_mapped[i] + xyzcomponent[i2][i];\n\n                        i_prim = get_minimum_index_in_primitive(order + 2,\n                                                                ind_mapped,\n                                                                nat,\n                                                                symm_in->get_nat_prim(),\n                                                                symm_in->get_map_p2s());\n                        std::swap(ind_mapped[0], ind_mapped[i_prim]);\n                        sort_tail(order + 2, ind_mapped);\n\n                        if (!is_zero) {\n                            bool zeroflag = true;\n                            for (i = 0; i < order + 2; ++i) {\n                                zeroflag = zeroflag & (ind[i] == ind_mapped[i]);\n                            }\n                            zeroflag = zeroflag & (std::abs(c_tmp + 1.0) < eps8);\n                            is_zero = zeroflag;\n                        }\n\n                        // Add to found list (set) and fcset (vector) if the created is new one.\n\n                        if (list_found.find(IntList(order + 2, ind_mapped)) == list_found.end()) {\n                            list_found.insert(IntList(order + 2, ind_mapped));\n\n                            fc_vec.emplace_back(FcProperty(order + 2,\n                                                           c_tmp,\n                                                           ind_mapped,\n                                                           nmother));\n                            ++ndeps;\n\n                            // Add equivalent interaction list (permutation) if there are two or more indices\n                            // which belong to the primitive cell.\n                            // This procedure is necessary for constructing a sensing matrix.\n\n                            for (i = 0; i < 3 * nat; ++i) is_searched[i] = false;\n                            is_searched[ind_mapped[0]] = true;\n                            for (i = 1; i < order + 2; ++i) {\n                                if ((!is_searched[ind_mapped[i]]) && is_inprim(ind_mapped[i],\n                                                                               symm_in->get_nat_prim(),\n                                                                               symm_in->get_map_p2s())) {\n\n                                    for (j = 0; j < order + 2; ++j) ind_mapped_tmp[j] = ind_mapped[j];\n                                    std::swap(ind_mapped_tmp[0], ind_mapped_tmp[i]);\n                                    sort_tail(order + 2, ind_mapped_tmp);\n                                    fc_vec.emplace_back(FcProperty(order + 2,\n                                                                   c_tmp,\n                                                                   ind_mapped_tmp,\n                                                                   nmother));\n\n                                    ++ndeps;\n\n                                    is_searched[ind_mapped[i]] = true;\n                                }\n                            }\n\n\n                        }\n                    }\n                }\n            } // close symmetry loop\n\n            if (is_zero) {\n                if (store_zeros_in) {\n                    for (auto it = fc_vec.rbegin(); it != fc_vec.rbegin() + ndeps; ++it) {\n                        (*it).mother = std::numeric_limits<size_t>::max();\n                        fc_zeros_out.push_back(*it);\n                    }\n                }\n                for (i = 0; i < ndeps; ++i) fc_vec.pop_back();\n            } else {\n                ndup.push_back(ndeps);\n                ++nmother;\n            }\n\n        } // close xyz component loop\n    }     // close atom number loop (iterator)\n\n    deallocate(xyzcomponent);\n    list_found.clear();\n    deallocate(atmn);\n    deallocate(atmn_mapped);\n    deallocate(ind);\n    deallocate(ind_mapped);\n    deallocate(ind_tmp);\n    deallocate(ind_mapped_tmp);\n    deallocate(is_searched);\n    deallocate(rotation);\n    deallocate(map_sym);\n\n    // sort fc_vec\n\n    if (!ndup.empty()) {\n        std::sort(fc_vec.begin(), fc_vec.begin() + ndup[0]);\n        auto nbegin = ndup[0];\n        for (size_t mm = 1; mm < ndup.size(); ++mm) {\n            const auto nend = nbegin + ndup[mm];\n            std::sort(fc_vec.begin() + nbegin, fc_vec.begin() + nend);\n            nbegin += ndup[mm];\n        }\n    }\n}\n\nvoid Fcs::get_constraint_symmetry(const size_t nat,\n                                  const Symmetry *symmetry,\n                                  const int order,\n                                  const std::string basis,\n                                  const std::vector<FcProperty> &fc_table_in,\n                                  const size_t nparams,\n                                  const double tolerance,\n                                  ConstraintSparseForm &const_out,\n                                  const bool do_rref) const\n{\n    // Create constraint matrices arising from the crystal symmetry.\n    // Necessary for hexagonal systems.\n\n    int i;\n    // int j;\n    unsigned int isym;\n    int ixyz;\n    int *index_tmp;\n    int **xyzcomponent;\n    int nsym_in_use;\n    std::unordered_set<FcProperty> list_found;\n\n    typedef std::vector<ConstraintDoubleElement> ConstEntry;\n    std::vector<ConstEntry> constraint_all;\n    ConstEntry const_tmp;\n\n    int **map_sym;\n    double ***rotation;\n    const auto nsym = symmetry->get_SymmData().size();\n    const auto natmin = symmetry->get_nat_prim();\n    const auto nfcs = fc_table_in.size();\n    const auto use_compatible = false;\n\n    if (order < 0 || nparams == 0) return;\n\n    const auto nxyz = static_cast<int>(std::pow(static_cast<double>(3), order + 2));\n\n    allocate(rotation, nsym, 3, 3);\n    allocate(map_sym, nat, nsym);\n\n    get_available_symmop(nat,\n                         symmetry,\n                         basis,\n                         nsym_in_use,\n                         map_sym,\n                         rotation,\n                         use_compatible);\n\n    if (nsym_in_use == 0) {\n        deallocate(rotation);\n        deallocate(map_sym);\n        return;\n    }\n\n    const_out.clear();\n\n    allocate(index_tmp, order + 2);\n    allocate(xyzcomponent, nxyz, order + 2);\n    get_xyzcomponent(order + 2, xyzcomponent);\n\n    // Generate temporary list of parameters\n    list_found.clear();\n    for (const auto &p : fc_table_in) {\n        for (i = 0; i < order + 2; ++i) index_tmp[i] = p.elems[i];\n        list_found.insert(FcProperty(order + 2, p.sign,\n                                     index_tmp, p.mother));\n    }\n\n\n#ifdef _OPENMP\n#pragma omp parallel\n#endif\n    {\n        int j;\n        int i_prim;\n        int loc_nonzero;\n        int *ind;\n        int *atm_index, *atm_index_symm;\n        int *xyz_index;\n        double c_tmp;\n        // double maxabs;\n\n        std::unordered_set<FcProperty>::iterator iter_found;\n        std::vector<double> const_now_omp;\n        std::vector<std::vector<double>> const_omp;\n\n        ConstEntry const_tmp_omp;\n        std::vector<ConstEntry> constraint_list_omp;\n\n        allocate(ind, order + 2);\n        allocate(atm_index, order + 2);\n        allocate(atm_index_symm, order + 2);\n        allocate(xyz_index, order + 2);\n\n        const_omp.clear();\n        const_now_omp.resize(nparams);\n\n#ifdef _OPENMP\n#pragma omp for private(i, isym, ixyz), schedule(static)\n#endif\n        for (long ii = 0; ii < nfcs; ++ii) {\n\n            for (i = 0; i < order + 2; ++i) {\n                atm_index[i] = fc_table_in[ii].elems[i] / 3;\n                xyz_index[i] = fc_table_in[ii].elems[i] % 3;\n            }\n\n            for (isym = 0; isym < nsym_in_use; ++isym) {\n\n                for (i = 0; i < order + 2; ++i)\n                    atm_index_symm[i] = map_sym[atm_index[i]][isym];\n                if (!is_inprim(order + 2, atm_index_symm, natmin, symmetry->get_map_p2s())) continue;\n\n                for (i = 0; i < nparams; ++i) const_now_omp[i] = 0.0;\n\n                const_now_omp[fc_table_in[ii].mother] = -fc_table_in[ii].sign;\n\n                for (ixyz = 0; ixyz < nxyz; ++ixyz) {\n                    for (i = 0; i < order + 2; ++i)\n                        ind[i] = 3 * atm_index_symm[i] + xyzcomponent[ixyz][i];\n\n                    i_prim = get_minimum_index_in_primitive(order + 2, ind, nat, natmin, symmetry->get_map_p2s());\n                    std::swap(ind[0], ind[i_prim]);\n                    sort_tail(order + 2, ind);\n\n                    iter_found = list_found.find(FcProperty(order + 2, 1.0, ind, 1));\n                    if (iter_found != list_found.end()) {\n                        c_tmp = coef_sym(order + 2, rotation[isym], xyz_index, xyzcomponent[ixyz]);\n                        const_now_omp[(*iter_found).mother] += (*iter_found).sign * c_tmp;\n                    }\n                }\n\n                if (!is_allzero(const_now_omp, eps8, loc_nonzero)) {\n                    if (const_now_omp[loc_nonzero] < 0.0) {\n                        for (j = 0; j < nparams; ++j) const_now_omp[j] *= -1.0;\n                    }\n\n                    const_tmp_omp.clear();\n                    for (j = 0; j < nparams; ++j) {\n                        if (std::abs(const_now_omp[j]) >= eps8) {\n                            const_tmp_omp.emplace_back(j, const_now_omp[j]);\n                        }\n                    }\n                    constraint_list_omp.emplace_back(const_tmp_omp);\n                }\n\n            } // close isym loop\n        }     // close ii loop\n\n        deallocate(ind);\n        deallocate(atm_index);\n        deallocate(atm_index_symm);\n        deallocate(xyz_index);\n\n#pragma omp critical\n        {\n            for (const auto &it : constraint_list_omp) {\n                constraint_all.emplace_back(it);\n            }\n        }\n        constraint_list_omp.clear();\n    } // close openmp region\n\n    deallocate(xyzcomponent);\n    deallocate(index_tmp);\n    deallocate(rotation);\n    deallocate(map_sym);\n\n    std::sort(constraint_all.begin(), constraint_all.end());\n    constraint_all.erase(std::unique(constraint_all.begin(),\n                                     constraint_all.end()),\n                         constraint_all.end());\n\n    MapConstraintElement const_tmp2;\n    auto division_factor = 1.0;\n    int counter;\n    const_out.clear();\n\n    for (const auto &it : constraint_all) {\n        const_tmp2.clear();\n        counter = 0;\n        for (const auto &it2 : it) {\n            if (counter == 0) {\n                division_factor = 1.0 / it2.val;\n            }\n            const_tmp2[it2.col] = it2.val * division_factor;\n            ++counter;\n        }\n        const_out.emplace_back(const_tmp2);\n    }\n    constraint_all.clear();\n\n    if (do_rref) rref_sparse(nparams, const_out, tolerance);\n}\n\nvoid Fcs::get_constraint_symmetry_in_integer(const size_t nat,\n                                             const Symmetry *symmetry,\n                                             const int order,\n                                             const std::string basis,\n                                             const std::vector<FcProperty> &fc_table_in,\n                                             const size_t nparams,\n                                             const double tolerance,\n                                             ConstraintSparseForm &const_out,\n                                             const bool do_rref) const\n{\n    // Create constraint matrices arising from the crystal symmetry.\n    // Necessary for hexagonal systems.\n    // This does exactly the same thing as get_constraint_symmetry but assumes\n    // all elements of the constraint matrix are integer.\n    // This version is expected to be more stable (and fast?).\n\n    int i;\n    unsigned int isym;\n    int ixyz;\n    int *index_tmp;\n    int **xyzcomponent;\n    int nsym_in_use;\n    std::unordered_set<FcProperty> list_found;\n\n    typedef std::vector<ConstraintIntegerElement> ConstEntry;\n    std::vector<ConstEntry> constraint_all;\n    ConstEntry const_tmp;\n\n    int **map_sym;\n    double ***rotation;\n    const auto nsym = symmetry->get_SymmData().size();\n    const auto natmin = symmetry->get_nat_prim();\n    const auto nfcs = fc_table_in.size();\n    const auto use_compatible = false;\n\n    if (order < 0 || nparams == 0) return;\n\n    const auto nxyz = static_cast<int>(std::pow(static_cast<double>(3), order + 2));\n\n    allocate(rotation, nsym, 3, 3);\n    allocate(map_sym, nat, nsym);\n\n    get_available_symmop(nat,\n                         symmetry,\n                         basis,\n                         nsym_in_use,\n                         map_sym,\n                         rotation,\n                         use_compatible);\n\n    if (nsym_in_use == 0) {\n        deallocate(rotation);\n        deallocate(map_sym);\n        return;\n    }\n\n    const_out.clear();\n\n    allocate(index_tmp, order + 2);\n    allocate(xyzcomponent, nxyz, order + 2);\n    get_xyzcomponent(order + 2, xyzcomponent);\n\n    // Generate temporary list of parameters\n    list_found.clear();\n    for (const auto &p : fc_table_in) {\n        for (i = 0; i < order + 2; ++i) index_tmp[i] = p.elems[i];\n        list_found.insert(FcProperty(order + 2, p.sign,\n                                     index_tmp, p.mother));\n    }\n\n#ifdef _OPENMP\n#pragma omp parallel\n#endif\n    {\n        int j;\n        int i_prim;\n        int loc_nonzero;\n        int *ind;\n        int *atm_index, *atm_index_symm;\n        int *xyz_index;\n        int c_tmp;\n\n        std::unordered_set<FcProperty>::iterator iter_found;\n        std::vector<int> const_now_omp;\n        std::vector<std::vector<int>> const_omp;\n\n        ConstEntry const_tmp_omp;\n        std::vector<ConstEntry> constraint_list_omp;\n\n        allocate(ind, order + 2);\n        allocate(atm_index, order + 2);\n        allocate(atm_index_symm, order + 2);\n        allocate(xyz_index, order + 2);\n\n        const_omp.clear();\n        const_now_omp.resize(nparams);\n\n#ifdef _OPENMP\n#pragma omp for private(i, isym, ixyz), schedule(static)\n#endif\n        for (long ii = 0; ii < nfcs; ++ii) {\n\n            for (i = 0; i < order + 2; ++i) {\n                atm_index[i] = fc_table_in[ii].elems[i] / 3;\n                xyz_index[i] = fc_table_in[ii].elems[i] % 3;\n            }\n\n            for (isym = 0; isym < nsym_in_use; ++isym) {\n\n                for (i = 0; i < order + 2; ++i)\n                    atm_index_symm[i] = map_sym[atm_index[i]][isym];\n                if (!is_inprim(order + 2, atm_index_symm, natmin, symmetry->get_map_p2s())) continue;\n\n                for (i = 0; i < nparams; ++i) const_now_omp[i] = 0;\n\n                const_now_omp[fc_table_in[ii].mother] = -nint(fc_table_in[ii].sign);\n\n                for (ixyz = 0; ixyz < nxyz; ++ixyz) {\n                    for (i = 0; i < order + 2; ++i)\n                        ind[i] = 3 * atm_index_symm[i] + xyzcomponent[ixyz][i];\n\n                    i_prim = get_minimum_index_in_primitive(order + 2, ind, nat, natmin, symmetry->get_map_p2s());\n                    std::swap(ind[0], ind[i_prim]);\n                    sort_tail(order + 2, ind);\n\n                    iter_found = list_found.find(FcProperty(order + 2, 1.0, ind, 1));\n                    if (iter_found != list_found.end()) {\n                        c_tmp = nint(coef_sym(order + 2, rotation[isym], xyz_index, xyzcomponent[ixyz]));\n                        const_now_omp[(*iter_found).mother] += nint((*iter_found).sign) * c_tmp;\n                    }\n                }\n\n                if (!is_allzero(const_now_omp, loc_nonzero)) {\n                    if (const_now_omp[loc_nonzero] < 0) {\n                        for (j = 0; j < nparams; ++j) const_now_omp[j] *= -1;\n                    }\n\n                    const_tmp_omp.clear();\n                    for (j = 0; j < nparams; ++j) {\n                        if (std::abs(const_now_omp[j]) > 0) {\n                            const_tmp_omp.emplace_back(j, const_now_omp[j]);\n                        }\n                    }\n                    constraint_list_omp.emplace_back(const_tmp_omp);\n                }\n\n            } // close isym loop\n        }     // close ii loop\n\n        deallocate(ind);\n        deallocate(atm_index);\n        deallocate(atm_index_symm);\n        deallocate(xyz_index);\n\n#pragma omp critical\n        {\n            for (const auto &it : constraint_list_omp) {\n                constraint_all.emplace_back(it);\n            }\n        }\n        constraint_list_omp.clear();\n    } // close openmp region\n\n    deallocate(xyzcomponent);\n    deallocate(index_tmp);\n    deallocate(rotation);\n    deallocate(map_sym);\n\n    std::sort(constraint_all.begin(), constraint_all.end());\n    constraint_all.erase(std::unique(constraint_all.begin(),\n                                     constraint_all.end()),\n                         constraint_all.end());\n\n    MapConstraintElement const_tmp2;\n    auto division_factor = 1.0;\n    int counter;\n    const_out.clear();\n\n    for (const auto &it : constraint_all) {\n        const_tmp2.clear();\n        counter = 0;\n        for (const auto &it2 : it) {\n            if (counter == 0) {\n                division_factor = 1.0 / it2.val;\n            }\n            const_tmp2[it2.col] = it2.val * division_factor;\n            ++counter;\n        }\n        const_out.emplace_back(const_tmp2);\n    }\n    constraint_all.clear();\n\n    if (do_rref) rref_sparse(nparams, const_out, tolerance);\n}\n\nstd::vector<size_t>* Fcs::get_nequiv() const\n{\n    return nequiv;\n}\n\nstd::vector<FcProperty>* Fcs::get_fc_table() const\n{\n    return fc_table;\n}\n\nstd::vector<ForceConstantTable>* Fcs::get_fc_cart() const\n{\n    return fc_cart;\n}\n\nvoid Fcs::set_forceconstant_basis(const std::string preferred_basis_in)\n{\n    preferred_basis = preferred_basis_in;\n}\n\nstd::string Fcs::get_forceconstant_basis() const\n{\n    return preferred_basis;\n}\n\nvoid Fcs::set_forceconstant_cartesian(const int maxorder,\n                                      double *param_in)\n{\n    auto ishift = 0;\n    int j;\n\n    std::vector<int> atoms_old, atoms_now;\n    std::vector<int> coords_now;\n    std::vector<std::vector<int>> coord_list;\n    std::vector<double> fc_list;\n    int **xyzcomponent;\n    double prod_matrix;\n\n    if (fc_cart) {\n        deallocate(fc_cart);\n    }\n    allocate(fc_cart, maxorder);\n\n    std::vector<int> elems_permutation;\n\n    std::vector<FcProperty> fc_table_copy;\n\n    nfc_cart_permu.resize(maxorder);\n    nfc_cart_nopermu.resize(maxorder);\n\n    for (int i = 0; i < maxorder; ++i) {\n\n        auto nelems = i + 2;\n\n        atoms_old.resize(nelems);\n        atoms_now.resize(nelems);\n        coords_now.resize(nelems);\n        coord_list.clear();\n        fc_list.clear();\n\n        const auto nxyz = static_cast<int>(std::pow(3.0, nelems));\n        allocate(xyzcomponent, nxyz, nelems);\n        get_xyzcomponent(nelems, xyzcomponent);\n\n        for (j = 0; j < nelems; ++j) atoms_old[j] = -1;\n        int icount = 0;\n\n        fc_table_copy.clear();\n        for (const auto &it : fc_table[i]) {\n            elems_permutation = it.elems;\n            do {\n                fc_table_copy.emplace_back(nelems,\n                                           it.sign,\n                                           &elems_permutation[0],\n                                           it.mother);\n            } while (std::next_permutation(elems_permutation.begin() + 1,\n                                           elems_permutation.end()));\n        }\n\n        // Sort fc_table_copy in ascending order of atomic indices.\n        std::sort(fc_table_copy.begin(),\n                  fc_table_copy.end(),\n                  FcProperty::compare_atom_index);\n\n        for (const auto &it : fc_table_copy) {\n\n            for (j = 0; j < nelems; ++j) {\n                atoms_now[j] = it.elems[j] / 3;\n                coords_now[j] = it.elems[j] % 3;\n            }\n\n            if (atoms_now == atoms_old) {\n\n                coord_list.push_back(coords_now);\n                fc_list.push_back(param_in[it.mother + ishift] * it.sign);\n\n                ++icount;\n\n            } else {\n\n                if (icount > 0) {\n                    for (auto ixyz = 0; ixyz < nxyz; ++ixyz) {\n\n                        auto fcs_cart = 0.0;\n\n                        for (j = 0; j < icount; ++j) {\n                            prod_matrix = 1.0;\n                            for (auto k = 0; k < nelems; ++k) {\n                                prod_matrix *= basis_conversion_matrix(coord_list[j][k],\n                                                                       xyzcomponent[ixyz][k]);\n                            }\n                            fcs_cart += prod_matrix * fc_list[j];\n                        }\n\n                        if (std::abs(fcs_cart) > eps12) {\n                            fc_cart[i].emplace_back(nelems,\n                                                    fcs_cart,\n                                                    &atoms_old[0],\n                                                    xyzcomponent[ixyz]);\n                        }\n                    }\n                }\n                atoms_old = atoms_now;\n                coord_list.clear();\n                fc_list.clear();\n                coord_list.push_back(coords_now);\n                fc_list.push_back(param_in[it.mother + ishift] * it.sign);\n                icount = 1;\n            }\n        }\n\n        if (icount > 0) {\n            for (auto ixyz = 0; ixyz < nxyz; ++ixyz) {\n\n                auto fcs_cart = 0.0;\n\n                for (j = 0; j < icount; ++j) {\n                    prod_matrix = 1.0;\n                    for (auto k = 0; k < nelems; ++k) {\n                        prod_matrix *= basis_conversion_matrix(coord_list[j][k],\n                                                               xyzcomponent[ixyz][k]);\n                    }\n                    fcs_cart += prod_matrix * fc_list[j];\n                }\n\n                if (std::abs(fcs_cart) > eps12) {\n                    fc_cart[i].emplace_back(nelems,\n                                            fcs_cart,\n                                            &atoms_old[0],\n                                            xyzcomponent[ixyz]);\n                }\n            }\n        }\n\n        ishift += nequiv[i].size();\n\n        deallocate(xyzcomponent);\n\n        nfc_cart_permu[i] = fc_cart[i].size();\n        nfc_cart_nopermu[i] = std::count_if(fc_cart[i].begin(),\n                                            fc_cart[i].end(),\n                                            [](const ForceConstantTable &obj) { return obj.is_ascending_order; });\n    }\n}\n\nstd::vector<size_t> Fcs::get_nfc_cart(const int permutation) const\n{\n    if (permutation) {\n        return nfc_cart_permu;\n    } else {\n        return nfc_cart_nopermu;\n    }\n}\n\nvoid Fcs::get_available_symmop(const size_t nat,\n                               const Symmetry *symmetry,\n                               const std::string basis,\n                               int &nsym_avail,\n                               int **mapping_symm,\n                               double ***rotation,\n                               const bool use_compatible) const\n{\n    // Return mapping information of atoms and the rotation matrices of symmetry operations\n    // that are (compatible, incompatible) with the given lattice basis (Cartesian or Lattice).\n\n    // use_compatible == true returns the compatible space group (for creating fc_table)\n    // use_compatible == false returnes the incompatible supace group (for creating constraint)\n\n    // int k = 0;\n    // for (const auto &it : symmetry->get_SymmData()) {\n    //     std::cout << \"SYMM #\" << ++k << '\\n';\n    //     std::cout << \"compatibility (Cart, Latt): \" << it.compatible_with_cartesian << \" \" << it.compatible_with_lattice << '\\n';\n    //     for (auto i = 0; i < 3; ++i) {\n    //         for (auto j = 0; j < 3; ++j) {\n    //             std::cout << std::setw(15) << it.rotation_cart[i][j];\n    //         }\n    //         std::cout << '\\n';\n    //     }\n    //     std::cout << '\\n';\n    //     for (auto i = 0; i < 3; ++i) {\n    //         for (auto j = 0; j < 3; ++j) {\n    //             std::cout << std::setw(15) << it.rotation[i][j];\n    //         }\n    //         std::cout << '\\n';\n    //     }\n    //     std::cout << '\\n';\n    // }\n\n    int i, j;\n    int counter = 0;\n\n    nsym_avail = 0;\n\n    if (basis == \"Cartesian\") {\n\n        for (auto it = symmetry->get_SymmData().begin(); it != symmetry->get_SymmData().end(); ++it) {\n\n            if ((*it).compatible_with_cartesian == use_compatible) {\n\n                for (i = 0; i < 3; ++i) {\n                    for (j = 0; j < 3; ++j) {\n                        rotation[nsym_avail][i][j] = (*it).rotation_cart[i][j];\n                    }\n                }\n                for (i = 0; i < nat; ++i) {\n                    mapping_symm[i][nsym_avail] = symmetry->get_map_sym()[i][counter];\n                }\n                ++nsym_avail;\n            }\n            ++counter;\n        }\n\n    } else if (basis == \"Lattice\") {\n\n        for (auto it = symmetry->get_SymmData().begin(); it != symmetry->get_SymmData().end(); ++it) {\n            if ((*it).compatible_with_lattice == use_compatible) {\n                for (i = 0; i < 3; ++i) {\n                    for (j = 0; j < 3; ++j) {\n                        rotation[nsym_avail][i][j]\n                            = static_cast<double>((*it).rotation[i][j]);\n                    }\n                }\n                for (i = 0; i < nat; ++i) {\n                    mapping_symm[i][nsym_avail] = symmetry->get_map_sym()[i][counter];\n                }\n                ++nsym_avail;\n            }\n            ++counter;\n        }\n\n\n    } else {\n        deallocate(rotation);\n        deallocate(mapping_symm);\n        exit(\"get_available_symmop\", \"Invalid basis input\");\n    }\n}\n\ndouble Fcs::coef_sym(const int n,\n                     const double * const *rot,\n                     const int *arr1,\n                     const int *arr2) const\n{\n    auto tmp = 1.0;\n\n    for (auto i = 0; i < n; ++i) {\n        tmp *= rot[arr2[i]][arr1[i]];\n    }\n    return tmp;\n}\n\nbool Fcs::is_ascending(const int n,\n                       const int *arr) const\n{\n    for (auto i = 0; i < n - 1; ++i) {\n        if (arr[i] > arr[i + 1]) return false;\n    }\n    return true;\n}\n\nint Fcs::get_minimum_index_in_primitive(const int n,\n                                        const int *arr,\n                                        const size_t nat,\n                                        const size_t natmin,\n                                        const std::vector<std::vector<int>> &map_p2s) const\n{\n    int i, atmnum;\n\n    std::vector<size_t> ind(n, 3 * nat);\n\n    for (i = 0; i < n; ++i) {\n\n        atmnum = arr[i] / 3;\n\n        for (size_t j = 0; j < natmin; ++j) {\n            if (map_p2s[j][0] == atmnum) {\n                ind[i] = arr[i];\n            }\n        }\n    }\n\n    auto minval = ind[0];\n    auto minloc = 0;\n\n    for (i = 0; i < n; ++i) {\n        if (ind[i] < minval) {\n            minval = ind[i];\n            minloc = i;\n        }\n    }\n\n    return minloc;\n}\n\nbool Fcs::is_inprim(const int n,\n                    const int *arr,\n                    const size_t natmin,\n                    const std::vector<std::vector<int>> &map_p2s) const\n{\n    for (auto i = 0; i < n; ++i) {\n        for (size_t j = 0; j < natmin; ++j) {\n            if (map_p2s[j][0] == arr[i]) return true;\n        }\n    }\n    return false;\n}\n\nbool Fcs::is_inprim(const int n,\n                    const size_t natmin,\n                    const std::vector<std::vector<int>> &map_p2s) const\n{\n    const auto atmn = n / 3;\n\n    for (size_t i = 0; i < natmin; ++i) {\n        if (map_p2s[i][0] == atmn) return true;\n    }\n\n    return false;\n}\n\nvoid Fcs::get_xyzcomponent(const int n,\n                           int **xyz) const\n{\n    // Return xyz component for the given order using boost algorithm library\n\n    int i;\n\n    std::vector<int> v(3 * n);\n\n    for (i = 0; i < n; ++i) v[i] = 0;\n    for (i = n; i < 2 * n; ++i) v[i] = 1;\n    for (i = 2 * n; i < 3 * n; ++i) v[i] = 2;\n\n    auto m = 0;\n\n    do {\n        xyz[m][0] = v[0];\n        for (i = 1; i < n; ++i) xyz[m][i] = v[i];\n        ++m;\n    } while (boost::next_partial_permutation(v.begin(), v.begin() + n, v.end()));\n}\n\nbool Fcs::is_allzero(const std::vector<double> &vec,\n                     const double tol,\n                     int &loc) const\n{\n    loc = -1;\n    const auto n = vec.size();\n    for (auto i = 0; i < n; ++i) {\n        if (std::abs(vec[i]) > tol) {\n            loc = i;\n            return false;\n        }\n    }\n    return true;\n}\n\nbool Fcs::is_allzero(const std::vector<int> &vec,\n                     int &loc) const\n{\n    loc = -1;\n    for (auto i = 0; i < vec.size(); ++i) {\n        if (std::abs(vec[i]) > 0) {\n            loc = i;\n            return false;\n        }\n    }\n    return true;\n}\n\nEigen::Matrix3d Fcs::get_basis_conversion_matrix() const\n{\n    return basis_conversion_matrix;\n}\n\nvoid Fcs::set_basis_conversion_matrix(const Cell &supercell)\n{\n    if (preferred_basis == \"Lattice\") {\n        // multiply the scale factor for making the determinant of the basis_conversion_matrix \n        // as one.\n        const auto scale_factor = std::pow(supercell.volume, 1.0 / 3.0) / (2.0 * pi);\n        for (auto i = 0; i < 3; ++i) {\n            for (auto j = 0; j < 3; ++j) {\n                basis_conversion_matrix(i, j)\n                    = supercell.reciprocal_lattice_vector[i][j] * scale_factor;\n            }\n        }\n    } else if (preferred_basis == \"Cartesian\") {\n        for (auto i = 0; i < 3; ++i) {\n            for (auto j = 0; j < 3; ++j) {\n                if (i == j) {\n                    basis_conversion_matrix(i, j) = 1.0;\n                } else {\n                    basis_conversion_matrix(i, j) = 0.0;\n\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "a11a3796e17db124a457f3568159fc0c376ef473", "size": 36923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "alm/fcs.cpp", "max_stars_repo_name": "wichoi77/alamode", "max_stars_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T19:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T19:05:03.000Z", "max_issues_repo_path": "alm/fcs.cpp", "max_issues_repo_name": "wichoi77/alamode", "max_issues_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alm/fcs.cpp", "max_forks_repo_name": "wichoi77/alamode", "max_forks_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T14:01:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T14:01:15.000Z", "avg_line_length": 31.6392459297, "max_line_length": 132, "alphanum_fraction": 0.4682447255, "num_tokens": 8687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.03308598017635717, "lm_q1q2_score": 0.013228160019793694}}
{"text": "#include <iostream>\r\n#include <iomanip>\r\n#include <fstream>\r\n#include <assert.h>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n#include <queue>\r\n#include <boost/regex.hpp>\r\n#include <boost/tokenizer.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <boost/foreach.hpp>\r\n#include <boost/algorithm/string.hpp>\r\n#include \"commands.h\"\r\n#include \"Point.h\"\r\n#include \"Vector.h\"\r\n#include \"ProjPoint.h\"\r\n#include \"TransformationWithFrames.h\"\r\n#include \"TexShape.h\"\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\nconst double\t pi = 3.1415926535897;\r\nconst char polypathstr[] = \"poly\";\r\nconst char polyextstr[] = \".poly\";\r\nconst char texpathstr[] = \"tex\";\r\nboost::filesystem::path polypath(polypathstr);\r\nboost::filesystem::path polyext(polyextstr);\r\n\r\nCommand::~Command() { }\r\n\r\ntoken Command::tokenize_cmd(string command) {\r\n\tchar_separator<char> seq(\" \\\\\");\r\n\treturn token(command, seq);\r\n}\r\n\r\nvoid Command::writePolygons(polygonList polygons, string filename) {\r\n\tboost::filesystem::create_directory(polypathstr);\r\n\tofstream outfile((string(polypathstr) + \"/\" + filename).c_str());\r\n\t//cout << (string(polypathstr) + \"/\" + filename).c_str() << \" created\\n\";\r\n\tBOOST_FOREACH(vector<Point> polygon, polygons) {\r\n\t\tif (polygon.size() < 1)\r\n\t\t\tcontinue;\r\n\t\tBOOST_FOREACH(Point p, polygon) {\r\n\t\t\toutfile << p << \" \";\r\n\t\t}\r\n\t\toutfile << endl;\r\n\t}\r\n\toutfile.close();\r\n}\r\n\r\n/**\r\n * store the command name and filename argument\r\n */\r\ntoken::iterator preparse(token tok, Command &c) {\r\n\ttoken::iterator itr = tok.begin();\r\n\tc.cname = *itr; // command name\r\n\tassert(++itr != tok.end());\r\n\r\n\t// check for file extension\r\n\tcmatch what;\r\n\tregex exp(\"(.*)(\\\\.poly)\");\r\n\tif (regex_match(((string)*itr).c_str(), what, exp)) { // file extension found\r\n\t\tc.filename = what[0];\r\n\t} else { // append file extension\r\n\t\tc.filename = ((string)*itr).append(polyextstr);\r\n\t}\r\n\treturn ++itr;\r\n}\r\n\r\n/**\r\n * convert a transform code in string to enum type\r\n */\r\ncode_t codeStrToEnum(string code) {\r\n\tint index = -1;\r\n\tdo {\r\n\t\tif (string(codeStr[++index]) == code)\r\n\t\t\tbreak;\r\n\t} while ((code_t)index != END);\r\n\tassert((code_t)index != END);\r\n\tcode_t enumcode = (code_t)index;\r\n\treturn enumcode;\r\n}\r\n\r\nMidasPolygon::MidasPolygon(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\t// insert the 2d points\r\n\tfor (; itr != tok.end(); ++itr) {\r\n\t\tdouble x = atof( ((string)*itr).c_str() );\r\n\t\tassert(++itr != tok.end());\r\n\t\tdouble y = atof( ((string)*itr).c_str() );\r\n\t\tint r = 255, g = 255, b = 255;//, a = 255;\r\n\t\ttoken::iterator backtrackItr = itr;\r\n\t\tif (++itr != tok.end()) {\r\n\t\t\tstring color = (string)*itr;\r\n\t\t\tif (color.size() == 6) {\r\n\t\t\t\tstring red = string(\"0x\").append(color.substr(0,2));\r\n\t\t\t\tstring green = string(\"0x\").append(color.substr(2,2));\r\n\t\t\t\tstring blue = string(\"0x\").append(color.substr(4,2));\r\n\t\t\t\t//string alpha = string(\"0x\").append(color.substr(6,2));\r\n\t\t\t\t//cout << red << \" \" << green << \" \" << blue << endl;\r\n\t\t\t\tchar *endptr;\r\n\t\t\t\tr = strtol(red.c_str(), &endptr, 16);\r\n\t\t\t\tg = strtol(green.c_str(), &endptr, 16);\r\n\t\t\t\tb = strtol(blue.c_str(), &endptr, 16);\r\n\t\t\t\t//a = strtol(alpha.c_str(), &endptr, 16);\r\n\t\t\t} else\r\n\t\t\t\titr = backtrackItr;\r\n\t\t} else\r\n\t\t\titr = backtrackItr;\r\n\t\t//cout << r << \" \" << g << \" \" << b << endl;\r\n\t\tPoint p(x, y, 0.0, r, g, b);\r\n\t\t//cout << p << \"\\n\";\r\n\t\tpoints.push_back(p);\r\n\t\t//cout << points.back() << \"\\n\\n\";\r\n\t\tassert(itr != tok.end());\r\n\t}\r\n\t//cout << endl;\r\n}\r\n\r\nvoid MidasPolygon::execute() {\r\n\t//cout << \"Executing Polygon\\n\";\r\n\tboost::filesystem::create_directory(polypathstr);\r\n\tofstream file((string(polypathstr) + \"/\" + this->filename).c_str());\r\n\tBOOST_FOREACH(Point p, this->points) {\r\n\t\tfile << p << \" \";\r\n\t}\r\n\tfile << \"\\n\";\r\n\tfile.close();\r\n}\r\n\r\nAssemble::Assemble(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\r\n\tfor (; itr != tok.end(); ++itr) {\r\n\t\tboost::filesystem::path filepath = polypath / (*itr + polyextstr);\r\n\t\tassert(boost::filesystem::exists(filepath));\r\n\t\tthis->files.push_back(*itr);\r\n\t}\r\n}\r\n\r\nvoid Assemble::execute() {\r\n\t//cout << \"Executing Assemble\\n\";\r\n\tboost::filesystem::create_directory(polypathstr);\r\n\tofstream newfile((string(polypathstr) + \"/\" + this->filename).c_str());\r\n\tBOOST_FOREACH(string thisfile, files) {\r\n\t\tifstream curfile((polypath / (thisfile + polyextstr)).string().c_str());\r\n\t\tchar c;\r\n\t\twhile ((c = curfile.get()) != EOF)\r\n\t\t\tnewfile << c;\r\n\t\tcurfile.close();\r\n\t}\r\n\tnewfile.close();\r\n\t//cout << (string(polypathstr) + \"/\" + this->filename).c_str() << \" assembled\\n\";\r\n}\r\n\r\nTransform::Transform() {\r\n\r\n}\r\n\r\nTransform::Transform(polygonList polygons) {\r\n\tthis->polygons = polygons;\r\n}\r\n\r\nTransform::Transform(projPolygonList projPolygons) {\r\n\tthis->projPolygons = projPolygons;\r\n}\r\n\r\n/**\r\n * transform constructor with argument\r\n * param tok tokenized command\r\n */\r\nTransform::Transform(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\treadPolygons(this->filename, &polygons, &texturedPolygons);\r\n\treadCodes(tok, itr);\r\n}\r\n\r\nvoid Transform::readCodes(token tok, token::iterator itr) {\r\n\tfor(; itr != tok.end(); itr++) {\r\n\t\tcode_t code = codeStrToEnum(*itr);\r\n\t\titr++;\r\n\t\tassert(itr != tok.end());\r\n\t\ttfCmd[code] = new double(atof((*itr).c_str()));\r\n\t}\r\n}\r\n\r\nvector<Point> getCoords(token tok) {\r\n\tvector<Point> newPolygon;\r\n\tvector<string> coords; // put all coords string in a vector\r\n\tBOOST_FOREACH(string s, tok) {\r\n\t\t//cout << s << \" \";\r\n\t\tcoords.push_back(s);\r\n\t\t////cout << coords.back() << \" \";\r\n\t}\r\n\t//cout << endl;\r\n\r\n\tassert(coords.size() % 4 == 0);\r\n\tfor (unsigned int i = 0; i < coords.size(); i += 4) {\r\n\t\tdouble x = atof(coords[i].c_str());\r\n\t\tdouble y = atof(coords[i+1].c_str());\r\n\t\tdouble z = atof(coords[i+2].c_str());\r\n\t\tstring color = coords[i+3];\r\n\t\tassert(color.size() == 6);\r\n\t\tstring red = string(\"0x\").append(color.substr(0,2));\r\n\t\tstring green = string(\"0x\").append(color.substr(2,2));\r\n\t\tstring blue = string(\"0x\").append(color.substr(4,2));\r\n\t\t//string alpha = string(\"0x\").append(color.substr(6,2));\r\n\t\t//cout << red << \" \" << green << \" \" << blue << endl;\r\n\t\tchar *endptr;\r\n\t\tint r = strtol(red.c_str(), &endptr, 16);\r\n\t\tint g = strtol(green.c_str(), &endptr, 16);\r\n\t\tint b = strtol(blue.c_str(), &endptr, 16);\r\n\t\t//int a = strtol(alpha.c_str(), &endptr, 16);\r\n\t\tnewPolygon.push_back(Point(x, y, z, r, g, b));\r\n\t}\r\n\treturn newPolygon;\r\n}\r\n\r\nvoid Command::readPolygons(string filename, polygonList* polygons, texturedPolygonList* texturedPolygons) {\r\n\t//cout << \"Reading \" << filename << \":\\n\";\r\n\tchar c[512];\r\n\tassert(boost::filesystem::exists(polypath / filename));\r\n\t//cout << (string(polypathstr) + \"/\" + filename).c_str() << endl;\r\n\tifstream inf((string(polypathstr) + \"/\" + filename).c_str());\r\n\twhile(inf.good()) {\r\n\t\tinf.getline(c,512);\r\n\t\tif (c[0] == '#' || c[0] == '\\n') // comment or blank lines\r\n\t\t\tcontinue;\r\n\t\tif (c[0] == '\\0')\r\n\t\t\tbreak;\r\n\r\n\t\tstring str(c);\r\n\t\terase_all(str, \")\"); // remove extra characters\r\n\t\terase_all(str, \"(\");\r\n\t\treplace_all(str, \",\", \" \");\r\n//\t\tcout << str << endl;\r\n\r\n\t\tchar_separator<char> sep(\" \"); // tokenize line\r\n\t\ttokenizer<char_separator<char> > tok(str, sep);\r\n\r\n\t\ttoken::iterator itr = tok.begin();\r\n\t\tif (*itr == string(\"t\")) {\t// if textured polygon\r\n\t\t\tTexShape newTexShape;\r\n\t\t\tnewTexShape.texturefile = *(++itr);\r\n\t\t\tint count = atoi((++itr)->c_str());\r\n\t\t\t//cout << count << endl;\r\n\t\t\tfor (int i = 0; i < count; i++) {\r\n\t\t\t\tif (c[0] == '#' || c[0] == '\\n') // comment or blank lines\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tif (c[0] == '\\0')\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tinf.getline(c,512);\r\n\t\t\t\tstr = string(c);\r\n\t\t\t\terase_all(str, \")\"); // remove extra characters\r\n\t\t\t\terase_all(str, \"(\");\r\n\t\t\t\treplace_all(str, \",\", \" \");\r\n\t\t\t\ttok = token(str, sep);\r\n\t\t\t\tnewTexShape.shape.push_back(getCoords(tok));\r\n\r\n\t\t\t\tinf.getline(c,512);\r\n\t\t\t\tstr = string(c);\r\n\t\t\t\terase_all(str, \")\"); // remove extra characters\r\n\t\t\t\terase_all(str, \"(\");\r\n\t\t\t\treplace_all(str, \",\", \" \");\r\n\t\t\t\ttok = token(str, sep);\r\n\t\t\t\tnewTexShape.texture.push_back(getCoords(tok));\r\n\t\t\t}\r\n\t\t\t//newTexShape.print(cout);\r\n\t\t\tif (texturedPolygons) {\r\n\t\t\t\ttexturedPolygons->push_back(newTexShape);\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tvector<Point> newPolygon = getCoords(tok);\r\n\t\tif (newPolygon.size() > 0) // make sure no empty polygon is inserted\r\n\t\t\tpolygons->push_back(newPolygon);\r\n\t}\r\n\tBOOST_FOREACH(vector<Point> polygon, *polygons) {\r\n\t\tBOOST_FOREACH(Point p, polygon) {\r\n\t\t\t//cout << p << \" \";\r\n\t\t}\r\n\t\t//cout << endl;\r\n\t}\r\n\tinf.close();\r\n}\r\n\r\nvoid Transform::execute() {\r\n\t//cout << \"Executing Transform\\n\";\r\n\ttransform(translate() * scale() * rotate(), false);\r\n}\r\n\r\npolygonList Transform::transform(Transformation t, bool project) {\r\n\t//cout << \"Transformation matrix:\\n\";\r\n\t//cout << t << endl;\r\n\tif (!project) { // transforming only\r\n\t\tvector< vector<Point> >::iterator polygonItr = polygons.begin();\r\n\t\tfor(; polygonItr != polygons.end(); polygonItr++) {\r\n\t\t\tvector<Point>::iterator pointItr = (*polygonItr).begin();\r\n\t\t\tfor(; pointItr != (*polygonItr).end(); pointItr++) // apply matrix to each points\r\n\t\t\t\t(*polygonItr).insert((*polygonItr).erase(pointItr),  t.applied_to(*pointItr));\r\n\t\t}\r\n\t\tfor (int i = 0; i < texturedPolygons.size(); i++) {\r\n\t\t\tTexShape *ts = &texturedPolygons[i];\r\n\t\t\tvector< vector<Point> >::iterator polygonItr = ts->shape.begin();\r\n\t\t\tfor(; polygonItr != ts->shape.end(); polygonItr++) {\r\n\t\t\t\tvector<Point>::iterator pointItr = (*polygonItr).begin();\r\n\t\t\t\tfor(; pointItr != (*polygonItr).end(); pointItr++) // apply matrix to each points\r\n\t\t\t\t\t(*polygonItr).insert((*polygonItr).erase(pointItr),  t.applied_to(*pointItr));\r\n\t\t\t}\r\n\t\t}\r\n\t\t//cout << \"polygons: \\n\";\r\n//\t\tBOOST_FOREACH(vector<Point> polygon, polygons) {\r\n//\t\t\tBOOST_FOREACH(Point p, polygon) {\r\n//\t\t\t\tcout << p << \" \";\r\n//\t\t\t}\r\n//\t\t\tcout << endl;\r\n//\t\t}\r\n\t\t//cout << \"textured polygons:\\n\";\r\n//\t\tBOOST_FOREACH(TexShape ts, texturedPolygons) {\r\n//\t\t\tBOOST_FOREACH(vector<Point> shape, ts.shape) {\r\n//\t\t\t\tBOOST_FOREACH(Point p, shape) {\r\n//\t\t\t\t\tcout << p << \" \";\r\n//\t\t\t\t}\r\n//\t\t\t\tcout << endl;\r\n//\t\t\t}\r\n//\t\t}\r\n\t} else { // camera / viewing transform\r\n\t\tvector< vector<ProjPoint> >::iterator polygonItr = projPolygons.begin();\r\n\t\tfor(; polygonItr != projPolygons.end(); polygonItr++) {\r\n\t\t\tvector<ProjPoint>::iterator pointItr = (*polygonItr).begin();\r\n\t\t\tfor(; pointItr != (*polygonItr).end(); pointItr++)\r\n\t\t\t\t(*polygonItr).insert((*polygonItr).erase(pointItr),  t.applied_to(*pointItr));\r\n\t\t}\r\n\r\n//\t\tBOOST_FOREACH(vector<ProjPoint> polygon, projPolygons) {\r\n//\t\t\tBOOST_FOREACH(ProjPoint p, polygon) {\r\n//\t\t\t\t//cout << p << \" \";\r\n//\t\t\t}\r\n//\t\t\t//cout << endl;\r\n//\t\t}\r\n\r\n\t\tpolygons.clear();\r\n\t\tBOOST_FOREACH(vector<ProjPoint> polygon, projPolygons) {\r\n\t\t\tvector<Point> newpolygon;\r\n\t\t\tBOOST_FOREACH(ProjPoint p, polygon) {\r\n//\t\t\t\tif (p.w() < 0)\r\n//\t\t\t\t\tp.setW(-1.0 * p.w());\r\n\t\t\t\t//cout << p << \" \";\r\n\t\t\t\tPoint pp = p.project();\r\n\t\t\t\tnewpolygon.push_back(pp);\r\n\t\t\t}\r\n\t\t\tpolygons.push_back(newpolygon);\r\n\t\t\t//cout << endl;\r\n\t\t}\r\n\t}\r\n\treturn this->polygons;\r\n}\r\n\r\nTransformation Transform::translate() {\r\n\tdouble x = (tfCmd[XT])?*tfCmd[XT]:0.000;\r\n\tdouble y = (tfCmd[YT])?*tfCmd[YT]:0.000;\r\n\tdouble z = (tfCmd[ZT])?*tfCmd[ZT]:0.000;\r\n\t//cout << codeStr[XT] << \": \" << x << endl;\r\n\t//cout << codeStr[YT] << \": \" << y << endl;\r\n\t//cout << codeStr[ZT] << \": \" << z << endl;\r\n\treturn Transformation::translate_by(x, y, z);\r\n}\r\n\r\nTransformation Transform::scale() {\r\n\tdouble x = (tfCmd[XS])?*tfCmd[XS]:1.000;\r\n\tdouble y = (tfCmd[YS])?*tfCmd[YS]:1.000;\r\n\tdouble z = (tfCmd[ZS])?*tfCmd[ZS]:1.000;\r\n\tdouble u = (tfCmd[US])?*tfCmd[US]:1.000;\r\n\t//cout << codeStr[XS] << \": \" << x << endl;\r\n\t//cout << codeStr[YS] << \": \" << y << endl;\r\n\t//cout << codeStr[ZS] << \": \" << z << endl;\r\n\t//cout << codeStr[US] << \": \" << u << endl;\r\n\treturn Transformation::scale_by(x, y, z) * Transformation::scale_by(u, u, u);\r\n}\r\n\r\nTransformation Transform::rotate() {\r\n\tdouble xd = (tfCmd[XD])?*tfCmd[XD]:0.000;\r\n\tdouble yd = (tfCmd[YD])?*tfCmd[YD]:0.000;\r\n\tdouble zd = (tfCmd[ZD])?*tfCmd[ZD]:0.000;\r\n\tdouble xr = (tfCmd[XR])?*tfCmd[XR]:0.000;\r\n\tdouble yr = (tfCmd[YR])?*tfCmd[YR]:0.000;\r\n\tdouble zr = (tfCmd[ZR])?*tfCmd[ZR]:0.000;\r\n\t//cout << codeStr[XD] << \": \" << xd << endl;\r\n\t//cout << codeStr[YD] << \": \" << yd << endl;\r\n\t//cout << codeStr[ZD] << \": \" << zd << endl;\r\n\t//cout << codeStr[XR] << \": \" << xr << endl;\r\n\t//cout << codeStr[YR] << \": \" << yr << endl;\r\n\t//cout << codeStr[ZR] << \": \" << zr << endl;\r\n\treturn Transformation::x_rotate_by(xd) * Transformation::y_rotate_by(yd) *\r\n\t\tTransformation::z_rotate_by(zd) * Transformation::x_rotate_by(xr * 180.0 / pi) *\r\n\t\tTransformation::y_rotate_by(yr * 180.0 / pi) * Transformation::z_rotate_by(zr * 180.0 / pi);\r\n}\r\n\r\n\r\n/**\r\n * create newfile oldfile transforms\r\n */\r\nCreate::Create(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\toutputfile = filename;\r\n\r\n\tassert(itr != tok.end());\r\n\t// check for file extension\r\n\tcmatch what;\r\n\tregex exp(\"(.*)(\\\\.poly)\");\r\n\tif (regex_match(((string)*itr).c_str(), what, exp)) { // file extension found\r\n\t\tfilename = what[0];\r\n\t} else { // append file extension\r\n\t\tfilename = ((string)*itr).append(polyextstr);\r\n\t}\r\n\treadPolygons(filename, &polygons, &texturedPolygons);\r\n\treadCodes(tok, ++itr);\r\n}\r\n\r\nvoid Create::execute() {\r\n\t//cout << \"Executing Create\\n\";\r\n\tTransform::execute();\r\n\twritePolygons(polygons, this->outputfile);\r\n\tBOOST_FOREACH(TexShape ts, texturedPolygons) {\r\n\t\tSurface::writeSurface(ts, outputfile);\r\n\t}\r\n}\r\n\r\nView::View() {\r\n\r\n}\r\n\r\nView::View(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\teyeX = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\teyeY = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\teyeZ = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tupX = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tupY = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tupZ = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tcenterX = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tcenterY = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tcenterZ = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tangle = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tnear = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tfar = atof((*itr).c_str());\r\n\treadPolygons(filename, &polygons, &texturedPolygons);\r\n}\r\n\r\nvoid View::convert() {\r\n\t//cout << \"Converting points to projective space\\n\";\r\n\tBOOST_FOREACH(vector<Point> polygon, polygons) {\r\n\t\tvector<ProjPoint> newpolygon;\r\n\t\tBOOST_FOREACH(Point p, polygon) {\r\n\t\t\tProjPoint pp(p);\r\n\t\t\tnewpolygon.push_back(pp);\r\n\t\t\t//cout << pp << \" \";\r\n\t\t}\r\n\t\tprojPolygons.push_back(newpolygon);\r\n\t\t//cout << endl;\r\n\t}\r\n}\r\n\r\n/**\r\n * view file eyex eyey eyez roll upy pitch centerx centery centerz angle near far\r\n */\r\nvoid View::execute() {\r\n//\tconvert();\r\n\t//cout << \"Executing View\\n\";\r\n//\tFrame f1(Vector(1, 0, 0), Vector(0, 1, 0), Vector(0, 0, 1), Point(centerX, centerY, centerZ));\r\n//\tVector w = Point(eyeX, eyeY, eyeZ) - Point(centerX, centerY, centerZ);\r\n//\tw.normalize();\r\n//\tFrame f2(w, Vector(upX,1,0), Point(eyeX, eyeY, eyeZ));\r\n//\tTransform tf(projPolygons);\r\n//\tTransformation camera_t = Transformation::frame_to_frame(f1, f2);\r\n//\tTransformation viewing_t = Transformation::view(near, far, angle);\r\n//\t//cout << \"Camera:\\n\" << camera_t << endl;\r\n//\t//cout << \"Viewing:\\n\" << viewing_t << endl;\r\n//\tpolygons = tf.transform(camera_t * viewing_t, true);\r\n\t//cout << \"Final Points:\\n\";\r\n//\tBOOST_FOREACH(vector<Point> polygon, polygons) {\r\n//\t\tBOOST_FOREACH(Point p, polygon) {\r\n//\t\t\t//cout << p << \" \";\r\n//\t\t}\r\n//\t\t//cout << endl;\r\n//\t}\r\n}\r\n\r\nExtrude::Extrude(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\tassert(itr != tok.end());\r\n\r\n\tcmatch what;\r\n\tregex exp(\"(.*)(\\\\.poly)\");\r\n\tif (regex_match(((string)*itr).c_str(), what, exp)) { // file extension found\r\n\t\tnewfile = what[0];\r\n\t} else { // append file extension\r\n\t\tnewfile = ((string)*itr).append(polyextstr);\r\n\t}\r\n\tassert(++itr != tok.end());\r\n\tunits = atof((*itr).c_str());\r\n\treadPolygons(filename, &polygons);\r\n}\r\n\r\n/**\r\n * extrude oldfile newfile units\r\n */\r\n\r\nvoid Extrude::execute() {\r\n\t//cout << \"Executing Extrude\\n\";\r\n\tvector<vector<Point> > newPolygons;\r\n\r\n\tBOOST_FOREACH(vector<Point> polygon, polygons) {\r\n\t\tnewPolygons.push_back(polygon); // add the original base\r\n\t\tvector<Point> topFace;\r\n\t\tVector normal;\r\n\t\tfor (unsigned int i = 0; i < polygon.size(); i++) {\r\n\t\t\tif (i == 0) { // get the normal vector from first 3 points\r\n\t\t\t\tVector v1;\r\n\t\t\t\tVector v2;\r\n\t\t\t\tv1 = polygon.back() - polygon[0];\r\n\t\t\t\t//cout << \"v1: \" << v1 << endl;\r\n\t\t\t\tv2 = polygon[i+1] - polygon[i];\r\n\t\t\t\tv1.normalize();\r\n\t\t\t\tv2.normalize();\r\n\t\t\t\t//cout << \"v2: \" << v2 << endl;\r\n\t\t\t\tnormal = cross(v1, v2);\r\n\t\t\t\tnormal.normalize();\r\n\t\t\t\t//cout << \"normal: \" << normal << endl;\r\n\t\t\t\tnormal *= units;\r\n\t\t\t}\r\n\t\t\ttopFace.push_back(polygon[i] + normal); // add the extruded points\r\n\t\t}\r\n//\t\tBOOST_FOREACH(Point p, topFace) {\r\n//\t\t\t//cout << p << \" \";\r\n//\t\t}\r\n\t\t//cout << endl;\r\n\t\tnewPolygons.push_back(topFace); // add extruded face\r\n\r\n\t\t// add the extruded sides\r\n\t\tfor (unsigned int i = 0; i < polygon.size(); i++) {\r\n\t\t\tvector<Point> newSideFace;\r\n\t\t\tnewSideFace.push_back(polygon[i]); // push 2 base points\r\n\t\t\tif (i+1 < polygon.size())\r\n\t\t\t\tnewSideFace.push_back(polygon[i+1]);\r\n\t\t\telse\r\n\t\t\t\tnewSideFace.push_back(polygon[0]);\r\n\t\t\tif (i+1 < topFace.size()) // push 2 top face points\r\n\t\t\t\tnewSideFace.push_back(topFace[i+1]);\r\n\t\t\telse\r\n\t\t\t\tnewSideFace.push_back(topFace[0]);\r\n\t\t\tnewSideFace.push_back(topFace[i]);\r\n\r\n\t\t\tnewPolygons.push_back(newSideFace); // add extruded sides\r\n\t\t}\r\n\r\n//\t\tBOOST_FOREACH(vector<Point> polygon, newPolygons) {\r\n//\t\t\tBOOST_FOREACH(Point p, polygon) {\r\n//\t\t\t\t//cout << p << \" \";\r\n//\t\t\t}\r\n//\t\t\t//cout << endl;\r\n//\t\t}\r\n\r\n\t\twritePolygons(newPolygons, this->newfile);\r\n\r\n\t}\r\n}\r\n\r\nClip::Clip(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\tassert(itr != tok.end());\r\n\r\n\tcmatch what;\r\n\tregex exp(\"(.*)(\\\\.poly)\");\r\n\tif (regex_match(((string)*itr).c_str(), what, exp)) { // file extension found\r\n\t\tnewfile = what[0];\r\n\t} else { // append file extension\r\n\t\tnewfile = ((string)*itr).append(polyextstr);\r\n\t}\r\n\tdouble px, py, pz, nx, ny, nz;\r\n\tassert(++itr != tok.end());\r\n\tpx = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tpy = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tpz = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tnx = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tny = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tnz = atof((*itr).c_str());\r\n\tp = Point(px, py, pz);\r\n\tvnorm = Vector(nx, ny, nz);\r\n\tvnorm.normalize();\r\n\r\n\treadPolygons(filename, &polygons);\r\n}\r\n\r\nvoid Clip::execute() {\r\n\t//cout << \"Executing Clip\" << endl;\r\n\t// get the clipping point\r\n\t//cout << \"p: \" << p << endl << \"vnorm: \" << vnorm << endl;\r\n\tpolygonList clippedPolygons;\r\n\tBOOST_FOREACH(vector<Point> polygon, polygons) {\r\n\t\tvector<Point> clippedPolygon;\r\n\t\tPoint lastPoint = polygon.back();\r\n\t\tBOOST_FOREACH(Point q, polygon) {\r\n\t\t\tfloat d1 = dot(vnorm, (q-p));\r\n\t\t\tfloat d2 = dot(vnorm, (lastPoint - p));\r\n\t\t\t//cout << \"d1: \" << d1 << \" d2: \" << d2 << endl;\r\n\t\t\tif (d1 >= 0.0 && d2 >= 0.0) {\r\n\t\t\t\tclippedPolygon.push_back(q);\r\n\t\t\t\t//cout << q << \" is IN\" << endl;\r\n\t\t\t}\r\n\t\t\telse if (d1 >= 0.0 && d2 < 0.0 || d1 < 0.0 && d2 >= 0.0) { // lastpoint on outside\r\n\t\t\t\tfloat t = d1 / (d1 - d2);\r\n\t\t\t\tPoint I = q + t*(lastPoint - q);\r\n\t\t\t\tPoint *outPoint; // determine which one is out to set color\r\n\t\t\t\tif (d1 >= 0.0) { // current is IN, last is OUT\r\n\t\t\t\t\t//cout << q << \" is IN\\n\";\r\n\t\t\t\t\toutPoint = &lastPoint;\r\n\t\t\t\t} else { // current is OUT, last is IN\r\n\t\t\t\t\t//cout << q << \" is OUT\\n\";\r\n\t\t\t\t\toutPoint = &q;\r\n\t\t\t\t}\r\n\t\t\t\tI.setA(outPoint->a()); // set color of intersection point\r\n\t\t\t\tI.setG(outPoint->g()); //  to the color of point on\r\n\t\t\t\tI.setR(outPoint->r()); //  outside\r\n\t\t\t\tI.setB(outPoint->b());\r\n\t\t\t\t//cout << I << \" is an intersection\\n\";\r\n\t\t\t\tclippedPolygon.push_back(I); // add intersection point to polygon\r\n\t\t\t\tif (d1 >= 0.0) // add current point to polygon if IN\r\n\t\t\t\t\tclippedPolygon.push_back(q);\r\n\t\t\t} else if (d1 == 0.0) { // point is on the plane\r\n\t\t\t\tclippedPolygon.push_back(q);\r\n\t\t\t\t//cout << q << \" is on the plane\\n\";\r\n\t\t\t} else {\r\n\t\t\t\t//cout << q << \" is OUT\\n\";\r\n\t\t\t}\r\n\t\t\tlastPoint = q;\r\n\t\t}\r\n\t\tclippedPolygons.push_back(clippedPolygon);\r\n\t}\r\n\r\n\t//cout << \"clipped polygons:\\n\";\r\n//\tBOOST_FOREACH(vector<Point> clippedPolygon, clippedPolygons) {\r\n//\t\tBOOST_FOREACH(Point cp, clippedPolygon) {\r\n//\t\t\t//cout << cp << \" \";\r\n//\t\t}\r\n//\t\t//cout << endl;\r\n//\t}\r\n\r\n\twritePolygons(clippedPolygons, this->newfile);\r\n}\r\n\r\nVolume::Volume(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\tassert(itr != tok.end());\r\n\r\n\tcmatch what;\r\n\tregex exp(\"(.*)(\\\\.poly)\");\r\n\tif (regex_match(((string)*itr).c_str(), what, exp)) { // file extension found\r\n\t\tnewfile = what[0];\r\n\t} else { // append file extension\r\n\t\tnewfile = ((string)*itr).append(polyextstr);\r\n\t}\r\n\tassert(++itr != tok.end());\r\n\tdouble px = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tdouble py = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tdouble pz = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tdouble vx = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tdouble vy = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tdouble vz = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\talpha = atof((*itr).c_str());\r\n\tassert(++itr != tok.end());\r\n\tresolution = atof((*itr).c_str());\r\n\r\n\treferencePoint = Point(px, py, pz);\r\n\taxis = Vector(vx, vy, vz);\r\n\r\n\treadPolygons(filename, &polygons);\r\n}\r\n\r\nvoid Volume::execute() {\r\n\t//cout << \"Executing Volume\\n\";\r\n\r\n\tpolygonList newPolygons;\r\n\r\n\t//cout << \"\\tTranslating to origin...\\n\";\r\n\tPoint p1 = -referencePoint;\r\n\tTransformation translateTransform = Transformation::translate_by(p1.x(), p1.y(), p1.z());\r\n\tTransform* transformCmd = new Transform(polygons);\r\n\tpolygons = transformCmd->transform(translateTransform, false);\r\n\r\n\tTransformation stepRotate = Transformation::rotate_by(resolution, axis);\r\n\t//cout << \"\\t\" << stepRotate << endl;\r\n\r\n\tpolygonList lastPolygons = polygons;\r\n\tdouble curRotated = 0.0;\r\n\r\n\tfor (; curRotated <= alpha; curRotated += resolution) {\r\n\t\t//cout << \"\\tRotated by \" << curRotated << \" degrees\\n\";\r\n\t\tpolygons = transformCmd->transform(stepRotate, false);\r\n\t\tfor(unsigned int i = 0; i < polygons.size(); i++) {\r\n\t\t\tvector<Point> polygon = polygons[i];\r\n\t\t\tvector<Point> lastpolygon = lastPolygons[i];\r\n\t\t\tnewPolygons.push_back(lastpolygon);\r\n\t\t\tif (curRotated + resolution >= alpha)\r\n\t\t\t\tnewPolygons.push_back(polygon);\r\n\r\n\t\t\tfor(unsigned int j = 0; j < polygon.size(); j++) {\r\n\t\t\t\tvector<Point> newSideFace;\r\n\t\t\t\tnewSideFace.push_back(polygon[j]); // push 2 base points\r\n\t\t\t\tif (j+1 < polygon.size())\r\n\t\t\t\t\tnewSideFace.push_back(polygon[j+1]);\r\n\t\t\t\telse\r\n\t\t\t\t\tnewSideFace.push_back(polygon[0]);\r\n\t\t\t\tif (j+1 < lastpolygon.size()) // push 2 top face points\r\n\t\t\t\t\tnewSideFace.push_back(lastpolygon[j+1]);\r\n\t\t\t\telse\r\n\t\t\t\t\tnewSideFace.push_back(lastpolygon[0]);\r\n\t\t\t\tnewSideFace.push_back(lastpolygon[j]);\r\n\r\n\t\t\t\tnewPolygons.push_back(newSideFace); // add surfaces\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\tlastPolygons = polygons;\r\n\t}\r\n\tif (curRotated < alpha) {\r\n\t\t// generate one more volume to close surface\r\n\t}\r\n\r\n\t//cout << \"\\tTranslating back to original position...\\n\";\r\n\tPoint p0 = referencePoint;\r\n\ttranslateTransform = Transformation::translate_by(p0.x(), p0.y(), p0.z());\r\n\tif (transformCmd) delete transformCmd;\r\n\ttransformCmd = new Transform(newPolygons);\r\n\tnewPolygons = transformCmd->transform(translateTransform, false);\r\n\r\n\twritePolygons(newPolygons, newfile);\r\n}\r\n\r\nSurface::Surface(token tok) {\r\n\ttoken::iterator itr = preparse(tok, *this);\r\n\tassert(itr != tok.end());\r\n\ttexturefile = *itr;\r\n\titr++;\r\n\tint level = atoi((*itr).c_str());\r\n\tassert(level >= 0);\r\n\r\n\tmatrix<Point> patch(4,4);\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tfor (int j = 0; j < 4; j++) {\r\n\t\t\tassert(++itr != tok.end());\r\n\t\t\tint x = atoi((*itr).c_str());\r\n\t\t\tassert(++itr != tok.end());\r\n\t\t\tint y = atoi((*itr).c_str());\r\n\t\t\tassert(++itr != tok.end());\r\n\t\t\tint z = atoi((*itr).c_str());\r\n\t\t\tpatch(i,j) = Point(x,y,z);\r\n\t\t}\r\n\t}\r\n\tsurface = new BezierPatch(patch);\r\n\tsurface->refine(level);\r\n}\r\n\r\nvoid Surface::execute() {\r\n\tcout << \"Executing Surface...\" << endl;\r\n\tmatrix<Point> patch = surface->flatten();\r\n\tfor (unsigned int i = 0; i < patch.RowNo()-1; i++) {\r\n\t\tfor (unsigned int j = 0; j < patch.ColNo()-1; j++) {\r\n\t\t\tvector<Point> polygon;\r\n\t\t\tvector<Point> texCoords;\r\n\t\t\tpolygon.push_back(Point(patch(i,j))); // top left\r\n\t\t\ttexCoords.push_back( Point(\r\n\t\t\t\t\t(double)j/((double)patch.ColNo()-1.0),\r\n\t\t\t\t\t1.0-(double)i/((double)patch.RowNo()-1.0) ) );\r\n\t\t\tpolygon.push_back(Point(patch(i,j+1))); // top right\r\n\t\t\ttexCoords.push_back( Point(\r\n\t\t\t\t\t(double)(j+1)/((double)patch.ColNo()-1.0),\r\n\t\t\t\t\t1.0-(double)i/((double)patch.RowNo()-1.0) ) );\r\n\t\t\tpolygon.push_back(Point(patch(i+1,j+1))); // bottom right\r\n\t\t\ttexCoords.push_back( Point(\r\n\t\t\t\t\t(double)(j+1)/((double)patch.ColNo()-1.0),\r\n\t\t\t\t\t1.0-(double)(i+1)/((double)patch.RowNo()-1.0) ) );\r\n\t\t\tpolygon.push_back(Point(patch(i+1,j))); // bottom left\r\n\t\t\ttexCoords.push_back( Point(\r\n\t\t\t\t\t(double)j/((double)patch.ColNo()-1.0),\r\n\t\t\t\t\t1.0-(double)(i+1)/((double)patch.RowNo()-1.0) ) );\r\n\t\t\tpolygons.shape.push_back(polygon);\r\n\t\t\tpolygons.texture.push_back(texCoords);\r\n\t\t\tpolygons.texturefile = texturefile;\r\n\t\t}\r\n\t}\r\n\twriteSurface(polygons, filename, ios_base::trunc);\r\n}\r\n\r\nvoid Surface::writeSurface(TexShape polygons, string filename, ios_base::openmode mode) {\r\n\tboost::filesystem::create_directory(polypathstr);\r\n\tofstream outfile((string(polypathstr) + \"/\" + filename).c_str(), mode);\r\n\tpolygons.print(outfile);\r\n\toutfile.close();\r\n\tcout << (string(polypathstr) + \"/\" + filename).c_str() << \" created\\n\";\r\n}\r\n", "meta": {"hexsha": "af33b11b2dfde468db6e860226b84139a3e27520", "size": 25680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "commands.cpp", "max_stars_repo_name": "eddy-chan/midas", "max_stars_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "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": "commands.cpp", "max_issues_repo_name": "eddy-chan/midas", "max_issues_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "commands.cpp", "max_forks_repo_name": "eddy-chan/midas", "max_forks_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0144927536, "max_line_length": 108, "alphanum_fraction": 0.5972741433, "num_tokens": 7476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.042087724160866216, "lm_q1q2_score": 0.013217672169770128}}
{"text": "//  (C) Copyright John Maddock 2008.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_SPECIAL_NEXT_HPP\n#define BOOST_MATH_SPECIAL_NEXT_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/tools/traits.hpp>\n\n#include <float.h>\n\n#if !defined(_CRAYC) && !defined(__CUDACC__) && (!defined(__GNUC__) || (__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ > 3)))\n#if (defined(_M_IX86_FP) && (_M_IX86_FP >= 2)) || defined(__SSE2__)\n#include \"xmmintrin.h\"\n#define BOOST_MATH_CHECK_SSE2\n#endif\n#endif\n\nnamespace boost{ namespace math{\n\n   namespace concepts {\n\n      class real_concept;\n      class std_real_concept;\n\n   }\n\nnamespace detail{\n\ntemplate <class T>\nstruct has_hidden_guard_digits;\ntemplate <>\nstruct has_hidden_guard_digits<float> : public std::false_type {};\ntemplate <>\nstruct has_hidden_guard_digits<double> : public std::false_type {};\ntemplate <>\nstruct has_hidden_guard_digits<long double> : public std::false_type {};\n#ifdef BOOST_HAS_FLOAT128\ntemplate <>\nstruct has_hidden_guard_digits<__float128> : public std::false_type {};\n#endif\ntemplate <>\nstruct has_hidden_guard_digits<boost::math::concepts::real_concept> : public std::false_type {};\ntemplate <>\nstruct has_hidden_guard_digits<boost::math::concepts::std_real_concept> : public std::false_type {};\n\ntemplate <class T, bool b>\nstruct has_hidden_guard_digits_10 : public std::false_type {};\ntemplate <class T>\nstruct has_hidden_guard_digits_10<T, true> : public std::integral_constant<bool, (std::numeric_limits<T>::digits10 != std::numeric_limits<T>::max_digits10)> {};\n\ntemplate <class T>\nstruct has_hidden_guard_digits \n   : public has_hidden_guard_digits_10<T, \n   std::numeric_limits<T>::is_specialized\n   && (std::numeric_limits<T>::radix == 10) >\n{};\n\ntemplate <class T>\ninline const T& normalize_value(const T& val, const std::false_type&) { return val; }\ntemplate <class T>\ninline T normalize_value(const T& val, const std::true_type&) \n{\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::radix != 2);\n\n   boost::intmax_t shift = (boost::intmax_t)std::numeric_limits<T>::digits - (boost::intmax_t)ilogb(val) - 1;\n   T result = scalbn(val, shift);\n   result = round(result);\n   return scalbn(result, -shift); \n}\n\ntemplate <class T>\ninline T get_smallest_value(std::true_type const&)\n{\n   //\n   // numeric_limits lies about denorms being present - particularly\n   // when this can be turned on or off at runtime, as is the case\n   // when using the SSE2 registers in DAZ or FTZ mode.\n   //\n   static const T m = std::numeric_limits<T>::denorm_min();\n#ifdef BOOST_MATH_CHECK_SSE2\n   return (_mm_getcsr() & (_MM_FLUSH_ZERO_ON | 0x40)) ? tools::min_value<T>() : m;\n#else\n   return ((tools::min_value<T>() / 2) == 0) ? tools::min_value<T>() : m;\n#endif\n}\n\ntemplate <class T>\ninline T get_smallest_value(std::false_type const&)\n{\n   return tools::min_value<T>();\n}\n\ntemplate <class T>\ninline T get_smallest_value()\n{\n#if defined(BOOST_MSVC) && (BOOST_MSVC <= 1310)\n   return get_smallest_value<T>(std::integral_constant<bool, std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == 1)>());\n#else\n   return get_smallest_value<T>(std::integral_constant<bool, std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::has_denorm == std::denorm_present)>());\n#endif\n}\n\n//\n// Returns the smallest value that won't generate denorms when\n// we calculate the value of the least-significant-bit:\n//\ntemplate <class T>\nT get_min_shift_value();\n\ntemplate <class T>\nstruct min_shift_initializer\n{\n   struct init\n   {\n      init()\n      {\n         do_init();\n      }\n      static void do_init()\n      {\n         get_min_shift_value<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 min_shift_initializer<T>::init min_shift_initializer<T>::initializer;\n\ntemplate <class T>\ninline T calc_min_shifted(const std::true_type&)\n{\n   BOOST_MATH_STD_USING\n   return ldexp(tools::min_value<T>(), tools::digits<T>() + 1);\n}\ntemplate <class T>\ninline T calc_min_shifted(const std::false_type&)\n{\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::radix != 2);\n\n   return scalbn(tools::min_value<T>(), std::numeric_limits<T>::digits + 1);\n}\n\n\ntemplate <class T>\ninline T get_min_shift_value()\n{\n   static const T val = calc_min_shifted<T>(std::integral_constant<bool, !std::numeric_limits<T>::is_specialized || std::numeric_limits<T>::radix == 2>());\n   min_shift_initializer<T>::force_instantiate();\n\n   return val;\n}\n\ntemplate <class T, bool b = boost::math::tools::detail::has_backend_type<T>::value>\nstruct exponent_type\n{\n   typedef int type;\n};\n\ntemplate <class T>\nstruct exponent_type<T, true>\n{\n   typedef typename T::backend_type::exponent_type type;\n};\n\ntemplate <class T, class Policy>\nT float_next_imp(const T& val, const std::true_type&, const Policy& pol)\n{\n   typedef typename exponent_type<T>::type exponent_type;\n   \n   BOOST_MATH_STD_USING\n   exponent_type expon;\n   static const char* function = \"float_next<%1%>(%1%)\";\n\n   int fpclass = (boost::math::fpclassify)(val);\n\n   if((fpclass == (int)FP_NAN) || (fpclass == (int)FP_INFINITE))\n   {\n      if(val < 0)\n         return -tools::max_value<T>();\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument must be finite, but got %1%\", val, pol);\n   }\n\n   if(val >= tools::max_value<T>())\n      return policies::raise_overflow_error<T>(function, 0, pol);\n\n   if(val == 0)\n      return detail::get_smallest_value<T>();\n\n   if((fpclass != (int)FP_SUBNORMAL) && (fpclass != (int)FP_ZERO) && (fabs(val) < detail::get_min_shift_value<T>()) && (val != -tools::min_value<T>()))\n   {\n      //\n      // Special case: if the value of the least significant bit is a denorm, and the result\n      // would not be a denorm, then shift the input, increment, and shift back.\n      // This avoids issues with the Intel SSE2 registers when the FTZ or DAZ flags are set.\n      //\n      return ldexp(float_next(T(ldexp(val, 2 * tools::digits<T>())), pol), -2 * tools::digits<T>());\n   }\n\n   if(-0.5f == frexp(val, &expon))\n      --expon; // reduce exponent when val is a power of two, and negative.\n   T diff = ldexp(T(1), expon - tools::digits<T>());\n   if(diff == 0)\n      diff = detail::get_smallest_value<T>();\n   return val + diff;\n} // float_next_imp\n//\n// Special version for some base other than 2:\n//\ntemplate <class T, class Policy>\nT float_next_imp(const T& val, const std::false_type&, const Policy& pol)\n{\n   typedef typename exponent_type<T>::type exponent_type;\n\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::radix != 2);\n\n   BOOST_MATH_STD_USING\n   exponent_type expon;\n   static const char* function = \"float_next<%1%>(%1%)\";\n\n   int fpclass = (boost::math::fpclassify)(val);\n\n   if((fpclass == (int)FP_NAN) || (fpclass == (int)FP_INFINITE))\n   {\n      if(val < 0)\n         return -tools::max_value<T>();\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument must be finite, but got %1%\", val, pol);\n   }\n\n   if(val >= tools::max_value<T>())\n      return policies::raise_overflow_error<T>(function, 0, pol);\n\n   if(val == 0)\n      return detail::get_smallest_value<T>();\n\n   if((fpclass != (int)FP_SUBNORMAL) && (fpclass != (int)FP_ZERO) && (fabs(val) < detail::get_min_shift_value<T>()) && (val != -tools::min_value<T>()))\n   {\n      //\n      // Special case: if the value of the least significant bit is a denorm, and the result\n      // would not be a denorm, then shift the input, increment, and shift back.\n      // This avoids issues with the Intel SSE2 registers when the FTZ or DAZ flags are set.\n      //\n      return scalbn(float_next(T(scalbn(val, 2 * std::numeric_limits<T>::digits)), pol), -2 * std::numeric_limits<T>::digits);\n   }\n\n   expon = 1 + ilogb(val);\n   if(-1 == scalbn(val, -expon) * std::numeric_limits<T>::radix)\n      --expon; // reduce exponent when val is a power of base, and negative.\n   T diff = scalbn(T(1), expon - std::numeric_limits<T>::digits);\n   if(diff == 0)\n      diff = detail::get_smallest_value<T>();\n   return val + diff;\n} // float_next_imp\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type float_next(const T& val, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   return detail::float_next_imp(detail::normalize_value(static_cast<result_type>(val), typename detail::has_hidden_guard_digits<result_type>::type()), std::integral_constant<bool, !std::numeric_limits<result_type>::is_specialized || (std::numeric_limits<result_type>::radix == 2)>(), pol);\n}\n\n#if 0 //def BOOST_MSVC\n//\n// We used to use ::_nextafter here, but doing so fails when using\n// the SSE2 registers if the FTZ or DAZ flags are set, so use our own\n// - albeit slower - code instead as at least that gives the correct answer.\n//\ntemplate <class Policy>\ninline double float_next(const double& val, const Policy& pol)\n{\n   static const char* function = \"float_next<%1%>(%1%)\";\n\n   if(!(boost::math::isfinite)(val) && (val > 0))\n      return policies::raise_domain_error<double>(\n         function,\n         \"Argument must be finite, but got %1%\", val, pol);\n\n   if(val >= tools::max_value<double>())\n      return policies::raise_overflow_error<double>(function, 0, pol);\n\n   return ::_nextafter(val, tools::max_value<double>());\n}\n#endif\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type float_next(const T& val)\n{\n   return float_next(val, policies::policy<>());\n}\n\nnamespace detail{\n\ntemplate <class T, class Policy>\nT float_prior_imp(const T& val, const std::true_type&, const Policy& pol)\n{\n   typedef typename exponent_type<T>::type exponent_type;\n\n   BOOST_MATH_STD_USING\n   exponent_type expon;\n   static const char* function = \"float_prior<%1%>(%1%)\";\n\n   int fpclass = (boost::math::fpclassify)(val);\n\n   if((fpclass == (int)FP_NAN) || (fpclass == (int)FP_INFINITE))\n   {\n      if(val > 0)\n         return tools::max_value<T>();\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument must be finite, but got %1%\", val, pol);\n   }\n\n   if(val <= -tools::max_value<T>())\n      return -policies::raise_overflow_error<T>(function, 0, pol);\n\n   if(val == 0)\n      return -detail::get_smallest_value<T>();\n\n   if((fpclass != (int)FP_SUBNORMAL) && (fpclass != (int)FP_ZERO) && (fabs(val) < detail::get_min_shift_value<T>()) && (val != tools::min_value<T>()))\n   {\n      //\n      // Special case: if the value of the least significant bit is a denorm, and the result\n      // would not be a denorm, then shift the input, increment, and shift back.\n      // This avoids issues with the Intel SSE2 registers when the FTZ or DAZ flags are set.\n      //\n      return ldexp(float_prior(T(ldexp(val, 2 * tools::digits<T>())), pol), -2 * tools::digits<T>());\n   }\n\n   T remain = frexp(val, &expon);\n   if(remain == 0.5f)\n      --expon; // when val is a power of two we must reduce the exponent\n   T diff = ldexp(T(1), expon - tools::digits<T>());\n   if(diff == 0)\n      diff = detail::get_smallest_value<T>();\n   return val - diff;\n} // float_prior_imp\n//\n// Special version for bases other than 2:\n//\ntemplate <class T, class Policy>\nT float_prior_imp(const T& val, const std::false_type&, const Policy& pol)\n{\n   typedef typename exponent_type<T>::type exponent_type;\n\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::radix != 2);\n\n   BOOST_MATH_STD_USING\n   exponent_type expon;\n   static const char* function = \"float_prior<%1%>(%1%)\";\n\n   int fpclass = (boost::math::fpclassify)(val);\n\n   if((fpclass == (int)FP_NAN) || (fpclass == (int)FP_INFINITE))\n   {\n      if(val > 0)\n         return tools::max_value<T>();\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument must be finite, but got %1%\", val, pol);\n   }\n\n   if(val <= -tools::max_value<T>())\n      return -policies::raise_overflow_error<T>(function, 0, pol);\n\n   if(val == 0)\n      return -detail::get_smallest_value<T>();\n\n   if((fpclass != (int)FP_SUBNORMAL) && (fpclass != (int)FP_ZERO) && (fabs(val) < detail::get_min_shift_value<T>()) && (val != tools::min_value<T>()))\n   {\n      //\n      // Special case: if the value of the least significant bit is a denorm, and the result\n      // would not be a denorm, then shift the input, increment, and shift back.\n      // This avoids issues with the Intel SSE2 registers when the FTZ or DAZ flags are set.\n      //\n      return scalbn(float_prior(T(scalbn(val, 2 * std::numeric_limits<T>::digits)), pol), -2 * std::numeric_limits<T>::digits);\n   }\n\n   expon = 1 + ilogb(val);\n   T remain = scalbn(val, -expon);\n   if(remain * std::numeric_limits<T>::radix == 1)\n      --expon; // when val is a power of two we must reduce the exponent\n   T diff = scalbn(T(1), expon - std::numeric_limits<T>::digits);\n   if(diff == 0)\n      diff = detail::get_smallest_value<T>();\n   return val - diff;\n} // float_prior_imp\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type float_prior(const T& val, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   return detail::float_prior_imp(detail::normalize_value(static_cast<result_type>(val), typename detail::has_hidden_guard_digits<result_type>::type()), std::integral_constant<bool, !std::numeric_limits<result_type>::is_specialized || (std::numeric_limits<result_type>::radix == 2)>(), pol);\n}\n\n#if 0 //def BOOST_MSVC\n//\n// We used to use ::_nextafter here, but doing so fails when using\n// the SSE2 registers if the FTZ or DAZ flags are set, so use our own\n// - albeit slower - code instead as at least that gives the correct answer.\n//\ntemplate <class Policy>\ninline double float_prior(const double& val, const Policy& pol)\n{\n   static const char* function = \"float_prior<%1%>(%1%)\";\n\n   if(!(boost::math::isfinite)(val) && (val < 0))\n      return policies::raise_domain_error<double>(\n         function,\n         \"Argument must be finite, but got %1%\", val, pol);\n\n   if(val <= -tools::max_value<double>())\n      return -policies::raise_overflow_error<double>(function, 0, pol);\n\n   return ::_nextafter(val, -tools::max_value<double>());\n}\n#endif\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type float_prior(const T& val)\n{\n   return float_prior(val, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type nextafter(const T& val, const U& direction, const Policy& pol)\n{\n   typedef typename tools::promote_args<T, U>::type result_type;\n   return val < direction ? boost::math::float_next<result_type>(val, pol) : val == direction ? val : boost::math::float_prior<result_type>(val, pol);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type nextafter(const T& val, const U& direction)\n{\n   return nextafter(val, direction, policies::policy<>());\n}\n\nnamespace detail{\n\ntemplate <class T, class Policy>\nT float_distance_imp(const T& a, const T& b, const std::true_type&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   //\n   // Error handling:\n   //\n   static const char* function = \"float_distance<%1%>(%1%, %1%)\";\n   if(!(boost::math::isfinite)(a))\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument a must be finite, but got %1%\", a, pol);\n   if(!(boost::math::isfinite)(b))\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument b must be finite, but got %1%\", b, pol);\n   //\n   // Special cases:\n   //\n   if(a > b)\n      return -float_distance(b, a, pol);\n   if(a == b)\n      return T(0);\n   if(a == 0)\n      return 1 + fabs(float_distance(static_cast<T>((b < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), b, pol));\n   if(b == 0)\n      return 1 + fabs(float_distance(static_cast<T>((a < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), a, pol));\n   if(boost::math::sign(a) != boost::math::sign(b))\n      return 2 + fabs(float_distance(static_cast<T>((b < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), b, pol))\n         + fabs(float_distance(static_cast<T>((a < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), a, pol));\n   //\n   // By the time we get here, both a and b must have the same sign, we want\n   // b > a and both positive for the following logic:\n   //\n   if(a < 0)\n      return float_distance(static_cast<T>(-b), static_cast<T>(-a), pol);\n\n   BOOST_ASSERT(a >= 0);\n   BOOST_ASSERT(b >= a);\n\n   int expon;\n   //\n   // Note that if a is a denorm then the usual formula fails\n   // because we actually have fewer than tools::digits<T>()\n   // significant bits in the representation:\n   //\n   (void)frexp(((boost::math::fpclassify)(a) == (int)FP_SUBNORMAL) ? tools::min_value<T>() : a, &expon);\n   T upper = ldexp(T(1), expon);\n   T result = T(0);\n   //\n   // If b is greater than upper, then we *must* split the calculation\n   // as the size of the ULP changes with each order of magnitude change:\n   //\n   if(b > upper)\n   {\n      int expon2;\n      (void)frexp(b, &expon2);\n      T upper2 = ldexp(T(0.5), expon2);\n      result = float_distance(upper2, b);\n      result += (expon2 - expon - 1) * ldexp(T(1), tools::digits<T>() - 1);\n   }\n   //\n   // Use compensated double-double addition to avoid rounding\n   // errors in the subtraction:\n   //\n   expon = tools::digits<T>() - expon;\n   T mb, x, y, z;\n   if(((boost::math::fpclassify)(a) == (int)FP_SUBNORMAL) || (b - a < tools::min_value<T>()))\n   {\n      //\n      // Special case - either one end of the range is a denormal, or else the difference is.\n      // The regular code will fail if we're using the SSE2 registers on Intel and either\n      // the FTZ or DAZ flags are set.\n      //\n      T a2 = ldexp(a, tools::digits<T>());\n      T b2 = ldexp(b, tools::digits<T>());\n      mb = -(std::min)(T(ldexp(upper, tools::digits<T>())), b2);\n      x = a2 + mb;\n      z = x - a2;\n      y = (a2 - (x - z)) + (mb - z);\n\n      expon -= tools::digits<T>();\n   }\n   else\n   {\n      mb = -(std::min)(upper, b);\n      x = a + mb;\n      z = x - a;\n      y = (a - (x - z)) + (mb - z);\n   }\n   if(x < 0)\n   {\n      x = -x;\n      y = -y;\n   }\n   result += ldexp(x, expon) + ldexp(y, expon);\n   //\n   // Result must be an integer:\n   //\n   BOOST_ASSERT(result == floor(result));\n   return result;\n} // float_distance_imp\n//\n// Special versions for bases other than 2:\n//\ntemplate <class T, class Policy>\nT float_distance_imp(const T& a, const T& b, const std::false_type&, const Policy& pol)\n{\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::radix != 2);\n\n   BOOST_MATH_STD_USING\n   //\n   // Error handling:\n   //\n   static const char* function = \"float_distance<%1%>(%1%, %1%)\";\n   if(!(boost::math::isfinite)(a))\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument a must be finite, but got %1%\", a, pol);\n   if(!(boost::math::isfinite)(b))\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument b must be finite, but got %1%\", b, pol);\n   //\n   // Special cases:\n   //\n   if(a > b)\n      return -float_distance(b, a, pol);\n   if(a == b)\n      return T(0);\n   if(a == 0)\n      return 1 + fabs(float_distance(static_cast<T>((b < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), b, pol));\n   if(b == 0)\n      return 1 + fabs(float_distance(static_cast<T>((a < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), a, pol));\n   if(boost::math::sign(a) != boost::math::sign(b))\n      return 2 + fabs(float_distance(static_cast<T>((b < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), b, pol))\n         + fabs(float_distance(static_cast<T>((a < 0) ? T(-detail::get_smallest_value<T>()) : detail::get_smallest_value<T>()), a, pol));\n   //\n   // By the time we get here, both a and b must have the same sign, we want\n   // b > a and both positive for the following logic:\n   //\n   if(a < 0)\n      return float_distance(static_cast<T>(-b), static_cast<T>(-a), pol);\n\n   BOOST_ASSERT(a >= 0);\n   BOOST_ASSERT(b >= a);\n\n   boost::intmax_t expon;\n   //\n   // Note that if a is a denorm then the usual formula fails\n   // because we actually have fewer than tools::digits<T>()\n   // significant bits in the representation:\n   //\n   expon = 1 + ilogb(((boost::math::fpclassify)(a) == (int)FP_SUBNORMAL) ? tools::min_value<T>() : a);\n   T upper = scalbn(T(1), expon);\n   T result = T(0);\n   //\n   // If b is greater than upper, then we *must* split the calculation\n   // as the size of the ULP changes with each order of magnitude change:\n   //\n   if(b > upper)\n   {\n      boost::intmax_t expon2 = 1 + ilogb(b);\n      T upper2 = scalbn(T(1), expon2 - 1);\n      result = float_distance(upper2, b);\n      result += (expon2 - expon - 1) * scalbn(T(1), std::numeric_limits<T>::digits - 1);\n   }\n   //\n   // Use compensated double-double addition to avoid rounding\n   // errors in the subtraction:\n   //\n   expon = std::numeric_limits<T>::digits - expon;\n   T mb, x, y, z;\n   if(((boost::math::fpclassify)(a) == (int)FP_SUBNORMAL) || (b - a < tools::min_value<T>()))\n   {\n      //\n      // Special case - either one end of the range is a denormal, or else the difference is.\n      // The regular code will fail if we're using the SSE2 registers on Intel and either\n      // the FTZ or DAZ flags are set.\n      //\n      T a2 = scalbn(a, std::numeric_limits<T>::digits);\n      T b2 = scalbn(b, std::numeric_limits<T>::digits);\n      mb = -(std::min)(T(scalbn(upper, std::numeric_limits<T>::digits)), b2);\n      x = a2 + mb;\n      z = x - a2;\n      y = (a2 - (x - z)) + (mb - z);\n\n      expon -= std::numeric_limits<T>::digits;\n   }\n   else\n   {\n      mb = -(std::min)(upper, b);\n      x = a + mb;\n      z = x - a;\n      y = (a - (x - z)) + (mb - z);\n   }\n   if(x < 0)\n   {\n      x = -x;\n      y = -y;\n   }\n   result += scalbn(x, expon) + scalbn(y, expon);\n   //\n   // Result must be an integer:\n   //\n   BOOST_ASSERT(result == floor(result));\n   return result;\n} // float_distance_imp\n\n} // namespace detail\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type float_distance(const T& a, const U& b, const Policy& pol)\n{\n   //\n   // We allow ONE of a and b to be an integer type, otherwise both must be the SAME type.\n   //\n   BOOST_STATIC_ASSERT_MSG(\n      (boost::is_same<T, U>::value \n      || (boost::is_integral<T>::value && !boost::is_integral<U>::value) \n      || (!boost::is_integral<T>::value && boost::is_integral<U>::value)\n      || (std::numeric_limits<T>::is_specialized && std::numeric_limits<U>::is_specialized\n         && (std::numeric_limits<T>::digits == std::numeric_limits<U>::digits)\n         && (std::numeric_limits<T>::radix == std::numeric_limits<U>::radix)\n         && !std::numeric_limits<T>::is_integer && !std::numeric_limits<U>::is_integer)),\n      \"Float distance between two different floating point types is undefined.\");\n\n   BOOST_IF_CONSTEXPR (!boost::is_same<T, U>::value)\n   {\n      BOOST_IF_CONSTEXPR(boost::is_integral<T>::value)\n      {\n         return float_distance(static_cast<U>(a), b, pol);\n      }\n      else\n      {\n         return float_distance(a, static_cast<T>(b), pol);\n      }\n   }\n   else\n   {\n      typedef typename tools::promote_args<T, U>::type result_type;\n      return detail::float_distance_imp(detail::normalize_value(static_cast<result_type>(a), typename detail::has_hidden_guard_digits<result_type>::type()), detail::normalize_value(static_cast<result_type>(b), typename detail::has_hidden_guard_digits<result_type>::type()), std::integral_constant<bool, !std::numeric_limits<result_type>::is_specialized || (std::numeric_limits<result_type>::radix == 2)>(), pol);\n   }\n}\n\ntemplate <class T, class U>\ntypename tools::promote_args<T, U>::type float_distance(const T& a, const U& b)\n{\n   return boost::math::float_distance(a, b, policies::policy<>());\n}\n\nnamespace detail{\n\ntemplate <class T, class Policy>\nT float_advance_imp(T val, int distance, const std::true_type&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   //\n   // Error handling:\n   //\n   static const char* function = \"float_advance<%1%>(%1%, int)\";\n\n   int fpclass = (boost::math::fpclassify)(val);\n\n   if((fpclass == (int)FP_NAN) || (fpclass == (int)FP_INFINITE))\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument val must be finite, but got %1%\", val, pol);\n\n   if(val < 0)\n      return -float_advance(-val, -distance, pol);\n   if(distance == 0)\n      return val;\n   if(distance == 1)\n      return float_next(val, pol);\n   if(distance == -1)\n      return float_prior(val, pol);\n\n   if(fabs(val) < detail::get_min_shift_value<T>())\n   {\n      //\n      // Special case: if the value of the least significant bit is a denorm,\n      // implement in terms of float_next/float_prior.\n      // This avoids issues with the Intel SSE2 registers when the FTZ or DAZ flags are set.\n      //\n      if(distance > 0)\n      {\n         do{ val = float_next(val, pol); } while(--distance);\n      }\n      else\n      {\n         do{ val = float_prior(val, pol); } while(++distance);\n      }\n      return val;\n   }\n\n   int expon;\n   (void)frexp(val, &expon);\n   T limit = ldexp((distance < 0 ? T(0.5f) : T(1)), expon);\n   if(val <= tools::min_value<T>())\n   {\n      limit = sign(T(distance)) * tools::min_value<T>();\n   }\n   T limit_distance = float_distance(val, limit);\n   while(fabs(limit_distance) < abs(distance))\n   {\n      distance -= itrunc(limit_distance);\n      val = limit;\n      if(distance < 0)\n      {\n         limit /= 2;\n         expon--;\n      }\n      else\n      {\n         limit *= 2;\n         expon++;\n      }\n      limit_distance = float_distance(val, limit);\n      if(distance && (limit_distance == 0))\n      {\n         return policies::raise_evaluation_error<T>(function, \"Internal logic failed while trying to increment floating point value %1%: most likely your FPU is in non-IEEE conforming mode.\", val, pol);\n      }\n   }\n   if((0.5f == frexp(val, &expon)) && (distance < 0))\n      --expon;\n   T diff = 0;\n   if(val != 0)\n      diff = distance * ldexp(T(1), expon - tools::digits<T>());\n   if(diff == 0)\n      diff = distance * detail::get_smallest_value<T>();\n   return val += diff;\n} // float_advance_imp\n//\n// Special version for bases other than 2:\n//\ntemplate <class T, class Policy>\nT float_advance_imp(T val, int distance, const std::false_type&, const Policy& pol)\n{\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT(std::numeric_limits<T>::radix != 2);\n\n   BOOST_MATH_STD_USING\n   //\n   // Error handling:\n   //\n   static const char* function = \"float_advance<%1%>(%1%, int)\";\n\n   int fpclass = (boost::math::fpclassify)(val);\n\n   if((fpclass == (int)FP_NAN) || (fpclass == (int)FP_INFINITE))\n      return policies::raise_domain_error<T>(\n         function,\n         \"Argument val must be finite, but got %1%\", val, pol);\n\n   if(val < 0)\n      return -float_advance(-val, -distance, pol);\n   if(distance == 0)\n      return val;\n   if(distance == 1)\n      return float_next(val, pol);\n   if(distance == -1)\n      return float_prior(val, pol);\n\n   if(fabs(val) < detail::get_min_shift_value<T>())\n   {\n      //\n      // Special case: if the value of the least significant bit is a denorm,\n      // implement in terms of float_next/float_prior.\n      // This avoids issues with the Intel SSE2 registers when the FTZ or DAZ flags are set.\n      //\n      if(distance > 0)\n      {\n         do{ val = float_next(val, pol); } while(--distance);\n      }\n      else\n      {\n         do{ val = float_prior(val, pol); } while(++distance);\n      }\n      return val;\n   }\n\n   boost::intmax_t expon = 1 + ilogb(val);\n   T limit = scalbn(T(1), distance < 0 ? expon - 1 : expon);\n   if(val <= tools::min_value<T>())\n   {\n      limit = sign(T(distance)) * tools::min_value<T>();\n   }\n   T limit_distance = float_distance(val, limit);\n   while(fabs(limit_distance) < abs(distance))\n   {\n      distance -= itrunc(limit_distance);\n      val = limit;\n      if(distance < 0)\n      {\n         limit /= std::numeric_limits<T>::radix;\n         expon--;\n      }\n      else\n      {\n         limit *= std::numeric_limits<T>::radix;\n         expon++;\n      }\n      limit_distance = float_distance(val, limit);\n      if(distance && (limit_distance == 0))\n      {\n         return policies::raise_evaluation_error<T>(function, \"Internal logic failed while trying to increment floating point value %1%: most likely your FPU is in non-IEEE conforming mode.\", val, pol);\n      }\n   }\n   /*expon = 1 + ilogb(val);\n   if((1 == scalbn(val, 1 + expon)) && (distance < 0))\n      --expon;*/\n   T diff = 0;\n   if(val != 0)\n      diff = distance * scalbn(T(1), expon - std::numeric_limits<T>::digits);\n   if(diff == 0)\n      diff = distance * detail::get_smallest_value<T>();\n   return val += diff;\n} // float_advance_imp\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type float_advance(T val, int distance, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   return detail::float_advance_imp(detail::normalize_value(static_cast<result_type>(val), typename detail::has_hidden_guard_digits<result_type>::type()), distance, std::integral_constant<bool, !std::numeric_limits<result_type>::is_specialized || (std::numeric_limits<result_type>::radix == 2)>(), pol);\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type float_advance(const T& val, int distance)\n{\n   return boost::math::float_advance(val, distance, policies::policy<>());\n}\n\n}} // boost math namespaces\n\n#endif // BOOST_MATH_SPECIAL_NEXT_HPP\n", "meta": {"hexsha": "4477e7da3f8d86ba52d8662dafd23320e0743811", "size": 30561, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/special_functions/next.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/special_functions/next.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/special_functions/next.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": 33.6945975744, "max_line_length": 412, "alphanum_fraction": 0.6421910278, "num_tokens": 8308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.03789242472824807, "lm_q1q2_score": 0.013211009034610139}}
{"text": "/* Hector -- A Simple Climate Model\n   Copyright (C) 2014-2015  Battelle Memorial Institute\n\n   Please see the accompanying file LICENSE.md for additional licensing\n   information.\n*/\n/*\n *  forcing_component.cpp\n *  hector\n *\n *  Created by Ben on 02 March 2011.\n *\n */\n\n#include <boost/array.hpp>\n#include <math.h>\n\n#include \"forcing_component.hpp\"\n#include \"halocarbon_component.hpp\"\n#include \"core.hpp\"\n#include \"dependency_finder.hpp\"\n#include \"h_util.hpp\"\n#include \"avisitor.hpp\"\n\nnamespace Hector {\n\n/* These next two arrays and the map that connects them are a\n * workaround for the problems created by storing the halocarbon\n * forcings in the halocarbon components.  Because the halocarbon\n * components don't know about the base year adjustments, they can't\n * provide the forcings relative to the base year, which is what\n * outside callers will generally want.  Internally, however, we still\n * need to be able to get the raw forcings from the halocarbon\n * components, so we can't just change everything to point at the\n * forcing component (which would return the base year adjusted value).\n *\n * The solution we adopted was to create a second set of capabilities\n * to refer to the adjusted values, and we let the forcing component\n * intercept those.  However, the forcing values themselves are stored\n * under the names used for the unadjusted values, so we have to have\n * a name translation table so that we can find the data that the\n * message is asking for.  In the end, the whole process winds up\n * being a little ugly, but it gets the job done.\n */\n\nconst char *ForcingComponent::adjusted_halo_forcings[N_HALO_FORCINGS] = {\n    D_RFADJ_CF4,\n    D_RFADJ_C2F6,\n    D_RFADJ_HFC23,\n    D_RFADJ_HFC32,\n    D_RFADJ_HFC4310,\n    D_RFADJ_HFC125,\n    D_RFADJ_HFC134a,\n    D_RFADJ_HFC143a,\n    D_RFADJ_HFC227ea,\n    D_RFADJ_HFC245fa,\n    D_RFADJ_SF6,\n    D_RFADJ_CFC11,\n    D_RFADJ_CFC12,\n    D_RFADJ_CFC113,\n    D_RFADJ_CFC114,\n    D_RFADJ_CFC115,\n    D_RFADJ_CCl4,\n    D_RFADJ_CH3CCl3,\n    D_RFADJ_HCF22,\n    D_RFADJ_HCF141b,\n    D_RFADJ_HCF142b,\n    D_RFADJ_halon1211,\n    D_RFADJ_halon1301,\n    D_RFADJ_halon2402,\n    D_RFADJ_CH3Cl,\n    D_RFADJ_CH3Br\n};\n\nconst char *ForcingComponent::halo_forcing_names[N_HALO_FORCINGS] = {\n    D_RF_CF4,\n    D_RF_C2F6,\n    D_RF_HFC23,\n    D_RF_HFC32,\n    D_RF_HFC4310,\n    D_RF_HFC125,\n    D_RF_HFC134a,\n    D_RF_HFC143a,\n    D_RF_HFC227ea,\n    D_RF_HFC245fa,\n    D_RF_SF6,\n    D_RF_CFC11,\n    D_RF_CFC12,\n    D_RF_CFC113,\n    D_RF_CFC114,\n    D_RF_CFC115,\n    D_RF_CCl4,\n    D_RF_CH3CCl3,\n    D_RF_HCF22,\n    D_RF_HCF141b,\n    D_RF_HCF142b,\n    D_RF_halon1211,\n    D_RF_halon1301,\n    D_RF_halon2402,\n    D_RF_CH3Cl,\n    D_RF_CH3Br \n};\n\nstd::map<std::string, std::string> ForcingComponent::forcing_name_map;\n\nusing namespace std;\n\n//------------------------------------------------------------------------------\n/*! \\brief Constructor\n */\nForcingComponent::ForcingComponent() {\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Destructor\n */\nForcingComponent::~ForcingComponent() {\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nstring ForcingComponent::getComponentName() const {\n    const string name = FORCING_COMPONENT_NAME;\n    return name;\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid ForcingComponent::init( Core* coreptr ) {\n    \n    logger.open( getComponentName(), false, coreptr->getGlobalLogger().getEchoToFile(), coreptr->getGlobalLogger().getMinLogLevel() );\n    H_LOG( logger, Logger::DEBUG ) << \"hello \" << getComponentName() << std::endl;\n    \n    core = coreptr;\n    \n    baseyear = 0.0;\n    currentYear = 0.0;\n    \n    Ftot_constrain.allowInterp( true );\n    Ftot_constrain.name = D_RF_TOTAL;\n    \n    // Register the data we can provide\n    core->registerCapability( D_RF_TOTAL, getComponentName() );\n    core->registerCapability( D_RF_BASEYEAR, getComponentName() );\n    core->registerCapability( D_RF_CO2, getComponentName());\n    core->registerCapability( D_RF_CH4, getComponentName());\n    core->registerCapability( D_RF_N2O, getComponentName());\n    core->registerCapability( D_RF_H2O, getComponentName());\n    core->registerCapability( D_RF_O3, getComponentName());\n    core->registerCapability( D_RF_BC, getComponentName());\n    core->registerCapability( D_RF_OC, getComponentName());\n    core->registerCapability( D_RF_SO2d, getComponentName());\n    core->registerCapability( D_RF_SO2i, getComponentName());\n    core->registerCapability( D_RF_SO2, getComponentName());\n    core->registerCapability( D_RF_VOL, getComponentName());\n    for(int i=0; i<N_HALO_FORCINGS; ++i) {\n        core->registerCapability(adjusted_halo_forcings[i], getComponentName());\n        forcing_name_map[adjusted_halo_forcings[i]] = halo_forcing_names[i];\n    }\n    \n    // Register our dependencies\n\n    core->registerDependency( D_ATMOSPHERIC_CH4, getComponentName() );\n    core->registerDependency( D_ATMOSPHERIC_CO2, getComponentName() );\n    core->registerDependency( D_ATMOSPHERIC_O3, getComponentName() );\n    core->registerDependency( D_EMISSIONS_BC, getComponentName() );\n    core->registerDependency( D_EMISSIONS_OC, getComponentName() );\n    core->registerDependency( D_NATURAL_SO2, getComponentName() );\n    core->registerDependency( D_ATMOSPHERIC_N2O, getComponentName() );\n    \n    core->registerDependency( D_RF_CF4, getComponentName() );\n    core->registerDependency( D_RF_C2F6, getComponentName() );\n    core->registerDependency( D_RF_HFC23, getComponentName() );\n    core->registerDependency( D_RF_HFC32, getComponentName() );\n    core->registerDependency( D_RF_HFC4310, getComponentName() );\n    core->registerDependency( D_RF_HFC125, getComponentName() );\n    core->registerDependency( D_RF_HFC134a, getComponentName() );\n    core->registerDependency( D_RF_HFC143a, getComponentName() );\n    core->registerDependency( D_RF_HFC227ea, getComponentName() );\n    core->registerDependency( D_RF_HFC245fa, getComponentName() );\n    core->registerDependency( D_RF_SF6, getComponentName() );\n    core->registerDependency( D_RF_CFC11, getComponentName() );\n    core->registerDependency( D_RF_CFC12, getComponentName() );\n    core->registerDependency( D_RF_CFC113, getComponentName() );\n    core->registerDependency( D_RF_CFC114, getComponentName() );\n    core->registerDependency( D_RF_CFC115, getComponentName() );\n    core->registerDependency( D_RF_CCl4, getComponentName() );\n    core->registerDependency( D_RF_CH3CCl3, getComponentName() );\n    core->registerDependency( D_RF_HCF22, getComponentName() );\n    core->registerDependency( D_RF_HCF141b, getComponentName() );\n    core->registerDependency( D_RF_HCF142b, getComponentName() );\n    core->registerDependency( D_RF_halon1211, getComponentName() );\n    core->registerDependency( D_RF_halon1301, getComponentName() );\n    core->registerDependency( D_RF_halon2402, getComponentName() );\n    core->registerDependency( D_RF_CH3Br, getComponentName() );\n    core->registerDependency( D_RF_CH3Cl, getComponentName() );\n    core->registerDependency( D_RF_T_ALBEDO, getComponentName() );\n}\n    \n//------------------------------------------------------------------------------\n// documentation is inherited\nunitval ForcingComponent::sendMessage( const std::string& message,\n                                      const std::string& datum,\n                                      const message_data info ) throw ( h_exception )\n{\n    unitval returnval;\n    \n    if( message==M_GETDATA ) {          //! Caller is requesting data\n        return getData( datum, info.date );\n        \n    } else if( message==M_SETDATA ) {   //! Caller is requesting to set data\n        //TODO: call setData below\n        //TODO: change core so that parsing is routed through sendMessage\n        //TODO: make setData private\n        \n    } else {                        //! We don't handle any other messages\n        H_THROW( \"Caller sent unknown message: \"+message );\n    }\n    \n    return returnval;\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid ForcingComponent::setData( const string& varName,\n                                const message_data& data ) throw ( h_exception )\n{\n    H_LOG( logger, Logger::DEBUG ) << \"Setting \" << varName << \"[\" << data.date << \"]=\" << data.value_str << std::endl;\n    \n    try {\n        if( varName == D_RF_BASEYEAR ) {\n            H_ASSERT( data.date == Core::undefinedIndex(), \"date not allowed\" );\n            baseyear = data.getUnitval(U_UNDEFINED);\n        } else if( varName == D_FTOT_CONSTRAIN ) {\n            H_ASSERT( data.date != Core::undefinedIndex(), \"date required\" );\n            Ftot_constrain.set(data.date, data.getUnitval(U_W_M2));\n        } else {\n            H_LOG( logger, Logger::DEBUG ) << \"Unknown variable \" << varName << std::endl;\n            H_THROW( \"Unknown variable name while parsing \"+ getComponentName() + \": \"\n                    + varName );\n        }\n    } catch( h_exception& parseException ) {\n        H_RETHROW( parseException, \"Could not parse var: \"+varName );\n    }\n}\n    \n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid ForcingComponent::prepareToRun() throw ( h_exception ) {\n    \n    H_LOG( logger, Logger::DEBUG ) << \"prepareToRun \" << std::endl;\n    \n    if( baseyear==0.0 )\n        baseyear = core->getStartDate() + 1;        // default, if not supplied by user\n    H_LOG( logger, Logger::DEBUG ) << \"Base year for reporting is \" << baseyear << std::endl;\n    \n    H_ASSERT( baseyear > core->getStartDate(), \"Base year must be >= model start date\" );\n    \n    if( Ftot_constrain.size() ) {\n        Logger& glog = core->getGlobalLogger();\n        H_LOG( glog, Logger::WARNING ) << \"Total forcing will be overwritten by user-supplied values!\" << std::endl;\n    }\n    \n    baseyear_forcings.clear();\n}\n    \n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid ForcingComponent::run( const double runToDate ) throw ( h_exception ) {\n    \n    // Calculate instantaneous radiative forcing for any & all agents\n    // As each is computed, push it into 'forcings' map for Ftot calculation.\n\t// Note that forcings have to be mutually exclusive, there are no subtotals for different species.\n    H_LOG( logger, Logger::DEBUG ) << \"-----------------------------\" << std::endl;\n    currentYear = runToDate;\n    \n    if( runToDate < baseyear ) {\n        H_LOG( logger, Logger::DEBUG ) << \"not yet at baseyear\" << std::endl;\n    } else {\n        forcings_t forcings;\n        \n        // ---------- CO2 ----------\n        // Instantaneous radiative forcings for CO2, CH4, and N2O from http://www.esrl.noaa.gov/gmd/aggi/\n        // These are in turn from IPCC (2001)\n        \n        // This is identical to that of MAGICC; see Meinshausen et al. (2011)\n        unitval Ca = core->sendMessage( M_GETDATA, D_ATMOSPHERIC_CO2 );\n        if( runToDate==baseyear )\n            C0 = Ca;\n        forcings[D_RF_CO2 ].set( 5.35 * log( Ca/C0 ), U_W_M2 );\n        \n        // ---------- Terrestrial albedo ----------\n        if( core->checkCapability( D_RF_T_ALBEDO ) ) {\n            forcings[ D_RF_T_ALBEDO ] = core->sendMessage( M_GETDATA, D_RF_T_ALBEDO, message_data( runToDate ) );\n        }\n        \n        // ---------- N2O and CH4 ----------\n        // Equations from Joos et al., 2001\n        if( core->checkCapability( D_ATMOSPHERIC_CH4 ) && core->checkCapability( D_ATMOSPHERIC_N2O ) ) {\n            \n#define f(M,N) 0.47 * log( 1 + 2.01 * 1e-5 * pow( M * N, 0.75 ) + 5.31 * 1e-15 * M * pow( M * N, 1.52 ) )\n            double Ma = core->sendMessage( M_GETDATA, D_ATMOSPHERIC_CH4, message_data( runToDate ) ).value( U_PPBV_CH4 );\n            double M0 = core->sendMessage( M_GETDATA, D_PREINDUSTRIAL_CH4 ).value( U_PPBV_CH4 );\n            double Na = core->sendMessage( M_GETDATA, D_ATMOSPHERIC_N2O, message_data( runToDate ) ).value( U_PPBV_N2O );\n            double N0 = core->sendMessage( M_GETDATA, D_PREINDUSTRIAL_N2O ).value( U_PPBV_N2O );\n            \n            double fch4 =  0.036 * ( sqrt( Ma ) - sqrt( M0 ) ) - ( f( Ma, N0 ) - f( M0, N0 ) );\n            forcings[D_RF_CH4].set( fch4, U_W_M2 );\n            \n            double fn2o =  0.12 * ( sqrt( Na ) - sqrt( N0 ) ) - ( f( M0, Na ) - f( M0, N0 ) );\n            forcings[D_RF_N2O].set( fn2o, U_W_M2 );\n            \n            // ---------- Stratospheric H2O from CH4 oxidation ----------\n            // From Tanaka et al, 2007, but using Joos et al., 2001 value of 0.05\n            const double fh2o = 0.05 * ( 0.036 * ( sqrt( Ma ) - sqrt( M0 ) ) );\n            forcings[D_RF_H2O].set( fh2o, U_W_M2 );\n        }\n        \n        // ---------- Troposheric Ozone ----------\n        if( core->checkCapability( D_ATMOSPHERIC_O3 ) ) {\n            //from Tanaka et al, 2007\n            const double ozone = core->sendMessage( M_GETDATA, D_ATMOSPHERIC_O3, message_data( runToDate ) ).value( U_DU_O3 );\n            const double fo3 = 0.042 * ozone;\n            forcings[D_RF_O3].set( fo3, U_W_M2 );\n        }\n        \n        // ---------- Halocarbons ----------\n        // TODO: Would like to just 'know' all the halocarbon instances out there\n        boost::array<string, 26> halos = {\n            {\n                D_RF_CF4,\n                D_RF_C2F6,\n                D_RF_HFC23,\n                D_RF_HFC32,\n                D_RF_HFC4310,\n                D_RF_HFC125,\n                D_RF_HFC134a,\n                D_RF_HFC143a,\n                D_RF_HFC227ea,\n                D_RF_HFC245fa,\n                D_RF_SF6,\n                D_RF_CFC11,\n                D_RF_CFC12,\n                D_RF_CFC113,\n                D_RF_CFC114,\n                D_RF_CFC115,\n                D_RF_CCl4,\n                D_RF_CH3CCl3,\n                D_RF_HCF22,\n                D_RF_HCF141b,\n                D_RF_HCF142b,\n                D_RF_halon1211,\n                D_RF_halon1301,\n                D_RF_halon2402,\n                D_RF_CH3Cl,\n                D_RF_CH3Br\n            }\n        };\n        \n        // Halocarbons can be disabled individually via the input file, so we run through all possible ones\n         for (unsigned hc=0; hc<halos.size(); ++hc) {\n            if( core->checkCapability( halos[hc] ) ) {\n                // Forcing values are actually computed by the halocarbon itself\n                forcings[ halos[hc] ] = core->sendMessage( M_GETDATA, halos[hc], message_data( runToDate ) );\n                }\n        }\n        \n        // ---------- Black carbon ----------\n        if( core->checkCapability( D_EMISSIONS_BC ) ) {\n            double fbc = 0.0743 * core->sendMessage( M_GETDATA, D_EMISSIONS_BC, message_data( runToDate ) ).value( U_TG );\n            forcings[D_RF_BC].set( fbc, U_W_M2 );\n            // includes both indirect and direct forcings from Bond et al 2013, Journal of Geophysical Research Atmo (table C1 - Central)\n        }\n        \n        // ---------- Organic carbon ----------\n        if( core->checkCapability( D_EMISSIONS_OC ) ) {\n            double foc = -0.0128 * core->sendMessage( M_GETDATA, D_EMISSIONS_OC, message_data( runToDate ) ).value( U_TG );\n            forcings[D_RF_OC].set( foc, U_W_M2 );\n            // includes both indirect and direct forcings from Bond et al 2013, Journal of Geophysical Research Atmo (table C1 - Central).\n            // The fossil fuel and biomass are weighted (-4.5) then added to the snow and clouds for a total of -12.8 (personal communication Steve Smith, PNNL)\n        }\n        \n        // ---------- Sulphate Aerosols ----------\n        if( core->checkCapability( D_NATURAL_SO2 ) && core->checkCapability( D_EMISSIONS_SO2 ) ) {\n            \n            unitval S0 = core->sendMessage( M_GETDATA, D_2000_SO2 );\n            unitval SN = core->sendMessage( M_GETDATA, D_NATURAL_SO2 );\n            \n            // Includes only direct forcings from Forster et al 2007 (IPCC)\n            // Equations from Joos et al., 2001\n            H_ASSERT( S0.value( U_GG_S ) >0, \"S0 is 0\" );\n            unitval emission = core->sendMessage( M_GETDATA, D_EMISSIONS_SO2, message_data( runToDate ) );\n            double fso2d = -0.35 * emission/S0;\n            forcings[D_RF_SO2d].set( fso2d, U_W_M2 );\n            // includes only direct forcings from Forster etal 2007 (IPCC)\n            \n            // Indirect aerosol effect via changes in cloud properties\n            const double a = -0.6 * ( log( ( SN.value( U_GG_S ) + emission.value( U_GG_S ) ) / SN.value( U_GG_S ) ) ); // -.6\n            const double b =  pow ( log ( ( SN.value( U_GG_S ) + S0.value( U_GG_S ) ) / SN.value( U_GG_S ) ), -1 );\n            double fso2i = a * b;\n            forcings[D_RF_SO2i].set( fso2i, U_W_M2 );\n        }\n        \n        if( core->checkCapability( D_VOLCANIC_SO2 ) ) {\n            // Volcanic forcings\n            forcings[D_RF_VOL] = core->sendMessage( M_GETDATA, D_VOLCANIC_SO2, message_data( runToDate ) );\n        }\n        \n        // ---------- Total ----------\n        unitval Ftot( 0.0, U_W_M2 );  // W/m2\n        for( forcingsIterator it = forcings.begin(); it != forcings.end(); ++it ) {\n            Ftot = Ftot + ( *it ).second;\n            H_LOG( logger, Logger::DEBUG ) << \"forcing \" << ( *it).first << \" in \" << runToDate << \" is \" << ( *it ).second << std::endl;\n        }\n        \n        // If the user has supplied total forcing data, use that\n        if( Ftot_constrain.size() && runToDate <= Ftot_constrain.lastdate() ) {\n            H_LOG( logger, Logger::WARNING ) << \"** Overwriting total forcing with user-supplied value\" << std::endl;\n            forcings[ D_RF_TOTAL ] = Ftot_constrain.get( runToDate );\n        } else {\n            forcings[ D_RF_TOTAL ] = Ftot;\n        }\n        H_LOG( logger, Logger::DEBUG ) << \"forcing total is \" << forcings[ D_RF_TOTAL ] << std::endl;\n        \n        //---------- Change to relative forcing ----------\n        // Note that the code below assumes model is always consistently run from base-year forward. \n        // Results will not be consistent if parameters are changed but base-year is not re-run.\n\n       // At this point, we've computed all absolute forcings. If base year, save those values\n        if( runToDate==baseyear ) {\n            H_LOG( logger, Logger::DEBUG ) << \"** At base year! Storing current forcing values\" << std::endl;\n            baseyear_forcings = forcings;\n        }\n        \n        // Subtract base year forcing values from forcings, i.e. make them relative to base year\n        for( forcingsIterator it = forcings.begin(); it != forcings.end(); ++it ) {\n            forcings[ ( *it ).first ] = ( *it ).second - baseyear_forcings[ ( *it ).first ];\n        }\n\n        // Store the forcings that we have calculated\n        forcings_ts.set(runToDate, forcings);\n    }\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nunitval ForcingComponent::getData( const std::string& varName,\n                                  const double date ) throw ( h_exception ) {\n    \n    \n    unitval returnval;\n    double getdate = date;             // This is why I hate declaring PBV args as const!\n    \n    if(getdate == Core::undefinedIndex()) {\n        // If no date specified, provide the current date\n        getdate = currentYear;\n    }\n\n    if(getdate < baseyear) {\n        // Forcing component hasn't run yet, so there is no data to get.\n        returnval.set(0.0, U_W_M2);\n        return returnval;\n    }\n\n    H_LOG(logger, Logger::DEBUG) << \"getData request, time= \"\n                                 << getdate\n                                 << \"  baseyear = \"\n                                 << baseyear\n                                 << std::endl;\n    \n    forcings_t forcings(forcings_ts.get(getdate));\n\n    if( varName == D_RF_BASEYEAR ) {\n        returnval.set( baseyear, U_UNITLESS );\n    } else if (varName == D_RF_SO2) {\n        // total SO2 forcing\n        std::map<std::string, unitval>::const_iterator forcing_SO2d = forcings.find( D_RF_SO2d );\n        std::map<std::string, unitval>::const_iterator forcing_SO2i = forcings.find( D_RF_SO2i );\n        if ( forcing_SO2d != forcings.end() ) {\n            if ( forcing_SO2i != forcings.end() ) {\n                returnval = forcing_SO2d->second + forcing_SO2i->second;\n            } else {\n                returnval = forcing_SO2d->second;\n            }\n        } else {\n            if ( forcing_SO2i != forcings.end() ) {\n                returnval = forcing_SO2i->second;\n            } else {\n                returnval.set( 0.0, U_W_M2 );\n            }\n        }\n    } else {\n        std::string forcing_name;\n        auto forcit = forcing_name_map.find(varName);\n        if(forcit != forcing_name_map.end()) {\n            forcing_name = forcing_name_map[varName];\n        }\n        else {\n            forcing_name = varName;\n        }\n        std::map<std::string, unitval>::const_iterator forcing = forcings.find(forcing_name);\n        if ( forcing != forcings.end() ) {\n            // from the forcing map\n            returnval = forcing->second;\n        } else {\n            if (currentYear < baseyear) {\n                returnval.set( 0.0, U_W_M2 );\n            } else {\n                H_THROW( \"Caller is requesting unknown variable: \" + varName );\n            }\n        }\n    }\n    \n    return returnval;\n}\n\nvoid ForcingComponent::reset(double time) throw(h_exception)\n{\n    // Set the current year to the reset year, and drop outputs after the reset year.\n    currentYear = time;\n    forcings_ts.truncate(time);\n    H_LOG(logger, Logger::NOTICE)\n        << getComponentName() << \" reset to time= \" << time << \"\\n\";\n}\n\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid ForcingComponent::shutDown() {\n\tH_LOG( logger, Logger::DEBUG ) << \"goodbye \" << getComponentName() << std::endl;\n    logger.close();\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid ForcingComponent::accept( AVisitor* visitor ) {\n    visitor->visit( this );\n}\n\n}\n", "meta": {"hexsha": "16524cd2219df5082754c497a4b1e50f90aae2d6", "size": 22276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/forcing_component.cpp", "max_stars_repo_name": "bvegawe/hector", "max_stars_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/forcing_component.cpp", "max_issues_repo_name": "bvegawe/hector", "max_issues_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/forcing_component.cpp", "max_forks_repo_name": "bvegawe/hector", "max_forks_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_forks_repo_licenses": ["ECL-2.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.1756007394, "max_line_length": 160, "alphanum_fraction": 0.5843059795, "num_tokens": 5709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.039048291048794204, "lm_q1q2_score": 0.013201333419907587}}
{"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\n#include <list>\n// uncomment to disable assert() calls\n// #define NDEBUG\n#include <cassert>\n\n#include <boost/python.hpp>\n#include <boost/foreach.hpp>\n\n#include \"point.h\"\n#include \"triangle.h\"\n#include \"millingcutter.h\"\n#include \"numeric.h\"\n#include \"octree.h\"\n#include \"ocode.h\"\n\n//#define DEBUG_BUILD_OCT\n\nnamespace ocl\n{\n\n\n\n\n//**************** LinOCT ********************/\n\nLinOCT::LinOCT() {\n    clist.clear();\n}\n\nint LinOCT::size() const {\n    return clist.size();\n}\n\nvoid LinOCT::append(Ocode& code) {\n    clist.push_back( code );\n}\n\nvoid LinOCT::delete_at(std::list<Ocode>::iterator& it) { \n    clist.erase( it );\n}\n\n\nvoid LinOCT::expand_at(std::list<Ocode>::iterator& itr) {\n    // note: there was a valid-index check here\n    // consider checking that itr is valid?\n       // if ( itr->expandable()) {  // was: clist[idx].expandable()\n            std::list<Ocode> newnodes = itr->expand(); // the new nodes  clist[idx]                \n            BOOST_FOREACH( Ocode o, newnodes) {\n                clist.insert(itr, o);\n            }\n\n            // delete old node\n            std::list<Ocode>::iterator temp;\n            temp = itr;\n            itr--; // jump out of the way from erase()\n            clist.erase(temp);\n        /*} else {\n            std::cout << \"LinOCT::expand_at() cannot expand \" << *itr << \"!\\n\";\n        }*/\n    return;\n}\n\n/// initialize octree and expand min_expans times\nvoid LinOCT::init(int min_expand) \n{\n    // assume the list is empty.\n    if (size() > 0) {\n        std::cout << \"cannot call LinOCT::init() on non-empty tree! \\n\";\n        assert(0);\n    }\n    \n    Ocode o = Ocode(); // create an onode, initally all \"8\"\n    o.init();\n    append(o);\n    \n    for (int m=0; m<min_expand ; m++) { // go through the list min_expand times\n        \n        std::list<Ocode>::iterator itr;\n        std::list<Ocode>::iterator current_end;\n        itr = clist.begin();\n        current_end = clist.end();        \n        for(int n=0; n<size() ; n++) {\n            if ( itr->expandable() ) { // if expandable\n                //std::cout << \" init() expanding \" << *itr << \"\\n\";\n                expand_at(itr); // expand the node\n                //std::cout << \" after expand itr= \" << *itr << \"\\n\";\n                n=n+7; // jump forward, since we have inserted new nodes\n                itr++; // after expand(), itr points to the last expanded node\n                       // so jump forward to expand next node\n                if ( itr == clist.end() )\n                    itr--; // unless at the end of list\n            }\n        }\n        // std::cout << \" LinOCT:init() m=\" << m << \" N=\" << size() << \"\\n\";\n    }\n    return;\n}\n\n/// build LinOCT octree from input volume OCTVolume\nvoid LinOCT::build(OCTVolume* vol)\n{   // loop through the whole list:\n    // - deleting white nodes \n    // - expanding grey nodes if possible\n    // - skipping over black nodes (only these remain when done) \n    // std::cout << size() << \" nodes before build()\\n\";\n    std::list<Ocode>::iterator it;\n    std::list<Ocode>::iterator temp;\n    it = clist.begin();\n    int calc_calls = 0;\n    while ( it != clist.end()  ) { \n        if (  ! (vol->isInsideBBo( *it )) ) { // nodes outside bounding-box can be deleted\n            temp = it;\n            if ( it != clist.begin() ) \n                it--; // jump back out of the way from erase()\n            else\n                it++;\n            clist.erase(temp);\n        }\n        else {  // this ocode contains the bounding-box\n            it->calcScore( vol ); // expensive call...\n            ++calc_calls;\n            if ( (it->score == 9) ) { // black node\n                it++; // node is black, so leave it in the list, and move forward\n            } else if ( (it->score == 0) && (it->deg > 5) ) { \n                temp = it;\n                if ( it != clist.begin() ) \n                    it--; // jump out of the way from erase()\n                else\n                    it++;\n                clist.erase(temp); // white node, delete.\n            }\n            else { // grey node, expand if possible, otherwise delete\n                if ( it->expandable() ) {\n                    temp = it;\n                    bool first=false; \n                    if (it == clist.begin()) {\n                        first = true;\n                    } else {\n                        temp--;\n                    }\n                    expand_at(it); // iterator moves to last expanded node.\n                    if (first) // so need to reset iterator to first expanded node\n                        it = clist.begin();\n                    else\n                        it = temp;    \n                } else { // grey non-expandable nodes are removed\n                    temp = it;\n                    if ( it != clist.begin() ) \n                        it--; // jump out of the way from erase()\n                    else\n                        it++;\n                    clist.erase(temp);\n                }  \n            }\n        }\n    }\n    std::cout << \" LinOCT::build() \" << calc_calls << \" calcScore() calls \\n\";\n    // std::cout << size() << \" nodes after build()\\n\";  \n}\n\n// NOTE: condense() seems to run very slowly \n// >60s run time on length=138000 list.\nvoid LinOCT::condense() {\n    // NOTE: list needs to be sorted before we come here.  \n    // NOTE: consider using std::list<> unique() to remove duplicates\n    int n=0;\n    int n_duplicates=0;\n    int n_contained=0;\n    int n_collapse=0;\n    std::list<Ocode>::iterator itr;\n    std::list<Ocode>::iterator next;\n    itr = clist.begin();\n    \n    while ( n < (size()-1) ) {\n        next=itr;\n        next++;\n        if ( (*itr) == (*next) ) { //( clist[n] == clist[n+1] ) { // remove duplicates\n        \n            // FIXME delete_at(n); \n            n_duplicates++;\n            \n            // deleting a duplicate creates an opportunity to collapse\n            // so need to jump back by 7 steps to check for collapse\n            int jump=7;\n            if (n<8)\n                jump=n;\n            n-=jump; \n        }\n        else if ( itr->containedIn( *next ) ) {\n            // remove nodes contained in the following node\n            // FIXME delete_at(n);\n            if (n>0)\n                n--; // jump back to check for more contained nodes \n            n_contained++;\n        }\n        // condense nodes if all eight sub-quadrants are present\n        else if ( can_collapse_at(n) ) { // can collapse the octet\n            //std::cout << \"collapsing at \" << n << \"\\n\";\n            int deg = itr->degree();\n            \n\n            // construct parent node of sub-octants\n            Ocode o; // parent node, all digits default to \"8\"\n            for (int m=0;m<(deg-1); m++) {\n                o.code[m] =  itr->code[m]; // match code up to deg-1\n            }\n            \n            //std::cout << \"before collapse at \" << n <<\" code:\" << clist[n] << \"\\n\";            \n            // add parent \n            \n            // FIXME append_at(o, n); \n            \n            //std::cout << \"parent insert at \" << n <<\" code:\" << clist[n] << \"\\n\"; \n            n++; // jump forward and delete the redundant sub-octants\n            \n            for (int m=0;m<8;m++) {\n                //std::cout << \" deleting at \" << n<< \" : \" << clist[n] << \"\\n\";\n                // FIXME delete_at(n); \n            }\n                \n            n--; // jump back to the new parent            \n            int jump=7;\n            if (n<8)\n                jump=n;\n            n-=jump; \n                    // jump backward and see if the collapse has created \n                     // an opportunity for more collapsing\n                     // collapsable nodes can be as far back as 7 steps\n            n_collapse++;\n        }        \n        else {\n            n++; // move forward in list\n            itr++;\n        }\n    }\n    if ( (n_duplicates>0) || (n_contained>0) || (n_collapse>0)) {\n        std::cout << \"n_duplicates=\"<<n_duplicates<<\"\\n\";\n        std::cout << \"n_contained=\"<<n_contained<<\"\\n\";\n        std::cout << \"n_collapse=\"<<n_collapse<<\"\\n\";\n    } else {\n        std::cout << \"condense(): nothing to do!\\n\";\n    }\n    return;\n}\n\n/// return true if eight consequtive \n/// nodes beginning at idx can be collapsed\nbool LinOCT::can_collapse_at(int idx) {\n    std::list<Ocode>::iterator it;  \n    it=clist.begin();\n    for (int n=0;n<idx;n++)\n        it++;\n    \n    if ( (size()-idx) < 8 ) // at least 8 nodes must remain\n        return false;\n        \n    int deg = it->degree();\n    // check for consequtive numbers 0-7 at position deg\n    Ocode o;\n    //std::cout << \" checking \"<< idx << \" to \" << idx+7 << \" deg=\" << deg << \"\\n\"; \n    for (int n=0; n < 8 ; n++) {\n        o = *it; // clist[idx+n];\n        //std::cout << \"n=\" << n << \" Ocode= \"<< o <<\" code=\" << (int)o.code[deg-1] << \"\\n\";\n        \n        if ( (o.code[deg-1] != n) || (o.degree() != deg) ) {// code must match 0-7\n            //std::cout << \" no match\\n\";\n            return false;\n        }\n        it++;\n    }\n    return true;\n}\n\n/// remove o from this\nvoid LinOCT::diff( LinOCT& o ) \n{\n    std::list<Ocode>::iterator itr1;  \n    std::list<Ocode>::iterator temp;  \n    std::list<Ocode>::iterator itr2; \n    std::vector<Ocode> Q12;\n    \n    itr1=clist.begin();\n    itr2=o.clist.begin(); \n    Ocode Hold12;\n    Hold12.null();\n    \n    while ( (itr1 != clist.end() ) && ( itr2 != o.clist.end() )   ) {\n        if  ( *itr1 == *itr2 ) {\n            // remove from 1\n            temp = itr1;\n            itr1++;\n            clist.erase(temp);\n            itr2++;\n        }\n        else if ( itr1->containedIn( *itr2 ) ) {\n            temp = itr1;\n            itr1++;\n            clist.erase(temp);\n        }\n        else if ( itr2->containedIn( *itr1 ) ) { // case 2\n            expand_at(itr1);\n            // need to jump back 7 steps\n            for (int m=0;m<7;m++)\n                itr1--;\n        }\n        else if ( *itr1 < *itr2 ) {  // case 3\n            itr1++;\n        }\n        else { // case 4:  o2 < o1\n            itr2++;\n        }\n    } // end while-loop\n    \n    return;\n}\n\n\n/// compute difference, i.e.\n/// remove nodes in other from this\nLinOCT LinOCT::operation(int type, LinOCT& o)\n{\n    // traverse through both lists\n    int idx1 = 0;\n    int idx2 = 0;\n    std::list<Ocode>::iterator itr1;  \n    std::list<Ocode>::iterator itr2; \n    itr1=clist.begin();\n    itr2=o.clist.begin();\n    \n    \n    std::vector<Ocode> intersection;\n    std::vector<Ocode> sum; // a.k.a. union\n    std::vector<Ocode> diff12;\n    std::vector<Ocode> diff21;\n    std::list<Ocode> Q21;\n    std::list<Ocode> Q12;\n    Ocode Hold21;\n    Ocode Hold12;\n    Hold21.null();\n    Hold12.null();\n    \n    while ( (idx1<size()) && (idx2<o.size())   ) {  \n        \n        // case 0\n        if  ( *itr1 == *itr2 ) { //(clist[idx1] == o.clist[idx2]) { // identical nodes\n            intersection.push_back( *itr1 ); //clist[idx1] );\n            sum.push_back( *itr1 ); //clist[idx1] );\n            idx1++;\n            idx2++;  \n            itr1++;\n            itr2++;\n        }\n        \n        else if ( itr1->containedIn( *itr2 ) ) { //clist[idx1].containedIn( o.clist[idx2]  )  ) {  // case 1\n            intersection.push_back( *itr1 ); //clist[idx1] ); // idx1 contained is in both o1 and o2\n            if ( Hold21.isNull() )\n                Hold21 = *itr2; // o.clist[idx2];   // remember this node for later processing\n            Q21.push_back( *itr1 ); //clist[idx1] ); // these need to be removed from Hold21 later\n            idx1++; \n            itr1++;\n        }\n        \n        else if ( itr2->containedIn( *itr1 ) ) { //o.clist[idx2].containedIn( clist[idx1] ) ) { // case 2\n            intersection.push_back( *itr2 ); //o.clist[idx2] ); // o2[idx2] is in both o1 and o2\n            if ( Hold12.isNull() )\n                Hold12 = *itr1; //clist[idx1];        // store for later processing\n            Q12.push_back( *itr2 ); //o.clist[idx2] );  // remove these later from Hold12\n            idx2++;\n            itr2++;\n        }\n        \n        \n        else if ( *itr1 < *itr2 ) { // clist[idx1] < o.clist[idx2] ) { // case 3\n            // add o1 element to union\n            sum.push_back( *itr1 ); //clist[idx1] );\n            \n            // process the difference queues, if any\n            if ( Hold12 == *itr1 ) { //clist[idx1] )  { //compute difference o1-o2  Hold12 == clist[idx1]\n                do_diff( Hold12, Q12, diff12 ); // function for calculating difference\n                Hold12.null();\n            }\n            else\n                diff12.push_back( *itr1 ); //clist[idx1] );  // no matching node in o2, so o1 belongs to diff\n            idx1++;\n            itr1++;\n        }\n        else { // case 4:  o2 < o1\n            if ( !( *itr2 < *itr1 ) ) { //o.clist[idx2] < clist[idx1]) ) {\n                std::cout << \" case 4 o2 < o1 not true!\\n\";\n                // std::cout << \"o2=\" << *itr2 << \"number=\" << itr2->number() <<  \"\\n\";\n                // std::cout << \"o1=\" << *itr1 << \"number=\" << itr1->number() << \"\\n\";\n                assert(0);\n            }\n                \n            // add o2 element to union\n            sum.push_back( *itr2 ); //o.clist[idx2] );\n            \n            if ( Hold21 == *itr2 ) { //o.clist[idx2] ) { // Hold21 == o.clist[idx2]\n                do_diff( Hold21, Q21, diff21);\n                Hold21.null();\n            }\n            else\n                diff21.push_back( *itr2 ); //o.clist[idx2] ); // o2 belongs to diff21\n            idx2++;\n            itr2++;\n        }\n        \n    } // end of while-loop through elements\n    \n    // now process remaining elements, i.e. case where o1 is longer than o2 or vice versa\n    if (idx1 < size()) {// process rest of o1\n        int idx3 = idx1;\n        std::list<Ocode>::iterator itr3;\n        itr3 = itr1;\n        if ( Hold12 == *itr1 ) { //clist[idx1] ) {\n            do_diff( Hold12, Q12, diff12);\n            Hold12.null();\n            idx3++;\n            itr3++;\n        }\n        //for (int i=idx3; i<size(); i++)\n        for ( ; itr3 != clist.end() ; itr3++ )\n            diff12.push_back( *itr3 );\n            //diff12.push_back( clist[i] ); // o1 elements not in o2 are in diff12\n            \n        //union calc here\n        //for (int i=idx1; i<size();i++)\n        for ( ; itr1 != clist.end(); itr1++)\n            sum.push_back( *itr1 );\n            \n    }\n    else { // process rest of o2\n        int idx3=idx2;\n        std::list<Ocode>::iterator itr3;\n        itr3 = itr2;\n        \n        if (Hold21 == *itr2 ) {\n            do_diff(Hold21, Q21, diff21);\n            Hold21.null();\n            idx3++;\n            itr3++;\n        }\n        for (; itr3 != o.clist.end() ; itr3++) {\n            diff21.push_back( *itr3 ); // o2 elements to diff21\n        }\n        \n        // union calc here\n        for (; itr2 != o.clist.end(); itr2++)\n            sum.push_back( *itr2 );\n        \n    }\n    \n    /*\n    std::cout << \" diff12= \" << diff12.size() << \"\\n\";\n    std::cout << \" diff21= \" << diff21.size() << \"\\n\";\n    std::cout << \" inters= \" << intersection.size() << \"\\n\";\n    */\n    \n    LinOCT result;\n    \n    if (type==1) {\n        BOOST_FOREACH( Ocode o, diff12 ) {\n            result.append(o);\n        }\n    }\n    else if (type==2) {\n        BOOST_FOREACH( Ocode o, diff21 ) {\n            result.append(o);\n        }\n    } else if (type==3) {\n        BOOST_FOREACH( Ocode o, intersection) {\n            result.append(o);\n        }\n    } else if (type==4) {\n        BOOST_FOREACH( Ocode o, sum) {\n            result.append(o);\n        }\n        result.condense();\n    }\n        \n    \n    return result;\n}\n\n\n// computes difference H - Q\n// where H is a node that is expanded\n// and Q is a queue of nodes to be subtracted from H\n// the result is appended to D\nvoid LinOCT::do_diff(Ocode& H, std::list<Ocode>& Q, std::vector<Ocode>& D) \n{\n    // H - an expandable node\n    // Q - queue of nodes contained in H\n    // D - difference queue for H-Q results\n    \n    // Q2 contains expanded node\n    std::list<Ocode> Q2;\n    \n    if ( !H.expandable()) {\n        /*\n        std::cout << \" do_diff node H not expandable...\\n\";\n        std::cout << \" H=\" << H << \"\\n\";\n        std::cout << \" Q=\\n\";\n        BOOST_FOREACH( Ocode o, Q) {\n            std::cout << o << \"\\n\";\n        }*/\n        Q2.push_back(H);\n    } else {\n        Q2 = H.expand(); \n    }\n    \n    /*\n    std::cout << \" H.expand() on H=\" << H <<\" :\\n\";\n    BOOST_FOREACH( Ocode o, Q2) {\n        std::cout << o << \"\\n\";\n    }*/\n    \n    while ( !Q2.empty() ) { // go through the expanded nodes\n    \n        if ( !Q.empty() ) {\n            Ocode n = Q.back();\n            Ocode n2 = Q2.back();\n            if ( n == n2 ) {// matching elements\n                Q2.pop_back(); //erase(Q2.begin());  // nothing to put into diff\n                Q.pop_back(); // erase(Q.begin());\n            } else if ( n.containedIn( n2 ) ) {// need to expand further\n                // expand n2 and add to front of Q2\n                std::list<Ocode> subocts = n2.expand();\n                Q2.pop_back(); // delete parent\n                BOOST_FOREACH( Ocode o, subocts) {\n                    Q2.push_back(o); // insert new children\n                }\n            } else {\n                // no match in Q, so push node to diff\n                D.push_back( n2 );\n                Q2.pop_back();\n            }\n        }\n        else { // Q is empty\n            D.push_back( Q2.back() ); // no match in Q, so push node to diff\n            Q2.pop_back();\n        }\n        \n    }// end while\n    //Q.clear();\n    \n    //std::cout << \" after do_diff Q.size() = \" << Q.size() << \"\\n\";\n    return;\n}\n\n/// add nodes of two trees together into one\nvoid LinOCT::sum(LinOCT& other) {\n    // join the two lists, sort, and condense\n    BOOST_FOREACH( Ocode o, other.clist ) {\n        append( o );\n    }\n    sort();\n    condense();\n    return;\n}\n\n/// sort list of ocodes\nvoid LinOCT::sort() {\n    clist.sort();\n}\n\n/// return list of triangles to python\n/// the triangles correspond to every node/cube of the octree\nboost::python::list LinOCT::get_triangles()\n{    \n    boost::python::list tlist;\n    BOOST_FOREACH( Ocode o, clist) {\n        std::vector<Point> p(8);\n        for (int m=0;m<8;++m)\n            p[m]=o.corner(m);\n        // these 12 triangles cover the 6 sides of the cube\n        tlist.append(Triangle(p[0],p[1],p[2])); \n        tlist.append(Triangle(p[1],p[2],p[6])); \n        tlist.append(Triangle(p[3],p[4],p[5])); \n        tlist.append(Triangle(p[4],p[5],p[7])); \n        tlist.append(Triangle(p[0],p[2],p[3])); \n        tlist.append(Triangle(p[3],p[4],p[2]));\n        tlist.append(Triangle(p[1],p[5],p[6])); \n        tlist.append(Triangle(p[6],p[7],p[5]));\n        tlist.append(Triangle(p[2],p[4],p[6])); \n        tlist.append(Triangle(p[6],p[7],p[4]));\n        tlist.append(Triangle(p[0],p[1],p[3])); \n        tlist.append(Triangle(p[3],p[5],p[1]));\n    }\n    return tlist;\n}\n\n\nboost::python::list LinOCT::get_nodes() {    \n    boost::python::list nodelist;\n    BOOST_FOREACH( Ocode o, clist) {\n            nodelist.append(o);\n    }\n    return nodelist;\n}\n\n\n/// string repr\nstd::ostream& operator<<(std::ostream &stream, const LinOCT &l) {\n    stream << \"LinOCT: N=\"<< l.size() ;     \n    return stream;\n}\n\n/// print the whole list\nvoid LinOCT::printList() {\n    BOOST_FOREACH( Ocode o, clist ) {\n        std::cout << \" \" << o << \"\\n\";\n    }\n}\n\n/// string repr\nstd::string LinOCT::str() const {\n    std::ostringstream o;\n    o << *this;\n    return o.str();\n}\n\n} // end namespace\n// end of file octree.cpp\n", "meta": {"hexsha": "16be29c7c62f8d79bc07f44dddd0c75638db953b", "size": 20359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/attic/octree.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/octree.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/octree.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": 31.5154798762, "max_line_length": 109, "alphanum_fraction": 0.4785107324, "num_tokens": 5467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.03358950734309017, "lm_q1q2_score": 0.013178400360547097}}
{"text": "// Copyright (c) 2014, NICTA.\n// This file is licensed under the General Public License version 3 or later.\n//!\n//! Contains the implementation for the thermal forward model.\n//!\n//! \\file fwdmodel/thermal.cpp\n//! \\author Lachlan McCalman\n//! \\date 2014\n//! \\license Affero General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#include <glog/logging.h>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n#include \"thermal.hpp\"\n#pragma GCC diagnostic pop\n\n#include \"boost/multi_array.hpp\"\n#include \"world/voxelise.hpp\"\n#include <iostream>\n#include <algorithm>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseCholesky>\n#include <Eigen/IterativeLinearSolvers>\n\n#include <chrono>\ntypedef std::chrono::high_resolution_clock hrc;\n\nnamespace obsidian\n{\n  namespace fwd\n  {\n    boost::multi_array<double, 3> fillAndPad(const Eigen::VectorXd& values, const ThermalSpec& spec)\n    {\n      // The true grid size\n      uint nx = spec.voxelisation.xResolution;\n      uint ny = spec.voxelisation.yResolution;\n      uint nz = spec.voxelisation.zResolution;\n      // Make sure we have the right amount of data\n      CHECK_EQ(nx * ny * nz, values.size());\n\n      uint bigx = nx + 2 + 2; // top and bottom padding\n      uint bigy = ny + 2 + 2; // top and bottom padding\n      uint bigz = nz + 1 + 2; // top and bottom padding\n      // The multiarrays we'll use\n      boost::multi_array<double, 3> volume(boost::extents[bigx][bigy][bigz]);\n      // fill in the values to the multiarray\n      for (uint i = 0; i < bigx; i++)\n      {\n        for (uint j = 0; j < bigy; j++)\n        {\n          for (uint k = 0; k < bigz; k++)\n          {\n            // first we contrain these to only index the internal region\n            // ie no padding. Then we remove the padding offsets so we're\n            // actually indexing into the original values matrix\n            uint smalli = std::min(std::max(i, (uint) 2), (bigx - 1) - 2) - 2;\n            uint smallj = std::min(std::max(j, (uint) 2), (bigy - 1) - 2) - 2;\n            uint smallk = std::min(std::max(k, (uint) 1), (bigz - 1) - 2) - 1;\n            // Compute the 1D offset into our values matrix\n            uint c = smalli * ny * nz + smallj * nz + smallk;\n            volume[i][j][k] = values(c);\n          }\n        }\n      }\n      return volume;\n    }\n\n    boost::multi_array<double, 3> eastWest(const boost::multi_array<double, 3>& pad)\n    {\n      // The padded grid size\n      uint padx = pad.shape()[0];\n      uint pady = pad.shape()[1];\n      uint padz = pad.shape()[2];\n      // new size -- one off all dims and 1 further off the summing dimension\n      uint nx = (padx - 1) - 1;\n      uint ny = (pady - 1);\n      uint nz = (padz - 1);\n      boost::multi_array<double, 3> ew(boost::extents[nx][ny][nz]);\n      for (uint i = 0; i < nx; i++)\n      {\n        for (uint j = 0; j < ny; j++)\n        {\n          for (uint k = 0; k < nz; k++)\n          {\n            double t1 = pad[i + 1][j][k];\n            double t2 = pad[i + 1][j + 1][k];\n            double t3 = pad[i + 1][j][k + 1];\n            double t4 = pad[i + 1][j + 1][k + 1];\n            ew[i][j][k] = (t1 + t2 + t3 + t4) / 4.0;\n          }\n        }\n      }\n      return ew;\n    }\n\n    boost::multi_array<double, 3> cells(const boost::multi_array<double, 3>& pad, uint axis)\n    {\n      // The padded grid size\n      uint padx = pad.shape()[0];\n      uint pady = pad.shape()[1];\n      uint padz = pad.shape()[2];\n      // bools to switch which axis we're dealing with\n      CHECK(axis < 3);\n      uint isx = axis == 0;\n      uint isy = axis == 1;\n      uint isz = axis == 2;\n      // new size -- one off all dims and 1 further off the summing dimension\n      uint nx = (padx - 1) - isx;\n      uint ny = (pady - 1) - isy;\n      uint nz = (padz - 1) - isz;\n      boost::multi_array<double, 3> ew(boost::extents[nx][ny][nz]);\n\n      // Compute our indexing offsets\n      Eigen::MatrixXi indices(4, 3);\n      indices << 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1;\n      uint xcol = isx * 0 + isy * 1 + isz * 2;\n      uint ycol = isx * 2 + isy * 0 + isz * 1;\n      uint zcol = isx * 1 + isy * 2 + isz * 0;\n\n      for (uint i = 0; i < nx; i++)\n      {\n        for (uint j = 0; j < ny; j++)\n        {\n          for (uint k = 0; k < nz; k++)\n          {\n            double t1 = pad[i + indices(0, xcol)][j + indices(0, ycol)][k + indices(0, zcol)];\n            double t2 = pad[i + indices(1, xcol)][j + indices(1, ycol)][k + indices(1, zcol)];\n            double t3 = pad[i + indices(2, xcol)][j + indices(2, ycol)][k + indices(2, zcol)];\n            double t4 = pad[i + indices(3, xcol)][j + indices(3, ycol)][k + indices(3, zcol)];\n            ew[i][j][k] = (t1 + t2 + t3 + t4) / 4.0;\n          }\n        }\n      }\n      return ew;\n    }\n\n    boost::multi_array<double, 3> isocells(const boost::multi_array<double, 3>& pad)\n    {\n      // The padded grid size\n      uint padx = pad.shape()[0];\n      uint pady = pad.shape()[1];\n      uint padz = pad.shape()[2];\n      uint nx = padx - 1;\n      uint ny = pady - 1;\n      uint nz = padz - 1;\n      boost::multi_array<double, 3> a(boost::extents[nx][ny][nz]);\n\n      for (uint i = 0; i < nx; i++)\n      {\n        for (uint j = 0; j < ny; j++)\n        {\n          for (uint k = 0; k < nz; k++)\n          {\n            bool px0 = i > 0;\n            bool px1 = i < nx - 1;\n            bool py0 = j > 0;\n            bool py1 = j < ny - 1;\n            bool pz0 = k > 0;\n            bool pz1 = k < nz - 1;\n            bool t1On = (px0 && py0 && pz0);\n            bool t2On = (px0 && py0 && pz1);\n            bool t3On = (px0 && py1 && pz0);\n            bool t4On = (px0 && py1 && pz1);\n            bool t5On = (px1 && py0 && pz0);\n            bool t6On = (px1 && py0 && pz1);\n            bool t7On = (px1 && py1 && pz0);\n            bool t8On = (px1 && py1 && pz1);\n            double t1 = t1On * pad[i][j][k];\n            double t2 = t2On * pad[i][j][k + 1];\n            double t3 = t3On * pad[i][j + 1][k];\n            double t4 = t4On * pad[i][j + 1][k + 1];\n            double t5 = t5On * pad[i + 1][j][k];\n            double t6 = t6On * pad[i + 1][j][k + 1];\n            double t7 = t7On * pad[i + 1][j + 1][k];\n            double t8 = t8On * pad[i + 1][j + 1][k + 1];\n            double norm = (t1On + t2On + t3On + t4On + t5On + t6On + t7On + t8On);\n            a[i][j][k] = (t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8) / (8.0 * norm);\n          }\n        }\n      }\n      return a;\n    }\n\n    boost::multi_array<double, 3> temp(const boost::multi_array<double, 3>& eastwest, const boost::multi_array<double, 3>& northsouth,\n                                       const boost::multi_array<double, 3>& updown, const boost::multi_array<double, 3>& sCells,\n                                       const Eigen::MatrixXd& tempZ0, const Eigen::MatrixXd& zLowBound, bool zLowBoundIsHeatFlow,\n                                       double xSize, double ySize, double zSize)\n    {\n      //remove the padding from sCells\n      uint nx = sCells.shape()[0] - 2;\n      uint ny = sCells.shape()[1] - 2;\n      uint nz = sCells.shape()[2] - 2;\n      uint n = nx * ny * nz; // total n\n\n      double dx = xSize / double(nx - 1); // original number of cells\n      double dy = ySize / double(ny - 1); // original number of cells\n      double dz = zSize / double(nz);\n\n      Eigen::SparseMatrix<double> A(n, n);  // big sparse matrix\n      std::vector<Eigen::Triplet<double>> coeffs;\n      Eigen::VectorXd b = Eigen::VectorXd::Zero(n); // constant term\n\n      for (uint i = 0; i < nx; i++)\n      {\n        for (uint j = 0; j < ny; j++)\n        {\n          for (uint k = 0; k < nz; k++)\n          {\n            uint row = i * ny * nz + j * nz + k;\n            uint col = row;\n            b(row) = -1 * sCells[i + 1][j + 1][k + 1]; //ignores the outer layer of sCells\n\n            double val_west = eastwest[i][j + 1][k + 1];\n            double val_east = eastwest[i + 1][j + 1][k + 1];\n            double val_north = northsouth[i + 1][j][k + 1];\n            double val_south = northsouth[i + 1][j + 1][k + 1];\n            double val_up = updown[i + 1][j + 1][k];\n            double val_down = updown[i + 1][j + 1][k + 1];\n\n            double z_up_contrib = val_up / (dz * dz);\n            double z_down_contrib = val_down / (dz * dz);\n            double y_north_contrib = val_north / (dy * dy);\n            double y_south_contrib = val_south / (dy * dy);\n            double x_west_contrib = val_west / (dx * dx);\n            double x_east_contrib = val_east / (dx * dx);\n\n            double sum = -1 * (z_up_contrib + z_down_contrib + y_north_contrib + y_south_contrib + x_west_contrib + x_east_contrib);\n            // Assign to a\n            coeffs.push_back( { row, col, sum });\n            // Z-axis contribution\n            // Top\n            if (k == 0)\n            {\n              b(row) = b(row) - z_up_contrib * tempZ0(i, j);\n            } else\n            {\n              col = i * ny * nz + j * nz + k - 1;\n              coeffs.push_back( { row, col, z_up_contrib });\n            }\n\n            // Bottom\n            if (k == nz - 1)\n            {\n              if (zLowBoundIsHeatFlow)\n              {\n                col = row;\n                coeffs.push_back( { row, col, z_down_contrib });\n                b(row) = b(row) - zLowBound(i, j) / dz;\n              } else\n              {\n                b(row) = b(row) - z_down_contrib * zLowBound(i, j);\n              }\n            } else\n            {\n              col = i * ny * nz + j * nz + k + 1;\n              coeffs.push_back( { row, col, z_down_contrib });\n            }\n\n            // Y-axis contribution\n            if (j == 0)\n            {\n              col = i * ny * nz + j * nz + k;\n              coeffs.push_back( { row, col, y_north_contrib });\n            } else\n            {\n              col = i * ny * nz + (j - 1) * nz + k;\n              coeffs.push_back( { row, col, y_north_contrib });\n            }\n            if (j == ny - 1)\n            {\n              col = i * ny * nz + j * nz + k;\n              coeffs.push_back( { row, col, y_south_contrib });\n            } else\n            {\n              col = i * ny * nz + (j + 1) * nz + k;\n              coeffs.push_back( { row, col, y_south_contrib });\n            }\n            // X-axis contribution\n            if (i == 0)\n            {\n              col = i * ny * nz + j * nz + k;\n              coeffs.push_back( { row, col, x_west_contrib });\n            } else\n            {\n              col = (i - 1) * ny * nz + j * nz + k;\n              coeffs.push_back( { row, col, x_west_contrib });\n            }\n            if (i == nx - 1)\n            {\n              col = i * ny * nz + j * nz + k;\n              coeffs.push_back( { row, col, x_east_contrib });\n            } else\n            {\n              col = (i + 1) * ny * nz + j * nz + k;\n              coeffs.push_back( { row, col, x_east_contrib });\n            }\n\n          }\n        }\n      }\n\n      A.setFromTriplets(coeffs.begin(), coeffs.end());\n\n      // solve for -A\n      A = -1 * A;\n      b = -1 * b;\n\n      Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> solver;\n      solver.setTolerance(1.0e-4); // tested using demo3dworld - should be +- 0.5 degrees under typical use @ 40*24*32\n      solver.compute(A);\n\n      if (solver.info() != Eigen::Success)\n      {\n        LOG(ERROR)<< \"Matrix decomposition failed\";\n      }\n      Eigen::VectorXd tvec(n);\n      tvec = solver.solve(b);\n      if (solver.info() != Eigen::Success)\n      {\n        LOG(ERROR)<< \"Linear system could not be solved\";\n      }\n      boost::multi_array<double, 3> t(boost::extents[nx][ny][nz + 1]);\n      // add the surface temperature\n\n      for (uint i = 0; i < nx; i++)\n      {\n        for (uint j = 0; j < ny; j++)\n        {\n          t[i][j][0] = tempZ0(i, j);\n        }\n      }\n      // count from z=1\n      uint c = 0;\n      for (uint i = 0; i < nx; i++)\n      {\n        for (uint j = 0; j < ny; j++)\n        {\n          for (uint k = 1; k < nz + 1; k++)\n          {\n            t[i][j][k] = tvec(c);\n            c++;\n          }\n        }\n      }\n      return t;\n    }\n\n    uint clip(int in, uint maxX)\n    {\n      uint x = (in > 0) * in;\n      x = maxX - (x < maxX) * (maxX - x);\n      return (uint) x;\n    }\n\n    Eigen::VectorXd evalAtLocations(const boost::multi_array<double, 3>& tempVox, const Eigen::MatrixXd& locations,\n                                    const std::pair<double, double>& xSize, const std::pair<double, double>& ySize,\n                                    const std::pair<double, double>& zSize)\n    {\n      uint nx = tempVox.shape()[0];\n      uint ny = tempVox.shape()[1];\n      uint nz = tempVox.shape()[2];\n      double x0 = xSize.first;\n      double y0 = ySize.first;\n      double z0 = zSize.first;\n      double deltaX = xSize.second - x0;\n      double deltaY = ySize.second - y0;\n      double deltaZ = zSize.second - z0;\n      Eigen::VectorXd temps(locations.rows());\n      for (uint i = 0; i < locations.rows(); i++) //AAA\n      {\n        // Clip rather than check\n        double xx = (double) (nx - 1) * (locations(i, 0) - x0) / deltaX;\n        double yy = (double) (ny - 1) * (locations(i, 1) - y0) / deltaY;\n        double zz = (double) (nz - 1) * (locations(i, 2) - z0) / deltaZ;\n\n        // Clip so we get continuous edge conditions after the image\n        uint x1 = clip(xx, nx - 1);\n        uint x2 = clip(xx + 1, nx - 1);\n        uint y1 = clip(yy, ny - 1);\n        uint y2 = clip(yy + 1, ny - 1);\n        uint z1 = clip(zz, nz - 1);\n        uint z2 = clip(zz + 1, nz - 1);\n\n        double alpha2 = xx - (double) x1;\n        double beta2 = yy - (double) y1;\n        double gamma2 = zz - (double) z1;\n        double alpha1 = 1.0 - alpha2;\n        double beta1 = 1.0 - beta2;\n        double gamma1 = 1.0 - gamma2;\n\n        /*Eigen::VectorXi pos(6);\n         pos << xx,yy,zz, (alpha1*(double)x1 + alpha2*(double)x2),(beta1*(double)y1 + beta2*(double)y2),(gamma1*(double)z1 + gamma2*(double)z2);\n         std::cout << pos.transpose() <<\"\\n\";\n         */\n\n        // who needs loops?\n        temps(i) = alpha1 * beta1 * gamma1 * tempVox[x1][y1][z1] + alpha1 * beta1 * gamma2 * tempVox[x1][y1][z2]\n            + alpha1 * beta2 * gamma1 * tempVox[x1][y2][z1] + alpha1 * beta2 * gamma2 * tempVox[x1][y2][z2]\n            + alpha2 * beta1 * gamma1 * tempVox[x2][y1][z1] + alpha2 * beta1 * gamma2 * tempVox[x2][y1][z2]\n            + alpha2 * beta2 * gamma1 * tempVox[x2][y2][z1] + alpha2 * beta2 * gamma2 * tempVox[x2][y2][z2]; //ouch\n      }\n      return temps;\n    }\n\n    template<>\n    ThermalCache generateCache<ForwardModel::THERMAL>(const std::vector<world::InterpolatorSpec>& boundaryInterpolation,\n                                                      const WorldSpec& worldSpec, const ThermalSpec& thermSpec)\n    {\n      const VoxelSpec& thermVox = thermSpec.voxelisation;\n      world::Query thermQuery(boundaryInterpolation, worldSpec, thermVox.xResolution, thermVox.yResolution, thermVox.zResolution,\n                              world::SamplingStrategy::noAA);\n      return\n      { boundaryInterpolation, thermQuery, worldSpec.xBounds, worldSpec.yBounds, worldSpec.zBounds};\n    }\n\n    template<>\n    ThermalResults forwardModel<ForwardModel::THERMAL>(const ThermalSpec& spec, const ThermalCache& cache, const WorldParams& world)\n    {\n      Eigen::MatrixXd cond = world::getVoxels(cache.boundaryInterpolation, world, cache.query, RockProperty::ThermalConductivity); // conductivity shouldnt go to zero...\n      Eigen::MatrixXd prod = world::getVoxels(cache.boundaryInterpolation, world, cache.query, RockProperty::ThermalProductivity);\n\n      auto volume = fillAndPad(world::flatten(cond), spec);\n      auto eastwest = cells(volume, 0);\n      auto northsouth = cells(volume, 1);\n      auto updown = cells(volume, 2);\n      auto sVolume = fillAndPad(world::flatten(prod), spec);\n      auto sCells = isocells(sVolume);\n\n      uint nx = spec.voxelisation.xResolution;\n      uint ny = spec.voxelisation.yResolution;\n      Eigen::MatrixXd tempZ0 = Eigen::MatrixXd::Ones(nx + 1, ny + 1) * spec.surfaceTemperature;\n      Eigen::MatrixXd zLowBound = Eigen::MatrixXd::Ones(nx + 1, ny + 1) * spec.lowerBoundary;\n      bool isHeatFlow = spec.lowerBoundaryIsHeatFlow;\n      double xSize = cache.xBounds.second - cache.xBounds.first;\n      double ySize = cache.yBounds.second - cache.yBounds.first;\n      double zSize = cache.zBounds.second - cache.zBounds.first;\n      boost::multi_array<double, 3> tempVox = temp(eastwest, northsouth, updown, sCells, tempZ0, zLowBound, isHeatFlow, xSize, ySize,\n                                                   zSize);\n\n      ThermalResults results;\n      results.readings = evalAtLocations(tempVox, spec.locations, cache.xBounds, cache.yBounds, cache.zBounds);\n      return results;\n    }\n\n  }\n}\n", "meta": {"hexsha": "979617b785ce8e4ba3b3bb5a5e689cf43035456a", "size": 16810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fwdmodel/thermal.cpp", "max_stars_repo_name": "divad-nhok/obsidian_fork", "max_stars_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T01:03:57.000Z", "max_issues_repo_path": "src/fwdmodel/thermal.cpp", "max_issues_repo_name": "divad-nhok/obsidian_fork", "max_issues_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T00:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-16T00:46:58.000Z", "max_forks_repo_path": "src/fwdmodel/thermal.cpp", "max_forks_repo_name": "divad-nhok/obsidian_fork", "max_forks_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T05:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T21:37:47.000Z", "avg_line_length": 37.3555555556, "max_line_length": 169, "alphanum_fraction": 0.5063652588, "num_tokens": 5008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326716, "lm_q2_score": 0.029312229055423987, "lm_q1q2_score": 0.01317270026956309}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n//\n// Comparison operators for cpp_int_backend:\n//\n#ifndef BOOST_MP_CPP_INT_MISC_HPP\n#define BOOST_MP_CPP_INT_MISC_HPP\n\n#include <boost/multiprecision/detail/bitscan.hpp> // lsb etc\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4702)\n#endif\n\nnamespace boost{ namespace multiprecision{ namespace backends{\n\ntemplate <class R, class CppInt>\nvoid check_in_range(const CppInt& val, const mpl::int_<checked>&)\n{\n   typedef typename boost::multiprecision::detail::canonical<R, CppInt>::type cast_type;\n   if(val.sign())\n   {\n      if(val.compare(static_cast<cast_type>((std::numeric_limits<R>::min)())) < 0)\n         BOOST_THROW_EXCEPTION(std::overflow_error(\"Could not convert to the target type - -value is out of range.\"));\n   }\n   else\n   {\n      if(val.compare(static_cast<cast_type>((std::numeric_limits<R>::max)())) > 0)\n         BOOST_THROW_EXCEPTION(std::overflow_error(\"Could not convert to the target type - -value is out of range.\"));\n   }\n}\ntemplate <class R, class CppInt>\ninline void check_in_range(const CppInt& /*val*/, const mpl::int_<unchecked>&) BOOST_NOEXCEPT {}\n\ninline void check_is_negative(const mpl::true_&) BOOST_NOEXCEPT {}\ninline void check_is_negative(const mpl::false_&)\n{\n   BOOST_THROW_EXCEPTION(std::range_error(\"Attempt to assign a negative value to an unsigned type.\"));\n}\n\ntemplate <class Integer>\ninline Integer negate_integer(Integer i, const mpl::true_&) BOOST_NOEXCEPT\n{\n   return -i;\n}\ntemplate <class Integer>\ninline Integer negate_integer(Integer i, const mpl::false_&) BOOST_NOEXCEPT\n{\n   return ~(i-1);\n}\n\ntemplate <class R, unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<is_integral<R>::value && !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, void>::type\n   eval_convert_to(R* result, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& backend) BOOST_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   typedef mpl::int_<Checked1> checked_type;\n   check_in_range<R>(backend, checked_type());\n\n   *result = static_cast<R>(backend.limbs()[0]);\n   unsigned shift = cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   for(unsigned i = 1; (i < backend.size()) && (shift < static_cast<unsigned>(std::numeric_limits<R>::digits)); ++i)\n   {\n      *result += static_cast<R>(backend.limbs()[i]) << shift;\n      shift += cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   }\n   if(backend.sign())\n   {\n      check_is_negative(boost::is_signed<R>());\n      *result = negate_integer(*result, boost::is_signed<R>());\n   }\n}\n\ntemplate <class R, unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<is_floating_point<R>::value && !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, void>::type\n   eval_convert_to(R* result, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& backend) BOOST_NOEXCEPT_IF(is_arithmetic<R>::value)\n{\n   typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::const_limb_pointer p = backend.limbs();\n   unsigned shift = cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   *result = static_cast<R>(*p);\n   for(unsigned i = 1; i < backend.size(); ++i)\n   {\n      *result += static_cast<R>(std::ldexp(static_cast<long double>(p[i]), shift));\n      shift += cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   }\n   if(backend.sign())\n      *result = -*result;\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, bool>::type\n   eval_is_zero(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val) BOOST_NOEXCEPT\n{\n   return (val.size() == 1) && (val.limbs()[0] == 0);\n}\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, int>::type\n   eval_get_sign(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val) BOOST_NOEXCEPT\n{\n   return eval_is_zero(val) ? 0 : val.sign() ? -1 : 1;\n}\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_abs(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val) BOOST_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   result = val;\n   result.sign(false);\n}\n\n//\n// Get the location of the least-significant-bit:\n//\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, unsigned>::type\n   eval_lsb(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a)\n{\n   using default_ops::eval_get_sign;\n   if(eval_get_sign(a) == 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n   }\n   if(a.sign())\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n   }\n\n   //\n   // Find the index of the least significant limb that is non-zero:\n   //\n   unsigned index = 0;\n   while(!a.limbs()[index] && (index < a.size()))\n      ++index;\n   //\n   // Find the index of the least significant bit within that limb:\n   //\n   unsigned result = boost::multiprecision::detail::find_lsb(a.limbs()[index]);\n\n   return result + index * cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n}\n\n//\n// Get the location of the most-significant-bit:\n//\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, unsigned>::type\n   eval_msb(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a)\n{\n   using default_ops::eval_get_sign;\n   if(eval_get_sign(a) == 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n   }\n   if(a.sign())\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n   }\n\n   //\n   // Find the index of the most significant bit that is non-zero:\n   //\n   return (a.size() - 1) * cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits + boost::multiprecision::detail::find_msb(a.limbs()[a.size() - 1]);\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, bool>::type\n   eval_bit_test(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val, unsigned index) BOOST_NOEXCEPT\n{\n   unsigned offset = index / cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   unsigned shift = index % cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   limb_type mask = shift ? limb_type(1u) << shift : limb_type(1u);\n   if(offset >= val.size())\n      return false;\n   return val.limbs()[offset] & mask ? true : false;\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_bit_set(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val, unsigned index)\n{\n   unsigned offset = index / cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   unsigned shift = index % cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   limb_type mask = shift ? limb_type(1u) << shift : limb_type(1u);\n   if(offset >= val.size())\n   {\n      unsigned os = val.size();\n      val.resize(offset + 1, offset + 1);\n      if(offset >= val.size())\n         return;  // fixed precision overflow\n      for(unsigned i = os; i <= offset; ++i)\n         val.limbs()[i] = 0;\n   }\n   val.limbs()[offset] |= mask;\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_bit_unset(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val, unsigned index) BOOST_NOEXCEPT\n{\n   unsigned offset = index / cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   unsigned shift = index % cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   limb_type mask = shift ? limb_type(1u) << shift : limb_type(1u);\n   if(offset >= val.size())\n      return;\n   val.limbs()[offset] &= ~mask;\n   val.normalize();\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_bit_flip(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val, unsigned index)\n{\n   unsigned offset = index / cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   unsigned shift = index % cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::limb_bits;\n   limb_type mask = shift ? limb_type(1u) << shift : limb_type(1u);\n   if(offset >= val.size())\n   {\n      unsigned os = val.size();\n      val.resize(offset + 1, offset + 1);\n      if(offset >= val.size())\n         return;  // fixed precision overflow\n      for(unsigned i = os; i <= offset; ++i)\n         val.limbs()[i] = 0;\n   }\n   val.limbs()[offset] ^= mask;\n   val.normalize();\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_qr(\n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& x,\n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& y,\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& q,\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& r) BOOST_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   divide_unsigned_helper(&q, x, y, r);\n   q.sign(x.sign() != y.sign());\n   r.sign(x.sign());\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_qr(\n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& x,\n      limb_type y,\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& q,\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& r) BOOST_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   divide_unsigned_helper(&q, x, y, r);\n   q.sign(x.sign());\n   r.sign(x.sign());\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class U>\ninline typename enable_if_c<is_integral<U>::value>::type eval_qr(\n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& x,\n      U y,\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& q,\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& r) BOOST_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   using default_ops::eval_qr;\n   cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> t(y);\n   eval_qr(x, t, q, r);\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class Integer>\ninline typename enable_if_c<is_unsigned<Integer>::value && !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, Integer>::type\n   eval_integer_modulus(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& x, Integer val)\n{\n   if((sizeof(Integer) <= sizeof(limb_type)) || (val <= (std::numeric_limits<limb_type>::max)()))\n   {\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> d;\n      divide_unsigned_helper(static_cast<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>*>(0), x, static_cast<limb_type>(val), d);\n      return d.limbs()[0];\n   }\n   else\n   {\n      return default_ops::eval_integer_modulus(x, val);\n   }\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class Integer>\nBOOST_MP_FORCEINLINE typename enable_if_c<is_signed<Integer>::value && !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, Integer>::type\n   eval_integer_modulus(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& x, Integer val)\n{\n   return eval_integer_modulus(x, boost::multiprecision::detail::unsigned_abs(val));\n}\n\ninline limb_type integer_gcd_reduce(limb_type u, limb_type v)\n{\n   do\n   {\n      if(u > v)\n         std::swap(u, v);\n      if(u == v)\n         break;\n      v -= u;\n      v >>= boost::multiprecision::detail::find_lsb(v);\n   } while(true);\n   return u;\n}\n\ninline double_limb_type integer_gcd_reduce(double_limb_type u, double_limb_type v)\n{\n   do\n   {\n      if(u > v)\n         std::swap(u, v);\n      if(u == v)\n         break;\n      if(v <= ~static_cast<limb_type>(0))\n      {\n         u = integer_gcd_reduce(static_cast<limb_type>(v), static_cast<limb_type>(u));\n         break;\n      }\n      v -= u;\n      while((static_cast<unsigned>(v) & 1u) == 0)\n         v >>= 1;\n   } while(true);\n   return u;\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_gcd(\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, \n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a, \n      limb_type v)\n{\n   using default_ops::eval_lsb;\n   using default_ops::eval_is_zero;\n   using default_ops::eval_get_sign;\n\n   int shift;\n\n   cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> u(a);\n\n   int s = eval_get_sign(u);\n\n   /* GCD(0,x) := x */\n   if(s < 0)\n   {\n      u.negate();\n   }\n   else if(s == 0)\n   {\n      result = v;\n      return;\n   }\n   if(v == 0)\n   {\n      result = u;\n      return;\n   }\n\n   /* Let shift := lg K, where K is the greatest power of 2\n   dividing both u and v. */\n\n   unsigned us = eval_lsb(u);\n   unsigned vs = boost::multiprecision::detail::find_lsb(v);\n   shift = (std::min)(us, vs);\n   eval_right_shift(u, us);\n   if(vs)\n      v >>= vs;\n\n   do \n   {\n      /* Now u and v are both odd, so diff(u, v) is even.\n      Let u = min(u, v), v = diff(u, v)/2. */\n      if(u.size() <= 2)\n      {\n         if(u.size() == 1)\n            v = integer_gcd_reduce(*u.limbs(), v);\n         else\n         {\n            double_limb_type i;\n            i = u.limbs()[0] | (static_cast<double_limb_type>(u.limbs()[1]) << sizeof(limb_type) * CHAR_BIT);\n            v = static_cast<limb_type>(integer_gcd_reduce(i, static_cast<double_limb_type>(v)));\n         }\n         break;\n      }\n      eval_subtract(u, v);\n      us = eval_lsb(u);\n      eval_right_shift(u, us);\n   } \n   while(true);\n\n   result = v;\n   eval_left_shift(result, shift);\n}\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class Integer>\ninline typename enable_if_c<is_unsigned<Integer>::value && (sizeof(Integer) <= sizeof(limb_type)) && !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_gcd(\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, \n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a, \n      const Integer& v)\n{\n   eval_gcd(result, a, static_cast<limb_type>(v));\n}\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1, class Integer>\ninline typename enable_if_c<is_signed<Integer>::value && (sizeof(Integer) <= sizeof(limb_type)) && !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_gcd(\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, \n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a, \n      const Integer& v)\n{\n   eval_gcd(result, a, static_cast<limb_type>(v < 0 ? -v : v));\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_gcd(\n      cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, \n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a, \n      const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b)\n{\n   using default_ops::eval_lsb;\n   using default_ops::eval_is_zero;\n   using default_ops::eval_get_sign;\n\n   if(a.size() == 1)\n   {\n      eval_gcd(result, b, *a.limbs());\n      return;\n   }\n   if(b.size() == 1)\n   {\n      eval_gcd(result, a, *b.limbs());\n      return;\n   }\n\n   int shift;\n\n   cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> u(a), v(b);\n\n   int s = eval_get_sign(u);\n\n   /* GCD(0,x) := x */\n   if(s < 0)\n   {\n      u.negate();\n   }\n   else if(s == 0)\n   {\n      result = v;\n      return;\n   }\n   s = eval_get_sign(v);\n   if(s < 0)\n   {\n      v.negate();\n   }\n   else if(s == 0)\n   {\n      result = u;\n      return;\n   }\n\n   /* Let shift := lg K, where K is the greatest power of 2\n   dividing both u and v. */\n\n   unsigned us = eval_lsb(u);\n   unsigned vs = eval_lsb(v);\n   shift = (std::min)(us, vs);\n   eval_right_shift(u, us);\n   eval_right_shift(v, vs);\n\n   do \n   {\n      /* Now u and v are both odd, so diff(u, v) is even.\n      Let u = min(u, v), v = diff(u, v)/2. */\n      s = u.compare(v);\n      if(s > 0)\n         u.swap(v);\n      if(s == 0)\n         break;\n      if(v.size() <= 2)\n      {\n         if(v.size() == 1)\n            u = integer_gcd_reduce(*v.limbs(), *u.limbs());\n         else\n         {\n            double_limb_type i, j;\n            i = v.limbs()[0] | (static_cast<double_limb_type>(v.limbs()[1]) << sizeof(limb_type) * CHAR_BIT);\n            j = (u.size() == 1) ? *u.limbs() : u.limbs()[0] | (static_cast<double_limb_type>(u.limbs()[1]) << sizeof(limb_type) * CHAR_BIT);\n            u = integer_gcd_reduce(i, j);\n         }\n         break;\n      }\n      eval_subtract(v, u);\n      vs = eval_lsb(v);\n      eval_right_shift(v, vs);\n   } \n   while(true);\n\n   result = u;\n   eval_left_shift(result, shift);\n}\n//\n// Now again for trivial backends:\n//\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE typename enable_if_c<is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value>::type\n   eval_gcd(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b) BOOST_NOEXCEPT\n{\n   *result.limbs() = boost::math::gcd(*a.limbs(), *b.limbs());\n}\n// This one is only enabled for unchecked cpp_int's, for checked int's we need the checking in the default version:\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\nBOOST_MP_FORCEINLINE typename enable_if_c<is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value && (Checked1 == unchecked)>::type\n   eval_lcm(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b) BOOST_NOEXCEPT_IF((is_non_throwing_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value))\n{\n   *result.limbs() = boost::math::lcm(*a.limbs(), *b.limbs());\n   result.normalize(); // result may overflow the specified number of bits\n}\n\ninline void conversion_overflow(const mpl::int_<checked>&)\n{\n   BOOST_THROW_EXCEPTION(std::overflow_error(\"Overflow in conversion to narrower type\"));\n}\ninline void conversion_overflow(const mpl::int_<unchecked>&){}\n\ntemplate <class R, unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<\n            is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value\n            && is_signed_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value\n         >::type\n   eval_convert_to(R* result, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val)\n{\n   typedef typename common_type<R, typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::local_limb_type>::type common_type;\n   if(std::numeric_limits<R>::is_specialized && (static_cast<common_type>(*val.limbs()) > static_cast<common_type>((std::numeric_limits<R>::max)())))\n   {\n      conversion_overflow(typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());\n      *result = (std::numeric_limits<R>::max)();\n   }\n   else\n      *result = static_cast<R>(*val.limbs());\n   if(val.isneg())\n   {\n      check_is_negative(mpl::bool_<boost::is_signed<R>::value || boost::is_floating_point<R>::value>());\n      *result = negate_integer(*result, mpl::bool_<boost::is_signed<R>::value || boost::is_floating_point<R>::value>());\n   }\n}\n\ntemplate <class R, unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<\n            is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value\n            && is_unsigned_number<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value\n         >::type\n   eval_convert_to(R* result, const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& val)\n{\n   typedef typename common_type<R, typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::local_limb_type>::type common_type;\n   if(std::numeric_limits<R>::is_specialized && (static_cast<common_type>(*val.limbs()) > static_cast<common_type>((std::numeric_limits<R>::max)())))\n   {\n      conversion_overflow(typename cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>::checked_type());\n      *result = (std::numeric_limits<R>::max)();\n   }\n   else\n      *result = static_cast<R>(*val.limbs());\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, unsigned>::type\n   eval_lsb(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a)\n{\n   using default_ops::eval_get_sign;\n   if(eval_get_sign(a) == 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n   }\n   if(a.sign())\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n   }\n   //\n   // Find the index of the least significant bit within that limb:\n   //\n   return boost::multiprecision::detail::find_lsb(*a.limbs());\n}\n\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1, cpp_int_check_type Checked1, class Allocator1>\ninline typename enable_if_c<is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> >::value, unsigned>::type\n   eval_msb(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a)\n{\n   using default_ops::eval_get_sign;\n   if(eval_get_sign(a) == 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n   }\n   if(a.sign())\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n   }\n   //\n   // Find the index of the least significant bit within that limb:\n   //\n   return boost::multiprecision::detail::find_msb(*a.limbs());\n}\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n}}} // namespaces\n\n#endif\n", "meta": {"hexsha": "0ef79b94452b7974817872ecbd3b4db3e9b5d696", "size": 26746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/multiprecision/cpp_int/misc.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/multiprecision/cpp_int/misc.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": "3party/boost/boost/multiprecision/cpp_int/misc.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "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": 43.9178981938, "max_line_length": 370, "alphanum_fraction": 0.7136020339, "num_tokens": 7543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.027585284824929363, "lm_q1q2_score": 0.013146585416356951}}
{"text": "#include <jni.h>\n#include <android/log.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <Eigen/Geometry>\n#include <g2o/core/hyper_graph_action.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/types/slam3d/vertex_se3.h>\n#include <g2o/types/slam3d/parameter_se3_offset.h>\n\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/pcg/linear_solver_pcg.h>\n\n#include <g2o/core/hyper_dijkstra.h>\n\nusing namespace std;\n\n#define  LOG_TAG\t\"G2O\"\n#define  LOGI(...)\t__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)\n#define  LOGE(...)\t__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)\n\n/**\n * Stop iterating based on the gain which is (oldChi - currentChi) / currentChi.\n *\n * If the gain is larger than zero and below the threshold, then the optimizer is stopped.\n * Typically usage of this action includes adding it as a postIteration action, by calling\n * addPostIterationAction on a sparse optimizer.\n */\nclass ConvergenceCheckAction : public g2o::HyperGraphAction\n{\n\tpublic:\n\t\tConvergenceCheckAction(g2o::SparseOptimizer* opt, double error_th = 1e-8)\n        : m_optimizer(opt), m_gain_th(error_th), m_last_chi2(0.), m_stop_flag(false)\n\t\t{}\n\n\t\tvoid reset(g2o::SparseOptimizer* opt = NULL, double error_th = -1.)\n\t\t{\n\t\t\tif(opt != NULL)\n\t\t\t\tm_optimizer = opt;\n\t\t\tif(error_th >= 0)\n\t\t\t\tm_gain_th = error_th;\n\t\t\tm_last_chi2 = 0.;\n\t\t\tm_stop_flag = false;\n\t\t}\n\n\t\tvirtual g2o::HyperGraphAction* operator()(const g2o::HyperGraph* graph, g2o::HyperGraphAction::Parameters* = 0)\n\t\t{\n\t\t\tm_optimizer->computeActiveErrors();\n\t\t\tconst double current_chi2 = m_optimizer->activeChi2();\n\t\t\tconst double gain = m_last_chi2/current_chi2 - 1.0;\n\t\t\tif((gain >= 0 && gain < m_gain_th) || current_chi2 == 0.0)\n\t\t\t{\n\t\t\t\t// tell the optimizer to stop\n\t\t\t\tif(m_optimizer->forceStopFlag() != NULL)\n\t\t\t\t\t*(m_optimizer->forceStopFlag()) = true;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_stop_flag = true;\n\t\t\t\t\tm_optimizer->setForceStopFlag(&m_stop_flag);\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_last_chi2 = current_chi2;\n\t\t\treturn this;\n\t\t}\n\n    private:\n\t\tg2o::SparseOptimizer* m_optimizer;\n\t\tdouble m_gain_th, m_last_chi2;\n\t\tbool m_stop_flag;\n};\n\n/** col-0 = point-0; col-1 = point-1 */\ntypedef Eigen::Matrix<double,3,2> XYZPairMeasurement;\n\nclass EdgeSE3XYZPair : public g2o::BaseBinaryEdge<3, XYZPairMeasurement, g2o::VertexSE3, g2o::VertexSE3>\n{\n\tpublic:\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\t\tEdgeSE3XYZPair()\n\t\t: offset0_(NULL), offset1_(NULL), cache0_(NULL), cache1_(NULL), weight_(1)\n\t\t{\n\t\t\tjac_buffer_.setZero();\n\t\t\tresizeParameters(2);\n\t\t\tinstallParameter(offset0_, 0);\n\t\t\tinstallParameter(offset1_, 1);\n\t\t}\n\n\t\tinline void setWeight(double w)\n\t\t{\n\t\t\tweight_ = w;\n\t\t}\n\n\t\tinline void setPointPointMetric()\n\t\t{\n\t\t\tplane_plane_metric_ = false;\n\t\t\t_information.setIdentity();\n\t\t}\n\n\t\tinline void setPointPlaneMetric(const Eigen::Vector3d& normal0, double e = 1e-3)\n\t\t{\n\t\t\tplane_plane_metric_ = false;\n\t\t\tEigen::Matrix3d info;\n\t\t\tinfo << e, 0, 0,\n\t\t\t\t\t0, e, 0,\n\t\t\t\t\t0, 0, 1;\n\t\t\tEigen::Matrix3d rot0 = computeRotation(normal0);\n\t\t\t_information = rot0.transpose()*info*rot0;\n\t\t}\n\n\t\tinline void setPlanePlaneMetric(const Eigen::Vector3d& normal0, const Eigen::Vector3d& normal1, double e = 1e-3)\n\t\t{\n\t\t\tplane_plane_metric_ = true;\n\t\t\tEigen::Matrix3d info;\n\t\t\tinfo << 1, 0, 0,\n\t\t\t\t\t0, 1, 0,\n\t\t\t\t\t0, 0, e;\n\n\t\t\tEigen::Matrix3d rot = computeRotation(normal0);\n\t\t\tcov0_ = rot.transpose()*info*rot;\n\t\t\trot = computeRotation(normal1);\n\t\t\tcov1_ = rot.transpose()*info*rot;\n\t\t}\n\n\t\tdouble weight() const\n\t\t{\n\t\t\treturn weight_;\n\t\t}\n\n\t\tconst Eigen::Matrix3d& cov0() const\n\t\t{\n\t\t\treturn cov0_;\n\t\t}\n\n\t\tconst Eigen::Matrix3d& cov1() const\n\t\t{\n\t\t\treturn cov1_;\n\t\t}\n\n\t\t//TODO meglio spostare poi il tutto in un altro file!\n\n\t\tvirtual bool read(std::istream& is)\n\t\t{\n\t\t\tint pid0, pid1;\n\t\t\tis >> pid0 >> pid1;\n\t\t\tif(!setParameterId(0, pid0))\n\t\t\t\treturn false;\n\t\t\tif(!setParameterId(1, pid1))\n\t\t\t\treturn false;\n\t\t\tif(!is.good())\n\t\t\t\treturn false;\n\n\t\t\tis >> _measurement(0,0) >> _measurement(1,0) >> _measurement(2,0)\n\t\t       >> _measurement(0,1) >> _measurement(1,1) >> _measurement(2,1);\n\t\t\tif(!is.good())\n\t\t\t\treturn false;\n\n\t\t\tfor (unsigned i = 0; i < 3; ++i)\n\t\t\t\tfor (unsigned j = 0; j < 3; ++j)\n\t\t\t\t\tis >> _information(i,j);\n\t\t\tif(!is.good())\n\t\t\t\treturn false;\n\n\t\t\tint plpl;\n\t\t\tis >> weight_ >> plpl;\n\t\t\tplane_plane_metric_ = (plpl == 1 ? true : false);\n\t\t\tif(!is.good())\n\t\t\t\treturn false;\n\n\t\t\tfor (unsigned i = 0; i < 3; ++i)\n\t\t\t\tfor (unsigned j = 0; j < 3; ++j)\n\t\t\t\t\tis >> cov0_(i,j);\n\t\t\tif(!is.good())\n\t\t\t\treturn false;\n\n\t\t\tfor (unsigned i = 0; i < 3; ++i)\n\t\t\t\tfor (unsigned j = 0; j < 3; ++j)\n\t\t\t\t\tis >> cov1_(i,j);\n\t\t\treturn true;\n\t\t}\n\n\t\tvirtual bool write(std::ostream& os) const\n\t\t{\n\t\t\tos << offset0_->id() << \" \" << offset1_->id() << \" \";\n\t\t\tos << _measurement(0,0) << \" \" << _measurement(1,0) << \" \" << _measurement(2,0) << \" \"\n\t\t       << _measurement(0,1) << \" \" << _measurement(1,1) << \" \" << _measurement(2,1) << \" \";\n\t\t\tfor (unsigned i = 0; i < 3; ++i)\n\t\t\t\tfor (unsigned j = 0; j < 3; ++j)\n\t\t\t\t\tos << _information(i,j) << \" \";\n\t\t\tos << weight_ << \" \" << (plane_plane_metric_ ? 1 : 0) << \" \";\n\t\t\tfor (unsigned i = 0; i < 3; ++i)\n\t\t\t\tfor (unsigned j = 0; j < 3; ++j)\n\t\t\t\t\tos << cov0_(i,j) << \" \";\n\t\t\tfor (unsigned i = 0; i < 3; ++i)\n\t\t\t\tfor (unsigned j = 0; j < 3; ++j)\n\t\t\t\t\tos << cov1_(i,j) << \" \";\n\n\t\t\treturn os.good();\n\t\t}\n\n\t\tvirtual void computeError()\n\t\t{\n\t\t\tif(plane_plane_metric_)\n\t\t\t{\n\t\t\t\tconst Eigen::Isometry3d n2n = cache0_->w2n() * cache1_->n2w();\n\t\t\t\t_error = weight_ * ((n2n * _measurement.col(1)) - _measurement.col(0));\n\t\t\t\t_information = (cov0_ + n2n.rotation() * cov1_ * n2n.rotation().transpose()).inverse();\n\t\t\t}\n\t\t\telse\n\t\t\t\t_error = weight_ * ((cache0_->w2n() * (cache1_->n2w() * _measurement.col(1))) - _measurement.col(0));\n\t\t}\n\n\t\tvirtual bool setMeasurementData(const double* d)\n\t\t{\n\t\t\t_measurement = Eigen::Map<const XYZPairMeasurement>(d);\n\t\t\treturn true;\n\t\t}\n\n\t\tvirtual bool getMeasurementData(double* d) const\n\t\t{\n\t\t\tEigen::Map<XYZPairMeasurement> v(d);\n\t\t\tv = _measurement;\n\t\t\treturn true;\n\t\t}\n\n\t\tvirtual void linearizeOplus()\n\t\t{\n\t\t\tconst g2o::VertexSE3* vp0 = static_cast<const g2o::VertexSE3*>(_vertices[0]);\n\t\t\tconst g2o::VertexSE3* vp1 = static_cast<const g2o::VertexSE3*>(_vertices[1]);\n\n\t\t\tif (!vp0->fixed())\n\t\t\t{\n\t\t\t\tconst Eigen::Vector3d p1t = cache0_->w2l() *  (cache1_->n2w() * _measurement.col(1));\n\t\t\t\tjac_buffer_(1,0) = 2.0*p1t[2];\n\t\t\t\tjac_buffer_(2,0) = -2.0*p1t[1];\n\t\t\t\tjac_buffer_(0,1) = -2.0*p1t[2];\n\t\t\t\tjac_buffer_(2,1) = 2.0*p1t[0];\n\t\t\t\tjac_buffer_(0,2) = 2.0*p1t[1];\n\t\t\t\tjac_buffer_(1,2) = -2.0*p1t[0];\n\n\t\t\t\t_jacobianOplusXi.block<3,3>(0,0) = -1. * offset0_->inverseOffset().rotation();\n\t\t\t\t_jacobianOplusXi.block<3,3>(0,3) = offset0_->inverseOffset().rotation() * jac_buffer_;\n\t\t\t}\n\n\t\t\tif (!vp1->fixed())\n\t\t\t{\n\t\t\t\tconst Eigen::Vector3d p1o = offset1_->offset() * _measurement.col(1);\n\t\t\t\tjac_buffer_(1,0) = -2.0*p1o[2];\n\t\t\t\tjac_buffer_(2,0) = 2.0*p1o[1];\n\t\t\t\tjac_buffer_(0,1) = 2.0*p1o[2];\n\t\t\t\tjac_buffer_(2,1) = -2.0*p1o[0];\n\t\t\t\tjac_buffer_(0,2) = -2.0*p1o[1];\n\t\t\t\tjac_buffer_(1,2) = 2.0*p1o[0];\n\n\t\t\t\t_jacobianOplusXj.block<3,3>(0,0) = cache0_->w2n().rotation() * vp1->estimate().rotation();\n\t\t\t\t_jacobianOplusXj.block<3,3>(0,3) = _jacobianOplusXj.block<3,3>(0,0) * jac_buffer_;\n\t\t\t}\n\t\t}\n\n\t\tvirtual int measurementDimension() const\n\t\t{\n\t\t\treturn 6;\n\t\t}\n\n\tprivate:\n\t\tinline Eigen::Matrix3d computeRotation(const Eigen::Vector3d& normal) const\n\t\t{\n\t\t\tEigen::Matrix3d rot;\n\t\t\trot.row(2) = normal;\n\t\t\trot.row(1) = (Eigen::Vector3d::UnitY() - normal(1)*normal).normalized();\n\t\t\trot.row(0) = normal.cross(rot.row(1));\n\t\t\treturn rot;\n\t\t}\n\n\t\tvirtual bool resolveCaches()\n\t\t{\n\t\t\tassert(offset0_ && offset1_);\n\n\t\t\tg2o::ParameterVector pv(2);\n\t\t\tpv[0] = offset0_;\n\t\t\tresolveCache(cache0_, (g2o::OptimizableGraph::Vertex*)_vertices[0], \"CACHE_SE3_OFFSET\", pv);\n\t\t\tpv[1] = offset1_;\n\t\t\tresolveCache(cache1_, (g2o::OptimizableGraph::Vertex*)_vertices[1], \"CACHE_SE3_OFFSET\", pv);\n\t\t\treturn (cache0_ && cache1_);\n\t\t}\n\n\t\tg2o::ParameterSE3Offset *offset0_, *offset1_;\n\t\tg2o::CacheSE3Offset  *cache0_, *cache1_;\n\n\t\tdouble weight_;\n\t\tbool plane_plane_metric_;\n\t\tEigen::Matrix3d cov0_, cov1_;\n\t\tEigen::Matrix3d jac_buffer_;\n};\n\nextern \"C\"\n{\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_initNativeGraph(JNIEnv *env, jobject obj);\n\tJNIEXPORT jdouble JNICALL Java_it_unibo_slam_graph_GraphBackend_getChi2Native(JNIEnv *env, jobject obj);\n\tJNIEXPORT jdouble JNICALL Java_it_unibo_slam_graph_GraphBackend_getWeightedMeanChi2Native(JNIEnv *env, jobject obj);\n\tJNIEXPORT jint JNICALL Java_it_unibo_slam_graph_GraphBackend_getNumberOfEdgesNative(JNIEnv *env, jobject obj);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_clearNative(JNIEnv *env, jobject obj);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_setFixedViewNative(JNIEnv *env, jobject obj,\n\t\t\tjint viewId, jboolean fixed);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_addVertexWithEstimateNative(JNIEnv *env, jobject obj,\n\t\t\tjint poseId, jdoubleArray estimate);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_setVertexEstimateNative(JNIEnv *env, jobject obj,\n\t\t\tjint poseId, jdoubleArray estimate);\n\tJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_graph_GraphBackend_getVertexEstimateNative(JNIEnv *env, jobject obj,\n\t\t\tjint poseId);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_removeVertexNative(JNIEnv *env, jobject obj,\n\t\t\tjint poseId);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_addEdgeNative(JNIEnv *env, jobject obj,\n\t\t\tjint referenceId, jint matchingId, jdoubleArray referenceVx, jdoubleArray matchingVx, jdouble score);\n\tJNIEXPORT jint JNICALL Java_it_unibo_slam_graph_GraphBackend_optimizeNative(JNIEnv *env, jobject obj,\n\t\t\tjint maximumNumberOfIterations);\n\tJNIEXPORT jint JNICALL Java_it_unibo_slam_graph_GraphBackend_relativeOptimizeNative(JNIEnv *env, jobject obj,\n\t\t\tjintArray vSet, jint size, jint maximumNumberOfIterations);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_createRBASubsetNative(JNIEnv *env, jobject obj,\n\t\t\tjint originId, jint ring, jobject vSet, jobject fSet);\n}\n\n// Global variables accessible only within this source file\nnamespace\n{\n\tg2o::SparseOptimizer optimizer;\n\tConvergenceCheckAction action = ConvergenceCheckAction(&optimizer, 1E-10);\n\tdouble edgeWeights = 0.0;\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_initNativeGraph(JNIEnv *env, jobject obj)\n{\n\taction = ConvergenceCheckAction(&optimizer, 1E-10);\n\tedgeWeights = 0.0;\n\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<6, 0> > BlockSolver_6_0;\n\n\tBlockSolver_6_0::LinearSolverType* linearSolver = new g2o::LinearSolverPCG<BlockSolver_6_0::PoseMatrixType>();\n\tBlockSolver_6_0* solverPointer = new BlockSolver_6_0(linearSolver);\n\tg2o::OptimizationAlgorithmLevenberg* optimizationAlgorithm = new g2o::OptimizationAlgorithmLevenberg(solverPointer);\n\n\t// Set the algorithm and the termination action\n\toptimizer.setAlgorithm(optimizationAlgorithm);\n\toptimizer.addPostIterationAction(&action);\n\n\tg2o::ParameterSE3Offset* offset = new g2o::ParameterSE3Offset();\n\toffset->setId(0);\n\toptimizer.addParameter(offset);\n}\n\nJNIEXPORT jdouble JNICALL Java_it_unibo_slam_graph_GraphBackend_getChi2Native(JNIEnv *env, jobject obj)\n{\n\treturn optimizer.activeChi2();\n}\n\nJNIEXPORT jdouble JNICALL Java_it_unibo_slam_graph_GraphBackend_getWeightedMeanChi2Native(JNIEnv *env, jobject obj)\n{\n\tassert(edgeWeights > 0);\n\treturn optimizer.activeChi2() / edgeWeights;\n}\n\nJNIEXPORT jint JNICALL Java_it_unibo_slam_graph_GraphBackend_getNumberOfEdgesNative(JNIEnv *env, jobject obj)\n{\n\treturn optimizer.edges().size();\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_clearNative(JNIEnv *env, jobject obj)\n{\n\toptimizer.clear();\n\tedgeWeights = 0.0;\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_setFixedViewNative(JNIEnv *env, jobject obj,\n\t\tjint viewId, jboolean fixed)\n{\n\tg2o::SparseOptimizer::Vertex* v = optimizer.vertex(viewId);\n\tif (v != NULL)\n\t\tv->setFixed(fixed);\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_addVertexWithEstimateNative(JNIEnv *env, jobject obj,\n\t\tjint poseId, jdoubleArray estimate)\n{\n\tdouble tempEstimate[16];\n\tenv->GetDoubleArrayRegion(estimate, 0, 16, tempEstimate);\n\n\tEigen::Isometry3d estimateEigen(Eigen::Matrix4d::Map(tempEstimate));\n\n\tg2o::VertexSE3* vx = new g2o::VertexSE3();\n\tvx->setId(poseId);\n\tvx->setEstimate(estimateEigen);\n\toptimizer.addVertex(vx);\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_setVertexEstimateNative(JNIEnv *env, jobject obj,\n\t\tjint poseId, jdoubleArray estimate)\n{\n\tdouble tempEstimate[16];\n\tenv->GetDoubleArrayRegion(estimate, 0, 16, tempEstimate);\n\n\tEigen::Isometry3d estimateEigen(Eigen::Matrix4d::Map(tempEstimate));\n\n\tstatic_cast<g2o::VertexSE3*>(optimizer.vertex(poseId))->setEstimate(estimateEigen);\n}\n\nJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_graph_GraphBackend_getVertexEstimateNative(JNIEnv *env, jobject obj,\n\t\tjint poseId)\n{\n\tjdoubleArray vertexEstimateArray;\n\tvertexEstimateArray = env->NewDoubleArray(16);\n\tdouble *tempVertexEstimateArray;\n\n\tEigen::Isometry3d vertexEstimate = static_cast<g2o::VertexSE3*>(optimizer.vertex(poseId))->estimate();\n\ttempVertexEstimateArray = vertexEstimate.data();\n\tenv->SetDoubleArrayRegion(vertexEstimateArray, 0, 16, tempVertexEstimateArray);\n\treturn vertexEstimateArray;\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_removeVertexNative(JNIEnv *env, jobject obj,\n\t\tjint poseId)\n{\n\tg2o::SparseOptimizer::Vertex* vx = optimizer.vertex(poseId);\n\n\tfor(g2o::HyperGraph::EdgeSet::const_iterator it = vx->edges().begin(); it != vx->edges().end(); ++it)\n\t\tedgeWeights -= static_cast<const EdgeSE3XYZPair*>(*it)->weight();\n\n\toptimizer.removeVertex(vx);\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_addEdgeNative(JNIEnv *env, jobject obj,\n\t\tjint referenceId, jint matchingId, jdoubleArray referenceVx, jdoubleArray matchingVx, jdouble score)\n{\n\tdouble tempReferenceVx[3];\n\tdouble tempMatchingVx[3];\n\tenv->GetDoubleArrayRegion(referenceVx, 0, 3, tempReferenceVx);\n\tenv->GetDoubleArrayRegion(matchingVx, 0, 3, tempMatchingVx);\n\n\tEigen::Vector3d referenceVxEigen(tempReferenceVx[0], tempReferenceVx[1], tempReferenceVx[2]);\n\tEigen::Vector3d matchingVxEigen(tempMatchingVx[0], tempMatchingVx[1], tempMatchingVx[2]);\n\n\tg2o::SparseOptimizer::Vertex* referenceVertex = optimizer.vertex(referenceId);\n\tg2o::SparseOptimizer::Vertex* matchingVertex = optimizer.vertex(matchingId);\n\n\tEdgeSE3XYZPair* edge = new EdgeSE3XYZPair();\n\tedge->setParameterId(0, 0);\n\tedge->setParameterId(1, 0);\n\tedge->vertices()[0] = referenceVertex;\n\tedge->vertices()[1] = matchingVertex;\n\n\tXYZPairMeasurement measurement;\n\tmeasurement.col(0) = referenceVxEigen;\n\tmeasurement.col(1) = matchingVxEigen;\n\n\tedge->setMeasurement(measurement);\n\tif (score > 0)\n\t\tedge->setWeight(score);\n\tedge->setPointPointMetric();\n\toptimizer.addEdge(edge);\n\n\tedgeWeights += edge->weight();\n}\n\nJNIEXPORT jint JNICALL Java_it_unibo_slam_graph_GraphBackend_optimizeNative(JNIEnv *env, jobject obj,\n\t\tjint maximumNumberOfIterations)\n{\n\taction.reset();\n\toptimizer.initializeOptimization(-1);\n\treturn optimizer.optimize(maximumNumberOfIterations);\n}\n\nJNIEXPORT jint JNICALL Java_it_unibo_slam_graph_GraphBackend_relativeOptimizeNative(JNIEnv *env, jobject obj,\n\t\tjintArray vSet, jint size, jint maximumNumberOfIterations)\n{\n\tint vSetArray[size];\n\tenv->GetIntArrayRegion(vSet, 0, size, vSetArray);\n\n\tg2o::HyperGraph::VertexSet vSetG2O;\n\tfor (int i = 0; i < size; i++)\n\t\tvSetG2O.insert(optimizer.vertex(vSetArray[i]));\n\n\taction.reset();\n\toptimizer.initializeOptimization(vSetG2O, -1);\n\treturn optimizer.optimize(maximumNumberOfIterations);\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_graph_GraphBackend_createRBASubsetNative(JNIEnv *env, jobject obj,\n\t\tjint originId, jint ring, jobject vSet, jobject fSet)\n{\n\t//TODO verificare se i metodi sono corretti\n\n\tjclass vSetClass = env->GetObjectClass(vSet);\n\tjmethodID vSetMethod = env->GetMethodID(vSetClass, \"add\", \"(Ljava/lang/Object;)Z\");\n\tif (vSetMethod == 0)\n\t{\n\t\tLOGE(\"VSET METHOD NOT FOUND\");\n\t\treturn;\n\t}\n\n\tjclass fSetClass = env->GetObjectClass(fSet);\n\tjmethodID fSetMethod = env->GetMethodID(fSetClass, \"add\", \"(Ljava/lang/Object;)Z\");\n\tif (fSetMethod == 0)\n\t{\n\t\tLOGE(\"FSET METHOD NOT FOUND\");\n\t\treturn;\n\t}\n\n\tg2o::HyperGraph::Vertex* origin = optimizer.vertex(originId);\n\tg2o::HyperGraph::VertexSet vSetG2O;\n\tg2o::HyperGraph::VertexSet fSetG2O;\n\n\tvSetG2O.insert(origin);\n\n\tg2o::HyperGraph::VertexSet localSets[2];\n\tlocalSets[0] = vSetG2O;\n\tg2o::HyperGraph::VertexSet* lastRing = &localSets[0];\n\tg2o::HyperGraph::VertexSet* nextRing = &localSets[1];\n\n\tfor (unsigned cr = 0; cr <= ring; ++cr)\n\t{\n\t\tfor (g2o::HyperGraph::VertexSet::const_iterator vit = lastRing->begin(); vit != lastRing->end(); ++vit)\n\t\t{\n\t\t\t// Collect next ring\n\t\t\tfor (g2o::HyperGraph::EdgeSet::iterator eit = (*vit)->edges().begin(); eit != (*vit)->edges().end(); ++eit)\n\t\t\t{\n\t\t\t\tfor (unsigned i = 0; i < (*eit)->vertices().size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tg2o::HyperGraph::Vertex* vi = (*eit)->vertex(i);\n\t\t\t\t\tif (!vSetG2O.count(vi))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (cr == ring)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvSetG2O.insert(vi);\n\t\t\t\t\t\t\tfSetG2O.insert(vi);\n\t\t\t\t\t\t\tstatic_cast<g2o::SparseOptimizer::Vertex*>(vi)->setFixed(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tnextRing->insert(vi);\n\t\t\t\t\t}\n\t\t\t\t} // For every vx attached to the periphery\n\t\t\t} // For every peripheral edge\n\t\t} // For every peripheral vx\n\n\t\tif (nextRing->empty())\n\t\t\tbreak;\n\n\t\tvSetG2O.insert(nextRing->begin(), nextRing->end());\n\t\tstd::swap(lastRing, nextRing);\n\t\tnextRing->clear();\n\n\t} // For every ring\n\n\tjclass integerClass = env->FindClass(\"java/lang/Integer\");\n\tjmethodID integerInitMethod = env->GetMethodID(integerClass, \"<init>\", \"(I)V\");\n\n\t//TODO verificare funzionamento - passaggio da int a Integer\n\tfor (g2o::HyperGraph::VertexSet::const_iterator vit = vSetG2O.begin(); vit != vSetG2O.end(); ++vit)\n\t\tenv->CallBooleanMethod(vSet, vSetMethod, env->NewObject(integerClass, integerInitMethod, (*vit)->id()));\n\tfor (g2o::HyperGraph::VertexSet::const_iterator fit = fSetG2O.begin(); fit != fSetG2O.end(); ++fit)\n\t\tenv->CallBooleanMethod(fSet, fSetMethod, env->NewObject(integerClass, integerInitMethod, (*fit)->id()));\n}\n\nextern \"C\"\n{\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunk_initDijkstraNative(JNIEnv *env, jobject obj);\n\tJNIEXPORT jboolean JNICALL Java_it_unibo_slam_main_SlamDunk_loopClosureCheck(JNIEnv *env, jobject obj,\n\t\t\tjintArray trackedKeyframes, jint size, jint rbaRings);\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunk_updateAdjacencyMap(JNIEnv *env, jobject obj,\n\t\t\tjint id);\n}\n\ng2o::HyperDijkstra dijkstra = g2o::HyperDijkstra(&optimizer);\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunk_initDijkstraNative(JNIEnv *env, jobject obj)\n{\n\tdijkstra = g2o::HyperDijkstra(&optimizer);\n}\n\nJNIEXPORT jboolean JNICALL Java_it_unibo_slam_main_SlamDunk_loopClosureCheck(JNIEnv *env, jobject obj,\n\t\tjintArray trackedKeyframes, jint size, jint rbaRings)\n{\n\tint trackedKeyframesArray[size];\n\tenv->GetIntArrayRegion(trackedKeyframes, 0, size, trackedKeyframesArray);\n\n\tstd::vector<g2o::HyperGraph::Vertex*> trackedVertices(size);\n\tfor (unsigned k = 0; k < trackedVertices.size(); k++)\n\t\ttrackedVertices[k] = optimizer.vertex(trackedKeyframesArray[k]);\n\n\tg2o::UniformCostFunction edgeCost;\n\tbool isKeyframe = false;\n\tfor (unsigned k = 0; k < trackedVertices.size() && !isKeyframe; ++k)\n\t{\n\t\tg2o::HyperGraph::Vertex* vx = trackedVertices[k];\n\t\tdijkstra.shortestPaths(vx, &edgeCost, rbaRings);\n\t\tconst g2o::HyperGraph::VertexSet& visited = dijkstra.visited();\n\n\t\tfor (unsigned k2 = k; k2 < trackedVertices.size() && !isKeyframe; ++k2)\n\t\t\tisKeyframe = (visited.count(trackedVertices[k2]) == 0);\n\t}\n\n\treturn isKeyframe;\n}\n\nJNIEXPORT void JNICALL Java_it_unibo_slam_main_SlamDunk_updateAdjacencyMap(JNIEnv *env, jobject obj,\n\t\tjint id)\n{\n\tg2o::HyperGraph::Vertex* vx = optimizer.vertex(id);\n\tg2o::HyperDijkstra::AdjacencyMapEntry entry(vx, 0, 0, std::numeric_limits< double >::max());\n\tdijkstra.adjacencyMap().insert(std::make_pair(entry.child(), entry));\n}\n", "meta": {"hexsha": "ffef3daac190bd1ed1c6e60ad5aab7e20df35090", "size": 20154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni/g2o/G2O.cpp", "max_stars_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_stars_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T15:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:07:15.000Z", "max_issues_repo_path": "jni/g2o/G2O.cpp", "max_issues_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_issues_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-31T05:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T14:06:53.000Z", "max_forks_repo_path": "jni/g2o/G2O.cpp", "max_forks_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_forks_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T12:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T08:07:55.000Z", "avg_line_length": 32.7707317073, "max_line_length": 119, "alphanum_fraction": 0.7192120671, "num_tokens": 6140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.027585284125430275, "lm_q1q2_score": 0.013146585082989921}}
{"text": "// This file is part of the dune-grid-multiscale project:\n//   http://users.dune-project.org/projects/dune-grid-multiscale\n// Copyright holders: Felix Albrecht\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#ifndef DUNE_GRID_MULTISCALE_GLUED_HH\n#define DUNE_GRID_MULTISCALE_GLUED_HH\n\n#include <algorithm>\n#include <memory>\n#include <map>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/version.hh>\n\n#include <dune/grid/common/gridfactory.hh>\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n# include <dune/grid/common/rangegenerators.hh>\n#else\n# include <dune/stuff/common/ranges.hh>\n#endif\n#include <dune/grid/io/file/vtk/vtkwriter.hh>\n\n#include <dune/grid-glue/extractors/codim1extractor.hh>\n#include <dune/grid-glue/extractors/extractorpredicate.hh>\n#include <dune/grid-glue/gridglue.hh>\n#include <dune/grid-glue/merging/contactmerge.hh>\n\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/float_cmp.hh>\n#include <dune/stuff/common/memory.hh>\n#include <dune/stuff/common/timedlogging.hh>\n#include <dune/stuff/common/ranges.hh>\n#include <dune/stuff/common/vector.hh>\n#include <dune/stuff/grid/intersection.hh>\n#include <dune/stuff/grid/provider/cube.hh>\n#include <dune/stuff/grid/provider/interface.hh>\n#include <dune/stuff/grid/search.hh>\n\nnamespace Dune {\nnamespace grid {\nnamespace Multiscale {\nnamespace Exceptions {\n\n\nclass intersection_orientation_is_broken : public Dune::InvalidStateException {};\n\n\n} // namespace Exceptions\n\n\ntemplate<typename P0, typename P1>\nsize_t check_for_broken_coupling_intersections(const GridGlue::GridGlue<P0, P1>& glue,\n                                               const typename P0::ctype& tolerance = 10*Stuff::Common::FloatCmp::DefaultEpsilon<typename P0::ctype>::value())\n{\n  const auto inside_grid_view = glue.template gridView<0>();\n  size_t failures = 0;\n  // walk the coupling\n  const auto coupling_intersection_it_end = glue.template iend<0>();\n  for (auto coupling_intersection_it = glue.template ibegin<0>();\n       coupling_intersection_it != coupling_intersection_it_end;\n       ++coupling_intersection_it) {\n    const auto& coupling_intersection = *coupling_intersection_it;\n    const auto coupling_intersection_normal = coupling_intersection.centerUnitOuterNormal();\n    const auto local_entity_ptr = coupling_intersection.inside();\n    const auto& local_entity = *local_entity_ptr;\n    typename std::remove_const<decltype(coupling_intersection_normal)>::type local_intersection_normal(0.);\n    // find the intersection of the local inside entity that corresponds to the coupling intersection\n    size_t found = 0;\n    for (auto&& local_intersection : intersection_range(inside_grid_view, local_entity)) {\n      // the coupling intersection may be smaller than the local intersection, so check if all of the corners of the\n      // coupling intersection lie within this local intersection\n      int corners_inside = 0;\n      for (auto ii : DSC::valueRange(coupling_intersection.geometry().corners()))\n        if (DSG::contains(local_intersection, coupling_intersection.geometry().corner(ii)))\n          ++corners_inside;\n      if (corners_inside == coupling_intersection.geometry().corners()) {\n        // this is the one\n        ++found;\n        local_intersection_normal = local_intersection.centerUnitOuterNormal();\n      }\n    }\n    if (found != 1)\n      DUNE_THROW(InvalidStateException,\n                 \"This should not happen!\\n\"\n                 << \"There were \" << found << \" local intersections which contain the coupling intersection, \"\n                 << \"and there must not be more than one!\");\n    // now the expected normal is local_intersection_normal\n    // and we would like coupling_intersection_normal to point in the same direction\n    // since they have unit length, they should be identical\n    if ((local_intersection_normal - coupling_intersection_normal).infinity_norm() > tolerance)\n      ++failures;\n  }\n  return failures;\n} // ... check_for_broken_coupling_intersections(...)\n\n\n// forward\ntemplate <class MacroGridType, class LocalGridType>\nclass GluedVTKWriter;\n\n\ntemplate <class MacroGridImp, class LocalGridImp>\nclass Glued\n{\n  template< class G, bool anything = true>\n  struct allowed_macro_grid\n  {\n    static const bool value = true;\n  };\n\n  template< class G, bool anything = true>\n  struct allowed_local_grid\n  {\n    static const bool value = true;\n  };\n\n#if HAVE_ALUGRID\n  template< class Comm, bool anything>\n  struct allowed_local_grid<ALUGrid<3, 3, simplex, conforming, Comm>, anything>\n  {\n    static const bool value = false;\n  };\n\n  template< class Comm, bool anything>\n  struct allowed_local_grid<ALUGrid<3, 3, cube, conforming, Comm>, anything>\n  {\n    static const bool value = false;\n  };\n#endif\n\n  static_assert(allowed_macro_grid<MacroGridImp>::value,\n                \"This macro grid is known to fail, enable on your onw risk by disabling this check!\");\n  static_assert(allowed_local_grid<LocalGridImp>::value,\n                \"This local grid is known to fail, enable on your onw risk by disabling this check!\");\npublic:\n  typedef MacroGridImp                                      MacroGridType;\n  typedef Stuff::Grid::ProviderInterface<MacroGridType>     MacroGridProviderType;\n  typedef typename MacroGridProviderType::LeafGridViewType  MacroGridViewType;\n  typedef typename MacroGridType::template Codim<0>::Entity MacroEntityType;\n\n  typedef LocalGridImp                                             LocalGridType;\n  typedef Stuff::Grid::ProviderInterface<LocalGridType>            LocalGridProviderType;\n\n#if HAVE_DUNE_FEM\n  typedef typename LocalGridProviderType::LevelGridPartType            MicroGridPartType;\n#endif\n  typedef typename LocalGridType::LevelGridView                        MicroGridViewType;\n  typedef typename MicroGridViewType::template Codim<0>::Entity        MicroEntityType;\n  typedef typename MicroGridViewType::template Codim<0>::EntityPointer MicroEntityPointerType;\n\n  typedef typename MacroGridType::ctype ctype;\n  static const size_t dimDomain = MacroGridType::dimension;\n  static const size_t dimWorld  = MacroGridType::dimensionworld;\n\nprivate:\n  typedef typename LocalGridProviderType::LevelGridViewType LocalViewType;\n  typedef GridGlue::Codim1Extractor<LocalViewType> LocalExtractorType;\n  typedef GridGlue::GridGlue<LocalExtractorType, LocalExtractorType> GlueType;\n\n  template <class GridView, class MacroIntersectionType>\n  class CouplingFaceDescriptor : public GridGlue::ExtractorPredicate<GridView, 1>\n  {\n    typedef typename GridView::Traits::template Codim<0>::Entity LocalEntityType;\n    typedef typename GridView::ctype ctype;\n\n  public:\n    CouplingFaceDescriptor(const MacroIntersectionType& macro_intersection) : macro_intersection_(macro_intersection) {}\n\n    virtual bool contains(const LocalEntityType& element, unsigned int face) const override final\n    {\n      const auto local_intersection_ptr       = element.template subEntity<1>(face);\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n      const auto& local_intersection          = local_intersection_ptr;\n#else\n      const auto& local_intersection          = *local_intersection_ptr;\n#endif\n      const auto& local_intersection_geometry = local_intersection.geometry();\n      // Check if all corners of the local intersection lie within the macro intersection.\n      for (auto ii : DSC::valueRange(local_intersection_geometry.corners()))\n        if (!DSG::contains(macro_intersection_, local_intersection_geometry.corner(ii)))\n          return false;\n      return true;\n    } // ... contains(...)\n\n  private:\n    const MacroIntersectionType& macro_intersection_;\n  }; // CouplingFaceDescriptor\n\n  template <class GV, class MI>\n  static CouplingFaceDescriptor<GV, MI> create_descriptor(const GV& /*gv*/, const MI& mi)\n  {\n    return CouplingFaceDescriptor<GV, MI>(mi);\n  }\n\npublic:\n  Glued(MacroGridProviderType& macro_grid_provider,\n        const size_t num_local_refinements = 0,\n        const bool prepare_glues = false,\n        const bool allow_for_broken_orientation_of_coupling_intersections = false,\n        const ctype& allowed_overlap = 10 * Stuff::Common::FloatCmp::DefaultEpsilon<ctype>::value())\n    : macro_grid_(macro_grid_provider)\n    , allowed_overlap_(allowed_overlap)\n    , macro_leaf_view_(macro_grid_.leaf_view())\n    , local_grids_(macro_leaf_view_.indexSet().size(0), nullptr)\n    , glues_(macro_leaf_view_.indexSet().size(0))\n  {\n    setup_local_grids();\n    if (num_local_refinements > 0)\n      for (auto& local_grid_provider : local_grids_) {\n        assert(local_grid_provider);\n        local_grid_provider->grid().globalRefine(boost::numeric_cast<int>(num_local_refinements));\n      }\n    if (prepare_glues)\n      setup_glues(allow_for_broken_orientation_of_coupling_intersections);\n  } // Glued(...)\n\n  const MacroGridViewType& macro_grid_view() const { return macro_leaf_view_; }\n\n  size_t num_subdomains() const\n  {\n    return macro_grid_view().indexSet().size(0);\n  }\n\n  size_t subdomain(const MacroEntityType& macro_entity) const\n  {\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return macro_leaf_view_.indexSet().index(macro_entity);\n  }\n\n  bool boundary(const MacroEntityType& macro_entity) const\n  {\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return macro_entity.hasBoundaryIntersections();\n  }\n\n  MicroGridViewType global_grid_view()\n  {\n    auto logger = DSC::TimedLogger().get(\"grid-multiscale.glued.global_grid_view\");\n    logger.warn() << \"Requiring access to global micro grid!\" << std::endl;\n    prepare_global_grid();\n    return global_grid_->level_view(global_grid_->grid().maxLevel());\n  }\n\n#if HAVE_DUNE_FEM\n  MicroGridPartType global_grid_part()\n  {\n    auto logger = DSC::TimedLogger().get(\"grid-multiscale.glued.global_grid_part\");\n    logger.warn() << \"Requiring access to global micro grid!\" << std::endl;\n    prepare_global_grid();\n    return MicroGridPartType(global_grid_->grid(), global_grid_->grid().maxLevel());\n  }\n#endif // HAVE_DUNE_FEM\n\n  const std::vector<std::vector<size_t>>& local_to_global_indices()\n  {\n    auto logger = DSC::TimedLogger().get(\"grid-multiscale.glued.local_to_global_indices\");\n    logger.warn() << \"Requiring access to global micro grid!\" << std::endl;\n    prepare_global_grid();\n    return *local_to_global_indices_;\n  }\n\n  MicroEntityPointerType local_to_global_entity(const size_t subdomain, const MicroEntityType& local_entity)\n  {\n    return local_to_global_entity(subdomain, local_grids_[subdomain]->level_view(max_local_level(subdomain)).indexSet().index(local_entity));\n  }\n\n  MicroEntityPointerType local_to_global_entity(const size_t subdomain, const size_t local_entity_index)\n  {\n    auto logger = DSC::TimedLogger().get(\"grid-multiscale.glued.local_to_global_entity\");\n    logger.warn() << \"Requiring access to global micro grid!\" << std::endl;\n    prepare_global_grid();\n    const size_t global_index_of_local_entity = local_to_global_indices_->operator[](subdomain)[local_entity_index];\n    const auto global_micro_grid_view = global_grid_view();\n    const auto entity_it_end = global_micro_grid_view.template end<0>();\n    for (auto entity_it = global_micro_grid_view.template begin<0>();\n         entity_it != entity_it_end;\n         ++entity_it) {\n      const auto& entity = *entity_it;\n      if (global_micro_grid_view.indexSet().index(entity) == global_index_of_local_entity)\n        return entity_it;\n    }\n    DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n               \"subdomain: \" << subdomain << \"\\n\"\n               << \"local_entity_index: \" << local_entity_index << \"\\n\"\n               << \"global_index_of_local_entity: \" << global_index_of_local_entity);\n    return global_micro_grid_view.template begin<0>();\n  } // ... local_to_global_entity(...)\n\n  MicroEntityPointerType global_to_local_entity(const MicroEntityType& micro_entity)\n  {\n    prepare_global_grid();\n    return global_to_local_entity(global_grid_view().indexSet().index(micro_entity));\n  }\n\n  MicroEntityPointerType global_to_local_entity(const size_t micro_entity_index)\n  {\n    auto logger = DSC::TimedLogger().get(\"grid-multiscale.glued.global_to_local_entity\");\n    logger.warn() << \"Requiring access to global micro grid!\" << std::endl;\n    prepare_global_grid();\n    auto subdomain_and_local_entity_index = global_to_local_indices_->operator[](micro_entity_index);\n    const auto subdomain = subdomain_and_local_entity_index.first;\n    const auto local_index_of_global_entity = subdomain_and_local_entity_index.second;\n    const auto local_grid_view = local_grids_[subdomain]->level_view(max_local_level(subdomain));\n    const auto entity_it_end = local_grid_view.template end<0>();\n    for (auto entity_it = local_grid_view.template begin<0>();\n         entity_it != entity_it_end;\n         ++entity_it) {\n      const auto& entity = *entity_it;\n      if (local_grid_view.indexSet().index(entity) == local_index_of_global_entity)\n        return MicroEntityPointerType(entity_it);\n    }\n    DUNE_THROW(Stuff::Exceptions::wrong_input_given,\n               \"micro_entity_index: \" << micro_entity_index << \"\\n\"\n               \"subdomain: \" << subdomain << \"\\n\"\n               << \"local_index_of_global_entity: \" << local_index_of_global_entity);\n    return MicroEntityPointerType(local_grid_view.template begin<0>());\n  } // ... global_to_local_entity(...)\n\n  const std::vector<std::pair<size_t, size_t>>& global_to_local_indices()\n  {\n    auto logger = DSC::TimedLogger().get(\"grid-multiscale.glued.global_to_local_indices\");\n    logger.warn() << \"Requiring access to global micro grid!\" << std::endl;\n    prepare_global_grid();\n    assert(global_to_local_indices_);\n    return *global_to_local_indices_;\n  }\n\n  const LocalGridProviderType& local_grid(const MacroEntityType& macro_entity) const\n  {\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return local_grid(macro_leaf_view_.indexSet().index(macro_entity));\n  }\n\n  LocalGridProviderType& local_grid(const MacroEntityType& macro_entity)\n  {\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return local_grid(macro_leaf_view_.indexSet().index(macro_entity));\n  }\n\n  LocalGridProviderType& local_grid(const size_t macro_entity_index)\n  {\n    return *(local_grids_.at(macro_entity_index));\n  }\n\n  const LocalGridProviderType& local_grid(const size_t macro_entity_index) const\n  {\n    return *(local_grids_.at(macro_entity_index));\n  }\n\n  /**\n   * \\brief Returns (and creates, if it does not exist) the coupling glue between the local grid view of level\n   *        local_level_macro_entity on macro_entity and the local grid view of level local_level_macro_neighbor on macro_neighbor.\n   * \\note  Access is not implemented efficiently. This could be improved by using std::map::find instead of\n   *        std::map::operator[].\n   */\n  const GlueType& coupling(const MacroEntityType& macro_entity, const int local_level_macro_entity,\n                           const MacroEntityType& macro_neighbor, const int local_level_macro_neighbor,\n                           const bool allow_for_broken_orientation_of_coupling_intersections = false)\n  {\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    assert(macro_index_set.contains(macro_entity));\n    assert(macro_index_set.contains(macro_neighbor));\n    if (local_level_macro_entity > max_local_level(macro_entity))\n      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,\n                    \"max_local_level(macro_entity): \" << max_local_level(macro_entity) << \"\\n\"\n                 << \"   local_level_macro_entity:      \" << local_level_macro_entity);\n    if (local_level_macro_neighbor > max_local_level(macro_neighbor))\n      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,\n                    \"max_local_level(macro_neighbor): \" << max_local_level(macro_neighbor) << \"\\n\"\n                 << \"   local_level_macro_neighbor:      \" << local_level_macro_neighbor);\n    const auto entity_index   = macro_index_set.index(macro_entity);\n    const auto neighbor_index = macro_index_set.index(macro_neighbor);\n    if (glues_[entity_index][neighbor_index][local_level_macro_entity][local_level_macro_neighbor] == nullptr) {\n      // find the corresponding macro intersection ...\n      const auto macro_intersection_it_end = macro_leaf_view_.iend(macro_entity);\n      for (auto macro_intersection_it = macro_leaf_view_.ibegin(macro_entity);\n           macro_intersection_it != macro_intersection_it_end;\n           ++macro_intersection_it) {\n        const auto& macro_intersection = *macro_intersection_it;\n        if (macro_intersection.neighbor() && !macro_intersection.boundary()) {\n          const auto real_neighbor_ptr = macro_intersection.outside();\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n          const auto& real_neighbor = real_neighbor_ptr;\n#else\n          const auto& real_neighbor = *real_neighbor_ptr;\n#endif\n          if (macro_index_set.index(real_neighbor) == neighbor_index)\n            glues_[entity_index][neighbor_index][local_level_macro_entity][local_level_macro_neighbor] =\n                create_glue(macro_entity, macro_neighbor,\n                            macro_intersection,\n                            local_level_macro_entity, local_level_macro_neighbor);\n        }\n      } // ... find the corresponding macro intersection\n    }\n\n    const auto& glue = *(glues_[entity_index][neighbor_index][local_level_macro_entity][local_level_macro_neighbor]);\n    if (!allow_for_broken_orientation_of_coupling_intersections) {\n      const size_t brocken_intersections = check_for_broken_coupling_intersections(glue);\n      if (brocken_intersections > 0)\n        DUNE_THROW(Exceptions::intersection_orientation_is_broken,\n                   \"The coupling glue between the grid views of\\n\"\n                   << \"     level \" << local_level_macro_entity << \" on macro entity   \"\n                   << macro_leaf_view_.indexSet().index(macro_entity) << \" and\\n\"\n                   << \"     level \" << local_level_macro_neighbor << \" on macro neighbor \"\n                   << macro_leaf_view_.indexSet().index(macro_neighbor) << \"\\n\"\n                   << \"   contains\\n\"\n                   << \"     \" << brocken_intersections << \"/\" << glue.size()\n                   << \" intersections with wrong orientation!\");\n    }\n    return glue;\n  } // ... coupling(...)\n\n  const GlueType& coupling(const MacroEntityType& macro_entity,\n                           const MacroEntityType& macro_neighbor,\n                           const bool allow_for_broken_orientation_of_coupling_intersections = false)\n  {\n    return coupling(macro_entity, max_local_level(macro_entity),\n                    macro_neighbor, max_local_level(macro_neighbor),\n                    allow_for_broken_orientation_of_coupling_intersections);\n  }\n\n  int max_local_level(const MacroEntityType& macro_entity) const\n  {\n    return local_grid(macro_entity).grid().maxLevel();\n  }\n\n  int max_local_level(const size_t macro_entity_index) const\n  {\n    return local_grid(macro_entity_index).grid().maxLevel();\n  }\n\n      const std::vector<std::pair<MicroEntityPointerType, std::vector<int>>>&\n  local_boundary_entities(const MacroEntityType& macro_entity, const int local_level)\n  {\n//    auto logger = Stuff::Common::TimedLogger().get(\"grid-multiscale.glued.local_boundary_entities\");\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    const size_t macro_entity_index = macro_leaf_view_.indexSet().index(macro_entity);\n    if (local_level > max_local_level(macro_entity))\n      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,\n                 \"macro_entity_index: \" << macro_entity_index << \"\\n\"\n                 << \"local_level: \" << local_level << \"\\n\"\n                 << \"max_local_level(macro_entity): \" << max_local_level(macro_entity));\n    auto& local_level_to_boundary_entity_ptrs_with_local_intersections = macro_entity_to_local_level_to_boundary_entity_ptrs_with_local_intersections_[macro_entity_index];\n    auto& boundary_entity_ptrs_with_local_intersections = local_level_to_boundary_entity_ptrs_with_local_intersections[local_level];\n//    logger.debug() << \"macro_entity: \" << macro_entity_index << std::endl;\n    if (boundary(macro_entity) && boundary_entity_ptrs_with_local_intersections.empty()) {\n      // create the container, therefore\n      const auto local_leaf_view = local_grids_[macro_entity_index]->leaf_view();\n      // * walk the local grid (manually, to have access to the entity pointer)\n      const auto local_entity_it_end = local_leaf_view.template end<0>();\n      for (auto local_entity_it = local_leaf_view.template begin<0>(); local_entity_it != local_entity_it_end; ++local_entity_it) {\n        const auto& local_entity = *local_entity_it;\n//        logger.debug() << \"local_entity: \" << local_leaf_view.indexSet().index(local_entity) << \" \";\n        if (local_entity.hasBoundaryIntersections()) {\n//          logger.debug() << \"(boundary entity)\" << std::endl;\n          std::vector<int> local_boundary_intersections;\n          // This entity has intersections on the local grid boundary, those could either be the domain boundary (which\n          // we are looking for) or a boundary to another local grid (which we are not looking for). To find out\n          // * walk the intersections\n          for (auto&& local_intersection : DSC::intersectionRange(local_leaf_view, local_entity)) {\n            if (local_intersection.boundary() && !local_intersection.neighbor()) {\n//              logger.debug() << \"local_intersection: \" << local_intersection.indexInInside() << \":\" << std::endl;\n              const auto local_intersection_geometry = local_intersection.geometry();\n              const size_t num_corners = boost::numeric_cast<size_t>(local_intersection_geometry.corners());\n              // ** Check if all corners of the intersection lie on the domain boundary (aka the boundary intersection of\n              //    the macro entity this local grid belongs to. Therefore\n              //    *** walk the intersections of the macro entity\n              for (auto&& macro_intersection : DSC::intersectionRange(macro_leaf_view_, macro_entity)) {\n                if (macro_intersection.boundary() && !macro_intersection.neighbor()) {\n                  // This macro intersection lies on the domain boundary, check if the local intersection is contained.\n                  size_t corners_lie_on_boundary = 0;\n                  for (size_t ii = 0; ii < num_corners; ++ii) {\n                    if (DSG::contains(macro_intersection, local_intersection_geometry.corner(boost::numeric_cast<int>(ii))))\n                      ++corners_lie_on_boundary;\n                  }\n                  if (corners_lie_on_boundary == num_corners) {\n                    // add the information to the container\n                    local_boundary_intersections.push_back(local_intersection.indexInInside());\n                  } // add the information to the container\n                }\n              } //    *** walk the intersections of the macro entity\n            }\n          } // * walk the intersections\n          if (!local_boundary_intersections.empty()) {\n            // add this local entity and its local intersections to the container\n            boundary_entity_ptrs_with_local_intersections.emplace_back(local_entity_it, local_boundary_intersections);\n          }\n        } /*else\n          logger.debug() << \"(inner entity)\" << std::endl;*/\n      } // * walk the local grid\n    } // create the container\n    return boundary_entity_ptrs_with_local_intersections;\n  } // ... local_boundary_entities(...)\n\n  template< class... Args >\n  void visualize(const std::string& filename = \"grid.multiscale.glued\",\n                 Args&& ...args)\n  {\n    auto logger = Stuff::Common::TimedLogger().get(\"grid-multiscale.glued.visualize\");\n    macro_grid_.visualize(filename + \".macro\", std::forward< Args >(args)...);\n    GluedVTKWriter<MacroGridType, LocalGridType> vtk_writer(*this);\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    std::vector<std::vector<double>> subdomain_visualization(macro_index_set.size(0));\n    std::vector<std::vector<double>> boundary_visualization(macro_index_set.size(0));\n    std::vector<std::vector<double>> inside_outside_coupling_visualization(macro_index_set.size(0));\n    std::vector<std::vector<double>> outside_inside_coupling_visualization(macro_index_set.size(0));\n    // walk the macro grid\n    for (auto&& macro_entity :\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                               elements\n#else\n                               DSC::entityRange\n#endif\n                                               (macro_leaf_view_)) {\n      const size_t macro_entity_index = macro_index_set.index(macro_entity);\n      logger.debug() << \"macro_entity: \" << macro_entity_index << \" \";\n      const auto local_level = max_local_level(macro_entity);\n      const auto local_grid_view = local_grids_[macro_entity_index]->level_view(local_level);\n      subdomain_visualization[macro_entity_index] = std::vector<double>(local_grid_view.indexSet().size(0),\n                                                                        macro_entity_index);\n      boundary_visualization[macro_entity_index] = std::vector<double>(local_grid_view.indexSet().size(0), -1);\n      if (inside_outside_coupling_visualization[macro_entity_index].empty())\n        inside_outside_coupling_visualization[macro_entity_index] = std::vector<double>(local_grid_view.indexSet().size(0), -1);\n      if (outside_inside_coupling_visualization[macro_entity_index].empty())\n        outside_inside_coupling_visualization[macro_entity_index] = std::vector<double>(local_grid_view.indexSet().size(0), -1);\n      // local boundary entities\n      if (boundary(macro_entity)) {\n        logger.debug() << \"(boundary entity)\" << std::endl;\n        const auto& boundary_entity_ptrs_with_local_intersections\n            = local_boundary_entities(macro_entity, local_level);\n        logger.debug() << \"  \" << boundary_entity_ptrs_with_local_intersections.size() << \"/\"\n                       << local_grid_view.indexSet().size(0) << \" boundary entities\" << std::endl;\n        for (const auto& element : boundary_entity_ptrs_with_local_intersections) {\n          const auto& local_entity_ptr = element.first;\n          const auto& local_intersections = element.second;\n          if (!local_intersections.empty()) {\n            const auto& local_entity = *local_entity_ptr;\n            const size_t local_entity_index = local_grid_view.indexSet().index(local_entity);\n            boundary_visualization[macro_entity_index][local_entity_index] = macro_entity_index;\n          }\n        }\n      } else\n        logger.debug() << \"(inner entity)\" << std::endl;\n      for (auto&& macro_intersection : DSC::intersectionRange(macro_leaf_view_, macro_entity)) {\n        if (!macro_intersection.boundary() && macro_intersection.neighbor()) {\n          const auto macro_neighbor_ptr = macro_intersection.outside();\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n          const auto& macro_neighbor = macro_neighbor_ptr;\n#else\n          const auto& macro_neighbor = *macro_neighbor_ptr;\n#endif\n          const size_t macro_neighbor_index = macro_leaf_view_.indexSet().index(macro_neighbor);\n          const auto local_neighbor_level = max_local_level(macro_neighbor);\n          const auto local_neighbor_grid_view = local_grids_[macro_neighbor_index]->level_view(local_neighbor_level);\n          if (inside_outside_coupling_visualization[macro_neighbor_index].empty())\n            inside_outside_coupling_visualization[macro_neighbor_index] = std::vector<double>(local_neighbor_grid_view.indexSet().size(0), -1);\n          if (outside_inside_coupling_visualization[macro_neighbor_index].empty())\n            outside_inside_coupling_visualization[macro_neighbor_index] = std::vector<double>(local_neighbor_grid_view.indexSet().size(0), -1);\n          // walk the coupling, where this is the inside\n          size_t num_coupling_intersections = 0;\n          const auto& in_out_coupling_glue = coupling(macro_entity, local_level, macro_neighbor, local_neighbor_level,\n                                                      /*allow_for_broken_orientation_of_coupling_intersections=*/true);\n          const auto in_out_coupling_intersection_it_end = in_out_coupling_glue.template iend<0>();\n          for (auto in_out_coupling_intersection_it = in_out_coupling_glue.template ibegin<0>();\n               in_out_coupling_intersection_it != in_out_coupling_intersection_it_end;\n               ++in_out_coupling_intersection_it) {\n            ++num_coupling_intersections;\n            const auto& coupling_intersection = *in_out_coupling_intersection_it;\n            const auto local_entity_ptr = coupling_intersection.inside();\n            const auto& local_entity = *local_entity_ptr;\n            const size_t local_entity_index = local_grid_view.indexSet().index(local_entity);\n            inside_outside_coupling_visualization[macro_entity_index][local_entity_index] = macro_entity_index;\n            const auto local_neighbor_ptr = coupling_intersection.outside();\n            const auto& local_neighbor = *local_neighbor_ptr;\n            const size_t local_neighbor_index = local_neighbor_grid_view.indexSet().index(local_neighbor);\n            inside_outside_coupling_visualization[macro_neighbor_index][local_neighbor_index] = macro_neighbor_index;\n          }\n          // walk the coupling, where this is the outside\n          size_t out_in_num_coupling_intersections = 0;\n          const auto& out_in_coupling_glue = coupling(macro_neighbor, local_neighbor_level, macro_entity, local_level,\n                                                      /*allow_for_broken_orientation_of_coupling_intersections=*/true);\n          const auto out_in_coupling_intersection_it_end = out_in_coupling_glue.template iend<0>();\n          for (auto out_in_coupling_intersection_it = out_in_coupling_glue.template ibegin<0>();\n               out_in_coupling_intersection_it != out_in_coupling_intersection_it_end;\n               ++out_in_coupling_intersection_it) {\n            ++out_in_num_coupling_intersections;\n            const auto& coupling_intersection = *out_in_coupling_intersection_it;\n            const auto local_entity_ptr = coupling_intersection.inside();\n            const auto& local_entity = *local_entity_ptr;\n            const size_t local_entity_index = local_grid_view.indexSet().index(local_entity);\n            outside_inside_coupling_visualization[macro_neighbor_index][local_entity_index] = macro_neighbor_index;\n            const auto local_neighbor_ptr = coupling_intersection.outside();\n            const auto& local_neighbor = *local_neighbor_ptr;\n            const size_t local_neighbor_index = local_neighbor_grid_view.indexSet().index(local_neighbor);\n            outside_inside_coupling_visualization[macro_entity_index][local_neighbor_index] = macro_entity_index;\n          }\n          if (num_coupling_intersections != out_in_num_coupling_intersections)\n            DUNE_THROW(Stuff::Exceptions::internal_error,\n                       \"The coupling glue is broken!\\n\"\n                       << \"macro entity (local level):   \" << macro_entity_index << \" (\" << local_level << \")\\n\"\n                       << \"macro neighbor (local level): \" << macro_neighbor_index << \" (\" << local_neighbor_level\n                       << \")\");\n          logger.debug() << \"  \" << num_coupling_intersections << \" coupling intersections with neighbor \" << macro_neighbor_index << std::endl;\n        }\n      }\n    } // walk the macro grid\n    vtk_writer.addCellData(subdomain_visualization, \"subdomains\");\n    vtk_writer.addCellData(boundary_visualization, \"local boundary entities\");\n    vtk_writer.addCellData(inside_outside_coupling_visualization, \"local coupling entities (inside/outside)\");\n    vtk_writer.addCellData(outside_inside_coupling_visualization, \"local coupling entities (outside/inside)\");\n    vtk_writer.write(filename, VTK::appendedraw);\n  } // ... visualize(...)\n\nprivate:\n  template <class MacroEntityType>\n  static std::shared_ptr<LocalGridProviderType> create_grid_of_simplex(const MacroEntityType& macro_entity)\n  {\n    try {\n      GridFactory<LocalGridType> subdomain_factory;\n      const auto num_vertices = macro_entity.\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n\n                                             subEntities(dimDomain);\n#else\n                                             template count<dimDomain>();\n#endif\n      std::vector<unsigned int> vertex_ids(num_vertices, 0);\n      for (int local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {\n        const auto vertex = macro_entity.template subEntity<dimDomain>(local_vertex_id)\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                                                                                       .\n#else\n                                                                                       ->\n#endif\n                                                                                         geometry().center();\n        subdomain_factory.insertVertex(vertex);\n        vertex_ids[local_vertex_id] = local_vertex_id;\n      }\n      subdomain_factory.insertElement(macro_entity.geometry().type(), vertex_ids);\n      return std::make_shared<Stuff::Grid::Providers::Default<LocalGridType>>(subdomain_factory.createGrid());\n    } catch (GridError& ee) {\n      DUNE_THROW(GridError,\n                 \"It was not possible to create a grid for this simplex with the given GridType!\\n\\n\"\n                     << \"GridType: \"\n                     << Stuff::Common::Typename<LocalGridType>::value()\n                     << \"\\n\\n\"\n                     << \"This was the original error: \"\n                     << ee.what());\n    }\n  } // ... create_grid_of_simplex(...)\n\n  template <class MacroEntityType>\n  static std::shared_ptr<LocalGridProviderType> create_grid_of_cube(const MacroEntityType& macro_entity)\n  {\n    const auto num_vertices = macro_entity.\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n\n                                           subEntities(dimDomain);\n#else\n                                           template count<dimDomain>();\n#endif\n    FieldVector<ctype, dimDomain> lower_left(std::numeric_limits<ctype>::max());\n    FieldVector<ctype, dimDomain> upper_right(std::numeric_limits<ctype>::min());\n    for (int local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {\n      const auto vertex = macro_entity.template subEntity<dimDomain>(local_vertex_id)\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                                                                                     .\n#else\n                                                                                     ->\n#endif\n                                                                                       geometry().center();\n      for (size_t dd = 0; dd < dimDomain; ++dd) {\n        lower_left[dd]  = std::min(lower_left[dd], vertex[dd]);\n        upper_right[dd] = std::max(upper_right[dd], vertex[dd]);\n      }\n    }\n    return std::make_shared<Stuff::Grid::Providers::Cube<LocalGridType>>(lower_left, upper_right, 1);\n  } // ... create_grid_of_cube(...)\n\n  void setup_local_grids()\n  {\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    for (auto&& macro_entity :\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                               elements\n#else\n                               DSC::entityRange\n#endif\n                                               (macro_leaf_view_)) {\n      auto macro_entity_index = macro_index_set.index(macro_entity);\n      if (macro_entity.type().isSimplex())\n        local_grids_[macro_entity_index] = create_grid_of_simplex(macro_entity);\n      else if (macro_entity.type().isCube())\n        local_grids_[macro_entity_index] = create_grid_of_cube(macro_entity);\n      else\n        DUNE_THROW(GridError, \"Unknown entity.type() encountered: \" << macro_entity.type());\n    }\n  } // ... setup_local_grids()\n\n  template <class MacroIntersectionType>\n  std::shared_ptr<GlueType> create_glue(const MacroEntityType& macro_entity, const MacroEntityType& macro_neighbor,\n                                        const MacroIntersectionType& macro_intersection, const int local_entity_level,\n                                        const int local_neighbor_level) const\n  {\n    assert(local_entity_level >= 0);\n    assert(local_neighbor_level >= 0);\n    const auto& local_entity_grid   = local_grid(macro_entity);\n    const auto& local_neighbor_grid = local_grid(macro_neighbor);\n    assert(local_entity_level <= local_entity_grid.grid().maxLevel());\n    assert(local_neighbor_level <= local_neighbor_grid.grid().maxLevel());\n    auto local_entity_view   = local_entity_grid.level_view(local_entity_level);\n    auto local_neighbor_view = local_neighbor_grid.level_view(local_neighbor_level);\n    // create descriptors, these can be discarded after creating the extractors\n    auto entity_descriptor   = create_descriptor(local_entity_view, macro_intersection);\n    auto neighbor_descriptor = create_descriptor(local_neighbor_view, macro_intersection);\n    // create extractors and merger as shared_ptr, so glue will handle memory\n    auto entity_extractor   = std::make_shared<LocalExtractorType>(local_entity_view, entity_descriptor);\n    auto neighbor_extractor = std::make_shared<LocalExtractorType>(local_neighbor_view, neighbor_descriptor);\n    auto contact_merger     = std::make_shared<GridGlue::ContactMerge<dimWorld, ctype>>(allowed_overlap_);\n    // create glue\n    auto glue = std::make_shared<GlueType>(entity_extractor, neighbor_extractor, contact_merger);\n    glue->build();\n    if (glue->size() == 0)\n      DUNE_THROW(GridError, // clang-format off\n                 \"Something went wrong, the coupling glue is empty!\\n\"\n                     << \"   macro_entity \"         << macro_leaf_view_.indexSet().index(macro_entity) << \"\\n\"\n                     << \"   local_entity_level \"   << local_entity_level << \"\\n\"\n                     << \"   macro_neighbor \"       << macro_leaf_view_.indexSet().index(macro_neighbor) << \"\\n\"\n                     << \"   local_neighbor_level \" << local_neighbor_level << \"\\n\"); // clang-format on\n    return glue;\n  } // ... create_glue(...)\n\n  void setup_glues(const bool allow_for_broken_orientation_of_coupling_intersections = false)\n  {\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    for (auto&& macro_entity :\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                               elements\n#else\n                               DSC::entityRange\n#endif\n                                               (macro_leaf_view_)) {\n      const auto macro_entity_index = macro_index_set.index(macro_entity);\n      auto& entity_glues            = glues_[macro_entity_index];\n      // walk the neighbors ...\n      const auto macro_intersection_it_end = macro_leaf_view_.iend(macro_entity);\n      for (auto macro_intersection_it = macro_leaf_view_.ibegin(macro_entity);\n           macro_intersection_it != macro_intersection_it_end;\n           ++macro_intersection_it) {\n        const auto& macro_intersection = *macro_intersection_it;\n        if (macro_intersection.neighbor() && !macro_intersection.boundary()) {\n          const auto macro_neighbor_ptr   = macro_intersection.outside();\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n          const auto& macro_neighbor      = macro_neighbor_ptr;\n#else\n          const auto& macro_neighbor      = *macro_neighbor_ptr;\n#endif\n          const auto macro_neighbor_index = macro_index_set.index(macro_neighbor);\n          for (auto local_entity_level : DSC::valueRange(local_grids_[macro_entity_index]->grid().maxLevel() + 1))\n            for (auto local_neighbor_level : DSC::valueRange(local_grids_[macro_neighbor_index]->grid().maxLevel() + 1)) {\n              auto glue = create_glue(macro_entity, macro_neighbor,\n                                      macro_intersection,\n                                      local_entity_level, local_neighbor_level);\n              if (!allow_for_broken_orientation_of_coupling_intersections) {\n                const size_t brocken_intersections = check_for_broken_coupling_intersections(*glue);\n                if (brocken_intersections > 0)\n                  DUNE_THROW(Exceptions::intersection_orientation_is_broken,\n                             \"The coupling glue between the grid views of\\n\"\n                             << \"  level \" << local_entity_level << \" on macro entity   \"\n                             << macro_leaf_view_.indexSet().index(macro_entity) << \" and\\n\"\n                             << \"  level \" << local_neighbor_level << \" on macro neighbor \"\n                             << macro_leaf_view_.indexSet().index(macro_neighbor) << \"\\n\"\n                             << \"contains\\n\"\n                             << \"  \" << brocken_intersections << \"/\" << glue->size() << \" intersections with wrong\"\n                             << \"orientation!\");\n              }\n              entity_glues[macro_neighbor_index][local_entity_level][local_neighbor_level] = glue;\n            }\n        }\n      } // ... walk the neighbors\n    }\n  } // ... setup_glues(...)\n\n  void prepare_global_grid()\n  {\n    if (global_grid_)\n      return;\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    std::vector<FieldVector<ctype, dimDomain>> vertices;\n    std::vector<std::vector<std::vector<unsigned int>>> entity_to_vertex_ids(local_grids_.size());\n    std::vector<std::vector<GeometryType>> geometry_types(local_grids_.size());\n    // walk the grid for the first time\n    for (auto&& macro_entity :\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                               elements\n#else\n                               DSC::entityRange\n#endif\n                                               (macro_leaf_view_)) {\n      const auto local_leaf_view = local_grid(macro_entity).leaf_view();\n      const auto& local_index_set = local_leaf_view.indexSet();\n      const size_t macro_index = macro_index_set.index(macro_entity);\n      entity_to_vertex_ids[macro_index] = std::vector<std::vector<unsigned int>>(local_index_set.size(0));\n      geometry_types[macro_index] = std::vector<GeometryType>(local_index_set.size(0));\n      for (auto&& micro_entity :\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                                 elements\n#else\n                                 DSC::entityRange\n#endif\n                                                 (local_leaf_view)) {\n        const size_t micro_index = local_index_set.index(micro_entity);\n        const auto num_vertices = micro_entity.\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n\n                                                subEntities(dimDomain);\n#else\n                                                template count<dimDomain>();\n#endif\n        entity_to_vertex_ids[macro_index][micro_index] = std::vector<unsigned int>(num_vertices);\n        geometry_types[macro_index][micro_index] = micro_entity.geometry().type();\n        for (unsigned int local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {\n          const unsigned int global_vertex_id\n              = find_insert_vertex(vertices,\n                                   micro_entity.template subEntity<dimDomain>(local_vertex_id)\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                                                                                              .\n#else\n                                                                                              ->\n#endif\n                                                                                                geometry().center());\n          entity_to_vertex_ids[macro_index][micro_index][local_vertex_id] = global_vertex_id;\n        }\n      } // walk the local grid\n    } // walk the macro grid\n    GridFactory<LocalGridType> global_factory;\n    for (const auto& vertex : vertices)\n      global_factory.insertVertex(vertex);\n    size_t II = 0;\n    size_t JJ = 0;\n    try {\n      for (size_t ii = 0; ii < local_grids_.size(); ++ii, II = ii)\n        for (size_t jj = 0; jj < entity_to_vertex_ids[ii].size(); ++jj, JJ = jj)\n            global_factory.insertElement(geometry_types[ii][jj], entity_to_vertex_ids[ii][jj]);\n    } catch (GridError& ee) {\n      DUNE_THROW(GridError,\n                 \"It was not possible to insert an element into the grid factory!\\n\\n\"\n                 << \"GridType: \" << Stuff::Common::Typename<LocalGridType>::value() << \"\\n\"\n                 << \"GeometryType: \" << geometry_types[II][JJ] << \"\\n\"\n                 << \"\\n\"\n                 << \"This was the original error: \" << ee.what());\n    } // try\n    global_grid_ = DSC::make_unique<Stuff::Grid::Providers::Default<LocalGridType>>(global_factory.createGrid());\n\n    // build maps of indices, relating the local to the global grid\n    const auto global_grid_view = global_grid_->leaf_view();\n    local_to_global_indices_ = DSC::make_unique<std::vector<std::vector<size_t>>>(macro_leaf_view_.indexSet().size(0));\n    auto& local_to_global_indices = *local_to_global_indices_;\n    global_to_local_indices_ = DSC::make_unique<std::vector<std::pair<size_t, size_t>>>(global_grid_view.indexSet().size(0));\n    auto& global_to_local_indices = *global_to_local_indices_;\n    // therefore\n    // * create a search on the global view: if all is fine, we only need to walk that one once\n    std::vector<FieldVector<ctype, dimDomain>> local_entity_center{FieldVector<ctype, dimDomain>(0.0)};\n    auto global_search = DSG::make_entity_in_level_search(global_grid_view);\n    // * walk the macro grid\n    for (auto&& macro_entity :\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                               elements\n#else\n                               DSC::entityRange\n#endif\n                                               (macro_leaf_view_)) {\n      const size_t subdomain = macro_leaf_view_.indexSet().index(macro_entity);\n      const auto local_leaf_view = local_grid(macro_entity).leaf_view();\n      const auto& local_index_set = local_leaf_view.indexSet();\n      local_to_global_indices[subdomain] = std::vector<size_t>(local_index_set.size(0));\n      // * walk the local grid\n      for (auto&& local_entity :\n#if DUNE_VERSION_NEWER(DUNE_GRID, 2, 4)\n                                 elements\n#else\n                                 DSC::entityRange\n#endif\n                                                 (local_leaf_view)) {\n        const size_t local_entity_index = local_index_set.index(local_entity);\n        local_entity_center[0] = local_entity.geometry().center();\n        const auto global_entity_ptr_unique_ptrs = global_search(local_entity_center);\n        // the search has to be successfull, since the global grid has been constructed to exactly contain each local entity\n        assert(global_entity_ptr_unique_ptrs.size() == 1);\n        const auto& global_entity_ptr_unique_ptr = global_entity_ptr_unique_ptrs.at(0);\n        assert(global_entity_ptr_unique_ptr);\n        const auto& global_entity_ptr = *global_entity_ptr_unique_ptr;\n        const auto& global_entity = *global_entity_ptr;\n        const size_t global_entity_index = global_grid_view.indexSet().index(global_entity);\n        // store information\n        local_to_global_indices[subdomain][local_entity_index] = global_entity_index;\n        global_to_local_indices[global_entity_index] = {subdomain, local_entity_index};\n      } // * walk the local grid\n    } // * walk the macro grid\n\n  } // ... prepare_global_grid(...)\n\n  size_t find_insert_vertex(std::vector<FieldVector<ctype, dimDomain>>& vertices,\n                            FieldVector<ctype, dimDomain>&& vertex) const\n  {\n    // check if vertex is already contained\n    for (size_t ii = 0; ii < vertices.size(); ++ii)\n      if (DSC::FloatCmp::eq(vertex, vertices[ii]))\n        return ii;\n    // if not, add it\n    vertices.emplace_back(std::move(vertex));\n    return vertices.size() - 1;\n  } // ... find_insert_vertex(...)\n\n  MacroGridProviderType& macro_grid_;\n  const ctype allowed_overlap_;\n  MacroGridViewType macro_leaf_view_;\n  std::vector<std::shared_ptr<LocalGridProviderType>> local_grids_;\n  std::vector<std::map<size_t, std::map<int, std::map<int, std::shared_ptr<GlueType>>>>> glues_;\n  std::map<size_t, std::map<int, std::vector<std::pair<MicroEntityPointerType, std::vector<int>>>>>\n      macro_entity_to_local_level_to_boundary_entity_ptrs_with_local_intersections_;\n  std::unique_ptr<LocalGridProviderType> global_grid_;\n  std::unique_ptr<std::vector<std::vector<size_t>>> local_to_global_indices_;\n  std::unique_ptr<std::vector<std::pair<size_t, size_t>>> global_to_local_indices_;\n}; // class Glued\n\n\ntemplate <class MacroGridType, class LocalGridType>\nclass GluedVTKWriter\n{\n  typedef typename LocalGridType::LevelGridView LocalGridViewType;\n\n  // we only need this class to access a protected pwrite method of VTKWriter\n  class LocalVTKWriter\n    : public VTKWriter<LocalGridViewType>\n  {\n    typedef VTKWriter<LocalGridViewType> BaseType;\n  public:\n    LocalVTKWriter(const LocalGridViewType& local_grid_view, const size_t subdomain, const size_t num_subdomains)\n      : BaseType(local_grid_view)\n      , commRank_(boost::numeric_cast<int>(subdomain))\n      , commSize_(boost::numeric_cast<int>(num_subdomains))\n    {}\n\n    void write_locally(const std::string& name, VTK::OutputType ot)\n    {\n      BaseType::pwrite(name, \"\", \"\", ot, commRank_, commSize_);\n    }\n\n  private:\n    const int commRank_;\n    const int commSize_;\n  }; // class LocalVTKWriter\n\npublic:\n  typedef Glued<MacroGridType, LocalGridType> GluedGridType;\n\n  GluedVTKWriter(const GluedGridType& glued_grid, const int local_level = -1)\n    : glued_grid_(glued_grid)\n    , local_levels_(glued_grid_.num_subdomains(), -1)\n  {\n    // set each local level to its respective max\n    if (local_level < 0)\n      for (auto&& macro_entity : DSC::entityRange(glued_grid_.macro_grid_view()))\n        local_levels_[glued_grid_.subdomain(macro_entity)] = glued_grid_.max_local_level(macro_entity);\n    prepare_local_vtk_writers();\n  } // GluedVTKWriter(...)\n\n  GluedVTKWriter(const GluedGridType& glued_grid, const std::vector<int>& local_levels)\n    : glued_grid_(glued_grid)\n    , local_levels_(local_levels)\n  {\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      if (local_levels_[ss] < 0)\n        local_levels_[ss] = glued_grid_.max_local_level(ss);\n    prepare_local_vtk_writers();\n  }\n\n  template <class V>\n  void addCellData(const std::vector<std::vector<V>>& vectors, const std::string& name, const int ncomps = 1)\n  {\n    if (vectors.size() != glued_grid_.num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::shapes_do_not_match,\n                 \"vectors.size(): \" << vectors.size() << \"\\n\"\n                 << \"glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addCellData(vectors[ss], name, ncomps);\n  } // ... addCellData(...)\n\n  template <class VTKFunctionType>\n  void addCellData(const std::vector<std::shared_ptr<VTKFunctionType>>& functions)\n  {\n    if (functions.size() != glued_grid_.num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::shapes_do_not_match,\n                 \"funcitons.size(): \" << functions.size() << \"\\n\"\n                 << \"glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addCellData(functions[ss]);\n  } // ... addCellData(...)\n\n  template <class V>\n  void addVertexData(const std::vector<std::vector<V>>& vectors, const std::string& name, const int ncomps = 1)\n  {\n    if (vectors.size() != glued_grid_.num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::shapes_do_not_match,\n                 \"vectors.size(): \" << vectors.size() << \"\\n\"\n                 << \"glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addVertexData(vectors[ss], name, ncomps);\n  } // ... addVertexData(...)\n\n  template <class VTKFunctionType>\n  void addVertexData(const std::vector<std::shared_ptr<VTKFunctionType>>& functions)\n  {\n    if (functions.size() != glued_grid_.num_subdomains())\n      DUNE_THROW(Stuff::Exceptions::shapes_do_not_match,\n                 \"funcitons.size(): \" << functions.size() << \"\\n\"\n                 << \"glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addVertexData(functions[ss]);\n  } // ... addVertexData(...)\n\n  void clear()\n  {\n    for (auto& local_vtk_writer : local_vtk_writers_)\n      local_vtk_writer.clear();\n  }\n\n  void write(const std::string& name, VTK::OutputType type = VTK::ascii)\n  {\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->write_locally(name, type);\n  }\n\nprivate:\n  void prepare_local_vtk_writers()\n  {\n    for (auto&& macro_entity : DSC::entityRange(glued_grid_.macro_grid_view())) {\n      const size_t subdomain = glued_grid_.subdomain(macro_entity);\n      local_vtk_writers_.emplace_back(\n            new LocalVTKWriter(glued_grid_.local_grid(macro_entity).level_view(local_levels_[subdomain]),\n                               subdomain,\n                               glued_grid_.num_subdomains()));\n    }\n  } // ... prepare_local_vtk_writers(...)\n\n  const GluedGridType& glued_grid_;\n  std::vector<int> local_levels_;\n  std::vector<std::unique_ptr<LocalVTKWriter>> local_vtk_writers_;\n}; // class GluedVTKWriter\n\n\n} // namespace Multiscale\n} // namespace grid\n} // namespace Dune\n\n#endif // DUNE_GRID_MULTISCALE_GLUED_HH\n", "meta": {"hexsha": "555e0d43d0c057cc67dd11c9506bc69b4a72017e", "size": 53758, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/grid/multiscale/glued.hh", "max_stars_repo_name": "pymor/dune-grid-multiscale", "max_stars_repo_head_hexsha": "cda095af3c472fb173717239527741439f5c0af6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T13:50:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-12T13:50:01.000Z", "max_issues_repo_path": "dune/grid/multiscale/glued.hh", "max_issues_repo_name": "dune-community/dune-grid-multiscale", "max_issues_repo_head_hexsha": "cda095af3c472fb173717239527741439f5c0af6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-09T08:05:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-28T11:57:35.000Z", "max_forks_repo_path": "dune/grid/multiscale/glued.hh", "max_forks_repo_name": "pymor/dune-grid-multiscale", "max_forks_repo_head_hexsha": "cda095af3c472fb173717239527741439f5c0af6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T04:10:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:10:49.000Z", "avg_line_length": 50.7150943396, "max_line_length": 171, "alphanum_fraction": 0.6725138584, "num_tokens": 11771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149845400438, "lm_q2_score": 0.04468087329388052, "lm_q1q2_score": 0.013145782445394712}}
{"text": "/* Software License Agreement (BSD License)\n *\n * Copyright (c) 2014, Ross Linscott (rossklin@gmail.com)\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *     Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in\n *     the documentation and/or other materials provided with the\n *     distribution.\n *\n *     The names of its contributors may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#if defined(NDEBUG)\n#undef NDEBUG\n#endif\n\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#ifdef STANDALONE\n#include <RInside.h>\n#endif\n\n#include \"../inst/include/SimpleSDESampler.h\"\n\n//' LPoly system constructor\n//'\n//' Returns an XPtr to an lpoly_system_type object\n//' @param cm Model coefficient matrix\n//' @param trm Model term specification, as generated by lpoly_model_spec (each row represents the powers of the different factors in a term)\n//' @export\n// [[Rcpp::export]]\nXPtr<lpoly_system_type> lpoly_make_system_xptr(NumericMatrix cm, NumericMatrix trm){\n\n  if (cm.ncol() != trm.nrow()){\n    Rcpp::Rcout << \"lpoly_make_system: dimension mismatch: \" << cm.ncol() << \" != \" << trm.nrow() << endl;\n    exit(-1);\n  }\n\n  return XPtr<lpoly_system_type>(new lpoly_system_type(lpoly_evaluator(cm,trm), lpoly_jacobian(cm, trm)), true);\n}\n\n//' LPoly model matrix generator\n//'\n//' Builds the model matrix from the data using the lpoly_system_type object\n//' @param lps XPtr to an lpoly_system_type object created by a call to lpoly_make_system\n//' @param data One column per measurement variable\n//' @export\n// [[Rcpp::export]]\nNumericMatrix lpoly_model_matrix(XPtr<lpoly_system_type> lps, NumericMatrix data){\n  return lps -> first.build(data);\n}\n\n//' LPoly Jacobian\n//'\n//' Builds the model matrix from the data using the lpoly_system_type object\n//' @param lps XPtr to an lpoly_system_type object created by a call to lpoly_make_system\n//' @param state Single row matrix\n//' @export\n// [[Rcpp::export]]\nNumericMatrix lpoly_compute_jacobian(XPtr<lpoly_system_type> lps, NumericMatrix state){\n  uvector q(state.ncol());\n  umatrix res;\n  memcpy(&q(0), &state[0], q.size() * sizeof(double));\n  lps -> second(q, res, 0);\n  return as_r_matrix(res);\n}\n\n\n//' LPoly System Implicit SDE Simulator using NLOPT\n//'\n//' Simulates a trajectory to the SDE specified by *sys* and the noise level sigma, starting at the point start and integrating over times [*from*,*to*] on *steps + 1* time points.\n//' @param sys lpoly_system_type XPtr object created with lpoly_make_system\n//' @param sigma Amplitude of noise: scalar\n//' @param start Initial position: n vector\n//' @param from Initial time: scalar\n//' @param to Final time: scalar\n//' @param steps Number of points to take, s.t. dt = (from - to) / (steps + 1): integer\n//' @export\n// [[Rcpp::export]]\nNumericMatrix lpoly_sde(XPtr<lpoly_system_type> sys\n\t\t\t, double sigma\n\t\t\t, NumericVector start\n\t\t\t, double from, double to, int steps \n\t\t\t, double x_tol = 0\n\t\t\t, const char* algorithm = \"LBFGS\") {\n\n  const double dt = (to - from)/steps;\n  lpoly_system s(sys);\n  nlopt_stepper stepper(&s, dt, start.size(), sigma, steps, x_tol, algorithm);\n\n  return lpoly_sde(stepper, start, from, to, steps, x_tol, algorithm);\n}\n\n\n//' LPoly System Implicit SDE Simulator using NLOPT, with precached noise data\n//'\n//' Simulates a trajectory to the SDE specified by *sys* and the noise level sigma, starting at the point start and integrating over times [*from*,*to*] on *steps + 1* time points.\n//' @param sys lpoly_system_type XPtr object created with lpoly_make_system\n//' @param noise Noise buffer (brownian motion normalised steps ~N(0,sigma^2))\n//' @param start Initial position: n vector\n//' @param from Initial time: scalar\n//' @param to Final time: scalar\n//' @param steps Number of points to take, s.t. dt = (from - to) / (steps + 1): integer\n//' @export\n// [[Rcpp::export]]\nNumericMatrix lpoly_sde_precached(XPtr<lpoly_system_type> sys\n\t\t\t\t  , NumericMatrix noise\n\t\t\t\t  , NumericVector start\n\t\t\t\t  , double from\n\t\t\t\t  , double to\n\t\t\t\t  , int steps \n\t\t\t\t  , double x_tol = 0\n\t\t\t\t  , const char* algorithm = \"LBFGS\") {\n\n  const double dt = (to - from)/steps;\n  lpoly_system s(sys);\n  nlopt_stepper stepper(&s, dt, start.size(), as_ublas_matrix(noise), x_tol, algorithm);\n\n  return lpoly_sde(stepper, start, from, to, steps, x_tol, algorithm);\n}\n\n//' LPoly System Implicit SDE Simulator: time-wise averages\n//'\n//' Samples multiple times from lpoly_sde and returns the time-wise average\n//' @param nrep Number of repetitions to average over: integer\n//' @param sys lpoly_system_type XPtr object created with lpoly_make_system\n//' @param sigma Amplitude of noise: scalar\n//' @param start Initial position: n vector\n//' @param from Initial time: scalar\n//' @param to Final time: scalar\n//' @param steps Number of points to take, s.t. dt = (from - to) / (steps + 1): integer\n//' @export\n// [[Rcpp::export]]\nNumericMatrix lpoly_sde_averages( int nrep\n\t\t\t\t  , XPtr<lpoly_system_type> sys\n\t\t\t\t  , double sigma\n\t\t\t\t  , NumericVector start\n\t\t\t\t  , double from, double to, int steps){\n  \n  NumericMatrix result(steps+1, start.size());\n  NumericMatrix buf;\n  int i,j;\n  double *p, *q;\n  int smax = result.nrow() * result.ncol();\n\n  p = &result(0,0);\n\n  memset(p, 0, smax * sizeof(double));\n  \n  for (i = 0; i < nrep; i++){\n    buf = lpoly_sde( sys\n\t\t     , sigma\n\t\t     , start\n\t\t     , from\n\t\t     , to\n\t\t     , steps);\n\n    q = &buf(0,0);\n    for (j = 0; j < smax; j++){\n      p[j] += q[j];\n    }\n  }\n\n  for (j = 0; j < smax; j++){\n    p[j] /= nrep;\n  }\n\n  return result;\n} \n", "meta": {"hexsha": "8088e0055fb7e465f597868ce7ec6d3be8ba71c4", "size": 6898, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lpoly_exports.cc", "max_stars_repo_name": "rossklin/SimpleSDESampler", "max_stars_repo_head_hexsha": "bb45a818f2ee38065f41a2fa222207172eb61007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lpoly_exports.cc", "max_issues_repo_name": "rossklin/SimpleSDESampler", "max_issues_repo_head_hexsha": "bb45a818f2ee38065f41a2fa222207172eb61007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lpoly_exports.cc", "max_forks_repo_name": "rossklin/SimpleSDESampler", "max_forks_repo_head_hexsha": "bb45a818f2ee38065f41a2fa222207172eb61007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0152284264, "max_line_length": 180, "alphanum_fraction": 0.7039721658, "num_tokens": 1807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.029760091471954672, "lm_q1q2_score": 0.013144229049272411}}
{"text": "#ifndef STATIC_RTREE_HPP\n#define STATIC_RTREE_HPP\n\n#include \"storage/io.hpp\"\n#include \"util/bearing.hpp\"\n#include \"util/coordinate_calculation.hpp\"\n#include \"util/deallocating_vector.hpp\"\n#include \"util/exception.hpp\"\n#include \"util/hilbert_value.hpp\"\n#include \"util/integer_range.hpp\"\n#include \"util/mmap_file.hpp\"\n#include \"util/rectangle.hpp\"\n#include \"util/typedefs.hpp\"\n#include \"util/vector_view.hpp\"\n#include \"util/web_mercator.hpp\"\n\n#include \"osrm/coordinate.hpp\"\n\n#include \"storage/shared_memory_ownership.hpp\"\n\n#include <boost/assert.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n#include <boost/iostreams/device/mapped_file.hpp>\n\n#include <tbb/blocked_range.h>\n#include <tbb/parallel_for.h>\n#include <tbb/parallel_sort.h>\n\n#include <algorithm>\n#include <array>\n#include <limits>\n#include <memory>\n#include <queue>\n#include <string>\n#include <vector>\n\n// An extended alignment is implementation-defined, so use compiler attributes\n// until alignas(LEAF_PAGE_SIZE) is compiler-independent.\n#if defined(_MSC_VER)\n#define ALIGNED(x) __declspec(align(x))\n#elif defined(__GNUC__)\n#define ALIGNED(x) __attribute__((aligned(x)))\n#else\n#define ALIGNED(x)\n#endif\n\nnamespace osrm\n{\nnamespace util\n{\n\n/***\n * Static RTree for serving nearest neighbour queries\n * // All coordinates are pojected first to Web Mercator before the bounding boxes\n * // are computed, this means the internal distance metric doesn not represent meters!\n */\n\ntemplate <class EdgeDataT,\n          storage::Ownership Ownership = storage::Ownership::Container,\n          std::uint32_t BRANCHING_FACTOR = 64,\n          std::uint32_t LEAF_PAGE_SIZE = 4096>\nclass StaticRTree\n{\n    /**********************************************************\n     * Example RTree construction:\n     *\n     * 30 elements (EdgeDataT objects)\n     * LEAF_NODE_SIZE = 3\n     * BRANCHING_FACTOR = 2\n     *\n     * 012 345 678 901 234 567 890 123 456 789  <- EdgeDataT objects in .fileIndex data, sorted by\n     * \\|/ \\|/ \\|/ \\|/ \\|/ \\|/ \\|/ \\|/ \\|/ \\|/     Hilbert Code of the centroid coordinate\n     * A   B   C   D   E   F   G   H   I   J   <- Everything from here down is a Rectangle in\n     * \\ /     \\ /     \\ /     \\ /     \\ /        .ramIndex\n     *  K       L       M       N       O\n     *   \\     /         \\     /       /\n     *    \\   /           \\   /       /\n     *     \\ /             \\ /       /\n     *      P               Q       R\n     *       \\             /       /\n     *        \\           /       /\n     *         \\         /       /\n     *          \\       /       /\n     *           \\     /       /\n     *            \\   /       /\n     *             \\ /       /\n     *              U       V\n     *               \\     /\n     *                \\   /\n     *                 \\ /\n     *                  W\n     *\n     * Step 1 - objects 01234567... are sorted by Hilbert code (these are the line\n     *          segments of the OSM roads)\n     * Step 2 - we grab LEAF_NODE_SIZE of them at a time and create TreeNode A with a\n     *          bounding-box that surrounds the first LEAF_NODE_SIZE objects\n     * Step 2a- continue grabbing LEAF_NODE_SIZE objects, creating TreeNodes B,C,D,E...J\n     *          until we run out of objects.  The last TreeNode J may not have\n     *          LEAF_NODE_SIZE entries.  Our math later on caters for this.\n     * Step 3 - Now start grabbing nodes from A..J in groups of BRANCHING_FACTOR,\n     *          and create K..O with bounding boxes surrounding the groups of\n     *          BRANCHING_FACTOR.  Again, O, the last entry, may have fewer than\n     *          BRANCHING_FACTOR entries.\n     * Step 3a- Repeat this process for each level, until you only create 1 TreeNode\n     *          to contain its children (in this case, W).\n     *\n     * As we create TreeNodes, we append them to the m_search_tree vector.\n     *\n     * After this part of the building process, m_search_tree will contain TreeNode\n     * objects in this order:\n     *\n     * ABCDEFGHIJ KLMNO PQR UV W\n     * 10         5     3   2  1  <- number of nodes in the level\n     *\n     * In order to make our math easy later on, we reverse the whole array,\n     * then reverse the nodes within each level:\n     *\n     *   Reversed:        W VU RQP ONMKL JIHGFEDCBA\n     *   Levels reversed: W UV PQR KLMNO ABCDEFGHIJ\n     *\n     * We also now have the following information:\n     *\n     *   level sizes = {1,2,3,5,10}\n     *\n     * and we can calculate the array position the nodes for each level\n     * start (based on the sum of the previous level sizes):\n     *\n     *   level starts = {0,1,3,6,11}\n     *\n     * Now, some basic math can be used to navigate around the tree.  See\n     * the body of the `child_indexes` function for the details.\n     *\n     ***********************************************/\n    template <typename T> using Vector = ViewOrVector<T, Ownership>;\n\n  public:\n    using Rectangle = RectangleInt2D;\n    using EdgeData = EdgeDataT;\n    using CoordinateList = Vector<util::Coordinate>;\n\n    static_assert(LEAF_PAGE_SIZE >= sizeof(EdgeDataT), \"page size is too small\");\n    static_assert(((LEAF_PAGE_SIZE - 1) & LEAF_PAGE_SIZE) == 0, \"page size is not a power of 2\");\n    static constexpr std::uint32_t LEAF_NODE_SIZE = (LEAF_PAGE_SIZE / sizeof(EdgeDataT));\n\n    struct CandidateSegment\n    {\n        Coordinate fixed_projected_coordinate;\n        EdgeDataT data;\n    };\n\n    /**\n     * Represents a node position somewhere in our tree.  This is purely a navigation\n     * class used to find children of each node - the actual data for each node\n     * is in the m_search_tree vector of TreeNode objects.\n     */\n    struct TreeIndex\n    {\n        TreeIndex() : level(0), offset(0) {}\n        TreeIndex(std::uint32_t level_, std::uint32_t offset_) : level(level_), offset(offset_) {}\n        std::uint32_t level;  // Which level of the tree is this node in\n        std::uint32_t offset; // Which node on this level is this (0=leftmost)\n    };\n\n    /**\n     * An actual node in the tree.  It's pretty minimal, we use the TreeIndex\n     * classes to navigate around.  The TreeNode is packed into m_search_tree\n     * in a specific order so we can calculate positions of children\n     * (see the children_indexes function)\n     */\n    struct TreeNode\n    {\n        Rectangle minimum_bounding_rectangle;\n    };\n\n  private:\n    /**\n     * A lightweight wrapper for the Hilbert Code for each EdgeDataT object\n     * A vector of these is used to sort the EdgeDataT input onto the\n     * Hilbert Curve.\n     * The sorting doesn't modify the original array, so this struct\n     * maintains a pointer to the original index position (m_original_index)\n     * so we can fetch the original data from the sorted position.\n     */\n    struct WrappedInputElement\n    {\n        explicit WrappedInputElement(const uint64_t _hilbert_value,\n                                     const std::uint32_t _original_index)\n            : m_hilbert_value(_hilbert_value), m_original_index(_original_index)\n        {\n        }\n\n        WrappedInputElement() : m_hilbert_value(0), m_original_index(UINT_MAX) {}\n\n        uint64_t m_hilbert_value;\n        std::uint32_t m_original_index;\n\n        inline bool operator<(const WrappedInputElement &other) const\n        {\n            return m_hilbert_value < other.m_hilbert_value;\n        }\n    };\n\n    struct QueryCandidate\n    {\n        QueryCandidate(std::uint64_t squared_min_dist, TreeIndex tree_index)\n            : squared_min_dist(squared_min_dist), tree_index(tree_index),\n              segment_index(std::numeric_limits<std::uint32_t>::max())\n        {\n        }\n\n        QueryCandidate(std::uint64_t squared_min_dist,\n                       TreeIndex tree_index,\n                       std::uint32_t segment_index,\n                       const Coordinate &coordinate)\n            : squared_min_dist(squared_min_dist), tree_index(tree_index),\n              fixed_projected_coordinate(coordinate), segment_index(segment_index)\n        {\n        }\n\n        inline bool is_segment() const\n        {\n            return segment_index != std::numeric_limits<std::uint32_t>::max();\n        }\n\n        inline bool operator<(const QueryCandidate &other) const\n        {\n            // Attn: this is reversed order. std::priority_queue is a\n            // max pq (biggest item at the front)!\n            return other.squared_min_dist < squared_min_dist;\n        }\n\n        std::uint64_t squared_min_dist;\n        TreeIndex tree_index;\n        Coordinate fixed_projected_coordinate;\n        std::uint32_t segment_index;\n    };\n\n    // We use a const view type when we don't own the data, otherwise\n    // we use a mutable type (usually becase we're building the tree)\n    using TreeViewType = typename std::conditional<Ownership == storage::Ownership::View,\n                                                   const Vector<const TreeNode>,\n                                                   Vector<TreeNode>>::type;\n    TreeViewType m_search_tree;\n\n    // Reference to the actual lon/lat data we need for doing math\n    const Vector<Coordinate> &m_coordinate_list;\n\n    // Holds the number of TreeNodes in each level.\n    // We always start with the root node, so\n    // m_tree_level_sizes[0] should always be 1\n    std::vector<std::uint64_t> m_tree_level_sizes;\n\n    // Holds the start indexes of each level in m_search_tree\n    std::vector<std::uint64_t> m_tree_level_starts;\n\n    // mmap'd .fileIndex file\n    boost::iostreams::mapped_file_source m_objects_region;\n    // This is a view of the EdgeDataT data mmap'd from the .fileIndex file\n    util::vector_view<const EdgeDataT> m_objects;\n\n  public:\n    StaticRTree(const StaticRTree &) = delete;\n    StaticRTree &operator=(const StaticRTree &) = delete;\n\n    // Construct a packed Hilbert-R-Tree with Kamel-Faloutsos algorithm [1]\n    explicit StaticRTree(const std::vector<EdgeDataT> &input_data_vector,\n                         const std::string &tree_node_filename,\n                         const std::string &leaf_node_filename,\n                         const Vector<Coordinate> &coordinate_list)\n        : m_coordinate_list(coordinate_list)\n    {\n        const auto element_count = input_data_vector.size();\n        std::vector<WrappedInputElement> input_wrapper_vector(element_count);\n\n        // Step 1 - create a vector of Hilbert Code/original position pairs\n        tbb::parallel_for(\n            tbb::blocked_range<uint64_t>(0, element_count),\n            [&input_data_vector, &input_wrapper_vector, this](\n                const tbb::blocked_range<uint64_t> &range) {\n                for (uint64_t element_counter = range.begin(), end = range.end();\n                     element_counter != end;\n                     ++element_counter)\n                {\n                    WrappedInputElement &current_wrapper = input_wrapper_vector[element_counter];\n                    current_wrapper.m_original_index = element_counter;\n\n                    EdgeDataT const &current_element = input_data_vector[element_counter];\n\n                    // Get Hilbert-Value for centroid in mercartor projection\n                    BOOST_ASSERT(current_element.u < m_coordinate_list.size());\n                    BOOST_ASSERT(current_element.v < m_coordinate_list.size());\n\n                    Coordinate current_centroid = coordinate_calculation::centroid(\n                        m_coordinate_list[current_element.u], m_coordinate_list[current_element.v]);\n                    current_centroid.lat = FixedLatitude{static_cast<std::int32_t>(\n                        COORDINATE_PRECISION *\n                        web_mercator::latToY(toFloating(current_centroid.lat)))};\n\n                    current_wrapper.m_hilbert_value = GetHilbertCode(current_centroid);\n                }\n            });\n\n        // sort the hilbert-value representatives\n        tbb::parallel_sort(input_wrapper_vector.begin(), input_wrapper_vector.end());\n        {\n            storage::io::FileWriter leaf_node_file(leaf_node_filename,\n                                                   storage::io::FileWriter::HasNoFingerprint);\n            // Note, we can't just write everything in one go, because the input_data_vector\n            // is not sorted by hilbert code, only the input_wrapper_vector is in the correct\n            // order.  Instead, we iterate over input_wrapper_vector, copy the hilbert-indexed\n            // entries from input_data_vector into a temporary contiguous array, then write\n            // that array to disk.\n\n            // Create the first level of TreeNodes - each bounding LEAF_NODE_COUNT EdgeDataT\n            // objects.\n            std::size_t wrapped_element_index = 0;\n            while (wrapped_element_index < element_count)\n            {\n                TreeNode current_node;\n\n                std::array<EdgeDataT, LEAF_NODE_SIZE> objects;\n                std::uint32_t object_count = 0;\n\n                // Loop over the next block of EdgeDataT, calculate the bounding box\n                // for the block, and save the data to write to disk in the correct\n                // order.\n                for (std::uint32_t object_index = 0;\n                     object_index < LEAF_NODE_SIZE && wrapped_element_index < element_count;\n                     ++object_index, ++wrapped_element_index)\n                {\n                    const std::uint32_t input_object_index =\n                        input_wrapper_vector[wrapped_element_index].m_original_index;\n                    const EdgeDataT &object = input_data_vector[input_object_index];\n\n                    object_count += 1;\n                    objects[object_index] = object;\n\n                    Coordinate projected_u{\n                        web_mercator::fromWGS84(Coordinate{m_coordinate_list[object.u]})};\n                    Coordinate projected_v{\n                        web_mercator::fromWGS84(Coordinate{m_coordinate_list[object.v]})};\n\n                    BOOST_ASSERT(std::abs(toFloating(projected_u.lon).operator double()) <= 180.);\n                    BOOST_ASSERT(std::abs(toFloating(projected_u.lat).operator double()) <= 180.);\n                    BOOST_ASSERT(std::abs(toFloating(projected_v.lon).operator double()) <= 180.);\n                    BOOST_ASSERT(std::abs(toFloating(projected_v.lat).operator double()) <= 180.);\n\n                    Rectangle rectangle;\n                    rectangle.min_lon =\n                        std::min(rectangle.min_lon, std::min(projected_u.lon, projected_v.lon));\n                    rectangle.max_lon =\n                        std::max(rectangle.max_lon, std::max(projected_u.lon, projected_v.lon));\n\n                    rectangle.min_lat =\n                        std::min(rectangle.min_lat, std::min(projected_u.lat, projected_v.lat));\n                    rectangle.max_lat =\n                        std::max(rectangle.max_lat, std::max(projected_u.lat, projected_v.lat));\n\n                    BOOST_ASSERT(rectangle.IsValid());\n                    current_node.minimum_bounding_rectangle.MergeBoundingBoxes(rectangle);\n                }\n\n                // Write out our EdgeDataT block to the leaf node file\n                leaf_node_file.WriteFrom(objects.data(), object_count);\n\n                m_search_tree.emplace_back(current_node);\n            }\n\n            // leaf_node_file wil be RAII closed at this point\n        }\n\n        // Should hold the number of nodes at the lowest level of the graph (closest\n        // to the data)\n        std::uint32_t nodes_in_previous_level = m_search_tree.size();\n        m_tree_level_sizes.push_back(nodes_in_previous_level);\n\n        // Now, repeatedly create levels of nodes that contain BRANCHING_FACTOR\n        // nodes from the previous level.\n        while (nodes_in_previous_level > 1)\n        {\n            auto previous_level_start_pos = m_search_tree.size() - nodes_in_previous_level;\n\n            // We can calculate how many nodes will be in this level, we divide by\n            // BRANCHING_FACTOR\n            // and round up\n            std::uint32_t nodes_in_current_level =\n                std::ceil(static_cast<double>(nodes_in_previous_level) / BRANCHING_FACTOR);\n\n            for (auto current_node_idx : irange<std::size_t>(0, nodes_in_current_level))\n            {\n                TreeNode parent_node;\n                auto first_child_index =\n                    current_node_idx * BRANCHING_FACTOR + previous_level_start_pos;\n                auto last_child_index =\n                    first_child_index +\n                    std::min<std::size_t>(BRANCHING_FACTOR,\n                                          nodes_in_previous_level -\n                                              current_node_idx * BRANCHING_FACTOR);\n\n                // Calculate the bounding box for BRANCHING_FACTOR nodes in the previous\n                // level, then save that box as a new TreeNode in the new level.\n                for (auto child_node_idx : irange<std::size_t>(first_child_index, last_child_index))\n                {\n                    parent_node.minimum_bounding_rectangle.MergeBoundingBoxes(\n                        m_search_tree[child_node_idx].minimum_bounding_rectangle);\n                }\n                m_search_tree.emplace_back(parent_node);\n            }\n            nodes_in_previous_level = nodes_in_current_level;\n            m_tree_level_sizes.push_back(nodes_in_previous_level);\n        }\n        // At this point, we've got our tree built, but the nodes are in a weird order.\n        // Next thing we'll do is flip it around so that we don't end up with a lot of\n        // `size - n` math later on.\n\n        // Flip the tree so that the root node is at 0.\n        // This just makes our math during search a bit more intuitive\n        std::reverse(m_search_tree.begin(), m_search_tree.end());\n\n        // Same for the level sizes - root node / base level is at 0\n        std::reverse(m_tree_level_sizes.begin(), m_tree_level_sizes.end());\n\n        // The first level starts at 0\n        m_tree_level_starts = {0};\n        // The remaining levels start at the partial sum of the preceeding level sizes\n        std::partial_sum(m_tree_level_sizes.begin(),\n                         m_tree_level_sizes.end() - 1,\n                         std::back_inserter(m_tree_level_starts));\n\n        // Now we have to flip the coordinates within each level so that math is easier\n        // later on.  The workflow here is:\n        // The initial order of tree nodes in the m_search_tree array is roughly:\n        // 6789 345 12 0   (each block here is a level of the tree)\n        // Then we reverse it and get:\n        // 0 21 543 9876\n        // Now the loop below reverses each level to give us the final result\n        // 0 12 345 6789\n        // This ordering keeps the position math easy to understand during later\n        // searches\n        for (auto i : irange<std::size_t>(0, m_tree_level_sizes.size()))\n        {\n            std::reverse(m_search_tree.begin() + m_tree_level_starts[i],\n                         m_search_tree.begin() + m_tree_level_starts[i] + m_tree_level_sizes[i]);\n        }\n\n        // Write all the TreeNode data to disk\n        {\n            storage::io::FileWriter tree_node_file(tree_node_filename,\n                                                   storage::io::FileWriter::GenerateFingerprint);\n\n            std::uint64_t size_of_tree = m_search_tree.size();\n            BOOST_ASSERT_MSG(0 < size_of_tree, \"tree empty\");\n\n            tree_node_file.WriteOne(size_of_tree);\n            tree_node_file.WriteFrom(m_search_tree);\n\n            tree_node_file.WriteOne(static_cast<std::uint64_t>(m_tree_level_sizes.size()));\n            tree_node_file.WriteFrom(m_tree_level_sizes);\n        }\n\n        m_objects = mmapFile<EdgeDataT>(leaf_node_filename, m_objects_region);\n    }\n\n    /**\n     * Constructs an r-tree from already prepared files on disk (generated by the previous\n     * constructor)\n     */\n    explicit StaticRTree(const boost::filesystem::path &node_file,\n                         const boost::filesystem::path &leaf_file,\n                         const Vector<Coordinate> &coordinate_list)\n        : m_coordinate_list(coordinate_list)\n    {\n        storage::io::FileReader tree_node_file(node_file,\n                                               storage::io::FileReader::VerifyFingerprint);\n\n        const auto tree_size = tree_node_file.ReadElementCount64();\n        m_search_tree.resize(tree_size);\n        tree_node_file.ReadInto(m_search_tree);\n\n        const auto levels_array_size = tree_node_file.ReadElementCount64();\n        m_tree_level_sizes.resize(levels_array_size);\n        tree_node_file.ReadInto(m_tree_level_sizes);\n\n        // The first level always starts at 0\n        m_tree_level_starts = {0};\n        // The remaining levels start at the partial sum of the preceeding level sizes\n        std::partial_sum(m_tree_level_sizes.begin(),\n                         m_tree_level_sizes.end() - 1,\n                         std::back_inserter(m_tree_level_starts));\n\n        m_objects = mmapFile<EdgeDataT>(leaf_file, m_objects_region);\n    }\n\n    /**\n     * Constructs an r-tree from blocks of memory loaded by someone else\n     * (usually a shared memory block created by osrm-datastore)\n     * These memory blocks basically just contain the files read into RAM,\n     * excep the .fileIndex file always stays on disk, and we mmap() it as usual\n     */\n    explicit StaticRTree(const TreeNode *tree_node_ptr,\n                         const uint64_t number_of_nodes,\n                         const std::uint64_t *level_sizes_ptr,\n                         const std::size_t number_of_levels,\n                         const boost::filesystem::path &leaf_file,\n                         const Vector<Coordinate> &coordinate_list)\n        : m_search_tree(tree_node_ptr, number_of_nodes), m_coordinate_list(coordinate_list),\n          m_tree_level_sizes(level_sizes_ptr, level_sizes_ptr + number_of_levels)\n    {\n        // The first level starts at 0\n        m_tree_level_starts = {0};\n        // The remaining levels start at the partial sum of the preceeding level sizes\n        std::partial_sum(m_tree_level_sizes.begin(),\n                         m_tree_level_sizes.end() - 1,\n                         std::back_inserter(m_tree_level_starts));\n        m_objects = mmapFile<EdgeDataT>(leaf_file, m_objects_region);\n    }\n\n    /* Returns all features inside the bounding box.\n       Rectangle needs to be projected!*/\n    std::vector<EdgeDataT> SearchInBox(const Rectangle &search_rectangle) const\n    {\n        const Rectangle projected_rectangle{\n            search_rectangle.min_lon,\n            search_rectangle.max_lon,\n            toFixed(FloatLatitude{\n                web_mercator::latToY(toFloating(FixedLatitude(search_rectangle.min_lat)))}),\n            toFixed(FloatLatitude{\n                web_mercator::latToY(toFloating(FixedLatitude(search_rectangle.max_lat)))})};\n        std::vector<EdgeDataT> results;\n\n        std::queue<TreeIndex> traversal_queue;\n        traversal_queue.push(TreeIndex{});\n\n        while (!traversal_queue.empty())\n        {\n            auto const current_tree_index = traversal_queue.front();\n            traversal_queue.pop();\n\n            // If we're at the bottom of the tree, we need to explore the\n            // element array\n            if (is_leaf(current_tree_index))\n            {\n\n                // Note: irange is [start,finish), so we need to +1 to make sure we visit the\n                // last\n                for (const auto current_child_index : child_indexes(current_tree_index))\n                {\n                    const auto &current_edge = m_objects[current_child_index];\n\n                    // we don't need to project the coordinates here,\n                    // because we use the unprojected rectangle to test against\n                    const Rectangle bbox{std::min(m_coordinate_list[current_edge.u].lon,\n                                                  m_coordinate_list[current_edge.v].lon),\n                                         std::max(m_coordinate_list[current_edge.u].lon,\n                                                  m_coordinate_list[current_edge.v].lon),\n                                         std::min(m_coordinate_list[current_edge.u].lat,\n                                                  m_coordinate_list[current_edge.v].lat),\n                                         std::max(m_coordinate_list[current_edge.u].lat,\n                                                  m_coordinate_list[current_edge.v].lat)};\n\n                    // use the _unprojected_ input rectangle here\n                    if (bbox.Intersects(search_rectangle))\n                    {\n                        results.push_back(current_edge);\n                    }\n                }\n            }\n            else\n            {\n                BOOST_ASSERT(current_tree_index.level + 1 < m_tree_level_starts.size());\n\n                for (const auto child_index : child_indexes(current_tree_index))\n                {\n                    const auto &child_rectangle =\n                        m_search_tree[child_index].minimum_bounding_rectangle;\n\n                    if (child_rectangle.Intersects(projected_rectangle))\n                    {\n                        traversal_queue.push(TreeIndex(\n                            current_tree_index.level + 1,\n                            child_index - m_tree_level_starts[current_tree_index.level + 1]));\n                    }\n                }\n            }\n        }\n        return results;\n    }\n\n    // Override filter and terminator for the desired behaviour.\n    std::vector<EdgeDataT> Nearest(const Coordinate input_coordinate,\n                                   const std::size_t max_results) const\n    {\n        return Nearest(input_coordinate,\n                       [](const CandidateSegment &) { return std::make_pair(true, true); },\n                       [max_results](const std::size_t num_results, const CandidateSegment &) {\n                           return num_results >= max_results;\n                       });\n    }\n\n    // Override filter and terminator for the desired behaviour.\n    template <typename FilterT, typename TerminationT>\n    std::vector<EdgeDataT> Nearest(const Coordinate input_coordinate,\n                                   const FilterT filter,\n                                   const TerminationT terminate) const\n    {\n        std::vector<EdgeDataT> results;\n        auto projected_coordinate = web_mercator::fromWGS84(input_coordinate);\n        Coordinate fixed_projected_coordinate{projected_coordinate};\n        // initialize queue with root element\n        std::priority_queue<QueryCandidate> traversal_queue;\n        traversal_queue.push(QueryCandidate{0, TreeIndex{}});\n\n        while (!traversal_queue.empty())\n        {\n            QueryCandidate current_query_node = traversal_queue.top();\n            traversal_queue.pop();\n\n            const TreeIndex &current_tree_index = current_query_node.tree_index;\n            if (!current_query_node.is_segment())\n            { // current object is a tree node\n                if (is_leaf(current_tree_index))\n                {\n                    ExploreLeafNode(current_tree_index,\n                                    fixed_projected_coordinate,\n                                    projected_coordinate,\n                                    traversal_queue);\n                }\n                else\n                {\n                    ExploreTreeNode(\n                        current_tree_index, fixed_projected_coordinate, traversal_queue);\n                }\n            }\n            else\n            { // current candidate is an actual road segment\n                // We deliberatly make a copy here, we mutate the value below\n                auto edge_data = m_objects[current_query_node.segment_index];\n                const auto &current_candidate =\n                    CandidateSegment{current_query_node.fixed_projected_coordinate, edge_data};\n\n                // to allow returns of no-results if too restrictive filtering, this needs to be\n                // done here even though performance would indicate that we want to stop after\n                // adding the first candidate\n                if (terminate(results.size(), current_candidate))\n                {\n                    break;\n                }\n\n                auto use_segment = filter(current_candidate);\n                if (!use_segment.first && !use_segment.second)\n                {\n                    continue;\n                }\n                edge_data.forward_segment_id.enabled &= use_segment.first;\n                edge_data.reverse_segment_id.enabled &= use_segment.second;\n\n                // store phantom node in result vector\n                results.push_back(std::move(edge_data));\n            }\n        }\n\n        return results;\n    }\n\n  private:\n    /**\n     * Iterates over all the objects in a leaf node and inserts them into our\n     * search priority queue.  The speed of this function is very much governed\n     * by the value of LEAF_NODE_SIZE, as we'll calculate the euclidean distance\n     * for every child of each leaf node visited.\n     */\n    template <typename QueueT>\n    void ExploreLeafNode(const TreeIndex &leaf_id,\n                         const Coordinate &projected_input_coordinate_fixed,\n                         const FloatCoordinate &projected_input_coordinate,\n                         QueueT &traversal_queue) const\n    {\n        // Check that we're actually looking at the bottom level of the tree\n        BOOST_ASSERT(is_leaf(leaf_id));\n\n        for (const auto i : child_indexes(leaf_id))\n        {\n            const auto &current_edge = m_objects[i];\n\n            const auto projected_u = web_mercator::fromWGS84(m_coordinate_list[current_edge.u]);\n            const auto projected_v = web_mercator::fromWGS84(m_coordinate_list[current_edge.v]);\n\n            FloatCoordinate projected_nearest;\n            std::tie(std::ignore, projected_nearest) =\n                coordinate_calculation::projectPointOnSegment(\n                    projected_u, projected_v, projected_input_coordinate);\n\n            const auto squared_distance = coordinate_calculation::squaredEuclideanDistance(\n                projected_input_coordinate_fixed, projected_nearest);\n            // distance must be non-negative\n            BOOST_ASSERT(0. <= squared_distance);\n            BOOST_ASSERT(i < std::numeric_limits<std::uint32_t>::max());\n            traversal_queue.push(QueryCandidate{squared_distance,\n                                                leaf_id,\n                                                static_cast<std::uint32_t>(i),\n                                                Coordinate{projected_nearest}});\n        }\n    }\n\n    /**\n     * Iterates over all the children of a TreeNode and inserts them into the search\n     * priority queue using their distance from the search coordinate as the\n     * priority metric.\n     * The closests distance to a box from our point is also the closest distance\n     * to the closest line in that box (assuming the boxes hug their contents).\n     */\n    template <class QueueT>\n    void ExploreTreeNode(const TreeIndex &parent,\n                         const Coordinate &fixed_projected_input_coordinate,\n                         QueueT &traversal_queue) const\n    {\n        // Figure out which_id level the parent is on, and it's offset\n        // in that level.\n        // Check that we're actually looking at the bottom level of the tree\n        BOOST_ASSERT(!is_leaf(parent));\n\n        for (const auto child_index : child_indexes(parent))\n        {\n            const auto &child = m_search_tree[child_index];\n\n            const auto squared_lower_bound_to_element =\n                child.minimum_bounding_rectangle.GetMinSquaredDist(\n                    fixed_projected_input_coordinate);\n\n            traversal_queue.push(QueryCandidate{\n                squared_lower_bound_to_element,\n                TreeIndex(parent.level + 1, child_index - m_tree_level_starts[parent.level + 1])});\n        }\n    }\n\n    /**\n     * Calculates the absolute position of child data in our packed data\n     * vectors.\n     *\n     * when given a TreeIndex that is a leaf node (i.e. at the bottom of the tree),\n     * this function returns indexes valid for `m_objects`\n     *\n     * otherwise, the indexes are to be used with m_search_tree to iterate over\n     * the children of `parent`\n     *\n     * This function assumes we pack nodes as described in the big comment\n     * at the top of this class.  All nodes are fully filled except for the last\n     * one in each level.\n     */\n    range<std::size_t> child_indexes(const TreeIndex &parent) const\n    {\n        // If we're looking at a leaf node, the index is from 0 to m_objects.size(),\n        // there is only 1 level of object data in the m_objects array\n        if (is_leaf(parent))\n        {\n            const std::uint64_t first_child_index = parent.offset * LEAF_NODE_SIZE;\n            const std::uint64_t end_child_index = std::min(\n                first_child_index + LEAF_NODE_SIZE, static_cast<std::uint64_t>(m_objects.size()));\n\n            BOOST_ASSERT(first_child_index < std::numeric_limits<std::uint32_t>::max());\n            BOOST_ASSERT(end_child_index < std::numeric_limits<std::uint32_t>::max());\n            BOOST_ASSERT(end_child_index <= m_objects.size());\n\n            return irange<std::size_t>(first_child_index, end_child_index);\n        }\n        else\n        {\n            const std::uint64_t first_child_index =\n                m_tree_level_starts[parent.level + 1] + parent.offset * BRANCHING_FACTOR;\n\n            const std::uint64_t end_child_index = std::min(\n                first_child_index + BRANCHING_FACTOR,\n                m_tree_level_starts[parent.level + 1] + m_tree_level_sizes[parent.level + 1]);\n            BOOST_ASSERT(first_child_index < std::numeric_limits<std::uint32_t>::max());\n            BOOST_ASSERT(end_child_index < std::numeric_limits<std::uint32_t>::max());\n            BOOST_ASSERT(end_child_index <= m_search_tree.size());\n            BOOST_ASSERT(end_child_index <= m_tree_level_starts[parent.level + 1] +\n                                                m_tree_level_sizes[parent.level + 1]);\n            return irange<std::size_t>(first_child_index, end_child_index);\n        }\n    }\n\n    bool is_leaf(const TreeIndex &treeindex) const\n    {\n        return treeindex.level == m_tree_level_starts.size() - 1;\n    }\n};\n\n//[1] \"On Packing R-Trees\"; I. Kamel, C. Faloutsos; 1993; DOI: 10.1145/170088.170403\n//[2] \"Nearest Neighbor Queries\", N. Roussopulos et al; 1995; DOI: 10.1145/223784.223794\n//[3] \"Distance Browsing in Spatial Databases\"; G. Hjaltason, H. Samet; 1999; ACM Trans. DB Sys\n// Vol.24 No.2, pp.265-318\n}\n}\n\n#endif // STATIC_RTREE_HPP\n", "meta": {"hexsha": "a0cac25a41ccf199d7631d9811ef56f0f2b16fed", "size": 34870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/static_rtree.hpp", "max_stars_repo_name": "AugustoQueiroz/pedalavel-backend", "max_stars_repo_head_hexsha": "c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/util/static_rtree.hpp", "max_issues_repo_name": "AugustoQueiroz/pedalavel-backend", "max_issues_repo_head_hexsha": "c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/util/static_rtree.hpp", "max_forks_repo_name": "AugustoQueiroz/pedalavel-backend", "max_forks_repo_head_hexsha": "c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-23T22:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T22:49:07.000Z", "avg_line_length": 43.6967418546, "max_line_length": 100, "alphanum_fraction": 0.5963865787, "num_tokens": 7177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.028007523648406737, "lm_q1q2_score": 0.013129664561385933}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n#include <votca/xtp/qmmachine.h>\n#include <sys/stat.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <votca/tools/elements.h>\n#include <votca/xtp/espfit.h>\n#include <votca/xtp/aomatrix.h>\n\n\nusing boost::format;\n\nnamespace votca {\n  namespace xtp {\n\n\n    QMMachine::QMMachine(ctp::XJob *job, ctp::XInductor *xind, QMPackage *qmpack,\n            Property *opt, string sfx)\n    : _job(job), _xind(xind), _qmpack(qmpack), \n    _isConverged(false) {\n\n      string key = sfx + \".qmmmconvg\";\n      _crit_dR = opt->ifExistsReturnElseReturnDefault<double>(key + \".dR\", 0.01); //nm\n      _crit_dQ = opt->ifExistsReturnElseReturnDefault<double>(key + \".dQ\", 0.01); //e\n      _crit_dE_QM = opt->ifExistsReturnElseReturnDefault<double>(key + \".dQdE_QM\", 0.001); //eV\n      _crit_dE_MM = opt->ifExistsReturnElseReturnDefault<double>(key + \".dE_MM\", _crit_dE_QM); //eV\n      _maxIter = opt->ifExistsReturnElseReturnDefault<int>(key + \".max_iter\", 32);\n      _alpha = opt->ifExistsReturnElseReturnDefault<double>(key + \".mixing\", 0.0);\n\n      key = sfx;\n      double dpl_spacing = opt->ifExistsReturnElseReturnDefault<double>(key + \".dpl_spacing\", 1e-3);\n\n      // check for archiving\n      std::string _archiving_string = opt->ifExistsReturnElseReturnDefault<std::string>(key + \".archiving\", \"\");\n      if (_archiving_string.find(\"iterations\") != std::string::npos) {\n        _do_archive = true;\n      } else {\n        _do_archive = false;\n      }\n\n      // check for static or polarized qmmm\n      key = sfx + \".tholemodel\";\n      _static_qmmm = true;\n      qmpack->setWithPolarization(false);\n      if (opt->exists(key + \".induce\")) {\n        bool induce = opt->get(key + \".induce\").as<bool>();\n        if (induce) {\n          qmpack->setWithPolarization(true);\n          qmpack->setDipoleSpacing(dpl_spacing);\n        }\n        _static_qmmm = !induce;\n      }\n\n      // GDMA options\n      key = sfx + \".gdma\";\n      if (opt->exists(key)) {\n        _do_gdma = true;\n        string gdma_xml = opt->get(key).as<string> ();\n        load_property_from_xml(_gdma_options, gdma_xml.c_str());\n      } else {\n        _do_gdma = false;\n      }\n\n      // GWBSE options\n      key = sfx + \".gwbse\";\n      if (opt->exists(key)) {\n        string _gwbse_xml = opt->get(key + \".gwbse_options\").as<string> ();\n        load_property_from_xml(_gwbse_options, _gwbse_xml.c_str());\n         key = sfx + \".gwbse.filter\";\n         if(opt->exists(key)){\n           tools::Property& filterprop=opt->get(key);\n           _filter.Initialize(filterprop);\n         }\n      } \n\n      return;\n    }\n\n\n    QMMachine::~QMMachine() {\n      for (QMMIter* qit : _iters) {\n        delete qit;\n      }\n      _iters.clear();\n    }\n\n\n    int QMMachine::Evaluate(ctp::XJob *job) {\n\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... dR %1$1.4f dQ %2$1.4f QM %3$1.4f MM %4$1.4f IT %5$d\")\n              % _crit_dR % _crit_dQ % _crit_dE_QM % _crit_dE_MM % _maxIter << flush;\n\n      // FIGURE OUT CHARGE + MULTIPLICITY\n      double dQ = 0.0;\n      for (unsigned int i = 0; i < _job->getPolarTop()->QM0().size(); ++i) {\n        dQ += _job->getPolarTop()->QM0()[i]->CalcTotQ();\n      }\n      int chrg = std::round(dQ);\n      int spin = ((chrg < 0) ? -chrg : chrg) % 2 + 1;\n      CTP_LOG(ctp::logINFO, *_log) << \"... Q = \" << chrg << \", 2S+1 = \" << spin << flush;\n\n\n      // PREPARE JOB DIRECTORY\n      boost::filesystem::path arg_path;\n      string frame_dir = \"frame_\" + boost::lexical_cast<string>(_job->getTop()->getDatabaseId());\n      string jobFolder = \"job_\" + boost::lexical_cast<string>(_job->getId())\n              + \"_\" + _job->getTag();\n      string work_dir = (arg_path / \"QMMM\" / frame_dir / jobFolder).c_str();\n      bool created = boost::filesystem::create_directories(work_dir);\n      if (created) {\n        CTP_LOG(ctp::logINFO, *_log) << \"Created directory \" << work_dir << flush;\n      }\n      \n      vector<string> split;\n      Tokenizer toker(_job->getTag(), \":\");\n      toker.ToVector(split);\n      _initialstate=QMState(split.back());\n      if(_initialstate.Type().isExciton() || _initialstate.Type().isGWState()){\n       _filter.setInitialState(_initialstate);\n       _filter.setLogger(_log);\n       _do_gwbse=true;\n      }\n      \n      _qmpack->setCharge(chrg);\n      _qmpack->setSpin(spin);\n\n      int iterCnt = 0;\n      int iterMax = _maxIter;\n      for (; iterCnt < iterMax; ++iterCnt) {\n\n        // check for polarized QM/MM convergence\n        int info = Iterate(work_dir, iterCnt);\n        if (info != 0) {\n          CTP_LOG(ctp::logERROR, *_log)\n                  << format(\"Iterating job failed!\") << flush;\n          return 1;\n        }\n        if (_static_qmmm) {\n          _isConverged = true;\n          break;\n        } else if (hasConverged()) {\n          break;\n        }\n\n      }\n\n      if (iterCnt == iterMax - 1 && !_isConverged) {\n        CTP_LOG(ctp::logWARNING, *_log)\n                << format(\"Not converged within %1$d iterations.\") % iterMax;\n        return 2;\n      }\n\n      return 0;\n    }\n\n\n    void QMMachine::RunGDMA(QMMIter* thisIter, string& runFolder){\n      if (_qmpack->getPackageName() != \"gaussian\" || _qmpack->getExecutable() != \"g03\") {\n        throw std::runtime_error(\" Invalid QMPackage: \" + _qmpack->getPackageName()+ \" Gaussian 03 only!\");\n      } else {\n        GDMA gdma;\n        gdma.Initialize(_gdma_options);\n        gdma.setLog(_log);\n        gdma.SetRunDir(runFolder);\n        CTP_LOG(ctp::logINFO, *_log) << \"Running GDMA \" << flush;\n        gdma.WriteInputFile();\n        gdma.RunExternal();\n        gdma.ParseOutputFile();\n        thisIter->UpdateMPSFromGDMA(gdma.GetMultipoles(), _job->getPolarTop()->QM0());\n      } \n    }\n\n\n    void QMMachine::RunGWBSE(string& runFolder){\n      CTP_LOG(ctp::logDEBUG, *_log) << \"Running GWBSE \"<< flush;\n      GWBSE gwbse = GWBSE(orb_iter_input);\n      // define own logger for GW-BSE that is written into a runFolder logfile\n      ctp::Logger gwbse_logger(ctp::logDEBUG);\n      gwbse_logger.setMultithreading(false);\n      gwbse.setLogger(&gwbse_logger);\n      gwbse_logger.setPreface(ctp::logINFO, (format(\"\\nGWBSE INF ...\")).str());\n      gwbse_logger.setPreface(ctp::logERROR, (format(\"\\nGWBSE ERR ...\")).str());\n      gwbse_logger.setPreface(ctp::logWARNING, (format(\"\\nGWBSE WAR ...\")).str());\n      gwbse_logger.setPreface(ctp::logDEBUG, (format(\"\\nGWBSE DBG ...\")).str());\n      \n      // Initialize with options\n      gwbse.Initialize(_gwbse_options);\n      // actual GW-BSE run\n      gwbse.Evaluate();\n      \n      // write logger to log file\n      ofstream ofs;\n      string gwbse_logfile = runFolder + \"/gwbse.log\";\n      ofs.open(gwbse_logfile.c_str(), ofstream::out);\n      if (!ofs.is_open()) {\n        throw runtime_error(\"Bad file handle: \" + gwbse_logfile);\n      }\n      ofs << gwbse_logger << endl;\n      ofs.close();\n    }\n\n\n    bool QMMachine::RunDFT(string& runFolder, std::vector<std::shared_ptr<ctp::PolarSeg> >& MultipolesBackground){\n      ctp::Logger dft_logger(ctp::logDEBUG);\n      dft_logger.setMultithreading(false);\n      dft_logger.setPreface(ctp::logINFO, (format(\"\\nGWBSE INF ...\")).str());\n      dft_logger.setPreface(ctp::logERROR, (format(\"\\nGWBSE ERR ...\")).str());\n      dft_logger.setPreface(ctp::logWARNING, (format(\"\\nGWBSE WAR ...\")).str());\n      dft_logger.setPreface(ctp::logDEBUG, (format(\"\\nGWBSE DBG ...\")).str());\n      _qmpack->setLog(&dft_logger);\n      \n      _qmpack->setMultipoleBackground(MultipolesBackground);\n      \n      // setting RUNDIR for the external QMPackages, dummy for internal\n      _qmpack->setRunDir(runFolder);\n      \n      CTP_LOG(ctp::logDEBUG, *_log) << \"Writing input file \" << runFolder << flush;\n      CTP_LOG(ctp::logDEBUG, *_log) << \"Running DFT \" << flush;\n      _qmpack->WriteInputFile(orb_iter_input);\n      \n      orb_iter_input.WriteXYZ(runFolder + \"/system_qm.xyz\");\n      \n      _qmpack->Run(orb_iter_input);\n      \n      /* Parse information from the LOGFILE into orbitals, if\n       * external QMPackage is run. Dummy for internal DFTENGINE.\n       * The QMPackage's MOcoefficients are not automatically\n       * parsed in DFT-only calculations and ESP fits for\n       * polarized QMMM are expected in the LOGFILE.\n       * IF the internal ESPFITs should be used, the MOcoefficients\n       * need to be parsed too.\n       */\n      bool success1= _qmpack->ParseLogFile(orb_iter_input);\n   \n      bool success2=_qmpack->ParseOrbitalsFile(orb_iter_input);\n      _qmpack->CleanUp();\n      \n      ofstream ofs;\n      string dft_logfile = runFolder + \"/dft.log\";\n      ofs.open(dft_logfile.c_str(), ofstream::out);\n      if (!ofs.is_open()) {\n        throw runtime_error(\"Bad file handle: \" + dft_logfile);\n      }\n      ofs << dft_logger << endl;\n      ofs.close();\n      _qmpack->setLog(_log);\n        return success1&&success2;\n    }\n\n    bool QMMachine::Iterate(string jobFolder, int iterCnt) {\n\n      // CREATE ITERATION OBJECT & SETUP RUN DIRECTORY\n      QMMIter *thisIter = this->CreateNewIter();\n      int iter = iterCnt;\n      string runFolder = jobFolder + \"/iter_\" + boost::lexical_cast<string>(iter);\n\n      bool created = boost::filesystem::create_directory(runFolder);\n      if (created)\n        CTP_LOG(ctp::logDEBUG, *_log) << \"Created directory \" << runFolder << flush;\n      else\n        CTP_LOG(ctp::logWARNING, *_log) << \"Could not create directory \" << runFolder << flush;\n\n      // RUN CLASSICAL INDUCTION & SAVE\n      _job->getPolarTop()->PrintPDB(runFolder + \"/QM0_MM1_MM2.pdb\");\n      _xind->Evaluate(_job);\n\n      if(!_xind->hasConverged()){\n        throw std::runtime_error(\"Classical induction did not converge\");\n      }\n\n      thisIter->setE_FM(_job->getEF00(), _job->getEF01(), _job->getEF02(),\n              _job->getEF11(), _job->getEF12(), _job->getEM0(),\n              _job->getEM1(), _job->getEM2(), _job->getETOT());\n\n\n      /* Translate atoms in QM0() to QMAtoms in orbitals object\n       * to be used in writing the QM input files for the\n       * external QMPackages or directly in internal DFT engine.\n       * DRAWBACK: QMAtom positions are fixed for all iterations\n       *           unless the UPDATE function at the end of the\n       *           iteration updates orb_iter_input (TO BE TESTED)\n       */\n      QMInterface qminterface;\n      if (iterCnt == 0) qminterface.GenerateQMAtomsFromPolarSegs(_job->getPolarTop(), orb_iter_input);\n\n      /* Generate list of polar segments in the MM1() and MM2()\n       * region to be used in writing the background multipoles\n       * in the external QMPackages or in the direct evaluation\n       * in the internal DFT engine.\n       */\n      std::vector<std::shared_ptr<ctp::PolarSeg> > MultipolesBackground = qminterface.GenerateMultipoleList(_job->getPolarTop());\n\n      bool success=RunDFT(runFolder, MultipolesBackground);\n      if (!success) {\n        return 1;\n      }\n       \n\ndouble energy_ex=0.0;\n      if (_do_gwbse) {\n        if (_initialstate.Type()==QMStateType::Gstate) {\n         CTP_LOG(ctp::logDEBUG, *_log) <<\"QMMMachine no GWBSE necessary for \" + _initialstate.ToLongString();\n        }\n        RunGWBSE(runFolder);\n        CTP_LOG(ctp::logDEBUG, *_log) << \"Excited state via GWBSE: \" << flush;\n        CTP_LOG(ctp::logDEBUG, *_log) << \"state:\" << _initialstate.ToLongString() << flush;\n        _filter.PrintInfo();\n       \n        QMState newstate= _filter.CalcStateAndUpdate(orb_iter_input);\n        energy_ex=orb_iter_input.getExcitedStateEnergy(newstate)* tools::conv::hrt2ev;    \n\n        if (!_static_qmmm) {\n          Density2Charges(newstate);\n        }\n\n      } //_do_gwbse\n\n\n      /* new ESP fit only required for\n       * - polarizable QMMM\n       * AND\n       * - GWBSE or DFT with internal DFTENGINE\n       */\n      if (!_static_qmmm && _qmpack->getPackageName() == \"xtp\" && !_do_gwbse) {\n        QMState gsstate=QMState(QMStateType::Gstate,0,false);\n        Density2Charges(gsstate);\n      } // for polarized QMMM\n\n      if (tools::globals::verbose) {\n        CTP_LOG(ctp::logDEBUG, *_log) << \"Calculated partial charges\" << flush;\n        for (const QMAtom* atom : orb_iter_input.QMAtoms()) {\n          CTP_LOG(ctp::logDEBUG, *_log) << atom->getType() << \" \" << atom->getPartialcharge() << flush;\n        }\n      }\n      \n      // EXTRACT & SAVE QM ENERGIES\n      double energy_sf = orb_iter_input.getSelfEnergy();\n      double energy_qmsf = orb_iter_input.getQMEnergy();\n      double energy_qm = energy_qmsf - energy_sf;\n      thisIter->setQMSF(energy_qm, energy_sf, energy_ex);\n      _job->setEnergy_QMMM(thisIter->getQMEnergy(), thisIter->getGWBSEEnergy(), thisIter->getSFEnergy(),\n              thisIter->getQMMMEnergy());\n\n      // EXTRACT & SAVE QMATOM DATA\n      std::vector< QMAtom* > &atoms = orb_iter_input.QMAtoms();\n\n      thisIter->UpdatePosChrgFromQMAtoms(atoms, _job->getPolarTop()->QM0());\n      \n      if (_do_gdma) {\n        RunGDMA(thisIter, runFolder);\n      } \n\n      // serialize this iteration\n      if (_do_archive) {\n        // save orbitals\n        std::string orb_file = runFolder + \"/system.orb\";\n        CTP_LOG(ctp::logDEBUG, *_log) << \"Archiving data to \" << orb_file << flush;\n        orb_iter_input.WriteToCpt(orb_file);\n      }\n\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"Summary - iteration %1$d:\") % (iterCnt + 1) << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... QM Size  = %1$d atoms\") % int(atoms.size()) << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... E(QM)    = %1$+4.9e\") % thisIter->getQMEnergy() << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... E(GWBSE) = %1$+4.9e\") % thisIter->getGWBSEEnergy() << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... E(SF)    = %1$+4.9e\") % thisIter->getSFEnergy() << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... E(FM)    = %1$+4.9e\") % thisIter->getFMEnergy() << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... E(MM)    = %1$+4.9e\") % thisIter->getMMEnergy() << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... E(QMMM)  = %1$+4.9e\") % thisIter->getQMMMEnergy() << flush;\n      if (!_static_qmmm) {\n        CTP_LOG(ctp::logINFO, *_log)\n                << format(\"... RMS(dR)  = %1$+4.9e\") % thisIter->getRMSdR() << flush;\n        CTP_LOG(ctp::logINFO, *_log)\n                << format(\"... RMS(dQ)  = %1$+4.9e\") % thisIter->getRMSdQ() << flush;\n        CTP_LOG(ctp::logINFO, *_log)\n                << format(\"... SUM(dQ)  = %1$+4.9e\") % thisIter->getSUMdQ() << flush;\n      }\n      // CLEAN DIRECTORY\n     \n\n      return 0;\n    }\n\n\n    void QMMachine::Density2Charges(const QMState& state) {\n\n      Eigen::MatrixXd DMAT = orb_iter_input.DensityMatrixFull(state);\n      \n      int iter = _iters.size() - 1;\n      Eigen::MatrixXd DMAT_mixed;\n      if (iter == 0) {\n        DMAT_mixed = DMAT;\n      } else {\n        DMAT_mixed = _alpha * _DMAT_old + (1 - _alpha) * DMAT;\n      }\n\n      _DMAT_old = DMAT_mixed;\n      BasisSet dftbs;\n      if (orb_iter_input.getDFTbasis() != \"\") {\n        dftbs.LoadBasisSet(orb_iter_input.getDFTbasis());\n        CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Loaded DFT Basis Set \" << orb_iter_input.getDFTbasis() << flush;\n      }else{\n        throw std::runtime_error(\"Basisset in orb_iter_input not set\");\n      }\n      // fill DFT AO basis by going through all atoms\n      AOBasis dftbasis;\n      dftbasis.AOBasisFill(dftbs, orb_iter_input.QMAtoms());\n      Espfit esp = Espfit(_log);\n      esp.Fit2Density(orb_iter_input.QMAtoms(), DMAT_mixed, dftbasis, \"medium\");\n\n      return;\n    }\n\n\n    QMMIter *QMMachine::CreateNewIter() {\n\n      QMMIter *newIter = new QMMIter(_iters.size());\n      this->_iters.push_back(newIter);\n      return newIter;\n    }\n\n\n    bool QMMachine::hasConverged() {\n\n    bool  convg_dR = false;\n    bool  convg_dQ = false;\n    bool  convg_dE_QM = false;\n    bool  convg_dE_MM = false;\n\n      if (_iters.size() > 1) {\n\n        QMMIter *iter_0 = _iters[_iters.size() - 2];\n        QMMIter *iter_1 = _iters[_iters.size() - 1];\n\n        double dR = iter_1->getRMSdR();\n        double dQ = iter_1->getRMSdQ();\n        double dE_QM = iter_1->getQMEnergy() - iter_0->getQMEnergy();\n        double dE_MM = iter_1->getMMEnergy() - iter_0->getMMEnergy();\n\n        CTP_LOG(ctp::logINFO, *_log)\n                << format(\"... dE_QM  = %1$+4.9e\") % dE_QM << flush;\n        CTP_LOG(ctp::logINFO, *_log)\n                << format(\"... dE_MM  = %1$+4.9e\") % dE_MM << flush;\n\n        if (dR <= _crit_dR) convg_dR = true;\n        if (dQ <= _crit_dQ) convg_dQ = true;\n        if (dE_QM * dE_QM <= _crit_dE_QM * _crit_dE_QM) convg_dE_QM = true;\n        if (dE_MM * dE_MM <= _crit_dE_MM * _crit_dE_MM) convg_dE_MM = true;\n      }\n\n      _isConverged = ((convg_dR && convg_dQ) && (convg_dE_QM && convg_dE_MM));\n\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... Convg dR = %s\") % (convg_dR ? \"true\" : \"false\") << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... Convg dQ = %s\") % (convg_dQ ? \"true\" : \"false\") << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... Convg QM = %s\") % (convg_dE_QM ? \"true\" : \"false\") << flush;\n      CTP_LOG(ctp::logINFO, *_log)\n              << format(\"... Convg MM = %s\") % (convg_dE_MM ? \"true\" : \"false\") << flush;\n\n      return _isConverged;\n    }\n\n\n\n\n  }\n}\n", "meta": {"hexsha": "e3a948f49be38455d8ef2c14803a1a3118463a48", "size": 18088, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/qmmachine.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/qmmachine.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/qmmachine.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3212851406, "max_line_length": 129, "alphanum_fraction": 0.5933215391, "num_tokens": 5367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.034100429025267616, "lm_q1q2_score": 0.013125669745152441}}
{"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 <map>\n#include <fstream>\n#include <string>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/trim.hpp>\n\n#include \"Tudat/InputOutput/multiDimensionalArrayReader.h\"\n\nnamespace tudat\n{\n\nnamespace input_output\n{\n\n//! Function to parse a block of values read from a file into a multi-array of size 1.\nboost::multi_array< double, 1 > parseRawOneDimensionalCoefficientsFromFile(\n        const std::vector< int > independentVariableSize,\n        const Eigen::MatrixXd& coefficientsBlock )\n{\n    boost::multi_array< double, 1 > coefficientMultiarray;\n\n    // Check input consistency\n    if ( independentVariableSize.size( ) == 1 )\n    {\n        // Define size of multi-array\n        coefficientMultiarray.resize( boost::extents[ independentVariableSize.at( 0 ) ] );\n\n        // Parse data\n        for ( int i = 0; i < independentVariableSize.at( 0 ); i++ )\n        {\n            coefficientMultiarray[ i ] = coefficientsBlock( i, 0 );\n        }\n    }\n    else\n    {\n        throw std::runtime_error( \"Error, expected size of 1 dimension when parsing 1-dimensional data into multi-array.\" );\n    }\n    return coefficientMultiarray;\n}\n\n//! Function to parse a block of values read from a file into a multi-array of size 2.\nboost::multi_array< double, 2 > parseRawTwoDimensionalCoefficientsFromFile(\n        const std::vector< int > independentVariableSize,\n        const Eigen::MatrixXd& coefficientsBlock )\n{\n    boost::multi_array< double, 2 > coefficientMultiarray;\n\n    // Check input consistency\n    if ( independentVariableSize.size( ) == 2 )\n    {\n        // Define size of multi-array\n        coefficientMultiarray.resize( boost::extents[ independentVariableSize.at( 0 ) ][ independentVariableSize.at( 1 ) ]  );\n\n        // Parse data\n        for ( int i = 0; i < independentVariableSize.at( 0 ); i++ )\n        {\n            for ( int j = 0; j < independentVariableSize.at( 1 ); j++ )\n            {\n                coefficientMultiarray[ i ][ j ] = coefficientsBlock( i, j );\n            }\n        }\n    }\n    else\n    {\n        throw std::runtime_error( \"Error, expected size of 2 dimensions when parsing 1-dimensional data into multi-array.\" );\n    }\n    return coefficientMultiarray;\n}\n\n//! Function to parse a block of values read from a file into a multi-array of size 3.\nboost::multi_array< double, 3 > parseRawThreeDimensionalCoefficientsFromFile(\n        const std::vector< int > independentVariableSize,\n        const Eigen::MatrixXd& coefficientsBlock )\n{\n    boost::multi_array< double, 3 > coefficientMultiarray;\n\n    // Check input consistency\n    if ( independentVariableSize.size( ) == 3 )\n    {\n        // Define size of multi-array\n        coefficientMultiarray.resize( boost::extents[ independentVariableSize.at( 0 ) ]\n                [ independentVariableSize.at( 1 ) ][ independentVariableSize.at( 2 ) ] );\n\n        // Parse data\n        int currentStartRow = 0;\n        for ( int k = 0; k < independentVariableSize.at( 2 ); k++ )\n        {\n            for ( int i = 0; i < independentVariableSize.at( 0 ); i++ )\n            {\n                for ( int j = 0; j < independentVariableSize.at( 1 ); j++ )\n                {\n                    coefficientMultiarray[ i ][ j ][ k ] = coefficientsBlock( i + currentStartRow, j );\n                }\n            }\n            currentStartRow += independentVariableSize.at( 0 );\n        }\n    }\n    else\n    {\n        throw std::runtime_error( \"Error, expected size of 3 dimensions when parsing 1-dimensional data into multi-array.\" );\n    }\n    return coefficientMultiarray;\n}\n\n//! Function to parse a block of values read from a file into a multi-array of size 4.\nboost::multi_array< double, 4 > parseRawFourDimensionalCoefficientsFromFile(\n        const std::vector< int > independentVariableSize,\n        const Eigen::MatrixXd& coefficientsBlock )\n{\n    boost::multi_array< double, 4 > coefficientMultiarray;\n\n    // Check input consistency\n    if ( independentVariableSize.size( ) == 4 )\n    {\n        // Define size of multi-array\n        coefficientMultiarray.resize( boost::extents[ independentVariableSize.at( 0 ) ]\n                [ independentVariableSize.at( 1 ) ][ independentVariableSize.at( 2 ) ][ independentVariableSize.at( 3 ) ] );\n\n        // Parse data\n        if ( coefficientsBlock.rows( ) == ( independentVariableSize.at( 0 ) * independentVariableSize.at( 2 ) *\n                                            independentVariableSize.at( 3 ) ) )\n        {\n            int currentStartRowFourthDimension = 0;\n            for ( int l = 0; l < independentVariableSize.at( 3 ); l++ )\n            {\n                int currentStartRowThirdDimension = 0;\n                for ( int k = 0; k < independentVariableSize.at( 2 ); k++ )\n                {\n                    for ( int i = 0; i < independentVariableSize.at( 0 ); i++ )\n                    {\n                        for ( int j = 0; j < independentVariableSize.at( 1 ); j++ )\n                        {\n                            coefficientMultiarray[ i ][ j ][ k ][ l ] = coefficientsBlock( i + currentStartRowThirdDimension +\n                                                                                           currentStartRowFourthDimension, j );\n                        }\n                    }\n                    currentStartRowThirdDimension += independentVariableSize.at( 0 );\n                }\n                currentStartRowFourthDimension += independentVariableSize.at( 2 ) * independentVariableSize.at( 0 );\n            }\n        }\n        else if ( coefficientsBlock.cols( ) == ( independentVariableSize.at( 1 ) * independentVariableSize.at( 3 ) ) )\n        {\n            int currentStartColumn = 0;\n            for ( int l = 0; l < independentVariableSize.at( 3 ); l++ )\n            {\n                int currentStartRow = 0;\n                for ( int k = 0; k < independentVariableSize.at( 2 ); k++ )\n                {\n                    for ( int i = 0; i < independentVariableSize.at( 0 ); i++ )\n                    {\n                        for ( int j = 0; j < independentVariableSize.at( 1 ); j++ )\n                        {\n                            coefficientMultiarray[ i ][ j ][ k ][ l ] = coefficientsBlock( i + currentStartRow, j + currentStartColumn );\n                        }\n                    }\n                    currentStartRow += independentVariableSize.at( 0 );\n                }\n                currentStartColumn += independentVariableSize.at( 1 );\n            }\n        }\n        else\n        {\n            throw std::runtime_error( \"Error, the way the 4 dimensional data is stored is not currently supported. The fourth dimension can \"\n                                      \"either be stored as extra columns, or as repeating blocks.\" );\n        }\n    }\n    else\n    {\n        throw std::runtime_error( \"Error, expected size of 4 dimensions when parsing 1-dimensional data into multi-array.\" );\n    }\n    return coefficientMultiarray;\n}\n\n//! Function to read a coefficient file (data on a structured grid as a function of N independent variables)\nvoid readCoefficientsFile(\n        const std::string fileName,\n        std::vector< std::vector< double > >& independentVariables,\n        Eigen::MatrixXd& coefficientBlock )\n{\n    // Open file and create file stream.\n    std::fstream stream( fileName.c_str( ), std::ios::in );\n\n    // Check if file opened correctly.\n    if ( stream.fail( ) )\n    {\n        throw std::runtime_error( \"Data file could not be opened: \" + fileName );\n    }\n\n    // Initialize boolean that gets set to true once the file header is passed.\n    bool isHeaderPassed = 0;\n    bool isFirstLinePassed = 0;\n\n    // Line based parsing\n    std::string line;\n    std::vector< std::string > vectorOfIndividualStrings;\n\n    // Read file line-by-line\n    int numberOfDataLinesParsed = 0;\n    int numberOfIndependentVariables = -1;\n    while ( !stream.fail( ) && !stream.eof( ) )\n    {\n        // Get line from stream\n        std::getline( stream, line );\n\n        // Trim input string (removes all leading and trailing whitespaces).\n        boost::algorithm::trim( line );\n\n        // Skip empty and comment lines\n        if ( line.size( ) > 0 && !( line.at( 0 ) == '#' ) )\n        {\n            // Split string into multiple strings, each containing one element from a line from the data file.\n            boost::algorithm::split( vectorOfIndividualStrings,\n                                     line,\n                                     boost::algorithm::is_any_of( \"\\t ;, \" ),\n                                     boost::algorithm::token_compress_on );\n\n            // If this is the first line that is read, it should contain the number of independent variables\n            if ( !isFirstLinePassed )\n            {\n                if ( vectorOfIndividualStrings.size( ) != 1 )\n                {\n                    throw std::runtime_error( \"Error when reading multi-array, expected number of independent variables.\" );\n                }\n                numberOfIndependentVariables = std::stoi( vectorOfIndividualStrings.at( 0 ) );\n                isFirstLinePassed = true;\n            }            \n            // If the file header is not passed, this should contain the independent variables\n            else if ( !isHeaderPassed )\n            {\n                std::vector< double > currentDataPoints;\n                for ( unsigned int i = 0; i < vectorOfIndividualStrings.size( ); i++ )\n                {\n                    currentDataPoints.push_back( std::stod( vectorOfIndividualStrings.at( i ) ) );\n                }\n                independentVariables.push_back( currentDataPoints );\n            }\n            else if ( isHeaderPassed )\n            {\n                // Check line consistency\n                if ( vectorOfIndividualStrings.size( ) != static_cast< unsigned int >( coefficientBlock.cols( ) ) )\n                {\n                    throw std::runtime_error(\n                                \"Error on data line \" + std::to_string( numberOfDataLinesParsed ) +\n                                \" found \" + std::to_string( vectorOfIndividualStrings.size( ) ) +\n                                \" columns, but expected \" + std::to_string( coefficientBlock.cols( ) ) );\n                }\n                else if ( numberOfDataLinesParsed > coefficientBlock.rows( ) )\n                {\n                    throw std::runtime_error(\n                                \"Error on data line \" + std::to_string( numberOfDataLinesParsed ) +\n                                \" expected \" +  std::to_string( coefficientBlock.rows( ) ) + \"rows.\" );\n                }\n                else\n                {\n                    // Parse data from current line into output matrix.\n                    for ( unsigned int i = 0; i < vectorOfIndividualStrings.size( ); i++ )\n                    {\n                        coefficientBlock( numberOfDataLinesParsed, i ) =\n                                std::stod( vectorOfIndividualStrings.at( i ) );\n                    }\n                    numberOfDataLinesParsed++;\n                }\n            }\n\n            // If the number of independent variables read is the same as the number of independent variables that\n            // should be defined, allocate memory for output matrix.\n            if ( ( static_cast< int >( independentVariables.size( ) ) == numberOfIndependentVariables ) && !isHeaderPassed )\n            {\n                // Check input consistency\n                if ( independentVariables.size( ) == 0 )\n                {\n                    throw std::runtime_error( \"Error when reading multi-array, no header found.\" );\n                }\n                else\n                {\n                    // Get information on 4 dimensional file\n                    bool fourthDimensionAlongColumns = false;\n                    if ( independentVariables.size( ) == 4 )\n                    {\n                        // Get current position in file\n                        std::streampos currentPositionInFile = stream.tellg( );\n\n                        // Read and process next line\n                        std::getline( stream, line );\n                        while ( line.size( ) == 0 )\n                        {\n                            std::getline( stream, line );\n                        }\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\n                        // Detect way data was stored\n                        unsigned int numberOfColumnsInFile = vectorOfIndividualStrings.size( );\n                        if ( numberOfColumnsInFile == ( independentVariables.at( 1 ).size( ) * independentVariables.at( 3 ).size( ) ) )\n                        {\n                            fourthDimensionAlongColumns = true;\n                        }\n\n                        // Rewind to previous position\n                        stream.seekg( currentPositionInFile );\n                    }\n\n                    // Define size of output matrix, and allocate memory\n                    int numberOfRows = independentVariables.at( 0 ).size( );\n                    int numberOfColumns = 1;\n                    if ( independentVariables.size( ) > 1 )\n                    {\n                        if ( !fourthDimensionAlongColumns )\n                        {\n                            numberOfColumns = independentVariables.at( 1 ).size( );\n                            for ( unsigned int i = 2; i < independentVariables.size( ); i++ )\n                            {\n                                numberOfRows *= independentVariables.at( i ).size( );\n                            }\n                        }\n                        else\n                        {\n                            numberOfColumns = independentVariables.at( 1 ).size( ) * independentVariables.at( 3 ).size( );\n                            for ( unsigned int i = 2; i < independentVariables.size( ); i++ )\n                            {\n                                numberOfRows *= ( i != 3 ) ? independentVariables.at( i ).size( ) : 1;\n                            }\n                        }\n                    }\n                    coefficientBlock.setZero( numberOfRows, numberOfColumns );\n                }\n                isHeaderPassed = true;\n            }\n\n        }\n    }\n\n    if ( numberOfDataLinesParsed != coefficientBlock.rows( ) )\n    {\n        throw std::runtime_error(\n                    \"Error at end of coefficient file reader, found \" +\n                    std::to_string( numberOfDataLinesParsed ) +\n                    \" lines, but expected \" +  std::to_string( coefficientBlock.rows( ) ) + \"rows.\" );\n    }\n}\n\n//! Function to retrieve the number of independent variables that the coefficients in a file are given for.\nint getNumberOfIndependentVariablesInCoefficientFile( const std::string& fileName )\n{\n    // Open file and create file stream.\n    std::fstream stream( fileName.c_str( ), std::ios::in );\n\n    // Check if file opened correctly.\n    if ( stream.fail( ) )\n    {\n       throw std::runtime_error( \"Data file could not be opened: \" + fileName );\n    }\n\n    std::string line;\n    std::vector< std::string > vectorOfIndividualStrings;\n\n    // Retrieve number of independent variables from file.\n    int numberOfIndependentVariables = -1;\n    while ( !stream.fail( ) && !stream.eof( ) && ( numberOfIndependentVariables < 0 ) )\n    {\n        // Get line from stream\n        std::getline( stream, line );\n        boost::algorithm::trim( line );\n\n        if ( line.size( ) > 0 && !( line.at( 0 ) == '#' ) )\n        {\n            boost::algorithm::split( vectorOfIndividualStrings,\n                                     line,\n                                     boost::algorithm::is_any_of( \"\\t ;, \" ),\n                                     boost::algorithm::token_compress_on );\n            try\n            {\n                numberOfIndependentVariables = std::stod( vectorOfIndividualStrings.at( 0 ) );\n            }\n            catch( std::runtime_error )\n            {\n                throw std::runtime_error( \"Error when reading coefficicent file size, input is inconsistent.\" );\n            }\n        }\n    }\n    return numberOfIndependentVariables;\n}\n\n} // namespace input_output\n\n} // namespace tudat\n", "meta": {"hexsha": "d9846f0d6396d6e35cf9467dd6ffd391e1c73a1b", "size": 17060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/InputOutput/multiDimensionalArrayReader.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/InputOutput/multiDimensionalArrayReader.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/InputOutput/multiDimensionalArrayReader.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": 42.0197044335, "max_line_length": 141, "alphanum_fraction": 0.5298358734, "num_tokens": 3472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256832002764217, "lm_q2_score": 0.051082740929748405, "lm_q1q2_score": 0.013119682659672924}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/none.hpp>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <deque>\n\n#include \"DataStructures/DataVector.hpp\"\n\n/// \\ingroup ControlSystemGroup\n/// A weighted exponential averager of \\f$Q\\f$ and its derivatives\n/// implementing Appendix A in \\cite Hemberger2012jz\n///\n/// The purpose of the averager is to provide \\f$Q\\f$ and 'smoothed' numerical\n/// derivatives of \\f$Q\\f$ up to the `DerivOrder`'th derivative. The 0th\n/// derivative of \\f$Q\\f$ is not typically averaged, since no differencing is\n/// necessary and no noise is introduced. The `average_0th_deriv_of_q` option\n/// allows for specifying that the 0th derivative should be averaged in addition\n/// to the derivatives. This may be desirable for control systems where\n/// \\f$Q\\f$ contains some 'noise', e.g. size control typically uses an averaged\n/// \\f$Q\\f$ since the raw computed \\f$Q\\f$ is a function of the minimum on a\n/// surface and may jump around discontinuously.\n///\n/// The averager is designed to support an arbitrary DerivOrder, however the\n/// private get_derivs method currently only supports DerivOrder = 2.\n/// If an additional DerivOrder is needed, finite differencing needs to be\n/// implemented to specifically handle that order (as it seems like overkill to\n/// generalize the differencing stencil at this time).\ntemplate <size_t DerivOrder>\nclass Averager {\n public:\n  /// `avg_timescale_frac` determines the exponential averaging timescale\n  /// through \\f$\\tau_\\mathrm{avg} = \\f$`avg_timescale_frac`\\f$\\times \\tau\\f$,\n  /// where \\f$\\tau\\f$ is the damping time.\n  /// `avg_timescale_frac` must be positive.\n  /// `average_0th_deriv_of_q` determines whether the call operator returns an\n  /// averaged or unaveraged quantity for the 0th derivative of \\f$Q\\f$.\n  /// `true` returns an averaged 0th derivative of \\f$Q\\f$.\n  /// `false` returns the raw 0th derivative of \\f$Q\\f$.\n  /// The derivatives are always averaged (to reduce noise due to numerical\n  /// differentiation), so the `average_0th_deriv_of_q` option only specifies\n  /// whether to return an averaged value for the 0th derivative piece of the\n  /// function.\n  Averager(double avg_timescale_frac, bool average_0th_deriv_of_q) noexcept;\n\n  // Explicitly defined move constructor due to the fact that the std::deque\n  // move constructor is not marked noexcept\n  Averager(Averager&& rhs) noexcept;\n  Averager& operator=(Averager&& rhs) noexcept;\n  Averager(const Averager&) = delete;\n  Averager& operator=(const Averager&) = delete;\n  ~Averager() = default;\n\n  /// Returns \\f$Q\\f$ and its derivatives at \\f$t=\\f$`time`, provided there is\n  /// sufficient data. The averager is limited by the need for at least\n  /// (`DerivOrder` + 1) data points in order to provide the `DerivOrder`'th\n  /// derivative. If sufficient data is available, it returns \\f$Q\\f$ and\n  /// averaged derivatives of \\f$Q\\f$ up to the `DerivOrder`'th derivative, at\n  /// \\f$t=\\f$`time`. If `using_average_0th_deriv_of_q()` is `true`, then the\n  /// returned 0th derivative of \\f$Q\\f$ is also averaged. In the case that\n  /// there is insufficient data, the operator returns an\n  /// unitialized `boost::optional` (`boost::none`).\n  const boost::optional<std::array<DataVector, DerivOrder + 1>>& operator()(\n      double time) const noexcept;\n  /// A function that allows for resetting the averager.\n  void clear() noexcept;\n  /// The function responsible for updating the averaged values\n  /// at \\f$t=\\f$`time`. Requires `raw_q` (the raw components of \\f$Q(t)\\f$)\n  /// and `timescales` (the associated damping times for each component).\n  void update(double time, const DataVector& raw_q,\n              const DataVector& timescales) noexcept;\n  /// Returns the latest time at which the averager has sufficient data to\n  /// return \\f$Q\\f$ and its derivatives.\n  double last_time_updated() const noexcept;\n  /// Returns the exponentially averaged time at \\f$t=\\f$`time`. The time is\n  /// averaged along side \\f$Q\\f$ to determine the effective time at which\n  /// the average value is computed. The effective time is retarded, due to the\n  /// weighting of past times.\n  double average_time(double time) const noexcept;\n  /// Returns a bool corresponding to whether `average_0th_deriv_of_q`\n  /// is `true`/`false`.\n  bool using_average_0th_deriv_of_q() const noexcept {\n    return average_0th_deriv_of_q_;\n  };\n\n private:\n  /// Returns the function and numerical derivatives up to the\n  /// `DerivOrder`'th derivative using backward finite differencing that\n  /// supports non-uniform time spacing. Since we use a stencil size of\n  /// (`DerivOrder` + 1), the order of the finite difference varies for\n  /// different derivatives. Assuming \\f$M\\lte\\f$`DerivOrder`, the \\f$M\\f$'th\n  /// derivative is of order (`DerivOrder` + 1 - \\f$M\\f$).\n  ///\n  /// NOTE: the derivative function currently only supports DerivOrder = 2,\n  /// and contains a static_assert to guard against the possible instantiation\n  /// of another DerivOrder, for which finite differencing does not\n  /// currently support.\n  std::array<DataVector, DerivOrder + 1> get_derivs() const noexcept;\n\n  double avg_tscale_frac_;\n  bool average_0th_deriv_of_q_;\n  boost::optional<std::array<DataVector, DerivOrder + 1>> averaged_values_{};\n  boost::optional<std::array<DataVector, DerivOrder + 1>> boost_none_ =\n      boost::none;\n  std::deque<double> times_;\n  std::deque<DataVector> raw_qs_;\n  double weight_k_ = 0.0;\n  double tau_k_ = 0.0;\n};\n", "meta": {"hexsha": "6ac399ba9b39ad67466d0d7c68885b2ae7c6d91e", "size": 5558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ControlSystem/Averager.hpp", "max_stars_repo_name": "tomwlodarczyk/spectre", "max_stars_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ControlSystem/Averager.hpp", "max_issues_repo_name": "tomwlodarczyk/spectre", "max_issues_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ControlSystem/Averager.hpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "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": 48.7543859649, "max_line_length": 80, "alphanum_fraction": 0.7238215185, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.031618766242062835, "lm_q1q2_score": 0.013118589619349709}}
{"text": "//  Copyright (c) 2018-2019\r\n//  Cem Bassoy\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//  The authors gratefully acknowledge the support of\r\n//  Fraunhofer and Google in producing this work\r\n//  which started as a Google Summer of Code project.\r\n//\r\n\r\n\r\n/// \\file tensor.hpp Definition for the tensor template class\r\n\r\n#ifndef BOOST_UBLAS_TENSOR_IMPL_HPP\r\n#define BOOST_UBLAS_TENSOR_IMPL_HPP\r\n\r\n#include <boost/config.hpp>\r\n\r\n#include <initializer_list>\r\n\r\n#include \"algorithms.hpp\"\r\n#include \"expression.hpp\"\r\n#include \"expression_evaluation.hpp\"\r\n#include \"extents.hpp\"\r\n#include \"strides.hpp\"\r\n#include \"index.hpp\"\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\ntemplate<class T, class F, class A>\r\nclass tensor;\r\n\r\ntemplate<class T, class F, class A>\r\nclass matrix;\r\n\r\ntemplate<class T, class A>\r\nclass vector;\r\n\r\n///** \\brief Base class for Tensor container models\r\n// *\r\n// * it does not model the Tensor concept but all derived types should.\r\n// * The class defines a common base type and some common interface for all\r\n// * statically derived Tensor classes\r\n// * We implement the casts to the statically derived type.\r\n// */\r\n//template<class C>\r\n//class tensor_container:\r\n//\t\tpublic detail::tensor_expression<C>\r\n//{\r\n//public:\r\n//\tstatic const unsigned complexity = 0;\r\n//\ttypedef C container_type;\r\n//\ttypedef tensor_tag type_category;\r\n\r\n//\tBOOST_UBLAS_INLINE\r\n//\tconst container_type &operator () () const {\r\n//\t\t\treturn *static_cast<const container_type *> (this);\r\n//\t}\r\n//\tBOOST_UBLAS_INLINE\r\n//\tcontainer_type &operator () () {\r\n//\t\t\treturn *static_cast<container_type *> (this);\r\n//\t}\r\n//};\r\n\r\n\r\n\r\n/** @brief A dense tensor of values of type \\c T.\r\n\t\t*\r\n\t\t* For a \\f$n\\f$-dimensional tensor \\f$v\\f$ and \\f$0\\leq i < n\\f$ every element \\f$v_i\\f$ is mapped\r\n\t\t* to the \\f$i\\f$-th element of the container. A storage type \\c A can be specified which defaults to \\c unbounded_array.\r\n\t\t* Elements are constructed by \\c A, which need not initialise their value.\r\n\t\t*\r\n\t\t* @tparam T type of the objects stored in the tensor (like int, double, complex,...)\r\n\t\t* @tparam A The type of the storage array of the tensor. Default is \\c unbounded_array<T>. \\c <bounded_array<T> and \\c std::vector<T> can also be used\r\n\t\t*/\r\ntemplate<class T, class F = first_order, class A = std::vector<T,std::allocator<T>> >\r\nclass tensor:\r\n\t\tpublic detail::tensor_expression<tensor<T, F, A>,tensor<T, F, A>>\r\n{\r\n\r\n\tstatic_assert( std::is_same<F,first_order>::value ||\r\n\t\t\t\t\t\t\t\t std::is_same<F,last_order >::value, \"boost::numeric::tensor template class only supports first- or last-order storage formats.\");\r\n\r\n\tusing self_type  = tensor<T, F, A>;\r\npublic:\r\n\r\n\r\n\r\n\ttemplate<class derived_type>\r\n\tusing tensor_expression_type = detail::tensor_expression<self_type,derived_type>;\r\n\r\n\ttemplate<class derived_type>\r\n\tusing matrix_expression_type = matrix_expression<derived_type>;\r\n\r\n\ttemplate<class derived_type>\r\n\tusing vector_expression_type = vector_expression<derived_type>;\r\n\r\n\tusing super_type = tensor_expression_type<self_type>;\r\n\r\n//\tstatic_assert(std::is_same_v<tensor_expression_type<self_type>, detail::tensor_expression<tensor<T,F,A>,tensor<T,F,A>>>, \"tensor_expression_type<self_type>\");\r\n\r\n\tusing array_type  = A;\r\n\tusing layout_type = F;\r\n\r\n\r\n\tusing size_type       = typename array_type::size_type;\r\n\tusing difference_type = typename array_type::difference_type;\r\n\tusing value_type      = typename array_type::value_type;\r\n\r\n\tusing reference       = typename array_type::reference;\r\n\tusing const_reference = typename array_type::const_reference;\r\n\r\n\tusing pointer         = typename array_type::pointer;\r\n\tusing const_pointer   = typename array_type::const_pointer;\r\n\r\n\tusing iterator        = typename array_type::iterator;\r\n\tusing const_iterator  = typename array_type::const_iterator;\r\n\r\n\tusing reverse_iterator        = typename array_type::reverse_iterator;\r\n\tusing const_reverse_iterator  = typename array_type::const_reverse_iterator;\r\n\r\n\tusing tensor_temporary_type = self_type;\r\n\tusing storage_category = dense_tag;\r\n\r\n\tusing strides_type = basic_strides<std::size_t,layout_type>;\r\n\tusing extents_type = shape;\r\n\r\n\tusing matrix_type     = matrix<value_type,layout_type,array_type>;\r\n\tusing vector_type     = vector<value_type,array_type>;\r\n\r\n\r\n\t/** @brief Constructs a tensor.\r\n\t *\r\n\t * @note the tensor is empty.\r\n\t * @note the tensor needs to reshaped for further use.\r\n\t *\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\tconstexpr tensor ()\r\n\t\t: tensor_expression_type<self_type>() // container_type\r\n\t\t, extents_()\r\n\t\t, strides_()\r\n\t\t, data_()\r\n\t{\r\n\t}\r\n\r\n\r\n\t/** @brief Constructs a tensor with an initializer list\r\n\t *\r\n\t * By default, its elements are initialized to 0.\r\n\t *\r\n\t * @code tensor<float> A{4,2,3}; @endcode\r\n\t *\r\n\t * @param l initializer list for setting the dimension extents of the tensor\r\n\t */\r\n\texplicit BOOST_UBLAS_INLINE\r\n\ttensor (std::initializer_list<size_type> l)\r\n\t\t: tensor_expression_type<self_type>()\r\n\t\t, extents_ (std::move(l))\r\n\t\t, strides_ (extents_)\r\n\t\t, data_    (extents_.product())\r\n\t{\r\n\t}\r\n\r\n\r\n\t/** @brief Constructs a tensor with a \\c shape\r\n\t *\r\n\t * By default, its elements are initialized to 0.\r\n\t *\r\n\t * @code tensor<float> A{extents{4,2,3}}; @endcode\r\n\t *\r\n\t * @param s initial tensor dimension extents\r\n\t */\r\n\texplicit BOOST_UBLAS_INLINE\r\n\ttensor (extents_type const& s)\r\n\t\t: tensor_expression_type<self_type>() //tensor_container<self_type>()\r\n\t\t, extents_ (s)\r\n\t\t, strides_ (extents_)\r\n\t\t, data_    (extents_.product())\r\n\t{}\r\n\r\n\r\n\t/** @brief Constructs a tensor with a \\c shape and initiates it with one-dimensional data\r\n\t *\r\n\t * @code tensor<float> A{extents{4,2,3}, array }; @endcode\r\n\t *\r\n\t *\r\n\t *  @param s initial tensor dimension extents\r\n\t *  @param a container of \\c array_type that is copied according to the storage layout\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (extents_type const& s, const array_type &a)\r\n\t\t: tensor_expression_type<self_type>() //tensor_container<self_type>()\r\n\t\t, extents_ (s)\r\n\t\t, strides_ (extents_)\r\n\t\t, data_    (a)\r\n\t{\r\n\t\tif(this->extents_.product() != this->data_.size())\r\n\t\t\tthrow std::runtime_error(\"Error in boost::numeric::ublas::tensor: size of provided data and specified extents do not match.\");\r\n\t}\r\n\r\n\r\n\r\n\t/** @brief Constructs a tensor using a shape tuple and initiates it with a value.\r\n\t *\r\n\t *  @code tensor<float> A{extents{4,2,3}, 1 }; @endcode\r\n\t *\r\n\t *  @param e initial tensor dimension extents\r\n\t *  @param i initial value of all elements of type \\c value_type\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (extents_type const& e, const value_type &i)\r\n\t\t: tensor_expression_type<self_type>() //tensor_container<self_type> ()\r\n\t\t, extents_ (e)\r\n\t\t, strides_ (extents_)\r\n\t\t, data_    (extents_.product(), i)\r\n\t{}\r\n\r\n\r\n\r\n\t/** @brief Constructs a tensor from another tensor\r\n\t *\r\n\t *  @param v tensor to be copied.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (const tensor &v)\r\n\t\t: tensor_expression_type<self_type>()\r\n\t\t, extents_ (v.extents_)\r\n\t\t, strides_ (v.strides_)\r\n\t\t, data_    (v.data_   )\r\n\t{}\r\n\r\n\r\n\r\n\t/** @brief Constructs a tensor from another tensor\r\n\t *\r\n\t *  @param v tensor to be moved.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (tensor &&v)\r\n\t\t: tensor_expression_type<self_type>() //tensor_container<self_type> ()\r\n\t\t, extents_ (std::move(v.extents_))\r\n\t\t, strides_ (std::move(v.strides_))\r\n\t\t, data_    (std::move(v.data_   ))\r\n\t{}\r\n\r\n\r\n\t/** @brief Constructs a tensor with a matrix\r\n\t *\r\n\t * \\note Initially the tensor will be two-dimensional.\r\n\t *\r\n\t *  @param v matrix to be copied.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (const matrix_type &v)\r\n\t\t: tensor_expression_type<self_type>()\r\n\t\t, extents_ ()\r\n\t\t, strides_ ()\r\n\t\t, data_    (v.data())\r\n\t{\r\n\t\tif(!data_.empty()){\r\n\t\t\textents_ = extents_type{v.size1(),v.size2()};\r\n\t\t\tstrides_ = strides_type(extents_);\r\n\t\t}\r\n\t}\r\n\r\n\t/** @brief Constructs a tensor with a matrix\r\n\t *\r\n\t * \\note Initially the tensor will be two-dimensional.\r\n\t *\r\n\t *  @param v matrix to be moved.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (matrix_type &&v)\r\n\t\t: tensor_expression_type<self_type>()\r\n\t\t, extents_ {}\r\n\t\t, strides_ {}\r\n\t\t, data_    {}\r\n\t{\r\n\t\tif(v.size1()*v.size2() != 0){\r\n\t\t\textents_ = extents_type{v.size1(),v.size2()};\r\n\t\t\tstrides_ = strides_type(extents_);\r\n\t\t\tdata_    = std::move(v.data());\r\n\t\t}\r\n\t}\r\n\r\n\t/** @brief Constructs a tensor using a \\c vector\r\n\t *\r\n\t * @note It is assumed that vector is column vector\r\n\t * @note Initially the tensor will be one-dimensional.\r\n\t *\r\n\t *  @param v vector to be copied.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (const vector_type &v)\r\n\t\t: tensor_expression_type<self_type>()\r\n\t\t, extents_ ()\r\n\t\t, strides_ ()\r\n\t\t, data_    (v.data())\r\n\t{\r\n\t\tif(!data_.empty()){\r\n\t\t\textents_ = extents_type{data_.size(),1};\r\n\t\t\tstrides_ = strides_type(extents_);\r\n\t\t}\r\n\t}\r\n\r\n\t/** @brief Constructs a tensor using a \\c vector\r\n\t *\r\n\t *  @param v vector to be moved.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttensor (vector_type &&v)\r\n\t\t: tensor_expression_type<self_type>()\r\n\t\t, extents_ {}\r\n\t\t, strides_ {}\r\n\t\t, data_    {}\r\n\t{\r\n\t\tif(v.size() != 0){\r\n\t\t\textents_ = extents_type{v.size(),1};\r\n\t\t\tstrides_ = strides_type(extents_);\r\n\t\t\tdata_    = std::move(v.data());\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t/** @brief Constructs a tensor with another tensor with a different layout\r\n\t *\r\n\t * @param other tensor with a different layout to be copied.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttemplate<class other_layout>\r\n\ttensor (const tensor<value_type, other_layout> &other)\r\n\t\t: tensor_expression_type<self_type> ()\r\n\t\t, extents_ (other.extents())\r\n\t\t, strides_ (other.extents())\r\n\t\t, data_    (other.extents().product())\r\n\t{\r\n\t\tcopy(this->rank(), this->extents().data(),\r\n\t\t\t\t this->data(), this->strides().data(),\r\n\t\t\t\t other.data(), other.strides().data());\r\n\t}\r\n\r\n\t/** @brief Constructs a tensor with an tensor expression\r\n\t *\r\n\t * @code tensor<float> A = B + 3 * C; @endcode\r\n\t *\r\n\t * @note type must be specified of tensor must be specified.\r\n\t * @note dimension extents are extracted from tensors within the expression.\r\n\t *\r\n\t * @param expr tensor expression\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttemplate<class derived_type>\r\n\ttensor (const tensor_expression_type<derived_type> &expr)\r\n\t\t: tensor_expression_type<self_type> ()\r\n\t\t, extents_ ( detail::retrieve_extents(expr) )\r\n\t\t, strides_ ( extents_ )\r\n\t\t, data_    ( extents_.product() )\r\n\t{\r\n\t\tstatic_assert( detail::has_tensor_types<self_type, tensor_expression_type<derived_type>>::value,\r\n\t\t\t\t\t\t\t\t\t \"Error in boost::numeric::ublas::tensor: expression does not contain a tensor. cannot retrieve shape.\");\r\n\t\tdetail::eval( *this, expr );\r\n\t}\r\n\r\n\t/** @brief Constructs a tensor with a matrix expression\r\n\t *\r\n\t * @code tensor<float> A = B + 3 * C; @endcode\r\n\t *\r\n\t * @note matrix expression is evaluated and pushed into a temporary matrix before assignment.\r\n\t * @note extents are automatically extracted from the temporary matrix\r\n\t *\r\n\t * @param expr matrix expression\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttemplate<class derived_type>\r\n\ttensor (const matrix_expression_type<derived_type> &expr)\r\n\t\t: tensor(  matrix_type ( expr )  )\r\n\t{\r\n\t}\r\n\r\n\t/** @brief Constructs a tensor with a vector expression\r\n\t *\r\n\t * @code tensor<float> A = b + 3 * b; @endcode\r\n\t *\r\n\t * @note matrix expression is evaluated and pushed into a temporary matrix before assignment.\r\n\t * @note extents are automatically extracted from the temporary matrix\r\n\t *\r\n\t * @param expr vector expression\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttemplate<class derived_type>\r\n\ttensor (const vector_expression_type<derived_type> &expr)\r\n\t\t: tensor(  vector_type ( expr )  )\r\n\t{\r\n\t}\r\n\r\n\t/** @brief Evaluates the tensor_expression and assigns the results to the tensor\r\n\t *\r\n\t * @code A = B + C * 2;  @endcode\r\n\t *\r\n\t * @note rank and dimension extents of the tensors in the expressions must conform with this tensor.\r\n\t *\r\n\t * @param expr expression that is evaluated.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttemplate<class derived_type>\r\n\ttensor &operator = (const tensor_expression_type<derived_type> &expr)\r\n\t{\r\n\t\tdetail::eval(*this, expr);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\ttensor& operator=(tensor other)\r\n\t{\r\n\t\tswap (*this, other);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\ttensor& operator=(const_reference v)\r\n\t{\r\n\t\tstd::fill(this->begin(), this->end(), v);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t/** @brief Returns true if the tensor is empty (\\c size==0) */\r\n\tBOOST_UBLAS_INLINE\r\n\tbool empty () const {\r\n\t\treturn this->data_.empty();\r\n\t}\r\n\r\n\r\n\t/** @brief Returns the size of the tensor */\r\n\tBOOST_UBLAS_INLINE\r\n\tsize_type size () const {\r\n\t\treturn this->data_.size ();\r\n\t}\r\n\r\n\t/** @brief Returns the size of the tensor */\r\n\tBOOST_UBLAS_INLINE\r\n\tsize_type size (size_type r) const {\r\n\t\treturn this->extents_.at(r);\r\n\t}\r\n\r\n\t/** @brief Returns the number of dimensions/modes of the tensor */\r\n\tBOOST_UBLAS_INLINE\r\n\tsize_type rank () const {\r\n\t\treturn this->extents_.size();\r\n\t}\r\n\r\n\t/** @brief Returns the number of dimensions/modes of the tensor */\r\n\tBOOST_UBLAS_INLINE\r\n\tsize_type order () const {\r\n\t\treturn this->extents_.size();\r\n\t}\r\n\r\n\t/** @brief Returns the strides of the tensor */\r\n\tBOOST_UBLAS_INLINE\r\n\tstrides_type const& strides () const {\r\n\t\treturn this->strides_;\r\n\t}\r\n\r\n\t/** @brief Returns the extents of the tensor */\r\n\tBOOST_UBLAS_INLINE\r\n\textents_type const& extents () const {\r\n\t\treturn this->extents_;\r\n\t}\r\n\r\n\r\n\t/** @brief Returns a \\c const reference to the container. */\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_pointer data () const {\r\n\t\treturn this->data_.data();\r\n\t}\r\n\r\n\t/** @brief Returns a \\c const reference to the container. */\r\n\tBOOST_UBLAS_INLINE\r\n\tpointer data () {\r\n\t\treturn this->data_.data();\r\n\t}\r\n\r\n\t/** @brief Element access using a single index.\r\n\t *\r\n\t *  @code auto a = A[i]; @endcode\r\n\t *\r\n\t *  @param i zero-based index where 0 <= i < this->size()\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_reference operator [] (size_type i) const {\r\n\t\treturn this->data_[i];\r\n\t}\r\n\r\n\t/** @brief Element access using a single index.\r\n\t *\r\n\t *\r\n\t *  @code A[i] = a; @endcode\r\n\t *\r\n\t *  @param i zero-based index where 0 <= i < this->size()\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\treference operator [] (size_type i)\r\n\t{\r\n\t\treturn this->data_[i];\r\n\t}\r\n\r\n\r\n\t/** @brief Element access using a multi-index or single-index.\r\n\t *\r\n\t *\r\n\t *  @code auto a = A.at(i,j,k); @endcode or\r\n\t *  @code auto a = A.at(i);     @endcode\r\n\t *\r\n\t *  @param i zero-based index where 0 <= i < this->size() if sizeof...(is) == 0, else 0<= i < this->size(0)\r\n\t *  @param is zero-based indices where 0 <= is[r] < this->size(r) where  0 < r < this->rank()\r\n\t */\r\n\ttemplate<class ... size_types>\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_reference at (size_type i, size_types ... is) const {\r\n\t\tif constexpr (sizeof...(is) == 0)\r\n\t\t\treturn this->data_[i];\r\n\t\telse\r\n\t\t\treturn this->data_[detail::access<0ul>(size_type(0),this->strides_,i,std::forward<size_types>(is)...)];\r\n\t}\r\n\r\n\t/** @brief Element access using a multi-index or single-index.\r\n\t *\r\n\t *\r\n\t *  @code A.at(i,j,k) = a; @endcode or\r\n\t *  @code A.at(i) = a;     @endcode\r\n\t *\r\n\t *  @param i zero-based index where 0 <= i < this->size() if sizeof...(is) == 0, else 0<= i < this->size(0)\r\n\t *  @param is zero-based indices where 0 <= is[r] < this->size(r) where  0 < r < this->rank()\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttemplate<class ... size_types>\r\n\treference at (size_type i, size_types ... is) {\r\n\t\tif constexpr (sizeof...(is) == 0)\r\n\t\t\treturn this->data_[i];\r\n\t\telse\r\n\t\t\treturn this->data_[detail::access<0ul>(size_type(0),this->strides_,i,std::forward<size_types>(is)...)];\r\n\t}\r\n\r\n\r\n\r\n\r\n\t/** @brief Element access using a single index.\r\n\t *\r\n\t *\r\n\t *  @code A(i) = a; @endcode\r\n\t *\r\n\t *  @param i zero-based index where 0 <= i < this->size()\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_reference operator()(size_type i) const {\r\n\t\treturn this->data_[i];\r\n\t}\r\n\r\n\r\n\t/** @brief Element access using a single index.\r\n\t *\r\n\t *  @code A(i) = a; @endcode\r\n\t *\r\n\t *  @param i zero-based index where 0 <= i < this->size()\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\treference operator()(size_type i){\r\n\t\treturn this->data_[i];\r\n\t}\r\n\r\n\r\n\r\n\r\n\t/** @brief Generates a tensor index for tensor contraction\r\n\t *\r\n\t *\r\n\t *  @code auto Ai = A(_i,_j,k); @endcode\r\n\t *\r\n\t *  @param i placeholder\r\n\t *  @param is zero-based indices where 0 <= is[r] < this->size(r) where  0 < r < this->rank()\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\ttemplate<std::size_t I, class ... index_types>\r\n\tdecltype(auto) operator() (index::index_type<I> p, index_types ... ps) const\r\n\t{\r\n\t\tconstexpr auto N = sizeof...(ps)+1;\r\n\t\tif( N != this->rank() )\r\n\t\t\tthrow std::runtime_error(\"Error in boost::numeric::ublas::operator(): size of provided index_types does not match with the rank.\");\r\n\r\n\t\treturn std::make_pair( std::cref(*this),  std::make_tuple( p, std::forward<index_types>(ps)... ) );\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\t/** @brief Reshapes the tensor\r\n\t *\r\n\t *\r\n\t * (1) @code A.reshape(extents{m,n,o});     @endcode or\r\n\t * (2) @code A.reshape(extents{m,n,o},4);   @endcode\r\n\t *\r\n\t * If the size of this smaller than the specified extents than\r\n\t * default constructed (1) or specified (2) value is appended.\r\n\t *\r\n\t * @note rank of the tensor might also change.\r\n\t *\r\n\t * @param e extents with which the tensor is reshaped.\r\n\t * @param v value which is appended if the tensor is enlarged.\r\n\t */\r\n\tBOOST_UBLAS_INLINE\r\n\tvoid reshape (extents_type const& e, value_type v = value_type{})\r\n\t{\r\n\t\tthis->extents_ = e;\r\n\t\tthis->strides_ = strides_type(this->extents_);\r\n\r\n\t\tif(e.product() != this->size())\r\n\t\t\tthis->data_.resize (this->extents_.product(), v);\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\tfriend void swap(tensor& lhs, tensor& rhs) {\r\n\t\tstd::swap(lhs.data_   , rhs.data_   );\r\n\t\tstd::swap(lhs.extents_, rhs.extents_);\r\n\t\tstd::swap(lhs.strides_, rhs.strides_);\r\n\t}\r\n\r\n\r\n\t/// \\brief return an iterator on the first element of the tensor\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_iterator begin () const {\r\n\t\treturn data_.begin ();\r\n\t}\r\n\r\n\t/// \\brief return an iterator on the first element of the tensor\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_iterator cbegin () const {\r\n\t\treturn data_.cbegin ();\r\n\t}\r\n\r\n\t/// \\brief return an iterator after the last element of the tensor\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_iterator end () const {\r\n\t\treturn data_.end();\r\n\t}\r\n\r\n\t/// \\brief return an iterator after the last element of the tensor\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_iterator cend () const {\r\n\t\treturn data_.cend ();\r\n\t}\r\n\r\n\t/// \\brief Return an iterator on the first element of the tensor\r\n\tBOOST_UBLAS_INLINE\r\n\titerator begin () {\r\n\t\treturn data_.begin();\r\n\t}\r\n\r\n\t/// \\brief Return an iterator at the end of the tensor\r\n\tBOOST_UBLAS_INLINE\r\n\titerator end () {\r\n\t\treturn data_.end();\r\n\t}\r\n\r\n\t/// \\brief Return a const reverse iterator before the first element of the reversed tensor (i.e. end() of normal tensor)\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_reverse_iterator rbegin () const {\r\n\t\treturn data_.rbegin();\r\n\t}\r\n\r\n\t/// \\brief Return a const reverse iterator before the first element of the reversed tensor (i.e. end() of normal tensor)\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_reverse_iterator crbegin () const {\r\n\t\treturn data_.crbegin();\r\n\t}\r\n\r\n\t/// \\brief Return a const reverse iterator on the end of the reverse tensor (i.e. first element of the normal tensor)\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_reverse_iterator rend () const {\r\n\t\treturn data_.rend();\r\n\t}\r\n\r\n\t/// \\brief Return a const reverse iterator on the end of the reverse tensor (i.e. first element of the normal tensor)\r\n\tBOOST_UBLAS_INLINE\r\n\tconst_reverse_iterator crend () const {\r\n\t\treturn data_.crend();\r\n\t}\r\n\r\n\t/// \\brief Return a const reverse iterator before the first element of the reversed tensor (i.e. end() of normal tensor)\r\n\tBOOST_UBLAS_INLINE\r\n\treverse_iterator rbegin () {\r\n\t\treturn data_.rbegin();\r\n\t}\r\n\r\n\t/// \\brief Return a const reverse iterator on the end of the reverse tensor (i.e. first element of the normal tensor)\r\n\tBOOST_UBLAS_INLINE\r\n\treverse_iterator rend () {\r\n\t\treturn data_.rend();\r\n\t}\r\n\r\n\r\n#if 0\r\n\t// -------------\r\n\t// Serialization\r\n\t// -------------\r\n\r\n\t/// Serialize a tensor into and archive as defined in Boost\r\n\t/// \\param ar Archive object. Can be a flat file, an XML file or any other stream\r\n\t/// \\param file_version Optional file version (not yet used)\r\n\ttemplate<class Archive>\r\n\tvoid serialize(Archive & ar, const unsigned int /* file_version */){\r\n\t\tar & serialization::make_nvp(\"data\",data_);\r\n\t}\r\n#endif\r\n\r\n\r\n\r\nprivate:\r\n\r\n\textents_type extents_;\r\n\tstrides_type strides_;\r\n\tarray_type data_;\r\n};\r\n\r\n}}} // namespaces\r\n\r\n\r\n\r\n\r\n\r\n#endif\r\n", "meta": {"hexsha": "10c5a6027a760bd1c30b9db7481551def05f890e", "size": 20384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/numeric/ublas/tensor/tensor.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": 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": "deps/boost/include/boost/numeric/ublas/tensor/tensor.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": 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": "deps/boost/include/boost/numeric/ublas/tensor/tensor.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": 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": 27.7333333333, "max_line_length": 162, "alphanum_fraction": 0.6609105181, "num_tokens": 5377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.0440186542523378, "lm_q1q2_score": 0.013094226553983228}}
{"text": "﻿/*! \\file eigenvaluesearch.cpp\n    \\brief エネルギー固有値検索を行うクラスの実装\n\n    Copyright ©  2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"eigenvaluesearch.h\"\n#include <cmath>                // for std::fabs, std::log10\n#include <iomanip>              // for std::setprecision\n#include <iostream>             // for std::cot, std::cerr\n#include <boost/assert.hpp>     // for BOOST_ASSERT\n#include <boost/cast.hpp>       // for boost::numeric_cast\n#include <gsl/gsl_errno.h>      // for GSL_SUCCESS\n#include <gsl/gsl_roots.h>      // for gsl_root_fsolver\n\nnamespace schrac {\n    // #region staticメンバ変数\n\n    bool EigenValueSearch::nodeok = false;\n\n    // #endregion staticメンバ変数 \n\n    // #region コンストラクタ\n\n    EigenValueSearch::EigenValueSearch(std::shared_ptr<Data> const & pdata, std::shared_ptr<DiffData> const & pdiffdata, std::shared_ptr<Rho> const & prho, std::shared_ptr<Vhartree> const & pvh) :\n        PData([this]() { return std::cref(pdata_); }, nullptr),\n        PDiffSolver([this]() { return std::cref(pdiffsolver_); }, nullptr),\n        loop_(1),\n        pdata_(pdata),\n        pdiffdata_(pdiffdata),\n        pvh_(pvh)\n    {\n        initialize(prho);\n        setoutstream();\n    }\n\n    // #endregion コンストラクタ\n\n    // #region publicメンバ関数\n\n    bool EigenValueSearch::search()\n    {\n        for (; loop_ < EigenValueSearch::EVALSEARCHMAX; loop_++) {\n            if (!rough_search()) {\n                return false;\n            }\n\n            if (brent() && EigenValueSearch::nodeok) {\n                return true;\n            }\n            else {\n                pdiffsolver_->E_ += DE_;\n\n                if (pdiffsolver_->E_ > 0.0) {\n                    return false;\n                }\n            }\n        }\n\n        return false;\n    }\n\n    // #endregion publicメンバ関数\n\n    // #region privateメンバ関数\n\n    bool EigenValueSearch::brent()\n    {\n        std::unique_ptr<gsl_root_fsolver, decltype(&gsl_root_fsolver_free)> s(\n            gsl_root_fsolver_alloc(gsl_root_fsolver_brent),\n            gsl_root_fsolver_free);\n\n        gsl_function F;\n\n        F.function = &func_D;\n        F.params = reinterpret_cast<void *>(pdiffsolver_.get());\n\n        gsl_root_fsolver_set(s.get(), &F, Emin_, Emax_);\n\n        for (; loop_ < EVALSEARCHMAX; loop_++) {\n            auto const ret = gsl_root_fsolver_iterate(s.get());\n\n            switch (ret)\n            {\n            case GSL_EBADFUNC:\n                std::cerr << \"the iteration encountered a singular point where\"\n                    << \"the function or its derivative evaluated to Inf or NaN.\\n\";\n                    return false;\n                break;\n\n            case GSL_EZERODIV:\n                std::cerr << \"the derivative of the function vanished at the iteration point,\"\n                    << \"preventing the algorithm from continuing without a division by zero.\\n\";\n                    return false;\n                break;\n\n            default:\n                break;\n            }\n\n            if (pdata_->chemical_symbol_ == Data::Chemical_Symbol[0]) {\n                info(func_D(pdiffsolver_->E_, F.params), pdiffsolver_->E_);\n            }\n\n            pdiffsolver_->E_ = gsl_root_fsolver_root(s.get());\n            \n            auto const status = gsl_root_test_interval(\n                gsl_root_fsolver_x_lower(s.get()),\n                gsl_root_fsolver_x_upper(s.get()),\n                0.0,\n                pdata_->eps_);\n\n            if (status == GSL_SUCCESS) {\n                break;\n            }\n        }\n\n        return loop_ != EVALSEARCHMAX;\n    }\n\n    void EigenValueSearch::info() const\n    {\n        std::cout << \"i = \" << loop_ << \", D = \" << Dold << \", node = \"\n            << pdiffdata_->thisnode_;\n\n        if (EigenValueSearch::nodeok) {\n            std::cout << \" (OK)\" << std::endl;\n        } \n        else {\n            std::cout << \" (NG)\" << std::endl;\n        }\n    }\n        \n    void EigenValueSearch::info(double D, double E) const\n    {\n        std::cout << \"i = \" << loop_ << \", D = \"\n            << D << \", E = \" << E\n            << \", node = \"\n            << pdiffdata_->thisnode_;\n\n        if (EigenValueSearch::nodeok) {\n            std::cout << \" (OK)\" << std::endl;\n        } \n        else {\n            std::cout << \" (NG)\" << std::endl;\n        }\n    }\n\n    void EigenValueSearch::initialize(std::shared_ptr<Rho> const & prho)\n    {\n        switch (pdata_->eq_type_) {\n        case Data::Eq_type::SCH:\n                Eapprox_ = Eapprox_sch(pdata_);\n            break;\n\n        case Data::Eq_type::SDIRAC:\n        case Data::Eq_type::DIRAC:\n                Eapprox_ = Eapprox_dirac(pdata_);\n            break;\n\n        default:\n                BOOST_ASSERT(\"何かがおかしい！！\");\n            break;\n        }\n\n        pdiffsolver_ = std::make_shared<DiffSolver>(pdata_, pdiffdata_, prho, pvh_);\n\n        if (pdata_->search_lowerE_) {\n            pdiffsolver_->E_ = *pdata_->search_lowerE_;\n            DE_ = - pdiffsolver_->E_ / static_cast<double>(pdata_->num_of_partition_);\n        } else {\n            pdiffsolver_->E_ = Eapprox_;\n            DE_ = - pdiffsolver_->E_ / static_cast<double>(pdata_->num_of_partition_);\n            pdiffsolver_->E_ -= 3.0 * DE_;\n        }\n    }\n\n    bool EigenValueSearch::rough_search()\n    {\n        auto pdiffsolver = reinterpret_cast<void *>(pdiffsolver_.get());\n        Dold = func_D(pdiffsolver_->E_, pdiffsolver);\n\n        if (pdata_->chemical_symbol_ == Data::Chemical_Symbol[0]) {\n            info();\n        }\n\n        ++loop_;\n\n        for (; loop_ < EVALSEARCHMAX; loop_++) {\n            pdiffsolver_->E_ += DE_;\n\n            if (pdiffsolver_->E_ > 0.0) {\n                return false;\n            }\n\n            auto const Dnew = func_D(pdiffsolver_->E_, pdiffsolver);\n     \n            if (Dnew * Dold < 0.0) {\n                Emax_ = pdiffsolver_->E_;\n                Emin_ = pdiffsolver_->E_ - DE_;\n\n                break;\n            } else {\n                Dold = Dnew;\n            }\n\n            if (pdata_->chemical_symbol_ == Data::Chemical_Symbol[0]) {\n                info();\n            }\n        }\n\n        return loop_ != EVALSEARCHMAX;\n    }\n\n    void EigenValueSearch::setoutstream() const\n    {\n        std::cout.setf(std::ios::fixed, std::ios::floatfield);\n        std::cout << std::setprecision(\n            boost::numeric_cast<std::streamsize>(std::fabs(std::log10(pdata_->eps_))));\n    }\n    \n    // #endregion privateメンバ関数 \n\n    // #region 非メンバ関数\n\n    double func_D(double E, void * params)\n    {\n        auto pdiffsolver = reinterpret_cast<DiffSolver *>(params);\n        pdiffsolver->initialize(E);\n        pdiffsolver->solve_diff_equ();\n\n        EigenValueSearch::nodeok = \n            pdiffsolver->PDiffData()->node_ == pdiffsolver->PDiffData()->thisnode_;\n\n        auto [L, M] = pdiffsolver->getMPval();\n        return M[0] - (L[0] / L[1]) * M[1];\n    }\n\n    double Eapprox_dirac(std::shared_ptr<Data> const & pdata)\n    {\n        auto const nr = static_cast<double>(pdata->n_) - pdata->j_ - 0.5;\n        auto const lambda = std::sqrt(sqr(pdata->kappa_) - sqr(pdata->Z_ / Data::c));\n        auto const denominator = std::sqrt(sqr(nr + lambda) + sqr(pdata->Z_ / Data::c));\n\n        return ((nr + lambda) / denominator - 1.0) * sqr(Data::c);\n    }\n\n    double Eapprox_sch(std::shared_ptr<Data> const & pdata)\n    {\n        return -sqr(pdata->Z_ / static_cast<double>(pdata->n_)) / 2.0;\n    }\n\n    // #endregion 非メンバ関数\n}\n", "meta": {"hexsha": "bb9b4a53ae6a906b895b45b854febc00ee87c122", "size": 7448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigenvaluesearch.cpp", "max_stars_repo_name": "dc1394/Schrac", "max_stars_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T23:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T07:10:30.000Z", "max_issues_repo_path": "src/eigenvaluesearch.cpp", "max_issues_repo_name": "dc1394/schrac", "max_issues_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "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/eigenvaluesearch.cpp", "max_forks_repo_name": "dc1394/schrac", "max_forks_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "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.09375, "max_line_length": 196, "alphanum_fraction": 0.5249731472, "num_tokens": 1942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.028870908721893265, "lm_q1q2_score": 0.013086081014717905}}
{"text": "#include <cstdlib>\n#include <sstream>\n#include <iostream>\n#include <vector>\n#include <limits>\n#include <cmath>\n\n#if HAVE_NEW_CXX\n# include <unordered_map>\n# include <unordered_set>\n#else\n# include <tr1/unordered_map>\n# include <tr1/unordered_set>\nnamespace std { using std::tr1::unordered_map; using std::tr1::unordered_set; }\n#endif\n\n#include <signal.h>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"json_feature_map_lexer.h\"\n#include \"fdict.h\"\n#include \"feature_map.h\"\n#include \"prob.h\"\n#include \"filelib.h\"\n#include \"liblbfgs/lbfgs++.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvolatile bool* requested_stop = NULL;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"linear,n\", \"Linear regression (default is multiclass logistic regression)\")\n        (\"ordinal,o\", \"Ordinal regression (proportional odds)\")\n        (\"training_features,x\", po::value<vector<string> >(), \"Files containing training instance features\")\n        (\"training_responses,y\", po::value<string>(), \"File containing training instance responses (if unspecified, do prediction only)\")\n        (\"tx\", po::value<vector<string> >(), \"File containing test instance features\")\n        (\"ty\", po::value<string>(), \"File containing test instance responses (optional)\")\n        (\"z\", po::value<string>(), \"Write learned weights to this file (optional)\")\n        (\"write_test_predictions,p\", \"Write model prediction for each test instance\")\n        (\"write_test_distribution,D\", \"Write posterior distribution of outputs for each test instance (categorical models only)\")\n        (\"dont_write_weights,W\", \"Supress writing learned weights\")\n        (\"multiclass_test_probability_threshold,P\", po::value<double>()->default_value(0.0), \"When evaluating a multiclass model, only compute the accuracy on instances where the predicted class posterior probability is > P\")\n        (\"l1\",po::value<double>()->default_value(0.0), \"l_1 regularization strength\")\n        (\"l2\",po::value<double>()->default_value(1e-10), \"l_2 regularization strength\")\n        (\"temperature,T\",po::value<double>()->default_value(0), \"Temperature for entropy regularization (> 0 flattens, < 0 sharpens; = 0 no effect)\")\n        (\"weights,w\", po::value<string>(), \"Initial weights file\")\n        (\"epsilon,e\", po::value<double>()->default_value(1e-4), \"Epsilon for convergence test. Terminates when ||g|| < epsilon * max(1, ||w||)\")\n        (\"delta,d\", po::value<double>()->default_value(0), \"Delta for convergence test. Terminates when (f' - f) / f < delta\")\n        (\"memory_buffers,m\",po::value<unsigned>()->default_value(40), \"Number of memory buffers for LBFGS\")\n        (\"test_features,t\", po::value<string>(), \"[deprecated option, use --tx] File containing test instance features\")\n        (\"test_responses,s\", po::value<string>(), \"[deprecated option, use --ty] File containing test response features (ARKRegression format)\")\n        (\"help,h\", \"Help\");\n  po::options_description dcmdline_options;\n  dcmdline_options.add(opts);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  bool prediction_only = !conf->count(\"training_responses\");\n  if (conf->count(\"help\") || (prediction_only && (!conf->count(\"weights\") || !conf->count(\"tx\")))) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nenum RegressionType { kLINEAR, kLOGISTIC, kORDINAL };\n\nstruct TrainingInstance {\n  FrozenFeatureMap x;\n  union {\n    unsigned label;  // for categorical & ordinal predictions\n    float value;     // for continuous predictions\n  } y;\n};\n\nstruct ReaderHelper {\n  explicit ReaderHelper(vector<TrainingInstance>* xyp,\n                        bool h,\n                        vector<string>* iids) : xy_pairs(xyp), lc(), flag(), has_labels(h), ids(iids), merge() {}\n  unordered_map<string, unsigned> id2ind;\n  FeatureMapStorage* fms;\n  vector<TrainingInstance>* xy_pairs;\n  int lc;\n  bool flag;\n  bool has_labels;\n  vector<string>* ids;\n  vector<bool> merged;\n  bool merge;\n};\n\nvoid ReaderCB(const string& id,\n              const std::pair<int,float>* begin,\n              const std::pair<int,float>* end,\n              void* extra) {\n  ReaderHelper& rh = *reinterpret_cast<ReaderHelper*>(extra);\n  ++rh.lc;\n  if (rh.lc % 1000  == 0) { cerr << '.'; rh.flag = true; }\n  if (rh.lc % 50000 == 0) { cerr << \" [\" << rh.lc << \"]\\n\"; rh.flag = false; }\n  if (rh.ids && !rh.merge) rh.ids->push_back(id);\n  if (rh.has_labels) {\n    const unordered_map<string, unsigned>::iterator it = rh.id2ind.find(id);\n    if (it == rh.id2ind.end()) {\n      cerr << \"\\nUnlabeled example in line \" << rh.lc << \" (key=\" << id << ')' << endl;\n      abort();\n    } else {\n      if (rh.merge) {\n        rh.merged[it->second - 1] = true;\n        const FrozenFeatureMap& prev = (*rh.xy_pairs)[it->second - 1].x;\n        (*rh.xy_pairs)[it->second - 1].x = rh.fms->AddFeatureMap(begin,end,prev);\n      } else {\n        (*rh.xy_pairs)[it->second - 1].x = rh.fms->AddFeatureMap(begin,end);\n      }\n    }\n  } else {\n    TrainingInstance x_no_y;\n    if (rh.merge) {\n      if (!rh.ids) {\n        cerr << \"Missing IDs\\n\";\n        abort();\n      }\n      unsigned& ind = rh.id2ind[id];\n      rh.merged[ind - 1] = true;\n      const FrozenFeatureMap& prev = (*rh.xy_pairs)[ind - 1].x;\n      (*rh.xy_pairs)[ind - 1].x = rh.fms->AddFeatureMap(begin,end,prev);\n    } else {\n      x_no_y.x = rh.fms->AddFeatureMap(begin,end);\n      unsigned& ind = rh.id2ind[id];\n      assert(ind == 0);\n      rh.xy_pairs->push_back(x_no_y);\n      ind = rh.xy_pairs->size();\n    }\n  }\n}\n\nvoid ReadWeightsMulticlass(const string& fname,\n                           vector<string>* plabels,\n                           vector<double>* pw) {\n  map<string, unsigned> lm;\n  vector<string>& labels = *plabels;\n  vector<double>& weights = *pw;\n// 3\t***CATEGORICAL***\tIris-versicolor\tIris-setosa\tIris-virginica\n  ReadFile rf(fname);\n  istream& in = *rf.stream();\n  unsigned rk; // read K\n  string cat;\n  in >> rk >> cat;\n  if (cat != \"***CATEGORICAL***\") {\n    cerr << \"Unexpected weights type: \" << cat << endl;\n    abort();\n  }\n  bool has_labels = labels.size() > 0;\n  for (unsigned i = 0; i < rk; ++i) {\n    string f;\n    in >> f;\n    if (has_labels) {\n      if (labels[i] != f) { cerr << \"Bad label order: \" << labels[i] << \" != \" << f << endl; abort(); }\n    } else {\n      labels.push_back(f);\n    }\n  }\n  for (unsigned i = 0; i < labels.size(); ++i)\n    lm[labels[i]] = i;\n  const unsigned K = labels.size();\n// Iris-versicolor\t***BIAS***\t17.619343957411\n// Iris-setosa\t***BIAS***\t28.1532494500727\n//  Iris-versicolor\tpetal-length\t-2.69876613900064\n  string l,f;\n  double w;\n  weights.resize((1 + FD::NumFeats()) * (labels.size() - 1), 0.0);\n  for (unsigned i = 1; i < K; ++i) {\n    in >> l >> f >> w;\n    if (f != \"***BIAS***\") { cerr << \"Bad format!\\n\"; abort(); }\n    weights[lm[l]] = w;\n  }\n  unsigned p = FD::NumFeats();\n  FD::Freeze();\n  string fl;\n  unsigned total = 0;\n  unsigned skipped = 0;\n  getline(in, fl); // extra newline after >> reading\n  while(getline(in, fl)) {\n    ++total;\n    size_t first_field_end = fl.find('\\t');\n    size_t second_field_end = fl.rfind('\\t');\n    if (first_field_end == string::npos || second_field_end == string::npos || first_field_end == second_field_end) {\n      cerr << \"Badly formatted weight: \" << fl << endl;\n      abort();\n    }\n    unsigned y = lm[fl.substr(0, first_field_end)];\n    unsigned fid = FD::Convert(fl.substr(first_field_end+1,second_field_end - first_field_end - 1));\n    double w = strtod(&fl[second_field_end+1], NULL);\n    if (!fid) {\n      // cerr << \"Skipping feature \" << FD::Convert(fid) << endl;\n      ++skipped;\n    } else {\n      weights[(K - 1) + y * p + fid] = w;\n    }\n  }\n  if (skipped) {\n    cerr << \"Skipped \" << skipped << \" unneeded features of \" << total << \" total features\\n\";\n  }\n}\n\nvoid ReadWeightsLinear(const string& fname,\n                       vector<double>* pw) {\n  map<string, unsigned> lm;\n  vector<double>& weights = *pw;\n  // 6\t***CONTINUOUS***\n\n  ReadFile rf(fname);\n  istream& in = *rf.stream();\n  unsigned rk; // read K\n  string cat;\n  in >> rk >> cat;\n  if (cat != \"***CONTINUOUS***\") {\n    cerr << \"Unexpected weights type: \" << cat << endl;\n    abort();\n  }\n  weights.resize(1 + FD::NumFeats(), 0.0);\n  string f;\n  double w;\n  in >> f >> w;\n  if (f != \"***BIAS***\") { cerr << \"Bad format!\\n\"; abort(); }\n  weights[0] = w;\n  // ***BIAS***\t44.1115567293068\n  // horsepower\t-0.0366264048792159\n  // acceleration\t-0.0140216308150685\n\n  FD::Freeze();\n  string fl;\n  unsigned total = 0;\n  unsigned skipped = 0;\n  getline(in, fl); // extra newline after >> reading\n  while(getline(in, fl)) {\n    ++total;\n    size_t first_field_end = fl.find('\\t');\n    if (first_field_end == string::npos) {\n      cerr << \"Badly formatted weight: \" << fl << endl;\n      abort();\n    }\n    unsigned fid = FD::Convert(fl.substr(0, first_field_end));\n    double w = strtod(&fl[first_field_end+1], NULL);\n    if (!fid) {\n      // cerr << \"Skipping feature \" << FD::Convert(fid) << endl;\n      ++skipped;\n    } else {\n      weights[fid + 1] = w;\n    }\n  }\n  if (skipped) {\n    cerr << \"Skipped \" << skipped << \" unneeded features of \" << total << \" total features\\n\";\n  }\n}\n\nvoid ReadLabeledInstances(const vector<string>& ffeats,\n                          const string& fresp,\n                          const RegressionType resptype,\n                          FeatureMapStorage* fms,\n                          vector<TrainingInstance>* xy_pairs,\n                          vector<string>* labels,\n                          vector<string>* instance_ids = NULL) {\n  bool flag = false;\n  xy_pairs->clear();\n  int lc = 0;\n  ReaderHelper rh(xy_pairs, fresp.size() > 0, instance_ids);\n  rh.merge = false;\n  unordered_map<string, unsigned> label2id;\n  if (fresp.size() == 0) {\n    cerr << \"No gold standard responses provided to learn from!\" << endl;\n  } else {\n    cerr << \"Reading responses from \" << fresp << \" ...\" << endl;\n    ReadFile fr(fresp);\n    for (unsigned i = 0; i < labels->size(); ++i)\n      label2id[(*labels)[i]] = i;\n    istream& in = *fr.stream();\n    string line;\n    while(getline(in, line)) {\n      ++lc;\n      if (lc % 1000 == 0) { cerr << '.'; flag = true; }\n      if (lc % 40000 == 0) { cerr << \" [\" << lc << \"]\\n\"; flag = false; }\n      if (line.size() == 0) continue;\n      if (line[0] == '#') {\n        if (line.size() > 1 && line[1] == '#') {\n          if (lc != 1) {\n            cerr << \"[WARNING] Line \" << lc << \" appears to be label declaration ... ignoring\\n\";\n          } else {\n            istringstream is(line);\n            string label;\n            is >> label;\n            while(is >> label) {\n              unordered_map<string, unsigned>::iterator it = label2id.find(label);\n              if (it == label2id.end()) {\n                it = label2id.insert(make_pair(label, labels->size())).first;\n                labels->push_back(label);\n              }\n            }\n          }\n        }\n        continue;\n      }\n      unsigned p = 0;\n      while (p < line.size() && line[p] != ' ' && line[p] != '\\t') { ++p; }\n      unsigned& ind = rh.id2ind[line.substr(0, p)];\n      if (ind != 0) { cerr << \"ID \" << line.substr(0, p) << \" duplicated in line \" << lc << endl; abort(); }\n      while (p < line.size() && (line[p] == ' ' || line[p] == '\\t')) { ++p; }\n      assert(p < line.size());\n      xy_pairs->push_back(TrainingInstance());\n      ind = xy_pairs->size();\n      switch (resptype) {\n        case kLINEAR:\n          xy_pairs->back().y.value = strtof(&line[p], 0);\n          break;\n        case kLOGISTIC:\n          {\n            unordered_map<string, unsigned>::iterator it = label2id.find(line.substr(p));\n            if (it == label2id.end()) {\n              const string label = line.substr(p);\n              it = label2id.insert(make_pair(label, labels->size())).first;\n              labels->push_back(label);\n            }\n            xy_pairs->back().y.label = it->second;  // label id\n          }\n          break;\n        case kORDINAL:\n          {\n            // TODO allow labels not to be consecutive and start from 0 \n            // requires label re-indexing\n            const unsigned label = strtol(&line[p], 0, 10);\n            xy_pairs->back().y.label = label;\n            if (label >= labels->size()) {\n              labels->resize(label + 1);\n            }\n            (*labels)[label] = line.substr(p);\n          }\n          break;\n      }\n    }\n    if (flag) cerr << endl;\n    if (resptype == kLOGISTIC || resptype == kORDINAL) {\n      cerr << \"LABELS:\";\n      for (unsigned j = 0; j < labels->size(); ++j)\n        cerr << \" \" << (*labels)[j];\n      cerr << endl;\n    }\n  }\n  FeatureMapStorage* pfms = NULL;\n  FeatureMapStorage* tfms = NULL;\n  for (unsigned i = 0; i < ffeats.size(); ++i) {\n    if (i == ffeats.size() - 1) {\n      pfms = tfms;\n      rh.fms = fms;\n    } else {\n      delete pfms;\n      pfms = tfms;\n      tfms = new FeatureMapStorage;\n      rh.fms = tfms;\n    }\n    if (pfms) {\n      rh.merge = true;\n      rh.merged.clear();\n      rh.merged.resize(rh.xy_pairs->size(), false);\n    }\n    const string& ffeat = ffeats[i];\n    cerr << \"Reading features from \" << ffeat << \" ...\" << endl;\n    ReadFile ff(ffeat);\n    JSONFeatureMapLexer::ReadRules(ff.stream(), ReaderCB, &rh);\n    if (pfms) {\n      for (unsigned j = 0; j < rh.xy_pairs->size(); ++j)\n        if (!rh.merged[j])\n          (*rh.xy_pairs)[j].x = rh.fms->AddFeatureMap(NULL, NULL, (*rh.xy_pairs)[j].x);\n    }\n    if (rh.flag) cerr << endl;\n  }\n  delete pfms;\n}\n\n// helper base class (not polymorphic- just a container and some helper functions) for loss functions\n// real loss functions should implement double operator()(const vector<double>& x, double* g),\n// which should evaluate f(x) and g = f'(x)\nstruct BaseLoss {\n  // dimp1 = number of categorial outputs possible for logistic regression\n  // for linear regression, it should be 1 more than the dimension of the response variable\n  BaseLoss(\n      const vector<TrainingInstance>& tr,\n      unsigned dimp1,\n      unsigned numfeats,\n      unsigned ll2) : training(tr), K(dimp1), p(numfeats), l2(ll2) {}\n\n  // w.x (bias excluded)\n  template <class FeatureMapType>\n  double DotProduct(const FeatureMapType& fx,\n                    const vector<double>& w) const {\n    const unsigned km1 = K - 1;\n    double dotproduct = 0;\n    for (typename FeatureMapType::const_iterator it = fx.begin(); it != fx.end(); ++it)\n      dotproduct += w[it->first + km1] * it->second;\n    return dotproduct;\n  }\n\n  double ApplyRegularizationTerms(const vector<double>& weights,\n                                  double* g) const {\n    double reg = 0;\n    for (size_t i = K - 1; i < weights.size(); ++i) {\n      const double& w_i = weights[i];\n      reg += l2 * w_i * w_i;\n      g[i] += 2 * l2 * w_i;\n    }\n    return reg;\n  }\n\n  template <class FeatureMapType>\n  void GradAdd(const FeatureMapType& fx,\n               const unsigned y,\n               const double scale,\n               double* acc) const {\n    acc[y] += scale; // class bias\n    for (typename FeatureMapType::const_iterator it = fx.begin();\n         it != fx.end(); ++it)\n      acc[it->first + y * p + K - 1] += it->second * scale;\n  }\n\n  const vector<TrainingInstance>& training;\n  const unsigned K, p;\n  const double l2;\n};\n\nstruct UnivariateSquaredLoss : public BaseLoss {\n\n  // weight vector layout for p features\n  //   w[0] = bias weight\n  //   w[1 : p] = feature weights\n\n  UnivariateSquaredLoss(\n          const vector<TrainingInstance>& tr,\n          unsigned numfeats,\n          const double l2) : BaseLoss(tr, 2, numfeats, l2) {}\n\n  template <class FeatureMapType>\n  double Predict(const FeatureMapType& fx, const vector<double>& w) const {\n    return DotProduct(fx, w) + w[0];\n  }\n\n  // evaluate squared loss and gradient\n  double operator()(const vector<double>& x, double* g) const {\n    fill(g, g + x.size(), 0.0);\n    double cll = 0;\n    for (unsigned i = 0; i < training.size(); ++i) {\n      const FrozenFeatureMap& fmapx = training[i].x;\n      const double refy = training[i].y.value;\n      const double predy = Predict(fmapx, x);\n      const double diff = predy - refy;\n      cll += diff * diff;\n      GradAdd(fmapx, 0, 2 * diff, g);\n    }\n    const double reg = ApplyRegularizationTerms(x, g);\n    return cll + reg;\n  }\n\n  // return RMSE\n  double Evaluate(const vector<TrainingInstance>& test,\n                  const vector<double>& w,\n                  vector<float>* preds = NULL) const {\n    vector<double> dotprods(1);  // K-1 degrees of freedom\n    double mse = 0;\n    if (preds) preds->resize(test.size());\n    for (unsigned i = 0; i < test.size(); ++i) {\n      const double predy = Predict(test[i].x, w);\n      if (preds) (*preds)[i] = predy;\n      const double refy = test[i].y.value;\n      const double diff = predy - refy;\n      //cerr << \"line=\" << (i+1) << \" true=\" << refy << \" pred=\" << predy << endl;\n      mse += diff * diff;\n    }\n    mse /= test.size();\n    return sqrt(mse);\n  }\n};\n\n// predictions made by multiclass logistic regression for some\n// input x\n//   y_hat is the 1-best prediction\n//   posterior[y] is p(y_hat | x)\nstruct MulticlassPrediction {\n  unsigned y_hat;\n  vector<double> posterior;\n};\n\nstruct MulticlassLogLoss : public BaseLoss {\n\n  // weight vector layout for K classes, with p features\n  //   w[0 : K-2] = bias weights\n  //   w[y*p + K-1 : y*p + K + p - 2] = feature weights for y^th class\n\n  MulticlassLogLoss(\n          const vector<TrainingInstance>& tr,\n          unsigned k,\n          unsigned numfeats,\n          const double l2,\n          const double t = 0.0) : BaseLoss(tr, k, numfeats, l2), T(t) {}\n\n  //   g = E[ F(x,y) * log p(y|x) ] + H(y | x) * E[ F(x,y) ]\n  //   note: g will be scaled by T\n  double Entropy(const prob_t& z,\n                 const vector<double>& dotprods,\n                 const FrozenFeatureMap& fmapx,\n                 double* g) const {\n    const double log_z = log(z);\n    double entropy = log_z * exp(-log_z);   // class K dotprod = 0\n    map<unsigned, double> ef;\n    for (unsigned j = 0; j < dotprods.size(); ++j) {\n      const double log_prob = dotprods[j] - log_z;\n      const double prob = exp(log_prob);\n      const double e_logprob = prob * log_prob;\n      entropy -= e_logprob;\n      GradAdd(fmapx, j, T * e_logprob, g);\n    }\n    for (unsigned j = 0; j < dotprods.size(); ++j) {\n      const double log_prob = dotprods[j] - log_z;\n      const double prob = exp(log_prob);\n      GradAdd(fmapx, j, T * prob * entropy, g);\n    }\n\n    return entropy;\n  }\n\n  // evaluate log loss and gradient\n  double operator()(const vector<double>& x, double* g) const {\n    fill(g, g + x.size(), 0.0);\n    vector<double> dotprods(K - 1);  // K-1 degrees of freedom\n    vector<prob_t> probs(K);\n    double cll = 0;\n    double entropy = 0;  // only computed if T != 0\n    for (unsigned i = 0; i < training.size(); ++i) {\n      const FrozenFeatureMap& fmapx = training[i].x;\n      const unsigned refy = training[i].y.label;\n      ComputeDotProducts(fmapx, x, &dotprods);\n      prob_t z;\n      for (unsigned j = 0; j < dotprods.size(); ++j)\n        z += (probs[j] = prob_t(dotprods[j], init_lnx()));\n      z += (probs.back() = prob_t::One());\n      for (unsigned y = 0; y < probs.size(); ++y) {\n        probs[y] /= z;\n        //cerr << \"  p(y=\" << y << \")=\" << probs[y].as_float() << \"\\tz=\" << z << endl;\n      }\n      cll -= log(probs[refy]);  // log p(y | x)\n\n      for (unsigned y = 0; y < dotprods.size(); ++y) {\n        double scale = probs[y].as_float();\n        if (y == refy) { scale -= 1.0; }\n        GradAdd(fmapx, y, scale, g);\n      }\n      if (T) entropy += Entropy(z, dotprods, fmapx, g);\n    }\n    double reg = ApplyRegularizationTerms(x, g);\n    return cll + reg - T * entropy;\n  }\n\n  template <class FeatureMapType>\n  pair<unsigned, double> Predict(const FeatureMapType& fx,\n                                 const vector<double>& w,\n                                 MulticlassPrediction* pred = NULL) const {\n    vector<double> dotprods(K - 1);  // K-1 degrees of freedom\n    if (pred) pred->posterior.resize(K);\n    ComputeDotProducts(fx, w, &dotprods);\n    prob_t z = prob_t::One();  // exp(0) for k^th class\n    for (unsigned j = 0; j < dotprods.size(); ++j)\n      z += prob_t(dotprods[j], init_lnx());\n    const double log_z = log(z);\n    double best = 0;\n    unsigned besty = dotprods.size();\n    for (unsigned y = 0; y < dotprods.size(); ++y) {\n      if (dotprods[y] > best) { best = dotprods[y]; besty = y; }\n      if (pred) pred->posterior[y] = exp(dotprods[y] - log_z);\n    }\n    if (pred) {\n      pred->posterior.back() = exp(-log_z);\n      pred->y_hat = besty;\n    }\n    return make_pair(besty, exp(best - log_z));\n  }\n\n  double Evaluate(const vector<TrainingInstance>& test,\n                  const vector<double>& w,\n                  double thresh_p,\n\t\t  vector<MulticlassPrediction>* preds = NULL) const {\n    double correct = 0;\n    unsigned examples = 0;\n    if (preds) preds->resize(test.size());\n    for (unsigned i = 0; i < test.size(); ++i) {\n      MulticlassPrediction* ppred = NULL;\n      if (preds) ppred = &(*preds)[i];\n      const pair<unsigned, double> pred = Predict(test[i].x, w, ppred);\n      const unsigned predy = pred.first;\n      const unsigned refy = test[i].y.label;\n      // cerr << \"line=\" << (i+1) << \" true=\" << refy << \" pred=\" << predy << \"  p(y|x) = \" << pred.second << endl;\n      if (pred.second >= thresh_p) {\n        ++examples;\n        if (refy == predy) ++correct;\n      }\n    }\n    return correct / examples;\n  }\n\n  template <class FeatureMapType>\n  void ComputeDotProducts(const FeatureMapType& fx,  // feature vector of x\n                          const vector<double>& w,         // full weight vector\n                          vector<double>* pdotprods) const {\n    vector<double>& dotprods = *pdotprods;\n    const unsigned km1 = K - 1;\n    dotprods.resize(km1);\n    for (unsigned y = 0; y < km1; ++y)\n      dotprods[y] = w[y];  // bias terms\n    for (typename FeatureMapType::const_iterator it = fx.begin(); it != fx.end(); ++it) {\n      const float fval = it->second;\n      const unsigned fid = it->first;\n      for (unsigned y = 0; y < km1; ++y)\n        dotprods[y] += w[fid + y * p + km1] * fval;\n    }\n  }\n\n  const double T; // temperature for entropy regularization\n};\n\nstruct OrdinalLogLoss : public BaseLoss {\n\n  // weight vector layout for K levels, with p features\n  //   w[0 : K-2] = level biases\n  //   w[K-1 : K + p - 2] = feature weights\n\n  OrdinalLogLoss(\n          const vector<TrainingInstance>& tr,\n          unsigned k,\n          unsigned numfeats,\n          const double l2) : BaseLoss(tr, k, numfeats, l2) {}\n\n  // evaluate log loss and gradient\n  double operator()(const vector<double>& x, double* g) const {\n    const unsigned km1 = K - 1;\n    double cll = 0;\n    fill(g, g + x.size(), 0.0);\n    vector<double> u(K);\n    u[0] = u[km1] = 0;\n    for (unsigned k = 1; k < km1; k++)\n      u[k] = 1 / (1 - exp(x[k] - x[k - 1]));\n    for (unsigned i = 0; i < training.size(); ++i) {\n      const FrozenFeatureMap& fmapx = training[i].x;\n      const unsigned level = training[i].y.label;\n      const double dotprod = DotProduct(fmapx, x);\n      const double pj = LevelProb(dotprod, x, level);\n      const double pjp1 = LevelProb(dotprod, x, level + 1);\n      cll -= LogDeltaProb(dotprod, x, level);\n      if (level > 0)\n        g[level - 1] -= u[level] - 1 + pj;\n      if (level < km1)\n        g[level] -= - u[level] + pjp1;\n      double scale = (1 - pj - pjp1);\n      for (FrozenFeatureMap::const_iterator it = fmapx.begin();\n          it != fmapx.end(); ++it)\n        g[km1 + it->first] -= it->second * scale;\n    }\n    double reg = ApplyRegularizationTerms(x, g);\n    return cll + reg;\n  }\n\n  template <class FeatureMapType>\n  unsigned Predict(const FeatureMapType& fx, const vector<double>& w) const {\n    const double dotprod = DotProduct(fx, w);\n    for (unsigned k = 0; k < K; k++)\n      if (dotprod < w[k]) return k;\n    return K-1;\n  }\n\n  template <class FeatureMapType>\n  unsigned Predict(const FeatureMapType& fx, const vector<double>& w, MulticlassPrediction* pred) const {\n    const double dotprod = DotProduct(fx, w);\n    pred->posterior.resize(K);\n    double bestp = -1;\n    unsigned besty = 0;\n    for (unsigned k = 0; k < K; ++k) {\n      double p = exp(LogDeltaProb(dotprod, w, k));\n      pred->posterior[k] = p;\n      if (p > bestp) { bestp = p; besty = k; }\n    }\n    pred->y_hat = besty;\n    return besty;\n  }\n\n  double Evaluate(const vector<TrainingInstance>& test,\n                  const vector<double>& w,\n                  vector<MulticlassPrediction>* predictions = NULL) const {\n    double correct = 0;\n    if (predictions) predictions->resize(test.size());\n    MulticlassPrediction dummy;\n    for (unsigned i = 0; i < test.size(); ++i) {\n      MulticlassPrediction* pred = predictions ? &(*predictions)[i] : &dummy;\n      const unsigned predy = Predict(test[i].x, w, pred);\n      const unsigned refy = test[i].y.label;\n      if (refy == predy) correct++;\n    }\n    return correct / test.size();\n  }\n\n  double LevelProb(double dotprod, const vector<double>& w,\n                   unsigned level) const { // p(y >= level+1)\n    if (level == K) return 0; // p(y > K) = 0\n    if (level == 0) return 1; // p(y >= 1) = 1\n    return 1 / (1 + exp(w[level - 1] - dotprod));\n  }\n\n  double LogDeltaProb(double dotprod, const vector<double>& w,\n                      unsigned level) const { // log p(y == level + 1)\n        if (level == K-1) {\n          prob_t zj = prob_t(dotprod, init_lnx()) + prob_t(w[K-2], init_lnx());\n          return dotprod - log(zj);\n        }\n        if (level == 0) {\n          prob_t zjp1 = prob_t(dotprod, init_lnx()) + prob_t(w[0], init_lnx());\n          return w[0] - log(zjp1);\n        }\n        if (w[level] <= w[level - 1]) return -1e3;\n        prob_t zj = prob_t(dotprod, init_lnx()) + prob_t(w[level - 1], init_lnx());\n        prob_t zjp1 = prob_t(dotprod, init_lnx()) + prob_t(w[level], init_lnx());\n        prob_t dalpha = prob_t(w[level], init_lnx()) - prob_t(w[level - 1], init_lnx());\n        return (dotprod + log(dalpha) - log(zj) - log(zjp1));\n      }\n\n};\n\ntemplate <class LossFunction>\ndouble LearnParameters(LossFunction& loss,\n                       const double l1,\n                       const unsigned l1_start,\n                       const unsigned memory_buffers,\n                       const double epsilon,\n                       const double delta,\n                       vector<double>* px) {\n  LBFGS<LossFunction> lbfgs(px, loss, memory_buffers, l1, l1_start, epsilon, delta);\n  requested_stop = lbfgs.GetCancelFlag();\n  lbfgs.MinimizeFunction();\n  return 0;\n}\n\nvoid signal_callback_handler(int /* signum */) {\n  if (!requested_stop || *requested_stop) {\n    cerr << \"\\nReceived SIGINT again, quitting.\\n\";\n    exit(1);\n  }\n  cerr << \"\\nReceived SIGINT terminating optimization early.\\n\";\n  *requested_stop = true;\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  string line;\n  double l1 = conf[\"l1\"].as<double>();\n  double l2 = conf[\"l2\"].as<double>();\n  double temp = conf[\"temperature\"].as<double>();\n  const unsigned memory_buffers = conf[\"memory_buffers\"].as<unsigned>();\n  const double epsilon = conf[\"epsilon\"].as<double>();\n  const double delta = conf[\"delta\"].as<double>();\n  const double p_thresh = conf[\"multiclass_test_probability_threshold\"].as<double>();\n  if (l1 < 0.0) {\n    cerr << \"L1 strength must be >= 0\\n\";\n    return 1;\n  }\n  if (l2 < 0.0) {\n    cerr << \"L2 strength must be >= 0\\n\";\n    return 2;\n  }\n  if (p_thresh < 0.0 || p_thresh > 1.0) {\n    cerr << \"--multiclass_test_probability_threshold must be between 0 and 1\\n\";\n    return 3;\n  }\n\n  RegressionType resptype = kLOGISTIC;\n  if (conf.count(\"linear\")) {\n    if (conf.count(\"ordinal\")) {\n      cerr << \"--ordinal and --linear are mutually exclusive\\n\";\n      return 1;\n    }\n    resptype = kLINEAR;\n  } else if (conf.count(\"ordinal\")) {\n    resptype = kORDINAL;\n  }\n  bool do_training = conf.count(\"training_features\") && conf.count(\"training_responses\");\n  if (!do_training && (conf.count(\"training_features\") && conf.count(\"training_responses\"))) {\n    cerr << \"You must specify both training_features (-x) and training_responses (-y)!\\n\";\n    return 1;\n  }\n  vector<string> labels; // only populated for non-continuous models\n  vector<TrainingInstance> training, test;\n  FeatureMapStorage fms;\n  if (do_training) {\n    vector<string> xfile = conf[\"training_features\"].as<vector<string> >();\n    string yfile = conf[\"training_responses\"].as<string>();\n    ReadLabeledInstances(xfile, yfile, resptype, &fms, &training, &labels);\n  }\n\n  if (conf.count(\"test_features\")) {\n    std::cerr << \"THE OPTION --test_features IS DEPRECATED USE --tx AND --ty INSTEAD\\n\";\n    const vector<string> txfile = conf[\"test_features\"].as<vector<string> >();\n    const string tyfile = conf[\"test_responses\"].as<string>();\n    ReadLabeledInstances(txfile, tyfile, resptype, &fms, &test, &labels);\n  }\n\n  bool test_labels = false;\n  vector<string> test_ids;\n  if (conf.count(\"tx\")) {\n    const vector<string> txfile = conf[\"tx\"].as<vector<string> >();\n    string tyfile;\n    if (conf.count(\"ty\")) tyfile = conf[\"ty\"].as<string>();\n    test_labels = tyfile.size();\n    ReadLabeledInstances(txfile, tyfile, resptype, &fms, &test, &labels, &test_ids);\n  }\n  assert(test_ids.size() == test.size());\n\n  string weights_file;\n  if (conf.count(\"weights\")) {\n    weights_file = conf[\"weights\"].as<string>();\n    cerr << \"               WEIGHTS FILE: \" << weights_file << endl;\n  }\n  vector<double> weights;\n  if (weights_file.size() > 0) {\n    if (resptype == kLOGISTIC)\n      ReadWeightsMulticlass(weights_file, &labels, &weights);\n    else if (resptype == kLINEAR)\n      ReadWeightsLinear(weights_file, &weights);\n    else {\n      cerr << \"Don't know how to read weights file--please implement\\n\";\n      abort();\n    }\n  }\n\n  cerr << \"         Number of features: \" << FD::NumFeats() << endl;\n  cerr << \"Number of training examples: \" << training.size() << endl;\n  const unsigned p = FD::NumFeats();\n  cout.precision(15);\n  ostream* out = &cout;\n  if (conf.count(\"dont_write_weights\")) out = NULL;\n  if (conf.count(\"z\") == 1) {\n    if (!out) {\n      cerr << \"You specified an output weights file (--z) but also used -W.\\n\";\n      return 1;\n    }\n    out = new ofstream(conf[\"z\"].as<string>().c_str());\n  }\n  bool write_dist = conf.count(\"write_test_distribution\");\n  bool write_pps = conf.count(\"write_test_predictions\");\n\n  // set up signal handler to catch SIGINT\n  signal(SIGINT, signal_callback_handler);\n\n  if (conf.count(\"linear\")) {  // linear regression\n    weights.resize(1 + p, 0.0);\n    cerr << \"       Number of parameters: \" << weights.size() << endl;\n    UnivariateSquaredLoss loss(training, p, l2);\n    LearnParameters(loss, l1, 1, memory_buffers, epsilon, delta, &weights);\n\n    if (test.size()) {\n      vector<float> preds;\n      double rmse = loss.Evaluate(test, weights, &preds);\n      if (test_labels) {\n        cerr << \"Held-out RMSE: \" << rmse << endl;\n      }\n      if (!test_labels || write_pps) {\n        for (unsigned i = 0; i < test.size(); ++i)\n          cout << test_ids[i] << \"\\t\" << preds[i] << endl;\n      }\n    }\n\n    if (out) {\n      *out << p << \"\\t***CONTINUOUS***\" << endl;\n      *out << \"***BIAS***\\t\" << weights[0] << endl;\n      for (unsigned f = 0; f < p; ++f) {\n        const double w = weights[1 + f];\n        if (w)\n          *out << FD::Convert(f) << \"\\t\" << w << endl;\n      }\n    }\n  } else if (conf.count(\"ordinal\")) {\n    const unsigned K = labels.size();\n    const unsigned km1 = K - 1;\n    weights.resize(p + km1, 0.0);\n    for (unsigned k = 0; k < km1; k++)\n      weights[k] = log(k+1) - log(K);\n    if (weights_file.size() > 0) {\n      cerr << \"Please implement.\\n\";\n      abort();\n    }\n    OrdinalLogLoss loss(training, K, p, l2);\n    LearnParameters(loss, l1, km1, memory_buffers, epsilon, delta, &weights);\n\n    if (test.size()) {\n      vector<MulticlassPrediction> predictions;\n      double acc = loss.Evaluate(test, weights, &predictions);\n      if (test_labels) {\n        cerr << \"Held-out accuracy: \" << acc << endl;\n      }\n      if (!test_labels || write_dist || write_pps) {\n        for (unsigned i = 0; i < test.size(); ++i) {\n          cout << test_ids[i] << '\\t' << predictions[i].y_hat;\n          if (write_dist) {\n            cout << \"\\t{\";\n            for (unsigned y = 0; y < K; ++y)\n              cout << (y ? \", \" : \"\") << '\"' << labels[y] << \"\\\": \" << predictions[i].posterior[y];\n            cout << '}';\n          }\n          cout << endl;\n        }\n      }\n    }\n\n    if (out) {\n      *out << p << \"\\t***ORDINAL***\";\n      for (unsigned y = 0; y < K; ++y)\n        *out << '\\t' << labels[y];\n      *out << endl;\n      for (unsigned y = 0; y < km1; ++y)\n        *out << \"y>=\" << labels[y+1] << \"\\t\" << weights[y] << endl;\n      for (unsigned f = 0; f < p; ++f) {\n        const double w = weights[km1 + f];\n        if (w) *out << FD::Convert(f) << \"\\t\" << w << endl;\n      }\n    }\n  } else {                     // logistic regression\n    weights.resize((1 + FD::NumFeats()) * (labels.size() - 1), 0.0);\n    cerr << \"       Number of parameters: \" << weights.size() << endl;\n    cerr << \"           Number of labels: \" << labels.size() << endl;\n    const unsigned K = labels.size();\n    const unsigned km1 = K - 1;\n    MulticlassLogLoss loss(training, K, p, l2, temp);\n    if (do_training) {\n      LearnParameters(loss, l1, km1, memory_buffers, epsilon, delta, &weights);\n    }\n\n    if (test.size()) {\n      vector<MulticlassPrediction> predictions;\n      double acc = loss.Evaluate(test, weights, p_thresh, &predictions);\n      if (test_labels) {\n        cerr << \"Held-out accuracy: \" << acc << endl;\n      }\n      if (!test_labels || write_dist || write_pps) {\n        for (unsigned i = 0; i < test.size(); ++i) {\n          cout << test_ids[i] << '\\t' << labels[predictions[i].y_hat];\n          if (write_dist) {\n            cout << \"\\t{\";\n            for (unsigned y = 0; y < K; ++y)\n              cout << (y ? \", \" : \"\") << '\"' << labels[y] << \"\\\": \" << predictions[i].posterior[y];\n            cout << '}';\n          }\n          cout << endl;\n        }\n      }\n    }\n\n    if (out) {\n      *out << K << \"\\t***CATEGORICAL***\";\n      for (unsigned y = 0; y < K; ++y)\n        *out << '\\t' << labels[y];\n      *out << endl;\n      for (unsigned y = 0; y < km1; ++y)\n        *out << labels[y] << \"\\t***BIAS***\\t\" << weights[y] << endl;\n      for (unsigned y = 0; y < km1; ++y) {\n        for (unsigned f = 0; f < p; ++f) {\n          const double w = weights[km1 + y * p + f];\n          if (w)\n            *out << labels[y] << \"\\t\" << FD::Convert(f) << \"\\t\" << w << endl;\n        }\n      }\n    }\n  }\n  if (out && out != &cout)\n    delete out;\n\n  return 0;\n}\n", "meta": {"hexsha": "81ca762ab598719ee12463bf7e6325b11f56ecc6", "size": 34961, "ext": "cc", "lang": "C++", "max_stars_repo_path": "creg/creg.cc", "max_stars_repo_name": "redpony/creg", "max_stars_repo_head_hexsha": "33d59a85fe3f87a12e9658d36eee2a04c4058f25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T19:13:26.000Z", "max_issues_repo_path": "creg/creg.cc", "max_issues_repo_name": "redpony/creg", "max_issues_repo_head_hexsha": "33d59a85fe3f87a12e9658d36eee2a04c4058f25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-16T17:46:10.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-17T02:50:09.000Z", "max_forks_repo_path": "creg/creg.cc", "max_forks_repo_name": "redpony/creg", "max_forks_repo_head_hexsha": "33d59a85fe3f87a12e9658d36eee2a04c4058f25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T13:56:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-11T02:47:42.000Z", "avg_line_length": 35.6744897959, "max_line_length": 225, "alphanum_fraction": 0.5669174223, "num_tokens": 9831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.02675928580494465, "lm_q1q2_score": 0.013066114928530007}}
{"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 *      110221    J. Leloux         Startup of TLE header file and class.\n *      110301    J. Leloux         Adjusting header file to parent classes and Tudat rules.\n *      110803    J. Leloux         First setup for codecheck.\n *      110805    K. Kumar          Layout and comment corrections; added\n *                                  get-function for vector container of TLE data.\n *      110810    J. Leloux         Tested new setup and changed descriptions.\n *      110826    J. Leloux         Added functionality for 2-line and 3-line data.\n *      111027    K. Kumar          Modified 2-line and 3-line options using enum.\n *\n *    References\n *      Leloux, J. Filtering Techniques for Orbital Debris Conjunction Analysis\n *          - applied to SSN TLE catalog data and including astrodynamics and\n *          collision probability theory, MSc Literature Research, Delft\n *          University of Technology, 2010.\n *      Celestrak (a). Space Track TLE Retriever Help,\n *          http://celestrak.com/SpaceTrack/TLERetrieverHelp.asp, 2011. Last\n *          accessed: 5 August, 2011.\n *      Space Track. TLE Format, http://www.space-track.org/tle_format.html,\n *          2004. Last accessed: 5 August, 2011.\n *      Celestrak (b). FAQs: Two-Line Element Set Format,\n *          http://celestrak.com/columns/v04n03/, 2006. Last accessed:\n *          5 August, 2011.\n *      Celestrak (c). NORAD Two-Line Element Set Format,\n *          http://celestrak.com/NORAD/documentation/tle-fmt.asp, 2004. Last\n *          accessed: 5 August, 2011.\n *\n *    Notes\n *      Raw TLE data can be obtained from (Celestrak (a), 2011). Explanations of the TLE data\n *      format can be viewed in (Space Track, 2004), (Celestrak (b), 2006), and\n *      (Celestrak (c), 2004).\n *\n */ \n\n#include <cmath>\n#include <iostream>\n#include <map>\n#include <string>\n#include <utility>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n#include <boost/exception/all.hpp>\n#include <boost/throw_exception.hpp>\n#include <boost/algorithm/string/trim.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/InputOutput/twoLineElementsTextFileReader.h\"\n\nnamespace tudat\n{\nnamespace input_output\n{\n\n// Using declarations.\nusing mathematical_constants::PI;\nusing std::string;\nusing std::stringstream;\nusing std::endl;\nusing std::cerr;\nusing std::vector;\nusing std::multimap;\nusing std::pair;\n\n//! Open data file.\nvoid TwoLineElementsTextFileReader::openFile( )\n{\n    if ( absoluteDirectoryPath_.compare( \"\" ) == 0 )\n    {\n        absoluteFilePath_ = getTudatRootPath( ) + relativeDirectoryPath_ + fileName_;\n    }\n\n    else\n    {\n        absoluteFilePath_ = absoluteDirectoryPath_ + fileName_;\n    }\n\n    // Open data file.\n    dataFile_.open( absoluteFilePath_.c_str( ), std::ios::binary );\n\n    // Check if file could be opened. Throw exception with error message if file could not be\n    // opened.\n    if ( !dataFile_ )\n    {\n        boost::throw_exception(\n                    boost::enable_error_info(\n                        std::runtime_error(\n                            boost::str( boost::format( \"Data file '%s' could not be opened.\" )\n                                 % absoluteFilePath_.c_str( ) ) ) )\n            << boost::errinfo_file_name( absoluteFilePath_.c_str( ) )\n            << boost::errinfo_file_open_mode( \"std::ios::binary\" )\n            << boost::errinfo_api_function( \"std::ifstream::open\" ) );\n    }\n}\n\n//! Skip lines.\nvoid TwoLineElementsTextFileReader::skipLines( unsigned int numberOfLines )\n{\n    // Call getline( ) function for set number of lines to be skipped.\n    for ( unsigned int i = 0; i < numberOfLines; i++ )\n    {\n        // Get next line of data from file and don't do anything.\n        std::getline( dataFile_, stringOfData_ );\n\n        // Increment line counter.\n        lineCounter_++;\n    }\n}\n\n//! Read and store data.\nvoid TwoLineElementsTextFileReader::readAndStoreData( )\n{\n    // Reset the datafile.\n    containerOfDataFromFile_.clear( );\n\n    // Whilst the end of the data file has not been reached, continue reading\n    // from lines from data file.\n    while( !dataFile_.eof( ) )\n    {\n        // Get next line of data from data file and store in a string.\n        getline( dataFile_, stringOfData_ );\n\n        // Check if line of data is header line.\n        if ( lineCounter_ <= numberOfHeaderLines_ )\n        {\n            // Store header line data.\n            containerOfHeaderDataFromFile_[ lineCounter_ ] = stringOfData_;\n        }\n\n        // Else process non-header data line.\n        else\n        {\n            // Check if string doesn't start with set starting character, if string\n            // is not empty, and if the skip keyword is not in the string.\n            if ( ( ( !startingCharacter_.empty( ) && stringOfData_.substr( 0, 1 )\n                     .compare( startingCharacter_ ) != 0 )\n                   || ( !skipKeyword_.empty( ) && stringOfData_.find( skipKeyword_ )\n                        == string::npos )\n                   || ( startingCharacter_.empty( ) && skipKeyword_.empty( ) ) )\n                 && !stringOfData_.empty( ) )\n            {\n                // Store string in container.\n                containerOfDataFromFile_[ lineCounter_ ] = stringOfData_;\n            }\n        }\n\n        // Increment line counter.\n        lineCounter_++;\n    }\n}\n\n//! Read and store data.\nvoid TwoLineElementsTextFileReader::readAndStoreData( unsigned int numberOfLines )\n{\n    // Loop over number of lines of data to read and stored from data file.\n    for ( unsigned int i = 0; i < numberOfLines; i++ )\n    {\n        // Get next line of data from data file and store in a string.\n        getline( dataFile_, stringOfData_ );\n\n        // Check string is not empty.\n        if ( !stringOfData_.empty( ) )\n        {\n            // Store string in container.\n            containerOfDataFromFile_[ lineCounter_ ] = stringOfData_;\n        }\n\n        // Increment line counter.\n        lineCounter_++;\n    }\n}\n\n//! Strip End-Of-Line characters.\nvoid TwoLineElementsTextFileReader::stripEndOfLineCharacters(\n        LineBasedStringDataMap& containerOfLinesOfData )\n{\n    // Declare local variables.\n    // Declare string iterator.\n    string::iterator iteratorString_;\n\n    // Loop through all the strings stored in the container.\n    for ( LineBasedStringDataMap::iterator iteratorContainerOfDataFromFile_\n          = containerOfLinesOfData.begin( );\n          iteratorContainerOfDataFromFile_ != containerOfLinesOfData.end( );\n          iteratorContainerOfDataFromFile_++ )\n    {\n        // Loop through all the characters in the string.\n        for ( iteratorString_ = iteratorContainerOfDataFromFile_->second.begin( );\n              iteratorString_ != iteratorContainerOfDataFromFile_->second.end( );\n              iteratorString_++ )\n        {\n            // Check if end-of-line characters are present in string.\n            // The end-of-line characters are checked for their integer\n            // equivalents. See: http://www.asciitable.com/.\n            if ( static_cast< int >( *iteratorString_ ) == 10\n                 || static_cast< int >( *iteratorString_ ) == 13 )\n            {\n                // Strip end-of-line character from string.\n                iteratorContainerOfDataFromFile_->second.erase( iteratorString_ );\n\n                // Decrement string iterator since character was erased from string.\n                iteratorString_--;\n            }\n        }\n    }\n}\n\n//! Convert and store TLE data.\nvoid TwoLineElementsTextFileReader::storeTwoLineElementData( )\n{\n    using boost::algorithm::trim_copy;\n\n    // Strip End-Of-Line characters from data container.\n    stripEndOfLineCharacters( containerOfDataFromFile_ );\n\n    // Calculate number of objects in catalog file.\n    numberOfObjects_ = static_cast< int >( lineCounter_ / numberOfLinesPerTwoLineElementDatum_ );\n\n    // Set TLE data vector size.\n    twoLineElementData_.resize( numberOfObjects_ );\n\n    // Create vector of the three lines of a single object's TLE data as strings.\n    vector< string > twoLineElementString_( 3 );\n\n    // Create the object counter.\n    unsigned int objectNumberCounter_ = 0;\n\n    // Declare Keplerian elements variables.\n    double inclination_;\n    double rightAscensionOfAscendingNode_;\n    double eccentricity_;\n    double argumentOfPerigee_;\n    double meanMotion_;\n\n    // Declare approximate number of revolutions, remainder, and lost part.\n    int approximateNumberOfRevolutions_;\n    int approximateNumberOfRevolutionsRemainder_;\n    int lostNumberOfRevolutions_;\n\n    // Reference: Table 2 in (Vallado, D.A., et al., 2006).\n    const double earthWithWorldGeodeticSystem72GravitationalParameter = 398600.8e9;\n\n    // For every 3 lines, read the data from 3 consecutive strings of TLE data\n    // and convert them to the TLE data variables\n    for ( unsigned int i = 1; i < lineCounter_; i += numberOfLinesPerTwoLineElementDatum_ )\n    {\n        // General setup for variable storing.\n        //---------------------------------------------------------------------\n\n        // Fill the vector with the line strings from the data container.\n        if ( numberOfLinesPerTwoLineElementDatum_ == 3 )\n        {\n            twoLineElementString_.at( 0 ) = containerOfDataFromFile_.at( i );\n            twoLineElementString_.at( 1 ) = containerOfDataFromFile_.at( i + 1 );\n            twoLineElementString_.at( 2 ) = containerOfDataFromFile_.at( i + 2 );\n        }\n\n        else if ( numberOfLinesPerTwoLineElementDatum_ == 2 )\n        {\n            twoLineElementString_.at( 1 ) = containerOfDataFromFile_.at( i );\n            twoLineElementString_.at( 2 ) = containerOfDataFromFile_.at( i + 1 );\n        }\n\n        // Push the TLE strings to the TLE data container.\n        twoLineElementData_[ objectNumberCounter_ ].twoLineElementStrings = twoLineElementString_;\n\n        // Push the line numbers to the TLE data container.\n        twoLineElementData_[ objectNumberCounter_ ].lineNumbers.push_back( i );\n        twoLineElementData_[ objectNumberCounter_ ].lineNumbers.push_back( i + 1 );\n        if ( numberOfLinesPerTwoLineElementDatum_ == 3 )\n        {\n            twoLineElementData_[ objectNumberCounter_ ].lineNumbers.push_back( i + 2 );\n        }\n\n        // Initiate a stringstream for each line.\n        stringstream line0StringStream_( stringstream::in | stringstream::out );\n        stringstream line1StringStream_( stringstream::in | stringstream::out );\n        stringstream line2StringStream_( stringstream::in | stringstream::out );\n\n        // Insert the strings into the stringstreams\n        if ( numberOfLinesPerTwoLineElementDatum_ == 3 )\n        {\n            line0StringStream_ << twoLineElementString_.at( 0 );\n        }\n        line1StringStream_ << twoLineElementString_.at( 1 );\n        line2StringStream_ << twoLineElementString_.at( 2 );\n\n        // Line-0 variable storing.\n        //---------------------------------------------------------------------\n        if ( numberOfLinesPerTwoLineElementDatum_ == 3 )\n        {\n            // Declare string containing part of name of object.\n            string namePart_;\n\n            // Loop through the stringstream and read words that constitute name of\n            // object. Store name parts in objectName storage container.\n            while ( line0StringStream_ >> namePart_ )\n            {\n                twoLineElementData_[ objectNumberCounter_ ].objectName.push_back( namePart_ );\n            }\n\n            // Insert the entire line-0 string in the object name string.\n            twoLineElementData_[ objectNumberCounter_ ].objectNameString\n                    = twoLineElementString_.at( 0 );\n        }\n\n        // Line-1 variable storing.\n        //---------------------------------------------------------------------\n        // Fill all line-1 variables of the object structure with substrings\n        // of the line-1 string using the template function to transform the\n        // string to another type.\n        // See reference for which columns are assigned to which variable.\n\n        // Get line number integer of line-1 from string.\n        twoLineElementData_[ objectNumberCounter_ ].lineNumberLine1  =\n                boost::lexical_cast<unsigned int>(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 0, 1 ) ) );\n\n        // Get object indentification number integer of line-1 from string\n        twoLineElementData_[ objectNumberCounter_ ].objectIdentificationNumber =\n                boost::lexical_cast<unsigned int>(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 2, 5 ) ) );\n\n\n        // Get classification character from string.\n        twoLineElementData_[ objectNumberCounter_ ].tleClassification =\n                twoLineElementString_.at( 1 ) [ 7 ];\n\n        // Get launch year integer from string.\n        twoLineElementData_[ objectNumberCounter_ ].launchYear =\n                boost::lexical_cast< unsigned int >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 9, 2 ) ) );\n\n        // Calculate four-digit launch year from the above.\n        if ( twoLineElementData_[ objectNumberCounter_ ].launchYear > 56 )\n        {\n            twoLineElementData_[ objectNumberCounter_ ].fourDigitlaunchYear =\n                    twoLineElementData_[ objectNumberCounter_ ].launchYear + 1900;\n        }\n\n        else\n        {\n            twoLineElementData_[ objectNumberCounter_ ].fourDigitlaunchYear =\n                    twoLineElementData_[ objectNumberCounter_ ].launchYear + 2000;\n        }\n\n        // Get launch number integer from string.\n        twoLineElementData_[ objectNumberCounter_ ].launchNumber =\n                boost::lexical_cast< unsigned int >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 11, 3 ) ) );\n\n        // Get launch part string from string.\n        twoLineElementData_[ objectNumberCounter_ ].launchPart =\n                twoLineElementString_.at( 1 ).substr( 14, 3 );\n\n        // Get epoch year integer from string.\n        twoLineElementData_[ objectNumberCounter_ ].epochYear =\n                boost::lexical_cast< unsigned int >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 18, 2 ) ) );\n\n        // Calculate four-digit epoch year from the above.\n        if ( twoLineElementData_[ objectNumberCounter_ ].epochYear > 56 )\n        {\n            twoLineElementData_[ objectNumberCounter_ ].fourDigitEpochYear =\n                    twoLineElementData_[ objectNumberCounter_ ].epochYear + 1900;\n        }\n\n        else\n        {\n            twoLineElementData_[ objectNumberCounter_ ].fourDigitEpochYear =\n                    twoLineElementData_[ objectNumberCounter_ ].epochYear + 2000;\n        }\n\n        // Get epoch day double from string.\n        twoLineElementData_[ objectNumberCounter_ ].epochDay =\n                boost::lexical_cast< double >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 20, 12 ) ) );\n\n        // Get \"first-derivative of mean motion divided by two\" double from string.\n        twoLineElementData_[ objectNumberCounter_].firstDerivativeOfMeanMotionDividedByTwo =\n                boost::lexical_cast< double >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 33, 10 ) ) );\n\n        // Get coefficient of scientific notation of \"second-derivative of mean motion divided\n        // by six\" double from string,\n        // Apply implied leading decimal point.\n        twoLineElementData_[ objectNumberCounter_ ]\n                .coefficientOfSecondDerivativeOfMeanMotionDividedBySix =\n                boost::lexical_cast< double >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 44, 6 ) ) ) / 100000.0;\n\n        // Get exponent of scientific notation of \"second-derivative of mean motion divided\n        // by six\" integer from string.\n        twoLineElementData_[ objectNumberCounter_]\n                .exponentOfSecondDerivativeOfMeanMotionDividedBySix =\n                boost::lexical_cast< double >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 50, 2 ) ) );\n\n        // Calculate \"second-derivative of mean motion divided by six\" double from the above two.\n        twoLineElementData_[ objectNumberCounter_ ].secondDerivativeOfMeanMotionDividedBySix =\n                twoLineElementData_[ objectNumberCounter_]\n                .coefficientOfSecondDerivativeOfMeanMotionDividedBySix\n                * pow( 10, twoLineElementData_[ objectNumberCounter_ ]\n                       .exponentOfSecondDerivativeOfMeanMotionDividedBySix );\n\n        // Get coefficient of scientific notation of \"B* divided by six\" double\n        // from string; apply implied leading decimal point.\n        twoLineElementData_[ objectNumberCounter_ ].coefficientOfBStar =\n                boost::lexical_cast< double >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 53, 6 ) ) ) /\n                100000.0;\n\n        // Get exponent of scientific notation of B* integer from string\n        twoLineElementData_[ objectNumberCounter_ ].exponentOfBStar =\n                boost::lexical_cast< int >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 59, 2 ) ) );\n\n        // Calculate B* double from the above two.\n        twoLineElementData_[ objectNumberCounter_ ].bStar =\n                twoLineElementData_[ objectNumberCounter_ ].coefficientOfBStar\n                * pow( 10.0, twoLineElementData_[ objectNumberCounter_ ].exponentOfBStar );\n\n        // Get orbital model integer from string.\n        twoLineElementData_[ objectNumberCounter_ ].orbitalModel =\n                boost::lexical_cast< unsigned int >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 62, 1 ) ) );\n\n        // Get TLE number integer from string.\n        twoLineElementData_[ objectNumberCounter_ ].tleNumber =\n                boost::lexical_cast< unsigned int >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 64, 4 ) ) );\n\n        // Get modulo-10 checksum integer from string.\n        twoLineElementData_[ objectNumberCounter_ ].modulo10CheckSumLine1 =\n                boost::lexical_cast< unsigned int >(\n                    trim_copy( twoLineElementString_.at( 1 ).substr( 68, 1 ) ) );\n\n        // Line-2 variable storing.\n        //---------------------------------------------------------------------\n        // Fill all line-2 variables of the object structure partly with the\n        // stringstream and partly with with substrings of the line-2 string\n        // using the template function to transform the string to another type.\n        // See reference for which columns are assigned to which variable.\n\n        // Get line number integer of line-2 from stringstream.\n        line2StringStream_ >> twoLineElementData_[ objectNumberCounter_ ].lineNumberLine2;\n\n        // Get object identification number integer of line-2 from stringstream.\n        line2StringStream_ >> twoLineElementData_[ objectNumberCounter_ ]\n                              .objectIdentificationNumberLine2;\n\n        // Get inclination double from stringstream.\n        line2StringStream_ >> inclination_;\n        twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                    orbital_element_conversions::inclinationIndex ) = inclination_;\n\n        // Get right ascension of ascending node double from stringstream.\n        line2StringStream_ >> rightAscensionOfAscendingNode_;\n        twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                    orbital_element_conversions::longitudeOfAscendingNodeIndex )\n                = rightAscensionOfAscendingNode_;\n\n        // Get eccetricity double from stringstream.\n        line2StringStream_ >> eccentricity_;\n        eccentricity_ /= 10000000;\n        twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                    orbital_element_conversions::eccentricityIndex ) = eccentricity_;\n\n        // Get argument of perigee double from stringstream\n        line2StringStream_ >> argumentOfPerigee_;\n        twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                    orbital_element_conversions::argumentOfPeriapsisIndex ) = argumentOfPerigee_;\n\n        // Get mean anomaly double from stringstream.\n        line2StringStream_ >> twoLineElementData_[ objectNumberCounter_ ].meanAnomaly;\n\n        // Get mean motion double from line-2 string.\n        twoLineElementData_[ objectNumberCounter_ ].meanMotionInRevolutionsPerDay =\n                boost::lexical_cast< double >(\n                    trim_copy( twoLineElementString_[ 2 ].substr( 52, 11 ) ) );\n\n        // Get revolution number integer from line-2 string.\n        twoLineElementData_[ objectNumberCounter_ ].revolutionNumber =\n                boost::lexical_cast< int >(\n                    trim_copy( twoLineElementString_[ 2 ].substr( 63, 5 ) ) );\n\n        // Get modulo-10 checksum integer of line-2 from line-2 string.\n        twoLineElementData_[ objectNumberCounter_ ].modulo10CheckSumLine2 =\n                boost::lexical_cast< unsigned int >(\n                    trim_copy( twoLineElementString_[ 2 ].substr( 68, 1 ) ) );\n\n        // Calculate the approximate total number of revolutions, as the counter resets to 0 after\n        // passing by 99999, insert the current year in the following equation.\n        approximateNumberOfRevolutions_ = twoLineElementData_[ objectNumberCounter_ ]\n                .meanMotionInRevolutionsPerDay\n                * ( currentYear_\n                    - twoLineElementData_[ objectNumberCounter_ ].fourDigitlaunchYear )\n                * physical_constants::JULIAN_YEAR_IN_DAYS;\n        approximateNumberOfRevolutionsRemainder_ = approximateNumberOfRevolutions_ % 100000;\n        lostNumberOfRevolutions_ = approximateNumberOfRevolutions_\n                - approximateNumberOfRevolutionsRemainder_;\n\n        // Check if the counter has been reset after passing 99999.\n        if ( ( twoLineElementData_[ objectNumberCounter_ ].revolutionNumber -\n               approximateNumberOfRevolutionsRemainder_ ) <=\n             ( approximateNumberOfRevolutionsRemainder_ + 100000 -\n               twoLineElementData_[ objectNumberCounter_ ].revolutionNumber ) )\n        {\n            twoLineElementData_[ objectNumberCounter_ ].totalRevolutionNumber =\n                    lostNumberOfRevolutions_ + twoLineElementData_[ objectNumberCounter_ ]\n                    .revolutionNumber;\n        }\n\n        else\n        {\n            twoLineElementData_[ objectNumberCounter_ ].totalRevolutionNumber =\n                    lostNumberOfRevolutions_ - 100000\n                    + twoLineElementData_[ objectNumberCounter_ ].revolutionNumber;\n        }\n\n        // Check if total number of revolutions is negative.\n        if ( twoLineElementData_[ objectNumberCounter_ ].totalRevolutionNumber < 0 )\n        {\n            twoLineElementData_[ objectNumberCounter_ ].totalRevolutionNumber =\n                    twoLineElementData_[ objectNumberCounter_ ].revolutionNumber;\n        }\n\n        // Semi-major axis of the object is calculated from the other TLE variables.\n        meanMotion_ = twoLineElementData_[ objectNumberCounter_ ].meanMotionInRevolutionsPerDay\n                * 2.0 * PI / physical_constants::JULIAN_DAY;\n        twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                    orbital_element_conversions::semiMajorAxisIndex )\n                = orbital_element_conversions::\n                convertEllipticalMeanMotionToSemiMajorAxis(\n                    meanMotion_, earthWithWorldGeodeticSystem72GravitationalParameter );\n\n        // Perigee of the object is calculated from the other TLE variables.\n        twoLineElementData_[ objectNumberCounter_ ].perigee =\n                twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                    orbital_element_conversions::semiMajorAxisIndex )\n                * ( 1.0 - twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                        orbital_element_conversions::eccentricityIndex ) );\n\n        // Apogee of the object is calculated from the other TLE variables.\n        twoLineElementData_[ objectNumberCounter_ ].apogee =\n                twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                    orbital_element_conversions::semiMajorAxisIndex )\n                * ( 1.0 + twoLineElementData_[ objectNumberCounter_ ].TLEKeplerianElements(\n                        orbital_element_conversions::eccentricityIndex ) );\n\n        // Increment object number counter by one.\n        objectNumberCounter_++;\n    }\n}\n\n//! Checks the integrity of the TLE input file.\nmultimap< int, string > TwoLineElementsTextFileReader::checkTwoLineElementsFileIntegrity( )\n{\n    // Create vector of the three lines of a TLE as strings\n    vector< string > twoLineElementString_( 3 );\n\n    // Boolean which turns to true if one of the tests is not passed.\n    bool isObjectErroneous = false;\n\n    // Vector of object numbers of objects with corrupted TLE data.\n    vector< int > corruptedTwoLineElementDataPositions_;\n\n    // Multimap of corrupted TLE errors.\n    multimap< int, string > corruptedTwoLineElementDataErrors_;\n\n    // Loop is started over the entire structure of objects,\n    // multiple checks are performed per TLE, if a check is not passed boolean\n    // is set to true for that object, and amount of corrupted TLEs integer is\n    // incremented.\n    for ( unsigned int i = 0; i < numberOfObjects_; i++ )\n    {\n        // Fill the vector with the line strings from the data container.\n        if ( numberOfLinesPerTwoLineElementDatum_ == 3 )\n        {\n            twoLineElementString_.at( 1 ) = containerOfDataFromFile_[ i + 1 + ( i * 2 ) + 1 ];\n            twoLineElementString_.at( 2 ) = containerOfDataFromFile_[ i + 1 + ( i * 2 ) + 2 ];\n        }\n\n        else if ( numberOfLinesPerTwoLineElementDatum_ == 2 )\n        {\n            twoLineElementString_.at( 1 ) = containerOfDataFromFile_[ 2 * i + 1 ];\n            twoLineElementString_.at( 2 ) = containerOfDataFromFile_[ 2 * i + 1 + 1 ];\n        }\n\n        // Set boolean to false.\n        isObjectErroneous = false;\n\n        // If a line-1 line number is not 1, error message is given and boolean is set to true.\n        if ( twoLineElementData_.at( i ).lineNumberLine1 != 1 )\n        {\n            corruptedTwoLineElementDataErrors_.insert(\n                        pair< int, string >( i, \"Incorrect line-1 leading integer.\" ) );\n\n            isObjectErroneous = true;\n        }\n\n        // If a line-2 line number is not 2, error message is given and boolean is set to true.\n        if ( twoLineElementData_.at( i ).lineNumberLine2 != 2 )\n        {\n            corruptedTwoLineElementDataErrors_.insert(\n                        pair< int, string >( i, \"Incorrect line-2 leading integer.\" ) );\n\n            isObjectErroneous = true;\n        }\n\n        if ( twoLineElementData_.at( i ).tleClassification != 'U'\n                  && twoLineElementData_.at( i ).tleClassification != 'C' )\n        {\n            corruptedTwoLineElementDataErrors_.insert(\n                        pair< int, string >( i, \"Invalid TLE classification.\" ) );\n\n            isObjectErroneous = true;\n        }\n\n        // Check if orbital model is 0, else error message is given and boolean is set to true.\n        if ( twoLineElementData_.at( i ).orbitalModel != 0 )\n        {\n            corruptedTwoLineElementDataErrors_.insert(\n                        pair< int, string >( i, \"Incorrect orbital model.\" ) );\n\n            isObjectErroneous = true;\n        }\n\n        // Line-1 modulo-10 checker, add all integers of line 1 together,\n        // and minus signs count as 1, rest is not counted.\n\n        // Create calculated modulo-10 checksum of line 1 and temporary integer for addition.\n        unsigned int line1Modulo10Sum_ = 0;\n\n        // Run loop over the 69-character long, line-2 string, but not the last character,\n        // since this is the modulo-10 checksum itself and is not added.\n        for ( unsigned int j = 0; j < 68; j++ )\n        {\n            // Check if the char is not a space or a dot, or a plus or a minus sign or any of the\n            // alphabetical positions, because these can not be added.\n            if ( twoLineElementString_.at( 1 )[ j ] != ' ' &&\n                 twoLineElementString_.at( 1 )[ j ] != '.' &&\n                 twoLineElementString_.at( 1 )[ j ] != '+' &&\n                 twoLineElementString_.at( 1 )[ j ] != '-' &&\n                 j != 7 && j != 14 && j != 15 && j != 16 )\n            {\n                // Add int to checksum.\n                line1Modulo10Sum_ += boost::lexical_cast<int>(\n                            twoLineElementString_.at( 1 ).substr( j , 1 ) );\n            }\n\n            // Check is the char is a minus sign\n            else if ( twoLineElementString_.at( 1 )[ j ] == '-' )\n            {\n                // Add 1 to checksum.\n                line1Modulo10Sum_++;\n            }\n        }\n\n        // Take modulo 10 of checksum.\n        line1Modulo10Sum_ %= 10;\n\n        // Comparison of calculated modulo-10 checksum with modulo-10 checksum from TLE for line 1,\n        // if they do not compare, error message is given and boolean is set to true.\n        if ( line1Modulo10Sum_ != twoLineElementData_.at( i ).modulo10CheckSumLine1 )\n        {\n            corruptedTwoLineElementDataErrors_.insert(\n                        pair< int, string >( i, \"Incorrect line-1 modulo-10 checksum.\" ) );\n\n            isObjectErroneous = true;\n        }\n\n        // Line-2 modulo-10 checker, add all integers of line 2 together.\n        unsigned int line2Modulo10Sum_ = 0;\n\n        // Run loop over the 69-character long, line-2 string, but not the last character,\n        // since this is the modulo-10 checksum itself and is not added.\n        for ( unsigned int k = 0; k < 68; k++ )\n        {\n            // Check if the char is not a space or a dot, because these can not be added.\n            if ( twoLineElementString_.at( 2 )[ k ] != ' ' &&\n                 twoLineElementString_.at( 2 )[ k ] != '.' )\n            {\n                // Add int to checksum.\n                line2Modulo10Sum_ += boost::lexical_cast<int>(\n                            twoLineElementString_[ 2 ].substr( k , 1 ) );\n            }\n        }\n\n        // Take modulo 10 of checksum.\n        line2Modulo10Sum_ %= 10;\n\n        // Comparison of calculated modulo-10 checksum with modulo-10 checksum from TLE for line 2,\n        // if they do not compare error message is given and boolean is set to true.\n        if ( line2Modulo10Sum_ != twoLineElementData_.at( i ).modulo10CheckSumLine2 )\n        {\n            corruptedTwoLineElementDataErrors_.insert(\n                        pair< int, string >( i, \"Incorrect line-2 modulo-10 checksum.\" ) );\n\n            isObjectErroneous = true;\n        }\n\n        // When the object's line-1 and line-2 identification numbers do not match an\n        // error message is given and boolean is set to true.\n        if ( twoLineElementData_.at( i ).objectIdentificationNumber !=\n             twoLineElementData_.at( i ).objectIdentificationNumberLine2 )\n        {\n            corruptedTwoLineElementDataErrors_.insert(\n                        pair< int, string >(\n                            i, \"Line-1 and line-2 object idenfitication number mismatch.\" ) );\n\n            isObjectErroneous = true;\n        }\n\n        // If object is erroneous, add to list.\n        if ( isObjectErroneous )\n        {\n            corruptedTwoLineElementDataPositions_.push_back( i );\n        }\n    }\n\n    // Erase all the corrupted TLEs from the TLE data vector.\n\n    for ( unsigned int q = 0; q < corruptedTwoLineElementDataPositions_.size( ); q++ )\n    {\n        twoLineElementData_.erase( twoLineElementData_.begin( ) + (\n                                   corruptedTwoLineElementDataPositions_.at( q ) - q ) );\n        numberOfObjects_--;\n    }\n\n    // Return the amount of corrupted TLEs\n    return corruptedTwoLineElementDataErrors_;\n}\n\n} // namespace input_output\n} // namespace tudat\n", "meta": {"hexsha": "6d4bd7a73521c15358a90bae89d965442dbbd67c", "size": 34231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/InputOutput/twoLineElementsTextFileReader.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/InputOutput/twoLineElementsTextFileReader.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/InputOutput/twoLineElementsTextFileReader.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": 44.5716145833, "max_line_length": 99, "alphanum_fraction": 0.6320002337, "num_tokens": 7745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894279828469, "lm_q2_score": 0.03904829090900819, "lm_q1q2_score": 0.01306514531895285}}
{"text": "// ======================================================================\n/*!\n * \\file NFmiSoundingIndexCalculator.cpp\n *\n * Tämä luokka laskee erilaisia luotausi ndeksejä annettujen querinfojen avulla.\n * Mm. CAPE, CIN, LCL, BulkShear StormRelatedHellicity jne.\n */\n// ======================================================================\n\n#include \"NFmiSoundingIndexCalculator.h\"\n#include \"NFmiDrawParam.h\"\n#include \"NFmiInfoOrganizer.h\"\n#include \"NFmiSoundingData.h\"\n#include \"NFmiSoundingFunctions.h\"\n#include <newbase/NFmiFastQueryInfo.h>\n#include <newbase/NFmiGrid.h>\n#include <newbase/NFmiQueryData.h>\n#include <newbase/NFmiQueryDataUtil.h>\n#include <newbase/NFmiValueString.h>\n\n#ifndef BOOST_DISABLE_THREADS\n\n#ifdef _MSC_VER\n#pragma warning(disable : 4244)  // boost:in thread kirjastosta tulee ikävästi 4244 varoituksia\n#endif\n#include <boost/thread.hpp>\n#ifdef _MSC_VER\n#pragma warning(default : 4244)  // laitetaan 4244 takaisin päälle, koska se on tärkeä (esim. double\n                                 // -> int auto castaus varoitus)\n#endif\n\n#endif  // BOOST_DISABLE_THREADS\n\nusing namespace NFmiSoundingFunctions;\n\nbool NFmiSoundingIndexCalculator::FillSoundingData(\n    const boost::shared_ptr<NFmiFastQueryInfo> &theInfo,\n    NFmiSoundingData &theSoundingData,\n    const NFmiMetTime &theTime,\n    const NFmiLocation &theLocation,\n    const boost::shared_ptr<NFmiFastQueryInfo> &theGroundDataInfo)\n{\n  if (theInfo)\n  {\n    if (theInfo->IsGrid())\n      return theSoundingData.FillSoundingData(\n          theInfo, theTime, theInfo->OriginTime(), theLocation, theGroundDataInfo);\n    else\n      return theSoundingData.FillSoundingData(theInfo, theTime, theInfo->OriginTime(), theLocation);\n  }\n  return false;\n}\n\nstatic bool FillSoundingData(const boost::shared_ptr<NFmiFastQueryInfo> &theInfo,\n                             NFmiSoundingData &theSoundingData,\n                             const boost::shared_ptr<NFmiFastQueryInfo> &thePossibleGroundInfo,\n                             const NFmiMetTime &theTime,\n                             const NFmiPoint &theLatlon,\n                             bool useFastFill)\n{\n  if (theInfo)\n  {\n    if (theInfo->IsGrid())\n      return theSoundingData.FillSoundingData(theInfo,\n                                              theTime,\n                                              theInfo->OriginTime(),\n                                              NFmiLocation(theLatlon),\n                                              thePossibleGroundInfo,\n                                              useFastFill);\n  }\n  return false;\n}\n\nbool NFmiSoundingIndexCalculator::IsSurfaceBasedSoundingIndex(\n    FmiSoundingParameters theSoundingParameter)\n{\n  if (theSoundingParameter >= kSoundingParLCLSurBas &&\n      theSoundingParameter <= kSoundingParCAPE_TT_SurBas)\n    return true;\n  else\n    return false;\n}\n\n#if 0  // NEVER USED\nstatic bool FillSurfaceValuesFromInfo(NFmiSmartInfo *theInfo, NFmiSoundingData &theSoundingData, const NFmiPoint &theLatLon, float &theT, float &theTd)\n{\n\ttheInfo->Param(kFmiTemperature);\n\tfloat T = theInfo->InterpolatedValue(theLatLon);\n\ttheT = T;\n\ttheInfo->Param(kFmiDewPoint);\n\tfloat Td = theInfo->InterpolatedValue(theLatLon);\n\ttheTd = Td;\n\tif(T != kFloatMissing && Td != kFloatMissing)\n\t{\n\t\ttheSoundingData.SetTandTdSurfaceValues(T, Td);\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n#endif\n\nstatic void CheckIfStopped(NFmiStopFunctor *theStopFunctor)\n{\n  if (theStopFunctor && theStopFunctor->Stop())\n    throw NFmiStopThreadException();\n}\n\nstatic void CalcAllSoundingIndexParamFields(\n    boost::shared_ptr<NFmiFastQueryInfo> &theSourceInfo,\n    boost::shared_ptr<NFmiFastQueryInfo> &theResultInfo,\n    const boost::shared_ptr<NFmiFastQueryInfo> &thePossibleGroundInfo,\n    bool useFastFill,\n    NFmiStopFunctor *theStopFunctor)\n{\n  // bool fObsDataFound = false; // toistaiseksi ei käytössä\n  // bool useAnalyzeData = false; // toistaiseksi ei käytössä\n\n  NFmiSoundingData soundingData;\n  unsigned long counter = 0;\n  for (theResultInfo->ResetLocation(); theResultInfo->NextLocation();)\n  {\n    try\n    {\n      // bool surfaceBaseStatus = false;\n      if (useFastFill)\n        theSourceInfo->LocationIndex(theResultInfo->LocationIndex());\n      ::FillSoundingData(theSourceInfo,\n                         soundingData,\n                         thePossibleGroundInfo,\n                         theResultInfo->Time(),\n                         theResultInfo->LatLon(),\n                         useFastFill);\n      if (theSourceInfo->Grid() && !soundingData.IsDataGood())\n        continue;  // jos oltiin mallidatassa ja datassa oli tiettyjä puutteita, ei tehdä laskentoja\n\n      for (theResultInfo->ResetParam(); theResultInfo->NextParam();)\n      {\n        counter++;\n        if (counter % 20 == 0)\n          ::CheckIfStopped(\n              theStopFunctor);  // joka 20 hila/paramtrilla -pisteellä katsotaan, pitääkö lopettaa\n\n        FmiSoundingParameters soundingParameter =\n            static_cast<FmiSoundingParameters>(theResultInfo->Param().GetParamIdent());\n        // bool surfaceBasedCalculation =\n        // NFmiSoundingIndexCalculator::IsSurfaceBasedSoundingIndex(soundingParameter); // onko\n        // surfacebased???\n\n        // HUOM!!!! muista muuttaa luotaus-parametri pelkäksi surface arvoksi, koska loppu menee\n        // itsestään sitten\n        float value = NFmiSoundingIndexCalculator::Calc(soundingData, soundingParameter);\n        theResultInfo->FloatValue(value);\n      }\n    }\n    catch (NFmiStopThreadException &)\n    {\n      break;\n    }\n    catch (...)\n    {\n      // jouduin laittamaan try-catch blokin tänne, koska aina silloin tällöin jossain vaiheessa\n      // lentää poikkeus, joka lopettaa laskennat\n      // tässä ei tehdä mitään, mutta laskennat jatkuvat ainakin seuraavasta pisteestä...\n    }\n  }\n}\n\nstatic void CalculatePartOfSoundingData(\n    boost::shared_ptr<NFmiFastQueryInfo> &theSourceInfo,\n    boost::shared_ptr<NFmiFastQueryInfo> &theResultInfo,\n    const boost::shared_ptr<NFmiFastQueryInfo> &thePossibleGroundInfo,\n    unsigned long startTimeIndex,\n    unsigned long endTimeIndex,\n    bool useFastFill,\n    NFmiStopFunctor *theStopFunctor,\n    int index,\n    bool fDoCerrReporting)\n{\n  try\n  {\n    if (theSourceInfo->IsGrid() == false || theResultInfo->IsGrid() == false)\n      throw std::runtime_error(\n          \"Error in CalculatePartOfSoundingData, source or result data was non grid-data.\");\n\n    for (unsigned long i = startTimeIndex; i <= endTimeIndex; i++)\n    {\n      if (theResultInfo->TimeIndex(i))\n      {\n        if (useFastFill == false ||\n            theSourceInfo->TimeIndex(\n                theResultInfo->TimeIndex()))  // optimointia, molemmissa samat ajat!!!\n        {\n          if (fDoCerrReporting)\n            std::cerr << \"thread nro: \" << index << \" starting time step nro: \" << i << std::endl;\n          ::CheckIfStopped(theStopFunctor);\n          ::CalcAllSoundingIndexParamFields(\n              theSourceInfo, theResultInfo, thePossibleGroundInfo, useFastFill, theStopFunctor);\n        }\n      }\n    }\n  }\n  catch (NFmiStopThreadException & /* stopException */)\n  {\n    // lopetetaan sitten kun on niin haluttu\n    if (fDoCerrReporting)\n      std::cerr << \"thread nro: \" << index << \" stops because it was told to do so.\" << std::endl;\n  }\n  catch (std::exception &e)\n  {\n    // lopetetaan muutenkin, jos tulee poikkeus\n    if (fDoCerrReporting)\n      std::cerr << \"thread nro: \" << index << \" stops because exception was thrown:\\n\"\n                << e.what() << std::endl;\n  }\n  catch (...)\n  {\n    // lopetetaan muutenkin, jos tulee poikkeus\n    if (fDoCerrReporting)\n      std::cerr << \"thread nro: \" << index << \" stops because unknown error.\" << std::endl;\n  }\n  if (fDoCerrReporting)\n    std::cerr << \"thread nro: \" << index << \" end here.\" << std::endl;\n}\n\nstatic void CalculateSoundingDataOneTimeStepAtTime(\n    boost::shared_ptr<NFmiFastQueryInfo> &theSourceInfo,\n    boost::shared_ptr<NFmiFastQueryInfo> &theResultInfo,\n    const boost::shared_ptr<NFmiFastQueryInfo> &thePossibleGroundInfo,\n    NFmiTimeIndexCalculator &theTimeIndexCalculator,\n    bool useFastFill,\n    NFmiStopFunctor *theStopFunctor,\n    int index,\n    bool fDoCerrReporting)\n{\n  try\n  {\n    if (theSourceInfo->IsGrid() == false || theResultInfo->IsGrid() == false)\n      throw std::runtime_error(\n          \"Error in CalculatePartOfSoundingData, source or result data was non grid-data.\");\n\n    unsigned long workedTimeIndex = 0;\n    for (; theTimeIndexCalculator.GetCurrentTimeIndex(workedTimeIndex);)\n    {\n      if (theResultInfo->TimeIndex(workedTimeIndex))\n      {\n        if (useFastFill == false ||\n            theSourceInfo->TimeIndex(\n                theResultInfo->TimeIndex()))  // optimointia, molemmissa samat ajat!!!\n        {\n          if (fDoCerrReporting)\n            std::cerr << \"thread nro: \" << index << \" starting time step nro: \" << workedTimeIndex\n                      << std::endl;\n          ::CheckIfStopped(theStopFunctor);\n          ::CalcAllSoundingIndexParamFields(\n              theSourceInfo, theResultInfo, thePossibleGroundInfo, useFastFill, theStopFunctor);\n        }\n      }\n    }\n  }\n  catch (NFmiStopThreadException & /* stopException */)\n  {\n    // lopetetaan sitten kun on niin haluttu\n    if (fDoCerrReporting)\n      std::cerr << \"thread nro: \" << index << \" stops because it was told to do so.\" << std::endl;\n  }\n  catch (std::exception &e)\n  {\n    // lopetetaan muutenkin, jos tulee poikkeus\n    if (fDoCerrReporting)\n      std::cerr << \"thread nro: \" << index << \" stops because exception was thrown:\\n\"\n                << e.what() << std::endl;\n  }\n  catch (...)\n  {\n    // lopetetaan muutenkin, jos tulee poikkeus\n    if (fDoCerrReporting)\n      std::cerr << \"thread nro: \" << index << \" stops because unknown error.\" << std::endl;\n  }\n  if (fDoCerrReporting)\n    std::cerr << \"thread nro: \" << index << \" end here.\" << std::endl;\n}\n\n// Jos useFastFill on true, on datoilla sama hila ja aika descriptor rakenne\n// theMaxThreadCount -parametrilla voidaan rajoittaa käytettävien threadien määrää. Jos sen arvo on\n// <=0,\n// ei rajoitusta ole ja käytetään koneen kaikkia coreja (paitsi jos fUseOnlyOneThread = true,\n// jolloin\n// käytetään vain yhtä threadia).\nvoid NFmiSoundingIndexCalculator::CalculateWholeSoundingData(NFmiQueryData &theSourceData,\n                                                             NFmiQueryData &theResultData,\n                                                             NFmiQueryData *thePossibleGroundData,\n                                                             bool useFastFill,\n                                                             bool fDoCerrReporting,\n                                                             NFmiStopFunctor *theStopFunctor,\n                                                             bool fUseOnlyOneThread,\n                                                             int theMaxThreadCount)\n{\n  NFmiSoundingFunctions::CalcDP(1, 56);  // tämä funktio pitää varmistaa että se on alustettu, koska\n                                         // siellä on pari staattista muuttujaa, jotka\n  // alustetaan ensimmäisellä kerralla ja multi-threaddaavassa jutussa se voisi olla ongelma.\n\n  unsigned long timeSize = theResultData.Info()->SizeTimes();\n  unsigned int usedThreadCount = boost::thread::hardware_concurrency();\n  if (theMaxThreadCount > 0 && usedThreadCount > static_cast<unsigned int>(theMaxThreadCount))\n    usedThreadCount = static_cast<unsigned int>(theMaxThreadCount);  // jos on haluttu säätää maksim\n  // threadien määrää, säädetään\n  // maksimia jos usedThreadCount\n  // olisi muuten ylittänyt sen.\n\n  usedThreadCount = NFmiQueryDataUtil::CalcOptimalThreadCount(usedThreadCount, timeSize);\n\n  if (fUseOnlyOneThread || usedThreadCount < 2)\n  {  // jos aikoja oli alle kaksi, lasketaan data yhdessä funktiossa\n\n    if (fDoCerrReporting)\n      std::cerr << \"making data in single thread\" << std::endl;\n    boost::shared_ptr<NFmiFastQueryInfo> sourceInfo(new NFmiFastQueryInfo(&theSourceData));\n    boost::shared_ptr<NFmiFastQueryInfo> resultInfo(new NFmiFastQueryInfo(&theResultData));\n    boost::shared_ptr<NFmiFastQueryInfo> possibleGroundInfo(\n        thePossibleGroundData ? new NFmiFastQueryInfo(thePossibleGroundData) : nullptr);\n    ::CalculatePartOfSoundingData(sourceInfo,\n                                  resultInfo,\n                                  possibleGroundInfo,\n                                  0,\n                                  timeSize - 1,\n                                  useFastFill,\n                                  theStopFunctor,\n                                  1,\n                                  fDoCerrReporting);\n  }\n  else\n  {\n    if (fDoCerrReporting)\n      std::cerr << \"making data in multiple threads\" << std::endl;\n\n#ifndef WGS84\n    theSourceData.LatLonCache();  // Ennen multi-thread laskuja pitää varmistaa että kunkin datan\n                                  // (source + result) latlon-cache on alustettu, muutern tulee\n                                  // ongelmia.\n    theResultData.LatLonCache();\n    if (thePossibleGroundData)\n      thePossibleGroundData->LatLonCache();\n#endif\n\n    // pakko luoda dynaamisesti eri threadeille tarvittavat kopiot source ja target datoista\n    std::vector<boost::shared_ptr<NFmiFastQueryInfo> > resultInfos(usedThreadCount);\n    std::vector<boost::shared_ptr<NFmiFastQueryInfo> > sourceInfos(usedThreadCount);\n    std::vector<boost::shared_ptr<NFmiFastQueryInfo> > possibleGroundInfos(usedThreadCount);\n    for (unsigned int i = 0; i < usedThreadCount; i++)\n    {\n      resultInfos[i] = boost::shared_ptr<NFmiFastQueryInfo>(new NFmiFastQueryInfo(&theResultData));\n      sourceInfos[i] = boost::shared_ptr<NFmiFastQueryInfo>(new NFmiFastQueryInfo(&theSourceData));\n      if (thePossibleGroundData)\n        possibleGroundInfos[i] =\n            boost::shared_ptr<NFmiFastQueryInfo>(new NFmiFastQueryInfo(thePossibleGroundData));\n    }\n\n    NFmiTimeIndexCalculator timeIndexCalculator(0, timeSize - 1);\n    boost::thread_group calcParts;\n    for (unsigned int i = 0; i < usedThreadCount; i++)\n      calcParts.add_thread(new boost::thread(::CalculateSoundingDataOneTimeStepAtTime,\n                                             sourceInfos[i],\n                                             resultInfos[i],\n                                             possibleGroundInfos[i],\n                                             boost::ref(timeIndexCalculator),\n                                             useFastFill,\n                                             theStopFunctor,\n                                             i + 1,\n                                             fDoCerrReporting));\n    calcParts.join_all();  // odotetaan että threadit lopettavat\n\n    if (fDoCerrReporting)\n      std::cerr << \"all threads ended\" << std::endl;\n  }\n}\n\nfloat NFmiSoundingIndexCalculator::Calc(NFmiSoundingData &theSoundingData,\n                                        FmiSoundingParameters theParam)\n{\n  double value = kFloatMissing;\n  double xxxxValue = kFloatMissing;  // tämä on ns. hukka parametri, koska jotkut parametrit\n                                     // syntyvät sivutuotteena ja tähän sijoitetaan aina se ei\n                                     // haluttu parametri\n  switch (theParam)\n  {\n    // **** 1. yksinkertaiset indeksit, tarvitaan vain soundingdata ***\n    case kSoundingParSHOW:\n      value = theSoundingData.CalcSHOWIndex();\n      break;\n    case kSoundingParLIFT:\n      value = theSoundingData.CalcLIFTIndex();\n      break;\n    case kSoundingParKINX:\n      value = theSoundingData.CalcKINXIndex();\n      break;\n    case kSoundingParCTOT:\n      value = theSoundingData.CalcCTOTIndex();\n      break;\n    case kSoundingParVTOT:\n      value = theSoundingData.CalcVTOTIndex();\n      break;\n    case kSoundingParTOTL:\n      value = theSoundingData.CalcTOTLIndex();\n      break;\n\n    // **** 2. indeksit joissa tarvitaan myös pintakerros lasku tyyppi soundingdatan lisäksi ja\n    // mahd. korkeus parametri ***\n    // **** surface ****\n    case kSoundingParLCLSur:\n    case kSoundingParLCLSurBas:\n      value = theSoundingData.CalcLCLIndex(kLCLCalcSurface);\n      break;\n    case kSoundingParCAPESur:\n    case kSoundingParCAPESurBas:\n      value = theSoundingData.CalcCAPE500Index(kLCLCalcSurface);\n      break;\n    case kSoundingParCAPE0_3kmSur:\n    case kSoundingParCAPE0_3kmSurBas:\n      value = theSoundingData.CalcCAPE500Index(kLCLCalcSurface, 3000);\n      break;\n    case kSoundingParCAPE_TT_Sur:\n    case kSoundingParCAPE_TT_SurBas:\n      value = theSoundingData.CalcCAPE_TT_Index(kLCLCalcSurface, -10, -40);\n      break;\n    case kSoundingParCINSur:\n    case kSoundingParCINSurBas:\n      value = theSoundingData.CalcCINIndex(kLCLCalcSurface);\n      break;\n    case kSoundingParLCLHeightSur:\n    case kSoundingParLCLHeightSurBas:\n      value = theSoundingData.CalcLCLHeightIndex(kLCLCalcSurface);\n      break;\n\n    // **** 500 m mixing ****\n    case kSoundingParLCL500m:\n      value = theSoundingData.CalcLCLIndex(kLCLCalc500m2);\n      break;\n    case kSoundingParCAPE500m:\n      value = theSoundingData.CalcCAPE500Index(kLCLCalc500m2);\n      break;\n    case kSoundingParCAPE0_3km500m:\n      value = theSoundingData.CalcCAPE500Index(kLCLCalc500m2, 3000);\n      break;\n    case kSoundingParCAPE_TT_500m:\n      value = theSoundingData.CalcCAPE_TT_Index(kLCLCalc500m2, -10, -40);\n      break;\n    case kSoundingParCIN500m:\n      value = theSoundingData.CalcCINIndex(kLCLCalc500m2);\n      break;\n    case kSoundingParLCLHeight500m:\n      value = theSoundingData.CalcLCLHeightIndex(kLCLCalc500m2);\n      break;\n\n    // **** most unstable case ****\n    case kSoundingParLCLMostUn:\n      value = theSoundingData.CalcLCLIndex(kLCLCalcMostUnstable);\n      break;\n    case kSoundingParCAPEMostUn:\n      value = theSoundingData.CalcCAPE500Index(kLCLCalcMostUnstable);\n      break;\n    case kSoundingParCAPE0_3kmMostUn:\n      value = theSoundingData.CalcCAPE500Index(kLCLCalcMostUnstable, 3000);\n      break;\n    case kSoundingParCAPE_TT_MostUn:\n      value = theSoundingData.CalcCAPE_TT_Index(kLCLCalcMostUnstable, -10, -40);\n      break;\n    case kSoundingParCINMostUn:\n      value = theSoundingData.CalcCINIndex(kLCLCalcMostUnstable);\n      break;\n    case kSoundingParLCLHeightMostUn:\n      value = theSoundingData.CalcLCLHeightIndex(kLCLCalcMostUnstable);\n      break;\n\n    // **** 3. indeksit jotka lasketaan jonkun muun indeksin yhteydessä, tarvitaan myös\n    // mahdollisesti pintakerros lasku tyyppi ja soundingdata ***\n    case kSoundingParLFCSur:\n    case kSoundingParLFCSurBas:\n      value = theSoundingData.CalcLFCIndex(kLCLCalcSurface, xxxxValue);\n      break;\n    case kSoundingParELSur:\n    case kSoundingParELSurBas:\n      xxxxValue = theSoundingData.CalcLFCIndex(kLCLCalcSurface, value);\n      break;\n    case kSoundingParLFCHeightSur:\n    case kSoundingParLFCHeightSurBas:\n      value = theSoundingData.CalcLFCHeightIndex(kLCLCalcSurface, xxxxValue);\n      break;\n    case kSoundingParELHeightSur:\n    case kSoundingParELHeightSurBas:\n      xxxxValue = theSoundingData.CalcLFCHeightIndex(kLCLCalcSurface, value);\n      break;\n\n    case kSoundingParLFC500m:\n      value = theSoundingData.CalcLFCIndex(kLCLCalc500m2, xxxxValue);\n      break;\n    case kSoundingParEL500m:\n      xxxxValue = theSoundingData.CalcLFCIndex(kLCLCalc500m2, value);\n      break;\n    case kSoundingParLFCHeight500m:\n      value = theSoundingData.CalcLFCHeightIndex(kLCLCalc500m2, xxxxValue);\n      break;\n    case kSoundingParELHeight500m:\n      xxxxValue = theSoundingData.CalcLFCHeightIndex(kLCLCalc500m2, value);\n      break;\n\n    case kSoundingParLFCMostUn:\n      value = theSoundingData.CalcLFCIndex(kLCLCalcMostUnstable, xxxxValue);\n      break;\n    case kSoundingParELMostUn:\n      xxxxValue = theSoundingData.CalcLFCIndex(kLCLCalcMostUnstable, value);\n      break;\n    case kSoundingParLFCHeightMostUn:\n      value = theSoundingData.CalcLFCHeightIndex(kLCLCalcMostUnstable, xxxxValue);\n      break;\n    case kSoundingParELHeightMostUn:\n      xxxxValue = theSoundingData.CalcLFCHeightIndex(kLCLCalcMostUnstable, value);\n      break;\n\n    // **** 4. indeksit joiden laskuissa tarvitaan korkeus parametreja ja soundingdata ***\n    case kSoundingParBS0_6km:\n      value = theSoundingData.CalcBulkShearIndex(0, 6);\n      break;\n    case kSoundingParBS0_1km:\n      value = theSoundingData.CalcBulkShearIndex(0, 1);\n      break;\n    case kSoundingParSRH0_3km:\n      value = theSoundingData.CalcSRHIndex(0, 3);\n      break;\n    case kSoundingParSRH0_1km:\n      value = theSoundingData.CalcSRHIndex(0, 1);\n      break;\n    case kSoundingParWS1500m:\n      value = theSoundingData.CalcWSatHeightIndex(1500);\n      break;\n    case kSoundingParThetaE0_3km:\n      value = theSoundingData.CalcThetaEDiffIndex(0, 3);\n      break;\n    case kSoundingParGDI:\n      value = theSoundingData.CalcGDI();\n      break;\n    case kSoundingParNone:\n      value = kFloatMissing;\n      break;\n  }\n\n  return static_cast<float>(value);\n}\n\nfloat NFmiSoundingIndexCalculator::Calc(const boost::shared_ptr<NFmiFastQueryInfo> &theInfo,\n                                        const NFmiPoint &theLatlon,\n                                        const NFmiMetTime &theTime,\n                                        FmiSoundingParameters theParam)\n{\n  NFmiSoundingData soundingData;\n  NFmiLocation wantedLocation(theLatlon);\n  if (FillSoundingData(theInfo, soundingData, theTime, wantedLocation, nullptr))\n    return Calc(soundingData, theParam);\n  return kFloatMissing;\n}\n\nstatic const NFmiParamDescriptor &GetSoundingIndexParams()\n{\n  static bool firstTime = true;\n  static NFmiParamDescriptor soundingParams;\n  if (firstTime)\n  {\n    firstTime = false;\n    NFmiParamBag parBag;\n\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParSHOW,\n                                       \"SHOW\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLIFT,\n                                       \"LIFT\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParKINX,\n                                       \"KINX\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCTOT,\n                                       \"CTOT\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParVTOT,\n                                       \"VTOT\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParTOTL,\n                                       \"TOTL\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCLSur,\n                                       \"LCL (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFCSur,\n                                       \"LFC (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParELSur,\n                                       \"EL (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCLHeightSur,\n                                       \"LCL height (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFCHeightSur,\n                                       \"LFC height (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParELHeightSur,\n                                       \"EL height (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPESur,\n                                       \"CAPE (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE0_3kmSur,\n                                       \"CAPE 0-3km (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE_TT_Sur,\n                                       \"CAPE -10-40 (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCINSur,\n                                       \"CIN (sur)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCL500m,\n                                       \"LCL (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFC500m,\n                                       \"LFC (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParEL500m,\n                                       \"EL (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCLHeight500m,\n                                       \"LCL height (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFCHeight500m,\n                                       \"LFC height (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParELHeight500m,\n                                       \"EL height (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE500m,\n                                       \"CAPE (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE0_3km500m,\n                                       \"CAPE 0-3km (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE_TT_500m,\n                                       \"CAPE -10-40 (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCIN500m,\n                                       \"CIN (500m)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCLMostUn,\n                                       \"LCL (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFCMostUn,\n                                       \"LFC (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParELMostUn,\n                                       \"EL (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCLHeightMostUn,\n                                       \"LCL height (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFCHeightMostUn,\n                                       \"LFC height (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParELHeightMostUn,\n                                       \"EL height (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPEMostUn,\n                                       \"CAPE (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE0_3kmMostUn,\n                                       \"CAPE 0-3km (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE_TT_MostUn,\n                                       \"CAPE -10-40 (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCINMostUn,\n                                       \"CIN (mu)\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n\n    /* xxxx jää kommenttiin\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCLSurBas, \"LCL (obs-bas)\",\n       kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFCSurBas, \"LFC (obs-bas)\",\n       kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParELSurBas, \"EL (obs-bas)\",\n       kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLCLHeightSurBas, \"LCL height\n       (obs-bas)\", kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParLFCHeightSurBas, \"LFC height\n       (obs-bas)\", kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParELHeightSurBas, \"EL height\n       (obs-bas)\", kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPESurBas, \"CAPE (obs-bas)\",\n       kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE0_3kmSurBas, \"CAPE 0-3km\n       (obs-bas)\", kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCAPE_TT_SurBas, \"CAPE -10-40\n       (obs-bas)\", kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n                    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParCINSurBas, \"CIN (obs-bas)\",\n       kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, \"%.1f\", kLinearly)));\n    */\n\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParBS0_6km,\n                                       \"BS 0-6km\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParBS0_1km,\n                                       \"BS 0-1km\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParSRH0_3km,\n                                       \"SRH 0-3km\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParSRH0_1km,\n                                       \"SRH 0-1km\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParWS1500m,\n                                       \"WS 1500m\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParThetaE0_3km,\n                                       \"ThetaE 0-3km\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n    parBag.Add(NFmiDataIdent(NFmiParam(kSoundingParGDI,\n                                       \"GDI\",\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       kFloatMissing,\n                                       \"%.1f\",\n                                       kLinearly)));\n\n    soundingParams = NFmiParamDescriptor(parBag);\n  }\n\n  return soundingParams;\n}\n\nstatic NFmiQueryInfo MakeSoundingIndexInfo(NFmiQueryData &theSourceData,\n                                           const std::string &theProducerName)\n{\n  NFmiFastQueryInfo fInfo(&theSourceData);\n\n  NFmiParamDescriptor params = ::GetSoundingIndexParams();\n  NFmiProducer usedProducer = *fInfo.Producer();\n  if (theProducerName.empty() == false)\n    usedProducer.SetName(theProducerName);\n  else\n  {\n    NFmiString prodName = usedProducer.GetName();\n    prodName += \" (sounding index)\";\n    usedProducer.SetName(prodName);\n  }\n  params.SetProducer(usedProducer);  // tuottaja pitää asettaa oikeaksi\n\n  NFmiQueryInfo info(\n      params, fInfo.TimeDescriptor(), fInfo.HPlaceDescriptor());  // default vplaceDesc riittää kun\n                                                                  // dataa lasketaan vain yhteen\n                                                                  // tasoon\n  return info;\n}\n\nboost::shared_ptr<NFmiQueryData> NFmiSoundingIndexCalculator::CreateNewSoundingIndexData(\n    const std::string &theSourceFileFilter,\n    const std::string &theProducerName,\n    bool fDoCerrReporting,\n    NFmiStopFunctor *theStopFunctor,\n    bool fUseOnlyOneThread,\n    int theMaxThreadCount)\n{\n  return NFmiSoundingIndexCalculator::CreateNewSoundingIndexData(theSourceFileFilter,\n                                                                 theProducerName,\n                                                                 \"\",\n                                                                 fDoCerrReporting,\n                                                                 theStopFunctor,\n                                                                 fUseOnlyOneThread,\n                                                                 theMaxThreadCount);\n}\n\nconst std::string NFmiSoundingIndexCalculator::itsReadCompatibleGroundData_functionName =\n    \"ReadCompatibleGroundData\";\n\n// Jos thePossibleGroundDataFileFilter ei ole tyhjä, vaaditaan että löytyy data, jossa on sama\n// tuottaja kuin theSourceData:ssa ja niissä sama origin aika. Jos pinta dataa ei vaadita,\n// palautetaan tyhjää. Jos löytyy, palautetaan ladattu data. Jos pintadata vaaditaan, mutta sitä ei\n// löydy, heitetään poikkeus.\nstatic boost::shared_ptr<NFmiQueryData> ReadCompatibleGroundData(\n    const std::string &thePossibleGroundDataFileFilter,\n    boost::shared_ptr<NFmiQueryData> &theSourceData,\n    bool fDoCerrReporting)\n{\n  if (thePossibleGroundDataFileFilter.empty())\n    return boost::shared_ptr<NFmiQueryData>();\n  else\n  {\n    boost::shared_ptr<NFmiQueryData> groundData(\n        NFmiQueryDataUtil::ReadNewestData(thePossibleGroundDataFileFilter));\n    if (!groundData)\n      throw std::runtime_error(\n          NFmiSoundingIndexCalculator::itsReadCompatibleGroundData_functionName +\n          \": Cannot read required ground data \" + thePossibleGroundDataFileFilter);\n    else\n    {\n      if (theSourceData->Info()->Producer()->GetIdent() !=\n          groundData->Info()->Producer()->GetIdent())\n        throw std::runtime_error(\n            NFmiSoundingIndexCalculator::itsReadCompatibleGroundData_functionName +\n            \": Sounding index source data had different producer id than in ground data \" +\n            thePossibleGroundDataFileFilter);\n      else\n      {\n        if (theSourceData->OriginTime() != groundData->OriginTime())\n          throw std::runtime_error(\n              NFmiSoundingIndexCalculator::itsReadCompatibleGroundData_functionName +\n              \": Sounding index source data had different origin time than in ground data \" +\n              thePossibleGroundDataFileFilter);\n        else\n        {\n          if (!groundData->Info()->Param(kFmiPressureAtStationLevel))\n            throw std::runtime_error(\n                NFmiSoundingIndexCalculator::itsReadCompatibleGroundData_functionName +\n                \": Required ground data didn't have the needed PressureAtStationLevel parameter \" +\n                thePossibleGroundDataFileFilter);\n        }\n      }\n    }\n    return groundData;\n  }\n}\n\nboost::shared_ptr<NFmiQueryData> NFmiSoundingIndexCalculator::CreateNewSoundingIndexData(\n    const std::string &theSourceFileFilter,\n    const std::string &theProducerName,\n    const std::string &thePossibleGroundDataFileFilter,\n    bool fDoCerrReporting,\n    NFmiStopFunctor *theStopFunctor,\n    bool fUseOnlyOneThread,\n    int theMaxThreadCount)\n{\n  // 1. lue uusin pohjadata käyttöön\n  boost::shared_ptr<NFmiQueryData> sourceData(\n      NFmiQueryDataUtil::ReadNewestData(theSourceFileFilter));\n  if (sourceData == 0)\n    throw std::runtime_error(\"Error in CreateNewSoundingIndexData, cannot read source data.\");\n  else\n  {\n    if (fDoCerrReporting)\n      std::cerr << \"read qd-file: \" << theSourceFileFilter << std::endl;\n  }\n\n  boost::shared_ptr<NFmiQueryData> possibleGroundData =\n      ::ReadCompatibleGroundData(thePossibleGroundDataFileFilter, sourceData, fDoCerrReporting);\n\n  return NFmiSoundingIndexCalculator::CreateNewSoundingIndexData(sourceData,\n                                                                 possibleGroundData,\n                                                                 theProducerName,\n                                                                 fDoCerrReporting,\n                                                                 theStopFunctor,\n                                                                 fUseOnlyOneThread,\n                                                                 theMaxThreadCount);\n}\n\nboost::shared_ptr<NFmiQueryData> NFmiSoundingIndexCalculator::CreateNewSoundingIndexData(\n    boost::shared_ptr<NFmiQueryData> sourceData,\n    boost::shared_ptr<NFmiQueryData> possibleGroundData,\n    const std::string &theProducerName,\n    bool fDoCerrReporting,\n    NFmiStopFunctor *theStopFunctor,\n    bool fUseOnlyOneThread,\n    int theMaxThreadCount)\n{\n  // 1. luo sen avulla uusi qinfo pohjaksi\n  NFmiQueryInfo soundingIndexInfo = ::MakeSoundingIndexInfo(*sourceData, theProducerName);\n  // 2. luo uusi qdata\n  boost::shared_ptr<NFmiQueryData> data(NFmiQueryDataUtil::CreateEmptyData(soundingIndexInfo));\n  if (data == 0)\n    throw std::runtime_error(\"Error in CreateNewSoundingIndexData, could not create result data.\");\n  // 4. täytä qdata\n  NFmiSoundingIndexCalculator::CalculateWholeSoundingData(*sourceData.get(),\n                                                          *data.get(),\n                                                          possibleGroundData.get(),\n                                                          true,\n                                                          fDoCerrReporting,\n                                                          theStopFunctor,\n                                                          fUseOnlyOneThread,\n                                                          theMaxThreadCount);\n\n  if (theStopFunctor && theStopFunctor->Stop())\n    return boost::shared_ptr<NFmiQueryData>();  // Jos Esim. SmartMetia ollaan sulkemassa ja laskut\n                                                // on lopetettu kesken, ei haluta tallettaa kesken\n                                                // jääneitä laskuja tiedostoon, eli palautetaan\n                                                // tässä tyhjä smart-pointer\n  else\n    return data;\n}\n", "meta": {"hexsha": "4d1889aae7e73453243ab598438b3b7e47649188", "size": 49648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smarttools/NFmiSoundingIndexCalculator.cpp", "max_stars_repo_name": "fmidev/smartmet-library-smarttools", "max_stars_repo_head_hexsha": "de5ab75a66e6c7be72e4425d8c3875fbba7d1704", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smarttools/NFmiSoundingIndexCalculator.cpp", "max_issues_repo_name": "fmidev/smartmet-library-smarttools", "max_issues_repo_head_hexsha": "de5ab75a66e6c7be72e4425d8c3875fbba7d1704", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-08T11:58:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-13T07:40:04.000Z", "max_forks_repo_path": "smarttools/NFmiSoundingIndexCalculator.cpp", "max_forks_repo_name": "fmidev/smartmet-library-smarttools", "max_forks_repo_head_hexsha": "de5ab75a66e6c7be72e4425d8c3875fbba7d1704", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T08:16:56.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-02T08:16:56.000Z", "avg_line_length": 44.8086642599, "max_line_length": 151, "alphanum_fraction": 0.5050354496, "num_tokens": 10597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.029312233931229704, "lm_q1q2_score": 0.013059465954351954}}
{"text": "/**\n * This code is part of Qiskit.\n *\n * (C) Copyright IBM 2018, 2019.\n *\n * This code is licensed under the Apache License, Version 2.0. You may\n * obtain a copy of this license in the LICENSE.txt file in the root directory\n * of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n *\n * Any modifications or derivative works of this code must retain this\n * copyright notice, and modified files need to carry a notice indicating\n * that they have been altered from the originals.\n */\n\n#ifndef _aer_statevector_controller_hpp_\n#define _aer_statevector_controller_hpp_\n\n#include \"base/controller.hpp\"\n#include \"statevector_state.hpp\"\n#include \"framework/json.hpp\"\n#include <chrono>\n#include <ctime>    \n#include <sstream>\n#include <boost/lexical_cast.hpp>\n\n\n#include <limits>\n//#include \"dtoa_milo.h\"\n\nextern \"C\" {\n  #include \"devittsim/Simulator/sim.h\"\n}\n\n#include <Python.h>\n//#include <stdlib.h>\n#include <cmath>\n\nnamespace AER {\nnamespace Simulator {\n\nenum class Gates {\n  id, h, s, sdg, t, tdg, // single qubit\n  // multi-qubit controlled (including single-qubit non-controlled)\n  mcx, mcy, mcz, mcu1, mcu2, mcu3, mcswap\n};\n//=========================================================================\n// StatevectorController class\n//=========================================================================\n\n/**************************************************************************\n * Config settings:\n * \n * From Statevector::State class\n * \n * - \"initial_statevector\" (json complex vector): Use a custom initial\n *      statevector for the simulation [Default: null].\n * - \"zero_threshold\" (double): Threshold for truncating small values to\n *      zero in result data [Default: 1e-10]\n * - \"statevector_parallel_threshold\" (int): Threshold that number of qubits\n *      must be greater than to enable OpenMP parallelization at State\n *      level [Default: 13]\n * - \"statevector_sample_measure_opt\" (int): Threshold that number of qubits\n *      must be greater than to enable indexing optimization during\n *      measure sampling [Default: 10]\n * - \"statevector_hpc_gate_opt\" (bool): Enable large qubit gate optimizations.\n *      [Default: False]\n * \n * From BaseController Class\n *\n * - \"max_parallel_threads\" (int): Set the maximum OpenMP threads that may\n *      be used across all levels of parallelization. Set to 0 for maximum\n *      available. [Default : 0]\n * - \"max_parallel_experiments\" (int): Set number of circuits that may be\n *      executed in parallel. Set to 0 to use the number of max parallel\n *      threads [Default: 1]\n * - \"counts\" (bool): Return counts object in circuit data [Default: True]\n * - \"snapshots\" (bool): Return snapshots object in circuit data [Default: True]\n * - \"memory\" (bool): Return memory array in circuit data [Default: False]\n * - \"register\" (bool): Return register array in circuit data [Default: False]\n * \n **************************************************************************/\n\nconst stringmap_t<Gates> ma_gateset_({\n  // Single qubit gates\n  {\"id\", Gates::id},     // Pauli-Identity gate\n  {\"x\", Gates::mcx},     // Pauli-X gate\n  {\"y\", Gates::mcy},     // Pauli-Y gate\n  {\"z\", Gates::mcz},     // Pauli-Z gate\n  {\"s\", Gates::s},       // Phase gate (aka sqrt(Z) gate)\n  {\"sdg\", Gates::sdg},   // Conjugate-transpose of Phase gate\n  {\"h\", Gates::h},       // Hadamard gate (X + Z / sqrt(2))\n  {\"t\", Gates::t},       // T-gate (sqrt(S))\n  {\"tdg\", Gates::tdg},   // Conjguate-transpose of T gate\n  // Waltz Gates\n  {\"u1\", Gates::mcu1},   // zero-X90 pulse waltz gate\n  {\"u2\", Gates::mcu2},   // single-X90 pulse waltz gate\n  {\"u3\", Gates::mcu3},   // two X90 pulse waltz gate\n  // Two-qubit gates\n  {\"cx\", Gates::mcx},        // Controlled-X gate (CNOT)\n  {\"cy\", Gates::mcy},        // Controlled-Y gate\n  {\"cz\", Gates::mcz},        // Controlled-Z gate\n  /*{\"cu1\", Gates::mcu1},      // Controlled-u1 gate\n  {\"cu2\", Gates::mcu2},      // Controlled-u2 gate\n  {\"cu3\", Gates::mcu3},      // Controlled-u3 gate\n  */\n  {\"swap\", Gates::mcswap},   // SWAP gate\n  // 3-qubit gates\n  //{\"ccx\", Gates::mcx},       // Controlled-CX gate (Toffoli)\n  //{\"cswap\", Gates::mcswap},  // Controlled SWAP gate (Fredkin)\n  // Multi-qubit controlled gates\n  /*{\"mcx\", Gates::mcx},      // Multi-controlled-X gate\n  {\"mcy\", Gates::mcy},      // Multi-controlled-Y gate\n  {\"mcz\", Gates::mcz},      // Multi-controlled-Z gate\n  {\"mcu1\", Gates::mcu1},    // Multi-controlled-u1\n  {\"mcu2\", Gates::mcu2},    // Multi-controlled-u2\n  {\"mcu3\", Gates::mcu3},    // Multi-controlled-u3\n  {\"mcswap\", Gates::mcswap} // Multi-controlled SWAP gate\n  */\n});\nclass StatevectorController : public Base::Controller {\npublic:\n  //-----------------------------------------------------------------------\n  // Base class config override\n  //-----------------------------------------------------------------------\n  StatevectorController();\n\n  // Load Controller, State and Data config from a JSON\n  // config settings will be passed to the State and Data classes\n  // Allowed config options:\n  // - \"initial_statevector: complex_vector\"\n  // Plus Base Controller config options\n  virtual void set_config(const json_t &config) override;\n\n  // Clear the current config\n  void virtual clear_config() override;\n\nprotected:\n\n  virtual size_t required_memory_mb(const Circuit& circuit,\n                                    const Noise::NoiseModel& noise) const override;\n\nprivate:\n\n  //-----------------------------------------------------------------------\n  // Base class abstract method override\n  //-----------------------------------------------------------------------\n\n  // This simulator will only return a single shot, regardless of the\n  // input shot number\n\n  virtual void ds_apply_ops(ds_Register ds_reg, const Circuit &circ, const std::unordered_set<int> & x_errors, const std::unordered_set<int> & y_errors, const std::unordered_set<int> & z_errors) const;\n  virtual void check_and_inject(ds_Register ds_reg, long position, int qubit, const std::unordered_set<int> & x_errors, const std::unordered_set<int> & y_errors, const std::unordered_set<int> & z_errors) const;\n\n  virtual ExperimentData run_circuit(const Circuit &circ,\n                                 const Noise::NoiseModel& noise,\n                                 const json_t &config,\n                                 uint_t shots,\n                                 uint_t rng_seed) const override;\n\n  virtual ExperimentData direct_ds_sim(const Circuit &circ,\n                                 const Noise::NoiseModel& noise,\n                                 const json_t &config,\n                                 uint_t shots,\n                                 uint_t rng_seed) const;\n\n  virtual ExperimentData inject_n_errors(const Circuit &circ,\n                                 const Noise::NoiseModel& noise,\n                                 const json_t &config,\n                                 uint_t shots,\n                                 uint_t rng_seed) const;\n\n  virtual ExperimentData get_hotspots(const Circuit &circ,\n                                 const Noise::NoiseModel& noise,\n                                 const json_t &config,\n                                 uint_t shots,\n                                 uint_t rng_seed) const;\n  //-----------------------------------------------------------------------\n  // Custom initial state\n  //-----------------------------------------------------------------------        \n  cvector_t initial_state_;\n};\n\n//=========================================================================\n// Implementations\n//=========================================================================\n\nStatevectorController::StatevectorController() : Base::Controller() {\n  // Disable qubit truncation by default\n  Base::Controller::truncate_qubits_ = false;\n}\n\n//-------------------------------------------------------------------------\n// Config\n//-------------------------------------------------------------------------\n\nvoid StatevectorController::set_config(const json_t &config) {\n  // Set base controller config\n  Base::Controller::set_config(config);\n\n  //Add custom initial state\n  if (JSON::get_value(initial_state_, \"initial_statevector\", config)) {\n    // Check initial state is normalized\n    if (!Utils::is_unit_vector(initial_state_, validation_threshold_))\n      throw std::runtime_error(\"StatevectorController: initial_statevector is not a unit vector\");\n  }\n}\n\nvoid StatevectorController::clear_config() {\n  Base::Controller::clear_config();\n  initial_state_ = cvector_t();\n}\n\nsize_t StatevectorController::required_memory_mb(const Circuit& circ,\n                                                 const Noise::NoiseModel& noise) const {\n  //Statevector::State<> state;\n  //return state.required_memory_mb(circ.num_qubits, circ.ops);\n  return 32;\n}\n\n//-------------------------------------------------------------------------\n// Run circuit\n//-------------------------------------------------------------------------\n\nvoid StatevectorController::check_and_inject(ds_Register ds_reg, long position, int qubit, const std::unordered_set<int> & x_errors, const std::unordered_set<int> & y_errors, const std::unordered_set<int> & z_errors) const{\n  if(x_errors.count(position) != 0){\n    ds_X_no_error(ds_reg, qubit, 1);\n    ds_reg.n_errors[0] += 1;\n  }\n  if(y_errors.count(position) != 0){   \n    ds_XZ_no_error(ds_reg, qubit, 1);\n    ds_reg.n_errors[2] += 1;\n  }\n  if(z_errors.count(position) != 0){   \n    ds_Z_no_error(ds_reg, qubit, 1);\n    ds_reg.n_errors[1] += 1;\n  }\n}\nvoid StatevectorController::ds_apply_ops(ds_Register ds_reg, const Circuit &circ,const std::unordered_set<int> & x_errors, const std::unordered_set<int> & y_errors, const std::unordered_set<int> & z_errors) const {\n  int gate_time = 1;\n  long gate_position = 0;\n  std::unordered_set<int> qubit_init_done;\n  //std::cout<<\"Add code for errors directly after initialization!\" << std::endl;\n\n  for(int i = 0; i < circ.num_qubits; i++){\n    check_and_inject(ds_reg, i, i, x_errors, y_errors, z_errors);\n  }\n  gate_position += circ.num_qubits;\n  bool do_init_errors = true;\n  for (const auto & op: circ.ops) {\n    reg_t oqs = op.qubits;\n    const size_t Nqs = op.qubits.size();\n    switch (op.type) {\n      case Operations::OpType::gate:\n        auto it = ma_gateset_.find(op.name);\n        if (it == ma_gateset_.end())\n          throw std::invalid_argument(\"QubitVectorState::invalid gate instruction \\'\" + \n                                      op.name + \"\\'.\");\n        switch (it -> second) {\n\t  case Gates::mcx:\n\t    // Includes X, CX, CCX, etc\n\t    //BaseState::qreg_.apply_mcx(op.qubits);\n            if (Nqs == 1){\n              ds_X(ds_reg,oqs[0],gate_time);\n            }\n            else if(Nqs == 2){\n              ds_cnot(ds_reg,oqs[0],oqs[1], gate_time);\n            }\n            else {\n                throw std::invalid_argument(\"QubitVectorState::invalid gate instruction \\'\" +\n                                            op.name + \"\\'. X with more than 2 argument qubits\");\n            }\n\t    break;            \n          case Gates::mcy:\n\t    // Includes Y, CY, CCY, etc\n\t    //BaseState::qreg_.apply_mcy(op.qubits);\n            if (Nqs == 1){\n              ds_XZ(ds_reg,oqs[0],gate_time);\n            }\n            else {\n              throw std::invalid_argument(\"QubitVectorState::invalid gate instruction \\'\" +\n                                          op.name + \"\\'. Y with more than 2 argument qubits\");\n            }\n\t    break;\n\t  case Gates::mcz:\n\t    // Includes Z, CZ, CCZ, etc\n\t    //BaseState::qreg_.apply_mcphase(op.qubits, -1);\n            if (Nqs == 1){\n              ds_Z(ds_reg,oqs[0],gate_time);\n            }\n            else {\n                throw std::invalid_argument(\"QubitVectorState::invalid gate instruction \\'\" +\n                                            op.name + \"\\'. Z with more than 2 argument qubits\");\n            }\n\t    break;\n            \n\t  case Gates::id:\n\t    break;\n\t  case Gates::h:\n\t    //apply_gate_mcu3(op.qubits, M_PI / 2., 0., M_PI);\n            if (Nqs == 1){\n              ds_Hadamard(ds_reg,oqs[0],gate_time);\n            }\n            else {\n                throw std::invalid_argument(\"QubitVectorState::invalid gate instruction \\'\" +\n                                            op.name + \"\\'. H with more than 2 argument qubits\");\n            }\n\t    break;\n          /*\n          case Gates::s:\n            apply_gate_phase(op.qubits[0], complex_t(0., 1.));\n            break;\n          case Gates::sdg:\n            apply_gate_phase(op.qubits[0], complex_t(0., -1.));\n            break;\n          case Gates::t: {\n            const double isqrt2{1. / std::sqrt(2)};\n            apply_gate_phase(op.qubits[0], complex_t(isqrt2, isqrt2));\n          } break;\n          case Gates::tdg: {\n            const double isqrt2{1. / std::sqrt(2)};\n            apply_gate_phase(op.qubits[0], complex_t(isqrt2, -isqrt2));\n          } break;\n          case Gates::mcswap:\n            // Includes SWAP, CSWAP, etc\n            BaseState::qreg_.apply_mcswap(op.qubits);\n            break;\n          case Gates::mcu3:\n            // Includes u3, cu3, etc\n            apply_gate_mcu3(op.qubits,\n\t\t\t      std::real(op.params[0]),\n\t\t\t      std::real(op.params[1]),\n\t\t\t      std::real(op.params[2]));\n            break;\n          case Gates::mcu2:\n\t    // Includes u2, cu2, etc\n\t    apply_gate_mcu3(op.qubits,\n\t\t    apply_gate(op);\n\t\t    break;\n          */\n          default:\n            throw std::invalid_argument(\"QubitVector::State::invalid instruction \\'\" +\n                                        op.name + \"\\'.\");\n        }\n     }\n    \n    for(int i = 0; i < Nqs; i++){\n      check_and_inject(ds_reg, gate_position, oqs[i], x_errors, y_errors, z_errors);\n      gate_position += 1;\n    }\n\n  }\n  /*for(i=0;i<qs;i++){\n    ds_Hadamard(ds_reg, i, 1);\t\t\n  }\n  for(i=0;i<qs;i++){\n    ds_Z(ds_reg, i, 1);\t\t\n  }\n  for(i=0;i<qs;i++){\n    ds_Hadamard(ds_reg, i, 1);\t\t\n  }*/\n}\n\nExperimentData StatevectorController::direct_ds_sim(const Circuit &circ,\n                                 const Noise::NoiseModel& noise,\n                                 const json_t &config,\n                                 uint_t shots,\n                                 uint_t rng_seed) const {\n {\n\n    Statevector::State<> state;\n    // Set config\n    state.set_config(config);\n    double error_rate=-1.0;\n    JSON::get_value(error_rate, \"ds_error_rate\",config);\n    // Rng engine\n    //RngEngine rng;\n    //rng.set_seed(rng_seed);\n\n    // Output data container\n    ExperimentData data;\n    data.set_config(config);   \n    \n    int i;\n    int qs = circ.num_qubits;\n\n    int gate_time=1;\n    long ds_seed_offset = 0;\n    JSON::get_value(ds_seed_offset, \"ds_seed_offset\",config);\n\n    long ds_seed_py = rng_seed+ds_seed_offset;\n    ds_initialize_simulator(ds_seed_offset);\n    \n    ds_Register ds_reg;\n    ds_reg = ds_create_register(qs, error_rate, 0);\n    ds_set_state(ds_reg, 0, 1, 0);\n    // apply ops\t\n    //state.apply_ops(circ.ops, data, rng);\n    std::unordered_set <int> x_errors, y_errors, z_errors;\n    ds_apply_ops(ds_reg, circ, x_errors, y_errors, z_errors);\n    //std::vector<std::complex<double>> state_from_sim;\n    //cvector_t state_from_sim;\n\n    std::time_t done_sim = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n    //std::cout << \"done sim at: \"<<std::ctime(&done_sim) <<\"nc: \" <<ds_reg.nc<<std::endl;\n\n    //std::vector<complex_t> state_from_sim;\n    //data.sv_vec.reserve(ds_reg.nc);\n\n    //PyObject* resList = PyList_New(ds_reg.nc);\n    data.sv_list = PyList_New(ds_reg.nc);\n\n    //std::cout<<\"injected \"<<ds_reg.n_errors[0]<<\" X-errors \"<<ds_reg.n_errors[1]<<\" Z-errors and \"<<ds_reg.n_errors[2]<<\" Y-Errors\" << std::endl;\n    \n\n    data.add_additional_data(\"x_errors\", ds_reg.n_errors[0]);\n    data.add_additional_data(\"z_errors\", ds_reg.n_errors[1]);\n    data.add_additional_data(\"y_errors\", ds_reg.n_errors[2]);\n    for(i=0;i<ds_reg.nc;i++){\n      //std::cout<<\" i: \"<<i<<\" x: \"<<ds_reg.state[i].x<<\" <: \"<<ds_reg.state[i].y<<std::endl;\n      //data.sv_vec.emplace_back(std::complex<double>{ds_reg.state[i].x, ds_reg.state[i].y});\n\n      //PyList_SetItem(data.sv_list, i, PyComplex_FromDoubles(0.1,-0.3));\n      PyList_SetItem(data.sv_list, i, PyComplex_FromDoubles(ds_reg.state[i].x, ds_reg.state[i].y));\n    }\n\n    /*\n    for(i=0;i<ds_reg.nc;i++){\n      //std::ostringstream strs;\n      //strs <<std::setprecision(std::numeric_limits<double>::max_digits10)<< ds_reg.state[i].x<<\"+\"<<ds_reg.state[i].y<<\"j\";\n      //state_from_sim.emplace_back(std::complex<double>{ds_reg.state[i].x, ds_reg.state[i].y});\n      char buffer1[256] = { '\\0' };\n      char buffer2[256] = { '\\0' };\n      dtoa_milo(ds_reg.state[i].x, buffer1);\n      dtoa_milo(ds_reg.state[i].y, buffer2);\n\n      std::string strbuffer1(buffer1);\n      std::string strbuffer2(buffer2);\n      //strbuffer+= strbuffer1 + \"+\"+strbuffer2+\"j\";\n      state_from_sim.emplace_back(strbuffer1+\"+\"+strbuffer2+\"j\");\n      //state_from_sim.emplace_back(boost::lexical_cast<std::string>(ds_reg.state[i].x)+\"+\"+boost::lexical_cast<std::string>(ds_reg.state[i].y)+\"j\");\n    }\n    */\n    //ds_print(ds_reg);\n    // translate ds_reg to std::vector<std::complex<RealType>> ret;\n    //\n\n    std::time_t bfddone_sim = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n    //std::cout << \"bafore destroy at: \"<<std::ctime(&bfddone_sim) <<std::endl;\n    //:wqds_reg = &ds_reg;\n   //std::cout<<\"injected \"<<ds_reg.n_errors<<\" errors\" << std::endl;\n    ds_destroy_register(ds_reg);\n    //state.add_creg_to_data(data);\n    //json_t jdata = state_from_sim; \n    // Add final state to the data\n    //json_t datRes = state_from_sim;\n    //data.add_additional_data(\"statevector\",datRes);\n    //data.sv_vec=state_from_sim;\n    //data.sv_list = resList;\n    //ExperimentData data2;\n    //data2.set_config(config);   \n    //data.sim_reg = ds_reg;\n    std::time_t end_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n    //std::cout << \"done sim at: \"<<std::ctime(&end_time) <<std::endl;\n    return data;\n  }\n}\n\nExperimentData StatevectorController::inject_n_errors(const Circuit &circ,\n                                 const Noise::NoiseModel& noise,\n                                 const json_t &config,\n                                 uint_t shots,\n                                 uint_t rng_seed) const {\n    Statevector::State<> state;\n    // Set config\n    state.set_config(config);\n    double error_rate=-1.0;\n    JSON::get_value(error_rate, \"ds_error_rate\",config);\n    // Rng engine\n    RngEngine rng;\n    rng.set_seed(rng_seed);\n\n    // Output data container\n    ExperimentData data;\n    data.set_config(config);   \n    \n    int i;\n    int qs = circ.num_qubits;\n\n    int gate_time=1;\n    long ds_seed_offset = 1;\n    JSON::get_value(ds_seed_offset, \"ds_seed_offset\",config);\n\n    long ds_seed_py = rng_seed+ds_seed_offset;\n    ds_initialize_simulator(ds_seed_offset);\n    \n    ds_Register ds_reg;\n    //error-free, errors are injected using x_/y_/z_errors in ds_apply_ops\n    ds_reg = ds_create_register(qs, 0, 0);\n    ds_set_state(ds_reg, 0, 1, 0);\n    // apply ops\t\n    //state.apply_ops(circ.ops, data, rng);\n    std::unordered_set <int> x_errors, y_errors, z_errors;\n\n    //std::cout << \"ds::before first apply_ops\" <<std::endl;\n    ds_apply_ops(ds_reg, circ, x_errors, y_errors, z_errors);\n    //std::vector<std::complex<double>> state_from_sim;\n    //cvector_t state_from_sim;\n\n    //std::cout << \"ds::after first apply_ops\" <<std::endl;\n    int *qubits_to_measure = new int[qs];\n    for(int j=0;j<qs;j++){\n      qubits_to_measure[j] = qs - j - 1;\n    }\n\n    //std::cout << \"ds::before measure\" <<std::endl;\n    double correct_result = ds_set_measure(ds_reg, qs, qubits_to_measure, (1 << qs) - 1);\n    int locations = 0;\n    // locations gives how many positions there are to inject an error\n    for(int j = 0; j<qs; j++){\n      locations += ds_reg.steps[j];\n    }\n    // allow for init errors\n    locations += qs;\n    //std::cout << \" number of locations in circuit: \" << locations << std::endl;\n    //get number of errors\n    long num_x_errors, num_y_errors, num_z_errors;  \n    num_x_errors = 0;\n    num_y_errors = 0;\n    num_z_errors = 0;\n\n    JSON::get_value(num_x_errors, \"ds_num_x_errors\", config);\n    JSON::get_value(num_y_errors, \"ds_num_y_errors\", config);\n    JSON::get_value(num_z_errors, \"ds_num_z_errors\", config);\n    \n    // create arrays that store the location of the errors\n    std::vector<int> x_error_locations, y_error_locations, z_error_locations;\n\n    x_error_locations.resize(num_x_errors);\n    y_error_locations.resize(num_y_errors);\n    z_error_locations.resize(num_z_errors);\n\n    // repeat simulations num_iterations times\n    int num_iterations;  \n    num_iterations = 1;\n    JSON::get_value(num_iterations, \"ds_num_iterations\", config);\n    std::vector<double> result_ar;\n    result_ar.reserve(num_iterations);\n\n    //std::cout << \"ds::before iterations\" <<std::endl;\n    for(int iteration=0;iteration<num_iterations;iteration++){\n\n      x_errors.clear();\n      y_errors.clear();\n      z_errors.clear();\n\n      for(int j=0; j<num_x_errors; j++)\n        x_error_locations.at(j) = rng.rand_int((int_t) 0, (int_t) (locations-1)); //interval excluding #locations\n\n      for(int j=0; j<num_y_errors; j++)\n        y_error_locations.at(j) = rng.rand_int((int_t)0, (int_t) locations-1); //interval excluding #locations\n\n      for(int j=0; j<num_z_errors; j++)\n        z_error_locations.at(j) = rng.rand_int((int_t)0, (int_t) locations-1); //interval excluding #locations\n\n      // only inject if there is an odd number of errors at a location\n      for(int j=0; j<num_x_errors; j++)\n        if(std::count(x_error_locations.begin(), x_error_locations.end(), x_error_locations[j]) % 2 == 1)\n          x_errors.insert(x_error_locations[j]);\n \n      for(int j=0; j<num_y_errors; j++)\n        if(std::count(y_error_locations.begin(), y_error_locations.end(), y_error_locations[j]) % 2 == 1)\n          y_errors.insert(y_error_locations[j]);\n\n      for(int j=0; j<num_z_errors; j++)\n        if(std::count(z_error_locations.begin(), z_error_locations.end(), z_error_locations[j]) % 2 == 1)\n          z_errors.insert(z_error_locations[j]);\n      // reset ds_reg and start new simulation with errors injected at locations given by unordered sets x_/y_/z_errors\n      ds_clearreg(ds_reg);\n      ds_set_state(ds_reg, 0, 1, 0);   \n\n      //std::cout << \"ds::before iteration apply ops\" <<std::endl;\n      ds_apply_ops(ds_reg, circ, x_errors, y_errors, z_errors);\n\n      //std::cout << \"ds::after iteration apply ops\" <<std::endl;\n      double result_with_error = ds_set_measure(ds_reg, qs, qubits_to_measure, (1<<qs) - 1);\n\n      //std::cout << \"ds::after iteration apply op measurement: \"<< result_with_error <<std::endl;\n      result_ar.push_back(result_with_error);\n    }\n    //TODO: return result_ar\n    //\n\n    //std::cout << \"ds::done adding info to return object\" <<std::endl;\n    data.add_additional_data(\"result-ar\", result_ar);\n    data.add_additional_data(\"correct-result\", correct_result);\n\n    //data.add_additional_data(\"x_errors\", ds_reg.n_errors[0]);\n    //data.add_additional_data(\"z_errors\", ds_reg.n_errors[1]);\n    //data.add_additional_data(\"y_errors\", ds_reg.n_errors[2]);\n\n    data.sv_list = PyList_New(ds_reg.nc);\n\n    //std::cout<<\"injected \"<<ds_reg.n_errors[0]<<\" X-errors \"<<ds_reg.n_errors[1]<<\" Z-errors and \"<<ds_reg.n_errors[2]<<\" Y-Errors\" << std::endl;\n    \n\n    data.add_additional_data(\"x_errors\", ds_reg.n_errors[0]);\n    data.add_additional_data(\"z_errors\", ds_reg.n_errors[1]);\n    data.add_additional_data(\"y_errors\", ds_reg.n_errors[2]);\n    for(i=0;i<ds_reg.nc;i++){\n      //std::cout<<\" i: \"<<i<<\" x: \"<<ds_reg.state[i].x<<\" <: \"<<ds_reg.state[i].y<<std::endl;\n      //data.sv_vec.emplace_back(std::complex<double>{ds_reg.state[i].x, ds_reg.state[i].y});\n\n      //PyList_SetItem(data.sv_list, i, PyComplex_FromDoubles(0.1,-0.3));\n      PyList_SetItem(data.sv_list, i, PyComplex_FromDoubles(ds_reg.state[i].x, ds_reg.state[i].y));\n    }\n\n    data.add_additional_data(\"x_error_locs\", x_errors);\n    data.add_additional_data(\"z_error_locs\", z_errors);\n    data.add_additional_data(\"y_error_locs\", y_errors);\n\n    ds_destroy_register(ds_reg);\n\n    delete[] qubits_to_measure;\n\n    //std::cout << \"ds::returning data\" <<std::endl;\n    //state.add_creg_to_data(data);\n    //json_t jdata = state_from_sim; \n    // Add final state to the data\n    //json_t datRes = state_from_sim;\n    //data.add_additional_data(\"statevector\",datRes);\n    //data.sv_vec=state_from_sim;\n    //data.sv_list = resList;\n    //ExperimentData data2;\n    //data2.set_config(config);   \n    //data.sim_reg = ds_reg;\n    //std::time_t end_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n    //std::cout << \"done sim at: \"<<std::ctime(&end_time) <<std::endl;\n    return data;\n}\n\nExperimentData StatevectorController::get_hotspots(const Circuit &circ,\n                                 const Noise::NoiseModel& noise,\n                                 const json_t &config,\n                                 uint_t shots,\n                                 uint_t rng_seed) const {\n/* TODO\n * similar to inject_n_errors: iterate over every location, do simulation with error at that location, divide and get probiablity for noisy result by correct result? or by 1/2^Qubits\n *\n * */\n\n    Statevector::State<> state;\n    // Set config\n    state.set_config(config);\n    double error_rate=-1.0;\n    JSON::get_value(error_rate, \"ds_error_rate\",config);\n    // Rng engine\n    RngEngine rng;\n    rng.set_seed(rng_seed);\n\n    // Output data container\n    ExperimentData data;\n    data.set_config(config);   \n    \n    int i;\n    int qs = circ.num_qubits;\n\n    int gate_time=1;\n    long ds_seed_offset = 1;\n    JSON::get_value(ds_seed_offset, \"ds_seed_offset\",config);\n\n    long ds_seed_py = rng_seed+ds_seed_offset;\n    ds_initialize_simulator(ds_seed_offset);\n    \n    ds_Register ds_reg;\n    //error-free, errors are injected using x_/y_/z_errors in ds_apply_ops\n    ds_reg = ds_create_register(qs, 0, 0);\n    ds_set_state(ds_reg, 0, 1, 0);\n    // apply ops\t\n    //state.apply_ops(circ.ops, data, rng);\n    std::unordered_set <int> x_errors, y_errors, z_errors;\n    ds_apply_ops(ds_reg, circ, x_errors, y_errors, z_errors);\n    //std::vector<std::complex<double>> state_from_sim;\n    //cvector_t state_from_sim;\n    int *qubits_to_measure = new int[qs];\n    for(int j=0;j<qs;j++){\n      qubits_to_measure[j] = qs - j - 1;\n    }\n    double correct_result = ds_set_measure(ds_reg, qs, qubits_to_measure, (1<<qs) - 1);\n    int locations = 0;\n    // locations gives how many positions there are to inject an error\n    for(int j = 0; j<qs; j++){\n      locations += ds_reg.steps[j];\n    }\n    // allow for init errors\n    locations += qs;\n\n    std::vector<double> result_ar_x;\n    std::vector<double> result_ar_y;\n    std::vector<double> result_ar_z;\n\n    result_ar_x.reserve(locations);\n    result_ar_y.reserve(locations);\n    result_ar_z.reserve(locations);\n\n    for(int location=0; location<locations;location++){\n      x_errors.insert(location);      \n      ds_clearreg(ds_reg);\n      ds_set_state(ds_reg, 0, 1, 0);   \n      ds_apply_ops(ds_reg, circ, x_errors, y_errors, z_errors);\n      double result_with_error = ds_set_measure(ds_reg, qs, qubits_to_measure, (1<<qs) - 1);\n      result_ar_x[location] = result_with_error;\n      x_errors.clear(); \n    }\n\n    for(int location=0; location<locations;location++){\n      y_errors.insert(location);      \n      ds_clearreg(ds_reg);\n      ds_set_state(ds_reg, 0, 1, 0);   \n      ds_apply_ops(ds_reg, circ, x_errors, y_errors, z_errors);\n      double result_with_error = ds_set_measure(ds_reg, qs, qubits_to_measure, (1<<qs) - 1);\n      result_ar_y[location] = result_with_error;\n      y_errors.clear(); \n    }\n\n    for(int location=0; location<locations;location++){\n      z_errors.insert(location);      \n      ds_clearreg(ds_reg);\n      ds_set_state(ds_reg, 0, 1, 0);   \n      ds_apply_ops(ds_reg, circ, x_errors, y_errors, z_errors);\n      double result_with_error = ds_set_measure(ds_reg, qs, qubits_to_measure, (1<<qs) - 1);\n      result_ar_z[location] = result_with_error;\n      z_errors.clear(); \n    }\n\n    data.add_additional_data(\"result-ar-x\",result_ar_x);\n    data.add_additional_data(\"result-ar-y\",result_ar_y);\n    data.add_additional_data(\"result-ar-z\",result_ar_z);\n\n    data.add_additional_data(\"correct-result\", correct_result);\n}\nExperimentData StatevectorController::run_circuit(const Circuit &circ,\n                                              const Noise::NoiseModel& noise,\n                                              const json_t &config,\n                                              uint_t shots,\n                                              uint_t rng_seed) const {\n  // Initialize  state\n  Statevector::State<> state;\n\n  //std::time_t sstart_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n  //std::cout << \"start sim at: \"<<std::ctime(&sstart_time) <<std::endl;\n  bool is_devitt_sim = false;\n  bool is_inject_n_errors = false;\n  bool is_hotspots = false;\n\n  JSON::get_value(is_devitt_sim, \"ds_direct_sim\",config);\n  JSON::get_value(is_inject_n_errors, \"ds_inject_n_errors\",config);\n  JSON::get_value(is_hotspots, \"ds_hotspots\",config);\n  if(is_devitt_sim){\n    return direct_ds_sim(circ, noise, config, shots, rng_seed);\n  }\n  else if(is_inject_n_errors){  \n    std::cout << \"start running inject n errors\" <<std::endl;\n    return inject_n_errors(circ, noise, config, shots, rng_seed);\n  }\n  else if(is_hotspots){\n    return get_hotspots(circ, noise, config, shots, rng_seed);\n  }\n  else {\n    std::cout << \"Old Code! Did not check functionality.\"<<std::endl;\n    // Set config\n    state.set_config(config);\n    state.set_parallalization(parallel_state_update_);\n    \n    // Rng engine\n    RngEngine rng;\n    rng.set_seed(rng_seed);\n \n    // Output data container\n    ExperimentData data;\n    data.set_config(config);\n    \n    // Run single shot collecting measure data or snapshots\n    if (initial_state_.empty())\n      state.initialize_qreg(circ.num_qubits);\n    else\n      state.initialize_qreg(circ.num_qubits, initial_state_);\n    state.initialize_creg(circ.num_memory, circ.num_registers);\n    //state.apply_ops(circ.ops, data, rng);\n    state.add_creg_to_data(data);\n    \n    // Add final state to the data\n    data.add_additional_data(\"statevector\", state.qreg().vector());\n  \n    return data;\n  }\n}\n\n//-------------------------------------------------------------------------\n} // end namespace Simulator\n//-------------------------------------------------------------------------\n} // end namespace AER\n//-------------------------------------------------------------------------\n#endif\n", "meta": {"hexsha": "91968306ff721820ca5bf992be5d1c38f60ee4bd", "size": 30862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simulators/statevector/statevector_controller.hpp", "max_stars_repo_name": "brandhsn/qiskit-aer", "max_stars_repo_head_hexsha": "c6bf825e0da103e3d839da20e191e5f624b8f808", "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/simulators/statevector/statevector_controller.hpp", "max_issues_repo_name": "brandhsn/qiskit-aer", "max_issues_repo_head_hexsha": "c6bf825e0da103e3d839da20e191e5f624b8f808", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulators/statevector/statevector_controller.hpp", "max_forks_repo_name": "brandhsn/qiskit-aer", "max_forks_repo_head_hexsha": "c6bf825e0da103e3d839da20e191e5f624b8f808", "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.3855721393, "max_line_length": 223, "alphanum_fraction": 0.5957812196, "num_tokens": 7734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.027169234194192645, "lm_q1q2_score": 0.013054237729199674}}
{"text": "/// \\file   python_module_walras.cpp\n///\n/// \\brief\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2020-10-11\n/// \\copyright  Copyright 2017-2020 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#include <esl/economics/markets/walras/python_module_walras.hpp>\n#include <esl/economics/markets/walras/price_setter.hpp>\n#include <esl/economics/markets/walras/tatonnement.hpp>\n\n\n#ifdef WITH_PYTHON\n#define BOOST_BIND_GLOBAL_PLACEHOLDERS\n#include <boost/python.hpp>\n\nusing namespace boost::python;\nusing namespace esl::economics::markets;\nusing namespace esl::economics::markets::tatonnement;\n\nBOOST_PYTHON_MODULE(_walras)\n{\n    enum_<excess_demand_model::solver>(\"solver\")\n        .value(\"root\", excess_demand_model::root)\n        .value(\"minimization\", excess_demand_model::minimization)\n        .export_values()\n        ;\n\n    class_<excess_demand_model>(\"excess_demand_model\", init<esl::law::property_map<quote>>())\n    .def_readwrite(\"circuit_breaker\", &excess_demand_model::circuit_breaker)\n        .def_readwrite(\"methods\", &excess_demand_model::methods)\n        .def_readwrite(\"quotes\", &excess_demand_model::quotes)\n        .def(\"compute_clearing_quotes\", &excess_demand_model::compute_clearing_quotes)\n        ;\n\n}\n\n#endif\n", "meta": {"hexsha": "ef0ddfa568119005db1beb5587bc1a05a2fbb06a", "size": 2088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "esl/economics/markets/walras/python_module_walras.cpp", "max_stars_repo_name": "rht/ESL", "max_stars_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "esl/economics/markets/walras/python_module_walras.cpp", "max_issues_repo_name": "rht/ESL", "max_issues_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/economics/markets/walras/python_module_walras.cpp", "max_forks_repo_name": "rht/ESL", "max_forks_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-27T12:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T12:11:48.000Z", "avg_line_length": 37.2857142857, "max_line_length": 93, "alphanum_fraction": 0.68151341, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.03358950698030742, "lm_q1q2_score": 0.013053488396394242}}
{"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 I/O stream operations.\r\n\r\n#ifndef BOOST_MATH_CSTDFLOAT_IOSTREAM_2014_02_15_HPP_\r\n  #define BOOST_MATH_CSTDFLOAT_IOSTREAM_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  #include <boost/math/cstdfloat/cstdfloat_cmath.hpp>\r\n\r\n  #if defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH)\r\n  #error You can not use <boost/math/cstdfloat/cstdfloat_iostream.hpp> with BOOST_CSTDFLOAT_NO_LIBQUADMATH_CMATH defined.\r\n  #endif\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 <cstddef>\r\n  #include <istream>\r\n  #include <ostream>\r\n  #include <sstream>\r\n  #include <stdexcept>\r\n  #include <string>\r\n  #include <boost/static_assert.hpp>\r\n  #include <boost/throw_exception.hpp>\r\n\r\n//  #if (0)\r\n  #if defined(__GNUC__)\r\n\r\n  // Forward declarations of quadruple-precision string functions.\r\n  extern \"C\" int quadmath_snprintf(char *str, size_t size, const char *format, ...) throw();\r\n  extern \"C\" boost::math::cstdfloat::detail::float_internal128_t strtoflt128(const char*, char **) throw();\r\n\r\n  namespace std\r\n  {\r\n    template<typename char_type, class traits_type>\r\n    inline std::basic_ostream<char_type, traits_type>& operator<<(std::basic_ostream<char_type, traits_type>& os, const boost::math::cstdfloat::detail::float_internal128_t& x)\r\n    {\r\n      std::basic_ostringstream<char_type, traits_type> ostr;\r\n      ostr.flags(os.flags());\r\n      ostr.imbue(os.getloc());\r\n      ostr.precision(os.precision());\r\n\r\n      char my_buffer[64U];\r\n\r\n      const int my_prec   = static_cast<int>(os.precision());\r\n      const int my_digits = ((my_prec == 0) ? 36 : my_prec);\r\n\r\n      const std::ios_base::fmtflags my_flags  = os.flags();\r\n\r\n      char my_format_string[8U];\r\n\r\n      std::size_t my_format_string_index = 0U;\r\n\r\n      my_format_string[my_format_string_index] = '%';\r\n      ++my_format_string_index;\r\n\r\n      if(my_flags & std::ios_base::showpos)   { my_format_string[my_format_string_index] = '+'; ++my_format_string_index; }\r\n      if(my_flags & std::ios_base::showpoint) { my_format_string[my_format_string_index] = '#'; ++my_format_string_index; }\r\n\r\n      my_format_string[my_format_string_index + 0U] = '.';\r\n      my_format_string[my_format_string_index + 1U] = '*';\r\n      my_format_string[my_format_string_index + 2U] = 'Q';\r\n\r\n      my_format_string_index += 3U;\r\n\r\n      char the_notation_char;\r\n\r\n      if     (my_flags & std::ios_base::scientific) { the_notation_char = 'e'; }\r\n      else if(my_flags & std::ios_base::fixed)      { the_notation_char = 'f'; }\r\n      else                                          { the_notation_char = 'g'; }\r\n\r\n      my_format_string[my_format_string_index + 0U] = the_notation_char;\r\n      my_format_string[my_format_string_index + 1U] = 0;\r\n\r\n      const int v = ::quadmath_snprintf(my_buffer,\r\n                                        static_cast<int>(sizeof(my_buffer)),\r\n                                        my_format_string,\r\n                                        my_digits,\r\n                                        x);\r\n\r\n      if(v < 0) { BOOST_THROW_EXCEPTION(std::runtime_error(\"Formatting of boost::float128_t failed internally in quadmath_snprintf().\")); }\r\n\r\n      if(v >= static_cast<int>(sizeof(my_buffer) - 1U))\r\n      {\r\n        // Evidently there is a really long floating-point string here,\r\n        // such as a small decimal representation in non-scientific notation.\r\n        // So we have to use dynamic memory allocation for the output\r\n        // string buffer.\r\n\r\n        char* my_buffer2 = static_cast<char*>(0U);\r\n\r\n#ifndef BOOST_NO_EXCEPTIONS\r\n        try\r\n        {\r\n#endif\r\n          my_buffer2 = new char[v + 3];\r\n#ifndef BOOST_NO_EXCEPTIONS\r\n        }\r\n        catch(const std::bad_alloc&)\r\n        {\r\n          BOOST_THROW_EXCEPTION(std::runtime_error(\"Formatting of boost::float128_t failed while allocating memory.\"));\r\n        }\r\n#endif\r\n        const int v2 = ::quadmath_snprintf(my_buffer2,\r\n                                            v + 3,\r\n                                            my_format_string,\r\n                                            my_digits,\r\n                                            x);\r\n\r\n        if(v2 >= v + 3)\r\n        {\r\n          BOOST_THROW_EXCEPTION(std::runtime_error(\"Formatting of boost::float128_t failed.\"));\r\n        }\r\n\r\n        static_cast<void>(ostr << my_buffer2);\r\n\r\n        delete [] my_buffer2;\r\n      }\r\n      else\r\n      {\r\n        static_cast<void>(ostr << my_buffer);\r\n      }\r\n\r\n      return (os << ostr.str());\r\n    }\r\n\r\n    template<typename char_type, class traits_type>\r\n    inline std::basic_istream<char_type, traits_type>& operator>>(std::basic_istream<char_type, traits_type>& is, boost::math::cstdfloat::detail::float_internal128_t& x)\r\n    {\r\n      std::string str;\r\n\r\n      static_cast<void>(is >> str);\r\n\r\n      char* p_end;\r\n\r\n      x = strtoflt128(str.c_str(), &p_end);\r\n\r\n      if(static_cast<std::ptrdiff_t>(p_end - str.c_str()) != static_cast<std::ptrdiff_t>(str.length()))\r\n      {\r\n        for(std::string::const_reverse_iterator it = str.rbegin(); it != str.rend(); ++it)\r\n        {\r\n          static_cast<void>(is.putback(*it));\r\n        }\r\n\r\n        is.setstate(ios_base::failbit);\r\n\r\n        BOOST_THROW_EXCEPTION(std::runtime_error(\"Unable to interpret input string as a boost::float128_t\"));\r\n      }\r\n\r\n      return is;\r\n    }\r\n  }\r\n\r\n//  #elif defined(__GNUC__)\r\n  #elif defined(BOOST_INTEL)\r\n\r\n  // The section for I/O stream support for the ICC compiler is particularly\r\n  // long, because these functions must be painstakingly synthesized from\r\n  // manually-written routines (ICC does not support I/O stream operations\r\n  // for its _Quad type).\r\n\r\n  // The following string-extraction routines are based on the methodology\r\n  // used in Boost.Multiprecision by John Maddock and Christopher Kormanyos.\r\n  // This methodology has been slightly modified here for boost::float128_t.\r\n\r\n  #include <cstring>\r\n  #include <cctype>\r\n  #include <boost/lexical_cast.hpp>\r\n\r\n  namespace boost { namespace math { namespace cstdfloat { namespace detail {\r\n\r\n  template<class string_type>\r\n  void format_float_string(string_type& str,\r\n                            int my_exp,\r\n                            int digits,\r\n                            const std::ios_base::fmtflags f,\r\n                            const bool iszero)\r\n  {\r\n    typedef typename string_type::size_type size_type;\r\n\r\n    const bool scientific = ((f & std::ios_base::scientific) == std::ios_base::scientific);\r\n    const bool fixed      = ((f & std::ios_base::fixed)      == std::ios_base::fixed);\r\n    const bool showpoint  = ((f & std::ios_base::showpoint)  == std::ios_base::showpoint);\r\n    const bool showpos    = ((f & std::ios_base::showpos)    == std::ios_base::showpos);\r\n\r\n    const bool b_neg = ((str.size() != 0U) && (str[0] == '-'));\r\n\r\n    if(b_neg)\r\n    {\r\n      str.erase(0, 1);\r\n    }\r\n\r\n    if(digits == 0)\r\n    {\r\n      digits = static_cast<int>((std::max)(str.size(), size_type(16)));\r\n    }\r\n\r\n    if(iszero || str.empty() || (str.find_first_not_of('0') == string_type::npos))\r\n    {\r\n      // We will be printing zero, even though the value might not\r\n      // actually be zero (it just may have been rounded to zero).\r\n      str = \"0\";\r\n\r\n      if(scientific || fixed)\r\n      {\r\n        str.append(1, '.');\r\n        str.append(size_type(digits), '0');\r\n\r\n        if(scientific)\r\n        {\r\n          str.append(\"e+00\");\r\n        }\r\n      }\r\n      else\r\n      {\r\n        if(showpoint)\r\n        {\r\n          str.append(1, '.');\r\n          if(digits > 1)\r\n          {\r\n            str.append(size_type(digits - 1), '0');\r\n          }\r\n        }\r\n      }\r\n\r\n      if(b_neg)\r\n      {\r\n        str.insert(0U, 1U, '-');\r\n      }\r\n      else if(showpos)\r\n      {\r\n        str.insert(0U, 1U, '+');\r\n      }\r\n\r\n      return;\r\n    }\r\n\r\n    if(!fixed && !scientific && !showpoint)\r\n    {\r\n      // Suppress trailing zeros.\r\n      typename string_type::iterator pos = str.end();\r\n\r\n      while(pos != str.begin() && *--pos == '0') { ; }\r\n\r\n      if(pos != str.end())\r\n      {\r\n        ++pos;\r\n      }\r\n\r\n      str.erase(pos, str.end());\r\n\r\n      if(str.empty())\r\n      {\r\n        str = '0';\r\n      }\r\n    }\r\n    else if(!fixed || (my_exp >= 0))\r\n    {\r\n      // Pad out the end with zero's if we need to.\r\n\r\n      int chars = static_cast<int>(str.size());\r\n      chars = digits - chars;\r\n\r\n      if(scientific)\r\n      {\r\n        ++chars;\r\n      }\r\n\r\n      if(chars > 0)\r\n      {\r\n        str.append(static_cast<size_type>(chars), '0');\r\n      }\r\n    }\r\n\r\n    if(fixed || (!scientific && (my_exp >= -4) && (my_exp < digits)))\r\n    {\r\n      if((1 + my_exp) > static_cast<int>(str.size()))\r\n      {\r\n        // Just pad out the end with zeros.\r\n        str.append(static_cast<size_type>((1 + my_exp) - static_cast<int>(str.size())), '0');\r\n\r\n        if(showpoint || fixed)\r\n        {\r\n          str.append(\".\");\r\n        }\r\n      }\r\n      else if(my_exp + 1 < static_cast<int>(str.size()))\r\n      {\r\n        if(my_exp < 0)\r\n        {\r\n          str.insert(0U, static_cast<size_type>(-1 - my_exp), '0');\r\n          str.insert(0U, \"0.\");\r\n        }\r\n        else\r\n        {\r\n          // Insert the decimal point:\r\n          str.insert(static_cast<size_type>(my_exp + 1), 1, '.');\r\n        }\r\n      }\r\n      else if(showpoint || fixed) // we have exactly the digits we require to left of the point\r\n      {\r\n        str += \".\";\r\n      }\r\n\r\n      if(fixed)\r\n      {\r\n        // We may need to add trailing zeros.\r\n        int l = static_cast<int>(str.find('.') + 1U);\r\n        l = digits - (static_cast<int>(str.size()) - l);\r\n\r\n        if(l > 0)\r\n        {\r\n          str.append(size_type(l), '0');\r\n        }\r\n      }\r\n    }\r\n    else\r\n    {\r\n      // Scientific format:\r\n      if(showpoint || (str.size() > 1))\r\n      {\r\n        str.insert(1U, 1U, '.');\r\n      }\r\n\r\n      str.append(1U, 'e');\r\n      string_type e = boost::lexical_cast<string_type>(std::abs(my_exp));\r\n\r\n      if(e.size() < 2U)\r\n      {\r\n        e.insert(0U, 2U - e.size(), '0');\r\n      }\r\n\r\n      if(my_exp < 0)\r\n      {\r\n        e.insert(0U, 1U, '-');\r\n      }\r\n      else\r\n      {\r\n        e.insert(0U, 1U, '+');\r\n      }\r\n\r\n      str.append(e);\r\n    }\r\n\r\n    if(b_neg)\r\n    {\r\n      str.insert(0U, 1U, '-');\r\n    }\r\n    else if(showpos)\r\n    {\r\n      str.insert(0U, 1U, '+');\r\n    }\r\n  }\r\n\r\n  template<class float_type, class type_a> inline void eval_convert_to(type_a* pa,    const float_type& cb)                        { *pa  = static_cast<type_a>(cb); }\r\n  template<class float_type, class type_a> inline void eval_add       (float_type& b, const type_a& a)                             { b   += a; }\r\n  template<class float_type, class type_a> inline void eval_subtract  (float_type& b, const type_a& a)                             { b   -= a; }\r\n  template<class float_type, class type_a> inline void eval_multiply  (float_type& b, const type_a& a)                             { b   *= a; }\r\n  template<class float_type>               inline void eval_multiply  (float_type& b, const float_type& cb, const float_type& cb2) { b    = (cb * cb2); }\r\n  template<class float_type, class type_a> inline void eval_divide    (float_type& b, const type_a& a)                             { b   /= a; }\r\n  template<class float_type>               inline void eval_log10     (float_type& b, const float_type& cb)                        { b    = std::log10(cb); }\r\n  template<class float_type>               inline void eval_floor     (float_type& b, const float_type& cb)                        { b    = std::floor(cb); }\r\n\r\n  inline void round_string_up_at(std::string& s, int pos, int& expon)\r\n  {\r\n    // This subroutine rounds up a string representation of a\r\n    // number at the given position pos.\r\n\r\n    if(pos < 0)\r\n    {\r\n      s.insert(0U, 1U, '1');\r\n      s.erase(s.size() - 1U);\r\n      ++expon;\r\n    }\r\n    else if(s[pos] == '9')\r\n    {\r\n      s[pos] = '0';\r\n      round_string_up_at(s, pos - 1, expon);\r\n    }\r\n    else\r\n    {\r\n      if((pos == 0) && (s[pos] == '0') && (s.size() == 1))\r\n      {\r\n        ++expon;\r\n      }\r\n\r\n      ++s[pos];\r\n    }\r\n  }\r\n\r\n  template<class float_type>\r\n  std::string convert_to_string(float_type& x,\r\n                                std::streamsize digits,\r\n                                const std::ios_base::fmtflags f)\r\n  {\r\n    const bool isneg  = (x < 0);\r\n    const bool iszero = ((!isneg) ? bool(+x < (std::numeric_limits<float_type>::min)())\r\n                                  : bool(-x < (std::numeric_limits<float_type>::min)()));\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    int expon = 0;\r\n\r\n    if(digits <= 0) { digits = std::numeric_limits<float_type>::max_digits10; }\r\n\r\n    const int org_digits = static_cast<int>(digits);\r\n\r\n    std::string result;\r\n\r\n    if(iszero)\r\n    {\r\n      result = \"0\";\r\n    }\r\n    else if(isinf)\r\n    {\r\n      if(x < 0)\r\n      {\r\n        return \"-inf\";\r\n      }\r\n      else\r\n      {\r\n        return ((f & std::ios_base::showpos) == std::ios_base::showpos) ? \"+inf\" : \"inf\";\r\n      }\r\n    }\r\n    else if(isnan)\r\n    {\r\n      return \"nan\";\r\n    }\r\n    else\r\n    {\r\n      // Start by figuring out the base-10 exponent.\r\n      if(isneg) { x = -x; }\r\n\r\n      float_type t;\r\n      float_type ten = 10;\r\n\r\n      eval_log10(t, x);\r\n      eval_floor(t, t);\r\n      eval_convert_to(&expon, t);\r\n\r\n      if(-expon > std::numeric_limits<float_type>::max_exponent10 - 3)\r\n      {\r\n        int e = -expon / 2;\r\n\r\n        const float_type t2 = boost::math::cstdfloat::detail::pown(ten, e);\r\n\r\n        eval_multiply(t, t2, x);\r\n        eval_multiply(t, t2);\r\n\r\n        if((expon & 1) != 0)\r\n        {\r\n          eval_multiply(t, ten);\r\n        }\r\n      }\r\n      else\r\n      {\r\n        t = boost::math::cstdfloat::detail::pown(ten, -expon);\r\n        eval_multiply(t, x);\r\n      }\r\n\r\n      // Make sure that the value lies between [1, 10), and adjust if not.\r\n      if(t < 1)\r\n      {\r\n        eval_multiply(t, 10);\r\n\r\n        --expon;\r\n      }\r\n      else if(t >= 10)\r\n      {\r\n        eval_divide(t, 10);\r\n\r\n        ++expon;\r\n      }\r\n\r\n      float_type digit;\r\n      int        cdigit;\r\n\r\n      // Adjust the number of digits required based on formatting options.\r\n      if(((f & std::ios_base::fixed) == std::ios_base::fixed) && (expon != -1))\r\n      {\r\n        digits += (expon + 1);\r\n      }\r\n\r\n      if((f & std::ios_base::scientific) == std::ios_base::scientific)\r\n      {\r\n        ++digits;\r\n      }\r\n\r\n      // Extract the base-10 digits one at a time.\r\n      for(int i = 0; i < digits; ++i)\r\n      {\r\n        eval_floor(digit, t);\r\n        eval_convert_to(&cdigit, digit);\r\n\r\n        result += static_cast<char>('0' + cdigit);\r\n\r\n        eval_subtract(t, digit);\r\n        eval_multiply(t, ten);\r\n      }\r\n\r\n      // Possibly round the result.\r\n      if(digits >= 0)\r\n      {\r\n        eval_floor(digit, t);\r\n        eval_convert_to(&cdigit, digit);\r\n        eval_subtract(t, digit);\r\n\r\n        if((cdigit == 5) && (t == 0))\r\n        {\r\n          // Use simple bankers rounding.\r\n\r\n          if((static_cast<int>(*result.rbegin() - '0') & 1) != 0)\r\n          {\r\n            round_string_up_at(result, static_cast<int>(result.size() - 1U), expon);\r\n          }\r\n        }\r\n        else if(cdigit >= 5)\r\n        {\r\n          round_string_up_at(result, static_cast<int>(result.size() - 1), expon);\r\n        }\r\n      }\r\n    }\r\n\r\n    while((result.size() > static_cast<std::string::size_type>(digits)) && result.size())\r\n    {\r\n      // We may get here as a result of rounding.\r\n\r\n      if(result.size() > 1U)\r\n      {\r\n        result.erase(result.size() - 1U);\r\n      }\r\n      else\r\n      {\r\n        if(expon > 0)\r\n        {\r\n          --expon; // so we put less padding in the result.\r\n        }\r\n        else\r\n        {\r\n          ++expon;\r\n        }\r\n\r\n        ++digits;\r\n      }\r\n    }\r\n\r\n    if(isneg)\r\n    {\r\n      result.insert(0U, 1U, '-');\r\n    }\r\n\r\n    format_float_string(result, expon, org_digits, f, iszero);\r\n\r\n    return result;\r\n  }\r\n\r\n  template <class float_type>\r\n  bool convert_from_string(float_type& value, const char* p)\r\n  {\r\n    value = 0;\r\n\r\n    if((p == static_cast<const char*>(0U)) || (*p == static_cast<char>(0)))\r\n    {\r\n      return;\r\n    }\r\n\r\n    bool is_neg       = false;\r\n    bool is_neg_expon = false;\r\n\r\n    BOOST_CONSTEXPR_OR_CONST int ten = 10;\r\n\r\n    int expon       = 0;\r\n    int digits_seen = 0;\r\n\r\n    BOOST_CONSTEXPR_OR_CONST int max_digits = std::numeric_limits<float_type>::max_digits10 + 1;\r\n\r\n    if(*p == static_cast<char>('+'))\r\n    {\r\n      ++p;\r\n    }\r\n    else if(*p == static_cast<char>('-'))\r\n    {\r\n      is_neg = true;\r\n      ++p;\r\n    }\r\n\r\n    const bool isnan = ((std::strcmp(p, \"nan\") == 0) || (std::strcmp(p, \"NaN\") == 0) || (std::strcmp(p, \"NAN\") == 0));\r\n\r\n    if(isnan)\r\n    {\r\n      eval_divide(value, 0);\r\n\r\n      if(is_neg)\r\n      {\r\n        value = -value;\r\n      }\r\n\r\n      return true;\r\n    }\r\n\r\n    const bool isinf = ((std::strcmp(p, \"inf\") == 0) || (std::strcmp(p, \"Inf\") == 0) || (std::strcmp(p, \"INF\") == 0));\r\n\r\n    if(isinf)\r\n    {\r\n      value = 1;\r\n      eval_divide(value, 0);\r\n\r\n      if(is_neg)\r\n      {\r\n        value = -value;\r\n      }\r\n\r\n      return true;\r\n    }\r\n\r\n    // Grab all the leading digits before the decimal point.\r\n    while(std::isdigit(*p))\r\n    {\r\n      eval_multiply(value, ten);\r\n      eval_add(value, static_cast<int>(*p - '0'));\r\n      ++p;\r\n      ++digits_seen;\r\n    }\r\n\r\n    if(*p == static_cast<char>('.'))\r\n    {\r\n      // Grab everything after the point, stop when we've seen\r\n      // enough digits, even if there are actually more available.\r\n\r\n      ++p;\r\n\r\n      while(std::isdigit(*p))\r\n      {\r\n        eval_multiply(value, ten);\r\n        eval_add(value, static_cast<int>(*p - '0'));\r\n        ++p;\r\n        --expon;\r\n\r\n        if(++digits_seen > max_digits)\r\n        {\r\n          break;\r\n        }\r\n      }\r\n\r\n      while(std::isdigit(*p))\r\n      {\r\n        ++p;\r\n      }\r\n    }\r\n\r\n    // Parse the exponent.\r\n    if((*p == static_cast<char>('e')) || (*p == static_cast<char>('E')))\r\n    {\r\n      ++p;\r\n\r\n      if(*p == static_cast<char>('+'))\r\n      {\r\n        ++p;\r\n      }\r\n      else if(*p == static_cast<char>('-'))\r\n      {\r\n        is_neg_expon = true;\r\n        ++p;\r\n      }\r\n\r\n      int e2 = 0;\r\n\r\n      while(std::isdigit(*p))\r\n      {\r\n        e2 *= 10;\r\n        e2 += (*p - '0');\r\n        ++p;\r\n      }\r\n\r\n      if(is_neg_expon)\r\n      {\r\n        e2 = -e2;\r\n      }\r\n\r\n      expon += e2;\r\n    }\r\n\r\n    if(expon)\r\n    {\r\n      // Scale by 10^expon. Note that 10^expon can be outside the range\r\n      // of our number type, even though the result is within range.\r\n      // If that looks likely, then split the calculation in two parts.\r\n      float_type t;\r\n      t = ten;\r\n\r\n      if(expon > (std::numeric_limits<float_type>::min_exponent10 + 2))\r\n      {\r\n        t = boost::math::cstdfloat::detail::pown(t, expon);\r\n        eval_multiply(value, t);\r\n      }\r\n      else\r\n      {\r\n        t = boost::math::cstdfloat::detail::pown(t, (expon + digits_seen + 1));\r\n        eval_multiply(value, t);\r\n        t = ten;\r\n        t = boost::math::cstdfloat::detail::pown(t, (-digits_seen - 1));\r\n        eval_multiply(value, t);\r\n      }\r\n    }\r\n\r\n    if(is_neg)\r\n    {\r\n      value = -value;\r\n    }\r\n\r\n    return (*p == static_cast<char>(0));\r\n  }\r\n  } } } } // boost::math::cstdfloat::detail\r\n\r\n  namespace std\r\n  {\r\n    template<typename char_type, class traits_type>\r\n    inline std::basic_ostream<char_type, traits_type>& operator<<(std::basic_ostream<char_type, traits_type>& os, const boost::math::cstdfloat::detail::float_internal128_t& x)\r\n    {\r\n      boost::math::cstdfloat::detail::float_internal128_t non_const_x = x;\r\n\r\n      const std::string str = boost::math::cstdfloat::detail::convert_to_string(non_const_x,\r\n                                                                                os.precision(),\r\n                                                                                os.flags());\r\n\r\n      std::basic_ostringstream<char_type, traits_type> ostr;\r\n      ostr.flags(os.flags());\r\n      ostr.imbue(os.getloc());\r\n      ostr.precision(os.precision());\r\n\r\n      static_cast<void>(ostr << str);\r\n\r\n      return (os << ostr.str());\r\n    }\r\n\r\n    template<typename char_type, class traits_type>\r\n    inline std::basic_istream<char_type, traits_type>& operator>>(std::basic_istream<char_type, traits_type>& is, boost::math::cstdfloat::detail::float_internal128_t& x)\r\n    {\r\n      std::string str;\r\n\r\n      static_cast<void>(is >> str);\r\n\r\n      const bool conversion_is_ok = boost::math::cstdfloat::detail::convert_from_string(x, str.c_str());\r\n\r\n      if(false == conversion_is_ok)\r\n      {\r\n        for(std::string::const_reverse_iterator it = str.rbegin(); it != str.rend(); ++it)\r\n        {\r\n          static_cast<void>(is.putback(*it));\r\n        }\r\n\r\n        is.setstate(ios_base::failbit);\r\n\r\n        BOOST_THROW_EXCEPTION(std::runtime_error(\"Unable to interpret input string as a boost::float128_t\"));\r\n      }\r\n\r\n      return is;\r\n    }\r\n  }\r\n\r\n  #endif // Use __GNUC__ or BOOST_INTEL libquadmath\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_IOSTREAM_2014_02_15_HPP_\r\n", "meta": {"hexsha": "ff384a9b330e7de08a577ff0b622582f92fb0b8e", "size": 21960, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/cstdfloat/cstdfloat_iostream.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_iostream.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_iostream.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": 28.335483871, "max_line_length": 176, "alphanum_fraction": 0.5220400729, "num_tokens": 5517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.04023794190428388, "lm_q1q2_score": 0.01304656514750787}}
{"text": "/**\n * @file cl_cbs.cpp\n * @author Licheng Wen (wenlc@zju.edu.cn)\n * @brief The implement of CL-CBS\n * @date 2020-11-12\n *\n * @copyright Copyright (c) 2020\n *\n */\n#include \"cl_cbs.hpp\"\n\n#include <sys/stat.h>\n#include <unistd.h>\n#include <yaml-cpp/yaml.h>\n\n#include <boost/functional/hash.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/program_options.hpp>\n#include <fstream>\n#include <iostream>\n\n#include \"environment.hpp\"\n#include \"timer.hpp\"\n\nusing libMultiRobotPlanning::CL_CBS;\nusing libMultiRobotPlanning::Neighbor;\nusing libMultiRobotPlanning::PlanResult;\nusing namespace libMultiRobotPlanning;\n\n// calculate agent collision more precisely BUT need LONGER time\n// #define PRCISE_COLLISION\n\nstruct Location {\n  Location(double x, double y) : x(x), y(y) {}\n  double x;\n  double y;\n\n  bool operator<(const Location& other) const {\n    return std::tie(x, y) < std::tie(other.x, other.y);\n  }\n\n  bool operator==(const Location& other) const {\n    return std::tie(x, y) == std::tie(other.x, other.y);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Location& c) {\n    return os << \"(\" << c.x << \",\" << c.y << \")\";\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    return seed;\n  }\n};\n}  // namespace std\n\nstruct State {\n  State(double x, double y, double yaw, int time = 0)\n      : time(time), x(x), y(y), yaw(yaw) {\n    rot.resize(2, 2);\n    rot(0, 0) = cos(-this->yaw);\n    rot(0, 1) = -sin(-this->yaw);\n    rot(1, 0) = sin(-this->yaw);\n    rot(1, 1) = cos(-this->yaw);\n#ifdef PRCISE_COLLISION\n    corner1 = Point(\n        this->x -\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LB * 1.1, 2)) *\n                cos(atan2(Constants::carWidth / 2, Constants::LB) - this->yaw),\n        this->y -\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LB * 1.1, 2)) *\n                sin(atan2(Constants::carWidth / 2, Constants::LB) - this->yaw));\n    corner2 = Point(\n        this->x -\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LB * 1.1, 2)) *\n                cos(atan2(Constants::carWidth / 2, Constants::LB) + this->yaw),\n        this->y +\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LB * 1.1, 2)) *\n                sin(atan2(Constants::carWidth / 2, Constants::LB) + this->yaw));\n    corner3 = Point(\n        this->x +\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LF * 1.1, 2)) *\n                cos(atan2(Constants::carWidth / 2, Constants::LF) - this->yaw),\n        this->y +\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LF * 1.1, 2)) *\n                sin(atan2(Constants::carWidth / 2, Constants::LF) - this->yaw));\n    corner4 = Point(\n        this->x +\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LF * 1.1, 2)) *\n                cos(atan2(Constants::carWidth / 2, Constants::LF) + this->yaw),\n        this->y -\n            sqrt(pow(Constants::carWidth / 2 * 1.1, 2) +\n                 pow(Constants::LF * 1.1, 2)) *\n                sin(atan2(Constants::carWidth / 2, Constants::LF) + this->yaw));\n#endif\n  }\n\n  State() = default;\n\n  bool operator==(const State& s) const {\n    return std::tie(time, x, y, yaw) == std::tie(s.time, s.x, s.y, s.yaw);\n  }\n\n  bool agentCollision(const State& other) const {\n#ifndef PRCISE_COLLISION\n    if (pow(this->x - other.x, 2) + pow(this->y - other.y, 2) <\n        pow(2 * Constants::LF, 2) + pow(Constants::carWidth, 2))\n      return true;\n    return false;\n#else\n    std::vector<Segment> rectangle1{Segment(this->corner1, this->corner2),\n                                    Segment(this->corner2, this->corner3),\n                                    Segment(this->corner3, this->corner4),\n                                    Segment(this->corner4, this->corner1)};\n    std::vector<Segment> rectangle2{Segment(other.corner1, other.corner2),\n                                    Segment(other.corner2, other.corner3),\n                                    Segment(other.corner3, other.corner4),\n                                    Segment(other.corner4, other.corner1)};\n    for (auto seg1 = rectangle1.begin(); seg1 != rectangle1.end(); seg1++)\n      for (auto seg2 = rectangle2.begin(); seg2 != rectangle2.end(); seg2++) {\n        if (boost::geometry::intersects(*seg1, *seg2)) return true;\n      }\n    return false;\n#endif\n  }\n\n  bool obsCollision(const Location& obstacle) const {\n    boost::numeric::ublas::matrix<double> obs(1, 2);\n    obs(0, 0) = obstacle.x - this->x;\n    obs(0, 1) = obstacle.y - this->y;\n\n    auto rotated_obs = boost::numeric::ublas::prod(obs, rot);\n    if (rotated_obs(0, 0) > -Constants::LB - Constants::obsRadius &&\n        rotated_obs(0, 0) < Constants::LF + Constants::obsRadius &&\n        rotated_obs(0, 1) > -Constants::carWidth / 2.0 - Constants::obsRadius &&\n        rotated_obs(0, 1) < Constants::carWidth / 2.0 + Constants::obsRadius)\n      return true;\n    return false;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const State& s) {\n    return os << \"(\" << s.x << \",\" << s.y << \":\" << s.yaw << \")@\" << s.time;\n  }\n\n  int time;\n  double x;\n  double y;\n  double yaw;\n\n private:\n  boost::numeric::ublas::matrix<double> rot;\n  Point corner1, corner2, corner3, corner4;\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.yaw);\n    return seed;\n  }\n};\n}  // namespace std\n\nusing Action = int;  // int<7 int ==6 wait\n\nstruct Conflict {\n  int time;\n  size_t agent1;\n  size_t agent2;\n\n  State s1;\n  State s2;\n\n  friend std::ostream& operator<<(std::ostream& os, const Conflict& c) {\n    os << c.time << \": Collision [ \" << c.agent1 << c.s1 << \" , \" << c.agent2\n       << c.s2 << \" ]\";\n    return os;\n  }\n};\n\nstruct Constraint {\n  Constraint(int time, State s, size_t agentid)\n      : time(time), s(s), agentid(agentid) {}\n  Constraint() = default;\n  int time;\n  State s;\n  size_t agentid;\n\n  bool operator<(const Constraint& other) const {\n    return std::tie(time, s.x, s.y, s.yaw, agentid) <\n           std::tie(other.time, other.s.x, other.s.y, other.s.yaw,\n                    other.agentid);\n  }\n\n  bool operator==(const Constraint& other) const {\n    return std::tie(time, s.x, s.y, s.yaw, agentid) ==\n           std::tie(other.time, other.s.x, other.s.y, other.s.yaw,\n                    other.agentid);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Constraint& c) {\n    return os << \"Constraint[\" << c.time << \",\" << c.s << \"from \" << c.agentid\n              << \"]\";\n  }\n\n  bool satisfyConstraint(const State& state) const {\n    if (state.time < this->time ||\n        state.time > this->time + Constants::constraintWaitTime)\n      return true;\n    return !this->s.agentCollision(state);\n  }\n};\n\nnamespace std {\ntemplate <>\nstruct hash<Constraint> {\n  size_t operator()(const Constraint& s) const {\n    size_t seed = 0;\n    boost::hash_combine(seed, s.time);\n    boost::hash_combine(seed, s.s.x);\n    boost::hash_combine(seed, s.s.y);\n    boost::hash_combine(seed, s.s.yaw);\n    boost::hash_combine(seed, s.agentid);\n    return seed;\n  }\n};\n}  // namespace std\n\n// FIXME: modidy data struct, it's not the best option\nstruct Constraints {\n  std::unordered_set<Constraint> constraints;\n\n  void add(const Constraints& other) {\n    constraints.insert(other.constraints.begin(), other.constraints.end());\n  }\n\n  bool overlap(const Constraints& other) {\n    for (const auto& c : constraints) {\n      if (other.constraints.count(c) > 0) return true;\n    }\n    return false;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const Constraints& cs) {\n    for (const auto& c : cs.constraints) {\n      os << c << std::endl;\n    }\n    return os;\n  }\n};\n\nvoid readAgentConfig() {\n  YAML::Node car_config;\n  std::string test(__FILE__);\n  boost::replace_all(test, \"cl_cbs.cpp\", \"config.yaml\");\n  try {\n    car_config = YAML::LoadFile(test.c_str());\n  } catch (std::exception& e) {\n    std::cerr << \"\\033[1m\\033[33mWARNING: Failed to load agent config file: \"\n              << test << \"\\033[0m , Using default params. \\n\";\n  }\n  // int car_r = car_config[\"r\"].as<int>();\n  Constants::r = car_config[\"r\"].as<double>();\n  Constants::deltat = car_config[\"deltat\"].as<double>();\n  Constants::penaltyTurning = car_config[\"penaltyTurning\"].as<double>();\n  Constants::penaltyReversing = car_config[\"penaltyTurning\"].as<double>();\n  Constants::penaltyCOD = car_config[\"penaltyTurning\"].as<double>();\n  // map resolution\n  Constants::mapResolution = car_config[\"mapResolution\"].as<double>();\n  // change to set calcIndex resolution\n  Constants::xyResolution = Constants::r * Constants::deltat;\n  Constants::yawResolution = Constants::deltat;\n\n  Constants::carWidth = car_config[\"carWidth\"].as<double>();\n  Constants::LF = car_config[\"LF\"].as<double>();\n  Constants::LB = car_config[\"LB\"].as<double>();\n  // obstacle default radius\n  Constants::obsRadius = car_config[\"obsRadius\"].as<double>();\n  // least time to wait for constraint\n  Constants::constraintWaitTime = car_config[\"constraintWaitTime\"].as<double>();\n\n  Constants::dx = {Constants::r * Constants::deltat,\n                   Constants::r * sin(Constants::deltat),\n                   Constants::r * sin(Constants::deltat),\n                   -Constants::r * Constants::deltat,\n                   -Constants::r * sin(Constants::deltat),\n                   -Constants::r * sin(Constants::deltat)};\n  Constants::dy = {0,\n                   -Constants::r * (1 - cos(Constants::deltat)),\n                   Constants::r * (1 - cos(Constants::deltat)),\n                   0,\n                   -Constants::r * (1 - cos(Constants::deltat)),\n                   Constants::r * (1 - cos(Constants::deltat))};\n  Constants::dyaw = {0, Constants::deltat,  -Constants::deltat,\n                     0, -Constants::deltat, Constants::deltat};\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  int batchSize;\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      \"batchsize,b\", po::value<int>(&batchSize)->default_value(10),\n      \"batch size for iter\");\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  readAgentConfig();\n\n  YAML::Node map_config;\n  try {\n    map_config = YAML::LoadFile(inputFile);\n  } catch (std::exception& e) {\n    std::cerr << \"\\033[1m\\033[31mERROR: Failed to load map file: \" << inputFile\n              << \"\\033[0m \\n\";\n    return 0;\n  }\n  const auto& dim = map_config[\"map\"][\"dimensions\"];\n  int dimx = dim[0].as<int>();\n  int dimy = dim[1].as<int>();\n\n  std::unordered_set<Location> obstacles;\n  std::multimap<int, State> dynamic_obstacles;\n  std::vector<State> goals;\n  std::vector<State> startStates;\n  for (const auto& node : map_config[\"map\"][\"obstacles\"]) {\n    obstacles.insert(Location(node[0].as<double>(), node[1].as<double>()));\n  }\n  for (const auto& node : map_config[\"agents\"]) {\n    const auto& start = node[\"start\"];\n    const auto& goal = node[\"goal\"];\n    startStates.emplace_back(State(start[0].as<double>(), start[1].as<double>(),\n                                   start[2].as<double>()));\n    // std::cout << \"s: \" << startStates.back() << std::endl;\n    goals.emplace_back(State(goal[0].as<double>(), goal[1].as<double>(),\n                             goal[2].as<double>()));\n  }\n\n  std::cout << \"Calculating Solution...\\n\";\n  double timer = 0;\n  bool success = false;\n  std::vector<PlanResult<State, Action, double>> solution;\n  for (size_t iter = 0; iter < (double)goals.size() / batchSize; iter++) {\n    size_t first = iter * batchSize;\n    size_t last = first + batchSize;\n    if (last >= goals.size()) last = goals.size();\n    std::vector<State> m_goals(goals.begin() + first, goals.begin() + last);\n    std::vector<State> m_starts(startStates.begin() + first,\n                                startStates.begin() + last);\n\n    Environment<Location, State, Action, double, Conflict, Constraint,\n                Constraints>\n        mapf(dimx, dimy, obstacles, dynamic_obstacles, m_goals);\n    if (!mapf.startAndGoalValid(m_starts, iter, batchSize)) {\n      success = false;\n      break;\n    }\n    for (auto goal = goals.begin() + last; goal != goals.end(); goal++) {\n      dynamic_obstacles.insert(\n          std::pair<int, State>(-1, State(goal->x, goal->y, goal->yaw)));\n    }\n    CL_CBS<State, Action, double, Conflict, Constraints,\n           Environment<Location, State, Action, double, Conflict, Constraint,\n                       Constraints>>\n        cbsHybrid(mapf);\n    std::vector<PlanResult<State, Action, double>> m_solution;\n    Timer iterTimer;\n    success = cbsHybrid.search(m_starts, m_solution);\n    iterTimer.stop();\n\n    if (!success) {\n      std::cout << \"\\033[1m\\033[31m No.\" << iter\n                << \"iter fail to find a solution \\033[0m\\n\";\n      break;\n    } else {\n      solution.insert(solution.end(), m_solution.begin(), m_solution.end());\n      for (size_t a = 0; a < m_solution.size(); ++a) {\n        for (const auto& state : m_solution[a].states)\n          dynamic_obstacles.insert(std::pair<int, State>(\n              state.first.time,\n              State(state.first.x, state.first.y, state.first.yaw)));\n        State lastState = m_solution[a].states.back().first;\n        dynamic_obstacles.insert(std::pair<int, State>(\n            -lastState.time, State(lastState.x, lastState.y, lastState.yaw)));\n      }\n      timer += iterTimer.elapsedSeconds();\n      std::cout << \"Complete \" << iter\n                << \" iter. Runtime:\" << iterTimer.elapsedSeconds()\n                << \" Expand high-level nodes:\" << mapf.highLevelExpanded()\n                << \" Average Low-level-search time:\"\n                << iterTimer.elapsedSeconds() / mapf.highLevelExpanded() /\n                       m_goals.size()\n                << std::endl;\n    }\n    dynamic_obstacles.erase(-1);\n  }\n\n  std::ofstream out;\n  out = std::ofstream(outputFile);\n\n  if (success) {\n    std::cout << \"\\033[1m\\033[32m Successfully find solution! \\033[0m\\n\";\n\n    double makespan = 0, flowtime = 0, cost = 0;\n    for (const auto& s : solution) cost += s.cost;\n\n    for (size_t a = 0; a < solution.size(); ++a) {\n      // calculate makespan\n      double current_makespan = 0;\n      for (size_t i = 0; i < solution[a].actions.size(); ++i) {\n        // some action cost have penalty coefficient\n\n        if (solution[a].actions[i].second < Constants::dx[0])\n          current_makespan += solution[a].actions[i].second;\n        else if (solution[a].actions[i].first % 3 == 0)\n          current_makespan += Constants::dx[0];\n        else\n          current_makespan += Constants::r * Constants::deltat;\n      }\n      flowtime += current_makespan;\n      if (current_makespan > makespan) makespan = current_makespan;\n    }\n    std::cout << \" Runtime: \" << timer << std::endl\n              << \" Makespan:\" << makespan << std::endl\n              << \" Flowtime:\" << flowtime << std::endl\n              << \" cost:\" << cost << std::endl;\n    // output to file\n    out << \"statistics:\" << std::endl;\n    out << \"  cost: \" << cost << std::endl;\n    out << \"  makespan: \" << makespan << std::endl;\n    out << \"  flowtime: \" << flowtime << std::endl;\n    out << \"  runtime: \" << timer << 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 << \"->\"\n      //             << solution[a].actions[i].first\n      //             << \"(cost: \" << solution[a].actions[i].second << \")\"\n      //             << 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            << \"      yaw: \" << state.first.yaw << std::endl\n            << \"      t: \" << state.first.time << std::endl;\n      }\n    }\n  } else {\n    std::cout << \"\\033[1m\\033[31m Fail to find paths \\033[0m\\n\";\n  }\n}\n", "meta": {"hexsha": "7964ab4d54758a988122dcd5d8ee4000e01b93ab", "size": 17333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cl_cbs.cpp", "max_stars_repo_name": "LIJUNCHENG001/CL-CBS", "max_stars_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-25T05:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T05:30:36.000Z", "max_issues_repo_path": "src/cl_cbs.cpp", "max_issues_repo_name": "mieximiemie/CL-CBS", "max_issues_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cl_cbs.cpp", "max_forks_repo_name": "mieximiemie/CL-CBS", "max_forks_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T08:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T08:39:29.000Z", "avg_line_length": 34.9455645161, "max_line_length": 80, "alphanum_fraction": 0.5687417066, "num_tokens": 4720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.027585280727863537, "lm_q1q2_score": 0.01303910639799716}}
{"text": "// This file is part of RegSeg\n//\n// Copyright 2014-2017, Oscar Esteban <code@oscaresteban.es>\n//\n// Permission is hereby granted, free of charge, to any person\n// obtaining a copy of this software and associated documentation\n// files (the \"Software\"), to deal in the Software without\n// restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above 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#ifndef __WeightedCovarianceSampleFilter_hxx\n#define __WeightedCovarianceSampleFilter_hxx\n\n#include \"WeightedCovarianceSampleFilter.h\"\n#include <itkWeightedMeanSampleFilter.h>\n\n#include <boost/math/special_functions/digamma.hpp>\n\nnamespace bm = boost::math;\n\nnamespace itk\n{\ntemplate< typename TSample >\nWeightedCovarianceSampleFilter< TSample >\n::WeightedCovarianceSampleFilter():\n m_RemoveOutliers(true),\n Superclass()\n{\n  this->ProcessObject::SetNthInput(1, ITK_NULLPTR);\n\n  this->ProcessObject::SetNumberOfRequiredOutputs(4);\n  this->ProcessObject::SetNthOutput( 2, this->MakeOutput(2) );\n  this->ProcessObject::SetNthOutput( 3, this->MakeOutput(3) );\n}\n\ntemplate< typename TSample >\nWeightedCovarianceSampleFilter< TSample >\n::~WeightedCovarianceSampleFilter()\n{}\n\ntemplate< typename TSample >\nvoid\nWeightedCovarianceSampleFilter< TSample >\n::PrintSelf(std::ostream & os, itk::Indent indent) const\n{\n  Superclass::PrintSelf(os, indent);\n  // m_Weights\n  os << indent << \"Weights: \" << this->GetWeightsInput() << std::endl;\n}\n\ntemplate< typename TSample >\ninline void\nWeightedCovarianceSampleFilter< TSample >\n::GenerateData()\n{\n  // if weight array is specified use it to compute the covariance\n  const InputWeightArrayObjectType *weightArrayObject =\n    this->GetWeightsInput();\n\n  if ( weightArrayObject != ITK_NULLPTR )\n    {\n    this->ComputeCovarianceMatrixWithWeights();\n    return;\n    }\n\n  // Otherwise compute the regular covariance matrix ( without weight\n  // coefficients)\n  Superclass::GenerateData();\n}\n\n\ntemplate< typename TSample >\ntypename WeightedCovarianceSampleFilter< TSample >::DataObjectPointer\nWeightedCovarianceSampleFilter< TSample >\n::MakeOutput(DataObjectPointerArraySizeType index)\n{\n  MeasurementVectorSizeType measurementVectorSize = this->GetMeasurementVectorSize();\n\n  if ( index == 0 )\n    {\n    MatrixType covarianceMatrix(measurementVectorSize, measurementVectorSize);\n    covarianceMatrix.SetIdentity();\n    typename MatrixDecoratedType::Pointer decoratedCovarianceMatrix = MatrixDecoratedType::New();\n    decoratedCovarianceMatrix->Set(covarianceMatrix);\n    return decoratedCovarianceMatrix.GetPointer();\n    }\n\n  if ( index >= 1 )\n    {\n    MeasurementVectorRealType mean;\n    (void)mean; // for complainty pants : valgrind\n    NumericTraits<MeasurementVectorRealType>::SetLength(mean, this->GetMeasurementVectorSize());\n    // NumericTraits::SetLength also initializes array to zero\n    typename MeasurementVectorDecoratedType::Pointer decoratedMean = MeasurementVectorDecoratedType::New();\n    decoratedMean->Set( mean );\n    return decoratedMean.GetPointer();\n    }\n  itkExceptionMacro(\"Trying to create output of index \" << index << \" larger than the number of output\");\n}\n\ntemplate< typename TSample >\ninline void\nWeightedCovarianceSampleFilter< TSample >\n::ComputeCovarianceMatrixWithWeights()\n{\n  // set up input / output\n  const SampleType *input = this->GetInput();\n\n  MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize();\n\n  MatrixDecoratedType *decoratedOutput =\n    itkDynamicCastInDebugMode< MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) );\n\n  MatrixType output = decoratedOutput->Get();\n  output.SetSize( measurementVectorSize, measurementVectorSize );\n  output.Fill( NumericTraits< typename MatrixType::ValueType >::Zero );\n\n  MeasurementVectorDecoratedType *decoratedMeanOutput =\n    itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(1) );\n\n  WeightArrayType weightsArray(this->GetWeights());\n  std::vector<std::vector<MeasurementType>> sampleComponents(measurementVectorSize);\n\n  typename SampleType::ConstIterator iter =      input->Begin();\n  const typename SampleType::ConstIterator end = input->End();\n\n  MeasurementVectorType mean;\n  MeasurementVectorType pbottom, ptop;\n  itk::NumericTraits<MeasurementVectorType>::SetLength( pbottom, measurementVectorSize );\n  itk::NumericTraits<MeasurementVectorType>::SetLength( ptop, measurementVectorSize );\n  pbottom.Fill(itk::NumericTraits<MeasurementType>::min());\n  ptop.Fill(itk::NumericTraits<MeasurementType>::max());\n\n  if( this->m_RemoveOutliers ) {\n\t  MeasurementVectorType median;\n\t  // calculate percentiles\n\t  for ( unsigned int sampleVectorIndex = 0; iter != end; ++iter, ++sampleVectorIndex ) {\n\t    const MeasurementVectorType & measurement = iter.GetMeasurementVector();\n\t    const WeightValueType rawWeight = weightsArray[sampleVectorIndex];\n\n\t    if( rawWeight >= 0.9 ) {\n\t    \tfor(size_t c = 0; c < measurementVectorSize; c++)\n\t    \t\tsampleComponents[c].push_back(measurement[c]);\n\t    }\n\t  }\n\n\t  itk::NumericTraits<MeasurementVectorType>::SetLength( median, measurementVectorSize );\n\n\t  size_t sampleSize = sampleComponents[0].size();\n\t  if (sampleSize > 0) {\n\t\t  for(size_t c = 0; c < measurementVectorSize; c++) {\n\t\t\t  std::sort(sampleComponents[c].begin(), sampleComponents[c].end());\n\t\t\t  pbottom[c] = sampleComponents[c][int(0.02 * sampleSize)];\n\t\t\t  ptop[c] = sampleComponents[c][int(0.98 * sampleSize)];\n\t\t\t  median[c] = sampleComponents[c][int(0.50 * sampleSize)];\n\t\t  }\n\t\t  // mean = median;\n\t  }\n  }\n\n  MeasurementVectorDecoratedType *decoratedRangeMaxOutput =\n\t    itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(2) );\n  decoratedRangeMaxOutput->Set( ptop );\n\n  MeasurementVectorDecoratedType *decoratedRangeMinOutput =\n\t    itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(3) );\n  decoratedRangeMinOutput->Set( pbottom );\n\n  // reset sample iterator\n  iter = input->Begin();\n  // fills the lower triangle and the diagonal cells in the covariance matrix\n  for ( unsigned int sampleVectorIndex = 0;\n        iter != end;\n        ++iter, ++sampleVectorIndex ) {\n\t  const MeasurementVectorType & measurement = iter.GetMeasurementVector();\n\t  WeightValueType rawWeight = weightsArray[sampleVectorIndex];\n\n\t  if (rawWeight > 0.0) {\n\t\t    for(size_t c = 0; c < measurementVectorSize; c++) {\n\t\t    \tif (measurement[c] > ptop[c] || measurement[c] < pbottom[c] ) {\n\t\t    \t\tweightsArray[sampleVectorIndex] = 0.0;\n\t\t    \t\tcontinue;\n\t\t    \t}\n\t\t    }\n\t  }\n  }\n\n  // calculate mean\n  typedef itk::Statistics::WeightedMeanSampleFilter< SampleType > WeightedMeanFilterType;\n  typename WeightedMeanFilterType::Pointer meanFilter = WeightedMeanFilterType::New();\n\n  meanFilter->SetInput( input );\n  meanFilter->SetWeights( weightsArray );\n  meanFilter->Update();\n\n  mean = meanFilter->GetMean();\n  decoratedMeanOutput->Set( mean );\n\n  // covariance algorithm\n  MeasurementVectorRealType diff;\n  itk::NumericTraits<MeasurementVectorRealType>::SetLength( diff, measurementVectorSize );\n\n  WeightValueType totalWeight = itk::NumericTraits< WeightValueType >::Zero;\n  WeightValueType totalSquaredWeight = itk::NumericTraits< WeightValueType >::Zero;\n\n  // reset sample iterator\n  iter = input->Begin();\n\n  // fills the lower triangle and the diagonal cells in the covariance matrix\n  for ( unsigned int sampleVectorIndex = 0;\n        iter != end;\n        ++iter, ++sampleVectorIndex )\n    {\n    const MeasurementVectorType & measurement = iter.GetMeasurementVector();\n    const typename SampleType::AbsoluteFrequencyType frequency = iter.GetFrequency();\n    const WeightValueType rawWeight = weightsArray[sampleVectorIndex];\n\n    if ( rawWeight < 1.0e-8 )\n    \tcontinue;\n\n    WeightValueType weight = ( rawWeight * static_cast< WeightValueType >( frequency ) );\n\n    totalWeight += weight;\n    totalSquaredWeight += ( weight * weight );\n\n    for ( unsigned int dim = 0; dim < measurementVectorSize; ++dim )\n      {\n      const MeasurementRealType component =\n        static_cast< MeasurementRealType >( measurement[dim] );\n\n      diff[dim] = ( component - mean[dim] );\n      }\n\n    // updates the covariance matrix\n    for ( unsigned int row = 0; row < measurementVectorSize; ++row )\n      {\n      for ( unsigned int col = 0; col < row + 1; ++col )\n        {\n        output(row, col) +=\n          ( static_cast< MeasurementRealType >( weight ) * diff[row] * diff[col] );\n        }\n      }\n    }\n\n  // fills the upper triangle using the lower triangle\n  for ( unsigned int row = 1; row < measurementVectorSize; ++row )\n    {\n    for ( unsigned int col = 0; col < row; ++col ) {\n    \toutput(col, row) = output(row, col);\n      }\n    }\n\n  const double normalizationFactor = ( totalWeight - ( totalSquaredWeight / totalWeight ) );\n\n  if( normalizationFactor > vnl_math::eps )\n    {\n    const double inverseNormalizationFactor = 1.0 / normalizationFactor;\n\n    output *= inverseNormalizationFactor;\n    }\n  else\n    {\n    itkExceptionMacro(\"Normalization factor was too close to zero. Value = \" << normalizationFactor );\n    }\n\n  // Bias estimation\n  // See http://en.wikipedia.org/wiki/Estimation_of_covariance_matrices#Bias_of_the_sample_covariance_matrix\n  float p = measurementVectorSize;\n  float n = totalWeight;\n  float beta = (1/p) * (p * log(n) + p - bm::digamma(n-p+1) + (n - p + 1) * bm::digamma(n - p + 2) + bm::digamma(n+1) - (n+1)* bm::digamma(n+2));\n\n  MatrixType ident;\n  ident.SetSize( measurementVectorSize, measurementVectorSize );\n  ident.SetIdentity();\n  output+= output * exp( -beta );\n\n  decoratedOutput->Set( output );\n}\n\ntemplate< typename TSample >\nconst typename WeightedCovarianceSampleFilter< TSample >::MeasurementVectorDecoratedType *\nWeightedCovarianceSampleFilter< TSample >\n::GetRangeMaxOutput() const\n{\n  return static_cast< const MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(2) );\n}\n\ntemplate< typename TSample >\nconst typename WeightedCovarianceSampleFilter< TSample >::MeasurementVectorRealType\nWeightedCovarianceSampleFilter< TSample >\n::GetRangeMax() const\n{\n  return this->GetRangeMaxOutput()->Get();\n}\n\ntemplate< typename TSample >\nconst typename WeightedCovarianceSampleFilter< TSample >::MeasurementVectorDecoratedType *\nWeightedCovarianceSampleFilter< TSample >\n::GetRangeMinOutput() const\n{\n  return static_cast< const MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(3) );\n}\n\ntemplate< typename TSample >\nconst typename WeightedCovarianceSampleFilter< TSample >::MeasurementVectorRealType\nWeightedCovarianceSampleFilter< TSample >\n::GetRangeMin() const\n{\n  return this->GetRangeMinOutput()->Get();\n}\n\n} // end of namespace itk\n\n#endif\n", "meta": {"hexsha": "88539edcefc0b3a17cba188f4d63e14eb410f655", "size": 11491, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Code/Modules/ITKReviewed/include/WeightedCovarianceSampleFilter.hxx", "max_stars_repo_name": "xiaochengcike/RegSeg", "max_stars_repo_head_hexsha": "e2cff93ef4f195bfd59c518e047cf8f37560b6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2016-05-16T08:47:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T14:57:16.000Z", "max_issues_repo_path": "Code/Modules/ITKReviewed/include/WeightedCovarianceSampleFilter.hxx", "max_issues_repo_name": "xiaochengcike/RegSeg", "max_issues_repo_head_hexsha": "e2cff93ef4f195bfd59c518e047cf8f37560b6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-01-24T02:52:55.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-18T02:13:15.000Z", "max_forks_repo_path": "Code/Modules/ITKReviewed/include/WeightedCovarianceSampleFilter.hxx", "max_forks_repo_name": "oesteban/RegSeg", "max_forks_repo_head_hexsha": "e2cff93ef4f195bfd59c518e047cf8f37560b6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-24T21:13:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T00:06:35.000Z", "avg_line_length": 34.8212121212, "max_line_length": 145, "alphanum_fraction": 0.7319641459, "num_tokens": 2765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195662561499, "lm_q2_score": 0.03410042595771566, "lm_q1q2_score": 0.012999749592750319}}
{"text": "// Copyright (c) 2014, Tobias Holl\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//   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 notice,\n//        this list of conditions and the following disclaimer in the documentation\n//        and/or other materials provided with the distribution.\n//   3.   Neither the name of the copyright holder nor the names of its contributors\n//        may be used to endorse or promote products derived from this software\n//        without specific prior written permission.\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 DISCLAIMED.\n// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n// 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// modification: defines and mesh() code moved to separate file to avoid multiple inclusion\n// saving PLY files, both in ASCII and binary formats, added to this file\n\n\n#ifndef MARCHING_CUBES_HPP\n#define MARCHING_CUBES_HPP\n\n#include <memory>\n#include <boost/progress.hpp>\n\n#include \"types.hpp\"\n\nnamespace marching_cubes {\n\n/**\n * @brief Vertex struct to manage handling points with normals\n */\nstruct vertex {\n    Eigen::Vector3f point;\n    Eigen::Vector3f normal;\n\n    //int reference = -1; // If this vertex should be replaced by another one, store its ID here.\n\tint reference;\n\n    // Color\n    unsigned char r;\n    unsigned char g;\n    unsigned char b;\n\n    // Location in the voxel cube\n    int x;\n    int y;\n    int z;\n\n\tvertex(Eigen::Vector3f p, Eigen::Vector3f n, unsigned char rv, unsigned char gv, unsigned char bv, int xv, int yv, int zv) : point(p), normal(n), reference(-1), r(rv), g(gv), b(bv), x(xv), y(yv), z(zv) {}\n    vertex(vertex const& o) : point(o.point), normal(o.normal), reference(o.reference), r(o.r), g(o.g), b(o.b), x(o.x), y(o.y), z(o.z) {}\n    vertex(int ref) : reference(ref) {}\n\n    // Equality and inequality operators for searching\n    bool operator==(vertex other) {\n        return ((reference == other.reference && reference != -1) ||\n                (point == other.point && normal == other.normal));\n    }\n    bool operator!=(vertex other) {\n        return ((reference != other.reference) ||\n                (point != other.point) ||\n                (normal != other.normal));\n    }\n};\n\n/**\n * @brief Holds a triangle\n */\nstruct triangle {\n    std::vector<vertex> points;\n\n    triangle() {}\n    triangle(std::vector<vertex> const& p) : points(p) {}\n    triangle(triangle const& o) : points(o.points) {}\n};\n\nEigen::Vector3f interpolate(Eigen::Vector3f p1, Eigen::Vector3f p2, float valp1, float valp2);\nEigen::Vector3f norm_at(sdf &s, int x, int y, int z);\nstd::vector<triangle> getCubeCase(sdf &s, int x, int y, int z);\n\n} // namespace reconstruct::marching_cubes\n\n/**\n * @brief mesh Mesh and scale a sdf object\n * @param s Finished SDF data\n */\nstd::vector<marching_cubes::triangle> mesh(sdf &s);\nstd::vector<marching_cubes::triangle> mesh(plain_sdf &s);\nstd::vector<marching_cubes::triangle> mesh_valid_only(sdf &s);\n\nstd::vector<marching_cubes::triangle> mesh_world(sdf &s, Eigen::Vector3f lower_left);\n\n\n\nvoid save_mesh_ply(std::vector<marching_cubes::triangle> &tris, std::string const& filename, bool allow_duplicates=false );\nvoid save_mesh_binary_ply( std::vector<marching_cubes::triangle> tris, std::string const& filename, bool allow_duplicates=false );\nvoid save_mesh_binary_ply(std::vector<marching_cubes::triangle> tris, std::vector<marching_cubes::vertex> points, int element_vertex_count, std::string const& filename);\n\nvoid save_point_cloud_ply( std::vector<Eigen::Vector3f> pts, std::vector<Eigen::Vector3f> rgbs, std::string const& filename );\nvoid save_point_cloud_binary_ply( std::vector<Eigen::Vector3f> pts, std::vector<Eigen::Vector3f> rgbs, std::string const& filename );\n\nvoid postprocess_triangles(std::vector<marching_cubes::triangle> &tris, bool allow_duplicates, std::vector<marching_cubes::vertex> &points, Eigen::Vector3f &point_coord_mean, int &element_vertex_count);\n\n\n#endif // MARCHING_CUBES_HPP\n", "meta": {"hexsha": "590d22a60501e1d3cd02fc64423c31cfe776b16c", "size": 4862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdf_fusion/src/aruco_sdffusion/include/marching_cubes.hpp", "max_stars_repo_name": "YyYyYong0331/homebrewdb", "max_stars_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T16:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T05:47:29.000Z", "max_issues_repo_path": "sdf_fusion/src/aruco_sdffusion/include/marching_cubes.hpp", "max_issues_repo_name": "YyYyYong0331/homebrewdb", "max_issues_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-04-16T15:03:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T07:28:52.000Z", "max_forks_repo_path": "sdf_fusion/src/aruco_sdffusion/include/marching_cubes.hpp", "max_forks_repo_name": "YyYyYong0331/homebrewdb", "max_forks_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-27T09:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T10:42:33.000Z", "avg_line_length": 42.2782608696, "max_line_length": 205, "alphanum_fraction": 0.7163718634, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.03308597672022805, "lm_q1q2_score": 0.012980847229397014}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cstring>\n#include <cassert>\n#include <vector>\n#include <unordered_map>\n#include <chrono>\n#include \"hyperKMP.hpp\"\n\n#include <emmintrin.h>\n#include <pmmintrin.h>\n#include <smmintrin.h>\n\n#include <boost/iostreams/device/mapped_file.hpp>\n//---------------------------------------------------------------------------\n#define HYPER_MODE 0\n#define NORMAL_MODE 1\n#define TEST_MODE 2\n//---------------------------------------------------------------------------\nusing namespace std;\n//---------------------------------------------------------------------------\nhyperKMP::hyperKMP() {\n}\n//---------------------------------------------------------------------------\nhyperKMP::hyperKMP(char* pattern, unsigned mode) {\n  this->mode = mode;\n  this->length = strlen(pattern);\n  this->pattern = new char[this->length + 2];\n  strcpy(this->pattern, pattern); // the last char should be null\n  \n  // Transform pattern without underscores\n  for (unsigned index = 0; index < this->length; ++index)\n      if (this->pattern[index] == '_') \n        this->pattern[index] = ' ';\n  cerr << \"modified pattern: \" << this->pattern << endl;\n      \n  // For benchmarking\n  this->hyperSum = this->hyperMaximum = this->normalSum = this->normalMaximum = 0;\n  \n  this->valid = new bool[this->length + 1]();\n  this->psi = new unsigned[this->length + 1]();\n  this->omega = new unsigned[this->length + 1]();\n  this->degrees = new unsigned[this->length + 1]();\n  this->edges = new unsigned*[this->length + 1];\n  compressPi();\n  \n  // Only for benchmark reasons\n  this->pi = new unsigned[this->length + 1]();\n  normalPi();\n}\n//---------------------------------------------------------------------------\nvoid hyperKMP::normalPi() \n// compute the normal pi[] table\n{\n  unsigned k = 0;\n  for (unsigned q = 1; q < this->length; ++q) {\n    while ((k > 0) && (pattern[q] != pattern[k]))\n      k = pi[k - 1];\n    if (pattern[q] == pattern[k])\n      k++;\n    pi[q] = k;\n  }\n#if 1\n  cerr << \"Debug pi[]\" << endl;\n  for (unsigned index = 0; index < this->length; ++index) {\n    cerr << index << \" -> \" << pi[index] << endl;\n  }\n  cerr << endl;\n#endif\n}\n//---------------------------------------------------------------------------\nvoid hyperKMP::compressPi()\n// compress pi[] and create two new arrays: psi[] and omega[]\n// description in README\n{  \n  // Initialize the first values\n  // 0 is the first state. At this step it receives 2 sons\n  psi[0] = 0;\n  psi[1] = 0;\n  degrees[0] = 2;\n  // Compute pi and psi\n  unsigned k = 0;\n  for (unsigned q = 1; q < this->length; ++q) {\n    // Compute psi\n    while ((k > 0) && (pattern[q] != pattern[k])) {\n      k = psi[k];\n    }\n    if (pattern[q] == pattern[k]) {\n      k++;\n    }\n    // Compress possible path\n    // For understandability reasons, keep the formula like this\n    // TODO: it could be replaced by: (pattern[q + 1] == pattern[k]) ? psi[k] : k\n#if 1\n    psi[q + 1] = (!k) ? 0 : ((pattern[q + 1] == pattern[k]) ? psi[k] : k);\n#else\n    // If no jump, connect directly to 0\n    pi[q] = k;\n    if (pi[q] == 0) {\n      psi[q + 1] = 0;\n    } else if (pattern[q + 1] == pattern[pi[q]]) {\n      // Try to hang the edge (q, pi[q]) at the root of pi[q]\n      psi[q + 1] = psi[pi[q]];\n    } else {\n      // Put the edge back where it was\n      psi[q + 1] = pi[q];\n    }\n    // build the graph of psi, by counting the degree of each node\n#endif\n    degrees[psi[q + 1]]++;\n  }\n  \n  // Alloc the graph and reset the degrees to 0\n  for (unsigned q = 0; q <= this->length; ++q) {\n    if (degrees[q])\n      edges[q] = new unsigned[degrees[q]];\n    degrees[q] = 0;\n  }\n  // Compute the graph\n  for (unsigned q = 1; q <= this->length; ++q) {\n    edges[psi[q]][degrees[psi[q]]++] = q; \n  }\n\n#if 0\n  cerr << \"Debug\" << endl;\n  for (unsigned index = 0; index <= this->length; ++index) {\n    cerr << \"Main node : \" << index << \" \";\n    for (unsigned ptr = 0; ptr < degrees[index]; ++ptr) {\n      cerr << edges[index][ptr] << \" \";\n    }\n    cerr << endl;\n  }\n  cerr << endl;\n#endif\n  \n  // Compute omega[] with dfs\n  unordered_map<char, unsigned> indexes;\n  vector<unsigned> activeNodes;\n  dfs(0, indexes, activeNodes, 0);\n  assert(indexes.empty());\n  assert(activeNodes.empty());  \n\n#if 1\n  cerr << \"Debug psi[]\" << endl;\n  for (unsigned index = 0; index <= this->length; ++index) {\n    cerr << index << \" with \" << pattern[index] << \" psi = \" << psi[index] << \" and omega = \" << omega[index] << endl;\n  }\n  cerr << endl;\n#endif\n\n  // delete the graph\n  for (unsigned index = 0; index <= this->length; ++index) {\n    if (degrees[index])\n      delete[] edges[index];\n  }\n  delete[] degrees;\n}\n//---------------------------------------------------------------------------\nvoid hyperKMP::dfs(unsigned state, unordered_map<char, unsigned>& indexes, vector<unsigned>& activeNodes, unsigned minimumHalt)\n// compute the omega[] in linear time\n{\n  // Save into the modified recursion stack\n  activeNodes.push_back(state);\n  valid[state] = true;\n    \n  // Additional variables for reset\n  bool replaced = false;\n  unsigned replacer;\n  if (state) {\n    // Get the last index of the curren state\n    auto iter = indexes.find(state);\n    \n    // Is it the first time we see it?\n    if (iter == indexes.end()) {\n      // Add its index\n      indexes[pattern[state]] = state;\n    } else {\n      // Replace the last with the new position\n      replaced = true;\n      replacer = iter->second;\n      \n      // Unmark the last index and update with the current index\n      valid[replacer] = false;\n      indexes[pattern[state]] = state;\n    }\n    \n    // Compute the minimum halt\n    while (!valid[activeNodes[minimumHalt]])\n      ++minimumHalt;\n  }\n  omega[state] = activeNodes[minimumHalt];\n  \n  // Explore the neighbours\n  for (unsigned index = 0; index < degrees[state]; ++index)\n    dfs(edges[state][index], indexes, activeNodes, minimumHalt);\n  \n  // Reset the stack\n  activeNodes.pop_back();\n  valid[state] = false;\n  if (state) {\n    if (!replaced) {\n      // Erase the state\n      indexes.erase(pattern[state]);\n    } else {\n      // Mark the last index and update it\n      valid[replacer] = true;\n      indexes[pattern[state]] = replacer;\n    }\n  }\n}\n//---------------------------------------------------------------------------\nbool hyperKMP::search(const char* str, unsigned n)\n// checks if the pattern can be found in str\n{\n  if (this->length > n)\n    return false;\n  \n  switch (this->mode) {\n    case HYPER_MODE : {\n      unsigned q = 0; // current state\n      for (unsigned index = 0; index < n; ++index) {\n        // Search only on psi now\n#if 1\n        while ((q > 0) && (str[index] != pattern[q]))\n          q = psi[q];\n#else\n        // lastHalt represents the last state which should be checked (starting from q)\n        unsigned lastHalt = omega[q];\n        while ((q > 0) && (str[index] != pattern[q]))\n          q = psi[q];\n#endif\n        if (str[index] == pattern[q]) {\n          ++q;\n        }\n        // Found?\n        if (q == this->length)\n          return true;\n      }\n      return false;\n    }\n    case NORMAL_MODE : {\n      unsigned q = 0; // current state\n      for (unsigned index = 0; index < n; ++index) {\n        while ((q > 0) && (str[index] != pattern[q]))\n          q = pi[q - 1];\n        if (str[index] == pattern[q]) {\n          ++q;\n        }\n        // Found?\n        if (q == this->length)\n          return true;\n      }\n      return false;\n    }\n    case TEST_MODE : {\n      unsigned q = 0;\n      unsigned hyperLoopsCtr, normalLoopsCtr;\n      for (unsigned index = 0; index < n; ++index) {\n        hyperLoopsCtr = 0, normalLoopsCtr = 0;\n        // lastHalt represents the last state which should be discovered (starting from q)\n        unsigned before = q;\n        unsigned lastHalt = omega[q];\n        while ((q > lastHalt) && (str[index] != pattern[q])) {\n          q = psi[q];\n          hyperLoopsCtr++;\n        }\n        unsigned after = q;\n    \n        q = before;\n        //if (q >= this->length / 2 && str[index] != pattern[q] && pi[q - 1] != 0) cerr << '#' << endl;\n        while ((q > 0) && (str[index] != pattern[q])) {\n          q = pi[q - 1];\n          normalLoopsCtr++;\n        }\n        assert(q == after);\n#if 0\n        //cerr << q << \" vs \" << after << endl;\n        if (q != after) {\n          cerr << \"assert : at \" << index << \" \" << q << \" vs \" << after << endl;\n          assert(0);\n        }\n#endif\n        // Compute the average and the maximum loop steps\n        hyperSum += hyperLoopsCtr;\n        normalSum += normalLoopsCtr;\n        hyperMaximum = std::max(hyperMaximum, hyperLoopsCtr);\n        normalMaximum = std::max(normalMaximum, normalLoopsCtr);\n    \n        // Continue after testing\n        if (str[index] == pattern[q]) {\n          ++q;\n        }\n        // Found?\n        if (q == this->length) {\n          return true;\n        }\n      }\n      return false;\n    }\n  }\n  cerr << \"Something went wrong!\" << endl;\n  return false;\n}\n//---------------------------------------------------------------------------\nvoid hyperKMP::benchmark() {\n  cerr << \"Show benchmark\" << endl;\n  cerr << \"Hyper: sum = \" << hyperSum << \", max = \" << hyperMaximum << endl; \n  cerr << \"Normal: sum = \" << normalSum << \", max = \" << normalMaximum << endl;\n  cerr << \"Win \" << (normalSum - hyperSum) << \" comparisons saved. Relative saving = \" << 100 * ((double)(normalSum - hyperSum) / normalSum) << \"%\" << endl;\n}\n//---------------------------------------------------------------------------\nstatic inline const char* findNl(const char* reader, const char* readerLimit)\n{\n#if 0\n   auto bars=_mm_set1_epi8('\\n');\n   auto limit=readerLimit-16;\n   for (;reader<=limit;reader+=16) {\n      auto nextChars=_mm_lddqu_si128(reinterpret_cast<const __m128i*>(reader));\n      auto cmp=_mm_cmpeq_epi8(nextChars,bars);\n      unsigned mask=_mm_movemask_epi8(cmp);\n      if (mask)\n         return reader=reader+__builtin_ctzl(mask);\n   }\n   for (;reader<=readerLimit;++reader)\n      if ((*reader)=='\\n')\n         return reader;\n   return nullptr;\n#else\n   return static_cast<const char*>(memchr(reader, '\\n', readerLimit-reader));\n#endif\n}\n//---------------------------------------------------------------------------\nint main(int argc, char** argv) {\n  if (argc < 4) {\n    cerr << \"Usage: \" << argv[0] << \"\\n<pattern> (spaces are also allowed, simply an underscore instead: 'aa bb' -> 'aa_bb')\\n<file>\\n<mode>(0 -> hyperKMP, 1 -> normalKMP, 2 -> benchmark to see comparisons)\" << endl;\n    return 0;\n  }\n  // ifstream in;\n  // in.open(argv[2]);\n  \n  unsigned mode = atoi(argv[3]);\n  if (mode > TEST_MODE) {\n    cerr << \"Mode not available!\" << endl;\n    exit(0);\n  }\n  hyperKMP hyper(argv[1], mode);\n  \n  const char* str;\n  unsigned testCases = 0;\n  unsigned countMatches = 0;\n  \n  boost::iostreams::mapped_file_source f(argv[2]);\n  auto fileBegin = f.data();\n  auto fileEnd = fileBegin + f.size();\n  auto reader = fileBegin;\n  \n  auto start = std::chrono::high_resolution_clock::now();\n  while (true) {\n    if (!reader) \n      break;\n    ++testCases;\n    \n    str = reader;\n    unsigned n;\n    {\n      auto eol = findNl(reader, fileEnd);\n      n = eol ? (eol - reader) : (fileEnd - reader);\n      reader = eol? (eol + 1) : nullptr;\n    }\n    countMatches += hyper.search(str, n);\n  }\n  cout << \"Matches = \" << countMatches << \" out of \" << testCases << endl;\n  if (mode == TEST_MODE) {\n    hyper.benchmark();\n  } else {\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto duration = stop - start;\n    cerr << \"Mode (0 -> hyperKMP, 1 -> kmp, 2 -> benchmark) \" << mode << \" took: \" << duration.count() * 1e-6 << \"ms\" << endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "39c44deb90e4594e9a5787a0cdde7373bc7f416b", "size": 11617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark.cpp", "max_stars_repo_name": "stoianmihail/HyperKMP", "max_stars_repo_head_hexsha": "9deb98e9d004026c4d0c72b3d3441560597b5fc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T10:38:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-21T10:38:55.000Z", "max_issues_repo_path": "benchmark.cpp", "max_issues_repo_name": "stoianmihail/HyperKMP", "max_issues_repo_head_hexsha": "9deb98e9d004026c4d0c72b3d3441560597b5fc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark.cpp", "max_forks_repo_name": "stoianmihail/HyperKMP", "max_forks_repo_head_hexsha": "9deb98e9d004026c4d0c72b3d3441560597b5fc6", "max_forks_repo_licenses": ["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.4109947644, "max_line_length": 216, "alphanum_fraction": 0.5241456486, "num_tokens": 3108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.03210070903192238, "lm_q1q2_score": 0.012954782146687636}}
{"text": "/// \\file   walras.hpp\n///\n/// \\brief  A quote is the variable along which trade negotation takes place\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2019-04-04\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#ifndef ESL_QUOTE_HPP\n#define ESL_QUOTE_HPP\n\n#include <variant>\n#include <utility>\n#include <type_traits>\n\n#include <esl/economics/exchange_rate.hpp>\n#include <esl/economics/price.hpp>\n#include <esl/exception.hpp>\n\n\nnamespace esl::economics::markets {\n\n    ///\n    /// \\brief  A quote is a numerical value around which the market is\n    ///     organised. Most commonly, this is a monetary value\n    ///         (a price), but different markets may use different types of\n    ///         quotes such as interest rates in a mortgage market, or a ratio\n    ///         (exchange rate) when bartering.\n    ///\n    ///\n    struct quote\n    {\n    private:\n        constexpr void assert_equal_type_(const quote& other) const\n        {\n            if(type.index() != other.type.index()){\n                throw esl::exception(\"comparing quotes of different types\");\n            }\n        }\n    public:\n        std::variant<exchange_rate, price> type;\n\n        uint64_t lot;\n\n        explicit quote(const exchange_rate &er = exchange_rate(),\n                       uint64_t lot            = 1)\n        : type(er)\n        , lot(lot)\n        {\n            if(0 >= lot){\n                throw esl::exception(\"lot size must be strictly positive\");\n            }\n        }\n\n        ///\n        /// \\param p\n        /// \\param lot\n        explicit quote(const price &p, uint64_t lot = 1)\n        : type(p)\n        , lot(lot )\n        {\n            if(0 >= lot){\n                throw esl::exception(\"lot size must be strictly positive\");\n            }\n        }\n\n\n        explicit quote(double f, const quote &similar)\n        {\n            *this = std::visit([&] (const auto& k) {\n                using variant_ = std::decay_t<decltype(k)>;\n                return quote(variant_(f, k), similar.lot);\n                }, similar.type);\n        }\n\n\n        quote(const quote &q)\n        : type(q.type)\n        , lot(q.lot)\n        {\n            if(0 >= lot){\n                throw esl::exception(\"lot size must be strictly positive\");\n            }\n        }\n\n        ///\n        /// \\brief  When converting to floating point, we divide by the lot size\n        ///         so that we get the quote per unit of goods.\n        ///\n        /// \\tparam floating_point_t_\n        /// \\return\n        template<typename floating_point_t_>\n        explicit operator floating_point_t_() const\n        {\n            return std::visit(\n                [this](auto &&arg) { return floating_point_t_(arg) / lot; },\n                type);\n        }\n\n        ///\n        /// \\param o\n        /// \\return\n        quote &operator = (const quote &o) = default;\n\n        ///\n        /// \\param other\n        /// \\return\n        [[nodiscard]] constexpr bool operator == (const quote &other) const\n        {\n            assert_equal_type_(other);\n\n            return std::visit([&] (const auto& k) {\n                using variant_ = std::decay_t<decltype(k)>;\n\n                if(auto *vp = std::get_if<variant_>(&other.type)  ){\n                    return (lot * k) == ( (*vp) * other.lot );\n                }\n                throw esl::exception(\"quote variants do not match\");\n            }, type);\n        }\n\n        [[nodiscard]] constexpr bool operator != (const quote &other) const\n        {\n            assert_equal_type_(other);\n\n            return std::visit([&] (const auto& k) {\n                using variant_ = std::decay_t<decltype(k)>;\n                if(auto *vp = std::get_if<variant_>(&other.type)  ){\n                    return (lot * k) != ((*vp) * other.lot );\n                }\n                throw esl::exception(\"quote variants do not match\");\n            }, type);\n        }\n\n\n        [[nodiscard]] constexpr bool operator < (const quote &other) const\n        {\n            assert_equal_type_(other);\n\n            return std::visit([&] (const auto& k) {\n                using variant_ = std::decay_t<decltype(k)>;\n                //return (lot * k) < (std::get<variant_>(other.type) * other.lot );\n                if(auto *vp = std::get_if<variant_>(&other.type)  ){\n                    return (lot * k) < ((*vp) * other.lot );\n                }\n                throw esl::exception(\"quote variants do not match\");\n            }, type);\n        }\n\n        [[nodiscard]] constexpr bool operator > (const quote &other) const\n        {\n            assert_equal_type_(other);\n\n            return std::visit([&] (const auto& k) {\n                using variant_ = std::decay_t<decltype(k)>;\n                //return (lot * k) > (std::get<variant_>(other.type) * other.lot );\n                if(auto *vp = std::get_if<variant_>(&other.type)  ){\n                    return (lot * k) > ((*vp) * other.lot );\n                }\n                throw esl::exception(\"quote variants do not match\");\n            }, type);\n        }\n\n        [[nodiscard]] constexpr bool operator <= (const quote &other) const\n        {\n            assert_equal_type_(other);\n\n            return std::visit([&] (const auto& k) {\n                using variant_ = std::decay_t<decltype(k)>;\n                //return (lot * k) <= (std::get<variant_>(other.type) * other.lot );\n                if(auto *vp = std::get_if<variant_>(&other.type)  ){\n                    return (lot * k) <= ((*vp) * other.lot );\n                }\n                throw esl::exception(\"quote variants do not match\");\n            }, type);\n        }\n\n        [[nodiscard]] constexpr bool operator >= (const quote &other) const\n        {\n            assert_equal_type_(other);\n\n            return std::visit([&] (const auto& k) {\n                using variant_ = std::decay_t<decltype(k)>;\n                //return (lot * k) >= (std::get<variant_>(other.type) * other.lot );\n                if(auto *vp = std::get_if<variant_>(&other.type)  ){\n                    return (lot * k) >= ((*vp) * other.lot );\n                }\n                throw esl::exception(\"quote variants do not match\");\n            }, type);\n        }\n\n\n        template<class archive_t>\n        void save(archive_t &archive, const unsigned int version) const\n        {\n            (void)version;\n\n            archive << BOOST_SERIALIZATION_NVP(lot);\n            size_t index_ = type.index();\n            archive &BOOST_SERIALIZATION_NVP(index_);\n            switch(index_) {\n            case 0:\n                if(auto *vp = std::get_if<exchange_rate>(&type)  ){\n                    archive << boost::serialization::make_nvp(\n                        \"exchange_rate\", (vp));\n                    break;\n                }\n            case 1:\n                if(auto *vp = std::get_if<price>(&type)  ){\n                    archive << boost::serialization::make_nvp(\n                        \"price\", *vp);\n                    break;\n                }\n            default:\n                throw esl::exception(\"variant quote not supported\");\n            }\n        }\n\n        template<class archive_t>\n        void load(archive_t &archive, const unsigned int version)\n        {\n            (void)version;\n\n            archive >> BOOST_SERIALIZATION_NVP(lot);\n\n            size_t index_ = 0;\n            archive >> BOOST_SERIALIZATION_NVP(index_);\n            if(0 == index_) {\n                exchange_rate re;\n                archive >> boost::serialization::make_nvp(\"exchange_rate\", re);\n                type.emplace<0>(re);\n            } else if(1 == index_) {\n                price p;\n                archive >> boost::serialization::make_nvp(\"price\", p);\n                type.emplace<1>(p);\n            }\n        }\n\n        template<class archive_t>\n        void serialize(archive_t &archive, const unsigned int version)\n        {\n            boost::serialization::split_member(archive, *this, version);\n        }\n\n//        std::ostream &operator << (std::ostream &stream) const\n//        {\n//            stream << lot << '@';\n//            std::visit([&](const auto &elem)\n//                       {\n//                           stream << elem;\n//                       },\n//                       type);\n//            return stream;\n//        }\n\n        friend std::ostream &operator << (std::ostream &stream, const quote &q)\n        {\n            stream << q.lot << '@';\n            std::visit([&](const auto &elem)\n                       {\n                           stream << elem;\n                       },\n                       q.type);\n            return stream;\n        }\n    };\n\n}  // namespace esl::economics\n\n\n#ifdef WITH_MPI\n#include <boost/mpi.hpp>\nnamespace boost { namespace mpi {\n    template<>\n    struct is_mpi_datatype<esl::economics::markets::quote>\n    : public boost::mpl::true_//is_mpi_datatype<std::variant<esl::economics::exchange_rate\n             //                             , esl::economics::price>>::value\n    {\n\n    };\n}}      // namespace boost::mpi\n#endif  // WITH_MPI\n\n\n#endif  // ESL_QUOTE_HPP\n", "meta": {"hexsha": "09504c994d1eb27fcb53af4eb6dc5df9737f03a1", "size": 9943, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "esl/economics/markets/quote.hpp", "max_stars_repo_name": "rht/ESL", "max_stars_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "esl/economics/markets/quote.hpp", "max_issues_repo_name": "rht/ESL", "max_issues_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/economics/markets/quote.hpp", "max_forks_repo_name": "rht/ESL", "max_forks_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-27T12:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T12:11:48.000Z", "avg_line_length": 32.9238410596, "max_line_length": 90, "alphanum_fraction": 0.4917027054, "num_tokens": 2143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.03210070405485706, "lm_q1q2_score": 0.012954780138109042}}
{"text": "/*  \n *  Copyright 2010-2011 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 <boost/foreach.hpp>\n#include <boost/progress.hpp>\n\n#ifdef _OPENMP // this should really not be a check for Windows, but a check for OpenMP\n    #include <omp.h>\n#endif\n\n#include \"point.hpp\"\n#include \"triangle.hpp\"\n#include \"batchdropcutter.hpp\"\n\nnamespace ocl\n{\n\n//********   ********************** */\n\nBatchDropCutter::BatchDropCutter() {\n    clpoints = new std::vector<CLPoint>();\n    nCalls = 0;\n#ifdef _OPENMP\n    nthreads = omp_get_num_procs(); // figure out how many cores we have\n#endif\n    cutter = NULL;\n    bucketSize = 1;\n    root = new KDTree<Triangle>();\n}\n\nBatchDropCutter::~BatchDropCutter() { \n    clpoints->clear();\n    delete clpoints;\n    delete root;\n}\n \nvoid BatchDropCutter::setSTL(const STLSurf &s) {\n    std::cout << \"bdc::setSTL()\\n\";\n    surf = &s;\n    root->setXYDimensions(); // we search for triangles in the XY plane, don't care about Z-coordinate\n    root->setBucketSize( bucketSize );\n    root->build(s.tris);\n    std::cout << \"bdc::setSTL() done.\\n\";\n}\n\n\n\nvoid BatchDropCutter::appendPoint(CLPoint& p) {\n    clpoints->push_back(p);\n}\n\n// drop cutter against all triangles in surface\nvoid BatchDropCutter::dropCutter1() {\n    std::cout << \"dropCutterSTL1 \" << clpoints->size() << \n              \" cl-points and \" << surf->tris.size() << \" triangles...\";\n    nCalls = 0;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) {\n        BOOST_FOREACH( const Triangle& t, surf->tris) {// test against all triangles in s\n            cutter->dropCutter(cl,t);\n            ++nCalls;\n        }\n    }\n    std::cout << \"done.\\n\";\n    return;\n}\n\n// first search for triangles under the cutter\n// then only drop cutter against found triangles\nvoid BatchDropCutter::dropCutter2() {\n    std::cout << \"dropCutterSTL2 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    std::cout.flush();\n    nCalls = 0;\n    std::list<Triangle> *triangles_under_cutter;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) { //loop through each CL-point\n        triangles_under_cutter = root->search_cutter_overlap( cutter , &cl);\n        BOOST_FOREACH( const Triangle& t, *triangles_under_cutter) {\n            cutter->dropCutter(cl,t);\n            ++nCalls;\n        }\n        delete triangles_under_cutter;\n    }\n    \n    std::cout << \"done. \" << nCalls << \" dropCutter() calls.\\n\";\n    std::cout.flush();\n    return;\n}\n\n// compared to dropCutter2, add an additional explicit overlap-test before testing triangle\nvoid BatchDropCutter::dropCutter3() {\n    std::cout << \"dropCutterSTL3 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    nCalls = 0;\n    boost::progress_display show_progress( clpoints->size() );\n    std::list<Triangle> *triangles_under_cutter;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) { //loop through each CL-point\n        triangles_under_cutter = root->search_cutter_overlap( cutter , &cl);\n        BOOST_FOREACH( const Triangle& t, *triangles_under_cutter) {\n            if (cutter->overlaps(cl,t)) {\n                if ( cl.below(t) ) {\n                    cutter->dropCutter(cl,t);\n                    ++nCalls;\n                }\n            }\n        }\n        ++show_progress;\n        delete triangles_under_cutter;\n    }\n    \n    std::cout << \"done. \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n// use OpenMP to share work between threads\nvoid BatchDropCutter::dropCutter4() {\n    std::cout << \"dropCutterSTL4 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    boost::progress_display show_progress( clpoints->size() );\n    nCalls = 0;\n    int calls=0;\n    long int ntris = 0;\n    std::list<Triangle>* tris;\n    unsigned int n;\n    unsigned int Nmax = clpoints->size();\n    std::vector<CLPoint>& clref = *clpoints; \n    int nloop=0;\n#ifdef _OPENMP\n    omp_set_num_threads(nthreads); // the constructor sets number of threads right\n                                   // or the user can explicitly specify something else\n#endif\n    std::list<Triangle>::iterator it;\n    #pragma omp parallel for shared( nloop, ntris, calls, clref) private(n,tris,it)\n        for (n=0;n< Nmax ;n++) { // PARALLEL OpenMP loop!\n#ifdef _OPENMP\n            if ( n== 0 ) { // first iteration\n                if (omp_get_thread_num() == 0 ) \n                    std::cout << \"Number of OpenMP threads = \"<< omp_get_num_threads() << \"\\n\";// print out how many threads we are using\n            }\n#endif\n            nloop++;\n            tris = root->search_cutter_overlap( cutter, &clref[n] );\n//            assert( tris->size() <= ntriangles ); // can't possibly find more triangles than in the STLSurf \n            for( it=tris->begin(); it!=tris->end() ; ++it) { // loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { // cutter overlap triangle? check\n                    if (clref[n].below(*it)) {\n                        cutter->vertexDrop( clref[n],*it);\n                        ++calls;\n                    }\n                }\n            }\n            for( it=tris->begin(); it!=tris->end() ; ++it) { // loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { // cutter overlap triangle? check\n                    if (clref[n].below(*it))\n                        cutter->facetDrop( clref[n],*it);\n                }\n            }\n            for( it=tris->begin(); it!=tris->end() ; ++it) { // loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { // cutter overlap triangle? check\n                    if (clref[n].below(*it))\n                        cutter->edgeDrop( clref[n],*it);\n                }\n            }\n            ntris += tris->size();\n            delete( tris );\n            ++show_progress;\n        } // end OpenMP PARALLEL for\n    nCalls = calls;\n    std::cout << \" \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n// use OpenMP to share work between threads\nvoid BatchDropCutter::dropCutter5() {\n    std::cout << \"dropCutterSTL5 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    boost::progress_display show_progress( clpoints->size() );\n    nCalls = 0;\n    int calls=0;\n    long int ntris = 0;\n    std::list<Triangle>* tris;\n    unsigned int n;\n    unsigned int Nmax = clpoints->size();\n    std::vector<CLPoint>& clref = *clpoints; \n    int nloop=0;\n    \n#ifdef _OPENMP\n    omp_set_num_threads(nthreads); // the constructor sets number of threads right\n                                   // or the user can explicitly specify something else\n#endif\n    std::list<Triangle>::iterator it;\n    #pragma omp parallel for schedule(dynamic) shared( nloop, ntris, calls, clref ) private(n,tris,it) \n        for (n=0;n<Nmax;++n) { // PARALLEL OpenMP loop!\n#ifdef _OPENMP\n            if ( n== 0 ) { // first iteration\n                if (omp_get_thread_num() == 0 ) \n                    std::cout << \"Number of OpenMP threads = \"<< omp_get_num_threads() << \"\\n\";\n            }\n#endif\n            nloop++;\n            tris = root->search_cutter_overlap( cutter, &clref[n] );\n            assert( tris );\n//\t\t\tassert( tris->size() <= ntriangles ); // can't possibly find more triangles than in the STLSurf \n            for( it=tris->begin(); it!=tris->end() ; ++it) { // loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { // cutter overlap triangle? check\n                    if (clref[n].below(*it)) {\n                        cutter->dropCutter( clref[n],*it);\n                        ++calls;\n                    }\n                }\n            }\n            ntris += tris->size();\n            delete( tris );\n            ++show_progress;\n        } // end OpenMP PARALLEL for\n    nCalls = calls;\n    std::cout << \"\\n \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n}// end namespace\n// end file batchdropcutter.cpp\n", "meta": {"hexsha": "6494dd29a18f76bda74d45628dcb1cff3195b653", "size": 8638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/dropcutter/batchdropcutter.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/dropcutter/batchdropcutter.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/dropcutter/batchdropcutter.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": 36.2941176471, "max_line_length": 137, "alphanum_fraction": 0.5713128039, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.04401865080353022, "lm_q1q2_score": 0.01295094557599172}}
{"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 __FACE_HANDLES_HPP__\r\n#define __FACE_HANDLES_HPP__\r\n\r\n\r\n#include <list>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n\r\n\r\n// A \"face handle\" is an optimization meant to serve two purposes in\r\n// the implementation of the Boyer-Myrvold planarity test: (1) it holds\r\n// the partial planar embedding of a particular vertex as it's being\r\n// constructed, and (2) it allows for efficient traversal around the\r\n// outer face of the partial embedding at that particular vertex. A face\r\n// handle is lightweight, just a shared pointer to the actual implementation,\r\n// since it is passed around/copied liberally in the algorithm. It consists\r\n// of an \"anchor\" (the actual vertex it's associated with) as well as a\r\n// sequence of edges. The functions first_vertex/second_vertex and\r\n// first_edge/second_edge allow fast access to the beginning and end of the\r\n// stored sequence, which allows one to traverse the outer face of the partial\r\n// planar embedding as it's being created. \r\n//\r\n// There are some policies below that define the contents of the face handles:\r\n// in the case no embedding is needed (for example, if one just wants to use\r\n// the Boyer-Myrvold algorithm as a true/false test for planarity, the\r\n// no_embedding class can be passed as the StoreEmbedding policy. Otherwise,\r\n// either std_list (which uses as std::list) or recursive_lazy_list can be\r\n// passed as this policy. recursive_lazy_list has the best theoretical\r\n// performance (O(n) for a sequence of interleaved concatenations and reversals\r\n// of the underlying list), but I've noticed little difference between std_list\r\n// and recursive_lazy_list in my tests, even though using std_list changes\r\n// the worst-case complexity of the planarity test to O(n^2)\r\n//\r\n// Another policy is StoreOldHandlesPolicy, which specifies whether or not\r\n// to keep a record of the previous first/second vertex/edge - this is needed\r\n// if a Kuratowski subgraph needs to be isolated.\r\n\r\n\r\nnamespace boost { namespace graph { namespace detail {\r\n\r\n\r\n  //face handle policies\r\n  \r\n  //EmbeddingStorage policy\r\n  struct store_embedding {};\r\n  struct recursive_lazy_list : public store_embedding {};\r\n  struct std_list : public store_embedding {};\r\n  struct no_embedding {};\r\n\r\n  //StoreOldHandlesPolicy\r\n  struct store_old_handles {};\r\n  struct no_old_handles {};\r\n\r\n\r\n\r\n\r\n  template<typename DataType>\r\n  struct lazy_list_node\r\n  {\r\n    typedef shared_ptr< lazy_list_node<DataType> > ptr_t;\r\n\r\n    lazy_list_node(const DataType& data) :\r\n      m_reversed(false),\r\n      m_data(data),\r\n      m_has_data(true)\r\n    {}\r\n    \r\n    lazy_list_node(ptr_t left_child, ptr_t right_child) :\r\n      m_reversed(false),\r\n      m_has_data(false),\r\n      m_left_child(left_child),\r\n      m_right_child(right_child)\r\n    {}\r\n\r\n    bool m_reversed;\r\n    DataType m_data;\r\n    bool m_has_data;\r\n    shared_ptr<lazy_list_node> m_left_child;\r\n    shared_ptr<lazy_list_node> m_right_child;\r\n  };\r\n  \r\n\r\n\r\n  template <typename StoreOldHandlesPolicy, typename Vertex, typename Edge>\r\n  struct old_handles_storage;\r\n\r\n  template <typename Vertex, typename Edge>\r\n  struct old_handles_storage<store_old_handles, Vertex, Edge>\r\n  {\r\n    Vertex first_vertex;\r\n    Vertex second_vertex;\r\n    Edge first_edge;\r\n    Edge second_edge;\r\n  };\r\n\r\n  template <typename Vertex, typename Edge>\r\n  struct old_handles_storage<no_old_handles, Vertex, Edge>\r\n  {};\r\n\r\n\r\n\r\n\r\n\r\n\r\n  template <typename StoreEmbeddingPolicy, typename Edge>\r\n  struct edge_list_storage;\r\n\r\n\r\n\r\n\r\n\r\n  template <typename Edge>\r\n  struct edge_list_storage<no_embedding, Edge>\r\n  {\r\n    typedef void type;\r\n\r\n    void push_back(Edge) {}\r\n    void push_front(Edge) {}\r\n    void reverse() {}\r\n    void concat_front(edge_list_storage<no_embedding,Edge>) {}\r\n    void concat_back(edge_list_storage<no_embedding,Edge>) {}\r\n    template <typename OutputIterator>\r\n    void get_list(OutputIterator) {}\r\n  };\r\n\r\n\r\n\r\n\r\n\r\n  template <typename Edge>\r\n  struct edge_list_storage<recursive_lazy_list, Edge>\r\n  {\r\n    typedef lazy_list_node<Edge> node_type;\r\n    typedef shared_ptr< node_type > type;\r\n    type value;\r\n\r\n    void push_back(Edge e)\r\n    {\r\n      type new_node(new node_type(e));\r\n      value = type(new node_type(value, new_node));\r\n    }\r\n\r\n    void push_front(Edge e)\r\n    {\r\n      type new_node(new node_type(e));\r\n      value = type(new node_type(new_node, value));\r\n    }\r\n\r\n    void reverse()\r\n    {\r\n      value->m_reversed = !value->m_reversed;\r\n    }\r\n\r\n    void concat_front(edge_list_storage<recursive_lazy_list, Edge> other)\r\n    {\r\n      value = type(new node_type(other.value, value));\r\n    }\r\n\r\n    void concat_back(edge_list_storage<recursive_lazy_list, Edge> other)\r\n    {\r\n      value = type(new node_type(value, other.value));\r\n    }\r\n\r\n    template <typename OutputIterator>\r\n    void get_list(OutputIterator out)\r\n    {\r\n      get_list_helper(out, value);\r\n    }\r\n\r\n  private:\r\n\r\n    template <typename OutputIterator>\r\n    void get_list_helper(OutputIterator o_itr, \r\n                         type root,\r\n                         bool flipped = false\r\n                         )\r\n    {\r\n      if (!root)\r\n        return;\r\n      \r\n      if (root->m_has_data)\r\n        *o_itr = root->m_data;\r\n      \r\n      if ((flipped && !root->m_reversed) ||\r\n          (!flipped && root->m_reversed)\r\n          )\r\n        {\r\n          get_list_helper(o_itr, root->m_right_child, true);\r\n          get_list_helper(o_itr, root->m_left_child, true);\r\n        }\r\n      else\r\n        {\r\n          get_list_helper(o_itr, root->m_left_child, false);\r\n          get_list_helper(o_itr, root->m_right_child, false);\r\n        }\r\n      \r\n    }\r\n    \r\n  };\r\n\r\n\r\n\r\n\r\n\r\n  template <typename Edge>\r\n  struct edge_list_storage<std_list, Edge>\r\n  {\r\n    typedef std::list<Edge> type;\r\n    type value;\r\n\r\n    void push_back(Edge e)\r\n    {\r\n      value.push_back(e);\r\n    }\r\n\r\n    void push_front(Edge e)\r\n    {\r\n      value.push_front(e);\r\n    }\r\n\r\n    void reverse()\r\n    {\r\n      value.reverse();\r\n    }\r\n\r\n    void concat_front(edge_list_storage<std_list,Edge> other)\r\n    {\r\n      value.splice(value.begin(), other.value);\r\n    }\r\n\r\n    void concat_back(edge_list_storage<std_list, Edge> other)\r\n    {\r\n      value.splice(value.end(), other.value);\r\n    }\r\n\r\n    template <typename OutputIterator>\r\n    void get_list(OutputIterator out)\r\n    {\r\n      std::copy(value.begin(), value.end(), out);\r\n    }\r\n\r\n  };\r\n\r\n\r\n\r\n\r\n\r\n\r\n  \r\n  template<typename Graph, \r\n           typename StoreOldHandlesPolicy, \r\n           typename StoreEmbeddingPolicy           \r\n           >\r\n  struct face_handle_impl\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 edge_list_storage<StoreEmbeddingPolicy, edge_t>::type \r\n      edge_list_storage_t;\r\n\r\n\r\n    face_handle_impl() : \r\n      cached_first_vertex(graph_traits<Graph>::null_vertex()),\r\n      cached_second_vertex(graph_traits<Graph>::null_vertex()),\r\n      true_first_vertex(graph_traits<Graph>::null_vertex()),\r\n      true_second_vertex(graph_traits<Graph>::null_vertex()),\r\n      anchor(graph_traits<Graph>::null_vertex())\r\n    {\r\n      initialize_old_vertices_dispatch(StoreOldHandlesPolicy());\r\n    }\r\n\r\n    void initialize_old_vertices_dispatch(store_old_handles)\r\n    {\r\n      old_handles.first_vertex = graph_traits<Graph>::null_vertex();\r\n      old_handles.second_vertex = graph_traits<Graph>::null_vertex();\r\n    }\r\n\r\n    void initialize_old_vertices_dispatch(no_old_handles) {}\r\n\r\n    vertex_t cached_first_vertex;\r\n    vertex_t cached_second_vertex;\r\n    vertex_t true_first_vertex;\r\n    vertex_t true_second_vertex;\r\n    vertex_t anchor;\r\n    edge_t cached_first_edge;\r\n    edge_t cached_second_edge;\r\n\r\n    edge_list_storage<StoreEmbeddingPolicy, edge_t> edge_list;\r\n    old_handles_storage<StoreOldHandlesPolicy, vertex_t, edge_t> old_handles;\r\n\r\n  };\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n  template <typename Graph, \r\n            typename StoreOldHandlesPolicy = store_old_handles, \r\n            typename StoreEmbeddingPolicy = recursive_lazy_list\r\n            >\r\n  class face_handle \r\n  {\r\n  public:\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 face_handle_impl\r\n      <Graph, StoreOldHandlesPolicy, StoreEmbeddingPolicy> impl_t;\r\n    typedef face_handle\r\n      <Graph, StoreOldHandlesPolicy, StoreEmbeddingPolicy> self_t;\r\n\r\n    face_handle(vertex_t anchor = graph_traits<Graph>::null_vertex()) :\r\n      pimpl(new impl_t())\r\n    {\r\n      pimpl->anchor = anchor;\r\n    }\r\n\r\n    face_handle(vertex_t anchor, edge_t initial_edge, const Graph& g) :\r\n      pimpl(new impl_t())\r\n    {\r\n      vertex_t s(source(initial_edge,g));\r\n      vertex_t t(target(initial_edge,g));\r\n      vertex_t other_vertex = s == anchor ? t : s;\r\n      pimpl->anchor = anchor;\r\n      pimpl->cached_first_edge = initial_edge;\r\n      pimpl->cached_second_edge = initial_edge;\r\n      pimpl->cached_first_vertex = other_vertex;\r\n      pimpl->cached_second_vertex = other_vertex;\r\n      pimpl->true_first_vertex = other_vertex;\r\n      pimpl->true_second_vertex = other_vertex;\r\n\r\n      pimpl->edge_list.push_back(initial_edge);\r\n      store_old_face_handles_dispatch(StoreOldHandlesPolicy());\r\n    }\r\n\r\n    //default copy construction, assignment okay.\r\n    \r\n    void push_first(edge_t e, const Graph& g) \r\n    { \r\n      pimpl->edge_list.push_front(e);\r\n      pimpl->cached_first_vertex = pimpl->true_first_vertex = \r\n        source(e, g) == pimpl->anchor ? target(e,g) : source(e,g);\r\n      pimpl->cached_first_edge = e;\r\n    }\r\n  \r\n    void push_second(edge_t e, const Graph& g) \r\n    { \r\n      pimpl->edge_list.push_back(e);\r\n      pimpl->cached_second_vertex = pimpl->true_second_vertex = \r\n        source(e, g) == pimpl->anchor ? target(e,g) : source(e,g);\r\n      pimpl->cached_second_edge = e;\r\n    }\r\n\r\n    inline void store_old_face_handles()\r\n    {\r\n      store_old_face_handles_dispatch(StoreOldHandlesPolicy());\r\n    }\r\n\r\n    inline vertex_t first_vertex() const\r\n    { \r\n      return pimpl->cached_first_vertex;\r\n    }\r\n    \r\n    inline vertex_t second_vertex() const \r\n    { \r\n      return pimpl->cached_second_vertex;\r\n    }\r\n\r\n    inline vertex_t true_first_vertex() const \r\n    { \r\n      return pimpl->true_first_vertex;\r\n    }\r\n\r\n    inline vertex_t true_second_vertex() const \r\n    { \r\n      return pimpl->true_second_vertex;\r\n    }\r\n\r\n    inline vertex_t old_first_vertex() const\r\n    {\r\n      return pimpl->old_handles.first_vertex;\r\n    }\r\n\r\n    inline vertex_t old_second_vertex() const\r\n    {\r\n      return pimpl->old_handles.second_vertex;\r\n    }\r\n\r\n    inline edge_t old_first_edge() const\r\n    {\r\n      return pimpl->old_handles.first_edge;\r\n    }\r\n\r\n    inline edge_t old_second_edge() const\r\n    {\r\n      return pimpl->old_handles.second_edge;\r\n    }\r\n\r\n    inline edge_t first_edge() const\r\n    {\r\n      return pimpl->cached_first_edge;\r\n    }\r\n  \r\n    inline edge_t second_edge() const\r\n    {\r\n      return pimpl->cached_second_edge;\r\n    }\r\n    \r\n    inline vertex_t get_anchor() const\r\n    {\r\n      return pimpl->anchor;\r\n    }\r\n  \r\n    void glue_first_to_second\r\n      (face_handle<Graph,StoreOldHandlesPolicy,StoreEmbeddingPolicy>& bottom)\r\n    {\r\n      pimpl->edge_list.concat_front(bottom.pimpl->edge_list);\r\n      pimpl->true_first_vertex = bottom.pimpl->true_first_vertex;\r\n      pimpl->cached_first_vertex = bottom.pimpl->cached_first_vertex;\r\n      pimpl->cached_first_edge = bottom.pimpl->cached_first_edge;\r\n    }\r\n    \r\n    void glue_second_to_first\r\n      (face_handle<Graph,StoreOldHandlesPolicy,StoreEmbeddingPolicy>& bottom)\r\n    {\r\n      pimpl->edge_list.concat_back(bottom.pimpl->edge_list);\r\n      pimpl->true_second_vertex = bottom.pimpl->true_second_vertex;\r\n      pimpl->cached_second_vertex = bottom.pimpl->cached_second_vertex;\r\n      pimpl->cached_second_edge = bottom.pimpl->cached_second_edge;\r\n    }\r\n  \r\n    void flip()\r\n    {\r\n      pimpl->edge_list.reverse();\r\n      std::swap(pimpl->true_first_vertex, pimpl->true_second_vertex);\r\n      std::swap(pimpl->cached_first_vertex, pimpl->cached_second_vertex);\r\n      std::swap(pimpl->cached_first_edge, pimpl->cached_second_edge);\r\n    }\r\n    \r\n    template <typename OutputIterator>\r\n    void get_list(OutputIterator o_itr)\r\n    {\r\n      pimpl->edge_list.get_list(o_itr);\r\n    }\r\n\r\n    void reset_vertex_cache()\r\n    {\r\n      pimpl->cached_first_vertex = pimpl->true_first_vertex;\r\n      pimpl->cached_second_vertex = pimpl->true_second_vertex;\r\n    }\r\n\r\n    inline void set_first_vertex(vertex_t v)\r\n    {\r\n      pimpl->cached_first_vertex = v;\r\n    }\r\n\r\n    inline void set_second_vertex(vertex_t v)\r\n    {\r\n      pimpl->cached_second_vertex = v;\r\n    }\r\n\r\n  private:\r\n\r\n    void store_old_face_handles_dispatch(store_old_handles)\r\n    {\r\n      pimpl->old_handles.first_vertex = pimpl->true_first_vertex;\r\n      pimpl->old_handles.second_vertex = pimpl->true_second_vertex;\r\n      pimpl->old_handles.first_edge = pimpl->cached_first_edge;\r\n      pimpl->old_handles.second_edge = pimpl->cached_second_edge;\r\n    }\r\n  \r\n    void store_old_face_handles_dispatch(no_old_handles) {}\r\n\r\n\r\n\r\n    boost::shared_ptr<impl_t> pimpl;\r\n\r\n  };\r\n\r\n\r\n} /* namespace detail */ } /* namespace graph */ } /* namespace boost */\r\n\r\n\r\n#endif //__FACE_HANDLES_HPP__\r\n", "meta": {"hexsha": "81c8cce7431e3f38278f837a94a8d49ff7a759e3", "size": 13759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/planar_detail/face_handles.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/planar_detail/face_handles.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/planar_detail/face_handles.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 27.6285140562, "max_line_length": 80, "alphanum_fraction": 0.6549894614, "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824860330003, "lm_q2_score": 0.03789242309851159, "lm_q1q2_score": 0.012943388083803872}}
{"text": "/**\n * @file\n * @brief Implementation of generic charge propagation module\n * @remarks Based on code from Paul Schuetze\n * @copyright Copyright (c) 2017-2020 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n */\n\n#include \"GenericPropagationModule.hpp\"\n\n#include <cmath>\n#include <limits>\n#include <map>\n#include <memory>\n#include <random>\n#include <sstream>\n#include <string>\n#include <utility>\n\n#include <Eigen/Core>\n\n#include <Math/Point3D.h>\n#include <Math/Vector3D.h>\n#include <TCanvas.h>\n#include <TFile.h>\n#include <TH2F.h>\n#include <TH3F.h>\n#include <TPaveText.h>\n#include <TPolyLine3D.h>\n#include <TPolyMarker3D.h>\n#include <TStyle.h>\n\n#include \"core/config/Configuration.hpp\"\n#include \"core/messenger/Messenger.hpp\"\n#include \"core/utils/distributions.h\"\n#include \"core/utils/log.h\"\n#include \"core/utils/unit.h\"\n#include \"tools/ROOT.h\"\n#include \"tools/runge_kutta.h\"\n\n#include \"objects/DepositedCharge.hpp\"\n#include \"objects/PropagatedCharge.hpp\"\n\nusing namespace allpix;\n\n/**\n * Besides binding the message and setting defaults for the configuration, the module copies some configuration variables to\n * local copies to speed up computation.\n */\nGenericPropagationModule::GenericPropagationModule(Configuration& config,\n                                                   Messenger* messenger,\n                                                   std::shared_ptr<Detector> detector)\n    : Module(config, detector), messenger_(messenger), detector_(std::move(detector)) {\n    // Save detector model\n    model_ = detector_->getModel();\n\n    // Require deposits message for single detector\n    messenger_->bindSingle<DepositedChargeMessage>(this, MsgFlags::REQUIRED);\n\n    // Set default value for config variables\n    config_.setDefault<double>(\"spatial_precision\", Units::get(0.25, \"nm\"));\n    config_.setDefault<double>(\"timestep_start\", Units::get(0.01, \"ns\"));\n    config_.setDefault<double>(\"timestep_min\", Units::get(0.001, \"ns\"));\n    config_.setDefault<double>(\"timestep_max\", Units::get(0.5, \"ns\"));\n    config_.setDefault<double>(\"integration_time\", Units::get(25, \"ns\"));\n    config_.setDefault<unsigned int>(\"charge_per_step\", 10);\n    config_.setDefault<double>(\"temperature\", 293.15);\n\n    // Models:\n    config_.setDefault<std::string>(\"mobility_model\", \"jacoboni\");\n    config_.setDefault<std::string>(\"recombination_model\", \"none\");\n\n    config_.setDefault<bool>(\"output_linegraphs\", false);\n    config_.setDefault<bool>(\"output_animations\", false);\n    config_.setDefault<bool>(\"output_plots\",\n                             config_.get<bool>(\"output_linegraphs\") || config_.get<bool>(\"output_animations\"));\n    config_.setDefault<bool>(\"output_animations_color_markers\", false);\n    config_.setDefault<double>(\"output_plots_step\", config_.get<double>(\"timestep_max\"));\n    config_.setDefault<bool>(\"output_plots_use_pixel_units\", false);\n    config_.setDefault<bool>(\"output_plots_align_pixels\", false);\n    config_.setDefault<double>(\"output_plots_theta\", 0.0f);\n    config_.setDefault<double>(\"output_plots_phi\", 0.0f);\n    config_.setDefault<bool>(\"output_plots_lines_at_implants\", false);\n\n    // Set defaults for charge carrier propagation:\n    config_.setDefault<bool>(\"propagate_electrons\", true);\n    config_.setDefault<bool>(\"propagate_holes\", false);\n    if(!config_.get<bool>(\"propagate_electrons\") && !config_.get<bool>(\"propagate_holes\")) {\n        throw InvalidValueError(\n            config_,\n            \"propagate_electrons\",\n            \"No charge carriers selected for propagation, enable 'propagate_electrons' or 'propagate_holes'.\");\n    }\n\n    config_.setDefault<bool>(\"ignore_magnetic_field\", false);\n\n    // Copy some variables from configuration to avoid lookups:\n    temperature_ = config_.get<double>(\"temperature\");\n    timestep_min_ = config_.get<double>(\"timestep_min\");\n    timestep_max_ = config_.get<double>(\"timestep_max\");\n    timestep_start_ = config_.get<double>(\"timestep_start\");\n    integration_time_ = config_.get<double>(\"integration_time\");\n    target_spatial_precision_ = config_.get<double>(\"spatial_precision\");\n    output_plots_ = config_.get<bool>(\"output_plots\");\n    output_linegraphs_ = config_.get<bool>(\"output_linegraphs\");\n    output_animations_ = config_.get<bool>(\"output_animations\");\n    output_plots_step_ = config_.get<double>(\"output_plots_step\");\n    output_plots_lines_at_implants_ = config_.get<bool>(\"output_plots_lines_at_implants\");\n    propagate_electrons_ = config_.get<bool>(\"propagate_electrons\");\n    propagate_holes_ = config_.get<bool>(\"propagate_holes\");\n    charge_per_step_ = config_.get<unsigned int>(\"charge_per_step\");\n\n    // Enable multithreading of this module if multithreading is enabled and no per-event output plots are requested:\n    // FIXME: Review if this is really the case or we can still use multithreading\n    if(!(output_animations_ || output_linegraphs_)) {\n        allow_multithreading();\n    } else {\n        LOG(WARNING) << \"Per-event line graphs or animations requested, disabling parallel event processing\";\n    }\n\n    boltzmann_kT_ = Units::get(8.6173e-5, \"eV/K\") * temperature_;\n\n    // Parameter for charge transport in magnetic field (approximated from graphs:\n    // http://www.ioffe.ru/SVA/NSM/Semicond/Si/electric.html) FIXME\n    electron_Hall_ = 1.15;\n    hole_Hall_ = 0.9;\n}\n\nvoid GenericPropagationModule::create_output_plots(uint64_t event_num, OutputPlotPoints& output_plot_points) {\n    LOG(TRACE) << \"Writing output plots\";\n\n    // Convert to pixel units if necessary\n    if(config_.get<bool>(\"output_plots_use_pixel_units\")) {\n        for(auto& deposit_points : output_plot_points) {\n            for(auto& point : deposit_points.second) {\n                point.SetX(point.x() / model_->getPixelSize().x());\n                point.SetY(point.y() / model_->getPixelSize().y());\n            }\n        }\n    }\n\n    // Calculate the axis limits\n    double minX = FLT_MAX, maxX = FLT_MIN;\n    double minY = FLT_MAX, maxY = FLT_MIN;\n    unsigned long tot_point_cnt = 0;\n    double start_time = std::numeric_limits<double>::max();\n    unsigned int total_charge = 0;\n    unsigned int max_charge = 0;\n    for(auto& [deposit, points] : output_plot_points) {\n        for(auto& point : points) {\n            minX = std::min(minX, point.x());\n            maxX = std::max(maxX, point.x());\n\n            minY = std::min(minY, point.y());\n            maxY = std::max(maxY, point.y());\n        }\n        start_time = std::min(start_time, deposit.getGlobalTime());\n        total_charge += deposit.getCharge();\n        max_charge = std::max(max_charge, deposit.getCharge());\n\n        tot_point_cnt += points.size();\n    }\n\n    // Compute frame axis sizes if equal scaling is requested\n    if(config_.get<bool>(\"output_plots_use_equal_scaling\", true)) {\n        double centerX = (minX + maxX) / 2.0;\n        double centerY = (minY + maxY) / 2.0;\n        if(config_.get<bool>(\"output_plots_use_pixel_units\")) {\n            minX = centerX - model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;\n            maxX = centerX + model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;\n\n            minY = centerY - model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;\n            maxY = centerY + model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;\n        } else {\n            minX = centerX - model_->getSensorSize().z() / 2.0;\n            maxX = centerX + model_->getSensorSize().z() / 2.0;\n\n            minY = centerY - model_->getSensorSize().z() / 2.0;\n            maxY = centerY + model_->getSensorSize().z() / 2.0;\n        }\n    }\n\n    // Align on pixels if requested\n    if(config_.get<bool>(\"output_plots_align_pixels\")) {\n        if(config_.get<bool>(\"output_plots_use_pixel_units\")) {\n            minX = std::floor(minX - 0.5) + 0.5;\n            minY = std::floor(minY + 0.5) - 0.5;\n            maxX = std::ceil(maxX - 0.5) + 0.5;\n            maxY = std::ceil(maxY + 0.5) - 0.5;\n        } else {\n            double div = minX / model_->getPixelSize().x();\n            minX = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().x();\n            div = minY / model_->getPixelSize().y();\n            minY = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().y();\n            div = maxX / model_->getPixelSize().x();\n            maxX = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().x();\n            div = maxY / model_->getPixelSize().y();\n            maxY = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().y();\n        }\n    }\n\n    // Use a histogram to create the underlying frame\n    auto* histogram_frame = new TH3F((\"frame_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                     \"\",\n                                     10,\n                                     minX,\n                                     maxX,\n                                     10,\n                                     minY,\n                                     maxY,\n                                     10,\n                                     model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,\n                                     model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0);\n    histogram_frame->SetDirectory(getROOTDirectory());\n\n    // Create the canvas for the line plot and set orientation\n    auto canvas = std::make_unique<TCanvas>((\"line_plot_\" + std::to_string(event_num)).c_str(),\n                                            (\"Propagation of charge for event \" + std::to_string(event_num)).c_str(),\n                                            1280,\n                                            1024);\n    canvas->cd();\n    canvas->SetTheta(config_.get<float>(\"output_plots_theta\") * 180.0f / ROOT::Math::Pi());\n    canvas->SetPhi(config_.get<float>(\"output_plots_phi\") * 180.0f / ROOT::Math::Pi());\n\n    // Draw the frame on the canvas\n    histogram_frame->GetXaxis()->SetTitle(\n        (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n    histogram_frame->GetYaxis()->SetTitle(\n        (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n    histogram_frame->GetZaxis()->SetTitle(\"z (mm)\");\n    histogram_frame->Draw();\n\n    // Loop over all point sets created during propagation\n    // The vector of unique_pointers is required in order not to delete the objects before the canvas is drawn.\n    std::vector<std::unique_ptr<TPolyLine3D>> lines;\n    short current_color = 1;\n    for(auto& [deposit, points] : output_plot_points) {\n        auto line = std::make_unique<TPolyLine3D>();\n        for(auto& point : points) {\n            line->SetNextPoint(point.x(), point.y(), point.z());\n        }\n        // Plot all lines with at least three points with different color\n        if(line->GetN() >= 3) {\n            EColor plot_color = (deposit.getType() == CarrierType::ELECTRON ? EColor::kAzure : EColor::kOrange);\n            current_color = static_cast<short int>(plot_color - 9 + (static_cast<int>(current_color) + 1) % 19);\n            line->SetLineColor(current_color);\n            line->Draw(\"same\");\n        }\n        lines.push_back(std::move(line));\n    }\n\n    // Draw and write canvas to module output file, then clear the stored lines\n    canvas->Draw();\n    getROOTDirectory()->WriteTObject(canvas.get());\n    lines.clear();\n\n    // Create canvas for GIF animition of process\n    canvas = std::make_unique<TCanvas>((\"animation_\" + std::to_string(event_num)).c_str(),\n                                       (\"Propagation of charge for event \" + std::to_string(event_num)).c_str(),\n                                       1280,\n                                       1024);\n    canvas->cd();\n\n    // Change axis labels if close to zero or PI as they behave different here\n    if(std::fabs(config_.get<double>(\"output_plots_theta\") / (ROOT::Math::Pi() / 2.0) -\n                 std::round(config_.get<double>(\"output_plots_theta\") / (ROOT::Math::Pi() / 2.0))) < 1e-6 ||\n       std::fabs(config_.get<double>(\"output_plots_phi\") / (ROOT::Math::Pi() / 2.0) -\n                 std::round(config_.get<double>(\"output_plots_phi\") / (ROOT::Math::Pi() / 2.0))) < 1e-6) {\n        histogram_frame->GetXaxis()->SetLabelOffset(-0.1f);\n        histogram_frame->GetYaxis()->SetLabelOffset(-0.075f);\n    } else {\n        histogram_frame->GetXaxis()->SetTitleOffset(2.0f);\n        histogram_frame->GetYaxis()->SetTitleOffset(2.0f);\n    }\n\n    // Draw frame on canvas\n    histogram_frame->Draw();\n\n    if(output_animations_) {\n        // Create the contour histogram\n        std::vector<std::string> file_name_contour;\n        std::vector<TH2F*> histogram_contour;\n        file_name_contour.push_back(createOutputFile(\"contourX\" + std::to_string(event_num) + \".gif\"));\n        histogram_contour.push_back(new TH2F((\"contourX_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                             \"\",\n                                             100,\n                                             minY,\n                                             maxY,\n                                             100,\n                                             model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,\n                                             model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));\n        histogram_contour.back()->SetDirectory(getROOTDirectory());\n        file_name_contour.push_back(createOutputFile(\"contourY\" + std::to_string(event_num) + \".gif\"));\n        histogram_contour.push_back(new TH2F((\"contourY_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                             \"\",\n                                             100,\n                                             minX,\n                                             maxX,\n                                             100,\n                                             model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,\n                                             model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));\n        histogram_contour.back()->SetDirectory(getROOTDirectory());\n        file_name_contour.push_back(createOutputFile(\"contourZ\" + std::to_string(event_num) + \".gif\"));\n        histogram_contour.push_back(new TH2F((\"contourZ_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                             \"\",\n                                             100,\n                                             minX,\n                                             maxX,\n                                             100,\n                                             minY,\n                                             maxY));\n        histogram_contour.back()->SetDirectory(getROOTDirectory());\n\n        // Create file and disable statistics for histogram\n        std::string file_name_anim = createOutputFile(\"animation\" + std::to_string(event_num) + \".gif\");\n        for(size_t i = 0; i < 3; ++i) {\n            histogram_contour[i]->SetStats(false);\n        }\n\n        // Remove temporary created files\n        auto ret = remove(file_name_anim.c_str());\n        for(size_t i = 0; i < 3; ++i) {\n            ret |= remove(file_name_contour[i].c_str());\n        }\n        if(ret != 0) {\n            throw ModuleError(\"Could not delete temporary animation files.\");\n        }\n\n        // Create color table\n        TColor* colors[80]; // NOLINT\n        for(int i = 20; i < 100; ++i) {\n            auto color_idx = TColor::GetFreeColorIndex();\n            colors[i - 20] = new TColor(color_idx,\n                                        static_cast<float>(i) / 100.0f - 0.2f,\n                                        static_cast<float>(i) / 100.0f - 0.2f,\n                                        static_cast<float>(i) / 100.0f - 0.2f);\n        }\n\n        // Create animation of moving charges\n        auto animation_time = static_cast<unsigned int>(\n            std::round((Units::convert(config_.get<long double>(\"output_plots_step\"), \"ms\") / 10.0) *\n                       config_.get<long double>(\"output_animations_time_scaling\", 1e9)));\n        unsigned long plot_idx = 0;\n        unsigned int point_cnt = 0;\n        LOG_PROGRESS(INFO, getUniqueName() + \"_OUTPUT_PLOTS\") << \"Written 0 of \" << tot_point_cnt << \" points for animation\";\n        while(point_cnt < tot_point_cnt) {\n            std::vector<std::unique_ptr<TPolyMarker3D>> markers;\n            unsigned long min_idx_diff = std::numeric_limits<unsigned long>::max();\n\n            // Reset the canvas\n            canvas->Clear();\n            canvas->SetTheta(config_.get<float>(\"output_plots_theta\") * 180.0f / ROOT::Math::Pi());\n            canvas->SetPhi(config_.get<float>(\"output_plots_phi\") * 180.0f / ROOT::Math::Pi());\n            canvas->Draw();\n\n            // Reset the histogram frame\n            histogram_frame->SetTitle(\"Charge propagation in sensor\");\n            histogram_frame->GetXaxis()->SetTitle(\n                (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n            histogram_frame->GetYaxis()->SetTitle(\n                (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n            histogram_frame->GetZaxis()->SetTitle(\"z (mm)\");\n            histogram_frame->Draw();\n\n            auto text = std::make_unique<TPaveText>(-0.75, -0.75, -0.60, -0.65);\n            auto time_ns = Units::convert(plot_idx * config_.get<long double>(\"output_plots_step\"), \"ns\");\n            std::stringstream sstr;\n            sstr << std::fixed << std::setprecision(2) << time_ns << \"ns\";\n            auto time_str = std::string(8 - sstr.str().size(), ' ');\n            time_str += sstr.str();\n            text->AddText(time_str.c_str());\n            text->Draw();\n\n            // Plot all the required points\n            for(auto& [deposit, points] : output_plot_points) {\n                auto diff = static_cast<unsigned long>(\n                    std::round((deposit.getGlobalTime() - start_time) / config_.get<long double>(\"output_plots_step\")));\n                if(plot_idx < diff) {\n                    min_idx_diff = std::min(min_idx_diff, diff - plot_idx);\n                    continue;\n                }\n                auto idx = plot_idx - diff;\n                if(idx >= points.size()) {\n                    continue;\n                }\n                min_idx_diff = 0;\n\n                auto marker = std::make_unique<TPolyMarker3D>();\n                marker->SetMarkerStyle(kFullCircle);\n                marker->SetMarkerSize(\n                    static_cast<float>(deposit.getCharge() * config_.get<double>(\"output_animations_marker_size\", 1)) /\n                    static_cast<float>(max_charge));\n                auto initial_z_perc = static_cast<int>(\n                    ((points[0].z() + model_->getSensorSize().z() / 2.0) / model_->getSensorSize().z()) * 80);\n                initial_z_perc = std::max(std::min(79, initial_z_perc), 0);\n                if(config_.get<bool>(\"output_animations_color_markers\")) {\n                    marker->SetMarkerColor(static_cast<Color_t>(colors[initial_z_perc]->GetNumber()));\n                }\n                marker->SetNextPoint(points[idx].x(), points[idx].y(), points[idx].z());\n                marker->Draw();\n                markers.push_back(std::move(marker));\n\n                histogram_contour[0]->Fill(points[idx].y(), points[idx].z(), deposit.getCharge());\n                histogram_contour[1]->Fill(points[idx].x(), points[idx].z(), deposit.getCharge());\n                histogram_contour[2]->Fill(points[idx].x(), points[idx].y(), deposit.getCharge());\n                ++point_cnt;\n            }\n\n            // Create a step in the animation\n            if(min_idx_diff != 0) {\n                canvas->Print((file_name_anim + \"+100\").c_str());\n                plot_idx += min_idx_diff;\n            } else {\n                // print animation\n                if(point_cnt < tot_point_cnt - 1) {\n                    canvas->Print((file_name_anim + \"+\" + std::to_string(animation_time)).c_str());\n                } else {\n                    canvas->Print((file_name_anim + \"++100\").c_str());\n                }\n\n                // Draw and print contour histograms\n                for(size_t i = 0; i < 3; ++i) {\n                    canvas->Clear();\n                    canvas->SetTitle((std::string(\"Contour of charge propagation projected on the \") +\n                                      static_cast<char>('X' + i) + \"-axis\")\n                                         .c_str());\n                    switch(i) {\n                    case 0 /* x */:\n                        histogram_contour[i]->GetXaxis()->SetTitle(\n                            (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        histogram_contour[i]->GetYaxis()->SetTitle(\"z (mm)\");\n                        break;\n                    case 1 /* y */:\n                        histogram_contour[i]->GetXaxis()->SetTitle(\n                            (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        histogram_contour[i]->GetYaxis()->SetTitle(\"z (mm)\");\n                        break;\n                    case 2 /* z */:\n                        histogram_contour[i]->GetXaxis()->SetTitle(\n                            (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        histogram_contour[i]->GetYaxis()->SetTitle(\n                            (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        break;\n                    default:;\n                    }\n                    histogram_contour[i]->SetMinimum(1);\n                    histogram_contour[i]->SetMaximum(total_charge /\n                                                     config_.get<double>(\"output_animations_contour_max_scaling\", 10));\n                    histogram_contour[i]->Draw(\"CONTZ 0\");\n                    if(point_cnt < tot_point_cnt - 1) {\n                        canvas->Print((file_name_contour[i] + \"+\" + std::to_string(animation_time)).c_str());\n                    } else {\n                        canvas->Print((file_name_contour[i] + \"++100\").c_str());\n                    }\n                    histogram_contour[i]->Reset();\n                }\n                ++plot_idx;\n            }\n            markers.clear();\n\n            LOG_PROGRESS(INFO, getUniqueName() + \"_OUTPUT_PLOTS\")\n                << \"Written \" << point_cnt << \" of \" << tot_point_cnt << \" points for animation\";\n        }\n    }\n}\n\nvoid GenericPropagationModule::initialize() {\n\n    auto detector = getDetector();\n\n    // Check for electric field and output warning for slow propagation if not defined\n    if(!detector->hasElectricField()) {\n        LOG(WARNING) << \"This detector does not have an electric field.\";\n    }\n\n    // For linear fields we can in addition check if the correct carriers are propagated\n    if(detector->getElectricFieldType() == FieldType::LINEAR) {\n        auto model = detector_->getModel();\n        auto probe_point = ROOT::Math::XYZPoint(model->getSensorCenter().x(),\n                                                model->getSensorCenter().y(),\n                                                model->getSensorCenter().z() + model->getSensorSize().z() / 2.01);\n\n        // Get the field close to the implants and check its sign:\n        auto efield = detector->getElectricField(probe_point);\n        auto direction = std::signbit(efield.z());\n        // Compare with propagated carrier type:\n        if(direction && !propagate_electrons_) {\n            LOG(WARNING) << \"Electric field indicates electron collection at implants, but electrons are not propagated!\";\n        }\n        if(!direction && !propagate_holes_) {\n            LOG(WARNING) << \"Electric field indicates hole collection at implants, but holes are not propagated!\";\n        }\n    }\n\n    // Check for magnetic field\n    has_magnetic_field_ = detector->hasMagneticField();\n    if(has_magnetic_field_) {\n        if(config_.get<bool>(\"ignore_magnetic_field\")) {\n            has_magnetic_field_ = false;\n            LOG(WARNING) << \"A magnetic field is switched on, but is set to be ignored for this module.\";\n        } else {\n            LOG(DEBUG) << \"This detector sees a magnetic field.\";\n            magnetic_field_ = detector_->getMagneticField();\n        }\n    }\n\n    if(output_plots_) {\n        step_length_histo_ =\n            CreateHistogram<TH1D>(\"step_length_histo\",\n                                  \"Step length;length [#mum];integration steps\",\n                                  100,\n                                  0,\n                                  static_cast<double>(Units::convert(0.25 * model_->getSensorSize().z(), \"um\")));\n\n        drift_time_histo_ = CreateHistogram<TH1D>(\"drift_time_histo\",\n                                                  \"Drift time;Drift time [ns];charge carriers\",\n                                                  static_cast<int>(Units::convert(integration_time_, \"ns\") * 5),\n                                                  0,\n                                                  static_cast<double>(Units::convert(integration_time_, \"ns\")));\n\n        uncertainty_histo_ =\n            CreateHistogram<TH1D>(\"uncertainty_histo\",\n                                  \"Position uncertainty;uncertainty [nm];integration steps\",\n                                  100,\n                                  0,\n                                  static_cast<double>(4 * Units::convert(config_.get<double>(\"spatial_precision\"), \"nm\")));\n\n        group_size_histo_ = CreateHistogram<TH1D>(\"group_size_histo\",\n                                                  \"Charge carrier group size;group size;number of groups transported\",\n                                                  static_cast<int>(charge_per_step_ - 1),\n                                                  1,\n                                                  static_cast<double>(charge_per_step_));\n\n        recombine_histo_ =\n            CreateHistogram<TH1D>(\"recombination_histo\",\n                                  \"Fraction of recombined charge carriers;recombination [N / N_{total}] ;number of events\",\n                                  100,\n                                  0,\n                                  1);\n    }\n\n    // Prepare mobility model\n    try {\n        mobility_ = Mobility(config_.get<std::string>(\"mobility_model\"), temperature_, detector->hasDopingProfile());\n    } catch(ModelError& e) {\n        throw InvalidValueError(config_, \"mobility_model\", e.what());\n    }\n\n    // Prepare recombination model\n    try {\n        recombination_ = Recombination(config_.get<std::string>(\"recombination_model\"), detector->hasDopingProfile());\n    } catch(ModelError& e) {\n        throw InvalidValueError(config_, \"recombination_model\", e.what());\n    }\n}\n\nvoid GenericPropagationModule::run(Event* event) {\n    auto deposits_message = messenger_->fetchMessage<DepositedChargeMessage>(this, event);\n\n    // Create vector of propagated charges to output\n    std::vector<PropagatedCharge> propagated_charges;\n\n    // List of points to plot to plot for output plots\n    OutputPlotPoints output_plot_points;\n\n    // Loop over all deposits for propagation\n    LOG(TRACE) << \"Propagating charges in sensor\";\n    unsigned int propagated_charges_count = 0;\n    unsigned int recombined_charges_count = 0;\n    unsigned int step_count = 0;\n    long double total_time = 0;\n    for(const auto& deposit : deposits_message->getData()) {\n\n        if((deposit.getType() == CarrierType::ELECTRON && !propagate_electrons_) ||\n           (deposit.getType() == CarrierType::HOLE && !propagate_holes_)) {\n            LOG(DEBUG) << \"Skipping charge carriers (\" << deposit.getType() << \") on \"\n                       << Units::display(deposit.getLocalPosition(), {\"mm\", \"um\"});\n            continue;\n        }\n\n        // Only process if within requested integration time:\n        if(deposit.getLocalTime() > integration_time_) {\n            LOG(DEBUG) << \"Skipping charge carriers deposited beyond integration time: \"\n                       << Units::display(deposit.getGlobalTime(), \"ns\") << \" global / \"\n                       << Units::display(deposit.getLocalTime(), {\"ns\", \"ps\"}) << \" local\";\n            continue;\n        }\n\n        // Loop over all charges in the deposit\n        unsigned int charges_remaining = deposit.getCharge();\n\n        LOG(DEBUG) << \"Set of charge carriers (\" << deposit.getType() << \") on \"\n                   << Units::display(deposit.getLocalPosition(), {\"mm\", \"um\"});\n\n        auto charge_per_step = charge_per_step_;\n        while(charges_remaining > 0) {\n            // Define number of charges to be propagated and remove charges of this step from the total\n            if(charge_per_step > charges_remaining) {\n                charge_per_step = charges_remaining;\n            }\n            charges_remaining -= charge_per_step;\n\n            // Get position and propagate through sensor\n            auto initial_position = deposit.getLocalPosition();\n\n            // Add point of deposition to the output plots if requested\n            if(output_linegraphs_) {\n                auto global_position = detector_->getGlobalPosition(initial_position);\n                std::lock_guard<std::mutex> lock{stats_mutex_};\n                output_plot_points.emplace_back(PropagatedCharge(initial_position,\n                                                                 global_position,\n                                                                 deposit.getType(),\n                                                                 charge_per_step,\n                                                                 deposit.getLocalTime(),\n                                                                 deposit.getGlobalTime()),\n                                                std::vector<ROOT::Math::XYZPoint>());\n            }\n\n            // Propagate a single charge deposit\n            auto [final_position, time, alive] = propagate(\n                initial_position, deposit.getType(), deposit.getLocalTime(), event->getRandomEngine(), output_plot_points);\n\n            if(!alive) {\n                LOG(DEBUG) << \" Recombined \" << charge_per_step << \" at \" << Units::display(final_position, {\"mm\", \"um\"})\n                           << \" in \" << Units::display(time, \"ns\") << \" time, removing\";\n                recombined_charges_count += charge_per_step;\n                continue;\n            }\n\n            LOG(DEBUG) << \" Propagated \" << charge_per_step << \" to \" << Units::display(final_position, {\"mm\", \"um\"})\n                       << \" in \" << Units::display(time, \"ns\") << \" time\";\n\n            // Create a new propagated charge and add it to the list\n            auto global_position = detector_->getGlobalPosition(final_position);\n            PropagatedCharge propagated_charge(final_position,\n                                               global_position,\n                                               deposit.getType(),\n                                               charge_per_step,\n                                               deposit.getLocalTime() + time,\n                                               deposit.getGlobalTime() + time,\n                                               &deposit);\n\n            propagated_charges.push_back(std::move(propagated_charge));\n\n            // Update statistical information\n            ++step_count;\n            propagated_charges_count += charge_per_step;\n            total_time += charge_per_step * time;\n            if(output_plots_) {\n                drift_time_histo_->Fill(static_cast<double>(Units::convert(time, \"ns\")), charge_per_step);\n                group_size_histo_->Fill(charge_per_step);\n            }\n        }\n    }\n\n    // Output plots if required\n    if(output_linegraphs_) {\n        create_output_plots(event->number, output_plot_points);\n    }\n\n    // Write summary and update statistics\n    long double average_time = total_time / std::max(1u, propagated_charges_count);\n    LOG(INFO) << \"Propagated \" << propagated_charges_count << \" charges in \" << step_count << \" steps in average time of \"\n              << Units::display(average_time, \"ns\") << std::endl\n              << \"Recombined \" << recombined_charges_count << \" charges during transport\";\n    total_propagated_charges_ += propagated_charges_count;\n    total_steps_ += step_count;\n    total_time_picoseconds_ += static_cast<long unsigned int>(total_time * 1e3);\n\n    if(output_plots_) {\n        recombine_histo_->Fill(static_cast<double>(recombined_charges_count) /\n                               (propagated_charges_count + recombined_charges_count));\n    }\n\n    // Create a new message with propagated charges\n    auto propagated_charge_message = std::make_shared<PropagatedChargeMessage>(std::move(propagated_charges), detector_);\n\n    // Dispatch the message with propagated charges\n    messenger_->dispatchMessage(this, propagated_charge_message, event);\n}\n\n/**\n * Propagation is simulated using a parameterization for the electron mobility. This is used to calculate the electron\n * velocity at every point with help of the electric field map of the detector. An Runge-Kutta integration is applied in\n * multiple steps, adding a random diffusion to the propagating charge every step.\n */\nstd::tuple<ROOT::Math::XYZPoint, double, bool>\nGenericPropagationModule::propagate(const ROOT::Math::XYZPoint& pos,\n                                    const CarrierType& type,\n                                    const double initial_time,\n                                    RandomNumberGenerator& random_generator,\n                                    OutputPlotPoints& output_plot_points) const {\n    // Create a runge kutta solver using the electric field as step function\n    Eigen::Vector3d position(pos.x(), pos.y(), pos.z());\n\n    // Define a function to compute the diffusion\n    auto carrier_diffusion = [&](double efield_mag, double doping_concentration, double timestep) -> Eigen::Vector3d {\n        double diffusion_constant = boltzmann_kT_ * mobility_(type, efield_mag, doping_concentration);\n        double diffusion_std_dev = std::sqrt(2. * diffusion_constant * timestep);\n\n        // Compute the independent diffusion in three\n        allpix::normal_distribution<double> gauss_distribution(0, diffusion_std_dev);\n        Eigen::Vector3d diffusion;\n        for(int i = 0; i < 3; ++i) {\n            diffusion[i] = gauss_distribution(random_generator);\n        }\n        return diffusion;\n    };\n\n    // Survival probability of this charge carrier package, evaluated at every step\n    std::uniform_real_distribution<double> survival(0, 1);\n\n    // Define lambda functions to compute the charge carrier velocity with or without magnetic field\n    std::function<Eigen::Vector3d(double, const Eigen::Vector3d&)> carrier_velocity_noB =\n        [&](double, const Eigen::Vector3d& cur_pos) -> Eigen::Vector3d {\n        auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));\n        Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());\n        auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(cur_pos));\n\n        return static_cast<int>(type) * mobility_(type, efield.norm(), doping) * efield;\n    };\n\n    std::function<Eigen::Vector3d(double, const Eigen::Vector3d&)> carrier_velocity_withB =\n        [&](double, const Eigen::Vector3d& cur_pos) -> Eigen::Vector3d {\n        auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));\n        Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());\n\n        Eigen::Vector3d velocity;\n        Eigen::Vector3d bfield(magnetic_field_.x(), magnetic_field_.y(), magnetic_field_.z());\n\n        auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(cur_pos));\n\n        auto mob = mobility_(type, efield.norm(), doping);\n        auto exb = efield.cross(bfield);\n\n        Eigen::Vector3d term1;\n        double hallFactor = (type == CarrierType::ELECTRON ? electron_Hall_ : hole_Hall_);\n        term1 = static_cast<int>(type) * mob * hallFactor * exb;\n\n        Eigen::Vector3d term2 = mob * mob * hallFactor * hallFactor * efield.dot(bfield) * bfield;\n\n        auto rnorm = 1 + mob * mob * hallFactor * hallFactor * bfield.dot(bfield);\n        return static_cast<int>(type) * mob * (efield + term1 + term2) / rnorm;\n    };\n\n    // Create the runge kutta solver with an RKF5 tableau, using different velocity calculators depending on the magnetic\n    // field\n    auto runge_kutta = make_runge_kutta(\n        tableau::RK5, (has_magnetic_field_ ? carrier_velocity_withB : carrier_velocity_noB), timestep_start_, position);\n\n    // Continue propagation until the deposit is outside the sensor\n    Eigen::Vector3d last_position = position;\n    double last_time = 0;\n    size_t next_idx = 0;\n    bool is_alive = true;\n    while(detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position)) &&\n          (initial_time + runge_kutta.getTime()) < integration_time_ && is_alive) {\n        // Update output plots if necessary (depending on the plot step)\n        if(output_linegraphs_) {\n            auto time_idx = static_cast<size_t>(runge_kutta.getTime() / output_plots_step_);\n            while(next_idx <= time_idx) {\n                output_plot_points.back().second.push_back(static_cast<ROOT::Math::XYZPoint>(position));\n                next_idx = output_plot_points.back().second.size();\n            }\n        }\n\n        // Save previous position and time\n        last_position = position;\n        last_time = runge_kutta.getTime();\n\n        // Execute a Runge Kutta step\n        auto step = runge_kutta.step();\n\n        // Get the current result and timestep\n        auto timestep = runge_kutta.getTimeStep();\n        position = runge_kutta.getValue();\n\n        // Get electric field at current position and fall back to empty field if it does not exist\n        auto efield = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(position));\n        auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(position));\n\n        // Apply diffusion step\n        auto diffusion = carrier_diffusion(std::sqrt(efield.Mag2()), doping, timestep);\n        position += diffusion;\n        runge_kutta.setValue(position);\n\n        // Check if charge carrier is still alive:\n        is_alive = !recombination_(type,\n                                   detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(position)),\n                                   survival(random_generator),\n                                   timestep);\n\n        LOG(TRACE) << \"Step from \" << Units::display(static_cast<ROOT::Math::XYZPoint>(last_position), {\"um\", \"mm\"})\n                   << \" to \" << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {\"um\", \"mm\"}) << \" at \"\n                   << Units::display(initial_time + runge_kutta.getTime(), {\"ps\", \"ns\", \"us\"})\n                   << (is_alive ? \"\" : \", recombined\");\n        // Adapt step size to match target precision\n        double uncertainty = step.error.norm();\n\n        // Update step length histogram\n        if(output_plots_) {\n            step_length_histo_->Fill(static_cast<double>(Units::convert(step.value.norm(), \"um\")));\n            uncertainty_histo_->Fill(static_cast<double>(Units::convert(step.error.norm(), \"nm\")));\n        }\n\n        // Lower timestep when reaching the sensor edge\n        if(std::fabs(model_->getSensorSize().z() / 2.0 - position.z()) < 2 * step.value.z()) {\n            timestep *= 0.75;\n        } else {\n            if(uncertainty > target_spatial_precision_) {\n                timestep *= 0.75;\n            } else if(2 * uncertainty < target_spatial_precision_) {\n                timestep *= 1.5;\n            }\n        }\n        // Limit the timestep to certain minimum and maximum step sizes\n        if(timestep > timestep_max_) {\n            timestep = timestep_max_;\n        } else if(timestep < timestep_min_) {\n            timestep = timestep_min_;\n        }\n        runge_kutta.setTimeStep(timestep);\n    }\n\n    // Find proper final position in the sensor\n    auto time = runge_kutta.getTime();\n    if(!detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position))) {\n        auto check_position = position;\n        check_position.z() = last_position.z();\n        if(position.z() > 0 && detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(check_position))) {\n            // Carrier left sensor on the side of the pixel grid, interpolate end point on surface\n            auto z_cur_border = std::fabs(position.z() - model_->getSensorSize().z() / 2.0);\n            auto z_last_border = std::fabs(model_->getSensorSize().z() / 2.0 - last_position.z());\n            auto z_total = z_cur_border + z_last_border;\n            position = (z_last_border / z_total) * position + (z_cur_border / z_total) * last_position;\n            time = (z_last_border / z_total) * time + (z_cur_border / z_total) * last_time;\n        } else {\n            // Carrier left sensor on any order border, use last position inside instead\n            position = last_position;\n            time = last_time;\n        }\n    }\n\n    // If requested, remove charge drift lines from plots if they did not reach the implant side within the integration time:\n    if(output_linegraphs_ && output_plots_lines_at_implants_) {\n        // If drift time is larger than integration time or the charge carriers have been collected at the backside, remove\n        if(time >= integration_time_ || last_position.z() < -model_->getSensorSize().z() * 0.45) {\n            output_plot_points.pop_back();\n        }\n    }\n\n    if(!is_alive) {\n        LOG(DEBUG) << \"Charge carrier recombined after \" << Units::display(last_time, {\"ns\"});\n    }\n\n    // Return the final position of the propagated charge\n    return std::make_tuple(static_cast<ROOT::Math::XYZPoint>(position), initial_time + time, is_alive);\n}\n\nvoid GenericPropagationModule::finalize() {\n    if(output_plots_) {\n        step_length_histo_->Write();\n        drift_time_histo_->Write();\n        uncertainty_histo_->Write();\n        group_size_histo_->Write();\n        recombine_histo_->Write();\n    }\n\n    long double average_time = static_cast<long double>(total_time_picoseconds_) / 1e3 /\n                               std::max(1u, static_cast<unsigned int>(total_propagated_charges_));\n    LOG(INFO) << \"Propagated total of \" << total_propagated_charges_ << \" charges in \" << total_steps_\n              << \" steps in average time of \" << Units::display(average_time, \"ns\");\n}\n", "meta": {"hexsha": "51edb584ab6ed521376076b7cf871d1235b04a63", "size": 43538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/GenericPropagation/GenericPropagationModule.cpp", "max_stars_repo_name": "bencline1/Allpix_GaAs", "max_stars_repo_head_hexsha": "c4922dc9d981aca265e076eb5bfe4cefe51913a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-04T22:31:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T11:19:17.000Z", "max_issues_repo_path": "src/modules/GenericPropagation/GenericPropagationModule.cpp", "max_issues_repo_name": "bencline1/Allpix_GaAs", "max_issues_repo_head_hexsha": "c4922dc9d981aca265e076eb5bfe4cefe51913a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-04-01T12:25:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:20:19.000Z", "max_forks_repo_path": "src/modules/GenericPropagation/GenericPropagationModule.cpp", "max_forks_repo_name": "bencline1/Allpix_GaAs", "max_forks_repo_head_hexsha": "c4922dc9d981aca265e076eb5bfe4cefe51913a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T14:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T17:16:21.000Z", "avg_line_length": 49.475, "max_line_length": 125, "alphanum_fraction": 0.5715926317, "num_tokens": 9404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.02758528122750568, "lm_q1q2_score": 0.012931721681754767}}
{"text": "// Copyright (C) 2006-2008 Garth N. Wells\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// Modified by Anders Logg 2006-2010.\n// Modified by Kent-Andre Mardal 2008.\n// Modified by Martin Sandve Alnes 2008.\n//\n// First added:  2006-04-04\n// Last changed: 2011-01-14\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/unordered_set.hpp>\n\n#include <dolfin/log/dolfin_log.h>\n#include <dolfin/common/Array.h>\n#include \"uBLASVector.h\"\n#include \"uBLASFactory.h\"\n#include \"LinearAlgebraFactory.h\"\n\n#ifdef HAS_PETSC\n#include \"PETScVector.h\"\n#endif\n\nusing namespace dolfin;\n\n//-----------------------------------------------------------------------------\nuBLASVector::uBLASVector(): x(new ublas_vector(0))\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nuBLASVector::uBLASVector(uint N): x(new ublas_vector(N))\n{\n  // Set all entries to zero\n  x->clear();\n}\n//-----------------------------------------------------------------------------\nuBLASVector::uBLASVector(const uBLASVector& x): x(new ublas_vector(*(x.x)))\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nuBLASVector::uBLASVector(boost::shared_ptr<ublas_vector> x) : x(x)\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nuBLASVector::~uBLASVector()\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nuBLASVector* uBLASVector::copy() const\n{\n  return new uBLASVector(*this);\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::resize(uint N)\n{\n  if (x->size() == N)\n    return;\n  x->resize(N, false);\n\n  // Set vector to zero to prevent random numbers entering the vector.\n  // Fixes this bug: https://bugs.launchpad.net/dolfin/+bug/594954\n  x->clear();\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::resize(std::pair<uint, uint> range)\n{\n  if (range.first != 0)\n  {\n    dolfin_error(\"uBLASVector.cpp\",\n                 \"resize uBLAS vector\",\n                 \"Distributed vectors not supported by uBLAS backend\");\n  }\n\n  resize(range.second - range.first);\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::resize(std::pair<uint, uint> range,\n                    const std::vector<uint>& ghost_indices)\n{\n  if (range.first != 0)\n  {\n    dolfin_error(\"uBLASVector.cpp\",\n                 \"resize uBLAS vector\",\n                 \"Distributed vectors not supported by uBLAS backend\");\n  }\n\n  if (ghost_indices.size() != 0)\n  {\n    dolfin_error(\"uBLASVector.cpp\",\n                 \"resize uBLAS vector\",\n                 \"Distributed vectors not supported by uBLAS backend\");\n  }\n\n  resize(range.second - range.first);\n}\n//-----------------------------------------------------------------------------\ndolfin::uint uBLASVector::size() const\n{\n  return x->size();\n}\n//-----------------------------------------------------------------------------\nstd::pair<dolfin::uint, dolfin::uint> uBLASVector::local_range() const\n{\n  return std::make_pair(0, size());\n}\n//-----------------------------------------------------------------------------\nbool uBLASVector::owns_index(uint i) const\n{\n  if (i < size())\n    return true;\n  else\n    return false;\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::get_local(double* block, uint m, const uint* rows) const\n{\n  for (uint i = 0; i < m; i++)\n    block[i] = (*x)(rows[i]);\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::get_local(Array<double>& values) const\n{\n  values.resize(size());\n  for (uint i = 0; i < size(); i++)\n    values[i] = (*x)(i);\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::set_local(const Array<double>& values)\n{\n  dolfin_assert(values.size() == size());\n  for (uint i = 0; i < size(); i++)\n    (*x)(i) = values[i];\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::add_local(const Array<double>& values)\n{\n  dolfin_assert(values.size() == size());\n  for (uint i = 0; i < size(); i++)\n    (*x)(i) += values[i];\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::gather(GenericVector& x, const Array<uint>& indices) const\n{\n  not_working_in_parallel(\"uBLASVector::gather)\");\n\n  const uint _size = indices.size();\n  dolfin_assert(this->size() >= _size);\n\n  x.resize(_size);\n  ublas_vector& _x = x.down_cast<uBLASVector>().vec();\n  for (uint i = 0; i < _size; i++)\n    _x(i) = (*this->x)(indices[i]);\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::gather(Array<double>& x, const Array<uint>& indices) const\n{\n  not_working_in_parallel(\"uBLASVector::gather)\");\n\n  const uint _size = indices.size();\n  x.resize(_size);\n  dolfin_assert(x.size() == _size);\n  for (uint i = 0; i < _size; i++)\n    x[i] = (*this->x)(indices[i]);\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::gather_on_zero(Array<double>& x) const\n{\n  not_working_in_parallel(\"uBLASVector::gather_on_zero)\");\n\n  get_local(x);\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::set(const double* block, uint m, const uint* rows)\n{\n  for (uint i = 0; i < m; i++)\n    (*x)(rows[i]) = block[i];\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::add(const double* block, uint m, const uint* rows)\n{\n  for (uint i = 0; i < m; i++)\n    (*x)(rows[i]) += block[i];\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::apply(std::string mode)\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::zero()\n{\n  x->clear();\n}\n//-----------------------------------------------------------------------------\ndouble uBLASVector::norm(std::string norm_type) const\n{\n  if (norm_type == \"l1\")\n    return norm_1(*x);\n  else if (norm_type == \"l2\")\n    return norm_2(*x);\n  else if (norm_type == \"linf\")\n    return norm_inf(*x);\n  else\n  {\n    dolfin_error(\"uBLASVector.cpp\",\n                 \"compute norm of uBLAS vector\",\n                 \"Unknown norm type (\\\"%s\\\")\", norm_type.c_str());\n  }\n\n  return 0.0;\n}\n//-----------------------------------------------------------------------------\ndouble uBLASVector::min() const\n{\n  double value = *std::min_element(x->begin(), x->end());\n  return value;\n}\n//-----------------------------------------------------------------------------\ndouble uBLASVector::max() const\n{\n  double value = *std::max_element(x->begin(), x->end());\n  return value;\n}\n//-----------------------------------------------------------------------------\ndouble uBLASVector::sum() const\n{\n  return ublas::sum(*x);\n}\n//-----------------------------------------------------------------------------\ndouble uBLASVector::sum(const Array<uint>& rows) const\n{\n  boost::unordered_set<uint> row_set;\n  double _sum = 0.0;\n  for (uint i = 0; i < rows.size(); ++i)\n  {\n    const uint index = rows[i];\n    dolfin_assert(index < size());\n    if (row_set.find(index) == row_set.end())\n    {\n      _sum += (*x)[index];\n      row_set.insert(index);\n    }\n  }\n  return _sum;\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::axpy(double a, const GenericVector& y)\n{\n  if (size() != y.size())\n  {\n    dolfin_error(\"uBLASVector.cpp\",\n                 \"perform axpy operation with uBLAS vector\",\n                 \"Vectors are not of the same size\");\n  }\n\n  (*x) += a * y.down_cast<uBLASVector>().vec();\n}\n//-----------------------------------------------------------------------------\nvoid uBLASVector::abs()\n{\n  dolfin_assert(x);\n  const uint size = x->size();\n  for (uint i = 0; i < size; i++)\n    (*x)[i] = std::abs((*x)[i]);\n}\n//-----------------------------------------------------------------------------\ndouble uBLASVector::inner(const GenericVector& y) const\n{\n  return ublas::inner_prod(*x, y.down_cast<uBLASVector>().vec());\n}\n//-----------------------------------------------------------------------------\nconst GenericVector& uBLASVector::operator= (const GenericVector& v)\n{\n  *this = v.down_cast<uBLASVector>();\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst uBLASVector& uBLASVector::operator= (const uBLASVector& v)\n{\n  if (size() != v.size())\n  {\n    dolfin_error(\"uBLASVector.cpp\",\n                 \"assign one vector to another\",\n                 \"Vectors must be of the same length when assigning. \"\n                 \"Consider using the copy constructor instead\");\n  }\n\n  assert(x);\n  *x = v.vec();\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst uBLASVector& uBLASVector::operator= (double a)\n{\n  x->ublas_vector::assign(ublas::scalar_vector<double> (x->size(), a));\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst uBLASVector& uBLASVector::operator*= (const double a)\n{\n  (*x) *= a;\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst uBLASVector& uBLASVector::operator*= (const GenericVector& y)\n{\n  *x = ublas::element_prod(*x,y.down_cast<uBLASVector>().vec());\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst uBLASVector& uBLASVector::operator/= (const double a)\n{\n  (*x) /= a;\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst uBLASVector& uBLASVector::operator+= (const GenericVector& y)\n{\n  *x += y.down_cast<uBLASVector>().vec();\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst uBLASVector& uBLASVector::operator-= (const GenericVector& y)\n{\n  *x -= y.down_cast<uBLASVector>().vec();\n  return *this;\n}\n//-----------------------------------------------------------------------------\nstd::string uBLASVector::str(bool verbose) const\n{\n  std::stringstream s;\n\n  if (verbose)\n  {\n    s << str(false) << std::endl << std::endl;\n\n    s << \"[\";\n    for (ublas_vector::const_iterator it = x->begin(); it != x->end(); ++it)\n    {\n      std::stringstream entry;\n      entry << std::setiosflags(std::ios::scientific);\n      entry << std::setprecision(16);\n      entry << *it << \" \";\n      s << entry.str() << std::endl;\n    }\n    s << \"]\";\n  }\n  else\n  {\n    s << \"<uBLASVector of size \" << size() << \">\";\n  }\n\n  return s.str();\n}\n//-----------------------------------------------------------------------------\nLinearAlgebraFactory& uBLASVector::factory() const\n{\n  return uBLASFactory<>::instance();\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "b254180256ed56488b1d2ef6d1d24a563bed17bf", "size": 11779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/la/uBLASVector.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/la/uBLASVector.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/la/uBLASVector.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.6744791667, "max_line_length": 79, "alphanum_fraction": 0.4556413957, "num_tokens": 2545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.03904829356494251, "lm_q1q2_score": 0.012929660798180184}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2013, 2014, 2015.\n// Modifications copyright (c) 2013-2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_AREAL_AREAL_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_AREAL_AREAL_HPP\n\n#include <boost/geometry/core/topological_dimension.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/range.hpp>\n\n#include <boost/geometry/algorithms/num_interior_rings.hpp>\n#include <boost/geometry/algorithms/detail/point_on_border.hpp>\n#include <boost/geometry/algorithms/detail/sub_range.hpp>\n#include <boost/geometry/algorithms/detail/single_geometry.hpp>\n\n#include <boost/geometry/algorithms/detail/relate/point_geometry.hpp>\n#include <boost/geometry/algorithms/detail/relate/turns.hpp>\n#include <boost/geometry/algorithms/detail/relate/boundary_checker.hpp>\n#include <boost/geometry/algorithms/detail/relate/follow_helpers.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace relate {\n    \n// WARNING!\n// TODO: In the worst case calling this Pred in a loop for MultiPolygon/MultiPolygon may take O(NM)\n// Use the rtree in this case!\n\n// may be used to set EI and EB for an Areal geometry for which no turns were generated\ntemplate <typename OtherAreal, typename Result, bool TransposeResult>\nclass no_turns_aa_pred\n{\npublic:\n    no_turns_aa_pred(OtherAreal const& other_areal, Result & res)\n        : m_result(res)\n        , m_other_areal(other_areal)\n        , m_flags(0)\n    {\n        // check which relations must be analysed\n\n        if ( ! may_update<interior, interior, '2', TransposeResult>(m_result)\n          && ! may_update<boundary, interior, '1', TransposeResult>(m_result)\n          && ! may_update<exterior, interior, '2', TransposeResult>(m_result) )\n        {\n            m_flags |= 1;\n        }\n\n        if ( ! may_update<interior, exterior, '2', TransposeResult>(m_result)\n          && ! may_update<boundary, exterior, '1', TransposeResult>(m_result) )\n        {\n            m_flags |= 2;\n        }\n    }\n\n    template <typename Areal>\n    bool operator()(Areal const& areal)\n    {\n        // if those flags are set nothing will change\n        if ( m_flags == 3 )\n        {\n            return false;\n        }\n\n        typedef typename geometry::point_type<Areal>::type point_type;\n        point_type pt;\n        bool const ok = boost::geometry::point_on_border(pt, areal);\n\n        // TODO: for now ignore, later throw an exception?\n        if ( !ok )\n        {\n            return true;\n        }\n\n        // check if the areal is inside the other_areal\n        // TODO: This is O(N)\n        // Run in a loop O(NM) - optimize!\n        int const pig = detail::within::point_in_geometry(pt, m_other_areal);\n        //BOOST_ASSERT( pig != 0 );\n        \n        // inside\n        if ( pig > 0 )\n        {\n            update<interior, interior, '2', TransposeResult>(m_result);\n            update<boundary, interior, '1', TransposeResult>(m_result);\n            update<exterior, interior, '2', TransposeResult>(m_result);\n            m_flags |= 1;\n\n            // TODO: OPTIMIZE!\n            // Only the interior rings of other ONE single geometry must be checked\n            // NOT all geometries\n\n            // Check if any interior ring is outside\n            ring_identifier ring_id(0, -1, 0);\n            int const irings_count = boost::numeric_cast<int>(\n                                        geometry::num_interior_rings(areal) );\n            for ( ; ring_id.ring_index < irings_count ; ++ring_id.ring_index )\n            {\n                typename detail::sub_range_return_type<Areal const>::type\n                    range_ref = detail::sub_range(areal, ring_id);\n\n                if ( boost::empty(range_ref) )\n                {\n                    // TODO: throw exception?\n                    continue; // ignore\n                }\n\n                // TODO: O(N)\n                // Optimize!\n                int const hpig = detail::within::point_in_geometry(range::front(range_ref), m_other_areal);\n\n                // hole outside\n                if ( hpig < 0 )\n                {\n                    update<interior, exterior, '2', TransposeResult>(m_result);\n                    update<boundary, exterior, '1', TransposeResult>(m_result);\n                    m_flags |= 2;\n                    break;\n                }\n            }\n        }\n        // outside\n        else\n        {\n            update<interior, exterior, '2', TransposeResult>(m_result);\n            update<boundary, exterior, '1', TransposeResult>(m_result);\n            m_flags |= 2;\n\n            // Check if any interior ring is inside\n            ring_identifier ring_id(0, -1, 0);\n            int const irings_count = boost::numeric_cast<int>(\n                                        geometry::num_interior_rings(areal) );\n            for ( ; ring_id.ring_index < irings_count ; ++ring_id.ring_index )\n            {\n                typename detail::sub_range_return_type<Areal const>::type\n                    range_ref = detail::sub_range(areal, ring_id);\n\n                if ( boost::empty(range_ref) )\n                {\n                    // TODO: throw exception?\n                    continue; // ignore\n                }\n\n                // TODO: O(N)\n                // Optimize!\n                int const hpig = detail::within::point_in_geometry(range::front(range_ref), m_other_areal);\n\n                // hole inside\n                if ( hpig > 0 )\n                {\n                    update<interior, interior, '2', TransposeResult>(m_result);\n                    update<boundary, interior, '1', TransposeResult>(m_result);\n                    update<exterior, interior, '2', TransposeResult>(m_result);\n                    m_flags |= 1;\n                    break;\n                }\n            }\n        }\n                    \n        return m_flags != 3 && !m_result.interrupt;\n    }\n\nprivate:\n    Result & m_result;\n    OtherAreal const& m_other_areal;\n    int m_flags;\n};\n\n// The implementation of an algorithm calculating relate() for A/A\ntemplate <typename Geometry1, typename Geometry2>\nstruct areal_areal\n{\n    // check Linear / Areal\n    BOOST_STATIC_ASSERT(topological_dimension<Geometry1>::value == 2\n                     && topological_dimension<Geometry2>::value == 2);\n\n    static const bool interruption_enabled = true;\n\n    typedef typename geometry::point_type<Geometry1>::type point1_type;\n    typedef typename geometry::point_type<Geometry2>::type point2_type;\n    \n    template <typename Result>\n    static inline void apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Result & result)\n    {\n// TODO: If Areal geometry may have infinite size, change the following line:\n\n        // The result should be FFFFFFFFF\n        relate::set<exterior, exterior, result_dimension<Geometry2>::value>(result);// FFFFFFFFd, d in [1,9] or T\n\n        if ( BOOST_GEOMETRY_CONDITION(result.interrupt) )\n            return;\n\n        // get and analyse turns\n        typedef typename turns::get_turns<Geometry1, Geometry2>::turn_info turn_type;\n        std::vector<turn_type> turns;\n\n        interrupt_policy_areal_areal<Result> interrupt_policy(geometry1, geometry2, result);\n\n        turns::get_turns<Geometry1, Geometry2>::apply(turns, geometry1, geometry2, interrupt_policy);\n        if ( BOOST_GEOMETRY_CONDITION(result.interrupt) )\n            return;\n\n        no_turns_aa_pred<Geometry2, Result, false> pred1(geometry2, result);\n        for_each_disjoint_geometry_if<0, Geometry1>::apply(turns.begin(), turns.end(), geometry1, pred1);\n        if ( BOOST_GEOMETRY_CONDITION(result.interrupt) )\n            return;\n\n        no_turns_aa_pred<Geometry1, Result, true> pred2(geometry1, result);\n        for_each_disjoint_geometry_if<1, Geometry2>::apply(turns.begin(), turns.end(), geometry2, pred2);\n        if ( BOOST_GEOMETRY_CONDITION(result.interrupt) )\n            return;\n        \n        if ( turns.empty() )\n            return;\n\n        if ( may_update<interior, interior, '2'>(result)\n          || may_update<interior, exterior, '2'>(result)\n          || may_update<boundary, interior, '1'>(result)\n          || may_update<boundary, exterior, '1'>(result)\n          || may_update<exterior, interior, '2'>(result) )\n        {\n            // sort turns\n            typedef turns::less<0, turns::less_op_areal_areal<0> > less;\n            std::sort(turns.begin(), turns.end(), less());\n\n            /*if ( may_update<interior, exterior, '2'>(result)\n              || may_update<boundary, exterior, '1'>(result)\n              || may_update<boundary, interior, '1'>(result)\n              || may_update<exterior, interior, '2'>(result) )*/\n            {\n                // analyse sorted turns\n                turns_analyser<turn_type, 0> analyser;\n                analyse_each_turn(result, analyser, turns.begin(), turns.end());\n\n                if ( BOOST_GEOMETRY_CONDITION(result.interrupt) )\n                    return;\n            }\n\n            if ( may_update<interior, interior, '2'>(result)\n              || may_update<interior, exterior, '2'>(result)\n              || may_update<boundary, interior, '1'>(result)\n              || may_update<boundary, exterior, '1'>(result)\n              || may_update<exterior, interior, '2'>(result) )\n            {\n                // analyse rings for which turns were not generated\n                // or only i/i or u/u was generated\n                uncertain_rings_analyser<0, Result, Geometry1, Geometry2> rings_analyser(result, geometry1, geometry2);\n                analyse_uncertain_rings<0>::apply(rings_analyser, turns.begin(), turns.end());\n\n                if ( BOOST_GEOMETRY_CONDITION(result.interrupt) )\n                    return;\n            }\n        }\n\n        if ( may_update<interior, interior, '2', true>(result)\n          || may_update<interior, exterior, '2', true>(result)\n          || may_update<boundary, interior, '1', true>(result)\n          || may_update<boundary, exterior, '1', true>(result)\n          || may_update<exterior, interior, '2', true>(result) )\n        {\n            // sort turns\n            typedef turns::less<1, turns::less_op_areal_areal<1> > less;\n            std::sort(turns.begin(), turns.end(), less());\n\n            /*if ( may_update<interior, exterior, '2', true>(result)\n              || may_update<boundary, exterior, '1', true>(result)\n              || may_update<boundary, interior, '1', true>(result)\n              || may_update<exterior, interior, '2', true>(result) )*/\n            {\n                // analyse sorted turns\n                turns_analyser<turn_type, 1> analyser;\n                analyse_each_turn(result, analyser, turns.begin(), turns.end());\n\n                if ( BOOST_GEOMETRY_CONDITION(result.interrupt) )\n                    return;\n            }\n\n            if ( may_update<interior, interior, '2', true>(result)\n              || may_update<interior, exterior, '2', true>(result)\n              || may_update<boundary, interior, '1', true>(result)\n              || may_update<boundary, exterior, '1', true>(result)\n              || may_update<exterior, interior, '2', true>(result) )\n            {\n                // analyse rings for which turns were not generated\n                // or only i/i or u/u was generated\n                uncertain_rings_analyser<1, Result, Geometry2, Geometry1> rings_analyser(result, geometry2, geometry1);\n                analyse_uncertain_rings<1>::apply(rings_analyser, turns.begin(), turns.end());\n\n                //if ( result.interrupt )\n                //    return;\n            }\n        }\n    }\n\n    // interrupt policy which may be passed to get_turns to interrupt the analysis\n    // based on the info in the passed result/mask\n    template <typename Result>\n    class interrupt_policy_areal_areal\n    {\n    public:\n        static bool const enabled = true;\n\n        interrupt_policy_areal_areal(Geometry1 const& geometry1,\n                                     Geometry2 const& geometry2,\n                                     Result & result)\n            : m_result(result)\n            , m_geometry1(geometry1)\n            , m_geometry2(geometry2)\n        {}\n\n        template <typename Range>\n        inline bool apply(Range const& turns)\n        {\n            typedef typename boost::range_iterator<Range const>::type iterator;\n            \n            for (iterator it = boost::begin(turns) ; it != boost::end(turns) ; ++it)\n            {\n                per_turn<0>(*it);\n                per_turn<1>(*it);\n            }\n\n            return m_result.interrupt;\n        }\n\n    private:\n        template <std::size_t OpId, typename Turn>\n        inline void per_turn(Turn const& turn)\n        {\n            static const std::size_t other_op_id = (OpId + 1) % 2;\n            static const bool transpose_result = OpId != 0;\n\n            overlay::operation_type const op = turn.operations[OpId].operation;\n\n            if ( op == overlay::operation_union )\n            {\n                // ignore u/u\n                /*if ( turn.operations[other_op_id].operation != overlay::operation_union )\n                {\n                    update<interior, exterior, '2', transpose_result>(m_result);\n                    update<boundary, exterior, '1', transpose_result>(m_result);\n                }*/\n\n                update<boundary, boundary, '0', transpose_result>(m_result);\n            }\n            else if ( op == overlay::operation_intersection )\n            {\n                // ignore i/i\n                if ( turn.operations[other_op_id].operation != overlay::operation_intersection )\n                {\n                    update<interior, interior, '2', transpose_result>(m_result);\n                    //update<boundary, interior, '1', transpose_result>(m_result);\n                }\n\n                update<boundary, boundary, '0', transpose_result>(m_result);\n            }\n            else if ( op == overlay::operation_continue )\n            {\n                update<boundary, boundary, '1', transpose_result>(m_result);\n                update<interior, interior, '2', transpose_result>(m_result);\n            }\n            else if ( op == overlay::operation_blocked )\n            {\n                update<boundary, boundary, '1', transpose_result>(m_result);\n                update<interior, exterior, '2', transpose_result>(m_result);\n            }\n        }\n\n        Result & m_result;\n        Geometry1 const& m_geometry1;\n        Geometry2 const& m_geometry2;\n    };\n\n    // This analyser should be used like Input or SinglePass Iterator\n    // IMPORTANT! It should be called also for the end iterator - last\n    template <typename TurnInfo, std::size_t OpId>\n    class turns_analyser\n    {\n        typedef typename TurnInfo::point_type turn_point_type;\n\n        static const std::size_t op_id = OpId;\n        static const std::size_t other_op_id = (OpId + 1) % 2;\n        static const bool transpose_result = OpId != 0;\n\n    public:\n        turns_analyser()\n            : m_previous_turn_ptr(0)\n            , m_previous_operation(overlay::operation_none)\n            , m_enter_detected(false)\n            , m_exit_detected(false)\n        {}\n\n        template <typename Result,\n                  typename TurnIt>\n        void apply(Result & result, TurnIt it)\n        {\n            //BOOST_ASSERT( it != last );\n\n            overlay::operation_type const op = it->operations[op_id].operation;\n\n            if ( op != overlay::operation_union\n              && op != overlay::operation_intersection\n              && op != overlay::operation_blocked\n              && op != overlay::operation_continue )\n            {\n                return;\n            }\n\n            segment_identifier const& seg_id = it->operations[op_id].seg_id;\n            //segment_identifier const& other_id = it->operations[other_op_id].seg_id;\n\n            const bool first_in_range = m_seg_watcher.update(seg_id);\n\n            if ( m_previous_turn_ptr )\n            {\n                if ( m_exit_detected /*m_previous_operation == overlay::operation_union*/ )\n                {\n                    // real exit point - may be multiple\n                    if ( first_in_range\n                      || ! turn_on_the_same_ip<op_id>(*m_previous_turn_ptr, *it) )\n                    {\n                        update_exit(result);\n                        m_exit_detected = false;\n                    }\n                    // fake exit point, reset state\n                    else if ( op != overlay::operation_union )\n                    {\n                        m_exit_detected = false;\n                    }\n                }                \n                /*else*/\n                if ( m_enter_detected /*m_previous_operation == overlay::operation_intersection*/ )\n                {\n                    // real entry point\n                    if ( first_in_range\n                      || ! turn_on_the_same_ip<op_id>(*m_previous_turn_ptr, *it) )\n                    {\n                        update_enter(result);\n                        m_enter_detected = false;\n                    }\n                    // fake entry point, reset state\n                    else if ( op != overlay::operation_intersection )\n                    {\n                        m_enter_detected = false;\n                    }\n                }\n            }\n\n            if ( op == overlay::operation_union )\n            {\n                // already set in interrupt policy\n                //update<boundary, boundary, '0', transpose_result>(m_result);\n\n                // ignore u/u\n                //if ( it->operations[other_op_id].operation != overlay::operation_union )\n                {\n                    m_exit_detected = true;\n                }\n            }\n            else if ( op == overlay::operation_intersection )\n            {\n                // ignore i/i\n                if ( it->operations[other_op_id].operation != overlay::operation_intersection )\n                {\n                    // already set in interrupt policy\n                    //update<interior, interior, '2', transpose_result>(result);\n                    //update<boundary, boundary, '0', transpose_result>(result);\n                    m_enter_detected = true;\n                }\n            }\n            else if ( op == overlay::operation_blocked )\n            {\n                // already set in interrupt policy\n            }\n            else // if ( op == overlay::operation_continue )\n            {\n                // already set in interrupt policy\n            }\n\n            // store ref to previously analysed (valid) turn\n            m_previous_turn_ptr = boost::addressof(*it);\n            // and previously analysed (valid) operation\n            m_previous_operation = op;\n        }\n\n        // it == last\n        template <typename Result>\n        void apply(Result & result)\n        {\n            //BOOST_ASSERT( first != last );\n\n            if ( m_exit_detected /*m_previous_operation == overlay::operation_union*/ )\n            {\n                update_exit(result);\n                m_exit_detected = false;\n            }\n\n            if ( m_enter_detected /*m_previous_operation == overlay::operation_intersection*/ )\n            {\n                update_enter(result);\n                m_enter_detected = false;\n            }\n        }\n\n        template <typename Result>\n        static inline void update_exit(Result & result)\n        {\n            update<interior, exterior, '2', transpose_result>(result);\n            update<boundary, exterior, '1', transpose_result>(result);\n        }\n\n        template <typename Result>\n        static inline void update_enter(Result & result)\n        {\n            update<boundary, interior, '1', transpose_result>(result);\n            update<exterior, interior, '2', transpose_result>(result);\n        }\n\n    private:\n        segment_watcher<same_ring> m_seg_watcher;\n        TurnInfo * m_previous_turn_ptr;\n        overlay::operation_type m_previous_operation;\n        bool m_enter_detected;\n        bool m_exit_detected;\n    };\n\n    // call analyser.apply() for each turn in range\n    // IMPORTANT! The analyser is also called for the end iterator - last\n    template <typename Result,\n              typename Analyser,\n              typename TurnIt>\n    static inline void analyse_each_turn(Result & res,\n                                         Analyser & analyser,\n                                         TurnIt first, TurnIt last)\n    {\n        if ( first == last )\n            return;\n\n        for ( TurnIt it = first ; it != last ; ++it )\n        {\n            analyser.apply(res, it);\n\n            if ( BOOST_GEOMETRY_CONDITION(res.interrupt) )\n                return;\n        }\n\n        analyser.apply(res);\n    }\n\n    template <std::size_t OpId, typename Result, typename Geometry, typename OtherGeometry>\n    class uncertain_rings_analyser\n    {\n        static const bool transpose_result = OpId != 0;\n        static const int other_id = (OpId + 1) % 2;\n\n    public:\n        inline uncertain_rings_analyser(Result & result,\n                                        Geometry const& geom,\n                                        OtherGeometry const& other_geom)\n            : geometry(geom), other_geometry(other_geom)\n            , interrupt(result.interrupt) // just in case, could be false as well\n            , m_result(result)\n            , m_flags(0)\n        {\n            // check which relations must be analysed\n\n            if ( ! may_update<interior, interior, '2', transpose_result>(m_result) )\n            {\n                m_flags |= 1;\n            }\n\n            if ( ! may_update<interior, exterior, '2', transpose_result>(m_result)\n              && ! may_update<boundary, exterior, '1', transpose_result>(m_result) )\n            {\n                m_flags |= 2;\n            }\n\n            if ( ! may_update<boundary, interior, '1', transpose_result>(m_result)\n              && ! may_update<exterior, interior, '2', transpose_result>(m_result) )\n            {\n                m_flags |= 4;\n            }\n        }\n\n        inline void no_turns(segment_identifier const& seg_id)\n        {\n            // if those flags are set nothing will change\n            if ( m_flags == 7 )\n            {\n                return;\n            }\n\n            typename detail::sub_range_return_type<Geometry const>::type\n                range_ref = detail::sub_range(geometry, seg_id);\n\n            if ( boost::empty(range_ref) )\n            {\n                // TODO: throw an exception?\n                return; // ignore\n            }\n                \n            // TODO: possible optimization\n            // if the range is an interior ring we may use other IPs generated for this single geometry\n            // to know which other single geometries should be checked\n\n            // TODO: optimize! e.g. use spatial index\n            // O(N) - running it in a loop gives O(NM)\n            int const pig = detail::within::point_in_geometry(range::front(range_ref), other_geometry);\n\n            //BOOST_ASSERT(pig != 0);\n            if ( pig > 0 )\n            {\n                update<interior, interior, '2', transpose_result>(m_result);\n                m_flags |= 1;\n\n                update<boundary, interior, '1', transpose_result>(m_result);\n                update<exterior, interior, '2', transpose_result>(m_result);\n                m_flags |= 4;\n            }\n            else\n            {\n                update<boundary, exterior, '1', transpose_result>(m_result);\n                update<interior, exterior, '2', transpose_result>(m_result);\n                m_flags |= 2;\n            }\n\n// TODO: break if all things are set\n// also some of them could be checked outside, before the analysis\n// In this case we shouldn't relay just on dummy flags\n// Flags should be initialized with proper values\n// or the result should be checked directly\n// THIS IS ALSO TRUE FOR OTHER ANALYSERS! in L/L and L/A\n\n            interrupt = m_flags == 7 || m_result.interrupt;\n        }\n\n        template <typename TurnIt>\n        inline void turns(TurnIt first, TurnIt last)\n        {\n            // if those flags are set nothing will change\n            if ( (m_flags & 6) == 6 )\n            {\n                return;\n            }\n\n            bool found_ii = false;\n            bool found_uu = false;\n\n            for ( TurnIt it = first ; it != last ; ++it )\n            {\n                if ( it->operations[0].operation == overlay::operation_intersection \n                  && it->operations[1].operation == overlay::operation_intersection )\n                {\n                    // ignore exterior ring\n                    if ( it->operations[OpId].seg_id.ring_index >= 0 )\n                    {\n                        found_ii = true;\n                    }\n                }\n                else if ( it->operations[0].operation == overlay::operation_union \n                       && it->operations[1].operation == overlay::operation_union )\n                {\n                    // ignore if u/u is for holes\n                    //if ( it->operations[OpId].seg_id.ring_index >= 0\n                    //  && it->operations[other_id].seg_id.ring_index >= 0 )\n                    {\n                        found_uu = true;\n                    }\n                }\n                else // ignore\n                {\n                    return; // don't interrupt\n                }\n            }\n\n            // only i/i was generated for this ring\n            if ( found_ii )\n            {\n                //update<interior, interior, '0', transpose_result>(m_result);\n                //update<boundary, boundary, '0', transpose_result>(m_result);\n                update<boundary, interior, '1', transpose_result>(m_result);\n                update<exterior, interior, '2', transpose_result>(m_result);\n                m_flags |= 4;\n            }\n\n            // only u/u was generated for this ring\n            if ( found_uu )\n            {\n                update<boundary, exterior, '1', transpose_result>(m_result);\n                update<interior, exterior, '2', transpose_result>(m_result);\n                m_flags |= 2;\n            }\n\n            interrupt = m_flags == 7 || m_result.interrupt; // interrupt if the result won't be changed in the future\n        }\n\n        Geometry const& geometry;\n        OtherGeometry const& other_geometry;\n        bool interrupt;\n\n    private:\n        Result & m_result;\n        int m_flags;\n    };\n\n    template <std::size_t OpId>\n    class analyse_uncertain_rings\n    {\n    public:\n        template <typename Analyser, typename TurnIt>\n        static inline void apply(Analyser & analyser, TurnIt first, TurnIt last)\n        {\n            if ( first == last )\n                return;\n\n            for_preceding_rings(analyser, *first);\n            //analyser.per_turn(*first);\n\n            TurnIt prev = first;\n            for ( ++first ; first != last ; ++first, ++prev )\n            {\n                // same multi\n                if ( prev->operations[OpId].seg_id.multi_index\n                  == first->operations[OpId].seg_id.multi_index )\n                {\n                    // same ring\n                    if ( prev->operations[OpId].seg_id.ring_index\n                      == first->operations[OpId].seg_id.ring_index )\n                    {\n                        //analyser.per_turn(*first);\n                    }\n                    // same multi, next ring\n                    else\n                    {\n                        //analyser.end_ring(*prev);\n                        analyser.turns(prev, first);\n\n                        //if ( prev->operations[OpId].seg_id.ring_index + 1\n                        //   < first->operations[OpId].seg_id.ring_index)\n                        {\n                            for_no_turns_rings(analyser,\n                                               *first,\n                                               prev->operations[OpId].seg_id.ring_index + 1,\n                                               first->operations[OpId].seg_id.ring_index);\n                        }\n\n                        //analyser.per_turn(*first);\n                    }\n                }\n                // next multi\n                else\n                {\n                    //analyser.end_ring(*prev);\n                    analyser.turns(prev, first);\n                    for_following_rings(analyser, *prev);\n                    for_preceding_rings(analyser, *first);\n                    //analyser.per_turn(*first);\n                }\n\n                if ( analyser.interrupt )\n                {\n                    return;\n                }\n            }\n\n            //analyser.end_ring(*prev);\n            analyser.turns(prev, first); // first == last\n            for_following_rings(analyser, *prev);\n        }\n\n    private:\n        template <typename Analyser, typename Turn>\n        static inline void for_preceding_rings(Analyser & analyser, Turn const& turn)\n        {\n            segment_identifier const& seg_id = turn.operations[OpId].seg_id;\n\n            for_no_turns_rings(analyser, turn, -1, seg_id.ring_index);\n        }\n\n        template <typename Analyser, typename Turn>\n        static inline void for_following_rings(Analyser & analyser, Turn const& turn)\n        {\n            segment_identifier const& seg_id = turn.operations[OpId].seg_id;\n\n            signed_index_type\n                count = boost::numeric_cast<signed_index_type>(\n                            geometry::num_interior_rings(\n                                detail::single_geometry(analyser.geometry, seg_id)));\n            \n            for_no_turns_rings(analyser, turn, seg_id.ring_index + 1, count);\n        }\n\n        template <typename Analyser, typename Turn>\n        static inline void for_no_turns_rings(Analyser & analyser,\n                                              Turn const& turn,\n                                              signed_index_type first,\n                                              signed_index_type last)\n        {\n            segment_identifier seg_id = turn.operations[OpId].seg_id;\n\n            for ( seg_id.ring_index = first ; seg_id.ring_index < last ; ++seg_id.ring_index )\n            {\n                analyser.no_turns(seg_id);\n            }\n        }\n    };\n};\n\n}} // namespace detail::relate\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_AREAL_AREAL_HPP\n", "meta": {"hexsha": "2859841de416374a19b13752ab7a263a509ab048", "size": 30885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/algorithms/detail/relate/areal_areal.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": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T19:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T19:18:58.000Z", "max_issues_repo_path": "deps/cinder/include/boost/geometry/algorithms/detail/relate/areal_areal.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": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-14T07:38:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T04:22:10.000Z", "max_forks_repo_path": "deps/cinder/include/boost/geometry/algorithms/detail/relate/areal_areal.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": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-01-27T22:36:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T12:00:36.000Z", "avg_line_length": 37.3910411622, "max_line_length": 119, "alphanum_fraction": 0.5326533916, "num_tokens": 6501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.033589507826800535, "lm_q1q2_score": 0.012929009489773663}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#include <cmath>\n#include <fstream>\n#include <algorithm>\n#include <functional>\n#include <boost/format.hpp>\n#include \"basic_tree.hpp\"\n#include \"cond_likelihood.hpp\"\n#include \"cond_likelihood_storage.hpp\"\n#include \"tip_data.hpp\"\n#include \"sim_data.hpp\"\n#include \"phycas_string.hpp\"\n\nconst int8_t phycas::SimData::missing_state = -1;\t// GCC 3.2.3 (Red Hat Linux 3.2.3-20) requires initializing here rather than in header\nusing std::exp;\n\nclass LookupStateSymbol : public std::unary_function<int8_t, char>\n\t{\n\tpublic:\n\t\tLookupStateSymbol(const std::vector<std::string> & state_symbols) : symbols(state_symbols) {}\n\n\t\tchar operator()(int8_t i)\n\t\t\t{\n\t\t\tPHYCAS_ASSERT((unsigned)i < (unsigned)symbols.size());\n\t\t\treturn symbols[i][0];\n\t\t\t}\n\n\tprivate:\n\t\tconst std::vector<std::string> & symbols;\n\t};\n\nnamespace phycas\n{\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the vector of counts (`binv') that is created in the calctBinned function. The table below shows the\n|   identity of each bin for the case of 4 states. The length of `binv' is 2k - 1, where k is the number of states.\n|   The number of states can thus be obtained as (sz + 1)/2, where sz is the length of `binv'.\n|>\n|\tCount   Bin description\n|   ----------------------------------------\n|\tn_0     all patterns containing only A\n|\tn_1     all patterns containing only C\n|\tn_2     all patterns containing only G\n|\tn_3     all patterns containing only T\n|\tn_4     patterns containing any 2 states\n|\tn_5     patterns containing any 3 states\n|\tn_6     patterns containing any 4 states\n|   ----------------------------------------\n|>\n*/\nstd::vector<double> SimData::getBinnedCounts()\n\t{\n    if (binv.empty())\n        {\n        std::cerr << \"Doh!\" << std::endl;\n        }\n    PHYCAS_ASSERT(!binv.empty());\n\n    return binv;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|   Builds up the `binv' vector by classifying stored site patterns into the following categories (bins):\n|>\n|\tCount   Bin description\n|   ----------------------------------------\n|\tn_0     all patterns containing only A\n|\tn_1     all patterns containing only C\n|\tn_2     all patterns containing only G\n|\tn_3     all patterns containing only T\n|\tn_4     patterns containing any 2 states\n|\tn_5     patterns containing any 3 states\n|\tn_6     patterns containing any 4 states\n|   ----------------------------------------\n|>\n|\tWarning: this function currently assumes no missing data! A missing state is treated as if it were one of the\n|\tother states in the pattern. For example, the count for the pattern 'AAACA?GAA' would be stuffed into the 3-state\n|\tbin, with the implicit assumption being that the ? equals either A, C or G.\n*/\nvoid SimData::buildBinVector(\n  //unsigned nstates,   /**< is the number of states */ //POLOLD\n  unsigned nstates,   /**< is the number of states */\n  bool minbins)     /**< if true, minimum number of bins will be used; if false, a bin will be created for every permutation of every possible subset of states */\n\t{\n\tPHYCAS_ASSERT(nstates == 4);    // Currently assumes DNA or RNA sequence data\n\tunsigned nbins = 0;\n    if (minbins)\n        nbins = 7;\n    else\n        nbins = 15;\n\n    binv.clear();\n\tbinv.resize(nbins, 0.0);\n\tstd::set<int8_t> state_set;\n\n    std::vector<bool> seen(4, false);\n\n    // pattern_map_t associates int8_vect_t keys (pattern) with double values (count)\n\tfor (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n\t\t{\n\t\tconst int8_vect_t & p = it->first;\n\n        seen.assign(4, false);\n\n        // For this pattern, count distinct states by creating a set\n\t\tstate_set.clear();\n\t\tunsigned last_state = UINT_MAX;\n\t\tfor (int8_vect_t::const_iterator pit = p.begin(); pit != p.end(); ++pit)\n\t\t\t{\n\t\t\tint8_t curr_state = *pit;\n\t\t\tint cs = (int)curr_state;\n\t\t\tif (cs >= 0 && cs < (int)nstates)\n\t\t\t\t{\n\t\t\t\t// state is not a gap (-1), missing (nstates), or an ambiguity code (> nstates), so add to set\n\t\t\t\tstate_set.insert(curr_state);\n\t\t\t\tlast_state = cs;\n\n                seen[cs] = true;\n\t\t\t\t}\n\t\t\t}\n\t\tunsigned sz = (unsigned)state_set.size();\n\t\tPHYCAS_ASSERT(sz > 0);\n\t\tPHYCAS_ASSERT(sz <= nstates);\n\n\t\tdouble this_count = (double)(it->second);\n\t\tif (sz == 1)\n\t\t\t{\n\t\t\t// pattern had only one state, so add pattern count to appropriate constant site bin\n\t\t\tbinv[last_state] += this_count;\n\t\t\t}\n\t\telse if (minbins)\n\t\t\t{\n\t\t\t// pattern had sz states, so add pattern count to appropriate variable site bin\n\t\t\tbinv[nstates + sz - 2] += this_count;\n\t\t\t}\n        else\n            {\n            // sz > 1 and not minbins, so need to use composition of state_set to determine bin index\n            if (sz == 2)\n                {\n                if (seen[0] && seen[1])\n                    binv[4] += this_count;\n                else if (seen[0] && seen[2])\n                    binv[5] += this_count;\n                else if (seen[0] && seen[3])\n                    binv[6] += this_count;\n                else if (seen[1] && seen[2])\n                    binv[7] += this_count;\n                else if (seen[1] && seen[3])\n                    binv[8] += this_count;\n                else if (seen[2] && seen[3])\n                    binv[9] += this_count;\n                else\n                    PHYCAS_ASSERT(0);\n                }\n            else if (sz == 3)\n                {\n                if (seen[0] && seen[1] && seen[2])\n                    binv[10] += this_count;\n                else if (seen[0] && seen[1] && seen[3])\n                    binv[11] += this_count;\n                else if (seen[0] && seen[2] && seen[3])\n                    binv[12] += this_count;\n                else if (seen[1] && seen[2] && seen[3])\n                    binv[13] += this_count;\n                else\n                    PHYCAS_ASSERT(0);\n                }\n            else\n                {\n                PHYCAS_ASSERT(sz == 4);\n                binv[14] += this_count;\n                }\n\n            }\n\n\t\t}\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCalculates the binned t function used in the Gelfand-Ghosh measure for the patterns currently stored in this\n|\tobject. The binned t function looks like this for multinomial data, 4 DNA states and 4 taxa:\n|>\n|\tCount   Bin description                     t calculation\n|   ----------------------------------------------------------------------------------------------\n|\tn_0     all patterns containing only A      t_0 = (n_0 + eps)/(n + 1) log[(n_0 + eps)/(n + 1)]\n|\tn_1     all patterns containing only C      t_1 = (n_1 + eps)/(n + 1) log[(n_1 + eps)/(n + 1)]\n|\tn_2     all patterns containing only G      t_2 = (n_2 + eps)/(n + 1) log[(n_2 + eps)/(n + 1)]\n|\tn_3     all patterns containing only T      t_3 = (n_3 + eps)/(n + 1) log[(n_3 + eps)/(n + 1)]\n|\tn_4     patterns containing any 2 states    t_4 = (n_4 + eps)/(n + 1) log[(n_4 + eps)/(n + 1)]\n|\tn_5     patterns containing any 3 states    t_5 = (n_5 + eps)/(n + 1) log[(n_5 + eps)/(n + 1)]\n|\tn_6     patterns containing any 4 states    t_6 = (n_6 + eps)/(n + 1) log[(n_6 + eps)/(n + 1)]\n|   ----------------------------------------------------------------------------------------------\n|   n = n_0 + n_1 + ... + n_6                   t = t_0 + t_1 + ... + t_6\n|>\n|\twhere n_i is the count of the number of characters placed into bin i, n is the total number of characters, and\n|\teps equals 1/7 (the inverse of the total number of bins). The total number of bins is (2*nstates - 1), regardless\n|\tof the number of taxa, which allows this approach to Gelfand-Ghosh to scale nicely to large problems. The drawback,\n|\tof course, is that information about frequencies of individual rare patterns is not used.\n|\n|\tWarning: this function currently assumes no missing data! A missing state is treated as if it were one of the\n|\tother states in the pattern. For example, the count for the pattern 'AAACA?GAA' would be stuffed into the 3-state\n|\tbin, with the implicit assumption being that the ? equals either A, C or G.\n*/\ndouble SimData::calctBinned(\n  unsigned nstates, /**< is the number of states */\n  bool minbins)     /**< if true, minimum number of bins will be used; if false, a bin will be created for every permutation of every possible subset of states */\n\t{\n\tPHYCAS_ASSERT(nstates == 4);    // Currently assumes DNA or RNA sequence data\n\n\t// m is the number of distinct patterns\n\t//double m\t\t\t\t\t= (double)sim_pattern_map.size();\n\n\t// s is the number of character states\n\t//double s\t\t\t\t\t= (double)nstates;\n\t//double log_s\t\t\t\t= std::log(s);\n\n\t// n is the number of characters (i.e. sum of counts of all distinct patterns)\n\tdouble n\t\t\t\t\t= (double)total_count;\n\tdouble n_plus_one\t\t\t= n + 1.0;\n\tdouble log_n_plus_one\t\t= std::log(n_plus_one);\n\n    unsigned nbins = 0;\n    if (minbins)\n        nbins = 7;\n    else\n        nbins = 15;\n\n\t// epsilon is the number of bins (nstates constant bins plus nstates - 1 additional bins for patterns with 2, 3, ..., nstates states)\n\tdouble epsilon\t\t\t\t= 1.0/(double)nbins;\n\n\t// classify patterns and build up bin, the vector of bin counts\n    buildBinVector(nstates, minbins);\n\n\t// now accumulate t by summing over bins\n\tdouble t = 0.0;\n\tfor (std::vector<double>::iterator vit = binv.begin(); vit != binv.end(); ++vit)\n\t\t{\n\t\tdouble count\t\t\t\t= (*vit);\n\t\tdouble count_plus_epsilon\t= count + epsilon;\n\t\tdouble first\t\t\t\t= count_plus_epsilon;\n\t\tdouble second\t\t\t\t= std::log(count_plus_epsilon);\n\t\tdouble this_term\t\t\t= first*second;\n\t\tt += this_term;\n\t\t}\n    t /= n_plus_one;\n    t -= log_n_plus_one;\n\n\treturn t;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCalculates the t function used in the Gelfand-Ghosh measure for the patterns currently stored in this object. The\n|\tt function looks like this for multinomial data and 4 taxa:\n|>\n|\tsum_{i=1}^{256} (x_i + eps)/(n + 1) log[(x_i + eps)/(n + 1)]\n|>\n|\twhere 256 is the total number of possible data patterns (=nstates^ntaxa), x_i is the count of the number of\n|\tcharacters having pattern i, n is the total number of characters, and eps equals 1/256 (the inverse of the total\n|\tnumber of possible patterns).\n*/\ndouble SimData::calct(\n  unsigned nstates) /**< is the number of states */\n\t{\n\t// m is the number of distinct patterns\n\tdouble m\t\t\t\t\t= (double)sim_pattern_map.size();\n\t//unused:  double log_m\t\t\t\t= std::log(m);\n\n\t// s is the number of character states\n\tdouble s\t\t\t\t\t= (double)nstates;\n\tdouble log_s\t\t\t\t= std::log(s);\n\n\t// n is the number of characters (i.e. sum of counts of all distinct patterns)\n\tdouble n\t\t\t\t\t= (double)total_count;\n\n\tdouble n_plus_one\t\t\t= n + 1.0;\n\tdouble log_n_plus_one\t\t= std::log(n_plus_one);\n\n\t// ntaxa is the number of taxa in the tree\n\tdouble ntaxa\t\t\t\t= (double)pattern_length;\n\tdouble ntaxa_times_log_s\t= ntaxa*log_s;\n\n\t// epsilon is the inverse of the total number of possible patterns\n\tdouble epsilon\t\t\t\t= std::exp(-ntaxa_times_log_s);\n\n\t// added_on is the sum of all terms in t in which the pattern count equals zero\n\tdouble log_term\t\t\t\t= -ntaxa_times_log_s - log_n_plus_one;\n\tdouble added_on\t\t\t\t= (1.0 - m*epsilon)*log_term/n_plus_one;\n\n\t// now compute the sum of all terms in t in which the pattern count is greater than zero\n\tdouble sum\t\t\t\t\t= 0.0;\n\tfor (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n\t\t{\n\t\tdouble count\t\t\t\t= (double)it->second;\n\t\tdouble count_plus_epsilon\t= count + epsilon;\n\t\tdouble first\t\t\t\t= count_plus_epsilon/n_plus_one;\n\t\tdouble second\t\t\t\t= std::log(count_plus_epsilon) - log_n_plus_one;\n\t\tdouble this_term\t\t\t= first*second;\n\t\tsum += this_term;\n\t\t}\n\n\tdouble t = sum + added_on;\n\n\treturn t;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns simulated data stored in `sim_pattern_map' as a string in the form of a two-column table. The first column\n|\tis labeled \"Count\" and the second is labeled \"Pattern\". The Count column shows the number of times its associated\n|\tpattern was inserted using the insertPattern function. The Pattern column shows a representation of the pattern\n|\titself, using symbols for states provided in the `state_symbols' argument. The `state_symbols' argument should be\n|\ta vector of single-character strings supplying a symbol to represent each state that might show up in any pattern.\n|\tAssumes that no state in any pattern stored in `sim_pattern_map' is greater than or equal to the length of the\n|\t`state_symbols' vector (because states are used as indices into `state_symbols').\n*/\nstd::string SimData::patternTable(\n  const StringVect & state_symbols) /**< is a vector of strings representing states (e.g. {\"A\", \"C\", \"G\", \"T\"}). Note that each state symbol should be a string of length 1 (i.e. a single character) */\n\t{\n\tPHYCAS_ASSERT(state_symbols.size() > 0);\n\n\toutstr.clear();\n\n\tif (sim_pattern_map.empty())\n\t\t{\n\t\toutstr = \"Sorry, no patterns are stored\";\n\t\t}\n\telse\n\t\t{\n\t\toutstr = \"     Count  Pattern\";\n\n\t\tfor (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n\t\t\t{\n\t\t\t// Output the count first\n\t\t\toutstr << str(boost::format(\"\\n%10.1f\") % it->second) << \"  \";\n\n\t\t\t// Now output the pattern\n\t\t\tstd::transform(it->first.begin(), it->first.end(), std::back_inserter(outstr), LookupStateSymbol(state_symbols));\n\t\t\t}\n\t\t}\n\treturn outstr;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns row `i' of `sim_pattern_vect' as a vector. Returns vector by value.\n*/\nstd::vector<unsigned> SimData::getPatternVectRow(\n  unsigned i) const\n    {\n    unsigned nchar = (unsigned)sim_pattern_vect.size();\n    std::vector<unsigned> v(nchar, 5);\n    for (unsigned k = 0; k < nchar; ++k)\n        v[k] = (unsigned)sim_pattern_vect[k][i];\n    return v;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSaves simulated data stored in `sim_pattern_map' to a file named `filename'. If the file already exists, it will be\n|\toverwritten without warning. If the file does not yet exist, it will be created. The file written will be a valid\n|\tNEXUS data file suitable for executing in phylogenetic analysis software that reads the NEXUS file format. The\n|\tsupplied `taxon_names' will be used in the matrix command of the NEXUS file to specify the names of the taxa.\n|\tAssumes that the number of elements in `taxon_names' equals `pattern_length'. The `datatype' argument should be the\n|\tcorrect NEXUS datatype (e.g. \"dna\", \"standard\") for the data simulated. The symbols used for the states are\n|\tsupplied in the `state_symbols' vector. Each element of this vector should be a single-character string. Assumes\n|\tthat no state in any pattern stored in `sim_pattern_map' is greater than or equal to the length of the\n|\t`state_symbols' vector (because states are used as indices into `state_symbols').\n*/\nvoid SimData::saveToNexusFile(\n  const std::string filename,\t\t\t/**< is the name of the file to create containing the simulated data stored in this object */\n  const StringVect & taxon_names,\t\t/**< is a vector containing the taxon names to use in the saved file */\n  const std::string datatype,\t\t\t/**< is a string to be used as the NEXUS datatype (e.g. \"dna\" or \"standard\") */\n  const StringVect & state_symbols)\t\t/**< is a vector of strings representing states (e.g. {\"A\", \"C\", \"G\", \"T\"}). Note that each state symbol should be a string of length 1 (i.e. a single character) */\n\t{\n\t//std::cerr << \"taxon_names size = \" << taxon_names.size() << std::endl;\n\t//std::cerr << \"pattern_length   = \" << pattern_length << std::endl;\n\t//std::cerr << \"taxon_names: |\";\n\t//std::copy(taxon_names.begin(), taxon_names.end(), std::ostream_iterator<std::string>(std::cerr, \"|\"));\n\n\tPHYCAS_ASSERT(state_symbols.size() > 0);\n\tPHYCAS_ASSERT(taxon_names.size() == pattern_length);\n\n\t// Find length of longest string in taxon_names vector; this is used later for formatting purposes\n\t// The 2 is included in case apostrophes are needed when taxon names are output in the matrix command\n\tunsigned length_of_longest_name = 2 + (unsigned)std::max_element(taxon_names.begin(), taxon_names.end(), StringLengthLess())->length();\n\n\tstd::ofstream outf(filename.c_str());\n\n\toutf << \"#nexus\" << \"\\n\\n\";\n\toutf << \"begin data;\" << \"\\n\";\n\toutf << str(boost::format(\"  dimensions ntax=%d nchar=%d;\") % pattern_length % (unsigned)total_count) << \"\\n\";\n\toutf << \"  format datatype=\" << datatype << \";\" << \"\\n\";\n\toutf << \"  matrix\" << \"\\n\";\n\n\t// Create a format string to use with boost::format that left-justifies (the \"-\" flag) the\n\t// taxon names in a field of width length_of_longest_name\n\tstd::string fmtstr = str(boost::format(\"    %%-%ds\") % length_of_longest_name);\n\n\tfor (unsigned i = 0; i < pattern_length; ++i)\n\t\t{\n\t\tif (taxon_names[i].find(' ') != std::string::npos)\n\t\t\t{\n\t\t\tstd::string s = \"'\";\n\t\t\ts += taxon_names[i];\n\t\t\ts += \"'\";\n\t\t\toutf << str(boost::format(fmtstr) % s) << \"  \";\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\toutf << str(boost::format(fmtstr) % taxon_names[i]) << \"  \";\n\t\t\t}\n\n#if 1\n        // Spit out characters in the order in which they were simulated. While this is a nice feature,\n        // it currently requires storing the data twice (sim_pattern_vect and sim_pattern_map)\n        unsigned nchar = (unsigned)sim_pattern_vect.size();\n        for (unsigned k = 0; k < nchar; ++k)\n            {\n            unsigned j = (unsigned)sim_pattern_vect[k][i];\n            char s = state_symbols[j][0];\n            outf << s;\n            }\n#else\n\t\tfor (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n\t\t\t{\n\t\t\t// The first member of it is the state, which must be converted from its coded form\n\t\t\t// to the standard symbol for this data type (e.g. A, C, G or T for DNA characters)\n\t\t\tint8_t j = (*it).first[i];\n\n\t\t\tPHYCAS_ASSERT(j < (int8_t)state_symbols.size());\n\t\t\tchar s = state_symbols[j][0];\t// use the first (and hopefully only) character in the string at position j\n\n\t\t\t// The second member of it is the pattern count\n\t\t\tunsigned n = (unsigned)it->second;\t//@POL assuming counts not fractional\n\t\t\tfor (unsigned k = 0; k < n; ++k)\n\t\t\t\t{\n\t\t\t\toutf << s;\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\toutf << \"\\n\";\n\t\t}\n\n\toutf << \"  ;\" << \"\\n\";\n\toutf << \"end;\" << \"\\n\";\n\n\toutf.close();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAdds `tmp_pattern' to `sim_pattern_map'. Increments total_count to reflect the new total number of counts over all\n|   patterns. After calling, you should pass `missing_state' to the wipePattern() function to fill `tmp_pattern' with\n|   invalid values. Unlike insertPattern, insertPatternOnly does not add site indices to `pattern_to_sites_map' and does\n|   not add `tmp_pattern' to `sim_pattern_vect', so only use this function if you do not care to keep track of the\n|   order in which sites were simulated.\n*/\nvoid SimData::insertPatternOnly(\n  pattern_count_t count)\t/**< is the count to be associated with the pattern now stored in `tmp_pattern' */\n\t{\n\t// insert the pattern stored in tmp_pattern into sim_pattern_map\n\t// Add tmp_pattern to sim_pattern_map if it has not yet been seen, otherwise increment the count\n\t// for this pattern if it is already in the map (see item 24, p. 110, in Meyers' Efficient STL)\n\tpattern_map_t::iterator lowb = sim_pattern_map.lower_bound(tmp_pattern);\n\tif (lowb != sim_pattern_map.end() && !(sim_pattern_map.key_comp()(tmp_pattern, lowb->first)))\n\t\t{\n\t\t// Pattern is already in sim_pattern_map, so just modify its count\n\t\tlowb->second += count;\n\t\t}\n\telse\n\t\t{\n\t\t// tmp_pattern has not yet been stored in sim_pattern_map\n\t\tsim_pattern_map.insert(lowb, pattern_map_t::value_type(tmp_pattern, count));\n\t\t}\n\n    total_count += count;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAdds `tmp_pattern' to `sim_pattern_map'. Increments total_count to reflect the new total number of counts over all\n|   patterns. After calling, you should pass `missing_state' to the wipePattern() function to fill `tmp_pattern' with\n|   invalid values.\n*/\nvoid SimData::insertPattern(\n  const uint_vect_t & sitelist, /**< is a list of site indices corresponding to the current pattern */  //UINT_LIST\n  pattern_count_t count)\t/**< is the count to be associated with the pattern now stored in `tmp_pattern' */\n\t{\n\t// Insert the pattern stored in tmp_pattern into sim_pattern_map\n\t// Add tmp_pattern to sim_pattern_map if it has not yet been seen, otherwise increment the count\n\t// for this pattern if it is already in the map (see item 24, p. 110, in Meyers' Efficient STL)\n\tpattern_map_t::iterator lowb = sim_pattern_map.lower_bound(tmp_pattern);\n\tif (lowb != sim_pattern_map.end() && !(sim_pattern_map.key_comp()(tmp_pattern, lowb->first)))\n\t\t{\n\t\t// Pattern is already in sim_pattern_map, so just modify its count\n\t\tlowb->second += count;\n\t\t}\n\telse\n\t\t{\n\t\t// tmp_pattern has not yet been stored in sim_pattern_map\n\t\tsim_pattern_map.insert(lowb, pattern_map_t::value_type(tmp_pattern, count));\n\t\t}\n\n\t// Insert the supplied sitelist into pattern_to_sites_map\n\tpattern_to_sites_map_t::iterator lowbb = pattern_to_sites_map.lower_bound(tmp_pattern);\n\tif (lowbb != pattern_to_sites_map.end() && !(pattern_to_sites_map.key_comp()(tmp_pattern, lowbb->first)))\n\t\t{\n\t\t// Pattern is already in pattern_to_sites_map, so just modify the existing list\n\t\tuint_vect_t & existing_sitelist = lowbb->second;//UINT_LIST\n        unsigned existing_nsites = (unsigned)existing_sitelist.size();\n        unsigned additional_sites = (unsigned)sitelist.size();\n        existing_sitelist.resize(existing_nsites + additional_sites);\n\t\tstd::copy(sitelist.begin(), sitelist.end(), std::back_inserter(existing_sitelist));\n        }\n\telse\n\t\t{\n\t\t// tmp_pattern has not yet been stored in pattern_to_sites_map\n\t\tpattern_to_sites_map.insert(lowbb, pattern_to_sites_map_t::value_type(tmp_pattern, sitelist));\n\t\t}\n\n    // Insert tmp_pattern into sim_pattern_vect at every position listed in sitelist vector (usually of length one)\n    for (uint_vect_t::const_iterator i = sitelist.begin(); i != sitelist.end(); ++i)\n        {\n        unsigned pos = (unsigned)(*i);\n        PHYCAS_ASSERT(sim_pattern_vect.size() > pos);\n        sim_pattern_vect[pos] = tmp_pattern;\n        total_count += count;\n        }\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAdds data currently stored in `sim_pattern_map' to the patterns already in `other'. The value of `mult' is used to\n|\tmodify the counts before they are added to `other'; that is, the count of each pattern added to `other' is the\n|\toriginal count multiplied by `mult'. Normally, `mult' would be specified to be 1.0, but in some cases it is\n|\tnecessary to build up SimData objects that represent averages of other SimData objects, and it is these situations\n|\twhere `mult' comes in handy. Assumes that `mult' is positive and non-zero. Assumes that `pattern_length' for this\n|   SimData object is identical to the `pattern_length' of `other'.\n*/\nvoid SimData::addDataTo(\n  SimData & other, \t\t\t/**< is the SimData object that will receive the data currently contained in this SimData object */\n  pattern_count_t mult)\t\t/**< is the factor multiplied by each pattern's count before pattern is stored in `other' */\n\t{\n\tPHYCAS_ASSERT(mult > 0.0);\n\n\t// If this object has no patterns, return immediately\n\tif (total_count == 0.0)\n\t\treturn;\n\n\t// If other is empty, then it most likely needs to be initialized\n\tif (other.getTotalCount() == 0)\n\t\t{\n\t\tother.resetPatternLength(pattern_length);\n\t\t}\n\tPHYCAS_ASSERT(pattern_length == other.getPatternLength());\n\n    pattern_map_t::iterator pit = sim_pattern_map.begin();\n\tfor (; pit != sim_pattern_map.end(); ++pit)\n\t\t{\n\t\tpattern_count_t count = pit->second;\n\n\t\t// getCurrPattern returns a workspace for building up a pattern to be added to other\n\t\tint8_vect_t & other_pattern = other.getCurrPattern();\n\n\t\t// Copy pattern represented by *it to other's workspace\n\t\tstd::copy(pit->first.begin(), pit->first.end(), other_pattern.begin());\n\n\t\t// Add the pattern in other's workspace to other's pattern map\n\t\tpattern_count_t mult_count = mult*count;\n\n\t\tother.insertPatternOnly(mult_count);\n\t\t}\n    //#endif\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets `total_count' and `pattern_length' both to zero.\n*/\nSimData::SimData()\n  : pattern_length(0), total_count(0.0)\n    , _nchar(0)\n    {\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tResets this object to its just-constructed state.\n*/\nvoid SimData::clear()\n    {\n    tmp_pattern.clear();\n    sim_pattern_map.clear();\n    total_count = 0.0;\n    pattern_length = 0;\n    sim_pattern_vect.clear();\n    pattern_to_sites_map.clear();\n    sim_pattern_vect.resize(_nchar);\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tResizes sim_pattern_vect to the supplied length.\n*/\nvoid SimData::resizePatternVect(\n  unsigned sz)  /**< new size of sim_pattern_vect vector */\n    {\n    sim_pattern_vect.resize(sz);\n    _nchar = sz;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns a const reference to the data member `sim_pattern_map'.\n*/\nconst pattern_map_t & SimData::getSimPatternMap() const\n    {\n    return sim_pattern_map;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns a reference to the data member `pattern_to_sites_map'.\n*/\npattern_to_sites_map_t & SimData::getPatternToSitesMap()\n    {\n    return pattern_to_sites_map;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tIf `ntaxa' equals `pattern_length', this function returns immediately without taking any action. If `ntaxa' differs\n|\tfrom `pattern_length', sets `pattern_length' to `ntaxa' and clears `sim_pattern_map' because it is invalidated when\n|\t`pattern_length' changes. Also refreshes the `tmp_pattern' data member to conform to the new value of\n|\t`pattern_length'. Assumes `ntaxa' is non-zero. Use clear() to set `ntaxa' to 0 and return the object to its\n|\tjust-constructed state.\n*/\nvoid SimData::resetPatternLength(\n  unsigned ntaxa)\t/**< is the number of taxa (same as the number of elements in a pattern vector) */\n    {\n    PHYCAS_ASSERT(ntaxa > 0);\n    if (ntaxa == pattern_length)\n        return;\n\n    clear();\n    pattern_length = ntaxa;\n\n    // Create a int8_vect_t vector with ntaxa elements all of which are -1\n    // and swap into tmp_pattern so that tmp_pattern now has the correct size\n    pattern_t v(ntaxa, missing_state);\t// GCC 3.2.3 (Red Hat Linux 3.2.3-20) requires this split\n    tmp_pattern.swap(v);\t\t\t\t\t// into two lines\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets every element in `tmp_pattern' to the value of `missing_state'.\n*/\nvoid SimData::wipePattern()\n    {\n    tmp_pattern.assign((pattern_t::size_type)pattern_length, SimData::missing_state);\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets all counts in `sim_pattern_map' to zero.\n*/\nvoid SimData::zeroCounts()\n    {\n    for (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n        {\n        it->second = 0.0;\n        }\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSaves all counts as a tab-delimited row appended to the file whose name is 'fn'. Note: no header is output\n|\tidentifying which pattern goes with each count, so this will not be useful unless only the unidentified counts are\n|\tof interest.\n*/\nvoid SimData::appendCountsToFile(\n  std::string fn,   /**< is the name of the file to which counts will be appended */\n  bool binary)      /**< if true, any non-zero counts will be output as 1 */\n    {\n    std::ofstream outf(fn.c_str(), std::ios::out | std::ios::app);\n    pattern_map_t::iterator it = sim_pattern_map.begin();\n    unsigned count = (unsigned)(it->second);\n    if (binary && count > 0)\n        count = 1;\n    outf << count;\n    ++it;\n    for (; it != sim_pattern_map.end(); ++it)\n    {\n        count = (unsigned)(it->second);\n        if (binary && count > 0)\n            count = 1;\n        outf << '\\t' << count;\n    }\n    outf << std::endl;\n    outf.close();\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSaves all counts as a tab-delimited row appended to the file whose name is 'fn'. Note: no header is output\n|\tidentifying which pattern goes with each count, so this will not be useful unless only the unidentified counts are\n|\tof interest.\n*/\nvoid SimData::debugAppendCountsToFile(\n  std::string row_name,     /**< is the name of the row, which is output before any counts */\n  std::string fn)           /**< is the name of the file to which counts will be appended */\n    {\n    std::ofstream outf(fn.c_str(), std::ios::out | std::ios::app);\n    outf << row_name;\n\n#if 0\n\n    for (unsigned i = 0; i < 4; ++i)\n        {\n        for (unsigned j = 0; j < 4; ++j)\n            {\n            for (unsigned k = 0; k < 4; ++k)\n                {\n                for (unsigned m = 0; m < 4; ++m)\n                    {\n                    int8_vect_t v;\n                    v.push_back(i);\n                    v.push_back(j);\n                    v.push_back(k);\n                    v.push_back(m);\n                    pattern_map_t::iterator it = sim_pattern_map.find(v);\n                    PatternCountType count = 0.0;\n                    if (it != sim_pattern_map.end())\n                        {\n                        count = (PatternCountType)(it->second);\n                        }\n                    outf << '\\t' << count;\n                    }\n                }\n            }\n        }\n\n#else\n\n    pattern_map_t::iterator it = sim_pattern_map.begin();\n    pattern_count_t count = (pattern_count_t)(it->second);\n    outf << count;\n    ++it;\n    for (; it != sim_pattern_map.end(); ++it)\n        {\n        count = (pattern_count_t)(it->second);\n        outf << '\\t' << count;\n        }\n\n#endif\n\n    outf << std::endl;\n    outf.close();\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns a vector of patterns, each represented as a string. The patterns are in the same order as the counts\n|\treturned by the appendCountsToFile function, so this function can be used to identify the patterns belonging to the\n|\tpattern counts returned by that function. This is a slow function, so don't use it in situations where speed is\n|\tcritical.\n*/\nstd::vector<std::string> SimData::getPatterns(\n  std::vector<std::string> symbols) /**< is a vector of state symbols */\n    {\n    std::vector<std::string> v;\n    for (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n        {\n        // Create a string out of the pattern\n        std::string s;\n        for (pattern_t::const_iterator i = it->first.begin(); i != it->first.end(); ++i)\n            {\n            s += symbols.at(*i);\n            }\n        v.push_back(s);\n        }\n    return v;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSaves all counts as a string that can be used within Maple to create a 3D surface plot. To make a surface plot of\n|\tthe following 2x3 matrix in Maple 9,\n|>\n|\t1  2  3\n|\t4  6  8\n|>\n|\tplace the following commands in a file named maple_commands:\n|>\n|\twith(linalg);\n|\twith(plots);\n|\tpoints := [[[0,0,1],[0,1,2],[0,2,3]],[[1,0,4],[1,1,6],[1,2,8]]];\n|\tsurfdata(points, axes=framed, labels=[\"rows\", \"cols\", \"height\"]);\n|>\n|\tthen read this file by typing 'read maple_commands;' in the Maple interpreter. In our case, rows will be separate\n|\tposterior predictive data sets and columns will be patterns (256 columns for 4 taxa and DNA data). The height\n|\twill be the number of counts. This function returns a string representing one row of the points matrix. For\n|\texample, if this data set were going to be the 2nd row (index 1) in the above example, the string returned would be\n|>\n|\t[[1,0,4],[1,1,5],[1,2,6]]\n|>\n|\n*/\nstd::string SimData::createMapleTuples(\n  unsigned row,         /**< is the row */\n  unsigned cutoff)      /**< is the cutoff */\n    {\n    bool use_cutoff = true;\n    if (cutoff == 0)\n        use_cutoff = false;\n\n    std::string s = \"[\";\n    unsigned col = 0;\n    pattern_map_t::iterator it = sim_pattern_map.begin();\n    unsigned count = (unsigned)(it->second);\n    if (use_cutoff && count > cutoff)\n        count = 0;\n    double log_count = count > 0 ? std::log((double)count) : 0.0;\n    s += str(boost::format(\"[%d,%d,%f]\") % row % col % log_count);\n    ++it;\n    ++col;\n    for (; it != sim_pattern_map.end(); ++it, ++col)\n        {\n        count = (unsigned)(it->second);\n        if (use_cutoff && count > cutoff)\n            count = 0;\n        log_count = count > 0 ? std::log((double)count) : 0.0;\n        s += str(boost::format(\",[%d,%d,%f]\") % row % col % log_count);\n        }\n    s += \"]\";\n    return s;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets `tmp_pattern'[`pos'] to the supplied `state'.\n*/\nvoid SimData::setState(\n  unsigned pos, \t/**< is the position in `tmp_pattern' to set */\n  int8_t state)\t\t/**< is the state to assign to the element in `tmp_pattern' at position pos */\n    {\n    PHYCAS_ASSERT(pos < pattern_length);\n    tmp_pattern[pos] = state;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns a reference to the `tmp_pattern' data member.\n*/\npattern_t & SimData::getCurrPattern()\n    {\n    return tmp_pattern;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the value of the `pattern_length' data member.\n*/\nunsigned SimData::getPatternLength()\n    {\n    return pattern_length;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the value of the `total_count' data member, which represents the total number of patterns added (not\n|\t`sim_pattern_map'.size()).\n*/\npattern_count_t SimData::getTotalCount()\n    {\n    return total_count;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets the value of the `total_count' data member, which represents the sum of all pattern counts (not\n|\t`sim_pattern_map'.size()).\n*/\nvoid SimData::setTotalCount(\n  pattern_count_t total)\t/**< is the new total count */\n    {\n    total_count = total;\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the value `sim_pattern_map'.size(), the number of unique patterns currently stored.\n*/\nunsigned SimData::getNUniquePatterns()\n    {\n    return (unsigned)sim_pattern_map.size();\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tDivides the count associated with every pattern in `sim_pattern_map' by `factor'. Also divides `total_count' by\n|\t`factor'. Assumes `factor' is greater than zero.\n*/\nvoid SimData::divideBy(\n  pattern_count_t factor)   /**< is the factor by which counts will be divided */\n    {\n    PHYCAS_ASSERT(factor > 0.0);\n\n    total_count /= factor;\n\n    for (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n        {\n        it->second /= factor;\n        }\n    }\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tMultiplies the count associated with every pattern in `sim_pattern_map' by `factor'. Also multiplies `total_count'\n|\t`factor'. Assumes `factor' is greater than zero.\n*/\nvoid SimData::multBy(\n  pattern_count_t factor)  /**< is the factor by which counts will be multiplied */\n    {\n    if (sim_pattern_map.empty())\n        return;\n\n    total_count *= factor;\n\n    for (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)\n        {\n        it->second *= factor;\n        }\n    }\n\n}\t// namespace phycas\n", "meta": {"hexsha": "09f089de52d331461807ed42e44a418002500e07", "size": 38571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/sim_data.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/sim_data.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/sim_data.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 41.4296455424, "max_line_length": 201, "alphanum_fraction": 0.5783619818, "num_tokens": 9239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.033589503957117864, "lm_q1q2_score": 0.012929008474290307}}
{"text": "/// @file DeconvolverMultiTermBasisFunction.tcc\n/// @brief Class for a deconvolver based on CLEANing with basis functions.\n/// @details This concrete class defines a deconvolver used to estimate an\n/// image from a residual image, psf optionally using a weights image.\n/// @ingroup Deconvolver\n///\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Tim Cornwell <tim.cornwell@csiro.au>\n///\n\n#include <string>\n#include <askap/AskapLogging.h>\n#include <casacore/casa/aips.h>\n#include <boost/shared_ptr.hpp>\n#include <casacore/casa/Arrays/Array.h>\n#include <casacore/casa/Arrays/Vector.h>\n#include <casacore/casa/Arrays/ArrayMath.h>\n#include <casacore/casa/Arrays/MaskArrMath.h>\n#include <casacore/casa/Arrays/MatrixMath.h>\n#include <casacore/scimath/Mathematics/MatrixMathLA.h>\n#include <measurementequation/SynthesisParamsHelper.h>\n#include <profile/AskapProfiler.h>\nASKAP_LOGGER(decmtbflogger, \".deconvolution.multitermbasisfunction\");\n\n#include <deconvolution/DeconvolverMultiTermBasisFunction.h>\n#include <deconvolution/MultiScaleBasisFunction.h>\n\nnamespace askap {\n\n    namespace synthesis {\n\n        /// @brief Class for a deconvolver based on the BasisFunction Clean\n        /// @details This base class defines a deconvolver used to estimate an\n        /// image from a residual image, psf optionally using a weights image.\n        /// The template argument T is the type, and FT is the transform\n        /// e.g. DeconvolverMultiTermBasisFunction<Double, DComplex>\n        /// @ingroup Deconvolver\n\n        template<class T, class FT>\n        DeconvolverMultiTermBasisFunction<T, FT>::DeconvolverMultiTermBasisFunction(Vector<Array<T> >& dirty,\n                Vector<Array<T> >& psf,\n                Vector<Array<T> >& psfLong)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf), itsDirtyChanged(True), itsBasisFunctionChanged(True),\n                itsSolutionType(\"MAXCHISQ\"), itsDecoupled(false), itsDeep(False)\n        {\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"There are \" << this->itsNumberTerms << \" terms to be solved\");\n\n            ASKAPCHECK(psfLong.nelements() == (2*this->itsNumberTerms - 1), \"Long PSF vector has incorrect length \" << psfLong.nelements());\n            this->itsPsfLongVec.resize(2*this->itsNumberTerms - 1);\n\n            for (uInt term = 0; term < (2*this->itsNumberTerms - 1); term++) {\n                ASKAPCHECK(psfLong(term).nonDegenerate().shape().nelements() == 2, \"PSF(\" << term << \") has too many dimensions \" << psfLong(term).shape());\n                this->itsPsfLongVec(term) = psfLong(term).nonDegenerate();\n            }\n\n        };\n\n        template<class T, class FT>\n        DeconvolverMultiTermBasisFunction<T, FT>::DeconvolverMultiTermBasisFunction(Array<T>& dirty,\n                Array<T>& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf), itsDirtyChanged(True), itsBasisFunctionChanged(True),\n                itsSolutionType(\"MAXCHISQ\"), itsDecoupled(false), itsDeep(False)\n        {\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"There is only one term to be solved\");\n            this->itsPsfLongVec.resize(1);\n            this->itsPsfLongVec(0) = psf;\n        };\n\n        template<class T, class FT>\n        DeconvolverMultiTermBasisFunction<T, FT>::~DeconvolverMultiTermBasisFunction()\n        {\n        };\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::setSolutionType(String sol)\n        {\n            itsSolutionType = sol;\n        };\n\n        template<class T, class FT>\n        const String DeconvolverMultiTermBasisFunction<T, FT>::solutionType()\n        {\n            return itsSolutionType;\n        };\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::setDecoupled(Bool decoupled)\n        {\n            itsDecoupled=decoupled;\n        };\n\n        template<class T, class FT>\n        const Bool DeconvolverMultiTermBasisFunction<T, FT>::decoupled()\n        {\n            return itsDecoupled;\n        };\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::setDeepCleanMode(Bool deep)\n        {\n            itsDeep = deep;\n        };\n\n        template<class T, class FT>\n        const Bool DeconvolverMultiTermBasisFunction<T, FT>::deepCleanMode()\n        {\n            return itsDeep;\n        };\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::setBasisFunction(boost::shared_ptr<BasisFunction<T> > bf)\n        {\n            this->itsBasisFunction = bf;\n            this->itsBasisFunctionChanged = True;\n        };\n\n        template<class T, class FT>\n        boost::shared_ptr<BasisFunction<T> > DeconvolverMultiTermBasisFunction<T, FT>::basisFunction()\n        {\n            return itsBasisFunction;\n        };\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::updateDirty(Array<T>& dirty, casa::uInt term)\n        {\n            DeconvolverBase<T, FT>::updateDirty(dirty, term);\n            this->itsDirtyChanged = True;\n        }\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::updateDirty(Vector<Array<T> >& dirtyVec)\n        {\n            DeconvolverBase<T, FT>::updateDirty(dirtyVec);\n            this->itsDirtyChanged = True;\n        }\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::configure(const LOFAR::ParameterSet& parset)\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::configure\");\n            DeconvolverBase<T, FT>::configure(parset);\n\n            // Make the basis function\n            std::vector<float> defaultScales(3);\n            defaultScales[0] = 0.0;\n            defaultScales[1] = 10.0;\n            defaultScales[2] = 30.0;\n            std::vector<float> scales = parset.getFloatVector(\"scales\", defaultScales);\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Constructing Multiscale basis function with scales \"\n                                   << scales);\n            Bool orthogonal = parset.getBool(\"orthogonal\", false);\n            if (orthogonal) {\n                ASKAPLOG_DEBUG_STR(decmtbflogger, \"Multiscale basis functions will be orthogonalised\");\n            }\n            itsBasisFunction = BasisFunction<Float>::ShPtr(new MultiScaleBasisFunction<Float>(scales,\n                               orthogonal));\n\n            String solutionType = parset.getString(\"solutiontype\", \"MAXCHISQ\");\n            Bool  itsDecoupled = parset.getBool(\"decoupled\", false);\n            if (itsDecoupled) {\n                ASKAPLOG_DEBUG_STR(decmtbflogger, \"Using decoupled residuals\");\n            }\n\n            if (solutionType == \"MAXBASE\") {\n                itsSolutionType = solutionType;\n                ASKAPLOG_DEBUG_STR(decmtbflogger, \"Component search to maximise over bases\");\n            } else if (solutionType == \"MAXTERM0\") {\n                itsSolutionType = solutionType;\n                ASKAPLOG_DEBUG_STR(decmtbflogger, \"Component search to maximise Taylor term 0 over bases\");\n            } else {\n                itsSolutionType = \"MAXCHISQ\";\n                ASKAPLOG_DEBUG_STR(decmtbflogger, \"Component search to find maximum in chi-squared\");\n            }\n        }\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::finalise()\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::finalise\");\n            this->updateResiduals(this->itsModel);\n\n            for (uInt base = 0; base < itsTermBaseFlux.nelements(); base++) {\n                for (uInt term = 0; term < itsTermBaseFlux(base).nelements(); term++) {\n                    ASKAPLOG_DEBUG_STR(decmtbflogger, \"   Term(\" << term << \"), Base(\" << base\n                                           << \"): Flux = \" << itsTermBaseFlux(base)(term));\n                }\n            }\n\n        }\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::initialiseForBasisFunction(bool force)\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::initialiseForBasisFunction\");\n            if (!force && !this->itsBasisFunctionChanged) return;\n\n            ASKAPLOG_DEBUG_STR(decmtbflogger,\n                               \"Updating Multi-Term Basis Function deconvolver for change in basis function\");\n\n            IPosition subPsfShape(this->findSubPsfShape());\n\n            // Use a smaller size for the psfs if specified.\n            this->itsBasisFunction->initialise(subPsfShape);\n\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Initialising for PSFs: shape = \" << subPsfShape);\n            initialisePSF();\n\n            itsBasisFunctionChanged = False;\n        }\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::initialise()\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::initialise\");\n            DeconvolverBase<T, FT>::initialise();\n\n            // Initialise residuals\n            initialiseResidual();\n\n            // Initialise masks\n            initialiseMask();\n\n            // Force change in basis function\n            initialiseForBasisFunction(true);\n\n            this->state()->resetInitialObjectiveFunction();\n        }\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::initialiseResidual()\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::initialiseResidual\");\n\n            if (!this->itsDirtyChanged) return;\n\n            // Initialise the basis function for residual calculations.\n            this->itsBasisFunction->initialise(this->dirty(0).shape());\n\n            ASKAPCHECK(this->itsBasisFunction, \"Basis function not initialised\");\n\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Shape of basis functions \"\n                                   << this->itsBasisFunction->basisFunction().shape());\n\n            uInt nBases(this->itsBasisFunction->numberBases());\n\n            itsResidualBasis.resize(nBases);\n            for (uInt base = 0; base < nBases; base++) {\n                itsResidualBasis(base).resize(this->itsNumberTerms);\n            }\n\n            // Calculate residuals convolved with bases [nx,ny][nterms][nbases]\n\n            ASKAPLOG_DEBUG_STR(decmtbflogger,\n                               \"Calculating convolutions of residual images with basis functions\");\n            for (uInt base = 0; base < nBases; base++) {\n                // Calculate transform of residual images [nx,ny,nterms]\n                for (uInt term = 0; term < this->itsNumberTerms; term++) {\n\n                    // Calculate transform of residual image\n                    Matrix<FT> residualFFT(this->dirty(term).shape().nonDegenerate());\n                    residualFFT.set(FT(0.0));\n                    casa::setReal(residualFFT, this->dirty(term).nonDegenerate());\n                    scimath::fft2d(residualFFT, true);\n\n                    // Calculate transform of basis function [nx,ny,nbases]\n                    Matrix<FT> basisFunctionFFT(this->dirty(term).shape().nonDegenerate());\n                    basisFunctionFFT.set(FT(0.0));\n                    casa::setReal(basisFunctionFFT, Cube<T>(this->itsBasisFunction->basisFunction()).xyPlane(base));\n                    scimath::fft2d(basisFunctionFFT, true);\n\n                    // Calculate product and transform back\n                    Matrix<FT> work(this->dirty(term).shape().nonDegenerate());\n                    ASKAPASSERT(basisFunctionFFT.shape().conform(residualFFT.shape()));\n                    // Removing the extra convolution with PSF0. Leave text here temporarily.\n                    //work = conj(basisFunctionFFT) * residualFFT * conj(xfrZero);\n                    work = conj(basisFunctionFFT) * residualFFT;\n                    scimath::fft2d(work, false);\n\n                    ASKAPLOG_DEBUG_STR(decmtbflogger, \"Basis(\" << base\n                                           << \")*Residual(\" << term << \"): max = \" << max(real(work))\n                                           << \" min = \" << min(real(work)));\n\n                    this->itsResidualBasis(base)(term) = real(work);\n                }\n            }\n        }\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::initialiseMask()\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::initialiseMask\");\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"initialiseMask called\");\n\n            // check if we need the masks\n            if (this->control()->targetObjectiveFunction2()==0) return;\n            // check if we've already done this\n            if (this->itsMask.nelements()>0) return;\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Initialising deep clean masks\");\n\n            ASKAPCHECK(this->itsBasisFunction, \"Basis function not initialised\");\n\n            uInt nBases(this->itsBasisFunction->numberBases());\n\n            this->itsMask.resize(nBases);\n            for (uInt base = 0; base < nBases; base++) {\n                this->itsMask(base).resize(this->dirty(0).shape().nonDegenerate());\n                this->itsMask(base).set(T(0.0));\n            }\n        }\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::initialisePSF()\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::initialisePSF\");\n\n            if (!this->itsBasisFunctionChanged) return;\n\n            ASKAPCHECK(this->itsBasisFunction, \"Basis function not initialised\");\n\n            ASKAPLOG_DEBUG_STR(decmtbflogger,\n                               \"Updating Multi-Term Basis Function deconvolver for change in basis function\");\n            IPosition subPsfShape(this->findSubPsfShape());\n\n            Array<FT> work(subPsfShape);\n\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Shape of basis functions \"\n                                   << this->itsBasisFunction->basisFunction().shape());\n\n            IPosition stackShape(this->itsBasisFunction->basisFunction().shape());\n\n            uInt nBases(this->itsBasisFunction->numberBases());\n\n            // Now transform the basis functions. These may be a different size from\n            // those in initialiseResidual so we don't keep either\n            Cube<FT> basisFunctionFFT(this->itsBasisFunction->basisFunction().shape());\n            basisFunctionFFT.set(FT(0.0));\n            casa::setReal(basisFunctionFFT, this->itsBasisFunction->basisFunction());\n            scimath::fft2d(basisFunctionFFT, true);\n\n            itsTermBaseFlux.resize(nBases);\n            for (uInt base = 0; base < nBases; base++) {\n                itsTermBaseFlux(base).resize(this->itsNumberTerms);\n                itsTermBaseFlux(base) = 0.0;\n            }\n\n            const uInt nx(this->psf(0).shape()(0));\n            const uInt ny(this->psf(0).shape()(1));\n\n            const IPosition subPsfStart(2, (nx - subPsfShape(0)) / 2, (ny - subPsfShape(1)) / 2);\n            //const IPosition subPsfEnd(2,(nx+subPsfShape(0))/2-1,(ny+subPsfShape(1))/2-1);\n            //const IPosition subPsfStride(2,1,1);\n\n            //Slicer subPsfSlicer(subPsfStart, subPsfEnd, subPsfStride, Slicer::endIsLast);\n            Slicer subPsfSlicer(subPsfStart, subPsfShape);\n            // check just in case\n            ASKAPCHECK(subPsfSlicer.length() == subPsfShape, \"Slicer selected length of \" <<\n                subPsfSlicer.length() << \" is different from requested shape \" << subPsfShape);\n\n            casa::IPosition minPos;\n            casa::IPosition maxPos;\n            T minVal, maxVal;\n            casa::minMax(minVal, maxVal, minPos, maxPos, this->psf(0).nonDegenerate()(subPsfSlicer));\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Maximum of PSF(0) = \" << maxVal << \" at \" << maxPos);\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Minimum of PSF(0) = \" << minVal << \" at \" << minPos);\n            this->itsPeakPSFVal = maxVal;\n            this->itsPeakPSFPos(0) = maxPos(0);\n            this->itsPeakPSFPos(1) = maxPos(1);\n\n            IPosition subPsfPeak(2, this->itsPeakPSFPos(0), this->itsPeakPSFPos(1));\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Peak of PSF subsection at  \" << subPsfPeak);\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Shape of PSF subsection is \" << subPsfShape);\n\n            // Calculate XFR for the subsection only. We need all PSF's up to\n            // 2*nTerms-1\n            ASKAPCHECK(this->itsPsfLongVec.nelements() == (2*this->itsNumberTerms - 1),\n                \"PSF long vector has wrong length \" << this->itsPsfLongVec.nelements());\n\n            // Calculate all the transfer functions\n            Vector<Array<FT> > subXFRVec(2*this->itsNumberTerms - 1);\n            for (uInt term1 = 0; term1 < (2*this->itsNumberTerms - 1); term1++) {\n                subXFRVec(term1).resize(subPsfShape);\n                subXFRVec(term1).set(0.0);\n                casa::setReal(subXFRVec(term1), this->itsPsfLongVec(term1).nonDegenerate()(subPsfSlicer));\n                scimath::fft2d(subXFRVec(term1), true);\n            }\n            // Calculate residuals convolved with bases [nx,ny][nterms][nbases]\n            // Calculate transform of PSF(0)\n            T normPSF;\n            // Removing the extra convolution with PSF0. Leave text here temporarily.\n            //normPSF = casa::sum(casa::real(subXFRVec(0) * conj(subXFRVec(0)))) / subXFRVec(0).nelements();\n            normPSF = casa::sum(casa::real(subXFRVec(0))) / subXFRVec(0).nelements();\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"PSF effective volume = \" << normPSF);\n\n            itsPSFCrossTerms.resize(nBases, nBases);\n            for (uInt base = 0; base < nBases; base++) {\n                for (uInt base1 = 0; base1 < nBases; base1++) {\n                    itsPSFCrossTerms(base, base1).resize(this->itsNumberTerms, this->itsNumberTerms);\n                    for (uInt term1 = 0; term1 < this->itsNumberTerms; term1++) {\n                        for (uInt term2 = 0; term2 < this->itsNumberTerms; term2++) {\n                            // should not have to do this, since assigment happens below\n                            //itsPSFCrossTerms(base, base1)(term1, term2).resize(subPsfShape);\n                        }\n                    }\n                }\n            }\n\n            this->itsCouplingMatrix.resize(nBases);\n            for (uInt base1 = 0; base1 < nBases; base1++) {\n                itsCouplingMatrix(base1).resize(this->itsNumberTerms, this->itsNumberTerms);\n                for (uInt base2 = base1; base2 < nBases; base2++) {\n                    for (uInt term1 = 0; term1 < this->itsNumberTerms; term1++) {\n                        for (uInt term2 = term1; term2 < this->itsNumberTerms; term2++) {\n                            // Removing the extra convolution with PSF0. Leave text here temporarily.\n                            //work = conj(basisFunctionFFT.xyPlane(base1)) * basisFunctionFFT.xyPlane(base2) *\n                            //       subXFRVec(0) * conj(subXFRVec(term1 + term2)) / normPSF;\n                            work = conj(basisFunctionFFT.xyPlane(base1)) * basisFunctionFFT.xyPlane(base2) *\n                                   conj(subXFRVec(term1 + term2)) / normPSF;\n                            scimath::fft2d(work, false);\n                            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Base(\" << base1 << \")*Base(\" << base2\n                                                   << \")*PSF(\" << term1 + term2\n                                                   << \"): max = \" << max(real(work))\n                                                   << \" min = \" << min(real(work))\n                                                   << \" centre = \" << real(work(subPsfPeak)));\n                            // Remember that casa::Array reuses the same memory where possible so this\n                            // apparent redundancy does not cause any memory bloat\n                            // I don't think that is true here: simple assigment does not share memory only the copy constructor does\n                            // Need to use .reference() to get the behavior wanted\n                            itsPSFCrossTerms(base1, base2)(term1, term2) = real(work);\n                            itsPSFCrossTerms(base2, base1)(term1, term2).reference(itsPSFCrossTerms(base1, base2)(term1, term2));\n                            itsPSFCrossTerms(base1, base2)(term2, term1).reference(itsPSFCrossTerms(base1, base2)(term1, term2));\n                            itsPSFCrossTerms(base2, base1)(term2, term1).reference(itsPSFCrossTerms(base1, base2)(term1, term2));\n                            if (base1 == base2) {\n                                itsCouplingMatrix(base1)(term1, term2) = real(work(subPsfPeak));\n                                itsCouplingMatrix(base1)(term2, term1) = real(work(subPsfPeak));\n                            }\n                        }\n                    }\n                }\n            }\n\n            ASKAPLOG_DEBUG_STR(decmtbflogger, \"Calculating inverses of coupling matrices\");\n\n            // Invert the coupling matrices and check for correctness\n            this->itsInverseCouplingMatrix.resize(nBases);\n            this->itsDetCouplingMatrix.resize(nBases);\n\n            for (uInt base = 0; base < nBases; base++) {\n                this->itsInverseCouplingMatrix(base).resize(this->itsNumberTerms, this->itsNumberTerms);\n                ASKAPLOG_INFO_STR(decmtbflogger, \"Coupling matrix(\" << base << \")=\"\n                                       << this->itsCouplingMatrix(base).row(0));\n                for (uInt term = 1; term < this->itsNumberTerms; term++) {\n                    ASKAPLOG_INFO_STR(decmtbflogger, \"                   \"\n                                       << this->itsCouplingMatrix(base).row(term));\n                }\n                ASKAPLOG_DEBUG_STR(decmtbflogger, \"Calculating matrix inverse by Cholesky decomposition\");\n                invertSymPosDef(this->itsInverseCouplingMatrix(base),\n                                this->itsDetCouplingMatrix(base), this->itsCouplingMatrix(base));\n                ASKAPLOG_INFO_STR(decmtbflogger, \"Coupling matrix determinant(\" << base << \") = \"\n                                       << this->itsDetCouplingMatrix(base));\n                ASKAPLOG_INFO_STR(decmtbflogger, \"Inverse coupling matrix(\" << base\n                                       << \")=\" << this->itsInverseCouplingMatrix(base).row(0));\n                for (uInt term = 1; term < this->itsNumberTerms; term++) {\n                    ASKAPLOG_INFO_STR(decmtbflogger, \"                           \"\n                                       << this->itsInverseCouplingMatrix(base).row(term));\n                }\n            }\n            this->itsBasisFunctionChanged = False;\n        }\n\n        template<class T, class FT>\n        bool DeconvolverMultiTermBasisFunction<T, FT>::deconvolve()\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::deconvolve\");\n            this->initialise();\n\n            if (this->control()->targetIter() != 0) {\n                ASKAPLOG_INFO_STR(decmtbflogger, \"Performing Multi-Term BasisFunction CLEAN for \"\n                                      << this->control()->targetIter() << \" iterations\");\n                do {\n                    this->oneIteration();\n                    this->monitor()->monitor(*(this->state()));\n                    this->state()->incIter();\n                } while (!this->control()->terminate(*(this->state())));\n\n                ASKAPLOG_INFO_STR(decmtbflogger, \"Performed Multi-Term BasisFunction CLEAN for \"\n                                      << this->state()->currentIter() << \" iterations\");\n                ASKAPLOG_INFO_STR(decmtbflogger, this->control()->terminationString());\n            } else {\n                ASKAPLOG_INFO_STR(decmtbflogger,\n                    \"Bypassed Multi-Term BasisFunction CLEAN due to 0 iterations in the setup\");\n            }\n            this->finalise();\n\n            return True;\n        }\n\n        // Helper function to replace minMaxMasked calls when we only need the abs maximum\n        template<class T>\n        void absMaxPosMasked(T& maxVal, IPosition&  maxPos,  const Matrix<T>& im, const Matrix<T>& mask)\n        {\n            maxVal = T(0);\n            const uInt ncol = mask.ncolumn();\n            const uInt nrow = mask.nrow();\n            for (uInt j = 0; j < ncol; j++ ) {\n                const T* pIm = &im(0,j);\n                const T* pMask = &mask(0,j);\n                for (uInt i = 0; i < nrow; i++ ) {\n                    //T val = abs(mask(i,j) * im(i,j));\n                    T val = abs(*pIm++ * *pMask++);\n                    if (val > maxVal) {\n                        maxVal = val;\n                        maxPos(0) = i;\n                        maxPos(1) = j;\n                    }\n                }\n            }\n        }\n\n\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::getCoupledResidual(T& absPeakRes) {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction:::getCoupledResidual\");\n            const uInt nBases(this->itsResidualBasis.nelements());\n            const uInt nTerms(this->itsNumberTerms);\n            bool isWeighted((this->itsWeight.nelements() > 0) &&\n                (this->itsWeight(0).shape().nonDegenerate().conform(this->itsResidualBasis(0)(0).shape())));\n\n            Vector<T> maxTermVals(nTerms);\n            Vector<T> maxBaseVals(nBases);\n\n            for (uInt term = 0; term < nTerms; term++) {\n                for (uInt base = 0; base < nBases; base++) {\n                    casa::IPosition minPos(2, 0);\n                    casa::IPosition maxPos(2, 0);\n                    T minVal(0.0), maxVal(0.0);\n                    if (isWeighted) {\n                        const casa::Matrix<T> res = this->itsResidualBasis(base)(term);\n                        const casa::Matrix<T> wt = this->itsWeight(0).nonDegenerate();\n                        absMaxPosMasked(maxVal, maxPos, res, wt);\n                        //casa::minMaxMasked(minVal, maxVal, minPos, maxPos, this->itsResidualBasis(base)(term),\n                        //                   this->itsWeight(0).nonDegenerate());\n                    } else {\n                        casa::minMax(minVal, maxVal, minPos, maxPos, this->itsResidualBasis(base)(term));\n                    }\n                    if (abs(minVal) > abs(maxVal)) {\n                        maxBaseVals(base) = abs(this->itsResidualBasis(base)(term)(minPos));\n                    }\n                    else {\n                        maxBaseVals(base) = abs(this->itsResidualBasis(base)(term)(maxPos));\n                    }\n\n                }\n                casa::IPosition minPos(1, 0);\n                casa::IPosition maxPos(1, 0);\n                T minVal(0.0), maxVal(0.0);\n                casa::minMax(minVal, maxVal, minPos, maxPos,maxBaseVals);\n                maxTermVals(term) = maxVal;\n            }\n            casa::IPosition minPos(1, 0);\n            casa::IPosition maxPos(1, 0);\n            T minVal(0.0), maxVal(0.0);\n            casa::minMax(minVal, maxVal, minPos, maxPos,maxTermVals);\n            absPeakRes = maxVal;\n        }\n        // This contains the heart of the Multi-Term BasisFunction Clean algorithm\n        template<class T, class FT>\n        void DeconvolverMultiTermBasisFunction<T, FT>::chooseComponent(uInt& optimumBase,\n                casa::IPosition& absPeakPos, T& absPeakVal, Vector<T>& peakValues)\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction:::chooseComponent\");\n\n            const uInt nBases(this->itsResidualBasis.nelements());\n\n            absPeakVal = 0.0;\n\n            ASKAPDEBUGASSERT(peakValues.nelements() <= this->itsNumberTerms);\n\n            // Find the base having the peak value in term=0\n            // Here the weights image is used as a weight in the determination\n            // of the maximum i.e. it finds the max in weight . residual. The values\n            // returned are without the weight\n            bool isWeighted((this->itsWeight.nelements() > 0) &&\n                (this->itsWeight(0).shape().nonDegenerate().conform(this->itsResidualBasis(0)(0).shape())));\n\n            Vector<T> minValues(this->itsNumberTerms);\n            Vector<T> maxValues(this->itsNumberTerms);\n\n            // Set the mask - we need it for weighted search and deep clean\n            Matrix<T> mask;\n            if (isWeighted) {\n                mask = this->itsWeight(0).nonDegenerate();\n                if  (this->itsSolutionType == \"MAXCHISQ\") {\n                    // square weights for MAXCHISQ\n                    mask*=mask;\n                }\n            }\n\n            for (uInt base = 0; base < nBases; base++) {\n\n                // Find peak in residual image cube\n                casa::IPosition minPos(2, 0);\n                casa::IPosition maxPos(2, 0);\n                T minVal(0.0), maxVal(0.0);\n\n                if (deepCleanMode()) {\n                    if (isWeighted) {\n                        // recompute mask*weight for each new base\n                        if (base>0) {\n                            mask = this->itsWeight(0).nonDegenerate();\n                            if  (this->itsSolutionType == \"MAXCHISQ\") {\n                                // square weights for MAXCHISQ\n                                mask*=mask;\n                            }\n                        }\n                        mask*=this->itsMask(base);\n                    } else {\n                        mask=this->itsMask(base);\n                    }\n                }\n\n                Bool haveMask=mask.nelements()>0;\n\n                // We implement various approaches to finding the peak. The first is the cheapest\n                // and evidently the best (according to Urvashi).\n\n                // Look for the maximum in term=0 for this base\n                if (this->itsSolutionType == \"MAXBASE\") {\n                    if (haveMask) {\n                        const casa::Matrix<T> res = this->itsResidualBasis(base)(0);\n                        absMaxPosMasked(maxVal, maxPos, res, mask);\n//                      casa::minMaxMasked(minVal, maxVal, minPos, maxPos, this->itsResidualBasis(base)(0),mask)\n\n                    } else {\n                        casa::minMax(minVal, maxVal, minPos, maxPos, this->itsResidualBasis(base)(0));\n                    }\n                    for (uInt term = 0; term < this->itsNumberTerms; term++) {\n                        minValues(term) = this->itsResidualBasis(base)(term)(minPos);\n                        maxValues(term) = this->itsResidualBasis(base)(term)(maxPos);\n                    }\n                    // In performing the search for the peak across bases, we want to take into account\n                    // the SNR so we normalise out the coupling matrix for term=0 to term=0.\n                    T norm(1 / sqrt(this->itsCouplingMatrix(base)(0, 0)));\n                    maxVal *= norm;\n                    minVal *= norm;\n                } else {\n                    // All these algorithms need the decoupled terms\n\n                    // Decouple all terms using inverse coupling matrix\n                    Vector<Array<T> > coefficients(this->itsNumberTerms);\n                    for (uInt term1 = 0; term1 < this->itsNumberTerms; term1++) {\n                        coefficients(term1).resize(this->dirty(0).shape().nonDegenerate());\n                        coefficients(term1).set(T(0.0));\n                        for (uInt term2 = 0; term2 < this->itsNumberTerms; term2++) {\n                            coefficients(term1) = coefficients(term1) +\n                                                  T(this->itsInverseCouplingMatrix(base)(term1, term2)) *\n                                                  this->itsResidualBasis(base)(term2);\n                        }\n                    }\n\n                    if (this->itsSolutionType == \"MAXTERM0\") {\n                        if (haveMask) {\n                            casa::minMaxMasked(minVal, maxVal, minPos, maxPos, coefficients(0),\n                                               mask);\n                        } else {\n                            casa::minMax(minVal, maxVal, minPos, maxPos, coefficients(0));\n                        }\n                        for (uInt term = 0; term < this->itsNumberTerms; term++) {\n                            minValues(term) = coefficients(term)(minPos);\n                            maxValues(term) = coefficients(term)(maxPos);\n                        }\n                    } else {\n                        // MAXCHISQ\n                        // Now form the criterion image and then search for the peak.\n                        Array<T> negchisq(this->dirty(0).shape().nonDegenerate());\n                        negchisq.set(T(0.0));\n                        for (uInt term1 = 0; term1 < this->itsNumberTerms; term1++) {\n                            negchisq = negchisq + coefficients(term1) * this->itsResidualBasis(base)(term1);\n                        }\n                        // Need to take the square root to ensure that the SNR weighting is correct\n                        //            ASKAPCHECK(min(negchisq)>0.0, \"Negchisq has negative values\");\n                        //            negchisq=sqrt(negchisq);\n                        //            SynthesisParamsHelper::saveAsCasaImage(\"negchisq.img\",negchisq);\n                        //            SynthesisParamsHelper::saveAsCasaImage(\"coefficients0.img\",coefficients(0));\n                        //            SynthesisParamsHelper::saveAsCasaImage(\"coefficients1.img\",coefficients(1));\n                        //            ASKAPTHROW(AskapError, \"Written debug images\");\n                        // Remember that the weights must be squared.\n                        if (haveMask) {\n                            casa::minMaxMasked(minVal, maxVal, minPos, maxPos, negchisq,\n                                               mask);\n                        } else {\n                            casa::minMax(minVal, maxVal, minPos, maxPos, negchisq);\n                        }\n                        for (uInt term = 0; term < this->itsNumberTerms; term++) {\n                            minValues(term) = coefficients(term)(minPos);\n                            maxValues(term) = coefficients(term)(maxPos);\n                        }\n                    }\n                }\n\n                // We use the minVal and maxVal to find the optimum base\n                if (abs(minVal) > absPeakVal) {\n                    optimumBase = base;\n                    absPeakVal = abs(minVal);\n                    absPeakPos = minPos;\n                }\n                if (abs(maxVal) > absPeakVal) {\n                    optimumBase = base;\n                    absPeakVal = abs(maxVal);\n                    absPeakPos = maxPos;\n                }\n            }\n\n            // Now that we know the location of the peak found using one of the\n            // above methods we can look up the values of the residuals. Remember\n            // that we have to decouple the answer\n            for (uInt term1 = 0; term1 < this->itsNumberTerms; ++term1) {\n                peakValues(term1) = 0.0;\n                for (uInt term2 = 0; term2 < this->itsNumberTerms; ++term2) {\n                    peakValues(term1) +=\n                        T(this->itsInverseCouplingMatrix(optimumBase)(term1, term2)) *\n                        this->itsResidualBasis(optimumBase)(term2)(absPeakPos);\n                }\n            }\n\n            // Record location of peak in mask\n            if (this->itsMask.nelements()) this->itsMask(optimumBase)(absPeakPos)=T(1.0);\n\n            // Take square root to get value comparable to peak residual\n            if (this->itsSolutionType == \"MAXCHISQ\") {\n                absPeakVal = sqrt(max(T(0.0), absPeakVal));\n            }\n\n            // Not sure I agree with the this I think the absPeakVal should\n            // be the absolute value of the peak residual\n            // For deep cleaning we want to restrict the abspeakval to the mask\n            // so we just use the value determined above\n            if (!deepCleanMode() && !decoupled()) getCoupledResidual(absPeakVal);\n\n        }\n\n        template<class T, class FT>\n        bool DeconvolverMultiTermBasisFunction<T, FT>::oneIteration()\n        {\n            ASKAPTRACE(\"DeconvolverMultiTermBasisFunction::oneIteration\");\n\n            // For the psf convolutions, we only need a small part of the\n            // basis functions so we recalculate for that size\n            IPosition subPsfShape(this->findSubPsfShape());\n\n            const uInt nBases(this->itsResidualBasis.nelements());\n\n            casa::IPosition absPeakPos(2, 0);\n            T absPeakVal(0.0);\n            uInt optimumBase(0);\n            Vector<T> peakValues(this->itsNumberTerms);\n            chooseComponent(optimumBase, absPeakPos, absPeakVal, peakValues);\n\n            // Report on progress\n            // We want the worst case residual\n            // T absPeakRes = max(abs(peakValues));\n\n\n\n            //      ASKAPLOG_INFO_STR(decmtbflogger, \"All terms: absolute max = \" << absPeakRes << \" at \" << absPeakPos);\n            //      ASKAPLOG_INFO_STR(decmtbflogger, \"Optimum base = \" << optimumBase);\n\n            if (this->state()->initialObjectiveFunction() == 0.0) {\n                this->state()->setInitialObjectiveFunction(abs(absPeakVal));\n            }\n            this->state()->setPeakResidual(abs(absPeakVal));\n            this->state()->setObjectiveFunction(abs(absPeakVal));\n            this->state()->setTotalFlux(sum(this->model(0)));\n\n            //  Check if we should enter deep cleaning mode\n            if (abs(absPeakVal) < this->control()->targetObjectiveFunction() &&\n                this->control()->targetObjectiveFunction2()>0 &&\n                abs(absPeakVal) > this->control()->targetObjectiveFunction2()) {\n              if (!deepCleanMode()) ASKAPLOG_INFO_STR(decmtbflogger, \"Starting deep cleaning phase\");\n              setDeepCleanMode(True);\n            }\n\n            // Now we adjust model and residual for this component\n            const casa::IPosition residualShape(this->dirty(0).shape().nonDegenerate());\n            //IPosition subPsfStart(2, nx / 2 - subPsfShape(0) / 2, ny / 2 - subPsfShape(1) / 2);\n            //IPosition subPsfEnd(2, nx / 2 + subPsfShape(0) / 2 - 1, ny / 2 + subPsfShape(1) / 2 - 1);\n            //IPosition subPsfStride(2, 1, 1);\n\n            //Slicer subPsfSlicer(subPsfStart, subPsfEnd, subPsfStride, Slicer::endIsLast);\n            const casa::IPosition psfShape(2, this->itsBasisFunction->basisFunction().shape()(0),\n                                           this->itsBasisFunction->basisFunction().shape()(1));\n\n            casa::IPosition residualStart(2, 0), residualEnd(2, 0), residualStride(2, 1);\n            casa::IPosition psfStart(2, 0), psfEnd(2, 0), psfStride(2, 1);\n\n            const casa::IPosition modelShape(this->model(0).shape().nonDegenerate());\n            casa::IPosition modelStart(2, 0), modelEnd(2, 0), modelStride(2, 1);\n\n            // Wrangle the start, end, and shape into consistent form. It took me\n            // quite a while to figure this out (slow brain day) so it may be\n            // that there are some edge cases for which it fails.\n            for (uInt dim = 0; dim < 2; dim++) {\n                residualStart(dim) = max(0, Int(absPeakPos(dim) - psfShape(dim) / 2));\n                residualEnd(dim) = min(Int(absPeakPos(dim) + psfShape(dim) / 2 - 1), Int(residualShape(dim) - 1));\n                // Now we have to deal with the PSF. Here we want to use enough of the\n                // PSF to clean the residual image.\n                psfStart(dim) = max(0, Int(this->itsPeakPSFPos(dim) - (absPeakPos(dim) - residualStart(dim))));\n                psfEnd(dim) = min(Int(this->itsPeakPSFPos(dim) - (absPeakPos(dim) - residualEnd(dim))),\n                                  Int(psfShape(dim) - 1));\n\n                modelStart(dim) = residualStart(dim);\n                modelEnd(dim) = residualEnd(dim);\n            }\n\n            casa::Slicer psfSlicer(psfStart, psfEnd, psfStride, Slicer::endIsLast);\n            casa::Slicer residualSlicer(residualStart, residualEnd, residualStride, Slicer::endIsLast);\n            casa::Slicer modelSlicer(modelStart, modelEnd, modelStride, Slicer::endIsLast);\n\n            // Add to model\n            // We loop over all terms for the optimum base and ignore those terms with no flux\n            for (uInt term = 0; term < this->itsNumberTerms; ++term) {\n                if (abs(peakValues(term)) > 0.0) {\n                    casa::Array<float> slice = this->model(term).nonDegenerate()(modelSlicer);\n                    slice += this->control()->gain() * peakValues(term) *\n                             Cube<T>(this->itsBasisFunction->basisFunction()).xyPlane(optimumBase).nonDegenerate()(psfSlicer);\n                    this->itsTermBaseFlux(optimumBase)(term) += this->control()->gain() * peakValues(term);\n                }\n            }\n\n            // Subtract PSFs, including base-base crossterms\n            for (uInt term1 = 0; term1 < this->itsNumberTerms; term1++) {\n                for (uInt term2 = 0; term2 < this->itsNumberTerms; term2++) {\n                    if (abs(peakValues(term2)) > 0.0) {\n                        for (uInt base = 0; base < nBases; base++) {\n                            this->itsResidualBasis(base)(term1)(residualSlicer) =\n                                this->itsResidualBasis(base)(term1)(residualSlicer)\n                                - this->control()->gain() * peakValues(term2) *\n                                this->itsPSFCrossTerms(base, optimumBase)(term1, term2)(psfSlicer);\n\n                        }\n                    }\n                }\n            }\n\n            return True;\n        }\n\n    }\n}\n// namespace synthesis\n// namespace askap\n", "meta": {"hexsha": "1047d9999999b75c4998b71efb5e910e8fd25a82", "size": 42888, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverMultiTermBasisFunction.tcc", "max_stars_repo_name": "ATNF/askapsoft", "max_stars_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverMultiTermBasisFunction.tcc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverMultiTermBasisFunction.tcc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.2399540758, "max_line_length": 156, "alphanum_fraction": 0.5468429398, "num_tokens": 10086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398145016252115, "lm_q2_score": 0.0297600957745801, "lm_q1q2_score": 0.01291532952122779}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2011-2014, Willow Garage, Inc.\n *  Copyright (c) 2014-2015, Open Source Robotics Foundation\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 Open Source Robotics Foundation 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 Jia Pan */\n\n#include <hpp/fcl/internal/intersect.h>\n#include <iostream>\n#include <limits>\n#include <vector>\n#include <boost/math/special_functions/fpclassify.hpp>  // isnan.\n#include <hpp/fcl/internal/tools.h>\n\nnamespace hpp {\nnamespace fcl {\n\nbool Intersect::buildTrianglePlane(const Vec3f& v1, const Vec3f& v2,\n                                   const Vec3f& v3, Vec3f* n, FCL_REAL* t) {\n  Vec3f n_ = (v2 - v1).cross(v3 - v1);\n  FCL_REAL norm2 = n_.squaredNorm();\n  if (norm2 > 0) {\n    *n = n_ / sqrt(norm2);\n    *t = n->dot(v1);\n    return true;\n  }\n  return false;\n}\n\nvoid TriangleDistance::segPoints(const Vec3f& P, const Vec3f& A, const Vec3f& Q,\n                                 const Vec3f& B, Vec3f& VEC, Vec3f& X,\n                                 Vec3f& Y) {\n  Vec3f T;\n  FCL_REAL A_dot_A, B_dot_B, A_dot_B, A_dot_T, B_dot_T;\n  Vec3f TMP;\n\n  T = Q - P;\n  A_dot_A = A.dot(A);\n  B_dot_B = B.dot(B);\n  A_dot_B = A.dot(B);\n  A_dot_T = A.dot(T);\n  B_dot_T = B.dot(T);\n\n  // t parameterizes ray P,A\n  // u parameterizes ray Q,B\n\n  FCL_REAL t, u;\n\n  // compute t for the closest point on ray P,A to\n  // ray Q,B\n\n  FCL_REAL denom = A_dot_A * B_dot_B - A_dot_B * A_dot_B;\n\n  t = (A_dot_T * B_dot_B - B_dot_T * A_dot_B) / denom;\n\n  // clamp result so t is on the segment P,A\n\n  if ((t < 0) || boost::math::isnan(t))\n    t = 0;\n  else if (t > 1)\n    t = 1;\n\n  // find u for point on ray Q,B closest to point at t\n\n  u = (t * A_dot_B - B_dot_T) / B_dot_B;\n\n  // if u is on segment Q,B, t and u correspond to\n  // closest points, otherwise, clamp u, recompute and\n  // clamp t\n\n  if ((u <= 0) || boost::math::isnan(u)) {\n    Y = Q;\n\n    t = A_dot_T / A_dot_A;\n\n    if ((t <= 0) || boost::math::isnan(t)) {\n      X = P;\n      VEC = Q - P;\n    } else if (t >= 1) {\n      X = P + A;\n      VEC = Q - X;\n    } else {\n      X = P + A * t;\n      TMP = T.cross(A);\n      VEC = A.cross(TMP);\n    }\n  } else if (u >= 1) {\n    Y = Q + B;\n\n    t = (A_dot_B + A_dot_T) / A_dot_A;\n\n    if ((t <= 0) || boost::math::isnan(t)) {\n      X = P;\n      VEC = Y - P;\n    } else if (t >= 1) {\n      X = P + A;\n      VEC = Y - X;\n    } else {\n      X = P + A * t;\n      T = Y - P;\n      TMP = T.cross(A);\n      VEC = A.cross(TMP);\n    }\n  } else {\n    Y = Q + B * u;\n\n    if ((t <= 0) || boost::math::isnan(t)) {\n      X = P;\n      TMP = T.cross(B);\n      VEC = B.cross(TMP);\n    } else if (t >= 1) {\n      X = P + A;\n      T = Q - X;\n      TMP = T.cross(B);\n      VEC = B.cross(TMP);\n    } else {\n      X = P + A * t;\n      VEC = A.cross(B);\n      if (VEC.dot(T) < 0) {\n        VEC = VEC * (-1);\n      }\n    }\n  }\n}\n\nFCL_REAL TriangleDistance::sqrTriDistance(const Vec3f S[3], const Vec3f T[3],\n                                          Vec3f& P, Vec3f& Q) {\n  // Compute vectors along the 6 sides\n\n  Vec3f Sv[3];\n  Vec3f Tv[3];\n  Vec3f VEC;\n\n  Sv[0] = S[1] - S[0];\n  Sv[1] = S[2] - S[1];\n  Sv[2] = S[0] - S[2];\n\n  Tv[0] = T[1] - T[0];\n  Tv[1] = T[2] - T[1];\n  Tv[2] = T[0] - T[2];\n\n  // For each edge pair, the vector connecting the closest points\n  // of the edges defines a slab (parallel planes at head and tail\n  // enclose the slab). If we can show that the off-edge vertex of\n  // each triangle is outside of the slab, then the closest points\n  // of the edges are the closest points for the triangles.\n  // Even if these tests fail, it may be helpful to know the closest\n  // points found, and whether the triangles were shown disjoint\n\n  Vec3f V, Z, minP, minQ;\n  FCL_REAL mindd;\n  int shown_disjoint = 0;\n\n  mindd = (S[0] - T[0]).squaredNorm() + 1;  // Set first minimum safely high\n\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      // Find closest points on edges i & j, plus the\n      // vector (and distance squared) between these points\n      segPoints(S[i], Sv[i], T[j], Tv[j], VEC, P, Q);\n\n      V = Q - P;\n      FCL_REAL dd = V.dot(V);\n\n      // Verify this closest point pair only if the distance\n      // squared is less than the minimum found thus far.\n\n      if (dd <= mindd) {\n        minP = P;\n        minQ = Q;\n        mindd = dd;\n\n        Z = S[(i + 2) % 3] - P;\n        FCL_REAL a = Z.dot(VEC);\n        Z = T[(j + 2) % 3] - Q;\n        FCL_REAL b = Z.dot(VEC);\n\n        if ((a <= 0) && (b >= 0)) return dd;\n\n        FCL_REAL p = V.dot(VEC);\n\n        if (a < 0) a = 0;\n        if (b > 0) b = 0;\n        if ((p - a + b) > 0) shown_disjoint = 1;\n      }\n    }\n  }\n\n  // No edge pairs contained the closest points.\n  // either:\n  // 1. one of the closest points is a vertex, and the\n  //    other point is interior to a face.\n  // 2. the triangles are overlapping.\n  // 3. an edge of one triangle is parallel to the other's face. If\n  //    cases 1 and 2 are not true, then the closest points from the 9\n  //    edge pairs checks above can be taken as closest points for the\n  //    triangles.\n  // 4. possibly, the triangles were degenerate.  When the\n  //    triangle points are nearly colinear or coincident, one\n  //    of above tests might fail even though the edges tested\n  //    contain the closest points.\n\n  // First check for case 1\n\n  Vec3f Sn;\n  FCL_REAL Snl;\n\n  Sn = Sv[0].cross(Sv[1]);  // Compute normal to S triangle\n  Snl = Sn.dot(Sn);         // Compute square of length of normal\n\n  // If cross product is long enough,\n\n  if (Snl > 1e-15) {\n    // Get projection lengths of T points\n\n    Vec3f Tp;\n\n    V = S[0] - T[0];\n    Tp[0] = V.dot(Sn);\n\n    V = S[0] - T[1];\n    Tp[1] = V.dot(Sn);\n\n    V = S[0] - T[2];\n    Tp[2] = V.dot(Sn);\n\n    // If Sn is a separating direction,\n    // find point with smallest projection\n\n    int point = -1;\n    if ((Tp[0] > 0) && (Tp[1] > 0) && (Tp[2] > 0)) {\n      if (Tp[0] < Tp[1])\n        point = 0;\n      else\n        point = 1;\n      if (Tp[2] < Tp[point]) point = 2;\n    } else if ((Tp[0] < 0) && (Tp[1] < 0) && (Tp[2] < 0)) {\n      if (Tp[0] > Tp[1])\n        point = 0;\n      else\n        point = 1;\n      if (Tp[2] > Tp[point]) point = 2;\n    }\n\n    // If Sn is a separating direction,\n\n    if (point >= 0) {\n      shown_disjoint = 1;\n\n      // Test whether the point found, when projected onto the\n      // other triangle, lies within the face.\n\n      V = T[point] - S[0];\n      Z = Sn.cross(Sv[0]);\n      if (V.dot(Z) > 0) {\n        V = T[point] - S[1];\n        Z = Sn.cross(Sv[1]);\n        if (V.dot(Z) > 0) {\n          V = T[point] - S[2];\n          Z = Sn.cross(Sv[2]);\n          if (V.dot(Z) > 0) {\n            // T[point] passed the test - it's a closest point for\n            // the T triangle; the other point is on the face of S\n            P = T[point] + Sn * (Tp[point] / Snl);\n            Q = T[point];\n            return (P - Q).squaredNorm();\n          }\n        }\n      }\n    }\n  }\n\n  Vec3f Tn;\n  FCL_REAL Tnl;\n\n  Tn = Tv[0].cross(Tv[1]);\n  Tnl = Tn.dot(Tn);\n\n  if (Tnl > 1e-15) {\n    Vec3f Sp;\n\n    V = T[0] - S[0];\n    Sp[0] = V.dot(Tn);\n\n    V = T[0] - S[1];\n    Sp[1] = V.dot(Tn);\n\n    V = T[0] - S[2];\n    Sp[2] = V.dot(Tn);\n\n    int point = -1;\n    if ((Sp[0] > 0) && (Sp[1] > 0) && (Sp[2] > 0)) {\n      if (Sp[0] < Sp[1])\n        point = 0;\n      else\n        point = 1;\n      if (Sp[2] < Sp[point]) point = 2;\n    } else if ((Sp[0] < 0) && (Sp[1] < 0) && (Sp[2] < 0)) {\n      if (Sp[0] > Sp[1])\n        point = 0;\n      else\n        point = 1;\n      if (Sp[2] > Sp[point]) point = 2;\n    }\n\n    if (point >= 0) {\n      shown_disjoint = 1;\n\n      V = S[point] - T[0];\n      Z = Tn.cross(Tv[0]);\n      if (V.dot(Z) > 0) {\n        V = S[point] - T[1];\n        Z = Tn.cross(Tv[1]);\n        if (V.dot(Z) > 0) {\n          V = S[point] - T[2];\n          Z = Tn.cross(Tv[2]);\n          if (V.dot(Z) > 0) {\n            P = S[point];\n            Q = S[point] + Tn * (Sp[point] / Tnl);\n            return (P - Q).squaredNorm();\n          }\n        }\n      }\n    }\n  }\n\n  // Case 1 can't be shown.\n  // If one of these tests showed the triangles disjoint,\n  // we assume case 3 or 4, otherwise we conclude case 2,\n  // that the triangles overlap.\n\n  if (shown_disjoint) {\n    P = minP;\n    Q = minQ;\n    return mindd;\n  } else\n    return 0;\n}\n\nFCL_REAL TriangleDistance::sqrTriDistance(const Vec3f& S1, const Vec3f& S2,\n                                          const Vec3f& S3, const Vec3f& T1,\n                                          const Vec3f& T2, const Vec3f& T3,\n                                          Vec3f& P, Vec3f& Q) {\n  Vec3f S[3];\n  Vec3f T[3];\n  S[0] = S1;\n  S[1] = S2;\n  S[2] = S3;\n  T[0] = T1;\n  T[1] = T2;\n  T[2] = T3;\n\n  return sqrTriDistance(S, T, P, Q);\n}\n\nFCL_REAL TriangleDistance::sqrTriDistance(const Vec3f S[3], const Vec3f T[3],\n                                          const Matrix3f& R, const Vec3f& Tl,\n                                          Vec3f& P, Vec3f& Q) {\n  Vec3f T_transformed[3];\n  T_transformed[0] = R * T[0] + Tl;\n  T_transformed[1] = R * T[1] + Tl;\n  T_transformed[2] = R * T[2] + Tl;\n\n  return sqrTriDistance(S, T_transformed, P, Q);\n}\n\nFCL_REAL TriangleDistance::sqrTriDistance(const Vec3f S[3], const Vec3f T[3],\n                                          const Transform3f& tf, Vec3f& P,\n                                          Vec3f& Q) {\n  Vec3f T_transformed[3];\n  T_transformed[0] = tf.transform(T[0]);\n  T_transformed[1] = tf.transform(T[1]);\n  T_transformed[2] = tf.transform(T[2]);\n\n  return sqrTriDistance(S, T_transformed, P, Q);\n}\n\nFCL_REAL TriangleDistance::sqrTriDistance(const Vec3f& S1, const Vec3f& S2,\n                                          const Vec3f& S3, const Vec3f& T1,\n                                          const Vec3f& T2, const Vec3f& T3,\n                                          const Matrix3f& R, const Vec3f& Tl,\n                                          Vec3f& P, Vec3f& Q) {\n  Vec3f T1_transformed = R * T1 + Tl;\n  Vec3f T2_transformed = R * T2 + Tl;\n  Vec3f T3_transformed = R * T3 + Tl;\n  return sqrTriDistance(S1, S2, S3, T1_transformed, T2_transformed,\n                        T3_transformed, P, Q);\n}\n\nFCL_REAL TriangleDistance::sqrTriDistance(const Vec3f& S1, const Vec3f& S2,\n                                          const Vec3f& S3, const Vec3f& T1,\n                                          const Vec3f& T2, const Vec3f& T3,\n                                          const Transform3f& tf, Vec3f& P,\n                                          Vec3f& Q) {\n  Vec3f T1_transformed = tf.transform(T1);\n  Vec3f T2_transformed = tf.transform(T2);\n  Vec3f T3_transformed = tf.transform(T3);\n  return sqrTriDistance(S1, S2, S3, T1_transformed, T2_transformed,\n                        T3_transformed, P, Q);\n}\n\nProject::ProjectResult Project::projectLine(const Vec3f& a, const Vec3f& b,\n                                            const Vec3f& p) {\n  ProjectResult res;\n\n  const Vec3f d = b - a;\n  const FCL_REAL l = d.squaredNorm();\n\n  if (l > 0) {\n    const FCL_REAL t = (p - a).dot(d);\n    res.parameterization[1] = (t >= l) ? 1 : ((t <= 0) ? 0 : (t / l));\n    res.parameterization[0] = 1 - res.parameterization[1];\n    if (t >= l) {\n      res.sqr_distance = (p - b).squaredNorm();\n      res.encode = 2; /* 0x10 */\n    } else if (t <= 0) {\n      res.sqr_distance = (p - a).squaredNorm();\n      res.encode = 1; /* 0x01 */\n    } else {\n      res.sqr_distance = (a + d * res.parameterization[1] - p).squaredNorm();\n      res.encode = 3; /* 0x00 */\n    }\n  }\n\n  return res;\n}\n\nProject::ProjectResult Project::projectTriangle(const Vec3f& a, const Vec3f& b,\n                                                const Vec3f& c,\n                                                const Vec3f& p) {\n  ProjectResult res;\n\n  static const size_t nexti[3] = {1, 2, 0};\n  const Vec3f* vt[] = {&a, &b, &c};\n  const Vec3f dl[] = {a - b, b - c, c - a};\n  const Vec3f& n = dl[0].cross(dl[1]);\n  const FCL_REAL l = n.squaredNorm();\n\n  if (l > 0) {\n    FCL_REAL mindist = -1;\n    for (size_t i = 0; i < 3; ++i) {\n      if ((*vt[i] - p).dot(dl[i].cross(n)) >\n          0)  // origin is to the outside part of the triangle edge, then the\n              // optimal can only be on the edge\n      {\n        size_t j = nexti[i];\n        ProjectResult res_line = projectLine(*vt[i], *vt[j], p);\n\n        if (mindist < 0 || res_line.sqr_distance < mindist) {\n          mindist = res_line.sqr_distance;\n          res.encode =\n              static_cast<unsigned int>(((res_line.encode & 1) ? 1 << i : 0) +\n                                        ((res_line.encode & 2) ? 1 << j : 0));\n          res.parameterization[i] = res_line.parameterization[0];\n          res.parameterization[j] = res_line.parameterization[1];\n          res.parameterization[nexti[j]] = 0;\n        }\n      }\n    }\n\n    if (mindist < 0)  // the origin project is within the triangle\n    {\n      FCL_REAL d = (a - p).dot(n);\n      FCL_REAL s = sqrt(l);\n      Vec3f p_to_project = n * (d / l);\n      mindist = p_to_project.squaredNorm();\n      res.encode = 7;  // m = 0x111\n      res.parameterization[0] = dl[1].cross(b - p - p_to_project).norm() / s;\n      res.parameterization[1] = dl[2].cross(c - p - p_to_project).norm() / s;\n      res.parameterization[2] =\n          1 - res.parameterization[0] - res.parameterization[1];\n    }\n\n    res.sqr_distance = mindist;\n  }\n\n  return res;\n}\n\nProject::ProjectResult Project::projectTetrahedra(const Vec3f& a,\n                                                  const Vec3f& b,\n                                                  const Vec3f& c,\n                                                  const Vec3f& d,\n                                                  const Vec3f& p) {\n  ProjectResult res;\n\n  static const size_t nexti[] = {1, 2, 0};\n  const Vec3f* vt[] = {&a, &b, &c, &d};\n  const Vec3f dl[3] = {a - d, b - d, c - d};\n  FCL_REAL vl = triple(dl[0], dl[1], dl[2]);\n  bool ng = (vl * (a - p).dot((b - c).cross(a - b))) <= 0;\n  if (ng &&\n      std::abs(vl) > 0)  // abs(vl) == 0, the tetrahedron is degenerated; if ng\n                         // is false, then the last vertex in the tetrahedron\n                         // does not grow toward the origin (in fact origin is\n                         // on the other side of the abc face)\n  {\n    FCL_REAL mindist = -1;\n\n    for (size_t i = 0; i < 3; ++i) {\n      size_t j = nexti[i];\n      FCL_REAL s = vl * (d - p).dot(dl[i].cross(dl[j]));\n      if (s > 0)  // the origin is to the outside part of a triangle face, then\n                  // the optimal can only be on the triangle face\n      {\n        ProjectResult res_triangle = projectTriangle(*vt[i], *vt[j], d, p);\n        if (mindist < 0 || res_triangle.sqr_distance < mindist) {\n          mindist = res_triangle.sqr_distance;\n          res.encode =\n              static_cast<unsigned int>((res_triangle.encode & 1 ? 1 << i : 0) +\n                                        (res_triangle.encode & 2 ? 1 << j : 0) +\n                                        (res_triangle.encode & 4 ? 8 : 0));\n          res.parameterization[i] = res_triangle.parameterization[0];\n          res.parameterization[j] = res_triangle.parameterization[1];\n          res.parameterization[nexti[j]] = 0;\n          res.parameterization[3] = res_triangle.parameterization[2];\n        }\n      }\n    }\n\n    if (mindist < 0) {\n      mindist = 0;\n      res.encode = 15;\n      res.parameterization[0] = triple(c - p, b - p, d - p) / vl;\n      res.parameterization[1] = triple(a - p, c - p, d - p) / vl;\n      res.parameterization[2] = triple(b - p, a - p, d - p) / vl;\n      res.parameterization[3] =\n          1 - (res.parameterization[0] + res.parameterization[1] +\n               res.parameterization[2]);\n    }\n\n    res.sqr_distance = mindist;\n  } else if (!ng) {\n    res = projectTriangle(a, b, c, p);\n    res.parameterization[3] = 0;\n  }\n  return res;\n}\n\nProject::ProjectResult Project::projectLineOrigin(const Vec3f& a,\n                                                  const Vec3f& b) {\n  ProjectResult res;\n\n  const Vec3f d = b - a;\n  const FCL_REAL l = d.squaredNorm();\n\n  if (l > 0) {\n    const FCL_REAL t = -a.dot(d);\n    res.parameterization[1] = (t >= l) ? 1 : ((t <= 0) ? 0 : (t / l));\n    res.parameterization[0] = 1 - res.parameterization[1];\n    if (t >= l) {\n      res.sqr_distance = b.squaredNorm();\n      res.encode = 2; /* 0x10 */\n    } else if (t <= 0) {\n      res.sqr_distance = a.squaredNorm();\n      res.encode = 1; /* 0x01 */\n    } else {\n      res.sqr_distance = (a + d * res.parameterization[1]).squaredNorm();\n      res.encode = 3; /* 0x00 */\n    }\n  }\n\n  return res;\n}\n\nProject::ProjectResult Project::projectTriangleOrigin(const Vec3f& a,\n                                                      const Vec3f& b,\n                                                      const Vec3f& c) {\n  ProjectResult res;\n\n  static const size_t nexti[3] = {1, 2, 0};\n  const Vec3f* vt[] = {&a, &b, &c};\n  const Vec3f dl[] = {a - b, b - c, c - a};\n  const Vec3f& n = dl[0].cross(dl[1]);\n  const FCL_REAL l = n.squaredNorm();\n\n  if (l > 0) {\n    FCL_REAL mindist = -1;\n    for (size_t i = 0; i < 3; ++i) {\n      if (vt[i]->dot(dl[i].cross(n)) >\n          0)  // origin is to the outside part of the triangle edge, then the\n              // optimal can only be on the edge\n      {\n        size_t j = nexti[i];\n        ProjectResult res_line = projectLineOrigin(*vt[i], *vt[j]);\n\n        if (mindist < 0 || res_line.sqr_distance < mindist) {\n          mindist = res_line.sqr_distance;\n          res.encode =\n              static_cast<unsigned int>(((res_line.encode & 1) ? 1 << i : 0) +\n                                        ((res_line.encode & 2) ? 1 << j : 0));\n          res.parameterization[i] = res_line.parameterization[0];\n          res.parameterization[j] = res_line.parameterization[1];\n          res.parameterization[nexti[j]] = 0;\n        }\n      }\n    }\n\n    if (mindist < 0)  // the origin project is within the triangle\n    {\n      FCL_REAL d = a.dot(n);\n      FCL_REAL s = sqrt(l);\n      Vec3f o_to_project = n * (d / l);\n      mindist = o_to_project.squaredNorm();\n      res.encode = 7;  // m = 0x111\n      res.parameterization[0] = dl[1].cross(b - o_to_project).norm() / s;\n      res.parameterization[1] = dl[2].cross(c - o_to_project).norm() / s;\n      res.parameterization[2] =\n          1 - res.parameterization[0] - res.parameterization[1];\n    }\n\n    res.sqr_distance = mindist;\n  }\n\n  return res;\n}\n\nProject::ProjectResult Project::projectTetrahedraOrigin(const Vec3f& a,\n                                                        const Vec3f& b,\n                                                        const Vec3f& c,\n                                                        const Vec3f& d) {\n  ProjectResult res;\n\n  static const size_t nexti[] = {1, 2, 0};\n  const Vec3f* vt[] = {&a, &b, &c, &d};\n  const Vec3f dl[3] = {a - d, b - d, c - d};\n  FCL_REAL vl = triple(dl[0], dl[1], dl[2]);\n  bool ng = (vl * a.dot((b - c).cross(a - b))) <= 0;\n  if (ng &&\n      std::abs(vl) > 0)  // abs(vl) == 0, the tetrahedron is degenerated; if ng\n                         // is false, then the last vertex in the tetrahedron\n                         // does not grow toward the origin (in fact origin is\n                         // on the other side of the abc face)\n  {\n    FCL_REAL mindist = -1;\n\n    for (size_t i = 0; i < 3; ++i) {\n      size_t j = nexti[i];\n      FCL_REAL s = vl * d.dot(dl[i].cross(dl[j]));\n      if (s > 0)  // the origin is to the outside part of a triangle face, then\n                  // the optimal can only be on the triangle face\n      {\n        ProjectResult res_triangle = projectTriangleOrigin(*vt[i], *vt[j], d);\n        if (mindist < 0 || res_triangle.sqr_distance < mindist) {\n          mindist = res_triangle.sqr_distance;\n          res.encode =\n              static_cast<unsigned int>((res_triangle.encode & 1 ? 1 << i : 0) +\n                                        (res_triangle.encode & 2 ? 1 << j : 0) +\n                                        (res_triangle.encode & 4 ? 8 : 0));\n          res.parameterization[i] = res_triangle.parameterization[0];\n          res.parameterization[j] = res_triangle.parameterization[1];\n          res.parameterization[nexti[j]] = 0;\n          res.parameterization[3] = res_triangle.parameterization[2];\n        }\n      }\n    }\n\n    if (mindist < 0) {\n      mindist = 0;\n      res.encode = 15;\n      res.parameterization[0] = triple(c, b, d) / vl;\n      res.parameterization[1] = triple(a, c, d) / vl;\n      res.parameterization[2] = triple(b, a, d) / vl;\n      res.parameterization[3] =\n          1 - (res.parameterization[0] + res.parameterization[1] +\n               res.parameterization[2]);\n    }\n\n    res.sqr_distance = mindist;\n  } else if (!ng) {\n    res = projectTriangleOrigin(a, b, c);\n    res.parameterization[3] = 0;\n  }\n  return res;\n}\n\n}  // namespace fcl\n\n}  // namespace hpp\n", "meta": {"hexsha": "3667523c9fe7aa6668e4da28f39c4a84be391618", "size": 22379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/intersect.cpp", "max_stars_repo_name": "proyan/hpp-fcl", "max_stars_repo_head_hexsha": "d63ea45eeb60f39822dc258ea29f8b837da7c044", "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/intersect.cpp", "max_issues_repo_name": "proyan/hpp-fcl", "max_issues_repo_head_hexsha": "d63ea45eeb60f39822dc258ea29f8b837da7c044", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/intersect.cpp", "max_forks_repo_name": "proyan/hpp-fcl", "max_forks_repo_head_hexsha": "d63ea45eeb60f39822dc258ea29f8b837da7c044", "max_forks_repo_licenses": ["BSD-3-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.5197183099, "max_line_length": 80, "alphanum_fraction": 0.5194602082, "num_tokens": 6900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.02976009276274224, "lm_q1q2_score": 0.012915328649874776}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// @project        Open Space Toolkit ▸ Physics\n/// @file           OpenSpaceToolkit/Physics/Time/DateTime.cpp\n/// @author         Lucas Brémond <lucas@loftorbital.com>\n/// @license        Apache License 2.0\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <OpenSpaceToolkit/Physics/Time/DateTime.hpp>\n\n#include <OpenSpaceToolkit/Core/Error.hpp>\n#include <OpenSpaceToolkit/Core/Utilities.hpp>\n\n#include <boost/regex.hpp>\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nnamespace ostk\n{\nnamespace physics\n{\nnamespace time\n{\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n                                DateTime::DateTime                          (   const   Date&                       aDate,\n                                                                                const   Time&                       aTime                                       )\n                                :   date_(aDate),\n                                    time_(aTime)\n{\n\n}\n\n                                DateTime::DateTime                          (           Uint16                      aYear,\n                                                                                        Uint8                       aMonth,\n                                                                                        Uint8                       aDay,\n                                                                                        Uint8                       anHour,\n                                                                                        Uint8                       aMinute,\n                                                                                        Uint8                       aSecond,\n                                                                                        Uint16                      aMillisecond,\n                                                                                        Uint16                      aMicrosecond,\n                                                                                        Uint16                      aNanosecond                                 )\n                                :   date_({aYear, aMonth, aDay}),\n                                    time_({anHour, aMinute, aSecond, aMillisecond, aMicrosecond, aNanosecond})\n{\n\n}\n\nbool                            DateTime::operator ==                       (   const   DateTime&                   aDateTime                                   ) const\n{\n\n    if ((!this->isDefined()) || (!aDateTime.isDefined()))\n    {\n        return false ;\n    }\n\n    return (date_ == aDateTime.date_) && (time_ == aDateTime.time_) ;\n\n}\n\nbool                            DateTime::operator !=                       (   const   DateTime&                   aDateTime                                   ) const\n{\n\n    if ((!this->isDefined()) || (!aDateTime.isDefined()))\n    {\n        return true ;\n    }\n\n    return (date_ != aDateTime.date_) || (time_ != aDateTime.time_) ;\n\n}\n\nstd::ostream&                   operator <<                                 (           std::ostream&               anOutputStream,\n                                                                                const   DateTime&                   aDateTime                                   )\n{\n\n    ostk::core::utils::Print::Header(anOutputStream, \"DateTime\") ;\n\n    ostk::core::utils::Print::Line(anOutputStream) << \"Year:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.date_.getYear()) : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Month:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.date_.getMonth()) : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Day:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.date_.getDay()) : \"Undefined\") ;\n\n    ostk::core::utils::Print::Line(anOutputStream) << \"Hour:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.time_.getHour()) : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Minute:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.time_.getMinute()) : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Second:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.time_.getSecond()) : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Millisecond:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.time_.getMillisecond()) : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Microsecond:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.time_.getMicrosecond()) : \"Undefined\") ;\n    ostk::core::utils::Print::Line(anOutputStream) << \"Nanosecond:\" << (aDateTime.isDefined() ? String::Format(\"{:d}\", aDateTime.time_.getNanosecond()) : \"Undefined\") ;\n\n    ostk::core::utils::Print::Footer(anOutputStream) ;\n\n    return anOutputStream ;\n\n}\n\nbool                            DateTime::isDefined                         ( ) const\n{\n    return date_.isDefined() && time_.isDefined() ;\n}\n\nconst Date&                     DateTime::accessDate                        ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"DateTime\") ;\n    }\n\n    return date_ ;\n\n}\n\nTime                            DateTime::getTime                           ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"DateTime\") ;\n    }\n\n    return time_ ;\n\n}\n\nDate                            DateTime::getDate                           ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"DateTime\") ;\n    }\n\n    return date_ ;\n\n}\n\nconst Time&                     DateTime::accessTime                        ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"DateTime\") ;\n    }\n\n    return time_ ;\n\n}\n\nReal                            DateTime::getJulianDate                     ( ) const\n{\n\n    using ostk::core::types::Int16 ;\n    using ostk::core::types::Int32 ;\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"DateTime\") ;\n    }\n\n    const Uint16 year = date_.getYear() ;\n    const Uint8 month = date_.getMonth() ;\n    const Uint8 day = date_.getDay() ;\n\n    const Int32 julianDate = day\n                           + 1461 * (year + 4800 + (month - 14) / 12) / 4\n                           + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n                           - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n                           - 32075 ;\n\n    const Int16 hour = time_.getHour() ;\n    const Int16 minute = time_.getMinute() ;\n    const Int16 second = time_.getSecond() ;\n    const Uint16 millisecond = time_.getMillisecond() ;\n    const Uint16 microsecond = time_.getMicrosecond() ;\n    const Uint16 nanosecond = time_.getNanosecond() ;\n\n    const Real fractionalDay = ((hour - 12.0) + (minute / 60.0) + (second / 3600.0) + ((millisecond / 1e3) + (microsecond / 1e6) + (nanosecond / 1e9)) / 3600.0) / 24.0 ;\n\n    return Real(julianDate) + fractionalDay ;\n\n}\n\nReal                            DateTime::getModifiedJulianDate             ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"DateTime\") ;\n    }\n\n    return DateTime::ModifiedJulianDateFromJulianDate(this->getJulianDate()) ;\n\n}\n\nString                          DateTime::toString                         (   const   DateTime::Format&           aFormat                                     ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"DateTime\") ;\n    }\n\n    switch (aFormat)\n    {\n\n        case DateTime::Format::Standard:\n            return date_.toString(Date::Format::Standard) + \" \" + time_.toString(Time::Format::Standard) ;\n\n        case DateTime::Format::ISO8601:\n            return date_.toString(Date::Format::Standard) + \"T\" + time_.toString(Time::Format::ISO8601) ;\n\n        case DateTime::Format::STK:\n            return date_.toString(Date::Format::STK) + \" \" + time_.toString(Time::Format::ISO8601) ;\n\n        default:\n            throw ostk::core::error::runtime::Wrong(\"Format\") ;\n            break ;\n\n    }\n\n    return String::Empty() ;\n\n}\n\nDateTime                        DateTime::Undefined                         ( )\n{\n    return DateTime(Date::Undefined(), Time::Undefined()) ;\n}\n\nDateTime                        DateTime::J2000                             ( )\n{\n    return DateTime(Date::J2000(), Time::Noon()) ;\n}\n\nDateTime                        DateTime::GPSEpoch                          ( )\n{\n    return DateTime(Date::GPSEpoch(), Time::Midnight()) ;\n}\n\nDateTime                        DateTime::UnixEpoch                         ( )\n{\n    return DateTime(Date::UnixEpoch(), Time::Midnight()) ;\n}\n\nDateTime                        DateTime::ModifiedJulianDateEpoch           ( )\n{\n    return DateTime(Date::ModifiedJulianDateEpoch(), Time::Midnight()) ;\n}\n\nDateTime                        DateTime::JulianDate                        (   const   Real&                       aJulianDate                                 )\n{\n\n    using ostk::core::types::Int32 ;\n    using ostk::core::types::Int64 ;\n    using ostk::core::types::Uint32 ;\n    using ostk::core::types::Uint64 ;\n\n    if (!aJulianDate.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Julian Date\") ;\n    }\n\n    if (aJulianDate < 0.0)\n    {\n        throw ostk::core::error::RuntimeError(\"Julian Date [{}] is negative.\", aJulianDate) ;\n    }\n\n    // const Int32 J = std::floor(aJulianDate) ;\n\n    // const Int32 y = 4716 ;\n    // const Int32 v = 3 ;\n    // const Int32 j = 1401 ;\n    // const Int32 u = 5 ;\n    // const Int32 m = 2 ;\n    // const Int32 s = 153 ;\n    // const Int32 n = 12 ;\n    // const Int32 w = 2 ;\n    // const Int32 r = 4 ;\n    // const Int32 B = 274277 ;\n    // const Int32 p = 1461 ;\n    // const Int32 C = -38 ;\n\n    // const Int32 f = J + j + (((4 * J + B) / 146097) * 3) / 4 + C ;\n    // const Int32 e = r * f + v ;\n    // const Int32 g = (e % p) / r ;\n    // const Int32 h = u * g + w ;\n\n    // const Int32 D = (h % s) / u + 1 ;\n    // const Int32 M = ((h / s + m) % n) + 1 ;\n    // const Int32 Y = (e / p) - y + (n + m - M) / n ;\n\n    // Uint32 year = static_cast<Uint32>(Y) ;\n    // Uint32 month = static_cast<Uint32>(M) ;\n    // Uint32 day = static_cast<Uint32>(D) ;\n\n    const Int64 integerJulianDate = std::floor(aJulianDate + 0.5) ;\n    const double fractionalJulianDate = static_cast<double>(aJulianDate) - integerJulianDate + 0.5 ;\n\n    const Int32 a = integerJulianDate + 32044 ;\n    const Int32 b = std::floor((4 * a + 3) / 146097) ;\n    const Int32 c = a - std::floor((b * 146097) / 4) ;\n\n    const Int32 d = std::floor((4 * c + 3) / 1461) ;\n    const Int32 e = c - std::floor((1461 * d) / 4) ;\n    const Int32 m = std::floor((5 * e + 2) / 153) ;\n\n    Uint32 year = static_cast<Uint32>(b * 100 + d - 4800 + std::floor(m / 10)) ;\n    Uint32 month = static_cast<Uint32>(m + 3 - 12 * std::floor(m / 10)) ;\n    Uint32 day = static_cast<Uint32>(e - std::floor((153 * m + 2) / 5) + 1) ;\n\n    Uint64 nanosecondCountOfDay = Uint64(fractionalJulianDate * 86400.0 * 1e9) ;\n\n    Uint32 hours = static_cast<Uint32>(std::floor(nanosecondCountOfDay / (3600.0 * 1e9))) ;\n\n    if (nanosecondCountOfDay > Uint64(hours * 3600 * 1e9))\n    {\n        nanosecondCountOfDay -= Uint64(hours * 3600 * 1e9) ;\n    }\n    else\n    {\n        nanosecondCountOfDay = 0 ;\n    }\n\n    Uint32 minute = static_cast<Uint32>(std::floor(nanosecondCountOfDay / (60.0 * 1e9))) ;\n\n    if (nanosecondCountOfDay > Uint64(minute * 60 * 1e9))\n    {\n        nanosecondCountOfDay -= Uint64(minute * 60 * 1e9) ;\n    }\n    else\n    {\n        nanosecondCountOfDay = 0 ;\n    }\n\n    Uint32 second = static_cast<Uint32>(std::floor(nanosecondCountOfDay / 1e9)) ;\n\n    if (nanosecondCountOfDay > Uint64(second * 1e9))\n    {\n        nanosecondCountOfDay -= Uint64(second * 1e9) ;\n    }\n    else\n    {\n        nanosecondCountOfDay = 0 ;\n    }\n\n    Uint32 millisecond = static_cast<Uint32>(std::round(nanosecondCountOfDay / 1e6)) ;\n\n    if (nanosecondCountOfDay > Uint64(millisecond * 1e6))\n    {\n        nanosecondCountOfDay -= Uint64(millisecond * 1e6) ;\n    }\n    else\n    {\n        nanosecondCountOfDay = 0 ;\n    }\n\n    Uint32 microsecond = static_cast<Uint32>(std::round(nanosecondCountOfDay / 1e3)) ;\n\n    if (nanosecondCountOfDay > Uint64(microsecond * 1e3))\n    {\n        nanosecondCountOfDay -= Uint64(microsecond * 1e3) ;\n    }\n    else\n    {\n        nanosecondCountOfDay = 0 ;\n    }\n\n    Uint32 nanosecond = nanosecondCountOfDay ;\n\n    if (millisecond == 1000)\n    {\n        second++ ;\n        millisecond = 0 ;\n    }\n\n    if (second == 60)\n    {\n        minute++ ;\n        second = 0 ;\n    }\n\n    if (minute == 60)\n    {\n        hours++ ;\n        minute = 0 ;\n    }\n\n    if (hours == 24)\n    {\n\n        day++ ;\n        hours = 0 ;\n\n        if (day > 28)\n        {\n            throw ostk::core::error::RuntimeError(\"Implementation error.\") ;\n        }\n\n    }\n\n    return DateTime(year, month, day, hours, minute, second, millisecond, microsecond, nanosecond) ;\n\n}\n\nDateTime                        DateTime::ModifiedJulianDate                (   const   Real&                       aModifiedJulianDate                         )\n{\n\n    if (!aModifiedJulianDate.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Modified Julian Date\") ;\n    }\n\n    if (aModifiedJulianDate < 0.0)\n    {\n        throw ostk::core::error::RuntimeError(\"Modified Julian Date [{}] is negative.\", aModifiedJulianDate) ;\n    }\n\n    return DateTime::JulianDate(DateTime::JulianDateFromModifiedJulianDate(aModifiedJulianDate)) ;\n\n}\n\nDateTime                        DateTime::Parse                             (   const   String&                     aString,\n                                                                                const   DateTime::Format&           aFormat                                     )\n{\n\n    if (aString.isEmpty())\n    {\n        throw ostk::core::error::runtime::Undefined(\"String\") ;\n    }\n\n    switch (aFormat)\n    {\n\n        case DateTime::Format::Undefined: // Automatic format detection\n        {\n\n            if (aString.match(std::regex(\"^([-]?[0-9]+-[0-9]{2}-[0-9]{2})T([0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\\\.[0-9]{1,9})?)$\")))\n            {\n                return DateTime::Parse(aString, DateTime::Format::ISO8601) ;\n            }\n\n            if (aString.match(std::regex(\"^([\\\\d]{1,2} [\\\\w]{3} [\\\\d]{4}) ([0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\\\.[0-9]{1,9})?)$\")))\n            {\n                return DateTime::Parse(aString, DateTime::Format::STK) ;\n            }\n\n            return DateTime::Parse(aString, DateTime::Format::Standard) ;\n\n        }\n\n        case DateTime::Format::Standard:\n        {\n\n            boost::smatch match ;\n\n            if (boost::regex_match(aString, match, boost::regex(\"^([-]?[0-9]+-[0-9]{2}-[0-9]{2}) ([0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\\\.[0-9]{1,3})?(?:\\\\.[0-9]{1,3})?(?:\\\\.[0-9]{1,3})?)$\")))\n            {\n                return DateTime(Date::Parse(String(match[1]), Date::Format::Standard), Time::Parse(String(match[2]), Time::Format::Standard)) ;\n            }\n            else\n            {\n                throw ostk::core::error::RuntimeError(\"Cannot parse [Standard] date-time string [{}].\", aString) ;\n            }\n\n        }\n\n        case DateTime::Format::ISO8601:\n        {\n\n            boost::smatch match ;\n\n            if (boost::regex_match(aString, match, boost::regex(\"^([-]?[0-9]+-[0-9]{2}-[0-9]{2})T([0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\\\.[0-9]{1,9})?)$\")))\n            {\n                return DateTime(Date::Parse(String(match[1]), Date::Format::Standard), Time::Parse(String(match[2]), Time::Format::ISO8601)) ;\n            }\n            else\n            {\n                throw ostk::core::error::RuntimeError(\"Cannot parse [ISO 8601] date-time string [{}].\", aString) ;\n            }\n\n        }\n\n        case DateTime::Format::STK:\n        {\n\n            boost::smatch match ;\n\n            if (boost::regex_match(aString, match, boost::regex(\"^([\\\\d]{1,2} [\\\\w]{3} [\\\\d]{4}) ([0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\\\.[0-9]{1,9})?)$\")))\n            {\n                return DateTime(Date::Parse(String(match[1]), Date::Format::STK), Time::Parse(String(match[2]), Time::Format::ISO8601)) ;\n            }\n            else\n            {\n                throw ostk::core::error::RuntimeError(\"Cannot parse [STK] date-time string [{}].\", aString) ;\n            }\n\n        }\n\n        default:\n            throw ostk::core::error::runtime::Wrong(\"Format\") ;\n            break ;\n\n    }\n\n    return DateTime::Undefined() ;\n\n}\n\nReal                            DateTime::ModifiedJulianDateFromJulianDate  (   const   Real&                       aJulianDate                                 )\n{\n    return aJulianDate - 2400000.5 ; // MJD = JD - 2400000.5 [day]\n}\n\nReal                            DateTime::JulianDateFromModifiedJulianDate  (   const   Real&                       aModifiedJulianDate                         )\n{\n    return aModifiedJulianDate + 2400000.5 ; // JD = MJD + 2400000.5 [day]\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n}\n}\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "289dd1d67dfce41f0da1e7dce8b6de06017f4ae5", "size": 18039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OpenSpaceToolkit/Physics/Time/DateTime.cpp", "max_stars_repo_name": "robinpdm/open-space-toolkit-physics", "max_stars_repo_head_hexsha": "b53e5d4287fa6568d700cb8942c9a56d57b8d7cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T06:47:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T03:36:52.000Z", "max_issues_repo_path": "src/OpenSpaceToolkit/Physics/Time/DateTime.cpp", "max_issues_repo_name": "robinpdm/open-space-toolkit-physics", "max_issues_repo_head_hexsha": "b53e5d4287fa6568d700cb8942c9a56d57b8d7cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-06-25T08:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-05T20:34:02.000Z", "max_forks_repo_path": "src/OpenSpaceToolkit/Physics/Time/DateTime.cpp", "max_forks_repo_name": "robinpdm/open-space-toolkit-physics", "max_forks_repo_head_hexsha": "b53e5d4287fa6568d700cb8942c9a56d57b8d7cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-19T22:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-19T22:44:23.000Z", "avg_line_length": 34.1647727273, "max_line_length": 184, "alphanum_fraction": 0.4495260269, "num_tokens": 4315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.0453525760382107, "lm_q1q2_score": 0.012906254869880196}}
{"text": "//   -----------------------------------------------------------------------------------------------\n//    Copyright 2015 André Bergner. Distributed under the Boost Software License, Version 1.0.\n//     (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//      --------------------------------------------------------------------------------------------\n\n#pragma once\n\n#include <iostream>\n#include <array>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/min_max.hpp>\n#include <boost/typeof/typeof.hpp>\n#include <boost/proto/core.hpp>\n#include <boost/proto/context.hpp>\n#include <boost/proto/transform.hpp>\n#include <boost/proto/debug.hpp>\n\n#include <boost/algorithm/string/erase.hpp>\n\n#include \"callable_decltype.hpp\"\n#include \"tuple_tools.hpp\"\n#include \"demangle.h\"\n\n\n\nnamespace flowz\n{\n\n\n\nnamespace mpl = boost::mpl;\nnamespace proto = boost::proto;\n\n\n\nnamespace building_blocks\n{\n   using namespace proto;\n\n   //  ---------------------------------------------------------------------------------------------\n   // copy_domain -- all flowz expressions should be hold by value to avoid dangling references\n   //  ---------------------------------------------------------------------------------------------\n\n\n   template< typename E >\n   struct copy_expr;\n\n   struct copy_generator : proto::pod_generator< copy_expr > {};\n\n   struct copy_domain : proto::domain< copy_generator >\n   {\n      template < typename T >\n      struct as_child : proto_base_domain::as_expr<T> {};\n   };\n\n   template< typename Expr >\n   struct copy_expr\n   {\n      BOOST_PROTO_EXTENDS( Expr, copy_expr<Expr>, copy_domain )\n   };\n\n\n   //  ---------------------------------------------------------------------------------------------\n   // definition of the building blocks of the language\n   //  ---------------------------------------------------------------------------------------------\n\n   template< typename X >\n   auto make_terminal( X x )\n   {\n      return  make_expr<tag::terminal,copy_domain>(x);\n   }\n\n\n   template < typename I >  struct placeholder       { using arity = I; };\n   template < typename T >  struct placeholder_arity { using type = typename T::arity; };\n\n   template< int n >\n   auto make_placeholder()\n   {\n      return  make_expr<tag::terminal, copy_domain>( placeholder< mpl::int_<n> >{} );\n   }\n\n   template < typename idx = _ >\n   using delayed_placeholder = subscript< terminal<placeholder<idx>> , terminal<placeholder<_>> >;\n\n   //  ---------------------------------------------------------------------------------------------\n   // block composition operators -- TODO needs correct grammar as arguments\n\n   using channel_operator  = comma              < _ , _ >;\n   using parallel_operator = bitwise_or         < _ , _ >;\n   using sequence_operator = bitwise_or_assign  < _ , _ >;\n   using feedback_operator = complement         < _ >;\n\n   // private nodes\n\n   struct binary_feedback_tag {};\n   using binary_feedback_operator = binary_expr< binary_feedback_tag , _ , _ >;\n\n   template < typename LeftExpr , typename RightExpr >\n   auto make_binary_feedback( LeftExpr const & l , RightExpr const & r )\n   {  return make_expr<building_blocks::binary_feedback_tag>( l, r );  }\n}\n\nusing building_blocks :: make_terminal;\n\nusing building_blocks :: placeholder;\nusing building_blocks :: placeholder_arity;\nusing building_blocks :: make_placeholder;\nusing building_blocks :: delayed_placeholder;\n\nusing building_blocks :: channel_operator;\nusing building_blocks :: sequence_operator;\nusing building_blocks :: parallel_operator;\nusing building_blocks :: feedback_operator;\nusing building_blocks :: binary_feedback_operator;\nusing building_blocks :: make_binary_feedback;\n\n\nBOOST_PROTO_DEFINE_ENV_VAR( current_input_t, current_input );\nBOOST_PROTO_DEFINE_ENV_VAR( delayed_input_t, delayed_input );\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// very simple delay_line operation on std::array --> TODO should be own type static_delay_line !\n\nstruct no_state {};\n\nstruct\n{\n    template< typename T , size_t N , typename Y >\n    void operator()( std::array<T,N>& xs , Y y ) const\n    {\n        for ( size_t n = 1 ; n < xs.size() ; ++n )  xs[n-1] = xs[n];\n        xs.back() = y;\n    }\n\n    template< typename T , typename Y >\n    void operator()( std::array<T,0>& , Y ) const { }\n\n    template< typename T , typename Y >\n    void operator()( no_state , Y ) const { }\n\n    template< typename T , typename Y >   // if input is not an array, e.g. for not fully\n    void operator()( T& , Y ) const { }   // unpacked state while traversing the tree (tuple o'tuples)\n}\nrotate_push_back;\n\n\n\nnamespace transforms\n{\n   using namespace proto;\n\n   //  ---------------------------------------------------------------------------------------------\n   // static analysis transforms  --  helpers that inspect structure of expression\n   //  ---------------------------------------------------------------------------------------------\n\n   struct output_arity;\n\n   struct input_arity : or_\n   <  when\n      <  delayed_placeholder<>\n      ,  placeholder_arity<_value(_left)>()\n      >\n   ,  when\n      <  terminal< placeholder<_> >\n      ,  placeholder_arity<_value>()\n      >\n   ,  when\n      <  terminal<_>\n      ,  mpl::int_<0>()\n      >\n   ,  when\n      <  feedback_operator\n      ,  mpl::max\n         <  mpl::int_<0>\n         ,  mpl::minus< input_arity(_child) , output_arity(_child) >\n         >()\n      >\n   ,  when\n      <  binary_feedback_operator\n      ,  mpl::plus\n         <  mpl::max\n            <  mpl::int_<0>\n            ,  mpl::minus< input_arity(_left) , output_arity(_right) >\n            >\n         ,  mpl::max\n            <  mpl::int_<0>\n            ,  mpl::minus< input_arity(_right) , output_arity(_left) >\n            >\n         >()\n      >\n   ,  when\n      <  parallel_operator\n      ,  mpl::plus< input_arity(_left) , input_arity(_right) >()\n      >\n   ,  when\n      <  sequence_operator\n      ,  mpl::plus\n         <  input_arity(_left)\n         ,  mpl::max\n            <  mpl::int_<0>\n            ,  mpl::minus< input_arity(_right) , output_arity(_left) >\n            >\n         >()\n      >\n   ,  when\n      <  nary_expr<_, vararg<_>>\n      ,  fold<_, mpl::int_<0>(), mpl::max<input_arity, _state>()>\n      >\n   >\n   {};\n\n\n   struct output_arity : or_\n   <  when\n      <  channel_operator\n      ,  mpl::plus< output_arity(_left) , output_arity(_right) >()\n      >\n   ,  when\n      <  feedback_operator\n      ,  output_arity(_child)\n      >\n   ,  when\n      <  binary_feedback_operator\n      ,  output_arity(_right)\n      >\n   ,  when\n      <  parallel_operator\n      ,  mpl::plus< output_arity(_left) , output_arity(_right) >()\n      >\n   ,  when\n      <  sequence_operator\n      ,  mpl::plus\n         <  output_arity(_right)\n         ,  mpl::max\n            <  mpl::int_<0>\n            ,  mpl::minus< output_arity(_left) , input_arity(_right) >\n            >\n         >()\n      >\n   ,  otherwise< mpl::int_<1>() >\n   >\n   {};\n\n\n   template < typename Expr >\n   using input_arity_t = typename boost::result_of<input_arity(Expr)>::type;\n\n   template < typename Expr >\n   using output_arity_t = typename boost::result_of<output_arity(Expr)>::type;\n\n\n   // -------------------------------------------------------------------------------------------\n   // front-panel for the expressions -- collects all loose wires\n   // -------------------------------------------------------------------------------------------\n\n\n   template < std::size_t N >\n   inline auto make_front()\n   {\n      return make_front<N-1>() | make_placeholder<1>();\n   }\n\n   template <>\n   inline auto make_front<1>()\n   {\n      return make_placeholder<1>();\n   }\n\n   template < typename Expr >\n   auto add_front_panel( Expr const & x )\n   {\n      return  make_front<input_arity_t<Expr>::value>() |= x;\n   }\n\n\n\n\n   // -------------------------------------------------------------------------------------------\n   // state and wire related tuple tools\n   // -------------------------------------------------------------------------------------------\n\n   template < typename arity , typename delay , typename base_other >\n   struct make_arity_impl\n   {\n      using type = tuple_cat_t< repeat_t< arity::value-1ul, base_other >\n                              , std::tuple<delay>\n                              >;\n   };\n\n   template < typename delay , typename base_other >\n   struct make_arity_impl<mpl::int_<0>, delay, base_other>\n   {\n      using type = std::tuple<>;\n   };\n\n   template < typename arity , typename delay = mpl::int_<0>, typename base_other = mpl::int_<0> >\n   using make_arity = typename make_arity_impl<arity,delay,base_other>::type;\n\n\n   struct delay_per_wire : callable_decltype\n   {\n      using default_t = placeholder<mpl::int_<0>>;\n\n      template < typename Placeholder = default_t , typename Delay = default_t>\n      auto operator()( Placeholder const & = default_t{}, Delay const & = default_t{} ) const\n      {\n         return make_arity<typename Placeholder::arity, typename Delay::arity>{};\n      }\n   };\n\n\n   struct delay_per_wire_2 : callable_decltype\n   {\n      using default_t = placeholder<mpl::int_<0>>;\n\n      template < typename Placeholder = default_t , typename Delay = default_t>\n      auto operator()( Placeholder const & = default_t{}, Delay const & = default_t{} ) const\n      {\n         return make_arity<typename Placeholder::arity, typename Delay::arity, mpl::int_<-1>>{};\n      }\n   };\n\n\n\n   struct tuple_cat_fn : callable_decltype\n   {\n      template < typename... Tuples >\n      auto operator()( Tuples&&... ts ) const\n      {\n         return std::tuple_cat( std::forward<Tuples>(ts)... );\n      }\n   };\n\n   struct make_tuple_fn : callable_decltype\n   {\n      template < typename... Ts >\n      auto operator()( Ts&&... ts ) const\n      {\n         return std::make_tuple( std::forward<Ts>(ts)... );\n      }\n   };\n\n   // -------------------------------------------------------------------------------------------\n   // max-zip tuple\n   // -------------------------------------------------------------------------------------------\n\n   template < typename Tuple1, typename Tuple2, std::size_t... Ns >\n   auto zip_with_max( Tuple1&& t1, Tuple2&& t2, std::index_sequence<Ns...> )\n   {\n      using namespace std;\n      return tuple< typename mpl::max< decay_t<decltype(get<Ns>(t1))> , decay_t<decltype(get<Ns>(t2))> >::type... >{};\n   }\n\n   template < typename Tuple1, typename Tuple2 >\n   auto zip_with_max( Tuple1&&, Tuple2&&, std::index_sequence<> )\n   {\n      return std::tuple<>{};\n   }\n\n   struct max_delay_of_wires : callable_decltype\n   {\n      template < typename Tuple_l , typename Tuple_r >\n      auto operator()( Tuple_l&& tl, Tuple_r&& tr ) const\n      {\n         using tuple_tl = std::decay_t<Tuple_l>;\n         using tuple_tr = std::decay_t<Tuple_r>;\n         using min_size = typename mpl::min< mpl::int_<std::tuple_size<tuple_tl>::value>\n                                           , mpl::int_<std::tuple_size<tuple_tr>::value>\n                                           >::type;\n         return  std::tuple_cat(  zip_with_max(tl,tr,std::make_index_sequence<min_size::value>{})\n                               ,  tuple_drop<min_size::value>( std::forward<Tuple_l>(tl) )\n                               ,  tuple_drop<min_size::value>( std::forward<Tuple_r>(tr) )\n                               );\n      }\n   };\n\n\n\n\n   template < int n , int m >\n   using map_min = mpl::int_< n == -1 ? m : m == -1 ? n : (n<m)?n:m >;\n   // -1 ,  m  ->  m\n   //  n , -1  ->  n\n   //  n ,  m  ->  min(n,m)\n\n   template < typename Tuple1, typename Tuple2, std::size_t... Ns >\n   auto zip_with_min( Tuple1&& t1, Tuple2&& t2, std::index_sequence<Ns...> )\n   {\n      using namespace std;\n      return tuple< map_min< decay_t<decltype(get<Ns>(t1))>::value , decay_t<decltype(get<Ns>(t2))>::value >... >{};\n   }\n\n   template < typename Tuple1, typename Tuple2 >\n   auto zip_with_min( Tuple1&&, Tuple2&&, std::index_sequence<> )\n   {\n      return std::tuple<>{};\n   }\n\n   struct min_delay_of_wires : callable_decltype\n   {\n      template < typename Tuple_l , typename Tuple_r >\n      auto operator()( Tuple_l&& tl, Tuple_r&& tr ) const\n      {\n         using tuple_tl = std::decay_t<Tuple_l>;\n         using tuple_tr = std::decay_t<Tuple_r>;\n         using min_size = typename mpl::min< mpl::int_<std::tuple_size<tuple_tl>::value>\n                                           , mpl::int_<std::tuple_size<tuple_tr>::value>\n                                           >::type;\n         return  std::tuple_cat(  zip_with_min(tl,tr,std::make_index_sequence<min_size::value>{})\n                               ,  tuple_drop<min_size::value>( std::forward<Tuple_l>(tl) )\n                               ,  tuple_drop<min_size::value>( std::forward<Tuple_r>(tr) )\n                               );\n      }\n   };\n\n\n\n\n\n\n   struct tuple_take_ : callable_decltype\n   {\n      template< typename Drop , typename Tuple >\n      decltype(auto) operator()( Drop , Tuple const & t ) const\n      {\n         return tuple_take<Drop::value>(t);\n      }\n   };\n\n   struct tuple_drop_ : callable_decltype\n   {\n      template< typename Drop , typename Tuple >\n      decltype(auto) operator()( Drop , Tuple&& t ) const\n      {\n         return tuple_drop<Drop::value>( std::forward<Tuple>(t) );\n      }\n   };\n\n   template < typename Generator , typename Combiner >\n   struct input_delays\n   {\n      struct apply : or_\n      <  when\n         <  delayed_placeholder<>\n         ,  Generator( _value(_left) , _value(_right) )\n         >\n      ,  when\n         <  terminal< placeholder<_> >\n         ,  Generator( _value() )\n         >\n      ,  when\n         <  terminal<_>\n         ,  std::tuple<>()\n         >\n      ,  when\n         <  feedback_operator\n         ,  tuple_drop_\n            (  output_arity(_child)\n            ,  apply(_child)\n            )\n         >\n      ,  when\n         <  binary_feedback_operator\n         ,  tuple_cat_fn\n            (  tuple_drop_\n               (  output_arity(_right)\n               ,  apply(_left)\n               )\n            ,  tuple_drop_\n               (  output_arity(_left)\n               ,  apply(_right)\n               )\n            )\n         >\n      ,  when\n         <  parallel_operator\n         ,  tuple_cat_fn( apply(_left) , apply(_right) )\n         >\n      ,  when\n         <  sequence_operator\n         ,  tuple_cat_fn\n            (  apply(_left)\n            ,  tuple_drop_\n               (  output_arity(_left)\n               ,  apply(_right)\n               )\n            )\n         >\n      ,  when\n         <  nary_expr<_, vararg<_>>\n         ,  fold<_, std::tuple<>(), Combiner(apply, _state) >\n         >\n      >\n      {};\n   };\n\n\n   using max_input_delays = typename input_delays< delay_per_wire , max_delay_of_wires >::apply;\n   using min_input_delays = typename input_delays< delay_per_wire_2 , min_delay_of_wires >::apply;\n\n   template < typename Expr >\n   using min_input_delays_t = decltype( min_input_delays{}( std::declval<Expr>() ) );\n\n\n\n\n   // -------------------------------------------------------------------------------------------\n   // state and wire related tuple tools -- type per tuple\n   // -------------------------------------------------------------------------------------------\n\n   // ResultType computes the result type for a given expression and a given input.\n\n   // Handling of feedback.\n   //\n   //    Consider the following exmaple:\n   //\n   //    ~(_1[_1] + _2 + _3)   with typeof(_2) == float and typeof(_3) == complex<double>\n   //                          --> What should be the type of _1 to be used for the delay?\n   //\n   //    Problem:  _1[_1] + _2 + _3   needs all three input types to determine its output type\n   //                                 but the output type depends on expressions result and so\n   //                                 depends the input type --> cyclic dependency\n   //    Solution:\n   //\n   //      assign temporary type 'absorber' to _1.\n   //\n   //      absorber is special type that returns for all binary operations always the other type.\n   //\n   //      unary-op absorber   → absorber\n   //      binary-op absorber T → T\n\n\n   struct absorber {};\n\n   using left_binary_absorber  = binary_expr< _ , terminal<absorber> , _ >;\n   using right_binary_absorber = binary_expr< _ , _ , terminal<absorber> >;\n\n   template <typename Transform>\n   using absorb_left = when< left_binary_absorber, Transform(_right) >;\n\n   template <typename Transform>\n   using absorb_right = when< right_binary_absorber, Transform(_left) >;\n\n\n   struct get_fn : callable_decltype\n   {\n      template < typename Tuple, int N >\n      auto operator()( Tuple&& t, mpl::int_<N> ) const\n      {\n         return std::get<N-1>(t);\n      }\n   };\n\n   struct make_flat_tuple : callable_decltype\n   {\n      template < typename T >\n      auto operator()( T&& t ) const\n      {\n         return flatten_tuple( std::forward_as_tuple(t) );\n      }\n   };\n\n   struct repeat_fn : callable_decltype\n   {\n      template < typename N, typename T >\n      auto operator()( N, T&& ) const\n      {\n         return repeat_t< N::value, std::decay_t<T> >{};\n      }\n   };\n\n   struct make_terminal : callable_decltype\n   {\n      template < typename T >\n      auto operator()( T&& x ) const\n      {\n         return proto::make_expr<proto::tag::terminal>(x);\n      }\n   };\n\n   struct ResultType : or_\n   <  or_< absorb_left<ResultType>, absorb_right<ResultType> >\n   ,  when\n      <  delayed_placeholder<>\n      ,  get_fn( _state , placeholder_arity<_value(_left)>() )\n      >\n   ,  when\n      <  terminal< placeholder<_> >\n      ,  get_fn( _state , placeholder_arity<_value>() )\n      >\n   ,  when\n      <  terminal<_>\n      ,  _value\n      >\n   ,  when\n      <  binary_feedback_operator\n         // we have to call this transform twice\n         // 1. substitutes all that depend on the recursion with the absorber type\n         // 2. removes all absorbers by merging them with their respecitve operations (absorb left/right)\n         // TODO static_assert that result must not contain any leftover absorbers,\n         //      e.g. the expression  ~(_1[_1]) will return absorber due to lacking information about\n         //           the type inside the recursion cycle. User has to resolve explicitly with\n         //           ~(_1[_1] * 1.f) for instance\n      ,  make_flat_tuple( ResultType(\n            ResultType( _right, tuple_cat_fn( repeat_fn(output_arity(_left), make_terminal(absorber())), _state ))\n         ))\n      >\n   ,  when\n      <  feedback_operator   // here same comment as for binary_feedback_operator applies\n      ,  make_flat_tuple( ResultType(\n            ResultType( _child, tuple_cat_fn( repeat_fn(output_arity(_child), make_terminal(absorber())), _state ))\n         ))\n      >\n   ,  when\n      <  sequence_operator\n      ,  tuple_cat_fn(\n            make_flat_tuple(\n               ResultType( _right, tuple_take_( input_arity(_right), make_flat_tuple(ResultType(_left)) ) )\n            )\n         ,  tuple_drop_( input_arity(_right), make_flat_tuple(ResultType(_left)) )\n         )\n      >\n   ,  when\n      <  parallel_operator\n      ,  tuple_cat_fn( make_flat_tuple(ResultType( _left, tuple_take_(input_arity(_left), _state) ) )\n                     , make_flat_tuple(ResultType( _right, tuple_drop_(input_arity(_left), _state) ) )\n                     )\n      >\n   ,  when\n      <  channel_operator\n      ,  tuple_cat_fn( make_flat_tuple(ResultType(_left))\n                     , make_flat_tuple(ResultType(_right))\n                     )\n      >\n   ,  when\n      <  _\n      ,  _default<ResultType>\n      >\n   >\n   {};\n\n\n\n   // -------------------------------------------------------------------------------------------\n   //\n   // -------------------------------------------------------------------------------------------\n\n\n   template < bool... bs >\n   struct bools {};\n\n   template < typename Tuple , typename T >\n   struct any_of_;\n\n   template < typename... Ts , typename T >\n   struct any_of_< std::tuple<Ts...> , T > : std::integral_constant\n   <  bool\n   ,  !std::is_same\n      <  bools< std::is_same<T , Ts>::value... >\n      ,  bools< !std::is_same<Ts, Ts>::value... >\n      >::value\n   >\n   {};\n\n\n   template < typename Expr >\n   using needs_direct_input = any_of_< min_input_delays_t<Expr> , mpl::int_<0> >;\n\n   template < typename Expr , std::size_t N >\n   using needs_num_direct_input = any_of_< tuple_take_t<N,min_input_delays_t<Expr>> , mpl::int_<0> >;\n\n\n\n\n   struct identity : callable_decltype\n   {\n      template < typename X >\n      auto operator()( X&& x ) { return std::forward<X>(x); }\n   };\n\n   template < typename StateCtor >\n   struct build_state_impl\n   {\n      struct apply : or_\n      <  when\n         <  feedback_operator\n         ,  make_tuple_fn\n            (  StateCtor(max_input_delays( _child ))\n            ,  apply( _child )\n            )\n         >\n      ,  when\n         <  binary_feedback_operator\n         ,  make_tuple_fn\n            (  StateCtor( tuple_take_( output_arity(_left) , max_input_delays(_right) ))\n            ,  apply( _left  )\n            ,  apply( _right )\n            )\n         >\n      ,  when\n         <  sequence_operator\n         ,  make_tuple_fn\n            (  StateCtor( tuple_take_( output_arity(_left) , max_input_delays(_right) ))\n            ,  apply( _left  )\n            ,  apply( _right )\n            )\n         >\n      ,  when\n         <  parallel_operator\n         ,  make_tuple_fn\n            (  apply( _left  )\n            ,  apply( _right )\n            )\n         >\n      ,  otherwise< std::tuple<>() >\n      >\n      {};\n   };\n\n   template < typename StateCtor = identity >\n   using build_state = typename build_state_impl<StateCtor>::apply;\n\n\n   //  ---------------------------------------------------------------------------------------------\n   // Evaluators -- transforms that work together for the evaluation of flowz-expressions\n   //  ---------------------------------------------------------------------------------------------\n\n   struct place_the_holder;\n   struct place_delay;\n   struct sequence;\n   struct feedback;\n   struct binary_feedback;\n   struct parallel;\n\n\n   struct eval_it : or_\n   <  when\n      <  delayed_placeholder<>\n      ,  place_delay( _value(_left) , _value(_right) , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  terminal< placeholder<_> >\n      ,  place_the_holder( _value , _env_var<current_input_t> )\n      >\n   ,  when\n      <  feedback_operator\n      ,  feedback( _child , _env_var<current_input_t> , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  binary_feedback_operator\n      ,  binary_feedback( _left , _right, _env_var<current_input_t> , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  sequence_operator\n      ,  sequence( _left , _right , _env_var<current_input_t> , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  parallel_operator\n      ,  parallel( _left , _right , _env_var<current_input_t> , _env_var<delayed_input_t> )\n      >\n   ,  when\n      <  channel_operator    //  grammar rule: only allowed after sequence or recursion at top of sub-tree\n      ,  make_tuple_fn( eval_it(_left), eval_it(_right) )\n      >\n   ,  when\n      <  _\n      ,  _default< eval_it >\n      >\n   >\n   {};\n\n\n   //-----------------------------------------------------------------------------------------------\n\n\n   template < typename T >\n   using in_t = T const &;\n   //using in_t = T;\n\n   //  ---------------------------------------------------------------------------------------------\n   // expression rebuilder -- transforms unary feedback nodes into binary ones\n   //  ---------------------------------------------------------------------------------------------\n\n   // example: a*_1 |= _1 + _2 |= _1[_1]   -->  future_expr: a*_1 |= _1 + _2\n\n   //  ~( _1 |= ~(a*_1[_1]+_2[_1]) )\n\n   struct split_future_subexpr;\n\n   struct make_canonical : or_\n   <  when\n      <  terminal<_>\n      ,  _\n      >\n   ,  when\n      <  feedback_operator\n      ,  split_future_subexpr( _child )\n      >\n   ,  otherwise< _default<make_canonical> >\n   >\n   {};\n\n\n   struct split_in_sequence_combinator;\n   struct lifted_default;\n\n   struct unary_to_binary_feedback : or_\n   <  when\n      <  terminal<_>\n      ,  make_tuple_fn(_)\n      >\n   ,  when\n      <  sequence_operator\n      ,  split_in_sequence_combinator( _left , _right , _state )\n      >\n   ,  when\n      <  _\n      ,  lifted_default( _ , _state )\n      >\n   >\n   {};\n\n   struct lifted_default : callable_decltype\n   {\n      template< typename Expr , typename State , std::size_t... Ns >\n      auto apply( std::index_sequence<Ns...> , Expr const & x , State const & s ) const\n      {\n         using  tag = typename tag_of<Expr>::type;\n         unary_to_binary_feedback   e;\n         auto res = std::make_tuple( e(child_c<Ns>(x),s)... );\n         return std::tuple_cat( std::make_tuple( make_expr<tag>( std::get<0>(std::get<Ns>(res))... ) )\n                              , tail(std::get<0>(res))\n                              );\n      }\n\n      template< typename Expr, typename State >\n      auto operator()( Expr const & e , State const & s ) const\n      {\n         using idx_seq = std::make_index_sequence< proto::arity_of<Expr>::value >;\n         return apply( idx_seq{}, e , s );\n      }\n   };\n\n\n\n   // TODO\n   // • in compile: transform expression into new expression w/ binary feedback node\n   // • handle expr w/o future part, e.g. _1[_1] |= _1[_1] -->  (expr,())\n   // • needs_direct_input must be parametrized prev. output arity\n   // • handle parallel combiner, e.g. (_1 |= _1[_1]) | (_1 |= _1[_1]) should work (diff. split point)\n   // • handle expr w/o current part, e.g. _1 |= _1 -->  ((),expr) compile error\n   // • nested recursion:\n   //   - idea: trafo1 -> go down and rebuild expr\n   //                   , when in first (i.e. deepest) una_feedback call rebuild-splitter\n   //                   , return this expr\n   //                   , what to do with bin_feeback?\n\n   struct split_future_subexpr : callable_decltype\n   {\n      template < typename Expr >\n      auto operator()( in_t<Expr> x ) const\n      {\n         make_canonical  t;\n         unary_to_binary_feedback  e;\n         auto split_pred = [](auto const & l, auto const & r)\n         {\n            using l_expr_t = decltype(l);\n            using r_expr_t = decltype(r);\n            return needs_num_direct_input<r_expr_t,output_arity_t<l_expr_t>::value>{};\n         };\n         //return impl( e(t(add_front_panel(x)), split_pred) );\n         return impl( e(t(make_front<output_arity_t<Expr>::value>() |= x), split_pred) );\n      }\n\n      template < typename LiftedExpr >\n      auto impl( in_t<LiftedExpr> x ) const\n      {\n         return make_binary_feedback( std::get<0>(x), std::get<1>(x) );\n      }\n   };\n\n\n   struct split_in_sequence_combinator : callable_decltype\n   {\n      template < typename LeftExpr , typename RightExpr , typename State >\n      auto operator()( in_t<LeftExpr> l , in_t<RightExpr> r , State const & s ) const\n      {\n         unary_to_binary_feedback  e;\n         return impl( e(l,s), r, s );\n      }\n\n   private:\n\n      template < typename LL , typename LR , typename R , typename Pred >\n      auto impl( in_t<std::tuple<LL,LR>> l , in_t<R> r , in_t<Pred> p ) const\n      {\n         return std::make_tuple( std::get<0>(l), std::get<1>(l) |= r );\n      }\n\n      template < typename L , typename R , typename Pred >\n      auto impl( in_t<std::tuple<L>> l , in_t<R> r , in_t<Pred> p ) const\n      {\n         return impl2( p(std::get<0>(l),r), l, r, p );\n      }\n\n      template < typename L , typename R , typename P >\n      auto impl2( std::true_type , in_t<L> l , in_t<R> r , in_t<P> p ) const\n      {\n         unary_to_binary_feedback  e;\n         return impl3( l , e(r,p) );\n      }\n\n      template < typename LeftExpr , typename RL , typename RR >\n      auto impl3( in_t<LeftExpr> l , in_t<std::tuple<RL,RR>> r ) const\n      {\n         return std::make_tuple( std::get<0>(l) |= std::get<0>(r) , std::get<1>(r) );\n      }\n\n      template < typename LeftExpr , typename R >\n      auto impl3( in_t<LeftExpr> l , in_t<std::tuple<R>> r ) const\n      {\n         return std::make_tuple( std::get<0>(l) |= std::get<0>(r) );\n      }\n\n      template < typename L , typename RightExpr , typename P >\n      auto impl2( std::false_type , in_t<L> l , in_t<RightExpr> r , in_t<P> ) const\n      {\n         return std::make_tuple( std::get<0>(l) , r );\n      }\n\n   };\n\n\n   //-----------------------------------------------------------------------------------------------\n\n\n   struct place_the_holder : callable_decltype\n   {\n      template < typename I , typename Tuple >\n      auto operator()( placeholder<I> const & , Tuple const & args ) const\n      {\n         return std::get<I::value-1>( args );\n      }\n   };\n\n   struct place_delay : callable_decltype\n   {\n      template < typename I , typename J , typename Delayed_input >\n      auto operator()( placeholder<I> , placeholder<J> , in_t<Delayed_input> del_in ) const\n      {\n         auto const & s = std::get<I::value-1>(std::get<0>(del_in));\n         return s[s.size()-J::value];\n      }\n   };\n\n   struct sequence : callable_decltype\n   {\n      template < typename LeftExpr , typename RightExpr , typename Input , typename State >\n      auto operator()( in_t<LeftExpr> l , in_t<RightExpr> r , in_t<Input> input , State state ) const\n      {\n         eval_it  e;\n\n         auto in_state    = deep_tie(std::get<0>(state));\n         auto node_state  = deep_tie(std::get<0>(std::get<1>(state)));\n         auto left_state  = deep_tie(std::get<1>(std::get<1>(state)));\n         auto right_state = deep_tie(std::get<2>(std::get<1>(state)));\n\n         //static_assert( std::tuple_size<Input>::value == std::tuple_size<decltype(in_state)>::value );\n\n         auto left_delayed_input = tuple_take<input_arity_t<LeftExpr>::value>(in_state);\n\n         auto left_result =\n            flatten_tuple( std::make_tuple(\n               e( l, 0, ( current_input = tuple_take<input_arity_t<LeftExpr>::value>(input)\n                        , delayed_input = std::tie( left_delayed_input, left_state )\n                        ))\n            ));\n\n         using left_size = std::tuple_size<decltype(left_result)>;\n         auto right_input = tuple_cat( left_result, tuple_drop<input_arity_t<LeftExpr>::value>(input) );\n         auto right_delayed_input = std::tuple_cat( node_state , tuple_drop<input_arity_t<LeftExpr>::value>(in_state) );\n\n         auto right_result =\n            flatten_tuple( std::make_tuple(\n               e( r, 0, ( current_input = right_input\n                        , delayed_input = std::tie( right_delayed_input, right_state )\n                        ))\n            ));\n\n         tuple_for_each( rotate_push_back, node_state, left_result );\n\n         return tuple_cat( right_result\n                         , tuple_drop< input_arity_t<RightExpr>::value >( std::move(left_result) )\n                         , tuple_drop< input_arity_t<LeftExpr>::value + left_size::value >( input )\n                         );\n      }\n   };\n\n\n   struct bottom_type {};\n\n   struct feedback : callable_decltype\n   {\n      template < typename Expr , typename Input , typename State >\n      auto operator()( in_t<Expr> x , in_t<Input> input , State state ) const\n      {\n         eval_it  e;\n\n         auto in_state    = deep_tie(std::get<0>(state));\n         auto node_state  = deep_tie(std::get<0>(std::get<1>(state)));\n         auto child_state = deep_tie(std::get<1>(std::get<1>(state)));\n         auto next_state  = std::tuple_cat( node_state, in_state );\n\n         auto aligned_input = std::tuple_cat( repeat_t<output_arity_t<Expr>::value, bottom_type>{} , input );\n         auto result =\n            flatten_tuple( std::make_tuple(\n               e( x, 0, ( current_input = aligned_input , delayed_input = std::tie(next_state,child_state) ))\n            ));\n\n\n         tuple_for_each( rotate_push_back, node_state, std::tuple_cat( result, input) );\n         using size = std::tuple_size<decltype(result)>;\n         return tuple_cat( result, tuple_drop<size::value>(input) );\n      }\n   };\n\n   struct binary_feedback : callable_decltype\n   {\n      template < typename LeftExpr , typename RightExpr , typename Input , typename State >\n      auto operator()( in_t<LeftExpr> l , in_t<RightExpr> r , in_t<Input> input , State state ) const\n      {\n         eval_it  e;\n\n         auto in_state    = deep_tie(std::get<0>(state));\n         auto node_state  = deep_tie(std::get<0>(std::get<1>(state)));\n         auto left_state  = deep_tie(std::get<1>(std::get<1>(state)));\n         auto right_state = deep_tie(std::get<2>(std::get<1>(state)));\n\n         auto future_input = std::tuple_cat\n                           ( repeat_t<output_arity_t<LeftExpr>::value, bottom_type>{}\n                           //, tuple_drop< input_arity_t<LeftExpr>::value-output_arity_t<RightExpr>::value >(input) );\n                           , tuple_drop< std::min(0,input_arity_t<LeftExpr>::value-output_arity_t<RightExpr>::value) >(input) );\n                           // TODO min( 0 , drop_value )\n         auto left_delayed_input = std::tuple_cat\n               //( node_state , tuple_drop< input_arity_t<LeftExpr>::value-output_arity_t<RightExpr>::value >(in_state) );\n               ( node_state , tuple_drop< std::min(0,input_arity_t<LeftExpr>::value-output_arity_t<RightExpr>::value) >(in_state) );\n\n         auto result =\n            flatten_tuple( std::make_tuple(\n               e( r, 0, ( current_input = future_input , delayed_input = std::tie(left_delayed_input,right_state) ))\n            ));\n\n         auto promise_input = std::tuple_cat( result, tuple_take< input_arity_t<LeftExpr>::value-output_arity_t<RightExpr>::value >(input) );\n         auto right_delayed_input = std::tuple_cat\n               ( repeat_t<output_arity_t<LeftExpr>::value, no_state>{}\n               , tuple_take< input_arity_t<LeftExpr>::value-output_arity_t<RightExpr>::value >(in_state) );\n\n         auto promise_result =\n            flatten_tuple( std::make_tuple(\n               e( l, 0, ( current_input = promise_input , delayed_input = std::tie( right_delayed_input ,left_state) ))\n            ));\n\n         tuple_for_each( rotate_push_back, node_state, promise_result );\n\n         return tuple_cat( result\n                         //, tuple_drop< input_arity_t<RightExpr>::value >( std::move(left_result) )\n                         //, tuple_drop< input_arity_t<LeftExpr>::value + left_size::value >( input )\n                         );\n      }\n   };\n\n   struct parallel : callable_decltype\n   {\n      template < typename LeftExpr , typename RightExpr , typename Input , typename State >\n      auto operator()( in_t<LeftExpr> l , in_t<RightExpr> r , in_t<Input> input , State state ) const\n      {\n         eval_it  e;\n\n         auto in_state    = deep_tie(std::get<0>(state));\n         auto left_state  = deep_tie(std::get<0>(std::get<1>(state)));\n         auto right_state = deep_tie(std::get<1>(std::get<1>(state)));\n\n         auto in_state_l = tuple_take<input_arity_t<LeftExpr>::value>(in_state);\n         auto left_state_  = ( current_input = tuple_take<input_arity_t<LeftExpr>::value>(input)\n                             , delayed_input = std::tie(in_state_l,left_state)\n                             );\n\n         auto in_state_r = tuple_drop<input_arity_t<LeftExpr>::value>(in_state);\n         auto right_state_ = ( current_input = tuple_drop<input_arity_t<LeftExpr>::value>(input)\n                             , delayed_input = std::tie(in_state_r,right_state)\n                             );\n         return std::make_tuple\n                (  e( l, 0, left_state_ )\n                ,  e( r, 0, right_state_ )\n                );\n      }\n   };\n\n}\n\n\nusing  transforms :: input_arity;\nusing  transforms :: max_input_delays;\nusing  transforms :: build_state;\nusing  transforms :: input_arity_t;\nusing  transforms :: output_arity;\nusing  transforms :: eval_it;\nusing  transforms :: add_front_panel;\n\n\n//  ------------------------------------------------------------------------------------------------\n// supporting state tools\n//  ------------------------------------------------------------------------------------------------\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// lift_into_tuple  --  lifts a meta-function into a tuple,\n//                      i.e. applies it on each type in tuple, returns tuple of new types\n\ntemplate< typename F , typename Tuple >\nstruct lift_into_tuple;\n\ntemplate< typename F , typename... Ts >\nstruct lift_into_tuple< F , std::tuple<Ts...> >\n{\n    using type = std::tuple< typename F::template apply_t<Ts>... >;\n};\n\ntemplate< typename F , typename Tuple >\nusing lift_into_tuple_t = typename lift_into_tuple<F,Tuple>::type;\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// to_array  --  meta-function that maps mpl::int_<N> to array<T,N>\n\ntemplate< typename T , typename Int >\nstruct to_array_impl\n{\n   using type = std::array< T , std::decay_t<Int>::value >;\n};\n\ntemplate< typename T >\nstruct to_array_impl< T, mpl::int_<0> >\n{\n   using type = no_state;     // array<T,N> prevents empty base class optimization to kick in.\n};\n\n\ntemplate< typename T >\nstruct to_array\n{\n   template< typename Int >\n   using apply_t = typename to_array_impl<T,std::decay_t<Int>>::type;\n};\n\ntemplate < typename T >\nstruct to_array_tuple\n{\n   struct apply : proto::callable_decltype\n   {\n       template< typename Tuple >\n       auto operator()( Tuple ) { return lift_into_tuple_t< to_array<T>, Tuple > {}; }\n   };\n};\n\n\n\n//  ------------------------------------------------------------------------------------------------\n// compile  --  main function of framework\n//  • takes an expression\n//  • returns closure holding the expression and an associated context with state & ceofficients\n//  ------------------------------------------------------------------------------------------------\n\n\ntemplate\n<  typename Expression\n,  typename State\n,  size_t   arity\n>\nstruct stateful_lambda\n{\nprivate:\n\n   Expression  expr_;\n   State       state_;\n\n   template < typename... Args >\n   auto call_impl( mpl::int_<0> , Args const &... args ) -> decltype(auto)\n   {\n      std::tuple<> in_state;\n      auto in_tuple = std::tie(in_state,state_);\n      auto result = eval_it{}( expr_, 0, ( current_input = std::make_tuple(args...)\n                                         , delayed_input = in_tuple ) );\n      return flatten_tuple( std::make_tuple( result ));\n   }\n\n   template < int arg_diff , typename... Args >\n   auto call_impl( mpl::int_<arg_diff> , Args const &... args )\n   {\n      return [ args...\n             , expr = *this ]           // TODO should not be a lambda, but a type that is\n      ( auto const &... missing_args ) mutable  //      aware of the # of args (enable_if them)\n      {\n         return expr( args..., missing_args... );\n      };\n   }\n\npublic:\n\n   stateful_lambda( Expression expr ) : expr_( expr )\n   {\n      //build_state<> b;\n      //std::cout << \"• size expr:  \" << sizeof(expr_)  << std::endl;\n      //std::cout << \"• size state: \" << sizeof(state_) << std::endl;\n      //std::cout << \"• state: \";     print_state(state_);\n      ////print_state(b(expr));\n   }\n\n   template < typename... Args , typename = std::enable_if_t< sizeof...(Args) <= arity > >\n   auto operator()( Args const &... args ) -> decltype(auto)\n   {\n      return call_impl( mpl::int_< arity - sizeof...(Args) >{} , args... );\n   }\n};\n\n\nauto compile = []( auto expr_ )\n{\n   // static_assert( is_valid_expr<decltype(expr_)>::value , \"This expression is not valid.\" );\n   // TODO must not contain private expressions, yet.\n\n   using arity_t = input_arity_t<decltype(expr_)>;\n\n   transforms :: make_canonical  canonize;\n\n   auto expr = canonize( add_front_panel(expr_) );\n   using expr_t = decltype(expr);\n\n   auto builder = build_state< to_array_tuple<float>::apply >{};\n   using state_t = decltype( builder(expr) );\n\n   return stateful_lambda< expr_t, state_t, arity_t::value>{ expr };\n};\n\n\nconst auto _1 = make_placeholder<1>();\nconst auto _2 = make_placeholder<2>();\nconst auto _3 = make_placeholder<3>();\nconst auto _4 = make_placeholder<4>();\nconst auto _5 = make_placeholder<5>();\nconst auto _6 = make_placeholder<6>();\n\n\n}  // flowz\n\n", "meta": {"hexsha": "27e419e7cde8fe9ed43bdecaa29c699719a3be6f", "size": 40412, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "flowz/flowz.hpp", "max_stars_repo_name": "andre-bergner/zignal", "max_stars_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2016-02-04T20:56:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T15:51:17.000Z", "max_issues_repo_path": "flowz/flowz.hpp", "max_issues_repo_name": "andre-bergner/zignal", "max_issues_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-02-05T14:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-05T14:46:11.000Z", "max_forks_repo_path": "flowz/flowz.hpp", "max_forks_repo_name": "andre-bergner/zignal", "max_forks_repo_head_hexsha": "bdc4e29192e693f6e60f095067982f9cd70ac8f3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-20T15:27:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-09T16:34:04.000Z", "avg_line_length": 32.0221870048, "max_line_length": 141, "alphanum_fraction": 0.5383549441, "num_tokens": 9600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.043365799227540074, "lm_q1q2_score": 0.012900021807227395}}
{"text": "#include <config.h>\n#include <assert.h>\n#include <boost/concept/usage.hpp>\n#include <boost/format.hpp>\n#include <dune/common/exceptions.hh>\n#include <dune/istl/scalarproducts.hh>\n#include <dune/istl/solvers.hh>\n#include <dune/multiscale/msfem/localproblems/localoperator.hh>\n#include <dune/multiscale/problems/selector.hh>\n#include <dune/multiscale/common/df_io.hh>\n#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>\n#include <dune/multiscale/tools/misc.hh>\n#include <dune/xt/common/logging.hh>\n#include <dune/xt/common/math.hh>\n#include <dune/xt/common/memory.hh>\n#include <dune/xt/common/configuration.hh>\n#include <dune/xt/common/timings.hh>\n#include <dune/xt/common/ranges.hh>\n#include <dune/xt/common/parallel/partitioner.hh>\n#include <dune/grid/utility/partitioning/seedlist.hh>\n#include <dune/gdt/products/l2.hh>\n#include <dune/stuff/grid/walker.hh>\n#include <dune/stuff/grid/walker/functors.hh>\n#include <iterator>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include <dune/multiscale/msfem/localproblems/localgridlist.hh>\n#include <dune/multiscale/tools/misc/outputparameter.hh>\n#include \"localproblemsolver.hh\"\n\nnamespace Dune {\nnamespace Multiscale {\n\n/** \\brief define output parameters for local problems\n *  appends \"local_problems\" for path\n **/\nstruct LocalProblemDataOutputParameters : public OutputParameters\n{\npublic:\n  explicit LocalProblemDataOutputParameters(const Problem::ProblemContainer& problem);\n};\n\nLocalProblemDataOutputParameters::LocalProblemDataOutputParameters(const DMP::ProblemContainer& problem)\n  : OutputParameters(problem.config().get(\"global.datadir\", \"data\") + std::string(\"/local_problems/\"))\n{\n}\n\nLocalProblemSolver::LocalProblemSolver(const Problem::ProblemContainer& problem,\n                                       CommonTraits::SpaceType coarse_space,\n                                       LocalGridList& localgrid_list)\n  : localgrid_list_(localgrid_list)\n  , coarse_space_(coarse_space)\n  , problem_(problem)\n{\n}\n\nvoid LocalProblemSolver::solve_all_on_single_cell(\n    const MsFEMTraits::CoarseEntityType& coarseCell,\n    MsFEMTraits::LocalSolutionVectorType& all_localproblem_solutions) const\n{\n  assert(all_localproblem_solutions.size() > 0);\n\n  const bool hasBoundary = coarseCell.hasBoundaryIntersections();\n  const auto numBoundaryCorrectors = DSG::is_simplex_grid(*coarse_space_) ? 1u : 2u;\n  const auto numInnerCorrectors = all_localproblem_solutions.size() - numBoundaryCorrectors;\n\n  // clear return argument\n  for (auto& localSol : all_localproblem_solutions)\n    localSol->vector() *= 0;\n\n  const auto& local_space = all_localproblem_solutions[0]->space();\n\n  //! define the discrete (elliptic) local MsFEM problem operator\n  // ( effect of the discretized differential operator on a certain discrete function )\n  LocalProblemOperator localProblemOperator(problem_, *coarse_space_, local_space);\n\n  // right hand side vector of the algebraic local MsFEM problem\n  MsFEMTraits::LocalSolutionVectorType allLocalRHS(all_localproblem_solutions.size());\n  for (auto& it : allLocalRHS)\n    it = Dune::XT::Common::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>(local_space,\n                                                                                   \"rhs of local MsFEM problem\");\n\n  localProblemOperator.assemble_all_local_rhs(coarseCell, allLocalRHS);\n\n  for (auto i : Dune::XT::Common::value_range(all_localproblem_solutions.size())) {\n    auto& current_rhs = *allLocalRHS[i];\n    auto& current_solution = *all_localproblem_solutions[i];\n\n    // is the right hand side of the local MsFEM problem equal to zero or almost identical to zero?\n    // if yes, the solution of the local MsFEM problem is also identical to zero. The solver is getting a problem with\n    // this situation, which is why we do not solve local msfem problems for zero-right-hand-side, since we already know\n    // the result.\n    //! TODO calculating the norm has really bad performance impact, is the instability actually still there?\n    //    const auto norm = GDT::Products::L2<typename MsFEMTraits::LocalGridViewType>(current_rhs.space().grid_view())\n    //                          .induced_norm(current_rhs);\n    //    if (norm < 1e-12) {\n    //      current_solution.vector() *= 0;\n    //      MS_LOG_DEBUG << boost::format(\"Local MsFEM problem with solution zero. (corrector %d)\") % i << std::endl;\n    //      continue;\n    //    }\n\n    // don't solve local problems for boundary correctors if coarse cell has no boundary intersections\n    if (i >= numInnerCorrectors && !hasBoundary) {\n      current_solution.vector() *= 0;\n      MS_LOG_DEBUG << \"Zero-Boundary corrector.\" << std::endl;\n      continue;\n    }\n    localProblemOperator.apply_inverse(current_rhs, current_solution);\n  }\n}\n\nvoid LocalProblemSolver::solve_for_all_cells()\n{\n  const auto& grid = coarse_space_->grid_view().grid();\n  const auto coarseGridSize = grid.size(0) - grid.overlapSize(0);\n\n  MS_LOG_INFO << boost::format(\"Rank %d will solve local problems for %d coarse entities\\n\") % grid.comm().rank()\n                     % coarseGridSize;\n  DXTC_TIMINGS.start(\"msfem.local.solve_for_all_cells\");\n\n  // we want to determine minimum, average and maxiumum time for solving a local msfem problem in the current method\n  Dune::XT::Common::MinMaxAvg<double> solveTime;\n\n  const auto interior = coarse_space_->grid_view().grid().template leafGridView<InteriorBorder_Partition>();\n  typedef std::remove_const<decltype(interior)>::type InteriorType;\n  GDT::SystemAssembler<CommonTraits::SpaceType, InteriorType> walker(*coarse_space_, interior);\n  Dune::XT::Common::IndexSetPartitioner<InteriorType> ip(interior.indexSet());\n  SeedListPartitioning<typename InteriorType::Grid, 0> partitioning(interior, ip);\n\n  const std::function<void(const CommonTraits::EntityType&)> func = [&](const CommonTraits::EntityType& coarseEntity) {\n    const int coarse_index = walker.ansatz_space().grid_view().indexSet().index(coarseEntity);\n    MS_LOG_DEBUG << \"-------------------------\" << std::endl << \"Coarse index \" << coarse_index << std::endl;\n\n    // take time\n    //    DXTC_TIMINGS.start(\"msfem.local.solve_all_on_single_cell\");\n    LocalproblemSolutionManager localSolutionManager(*coarse_space_, coarseEntity, localgrid_list_);\n    // solve the problems\n    solve_all_on_single_cell(coarseEntity, localSolutionManager.getLocalSolutions());\n    //    solveTime(DXTC_TIMINGS.stop(\"msfem.local.solve_all_on_single_cell\") / 1000.f);\n\n    // save the local solutions to disk/mem\n    localSolutionManager.save();\n\n    //    DXTC_TIMINGS.resetTiming(\"msfem.local.solve_all_on_single_cell\");\n  };\n\n  walker.add(func);\n  walker.assemble(partitioning);\n\n  //! @todo The following debug-output is wrong (number of local problems may be different)\n  const auto totalTime = DXTC_TIMINGS.stop(\"msfem.local.solve_for_all_cells\") / 1000.f;\n  MS_LOG_INFO << \"Local problems solved for \" << coarseGridSize << \" coarse grid entities.\\n\"\n              //               << \"Minimum time for solving a local problem = \" << solveTime.min() << \"s.\\n\"\n              //               << \"Maximum time for solving a local problem = \" << solveTime.max() << \"s.\\n\"\n              //               << \"Average time for solving a local problem = \" << solveTime.average() << \"s.\\n\"\n              << \"Total time for computing and saving the localproblems = \" << totalTime << \"s on rank\"\n              << coarse_space_->grid_view().grid().comm().rank() << std::endl;\n} // assemble_all\n\n} // namespace Multiscale {\n} // namespace Dune {\n", "meta": {"hexsha": "567e7c798e58ffa4c6ea0197299ccc7170218fcc", "size": 7583, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dune/multiscale/msfem/localproblems/localproblemsolver.cc", "max_stars_repo_name": "wwu-numerik/DUNE-Multiscale", "max_stars_repo_head_hexsha": "db7c4520c87d61bccdc05b05c54e7e50bdfd8d14", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-17T12:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T08:54:32.000Z", "max_issues_repo_path": "dune/multiscale/msfem/localproblems/localproblemsolver.cc", "max_issues_repo_name": "wwu-numerik/DUNE-Multiscale", "max_issues_repo_head_hexsha": "db7c4520c87d61bccdc05b05c54e7e50bdfd8d14", "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/multiscale/msfem/localproblems/localproblemsolver.cc", "max_forks_repo_name": "wwu-numerik/DUNE-Multiscale", "max_forks_repo_head_hexsha": "db7c4520c87d61bccdc05b05c54e7e50bdfd8d14", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T12:00:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-17T12:00:04.000Z", "avg_line_length": 45.6807228916, "max_line_length": 120, "alphanum_fraction": 0.7127785837, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618332444287, "lm_q2_score": 0.028436035926617798, "lm_q1q2_score": 0.01288896977430322}}
{"text": "/*\n    Copyright (c) 2011-2014 University of Zurich\n    \n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n    \n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n    \n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n*/\n\n#include <plll/config.hpp>\n#include <plll/arithmetic.hpp>\n#include <plll/helper.hpp>\n#include \"myalloc.hpp\"\n#include \"buffer.hpp\"\n#include \"keccak.hpp\"\n#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <boost/thread/tss.hpp>\n#include <boost/thread.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#if (BOOST_VERSION >= 104700)\n  #include <boost/random/seed_seq.hpp>\n#endif\n\n#if defined(PLLL_INTERNAL_HR_POSIX)\n  #include <time.h>\n#endif\n\nnamespace plll\n{\n    namespace arithmetic\n    {\n#ifdef PLLL_INTERNAL__BIGINT__HELP_FINDING_PRECISION_BUGS\n        namespace internal\n        {\n            bool Real_precision_check_enabled = true;\n        };\n#endif\n        \n        void initArithmeticThreadAllocators()\n        {\n            // Sets the Thread-Local Secure Allocator as the standard allocator for GMP and MPFR.\n            \n            initTLAlloc(); // Make sure that the allocator is initialized for this thread\n            \n            mp_set_memory_functions(TLSalloc, TLSrealloc, TLSfree); // Set the GMP/MPFR allocation\n                                                                    // functions\n        }\n        \n        namespace\n        {\n            // This is not visible to other modules\n            boost::thread_specific_ptr<RealContext> g_realcontexts;\n            \n            template<typename T>\n            class ArrayStore\n            {\n            private:\n                T * d_storage;\n                \n            public:\n                ArrayStore(std::size_t n = 0)\n                    : d_storage(n ? new T[n] : NULL)\n                {\n                }\n                \n                ~ArrayStore()\n                {\n                    delete [] d_storage;\n                }\n                \n                void reset(std::size_t n)\n                {\n                    delete [] d_storage;\n                    d_storage = new T[n];\n                }\n                \n                void release()\n                {\n                    delete [] d_storage;\n                    d_storage = NULL;\n                }\n                \n                T * get()\n                {\n                    return d_storage;\n                }\n                \n                const T * get() const\n                {\n                    return d_storage;\n                }\n                \n                T & operator [] (std::size_t i)\n                {\n                    return d_storage[i];\n                }\n                \n                T & operator [] (std::size_t i) const\n                {\n                    return d_storage[i];\n                }\n            };\n        }\n        \n        RealContext & getThreadRealContext()\n        // returns context for current thread\n        {\n            if (g_realcontexts.get() == NULL)\n                g_realcontexts.reset(new RealContext(true));\n            return *g_realcontexts;\n        }\n        \n        template<typename Sponge>\n        class SpongeSeeder\n        {\n        private:\n            Sponge & d_sponge;\n            \n        public:\n            SpongeSeeder(Sponge & sponge)\n                : d_sponge(sponge)\n            {\n            }\n            \n            template<typename It>\n            void generate(It begin, It end) const\n            // For boost 1.47.0 or newer\n            {\n                while (begin != end)\n                {\n                    *begin = d_sponge.read();\n                    ++begin;\n                }\n            }\n            \n            unsigned operator () () const\n            // For boost 1.46.1 or older\n            {\n                return d_sponge.read();\n            }\n        };\n        \n        class RNGImpl\n        {\n#if (BOOST_VERSION >= 104700)\n        public:\n            enum { statelen = 312 * 8 }; // number of bytes per state\n            \n        private:\n            boost::random::mt19937_64 d_rng;\n            typedef uint64_t OutputT; // this is what d_rng() returns\n            enum { outchunks = sizeof(OutputT) }; // number of chars in OutputT\n#else\n        public:\n            enum { statelen = 624 * 4 }; // number of bytes per state\n            \n        private:\n            boost::mt19937 d_rng; // note the missing namespace random::, which is apparently not\n                                  // used here in older version of boost...\n            typedef uint32_t OutputT; // this is what d_rng() returns\n            enum { outchunks = sizeof(OutputT) }; // number of chars in OutputT\n#endif\n            \n        public:\n            inline void seed(const mpz_t & x)\n            {\n#if (BOOST_VERSION >= 104700)\n                // First, get uint32_t array\n                size_t size = mpz_size(x) * mp_bits_per_limb / 8; // first, find out size in bytes\n                size = (size + sizeof(uint32_t) - 1) / sizeof(uint32_t); // convert to number of uint32_t's\n                ArrayStore<uint32_t> buffer(size);\n                size_t s;\n                mpz_export(buffer.get(), &s, 1, sizeof(uint32_t), 0, 0, x);\n                assert(s == size);\n                // Next, generate sequence seeder\n                boost::random::seed_seq seedseq(buffer.get(), buffer.get() + size);\n                buffer.release();\n                // Seed RNG with sequence seeder\n                d_rng.seed(seedseq);\n#else\n                // First, get unsigned array\n                size_t size = mpz_size(x) * mp_bits_per_limb / 8; // first, find out size in bytes\n                size = (size + sizeof(unsigned) - 1) / sizeof(unsigned); // convert to number of unsigned's\n                ArrayStore<unsigned> buffer(size);\n                size_t s;\n                mpz_export(buffer.get(), &s, 1, sizeof(unsigned), 0, 0, x);\n                assert(s == size);\n                // Next, generate and feed sponge\n                typedef helper::keccak::DuplexSponge<1600, 1024> Sponge;\n                Sponge sponge;\n                sponge.feed(buffer.get(), buffer.get() + size);\n                buffer.release();\n                sponge.squeeze();\n                // Seed RNG with sponge seeder\n                SpongeSeeder<Sponge> seeder(sponge);\n                d_rng.seed(seeder);\n#endif\n            }\n            \n            inline void genLimbs(mpz_t & x, size_t limbs)\n            {\n                unsigned count = (limbs * mp_bits_per_limb / 8 + sizeof(OutputT) - 1) / sizeof(OutputT);\n                ArrayStore<OutputT> data(count);\n                for (unsigned i = 0; i < count; ++i)\n                    data[i] = d_rng();\n                mpz_import(x, limbs, 1, sizeof(mp_limb_t), 0, 0, data.get());\n            }\n            \n            inline void genBytes(char * dest, size_t count)\n            {\n                // \"Giant steps\"\n                while (count >= sizeof(OutputT))\n                {\n                    *((OutputT*)dest) = d_rng();\n                    dest += sizeof(OutputT);\n                    count -= sizeof(OutputT);\n                }\n                // \"Baby steps\"\n                if (count)\n                {\n                    OutputT r = d_rng();\n                    while (count)\n                    {\n                        *dest = r;\n                        ++dest;\n                        r >>= 64 / sizeof(OutputT);\n                        --count;\n                    }\n                }\n            }\n            \n            inline void genBits(mpz_t & x, size_t bits)\n            {\n                size_t limbs = (bits + mp_bits_per_limb - 1) / mp_bits_per_limb;\n                genLimbs(x, limbs);\n                // Make sure we have the right size\n                if (limbs * mp_bits_per_limb > bits)\n                    mpz_tdiv_q_2exp(x, x, limbs * mp_bits_per_limb - bits);\n            }\n            \n            inline void genRand(mpz_t & x, const mpz_t & bound)\n            {\n                assert(mpz_sgn(bound) > 0);\n                \n                size_t limbs = mpz_size(x) + 1;\n                mpz_t xx;\n                mpz_init(xx);\n                do\n                {\n                    // Generate random number (using full length of bound)\n                    genLimbs(xx, limbs);\n                    mpz_mod(x, xx, bound);\n                    if (!mpz_tstbit(xx, limbs * mp_bits_per_limb - 1))\n                        break;\n                    mpz_sub(xx, xx, x);\n                    mpz_add(xx, xx, bound);\n                }\n                while (mpz_size(xx) > limbs);\n                mpz_clear(xx);\n            }\n            \n        private:\n            static inline bool isPOT(unsigned long ul)\n            // C++ standard enforces two's complement for unsigned integer types; therefore, this\n            // works on any platform.\n            {\n                return (ul & (-ul)) == ul;\n            }\n            \n            inline unsigned long genUL()\n            {\n                if (sizeof(unsigned long) > sizeof(OutputT))\n                {\n                    unsigned long output = d_rng();\n                    for (unsigned i = 1; i < sizeof(unsigned long) / sizeof(OutputT); ++i)\n                    {\n                        output <<= (std::numeric_limits<OutputT>::digits % std::numeric_limits<unsigned long>::digits);\n                        // The only reason of the modulo is to stop GCC from producing a warning\n                        // (\"left shift count >= width of type\"), which is absurd, since in case the\n                        // warning is true, this part of the if clause will never be executed...\n                        output |= d_rng();\n                    }\n                    return output;\n                }\n                else\n                    return d_rng();\n            }\n            \n        public:\n            inline unsigned long genRand(unsigned long bound)\n            {\n                assert(bound > 0);\n                // Special case: power of 2\n                if (isPOT(bound))\n                    return genUL() & (bound - 1);\n                unsigned long v; \n                // Large?\n                if (bound > std::numeric_limits<unsigned long>::max() / 2)\n                {\n                    // General case: try until done\n                    // Expected: at most two iterations in average\n                    do\n                    {\n                        v = genUL();\n                    }\n                    while (v >= bound);\n                }\n                else\n                {\n                    // General case: try until done\n                    // Know: 2 * bound < maximal value of unsigned long\n                    unsigned long r, end = std::numeric_limits<unsigned long>::max() - bound;\n                    do\n                    {\n                        // Generate random number (using full length of bound)\n                        r = genUL();\n                        v = r % bound;\n                    }\n                    while (r - v > end);\n                }\n                return v;\n            }\n        };\n        \n        RandomNumberGenerator::RandomNumberGenerator()\n        {\n            d_state = new RNGImpl();\n        }\n        \n        RandomNumberGenerator::RandomNumberGenerator(const RandomNumberGenerator & rg)\n            : d_seed(rg.d_seed)\n        {\n            RNGImpl * other_state = reinterpret_cast<RNGImpl*>(rg.d_state);\n            d_state = new RNGImpl(*other_state);\n        }\n        \n        RandomNumberGenerator::~RandomNumberGenerator()\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            delete state;\n        }\n        \n        RandomNumberGenerator & RandomNumberGenerator::operator = (const RandomNumberGenerator & rg)\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            if (this != &rg)\n            {\n                RNGImpl * other_state = reinterpret_cast<RNGImpl*>(rg.d_state);\n                *state = *other_state;\n                d_seed = rg.d_seed;\n            }\n            return *this;\n        }\n        \n        Integer RandomNumberGenerator::getSeed() const\n        {\n            return d_seed;\n        }\n        \n        void RandomNumberGenerator::setSeed(const Integer & seed)\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            d_seed = seed;\n            state->seed(seed.d_value);\n        }\n        \n        namespace\n        {\n            boost::mutex s_rng_mutex;\n            RandomNumberGenerator * s_rng = NULL;\n        }\n        \n        static void initSeeder(double goodness)\n        {\n            if (!s_rng)\n            {\n                // Warning! This could very well be blocking, depending on the size of the system's entropy cache!\n                s_rng = new RandomNumberGenerator();\n                std::cout << \"Initializing seeder using /dev/(u)random (might be blocking)...\" << std::flush;\n                s_rng->randomizeDevRandom(false/*true*/);\n                std::cout << \" done.\\n\";\n            }\n        }\n        \n        Integer RandomNumberGenerator::createSeed()\n        // create seed from internal RNG (initialized using /dev/random)\n        {\n            Integer res;\n            s_rng_mutex.lock();\n            initSeeder(0.1);\n            res = s_rng->randomBits(RNGImpl::statelen * 8);\n            s_rng_mutex.unlock();\n            return res;\n        }\n        \n        void RandomNumberGenerator::randomizeTime()\n        {\n#if defined(PLLL_INTERNAL_HR_POSIX)\n            timespec t;\n            clock_gettime(CLOCK_REALTIME, &t);\n#else\n            time_t t = time(0);\n#endif\n            Integer seed;\n            mpz_import(seed.d_value, sizeof(t), 1, 1, 0, 0, &t);\n            setSeed(seed);\n            seed = randomBits(RNGImpl::statelen * 8);\n            setSeed(seed);\n        }\n        \n        void RandomNumberGenerator::randomizeDevRandom(double goodness)\n        // Parameter is in range [0, 1]. Decides how much is used from /dev/random and how much from /dev/urandom\n        {\n            if (goodness < 0)\n                goodness = 0;\n            else if (goodness > 1)\n                goodness = 1;\n            // Use /dev/random and /dev/urandom to initialize RNG\n            const int size = RNGImpl::statelen;\n            // Map [0,1] monotonically increasing to [0, size] such that 0.01 is mapped to 2\n            int size1 = 0.5 + ((goodness <= 0.01) ? (2 * (goodness / 0.01)) : (2 + (goodness - 0.01) / (1 - 0.01) * (size - 2)));\n            if (size1 < 0)\n                size1 = 0;\n            else if (size1 > size)\n                size1 = size;\n            // Fill the bytes\n            char bytes[size];\n            std::ifstream f;\n            if (size1 > 0)\n            {\n                f.open(\"/dev/random\");\n                f.read(bytes, size1);\n                f.close();\n            }\n            if (size1 < size)\n            {\n                f.open(\"/dev/urandom\");\n                f.read(bytes + size1, size - size1);\n                f.close();\n            }\n            // Create seed\n            Integer seed;\n            mpz_import(seed.d_value, size, 1, 1, 0, 0, bytes);\n            setSeed(seed);\n        }\n        \n        void RandomNumberGenerator::initializeSeeder(double goodness)\n        // Can (optionally) be called so that the seeder is ready when randomizeSeed() is called\n        {\n            if (!s_rng)\n            {\n                s_rng_mutex.lock();\n                initSeeder(goodness);\n                s_rng_mutex.unlock();\n            }\n        }\n        \n        void RandomNumberGenerator::randomizeSeed()\n        {\n            setSeed(createSeed());\n        }\n        \n        void RandomNumberGenerator::random(Integer & r, const Integer & bound)\n        // returns a random integer x with 0 <= x < bound\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            state->genRand(r.d_value, bound.d_value);\n        }\n        \n        Integer RandomNumberGenerator::random(const Integer & bound)\n        // returns a random integer x with 0 <= x < bound\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            Integer r;\n            state->genRand(r.d_value, bound.d_value);\n            return r;\n        }\n        \n        unsigned long RandomNumberGenerator::random(unsigned long bound)\n        // returns a random integer x with 0 <= x < bound\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            return state->genRand(bound);\n        }\n        \n        void RandomNumberGenerator::randomBits(void * dest, unsigned long size)\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            state->genBytes(reinterpret_cast<char*>(dest), size);\n        }\n        \n        void RandomNumberGenerator::randomBits(Integer & r, unsigned long bits)\n        // returns a random integer x with 0 <= x < 2^bits\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            state->genBits(r.d_value, bits);\n        }\n        \n        Integer RandomNumberGenerator::randomBits(unsigned long bits)\n        // returns a random integer x with 0 <= x < 2^bits\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            Integer r;\n            state->genBits(r.d_value, bits);\n            return r;\n        }\n        \n        void RandomNumberGenerator::randomLen(Integer & r, unsigned long bits)\n        // returns a random integer x with 2^(bits-1) <= x < 2^bits\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            if (bits)\n            {\n                if (bits > 1)\n                    state->genBits(r.d_value, bits - 1);\n                setbit(r, bits - 1, true);\n            }\n            else\n                setZero(r);\n        }\n        \n        Integer RandomNumberGenerator::randomLen(unsigned long bits)\n        // returns a random integer x with 2^(bits-1) <= x < 2^bits\n        {\n            RNGImpl * state = reinterpret_cast<RNGImpl*>(d_state);\n            Integer r;\n            if (bits)\n            {\n                if (bits > 1)\n                    state->genBits(r.d_value, bits - 1);\n                setbit(r, bits - 1, true);\n            }\n            return r;\n        }\n        \n        void RandomNumberGenerator::randomUniform(Real & r)\n        // generates a uniform Real number in [0, 1)\n        {\n            unsigned long b = mpfr_get_default_prec();\n            mpfr_set_z(r.d_value, randomBits(b).d_value, MPFR_RNDN);\n            shr(r, r, b);\n        }\n        \n        void RandomNumberGenerator::randomUniform(Real & r, const RealContext & rc)\n        // generates a uniform Real number in [0, 1)\n        {\n            unsigned long b = rc.getRealPrecision();\n            mpfr_set_z(r.d_value, randomBits(b).d_value, MPFR_RNDN);\n            shr(r, r, b);\n        }\n        \n        void randomUniform(float & r, RandomNumberGenerator & rng)\n        {\n            // Assume that mantissa is at most 64 bits\n            uint64_t x;\n            rng.randomBits(&x, sizeof(x));\n            float rr = x;\n            r = ldexp(rr, -64);\n        }\n        \n        void randomUniform(double & r, RandomNumberGenerator & rng)\n        {\n            // Assume that mantissa is at most 64 bits\n            uint64_t x;\n            rng.randomBits(&x, sizeof(x));\n            double rr = x;\n            r = ldexp(rr, -64);\n        }\n        \n        void randomUniform(long double & r, RandomNumberGenerator & rng)\n        {\n    #if PLLL_INTERNAL_LONGDOUBLE == PLLL_INTERNAL_LONGDOUBLE_EP\n            uint64_t x;\n            rng.randomBits(&x, sizeof(x));\n            long double rr = x;\n            r = ldexp(rr, -64);\n    #elif PLLL_INTERNAL_LONGDOUBLE == PLLL_INTERNAL_LONGDOUBLE_QP\n            uint64_t x;\n            rng.randomBits(&x, sizeof(x));\n            long double rr = x;\n            r = ldexp(rr, -128);\n            rng.randomBits(&x, sizeof(x));\n            rr = x;\n            r += ldexp(rr, -64);\n    #endif\n        }\n        \n        static inline bool isPOT(unsigned long long ul)\n        // C++ standard enforces two's complement for unsigned integer types; therefore, this works\n        // on any platform.\n        {\n            return (ul & (-ul)) == ul;\n        }\n        \n        namespace implementation\n        {\n            void randomInt(int & l, long b, RandomNumberGenerator & rng)\n            {\n                l = rng.random(b);\n            }\n            \n            void randomInt(long & l, long b, RandomNumberGenerator & rng)\n            {\n                l = rng.random(b);\n            }\n            \n            void randomInt(long long & v, long long bound, RandomNumberGenerator & rng)\n            {\n                if (sizeof(long long) <= sizeof(long))\n                {\n                    v = rng.random((long)bound);\n                }\n                else\n                {\n                    assert(bound > 0);\n                    // Special case: power of 2\n                    if (isPOT(bound))\n                    {\n                        rng.randomBits(&v, sizeof(v));\n                        v &= bound - 1;\n                        return;\n                    }\n                    // Large?\n                    if (bound * 2 < bound)\n                    {\n                        // General case: try until done\n                        // Expected: at most two iterations in average\n                        do\n                        {\n                            rng.randomBits(&v, sizeof(v));\n                        }\n                        while (v >= bound);\n                    }\n                    else\n                    {\n                        // General case: try until done\n                        // Know: 2 * bound < maximal value of unsigned long\n                        unsigned long long r;\n                        do\n                        {\n                            // Generate random number (using full length of bound)\n                            rng.randomBits(&r, sizeof(r));\n                            v = r % bound;\n                        }\n                        while (r - v + (unsigned long long)bound < (unsigned long long)bound);\n                    }\n                }\n            }\n            \n            void randomBits(int & l, unsigned long b, RandomNumberGenerator & rng)\n            {\n                PLLL_INTERNAL_STATIC_CHECK(std::numeric_limits<unsigned int>::radix == 2, Implementation_requires_radix_to_be_2);\n                unsigned int ll;\n                rng.randomBits(&ll, sizeof(l));\n                l = (int)(ll >> (std::numeric_limits<unsigned int>::digits - b));\n            }\n            \n            void randomBits(long & l, unsigned long b, RandomNumberGenerator & rng)\n            {\n                PLLL_INTERNAL_STATIC_CHECK(std::numeric_limits<unsigned long>::radix == 2, Implementation_requires_radix_to_be_2);\n                unsigned long ll;\n                rng.randomBits(&ll, sizeof(l));\n                l = (long)(ll >> (std::numeric_limits<unsigned long>::digits - b));\n            }\n            \n            void randomBits(long long & l, unsigned long b, RandomNumberGenerator & rng)\n            {\n                PLLL_INTERNAL_STATIC_CHECK(std::numeric_limits<unsigned long long>::radix == 2, Implementation_requires_radix_to_be_2);\n                unsigned long long ll;\n                rng.randomBits(&ll, sizeof(l));\n                l = (long long)(ll >> (std::numeric_limits<unsigned long long>::digits - b));\n            }\n        }\n        \n        void Integer::mpz_init_set_ld(mpz_t & v, long double d)\n        {\n            mpz_init(v);\n            Integer::mpz_set_ld(v, d);\n        }\n        \n        struct LDExtractEP\n        // This only works if long double is in Extended Precision (80 bit) format!\n        {\n            unsigned long mantissa : 64;\n            unsigned long exp : 15;\n            unsigned long sign : 1;\n            unsigned long rest : 48;\n        };\n        \n        unsigned find_msb_64(unsigned long x)\n        // Assume that unsigned long has precisely 64 bits. x is garuanteed to be non-zero.\n        {\n            // Adapted from http://www.hackersdelight.org/HDcode/nlz.c.txt\n            unsigned n = 0;\n            if (x <= 0x00000000FFFFFFFFul) { n = n + 32; x = x << 32; }\n            if (x <= 0x0000FFFFFFFFFFFFul) { n = n + 16; x = x << 16; }\n            if (x <= 0x00FFFFFFFFFFFFFFul) { n = n +  8; x = x <<  8; }\n            if (x <= 0x0FFFFFFFFFFFFFFFul) { n = n +  4; x = x <<  4; }\n            if (x <= 0x3FFFFFFFFFFFFFFFul) { n = n +  2; x = x <<  2; }\n            if (x <= 0x7FFFFFFFFFFFFFFFul) { n = n +  1; }\n            return 63 - n;\n        }\n        \n        namespace\n        {\n            long double anon_ld_infty = std::numeric_limits<long double>::infinity();\n            long double anon_ld_minfty = -std::numeric_limits<long double>::infinity();\n        }\n        \n        void Integer::mpz_set_ld(mpz_t & v, long double d)\n        // As mpz_set_d, we truncate (and do not round or something like that).\n        {\n#if GMP_LIMB_BITS == 64\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long double) == 16, LongDoubleShouldHave16Bytes);\n            PLLL_INTERNAL_STATIC_CHECK(std::numeric_limits<long double>::has_infinity, LongDoubleShouldHaveInfinity);\n            // Check for NaN, +-inf, +-0. This can easily be done platform independent.\n            if ((d != d) || // NaN\n                (d == anon_ld_infty) || (d == anon_ld_minfty) || // +-inf\n                (d == 0.0l)) // +-0\n            {\n                mpz_set_ui(v, 0);\n                return;\n            }\n  #define PLLL_INTERNAL_LONGDOUBLE_EP 1\n  #define PLLL_INTERNAL_LONGDOUBLE_QP 2\n  #if PLLL_INTERNAL_LONGDOUBLE == PLLL_INTERNAL_LONGDOUBLE_EP\n            union {\n                long double ld;\n                LDExtractEP lde;\n            } ld;\n            ld.ld = d;\n            \n            // Get mantissa\n            mpz_set_ui(v, ld.lde.mantissa);\n            \n            // Shift correctly\n            signed exp = (signed)ld.lde.exp - (signed)((1ul << 14) - 1);\n            exp -= 63;\n            if (exp < 0)\n                mpz_tdiv_q_2exp(v, v, -exp);\n            else\n                mpz_mul_2exp(v, v, exp);\n            \n            // Consider sign\n            if (ld.lde.sign)\n                mpz_neg(v, v);\n  #elif PLLL_INTERNAL_LONGDOUBLE == PLLL_INTERNAL_LONGDOUBLE_QP\n            union\n            {\n                long double ld;\n                unsigned long l[2];\n            } ld;\n            ld.ld = d;\n            \n            // Get mantissa\n            mpz_set_ui(v, (ld.l[0] & 0x0000FFFFFFFFFFFF) | 0x0001000000000000);\n            mpz_mul_2exp(v, v, 64);\n            mpz_add_ui(v, v, ld.l[1]);\n            \n            // Get exponent\n            signed exp = (signed)((ld.l[0] & 0x7FFF000000000000) >> 48) - (signed)((1ul << 14) - 1);\n            exp -= 112;\n            if (exp < 0)\n                mpz_tdiv_q_2exp(v, v, -exp);\n            else\n                mpz_mul_2exp(v, v, exp);\n            \n            // Consider sign\n            if (ld.l[0] & 0x8000000000000000)\n                mpz_neg(v, v);\n  #else // #if PLLL_INTERNAL_LONGDOUBLE\n    #error Long double type not supported yet!\n  #endif\n#else\n            // Fallback: use MPFR. This is *SLOW*\n            mpfr_t tmp;\n            mpfr_init2(tmp, std::numeric_limits<long double>::digits);\n            mpfr_set_ld(tmp, d, MPFR_RNDN);\n            mpfr_get_z(v, tmp, MPFR_RNDN);\n            mpfr_clear(tmp);\n#endif\n        }\n        \n        long double Integer::mpz_get_ld(const mpz_t & v)\n        {\n#if GMP_LIMB_BITS == 64\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long double) == 16, LongDoubleShouldHave16Bytes);\n            PLLL_INTERNAL_STATIC_CHECK(std::numeric_limits<long double>::has_infinity, LongDoubleShouldHaveInfinity);\n  #define PLLL_INTERNAL_LONGDOUBLE_EP 1\n  #define PLLL_INTERNAL_LONGDOUBLE_QP 2\n  #if PLLL_INTERNAL_LONGDOUBLE == PLLL_INTERNAL_LONGDOUBLE_EP\n            union\n            {\n                long double ld;\n                LDExtractEP lde;\n            } ld;\n            ld.ld = 0.0l;\n            if (mpz_sgn(v) == 0)\n                return ld.ld;\n            if (mpz_sgn(v) < 0)\n                ld.lde.sign = 1;\n            size_t size = mpz_size(v);\n            mp_limb_t msl = mpz_getlimbn(v, size - 1);\n            mp_limb_t smsl = size > 1 ? mpz_getlimbn(v, size - 2) : 0;\n            size_t msb = find_msb_64(msl);\n            if (msb < 64-1)\n            {\n                msl <<= (64-1) - msb;\n                msl |= (mp_limb_t)smsl >> (msb + 1);\n            }\n            signed long exp = ((1ul << 14) - 1) + msb + (size - 1) * 64;\n            // round?\n            if ((smsl >> msb) & 1)\n            {\n                // overflow?\n                if (msl == 0xFFFFFFFFFFFFFFFF)\n                {\n                    ++exp;\n                    msl = 0x8000000000000000;\n                }\n                else\n                    ++msl;\n            }\n            if (exp >= 0x7FFF)\n            {\n                // Too large: this is infinity!\n                return mpz_sgn(v) < 0 ? -std::numeric_limits<long double>::infinity() : std::numeric_limits<long double>::infinity();\n            }\n            if (exp <= 0)\n            {\n                // Too small: ...\n                return mpz_sgn(v) < 0 ? -0.0l : 0.0l; // one should use denormalized values instead!!! ??? ...\n            }\n            // now the MSB of msl is 1\n            ld.lde.mantissa = msl;\n            ld.lde.exp = (unsigned long)exp;\n            return ld.ld;\n  #elif PLLL_INTERNAL_LONGDOUBLE == PLLL_INTERNAL_LONGDOUBLE_QP\n            union\n            {\n                long double ld;\n                unsigned long l[2];\n            } ld;\n            ld.ld = 0.0l;\n            if (mpz_sgn(v) == 0)\n                return ld.ld;\n            if (mpz_sgn(v) < 0)\n                ld.l[0] |= (1ul << (64 - 1));\n            size_t size = mpz_size(v);\n            mp_limb_t msl = mpz_getlimbn(v, size - 1);\n            mp_limb_t smsl = size > 1 ? mpz_getlimbn(v, size - 2) : 0;\n            mp_limb_t tmsl = size > 2 ? mpz_getlimbn(v, size - 3) : 0;\n            size_t msb = find_msb_64(msl);\n            if (msb < 64-1)\n            {\n                msl <<= (64-1) - msb;\n                msl |= (unsigned long)smsl >> (msb + 1);\n                smsl <<= (64-1) - msb;\n                smsl |= (unsigned long)tmsl >> (msb + 1);\n            }\n            bool round = (smsl >> 14) & 1;\n            smsl >>= 15;\n            smsl |= msl << (64 - 15);\n            msl >>= 15;\n            signed long exp = ((1ul << 14) - 1) + msb + (size - 1) * 64;\n            // round?\n            if (round)\n            {\n                // overflow?\n                if (smsl == 0xFFFFFFFFFFFFFFFF)\n                {\n                    smsl = 0;\n                    ++msl;\n                    if (msl == 0x0001FFFFFFFFFFFF)\n                    {\n                        ++exp;\n                        msl = 0x0001000000000000;\n                    }\n                }\n                else\n                    ++msl;\n            }\n            if (exp >= 0x7FFF)\n            {\n                // Too large: this is infinity!\n                return mpz_sgn(v) < 0 ? -std::numeric_limits<long double>::infinity() : std::numeric_limits<long double>::infinity();\n            }\n            if (exp <= 0)\n            {\n                // Too small: ...\n                return mpz_sgn(v) < 0 ? -0.0l : 0.0l; // one should use denormalized values instead!!! ??? ...\n            }\n            // The leading 1 of the mantissa is thrown away...\n            ld.l[0] |= ((unsigned long)exp << 48) | (msl & 0x0000FFFFFFFFFFFF);\n            ld.l[1] = smsl;\n            return ld.ld;\n  #else // #if PLLL_INTERNAL_LONGDOUBLE\n    #error Long double type not supported yet!\n  #endif\n#else // #if GMP_LIMB_BITS\n            // Fallback: use MPFR. This is *SLOW*\n            mpfr_t tmp;\n            mpfr_init2(tmp, std::numeric_limits<long double>::digits);\n            mpfr_set_z(tmp, v, MPFR_RNDN);\n            long double r = mpfr_get_ld(tmp, MPFR_RNDN);\n            mpfr_clear(tmp);\n            return r;\n#endif\n        }\n        \n        std::ostream & operator << (std::ostream & s, const Integer & i)\n        // Output to stream\n        {\n            char * str = mpz_get_str(NULL, 10, i.d_value);\n            s << str;\n            mpfr_free_str(str); // There is no nice way to directly call the free() method of\n            // GMP. But since MPFR is using the same allocators as GMP, we can\n            // just use mpfr_free_str() instead...\n            // std::free(str);\n            return s;\n        }\n        \n        std::istream & operator >> (std::istream & s, Integer & i)\n        // Input from stream\n        {\n            Buffer<char> buf;\n            char c;\n            c = s.get();\n            if (!s)\n            {\n                mpz_set_ui(i.d_value, 0);\n                s.setstate(std::ios_base::failbit);\n                return s;\n            }\n            if ((c == '-') || (c == '+'))\n            {\n                buf.add(c);\n                c = s.get();\n                if (!s)\n                {\n                    mpz_set_ui(i.d_value, 0);\n                    s.setstate(std::ios_base::failbit);\n                    return s;\n                }\n            }\n            if (!isdigit(c))\n            {\n                mpz_set_ui(i.d_value, 0);\n                s.setstate(std::ios_base::failbit);\n                return s;\n            }\n            while (isdigit(c))\n            {\n                buf.add(c);\n                c = s.get();\n                if (!s)\n                {\n                    if (s.eof())\n                        break;\n                    mpz_set_ui(i.d_value, 0);\n                    s.setstate(std::ios_base::failbit);\n                    return s;\n                }\n            }\n            if (!s.eof())\n                s.unget();\n            else\n            {\n                if (!s.bad())\n                    s.clear(std::ios_base::eofbit);\n            }\n            buf.add(0);\n            if (mpz_set_str(i.d_value, buf.data(), 10))\n            {\n                // Not a valid integer, set to zero\n                mpz_set_ui(i.d_value, 0);\n                // Mark stream as bad\n                s.setstate(std::ios_base::failbit);\n            }\n            return s;\n        }\n        \n        namespace implementation\n        {\n            bool from_string_conversion<IntegerContext>::convert(Integer & res, const std::string & s, const IntegerContext & c)\n            {\n                return mpz_set_str(res.d_value, s.c_str(), 10) == 0;\n            }\n            \n            bool from_string_conversion<IntegerContext>::convert(Integer & res, const char * s, const IntegerContext & c)\n            {\n                return mpz_set_str(res.d_value, s, 10) == 0;\n            }\n            \n            std::string to_string_conversion<Integer>::convert(const Integer & val)\n            {\n                char * str = mpz_get_str(NULL, 10, val.d_value);\n                std::string res(str);\n                mpfr_free_str(str); // There is no nice way to directly call the free() method of\n                                    // GMP. But since MPFR is using the same allocators as GMP, we can\n                                    // just use mpfr_free_str() instead...\n                return res;\n            }\n            \n            std::string to_string_conversion<Integer>::convert(const Integer & val, unsigned base)\n            {\n                char * str = mpz_get_str(NULL, base, val.d_value);\n                std::string res(str);\n                mpfr_free_str(str); // There is no nice way to directly call the free() method of\n                                    // GMP. But since MPFR is using the same allocators as GMP, we can\n                                    // just use mpfr_free_str() instead...\n                return res;\n            }\n            \n            void to_string_conversion<Integer>::convert(std::string & res, const Integer & val)\n            {\n                char * str = mpz_get_str(NULL, 10, val.d_value);\n                res = str;\n                mpfr_free_str(str); // There is no nice way to directly call the free() method of\n                                    // GMP. But since MPFR is using the same allocators as GMP, we can\n                                    // just use mpfr_free_str() instead...\n            }\n            \n            void to_string_conversion<Integer>::convert(std::string & res, const Integer & val, unsigned base)\n            {\n                char * str = mpz_get_str(NULL, base, val.d_value);\n                res = str;\n                mpfr_free_str(str); // There is no nice way to directly call the free() method of\n                                    // GMP. But since MPFR is using the same allocators as GMP, we can\n                                    // just use mpfr_free_str() instead...\n            }\n        }\n        \n        enum OutputType { OT_Default, OT_Fixed, OT_Scientific };\n        enum BaseType { BT_Dec, BT_Hex, BT_Oct };\n        enum AdjustType { AT_Internal, AT_Left, AT_Right };\n        \n        namespace\n        {\n            class CallMPFRFreeStr\n            {\n            private:\n                char * d_str;\n                \n            public:\n                CallMPFRFreeStr(char * str)\n                    : d_str(str)\n                {\n                }\n                \n                ~CallMPFRFreeStr()\n                {\n                    mpfr_free_str(d_str);\n                }\n            };\n        }\n        \n        void printToStream(std::ostream & s, const mpfr_t & r,\n                           OutputType ot, BaseType bt, AdjustType at, unsigned width, unsigned precision,\n                           char fill, bool showbase, bool showpoint, bool showpos, bool uppercase)\n        // Output to stream\n        {\n            // Retrieve string and exponent\n            mpfr_exp_t exp;\n            int b = 10;\n            switch (bt)\n            {\n            case BT_Dec: b = 10; break;\n            case BT_Hex: b = 16; break;\n            case BT_Oct: b =  8; break;\n            }\n            int digits = precision;\n            if (ot == OT_Scientific)\n                ++digits;\n            if ((ot == OT_Fixed) && !mpfr_zero_p(r))\n            {\n                char * str = mpfr_get_str(NULL, &exp, b, 2, r, MPFR_RNDN);\n                CallMPFRFreeStr strrel(str);\n                digits = precision + exp;\n                if (digits < 1)\n                    digits = 1;\n            }\n            digits += 3; // just in case\n            char * str = mpfr_get_str(NULL, &exp, b, digits, r, MPFR_RNDN);\n            CallMPFRFreeStr strrel(str);\n            char * rstr = str;\n            ArrayStore<char> rstr_storage;\n            if (str == NULL)\n                // Error!\n                return;\n            // Handle sign and base\n            char sign = 0;\n            const char * base = NULL;\n            if ((mpfr_sgn(r) < 0) || (*rstr == '-'))\n            {\n                if (*rstr == '-') // safe guard\n                    ++rstr;\n                sign = '-';\n            }\n            else\n                if (showpos && (mpfr_sgn(r) > 0))\n                    sign = '+';\n            if (showbase)\n                switch (bt)\n                {\n                case BT_Dec: break;\n                case BT_Hex: base = uppercase ? \"0X\" : \"0x\"; break;\n                case BT_Oct: base = \"0\"; break;\n                }\n            // Compute number of leading digits and length\n            int leading = 1, len = std::strlen(rstr);\n            if (mpfr_zero_p(r))\n                exp = leading;\n            // Shorten if necessary\n            if (len > digits - 3)\n            {\n                len = digits - 3;\n                rstr[len] = 0;\n            }\n            // Convert digits to uppercase if necessary\n            if (uppercase && (bt == BT_Hex))\n                for (int i = 0; i < len; ++i)\n                    if (rstr[i] >= 'a')\n                        rstr[i] -= 'a' - 'A';\n            // Decide how many leading digits to display\n            switch (ot)\n            {\n            case OT_Default:\n                if ((exp > 0) && (exp <= len))\n                    leading = exp;\n                // Remove trailing zeros from the fractional part\n                while (len > leading)\n                    if (rstr[len - 1] == '0')\n                        --len;\n                    else\n                        break;\n                rstr[len] = 0;\n                // Prepend zeros?\n                if ((leading == 1) && (exp <= 0) && (len - exp - 3 < precision))\n                {\n                    // Insert -exp+1 zeros\n                    for (int i = len; i >= 0; --i)\n                        rstr[i + 1 - exp] = rstr[i];\n                    for (unsigned i = 0; i < 1 - exp; ++i)\n                        rstr[i] = '0';\n                \n                    // Increase len\n                    len += 1-exp;\n                \n                    // Set exp to leading == 1\n                    exp = 1;\n                }\n                break;\n            case OT_Scientific:\n                // Nothing to do.\n                break;\n            case OT_Fixed:\n                // Shorten if necessary\n                if ((exp > 0) && (exp + precision < len))\n                    len = exp + precision;\n            \n                // Insert zeros if necessary\n                if (exp <= 0)\n                {\n                    rstr_storage.reset(precision + 2);\n                    for (unsigned i = 0; i <= precision; ++i)\n                        rstr_storage[i] = '0';\n                    rstr_storage[precision + 1] = 0;\n                    for (unsigned i = -exp + 1; i <= precision; ++i)\n                        if (i + exp <= len)\n                            rstr_storage[i] = rstr[i + exp - 1];\n                    rstr = rstr_storage.get();\n                    len = precision + 1;\n                    leading = 1;\n                    exp = 1;\n                }\n            \n                if ((exp > 0) && (exp < len))\n                    leading = exp;\n                break;\n            }\n            // Determine output length\n            unsigned outlen = 0;\n            if (sign) ++outlen;\n            if (base) outlen += strlen(base);\n            outlen += len;\n            if ((leading < len) || (showpoint)) ++outlen;\n            if ((ot == OT_Fixed) && ((unsigned)len < precision + (unsigned)leading))\n                outlen += precision + leading - len;\n            unsigned pot = 1;\n            if ((exp - leading) || (ot == OT_Scientific))\n            {\n                outlen += 2;\n                unsigned t = std::abs(exp - leading);\n                do\n                {\n                    ++outlen;\n                    t /= 10;\n                    pot *= 10;\n                } while (t);\n                pot /= 10;\n            }\n            // Pad in front?\n            if ((outlen < width) && (at == AT_Right))\n            {\n                for (unsigned i = outlen; i < width; ++i)\n                    s.put(fill);\n                outlen = width;\n            }\n            // Output sign/base\n            if (sign)\n            {\n                s << sign;\n            }\n            if (base)\n                s << base;\n            // Pad in middle?\n            if ((outlen < width) && (at == AT_Internal))\n            {\n                for (unsigned i = outlen; i < width; ++i)\n                    s.put(fill);\n                outlen = width;\n            }\n            // Output leading digits\n            for (int i = 0; i < leading; ++i)\n                s.put(rstr[i]);\n            // Print decimal dot\n            if ((leading < len) || (showpoint))\n                s.put('.');\n            // Is something left to show?\n            for (int i = leading; i < len; ++i)\n                s.put(rstr[i]);\n            if (ot == OT_Fixed)\n                for (unsigned i = len - leading; i < precision; ++i)\n                    s.put('0');\n            // Output exponent if needed\n            if ((exp - leading) || (ot == OT_Scientific))\n            {\n                s.put(uppercase ? 'E' : 'e');\n                s.put((exp >= leading) ? '+' : '-');\n                unsigned e = std::abs(exp - leading);\n                do\n                {\n                    s.put('0' + (e / pot));\n                    e %= pot;\n                    pot /= 10;\n                } while (pot);\n            }\n            // Pad in end?\n            if ((outlen < width) && (at == AT_Left))\n            {\n                for (unsigned i = outlen; i < width; ++i)\n                    s.put(fill);\n                outlen = width;\n            }\n        }\n    \n        std::ostream & operator << (std::ostream & s, const Real & r)\n        // Output to stream\n        {\n            char fill = s.fill(); // fill character\n            unsigned width = s.width(); // field width\n            unsigned prec = s.precision(); // output precision (maximum number of digits)\n            OutputType ot = OT_Default;\n            switch (s.flags() & std::ios::floatfield)\n            {\n            case std::ios::scientific: ot = OT_Scientific; break;\n            case std::ios::fixed: ot = OT_Fixed; break;\n            default: ;\n            }\n            bool showbase = s.flags() & std::ios::showbase;\n            bool showpoint = s.flags() & std::ios::showpoint;\n            bool showpos = s.flags() & std::ios::showpos;\n            bool uppercase = s.flags() & std::ios::uppercase;\n            BaseType bt = BT_Dec;\n            switch (s.flags() & std::ios::basefield)\n            {\n            case std::ios::dec: bt = BT_Dec; break;\n            case std::ios::hex: bt = BT_Hex; break;\n            case std::ios::oct: bt = BT_Oct; break;\n            default: ;\n            }\n            AdjustType at = AT_Right;\n            switch (s.flags() & std::ios::adjustfield)\n            {\n            case std::ios::internal: at = AT_Internal; break;\n            case std::ios::left: at = AT_Left; break;\n            case std::ios::right: at = AT_Right; break;\n            default: ;\n            }\n            s.width(0); // reset width\n            printToStream(s, r.d_value, ot, bt, at, width, prec, fill, showbase, showpoint, showpos, uppercase);\n            return s;\n        }\n    \n        std::istream & operator >> (std::istream & s, Real & r)\n        // Input from stream\n        {\n            Buffer<char> buf;\n            char c;\n            c = s.get();\n            if (!s)\n            {\n                s.setstate(std::ios_base::failbit);\n                return s;\n            }\n            if ((c == '-') || (c == '+'))\n            {\n                buf.add(c);\n                c = s.get();\n                if (!s)\n                {\n                    s.setstate(std::ios_base::failbit);\n                    return s;\n                }\n            }\n            if (!isdigit(c) && (c != '.'))\n            {\n                s.setstate(std::ios_base::failbit);\n                return s;\n            }\n            while (isdigit(c))\n            {\n                buf.add(c);\n                c = s.get();\n                if (!s)\n                {\n                    if (s.eof())\n                    {\n                        c = ' ';\n                        break;\n                    }\n                    s.setstate(std::ios_base::failbit);\n                    return s;\n                }\n            }\n            if (c == '.')\n            {\n                buf.add(c);\n                c = s.get();\n                if (!s)\n                {\n                    s.setstate(std::ios_base::failbit);\n                    return s;\n                }\n                while (isdigit(c))\n                {\n                    buf.add(c);\n                    c = s.get();\n                    if (!s)\n                    {\n                        if (s.eof())\n                        {\n                            c = ' ';\n                            break;\n                        }\n                        s.setstate(std::ios_base::failbit);\n                        return s;\n                    }\n                }\n            }\n            if ((c == 'e') || (c == 'E'))\n            {\n                buf.add(c);\n                c = s.get();\n                if (!s)\n                {\n                    s.setstate(std::ios_base::failbit);\n                    return s;\n                }\n                if ((c == '-') || (c == '+'))\n                {\n                    buf.add(c);\n                    c = s.get();\n                    if (!s)\n                    {\n                        s.setstate(std::ios_base::failbit);\n                        return s;\n                    }\n                }\n                if (!isdigit(c))\n                {\n                    s.setstate(std::ios_base::failbit);\n                    return s;\n                }\n                while (isdigit(c))\n                {\n                    buf.add(c);\n                    c = s.get();\n                    if (!s)\n                    {\n                        if (s.eof())\n                        {\n                            c = ' ';\n                            break;\n                        }\n                        s.setstate(std::ios_base::failbit);\n                        return s;\n                    }\n                }\n            }\n            if (!s.eof())\n                s.unget();\n            else\n            {\n                if (!s.bad())\n                    s.clear(std::ios_base::eofbit);\n            }\n            buf.add(0);\n            char * s_end;\n            mpfr_strtofr(r.d_value, buf.data(), &s_end, 10, MPFR_RNDN);\n            if (*s_end != 0)\n                s.setstate(std::ios_base::failbit);\n            return s;\n        }\n        \n        namespace implementation\n        {\n            bool from_string_conversion<RealContext>::convert(Real & res, const std::string & s, const RealContext & c)\n            {\n                return convert(res, s.c_str(), c);\n            }\n            \n            bool from_string_conversion<RealContext>::convert(Real & res, const char * s, const RealContext & c)\n            {\n                if (*s == 0)\n                    return false;\n                char * s_end;\n                res.setContext(c);\n                mpfr_strtofr(res.d_value, s, &s_end, 10, MPFR_RNDN);\n                return s + strlen(s) == s_end;\n            }\n            \n            std::string to_string_conversion<Real>::convert(const Real & val)\n            {\n                mpfr_exp_t exp;\n                char * str = mpfr_get_str(NULL, &exp, 10, 0, val.d_value, MPFR_RNDN);\n                std::string s;\n                if (sign(val) < 0)\n                    s += '-';\n                s += \"0.\";\n                s += (sign(val) < 0 ? str + 1 : str);\n                mpfr_free_str(str);\n                const int expstrsize = 20;\n                char expstr[expstrsize];\n                snprintf(expstr, expstrsize, \"e%li\", exp);\n                s += expstr;\n                return s;\n            }\n            \n            std::string to_string_conversion<Real>::convert(const Real & val, unsigned base)\n            {\n                mpfr_exp_t exp;\n                char * str = mpfr_get_str(NULL, &exp, base, 0, val.d_value, MPFR_RNDN);\n                std::string s;\n                if (sign(val) < 0)\n                    s += '-';\n                s += \"0.\";\n                s += (sign(val) < 0 ? str + 1 : str);\n                mpfr_free_str(str);\n                const int expstrsize = 20;\n                char expstr[expstrsize];\n                snprintf(expstr, expstrsize, \"e%li\", exp);\n                s += expstr;\n                return s;\n            }\n            \n            void to_string_conversion<Real>::convert(std::string & res, const Real & val)\n            {\n                mpfr_exp_t exp;\n                char * str = mpfr_get_str(NULL, &exp, 10, 0, val.d_value, MPFR_RNDN);\n                res.clear();\n                if (sign(val) < 0)\n                    res += '-';\n                res += \"0.\";\n                res += (sign(val) < 0 ? str + 1 : str);\n                mpfr_free_str(str);\n                const int expstrsize = 20;\n                char expstr[expstrsize];\n                snprintf(expstr, expstrsize, \"e%li\", exp);\n                res += expstr;\n            }\n            \n            void to_string_conversion<Real>::convert(std::string & res, const Real & val, unsigned base)\n            {\n                mpfr_exp_t exp;\n                char * str = mpfr_get_str(NULL, &exp, base, 0, val.d_value, MPFR_RNDN);\n                res.clear();\n                if (sign(val) < 0)\n                    res += '-';\n                res += \"0.\";\n                res += (sign(val) < 0 ? str + 1 : str);\n                mpfr_free_str(str);\n                const int expstrsize = 20;\n                char expstr[expstrsize];\n                snprintf(expstr, expstrsize, \"e%li\", exp);\n                res += expstr;\n            }\n        }\n        \n        void Integer::mpz_set_ll(mpz_t & value, long long i)\n        {\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long long) == 8, Implementation_requires_longlong_to_be_64bits);\n        \n            bool neg = i < 0;\n            unsigned long long u = neg ? -i : i;\n            mpz_set_ui(value, (unsigned long)(u >> 32));\n            mpz_mul_2exp(value, value, 32);\n            mpz_add_ui(value, value, (unsigned long)(u & 0xFFFFFFFFull));\n        }\n        \n        long long Integer::mpz_get_ll(const mpz_t & value)\n        {\n            unsigned long long u;\n#if GMP_LIMB_BITS == 64\n            u = mpz_getlimbn(value, 0);\n#else\n  #error Implementation currently only supports limb size of 64!\n#endif\n            return (mpz_sgn(value) < 0) ? -u : u;\n        }\n        \n        void Real::mpfr_set_ll(mpfr_t & v, long long i, mpfr_rnd_t rnd)\n        {\n#if _MPFR_H_HAVE_INTMAX_T\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long long) <= sizeof(intmax_t), Implementation_requires_longlong_to_be_64bits);\n            mpfr_set_sj(v, i, rnd);\n#else\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long long) == 8, Implementation_requires_longlong_to_be_64bits);\n            bool neg = i < 0;\n            unsigned long long u = neg ? -i : i;\n            mpfr_set_ui(v, (unsigned long)(u >> 32), rnd);\n            mpfr_mul_2ui(v, v, 32, rnd);\n            mpfr_add_ui(v, v, (unsigned long)(u & 0xFFFFFFFFull), rnd);\n#endif\n        }\n        \n        long long Real::mpfr_get_ll(const mpfr_t & v, mpfr_rnd_t rnd)\n        {\n#if _MPFR_H_HAVE_INTMAX_T\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long long) <= sizeof(intmax_t), Implementation_requires_longlong_to_be_64bits);\n            return mpfr_get_sj(v, rnd);\n#else\n            bool neg = mpfr_signbit(v);\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long long) == 8, Implementation_requires_longlong_to_be_64bits);\n            mpfr_t t;\n            mpfr_prec_t p = mpfr_get_prec(v);\n            mpfr_init2(t, p);\n            mpfr_rint(t, v, rnd);\n            mpfr_abs(t, t, MPFR_RNDN);\n            unsigned long long res;\n            unsigned long tt;\n            mpfr_div_2ui(t, t, 32, MPFR_RNDN);\n            tt = mpfr_get_ui(t, MPFR_RNDZ);\n            mpfr_sub_ui(t, t, tt, MPFR_RNDN);\n            mpfr_mul_2ui(t, t, 32, MPFR_RNDN);\n            res = (((unsigned long long)tt) << 32) + (unsigned long long)mpfr_get_ui(t, MPFR_RNDZ);\n            mpfr_clear(t);\n            return neg ? -res : res;\n#endif\n        }\n        \n        long long Real::mpfr_get_ll(const mpfr_t & v, mpfr_rnd_t rnd, bool & roundUp)\n        {\n#if _MPFR_H_HAVE_INTMAX_T\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long long) <= sizeof(intmax_t), Implementation_requires_longlong_to_be_64bits);\n            long long w = mpfr_get_sj(v, rnd);\n            roundUp = (rnd == MPFR_RNDD) ? false : (w > mpfr_get_sj(v, MPFR_RNDD));\n            return w;\n#else\n            bool neg = mpfr_signbit(v);\n            PLLL_INTERNAL_STATIC_CHECK(sizeof(long long) == 8, Implementation_requires_longlong_to_be_64bits);\n            mpfr_t t;\n            mpfr_prec_t p = mpfr_get_prec(v);\n            mpfr_init2(t, p);\n            mpfr_rint(t, v, rnd);\n            roundUp = mpfr_cmp(v, t) < 0;\n            mpfr_abs(t, t, MPFR_RNDN);\n            unsigned long long res;\n            unsigned long tt;\n            mpfr_div_2ui(t, t, 32, MPFR_RNDN);\n            tt = mpfr_get_ui(t, MPFR_RNDZ);\n            mpfr_sub_ui(t, t, tt, MPFR_RNDN);\n            mpfr_mul_2ui(t, t, 32, MPFR_RNDN);\n            res = (((unsigned long long)tt) << 32) + (unsigned long long)mpfr_get_ui(t, MPFR_RNDZ);\n            mpfr_clear(t);\n            return neg ? -res : res;\n#endif\n        }\n    }\n}\n", "meta": {"hexsha": "ec221975ec88b8739fd1d060fcc3efe8c9dfe4cc", "size": 58087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plll/src/arithmetic/arithmetic-gmp.cpp", "max_stars_repo_name": "KudrinMatvey/myfplll", "max_stars_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plll/src/arithmetic/arithmetic-gmp.cpp", "max_issues_repo_name": "KudrinMatvey/myfplll", "max_issues_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plll/src/arithmetic/arithmetic-gmp.cpp", "max_forks_repo_name": "KudrinMatvey/myfplll", "max_forks_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1462352209, "max_line_length": 135, "alphanum_fraction": 0.4362421884, "num_tokens": 12871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.030214587940651676, "lm_q1q2_score": 0.012881131689480905}}
{"text": "/// @file HealPixFacade.cc\n///\n/// @copyright (c) 2016 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 Daniel Collins <daniel.collins@csiro.au>\n\n// Include own header file first\n#include \"HealPixFacade.h\"\n\n// Include package level header file\n#include \"askap_skymodel.h\"\n\n// System includes\n#include <string>\n\n// ASKAPsoft includes\n#include <askap/AskapError.h>\n#include <askap/AskapLogging.h>\n#include <Common/ParameterSet.h>\n#include <boost/scoped_ptr.hpp>\n#include <healpix_tables.h>\n#include <rangeset.h>\n\n// Local includes\n//#include \"SkyModelServiceImpl.h\"\n\nASKAP_LOGGER(logger, \".HealPixFacade\");\n\nusing namespace std;\nusing namespace boost;\nusing namespace askap::cp::sms;\n\nnamespace askap {\nnamespace cp {\nnamespace sms {\n\n\nHealPixFacade::HealPixFacade(Index order)\n    :\n    itsHealPixBase(2 << order, NEST, SET_NSIDE),\n    itsNSide(2 << order)\n{\n}\n\nHealPixFacade::Index HealPixFacade::calcHealPixIndex(Coordinate coordinate) const\n{\n    // Note: this initial implementation is not likely to be the most efficient,\n    // but it does give me enough to sort out the basics.\n    // A more efficient option is likely to be threaded processing of\n    // contiguous arrays of ra and dec coordinates, with the T_Healpix_Base\n    // object being reused if possible, or thread-local if it is not\n    // thread-safe.\n    return itsHealPixBase.ang2pix(J2000ToPointing(coordinate));\n}\n\nHealPixFacade::IndexListPtr HealPixFacade::queryDisk(Coordinate centre, double radius, int fact) const\n{\n    rangeset<Index> pixels;\n    itsHealPixBase.query_disc_inclusive(\n        J2000ToPointing(centre),\n        utility::degreesToRadians(radius),\n        pixels,\n        fact);\n\n    return IndexListPtr(new IndexList(pixels.toVector()));\n}\n\nHealPixFacade::IndexListPtr HealPixFacade::queryRect(\n    Rect rect,\n    int fact) const\n{\n    // munge the inputs into a polygon, moving clockwise from the top-left\n    std::vector<pointing> vertex;\n    vertex.push_back(J2000ToPointing(rect.topLeft()));\n    vertex.push_back(J2000ToPointing(rect.topRight()));\n    vertex.push_back(J2000ToPointing(rect.bottomRight()));\n    vertex.push_back(J2000ToPointing(rect.bottomLeft()));\n    \n    // intersect with HEALPix\n    rangeset<Index> pixels;\n    itsHealPixBase.query_polygon_inclusive(vertex, pixels, fact);\n\n    // return pixels as an IndexList\n    return IndexListPtr(new IndexList(pixels.toVector()));\n}\n\n};\n};\n};\n", "meta": {"hexsha": "b88b7bc30a1f7a811eb30c93d4bc0edc8d3ac349", "size": 3371, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/Components/Services/skymodel/current/service/HealPixFacade.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Services/skymodel/service/service/HealPixFacade.cc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Services/skymodel/service/service/HealPixFacade.cc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6454545455, "max_line_length": 102, "alphanum_fraction": 0.7315336695, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.03161876852335766, "lm_q1q2_score": 0.012879380032911614}}
{"text": "#include <jni.h>\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n\r\n#include <Eigen/Geometry>\r\n\r\n#include <android/log.h>\r\n\r\n#include \"kalman/include/KalmanGlobal.h\"\r\n#include \"kalman/include/KalmanFilterHandler.h\"\r\n#include \"kalman/include/BasicExtendedKalmanFilterHandler.h\"\r\n\r\n#define  LOG_TAG\t\"Kalman\"\r\n#define  LOGI(...)\t__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)\r\n#define  LOGE(...)\t__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)\r\n\r\nusing namespace kalman;\r\nusing namespace Eigen;\r\n\r\nextern \"C\"\r\n{\r\n\tJNIEXPORT jboolean JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_initializeKalmanNative(JNIEnv *env, jobject obj,\r\n\t\t\tjint kalmanType, jfloat accelDeltaT, jfloat gyroDeltaT, jfloatArray gravity);\r\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_handleDataNative(JNIEnv *env, jobject obj,\r\n\t\t\tjint dataType, jfloatArray acceleration, jfloatArray angularVelocity, jfloatArray position,\r\n\t\t\tjfloatArray orientation);\r\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_getFilteredPoseNative(JNIEnv *env, jobject obj,\r\n\t\t\tjfloatArray pose);\r\n\tJNIEXPORT void JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_setVisualObservationNoise(JNIEnv *env, jobject obj,\r\n\t\t\tjfloat noiseValue);\r\n}\r\n\r\n// Kalman types.\r\nenum\r\n{\r\n\tBASIC_KALMAN = 0,\r\n\tINDIRECT_KALMAN = 1\r\n};\r\n\r\nJNIEXPORT jboolean JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_initializeKalmanNative(JNIEnv *env, jobject obj,\r\n\t\tjint kalmanType, jfloat accelDeltaT, jfloat gyroDeltaT, jfloatArray gravity)\r\n{\r\n\t//TODO Cambiare in base al tipo di kalman! per ora inizializzo il basic\r\n\r\n\tjfloat tempGravity[3];\r\n\tenv->GetFloatArrayRegion(gravity, 0, 3, tempGravity);\r\n\tVector3f gravityVec(tempGravity[0], tempGravity[1], tempGravity[2]);\r\n\r\n\tbool success = false;\r\n\r\n\tif (kalmanType == BASIC_KALMAN)\r\n\t{\r\n\t\tKalmanFilterHandler *handler = new BasicExtendedKalmanFilterHandler(accelDeltaT, gyroDeltaT, gravityVec);\r\n\t\tsuccess = KalmanGlobal::getInstance().setHandlerPtr(handler);\r\n\t\tif (!success)\r\n\t\t\tdelete handler;\r\n\t}\r\n\r\n\treturn success;\r\n}\r\n\r\nJNIEXPORT void JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_handleDataNative(JNIEnv *env, jobject obj,\r\n\t\tjint dataType, jfloatArray acceleration, jfloatArray angularVelocity, jfloatArray position,\r\n\t\tjfloatArray orientation)\r\n{\r\n\tjfloat tempAcceleration[3];\r\n\tenv->GetFloatArrayRegion(acceleration, 0, 3, tempAcceleration);\r\n\tVector3f accelerationVec(tempAcceleration[0], tempAcceleration[1], tempAcceleration[2]);\r\n\r\n\tjfloat tempAngularVelocity[3];\r\n\tenv->GetFloatArrayRegion(angularVelocity, 0, 3, tempAngularVelocity);\r\n\tVector3f angularVelocityVec(tempAngularVelocity[0], tempAngularVelocity[1], tempAngularVelocity[2]);\r\n\r\n\tjfloat tempPosition[3];\r\n\tenv->GetFloatArrayRegion(position, 0, 3, tempPosition);\r\n\tVector3f positionVec(tempPosition[0], tempPosition[1], tempPosition[2]);\r\n\r\n\tjfloat tempOrientation[9];\r\n\tenv->GetFloatArrayRegion(orientation, 0, 9, tempOrientation);\r\n\tMatrix3f orientationMat;\r\n\torientationMat << \ttempOrientation[0], tempOrientation[3], tempOrientation[6],\r\n\t\t\t\t\t\ttempOrientation[1], tempOrientation[4], tempOrientation[7],\r\n\t\t\t\t\t\ttempOrientation[2], tempOrientation[5], tempOrientation[8];\r\n\r\n\tKalmanData data;\r\n\tdata.dataType = dataType;\r\n\tdata.acceleration = accelerationVec;\r\n\tdata.angularVelocity = angularVelocityVec;\r\n\tdata.position = positionVec;\r\n\tdata.orientation = orientationMat;\r\n\r\n\tKalmanGlobal::getInstance().getHandlerPtr()->handleData(data);\r\n}\r\n\r\nJNIEXPORT void JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_getFilteredPoseNative(JNIEnv *env, jobject obj,\r\n\t\tjfloatArray pose)\r\n{\r\n\tjfloat* elements = env->GetFloatArrayElements(pose, NULL);\r\n\r\n\tIsometry3f poseEigen = KalmanGlobal::getInstance().getHandlerPtr()->getCurrentPose();\r\n\r\n\tfor (int i = 0; i < 16; i++)\r\n\t\telements[i] = poseEigen.matrix().data()[i];\r\n\r\n\tenv->ReleaseFloatArrayElements(pose, elements, 0);\r\n}\r\n\r\nJNIEXPORT void JNICALL Java_it_unibo_slam_kalman_KalmanGlobal_setVisualObservationNoise(JNIEnv *env, jobject obj,\r\n\t\tjfloat noiseValue)\r\n{\r\n\tKalmanGlobal::getInstance().getHandlerPtr()->setVisualObservationNoise(noiseValue);\r\n}\r\n", "meta": {"hexsha": "46036302f177595b7bc8f950546b10a5b4f9b977", "size": 4125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni/kalman/KalmanMain.cpp", "max_stars_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_stars_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T15:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:07:15.000Z", "max_issues_repo_path": "jni/kalman/KalmanMain.cpp", "max_issues_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_issues_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-31T05:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T14:06:53.000Z", "max_forks_repo_path": "jni/kalman/KalmanMain.cpp", "max_forks_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_forks_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T12:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T08:07:55.000Z", "avg_line_length": 35.8695652174, "max_line_length": 116, "alphanum_fraction": 0.775030303, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.02635534997830781, "lm_q1q2_score": 0.01286887977161814}}
{"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_ACCUMULATORS_KDF_HPP\n#define CRYPTO3_ACCUMULATORS_KDF_HPP\n\n#include <boost/container/static_vector.hpp>\n\n#include <boost/parameter/value_type.hpp>\n\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n\n#include <nil/crypto3/block/accumulators/parameters/cipher.hpp>\n#include <nil/crypto3/block/accumulators/parameters/bits.hpp>\n\n#include <nil/crypto3/detail/make_array.hpp>\n#include <nil/crypto3/detail/digest.hpp>\n\n#include <nil/crypto3/block/cipher.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace accumulators {\n            namespace impl {\n                template<typename Mode>\n                struct kdf_impl : boost::accumulators::accumulator_base {\n                protected:\n                    typedef Mode mode_type;\n                    typedef typename Mode::cipher_type cipher_type;\n                    typedef typename Mode::padding_type padding_type;\n\n                    typedef typename mode_type::finalizer_type finalizer_type;\n\n                    constexpr static const std::size_t word_bits = mode_type::word_bits;\n                    typedef typename mode_type::word_type word_type;\n\n                    constexpr static const std::size_t state_bits = mode_type::state_bits;\n                    constexpr static const std::size_t state_words = mode_type::state_words;\n                    typedef typename mode_type::state_type state_type;\n\n                    constexpr static const std::size_t block_bits = mode_type::block_bits;\n                    constexpr static const std::size_t block_words = mode_type::block_words;\n                    typedef typename mode_type::block_type block_type;\n\n                    typedef boost::container::static_vector<word_type, block_words> cache_type;\n\n                public:\n                    typedef digest<block_bits> result_type;\n\n                    template<typename Args>\n                    kdf_impl(const Args &args) : cipher(args[accumulators::cipher]), seen(0) {\n                    }\n\n                    template<typename ArgumentPack>\n                    inline void operator()(const ArgumentPack &args) {\n                        return process(args[boost::accumulators::sample]);\n                    }\n\n                    template<typename ArgumentPack>\n                    inline result_type result(const ArgumentPack &args) const {\n                        result_type res = dgst;\n\n                        if (!cache.empty()) {\n                            block_type ib = {0};\n                            std::move(cache.begin(), cache.end(), ib.begin());\n                            block_type ob = cipher.end_message(ib);\n                            std::move(ob.begin(), ob.end(), std::inserter(res, res.end()));\n                        }\n\n                        if (seen % block_bits) {\n                            finalizer_type(block_bits - seen % block_bits)(res);\n                        } else {\n                            finalizer_type(0)(res);\n                        }\n\n                        return res;\n                    }\n\n                protected:\n                    inline void resolve_type(const word_type &value, std::size_t bits) {\n                        if (bits == std::size_t()) {\n                            process(value, word_bits);\n                        } else {\n                            process(value, bits);\n                        }\n                    }\n\n                    inline void resolve_type(const block_type &value, std::size_t bits) {\n                        if (bits == std::size_t()) {\n                            process(value, block_bits);\n                        } else {\n                            process(value, bits);\n                        }\n                    }\n\n                    inline void process(const word_type &value, std::size_t bits) {\n                        if (cache.size() == cache.max_size()) {\n                            block_type ib = {0};\n                            std::move(cache.begin(), cache.end(), ib.begin());\n                            block_type ob = dgst.empty() ? cipher.begin_message(ib) : cipher.process_block(ib);\n                            std::move(ob.begin(), ob.end(), std::inserter(dgst, dgst.end()));\n\n                            cache.clear();\n                        }\n\n                        cache.push_back(value);\n                        seen += bits;\n                    }\n\n                    inline void process(const block_type &block, std::size_t bits) {\n                        block_type ob;\n                        if (cache.empty()) {\n                            ob = dgst.empty() ? cipher.begin_message(block) : cipher.process_block(block);\n                        } else {\n                            block_type b = make_array<block_words>(cache.begin(), cache.end());\n                            typename block_type::const_iterator itr = block.begin() + (cache.max_size() - cache.size());\n\n                            std::copy(block.begin(), itr, b.end());\n\n                            ob = dgst.empty() ? cipher.begin_message(b) : cipher.process_block(b);\n\n                            cache.clear();\n                            cache.insert(cache.end(), itr, block.end());\n                        }\n\n                        std::move(ob.begin(), ob.end(), std::inserter(dgst, dgst.end()));\n                        seen += bits;\n                    }\n\n                    block::cipher<cipher_type, mode_type, padding_type> cipher;\n\n                    std::size_t seen;\n                    cache_type cache;\n                    result_type dgst;\n                };\n            }    // namespace impl\n\n            namespace tag {\n                template<typename Mode>\n                struct kdf : boost::accumulators::depends_on<> {\n                    typedef Mode mode_type;\n\n                    /// INTERNAL ONLY\n                    ///\n\n                    typedef boost::mpl::always<accumulators::impl::kdf_impl<Mode>> impl;\n                };\n            }    // namespace tag\n\n            namespace extract {\n                template<typename Mode, typename AccumulatorSet>\n                typename boost::mpl::apply<AccumulatorSet, tag::kdf<Mode>>::type::result_type\n                    kdf(const AccumulatorSet &acc) {\n                    return boost::accumulators::extract_result<tag::kdf<Mode>>(acc);\n                }\n            }    // namespace extract\n        }        // namespace accumulators\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ACCUMULATORS_BLOCK_HPP\n", "meta": {"hexsha": "fdc32920b67c04c4d81c0c3201e98dbbf85ef770", "size": 8062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/kdf/accumulators/kdf.hpp", "max_stars_repo_name": "NilFoundation/crypto3-kdf", "max_stars_repo_head_hexsha": "f7839580991b825e3857c0ec3fb7832b2cb9ad0c", "max_stars_repo_licenses": ["MIT"], "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/kdf/accumulators/kdf.hpp", "max_issues_repo_name": "NilFoundation/crypto3-kdf", "max_issues_repo_head_hexsha": "f7839580991b825e3857c0ec3fb7832b2cb9ad0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:20:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:28:30.000Z", "max_forks_repo_path": "include/nil/crypto3/kdf/accumulators/kdf.hpp", "max_forks_repo_name": "NilFoundation/crypto3-kdf", "max_forks_repo_head_hexsha": "f7839580991b825e3857c0ec3fb7832b2cb9ad0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-11T15:36:04.000Z", "avg_line_length": 43.3440860215, "max_line_length": 120, "alphanum_fraction": 0.5214586951, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.028870908095209008, "lm_q1q2_score": 0.012862842259828705}}
{"text": "/*\n *  Copyright (c) 2019--2023, The University of Hong Kong\n *  All rights reserved.\n *\n *  Author: 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#ifndef ESEKFOM_EKF_HPP\n#define ESEKFOM_EKF_HPP\n\n#include <cstdlib>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n#include <boost/bind.hpp>\n\n#include \"../mtk/build_manifold.hpp\"\n#include \"../mtk/startIdx.hpp\"\n#include \"../mtk/types/S2.hpp\"\n#include \"../mtk/types/SOn.hpp\"\n#include \"../mtk/types/vect.hpp\"\n#include \"util.hpp\"\n\n//#define USE_sparse\n\nnamespace esekfom {\n\nusing namespace Eigen;\n\n// used for iterated error state EKF update\n// for the aim to calculate  measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the\n// noise covariance (R) at the same time, by only one function. applied for measurement as a manifold.\ntemplate <typename S, typename M, int measurement_noise_dof = M::DOF>\nstruct share_datastruct {\n    bool valid;\n    bool converge;\n    M z;\n    Eigen::Matrix<typename S::scalar, M::DOF, measurement_noise_dof> h_v;\n    Eigen::Matrix<typename S::scalar, M::DOF, S::DOF> h_x;\n    Eigen::Matrix<typename S::scalar, measurement_noise_dof, measurement_noise_dof> R;\n};\n\n// used for iterated error state EKF update\n// for the aim to calculate  measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the\n// noise covariance (R) at the same time, by only one function. applied for measurement as an Eigen matrix whose\n// dimension is changing\ntemplate <typename T>\nstruct dyn_share_datastruct {\n    bool valid;\n    bool converge;\n    Eigen::Matrix<T, Eigen::Dynamic, 1> z;\n    Eigen::Matrix<T, Eigen::Dynamic, 1> h;\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> h_v;\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> h_x;\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> R;\n};\n\n// used for iterated error state EKF update\n// for the aim to calculate  measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the\n// noise covariance (R) at the same time, by only one function. applied for measurement as a dynamic manifold whose\n// dimension or type is changing\ntemplate <typename T>\nstruct dyn_runtime_share_datastruct {\n    bool valid;\n    bool converge;\n    // Z z;\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> h_v;\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> h_x;\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> R;\n};\n\ntemplate <typename state, int process_noise_dof, typename input = state, typename measurement = state,\n          int measurement_noise_dof = 0>\nclass esekf {\n    typedef esekf self;\n    enum { n = state::DOF, m = state::DIM, l = measurement::DOF };\n\n   public:\n    typedef typename state::scalar scalar_type;\n    typedef Matrix<scalar_type, n, n> cov;\n    typedef Matrix<scalar_type, m, n> cov_;\n    typedef SparseMatrix<scalar_type> spMt;\n    typedef Matrix<scalar_type, n, 1> vectorized_state;\n    typedef Matrix<scalar_type, m, 1> flatted_state;\n    typedef flatted_state processModel(state &, const input &);\n    typedef Eigen::Matrix<scalar_type, m, n> processMatrix1(state &, const input &);\n    typedef Eigen::Matrix<scalar_type, m, process_noise_dof> processMatrix2(state &, const input &);\n    typedef Eigen::Matrix<scalar_type, process_noise_dof, process_noise_dof> processnoisecovariance;\n    typedef measurement measurementModel(state &, bool &);\n    typedef measurement measurementModel_share(state &, share_datastruct<state, measurement, measurement_noise_dof> &);\n    typedef Eigen::Matrix<scalar_type, Eigen::Dynamic, 1> measurementModel_dyn(state &, bool &);\n    using measurementModel_dyn_share = std::function<void(state &, dyn_share_datastruct<scalar_type> &)>;\n\n    typedef Eigen::Matrix<scalar_type, l, n> measurementMatrix1(state &, bool &);\n    typedef Eigen::Matrix<scalar_type, Eigen::Dynamic, n> measurementMatrix1_dyn(state &, bool &);\n    typedef Eigen::Matrix<scalar_type, l, measurement_noise_dof> measurementMatrix2(state &, bool &);\n    typedef Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> measurementMatrix2_dyn(state &, bool &);\n    typedef Eigen::Matrix<scalar_type, measurement_noise_dof, measurement_noise_dof> measurementnoisecovariance;\n    typedef Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> measurementnoisecovariance_dyn;\n\n    esekf(const state &x = state(), const cov &P = cov::Identity()) : x_(x), P_(P) {\n#ifdef USE_sparse\n        SparseMatrix<scalar_type> ref(n, n);\n        ref.setIdentity();\n        l_ = ref;\n        f_x_2 = ref;\n        f_x_1 = ref;\n#endif\n    };\n\n    // receive system-specific models and their differentions.\n    // for measurement as a manifold.\n    void init(processModel f_in, processMatrix1 f_x_in, processMatrix2 f_w_in, measurementModel h_in,\n              measurementMatrix1 h_x_in, measurementMatrix2 h_v_in, int maximum_iteration,\n              scalar_type limit_vector[n]) {\n        f = f_in;\n        f_x = f_x_in;\n        f_w = f_w_in;\n        h = h_in;\n        h_x = h_x_in;\n        h_v = h_v_in;\n\n        maximum_iter = maximum_iteration;\n        for (int i = 0; i < n; i++) {\n            limit[i] = limit_vector[i];\n        }\n\n        x_.build_S2_state();\n        x_.build_SO3_state();\n        x_.build_vect_state();\n    }\n\n    // receive system-specific models and their differentions.\n    // for measurement as an Eigen matrix whose dimention is chaing.\n    void init_dyn(processModel f_in, processMatrix1 f_x_in, processMatrix2 f_w_in, measurementModel_dyn h_in,\n                  measurementMatrix1_dyn h_x_in, measurementMatrix2_dyn h_v_in, int maximum_iteration,\n                  scalar_type limit_vector[n]) {\n        f = f_in;\n        f_x = f_x_in;\n        f_w = f_w_in;\n        h_dyn = h_in;\n        h_x_dyn = h_x_in;\n        h_v_dyn = h_v_in;\n\n        maximum_iter = maximum_iteration;\n        for (int i = 0; i < n; i++) {\n            limit[i] = limit_vector[i];\n        }\n\n        x_.build_S2_state();\n        x_.build_SO3_state();\n        x_.build_vect_state();\n    }\n\n    // receive system-specific models and their differentions.\n    // for measurement as a dynamic manifold whose dimension or type is changing.\n    void init_dyn_runtime(processModel f_in, processMatrix1 f_x_in, processMatrix2 f_w_in,\n                          measurementMatrix1_dyn h_x_in, measurementMatrix2_dyn h_v_in, int maximum_iteration,\n                          scalar_type limit_vector[n]) {\n        f = f_in;\n        f_x = f_x_in;\n        f_w = f_w_in;\n        h_x_dyn = h_x_in;\n        h_v_dyn = h_v_in;\n\n        maximum_iter = maximum_iteration;\n        for (int i = 0; i < n; i++) {\n            limit[i] = limit_vector[i];\n        }\n\n        x_.build_S2_state();\n        x_.build_SO3_state();\n        x_.build_vect_state();\n    }\n\n    // receive system-specific models and their differentions\n    // for measurement as a manifold.\n    // calculate  measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the noise\n    // covariance (R) at the same time, by only one function (h_share_in).\n    void init_share(processModel f_in, processMatrix1 f_x_in, processMatrix2 f_w_in, measurementModel_share h_share_in,\n                    int maximum_iteration, scalar_type limit_vector[n]) {\n        f = f_in;\n        f_x = f_x_in;\n        f_w = f_w_in;\n        h_share = h_share_in;\n\n        maximum_iter = maximum_iteration;\n        for (int i = 0; i < n; i++) {\n            limit[i] = limit_vector[i];\n        }\n\n        x_.build_S2_state();\n        x_.build_SO3_state();\n        x_.build_vect_state();\n    }\n\n    // receive system-specific models and their differentions\n    // for measurement as an Eigen matrix whose dimension is changing.\n    // calculate  measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the noise\n    // covariance (R) at the same time, by only one function (h_dyn_share_in).\n    void init_dyn_share(processModel f_in, processMatrix1 f_x_in, processMatrix2 f_w_in,\n                        measurementModel_dyn_share h_dyn_share_in, int maximum_iteration, scalar_type limit_vector[n]) {\n        f = f_in;\n        f_x = f_x_in;\n        f_w = f_w_in;\n        h_dyn_share = h_dyn_share_in;\n\n        maximum_iter = maximum_iteration;\n        for (int i = 0; i < n; i++) {\n            limit[i] = limit_vector[i];\n        }\n\n        x_.build_S2_state();\n        x_.build_SO3_state();\n        x_.build_vect_state();\n    }\n\n    // receive system-specific models and their differentions\n    // for measurement as a dynamic manifold whose dimension  or type is changing.\n    // calculate  measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the noise\n    // covariance (R) at the same time, by only one function (h_dyn_share_in). for any scenarios where it is needed\n    void init_dyn_runtime_share(processModel f_in, processMatrix1 f_x_in, processMatrix2 f_w_in, int maximum_iteration,\n                                scalar_type limit_vector[n]) {\n        f = f_in;\n        f_x = f_x_in;\n        f_w = f_w_in;\n\n        maximum_iter = maximum_iteration;\n        for (int i = 0; i < n; i++) {\n            limit[i] = limit_vector[i];\n        }\n\n        x_.build_S2_state();\n        x_.build_SO3_state();\n        x_.build_vect_state();\n    }\n\n    // iterated error state EKF propogation\n    void predict(double &dt, processnoisecovariance &Q, const input &i_in) {\n        flatted_state f_ = f(x_, i_in);\n        cov_ f_x_ = f_x(x_, i_in);\n        cov f_x_final;\n\n        Matrix<scalar_type, m, process_noise_dof> f_w_ = f_w(x_, i_in);\n        Matrix<scalar_type, n, process_noise_dof> f_w_final;\n        state x_before = x_;\n        x_.oplus(f_, dt);\n\n        F_x1 = cov::Identity();\n        for (std::vector<std::pair<std::pair<int, int>, int>>::iterator it = x_.vect_state.begin();\n             it != x_.vect_state.end(); it++) {\n            int idx = (*it).first.first;\n            int dim = (*it).first.second;\n            int dof = (*it).second;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < dof; j++) {\n                    f_x_final(idx + j, i) = f_x_(dim + j, i);\n                }\n            }\n            for (int i = 0; i < process_noise_dof; i++) {\n                for (int j = 0; j < dof; j++) {\n                    f_w_final(idx + j, i) = f_w_(dim + j, i);\n                }\n            }\n        }\n        Matrix<scalar_type, 3, 3> res_temp_SO3;\n        MTK::vect<3, scalar_type> seg_SO3;\n        for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n            int idx = (*it).first;\n            int dim = (*it).second;\n            for (int i = 0; i < 3; i++) {\n                seg_SO3(i) = -1 * f_(dim + i) * dt;\n            }\n            MTK::SO3<scalar_type> res;\n            res.w() = MTK::exp<scalar_type, 3>(res.vec(), seg_SO3, scalar_type(1 / 2));\n#ifdef USE_sparse\n            res_temp_SO3 = res.toRotationMatrix();\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    f_x_1.coeffRef(idx + i, idx + j) = res_temp_SO3(i, j);\n                }\n            }\n#else\n            F_x1.template block<3, 3>(idx, idx) = res.toRotationMatrix();\n#endif\n            res_temp_SO3 = MTK::A_matrix(seg_SO3);\n            for (int i = 0; i < n; i++) {\n                f_x_final.template block<3, 1>(idx, i) = res_temp_SO3 * (f_x_.template block<3, 1>(dim, i));\n            }\n            for (int i = 0; i < process_noise_dof; i++) {\n                f_w_final.template block<3, 1>(idx, i) = res_temp_SO3 * (f_w_.template block<3, 1>(dim, i));\n            }\n        }\n\n        Matrix<scalar_type, 2, 3> res_temp_S2;\n        Matrix<scalar_type, 2, 2> res_temp_S2_;\n        MTK::vect<3, scalar_type> seg_S2;\n        for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n            int idx = (*it).first;\n            int dim = (*it).second;\n            for (int i = 0; i < 3; i++) {\n                seg_S2(i) = f_(dim + i) * dt;\n            }\n            MTK::vect<2, scalar_type> vec = MTK::vect<2, scalar_type>::Zero();\n            MTK::SO3<scalar_type> res;\n            res.w() = MTK::exp<scalar_type, 3>(res.vec(), seg_S2, scalar_type(1 / 2));\n            Eigen::Matrix<scalar_type, 2, 3> Nx;\n            Eigen::Matrix<scalar_type, 3, 2> Mx;\n            x_.S2_Nx_yy(Nx, idx);\n            x_before.S2_Mx(Mx, vec, idx);\n#ifdef USE_sparse\n            res_temp_S2_ = Nx * res.toRotationMatrix() * Mx;\n            for (int i = 0; i < 2; i++) {\n                for (int j = 0; j < 2; j++) {\n                    f_x_1.coeffRef(idx + i, idx + j) = res_temp_S2_(i, j);\n                }\n            }\n#else\n            F_x1.template block<2, 2>(idx, idx) = Nx * res.toRotationMatrix() * Mx;\n#endif\n\n            Eigen::Matrix<scalar_type, 3, 3> x_before_hat;\n            x_before.S2_hat(x_before_hat, idx);\n            res_temp_S2 = -Nx * res.toRotationMatrix() * x_before_hat * MTK::A_matrix(seg_S2).transpose();\n\n            for (int i = 0; i < n; i++) {\n                f_x_final.template block<2, 1>(idx, i) = res_temp_S2 * (f_x_.template block<3, 1>(dim, i));\n            }\n            for (int i = 0; i < process_noise_dof; i++) {\n                f_w_final.template block<2, 1>(idx, i) = res_temp_S2 * (f_w_.template block<3, 1>(dim, i));\n            }\n        }\n\n#ifdef USE_sparse\n        f_x_1.makeCompressed();\n        spMt f_x2 = f_x_final.sparseView();\n        spMt f_w1 = f_w_final.sparseView();\n        spMt xp = f_x_1 + f_x2 * dt;\n        P_ = xp * P_ * xp.transpose() + (f_w1 * dt) * Q * (f_w1 * dt).transpose();\n#else\n        F_x1 += f_x_final * dt;\n        P_ = (F_x1)*P_ * (F_x1).transpose() + (dt * f_w_final) * Q * (dt * f_w_final).transpose();\n#endif\n    }\n\n    // iterated error state EKF update for measurement as a manifold.\n    void update_iterated(measurement &z, measurementnoisecovariance &R) {\n        if (!(is_same<typename measurement::scalar, scalar_type>())) {\n            std::cerr << \"the scalar type of measurment must be the same as the state\" << std::endl;\n            std::exit(100);\n        }\n        int t = 0;\n        bool converg = true;\n        bool valid = true;\n        state x_propagated = x_;\n        cov P_propagated = P_;\n\n        for (int i = -1; i < maximum_iter; i++) {\n            vectorized_state dx, dx_new;\n            x_.boxminus(dx, x_propagated);\n            dx_new = dx;\n#ifdef USE_sparse\n            spMt h_x_ = h_x(x_, valid).sparseView();\n            spMt h_v_ = h_v(x_, valid).sparseView();\n            spMt R_ = R.sparseView();\n#else\n            Matrix<scalar_type, l, n> h_x_ = h_x(x_, valid);\n            Matrix<scalar_type, l, Eigen::Dynamic> h_v_ = h_v(x_, valid);\n#endif\n            if (!valid) {\n                continue;\n            }\n\n            P_ = P_propagated;\n\n            Matrix<scalar_type, 3, 3> res_temp_SO3;\n            MTK::vect<3, scalar_type> seg_SO3;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 3; i++) {\n                    seg_SO3(i) = dx(idx + i);\n                }\n\n                res_temp_SO3 = A_matrix(seg_SO3).transpose();\n                dx_new.template block<3, 1>(idx, 0) = res_temp_SO3 * dx.template block<3, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                }\n            }\n\n            Matrix<scalar_type, 2, 2> res_temp_S2;\n            MTK::vect<2, scalar_type> seg_S2;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 2; i++) {\n                    seg_S2(i) = dx(idx + i);\n                }\n\n                Eigen::Matrix<scalar_type, 2, 3> Nx;\n                Eigen::Matrix<scalar_type, 3, 2> Mx;\n                x_.S2_Nx_yy(Nx, idx);\n                x_propagated.S2_Mx(Mx, seg_S2, idx);\n                res_temp_S2 = Nx * Mx;\n                dx_new.template block<2, 1>(idx, 0) = res_temp_S2 * dx.template block<2, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                }\n            }\n\n            Matrix<scalar_type, n, l> K_;\n            if (n > l) {\n#ifdef USE_sparse\n                Matrix<scalar_type, l, l> K_temp = h_x_ * P_ * h_x_.transpose();\n                spMt R_temp = h_v_ * R_ * h_v_.transpose();\n                K_temp += R_temp;\n                K_ = P_ * h_x_.transpose() * K_temp.inverse();\n#else\n                K_ = P_ * h_x_.transpose() * (h_x_ * P_ * h_x_.transpose() + h_v_ * R * h_v_.transpose()).inverse();\n#endif\n            } else {\n#ifdef USE_sparse\n                measurementnoisecovariance b = measurementnoisecovariance::Identity();\n                Eigen::SparseQR<Eigen::SparseMatrix<scalar_type>, Eigen::COLAMDOrdering<int>> solver;\n                solver.compute(R_);\n                measurementnoisecovariance R_in_temp = solver.solve(b);\n                spMt R_in = R_in_temp.sparseView();\n                spMt K_temp = h_x_.transpose() * R_in * h_x_;\n                cov_ P_temp = P_.inverse();\n                P_temp += K_temp;\n                K_ = P_temp.inverse() * h_x_.transpose() * R_in;\n#else\n                measurementnoisecovariance R_in = (h_v_ * R * h_v_.transpose()).inverse();\n                K_ = (h_x_.transpose() * R_in * h_x_ + P_.inverse()).inverse() * h_x_.transpose() * R_in;\n#endif\n            }\n            Matrix<scalar_type, l, 1> innovation;\n            z.boxminus(innovation, h(x_, valid));\n            cov K_x = K_ * h_x_;\n            Matrix<scalar_type, n, 1> dx_ = K_ * innovation + (K_x - Matrix<scalar_type, n, n>::Identity()) * dx_new;\n            state x_before = x_;\n            x_.boxplus(dx_);\n\n            converg = true;\n            for (int i = 0; i < n; i++) {\n                if (std::fabs(dx_[i]) > limit[i]) {\n                    converg = false;\n                    break;\n                }\n            }\n\n            if (converg) t++;\n\n            if (t > 1 || i == maximum_iter - 1) {\n                L_ = P_;\n\n                Matrix<scalar_type, 3, 3> res_temp_SO3;\n                MTK::vect<3, scalar_type> seg_SO3;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin();\n                     it != x_.SO3_state.end(); it++) {\n                    int idx = (*it).first;\n                    for (int i = 0; i < 3; i++) {\n                        seg_SO3(i) = dx_(i + idx);\n                    }\n                    res_temp_SO3 = A_matrix(seg_SO3).transpose();\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                    }\n                    if (n > l) {\n                        for (int i = 0; i < l; i++) {\n                            K_.template block<3, 1>(idx, i) = res_temp_SO3 * (K_.template block<3, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<3, 1>(idx, i) = res_temp_SO3 * (K_x.template block<3, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 3>(i, idx) = (L_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                        P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                    }\n                }\n\n                Matrix<scalar_type, 2, 2> res_temp_S2;\n                MTK::vect<2, scalar_type> seg_S2;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin();\n                     it != x_.S2_state.end(); it++) {\n                    int idx = (*it).first;\n\n                    for (int i = 0; i < 2; i++) {\n                        seg_S2(i) = dx_(i + idx);\n                    }\n\n                    Eigen::Matrix<scalar_type, 2, 3> Nx;\n                    Eigen::Matrix<scalar_type, 3, 2> Mx;\n                    x_.S2_Nx_yy(Nx, idx);\n                    x_propagated.S2_Mx(Mx, seg_S2, idx);\n                    res_temp_S2 = Nx * Mx;\n\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                    }\n                    if (n > l) {\n                        for (int i = 0; i < l; i++) {\n                            K_.template block<2, 1>(idx, i) = res_temp_S2 * (K_.template block<2, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<2, 1>(idx, i) = res_temp_S2 * (K_x.template block<2, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 2>(i, idx) = (L_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                        P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                    }\n                }\n                if (n > l) {\n                    P_ = L_ - K_ * h_x_ * P_;\n                } else {\n                    P_ = L_ - K_x * P_;\n                }\n                return;\n            }\n        }\n    }\n\n    // iterated error state EKF update for measurement as a manifold.\n    // calculate measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the noise\n    // covariance (R) at the same time, by only one function.\n    void update_iterated_share() {\n        if (!(is_same<typename measurement::scalar, scalar_type>())) {\n            std::cerr << \"the scalar type of measurment must be the same as the state\" << std::endl;\n            std::exit(100);\n        }\n\n        int t = 0;\n        share_datastruct<state, measurement, measurement_noise_dof> _share;\n        _share.valid = true;\n        _share.converge = true;\n        state x_propagated = x_;\n        cov P_propagated = P_;\n\n        for (int i = -1; i < maximum_iter; i++) {\n            vectorized_state dx, dx_new;\n            x_.boxminus(dx, x_propagated);\n            dx_new = dx;\n            measurement h = h_share(x_, _share);\n            measurement z = _share.z;\n            measurementnoisecovariance R = _share.R;\n#ifdef USE_sparse\n            spMt h_x_ = _share.h_x.sparseView();\n            spMt h_v_ = _share.h_v.sparseView();\n            spMt R_ = _share.R.sparseView();\n#else\n            Matrix<scalar_type, l, n> h_x_ = _share.h_x;\n            Matrix<scalar_type, l, Eigen::Dynamic> h_v_ = _share.h_v;\n#endif\n            if (!_share.valid) {\n                continue;\n            }\n\n            P_ = P_propagated;\n\n            Matrix<scalar_type, 3, 3> res_temp_SO3;\n            MTK::vect<3, scalar_type> seg_SO3;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 3; i++) {\n                    seg_SO3(i) = dx(idx + i);\n                }\n\n                res_temp_SO3 = A_matrix(seg_SO3).transpose();\n                dx_new.template block<3, 1>(idx, 0) = res_temp_SO3 * dx.template block<3, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                }\n            }\n\n            Matrix<scalar_type, 2, 2> res_temp_S2;\n            MTK::vect<2, scalar_type> seg_S2;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 2; i++) {\n                    seg_S2(i) = dx(idx + i);\n                }\n\n                Eigen::Matrix<scalar_type, 2, 3> Nx;\n                Eigen::Matrix<scalar_type, 3, 2> Mx;\n                x_.S2_Nx_yy(Nx, idx);\n                x_propagated.S2_Mx(Mx, seg_S2, idx);\n                res_temp_S2 = Nx * Mx;\n                dx_new.template block<2, 1>(idx, 0) = res_temp_S2 * dx.template block<2, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                }\n            }\n\n            Matrix<scalar_type, n, l> K_;\n            if (n > l) {\n#ifdef USE_sparse\n                Matrix<scalar_type, l, l> K_temp = h_x_ * P_ * h_x_.transpose();\n                spMt R_temp = h_v_ * R_ * h_v_.transpose();\n                K_temp += R_temp;\n                K_ = P_ * h_x_.transpose() * K_temp.inverse();\n#else\n                K_ = P_ * h_x_.transpose() * (h_x_ * P_ * h_x_.transpose() + h_v_ * R * h_v_.transpose()).inverse();\n#endif\n            } else {\n#ifdef USE_sparse\n                measurementnoisecovariance b = measurementnoisecovariance::Identity();\n                Eigen::SparseQR<Eigen::SparseMatrix<scalar_type>, Eigen::COLAMDOrdering<int>> solver;\n                solver.compute(R_);\n                measurementnoisecovariance R_in_temp = solver.solve(b);\n                spMt R_in = R_in_temp.sparseView();\n                spMt K_temp = h_x_.transpose() * R_in * h_x_;\n                cov_ P_temp = P_.inverse();\n                P_temp += K_temp;\n                K_ = P_temp.inverse() * h_x_.transpose() * R_in;\n#else\n                measurementnoisecovariance R_in = (h_v_ * R * h_v_.transpose()).inverse();\n                K_ = (h_x_.transpose() * R_in * h_x_ + P_.inverse()).inverse() * h_x_.transpose() * R_in;\n#endif\n            }\n            Matrix<scalar_type, l, 1> innovation;\n            z.boxminus(innovation, h);\n            cov K_x = K_ * h_x_;\n            Matrix<scalar_type, n, 1> dx_ = K_ * innovation + (K_x - Matrix<scalar_type, n, n>::Identity()) * dx_new;\n            state x_before = x_;\n            x_.boxplus(dx_);\n\n            _share.converge = true;\n            for (int i = 0; i < n; i++) {\n                if (std::fabs(dx_[i]) > limit[i]) {\n                    _share.converge = false;\n                    break;\n                }\n            }\n\n            if (_share.converge) t++;\n\n            if (t > 1 || i == maximum_iter - 1) {\n                L_ = P_;\n\n                Matrix<scalar_type, 3, 3> res_temp_SO3;\n                MTK::vect<3, scalar_type> seg_SO3;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin();\n                     it != x_.SO3_state.end(); it++) {\n                    int idx = (*it).first;\n                    for (int i = 0; i < 3; i++) {\n                        seg_SO3(i) = dx_(i + idx);\n                    }\n                    res_temp_SO3 = A_matrix(seg_SO3).transpose();\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                    }\n                    if (n > l) {\n                        for (int i = 0; i < l; i++) {\n                            K_.template block<3, 1>(idx, i) = res_temp_SO3 * (K_.template block<3, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<3, 1>(idx, i) = res_temp_SO3 * (K_x.template block<3, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 3>(i, idx) = (L_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                        P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                    }\n                }\n\n                Matrix<scalar_type, 2, 2> res_temp_S2;\n                MTK::vect<2, scalar_type> seg_S2;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin();\n                     it != x_.S2_state.end(); it++) {\n                    int idx = (*it).first;\n\n                    for (int i = 0; i < 2; i++) {\n                        seg_S2(i) = dx_(i + idx);\n                    }\n\n                    Eigen::Matrix<scalar_type, 2, 3> Nx;\n                    Eigen::Matrix<scalar_type, 3, 2> Mx;\n                    x_.S2_Nx_yy(Nx, idx);\n                    x_propagated.S2_Mx(Mx, seg_S2, idx);\n                    res_temp_S2 = Nx * Mx;\n\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                    }\n                    if (n > l) {\n                        for (int i = 0; i < l; i++) {\n                            K_.template block<2, 1>(idx, i) = res_temp_S2 * (K_.template block<2, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<2, 1>(idx, i) = res_temp_S2 * (K_x.template block<2, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 2>(i, idx) = (L_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                        P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                    }\n                }\n                if (n > l) {\n                    P_ = L_ - K_ * h_x_ * P_;\n                } else {\n                    P_ = L_ - K_x * P_;\n                }\n                return;\n            }\n        }\n    }\n\n    // iterated error state EKF update for measurement as an Eigen matrix whose dimension is changing.\n    void update_iterated_dyn(Eigen::Matrix<scalar_type, Eigen::Dynamic, 1> z, measurementnoisecovariance_dyn R) {\n        int t = 0;\n        bool valid = true;\n        bool converg = true;\n        state x_propagated = x_;\n        cov P_propagated = P_;\n        int dof_Measurement;\n        int dof_Measurement_noise = R.rows();\n        for (int i = -1; i < maximum_iter; i++) {\n            valid = true;\n#ifdef USE_sparse\n            spMt h_x_ = h_x_dyn(x_, valid).sparseView();\n            spMt h_v_ = h_v_dyn(x_, valid).sparseView();\n            spMt R_ = R.sparseView();\n#else\n            Matrix<scalar_type, Eigen::Dynamic, n> h_x_ = h_x_dyn(x_, valid);\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_v_ = h_v_dyn(x_, valid);\n#endif\n            Matrix<scalar_type, Eigen::Dynamic, 1> h_ = h_dyn(x_, valid);\n            dof_Measurement = h_.rows();\n            vectorized_state dx, dx_new;\n            x_.boxminus(dx, x_propagated);\n            dx_new = dx;\n            if (!valid) {\n                continue;\n            }\n\n            P_ = P_propagated;\n            Matrix<scalar_type, 3, 3> res_temp_SO3;\n            MTK::vect<3, scalar_type> seg_SO3;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 3; i++) {\n                    seg_SO3(i) = dx(idx + i);\n                }\n\n                res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                dx_new.template block<3, 1>(idx, 0) = res_temp_SO3 * dx_new.template block<3, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                }\n            }\n\n            Matrix<scalar_type, 2, 2> res_temp_S2;\n            MTK::vect<2, scalar_type> seg_S2;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 2; i++) {\n                    seg_S2(i) = dx(idx + i);\n                }\n\n                Eigen::Matrix<scalar_type, 2, 3> Nx;\n                Eigen::Matrix<scalar_type, 3, 2> Mx;\n                x_.S2_Nx_yy(Nx, idx);\n                x_propagated.S2_Mx(Mx, seg_S2, idx);\n                res_temp_S2 = Nx * Mx;\n                dx_new.template block<2, 1>(idx, 0) = res_temp_S2 * dx_new.template block<2, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                }\n            }\n\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_;\n            if (n > dof_Measurement) {\n#ifdef USE_sparse\n                Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_temp = h_x_ * P_ * h_x_.transpose();\n                spMt R_temp = h_v_ * R_ * h_v_.transpose();\n                K_temp += R_temp;\n                K_ = P_ * h_x_.transpose() * K_temp.inverse();\n#else\n                K_ = P_ * h_x_.transpose() * (h_x_ * P_ * h_x_.transpose() + h_v_ * R * h_v_.transpose()).inverse();\n#endif\n            } else {\n#ifdef USE_sparse\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> b =\n                    Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic>::Identity(dof_Measurement_noise,\n                                                                                         dof_Measurement_noise);\n                Eigen::SparseQR<Eigen::SparseMatrix<scalar_type>, Eigen::COLAMDOrdering<int>> solver;\n                solver.compute(R_);\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in_temp = solver.solve(b);\n                spMt R_in = R_in_temp.sparseView();\n                spMt K_temp = h_x_.transpose() * R_in * h_x_;\n                cov_ P_temp = P_.inverse();\n                P_temp += K_temp;\n                K_ = P_temp.inverse() * h_x_.transpose() * R_in;\n#else\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in =\n                    (h_v_ * R * h_v_.transpose()).inverse();\n                K_ = (h_x_.transpose() * R_in * h_x_ + P_.inverse()).inverse() * h_x_.transpose() * R_in;\n#endif\n            }\n            cov K_x = K_ * h_x_;\n            Matrix<scalar_type, n, 1> dx_ = K_ * (z - h_) + (K_x - Matrix<scalar_type, n, n>::Identity()) * dx_new;\n            state x_before = x_;\n            x_.boxplus(dx_);\n            converg = true;\n            for (int i = 0; i < n; i++) {\n                if (std::fabs(dx_[i]) > limit[i]) {\n                    converg = false;\n                    break;\n                }\n            }\n            if (converg) t++;\n            if (t > 1 || i == maximum_iter - 1) {\n                L_ = P_;\n                std::cout << \"iteration time:\" << t << \",\" << i << std::endl;\n\n                Matrix<scalar_type, 3, 3> res_temp_SO3;\n                MTK::vect<3, scalar_type> seg_SO3;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin();\n                     it != x_.SO3_state.end(); it++) {\n                    int idx = (*it).first;\n                    for (int i = 0; i < 3; i++) {\n                        seg_SO3(i) = dx_(i + idx);\n                    }\n                    res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<3, 1>(idx, i) = res_temp_SO3 * (K_.template block<3, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<3, 1>(idx, i) = res_temp_SO3 * (K_x.template block<3, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 3>(i, idx) = (L_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                        P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                    }\n                }\n\n                Matrix<scalar_type, 2, 2> res_temp_S2;\n                MTK::vect<2, scalar_type> seg_S2;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin();\n                     it != x_.S2_state.end(); it++) {\n                    int idx = (*it).first;\n\n                    for (int i = 0; i < 2; i++) {\n                        seg_S2(i) = dx_(i + idx);\n                    }\n\n                    Eigen::Matrix<scalar_type, 2, 3> Nx;\n                    Eigen::Matrix<scalar_type, 3, 2> Mx;\n                    x_.S2_Nx_yy(Nx, idx);\n                    x_propagated.S2_Mx(Mx, seg_S2, idx);\n                    res_temp_S2 = Nx * Mx;\n\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<2, 1>(idx, i) = res_temp_S2 * (K_.template block<2, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<2, 1>(idx, i) = res_temp_S2 * (K_x.template block<2, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 2>(i, idx) = (L_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                        P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                    }\n                }\n                if (n > dof_Measurement) {\n                    P_ = L_ - K_ * h_x_ * P_;\n                } else {\n                    P_ = L_ - K_x * P_;\n                }\n                return;\n            }\n        }\n    }\n    // iterated error state EKF update for measurement as an Eigen matrix whose dimension is changing.\n    // calculate measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the noise\n    // covariance (R) at the same time, by only one function.\n    void update_iterated_dyn_share() {\n        int t = 0;\n        dyn_share_datastruct<scalar_type> dyn_share;\n        dyn_share.valid = true;\n        dyn_share.converge = true;\n        state x_propagated = x_;\n        cov P_propagated = P_;\n        int dof_Measurement;\n        int dof_Measurement_noise;\n        for (int i = -1; i < maximum_iter; i++) {\n            dyn_share.valid = true;\n            h_dyn_share(x_, dyn_share);\n            // Matrix<scalar_type, Eigen::Dynamic, 1> h = h_dyn_share (x_,  dyn_share);\n            Matrix<scalar_type, Eigen::Dynamic, 1> z = dyn_share.z;\n            Matrix<scalar_type, Eigen::Dynamic, 1> h = dyn_share.h;\n#ifdef USE_sparse\n            spMt h_x = dyn_share.h_x.sparseView();\n            spMt h_v = dyn_share.h_v.sparseView();\n            spMt R_ = dyn_share.R.sparseView();\n#else\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R = dyn_share.R;\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_x = dyn_share.h_x;\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_v = dyn_share.h_v;\n#endif\n            dof_Measurement = h_x.rows();\n            dof_Measurement_noise = dyn_share.R.rows();\n            vectorized_state dx, dx_new;\n            x_.boxminus(dx, x_propagated);\n            dx_new = dx;\n            if (!(dyn_share.valid)) {\n                continue;\n            }\n\n            P_ = P_propagated;\n            Matrix<scalar_type, 3, 3> res_temp_SO3;\n            MTK::vect<3, scalar_type> seg_SO3;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 3; i++) {\n                    seg_SO3(i) = dx(idx + i);\n                }\n\n                res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                dx_new.template block<3, 1>(idx, 0) = res_temp_SO3 * dx_new.template block<3, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                }\n            }\n\n            Matrix<scalar_type, 2, 2> res_temp_S2;\n            MTK::vect<2, scalar_type> seg_S2;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 2; i++) {\n                    seg_S2(i) = dx(idx + i);\n                }\n\n                Eigen::Matrix<scalar_type, 2, 3> Nx;\n                Eigen::Matrix<scalar_type, 3, 2> Mx;\n                x_.S2_Nx_yy(Nx, idx);\n                x_propagated.S2_Mx(Mx, seg_S2, idx);\n                res_temp_S2 = Nx * Mx;\n                dx_new.template block<2, 1>(idx, 0) = res_temp_S2 * dx_new.template block<2, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                }\n            }\n\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_;\n            if (n > dof_Measurement) {\n#ifdef USE_sparse\n                Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_temp = h_x * P_ * h_x.transpose();\n                spMt R_temp = h_v * R_ * h_v.transpose();\n                K_temp += R_temp;\n                K_ = P_ * h_x.transpose() * K_temp.inverse();\n#else\n                K_ = P_ * h_x.transpose() * (h_x * P_ * h_x.transpose() + h_v * R * h_v.transpose()).inverse();\n#endif\n            } else {\n#ifdef USE_sparse\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> b =\n                    Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic>::Identity(dof_Measurement_noise,\n                                                                                         dof_Measurement_noise);\n                Eigen::SparseQR<Eigen::SparseMatrix<scalar_type>, Eigen::COLAMDOrdering<int>> solver;\n                solver.compute(R_);\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in_temp = solver.solve(b);\n                spMt R_in = R_in_temp.sparseView();\n                spMt K_temp = h_x.transpose() * R_in * h_x;\n                cov_ P_temp = P_.inverse();\n                P_temp += K_temp;\n                K_ = P_temp.inverse() * h_x.transpose() * R_in;\n#else\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in = (h_v * R * h_v.transpose()).inverse();\n                K_ = (h_x.transpose() * R_in * h_x + P_.inverse()).inverse() * h_x.transpose() * R_in;\n#endif\n            }\n\n            cov K_x = K_ * h_x;\n            Matrix<scalar_type, n, 1> dx_ = K_ * (z - h) + (K_x - Matrix<scalar_type, n, n>::Identity()) * dx_new;\n            state x_before = x_;\n            x_.boxplus(dx_);\n            dyn_share.converge = true;\n            for (int i = 0; i < n; i++) {\n                if (std::fabs(dx_[i]) > limit[i]) {\n                    dyn_share.converge = false;\n                    break;\n                }\n            }\n            if (dyn_share.converge) t++;\n            if (t > 1 || i == maximum_iter - 1) {\n                L_ = P_;\n                std::cout << \"iteration time:\" << t << \",\" << i << std::endl;\n\n                Matrix<scalar_type, 3, 3> res_temp_SO3;\n                MTK::vect<3, scalar_type> seg_SO3;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin();\n                     it != x_.SO3_state.end(); it++) {\n                    int idx = (*it).first;\n                    for (int i = 0; i < 3; i++) {\n                        seg_SO3(i) = dx_(i + idx);\n                    }\n                    res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                    for (int i = 0; i < int(n); i++) {\n                        L_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<3, 1>(idx, i) = res_temp_SO3 * (K_.template block<3, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<3, 1>(idx, i) = res_temp_SO3 * (K_x.template block<3, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 3>(i, idx) = (L_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                        P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                    }\n                }\n\n                Matrix<scalar_type, 2, 2> res_temp_S2;\n                MTK::vect<2, scalar_type> seg_S2;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin();\n                     it != x_.S2_state.end(); it++) {\n                    int idx = (*it).first;\n\n                    for (int i = 0; i < 2; i++) {\n                        seg_S2(i) = dx_(i + idx);\n                    }\n\n                    Eigen::Matrix<scalar_type, 2, 3> Nx;\n                    Eigen::Matrix<scalar_type, 3, 2> Mx;\n                    x_.S2_Nx_yy(Nx, idx);\n                    x_propagated.S2_Mx(Mx, seg_S2, idx);\n                    res_temp_S2 = Nx * Mx;\n\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<2, 1>(idx, i) = res_temp_S2 * (K_.template block<2, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<2, 1>(idx, i) = res_temp_S2 * (K_x.template block<2, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 2>(i, idx) = (L_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                        P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                    }\n                }\n                if (n > dof_Measurement) {\n                    P_ = L_ - K_ * h_x * P_;\n                } else {\n                    P_ = L_ - K_x * P_;\n                }\n                return;\n            }\n        }\n    }\n\n    // iterated error state EKF update for measurement as a dynamic manifold, whose dimension or type is changing.\n    // the measurement and the measurement model are received in a dynamic manner.\n    template <typename measurement_runtime, typename measurementModel_runtime>\n    void update_iterated_dyn_runtime(measurement_runtime z, measurementnoisecovariance_dyn R,\n                                     measurementModel_runtime h_runtime) {\n        int t = 0;\n        bool valid = true;\n        bool converg = true;\n        state x_propagated = x_;\n        cov P_propagated = P_;\n        int dof_Measurement;\n        int dof_Measurement_noise;\n        for (int i = -1; i < maximum_iter; i++) {\n            valid = true;\n#ifdef USE_sparse\n            spMt h_x_ = h_x_dyn(x_, valid).sparseView();\n            spMt h_v_ = h_v_dyn(x_, valid).sparseView();\n            spMt R_ = R.sparseView();\n#else\n            Matrix<scalar_type, Eigen::Dynamic, n> h_x_ = h_x_dyn(x_, valid);\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_v_ = h_v_dyn(x_, valid);\n#endif\n            measurement_runtime h_ = h_runtime(x_, valid);\n            dof_Measurement = measurement_runtime::DOF;\n            dof_Measurement_noise = R.rows();\n            vectorized_state dx, dx_new;\n            x_.boxminus(dx, x_propagated);\n            dx_new = dx;\n            if (!valid) {\n                continue;\n            }\n\n            P_ = P_propagated;\n            Matrix<scalar_type, 3, 3> res_temp_SO3;\n            MTK::vect<3, scalar_type> seg_SO3;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 3; i++) {\n                    seg_SO3(i) = dx(idx + i);\n                }\n\n                res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                dx_new.template block<3, 1>(idx, 0) = res_temp_SO3 * dx_new.template block<3, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                }\n            }\n\n            Matrix<scalar_type, 2, 2> res_temp_S2;\n            MTK::vect<2, scalar_type> seg_S2;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 2; i++) {\n                    seg_S2(i) = dx(idx + i);\n                }\n\n                Eigen::Matrix<scalar_type, 2, 3> Nx;\n                Eigen::Matrix<scalar_type, 3, 2> Mx;\n                x_.S2_Nx_yy(Nx, idx);\n                x_propagated.S2_Mx(Mx, seg_S2, idx);\n                res_temp_S2 = Nx * Mx;\n                dx_new.template block<2, 1>(idx, 0) = res_temp_S2 * dx_new.template block<2, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                }\n            }\n\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_;\n            if (n > dof_Measurement) {\n#ifdef USE_sparse\n                Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_temp = h_x_ * P_ * h_x_.transpose();\n                spMt R_temp = h_v_ * R_ * h_v_.transpose();\n                K_temp += R_temp;\n                K_ = P_ * h_x_.transpose() * K_temp.inverse();\n#else\n                K_ = P_ * h_x_.transpose() * (h_x_ * P_ * h_x_.transpose() + h_v_ * R * h_v_.transpose()).inverse();\n#endif\n            } else {\n#ifdef USE_sparse\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> b =\n                    Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic>::Identity(dof_Measurement_noise,\n                                                                                         dof_Measurement_noise);\n                Eigen::SparseQR<Eigen::SparseMatrix<scalar_type>, Eigen::COLAMDOrdering<int>> solver;\n                solver.compute(R_);\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in_temp = solver.solve(b);\n                spMt R_in = R_in_temp.sparseView();\n                spMt K_temp = h_x_.transpose() * R_in * h_x_;\n                cov_ P_temp = P_.inverse();\n                P_temp += K_temp;\n                K_ = P_temp.inverse() * h_x_.transpose() * R_in;\n#else\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in =\n                    (h_v_ * R * h_v_.transpose()).inverse();\n                K_ = (h_x_.transpose() * R_in * h_x_ + P_.inverse()).inverse() * h_x_.transpose() * R_in;\n#endif\n            }\n            cov K_x = K_ * h_x_;\n            Eigen::Matrix<scalar_type, measurement_runtime::DOF, 1> innovation;\n            z.boxminus(innovation, h_);\n            Matrix<scalar_type, n, 1> dx_ = K_ * innovation + (K_x - Matrix<scalar_type, n, n>::Identity()) * dx_new;\n            state x_before = x_;\n            x_.boxplus(dx_);\n            converg = true;\n            for (int i = 0; i < n; i++) {\n                if (std::fabs(dx_[i]) > limit[i]) {\n                    converg = false;\n                    break;\n                }\n            }\n            if (converg) t++;\n            if (t > 1 || i == maximum_iter - 1) {\n                L_ = P_;\n                std::cout << \"iteration time:\" << t << \",\" << i << std::endl;\n\n                Matrix<scalar_type, 3, 3> res_temp_SO3;\n                MTK::vect<3, scalar_type> seg_SO3;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin();\n                     it != x_.SO3_state.end(); it++) {\n                    int idx = (*it).first;\n                    for (int i = 0; i < 3; i++) {\n                        seg_SO3(i) = dx_(i + idx);\n                    }\n                    res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<3, 1>(idx, i) = res_temp_SO3 * (K_.template block<3, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<3, 1>(idx, i) = res_temp_SO3 * (K_x.template block<3, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 3>(i, idx) = (L_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                        P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                    }\n                }\n\n                Matrix<scalar_type, 2, 2> res_temp_S2;\n                MTK::vect<2, scalar_type> seg_S2;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin();\n                     it != x_.S2_state.end(); it++) {\n                    int idx = (*it).first;\n\n                    for (int i = 0; i < 2; i++) {\n                        seg_S2(i) = dx_(i + idx);\n                    }\n\n                    Eigen::Matrix<scalar_type, 2, 3> Nx;\n                    Eigen::Matrix<scalar_type, 3, 2> Mx;\n                    x_.S2_Nx_yy(Nx, idx);\n                    x_propagated.S2_Mx(Mx, seg_S2, idx);\n                    res_temp_S2 = Nx * Mx;\n\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<2, 1>(idx, i) = res_temp_S2 * (K_.template block<2, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<2, 1>(idx, i) = res_temp_S2 * (K_x.template block<2, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 2>(i, idx) = (L_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                        P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                    }\n                }\n                if (n > dof_Measurement) {\n                    P_ = L_ - K_ * h_x_ * P_;\n                } else {\n                    P_ = L_ - K_x * P_;\n                }\n                return;\n            }\n        }\n    }\n\n    // iterated error state EKF update for measurement as a dynamic manifold, whose dimension or type is changing.\n    // the measurement and the measurement model are received in a dynamic manner.\n    // calculate measurement (z), estimate measurement (h), partial differention matrices (h_x, h_v) and the noise\n    // covariance (R) at the same time, by only one function.\n    template <typename measurement_runtime, typename measurementModel_dyn_runtime_share>\n    void update_iterated_dyn_runtime_share(measurement_runtime z, measurementModel_dyn_runtime_share h) {\n        int t = 0;\n        dyn_runtime_share_datastruct<scalar_type> dyn_share;\n        dyn_share.valid = true;\n        dyn_share.converge = true;\n        state x_propagated = x_;\n        cov P_propagated = P_;\n        int dof_Measurement;\n        int dof_Measurement_noise;\n        for (int i = -1; i < maximum_iter; i++) {\n            dyn_share.valid = true;\n            measurement_runtime h_ = h(x_, dyn_share);\n            // measurement_runtime z = dyn_share.z;\n#ifdef USE_sparse\n            spMt h_x = dyn_share.h_x.sparseView();\n            spMt h_v = dyn_share.h_v.sparseView();\n            spMt R_ = dyn_share.R.sparseView();\n#else\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R = dyn_share.R;\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_x = dyn_share.h_x;\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_v = dyn_share.h_v;\n#endif\n            dof_Measurement = measurement_runtime::DOF;\n            dof_Measurement_noise = dyn_share.R.rows();\n            vectorized_state dx, dx_new;\n            x_.boxminus(dx, x_propagated);\n            dx_new = dx;\n            if (!(dyn_share.valid)) {\n                continue;\n            }\n\n            P_ = P_propagated;\n            Matrix<scalar_type, 3, 3> res_temp_SO3;\n            MTK::vect<3, scalar_type> seg_SO3;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 3; i++) {\n                    seg_SO3(i) = dx(idx + i);\n                }\n\n                res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                dx_new.template block<3, 1>(idx, 0) = res_temp_SO3 * dx_new.template block<3, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                }\n            }\n\n            Matrix<scalar_type, 2, 2> res_temp_S2;\n            MTK::vect<2, scalar_type> seg_S2;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 2; i++) {\n                    seg_S2(i) = dx(idx + i);\n                }\n\n                Eigen::Matrix<scalar_type, 2, 3> Nx;\n                Eigen::Matrix<scalar_type, 3, 2> Mx;\n                x_.S2_Nx_yy(Nx, idx);\n                x_propagated.S2_Mx(Mx, seg_S2, idx);\n                res_temp_S2 = Nx * Mx;\n                dx_new.template block<2, 1>(idx, 0) = res_temp_S2 * dx_new.template block<2, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                }\n            }\n\n            Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_;\n            if (n > dof_Measurement) {\n#ifdef USE_sparse\n                Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_temp = h_x * P_ * h_x.transpose();\n                spMt R_temp = h_v * R_ * h_v.transpose();\n                K_temp += R_temp;\n                K_ = P_ * h_x.transpose() * K_temp.inverse();\n#else\n                K_ = P_ * h_x.transpose() * (h_x * P_ * h_x.transpose() + h_v * R * h_v.transpose()).inverse();\n#endif\n            } else {\n#ifdef USE_sparse\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> b =\n                    Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic>::Identity(dof_Measurement_noise,\n                                                                                         dof_Measurement_noise);\n                Eigen::SparseQR<Eigen::SparseMatrix<scalar_type>, Eigen::COLAMDOrdering<int>> solver;\n                solver.compute(R_);\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in_temp = solver.solve(b);\n                spMt R_in = R_in_temp.sparseView();\n                spMt K_temp = h_x.transpose() * R_in * h_x;\n                cov_ P_temp = P_.inverse();\n                P_temp += K_temp;\n                K_ = P_temp.inverse() * h_x.transpose() * R_in;\n#else\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in = (h_v * R * h_v.transpose()).inverse();\n                K_ = (h_x.transpose() * R_in * h_x + P_.inverse()).inverse() * h_x.transpose() * R_in;\n#endif\n            }\n            cov K_x = K_ * h_x;\n            Eigen::Matrix<scalar_type, measurement_runtime::DOF, 1> innovation;\n            z.boxminus(innovation, h_);\n            Matrix<scalar_type, n, 1> dx_ = K_ * innovation + (K_x - Matrix<scalar_type, n, n>::Identity()) * dx_new;\n            state x_before = x_;\n            x_.boxplus(dx_);\n            dyn_share.converge = true;\n            for (int i = 0; i < n; i++) {\n                if (std::fabs(dx_[i]) > limit[i]) {\n                    dyn_share.converge = false;\n                    break;\n                }\n            }\n            if (dyn_share.converge) t++;\n            if (t > 1 || i == maximum_iter - 1) {\n                L_ = P_;\n                std::cout << \"iteration time:\" << t << \",\" << i << std::endl;\n\n                Matrix<scalar_type, 3, 3> res_temp_SO3;\n                MTK::vect<3, scalar_type> seg_SO3;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin();\n                     it != x_.SO3_state.end(); it++) {\n                    int idx = (*it).first;\n                    for (int i = 0; i < 3; i++) {\n                        seg_SO3(i) = dx_(i + idx);\n                    }\n                    res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                    for (int i = 0; i < int(n); i++) {\n                        L_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<3, 1>(idx, i) = res_temp_SO3 * (K_.template block<3, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<3, 1>(idx, i) = res_temp_SO3 * (K_x.template block<3, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 3>(i, idx) = (L_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                        P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                    }\n                }\n\n                Matrix<scalar_type, 2, 2> res_temp_S2;\n                MTK::vect<2, scalar_type> seg_S2;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin();\n                     it != x_.S2_state.end(); it++) {\n                    int idx = (*it).first;\n\n                    for (int i = 0; i < 2; i++) {\n                        seg_S2(i) = dx_(i + idx);\n                    }\n\n                    Eigen::Matrix<scalar_type, 2, 3> Nx;\n                    Eigen::Matrix<scalar_type, 3, 2> Mx;\n                    x_.S2_Nx_yy(Nx, idx);\n                    x_propagated.S2_Mx(Mx, seg_S2, idx);\n                    res_temp_S2 = Nx * Mx;\n\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                    }\n                    if (n > dof_Measurement) {\n                        for (int i = 0; i < dof_Measurement; i++) {\n                            K_.template block<2, 1>(idx, i) = res_temp_S2 * (K_.template block<2, 1>(idx, i));\n                        }\n                    } else {\n                        for (int i = 0; i < n; i++) {\n                            K_x.template block<2, 1>(idx, i) = res_temp_S2 * (K_x.template block<2, 1>(idx, i));\n                        }\n                    }\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 2>(i, idx) = (L_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                        P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                    }\n                }\n                if (n > dof_Measurement) {\n                    P_ = L_ - K_ * h_x * P_;\n                } else {\n                    P_ = L_ - K_x * P_;\n                }\n                return;\n            }\n        }\n    }\n\n    // iterated error state EKF update modified for one specific system.\n    void update_iterated_dyn_share_modified(double R, double &solve_time) {\n        dyn_share_datastruct<scalar_type> dyn_share;\n        dyn_share.valid = true;\n        dyn_share.converge = true;\n        int t = 0;\n        state x_propagated = x_;\n        cov P_propagated = P_;\n        int dof_Measurement;\n\n        Matrix<scalar_type, n, 1> K_h;\n        Matrix<scalar_type, n, n> K_x;\n\n        vectorized_state dx_new = vectorized_state::Zero();\n        for (int i = -1; i < maximum_iter; i++) {\n            dyn_share.valid = true;\n            h_dyn_share(x_, dyn_share);\n\n            if (!dyn_share.valid) {\n                continue;\n            }\n\n// Matrix<scalar_type, Eigen::Dynamic, 1> h = h_dyn_share(x_, dyn_share);\n#ifdef USE_sparse\n            spMt h_x_ = dyn_share.h_x.sparseView();\n#else\n            Eigen::Matrix<scalar_type, Eigen::Dynamic, 12> h_x_ = dyn_share.h_x;\n#endif\n            // double solve_start = omp_get_wtime();\n            dof_Measurement = h_x_.rows();\n            vectorized_state dx;\n            x_.boxminus(dx, x_propagated);\n            dx_new = dx;\n\n            P_ = P_propagated;\n\n            Matrix<scalar_type, 3, 3> res_temp_SO3;\n            MTK::vect<3, scalar_type> seg_SO3;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin(); it != x_.SO3_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 3; i++) {\n                    seg_SO3(i) = dx(idx + i);\n                }\n\n                res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                dx_new.template block<3, 1>(idx, 0) = res_temp_SO3 * dx_new.template block<3, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                }\n            }\n\n            Matrix<scalar_type, 2, 2> res_temp_S2;\n            MTK::vect<2, scalar_type> seg_S2;\n            for (std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin(); it != x_.S2_state.end(); it++) {\n                int idx = (*it).first;\n                int dim = (*it).second;\n                for (int i = 0; i < 2; i++) {\n                    seg_S2(i) = dx(idx + i);\n                }\n\n                Eigen::Matrix<scalar_type, 2, 3> Nx;\n                Eigen::Matrix<scalar_type, 3, 2> Mx;\n                x_.S2_Nx_yy(Nx, idx);\n                x_propagated.S2_Mx(Mx, seg_S2, idx);\n                res_temp_S2 = Nx * Mx;\n                dx_new.template block<2, 1>(idx, 0) = res_temp_S2 * dx_new.template block<2, 1>(idx, 0);\n                for (int i = 0; i < n; i++) {\n                    P_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                }\n                for (int i = 0; i < n; i++) {\n                    P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                }\n            }\n            // Matrix<scalar_type, n, Eigen::Dynamic> K_;\n            // Matrix<scalar_type, n, 1> K_h;\n            // Matrix<scalar_type, n, n> K_x;\n\n            /*\n            if(n > dof_Measurement)\n            {\n                    K_= P_ * h_x_.transpose() * (h_x_ * P_ * h_x_.transpose()/R + Eigen::Matrix<double, Dynamic,\n            Dynamic>::Identity(dof_Measurement, dof_Measurement)).inverse()/R;\n            }\n            else\n            {\n                    K_= (h_x_.transpose() * h_x_ + (P_/R).inverse()).inverse()*h_x_.transpose();\n            }\n            */\n\n            if (n > dof_Measurement) {\n                //#ifdef USE_sparse\n                // Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_temp = h_x * P_ * h_x.transpose();\n                // spMt R_temp = h_v * R_ * h_v.transpose();\n                // K_temp += R_temp;\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_x_cur =\n                    Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic>::Zero(dof_Measurement, n);\n                h_x_cur.topLeftCorner(dof_Measurement, 12) = h_x_;\n                /*\n                h_x_cur.col(0) = h_x_.col(0);\n                h_x_cur.col(1) = h_x_.col(1);\n                h_x_cur.col(2) = h_x_.col(2);\n                h_x_cur.col(3) = h_x_.col(3);\n                h_x_cur.col(4) = h_x_.col(4);\n                h_x_cur.col(5) = h_x_.col(5);\n                h_x_cur.col(6) = h_x_.col(6);\n                h_x_cur.col(7) = h_x_.col(7);\n                h_x_cur.col(8) = h_x_.col(8);\n                h_x_cur.col(9) = h_x_.col(9);\n                h_x_cur.col(10) = h_x_.col(10);\n                h_x_cur.col(11) = h_x_.col(11);\n                */\n\n                Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> K_ =\n                    P_ * h_x_cur.transpose() *\n                    (h_x_cur * P_ * h_x_cur.transpose() / R +\n                     Eigen::Matrix<double, Dynamic, Dynamic>::Identity(dof_Measurement, dof_Measurement))\n                        .inverse() /\n                    R;\n                K_h = K_ * dyn_share.h;\n                K_x = K_ * h_x_cur;\n                //#else\n                //\tK_= P_ * h_x.transpose() * (h_x * P_ * h_x.transpose() + h_v * R * h_v.transpose()).inverse();\n                //#endif\n            } else {\n#ifdef USE_sparse\n                // Eigen::Matrix<scalar_type, n, n> b = Eigen::Matrix<scalar_type, n, n>::Identity();\n                // Eigen::SparseQR<Eigen::SparseMatrix<scalar_type>, Eigen::COLAMDOrdering<int>> solver;\n                spMt A = h_x_.transpose() * h_x_;\n                cov_ P_temp = (P_ / R).inverse();\n                P_temp.template block<12, 12>(0, 0) += A;\n                P_temp = P_temp.inverse();\n                /*\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_x_cur = Eigen::Matrix<scalar_type,\n                Eigen::Dynamic, Eigen::Dynamic>::Zero(dof_Measurement, n); h_x_cur.col(0) = h_x_.col(0); h_x_cur.col(1)\n                = h_x_.col(1); h_x_cur.col(2) = h_x_.col(2); h_x_cur.col(3) = h_x_.col(3); h_x_cur.col(4) = h_x_.col(4);\n                h_x_cur.col(5) = h_x_.col(5);\n                h_x_cur.col(6) = h_x_.col(6);\n                h_x_cur.col(7) = h_x_.col(7);\n                h_x_cur.col(8) = h_x_.col(8);\n                h_x_cur.col(9) = h_x_.col(9);\n                h_x_cur.col(10) = h_x_.col(10);\n                h_x_cur.col(11) = h_x_.col(11);\n                */\n                K_ = P_temp.template block<n, 12>(0, 0) * h_x_.transpose();\n                K_x = cov_::Zero();\n                K_x.template block<n, 12>(0, 0) = P_inv.template block<n, 12>(0, 0) * HTH;\n                /*\n                solver.compute(R_);\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> R_in_temp = solver.solve(b);\n                spMt R_in =R_in_temp.sparseView();\n                spMt K_temp = h_x.transpose() * R_in * h_x;\n                cov_ P_temp = P_.inverse();\n                P_temp += K_temp;\n                K_ = P_temp.inverse() * h_x.transpose() * R_in;\n                */\n#else\n                cov P_temp = (P_ / R).inverse();\n                // Eigen::Matrix<scalar_type, 12, Eigen::Dynamic> h_T = h_x_.transpose();\n                Eigen::Matrix<scalar_type, 12, 12> HTH = h_x_.transpose() * h_x_;\n                P_temp.template block<12, 12>(0, 0) += HTH;\n                /*\n                Eigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_x_cur = Eigen::Matrix<scalar_type,\n                Eigen::Dynamic, Eigen::Dynamic>::Zero(dof_Measurement, n);\n                //std::cout << \"line 1767\" << std::endl;\n                h_x_cur.col(0) = h_x_.col(0);\n                h_x_cur.col(1) = h_x_.col(1);\n                h_x_cur.col(2) = h_x_.col(2);\n                h_x_cur.col(3) = h_x_.col(3);\n                h_x_cur.col(4) = h_x_.col(4);\n                h_x_cur.col(5) = h_x_.col(5);\n                h_x_cur.col(6) = h_x_.col(6);\n                h_x_cur.col(7) = h_x_.col(7);\n                h_x_cur.col(8) = h_x_.col(8);\n                h_x_cur.col(9) = h_x_.col(9);\n                h_x_cur.col(10) = h_x_.col(10);\n                h_x_cur.col(11) = h_x_.col(11);\n                */\n                cov P_inv = P_temp.inverse();\n                // std::cout << \"line 1781\" << std::endl;\n                K_h = P_inv.template block<n, 12>(0, 0) * h_x_.transpose() * dyn_share.h;\n                // std::cout << \"line 1780\" << std::endl;\n                // cov_ HTH_cur = cov_::Zero();\n                // HTH_cur. template block<12, 12>(0, 0) = HTH;\n                K_x.setZero();  // = cov_::Zero();\n                K_x.template block<n, 12>(0, 0) = P_inv.template block<n, 12>(0, 0) * HTH;\n                // K_= (h_x_.transpose() * h_x_ + (P_/R).inverse()).inverse()*h_x_.transpose();\n#endif\n            }\n\n            // K_x = K_ * h_x_;\n            Matrix<scalar_type, n, 1> dx_ = K_h + (K_x - Matrix<scalar_type, n, n>::Identity()) * dx_new;\n            state x_before = x_;\n            x_.boxplus(dx_);\n            dyn_share.converge = true;\n            for (int i = 0; i < n; i++) {\n                if (std::fabs(dx_[i]) > limit[i]) {\n                    dyn_share.converge = false;\n                    break;\n                }\n            }\n            if (dyn_share.converge) t++;\n\n            if (!t && i == maximum_iter - 2) {\n                dyn_share.converge = true;\n            }\n\n            if (t > 1 || i == maximum_iter - 1) {\n                L_ = P_;\n                // std::cout << \"iteration time\" << t << \",\" << i << std::endl;\n                Matrix<scalar_type, 3, 3> res_temp_SO3;\n                MTK::vect<3, scalar_type> seg_SO3;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.SO3_state.begin();\n                     it != x_.SO3_state.end(); it++) {\n                    int idx = (*it).first;\n                    for (int i = 0; i < 3; i++) {\n                        seg_SO3(i) = dx_(i + idx);\n                    }\n                    res_temp_SO3 = MTK::A_matrix(seg_SO3).transpose();\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<3, 1>(idx, i) = res_temp_SO3 * (P_.template block<3, 1>(idx, i));\n                    }\n                    // if(n > dof_Measurement)\n                    // {\n                    // \tfor(int i = 0; i < dof_Measurement; i++){\n                    // \t\tK_.template block<3, 1>(idx, i) = res_temp_SO3 * (K_. template block<3, 1>(idx, i));\n                    // \t}\n                    // }\n                    // else\n                    // {\n                    for (int i = 0; i < 12; i++) {\n                        K_x.template block<3, 1>(idx, i) = res_temp_SO3 * (K_x.template block<3, 1>(idx, i));\n                    }\n                    //}\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 3>(i, idx) = (L_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                        P_.template block<1, 3>(i, idx) = (P_.template block<1, 3>(i, idx)) * res_temp_SO3.transpose();\n                    }\n                }\n\n                Matrix<scalar_type, 2, 2> res_temp_S2;\n                MTK::vect<2, scalar_type> seg_S2;\n                for (typename std::vector<std::pair<int, int>>::iterator it = x_.S2_state.begin();\n                     it != x_.S2_state.end(); it++) {\n                    int idx = (*it).first;\n\n                    for (int i = 0; i < 2; i++) {\n                        seg_S2(i) = dx_(i + idx);\n                    }\n\n                    Eigen::Matrix<scalar_type, 2, 3> Nx;\n                    Eigen::Matrix<scalar_type, 3, 2> Mx;\n                    x_.S2_Nx_yy(Nx, idx);\n                    x_propagated.S2_Mx(Mx, seg_S2, idx);\n                    res_temp_S2 = Nx * Mx;\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<2, 1>(idx, i) = res_temp_S2 * (P_.template block<2, 1>(idx, i));\n                    }\n                    // if(n > dof_Measurement)\n                    // {\n                    // \tfor(int i = 0; i < dof_Measurement; i++){\n                    // \t\tK_. template block<2, 1>(idx, i) = res_temp_S2 * (K_. template block<2, 1>(idx, i));\n                    // \t}\n                    // }\n                    // else\n                    // {\n                    for (int i = 0; i < 12; i++) {\n                        K_x.template block<2, 1>(idx, i) = res_temp_S2 * (K_x.template block<2, 1>(idx, i));\n                    }\n                    //}\n                    for (int i = 0; i < n; i++) {\n                        L_.template block<1, 2>(i, idx) = (L_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                        P_.template block<1, 2>(i, idx) = (P_.template block<1, 2>(i, idx)) * res_temp_S2.transpose();\n                    }\n                }\n\n                // if(n > dof_Measurement)\n                // {\n                // \tEigen::Matrix<scalar_type, Eigen::Dynamic, Eigen::Dynamic> h_x_cur = Eigen::Matrix<scalar_type,\n                // Eigen::Dynamic, Eigen::Dynamic>::Zero(dof_Measurement, n); h_x_cur.topLeftCorner(dof_Measurement, 12)\n                // = h_x_;\n                // \t/*\n                // \th_x_cur.col(0) = h_x_.col(0);\n                // \th_x_cur.col(1) = h_x_.col(1);\n                // \th_x_cur.col(2) = h_x_.col(2);\n                // \th_x_cur.col(3) = h_x_.col(3);\n                // \th_x_cur.col(4) = h_x_.col(4);\n                // \th_x_cur.col(5) = h_x_.col(5);\n                // \th_x_cur.col(6) = h_x_.col(6);\n                // \th_x_cur.col(7) = h_x_.col(7);\n                // \th_x_cur.col(8) = h_x_.col(8);\n                // \th_x_cur.col(9) = h_x_.col(9);\n                // \th_x_cur.col(10) = h_x_.col(10);\n                // \th_x_cur.col(11) = h_x_.col(11);\n                // \t*/\n                // \tP_ = L_ - K_*h_x_cur * P_;\n                // }\n                // else\n                //{\n                P_ = L_ - K_x.template block<n, 12>(0, 0) * P_.template block<12, n>(0, 0);\n                //}\n                // solve_time += omp_get_wtime() - solve_start;\n                return;\n            }\n            // solve_time += omp_get_wtime() - solve_start;\n        }\n    }\n\n    void change_x(state &input_state) {\n        x_ = input_state;\n        if ((!x_.vect_state.size()) && (!x_.SO3_state.size()) && (!x_.S2_state.size())) {\n            x_.build_S2_state();\n            x_.build_SO3_state();\n            x_.build_vect_state();\n        }\n    }\n\n    void change_P(cov &input_cov) { P_ = input_cov; }\n\n    const state &get_x() const { return x_; }\n    const cov &get_P() const { return P_; }\n\n   private:\n    state x_;\n    measurement m_;\n    cov P_;\n    spMt l_;\n    spMt f_x_1;\n    spMt f_x_2;\n    cov F_x1 = cov::Identity();\n    cov F_x2 = cov::Identity();\n    cov L_ = cov::Identity();\n\n    processModel *f;\n    processMatrix1 *f_x;\n    processMatrix2 *f_w;\n\n    measurementModel *h;\n    measurementMatrix1 *h_x;\n    measurementMatrix2 *h_v;\n\n    measurementModel_dyn *h_dyn;\n    measurementMatrix1_dyn *h_x_dyn;\n    measurementMatrix2_dyn *h_v_dyn;\n\n    measurementModel_share *h_share;\n    measurementModel_dyn_share h_dyn_share;\n\n    int maximum_iter = 0;\n    scalar_type limit[n];\n\n    template <typename T>\n    T check_safe_update(T _temp_vec) {\n        T temp_vec = _temp_vec;\n        if (std::isnan(temp_vec(0, 0))) {\n            temp_vec.setZero();\n            return temp_vec;\n        }\n        double angular_dis = temp_vec.block(0, 0, 3, 1).norm() * 57.3;\n        double pos_dis = temp_vec.block(3, 0, 3, 1).norm();\n        if (angular_dis >= 20 || pos_dis > 1) {\n            printf(\"Angular dis = %.2f, pos dis = %.2f\\r\\n\", angular_dis, pos_dis);\n            temp_vec.setZero();\n        }\n        return temp_vec;\n    }\n\n   public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n}  // namespace esekfom\n\n#endif  //  ESEKFOM_EKF_HPP\n", "meta": {"hexsha": "26f4ebd12a0b542a4506c087439c3ab1376ef75a", "size": 85961, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/IKFoM_toolkit/esekfom/esekfom.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/esekfom/esekfom.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/esekfom/esekfom.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": 45.1950578339, "max_line_length": 120, "alphanum_fraction": 0.4811716941, "num_tokens": 23297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047866316946014, "lm_q2_score": 0.026759285610907495, "lm_q1q2_score": 0.012857265777698603}}
{"text": "/*!\n  \\file gpp_python_knowledge_gradient_mcmc.cpp\n  \\rst\n  This file has the logic to invoke C++ functions pertaining to knowledge gradient from Python.\n  The data flow follows the basic 4 step from gpp_python_common.hpp.\n\n  .. NoteL: several internal functions of this source file are only called from ``Export*()`` functions,\n  so their description, inputs, outputs, etc. comments have been moved. These comments exist in\n  ``Export*()`` as Python docstrings, so we saw no need to repeat ourselves.\n\\endrst*/\n// This include violates the Google Style Guide by placing an \"other\" system header ahead of C and C++ system headers.  However,\n// it needs to be at the top, otherwise compilation fails on some systems with some versions of python: OS X, python 2.7.3.\n// Putting this include first prevents pyport from doing something illegal in C++; reference: http://bugs.python.org/issue10910\n#include \"Python.h\"  // NOLINT(build/include)\n\n#include \"gpp_python_knowledge_gradient_mcmc.hpp\"\n\n// NOLINT-ing the C, C++ header includes as well; otherwise cpplint gets confused\n#include <string>  // NOLINT(build/include_order)\n#include <vector>  // NOLINT(build/include_order)\n\n#include <boost/python/bases.hpp>  // NOLINT(build/include_order)\n#include <boost/python/class.hpp>  // NOLINT(build/include_order)\n#include <boost/python/def.hpp>  // NOLINT(build/include_order)\n#include <boost/python/dict.hpp>  // NOLINT(build/include_order)\n#include <boost/python/extract.hpp>  // NOLINT(build/include_order)\n#include <boost/python/list.hpp>  // NOLINT(build/include_order)\n#include <boost/python/object.hpp>  // NOLINT(build/include_order)\n#include <boost/python/make_constructor.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_covariance.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_knowledge_gradient_mcmc_optimization.hpp\"\n#include \"gpp_geometry.hpp\"\n#include \"gpp_math.hpp\"\n#include \"gpp_optimization.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_python_common.hpp\"\n\nnamespace optimal_learning {\n\nnamespace {\n/*!\\rst\n  Surrogate \"constructor\" for GaussianProcess intended only for use by boost::python.  This aliases the normal C++ constructor,\n  replacing ``double const * restrict`` arguments with ``const boost::python::list&`` arguments.\n\\endrst*/\nGaussianProcessMCMC * make_gaussian_process_mcmc(const boost::python::list& hyperparameters_list,\n                                                 const boost::python::list& noise_variance_list,\n                                                 const boost::python::list& points_sampled,\n                                                 const boost::python::list& points_sampled_value,\n                                                 const boost::python::list& derivatives,\n                                                 int num_mcmc, int num_derivatives, int dim, int num_sampled) {\n  std::vector<double> hyperparameters_list_vector(num_mcmc*(dim+1));\n  CopyPylistToVector(hyperparameters_list, num_mcmc*(dim+1), hyperparameters_list_vector);\n\n  std::vector<double> noise_variance_list_vector(num_mcmc*(1+num_derivatives));\n  CopyPylistToVector(noise_variance_list, num_mcmc*(1+num_derivatives), noise_variance_list_vector);\n\n  std::vector<double> points_sampled_vector(dim*num_sampled);\n  CopyPylistToVector(points_sampled, dim*num_sampled, points_sampled_vector);\n\n  std::vector<double> points_sampled_value_vector(num_sampled*(1+num_derivatives));\n  CopyPylistToVector(points_sampled_value, num_sampled*(1+num_derivatives), points_sampled_value_vector);\n\n  std::vector<int> derivatives_vector(num_derivatives);\n  CopyPylistToIntVector(derivatives, num_derivatives, derivatives_vector);\n\n  GaussianProcessMCMC * new_gp_mcmc = new GaussianProcessMCMC(hyperparameters_list_vector.data(), noise_variance_list_vector.data(),\n                                                              num_mcmc, points_sampled_vector.data(), points_sampled_value_vector.data(),\n                                                              derivatives_vector.data(), num_derivatives,\n                                                              dim, num_sampled);\n  for (int i=0;i<num_mcmc;i++){\n      new_gp_mcmc->gaussian_process_lst[i].SetRandomizedSeed(0);\n  }\n  return new_gp_mcmc;\n}\n\ndouble ComputeKnowledgeGradientMCMCWrapper(GaussianProcessMCMC& gaussian_process_mcmc,\n                                           const int num_fidelity,\n                                           const boost::python::object& optimizer_parameters,\n                                           const boost::python::list& domain_bounds,\n                                           const boost::python::list& discrete_pts,\n                                           const boost::python::list& points_to_sample,\n                                           const boost::python::list& points_being_sampled,\n                                           int num_pts, int num_to_sample, int num_being_sampled,\n                                           int max_int_steps, const boost::python::list& best_so_far,\n                                           RandomnessSourceContainer& randomness_source) {\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container_discrete(discrete_pts, gradients, gaussian_process_mcmc.dim()-num_fidelity,\n                                                         num_pts*gaussian_process_mcmc.num_mcmc(), num_derivatives_input);\n  PythonInterfaceInputContainer input_container(points_to_sample, points_being_sampled, gradients, gaussian_process_mcmc.dim(),\n                                                num_to_sample, num_being_sampled, num_derivatives_input);\n\n  bool configure_for_gradients = false;\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim-num_fidelity);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim-num_fidelity, domain_bounds_C);\n\n  std::vector<double> best_so_far_list(gaussian_process_mcmc.num_mcmc());\n  CopyPylistToVector(best_so_far, gaussian_process_mcmc.num_mcmc(), best_so_far_list);\n\n  TensorProductDomain domain(domain_bounds_C.data(), input_container.dim-num_fidelity);\n  const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n\n  std::vector<typename KnowledgeGradientState<TensorProductDomain>::EvaluatorType> evaluator_vector;\n  KnowledgeGradientMCMCEvaluator<TensorProductDomain> kg_evaluator(gaussian_process_mcmc, num_fidelity, input_container_discrete.points_to_sample.data(),\n                                                                   num_pts, max_int_steps, domain, gradient_descent_parameters,\n                                                                   best_so_far_list.data(), &evaluator_vector);\n\n  std::vector<typename KnowledgeGradientEvaluator<TensorProductDomain>::StateType> state_vector;\n  KnowledgeGradientMCMCEvaluator<TensorProductDomain>::StateType kg_state(kg_evaluator, input_container.points_to_sample.data(),\n                                                                          input_container.points_being_sampled.data(),\n                                                                          input_container.num_to_sample,\n                                                                          input_container.num_being_sampled,\n                                                                          num_pts, gaussian_process_mcmc.derivatives().data(),\n                                                                          gaussian_process_mcmc.num_derivatives(), configure_for_gradients,\n                                                                          randomness_source.normal_rng_vec.data(), &state_vector);\n  return kg_evaluator.ComputeKnowledgeGradient(&kg_state);\n}\n\nboost::python::list ComputeGradKnowledgeGradientMCMCWrapper(GaussianProcessMCMC& gaussian_process_mcmc,\n                                                            const int num_fidelity,\n                                                            const boost::python::object& optimizer_parameters,\n                                                            const boost::python::list& domain_bounds,\n                                                            const boost::python::list& discrete_pts,\n                                                            const boost::python::list& points_to_sample,\n                                                            const boost::python::list& points_being_sampled,\n                                                            int num_pts, int num_to_sample, int num_being_sampled,\n                                                            int max_int_steps, const boost::python::list& best_so_far,\n                                                            RandomnessSourceContainer& randomness_source) {\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container_discrete(discrete_pts, gradients, gaussian_process_mcmc.dim()-num_fidelity,\n                                                         num_pts*gaussian_process_mcmc.num_mcmc(), num_derivatives_input);\n  PythonInterfaceInputContainer input_container(points_to_sample, points_being_sampled, gradients, gaussian_process_mcmc.dim(),\n                                                num_to_sample, num_being_sampled, num_derivatives_input);\n\n  std::vector<double> grad_KG(num_to_sample*input_container.dim);\n  bool configure_for_gradients = true;\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim-num_fidelity);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim-num_fidelity, domain_bounds_C);\n\n  std::vector<double> best_so_far_list(gaussian_process_mcmc.num_mcmc());\n  CopyPylistToVector(best_so_far, gaussian_process_mcmc.num_mcmc(), best_so_far_list);\n\n  TensorProductDomain domain(domain_bounds_C.data(), input_container.dim-num_fidelity);\n  const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n\n  std::vector<typename KnowledgeGradientState<TensorProductDomain>::EvaluatorType> evaluator_vector;\n  KnowledgeGradientMCMCEvaluator<TensorProductDomain> kg_evaluator(gaussian_process_mcmc, num_fidelity, input_container_discrete.points_to_sample.data(),\n                                                                   num_pts, max_int_steps, domain, gradient_descent_parameters,\n                                                                   best_so_far_list.data(), &evaluator_vector);\n\n  std::vector<typename KnowledgeGradientEvaluator<TensorProductDomain>::StateType> state_vector;\n  KnowledgeGradientMCMCEvaluator<TensorProductDomain>::StateType kg_state(kg_evaluator, input_container.points_to_sample.data(),\n                                                                          input_container.points_being_sampled.data(),\n                                                                          input_container.num_to_sample,\n                                                                          input_container.num_being_sampled,\n                                                                          num_pts, gaussian_process_mcmc.derivatives().data(),\n                                                                          gaussian_process_mcmc.num_derivatives(), configure_for_gradients,\n                                                                          randomness_source.normal_rng_vec.data(), &state_vector);\n  kg_evaluator.ComputeGradKnowledgeGradient(&kg_state, grad_KG.data());\n\n  return VectorToPylist(grad_KG);\n}\n\n/*!\\rst\n  Utility that dispatches KG optimization based on optimizer type and num_to_sample.\n  This is just used to reduce copy-pasted code.\n\n  \\param\n    :optimizer_parameters: python/cpp_wrappers/optimization._CppOptimizerParameters\n      Python object containing the DomainTypes domain_type and OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton).\n      See comments on the python interface for multistart_expected_improvement_optimization_wrapper\n    :gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities) that describes the\n      underlying GP\n    :input_container: PythonInterfaceInputContainer object containing data about points_being_sampled\n    :domain: object specifying the domain to optimize over (see gpp_domain.hpp)\n    :optimizer_type: type of optimization to use (e.g., null, gradient descent)\n    :num_to_sample: how many simultaneous experiments you would like to run (i.e., the q in q,p-KG)\n    :best_so_far: value of the best sample so far (must be min(points_sampled_value))\n    :max_int_steps: maximum number of MC iterations\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :randomness_source: object containing randomness sources (sufficient for multithreading) used in KG computation\n    :status: pydict object; cannot be None\n  \\output\n    :randomness_source: PRNG internal states modified\n    :status: modified on exit to describe whether convergence occurred\n    :best_points_to_sample[num_to_sample][dim]: next set of points to evaluate\n\\endrst*/\n\ntemplate <typename DomainType>\nvoid DispatchKnowledgeGradientMCMCOptimization(const boost::python::object& optimizer_parameters,\n                                               const boost::python::object& optimizer_parameters_inner,\n                                               GaussianProcessMCMC& gaussian_process_mcmc, const int num_fidelity,\n                                               const PythonInterfaceInputContainer& input_container_discrete,\n                                               const PythonInterfaceInputContainer& input_container,\n                                               const DomainType& domain, const DomainType& inner_domain, OptimizerTypes optimizer_type,\n                                               int num_pts, int num_to_sample, std::vector<double> best_so_far_list,\n                                               int max_int_steps, int max_num_threads,\n                                               RandomnessSourceContainer& randomness_source,\n                                               boost::python::dict& status,\n                                               double * restrict best_points_to_sample) {\n  bool found_flag = false;\n\n  switch (optimizer_type) {\n    case OptimizerTypes::kNull: {\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_static);\n      // optimizer_parameters must contain an int num_random_samples field, extract it\n      const GradientDescentParameters& gradient_descent_parameters_inner = boost::python::extract<GradientDescentParameters&>(optimizer_parameters_inner.attr(\"optimizer_parameters\"));\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      ComputeKGMCMCOptimalPointsToSampleViaLatinHypercubeSearch(gaussian_process_mcmc, num_fidelity, gradient_descent_parameters_inner, domain, inner_domain, thread_schedule,\n                                                                input_container.points_being_sampled.data(),\n                                                                input_container_discrete.points_to_sample.data(),\n                                                                num_random_samples, num_to_sample,\n                                                                input_container.num_being_sampled,\n                                                                num_pts, best_so_far_list.data(), max_int_steps,\n                                                                &found_flag, &randomness_source.uniform_generator,\n                                                                randomness_source.normal_rng_vec.data(),\n                                                                best_points_to_sample);\n      status[std::string(\"lhc_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kNull optimizer_type\n    case OptimizerTypes::kGradientDescent: {\n      // optimizer_parameters must contain a optimizer_parameters field\n      // of type GradientDescentParameters. extract it\n      const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n      const GradientDescentParameters& gradient_descent_parameters_inner = boost::python::extract<GradientDescentParameters&>(optimizer_parameters_inner.attr(\"optimizer_parameters\"));\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_dynamic);\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      bool random_search_only = false;\n      ComputeKGMCMCOptimalPointsToSample(gaussian_process_mcmc, num_fidelity, gradient_descent_parameters, gradient_descent_parameters_inner, domain, inner_domain, thread_schedule,\n                                         input_container.points_being_sampled.data(), input_container_discrete.points_to_sample.data(),\n                                         num_to_sample, input_container.num_being_sampled, num_pts,\n                                         best_so_far_list.data(), max_int_steps, random_search_only, num_random_samples, &found_flag,\n                                         &randomness_source.uniform_generator, randomness_source.normal_rng_vec.data(), best_points_to_sample);\n\n      status[std::string(\"gradient_descent_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kGradientDescent optimizer_type\n    default: {\n      std::fill(best_points_to_sample, best_points_to_sample + input_container.dim*num_to_sample, 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid optimizer choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over optimizer_type\n}\n\nboost::python::list MultistartKnowledgeGradientMCMCOptimizationWrapper(const boost::python::object& optimizer_parameters,\n                                                                       const boost::python::object& optimizer_parameters_inner,\n                                                                       GaussianProcessMCMC& gaussian_process_mcmc, const int num_fidelity,\n                                                                       const boost::python::list& domain_bounds,\n                                                                       const boost::python::list& discrete_pts,\n                                                                       const boost::python::list& points_being_sampled,\n                                                                       int num_pts, int num_to_sample, int num_being_sampled,\n                                                                       const boost::python::list& best_so_far, int max_int_steps, int max_num_threads,\n                                                                       RandomnessSourceContainer& randomness_source,\n                                                                       boost::python::dict& status) {\n  // TODO(GH-131): make domain objects constructible from python; and pass them in through\n  // the optimizer_parameters python object\n\n  // abort if we do not have enough sources of randomness to run with max_num_threads\n  if (unlikely(max_num_threads > static_cast<int>(randomness_source.normal_rng_vec.size()))) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"Fewer randomness_sources than max_num_threads.\", randomness_source.normal_rng_vec.size(), max_num_threads);\n  }\n\n  int num_to_sample_input = 0;  // No points to sample; we are generating these via KG optimization\n  const boost::python::list points_to_sample_dummy;\n\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container_discrete(discrete_pts, gradients, gaussian_process_mcmc.dim()-num_fidelity,\n                                                         num_pts*gaussian_process_mcmc.num_mcmc(), num_derivatives_input);\n  PythonInterfaceInputContainer input_container(points_to_sample_dummy, points_being_sampled, gradients, gaussian_process_mcmc.dim(),\n                                                num_to_sample_input, num_being_sampled, num_derivatives_input);\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim, domain_bounds_C);\n\n  std::vector<double> best_so_far_list(gaussian_process_mcmc.num_mcmc());\n  CopyPylistToVector(best_so_far, gaussian_process_mcmc.num_mcmc(), best_so_far_list);\n\n  std::vector<double> best_points_to_sample_C(input_container.dim*num_to_sample);\n\n  DomainTypes domain_type = boost::python::extract<DomainTypes>(optimizer_parameters.attr(\"domain_type\"));\n  OptimizerTypes optimizer_type = boost::python::extract<OptimizerTypes>(optimizer_parameters.attr(\"optimizer_type\"));\n  switch (domain_type) {\n    case DomainTypes::kTensorProduct: {\n      TensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n      TensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim-num_fidelity);\n\n      DispatchKnowledgeGradientMCMCOptimization(optimizer_parameters, optimizer_parameters_inner, gaussian_process_mcmc, num_fidelity, input_container_discrete,\n                                                input_container, domain, inner_domain, optimizer_type, num_pts, num_to_sample, best_so_far_list,\n                                                max_int_steps, max_num_threads, randomness_source, status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kTensorProduct\n    case DomainTypes::kSimplex: {\n      SimplexIntersectTensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n      SimplexIntersectTensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim-num_fidelity);\n\n      DispatchKnowledgeGradientMCMCOptimization(optimizer_parameters, optimizer_parameters_inner, gaussian_process_mcmc, num_fidelity, input_container_discrete,\n                                                input_container, domain, inner_domain, optimizer_type, num_pts, num_to_sample, best_so_far_list,\n                                                max_int_steps, max_num_threads, randomness_source, status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kSimplex\n    default: {\n      std::fill(best_points_to_sample_C.begin(), best_points_to_sample_C.end(), 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid domain choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over domain_type\n\n  return VectorToPylist(best_points_to_sample_C);\n}\n\nboost::python::list EvaluateKGMCMCAtPointListWrapper(GaussianProcessMCMC& gaussian_process_mcmc,\n                                                     const int num_fidelity,\n                                                     const boost::python::object& optimizer_parameters,\n                                                     const boost::python::list& domain_bounds,\n                                                     const boost::python::list& initial_guesses,\n                                                     const boost::python::list& discrete_being_sampled,\n                                                     int num_multistarts, int num_pts, int num_to_sample,\n                                                     int num_being_sampled, const boost::python::list& best_so_far,\n                                                     int max_int_steps, int max_num_threads,\n                                                     RandomnessSourceContainer& randomness_source,\n                                                     boost::python::dict& status) {\n  // abort if we do not have enough sources of randomness to run with max_num_threads\n  if (unlikely(max_num_threads > static_cast<int>(randomness_source.normal_rng_vec.size()))) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"Fewer randomness_sources than max_num_threads.\", randomness_source.normal_rng_vec.size(), max_num_threads);\n  }\n\n  int num_to_sample_input = 0;  // No points to sample; we are generating these via KG optimization\n  const boost::python::list points_to_sample_dummy;\n\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container(discrete_being_sampled, gradients, gaussian_process_mcmc.dim(),\n                                                num_pts*gaussian_process_mcmc.num_mcmc()+num_being_sampled, num_derivatives_input);\n  int num_discrete_pts_and_pts_being_sampled = num_pts*gaussian_process_mcmc.num_mcmc()*(gaussian_process_mcmc.dim()-num_fidelity)\n                                               + num_being_sampled*gaussian_process_mcmc.dim();\n  std::vector<double> discrete_pts_and_pts_being_sampled(num_discrete_pts_and_pts_being_sampled);\n  CopyPylistToVector(discrete_being_sampled, num_discrete_pts_and_pts_being_sampled, discrete_pts_and_pts_being_sampled);\n\n  std::vector<double> result_point_C(input_container.dim);  // not used\n  std::vector<double> result_function_values_C(num_multistarts);\n  std::vector<double> initial_guesses_C(input_container.dim * num_multistarts);\n\n  CopyPylistToVector(initial_guesses, input_container.dim * num_multistarts, initial_guesses_C);\n\n  ThreadSchedule thread_schedule(max_num_threads, omp_sched_static);\n  bool found_flag = false;\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim, domain_bounds_C);\n\n  std::vector<double> best_so_far_list(gaussian_process_mcmc.num_mcmc());\n  CopyPylistToVector(best_so_far, gaussian_process_mcmc.num_mcmc(), best_so_far_list);\n\n  TensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n  TensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim- num_fidelity);\n  const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n\n  EvaluateKGMCMCAtPointList(gaussian_process_mcmc, num_fidelity, gradient_descent_parameters, domain, inner_domain, thread_schedule, initial_guesses_C.data(),\n                            discrete_pts_and_pts_being_sampled.data() + num_pts*gaussian_process_mcmc.num_mcmc()*(gaussian_process_mcmc.dim()-num_fidelity),\n                            discrete_pts_and_pts_being_sampled.data(), num_multistarts, num_to_sample, input_container.num_being_sampled,\n                            num_pts, best_so_far_list.data(), max_int_steps, &found_flag, randomness_source.normal_rng_vec.data(),\n                            result_function_values_C.data(), result_point_C.data());\n\n  status[\"evaluate_KG_at_point_list\"] = found_flag;\n\n  return VectorToPylist(result_function_values_C);\n}\n}  // end unnamed namespace\n\nvoid ExportKnowldegeGradientMCMCFunctions() {\n  boost::python::class_<GaussianProcessMCMC, boost::noncopyable>(\"GaussianProcessMCMC\", boost::python::no_init)\n      .def(\"__init__\", boost::python::make_constructor(&make_gaussian_process_mcmc), R\"%%(\n    Constructor for a ``GPP.GaussianProcess`` object.\n\n    Seeds internal NormalRNG randomly.\n\n    :param hyperparameters: covariance hyperparameters; see \"Details on ...\" section at the top of ``BOOST_PYTHON_MODULE``\n    :type hyperparameters: list of len 2; index 0 is a float64 ``\\alpha`` (signal variance) and index 1 is the length scales (list of floa64 of length ``dim``)\n    :param points_sampled: points that have already been sampled\n    :type points_sampled: list of float64 with shape (num_sampled, dim)\n    :param points_sampled_value: values of the already-sampled points\n    :type points_sampled_value: list of float64 with shape (num_sampled, )\n    :param noise_variance: the ``\\sigma_n^2`` (noise variance) associated w/observation, points_sampled_value\n    :type noise_variance: list of float64 with shape (num_sampled, )\n    :param dim: the spatial dimension of a point (i.e., number of independent params in experiment)\n    :type param: int > 0\n    :param num_sampled: number of already-sampled points\n    :type num_sampled: int > 0\n          )%%\");\n\n  boost::python::def(\"compute_knowledge_gradient_mcmc\", ComputeKnowledgeGradientMCMCWrapper, R\"%%(\n    Compute knowledge gradient.\n    If ``num_to_sample == 1`` and ``num_being_sampled == 0`` AND ``force_monte_carlo is false``, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based KG computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: computed EI\n    :rtype: float64 >= 0.0\n    )%%\");\n\n  boost::python::def(\"compute_grad_knowledge_gradient_mcmc\", ComputeGradKnowledgeGradientMCMCWrapper, R\"%%(\n    Compute the gradient of knowledge gradient evaluated at points_to_sample.\n    If num_to_sample = 1 and num_being_sampled = 0 AND force_monte_carlo is false, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based KG computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: gradient of EI (computed at points_to_sample + points_being_sampled, wrt points_to_sample)\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"multistart_knowledge_gradient_mcmc_optimization\", MultistartKnowledgeGradientMCMCOptimizationWrapper, R\"%%(\n    Optimize expected improvement (i.e., solve q,p-EI) over the specified domain using the specified optimization method.\n    Can optimize for num_to_sample new points to sample (i.e., aka \"q\", experiments to run) simultaneously.\n    Allows the user to specify num_being_sampled (aka \"p\") ongoing/concurrent experiments.\n\n    The _CppOptimizerParameters object is a python class defined in:\n    python/cpp_wrappers/optimization._CppOptimizerParameters\n    See that class definition for more details.\n\n    This function expects it to have the fields:\n\n    * domain_type (DomainTypes enum from this file)\n    * optimizer_type (OptimizerTypes enum from this file)\n    * num_random_samples (int, number of samples to 'dumb' search over, if 'dumb' search is being used.\n      e.g., if optimizer = kNull or if to_sample > 1)\n    * optimizer_parameters (*Parameters struct (gpp_optimizer_parameters.hpp) where * matches optimizer_type\n      unused if optimizer_type == kNull)\n\n    This function also has the option of using GPU to compute general q,p-EI via MC simulation. To enable it,\n    make sure you have installed GPU components of MOE, otherwise, it will throw Runtime excpetion.\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n    :param optimizer_parameters: python object containing the DomainTypes domain_type and\n      OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton)\n    :type optimizer_parameters: _CppOptimizerParameters\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param domain: [lower, upper] bound pairs for each dimension\n    :type domain: list of float64 with shape (dim, 2)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param use_gpu: set to 1 if user wants to use GPU for MC computation\n    :type use_gpu: bool\n    :param which_gpu: GPU device ID\n    :type which_gpu: int >= 0\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: next set of points to eval\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"evaluate_KG_mcmc_at_point_list\", EvaluateKGMCMCAtPointListWrapper, R\"%%(\n    Evaluates the expected improvement at each point in initial_guesses; can handle q,p-EI.\n    Useful for plotting.\n\n    Equivalent to::\n\n      result = []\n      for point in initial_guesses:\n          result.append(compute_expected_improvement(point, ...))\n\n    But this method is substantially faster (loop in C++ and multithreaded).\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param initial_guesses: points at which to evaluate EI\n    :type initial_guesses: list of flaot64 with shape (num_multistarts, num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_multistarts: number of points at which to evaluate EI\n    :type num_multistarts: int > 0\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: EI values at each point of the initial_guesses list, in the same order\n    :rtype: list of float64 with shape (num_multistarts, )\n    )%%\");\n}\n}", "meta": {"hexsha": "8e385f31b2f4a6d027a06b6c5686a53e7759f2c4", "size": 38243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_python_knowledge_gradient_mcmc.cpp", "max_stars_repo_name": "misokg/Cornell-MOE", "max_stars_repo_head_hexsha": "1547d6b168b7fc70857d522baa0d5d45c41d3cdf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 218.0, "max_stars_repo_stars_event_min_datetime": "2017-10-14T03:54:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T14:48:38.000Z", "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_python_knowledge_gradient_mcmc.cpp", "max_issues_repo_name": "Tracy3370/Cornell-MOE", "max_issues_repo_head_hexsha": "df299d1be882d2af9796d7a68b3f9505cac7a53e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2017-09-27T14:33:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T09:32:50.000Z", "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_python_knowledge_gradient_mcmc.cpp", "max_forks_repo_name": "Tracy3370/Cornell-MOE", "max_forks_repo_head_hexsha": "df299d1be882d2af9796d7a68b3f9505cac7a53e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2017-09-25T14:23:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T01:41:42.000Z", "avg_line_length": 67.6867256637, "max_line_length": 183, "alphanum_fraction": 0.6806212902, "num_tokens": 7756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.029312230327373227, "lm_q1q2_score": 0.012833583678803925}}
{"text": "/************************************************************************\r\nMIT License\r\n\r\nCopyright (c) 2021 Deqi Tang\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n************************************************************************/\r\n\r\n\r\n#include <boost/program_options.hpp>\r\n//#include <experimental/filesystem>\r\n#include <boost/filesystem.hpp>\r\n#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n#include <regex>\r\n#include <cstdlib>\r\n#include <cmath>\r\n#include <armadillo>\r\n\r\n#include \"atomsciflow/parser/cif.h\"\r\n#include \"atomsciflow/parser/xyz.h\"\r\n#include \"atomsciflow/base/crystal.h\"\r\n#include \"atomsciflow/utils.h\"\r\n\r\n#include \"atomsciflow/cube_handle/cube_handle.h\"\r\n\r\n#include \"atomsciflow/cmd/cmd_utils.h\"\r\n\r\n// needs: libboost-dev, libboost-program-options-dev\r\n\r\nnamespace po = boost::program_options;\r\n\r\n\r\n//namespace filesys = std::experimental::filesystem;  // --std=c++17 -lstdc++fs\r\nnamespace filesys = boost::filesystem;     // --std=c++11 -lboost_filesystem -lboost_system\r\n\r\n\r\nint main(int argc, char const* argv[]) {\r\n    //\r\n\r\n    po::options_description global(\"Global options\");\r\n    global.add_options()\r\n        (\"subcommand\", po::value<std::string>(), \"command to execute\")\r\n        (\"subargs\", po::value<std::vector<std::string> >(), \"Arguments for command\")\r\n        (\"help, h\", \"print out help information\");\r\n        \r\n    po::positional_options_description pos;\r\n    pos.add(\"subcommand\", 1).add(\"subargs\", -1);\r\n    \r\n    po::variables_map vm;\r\n    \r\n    po::parsed_options parsed = po::command_line_parser(argc, argv).\r\n        options(global).\r\n        positional(pos).\r\n        allow_unregistered().\r\n        run();\r\n        \r\n    po::store(parsed, vm);\r\n   \r\n    log_cmd_start(\"atomsciflow-cube.x\");\r\n    \r\n    if (0 == vm.count(\"command\")) { // or by vm.empty()\r\n        std::cout << \"You didn't specify any subcommand!\\n\";\r\n        std::exit(1);\r\n    }\r\n    std::string subcommand = vm[\"subcommand\"].as<std::string>();\r\n\r\n\r\n    if (\"along\" == subcommand) {\r\n        \r\n        log_sub_cmd_start(\"along\");//\r\n\r\n        // along command has the following options:\r\n        po::options_description opt_along(\"along options\");\r\n        opt_along.add_options()\r\n            (\"input, i\", po::value<std::string>(), \"input cube file\")\r\n            (\"output, o\", po::value<std::string>(), \"output structure file\")\r\n            (\"abscissa\", po::value<std::vector<std::string> >()->multitoken(), \"choose the direction to do the dimension reduction\");\r\n        //opts.add_options()\r\n        //    (\"input, i\", po::value<std::string>(&input), \"input structure file\")\r\n        //    (\"output, o\", po::value<std::string>(&output), \"output structure file\");\r\n        // collect all the unrecognized options from the first pass. this will include the \r\n        // (positional) command name so we need to erase that\r\n        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);\r\n        opts.erase(opts.begin());\r\n        //parse again...\r\n        po::store(po::command_line_parser(opts).options(opt_along).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&allow_negative_numbers).run(), vm);\r\n        std::cout << \"parse arguments again\" << \"\\n\";\r\n\r\n        if (vm.count(\"help\")) {\r\n            std::cout << opt_along << std::endl;\r\n            std::exit(1);\r\n        }\r\n        po::notify(vm);\r\n\r\n\r\n\r\n        std::cout << \"Preparing to deal with input and output\\n\";\r\n\r\n        if (vm.count(\"input\") && vm.count(\"output\")) {\r\n\r\n        \r\n            std::string input_file = vm[\"input\"].as<std::string>();\r\n            std::string output_file = vm[\"output\"].as<std::string>();\r\n\r\n            filesys::path in_path(input_file);\r\n            filesys::path out_path(output_file);\r\n\r\n            std::vector<std::string> abscissa = vm[\"abscissa\"].as<std::vector<std::string>>();\r\n        \r\n            std::cout << \"input: \" << input_file << std::endl;\r\n            std::cout << \"output: \" << output_file << std::endl;\r\n        \r\n    \r\n        \r\n            // read structure file\r\n            std::cout << \"in_path(extension)->\" << in_path.extension().string() << std::endl;\r\n\r\n            \r\n            atomsciflow::CubeElectronDensity cube;\r\n            cube.read_cube(input_file);\r\n        \r\n            double bohr_to_angstrom = 0.529177249;\r\n            // data dimension reduction\r\n            // the unit of value is actually not physical now!\r\n            // cell_volume are in unit of Angstrom^3\r\n            arma::mat latcell(3, 3);\r\n            latcell.row(0) = arma::conv_to<arma::rowvec>::from(cube.crystal.cell[0]);\r\n            latcell.row(1) = arma::conv_to<arma::rowvec>::from(cube.crystal.cell[1]);\r\n            latcell.row(2) = arma::conv_to<arma::rowvec>::from(cube.crystal.cell[2]);\r\n            \r\n            std::cout << \"latcell:\\n\";\r\n            std::cout << latcell << std::endl;      \r\n\r\n            // std::cout << \"test value:\\n\";\r\n            // std::cout << arma::dot(arma::cross(latcell.row(0), latcell.row(1)), latcell.row(2)) << std::endl;\r\n\r\n            double cell_volume = arma::dot(arma::cross(latcell.row(0), latcell.row(1)), latcell.row(2));\r\n\r\n            double cell_volume_per_unit = cell_volume / (cube.ngridx * cube.ngridy * cube.ngridz);\r\n\r\n            //std::cout << \"cell volume per unit: \" << cell_volume_per_unit << std::endl;\r\n\r\n            int ngridx = cube.ngridx;\r\n            int ngridy = cube.ngridy;\r\n            int ngridz = cube.ngridz;\r\n            // value in cube file are \\rho(r)_of_electrons in unit of e/Bohr^3\r\n            // namely number of electrons each Borh^3\r\n            // so we have to convert it to e/Angstrom^3, through divide it by borh_to_angstrom**3\r\n        \r\n            double total_electrons = arma::accu(cube.data)  * cell_volume_per_unit / pow(bohr_to_angstrom, 3);\r\n\r\n            std::cout << \"======================================================\\n\";\r\n            std::cout << \"           Information collected\\n\";\r\n            std::cout << \"------------------------------------------------------\\n\";\r\n            std::cout << \"cell volume: \" << cell_volume << \" (A^3)\\n\";\r\n            std::cout << \"total electrons: \" << total_electrons << \"\\n\";\r\n            \r\n            // cube.data is in unit of e/Bohr^3\r\n            // we will build data_red_? to be in unit of e/Anstrom, namely number of electrons per Angstrom\r\n            // to do this we have to time the volume density with bohr_to_angstrom^-3\r\n            std::vector<double> data_red_a;\r\n            std::vector<double> data_red_b;\r\n            std::vector<double> data_red_c;\r\n            //arma::vec data_red_a;\r\n            //arma::vec data_red_b;\r\n            //arma::vec data_red_c;\r\n\r\n            double a = arma::norm(latcell.row(0), 2);\r\n            double b = arma::norm(latcell.row(1), 2);\r\n            double c = arma::norm(latcell.row(2), 2);\r\n            \r\n            if (std::find(abscissa.begin(), abscissa.end(), \"c\") != abscissa.end()) {\r\n                double len_ci = c / ngridz;\r\n                auto size = arma::size(cube.data);\r\n                double tmp;\r\n                double rho_line;\r\n                for (int ci = 0; ci < size[2]; ci++) {\r\n                    tmp  = 0;\r\n                    for (int bi = 0; bi < size[1]; bi++) {\r\n                        for (int ai = 0; ai < size[0]; ai++) {\r\n                            tmp += cube.data.at(ai, bi, ci);\r\n                        }\r\n                    }\r\n                    rho_line = tmp * cell_volume_per_unit / pow(bohr_to_angstrom, 3) / len_ci;\r\n                    data_red_c.push_back(rho_line);\r\n                }\r\n            }\r\n\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"b\") != abscissa.end())  {\r\n                double len_bi = b / ngridy;\r\n                auto size = arma::size(cube.data);\r\n                double tmp;\r\n                double rho_line;\r\n                for (int bi  = 0; bi < size[1]; bi++) {\r\n                    tmp = 0;\r\n                    for (int ai = 0; ai < size[0]; ai++) {\r\n                        for (int ci = 0; ci < size[2]; ci++) {\r\n                            tmp += cube.data.at(ai, bi, ci);\r\n                        }\r\n                    }\r\n                    rho_line = tmp * cell_volume_per_unit / pow(bohr_to_angstrom, 3) / len_bi;\r\n                    data_red_b.push_back(rho_line);\r\n                }\r\n            }\r\n\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"a\") != abscissa.end())  {\r\n                double len_ai = a / ngridx;\r\n                auto size = arma::size(cube.data);\r\n                double tmp;\r\n                double rho_line;\r\n                for (int ai = 0; ai < size[0]; ai++) {\r\n                    tmp = 0;\r\n                    for (int ci = 0; ci < size[2]; ci++) {\r\n                        for (int bi = 0; bi < size[1]; bi++) {\r\n                            tmp += cube.data.at(ai, bi, ci);\r\n                        }\r\n                    }\r\n                    rho_line = tmp * cell_volume_per_unit / pow(bohr_to_angstrom, 3) / len_ai;\r\n                    data_red_a.push_back(rho_line);\r\n                }\r\n            }\r\n\r\n            std::cout << \"Preparing to output the data\\n\";\r\n            // output the data and make the plot\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"c\") != abscissa.end()) {\r\n                std::ofstream fout;\r\n                fout.open(output_file+\".1d.c.data\");\r\n                fout << \"#c(angstrom) rho(e) (number of electron per Angstrom)\\n\";\r\n                arma::vec c_coord = arma::linspace(0, c, data_red_c.size());\r\n                for (int i = 0; i < data_red_c.size(); i++) {\r\n                    fout << c_coord.at(i) << \" \" << data_red_c.at(i) << \"\\n\";\r\n                }\r\n                fout.close();\r\n            }\r\n           \r\n            if (std::find(abscissa.begin(), abscissa.end(), \"b\") != abscissa.end()) {\r\n                std::ofstream fout;\r\n                fout.open(output_file+\".1d.b.data\");\r\n                fout << \"#b(angstrom) rho(e) (number of electron per Angstrom)\\n\";\r\n                arma::vec b_coord = arma::linspace(0, b, data_red_b.size());\r\n                for (int i = 0; i < data_red_b.size(); i++) {\r\n                    fout << b_coord.at(i) << \" \" << data_red_b.at(i) << \"\\n\";\r\n                }\r\n                fout.close();\r\n            }\r\n\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"a\") != abscissa.end())  {\r\n                std::ofstream fout;\r\n                fout.open(output_file+\".1d.a.data\");\r\n                fout << \"#a(angstrom) rho(e) (number of electron per Angstrom)\\n\";\r\n                arma::vec a_coord = arma::linspace(0, a, data_red_a.size());\r\n                for (int i = 0; i < data_red_a.size(); i++) {\r\n                    fout << a_coord.at(i) << \" \" << data_red_a.at(i) << \"\\n\";\r\n                }\r\n                fout.close();\r\n            }       \r\n\r\n            //std::ofstream fxx;\r\n            //fxx.open(\"xxx.data\");\r\n            //fxx << cube.data << std::endl;\r\n            //fxx.close();\r\n\r\n        }\r\n\r\n        log_sub_cmd_end(\"along\");\r\n        \r\n    } else if (\"diff\" == subcommand) {\r\n        //\r\n        log_sub_cmd_start(\"diff\");\r\n\r\n        // along command has the following options:\r\n        po::options_description opt_diff(\"diff options\");\r\n        opt_diff.add_options()\r\n            (\"input, i\", po::value<std::vector<std::string> >()->multitoken(), \"input three cube file: TOTAL PART1 PART2\")\r\n            (\"output, o\", po::value<std::string>(), \"output structure file\")\r\n            (\"abscissa\", po::value<std::vector<std::string> >()->multitoken(), \"choose the direction to do the dimension reduction\");\r\n        //opts.add_options()\r\n        //    (\"input, i\", po::value<std::string>(&input), \"input structure file\")\r\n        //    (\"output, o\", po::value<std::string>(&output), \"output structure file\");\r\n        // collect all the unrecognized options from the first pass. this will include the \r\n        // (positional) command name so we need to erase that\r\n        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);\r\n        opts.erase(opts.begin());\r\n        //parse again...\r\n        po::store(po::command_line_parser(opts).options(opt_diff).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&allow_negative_numbers).run(), vm);\r\n        std::cout << \"parse arguments again\" << \"\\n\";\r\n\r\n        if (vm.count(\"help\")) {\r\n            std::cout << opt_diff << std::endl;\r\n            std::exit(1);\r\n        }\r\n        po::notify(vm);\r\n\r\n\r\n\r\n        std::cout << \"Preparing to deal with input and output\\n\";\r\n\r\n        if (vm.count(\"input\") && vm.count(\"output\")) {\r\n\r\n        \r\n            // std::string input_file = vm[\"input\"].as<std::string>();\r\n            std::vector<std::string> input_files = vm[\"input\"].as<std::vector<std::string>>();\r\n            std::string output_file = vm[\"output\"].as<std::string>();\r\n\r\n            // filesys::path in_path(input_file);\r\n            filesys::path out_path(output_file);\r\n\r\n            std::vector<std::string> abscissa = vm[\"abscissa\"].as<std::vector<std::string>>();\r\n        \r\n            std::cout << \"input: \\n\" \r\n                << input_files[0] << \"\\n\" \r\n                << input_files[1] << \"\\n\" \r\n                << input_files[2] << \"\\n\" << std::endl;\r\n\r\n            std::cout << \"output: \" << output_file << std::endl;\r\n        \r\n\r\n            atomsciflow::cube_diff_1d(input_files, output_file, abscissa);\r\n\r\n        }\r\n        \r\n        log_sub_cmd_end(\"diff\"); \r\n        \r\n    } else {\r\n        std::cout << \"The specified subcommand is not defined!\\n\";\r\n    } \r\n    \r\n    //\r\n    return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "0313907187a1f75185a35498c9653cb70566182e", "size": 14843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmd/atomsciflow_cube.cpp", "max_stars_repo_name": "DeqiTang/build-test-atomsciflow", "max_stars_repo_head_hexsha": "6fb65c79e74993e2100fbbca31b910d495076805", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-25T01:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T01:44:32.000Z", "max_issues_repo_path": "cmd/atomsciflow_cube.cpp", "max_issues_repo_name": "DeqiTang/build-test-atomsciflow", "max_issues_repo_head_hexsha": "6fb65c79e74993e2100fbbca31b910d495076805", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmd/atomsciflow_cube.cpp", "max_forks_repo_name": "DeqiTang/build-test-atomsciflow", "max_forks_repo_head_hexsha": "6fb65c79e74993e2100fbbca31b910d495076805", "max_forks_repo_licenses": ["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.2877492877, "max_line_length": 211, "alphanum_fraction": 0.5184261942, "num_tokens": 3462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.04084571518021443, "lm_q1q2_score": 0.012827619112926484}}
{"text": "/****************************************************************************\n**\n** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group\n** Contact: v4r.acin.tuwien.ac.at\n**\n** This file is part of V4R\n**\n** V4R is distributed under dual licenses - GPLv3 or closed source.\n**\n** GNU General Public License Usage\n** V4R 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, or\n** (at your option) any later version.\n**\n** V4R 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** Please review the following information to ensure the GNU General Public\n** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html.\n**\n**\n** Commercial License Usage\n** If GPL is not suitable for your project, you must purchase a commercial\n** license to use V4R. Licensees holding valid commercial V4R licenses may\n** use this file in accordance with the commercial license agreement\n** provided with the Software or, alternatively, in accordance with the\n** terms contained in a written agreement between you and TU Wien, ACIN, V4R.\n** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at.\n**\n**\n** The copyright holder additionally grants the author(s) of the file the right\n** to use, copy, modify, merge, publish, distribute, sublicense, and/or\n** sell copies of their contributions without any restrictions.\n**\n****************************************************************************/\n\n#include \"v4r/attention_segmentation/algo.h\"\n#include \"v4r/attention_segmentation/AttentionModuleErrors.h\"\n\n#include <Eigen/Dense>\n\nnamespace v4r {\n\nvoid filterGaussian(cv::Mat &input, cv::Mat &output, cv::Mat &mask) {\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    for (int j = 0; j < input.cols; j = j + 2) {\n      if (mask.at<float>(i, j) > 0) {\n        float value = 0;\n        float kernel_sum = 0;\n\n        for (int k = 0; k < 5; ++k) {\n          int jj = j + (k - 2);\n          if ((jj >= 0) && (jj < input.cols)) {\n            if (mask.at<float>(i, jj) > 0) {\n              value += kernel[k] * input.at<float>(i, jj);\n              kernel_sum += kernel[k];\n            }\n          }\n        }\n\n        if (kernel_sum > 0) {\n          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    for (int j = 0; j < temp.cols; j = j + 2) {\n      if (mask.at<float>(i, j) > 0) {\n        float value = 0;\n        float kernel_sum = 0;\n\n        for (int k = 0; k < 5; ++k) {\n          int ii = i + (k - 2);\n          if ((ii >= 0) && (ii < temp.rows)) {\n            if (mask.at<float>(ii, j) > 0) {\n              value += kernel[k] * temp.at<float>(ii, j);\n              kernel_sum += kernel[k];\n            }\n          }\n        }\n\n        if (kernel_sum > 0) {\n          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    for (int j = 0; j < new_width; ++j) {\n      if (mask.at<float>(2 * i, 2 * j) > 0) {\n        mask_output.at<float>(i, j) = 1.0;\n        output.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  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    cv::Mat tempImage;\n\n    filterGaussian(pyramid.at(i - 1), tempImage, oldMask);\n    tempImage.copyTo(pyramid.at(i));\n  }\n}\n\nint createPointCloudPyramid(std::vector<cv::Mat> &pyramidX, std::vector<cv::Mat> &pyramidY,\n                            std::vector<cv::Mat> &pyramidZ, std::vector<cv::Mat> &pyramidIndices,\n                            std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &pyramidCloud) {\n  assert(pyramidX.size() == pyramidY.size());\n  assert(pyramidX.size() == pyramidZ.size());\n  assert(pyramidX.size() == pyramidIndices.size());\n\n  if (pyramidX.size() != pyramidY.size() && pyramidX.size() != pyramidZ.size() &&\n      pyramidX.size() != pyramidIndices.size())\n    return AM_DIFFERENTSIZES;\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    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    for (unsigned int i = 0; i < cur_height; ++i) {\n      for (unsigned int j = 0; j < cur_width; ++j) {\n        pcl::PointXYZRGB p_cur;\n        p_cur.x = pyramidX.at(idx).at<float>(i, j);\n        p_cur.y = pyramidY.at(idx).at<float>(i, j);\n        p_cur.z = pyramidZ.at(idx).at<float>(i, j);\n\n        int p_idx = i * cur_width + j;\n        pyramidCloud.at(idx)->points.at(p_idx) = p_cur;\n      }\n    }\n  }\n\n  return AM_OK;\n}\n\nvoid createNormalPyramid(std::vector<cv::Mat> &pyramidNx, std::vector<cv::Mat> &pyramidNy,\n                         std::vector<cv::Mat> &pyramidNz, std::vector<cv::Mat> &pyramidIndices,\n                         std::vector<pcl::PointCloud<pcl::Normal>::Ptr> &pyramidNormal) {\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    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      for (unsigned int j = 0; j < cur_width; ++j) {\n        if (pyramidIndices.at(idx).at<float>(i, j) > 0) {\n          pcl::Normal p_cur;\n          p_cur.normal[0] = pyramidNx.at(idx).at<float>(i, j);\n          p_cur.normal[1] = pyramidNy.at(idx).at<float>(i, j);\n          p_cur.normal[2] = pyramidNz.at(idx).at<float>(i, j);\n\n          pyramidNormal.at(idx)->points.push_back(p_cur);\n        }\n      }\n    }\n\n    pyramidNormal.at(idx)->width = pyramidNormal.at(idx)->points.size();\n    pyramidNormal.at(idx)->height = 1;\n  }\n}\n\nvoid createIndicesPyramid(std::vector<cv::Mat> &pyramidIndices,\n                          std::vector<pcl::PointIndices::Ptr> &pyramidIndiceSets) {\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    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      for (unsigned int j = 0; j < cur_width; ++j) {\n        if (pyramidIndices.at(idx).at<float>(i, j) > 0) {\n          int p_idx = i * cur_width + j;\n          pyramidIndiceSets.at(idx)->indices.push_back(p_idx);\n        }\n      }\n    }\n  }\n}\n\nvoid upscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height) {\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    for (unsigned int j = 0; j < (unsigned int)input.cols; ++j) {\n      output.at<float>(2 * i, 2 * j) = input.at<float>(i, j);\n    }\n  }\n\n  for (unsigned int i = 0; i < (unsigned int)output.rows; i = i + 2) {\n    for (unsigned int j = 1; j < (unsigned int)output.cols - 1; j = j + 2) {\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    for (unsigned int j = 0; j < (unsigned int)output.cols; j = j + 2) {\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    for (unsigned int j = 1; j < (unsigned int)output.cols - 1; j = j + 2) {\n      output.at<float>(i, j) = (output.at<float>(i - 1, j - 1) + output.at<float>(i - 1, j + 1) +\n                                output.at<float>(i + 1, j - 1) + output.at<float>(i + 1, j + 1)) /\n                               4.0;\n    }\n  }\n}\n\nvoid downscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height) {\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    for (unsigned int j = 0; j < (unsigned int)output.cols; ++j) {\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  assert(input.cols == inputPyramid.at(inLevel).cols);\n  assert(input.rows == inputPyramid.at(inLevel).rows);\n\n  if (inLevel < outLevel) {\n    input.copyTo(output);\n    for (int l = inLevel + 1; l <= outLevel; ++l) {\n      cv::Mat temp;\n      downscaleImage(output, temp, inputPyramid.at(l).cols, inputPyramid.at(l).rows);\n      temp.copyTo(output);\n    }\n  } else if (inLevel > outLevel) {\n    input.copyTo(output);\n    for (int l = inLevel - 1; l >= outLevel; --l) {\n      cv::Mat temp;\n      upscaleImage(output, temp, inputPyramid.at(l).cols, inputPyramid.at(l).rows);\n      temp.copyTo(output);\n    }\n  } else {\n    input.copyTo(output);\n  }\n}\n\nbool inPoly(std::vector<cv::Point> &poly, cv::Point p) {\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    return (false);\n  }\n\n  oldPoint = poly.at(poly.size() - 1);\n  for (unsigned int i = 0; i < poly.size(); i++) {\n    newPoint = poly.at(i);\n    if (newPoint.y > oldPoint.y) {\n      p1 = oldPoint;\n      p2 = newPoint;\n    } else {\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      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  for (int i = 0; i < polygonMap.rows; ++i) {\n    for (int j = 0; j < polygonMap.cols; ++j) {\n      unsigned int k = 0;\n      while ((polygonMap.at<uchar>(i, j) == 0) && (k < polygons.size())) {\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  for (unsigned int i = 0; i < polygons.size(); ++i) {\n    for (unsigned int j = 0; j < polygons.at(i).size(); ++j) {\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  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  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    _x[i] = x.at(i) - mean.at(i);\n    for (int j = 0; j < dim; ++j) {\n      _stddev(i, j) = stddev.at<float>(i, j);\n    }\n  }\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\nvoid addNoise(cv::Mat &image, cv::Mat &nImage, cv::RNG &rng, float min, float max) {\n  nImage = cv::Mat_<float>::zeros(image.rows, image.cols);\n  for (int i = 0; i < image.rows; ++i) {\n    for (int j = 0; j < image.cols; ++j) {\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  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  float total_sum = 0;\n  for (unsigned int i = 0; i < dist.size(); ++i) {\n    total_sum += dist.at(i);\n  }\n\n  for (unsigned int i = 0; i < dist.size(); ++i) {\n    dist.at(i) /= total_sum;\n  }\n}\n\nfloat getMean(std::vector<float> dist, float total_num) {\n  float mean = 0;\n  for (unsigned int i = 0; i < dist.size(); ++i) {\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  float stdDev = 0;\n\n  for (unsigned int i = 0; i < dist.size(); ++i) {\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  long min = 0;\n  long max = A.size() - 1;\n  while (max != min + 1) {\n    long mid = (min + max) / 2;\n    if (x <= A.at(mid)) {\n      max = mid;\n    } else {\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  contours.clear();\n  contours.resize(masks.size());\n\n  for (unsigned int i = 0; i < masks.size(); ++i) {\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      long totalPointsNum = 0;\n      for (unsigned int j = 0; j < temp.size(); ++j) {\n        totalPointsNum += 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        for (unsigned int k = 0; k < temp.at(j).size(); ++k) {\n          contours.at(i).at(totalPointsNum) = temp.at(j).at(k);\n          totalPointsNum += 1;\n        }\n      }\n    }\n  }\n}\n\nuchar Num01Transitions(cv::Mat s, int j, int i) {\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  for (int i = 1; i < s.rows - 1; ++i) {\n    for (int j = 1; j < s.cols - 1; ++j) {\n      if (s.at<uchar>(i, j) > 0) {\n        bool remove = true;\n        for (int p = 0; p < 8; ++p) {\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\n          if (element[p] < 2) {\n            if (value != element[p]) {\n              remove = false;\n            }\n          }\n        }\n\n        if (remove) {\n          s.at<uchar>(i, j) = 0;\n        }\n      }\n    }\n  }\n}\n\nV4R_EXPORTS void Skeleton(cv::Mat a, cv::Mat &s) {\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    cv::Mat m = cv::Mat_<uchar>::ones(height, width);\n\n    for (int j = 1; j < height - 1; ++j) {\n      for (int i = 1; i < width - 1; ++i) {\n        if (s.at<uchar>(j, i) == 1) {\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 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        }\n      }\n    }\n\n    for (int j = 1; j < height - 1; ++j) {\n      for (int i = 1; i < width - 1; ++i) {\n        s.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      for (int i = 1; i < width - 1; ++i) {\n        if (s.at<uchar>(j, i) == 1) {\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 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        }\n      }\n    }\n\n    for (int j = 1; j < height - 1; ++j) {\n      for (int i = 1; i < width - 1; ++i) {\n        s.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  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    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  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  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  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    for (int j = 0; j < mask.cols; ++j) {\n      uchar value = mask.at<uchar>(i, j);\n      if (value > 0) {\n        x_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    // 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      cv::Point p = points.front();\n      points.pop_front();\n      if (mask.at<uchar>(p.y, p.x) > 0) {\n        x_cen = p.x;\n        y_cen = p.y;\n        break;\n      }\n\n      for (int i = 0; i < 8; ++i) {\n        int new_x = p.x + dx8[i];\n        int new_y = p.y + dy8[i];\n\n        if ((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows))\n          continue;\n\n        if (used.at<uchar>(new_y, new_x) <= 0) {\n          points.push_back(cv::Point(new_x, new_y));\n          used.at<uchar>(new_y, new_x) = 1;\n        }\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  float x_cen = 0;\n  float y_cen = 0;\n\n  for (unsigned int i = 0; i < contour.size(); ++i) {\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    // 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      cv::Point p = points.front();\n      points.pop_front();\n      if (mask.at<uchar>(p.y, p.x) > 0) {\n        x_cen = p.x;\n        y_cen = p.y;\n        break;\n      }\n\n      for (int i = 0; i < 8; ++i) {\n        int new_x = p.x + dx8[i];\n        int new_y = p.y + dy8[i];\n\n        if ((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows))\n          continue;\n\n        if (used.at<uchar>(new_y, new_x) <= 0) {\n          points.push_back(cv::Point(new_x, new_y));\n          used.at<uchar>(new_y, new_x) = 1;\n        }\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  neighbors = cv::Mat_<bool>(patchesNumber, patchesNumber);\n  neighbors.setTo(false);\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    for (int c = 1; c < patches.cols - 1; c++) {\n      // if the patch exist\n      if (patches.at<int>(r, c) != -1) {\n        int patchIdx = patches.at<int>(r, c);\n\n        //@ep: why we did not use 1,-1 shift???\n        for (int i = 0; i < 3; ++i)  //@ep: TODO 3->4\n        {\n          int nr = r + dr[i];\n          int nc = c + dc[i];\n\n          int currentPatchIdx = patches.at<int>(nr, nc);\n          if (currentPatchIdx == -1)\n            continue;\n\n          if (patchIdx != currentPatchIdx) {\n            neighbors.at<bool>(currentPatchIdx, patchIdx) = true;\n            neighbors.at<bool>(patchIdx, currentPatchIdx) = true;\n          }\n        }\n      }\n    }\n  }\n}\n\n}  // namespace v4r\n", "meta": {"hexsha": "b9f0203c850126067cadb83bfd52a4dc74919861", "size": 24190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/attention_segmentation/src/algo.cpp", "max_stars_repo_name": "v4r-tuwien/v4r", "max_stars_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_stars_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-22T11:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T11:31:08.000Z", "max_issues_repo_path": "modules/attention_segmentation/src/algo.cpp", "max_issues_repo_name": "v4r-tuwien/v4r", "max_issues_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_issues_repo_licenses": ["BSD-1-Clause", "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": "modules/attention_segmentation/src/algo.cpp", "max_forks_repo_name": "v4r-tuwien/v4r", "max_forks_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_forks_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T10:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T13:39:03.000Z", "avg_line_length": 30.5044136192, "max_line_length": 115, "alphanum_fraction": 0.5457627119, "num_tokens": 7882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.027585284824929366, "lm_q1q2_score": 0.012824442670919423}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef METRO_SHOTGUNSTOCHASTICSEARCH_HPP\n#define METRO_SHOTGUNSTOCHASTICSEARCH_HPP\n\n#include <vector>\n#include <unordered_map>\n#include <boost/function.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\nnamespace metro {\n\t/*\n\t* This class performs a FINEMAP-like 'shotgun stochastic search'.\n\t* Given an integer N, starting with the empty state, this class searches by generating\n\t* all possible changes to the current state by adding / changing / removing any of the\n\t* N possible indicators.  It then computes a likelihood using the user-supplied\n\t* likelihood function.  Finally, it updates the current state by moving to one of the new states\n\t* uniformly weighted by the likelihood.\n\t* See Benner et al, \"FINEMAP: Efficient variable selection using summary data from genome-wide association studies\",\n\t* Bioinformatics (2016) for algorithm details.\n\t* This class merely implements the 'search' aspect of this algorithm.  To make efficient use of it,\n\t* the user must use a likelihood function that e.g. prohibits too-large numbers of predictor variables.\n\t*/\n\tstruct ShotgunStochasticSearch {\n\t\ttypedef std::vector< std::size_t > SelectedStates ;\n\t\ttypedef boost::function< double ( SelectedStates const& ) > ComputeLL ;\n\t\tstruct StateHash {\n\t\tpublic:\n\t\t\tsize_t operator()(const SelectedStates &p) const {\n\t\t\t\treturn boost::hash_value(p);\n\t\t\t}\n\t\t} ;\n\n\t\ttypedef std::unordered_map< SelectedStates, double, StateHash > Store ;\n\n\t\tShotgunStochasticSearch(\n\t\t\tstd::size_t n,\n\t\t\tComputeLL compute_ll,\n\t\t\tstd::uint32_t rng_seed\n\t\t) ;\n\n\t\t/* Compute the next search update with the given likelihood function */\n\t\tSelectedStates const& update() ;\n\n\t\t/* Return our store of states visited so far */ \n\t\tStore const& visited_states() const ;\n\t\tvoid visited_states( boost::function< void( SelectedStates const&, double ) > callback ) const ;\n\t\n\tprivate:\n\t\tstd::size_t const m_N ;\n\t\tShotgunStochasticSearch::ComputeLL m_compute_ll ;\n\t\tSelectedStates m_current_state ;\n\t\tStore m_lls ;\n\t\tboost::random::mt19937 m_rng;\n\t\n\tprivate:\n\t\t/* Generate all states obtained by deleting a member\n\t\tof the current state, and append to the given vector */\n\t\tvoid generate_deletions( std::vector< SelectedStates >* result ) ;\n\n\t\t/* Generate all states obtained by adding a member or changing a member\n\t\tof the current state, and append to the given vector */\n\t\tvoid generate_additions_and_changes( std::vector< SelectedStates >* result ) ;\n\t} ;\n}\n\n#endif\n\n\n", "meta": {"hexsha": "9a9f52f480528bdd0d4f84dc9fac9510fb328c86", "size": 2736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/ShotgunStochasticSearch.hpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/include/metro/ShotgunStochasticSearch.hpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/include/metro/ShotgunStochasticSearch.hpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 117, "alphanum_fraction": 0.745248538, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.028007520605988136, "lm_q1q2_score": 0.012803266016299822}}
{"text": "#ifndef N_BODY_PHYSICAL_HPP\n#define N_BODY_PHYSICAL_HPP\n\n#include \"communication.hpp\"\n#include \"config.hpp\"\n#include \"data.hpp\"\n#include \"logging.hpp\"\n#include \"space.hpp\"\n#include \"tree.hpp\"\n#include <boost/archive/xml_oarchive.hpp>\n#include <boost/mpi.hpp>\n#include <cmath>\n#include <cstddef>\n\nnamespace n_body::physical {\n\nusing namespace n_body::data;\n\ntemplate <typename T, std::size_t Dimension>\nvoid step(const config::Configuration<T> &config,\n          const boost::mpi::communicator &comm, int root,\n          data::Bodies<T, Dimension> &bodies,\n          const data::tree::BodyTree<T, Dimension> &tree);\n\ntemplate <typename T, std::size_t Dimension, typename Iter>\nvoid step(const config::Configuration<T> &config, Iter first, Iter last,\n          const data::tree::BodyTree<T, Dimension> &tree);\n\ntemplate <typename T, std::size_t Dimension, typename Iter>\nvoid step(const config::Configuration<T> &config, Iter first, Iter last,\n          const data::Bodies<T, Dimension> &bodies);\n\ntemplate <typename T, std::size_t Dimension>\ndata::Vector<T, Dimension> gravity_per_unit_mass_tree_to_position(\n    const config::Configuration<T> &config,\n    const data::tree::BodyTree<T, Dimension> &tree,\n    const data::Vector<T, Dimension> &position);\n\ntemplate <typename T, std::size_t Dimension>\ndata::Vector<T, Dimension> gravity_per_unit_mass_subtree_to_position(\n    const config::Configuration<T> &config,\n    const data::tree::BodyTree<T, Dimension> &tree, std::size_t root,\n    const data::Vector<T, Dimension> &position);\n\ntemplate <typename T, std::size_t Dimension>\ndata::Vector<T, Dimension> gravity_per_unit_mass_position_to_position(\n    const config::Configuration<T> &config,\n    const data::Vector<T, Dimension> &other_position,\n    data::Scalar<T> other_mass, const data::Vector<T, Dimension> &position);\n\n// update bodies one step\ntemplate <typename T, std::size_t Dimension>\nvoid step(const config::Configuration<T> &config,\n          const boost::mpi::communicator &comm,\n          data::Bodies<T, Dimension> &bodies,\n          const data::tree::BodyTree<T, Dimension> &tree) {\n  communication::Division division(comm, bodies.size());\n  data::Bodies<T, Dimension> local_bodies(&bodies[division.begin],\n                                          &bodies[division.end]);\n  // step(config, local_bodies.begin(), local_bodies.end(), tree);\n  step(config, local_bodies.begin(), local_bodies.end(), bodies);\n  boost::mpi::all_gather(comm, local_bodies.data(), division.count, bodies);\n}\n\n// update bodies one step by iterator\ntemplate <typename T, std::size_t Dimension, typename Iter>\nvoid step(const config::Configuration<T> &config, Iter first, Iter last,\n          const data::Bodies<T, Dimension> &bodies) {\n  for (; first != last; ++first) {\n    data::Vector<T, Dimension> acceleration{\n        0,\n        0,\n        0,\n    };\n    for (const auto &body : bodies) {\n      acceleration += gravity_per_unit_mass_position_to_position(\n          config, body.position, body.mass, first->position);\n    }\n    first->velocity += config.time * acceleration;\n    first->position += config.time * first->velocity;\n  }\n}\n\n// update bodies one step by iterator\ntemplate <typename T, std::size_t Dimension, typename Iter>\nvoid step(const config::Configuration<T> &config, Iter first, Iter last,\n          const data::tree::BodyTree<T, Dimension> &tree) {\n  for (; first != last; ++first) {\n    auto acceleration =\n        gravity_per_unit_mass_tree_to_position(config, tree, first->position);\n    first->velocity += config.time * acceleration;\n    first->position += config.time * first->velocity;\n  }\n}\n\ntemplate <typename T, std::size_t Dimension>\ndata::Vector<T, Dimension> gravity_per_unit_mass_tree_to_position(\n    const config::Configuration<T> &config,\n    const data::tree::BodyTree<T, Dimension> &tree,\n    const data::Vector<T, Dimension> &position) {\n  if (tree.tree.empty())\n    return {0, 0, 0};\n  return gravity_per_unit_mass_subtree_to_position(config, tree, 0, position);\n}\n\ntemplate <typename T, std::size_t Dimension>\ndata::Vector<T, Dimension> gravity_per_unit_mass_subtree_to_position(\n    const config::Configuration<T> &config,\n    const data::tree::BodyTree<T, Dimension> &tree, std::size_t root,\n    const data::Vector<T, Dimension> &position) {\n\n  if (tree.node(root).node_type() == data::tree::NodeType::Inner) {\n    auto position_in_space = space::contains(tree.node(root).space, position);\n\n    auto space_size = space::size_of_space(tree.node(root).space);\n    auto distance = data::module_of(position - tree.node(root).center_of_mass);\n    if (!position_in_space && (space_size / distance) < config.theta) {\n      return gravity_per_unit_mass_position_to_position(\n          config, tree.node(root).center_of_mass, tree.node(root).mass,\n          position);\n    } else {\n      data::Vector<T, Dimension> sum{\n          0,\n          0,\n          0,\n      };\n      for (std::size_t i = 0;\n           i < data::tree::BodyTreeInnerNode<T, Dimension>::CHILDREN_NUMBER;\n           ++i) {\n        if (auto subtree = tree.child_of_node(root, i)) {\n          sum += gravity_per_unit_mass_subtree_to_position(config, tree,\n                                                           *subtree, position);\n        }\n      }\n      return sum;\n    }\n  } else {\n    // node is a leaf\n    return gravity_per_unit_mass_position_to_position(\n        config, tree.node(root).center_of_mass, tree.node(root).mass, position);\n  }\n}\n\ntemplate <typename T, std::size_t Dimension>\ndata::Vector<T, Dimension> gravity_per_unit_mass_position_to_position(\n    const config::Configuration<T> &config,\n    const data::Vector<T, Dimension> &other_position,\n    data::Scalar<T> other_mass, const data::Vector<T, Dimension> &position) {\n  auto dp = other_position - position;\n  auto distance = data::module_of(dp);\n  if (distance == 0) {\n    return {\n        0,\n        0,\n        0,\n    };\n  } // singularity\n  auto G = config.G;\n  auto soften = config.soften_length;\n  auto result = G * other_mass /\n                std::pow((soften_length * soften_length + distance * distance),\n                         static_cast<T>(3) / static_cast<T>(2)) *\n                dp;\n  return result;\n}\n\n} // namespace n_body::physical\n\n#endif\n", "meta": {"hexsha": "1677364b618111ee7d20ad04b0faacb007c4ff55", "size": 6233, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/physical.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/physical.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/physical.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": 36.6647058824, "max_line_length": 80, "alphanum_fraction": 0.6709449703, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.03258974417877704, "lm_q1q2_score": 0.012786156927058355}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_IGH_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IGH_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/shared_ptr.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 igh {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace igh\n    {\n\n            template <typename CalculationType, typename Parameters>\n            struct par_igh\n            {\n                boost::shared_ptr<base_v<CalculationType, Parameters> > pj[12];\n                CalculationType dy0;\n            };\n\n            template <typename T>\n            inline T d4044118() { return (T(40) + T(44)/T(60.) + T(11.8)/T(3600.)) * geometry::math::d2r<T>(); } // 40d 44' 11.8\" [degrees]\n\n            template <typename T>\n            inline T d10() { return T(10) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d20() { return T(20) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d30() { return T(30) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d40() { return T(40) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d50() { return T(50) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d60() { return T(60) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d80() { return T(80) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d90() { return T(90) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d100() { return T(100) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d140() { return T(140) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d160() { return T(160) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T d180() { return T(180) * geometry::math::d2r<T>(); }\n\n            static const double EPSLN = 1.e-10; // allow a little 'slack' on zone edge positions\n\n            // Converted from #define SETUP(n, proj, x_0, y_0, lon_0)\n            template <template <typename, typename> class Entry, typename Parameters, typename CalculationType>\n            inline void do_setup(int n, Parameters const& par, par_igh<CalculationType, Parameters>& proj_parm,\n                                 CalculationType const& x_0, CalculationType const& y_0,\n                                 CalculationType const& lon_0)\n            {\n                Entry<CalculationType, Parameters> entry;\n                proj_parm.pj[n-1].reset(entry.create_new(par));\n                proj_parm.pj[n-1]->mutable_params().x0 = x_0;\n                proj_parm.pj[n-1]->mutable_params().y0 = y_0;\n                proj_parm.pj[n-1]->mutable_params().lam0 = lon_0;\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_igh_spheroid : public base_t_fi<base_igh_spheroid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_igh<CalculationType, Parameters> m_proj_parm;\n\n                inline base_igh_spheroid(const Parameters& par)\n                    : base_t_fi<base_igh_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                    static const CalculationType d4044118 = igh::d4044118<CalculationType>();\n                    static const CalculationType d20  =  igh::d20<CalculationType>();\n                    static const CalculationType d40  =  igh::d40<CalculationType>();\n                    static const CalculationType d80  =  igh::d80<CalculationType>();\n                    static const CalculationType d100 = igh::d100<CalculationType>();\n\n                        int z;\n                        if (lp_lat >=  d4044118) {          // 1|2\n                          z = (lp_lon <= -d40 ? 1: 2);\n                        }\n                        else if (lp_lat >=  0) {            // 3|4\n                          z = (lp_lon <= -d40 ? 3: 4);\n                        }\n                        else if (lp_lat >= -d4044118) {     // 5|6|7|8\n                               if (lp_lon <= -d100) z =  5; // 5\n                          else if (lp_lon <=  -d20) z =  6; // 6\n                          else if (lp_lon <=   d80) z =  7; // 7\n                          else z = 8;                       // 8\n                        }\n                        else {                              // 9|10|11|12\n                               if (lp_lon <= -d100) z =  9; // 9\n                          else if (lp_lon <=  -d20) z = 10; // 10\n                          else if (lp_lon <=   d80) z = 11; // 11\n                          else z = 12;                      // 12\n                        }\n\n                        lp_lon -= this->m_proj_parm.pj[z-1]->params().lam0;\n                        this->m_proj_parm.pj[z-1]->fwd(lp_lon, lp_lat, xy_x, xy_y);\n                        xy_x += this->m_proj_parm.pj[z-1]->params().x0;\n                        xy_y += this->m_proj_parm.pj[z-1]->params().y0;\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 d4044118 = igh::d4044118<CalculationType>();\n                    static const CalculationType d10  =  igh::d10<CalculationType>();\n                    static const CalculationType d20  =  igh::d20<CalculationType>();\n                    static const CalculationType d40  =  igh::d40<CalculationType>();\n                    static const CalculationType d50  =  igh::d50<CalculationType>();\n                    static const CalculationType d60  =  igh::d60<CalculationType>();\n                    static const CalculationType d80  =  igh::d80<CalculationType>();\n                    static const CalculationType d90  =  igh::d90<CalculationType>();\n                    static const CalculationType d100 = igh::d100<CalculationType>();\n                    static const CalculationType d160 = igh::d160<CalculationType>();\n                    static const CalculationType d180 = igh::d180<CalculationType>();\n\n                    static const CalculationType c2 = 2.0;\n                    \n                    const CalculationType y90 = this->m_proj_parm.dy0 + sqrt(c2); // lt=90 corresponds to y=y0+sqrt(2.0)\n\n                        int z = 0;\n                        if (xy_y > y90+EPSLN || xy_y < -y90+EPSLN) // 0\n                          z = 0;\n                        else if (xy_y >=  d4044118)       // 1|2\n                          z = (xy_x <= -d40? 1: 2);\n                        else if (xy_y >=  0)              // 3|4\n                          z = (xy_x <= -d40? 3: 4);\n                        else if (xy_y >= -d4044118) {     // 5|6|7|8\n                               if (xy_x <= -d100) z =  5; // 5\n                          else if (xy_x <=  -d20) z =  6; // 6\n                          else if (xy_x <=   d80) z =  7; // 7\n                          else z = 8;                     // 8\n                        }\n                        else {                            // 9|10|11|12\n                               if (xy_x <= -d100) z =  9; // 9\n                          else if (xy_x <=  -d20) z = 10; // 10\n                          else if (xy_x <=   d80) z = 11; // 11\n                          else z = 12;                    // 12\n                        }\n\n                        if (z)\n                        {\n                          int ok = 0;\n\n                          xy_x -= this->m_proj_parm.pj[z-1]->params().x0;\n                          xy_y -= this->m_proj_parm.pj[z-1]->params().y0;\n                          this->m_proj_parm.pj[z-1]->inv(xy_x, xy_y, lp_lon, lp_lat);\n                          lp_lon += this->m_proj_parm.pj[z-1]->params().lam0;\n\n                          switch (z) {\n                            case  1: ok = (lp_lon >= -d180-EPSLN && lp_lon <=  -d40+EPSLN) ||\n                                         ((lp_lon >=  -d40-EPSLN && lp_lon <=  -d10+EPSLN) &&\n                                          (lp_lat >=   d60-EPSLN && lp_lat <=   d90+EPSLN)); break;\n                            case  2: ok = (lp_lon >=  -d40-EPSLN && lp_lon <=  d180+EPSLN) ||\n                                         ((lp_lon >= -d180-EPSLN && lp_lon <= -d160+EPSLN) &&\n                                          (lp_lat >=   d50-EPSLN && lp_lat <=   d90+EPSLN)) ||\n                                         ((lp_lon >=  -d50-EPSLN && lp_lon <=  -d40+EPSLN) &&\n                                          (lp_lat >=   d60-EPSLN && lp_lat <=   d90+EPSLN)); break;\n                            case  3: ok = (lp_lon >= -d180-EPSLN && lp_lon <=  -d40+EPSLN); break;\n                            case  4: ok = (lp_lon >=  -d40-EPSLN && lp_lon <=  d180+EPSLN); break;\n                            case  5: ok = (lp_lon >= -d180-EPSLN && lp_lon <= -d100+EPSLN); break;\n                            case  6: ok = (lp_lon >= -d100-EPSLN && lp_lon <=  -d20+EPSLN); break;\n                            case  7: ok = (lp_lon >=  -d20-EPSLN && lp_lon <=   d80+EPSLN); break;\n                            case  8: ok = (lp_lon >=   d80-EPSLN && lp_lon <=  d180+EPSLN); break;\n                            case  9: ok = (lp_lon >= -d180-EPSLN && lp_lon <= -d100+EPSLN); break;\n                            case 10: ok = (lp_lon >= -d100-EPSLN && lp_lon <=  -d20+EPSLN); break;\n                            case 11: ok = (lp_lon >=  -d20-EPSLN && lp_lon <=   d80+EPSLN); break;\n                            case 12: ok = (lp_lon >=   d80-EPSLN && lp_lon <=  d180+EPSLN); break;\n                          }\n\n                          z = (!ok? 0: z); // projectable?\n                        }\n                     // if (!z) pj_errno = -15; // invalid x or y\n                        if (!z) lp_lon = HUGE_VAL;\n                        if (!z) lp_lat = HUGE_VAL;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"igh_spheroid\";\n                }\n\n            };\n\n            // Interrupted Goode Homolosine\n            template <typename CalculationType, typename Parameters>\n            inline void setup_igh(Parameters& par, par_igh<CalculationType, Parameters>& proj_parm)\n            {\n                static const CalculationType d0   =  0;\n                static const CalculationType d4044118 = igh::d4044118<CalculationType>();\n                static const CalculationType d20  =  igh::d20<CalculationType>();\n                static const CalculationType d30  =  igh::d30<CalculationType>();\n                static const CalculationType d60  =  igh::d60<CalculationType>();\n                static const CalculationType d100 = igh::d100<CalculationType>();\n                static const CalculationType d140 = igh::d140<CalculationType>();\n                static const CalculationType d160 = igh::d160<CalculationType>();\n\n            /*\n              Zones:\n\n                -180            -40                       180\n                  +--------------+-------------------------+    Zones 1,2,9,10,11 & 12:\n                  |1             |2                        |      Mollweide projection\n                  |              |                         |\n                  +--------------+-------------------------+    Zones 3,4,5,6,7 & 8:\n                  |3             |4                        |      Sinusoidal projection\n                  |              |                         |\n                0 +-------+------+-+-----------+-----------+\n                  |5      |6       |7          |8          |\n                  |       |        |           |           |\n                  +-------+--------+-----------+-----------+\n                  |9      |10      |11         |12         |\n                  |       |        |           |           |\n                  +-------+--------+-----------+-----------+\n                -180    -100      -20         80          180\n            */\n\n\n                    CalculationType lp_lam = 0, lp_phi = d4044118;\n                    CalculationType xy1_x, xy1_y;\n                    CalculationType xy3_x, xy3_y;\n\n                    // sinusoidal zones\n                    do_setup<sinu_entry>(3, par, proj_parm, -d100, d0, -d100);\n                    do_setup<sinu_entry>(4, par, proj_parm,   d30, d0,   d30);\n                    do_setup<sinu_entry>(5, par, proj_parm, -d160, d0, -d160);\n                    do_setup<sinu_entry>(6, par, proj_parm,  -d60, d0,  -d60);\n                    do_setup<sinu_entry>(7, par, proj_parm,   d20, d0,   d20);\n                    do_setup<sinu_entry>(8, par, proj_parm,  d140, d0,  d140);\n\n                    // mollweide zones\n                    do_setup<moll_entry>(1, par, proj_parm, -d100, d0, -d100);\n\n                    // y0 ?\n                     proj_parm.pj[0]->fwd(lp_lam, lp_phi, xy1_x, xy1_y); // zone 1\n                     proj_parm.pj[2]->fwd(lp_lam, lp_phi, xy3_x, xy3_y); // zone 3\n                    // y0 + xy1_y = xy3_y for lt = 40d44'11.8\"\n                    proj_parm.dy0 = xy3_y - xy1_y;\n\n                    proj_parm.pj[0]->mutable_params().y0 = proj_parm.dy0;\n\n                    // mollweide zones (cont'd)\n                    do_setup<moll_entry>( 2, par, proj_parm,   d30,  proj_parm.dy0,   d30);\n                    do_setup<moll_entry>( 9, par, proj_parm, -d160, -proj_parm.dy0, -d160);\n                    do_setup<moll_entry>(10, par, proj_parm,  -d60, -proj_parm.dy0,  -d60);\n                    do_setup<moll_entry>(11, par, proj_parm,   d20, -proj_parm.dy0,   d20);\n                    do_setup<moll_entry>(12, par, proj_parm,  d140, -proj_parm.dy0,  d140);\n\n                    par.es = 0.;\n            }\n\n    }} // namespace detail::igh\n    #endif // doxygen\n\n    /*!\n        \\brief Interrupted 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_igh.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct igh_spheroid : public detail::igh::base_igh_spheroid<CalculationType, Parameters>\n    {\n        inline igh_spheroid(const Parameters& par) : detail::igh::base_igh_spheroid<CalculationType, Parameters>(par)\n        {\n            detail::igh::setup_igh(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::igh, igh_spheroid, igh_spheroid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class igh_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<igh_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void igh_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"igh\", new igh_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_IGH_HPP\n\n", "meta": {"hexsha": "219f74239e55102a430f2690f4c53221ad3be976", "size": 18797, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/igh.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/igh.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/igh.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": 49.7275132275, "max_line_length": 139, "alphanum_fraction": 0.4994414002, "num_tokens": 4627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.025957359929267797, "lm_q1q2_score": 0.012775904591819999}}
{"text": "/* \n * Copyright (c) 2015-2016, Princeton University, Johannes M Dieterich, Emily A Carter\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 * 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 and/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors may\n * 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\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * 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\n * POSSIBILITY OF SUCH DAMAGE.\n */\n#include <armadillo>\n#ifdef _OPENMP\n#include <fftw3.h>\n#endif\n#include \"GridFactory.hpp\"\n#include \"BasicGridComputer.hpp\"\n#include \"CartesianOOPGrid.hpp\"\n#ifdef LIBKEDF_OCL\n#include <clFFT.h>\n#include \"CartesianOCLOOPGrid.hpp\"\n#endif\n#include <memory>\n#include <stdio.h>\n#include <time.h>\n#include \"Configuration.hpp\"\n#include \"FourierGrid.hpp\"\n#include \"FourierKEDF.hpp\"\n#include \"GridFactory.hpp\"\n#include \"GridFiller.hpp\"\n#include \"KEDF.hpp\"\n#include \"KEDFFactory.hpp\"\n#include \"FourierGrid.hpp\"\n#include \"StressTensor.hpp\"\nusing namespace arma;\nusing namespace std;\n\ntemplate<class GridType>\nvoid runKEDF(const Configuration* config, const KEDF<GridType>* kedf, const GridType* grid){\n    \n    cout << \"Setup complete. Running KEDF \" << kedf->getMethodDescription() << endl;\n    cout << \"Required citations:\" << endl;\n    const vector<string> citations = kedf->getCitations();\n    for(size_t i = 0; i < citations.size(); ++i){\n        cout << \"\" << (i+1) << \") \" << citations[i] << endl;  \n    }\n    \n    cout << endl;\n    cout << \"Working equations:\" << endl; \n    const vector<string> equations = kedf->getWorkingEquations();\n    for(size_t i = 0; i < equations.size(); ++i){\n        cout << equations[i] << endl;\n    }\n    cout << endl;\n    \n    // do whatever operation was asked for and print results\n    const int noIterations = config->getNoIterations();\n    job_types_t jobType = config->getJobType();\n    \n    time_t timerStart;\n    time_t timerEnd;\n    \n    time_t totalTimerStart;\n    time_t totalTimerEnd;\n    \n    time(&totalTimerStart);\n    \n    for(int iter = 0; iter < noIterations; ++iter){\n        \n        time(&timerStart);\n        \n        switch(jobType){\n            case ENERGY:\n            {\n                cout << \"###########################################\" << endl;\n                const double en = kedf->calcEnergy(*grid);\n                time(&timerEnd);\n                cout << \"Iteration \" << iter << endl;\n                cout << \"Energy: \" << en << endl;\n            }\n                break;\n            case POTENTIAL:\n            {\n                unique_ptr<GridType> potential = grid->emptyDuplicate();\n                cout << \"###########################################\" << endl;\n                const double enGrad = kedf->calcPotential(*grid,*potential.get());\n                time(&timerEnd);\n                cout << \"Iteration \" << iter << endl;\n                cout << \"Energy: \" << enGrad << endl;\n                const arma::cube* pot = potential->readRealGrid();\n                if(config->printVerbose()){\n                    pot->print(\"Potential:\");\n                }\n            }\n                break;\n            case STRESS:\n                cout << \"###########################################\" << endl;\n                unique_ptr<StressTensor> stress = kedf->calcStress(*grid);\n                time(&timerEnd);\n                cout << \"Iteration \" << iter << endl;\n                const arma::mat* const tensor = stress->getTensor();\n                tensor->print(\"Stress tensor:\");\n                break;\n        }\n        \n        const double seconds = difftime(timerEnd,timerStart);\n        printf (\"KEDF evaluation took %.f seconds\\n\", seconds);\n        \n    }\n    \n    time(&totalTimerEnd);\n    const double seconds = difftime(totalTimerEnd,totalTimerStart);\n    printf (\"All %d KEDF evaluations combined took %.f seconds\\n\", noIterations, seconds);    \n}\n\nint fillGrid(Grid* grid, const Configuration* config){\n    \n    try{\n        const fillstyle_t fillStyle = config->fillStyle();\n        switch(fillStyle){\n            case ZEROS:\n                GridFiller::fillEmptyGrid(grid);\n                break;\n            case RANDOM:\n                GridFiller::fillGridRandomly(grid);\n                break;\n            case FROMFILE:\n                GridFiller::fillGrid(grid,config->getGridFile());\n                break;\n        }\n        \n    } catch(exception& e){\n        cerr << \"Exception in grid filling: \" << e.what() << endl;\n        return -84;\n    }\n    \n    return  0;\n}\n\nint main(int argc, char** argv) {\n    \n    if(argc < 2){\n        cout << \"ERROR: KEDF client must be called with a config file as the argument\\n\";\n        return 1;\n    }\n    \n    // read the config file\n    Configuration* config = NULL;\n    try{\n        config = new Configuration(argv[1]);\n    } catch(exception& e){\n        cerr << \"Exception in configuration parsing: \" << e.what() << endl;\n        return -21;\n    }\n    \n    // construct the grid object and fill it\n    const size_t xDim = config->getXDim();\n    const size_t yDim = config->getYDim();\n    const size_t zDim = config->getZDim();\n    const shared_ptr<mat> cellVectors = config->getCellVectors();\n    const string gridConfig = config->getGridConfig();\n    const string kedfConfig = config->getKEDFConfig();\n    \n#ifdef _OPENMP\n    fftw_init_threads();\n#endif\n\n    if(gridConfig.compare(\"fftw3,out-of-place\") == 0){\n        CartesianOOPGrid* smpGrid = new CartesianOOPGrid(xDim,yDim,zDim, cellVectors);\n        KEDFFactory<CartesianOOPGrid>* factory = new KEDFFactory<CartesianOOPGrid>();\n        KEDF<CartesianOOPGrid>* smpKEDF;\n        try{\n           smpKEDF = factory->constructKEDF(smpGrid, kedfConfig);\n        } catch (exception e){\n            cout << \"KEDF is not a standard KEDF. Trying Fourier ones...\" << endl;\n            try{\n                smpKEDF = factory->constructFourierKEDF(smpGrid, kedfConfig);\n            } catch(exception e){\n                cerr << \"Also not a Fourier KEDF. Exiting.\" << endl;\n                return -31418;\n            }\n        }\n\n        smpGrid->getGNorms();\n        \n        const int ret = fillGrid(smpGrid, config);\n        if(ret){\n            return ret;\n        }\n        \n        runKEDF(config,smpKEDF,smpGrid);\n    \n        delete smpKEDF;\n        delete smpGrid;\n        \n        return 0;\n#ifdef LIBKEDF_OCL\n    } else if(gridConfig.compare(\"clfft,out-of-place\") == 0){\n        \n        size_t platformNo = 0;\n        size_t deviceNo = 0;\n        \n        clfftSetupData fftSetup;\n        cl_int err;\n        err = clfftInitSetupData(&fftSetup);\n        if(err != CL_SUCCESS){\n            cerr << \"ERROR in setting up setup data for clFFT API setup: \" << err << endl;\n            throw runtime_error(\"ERROR in setting up setup data for clFFT API setup.\");\n        }\n        err = clfftSetup(&fftSetup);\n        if(err != CL_SUCCESS){\n            cerr << \"ERROR in clFFT API setup: \" << err << endl;\n            throw runtime_error(\"ERROR in clFFT API setup.\");\n        }\n        \n        CartesianOCLOOPGrid* oclGrid = (new CartesianOCLOOPGrid(xDim,yDim,zDim, cellVectors, platformNo, deviceNo));\n        \n        KEDFFactory<CartesianOCLOOPGrid>* factory = new KEDFFactory<CartesianOCLOOPGrid>();\n        KEDF<CartesianOCLOOPGrid>* oclKEDF;\n        try{\n           oclKEDF = factory->constructKEDF(oclGrid, kedfConfig);\n        } catch (exception e){\n            cout << \"KEDF is not a standard KEDF. Trying Fourier ones...\" << endl;\n            try{\n                oclKEDF = factory->constructFourierKEDF(oclGrid, kedfConfig);\n            } catch(exception e){\n                cerr << \"Also not a Fourier KEDF. Exiting.\" << endl;\n                return -31418;\n            }\n        }\n\n        oclGrid->getGNorms();\n        \n        const int ret = fillGrid(oclGrid, config);\n        if(ret){\n            return ret;\n        }\n        \n        runKEDF(config,oclKEDF,oclGrid);\n    \n        delete oclKEDF;\n        delete oclGrid;\n\n        clfftTeardown();\n        \n        return 0;\n#endif\n    } else {\n        throw runtime_error(\"Unknown Grid definition \" + gridConfig);\n    }\n}\n", "meta": {"hexsha": "8713380f8d8f28ea0dbea88e604d29be3e2297c0", "size": 9285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "client/MainClient.cpp", "max_stars_repo_name": "EACcodes/libKEDF", "max_stars_repo_head_hexsha": "3dff53318ce7be52be5f45242ea8daf08a032866", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T12:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-29T01:13:25.000Z", "max_issues_repo_path": "client/MainClient.cpp", "max_issues_repo_name": "EACcodes/libKEDF", "max_issues_repo_head_hexsha": "3dff53318ce7be52be5f45242ea8daf08a032866", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client/MainClient.cpp", "max_forks_repo_name": "EACcodes/libKEDF", "max_forks_repo_head_hexsha": "3dff53318ce7be52be5f45242ea8daf08a032866", "max_forks_repo_licenses": ["BSD-3-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.3888888889, "max_line_length": 116, "alphanum_fraction": 0.5847065159, "num_tokens": 2163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881506183194, "lm_q2_score": 0.025957358610626615, "lm_q1q2_score": 0.012775904329500822}}
{"text": "#define _SCL_SECURE_NO_WARNINGS\r\n// Copyright Ingo Proff 2016.\r\n// https://github.com/CrikeeIP/OPTICS-Clustering\r\n// Distributed under the MIT Software License (X11 license).\r\n// (See accompanying file LICENSE)\r\n\r\n\r\n#pragma once\r\n\r\n#ifndef _HAS_AUTO_PTR_ETC\r\n#define _HAS_AUTO_PTR_ETC 1\r\n\r\n#ifndef _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1\r\n#endif\r\n#ifndef _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING\r\n#define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING 1\r\n#endif\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/index/rtree.hpp>\r\n\r\n#undef _HAS_AUTO_PTR_ETC\r\n\r\n#else\r\nstatic_assert(_HAS_AUTO_PTR_ETC, \"_HAS_AUTO_PTR_ETC has to be 1 for boost includes in MSVC_17, but has externally already been set to 0\");\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/index/rtree.hpp>\r\n#endif\r\n\r\n#include \"bgr_image.hpp\"\r\n#include \"tree.hpp\"\r\n#include \"nanoflann.hpp\"\r\n#include \"kdTree.hpp\"\r\n\r\n#include <geometry/geometry.hpp>\r\n#include <fplus/fplus.hpp>\r\n\r\n#include <vector>\r\n#include <exception>\r\n\r\n\r\n\r\nnamespace optics {\r\n\r\n\r\ntypedef std::pair<std::size_t, std::size_t> chi_cluster_indices;\r\ntypedef optics::Tree<chi_cluster_indices> cluster_tree;\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nusing Point = std::array<T, dimension>;\r\n\r\n\r\nstruct reachability_dist {\r\n\treachability_dist( std::size_t point_index_, double reach_dist_ ) : point_index( point_index_ ), reach_dist( reach_dist_ ) {}\r\n\r\n\tstd::string to_string() const{\r\n\t\treturn \"{\" + std::to_string(point_index) + \",\" + std::to_string( reach_dist ) +\"}\";\r\n\t}\r\n\tstd::size_t point_index;\r\n\tdouble reach_dist;\r\n};\r\n\r\ninline bool operator<( const reachability_dist& lhs, const reachability_dist& rhs ) {\r\n\treturn (lhs.reach_dist <= rhs.reach_dist && lhs.reach_dist >= rhs.reach_dist) ? (lhs.point_index < rhs.point_index) : (lhs.reach_dist < rhs.reach_dist);\r\n}\r\ninline bool operator==( const reachability_dist& lhs, const reachability_dist& rhs ) {\r\n\treturn (lhs.reach_dist <= rhs.reach_dist && lhs.reach_dist >= rhs.reach_dist) && (lhs.point_index == rhs.point_index) ;\r\n}\r\ninline std::ostringstream& operator<<( std::ostringstream& stream, const reachability_dist& r ) {\r\n\tstream << r.to_string();\r\n\treturn stream;\r\n}\r\n\r\n\r\nnamespace bg = boost::geometry;\r\nnamespace bgi = boost::geometry::index;\r\n\r\ntemplate<typename T, std::size_t N>\r\nusing Pt = typename bg::model::point<T, N, bg::cs::cartesian>;\r\n\r\ntemplate<typename T, std::size_t N>\r\nusing TreeValue = typename std::pair<Pt<T, N>, std::size_t>;\r\n\r\ntemplate<typename T, std::size_t N>\r\nusing Box = typename bg::model::box<Pt<T, N>>;\r\n\r\ntemplate<typename T, std::size_t N>\r\nusing RTree = typename bgi::rtree<TreeValue<T, N>, bgi::rstar<16>>; //TODO: Number of elems per node configurable?\r\n\r\n\r\n\r\n//recursive set boost coordinates template\r\ntemplate <typename T, size_t N, size_t I>\r\nstruct set_boost_point_coords\r\n{\r\n\tstatic inline int set( Pt<T, N>& boost_pt, const Point<T, N>& coords )\r\n\t{\r\n\t\tbg::set<I>( boost_pt, coords[I] );\r\n\t\treturn set_boost_point_coords<T, N, I - 1>::set( boost_pt, coords );\r\n\t}\r\n};\r\n\r\ntemplate <typename T, size_t N>\r\nstruct set_boost_point_coords<T, N, 0>\r\n{\r\n\tstatic inline int set( Pt<T, N>& boost_pt, const Point<T, N>& coords )\r\n\t{\r\n\t\tbg::set<0>( boost_pt, coords[0] );\r\n\t\treturn 0;\r\n\t}\r\n};\r\n\r\n\r\ntemplate<typename T, std::size_t N>\r\nPt<T, N> geom_to_boost_point( const Point<T, N>& point ) {\r\n\tPt<T, N> boost_point;\r\n\tset_boost_point_coords<T, N, N - 1 >::set( boost_point, point );\r\n\treturn boost_point;\r\n}\r\n\r\n\r\n\r\ntemplate<typename T, std::size_t N>\r\nRTree<T, N> initialize_rtree( const std::vector<Point<T, N>>& points ) {\r\n\t//Insert all points with index into cloud\r\n\tsize_t idx_id = 0;\r\n\tauto cloud = fplus::transform( [&idx_id]( const Point<T, N>& point ) -> TreeValue<T, N> {\r\n\t\treturn{ geom_to_boost_point<T,N>( point ),  idx_id++ };\r\n\t}, points );\r\n\r\n\t//Create an rtree from the cloud using packaging\r\n\tRTree<T, N> rtree( cloud );\r\n\treturn rtree;\r\n}\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\ndouble dist( const Pt<T,dimension>& boost_pt, const Point<T, dimension>& geom_pt ) { //TODO: Speed this up by writing a recursive template for square_dist(boost_pt, geom_pt) like geom::compute_pythagoras\r\n\tconst auto dist = bg::distance( boost_pt, geom_to_boost_point( geom_pt ) );\r\n\treturn dist;\r\n}\r\n\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstruct PointCloud {\r\n\tusing Point = std::array<T, dimension>;\r\n\r\n\tstd::vector<Point> pts;\r\n\r\n\t// Returns the number of data points\r\n\tinline size_t size() const { return pts.size(); }\r\n\tinline size_t kdtree_get_point_count() const { return size(); }\r\n\r\n\t// Returns the squared distance between the vector \"p1[0:size-1]\" and the data point with index \"idx_p2\" stored in the class:\r\n\tinline double kdtree_distance( const T* p1, const size_t idx_p2, size_t /*size*/ ) const {\r\n\t\treturn geom::dist<T,dimension>( *reinterpret_cast<const Point*>(p1), pts[idx_p2] );\r\n\t}\r\n\r\n\t// Returns the dim'th component of the idx'th point in the class:\r\n\t// Since this is inlined and the \"dim\" argument is typically an immediate value, the\r\n\t//  \"if/else's\" are actually solved at compile time.\r\n\tinline T kdtree_get_pt( const size_t idx, int dim ) const {\r\n\t\treturn pts[idx][dim];\r\n\t}\r\n\r\n\t// Optional bounding-box computation: return false to default to a standard bbox computation loop.\r\n\t//   Return true if the BBOX was already computed by the class and returned in \"bb\" so it can be avoided to redo it again.\r\n\t//   Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)\r\n\ttemplate<class BBOX>\r\n\tbool kdtree_get_bbox( BBOX& /*bb*/ ) const { return false; }\r\n\r\n};\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nusing nanoflann_tree = nanoflann::KDTreeSingleIndexAdaptor<\r\n\tnanoflann::L2_Simple_Adaptor<T, PointCloud<T, dimension>>,\r\n\tPointCloud<T, dimension>,\r\n\tdimension>;\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstd::shared_ptr<nanoflann_tree<T, dimension>> create_nanoflann_tree( const PointCloud<T, dimension>& cloud ) {\r\n\tauto index = std::make_shared<nanoflann_tree<T, dimension>>( dimension,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   cloud,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   nanoflann::KDTreeSingleIndexAdaptorParams( 10 ) );\r\n\tindex->buildIndex();\r\n\r\n\treturn index;\r\n}\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstd::vector<std::size_t> find_neighbor_indices_nanoflann(\r\n\tstd::shared_ptr<nanoflann_tree<T, dimension>> index,\r\n\tconst Point<T, dimension>& point,\r\n\tdouble epsilon\r\n){\r\n\tconst double search_radius = epsilon;\r\n\tstd::vector<std::pair<std::size_t, double>> ret_matches;\r\n\r\n\tnanoflann::SearchParams params;\r\n\t//params.sorted = false;\r\n\r\n\tconst size_t nMatches = index->radiusSearch( &point[0], search_radius, ret_matches, params );\r\n\r\n\tstd::vector<std::size_t> result;\r\n\tresult.reserve( nMatches );\r\n\r\n\tfor ( auto const& match : ret_matches ) {\r\n\t\tresult.push_back( match.first );\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\ntemplate<typename T, std::size_t N, std::size_t n_points, std::size_t max_points_per_node>\r\nstd::vector<std::size_t> find_neighbor_indices_kd_tree( const Point<T, N>& point, const double epsilon,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst kdt::KDTree<T, N, n_points, n_points, max_points_per_node, 0, std::true_type>& kdtree ) {\r\n\treturn kdtree.radius_search(point, epsilon);\r\n}\r\n\r\ntemplate<typename T, std::size_t N>\r\nstd::vector<std::size_t> find_neighbor_indices_rtree( const Point<T, N>& point, const double epsilon, const RTree<T, N>& rtree ) {\r\n\tstatic_assert( std::is_signed<T>::value, \"Type not allowed. Only Integers, Float & Double supported\" );\r\n\tassert( epsilon > 0 );\r\n\t//produce search box\r\n\tPoint<double, N> point_d = fplus::convert_elems<double>( point );\r\n\tPoint<double, N> corner1; Point<double, N> corner2;\r\n\tfor ( std::size_t i = 0; i < N; i++ ) {\r\n\t\tcorner1[i] = point_d[i] - epsilon;\r\n\t\tcorner2[i] = point_d[i] + epsilon;\r\n\t}\r\n\t\r\n\tBox<double, N> query_box( geom_to_boost_point( corner1 ), geom_to_boost_point( corner2 ) );\r\n\r\n\t//search neighbors in box (manhattan dist 2*epsilon)\r\n\tstd::vector<TreeValue<T, N>> neighbors;\r\n\tneighbors.reserve( 100 );\r\n\trtree.query( bgi::intersects( query_box ), std::back_inserter( neighbors ) );\r\n\t//rtree.query( bgi::nearest( geom_to_boost_point(point), min_pts ), std::back_inserter( neighbors ) );\r\n\t/*\r\n\t//Custom intersects method\r\n\trtree.query(\r\n\t\tbgi::satisfies( [&corner1, &corner2]( const TreeValue<T, N>& v ) {\r\n\t\t\tPt<T,N> pt = v.first;\r\n\t\t\treturn ( corner1[0] < pt.get<0>() &&\r\n\t\t\t\t\t corner1[1] < pt.get<1>() &&\r\n\t\t\t\t\t corner2[0] > pt.get<0>() &&\r\n\t\t\t\t\t corner2[1] > pt.get<1>()\r\n\t\t\t\t\t);\r\n\t\t}),\r\n\t\tstd::back_inserter( neighbors )\r\n\t);\r\n\r\n\tstd::vector<TreeValue<T, N>> neighbors2;\r\n\tneighbors2.reserve( 100 );\r\n\trtree.query( bgi::intersects( query_box ), std::back_inserter( neighbors2 ) );\r\n\tassert( neighbors == neighbors2 ); //TODO: DEBUG raus\r\n\tneighbors = neighbors2;\r\n\t*/\r\n\r\n\t//keep those with euclidean dist < epsilon\r\n\tstd::vector<std::size_t> neighbor_indices;\r\n\tneighbor_indices.reserve( neighbors.size() );\r\n\tfor ( const auto& n : neighbors ) {\r\n\t\tif ( dist<T, N>( n.first, point ) <= epsilon ) {\r\n\t\t\tneighbor_indices.push_back( n.second );\r\n\t\t}\r\n\t}\r\n\t/*auto neighbor_indices = fplus::transform_and_keep_justs( [&point, &epsilon]( const TreeValue<T, N>& tree_val ) ->  fplus::maybe<std::size_t> {\r\n\t\tif ( dist<T,N>( tree_val.first, point ) > epsilon ) {\r\n\t\t\treturn {};\r\n\t\t}\r\n\t\treturn tree_val.second;\r\n\t}, neighbors );\r\n\t*/\r\n\treturn neighbor_indices;\r\n}\r\n\r\n\r\ntemplate<typename T, std::size_t N>\r\nfplus::maybe<double> compute_core_dist( const Point<T, N>& point,\r\n\t\t\t\t\t\t\t\t\t\tconst std::vector<Point<T,N>>& points,\r\n\t\t\t\t\t\t\t\t\t\tconst std::vector<std::size_t>& neighbor_indices,\r\n\t\t\t\t\t\t\t\t\t\tconst std::size_t min_pts ) \r\n{\r\n\tif ( neighbor_indices.size() < min_pts ) { return{}; }\r\n\r\n\tauto core_elem_idx = fplus::nth_element_on( [&points, &point]( const std::size_t& idx ) -> double {\r\n\t\treturn geom::square_dist<T,N>( point, points[idx] );\r\n\t}, min_pts-1, neighbor_indices );\r\n\tdouble core_dist = geom::dist<T, N>( points[core_elem_idx], point );\r\n\treturn core_dist;\r\n}\r\n\r\n\r\ninline void erase_idx_from_set( const reachability_dist& d, std::set<reachability_dist>& seeds ) {\r\n\tauto x = seeds.erase( d );\r\n\tassert( x == 1 );\r\n}\r\n\r\ntemplate<typename T>\r\nT pop_from_set( std::set<T>& set ) {\r\n\tT element = *set.begin();\r\n\tset.erase( set.begin() );\r\n\treturn element;\r\n}\r\n\r\n\r\ntemplate<typename T, std::size_t N>\r\nvoid update( const Point<T, N>& point, const std::vector<Point<T, N>>& points, const std::vector<std::size_t>& neighbor_indices, const double core_dist,\r\n\t\t\t\tconst std::vector<bool>& processed, std::vector<double>& reachability, std::set<reachability_dist>& seeds\r\n\t\t\t)\r\n{\r\n\tfor ( const auto& o : neighbor_indices ) {\r\n\t\tif ( processed[o] ) { continue; }\r\n\t\tdouble new_reachability_dist = fplus::max( core_dist, geom::dist<T,N>( point, points[o] ) );\r\n\t\tif ( reachability[o] < 0.0 ) {\r\n\t\t\treachability[o] = new_reachability_dist;\r\n\t\t\tseeds.insert( reachability_dist( o, new_reachability_dist ) );\r\n\t\t}\r\n\r\n\t\telse if ( new_reachability_dist < reachability[o] ) {\r\n\t\t\t//erase from seeds\r\n\t\t\terase_idx_from_set( reachability_dist( o, reachability[o]), seeds );\r\n\t\t\t//update reachability\r\n\t\t\treachability[o] = new_reachability_dist;\r\n\t\t\t//re-insert seed with new reachability\r\n\t\t\tseeds.insert( reachability_dist( o, new_reachability_dist ) );\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstd::pair<Point<T, dimension>, Point<T, dimension>> bounding_box( const std::vector<Point<T, dimension>>& points ) {\r\n\tassert( points.size() > 0 ); //Bounding Box of 0 points not defined\r\n\tstatic_assert(std::is_convertible<T, double>::value, \"bounding_box(): bounding_box can only be computed for point types which can be converted to double!\");\r\n\r\n\tstd::array<T, dimension> min( points[0] );\r\n\tstd::array<T, dimension> max( points[1] );\r\n\r\n\tfor ( const auto& p : points ) {\r\n\t\tfor ( std::size_t i = 0; i < dimension; i++ ) {\r\n\t\t\tif ( p[i] < min[i] ) min[i] = p[i];\r\n\t\t\tif ( p[i] > max[i] ) max[i] = p[i];\r\n\t\t}\r\n\t}\r\n\r\n\treturn{ {min},{ max } };\r\n}\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\ndouble hypercuboid_voulume( const Point<T, dimension>& bl, const Point <T, dimension>& tr ) {\r\n\tdouble volume = 1;\r\n\tfor ( std::size_t i = 0; i < dimension; i++ ) {\r\n\t\tvolume *= std::abs( static_cast<double>(tr[i] - bl[i]) );\r\n\t}\r\n\treturn volume;\r\n}\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\ndouble epsilon_estimation( const std::vector<Point<T, dimension>>& points, const std::size_t min_pts ){\r\n\tstatic_assert(std::is_convertible<double, T>::value, \"optics::epsilon_estimation: Point type 'T' must be convertible to double!\");\r\n\tstatic_assert(dimension >= 1, \"optics::epsilon_estimation: dimension must be >=1\");\r\n\tif ( points.size() <= 1 ) { return 0; }\r\n\r\n\tdouble d = static_cast<double> (dimension);\r\n\tauto  space = bounding_box( points );\r\n\tdouble space_volume = hypercuboid_voulume( space.first, space.second );\r\n\t\r\n\tdouble space_per_minpts_points = (space_volume / static_cast<double>(points.size())) * static_cast<double>(min_pts);\r\n\tdouble n_dim_unit_ball_vol = std::sqrt( std::pow( geom::pi, d ) ) / std::tgamma( d / 2.0 + 1.0 );\r\n\tdouble r = std::pow( space_per_minpts_points / n_dim_unit_ball_vol, 1.0/d );\r\n\t\r\n\t//double nominator = space_volume * static_cast<double>(min_pts) * std::tgamma( d/2.0 + 1.0 );\r\n\t//double denominator = static_cast<double>(points.size()) * std::sqrt( std::pow( geom::pi, d ) );\r\n\t//double r = std::pow( nominator / denominator, 1.0 / d );\r\n\treturn r;\r\n}\r\n\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nPointCloud<T, dimension> toPointCloud( const std::vector<Point<T, dimension>>& points ) {\r\n\tstatic_assert(std::is_signed<T>::value, \"Type not allowed. Only Integers, Float & Double supported\");\r\n\tstatic_assert(std::is_convertible<double, T>::value,\r\n\t\t\t\t   \"optics::compute_reachability_dists: Point type 'T' must be convertible to double!\");\r\n\tstatic_assert(dimension >= 1, \"optics::compute_reachability_dists: dimension must be >=1\");\r\n\tif ( points.empty() ) { return {}; }\r\n\r\n\tPointCloud<T, dimension> cloud;\r\n\tcloud.pts.reserve( points.size() );\r\n\tfor ( const auto& p : points ) {\r\n\t\tcloud.pts.push_back( p );\r\n\t}\r\n\r\n\treturn cloud;\r\n}\r\n\r\n\r\nenum RadiusSearchMethod { NANOFLANN, KDTREE, BOOSTRSTAR };\r\nstatic const RadiusSearchMethod method = KDTREE;\r\n\r\n\r\ntemplate<std::size_t n_points, typename T, std::size_t dimension, std::size_t n_threads = 1>\r\nstd::vector<reachability_dist> compute_reachability_dists( const std::vector<std::array<T, dimension>>& points, std::size_t min_pts, double epsilon = -1.0 ) {\r\n\t\r\n\tstatic_assert(n_threads >= 1, \"Number of threads must be >= 1\");\r\n\tstatic_assert(std::is_signed<T>::value, \"Type not allowed. Only Integers, Float & Double supported\");\r\n\tstatic_assert(std::is_convertible<T,double>::value, \"Point type 'T' must be convertible to double!\" );\r\n\tstatic_assert( dimension >= 1, \"dimension must be >=1\");\r\n\tstatic_assert(n_points >= 2, \"Number of points to cluster must be >= 2\");\r\n\t\r\n\tif ( points.size() != n_points ) {\r\n\t\tstd::cerr << \"Error: provided vector of points does not have expected length n_points\";\r\n\t\tstd::exit(1); //points.size() must be == n_points for the kdTree\r\n\t}\r\n\tif ( points.empty() ) { return{}; }\r\n\r\n\tif ( epsilon <= 0.0 ) {\r\n\t\tepsilon = epsilon_estimation( points, min_pts );\r\n\t}\r\n\tassert( epsilon > 0 );\r\n\r\n\t//algorithm tracker\r\n\tstd::vector<bool> processed( points.size(), false );\r\n\tstd::vector<std::size_t> ordered_list;\r\n\tordered_list.reserve( points.size() );\r\n\tstd::vector<double> reachability( points.size(), -1.0f );\r\n\t\r\n   \r\n\r\n\tstd::vector<std::vector<std::size_t>> neighbors;\r\n\tswitch(method){\r\n\tcase NANOFLANN:\r\n\t{\r\n\t\tstd::cout << \"RadiusSearchMethod: Nanoflann\" << std::endl;\r\n\t\tconst PointCloud<T, dimension> cloud = toPointCloud( points );\r\n\t\tauto index = create_nanoflann_tree<T, dimension>( cloud );\r\n\r\n\t\tif ( n_threads == 1 ) {\r\n\t\t\tneighbors = fplus::transform(\r\n\t\t\t\t[&index, epsilon]( const Point<T, dimension>& point ) -> std::vector<std::size_t>\r\n\t\t\t{ return find_neighbor_indices_nanoflann<T, dimension>( index, point, epsilon ); },\r\n\t\t\t\tpoints\r\n\t\t\t);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tneighbors =\r\n\t\t\t\tfplus::transform_parallelly_n_threads(\r\n\t\t\t\t\tn_threads,\r\n\t\t\t\t\t[&index, epsilon]( const Point<T, dimension>& point ) -> std::vector<std::size_t>\r\n\t\t\t{ return find_neighbor_indices_nanoflann<T, dimension>( index, point, epsilon ); },\r\n\t\t\t\t\tpoints\r\n\t\t\t\t);\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tcase BOOSTRSTAR :\r\n\t{\r\n\t\tstd::cout << \"RadiusSearchMethod: Boost Rstar\" << std::endl;\r\n\t\tconst auto rtree = initialize_rtree( points );\r\n\r\n\t\t//Compute all neighbors parallely beforehand\r\n\r\n\t\tif ( n_threads == 1 ) {\r\n\t\t\tneighbors = fplus::transform(\r\n\t\t\t\t[&rtree, epsilon]( const Point<T, dimension>& point ) -> std::vector<std::size_t>\r\n\t\t\t{ return find_neighbor_indices_rtree( point, epsilon, rtree ); },\r\n\t\t\t\tpoints\r\n\t\t\t);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tneighbors =\r\n\t\t\t\tfplus::transform_parallelly_n_threads(\r\n\t\t\t\t\tn_threads,\r\n\t\t\t\t\t[&rtree, epsilon]( const Point<T, dimension>& point ) -> std::vector<std::size_t>\r\n\t\t\t{ return find_neighbor_indices_rtree( point, epsilon, rtree ); },\r\n\t\t\t\t\tpoints\r\n\t\t\t\t);\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tcase KDTREE:\r\n\t{\r\n\t\tstd::cout << \"RadiusSearchMethod: MyKDTree\" << std::endl;\r\n\t\tconstexpr std::size_t min_points_per_node = 8;//TODO: configurable? Optimum?\r\n\t\tconst auto kd_tree = kdt::make_KDTree<T, dimension, n_points, min_points_per_node>( points );\r\n\r\n\t\tif ( n_threads == 1 ) {\r\n\t\t\tneighbors = fplus::transform(\r\n\t\t\t\t[&kd_tree, epsilon]( const Point<T, dimension>& point ) -> std::vector<std::size_t>\r\n\t\t\t{ return find_neighbor_indices_kd_tree( point, epsilon, *kd_tree );\r\n\t\t\t}, points\r\n\t\t\t);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tneighbors =\r\n\t\t\t\tfplus::transform_parallelly_n_threads(\r\n\t\t\t\t\tn_threads,\r\n\t\t\t\t\t[&kd_tree, epsilon]( const Point<T, dimension>& point ) -> std::vector<std::size_t>\r\n\t\t\t{ return find_neighbor_indices_kd_tree( point, epsilon, *kd_tree );\r\n\t\t\t},\r\n\t\t\t\t\tpoints\r\n\t\t\t\t);\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tdefault:\r\n\t\tstd::cerr << \"RadiusSearchMethod \" << method << \" not implemented!\" << std::endl;\r\n\t\tstd::exit( 11 );\r\n\t}\r\n\r\n\tassert( neighbors.size() == points.size() );\r\n\r\n\r\n\tfor ( std::size_t point_idx = 0; point_idx < points.size(); point_idx++ ) {\r\n\t\tif ( processed[point_idx] == true ) continue;\r\n\t\tprocessed[point_idx] = true;\r\n\t\tordered_list.push_back( point_idx );\r\n\t\tstd::set<reachability_dist> seeds;\r\n\r\n\t\tauto neighbor_indices = neighbors[point_idx];\r\n\t\t//auto neighbor_indices = find_neighbor_indices( points[point_idx], epsilon, rtree );\r\n\r\n\t\tfplus::maybe<double> core_dist_m = compute_core_dist( points[point_idx], points, neighbor_indices, min_pts );\r\n\t\tif ( !core_dist_m.is_just() ) { continue; }\r\n\t\tdouble core_dist = core_dist_m.unsafe_get_just();\r\n\r\n\t\tupdate( points[point_idx], points, neighbor_indices, core_dist, processed, reachability, seeds );\r\n\t\twhile ( !seeds.empty() ) {\r\n\t\t\treachability_dist s = pop_from_set( seeds );\r\n\t\t\tassert( processed[s.point_index] == false );\r\n\t\t\tprocessed[s.point_index] = true;\r\n\t\t\tordered_list.push_back( s.point_index );\r\n\r\n\t\t\tauto s_neighbor_indices = neighbors[s.point_index];\r\n\t\t\t//auto s_neighbor_indices = find_neighbor_indices( points[s.point_index], epsilon, rtree );\r\n\t\t\t\r\n\t\t\tauto s_core_dist_m = compute_core_dist( points[s.point_index], points, s_neighbor_indices, min_pts );\r\n\t\t\tif ( !s_core_dist_m.is_just() ) { continue; }\r\n\t\t\tdouble s_core_dist = s_core_dist_m.unsafe_get_just();\r\n\r\n\t\t\tupdate( points[s.point_index], points, s_neighbor_indices, s_core_dist, processed, reachability, seeds );\r\n\t\t}\r\n\r\n\t}\r\n\t//sanity checks\r\n\tassert( ordered_list.size() == points.size() );\r\n\tassert( fplus::all_unique( ordered_list ) );\r\n\r\n\t//merge reachabilities into ordered list\r\n\tauto result = fplus::transform( [&reachability]( std::size_t point_idx ) -> reachability_dist {\r\n\t\treturn reachability_dist( point_idx, reachability[point_idx] );\r\n\t}, ordered_list );\r\n\treturn result;\r\n}\r\n\r\n\r\n\r\n/*\r\ntemplate<typename T, std::size_t dimension, std::size_t n_threads = 1>\r\nstd::vector<reachability_dist> compute_reachability_dists( const std::vector<std::array<T, dimension>>& points, const std::size_t min_pts, double epsilon = 0.0 ) {\r\n\tstatic_assert(std::is_signed<T>::value, \"Type not allowed. Only Integers, Float & Double supported\");\r\n\tstatic_assert(std::is_convertible<double, T>::value, \"optics::compute_reachability_dists: Point type 'T' must be convertible to double!\");\r\n\tstatic_assert(dimension >= 1, \"optics::compute_reachability_dists: dimension must be >=1\");\r\n\tif ( points.empty() ) { return{}; }\r\n\r\n\tstd::vector<geom::Vec<T, dimension>> geom_points;\r\n\tgeom_points.reserve( points.size() );\r\n\tfor ( const auto& p : points ) {\r\n\t\tgeom_points.push_back( geom::Vec<T, dimension>( p ) );\r\n\t}\r\n\r\n\treturn compute_reachability_dists<T, dimension, n_threads>( geom_points, min_pts, epsilon );\r\n}\r\n*/\r\n\r\n\r\n/**Exports a list of reachability distances into a csv file.\r\n* If switch replace_nodists is set (as by default), points that haven't been assigned a reachability distance will be set to the maximum reachability distance + 1.\r\n* Otherwise, points that haven't been assigned a reachability distance at all will appear with reachability distance -1.0.\r\n*/\r\ninline void export_reachability_dists( const std::vector<reachability_dist>& reach_dists, const std::string& csv_file_path, bool replace_nodists = true ) {\r\n\t//open filestream\r\n\tstd::ofstream stream;\r\n\tstream.open( csv_file_path, std::ios::binary );\r\n\tif ( !stream.is_open() ) {\r\n\t\tstd::cout << \"export_reachability_dists(): Stream to file \\\"\" + csv_file_path + \"\\\" could not be opened!\";\r\n\t\treturn;\r\n\t}\r\n\r\n\tdouble no_dist = -1;\r\n\tif ( replace_nodists ) {\r\n\t\tno_dist = fplus::maximum_on( []( const reachability_dist& r ) -> double {\r\n\t\t\treturn r.reach_dist;\r\n\t\t}, reach_dists ).reach_dist;\r\n\t\tno_dist += 1;\r\n\t}\r\n\r\n\t//write csv header\r\n\tstream << \"PointIndex;ReachabilityDistance\" << std::endl;\r\n\t//write body\r\n\tfor ( const auto& x : reach_dists ) {\r\n\t\tstream << x.point_index << \";\" << (x.reach_dist < 0 ? no_dist : x.reach_dist) << std::endl;\r\n\t}\r\n}\r\n\r\n\r\ninline bgr_image draw_reachability_plot( const std::vector<reachability_dist>& reach_dists, std::size_t min_width = 100 ) {\r\n\tif ( reach_dists.size() < 2 ) return bgr_image(size_2d(0,0));\r\n\tbgr_image image( size_2d( std::max( reach_dists.size(), min_width ), 256 ), bgr_col(255,255,255) );\r\n\r\n\tauto reach_dists_values = fplus::transform( []( const reachability_dist& r )-> double {\r\n\t\treturn r.reach_dist;\r\n\t}, reach_dists );\r\n\r\n\t//Normalize the data\r\n\tdouble max_val = fplus::maximum( reach_dists_values );\r\n\treach_dists_values.push_back( max_val + fplus::max( 30, max_val / 3 ) );//The future no_dist for points which weren't assigned any reachability dist. Has to be at least 30, and scale with max_val. Will be normalized to 256-64\r\n\treach_dists_values.push_back( 10.0 );//In order to see where 10.0 was mapped after the normalization\r\n\treach_dists_values.push_back( -1.0 );//In order to have at least one no dist\r\n\treach_dists_values = fplus::normalize_min_max( -1.0, 256.0 - 64.0, reach_dists_values );\r\n\treach_dists_values.pop_back();\r\n\t//Extract normalized 10.0:\r\n\tdouble ten = reach_dists_values.back();\r\n\treach_dists_values.pop_back();\r\n\t//Extract no_dist:\r\n\tint no_dist = fplus::min( 255, fplus::round(reach_dists_values.back()));\r\n\treach_dists_values.pop_back();\r\n\r\n\t//Drawing the graph\r\n\tfor ( int i = 0; i < static_cast<int>(reach_dists.size())-1; i++ ) {\r\n\t\tint x1 = fplus::round( (image.size().width_-1) * i/ static_cast<double>((reach_dists_values.size()-1)) );\r\n\t\tint y1 = static_cast<int>(image.size().height_) -1 - (reach_dists_values[i] < 0 ? no_dist : fplus::round( reach_dists_values[i]));\r\n\t\tint x2 = fplus::round( (static_cast<double>(image.size().width_)-1) * (i+1)/static_cast<double>((reach_dists_values.size()-1)) );\r\n\t\tint y2 = static_cast<int>(image.size().height_) -1 - (reach_dists_values[i+1] < 0 ? no_dist : fplus::round( reach_dists_values[i+1]));\r\n\t\tplot_line_segment( image, img_pos(x1, y1), img_pos(x2, y2), bgr_col(30,30,30) );\r\n\t\tbgr_col col = reach_dists_values[i] < 0 ? bgr_col(0, 0, 255) : bgr_col(0, 255, 0);\r\n\t\tplot_pixel( image, img_pos( x1, y1 ), col );\r\n\t\tcol = reach_dists_values[i+1] < 0 ? bgr_col( 0, 0, 255 ) : bgr_col( 0, 255, 0 );\r\n\t\tplot_pixel( image, img_pos( x2, y2 ), col );\r\n\t}\r\n\r\n\t//Fill area under the graph\r\n\tbgr_col fill_col( 177, 177, 177 );\r\n\tfor ( std::size_t x = 0; x < image.size().width_; x++ ) {\r\n\t\tint y = static_cast<int>(image.size().height_)-1;\r\n\t\twhile ( y >= 0 && image.pix( img_pos( x, y ) ) == bgr_col( 255, 255, 255 ) ) {\r\n\t\t\timage.pix( img_pos( x, y ) ) = fill_col;\r\n\t\t\ty--;\r\n\t\t}\r\n\t}\r\n\r\n\t//Draw Scale\r\n\tint x2 = fplus::round( image.size().width_ / static_cast<double>((reach_dists.size() - 1)) );\r\n\tplot_line_segment( image, img_pos( 0, image.size().height_ - 1 ), img_pos( x2, image.size().height_ - 1 ), bgr_col(0,255,0) ); //One point\r\n\tplot_line_segment( image, img_pos( 0, image.size().height_ - 1 ), img_pos( 0, image.size().height_ - 1 - fplus::round<double,std::size_t>( ten ) ), bgr_col( 255, 0, 0 ) ); //ReachDist 1\r\n\tint no_dist_marker = fplus::min( static_cast<int>(image.size().height_ -1), fplus::round( fplus::maximum( reach_dists_values ) + 10.0 ));\r\n\tplot_line_segment( image, img_pos( 0, image.size().height_ - 1 - no_dist_marker ), img_pos( image.size().width_/3, image.size().height_ - 1 - no_dist_marker ), bgr_col( 0, 0, 255 ) ); //ReachDist 1\r\n\r\n\treturn image;\r\n}\r\n\r\n\r\ninline std::vector<std::vector<std::size_t>> get_cluster_indices( const std::vector<reachability_dist>& reach_dists, double reachability_threshold, const std::string& reachability_plot_image_path = \"\") {\r\n\tassert( reach_dists.front().reach_dist < 0.0 );\r\n\tstd::vector<std::vector<std::size_t>> result;\r\n\tfor ( const auto& r : reach_dists ) {\r\n\t\tif ( r.reach_dist < 0.0 || r.reach_dist >= reachability_threshold ) {\r\n\t\t\tresult.push_back( { r.point_index } );\r\n\t\t}\r\n\t\telse {\r\n\t\t\tresult.back().push_back( r.point_index );\r\n\t\t}\r\n\t}\r\n\tif( reachability_plot_image_path!= \"\"){\r\n\t\tauto img = draw_reachability_plot( reach_dists);\r\n\t\timg.save( reachability_plot_image_path );\r\n\t}\r\n\treturn result;\r\n}\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstd::vector<std::vector<std::array<T, dimension>>> get_cluster_points(\r\n\t\t\tconst std::vector<reachability_dist>& reach_dists,\r\n\t\t\tdouble reachability_threshold,\r\n\t\t\tconst std::vector<std::array<T, dimension>>& points,\r\n\t\t\tconst std::string& reachability_plot_image_path = \"\" )\r\n{\r\n\tconst auto sorted_reachdist_indices =\r\n\t\tfplus::unique(\r\n\t\t\tfplus::sort_on(\r\n\t\t\t\t[]( const reachability_dist& r )->std::size_t { return r.point_index; },\r\n\t\t\t\treach_dists\r\n\t\t\t)\r\n\t\t);\r\n\tassert( sorted_reachdist_indices.size() == points.size() );\r\n\tassert( sorted_reachdist_indices.back().point_index == points.size() - 1 );\r\n\r\n\tauto clusters = get_cluster_indices( reach_dists, reachability_threshold );\r\n\tstd::vector<std::vector<std::array<T, dimension>>> result;\r\n\tresult.reserve( clusters.size() );\r\n\tfor ( const auto& cluster_indices : clusters ) {\r\n\t\tresult.push_back( fplus::elems_at_idxs( cluster_indices, points ) );\r\n\t}\r\n\r\n\tif( reachability_plot_image_path!= \"\"){\r\n\t\tauto img = draw_reachability_plot( reach_dists);\r\n\t\timg.save( reachability_plot_image_path );\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n\r\ninline std::vector<std::vector<std::size_t>> get_cluster_indices(\r\n\tconst std::vector<reachability_dist>& reach_dists,\r\n\tconst std::vector<chi_cluster_indices>& clusters )\r\n{\r\n\tstd::vector<std::vector<std::size_t>> result;\r\n\tresult.reserve( clusters.size() );\r\n\tfor ( const auto& c : clusters ) {\r\n\t\tresult.push_back( {} );\r\n\t\tresult.back().reserve( c.second - c.first + 1 );\r\n\t\tfor ( std::size_t idx = c.first; idx <= c.second; idx++ ) {\r\n\t\t\tconst auto& r = reach_dists[idx];\r\n\t\t\tresult.back().push_back( r.point_index );\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstd::vector<std::vector<geom::Vec<T, dimension>>> get_cluster_points(\r\n\tconst std::vector<reachability_dist>& reach_dists,\r\n\tconst std::vector<chi_cluster_indices>& clusters,\r\n\tconst std::vector<geom::Vec<T, dimension>>& points)\r\n{\r\n\tauto clusters_indices = get_cluster_indices( reach_dists, clusters );\r\n\r\n\tstd::vector<geom::Vec<T, dimension>> result;\r\n\tresult.reserve( clusters_indices.size() );\r\n\tfor ( const auto& cluster_indices : clusters ) {\r\n\t\tresult.push_back( fplus::elems_at_idxs( cluster_indices, points ) );\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstd::vector<std::vector<std::array<T, dimension>>> get_cluster_points(\r\n\tconst std::vector<reachability_dist>& reach_dists,\r\n\tconst std::vector<chi_cluster_indices>& clusters,\r\n\tconst std::vector<std::array<T, dimension>>& points\r\n\t)\r\n{\r\n\tauto clusters_indices = get_cluster_indices( reach_dists, clusters );\r\n\tstd::vector<std::vector<std::array<T, dimension>>> result;\r\n\tresult.reserve( clusters_indices.size() );\r\n\tfor ( const auto& cluster_indices : clusters_indices ) {\r\n\t\tresult.push_back( fplus::elems_at_idxs( cluster_indices, points ) );\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n\r\n\r\ntemplate<typename T, std::size_t dimension>\r\nstd::vector<std::vector<geom::Vec<T, dimension>>> get_cluster_points(\r\n\t\tconst std::vector<reachability_dist>& reach_dists,\r\n\t\tdouble reachability_threshold,\r\n\t\tconst std::vector<geom::Vec<T, dimension>>& points ,\r\n\t\tconst std::string& reachability_plot_image_path = \"\" )\r\n{\r\n\tconst auto sorted_reachdists = fplus::unique( fplus::sort( reach_dists ) );//TODO: Debug raus\r\n\tassert( sorted_reachdists.size() == points.size() );\r\n\tassert( sorted_reachdists.back() == points.size() - 1 );\r\n\r\n\tauto clusters = get_cluster_indices( reach_dists, reachability_threshold );\r\n\tstd::vector<geom::Vec<T, dimension>> result;\r\n\tresult.reserve( clusters.size() );\r\n\tfor ( const auto& cluster_indices : clusters ) {\r\n\t\tresult.push_back( fplus::elems_at_idxs( cluster_indices, points ) );\r\n\t}\r\n\tif( reachability_plot_image_path!= \"\"){\r\n\t\tauto img = draw_reachability_plot( reach_dists );\r\n\t\timg.save( reachability_plot_image_path );\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n\r\nstruct SDA{\r\n\tSDA( std::size_t begin_idx_, std::size_t end_idx_, double mib_) : begin_idx(begin_idx_), end_idx(end_idx_), mib(mib_){}\r\n\tstd::size_t begin_idx;\r\n\tstd::size_t end_idx;\r\n\tdouble mib;\r\n};\r\n\r\n\r\n\r\n\r\n\r\ninline std::vector<chi_cluster_indices> get_chi_clusters_flat( const std::vector<reachability_dist>& reach_dists_, const double chi, std::size_t min_pts, double steep_area_min_diff = 0.0 ){\r\n\tstd::vector<std::pair<std::size_t, std::size_t>> clusters;\r\n\tstd::vector<SDA> SDAs;\r\n\tconst std::size_t n_reachdists = reach_dists_.size();\r\n\tdouble mib(0);\r\n\tdouble max_reach(0.0);\r\n\tfor( const auto& r :reach_dists_ ){ if( r.reach_dist > max_reach ) max_reach = r.reach_dist; }\r\n\r\n\r\n\tconst auto get_reach_dist = [&reach_dists_, &max_reach](const std::size_t idx) -> double{\r\n\t\tassert( idx <= reach_dists_.size() );\r\n\t\tif( idx == reach_dists_.size() ) return max_reach;\r\n\t\tif( idx == 0 ) return max_reach;\r\n\t\tconst auto r = reach_dists_[idx].reach_dist;\r\n\t\treturn ((r<0) ? 2*max_reach : r);\r\n\t};\r\n\tconst auto is_steep_down_pt = [&get_reach_dist, &n_reachdists, &chi](std::size_t idx ){\r\n\t\tif( idx == 0 ) return true;\r\n\t\tif( idx+1 >= n_reachdists ) return false;\r\n\t\treturn get_reach_dist(idx+1) <= get_reach_dist(idx) * (1-chi);\r\n\t};\r\n\tconst auto is_steep_up_pt = [&get_reach_dist, &n_reachdists, &chi](std::size_t idx ){\r\n\t\tif( idx+1 >= n_reachdists ) return true;\r\n\t\treturn get_reach_dist(idx+1) * (1-chi) >= get_reach_dist(idx);\r\n\t};\r\n\tconst auto filter_sdas = [&chi, &steep_area_min_diff, &SDAs, &mib, &get_reach_dist](){\r\n\t\tSDAs = fplus::keep_if( [&mib, &chi, &steep_area_min_diff, &get_reach_dist](const SDA& sda)->bool{\r\n\t\t\t\t\tconst double f = fplus::max( chi, steep_area_min_diff );\r\n\t\t\t\t\treturn mib <= get_reach_dist(sda.begin_idx) * (1-f);\r\n\t\t\t}, SDAs);\r\n\t\tfor ( auto& sda : SDAs ) {\r\n\t\t\tsda.mib = std::max( sda.mib, mib );\r\n\t\t}\r\n\t};\r\n\tconst auto get_sda_end = [&chi, &n_reachdists, &get_reach_dist, &min_pts, &is_steep_down_pt]( const std::size_t start_idx ) -> std::size_t{\r\n\t\tassert( is_steep_down_pt(start_idx) );\r\n\t\tstd::size_t last_sd_idx = start_idx;\r\n\t\tstd::size_t idx = start_idx +1;\r\n\t\twhile( idx < n_reachdists ){\r\n\t\t\tif( idx - last_sd_idx >= min_pts){ return last_sd_idx; }\r\n\t\t\tif( get_reach_dist(idx) > get_reach_dist(idx-1) ){ return last_sd_idx; }\r\n\t\t\tif( is_steep_down_pt(idx) ){ last_sd_idx = idx; }\r\n\t\t\tidx++;\r\n\t\t}\r\n\t\treturn std::max( n_reachdists - 2, last_sd_idx);\r\n\t};\r\n\tconst auto get_sua_end = [&chi, &n_reachdists, &get_reach_dist, &min_pts, &is_steep_up_pt]( const std::size_t start_idx ) -> std::size_t {\r\n\t\tassert( is_steep_up_pt( start_idx ) );\r\n\t\tstd::size_t last_su_idx = start_idx;\r\n\t\tstd::size_t idx = start_idx + 1;\r\n\t\twhile ( idx < n_reachdists ) {\r\n\t\t\tif ( idx - last_su_idx >= min_pts ) { return last_su_idx; }\r\n\t\t\tif ( get_reach_dist(idx) < get_reach_dist(idx-1) ) { return last_su_idx; }\r\n\t\t\tif ( is_steep_up_pt( idx ) ) { last_su_idx = idx; }\r\n\t\t\tidx++;\r\n\t\t}\r\n\t\treturn std::max( n_reachdists - 2, last_su_idx );\r\n\t};\r\n\tconst auto cluster_borders = [&get_reach_dist, &n_reachdists, &chi]( const SDA& sda, std::size_t sua_begin_idx, std::size_t sua_end_idx ) -> std::pair<std::size_t, std::size_t> {\r\n\t\tdouble start_reach = get_reach_dist(sda.begin_idx);\r\n\t\tdouble end_reach = get_reach_dist(std::min( sua_end_idx + 1, n_reachdists - 1 ));\r\n\t\tif ( geom::in_range( start_reach, end_reach, start_reach*chi ) ) {\r\n\t\t\treturn { sda.begin_idx, sua_end_idx };\r\n\t\t}\r\n\t\tif ( start_reach > end_reach ) {\r\n\t\t\tstd::size_t start_idx = sda.begin_idx + 1;\r\n\t\t\twhile ( start_idx <= sda.end_idx && get_reach_dist(start_idx) > end_reach ) {\r\n\t\t\t\tstart_idx++;\r\n\t\t\t}\r\n\t\t\treturn { start_idx - 1, sua_end_idx };\r\n\t\t}\r\n\t\tif ( start_reach < end_reach ) {\r\n\t\t\tstd::size_t end_idx = sua_end_idx;\r\n\t\t\twhile ( end_idx >= sua_begin_idx && get_reach_dist(end_idx) >= start_reach ) {\r\n\t\t\t\tend_idx--;\r\n\t\t\t}\r\n\t\t\treturn std::make_pair( sda.begin_idx, end_idx + 1 );\r\n\t\t}\r\n\t\tassert( false );\r\n\t\treturn { 0,0 };\r\n\r\n\t};\r\n\tconst auto valid_combination = [&chi, &steep_area_min_diff, &min_pts, &get_reach_dist]( const SDA& sda, std::size_t sua_begin_idx, std::size_t sua_end_idx ) -> bool {\r\n\t\tconst double f = fplus::max( chi, steep_area_min_diff );\r\n\t\tif ( sda.mib > get_reach_dist( sua_end_idx + 1 ) * (1 - f) ) { return false; }\r\n\r\n\t\tstd::size_t sda_middle = (sda.begin_idx + (sda.end_idx- sda.begin_idx) / 2);\r\n\t\tstd::size_t sua_middle = (sua_begin_idx + (sua_end_idx - sua_begin_idx) / 2);\r\n\t\tif ( sua_middle - sda_middle < min_pts - 2 ) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t};\r\n\r\n\r\n\tfor ( std::size_t idx = 0; idx < n_reachdists; idx++ ) {\r\n\t\tdouble reach_i = get_reach_dist(idx);\r\n\r\n\t\t//Start of Steep Down Area?\r\n\t\tif ( idx < n_reachdists && is_steep_down_pt( idx ) ) {\r\n\t\t\tif ( reach_i > mib ) { mib = reach_i; }\r\n\t\t\tfilter_sdas();\r\n\t\t\tstd::size_t sda_end_idx = get_sda_end( idx );\r\n\t\t\tif ( reach_i *(1.0 - steep_area_min_diff) < get_reach_dist( sda_end_idx + 1 ) ) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tSDAs.push_back( SDA( idx, sda_end_idx, 0.0 ) );\r\n\t\t\tidx = sda_end_idx;\r\n\t\t\tif ( idx < n_reachdists - 1 ) { mib = get_reach_dist(idx+1); }\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t//Start of Steep Up Area?\r\n\t\telse if ( idx < n_reachdists && is_steep_up_pt( idx ) ) {\r\n\t\t\tfilter_sdas();\r\n\t\t\tstd::size_t sua_end_idx = get_sua_end( idx );\r\n\t\t\tif ( reach_i > get_reach_dist( sua_end_idx + 1 )*(1.0 - steep_area_min_diff) ) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor ( auto& sda : SDAs ) {\r\n\t\t\t\tif ( valid_combination( sda, idx, sua_end_idx ) ) {\r\n\t\t\t\t\tclusters.push_back( cluster_borders( sda, idx, sua_end_idx ) );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tidx = sua_end_idx;\r\n\t\t\tif ( idx < n_reachdists - 1 ) { mib = get_reach_dist(idx+1); }\r\n\t\t}\r\n\t\telse { if ( reach_i > mib ) { mib = reach_i; } }\r\n\t}\r\n\treturn clusters;\r\n}\r\n\r\n\r\n\r\ninline std::vector<cluster_tree> flat_clusters_to_tree( const std::vector<chi_cluster_indices>& clusters_flat ){\r\n\t//sort clusters_flat such that children are ordered before their parents in clusters_flat_sorted\r\n\tstd::vector<fplus::maybe<chi_cluster_indices>> clusters_flat_sorted_m( clusters_flat.size(), fplus::nothing<chi_cluster_indices>() );\r\n\tstd::size_t next_free_idx = 0;\r\n\tfor ( std::size_t idx = 0; idx < clusters_flat.size(); idx++ ) {\r\n\t\twhile ( next_free_idx < clusters_flat_sorted_m.size() && clusters_flat_sorted_m[next_free_idx].is_just() ) {\r\n\t\t\tnext_free_idx++;\r\n\t\t}\r\n\t\tstd::size_t idx_pos = next_free_idx;\r\n\t\tstd::size_t following_idx = idx + 1;\r\n\t\twhile ( following_idx < clusters_flat.size() && clusters_flat[following_idx].second <= clusters_flat[idx].second ) {\r\n\t\t\tfollowing_idx++;\r\n\t\t\tidx_pos++;\r\n\t\t}\r\n\t\tclusters_flat_sorted_m[idx_pos] = fplus::just( clusters_flat[idx] );\r\n\t}\r\n\r\n\tauto clusters_flat_sorted = fplus::justs( clusters_flat_sorted_m );\r\n\tassert( clusters_flat_sorted.size() == clusters_flat.size() );\r\n\r\n\t//compute tree from clusters_flat_sorted\r\n\tstd::vector<cluster_tree> result;\r\n\tstd::vector<cluster_tree> cluster_trees = fplus::transform( []( const chi_cluster_indices& c ) -> cluster_tree {\r\n\t\treturn cluster_tree( c );\r\n\t}, clusters_flat_sorted );\r\n\r\n\tauto get_first_parent_idx = [&cluster_trees]( std::size_t idx )->std::size_t {\r\n\t\tauto cluster = cluster_trees[idx].get_root().get_data();\r\n\t\tfor ( std::size_t first_parent_idx = idx + 1; first_parent_idx < cluster_trees.size(); first_parent_idx++ ) {\r\n\t\t\tauto parent_cluster = cluster_trees[first_parent_idx].get_root().get_data();\r\n\t\t\tif ( cluster.first >= parent_cluster.first && cluster.second <= parent_cluster.second ) {\r\n\t\t\t\treturn first_parent_idx;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn cluster_trees.size();\r\n\t};\r\n\tfor ( std::size_t idx = 0; idx < cluster_trees.size(); idx++ ) {\r\n\t\tauto first_parent_idx = get_first_parent_idx( idx );\r\n\t\tif ( first_parent_idx >= cluster_trees.size() ) {\r\n\t\t\tresult.push_back( cluster_trees[idx] );\r\n\t\t}\r\n\t\telse {\r\n\t\t\tcluster_trees[first_parent_idx].get_root().add_child( cluster_trees[idx].get_root() );\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\ninline void draw_cluster( bgr_image& cluster_indicator_img, const Node<chi_cluster_indices>& cluster, const std::size_t depth,\r\n\t\t\t\t\t\t  const double x_norm, const std::size_t v_dist ) {\r\n\tstd::size_t v_offset = (depth+1)*v_dist;\r\n\tassert( v_offset <= cluster_indicator_img.size().height_ );\r\n\tstd::size_t height = cluster_indicator_img.size().height_ - v_offset;\r\n\timg_pos x1( fplus::round<double, std::size_t>(x_norm*cluster.get_data().first), height );\r\n\timg_pos x2( fplus::round<double, std::size_t>( x_norm*cluster.get_data().second), height );\r\n\tbgr_col col( 0, 0, 0 );\r\n\tbgr_col st_col( 0, 255, 0 );\r\n\tbgr_col end_col( 255, 0, 0 );\r\n\tplot_line_segment( cluster_indicator_img, x1, x2, col );\r\n\tplot_pixel( cluster_indicator_img, x1, st_col );\r\n\tplot_pixel( cluster_indicator_img, x2, end_col );\r\n\tfor ( const auto& c : cluster.get_children() ) {\r\n\t\tdraw_cluster( cluster_indicator_img, c, depth+1, x_norm, v_dist );\r\n\t}\r\n}\r\n\r\n\r\n\r\ninline std::vector<cluster_tree> get_chi_clusters( const std::vector<reachability_dist>& reach_dists, const double chi, std::size_t min_pts, const double steep_area_min_diff = 0.0 ) {\r\n\tauto clusters_flat = get_chi_clusters_flat( reach_dists, chi, min_pts, steep_area_min_diff );\r\n\treturn flat_clusters_to_tree( clusters_flat );\r\n}\r\n\r\n\r\ninline bgr_image  draw_reachability_plot_with_chi_clusters( const std::vector<reachability_dist>& reach_dists,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst double chi, const std::size_t min_pts, const double steep_area_min_diff = 0.0,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::size_t min_width = 100\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n{\r\n\tauto img = draw_reachability_plot( reach_dists, min_width );\r\n\tauto cluster_trees = optics::get_chi_clusters( reach_dists, chi, min_pts, steep_area_min_diff );\r\n\r\n\tstd::size_t max_tree_depth = 0;\r\n\tfor ( const auto& t : cluster_trees ) {\r\n\t\tauto depth = optics::tree_depth<chi_cluster_indices>( t.get_root() );\r\n\t\tif ( depth > max_tree_depth ) { max_tree_depth = depth; }\r\n\t}\r\n\tstd::size_t v_space = 4;\r\n\tbgr_image cluster_indicator_img( size_2d( img.size().width_, (max_tree_depth +1) * v_space ), bgr_col(255,255,255) );\r\n\r\n\tdouble x_norm = 1;\r\n\tif ( min_width > reach_dists.size() ) {\r\n\t\tx_norm =  static_cast<double>(min_width)/ static_cast<double>(reach_dists.size()-1);\r\n\t}\r\n\tfor ( const auto& t : cluster_trees ) {\r\n\t\tdraw_cluster( cluster_indicator_img, t.get_root(), 0, x_norm, v_space );\r\n\t}\r\n\timg.append_rows(cluster_indicator_img);\r\n\treturn img;\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nbgr_image draw_2d_clusters( const std::vector<std::vector<geom::Vec<T,2>>>& clusters ) {\r\n\tauto box = geom2d::bounding_box( fplus::concat( clusters ) );\r\n\tbgr_image cluster_image( size_2d( fplus::round<double, std::size_t>(box.get_size().first+1), fplus::round<double, std::size_t>( box.get_size().second+1)), bgr_col(255,255,255) );\r\n\tstd::array<bgr_col, 12> colours = {\r\n\t\tbgr_col( 255,0,0 ), bgr_col( 0,255,0 ), bgr_col(0,0,255),\r\n\t\tbgr_col(255,255,0), bgr_col(255,0,255), bgr_col(0,255,255),\r\n\t\tbgr_col( 255,128,128 ), bgr_col( 128,255,128 ), bgr_col( 128,128,255 ),\r\n\t\tbgr_col( 255,255,128 ), bgr_col( 255,128,255 ), bgr_col( 128,255,255 )\r\n\t};\r\n\tint col_idx = 0;\r\n\tfor ( const auto& cluster : clusters ) {\r\n\t\tbgr_col col = colours[col_idx];\r\n\t\t++col_idx %= colours.size();\r\n\t\tauto cluster_box = geom2d::bounding_box( cluster );\r\n\t\tfor( const auto& edge: fplus::overlapping_pairs_cyclic(cluster_box.points()) ){\r\n\t\t\tplot_line_segment( cluster_image,\r\n\t\t\t\t\t\t\t   img_pos( fplus::round<double, std::size_t>(edge.first.x() - box.bl().x() ), fplus::round<double, std::size_t>( edge.first.y() - box.bl().y() )),\r\n\t\t\t\t\t\t\t   img_pos( fplus::round<double, std::size_t>( edge.second.x() - box.bl().x() ), fplus::round<double, std::size_t>( edge.second.y() - box.bl().y() ) ),\r\n\t\t\t\t\t\t\t   col );\r\n\t\t}\r\n\t\tfor ( const auto& pt : cluster ) {\r\n\t\t\timg_pos cluster_pt = img_pos( fplus::round<double, std::size_t>( pt.x() - box.bl().x() ), fplus::round<double, std::size_t>( pt.y() - box.bl().y() ) );\r\n\t\t\tplot_circle( cluster_image, cluster_pt, 2, col );\r\n\t\t}\r\n\t}\r\n\treturn cluster_image;\r\n}\r\n\r\ntemplate<typename T>\r\nbgr_image draw_2d_clusters( const std::vector<std::vector<std::array<T, 2>>>& clusters ) {\r\n\tauto geom_clusters = fplus::transform_inner( []( const std::array<T, 2>& pt )-> geom::Vec<T, 2> {\r\n\t\treturn geom::Vec<T,2>( pt );\r\n\t}, clusters );\r\n\r\n\treturn draw_2d_clusters( geom_clusters );\r\n}\r\n\r\n} //namespace optics\r\n", "meta": {"hexsha": "a13e1f15fe995f3e3147e4ccbcb6c85e4ff46514", "size": 42338, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/optics/optics.hpp", "max_stars_repo_name": "CrikeeIP/OPTICS-Clustering", "max_stars_repo_head_hexsha": "b2b98ba08a67bf633086fcafc6e2ad431d43801f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2016-08-17T13:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:48:22.000Z", "max_issues_repo_path": "include/optics/optics.hpp", "max_issues_repo_name": "CrikeeIP/OPTICS-Clustering", "max_issues_repo_head_hexsha": "b2b98ba08a67bf633086fcafc6e2ad431d43801f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-06-08T12:02:40.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-12T14:27:58.000Z", "max_forks_repo_path": "include/optics/optics.hpp", "max_forks_repo_name": "CrikeeIP/OPTICS-Clustering", "max_forks_repo_head_hexsha": "b2b98ba08a67bf633086fcafc6e2ad431d43801f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-08-17T13:22:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T21:59:19.000Z", "avg_line_length": 38.80659945, "max_line_length": 227, "alphanum_fraction": 0.6811611318, "num_tokens": 11861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.040237942767482444, "lm_q1q2_score": 0.012772579907612585}}
{"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 \"abstract_boundary_operator_pseudoinverse.hpp\"\n\n#include \"context.hpp\"\n#include \"discrete_inverse_sparse_boundary_operator.hpp\"\n#include \"discrete_dense_boundary_operator.hpp\"\n#include \"discrete_sparse_boundary_operator.hpp\"\n\n#include \"../common/to_string.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n\n#ifdef WITH_TRILINOS\n\n#include \"../assembly/discrete_inverse_sparse_boundary_operator.hpp\"\n#include \"../assembly/discrete_sparse_boundary_operator.hpp\"\n#include \"../assembly/discrete_boundary_operator_composition.hpp\"\n\n#include <Epetra_CrsMatrix.h>\n#include <Epetra_LocalMap.h>\n#include <Epetra_SerialComm.h>\n#include <EpetraExt_MatrixMatrix.h>\n#include <boost/make_shared.hpp>\n#include <tbb/tick_count.h>\n\n#endif\n\nnamespace Bempp {\n\n////////////////////////////////////////////////////////////////////////////////\n// AbstractBoundaryOperatorPseudoinverse\n\ntemplate <typename BasisFunctionType, typename ResultType>\nAbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>::\n    AbstractBoundaryOperatorPseudoinverse(\n        // TODO: add a solver argument specifying how to calculate the\n        // pseudoinv.\n        const BoundaryOperator<BasisFunctionType, ResultType> &operatorToInvert)\n    : Base(operatorToInvert.range(), operatorToInvert.domain(),\n           operatorToInvert.domain() == operatorToInvert.range()\n               ? operatorToInvert.dualToRange()\n               :\n               // assume that domain == dualToRange, we'll verify it\n               // in the body of the constructor\n               operatorToInvert.range(),\n           \"pinv(\" + operatorToInvert.label() + \")\",\n           throwIfUninitialized(operatorToInvert,\n                                \"AbstractBoundaryOperatorPseudoinverse::\"\n                                \"AbstractBoundaryOperatorPseudoinverse(): \"\n                                \"the boundary operator to be inverted must be \"\n                                \"initialized\")\n               .abstractOperator()\n               ->symmetry()),\n      m_operator(operatorToInvert),\n      m_id(boost::make_shared<AbstractBoundaryOperatorPseudoinverseId<\n          BasisFunctionType, ResultType>>(operatorToInvert)) {\n  if (operatorToInvert.domain() != operatorToInvert.range() &&\n      operatorToInvert.domain() != operatorToInvert.dualToRange())\n    throw std::runtime_error(\n        \"AbstractBoundaryOperatorPseudoinverse::\"\n        \"AbstractBoundaryOperatorPseudoinverse(): \"\n        \"Dual to the domain of the operator to invert cannot be determined \"\n        \"since the domain is different from both \"\n        \"the range and the space dual to its range\");\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nAbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>::\n    AbstractBoundaryOperatorPseudoinverse(\n        // TODO: add a solver argument specifying how to calculate the\n        // pseudoinv.\n        const BoundaryOperator<BasisFunctionType, ResultType> &operatorToInvert,\n        const shared_ptr<const Space<BasisFunctionType>> &dualToRange)\n    : Base(operatorToInvert.range(), operatorToInvert.domain(), dualToRange,\n           \"pinv(\" + operatorToInvert.label() + \")\",\n           throwIfUninitialized(operatorToInvert,\n                                \"AbstractBoundaryOperatorPseudoinverse::\"\n                                \"AbstractBoundaryOperatorPseudoinverse(): \"\n                                \"the boundary operator to be inverted must be \"\n                                \"initialized\")\n               .abstractOperator()\n               ->symmetry()),\n      m_operator(operatorToInvert),\n      m_id(boost::make_shared<AbstractBoundaryOperatorPseudoinverseId<\n          BasisFunctionType, ResultType>>(operatorToInvert)) {}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nbool\nAbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>::isLocal()\n    const {\n  return m_operator.abstractOperator()->isLocal();\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const AbstractBoundaryOperatorId>\nAbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>::id()\n    const {\n  return m_id;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<DiscreteBoundaryOperator<ResultType>>\nAbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>::\n    assembleWeakFormImpl(const Context<BasisFunctionType, ResultType> &context)\n    const {\n  bool verbose =\n      (context.assemblyOptions().verbosityLevel() >= VerbosityLevel::DEFAULT);\n  shared_ptr<const DiscreteBoundaryOperator<ResultType>> wrappedDiscreteOp =\n      m_operator.weakForm();\n\n  if (verbose)\n    std::cout << \"Calculating the (pseudo)inverse of operator '\"\n              << m_operator.label() << \"'...\" << std::endl;\n\n  tbb::tick_count start = tbb::tick_count::now();\n  shared_ptr<DiscreteBoundaryOperator<ResultType>> result;\n  if (shared_ptr<const DiscreteSparseBoundaryOperator<ResultType>>\n          wrappedSparseOp = boost::dynamic_pointer_cast<\n              const DiscreteSparseBoundaryOperator<ResultType>>(\n              wrappedDiscreteOp))\n    result = assembleWeakFormForSparseOperator(context, wrappedSparseOp);\n  else if (shared_ptr<const DiscreteDenseBoundaryOperator<ResultType>>\n               wrappedDenseOp = boost::dynamic_pointer_cast<\n                   const DiscreteDenseBoundaryOperator<ResultType>>(\n                   wrappedDiscreteOp))\n    result = assembleWeakFormForDenseOperator(context, wrappedDenseOp);\n  else\n    throw std::runtime_error(\n        \"AbstractBoundaryOperatorPseudoinverse::assembleWeakFormImpl(): \"\n        \"Currently only elementary boundary operators stored as sparse \"\n        \"or dense matrices can be inverted\");\n  tbb::tick_count end = tbb::tick_count::now();\n\n  if (verbose)\n    std::cout << \"Calculation of the (pseudo)inverse of operator '\"\n              << m_operator.label() << \"' took \" << (end - start).seconds()\n              << \" s\" << std::endl;\n  return result;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<DiscreteBoundaryOperator<ResultType>>\nAbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>::\n    assembleWeakFormForSparseOperator(\n        const Context<BasisFunctionType, ResultType> &context,\n        const shared_ptr<const DiscreteSparseBoundaryOperator<ResultType>> &\n            wrappedDiscreteOp) const {\n  typedef DiscreteBoundaryOperator<ResultType> DiscreteOp;\n  typedef DiscreteSparseBoundaryOperator<ResultType> DiscreteSparseOp;\n  typedef DiscreteInverseSparseBoundaryOperator<ResultType>\n  DiscreteInverseSparseOp;\n\n  shared_ptr<const Epetra_CrsMatrix> matrix = wrappedDiscreteOp->epetraMatrix();\n\n  const int rowCount = matrix->NumGlobalRows();\n  const int colCount = matrix->NumGlobalCols();\n  if (rowCount == colCount) {\n    // Square matrix; construct M^{-1}\n    return boost::make_shared<DiscreteInverseSparseOp>(\n        matrix, m_operator.abstractOperator()->symmetry());\n  } else {\n    // Construct the discrete operator representing M^H\n    shared_ptr<DiscreteOp> transposeOp = boost::make_shared<DiscreteSparseOp>(\n        matrix, NO_SYMMETRY, CONJUGATE_TRANSPOSE);\n\n    // Construct the discrete operator representing the smaller of\n    // (M^H M)^{-1} and (M M^H)^{-1}\n    Epetra_SerialComm comm; // To be replaced once we begin to use MPI\n    int size = std::min(rowCount, colCount);\n    Epetra_LocalMap map(size, 0 /* index_base */, comm);\n    shared_ptr<Epetra_CrsMatrix> productMatrix =\n        boost::make_shared<Epetra_CrsMatrix>(\n            Copy, map, map,\n            // estimate of the number of nonzero entries per row\n            3 * matrix->GlobalMaxNumEntries());\n\n    if (rowCount > colCount) {\n      // Tall matrix (overdetermined least-square problem);\n      // construct (M^H M)^{-1} M^H\n      EpetraExt::MatrixMatrix::Multiply(*matrix, true /* transpose */, *matrix,\n                                        false /* no transpose */,\n                                        *productMatrix);\n      shared_ptr<DiscreteOp> productInverseOp =\n          boost::make_shared<DiscreteInverseSparseOp>(productMatrix, HERMITIAN);\n\n      return boost::make_shared<\n          DiscreteBoundaryOperatorComposition<ResultType>>(productInverseOp,\n                                                           transposeOp);\n    } else {\n      // Wide matrix (underdetermined least-square problem);\n      // construct M^H (M M^H)^{-1}\n      EpetraExt::MatrixMatrix::Multiply(*matrix, false /* no transpose */,\n                                        *matrix, true /* transpose */,\n                                        *productMatrix);\n      shared_ptr<DiscreteOp> productInverseOp =\n          boost::make_shared<DiscreteInverseSparseOp>(productMatrix, HERMITIAN);\n      return boost::make_shared<\n          DiscreteBoundaryOperatorComposition<ResultType>>(transposeOp,\n                                                           productInverseOp);\n    }\n  }\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<DiscreteBoundaryOperator<ResultType>>\nAbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>::\n    assembleWeakFormForDenseOperator(\n        const Context<BasisFunctionType, ResultType> &context,\n        const shared_ptr<const DiscreteDenseBoundaryOperator<ResultType>> &\n            wrappedDiscreteOp) const {\n  typedef DiscreteDenseBoundaryOperator<ResultType> DiscreteDenseLinOp;\n\n  if (wrappedDiscreteOp->rowCount() == wrappedDiscreteOp->columnCount())\n    // TODO: store an LU decomposition instead of the inverse matrix.\n    return boost::make_shared<DiscreteDenseLinOp>(\n        arma::inv(wrappedDiscreteOp->asMatrix()));\n  else\n    // compute and store pseudoinverse\n    return boost::make_shared<DiscreteDenseLinOp>(\n        arma::pinv(wrappedDiscreteOp->asMatrix()));\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBoundaryOperator<BasisFunctionType, ResultType> pseudoinverse(\n    const BoundaryOperator<BasisFunctionType, ResultType> &boundaryOp) {\n  typedef AbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>\n  Pinv;\n  return BoundaryOperator<BasisFunctionType, ResultType>(\n      boundaryOp.context(), boost::make_shared<Pinv>(boundaryOp));\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBoundaryOperator<BasisFunctionType, ResultType>\npseudoinverse(const BoundaryOperator<BasisFunctionType, ResultType> &boundaryOp,\n              const shared_ptr<const Space<BasisFunctionType>> &dualToRange) {\n  typedef AbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>\n  Pinv;\n  return BoundaryOperator<BasisFunctionType, ResultType>(\n      boundaryOp.context(), boost::make_shared<Pinv>(boundaryOp, dualToRange));\n}\n\nBEMPP_GCC_DIAG_OFF(deprecated - declarations);\n\n////////////////////////////////////////////////////////////////////////////////\n// AbstractBoundaryOperatorPseudoinverseId\n\ntemplate <typename BasisFunctionType, typename ResultType>\nAbstractBoundaryOperatorPseudoinverseId<BasisFunctionType, ResultType>::\n    AbstractBoundaryOperatorPseudoinverseId(\n        const BoundaryOperator<BasisFunctionType, ResultType> &operatorToInvert)\n    : m_operatorToInvertId(operatorToInvert.abstractOperator()->id()) {}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nsize_t\nAbstractBoundaryOperatorPseudoinverseId<BasisFunctionType, ResultType>::hash()\n    const {\n  typedef AbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>\n  OperatorType;\n  size_t result = tbb::tbb_hasher(typeid(OperatorType).name());\n  tbb_hash_combine(result, m_operatorToInvertId->hash());\n  return result;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid\nAbstractBoundaryOperatorPseudoinverseId<BasisFunctionType, ResultType>::dump()\n    const {\n  typedef AbstractBoundaryOperatorPseudoinverse<BasisFunctionType, ResultType>\n  OperatorType;\n  std::cout << typeid(OperatorType).name() << \" \";\n  m_operatorToInvertId->dump();\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nbool\nAbstractBoundaryOperatorPseudoinverseId<BasisFunctionType, ResultType>::isEqual(\n    const AbstractBoundaryOperatorId &other) const {\n  // dynamic_cast won't suffice since we want to make sure both objects\n  // are of exactly the same type (dynamic_cast would succeed for a subclass)\n  if (typeid(other) == typeid(*this)) {\n    const AbstractBoundaryOperatorPseudoinverseId &otherCompatible =\n        static_cast<const AbstractBoundaryOperatorPseudoinverseId &>(other);\n    return (*m_operatorToInvertId == *(otherCompatible.m_operatorToInvertId));\n  } else\n    return false;\n}\n\nBEMPP_GCC_DIAG_ON(deprecated - declarations);\n\n#define INSTANTIATE_NONMEMBER_CONSTRUCTOR(BASIS, RESULT)                       \\\n  template BoundaryOperator<BASIS, RESULT> pseudoinverse(                      \\\n      const BoundaryOperator<BASIS, RESULT> &);                                \\\n  template BoundaryOperator<BASIS, RESULT> pseudoinverse(                      \\\n      const BoundaryOperator<BASIS, RESULT> &,                                 \\\n      const shared_ptr<const Space<BASIS>> &);\nFIBER_ITERATE_OVER_BASIS_AND_RESULT_TYPES(INSTANTIATE_NONMEMBER_CONSTRUCTOR);\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(\n    AbstractBoundaryOperatorPseudoinverse);\n\n} // namespace Bempp\n", "meta": {"hexsha": "04e0103c50b09ddaced0b935933b1ec31aac3c72", "size": 14437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/abstract_boundary_operator_pseudoinverse.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/abstract_boundary_operator_pseudoinverse.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/abstract_boundary_operator_pseudoinverse.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.115625, "max_line_length": 80, "alphanum_fraction": 0.7072799058, "num_tokens": 3113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.026355354088838358, "lm_q1q2_score": 0.012766008634701287}}
{"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// Created by  Cecilia Curreli, Technical University Munich on 18-7-4.\n#ifdef TENSORFLOW_ENABLED\n#include <Python.h>\n#include \"tensorflow/core/public/session.h\"\n#include \"tensorflow/cc/ops/standard_ops.h\" //maybe we don't need this\n\n#include <matrix_exp_op/kernels/matrix_exp_kernel.cc>\n#include <matrix_exp_op/kernels/matrix_exp_op.cc>\n#include <matrix_exp_op/kernels/matrix_exp_op.h>\n#include <matrix_exp_op/ops/matrix_exp.cc>\n//#include <tuple>\n\n#include \"tf_opt.h\"\n#include <kernel/utilities/ssl_plot.h>\nusing namespace ssl::utility;\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n\ntypedef std::chrono::high_resolution_clock::time_point TimeVar;\n#define duration(a) std::chrono::duration_cast<std::chrono::seconds>(a).count()\n#define timeNow() std::chrono::high_resolution_clock::now()\n\nnamespace ssl {\nnamespace oc {\n\ntf_opt::tf_opt(spin_system &sys)\n    : rf_(nullptr) {\n\n  sys_ = &sys;\n  superop_.rf_ctrl = sys.rf_hamiltonian();\n  superop_.L0 = sys.free_hamiltonian();\n  superop_.R = sys.relaxation();\n  superop_.L0s = sys.free_hamiltonians();\n  int bb_size = superop_.L0s.size();\n  if (bb_size) {\n    superop_.profile = vec::Ones(bb_size);\n    superop_.nominal_offset = sys.nominal_broadband();\n    superop_.grad_bb = std::vector<std::vector<double>>(bb_size);\n  }\n\n}\n\ntf_opt::~tf_opt() {\n}\n\nvoid tf_opt::create_graph(std::string g_type) {\n\n  int n_channels = sys_->nspins();\n  const int size = (int) (init_state_).size();\n  std::string graph_definition = \"opt_graph.pb\";\n  bool measure_time = true;\n  TimeVar start;\n\n  if (measure_time) { start = timeNow(); }\n\n  bool use_gpu = 0;\n\n  //call system which will call python function to construct the graph\n  if (call_system(size, n_channels, dt, graph_definition, g_type)) {\n    std::cout << \"\\n\\n\" << std::endl;\n    std::string s1 = str(boost::format(\"Time needed for graph computation: [%.3f] seconds.\\n\\n\") %\n        ((duration(timeNow() - start))));\n    ssl_color_text(\"info\", s1);\n  }\n  if (measure_time) { start = timeNow(); }\n\n  //load the graph\n  TF_CHECK_OK(ReadBinaryProto(Env::Default(), graph_definition, &graph_def));\n\n  //assign Device after defining the graph.\n  if (opts.target.empty() && use_gpu) {\n    std::cout << \"empty\" << std::endl;\n    graph::SetDefaultDevice(use_gpu ? \"/gpu:0\" : \"/cpu:0\", &graph_def);\n  }\n\n  // create a new session\n  TF_CHECK_OK(NewSession(opts, &session));\n  // Load graph into session\n  TF_CHECK_OK(session->Create(graph_def));\n\n  // this can be used to verify which devices are found\n  /*\n  std::vector<DeviceAttributes> resp;\n  TF_CHECK_OK(session->ListDevices(&resp));\n  bool has_gpu = false;\n  for (const auto& dev : resp) {\n      if (dev.device_type() == \"GPU\") { has_gpu = true; std::cout << \"Device found: GPU \" << std::endl;}\n      if (dev.device_type() == \"CPU\") { std::cout << \"Device found: CPU \" << std::endl; }\n  }\n  */\n  //\n\n  create_tf_variables_list();\n  initialize_placeholder();\n\n  if (measure_time) {\n    std::string\n        s1 = str(boost::format(\"Time needed to load the graph: [%.3f] seconds.\\n\\n\") % ((duration(timeNow() - start))));\n    ssl_color_text(\"info\", s1);\n  }\n\n}\n\nvoid tf_opt::update_tf_variables(const double *x) {\n\n  int n_channels = sys_->nspins();\n  Tensor *u_pointer = nullptr;\n\n  for (int i = 0; i < nsteps; ++i) {\n    for (int c = 0; c < n_channels; ++c) {\n\n      u_pointer = &std::get<1>(variables_list[i * n_channels * 2 + c * 2]);\n      u_pointer->scalar<double>()() = x[i * n_channels * 2 + c * 2];\n      //memcpy could be a bit faster.\n      //memcpy(u_pointer->flat<double>().data(),\n      // &raw_val[i * n_channels * 2 + c * 2], sizeof(double)); //u_pointer->scalar<double>()() = -250*2*M_PI ;\n\n      u_pointer = &std::get<1>(variables_list[i * n_channels * 2 + c * 2 + 1]);\n      u_pointer->scalar<double>()() = x[i * n_channels * 2 + c * 2 + 1];\n      //memcpy could be a bit faster.\n      //memcpy(u_pointer->flat<double>().data(),\n      // &raw_val[i * n_channels * 2 + c * 2 + 1], sizeof(double)); // u_pointer->scalar<double>()() = 0.0 ;\n\n    }\n  }\n\n  TF_CHECK_OK(session->Run(variables_list, {}, {\"init_all_vars_op\"}, nullptr));\n\n}\n\ndouble tf_opt::objfunc(const std::vector<double> &x, std::vector<double> &grad) {\n\n  rf_->update_raw_data(x.data());\n  //update variables in graph with values of x\n  update_tf_variables(x.data());\n\n  //get gradients\n  TF_CHECK_OK(session->Run(placeholder_list, gradient_names, {}, &outputs)); //add \"trace_real\" to the gradient_names\n  //save gradient in grad\n  Tensor *u_pointer = nullptr;\n  for (int i = 0; i < (outputs.size() - 1); ++i) {\n    u_pointer = &outputs[i];\n    grad[i] = -u_pointer->scalar<double>()();\n  }\n  double fidelity = (outputs[outputs.size() - 1].scalar<double>()());// - 1;\n  outputs.clear();\n  //TO DO\n//            TF_CHECK_OK(session->Run(placeholder_list, {\"fidelity\", \"psi\" + std::to_string(nsteps), \"Ux0_0\",\"Uy0_0\", \"trace_real\", \"trace\"}, {},  &outputs));\n////            double fidelity = (outputs[0].scalar<double>()());\n//            std::cout << \"Ux in x:    \" << x[0] << \";    Ux in tensorflow:    \" << outputs[2].scalar<double>()()<<std::endl;\n//            std::cout << \"Uy in x:     \" << x[0 + 1] << \";    Uy in tensorflow:    \" << outputs[3].scalar<double>()()<< std::endl;\n//                std::cout << \"grad wrt to first Ux:    \" << grad[0] << std::endl;\n//                std::cout << \"grad wrt to first Uy:     \" << grad[0 + 1] << std::endl;\n//    //            std::cout << \"trace.real():    \" << outputs[0].scalar<double>()()<< std::endl;\n//            std::cout << \"fidelity tf:    \" << (outputs[0].scalar<double>()()) << std::endl;\n//            std::cout << \"fidelity:    \" << fidelity << std::endl;\n//            std::cout << \"trace_real tf:    \" << (outputs[4].flat<double>()) << std::endl;\n//            std::cout << \"trace tf:    \" << (outputs[5].flat<complex<double>>()) << std::endl;\n//            outputs.clear();\n\n\n//            std::cout << \"final state :   \" <<outputs[1].flat<complex<double>>() << std::endl;\n//            std::cout << \"target state :   \" <<Eigen::VectorXcd(targ_state_) << std::endl;\n\n\n  std::cout << boost::format(\"==> %04d  [%.4f]\\n\") % (++opt_.iter_count) % fidelity;\n  opt_.vf.push_back(fidelity);\n  return fidelity;\n\n}\n\n\n//        void tf_opt::evaluation(const sol::table &t) {\n//\n//            double width = retrieve_table_double(\"width\", t); // unit in ms.\n//            nsteps = (size_t) (retrieve_table_double(\"step\", t));\n//            dt = width * 1e-3 / double(nsteps); // into s.\n//            if  (Eigen::MatrixXcd(superop_.R).isZero()) {relax = false;}\n//            else {relax = true;}\n//\n//\n//\n//            bool measure_time = 1;\n//            TimeVar start;\n//            if(measure_time) { start=timeNow(); }\n//\n//            assign_state(t);\n//            assign_nlopt(t);\n//            assign_pulse(t);\n//            assign_aux_var();\n//\n//            create_graph(\"evaluation\");\n//\n//            rf_->convert2(_ux_uy);\n//            std::vector<double> x = rf_->clone_raw_data();\n//\n//            //create std::vector with the names of the grafients to fetch gradient with a call to tensroflow run\n//            int n_channels = sys_->nspins();\n//            gradient_names = std::vector<std::string> (nsteps*n_channels*2 + 1); //here we have all nodes we want to fetch for the optimization\n//            std::string s;\n//            for (int i = 0; i < nsteps; ++i) {\n//                for (int c = 0; c < n_channels; ++c) {\n//                    s = std::to_string(c) + \"_\" + std::to_string(i);\n//                    gradient_names[i*n_channels*2 + c*2] = \"Cecilia_gradient/Complex_Ux\" + s + \"_grad/Reshape\";\n//                    gradient_names[i*n_channels*2 + c*2 + 1] = \"Cecilia_gradient/Complex_Uy\" + s + \"_grad/Reshape\";\n//                }\n//            }\n//            gradient_names[nsteps*n_channels*2] = \"trace_real\";\n//\n//            // optimization processing.\n//            nlopt::opt opt(opt_.algo, rf_->get_dims());\n//            opt.set_xtol_rel(opt_.tol_f);\n//            if (opt_.max_eval > 0)\n//                opt.set_maxeval(opt_.max_eval);\n//            if (opt_.max_time > 0)\n//                opt.set_maxtime(opt_.max_time);\n//            if (opt_.stopval > 0)\n//                opt.set_stopval(opt_.stopval);\n//\n//            opt.set_max_objective(objfunc, this);\n//\n//            // boundary limitation.\n//            // opt_amplitude_constraint(opt);\n//\n//            double max_f;\n//            nlopt::result result = opt.optimize(x, max_f);\n//\n//            if (result == nlopt::SUCCESS)\n//                ssl_color_text(\"info\", \"pulse optimization succeed.\\n\");\n//            if(measure_time) {\n//                std::string s1 = str(boost::format(\"Time needed for the Tensorflow optimization process is: [%.3f] seconds.\\n\") % duration(timeNow()-start));\n//                ssl_color_text(\"info\", s1);\n//            }\n//            if (result == nlopt::FAILURE)\n//                ssl_color_text(\"err\", \"pulse optimization failed.\\n\");\n//            if (result == nlopt::MAXEVAL_REACHED)\n//                ssl_color_text(\"warn\", \"pulse optimization terminated due to maximum iterations limitation.\\n\");\n//\n//            opt_.max_f = max_f;\n//            rf_->update_raw_data(x.data());\n//            update_tf_variables(x.data());\n//\n//            tf_opt::h5write();\n//\n//            //session->Close(); //this eliminates all the variables\n//            //delete session;\n//\n//            return *rf_;\n//        }\n\nseq_block &tf_opt::optimize(const sol::table &t) {\n\n  double width = retrieve_table_double(\"width\", t); // unit in ms.\n  nsteps = (size_t) (retrieve_table_double(\"step\", t));\n  dt = width * 1e-3 / double(nsteps); // into s.\n  if (Eigen::MatrixXcd(superop_.R).isZero()) { relax = false; }\n  else { relax = true; }\n\n  bool measure_time = 1;\n  TimeVar start;\n  if (measure_time) { start = timeNow(); }\n\n  assign_state(t);\n  assign_nlopt(t);\n  assign_pulse(t);\n  assign_aux_var();\n\n  create_graph(\"optimize\");\n\n  rf_->convert2(_ux_uy);\n  std::vector<double> x = rf_->clone_raw_data();\n\n  //create std::vector with the names of the grafients to fetch gradient with a call to tensroflow run\n  int n_channels = sys_->nspins();\n  gradient_names =\n      std::vector<std::string>(nsteps * n_channels * 2 + 1); //here we have all nodes we want to fetch for the optimization\n  std::string s;\n  for (int i = 0; i < nsteps; ++i) {\n    for (int c = 0; c < n_channels; ++c) {\n      s = std::to_string(c) + \"_\" + std::to_string(i);\n      gradient_names[i * n_channels * 2 + c * 2] = \"Cecilia_gradient/Complex_Ux\" + s + \"_grad/Reshape\";\n      gradient_names[i * n_channels * 2 + c * 2 + 1] = \"Cecilia_gradient/Complex_Uy\" + s + \"_grad/Reshape\";\n    }\n  }\n  gradient_names[nsteps * n_channels * 2] = \"trace_real\";\n\n  // optimization processing.\n  nlopt::opt opt(opt_.algo, rf_->get_dims());\n  opt.set_xtol_rel(opt_.tol_f);\n  if (opt_.max_eval > 0)\n    opt.set_maxeval(opt_.max_eval);\n  if (opt_.max_time > 0)\n    opt.set_maxtime(opt_.max_time);\n  if (opt_.stopval > 0)\n    opt.set_stopval(opt_.stopval);\n\n  opt.set_min_objective(objfunc, this);\n\n  // boundary limitation.\n  // opt_amplitude_constraint(opt);\n\n  double max_f;\n  nlopt::result result = opt.optimize(x, max_f);\n\n  if (result == nlopt::SUCCESS)\n    ssl_color_text(\"info\", \"pulse optimization succeed.\\n\");\n  if (measure_time) {\n    std::string s1 = str(boost::format(\"Time needed for the Tensorflow optimization process is: [%.3f] seconds.\\n\")\n                        % duration(timeNow() - start));\n    ssl_color_text(\"info\", s1);\n  }\n  if (result == nlopt::FAILURE)\n    ssl_color_text(\"err\", \"pulse optimization failed.\\n\");\n  if (result == nlopt::MAXEVAL_REACHED)\n    ssl_color_text(\"warn\", \"pulse optimization terminated due to maximum iterations limitation.\\n\");\n\n  opt_.max_f = max_f;\n  rf_->update_raw_data(x.data());\n  update_tf_variables(x.data());\n\n  tf_opt::h5write();\n\n  //session->Close(); //this eliminates all the variables\n  //delete session;\n\n  return *rf_;\n}\n\nvoid tf_opt::projection(const sol::table &t) { //results are not correct\n  sol::object val = retrieve_table(\"init_state\", t);\n  sp_cx_vec init_state = sys_->smart_state(val.as<std::string>());\n  init_state = norm_state(init_state);\n  //init_state = levante_ernst(init_state);\n\n  val = retrieve_table(\"rf\", t);\n  seq_block &sb = val.as<seq_block &>();\n  shaped_rf &user_rf = (shaped_rf &) sb; // transfrom into 'shaped_rf'.\n  user_rf.convert2(_ux_uy);\n\n  size_t nsteps = user_rf.get_steps();\n  size_t nchannels = user_rf.get_channels();\n  double dt = user_rf.width_in_ms() * 1e-3 / double(nsteps); // into s.\n\n  std::map<std::string, sp_cx_vec> obsrv_state_map;\n  std::vector<std::string> expr;\n  std::vector<sp_cx_vec> obsrv_state;\n  if (is_retrievable(\"observ_states\", t)) {\n    val = retrieve_table(\"observ_states\", t);\n    sol::table expr_table = val.as<sol::table>();\n    if (expr_table.size() == 0) {\n      obsrv_state_map = sys_->cartesian_basis_states();\n    } else {\n      for (size_t i = 0; i < expr_table.size(); i++) {\n        sol::object val = expr_table[i + 1];\n        std::string exp = val.as<std::string>();\n        sp_cx_vec rho = sys_->smart_state(exp);\n        obsrv_state_map.insert(std::pair<std::string, sp_cx_vec>(exp, rho));\n      }\n    }\n\n  } else {\n    obsrv_state_map = sys_->cartesian_basis_states();\n  }\n\n  std::map<std::string, sp_cx_vec>::iterator iter;\n  for (iter = obsrv_state_map.begin(); iter != obsrv_state_map.end(); iter++) {\n    obsrv_state.push_back(norm_state(iter->second));\n    //obsrv_state.push_back(levante_ernst(iter->second));\n    expr.push_back(iter->first);\n  }\n\n  std::string s;\n  for (size_t p = 0; p < expr.size(); p++)\n    s += \"row \" + std::to_string(p + 1) + \"-\" + expr[p] + \" \";\n  //std::cout << \"row \" << p + 1 << \"=>\" << expr[p] << \"\\n\";\n\n  std::string str_opt = \"step\";\n  if (is_retrievable(\"option\", t))\n    str_opt = retrieve_table_str(\"option\", t);\n\n  int nrows = 0;\n  if (str_opt == \"step\")\n    nrows = nsteps;\n  else if (str_opt == \"broadband\")\n    nrows = superop_.L0s.size();\n  else {\n    std::string s = \"unknown projection option ** \" + str_opt + \" ** using ‘step’ or 'broadband' instead.\";\n    throw std::runtime_error(s.c_str());\n  }\n\n  mat transfer_wave = mat::Zero(nrows, expr.size());\n\n  std::vector<double> x = user_rf.clone_raw_data();\n  if (str_opt == \"step\") {\n    sp_cx_mat L;\n    sp_cx_mat L0 = superop_.L0 + superop_.R;\n    sp_cx_vec *forward = new sp_cx_vec[nsteps + 1];\n    forward[0] = init_state;\n    sp_cx_vec rho = forward[0];\n\n    for (size_t i = 0; i < nsteps; i++) {\n      L = L0;\n      for (size_t j = 0; j < nchannels; j++)\n        L += update_rf_ham(x.data(), i, j, nchannels);\n      forward[i + 1] = ssl::spinsys::step(rho, L, dt);\n      rho = forward[i + 1];\n\n      for (size_t k = 0; k < obsrv_state.size(); k++) {\n        sp_cx_vec compo = obsrv_state[k];\n        transfer_wave(i, k) = transfer_fidelity(rho, compo);// / transfer_fidelity(compo, compo);\n      }\n    }\n\n    // TO BE REMOVED (for NSFC project).\n    /*\n    for (size_t i = 0; i < nsteps / 2; i++) {\n      L = L0;\n      for (size_t j = 0; j < nchannels; j++)\n        L += update_rf_ham(x.data(), i, j, nchannels);\n      forward[i + 1] = ssl::spinsys::step(rho, L, dt);\n      rho = forward[i + 1];\n\n      for (size_t k = 0; k < obsrv_state.size(); k++) {\n        sp_cx_vec compo = obsrv_state[k];\n        transfer_wave(i, k) = transfer_fidelity(rho, compo);// / transfer_fidelity(compo, compo);\n      }\n    }\n\n    //std::cout<< (superop_.rf_ctrl.Lx[0]*superop_.L0-superop_.L0*superop_.rf_ctrl.Lx[0])<<\"\\n\";\n    //exit(0);\n    sp_cx_mat Lrf = superop_.rf_ctrl.Lx[0] + superop_.rf_ctrl.Lx[1];\n    sp_cx_vec tmp = ssl::spinsys::step(rho, Lrf, _pi);\n    rho = tmp;\n\n    for (size_t i = nsteps / 2; i < nsteps; i++) {\n      L = L0;\n      for (size_t j = 0; j < nchannels; j++)\n        L += update_rf_ham(x.data(), i, j, nchannels);\n      forward[i + 1] = ssl::spinsys::step(rho, L, dt);\n      rho = forward[i + 1];\n\n      for (size_t k = 0; k < obsrv_state.size(); k++) {\n        sp_cx_vec compo = obsrv_state[k];\n        transfer_wave(i, k) = transfer_fidelity(rho, compo);// / transfer_fidelity(compo, compo);\n      }\n    }\n     */\n    // TO BE REMOVED (for NSFC project).\n\n  } else if (str_opt == \"broadband\") {\n    omp_set_num_threads(omp_core_num);\n\n    std::vector<sp_cx_vec *> forward_trajs_parfor = std::vector<sp_cx_vec *>(omp_core_num);\n    for (int i = 0; i < omp_core_num; i++) {\n      sp_cx_vec *forward = new sp_cx_vec[nsteps + 1];\n      forward[0] = init_state;\n      forward_trajs_parfor[i] = forward;\n    }\n\n#pragma omp parallel for\n    for (int p = 0; p < nrows; p++) {\n      int id = omp_get_thread_num();\n\n      sp_cx_mat L;\n      sp_cx_mat L0 = superop_.L0s[p] + ci * superop_.R;\n      sp_cx_vec rho = forward_trajs_parfor[id][0];\n\n      for (size_t i = 0; i < nsteps; i++) {\n        L = L0;\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, nchannels);\n        forward_trajs_parfor[id][i + 1] = ssl::spinsys::step(rho, L, dt);\n        rho = forward_trajs_parfor[id][i + 1];\n      }\n\n      for (size_t k = 0; k < obsrv_state.size(); k++) {\n        sp_cx_vec compo = obsrv_state[k];\n        transfer_wave(p, k) = transfer_fidelity(rho, compo);// / transfer_fidelity(compo, compo);\n      }\n    }\n  }\n\n  // plot.\n  sol::table lines = g_lua->create_table();\n  for (int i = 0; i < transfer_wave.cols(); i++) {\n    vec line = transfer_wave.col(i);\n    lines.add(line);\n  }\n\n  std::string fig_spec;\n  vec time;\n  if (str_opt == \"step\") {\n    time = vec::LinSpaced(nrows, 0, user_rf.width_in_ms());\n    fig_spec = \"title<transfer trajectories of basis operators> xlabel<pulse duration / ms> ylabel<coefficient>\";\n  } else if (str_opt == \"broadband\") {\n    int n = superop_.nominal_offset.size();\n    time = vec::LinSpaced(nrows, superop_.nominal_offset[0], superop_.nominal_offset[n - 1]);\n    //fig_spec = \"title[transfer coefficient] xlabel[freq offset / kHz]\";\n    fig_spec = \"title<transfer coefficient> xlabel<J coupling / Hz>\";\n  }\n\n  if (expr.size() > 5)\n    fig_spec += \" gnuplot<set key outside>\";\n\n  fig_spec += \" color<Spectral>\";\n  //fig_spec += \" latex[ON]\";\n\n  std::string lege;\n  for (size_t i = 0; i < expr.size(); i++)\n    lege += expr[i] + \";\";\n  fig_spec += \"legend<\" + lege + \">\";\n\n  plot(fig_spec, line_series(time, lines));\n\n  std::ofstream ofstr(\"basis_projection.dat\");\n  ofstr.precision(3);\n  ofstr << transfer_wave;\n  ofstr.close();\n\n  return; // Currently ignore the following map plot.\n}\n\nvoid tf_opt::create_tf_variables_list() {\n\n  int n_channels = sys_->nspins();\n  variables_list = std::vector<std::pair<std::string, Tensor> >(nsteps * n_channels * 2);\n\n  Tensor *u_pointer = nullptr;\n  for (int i = 0; i < nsteps; ++i) {\n    for (int c = 0; c < n_channels; ++c) {\n\n      u_pointer = new Tensor(DT_DOUBLE, tensorflow::TensorShape({1}));\n      variables_list[i * n_channels * 2 + c * 2] =\n          {\"Assignx\" + std::to_string(c) + \"_\" + std::to_string(i), *u_pointer};\n\n      u_pointer = new Tensor(DT_DOUBLE, tensorflow::TensorShape({1}));\n      variables_list[i * n_channels * 2 + c * 2 + 1] =\n          {\"Assigny\" + std::to_string(c) + \"_\" + std::to_string(i), *u_pointer};\n\n    }\n  }\n\n}\n\nvoid tf_opt::initialize_placeholder() {\n\n  const int size = (int) init_state_.size();\n  int n_channels = sys_->nspins();\n\n  placeholder_list = std::vector<std::pair<std::string, Tensor> >(2 * n_channels + 2 + 1);\n\n  Tensor *Lx = nullptr;\n  Tensor *Ly = nullptr;\n\n  //get values for placeholder by copying into tensors\n  Tensor psi0(DT_COMPLEX128, tensorflow::TensorShape({size, 1}));\n  auto ps = Eigen::VectorXcd(init_state_);\n  memcpy(psi0.flat<complex<double>>().data(), ps.data(), sizeof(complex<double>) * size);\n  //std::cout << \"initial state:\\n\" << ps << std::endl;\n\n  Tensor target(DT_COMPLEX128, tensorflow::TensorShape({size, 1}));\n  auto psn = Eigen::VectorXcd(targ_state_);\n  memcpy(target.flat<complex<double>>().data(), psn.data(), sizeof(complex<double>) * size);\n  //std::cout << \"target state:\\n\" << psn << std::endl;\n\n  Tensor L0(DT_COMPLEX128, tensorflow::TensorShape({size, size}));\n  auto L_free = Eigen::MatrixXcd(superop_.L0);\n  //this works only if L0 is always symmetric! otherwise we would copy a column mayor matrix into a row major matrix\n  //memcpy((L0.flat<complex<double>>()).data(), L_free.data(), sizeof(complex<double>) * size * size);\n  auto mapL0 = Eigen::Map<Eigen::Matrix<complex<double>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor  >>(\n      (L0.flat<complex<double>>()).data(), size, size); /* tensorflow::Tensor is always row-major */\n  mapL0 = L_free;\n\n  placeholder_list[n_channels * 2] = {\"psi0\", psi0};\n  placeholder_list[n_channels * 2 + 1] = {\"target\", target};\n  placeholder_list[n_channels * 2 + 2] = {\"L0\", L0};\n\n  if (relax) {\n    Tensor R(DT_COMPLEX128, tensorflow::TensorShape({size, size}));\n    auto R_sys = Eigen::MatrixXcd(superop_.R);\n\n    auto mapR = Eigen::Map<Eigen::Matrix<complex<double>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor  >>(\n        (R.flat<complex<double>>()).data(), size, size); /* tensorflow::Tensor is always row-major */\n    mapR = R_sys;\n    placeholder_list.push_back({\"R\", R});\n    std::cout << \"Ro matrix:\\n\" << superop_.R << std::endl;\n    std::cout << \"R0 matrix:\\n\" << Eigen::MatrixXcd(superop_.R) << std::endl;\n    std::cout << \"R0 tensor:\\n\" << R.matrix<complex<double>>() << std::endl;\n\n  }\n\n  for (int c = 0; c < n_channels; ++c) {\n    Lx = new Tensor(DT_COMPLEX128, tensorflow::TensorShape({size, size}));\n    Ly = new Tensor(DT_COMPLEX128, tensorflow::TensorShape({size, size}));\n\n    auto mapLx = Eigen::Map<Eigen::Matrix<complex<double>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor  >>(\n        (Lx->flat<complex<double>>()).data(), size, size); /* tensorflow::Tensor is always row-major */\n    auto mapLy = Eigen::Map<Eigen::Matrix<complex<double>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor  >>(\n        (Ly->flat<complex<double>>()).data(), size, size); /* tensorflow::Tensor is always row-major */\n\n    //solution 1, maybe not so fast\n    mapLx = Eigen::MatrixXcd(superop_.rf_ctrl.Lx[c]);\n    mapLy = Eigen::MatrixXcd(superop_.rf_ctrl.Ly[c]);\n\n    //solution 2, could be faster.\n    //memcpy(Ly->matrix<complex<double>>().data(),\n    //       (Eigen::MatrixXcd(superop_.rf_ctrl.Ly[c])).data(), sizeof(complex<double>) * size * size);\n    //mapLy.transposeInPlace();\n    //memcpy(Lx->matrix<complex<double>>().data(),\n    //       (Eigen::MatrixXcd(superop_.rf_ctrl.Lx[c])).data(), sizeof(complex<double>) * size * size);\n    //mapLx.transposeInPlace();\n\n    placeholder_list[c] = {\"Lx\" + std::to_string(c), *Lx};\n    placeholder_list[c + n_channels] = {\"Ly\" + std::to_string(c), *Ly};\n\n  }\n}\n\nbool tf_opt::call_system(int size,\n                         int n_channels,\n                         double dt,\n                         std::string graph_definition,\n                         std::string graph_type) //const int* inputs\n{\n  if (system(nullptr)) {\n    std::string s = \"cd \" + g_install_dir + \"; cp -r share/spin-scenario/tf_files\" + \" \" + g_terminal_dir + \"; cd \"\n        + g_terminal_dir;\n    int res = system(s.c_str());\n    std::string command = \"cd tf_files; python3 -c 'import graph_generator as gg; print (gg.compute_graph_\";\n    command += graph_type + \"(\" + std::to_string(size) + \", \" + std::to_string(nsteps) + \", \" + std::to_string(n_channels) + \", \" +\n        std::to_string(dt) + \", \" + std::to_string(relax) + \"))'\";\n    res = system(command.c_str());\n    struct stat buf;\n    std::cout << \"output of system \" << res << std::endl; //= 256 if error //= 0 if everything ok\n    if (!(stat(graph_definition.c_str(), &buf) == 0)) {\n      std::string s = \"\\n           Error in system() call to python code. Graph was not created!!\";\n      throw std::runtime_error(s.c_str());\n      return 0;\n    } else {\n      return 1;\n    }\n  } else {\n    std::string s = \"!!command processor doesn't exists!! Failed call to system()!!\";\n    throw std::runtime_error(s.c_str());\n    return 0;\n  }\n}\ndouble tf_opt::maxf() const {\n  return opt_.max_f;\n}\n\ndouble tf_opt::objfunc(const std::vector<double> &x, std::vector<double> &grad, void *func) {\n  return ((tf_opt *) func)->objfunc(x, grad);\n}\n\n//double grape::objfunc_broadband(const std::vector<double> &x, std::vector<double> &grad, void *func) {\n//    return ((grape *) func)->objfunc_broadband(x, grad);\n//}\n\nvoid tf_opt::assign_state(const sol::table &t) {\n  init_state_ = sys_->smart_state(retrieve_table_str(\"init_state\", t));\n  init_state_ = norm_state(init_state_);\n\n  sol::object obj = retrieve_table(\"targ_state\", t);\n  if (obj.get_type() == sol::type::string) {\n    targ_state_ = sys_->smart_state(retrieve_table_str(\"targ_state\", t));\n    targ_state_ = norm_state(targ_state_);\n\n    // in case of unified targ for diff freq offsets.\n    if (superop_.L0s.size())\n      targ_list_ = std::vector<sp_cx_vec>(superop_.L0s.size(), targ_state_);\n  }\n\n/*  if (obj.get_type() == sol::type::table) {\n    sol::table targ_table = obj.as<sol::table>();\n    for (size_t i = 0; i < targ_table.size(); i++) {\n      sol::object val = targ_table[i + 1];\n      sp_cx_vec targ = val.as<sp_cx_vec>();\n      targ = levante_ernst(targ);\n      targ_list_.push_back(targ);\n    }\n  }*/\n}\n\nvoid tf_opt::assign_nlopt(const sol::table &t) {\n  opt_.algo = nlopt::LD_LBFGS; // default algorithm.\n  if (is_retrievable(\"algorithm\", t)) {\n    std::string oc = retrieve_table_str(\"algorithm\", t);\n    boost::to_upper(oc);\n\n    if (oc == \"LBFGS\")\n      opt_.algo = nlopt::LD_LBFGS;\n\n    if (oc == \"MNA\")\n      opt_.algo = nlopt::LD_MMA;\n  }\n\n  if (is_retrievable(\"max_eval\", t))\n    opt_.max_eval = retrieve_table_int(\"max_eval\", t);\n\n  if (is_retrievable(\"max_time\", t))\n    opt_.max_time = retrieve_table_double(\"max_time\", t);\n\n  if (is_retrievable(\"tol_f\", t))\n    opt_.tol_f = retrieve_table_double(\"tol_f\", t);\n\n  if (is_retrievable(\"stopval\", t))\n    opt_.stopval = retrieve_table_double(\"stopval\", t);\n\n  if (is_retrievable(\"max_amp\", t))\n    opt_.max_amp = retrieve_table_double(\"max_amp\", t);\n}\n\nvoid tf_opt::assign_pulse(const sol::table &t) {\n  double width = retrieve_table_double(\"width\", t); // unit in ms.\n  size_t nsteps = (size_t) (retrieve_table_double(\"step\", t));\n  std::string pattern = \"random_spline\";\n  if (is_retrievable(\"init_pattern\", t))\n    pattern = retrieve_table_str(\"init_pattern\", t);\n\n  double dt = width * 1e-3 / double(nsteps); // into s.\n\n  std::string str_chs = boost::algorithm::join(superop_.rf_ctrl.chs, \" \");\n  std::string code = \"user_rf = shapedRF{name = 'juncy', width = \" + boost::lexical_cast<std::string>(width) +\n      \",  step = \" + boost::lexical_cast<std::string>(nsteps) +\n      \",  max_amp = 1\" +\n      \",  channel = '\" + str_chs + \"',\" +\n      \"pattern = '\" + pattern + \"'}\";\n  g_lua->script(code);\n\n  std::string s = str(boost::format(\"pulse width - [%.3f] ms, steps - [%d], step width - [%.3f] us.\\n\") % width % nsteps\n                     % (dt * 1e6));\n  ssl_color_text(\"info\", s);\n\n  sol::object val = (*g_lua)[\"user_rf\"];\n  seq_block &sb = val.as<seq_block &>(); // note the original type should be 'seq_block'.\n  shaped_rf &user_rf = (shaped_rf &) sb; // transfrom into 'shaped_rf'.\n\n  rf_ = &user_rf;\n//    double vals [100];\n//    for (int i = 0; i < 100; ++i) {\n//        if (i%2==0){vals[i] = -250*2*M_PI;}\n//        else{ vals[i] =0.0;}\n//    }\n//    rf_->update_raw_data(vals);\n\n}\n\nvoid tf_opt::h5write(std::string file_name) const {\n  if (file_name.empty()) {\n    std::string time_s = sys_time();\n    file_name = \"oc_\" + time_s + \".h5\";\n  }\n  H5File file(file_name, H5F_ACC_TRUNC);\n\n  rf_->switch_rf_mode(\"amp/phase\");\n  rf_->h5write(file, \"opt\");\n\n  ssl::utility::h5write(file, nullptr, \"obj\", stl2vec(opt_.vf));\n  file.close();\n}\n\nvoid tf_opt::assign_aux_var() {\n  traj_ = state_traj(rf_->get_steps());\n  int nbb = superop_.L0s.size();\n  if (nbb > 1) {\n    omp_set_num_threads(omp_core_num);\n    for (size_t i = 0; i < superop_.grad_bb.size(); i++)\n      superop_.grad_bb[i] = std::vector<double>(rf_->get_dims(), 0);\n\n    traj_omp_ = std::vector<state_traj>(omp_core_num);\n    for (int i = 0; i < omp_core_num; i++) {\n      traj_omp_[i] = state_traj(rf_->get_steps());\n    }\n  }\n}\n\n//void tf_opt::opt_amplitude_constraint(nlopt::opt &opt) {\n//    if (opt_.max_amp <= 0)\n//        return;\n//\n//    size_t dim = rf_->get_dims();\n//    size_t nsteps = rf_->get_steps();\n//    size_t nchannels = rf_->get_channels();\n//    std::vector<double> up_bound(dim);\n//    std::vector<double> low_bound(dim);\n//\n//    switch (opt_.algo) {\n//        case nlopt::LD_MMA:\n//        case nlopt::LD_LBFGS: {\n//            //if(rf_mode_ ==_amp_phase)\n//            //      for (size_t i = 0; i < opt_rf_.nsteps; i++) {\n//            //          for (size_t j = 0; j < opt_rf_.nchannels; j++) {\n//            //              // amp.\n//            //              up_bound[2 * opt_rf_.nchannels * i + 2 * j] = opt_rf_.max_amp * 2 * _pi;\n//            //              low_bound[2 * opt_rf_.nchannels * i + 2 * j] = 0;\n//\n//            //              // phase.\n//            //              up_bound[2 * opt_rf_.nchannels * i + 2 * j + 1] = 2 * _pi;\n//            //              low_bound[2 * opt_rf_.nchannels * i + 2 * j + 1] = 0;\n//            //          }\n//            //      }\n//\n//            if (rf_->mode() == _ux_uy)\n//                for (size_t i = 0; i < nsteps; i++) {\n//                    for (size_t j = 0; j < nchannels; j++) {\n//                        // ux.\n//                        up_bound[2 * nchannels * i + 2 * j] = opt_.max_amp * 2 * _pi;\n//                        low_bound[2 * nchannels * i + 2 * j] = -opt_.max_amp * 2 * _pi;\n//\n//                        // uy.\n//                        up_bound[2 * nchannels * i + 2 * j + 1] = opt_.max_amp * 2 * _pi;\n//                        low_bound[2 * nchannels * i + 2 * j + 1] = -opt_.max_amp * 2 * _pi;\n//                    }\n//                }\n//\n//            opt.set_upper_bounds(up_bound);\n//            opt.set_lower_bounds(low_bound);\n//        }\n//            break;\n//            /*case nlopt::LD_MMA: {\n//                amp_constraint_data data = { 0, 0, opt_rf_.nchannels, opt_rf_.max_amp * 2 * _pi };\n//                for (size_t i = 0; i < opt_rf_.nsteps; i++) {\n//                    for (size_t j = 0; j < opt_rf_.nchannels; j++) {\n//                        data.i = i;\n//                        data.j = j;\n//                        opt.add_inequality_constraint(amplitude_constraint, &data, opt_.opt_f);\n//                    }\n//                }\n//            }\n//            break;*/\n//        default:break;\n//    }\n//}\n\n\nvoid tf_opt::cartesian2polar(double amp, double phase, double gx, double gy, double &g_amp, double &g_phase) {\n  double ux = amp * cos(phase);\n  double uy = amp * sin(phase);\n  g_amp = gx * ux + gy * uy;\n  g_amp /= amp;\n  g_phase = -gx * uy + gy * ux;\n}\n\n//double tf_opt::amplitude_constraint(unsigned n, const double *x, double *grad, void *data) {\n//    amp_constraint_data *d = reinterpret_cast<amp_constraint_data *>(data);\n//\n//    double ux = x[2 * d->chs * d->i + 2 * d->j];\n//    double uy = x[2 * d->chs * d->i + 2 * d->j + 1];\n//\n//    return ux * ux + uy * uy - d->amp * d->amp;\n//}\n\n\n//double tf_opt::objfunc_broadband(const std::vector<double> &x, std::vector<double> &grad) {\n//    rf_->update_raw_data(x.data());\n//    int N = superop_.L0s.size();\n//    vec phi = vec::Zero(N);\n//\n//    size_t nsteps = rf_->get_steps();\n//    size_t nchannels = rf_->get_channels();\n//    double dt = rf_->width_in_ms() * 1e-3 / double(nsteps); // into s.\n//\n//#pragma omp parallel for\n//    for (int p = 0; p < N; p++) {\n//        int id = omp_get_thread_num();\n//        traj_omp_[id].forward[0] = init_state_;\n//        traj_omp_[id].backward[nsteps] = targ_list_[p];\n//        //std::cout << id << \"\\n\";\n//        sp_cx_mat L;\n//        sp_cx_mat L0 = superop_.L0s[p] + ci * superop_.R;\n//        double kx = 1, ky = 1;\n//        sp_cx_vec rho = traj_omp_[id].forward[0];\n//        for (size_t i = 0; i < nsteps; i++) {\n//            L = L0;\n//            for (size_t j = 0; j < nchannels; j++)\n//                L += update_rf_ham(x.data(), i, j, nchannels, kx, ky);\n//            traj_omp_[id].forward[i + 1] = ssl::spinsys::step(rho, L, dt);\n//            rho = traj_omp_[id].forward[i + 1];\n//        }\n//        rho = traj_omp_[id].backward[nsteps];\n//        for (int i = nsteps - 1; i >= 0; i--) {\n//            L = L0.adjoint();\n//            for (size_t j = 0; j < nchannels; j++)\n//                L += update_rf_ham(x.data(), i, j, nchannels, kx, ky);\n//            traj_omp_[id].backward[i] = ssl::spinsys::step(rho, L, -dt);\n//            rho = traj_omp_[id].backward[i];\n//        }\n//        sp_cx_mat Gx, Gy, tmp;\n//        int k = 0;\n//        for (size_t i = 0; i < nsteps; i++) {\n//            L = L0;\n//            for (size_t j = 0; j < nchannels; j++)\n//                L += update_rf_ham(x.data(), i, j, nchannels, kx, ky);\n//            tmp = traj_omp_[id].backward[i + 1].adjoint() * ssl::spinsys::propagator(L, dt);\n//            for (size_t j = 0; j < nchannels; j++) {\n//                Gx = propagator_derivative(L, superop_.rf_ctrl.Lx[j], dt);\n//                Gy = propagator_derivative(L, superop_.rf_ctrl.Ly[j], dt);\n//\n//                superop_.grad_bb[p][k] = traced(tmp * Gx * traj_omp_[id].forward[i]).real();\n//                superop_.grad_bb[p][k + 1] = traced(tmp * Gy * traj_omp_[id].forward[i]).real();\n//                k += 2;\n//            }\n//        }\n//        phi[p] = transfer_fidelity(traj_omp_[id].forward[nsteps], targ_list_[p]);\n//        /// transfer_fidelity(targ_list_[p], targ_list_[p]);\n//    } // end parallel for.\n//\n//    double val = phi.sum() / (double) N;\n//    double alpha = 0;\n//\n//    int k = 0;\n//    for (size_t i = 0; i < nsteps; i++) {\n//        for (size_t j = 0; j < nchannels; j++) {\n//            double gx = 0;\n//            double gy = 0;\n//            for (int p = 0; p < N; p++) {\n//                gx += superop_.grad_bb[p][k];\n//                gy += superop_.grad_bb[p][k + 1];\n//            }\n//            grad[k] = gx / (double) N;\n//            grad[k + 1] = gy / (double) N;\n//\n//            //double gxx = grad[k];\n//            //double gyy = grad[k + 1];\n//\n//            //if (opt_rf_.rf_mode == _amp_phase)  // Translate the control gradient into phase gradient\n//            //cartesian2polar(x[k], x[k + 1], gxx, gyy, grad[k], grad[k + 1]);\n//\n//            // rf power reduction.\n//            /*double ux, uy;\n//            ux = x[2 * opt_rf_.nchannels * i + 2 * j];\n//            uy = x[2 * opt_rf_.nchannels * i + 2 * j + 1];\n//            grad[k] += 2.0 * alpha*ux*opt_rf_.dt;\n//            grad[k+1] += 2.0 * alpha*uy*opt_rf_.dt;*/\n//\n//            k += 2;\n//        }\n//    }\n//\n//    double phi_rf = rf_->average_power();\n//    double PHI1 = val;\n//    double PHI2 = alpha * phi_rf * dt;\n//    std::cout << boost::format(\"==> %04d  [%.4f] [%.4f]\\n\") % (++opt_.iter_count) % PHI1 % PHI2;\n//    opt_.vf.push_back(PHI1 - PHI2);\n//    return (PHI1 - PHI2);\n//}\nsp_cx_mat tf_opt::update_rf_ham(const double *x,\n                                size_t step,\n                                size_t channel,\n                                size_t nchannels,\n                                double kx,\n                                double ky) const {\n  double ux = x[2 * nchannels * step + 2 * channel];\n  double uy = x[2 * nchannels * step + 2 * channel + 1];\n\n  /*if (opt_rf_.rf_mode ==_amp_phase) {\n      double uxx = ux*cos(uy);\n      double uyy = ux*sin(uy);\n      ux = uxx;\n      uy = uyy;\n  }*/\n  // Rf inhom\n  ux *= kx;\n  uy *= ky;\n  return ux * superop_.rf_ctrl.Lx[channel] + uy * superop_.rf_ctrl.Ly[channel];\n}\n}\n\n}\n#endif  // TENSORFLOW_ENABLED\n", "meta": {"hexsha": "d0f2ac5e0dcf5ab0f575282ee6c248525768ca79", "size": 36504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kernel/oc/tf_opt.cpp", "max_stars_repo_name": "spin-scenario/spin-scenario", "max_stars_repo_head_hexsha": "1872b30cb229fd28033181568ffbc800f45d8a7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:47:03.000Z", "max_issues_repo_path": "src/kernel/oc/tf_opt.cpp", "max_issues_repo_name": "spin-scenario/spin-scenario", "max_issues_repo_head_hexsha": "1872b30cb229fd28033181568ffbc800f45d8a7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T03:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T15:23:18.000Z", "max_forks_repo_path": "src/kernel/oc/tf_opt.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": 37.0598984772, "max_line_length": 159, "alphanum_fraction": 0.5751698444, "num_tokens": 10802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.03161876532954494, "lm_q1q2_score": 0.012760285643041595}}
{"text": "/*\nMIT License\n\nCopyright (c) 2020 Rik Baehnemann, ASL, ETH Zurich, Switzerland\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"fm_trajectories/strip_trajectory.h\"\n\n#include <angles/angles.h>\n#include <Eigen/Geometry>\n#include <cmath>\n\nnamespace fm_trajectories {\n\nstd::vector<Eigen::Vector3d>\nStripTrajectory::Settings::computeVerticesFromSettings(\n    double A_east, double A_north, double delta_deg, double a, double h_A_abs,\n    double h_B_rel, double offset) const {\n  // Express strip edge without changed heading.\n  Eigen::Vector3d v_a(a, 0.0, h_B_rel);\n\n  // Change heading.\n  double delta = angles::from_degrees(delta_deg);\n  Eigen::Quaterniond q_heading(\n      Eigen::AngleAxisd(delta, Eigen::Vector3d::UnitZ()));\n  v_a = q_heading * v_a;\n\n  std::vector<Eigen::Vector3d> vertices(2);\n  vertices[0] << A_east, A_north, h_A_abs;\n  vertices[1] = vertices[0] + v_a;\n\n  // Add perpendicular offset.\n  Eigen::Vector3d v_offset = offset * Eigen::Vector3d::UnitY();\n  v_offset = q_heading * v_offset;\n  vertices[0] += v_offset;\n  vertices[1] += v_offset;\n\n  return vertices;\n}\n\nStripTrajectory::StripTrajectory(\n    const std::shared_ptr<StripTrajectory::Settings>& settings)\n    : PolygonTrajectory(settings) {}\n\nbool StripTrajectory::toYaml(YAML::Node* node) {\n  CHECK_NOTNULL(node);\n  *node = YAML::Node();\n\n  Eigen::Vector3d A_wgs84;\n  if (!geotf_.convert(\n          \"enu\",\n          Eigen::Vector3d(\n              std::static_pointer_cast<StripTrajectory::Settings>(settings_)\n                  ->A_east,\n              std::static_pointer_cast<StripTrajectory::Settings>(settings_)\n                  ->A_north,\n              std::static_pointer_cast<StripTrajectory::Settings>(settings_)\n                  ->h_A_abs),\n          \"wgs84\", &A_wgs84))\n    return false;\n\n  (*node)[\"A_lat\"] = A_wgs84.x();\n  (*node)[\"A_lon\"] = A_wgs84.y();\n  (*node)[\"delta_deg\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)->delta_deg;\n  (*node)[\"a\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)->a;\n  (*node)[\"velocity\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)->velocity;\n  (*node)[\"h_A_abs\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)->h_A_abs;\n  (*node)[\"h_B_rel\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)->h_B_rel;\n  (*node)[\"offset\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)->offset;\n  (*node)[\"offset_heading_deg\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)\n          ->offset_heading_deg;\n  (*node)[\"start_vertex\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)\n          ->start_vertex;\n  (*node)[\"num_edges\"] =\n      std::static_pointer_cast<StripTrajectory::Settings>(settings_)->num_edges;\n  (*node)[\"trajectory_type\"] = static_cast<int>(TrajectoryType::Strip);\n\n  return true;\n}\n\n}  // namespace fm_trajectories\n", "meta": {"hexsha": "8f9c859e1470e8fcf7893c1482db7cd71fcf22de", "size": 3923, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/fm_trajectories/src/strip_trajectory.cc", "max_stars_repo_name": "ethz-asl/mav_findmine", "max_stars_repo_head_hexsha": "2835995ace0a20a30f20812437b1b066428253a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-25T03:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T08:39:48.000Z", "max_issues_repo_path": "libs/fm_trajectories/src/strip_trajectory.cc", "max_issues_repo_name": "ethz-asl/mav_findmine", "max_issues_repo_head_hexsha": "2835995ace0a20a30f20812437b1b066428253a9", "max_issues_repo_licenses": ["MIT"], "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/fm_trajectories/src/strip_trajectory.cc", "max_forks_repo_name": "ethz-asl/mav_findmine", "max_forks_repo_head_hexsha": "2835995ace0a20a30f20812437b1b066428253a9", "max_forks_repo_licenses": ["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.3240740741, "max_line_length": 80, "alphanum_fraction": 0.7132296712, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.02675928260333174, "lm_q1q2_score": 0.012752929565810135}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * DM20-0442\n */\n\n/**\n * Implementations of all GraphBLAS functions optimized for the sequential\n * (CPU) backend.\n */\n\n#pragma once\n\n#include <functional>\n#include <utility>\n#include <vector>\n#include <iterator>\n#include <iostream>\n#include <string>\n#include <graphblas/algebra.hpp>\n#include <graphblas/indices.hpp>\n#include <boost/container/vector.hpp>\n\n//****************************************************************************\n\nnamespace grb\n{\n    namespace backend\n    {\n        template <typename ScalarT>\n        void print_vec(std::ostream &os, std::string label,\n                       std::vector<std::tuple<IndexType, ScalarT> > vec)\n        {\n            os << label << \" \";\n            bool first = true;\n\n            for (auto&& [idx, val] : vec)\n            {\n                os << (!first ? \",\" : \" \") << idx << \":\" << val;\n                first = false;\n            }\n            os << std::endl;\n        }\n\n        //**********************************************************************\n\n        template <typename DstMatrixT,\n                  typename SrcMatrixT>\n        void sparse_copy(DstMatrixT &dstMatrix,\n                         SrcMatrixT const &srcMatrix)\n        {\n            using DstScalarType = typename DstMatrixT::ScalarType;\n            std::vector<std::tuple<IndexType, DstScalarType> > dstRow;\n\n            // Copying removes the contents of the other matrix so clear it first.\n            dstMatrix.clear();\n\n            IndexType nrows(dstMatrix.nrows());\n            for (IndexType row_idx = 0; row_idx < nrows; ++row_idx)\n            {\n                auto&& srcRow = srcMatrix[row_idx];\n                dstRow.clear();\n\n                // We need to construct a new row with the appropriate cast!\n                for (auto&& [idx, srcVal] : srcRow)\n                {\n                    dstRow.emplace_back(idx, static_cast<DstScalarType>(srcVal));\n                }\n\n                if (!dstRow.empty())\n                    dstMatrix.setRow(row_idx, dstRow);\n            }\n        }\n\n        // @todo: Make a sparse copy where they are the same type for efficiency\n\n        //**********************************************************************\n        /// Advance the provided iterator until the value evaluates to true or\n        /// the end is reached.\n        ///\n        /// Iter is iterator to std::vector<std::tuple<grb::IndexType,T>>\n        template <typename Iter>\n        void increment_until_true(Iter &iter, Iter const &iter_end)\n        {\n            while ((iter != iter_end) && !(std::get<1>(*iter))) {\n                ++iter;\n            }\n        }\n\n        //**********************************************************************\n        /// Increment the provided iterator while the index is less than the\n        /// provided index\n        ///\n        /// @retval true   If targeted index is found (false could mean end is\n        ///                reached first or targeted index was not present\n        template <typename Iter>\n        bool increment_while_below(Iter                 &iter,\n                                   Iter           const &iter_end,\n                                   grb::IndexType        target_idx)\n        {\n            while ((iter != iter_end) && (std::get<0>(*iter) < target_idx))\n            {\n                ++iter;\n            }\n            return ((iter != iter_end) && (std::get<0>(*iter) == target_idx));\n        }\n\n        //**********************************************************************\n        /// Increment the provided iterator while the index is less than the\n        /// provided index and append any elements to vec along the way\n        template <typename Iter, typename V>\n        void increment_and_add_while_below(Iter                 &iter,\n                                           Iter          const  &iter_end,\n                                           grb::IndexType        idx,\n                                           V                    &vec)\n        {\n            while ((iter != iter_end) && (std::get<0>(*iter) < idx)) {\n                vec.push_back(*iter);  // anything more efficient?\n                ++iter;\n            }\n        }\n\n        //**********************************************************************\n        /// Perform the dot product of a row of a matrix with a sparse vector\n        /// without pulling the indices out of the vector first.\n        template <typename D1, typename D2, typename D3, typename SemiringT>\n        bool dot2(D3                                                &ans,\n                  std::vector<std::tuple<grb::IndexType,D1> > const &A_row,\n                  std::vector<bool>                           const &u_bitmap,\n                  std::vector<D2>                             const &u_vals,\n                  grb::IndexType                                     u_nvals,\n                  SemiringT                                          op)\n        {\n            bool value_set(false);\n            ans = op.zero();\n\n            if ((u_nvals == 0) || A_row.empty())\n            {\n                return value_set;\n            }\n\n            // find first stored value in u\n            grb::IndexType u_idx(0);\n            while (!u_bitmap[u_idx]) ++u_idx; // skip unstored elements\n\n            // pull first value out of the row\n            auto A_iter = A_row.begin();\n            D1 a_val;\n            grb::IndexType a_idx;\n\n            // loop through both ordered sets to compute sparse dot prod\n            while ((A_iter != A_row.end()) && (u_idx < u_vals.size()))\n            {\n                std::tie(a_idx, a_val) = *A_iter;\n                if (u_idx == a_idx)\n                {\n                    if (value_set)\n                    {\n                        ans = op.add(ans, op.mult(a_val, u_vals[u_idx]));\n                    }\n                    else\n                    {\n                        ans = op.mult(a_val, u_vals[u_idx]);\n                        value_set = true;\n                    }\n\n                    do { ++u_idx; } while ((u_idx < u_vals.size()) && !u_bitmap[u_idx]);\n                    ++A_iter;\n                }\n                else if (u_idx > a_idx)\n                {\n                    ++A_iter;\n                }\n                else\n                {\n                    do { ++u_idx; } while ((u_idx < u_vals.size()) && !u_bitmap[u_idx]);\n                }\n            }\n\n            return value_set;\n        }\n\n        //************************************************************************\n        /// A dot product of two sparse vectors (vectors<tuple(index,value)>)\n        template <typename D1, typename D2, typename D3, typename SemiringT, typename allocator_t>\n        bool dot(D3                                                &ans,\n                 boost::container::vector<std::tuple<grb::IndexType,D1>, allocator_t > const &vec1,\n                 boost::container::vector<std::tuple<grb::IndexType,D2>, allocator_t > const &vec2,\n                 SemiringT                                          op)\n        {\n            bool value_set(false);\n\n            if (vec2.empty() || vec1.empty())\n            {\n                return value_set;\n            }\n\n            // point to first entries of the vectors\n            auto v1_it = vec1.begin();\n            auto v2_it = vec2.begin();\n\n            // loop through both ordered sets to compute sparse dot prod\n            while ((v1_it != vec1.end()) && (v2_it != vec2.end()))\n            {\n                if (std::get<0>(*v2_it) == std::get<0>(*v1_it))\n                {\n                    if (value_set)\n                    {\n                        ans = op.add(ans, op.mult(std::get<1>(*v1_it),\n                                                  std::get<1>(*v2_it)));\n                    }\n                    else\n                    {\n                        ans = op.mult(std::get<1>(*v1_it),\n                                      std::get<1>(*v2_it));\n                        value_set = true;\n                    }\n\n                    ++v2_it;\n                    ++v1_it;\n                }\n                else if (std::get<0>(*v2_it) > std::get<0>(*v1_it))\n                {\n                    ++v1_it;\n                }\n                else\n                {\n                    ++v2_it;\n                }\n            }\n\n            return value_set;\n        }\n\n        //************************************************************************\n        /// A dot product of two sparse vectors (vectors<tuple(index,value)>)\n        template <typename D1, typename D2, typename D3, typename SemiringT>\n        bool dot_rev(D3                                                &ans,\n                     std::vector<std::tuple<grb::IndexType,D1> > const &vec2,\n                     std::vector<std::tuple<grb::IndexType,D2> > const &vec1,\n                     SemiringT                                          op)\n        {\n            bool value_set(false);\n\n            if (vec2.empty() || vec1.empty())\n            {\n                return value_set;\n            }\n\n            // point to first entries of the vectors\n            auto v1_it = vec1.begin();\n            auto v2_it = vec2.begin();\n\n            // loop through both ordered sets to compute sparse dot prod\n            while ((v1_it != vec1.end()) && (v2_it != vec2.end()))\n            {\n                if (std::get<0>(*v2_it) == std::get<0>(*v1_it))\n                {\n                    if (value_set)\n                    {\n                        ans = op.add(ans, op.mult(std::get<1>(*v2_it),\n                                                  std::get<1>(*v1_it)));\n                    }\n                    else\n                    {\n                        ans = op.mult(std::get<1>(*v2_it),\n                                      std::get<1>(*v1_it));\n                        value_set = true;\n                    }\n\n                    ++v2_it;\n                    ++v1_it;\n                }\n                else if (std::get<0>(*v2_it) > std::get<0>(*v1_it))\n                {\n                    ++v1_it;\n                }\n                else\n                {\n                    ++v2_it;\n                }\n            }\n\n            return value_set;\n        }\n\n        //************************************************************************\n        /// A reduction of a sparse vector (vector<tuple(index,value)>) using a\n        /// binary op or a monoid.\n        template <typename D1, typename D3, typename BinaryOpT, typename allocator_t>\n        bool reduction(\n            D3                                                &ans,\n            boost::container::vector<std::tuple<grb::IndexType,D1>, allocator_t > const &vec,\n            BinaryOpT                                          op)\n        {\n            if (vec.empty())\n            {\n                return false;\n            }\n\n            using D3ScalarType =\n                decltype(op(std::declval<D1>(), std::declval<D1>()));\n            D3ScalarType tmp;\n\n            if (vec.size() == 1)\n            {\n                tmp = static_cast<D3ScalarType>(std::get<1>(vec[0]));\n            }\n            else\n            {\n                /// @note Since op is associative and commutative left to right\n                /// ordering is not strictly required.\n                tmp = op(std::get<1>(vec[0]), std::get<1>(vec[1]));\n\n                /// @todo replace with call to std::reduce?\n                for (size_t idx = 2; idx < vec.size(); ++idx)\n                {\n                    tmp = op(tmp, std::get<1>(vec[idx]));\n                }\n            }\n\n            ans = static_cast<D3>(tmp);\n            return true;\n        }\n\n        //**********************************************************************\n        /// Apply element-wise operation to union of 2 sparse vectors, store in 3rd.\n        /// ans = op(vec1, vec2)\n        ///\n        /// @note ans must be a unique vector from either vec1 or vec2\n        template <typename D1, typename D2, typename D3, typename BinaryOpT>\n        void ewise_or(D1       &ans,\n                      D2 const &vec1,\n                      D3 const &vec2,\n                      BinaryOpT op)\n        {\n            if (((void*)&ans == (void*)&vec1) || ((void*)&ans == (void*)&vec2))\n            {\n                throw PanicException(\n                    \"backend::ewise_or called with same vector for input and output.\");\n            }\n\n            ans.clear();\n\n            // point to first entries of the vectors\n            auto v1_it = vec1.begin();\n            auto v2_it = vec2.begin();\n            using scType = std::tuple_element_t<1, typename D3::value_type>;\n\n            // loop through both ordered sets to compute ewise_or\n            while ((v1_it != vec1.end()) || (v2_it != vec2.end()))\n            {\n                if ((v1_it != vec1.end()) && (v2_it != vec2.end()))\n                {\n                    auto&& [v1_idx, v1_val] = *v1_it;\n                    auto&& [v2_idx, v2_val] = *v2_it;\n                    //std::tie(v1_idx, v1_val) = *v1_it;\n                    //std::tie(v2_idx, v2_val) = *v2_it;\n\n                    if (v2_idx == v1_idx)\n                    {\n                        ans.emplace_back(v1_idx,\n                                         static_cast<scType>(op(v1_val, v2_val)));\n\n                        ++v2_it;\n                        ++v1_it;\n                    }\n                    else if (v2_idx > v1_idx)\n                    {\n                        ans.emplace_back(v1_idx, static_cast<scType>(v1_val));\n                        ++v1_it;\n                    }\n                    else\n                    {\n                        ans.emplace_back(v2_idx, static_cast<scType>(v2_val));\n                        ++v2_it;\n                    }\n                }\n                else if (v1_it != vec1.end())\n                {\n                    ans.emplace_back(std::get<0>(*v1_it),\n                                     static_cast<scType>(std::get<1>(*v1_it)));\n                    ++v1_it;\n                }\n                else // v2_it != vec2.end())\n                {\n                    ans.emplace_back(std::get<0>(*v2_it),\n                                     static_cast<scType>(std::get<1>(*v2_it)));\n                    ++v2_it;\n                }\n            }\n        }\n\n        //********************************************************************\n        // ALL SUPPORT\n        // This is where we turn alls into the correct range\n\n        template <typename SequenceT>\n        bool searchIndices(SequenceT seq, IndexType n)\n        {\n            for (auto it : seq)\n            {\n                if (it == n) return true;\n            }\n            return false;\n        }\n\n        bool searchIndices(AllIndices seq, IndexType n)\n        {\n            return true;\n        }\n\n        //**********************************************************************\n        /// Apply element-wise operation to union on sparse vectors.\n        /// Indices in the stencil indicate where elements of vec2 should be\n        /// used (whether there is a stored value or not); otherwise the value\n        /// in vec1 should be taken.  Note: that it is assumed that if a value\n        /// is stored in vec2 then the corresponding location is contained in\n        /// stencil indices.\n        ///\n        /// Truth table (for each element, i, of the answer, where '-' means\n        /// no stored value):\n        ///\n        ///  vec1_i   vec2   s_i   ans_i\n        ///    -        -     -      -\n        ///    -        -     x      -\n        ///    -        x --> x    vec2_i\n        ///    x        -     -    vec1_i\n        ///    x        -     x      -    (take vec1_i which is no stored value)\n        ///    x        x --> x    vec1_i\n        ///\n        /// \\tparam D1\n        /// \\tparam D2\n        /// \\tparam D3\n        /// \\tparam SequenceT  Could be a out of order subset of indices\n        ///\n        /// \\param ans   A row of the answer (Z or z), starts empty\n        /// \\param vec1  A row of the output container (C or w), indices increasing order\n        /// \\param vec2  A row of the T (or t) container, indices in increasing order\n        /// \\param stencil_indices  Assumed to not be in order\n        ///\n        template <typename D1, typename D2, typename D3, typename SequenceT>\n        void ewise_or_stencil(\n            std::vector<std::tuple<grb::IndexType,D3> >       &ans,\n            std::vector<std::tuple<grb::IndexType,D1> > const &vec1,\n            std::vector<std::tuple<grb::IndexType,D2> > const &vec2,\n            SequenceT                                          stencil_indices)\n        {\n            ans.clear();\n\n            //auto stencil_it = stencil_indices.begin();\n            //if (v1_it)\n            //while ((stencil_it != stencil_indices.end()) &&\n            //       (*stencil_it < std::get<0>(*v1_it)))\n            //{\n            //    ++stencil_it;\n            //}\n\n            D1 v1_val;\n            D2 v2_val;\n            grb::IndexType v1_idx, v2_idx;\n\n            // loop through both ordered sets to compute ewise_or\n            auto v1_it = vec1.begin();\n            auto v2_it = vec2.begin();\n            while ((v1_it != vec1.end()) || (v2_it != vec2.end()))\n            {\n                if ((v1_it != vec1.end()) && (v2_it != vec2.end()))\n                {\n                    std::tie(v1_idx, v1_val) = *v1_it;\n                    std::tie(v2_idx, v2_val) = *v2_it;\n\n                    // If v1 and v2 both have stored values, it is assumed index\n                    // is in stencil_indices so v2 should be stored\n                    if (v2_idx == v1_idx)\n                    {\n                        ans.emplace_back(v2_idx, static_cast<D3>(v2_val));\n\n                        ++v2_it;\n                        ++v1_it;\n                    }\n                    // In this case v1 has a value and not v2.  We need to search\n                    // stencil indices to see if index is present\n                    else if (v1_idx < v2_idx) // advance v1 and annihilate\n                    {\n                        if (!searchIndices(stencil_indices, v1_idx))\n                        {\n                            ans.emplace_back(v1_idx, static_cast<D3>(v1_val));\n                        }\n                        ++v1_it;\n                    }\n                    else\n                    {\n                        //std::cerr << \"Copying v2, Advancing v2_it\" << std::endl;\n                        ans.emplace_back(v2_idx, static_cast<D3>(v2_val));\n                        ++v2_it;\n                    }\n                }\n                else if (v1_it != vec1.end())  // vec2 exhausted\n                {\n                    std::tie(v1_idx, v1_val) = *v1_it;\n\n                    if (!searchIndices(stencil_indices, v1_idx))\n                    {\n                        ans.emplace_back(v1_idx, static_cast<D3>(v1_val));\n                    }\n                    ++v1_it;\n                }\n                else // v2_it != vec2.end()) and vec1 exhausted\n                {\n                    std::tie(v2_idx, v2_val) = *v2_it;\n                    ans.emplace_back(v2_idx, static_cast<D3>(v2_val));\n                    ++v2_it;\n                }\n            }\n        }\n\n\n        //**********************************************************************\n        template <typename ZScalarT,\n                  typename WVectorT,\n                  typename TScalarT,\n                  typename SequenceT,\n                  typename BinaryOpT >\n        void ewise_or_stencil_opt_accum_1D(\n            std::vector<std::tuple<grb::IndexType,ZScalarT>>       &z,\n            WVectorT const                                         &w,\n            std::vector<std::tuple<grb::IndexType,TScalarT>> const &t,\n            SequenceT const                                        &indices,\n            BinaryOpT                                               accum)\n        {\n            // If there is an accumulate operations, do nothing with the stencil\n            ewise_or(z, w.getContents(), t, accum);\n        }\n\n        //**********************************************************************\n        template <typename ZScalarT,\n                  typename WVectorT,\n                  typename TScalarT,\n                  typename SequenceT>\n        void ewise_or_stencil_opt_accum_1D(\n            std::vector<std::tuple<grb::IndexType,ZScalarT>>       &z,\n            WVectorT const                                         &w,\n            std::vector<std::tuple<grb::IndexType,TScalarT>> const &t,\n            SequenceT const                                        &indices,\n            grb::NoAccumulate)\n        {\n            // If there is no accumulate we need to annihilate stored values\n            // in w that fall in the stencil\n            ewise_or_stencil(z, w.getContents(), t, indices);\n        }\n\n\n        //**********************************************************************\n        template < typename ZMatrixT,\n                   typename CMatrixT,\n                   typename TMatrixT,\n                   typename RowSequenceT,\n                   typename ColSequenceT,\n                   typename BinaryOpT >\n        void ewise_or_stencil_opt_accum(ZMatrixT           &Z,\n                                        CMatrixT     const &C,\n                                        TMatrixT     const &T,\n                                        RowSequenceT const &row_indices,\n                                        ColSequenceT const &col_indices,\n                                        BinaryOpT           accum)\n        {\n            // If there is an accumulate operation, do nothing with the stencil\n            using ZScalarType = typename ZMatrixT::ScalarType;\n            using ZRowType = std::vector<std::tuple<IndexType,ZScalarType> >;\n\n            ZRowType tmp_row;\n            IndexType nRows(Z.nrows());\n\n            for (IndexType row_idx = 0; row_idx < nRows; ++row_idx)\n            {\n                ewise_or(tmp_row, C[row_idx], T[row_idx], accum);\n                Z.setRow(row_idx, tmp_row);\n            }\n        }\n\n        //**********************************************************************\n        template < typename ZMatrixT,\n                   typename CMatrixT,\n                   typename TMatrixT,\n                   typename RowSequenceT,\n                   typename ColSequenceT>\n        void ewise_or_stencil_opt_accum(ZMatrixT           &Z,\n                                        CMatrixT     const &C,\n                                        TMatrixT     const &T,\n                                        RowSequenceT const &row_indices,\n                                        ColSequenceT const &col_indices,\n                                        grb::NoAccumulate)\n        {\n            // If there is no accumulate, we need to annihilate stored values\n            // in C that fall in the stencil\n            using ZScalarType = typename ZMatrixT::ScalarType;\n            using ZRowType = std::vector<std::tuple<IndexType,ZScalarType> >;\n\n            ZRowType tmp_row;\n            IndexType nRows(Z.nrows());\n\n            for (IndexType row_idx = 0; row_idx < nRows; ++row_idx)\n            {\n                if (searchIndices(row_indices, row_idx))\n                {\n                    // Row Stenciled. merge C, T, using col stencil\\n\";\n                    ewise_or_stencil(tmp_row, C[row_idx], T[row_idx],\n                                     col_indices);\n                    Z.setRow(row_idx, tmp_row);\n                }\n                else\n                {\n                    // Row not stenciled.  Take row from C only\n                    // There should be nothing in T for this row\n                    Z.setRow(row_idx, C[row_idx]);\n                }\n            }\n        }\n\n        //**********************************************************************\n        template < typename ZMatrixT,\n                   typename CMatrixT,\n                   typename TMatrixT,\n                   typename BinaryOpT >\n        void ewise_or_opt_accum(ZMatrixT         &Z,\n                                CMatrixT const   &C,\n                                TMatrixT const   &T,\n                                BinaryOpT         accum)\n        {\n            using ZScalarType = typename ZMatrixT::ScalarType;\n            using ZRowType = std::vector<std::tuple<IndexType,ZScalarType> >;\n\n            ZRowType tmp_row;\n            IndexType nRows(Z.nrows());\n\n            for (IndexType row_idx = 0; row_idx < nRows; ++row_idx)\n            {\n                ewise_or(tmp_row, C[row_idx], T[row_idx], accum);\n                Z.setRow(row_idx, tmp_row);\n            }\n        }\n\n        //**********************************************************************\n\n        // Specialized version that gets used when we don't have an accumulator\n        template < typename ZMatrixT,\n                   typename CMatrixT,\n                   typename TMatrixT>\n        void ewise_or_opt_accum(ZMatrixT               &Z,\n                                CMatrixT          const &C,\n                                TMatrixT          const &T,\n                                grb::NoAccumulate )\n        {\n            sparse_copy(Z, T);\n        }\n\n        //**********************************************************************\n        template <typename R1,\n                  typename R2,\n                  typename R3,\n                  typename R4>\n        void ewise_or_opt_accum_1D(\n            R1       &z,\n            R2 const &w,\n            R3 const &t,\n            R4 accum)\n        {\n            //z.clear();\n            ewise_or(z, w.getContents(), t, accum);\n        }\n\n        //**********************************************************************\n        // Specialized version that gets used when we don't have an accumulator\n        template <typename ZScalarT,\n                  typename WVectorT,\n                  typename TScalarT>\n        void ewise_or_opt_accum_1D(\n            std::vector<std::tuple<grb::IndexType,ZScalarT>>       &z,\n            WVectorT const                                         &w,\n            std::vector<std::tuple<grb::IndexType,TScalarT>> const &t,\n            grb::NoAccumulate )\n        {\n            //sparse_copy(z, t);\n            for (auto tupl: t)\n            {\n                z.emplace_back(std::get<0>(tupl),\n                               static_cast<ZScalarT>(std::get<1>(tupl)));\n            }\n        }\n\n        //**********************************************************************\n        template <typename ZScalarT,\n                  typename WScalarT,\n                  typename TScalarT,\n                  typename BinaryOpT>\n        void opt_accum_scalar(ZScalarT       &z,\n                              WScalarT const &w,\n                              TScalarT const &t,\n                              BinaryOpT       accum)\n        {\n            z = static_cast<ZScalarT>(accum(w, t));\n        }\n\n        //**********************************************************************\n        // Specialized version that gets used when we don't have an accumulator\n        template <typename ZScalarT,\n                  typename WScalarT,\n                  typename TScalarT>\n        void opt_accum_scalar(ZScalarT                &z,\n                              WScalarT          const &w,\n                              TScalarT          const &t,\n                              grb::NoAccumulate        accum)\n        {\n            z = static_cast<ZScalarT>(t);\n        }\n\n        //************************************************************************\n        /// Apply element-wise operation to intersection of sparse vectors.\n        template <typename D1, typename D2, typename D3, typename BinaryOpT>\n        void ewise_and(std::vector<std::tuple<grb::IndexType,D3> >       &ans,\n                       std::vector<std::tuple<grb::IndexType,D1> > const &vec1,\n                       std::vector<std::tuple<grb::IndexType,D2> > const &vec2,\n                       BinaryOpT                                          op)\n        {\n            ans.clear();\n\n            // todo: early exit if either input vector is empty?\n\n            // point to first entries of the vectors\n            auto v1_it = vec1.begin();\n            auto v2_it = vec2.begin();\n\n            // loop through both ordered sets to compute ewise_or\n            while ((v1_it != vec1.end()) && (v2_it != vec2.end()))\n            {\n                if (std::get<0>(*v2_it) == std::get<0>(*v1_it))\n                {\n                    ans.emplace_back(std::get<0>(*v1_it),\n                                     static_cast<D3>(op(std::get<1>(*v1_it),\n                                                        std::get<1>(*v2_it))));\n\n                    ++v2_it;\n                    ++v1_it;\n                }\n                else if (std::get<0>(*v2_it) > std::get<0>(*v1_it))\n                {\n                    ++v1_it;\n                }\n                else\n                {\n                    ++v2_it;\n                }\n            }\n        }\n\n        //**********************************************************************\n        //**********************************************************************\n        /**\n         * This merges the values of C and Z into the result vector based on the\n         * values of the mask.\n         *\n         * If outp == REPLACE:\n         *\n         * \\f[ L(C) = {(i,j,Zij):(i,j) \\in (ind(Z) \\cap ind(M))} \\f]\n         *\n         * If outp == MERGE:\n         *\n         * \\f[ L(C) = {(i,j,Zij):(i,j) \\in (ind(C) \\cap ind(\\neg M))} \\cup\n         *            {(i,j,Zij):(i,j) \\in (ind(Z) \\cap ind(\\neg M))} \\f]\n         *\n         * @tparam CScalarT The scalar type of the C vector input AND result.\n         * @tparam ZScalarT The scalar type of the Z vector input.\n         * @tparam MScalarT The scalar type of the mask vector.\n         *\n         * @param result   Result vector.  We clear this first.\n         * @param c_vec    The original c values that may be carried through.\n         * @param z_vec    The new values to insert/overlay.\n         * @param mask_vec The mask which specifies which values to use.\n         * @param outp     If REPLACE, we should always clear the values specified\n         *                 by the mask regardless if they are overlayed.\n         */\n        template < typename R1,\n                   typename R2,\n                   typename R3,\n                   typename R4>\n        void apply_with_mask(\n            R1          &result,\n            R2 const    &c_vec,\n            R3 const    &z_vec,\n            R4 const    &mask_vec,\n            OutputControlEnum                                       outp)\n        {\n            using scType = std::tuple_element_t<1, typename R3::value_type>;\n            auto c_it = c_vec.begin();\n            auto z_it = z_vec.begin();\n            auto mask_it = mask_vec.begin();\n\n            result.clear();\n\n            // Design: This approach is driven by the mask.\n            while (mask_it != mask_vec.end())\n            {\n                // Make sure the mask is on a valid value\n                increment_until_true(mask_it, mask_vec.end());\n\n                // If we run out of mask, we are done!\n                if (mask_it == mask_vec.end())\n                {\n                    break;\n                }\n\n                // Get the mask location\n                auto mask_idx(std::get<0>(*mask_it));\n\n                // If outp==REPLACE, then we don't consider original C values.\n                // If outp==MERGE, then we want to keep C values outside the mask\n                // Any values in C \"outside\" the mask should now be applied\n                // So, we catch \"c\" up to the mask.  This is the intersection\n                // of C and !M.\n\n                if (outp == MERGE)\n                {\n                    // This is the part of (ind(C) \\cap int(\\not M)\n                    increment_and_add_while_below(c_it, c_vec.end(), mask_idx,\n                                                  result);\n                }\n\n                // \"Catch up\" the input to the mask.\n                if (increment_while_below(z_it, z_vec.end(), mask_idx))\n                {\n                    // Now, at the mask point add the value from Z if we have one.\n                    result.emplace_back(\n                        mask_idx, static_cast<scType>(std::get<1>(*z_it)));\n                }\n\n                // If there is a C here, skip it\n                if (c_it != c_vec.end())\n                {\n                    if (std::get<0>(*c_it) == mask_idx)\n                        ++c_it;\n                }\n\n                // Now move to the next mask entry.\n                ++mask_it;\n            } // while mask_it != end\n\n            // Now, we need to add the remaining C values beyond the mask\n            if (outp == MERGE)\n            {\n                // This is the part of (ind(C) \\cap int(\\not M)\n                while (c_it != c_vec.end())\n                {\n                    result.emplace_back(*c_it);\n                    ++c_it;\n                }\n            }\n        } // apply_with_mask\n\n        //**********************************************************************\n        // Matrix Mask Churn\n        //**********************************************************************\n\n        //**********************************************************************\n        // WARNING: costly\n        template <typename MatrixT>\n        decltype(auto)\n        get_structure_row(MatrixT const &mat, IndexType row_idx)\n        {\n            std::vector<std::tuple<IndexType, bool> > mask_tuples;\n            mask_tuples.reserve(mat.ncols() - mat[row_idx].size());\n\n            for (auto&& [ix, val] : mat[row_idx])\n            {\n                mask_tuples.emplace_back(ix, true);\n            }\n\n            return mask_tuples;\n        }\n\n        //**********************************************************************\n        // WARNING: costly\n        template <typename MatrixT>\n        decltype(auto)\n        get_complement_row(MatrixT const &mat, IndexType row_idx)\n        {\n            std::vector<std::tuple<IndexType, bool> > mask_tuples;\n            auto &row_tuples = mat[row_idx];\n            mask_tuples.reserve(mat.ncols() - row_tuples.size());\n            auto it = row_tuples.begin();\n\n            for (IndexType ix = 0; ix < mat.ncols(); ++ix)\n            {\n                if ((it == row_tuples.end()) || (ix < std::get<0>(*it)))\n                {\n                    mask_tuples.emplace_back(ix, true);\n                }\n                else\n                {\n                    if (static_cast<bool>(std::get<1>(*it)) == false)\n                    {\n                        mask_tuples.emplace_back(ix, true);\n                    }\n                    ++it;\n                }\n            }\n\n            return mask_tuples;\n        }\n\n        //**********************************************************************\n        // WARNING: costly\n        template <typename MatrixT>\n        decltype(auto)\n        get_structural_complement_row(MatrixT const &mat, IndexType row_idx)\n        {\n            std::vector<std::tuple<IndexType, bool> > mask_tuples;\n            auto &row_tuples = mat[row_idx];\n            mask_tuples.reserve(mat.ncols() - row_tuples.size());\n            auto it = row_tuples.begin();\n\n            for (IndexType ix = 0; ix < mat.ncols(); ++ix)\n            {\n                if ((it == row_tuples.end()) || (ix < std::get<0>(*it)))\n                {\n                    mask_tuples.emplace_back(ix, true);\n                }\n                else\n                {\n                    ++it;\n                }\n            }\n\n            return mask_tuples;\n        }\n\n        //**********************************************************************\n        // Matrix version\n        template < typename CMatrixT,\n                   typename ZMatrixT,\n                   typename MMatrixT>\n        void write_with_opt_mask(CMatrixT           &C,\n                                 ZMatrixT   const   &Z,\n                                 MMatrixT   const   &Mask,\n                                 OutputControlEnum   outp)\n        {\n            using CScalarType = typename CMatrixT::ScalarType;\n            using CRowType = std::vector<std::tuple<IndexType, CScalarType> >;\n\n            CRowType tmp_row;\n            IndexType nRows(C.nrows());\n            for (IndexType row_idx = 0; row_idx < nRows; ++row_idx)\n            {\n                apply_with_mask(tmp_row, C[row_idx], Z[row_idx],\n                                Mask[row_idx], outp);\n\n                // Now, set the new one.  Yes, we can optimize this later\n                C.setRow(row_idx, tmp_row);\n            }\n        }\n\n        //**********************************************************************\n        // Matrix version specialized for complement mask\n        template < typename CMatrixT,\n                   typename ZMatrixT,\n                   typename MMatrixT>\n        void write_with_opt_mask(\n            CMatrixT                                  &C,\n            ZMatrixT                            const &Z,\n            grb::MatrixComplementView<MMatrixT> const &Mask,\n            OutputControlEnum                          outp)\n        {\n            using CScalarType = typename CMatrixT::ScalarType;\n            using CRowType = std::vector<std::tuple<IndexType, CScalarType> >;\n\n            CRowType tmp_row;\n            IndexType nRows(C.nrows());\n            for (IndexType row_idx = 0; row_idx < nRows; ++row_idx)\n            {\n                apply_with_mask(tmp_row, C[row_idx], Z[row_idx],\n                                get_complement_row(Mask.m_mat, row_idx),\n                                outp);\n\n                // Now, set the new one.  Yes, we can optimize this later\n                C.setRow(row_idx, tmp_row);\n            }\n        }\n\n        //**********************************************************************\n        // Matrix version specialized for structure mask\n        template < typename CMatrixT,\n                   typename ZMatrixT,\n                   typename MMatrixT>\n        void write_with_opt_mask(\n            CMatrixT                                 &C,\n            ZMatrixT                           const &Z,\n            grb::MatrixStructureView<MMatrixT> const &Mask,\n            OutputControlEnum                         outp)\n        {\n            using CScalarType = typename CMatrixT::ScalarType;\n            using CRowType = std::vector<std::tuple<IndexType, CScalarType> >;\n\n            CRowType tmp_row;\n            IndexType nRows(C.nrows());\n            for (IndexType row_idx = 0; row_idx < nRows; ++row_idx)\n            {\n                apply_with_mask(tmp_row, C[row_idx], Z[row_idx],\n                                get_structure_row(Mask.m_mat, row_idx),\n                                outp);\n\n                // Now, set the new one.  Yes, we can optimize this later\n                C.setRow(row_idx, tmp_row);\n            }\n        }\n\n        //**********************************************************************\n        // Matrix version specialized for structural complement mask\n        template < typename CMatrixT,\n                   typename ZMatrixT,\n                   typename MMatrixT>\n        void write_with_opt_mask(\n            CMatrixT                                            &C,\n            ZMatrixT                                      const &Z,\n            grb::MatrixStructuralComplementView<MMatrixT> const &Mask,\n            OutputControlEnum                                    outp)\n        {\n            using CScalarType = typename CMatrixT::ScalarType;\n            using CRowType = std::vector<std::tuple<IndexType, CScalarType> >;\n\n            CRowType tmp_row;\n            IndexType nRows(C.nrows());\n            for (IndexType row_idx = 0; row_idx < nRows; ++row_idx)\n            {\n                apply_with_mask(tmp_row, C[row_idx], Z[row_idx],\n                                get_structural_complement_row(Mask.m_mat, row_idx),\n                                outp);\n\n                // Now, set the new one.  Yes, we can optimize this later\n                C.setRow(row_idx, tmp_row);\n            }\n        }\n\n        //**********************************************************************\n        // Matrix version specialized for no mask\n        template < typename CMatrixT,\n                   typename ZMatrixT >\n        void write_with_opt_mask(CMatrixT                   &C,\n                                 ZMatrixT           const   &Z,\n                                 grb::NoMask        const   &foo,\n                                 OutputControlEnum           outp)\n        {\n            sparse_copy(C, Z);\n        }\n\n        //**********************************************************************\n        // Vector Mask Churn\n        //**********************************************************************\n\n        //**********************************************************************\n        // WARNING: costly\n        template <typename VectorT>\n        decltype(auto)\n        get_structure_contents(VectorT const &vec)\n        {\n            std::vector<std::tuple<IndexType, bool> > mask_tuples;\n\n            for (auto [ix, val] : vec.getContents())\n            {\n                mask_tuples.emplace_back(ix, true);\n            }\n\n            return mask_tuples;\n        }\n\n        //**********************************************************************\n        // WARNING: costly\n        template <typename VectorT>\n        decltype(auto)\n        get_complement_contents(VectorT const &vec)\n        {\n            std::vector<std::tuple<IndexType, bool> > mask_tuples;\n            auto row_tuples(vec.getContents());\n            auto it = row_tuples.begin();\n\n            for (IndexType ix = 0; ix < vec.size(); ++ix)\n            {\n                if ((it == row_tuples.end()) || (ix < std::get<0>(*it)))\n                {\n                    mask_tuples.emplace_back(ix, true);\n                }\n                else\n                {\n                    if (static_cast<bool>(std::get<1>(*it)) == false)\n                    {\n                        mask_tuples.emplace_back(ix, true);\n                    }\n                    ++it;\n                }\n            }\n\n            return mask_tuples;\n        }\n\n        //**********************************************************************\n        // WARNING: costly\n        template <typename VectorT>\n        decltype(auto)\n        get_structural_complement_contents(VectorT const &vec)\n        {\n            std::vector<std::tuple<IndexType, bool> > mask_tuples;\n            auto row_tuples(vec.getContents());\n            auto it = row_tuples.begin();\n\n            for (IndexType ix = 0; ix < vec.size(); ++ix)\n            {\n                if ((it == row_tuples.end()) || (ix < std::get<0>(*it)))\n                {\n                    mask_tuples.emplace_back(ix, true);\n                }\n                else\n                {\n                    ++it;\n                }\n            }\n\n            return mask_tuples;\n        }\n\n        //**********************************************************************\n        // Vector version\n        template <typename WVectorT,\n                  typename ZScalarT,\n                  typename MaskT>\n        void write_with_opt_mask_1D(\n            WVectorT                                           &w,\n            std::vector<std::tuple<IndexType, ZScalarT>> const &z,\n            MaskT const                                        &mask,\n            OutputControlEnum                                   outp)\n        {\n            using WScalarType = typename WVectorT::ScalarType;\n            std::vector<std::tuple<IndexType, WScalarType> > tmp_row;\n\n            apply_with_mask(tmp_row, w.getContents(), z,\n                            mask.getContents(),\n                            outp);\n\n            // Now, set the new one.  Yes, we can optimize this later\n            w.setContents(tmp_row);\n        }\n\n        //**********************************************************************\n        // Vector version specialized for complement mask\n        template <typename WVectorT,\n                  typename ZScalarT,\n                  typename MaskT>\n        void write_with_opt_mask_1D(\n            WVectorT                                           &w,\n            std::vector<std::tuple<IndexType, ZScalarT>> const &z,\n            grb::VectorComplementView<MaskT>             const &mask,\n            OutputControlEnum                                   outp)\n        {\n            using WScalarType = typename WVectorT::ScalarType;\n            std::vector<std::tuple<IndexType, WScalarType> > tmp_row;\n\n            apply_with_mask(tmp_row, w.getContents(), z,\n                            get_complement_contents(mask.m_vec),\n                            outp);\n\n            // Now, set the new one.  Yes, we can optimize this later\n            w.setContents(tmp_row);\n        }\n\n        //**********************************************************************\n        // Vector version specialized for structure mask\n        template <typename WVectorT,\n                  typename ZScalarT,\n                  typename MaskT>\n        void write_with_opt_mask_1D(\n            WVectorT                                           &w,\n            std::vector<std::tuple<IndexType, ZScalarT>> const &z,\n            grb::VectorStructureView<MaskT>              const &mask,\n            OutputControlEnum                                   outp)\n        {\n            using WScalarType = typename WVectorT::ScalarType;\n            std::vector<std::tuple<IndexType, WScalarType> > tmp_row;\n\n            apply_with_mask(tmp_row, w.getContents(), z,\n                            get_structure_contents(mask.m_vec),\n                            outp);\n\n            // Now, set the new one.  Yes, we can optimize this later\n            w.setContents(tmp_row);\n        }\n\n\n        //**********************************************************************\n        // Vector version specialized for structural complement mask\n        template <typename WVectorT,\n                  typename ZScalarT,\n                  typename MaskT>\n        void write_with_opt_mask_1D(\n            WVectorT                                               &w,\n            std::vector<std::tuple<IndexType, ZScalarT>>     const &z,\n            grb::VectorStructuralComplementView<MaskT>       const &mask,\n            OutputControlEnum                                       outp)\n        {\n            using WScalarType = typename WVectorT::ScalarType;\n            std::vector<std::tuple<IndexType, WScalarType> > tmp_row;\n\n            apply_with_mask(tmp_row, w.getContents(), z,\n                            get_structural_complement_contents(mask.m_vec),\n                            outp);\n\n            // Now, set the new one.  Yes, we can optimize this later\n            w.setContents(tmp_row);\n        }\n\n        //**********************************************************************\n        // Vector version specialized for no mask\n        template <typename WVectorT,\n                  typename ZScalarT>\n        void write_with_opt_mask_1D(\n            WVectorT                                           &w,\n            std::vector<std::tuple<IndexType, ZScalarT>> const &z,\n            grb::NoMask                                  const &foo,\n            OutputControlEnum                                   outp)\n        {\n            //sparse_copy(w, z);\n            w.setContents(z);\n        }\n\n        //********************************************************************\n        // Index-out-of-bounds is an execution error and a responsibility of\n        // the backend.\n        template <typename SequenceT>\n        void check_index_array_content(SequenceT   const &array,\n                                       IndexType          dim,\n                                       std::string const &msg)\n        {\n            if (!IsAllSequence(array))\n            {\n                for (auto ix : array)\n                {\n                    if (ix >= dim)\n                    {\n                        throw IndexOutOfBoundsException(msg);\n                    }\n                }\n            }\n        }\n\n        //********************************************************************\n        // ALL SUPPORT\n        // This is where we turns alls into the correct range\n\n        template <typename SequenceT>\n        SequenceT setupIndices(SequenceT seq, IndexType n)\n        {\n            return seq;\n        }\n\n        IndexSequenceRange setupIndices(AllIndices seq, IndexType n)\n        {\n            return IndexSequenceRange(0, n);\n        }\n\n\n        //********************************************************************\n        // mxm helpers (may be of more general use).\n        //********************************************************************\n\n        // *******************************************************************\n        // Return true if iterator points to location with target_index;\n        // otherwise returns the at the insertion point for target_index\n        // which could be it_end.\n        template <typename TupleIteratorT>\n        bool advance_and_check_tuple_iterator(\n            TupleIteratorT       &it,\n            TupleIteratorT const &it_end,\n            IndexType             target_index)\n        {\n            GRB_LOG_FN_BEGIN(\"advance_and_check_tuple_iterator: tgt = \"\n                             << target_index);\n\n            while ((it != it_end) && (std::get<0>(*it) < target_index))\n            {\n                ++it;\n            }\n\n            bool tmp = ((it != it_end) && (std::get<0>(*it) == target_index));\n            GRB_LOG_FN_END(\"advance_and_check_tuple_iterator target_found = \"\n                           << tmp);\n            return tmp;\n        }\n\n        // *******************************************************************\n        // Only returns true if target index is found AND it evaluates to true\n        /// @todo Need to add support for STRUCTURE_ONLY\n        template <typename TupleIteratorT>\n        bool advance_and_check_mask_iterator(\n            TupleIteratorT       &it,\n            TupleIteratorT const &it_end,\n            bool                  structure_flag,\n            IndexType             target_index)\n        {\n            GRB_LOG_FN_BEGIN(\"advance_and_check_mask_iterator: sflag = \"\n                             << structure_flag << \", tgt = \" << target_index);\n\n            bool tmp =\n                (advance_and_check_tuple_iterator(it, it_end, target_index) &&\n                 (structure_flag || static_cast<bool>(std::get<1>(*it))));\n\n            GRB_LOG_FN_END(\"advance_and_check_mask_iterator: result = \" << tmp);\n            return tmp;\n        }\n\n        //**********************************************************************\n        /// accumulate one sparse vector with another (applying op in intersection).\n        ///  \"xpey = x plus equals y\"\n        /// vec1 += vec2\n        ///\n        /// @note similarities with axpy()\n        template <typename D1, typename D2, typename BinaryOpT>\n        void xpey(\n            std::vector<std::tuple<grb::IndexType,D1> >       &vec1,\n            std::vector<std::tuple<grb::IndexType,D2> > const &vec2,\n            BinaryOpT                                          op)\n        {\n            // point to first entries of the destination vector\n            auto v1_it = vec1.begin();\n\n            for (auto&& [v2_idx, v2_val] : vec2)\n            {\n                // scan forward through vec1 to find insert or merge point\n                if (advance_and_check_tuple_iterator(v1_it, vec1.end(), v2_idx))\n                {\n                    // merge\n                    std::get<1>(*v1_it) = op(std::get<1>(*v1_it), v2_val);\n                    ++v1_it;\n                }\n                else\n                {\n                    // insert\n                    v1_it = vec1.insert(\n                        v1_it, std::make_tuple(v2_idx, static_cast<D1>(v2_val)));\n                    ++v1_it;\n                }\n            }\n        }\n\n        // *******************************************************************\n        /// perform the following operation on sparse vectors implemented as\n        /// vector<tuple<Index, value>>\n        ///\n        /// c += a_ik*b[:]\n        template<typename R1,\n                 typename R2,\n                 typename R3,\n                 typename R4>\n        void axpy(\n            R1 &c,\n            R2 semiring,\n            R3 a,\n            R4 const &b)\n        {\n            GRB_LOG_FN_BEGIN(\"axpy\");\n            auto c_it = c.begin();\n            using scType = std::tuple_element_t<1, typename R1::value_type>;\n            for (auto&& [j, b_j] : b)\n            {\n                GRB_LOG_VERBOSE(\"j = \" << j);\n\n                auto t_j(semiring.mult(a, b_j));\n                GRB_LOG_VERBOSE(\"temp = \" << t_j);\n\n                // scan through C_row to find insert/merge point\n                if (advance_and_check_tuple_iterator(c_it, c.end(), j))\n                {\n                    GRB_LOG_VERBOSE(\"Accumulating\");\n                    std::get<1>(*c_it) = semiring.add(std::get<1>(*c_it), t_j);\n                    ++c_it;\n                }\n                else\n                {\n                    GRB_LOG_VERBOSE(\"Inserting\");\n                    c_it = c.insert(c_it,\n                                    std::make_tuple(j, static_cast<scType>(t_j)));\n                    ++c_it;\n                }\n            }\n            GRB_LOG_FN_END(\"axpy\");\n        }\n\n        // *******************************************************************\n        /// perform the following operation on sparse vectors implemented as\n        /// vector<tuple<Index, value>>\n        ///\n        /// c<[m[:]]> += a_ik*b[:]\n        template<typename CScalarT,\n                 typename MScalarT,\n                 typename SemiringT,\n                 typename AScalarT,\n                 typename BScalarT>\n        void masked_axpy(\n            std::vector<std::tuple<IndexType, CScalarT>>       &c,\n            std::vector<std::tuple<IndexType, MScalarT>> const &m,\n            bool                                                structure_flag,\n            bool                                                complement_flag,\n            SemiringT                                           semiring,\n            AScalarT                                            a,\n            std::vector<std::tuple<IndexType, BScalarT>> const &b)\n        {\n            GRB_LOG_FN_BEGIN(\"masked_axpy\");\n\n            if (m.empty() && complement_flag)\n            {\n                axpy(c, semiring, a, b);\n                return;\n            }\n\n            auto c_it = c.begin();\n            auto m_it = m.begin();\n\n            for (auto const &b_elt : b)\n            {\n                IndexType    j(std::get<0>(b_elt));\n                GRB_LOG_VERBOSE(\"j = \" << j);\n\n                // scan through M[i] to see if mask allows write.\n                if (advance_and_check_mask_iterator(\n                        m_it, m.end(), structure_flag, j) == complement_flag)\n                {\n                    GRB_LOG_VERBOSE(\"Skipping j = \" << j);\n                    continue;\n                }\n\n                BScalarT  b_j(std::get<1>(b_elt));\n\n                auto t_j(semiring.mult(a, b_j));\n                GRB_LOG_VERBOSE(\"temp = \" << t_j);\n\n                // scan through C_row to find insert/merge point\n                if (advance_and_check_tuple_iterator(c_it, c.end(), j))\n                {\n                    GRB_LOG_VERBOSE(\"Accumulating\");\n                    std::get<1>(*c_it) = semiring.add(std::get<1>(*c_it), t_j);\n                    ++c_it;\n                }\n                else\n                {\n                    GRB_LOG_VERBOSE(\"Inserting\");\n                    c_it = c.insert(c_it,\n                                    std::make_tuple(j, static_cast<CScalarT>(t_j)));\n                    ++c_it;\n                }\n            }\n            GRB_LOG_FN_END(\"masked_axpy\");\n        }\n\n        // *******************************************************************\n        /// Perform the following operation on sparse vectors implemented as\n        /// vector<tuple<Index, value>> (t assumed to be masked already)\n        ///\n        /// z = m ^ c (accum) t\n        template<typename CScalarT,\n                 typename AccumT,\n                 typename MScalarT,\n                 typename AScalarT,\n                 typename BScalarT>\n        void masked_accum(\n            std::vector<std::tuple<IndexType, CScalarT>>       &z,\n            std::vector<std::tuple<IndexType, MScalarT>> const &m,\n            bool                                                structure_flag,\n            bool                                                complement_flag,\n            AccumT                                       const &accum,\n            std::vector<std::tuple<IndexType, AScalarT>> const &c,\n            std::vector<std::tuple<IndexType, BScalarT>> const &t)\n        {\n            GRB_LOG_FN_BEGIN(\"masked_accum.v2\");\n            auto t_it = t.begin();\n            auto m_it = m.begin();\n            auto c_it = c.begin();\n\n            // for each element of c find out if it is not in mask\n            while ((t_it != t.end()) && (c_it != c.end()))\n            {\n                IndexType t_idx(std::get<0>(*t_it));\n                IndexType c_idx(std::get<0>(*c_it));\n                if (t_idx < c_idx)\n                {\n                    // t already masked\n                    z.emplace_back(t_idx,\n                                   static_cast<CScalarT>(std::get<1>(*t_it)));\n                    ++t_it;\n                }\n                else if (c_idx < t_idx)\n                {\n                    if (advance_and_check_mask_iterator(\n                            m_it, m.end(), structure_flag, c_idx) != complement_flag)\n                    {\n                        z.emplace_back(c_idx,\n                                       static_cast<CScalarT>(std::get<1>(*c_it)));\n                    }\n                    ++c_it;\n                }\n                else\n                {\n                    z.emplace_back(\n                        t_idx,\n                        static_cast<CScalarT>(accum(std::get<1>(*c_it),\n                                                    std::get<1>(*t_it))));\n                    ++t_it;\n                    ++c_it;\n                }\n            }\n\n            while (t_it != t.end())\n            {\n                z.emplace_back(std::get<0>(*t_it),\n                               static_cast<CScalarT>(std::get<1>(*t_it)));\n                ++t_it;\n            }\n\n            while (c_it != c.end())\n            {\n                IndexType c_idx(std::get<0>(*c_it));\n                if (advance_and_check_mask_iterator(\n                        m_it, m.end(), structure_flag, c_idx) != complement_flag)\n                {\n                    z.emplace_back(c_idx, std::get<1>(*c_it));\n                }\n                ++c_it;\n            }\n            GRB_LOG_FN_END(\"masked_accum.v2\");\n        }\n\n\n        // *******************************************************************\n        /// Perform the following operation on sparse vectors implemented as\n        /// vector<tuple<Index, value>>\n        ///\n        /// if complement_flag == false:\n        ///    c = (!m ^ ci) U z, where z = (m ^ t);  i.e., union assumes disjoint sets\n        /// else:\n        ///   c =   (m ^ ci) U z, where z = (!m ^ t)\n        template<typename CScalarT,\n                 typename MScalarT,\n                 typename ZScalarT>\n        void masked_merge(\n            std::vector<std::tuple<IndexType, CScalarT>>       &c,\n            std::vector<std::tuple<IndexType, MScalarT>> const &m,\n            bool                                                structure_flag,\n            bool                                                complement_flag,\n            std::vector<std::tuple<IndexType, CScalarT>> const &ci,\n            std::vector<std::tuple<IndexType, ZScalarT>> const &z)\n        {\n            GRB_LOG_FN_BEGIN(\"masked_merge.v2\");\n            auto m_it = m.begin();\n            auto c_it = ci.begin();\n            auto z_it = z.begin();\n\n            c.clear();\n\n            IndexType next_z;\n            for (auto const &elt : z)\n            {\n                next_z = std::get<0>(elt);\n                while (c_it != ci.end() && (std::get<0>(*c_it) < next_z))\n                {\n                    IndexType next_c(std::get<0>(*c_it));\n                    if (advance_and_check_mask_iterator(\n                            m_it, m.end(), structure_flag, next_c) == complement_flag)\n                    {\n                        c.emplace_back(next_c, std::get<1>(*c_it));\n                    }\n                    ++c_it;\n                }\n                c.emplace_back(next_z, static_cast<CScalarT>(std::get<1>(elt)));\n            }\n\n\n            while (c_it != ci.end() && (!z.empty() && (std::get<0>(*c_it) <= next_z)))\n            {\n                ++c_it;\n            }\n\n            while (c_it != ci.end())\n            {\n                IndexType next_c(std::get<0>(*c_it));\n                if (advance_and_check_mask_iterator(\n                        m_it, m.end(), structure_flag, next_c) == complement_flag)\n                {\n                    c.emplace_back(next_c, std::get<1>(*c_it));\n                }\n                ++c_it;\n            }\n\n            GRB_LOG_FN_END(\"masked_merge.v2\");\n        }\n\n    } // backend\n} // grb\n", "meta": {"hexsha": "5cd018569925d6e0d72c6eed21a9eabb61e765c9", "size": 63097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graphblas/platforms/sequential/sparse_helpers.hpp", "max_stars_repo_name": "kaushikvelusamy/QuickDiff-Metall-GBTL", "max_stars_repo_head_hexsha": "5afc2365c8e0283fbef2f9ef9446a93db9001390", "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/graphblas/platforms/sequential/sparse_helpers.hpp", "max_issues_repo_name": "kaushikvelusamy/QuickDiff-Metall-GBTL", "max_issues_repo_head_hexsha": "5afc2365c8e0283fbef2f9ef9446a93db9001390", "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/graphblas/platforms/sequential/sparse_helpers.hpp", "max_forks_repo_name": "kaushikvelusamy/QuickDiff-Metall-GBTL", "max_forks_repo_head_hexsha": "5afc2365c8e0283fbef2f9ef9446a93db9001390", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8528325123, "max_line_length": 99, "alphanum_fraction": 0.4080859629, "num_tokens": 12486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.03846619146718183, "lm_q1q2_score": 0.01273691530313218}}
{"text": "/**\n * @Author: Maxime Agor (4rzael)\n * @Date:   Sat Jun 23 2018\n * @Email:  maxime.agor23@gmail.com\n * @Project: CUDA-Based Simulator of Quantum Systems\n * @Filename: Circuit.hpp\n * @Last modified by:   vial-dj\n * @Last modified time: Wed Nov 14 2018, 11:27:21\n * @License: MIT License\n */\n\n#pragma once\n#include <limits>\n#include <string>\n#include <vector>\n#include <boost/variant/variant.hpp>\n\n#include \"Parser/AST.hpp\"\n\nstruct Circuit {\n    // methods\n    Circuit() {}\n    Circuit(Circuit const &other, uint beginStep=0, uint endStep=std::numeric_limits<uint>::max());\n\n    void removeMeasurements();\n\n    struct Register {\n        Register(const std::string &n, const uint &s) : name(n), size(s) {}\n        std::string name;\n        uint        size;\n    };\n\n    struct Qubit {\n        Qubit(const std::string &n, const uint &e) : registerName(n), element(e) {}\n        explicit Qubit(const Parser::AST::t_bit &b) : registerName(b.name), element(b.value) {}\n        bool operator==(const Qubit &other) const;\n        std::string registerName;\n        uint        element;\n    };\n\n    struct GateInterface {\n        virtual std::vector<Qubit> getTargets() const = 0;\n        virtual ~GateInterface() {}\n    };\n\n    struct CXGate : public GateInterface {\n        CXGate(const Qubit &ctrl, const Qubit &trgt)\n        : control(ctrl), target(trgt) {}\n        std::vector<Qubit> getTargets() const;\n\n        Qubit control;\n        Qubit target;\n    };\n\n    struct UGate : public GateInterface {\n        UGate(double t, double p, double l, const Qubit &trgt)\n        : theta(t), phi(p), lambda(l), target(trgt) {}\n        std::vector<Qubit> getTargets() const;\n\n        double theta;\n        double phi;\n        double lambda;\n        Qubit  target;\n    };\n\n    struct Measurement : public GateInterface {\n        Measurement(Measurement const &other): source(other.source), dest(other.dest) {}\n        Measurement(const Qubit &src, const Qubit &dst)\n        : source(src), dest(dst) {}\n        std::vector<Qubit> getTargets() const;\n\n        Qubit source;\n        Qubit dest;\n    };\n\n    struct Reset : public GateInterface {\n        explicit Reset(const Qubit &trgt)\n        : target(trgt) {}\n        std::vector<Qubit> getTargets() const;\n\n        Qubit target;\n    };\n\n    struct Barrier : public GateInterface {\n        explicit Barrier(const Qubit &trgt)\n        : target(trgt) {}\n        std::vector<Qubit> getTargets() const;\n\n        Qubit target;\n    };\n\n    typedef boost::variant<CXGate, UGate, Measurement, Reset> ConditionalCompatibleGate;\n    struct ConditionalGate : public GateInterface {\n        ConditionalGate(const Circuit::Register &tested, uint value, ConditionalCompatibleGate const &_gate)\n        : testedRegister(tested.name), expectedValue(value), gate(_gate), m_maxTestedRegisterSize(tested.size) {}\n        std::vector<Qubit> getTargets() const;\n\n        std::string testedRegister;\n        uint expectedValue;\n        ConditionalCompatibleGate gate;\n    private:\n        uint m_maxTestedRegisterSize; // only used for the getTargets() method\n    };\n\n    typedef boost::variant<CXGate, UGate, Measurement, Reset, Barrier, ConditionalGate> Gate;\n\n    struct Step : public std::vector<Gate> {\n        /**\n         * @brief Returns whether a qubit is used in this step\n         * \n         * @param qubit The qubit to check\n         * @return true if the qubit is used\n         * @return false otherwise\n         */\n        bool isQubitUsed(Qubit const &qubit) const;\n\n        /**\n         * @brief Returns whether or not the step contains a measurement gate \n         * \n         * @return true if a measurement is present\n         * @return false otherwise\n         */\n        bool containsMeasurement() const;\n    };\n\n    std::vector<Register> creg;\n    std::vector<Register> qreg;\n    std::vector<Step> steps;\n\n    friend std::ostream& operator<< (std::ostream& stream, const Circuit & c);\n};\n", "meta": {"hexsha": "5f1f7c3cb6c07cc414be865a813d6597c16f5024", "size": 3923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Circuit.hpp", "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": "include/Circuit.hpp", "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": "include/Circuit.hpp", "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": 29.7196969697, "max_line_length": 113, "alphanum_fraction": 0.6166199337, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.331119752830196, "lm_q2_score": 0.03846618884925529, "lm_q1q2_score": 0.012736914944085053}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <string>\n\n#define CERES_FOUND true\n\n#include <opencv2/core/utils/filesystem.hpp>\n#include <opencv2/core/utils/logger.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/sfm.hpp>\n#include <opencv2/viz.hpp>\n#include <opencv2/xfeatures2d.hpp>\n\n#include <boost/filesystem.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graphviz.hpp>\n\n#define _USE_OPENCV true\n#include <libs/MVS/Interface.h>\n\nusing namespace cv;\nusing namespace std;\nnamespace fs = boost::filesystem;\n\nclass StructureFromMotion {\n\npublic:\n    StructureFromMotion(const string& dir, const float matchSurvivalRate = 0.5f,\n        const bool viz = false, const string mvs = \"\", const string cloud = \"\",\n        const bool saveDebug = false)\n        : PAIR_MATCH_SURVIVAL_RATE(matchSurvivalRate)\n        , visualize(viz)\n        , saveMVS(mvs)\n        , saveCloud(cloud)\n        , saveDebugVisualizations(saveDebug)\n\n    {\n        findImagesInDiretcory(dir);\n    }\n\n    void runSfM()\n    {\n        extractFeatures();\n        matchFeatures();\n        buildTracks();\n        reconstructFromTracks();\n        if (visualize) {\n            visualize3D();\n        }\n        if (saveMVS != \"\") {\n            saveToMVSFile();\n        }\n        if (saveCloud != \"\") {\n            CV_LOG_INFO(TAG, \"Save point cloud to: \" + saveCloud);\n            viz::writeCloud(saveCloud, pointCloud, pointCloudColor);\n        }\n    }\n\nprivate:\n    void findImagesInDiretcory(const string& dir)\n    {\n        CV_LOG_INFO(TAG, \"Finding images in \" + dir);\n\n        utils::fs::glob(dir, \"*.jpg\", imagesFilenames);\n        utils::fs::glob(dir, \"*.JPG\", imagesFilenames);\n        utils::fs::glob(dir, \"*.png\", imagesFilenames);\n        utils::fs::glob(dir, \"*.PNG\", imagesFilenames);\n\n        std::sort(imagesFilenames.begin(), imagesFilenames.end());\n\n        CV_LOG_INFO(TAG, \"Found \" + std::to_string(imagesFilenames.size()) + \" images\");\n\n        CV_LOG_INFO(TAG, \"Reading images...\");\n        for (const auto& i : imagesFilenames) {\n            CV_LOG_INFO(TAG, i);\n            images[i] = imread(i);\n            imageIDs[i] = images.size() - 1;\n        }\n    }\n\n    void extractFeatures()\n    {\n        CV_LOG_INFO(TAG, \"Extract Features\");\n\n        auto detector = AKAZE::create();\n        auto extractor = AKAZE::create();\n\n        for (const auto& i : imagesFilenames) {\n            Mat grayscale;\n            cvtColor(images[i], grayscale, COLOR_BGR2GRAY);\n            detector->detect(grayscale, keypoints[i]);\n            extractor->compute(grayscale, keypoints[i], descriptors[i]);\n\n            CV_LOG_INFO(TAG, \"Found \" + to_string(keypoints[i].size()) + \" keypoints in \" + i);\n\n            if (saveDebugVisualizations) {\n                Mat out;\n                drawKeypoints(images[i], keypoints[i], out, Scalar(0, 0, 255));\n                imwrite(fs::basename(fs::path(i)) + \"_features.jpg\", out);\n            }\n        }\n    }\n\n    vector<DMatch> matchWithRatioTest(\n        const DescriptorMatcher& matcher, const Mat& desc1, const Mat& desc2)\n    {\n        // Raw match\n        vector<vector<DMatch>> nnMatch;\n        matcher.knnMatch(desc1, desc2, nnMatch, 2);\n\n        // Ratio test filter\n        vector<DMatch> ratioMatched;\n        for (size_t i = 0; i < nnMatch.size(); i++) {\n            DMatch first = nnMatch[i][0];\n            float dist1 = nnMatch[i][0].distance;\n            float dist2 = nnMatch[i][1].distance;\n\n            if (dist1 < MATCH_RATIO_THRESHOLD * dist2) {\n                ratioMatched.push_back(first);\n            }\n        }\n\n        return ratioMatched;\n    }\n\n    void matchFeatures()\n    {\n        CV_LOG_INFO(TAG, \"Match Features\");\n\n        BFMatcher matcher(NORM_HAMMING);\n\n        for (size_t i = 0; i < imagesFilenames.size() - 1; ++i) {\n            for (size_t j = i + 1; j < imagesFilenames.size(); ++j) {\n                const string imgi = imagesFilenames[i];\n                const string imgj = imagesFilenames[j];\n\n                // Match with ratio test filter\n                vector<DMatch> match\n                    = matchWithRatioTest(matcher, descriptors[imgi], descriptors[imgj]);\n\n                // Reciprocity test filter\n                vector<DMatch> matchRcp\n                    = matchWithRatioTest(matcher, descriptors[imgj], descriptors[imgi]);\n                vector<DMatch> merged;\n                for (const DMatch& dmr : matchRcp) {\n                    bool found = false;\n                    for (const DMatch& dm : match) {\n                        // Only accept match if 1 matches 2 AND 2 matches 1.\n                        if (dmr.queryIdx == dm.trainIdx and dmr.trainIdx == dm.queryIdx) {\n                            merged.push_back(dm);\n                            found = true;\n                            break;\n                        }\n                    }\n                    if (found) {\n                        continue;\n                    }\n                }\n\n                // Fundamental matrix filter\n                vector<uint8_t> inliersMask(merged.size());\n                vector<Point2f> imgiPoints, imgjPoints;\n                for (const auto& m : merged) {\n                    imgiPoints.push_back(keypoints[imgi][m.queryIdx].pt);\n                    imgjPoints.push_back(keypoints[imgj][m.trainIdx].pt);\n                }\n                findFundamentalMat(imgiPoints, imgjPoints, inliersMask);\n\n                vector<DMatch> final;\n                for (size_t m = 0; m < merged.size(); m++) {\n                    if (inliersMask[m]) {\n                        final.push_back(merged[m]);\n                    }\n                }\n\n                if ((float) final.size() / (float)match.size() < PAIR_MATCH_SURVIVAL_RATE) {\n                    CV_LOG_INFO(TAG,\n                        \"Final match '\" + imgi + \"'->'\" + imgj + \"' has less than \"\n                            + to_string(PAIR_MATCH_SURVIVAL_RATE) + \" inliers from orignal. Skip\");\n                    continue;\n                }\n\n                matches[make_pair(imgi, imgj)] = final;\n\n                CV_LOG_INFO(TAG,\n                    \"Matching \" + imgi + \" and \" + imgj + \": \" + to_string(final.size()) + \" / \"\n                        + to_string(match.size()));\n\n                if (saveDebugVisualizations) {\n                    Mat out;\n                    vector<DMatch> rawmatch;\n                    matcher.match(descriptors[imgi], descriptors[imgj], rawmatch);\n                    vector<pair<string, vector<DMatch>&>> showList { { \"Raw Match\", rawmatch },\n                        { \"Ratio Test Filter\", match }, { \"Reciprocal Filter\", merged },\n                        { \"Epipolar Filter\", final } };\n                    for (size_t i = 0; i < showList.size(); i++) {\n                        drawMatches(images[imgi], keypoints[imgi], images[imgj], keypoints[imgj],\n                            showList[i].second, out, CV_RGB(255, 0, 0));\n                        putText(out, showList[i].first, Point(10, 50), FONT_HERSHEY_COMPLEX, 2.0,\n                            CV_RGB(255, 255, 255), 2);\n                        putText(out, \"# Matches: \" + to_string(showList[i].second.size()),\n                            Point(10, 100), FONT_HERSHEY_COMPLEX, 1.0, CV_RGB(255, 255, 255));\n                        imwrite(fs::basename(fs::path(imgi)) + \"_\" + fs::basename(fs::path(imgj))\n                                + \"_\" + to_string(i) + \".jpg\",\n                            out);\n                    }\n                }\n            }\n        }\n    }\n\n    void buildTracks()\n    {\n        CV_LOG_INFO(TAG, \"Build tracks\");\n\n        using namespace boost;\n\n        struct ImageFeature {\n            string image;\n            size_t featureID;\n        };\n        typedef adjacency_list<listS, vecS, undirectedS, ImageFeature> Graph;\n        typedef graph_traits<Graph>::vertex_descriptor Vertex;\n\n        map<pair<string, int>, Vertex> vertexByImageFeature;\n\n        Graph g;\n\n        // Add vertices - image features\n        for (const auto& imgi : keypoints) {\n            for (size_t i = 0; i < imgi.second.size(); i++) {\n                Vertex v = add_vertex(g);\n                g[v].image = imgi.first;\n                g[v].featureID = i;\n                vertexByImageFeature[make_pair(imgi.first, i)] = v;\n            }\n        }\n\n        // Add edges - feature matches\n        for (const auto& match : matches) {\n            for (const DMatch& dm : match.second) {\n                Vertex& vI = vertexByImageFeature[make_pair(match.first.first, dm.queryIdx)];\n                Vertex& vJ = vertexByImageFeature[make_pair(match.first.second, dm.trainIdx)];\n                add_edge(vI, vJ, g);\n            }\n        }\n\n        using Filtered = filtered_graph<Graph, keep_all, std::function<bool(Vertex)>>;\n        Filtered gFiltered(g, keep_all {}, [&g](Vertex vd) { return degree(vd, g) > 0; });\n\n        // Get connected components\n        std::vector<int> component(num_vertices(gFiltered), -1);\n        int num = connected_components(gFiltered, &component[0]);\n        map<int, vector<Vertex>> components;\n        for (size_t i = 0; i != component.size(); ++i) {\n            if (component[i] >= 0) {\n                components[component[i]].push_back(i);\n            }\n        }\n        // Filter bad components (with more than 1 feature from a single image)\n        std::vector<int> vertexInGoodComponent(num_vertices(gFiltered), -1);\n        map<int, vector<Vertex>> goodComponents;\n        for (const auto& c : components) {\n            set<string> imagesInComponent;\n            bool isComponentGood = true;\n            for (int j = 0; j < c.second.size(); ++j) {\n                const string imgId = g[c.second[j]].image;\n                if (imagesInComponent.count(imgId) > 0) {\n                    // Image already represented in this component\n                    isComponentGood = false;\n                    break;\n                } else {\n                    imagesInComponent.insert(imgId);\n                }\n            }\n            if (isComponentGood) {\n                for (int j = 0; j < c.second.size(); ++j) {\n                    vertexInGoodComponent[c.second[j]] = 1;\n                }\n                goodComponents[c.first] = c.second;\n            }\n        }\n\n        Filtered gGoodComponents(g, keep_all {},\n            [&vertexInGoodComponent](Vertex vd) { return vertexInGoodComponent[vd] > 0; });\n\n        CV_LOG_INFO(TAG, \"Total number of components found: \" + to_string(components.size()));\n        CV_LOG_INFO(TAG, \"Number of good components: \" + to_string(goodComponents.size()));\n        const int accum = std::accumulate(goodComponents.begin(), goodComponents.end(), 0,\n            [](int a, pair<const int, vector<Vertex>>& v) { return a + v.second.size(); });\n        CV_LOG_INFO(TAG,\n            \"Average component size: \" + to_string((float)accum / (float)(goodComponents.size())));\n\n        if (saveDebugVisualizations) {\n            struct my_node_writer {\n                my_node_writer(Graph& g_, const map<string, int>& iid_)\n                    : g(g_)\n                    , iid(iid_) {};\n                void operator()(std::ostream& out, Vertex v)\n                {\n                    const int imgId = iid[g[v].image];\n                    out << \" [label=\\\"\" << imgId\n                        << \"\\\" colorscheme=\\\"accent8\\\" fillcolor=\" << (imgId + 1)\n                        << \" style=filled]\";\n                };\n                Graph g;\n                map<string, int> iid;\n            };\n            std::ofstream ofs(\"match_graph_good_components.dot\");\n            write_graphviz(ofs, gGoodComponents, my_node_writer(g, imageIDs));\n            std::ofstream ofsf(\"match_graph_filtered.dot\");\n            write_graphviz(ofsf, gFiltered, my_node_writer(g, imageIDs));\n        }\n\n        // Each component is a track\n        const size_t nViews = imagesFilenames.size();\n        tracks.resize(nViews);\n        for (int i = 0; i < nViews; i++) {\n            tracks[i].create(2, goodComponents.size(), CV_64FC1);\n            tracks[i].setTo(-1.0);\n        }\n        int i = 0;\n        for (auto c = goodComponents.begin(); c != goodComponents.end(); ++c, ++i) {\n            for (const int v : c->second) {\n                const int imageID = imageIDs[g[v].image];\n                const size_t featureID = g[v].featureID;\n                const Point2f p = keypoints[g[v].image][featureID].pt;\n                tracks[imageID].at<double>(0, i) = p.x;\n                tracks[imageID].at<double>(1, i) = p.y;\n            }\n        }\n\n        if (saveDebugVisualizations) {\n            vector<Scalar> colors\n                = { CV_RGB(240, 248, 255), CV_RGB(250, 235, 215), CV_RGB(0, 255, 255),\n                      CV_RGB(127, 255, 212), CV_RGB(240, 255, 255), CV_RGB(245, 245, 220),\n                      CV_RGB(255, 228, 196), CV_RGB(255, 235, 205), CV_RGB(0, 0, 255),\n                      CV_RGB(138, 43, 226), CV_RGB(165, 42, 42), CV_RGB(222, 184, 135) };\n\n            vector<Mat> imagesM;\n            for (const auto m : images)\n                imagesM.push_back(m.second);\n            Mat out;\n            hconcat(vector<Mat>(imagesM.begin(), imagesM.begin() + 4), out);\n            RNG& rng = cv::theRNG();\n            const Size imgS = imagesM[0].size();\n            for (int tId = 0; tId < 20; tId++) {\n                const int trackId = rng(tracks[0].cols); // Randomize a track ID\n\n                // Show track over images\n                for (int i = 0; i < 3; i++) {\n                    Point2f a = Point2f(tracks[i].col(trackId));\n                    Point2f b = Point2f(tracks[i + 1].col(trackId));\n\n                    if (a.x < 0 or a.y < 0 or b.x < 0 or b.y < 0) {\n                        continue;\n                    }\n\n                    const Scalar c = colors[tId % colors.size()];\n                    a.x += imgS.width * i;\n                    b.x += imgS.width * (i + 1);\n                    circle(out, a, 7, c, FILLED);\n                    circle(out, b, 7, c, FILLED);\n                    line(out, a, b, c, 3);\n                }\n                imwrite(\"tracks.jpg\", out);\n\n                // Show track patches\n                const int patchSize = 20;\n                const Point2f patch(patchSize, patchSize);\n                for (int i = 0; i < tracks.size(); i++) {\n                    Point2f a = Point2f(tracks[i].col(trackId));\n                    if (a.x < patchSize or a.y < patchSize or a.x > imgS.width - patchSize\n                        or a.y > imgS.height - patchSize) {\n                        continue;\n                    }\n\n                    imwrite(\"track_\" + to_string(trackId) + \"_\" + to_string(i) + \".png\",\n                        imagesM[i](Rect(a - patch, a + patch)));\n                }\n            }\n        }\n    }\n\n    bool reconstructFromTracks()\n    {\n        CV_LOG_INFO(TAG, \"Reconstruct from \" + to_string(tracks[0].cols) + \" tracks\");\n        const Size imgS = images.begin()->second.size();\n        const float f = std::max(imgS.width, imgS.height);\n        Mat K\n            = Mat(Matx33f { f, 0.0, imgS.width / 2.0f, 0.0, f, imgS.height / 2.0f, 0.0, 0.0, 1.0 });\n        cv::sfm::reconstruct(tracks, Rs, Ts, K, points3d, true);\n\n        K.copyTo(K_);\n\n        CV_LOG_INFO(TAG, \"Reconstruction: \");\n        CV_LOG_INFO(TAG, \"Estimated 3D points: \" + to_string(points3d.size()));\n        CV_LOG_INFO(TAG, \"Estimated cameras: \" + to_string(Rs.size()));\n        CV_LOG_INFO(TAG, \"Refined intrinsics: \");\n        CV_LOG_INFO(TAG, K_);\n\n        if (Rs.size() != imagesFilenames.size()) {\n            CV_LOG_ERROR(TAG,\n                \"Unable to reconstruct all camera views (\" + to_string(imagesFilenames.size())\n                    + \")\");\n            return false;\n        }\n\n        if (tracks[0].cols != points3d.size()) {\n            CV_LOG_WARNING(\n                TAG, \"Unable to reconstruct all tracks (\" + to_string(tracks[0].cols) + \")\");\n        }\n\n        // Create the point cloud\n        pointCloud.clear();\n        for (const auto& p : points3d)\n            pointCloud.emplace_back(Vec3f(p));\n\n        // Get the point colors\n        pointCloudColor.resize(pointCloud.size(), Vec3b(0, 255, 0));\n        vector<Point2f> point2d(1);\n        for (int i = 0; i < (int)pointCloud.size(); i++) {\n            for (int j = 0; j < imagesFilenames.size(); ++j) {\n                Mat point3d = Mat(pointCloud[i]).reshape(1, 1);\n                cv::projectPoints(point3d, Rs[j], Ts[j], K_, Mat(), point2d);\n                if (point2d[0].x < 0 or point2d[0].x >= imgS.width or point2d[0].y < 0\n                    or point2d[0].y >= imgS.height) {\n                    continue;\n                }\n                pointCloudColor[i] = images[imagesFilenames[j]].at<Vec3b>(point2d[0]);\n                break;\n            }\n        }\n\n        return true;\n    }\n\n    void visualize3D()\n    {\n        CV_LOG_INFO(TAG, \"Visualize reconstruction\");\n\n        if (saveDebugVisualizations) {\n            // 3d point reprojections\n            Mat points2d;\n            Mat points3dM(points3d.size(), 1, CV_32FC3);\n            for (int i = 0; i < points3d.size(); i++) {\n                points3dM.at<Vec3f>(i) = Vec3f(points3d[i]);\n            }\n            for (int j = 0; j < imagesFilenames.size(); j++) {\n                cv::projectPoints(points3dM, Rs[j], Ts[j], K_, noArray(), points2d);\n\n                Mat out;\n                images[imagesFilenames[j]].copyTo(out);\n                for (int i = 0; i < points2d.rows; i++) {\n                    circle(out, points2d.at<Point2f>(i), 3, CV_RGB(255, 0, 0), FILLED);\n                }\n                imwrite(\"reprojection_\" + to_string(j) + \".jpg\", out);\n            }\n        }\n\n        // Create 3D windows\n        viz::Viz3d window(\"Coordinate Frame\");\n        window.setWindowSize(Size(500, 500));\n        window.setWindowPosition(Point(150, 150));\n        window.setBackgroundColor(viz::Color::white());\n\n        // Recovering cameras\n        vector<Affine3d> path;\n        for (size_t i = 0; i < Rs.size(); ++i)\n            path.push_back(Affine3d(Rs[i], Ts[i]));\n\n        // Add the pointcloud\n        viz::WCloud cloud_widget(pointCloud, pointCloudColor);\n        window.showWidget(\"point_cloud\", cloud_widget);\n        // Add cameras\n        window.showWidget(\"cameras_frames_and_lines\",\n            viz::WTrajectory(path, viz::WTrajectory::BOTH, 0.1, viz::Color::black()));\n        window.showWidget(\n            \"cameras_frustums\", viz::WTrajectoryFrustums(path, K_, 0.1, viz::Color::navy()));\n        window.setViewerPose(path[0]);\n\n        /// Wait for key 'q' to close the window\n        CV_LOG_INFO(TAG, \"Press 'q' to close ... \")\n\n        window.spin();\n    }\n\n    void saveToMVSFile()\n    {\n        CV_LOG_INFO(TAG, \"Save reconstruction to MVS file: \" + saveMVS)\n\n        MVS::Interface interface;\n        MVS::Interface::Platform p;\n\n        // Add camera\n        MVS::Interface::Platform::Camera c;\n        const Size imgS = images[imagesFilenames[0]].size();\n        c.K = Matx33d(K_);\n        c.R = Matx33d::eye();\n        c.C = Point3d(0, 0, 0);\n        c.name = \"Camera1\";\n        c.width = imgS.width;\n        c.height = imgS.height;\n        p.cameras.push_back(c);\n\n        // Add views\n        p.poses.resize(Rs.size());\n        for (size_t i = 0; i < Rs.size(); ++i) {\n            Mat t = -Rs[i].t() * Ts[i];\n            p.poses[i].C.x = t.at<double>(0);\n            p.poses[i].C.y = t.at<double>(1);\n            p.poses[i].C.z = t.at<double>(2);\n            Mat r;\n            Rs[i].copyTo(r);\n            Mat(r).convertTo(p.poses[i].R, CV_64FC1);\n\n            // Add corresponding image\n            MVS::Interface::Image image;\n            image.cameraID = 0;\n            image.poseID = i;\n            image.name = imagesFilenames[i];\n            image.platformID = 0;\n            interface.images.push_back(image);\n        }\n        p.name = \"Platform1\";\n        interface.platforms.push_back(p);\n\n        // Add point cloud\n        for (size_t k = 0; k < points3d.size(); ++k) {\n            MVS::Interface::Color c;\n            MVS::Interface::Vertex v;\n            v.X = Vec3f(points3d[k]);\n\n            // Reproject to see if in image bounds and get the RGB color\n            Mat point3d;\n            Mat(points3d[k].t()).convertTo(point3d, CV_32FC1);\n            for (uint32_t j = 0; j < tracks.size(); ++j) {\n                vector<Point2f> points2d(1);\n                cv::projectPoints(point3d, Rs[j], Ts[j], K_, Mat(), points2d);\n                if (points2d[0].x < 0 or points2d[0].x > imgS.width or points2d[0].y < 0\n                    or points2d[0].y > imgS.height) {\n                    continue;\n                } else {\n                    c.c = images[imagesFilenames[j]].at<Vec3b>(points2d[0]);\n                    v.views.push_back({ j, 1.0 });\n                }\n            }\n\n            interface.verticesColor.push_back(c);\n            interface.vertices.push_back(v);\n        }\n\n        MVS::ARCHIVE::SerializeSave(interface, saveMVS);\n    }\n\n    vector<String> imagesFilenames;\n    map<string, int> imageIDs;\n    map<string, Mat> images;\n    map<string, vector<KeyPoint>> keypoints;\n    map<string, Mat> descriptors;\n    map<pair<string, string>, vector<DMatch>> matches;\n    vector<Mat> Rs, Ts;\n    vector<Mat> points3d;\n    vector<Mat> tracks;\n    vector<Vec3f> pointCloud;\n    vector<Vec3b> pointCloudColor;\n    Matx33f K_;\n\n    const float MATCH_RATIO_THRESHOLD = 0.8f; // Nearest neighbor matching ratio\n    const float\n        PAIR_MATCH_SURVIVAL_RATE; // Ratio of surviving matches for a successful stereo match\n    const bool visualize; // Show 3D visualization of the sprase cloud?\n    const string saveMVS; // Save the reconstruction in MVS format for OpenMVS?\n    const string saveCloud; // Save the reconstruction to a point cloud file?\n    const bool saveDebugVisualizations; // Save debug visualizations from the reconstruction process\n\n    const string TAG = \"StructureFromMotion\";\n};\n\nint main(int argc, char** argv)\n{\n    utils::logging::setLogLevel(utils::logging::LOG_LEVEL_DEBUG);\n\n    cv::CommandLineParser parser(argc, argv,\n        \"{help h ? |       | help message}\"\n        \"{@dir     | .     | directory with image files for reconstruction }\"\n        \"{mrate    | 0.5   | Survival rate of matches to consider image pair success }\"\n        \"{viz      | false | Visualize the sparse point cloud reconstruction? }\"\n        \"{debug    | false | Save debug visualizations to files? }\"\n        \"{mvs      |       | Save reconstruction to an .mvs file. Provide filename }\"\n        \"{cloud    |       | Save reconstruction to a point cloud file (PLY, XYZ and OBJ). Provide \"\n        \"filename}\");\n\n    if (parser.has(\"help\")) {\n        parser.printMessage();\n        return 0;\n    }\n\n    StructureFromMotion sfm(parser.get<string>(\"@dir\"), parser.get<float>(\"mrate\"),\n        parser.get<bool>(\"viz\"), parser.get<string>(\"mvs\"), parser.get<string>(\"cloud\"),\n        parser.get<bool>(\"debug\"));\n    sfm.runSfM();\n\n    return 0;\n}\n", "meta": {"hexsha": "8164dfee3a8a1d7b2c3616baebcd47b24d3427b5", "size": 23159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter_02/main.cpp", "max_stars_repo_name": "focusexplorer/Mastering-OpenCV-4-Third-Edition", "max_stars_repo_head_hexsha": "1c9aa404314408ec682b5563c0e8a19ca8547170", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 477.0, "max_stars_repo_stars_event_min_datetime": "2018-09-29T03:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:29:57.000Z", "max_issues_repo_path": "Chapter_02/main.cpp", "max_issues_repo_name": "focusexplorer/Mastering-OpenCV-4-Third-Edition", "max_issues_repo_head_hexsha": "1c9aa404314408ec682b5563c0e8a19ca8547170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T20:45:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T15:56:11.000Z", "max_forks_repo_path": "Chapter_02/main.cpp", "max_forks_repo_name": "focusexplorer/Mastering-OpenCV-4-Third-Edition", "max_forks_repo_head_hexsha": "1c9aa404314408ec682b5563c0e8a19ca8547170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 176.0, "max_forks_repo_forks_event_min_datetime": "2018-11-03T13:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T15:23:23.000Z", "avg_line_length": 38.0279146141, "max_line_length": 100, "alphanum_fraction": 0.5172934928, "num_tokens": 5651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.029760093730832948, "lm_q1q2_score": 0.012687370553691285}}
{"text": "#include <boost/asio.hpp>\n#include \"vdf.h\"\n\nusing boost::asio::ip::tcp;\n\nconst int max_length = 2048;\nstd::mutex socket_mutex;\n\nint process_number;\n// Segments are 2^16, 2^18, ..., 2^30\n// Best case it'll be able to proof for up to 2^36 due to 64-wesolowski restriction.\nint segments = 8;\nint thread_count = 3;\n\nvoid PrintInfo(std::string input) {\n    std::cout << \"VDF Client: \" << input << \"\\n\";\n    std::cout << std::flush;\n}\n\nchar disc[350];\nchar disc_size[5];\nint disc_int_size;\n\nvoid WriteProof(uint64_t iteration, Proof& result, tcp::socket& sock) {\n    // Writes the number of iterations\n    std::vector<unsigned char> bytes = ConvertIntegerToBytes(integer(iteration), 8);\n\n    // Writes the y, with prepended size\n    std::vector<unsigned char> y_size = ConvertIntegerToBytes(integer(result.y.size()), 8);\n    bytes.insert(bytes.end(), y_size.begin(), y_size.end());\n    bytes.insert(bytes.end(), result.y.begin(), result.y.end());\n    \n    // Writes the witness type.\n    std::vector<unsigned char> witness_type = ConvertIntegerToBytes(integer(result.witness_type), 1);\n    bytes.insert(bytes.end(), witness_type.begin(), witness_type.end());\n\n    bytes.insert(bytes.end(), result.proof.begin(), result.proof.end());\n    std::string str_result = BytesToStr(bytes);\n\n    const uint32_t length = str_result.size();\n    std::vector<unsigned char> prefix_bytes = ConvertIntegerToBytes(integer(length), 4);\n    std::string prefix = BytesToStr(prefix_bytes);\n\n    PrintInfo(\"Sending proof\");\n    {\n        std::lock_guard<std::mutex> lock(socket_mutex);\n        boost::asio::write(sock, boost::asio::buffer(prefix_bytes, 4));\n        boost::asio::write(sock, boost::asio::buffer(str_result.c_str(), str_result.size()));\n    }\n    PrintInfo(\"Sended proof\");\n}\n\nvoid CreateAndWriteProof(ProverManager& pm, uint64_t iteration, bool& stop_signal, tcp::socket& sock) {\n    Proof result = pm.Prove(iteration);\n    if (stop_signal == true) {\n        PrintInfo(\"Got stop signal before completing the proof!\");\n        return ;\n    }\n    WriteProof(iteration, result, sock);\n}\n\nvoid CreateAndWriteProofTwoWeso(integer& D, form f, uint64_t iters, TwoWesolowskiCallback* weso, bool& stop_signal, tcp::socket& sock) {\n    Proof result = ProveTwoWeso(D, f, iters, 0, weso, 0, stop_signal);\n    if (stop_signal) {\n        PrintInfo(\"Got stop signal before completing the proof!\");\n        return ;\n    }\n    WriteProof(iters, result, sock);\n}\n\nvoid InitSession(tcp::socket& sock) {\n    boost::system::error_code error;\n\n    memset(disc,0x00,sizeof(disc)); // For null termination\n    memset(disc_size,0x00,sizeof(disc_size)); // For null termination\n\n    boost::asio::read(sock, boost::asio::buffer(disc_size, 3), error);\n    disc_int_size = atoi(disc_size);\n    boost::asio::read(sock, boost::asio::buffer(disc, disc_int_size), error);\n\n    if (error == boost::asio::error::eof)\n        return ; // Connection closed cleanly by peer.\n    else if (error)\n        throw boost::system::system_error(error); // Some other error.\n\n    if (getenv( \"warn_on_corruption_in_production\" )!=nullptr) {\n        warn_on_corruption_in_production=true;\n    }\n    if (is_vdf_test) {\n        PrintInfo( \"=== Test mode ===\" );\n    }\n    if (warn_on_corruption_in_production) {\n        PrintInfo( \"=== Warn on corruption enabled ===\" );\n    }\n    assert(is_vdf_test); //assertions should be disabled in VDF_MODE==0\n    init_gmp();\n    allow_integer_constructor=true; //make sure the old gmp allocator isn't used\n    set_rounding_mode();\n}\n\nvoid FinishSession(tcp::socket& sock) {\n    try {\n        // Tell client I've stopped everything, wait for ACK and close.\n        boost::system::error_code error;\n\n        PrintInfo(\"Stopped everything! Ready for the next challenge.\");\n\n        std::lock_guard<std::mutex> lock(socket_mutex);\n        boost::asio::write(sock, boost::asio::buffer(\"STOP\", 4));\n\n        char ack[5];\n        memset(ack,0x00,sizeof(ack));\n        boost::asio::read(sock, boost::asio::buffer(ack, 3), error);\n        assert (strncmp(ack, \"ACK\", 3) == 0);\n    } catch (std::exception& e) {\n        PrintInfo(\"Exception in thread: \" + to_string(e.what()));\n    }\n}\n\nuint64_t ReadIteration(tcp::socket& sock) {\n    boost::system::error_code error;\n    char data[20];\n    memset(data, 0, sizeof(data));\n    boost::asio::read(sock, boost::asio::buffer(data, 2), error);\n    int size = (data[0] - '0') * 10 + (data[1] - '0');\n    memset(data, 0, sizeof(data));\n    boost::asio::read(sock, boost::asio::buffer(data, size), error);\n    uint64_t iters = 0;\n    for (int i = 0; i < size; i++)\n        iters = iters * 10 + data[i] - '0';       \n    return iters;\n}\n\nvoid SessionFastAlgorithm(tcp::socket& sock) {\n    InitSession(sock);\n    try {\n        integer D(disc);\n        integer L=root(-D, 4);\n        form f=form::generator(D);\n        PrintInfo(\"Discriminant = \" + to_string(D.impl));\n\n        std::vector<std::thread> threads;\n        const bool multi_proc_machine = (std::thread::hardware_concurrency() >= 16) ? true : false;\n        WesolowskiCallback* weso = new FastAlgorithmCallback(segments, D, multi_proc_machine);\n        FastStorage* fast_storage = NULL;\n        if (multi_proc_machine) {\n            fast_storage = new FastStorage((FastAlgorithmCallback*)weso);   \n        }\n        bool stopped = false;\n        std::thread vdf_worker(repeated_square, f, std::ref(D), std::ref(L), weso, fast_storage, std::ref(stopped));\n        ProverManager pm(D, (FastAlgorithmCallback*)weso, fast_storage, segments, thread_count);        \n        pm.start();\n\n        // Tell client that I'm ready to get the challenges.\n        boost::asio::write(sock, boost::asio::buffer(\"OK\", 2));\n\n        while (!stopped) {\n            uint64_t iters = ReadIteration(sock);\n            if (iters == 0) {\n                PrintInfo(\"Got stop signal!\");\n                stopped = true;\n                pm.stop();\n                vdf_worker.join();\n                for (int t = 0; t < threads.size(); t++) {\n                    threads[t].join();\n                }\n                if (fast_storage != NULL) {\n                    delete(fast_storage);\n                }\n                delete(weso);\n            } else {\n                PrintInfo(\"Received iteration: \" + to_string(iters));\n                threads.push_back(std::thread(CreateAndWriteProof, std::ref(pm), iters, std::ref(stopped), std::ref(sock)));\n            }\n        }\n    } catch (std::exception& e) {\n        PrintInfo(\"Exception in thread: \" + to_string(e.what()));\n    }\n    FinishSession(sock);\n}\n\nvoid SessionOneWeso(tcp::socket& sock) {\n    InitSession(sock);\n    try {\n        integer D(disc);\n        integer L=root(-D, 4);\n        form f=form::generator(D);\n        PrintInfo(\"Discriminant = \" + to_string(D.impl));\n\n        // Tell client that I'm ready to get the challenges.\n        boost::asio::write(sock, boost::asio::buffer(\"OK\", 2));\n\n        uint64_t iter = ReadIteration(sock);\n        bool stopped = false;\n        WesolowskiCallback* weso = new OneWesolowskiCallback(D, iter);\n        FastStorage* fast_storage = NULL;\n        std::thread vdf_worker(repeated_square, f, std::ref(D), std::ref(L), weso, fast_storage, std::ref(stopped));\n\n        Proof proof = ProveOneWesolowski(iter, D, (OneWesolowskiCallback*)weso, stopped);\n        WriteProof(iter, proof, sock);\n\n        iter = ReadIteration(sock);\n        while (iter != 0) {\n            std::cout << \"Warning: did not receive stop signal\\n\";\n            iter = ReadIteration(sock);\n        }\n        stopped = true;\n        vdf_worker.join();\n        delete(weso);\n    } catch (std::exception& e) {\n        PrintInfo(\"Exception in thread: \" + to_string(e.what()));\n    }\n    FinishSession(sock);\n}\n\nvoid SessionTwoWeso(tcp::socket& sock) {\n    const int kMaxProcessesAllowed = 3;\n    InitSession(sock);\n    try {\n        integer D(disc);\n        integer L=root(-D, 4);\n        form f = form::generator(D);\n        PrintInfo(\"Discriminant = \" + to_string(D.impl));\n\n        // Tell client that I'm ready to get the challenges.\n        boost::asio::write(sock, boost::asio::buffer(\"OK\", 2));\n\n        bool stopped = false;\n        bool stop_vector[100];\n        std::vector<std::thread> threads;\n        // (iteration, thread_id)\n        std::set<std::pair<uint64_t, uint64_t> > seen_iterations;\n        WesolowskiCallback* weso = new TwoWesolowskiCallback(D);\n        FastStorage* fast_storage = NULL;\n        std::thread vdf_worker(repeated_square, f, std::ref(D), std::ref(L), weso, fast_storage, std::ref(stopped));\n\n        while (!stopped) {\n            uint64_t iters = ReadIteration(sock);\n            if (iters == 0) {\n                PrintInfo(\"Got stop signal!\");\n                stopped = true;\n                for (int i = 0; i < threads.size(); i++)\n                    stop_vector[i] = true;\n                for (int t = 0; t < threads.size(); t++) {\n                    threads[t].join();\n                }\n                vdf_worker.join();\n                delete(weso);\n            } else {\n                uint64_t max_iter = 0;\n                uint64_t max_iter_thread_id = -1;\n                uint64_t min_iter = 1ULL << 62;\n                bool unique = true;\n                for (auto active_iter: seen_iterations) {\n                    if (active_iter.first > max_iter) {\n                        max_iter = active_iter.first;\n                        max_iter_thread_id = active_iter.second;\n                    }\n                    if (active_iter.first < min_iter) {\n                        min_iter = active_iter.first;\n                    }\n                    if (active_iter.first == iters) {\n                        unique = false;\n                        break;\n                    }\n                }\n                if (!unique) {\n                    PrintInfo(\"Duplicate iteration \" + to_string(iters) + \"... Ignoring.\");\n                    continue;\n                }\n                if (iters >= kMaxProcessesAllowed - 500000) {\n                    PrintInfo(\"Too big iter... ignoring\");\n                    continue;\n                }\n                if (threads.size() < kMaxProcessesAllowed || iters < min_iter) {\n                    seen_iterations.insert({iters, threads.size()});\n                    PrintInfo(\"Running proving for iter: \" + to_string(iters));\n                    stop_vector[threads.size()] = false;\n                    threads.push_back(std::thread(CreateAndWriteProofTwoWeso, std::ref(D), f, iters,\n                                      (TwoWesolowskiCallback*)weso, std::ref(stop_vector[threads.size()]), \n                                      std::ref(sock)));\n                    if (threads.size() > kMaxProcessesAllowed) {\n                        PrintInfo(\"Stopping proving for iter: \" + to_string(max_iter));\n                        stop_vector[max_iter_thread_id] = true;\n                        seen_iterations.erase({max_iter, max_iter_thread_id});\n                    }\n                }\n            }\n        }\n    } catch (std::exception& e) {\n        PrintInfo(\"Exception in thread: \" + to_string(e.what()));\n    }\n    FinishSession(sock);\n}\n\nint gcd_base_bits=50;\nint gcd_128_max_iter=3;\n\nint main(int argc, char* argv[])\n{\n  try\n  {\n    if (argc != 4)\n    {\n      std::cerr << \"Usage: ./vdf_client <host> <port>\\n\";\n      return 1;\n    }\n\n    if(hasAVX2())\n    {\n      gcd_base_bits=63;\n      gcd_128_max_iter=2;\n    }\n\n    boost::asio::io_service io_service;\n\n    tcp::resolver resolver(io_service);\n    tcp::resolver::query query(tcp::v6(), argv[1], argv[2], boost::asio::ip::resolver_query_base::v4_mapped);\n    tcp::resolver::iterator iterator = resolver.resolve(query);\n\n    tcp::socket s(io_service);\n    boost::asio::connect(s, iterator);\n    fast_algorithm = false;\n    two_weso = false;\n    boost::system::error_code error;\n    char prover_type_buf[5];\n    boost::asio::read(s, boost::asio::buffer(prover_type_buf, 1), error);\n    // Check for \"S\" (simple weso), \"N\" (n-weso), or \"T\" (2-weso)\n    if (prover_type_buf[0] == 'S') {\n        SessionOneWeso(s);\n    }\n    if (prover_type_buf[0] == 'N') {\n        fast_algorithm = true;\n        SessionFastAlgorithm(s);\n    }\n    if (prover_type_buf[0] == 'T') {\n        two_weso = true;\n        SessionTwoWeso(s);\n    }\n  } catch (std::exception& e) {\n    std::cerr << \"Exception: \" << e.what() << \"\\n\";\n  } \n  return 0;\n}\n", "meta": {"hexsha": "6d60cd2d03f7ef9d84f93a3afc96efd8e2f32e13", "size": 12376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vdf_client.cpp", "max_stars_repo_name": "cr-marcstevens/chiavdf", "max_stars_repo_head_hexsha": "16c967c38874f352f172a088b741b814a7219b2f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-23T14:39:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T14:39:23.000Z", "max_issues_repo_path": "src/vdf_client.cpp", "max_issues_repo_name": "cr-marcstevens/chiavdf", "max_issues_repo_head_hexsha": "16c967c38874f352f172a088b741b814a7219b2f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vdf_client.cpp", "max_forks_repo_name": "cr-marcstevens/chiavdf", "max_forks_repo_head_hexsha": "16c967c38874f352f172a088b741b814a7219b2f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T12:28:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T12:28:49.000Z", "avg_line_length": 35.8724637681, "max_line_length": 136, "alphanum_fraction": 0.5730446025, "num_tokens": 3065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.02556521633614946, "lm_q1q2_score": 0.012682746073452896}}
{"text": "#include <cstdint>\n\n#include <algorithm>\n#include <exception>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/as_vector.hpp>\n#include <boost/fusion/include/io.hpp>\n#include <boost/locale.hpp>\n#include <boost/optional/optional_io.hpp>\n#include <boost/optional.hpp>\n#include <boost/spirit/home/x3.hpp>\n#include <boost/variant.hpp>\n#include <boost/variant/get.hpp>\n\n#include \"common.hpp\"\n#include \"regex_parser.hpp\"\n#include \"config.hpp\"\n\n\nnamespace fusion = boost::fusion;\nnamespace x3 = boost::spirit::x3;\n\n\nstatic_assert(sizeof(char32_t) == sizeof(wchar_t), \"wchar is not 32bit, but it's required for spirit x3\");\n\n\nnamespace ast {\n    using optional_n = boost::optional<unsigned int>;\n\n    using multiplier_amount = unsigned int;\n\n    struct multiplier_range {\n        optional_n min;\n        optional_n max;\n\n        multiplier_range() = default;\n        multiplier_range(const optional_n& min, const optional_n& max) : min(min), max(max) {}\n    };\n\n    struct multiplier_plus {};\n    struct multiplier_question {};\n    struct multiplier_star {};\n\n    using multiplier = boost::variant<multiplier_range, multiplier_amount, multiplier_plus, multiplier_question, multiplier_star>;\n\n    using character = char32_t;\n\n    struct character_range {\n        character begin;\n        character end;\n\n        character_range() = default;\n        character_range(character begin, character end) : begin(begin), end(end) {}\n    };\n\n    using characterclass_element = boost::variant<character_range, character>;\n\n    using characterclass = std::vector<characterclass_element>;\n\n    using word = std::vector<character>;\n\n    using chunkcontent = boost::variant<characterclass, word>;\n\n    struct chunk {\n        chunkcontent content;\n        boost::optional<multiplier> amount;\n    };\n\n    using regex = std::vector<chunk>;\n\n    using fusion::operator<<;\n}\n\nBOOST_FUSION_ADAPT_STRUCT(ast::multiplier_range, min, max)\nBOOST_FUSION_ADAPT_STRUCT(ast::character_range, begin, end)\nBOOST_FUSION_ADAPT_STRUCT(ast::chunk, content, amount)\n\n\nnamespace parser {\n    static x3::rule<class multiplier_amount, ast::multiplier_amount> multiplier_amount = \"multiplier_amount\";\n    static x3::rule<class multiplier_range, ast::multiplier_range> multiplier_range = \"multiplier_range\";\n    static x3::rule<class multiplier_plus, ast::multiplier_plus> multiplier_plus = \"multiplier_plus\";\n    static x3::rule<class multiplier_question, ast::multiplier_question> multiplier_question = \"multiplier_question\";\n    static x3::rule<class multiplier_star, ast::multiplier_star> multiplier_star = \"multiplier_star\";\n    static x3::rule<class multiplier, ast::multiplier> multiplier = \"multiplier\";\n    static x3::rule<class character, ast::character> character = \"character\";\n    static x3::rule<class character_range, ast::character_range> character_range = \"character_range\";\n    static x3::rule<class characterclass_element, ast::characterclass_element> characterclass_element = \"characterclass_element\";\n    static x3::rule<class characterclass, ast::characterclass> characterclass = \"characterclass\";\n    static x3::rule<class word, ast::word> word = \"word\";\n    static x3::rule<class chunkcontent, ast::chunkcontent> chunkcontent = \"chunkcontent\";\n    static x3::rule<class chunk, ast::chunk> chunk = \"chunk\";\n    static x3::rule<class regex, ast::regex> regex = \"regex\";\n\n    auto const multiplier_amount_def = '{' >> x3::uint_ >> '}';\n    auto const multiplier_range_def = '{' >> -x3::uint_ >> ',' >> -x3::uint_ >> '}';\n    auto const multiplier_plus_def = x3::omit['+'];\n    auto const multiplier_question_def = x3::omit['?'];\n    auto const multiplier_star_def = x3::omit['*'];\n    auto const multiplier_def = multiplier_range | multiplier_amount | multiplier_plus | multiplier_question | multiplier_star;\n    auto const character_def = x3::char_ - '[' - ']' - '{' - '}' - '+' - '*' - '?' - '-' - static_cast<wchar_t>(0x00000000) - static_cast<wchar_t>(0xffffffff);\n    auto const character_range_def = character >> '-' >> character;\n    auto const characterclass_element_def = character_range | character;\n    auto const characterclass_def = '[' >> +(characterclass_element) >> ']';\n    auto const wordelement_def = characterclass | character;\n    auto const word_def = +character;\n    auto const chunkcontent_def = characterclass | word;\n    auto const chunk_def = chunkcontent >> (-multiplier);\n    auto const regex_def = +chunk;\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-parameter\"\n    BOOST_SPIRIT_DEFINE(\n        multiplier_amount,\n        multiplier_range,\n        multiplier_plus,\n        multiplier_question,\n        multiplier_star,\n        multiplier,\n        character,\n        character_range,\n        characterclass_element,\n        characterclass,\n        word,\n        chunkcontent,\n        chunk,\n        regex\n    )\n#pragma clang diagnostic pop\n}\n\n\nast::regex parse_ast(const std::u32string& input) {\n    ast::regex result;\n    auto it = input.begin();\n    auto end = input.end();\n    bool r = phrase_parse(it, end, parser::regex, x3::standard_wide::space, result);\n    if (r && it == end) {\n        return result;\n    } else {\n        std::string msg(\"malformed regex: \");\n        auto pos = static_cast<std::size_t>(it - input.begin());\n        std::stringstream errmsg;\n        errmsg << msg << boost::locale::conv::utf_to_utf<char>(input) << std::endl\n            << std::string(msg.size() + pos, ' ') << \"^\";\n        throw user_error(errmsg.str());\n    }\n}\n\n\nnamespace graph {\n    using slot_inner_t = std::vector<std::uint32_t>;\n    using slot_t = std::shared_ptr<slot_inner_t>;\n\n    slot_t make_slot(std::initializer_list<uint32_t> data) {\n        return std::make_shared<slot_inner_t>(data);\n    }\n\n    struct node {\n        std::vector<std::pair<char32_t, slot_t>> next;\n        std::uint32_t id;\n\n        node(std::uint32_t& id) : id(id++) {}\n    };\n    using node_t = std::shared_ptr<node>;\n    using graph_t = std::vector<node_t>;\n}\n\n\nnamespace transformers {\n    using collection_slots_t = std::vector<graph::slot_t>;\n    using transformer_result_t = std::pair<graph::graph_t, collection_slots_t>;\n\n    class characterclass_element_visitor : public boost::static_visitor<ast::character_range> {\n        public:\n            ast::character_range operator()(const ast::character& character) const {\n                return ast::character_range(character, character);\n            }\n\n            ast::character_range operator()(const ast::character_range& character_range) const {\n                return character_range;\n            }\n    };\n\n    class generic_visitor : public boost::static_visitor<transformer_result_t> {\n        public:\n            generic_visitor(std::uint32_t& id, collection_slots_t slots) : id(id), slots(slots) {}\n\n        protected:\n            std::uint32_t& id;\n            collection_slots_t slots;\n    };\n\n    class character_transformer : public generic_visitor {\n        public:\n            using generic_visitor::generic_visitor;\n\n            transformer_result_t operator()(const ast::character& character) const {\n                // 1. create new node\n                auto result = std::make_shared<graph::node>(id);\n\n                // 2. connect last ones to this one\n                for (auto& last : slots) {\n                    last->push_back(result->id);\n                }\n\n                // 3. fill this one\n                result->next.push_back(std::make_pair(0, graph::make_slot({serial::id_fail})));\n                result->next.push_back(std::make_pair(character, graph::make_slot({})));\n                result->next.push_back(std::make_pair(character + 1, graph::make_slot({serial::id_fail})));\n\n                // 4. get slots\n                collection_slots_t slots_new{std::get<1>(result->next[1])};\n\n                // 5. done\n                return {graph::graph_t{std::move(result)}, slots_new};\n            }\n    };\n\n    class chunkcontent_transformer : public generic_visitor {\n        public:\n            using generic_visitor::generic_visitor;\n\n            transformer_result_t operator()(const ast::word& word) const {\n                graph::graph_t result_nodes;\n                collection_slots_t slots_new = slots;\n                for (const auto& character : word) {\n                    auto sub_result = character_transformer(id, slots_new)(character);\n                    result_nodes.insert(result_nodes.end(), std::get<0>(sub_result).begin(), std::get<0>(sub_result).end());\n                    slots_new = std::get<1>(sub_result);\n                }\n                return std::make_pair(result_nodes, slots_new);\n            }\n\n            transformer_result_t operator()(const ast::characterclass& characterclass) const {\n                // 1. create new node\n                auto result = std::make_shared<graph::node>(id);\n\n                // 2. connect last ones to this one\n                for (auto& last : slots) {\n                    last->push_back(result->id);\n                }\n\n                // 3. prepare and merge ranges\n                std::vector<ast::character_range> ranges;\n                for (const auto& x : characterclass) {\n                    ranges.push_back(boost::apply_visitor(characterclass_element_visitor(), x));\n                }\n                std::sort(ranges.begin(), ranges.end(), [](const ast::character_range& a, const ast::character_range& b) {\n                    return a.begin < b.begin;\n                });\n                std::vector<ast::character_range> ranges_dedup;\n                for (const auto& x : ranges) {\n                    if (ranges_dedup.empty()) {\n                        ranges_dedup.push_back(x);\n                    } else {\n                        auto& last = ranges_dedup[ranges_dedup.size() - 1];\n                        if (x.begin <= last.end + 1) {\n                            last.end = x.end;\n                        } else {\n                            ranges_dedup.push_back(x);\n                        }\n                    }\n                }\n                if (ranges_dedup.size() > cfg::max_ranges) {\n                    throw user_error(\"Too many ranges in character class!\");\n                }\n\n                // 4. fill this one\n                result->next.push_back(std::make_pair(0, graph::make_slot({serial::id_fail})));\n                collection_slots_t slots_new{};\n                char32_t last_char = 0;\n                for (const auto& r : ranges_dedup) {\n                    if (last_char > 0) { // add range up to this element, skip first\n                        result->next.push_back(std::make_pair(last_char + 1, graph::make_slot({serial::id_fail})));\n                    }\n                    result->next.push_back(std::make_pair(r.begin, graph::make_slot({})));\n                    slots_new.push_back(std::get<1>(result->next[result->next.size() - 1]));\n                    last_char = r.end;\n                }\n                result->next.push_back(std::make_pair(last_char + 1, graph::make_slot({serial::id_fail})));\n\n                // 4. done\n                return {graph::graph_t{std::move(result)}, slots_new};\n            }\n    };\n\n    class multiplier_transformator : public generic_visitor {\n        public:\n            multiplier_transformator(std::uint32_t& id, collection_slots_t slots, const ast::chunkcontent& content) : generic_visitor(id, slots), content(content) {}\n\n            transformer_result_t operator()(const ast::multiplier_amount& amount) const {\n                return doit(amount, ast::optional_n(amount));\n            }\n\n            transformer_result_t operator()(const ast::multiplier_range& range) const {\n                std::size_t min = 0;\n                if (range.min) {\n                    min = *(range.min);\n                }\n                if (range.max && *(range.max) < min) {\n                    throw user_error(\"Illegal regex multiplier!\");\n                }\n                return doit(min, range.max);\n            }\n\n            transformer_result_t operator()(const ast::multiplier_plus& /*plus*/) const {\n                return doit(1, boost::none);\n            }\n\n            transformer_result_t operator()(const ast::multiplier_question& /*question*/) const {\n                return doit(0, ast::optional_n(1));\n            }\n\n            transformer_result_t operator()(const ast::multiplier_star& /*star*/) const {\n                return doit(0, boost::none);\n            }\n\n        protected:\n            const ast::chunkcontent& content;\n\n            transformer_result_t doit(std::size_t min, ast::optional_n max) const {\n                if (min > cfg::max_multiplier) {\n                    throw user_error(\"multiplier minimum is too large!\");\n                }\n                if (max && *max > cfg::max_multiplier) {\n                    throw user_error(\"multiplier maximum is too large!\");\n                }\n                graph::graph_t nodes_result;\n\n                // 1. start with the words we need at least\n                collection_slots_t slots_current = slots;\n                graph::graph_t nodes_current;\n                std::size_t i = 0;\n                for (; i < min; ++i) {\n                    auto sub_result = boost::apply_visitor(chunkcontent_transformer(id, slots_current), content);\n                    nodes_result.insert(nodes_result.end(), nodes_current.begin(), nodes_current.end());\n                    std::tie(nodes_current, slots_current) = sub_result;\n                }\n\n                // 2. add optional words\n                collection_slots_t slots_result;\n                if (max) {\n                    // some maximum => emit nodes, add all of them to result\n                    // also emit 1 additional word, so we can link it to FAIL\n\n                    // a) create nodes\n                    for (; i <= *max; ++i) {\n                        auto sub_result = boost::apply_visitor(chunkcontent_transformer(id, slots_current), content);\n                        nodes_result.insert(nodes_result.end(), nodes_current.begin(), nodes_current.end());\n                        slots_result.insert(slots_result.end(), slots_current.begin(), slots_current.end());\n                        std::tie(nodes_current, slots_current) = sub_result;\n                    }\n\n                    // b) now link the last node to FAIL, do NOT add it to slots_result\n                    nodes_result.insert(nodes_result.end(), nodes_current.begin(), nodes_current.end());\n                    for (auto& slot : slots_current) {\n                        slot->push_back(serial::id_fail);\n                    }\n                } else {\n                    // no max => create new word and link slots to nodes current (loop)\n\n                    // a) create node\n                    auto sub_result = boost::apply_visitor(chunkcontent_transformer(id, slots_current), content);\n                    nodes_result.insert(nodes_result.end(), nodes_current.begin(), nodes_current.end());\n                    slots_result.insert(slots_result.end(), slots_current.begin(), slots_current.end());\n                    std::tie(nodes_current, slots_current) = sub_result;\n\n                    // b) link it\n                    nodes_result.insert(nodes_result.end(), nodes_current.begin(), nodes_current.end());\n                    for (auto& slot : slots_current) {\n                        slot->push_back(nodes_current[0]->id);\n                    }\n                    slots_result.insert(slots_result.end(), slots_current.begin(), slots_current.end());\n                }\n\n                // done\n                return {nodes_result, slots_result};\n            }\n    };\n\n    class chunk_transfomer : public generic_visitor {\n        public:\n            using generic_visitor::generic_visitor;\n\n            transformer_result_t operator()(const ast::chunk& chunk) const {\n                if (chunk.amount) {\n                    return boost::apply_visitor(multiplier_transformator(id, slots, chunk.content), *(chunk.amount));\n                } else {\n                    return boost::apply_visitor(chunkcontent_transformer(id, slots), chunk.content);\n                }\n            }\n    };\n}\n\n\ngraph::graph_t ast_to_graph(const ast::regex& r) {\n    // start graph\n    std::uint32_t id = 0;\n    graph::graph_t nodes;\n    nodes.push_back(std::make_shared<graph::node>(id)); // FAIL node\n    nodes.push_back(std::make_shared<graph::node>(id)); // OK node\n    transformers::collection_slots_t slots; // no slots yet\n\n    // iterate over entire regex\n    for (const auto& chunk : r) {\n        auto sub_result = transformers::chunk_transfomer(id, slots)(chunk);\n        nodes.insert(nodes.end(), std::get<0>(sub_result).begin(), std::get<0>(sub_result).end());\n        slots = std::get<1>(sub_result);\n    }\n\n    // fill remaining slots with good outcome\n    for (auto& last : slots) {\n        last->push_back(serial::id_ok);\n    }\n\n    sanity_assert(id == nodes.size(), \"Some nodes are lost :(\");;\n    return nodes;\n}\n\n\ntemplate <typename T>\nvoid write_to_buffer(serial::buffer& b, std::size_t base, T element) {\n    static_assert(sizeof(serial::word) == 4, \"ups, need to rewrite the serializer!\");\n    static_assert(sizeof(T) % sizeof(serial::word) == 0, \"that doesn't match the word boundaries!\");\n\n    // XXX: check big vs little endian!\n    for (std::size_t i = 0; i < sizeof(T) / sizeof(serial::word); ++i) {\n        b[base + i] = (element >> (8 * 4 * i)) & 0xffffffff;\n    }\n}\n\n\nserial::graph serialize(const graph::graph_t& g) {\n    // 1. calculate maximum numbers for allocations\n    std::size_t n = g.size();\n    std::size_t m = 0;\n    std::size_t o = 0;\n    for (const auto& node : g) {\n        m = std::max(m, node->next.size());\n        for (const auto& value_slot : node->next) {\n            o = std::max(o, std::get<1>(value_slot)->size());\n        }\n    }\n\n    // 2. create buffer\n    serial::graph result(n, o);\n    // at this point, the dispatch table exists\n\n    // 3. write data\n    for (std::size_t i_node = 0; i_node < n; ++i_node) {\n        const auto& node = g[i_node];\n        std::size_t base_node = result.size();\n\n        // write current size to dispatch table\n        write_to_buffer(result.data, i_node, static_cast<serial::id>(base_node));\n\n        // start node by writing its size\n        result.grow(1);\n        write_to_buffer(result.data, base_node, static_cast<serial::id>(node->next.size()));\n\n        // write node body\n        std::size_t base_node_body = base_node + 1;\n        for (std::size_t i_value_slot = 0; i_value_slot < node->next.size(); ++i_value_slot) {\n            const auto& value_slot = node->next[i_value_slot];\n\n            std::size_t base_value_slot = base_node_body + i_value_slot * (1 + o);\n            serial::character c = std::get<0>(value_slot);\n\n            // write character that belongs to slot\n            result.grow(1);\n            write_to_buffer(result.data, base_value_slot, c);\n\n            // write fixed size, sorted, dedup data to slot\n            std::size_t base_value_slot_payload = base_value_slot + 1;\n            std::vector<std::uint32_t> entries_sorted(std::get<1>(value_slot)->begin(), std::get<1>(value_slot)->end());\n            std::sort(entries_sorted.begin(), entries_sorted.end());\n            entries_sorted.erase(std::unique(entries_sorted.begin(), entries_sorted.end()), entries_sorted.end());\n            for (std::size_t i_slot_entry = 0; i_slot_entry < o; ++i_slot_entry) {\n                result.grow(1);\n                if (i_slot_entry < entries_sorted.size()) {\n                    std::size_t base_slot_entry = base_value_slot_payload + i_slot_entry;\n                    serial::id id = entries_sorted[i_slot_entry];\n                    write_to_buffer(result.data, base_slot_entry, id);\n                } // else => data is 0\n            }\n        }\n    }\n\n    // 4. done\n    return result;\n}\n\n\nserial::graph string_to_graph(const std::u32string& input) {\n    auto r = parse_ast(input);\n    if (r.empty()) {\n        throw user_error(\"Empty regex is not allowed!\");\n    }\n\n    auto g = ast_to_graph(r);\n\n    return serialize(g);\n}\n", "meta": {"hexsha": "cd00550a37dbb8621a72967dfcb51d5f29b1f17d", "size": 20230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/regex_parser.cpp", "max_stars_repo_name": "seasvv/oclgrep", "max_stars_repo_head_hexsha": "84ac865056733c2535c1d539da0af4896dee39fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-11T12:37:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-26T20:24:03.000Z", "max_issues_repo_path": "src/regex_parser.cpp", "max_issues_repo_name": "seasvv/oclgrep", "max_issues_repo_head_hexsha": "84ac865056733c2535c1d539da0af4896dee39fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regex_parser.cpp", "max_forks_repo_name": "seasvv/oclgrep", "max_forks_repo_head_hexsha": "84ac865056733c2535c1d539da0af4896dee39fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-06-11T12:38:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T01:02:13.000Z", "avg_line_length": 39.5890410959, "max_line_length": 165, "alphanum_fraction": 0.5894710826, "num_tokens": 4410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.033589509277931646, "lm_q1q2_score": 0.012681405797391826}}
{"text": "#pragma once\n#include \"vector.hpp\"\n#include \"matrix.hpp\"\n#include \"quat.hpp\"\n#include \"bits.hpp\"\n#include \"abstbuff.hpp\"\n#include \"error.hpp\"\n#include \"optional.hpp\"\n#include <cassert>\n#include <cstring>\n#include <boost/regex_fwd.hpp>\n#include \"structure/angle.hpp\"\n\nnamespace spn {\n\t//! Y軸を上とした時のZベクトルに対するXベクトルを算出, またはベクトルに垂直なベクトルを得る\n\ttemplate <bool A>\n\tVecT<3,A> GetVerticalVec(const VecT<3,A>& zvec) {\n\t\tusing VT = VecT<3,A>;\n\t\tauto vt = zvec % VT(0,1,0);\n\t\tif(vt.len_sq() < 1e-6f)\n\t\t\tvt = zvec % VT(1,0,0);\n\t\treturn vt.normalization();\n\t}\n\ttemplate <bool A>\n\tspn::Optional<VecT<3,A>> NormalFromPoints(const VecT<3,A>& v0,const VecT<3,A>& v1, const VecT<3,A>& v2) {\n\t\tauto tmp = (v1 - v0) % (v2 - v0);\n\t\tif(tmp.len_sq() < 1e-6f)\n\t\t\treturn spn::none;\n\t\treturn tmp.normalization();\n\t}\n\t//! 任意の戻り値を返す関数 (定義のみ)\n\ttemplate <class T>\n\tT ReturnT();\n\t//! 関数の戻り値型を取得\n\t/*! ReturnType<T>::type */\n\ttemplate <class T>\n\tstruct ReturnType;\n\ttemplate <class RT, class... Args>\n\tstruct ReturnType<RT (*)(Args...)> {\n\t\tusing type = RT; };\n\ttemplate <class RT, class OBJ, class... Args>\n\tstruct ReturnType<RT (OBJ::*)(Args...)> {\n\t\tusing type = RT; };\n\ttemplate <class RT, class OBJ, class... Args>\n\tstruct ReturnType<RT (OBJ::*)(Args...) const> {\n\t\tusing type = RT; };\n\tinline uint32_t ARGBtoRGBA(uint32_t val) {\n\t\treturn (val & 0xff00ff00) | ((val>>16)&0xff) | ((val&0xff)<<16);\n\t}\n\tinline uint32_t SetAlphaR(uint32_t val) {\n\t\treturn (val & 0x00ffffff) | ((val&0xff)<<24);\n\t}\n\n\t//! ポインタ読み替え変換\n\ttemplate <class T0, class T1>\n\tinline T1 RePret(const T0& val) {\n\t\tstatic_assert(sizeof(T0) == sizeof(T1), \"invalid reinterpret value\");\n\t\treturn *reinterpret_cast<const T1*>(&val);\n\t}\n\t//! aがb以上だったらaからsizeを引いた値を返す\n\tinline int CndSub(int a, int b, int size) {\n\t\treturn a - (size & ((b - a - 1) >> 31));\n\t}\n\t//! aがb以上だったらaからbを引いた値を返す\n\tinline int CndSub(int a, int b) {\n\t\treturn CndSub(a, b, b);\n\t}\n\t//! aがbより小さかったらaにsizeを足した値を返す\n\tinline int CndAdd(int a, int b, int size) {\n\t\treturn a + (size & ((a - b) >> 31));\n\t}\n\t//! aが0より小さかったらaにsizeを足した値を返す\n\tinline int CndAdd(int a, int size) {\n\t\treturn CndAdd(a, 0, size);\n\t}\n\t//! aがlowerより小さかったらsizeを足し、upper以上だったらsizeを引く\n\tinline int CndRange(int a, int lower, int upper, int size) {\n\t\treturn a + (size & ((a - lower) >> 31))\n\t\t\t\t\t- (size & ((upper - a - 1) >> 31));\n\t}\n\t//! aが0より小さかったらsizeを足し、size以上だったらsizeを引く\n\tinline int CndRange(int a, int size) {\n\t\treturn CndRange(a, 0, size, size);\n\t}\n\t//! ポインタの読み替え\n\ttemplate <class T, class T2>\n\tT* ReinterpretPtr(T2* ptr) {\n\t\tusing TD = typename std::decay<T2>::type;\n\t\tstatic_assert(std::is_integral<TD>::value || std::is_floating_point<TD>::value, \"typename T must number\");\n\t\treturn reinterpret_cast<T*>(ptr);\n\t}\n\t//! リファレンスの読み替え\n\ttemplate <class T, class T2>\n\tT& ReinterpretRef(T2& val) {\n\t\treturn *reinterpret_cast<T*>(&val);\n\t}\n\t//! 値の読み替え\n\ttemplate <class T, class T2>\n\tT ReinterpretValue(const T2& val) {\n\t\treturn *reinterpret_cast<const T*>(&val);\n\t}\n\tconstexpr uint32_t FloatOne = 0x3f800000;\t\t//!< 1.0fの、整数表現\n\t//! 引数がプラスなら1, マイナスなら-1を返す\n\tfloat inline PlusMinus1(float val) {\n\t\tauto ival = spn::ReinterpretValue<uint32_t>(val);\n\t\treturn spn::ReinterpretValue<float>(FloatOne | (ival & 0x80000000));\n\t}\n\t//! PlusMinus1(float)の引数がintバージョン\n\tfloat inline PlusMinus1(int val) {\n\t\treturn spn::ReinterpretValue<float>(FloatOne | ((val>>31) & 0x80000000)); }\n\t//! PlusMinus1(float)の引数がunsigned intバージョン\n\tfloat inline PlusMinus1(unsigned int val) { return PlusMinus1(static_cast<int>(val)); }\n\t//! 2次元ベクトルを係数で混ぜ合わせる\n\tVec2 MixVector(const float (&cf)[3], const Vec2& p0, const Vec2& p1, const Vec2& p2);\n\t//! 重心座標を計算\n\tvoid BarycentricCoord(float ret[3], const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& pos);\n\t//! クラメルの公式で使う行列式を計算\n\tfloat CramerDet(const Vec3& v0, const Vec3& v1, const Vec3& v2);\n\tfloat CramerDet(const Vec2& v0, const Vec2& v1);\n\t//! 3元1次方程式の解をクラメルの公式を用いて計算\n\t/*! @param detInv[in] 行列式(v0,v1,v2)の逆数 */\n\tVec3 CramersRule(const Vec3& v0, const Vec3& v1, const Vec3& v2, const Vec3& a0, float detInv);\n\t//! 2元1次方程式を計算\n\tVec2 CramersRule(const Vec2& v0, const Vec2& v1, const Vec2& a0, float detInv);\n\t//! グラム・シュミットの正規直交化法\n\tvoid GramSchmidtOrth(Vec3& v0, Vec3& v1, Vec3& v2);\n\n\tstruct YawPitchDist {\n\t\tRadF\tyaw, pitch;\n\t\tfloat\tdistance;\n\t\t//! 方向ベクトルをYaw,Pitch,Distanceに分解\n\t\tstatic YawPitchDist FromPos(const spn::Vec3& pos);\n\t\t//! YawPitchDistの位置から座標原点を見る姿勢\n\t\tstd::pair<spn::Vec3, spn::Quat> toOffsetRot() const;\n\t};\n\tstd::ostream& operator << (std::ostream& os, const YawPitchDist& ypd);\n\n\tstruct AffineParts {\n\t\tAVec3 offset,\n\t\t\t\tscale;\n\t\tAQuat rotation;\n\t\t//! アフィン成分分解\n\t\tstatic AffineParts Decomp(const AMat43& m);\n\t};\n\t//! ソースコード文字列に行番号を付ける\n\t/*! \\param[in] src 元のソースコード\n\t\t\\param[in] numOffset 最初の数値(0や負数だとその分は番号を振らない)\n\t\t\\param[in] viewNum 行番号の表示を開始する位置\n\t\t\\param[in] bPrevLR 最初に改行を入れるか\n\t\t\\param[in] bPostLR 最後に改行を入れるか*/\n\tstd::string AddLineNumber(const std::string& src, int numOffset, int viewNum, bool bPrevLR, bool bPostLR);\n\n\tusing OPLinePos = spn::Optional<std::pair<int, typename std::string::const_iterator>>;\n\t//! regexに合致する最初の行\n\t/*!\t\\param[in] str 検索する文字列\n\t\t\\param[in] re 検索パターン(行単位)\n\t\t\\retval 合致する行が見つかった時: std::pair<先頭からの行番号, その位置>\n\t\t\\retval 見つからなかった時: spn::none*/\n\tOPLinePos RegexFindFirst(const std::string& str, const boost::regex& re);\n\t//! regexに合致する最後の行\n\tOPLinePos RegexFindLast(const std::string& str, const boost::regex& re);\n}\n", "meta": {"hexsha": "93d8fafd71652b4d6eba57a641b32bd2865dfeb7", "size": 5337, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "misc.hpp", "max_stars_repo_name": "degarashi/spinner", "max_stars_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc.hpp", "max_issues_repo_name": "degarashi/spinner", "max_issues_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc.hpp", "max_forks_repo_name": "degarashi/spinner", "max_forks_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_forks_repo_licenses": ["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.7423312883, "max_line_length": 108, "alphanum_fraction": 0.6814689901, "num_tokens": 2211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.025957354372137545, "lm_q1q2_score": 0.012674545125724499}}
{"text": "/*\n * Copyright 2015 David A. Boyuka II\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 * cblq-setops-nary2.cpp\n *\n *  Created on: Mar 25, 2014\n *      Author: David A. Boyuka II\n */\n\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\n#include <boost/smart_ptr.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n\n#include \"pique/region/cblq/cblq.hpp\"\n#include \"pique/setops/setops.hpp\"\n#include \"pique/setops/cblq/cblq-setops.hpp\"\n\nstruct child_ind_helper {\n\ttypedef uint16_t lookup_index_t;\n\tstatic constexpr int BITS_PER_CODE = 2;\n\tstatic constexpr int BITS_PER_LOOKUP = sizeof(lookup_index_t) * 8;\n\tstatic constexpr int CODES_PER_LOOKUP = BITS_PER_LOOKUP / BITS_PER_CODE;\n\tstatic constexpr uint64_t LOOKUP_ENTRIES = 1ULL << BITS_PER_LOOKUP;\n\tstatic constexpr lookup_index_t LOOKUP_MASK = ~(lookup_index_t)0;\n\n\tuint64_t children[CODES_PER_LOOKUP];\n\tint nchildren;\n\n\tstatic child_ind_helper CHILD_IND_TABLE[LOOKUP_ENTRIES];\n\tstatic bool CHILD_IND_TABLE_INIT;\n\n\tstatic void ensure_init();\n};\n\nbool child_ind_helper::CHILD_IND_TABLE_INIT = false;\nchild_ind_helper child_ind_helper::CHILD_IND_TABLE[LOOKUP_ENTRIES];\nvoid child_ind_helper::ensure_init() {\n\tif (CHILD_IND_TABLE_INIT)\n\t\treturn;\n\n\tfor (uint64_t word = 0; word < LOOKUP_ENTRIES; word++) {\n\t\tuint64_t *out = CHILD_IND_TABLE[word].children;\n\t\tfor (int i = 0; i < CODES_PER_LOOKUP; i++) {\n\t\t\tif (word & (0b10 << i * BITS_PER_CODE)) {// Two code\n\t\t\t\t*out = i;\n\t\t\t\t++out;\n\t\t\t}\n\t\t}\n\t\tCHILD_IND_TABLE[word].nchildren = out - CHILD_IND_TABLE[word].children;\n\t}\n\tCHILD_IND_TABLE_INIT = true;\n}\n\ntemplate<int ndim>\ninline static int count_two_codes(typename CBLQRegionEncoding<ndim>::cblq_word_t word) {\n\tstatic constexpr int NUM_LOOKUPS = (CBLQRegionEncoding<ndim>::CODES_PER_WORD - 1) / child_ind_helper::CODES_PER_LOOKUP + 1;\n\n\tint children = 0;\n\tfor (int i = 0; i < NUM_LOOKUPS; ++i) {\n\t\tconst typename child_ind_helper::lookup_index_t lookup_key = ((word >> (i * child_ind_helper::BITS_PER_LOOKUP)) & child_ind_helper::LOOKUP_MASK);\n\t\tchildren += child_ind_helper::CHILD_IND_TABLE[lookup_key].nchildren;\n\t}\n\n\treturn children;\n}\n\ntemplate<int ndim>\ninline static void append_child_inds(typename CBLQRegionEncoding<ndim>::cblq_word_t word, uint64_t base_ind, typename std::vector< int64_t >::iterator &out_inds_it) {\n\tstatic constexpr int NUM_LOOKUPS = (CBLQRegionEncoding<ndim>::CODES_PER_WORD - 1) / child_ind_helper::CODES_PER_LOOKUP + 1;\n\n\tif (CBLQRegionEncoding<ndim>::CODES_PER_WORD <= child_ind_helper::CODES_PER_LOOKUP) {\n\t\tconst child_ind_helper &lookup = child_ind_helper::CHILD_IND_TABLE[word];\n\n\t\tconst uint64_t *child_ind_offset = lookup.children;\n\t\tconst int nchildren = lookup.nchildren;\n\n\t\tfor (int i = 0; i < CBLQRegionEncoding<ndim>::CODES_PER_WORD; ++i)\n\t\t\tout_inds_it[i] = base_ind + child_ind_offset[i]; // This will overflow the valid end of out_level_inds, but we allocated enough extra sentinel space earlier so that it won't segfault\n\n\t\tout_inds_it += nchildren;\n\t} else {\n\t\tfor (int lookupnum = 0; lookupnum < NUM_LOOKUPS; ++lookupnum) {\n\t\t\tconst typename child_ind_helper::lookup_index_t lookup_key = (word >> (lookupnum * child_ind_helper::BITS_PER_LOOKUP)) & child_ind_helper::LOOKUP_MASK;\n\t\t\tconst child_ind_helper &lookup = child_ind_helper::CHILD_IND_TABLE[lookup_key];\n\n\t\t\tconst uint64_t *child_ind_offset = lookup.children;\n\t\t\tconst int nchildren = lookup.nchildren;\n\n\t\t\tfor (int i = 0; i < child_ind_helper::CODES_PER_LOOKUP; ++i)\n\t\t\t\tout_inds_it[i] = base_ind + child_ind_offset[i] + lookupnum * child_ind_helper::CODES_PER_LOOKUP;\n\n\t\t\tout_inds_it += nchildren;\n\t\t}\n\t}\n}\n\n// Handles postprocessing after iterating over a CBLQ level:\n// 1. Densely remaps inds produced by the level for use during the next level\n// 2. Maps any 3-codes into 1-codes\n// 3. Computes the level_len for the output CBLQ's next level\ntemplate<int ndim, NArySetOperation op>\ninline static void level_postprocess(\n\t\ttypename std::vector< typename CBLQRegionEncoding<ndim>::cblq_word_t >::iterator next_level_word_it,\n\t\tconst std::vector< uint64_t > &out_level_inds_operand_ends,\n\t\tstd::vector< int64_t > &inds /* in: output of prev level, out: input of next level */,\n\t\tuint64_t &level_len /* in: prev level, out: next level */)\n{\n\tstatic const int64_t CHUNK_SIZE = 1ULL << 13;\n\tusing cblq_word_t = typename CBLQRegionEncoding<ndim>::cblq_word_t;\n\n\tassert(CHUNK_SIZE % CBLQRegionEncoding<ndim>::CODES_PER_WORD == 0);\n\n\t// First, compute the compaction mapping for the outinds (remove all indices pointing to NO-OP and DELETE actions)\n\tconst int64_t max_ind = level_len * CBLQRegionEncoding<ndim>::CODES_PER_WORD; // One ind per code in the output of this level\n\tstd::vector< int64_t > ind_mapping;\n\n\tconst size_t num_operands = out_level_inds_operand_ends.size();\n\n\tint64_t mapped_ind = 0;\n\n\tauto scan_word_it = next_level_word_it;\n\n\tstd::vector< typename std::vector<int64_t>::iterator > ind_update_its;\n\tstd::vector< typename std::vector<int64_t>::iterator > ind_update_end_its;\n\tfor (auto operand_end_it = out_level_inds_operand_ends.begin(); operand_end_it != out_level_inds_operand_ends.end(); ++operand_end_it) {\n\t\tuint64_t operand_end_off = *operand_end_it;\n\t\tind_update_its.push_back(ind_update_end_its.empty() ? inds.begin() : ind_update_end_its.back());\n\t\tind_update_end_its.push_back(inds.begin() + operand_end_off);\n\t}\n\n\tfor (int64_t chunk_begin_ind = 0; chunk_begin_ind < max_ind; chunk_begin_ind += CHUNK_SIZE) {\n\t\tconst int64_t chunk_end_ind = std::min(chunk_begin_ind + CHUNK_SIZE, max_ind);\n\t\tconst int64_t cur_chunk_size = chunk_end_ind - chunk_begin_ind;\n\t\tind_mapping.clear();\n\t\tind_mapping.resize(cur_chunk_size, -1); // Initially, all inds map to -1 (i.e. DELETE)\n\n\t\tfor (int64_t cur_ind = 0; cur_ind < cur_chunk_size; ++scan_word_it) {\n\t\t\tcblq_word_t word = *scan_word_it;\n\t\t\tif (op == NArySetOperation::UNION) {\n\t\t\t\tword &= ~((word & CBLQRegionEncoding<ndim>::ONE_CODES_WORD) << 1); // Fix 3-codes -> 1-codes\n\t\t\t} else if (op == NArySetOperation::INTERSECTION) {\n\t\t\t\t// FF->FF\n\t\t\t\t// FT->FT\n\t\t\t\t// TF->FF\n\t\t\t\t// TT->TF\n\n\t\t\t\t// XY &= Y1, XY &= 1(~X)\n\n\t\t\t\tword &= (word << 1) | CBLQRegionEncoding<ndim>::ONE_CODES_WORD;\n\t\t\t\tword &= (~word >> 1) | CBLQRegionEncoding<ndim>::TWO_CODES_WORD;\n\t\t\t} else\n\t\t\t\tabort();\n\t\t\t*scan_word_it = word;\n\n\t\t\tfor (int codepos = 0; codepos < CBLQRegionEncoding<ndim>::CODES_PER_WORD; ++codepos, ++cur_ind) {\n\t\t\t\tif (word & 0b10 << (codepos * CBLQRegionEncoding<ndim>::BITS_PER_CODE))\n\t\t\t\t\tind_mapping[cur_ind] = mapped_ind++;\n\t\t\t}\n\t\t}\n\n\t\t// Densely remap all outinds produced\n\t\tfor (int operand = 0; operand < num_operands; operand++) {\n\t\t\tauto ind_update_it = ind_update_its[operand];\n\t\t\tauto ind_update_end_it = ind_update_end_its[operand];\n\t\t\tfor (; ind_update_it != ind_update_end_it; ++ind_update_it) {\n\t\t\t\tconst int64_t ind = *ind_update_it;\n\t\t\t\tif (ind >= 0) {\n\t\t\t\t\tif (ind >= chunk_end_ind)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse\n\t\t\t\t\t\t*ind_update_it = ind_mapping[ind - chunk_begin_ind];\n\t\t\t\t}\n\t\t\t}\n\t\t\tind_update_its[operand] = ind_update_it;\n\t\t}\n\t}\n\n\tlevel_len = mapped_ind; // Exclusive upper bound on all mapped outinds\n}\n\ntemplate<int ndim>\ntemplate<NArySetOperation op>\ninline boost::shared_ptr< CBLQRegionEncoding<ndim> >\nCBLQSetOperationsNAry3Fast<ndim>::nary_set_op_impl(RegionEncodingCPtrCIter cblq_it, RegionEncodingCPtrCIter cblq_end_it) const {\n\tconst boost::optional< bool > common_has_dense_suffix = CBLQRegionEncoding<ndim>::deduce_common_suffix_density(cblq_it, cblq_end_it);\n\tassert(common_has_dense_suffix); // all operands must have compatible suffix density (i.e., each the same/empty)\n\n\tconst int levels = (*cblq_it)->get_num_levels();\n\tconst bool has_dense_suffix = *common_has_dense_suffix;\n\tconst int non_dense_levels = has_dense_suffix ? levels - 1 : levels;\n\tconst uint64_t domain_size = (*cblq_it)->get_domain_size();\n\n\t// Initialize iterators to traverse through the words of each CBLQ operand passed to this function (as well as the implicit \"this\" CBLQ)\n\tsize_t num_operands = 0;\n\tstd::vector< typename std::vector<cblq_word_t>::const_iterator > cblq_word_its;\n\tstd::vector< typename std::vector<cblq_word_t>::const_iterator > cblq_word_end_its;\n\tstd::vector< typename std::vector<uint64_t>::const_iterator > cblq_level_len_its;\n\tfor (auto it = cblq_it; it != cblq_end_it; it++) {\n\t\tconst CBLQRegionEncoding<ndim> &cblq = **it; // first * = deref iterator, second * = deref pointer to CBLQ that the iterator was holding\n\t\t// Ensure uniform level count and suffix denseness across all CBLQs\n\t\tassert(cblq.get_num_levels() == levels);\n\t\t//assert(cblq.has_dense_suffix == has_dense_suffix); // now checked above\n\t\tassert(cblq.domain_size == domain_size);\n\n\t\tnum_operands++;\n\t\tcblq_word_its.push_back(cblq.words.cbegin());\n\t\tcblq_word_end_its.push_back(cblq.words.cend());\n\t\tcblq_level_len_its.push_back(cblq.level_lens.cbegin());\n\t}\n\n\t// Allocate a new CBLQ for output\n\tboost::shared_ptr< CBLQRegionEncoding<ndim> > output = boost::make_shared< CBLQRegionEncoding<ndim> >(domain_size);\n\toutput->has_dense_suffix = has_dense_suffix;\n\toutput->level_lens.resize(levels);\n\n\tstd::vector<cblq_word_t> &output_words = output->words;\n\n\t// Input operand target index array. Produced in the previous step, indicates which output CBLQ word should be modified by each input word\n\t// Outind arrays are packed back-to-back, since it is known how many belong to each operand (= operand.level_lens[level])\n\tstd::vector<int64_t> in_level_inds(num_operands, 0); // Fill with 0 indices for each operand\n\n\t// Output operand target index array. Built up during processing of a level, then dense-compacted and moved to in_level_outinds\n\tstd::vector<int64_t> out_level_inds;\n\tstd::vector<uint64_t> out_level_inds_operand_ends(num_operands);\n\n\t// Size of level for the next iteration (computed at the end of each iteration for the next iteration)\n\tsize_t next_level_len = 1;\n\n\t// For each CBLQ level\n\tfor (int level = 0; level < non_dense_levels; level++) {\n\t\toutput->level_lens[level] = next_level_len; // The number of words we will output this level is already known: it's the number of non-delete actions that are queued\n\n\t\t// Allocate space in out_level_inds\n\t\tif (level + 1 < levels) {\n\t\t\tuint64_t expected_out_inds = 0; // The number of inds produced by the next level is\n\t\t\tif (level + 1 < non_dense_levels) { // Next level is the dense suffix\n\t\t\t\tfor (size_t operand = 0; operand < num_operands; ++operand)\n\t\t\t\t\texpected_out_inds += *(cblq_level_len_its[operand] + 1); // Add the number of words in the next level\n\t\t\t} else {\n\t\t\t\tfor (auto it = cblq_it; it != cblq_end_it; ++it)\n\t\t\t\t\texpected_out_inds += (*it)->dense_suffix->get_num_semiwords(); // Add the number of semiwords in the next level\n\t\t\t}\n\t\t\tout_level_inds.resize(expected_out_inds + CBLQRegionEncoding<ndim>::CODES_PER_WORD /* Extra sentinel to allow intentional overrun */);\n\t\t} else {\n\t\t\tout_level_inds.resize(CBLQRegionEncoding<ndim>::CODES_PER_WORD /* Extra sentinel to allow intentional overrun */);\n\t\t}\n\n\t\t// Allocate space in output_words and set up the base iterator\n\t\tconst size_t prev_output_words_size = output_words.size();\n\t\toutput_words.resize(prev_output_words_size + next_level_len, (op == NArySetOperation::UNION) ? CBLQRegionEncoding<ndim>::ZERO_CODES_WORD : CBLQRegionEncoding<ndim>::ONE_CODES_WORD);\n\t\tconst auto level_output_words_it = output_words.begin() + prev_output_words_size;\n\n\t\t// Set up in and out ind iterators\n\t\tauto in_inds_it = in_level_inds.cbegin();\n\t\tauto out_inds_it = out_level_inds.begin();\n\n\t\t// For each operand, apply all CBLQ words to the proper locations in the output (or skip them if they are to be deleted)\n\t\tfor (size_t operand = 0; operand < num_operands; operand++) {\n\t\t\tauto &cblq_level_len_it = cblq_level_len_its[operand];\n\t\t\tconst uint64_t level_len = *cblq_level_len_it;\n\t\t\t++cblq_level_len_it;\n\n\t\t\tauto cblq_word_it = cblq_word_its[operand]; // Get the CBLQ word iterator for this CBLQ\n\t\t\tauto cblq_word_end_it = cblq_word_it + level_len;\n\n\t\t\t// For each action in which this operand participates\n\t\t\twhile (cblq_word_it != cblq_word_end_it) {\n\t\t\t\tconst int64_t ind = *in_inds_it;\n\t\t\t\t++in_inds_it;\n\n\t\t\t\tif (ind >= 0) { // BINARY SETOP\n\t\t\t\t\tcblq_word_t oper_cblq_word = *cblq_word_it;\n\t\t\t\t\t++cblq_word_it;\n\n\t\t\t\t\tif (op == NArySetOperation::UNION) {\n\t\t\t\t\t\tlevel_output_words_it[ind] |= oper_cblq_word; // Works for all cases but 1 union 2 resulting in 3. This is cleaned up later\n\t\t\t\t\t} else if (op == NArySetOperation::INTERSECTION) {\n\t\t\t\t\t\tlevel_output_words_it[ind] |= (oper_cblq_word & CBLQRegionEncoding<ndim>::TWO_CODES_WORD); // Add any 2 codes from oper_cblq_word to output\n\t\t\t\t\t\tlevel_output_words_it[ind] &= (oper_cblq_word | (oper_cblq_word >> 1) | CBLQRegionEncoding<ndim>::TWO_CODES_WORD); // Convert 1-codes to 0-codes and 3-codes to 2-codes for any 0-code in the input\n\t\t\t\t\t} else\n\t\t\t\t\t\tabort();\n\n\t\t\t\t\tconst uint64_t base_ind = ind * CBLQRegionEncoding<ndim>::CODES_PER_WORD;\n\t\t\t\t\tappend_child_inds<ndim>(oper_cblq_word, base_ind, out_inds_it); // This will overflow the valid end of out_level_inds, but we allocated enough extra sentinel space earlier so that it won't segfault\n\t\t\t\t} else { // DELETE\n\t\t\t\t\t// Skip the specified number of words, counting the number of two codes therein\n\t\t\t\t\tint64_t skip_children = 0;\n\t\t\t\t\tfor (int64_t i = 0; i < -ind; ++i) {\n\t\t\t\t\t\tskip_children += count_two_codes<ndim>(*cblq_word_it);\n\t\t\t\t\t\t++cblq_word_it;\n\t\t\t\t\t}\n\t\t\t\t\t// If there were any skipped two codes, enqueue a delete action covering all of them now\n\t\t\t\t\tif (skip_children) {\n\t\t\t\t\t\t*out_inds_it = -skip_children;\n\t\t\t\t\t\t++out_inds_it;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcblq_word_its[operand] = cblq_word_it;\n\t\t\tout_level_inds_operand_ends[operand] = out_inds_it - out_level_inds.begin();\n\t\t}\n\n\t\t// Post-process the output of the previous step\n\t\tif (level < levels - 1) {\n\t\t\tout_level_inds.resize(out_level_inds.size() - CBLQRegionEncoding<ndim>::CODES_PER_WORD); // Remove the extra sentinel for overflow so that the vector is tight (level_postprocess relies on an accurate size())\n\t\t\tlevel_postprocess<ndim, op>(level_output_words_it, out_level_inds_operand_ends, out_level_inds, next_level_len); // updates out_level_inds and next_level_len\n\t\t\tin_level_inds = std::move(out_level_inds);\n\t\t\tout_level_inds.clear();\n\t\t}\n\t}\n\n\tif (has_dense_suffix) {\n\t\tusing semiword_block_t = typename CBLQSemiwords<ndim>::block_t;\n\t\tconst int BITS_PER_BLOCK = std::numeric_limits<semiword_block_t>::digits;\n\n\t\t// Set the (non-dense) leaf level length to 0\n\t\toutput->level_lens[levels - 1] = 0;\n\n\t\t// Collect dense suffix information and iterators\n\t\tstd::vector< uint64_t > dense_level_lens;\n\t\tstd::vector< typename std::vector< semiword_block_t >::const_iterator > in_block_its;\n\t\tfor (auto it = cblq_it; it != cblq_end_it; it++) {\n\t\t\tconst CBLQRegionEncoding<ndim> &cblq = **it;\n\t\t\tdense_level_lens.push_back(cblq.dense_suffix->get_num_semiwords());\n\t\t\tcblq.dense_suffix->ensure_padded();\n\t\t\tin_block_its.push_back(cblq.dense_suffix->semiwords.begin());\n\t\t}\n\n\t\t// Set up output\n\t\tCBLQSemiwords<ndim> &output_semiwords = *output->dense_suffix;\n\t\tstd::vector< semiword_block_t > &output_blocks = output_semiwords.semiwords;\n\n\t\toutput_semiwords.num_semiwords = next_level_len;\n\t\toutput_blocks.clear();\n\t\toutput_blocks.resize(next_level_len / CBLQSemiwords<ndim>::SEMIWORDS_PER_BLOCK + 1, 0);\n\n\t\t// Process dense suffixes\n\t\tauto in_inds_it = in_level_inds.begin();\n\t\tfor (size_t operand = 0; operand < num_operands; ++operand) {\n\t\t\tconst uint64_t dense_level_len = dense_level_lens[operand];\n\t\t\tauto in_block_it = in_block_its[operand];\n\n\t\t\tsemiword_block_t cur_block = *in_block_it;\n\t\t\tuint64_t in_block_shift = 0;\n\t\t\tfor (uint64_t i = 0; i < dense_level_len;) {\n\t\t\t\tconst int64_t ind = *in_inds_it;\n\t\t\t\t++in_inds_it;\n\n\t\t\t\tif (ind >= 0) {\n\t\t\t\t\t// Compute intersection via De Morgan's Law (negation of union of negations). This is the inner negation.\n\t\t\t\t\tconst semiword_block_t semiword =\n\t\t\t\t\t\t\top == NArySetOperation::UNION ?\n\t\t\t\t\t\t\t\t\t((cur_block >> in_block_shift) & CBLQSemiwords<ndim>::SEMIWORD_MASK) :\n\t\t\t\t\t\t\t\t\t(((~cur_block) >> in_block_shift) & CBLQSemiwords<ndim>::SEMIWORD_MASK);\n\n\t\t\t\t\tconst uint64_t ind_block = ind / CBLQSemiwords<ndim>::SEMIWORDS_PER_BLOCK;\n\t\t\t\t\tconst int ind_shift = ind % CBLQSemiwords<ndim>::SEMIWORDS_PER_BLOCK * CBLQRegionEncoding<ndim>::BITS_PER_SEMIWORD;\n\n\t\t\t\t\toutput_blocks[ind_block] |= (semiword << ind_shift);\n\n\t\t\t\t\t++i;\n\t\t\t\t\tin_block_shift += CBLQRegionEncoding<ndim>::BITS_PER_SEMIWORD;\n\t\t\t\t\tif (in_block_shift == BITS_PER_BLOCK) {\n\t\t\t\t\t\tcur_block = *++in_block_it;\n\t\t\t\t\t\tin_block_shift = 0;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst int64_t skip = -ind;\n\t\t\t\t\tin_block_shift += (skip * CBLQRegionEncoding<ndim>::BITS_PER_SEMIWORD);\n\t\t\t\t\ti += skip;\n\n\t\t\t\t\tif (in_block_shift >= BITS_PER_BLOCK) {\n\t\t\t\t\t\tin_block_it += in_block_shift / BITS_PER_BLOCK;\n\t\t\t\t\t\tin_block_shift = in_block_shift % BITS_PER_BLOCK;\n\t\t\t\t\t\tcur_block = *in_block_it;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Compute intersection via De Morgan's Law (negation of union of negations). This is the outer negation.\n\t\tif (op == NArySetOperation::INTERSECTION) {\n\t\t\tfor (auto it = output_blocks.begin(); it != output_blocks.end(); ++it)\n\t\t\t\t*it = ~*it;\n\t\t}\n\t}\n\n\treturn output;\n}\n\ntemplate<int ndim>\nboost::shared_ptr< CBLQRegionEncoding<ndim> >\nCBLQSetOperationsNAry3Fast<ndim>::nary_set_op_impl(RegionEncodingCPtrCIter cblq_it, RegionEncodingCPtrCIter cblq_end_it, NArySetOperation op) const {\n\tchild_ind_helper::ensure_init();\n\n\tboost::shared_ptr< CBLQRegionEncoding<ndim> > output;\n\tif (op == NArySetOperation::UNION)\n\t\toutput = this->nary_set_op_impl<NArySetOperation::UNION>(cblq_it, cblq_end_it);\n\telse if (op == NArySetOperation::INTERSECTION)\n\t\toutput = this->nary_set_op_impl<NArySetOperation::INTERSECTION>(cblq_it, cblq_end_it);\n\telse\n\t\treturn this->nary_set_op_default_impl(cblq_it, cblq_end_it, op);\n\n\t// Finally, compact the output CBLQ if requested\n\tif (this->conf.compact_after_setop)\n\t\toutput->compact();\n\n\treturn output;\n}\n\n//template<int ndim>\n//boost::shared_ptr< CBLQRegionEncoding<ndim> >\n//CBLQSetOperationsNAry3Fast<ndim>::binary_set_op(boost::shared_ptr< const CBLQRegionEncoding<ndim> > left, boost::shared_ptr< const CBLQRegionEncoding<ndim> > right, NArySetOperation op) const {\n//\tstd::vector< boost::shared_ptr< CBLQRegionEncoding<ndim> > > operands = {\n//\t\tboost::const_pointer_cast< CBLQRegionEncoding<ndim> >(left),\n//\t\tboost::const_pointer_cast< CBLQRegionEncoding<ndim> >(right)\n//\t};\n//\n//\tif (op == NArySetOperation::UNION || op == NArySetOperation::INTERSECTION)\n//\t\treturn this->template CBLQSetOperationsNAry3Fast<ndim>::nary_set_op(operands.begin(), operands.end(), op);\n//\telse\n//\t\treturn this->template CBLQSetOperationsFast<ndim>::binary_set_op(left, right, op);\n//}\n\n// Explicit instantiation of 2D-4D CBLQ N-ary set operations\ntemplate class CBLQSetOperationsNAry3Fast<2>;\ntemplate class CBLQSetOperationsNAry3Fast<3>;\ntemplate class CBLQSetOperationsNAry3Fast<4>;\n", "meta": {"hexsha": "9d6de0a8ef39fd1e2b2c6490d8016b6148df980f", "size": 19432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/setops/cblq/cblq-setops-nary3-fast.cpp", "max_stars_repo_name": "daboyuka/PIQUE", "max_stars_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_stars_repo_licenses": ["ECL-2.0", "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/setops/cblq/cblq-setops-nary3-fast.cpp", "max_issues_repo_name": "daboyuka/PIQUE", "max_issues_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/setops/cblq/cblq-setops-nary3-fast.cpp", "max_forks_repo_name": "daboyuka/PIQUE", "max_forks_repo_head_hexsha": "d0e2ba4cc47aaeaf364b3c76339306e1795adb5e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.1822222222, "max_line_length": 210, "alphanum_fraction": 0.7371346233, "num_tokens": 5531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.026355352846119753, "lm_q1q2_score": 0.012663185094989763}}
{"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 <string>\n#include <boost/tuple/tuple.hpp>\n\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp>\n#include <boost/numeric/mtl/matrix/transposed_view.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/operation/sub_matrix.hpp>\n#include <boost/numeric/mtl/recursion/matrix_recursator.hpp>\n#include <boost/numeric/mtl/recursion/base_case_test.hpp>\n#include <boost/numeric/mtl/recursion/for_each.hpp>\n\n\n\nusing namespace std;  \n\n\ntemplate <typename Recursator>\nvoid print_depth_first(Recursator const& recursator, string str)\n{\n    if (recursator.is_empty())\n\treturn;\n    cout << \"\\nRecursion: \" << str << endl << *recursator;\n\n  \n    // for full recursion remove the string length limitation\n    if (!recursator.is_leaf()) { \n\tprint_depth_first(recursator.north_west(), string(\"north west of \") + str);\n\tprint_depth_first(recursator.south_west(), string(\"south west of \") + str);\n\tprint_depth_first(recursator.north_east(), string(\"north east of \") + str);\n\tprint_depth_first(recursator.south_east(), string(\"south east of \") + str);\n    }\n} \n\n\ntemplate <typename Recursator, typename BaseCaseTest>\nvoid recursive_print(Recursator const& recursator, string str, BaseCaseTest const& is_base)\n{\n    if (is_base(recursator))\n\tcout << \"\\nBase case: \" << str << endl << *recursator;\n    else {\n\trecursive_print(recursator.north_west(), string(\"north west of \") + str, is_base);\n\trecursive_print(recursator.south_west(), string(\"south west of \") + str, is_base);\n\trecursive_print(recursator.north_east(), string(\"north east of \") + str, is_base);\n\trecursive_print(recursator.south_east(), string(\"south east of \") + str, is_base);\n    }\n} \n\n\ntemplate <typename Recursator, typename BaseCaseTest>\nvoid recursive_print_checked(Recursator const& recursator, string str, BaseCaseTest const& is_base)\n{\n    if (recursator.is_empty())\n\treturn;\n    if (is_base(recursator)) {\n\tcout << \"\\nBase case: \" << str << endl << *recursator;\n    } else {\n\trecursive_print_checked(recursator.north_west(), string(\"north west of \") + str, is_base);\n\trecursive_print_checked(recursator.south_west(), string(\"south west of \") + str, is_base);\n\trecursive_print_checked(recursator.north_east(), string(\"north east of \") + str, is_base);\n\trecursive_print_checked(recursator.south_east(), string(\"south east of \") + str, is_base);\n    }\n} \n\nstruct print_functor\n{\n    template <typename Matrix>\n    void operator() (Matrix const& matrix) const\n    {\n\tcout << matrix << endl;\n    }\n};\n\ntemplate <typename Matrix>\nvoid test_sub_matrix(Matrix& matrix)\n{\n    using mtl::recursion::for_each; using mtl::recursion::max_dim_test; \n    using mtl::mat::recursator; using mtl::transposed_view;\n\n    cout << matrix << endl;    \n    \n    max_dim_test              is_base(2);\n    recursator<Matrix>        rec(matrix);\n    recursive_print_checked(rec, \"\", is_base);\n\t \n    cout << \"\\n====================\\n\"\n\t <<   \"Same with transposed\\n\"\n\t <<   \"====================\\n\\n\";\n\n    transposed_view<Matrix> trans_matrix(matrix);\n\n    cout << trans_matrix; \n    recursator< transposed_view<Matrix> > trans_recursator(trans_matrix);\n    // print_depth_first(trans_recursator, \"\");\n    recursive_print_checked(trans_recursator, \"\", is_base);\n\t \n    cout << \"\\n=============================\\n\"\n\t <<   \"Again with recursive for_each\\n\"\n\t <<   \"=============================\\n\\n\";\n\n    for_each(trans_recursator, print_functor(), is_base);\n}\n\n\ntemplate <typename Matrix>\nvoid fill_matrix(Matrix& matrix)\n{\n    namespace traits = mtl::traits;\n    using mtl::begin; using mtl::end;\n\n    typename traits::row<Matrix>::type                                 row(matrix);\n    typename traits::col<Matrix>::type                                 col(matrix);\n    typename traits::value<Matrix>::type                               value(matrix);\n    typedef  glas::tag::nz                                          tag;\n    typedef typename traits::range_generator<tag, Matrix>::type        cursor_type;\n    \n    double x= 10.3;\n    for (cursor_type cursor = begin<tag>(matrix), cend = end<tag>(matrix); cursor != cend; ++cursor) {\n\tvalue(*cursor, x);\n\tx+= 1.0; \n    }\n       \n}\n  \n \nint main(int, char**)\n{\n    using namespace mtl;\n\n    cout << \"=====================\\n\"\n\t << \"Morton-ordered matrix\\n\"\n\t << \"=====================\\n\\n\";\n\n    typedef morton_dense<double,  0x55555555> matrix_type;    \n    matrix_type matrix(6, 5);   \n    fill_matrix(matrix); \n    test_sub_matrix(matrix);\n\n    cout << \"\\n=========================\\n\"\n\t << \"Doppler matrix (4x4 base)\\n\"\n\t << \"=========================\\n\\n\";\n\n    typedef morton_dense<double,  0x55555553> dmatrix_type;    \n    dmatrix_type dmatrix(6, 5);   \n    fill_matrix(dmatrix); \n    test_sub_matrix(dmatrix);\n\n    cout << \"\\n======================\\n\"\n\t << \"Row-major dense matrix\\n\"\n\t << \"======================\\n\\n\";\n\n    dense2D<double, mat::parameters<> >   rmatrix(non_fixed::dimensions(6, 5));\n    fill_matrix(rmatrix); \n    test_sub_matrix(rmatrix);\n \n    cout << \"=================================\\n\"\n\t << \"Vector-like morton-ordered matrix\\n\"\n\t << \"=================================\\n\\n\";\n\n    matrix_type vmatrix(17, 2);   \n    fill_matrix(vmatrix); \n    test_sub_matrix(vmatrix);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "03c4c17875184bef36410a2385d4360860537043", "size": 5802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/sub_matrix_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/sub_matrix_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/sub_matrix_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 32.0552486188, "max_line_length": 102, "alphanum_fraction": 0.630989314, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.03904829412408659, "lm_q1q2_score": 0.012660839224848798}}
{"text": "//! 行列クラス基底ヘッダ\n/*! 他行列との演算を除いたメソッドを定義 */\n#if !BOOST_PP_IS_ITERATING\n\t#if !defined(MATRIX_H_) || INCLUDE_MATRIX_LEVEL >= 1\n\t\t#define MATRIX_H_\n\t\t#include <boost/preprocessor.hpp>\n\t\t#include <boost/serialization/access.hpp>\n\t\t#include <boost/serialization/level.hpp>\n\t\t#include <cstring>\n\t\t#include <stdexcept>\n\t\t#include <cassert>\n\t\t#include \"vector.hpp\"\n\t\t#include \"tostring.hpp\"\n\t\t#include \"structure/angle.hpp\"\n\t\t#include \"random/matrix.hpp\"\n\n\t\t// 定義する行列の次元(M,N)\n\t\t#define SEQ_MATDEF\t((2,2))((2,3))((2,4))((4,2))((3,2))((3,3))((3,4))((4,3))((4,4))\n\t\t#define LEN_SEQ\t\tBOOST_PP_SEQ_SIZE(SEQ_MATDEF)\n\t\t#define LEN_SEQ_M1\tBOOST_PP_DEC(LEN_SEQ)\n\n\t\t// 要求された定義レベルを実体化\n\t\t#ifndef INCLUDE_MATRIX_LEVEL\n\t\t\t#define INCLUDE_MATRIX_LEVEL 0\n\t\t#endif\n\t\t#define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LEN_SEQ_M1, \"matrix.hpp\", INCLUDE_MATRIX_LEVEL))\n\t\t#include BOOST_PP_ITERATE()\n\t\t#undef INCLUDE_MATRIX_LEVEL\n\t#endif\n#elif BOOST_PP_ITERATION_DEPTH() == 1\n\t// アラインメントイテレーション\n\t#define BOOST_PP_ITERATION_PARAMS_2 (3, (0, 1, \"matrix.hpp\"))\n\t#include BOOST_PP_ITERATE()\n#else\n\t#define TUP\tBOOST_PP_SEQ_ELEM(BOOST_PP_FRAME_ITERATION(1), SEQ_MATDEF)\n\t#define DIM_M\tBOOST_PP_TUPLE_ELEM(0, TUP)\n\t#define DIM_N\tBOOST_PP_TUPLE_ELEM(1, TUP)\n\t#define ALIGN\tBOOST_PP_ITERATION()\n\t#define ALIGNB\tBOOLNIZE(ALIGN)\n\t#define ALIGN16 BOOST_PP_IF(ALIGN, alignas(16), NOTHING)\n\t#define MT\t\tMatT<DIM_M, DIM_N, ALIGNB>\n\t#define DMAX \tBOOST_PP_MAX(DIM_M, DIM_N)\n\t#define DMIN \tBOOST_PP_MIN(DIM_M, DIM_N)\n\t#define DMUL\tBOOST_PP_MUL(DIM_M, DIM_N)\n\n\t#define DIMTUPLE(n,i)\t\t\t\tBOOST_PP_TUPLE_ELEM(i, BOOST_PP_SEQ_ELEM(n, SEQ_MATDEF))\n\t#define DEF_CONV_ITR(z,n,data)\t\tdata(DIMTUPLE(n,0), DIMTUPLE(n,1), 0) data(DIMTUPLE(n,0), DIMTUPLE(n,1), 1)\n\n\t#define DIM\t\tDIM_N\n\t#define DEFINE_MATRIX\n\t#include \"local_macro.hpp\"\n\n\t#if BOOST_PP_FRAME_FLAGS(1) == 0\n\t\tnamespace spn {\n\t\t\t// row-major\n\t\t\ttemplate <>\n\t\t\tstruct ALIGN16 MatT<DIM_M, DIM_N, ALIGNB> : MatBase, boost::equality_comparable<MT> {\n\t\t\t\tusing Row = VecT<DIM_N, ALIGNB>;\t\t\t//!< 行を表すベクトル型\n\t\t\t\tusing Column = VecT<DIM_M, false>;\t\t\t//!< 列を表すベクトル型\n\t\t\t\tusing RowE = VecT<4, ALIGNB>;\t\t\t\t//!< 4要素の行ベクトル型\n\t\t\t\tusing AMat = MatT<DIM_M, DIM_N, true>;\n\t\t\t\tusing UMat = MatT<DIM_M, DIM_N, false>;\n\t\t\t\tusing UVec2 = VecT<2,false>;\n\t\t\t\tusing UVec3 = VecT<3,false>;\n\n\t\t\t\tconstexpr static int width = DIM_N,\n\t\t\t\t\t\t\t\t\theight = DIM_M,\n\t\t\t\t\t\t\t\tPaddingedSize = BOOST_PP_IF(ALIGN, 4, DIM_N),\n\t\t\t\t\t\t\t\tAlignedSize = DIM_M*4-(4-DIM_N),\n\t\t\t\t\t\t\t\tUnAlignedSize = DIM_M*DIM_N;\n\t\t\t\tconstexpr static bool align = ALIGNB;\n\t\t\t\tunion {\n\t\t\t\t\t//! 容量確保用\n\t\t\t\t\tfloat\tdata[BOOST_PP_IF(ALIGN, AlignedSize, UnAlignedSize)];\n\t\t\t\t\t//! 2次元配列アクセス用\n\t\t\t\t\tfloat\tma[0][PaddingedSize];\n\t\t\t\t};\n\n\t\t\t\tfriend class boost::serialization::access;\n\t\t\t\ttemplate <class Archive>\n\t\t\t\tvoid serialize(Archive& ar, const unsigned int /*ver*/) {\n\t\t\t\t\tar & BOOST_SERIALIZATION_NVP(data);\n\t\t\t\t}\n\n\t\t\t\t// -------------------- ctor --------------------\n\t\t\t\tMatT() = default;\n\t\t\t\tMatT(const AMat& m);\n\t\t\t\tMatT(const UMat& m);\n\t\t\t\tMatT(std::initializer_list<float> il);\n\t\t\t\tMatT& mul_self();\n\n\t\t\t\t#define DIAGONAL2(z,n1,n0)\t\tma[n0][n1] = BOOST_PP_IF(BOOST_PP_EQUAL(n0,n1), s, 0);\n\t\t\t\t#define DIAGONAL(z,n,data)\t\tBOOST_PP_REPEAT_##z(DIM_N, DIAGONAL2, n)\n\t\t\t\tMatT(float s, _TagDiagonal) {\n\t\t\t\t\tBOOST_PP_REPEAT(DIM_M, DIAGONAL, NOTHING)\n\t\t\t\t}\n\t\t\t\t#define ALLSET(z,n,data)\tSTORETHIS(n, data);\n\t\t\t\tMatT(float s, _TagAll) {\n\t\t\t\t\treg128 r = reg_load1_ps(&s);\n\t\t\t\t\tBOOST_PP_REPEAT(DIM_M, ALLSET, r)\n\t\t\t\t}\n\t\t\t\tMatT(_TagIdentity): MatT(1.f, TagDiagonal) {}\n\n\t\t\t\t#define SETARRAY(z,n,src)\tSTORETHIS(n, reg_loadu_ps(src)); src += DIM_N;\n\t\t\t\tMatT(const float* src) {\n\t\t\t\t\tBOOST_PP_REPEAT(DIM_M, SETARRAY, src)\n\t\t\t\t}\n\t\t\t\ttemplate <int N>\n\t\t\t\tfloat& ref1D() {\n\t\t\t\t\treturn ma[N/DIM_N][N%DIM_N];\n\t\t\t\t}\n\n\t\t\t\t#define DEF_ARGS(z,n,data)\t(float BOOST_PP_CAT(data,n))\n\t\t\t\t#define SET_ARGS0(z,n,data)\tref1D<n>() = BOOST_PP_CAT(data,n);\n\t\t\t\t//! 全てを指定\n\t\t\t\tMatT(BOOST_PP_SEQ_ENUM(BOOST_PP_REPEAT(DMUL, DEF_ARGS, f))) {\n\t\t\t\t\tBOOST_PP_REPEAT(DMUL, SET_ARGS0, f)\n\t\t\t\t}\n\t\t\t\t#define SET_ARGS1(z,n,data)\tSTORETHIS(n, reg_mul_ps(xmm_const::matI()[n], reg_load1_ps(&BOOST_PP_CAT(data,n))));\n\t\t\t\t#define SET_ARGS2(z,n,dummy) STORETHIS(n, reg_setzero_ps());\n\t\t\t\t//! 対角線上\n\t\t\t\tMatT(BOOST_PP_SEQ_ENUM(BOOST_PP_REPEAT(DMIN, DEF_ARGS, f))) {\n\t\t\t\t\tBOOST_PP_REPEAT(DMIN, SET_ARGS1, f)\n\t\t\t\t\tBOOST_PP_REPEAT_FROM_TO(DMIN, DIM_M, SET_ARGS2, NOTHING)\n\t\t\t\t}\n\t\t\t\t#undef SET_ARGS2\n\t\t\t\ttemplate <bool A>\n\t\t\t\tbool operator == (const MatT<DIM_M, DIM_N, A>& m) const;\n\n\t\t\t\t// -------------------- query values --------------------\n\t\t\t\t#if ALIGN==1 && BOOST_PP_LESS(DIM_N,4)==1\n\t\t\t\t\ttemplate <class T>\n\t\t\t\t\tT& getAuxRef(int m, int n) {\n\t\t\t\t\t\treturn *reinterpret_cast<T*>(ma[m]+DIM_N+n);\n\t\t\t\t\t}\n\t\t\t\t\ttemplate <class T>\n\t\t\t\t\tconst T& getAuxRef(int m, int n) const {\n\t\t\t\t\t\treturn *reinterpret_cast<const T*>(ma[m]+DIM_N+n);\n\t\t\t\t\t}\n\t\t\t\t#endif\n\n\t\t\t\tconst Row& getRow(int n) const {\n\t\t\t\t\tif(n >= height)\n\t\t\t\t\t\treturn *reinterpret_cast<const Row*>(xmm_const::cs_matI()[n]);\n\t\t\t\t\treturn *reinterpret_cast<const Row*>(ma[n]);\n\t\t\t\t}\n\t\t\t\tRow& getRow(int n) {\n\t\t\t\t\treturn *reinterpret_cast<Row*>(ma[n]);\n\t\t\t\t}\n\t\t\t\t//! 行を取得(最大4まで)\n\t\t\t\t/*! 足りない分は対角要素のみ1それ以外は0とみなして取得 */\n\t\t\t\t#if ALIGN==0 || DIM_N==4\n\t\t\t\t\t// 普通のgetRowと同義\n\t\t\t\t\tconst Row& getRowE(int n) const {\n\t\t\t\t\t\treturn getRow(n); }\n\t\t\t\t#else\n\t\t\t\t\tRowE getRowE(int n) const {\n\t\t\t\t\t\tif(n >= height)\n\t\t\t\t\t\t\treturn RowE(xmm_const::matI()[n]);\n\t\t\t\t\t\treturn RowE(reg_or_ps(reg_and_ps(LOADTHIS(n), xmm_const::mask()[n]), xmm_const::matI()[n]));\n\t\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t\ttemplate <bool A>\n\t\t\t\tvoid setRow(int n, const VecT<DIM_N,A>& v) {\n\t\t\t\t\tgetRow(n) = v.loadPS();\n\t\t\t\t}\n\t\t\t\tvoid setColumn(int n, const Column& v) {\n\t\t\t\t\tfor(int i=0 ; i<DIM_M ; i++)\n\t\t\t\t\t\tma[i][n] = v.m[i];\n\t\t\t\t}\n\t\t\t\t#define SET_COLUMN(z,n,data)\t(ma[n][data])\n\t\t\t\tColumn getColumn(int n) const {\n\t\t\t\t\tif(n >= DIM_N)\n\t\t\t\t\t\treturn Column(xmm_const::matI()[n]);\n\t\t\t\t\treturn Column(BOOST_PP_SEQ_ENUM(BOOST_PP_REPEAT(DIM_M, SET_COLUMN, n)));\n\t\t\t\t}\n\t\t\t\t#undef SET_COLUMN\n\n\t\t\t\t#define DEF_GETROW(z,n,data)\tBOOST_PP_CAT(const Row& getRow, n)() const { return *reinterpret_cast<const Row*>(ma[n]); }\n\t\t\t\t//! マクロからのアクセス用: 行毎に個別のメンバ関数を用意\n\t\t\t\t/*! マクロのColumn取得は多分、不要 */\n\t\t\t\tBOOST_PP_REPEAT(DIM_M, DEF_GETROW, NOTHING)\n\t\t\t\t#undef DEF_GETROW\n\n\t\t\t\t// -------------------- operators --------------------\n\t\t\t\t#define FUNC(z,n,func)\t\tSTORETHIS(n, func(LOADTHIS(n), r0));\n\t\t\t\t#define FUNC2(z,n,func)\t\tSTORETHISPS(ret.ma[n], func(LOADTHIS(n), r0));\n\t\t\t\t#define DEF_OP(op, func) MatT& operator BOOST_PP_CAT(op,=) (float s) { \\\n\t\t\t\t\treg128 r0 = reg_load1_ps(&s); \\\n\t\t\t\t\tBOOST_PP_REPEAT(DIM_M, FUNC, func) \\\n\t\t\t\t\treturn *this; } \\\n\t\t\t\t\tMatT operator op (float s) const { \\\n\t\t\t\t\t\tMatT ret; \\\n\t\t\t\t\t\treg128 r0 = reg_load1_ps(&s); \\\n\t\t\t\t\t\tBOOST_PP_REPEAT(DIM_M, FUNC2, func) \\\n\t\t\t\t\t\treturn ret; } \\\n\t\t\t\t\tfriend MatT operator op (float s, const MatT& m);\n\n\t\t\t\tDEF_OP(+, reg_add_ps)\n\t\t\t\tDEF_OP(-, reg_sub_ps)\n\t\t\t\tDEF_OP(*, reg_mul_ps)\n\t\t\t\tDEF_OP(/, _mmDivPs)\n\t\t\t\t#undef DEF_OP\n\t\t\t\t#undef FUNC\n\t\t\t\t#undef FUNC2\n\n\t\t\t\t#define FUNC3(z,n,func)\t\tSTORETHIS(n, func(LOADTHIS(n), LOADTHISPS(m.ma[n])));\n\t\t\t\t#define FUNC4(z,n,func)\t\tSTORETHISPS(ret.ma[n], func(LOADTHIS(n), LOADTHISPS(m.ma[n])));\n\t\t\t\t#define DEF_OPM(op, func) MatT& operator BOOST_PP_CAT(op,=) (const MatT& m) { \\\n\t\t\t\t\tBOOST_PP_REPEAT(DIM_M, FUNC3, func) \\\n\t\t\t\t\treturn *this; } \\\n\t\t\t\tMatT operator op (const MatT& m) const { \\\n\t\t\t\t\tMatT ret; \\\n\t\t\t\t\tBOOST_PP_REPEAT(DIM_M, FUNC4, func) \\\n\t\t\t\t\treturn ret; }\n\n\t\t\t\tDEF_OPM(+, reg_add_ps)\n\t\t\t\tDEF_OPM(-, reg_sub_ps)\n\t\t\t\t#undef FUNC3\n\t\t\t\t#undef FUNC4\n\n\t\t\t\t// -------------------- others --------------------\n\t\t\t\t// 行列拡張Get = Mat::getRowE()\n\t\t\t\tvoid identity();\n\t\t\t\tstatic MatT Scaling(BOOST_PP_SEQ_ENUM(BOOST_PP_REPEAT(DMIN, DEF_ARGS, f)));\n\t\t\t\t#if (DMIN == 2 || DMIN == 3) && DIM_M == 3\n\t\t\t\t\t//! 2次元移動\n\t\t\t\t\tstatic MatT Translation(const UVec2& v);\n\t\t\t\t#endif\n\t\t\t\t#if DIM_M == 4 && DIM_N >= 3\n\t\t\t\t\t//! 3次元移動\n\t\t\t\t\tstatic MatT Translation(const UVec3& v);\n\t\t\t\t\tstatic MatT LookAtLH(const UVec3& pos, const UVec3& at, const UVec3& up);\n\t\t\t\t\tstatic MatT LookDirLH(const UVec3& pos, const UVec3& dir, const UVec3& up);\n\t\t\t\t\tstatic MatT LookAtRH(const UVec3& pos, const UVec3& at, const UVec3& up);\n\t\t\t\t\tstatic MatT LookDirRH(const UVec3& pos, const UVec3& dir, const UVec3& up);\n\t\t\t\t#endif\n\t\t\t\t#if DMIN == 2\n\t\t\t\t\t//! 2D回転\n\t\t\t\t\tstatic MatT Rotation(RadF ang);\n\t\t\t\t#elif DMIN >= 3\n\t\t\t\t\t\t//! X軸周りの回転\n\t\t\t\t\t\tstatic MatT RotationX(RadF ang);\n\t\t\t\t\t\t//! Y軸周りの回転\n\t\t\t\t\t\tstatic MatT RotationY(RadF ang);\n\t\t\t\t\t\t//! Z軸周りの回転\n\t\t\t\t\t\tstatic MatT RotationZ(RadF ang);\n\t\t\t\t\t\t//! 任意軸周りの回転\n\t\t\t\t\t\tstatic MatT RotationAxis(const UVec3& axis, RadF ang);\n\t\t\t\t\t#if DMIN == 4\n\t\t\t\t\t\t//! 透視変換行列\n\t\t\t\t\t\tstatic MatT PerspectiveFovLH(RadF fov, float aspect, float nz, float fz);\n\t\t\t\t\t\tstatic MatT PerspectiveFovRH(RadF fov, float aspect, float nz, float fz);\n\t\t\t\t\t\tstatic MatT _PerspectiveFov(RadF fov, float aspect, float nz, float fz, float coeff);\n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\n\t\t\t\t// 正方行列限定のルーチン\n\t\t\t\t#if DIM_M==DIM_N\n\t\t\t\t\tvoid transpose();\n\t\t\t\t\t//! 固有値計算\n\t\t\t\t\tfloat calcDeterminant() const;\n\t\t\t\t\t// TODO: 固有ベクトル計算\n\t\t\t\t\t//! 逆行列計算\n\t\t\t\t\tbool inversion(MatT& dst) const;\n\t\t\t\t\tbool inversion(MatT& dst, float det) const;\n\t\t\t\t\tbool invert();\n\t\t\t\t\t// -------- Luaへのエクスポート用 --------\n\t\t\t\t\tMatT addF(float s) const;\n\t\t\t\t\tMatT addM(const MatT& m) const;\n\t\t\t\t\tMatT subF(float s) const;\n\t\t\t\t\tMatT subM(const MatT& m) const;\n\t\t\t\t\tVecT<DIM_N,align> mulV(const VecT<DIM_N,align>& v) const;\n\t\t\t\t\tMatT mulF(float s) const;\n\t\t\t\t\tMatT mulM(const MatT& m) const;\n\t\t\t\t\tMatT divF(float s) const;\n\t\t\t\t\tMatT luaInvert() const;\n\t\t\t\t#endif\n\t\t\t\tstd::string toString() const;\n\t\t\t\tMatT<DIM_N,DIM_M,ALIGNB> transposition() const;\n\n\t\t\t\t#if DMIN > 2\n\t\t\t\t\t//! 指定した行と列を省いた物を出力\n\t\t\t\t\tMatT<height-1,width-1,ALIGNB> cutRC(int row, int clm) const;\n\t\t\t\t#endif\n\t\t\t\t// ---------- < 行の基本操作 > ----------\n\t\t\t\t//! 行を入れ替える\n\t\t\t\tvoid rowSwap(int r0, int r1);\n\t\t\t\t//! ある行を定数倍する\n\t\t\t\tvoid rowMul(int r0, float s);\n\t\t\t\t//! ある行を定数倍した物を別の行へ足す\n\t\t\t\tvoid rowMulAdd(int r0, float s, int r1);\n\t\t\t\t// ---------- < 列の基本操作 > ----------\n\t\t\t\t//! 列を入れ替える\n\t\t\t\tvoid clmSwap(int c0, int c1);\n\t\t\t\t//! ある列を定数倍する\n\t\t\t\tvoid clmMul(int c0, float s);\n\t\t\t\t//! ある列を定数倍した物を別の行へ足す\n\t\t\t\tvoid clmMulAdd(int c0, float s, int c1);\n\n\t\t\t\t//! ある行の要素が全てゼロか判定 (誤差=EPSILON込み)\n\t\t\t\tbool isZeroRowEps(int n) const;\n\t\t\t\tbool isZeroRow(int n) const;\n\t\t\t\t//! 零行列か判定\n\t\t\t\tbool isZero() const;\n\t\t\t\t//! 各行を正規化する (最大の係数が1になるように)\n\t\t\t\tvoid rowNormalize();\n\t\t\t\t//! 被約形かどうか判定\n\t\t\t\tbool isEchelon() const;\n\t\t\t\t//! 被約形にする\n\t\t\t\t/*! \\return 0の行数 */\n\t\t\t\tint rowReduce();\n\n\t\t\t\ttemplate <class RDF>\n\t\t\t\tstatic MatT Random(const RDF& rdf, const RangeF& r=random::DefaultRMatRange) {\n\t\t\t\t\treturn random::GenRMat<MatT>(rdf, r);\n\t\t\t\t}\n\n\t\t\t\t// TODO: DecompAffine [DIM >= 3]\n\n\t\t\t\t// 本来行列の積算が出来るのはDIM_N == 相手のDIM_Mの時だけだが\n\t\t\t\t// 足りない分をgetRowE()で補う事で可能にする\n\t\t\t\t// 演算結果も本当は(DIM_M, Other::DIM_N)となるが\n\t\t\t\t// convert<Tgt::DIM_M, Tgt::DIM_N>(result) とする事で合わせる\n\t\t\t\t// max(DIM_N, Other::DIM_M)\n\t\t\t\t// 演算子の出力自体はサイズそのまま\n\t\t\t\t// Mat34 a;\n\t\t\t\t// Mat44 b;\n\t\t\t\t// a * b -> 3x4\n\t\t\t\t// a * [3x4](4x4) -> 3x4\n\t\t\t\t// TODO: 入力が出力と同じサイズで、なおかつrvalueだったら&&で受け取ってそのアドレスを返す\n\n\t\t\t\t//! 行列サイズを変更\n\t\t\t\t/*! 縮小の場合は要素を削り\n\t\t\t\t\t拡大の際に足りない成分は対角=1, 他は0とする */\n\t\t\t\t// デバッグ時速度を考えるとテンプレートで実装できない(？)のでマクロ使用\n\t\t\t\t// SEQ_MATDEFの組み合わせを生成 + (Aligned | UnAligned)\n\t\t\t\t#define CONVFUNC(n0,n1,align)\tBOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_CAT(convert,AFLAG(align)), n0),n1)\n\t\t\t\t#define DEF_CONV(n0,n1,align)\tMatT<n0,n1,BOOLNIZE(align)> CONVFUNC(n0,n1,align)() const; \\\n\t\t\t\t\t\t\t\t\t\t\t\tvoid convert(MatT<n0,n1,BOOLNIZE(align)>& dst) const;\n\t\t\t\tBOOST_PP_REPEAT(LEN_SEQ, DEF_CONV_ITR, DEF_CONV)\n\t\t\t\t#undef DEF_CONV\n\t\t\t\t#undef CONVFUNC\n\t\t\t\t// サイズの合わない行列(DIM_N != n0)の演算関数は定義しない\n\t\t\t\t//! 行列との積算 (3 operands)\n\t\t\t\t#define DEF_MUL0(n0,n1,align) \\\n\t\t\t\t\tBOOST_PP_IF( \\\n\t\t\t\t\t\tBOOST_PP_EQUAL(DIM_N, n0), \\\n\t\t\t\t\t\tDEF_MUL, \\\n\t\t\t\t\t\tNOTHING_ARG \\\n\t\t\t\t\t)(n0,n1,align)\n\t\t\t\t#define DEF_MUL(n0,n1,align)\tMatT<DIM_M, n1, ALIGNB> operator * (const MatT<n0,n1,BOOLNIZE(align)>& m) const;\n\t\t\t\tBOOST_PP_REPEAT(LEN_SEQ, DEF_CONV_ITR, DEF_MUL0)\n\t\t\t\t#undef DEF_MUL\n\t\t\t\t#undef DEF_MUL0\n\t\t\t\t//! 行列との積算 (2 operands)\n\t\t\t\t#define DEF_MULE0(n0,n1,align) \\\n\t\t\t\t\tBOOST_PP_IF( \\\n\t\t\t\t\t\tBOOST_PP_AND( \\\n\t\t\t\t\t\t\tBOOST_PP_EQUAL(DIM_N, n0), \\\n\t\t\t\t\t\t\tBOOST_PP_EQUAL(n1, DIM_N) \\\n\t\t\t\t\t\t), \\\n\t\t\t\t\t\tDEF_MULE, \\\n\t\t\t\t\t\tNOTHING_ARG \\\n\t\t\t\t\t)(n0,n1,align)\n\t\t\t\t#define DEF_MULE(n0,n1,align)\tMatT& operator *= (const MatT<n0,n1,BOOLNIZE(align)>& m);\n\t\t\t\tBOOST_PP_REPEAT(LEN_SEQ, DEF_CONV_ITR, DEF_MULE0)\n\t\t\t\t#undef DEF_MULE\n\t\t\t\t#undef DEF_MULE0\n\t\t\t\t//! 行列の代入\n\t\t\t\tMT& operator = (const MT& m);\n\t\t\t\tMT& operator = (std::initializer_list<float> il);\n\n\t\t\t\t//! 行列との積算 (右から掛ける)\n\t\t\t\t/*! 列ベクトルとして扱う = ベクトルを転置して左から行ベクトルを掛ける */\n\t\t\t\ttemplate <bool A>\n\t\t\t\tVecT<DIM_N,ALIGNB> operator * (const VecT<DIM_N,A>& v) const;\n\n\t\t\t\tfriend std::ostream& operator << (std::ostream& os, const MT& m);\n\t\t\t};\n\t\t\t// 使いやすいように別名を定義 ex. MatT<2,2,true> = AMat22\n\t\t\tusing BOOST_PP_CAT(\n\t\t\t\t\tBOOST_PP_CAT(\n\t\t\t\t\t\tBOOST_PP_CAT(AFLAG(ALIGN),Mat)\n\t\t\t\t\t\t,DIM_M)\n\t\t\t\t\t,DIM_N)\n\t\t\t\t\t= MatT<DIM_M,DIM_N,ALIGNB>;\n\t\t}\n\tBOOST_CLASS_IMPLEMENTATION(spn::MT, object_serializable)\n\t#elif BOOST_PP_FRAME_FLAGS(1) == 1\n\t\tnamespace spn {\n\t\t\t#define FUNC_OP(z,n,func)\tSTORETHISPS(ret.ma[n], func(r, LOADTHISPS(m.ma[n])));\n\t\t\t#define DEF_OPERATOR_FUNC(op, func) MT operator op (float s, const MT& m) { \\\n\t\t\t\tMT ret; \\\n\t\t\t\treg128 r = reg_load1_ps(&s); \\\n\t\t\t\tBOOST_PP_REPEAT(DIM_M, FUNC_OP, func) \\\n\t\t\t\treturn ret; \\\n\t\t\t}\n\t\t\tDEF_OPERATOR_FUNC(+, reg_add_ps)\n\t\t\tDEF_OPERATOR_FUNC(-, reg_sub_ps)\n\t\t\tDEF_OPERATOR_FUNC(*, reg_mul_ps)\n\t\t\tDEF_OPERATOR_FUNC(/, _mmDivPs)\n\t\t\t#undef FUNC_OP\n\t\t\t#undef DEF_OPERATOR_FUNC\n\n\t\t\tMT::MatT(const AMat& m) {\n\t\t\t\tfor(int i=0 ; i<DIM_M ; i++)\n\t\t\t\t\tSTORETHIS(i, LOADPS(m.ma[i]));\n\t\t\t}\n\t\t\tMT::MatT(const UMat& m) {\n\t\t\t\tfor(int i=0 ; i<DIM_M ; i++)\n\t\t\t\t\tSTORETHIS(i, LOADPSU(m.ma[i]));\n\t\t\t}\n\t\t\tMT::MatT(std::initializer_list<float> il) {\n\t\t\t\t// 足りない要素分はすべてゼロにする\n\t\t\t\talignas(16) float tmp[DIM_M*DIM_N] = {};\n\t\t\t\tauto* pTmp = tmp;\n\t\t\t\tfor(auto itr=il.begin() ; itr!=il.end() ; ++itr)\n\t\t\t\t\t*pTmp++ = *itr;\n\t\t\t\tfor(int i=0 ; i<DIM_M ; i++)\n\t\t\t\t\tSTORETHIS(i, LOADPSU(tmp+i*DIM_N));\n\t\t\t}\n\t\t\t// 行列拡張Get = Mat::getRowE()\n\t\t\tvoid MT::identity() {\n\t\t\t\t*this = MatT(1.0f, TagDiagonal);\n\t\t\t}\n\t\t\tstd::string MT::toString() const {\n\t\t\t\treturn ToString(*this);\n\t\t\t}\n\t\t\tstd::ostream& operator << (std::ostream& os, const MT& m) {\n\t\t\t\tos << BOOST_PP_IF(ALIGN, 'A', ' ') << \"Mat\" << DIM_M << DIM_N << '[';\n\t\t\t\tfor(int i=0 ; i<DIM_M ; i++) {\n\t\t\t\t\tfor(int j=0 ; j<DIM_N-1 ; j++)\n\t\t\t\t\t\tos << m.ma[i][j] << ',';\n\t\t\t\t\tos << m.ma[i][DIM_N-1] << ' ';\n\t\t\t\t}\n\t\t\t\treturn os << ']';\n\t\t\t}\n\t\t\ttemplate <bool A>\n\t\t\tbool MT::operator == (const MatT<DIM_M, DIM_N, A>& m) const {\n\t\t\t\tfor(int i=0 ; i<DIM_M ; i++) {\n\t\t\t\t\tif(getRow(i) != Row(m.getRow(i)))\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ttemplate bool MT::operator == (const MatT<DIM_M, DIM_N, false>&) const;\n\t\t\ttemplate bool MT::operator == (const MatT<DIM_M, DIM_N, true>&) const;\n\n\t\t\t#define DEF_COPY(z,n,dummy)\tSTORETHISPS(ma[n], LOADTHISPS(m.ma[n]));\n\t\t\tMT& MT::operator = (const MT& m) {\n\t\t\t\tBOOST_PP_REPEAT(DIM_M, DEF_COPY, NOTHING)\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t#undef DEF_COPY\n\t\t\tMT& MT::operator = (std::initializer_list<float> il) {\n\t\t\t\treturn *this = MT(il);\n\t\t\t}\n\t\t\t#define SET_ARGS2(z,n,data) (BOOST_PP_CAT(data, n))\n\t\t\tMT MT::Scaling(BOOST_PP_SEQ_ENUM(BOOST_PP_REPEAT(DMIN, DEF_ARGS, f))) {\n\t\t\t\treturn MatT(BOOST_PP_SEQ_ENUM(BOOST_PP_REPEAT(DMIN, SET_ARGS2, f)));\n\t\t\t}\n\t\t\t#undef SET_ARGS2\n\t\t\t#if (DMIN == 2 || DMIN == 3) && DIM_M == 3\n\t\t\t\tMT MT::Translation(const VecT<2,false>& v) {\n\t\t\t\t\tMatT mt(TagIdentity);\n\t\t\t\t\tmt.ma[2][0] = v.x;\n\t\t\t\t\tmt.ma[2][1] = v.y;\n\t\t\t\t\treturn mt;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\t#if DIM_M == 4 && DIM_N >= 3\n\t\t\t\tMT MT::Translation(const UVec3& v) {\n\t\t\t\t\tMatT mt(TagIdentity);\n\t\t\t\t\tmt.ma[3][0] = v.x;\n\t\t\t\t\tmt.ma[3][1] = v.y;\n\t\t\t\t\tmt.ma[3][2] = v.z;\n\t\t\t\t\treturn mt;\n\t\t\t\t}\n\t\t\t\tMT MT::LookAtLH(const UVec3& pos, const UVec3& at, const UVec3& up) {\n\t\t\t\t\treturn LookDirLH(pos, (at-pos).normalization(), up);\n\t\t\t\t}\n\t\t\t\tMT MT::LookDirLH(const UVec3& pos, const UVec3& dir, const UVec3& up) {\n\t\t\t\t\tAVec3 xA(up % dir);\n\t\t\t\t\txA.normalize();\n\n\t\t\t\t\tMatT ret;\n\t\t\t\t\tSTORETHISPS(ret.ma[0], reg_setr_ps(xA.x, up.x, dir.x, 0));\n\t\t\t\t\tSTORETHISPS(ret.ma[1], reg_setr_ps(xA.y, up.y, dir.y, 0));\n\t\t\t\t\tSTORETHISPS(ret.ma[2], reg_setr_ps(xA.z, up.z, dir.z, 0));\n\t\t\t\t\tSTORETHISPS(ret.ma[3], reg_setr_ps(-pos.dot(xA), -pos.dot(up), -pos.dot(dir), 1));\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t\tMT MT::LookAtRH(const UVec3& pos, const UVec3& at, const UVec3& up) {\n\t\t\t\t\treturn LookDirLH(pos, (pos-at).normalization(), up);\n\t\t\t\t}\n\t\t\t\tMT MT::LookDirRH(const UVec3& pos, const UVec3& dir, const UVec3& up) {\n\t\t\t\t\treturn LookDirLH(pos, -dir, up);\n\t\t\t\t}\n\t\t\t#endif\n\t\t\t#if DMIN == 2\n\t\t\t\tMT MT::Rotation(RadF ang) {\n\t\t\t\t\tconst float S = std::sin(ang.get()),\n\t\t\t\t\t\t\t\tC = std::cos(ang.get());\n\t\t\t\t\tMatT mt(TagIdentity);\n\t\t\t\t\tmt.ma[0][0] = C;\n\t\t\t\t\tmt.ma[0][1] = S;\n\t\t\t\t\tmt.ma[1][0] = -S;\n\t\t\t\t\tmt.ma[1][1] = C;\n\t\t\t\t\treturn mt;\n\t\t\t\t}\n\t\t\t#elif DMIN >= 3\n\t\t\t\t\tMT MT::RotationX(RadF ang) {\n\t\t\t\t\t\tconst float C = std::cos(ang.get()),\n\t\t\t\t\t\t\t\t\tS = std::sin(ang.get());\n\t\t\t\t\t\tMatT mt;\n\t\t\t\t\t\tSTORETHISPS(mt.ma[0], reg_setr_ps(1,\t0,\t0,\t0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[1], reg_setr_ps(0,\tC,\tS,\t0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[2], reg_setr_ps(0,\t-S,\tC,\t0));\n\t\t\t\t\t\t#if DIM_M == 4\n\t\t\t\t\t\t\tSTORETHISPS(mt.ma[3], reg_setr_ps(0,0,0,1));\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\treturn mt;\n\t\t\t\t\t}\n\t\t\t\t\tMT MT::RotationY(RadF ang) {\n\t\t\t\t\t\tconst float C = std::cos(ang.get()),\n\t\t\t\t\t\t\t\t\tS = std::sin(ang.get());\n\t\t\t\t\t\tMatT mt;\n\t\t\t\t\t\tSTORETHISPS(mt.ma[0], reg_setr_ps(C,\t0,\t-S,\t0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[1], reg_setr_ps(0,\t1,\t0,\t0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[2], reg_setr_ps(S,\t0,\tC,\t0));\n\t\t\t\t\t\t#if DIM_M == 4\n\t\t\t\t\t\t\tSTORETHISPS(mt.ma[3], reg_setr_ps(0,0,0,1));\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\treturn mt;\n\t\t\t\t\t}\n\t\t\t\t\tMT MT::RotationZ(RadF ang) {\n\t\t\t\t\t\tconst float C = std::cos(ang.get()),\n\t\t\t\t\t\t\t\t\tS = std::sin(ang.get());\n\t\t\t\t\t\tMatT mt;\n\t\t\t\t\t\tSTORETHISPS(mt.ma[0], reg_setr_ps(C,\tS,\t0,\t0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[1], reg_setr_ps(-S,\tC,\t0,\t0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[2], reg_setr_ps(0,\t0,\t1,\t0));\n\t\t\t\t\t\t#if DIM_M == 4\n\t\t\t\t\t\t\tSTORETHISPS(mt.ma[3], reg_setr_ps(0,0,0,1));\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\treturn mt;\n\t\t\t\t\t}\n\t\t\t\t\tMT MT::RotationAxis(const UVec3& axis, RadF ang) {\n\t\t\t\t\t\tconst float C = std::cos(ang.get()),\n\t\t\t\t\t\t\t\t\tS = std::sin(ang.get()),\n\t\t\t\t\t\t\t\t\tRC = 1-C;\n\t\t\t\t\t\tMatT mt;\n\t\t\t\t\t\tconst float M00 = C + Square(axis.x) * RC,\n\t\t\t\t\t\t\t\t\tM01 = axis.x * axis.y * RC + axis.z*S,\n\t\t\t\t\t\t\t\t\tM02 = axis.x * axis.z * RC - axis.y*S,\n\t\t\t\t\t\t\t\t\tM10 = axis.x * axis.y * RC - axis.z*S,\n\t\t\t\t\t\t\t\t\tM11 = C + Square(axis.y) * RC,\n\t\t\t\t\t\t\t\t\tM12 = axis.y * axis.z * RC + axis.x*S,\n\t\t\t\t\t\t\t\t\tM20 = axis.x * axis.z * RC + axis.y*S,\n\t\t\t\t\t\t\t\t\tM21 = axis.y * axis.z * RC - axis.x*S,\n\t\t\t\t\t\t\t\t\tM22 = C + Square(axis.z) * RC;\n\t\t\t\t\t\tSTORETHISPS(mt.ma[0], reg_setr_ps(M00, M01, M02, 0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[1], reg_setr_ps(M10, M11, M12, 0));\n\t\t\t\t\t\tSTORETHISPS(mt.ma[2], reg_setr_ps(M20, M21, M22, 0));\n\t\t\t\t\t\t#if DIM_M == 4\n\t\t\t\t\t\t\tSTORETHISPS(mt.ma[3], reg_setr_ps(0,0,0,1));\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\treturn mt;\n\t\t\t\t\t}\n\t\t\t\t#if DMIN == 4\n\t\t\t\t\tMT MT::_PerspectiveFov(RadF fov, float aspect, float nz, float fz, float coeff) {\n\t\t\t\t\t\tfloat h = 1.0f / std::tan(fov.get()/2),\n\t\t\t\t\t\t\t\tw = h / aspect,\n\t\t\t\t\t\t\t\tf0 = fz/(fz-nz),\n\t\t\t\t\t\t\t\tf1 = -nz*fz/(fz-nz);\n\t\t\t\t\t\tMatT ret;\n\t\t\t\t\t\tSTORETHISPS(ret.ma[0], reg_setr_ps(w,0,0,0));\n\t\t\t\t\t\tSTORETHISPS(ret.ma[1], reg_setr_ps(0,h,0,0));\n\t\t\t\t\t\tSTORETHISPS(ret.ma[2], reg_setr_ps(0,0,f0,coeff));\n\t\t\t\t\t\tSTORETHISPS(ret.ma[3], reg_setr_ps(0,0,f1*coeff,0));\n\t\t\t\t\t\treturn ret;\n\t\t\t\t\t}\n\t\t\t\t\tMT MT::PerspectiveFovLH(RadF fov, float aspect, float nz, float fz) {\n\t\t\t\t\t\treturn _PerspectiveFov(fov, aspect, nz, fz, 1);\n\t\t\t\t\t}\n\t\t\t\t\tMT MT::PerspectiveFovRH(RadF fov, float aspect, float nz, float fz) {\n\t\t\t\t\t\treturn _PerspectiveFov(fov, aspect, nz, fz, -1);\n\t\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t#endif\n\t\t\tbool MT::isEchelon() const {\n\t\t\t\tuint32_t clmFlagT = 0,\n\t\t\t\t\t\tclmFlagF = 0;\n\t\t\t\tint topClm = -1;\n\t\t\t\tbool bZero = false;\n\t\t\t\tfor(int i=0 ; i<DIM_M ; i++) {\n\t\t\t\t\tint lcltop = -1;\n\t\t\t\t\tfor(int j=0 ; j<DIM_N-1 ; j++) {\n\t\t\t\t\t\tfloat val = ma[i][j];\n\t\t\t\t\t\tif(std::fabs(val) >= FLOAT_EPSILON) {\n\t\t\t\t\t\t\tif(lcltop >= 0)\n\t\t\t\t\t\t\t\tclmFlagF |= 1<<j;\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tlcltop = j;\n\t\t\t\t\t\t\t\t// 0でない成分を持つ全ての行について，先導成分が1である\n\t\t\t\t\t\t\t\t// 行の下に行くにつれて先導成分が右へずれていく\n\t\t\t\t\t\t\t\tif(topClm >= j || !(val-1.f >= FLOAT_EPSILON))\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\tclmFlagT |= 1<<j;\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\tif(lcltop < 0)\n\t\t\t\t\t\tbZero = true;\n\t\t\t\t\telse {\n\t\t\t\t\t\t// 0でない成分を持つすべての行は，0だけの行よりも先に来る\n\t\t\t\t\t\tif(bZero)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\ttopClm = lcltop;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// ある行の先導成分が第j列ならば，他の行の第j列は0である\n\t\t\t\treturn !(clmFlagT & clmFlagF);\n\t\t\t}\n\t\t\tvoid MT::rowSwap(int r0, int r1) {\n\t\t\t\treg128 xm0 = LOADTHIS(r0),\n\t\t\t\t\t\txm1 = LOADTHIS(r1);\n\t\t\t\tSTORETHIS(r1, xm0);\n\t\t\t\tSTORETHIS(r0, xm1);\n\t\t\t}\n\t\t\tvoid MT::rowMul(int r0, float s) {\n\t\t\t\tSTORETHIS(r0, reg_mul_ps(LOADTHIS(r0), reg_load1_ps(&s)));\n\t\t\t}\n\t\t\tvoid MT::rowMulAdd(int r0, float s, int r1) {\n\t\t\t\treg128 xm0 = reg_mul_ps(LOADTHIS(r0), reg_load1_ps(&s)),\n\t\t\t\t\t\txm1 = LOADTHIS(r1);\n\t\t\t\tSTORETHIS(r1, reg_add_ps(xm0, xm1));\n\t\t\t}\n\t\t\tvoid MT::clmSwap(int c0, int c1) {\n\t\t\t\tsetColumn(c1, getColumn(c0));\n\t\t\t}\n\t\t\tvoid MT::clmMul(int c0, float s) {\n\t\t\t\tauto clm = getColumn(c0);\n\t\t\t\tclm *= s;\n\t\t\t\tsetColumn(c0, clm);\n\t\t\t}\n\t\t\tvoid MT::clmMulAdd(int c0, float s, int c1) {\n\t\t\t\tColumn clm0 = getColumn(c0),\n\t\t\t\t\tclm1 = getColumn(c1);\n\t\t\t\tclm0 *= s;\n\t\t\t\tclm0 += clm1;\n\t\t\t\tsetColumn(c1, clm0);\n\t\t\t}\n\t\t\tbool MT::isZeroRow(int n) const {\n\t\t\t\treturn _mmIsZero(LOADTHISZ(n));\n\t\t\t}\n\t\t\tbool MT::isZeroRowEps(int n) const {\n\t\t\t\treturn _mmIsZeroEps(LOADTHISZ(n));\n\t\t\t}\n\t\t\tbool MT::isZero() const {\n\t\t\t\treg128 accum = reg_setzero_ps();\n\t\t\t\t#define ACCUM_ABS(dummy,n,dummy2)\treg_add_ps(accum, _mmAbsPs(LOADTHIS(n)));\n\t\t\t\tBOOST_PP_REPEAT(DIM_M, ACCUM_ABS, NOTHING)\n\t\t\t\t#undef ACCUM_ABS\n\t\t\t\taccum = reg_and_ps(accum, xmm_const::mask()[DIM_N]);\n\t\t\t\treturn reg_movemask_ps(accum) == 0;\n\t\t\t}\n\t\t\tvoid MT::rowNormalize() {\n\t\t\t\treg128 xm0 = LOADTHIS(0);\n\t\t\t\tfor(int i=1 ; i<height ; i++)\n\t\t\t\t\txm0 = reg_max_ps(xm0, LOADTHIS(i));\n\t\t\t\tRCP22BIT(xm0)\n\t\t\t\tfor(int i=0 ; i<height ; i++)\n\t\t\t\t\tSTORETHIS(i, reg_mul_ps(LOADTHIS(i), xm0));\n\t\t\t}\n\t\t\tint MT::rowReduce() {\n\t\t\t\t// rowNormalize();\n\t\t\t\tint rbase = 0,\n\t\t\t\t\tcbase = 0;\n\t\t\t\tfor(;;) {\n\t\t\t\t\t// 行の先端が0でなく、かつ絶対値が最大の行を探す\n\t\t\t\t\tint idx = -1;\n\t\t\t\t\tfloat absmax = 0;\n\t\t\t\t\tfor(int i=rbase ; i<DIM_M ; i++) {\n\t\t\t\t\t\tfloat v = std::fabs(ma[i][cbase]);\n\t\t\t\t\t\tif(absmax < v) {\n\t\t\t\t\t\t\tif(std::fabs(v) >= FLOAT_EPSILON) {\n\t\t\t\t\t\t\t\tabsmax = v;\n\t\t\t\t\t\t\t\tidx = i;\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\tif(idx < 0) {\n\t\t\t\t\t\t// 無かったので次の列へ\n\t\t\t\t\t\t++cbase;\n\t\t\t\t\t\tif(cbase == DIM_N) {\n\t\t\t\t\t\t\t// 終了\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// 基準行でなければ入れ替え\n\t\t\t\t\tif(idx > rbase)\n\t\t\t\t\t\trowSwap(idx, rbase);\n\t\t\t\t\t// 基点で割って1にする\n\t\t\t\t\trowMul(rbase, spn::Rcp22Bit(ma[rbase][cbase]));\n\t\t\t\t\tma[rbase][cbase] = 1;\t// 精度の問題で丁度1にならない事があるので強制的に1をセット\n\t\t\t\t\t// 他の行の同じ列を0にする\n\t\t\t\t\tfor(int i=0 ; i<DIM_M ; i++) {\n\t\t\t\t\t\tif(i==rbase)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tfloat scale = -ma[i][cbase];\n\t\t\t\t\t\trowMulAdd(rbase, scale, i);\n\t\t\t\t\t\tma[i][cbase] = 0;\t// 上と同じく精度の問題により0をセット\n\t\t\t\t\t}\n\t\t\t\t\t// 次の行,列へ移る\n\t\t\t\t\t++rbase;\n\t\t\t\t\t++cbase;\n\t\t\t\t\tif(rbase == DIM_M || cbase == DIM_N) {\n\t\t\t\t\t\t// 最後の行まで処理し終わるか，全て0の行しか無ければ終了\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn DIM_M - rbase;\n\t\t\t}\n\t\t\t#if DIM_M==DIM_N\n\t\t\t\tvoid MT::transpose() {\n\t\t\t\t\t*this = transposition();\n\t\t\t\t}\n\t\t\t\tfloat MT::calcDeterminant() const {\n\t\t\t\t\t#if DMIN == 2\n\t\t\t\t\t\t// 公式で計算\n\t\t\t\t\t\treturn ma[0][0]*ma[1][1] - ma[0][1]*ma[1][0];\n\t\t\t\t\t#else\n\t\t\t\t\t\tfloat res = 0,\n\t\t\t\t\t\t\t\ts = 1;\n\t\t\t\t\t\t// 部分行列を使って計算\n\t\t\t\t\t\tfor(int i=0 ; i<DIM_M ; i++) {\n\t\t\t\t\t\t\tauto mt = cutRC(0,i);\n\t\t\t\t\t\t\tres += ma[0][i] * mt.calcDeterminant() * s;\n\t\t\t\t\t\t\ts *= -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t#endif\n\t\t\t\t}\n\t\t\t\tbool MT::inversion(MatT& dst) const {\n\t\t\t\t\tassert(this != &dst);\n\t\t\t\t\treturn inversion(dst, calcDeterminant());\n\t\t\t\t}\n\t\t\t\tbool MT::inversion(MatT& dst, float det) const {\n\t\t\t\t\tif(std::fabs(det) < FLOAT_EPSILON)\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\tdet = spn::Rcp22Bit(det);\n\t\t\t\t\t#if DIM_M==2\n\t\t\t\t\t\tdst.ma[0][0] = ma[1][1] * det;\n\t\t\t\t\t\tdst.ma[0][1] = -ma[1][0] * det;\n\t\t\t\t\t\tdst.ma[1][0] = -ma[0][1] * det;\n\t\t\t\t\t\tdst.ma[1][1] = ma[0][0] * det;\n\t\t\t\t\t#else\n\t\t\t\t\t\tconst float c_val[2] = {1,-1};\n\t\t\t\t\t\tfor(int i=0 ; i<DIM_M ; i++) {\n\t\t\t\t\t\t\tfor(int j=0 ; j<DIM_N ; j++) {\n\t\t\t\t\t\t\t\tauto in_mat = cutRC(i,j);\n\t\t\t\t\t\t\t\tfloat in_det = in_mat.calcDeterminant();\n\t\t\t\t\t\t\t\tdst.ma[j][i] = c_val[(i+j)&1] * in_det * det;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t#endif\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbool MT::invert() {\n\t\t\t\t\tMT tmp(*this);\n\t\t\t\t\tbool b = inversion(tmp);\n\t\t\t\t\tif(b)\n\t\t\t\t\t\t*this = tmp;\n\t\t\t\t\treturn b;\n\t\t\t\t}\n\t\t\t\t// -------- Luaへのエクスポート用 --------\n\t\t\t\tMT MT::addF(float s) const {\n\t\t\t\t\treturn *this + s;\n\t\t\t\t}\n\t\t\t\tMT MT::addM(const MT& m) const {\n\t\t\t\t\treturn *this * m;\n\t\t\t\t}\n\t\t\t\tMT MT::subF(float s) const {\n\t\t\t\t\treturn *this - s;\n\t\t\t\t}\n\t\t\t\tMT MT::subM(const MT& m) const {\n\t\t\t\t\treturn *this - m;\n\t\t\t\t}\n\t\t\t\tMT MT::mulF(float s) const {\n\t\t\t\t\treturn *this * s;\n\t\t\t\t}\n\t\t\t\tMT MT::mulM(const MT& m) const {\n\t\t\t\t\treturn *this * m;\n\t\t\t\t}\n\t\t\t\tMT MT::divF(float s) const {\n\t\t\t\t\treturn *this / s;\n\t\t\t\t}\n\t\t\t\tMT MT::luaInvert() const {\n\t\t\t\t\tMT ret;\n\t\t\t\t\tinversion(ret);\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\t#if DMIN > 2\n\t\t\t\t//! 指定した行と列を省いた物を出力\n\t\t\t\tMatT<DIM_M-1,DIM_N-1,ALIGNB> MT::cutRC(int row, int clm) const {\n\t\t\t\t\t// TODO: 余力があったらマクロ展開\n\t\t\t\t\tMatT<height-1,width-1,ALIGNB> ret;\n\t\t\t\t\t// 左上\n\t\t\t\t\tfor(int i=0 ; i<row ; i++) {\n\t\t\t\t\t\tfor(int j=0 ; j<clm ; j++)\n\t\t\t\t\t\t\tret.ma[i][j] = ma[i][j];\n\t\t\t\t\t}\n\t\t\t\t\t// 右上\n\t\t\t\t\tfor(int i=0 ; i<row ; i++) {\n\t\t\t\t\t\tfor(int j=clm+1 ; j<width ; j++)\n\t\t\t\t\t\t\tret.ma[i][j-1] = ma[i][j];\n\t\t\t\t\t}\n\t\t\t\t\t// 左下\n\t\t\t\t\tfor(int i=row+1 ; i<height ; i++) {\n\t\t\t\t\t\tfor(int j=0 ; j<clm ; j++)\n\t\t\t\t\t\t\tret.ma[i-1][j] = ma[i][j];\n\t\t\t\t\t}\n\t\t\t\t\t// 右下\n\t\t\t\t\tfor(int i=row+1 ; i<height ; i++) {\n\t\t\t\t\t\tfor(int j=clm+1 ; j<width ; j++)\n\t\t\t\t\t\t\tret.ma[i-1][j-1] = ma[i][j];\n\t\t\t\t\t}\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\tMatT<DIM_N,DIM_M,ALIGNB> MT::transposition() const {\n\t\t\t\tMatT<DIM_N,DIM_M,ALIGNB> ret;\n\t\t\t\t#if DMIN == 2\n\t\t\t\t\t// DMIN == 2なら直接入れ替えたほうが速い\n\t\t\t\t\tret.ma[0][0] = ma[0][0];\n\t\t\t\t\tret.ma[0][1] = ma[1][0];\n\t\t\t\t\tret.ma[1][0] = ma[0][1];\n\t\t\t\t\tret.ma[1][1] = ma[1][1];\n\t\t\t\t#else\n\t\t\t\t\t// DMIN >= 3なら4x4行列として処理\n\t\t\t\t\t// M*4行列 = レジスタM本\n\t\t\t\t\treg128\txm[4], xmt[4];\n\t\t\t\t\t#define LOADROWE(n) BOOST_PP_IF(BOOST_PP_GREATER_EQUAL(n, DIM_M), xmm_const::matI()[n], LOADTHIS(n))\n\t\t\t\t\t#define BOOST_PP_LOCAL_MACRO(n)\txm[n] = LOADROWE(n);\n\t\t\t\t\t#define BOOST_PP_LOCAL_LIMITS (0,BOOST_PP_SUB(DMAX, 1))\n\t\t\t\t\t#include BOOST_PP_LOCAL_ITERATE()\n\n\t\t\t\t\txmt[0] = reg_unpacklo_ps(xm[0], xm[2]);\n\t\t\t\t\txmt[1] = reg_unpacklo_ps(xm[1], xm[3]);\n\t\t\t\t\txmt[2] = reg_unpackhi_ps(xm[0], xm[2]);\n\t\t\t\t\txmt[3] = reg_unpackhi_ps(xm[1], xm[3]);\n\n\t\t\t\t\txm[0] = reg_unpacklo_ps(xmt[0], xmt[1]);\n\t\t\t\t\txm[1] = reg_unpackhi_ps(xmt[0], xmt[1]);\n\t\t\t\t\txm[2] = reg_unpacklo_ps(xmt[2], xmt[3]);\n\t\t\t\t\txm[3] = reg_unpackhi_ps(xmt[2], xmt[3]);\n\t\t\t\t\t#define BOOST_PP_LOCAL_MACRO(n) STORETHISPS(ret.ma[n], xm[n]);\n\t\t\t\t\t#define BOOST_PP_LOCAL_LIMITS (0,BOOST_PP_SUB(DIM_N,1))\n\t\t\t\t\t#include BOOST_PP_LOCAL_ITERATE()\n\t\t\t\t\t#undef LOADROWE\n\t\t\t\t#endif\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\t/*\tPseudo-code:\n\t\t\t\tMatT<n0,n1,align> MT::convert##align##n0##n1() const {\n\t\t\t\t\tMatT<n0,n1,align> ret;\n\t\t\t\t\t// <Repeat by ITR_COPY>\n\t\t\t\t\tfor(int i=0 ; i<n0 ; i++) {\n\t\t\t\t\t\tif(i < DIM_M)\n\t\t\t\t\t\t\tSTOREPS_(A)##n1(ret.ma[i], LOADTHIS(i));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tSTOREPS_(A)##n1(ret.ma[i], xmm_const::matI()[i]);\n\t\t\t\t\t}\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t\tvoid MT::convert(MatT<n0,n1,align>& dst) const {\n\t\t\t\t\t dst = convert##align##n0##n1();\n\t\t\t\t}\n\t\t\t*/\n\t\t\t#define ITR_COPY_I(n,dim,align)\t\\\n\t\t\t\tBOOST_PP_CAT( \\\n\t\t\t\t\tBOOST_PP_CAT( \\\n\t\t\t\t\t\tSTOREPS_, \\\n\t\t\t\t\t\tAFLAG(align) \\\n\t\t\t\t\t), \\\n\t\t\t\t\tdim \\\n\t\t\t\t) \\\n\t\t\t\t(ret.ma[n], \\\n\t\t\t\t\tBOOST_PP_IF( \\\n\t\t\t\t\t\tBOOST_PP_LESS(n,DIM_M), \\\n\t\t\t\t\t\tLOADTHISI(n), \\\n\t\t\t\t\t\txmm_const::matI()[n] \\\n\t\t\t\t\t) \\\n\t\t\t\t);\n\t\t\t#define ITR_COPY(z,n,data)\t\tITR_COPY_I(n, BOOST_PP_SEQ_ELEM(0,data), BOOST_PP_SEQ_ELEM(1,data))\n\t\t\t#define DEF_CONV(n0,n1,align)\t\\\n\t\t\t\tMatT<n0,n1,BOOLNIZE(align)> MT::BOOST_PP_CAT( \\\n\t\t\t\t\tBOOST_PP_CAT( \\\n\t\t\t\t\t\tBOOST_PP_CAT(convert, AFLAG(align)), \\\n\t\t\t\t\t\tn0 \\\n\t\t\t\t\t), \\\n\t\t\t\t\tn1)() const { \\\n\t\t\t\tMatT<n0,n1,BOOLNIZE(align)> ret; \\\n\t\t\t\tBOOST_PP_REPEAT(n0, ITR_COPY, (n1)(align)) \\\n\t\t\t\treturn ret; } \\\n\t\t\t\tvoid MT::convert(MatT<n0,n1,BOOLNIZE(align)>& dst) const { \\\n\t\t\t\t\tdst = BOOST_PP_CAT( \\\n\t\t\t\t\t\t\tBOOST_PP_CAT( \\\n\t\t\t\t\t\t\t\tBOOST_PP_CAT(convert, AFLAG(align)), \\\n\t\t\t\t\t\t\t\tn0 \\\n\t\t\t\t\t\t\t), \\\n\t\t\t\t\t\t\tn1 \\\n\t\t\t\t\t\t)(); }\n\t\t\tBOOST_PP_REPEAT(LEN_SEQ, DEF_CONV_ITR, DEF_CONV)\n\t\t\t#undef ITR_COPY_I\n\t\t\t#undef ITR_COPY\n\t\t}\n\t\t#elif BOOST_PP_FRAME_FLAGS(1) == 2\n\t\tnamespace spn {\n\t\t\t#define DEF_MULSELF *this = *this * *this;\n\t\t\tMT& MT::mul_self() {\n\t\t\t\tBOOST_PP_IF(\n\t\t\t\t\tBOOST_PP_EQUAL(DIM_M, DIM_N),\n\t\t\t\t\tDEF_MULSELF,\n\t\t\t\t\tNOTHING\n\t\t\t\t)\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t#undef DEF_MULSELF\n\t\t\t// 行列の積算\n\t\t\t/*\tPseudo-code:\n\t\t\t\tMatT<DIM_M, n1, ALIGNB> MT::operator * (const MatT<n0,n1,align>& m) const {\n\t\t\t\t\tALIGN16 MatT<DIM_M, n1, ALIGNB> ret;\n\t\t\t\t\t// <Repeat by MUL_OUTER>\n\t\t\t\t\tfor(int i=0 ; i<n0 ; i++) {\n\t\t\t\t\t\treg128 tm = LOADTHISI(i);\n\t\t\t\t\t\treg128 accum = reg_mul_ps(reg_shuffle_ps(tm, tm, _REG_SHUFFLE(0,0,0,0)), LOADPS_I(A)n1(m.ma[0], 0));\n\t\t\t\t\t\t// <Repeat by MUL_INNER>\n\t\t\t\t\t\tfor(int j=1 ; j<DIM_N ; j++)\n\t\t\t\t\t\t\taccum = reg_add_ps(accum, reg_mul_ps(reg_shuffle_ps(tm, tm, _REG_SHUFFLE(j,j,j,j)), LOADPS_I(A)n1(m.ma[j], j)));\n\t\t\t\t\t\tSTOREPS_(A)n1(ret.ma[i], accum);\n\t\t\t\t\t}\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t*/\n\t\t\t// 対応する行列(サイズ)以外は何もコードを出力しない\n\t\t\t#define DEF_MUL0(n0,n1,align) \\\n\t\t\t\tBOOST_PP_IF( \\\n\t\t\t\t\tBOOST_PP_EQUAL(DIM_N, n0), \\\n\t\t\t\t\tDEF_MUL, \\\n\t\t\t\t\tNOTHING_ARG \\\n\t\t\t\t)(n0,n1,align)\n\t\t\t#define DEF_MUL(n0,n1,align)\tMatT<DIM_M, n1, ALIGNB> MT::operator * (const MatT<n0,n1,BOOLNIZE(align)>& m) const {\\\n\t\t\t\tALIGN16 MatT<DIM_M, n1, ALIGNB> ret; \\\n\t\t\t\tBOOST_PP_REPEAT( \\\n\t\t\t\t\tDIM_M, \\\n\t\t\t\t\tMUL_OUTER, \\\n\t\t\t\t\t(BOOST_PP_CAT( \\\n\t\t\t\t\t\tBOOST_PP_IF( \\\n\t\t\t\t\t\t\talign, \\\n\t\t\t\t\t\t\tA, \\\n\t\t\t\t\t\t\tNOTHING \\\n\t\t\t\t\t\t), \\\n\t\t\t\t\t\tn1 \\\n\t\t\t\t\t))(n0) \\\n\t\t\t\t) \\\n\t\t\t\treturn ret; \\\n\t\t\t}\n\t\t\t/*\tInner(z,n, AUn1)\n\t\t\t\taccum = reg_add_ps(accum, reg_mul_ps(reg_shuffle_ps(tm, tm, _REG_SHUFFLE(n,n,n,n)), LOADPS_I(A)n1(m.ma[n], n)));\n\t\t\t*/\n\t\t\t#define MUL_INNER(z,n,AUn1)\taccum = reg_add_ps( \\\n\t\t\t\t\t\t\t\t\t\t\t\t\taccum, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\treg_mul_ps( \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treg_shuffle_ps(tm, tm, _REG_SHUFFLE(n,n,n,n)), \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tLOADPS_I##AUn1(m.ma[n], 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);\n\t\t\t/*\tOuter(z,i, AUn1_n0)\n\t\t\t\treg128 tm = LOADTHISI(i);\n\t\t\t\treg128 accum = reg_mul_ps(reg_shuffle_ps(tm, tm, _REG_SHUFFLE(0,0,0,0)), LOADPS_I(A)n1(m.ma[0], 0));\n\t\t\t\tfor(int j=1 ; j<AUn1_n0[1] ; j++)\n\t\t\t\t\tInner(j, AUn1_n0[0]);\n\t\t\t\tSTOREPS_(A)AUn1_n0[0](ret.ma[i], accum);\n\t\t\t*/\n\t\t\t#define MUL_OUTER(z,n,AUn1_n0) { \\\n\t\t\t\treg128 tm = LOADTHISI(n); \\\n\t\t\t\treg128 accum = reg_mul_ps( \\\n\t\t\t\t\t\t\t\treg_shuffle_ps(tm, tm, _REG_SHUFFLE(0,0,0,0)), \\\n\t\t\t\t\t\t\t\tBOOST_PP_CAT( \\\n\t\t\t\t\t\t\t\t\tLOADPS_I, \\\n\t\t\t\t\t\t\t\t\tBOOST_PP_SEQ_ELEM(0,AUn1_n0) \\\n\t\t\t\t\t\t\t\t)(m.ma[0], 0) \\\n\t\t\t\t\t\t\t); \\\n\t\t\t\tBOOST_PP_REPEAT_FROM_TO( \\\n\t\t\t\t\t1, \\\n\t\t\t\t\tBOOST_PP_SEQ_ELEM(1,AUn1_n0), \\\n\t\t\t\t\tMUL_INNER, \\\n\t\t\t\t\tBOOST_PP_SEQ_ELEM(0,AUn1_n0) \\\n\t\t\t\t) \\\n\t\t\t\tBOOST_PP_CAT(STOREPS_, BOOST_PP_SEQ_ELEM(0, AUn1_n0))(ret.ma[n], accum); }\n\t\t\tBOOST_PP_REPEAT(LEN_SEQ, DEF_CONV_ITR, DEF_MUL0)\n\t\t\t#undef DEF_MUL0\n\t\t\t#undef DEF_MUL\n\t\t}\n\t\t#else\n\t\tnamespace spn {\n\t\t\t// 自分との積算でなければ上書き演算\n\t\t\t/*\tPseudo-code:\n\t\t\t\tMT& MT::operator *= (const MatT<n0,n1,align>& m) {\n\t\t\t\t\t// 自分との積算ならば *this = *this * *this; の形で計算\n\t\t\t\t\tif((uintptr_t)&m == (uintptr_t)this)\n\t\t\t\t\t\treturn *this = *this * *this;\n\t\t\t\t\t// <Repeat by MUL_OUTER2>\n\t\t\t\t\tfor(int i=0 ; i<DIM_M ; i++) {\n\t\t\t\t\t\treg128 tm = LOADTHIS(n);\n\t\t\t\t\t\treg128 accum = reg_mul_ps(reg_shuffle_ps(tm,tm, _REG_SHUFFLE(0,0,0,0)), LOADTHIS(0));\n\t\t\t\t\t\t// <Repeat by MUL_INNER2>\n\t\t\t\t\t\tfor(int j=0 ; j<DIM_M ; j++)\n\t\t\t\t\t\t\treg_add_ps(accum, reg_mul_ps(reg_shuffle_ps(tm,tm, _REG_SHUFFLE(j,j,j,j)), LOADTHIS(j));\n\t\t\t\t\t\tSTORETHIS(j,accum);\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t*/\n\t\t\t#define DEF_MULE0(n0,n1,align) \\\n\t\t\t\tBOOST_PP_IF( \\\n\t\t\t\t\tBOOST_PP_AND( \\\n\t\t\t\t\t\tBOOST_PP_EQUAL(DIM_N, n0), \\\n\t\t\t\t\t\tBOOST_PP_EQUAL(n1, DIM_N) \\\n\t\t\t\t\t), \\\n\t\t\t\t\tDEF_MULE, \\\n\t\t\t\t\tNOTHING_ARG \\\n\t\t\t\t)(n0,n1,align)\n\t\t\t#define DEF_MULE(n0,n1,align) \\\n\t\t\t\tMT& MT::operator *= (const MatT<n0,n1,BOOLNIZE(align)>& m) { \\\n\t\t\t\t\tif((intptr_t)&m == (intptr_t)this) return mul_self(); \\\n\t\t\t\t\t\tBOOST_PP_REPEAT( \\\n\t\t\t\t\t\t\tDIM_M, MUL_OUTER2, \\\n\t\t\t\t\t\t\tBOOST_PP_IF(align, NOTHING, U) \\\n\t\t\t\t\t\t) \\\n\t\t\t\t\treturn *this; }\n\t\t\t#define MUL_INNER2(z,n,AU) \\\n\t\t\t\taccum = reg_add_ps( \\\n\t\t\t\t\taccum, \\\n\t\t\t\t\treg_mul_ps(reg_shuffle_ps(tm,tm, _REG_SHUFFLE(n,n,n,n)), LOADPS##AU(m.ma[n])) \\\n\t\t\t\t);\n\t\t\t#define MUL_OUTER2(z,n,AU) { \\\n\t\t\t\treg128 tm = LOADTHIS(n); \\\n\t\t\t\treg128 accum = reg_mul_ps(reg_shuffle_ps(tm, tm, _REG_SHUFFLE(0,0,0,0)), LOADPS##AU(m.ma[0])); \\\n\t\t\t\tBOOST_PP_REPEAT_FROM_TO(1,DIM_N, MUL_INNER2, AU) \\\n\t\t\t\tSTORETHISPS(ma[n], accum); }\n\t\t\tBOOST_PP_REPEAT(LEN_SEQ, DEF_CONV_ITR, DEF_MULE0)\n\t\t\t#undef DEF_MULE0\n\t\t\t#undef DEF_MULE\n\t\t\t#undef DEF_INNER2\n\t\t\t#undef DEF_OUTER2\n\n\t\t\t// 他の行列やベクトルと計算するメソッドを定義\n\t\t\t/*\tPseudo-code:\n\t\t\t\ttemplate <>\n\t\t\t\tVecT<DIM_N,ALIGNB> operator * (const VecT<DIM_N,align>& v) const {\n\t\t\t\t\tauto tmpM = transposition();\n\t\t\t\t\treturn v * tmpM;\n\t\t\t\t}\n\t\t\t*/\n\t\t\t#define DEF_MULOP(z,align,dummy) \\\n\t\t\t\ttemplate <> VecT<DIM_N,ALIGNB> MT::operator * (const VecT<DIM_N,BOOLNIZE(align)>& v) const { \\\n\t\t\t\t\tauto tmpM = BOOST_PP_CAT( \\\n\t\t\t\t\t\t\t\t\tBOOST_PP_CAT( \\\n\t\t\t\t\t\t\t\t\t\tBOOST_PP_CAT( \\\n\t\t\t\t\t\t\t\t\t\t\ttransposition().convert, \\\n\t\t\t\t\t\t\t\t\t\t\tAFLAG(ALIGN) \\\n\t\t\t\t\t\t\t\t\t\t), \\\n\t\t\t\t\t\t\t\t\t\tDIM_N \\\n\t\t\t\t\t\t\t\t\t), \\\n\t\t\t\t\t\t\t\t\tDIM_N \\\n\t\t\t\t\t\t\t\t)(); \\\n\t\t\t\t\treturn v * tmpM; }\n\t\t\tBOOST_PP_REPEAT(1, DEF_MULOP, NOTHING)\n\t\t\t#undef DEF_MULOP\n\t\t\t#if DIM_M==DIM_N\n\t\t\t\tVecT<DIM_N,MT::align> MT::mulV(const VecT<DIM_N,align>& v) const {\n\t\t\t\t\tauto tmpM = transposition();\n\t\t\t\t\treturn v * tmpM;\n\t\t\t\t}\n\t\t\t#endif\n\t\t}\n\t#endif\n\t#include \"local_unmacro.hpp\"\n\t#undef TUP\n\t#undef DIM_M\n\t#undef DIM_N\n\t#undef DIM\n\t#undef ALIGN\n\t#undef ALIGNB\n\t#undef ALIGN16\n\t#undef MT\n\t#undef DMAX\n\t#undef DMIN\n\t#undef DMUL\n\t#undef DIMTUPLE\n\t#undef DEF_CONV_ITR\n\t#undef DEFINE_MATRIX\n#endif\n", "meta": {"hexsha": "189000accbcd7ddf92f1365f8d00e849ea6e3bc7", "size": 33913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "matrix.hpp", "max_stars_repo_name": "degarashi/spinner", "max_stars_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix.hpp", "max_issues_repo_name": "degarashi/spinner", "max_issues_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix.hpp", "max_forks_repo_name": "degarashi/spinner", "max_forks_repo_head_hexsha": "6c0d5dbdcde962a36de28cdc867478e2a715b689", "max_forks_repo_licenses": ["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.469901168, "max_line_length": 124, "alphanum_fraction": 0.5771238168, "num_tokens": 12941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378235137849365, "lm_q2_score": 0.028870909975261816, "lm_q1q2_score": 0.012640363251537702}}
{"text": "/*-----------------------------------------------------------------------------+\nCopyright (c) 2007-2011: Joachim Faulhaber\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n#ifndef BOOST_ICL_MAP_HPP_JOFA_070519\n#define BOOST_ICL_MAP_HPP_JOFA_070519\n\n#include <boost/icl/impl_config.hpp>\n\n#if defined(ICL_USE_BOOST_MOVE_IMPLEMENTATION)\n#   include <boost/container/map.hpp>\n#   include <boost/container/set.hpp>\n#elif defined(ICL_USE_STD_IMPLEMENTATION)\n#   include <map>\n#   include <set>\n#else // Default for implementing containers\n#   include <map>\n#   include <set>\n#endif\n\n#include <string>\n#include <boost/type_traits/ice.hpp>\n#include <boost/call_traits.hpp> \n#include <boost/icl/detail/notate.hpp>\n#include <boost/icl/detail/design_config.hpp>\n#include <boost/icl/detail/concept_check.hpp>\n#include <boost/icl/detail/on_absorbtion.hpp>\n#include <boost/icl/type_traits/is_map.hpp>\n#include <boost/icl/type_traits/absorbs_identities.hpp>\n#include <boost/icl/type_traits/is_total.hpp>\n#include <boost/icl/type_traits/is_element_container.hpp>\n#include <boost/icl/type_traits/has_inverse.hpp>\n#include <boost/icl/type_traits/to_string.hpp>\n#include <boost/icl/functors.hpp>\n\n#include <boost/icl/associative_element_container.hpp>\n\nnamespace boost{namespace icl\n{\n\nstruct partial_absorber\n{\n    enum { absorbs_identities = true };\n    enum { is_total = false };\n};\n\ntemplate<> \ninline std::string type_to_string<partial_absorber>::apply() { return \"@0\"; }\n\nstruct partial_enricher\n{\n    enum { absorbs_identities = false };\n    enum { is_total = false };\n};\n\ntemplate<> \ninline std::string type_to_string<partial_enricher>::apply() { return \"e0\"; }\n\nstruct total_absorber\n{\n    enum { absorbs_identities = true };\n    enum { is_total = true };\n};\n\ntemplate<> \ninline std::string type_to_string<total_absorber>::apply() { return \"^0\"; }\n\nstruct total_enricher\n{\n    enum { absorbs_identities = false };\n    enum { is_total = true };\n};\n\ntemplate<> \ninline std::string type_to_string<total_enricher>::apply() { return \"e^0\"; }\n\n\n\n/** \\brief Addable, subractable and intersectable maps */\ntemplate \n<\n    typename DomainT, \n    typename CodomainT, \n    class Traits = icl::partial_absorber,\n    ICL_COMPARE Compare = ICL_COMPARE_INSTANCE(ICL_COMPARE_DEFAULT, DomainT),\n    ICL_COMBINE Combine = ICL_COMBINE_INSTANCE(icl::inplace_plus, CodomainT),\n    ICL_SECTION Section = ICL_SECTION_INSTANCE(icl::inter_section, CodomainT), \n    ICL_ALLOC   Alloc   = std::allocator \n>\nclass map: private ICL_IMPL_SPACE::map<DomainT, CodomainT, ICL_COMPARE_DOMAIN(Compare,DomainT), \n                                       Alloc<std::pair<const DomainT, CodomainT> > >\n{\npublic:\n    typedef Alloc<typename std::pair<const DomainT, CodomainT> >  allocator_type;\n\n    typedef typename icl::map<DomainT,CodomainT,Traits, Compare,Combine,Section,Alloc> type;\n    typedef typename ICL_IMPL_SPACE::map<DomainT, CodomainT, ICL_COMPARE_DOMAIN(Compare,DomainT),\n                                         allocator_type>   base_type;\n\n    typedef Traits traits;\n\npublic:\n    typedef DomainT                                     domain_type;\n    typedef typename boost::call_traits<DomainT>::param_type domain_param;\n    typedef DomainT                                     key_type;\n    typedef CodomainT                                   codomain_type;\n    typedef CodomainT                                   mapped_type;\n    typedef CodomainT                                   data_type;\n    typedef std::pair<const DomainT, CodomainT>         element_type;\n    typedef std::pair<const DomainT, CodomainT>         value_type;\n    typedef ICL_COMPARE_DOMAIN(Compare,DomainT)         domain_compare;\n    typedef ICL_COMBINE_CODOMAIN(Combine,CodomainT)     codomain_combine;\n    typedef domain_compare                              key_compare;\n    typedef ICL_COMPARE_DOMAIN(Compare,element_type)    element_compare;\n    typedef typename inverse<codomain_combine >::type   inverse_codomain_combine;\n    typedef typename mpl::if_\n        <has_set_semantics<codomain_type>\n        , ICL_SECTION_CODOMAIN(Section,CodomainT)     \n        , codomain_combine\n        >::type                                         codomain_intersect;\n    typedef typename inverse<codomain_intersect>::type  inverse_codomain_intersect;\n    typedef typename base_type::value_compare           value_compare;\n\n    typedef typename ICL_IMPL_SPACE::set<DomainT, domain_compare, Alloc<DomainT> > set_type;\n    typedef set_type                                       key_object_type;\n\n\n    BOOST_STATIC_CONSTANT(bool, _total   = (Traits::is_total));\n    BOOST_STATIC_CONSTANT(bool, _absorbs = (Traits::absorbs_identities));\n    BOOST_STATIC_CONSTANT(bool, \n        total_invertible = (mpl::and_<is_total<type>, has_inverse<codomain_type> >::value));\n\n    typedef on_absorbtion<type,codomain_combine,Traits::absorbs_identities> \n                                                        on_identity_absorbtion;\n\npublic:\n    typedef typename base_type::pointer                 pointer;\n    typedef typename base_type::const_pointer           const_pointer;\n    typedef typename base_type::reference               reference;\n    typedef typename base_type::const_reference         const_reference;\n    typedef typename base_type::iterator                iterator;\n    typedef typename base_type::const_iterator          const_iterator;\n    typedef typename base_type::size_type               size_type;\n    typedef typename base_type::difference_type         difference_type;\n    typedef typename base_type::reverse_iterator        reverse_iterator;\n    typedef typename base_type::const_reverse_iterator  const_reverse_iterator;\n\npublic:\n    BOOST_STATIC_CONSTANT(bool, \n        is_total_invertible = (   Traits::is_total \n                               && has_inverse<codomain_type>::value));\n\n    BOOST_STATIC_CONSTANT(int, fineness = 4); \n\npublic:\n    //==========================================================================\n    //= Construct, copy, destruct\n    //==========================================================================\n    map()\n    {\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));\n        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));\n        BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));\n    }\n\n    map(const key_compare& comp): base_type(comp){}\n\n    template <class InputIterator>\n    map(InputIterator first, InputIterator past)\n        : base_type(first,past){} \n\n    template <class InputIterator>\n    map(InputIterator first, InputIterator past, const key_compare& comp)\n        : base_type(first,past,comp) \n    {}\n\n    map(const map& src)\n        : base_type(src)\n    {\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));\n        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));\n        BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));\n    }\n\n    explicit map(const element_type& key_value_pair): base_type::map()\n    { \n        insert(key_value_pair); \n    }\n\n    map& operator = (const map& src) \n    { \n        base_type::operator=(src);\n        return *this; \n    } \n\n#   ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n    //==========================================================================\n    //= Move semantics\n    //==========================================================================\n\n    map(map&& src)\n        : base_type(boost::move(src))\n    {\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));\n        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));\n        BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));\n    }\n\n    map& operator = (map&& src) \n    { \n        base_type::operator=(src);\n        return *this; \n    } \n    //==========================================================================\n#   endif // BOOST_NO_CXX11_RVALUE_REFERENCES\n\n    void swap(map& src) { base_type::swap(src); }\n\n    //==========================================================================\n    using base_type::empty;\n    using base_type::clear;\n\n    using base_type::begin;\n    using base_type::end;\n    using base_type::rbegin;\n    using base_type::rend;\n\n    using base_type::size;\n    using base_type::max_size;\n\n    using base_type::key_comp;\n    using base_type::value_comp;\n\n    using base_type::erase;\n    using base_type::find;\n    using base_type::count;\n\n    using base_type::lower_bound;\n    using base_type::upper_bound;\n    using base_type::equal_range;\n\n    using base_type::operator[];\n\npublic:\n    //==========================================================================\n    //= Containedness\n    //==========================================================================\n\n    template<class SubObject>\n    bool contains(const SubObject& sub)const \n    { return icl::contains(*this, sub); }\n\n    bool within(const map& super)const \n    { return icl::contains(super, *this); }\n\n    //==========================================================================\n    //= Size\n    //==========================================================================\n    /** \\c iterative_size() yields the number of elements that is visited\n        throu complete iteration. For interval sets \\c iterative_size() is\n        different from \\c size(). */\n    std::size_t iterative_size()const { return base_type::size(); }\n\n    //==========================================================================\n    //= Selection\n    //==========================================================================\n\n    /** Total select function. */\n    codomain_type operator()(const domain_type& key)const\n    {\n        const_iterator it = find(key); \n        return it==end() ? identity_element<codomain_type>::value()\n                         : it->second;\n    }\n\n    //==========================================================================\n    //= Addition\n    //==========================================================================\n    /** \\c add inserts \\c value_pair into the map if it's key does \n        not exist in the map.    \n        If \\c value_pairs's key value exists in the map, it's data\n        value is added to the data value already found in the map. */\n    map& add(const value_type& value_pair) \n    { \n        return _add<codomain_combine>(value_pair); \n    }\n\n    /** \\c add add \\c value_pair into the map using \\c prior as a hint to\n        insert \\c value_pair after the position \\c prior is pointing to. */\n    iterator add(iterator prior, const value_type& value_pair) \n    { \n        return _add<codomain_combine>(prior, value_pair); \n    }\n\n    //==========================================================================\n    //= Subtraction\n    //==========================================================================\n    /** If the \\c value_pair's key value is in the map, it's data value is\n        subtraced from the data value stored in the map. */\n    map& subtract(const element_type& value_pair)\n    {\n        on_invertible<type, is_total_invertible>\n            ::subtract(*this, value_pair);\n        return *this;\n    }\n\n    map& subtract(const domain_type& key)\n    {\n        icl::erase(*this, key);\n        return *this;\n    }\n\n    //==========================================================================\n    //= Insertion, erasure\n    //==========================================================================\n    std::pair<iterator,bool> insert(const value_type& value_pair)\n    {\n        if(on_identity_absorbtion::is_absorbable(value_pair.second)) \n            return std::pair<iterator,bool>(end(),true);\n        else\n            return base_type::insert(value_pair);\n    }\n    \n    iterator insert(iterator prior, const value_type& value_pair)\n    {\n        if(on_identity_absorbtion::is_absorbable(value_pair.second)) \n            return end();\n        else\n            return base_type::insert(prior, value_pair);\n    }\n\n    template<class Iterator>\n    iterator insert(Iterator first, Iterator last)\n    {\n        iterator prior = end(), it = first;\n        while(it != last)\n            prior = this->insert(prior, *it++);\n    }\n\n    /** With <tt>key_value_pair = (k,v)</tt> set value \\c v for key \\c k */\n    map& set(const element_type& key_value_pair)\n    { \n        return icl::set_at(*this, key_value_pair);\n    }\n\n    /** erase \\c key_value_pair from the map.\n        Erase only if, the exact value content \\c val is stored for the given key. */\n    size_type erase(const element_type& key_value_pair)\n    {\n        return icl::erase(*this, key_value_pair); \n    }\n\n    //==========================================================================\n    //= Intersection\n    //==========================================================================\n    /** The intersection of \\c key_value_pair and \\c *this map is added to \\c section. */\n    void add_intersection(map& section, const element_type& key_value_pair)const\n    {\n        on_definedness<type, Traits::is_total>\n            ::add_intersection(section, *this, key_value_pair);\n    }\n\n    //==========================================================================\n    //= Symmetric difference\n    //==========================================================================\n\n    map& flip(const element_type& operand)\n    {\n        on_total_absorbable<type,_total,_absorbs>::flip(*this, operand);\n        return *this;\n    }\n\nprivate:\n    template<class Combiner>\n    map& _add(const element_type& value_pair);\n\n    template<class Combiner>\n    iterator _add(iterator prior, const element_type& value_pair);\n\n    template<class Combiner>\n    map& _subtract(const element_type& value_pair);\n\n    template<class FragmentT>\n    void total_add_intersection(type& section, const FragmentT& fragment)const\n    {\n        section += *this;\n        section.add(fragment);\n    }\n\n    void partial_add_intersection(type& section, const element_type& operand)const\n    {\n        const_iterator it_ = find(operand.first);\n        if(it_ != end())\n        {\n            section.template _add<codomain_combine  >(*it_);\n            section.template _add<codomain_intersect>(operand); \n        }\n    }\n\n\nprivate:\n    //--------------------------------------------------------------------------\n    template<class Type, bool is_total_invertible>\n    struct on_invertible;\n\n    template<class Type>\n    struct on_invertible<Type, true>\n    {\n        typedef typename Type::element_type element_type;\n        typedef typename Type::inverse_codomain_combine inverse_codomain_combine;\n\n        static void subtract(Type& object, const element_type& operand)\n        { object.template _add<inverse_codomain_combine>(operand); }\n    };\n\n    template<class Type>\n    struct on_invertible<Type, false>\n    {\n        typedef typename Type::element_type element_type;\n        typedef typename Type::inverse_codomain_combine inverse_codomain_combine;\n\n        static void subtract(Type& object, const element_type& operand)\n        { object.template _subtract<inverse_codomain_combine>(operand); }\n    };\n\n    friend struct on_invertible<type, true>;\n    friend struct on_invertible<type, false>;\n    //--------------------------------------------------------------------------\n\n    //--------------------------------------------------------------------------\n    template<class Type, bool is_total>\n    struct on_definedness;\n\n    template<class Type>\n    struct on_definedness<Type, true>\n    {\n        static void add_intersection(Type& section, const Type& object, \n                                     const element_type& operand)\n        { object.total_add_intersection(section, operand); }\n    };\n\n    template<class Type>\n    struct on_definedness<Type, false>\n    {\n        static void add_intersection(Type& section, const Type& object, \n                                     const element_type& operand)\n        { object.partial_add_intersection(section, operand); }\n    };\n\n    friend struct on_definedness<type, true>;\n    friend struct on_definedness<type, false>;\n    //--------------------------------------------------------------------------\n\n    //--------------------------------------------------------------------------\n    template<class Type, bool has_set_semantics, bool absorbs_identities>\n    struct on_codomain_model;\n\n    template<class Type>\n    struct on_codomain_model<Type, false, false>\n    {                // !codomain_is_set, !absorbs_identities\n        static void subtract(Type&, typename Type::iterator it_, \n                              const typename Type::codomain_type& )\n        { (*it_).second = identity_element<typename Type::codomain_type>::value(); }\n    };\n\n    template<class Type>\n    struct on_codomain_model<Type, false, true>\n    {                // !codomain_is_set, absorbs_identities\n        static void subtract(Type& object, typename Type::iterator       it_, \n                                     const typename Type::codomain_type&     )\n        { object.erase(it_); }\n    };\n\n    template<class Type>\n    struct on_codomain_model<Type, true, false>\n    {               // !codomain_is_set, !absorbs_identities\n        typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;\n        static void subtract(Type&, typename Type::iterator       it_, \n                              const typename Type::codomain_type& co_value)\n        { \n            inverse_codomain_intersect()((*it_).second, co_value); \n        }\n    };\n\n    template<class Type>\n    struct on_codomain_model<Type, true, true>\n    {               // !codomain_is_set, absorbs_identities\n        typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;\n        static void subtract(Type& object, typename Type::iterator       it_, \n                                     const typename Type::codomain_type& co_value)\n        { \n            inverse_codomain_intersect()((*it_).second, co_value); \n            if((*it_).second == identity_element<codomain_type>::value())\n                object.erase(it_);\n        }\n    };\n    //--------------------------------------------------------------------------\n\n    //--------------------------------------------------------------------------\n    template<class Type, bool is_total, bool absorbs_identities>\n    struct on_total_absorbable;\n\n    template<class Type>\n    struct on_total_absorbable<Type, true, true>\n    {\n        typedef typename Type::element_type  element_type;\n        static void flip(Type& object, const typename Type::element_type&)\n        { icl::clear(object); }\n    };\n\n    template<class Type>\n    struct on_total_absorbable<Type, true, false>\n    {\n        typedef typename Type::element_type  element_type;\n        typedef typename Type::codomain_type codomain_type;\n\n        static void flip(Type& object, const element_type& operand)\n        { \n            object.add(operand);\n            ICL_FORALL(typename Type, it_, object)\n                (*it_).second = identity_element<codomain_type>::value();\n        }\n    };\n\n    template<class Type>\n    struct on_total_absorbable<Type, false, true>\n    {                         // !is_total, absorbs_identities\n        typedef typename Type::element_type   element_type;\n        typedef typename Type::codomain_type  codomain_type;\n        typedef typename Type::iterator       iterator;\n        typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;\n\n        static void flip(Type& object, const element_type& operand)\n        {\n            std::pair<iterator,bool> insertion = object.insert(operand);\n            if(!insertion.second)\n                on_codomain_model<Type, has_set_semantics<codomain_type>::value, true>\n                ::subtract(object, insertion.first, operand.second);\n        }\n    };\n\n    template<class Type>\n    struct on_total_absorbable<Type, false, false>\n    {                         // !is_total  !absorbs_identities\n        typedef typename Type::element_type   element_type;\n        typedef typename Type::codomain_type  codomain_type;\n        typedef typename Type::iterator       iterator;\n        typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;\n\n        static void flip(Type& object, const element_type& operand)\n        {\n            std::pair<iterator,bool> insertion = object.insert(operand);\n            if(!insertion.second)\n                on_codomain_model<Type, has_set_semantics<codomain_type>::value, false>\n                ::subtract(object, insertion.first, operand.second);\n        }\n    };\n\n    friend struct on_total_absorbable<type, true,  true >;\n    friend struct on_total_absorbable<type, false, true >;\n    friend struct on_total_absorbable<type, true,  false>;\n    friend struct on_total_absorbable<type, false, false>;\n    //--------------------------------------------------------------------------\n};\n\n\n\n//==============================================================================\n//= Addition<ElementMap>\n//==============================================================================\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\n    template <class Combiner>\nmap<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc>&\n    map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc>\n    ::_add(const element_type& addend)\n{\n    typedef typename on_absorbtion\n        <type,Combiner,absorbs_identities<type>::value>::type on_absorbtion_;\n\n    const codomain_type& co_val    = addend.second;\n    if(on_absorbtion_::is_absorbable(co_val))\n        return *this;\n\n    std::pair<iterator,bool> insertion \n        = base_type::insert(value_type(addend.first, version<Combiner>()(co_val)));\n\n    if(!insertion.second)\n    {\n        iterator it = insertion.first;\n        Combiner()((*it).second, co_val);\n\n        if(on_absorbtion_::is_absorbable((*it).second))\n            erase(it);\n    }\n    return *this;\n}\n\n\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\n    template <class Combiner>\ntypename map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc>::iterator\n    map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc>\n    ::_add(iterator prior_, const value_type& addend)\n{\n    typedef typename on_absorbtion\n        <type,Combiner,absorbs_identities<type>::value>::type on_absorbtion_;\n\n    const codomain_type& co_val    = addend.second;\n    if(on_absorbtion_::is_absorbable(co_val))\n        return end();\n\n    iterator inserted_ \n        = base_type::insert(prior_, \n                            value_type(addend.first, Combiner::identity_element()));\n    Combiner()((*inserted_).second, addend.second);\n\n    if(on_absorbtion_::is_absorbable((*inserted_).second))\n    {\n        erase(inserted_);\n        return end();\n    }\n    else\n        return inserted_;\n}\n\n\n//==============================================================================\n//= Subtraction<ElementMap>\n//==============================================================================\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\n    template <class Combiner>\nmap<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc>&\n    map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc>::_subtract(const value_type& minuend)\n{\n    typedef typename on_absorbtion\n        <type,Combiner,absorbs_identities<type>::value>::type on_absorbtion_;\n\n    iterator it_ = find(minuend.first);\n    if(it_ != end())\n    {\n        Combiner()((*it_).second, minuend.second);\n        if(on_absorbtion_::is_absorbable((*it_).second))\n            erase(it_);\n    }\n    return *this;\n}\n\n\n//-----------------------------------------------------------------------------\n// type traits\n//-----------------------------------------------------------------------------\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\nstruct is_map<icl::map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc> >\n{ \n    typedef is_map<icl::map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc> > type;\n    BOOST_STATIC_CONSTANT(bool, value = true); \n};\n\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\nstruct has_inverse<icl::map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc> >\n{ \n    typedef has_inverse<icl::map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc> > type;\n    BOOST_STATIC_CONSTANT(bool, value = (has_inverse<CodomainT>::value)); \n};\n\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\nstruct absorbs_identities<icl::map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc> >\n{ \n    typedef absorbs_identities type;\n    BOOST_STATIC_CONSTANT(int, value = Traits::absorbs_identities); \n};\n\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\nstruct is_total<icl::map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc> >\n{ \n    typedef is_total type;\n    BOOST_STATIC_CONSTANT(int, value = Traits::is_total); \n};\n\ntemplate <class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_ALLOC Alloc>\nstruct type_to_string<icl::map<DomainT,CodomainT,Traits,Compare,Combine,Section,Alloc> >\n{\n    static std::string apply()\n    {\n        return \"map<\"+ type_to_string<DomainT>::apply()  + \",\"\n                     + type_to_string<CodomainT>::apply() + \",\"\n                     + type_to_string<Traits>::apply() +\">\"; \n    }\n};\n\n\n\n}} // namespace icl boost\n\n#endif // BOOST_ICL_MAP_HPP_JOFA_070519\n\n", "meta": {"hexsha": "9edb0beaa5d367a47d1a59856026e32994a73387", "size": 26370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/icl/map.hpp", "max_stars_repo_name": "datacratic/boost-svn", "max_stars_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T18:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T18:18:10.000Z", "max_issues_repo_path": "boost/icl/map.hpp", "max_issues_repo_name": "datacratic/boost-svn", "max_issues_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/icl/map.hpp", "max_forks_repo_name": "datacratic/boost-svn", "max_forks_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5106685633, "max_line_length": 135, "alphanum_fraction": 0.5876374668, "num_tokens": 5578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.03308597922294221, "lm_q1q2_score": 0.012613022648530018}}
{"text": "// maya\n// Copyright (c) 2012-2016, Joshua Scoggins\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//\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\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.\nextern \"C\" {\n#include \"clips.h\"\n}\n#include \"mayasetup.h\"\n#include \"boost.h\"\n#include <string>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/random_generator.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <boost/math/common_factor.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/system/error_code.hpp>\n#include <boost/algorithm/clamp.hpp>\n\n\n#if BOOST_EXTENSIONS\nvoid HasPrefix(Environment*, UDFContext*, UDFValue*);\nvoid HasSuffix(Environment*, UDFContext*, UDFValue*);\nvoid TrimString(Environment*, UDFContext*, UDFValue*);\nvoid TrimStringFront(Environment*, UDFContext*, UDFValue*);\nvoid TrimStringBack(Environment*, UDFContext*, UDFValue*);\nvoid NewUUID(Environment*, UDFContext*, UDFValue*);\nvoid gcdFunction(Environment*, UDFContext*, UDFValue*);\nvoid lcmFunction(Environment*, UDFContext*, UDFValue*);\nvoid FileExists(Environment*, UDFContext*, UDFValue*);\nvoid IsDirectory(Environment*, UDFContext*, UDFValue*);\nvoid IsRegularFile(Environment*, UDFContext*, UDFValue*);\nvoid ClampValue(Environment*, UDFContext*, UDFValue*);\n#endif\n\nextern \"C\" void InstallBoostExtensions(Environment* theEnv) {\n#if BOOST_EXTENSIONS\n\tAddUDF(theEnv, \"has-prefix\", \"b\", 2, 2, \"sy;sy;sy\", HasPrefix, \"HasPrefix\",  NULL);\n\tAddUDF(theEnv, \"has-suffix\", \"b\", 2, 2, \"sy;sy;sy\", HasSuffix, \"HasSuffix\",  NULL);\n\tAddUDF(theEnv, \"string-trim\", \"y\", 1, 1, \"s\", TrimString, \"TrimString\", NULL);\n\tAddUDF(theEnv, \"string-trim-front\", \"y\", 1, 1, \"s\", TrimStringFront, \"TrimStringFront\", NULL);\n\tAddUDF(theEnv, \"string-trim-back\", \"y\",  1, 1, \"s\", TrimStringBack, \"TrimStringBack\", NULL);\n\tAddUDF(theEnv, \"new-uuid\", \"s\", 0, 0, \"\", NewUUID, \"NewUUID\", NULL);\n\tAddUDF(theEnv, \"gcd\", \"l\",  2, 2, \"l;l;l\", gcdFunction, \"gcdFunction\", NULL);\n\tAddUDF(theEnv, \"lcm\", \"l\",  2, 2, \"l;l;l\", lcmFunction, \"lcmFunction\", NULL);\n\tAddUDF(theEnv, \"path-exists\",   \"b\", 1, 1, \"sy\", FileExists, \"FileExists\", NULL);\n\tAddUDF(theEnv, \"directoryp\",    \"b\", 1, 1, \"sy\", IsDirectory, \"IsDirectory\", NULL);\n\tAddUDF(theEnv, \"regular-filep\", \"b\", 1, 1, \"sy\", IsRegularFile, \"IsRegularFile\", NULL);\n\tAddUDF(theEnv, \"clamp\", \"l\",  3, 3, \"l;l;l;l\", ClampValue, \"ClampValue\", NULL);\n#endif\n}\n\n\n#if BOOST_EXTENSIONS\nvoid ClampValue(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue v, lo, hi;\n\tif (!UDFFirstArgument(context, INTEGER_BIT,  &v)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else if (!UDFNextArgument(context, INTEGER_BIT, &lo)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else if (!UDFNextArgument(context, INTEGER_BIT, &hi)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tret->integerValue = CreateInteger(env, boost::algorithm::clamp(CVCoerceToInteger(&v), CVCoerceToInteger(&lo), CVCoerceToInteger(&hi)));\n\t}\n}\n\nvoid FileExists(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue path;\n\tif (!UDFFirstArgument(context, LEXEME_BITS, &path)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tstd::string p(path.lexemeValue->contents);\n\t\tret->lexemeValue = boost::filesystem::exists(p) ? TrueSymbol(env) : FalseSymbol(env);\n\t}\n}\n\nvoid IsDirectory(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue path;\n\tif (!UDFFirstArgument(context, LEXEME_BITS, &path)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tstd::string p(path.lexemeValue->contents);\n\t\tret->lexemeValue = boost::filesystem::is_directory(p) ? TrueSymbol(env) : FalseSymbol(env);\n\t}\n}\n\nvoid IsRegularFile(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue path;\n\tif (!UDFFirstArgument(context, LEXEME_BITS, &path)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tstd::string p(path.lexemeValue->contents);\n\t\tret->lexemeValue = boost::filesystem::is_regular_file(p) ? TrueSymbol(env) : FalseSymbol(env);\n\t}\n}\n\nvoid gcdFunction(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue first, second;\n\tif (!UDFFirstArgument(context, INTEGER_BIT, &first)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else if (!UDFNextArgument(context, INTEGER_BIT, &second)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tret->integerValue = CreateInteger(env, boost::math::gcd(CVCoerceToInteger(&first), CVCoerceToInteger(&second)));\n\t}\n}\nvoid lcmFunction(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue first, second;\n\tif (!UDFFirstArgument(context, INTEGER_BIT, &first)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else if (!UDFNextArgument(context, INTEGER_BIT, &second)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tret->integerValue = CreateInteger(env, boost::math::lcm(CVCoerceToInteger(&first), CVCoerceToInteger(&second)));\n\t}\n}\nvoid NewUUID(Environment* env, UDFContext* context, UDFValue* ret) {\n\tboost::uuids::random_generator rgen;\n\tboost::uuids::uuid theUUID(rgen());\n\tconst std::string tmp = boost::lexical_cast<std::string>(theUUID);\n\tret->value = CreateSymbol(env, tmp.c_str());\n}\nvoid HasPrefix(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue data, prefix;\n\tif (!UDFFirstArgument(context, LEXEME_BITS, &data)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t\treturn;\n\t} else if (!UDFNextArgument(context, LEXEME_BITS, &prefix)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t\treturn;\n\t}\n\tstd::string dataStr(data.lexemeValue->contents);\n\tstd::string prefixStr(prefix.lexemeValue->contents);\n\tret->lexemeValue = boost::starts_with(dataStr, prefixStr) ? TrueSymbol(env) : FalseSymbol(env);\n}\n\nvoid HasSuffix(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue data, suffix;\n\tif (!UDFFirstArgument(context, LEXEME_BITS, &data)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t\treturn;\n\t} else if (!UDFNextArgument(context, LEXEME_BITS, &suffix)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t\treturn;\n\t}\n\tstd::string dataStr(data.lexemeValue->contents);\n\tstd::string suffixStr(suffix.lexemeValue->contents);\n\tret->lexemeValue = boost::ends_with(dataStr, suffixStr) ? TrueSymbol(env) : FalseSymbol(env);\n}\nvoid TrimString(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue str;\n\tif (!UDFFirstArgument(context, STRING_BIT, &str)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tstd::string tmp(str.lexemeValue->contents);\n\t\tboost::algorithm::trim(tmp);\n\t\tret->value = CreateString(env, tmp.c_str());\n\t}\n}\nvoid TrimStringFront(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue str;\n\tif (!UDFFirstArgument(context, STRING_BIT, &str)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tstd::string tmp(str.lexemeValue->contents);\n\t\tboost::algorithm::trim_left(tmp);\n\t\tret->value = CreateString(env, tmp.c_str());\n\t}\n}\nvoid TrimStringBack(Environment* env, UDFContext* context, UDFValue* ret) {\n\tUDFValue str;\n\tif (!UDFFirstArgument(context, STRING_BIT, &str)) {\n\t\tret->lexemeValue = FalseSymbol(env);\n\t} else {\n\t\tstd::string tmp(str.lexemeValue->contents);\n\t\tboost::algorithm::trim_right(tmp);\n\t\tret->value = CreateString(env, tmp.c_str());\n\t}\n}\n#endif\n\n\n\n", "meta": {"hexsha": "b33726eda1d4d1a0a1b22e8c70d34871af28572b", "size": 8361, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boost.cc", "max_stars_repo_name": "DrItanium/syn", "max_stars_repo_head_hexsha": "bee289392e9e84a12d98a4b19f2a0ada9d7ae14a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-17T14:46:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-17T14:46:28.000Z", "max_issues_repo_path": "boost.cc", "max_issues_repo_name": "DrItanium/syn", "max_issues_repo_head_hexsha": "bee289392e9e84a12d98a4b19f2a0ada9d7ae14a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-03-15T23:28:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-29T22:48:28.000Z", "max_forks_repo_path": "boost.cc", "max_forks_repo_name": "DrItanium/syn", "max_forks_repo_head_hexsha": "bee289392e9e84a12d98a4b19f2a0ada9d7ae14a", "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.7853658537, "max_line_length": 137, "alphanum_fraction": 0.7253916996, "num_tokens": 2350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.027585282026933125, "lm_q1q2_score": 0.01261024525855271}}
{"text": "// BSD 3-Clause License\n\n// Copyright (c) 2020, Chenyu\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\n//    list of conditions and the following disclaimer.\n\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived from\n//    this software without specific prior written permission.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\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 \"base/track_selection.h\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <unordered_set>\n#include <utility>\n\n#include \"base/camera.h\"\n#include \"base/image.h\"\n#include \"base/projection.h\"\n#include \"util/hash.h\"\n\nusing namespace std;\n\nnamespace {\n\n// Track statistics are the track length and mean reprojection error.\ntypedef pair<int, double> TrackStatistics;\ntypedef pair<point3D_t, TrackStatistics> GridCellElement;\ntypedef unordered_map<Eigen::Vector2i, vector<GridCellElement>> ImageGrid;\n\n// Sorts the grid cell elements by the track statistics, which will sort first\n// by the (truncated) track length, then by the mean reprojection error.\nbool CompareGridCellElements(const pair<point3D_t, TrackStatistics>& element1,\n                             const pair<point3D_t, TrackStatistics>& element2) {\n  return element1.second < element2.second;\n}\n\n// Compute the reprojrection error and truncated track length for the\n// specific track.\nTrackStatistics ComputeStatisticsForTrack(\n    const Reconstruction& reconstruction, const point3D_t track_id,\n    const int long_track_length_threshold) {\n  // Any track that reach this function are guaranteed to exist and\n  // be estimated, so no need to check for that here.\n  const Point3D& point3d = reconstruction.Point3D(track_id);\n  const std::vector<TrackElement> track_elements = point3d.Track().Elements();\n  std::vector<image_t> images_observing_track;\n  for (const auto track_element : track_elements) {\n    images_observing_track.push_back(track_element.image_id);\n  }\n\n  double sq_reprojection_error_sum = 0.0;\n  int num_valid_reprojections = 0;\n  // Compute the squared reprojection error for each view that observes this\n  // track and add it to the accumulating sum.\n  for (const TrackElement element : track_elements) {\n    if (!reconstruction.IsImageRegistered(element.image_id)) {\n      continue;\n    }\n\n    const Image& image = reconstruction.Image(element.image_id);\n    const Camera& camera = reconstruction.Camera(image.CameraId());\n    const Point2D& point2d = image.Point2D(element.point2D_idx);\n\n    sq_reprojection_error_sum += colmap::CalculateSquaredReprojectionError(\n        point2d.XY(), point3d.XYZ(), image.Qvec(), image.Tvec(), camera);\n    num_valid_reprojections++;\n  }\n\n  // Compute and return the track statistics.\n  const int truncated_track_length =\n      std::min(num_valid_reprojections, long_track_length_threshold);\n  const double mean_sq_reprojection_error =\n      sq_reprojection_error_sum / static_cast<double>(num_valid_reprojections);\n\n  return TrackStatistics(truncated_track_length, mean_sq_reprojection_error);\n}\n\n// Compute the mean reprojection error and the truncated track length of each\n// track. We truncate the track length based on the observation that while\n// larger track lengths provide better constraints for bundle adjustment, larger\n// tracks are also more likely to contain outliers in our experience. Truncating\n// the track lengths enforces that the long tracks with the lowest reprojection\n// error are chosen.\nvoid ComputeTrackStatistics(\n    const Reconstruction& reconstruction,\n    const std::unordered_set<image_t> image_ids,\n    const int long_track_length_threshold,\n    std::unordered_map<point3D_t, TrackStatistics>* track_statistics) {\n  // Iterate over all registered views and compute the track statistics for each\n  // track we encounter.\n  for (const image_t image_id : image_ids) {\n    const Image image = reconstruction.Image(image_id);\n    const std::vector<Point2D> points2d = image.Points2D();\n    // Compute statistics for each point that has point3d and compute the\n    // track statistics for each track we encounter.\n    for (const Point2D& point2d : points2d) {\n      if (!point2d.HasPoint3D()) {\n        continue;\n      }\n      const point3D_t track_id = point2d.Point3DId();\n      if (track_statistics->count(track_id) != 0) {\n        continue;\n      }\n\n      // Compute the track statistics and add it to the output map.\n      const TrackStatistics& statistics_for_this_track =\n          ComputeStatisticsForTrack(reconstruction, track_id,\n                                    long_track_length_threshold);\n      track_statistics->emplace(track_id, statistics_for_this_track);\n    }\n  }\n}\n\n// Select tracks from the image to ensure good spatial coverage of the image. To\n// do this, we first bin the tracks into grid cells in an image grid. Then\n// within each cell we find the best ranked track and add it to the list of\n// tracks to optimize.\nvoid SelectBestTracksFromEachImageGridCell(\n    const Reconstruction& reconstruction, const Image& image,\n    const int grid_cell_size,\n    const std::unordered_map<point3D_t, TrackStatistics>& track_statistics,\n    std::unordered_set<point3D_t>* tracks_to_optimize) {\n  static const double inv_grid_cell_size = 1.0 / grid_cell_size;\n\n  // Hash each feature into a grid cell.\n  ImageGrid image_grid;\n  const std::vector<Point2D> points2d = image.Points2D();\n  for (const Point2D& point2d : points2d) {\n    if (!point2d.HasPoint3D()) {\n      continue;\n    }\n\n    const Eigen::Vector2d feature = point2d.XY();\n    const point3D_t track_id = point2d.Point3DId();\n\n    if (track_statistics.count(track_id) == 0) {\n      continue;\n    }\n\n    const TrackStatistics& current_track_statistics =\n        track_statistics.at(track_id);\n    const Eigen::Vector2i grid_cell =\n        (feature * inv_grid_cell_size).cast<int>();\n\n    image_grid[grid_cell].emplace_back(track_id, current_track_statistics);\n  }\n\n  // Select the best feature from each grid cell and add it to the tracks to\n  // optimize.\n  for (auto& grid_cell : image_grid) {\n    // Order the features in each cell by track length first, then mean\n    // reprojection error.\n    const GridCellElement& grid_cell_element =\n        *std::min_element(grid_cell.second.begin(), grid_cell.second.end(),\n                          CompareGridCellElements);\n    // Insert the track id in to the tracks to optimize.\n    tracks_to_optimize->emplace(grid_cell_element.first);\n  }\n}\n\n// Selects the top ranked tracks that have not already been chosen until the\n// view observes the minimum number of optimized tracks.\nvoid SelectTopRankedTracksInView(\n    const Reconstruction& reconstruction,\n    const std::unordered_map<point3D_t, TrackStatistics>& track_statistics,\n    const Image& image, const int min_num_optimized_tracks_per_view,\n    std::unordered_set<point3D_t>* tracks_to_optimize) {\n  int num_optimized_tracks = 0;\n  int num_estimated_tracks = 0;\n  std::vector<GridCellElement> ranked_candidate_tracks;\n\n  const std::vector<Point2D> points2d = image.Points2D();\n  for (const Point2D& point2d : points2d) {\n    if (!point2d.HasPoint3D()) {\n      continue;\n    }\n\n    // We only reach this point if the track is estimated.\n    num_estimated_tracks++;\n\n    const point3D_t track_id = point2d.Point3DId();\n    // If the track is already slated for optimization, increase the count of\n    // optimized features.\n    if (tracks_to_optimize->count(track_id) != 0) {\n      num_optimized_tracks++;\n      // If the number of optimized tracks is greater than the minimum then\n      // we can return early since we know that no more features need to added\n      // for this image.\n      if (num_optimized_tracks >= min_num_optimized_tracks_per_view) {\n        return;\n      }\n    } else {\n      // If the track is not already set to be optimized then add it to the list\n      // of candidate tracks.\n      if (track_statistics.count(track_id) != 0) {\n        ranked_candidate_tracks.emplace_back(track_id,\n                                             track_statistics.at(track_id));\n      }\n    }\n  }\n\n  // We only reach this point if the number of optimized tracks is less than the\n  // minimum. If that is the case then we add the top candidate features until\n  // the minimum number of features observed is met.\n  if (num_optimized_tracks != num_estimated_tracks) {\n    // Select how many tracks to add. If we need more tracks than are estimated\n    // then we simply add all remaining features.\n    const int num_optimized_tracks_needed =\n        std::min(min_num_optimized_tracks_per_view, num_estimated_tracks) -\n        num_optimized_tracks;\n    std::partial_sort(\n        ranked_candidate_tracks.begin(),\n        ranked_candidate_tracks.begin() + num_optimized_tracks_needed,\n        ranked_candidate_tracks.end());\n    // Add the candidate tracks to the list of tracks to be optimized.\n    for (int i = 0; i < num_optimized_tracks_needed; i++) {\n      tracks_to_optimize->emplace(ranked_candidate_tracks[i].first);\n    }\n  }\n}\n\n}  // namespace\n\nnamespace DAGSfM {\n\n// The efficiency of large scale bundle adjustment can be dramatically increased\n// by choosing only a subset of 3d points to optimize, as the 3d points tend to\n// have increasing scene redundancy. If the points are chosen in a way that\n// Properly constraints the nonlinear optimization, similar results in quality\n// may be observed compared to optimized all tracks.\n//\n// The 3d points are chosen such that they fit the following criteria:\n//    a) High confidence (i.e. low reprojection error).\n//    b) Longer tracks are preferred.\n//    c) The tracks used for optimization provide a good spatial coverage in\n//    each image.\nbool SelectGoodTracksForBundleAdjustment(\n    const Reconstruction& reconstruction, const int long_track_length_threshold,\n    const int image_grid_cell_size_pixels,\n    const int min_num_optimized_tracks_per_view,\n    std::unordered_set<point3D_t>* tracks_to_optimize) {\n  // Get the registered image ids.\n  std::vector<image_t> vec_reg_image_ids = reconstruction.RegImageIds();\n  std::unordered_set<image_t> reg_image_ids(vec_reg_image_ids.begin(),\n                                            vec_reg_image_ids.end());\n\n  return SelectGoodTracksForBundleAdjustment(\n      reconstruction, reg_image_ids, long_track_length_threshold,\n      image_grid_cell_size_pixels, min_num_optimized_tracks_per_view,\n      tracks_to_optimize);\n}\n\nbool SelectGoodTracksForBundleAdjustment(\n    const Reconstruction& reconstruction,\n    const std::unordered_set<image_t>& image_ids,\n    const int long_track_length_threshold,\n    const int image_grid_cell_size_pixels,\n    const int min_num_optimized_tracks_per_view,\n    std::unordered_set<point3D_t>* tracks_to_optimize) {\n  // Compute the track mean reprojection errors.\n  std::unordered_map<point3D_t, TrackStatistics> track_statistics;\n  ComputeTrackStatistics(reconstruction, image_ids, long_track_length_threshold,\n                         &track_statistics);\n\n  // For each image, divide the image into a grid and choose the highest quality\n  // tracks from each grid cell. This encourages good spatial coverage of tracks\n  // within each image.\n  for (const image_t image_id : image_ids) {\n    const Image& image = reconstruction.Image(image_id);\n\n    // Select the best tracks from each grid cell in the image and add them to\n    // the container of tracks to be optimized.\n    SelectBestTracksFromEachImageGridCell(reconstruction, image,\n                                          image_grid_cell_size_pixels,\n                                          track_statistics, tracks_to_optimize);\n  }\n\n  // To this point, we have only added features that have as full spatial\n  // coverage as possible within each image but we have not ensured that\n  // each image is constrained by at least K features. So, we cycle through all\n  // images again and add the top M tracks that have not already been added.\n  for (const image_t image_id : image_ids) {\n    const Image& image = reconstruction.Image(image_id);\n\n    // If this view is not constrained by enough optimized tracks, add the top\n    // ranked features until there are enough tracks constraining the view.\n    SelectTopRankedTracksInView(reconstruction, track_statistics, image,\n                                min_num_optimized_tracks_per_view,\n                                tracks_to_optimize);\n  }\n\n  return true;\n}\n\n}  // namespace DAGSfM", "meta": {"hexsha": "41297523a3cb462e4d02e842555a55a516d24c09", "size": 13579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/base/track_selection.cpp", "max_stars_repo_name": "Yzhbuaa/DAGSfM", "max_stars_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 255.0, "max_stars_repo_stars_event_min_datetime": "2018-12-14T05:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T12:15:32.000Z", "max_issues_repo_path": "src/base/track_selection.cpp", "max_issues_repo_name": "Yzhbuaa/DAGSfM", "max_issues_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2018-12-25T03:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T03:33:25.000Z", "max_forks_repo_path": "src/base/track_selection.cpp", "max_forks_repo_name": "Yzhbuaa/DAGSfM", "max_forks_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2018-12-14T06:09:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T08:29:31.000Z", "avg_line_length": 42.5673981191, "max_line_length": 80, "alphanum_fraction": 0.7309080197, "num_tokens": 2993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.029312227571483274, "lm_q1q2_score": 0.012608576542757152}}
{"text": "// (C) Copyright 2007 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_DETAIL_GEODESIC_HPP\n#define BOOST_GRAPH_DETAIL_GEODESIC_HPP\n\n#include <functional>\n#include <boost/config.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/numeric_values.hpp>\n#include <boost/concept/assert.hpp>\n\n// TODO: Should this really be in detail?\n\nnamespace boost\n{\n// This is a very good discussion on centrality measures. While I can't\n// say that this has been the motivating factor for the design and\n// implementation of ths centrality framework, it does provide a single\n// point of reference for defining things like degree and closeness\n// centrality. Plus, the bibliography seems fairly complete.\n//\n//     @article{citeulike:1144245,\n//         author = {Borgatti, Stephen  P. and Everett, Martin  G.},\n//         citeulike-article-id = {1144245},\n//         doi = {10.1016/j.socnet.2005.11.005},\n//         journal = {Social Networks},\n//         month = {October},\n//         number = {4},\n//         pages = {466--484},\n//         priority = {0},\n//         title = {A Graph-theoretic perspective on centrality},\n//         url = {https://doi.org/10.1016/j.socnet.2005.11.005},\n//             volume = {28},\n//             year = {2006}\n//         }\n//     }\n\nnamespace detail {\n    // Note that this assumes T == property_traits<DistanceMap>::value_type\n    // and that the args and return of combine are also T.\n    template <typename Graph,\n                typename DistanceMap,\n                typename Combinator,\n                typename Distance>\n    inline Distance\n    combine_distances(const Graph& g,\n                        DistanceMap dist,\n                        Combinator combine,\n                        Distance init)\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(( ReadablePropertyMapConcept<DistanceMap,Vertex> ));\n        BOOST_CONCEPT_ASSERT(( NumericValueConcept<Distance> ));\n        typedef numeric_values<Distance> DistanceNumbers;\n        BOOST_CONCEPT_ASSERT(( AdaptableBinaryFunction<Combinator,Distance,Distance,Distance> ));\n\n        // If there's ever an infinite distance, then we simply return\n        // infinity. Note that this /will/ include the a non-zero\n        // distance-to-self in the combined values. However, this is usually\n        // zero, so it shouldn't be too problematic.\n        Distance ret = init;\n        VertexIterator i, end;\n        for(boost::tie(i, end) = vertices(g); i != end; ++i) {\n            Vertex v = *i;\n            if(get(dist, v) != DistanceNumbers::infinity()) {\n                ret = combine(ret, get(dist, v));\n            }\n            else {\n                ret = DistanceNumbers::infinity();\n                break;\n            }\n        }\n        return ret;\n    }\n\n    // Similar to std::plus<T>, but maximizes parameters\n    // rather than adding them.\n    template <typename T>\n    struct maximize\n    {\n        typedef T result_type;\n        typedef T first_argument_type;\n        typedef T second_argument_type;\n        T operator ()(T x, T y) const\n        { BOOST_USING_STD_MAX(); return max BOOST_PREVENT_MACRO_SUBSTITUTION (x, y); }\n    };\n\n    // Another helper, like maximize() to help abstract functional\n    // concepts. This is trivially instantiated for builtin numeric\n    // types, but should be specialized for those types that have\n    // discrete notions of reciprocals.\n    template <typename T>\n    struct reciprocal\n    {\n        typedef T result_type;\n        typedef T argument_type;\n        T operator ()(T t)\n        { return T(1) / t; }\n    };\n} /* namespace detail */\n\n// This type defines the basic facilities used for computing values\n// based on the geodesic distances between vertices. Examples include\n// closeness centrality and mean geodesic distance.\ntemplate <typename Graph, typename DistanceType, typename ResultType>\nstruct geodesic_measure\n{\n    typedef DistanceType distance_type;\n    typedef ResultType result_type;\n    typedef typename graph_traits<Graph>::vertices_size_type size_type;\n\n    typedef numeric_values<distance_type> distance_values;\n    typedef numeric_values<result_type> result_values;\n\n    static inline distance_type infinite_distance()\n    { return distance_values::infinity(); }\n\n    static inline result_type infinite_result()\n    { return result_values::infinity(); }\n\n    static inline result_type zero_result()\n    { return result_values::zero(); }\n};\n\n} /* namespace boost */\n\n#endif\n", "meta": {"hexsha": "b94482ccdb39000da7e0736ab26a6581f1fd73b7", "size": 4816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/detail/geodesic.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/detail/geodesic.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/detail/geodesic.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": 35.9402985075, "max_line_length": 97, "alphanum_fraction": 0.653654485, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368159568461, "lm_q2_score": 0.03210070671700818, "lm_q1q2_score": 0.012594289063315533}}
{"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/BoundingVolume.h\"\n#include \"Open3D/Geometry/PointCloud.h\"\n#include \"Open3D/Geometry/Qhull.h\"\n#include \"Open3D/Geometry/TriangleMesh.h\"\n#include \"Open3D/Utility/Console.h\"\n\n#include <numeric>\n\n#include <Eigen/Eigenvalues>\n\nnamespace open3d {\nnamespace geometry {\n\nOrientedBoundingBox& OrientedBoundingBox::Clear() {\n    center_.setZero();\n    x_axis_.setZero();\n    y_axis_.setZero();\n    z_axis_.setZero();\n    return *this;\n}\n\nbool OrientedBoundingBox::IsEmpty() const { return Volume() == 0; }\n\nEigen::Vector3d OrientedBoundingBox::GetMinBound() const {\n    auto points = GetBoxPoints();\n    return ComputeMinBound(points);\n}\n\nEigen::Vector3d OrientedBoundingBox::GetMaxBound() const {\n    auto points = GetBoxPoints();\n    return ComputeMaxBound(points);\n}\n\nEigen::Vector3d OrientedBoundingBox::GetCenter() const { return center_; }\n\nAxisAlignedBoundingBox OrientedBoundingBox::GetAxisAlignedBoundingBox() const {\n    return AxisAlignedBoundingBox::CreateFromPoints(GetBoxPoints());\n}\n\nOrientedBoundingBox OrientedBoundingBox::GetOrientedBoundingBox() const {\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Transform(\n        const Eigen::Matrix4d& transformation) {\n    Eigen::Vector4d c;\n    c << center_, 1;\n    Eigen::Vector4d x;\n    x << center_ + x_axis_, 1;\n    Eigen::Vector4d y;\n    y << center_ + y_axis_, 1;\n    Eigen::Vector4d z;\n    z << center_ + z_axis_, 1;\n    c = transformation * c;\n    x = transformation * x;\n    y = transformation * y;\n    z = transformation * z;\n    center_ = c.head<3>() / c(3);\n    x_axis_ = x.head<3>() / x(3) - center_;\n    y_axis_ = y.head<3>() / y(3) - center_;\n    z_axis_ = z.head<3>() / z(3) - center_;\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Translate(\n        const Eigen::Vector3d& translation, bool relative) {\n    if (relative) {\n        center_ += translation;\n    } else {\n        center_ = translation;\n    }\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Scale(const double scale,\n                                                bool center) {\n    if (center) {\n        x_axis_ *= scale;\n        y_axis_ *= scale;\n        z_axis_ *= scale;\n    } else {\n        Eigen::Vector3d x = scale * (center_ + x_axis_);\n        Eigen::Vector3d y = scale * (center_ + y_axis_);\n        Eigen::Vector3d z = scale * (center_ + z_axis_);\n        center_ *= scale;\n        x_axis_ = x - center_;\n        y_axis_ = y - center_;\n        z_axis_ = z - center_;\n    }\n    return *this;\n}\n\nOrientedBoundingBox& OrientedBoundingBox::Rotate(\n        const Eigen::Vector3d& rotation, bool center, RotationType type) {\n    const Eigen::Matrix3d R = GetRotationMatrix(rotation, type);\n    if (center) {\n        x_axis_ = R * x_axis_;\n        y_axis_ = R * y_axis_;\n        z_axis_ = R * z_axis_;\n    } else {\n        Eigen::Vector3d x = R * (center_ + x_axis_);\n        Eigen::Vector3d y = R * (center_ + y_axis_);\n        Eigen::Vector3d z = R * (center_ + z_axis_);\n        center_ = R * center_;\n        x_axis_ = x - center_;\n        y_axis_ = y - center_;\n        z_axis_ = z - center_;\n    }\n    return *this;\n}\n\ndouble OrientedBoundingBox::Volume() const {\n    return (2 * x_axis_.norm()) * (2 * y_axis_.norm()) * (2 * z_axis_.norm());\n}\n\nstd::vector<Eigen::Vector3d> OrientedBoundingBox::GetBoxPoints() const {\n    std::vector<Eigen::Vector3d> points(8);\n    points[0] = center_ - x_axis_ - y_axis_ - z_axis_;\n    points[1] = center_ + x_axis_ - y_axis_ - z_axis_;\n    points[2] = center_ - x_axis_ + y_axis_ - z_axis_;\n    points[3] = center_ - x_axis_ - y_axis_ + z_axis_;\n    points[4] = center_ + x_axis_ + y_axis_ + z_axis_;\n    points[5] = center_ - x_axis_ + y_axis_ + z_axis_;\n    points[6] = center_ + x_axis_ - y_axis_ + z_axis_;\n    points[7] = center_ + x_axis_ + y_axis_ - z_axis_;\n    return points;\n}\n\nOrientedBoundingBox OrientedBoundingBox::CreateFromAxisAlignedBoundingBox(\n        const AxisAlignedBoundingBox& aabox) {\n    Eigen::Vector3d half_extend = aabox.GetHalfExtend();\n    OrientedBoundingBox obox;\n    obox.center_ = aabox.GetCenter();\n    obox.x_axis_ << half_extend(0), 0, 0;\n    obox.y_axis_ << 0, half_extend(1), 0;\n    obox.z_axis_ << 0, 0, half_extend(2);\n    return obox;\n}\n\nOrientedBoundingBox OrientedBoundingBox::CreateFromPoints(\n        const std::vector<Eigen::Vector3d>& points) {\n    PointCloud hull_pcd;\n    hull_pcd.points_ = Qhull::ComputeConvexHull(points)->vertices_;\n\n    Eigen::Vector3d mean;\n    Eigen::Matrix3d cov;\n    std::tie(mean, cov) = hull_pcd.ComputeMeanAndCovariance();\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(cov);\n    Eigen::Vector3d evals = es.eigenvalues();\n    Eigen::Matrix3d R = es.eigenvectors();\n    R.col(0) /= R.col(0).norm();\n    R.col(1) /= R.col(1).norm();\n    R.col(2) /= R.col(2).norm();\n\n    if (evals(1) > evals(0)) {\n        std::swap(evals(1), evals(0));\n        Eigen::Vector3d tmp = R.col(1);\n        R.col(1) = R.col(0);\n        R.col(0) = tmp;\n    }\n    if (evals(2) > evals(0)) {\n        std::swap(evals(2), evals(0));\n        Eigen::Vector3d tmp = R.col(2);\n        R.col(2) = R.col(0);\n        R.col(0) = tmp;\n    }\n    if (evals(2) > evals(1)) {\n        std::swap(evals(2), evals(1));\n        Eigen::Vector3d tmp = R.col(2);\n        R.col(2) = R.col(1);\n        R.col(1) = tmp;\n    }\n\n    for (auto& pt : hull_pcd.points_) {\n        pt = R.transpose() * (pt - mean);\n    }\n    const auto aabox = hull_pcd.GetAxisAlignedBoundingBox();\n    const Eigen::Vector3d half_extend = aabox.GetHalfExtend();\n\n    OrientedBoundingBox obox;\n    obox.center_ = R * aabox.GetCenter() + mean;\n    obox.x_axis_ = R * Eigen::Vector3d(half_extend(0), 0, 0);\n    obox.y_axis_ = R * Eigen::Vector3d(0, half_extend(1), 0);\n    obox.z_axis_ = R * Eigen::Vector3d(0, 0, half_extend(2));\n\n    return obox;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Clear() {\n    min_bound_.setZero();\n    max_bound_.setZero();\n    return *this;\n}\n\nbool AxisAlignedBoundingBox::IsEmpty() const { return Volume() == 0; }\nEigen::Vector3d AxisAlignedBoundingBox::GetMinBound() const {\n    return min_bound_;\n}\n\nEigen::Vector3d AxisAlignedBoundingBox::GetMaxBound() const {\n    return max_bound_;\n}\n\nEigen::Vector3d AxisAlignedBoundingBox::GetCenter() const {\n    return (min_bound_ + max_bound_) * 0.5;\n}\n\nAxisAlignedBoundingBox AxisAlignedBoundingBox::GetAxisAlignedBoundingBox()\n        const {\n    return *this;\n}\n\nOrientedBoundingBox AxisAlignedBoundingBox::GetOrientedBoundingBox() const {\n    return OrientedBoundingBox::CreateFromAxisAlignedBoundingBox(*this);\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Transform(\n        const Eigen::Matrix4d& transformation) {\n    utility::LogWarning(\n            \"A general transform of a AxisAlignedBoundingBox would not be axis \"\n            \"aligned anymore, convert it to a OrientedBoundingBox first\\n\");\n    return *this;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Translate(\n        const Eigen::Vector3d& translation, bool relative) {\n    if (relative) {\n        min_bound_ += translation;\n        max_bound_ += translation;\n    } else {\n        const Eigen::Vector3d half_extend = GetHalfExtend();\n        min_bound_ = translation - half_extend;\n        max_bound_ = translation + half_extend;\n    }\n    return *this;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Scale(const double scale,\n                                                      bool center) {\n    if (center) {\n        Eigen::Vector3d center = GetCenter();\n        min_bound_ = center + scale * (min_bound_ - center);\n        max_bound_ = center + scale * (max_bound_ - center);\n    } else {\n        min_bound_ *= scale;\n        max_bound_ *= scale;\n    }\n    return *this;\n}\n\nAxisAlignedBoundingBox& AxisAlignedBoundingBox::Rotate(\n        const Eigen::Vector3d& rotation, bool center, RotationType type) {\n    utility::LogWarning(\n            \"A rotation of a AxisAlignedBoundingBox would not be axis aligned \"\n            \"anymore, convert it to a OrientedBoundingBox first\\n\");\n    return *this;\n}\n\nstd::string AxisAlignedBoundingBox::GetLogInfo() const {\n    return fmt::format(\"[({:.4f}, {:.4f}, {:.4f}) - ({:.4f}, {:.4f}, {:.4f})]\",\n                       min_bound_(0), min_bound_(1), min_bound_(2),\n                       max_bound_(0), max_bound_(1), max_bound_(2));\n}\n\nAxisAlignedBoundingBox AxisAlignedBoundingBox::CreateFromPoints(\n        const std::vector<Eigen::Vector3d>& points) {\n    AxisAlignedBoundingBox box;\n    if (points.empty()) {\n        box.min_bound_ = Eigen::Vector3d(0.0, 0.0, 0.0);\n        box.max_bound_ = Eigen::Vector3d(0.0, 0.0, 0.0);\n    } else {\n        box.min_bound_ = std::accumulate(\n                points.begin(), points.end(), points[0],\n                [](const Eigen::Vector3d& a, const Eigen::Vector3d& b) {\n                    return a.array().min(b.array()).matrix();\n                });\n        box.max_bound_ = std::accumulate(\n                points.begin(), points.end(), points[0],\n                [](const Eigen::Vector3d& a, const Eigen::Vector3d& b) {\n                    return a.array().max(b.array()).matrix();\n                });\n    }\n    return box;\n}\n\ndouble AxisAlignedBoundingBox::Volume() const { return GetExtend().prod(); }\n\nstd::vector<Eigen::Vector3d> AxisAlignedBoundingBox::GetBoxPoints() const {\n    std::vector<Eigen::Vector3d> points(8);\n    Eigen::Vector3d extend = GetExtend();\n    points[0] = min_bound_;\n    points[1] = min_bound_ + Eigen::Vector3d(extend(0), 0, 0);\n    points[2] = min_bound_ + Eigen::Vector3d(0, extend(1), 0);\n    points[3] = min_bound_ + Eigen::Vector3d(0, 0, extend(2));\n    points[4] = max_bound_;\n    points[5] = max_bound_ - Eigen::Vector3d(extend(0), 0, 0);\n    points[6] = max_bound_ - Eigen::Vector3d(0, extend(1), 0);\n    points[7] = max_bound_ - Eigen::Vector3d(0, 0, extend(2));\n    return points;\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "3eef95762ba140f1aa5974a6f04ac1453a4163ab", "size": 11353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Open3D/Geometry/BoundingVolume.cpp", "max_stars_repo_name": "devshank3/Open3D", "max_stars_repo_head_hexsha": "91611eb562680a41be8a52497bb45d278f2c9377", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-05-09T07:31:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T07:32:14.000Z", "max_issues_repo_path": "src/Open3D/Geometry/BoundingVolume.cpp", "max_issues_repo_name": "devshank3/Open3D", "max_issues_repo_head_hexsha": "91611eb562680a41be8a52497bb45d278f2c9377", "max_issues_repo_licenses": ["MIT"], "max_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/Geometry/BoundingVolume.cpp", "max_forks_repo_name": "devshank3/Open3D", "max_forks_repo_head_hexsha": "91611eb562680a41be8a52497bb45d278f2c9377", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T06:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T03:21:24.000Z", "avg_line_length": 34.2990936556, "max_line_length": 80, "alphanum_fraction": 0.6243283714, "num_tokens": 3031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.028007520200332342, "lm_q1q2_score": 0.012586373287652323}}
{"text": "#define lsafemathlib_cpp\n\n#include \"uvm/lprefix.h\"\n\n\n#include <stdlib.h>\n#include <math.h>\n\n#include <uvm/lua.h>\n\n#include <uvm/lauxlib.h>\n#include <uvm/lualib.h>\n#include <uvm/lobject.h>\n#include <boost/algorithm/hex.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <uvm/uvm_lutil.h>\n#include <safenumber/safenumber.h>\n//#include <boost/multiprecision/cpp_dec_float.hpp>\n//#include <boost/multiprecision/mpfi.hpp>\n//#include <boost/multiprecision/mpfr.hpp>\n\n// bigint stores as { hex: hex string, type: 'bigint' }\n// bignumber stores as { value: base10 string, type: 'bignumber' }\n// safenumber stores as {value: base10 string, type: 'safenumber' }\n\ntypedef boost::multiprecision::int512_t sm_bigint;\n//typedef boost::multiprecision::mpf_float sm_bigdecimal;\n\n\nstatic void push_bigint(lua_State *L, sm_bigint value) {\n\tauto hex_str = uvm::util::hex(value.str());\n\tlua_newtable(L);\n\tlua_pushstring(L, hex_str.c_str());\n\tlua_setfield(L, -2, \"hex\");\n\tlua_pushstring(L, \"bigint\");\n\tlua_setfield(L, -2, \"type\");\n}\n\n//static void push_bignumber(lua_State *L, sm_bigdecimal value) {\n//\tauto value_str = value.str();\n//\tlua_newtable(L);\n//\tlua_pushstring(L, value_str.c_str());\n//\tlua_setfield(L, -2, \"value\");\n//\tlua_pushstring(L, \"bignumber\");\n//\tlua_setfield(L, -2, \"type\");\n//}\n\nstatic int safemath_bigint(lua_State *L) {\n\tif (lua_gettop(L) < 1) {\n\t\tluaL_argcheck(L, false, 1, \"argument is empty\");\n\t\treturn 0;\n\t}\n\tif (lua_isinteger(L, 1)) {\n\t\tlua_Integer n = lua_tointeger(L, 1);\n\t\tstd::string value_hex;\n\t\ttry {\n\t\t\tvalue_hex = uvm::util::hex(std::to_string(n));\n\t\t}\n\t\tcatch (...) {\n\t\t\tlua_pushnil(L);\n\t\t\treturn 1;\n\t\t}\n\t\tlua_newtable(L);\n\t\tlua_pushstring(L, value_hex.c_str());\n\t\tlua_setfield(L, -2, \"hex\");\n\t\tlua_pushstring(L, \"bigint\");\n\t\tlua_setfield(L, -2, \"type\");\n\t\treturn 1;\n\t}\n\telse if (lua_isstring(L, 1)) {\n\t\tstd::string int_str = luaL_checkstring(L, 1);\n\t\tstd::string value_hex;\n\t\ttry {\n\t\t\tvalue_hex = uvm::util::hex(int_str);\n\t\t}\n\t\tcatch (const std::exception& e) {\n\t\t\tlua_pushnil(L);\n\t\t\treturn 1;\n\t\t}\n\t\tlua_newtable(L);\n\t\tlua_pushstring(L, value_hex.c_str());\n\t\tlua_setfield(L, -2, \"hex\");\n\t\tlua_pushstring(L, \"bigint\");\n\t\tlua_setfield(L, -2, \"type\");\n\t\treturn 1;\n\t}\n\telse {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be integer or hex string\");\n\t\treturn 0;\n\t}\n\treturn 1;\n}\n\n//static int safemath_bignumber(lua_State *L) {\n//\tif (lua_gettop(L) < 1) {\n//\t\tluaL_argcheck(L, false, 1, \"argument is empty\");\n//\t\treturn 0;\n//\t}\n//\tif (lua_isinteger(L, 1)) {\n//\t\tlua_Integer n = lua_tointeger(L, 1);\n//\t\tsm_bigdecimal sm_value(n);\n//\t\tpush_bignumber(L, sm_value);\n//\t\treturn 1;\n//\t}\n//\telse if (lua_type(L, 1) == LUA_TNUMBER || lua_type(L, 1) == LUA_TNUMFLT) {\n//\t\tlua_Number n = lua_tonumber(L, 1);\n//\t\tsm_bigdecimal sm_value(n);\n//\t\tpush_bignumber(L, sm_value);\n//\t\treturn 1;\n//\t}\n//\telse if (lua_isstring(L, 1)) {\n//\t\tstd::string value_str = luaL_checkstring(L, 1);\n//\t\ttry {\n//\t\t\tsm_bigdecimal sm_value(value_str);\n//\t\t\tpush_bignumber(L, sm_value);\n//\t\t\treturn 1;\n//\t\t}\n//\t\tcatch (const std::exception& e) {\n//\t\t\tluaL_error(L, \"invalid number string\");\n//\t\t\treturn 0;\n//\t\t}\n//\t}\n//\telse {\n//\t\tluaL_argcheck(L, false, 1, \"first argument must be number or hex string\");\n//\t\treturn 0;\n//\t}\n//\treturn 1;\n//}\n\n\nstatic bool is_valid_bigint_obj(lua_State *L, int index, std::string& out)\n{\n\tif ((index > 0 && lua_gettop(L) < index) || (index < 0 && lua_gettop(L) < -index) || index == 0) {\n\t\treturn false;\n\t}\n\tif (!lua_istable(L, index)) {\n\t\treturn false;\n\t}\n\tlua_getfield(L, index, \"type\");\n\tif (lua_isnil(L, -1) || !lua_isstring(L, -1) || strcmp(\"bigint\", luaL_checkstring(L, -1)) != 0) {\n\t\tlua_pop(L, 1);\n\t\treturn false;\n\t}\n\tlua_pop(L, 1);\n\tlua_getfield(L, index, \"hex\");\n\tif (lua_isnil(L, -1) || !lua_isstring(L, -1) || strlen(luaL_checkstring(L, -1)) < 1) {\n\t\tlua_pop(L, 1);\n\t\treturn false;\n\t}\n\tstd::string hex_str = luaL_checkstring(L, -1);\n\tlua_pop(L, 1);\n\ttry {\n\t\tboost::algorithm::hex(hex_str);\n\t\tout = hex_str;\n\t\treturn true;\n\t}\n\tcatch (...) {\n\t\treturn false;\n\t}\n}\n\n//static bool is_valid_bignumber_obj(lua_State *L, int index, std::string& out)\n//{\n//\tif ((index > 0 && lua_gettop(L) < index) || (index < 0 && lua_gettop(L) < -index) || index == 0) {\n//\t\treturn false;\n//\t}\n//\tif (!lua_istable(L, index)) {\n//\t\treturn false;\n//\t}\n//\tlua_getfield(L, index, \"type\");\n//\tif (lua_isnil(L, -1) || !lua_isstring(L, -1) || strcmp(\"bignumber\", luaL_checkstring(L, -1)) != 0) {\n//\t\tlua_pop(L, 1);\n//\t\treturn false;\n//\t}\n//\tlua_pop(L, 1);\n//\tlua_getfield(L, index, \"value\");\n//\tif (lua_isnil(L, -1) || !lua_isstring(L, -1) || strlen(luaL_checkstring(L, -1)) < 1) {\n//\t\tlua_pop(L, 1);\n//\t\treturn false;\n//\t}\n//\tstd::string value_str = luaL_checkstring(L, -1);\n//\tlua_pop(L, 1);\n//\ttry {\n//\t\tsm_bigdecimal(hex_str);\n//\t\tout = value_str;\n//\t\treturn true;\n//\t}\n//\tcatch (const std::exception& e) {\n//\t\treturn false;\n//\t}\n//}\n\nstatic bool is_same_direction_safe_int(sm_bigint a, sm_bigint b)\n{\n\treturn (a > 0 && b > 0) || (a < 0 && b < 0);\n}\n\nstatic bool is_same_direction_int1024(boost::multiprecision::int1024_t a, boost::multiprecision::int1024_t b)\n{\n\treturn (a > 0 && b > 0) || (a < 0 && b < 0);\n}\n\nstatic int safemath_add(lua_State *L) {\n\tif (lua_gettop(L) < 2) {\n\t\tluaL_error(L, \"add need at least 2 argument\");\n\t}\n\tstd::string first_hex_str;\n\tstd::string second_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint obj\");\n\t}\n\tif (!is_valid_bigint_obj(L, 2, second_hex_str)) {\n\t\tluaL_argcheck(L, false, 2, \"invalid bigint obj\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint first_int(first_int_str);\n\tauto second_int_str = uvm::util::unhex(second_hex_str);\n\tsm_bigint second_int(second_int_str);\n\tauto result_int = first_int + second_int;\n\t// overflow check\n\tif (is_same_direction_safe_int(first_int, second_int)) {\n\t\tif ((first_int > 0 && result_int <= 0) || (first_int<0 && result_int >= 0)) {\n\t\t\tluaL_error(L, \"int512 overflow\");\n\t\t}\n\t}\n\tpush_bigint(L, result_int);\n\treturn 1;\n}\n\n//static int safemath_add(lua_State *L) {\n//\tif (lua_gettop(L) < 2) {\n//\t\tluaL_error(L, \"add need at least 2 argument\");\n//\t}\n//\tstd::string first_value_str;\n//\tstd::string second_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber obj\");\n//\t}\n//\tif (!is_valid_bignumber_obj(L, 2, second_value_str)) {\n//\t\tluaL_argcheck(L, false, 2, \"invalid bignumber obj\");\n//\t}\n//\tsm_bigdecimal first_value(first_value_str);\n//\tsm_bigdecimal second_value(second_value_str);\n//\tauto result_value = first_value + second_value;\n//\tpush_bignumber(L, result_value);\n//\treturn 1;\n//}\n\nstatic int safemath_mul(lua_State *L) {\n\tif (lua_gettop(L) < 2) {\n\t\tluaL_error(L, \"mul need at least 2 argument\");\n\t}\n\tstd::string first_hex_str;\n\tstd::string second_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint obj\");\n\t}\n\tif (!is_valid_bigint_obj(L, 2, second_hex_str)) {\n\t\tluaL_argcheck(L, false, 2, \"invalid bigint obj\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint first_int(first_int_str);\n\tauto second_int_str = uvm::util::unhex(second_hex_str);\n\tsm_bigint second_int(second_int_str);\n\tauto result_int = boost::multiprecision::int512_t(first_int) * boost::multiprecision::int512_t(second_int);\n\t// overflow check\n\tsm_bigint int512_max(\"13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095\");\n\tsm_bigint int512_min(\"-6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042048\");\n\tif (is_same_direction_safe_int(first_int, second_int) && result_int > int512_max) {\n\t\tluaL_error(L, \"int512 overflow\");\n\t}\n\telse if (is_same_direction_safe_int(first_int, second_int) && result_int < int512_min) {\n\t\tluaL_error(L, \"int512 overflow\");\n\t}\n\tpush_bigint(L, result_int.convert_to<sm_bigint>());\n\treturn 1;\n}\n\n//static int safemath_mul(lua_State *L) {\n//\tif (lua_gettop(L) < 2) {\n//\t\tluaL_error(L, \"mul need at least 2 argument\");\n//\t}\n//\tstd::string first_value_str;\n//\tstd::string second_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber obj\");\n//\t}\n//\tif (!is_valid_bignumber_obj(L, 2, second_value_str)) {\n//\t\tluaL_argcheck(L, false, 2, \"invalid bignumber obj\");\n//\t}\n//\tsm_bigdecimal first_value(first_value_str);\n//\tsm_bigdecimal second_value(second_value_str);\n//\tauto result_value = first_value * second_value;\n//\tpush_bignumber(L, result_value);\n//\treturn 1;\n//}\n\nstatic sm_bigint int512_pow(lua_State *L, sm_bigint value, sm_bigint n) {\n\tif (n > 100) {\n\t\tluaL_error(L, \"too large value in bigint pow\");\n\t}\n\tboost::multiprecision::int1024_t result(value);\n\tsm_bigint int512_max(\"13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095\");\n\tsm_bigint int512_min(\"-6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042048\");\n\tfor (int i = 1; i < n; i++) {\n\t\tauto mid_value = result * value;\n\t\t// overflow check\n\t\tif (is_same_direction_int1024(result, value) && mid_value > int512_max) {\n\t\t\tluaL_error(L, \"int512 overflow\");\n\t\t}\n\t\telse if(!is_same_direction_int1024(result, value) && mid_value < int512_min) {\n\t\t\tluaL_error(L, \"int512 overflow\");\n\t\t}\n\t\tresult = mid_value;\n\t}\n\treturn result.convert_to<boost::multiprecision::int512_t>();\n}\n\n//static sm_bigdecimal bignumber_pow(lua_State *L, sm_bigdecimal value, sm_bigdecimal n) {\n//\tif (n > 100) {\n//\t\tluaL_error(L, \"too large value in bignumber pow\");\n//\t}\n//\tsm_bigdecimal result(value);\n//\tfor (int i = 1; i < n; i++) {\n//\t\tauto mid_value = result * value;\n//\t\tresult = mid_value;\n//\t}\n//\treturn result;\n//}\n\nstatic int safemath_pow(lua_State *L) {\n\tif (lua_gettop(L) < 2) {\n\t\tluaL_error(L, \"pow need at least 2 argument\");\n\t}\n\tstd::string first_hex_str;\n\tstd::string second_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint obj\");\n\t}\n\tif (!is_valid_bigint_obj(L, 2, second_hex_str)) {\n\t\tluaL_argcheck(L, false, 2, \"invalid bigint obj\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint first_int(first_int_str);\n\tauto second_int_str = uvm::util::unhex(second_hex_str);\n\tsm_bigint second_int(second_int_str);\n\tauto result_int = int512_pow(L, first_int, second_int);\n\t// overflow check\n\tif (result_int <= 0) {\n\t\tluaL_error(L, \"int512 overflow\");\n\t}\n\tpush_bigint(L, result_int);\n\treturn 1;\n}\n\nenum compare_type {\n\tGT,\n\tGE,\n\tLT,\n\tLE,\n\tEQ,\n\tNE\n};\n\nstatic int _safemath_compare(lua_State* L, compare_type type) {\n\tif (lua_gettop(L) < 2) {\n\t\tluaL_error(L, \"pow need at least 2 argument\");\n\t}\n\tstd::string first_hex_str;\n\tstd::string second_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint obj\");\n\t}\n\tif (!is_valid_bigint_obj(L, 2, second_hex_str)) {\n\t\tluaL_argcheck(L, false, 2, \"invalid bigint obj\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint first_int(first_int_str);\n\tauto second_int_str = uvm::util::unhex(second_hex_str);\n\tsm_bigint second_int(second_int_str);\n\tbool result = false;\n\tif ( (type==compare_type::GT && first_int > second_int)\n\t\t|| (type == compare_type::GE && first_int >= second_int)\n\t\t|| (type == compare_type::LT && first_int < second_int)\n\t\t|| (type == compare_type::LE && first_int <= second_int)\n\t\t|| (type == compare_type::EQ && first_int == second_int)\n\t\t|| (type == compare_type::NE && first_int != second_int)\n\t\t){\n\t\tresult = true;\n\t}\n\telse {\n\t\tresult = false;\n\t}\n\tlua_pushboolean(L, result);\n\treturn 1;\n}\n\nstatic int safemath_gt(lua_State* L) {\n\treturn _safemath_compare(L, compare_type::GT);\n}\nstatic int safemath_ge(lua_State* L) {\n\treturn _safemath_compare(L, compare_type::GE);\n}\nstatic int safemath_lt(lua_State* L) {\n\treturn _safemath_compare(L, compare_type::LT);\n}\nstatic int safemath_le(lua_State* L) {\n\treturn _safemath_compare(L, compare_type::LE);\n}\nstatic int safemath_eq(lua_State* L) {\n\treturn _safemath_compare(L, compare_type::EQ);\n}\nstatic int safemath_ne(lua_State* L) {\n\treturn _safemath_compare(L, compare_type::NE);\n}\n\n//static int safemath_pow(lua_State *L) {\n//\tif (lua_gettop(L) < 2) {\n//\t\tluaL_error(L, \"pow need at least 2 argument\");\n//\t}\n//\tstd::string first_value_str;\n//\tstd::string second_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber obj\");\n//\t}\n//\tif (!is_valid_bignumber_obj(L, 2, second_value_str)) {\n//\t\tluaL_argcheck(L, false, 2, \"invalid bignumber obj\");\n//\t}\n//\tsm_bigdecimal first_value(first_value_str);\n//\tsm_bigdecimal second_value(second_value_str);\n//\tauto result_value = bignumber_pow(L, first_value, second_value);\n//\tpush_bignumber(L, result_value);\n//\treturn 1;\n//}\n\nstatic int safemath_div(lua_State *L) {\n\tif (lua_gettop(L) < 2) {\n\t\tluaL_error(L, \"div need at least 2 argument\");\n\t}\n\tstd::string first_hex_str;\n\tstd::string second_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint obj\");\n\t}\n\tif (!is_valid_bigint_obj(L, 2, second_hex_str)) {\n\t\tluaL_argcheck(L, false, 2, \"invalid bigint obj\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint first_int(first_int_str);\n\tauto second_int_str = uvm::util::unhex(second_hex_str);\n\tsm_bigint second_int(second_int_str);\n\tif (second_int.is_zero()) {\n\t\tluaL_error(L, \"div by 0 error\");\n\t}\n\tsm_bigint result_int;\n\ttry {\n\t\tresult_int = first_int / second_int;\n\t}\n\tcatch (...) {\n\t\tluaL_error(L, \"bigint divide error\");\n\t\treturn 0;\n\t}\n\t// overflow check\n\tif (is_same_direction_safe_int(first_int, second_int)) {\n\t\tif ((first_int > 0 && result_int < 0) || (first_int<0 && result_int > 0)) {\n\t\t\tluaL_error(L, \"int512 overflow\");\n\t\t}\n\t}\n\tpush_bigint(L, result_int);\n\treturn 1;\n}\n\n//static int safemath_div(lua_State *L) {\n//\tif (lua_gettop(L) < 2) {\n//\t\tluaL_error(L, \"div need at least 2 argument\");\n//\t}\n//\tstd::string first_value_str;\n//\tstd::string second_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber obj\");\n//\t}\n//\tif (!is_valid_bignumber_obj(L, 2, second_value_str)) {\n//\t\tluaL_argcheck(L, false, 2, \"invalid bignumber obj\");\n//\t}\n//\tsm_bigdecimal first_value(first_value_str);\n//\tsm_bigdecimal second_value(second_value_str);\n//\tif (second_value.is_zero()) {\n//\t\tluaL_error(L, \"div by 0 error\");\n//\t}\n//\tsm_bigdecimal result_value;\n//\ttry {\n//\t\tresult_value = first_value / second_value;\n//\t}\n//\tcatch (const std::exception& e) {\n//\t\tluaL_error(L, \"bignumber divid by zero error\");\n//\t}\n//\tpush_bignumber(L, result_value);\n//\treturn 1;\n//}\n\nstatic int safemath_rem(lua_State *L) {\n\tif (lua_gettop(L) < 2) {\n\t\tluaL_error(L, \"rem need at least 2 argument\");\n\t}\n\tstd::string first_hex_str;\n\tstd::string second_hex_str;\n\tstd::string first_int_str;\n\tstd::string second_int_str;\n\tsm_bigint first_int;\n\tsm_bigint second_int;\n\ttry {\n\t\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\t\tluaL_argcheck(L, false, 1, \"invalid bigint obj\");\n\t\t\treturn 0;\n\t\t}\n\t\tif (!is_valid_bigint_obj(L, 2, second_hex_str)) {\n\t\t\tluaL_argcheck(L, false, 2, \"invalid bigint obj\");\n\t\t\treturn 0;\n\t\t}\n\t\tfirst_int_str = uvm::util::unhex(first_hex_str);\n\t\tfirst_int = sm_bigint(first_int_str);\n\t\tauto second_int_str = uvm::util::unhex(second_hex_str);\n\t\tsecond_int = sm_bigint(second_int_str);\n\t\tif (second_int == 0) {\n\t\t\tluaL_error(L, \"rem by 0 error\");\n\t\t}\n\t\tauto result_int = first_int % second_int;\n\t\t// overflow check\n\t\tif (is_same_direction_safe_int(first_int, second_int)) {\n\t\t\tif ((first_int > 0 && result_int < 0) || (first_int < 0 && result_int > 0)) {\n\t\t\t\tluaL_error(L, \"int512 overflow\");\n\t\t\t}\n\t\t}\n\t\tpush_bigint(L, result_int);\n\t\treturn 1;\n\t}\n\tcatch (...) {\n\t\treturn 0;\n\t}\n}\n\n//static int safemath_rem(lua_State *L) {\n//\tif (lua_gettop(L) < 2) {\n//\t\tluaL_error(L, \"rem need at least 2 argument\");\n//\t}\n//\tstd::string first_value_str;\n//\tstd::string second_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber obj\");\n//\t}\n//\tif (!is_valid_bignumber_obj(L, 2, second_value_str)) {\n//\t\tluaL_argcheck(L, false, 2, \"invalid bignumber obj\");\n//\t}\n//\tsm_bigdecimal first_value(first_value_str);\n//\tsm_bigdecimal second_value(second_value_str);\n//\tif (second_value == 0) {\n//\t\tluaL_error(L, \"rem by 0 error\");\n//\t}\n//\tauto result_int = first_value.convert_to<sm_bigint>() % second_value.convert_to<sm_bigint>();\n//\tsm_bigdecimal result_value(result_int);\n//\tpush_bignumber(L, result_value);\n//\treturn 1;\n//}\n\nstatic int safemath_sub(lua_State *L) {\n\tif (lua_gettop(L) < 2) {\n\t\tluaL_error(L, \"sub need at least 2 argument\");\n\t}\n\tstd::string first_hex_str;\n\tstd::string second_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint obj\");\n\t}\n\tif (!is_valid_bigint_obj(L, 2, second_hex_str)) {\n\t\tluaL_argcheck(L, false, 2, \"invalid bigint obj\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint first_int(first_int_str);\n\tauto second_int_str = uvm::util::unhex(second_hex_str);\n\tsm_bigint second_int(second_int_str);\n\tauto result_int = first_int - second_int;\n\t// overflow check\n\tif (!is_same_direction_safe_int(first_int, second_int)) {\n\t\tif ((first_int > 0 && result_int <= 0) || (first_int<0 && result_int >= 0)) {\n\t\t\tluaL_error(L, \"int512 overflow\");\n\t\t}\n\t}\n\tpush_bigint(L, result_int);\n\treturn 1;\n}\n\n//static int safemath_sub(lua_State *L) {\n//\tif (lua_gettop(L) < 2) {\n//\t\tluaL_error(L, \"sub need at least 2 argument\");\n//\t}\n//\tstd::string first_value_str;\n//\tstd::string second_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber obj\");\n//\t}\n//\tif (!is_valid_bignumber_obj(L, 2, second_value_str)) {\n//\t\tluaL_argcheck(L, false, 2, \"invalid bignumber obj\");\n//\t}\n//\tsm_bigdecimal first_value(first_value_str);\n//\tsm_bigdecimal second_value(second_value_str);\n//\tauto result_value = first_value - second_value;\n//\tpush_bignumber(L, result_value);\n//\treturn 1;\n//}\n\nstatic int safemath_toint(lua_State* L) {\n\tstd::string hex_str;\n\tif (!is_valid_bigint_obj(L, 1, hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint object\");\n\t\treturn 0;\n\t}\n\ttry {\n\t\tauto value_str = uvm::util::unhex(hex_str);\n\t\tsm_bigint bigint_value(value_str);\n\t\tauto value = bigint_value.convert_to<lua_Integer>();\n\t\tlua_pushinteger(L, value);\n\t\treturn 1;\n\t}\n\tcatch (...) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint object\");\n\t\treturn 0;\n\t}\n}\n\n//static int safemath_toint(lua_State* L) {\n//\tstd::string value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber object\");\n//\t}\n//\tsm_bigdecimal big_value(value_str);\n//\tauto value = big_value.convert_to<lua_Integer>();\n//\tlua_pushinteger(L, value);\n//\treturn 1;\n//}\n\nstatic int safemath_tohex(lua_State* L) {\n\tstd::string hex_str;\n\tif (!is_valid_bigint_obj(L, 1, hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"invalid bigint object\");\n\t}\n\tlua_pushstring(L, hex_str.c_str());\n\treturn 1;\n}\n\n//static int safemath_tohex(lua_State* L) {\n//\tstd::string value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"invalid bignumber object\");\n//\t}\n//\tlua_pushstring(L, value_str.c_str());\n//\treturn 1;\n//}\n\nstatic int safemath_tostring(lua_State* L) {\n\tstd::string hex_str;\n\tif (is_valid_bigint_obj(L, 1, hex_str)) {\n\t\tauto value_str = uvm::util::unhex(hex_str);\n\t\tsm_bigint bigint_value(value_str);\n\t\tauto bigint_value_str = bigint_value.str();\n\t\tlua_pushstring(L, bigint_value_str.c_str());\n\t\treturn 1;\n\t}\n\t/*else if (is_valid_bignumber_obj(L, 1, hex_str)) {\n\t\tauto value_str = hex_str;\n\t\tlua_pushstring(L, value_str.c_str());\n\t\treturn 1;\n\t}*/\n\telse {\n\t\tluaL_error(L, \"invalid bignumber value\");\n\t\treturn 0;\n\t}\n}\n\nstatic int safemath_min(lua_State *L) {\n\tint n = lua_gettop(L);  /* number of arguments */\n\tint imin = 1;  /* index of current minimum value */\n\tstd::string first_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"bigint value expected\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint min_value(first_int_str);\n\tluaL_argcheck(L, n >= 1, 1, \"value expected\");\n\tfor (int i = 2; i <= n; i++) {\n\t\tstd::string hex_value;\n\t\tif (!is_valid_bigint_obj(L, i, hex_value)) {\n\t\t\tluaL_argcheck(L, false, i, \"bigint value expected\");\n\t\t}\n\t\tauto int_str = uvm::util::unhex(hex_value);\n\t\tsm_bigint int_value(int_str);\n\t\tif (int_value < min_value) {\n\t\t\timin = i;\n\t\t\tmin_value = int_value;\n\t\t}\n\t}\n\tlua_pushvalue(L, imin);\n\treturn 1;\n}\n\n//static int safemath_min(lua_State *L) {\n//\tint n = lua_gettop(L);  /* number of arguments */\n//\tint imin = 1;  /* index of current minimum value */\n//\tstd::string first_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"bignumber value expected\");\n//\t}\n//\tsm_bigdecimal min_value(first_value_str);\n//\tluaL_argcheck(L, n >= 1, 1, \"value expected\");\n//\tfor (int i = 2; i <= n; i++) {\n//\t\tstd::string value_str;\n//\t\tif (!is_valid_bignumber_obj(L, i, value_str)) {\n//\t\t\tluaL_argcheck(L, false, i, \"bignumber value expected\");\n//\t\t}\n//\t\tsm_bigdecimal big_value(value_str);\n//\t\tif (big_value < min_value) {\n//\t\t\timin = i;\n//\t\t\tmin_value = big_value;\n//\t\t}\n//\t}\n//\tlua_pushvalue(L, imin);\n//\treturn 1;\n//}\n\n\nstatic int safemath_max(lua_State *L) {\n\tint n = lua_gettop(L);  /* number of arguments */\n\tint imax = 1;  /* index of current max value */\n\tstd::string first_hex_str;\n\tif (!is_valid_bigint_obj(L, 1, first_hex_str)) {\n\t\tluaL_argcheck(L, false, 1, \"bigint value expected\");\n\t}\n\tauto first_int_str = uvm::util::unhex(first_hex_str);\n\tsm_bigint max_value(first_int_str);\n\tluaL_argcheck(L, n >= 1, 1, \"value expected\");\n\tfor (int i = 2; i <= n; i++) {\n\t\tstd::string hex_value;\n\t\tif (!is_valid_bigint_obj(L, i, hex_value)) {\n\t\t\tluaL_argcheck(L, false, i, \"bigint value expected\");\n\t\t}\n\t\tauto int_str = uvm::util::unhex(hex_value);\n\t\tsm_bigint int_value(int_str);\n\t\tif (int_value > max_value) {\n\t\t\timax = i;\n\t\t\tmax_value = int_value;\n\t\t}\n\t}\n\tlua_pushvalue(L, imax);\n\treturn 1;\n}\n\n//static int safemath_max(lua_State *L) {\n//\tint n = lua_gettop(L);  /* number of arguments */\n//\tint imax = 1;  /* index of current max value */\n//\tstd::string first_value_str;\n//\tif (!is_valid_bignumber_obj(L, 1, first_value_str)) {\n//\t\tluaL_argcheck(L, false, 1, \"bignumber value expected\");\n//\t}\n//\tsm_bigdecimal max_value(first_value_str);\n//\tluaL_argcheck(L, n >= 1, 1, \"value expected\");\n//\tfor (int i = 2; i <= n; i++) {\n//\t\tstd::string value_str;\n//\t\tif (!is_valid_bignumber_obj(L, i, value_str)) {\n//\t\t\tluaL_argcheck(L, false, i, \"bignumber value expected\");\n//\t\t}\n//\t\tsm_bigdecimal big_value(value_str);\n//\t\tif (big_value > max_value) {\n//\t\t\timax = i;\n//\t\t\tmax_value = big_value;\n//\t\t}\n//\t}\n//\tlua_pushvalue(L, imax);\n//\treturn 1;\n//}\n\nstatic void push_safenumber(lua_State *L, const SafeNumber& value) {\n\tconst auto& value_str = std::to_string(value);\n\tlua_newtable(L);\n\tlua_pushstring(L, value_str.c_str());\n\tlua_setfield(L, -2, \"value\");\n\tlua_pushstring(L, \"safenumber\");\n\tlua_setfield(L, -2, \"type\");\n}\n\nstatic int safemath_safe_number_create(lua_State *L) {\n\tif (lua_gettop(L) < 1) {\n\t\tluaL_argcheck(L, false, 1, \"argument is empty\");\n\t\treturn 0;\n\t}\n\tstd::string value_str;\n\tif (lua_isinteger(L, 1)) {\n\t\tlua_Integer n = lua_tointeger(L, 1);\n\t\tstd::string value_str;\n\t\tvalue_str = std::to_string(n);\n\t}\n\telse if (lua_isstring(L, 1)) {\n\t\tstd::string int_str = luaL_checkstring(L, 1);\n\t\tvalue_str = int_str;\n\t}\n\telse {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be integer or base10 string\");\n\t\treturn 0;\n\t}\n\tSafeNumber sn_value;\n\ttry {\n\t\tsn_value = safe_number_create(value_str);\n\t}\n\tcatch (const std::exception& e) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, sn_value);\n\treturn 1;\n}\n\nstatic bool is_valid_safe_number(lua_State *L, int index, SafeNumber& sn_value) {\n\tif ((index > 0 && lua_gettop(L) < index) || (index < 0 && lua_gettop(L) < -index) || index == 0) {\n\t\treturn false;\n\t}\n\tif (!lua_istable(L, index)) {\n\t\treturn false;\n\t}\n\tlua_getfield(L, index, \"type\");\n\tif (lua_isnil(L, -1) || !lua_isstring(L, -1) || strcmp(\"safenumber\", luaL_checkstring(L, -1)) != 0) {\n\t\tlua_pop(L, 1);\n\t\treturn false;\n\t}\n\tlua_pop(L, 1);\n\tlua_getfield(L, index, \"value\");\n\tif (lua_isnil(L, -1) || !lua_isstring(L, -1) || strlen(luaL_checkstring(L, -1)) < 1) {\n\t\tlua_pop(L, 1);\n\t\treturn false;\n\t}\n\tstd::string value_str = luaL_checkstring(L, -1);\n\tlua_pop(L, 1);\n\ttry {\n\t\tsn_value = safe_number_create(value_str);\n\t\treturn true;\n\t}\n\tcatch (...) {\n\t\treturn false;\n\t}\n}\n\nstatic int safemath_safe_number_gt(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (!is_valid_safe_number(L, 2, b)) {\n\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tbool result;\n\ttry {\n\t\tresult = safe_number_gt(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushboolean(L, false);\n\t\treturn 1;\n\t}\n\tlua_pushboolean(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_gte(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (!is_valid_safe_number(L, 2, b)) {\n\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tbool result;\n\ttry {\n\t\tresult = safe_number_gte(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushboolean(L, false);\n\t\treturn 1;\n\t}\n\tlua_pushboolean(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_lt(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (!is_valid_safe_number(L, 2, b)) {\n\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tbool result;\n\ttry {\n\t\tresult = safe_number_lt(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushboolean(L, false);\n\t\treturn 1;\n\t}\n\tlua_pushboolean(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_lte(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (!is_valid_safe_number(L, 2, b)) {\n\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tbool result;\n\ttry {\n\t\tresult = safe_number_lte(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushboolean(L, false);\n\t\treturn 1;\n\t}\n\tlua_pushboolean(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_eq(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (!is_valid_safe_number(L, 2, b)) {\n\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tbool result;\n\ttry {\n\t\tresult = safe_number_eq(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushboolean(L, false);\n\t\treturn 1;\n\t}\n\tlua_pushboolean(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_ne(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (!is_valid_safe_number(L, 2, b)) {\n\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tbool result;\n\ttry {\n\t\tresult = safe_number_ne(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushboolean(L, false);\n\t\treturn 1;\n\t}\n\tlua_pushboolean(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_add(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (lua_isinteger(L, 2)) {\n\t\ttry {\n\t\t\tb = safe_number_create(luaL_checkinteger(L, 2));\n\t\t}\n\t\tcatch (...) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tif (!is_valid_safe_number(L, 2, b)) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_add(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_minus(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (lua_isinteger(L, 2)) {\n\t\ttry {\n\t\t\tb = safe_number_create(luaL_checkinteger(L, 2));\n\t\t}\n\t\tcatch (...) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tif (!is_valid_safe_number(L, 2, b)) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_minus(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_neg(lua_State *L) {\n\tSafeNumber a{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_neg(a);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_multiply(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (lua_isinteger(L, 2)) {\n\t\ttry {\n\t\t\tb = safe_number_create(luaL_checkinteger(L, 2));\n\t\t}\n\t\tcatch (...) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tif (!is_valid_safe_number(L, 2, b)) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_multiply(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_mod(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (lua_isinteger(L, 2)) {\n\t\ttry {\n\t\t\tb = safe_number_create(luaL_checkinteger(L, 2));\n\t\t}\n\t\tcatch (...) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tif (!is_valid_safe_number(L, 2, b)) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_mod(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_abs(lua_State *L) {\n\tSafeNumber a{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_abs(a);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_div(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (lua_isinteger(L, 2)) {\n\t\ttry {\n\t\t\tb = safe_number_create(luaL_checkinteger(L, 2));\n\t\t}\n\t\tcatch (...) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tif (!is_valid_safe_number(L, 2, b)) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_div(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_idiv(lua_State *L) {\n\tSafeNumber a{};\n\tSafeNumber b{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tif (lua_isinteger(L, 2)) {\n\t\ttry {\n\t\t\tb = safe_number_create(luaL_checkinteger(L, 2));\n\t\t}\n\t\tcatch (...) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tif (!is_valid_safe_number(L, 2, b)) {\n\t\t\tluaL_argcheck(L, false, 2, \"second argument must be SafeNumber/integer value\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tSafeNumber result{};\n\ttry {\n\t\tresult = safe_number_idiv(a, b);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tpush_safenumber(L, result);\n\treturn 1;\n}\n\nstatic int safemath_safe_number_to_string(lua_State *L) {\n\tSafeNumber a{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tstd::string result;\n\ttry {\n\t\tresult = std::to_string(a);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tlua_pushstring(L, result.c_str());\n\treturn 1;\n}\n\nstatic int safemath_safe_number_to_int64(lua_State *L) {\n\tSafeNumber a{};\n\tif (!is_valid_safe_number(L, 1, a)) {\n\t\tluaL_argcheck(L, false, 1, \"first argument must be SafeNumber value\");\n\t\treturn 0;\n\t}\n\tlua_Integer result;\n\ttry {\n\t\tresult = safe_number_to_int64(a);\n\t}\n\tcatch (...) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\tlua_pushinteger(L, result);\n\treturn 1;\n}\n\nstatic const luaL_Reg safemathlib[] = {\n\t{ \"bigint\", safemath_bigint },\n\t/*{ \"bignumber\", safemath_bignumber },\n\t{ \"iadd\", safemath_iadd },\n\t{ \"isub\", safemath_isub },\n\t{ \"imul\", safemath_imul },\n\t{ \"imin\", safemath_imin },\n\t{ \"imax\", safemath_imax },\n\t{ \"idiv\", safemath_idiv },\n\t{ \"irem\", safemath_irem },\n\t{ \"ipow\", safemath_ipow },\n\t{ \"itoint\", safemath_itoint },\n\t{ \"itohex\", safemath_itohex },*/\n\t{ \"add\", safemath_add },\n\t{ \"sub\", safemath_sub },\n\t{ \"mul\", safemath_mul },\n\t{ \"min\", safemath_min },\n\t{ \"max\", safemath_max },\n\t{ \"div\", safemath_div },\n\t{ \"rem\", safemath_rem },\n\t{ \"pow\", safemath_pow },\n\t{ \"gt\", safemath_gt },\n\t{ \"ge\", safemath_ge },\n\t{ \"lt\", safemath_lt },\n\t{ \"le\", safemath_le },\n\t{ \"eq\", safemath_eq },\n\t{ \"ne\", safemath_ne },\n\t{ \"toint\", safemath_toint },\n\t{ \"tohex\", safemath_tohex },\n\t{ \"tostring\", safemath_tostring },\n\n\t{ \"safenumber\", safemath_safe_number_create },\n\t{ \"number_add\", safemath_safe_number_add },\n\t{ \"number_minus\", safemath_safe_number_minus },\n\t{ \"number_multiply\", safemath_safe_number_multiply },\n\t{ \"number_div\", safemath_safe_number_div },\n\t{ \"number_idiv\", safemath_safe_number_idiv },\n\t{ \"number_abs\", safemath_safe_number_abs },\n\t{ \"number_neg\", safemath_safe_number_neg },\n\t{ \"number_gt\", safemath_safe_number_gt },\n\t{ \"number_gte\", safemath_safe_number_gte },\n\t{ \"number_lt\", safemath_safe_number_lt },\n\t{ \"number_lte\", safemath_safe_number_lte },\n\t{ \"number_eq\", safemath_safe_number_eq },\n\t{ \"number_ne\", safemath_safe_number_ne },\n\t{ \"number_tostring\", safemath_safe_number_to_string },\n\t{ \"number_toint\", safemath_safe_number_to_int64 },\n\t{ \"number_mod\", safemath_safe_number_mod },\n\n\t{ nullptr, nullptr }\n};\n\n\n/*\n** Open math library\n*/\nLUAMOD_API int luaopen_safemath(lua_State *L) {\n\tluaL_newlib(L, safemathlib);\n\treturn 1;\n}\n\n", "meta": {"hexsha": "0913b2f87e325ca31b7b76f6d7e1b6bc1dd4bd17", "size": 35402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/uvm/src/uvm/lsafemathlib.cpp", "max_stars_repo_name": "JWOCC/core", "max_stars_repo_head_hexsha": "590c3cc7156a37494a501bb3852fbdb17fc56655", "max_stars_repo_licenses": ["MIT"], "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/uvm/src/uvm/lsafemathlib.cpp", "max_issues_repo_name": "JWOCC/core", "max_issues_repo_head_hexsha": "590c3cc7156a37494a501bb3852fbdb17fc56655", "max_issues_repo_licenses": ["MIT"], "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/uvm/src/uvm/lsafemathlib.cpp", "max_forks_repo_name": "JWOCC/core", "max_forks_repo_head_hexsha": "590c3cc7156a37494a501bb3852fbdb17fc56655", "max_forks_repo_licenses": ["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.7386706949, "max_line_length": 181, "alphanum_fraction": 0.6782950116, "num_tokens": 11242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.02976009362326731, "lm_q1q2_score": 0.012573777488334607}}
{"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_CALCULATOR_HPP\n#define AMA_TENSOR_MUL_MUL_CALCULATOR_HPP 1\n\n#include <ama/tensor/iexp/iexp_calculator.hpp>\n#include <ama/tensor/iexp/indices.hpp>\n#include <ama/common/size_t.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/size.hpp>\n\n/* forward declaration */\nnamespace ama\n{\n  template <typename S, size_t D, size_t CT, size_t CO> class tensor;\n  namespace tensor_\n  {\n    template <typename LEFT, typename RIGHT> class mul_outer;\n  }\n}\n\n\n\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    namespace mpl = ::boost::mpl;\n\n    /* get the covariant and the controvariant part of product */\n    template <typename LEFT, typename RIGHT>\n    struct mul_index\n    {\n      /* the controvariant and covariant indices */\n      typedef typename mpl::fold<\n            typename RIGHT::controvariant_list\n          , typename LEFT::controvariant_list\n          , mpl::push_back<mpl::_1, mpl::_2>\n          >::type controvariant_list;\n      typedef typename mpl::fold<\n            typename RIGHT::covariant_list\n          , typename LEFT::covariant_list\n          , mpl::push_back<mpl::_1, mpl::_2>\n          >::type covariant_list;\n\n      /* the dimension of controvariant and covariant components */\n      typedef mpl::size<controvariant_list> controvariant_type;\n      typedef mpl::size<covariant_list> covariant_type;\n\n      /* the full index list */\n      typedef typename mpl::fold<\n            covariant_list\n          , controvariant_list\n          , mpl::push_back<mpl::_1, mpl::_2>\n          >::type index_list;\n\n      /* tensor type */\n      typedef typename LEFT::value_type value_type;\n      typedef typename LEFT::dimension_type dimension_type;\n      typedef tensor<\n            value_type\n          , dimension_type::value\n          , controvariant_type::value\n          , covariant_type::value\n          > tensor_type;\n    };\n\n    template <typename LEFT, typename RIGHT>\n    struct mul_calculator:\n          mpl::if_<\n                has_repeated_indices<typename mul_index<LEFT, RIGHT>::index_list>\n              , typename mpl::if_<\n                      all_repeated_indices<typename mul_index<LEFT, RIGHT>::index_list>\n                    , typename LEFT::value_type\n                    , iexp_temporary<\n                            typename iexp_reduce<\n                                  typename mul_index<LEFT, RIGHT>::tensor_type\n                                , typename mul_index<LEFT, RIGHT>::index_list\n                                >::tensor_type\n                          , typename iexp_reduce<\n                                  typename mul_index<LEFT, RIGHT>::tensor_type\n                                , typename mul_index<LEFT, RIGHT>::index_list\n                                >::controvariant\n                          , typename iexp_reduce<\n                                  typename mul_index<LEFT, RIGHT>::tensor_type\n                                , typename mul_index<LEFT, RIGHT>::index_list\n                                >::covariant\n                          >\n                    >::type\n              , mul_outer<LEFT, RIGHT>\n              >\n    {\n      /* TODO check indices the repeated indices must be in different part */\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_MUL_MUL_CALCULATOR_HPP */\n", "meta": {"hexsha": "d8ddeddd1f0e4194087fbcc2ea40ad977c0352d9", "size": 4994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/mul/mul_calculator.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_calculator.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_calculator.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.1221374046, "max_line_length": 87, "alphanum_fraction": 0.6355626752, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.0259573578571174, "lm_q1q2_score": 0.012573227186438371}}
{"text": "#pragma once\n\n#include <vector>\n#include <armadillo>\n\n#include \"material.hpp\"\n\n/*!\n * \\brief The PipeWall class is a container class that defines the thickness\n * and Material properties of each layer a pipe consists of.\n */\nclass PipeWall\n{\npublic:\n    class Layer;\n\n    /*!\n     * \\brief Construct PipeWall with a given number of layers.\n     * \\param nWallLayers Number of layers.\n     */\n    explicit PipeWall(const arma::uword nWallLayers):\n        m_layers(std::vector<Layer>(nWallLayers))\n    {}\n\n    /*!\n     * \\brief Construct PipeWall from a vector of PipeWall::Layer.\n     * \\param wallLayers The layers of the wall.\n     */\n    explicit PipeWall(const std::vector<Layer>& wallLayers):\n        m_layers(wallLayers)\n    {}\n\n    //! Get layer with index i. Returns const reference to member.\n    const Layer& layer(const arma::uword i) const\n    {\n        return m_layers.at(i);\n    }\n\n    //! Get layer with index i. Returns (non-const) reference to member.\n    Layer& layer(const arma::uword i)\n    {\n        return m_layers.at(i);\n    }\n\n    //! Get all pipe wall layers. Returns const reference to member.\n    const std::vector<Layer>& layers() const { return m_layers; }\n\n    //! Get number of layers in the pipe wall.\n    arma::uword size() const { return m_layers.size(); }\n\n    // initialized in .cpp\n    static const PipeWall defaultPipeWall; //!< Predefined pipe wall.\n\nprivate:\n    //! m_layers Vector of PipeWall::Layer that the wall consists of.\n    std::vector<Layer> m_layers;\n};\n\n/*!\n * \\brief The PipeWall::Layer class is a simple container class that defines the\n * thickness and all other material properties of a single layer of pipe wall.\n */\nclass PipeWall::Layer : public Material\n{\npublic:\n    /*!\n     * \\brief Default constructor, sets all properties to -1.\n     */\n    constexpr Layer():\n        Material(-1, -1, -1),\n        m_thickness(-1)\n    {}\n\n    /*!\n     * \\brief Basic constructor that requires all material properties.\n     * \\param thickness Layer thickness [m]\n     * \\param conductivity Thermal conductivity [W/(m K)]\n     * \\param density Density [kg/m3]\n     * \\param heatCapacity Heat capacity at constant pressure (\\f$c_p\\f$) [J/(kg K)]\n     */\n    constexpr Layer(\n            const double thickness,\n            const double conductivity,\n            const double density,\n            const double heatCapacity):\n        Material(conductivity, density, heatCapacity),\n        m_thickness(thickness)\n    {}\n\n    /*!\n     * \\brief Construct from thickness and Material instance.\n     * \\param thickness Layer thickness [m]\n     * \\param material Pipe wall material.\n     */\n    constexpr Layer(\n            const double thickness,\n            const Material& material):\n        Material(material),\n        m_thickness(thickness)\n    {}\n\n    double thickness() const { return m_thickness; } //!< Thickness getter\n    double conductivity() const { return m_conductivity; } //!< Conductivity getter\n    double density() const { return m_density; } //!< Density getter\n    double heatCapacity() const { return m_heatCapacity; } //!< Heat capacity getter\n\n    // setters\n    double& thickness() { return m_thickness; } //!< Thickness setter\n    double& conductivity() { return m_conductivity; } //!< Conductivity setter\n    double& density() { return m_density; } //!< Density setter\n    double& heatCapacity() { return m_heatCapacity; } //!< Heat capacity setter\n\nprivate:\n    double m_thickness; //!< Layer wall thickness [m]\n};\n", "meta": {"hexsha": "1d97e344ce1d9d480f0da541e3b9cc05984a1308", "size": 3479, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heattransfer/pipewall.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/pipewall.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/pipewall.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": 29.9913793103, "max_line_length": 84, "alphanum_fraction": 0.6470250072, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.04272219373765974, "lm_q1q2_score": 0.012569509041267374}}
{"text": "#include <fstream>\n#include <yaml-cpp/yaml.h>\n#include <Eigen/Dense>\n#include <qualisys/QualisysCalib.h>\n\nusing namespace std;\nusing namespace ros;\nusing namespace Eigen;\n\n// Support for new yaml-cpp, taken from\n// https://github.com/ros-planning/moveit_setup_assistant/commit/c9238ca#diff-1\n#ifdef HAVE_NEW_YAMLCPP\n// The >> operator disappeared in yaml-cpp 0.5, so this function is\n// added to provide support for code written under the yaml-cpp 0.3 API.\ntemplate <typename T>\nstatic void operator>>(const YAML::Node &node, T &i)\n{\n  i = node.as<T>();\n}\n#endif\n\n// yaml-cpp 0.5 also changed how you load the YAML document.  This\n// function hides the changes.\nstatic void loadYaml(std::istream &in_stream, YAML::Node &doc_out)\n{\n#ifdef HAVE_NEW_YAMLCPP\n  doc_out = YAML::Load(in_stream);\n#else\n  YAML::Parser parser(in_stream);\n  parser.GetNextDocument(doc_out);\n#endif\n}\n\nnamespace qualisys\n{\n\nQualisysCalib::QualisysCalib(const ros::NodeHandle& n):\n  nh(n),\n  enable_calibration(false),\n  calib_stand_ready(false){\n  return;\n}\n\nbool QualisysCalib::init() {\n\n  // Load the name of files\n  nh.param(\"calib_marker_pos_file\", calib_marker_pos_file,\n      std::string(\"QuadrotorCalib.yaml\"));\n  nh.param(\"zero_pose_dir\", zero_pose_dir,\n      std::string(\"calib\"));\n\n  // Load the positon of markers on the calib stand\n  if(!loadCalibMarkerPos(calib_marker_pos_file, marker_pos_map)) {\n    ROS_ERROR(\"Error loading calib marker positions from file: %s\",\n              calib_marker_pos_file.c_str());\n    return false;\n  }\n\n  // Resize the number of markers on the stand accordingly.\n  calib_ref_points.resize(marker_pos_map.size());\n  calib_actual_points.resize(marker_pos_map.size());\n\n  // Create publishers, subscribers, and services\n  zero_pose_pub = nh.advertise<geometry_msgs::PoseStamped>(\"zero_pose\", 10);\n  Subscriber calib_sub = nh.subscribe(\"qualisys_calib\", 10,\n      &QualisysCalib::calibStandCallback, this,\n      ros::TransportHints().tcp().tcpNoDelay());\n  Subscriber subject_sub = nh.subscribe(\"qualisys_subject\", 10,\n      &QualisysCalib::subjectCallback, this,\n      ros::TransportHints().tcp().tcpNoDelay());\n  ServiceServer toggle_calib_srv = nh.advertiseService(\"toggle_calibration\",\n      &QualisysCalib::toggleCalibCallback, this);\n\n  return true;\n}\n\nbool QualisysCalib::loadZeroPoseFromFile(const std::string &filename,\n    Eigen::Affine3d &zero_pose)\n{\n  zero_pose = Eigen::Affine3d::Identity();\n\n  std::ifstream fin(filename.c_str());\n  if(!fin.is_open())\n  {\n#ifdef DEBUG\n    std::cerr << \"Error opening file: \" << filename\n              << \", setting zero pose to identity\" << std::endl;\n#endif\n    return false;\n  }\n\n  bool ret = false;\n\n  try\n  {\n    YAML::Node doc;\n    loadYaml(fin, doc);\n\n    try\n    {\n      Eigen::Vector3d v;\n      Eigen::Quaterniond q;\n      doc[\"translation\"][\"x\"] >> v(0);\n      doc[\"translation\"][\"y\"] >> v(1);\n      doc[\"translation\"][\"z\"] >> v(2);\n      doc[\"rotation\"][\"x\"] >> q.x();\n      doc[\"rotation\"][\"y\"] >> q.y();\n      doc[\"rotation\"][\"z\"] >> q.z();\n      doc[\"rotation\"][\"w\"] >> q.w();\n      zero_pose.translate(v);\n      zero_pose.rotate(q);\n      ret = true;\n    }\n    catch(YAML::KeyNotFound &e)\n    {\n      ret = false;\n    }\n  }\n  catch(YAML::ParserException &e)\n  {\n    ret = false;\n  }\n  fin.close();\n\n  if(!ret)\n  {\n#if DEBUG\n    std::cerr << \"Error parsing calib file: \" << filename\n              << \", setting zero_pose to Identity\" << std::endl;\n#endif\n  }\n  return ret;\n}\n\nbool QualisysCalib::saveZeroPoseToFile(const Eigen::Affine3d &zero_pose,\n    const std::string &filename)\n{\n  YAML::Emitter out;\n\n  Eigen::Vector3d v(zero_pose.translation());\n  Eigen::Quaterniond q(zero_pose.rotation());\n\n  out << YAML::BeginMap;\n  out << YAML::Key << \"translation\";\n  out << YAML::Value << YAML::BeginMap << YAML::Key << \"x\" << YAML::Value\n      << v.x() << YAML::Key << \"y\" << YAML::Value << v.y() << YAML::Key << \"z\"\n      << YAML::Value << v.z() << YAML::EndMap;\n  out << YAML::Key << \"rotation\";\n  out << YAML::Value << YAML::BeginMap << YAML::Key << \"x\" << YAML::Value\n      << q.x() << YAML::Key << \"y\" << YAML::Value << q.y() << YAML::Key << \"z\"\n      << YAML::Value << q.z() << YAML::Key << \"w\" << YAML::Value << q.w()\n      << YAML::EndMap;\n  out << YAML::EndMap;\n\n  std::ofstream fout(filename.c_str(),\n                     std::ios_base::out | std::ios_base::trunc);\n  if(!fout.is_open())\n  {\n#ifdef DEBUG\n    std::cerr << \"Error opening file: \" << filename << std::endl;\n#endif\n    return false;\n  }\n\n  bool ret = true;\n\n  fout << out.c_str() << std::endl;\n  if(!fout.good())\n  {\n#ifdef DEBUG\n    std::cerr << \"Error writing to file: \" << filename << std::endl;\n#endif\n    ret = false;\n  }\n\n  fout.close();\n\n  return ret;\n}\n\nbool QualisysCalib::getTransform(const std::vector<Eigen::Vector3d> &reference_points,\n    const std::vector<Eigen::Vector3d> &actual_points,\n    Eigen::Affine3d &transform)\n{\n  transform = Eigen::Affine3d::Identity();\n\n  if(reference_points.size() != actual_points.size())\n  {\n    return false;\n  }\n\n  // Algorithm from http://dx.doi.org/10.1016/0021-9290(94)00116-L\n  const size_t num_points = reference_points.size();\n  Eigen::Vector3d reference_mean = Eigen::Vector3d::Zero();\n  Eigen::Vector3d actual_mean = Eigen::Vector3d::Zero();\n  for(size_t i = 0; i < num_points; i++)\n  {\n    reference_mean += reference_points[i];\n    actual_mean += actual_points[i];\n  }\n  reference_mean /= num_points;\n  actual_mean /= num_points;\n\n  Eigen::Matrix3d C = Eigen::Matrix3d::Zero();\n  for(size_t i = 0; i < num_points; i++)\n  {\n    C += (actual_points[i] - actual_mean) *\n         (reference_points[i] - reference_mean).transpose();\n  }\n  C /= num_points;\n\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(\n      C, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n  const Eigen::Matrix3d U = svd.matrixU();\n  Eigen::Matrix3d S = Eigen::Matrix3d::Identity();\n  const Eigen::Matrix3d V = svd.matrixV();\n  if(U.determinant() * V.determinant() < 0)\n  {\n    S(2, 2) = -1;\n  }\n\n  const Eigen::Matrix3d rotation = U * S * V.transpose();\n\n  const Eigen::Vector3d translation = actual_mean - rotation * reference_mean;\n\n  transform.translate(translation);\n  transform.rotate(rotation);\n\n  return true;\n}\n\nbool QualisysCalib::loadCalibMarkerPos(const std::string &filename,\n    std::map<std::string, Eigen::Vector3d> &marker_pos_map)\n{\n  std::ifstream fin(filename.c_str());\n  if(!fin.is_open())\n  {\n#ifdef DEBUG\n    std::cerr << \"Error opening calib marker position file: \" << filename\n              << std::endl;\n#endif\n    return false;\n  }\n\n  bool ret = false;\n\n  try\n  {\n    YAML::Node doc;\n    loadYaml(fin, doc);\n\n    try\n    {\n      const YAML::Node &markers = doc[\"markers\"];\n\n      for(unsigned int i = 0; i < markers.size(); i++)\n      {\n        std::string name;\n        markers[i][\"name\"] >> name;\n        const YAML::Node &pos = markers[i][\"position\"];\n        Eigen::Vector3d position;\n        pos[0] >> position.x();\n        pos[1] >> position.y();\n        pos[2] >> position.z();\n        // Use a simple way to add a pair to the map\n        marker_pos_map[name] = position;\n        //marker_pos_map.insert(\n        //    std::make_pair<std::string, Eigen::Vector3d>(name, position));\n      }\n      ret = true;\n    }\n    catch(YAML::KeyNotFound &e)\n    {\n      ret = false;\n    }\n  }\n  catch(YAML::ParserException &e)\n  {\n    ret = false;\n  }\n  fin.close();\n\n  if(!ret)\n  {\n#if DEBUG\n    std::cerr << \"Error parsing calib marker position file: \" << filename\n              << std::endl;\n#endif\n    marker_pos_map.clear();\n  }\n  return ret;\n}\n\nvoid QualisysCalib::calibStandCallback(\n    const qualisys::Subject::ConstPtr &msg)\n{\n  calib_ref_points.clear();\n  calib_actual_points.clear();\n\n  std::map<std::string, Eigen::Vector3d>::iterator it;\n  for(size_t i = 0; i < msg->markers.size(); i++)\n  {\n    if(!msg->markers[i].occluded)\n    {\n      it = marker_pos_map.find(msg->markers[i].name);\n      if(it != marker_pos_map.end())\n      {\n        calib_ref_points.push_back(it->second);\n        calib_actual_points.push_back(Eigen::Vector3d(\n            msg->markers[i].position.x, msg->markers[i].position.y,\n            msg->markers[i].position.z));\n      }\n      else\n      {\n        ROS_WARN_THROTTLE(\n            1, \"Marker %s is not present in calib_marker_pos_file, skipping it\",\n            msg->markers[i].name.c_str());\n      }\n    }\n    else\n    {\n      ROS_WARN_THROTTLE(1, \"Marker %s is occluded, skipping it\",\n                        msg->markers[i].name.c_str());\n    }\n  }\n  if(!QualisysCalib::getTransform(calib_ref_points, calib_actual_points,\n                                        calib_transform))\n  {\n    ROS_WARN(\"QualisysCalib::getTransform failed\");\n    calib_stand_ready = false;\n  }\n  else\n  {\n    calib_stand_ready = true;\n  }\n}\n\nvoid QualisysCalib::subjectCallback(const qualisys::Subject::ConstPtr &msg)\n{\n  static bool calibrating = false;\n  static double t_x, t_y, t_z;\n  static double q_x, q_y, q_z, q_w;\n  static unsigned int count;\n\n  if(enable_calibration && !calibrating)\n  {\n    // Start calib\n    t_x = t_y = t_z = 0;\n    q_x = q_y = q_z = q_w = 0;\n    count = 0;\n    calibrating = true;\n  }\n  else if(!enable_calibration && calibrating)\n  {\n    // Stop calib\n    calibrating = false;\n\n    //vicon::SetPose pose;\n    Eigen::Affine3d zero_pose;\n    zero_pose.setIdentity();\n    Eigen::Quaterniond q(q_w / count, q_x / count, q_y / count, q_z / count);\n    q.normalize();\n    Eigen::Vector3d t(t_x/count, t_y/count, t_z/count);\n    zero_pose.translate(t);\n    zero_pose.rotate(q);\n\n    model_name = msg->name;\n    string model_zero_pose_file = zero_pose_dir+\"/\"+model_name+\".yaml\";\n    saveZeroPoseToFile(zero_pose, model_zero_pose_file);\n    //pose.request.subject_name = msg->name;\n    //pose.request.pose.position.x = t_x / count;\n    //pose.request.pose.position.y = t_y / count;\n    //pose.request.pose.position.z = t_z / count;\n    //pose.request.pose.orientation.x = q.x();\n    //pose.request.pose.orientation.y = q.y();\n    //pose.request.pose.orientation.z = q.z();\n    //pose.request.pose.orientation.w = q.w();\n    //set_zero_pose_srv.call(pose);\n  }\n\n  if(calibrating)\n  {\n    Eigen::Affine3d zero_pose, current_pose;\n    Eigen::Vector3d t(msg->position.x, msg->position.y, msg->position.z);\n    Eigen::Quaterniond q(msg->orientation.w, msg->orientation.x,\n                         msg->orientation.y, msg->orientation.z);\n    model_name = msg->name;\n    current_pose.setIdentity();\n    current_pose.translate(t);\n    current_pose.rotate(q);\n\n    zero_pose = calib_transform.inverse() * current_pose;\n\n    t = zero_pose.translation();\n    q = Eigen::Quaterniond(zero_pose.rotation());\n\n    // Accumulate (to calculate mean)\n    t_x += t(0);\n    t_y += t(1);\n    t_z += t(2);\n    q_x += q.x();\n    q_y += q.y();\n    q_z += q.z();\n    q_w += q.w();\n    count++;\n\n    geometry_msgs::PoseStamped::Ptr zero_pose_msg(\n        new geometry_msgs::PoseStamped);\n    zero_pose_msg->header.stamp = msg->header.stamp;\n    zero_pose_msg->header.frame_id = \"/qualisys\";\n\n    zero_pose_msg->pose.position.x = t_x / count;\n    zero_pose_msg->pose.position.y = t_y / count;\n    zero_pose_msg->pose.position.z = t_z / count;\n\n    q = Eigen::Quaterniond(q_w / count, q_x / count, q_y / count, q_z / count);\n    q.normalize();\n\n    zero_pose_msg->pose.orientation.x = q.x();\n    zero_pose_msg->pose.orientation.y = q.y();\n    zero_pose_msg->pose.orientation.z = q.z();\n    zero_pose_msg->pose.orientation.w = q.w();\n\n    zero_pose_pub.publish(zero_pose_msg);\n  }\n}\n\nbool QualisysCalib::toggleCalibCallback(std_srvs::Empty::Request &req,\n    std_srvs::Empty::Response &res)\n{\n  if(!calib_stand_ready)\n  {\n    ROS_ERROR(\"Do not have calib stand pose, cannot calibrate\");\n    enable_calibration = false;\n    return false;\n  }\n\n  enable_calibration = !enable_calibration;\n  return true;\n}\n}\n", "meta": {"hexsha": "2d01aa2aeb279c1c6e3f957eef2a6f6ccb9388c2", "size": 11809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/QualisysCalib.cpp", "max_stars_repo_name": "jeffersonkim97/qualisys", "max_stars_repo_head_hexsha": "787de25271c49dc1402cad41999fa9c0e39dd0ff", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-04-27T00:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T11:00:59.000Z", "max_issues_repo_path": "src/QualisysCalib.cpp", "max_issues_repo_name": "jeffersonkim97/qualisys", "max_issues_repo_head_hexsha": "787de25271c49dc1402cad41999fa9c0e39dd0ff", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-07-19T06:45:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-19T16:15:34.000Z", "max_forks_repo_path": "src/QualisysCalib.cpp", "max_forks_repo_name": "jeffersonkim97/qualisys", "max_forks_repo_head_hexsha": "787de25271c49dc1402cad41999fa9c0e39dd0ff", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-03-11T16:05:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:13:42.000Z", "avg_line_length": 26.6568848758, "max_line_length": 86, "alphanum_fraction": 0.6279109154, "num_tokens": 3281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.031143831658843563, "lm_q1q2_score": 0.01256861815582365}}
{"text": "// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye\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 ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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#pragma once\n\n#include <functional>\n#include <Eigen/Dense>\n#include <ze/common/types.hpp>\n#include <ze/common/transformation.hpp>\n\nnamespace ze {\n\n//! Manifold traits define a retract (boxPlus), and local (boxMinus) operation\n//! for scalars, vectors, rotations and transformations. The traits are used for\n//! simplified computation of numerical derivatives to verify the analytical ones\n//! and in the optimizer. These traits are inspired by GTSAM and for rotations\n//! and transformation we use the same convention (updates are applied on the\n//! right hand side / in the body frame).\ntemplate<typename T> struct traits;\n\n// -----------------------------------------------------------------------------\n// Manifold traits for scalars.\nnamespace internal {\ntemplate<typename Scalar>\nstruct ScalarTraits\n{\n  enum { dimension = 1 }; //! @todo(cfo): static constexpr int fails on GCC 4.8, works for Eigen because no derived class.\n  typedef Eigen::Matrix<Scalar, 1, 1> TangentVector;\n  typedef Eigen::Matrix<Scalar, 1, 1> Jacobian;\n\n  static int getDimension(const Scalar /*v*/)\n  {\n    return 1;\n  }\n\n  static bool equals(Scalar v1, Scalar v2, Scalar tol = 1e-8)\n  {\n    return std::abs(v1 - v2) < tol;\n  }\n\n  static TangentVector local(const Scalar origin, Scalar other,\n                             Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    if (H1)\n    {\n      (*H1)[0] = -1.0; // dlocal(origin, other) / dorigin\n    }\n    if (H2)\n    {\n      (*H2)[0] =  1.0; // dlocal(origin, other) / dother\n    }\n    TangentVector result;\n    result(0) = other - origin;\n    return result;\n  }\n\n  static Scalar retract(const Scalar origin, const TangentVector& v,\n                        Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    if (H1)\n    {\n      (*H1)[0] = 1.0; // dretract(origin, v) / dorigin\n    }\n    if (H2)\n    {\n      (*H2)[0] = 1.0; // dretract(origin, v) / dv\n    }\n    return origin + v[0];\n  }\n};\n} // namespace internal\n\n// Define scalar traits for float and double\ntemplate<> struct traits<double> : public internal::ScalarTraits<double> {};\ntemplate<> struct traits<float> : public internal::ScalarTraits<float> {};\n\n\n// -----------------------------------------------------------------------------\n// Manifold traits for fixed-size Eigen matrices and vectors with double precision.\ntemplate<int M, int N, int Options, int MaxRows, int MaxCols>\nstruct traits<Eigen::Matrix<real_t, M, N, Options, MaxRows, MaxCols> >\n{\n  //static constexpr int dimension = M * N;\n  enum { dimension = M * N };\n  typedef Eigen::Matrix<real_t, M, N, Options, MaxRows, MaxCols> Matrix;\n  typedef Eigen::Matrix<real_t, dimension, 1> TangentVector;\n  typedef Eigen::Matrix<real_t, dimension, dimension> Jacobian;\n\n  static int getDimension(const Matrix& /*v*/)\n  {\n    return M * N;\n  }\n\n  static bool equals(const Matrix& v1, const Matrix& v2, real_t tol = 1e-8)\n  {\n    if (v1.size() != v2.size())\n    {\n      return false;\n    }\n    return (v1 - v2).array().abs().maxCoeff() < tol;\n    // TODO(cfo): Check for nan entries.\n  }\n\n  static TangentVector local(\n      const Matrix& origin, Matrix other,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    if (H1)\n    {\n      *H1 = -Jacobian::Identity(); // dLocal(origin, other)/dOrigin\n    }\n    if (H2)\n    {\n      *H2 =  Jacobian::Identity(); // dLocal(origin, other)/dOther\n    }\n    TangentVector result;\n    Eigen::Map<Matrix>(result.data()) = other - origin;\n    return result;\n  }\n\n  static Matrix retract(\n      const Matrix& origin, const TangentVector& v,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    if (H1)\n    {\n      *H1 = Jacobian::Identity(); // dretract(origin, v) / dorigin\n    }\n    if (H2)\n    {\n      *H2 = Jacobian::Identity(); // dretract(origin, v) / dv\n    }\n    return origin + Eigen::Map<const Matrix>(v.data());\n  }\n};\n\n// -----------------------------------------------------------------------------\n// Manifold traits for dynamic-size Eigen matrices and vectors with double precision.\nnamespace internal {\n\n// traits for dynamic Eigen matrices\ntemplate<int M, int N, int Options, int MaxRows, int MaxCols>\nstruct DynamicMatrixTraits {\n\n  typedef Eigen::Matrix<real_t, M, N, Options, MaxRows, MaxCols> DynamicMatrix;\n\n  enum Dimension : int { dimension = Eigen::Dynamic };\n\n  typedef VectorX TangentVector;\n  typedef Eigen::Matrix<real_t, dimension, dimension> Jacobian;\n  typedef DynamicMatrix ManifoldType;\n\n  static int getDimension(const DynamicMatrix& m)\n  {\n    return m.rows() * m.cols();\n  }\n\n  static Jacobian eye(const DynamicMatrix& m)\n  {\n    int dim = getDimension(m);\n    return Eigen::Matrix<real_t, dimension, dimension>::Identity(dim, dim);\n  }\n\n  static TangentVector local(\n      const DynamicMatrix& origin, const DynamicMatrix& other,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    if (H1)\n    {\n      *H1 = -eye(origin); // dlocal(origin, other) / dorigin\n    }\n    if (H2)\n    {\n      *H2 =  eye(origin); // dlocal(origin, other) / dother\n    }\n    TangentVector v(getDimension(origin));\n    Eigen::Map<DynamicMatrix>(v.data(), origin.rows(), origin.cols()) = other - origin;\n    return v;\n  }\n\n  static DynamicMatrix retract(\n      const DynamicMatrix& origin, const TangentVector& v,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    if (H1)\n    {\n      *H1 = eye(origin); // dretract(origin, v) / dorigin\n    }\n    if (H2)\n    {\n      *H2 = eye(origin); // dretract(origin, v) / dv\n    }\n    return origin + Eigen::Map<const DynamicMatrix>(v.data(), origin.rows(), origin.cols());\n  }\n};\n\n} // namespace internal\n\n// traits for fully dynamic matrix\ntemplate<int Options, int MaxRows, int MaxCols>\nstruct traits<Eigen::Matrix<real_t, Eigen::Dynamic, Eigen::Dynamic, Options, MaxRows, MaxCols> > :\n    public internal::DynamicMatrixTraits<Eigen::Dynamic, Eigen::Dynamic, Options, MaxRows, MaxCols> {\n};\n\n// traits for dynamic column vector\ntemplate<int Options, int MaxRows, int MaxCols>\nstruct traits<Eigen::Matrix<real_t, Eigen::Dynamic, 1, Options, MaxRows, MaxCols> > :\n    public internal::DynamicMatrixTraits<Eigen::Dynamic, 1, Options, MaxRows, MaxCols> {\n};\n\n// traits for dynamic row vector\ntemplate<int Options, int MaxRows, int MaxCols>\nstruct traits<Eigen::Matrix<real_t, 1, Eigen::Dynamic, Options, MaxRows, MaxCols> > :\n    public internal::DynamicMatrixTraits<1, Eigen::Dynamic, Options, MaxRows, MaxCols> {\n};\n\n// -----------------------------------------------------------------------------\n// Manifold traits for SO(3)\ntemplate<> struct traits<Quaternion>\n{\n  enum { dimension = 3 }; // The dimension of the manifold.\n\n  typedef Eigen::Matrix<real_t, dimension, 1> TangentVector;\n  typedef Eigen::Matrix<real_t, dimension, dimension> Jacobian;\n\n  static int getDimension(const Quaternion& /*v*/)\n  {\n    return 3;\n  }\n\n  static bool equals(\n      const Quaternion& q1, const Quaternion& q2, real_t tol = 1e-8)\n  {\n    return (q1.getUnique().vector()\n            - q2.getUnique().vector()).array().abs().maxCoeff() < tol;\n  }\n\n  static TangentVector local(\n      const Quaternion& origin, const Quaternion& other,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    const Quaternion h = origin.inverse() * other;\n    const TangentVector v = h.log();\n    if(H1 || H2)\n    {\n      Jacobian D_v_h = logmapDerivativeSO3(v);\n      if(H1)\n      {\n        // dlocal(origin, other) / dorigin, using that Adjoint(h.inverse()) = h.inverse()\n        *H1 = - D_v_h * h.inverse().getRotationMatrix();\n      }\n      if(H2)\n      {\n        // dlocal(origin, other) / dother\n        *H2 = D_v_h;\n      }\n    }\n    return v;\n  }\n\n  static Quaternion retract(\n      const Quaternion& origin, const Vector3& v,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    const Quaternion g = Quaternion::exp(v);\n    const Quaternion h = origin * g;\n    if (H1)\n    {\n      // dretract(origin, v) / dorigin\n      *H1 = g.inverse().getRotationMatrix(); // Adjoint(g.inverse()) = g.inverse()\n    }\n    if (H2)\n    {\n      // dretract(origin, v) / dv\n      *H2 = expmapDerivativeSO3(v);\n    }\n    return h;\n  }\n};\n\n// -----------------------------------------------------------------------------\n// Manifold traits for SE(3)\ntemplate<> struct traits<Transformation>\n{\n  enum { dimension = 6 }; // The dimension of the manifold.\n\n  typedef Eigen::Matrix<real_t, dimension, 1> TangentVector;\n  typedef Eigen::Matrix<real_t, dimension, dimension> Jacobian;\n\n  static int getDimension(const Transformation& /*v*/)\n  {\n    return 6;\n  }\n\n  static bool equals(\n      const Transformation& T1, const Transformation& T2, real_t tol = 1e-8)\n  {\n    return (T1.getRotation().getUnique().vector()\n            - T2.getRotation().getUnique().vector()).array().abs().maxCoeff() < tol\n        && (T1.getPosition() - T2.getPosition()).array().abs().maxCoeff() < tol;\n  }\n\n  static TangentVector local(\n      const Transformation& origin, const Transformation& other,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    const Transformation h = origin.inverse() * other;\n    const TangentVector v = (Vector6() << h.getPosition(), h.getRotation().log()).finished();\n    if (H1 || H2)\n    {\n      Matrix3 J_r_inv = logmapDerivativeSO3(v.tail<3>());\n      if (H1)\n      {\n        // dlocal(origin, other) / dorigin\n        H1->block<3,3>(0,0) = -I_3x3;\n        H1->block<3,3>(0,3) = skewSymmetric(v.head<3>());\n        H1->block<3,3>(3,0) = Z_3x3;\n        H1->block<3,3>(3,3) = - J_r_inv * h.getRotation().inverse().getRotationMatrix();\n      }\n      if(H2)\n      {\n        // dlocal(origin, other) / dother\n        H2->block<3,3>(0,0) = h.getRotationMatrix();\n        H2->block<3,3>(0,3) = Z_3x3;\n        H2->block<3,3>(3,0) = Z_3x3;\n        H2->block<3,3>(3,3) = J_r_inv;\n      }\n    }\n    return v;\n  }\n\n  static Transformation retract(\n      const Transformation& origin, const Vector6& v,\n      Jacobian* H1 = nullptr, Jacobian* H2 = nullptr)\n  {\n    Transformation g(Quaternion::exp(v.tail<3>()), v.head<3>());\n    Transformation h  = origin * g;\n\n    if (H1 || H2)\n    {\n      const Matrix3 R_CB = Quaternion::exp(v.tail<3>()).inverse().getRotationMatrix();\n      if (H1)\n      {\n        // dretract(origin, other) / dorigin\n\n        // Remember: Computation of the translation components must be in the\n        // body frame of the result.\n        // Retraction: T_AC = T_AB * exp(xi_BC) = T_AB * T_BC\n        // Let's look at the translation component:\n        //    A_t_AC = A_t_AB + R_AB * B_t_BC\n        // Perturb it the translation (in the body frame B):\n        //    A_t_AC = A_t_AB + (R_AB * B_dt) + R_AB * B_t_BC\n        //           = A_t_AC + (R_AB * B_dt)\n        // !!! What we want is the perturbation in the body frame of the result\n        // i.e. in the frame C:\n        //    A_t_AC = A_t_AC + (R_AB * B_dt)\n        //    A_t_AC = A_t_AC + (R_AC * R_AC^-1) * (R_AB * B_dt) <- trick\n        //           = A_t_AC + R_AC * (R_CB * B_dt)\n        //           -> Jacobian = R_CB\n        H1->block<3,3>(0,0) = R_CB;\n        H1->block<3,3>(0,3) = - R_CB * skewSymmetric(v.head<3>());\n        H1->block<3,3>(3,0) = Z_3x3;\n        H1->block<3,3>(3,3) = g.getRotation().inverse().getRotationMatrix();\n      }\n      if(H2)\n      {\n        H2->block<3,3>(0,0) = R_CB;\n        H2->block<3,3>(0,3) = Z_3x3;\n        H2->block<3,3>(3,0) = Z_3x3;\n        H2->block<3,3>(3,3) = expmapDerivativeSO3(v.tail<3>());\n      }\n    }\n    return h;\n  }\n};\n\n} // namespace ze\n", "meta": {"hexsha": "fe15841eaec8f4c2e25d919f0d57e262204e2736", "size": 13078, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ze_common/include/ze/common/manifold.hpp", "max_stars_repo_name": "rockenbf/ze_oss", "max_stars_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-09-27T07:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T20:44:28.000Z", "max_issues_repo_path": "ze_common/include/ze/common/manifold.hpp", "max_issues_repo_name": "rockenbf/ze_oss", "max_issues_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-18T15:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-21T03:10:06.000Z", "max_forks_repo_path": "ze_common/include/ze/common/manifold.hpp", "max_forks_repo_name": "rockenbf/ze_oss", "max_forks_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-11-05T07:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T02:26:08.000Z", "avg_line_length": 32.695, "max_line_length": 122, "alphanum_fraction": 0.613702401, "num_tokens": 3536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.033589501780421555, "lm_q1q2_score": 0.012558302145971768}}
{"text": "#include \"rgbd_primitives.hpp\"\n#define PCL_VERBOSITY_LEVEL L_ERROR\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n\n// random numbers on range 0->1\nboost::variate_generator<boost::mt19937, boost::uniform_01<> >\n    rand01(boost::mt19937(time(0)),\n              boost::uniform_01<>());\n\n\n\n\nrgbd_primitives::rgbd_primitives(){\n\n}\n\nvoid set_color(pcl::PointXYZRGB &pt){\n pt.r =55.0;\n pt.g = 125.0;\n pt.b = 50.0;\n}\n\n\n// Duplicates function in pointcloud_math\nbool mergePolygonMesh(pcl::PolygonMesh::Ptr &meshA, pcl::PolygonMesh::Ptr meshB){\n  pcl::PointCloud<pcl::PointXYZRGB> cloudA;  \n  // HACKY BUG FIX: \n  // issue: if meshA->cloud contains no data, then it contains no cloud.fields\n  //        so it will complain and give a warning when we try to copy to cloudA\n  //        Failed to find match for field 'x'.\n  //        Failed to find match for field 'y'.\n  //        Failed to find match for field 'z'.\n  //        Failed to find match for field 'rgb'.  \n  // Instead dont try to copy if empty...\n  if ( meshA->cloud.fields.size()  !=0){\n    pcl::fromPCLPointCloud2(meshA->cloud, cloudA);\n  }\n  int original_size = cloudA.points.size() ;\n\n  //cout << original_size << \" is the cloud before (insize) size\\n\";\n  //cout <<  meshA->polygons.size () << \"polygons before\\n\";\n  \n  int N_polygonsB = meshB->polygons.size ();\n  pcl::PointCloud<pcl::PointXYZRGB> cloudB;  \n  pcl::fromPCLPointCloud2(meshB->cloud, cloudB);\n  Eigen::Vector4f tmp;\n  for(size_t i=0; i< N_polygonsB; i++){ // each triangle/polygon\n    pcl::Vertices apoly_in = meshB->polygons[i];//[i];\n    int N_points = apoly_in.vertices.size ();\n    for(size_t j=0; j< N_points; j++){ // each point\n      // increment the vertex numbers by the size of the original clouds\n      apoly_in.vertices[j] += original_size; \n    }\n    meshA->polygons.push_back(apoly_in);\n  } \n  cloudA += cloudB;\n  pcl::toPCLPointCloud2 (cloudA, meshA->cloud);\n  //cout <<  meshA->polygons.size () << \"polygons after\\n\";\n  //cout << cloudA.points.size() << \" is the cloud inside size\\n\";\n  return true;\n}\n\n\n// Duplicates function in pointcloud_math - and surely this can be done in a functioncall\nEigen::Isometry3f IsometryDoubleToFloat(Eigen::Isometry3d pose_in){\n  \n  Eigen::Quaterniond r(pose_in.rotation());\n  Eigen::Quaternionf rf(r.w() , r.x() , r.y() , r.z() );\n\n  Eigen::Isometry3f pose_out;\n  pose_out.setIdentity();\n  pose_out.translation()  << pose_in.translation().x() , pose_in.translation().y() , pose_in.translation().z();\n  pose_out.rotate(rf);\n  return pose_out;\n}\n\n\n\npcl::PolygonMesh::Ptr rgbd_primitives::getCylinderWithTransform(Eigen::Isometry3d transform, double base, double top, double height){\n\n  pcl::PolygonMesh::Ptr mesh_cylinder = getCylinder(base ,top , 0, height, 36,1);\n  bool add_lids=true; // TODO: add as an argument\n  if (add_lids){\n    pcl::PolygonMesh::Ptr mesh_base_lid = getCylinder(base ,0 , 0, 0, 36,1);\n    mergePolygonMesh(mesh_cylinder, mesh_base_lid);\n    pcl::PolygonMesh::Ptr mesh_top_lid = getCylinder(base ,0 , height, height, 36,1);\n    mergePolygonMesh(mesh_cylinder, mesh_top_lid);\n  }\n  \n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB> ());\n  pcl::fromPCLPointCloud2(mesh_cylinder->cloud, *cloud);  \n  \n  // Adjust object to be centered on z-axis (standard used by URDF)\n  pcl::transformPointCloud (*cloud, *cloud,\n        Eigen::Vector3f(0,0, -height/2.0), Eigen::Quaternionf(1.0, 0.0,0.0,0.0)); // !! modifies cloud\n    \n  Eigen::Isometry3f pose_f = IsometryDoubleToFloat(transform);\n  Eigen::Quaternionf quat_f(pose_f.rotation());\n  pcl::transformPointCloud (*cloud, *cloud,\n      pose_f.translation(), quat_f); // !! modifies cloud\n  \n  pcl::toPCLPointCloud2(*cloud, mesh_cylinder->cloud);\n    \n  return mesh_cylinder;\n}\n\n\npcl::PolygonMesh::Ptr rgbd_primitives::getCubeWithTransform(Eigen::Isometry3d transform, double xdim, double ydim, double zdim){\n\n  pcl::PolygonMesh::Ptr mesh_cylinder = getCube(xdim, ydim, zdim);\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB> ());\n  pcl::fromPCLPointCloud2(mesh_cylinder->cloud, *cloud);  \n  \n  // Adjust object to be centered on z-axis (standard used by URDF)\n  pcl::transformPointCloud (*cloud, *cloud,\n        Eigen::Vector3f( -xdim/2.0 , -ydim/2.0, -zdim/2.0), Eigen::Quaternionf(1.0, 0.0,0.0,0.0)); // !! modifies cloud\n    \n  Eigen::Isometry3f pose_f = IsometryDoubleToFloat(transform);\n  Eigen::Quaternionf quat_f(pose_f.rotation());\n  pcl::transformPointCloud (*cloud, *cloud,\n      pose_f.translation(), quat_f); // !! modifies cloud\n  \n  pcl::toPCLPointCloud2(*cloud, mesh_cylinder->cloud);\n    \n  return mesh_cylinder;\n}\n\n\npcl::PolygonMesh::Ptr rgbd_primitives::getSphereWithTransform(Eigen::Isometry3d transform, double radius){\n\n  pcl::PolygonMesh::Ptr mesh_cylinder = getSphere( radius);\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB> ());\n  pcl::fromPCLPointCloud2(mesh_cylinder->cloud, *cloud);  \n  \n  Eigen::Isometry3f pose_f = IsometryDoubleToFloat(transform);\n  Eigen::Quaternionf quat_f(pose_f.rotation());\n  pcl::transformPointCloud (*cloud, *cloud,\n      pose_f.translation(), quat_f); // !! modifies cloud\n  \n  pcl::toPCLPointCloud2(*cloud, mesh_cylinder->cloud);\n    \n  return mesh_cylinder;\n  \n}\n\n// create a polygon mesh of a cylinder (similar to clones gluCylinder)\n// This actually creates a triangle fan in a ring. \n// It can be used for \n// - cylinders\n// - cones (if a radius is set to zero)\n// - pyramids (if slices set to 4) \n// - discs (if base_height and top_height are equal and a radius is zero)\n// @base Specifies the radius of the cylinder at z = base_height (usually zero)\n// @top Specifies the radius of the cylinder at z = top_height.\n// @base_height Specifies the base height of the cylinder.\n// @top_height Specifies the top height of the cylinder.\n// @slices Specifies the number of subdivisions around the z axis.\n// @stacks - not used\npcl::PolygonMesh::Ptr rgbd_primitives::getCylinder(double base, double top, double base_height, double top_height, int slices, int stacks){ \n  pcl::PolygonMesh mesh;   \n  pcl::PolygonMesh::Ptr mesh_ptr (new pcl::PolygonMesh (mesh));  \n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr pts (new pcl::PointCloud<pcl::PointXYZRGB> ());\n  std::vector <pcl::Vertices> verts;\n  \n  double delta = (2*M_PI/slices);\n  for (double i=0, i_int=0;i< 2*M_PI; i=i+ delta, i_int++){\n    pcl::PointXYZRGB pt1, pt2, pt3, pt4, pt5, pt6;\n    pt1.x = base*cos(i);       pt1.y = base*sin(i);       pt1.z = base_height;  \n    pt2.x =  top*cos(i);       pt2.y =  top*sin(i);       pt2.z = top_height; \n    pt3.x = base*cos(i+delta); pt3.y = base*sin(i+delta); pt3.z = base_height;\n    set_color(pt1); set_color(pt2); set_color(pt3);\n    pts->points.push_back(pt1);\n    pts->points.push_back(pt2);\n    pts->points.push_back(pt3);\n    pcl::Vertices vert;\n    vert.vertices.push_back(i_int*6 ); vert.vertices.push_back(i_int*6+1); vert.vertices.push_back(i_int*6+2);\n    verts.push_back(vert);\n    \n    pt4.x = base*cos(i+delta)  ; pt4.y = base*sin(i+delta); pt4.z = base_height;\n    pt5.x =  top*cos(i+delta)  ; pt5.y =  top*sin(i+delta); pt5.z = top_height;\n    pt6.x =  top*cos(i)        ; pt6.y =  top*sin(i);       pt6.z = top_height;\n    set_color(pt4); set_color(pt5); set_color(pt6);\n    pts->points.push_back(pt4);\n    pts->points.push_back(pt5);\n    pts->points.push_back(pt6);\n    pcl::Vertices vertB;\n    vertB.vertices.push_back(i_int*6 +3); vertB.vertices.push_back(i_int*6+4); vertB.vertices.push_back(i_int*6+5);\n    verts.push_back(vertB);\n  }\n  \n  /* \n  std::cout << \"blah\\n\";\n  std::cout << verts[0] << \" 0verts\\n\";\n  std::cout << verts[1] << \" 1verts\\n\";\n  std::cout << pts->points[0] << \" pts\\n\";\n  */  \n  mesh_ptr->polygons = verts;\n  pcl::toPCLPointCloud2 (*pts, mesh_ptr->cloud);  \n  //std::cout << *mesh_ptr << \"\\n\";\n  return mesh_ptr;\n}\n\n\npcl::PolygonMesh::Ptr rgbd_primitives::getCube(double xdim, double ydim, double zdim){ \n  pcl::PolygonMesh mesh;   \n  pcl::PolygonMesh::Ptr mesh_ptr (new pcl::PolygonMesh (mesh));  \n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr pts (new pcl::PointCloud<pcl::PointXYZRGB> ());\n  std::vector <pcl::Vertices> verts;\n  \n  int i_int=0;\n  \n  // Top and Bottom:\n  for (double z=0 ; z <= zdim; z=z+zdim, i_int++){\n    pcl::PointXYZRGB pt1, pt2, pt3, pt4, pt5, pt6;\n    pt1.x = 0;       pt1.y = 0;    pt1.z = z;  \n    pt2.x = 0;       pt2.y = ydim; pt2.z = z; \n    pt3.x = xdim;    pt3.y = ydim; pt3.z = z;\n    pt4.x = xdim ; pt4.y =ydim; pt4.z = z;\n    pt5.x = xdim ; pt5.y =0   ; pt5.z = z;\n    pt6.x =  0   ; pt6.y =0   ; pt6.z = z;\n    set_color(pt1); set_color(pt2); set_color(pt3); set_color(pt4); set_color(pt5); set_color(pt6);\n    pts->points.push_back(pt1);    pts->points.push_back(pt2);\n    pts->points.push_back(pt3);    pts->points.push_back(pt4);\n    pts->points.push_back(pt5);    pts->points.push_back(pt6);\n    pcl::Vertices vert;\n    vert.vertices.push_back(i_int*6 ); vert.vertices.push_back(i_int*6+1); vert.vertices.push_back(i_int*6+2);\n    verts.push_back(vert);\n    pcl::Vertices vertB;\n    vertB.vertices.push_back(i_int*6 +3); vertB.vertices.push_back(i_int*6+4); vertB.vertices.push_back(i_int*6+5);\n    verts.push_back(vertB);    \n  }\n  \n  // Front and Back\n  for (double x=0 ; x <= xdim; x=x+xdim, i_int++){\n    pcl::PointXYZRGB pt1, pt2, pt3, pt4, pt5, pt6;\n    pt1.z = 0;       pt1.y = 0   ; pt1.x = x;  \n    pt2.z = 0;       pt2.y = ydim; pt2.x = x; \n    pt3.z = zdim;    pt3.y = ydim; pt3.x = x;\n    pt4.z = zdim;    pt4.y =ydim ; pt4.x = x;\n    pt5.z = zdim;    pt5.y =0    ; pt5.x = x;\n    pt6.z =  0;      pt6.y =0    ; pt6.x = x;\n    set_color(pt1); set_color(pt2); set_color(pt3); set_color(pt4); set_color(pt5); set_color(pt6);\n    pts->points.push_back(pt1);    pts->points.push_back(pt2);\n    pts->points.push_back(pt3);    pts->points.push_back(pt4);\n    pts->points.push_back(pt5);    pts->points.push_back(pt6);\n    pcl::Vertices vert;\n    vert.vertices.push_back(i_int*6 ); vert.vertices.push_back(i_int*6+1); vert.vertices.push_back(i_int*6+2);\n    verts.push_back(vert);\n    pcl::Vertices vertB;\n    vertB.vertices.push_back(i_int*6 +3); vertB.vertices.push_back(i_int*6+4); vertB.vertices.push_back(i_int*6+5);\n    verts.push_back(vertB);    \n  }  \n  \n  // Left and Right\n  for (double y=0 ; y <= ydim; y=y+ydim, i_int++){\n    pcl::PointXYZRGB pt1, pt2, pt3, pt4, pt5, pt6;\n    pt1.x = 0;       pt1.z = 0  ;  pt1.y = y;  \n    pt2.x = 0;       pt2.z =zdim;  pt2.y = y; \n    pt3.x = xdim;    pt3.z =zdim;  pt3.y = y;\n    pt4.x = xdim ;   pt4.z =zdim;  pt4.y = y;\n    pt5.x = xdim ;   pt5.z =0   ;  pt5.y = y;\n    pt6.x =  0   ;   pt6.z =0   ;  pt6.y = y;\n    set_color(pt1); set_color(pt2); set_color(pt3); set_color(pt4); set_color(pt5); set_color(pt6);\n    pts->points.push_back(pt1);    pts->points.push_back(pt2);\n    pts->points.push_back(pt3);    pts->points.push_back(pt4);\n    pts->points.push_back(pt5);    pts->points.push_back(pt6);\n    pcl::Vertices vert;\n    vert.vertices.push_back(i_int*6 ); vert.vertices.push_back(i_int*6+1); vert.vertices.push_back(i_int*6+2);\n    verts.push_back(vert);\n    pcl::Vertices vertB;\n    vertB.vertices.push_back(i_int*6 +3); vertB.vertices.push_back(i_int*6+4); vertB.vertices.push_back(i_int*6+5);\n    verts.push_back(vertB);    \n  }    \n  \n  /* \n  std::cout << \"blah\\n\";\n  std::cout << verts[0] << \" 0verts\\n\";\n  std::cout << verts[1] << \" 1verts\\n\";\n  std::cout << pts->points[0] << \" pts\\n\";\n  */  \n  mesh_ptr->polygons = verts;\n  pcl::toPCLPointCloud2 (*pts, mesh_ptr->cloud);  \n  //std::cout << *mesh_ptr << \"\\n\";\n  return mesh_ptr;\n}\n\n\n// Get a Sphere polygon mesh\n// NB: uses getCylinder to get slices of the cylinder\npcl::PolygonMesh::Ptr rgbd_primitives::getSphere(double radius){\n  pcl::PolygonMesh::Ptr mesh_ptr (new pcl::PolygonMesh ());  \n\n  // TODO: this would be much more efficient if the getCylinder() \n  // and mergePolygonMesh methods didn't convert between PCL types many times\n  \n  // TODO: this has a fixed set of 18 stacks and doesnt use the parameter\n  // I should modify this code to support that\n  for (int d=-90; d <=80; d=d+10){ \n    double  h0 =  radius * sin( d*M_PI/180);\n    double w0 = sqrt(radius*radius - h0*h0);\n  \n    double h1 =  radius * sin( (d+10)*M_PI/180);\n    double w1 = sqrt(radius*radius - h1*h1);\n\n    pcl::PolygonMesh::Ptr mesh_base_lid = getCylinder(w0 ,w1, h0, h1, 36,1);\n    mergePolygonMesh(mesh_ptr, mesh_base_lid);  \n  }\n   \n  return mesh_ptr;\n}\n\ndouble areaOfTriangle(pcl::PointXYZRGB p0, pcl::PointXYZRGB p1, pcl::PointXYZRGB p2){\n  // heron's formula\n  double d01 = sqrt( pow(p0.x-p1.x,2) + pow(p0.y-p1.y,2) + pow(p0.z-p1.z,2) );\n  double d02 = sqrt( pow(p0.x-p2.x,2) + pow(p0.y-p2.y,2) + pow(p0.z-p2.z,2) );\n  double d12 = sqrt( pow(p1.x-p2.x,2) + pow(p1.y-p2.y,2) + pow(p1.z-p2.z,2) );\n  double p = ( d01 + d02 + d12 ) /2.0;\n  return sqrt(p*(p- d01)*(p- d02)*(p- d12));\n}\n\npcl::PointCloud<pcl::PointXYZRGB>::Ptr rgbd_primitives::sampleMesh(pcl::PolygonMesh::Ptr &mesh, double pts_per_msquared){\n  // this functions samples points per triangle - so will be biased against small sized of triangles\n  // TODO: fix this!\n  \n  int N_polygonsB = mesh->polygons.size ();\n  pcl::PointCloud<pcl::PointXYZRGB> cloudB;  \n  pcl::fromPCLPointCloud2(mesh->cloud, cloudB);\n  Eigen::Vector4f tmp;\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr pts (new pcl::PointCloud<pcl::PointXYZRGB> ());\n  for(size_t i=0; i< N_polygonsB; i++){ // each triangle/polygon N_polygonsB\n    pcl::Vertices apoly_in = mesh->polygons[i];\n    double area = areaOfTriangle(cloudB.points[ apoly_in.vertices[0] ] , \n                                          cloudB.points[ apoly_in.vertices[1] ] ,\n                                          cloudB.points[ apoly_in.vertices[2] ]);\n    \n    // determine the number of points to sample on the surface:\n    int n_pts = floor(area*pts_per_msquared + 0.5);// rounding at .5\n    //std::cout << area << \" - \" << n_pts<< \" | \"<< (area*pts_per_msquared) << \" | \" << pts_per_msquared<< \"\\n\";\n    for (size_t i=0;i <n_pts; i++){\n      pcl::PointXYZRGB     pt;\n      pt = samplePointInTriangle(  cloudB.points[ apoly_in.vertices[0] ] , \n                                          cloudB.points[ apoly_in.vertices[1] ] ,\n                                          cloudB.points[ apoly_in.vertices[2] ] );\n      pts->points.push_back(pt);\n    }\n  } \n  pts->width = pts->points.size();\n  pts->height = 1;\n  \n  return pts;\n}\n\n//% from wykobi library\n// sample a random point inside a triangle\npcl::PointXYZRGB  rgbd_primitives::samplePointInTriangle(pcl::PointXYZRGB p0, pcl::PointXYZRGB p1,\n                                             pcl::PointXYZRGB p2){\n  double a = rand01(); // 0-1\n  double b = rand01(); // 0-1\n  if ((a + b) > 1){\n    a=1-a;\n    b=1-b;\n  }\n  double c = (1 - a - b);\n  \n  pcl::PointXYZRGB pt;\n  pt.x = p0.x * a + p1.x * b + p2.x * c ;\n  pt.y = p0.y * a + p1.y * b + p2.y * c ;\n  pt.z = p0.z * a + p1.z * b + p2.z * c ;\n  return pt;\n}", "meta": {"hexsha": "bc1f36f3f9c7d643bc2208397c21581c28b76932", "size": 15038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/perception/rgbd_simulation/src/rgbd_primitives/rgbd_primitives.cpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/perception/rgbd_simulation/src/rgbd_primitives/rgbd_primitives.cpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/perception/rgbd_simulation/src/rgbd_primitives/rgbd_primitives.cpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 40.3163538874, "max_line_length": 140, "alphanum_fraction": 0.6417076739, "num_tokens": 4686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.03258974793716634, "lm_q1q2_score": 0.012544189766685544}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n  =============================================================================*/\n\n/*!\n * \\file niftkBreastDensityFromMRIs.cxx \n * \\page niftkBreastDensityFromMRIs\n * \\section niftkBreastDensityFromMRIsSummary niftkBreastDensityFromMRIs\n * \n * Compute breast density for directories of DICOM MR images\n *\n */\n\n\n#include <string>\n#include <vector>\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n\n#include <QProcess>\n#include <QString>\n#include <QDebug>\n\n#include <boost/filesystem/path.hpp>\n#include <boost/iostreams/tee.hpp>\n#include <boost/iostreams/stream.hpp>\n\n#include <niftkFileHelper.h>\n#include <niftkConversionUtils.h>\n#include <niftkCSVRow.h>\n#include <niftkEnvironmentHelper.h>\n\n#include <itkCommandLineHelper.h>\n#include <itkImage.h>\n#include <itkImageFileReader.h>\n#include <itkImageSeriesReader.h>\n#include <itkImageFileWriter.h>\n#include <itkNifTKImageIOFactory.h>\n#include <itkWriteImage.h>\n#include <itkReadImage.h>\n#include <itkConversionUtils.h>\n#include <itkImageRegionIterator.h>\n#include <itkImageRegionIteratorWithIndex.h>\n#include <itkInvertIntensityBetweenMaxAndMinImageFilter.h>\n#include <itkMaskImageFilter.h>\n#include <itkCastImageFilter.h>\n#include <itkOrientImageFilter.h>\n#include <itkSampleImageFilter.h>\n#include <itkBinaryShapeBasedSuperSamplingFilter.h>\n#include <itkIsImageBinary.h>\n#include <itkRescaleIntensityImageFilter.h>\n\n//#define LINK_TO_SEG_EM\n\n#ifdef LINK_TO_SEG_EM\n#include <_seg_EM.h>\n#endif\n\n#include <niftkBreastDensityFromMRIsGivenMaskAndImageCLP.h>\n\n#define SegPrecisionTYPE float\n\nnamespace fs = boost::filesystem;\n\nnamespace bio = boost::iostreams;\nusing bio::tee_device;\nusing bio::stream;\n\n\ntypedef itk::MetaDataDictionary DictionaryType;\ntypedef itk::MetaDataObject< std::string > MetaDataStringType;\n\ntypedef float PixelType;\nconst unsigned int   Dimension = 3;\n\ntypedef itk::Image< PixelType, Dimension > ImageType;\ntypedef itk::Image< PixelType, 4 > ImageType4D;\n\n\n\n\n// -------------------------------------------------------------------------\n// CreateFilename()\n// -------------------------------------------------------------------------\n\nstd::string CreateFilename( std::string fileOne, \n                            std::string fileTwo,\n                            std::string description,\n                            std::string suffix ) \n{\n  std::string fileOneWithoutSuffix;\n  niftk::ExtractImageFileSuffix( fileOne, fileOneWithoutSuffix );\n\n  std::string fileTwoWithoutSuffix;\n  niftk::ExtractImageFileSuffix( fileTwo, fileTwoWithoutSuffix );\n\n  return fileOneWithoutSuffix + \"_\" + description + \"_\" + fileTwoWithoutSuffix + suffix;\n};\n\n\n// -------------------------------------------------------------------------\n// PrintOrientationInfo()\n// -------------------------------------------------------------------------\n\nvoid PrintOrientationInfo( ImageType::Pointer image )\n{\n  itk::SpatialOrientationAdapter adaptor;\n  ImageType::DirectionType direction;\n\n  for (unsigned int i = 0; i < Dimension; i++)\n  {\n    for (unsigned int j = 0; j < Dimension; j++)\n    {\n      direction[i][j] = image->GetDirection()[i][j];\n    }\n  }\n\n  std::cout << \"Image direction: \" << std::endl\n\t    << direction;\n\n  std::cout << \"ITK orientation: \" \n\t    << itk::ConvertSpatialOrientationToString(adaptor.FromDirectionCosines(direction)) \n\t    << std::endl;\n}\n\n\n// -------------------------------------------------------------------------\n// GetOrientation()\n// -------------------------------------------------------------------------\n\nitk::SpatialOrientation::ValidCoordinateOrientationFlags GetOrientation( ImageType::Pointer image )\n{\n  ImageType::DirectionType direction;\n  itk::SpatialOrientationAdapter adaptor;\n\n  for (unsigned int i = 0; i < Dimension; i++)\n  {\n    for (unsigned int j = 0; j < Dimension; j++)\n    {\n      direction[i][j] = image->GetDirection()[i][j];\n    }\n  }\n\n  return adaptor.FromDirectionCosines(direction);\n}\n\n\n// -------------------------------------------------------------------------\n// ReorientateImage()\n// -------------------------------------------------------------------------\n\nImageType::Pointer ReorientateImage( ImageType::Pointer image, \n                                     itk::SpatialOrientation::ValidCoordinateOrientationFlags desiredOrientation )\n{\n  std::cout << std::endl << \"Input image:\" << std::endl;\n  //image->Print( std::cout );\n  PrintOrientationInfo( image );\n\n  std::cout << \"Desired orientation: \" << itk::ConvertSpatialOrientationToString( desiredOrientation )\n            << std::endl;\n\n  typedef itk::OrientImageFilter<ImageType,ImageType> OrientImageFilterType;\n  OrientImageFilterType::Pointer orienter = OrientImageFilterType::New();\n\n  orienter->UseImageDirectionOn();\n  orienter->SetDesiredCoordinateOrientation( desiredOrientation );\n  orienter->SetInput( image );\n\n  orienter->Update();\n\n  typedef OrientImageFilterType::FlipAxesArrayType FlipAxesArrayType;\n  typedef OrientImageFilterType::PermuteOrderArrayType PermuteOrderArrayType;\n\n  FlipAxesArrayType flipAxes = orienter->GetFlipAxes();\n  PermuteOrderArrayType permuteAxes = orienter->GetPermuteOrder();\n\n  std::cout << std::endl\n            << \"Permute Axes: \" << permuteAxes << std::endl\n            << \"Flip Axes: \"    << flipAxes << std::endl;\n\n  ImageType::Pointer reorientatedImage = orienter->GetOutput();\n  //reorientatedImage->DisconnectPipeline();\n\n  std::cout << std::endl << \"Output image:\" << std::endl;\n  //reorientatedImage->Print( std::cout );\n  PrintOrientationInfo( reorientatedImage );\n\n  return reorientatedImage;\n};\n\n\n// -------------------------------------------------------------------------\n// ReorientateImage()\n// -------------------------------------------------------------------------\n\nImageType::Pointer ReorientateImage( ImageType::Pointer image, ImageType::Pointer reference )\n{\n  itk::SpatialOrientation::ValidCoordinateOrientationFlags desiredOrientation;\n\n  std::cout << std::endl << \"Reference image:\" << std::endl;\n  //reference->Print( std::cout );\n  PrintOrientationInfo( reference );\n\n  desiredOrientation = GetOrientation( reference );\n\n  return ReorientateImage( image, desiredOrientation );\n}\n\n\n// -------------------------------------------------------------------------\n// class InputParameters\n// -------------------------------------------------------------------------\n\nclass InputParameters\n{\n\npublic:\n\n  bool flgVerbose;\n  bool flgDebug;\n  bool flgCompression;\n  bool flgOverwrite;\n  bool flgFatIsBright;\n\n  std::string dirInput;\n  std::string dirOutput;\n\n  std::string fileLog;\n  std::string fileOutputCSV;\n\n  std::string fileMaskPattern;  \n  std::string fileImagePattern;  \n\n  std::string dirMask;  \n  std::string dirImage;  \n\n  std::string dirSubData;  \n  std::string dirPrefix;  \n\n  std::string progSegEM;\n\n  QStringList argsSegEM;\n\n  std::ofstream *foutLog;\n  std::ofstream *foutOutputCSV;\n  std::ostream *newCout;\n\n  typedef tee_device<std::ostream, std::ofstream> TeeDevice;\n  typedef stream<TeeDevice> TeeStream;\n\n  TeeDevice *teeDevice;\n  TeeStream *teeStream;\n\n  InputParameters( TCLAP::CmdLine &commandLine, \n\n                   bool verbose, \n                   bool compression, \n                   bool debug, \n                   bool overwrite,\n                   bool fatIsBright,\n\n                   std::string subDirMask, \n                   std::string fileMask,\n                   std::string subDirImage, \n                   std::string fileImage,\n\n                   std::string subDirData, \n                   std::string prefix, \n                   std::string dInput,\n\n                   std::string logfile, \n                   std::string csvfile,\n\n                   std::string segEM,       \n                   QStringList aSegEM ) {\n\n    std::stringstream message;\n\n    flgVerbose = verbose;\n    flgDebug = debug;\n    flgCompression = compression;\n    flgOverwrite = overwrite;\n    flgFatIsBright = fatIsBright;\n\n    dirMask  = subDirMask;\n    fileMaskPattern = fileMask;\n    dirImage = subDirImage;\n    fileImagePattern = fileImage;\n\n    dirSubData = subDirData;\n    dirPrefix  = prefix;\n    dirInput   = dInput;\n\n    fileLog = logfile;\n    fileOutputCSV = csvfile;\n\n    progSegEM       = segEM;\n    argsSegEM       = aSegEM;\n\n    if ( fileLog.length() > 0 )\n    {\n      foutLog = new std::ofstream( fileLog.c_str() );\n\n      if ((! *foutLog) || foutLog->bad()) {\n        message << \"Could not open file: \" << fileLog << std::endl;\n        PrintErrorAndExit( message );\n      }\n\n      newCout = new std::ostream( std::cout.rdbuf() );\n\n      teeDevice = new TeeDevice( *newCout, *foutLog); \n      teeStream = new TeeStream( *teeDevice );\n\n      std::cout.rdbuf( teeStream->rdbuf() );\n      std::cerr.rdbuf( teeStream->rdbuf() );\n    }\n    else\n    {\n      foutLog = 0;\n      newCout = 0;\n      teeDevice = 0;\n      teeStream = 0;\n    }\n\n    if ( fileOutputCSV.length() > 0 )\n    {\n      foutOutputCSV = new std::ofstream( fileOutputCSV.c_str() );\n\n      if ((! *foutOutputCSV) || foutOutputCSV->bad()) {\n        message << \"Could not open file: \" << fileOutputCSV << std::endl;\n        PrintErrorAndExit( message );\n      }\n    }\n    else\n    {\n      foutOutputCSV = 0;\n    }\n\n    \n    if ( dirInput.length() == 0 )\n    {\n      commandLine.getOutput()->usage( commandLine );\n      message << \"The input directory must be specified\" << std::endl;\n      PrintErrorAndExit( message );\n    }\n\n  }\n\n  ~InputParameters() {\n#if 0\n    if ( teeStream )\n    {\n      teeStream->flush();\n      teeStream->close();\n      delete teeStream;\n    }\n\n    if ( teeDevice )\n    {\n      delete teeDevice;\n    }\n\n    if ( foutLog )\n    {\n      foutLog->close();\n      delete foutLog;\n    }\n\n    if ( foutOutputCSV )\n    {\n      foutOutputCSV->close();\n      delete foutOutputCSV;\n    }    \n\n    if ( newCout )\n    {\n      delete newCout;\n    }\n#endif\n  }\n\n  void Print(void) {\n\n    std::stringstream message;\n\n    message << std::endl\n            << \"Examining directory: \" << dirInput << std::endl \n            << std::endl\n            << std::boolalpha\n            << \"Verbose output?: \"             << flgVerbose        << std::endl\n            << \"Compress images?: \"            << flgCompression    << std::endl\n            << \"Debugging output?: \"           << flgDebug          << std::endl\n            << \"Overwrite previous results?: \" << flgOverwrite      << std::endl       \n            << \"Fat is bright?: \"              << flgFatIsBright    << std::endl       \n            << std::noboolalpha\n            << std::endl\n            << \"Input mask sub-directory: \" << dirMask << std::endl\n            << \"Input mask file name pattern: \" << fileMaskPattern << std::endl\n            << \"Input image sub-directory: \" << dirImage << std::endl\n            << \"Input image file name pattern: \" << fileMaskPattern << std::endl\n            << \"Output data sub-directory: \" << dirSubData << std::endl\n            << \"Study directory prefix: \" << dirPrefix << std::endl\n            << std::endl\n            << \"Output log file: \" << fileLog << std::endl\n            << \"Output csv file: \" << fileOutputCSV << std::endl\n            << std::endl\n            << \"Segmentation executable: \"\n            << progSegEM       << \" \" << argsSegEM.join(\" \").toStdString() << std::endl\n            << std::endl;\n\n    PrintMessage( message );\n  }\n    \n  void PrintMessage( std::stringstream &message ) {\n\n    std::cout << message.str();\n    message.str( \"\" );\n    if ( teeStream )\n    {\n      teeStream->flush();\n    }\n  }\n    \n  void PrintError( std::stringstream &message ) {\n\n    std::cerr << \"ERROR: \" << message.str();\n    message.str( \"\" );\n    if ( teeStream )\n    {\n      teeStream->flush();\n    }\n  }\n    \n  void PrintErrorAndExit( std::stringstream &message ) {\n\n    PrintError( message );\n\n    exit( EXIT_FAILURE );\n  }\n    \n  void PrintWarning( std::stringstream &message ) {\n\n    std::cerr << \"WARNING: \" << message.str();\n    message.str( \"\" );\n    if ( teeStream )\n    {\n      teeStream->flush();\n    }\n  }\n\n  bool ReadImageFromFile( std::string fileInput, \n                          std::string description, ImageType::Pointer &image ) {\n  \n    std::stringstream message;\n\n    if ( fileInput.find( \".nii\" ) == std::string::npos )\n    {\n      return false;\n    }\n\n    if ( itk::ReadImageFromFile< ImageType >( fileInput, image ) )\n    {   \n      message << std::endl << \"Read \" << description << \" from file: \" << fileInput << std::endl;\n      PrintMessage( message );\n    }\n    else if ( itk::ReadImageFromFile< ImageType >( fileInput + \".gz\", image ) )\n    {   \n      message << std::endl << \"Read \" << description << \" from file: \" << fileInput << std::endl;\n      PrintMessage( message );\n    }\n    else\n    {\n      return false;\n    }\n\n    itk::SpatialOrientation::ValidCoordinateOrientationFlags orientation;\n\n    orientation = GetOrientation( image );\n\n    if ( orientation !=  itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI )\n    {\n      image = ReorientateImage( image, itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI );\n    }\n\n    return true;\n  }\n\n  bool ReadImageFromFile( std::string dirInput, std::string filename, \n                          std::string description, ImageType::Pointer &image ) {\n  \n    std::string fileInput = niftk::ConcatenatePath( dirInput, filename );               \n\n    return ReadImageFromFile( fileInput, description, image );\n  }\n\n  void WriteImageToFile( std::string filename, \n                         std::string description, ImageType::Pointer image,\n                         bool flgConcatenatePath=true ) {\n  \n    std::stringstream message;\n    std::string fileOutput;\n\n    if ( flgConcatenatePath )\n    {\n      fileOutput = niftk::ConcatenatePath( dirOutput, filename );\n    }\n    else\n    {\n      fileOutput = filename;\n    }\n              \n    message << std::endl << \"Writing \" << description << \" to file: \"\n            << fileOutput << std::endl;\n    PrintMessage( message );\n\n\n    if ( itk::IsImageBinary< ImageType >( image ) )\n    {\n      typedef unsigned char OutputPixelType;\n      typedef itk::Image< OutputPixelType, ImageType::ImageDimension> OutputImageType;\n\n      typedef itk::RescaleIntensityImageFilter< ImageType, OutputImageType > CastFilterType;\n\n      CastFilterType::Pointer caster = CastFilterType::New();\n\n      caster->SetInput( image );\n      caster->SetOutputMinimum(   0 );\n      caster->SetOutputMaximum( 255 );\n      caster->Update();\n\n      OutputImageType::Pointer imOut = caster->GetOutput();\n\n      itk::WriteImageToFile< OutputImageType >( fileOutput, imOut );      \n    }\n    else\n    {\n      itk::WriteImageToFile< ImageType >( fileOutput, image );\n    }\n  }\n\n  void DeleteFile( std::string filename ) {\n\n    std::stringstream message;\n    std::string filePath = niftk::ConcatenatePath( dirOutput, filename );\n\n    if ( ! niftk::FileIsRegular( filePath ) )\n    {\n      return;\n    }\n\n    if ( niftk::FileDelete( filePath ) )\n    {\n      message << std::endl << \"Deleted file: \" << filePath << std::endl;\n      PrintMessage( message );\n    }\n    else\n    {\n      message << std::endl << \"Failed to delete file: \" << filePath << std::endl;\n      PrintWarning( message );\n    }      \n  }\n\n};\n\n\n\n// -------------------------------------------------------------------------\n// SplitStringIntoCommandAndArguments()\n// -------------------------------------------------------------------------\n\nstd::string SplitStringIntoCommandAndArguments( std::string inString,\n                                                QStringList &arguments )\n{\n  std::string command;\n\n  std::stringstream ssString( inString );\n\n  std::istream_iterator< std::string > itStringStream( ssString );\n  std::istream_iterator< std::string > itEnd;\n\n  command = *itStringStream;\n  itStringStream++;\n  \n  for (; itStringStream != itEnd; itStringStream++)\n  {\n    arguments << (*itStringStream).c_str();\n  }\n\n  return command;\n};\n\n\n// -------------------------------------------------------------------------\n// ResampleImageToIsotropicVoxels()\n// -------------------------------------------------------------------------\n\nbool ResampleImageToIsotropicVoxels( ImageType::Pointer &image, InputParameters &args )\n{\n  std::stringstream message;\n\n  double factor[Dimension];\n\n  ImageType::SpacingType spacing = image->GetSpacing();\n\n  // Calculate the minimum spacing\n\n  double minSpacing = std::numeric_limits<double>::max();\n\n  for (unsigned int j = 0; j < ImageType::ImageDimension; j++)\n  {\n    if ( spacing[j] < minSpacing )\n    {\n      minSpacing = spacing[j];\n    }\n  }\n\n  // Calculate the subsampling factors\n\n  bool flgSamplingRequired = false;\n\n  for (unsigned int j = 0; j < ImageType::ImageDimension; j++)\n  {\n    factor[j] = minSpacing/spacing[j];\n\n    if ( factor[j] < 0.8 )\n    {\n      flgSamplingRequired = true;\n    }\n  }\n\n  // Run the sampling filter\n\n  if ( itk::IsImageBinary< ImageType >(image) )\n  {\n    typedef itk::BinaryShapeBasedSuperSamplingFilter< ImageType, ImageType > SampleImageFilterType;\n\n    SampleImageFilterType::Pointer sampler = SampleImageFilterType::New();\n\n    sampler->SetIsotropicVoxels( true );\n\n    sampler->SetInput( image );\n\n    sampler->VerboseOn();\n\n    message << \"Computing sampled binary image\" << std::endl;\n    args.PrintMessage( message );\n\n    sampler->Update();\n\n    ImageType::Pointer sampledImage = sampler->GetOutput();\n    sampledImage->DisconnectPipeline();\n\n    image = sampledImage;\n  }\n  else\n  {\n    typedef itk::SampleImageFilter< ImageType, ImageType > SampleImageFilterType;\n\n    SampleImageFilterType::Pointer sampler = SampleImageFilterType::New();\n\n    sampler->SetIsotropicVoxels( true );\n    sampler->SetInterpolationType( itk::NEAREST );\n\n    sampler->SetInput( image );\n\n    sampler->VerboseOn();\n\n    message << \"Computing sampled image\" << std::endl;\n    args.PrintMessage( message );\n\n    sampler->Update();\n\n    ImageType::Pointer sampledImage = sampler->GetOutput();\n    sampledImage->DisconnectPipeline();\n\n    image = sampledImage;\n  }\n\n  return true;\n};\n\n\n// -------------------------------------------------------------------------\n// NaiveParenchymaSegmentation()\n// -------------------------------------------------------------------------\n\nvoid NaiveParenchymaSegmentation( InputParameters &args, \n                        \n                                  ImageType::Pointer &imSegmentedBreastMask,\n                                  ImageType::Pointer &image,\n                                  \n                                  bool flgFatIsBright,\n\n                                  float &nLeftVoxels,\n                                  float &nRightVoxels,                                  \n\n                                  float &totalDensity,\n                                  float &leftDensity,\n                                  float &rightDensity,\n\n                                  std::string fileOutputParenchyma )\n{\n  float minFraction = 0.02;\n\n  std::stringstream message;\n\n  ImageType::Pointer imParenchyma = 0;\n\n  typedef itk::ImageDuplicator< ImageType > DuplicatorType; \n    \n  DuplicatorType::Pointer duplicator = DuplicatorType::New();\n\n  duplicator->SetInputImage( image );\n  duplicator->Update();\n\n  imParenchyma = duplicator->GetOutput();\n  imParenchyma->DisconnectPipeline();\n\n  imParenchyma->FillBuffer( 0. );\n\n  nLeftVoxels = 0;\n  nRightVoxels = 0;\n\n  totalDensity = 0.;\n  leftDensity = 0.;\n  rightDensity = 0.;\n\n  float meanOfHighProbIntensities = 0.;\n  float meanOfLowProbIntensities = 0.;\n\n  float nHighProbIntensities = 0.;\n  float nLowProbIntensities = 0.;\n\n  itk::ImageRegionIteratorWithIndex< ImageType > \n    itMask( imSegmentedBreastMask, imSegmentedBreastMask->GetLargestPossibleRegion() );\n\n  itk::ImageRegionIterator< ImageType > \n    itSegmentation( imParenchyma, imParenchyma->GetLargestPossibleRegion() );\n\n  itk::ImageRegionConstIterator< ImageType > \n    itImage( image, image->GetLargestPossibleRegion() );\n\n  \n  // Compute the range of intensities inside the mask\n  \n  float minIntensity = std::numeric_limits< float >::max();\n  float maxIntensity = -std::numeric_limits< float >::max();\n\n  for ( itMask.GoToBegin(), itImage.GoToBegin();\n        ! itMask.IsAtEnd();\n        ++itMask, ++itImage )\n  {\n    if ( itMask.Get() )\n    {\n      if ( itImage.Get() > maxIntensity )\n      {\n        maxIntensity = itImage.Get();\n      }\n\n      if ( itImage.Get() < minIntensity )\n      {\n        minIntensity = itImage.Get();\n      }\n    }\n  }\n\n  message  << std::endl\n           << \"Range of \" << \" is from: \" \n           << minIntensity << \" to: \" << maxIntensity << std::endl;\n  args.PrintMessage( message );\n  \n\n  // Compute 1st and 99th percentiles of the image from the image histogram\n\n  unsigned int nBins = static_cast<unsigned int>( maxIntensity - minIntensity + 0.5 ) + 1;\n\n  itk::Array< float > histogram( nBins );\n    \n  histogram.Fill( 0 );\n\n  float nPixels = 0;\n  float flIntensity;\n\n  for ( itImage.GoToBegin(), itMask.GoToBegin();\n        ! itImage.IsAtEnd();\n        ++itImage, ++itMask )\n  {\n    if ( itMask.Get() )\n    {\n      flIntensity = itImage.Get() - minIntensity;\n      \n      if ( flIntensity < 0. )\n      {\n        flIntensity = 0.;\n      }\n      \n      if ( flIntensity > static_cast<float>( nBins - 1 ) )\n      {\n        flIntensity = static_cast<float>( nBins - 1 );\n      }\n      \n      nPixels++;\n      histogram[ static_cast<unsigned int>( flIntensity ) ] += 1.;\n    }\n  }\n    \n  float sumProbability = 0.;\n  unsigned int intensity;\n\n  float pLowerBound = 0.;\n  float pUpperBound = 0.;\n\n  bool flgLowerBoundFound = false;\n  bool flgUpperBoundFound = false;\n\n\n  for ( intensity=0; intensity<nBins; intensity++ )\n  {\n    histogram[ intensity ] /= nPixels;\n    sumProbability += histogram[ intensity ];\n\n    if ( ( ! flgLowerBoundFound ) && ( sumProbability >= minFraction ) )\n    {\n      pLowerBound = intensity;\n      flgLowerBoundFound = true;\n    }\n\n    if ( ( ! flgUpperBoundFound ) && ( sumProbability >= (1. - minFraction) ) )\n    {\n      pUpperBound = intensity;\n      flgUpperBoundFound = true;\n    }\n    \n    if ( args.flgDebug )\n    {\n      std::cout << std::setw( 18 ) << intensity << \" \" \n                << std::setw( 18 ) << histogram[ intensity ]  << \" \" \n                << std::setw( 18 ) << sumProbability << std::endl;\n    }\n  }\n  \n  message << std::endl\n          << \"Density lower bound: \" << pLowerBound \n          << \" ( \" << minFraction*100. << \"% )\" << std::endl\n          << \" upper bound: \" << pUpperBound \n          << \" ( \" << (1. - minFraction)*100. << \"% )\" << std::endl;\n  args.PrintMessage( message );\n  \n\n  // Compute the density\n\n  ImageType::SpacingType spacing = imParenchyma->GetSpacing();\n\n  float voxelVolume = spacing[0]*spacing[1]*spacing[2];\n\n  ImageType::RegionType region;\n  region = imSegmentedBreastMask->GetLargestPossibleRegion();\n\n  ImageType::SizeType lateralSize;\n  lateralSize = region.GetSize();\n  lateralSize[0] = lateralSize[0]/2;\n\n  ImageType::IndexType idx;\n   \n  for ( itMask.GoToBegin(), itSegmentation.GoToBegin(), itImage.GoToBegin();\n        ! itMask.IsAtEnd();\n        ++itMask, ++itSegmentation, ++itImage )\n  {\n    if ( itMask.Get() )\n    {\n      idx = itMask.GetIndex();\n\n      flIntensity = ( itImage.Get() - pLowerBound )/( pUpperBound - pLowerBound );\n      \n      if ( flIntensity < 0. )\n      {\n        itSegmentation.Set( 0. );\n      }\n      else if ( flIntensity > 1. )\n      {\n        itSegmentation.Set( 1. );\n      }\n      else\n      {\n        itSegmentation.Set( flIntensity );\n      }\n\n      //std::cout << idx << \" \" << itImage.Get() << \" -> \" << flIntensity << std::endl;\n\n      // Left breast\n\n      if ( idx[0] < (int) lateralSize[0] )\n      {\n        nLeftVoxels++;\n        leftDensity += flIntensity;\n      }\n\n      // Right breast\n      \n      else \n      {\n        nRightVoxels++;\n        rightDensity += flIntensity;\n      }\n\n      // Both breasts\n\n      totalDensity += flIntensity;\n\n      // Ensure we have the polarity correct by calculating the\n      // mean intensities of each class\n\n      if ( flIntensity > 0.5 )\n      {\n        meanOfHighProbIntensities += itImage.Get();\n        nHighProbIntensities++;\n      }\n      else\n      {\n        meanOfLowProbIntensities += itImage.Get();\n        nLowProbIntensities++;\n      }              \n    }\n  }\n\n  leftDensity /= nLeftVoxels;\n  rightDensity /= nRightVoxels;\n  totalDensity /= ( nLeftVoxels + nRightVoxels);\n\n  // Calculate the mean intensities of each class\n  \n  if ( nHighProbIntensities > 0. )\n  {\n    meanOfHighProbIntensities /= nHighProbIntensities;\n  }\n  \n  if ( nLowProbIntensities > 0. )\n  {\n    meanOfLowProbIntensities /= nLowProbIntensities;\n  }\n\n  message  << std::endl\n           << \"Mean intensity of high probability class = \" << meanOfHighProbIntensities\n           << \" ( \" << nHighProbIntensities << \" voxels )\" << std::endl\n           << \"Mean intensity of low probability class = \" << meanOfLowProbIntensities\n           << \" ( \" << nLowProbIntensities << \" voxels )\" << std::endl;\n  args.PrintMessage( message );\n\n  // Fat should be high intensity in the T2 image so if the dense\n  // region (high prob) has a high intensity then it is probably fat\n  // and we need to invert the density, whereas the opposite is true\n  // for the fat-saturated T1w VIBE image.\n  \n  if ( (     flgFatIsBright   && ( meanOfHighProbIntensities > meanOfLowProbIntensities ) ) ||\n       ( ( ! flgFatIsBright ) && ( meanOfHighProbIntensities < meanOfLowProbIntensities ) ) )\n  {\n    message << \"Inverting the density estimation\" << std::endl;\n    args.PrintWarning( message );\n    \n    leftDensity  = 1. - leftDensity;\n    rightDensity = 1. - rightDensity;\n    totalDensity = 1. - totalDensity;\n    \n    typedef itk::InvertIntensityBetweenMaxAndMinImageFilter< ImageType > InvertFilterType;\n    InvertFilterType::Pointer invertFilter = InvertFilterType::New();\n    invertFilter->SetInput( imParenchyma );\n\n    typedef itk::MaskImageFilter< ImageType, ImageType > MaskFilterType;\n    MaskFilterType::Pointer maskFilter = MaskFilterType::New();\n\n    maskFilter->SetInput( invertFilter->GetOutput() );\n    maskFilter->SetMaskImage( imSegmentedBreastMask );\n    maskFilter->Update();\n\n    ImageType::Pointer imInverted = maskFilter->GetOutput();\n    imInverted->DisconnectPipeline();\n    imParenchyma = imInverted;\n  }\n\n  std::string fileOut = niftk::ModifyImageFileSuffix( fileOutputParenchyma, \n                                                      std::string( \"_Naive.nii\" ) );\n\n  if ( args.flgCompression ) fileOut.append( \".gz\" );\n\n  args.WriteImageToFile( fileOut, \n                         std::string( \"naive parenchyma image\"), imParenchyma );\n\n\n  float leftBreastVolume = nLeftVoxels*voxelVolume;\n  float rightBreastVolume = nRightVoxels*voxelVolume;\n\n  message << \"Naive - Number of left breast voxels: \" << nLeftVoxels << std::endl\n          << \"Naive - Volume of left breast: \" << leftBreastVolume << \" mm^3\" << std::endl\n          << \"Naive - Density of left breast (fraction of glandular tissue): \" << leftDensity \n          << std::endl << std::endl\n    \n          << \"Naive - Number of right breast voxels: \" << nRightVoxels << std::endl\n          << \"Naive - Volume of right breast: \" << rightBreastVolume << \" mm^3\" << std::endl\n          << \"Naive - Density of right breast (fraction of glandular tissue): \" << rightDensity \n          << std::endl << std::endl\n    \n          << \"Naive - Total number of breast voxels: \" \n          << nLeftVoxels + nRightVoxels << std::endl\n          << \"Naive - Total volume of both breasts: \" \n          << leftBreastVolume + rightBreastVolume << \" mm^3\" << std::endl\n          << \"Naive - Combined density of both breasts (fraction of glandular tissue): \" \n          << totalDensity << std::endl << std::endl;\n\n  args.PrintMessage( message );\n};\n\n\n// -------------------------------------------------------------------------\n// main()\n// -------------------------------------------------------------------------\n\nint main( int argc, char *argv[] )\n{\n  itk::NifTKImageIOFactory::Initialize();\n\n  bool flgVeryFirstRow = true;\n\n  float progress = 0.;\n  float iDirectory = 0.;\n  float nDirectories;\n\n  std::stringstream message;\n\n  fs::path pathExecutable( argv[0] );\n  fs::path dirExecutables = pathExecutable.parent_path();\n\n\n\n  // Validate command line args\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  PARSE_ARGS;\n\n  // Extract any arguments from the input commands\n\n  QStringList argsSegEM;\n  std::string progSegEM = SplitStringIntoCommandAndArguments( comSegEM, argsSegEM );\n\n  InputParameters args( commandLine, \n                        \n                        flgVerbose,\n                        flgCompression, \n                        flgDebug, \n                        flgOverwrite,\n                        flgFatIsBright,\n\n                        dirMask,\n                        fileMaskPattern,\n                        dirImage,\n                        fileImagePattern,\n                          \n                        dirSubData,\n                        dirPrefix, \n                        dirInput,\n                          \n                        fileLog, \n                        fileOutputCSV,\n                          \n                        progSegEM,       \n                        argsSegEM );\n\n\n  // Can we find the seg_EM executable or verify the path?\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  if ( ! niftk::FileIsRegular( args.progSegEM ) )\n  {\n    std::string fileSearchSegEM = niftk::ConcatenatePath( dirExecutables.string(), \n                                                          args.progSegEM );\n          \n    if ( niftk::FileIsRegular( fileSearchSegEM ) )\n    {\n      args.progSegEM = fileSearchSegEM;\n    }\n  }\n\n\n  args.Print();\n        \n  std::cout  << std::endl << \"<filter-progress>\" << std::endl\n             << 0. << std::endl\n             << \"</filter-progress>\" << std::endl << std::endl;\n\n\n  // Get the list of files in the directory\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  std::string dirFullPath;\n  std::string dirBaseName;\n\n  std::string dirMaskFullPath;\n  std::string dirImageFullPath;\n\n  std::vector< std::string > directoryNames;\n  std::vector< std::string >::iterator iterDirectoryNames;       \n\n  std::vector< std::string > fileMaskNames;\n  std::vector< std::string >::iterator iterFileMaskNames;       \n\n  std::vector< std::string > fileImageNames;\n  std::vector< std::string >::iterator iterFileImageNames;       \n\n  directoryNames = niftk::GetDirectoriesInDirectory( args.dirInput );\n\n  nDirectories = directoryNames.size();\n\n  for ( iterDirectoryNames = directoryNames.begin(); \n\titerDirectoryNames < directoryNames.end(); \n\t++iterDirectoryNames, iDirectory += 1. )\n  {\n    \n    dirFullPath = *iterDirectoryNames;\n    dirBaseName = niftk::Basename( dirFullPath );\n\n    if ( ! (dirBaseName.compare( 0, args.dirPrefix.length(), args.dirPrefix ) == 0) )\n    {\n      message << std::endl << \"Skipping directory: \" << dirFullPath << std::endl;\n      args.PrintMessage( message );\n      continue;\n    }\n\n    message << std::endl << \"Directory: \" << dirFullPath << std::endl;\n    args.PrintMessage( message );\n\n    \n    // The mask directory\n\n    if ( args.dirMask.length() > 0 )\n    {\n      dirMaskFullPath = niftk::ConcatenatePath( dirFullPath, args.dirMask );\n    }\n    else\n    {\n      dirMaskFullPath = dirFullPath;\n    }\n\n    // The image directory\n\n    if ( args.dirImage.length() > 0 )\n    {\n      dirImageFullPath = niftk::ConcatenatePath( dirFullPath, args.dirImage );\n    }\n    else\n    {\n      dirImageFullPath = dirFullPath;\n    }\n\n    // The output directory\n\n    if ( dirSubData.length() > 0 )\n    {\n      args.dirOutput = niftk::ConcatenatePath( dirFullPath, args.dirSubData );\n    }\n    else\n    {\n      args.dirOutput = dirFullPath;\n    }\n\n    if ( ! niftk::DirectoryExists( args.dirOutput ) )\n    {\n      niftk::CreateDirAndParents( args.dirOutput );\n\n      message << \"Creating output directory: \" << args.dirOutput << std::endl;\n      args.PrintMessage( message );\n    }\n\n\n    // For each mask image\n    // ~~~~~~~~~~~~~~~~~~~\n\n    fileMaskNames = niftk::GetFilesInDirectory( dirMaskFullPath );\n\n    float iMask = 0.;\n    float nMasks = fileMaskNames.size();\n\n    for ( iterFileMaskNames = fileMaskNames.begin(); \n          iterFileMaskNames < fileMaskNames.end(); \n          ++iterFileMaskNames, iMask += 1. )\n    {\n\n      std::string fileMaskFullPath = *iterFileMaskNames;\n      std::string fileMaskBasename = niftk::Basename( fileMaskFullPath );\n\n      if ( fileMaskBasename.find( args.fileMaskPattern ) == std::string::npos )\n      {\n        if ( args.flgDebug )\n        {\n          message << std::endl << \"Skipping non-mask file: \" << fileMaskBasename \n                  << std::endl;\n          args.PrintMessage( message );\n        }\n        continue;\n      }\n\n      // Read the mask image\n\n      ImageType::Pointer imMask = 0;\n\n      if ( ! args.ReadImageFromFile( fileMaskFullPath, \n                                     std::string( \"mask image\" ), \n                                     imMask ) )\n      {\n        if ( args.flgDebug )\n        {\n          message << std::endl << \"Cannot read mask: \" << fileMaskFullPath << std::endl << std::endl;\n          args.PrintMessage( message );\n        }\n        continue;\n      }\n\n      if ( ResampleImageToIsotropicVoxels( imMask, args ) )\n      {\n        fileMaskBasename = niftk::ModifyImageFileSuffix( fileMaskBasename, \n                                                         std::string( \"_Isotropic.nii\" ) );\n\n        fileMaskFullPath = niftk::ConcatenatePath( args.dirOutput, fileMaskBasename );\n\n        if ( flgCompression )\n        {\n          fileMaskFullPath.append( \".gz\" );          \n        }\n\n        args.WriteImageToFile( fileMaskFullPath, \n                               std::string( \"isotropic mask image\" ), \n                               imMask, false );\n      }\n\n\n      // For each image\n      // ~~~~~~~~~~~~~~\n\n      fileImageNames = niftk::GetFilesInDirectory( dirImageFullPath );\n\n      float iImage = 0.;\n      float nImages = fileImageNames.size();\n\n      for ( iterFileImageNames = fileImageNames.begin(); \n            iterFileImageNames < fileImageNames.end(); \n            ++iterFileImageNames, iImage += 1. )\n      {\n\n        std::string fileImageFullPath = *iterFileImageNames;\n        std::string fileImageBasename = niftk::Basename( fileImageFullPath );\n\n        if ( fileImageBasename.find( args.fileImagePattern ) == std::string::npos )\n        {\n          if ( args.flgDebug )\n          {\n            message << std::endl << \"Skipping non-image file: \" << fileImageBasename \n                    << std::endl;\n            args.PrintMessage( message );\n          }\n          continue;\n        }\n\n        // Read the image\n\n        ImageType::Pointer imInput = 0;\n\n        if ( ! args.ReadImageFromFile( fileImageFullPath, \n                                       std::string( \"input image\" ), \n                                       imInput ) )\n        {\n          if ( args.flgDebug )\n          {\n            message << std::endl << \"Cannot read image: \" << fileImageFullPath \n                    << std::endl;\n            args.PrintMessage( message );\n          }\n          continue;\n        }\n\n        if ( ResampleImageToIsotropicVoxels( imInput, args ) )\n        {\n          fileImageBasename = niftk::ModifyImageFileSuffix( fileImageBasename, \n                                                            std::string( \"_Isotropic.nii\" ) );\n\n          fileImageFullPath = niftk::ConcatenatePath( args.dirOutput, fileImageBasename );\n\n          if ( flgCompression )\n          {\n            fileImageFullPath.append( \".gz\" );          \n          }\n          \n          args.WriteImageToFile( fileImageFullPath, \n                                 std::string( \"isotropic image\" ), \n                                 imInput, false );\n        }\n\n        try\n        {      \n\n          // If the CSV file has already been generated then read it\n          // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n          std::string fileDensityMeasurements = CreateFilename( fileImageBasename, \n                                                                fileMaskBasename,\n                                                                std::string( \"WithMask\" ),\n                                                                std::string( \".csv\" ) );\n          \n          std::string fileInputDensityMeasurements  \n            =  niftk::ConcatenatePath( args.dirOutput, fileDensityMeasurements );\n\n          if ( ! args.flgOverwrite ) \n          {\n            if ( niftk::FileIsRegular( fileInputDensityMeasurements ) )\n            {\n              std::ifstream fin( fileInputDensityMeasurements.c_str() );\n\n              if ((! fin) || fin.bad()) \n              {\n                message << \"ERROR: Could not open file: \" << fileDensityMeasurements << std::endl;\n                args.PrintError( message );\n                continue;\n              }\n              \n              message << std::endl << \"Reading CSV file: \" << fileInputDensityMeasurements << std::endl;\n              args.PrintMessage( message );\n\n              niftk::CSVRow csvRow;\n              \n              bool flgFirstRowOfThisFile = true;\n              \n              while( fin >> csvRow )\n              {\n                message << \"\" << csvRow << std::endl;\n                args.PrintMessage( message );\n                \n                if ( flgFirstRowOfThisFile )\n                {\n                  if ( flgVeryFirstRow )    // Include the title row?\n                  {\n                    *args.foutOutputCSV << csvRow << std::endl;\n                    flgVeryFirstRow = false;\n                  }\n                  flgFirstRowOfThisFile = false;\n                }\n                else\n                {\n                  *args.foutOutputCSV << csvRow << std::endl;\n                }\n              }\n              \n              continue;\n            }\n            else\n            {\n              message << \"Density measurements: \" << fileInputDensityMeasurements \n                      << \" not found\" << std::endl;\n              args.PrintMessage( message );\n            }     \n          }\n          \n          progress = ( iDirectory + ( iMask + ( iImage + 0.3 )/nImages )/nMasks )/nDirectories;\n          std::cout  << std::endl << \"<filter-progress>\" << std::endl\n                     << progress << std::endl\n                     << \"</filter-progress>\" << std::endl << std::endl;\n\n\n          // Segment the parenchyma\n          // ~~~~~~~~~~~~~~~~~~~~~~\n\n          ImageType::Pointer imParenchyma = 0;\n          \n          std::string fileOutputParenchyma = CreateFilename( fileImageBasename, \n                                                             fileMaskBasename,\n                                                             std::string( \"WithMask\" ),\n                                                             std::string( \"_Parenchyma.nii\" ) );\n\n          if ( args.flgOverwrite || \n               ( ! args.ReadImageFromFile( args.dirOutput, \n                                           fileOutputParenchyma, \n                                           \"breast parenchyma\", imParenchyma ) ) )\n          {\n\n            // QProcess call to seg_EM\n\n            QStringList argumentsNiftySeg = args.argsSegEM; \n\n            argumentsNiftySeg \n              << \"-in\"   << fileImageFullPath.c_str()\n              << \"-mask\" << fileMaskFullPath.c_str()\n              << \"-out\"  << niftk::ConcatenatePath( args.dirOutput, fileOutputParenchyma ).c_str();\n\n            message << std::endl << \"Executing parenchyma segmentation (QProcess): \"\n                    << std::endl << \" \" << args.progSegEM;\n            for(int i=0;i<argumentsNiftySeg.size();i++)\n            {\n              message << \" \" << argumentsNiftySeg[i].toStdString();\n            }\n            message << std::endl << std::endl;\n            args.PrintMessage( message );\n\n            QProcess callSegEM;\n            QString outSegEM;\n\n            callSegEM.setProcessChannelMode( QProcess::MergedChannels );\n            callSegEM.start( args.progSegEM.c_str(), argumentsNiftySeg );\n\n            bool flgFinished = callSegEM.waitForFinished( 3600000 ); // Wait one hour\n\n            outSegEM = callSegEM.readAllStandardOutput();\n\n            message << \"\" << outSegEM.toStdString();\n\n            if ( ! flgFinished )\n            {\n              message << \"ERROR: Could not execute: \" << args.progSegEM << \" ( \" \n                      << callSegEM.errorString().toStdString() << \" )\" << std::endl;\n              args.PrintMessage( message );\n              \n              continue;\n            }\n            \n            args.PrintMessage( message );\n\n            callSegEM.close();\n\n            args.ReadImageFromFile( args.dirOutput, \n                                    fileOutputParenchyma, \n                                    \"breast parenchyma\", imParenchyma );\n          }\n\n\n          progress = ( iDirectory + ( iMask + ( iImage + 0.6 )/nImages )/nMasks )/nDirectories;\n          std::cout  << std::endl << \"<filter-progress>\" << std::endl\n                     << progress << std::endl\n                     << \"</filter-progress>\" << std::endl << std::endl;\n\n\n          // Compute the breast density\n          // ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n          if ( imParenchyma && imMask )\n          {\n            float nLeftVoxels = 0;\n            float nRightVoxels = 0;\n\n            float totalDensity = 0.;\n            float leftDensity = 0.;\n            float rightDensity = 0.;\n\n            float meanOfHighProbIntensities = 0.;\n            float meanOfLowProbIntensities = 0.;\n\n            float nHighProbIntensities = 0.;\n            float nLowProbIntensities = 0.;\n\n            itk::ImageRegionIteratorWithIndex< ImageType > \n              maskIterator( imMask, imMask->GetLargestPossibleRegion() );\n\n            itk::ImageRegionConstIterator< ImageType > \n              segmIterator( imParenchyma, imParenchyma->GetLargestPossibleRegion() );\n\n            itk::ImageRegionConstIterator< ImageType > \n              imIterator( imInput, imInput->GetLargestPossibleRegion() );\n\n            ImageType::SpacingType spacing = imParenchyma->GetSpacing();\n\n            float voxelVolume = spacing[0]*spacing[1]*spacing[2];\n\n            ImageType::RegionType region;\n            region = imMask->GetLargestPossibleRegion();\n\n            ImageType::SizeType lateralSize;\n            lateralSize = region.GetSize();\n            lateralSize[0] = lateralSize[0]/2;\n\n            ImageType::IndexType idx;\n   \n            for ( maskIterator.GoToBegin(), segmIterator.GoToBegin(), imIterator.GoToBegin();\n                  ! maskIterator.IsAtEnd();\n                  ++maskIterator, ++segmIterator, ++imIterator )\n            {\n              if ( maskIterator.Get() )\n              {\n                idx = maskIterator.GetIndex();\n\n                // Left breast\n\n                if ( idx[0] < (int) lateralSize[0] )\n                {\n                  nLeftVoxels++;\n                  leftDensity += segmIterator.Get();\n                }\n\n                // Right breast\n\n                else \n                {\n                  nRightVoxels++;\n                  rightDensity += segmIterator.Get();\n                }\n\n                // Both breasts\n\n                totalDensity += segmIterator.Get();\n\n                // Ensure we have the polarity correct by calculating the\n                // mean intensities of each class\n\n                if ( segmIterator.Get() > 0.5 )\n                {\n                  meanOfHighProbIntensities += imIterator.Get();\n                  nHighProbIntensities++;\n                }\n                else\n                {\n                  meanOfLowProbIntensities += imIterator.Get();\n                  nLowProbIntensities++;\n                }              \n              }\n            }\n\n            leftDensity /= nLeftVoxels;\n            rightDensity /= nRightVoxels;\n            totalDensity /= ( nLeftVoxels + nRightVoxels);\n\n            // Calculate the mean intensities of each class\n\n            if ( nHighProbIntensities > 0. )\n            {\n              meanOfHighProbIntensities /= nHighProbIntensities;\n            }\n\n            if ( nLowProbIntensities > 0. )\n            {\n              meanOfLowProbIntensities /= nLowProbIntensities;\n            }\n\n            message  << std::endl\n                     << \"Mean intensity of high probability class = \" << meanOfHighProbIntensities\n                     << \" ( \" << nHighProbIntensities << \" voxels )\" << std::endl\n                     << \"Mean intensity of low probability class = \" << meanOfLowProbIntensities\n                     << \" ( \" << nLowProbIntensities << \" voxels )\" << std::endl;\n            args.PrintMessage( message );\n\n            // Fat should be high intensity in the T2 image so if the\n            // dense region (high prob) has a high intensity then it is\n            // probably fat and we need to invert the density\n\n            if ( (     args.flgFatIsBright   && ( meanOfHighProbIntensities > meanOfLowProbIntensities ) ) ||\n                 ( ( ! args.flgFatIsBright ) && ( meanOfHighProbIntensities < meanOfLowProbIntensities ) ) )\n            {\n              message << std::endl << \"Inverting the density estimation\" << std::endl;\n              args.PrintWarning( message );\n        \n              leftDensity  = 1. - leftDensity;\n              rightDensity = 1. - rightDensity;\n              totalDensity = 1. - totalDensity;\n\n              itk::ImageRegionIterator< ImageType > \n              imIterator( imParenchyma, imParenchyma->GetLargestPossibleRegion() );\n              \n              itk::ImageRegionConstIterator< ImageType > \n              maskIterator( imMask, imMask->GetLargestPossibleRegion() );\n   \n              for ( maskIterator.GoToBegin(), imIterator.GoToBegin();\n                    ! maskIterator.IsAtEnd();\n                    ++maskIterator, ++imIterator )\n              {\n                if ( maskIterator.Get() )\n                {\n                  imIterator.Set( 1. - imIterator.Get() );\n                }\n              }\n\n              args.WriteImageToFile( fileOutputParenchyma, \n                                     std::string( \"inverted parenchyma image\" ), \n                                     imParenchyma );\n            }\n        \n  \n            float leftBreastVolume = nLeftVoxels*voxelVolume;\n            float rightBreastVolume = nRightVoxels*voxelVolume;\n\n            message << \"Number of left breast voxels: \" << nLeftVoxels << std::endl\n                    << \"Volume of left breast: \" << leftBreastVolume << \" mm^3\" << std::endl\n                    << \"Density of left breast (fraction of glandular tissue): \" << leftDensity \n                    << std::endl << std::endl\n        \n                    << \"Number of right breast voxels: \" << nRightVoxels << std::endl\n                    << \"Volume of right breast: \" << rightBreastVolume << \" mm^3\" << std::endl\n                    << \"Density of right breast (fraction of glandular tissue): \" << rightDensity \n                    << std::endl << std::endl\n        \n                    << \"Total number of breast voxels: \" \n                    << nLeftVoxels + nRightVoxels << std::endl\n                    << \"Total volume of both breasts: \" \n                    << leftBreastVolume + rightBreastVolume << \" mm^3\" << std::endl\n                    << \"Combined density of both breasts (fraction of glandular tissue): \" \n                    << totalDensity << std::endl << std::endl;\n            args.PrintMessage( message );\n\n\n            // Compute a naive value of the breast density\n\n            float nLeftVoxelsNaive;\n            float nRightVoxelsNaive;                                  \n      \n            float totalDensityNaive;\n            float leftDensityNaive;\n            float rightDensityNaive;\n\n            NaiveParenchymaSegmentation( args, \n                                         imMask, imInput,\n                                         flgFatIsBright,\n                                         nLeftVoxelsNaive, nRightVoxelsNaive,      \n                                         totalDensityNaive, leftDensityNaive, rightDensityNaive,\n                                         fileOutputParenchyma );\n\n\n            if ( fileDensityMeasurements.length() != 0 ) \n            {\n              std::string fileOutputDensityMeasurements \n                = niftk::ConcatenatePath( args.dirOutput, fileDensityMeasurements );\n\n              std::ofstream fout( fileOutputDensityMeasurements.c_str() );\n\n              fout.precision(16);\n\n              if ((! fout) || fout.bad()) \n              {\n                message << \"ERROR: Could not open file: \" << fileDensityMeasurements << std::endl;\n                args.PrintError( message );\n                continue;\n              }\n\n              fout << \"Study ID, \"\n                   << \"Image, \"\n                   << \"Mask, \"\n\n                   << \"Number of left breast voxels, \"\n                   << \"Volume of left breast (mm^3), \"\n                   << \"Density of left breast (fraction of glandular tissue), \"\n      \n                   << \"Number of right breast voxels, \"\n                   << \"Volume of right breast (mm^3), \"\n                   << \"Density of right breast (fraction of glandular tissue), \"\n      \n                   << \"Total number of breast voxels, \"\n                   << \"Total volume of both breasts (mm^3), \"\n                   << \"Combined density of both breasts (fraction of glandular tissue), \" \n\n                   << \"Naive density of left breast (fraction of glandular tissue), \"\n                   << \"Naive density of right breast (fraction of glandular tissue), \"\n                   << \"Naive combined density of both breasts (fraction of glandular tissue)\" \n                   << std::endl;\n\n              fout << dirBaseName << \", \"\n                   << fileImageBasename << \", \"\n                   << fileMaskBasename << \", \"\n\n                                  \n                   << nLeftVoxels << \", \"\n                   << leftBreastVolume << \", \"\n                   << leftDensity << \", \"\n      \n                   << nRightVoxels << \", \"\n                   << rightBreastVolume << \", \"\n                   << rightDensity << \", \"\n      \n                   << nLeftVoxels + nRightVoxels << \", \"\n                   << leftBreastVolume + rightBreastVolume << \", \"\n                   << totalDensity << \", \" \n\n                   << leftDensityNaive << \", \"\n                   << rightDensityNaive << \", \"\n                   << totalDensityNaive \n                \n                   << std::endl;\n    \n              fout.close();\n\n              message  << \"Density measurements written to file: \" \n                       << fileOutputDensityMeasurements  << std::endl << std::endl;\n              args.PrintMessage( message );\n            }\n\n            // Write the data to the main collated csv file\n\n            if ( args.foutOutputCSV )\n            {\n              if ( flgVeryFirstRow )    // Include the title row?\n              {\n                *args.foutOutputCSV << \"Study ID, \"\n                                    << \"Image, \"\n                                    << \"Mask, \"\n\n                                    << \"Number of left breast voxels, \"\n                                    << \"Volume of left breast (mm^3), \"\n                                    << \"Density of left breast (fraction of glandular tissue), \"\n              \n                                    << \"Number of right breast voxels, \"\n                                    << \"Volume of right breast (mm^3), \"\n                                    << \"Density of right breast (fraction of glandular tissue), \"\n              \n                                    << \"Total number of breast voxels, \"\n                                    << \"Total volume of both breasts (mm^3), \"\n                                    << \"Combined density of both breasts (fraction of glandular tissue), \" \n          \n                                    << \"Naive density of left breast (fraction of glandular tissue), \"\n                                    << \"Naive density of right breast (fraction of glandular tissue), \"\n                                    << \"Naive combined density of both breasts (fraction of glandular tissue)\" \n\n                                    << std::endl;\n                flgVeryFirstRow = false;\n              }\n\n              *args.foutOutputCSV << dirBaseName << \", \"\n                                  << fileImageBasename << \", \"\n                                  << fileMaskBasename << \", \"\n\n                                  << nLeftVoxels << \", \"\n                                  << leftBreastVolume << \", \"\n                                  << leftDensity << \", \"\n            \n                                  << nRightVoxels << \", \"\n                                  << rightBreastVolume << \", \"\n                                  << rightDensity << \", \"\n      \n                                  << nLeftVoxels + nRightVoxels << \", \"\n                                  << leftBreastVolume + rightBreastVolume << \", \"\n                                  << totalDensity  << \", \"\n\n                                  << leftDensityNaive << \", \"\n                                  << rightDensityNaive << \", \"\n                                  << totalDensityNaive \n\n                                  << std::endl;\n            }\n            else\n            {\n              message << \"Collated csv data file: \" << fileOutputCSV \n                      << \" is not open, data will not be written.\" << std::endl;\n              args.PrintWarning( message );\n            }\n          }\n\n          progress = ( iDirectory + ( iMask + ( iImage + 0.9 )/nImages )/nMasks )/nDirectories;\n          std::cout  << std::endl << \"<filter-progress>\" << std::endl\n                     << progress << std::endl\n                     << \"</filter-progress>\" << std::endl << std::endl;\n    \n          \n        }\n        catch (itk::ExceptionObject &ex)\n        {\n          message << ex << std::endl;\n          args.PrintError( message );\n          continue;\n        }\n\n        progress = ( iDirectory + ( iMask + iImage/nImages )/nMasks )/nDirectories;\n        std::cout  << std::endl << \"<filter-progress>\" << std::endl\n                   << progress << std::endl\n                   << \"</filter-progress>\" << std::endl << std::endl;\n      }\n    }\n  }\n\n\n  progress = iDirectory/nDirectories;\n  std::cout  << std::endl << \"<filter-progress>\" << std::endl\n             << progress << std::endl\n             << \"</filter-progress>\" << std::endl << std::endl;\n  \n  return EXIT_SUCCESS;\n}\n \n \n\n", "meta": {"hexsha": "f5a9755539de3ab898c1ce9f9a2ad2858869a7a6", "size": 55168, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Applications/BreastDensityFromMRIsGivenMaskAndImage/niftkBreastDensityFromMRIsGivenMaskAndImage.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "Applications/BreastDensityFromMRIsGivenMaskAndImage/niftkBreastDensityFromMRIsGivenMaskAndImage.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Applications/BreastDensityFromMRIsGivenMaskAndImage/niftkBreastDensityFromMRIsGivenMaskAndImage.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 30.8201117318, "max_line_length": 114, "alphanum_fraction": 0.52287558, "num_tokens": 12400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.032589745000924666, "lm_q1q2_score": 0.012544188636490466}}
{"text": "// Copyright Tom Westerhout (c) 2018\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//\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 Tom Westerhout nor the names of other\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#include \"diffusion.hpp\"\n#include \"hamiltonian.hpp\"\n#include \"quantum_state.hpp\"\n#include <boost/exception/get_error_info.hpp>\n#include <boost/optional.hpp>\n#include <boost/program_options.hpp>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <optional>\n\nnamespace po = boost::program_options;\n\nusing IStreamPtr = std::unique_ptr<std::istream, void (*)(std::istream*)>;\nusing OStreamPtr = std::unique_ptr<std::ostream, void (*)(std::ostream*)>;\n\nnamespace {\nauto parse_options(int argc, char** argv, IStreamPtr& input_file,\n    OStreamPtr& output_file, std::string& hamiltonian_file_name, double& lambda,\n    std::size_t& iterations, std::size_t& soft_max,\n    boost::optional<std::size_t>& hard_max) -> bool\n{\n    std::string                  input_file_name;\n    boost::optional<std::string> output_file_name;\n    po::options_description      cmdline_options{\"Command-line options\"};\n    // clang-format off\n    cmdline_options.add_options()\n        (\"help\", \"Produce the help message.\")\n        (\"input-file\", po::value(&input_file_name)->required(),\n            \"File containing the initial quantum state. '-' can be used to \"\n            \"indicate that the initial state should be read from the standard input.\")\n        (\"output-file,o\", po::value(&output_file_name),\n            \"Where to save the final quantum state.\")\n        (\"hamiltonian,H\", po::value(&hamiltonian_file_name)->required(),\n            \"The file containing the Hamiltonian specification.\")\n        (\"lambda,L\", po::value(&lambda)->default_value(1.0),\n            \"Value of Λ in the diffusion operator (H - Λ).\")\n        (\"iterations,n\", po::value(&iterations)->default_value(1.0),\n            \"Number of application of (H - Λ) to perform.\")\n        (\"max\", po::value(&soft_max)->default_value(1000),\n            \"Maximum number of elements to keep after each application of (H - Λ).\")\n        (\"hard-max\", po::value(&hard_max),\n            \"Initial number of buckets in the hash table. This parameter should \"\n            \"be chosen carefully, because too low a value will result in a lot of \"\n            \"rehashing, but too high a value will use more memory and result in \"\n            \"more cache misses.\")\n    ;\n    // clang-format on\n    po::positional_options_description positional;\n    positional.add(\"input-file\", 1);\n\n    po::variables_map vm;\n    store(po::command_line_parser(argc, argv)\n              .options(cmdline_options)\n              .positional(positional)\n              .run(),\n        vm);\n    if (vm.count(\"help\")) {\n        std::cout << cmdline_options << '\\n';\n        return false;\n    }\n    po::notify(vm);\n\n    if (input_file_name == \"-\") {\n        input_file = IStreamPtr{std::addressof(std::cin), [](auto*) {}};\n    }\n    else if (!std::filesystem::exists({input_file_name})) {\n        throw std::runtime_error{\n            \"Input file '\" + input_file_name + \"' does not exist.\"};\n    }\n    else {\n        input_file = IStreamPtr{new std::ifstream{input_file_name},\n            [](auto* p) { std::default_delete<std::istream>{}(p); }};\n        if (!*input_file) {\n            throw std::runtime_error{\n                \"Could not open '\" + input_file_name + \"' for reading.\"};\n        }\n    }\n\n    if (!output_file_name) {\n        output_file = OStreamPtr{std::addressof(std::cout), [](auto*) {}};\n    }\n    else {\n        // Issue #1: Prevent the user from overwriting the input file.\n        if (std::filesystem::exists({*output_file_name})\n            && input_file_name != \"-\"\n            && std::filesystem::equivalent(\n                   {*output_file_name}, {input_file_name})) {\n            throw std::runtime_error{\"Input file '\" + input_file_name\n                                     + \"' and output file '\" + *output_file_name\n                                     + \"' are the same.\"};\n        }\n        output_file = OStreamPtr{new std::ofstream{*output_file_name},\n            [](auto* p) { std::default_delete<std::ostream>{}(p); }};\n        if (!*output_file) {\n            throw std::runtime_error{\n                \"Could not open '\" + *output_file_name + \"' for writing.\"};\n        }\n    }\n    return true;\n}\n\nauto read_hamiltonian(std::string const& hamiltonian_file_name) -> Hamiltonian\n{\n    if (!std::filesystem::exists({hamiltonian_file_name})) {\n        throw std::runtime_error{\"Hamiltonian specification file '\"\n                                 + hamiltonian_file_name + \"' does not exist.\"};\n    }\n    std::ifstream hamiltonian_file{hamiltonian_file_name};\n    if (!hamiltonian_file) {\n        throw std::runtime_error{\n            \"Could not open '\" + hamiltonian_file_name + \"' for reading.\"};\n    }\n\n    Heisenberg hamiltonian;\n    if (!(hamiltonian_file >> hamiltonian) && !hamiltonian_file.eof()) {\n        throw std::runtime_error{\"Failed to parse the Hamiltonian.\"};\n    }\n    return {std::move(hamiltonian)};\n}\n} // namespace\n\nint main(int argc, char** argv)\n{\n    try {\n        IStreamPtr                   input_file{nullptr, [](auto*) {}};\n        OStreamPtr                   output_file{nullptr, [](auto*) {}};\n        std::string                  hamiltonian_file_name;\n        double                       lambda;\n        std::size_t                  iterations;\n        std::size_t                  soft_max;\n        boost::optional<std::size_t> hard_max;\n\n        auto const proceed = parse_options(argc, argv, input_file, output_file,\n            hamiltonian_file_name, lambda, iterations, soft_max, hard_max);\n        if (!proceed) { return EXIT_SUCCESS; }\n\n        QuantumState state{soft_max, hard_max ? *hard_max : 2 * soft_max, 1};\n        *input_file >> state;\n        auto const hamiltonian    = read_hamiltonian(hamiltonian_file_name);\n        auto const initial_energy = energy(hamiltonian, state);\n        *output_file << \"# Result of evaluating (Λ - H)ⁿ|ψ₀〉for\\n\"\n                     << \"# Λ = \" << lambda << '\\n'\n                     << \"# n = \" << iterations << '\\n'\n                     << \"# E₀ = 〈ψ₀|H|ψ₀〉= \" << initial_energy << '\\n';\n        state = diffusion_loop(lambda, hamiltonian, state, iterations);\n        auto const final_energy = energy(hamiltonian, state);\n        *output_file << \"# => E = \" << final_energy << '\\n' << state;\n        return EXIT_SUCCESS;\n    }\n    catch (std::exception const& e) {\n        auto const* st = boost::get_error_info<errinfo_backtrace>(e);\n        std::cerr << \"Error: \" << e.what() << '\\n';\n        if (st != nullptr) { std::cerr << \"Backtrace:\\n\" << *st << '\\n'; }\n        return EXIT_FAILURE;\n    }\n    catch (...) {\n        std::cerr << \"Error: \"\n                  << \"Unknown error occured.\" << '\\n';\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "cf76b91c83f6bbab833bcf047c12fa7e5b1085c2", "size": 8285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "twesterhout/walking-lanczos", "max_stars_repo_head_hexsha": "cf7798b345d2219f92577e3dbbefbbc2f329acf0", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_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": "twesterhout/walking-lanczos", "max_issues_repo_head_hexsha": "cf7798b345d2219f92577e3dbbefbbc2f329acf0", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T17:52:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-29T13:05:22.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "twesterhout/walking-lanczos", "max_forks_repo_head_hexsha": "cf7798b345d2219f92577e3dbbefbbc2f329acf0", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.706185567, "max_line_length": 86, "alphanum_fraction": 0.6112251056, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.03258974323917979, "lm_q1q2_score": 0.012544187498477282}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2018 Adeel Ahmad, Islamabad, Pakistan.\r\n\r\n// Contributed and/or modified by Adeel Ahmad, as part of Google Summer of Code 2018 program.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_KARNEY_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_KARNEY_HPP\r\n\r\n\r\n#include <boost/geometry/strategies/geographic/distance.hpp>\r\n#include <boost/geometry/strategies/geographic/parameters.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace distance\r\n{\r\n\r\n/*!\r\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\r\n       after Karney (2011).\r\n\\ingroup distance\r\n\\tparam Spheroid The reference spheroid model\r\n\\tparam CalculationType \\tparam_calculation\r\n\\author See\r\n- Charles F.F Karney, Algorithms for geodesics, 2011\r\nhttps://arxiv.org/pdf/1109.4448.pdf\r\n*/\r\ntemplate\r\n<\r\n    typename Spheroid = srs::spheroid<double>,\r\n    typename CalculationType = void\r\n>\r\nclass karney\r\n    : public strategy::distance::geographic\r\n        <\r\n            strategy::karney, Spheroid, CalculationType\r\n        >\r\n{\r\n    typedef strategy::distance::geographic\r\n        <\r\n            strategy::karney, Spheroid, CalculationType\r\n        > base_type;\r\n\r\npublic:\r\n    inline karney()\r\n        : base_type()\r\n    {}\r\n\r\n    explicit inline karney(Spheroid const& spheroid)\r\n        : base_type(spheroid)\r\n    {}\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct tag<karney<Spheroid, CalculationType> >\r\n{\r\n    typedef strategy_tag_distance_point_point type;\r\n};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\r\nstruct return_type<karney<Spheroid, CalculationType>, P1, P2>\r\n    : karney<Spheroid, CalculationType>::template calculation_type<P1, P2>\r\n{};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct comparable_type<karney<Spheroid, CalculationType> >\r\n{\r\n    typedef karney<Spheroid, CalculationType> type;\r\n};\r\n\r\n\r\ntemplate <typename Spheroid, typename CalculationType>\r\nstruct get_comparable<karney<Spheroid, CalculationType> >\r\n{\r\n    static inline karney<Spheroid, CalculationType> apply(karney<Spheroid, CalculationType> const& input)\r\n    {\r\n        return input;\r\n    }\r\n};\r\n\r\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\r\nstruct result_from_distance<karney<Spheroid, CalculationType>, P1, P2 >\r\n{\r\n    template <typename T>\r\n    static inline typename return_type<karney<Spheroid, CalculationType>, P1, P2>::type\r\n        apply(karney<Spheroid, CalculationType> const& , T const& value)\r\n    {\r\n        return value;\r\n    }\r\n};\r\n\r\n\r\n} // namespace services\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::distance\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_KARNEY_HPP\r\n", "meta": {"hexsha": "7695ab844b0df92331a40bd857b7ee6cb2b7a006", "size": 3101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/strategies/geographic/distance_karney.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/geometry/strategies/geographic/distance_karney.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/geometry/strategies/geographic/distance_karney.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.5042735043, "max_line_length": 106, "alphanum_fraction": 0.7178329571, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.02716923035412042, "lm_q1q2_score": 0.012525471074251008}}
{"text": "/**************************************************************************\\\n * Copyright (c) Kongsberg Oil & Gas Technologies AS\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 * \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 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 <Inventor/engines/SoHeightMapToNormalMap.h>\n\n#include <boost/scoped_array.hpp>\n\n#include <Inventor/SbVec3f.h>\n#include <Inventor/SbImage.h>\n#include \"engines/SoSubEngineP.h\"\n\n/*!\n  \\class SoHeightMapToNormalMap SoHeightMapToNormalMap.h Inventor/engines/SoHeightMapToNormalMap.h\n  \\brief Engine for computing a normal map from a height map.\n\n  This engine will create a normal map texture from a height map texture.\n  You can use it in an Inventor file like this:\n\n  \\code\n  Texture2 {\n    image = HeightMapToNormalMap {\n      sourceImage = Texture2 { filename \"HeightMap.jpg\" } . image\n    } . image\n  }\n  \\endcode\n\n  Be aware that the field connections will remain active, so both\n  Texture2 nodes and the HeightMapToNormalMap engine will be kept resident\n  in memory (unless you intervene manually and detach the engine) even\n  though only the \"outer\" Texture2 node is needed. This can give quite\n  a big memory use overhead.\n\n  \\ingroup coin_engines\n  \\COIN_CLASS_EXTENSION\n  \\since Coin 3.0\n*/\n\n/*!\n  \\enum SoHeightMapToNormalMap::NormalMapFormat\n  Enumeration of available normal map formats.\n*/\n\n/*!\n  \\var SoHeightMapToNormalMap::NormalMapFormat SoHeightMapToNormalMap::INT8\n  Encode the normals as a 3 component byte texture.\n  This is the only option for now, as long as float textures are not conveniently\n  supported in Coin.\n*/\n\n/*!\n  \\var SoMFEnum SoHeightMapToNormalMap::format\n  This setting decides what kind of normal map is generated.  For now, only the\n  INT8 format is available, and it is the default value.\n*/\n\nSO_ENGINE_SOURCE(SoHeightMapToNormalMap);\n\n/*!\n  \\copybrief SoBase::initClass(void)\n*/\nvoid\nSoHeightMapToNormalMap::initClass(void)\n{\n  SO_ENGINE_INTERNAL_INIT_CLASS(SoHeightMapToNormalMap);\n}\n\n/*!\n  Constructor.\n*/\nSoHeightMapToNormalMap::SoHeightMapToNormalMap(void)\n{\n  SO_ENGINE_INTERNAL_CONSTRUCTOR(SoHeightMapToNormalMap);\n\n  SO_ENGINE_ADD_INPUT(format, (INT8));\n\n  SO_ENGINE_DEFINE_ENUM_VALUE(NormalMapFormat, INT8);\n  SO_ENGINE_SET_SF_ENUM_TYPE(format, NormalMapFormat);\n}\n\n/*!\n  Static function for computing a normal map from a height map.\n  This function can be used directly without any engine instantiation.\n*/\nvoid\nSoHeightMapToNormalMap::convert(const unsigned char * srcptr, SbVec2s size, int nc, SbImage & dst_out)\n{\n  float dx, dy;\n  int width = size[0];\n  int height = size[1];\n  boost::scoped_array<unsigned char> dstarray(new unsigned char[width*height*3]);\n  unsigned char * dstptr = dstarray.get();\n  unsigned char red;\n  SbVec3f n;\n\n#define GET_PIXEL_RED(x_, y_) \\\n  srcptr[(y_)*width*nc + (x_)*nc]\n\n  for (int y = 0; y < height; y++) {\n    for (int x = 0; x < width; x++) {\n      // do Y Sobel filter\n      red = GET_PIXEL_RED((x-1+width) % width, (y+1) % height);\n      dy  = static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED(x % width, (y+1) % height);\n      dy += static_cast<float>(red) / 255.0f * -2.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y+1) % height);\n      dy += static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED((x-1+width) % width, (y-1+height) % height);\n      dy += static_cast<float>(red) / 255.0f *  1.0f;\n\n      red = GET_PIXEL_RED(x % width, (y-1+height) % height);\n      dy += static_cast<float>(red) / 255.0f *  2.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y-1+height) % height);\n      dy += static_cast<float>(red) / 255.0f *  1.0f;\n\n      // Do X Sobel filter\n      red = GET_PIXEL_RED((x-1+width) % width, (y-1+height) % height);\n      dx  = static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED((x-1+width) % width, y % height);\n      dx += static_cast<float>(red) / 255.0f * -2.0f;\n\n      red = GET_PIXEL_RED((x-1+width) % width, (y+1) % height);\n      dx += static_cast<float>(red) / 255.0f * -1.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y-1+height) % height);\n      dx += static_cast<float>(red) / 255.0f *  1.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, y % height);\n      dx += static_cast<float>(red) / 255.0f *  2.0f;\n\n      red = GET_PIXEL_RED((x+1) % width, (y+1) % height);\n      dx += static_cast<float>(red) / 255.0f *  1.0f;\n\n      n[0] = -dx;\n      n[1] = -dy;\n      n[2] = 1.0f;\n      (void) n.normalize();\n\n      *dstptr++ = static_cast<unsigned char>(SbMin((n[0]+1.0f) * 128.0f, 255.0f));\n      *dstptr++ = static_cast<unsigned char>(SbMin((n[1]+1.0f) * 128.0f, 255.0f));\n      *dstptr++ = static_cast<unsigned char>(SbMin((n[2]+1.0f) * 128.0f, 255.0f));\n    }\n  }\n#undef GET_PIXEL_RED\n  dst_out.setValue(size, 3, dstarray.get());\n}\n\nvoid\nSoHeightMapToNormalMap::inputChanged(SoField * which)\n{\n  // in case we need to override later\n  inherited::inputChanged(which);\n}\n\nvoid\nSoHeightMapToNormalMap::evaluate(void)\n{\n  SbVec2s size;\n  int nc;\n  const unsigned char * ptr =\n    static_cast<const unsigned char *>(sourceImage.getValue(size, nc));\n\n  SbImage targetimg;\n  SoHeightMapToNormalMap::convert(ptr, size, nc, targetimg);\n\n  ptr = static_cast<const unsigned char *>(targetimg.getValue(size, nc));\n  SO_ENGINE_OUTPUT(image, SoSFImage, setValue(size, nc, ptr));\n}\n", "meta": {"hexsha": "0f9051b212e5bf10ddf2d7bad055d954df8901ae", "size": 6779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/engines/SoHeightMapToNormalMap.cpp", "max_stars_repo_name": "montylab3d/coin", "max_stars_repo_head_hexsha": "46dec7c01e553815dc6903475116444a1a6e78f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 158.0, "max_stars_repo_stars_event_min_datetime": "2019-12-27T16:39:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T19:04:39.000Z", "max_issues_repo_path": "src/engines/SoHeightMapToNormalMap.cpp", "max_issues_repo_name": "montylab3d/coin", "max_issues_repo_head_hexsha": "46dec7c01e553815dc6903475116444a1a6e78f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 261.0, "max_issues_repo_issues_event_min_datetime": "2019-12-23T19:23:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T10:11:01.000Z", "max_forks_repo_path": "src/engines/SoHeightMapToNormalMap.cpp", "max_forks_repo_name": "montylab3d/coin", "max_forks_repo_head_hexsha": "46dec7c01e553815dc6903475116444a1a6e78f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2019-12-27T21:18:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T02:11:16.000Z", "avg_line_length": 33.5594059406, "max_line_length": 102, "alphanum_fraction": 0.6809263903, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.03410042706203433, "lm_q1q2_score": 0.01250086656514421}}
{"text": "//=======================================================================\n// Copyright 2001 University of Notre Dame.\n// Copyright 2006 Trustees of Indiana University\n// Authors: Jeremy G. Siek and Douglas Gregor <dgregor@cs.indiana.edu>\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_ADJACENCY_MATRIX_HPP\n#define BOOST_ADJACENCY_MATRIX_HPP\n\n#include <boost/config.hpp>\n#include <vector>\n#include <memory>\n#include <cassert>\n#include <boost/limits.hpp>\n#include <boost/iterator.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_mutability_traits.hpp>\n#include <boost/graph/graph_selectors.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/graph/adjacency_iterator.hpp>\n#include <boost/graph/detail/edge.hpp>\n#include <boost/iterator/iterator_adaptor.hpp>\n#include <boost/iterator/filter_iterator.hpp>\n#include <boost/pending/integer_range.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/ice.hpp>\n\nnamespace boost {\n\n  namespace detail {\n\n    template <class Directed, class Vertex>\n    class matrix_edge_desc_impl : public edge_desc_impl<Directed,Vertex>\n    {\n      typedef edge_desc_impl<Directed,Vertex> Base;\n    public:\n      matrix_edge_desc_impl() { }\n      matrix_edge_desc_impl(bool exists, Vertex s, Vertex d,\n                            const void* ep = 0)\n        : Base(s, d, ep), m_exists(exists) { }\n      bool exists() const { return m_exists; }\n    private:\n      bool m_exists;\n    };\n\n    struct does_edge_exist {\n      template <class Edge>\n      bool operator()(const Edge& e) const { return e.exists(); }\n    };\n\n    // Note to self... The int for get_edge_exists and set_edge exist helps\n    // make these calls unambiguous.\n    template <typename EdgeProperty>\n    bool get_edge_exists(const std::pair<bool, EdgeProperty>& stored_edge, int) {\n      return stored_edge.first;\n    }\n    template <typename EdgeProperty>\n    void set_edge_exists(\n        std::pair<bool, EdgeProperty>& stored_edge,\n        bool flag,\n        int\n        ) {\n      stored_edge.first = flag;\n    }\n\n    template <typename EdgeProxy>\n    bool get_edge_exists(const EdgeProxy& edge_proxy, ...) {\n      return edge_proxy;\n    }\n    template <typename EdgeProxy>\n    EdgeProxy& set_edge_exists(EdgeProxy& edge_proxy, bool flag, ...) {\n      edge_proxy = flag;\n      return edge_proxy; // just to avoid never used warning\n    }\n\n\n\n    template <typename EdgeProperty>\n    const EdgeProperty&\n    get_property(const std::pair<bool, EdgeProperty>& stored_edge) {\n      return stored_edge.second;\n    }\n    template <typename EdgeProperty>\n    EdgeProperty&\n    get_property(std::pair<bool, EdgeProperty>& stored_edge) {\n      return stored_edge.second;\n    }\n\n    template <typename StoredEdgeProperty, typename EdgeProperty>\n    inline void\n    set_property(std::pair<bool, StoredEdgeProperty>& stored_edge,\n                 const EdgeProperty& ep, int) {\n      stored_edge.second = ep;\n    }\n\n    inline const no_property& get_property(const char&) {\n      static no_property s_prop;\n      return s_prop;\n    }\n    inline no_property& get_property(char&) {\n      static no_property s_prop;\n      return s_prop;\n    }\n    template <typename EdgeProxy, typename EdgeProperty>\n    inline void\n    set_property(EdgeProxy, const EdgeProperty&, ...) {}\n\n    //=======================================================================\n    // Directed Out Edge Iterator\n\n    template <\n        typename VertexDescriptor, typename MatrixIter\n      , typename VerticesSizeType, typename EdgeDescriptor\n    >\n    struct dir_adj_matrix_out_edge_iter\n      : iterator_adaptor<\n            dir_adj_matrix_out_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        >\n    {\n        typedef iterator_adaptor<\n            dir_adj_matrix_out_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        > super_t;\n\n        dir_adj_matrix_out_edge_iter() { }\n\n        dir_adj_matrix_out_edge_iter(\n            const MatrixIter& i\n          , const VertexDescriptor& src\n          , const VerticesSizeType& n\n           )\n            : super_t(i), m_src(src), m_targ(0), m_n(n)\n        { }\n\n        void increment() {\n            ++this->base_reference();\n            ++m_targ;\n        }\n\n        inline EdgeDescriptor\n        dereference() const\n        {\n            return EdgeDescriptor(get_edge_exists(*this->base(), 0), m_src, m_targ,\n                                  &get_property(*this->base()));\n        }\n        VertexDescriptor m_src, m_targ;\n        VerticesSizeType m_n;\n    };\n\n    //=======================================================================\n    // Directed In Edge Iterator\n\n    template <\n        typename VertexDescriptor, typename MatrixIter\n      , typename VerticesSizeType, typename EdgeDescriptor\n    >\n    struct dir_adj_matrix_in_edge_iter\n      : iterator_adaptor<\n            dir_adj_matrix_in_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        >\n    {\n        typedef iterator_adaptor<\n            dir_adj_matrix_in_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        > super_t;\n\n        dir_adj_matrix_in_edge_iter() { }\n\n        dir_adj_matrix_in_edge_iter(\n            const MatrixIter& i\n          , const MatrixIter& last\n          , const VertexDescriptor& tgt\n          , const VerticesSizeType& n\n           )\n          : super_t(i), m_last(last), m_src(0), m_targ(tgt), m_n(n)\n        { }\n\n        void increment() {\n          if (VerticesSizeType(m_last - this->base_reference()) >= m_n) {\n            this->base_reference() += m_n;\n            ++m_src;\n          } else {\n            this->base_reference() = m_last;\n          }\n        }\n\n        inline EdgeDescriptor\n        dereference() const\n        {\n            return EdgeDescriptor(get_edge_exists(*this->base(), 0), m_src, m_targ,\n                                  &get_property(*this->base()));\n        }\n        MatrixIter m_last;\n        VertexDescriptor m_src, m_targ;\n        VerticesSizeType m_n;\n    };\n\n    //=======================================================================\n    // Undirected Out Edge Iterator\n\n    template <\n        typename VertexDescriptor, typename MatrixIter\n      , typename VerticesSizeType, typename EdgeDescriptor\n    >\n    struct undir_adj_matrix_out_edge_iter\n      : iterator_adaptor<\n            undir_adj_matrix_out_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        >\n    {\n        typedef iterator_adaptor<\n            undir_adj_matrix_out_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        > super_t;\n\n        undir_adj_matrix_out_edge_iter() { }\n\n        undir_adj_matrix_out_edge_iter(\n            const MatrixIter& i\n          , const VertexDescriptor& src\n          , const VerticesSizeType& n\n        )\n          : super_t(i), m_src(src), m_inc(src), m_targ(0), m_n(n)\n        {}\n\n        void increment()\n        {\n            if (m_targ < m_src)     // first half\n            {\n                ++this->base_reference();\n            }\n            else if (m_targ < m_n - 1)\n            {                  // second half\n                ++m_inc;\n                this->base_reference() += m_inc;\n            }\n            else\n            {                  // past-the-end\n                this->base_reference() += m_n - m_src;\n            }\n            ++m_targ;\n        }\n\n        inline EdgeDescriptor\n        dereference() const\n        {\n            return EdgeDescriptor(\n                get_edge_exists(*this->base(), 0), m_src, m_targ\n              , &get_property(*this->base())\n            );\n        }\n\n        VertexDescriptor m_src, m_inc, m_targ;\n        VerticesSizeType m_n;\n    };\n\n    //=======================================================================\n    // Undirected In Edge Iterator\n\n    template <\n        typename VertexDescriptor, typename MatrixIter\n      , typename VerticesSizeType, typename EdgeDescriptor\n    >\n    struct undir_adj_matrix_in_edge_iter\n      : iterator_adaptor<\n            undir_adj_matrix_in_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        >\n    {\n        typedef iterator_adaptor<\n            undir_adj_matrix_in_edge_iter<VertexDescriptor, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        > super_t;\n\n        undir_adj_matrix_in_edge_iter() { }\n\n        undir_adj_matrix_in_edge_iter(\n            const MatrixIter& i\n          , const VertexDescriptor& src\n          , const VerticesSizeType& n\n        )\n          : super_t(i), m_src(src), m_inc(src), m_targ(0), m_n(n)\n        {}\n\n        void increment()\n        {\n            if (m_targ < m_src)     // first half\n            {\n                ++this->base_reference();\n            }\n            else if (m_targ < m_n - 1)\n            {                  // second half\n                ++m_inc;\n                this->base_reference() += m_inc;\n            }\n            else\n            {                  // past-the-end\n                this->base_reference() += m_n - m_src;\n            }\n            ++m_targ;\n        }\n\n        inline EdgeDescriptor\n        dereference() const\n        {\n            return EdgeDescriptor(\n                     get_edge_exists(*this->base(), 0), m_targ, m_src\n              , &get_property(*this->base())\n            );\n        }\n\n        VertexDescriptor m_src, m_inc, m_targ;\n        VerticesSizeType m_n;\n    };\n\n    //=======================================================================\n    // Edge Iterator\n\n    template <typename Directed, typename MatrixIter,\n              typename VerticesSizeType, typename EdgeDescriptor>\n    struct adj_matrix_edge_iter\n      : iterator_adaptor<\n            adj_matrix_edge_iter<Directed, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        >\n    {\n        typedef iterator_adaptor<\n            adj_matrix_edge_iter<Directed, MatrixIter,  VerticesSizeType, EdgeDescriptor>\n          , MatrixIter\n          , EdgeDescriptor\n          , use_default\n          , EdgeDescriptor\n          , std::ptrdiff_t\n        > super_t;\n\n        adj_matrix_edge_iter() { }\n\n        adj_matrix_edge_iter(const MatrixIter& i, const MatrixIter& start, const VerticesSizeType& n)\n            : super_t(i), m_start(start), m_src(0), m_targ(0), m_n(n) { }\n\n        void increment()\n        {\n            increment_dispatch(this->base_reference(), Directed());\n        }\n\n        void increment_dispatch(MatrixIter& i, directedS)\n        {\n            ++i;\n            if (m_targ == m_n - 1)\n            {\n                m_targ = 0;\n                ++m_src;\n            }\n            else\n            {\n                ++m_targ;\n            }\n        }\n\n        void increment_dispatch(MatrixIter& i, undirectedS)\n        {\n            ++i;\n            if (m_targ == m_src)\n            {\n                m_targ = 0;\n                ++m_src;\n            }\n            else\n            {\n                ++m_targ;\n            }\n        }\n\n        inline EdgeDescriptor\n        dereference() const\n        {\n            return EdgeDescriptor(\n                get_edge_exists(\n                    *this->base(), 0), m_src, m_targ, &get_property(*this->base())\n            );\n        }\n\n        MatrixIter m_start;\n        VerticesSizeType m_src, m_targ, m_n;\n    };\n\n  } // namespace detail\n\n  //=========================================================================\n  // Adjacency Matrix Traits\n  template <typename Directed = directedS>\n  class adjacency_matrix_traits {\n    typedef typename Directed::is_directed_t is_directed;\n  public:\n    // The bidirectionalS tag is not allowed with the adjacency_matrix\n    // graph type. Instead, use directedS, which also provides the\n    // functionality required for a Bidirectional Graph (in_edges,\n    // in_degree, etc.).\n#if !defined(_MSC_VER) || _MSC_VER > 1300\n    BOOST_STATIC_ASSERT(type_traits::ice_not<(is_same<Directed, bidirectionalS>::value)>::value);\n#endif\n\n    typedef typename mpl::if_<is_directed,\n                                    bidirectional_tag, undirected_tag>::type\n      directed_category;\n\n    typedef disallow_parallel_edge_tag edge_parallel_category;\n\n    typedef std::size_t vertex_descriptor;\n\n    typedef detail::matrix_edge_desc_impl<directed_category,\n      vertex_descriptor> edge_descriptor;\n  };\n\n  struct adjacency_matrix_class_tag { };\n\n  struct adj_matrix_traversal_tag :\n    public virtual adjacency_matrix_tag,\n    public virtual vertex_list_graph_tag,\n    public virtual incidence_graph_tag,\n    public virtual adjacency_graph_tag,\n    public virtual edge_list_graph_tag { };\n\n  //=========================================================================\n  // Adjacency Matrix Class\n  template <typename Directed = directedS,\n            typename VertexProperty = no_property,\n            typename EdgeProperty = no_property,\n            typename GraphProperty = no_property,\n            typename Allocator = std::allocator<bool> >\n  class adjacency_matrix {\n    typedef adjacency_matrix self;\n    typedef adjacency_matrix_traits<Directed> Traits;\n\n  public:\n#if !defined(BOOST_MSVC) || BOOST_MSVC > 1300\n    // The bidirectionalS tag is not allowed with the adjacency_matrix\n    // graph type. Instead, use directedS, which also provides the\n    // functionality required for a Bidirectional Graph (in_edges,\n    // in_degree, etc.).\n    BOOST_STATIC_ASSERT(!(is_same<Directed, bidirectionalS>::value));\n#endif\n\n#ifndef BOOST_GRAPH_NO_BUNDLED_PROPERTIES\n    typedef typename detail::retag_property_list<vertex_bundle_t, VertexProperty>::type\n      vertex_property_type;\n    typedef typename detail::retag_property_list<edge_bundle_t, EdgeProperty>::type\n      edge_property_type;\n\n  private:\n    typedef typename detail::retag_property_list<vertex_bundle_t, VertexProperty>::retagged\n      maybe_vertex_bundled;\n\n    typedef typename detail::retag_property_list<edge_bundle_t, EdgeProperty>::retagged\n      maybe_edge_bundled;\n\n  public:\n    // The types that are actually bundled\n    typedef typename mpl::if_c<(is_same<maybe_vertex_bundled, no_property>::value),\n                           no_vertex_bundle,\n                           maybe_vertex_bundled>::type vertex_bundled;\n    typedef typename mpl::if_c<(is_same<maybe_edge_bundled, no_property>::value),\n                           no_edge_bundle,\n                           maybe_edge_bundled>::type edge_bundled;\n#else\n    typedef EdgeProperty     edge_property_type;\n    typedef VertexProperty   vertex_property_type;\n    typedef no_vertex_bundle vertex_bundled;\n    typedef no_edge_bundle   edge_bundled;\n#endif\n    typedef GraphProperty    graph_property_type;\n\n  public: // should be private\n    typedef typename mpl::if_<typename has_property<edge_property_type>::type,\n      std::pair<bool, edge_property_type>, char>::type StoredEdge;\n#if (defined(BOOST_MSVC) && BOOST_MSVC <= 1300) || defined(BOOST_NO_STD_ALLOCATOR)\n    typedef std::vector<StoredEdge> Matrix;\n#else\n    // This causes internal compiler error for MSVC\n    typedef typename Allocator::template rebind<StoredEdge>::other Alloc;\n    typedef std::vector<StoredEdge, Alloc> Matrix;\n#endif\n    typedef typename Matrix::iterator MatrixIter;\n    typedef typename Matrix::size_type size_type;\n  public:\n    // Graph concept required types\n    typedef typename Traits::vertex_descriptor vertex_descriptor;\n    typedef typename Traits::edge_descriptor edge_descriptor;\n    typedef typename Traits::directed_category directed_category;\n    typedef typename Traits::edge_parallel_category edge_parallel_category;\n    typedef adj_matrix_traversal_tag traversal_category;\n\n    static vertex_descriptor null_vertex()\n    {\n      return (std::numeric_limits<vertex_descriptor>::max)();\n    }\n\n    //private: if friends worked, these would be private\n\n    typedef detail::dir_adj_matrix_out_edge_iter<\n        vertex_descriptor, MatrixIter, size_type, edge_descriptor\n    > DirOutEdgeIter;\n\n    typedef detail::undir_adj_matrix_out_edge_iter<\n        vertex_descriptor, MatrixIter, size_type, edge_descriptor\n    > UnDirOutEdgeIter;\n\n    typedef typename mpl::if_<\n        typename Directed::is_directed_t, DirOutEdgeIter, UnDirOutEdgeIter\n    >::type unfiltered_out_edge_iter;\n\n    typedef detail::dir_adj_matrix_in_edge_iter<\n        vertex_descriptor, MatrixIter, size_type, edge_descriptor\n    > DirInEdgeIter;\n\n    typedef detail::undir_adj_matrix_in_edge_iter<\n        vertex_descriptor, MatrixIter, size_type, edge_descriptor\n    > UnDirInEdgeIter;\n\n    typedef typename mpl::if_<\n        typename Directed::is_directed_t, DirInEdgeIter, UnDirInEdgeIter\n    >::type unfiltered_in_edge_iter;\n\n    typedef detail::adj_matrix_edge_iter<\n        Directed, MatrixIter, size_type, edge_descriptor\n    > unfiltered_edge_iter;\n\n  public:\n\n    // IncidenceGraph concept required types\n    typedef filter_iterator<detail::does_edge_exist, unfiltered_out_edge_iter>\n      out_edge_iterator;\n\n    typedef size_type degree_size_type;\n\n    // BidirectionalGraph required types\n    typedef filter_iterator<detail::does_edge_exist, unfiltered_in_edge_iter>\n      in_edge_iterator;\n\n    // AdjacencyGraph required types\n     typedef typename adjacency_iterator_generator<self,\n       vertex_descriptor, out_edge_iterator>::type adjacency_iterator;\n\n    // VertexListGraph required types\n    typedef size_type vertices_size_type;\n    typedef integer_range<vertex_descriptor> VertexList;\n    typedef typename VertexList::iterator vertex_iterator;\n\n    // EdgeListGraph required types\n    typedef size_type edges_size_type;\n    typedef filter_iterator<\n        detail::does_edge_exist, unfiltered_edge_iter\n    > edge_iterator;\n\n    // PropertyGraph required types\n    typedef adjacency_matrix_class_tag graph_tag;\n\n    // Constructor required by MutableGraph\n    adjacency_matrix(vertices_size_type n_vertices,\n                     const GraphProperty& p = GraphProperty())\n      : m_matrix(Directed::is_directed ?\n                 (n_vertices * n_vertices)\n                 : (n_vertices * (n_vertices + 1) / 2)),\n      m_vertex_set(0, n_vertices),\n      m_vertex_properties(n_vertices),\n      m_num_edges(0),\n      m_property(p) { }\n\n    template <typename EdgeIterator>\n    adjacency_matrix(EdgeIterator first,\n                     EdgeIterator last,\n                     vertices_size_type n_vertices,\n                     const GraphProperty& p = GraphProperty())\n      : m_matrix(Directed::is_directed ?\n                 (n_vertices * n_vertices)\n                 : (n_vertices * (n_vertices + 1) / 2)),\n      m_vertex_set(0, n_vertices),\n      m_vertex_properties(n_vertices),\n      m_num_edges(0),\n      m_property(p)\n    {\n      for (; first != last; ++first) {\n        add_edge(first->first, first->second, *this);\n      }\n    }\n\n    template <typename EdgeIterator, typename EdgePropertyIterator>\n    adjacency_matrix(EdgeIterator first,\n                     EdgeIterator last,\n                     EdgePropertyIterator ep_iter,\n                     vertices_size_type n_vertices,\n                     const GraphProperty& p = GraphProperty())\n      : m_matrix(Directed::is_directed ?\n                 (n_vertices * n_vertices)\n                 : (n_vertices * (n_vertices + 1) / 2)),\n      m_vertex_set(0, n_vertices),\n      m_vertex_properties(n_vertices),\n      m_num_edges(0),\n      m_property(p)\n    {\n      for (; first != last; ++first, ++ep_iter) {\n        add_edge(first->first, first->second, *ep_iter, *this);\n      }\n    }\n\n#ifndef BOOST_GRAPH_NO_BUNDLED_PROPERTIES\n    // Directly access a vertex or edge bundle\n    vertex_bundled& operator[](vertex_descriptor v)\n    { return get(vertex_bundle, *this)[v]; }\n\n    const vertex_bundled& operator[](vertex_descriptor v) const\n    { return get(vertex_bundle, *this)[v]; }\n\n    edge_bundled& operator[](edge_descriptor e)\n    { return get(edge_bundle, *this)[e]; }\n\n    const edge_bundled& operator[](edge_descriptor e) const\n    { return get(edge_bundle, *this)[e]; }\n#endif\n\n    //private: if friends worked, these would be private\n\n    typename Matrix::const_reference\n    get_edge(vertex_descriptor u, vertex_descriptor v) const {\n      if (Directed::is_directed)\n        return m_matrix[u * m_vertex_set.size() + v];\n      else {\n        if (v > u)\n          std::swap(u, v);\n        return m_matrix[u * (u + 1)/2 + v];\n      }\n    }\n    typename Matrix::reference\n    get_edge(vertex_descriptor u, vertex_descriptor v) {\n      if (Directed::is_directed)\n        return m_matrix[u * m_vertex_set.size() + v];\n      else {\n        if (v > u)\n          std::swap(u, v);\n        return m_matrix[u * (u + 1)/2 + v];\n      }\n    }\n\n    Matrix m_matrix;\n    VertexList m_vertex_set;\n    std::vector<vertex_property_type> m_vertex_properties;\n    size_type m_num_edges;\n    GraphProperty m_property;\n  };\n\n  //=========================================================================\n  // Functions required by the AdjacencyMatrix concept\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  std::pair<typename adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor,\n            bool>\n  edge(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,\n       typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor v,\n       const adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    bool exists = detail::get_edge_exists(g.get_edge(u,v), 0);\n    typename adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor\n      e(exists, u, v, &detail::get_property(g.get_edge(u,v)));\n    return std::make_pair(e, exists);\n  }\n\n  //=========================================================================\n  // Functions required by the IncidenceGraph concept\n\n  // O(1)\n  template <typename VP, typename EP, typename GP, typename A>\n  std::pair<typename adjacency_matrix<directedS,VP,EP,GP,A>::out_edge_iterator,\n            typename adjacency_matrix<directedS,VP,EP,GP,A>::out_edge_iterator>\n  out_edges\n    (typename adjacency_matrix<directedS,VP,EP,GP,A>::vertex_descriptor u,\n     const adjacency_matrix<directedS,VP,EP,GP,A>& g_)\n  {\n    typedef adjacency_matrix<directedS,VP,EP,GP,A> Graph;\n    Graph& g = const_cast<Graph&>(g_);\n    typename Graph::vertices_size_type offset = u * g.m_vertex_set.size();\n    typename Graph::MatrixIter f = g.m_matrix.begin() + offset;\n    typename Graph::MatrixIter l = f + g.m_vertex_set.size();\n    typename Graph::unfiltered_out_edge_iter\n          first(f, u, g.m_vertex_set.size())\n        , last(l, u, g.m_vertex_set.size());\n    detail::does_edge_exist pred;\n    typedef typename Graph::out_edge_iterator out_edge_iterator;\n    return std::make_pair(out_edge_iterator(pred, first, last),\n                          out_edge_iterator(pred, last, last));\n  }\n\n  // O(1)\n  template <typename VP, typename EP, typename GP, typename A>\n  std::pair<\n    typename adjacency_matrix<undirectedS,VP,EP,GP,A>::out_edge_iterator,\n    typename adjacency_matrix<undirectedS,VP,EP,GP,A>::out_edge_iterator>\n  out_edges\n    (typename adjacency_matrix<undirectedS,VP,EP,GP,A>::vertex_descriptor u,\n     const adjacency_matrix<undirectedS,VP,EP,GP,A>& g_)\n  {\n    typedef adjacency_matrix<undirectedS,VP,EP,GP,A> Graph;\n    Graph& g = const_cast<Graph&>(g_);\n    typename Graph::vertices_size_type offset = u * (u + 1) / 2;\n    typename Graph::MatrixIter f = g.m_matrix.begin() + offset;\n    typename Graph::MatrixIter l = g.m_matrix.end();\n\n    typename Graph::unfiltered_out_edge_iter\n        first(f, u, g.m_vertex_set.size())\n      , last(l, u, g.m_vertex_set.size());\n\n    detail::does_edge_exist pred;\n    typedef typename Graph::out_edge_iterator out_edge_iterator;\n    return std::make_pair(out_edge_iterator(pred, first, last),\n                          out_edge_iterator(pred, last, last));\n  }\n\n  // O(N)\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  typename adjacency_matrix<D,VP,EP,GP,A>::degree_size_type\n  out_degree(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,\n             const adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    typename adjacency_matrix<D,VP,EP,GP,A>::degree_size_type n = 0;\n    typename adjacency_matrix<D,VP,EP,GP,A>::out_edge_iterator f, l;\n    for (tie(f, l) = out_edges(u, g); f != l; ++f)\n      ++n;\n    return n;\n  }\n\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A,\n    typename Dir, typename Vertex>\n  typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor\n  source(const detail::matrix_edge_desc_impl<Dir,Vertex>& e,\n         const adjacency_matrix<D,VP,EP,GP,A>&)\n  {\n    return e.m_source;\n  }\n\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A,\n    typename Dir, typename Vertex>\n  typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor\n  target(const detail::matrix_edge_desc_impl<Dir,Vertex>& e,\n         const adjacency_matrix<D,VP,EP,GP,A>&)\n  {\n    return e.m_target;\n  }\n\n  //=========================================================================\n  // Functions required by the BidirectionalGraph concept\n\n  // O(1)\n  template <typename VP, typename EP, typename GP, typename A>\n  std::pair<typename adjacency_matrix<directedS,VP,EP,GP,A>::in_edge_iterator,\n            typename adjacency_matrix<directedS,VP,EP,GP,A>::in_edge_iterator>\n  in_edges\n    (typename adjacency_matrix<directedS,VP,EP,GP,A>::vertex_descriptor u,\n     const adjacency_matrix<directedS,VP,EP,GP,A>& g_)\n  {\n    typedef adjacency_matrix<directedS,VP,EP,GP,A> Graph;\n    Graph& g = const_cast<Graph&>(g_);\n    typename Graph::MatrixIter f = g.m_matrix.begin() + u;\n    typename Graph::MatrixIter l = g.m_matrix.end();\n    typename Graph::unfiltered_in_edge_iter\n        first(f, l, u, g.m_vertex_set.size())\n      , last(l, l, u, g.m_vertex_set.size());\n    detail::does_edge_exist pred;\n    typedef typename Graph::in_edge_iterator in_edge_iterator;\n    return std::make_pair(in_edge_iterator(pred, first, last),\n                          in_edge_iterator(pred, last, last));\n  }\n\n  // O(1)\n  template <typename VP, typename EP, typename GP, typename A>\n  std::pair<\n    typename adjacency_matrix<undirectedS,VP,EP,GP,A>::in_edge_iterator,\n    typename adjacency_matrix<undirectedS,VP,EP,GP,A>::in_edge_iterator>\n  in_edges\n    (typename adjacency_matrix<undirectedS,VP,EP,GP,A>::vertex_descriptor u,\n     const adjacency_matrix<undirectedS,VP,EP,GP,A>& g_)\n  {\n    typedef adjacency_matrix<undirectedS,VP,EP,GP,A> Graph;\n    Graph& g = const_cast<Graph&>(g_);\n    typename Graph::vertices_size_type offset = u * (u + 1) / 2;\n    typename Graph::MatrixIter f = g.m_matrix.begin() + offset;\n    typename Graph::MatrixIter l = g.m_matrix.end();\n\n    typename Graph::unfiltered_in_edge_iter\n        first(f, u, g.m_vertex_set.size())\n      , last(l, u, g.m_vertex_set.size());\n\n    detail::does_edge_exist pred;\n    typedef typename Graph::in_edge_iterator in_edge_iterator;\n    return std::make_pair(in_edge_iterator(pred, first, last),\n                          in_edge_iterator(pred, last, last));\n  }\n\n  // O(N)\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  typename adjacency_matrix<D,VP,EP,GP,A>::degree_size_type\n  in_degree(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,\n             const adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    typename adjacency_matrix<D,VP,EP,GP,A>::degree_size_type n = 0;\n    typename adjacency_matrix<D,VP,EP,GP,A>::in_edge_iterator f, l;\n    for (tie(f, l) = in_edges(u, g); f != l; ++f)\n      ++n;\n    return n;\n  }\n\n  //=========================================================================\n  // Functions required by the AdjacencyGraph concept\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  std::pair<typename adjacency_matrix<D,VP,EP,GP,A>::adjacency_iterator,\n            typename adjacency_matrix<D,VP,EP,GP,A>::adjacency_iterator>\n  adjacent_vertices\n    (typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,\n     const adjacency_matrix<D,VP,EP,GP,A>& g_)\n  {\n      typedef adjacency_matrix<D,VP,EP,GP,A> Graph;\n      const Graph& cg = static_cast<const Graph&>(g_);\n      Graph& g = const_cast<Graph&>(cg);\n      typedef typename Graph::adjacency_iterator adjacency_iterator;\n      typename Graph::out_edge_iterator first, last;\n      boost::tie(first, last) = out_edges(u, g);\n      return std::make_pair(adjacency_iterator(first, &g),\n                            adjacency_iterator(last, &g));\n  }\n\n  //=========================================================================\n  // Functions required by the VertexListGraph concept\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  std::pair<typename adjacency_matrix<D,VP,EP,GP,A>::vertex_iterator,\n            typename adjacency_matrix<D,VP,EP,GP,A>::vertex_iterator>\n  vertices(const adjacency_matrix<D,VP,EP,GP,A>& g_) {\n    typedef adjacency_matrix<D,VP,EP,GP,A> Graph;\n    Graph& g = const_cast<Graph&>(g_);\n    return std::make_pair(g.m_vertex_set.begin(), g.m_vertex_set.end());\n  }\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  typename adjacency_matrix<D,VP,EP,GP,A>::vertices_size_type\n  num_vertices(const adjacency_matrix<D,VP,EP,GP,A>& g) {\n    return g.m_vertex_set.size();\n  }\n\n  //=========================================================================\n  // Functions required by the EdgeListGraph concept\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  std::pair<typename adjacency_matrix<D,VP,EP,GP,A>::edge_iterator,\n            typename adjacency_matrix<D,VP,EP,GP,A>::edge_iterator>\n  edges(const adjacency_matrix<D,VP,EP,GP,A>& g_)\n  {\n    typedef adjacency_matrix<D,VP,EP,GP,A> Graph;\n    Graph& g = const_cast<Graph&>(g_);\n\n    typename Graph::unfiltered_edge_iter\n      first(g.m_matrix.begin(), g.m_matrix.begin(),\n                                    g.m_vertex_set.size()),\n      last(g.m_matrix.end(), g.m_matrix.begin(),\n                                    g.m_vertex_set.size());\n    detail::does_edge_exist pred;\n    typedef typename Graph::edge_iterator edge_iterator;\n    return std::make_pair(edge_iterator(pred, first, last),\n                          edge_iterator(pred, last, last));\n  }\n\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  typename adjacency_matrix<D,VP,EP,GP,A>::edges_size_type\n  num_edges(const adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    return g.m_num_edges;\n  }\n\n  //=========================================================================\n  // Functions required by the MutableGraph concept\n\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A,\n            typename EP2>\n  std::pair<typename adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor, bool>\n  add_edge(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,\n           typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor v,\n           const EP2& ep,\n           adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    typedef typename adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor\n      edge_descriptor;\n    if (detail::get_edge_exists(g.get_edge(u,v), 0) == false) {\n      ++(g.m_num_edges);\n      detail::set_property(g.get_edge(u,v), EP(ep), 0);\n      detail::set_edge_exists(g.get_edge(u,v), true, 0);\n      return std::make_pair\n        (edge_descriptor(true, u, v, &detail::get_property(g.get_edge(u,v))),\n         true);\n    } else\n      return std::make_pair\n        (edge_descriptor(true, u, v, &detail::get_property(g.get_edge(u,v))),\n         false);\n  }\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  std::pair<typename adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor, bool>\n  add_edge(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,\n           typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor v,\n           adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    EP ep;\n    return add_edge(u, v, ep, g);\n  }\n\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  void\n  remove_edge(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,\n              typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor v,\n              adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    // Don'remove the edge unless it already exists.\n    if(detail::get_edge_exists(g.get_edge(u,v), 0)) {\n      --(g.m_num_edges);\n      detail::set_edge_exists(g.get_edge(u,v), false, 0);\n    }\n  }\n\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  void\n  remove_edge(typename adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor e,\n              adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    remove_edge(source(e, g), target(e, g), g);\n  }\n\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  inline typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor\n  add_vertex(adjacency_matrix<D,VP,EP,GP,A>& g) {\n    // UNDER CONSTRUCTION\n    assert(false);\n    return *vertices(g).first;\n  }\n\n  template <typename D, typename VP, typename EP, typename GP, typename A,\n            typename VP2>\n  inline typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor\n  add_vertex(const VP2& /*vp*/, adjacency_matrix<D,VP,EP,GP,A>& g) {\n    // UNDER CONSTRUCTION\n    assert(false);\n    return *vertices(g).first;\n  }\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  inline void\n  remove_vertex(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor /*u*/,\n                adjacency_matrix<D,VP,EP,GP,A>& /*g*/)\n  {\n    // UNDER CONSTRUCTION\n    assert(false);\n  }\n\n  // O(V)\n  template <typename VP, typename EP, typename GP, typename A>\n  void\n  clear_vertex\n    (typename adjacency_matrix<directedS,VP,EP,GP,A>::vertex_descriptor u,\n     adjacency_matrix<directedS,VP,EP,GP,A>& g)\n  {\n    typename adjacency_matrix<directedS,VP,EP,GP,A>::vertex_iterator\n      vi, vi_end;\n    for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n      remove_edge(u, *vi, g);\n    for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n      remove_edge(*vi, u, g);\n  }\n\n  // O(V)\n  template <typename VP, typename EP, typename GP, typename A>\n  void\n  clear_vertex\n    (typename adjacency_matrix<undirectedS,VP,EP,GP,A>::vertex_descriptor u,\n     adjacency_matrix<undirectedS,VP,EP,GP,A>& g)\n  {\n    typename adjacency_matrix<undirectedS,VP,EP,GP,A>::vertex_iterator\n      vi, vi_end;\n    for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n      remove_edge(u, *vi, g);\n  }\n\n  //=========================================================================\n  // Functions required by the PropertyGraph concept\n\n  // O(1)\n  template <typename D, typename VP, typename EP, typename GP, typename A,\n            typename Tag, typename Value>\n  inline void\n  set_property(adjacency_matrix<D,VP,EP,GP,A>& g, Tag, const Value& value)\n  {\n      get_property_value(g.m_property, Tag()) = value;\n  }\n\n  template <typename D, typename VP, typename EP, typename GP, typename A,\n            typename Tag>\n  inline\n  typename graph_property<adjacency_matrix<D,VP,EP,GP,A>, Tag>::type&\n  get_property(adjacency_matrix<D,VP,EP,GP,A>& g, Tag)\n  {\n      return get_property_value(g.m_property, Tag());\n  }\n\n  template <typename D, typename VP, typename EP, typename GP, typename A,\n            typename Tag>\n  inline\n  const\n  typename graph_property<adjacency_matrix<D,VP,EP,GP,A>, Tag>::type&\n  get_property(const adjacency_matrix<D,VP,EP,GP,A>& g, Tag)\n  {\n      return get_property_value(g.m_property, Tag());\n  }\n\n  //=========================================================================\n  // Vertex Property Map\n\n  template <typename GraphPtr, typename Vertex, typename T, typename R,\n    typename Tag>\n  class adj_matrix_vertex_property_map\n    : public put_get_helper<R,\n         adj_matrix_vertex_property_map<GraphPtr, Vertex, T, R, Tag> >\n  {\n  public:\n    typedef T value_type;\n    typedef R reference;\n    typedef Vertex key_type;\n    typedef boost::lvalue_property_map_tag category;\n    adj_matrix_vertex_property_map() { }\n    adj_matrix_vertex_property_map(GraphPtr g) : m_g(g) { }\n    inline reference operator[](key_type v) const {\n      return get_property_value(m_g->m_vertex_properties[v], Tag());\n    }\n    GraphPtr m_g;\n  };\n\n  template <class Property, class Vertex>\n  struct adj_matrix_vertex_id_map\n    : public boost::put_get_helper<Vertex,\n        adj_matrix_vertex_id_map<Property, Vertex> >\n  {\n    typedef Vertex value_type;\n    typedef Vertex reference;\n    typedef Vertex key_type;\n    typedef boost::readable_property_map_tag category;\n     adj_matrix_vertex_id_map() { }\n    template <class Graph>\n    inline adj_matrix_vertex_id_map(const Graph&) { }\n    inline value_type operator[](key_type v) const { return v; }\n  };\n\n  namespace detail {\n\n    struct adj_matrix_any_vertex_pa {\n      template <class Tag, class Graph, class Property>\n      struct bind_ {\n        typedef typename property_value<Property,Tag>::type Value;\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n\n        typedef adj_matrix_vertex_property_map<Graph*, Vertex, Value, Value&,\n          Tag> type;\n        typedef adj_matrix_vertex_property_map<const Graph*, Vertex, Value,\n          const Value&, Tag> const_type;\n      };\n    };\n    struct adj_matrix_id_vertex_pa {\n      template <class Tag, class Graph, class Property>\n      struct bind_ {\n        typedef typename Graph::vertex_descriptor Vertex;\n        typedef adj_matrix_vertex_id_map<Property, Vertex> type;\n        typedef adj_matrix_vertex_id_map<Property, Vertex> const_type;\n      };\n    };\n\n    template <class Tag>\n    struct adj_matrix_choose_vertex_pa_helper {\n      typedef adj_matrix_any_vertex_pa type;\n    };\n    template <>\n    struct adj_matrix_choose_vertex_pa_helper<vertex_index_t> {\n      typedef adj_matrix_id_vertex_pa type;\n    };\n\n    template <class Tag, class Graph, class Property>\n    struct adj_matrix_choose_vertex_pa {\n      typedef typename adj_matrix_choose_vertex_pa_helper<Tag>::type Helper;\n      typedef typename Helper::template bind_<Tag,Graph,Property> Bind;\n      typedef typename Bind::type type;\n      typedef typename Bind::const_type const_type;\n    };\n\n    struct adj_matrix_vertex_property_selector {\n      template <class Graph, class Property, class Tag>\n      struct bind_ {\n        typedef adj_matrix_choose_vertex_pa<Tag,Graph,Property> Choice;\n        typedef typename Choice::type type;\n        typedef typename Choice::const_type const_type;\n      };\n    };\n\n  } // namespace detail\n\n  template <>\n  struct vertex_property_selector<adjacency_matrix_class_tag> {\n    typedef detail::adj_matrix_vertex_property_selector type;\n  };\n\n  //=========================================================================\n  // Edge Property Map\n\n\n  template <typename Directed, typename Property, typename Vertex,\n    typename T, typename R, typename Tag>\n  class adj_matrix_edge_property_map\n    : public put_get_helper<R,\n         adj_matrix_edge_property_map<Directed, Property, Vertex, T, R, Tag> >\n  {\n  public:\n    typedef T value_type;\n    typedef R reference;\n    typedef detail::matrix_edge_desc_impl<Directed, Vertex> key_type;\n    typedef boost::lvalue_property_map_tag category;\n    inline reference operator[](key_type e) const {\n      Property& p = *(Property*)e.get_property();\n      return get_property_value(p, Tag());\n    }\n  };\n  struct adj_matrix_edge_property_selector {\n    template <class Graph, class Property, class Tag>\n    struct bind_ {\n      typedef typename property_value<Property,Tag>::type T;\n      typedef typename Graph::vertex_descriptor Vertex;\n      typedef adj_matrix_edge_property_map<typename Graph::directed_category,\n        Property, Vertex, T, T&, Tag> type;\n      typedef adj_matrix_edge_property_map<typename Graph::directed_category,\n        Property, Vertex, T, const T&, Tag> const_type;\n    };\n  };\n  template <>\n  struct edge_property_selector<adjacency_matrix_class_tag> {\n    typedef adj_matrix_edge_property_selector type;\n  };\n\n  //=========================================================================\n  // Functions required by PropertyGraph\n\n  namespace detail {\n\n    template <typename Property, typename D, typename VP, typename EP,\n              typename GP, typename A>\n    typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n      Property>::type\n    get_dispatch(adjacency_matrix<D,VP,EP,GP,A>& g, Property,\n                 vertex_property_tag)\n    {\n      typedef adjacency_matrix<D,VP,EP,GP,A> Graph;\n      typedef typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n        Property>::type PA;\n      return PA(&g);\n    }\n    template <typename Property, typename D, typename VP, typename EP,\n              typename GP, typename A>\n    typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n      Property>::type\n    get_dispatch(adjacency_matrix<D,VP,EP,GP,A>&, Property,\n                 edge_property_tag)\n    {\n      typedef typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n        Property>::type PA;\n      return PA();\n    }\n    template <typename Property, typename D, typename VP, typename EP,\n              typename GP, typename A>\n    typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n      Property>::const_type\n    get_dispatch(const adjacency_matrix<D,VP,EP,GP,A>& g, Property,\n                 vertex_property_tag)\n    {\n      typedef adjacency_matrix<D,VP,EP,GP,A> Graph;\n      typedef typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n        Property>::const_type PA;\n      return PA(&g);\n    }\n    template <typename Property, typename D, typename VP, typename EP,\n              typename GP, typename A>\n    typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n      Property>::const_type\n    get_dispatch(const adjacency_matrix<D,VP,EP,GP,A>&, Property,\n                 edge_property_tag)\n    {\n      typedef typename boost::property_map<adjacency_matrix<D,VP,EP,GP,A>,\n        Property>::const_type PA;\n      return PA();\n    }\n\n  } // namespace detail\n\n  template <typename Property, typename D, typename VP, typename EP,\n            typename GP, typename A>\n  inline\n  typename property_map<adjacency_matrix<D,VP,EP,GP,A>, Property>::type\n  get(Property p, adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    typedef typename property_kind<Property>::type Kind;\n    return detail::get_dispatch(g, p, Kind());\n  }\n\n  template <typename Property, typename D, typename VP, typename EP,\n            typename GP, typename A>\n  inline\n  typename property_map<adjacency_matrix<D,VP,EP,GP,A>, Property>::const_type\n  get(Property p, const adjacency_matrix<D,VP,EP,GP,A>& g)\n  {\n    typedef typename property_kind<Property>::type Kind;\n    return detail::get_dispatch(g, p, Kind());\n  }\n\n  template <typename Property, typename D, typename VP, typename EP,\n            typename GP, typename A, typename Key>\n  inline\n  typename property_traits<\n    typename property_map<adjacency_matrix<D,VP,EP,GP,A>, Property>::const_type\n  >::value_type\n  get(Property p, const adjacency_matrix<D,VP,EP,GP,A>& g,\n      const Key& key)\n  {\n    return get(get(p, g), key);\n  }\n\n  template <typename Property, typename D, typename VP, typename EP,\n            typename GP, typename A, typename Key, typename Value>\n  inline void\n  put(Property p, adjacency_matrix<D,VP,EP,GP,A>& g,\n      const Key& key, const Value& value)\n  {\n    typedef adjacency_matrix<D,VP,EP,GP,A> Graph;\n    typedef typename boost::property_map<Graph, Property>::type Map;\n    Map pmap = get(p, g);\n    put(pmap, key, value);\n  }\n\n  //=========================================================================\n  // Other Functions\n\n  template <typename D, typename VP, typename EP, typename GP, typename A>\n  typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor\n  vertex(typename adjacency_matrix<D,VP,EP,GP,A>::vertices_size_type n,\n         const adjacency_matrix<D,VP,EP,GP,A>&)\n  {\n    return n;\n  }\n\n  // Support for bundled properties\n#ifndef BOOST_GRAPH_NO_BUNDLED_PROPERTIES\n  template <typename Directed, typename VertexProperty, typename EdgeProperty, typename GraphProperty,\n            typename Allocator, typename T, typename Bundle>\n  inline\n  typename property_map<adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator>,\n                        T Bundle::*>::type\n  get(T Bundle::* p, adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator>& g)\n  {\n    typedef typename property_map<adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator>,\n                                  T Bundle::*>::type\n      result_type;\n    return result_type(&g, p);\n  }\n\n  template <typename Directed, typename VertexProperty, typename EdgeProperty, typename GraphProperty,\n            typename Allocator, typename T, typename Bundle>\n  inline\n  typename property_map<adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator>,\n                        T Bundle::*>::const_type\n  get(T Bundle::* p, adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator> const & g)\n  {\n    typedef typename property_map<adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator>,\n                                  T Bundle::*>::const_type\n      result_type;\n    return result_type(&g, p);\n  }\n\n  template <typename Directed, typename VertexProperty, typename EdgeProperty, typename GraphProperty,\n            typename Allocator, typename T, typename Bundle, typename Key>\n  inline T\n  get(T Bundle::* p, adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator> const & g,\n      const Key& key)\n  {\n    return get(get(p, g), key);\n  }\n\n  template <typename Directed, typename VertexProperty, typename EdgeProperty, typename GraphProperty,\n            typename Allocator, typename T, typename Bundle, typename Key>\n  inline void\n  put(T Bundle::* p, adjacency_matrix<Directed, VertexProperty, EdgeProperty, GraphProperty, Allocator>& g,\n      const Key& key, const T& value)\n  {\n    put(get(p, g), key, value);\n  }\n\n#endif\n\n#define ADJMAT_PARAMS \\\n    typename D, typename VP, typename EP, typename GP, typename A\n#define ADJMAT adjacency_matrix<D,VP,EP,GP,A>\ntemplate <ADJMAT_PARAMS>\nstruct graph_mutability_traits<ADJMAT> {\n    typedef mutable_edge_property_graph_tag category;\n};\n#undef ADJMAT_PARAMS\n#undef ADJMAT\n\n\n} // namespace boost\n\n#endif // BOOST_ADJACENCY_MATRIX_HPP\n", "meta": {"hexsha": "a3694dab7477189f6f38bb831c569380c46aad32", "size": 47914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/adjacency_matrix.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": "2017-04-08T10:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-08T10:44:28.000Z", "max_issues_repo_path": "boost/graph/adjacency_matrix.hpp", "max_issues_repo_name": "jonstewart/boost-svn", "max_issues_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/adjacency_matrix.hpp", "max_forks_repo_name": "jonstewart/boost-svn", "max_forks_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "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.9737226277, "max_line_length": 117, "alphanum_fraction": 0.6358475602, "num_tokens": 11054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.03622005612506083, "lm_q1q2_score": 0.012499732771072615}}
{"text": "/// \\file   quantity.hpp\n///\n/// \\brief  A class used to enforce conversion without numerical error when\n///         counting property, goods and other items.\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2018-02-05\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#ifndef ESL_AMOUNT_HPP\n#define ESL_AMOUNT_HPP\n\n#include <array>\n#include <cstdint>\n#include <vector>\n\n#include <iostream>\n\n#include <boost/serialization/nvp.hpp>\n\n#ifndef EXCEPTION_ON_BASIS_CHANGE\n#define EXCEPTION_ON_BASIS_CHANGE true\n#endif\n\n\nnamespace esl {\n    ///\n    /// \\brief  The quantity class is used to losslessly deal with quantities of\n    ///         economic goods in large quantities. A quantity is associated\n    ///         with a basis (the number of parts that make up a unit amount of\n    ///         the object).\n    ///\n    /// \\details    The quantity is not a fraction: a property that dividies\n    ///             into single parts, is not the same as a property that\n    ///             divides into 100 parts. Hence, quantity(1,1) is not the same\n    ///             as quantity(100,100). Implicit conversion or combination of\n    ///             `quantity` with different `basis` is not encouraged, and the\n    ///             preprocessor option EXCEPTION_ON_BASIS_CHANGE can be used to\n    ///             disallow this.\n    ///\n    struct quantity\n    {\n    private:\n    public:\n        ///\n        /// \\note   We explicitly delete the division into quantity operator as\n        /// this\n        ///         loses the remainder. Instead, use\n        ///         quantity::divide()\n        template<typename divisor_type_>\n        quantity &operator/=(divisor_type_) const = delete;\n\n        ///\n        ///`\\brief  The number of parts\n        ///\n        std::uint64_t amount;\n\n        ///\n        /// \\brief  The number of sub-units to make one part\n        ///\n        std::uint64_t basis;\n\n        ///\n        /// \\param amount   The number of parts of something, e.g. 23 cents.\n        ///                 Default: 0\n        /// \\param basis    The number of parts to make one unit, e.g.\n        ///                 100 cents to 1 dollar. Default: 1\n        explicit constexpr quantity(std::uint64_t amount = 0,\n                                    std::uint64_t basis  = 1)\n        : amount(amount), basis(basis)\n        {\n            if(basis < 1) {\n                throw std::logic_error(\"quantity with 0 basis\");\n            }\n        }\n\n        ///\n        /// \\param q\n        constexpr quantity(const quantity &q)\n        : quantity(q.amount, q.basis)\n        {\n\n        }\n\n        ///\n        /// \\param operand\n        /// \\return\n        constexpr void assert_equal_basis(const quantity &operand) const\n        {\n            if(basis != operand.basis) {\n                throw std::logic_error(\"assert_equal_basis\");\n            }\n        }\n\n        ///\n        /// \\tparam divisor_\n        /// \\return\n        template<uint64_t divisor_>\n        constexpr std::array<quantity, divisor_> divide() const\n        {\n            static_assert(divisor_ != 0, \"division by zero\");\n\n            std::uint64_t quotient_  = amount / divisor_;\n            std::uint64_t remainder_ = amount % divisor_;\n\n            std::array<quantity, divisor_> result_;\n\n            auto iterator_ = result_.begin();\n            for(; iterator_ != result_.begin() + remainder_; ++iterator_) {\n                iterator_->amount = quotient_ + 1;\n                iterator_->basis  = basis;\n            }\n\n            for(; iterator_ != result_.end(); ++iterator_) {\n                iterator_->amount = quotient_;\n                iterator_->basis  = basis;\n            }\n\n            return result_;\n        }\n\n\n        [[nodiscard]] constexpr quantity\n        operator*(const std::uint64_t &operand) const\n        {\n            return quantity(amount * operand, basis);\n        }\n\n        [[nodiscard]]\n#if !EXCEPTION_ON_BASIS_CHANGE\n        constexpr\n#endif\n        quantity\n        operator*(const quantity &operand) const\n        {\n            auto numerator_ = amount * operand.amount;\n            auto remainder_ = numerator_ % operand.basis;\n\n            if(!remainder_) {\n                return quantity(numerator_ / operand.basis, basis);\n            }\n\n            if(EXCEPTION_ON_BASIS_CHANGE) {\n                throw std::logic_error(\"EXCEPTION_ON_BASIS_CHANGE\");\n            }\n\n            auto coremainder_ = numerator_ % basis;\n\n            if(!coremainder_) {\n                return quantity(numerator_ / basis, operand.basis);\n            }\n\n            return quantity(numerator_, basis * operand.basis);\n        }\n\n        ///\n        /// \\param operand\n        /// \\return\n        quantity &operator*=(const std::uint64_t &operand)\n        {\n            (*this) = (*this) * operand;\n            return *this;\n        }\n\n        ///\n        /// \\brief  Add together two quantities.\n        ///\n        /// \\param operand\n        /// \\return\n        [[nodiscard]]\n#if !EXCEPTION_ON_BASIS_CHANGE\n        constexpr\n#endif\n        quantity operator+(const quantity &operand) const\n        {\n            auto numerator_ = amount * operand.basis + operand.amount * basis;\n            auto remainder_ = numerator_ % operand.basis;\n\n            if(!remainder_) {\n                return quantity(numerator_ / operand.basis, basis);\n            }\n\n            if(EXCEPTION_ON_BASIS_CHANGE) {\n                throw std::logic_error(\"EXCEPTION_ON_BASIS_CHANGE\");\n            }\n\n            auto coremainder_ = numerator_ % basis;\n\n            if(!coremainder_) {\n                return quantity(numerator_ / basis, operand.basis);\n            }\n\n            return quantity(numerator_, basis * operand.basis);\n        }\n\n        ///\n        /// \\param operand\n        /// \\return\n        quantity &operator+=(const quantity &operand)\n        {\n            (*this) = (*this) + operand;\n            return *this;\n        }\n\n        ///\n        /// \\brief  subtract two quantities.\n        ///\n        /// \\param operand\n        /// \\return\n        [[nodiscard]]\n#if !EXCEPTION_ON_BASIS_CHANGE\n        constexpr\n#endif\n        quantity operator-(const quantity &operand) const\n        {\n            auto left_  = amount * operand.basis;\n            auto right_ = operand.amount * basis;\n            if(right_ > left_) {\n                throw std::logic_error(\n                    \"subtraction results in negative quantity\");\n            }\n            auto numerator_ = left_ - right_;\n            auto remainder_ = numerator_ % operand.basis;\n\n            if(!remainder_) {\n                return quantity(numerator_ / operand.basis, basis);\n            }\n\n            if(EXCEPTION_ON_BASIS_CHANGE) {\n                throw std::logic_error(\"EXCEPTION_ON_BASIS_CHANGE\");\n            }\n\n            auto coremainder_ = numerator_ % basis;\n\n            if(!coremainder_) {\n                return quantity(numerator_ / basis, operand.basis);\n            }\n\n            return quantity(numerator_, basis * operand.basis);\n        }\n\n\n        quantity &operator=(const quantity &operand)\n        {\n            amount = operand.amount;\n            basis  = operand.basis;\n            return *this;\n        }\n\n        ///\n        /// \\param operand\n        /// \\return\n        quantity &operator-=(const quantity &operand)\n        {\n            (*this) = (*this) - operand;\n            return *this;\n        }\n\n        ///\n        /// \\brief  true if equal to the truncated double equivalent of this\n        ///         quantity\n        ///\n        /// \\param operand\n        /// \\return\n        [[nodiscard]] constexpr bool operator==(double operand) const\n        {\n            return (amount == std::uint64_t(operand * basis));\n        }\n\n        ///\n        /// \\param operand\n        /// \\return\n        [[nodiscard]] constexpr bool operator==(const quantity &operand) const\n        {\n            return (amount == operand.amount && basis == operand.basis);\n        }\n\n        [[nodiscard]] constexpr bool operator!=(double operand) const\n        {\n            return !((*this) == operand);\n        }\n\n        [[nodiscard]] constexpr bool operator<(double operand) const\n        {\n            return (amount < operand * basis);\n        }\n\n        [[nodiscard]] constexpr bool operator<(const quantity &operand) const\n        {\n            return (amount * basis < operand.amount * operand.basis);\n        }\n\n        [[nodiscard]] constexpr bool operator>(double operand) const\n        {\n            return (amount > operand * basis);\n        }\n\n        [[nodiscard]] constexpr bool operator>(const quantity &operand) const\n        {\n            return (amount * basis > operand.amount * operand.basis);\n        }\n\n        [[nodiscard]] constexpr bool operator<=(double operand) const\n        {\n            return (*this) < operand || (*this) == operand;\n        }\n\n        [[nodiscard]] constexpr bool operator<=(const quantity &operand) const\n        {\n            return (*this) < operand || (*this) == operand;\n        }\n\n        [[nodiscard]] constexpr bool operator>=(double operand) const\n        {\n            return (*this) > operand || (*this) == operand;\n        }\n\n        [[nodiscard]] constexpr bool operator>=(const quantity & operand) const\n        {\n            return (*this) > operand || (*this) == operand;\n        }\n\n        ///\n        /// \\brief  Division into `divisor` parts, allocating the remainder\n        /// starting at the first quotient.\n        ///\n        /// \\param divisor\n        /// \\return\n        [[nodiscard]] std::vector<quantity>\n        operator/(std::uint64_t divisor) const\n        {\n            std::uint64_t quotient_  = amount / divisor;\n            std::uint64_t remainder_ = amount % divisor;\n\n            if(divisor >= (2 * remainder_)) {\n                std::vector<quantity> result_(divisor,\n                                              quantity(quotient_, basis));\n                for(auto iterator_ = result_.begin();\n                    iterator_ != result_.begin() + remainder_;\n                    ++iterator_) {\n                    iterator_->amount = quotient_ + 1;\n                }\n                return result_;\n            }\n\n            std::vector<quantity> result_(divisor,\n                                          quantity(quotient_ + 1, basis));\n            for(auto iterator_ = result_.begin() + remainder_;\n                iterator_ != result_.end();\n                ++iterator_) {\n                iterator_->amount = quotient_;\n            }\n            return result_;\n        }\n\n        ///\n        /// \\return amount/basis as a double precision floating point number.\n        ///\n        [[nodiscard]] explicit operator double() const\n        {\n            return double(amount) / basis;\n        }\n\n        friend std::ostream &operator<<(std::ostream &stream, const quantity &q)\n        {\n            stream << q.amount;\n            if(q.basis != 1) {\n                stream << '/';\n                stream << q.basis;\n            }\n            return stream;\n        }\n\n        template<class archive_t>\n        void serialize(archive_t &archive, const unsigned int version)\n        {\n            (void)version;\n            archive &BOOST_SERIALIZATION_NVP(amount);\n            archive &BOOST_SERIALIZATION_NVP(basis);\n        }\n    };\n\n}  // namespace esl\n\n\n#endif  // ESL_AMOUNT_HPP\n", "meta": {"hexsha": "1909e500d14e52d7dda7b0f05ed7a03c1e0e6732", "size": 12243, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "esl/quantity.hpp", "max_stars_repo_name": "fagan2888/ESL", "max_stars_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-17T18:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T18:18:08.000Z", "max_issues_repo_path": "esl/quantity.hpp", "max_issues_repo_name": "fagan2888/ESL", "max_issues_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/quantity.hpp", "max_forks_repo_name": "fagan2888/ESL", "max_forks_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "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.3796526055, "max_line_length": 80, "alphanum_fraction": 0.521114106, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989356, "lm_q2_score": 0.029312231493326745, "lm_q1q2_score": 0.012496436784053868}}
{"text": "// Project: libv.algo, File: src/libv/algo/wildcard.cpp, Author: Császár Mátyás [Vader]\n\n// hpp\n#include <libv/algo/wildcard.hpp>\n// ext\n#include <boost/container/small_vector.hpp>\n\n\nnamespace libv {\n\n// -------------------------------------------------------------------------------------------------\n\nbool match_wildcard(const std::string_view str, const std::string_view pattern) noexcept {\n\tstatic constexpr auto WILDCARD_SINGLE = '?';\n\tstatic constexpr auto WILDCARD_ANY = '*';\n//\tstatic constexpr auto WILDCARD_ESCAPE = '\\\\';\n//\tstatic constexpr auto WILDCARD_ESCAPE_ESCAPE = \"\\\\\\\\\";\n\n\tboost::container::small_vector<bool, 1024> table;\n\ttable.resize((str.size() + 1) * (pattern.size() + 1), false);\n\tconst auto index = [&](size_t i, size_t j) -> bool& {\n\t\treturn table[(pattern.size() + 1) * i + j];\n\t};\n\n\t// clear\n\tfor (size_t i = 0; i <= str.size(); ++i)\n\t\tfor (size_t j = 0; j <= pattern.size(); ++j)\n\t\t\tindex(i, j) = false;\n\n\t// accept any leading WILDCARD_ANY as str start\n\tfor (size_t j = 1; j <= pattern.size() && pattern[j - 1] == WILDCARD_ANY; ++j)\n\t\tindex(0, j) = true;\n\n\t// base case\n\tindex(0, 0) = true;\n\n\t// solve\n\tfor (size_t i = 1; i <= str.size(); i++) {\n\t\tfor (size_t j = 1; j <= pattern.size(); j++) {\n\t\t\tif (str[i - 1] == pattern[j - 1] || pattern[j - 1] == WILDCARD_SINGLE)\n\t\t\t\tindex(i, j) = index(i - 1, j - 1);\n\n\t\t\telse if (pattern[j - 1] == WILDCARD_ANY)\n\t\t\t\tindex(i, j) = index(i, j - 1) || index(i - 1, j);\n\t\t}\n\t}\n\n\treturn index(str.size(), pattern.size());\n}\n\n// -------------------------------------------------------------------------------------------------\n\nstruct ImplWildcardGlobMatcher {\n\tstatic constexpr std::string_view WILDCARD_ESCAPE = \"\\\\\";\n\n\tstatic constexpr std::string_view WILDCARD_LAYER_ANY = \"**\";\n\tstatic constexpr std::string_view WILDCARD_LAYER = \"*\";\n\tstatic constexpr std::string_view WILDCARD_SINGLE = \"?\";\n\t//\tstatic constexpr std::string_view WILDCARD_RANGE = \"[abc]\";\n\t//\tstatic constexpr std::string_view WILDCARD_RANGE = \"[a-z]\";\n\t//\tstatic constexpr std::string_view WILDCARD_NEGATED_RANGE = \"[!abc]\";\n\t//\tstatic constexpr std::string_view WILDCARD_NEGATED_RANGE = \"[!a-z]\";\n\t//\tstatic constexpr std::string_view WILDCARD_ALTERNATE = \"(a.txt|b.jpg)\";\n\n\t/// Separator is not allowed in WILDCARD_SINGLE or WILDCARD_LAYER (but it is allowed in WILDCARD_LAYER_ANY)\n\tstatic constexpr std::string_view WILDCARD_SEPARATOR = \"/\";\n\n\tenum class TokenType {\n\t\tliteral,   // abc\n\t\tsingle,    // ?\n\t\tlayer,     // *\n\t\tlayer_any, // **\n\t};\n\n\tstruct Token {\n\t\tTokenType type;\n\t\tsize_t begin = 0;\n\t\tsize_t size = 0;\n\t};\n\npublic:\n\tboost::container::small_vector<Token, 10> pattern;\n\tboost::container::small_vector<std::string_view::value_type, 256> pattern_literals;\n\npublic:\n\tmutable boost::container::small_vector<bool, 1024> table;\n\npublic:\n\tvoid preprocess(const std::string_view pattern_str) {\n\t\tpattern.clear();\n\t\tpattern_literals.clear();\n\n\t\t// Preprocess pattern\n\t\tfor (size_t i = 0; i < pattern_str.size();) {\n\t\t\tif (pattern_str.substr(i).starts_with(WILDCARD_ESCAPE) && pattern_str.size() - i != WILDCARD_ESCAPE.size()) {\n\t\t\t\ti += WILDCARD_ESCAPE.size();\n\n\t\t\t\tif (!pattern.empty() && pattern.back().type == TokenType::literal)\n\t\t\t\t\tpattern.back().size++;\n\t\t\t\telse\n\t\t\t\t\tpattern.push_back(Token{TokenType::literal, pattern_literals.size(), 1});\n\n\t\t\t\tpattern_literals.push_back(pattern_str[i]);\n\t\t\t\ti++;\n\n\t\t\t} else if (pattern_str.substr(i).starts_with(WILDCARD_LAYER_ANY)) {\n\t\t\t\ti += WILDCARD_LAYER_ANY.size();\n\t\t\t\tif (!pattern.empty() && pattern.back().type == TokenType::layer)\n\t\t\t\t\tpattern.back().type = TokenType::layer_any;\n\n\t\t\t\telse if (pattern.empty() || pattern.back().type != TokenType::layer_any)\n\t\t\t\t\tpattern.push_back(Token{TokenType::layer_any});\n\n\t\t\t} else if (pattern_str.substr(i).starts_with(WILDCARD_LAYER)) {\n\t\t\t\ti += WILDCARD_LAYER.size();\n\t\t\t\tif (pattern.empty() || (pattern.back().type != TokenType::layer && pattern.back().type != TokenType::layer_any))\n\t\t\t\t\tpattern.push_back(Token{TokenType::layer});\n\n\t\t\t} else if (pattern_str.substr(i).starts_with(WILDCARD_SINGLE)) {\n\t\t\t\ti += WILDCARD_SINGLE.size();\n\t\t\t\tif (!pattern.empty() && pattern.back().type == TokenType::single)\n\t\t\t\t\tpattern.back().size++;\n\t\t\t\telse\n\t\t\t\t\tpattern.push_back(Token{TokenType::single, 0, 1});\n\n\t\t\t} else {\n\t\t\t\tif (!pattern.empty() && pattern.back().type == TokenType::literal)\n\t\t\t\t\tpattern.back().size++;\n\t\t\t\telse\n\t\t\t\t\tpattern.push_back(Token{TokenType::literal, pattern_literals.size(), 1});\n\n\t\t\t\tpattern_literals.push_back(pattern_str[i]);\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tinline bool& index(size_t i, size_t j) const noexcept {\n\t\treturn table[(pattern.size() + 1) * i + j];\n\t}\n\n\tbool match(const std::string_view str) const {\n\t\ttable.resize((str.size() + 1) * (pattern.size() + 1), false);\n\n\t\t// accept any leading WILDCARD_ANY and at most one WILDCARD_LAYER as str start\n\t\t{\n\t\t\tbool layer_accept = false;\n\t\t\tfor (size_t j = 1; j <= pattern.size(); ++j) {\n\t\t\t\tif (pattern[j - 1].type == TokenType::layer && !layer_accept) {\n\t\t\t\t\tlayer_accept = true;\n\t\t\t\t\tindex(0, j) = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (pattern[j - 1].type == TokenType::layer_any) {\n\t\t\t\t\tindex(0, j) = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// base case\n\t\tindex(0, 0) = true;\n\n\t\t// solve\n\t\tfor (size_t i = 1; i <= str.size(); i++) {\n\t\t\tfor (size_t j = 1; j <= pattern.size(); j++) {\n\t\t\t\tif (index(i, j)) // Optimization: Already calculated\n\t\t\t\t\tcontinue;\n\n\t\t\t\tconst auto& token = pattern[j - 1];\n\t\t\t\tconst auto str_literal = str.substr(i - 1);\n\n\t\t\t\tconst bool up = index(i - 1, j);\n\t\t\t\tconst bool left = index(i, j - 1);\n\t\t\t\tconst bool up_left = index(i - 1, j - 1);\n\n\t\t\t\tif (token.type == TokenType::literal) {\n\t\t\t\t\tconst bool accept = str_literal.starts_with(std::string_view(pattern_literals.data() + token.begin, token.size));\n\t\t\t\t\tif (accept && up_left)\n\t\t\t\t\t\t// Optimization: Prefill the every matched character\n\t\t\t\t\t\tfor (size_t s = 0; s < token.size && i + s <= str.size() && index(i + s, j) == false; ++s)\n\t\t\t\t\t\t\tindex(i + s, j) = true;\n\n\t\t\t\t} else if (token.type == TokenType::single) {\n\t\t\t\t\tconst bool accept = str_literal.size() >= token.size && str_literal.substr(0, token.size).find_first_of(WILDCARD_SEPARATOR) == str_literal.npos;\n\t\t\t\t\tif (accept && up_left)\n\t\t\t\t\t\t// Optimization: Prefill the every matched character\n\t\t\t\t\t\tfor (size_t s = 0; s < token.size && i + s <= str.size() && index(i + s, j) == false; ++s)\n\t\t\t\t\t\t\tindex(i + s, j) = true;\n\n\t\t\t\t} else if (token.type == TokenType::layer_any) {\n\t\t\t\t\tindex(i, j) |= left || up;\n\n\t\t\t\t} else if (token.type == TokenType::layer) {\n\t\t\t\t\tindex(i, j) |= left || (up && !str_literal.starts_with(WILDCARD_SEPARATOR));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn index(str.size(), pattern.size());\n\t}\n};\n\n// -------------------------------------------------------------------------------------------------\n\nWildcardGlobMatcher::WildcardGlobMatcher(const std::string_view pattern_str) :\n\tself(std::make_unique<ImplWildcardGlobMatcher>()) {\n\tself->preprocess(pattern_str);\n}\n\nvoid WildcardGlobMatcher::pattern(const std::string_view pattern_str) {\n\tself->preprocess(pattern_str);\n}\n\nbool WildcardGlobMatcher::match(const std::string_view str) const {\n\treturn self->match(str);\n}\n\nWildcardGlobMatcher::~WildcardGlobMatcher() {\n\t// For the sake of forward declared unique_ptr\n}\n\n// -------------------------------------------------------------------------------------------------\n\nbool match_wildcard_glob(const std::string_view str, const std::string_view pattern_str) noexcept {\n\tImplWildcardGlobMatcher matcher;\n\tmatcher.preprocess(pattern_str);\n\treturn matcher.match(str);\n}\n\n// -------------------------------------------------------------------------------------------------\n\n} // namespace libv\n", "meta": {"hexsha": "6cbb0353aa0d87d4b1ea320788fd5d1ec2f0902c", "size": 7664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libv/algo/wildcard.cpp", "max_stars_repo_name": "cpplibv/libv", "max_stars_repo_head_hexsha": "293e382f459f0acbc540de8ef6283782b38d2e63", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-04-11T03:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-29T15:24:12.000Z", "max_issues_repo_path": "src/libv/algo/wildcard.cpp", "max_issues_repo_name": "cpplibv/libv", "max_issues_repo_head_hexsha": "293e382f459f0acbc540de8ef6283782b38d2e63", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libv/algo/wildcard.cpp", "max_forks_repo_name": "cpplibv/libv", "max_forks_repo_head_hexsha": "293e382f459f0acbc540de8ef6283782b38d2e63", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T06:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T06:39:06.000Z", "avg_line_length": 32.6127659574, "max_line_length": 149, "alphanum_fraction": 0.6068632568, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.045352582328487, "lm_q1q2_score": 0.012477843989817605}}
{"text": "/*\n\nCopyright (c) 2005-2017, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef NAGAIHONDADIFFERENTIALADHESIONFORCE_HPP_\n#define NAGAIHONDADIFFERENTIALADHESIONFORCE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"NagaiHondaForce.hpp\"\n\n#include <iostream>\n\n/**\n * A force class for use in vertex-based simulations, based on a model\n * model proposed by T. Nagai and H. Honda (\"A dynamic cell model for\n * the formation of epithelial tissues\", Philosophical Magazine Part B\n * 81:699-719) to include differential adhesion between normal and\n * labelled cells. To include differential adhesion we override the\n * GetAdhesionParameter() method.\n *\n * Each of the model parameter member variables are rescaled such that\n * mDampingConstantNormal takes the default value 1, whereas Nagai and\n * Honda (who denote the parameter by nu) take the value 0.01.\n */\ntemplate<unsigned DIM>\nclass NagaiHondaDifferentialAdhesionForce  : public NagaiHondaForce<DIM>\n{\nprivate:\n\n    /**\n     * Cell-cell adhesion energy parameter for two labelled cells.\n     * Has units of kg (cell size at equilibrium rest length)^2 s^-2.\n     * Takes the default value 1.0.\n     */\n    double mNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter;\n\n    /**\n     * Cell-cell adhesion energy parameter for labelled and non-labelled cells.\n     * Has has units of kg (cell size at equilibrium rest length)^2 s^-2.\n     * Takes the default value 1.0.\n     */\n    double mNagaiHondaLabelledCellCellAdhesionEnergyParameter;\n\n    /**\n     * Cell-boundary adhesion energy parameter for labelled cells.\n     * Has units of kg (cell size at equilibrium rest length)^2 s^-2.\n     * Takes the default value 1.0.\n     */\n    double mNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter;\n\n    friend class boost::serialization::access;\n    /**\n     * Boost Serialization method for archiving/checkpointing.\n     * Archives the object and its member variables.\n     *\n     * @param archive  The boost archive.\n     * @param version  The current version of this class.\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<NagaiHondaForce<DIM> >(*this);\n        archive & mNagaiHondaLabelledCellCellAdhesionEnergyParameter;\n        archive & mNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter;\n        archive & mNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter;\n    }\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    NagaiHondaDifferentialAdhesionForce();\n\n    /**\n     * Destructor.\n     */\n    virtual ~NagaiHondaDifferentialAdhesionForce();\n\n    /**\n     * Overridden GetAdhesionParameter() method.\n     *\n     * Get the adhesion parameter for the edge between two given nodes. Depends\n     * on the type of cells attached to the elements.\n     *\n     * @param pNodeA one node\n     * @param pNodeB the other node\n     * @param rVertexCellPopulation reference to the cell population\n     *\n     * @return the adhesion parameter for this edge.\n     */\n    virtual double GetAdhesionParameter(Node<DIM>* pNodeA, Node<DIM>* pNodeB, VertexBasedCellPopulation<DIM>& rVertexCellPopulation);\n\n    /**\n     * @return mNagaiHondaLabelledCellCellAdhesionEnergyParameter\n     */\n    double GetNagaiHondaLabelledCellCellAdhesionEnergyParameter();\n\n    /**\n     * @return mNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter\n     */\n    double GetNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter();\n\n    /**\n     * @return mNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter\n     */\n    double GetNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter();\n\n    /**\n     * Set mNagaiHondaLabelledCellCellAdhesionEnergyParameter.\n     *\n     * @param labelledCellCellAdhesionEnergyParameter the new value of mNagaiHondaLabelledCellCellAdhesionEnergyParameter\n     */\n    void SetNagaiHondaLabelledCellCellAdhesionEnergyParameter(double labelledCellCellAdhesionEnergyParameter);\n\n    /**\n     * Set mNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter.\n     *\n     * @param labelledCellLabelledCellAdhesionEnergyParameter the new value of mNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter\n     */\n    void SetNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter(double labelledCellLabelledCellAdhesionEnergyParameter);\n\n    /**\n     * Set mNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter.\n     *\n     * @param labelledCellBoundaryAdhesionEnergyParameter the new value of mNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter\n     */\n    void SetNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter(double labelledCellBoundaryAdhesionEnergyParameter);\n\n    /**\n     * Overridden OutputForceParameters() method.\n     *\n     * @param rParamsFile the file stream to which the parameters are output\n     */\n    void OutputForceParameters(out_stream& rParamsFile);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(NagaiHondaDifferentialAdhesionForce)\n\n#endif /*NAGAIHONDADIFFERENTIALADHESIONFORCE_HPP_*/\n", "meta": {"hexsha": "b4657c40ac897689b0e556d4d65b9a580cd8d6fe", "size": 6735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/population/forces/NagaiHondaDifferentialAdhesionForce.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell_based/src/population/forces/NagaiHondaDifferentialAdhesionForce.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/population/forces/NagaiHondaDifferentialAdhesionForce.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4857142857, "max_line_length": 137, "alphanum_fraction": 0.7646622123, "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.027169232274156463, "lm_q1q2_score": 0.012420053640531495}}
{"text": "//   Copyright 2019 <Huawei Technologies Co., Ltd>\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/format.hpp>\n#include <boost/program_options.hpp>\n#include <chrono>\n#include <cstdint>\n#include <iostream>\n\n#include \"simulator-mpi/funcs.hpp\"\n\nnamespace po = boost::program_options;\n\nuint64_t calcSwaps(uint64_t aL, uint64_t aM, std::vector<uint64_t> anInvPerm,\n                   std::vector<uint64_t> aPairs)\n{\n     uint64_t res = 0;\n\n     for (uint64_t rank = 0; rank < (1ul << (aL - aM)); ++rank) {\n          auto start = std::chrono::high_resolution_clock::now();\n\n          for (uint64_t index = 0; index < (1ul << aM); ++index) {\n               uint64_t new_rank = rank;\n               uint64_t new_index = index;\n               for (size_t pi = 0; pi < aPairs.size(); pi += 2) {\n                    uint64_t remote_qubit = aPairs[pi];\n                    uint64_t local_qubit = aPairs[pi + 1];\n\n                    uint64_t remote_bit\n                        = (1ul << (anInvPerm[remote_qubit] - aM));\n                    uint64_t local_bit = (1ul << anInvPerm[local_qubit]);\n                    bool rb = rank & remote_bit;\n                    bool ib = index & local_bit;\n                    new_index ^= (-rb ^ new_index) & local_bit;\n                    new_rank ^= (-ib ^ new_rank) & remote_bit;\n               }\n\n               if (new_rank != rank) {\n                    res += new_index;\n                    //\t\t\t\tstd::cout << format(\"(%d: %d)->(%d: %d)\") %\n                    // rank % index % new_rank % new_index << std::endl;\n               }\n          }\n\n          auto end = std::chrono::high_resolution_clock::now();\n          std::chrono::duration<double, std::milli> elapsed_us = end - start;\n          std::cout << boost::format(\"rank: %d, \") % rank\n                    << boost::format(\"elapsed time: %.3f ms\")\n                           % elapsed_us.count()\n                    << std::endl;\n     }\n\n     return res;\n}\n\ntemplate <size_t NumPairs>\nuint64_t calcSwaps1(uint64_t aL, uint64_t aM, std::vector<uint64_t> aSwapBits)\n{\n     uint64_t res = 0;\n\n     for (uint64_t rank = 0; rank < (1ul << (aL - aM)); ++rank) {\n          auto start = std::chrono::high_resolution_clock::now();\n\n          for (uint64_t index = 0; index < (1ul << aM); ++index) {\n               uint64_t new_rank = rank;\n               uint64_t new_index = index;\n\n               uint64_t dst_idx = 0;\n\n               for (size_t pi = 0; pi < 2 * NumPairs; pi += 2) {\n                    uint64_t remote_bit = aSwapBits[pi];\n                    uint64_t local_bit = aSwapBits[pi + 1];\n\n                    bool rb = rank & remote_bit;\n                    bool ib = index & local_bit;\n                    new_index ^= (-rb ^ new_index) & local_bit;\n                    new_rank ^= (-ib ^ new_rank) & remote_bit;\n\n                    dst_idx ^= (-ib ^ dst_idx) & (1ul << (pi / 2));\n               }\n\n               res += new_index;\n\n               if (new_rank != rank) {\n                    std::cout\n                        << boost::format(\"(%d: %d)->(%d: %d),  dst_idx: %d\")\n                               % rank % index % new_rank % new_index % dst_idx\n                        << std::endl;\n               }\n          }\n\n          auto end = std::chrono::high_resolution_clock::now();\n          std::chrono::duration<double, std::milli> elapsed_us = end - start;\n          std::cout << boost::format(\"rank: %d, \") % rank\n                    << boost::format(\"elapsed time: %.3f ms\")\n                           % elapsed_us.count()\n                    << std::endl;\n     }\n\n     return res;\n}\n\ntemplate <>\nuint64_t calcSwaps1<0>(uint64_t, uint64_t, std::vector<uint64_t>)\n{\n     return 0;\n}\n\ntemplate <size_t NumPairs, class T = uint64_t>\nstruct CalcSwaps\n{\n     static T doCalc(uint64_t L, uint64_t M, const std::vector<T>& swap_bits)\n     {\n          if (NumPairs * 2 == swap_bits.size()) {\n               return calcSwaps1<NumPairs>(L, M, swap_bits);\n          }\n          else {\n               return CalcSwaps<NumPairs - 1, T>::doCalc(L, M, swap_bits);\n          }\n     }\n};\n\ntemplate <class T>\nstruct CalcSwaps<0, T>\n{\n     static T doCalc(uint64_t L, uint64_t M, const std::vector<T>& swap_bits)\n     {\n          return calcSwaps1<0>(L, M, swap_bits);\n     }\n};\n\nint main(int argc, const char** argv)\n{\n     uint64_t L = 0;\n     uint64_t M = 0;\n     std::vector<uint64_t> swap_pairs;\n     std::vector<uint64_t> perm_pairs;\n\n     po::options_description desc(\"Options\");\n     desc.add_options()(\"help\", \"produce help message\")(\n         \"L\", po::value<uint64_t>(&L), \"total number of qubits\")(\n         \"M\", po::value<uint64_t>(&M), \"number of local qubits\")(\n         \"swap\", po::value<std::vector<uint64_t>>(&swap_pairs)->multitoken(),\n         \"pair to swap\")(\n         \"perm\", po::value<std::vector<uint64_t>>(&perm_pairs)->multitoken(),\n         \"initial permutation by pairs\");\n\n     po::variables_map vm;\n     po::store(po::parse_command_line(argc, argv, desc), vm);\n     po::notify(vm);\n\n     if (vm.count(\"help\")) {\n          std::cout << desc << \"\\n\";\n          return 0;\n     }\n\n     std::cout << boost::format(\"L: %d, M: %d\") % L % M << std::endl;\n\n     printPairs(std::cout, \"Current permutation:\", perm_pairs);\n     printPairs(std::cout, \"Do swaps:\", swap_pairs);\n\n     auto perm = permuteQubits(naturalOrdering(L), perm_pairs);\n\n     //\tauto res = calcSwaps(L, M, inversePermutation(perm), swap_pairs);\n\n     std::vector<uint64_t> swapBits\n         = q2bits<uint64_t>(M, swap_pairs, inversePermutation(perm));\n     auto res = CalcSwaps<5>::doCalc(L, M, swapBits);\n\n     return res;\n}\n", "meta": {"hexsha": "01bb24be6d0b907f13621d2b60b4ed81e2dc32d5", "size": 6152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qswap.cpp", "max_stars_repo_name": "thexdesk/HiQsimulator", "max_stars_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T01:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T14:51:01.000Z", "max_issues_repo_path": "qswap.cpp", "max_issues_repo_name": "thexdesk/HiQsimulator", "max_issues_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T01:45:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-20T02:37:32.000Z", "max_forks_repo_path": "qswap.cpp", "max_forks_repo_name": "thexdesk/HiQsimulator", "max_forks_repo_head_hexsha": "0050444a7694de8c287d717d55870d12ff14c5e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2019-07-10T20:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T14:51:20.000Z", "avg_line_length": 33.6174863388, "max_line_length": 78, "alphanum_fraction": 0.533159948, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.027169229566413364, "lm_q1q2_score": 0.012420052402722705}}
{"text": "// NOLINTNEXTLINE(build/include): Its header file is included in symbolic.h.\n#include <algorithm>\n#include <cmath>\n#include <cstddef>\n#include <ios>\n#include <map>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <vector>\n\n#include <Eigen/Core>\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n\n#include \"drake/common/drake_assert.h\"\n#include \"drake/common/never_destroyed.h\"\n#include \"drake/common/symbolic.h\"\n#define DRAKE_COMMON_SYMBOLIC_DETAIL_HEADER\n#include \"drake/common/symbolic_expression_cell.h\"\n#undef DRAKE_COMMON_SYMBOLIC_DETAIL_HEADER\n\nnamespace drake {\nnamespace symbolic {\n\nusing std::logic_error;\nusing std::make_shared;\nusing std::map;\nusing std::numeric_limits;\nusing std::ostream;\nusing std::ostringstream;\nusing std::pair;\nusing std::runtime_error;\nusing std::shared_ptr;\nusing std::streamsize;\nusing std::string;\nusing std::vector;\n\nbool operator<(ExpressionKind k1, ExpressionKind k2) {\n  return static_cast<int>(k1) < static_cast<int>(k2);\n}\n\nnamespace {\n// Negates an addition expression.\n// - (E_1 + ... + E_n) => (-E_1 + ... + -E_n)\nExpression NegateAddition(const Expression& e) {\n  DRAKE_ASSERT(is_addition(e));\n  return ExpressionAddFactory{to_addition(e)}.Negate().GetExpression();\n}\n\n// Negates a multiplication expression.\n// - (c0 * E_1 * ... * E_n) => (-c0 * E_1 * ... * E_n)\nExpression NegateMultiplication(const Expression& e) {\n  DRAKE_ASSERT(is_multiplication(e));\n  return ExpressionMulFactory{to_multiplication(e)}.Negate().GetExpression();\n}\n}  // namespace\n\nshared_ptr<ExpressionCell> Expression::make_cell(const double d) {\n  if (d == 0.0) {\n    // The objects created by `Expression(0.0)` share the unique\n    // `ExpressionConstant` object created in `Expression::Zero()`.\n    //\n    // See https://github.com/RobotLocomotion/drake/issues/12453 for details.\n    return Expression::Zero().ptr_;\n  }\n  if (std::isnan(d)) {\n    return make_shared<ExpressionNaN>();\n  }\n  return make_shared<ExpressionConstant>(d);\n}\n\nExpression::Expression(const Variable& var)\n    : ptr_{make_shared<ExpressionVar>(var)} {}\nExpression::Expression(const double d) : ptr_{make_cell(d)} {}\nExpression::Expression(std::shared_ptr<ExpressionCell> ptr)\n    : ptr_{std::move(ptr)} {}\n\nExpressionKind Expression::get_kind() const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  return ptr_->get_kind();\n}\n\nvoid Expression::HashAppend(DelegatingHasher* hasher) const {\n  using drake::hash_append;\n  hash_append(*hasher, get_kind());\n  ptr_->HashAppendDetail(hasher);\n}\n\nExpression Expression::Zero() {\n  static const never_destroyed<Expression> zero{\n      Expression{make_shared<ExpressionConstant>(0.0)}};\n  return zero.access();\n}\n\nExpression Expression::One() {\n  static const never_destroyed<Expression> one{\n      Expression{make_shared<ExpressionConstant>(1.0)}};\n  return one.access();\n}\n\nExpression Expression::Pi() {\n  static const never_destroyed<Expression> pi{\n      Expression{make_shared<ExpressionConstant>(M_PI)}};\n  return pi.access();\n}\n\nExpression Expression::E() {\n  static const never_destroyed<Expression> e{\n      Expression{make_shared<ExpressionConstant>(M_E)}};\n  return e.access();\n}\n\nExpression Expression::NaN() {\n  static const never_destroyed<Expression> nan{\n      Expression{make_shared<ExpressionNaN>()}};\n  return nan.access();\n}\n\nVariables Expression::GetVariables() const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  return ptr_->GetVariables();\n}\n\nbool Expression::EqualTo(const Expression& e) const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  DRAKE_ASSERT(e.ptr_ != nullptr);\n  if (ptr_ == e.ptr_) {\n    return true;\n  }\n  if (get_kind() != e.get_kind()) {\n    return false;\n  }\n  // Check structural equality.\n  return ptr_->EqualTo(*(e.ptr_));\n}\n\nbool Expression::Less(const Expression& e) const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  DRAKE_ASSERT(e.ptr_ != nullptr);\n  if (ptr_ == e.ptr_) {\n    return false;  // this equals to e, not less-than.\n  }\n  const ExpressionKind k1{get_kind()};\n  const ExpressionKind k2{e.get_kind()};\n  if (k1 < k2) {\n    return true;\n  }\n  if (k2 < k1) {\n    return false;\n  }\n  // k1 == k2\n  return ptr_->Less(*(e.ptr_));\n}\n\nbool Expression::is_polynomial() const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  return ptr_->is_polynomial();\n}\n\nbool Expression::is_expanded() const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  return ptr_->is_expanded();\n}\n\nExpression& Expression::set_expanded() {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  ptr_->set_expanded();\n  return *this;\n}\n\ndouble Expression::Evaluate(const Environment& env,\n                            RandomGenerator* const random_generator) const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  if (random_generator == nullptr) {\n    return ptr_->Evaluate(env);\n  } else {\n    return ptr_->Evaluate(\n        PopulateRandomVariables(env, GetVariables(), random_generator));\n  }\n}\n\ndouble Expression::Evaluate(RandomGenerator* const random_generator) const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  return Evaluate(Environment{}, random_generator);\n}\n\nEigen::SparseMatrix<double> Evaluate(\n    const Eigen::Ref<const Eigen::SparseMatrix<Expression>>& m,\n    const Environment& env) {\n  return m.unaryExpr([&env](const Expression& e) { return e.Evaluate(env); });\n}\n\nExpression Expression::EvaluatePartial(const Environment& env) const {\n  if (env.empty()) {\n    return *this;\n  }\n  Substitution subst;\n  for (const pair<const Variable, double>& p : env) {\n    subst.emplace(p.first, p.second);\n  }\n  return Substitute(subst);\n}\n\nExpression Expression::Expand() const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  if (ptr_->is_expanded()) {\n    // If it is already expanded, return the current expression without calling\n    // Expand() on the cell.\n    return *this;\n  } else {\n    return ptr_->Expand();\n  }\n}\n\nExpression Expression::Substitute(const Variable& var,\n                                  const Expression& e) const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  return ptr_->Substitute({{var, e}});\n}\n\nExpression Expression::Substitute(const Substitution& s) const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  if (!s.empty()) {\n    return ptr_->Substitute(s);\n  }\n  return *this;\n}\n\nExpression Expression::Differentiate(const Variable& x) const {\n  DRAKE_ASSERT(ptr_ != nullptr);\n  return ptr_->Differentiate(x);\n}\n\nRowVectorX<Expression> Expression::Jacobian(\n    const Eigen::Ref<const VectorX<Variable>>& vars) const {\n  RowVectorX<Expression> J(vars.size());\n  for (VectorX<Variable>::Index i = 0; i < vars.size(); ++i) {\n    J(i) = Differentiate(vars(i));\n  }\n  return J;\n}\n\nstring Expression::to_string() const {\n  ostringstream oss;\n  oss << *this;\n  return oss.str();\n}\n\nExpression operator+(Expression lhs, const Expression& rhs) {\n  lhs += rhs;\n  return lhs;\n}\n\n// NOLINTNEXTLINE(runtime/references) per C++ standard signature.\nExpression& operator+=(Expression& lhs, const Expression& rhs) {\n  // Simplification: 0 + x => x\n  if (is_zero(lhs)) {\n    lhs = rhs;\n    return lhs;\n  }\n  // Simplification: x + 0 => x\n  if (is_zero(rhs)) {\n    return lhs;\n  }\n  // Simplification: Expression(c1) + Expression(c2) => Expression(c1 + c2)\n  if (is_constant(lhs) && is_constant(rhs)) {\n    lhs = get_constant_value(lhs) + get_constant_value(rhs);\n    return lhs;\n  }\n  // Simplification: flattening. To build a new expression, we use\n  // ExpressionAddFactory which holds intermediate terms and does\n  // simplifications internally.\n  ExpressionAddFactory add_factory{};\n  if (is_addition(lhs)) {\n    // 1. (e_1 + ... + e_n) + rhs\n    add_factory = to_addition(lhs);\n    // Note: AddExpression method takes care of the special case where `rhs` is\n    // of ExpressionAdd.\n    add_factory.AddExpression(rhs);\n  } else {\n    if (is_addition(rhs)) {\n      // 2. lhs + (e_1 + ... + e_n)\n      add_factory = to_addition(rhs);\n      add_factory.AddExpression(lhs);\n    } else {\n      // nothing to flatten: return lhs + rhs\n      add_factory.AddExpression(lhs);\n      add_factory.AddExpression(rhs);\n    }\n  }\n  // Extract an expression from factory\n  lhs = add_factory.GetExpression();\n  return lhs;\n}\n\nExpression& Expression::operator++() {\n  *this += Expression::One();\n  return *this;\n}\n\nExpression Expression::operator++(int) {\n  Expression copy(*this);\n  ++*this;\n  return copy;\n}\n\nExpression operator+(const Expression& e) { return e; }\n\nExpression operator-(Expression lhs, const Expression& rhs) {\n  lhs -= rhs;\n  return lhs;\n}\n\n// NOLINTNEXTLINE(runtime/references) per C++ standard signature.\nExpression& operator-=(Expression& lhs, const Expression& rhs) {\n  // Simplification: E - E => 0\n  // TODO(soonho-tri): This simplification is not sound since it cancels `E`\n  // which might cause 0/0 during evaluation.\n  if (lhs.EqualTo(rhs)) {\n    lhs = Expression::Zero();\n    return lhs;\n  }\n  // Simplification: x - 0 => x\n  if (is_zero(rhs)) {\n    return lhs;\n  }\n  // Simplification: Expression(c1) - Expression(c2) => Expression(c1 - c2)\n  if (is_constant(lhs) && is_constant(rhs)) {\n    lhs = get_constant_value(lhs) - get_constant_value(rhs);\n    return lhs;\n  }\n  // x - y => x + (-y)\n  lhs += -rhs;\n  return lhs;\n}\n\nExpression operator-(const Expression& e) {\n  // Simplification: constant folding\n  if (is_constant(e)) {\n    return Expression{-get_constant_value(e)};\n  }\n  // Simplification: push '-' inside over '+'.\n  // -(E_1 + ... + E_n) => (-E_1 + ... + -E_n)\n  if (is_addition(e)) {\n    return NegateAddition(e);\n  }\n  // Simplification: push '-' inside over '*'.\n  // -(c0 * E_1 * ... * E_n) => (-c0 * E_1 * ... * E_n)\n  if (is_multiplication(e)) {\n    return NegateMultiplication(e);\n  }\n  return -1 * e;\n}\n\nExpression& Expression::operator--() {\n  *this -= Expression::One();\n  return *this;\n}\n\nExpression Expression::operator--(int) {\n  // Declare as non-const to allow move.\n  Expression copy(*this);\n  --*this;\n  return copy;\n}\n\nExpression operator*(Expression lhs, const Expression& rhs) {\n  lhs *= rhs;\n  return lhs;\n}\n\n// NOLINTNEXTLINE(runtime/references) per C++ standard signature.\nExpression& operator*=(Expression& lhs, const Expression& rhs) {\n  // Simplification: 1 * x => x\n  if (is_one(lhs)) {\n    lhs = rhs;\n    return lhs;\n  }\n  // Simplification: x * 1 => x\n  if (is_one(rhs)) {\n    return lhs;\n  }\n  // Simplification: (E1 / E2) * (E3 / E4) => (E1 * E3) / (E2 * E4)\n  if (is_division(lhs) && is_division(rhs)) {\n    lhs = (get_first_argument(lhs) * get_first_argument(rhs)) /\n          (get_second_argument(lhs) * get_second_argument(rhs));\n    return lhs;\n  }\n  // Simplification: lhs * (c / E) => (c * lhs) / E\n  if (is_division(rhs) && is_constant(get_first_argument(rhs))) {\n    lhs = (get_first_argument(rhs) * lhs) / get_second_argument(rhs);\n    return lhs;\n  }\n  // Simplification: (c / E) * rhs => (c * rhs) / E\n  if (is_division(lhs) && is_constant(get_first_argument(lhs))) {\n    lhs = (get_first_argument(lhs) * rhs) / get_second_argument(lhs);\n    return lhs;\n  }\n  if (is_neg_one(lhs)) {\n    if (is_addition(rhs)) {\n      // Simplification: push '-' inside over '+'.\n      // -1 * (E_1 + ... + E_n) => (-E_1 + ... + -E_n)\n      lhs = NegateAddition(rhs);\n      return lhs;\n    }\n    if (is_multiplication(rhs)) {\n      // Simplification: push '-' inside over '*'.\n      // -1 * (c0 * E_1 * ... * E_n) => (-c0 * E_1 * ... * E_n)\n      lhs = NegateMultiplication(rhs);\n      return lhs;\n    }\n  }\n\n  if (is_neg_one(rhs)) {\n    if (is_addition(lhs)) {\n      // Simplification: push '-' inside over '+'.\n      // (E_1 + ... + E_n) * -1 => (-E_1 + ... + -E_n)\n      lhs = NegateAddition(lhs);\n      return lhs;\n    }\n    if (is_multiplication(lhs)) {\n      // Simplification: push '-' inside over '*'.\n      // (c0 * E_1 * ... * E_n) * -1 => (-c0 * E_1 * ... * E_n)\n      lhs = NegateMultiplication(lhs);\n      return lhs;\n    }\n  }\n\n  // Simplification: 0 * E => 0\n  // TODO(soonho-tri): This simplification is not sound since it cancels `E`\n  // which might cause 0/0 during evaluation.\n  if (is_zero(lhs)) {\n    return lhs;\n  }\n  // Simplification: E * 0 => 0\n  // TODO(soonho-tri): This simplification is not sound since it cancels `E`\n  // which might cause 0/0 during evaluation.\n  if (is_zero(rhs)) {\n    lhs = Expression::Zero();\n    return lhs;\n  }\n  // Pow-related simplifications.\n  if (is_pow(lhs)) {\n    const Expression& e1{get_first_argument(lhs)};\n    if (is_pow(rhs)) {\n      const Expression& e3{get_first_argument(rhs)};\n      if (e1.EqualTo(e3)) {\n        // Simplification: pow(e1, e2) * pow(e1, e4) => pow(e1, e2 + e4)\n        // TODO(soonho-tri): This simplification is not sound. For example, x^4\n        // * x^(-3) => x. The original expression `x^4 * x^(-3)` is evaluated to\n        // `nan` when x = 0 while the simplified expression `x` is evaluated to\n        // 0.\n        const Expression& e2{get_second_argument(lhs)};\n        const Expression& e4{get_second_argument(rhs)};\n        lhs = pow(e1, e2 + e4);\n        return lhs;\n      }\n    }\n    if (e1.EqualTo(rhs)) {\n      // Simplification: pow(e1, e2) * e1 => pow(e1, e2 + 1)\n      // TODO(soonho-tri): This simplification is not sound.\n      const Expression& e2{get_second_argument(lhs)};\n      lhs = pow(e1, e2 + 1);\n      return lhs;\n    }\n  } else {\n    if (is_pow(rhs)) {\n      const Expression& e1{get_first_argument(rhs)};\n      if (e1.EqualTo(lhs)) {\n        // Simplification: (lhs * rhs == e1 * pow(e1, e2)) => pow(e1, 1 + e2)\n        // TODO(soonho-tri): This simplification is not sound.\n        const Expression& e2{get_second_argument(rhs)};\n        lhs = pow(e1, 1 + e2);\n        return lhs;\n      }\n    }\n  }\n  if (is_constant(lhs) && is_constant(rhs)) {\n    // Simplification: Expression(c1) * Expression(c2) => Expression(c1 * c2)\n    lhs = Expression{get_constant_value(lhs) * get_constant_value(rhs)};\n    return lhs;\n  }\n  // Simplification: flattening\n  ExpressionMulFactory mul_factory{};\n  if (is_multiplication(lhs)) {\n    // (e_1 * ... * e_n) * rhs\n    mul_factory = to_multiplication(lhs);\n    // Note: AddExpression method takes care of the special case where `rhs` is\n    // of ExpressionMul.\n    mul_factory.AddExpression(rhs);\n  } else {\n    if (is_multiplication(rhs)) {\n      // e_1 * (e_2 * ... * e_n) -> (e_2 * ... * e_n * e_1)\n      //\n      // Note that we do not preserve the original ordering because * is\n      // associative.\n      mul_factory = to_multiplication(rhs);\n      mul_factory.AddExpression(lhs);\n    } else {\n      // Simplification: x * x => x^2 (=pow(x,2))\n      if (lhs.EqualTo(rhs)) {\n        lhs = pow(lhs, 2.0);\n        return lhs;\n      }\n      // nothing to flatten\n      mul_factory.AddExpression(lhs);\n      mul_factory.AddExpression(rhs);\n    }\n  }\n  lhs = mul_factory.GetExpression();\n  return lhs;\n}\n\nExpression operator/(Expression lhs, const Expression& rhs) {\n  lhs /= rhs;\n  return lhs;\n}\n\n// NOLINTNEXTLINE(runtime/references) per C++ standard signature.\nExpression& operator/=(Expression& lhs, const Expression& rhs) {\n  // Simplification: x / 1 => x\n  if (is_one(rhs)) {\n    return lhs;\n  }\n  // Simplification: Expression(c1) / Expression(c2) => Expression(c1 / c2)\n  if (is_constant(lhs) && is_constant(rhs)) {\n    const double v1{get_constant_value(lhs)};\n    const double v2{get_constant_value(rhs)};\n    if (v2 == 0.0) {\n      ostringstream oss{};\n      oss << \"Division by zero: \" << v1 << \"/\" << v2;\n      throw runtime_error(oss.str());\n    }\n    lhs = Expression{v1 / v2};\n    return lhs;\n  }\n  // Simplification: E / E => 1\n  // TODO(soonho-tri): This simplification is not sound since it cancels `E`\n  // which might contain 0/0 problems.\n  if (lhs.EqualTo(rhs)) {\n    lhs = Expression::One();\n    return lhs;\n  }\n  lhs.ptr_ = make_shared<ExpressionDiv>(lhs, rhs);\n  return lhs;\n}\n\nnamespace {\n// Changes the precision of `os` to be the `new_precision` and saves the\n// original precision so that it can be reverted when an instance of this class\n// is destructed. It is used in `operator<<` of symbolic expression.\nclass PrecisionGuard {\n public:\n  PrecisionGuard(ostream* const os, const streamsize& new_precision)\n      : os_{os}, original_precision_{os->precision()} {\n    os_->precision(new_precision);\n  }\n  DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PrecisionGuard)\n  ~PrecisionGuard() { os_->precision(original_precision_); }\n\n private:\n  ostream* const os_;\n  const streamsize original_precision_;\n};\n}  // namespace\n\nostream& operator<<(ostream& os, const Expression& e) {\n  DRAKE_ASSERT(e.ptr_ != nullptr);\n  const PrecisionGuard precision_guard{&os,\n                                       numeric_limits<double>::max_digits10};\n  return e.ptr_->Display(os);\n}\n\nExpression log(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    const double v{get_constant_value(e)};\n    ExpressionLog::check_domain(v);\n    return Expression{std::log(v)};\n  }\n  return Expression{make_shared<ExpressionLog>(e)};\n}\n\nExpression abs(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::fabs(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionAbs>(e)};\n}\n\nExpression exp(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::exp(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionExp>(e)};\n}\n\nExpression sqrt(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    const double v{get_constant_value(e)};\n    ExpressionSqrt::check_domain(v);\n    return Expression{std::sqrt(v)};\n  }\n  // Simplification: sqrt(pow(x, 2)) => abs(x)\n  if (is_pow(e)) {\n    if (is_two(get_second_argument(e))) {\n      return abs(get_first_argument(e));\n    }\n  }\n  return Expression{make_shared<ExpressionSqrt>(e)};\n}\n\nExpression pow(const Expression& e1, const Expression& e2) {\n  // Simplification\n  if (is_constant(e2)) {\n    const double v2{get_constant_value(e2)};\n    if (is_constant(e1)) {\n      // Constant folding\n      const double v1{get_constant_value(e1)};\n      ExpressionPow::check_domain(v1, v2);\n      return Expression{std::pow(v1, v2)};\n    }\n    // pow(E, 0) => 1\n    // TODO(soonho-tri): This simplification is not sound since it cancels `E`\n    // which might contain 0/0 problems.\n    if (v2 == 0.0) {\n      return Expression::One();\n    }\n    // pow(E, 1) => E\n    if (v2 == 1.0) {\n      return e1;\n    }\n  }\n  if (is_pow(e1)) {\n    // pow(base, exponent) ^ e2 => pow(base, exponent * e2)\n    const Expression& base{get_first_argument(e1)};\n    const Expression& exponent{get_second_argument(e1)};\n    return Expression{make_shared<ExpressionPow>(base, exponent * e2)};\n  }\n  return Expression{make_shared<ExpressionPow>(e1, e2)};\n}\n\nExpression sin(const Expression& e) {\n  // simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::sin(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionSin>(e)};\n}\n\nExpression cos(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::cos(get_constant_value(e))};\n  }\n\n  return Expression{make_shared<ExpressionCos>(e)};\n}\n\nExpression tan(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::tan(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionTan>(e)};\n}\n\nExpression asin(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    const double v{get_constant_value(e)};\n    ExpressionAsin::check_domain(v);\n    return Expression{std::asin(v)};\n  }\n  return Expression{make_shared<ExpressionAsin>(e)};\n}\n\nExpression acos(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    const double v{get_constant_value(e)};\n    ExpressionAcos::check_domain(v);\n    return Expression{std::acos(v)};\n  }\n  return Expression{make_shared<ExpressionAcos>(e)};\n}\n\nExpression atan(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::atan(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionAtan>(e)};\n}\n\nExpression atan2(const Expression& e1, const Expression& e2) {\n  // Simplification: constant folding.\n  if (is_constant(e1) && is_constant(e2)) {\n    return Expression{\n        std::atan2(get_constant_value(e1), get_constant_value(e2))};\n  }\n  return Expression{make_shared<ExpressionAtan2>(e1, e2)};\n}\n\nExpression sinh(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::sinh(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionSinh>(e)};\n}\n\nExpression cosh(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::cosh(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionCosh>(e)};\n}\n\nExpression tanh(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::tanh(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionTanh>(e)};\n}\n\nExpression min(const Expression& e1, const Expression& e2) {\n  // simplification: min(x, x) => x\n  if (e1.EqualTo(e2)) {\n    return e1;\n  }\n  // Simplification: constant folding.\n  if (is_constant(e1) && is_constant(e2)) {\n    return Expression{std::min(get_constant_value(e1), get_constant_value(e2))};\n  }\n  return Expression{make_shared<ExpressionMin>(e1, e2)};\n}\n\nExpression max(const Expression& e1, const Expression& e2) {\n  // Simplification: max(x, x) => x\n  if (e1.EqualTo(e2)) {\n    return e1;\n  }\n  // Simplification: constant folding\n  if (is_constant(e1) && is_constant(e2)) {\n    return Expression{std::max(get_constant_value(e1), get_constant_value(e2))};\n  }\n  return Expression{make_shared<ExpressionMax>(e1, e2)};\n}\n\nExpression ceil(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::ceil(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionCeiling>(e)};\n}\n\nExpression floor(const Expression& e) {\n  // Simplification: constant folding.\n  if (is_constant(e)) {\n    return Expression{std::floor(get_constant_value(e))};\n  }\n  return Expression{make_shared<ExpressionFloor>(e)};\n}\n\nExpression if_then_else(const Formula& f_cond, const Expression& e_then,\n                        const Expression& e_else) {\n  // simplification:: if(true, e1, e2) => e1\n  if (f_cond.EqualTo(Formula::True())) {\n    return e_then;\n  }\n  // simplification:: if(false, e1, e2) => e2\n  if (f_cond.EqualTo(Formula::False())) {\n    return e_else;\n  }\n  return Expression{make_shared<ExpressionIfThenElse>(f_cond, e_then, e_else)};\n}\n\nExpression uninterpreted_function(string name, vector<Expression> arguments) {\n  return Expression{make_shared<ExpressionUninterpretedFunction>(\n      std::move(name), std::move(arguments))};\n}\n\nbool is_constant(const Expression& e) { return is_constant(*e.ptr_); }\nbool is_constant(const Expression& e, const double v) {\n  return is_constant(e) && (to_constant(e)->get_value() == v);\n}\nbool is_zero(const Expression& e) { return is_constant(e, 0.0); }\nbool is_one(const Expression& e) { return is_constant(e, 1.0); }\nbool is_neg_one(const Expression& e) { return is_constant(e, -1.0); }\nbool is_two(const Expression& e) { return is_constant(e, 2.0); }\nbool is_nan(const Expression& e) { return e.get_kind() == ExpressionKind::NaN; }\nbool is_variable(const Expression& e) { return is_variable(*e.ptr_); }\nbool is_addition(const Expression& e) { return is_addition(*e.ptr_); }\nbool is_multiplication(const Expression& e) {\n  return is_multiplication(*e.ptr_);\n}\nbool is_division(const Expression& e) { return is_division(*e.ptr_); }\nbool is_log(const Expression& e) { return is_log(*e.ptr_); }\nbool is_abs(const Expression& e) { return is_abs(*e.ptr_); }\nbool is_exp(const Expression& e) { return is_exp(*e.ptr_); }\nbool is_sqrt(const Expression& e) { return is_sqrt(*e.ptr_); }\nbool is_pow(const Expression& e) { return is_pow(*e.ptr_); }\nbool is_sin(const Expression& e) { return is_sin(*e.ptr_); }\nbool is_cos(const Expression& e) { return is_cos(*e.ptr_); }\nbool is_tan(const Expression& e) { return is_tan(*e.ptr_); }\nbool is_asin(const Expression& e) { return is_asin(*e.ptr_); }\nbool is_acos(const Expression& e) { return is_acos(*e.ptr_); }\nbool is_atan(const Expression& e) { return is_atan(*e.ptr_); }\nbool is_atan2(const Expression& e) { return is_atan2(*e.ptr_); }\nbool is_sinh(const Expression& e) { return is_sinh(*e.ptr_); }\nbool is_cosh(const Expression& e) { return is_cosh(*e.ptr_); }\nbool is_tanh(const Expression& e) { return is_tanh(*e.ptr_); }\nbool is_min(const Expression& e) { return is_min(*e.ptr_); }\nbool is_max(const Expression& e) { return is_max(*e.ptr_); }\nbool is_ceil(const Expression& e) { return is_ceil(*e.ptr_); }\nbool is_floor(const Expression& e) { return is_floor(*e.ptr_); }\nbool is_if_then_else(const Expression& e) { return is_if_then_else(*e.ptr_); }\nbool is_uninterpreted_function(const Expression& e) {\n  return is_uninterpreted_function(*e.ptr_);\n}\n\ndouble get_constant_value(const Expression& e) {\n  return to_constant(e)->get_value();\n}\nconst Variable& get_variable(const Expression& e) {\n  return to_variable(e)->get_variable();\n}\nconst Expression& get_argument(const Expression& e) {\n  return to_unary(e)->get_argument();\n}\nconst Expression& get_first_argument(const Expression& e) {\n  return to_binary(e)->get_first_argument();\n}\nconst Expression& get_second_argument(const Expression& e) {\n  return to_binary(e)->get_second_argument();\n}\ndouble get_constant_in_addition(const Expression& e) {\n  return to_addition(e)->get_constant();\n}\nconst map<Expression, double>& get_expr_to_coeff_map_in_addition(\n    const Expression& e) {\n  return to_addition(e)->get_expr_to_coeff_map();\n}\ndouble get_constant_in_multiplication(const Expression& e) {\n  return to_multiplication(e)->get_constant();\n}\nconst map<Expression, Expression>& get_base_to_exponent_map_in_multiplication(\n    const Expression& e) {\n  return to_multiplication(e)->get_base_to_exponent_map();\n}\n\nconst string& get_uninterpreted_function_name(const Expression& e) {\n  return to_uninterpreted_function(e)->get_name();\n}\n\nconst vector<Expression>& get_uninterpreted_function_arguments(\n    const Expression& e) {\n  return to_uninterpreted_function(e)->get_arguments();\n}\n\nconst Formula& get_conditional_formula(const Expression& e) {\n  return to_if_then_else(e)->get_conditional_formula();\n}\n\nconst Expression& get_then_expression(const Expression& e) {\n  return to_if_then_else(e)->get_then_expression();\n}\n\nconst Expression& get_else_expression(const Expression& e) {\n  return to_if_then_else(e)->get_else_expression();\n}\n\nExpression operator+(const Variable& var) { return Expression{var}; }\nExpression operator-(const Variable& var) { return -Expression{var}; }\n\nVectorX<Variable> GetVariableVector(\n    const Eigen::Ref<const VectorX<Expression>>& evec) {\n  VectorX<Variable> vec(evec.size());\n  for (int i = 0; i < evec.size(); i++) {\n    const Expression e_i{evec(i)};\n    if (is_variable(e_i)) {\n      vec(i) = get_variable(e_i);\n    } else {\n      throw logic_error(fmt::format(\"{} is not a variable.\", e_i));\n    }\n  }\n  return vec;\n}\n\nMatrixX<Expression> Jacobian(const Eigen::Ref<const VectorX<Expression>>& f,\n                             const vector<Variable>& vars) {\n  DRAKE_DEMAND(!vars.empty());\n  const Eigen::Ref<const VectorX<Expression>>::Index n{f.size()};\n  const size_t m{vars.size()};\n  MatrixX<Expression> J(n, m);\n  for (int i = 0; i < n; ++i) {\n    for (size_t j = 0; j < m; ++j) {\n      J(i, j) = f[i].Differentiate(vars[j]);\n    }\n  }\n  return J;\n}\n\nMatrixX<Expression> Jacobian(const Eigen::Ref<const VectorX<Expression>>& f,\n                             const Eigen::Ref<const VectorX<Variable>>& vars) {\n  return Jacobian(f, vector<Variable>(vars.data(), vars.data() + vars.size()));\n}\n\nnamespace {\n\n// Helper class for IsAffine functions below where an instance of this class\n// is passed to Eigen::MatrixBase::visit() function.\nclass IsAffineVisitor {\n public:\n  IsAffineVisitor() = default;\n  explicit IsAffineVisitor(const Variables& variables)\n      : variables_{&variables} {}\n\n  // Called for the first coefficient. Needed for Eigen::MatrixBase::visit()\n  // function.\n  void init(const Expression& e, const Eigen::Index i, const Eigen::Index j) {\n    (*this)(e, i, j);\n  }\n\n  // Called for all other coefficients. Needed for Eigen::MatrixBase::visit()\n  // function.\n  void operator()(const Expression& e, const Eigen::Index, const Eigen::Index) {\n    // Note that `IsNotAffine` is only called when we have not found a\n    // non-affine element yet.\n    found_non_affine_element_ = found_non_affine_element_ || IsNotAffine(e);\n  }\n\n  [[nodiscard]] bool result() const { return !found_non_affine_element_; }\n\n private:\n  // Returns true if `e` is *not* affine in variables_ (if exists) or all\n  // variables in `e`.\n  [[nodiscard]] bool IsNotAffine(const Expression& e) const {\n    if (!e.is_polynomial()) {\n      return true;\n    }\n    const Polynomial p{(variables_ != nullptr) ? Polynomial{e, *variables_}\n                                               : Polynomial{e}};\n    return p.TotalDegree() > 1;\n  }\n\n  bool found_non_affine_element_{false};\n  const Variables* const variables_{nullptr};\n};\n\n}  // namespace\n\nbool IsAffine(const Eigen::Ref<const MatrixX<Expression>>& m,\n              const Variables& vars) {\n  if (m.size() == 0) {\n    return true;\n  }\n  IsAffineVisitor visitor{vars};\n  m.visit(visitor);\n  return visitor.result();\n}\n\nbool IsAffine(const Eigen::Ref<const MatrixX<Expression>>& m) {\n  if (m.size() == 0) {\n    return true;\n  }\n  IsAffineVisitor visitor;\n  m.visit(visitor);\n  return visitor.result();\n}\n\nnamespace {\n// Helper functions for TaylorExpand.\n//\n// We use the multi-index notation. Please read\n// https://en.wikipedia.org/wiki/Multi-index_notation for more information.\n\n// α = (a₁, ..., aₙ) where αᵢ ∈ Z.\nusing MultiIndex = vector<int>;\n\n// Generates multi-indices of order `order` whose size is `num_vars` and append\n// to `vec`. It generates the indices by increasing the elements of the given\n// `base`. It only changes the i-th dimension which is greater than or equal to\n// `start_dim` to avoid duplicates.\nvoid DoEnumerateMultiIndex(const int order, const int num_vars,\n                           const int start_dim, const MultiIndex& base,\n                           vector<MultiIndex>* const vec) {\n  DRAKE_ASSERT(order > 0);\n  DRAKE_ASSERT(start_dim >= 0);\n  DRAKE_ASSERT(base.size() == static_cast<size_t>(num_vars));\n  if (order == 0) {\n    return;\n  }\n  if (order == 1) {\n    for (int i = start_dim; i < num_vars; ++i) {\n      MultiIndex alpha = base;\n      ++alpha[i];\n      vec->push_back(std::move(alpha));\n    }\n    return;\n  } else {\n    for (int i = start_dim; i < num_vars; ++i) {\n      MultiIndex alpha = base;\n      ++alpha[i];\n      DoEnumerateMultiIndex(order - 1, num_vars, i, alpha, vec);\n    }\n  }\n}\n\n// Returns the set of multi-indices of order `order` whose size is `num-vars`.\nvector<MultiIndex> EnumerateMultiIndex(const int order, const int num_vars) {\n  DRAKE_ASSERT(order > 0);\n  DRAKE_ASSERT(num_vars >= 1);\n  vector<MultiIndex> vec;\n  MultiIndex base(num_vars, 0);  // base = (0, ..., 0)\n  DoEnumerateMultiIndex(order, num_vars, 0, base, &vec);\n  return vec;\n}\n\n// Computes the factorial of n.\nint Factorial(const int n) {\n  DRAKE_ASSERT(n >= 0);\n  int f = 1;\n  for (int i = 2; i <= n; ++i) {\n    f *= i;\n  }\n  return f;\n}\n\n// Given a multi index α = (α₁, ..., αₙ), returns α₁! * ... * αₙ!.\nint FactorialProduct(const MultiIndex& alpha) {\n  int ret = 1;\n  for (const int i : alpha) {\n    ret *= Factorial(i);\n  }\n  return ret;\n}\n\n// Computes ∂fᵅ(a) = ∂ᵅ¹...∂ᵅⁿf(a).\nExpression Derivative(Expression f, const MultiIndex& alpha,\n                      const Environment& a) {\n  int i = 0;\n  for (const pair<const Variable, double>& p : a) {\n    const Variable& v = p.first;\n    for (int j = 0; j < alpha[i]; ++j) {\n      f = f.Differentiate(v);\n    }\n    ++i;\n  }\n  return f.EvaluatePartial(a);\n}\n\n// Given terms = [e₁, ..., eₙ] and alpha = (α₁, ..., αₙ), returns\n// pow(e₁,α₁) * ... * pow(eₙ,αₙ)\nExpression Exp(const vector<Expression>& terms, const MultiIndex& alpha) {\n  DRAKE_ASSERT(terms.size() == alpha.size());\n  ExpressionMulFactory factory;\n  for (size_t i = 0; i < terms.size(); ++i) {\n    factory.AddExpression(pow(terms[i], alpha[i]));\n  }\n  return factory.GetExpression();\n}\n\n// Computes ∑_{|α| = order} ∂fᵅ(a) / α! * (x - a)ᵅ.\nvoid DoTaylorExpand(const Expression& f, const Environment& a,\n                    const vector<Expression>& terms, const int order,\n                    const int num_vars, ExpressionAddFactory* const factory) {\n  DRAKE_ASSERT(order > 0);\n  DRAKE_ASSERT(terms.size() == static_cast<size_t>(num_vars));\n  const vector<MultiIndex> multi_indices{EnumerateMultiIndex(order, num_vars)};\n  for (const MultiIndex& alpha : multi_indices) {\n    factory->AddExpression(Derivative(f, alpha, a) * Exp(terms, alpha) /\n                           FactorialProduct(alpha));\n  }\n}\n}  // namespace\n\nExpression TaylorExpand(const Expression& f, const Environment& a,\n                        const int order) {\n  // The implementation uses the formulation:\n  //      Taylor(f, a, order) = ∑_{|α| ≤ order} ∂fᵅ(a) / α! * (x - a)ᵅ.\n  DRAKE_DEMAND(order >= 1);\n  ExpressionAddFactory factory;\n  factory.AddExpression(f.EvaluatePartial(a));\n  const int num_vars = a.size();\n  if (num_vars == 0) {\n    return f;\n  }\n  vector<Expression> terms;  // (x - a)\n  for (const pair<const Variable, double>& p : a) {\n    const Variable& var = p.first;\n    const double v = p.second;\n    terms.push_back(var - v);\n  }\n  for (int i = 1; i <= order; ++i) {\n    DoTaylorExpand(f, a, terms, i, num_vars, &factory);\n  }\n  return factory.GetExpression();\n}\n\nnamespace {\n// Visitor used in the implementation of the GetDistinctVariables function\n// defined below.\nstruct GetDistinctVariablesVisitor {\n  // called for the first coefficient\n  void init(const Expression& value, Eigen::Index, Eigen::Index) {\n    variables += value.GetVariables();\n  }\n  // called for all other coefficients\n  void operator()(const Expression& value, Eigen::Index, Eigen::Index) {\n    variables += value.GetVariables();\n  }\n  Variables variables;\n};\n}  // namespace\n\nVariables GetDistinctVariables(const Eigen::Ref<const MatrixX<Expression>>& v) {\n  GetDistinctVariablesVisitor visitor;\n  v.visit(visitor);\n  return visitor.variables;\n}\n\n}  // namespace symbolic\n\ndouble ExtractDoubleOrThrow(const symbolic::Expression& e) {\n  if (is_nan(e)) {\n    // If this was a literal NaN provided by the user or a dummy_value<T>, then\n    // it is sound to promote it as the \"extracted value\" during scalar\n    // conversion.  (In contrast, if an expression tree includes a NaN term,\n    // then it's still desirable to throw an exception and we should NOT return\n    // NaN in that case.)\n    return std::numeric_limits<double>::quiet_NaN();\n  }\n  return e.Evaluate();\n}\n\n}  // namespace drake\n", "meta": {"hexsha": "a992c48e25f0ba0b8308db0c000ccbbfec728035", "size": 34960, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/symbolic_expression.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "common/symbolic_expression.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/symbolic_expression.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": 30.4795117698, "max_line_length": 80, "alphanum_fraction": 0.6640160183, "num_tokens": 9305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262526733264, "lm_q2_score": 0.03904829384451455, "lm_q1q2_score": 0.012394953588351174}}
{"text": "/* Copyright 2018 Nils Bore (nbore@kth.se), Yiping Xie (yipingx@kth.se)\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * 2. 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 * 3. Neither the name of the copyright holder nor the names of its contributors may be used 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 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <data_tools/jsf_data.h>\n\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n#include <boost/date_time.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#undef BOOST_NO_CXX11_SCOPED_ENUMS\n\n#include <fcntl.h>\n#ifdef _MSC_VER\n  #include <io.h>\n#else\n  #include <unistd.h>\n#endif\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <bitset>\n#include <data_tools/lat_long_utm.h>\n\n# define SONAR_MESSAGE_HEADER_START 0X1601\n# define SONAR_DATA_TYPE 0X0050\n# define DVL_DATA_TYPE 0X0820\n# define SITUATION_DATA_TYPE 0X082A\n\nusing namespace std;\n\nnamespace jsf_data{\n\n    jsf_sss_ping::PingsT filter_frequency(const jsf_sss_ping::PingsT& pings, int desired_freq)\n    {\n        jsf_sss_ping::PingsT filtered_pings;\n\n        std::copy_if(pings.begin(), pings.end(), std::back_inserter(filtered_pings), [&](const jsf_sss_ping& ping){ return ping.frequency == desired_freq; });\n\n        return filtered_pings;\n    }\n\ncv::Mat make_waterfall_image(const jsf_sss_ping::PingsT& pings)\n{\n    int rows = pings.size();\n    int cols = pings[0].port.pings.size() + pings[0].stbd.pings.size();\n    cv::Mat swath_img = cv::Mat(rows, cols, CV_8UC3, cv::Scalar(255, 255, 255));\n    for (int i = 0; i < pings.size(); ++i) {\n        for (int j = 0; j < pings[i].port.pings.size(); ++j) {\n            uchar intensity = uchar(std::min(std::max(255.*.005*pings[i].port.pings[j], 0.), 255.));\n            cv::Point3_<uchar>* p = swath_img.ptr<cv::Point3_<uchar> >(i, pings[0].stbd.pings.size()+j);\n            p->z = intensity;\n            p->y = intensity;\n            p->x = intensity;\n        }\n        for (int j = 0; j < pings[i].stbd.pings.size(); ++j) {\n            uchar intensity = uchar(std::min(std::max(255.*.005*pings[i].stbd.pings[j], 0.), 255.));\n            cv::Point3_<uchar>* p = swath_img.ptr<cv::Point3_<uchar> >(i, pings[0].stbd.pings.size()-j-1);\n            p->z = intensity;\n            p->y = intensity;\n            p->x = intensity;\n        }\n    }\n    cv::Mat resized_swath_img;//dst image\n    cv::resize(swath_img, resized_swath_img, cv::Size(512, rows));//resize image\n    \n    return resized_swath_img;\n}\n\nvoid show_waterfall_image(const jsf_sss_ping::PingsT& pings)\n{\n    cv::Mat waterfall_image = make_waterfall_image(pings);\n    cv::imshow(\"Waterfall image\", waterfall_image);\n    cv::waitKey();\n}\n\n// skip data \nvoid skip_data(ifstream& input, jsf_msg_header jsf_hdr)\n{\n    int nbr_bytes;\n    for (int i = 0; i < jsf_hdr.following_bytes; i++) {\n        input.read(reinterpret_cast<char*>(&nbr_bytes), sizeof(char));\n    }\n}\n\n\njsf_sss_ping_side process_side_scan_ping_side(ifstream& input,  jsf_msg_header& jsf_hdr,  jsf_sonar_data_msg_header& jsf_sonar_data_hdr)\n{\n    jsf_sss_ping_side ping_side;\n\n    ping_side.time_duration = double(jsf_sonar_data_hdr.spls_num_in_pkt - 1)*double(jsf_sonar_data_hdr.spl_intvl_in_ns)*1e-9;\n\n\n    //cout << \"Freq: \" << jsf_sonar_data_hdr.spl_freq_in_hz << endl;\n\n    if (jsf_sonar_data_hdr.data_format==0) {\n        int16_t env_data;\n        for (int i = 0; i < jsf_sonar_data_hdr.spls_num_in_pkt; ++i) {\n            input.read(reinterpret_cast<char*>(&env_data), sizeof(env_data));\n            ping_side.pings.push_back(ldexpf((float)env_data, -jsf_sonar_data_hdr.weighting_factor_n));\n\n        }\n    }\n    else if (jsf_sonar_data_hdr.data_format==1) {\n        cout << \"Data format: \" << jsf_sonar_data_hdr.data_format << \"has real and imginary part, stored in pings and pings_phase respectively\" << endl;\n        int16_t analytic_sig_data[2];\n\n        for (int i = 0; i < jsf_sonar_data_hdr.spls_num_in_pkt; ++i) {\n            input.read(reinterpret_cast<char*>(&analytic_sig_data), sizeof(analytic_sig_data));\n            ping_side.pings.push_back(ldexpf((float)analytic_sig_data[0], -jsf_sonar_data_hdr.weighting_factor_n));\n            ping_side.pings_phase.push_back(ldexpf((float)analytic_sig_data[1], -jsf_sonar_data_hdr.weighting_factor_n));\n        }\n    }\n    else{\n        cout << \"Skip data format: \" << jsf_sonar_data_hdr.data_format << endl;\n        for (int i = 0; i < jsf_hdr.following_bytes-sizeof(jsf_sonar_data_hdr); i++) {\n            int16_t nbr_bytes;\n            input.read(reinterpret_cast<char*>(&nbr_bytes), sizeof(char));\n        }\n    }\n    return ping_side;\n }\n\n\n\ntemplate <typename ReturnType, typename JsfHeaderType>\nReturnType read_datagram(std::ifstream& input,  JsfHeaderType& header,  jsf_msg_header& jsf_hdr)\n{\n    ReturnType rtn;\n\treturn rtn;\n}\n\ntemplate <typename ReturnType, typename JsfHeaderType, int Code>\nvector<ReturnType, Eigen::aligned_allocator<ReturnType> > parse_file_impl(const boost::filesystem::path& path)\n{\n    vector<ReturnType, Eigen::aligned_allocator<ReturnType> > returns;\n    if (boost::filesystem::extension(path) != \".JSF\" && boost::filesystem::extension(path) != \".jsf\") {\n        cout << \"Not an .JSF file, skipping...\" << endl;\n        cout << \"Extension: \" << boost::filesystem::extension(path) << endl;\n        return returns;\n    }\n\n    ifstream input;\n    input.open(path.string(), ios::binary);\n    if (input.fail()) {\n        cout << \"ERROR: Cannot open the file...\" << endl;\n        exit(0);\n        return returns;\n    }\n    while (!input.eof()) {\n        jsf_msg_header jsf_hdr;\n        input.read(reinterpret_cast<char*>(&jsf_hdr),sizeof(jsf_hdr));\n        if (jsf_hdr.start_marker != SONAR_MESSAGE_HEADER_START) {\n            cout << \"Invalid file format! start marker: \" << jsf_hdr.start_marker << endl;\n            break;\n        }\n\n        if (jsf_hdr.msg_type == Code) {\n            JsfHeaderType header;\n            input.read(reinterpret_cast<char*>(&header), sizeof(header));\n            returns.push_back(read_datagram<ReturnType, JsfHeaderType>(input, header, jsf_hdr));\n            returns.back().first_in_file_ = false;\n        }\n        else {\n            skip_data(input,jsf_hdr);\n        }\n    }\n\n    if (!returns.empty()) {\n        returns[0].first_in_file_ = true;\n    }\n\n\treturn returns;\n    \n}\n\ntemplate <>\njsf_sss_ping read_datagram<jsf_sss_ping, jsf_sonar_data_msg_header>(std::ifstream& input,  jsf_sonar_data_msg_header& jsf_sonar_data_hdr,  jsf_msg_header& jsf_hdr)\n{\n    jsf_sss_ping ping;\n    jsf_sss_ping_side ping_side;\n    ping.frequency = jsf_sonar_data_hdr.spl_freq_in_hz;\n    ping.sound_vel = jsf_sonar_data_hdr.sound_speed_in_m_per_s;\n    ping.rpy = Eigen::Vector3d(jsf_sonar_data_hdr.roll, jsf_sonar_data_hdr.pitch, jsf_sonar_data_hdr.compass_heading);\n    ping.rpy.head<2>() = M_PI/32768.*ping.rpy.head<2>();\n    ping.rpy[2] = .5*M_PI - M_PI/180.*0.01*ping.rpy[2];\n\n    // NOTE: this is only valid if coord_units == 2\n    ping.lat_ = 0.0001/60.*double(jsf_sonar_data_hdr.y_coord);\n    ping.long_ = 0.0001/60.*double(jsf_sonar_data_hdr.x_coord);\n    double easting, northing;\n    string utm_zone;\n    tie(northing, easting, utm_zone) = lat_long_utm::lat_long_to_UTM(ping.lat_, ping.long_);\n    //cout << \"UTM ZONE: \" << utm_zone << endl;\n    ping.utm_zone = utm_zone;\n    ping.pos_ = Eigen::Vector3d(easting, northing, -0.001*jsf_sonar_data_hdr.depth_in_mm);\n    ping_side = process_side_scan_ping_side(input, jsf_hdr, jsf_sonar_data_hdr);\n\n    //cout << \"Coord units: \" << jsf_sonar_data_hdr.coord_units << endl;\n\n    const boost::posix_time::ptime epoch = boost::posix_time::time_from_string(\"1970-01-01 00:00:00.000\");\n    boost::posix_time::ptime data_time;\n\n    if (jsf_hdr.prot_ver >= 8) {\n        data_time = epoch + boost::posix_time::seconds(jsf_sonar_data_hdr.ping_time_in_sec) + boost::posix_time::milliseconds(jsf_sonar_data_hdr.today_in_ms%1000);\n    }\n    else {\n        boost::posix_time::ptime data_time(boost::gregorian::date(jsf_sonar_data_hdr.cpu_year, 1, 1), boost::posix_time::hours(jsf_sonar_data_hdr.cpu_day*24-24)+boost::posix_time::minutes(0)+boost::posix_time::seconds(0)+boost::posix_time::milliseconds(jsf_sonar_data_hdr.today_in_ms)); \n    }\n    stringstream time_ss;\n    time_ss << data_time;\n    ping.time_string_ = time_ss.str();\n    boost::posix_time::time_duration const diff = data_time - epoch;\n    ping.time_stamp_ = diff.total_milliseconds();\n\n    if (jsf_hdr.channel_num == 0) {\n        ping.port = ping_side;\n    }\n    else {\n        ping.stbd = ping_side;\n    }\n  \n    ping.first_in_file_ = false;\n\n    return ping;\n\n}\n\ntemplate <>\njsf_dvl_ping read_datagram<jsf_dvl_ping, jsf_dvl_msg_header>(std::ifstream& input,  jsf_dvl_msg_header& jsf_dvl_msg,  jsf_msg_header& jsf_hdr)\n{\n    jsf_dvl_ping ping;\n    const boost::posix_time::ptime epoch = boost::posix_time::time_from_string(\"1970-01-01 00:00:00.000\");\n    boost::posix_time::ptime data_time;\n\n    data_time = epoch + boost::posix_time::seconds(jsf_dvl_msg.time_in_sec) + boost::posix_time::milliseconds(jsf_dvl_msg.ms_in_cur_sec);\n    \n    stringstream time_ss;\n    time_ss << data_time;\n    ping.time_string_ = time_ss.str();\n    boost::posix_time::time_duration const diff = data_time - epoch;\n    ping.time_stamp_ = diff.total_milliseconds();\n\n    ping.vel_wrt_bottom_ = Eigen::Vector3d(jsf_dvl_msg.x_vel_wrt_bottom/1000., jsf_dvl_msg.y_vel_wrt_bottom/1000., jsf_dvl_msg.z_vel_wrt_bottom/1000.);\n    ping.vel_wrt_water_ = Eigen::Vector3d(jsf_dvl_msg.x_vel_wrt_water/1000., jsf_dvl_msg.y_vel_wrt_water/1000., jsf_dvl_msg.z_vel_wrt_water/1000.);\n    ping.dist_to_bottom_ = Eigen::Vector4d(jsf_dvl_msg.dist_to_bottom_in_cm[0]/100., jsf_dvl_msg.dist_to_bottom_in_cm[1]/100,jsf_dvl_msg.dist_to_bottom_in_cm[2]/100.,jsf_dvl_msg.dist_to_bottom_in_cm[3]/100.);\n    ping.depth_ = jsf_dvl_msg.depth_in_dm/10.;\n    ping.pitch_ = jsf_dvl_msg.pitch/100./180.*M_PI;\n    ping.roll_ = jsf_dvl_msg.roll/100./180.*M_PI;\n    ping.heading_ = jsf_dvl_msg.heading/100./180.*M_PI;\n    ping.salinity_ = jsf_dvl_msg.salinity;\n    ping.temp_ = jsf_dvl_msg.temp/100.;\n    ping.sound_vel_ = jsf_dvl_msg.sound_vel;\n\n    // initialize the flag\n    ping.flag_[\"Vxy\"] = false; // bit 0\n    ping.flag_[\"Vz\"] = false; // bit 2\n    ping.flag_[\"Vxy_water\"] = false; // bit 3\n    ping.flag_[\"Vz_water\"] = false; // bit 4\n    ping.flag_[\"dist_bottom\"] = false; // bit 5\n    ping.flag_[\"heading\"] = false; // bit 6\n    ping.flag_[\"pitch\"] = false; // bit 7\n    ping.flag_[\"roll\"] = false; // bit 8\n    ping.flag_[\"temp\"] = false; // bit 9\n    ping.flag_[\"depth\"] = false; // bit 10\n    ping.flag_[\"salinity\"] = false; // bit 11\n    ping.flag_[\"sound_vel\"] = false; // bit 12\n\n    ping.ship_coord_ = false; // bit 1\n    ping.error_ = false; // bit 31\n\n    // bit 0\n    if (jsf_dvl_msg.flag & 0x01) ping.flag_[\"Vxy\"] = true;\n     \n    // bit 1\n    if (jsf_dvl_msg.flag & 0x02) ping.ship_coord_ = true;\n    \n\n    // bit 2\n    if (jsf_dvl_msg.flag & 0x04) ping.flag_[\"Vz\"] = true;\n\n    // bit 3\n    if (jsf_dvl_msg.flag & 0x08) ping.flag_[\"Vxy_water\"] = true;\n    \n    // bit 4\n    if (jsf_dvl_msg.flag & 0x10) ping.flag_[\"Vz_water\"] = true;\n\n    // bit 5\n    if (jsf_dvl_msg.flag & 0x20) ping.flag_[\"dist_bottom\"] = true;\n    \n    // bit 6\n    if (jsf_dvl_msg.flag & 0x40) ping.flag_[\"heading\"] = true;\n    \n    // bit 7\n    if (jsf_dvl_msg.flag & 0x80) ping.flag_[\"pitch\"] = true;\n    \n    // bit 8\n    if (jsf_dvl_msg.flag & 0x100) ping.flag_[\"roll\"] = true;\n    \n    // bit 9\n    if (jsf_dvl_msg.flag & 0x200) ping.flag_[\"temp\"] = true;\n\n    // bit 10\n    if (jsf_dvl_msg.flag & 0x400) ping.flag_[\"depth\"] = true;\n\n    // bit 11\n    if (jsf_dvl_msg.flag & 0x800) ping.flag_[\"salinity\"] = true;\n\n    // bit 12\n    if (jsf_dvl_msg.flag & 0x1000) ping.flag_[\"sound_vel\"] = true; \n\n    // bit 31\n    if(jsf_dvl_msg.flag & 0x100000000){\n        cout << \"Error detected! flag in decimal: \" << fixed << jsf_dvl_msg.flag << endl;\n        ping.error_ = true;\n    }\n\n    return ping;\n\n}\n\nstd_data::sss_ping::PingsT convert_to_xtf_pings(const jsf_sss_ping::PingsT& pings)\n{\n    std_data::sss_ping::PingsT converted;\n    converted.reserve(pings.size());\n\n    for (const jsf_sss_ping& ping : pings) {\n        std_data::sss_ping cping;\n        cping.time_stamp_ = ping.time_stamp_;\n        cping.time_string_ = ping.time_string_;\n        cping.first_in_file_ = ping.first_in_file_;\n        cping.roll_ = ping.rpy[0];\n        cping.pitch_ = ping.rpy[1];\n        cping.heading_ = ping.rpy[2];\n        cping.lat_ = ping.lat_;\n        cping.long_ = ping.long_;\n        cping.pos_ = ping.pos_;\n        cping.sound_vel_ = ping.sound_vel;\n\n        cping.stbd.time_duration = ping.stbd.time_duration;\n        cping.stbd.pings.resize(ping.stbd.pings.size());\n        for (int i = 0; i < ping.stbd.pings.size(); ++i)\n        {\n            cping.stbd.pings[i] = int(2.*32767.*(.005*ping.stbd.pings[i] - .5));\n        }\n\n        cping.port.time_duration = ping.port.time_duration;\n        cping.port.pings.resize(ping.port.pings.size());\n        for (int i = 0; i < ping.port.pings.size(); ++i)\n        {\n            cping.port.pings[i] = int(2.*32767.*(.005*ping.port.pings[i] - .5));\n        }\n\n        converted.push_back(cping);\n    }\n\n    return converted;\n}\n\n\n} // namespace jsf_data\n\n\n\nnamespace std_data {\n\nusing namespace jsf_data;\n\ntemplate <>\njsf_sss_ping::PingsT parse_file<jsf_sss_ping>(const boost::filesystem::path& file)\n{\n    jsf_sss_ping::PingsT pings = parse_file_impl<jsf_sss_ping, jsf_sonar_data_msg_header, 80>(file);\n    jsf_sss_ping::PingsT fixed_pings;\n    int start;\n    if ((pings[0].time_stamp_ - pings[1].time_stamp_) < 2) {\n        start = 0;\n    }\n    else if ((pings[1].time_stamp_ - pings[2].time_stamp_) < 2) {\n        start = 1;\n    }\n    for (int i = start; i < pings.size()-1; i+=2) {\n        jsf_sss_ping fixed_ping;\n        if (pings[i].port.pings.size() != 0 && pings[i+1].stbd.pings.size() != 0) {\n\n            fixed_ping = pings[i];\n            fixed_ping.stbd = pings[i+1].stbd;\n            fixed_pings.push_back(fixed_ping);\n        }\n        else if (pings[i].stbd.pings.size() != 0 && pings[i+1].port.pings.size() != 0) {\n            fixed_ping = pings[i];\n            fixed_ping.port = pings[i+1].port;\n            fixed_pings.push_back(fixed_ping);\n        }\n        else {\n            cout << \"Invalid data format! Channel numbers are not 0 and 1!\" << endl;\n            break;\n        }\n    }\n    return fixed_pings;\n}\n\ntemplate <>\njsf_dvl_ping::PingsT parse_file<jsf_dvl_ping>(const boost::filesystem::path& file)\n{\n    return parse_file_impl<jsf_dvl_ping, jsf_dvl_msg_header, 2080>(file);\n}\n\n} // namespace std_data\n", "meta": {"hexsha": "7207450c628389bbc6e0f025d4b5b130dac40978", "size": 15808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/data_tools/src/jsf_data.cpp", "max_stars_repo_name": "luxiya01/auvlib", "max_stars_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T16:17:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:25:08.000Z", "max_issues_repo_path": "src/data_tools/src/jsf_data.cpp", "max_issues_repo_name": "luxiya01/auvlib", "max_issues_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-01-11T16:17:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:41:48.000Z", "max_forks_repo_path": "src/data_tools/src/jsf_data.cpp", "max_forks_repo_name": "luxiya01/auvlib", "max_forks_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T16:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:18:58.000Z", "avg_line_length": 38.1835748792, "max_line_length": 758, "alphanum_fraction": 0.6675733806, "num_tokens": 4644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.035144847664027534, "lm_q1q2_score": 0.01237807797707211}}
{"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#include <votca/tools/linalg.h>\n#include <votca/xtp/forces.h>\n#include <boost/format.hpp>\n\nnamespace votca {\n    namespace xtp {\n\n        void Forces::Initialize(Property *options) {\n\n            // checking if there is only one segment\n            _nsegments = _segments.size();\n            if (_nsegments > 1) throw runtime_error(string(\"\\n Force calculation for more than 1 conjugated segment not supported. Stopping!\"));\n\n            // pre-check forces method\n            std::vector<string> choices = {\"forward\", \"central\"};\n            _force_method = options->ifExistsAndinListReturnElseThrowRuntimeError<string>(\".method\", choices);\n\n            // output level\n            _noisy_output = options->ifExistsReturnElseReturnDefault<bool>(\".noisy\", false); \n            \n            \n            // precaution in case we implement approx. analytic forces in the future\n            if ((_force_method == \"forward\") || (_force_method == \"central\")) {\n                _displacement = options->ifExistsReturnElseReturnDefault<double>(\".displacement\", 0.001); // Angstrom\n            }\n\n            // check for force removal options\n            choices = {\"total\", \"CoM\", \"none\"};\n            string _force_removal = options->ifExistsAndinListReturnElseThrowRuntimeError<string>(\".removal\", choices);\n            if (_force_removal == \"total\") _remove_total_force = true;\n            if (_force_removal == \"CoM\") _remove_CoM_force = true;\n\n            _natoms = _segments[0]->Atoms().size();\n            _forces = ub::zero_matrix<double>(_natoms, 3);\n\n\n            return;\n\n        }\n\n        void Forces::Calculate(const double& energy) {\n\n            ctp::TLogLevel _ReportLevel = _pLog->getReportLevel(); // backup report level\n            if ( ! _noisy_output ){\n                _pLog->setReportLevel(ctp::logERROR); // go silent for force calculations\n            }\n            \n            //backup current coordinates (WHY?)\n            std::vector <ctp::Segment* > _molecule;\n            ctp::Segment _current_coordinates(0, \"mol\");\n            _qminterface.Orbitals2Segment(&_current_coordinates, _orbitals);\n            _molecule.push_back(&_current_coordinates);\n\n            // displace all atoms in each Cartesian coordinate and get new energy\n            std::vector< ctp::Atom* > _atoms;\n            std::vector< ctp::Atom* > ::iterator ait;\n            _atoms = _current_coordinates.Atoms();\n\n            int _i_atom = 0;\n            for (ait = _atoms.begin(); ait < _atoms.end(); ++ait) {\n\n                if ( _noisy_output ){\n                    CTP_LOG(ctp::logINFO, *_pLog) << \"FORCES--DEBUG working on atom \" << _i_atom << flush;\n                }\n                \n                // Calculate Force on this atom\n                ub::matrix_range< ub::matrix<double> > _force = ub::subrange(_forces, _i_atom, _i_atom + 1, 0, 3);\n                if (_force_method == \"forward\") NumForceForward(energy, ait, _force, _molecule);\n                if (_force_method == \"central\") NumForceCentral(energy, ait, _force, _molecule);\n                _i_atom++;\n            }\n\n            _pLog->setReportLevel(_ReportLevel); // \n\n            // Remove Total Force, if requested\n            if (_remove_total_force) RemoveTotalForce();\n            //Report();\n\n            return;\n        }\n\n        void Forces::Report() {\n\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"   ---- FORCES (Hartree/Bohr)   \")).str() << flush;\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"        %1$s differences   \") % _force_method).str() << flush;\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"        displacement %1$1.4f Angstrom   \") % _displacement).str() << flush;\n            CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"   Atom\\t x\\t  y\\t  z \")).str() << flush;\n\n            for (unsigned _i = 0; _i < _forces.size1(); _i++) {\n                CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\" %1$4d    %2$+1.4f  %3$+1.4f  %4$+1.4f\")\n                        % _i % _forces(_i, 0) % _forces(_i, 1) % _forces(_i, 2)).str() << flush;\n            }\n\n            return;\n\n        }\n\n        /* Calculate forces on an atom numerically by forward differences */\n        void Forces::NumForceForward(double energy, std::vector< ctp::Atom* > ::iterator ait, ub::matrix_range< ub::matrix<double> >& _force,\n                std::vector<ctp::Segment*> _molecule) {\n\n            // get this atoms's current coordinates\n            vec _current_pos = (*ait)->getQMPos(); // in nm\n\n            for (unsigned _i_cart = 0; _i_cart < 3; _i_cart++) {\n\n                // get displacement std::vector\n                vec _displaced(0, 0, 0);\n                if (_i_cart == 0) {\n                    _displaced.setX(_displacement * tools::conv::ang2nm); // x, _displacement in Angstrom, now in nm\n                }\n                if (_i_cart == 1) {\n                    _displaced.setY(_displacement * tools::conv::ang2nm); // y, _displacement in in Angstrom, now in nm\n                }\n                if (_i_cart == 2) {\n                    _displaced.setZ(_displacement * tools::conv::ang2nm); // z, _displacement in in Angstrom, now in nm\n                }\n\n                // update the coordinate\n                vec _pos_displaced = _current_pos + _displaced;\n\n                (*ait)->setQMPos(_pos_displaced); // put updated coordinate into segment\n\n                // run DFT and GW-BSE for this geometry\n                _gwbse_engine.ExcitationEnergies(_qmpackage, _molecule, _orbitals);\n\n                // get total energy for this excited state\n                double energy_displaced = _orbitals->GetTotalEnergy(_spin_type, _opt_state);\n\n                // calculate force and put into matrix\n                _force(0, _i_cart) = (energy - energy_displaced) / (_displacement * votca::tools::conv::ang2bohr); // force a.u./a.u.\n                (*ait)->setQMPos(_current_pos); // restore original coordinate into segment\n            } // Cartesian directions\n            return;\n        }\n\n        /* Calculate forces on atoms numerically by central differences */\n        void Forces::NumForceCentral(double energy, std::vector< ctp::Atom* > ::iterator ait, ub::matrix_range< ub::matrix<double> >& _force,\n                std::vector<ctp::Segment*> _molecule) {\n\n\n            vec _current_pos = (*ait)->getQMPos(); // in nm\n\n            // go through all cartesian components\n            for (unsigned _i_cart = 0; _i_cart < 3; _i_cart++) {\n\n                if ( _noisy_output ){\n                    CTP_LOG(ctp::logINFO, *_pLog) << \"FORCES--DEBUG           Cartesian component \" << _i_cart << flush;\n                }\n                \n                // get displacement vector in positive direction\n                vec _displaced(0, 0, 0);\n                if (_i_cart == 0) {\n                    _displaced.setX(_displacement * tools::conv::ang2nm); // x, _displacement in Bohr\n                }\n                if (_i_cart == 1) {\n                    _displaced.setY(_displacement * tools::conv::ang2nm); // y, _displacement in in Angstrom\n                }\n                if (_i_cart == 2) {\n                    _displaced.setZ(_displacement * tools::conv::ang2nm); // z, _displacement in in Angstrom\n                }\n\n                // update the coordinate\n                vec _pos_displaced = _current_pos + _displaced;\n                (*ait)->setQMPos(_pos_displaced); // put updated coordinate into segment\n\n                // run DFT and GW-BSE for this geometry\n                _gwbse_engine.ExcitationEnergies(_qmpackage, _molecule, _orbitals);\n\n                // get total energy for this excited state\n                double energy_displaced_plus = _orbitals->GetTotalEnergy(_spin_type, _opt_state);\n\n                // get displacement vector in negative direction\n\n                // update the coordinate\n                _pos_displaced = _current_pos - 2.0 * _displaced;\n                (*ait)->setQMPos(_pos_displaced); // put updated coordinate into segment\n\n                // run DFT and GW-BSE for this geometry\n                _gwbse_engine.ExcitationEnergies(_qmpackage, _molecule, _orbitals);\n\n                // get total energy for this excited state\n                double energy_displaced_minus = _orbitals->GetTotalEnergy(_spin_type, _opt_state);\n\n                // calculate force and put into matrix\n                _force(0, _i_cart) = 0.5 * (energy_displaced_minus - energy_displaced_plus) / (_displacement * votca::tools::conv::ang2bohr); // force a.u./a.u.\n\n                (*ait)->setQMPos(_current_pos); // restore original coordinate into segment\n            }\n\n            return;\n        }\n\n        /* Adjust forces so that sum of forces is zero */\n        void Forces::RemoveTotalForce() {\n\n            // total force on all atoms\n            ub::vector<double> _total_force = TotalForce();\n\n            // zero total force\n            for (unsigned _i_atom = 0; _i_atom < _natoms; _i_atom++) {\n                for (unsigned _i_cart = 0; _i_cart < 3; _i_cart++) {\n                    _forces(_i_atom, _i_cart) -= _total_force(_i_cart) / _natoms;\n                }\n            }\n            return;\n        }\n\n        /* Determine Total Force on all atoms */\n        ub::vector<double> Forces::TotalForce() {\n\n            ub::vector<double> _total_force(3, 0.0);\n            for (unsigned _i_atom = 0; _i_atom < _natoms; _i_atom++) {\n                for (unsigned _i_cart = 0; _i_cart < 3; _i_cart++) {\n                    _total_force(_i_cart) += _forces(_i_atom, _i_cart);\n                }\n            }\n            return _total_force;\n        }\n    }\n}\n", "meta": {"hexsha": "96f06b6488110bea0d64ab0d024eabe0473cdb56", "size": 10342, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/forces.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/forces.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/forces.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": 42.9128630705, "max_line_length": 160, "alphanum_fraction": 0.5598530265, "num_tokens": 2515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.034100426693928106, "lm_q1q2_score": 0.012377404784975017}}
{"text": "/*\r\n* @file\t\t\tGTA.cpp\r\n* @main author  Sejoon Oh (ohhenrie@snu.ac.kr), Seoul National University\r\n* @author       Namyong Park (namyongp@cs.cmu.edu), Carnegie Mellon University\r\n* @author\t\tJun-gi Jang (elnino4@snu.ac.kr), Seoul National University\r\n* @author       Lee Sael (saellee@gmail.com), Seoul National University\r\n* @author       U Kang (ukang@snu.ac.kr), Seoul National University\r\n* @version      1.1\r\n* @date         2019-04-24\r\n*\r\n* A General Framework for Tucker Factorization on Heterogeneous Platforms\r\n*\r\n* This software is free of charge under research purposes.\r\n* For commercial purposes, please contact the main author.\r\n*\r\n*/\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <CL/cl.h>\r\n#include \"omp.h\"\r\n#include <time.h>\r\n#include <Eigen/Dense>\r\nusing namespace std;\r\nusing namespace Eigen;\r\ntypedef Matrix<double, Dynamic, Dynamic> MatrixXdd;\r\n#define lambda 0.001\r\n\r\nstruct GPU_objects {\r\n\tcl_platform_id platform;\r\n\tcl_device_id device;\r\n\tcl_device_id *devices;\r\n\tcl_context context;\r\n\tcl_command_queue queue;\r\n\tcl_command_queue *queues;\r\n\tcl_program program;\r\n\tchar *kernel_source;\r\n\tsize_t kernel_source_size;\r\n\tcl_kernel kernel;\r\n\tcl_kernel *kernels;\r\n\tcl_int err;\r\n\tcl_uint num_devices;\r\n}TF,RECON;\r\n\r\nstruct Tensor{\r\n\tint order;\t\t\t\t\t\t\t\t\t\t\t// Tensor order (e.g., 5)\r\n\tint nonzeros;\t\t\t\t\t\t\t\t\t\t// Number of nonzeros in a tensor (e.g., 1000000)\r\n\tint gpu_mode;\t\t\t\t\t\t\t\t\t\t// CPU:0, Single-GPU: 1, Multi-GPU: 2\r\n\tint partially_observed;\t\t\t\t\t\t\t\t// 0: fully observed, 1: partially observed (default)\r\n\tint local_size;\r\n\tint *dimension;\t\t\t\t\t\t\t\t\t\t// Tensor dimensionality (e.g., 100x100x100)\r\n\t//FOR COO format\r\n\tint *index;\t\t\t\t\t\t\t\t\t\t\t// Indices of a tensor (e.g., (1,2,3))\r\n\tfloat *value;\t\t\t\t\t\t\t\t\t\t// Values of a tensor (e.g., 4.5)\r\n\t//FOR CS-N format\r\n\tfloat *FactorM;\r\n}X,CoreT;\r\n\r\n#define CHECK_ERROR(err) \\\r\n  if (err != CL_SUCCESS) { \\\r\n    printf(\"[%s:%d] OpenCL error %d\\n\", __FILE__, __LINE__, err); \\\r\n    exit(EXIT_FAILURE); \\\r\n  }\r\n\r\ndouble ffrand(double x, double y) {//return the random value in (x,y) interval\r\n\treturn ((y - x)*((double)rand() / RAND_MAX)) + x;\r\n}\r\ndouble abss(double x) {\r\n\treturn x > 0 ? x : -x;\r\n}\r\n\r\ndouble Fit, pFit = -1;\r\nint max_dim;\r\nint *WhereX, *CountX;\t\t\t\t\t        // WhereX[n][I_n] contains all entries of a tensor X whose nth mode's index is I_n\r\n\r\ndouble copy_time, gpu_time;\r\n\r\nint rrank,l_size,gpu_mode,nnz_mode;\r\nchar* InputPath;\r\nchar* ResultPath;\r\n\r\n/////////////////////////////////        OpenCL-related Variables            /////////////////////////////////\r\ncl_context context;\r\ncl_command_queue *queues;\r\ncl_program program;\r\nchar *kernel_source;\r\nsize_t kernel_source_size;\r\ncl_kernel *kernels;\r\ncl_int err;\r\ncl_uint num_devices;\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n//[Input] Source code\r\n//[Output] Source code in a character format\r\n//[Function] Convert source code into a string\r\nchar * get_source_code(const char *file_name, size_t *len) {\r\n\tchar *source_code;\r\n\tsize_t length;\r\n\tFILE *file = fopen(file_name, \"rb\");\r\n\tif (file == NULL) {\r\n\t\tprintf(\"[%s:%d] Failed to open %s\\n\", __FILE__, __LINE__, file_name);\r\n\t\texit(EXIT_FAILURE);\r\n\t}\r\n\r\n\tfseek(file, 0, SEEK_END);\r\n\tlength = (size_t)ftell(file);\r\n\trewind(file);\r\n\r\n\tsource_code = (char *)malloc(length + 1);\r\n\tfread(source_code, length, 1, file);\r\n\tsource_code[length] = '\\0';\r\n\r\n\tfclose(file);\r\n\r\n\t*len = length;\r\n\treturn source_code;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n//[Input] Existing contents of a tensor\r\n//[Output] Tensor in a structured form \r\n//[Function] Constructor function\r\nvoid Construct_Core_Tensor(int ord, int nnz, int* dim, int* ind, float* val) {\r\n\tCoreT.order = ord; CoreT.nonzeros = nnz; CoreT.dimension = dim; CoreT.index = ind; CoreT.value = val;\r\n}\r\n//[Input] Path of a tensor and its metadata\r\n//[Output] Tensor in a structured form \r\n//[Function] Constructor function\r\nvoid Read_Tensor(char* Path) {\r\n\tprintf(\"Reading Input Tensor......\\n\");\r\n\tFILE* fin = fopen(Path, \"r\");\r\n\tFILE* fin2 = fopen(Path,\"r\");\r\n\tchar tmp[10005];\r\n\tint i, j,k;\r\n\tfloat v;\r\n\tint pos = 0,len;\r\n\tX.nonzeros=X.order=0;\r\n\twhile(fgets(tmp,10005,fin2)){\r\n\t\tX.nonzeros++;\r\n\t\tlen = strlen(tmp);\r\n\t\tif(X.nonzeros==1){\r\n\t\t\tfor(i=0;i<len;i++){\r\n\t\t\t\tif(tmp[i]==' ' || tmp[i]=='\\t'){\r\n\t\t\t\t\tX.order++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tX.dimension = (int *)malloc(sizeof(int)*X.order);\r\n\tX.index = (int *)malloc(sizeof(int)*X.order*X.nonzeros);\r\n\tX.value = (float *)malloc(sizeof(float)*X.nonzeros);\r\n\tX.gpu_mode = 0;\r\n\tfor (i = 0; i < X.order; i++) X.dimension[i] = 0;\r\n\tfor (i = 0; i < X.nonzeros; i++) {\r\n\t\tfgets(tmp, 10005, fin);\r\n\t\tlen = strlen(tmp);\r\n\t\tint k = 0, idx = 0, flag = 0, flag2 = 0;\r\n\t\tdouble mul = 0.1, val = 0;\r\n\t\tfor (j = 0; j < len; j++) {\r\n\t\t\tif (tmp[j] == ' ' || tmp[j] == '\\t') {\r\n\t\t\t\tX.index[pos++] = idx - 1;\r\n\t\t\t\tif (X.dimension[k] < idx) X.dimension[k] = idx;\r\n\t\t\t\tidx = 0;\r\n\t\t\t\tk++;\r\n\t\t\t}\r\n\t\t\telse if (tmp[j] >= '0' && tmp[j] <= '9') {\r\n\t\t\t\tif (flag == 1) {\r\n\t\t\t\t\tval += mul*(tmp[j] - '0');\r\n\t\t\t\t\tmul /= 10;\r\n\t\t\t\t}\r\n\t\t\t\telse idx = idx * 10 + tmp[j] - '0';\r\n\t\t\t}\r\n\t\t\telse if (tmp[j] == '.') {\r\n\t\t\t\tval += idx;\r\n\t\t\t\tflag = 1;\r\n\t\t\t}\r\n\t\t\telse if (tmp[j] == '-') {\r\n\t\t\t\tflag2 = 1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(flag==0) val = idx;\r\n        if(flag2 == 0){ \r\n\t\t    X.value[i] = val;\r\n        }else{\r\n            X.value[i] = -val;\r\n        }\r\n\t}\r\n\tX.partially_observed = nnz_mode; \r\n\tX.local_size = l_size; \r\n\tX.gpu_mode = gpu_mode;\r\n\tprintf(\"Reading DONE!\\n\\n\");\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n//[Input] GPU mode and kernel information\r\n//[Output] Initialized OpenCL variables\r\n//[Function] Setup and initialized Opencl-related variables\r\nGPU_objects GPU_INIT(int gpu_mode, char* kernel_code, char* kernel_name) {\r\n\tGPU_objects obj;\r\n\terr = clGetPlatformIDs(1, &obj.platform, NULL); CHECK_ERROR(err);\r\n\terr = clGetDeviceIDs(obj.platform, CL_DEVICE_TYPE_GPU, 0, NULL, &obj.num_devices); CHECK_ERROR(err);\r\n\tprintf(\"%u devices\\n\", obj.num_devices);\r\n\tobj.devices = (cl_device_id*)malloc(sizeof(cl_device_id) * obj.num_devices);\r\n\tobj.queues = (cl_command_queue*)malloc(sizeof(cl_command_queue) * obj.num_devices);\r\n\tobj.kernels = (cl_kernel*)malloc(sizeof(cl_kernel) * obj.num_devices);\r\n\terr = clGetDeviceIDs(obj.platform, CL_DEVICE_TYPE_GPU, obj.num_devices, obj.devices, NULL); CHECK_ERROR(err);\r\n\tobj.context = clCreateContext(NULL, obj.num_devices, obj.devices, NULL, NULL, &err); CHECK_ERROR(err);\r\n\tfor (int i = 0; i < obj.num_devices; i++) {\r\n\t\tobj.queues[i] = clCreateCommandQueue(obj.context, obj.devices[i], 0, &err);\tCHECK_ERROR(err);\r\n\t}\r\n\tobj.kernel_source = get_source_code(kernel_code, &obj.kernel_source_size);\r\n\tobj.program = clCreateProgramWithSource(obj.context, 1, (const char**)&obj.kernel_source, &obj.kernel_source_size, &err); CHECK_ERROR(err);\r\n\terr = clBuildProgram(obj.program, obj.num_devices, obj.devices, \"\", NULL, NULL);\r\n\tif (err == CL_BUILD_PROGRAM_FAILURE) {\r\n\t\tsize_t log_size;\r\n\t\tchar *log;\r\n\t\terr = clGetProgramBuildInfo(obj.program, obj.devices[0], CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); CHECK_ERROR(err);\r\n\t\tlog = (char*)malloc(log_size + 1);\r\n\t\terr = clGetProgramBuildInfo(obj.program, obj.devices[0], CL_PROGRAM_BUILD_LOG, log_size, log, NULL); CHECK_ERROR(err);\r\n\t\tlog[log_size] = '\\0';\r\n\t\tprintf(\"Compiler error:\\n%s\\n\", log);\r\n\t\tfree(log);\r\n\t\texit(0);\r\n\t}\r\n\tfor (int i = 0; i < obj.num_devices; i++) {\r\n\t\tobj.kernels[i] = clCreateKernel(obj.program, kernel_name, &err); CHECK_ERROR(err);\r\n\t}\r\n\treturn obj;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n//[Input] GPU mode and OpenCL variables\r\n//[Output] Released OpenCL variables\r\n//[Function] Release the corresponding OpenCL variables\r\nvoid GPU_DONE(int mode,GPU_objects obj) {\r\n\tif (mode == 0) return;\r\n\tint i = 0;\r\n\tfor (i = 0; i < obj.num_devices; i++) clReleaseKernel(obj.kernels[i]);\r\n\tfree(obj.kernels);\r\n\tfor (i = 0; i < obj.num_devices; i++) clReleaseCommandQueue(obj.queues[i]);\r\n\tfree(obj.queues);\r\n\tfree(obj.devices);\r\n\tclReleaseProgram(obj.program);\r\n\tclReleaseContext(obj.context);\r\n}\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nvoid assign_index() {\r\n\r\n\tint order = X.order, nonzeros = X.nonzeros;\r\n\tint* indices = X.index;\r\n\tint *tempX = (int *)malloc(sizeof(int)*max_dim*order);\r\n\tint pos = 0, i, j, k, l;\r\n\tfor (i = 0; i < order; i++) {\r\n\t\tfor (j = 0; j < X.dimension[i]; j++) {\r\n\t\t\tCountX[i*max_dim + j] = tempX[i*max_dim + j] = 0;\r\n\t\t}\r\n\t}\r\n\tfor (i = 0; i < nonzeros; i++) {\r\n\t\tfor (j = 0; j < order; j++) {\r\n\t\t\tk = indices[pos++];\r\n\t\t\tCountX[j*max_dim + k]++;\r\n\t\t\ttempX[j*max_dim + k]++;\r\n\t\t}\r\n\t}\r\n\tpos = 0;\r\n\tint now = 0;\r\n\tfor (i = 0; i < order; i++) {\r\n\t\tpos = i*max_dim;\r\n\t\tfor (j = 0; j < X.dimension[i]; j++) {\r\n\t\t\tk = CountX[pos];\r\n\t\t\tCountX[pos] = now;\r\n\t\t\ttempX[pos++] = now;\r\n\t\t\tnow += k;\r\n\t\t}\r\n\t\tCountX[pos] = now;\r\n\t\ttempX[pos] = now;\r\n\t}\r\n\tpos = 0;\r\n\tfor (i = 0; i < nonzeros; i++) {\r\n\t\tfor (j = 0; j < order; j++) {\r\n\t\t\tk = indices[pos++];\r\n\t\t\tint now = tempX[j*max_dim + k];\r\n\t\t\tWhereX[now] = i;\r\n\t\t\ttempX[j*max_dim + k]++;\r\n\t\t}\r\n\t}\r\n\tfree(tempX);\r\n}\r\n\r\nvoid partially_observed_pre_process(double *pre_check, int order, int rrank, int mult, float *FactorM, int* dim) {\r\n\tint i, j, k, l;\r\n\tfor (i = 0; i < order; i++) {\r\n\t\tfor (j = 0; j < rrank; j++) {\r\n\t\t\tfor (k = 0; k < rrank; k++) {\r\n\t\t\t\tint pos1 = i*mult + j, pos2 = i*mult + k, now = i*rrank*rrank + j*rrank + k;\r\n\t\t\t\tpre_check[now] = 0;\r\n\t\t\t\tfor (l = 0; l < dim[i]; l++) {\r\n\t\t\t\t\tpre_check[now] += FactorM[pos1 + l*rrank] * FactorM[pos2 + l*rrank];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nvoid Computing_Delta(float* Delta, int rrank, int i) {\r\n\tint order = X.order, nnz = X.nonzeros, Core_N = CoreT.nonzeros, j, k, l, ii, jj;\r\n\tint *dim = X.dimension;\r\n\tint mult = max_dim*rrank;\r\n\tdouble st = omp_get_wtime(),st2=omp_get_wtime();\r\n\tif (X.gpu_mode != 0) {\r\n\t\t\tint NNZ_PER_DEVICE = nnz / num_devices + 1, last;\r\n\t\t\tif (nnz%num_devices == 0) NNZ_PER_DEVICE--;\r\n\t\t\tlast = nnz - NNZ_PER_DEVICE*(num_devices - 1);\r\n\t\t\tcl_mem *bufA, *bufB, *bufC, *bufD, *bufE, *bufF;\r\n\t\t\tbufA = (cl_mem*)malloc(sizeof(cl_mem) * num_devices); bufB = (cl_mem*)malloc(sizeof(cl_mem) * num_devices); bufC = (cl_mem*)malloc(sizeof(cl_mem) * num_devices);  bufD = (cl_mem*)malloc(sizeof(cl_mem) * num_devices);  bufE = (cl_mem*)malloc(sizeof(cl_mem) * num_devices); bufF = (cl_mem*)malloc(sizeof(cl_mem) * num_devices);\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\tif (j != num_devices - 1) {\r\n\t\t\t\t\tbufA[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int) * NNZ_PER_DEVICE*order, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufA[j], CL_FALSE, 0, sizeof(int) * NNZ_PER_DEVICE*order, X.index + j*NNZ_PER_DEVICE*order, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufB[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*NNZ_PER_DEVICE, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufB[j], CL_FALSE, 0, sizeof(float) * NNZ_PER_DEVICE, X.value + j*NNZ_PER_DEVICE, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufF[j] = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float)*rrank*NNZ_PER_DEVICE, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufF[j], CL_FALSE, 0, sizeof(float)*NNZ_PER_DEVICE*rrank, (Delta + j*NNZ_PER_DEVICE*rrank), 0, NULL, NULL);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tbufA[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int) * last*order, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufA[j], CL_FALSE, 0, sizeof(int) * last*order, X.index + j*NNZ_PER_DEVICE*order, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufB[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*last, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufB[j], CL_FALSE, 0, sizeof(float) * last, X.value + j*NNZ_PER_DEVICE, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufF[j] = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float)*rrank*last, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufF[j], CL_FALSE, 0, sizeof(float)*last*rrank, (Delta + j*NNZ_PER_DEVICE*rrank), 0, NULL, NULL);\r\n\t\t\t\t}\r\n\t\t\t\tbufC[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int)*Core_N*order, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufC[j], CL_FALSE, 0, sizeof(int) * Core_N*order, CoreT.index, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\tbufD[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*Core_N, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufD[j], CL_FALSE, 0, sizeof(float) * Core_N, CoreT.value, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\tbufE[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*order*max_dim*rrank, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufE[j], CL_FALSE, 0, sizeof(float) * order*max_dim*rrank, X.FactorM, 0, NULL, NULL); CHECK_ERROR(err);\r\n\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tfor(int j=0;j<num_devices;j++){\r\n\t\t\t\t\tclFinish(queues[j]);\r\n\t\t\t}\r\n\t\t\tprintf(\"CPU->GPU COPY TIME: %lf\\n\",omp_get_wtime()-st);\r\n\t\t\tcopy_time += omp_get_wtime()-st;\r\n\t\t\tst = omp_get_wtime();\r\n\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 0, sizeof(cl_mem), &bufA[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 1, sizeof(cl_mem), &bufB[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 2, sizeof(cl_mem), &bufC[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 3, sizeof(cl_mem), &bufD[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 4, sizeof(cl_mem), &bufE[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 5, sizeof(cl_mem), &bufF[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 6, sizeof(cl_int), &order); CHECK_ERROR(err);\r\n\t\t\t\tif (j == num_devices - 1) {\r\n\t\t\t\t\terr = clSetKernelArg(kernels[j], 7, sizeof(cl_int), &last); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\terr = clSetKernelArg(kernels[j], 7, sizeof(cl_int), &NNZ_PER_DEVICE); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 8, sizeof(cl_int), &rrank); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 9, sizeof(cl_int), &i); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 10, sizeof(cl_int), &Core_N); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 11, sizeof(cl_int), &mult); CHECK_ERROR(err);\r\n\t\t\t}\r\n\t\t\tsize_t global_size = NNZ_PER_DEVICE;\r\n\t\t\tsize_t local_size = X.local_size;\r\n\t\t\tglobal_size = (global_size + local_size - 1) / local_size * local_size;\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\terr = clEnqueueNDRangeKernel(queues[j], kernels[j], 1, NULL, &global_size, &local_size, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t}\r\n\r\n\t\t\tfor(int j=0;j<num_devices;j++){\r\n\t\t\t\t\tclFinish(queues[j]);\r\n\t\t\t}\r\n\t\t\tprintf(\"GPU COMPUTING TIME: %lf\\n\",omp_get_wtime()-st);\r\n\t\t\tgpu_time += omp_get_wtime()-st;\r\n\t\t\tst = omp_get_wtime();\r\n\r\n\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\tif (j == num_devices - 1) {\r\n\t\t\t\t\terr = clEnqueueReadBuffer(queues[j], bufF[j], CL_TRUE, 0, sizeof(float)*last*rrank, Delta + j*NNZ_PER_DEVICE*rrank, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\terr = clEnqueueReadBuffer(queues[j], bufF[j], CL_TRUE, 0, sizeof(float)*NNZ_PER_DEVICE*rrank, Delta + j*NNZ_PER_DEVICE*rrank, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\tfor(int j=0;j<num_devices;j++){\r\n\t\t\t\t\tclFinish(queues[j]);\r\n\t\t\t}\r\n\t\t\tprintf(\"GPU->CPU COPY TIME: %lf\\n\",omp_get_wtime()-st);\r\n\t\t\tcopy_time += omp_get_wtime()-st;\r\n\t\t\tst = omp_get_wtime();\r\n\r\n\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\tclReleaseMemObject(bufA[j]); clReleaseMemObject(bufB[j]);  clReleaseMemObject(bufC[j]);  clReleaseMemObject(bufD[j]); clReleaseMemObject(bufE[j]); clReleaseMemObject(bufF[j]);\r\n\t\t\t}\r\n\t\t\tfree(bufA); free(bufB); free(bufC); free(bufD); free(bufE); free(bufF);\r\n\t\t}\r\n\r\n\telse {\r\n\t\t#pragma omp parallel for schedule(static)\r\n\t\tfor (j = 0; j < nnz; j++) {\r\n\t\t\tint pre_val = j*order, pre_val2 = j*rrank, k, l, ii;\r\n\t\t\tint *cach1 = (int *)malloc(sizeof(int)*order);\r\n\t\t\tfor (l = 0; l < order; l++) cach1[l] = X.index[pre_val + l];\r\n\t\t\tfor (l = 0; l < rrank; l++) Delta[pre_val2 + l] = 0;\r\n\t\t\tfor (l = 0; l < CoreT.nonzeros; l++) {\r\n\t\t\t\tint pre1 = l*order, pre2 = 0;\r\n\t\t\t\tint CorePos = CoreT.index[pre1 + i];\r\n\t\t\t\tdouble res = CoreT.value[l];\r\n\t\t\t\tfor (ii = 0; ii < order; ii++) {\r\n\t\t\t\t\tif (ii != i) {\r\n\t\t\t\t\t\tint mulrow = cach1[ii], mulcol = CoreT.index[pre1];\r\n\t\t\t\t\t\tres *= X.FactorM[pre2 + mulrow*rrank + mulcol];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpre1++;\r\n\t\t\t\t\tpre2 += mult;\r\n\t\t\t\t}\r\n\t\t\t\tDelta[pre_val2 + CorePos] += res;\r\n\t\t\t}\r\n\t\t\tfree(cach1);\r\n\t\t}\r\n\t}\r\n\tprintf(\"Elapsed time for Computing Delta: %lf\\n\", omp_get_wtime() - st2);\r\n}\r\n\r\nvoid Computing_BC(float* Delta, double* B, double* C, int rank, int i) {\r\n\tint iter, row_size = X.dimension[i],mult = max_dim*rank;\r\n\tdouble st = omp_get_wtime();\r\n\t//Initialize B and C\r\n\t#pragma omp parallel for schedule(static) //in parallel\r\n\tfor (int j = 0; j < row_size; j++) {\r\n\t\tint pos_B = j*rank*rank, pos_C = j*rank,k,l;\r\n\t\tfor (k = 0; k < rank; k++) {\r\n\t\t\tfor (l = 0; l < rank; l++) {\r\n\t\t\t\tB[pos_B] = 0;\r\n\t\t\t\tif (k == l) B[pos_B] = lambda;\r\n\t\t\t\tpos_B++;\r\n\t\t\t}\r\n\t\t\tC[pos_C++] = 0;\r\n\t\t}\r\n\t}\r\n\r\n\t#pragma omp parallel for schedule(dynamic) //in parallel\r\n\tfor (iter = 0; iter < row_size; iter++) {\r\n\t\tint j=iter, k, l, ii, jj,pos_B,pos_C;\r\n\t\tint pos = i*max_dim + j;\r\n\t\tint nnz = CountX[pos + 1] - CountX[pos];\r\n\t\tpos = CountX[pos];\r\n\t\tfor (k = 0; k < nnz; k++) { //Updating Delta, B, and C\r\n\t\t\tint current_input_entry = WhereX[pos + k];\r\n\t\t\tint pre_val = current_input_entry*rank;\r\n\t\t\tint now = 0;\r\n\t\t\tdouble Entry_val = X.value[current_input_entry];\r\n\t\t\tpos_B = j*rank*rank, pos_C = j*rank;\r\n\t\t\tfor (ii = 0; ii < rank; ii++) {\r\n\t\t\t\tdouble cach = Delta[pre_val + ii];\r\n\t\t\t\tfor (jj = 0; jj < rank; jj++) {\r\n\t\t\t\t\tB[pos_B++] += cach * Delta[pre_val + jj];\r\n\t\t\t\t}\r\n\t\t\t\tC[pos_C++] += cach * Entry_val;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tprintf(\"Elapsed time for Computing B and C: %lf\\n\", omp_get_wtime() - st);\r\n}\r\n\r\n\r\nvoid Update_Factor_Matrices(int rrank) {\r\n\tint order = X.order, nnz = X.nonzeros, Core_N = CoreT.nonzeros, i, j, k, l;\r\n\tint *dim = X.dimension;\r\n\tint *crows, rowcount, Core_dim;\r\n\tint mult = max_dim*rrank;\r\n\tdouble st = omp_get_wtime();\r\n\tfloat *Delta = (float *)malloc(sizeof(float)*nnz*rrank);\r\n\tdouble *pre_check = (double *)malloc(sizeof(double)*order*rrank*rrank);\r\n\tdouble *B = (double *)malloc(sizeof(double)*max_dim*rrank*rrank);\r\n\tdouble *C = (double *)malloc(sizeof(double)*max_dim*rrank);\r\n\tdouble *Shared_B = (double *)malloc(sizeof(double)*rrank*rrank);\r\n\tif (X.partially_observed == 0) {\r\n\t\tpartially_observed_pre_process(pre_check, order, rrank, mult, X.FactorM, dim);\r\n\t}\r\n\r\n\tkernels = TF.kernels; queues = TF.queues; context = TF.context; \r\n\tprintf(\"INIT TIME: %lf\\n\", omp_get_wtime() - st);\r\n\r\n\tcopy_time = gpu_time = 0;\r\n\r\n\tfor (i = 0; i < order; i++) { //Updating the ith Factor Matrix\r\n\t\tint row_size = dim[i];\r\n\t\tint column_size = rrank;\r\n\t\tint iter;\r\n\r\n\t\tst = omp_get_wtime();\r\n\t\tComputing_Delta(Delta, rrank, i);\r\n\r\n\t\tlong long sizee = Core_N*Core_N;\r\n\t\tif (X.partially_observed == 0) {\r\n\t\t\tdouble st2 = omp_get_wtime();\r\n\t\t\tfor (j = 0; j < column_size; j++) {\r\n\t\t\t\tfor (k = 0; k < column_size; k++) {\r\n\t\t\t\t\tdouble temp = 0;\r\n\t\t\t\t\tif (j == k) temp = lambda;\r\n\t\t\t\t\tShared_B[j*column_size + k] = temp;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tlong long j;\r\n\t\t\tfor (j = 0; j < sizee; j++) {\r\n\t\t\t\tint alpha = j / Core_N, beta = j - alpha*Core_N, k, aa;\r\n\t\t\t\tdouble totalval = CoreT.value[alpha] * CoreT.value[beta];\r\n\t\t\t\tfor (k = 0; k < order; k++) {\r\n\t\t\t\t\tif (k != i) {\r\n\t\t\t\t\t\tint pos3 = CoreT.index[alpha*order + k], pos4 = CoreT.index[beta*order + k], pos5 = k*mult;\r\n\t\t\t\t\t\ttotalval *= pre_check[k*rrank*rrank + pos3*rrank + pos4];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tint pos1 = CoreT.index[alpha*order + i], pos2 = CoreT.index[beta*order + i];\r\n\t\t\t\tShared_B[pos1*column_size + pos2] += totalval;\r\n\t\t\t}\r\n\t\t\tprintf(\"Shared_B calculation time : %lf\\n\", omp_get_wtime() - st2);\r\n\t\t}\r\n\r\n\t\tComputing_BC(Delta, B, C, rrank, i);\r\n\t\t\r\n\t\tdouble st2 = omp_get_wtime();\r\n\t\t#pragma omp parallel for schedule(static) //in parallel\r\n\t\tfor (iter = 0; iter < row_size; iter++) {\r\n\t\t\t//Getting the inverse matrix of [B+lambda*I]\r\n\t\t\tint pos, j, k, l;\r\n\t\t\tj = iter;\r\n\t\t\tint pos_B = j*column_size*column_size, pos_C = j*column_size;\r\n\t\t\tMatrixXdd AA(column_size, column_size);\r\n\t\t\tpos = 0;\r\n\t\t\tfor (k = 0; k < column_size; k++) {\r\n\t\t\t\tfor (l = 0; l < column_size; l++) {\r\n\t\t\t\t\tif (X.partially_observed == 1) AA(k, l) = B[pos_B+k*column_size + l];\r\n\t\t\t\t\telse AA(k, l) = Shared_B[k*column_size + l];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tMatrixXdd BB = AA.inverse();\r\n\r\n\t\t\t//Update the jth row of ith Factor Matrix \r\n\t\t\tint cach = i*mult + j*column_size;\r\n\t\t\tfor (k = 0; k < column_size; k++) {\r\n\t\t\t\tdouble res = 0;\r\n\t\t\t\tfor (l = 0; l < column_size; l++) {\r\n\t\t\t\t\tres += C[pos_C + l] * BB(l , k);\r\n\t\t\t\t}\r\n\t\t\t\tX.FactorM[cach + k] = res;\r\n\t\t\t}\r\n\t\t\tAA.resize(0,0); BB.resize(0,0);\r\n\t\t}\r\n\r\n\t\tprintf(\"UPDATE TIME : %lf\\n\",omp_get_wtime()-st2);\r\n\t\tif (X.partially_observed == 0) {\r\n\t\t\tfor (j = 0; j < rrank; j++) {\r\n\t\t\t\tfor (k = 0; k < rrank; k++) {\r\n\t\t\t\t\tint pos1 = i*mult + j, pos2 = i*mult + k, now = i*rrank*rrank + j*rrank + k;\r\n\t\t\t\t\tpre_check[now] = 0;\r\n\t\t\t\t\tfor (l = 0; l < dim[i]; l++) {\r\n\t\t\t\t\t\tdouble a1 =  X.FactorM[pos1 + l*rrank], a2 =   X.FactorM[pos2 + l*rrank];\r\n\t\t\t\t\t\tpre_check[now] += a1*a2;\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\tprintf(\"[FACTOR MATRIX %d] UPDATE time : %lf\\n\\n\", i + 1, (omp_get_wtime() - st));\r\n\t\t\r\n\t}\r\n\tprintf(\"copy time: %lf\\tgpu time: %lf\\n\",copy_time,gpu_time);\r\n\r\n\tfree(Delta); free(pre_check); free(Shared_B); free(B); free(C);\r\n}\r\n\r\nvoid Reconstruction(int rrank) {\r\n\tint order = X.order, nnz = X.nonzeros, Core_N = CoreT.nonzeros, i, j, k, l;\r\n\tint* dim = X.dimension;\r\n\tfloat *Error_T, Error = 0, NormX = 0;\r\n\tError_T = (float *)malloc(sizeof(float)*nnz);\r\n\tdouble st = omp_get_wtime();\r\n\tint mult = max_dim*rrank;\r\n\r\n\tif (X.gpu_mode == 0) {\r\n\t\t#pragma omp parallel for schedule(static)\r\n\t\tfor (i = 0; i < nnz; i++) {\r\n\t\t\tint j, pre_val = i*order;\r\n\t\t\tdouble ans = 0;\r\n\t\t\tint *cach1 = (int *)malloc(sizeof(int)*order);\r\n\t\t\tfor (j = 0; j < order; j++) cach1[j] = X.index[pre_val++];\r\n\t\t\tfor (j = 0; j < Core_N; j++) {\r\n\t\t\t\tdouble temp = CoreT.value[j];\r\n\t\t\t\tint k;\r\n\t\t\t\tint pos = j*order;\r\n\t\t\t\tint val = 0;\r\n\t\t\t\tfor (k = 0; k < order; k++) {\r\n\t\t\t\t\tint mulrow = cach1[k], mulcol = CoreT.index[pos++];\r\n\t\t\t\t\ttemp *= X.FactorM[val + mulrow*rrank + mulcol];\r\n\t\t\t\t\tval += mult;\r\n\t\t\t\t}\r\n\t\t\t\tans += temp;\r\n\t\t\t}\r\n\t\t\tfree(cach1);\r\n\t\t\tError_T[i] = ans;\r\n\t\t}\r\n\t}\r\n\r\n\tif (X.gpu_mode != 0) {\r\n\t\t\r\n\t\tkernels = RECON.kernels; queues = RECON.queues; context = RECON.context; \r\n\t\t\r\n\t\tint NNZ_PER_DEVICE = nnz / num_devices + 1, last;\r\n\t\t\tif (nnz%num_devices == 0) NNZ_PER_DEVICE--;\r\n\t\t\tlast = nnz - NNZ_PER_DEVICE*(num_devices - 1);\r\n\t\t\tcl_mem *bufA, *bufB, *bufC, *bufD, *bufE, *bufF;\r\n\t\t\tbufA = (cl_mem*)malloc(sizeof(cl_mem) * num_devices); bufB = (cl_mem*)malloc(sizeof(cl_mem) * num_devices);  bufC = (cl_mem*)malloc(sizeof(cl_mem) * num_devices);  bufD = (cl_mem*)malloc(sizeof(cl_mem) * num_devices);  bufE = (cl_mem*)malloc(sizeof(cl_mem) * num_devices); bufF = (cl_mem*)malloc(sizeof(cl_mem) * num_devices);\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\tif (j != num_devices - 1) {\r\n\t\t\t\t\tbufA[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int) * NNZ_PER_DEVICE*order, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufA[j], CL_FALSE, 0, sizeof(int) * NNZ_PER_DEVICE*order, X.index + j*NNZ_PER_DEVICE*order, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufB[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*NNZ_PER_DEVICE, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufB[j], CL_FALSE, 0, sizeof(float) * NNZ_PER_DEVICE, X.value + j*NNZ_PER_DEVICE, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufF[j] = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*NNZ_PER_DEVICE, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufF[j], CL_FALSE, 0, sizeof(float)*NNZ_PER_DEVICE, (Error_T + j*NNZ_PER_DEVICE), 0, NULL, NULL);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tbufA[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int) * last*order, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufA[j], CL_FALSE, 0, sizeof(int) * last*order, X.index + j*NNZ_PER_DEVICE*order, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufB[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*last, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufB[j], CL_FALSE, 0, sizeof(float) * last, X.value + j*NNZ_PER_DEVICE, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t\tbufF[j] = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*last, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufF[j], CL_FALSE, 0, sizeof(float)*last, (Error_T + j*NNZ_PER_DEVICE), 0, NULL, NULL);\r\n\t\t\t\t}\r\n\t\t\t\tbufC[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(int)*Core_N*order, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufC[j], CL_FALSE, 0, sizeof(int) * Core_N*order, CoreT.index, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\tbufD[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*Core_N, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufD[j], CL_FALSE, 0, sizeof(float) * Core_N, CoreT.value, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\tbufE[j] = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*order*max_dim*rrank, NULL, &err); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queues[j], bufE[j], CL_FALSE, 0, sizeof(float) * order*max_dim*rrank, X.FactorM, 0, NULL, NULL); CHECK_ERROR(err);\r\n\r\n\t\t\t}\r\n\r\n\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 0, sizeof(cl_mem), &bufA[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 1, sizeof(cl_mem), &bufB[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 2, sizeof(cl_mem), &bufC[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 3, sizeof(cl_mem), &bufD[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 4, sizeof(cl_mem), &bufE[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 5, sizeof(cl_mem), &bufF[j]); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 6, sizeof(cl_int), &order); CHECK_ERROR(err);\r\n\t\t\t\tif (j == num_devices - 1) {\r\n\t\t\t\t\terr = clSetKernelArg(kernels[j], 7, sizeof(cl_int), &last); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\terr = clSetKernelArg(kernels[j], 7, sizeof(cl_int), &NNZ_PER_DEVICE); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 8, sizeof(cl_int), &rrank); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 9, sizeof(cl_int), &Core_N); CHECK_ERROR(err);\r\n\t\t\t\terr = clSetKernelArg(kernels[j], 10, sizeof(cl_int), &mult); CHECK_ERROR(err);\r\n\t\t\t}\r\n\r\n\t\t\tsize_t global_size = NNZ_PER_DEVICE;\r\n\t\t\tsize_t local_size = X.local_size/2;\r\n\t\t\tglobal_size = (global_size + local_size - 1) / local_size * local_size;\r\n\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\terr = clEnqueueNDRangeKernel(queues[j], kernels[j], 1, NULL, &global_size, &local_size, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t}\r\n\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\tif (j == num_devices - 1) {\r\n\t\t\t\t\terr = clEnqueueReadBuffer(queues[j], bufF[j], CL_TRUE, 0, sizeof(float)*last, Error_T + j*NNZ_PER_DEVICE, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\terr = clEnqueueReadBuffer(queues[j], bufF[j], CL_TRUE, 0, sizeof(float)*NNZ_PER_DEVICE, Error_T + j*NNZ_PER_DEVICE, 0, NULL, NULL); CHECK_ERROR(err);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfor (int j = 0; j < num_devices; j++) {\r\n\t\t\t\tclReleaseMemObject(bufA[j]); clReleaseMemObject(bufB[j]); clReleaseMemObject(bufC[j]); clReleaseMemObject(bufD[j]); clReleaseMemObject(bufE[j]); clReleaseMemObject(bufF[j]);\r\n\t\t\t}\r\n\t\t\tfree(bufA); free(bufB); free(bufC); free(bufD); free(bufE); free(bufF);\r\n\t\t}\r\n\r\n\tif (X.partially_observed == 0) {\r\n\t\tdouble *pre_check = (double *)malloc(sizeof(double)*order*rrank*rrank);\r\n\r\n\t\tpartially_observed_pre_process(pre_check, order, rrank, mult, X.FactorM, dim);\r\n\r\n\t\tlong long sizee = Core_N*Core_N,j;\r\n\t\tfor (j = 0; j < sizee; j++) {\r\n\t\t\tint alpha = j / Core_N, beta = j - alpha*Core_N, k, aa;\r\n\t\t\tdouble totalval = CoreT.value[alpha] * CoreT.value[beta];\r\n\t\t\tfor (k = 0; k < order; k++) {\r\n\t\t\t\tint pos3 = CoreT.index[alpha*order + k], pos4 = CoreT.index[beta*order + k], pos5 = k*mult;\r\n\t\t\t\ttotalval *= pre_check[k*rrank*rrank + pos3*rrank + pos4];\r\n\t\t\t}\r\n\t\t\tError+=totalval;\r\n\t\t}\r\n\t\tfree(pre_check);\r\n\r\n#pragma omp parallel for schedule(static)\r\n\t\tfor (i = 0; i < nnz; i++) {\r\n\t\t\tfloat temp = X.value[i] * (X.value[i] - 2 * Error_T[i]);\r\n\t\t\tError_T[i] = temp;\r\n\t\t}\r\n\t}\r\n\tst = omp_get_wtime();\r\n\tif (X.partially_observed == 1) {\r\n#pragma omp parallel for schedule(static) reduction(+:Error)\r\n\t\tfor (i = 0; i < nnz; i++) {\r\n\t\t\tError += (X.value[i] - Error_T[i]) * (X.value[i] - Error_T[i]);\r\n\t\t}\r\n\t}\r\n\telse {\r\n#pragma omp parallel for schedule(static) reduction(+:Error)\r\n\t\tfor (i = 0; i < nnz; i++) {\r\n\t\t\tError += Error_T[i];\r\n\t\t}\r\n\t}\r\n\r\n#pragma omp parallel for schedule(static) reduction(+:NormX)\r\n\tfor (i = 0; i < nnz; i++) {\r\n\t\tNormX += X.value[i] * X.value[i];\r\n\t}\r\n\r\n\tNormX = sqrt(NormX);\r\n\tif (NormX == 0) Fit = 1;\r\n\telse Fit = 1 - sqrt(Error) / NormX;\r\n\tfree(Error_T);\r\n}\r\n\r\n\r\nvoid tensor_factorization(int rrank, char* Path) {\r\n\tprintf(\"INITIALIZING FOR TF......\\n\");\r\n\tint order = X.order, nnz = X.nonzeros, i, j, k, threads = omp_get_max_threads();\r\n\tomp_set_num_threads(threads);\r\n\tnum_devices = X.gpu_mode;\r\n\r\n\t//INITIALIZE\r\n\tfor(i=0;i<order;i++){\r\n\t\tif(max_dim<X.dimension[i]) max_dim = X.dimension[i];\r\n\t}\r\n\tmax_dim++;\r\n\t\r\n\tX.FactorM = (float *)malloc(sizeof(float)*order*max_dim * rrank);\r\n\tfor (i = 0; i < order; i++) {\r\n\t\tint row = X.dimension[i];\r\n\t\tfor (j = 0; j < row; j++) {\r\n\t\t\tfor (k = 0; k < rrank; k++) {\r\n\t\t\t\tX.FactorM[i*max_dim*rrank + j*rrank + k] = ffrand(0, 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tint Core_N = 1;\r\n\tint* core_dim = (int *)malloc(sizeof(int)*order);\r\n\tfor (i = 0; i < order; i++) {\r\n\t\tcore_dim[i] = rrank;\r\n\t\tCore_N *= rrank;\r\n\t}\r\n\tint* core_index = (int *)malloc(sizeof(int)*order*Core_N);\r\n\tfloat* core_val = (float *)malloc(sizeof(float)*order*Core_N);\r\n\tfor (i = 0; i < Core_N; i++) {\r\n\t\tcore_val[i] = ffrand(0, 1);\r\n\t\tif (i == 0) {\r\n\t\t\tfor (j = 0; j < order; j++) core_index[j] = 0;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfor (j = 0; j < order; j++) {\r\n\t\t\t\tcore_index[i*order + j] = core_index[(i - 1)*order + j];\r\n\t\t\t}\r\n\t\t\tcore_index[i*order + order - 1]++;  k = order - 1;\r\n\t\t\twhile (core_index[i*order + k] >= rrank) {\r\n\t\t\t\tcore_index[i*order + k] -= rrank;\r\n\t\t\t\tcore_index[i*order + k - 1]++; k--;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tConstruct_Core_Tensor(order, Core_N, core_dim, core_index, core_val);\r\n\r\n\tWhereX = (int *)malloc(sizeof(int)*order*nnz);\r\n\tCountX = (int *)malloc(sizeof(int)*max_dim*order);\r\n\tassign_index();\r\n\tTF = GPU_INIT(X.gpu_mode, \"src/GTA_GPU_Delta.cl\", \"compute_delta\");\r\n\tRECON = GPU_INIT(X.gpu_mode, \"src/GTA_reconstruction.cl\", \"recon\");\r\n\r\n\t//Main Iteration\r\n\tint iter = 0;\r\n\tdouble avertime = omp_get_wtime();\r\n\tprintf(\"INITIALIZE DONE!\\n\\nTensor order: %d\\tnonzeros: %d\\trrank: %d\\tthreads: %d\\tLocal size: %d\\tNumber of GPUs: %d\\n\\n\", order, nnz, rrank, omp_get_max_threads(),X.local_size,num_devices);\r\n\tif (X.gpu_mode == 0 && X.partially_observed==0) printf(\"Starting Tucker Factorization for a Fully Observable Tensor in CPU-mode......\\n\\n\");\r\n\tif (X.gpu_mode == 0 && X.partially_observed==1) printf(\"Starting Tucker Factorization for a Partially Observable Tensor in CPU-mode......\\n\\n\");\r\n\tif (X.gpu_mode == 1 && X.partially_observed==0) printf(\"Starting Tucker Factorization for a Fully Observable Tensor in Single-GPU-mode......\\n\\n\");\r\n\tif (X.gpu_mode == 1 && X.partially_observed==1) printf(\"Starting Tucker Factorization for a Partially Observable Tensor in Single-GPU-mode......\\n\\n\");\r\n\tif (X.gpu_mode >= 2 && X.partially_observed==0) printf(\"Starting Tucker Factorization for a Fully Observable Tensor in Multi-GPU-mode......\\n\\n\");\r\n\tif (X.gpu_mode >= 2 && X.partially_observed==1) printf(\"Starting Tucker Factorization for a Partially Observable Tensor in Multi-GPU-mode......\\n\\n\");\r\n\r\n\twhile (1) {\r\n\r\n\t\tdouble itertime = omp_get_wtime(), steptime;\r\n\t\tsteptime = itertime;\r\n\r\n\t\tUpdate_Factor_Matrices(rrank);\r\n\t\tprintf(\"Factor Time : %lf\\n\", omp_get_wtime() - steptime);\r\n\t\tsteptime = omp_get_wtime();\r\n\r\n\t\tReconstruction(rrank);\r\n\t\tprintf(\"Recon Time : %lf\\n\\n\", omp_get_wtime() - steptime);\r\n\t\tsteptime = omp_get_wtime();\r\n\r\n\t\tprintf(\"iter%d :      Fit : %lf\\tElapsed Time : %lf\\n\\n\", ++iter, Fit, omp_get_wtime() - itertime);\r\n\r\n\t\tif (iter>=10 || (pFit != -1 && abss(pFit - Fit) <= 0.0001)) break;\r\n\t\tpFit = Fit;\r\n\t}\r\n\tprintf(\"Average Elapsed time per iteration: %lf\\n\\n\", (omp_get_wtime() - avertime) / iter);\r\n\r\n\tprintf(\"\\nWriting factor matrices and core tensor to file...\\n\");\r\n\tchar temp[10005];\r\n\tint pos = 0;\r\n\tint mult = max_dim*rrank;\r\n\tfor (i = 0; i < order; i++) {\r\n\t\tsprintf(temp, \"%s/FACTOR%d\", Path, i);\r\n\t\tFILE *fin = fopen(temp, \"w\");\r\n\t\tfor (j = 0; j < X.dimension[i]; j++) {\r\n\t\t\tfor (k = 0; k < rrank; k++) {\r\n\t\t\t\tfprintf(fin, \"%e\\t\", X.FactorM[i*mult + j*rrank + k]);\r\n\t\t\t}\r\n\t\t\tfprintf(fin, \"\\n\");\r\n\t\t}\r\n\t}\r\n\tsprintf(temp, \"%s/CORETENSOR\", Path);\r\n\tFILE *fcore = fopen(temp, \"w\");\r\n\tpos = 0;\r\n\tfor (i = 0; i < Core_N; i++) {\r\n\t\tfor (j = 0; j < order; j++) {\r\n\t\t\tfprintf(fcore, \"%d\\t\", CoreT.index[pos++]);\r\n\t\t}\r\n\t\tfprintf(fcore, \"%e\\n\", CoreT.value[i]);\r\n\t}\r\n\r\n\tGPU_DONE(X.gpu_mode,TF);\r\n\tGPU_DONE(X.gpu_mode, RECON);\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n\r\n\tif (argc !=0) {\r\n\t\tInputPath = argv[1];\r\n\t\tResultPath = argv[2];\r\n\t\trrank = atoi(argv[3]);\r\n\t\tl_size = atoi(argv[4]);\r\n\t\tgpu_mode = atoi(argv[5]);\r\n\t\tnnz_mode = atoi(argv[6]);\r\n\t\t\r\n\r\n\t\tRead_Tensor(InputPath);\r\n\r\n\t\ttensor_factorization(rrank,ResultPath);\r\n\t}\t\r\n\t\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "b7b2b5e5eb323b446ce97afa06c5e2e66dda95f6", "size": 33990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GTA.cpp", "max_stars_repo_name": "dawonahn/GTA-Tensor", "max_stars_repo_head_hexsha": "07763aa4cd7e6d1a44c39cb7116f44483155b3e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-08-28T08:54:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T05:04:02.000Z", "max_issues_repo_path": "src/GTA.cpp", "max_issues_repo_name": "dawonahn/GTA-Tensor", "max_issues_repo_head_hexsha": "07763aa4cd7e6d1a44c39cb7116f44483155b3e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-20T01:30:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-20T01:30:25.000Z", "max_forks_repo_path": "src/GTA.cpp", "max_forks_repo_name": "dawonahn/GTA-Tensor", "max_forks_repo_head_hexsha": "07763aa4cd7e6d1a44c39cb7116f44483155b3e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-12-04T01:45:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T13:47:08.000Z", "avg_line_length": 39.6153846154, "max_line_length": 330, "alphanum_fraction": 0.6090909091, "num_tokens": 10653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.03410042509880116, "lm_q1q2_score": 0.012377404205993058}}
{"text": "//\r\n//=======================================================================\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//\r\n\r\n/*\r\n  This file implements the function\r\n\r\n  template <class EdgeListGraph, class Size, class P, class T, class R>\r\n  bool bellman_ford_shortest_paths(EdgeListGraph& g, Size N,\r\n     const bgl_named_params<P, T, R>& params)\r\n\r\n */\r\n\r\n#ifndef BOOST_GRAPH_BELLMAN_FORD_SHORTEST_PATHS_HPP\r\n#define BOOST_GRAPH_BELLMAN_FORD_SHORTEST_PATHS_HPP\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/graph/relax.hpp>\r\n#include <boost/graph/visitors.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/concept/assert.hpp>\r\n\r\nnamespace boost\r\n{\r\n\r\ntemplate < class Visitor, class Graph > struct BellmanFordVisitorConcept\r\n{\r\n    void constraints()\r\n    {\r\n        BOOST_CONCEPT_ASSERT((CopyConstructibleConcept< Visitor >));\r\n        vis.examine_edge(e, g);\r\n        vis.edge_relaxed(e, g);\r\n        vis.edge_not_relaxed(e, g);\r\n        vis.edge_minimized(e, g);\r\n        vis.edge_not_minimized(e, g);\r\n    }\r\n    Visitor vis;\r\n    Graph g;\r\n    typename graph_traits< Graph >::edge_descriptor e;\r\n};\r\n\r\ntemplate < class Visitors = null_visitor > class bellman_visitor\r\n{\r\npublic:\r\n    bellman_visitor() {}\r\n    bellman_visitor(Visitors vis) : m_vis(vis) {}\r\n\r\n    template < class Edge, class Graph > void examine_edge(Edge u, Graph& g)\r\n    {\r\n        invoke_visitors(m_vis, u, g, on_examine_edge());\r\n    }\r\n    template < class Edge, class Graph > void edge_relaxed(Edge u, Graph& g)\r\n    {\r\n        invoke_visitors(m_vis, u, g, on_edge_relaxed());\r\n    }\r\n    template < class Edge, class Graph > void edge_not_relaxed(Edge u, Graph& g)\r\n    {\r\n        invoke_visitors(m_vis, u, g, on_edge_not_relaxed());\r\n    }\r\n    template < class Edge, class Graph > void edge_minimized(Edge u, Graph& g)\r\n    {\r\n        invoke_visitors(m_vis, u, g, on_edge_minimized());\r\n    }\r\n    template < class Edge, class Graph >\r\n    void edge_not_minimized(Edge u, Graph& g)\r\n    {\r\n        invoke_visitors(m_vis, u, g, on_edge_not_minimized());\r\n    }\r\n\r\nprotected:\r\n    Visitors m_vis;\r\n};\r\ntemplate < class Visitors >\r\nbellman_visitor< Visitors > make_bellman_visitor(Visitors vis)\r\n{\r\n    return bellman_visitor< Visitors >(vis);\r\n}\r\ntypedef bellman_visitor<> default_bellman_visitor;\r\n\r\ntemplate < class EdgeListGraph, class Size, class WeightMap,\r\n    class PredecessorMap, class DistanceMap, class BinaryFunction,\r\n    class BinaryPredicate, class BellmanFordVisitor >\r\nbool bellman_ford_shortest_paths(EdgeListGraph& g, Size N, WeightMap weight,\r\n    PredecessorMap pred, DistanceMap distance, BinaryFunction combine,\r\n    BinaryPredicate compare, BellmanFordVisitor v)\r\n{\r\n    BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< EdgeListGraph >));\r\n    typedef graph_traits< EdgeListGraph > GTraits;\r\n    typedef typename GTraits::edge_descriptor Edge;\r\n    typedef typename GTraits::vertex_descriptor Vertex;\r\n    BOOST_CONCEPT_ASSERT((ReadWritePropertyMapConcept< DistanceMap, Vertex >));\r\n    BOOST_CONCEPT_ASSERT((ReadablePropertyMapConcept< WeightMap, Edge >));\r\n\r\n    typename GTraits::edge_iterator i, end;\r\n\r\n    for (Size k = 0; k < N; ++k)\r\n    {\r\n        bool at_least_one_edge_relaxed = false;\r\n        for (boost::tie(i, end) = edges(g); i != end; ++i)\r\n        {\r\n            v.examine_edge(*i, g);\r\n            if (relax(*i, g, weight, pred, distance, combine, compare))\r\n            {\r\n                at_least_one_edge_relaxed = true;\r\n                v.edge_relaxed(*i, g);\r\n            }\r\n            else\r\n                v.edge_not_relaxed(*i, g);\r\n        }\r\n        if (!at_least_one_edge_relaxed)\r\n            break;\r\n    }\r\n\r\n    for (boost::tie(i, end) = edges(g); i != end; ++i)\r\n        if (compare(combine(get(distance, source(*i, g)), get(weight, *i)),\r\n                get(distance, target(*i, g))))\r\n        {\r\n            v.edge_not_minimized(*i, g);\r\n            return false;\r\n        }\r\n        else\r\n            v.edge_minimized(*i, g);\r\n\r\n    return true;\r\n}\r\n\r\nnamespace detail\r\n{\r\n\r\n    template < typename VertexAndEdgeListGraph, typename Size,\r\n        typename WeightMap, typename PredecessorMap, typename DistanceMap,\r\n        typename P, typename T, typename R >\r\n    bool bellman_dispatch2(VertexAndEdgeListGraph& g,\r\n        typename graph_traits< VertexAndEdgeListGraph >::vertex_descriptor s,\r\n        Size N, WeightMap weight, PredecessorMap pred, DistanceMap distance,\r\n        const bgl_named_params< P, T, R >& params)\r\n    {\r\n        typedef typename property_traits< DistanceMap >::value_type D;\r\n        bellman_visitor<> null_vis;\r\n        typedef typename property_traits< WeightMap >::value_type weight_type;\r\n        typename graph_traits< VertexAndEdgeListGraph >::vertex_iterator v,\r\n            v_end;\r\n        for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v)\r\n        {\r\n            put(distance, *v, (std::numeric_limits< weight_type >::max)());\r\n            put(pred, *v, *v);\r\n        }\r\n        put(distance, s, weight_type(0));\r\n        return bellman_ford_shortest_paths(g, N, weight, pred, distance,\r\n            choose_param(\r\n                get_param(params, distance_combine_t()), closed_plus< D >()),\r\n            choose_param(\r\n                get_param(params, distance_compare_t()), std::less< D >()),\r\n            choose_param(get_param(params, graph_visitor), null_vis));\r\n    }\r\n\r\n    template < typename VertexAndEdgeListGraph, typename Size,\r\n        typename WeightMap, typename PredecessorMap, typename DistanceMap,\r\n        typename P, typename T, typename R >\r\n    bool bellman_dispatch2(VertexAndEdgeListGraph& g, param_not_found, Size N,\r\n        WeightMap weight, PredecessorMap pred, DistanceMap distance,\r\n        const bgl_named_params< P, T, R >& params)\r\n    {\r\n        typedef typename property_traits< DistanceMap >::value_type D;\r\n        bellman_visitor<> null_vis;\r\n        return bellman_ford_shortest_paths(g, N, weight, pred, distance,\r\n            choose_param(\r\n                get_param(params, distance_combine_t()), closed_plus< D >()),\r\n            choose_param(\r\n                get_param(params, distance_compare_t()), std::less< D >()),\r\n            choose_param(get_param(params, graph_visitor), null_vis));\r\n    }\r\n\r\n    template < class EdgeListGraph, class Size, class WeightMap,\r\n        class DistanceMap, class P, class T, class R >\r\n    bool bellman_dispatch(EdgeListGraph& g, Size N, WeightMap weight,\r\n        DistanceMap distance, const bgl_named_params< P, T, R >& params)\r\n    {\r\n        dummy_property_map dummy_pred;\r\n        return detail::bellman_dispatch2(g, get_param(params, root_vertex_t()),\r\n            N, weight,\r\n            choose_param(get_param(params, vertex_predecessor), dummy_pred),\r\n            distance, params);\r\n    }\r\n} // namespace detail\r\n\r\ntemplate < class EdgeListGraph, class Size, class P, class T, class R >\r\nbool bellman_ford_shortest_paths(\r\n    EdgeListGraph& g, Size N, const bgl_named_params< P, T, R >& params)\r\n{\r\n    return detail::bellman_dispatch(g, N,\r\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\r\n        choose_pmap(get_param(params, vertex_distance), g, vertex_distance),\r\n        params);\r\n}\r\n\r\ntemplate < class EdgeListGraph, class Size >\r\nbool bellman_ford_shortest_paths(EdgeListGraph& g, Size N)\r\n{\r\n    bgl_named_params< int, int > params(0);\r\n    return bellman_ford_shortest_paths(g, N, params);\r\n}\r\n\r\ntemplate < class VertexAndEdgeListGraph, class P, class T, class R >\r\nbool bellman_ford_shortest_paths(\r\n    VertexAndEdgeListGraph& g, const bgl_named_params< P, T, R >& params)\r\n{\r\n    BOOST_CONCEPT_ASSERT((VertexListGraphConcept< VertexAndEdgeListGraph >));\r\n    return detail::bellman_dispatch(g, num_vertices(g),\r\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\r\n        choose_pmap(get_param(params, vertex_distance), g, vertex_distance),\r\n        params);\r\n}\r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_BELLMAN_FORD_SHORTEST_PATHS_HPP\r\n", "meta": {"hexsha": "cbb9539087767ac6422768ac1e30c73cad7522b1", "size": 8455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/bellman_ford_shortest_paths.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/bellman_ford_shortest_paths.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/bellman_ford_shortest_paths.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": 37.2466960352, "max_line_length": 81, "alphanum_fraction": 0.642578356, "num_tokens": 1989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.03622005651518996, "lm_q1q2_score": 0.012372137434255684}}
{"text": "//=======================================================================\r\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\r\n// Copyright 2009 Trustees of Indiana University.\r\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek, Michael Hansen\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 BOOST_GRAPH_DIJKSTRA_NO_COLOR_MAP_HPP\r\n#define BOOST_GRAPH_DIJKSTRA_NO_COLOR_MAP_HPP\r\n\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/graph/relax.hpp>\r\n#include <boost/graph/detail/d_ary_heap.hpp>\r\n#include <boost/graph/dijkstra_shortest_paths.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n\r\nnamespace boost\r\n{\r\n\r\n// No init version\r\ntemplate < typename Graph, typename DijkstraVisitor, typename PredecessorMap,\r\n    typename DistanceMap, typename WeightMap, typename VertexIndexMap,\r\n    typename DistanceCompare, typename DistanceWeightCombine,\r\n    typename DistanceInfinity, typename DistanceZero >\r\nvoid dijkstra_shortest_paths_no_color_map_no_init(const Graph& graph,\r\n    typename graph_traits< Graph >::vertex_descriptor start_vertex,\r\n    PredecessorMap predecessor_map, DistanceMap distance_map,\r\n    WeightMap weight_map, VertexIndexMap index_map,\r\n    DistanceCompare distance_compare,\r\n    DistanceWeightCombine distance_weight_combine,\r\n    DistanceInfinity distance_infinity, DistanceZero distance_zero,\r\n    DijkstraVisitor visitor)\r\n{\r\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n    typedef typename property_traits< DistanceMap >::value_type Distance;\r\n\r\n    typedef indirect_cmp< DistanceMap, DistanceCompare >\r\n        DistanceIndirectCompare;\r\n    DistanceIndirectCompare distance_indirect_compare(\r\n        distance_map, distance_compare);\r\n\r\n    // Default - use d-ary heap (d = 4)\r\n    typedef detail::vertex_property_map_generator< Graph, VertexIndexMap,\r\n        std::size_t >\r\n        IndexInHeapMapHelper;\r\n    typedef typename IndexInHeapMapHelper::type IndexInHeapMap;\r\n    typedef d_ary_heap_indirect< Vertex, 4, IndexInHeapMap, DistanceMap,\r\n        DistanceCompare >\r\n        VertexQueue;\r\n\r\n    boost::scoped_array< std::size_t > index_in_heap_map_holder;\r\n    IndexInHeapMap index_in_heap = IndexInHeapMapHelper::build(\r\n        graph, index_map, index_in_heap_map_holder);\r\n    VertexQueue vertex_queue(distance_map, index_in_heap, distance_compare);\r\n\r\n    // Add vertex to the queue\r\n    vertex_queue.push(start_vertex);\r\n\r\n    // Starting vertex will always be the first discovered vertex\r\n    visitor.discover_vertex(start_vertex, graph);\r\n\r\n    while (!vertex_queue.empty())\r\n    {\r\n        Vertex min_vertex = vertex_queue.top();\r\n        vertex_queue.pop();\r\n\r\n        visitor.examine_vertex(min_vertex, graph);\r\n\r\n        // Check if any other vertices can be reached\r\n        Distance min_vertex_distance = get(distance_map, min_vertex);\r\n\r\n        if (!distance_compare(min_vertex_distance, distance_infinity))\r\n        {\r\n            // This is the minimum vertex, so all other vertices are unreachable\r\n            return;\r\n        }\r\n\r\n        // Examine neighbors of min_vertex\r\n        BGL_FORALL_OUTEDGES_T(min_vertex, current_edge, graph, Graph)\r\n        {\r\n            visitor.examine_edge(current_edge, graph);\r\n\r\n            // Check if the edge has a negative weight\r\n            if (distance_compare(get(weight_map, current_edge), distance_zero))\r\n            {\r\n                boost::throw_exception(negative_edge());\r\n            }\r\n\r\n            // Extract the neighboring vertex and get its distance\r\n            Vertex neighbor_vertex = target(current_edge, graph);\r\n            Distance neighbor_vertex_distance\r\n                = get(distance_map, neighbor_vertex);\r\n            bool is_neighbor_undiscovered = !distance_compare(\r\n                neighbor_vertex_distance, distance_infinity);\r\n\r\n            // Attempt to relax the edge\r\n            bool was_edge_relaxed\r\n                = relax_target(current_edge, graph, weight_map, predecessor_map,\r\n                    distance_map, distance_weight_combine, distance_compare);\r\n\r\n            if (was_edge_relaxed)\r\n            {\r\n                visitor.edge_relaxed(current_edge, graph);\r\n                if (is_neighbor_undiscovered)\r\n                {\r\n                    visitor.discover_vertex(neighbor_vertex, graph);\r\n                    vertex_queue.push(neighbor_vertex);\r\n                }\r\n                else\r\n                {\r\n                    vertex_queue.update(neighbor_vertex);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                visitor.edge_not_relaxed(current_edge, graph);\r\n            }\r\n\r\n        } // end out edge iteration\r\n\r\n        visitor.finish_vertex(min_vertex, graph);\r\n    } // end while queue not empty\r\n}\r\n\r\n// Full init version\r\ntemplate < typename Graph, typename DijkstraVisitor, typename PredecessorMap,\r\n    typename DistanceMap, typename WeightMap, typename VertexIndexMap,\r\n    typename DistanceCompare, typename DistanceWeightCombine,\r\n    typename DistanceInfinity, typename DistanceZero >\r\nvoid dijkstra_shortest_paths_no_color_map(const Graph& graph,\r\n    typename graph_traits< Graph >::vertex_descriptor start_vertex,\r\n    PredecessorMap predecessor_map, DistanceMap distance_map,\r\n    WeightMap weight_map, VertexIndexMap index_map,\r\n    DistanceCompare distance_compare,\r\n    DistanceWeightCombine distance_weight_combine,\r\n    DistanceInfinity distance_infinity, DistanceZero distance_zero,\r\n    DijkstraVisitor visitor)\r\n{\r\n    // Initialize vertices\r\n    BGL_FORALL_VERTICES_T(current_vertex, graph, Graph)\r\n    {\r\n        visitor.initialize_vertex(current_vertex, graph);\r\n\r\n        // Default all distances to infinity\r\n        put(distance_map, current_vertex, distance_infinity);\r\n\r\n        // Default all vertex predecessors to the vertex itself\r\n        put(predecessor_map, current_vertex, current_vertex);\r\n    }\r\n\r\n    // Set distance for start_vertex to zero\r\n    put(distance_map, start_vertex, distance_zero);\r\n\r\n    // Pass everything on to the no_init version\r\n    dijkstra_shortest_paths_no_color_map_no_init(graph, start_vertex,\r\n        predecessor_map, distance_map, weight_map, index_map, distance_compare,\r\n        distance_weight_combine, distance_infinity, distance_zero, visitor);\r\n}\r\n\r\nnamespace detail\r\n{\r\n\r\n    // Handle defaults for PredecessorMap, DistanceCompare,\r\n    // DistanceWeightCombine, DistanceInfinity and DistanceZero\r\n    template < typename Graph, typename DistanceMap, typename WeightMap,\r\n        typename VertexIndexMap, typename Params >\r\n    inline void dijkstra_no_color_map_dispatch2(const Graph& graph,\r\n        typename graph_traits< Graph >::vertex_descriptor start_vertex,\r\n        DistanceMap distance_map, WeightMap weight_map,\r\n        VertexIndexMap index_map, const Params& params)\r\n    {\r\n        // Default for predecessor map\r\n        dummy_property_map predecessor_map;\r\n\r\n        typedef\r\n            typename property_traits< DistanceMap >::value_type DistanceType;\r\n        DistanceType inf = choose_param(get_param(params, distance_inf_t()),\r\n            (std::numeric_limits< DistanceType >::max)());\r\n        dijkstra_shortest_paths_no_color_map(graph, start_vertex,\r\n            choose_param(\r\n                get_param(params, vertex_predecessor), predecessor_map),\r\n            distance_map, weight_map, index_map,\r\n            choose_param(get_param(params, distance_compare_t()),\r\n                std::less< DistanceType >()),\r\n            choose_param(get_param(params, distance_combine_t()),\r\n                std::plus< DistanceType >()),\r\n            inf,\r\n            choose_param(get_param(params, distance_zero_t()), DistanceType()),\r\n            choose_param(get_param(params, graph_visitor),\r\n                make_dijkstra_visitor(null_visitor())));\r\n    }\r\n\r\n    template < typename Graph, typename DistanceMap, typename WeightMap,\r\n        typename IndexMap, typename Params >\r\n    inline void dijkstra_no_color_map_dispatch1(const Graph& graph,\r\n        typename graph_traits< Graph >::vertex_descriptor start_vertex,\r\n        DistanceMap distance_map, WeightMap weight_map, IndexMap index_map,\r\n        const Params& params)\r\n    {\r\n        // Default for distance map\r\n        typedef typename property_traits< WeightMap >::value_type DistanceType;\r\n        typename std::vector< DistanceType >::size_type vertex_count\r\n            = is_default_param(distance_map) ? num_vertices(graph) : 1;\r\n\r\n        std::vector< DistanceType > default_distance_map(vertex_count);\r\n\r\n        detail::dijkstra_no_color_map_dispatch2(graph, start_vertex,\r\n            choose_param(distance_map,\r\n                make_iterator_property_map(default_distance_map.begin(),\r\n                    index_map, default_distance_map[0])),\r\n            weight_map, index_map, params);\r\n    }\r\n} // namespace detail\r\n\r\n// Named parameter version\r\ntemplate < typename Graph, typename Param, typename Tag, typename Rest >\r\ninline void dijkstra_shortest_paths_no_color_map(const Graph& graph,\r\n    typename graph_traits< Graph >::vertex_descriptor start_vertex,\r\n    const bgl_named_params< Param, Tag, Rest >& params)\r\n{\r\n    // Default for edge weight and vertex index map is to ask for them\r\n    // from the graph. Default for the visitor is null_visitor.\r\n    detail::dijkstra_no_color_map_dispatch1(graph, start_vertex,\r\n        get_param(params, vertex_distance),\r\n        choose_const_pmap(get_param(params, edge_weight), graph, edge_weight),\r\n        choose_const_pmap(get_param(params, vertex_index), graph, vertex_index),\r\n        params);\r\n}\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_DIJKSTRA_NO_COLOR_MAP_HPP\r\n", "meta": {"hexsha": "5f66d2290188756d9024f5102327907294fca9d2", "size": 9855, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/dijkstra_shortest_paths_no_color_map.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/dijkstra_shortest_paths_no_color_map.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/dijkstra_shortest_paths_no_color_map.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.7584745763, "max_line_length": 81, "alphanum_fraction": 0.6770167428, "num_tokens": 1911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.025957357951306048, "lm_q1q2_score": 0.012370748594968369}}
{"text": "#include \"plugins/featureeval/featureeval.h\"\n#include <iostream>\n#include <QDebug>\n#include <QAction>\n#include <QToolBar>\n#include <QtWidgets>\n#include <QScrollArea>\n#include <QDoubleSpinBox>\n\n#include <pcl/point_types.h>\n#include <pcl/features/fpfh.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/features/principal_curvatures.h>\n#include <pcl/octree/octree.h>\n#include <pcl/octree/octree_iterator.h>\n#include <pcl/octree/octree_container.h>\n#include <boost/serialization/shared_ptr.hpp>\n\n#include \"model/layerlist.h\"\n#include \"model/cloudlist.h\"\n#include \"gui/glwidget.h\"\n#include \"gui/flatview.h\"\n#include \"gui/mainwindow.h\"\n#include \"commands/select.h\"\n#include \"pluginsystem/core.h\"\n#include \"utilities/cv.h\"\n#include \"utilities/utils.h\"\n#include \"plugins/normalestimation/normalestimation.h\"\n#include \"plugins/featureeval/utils.h\"\n\nQString FeatureEval::getName(){\n    return \"featureeval\";\n}\n\nvoid FeatureEval::initialize(Core *core){\n    settings_ = nullptr;\n    tab_idx_ = -1;\n\n    image_container_ = nullptr;\n    image_ = nullptr;\n\n    core_= core;\n    cl_ = core_->cl_;\n    ll_ = core_->ll_;\n    glwidget_ = core_->mw_->glwidget_;\n    flatview_ = core_->mw_->flatview_;\n    mw_ = core_->mw_;\n    report_ = nullptr;\n}\n\nvoid FeatureEval::initialize2(PluginManager * pm) {\n    ne_ = pm->findPlugin<NormalEstimator>();\n    if (ne_ == nullptr) {\n        qDebug() << \"Normal estimator plugin needed for normal viz\";\n        return;\n    }\n\n    // GUI STUFF\n    visualise_on_ = true;\n    function_idx_ = 0;\n    layer_idx_ = -1;\n\n    // PARAMS\n    subsample_res_ = 0.1;\n    subsample_res_2_ = 0.2;\n    search_radius_ = 0.2;\n    max_nn_ = 20;\n    bins_ = 20;\n\n    // Set up viz tab\n    depth_widget_ = new QWidget(0);\n    tab_idx_ = core_->mw_->addTab(depth_widget_, \"Feature visualisation\");\n\n    QVBoxLayout * tablayout = new QVBoxLayout(depth_widget_);\n    QScrollArea * scrollarea = new QScrollArea();\n    scrollarea->setBackgroundRole(QPalette::Dark);\n    tablayout->addWidget(scrollarea);\n    image_container_ = new QLabel();\n    scrollarea->setWidget(image_container_);\n\n\n    // set up settings\n    is_enabled_ = false;\n    enable_ = new QAction(QIcon(\":/images/featureeval.png\"), \"Correlate and visualise\", 0);\n    enable_->setCheckable(true);\n\n    connect(enable_, SIGNAL(triggered()), this, SLOT(enable()));\n    mw_->toolbar_->addAction(enable_);\n    time = 0;\n    settings_ = new QWidget();\n    QVBoxLayout * layout = new QVBoxLayout(settings_);\n    settings_->setLayout(layout);\n    mw_->tooloptions_->addWidget(settings_);\n\n    // settings widgets\n    layout->addWidget(new QLabel(\"Feature\"));\n    feature_cb_ = new QComboBox(settings_);\n    layout->addWidget(feature_cb_);\n\n    // round up parameters\n    param_map_[\"subsample_res\"].f = &subsample_res_;\n    param_map_[\"subsample_res.small\"].f = &subsample_res_;\n    param_map_[\"subsample_res.big\"].f = &subsample_res_2_;\n    param_map_[\"bins\"].i =  &bins_;\n    param_map_[\"search_radius\"].f = &search_radius_;\n    param_map_[\"max_nn\"].i = &max_nn_;\n\n    // round up functions\n    feature_cb_->addItem(\"Difference of normals\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::difference_of_normals, this));\n    name_to_function_[\"difference_of_normals\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"intensity_histogram\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::intensity_histogram, this));\n    name_to_function_[\"intensity_histogram\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"Fast point feature histograms\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::fast_point_feature_histogram, this));\n    name_to_function_[\"fast_point_feature_histogram\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"Curvature\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::curvature, this));\n    name_to_function_[\"curvature\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"Distance standard deviation\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::distance_standard_deviation, this));\n    name_to_function_[\"distance_standard_deviation\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"Normal standard deviation\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::normal_standard_deviation, this));\n    name_to_function_[\"normal_standard_deviation\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"Eigen ratio\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::pca_eigen_value_ratio, this));\n    name_to_function_[\"pca_eigen_value_ratio\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"PCA\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::pca, this));\n    name_to_function_[\"pca\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"eigen_plane_consine_similarity\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::eigen_plane_consine_similarity, this));\n    name_to_function_[\"eigen_plane_consine_similarity\"] = functions_[functions_.size()-1];\n\n    feature_cb_->addItem(\"intensity\", (int)functions_.size());\n    functions_.push_back(std::bind(&FeatureEval::intensity, this));\n    name_to_function_[\"intensity\"] = functions_[functions_.size()-1];\n\n//    layout->addWidget(new QLabel(\"Correlate with layer:\"));\n//    layer_cb_ = new QComboBox(settings_);\n//    layout->addWidget(layer_cb_);\n\n\n    // Downsample settings\n    QDoubleSpinBox * downsample_sb = new QDoubleSpinBox();\n    downsample_sb->setAccelerated(true);\n    downsample_sb->setMinimum(0.001);\n    downsample_sb->setMaximum(1);\n    downsample_sb->setValue(subsample_res_);\n    connect(downsample_sb, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), [=] (double value){\n        subsample_res_ = value;\n    });\n\n    layout->addWidget(new QLabel(\"Downsample resolution (meters)\"));\n    layout->addWidget(downsample_sb);\n\n\n    QDoubleSpinBox * downsample_sb2 = new QDoubleSpinBox();\n    downsample_sb2->setAccelerated(true);\n    downsample_sb2->setMinimum(0.001);\n    downsample_sb2->setMaximum(1);\n    downsample_sb2->setValue(subsample_res_2_);\n    connect(downsample_sb2, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), [=] (double value){\n        subsample_res_2_ = value;\n    });\n\n    QLabel * sb2_label = new QLabel(\"Downsample resolution 2 (meters)\");\n    layout->addWidget(sb2_label);\n    layout->addWidget(downsample_sb2);\n\n    // feature change\n    connect(feature_cb_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [=] (int idx){\n        function_idx_ = feature_cb_->itemData(idx).toInt();\n        sb2_label->setVisible(function_idx_ == 0);\n        downsample_sb2->setVisible(function_idx_ == 0);\n        qDebug() << \"changed\";\n    });\n\n    // Run button\n    QPushButton * run = new QPushButton(\"Correlate and visualise\");\n    connect(run, &QPushButton::clicked, [=] (){\n        if(function_idx_ != -1){\n            qDebug() << \"call!\";\n            functions_[function_idx_]();\n        }\n\n    });\n    layout->addWidget(run);\n\n    layout->addStretch();\n\n    connect(ll_, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(layersModified()));\n}\n\nvoid FeatureEval::layersModified(){\n    if(layer_cb_ == nullptr)\n        return;\n\n    layer_cb_->clear();\n    layer_cb_->addItem(\"Select\", -1);\n\n    layer_idx_ = -1;\n\n    for(uint idx = 0; idx < ll_->getLayers().size(); idx++) {\n        boost::shared_ptr<Layer> layer = ll_->getLayers()[idx];\n        layer_cb_->addItem(layer->getName(), layer->getId());\n    }\n}\n\nvoid FeatureEval::cleanup(){\n    mw_->tooloptions_->removeWidget(settings_);\n    mw_->toolbar_->removeAction(enable_);\n    mw_->removeTab(tab_idx_);\n    delete enable_;\n    delete depth_widget_;\n}\n\nFeatureEval::~FeatureEval(){\n    if(image_ != nullptr)\n        delete image_;\n}\n\nstd::function<void()> FeatureEval::getFunction(QString name){\n    return name_to_function_[name];\n}\n\nvoid FeatureEval::setReportFuction(QDebug *dbg){\n    report_ = dbg;\n}\n\nvoid FeatureEval::reportResult(float r2, float * correl, int correl_size){\n    if(report_ == nullptr)\n        return;\n\n    *report_\n             << scan_ << \", \"\n             << layer_ << \", \"\n             << fname_ << \", \"\n             << time_ << \", \"\n             << subsample_res_ << \", \"\n             << subsample_res_2_ << \", \"\n             << search_radius_ << \", \"\n             << max_nn_ << \", \"\n             << bins_ << \", \"\n             << r2;\n\n    for(int idx = 0; idx < correl_size; idx++){\n        *report_ << \", \" << correl[idx];\n    }\n\n    *report_ << \"\\n\";\n}\n\nvoid FeatureEval::resetParams(){\n    subsample_res_ = -1;\n    subsample_res_2_ = -1;\n    search_radius_ = -1;\n    max_nn_ = -1;\n    bins_ = -1;\n}\n\nvoid FeatureEval::reportHeader(){\n    *report_ << \"\\\"scan\\\", \\\"layer\\\", \\\"feature\\\", \\\"time\\\", \\\"subsample_res_\\\", \\\"subsample_res_2_\\\", \\\"search_radius_ \\\", \\\"max_nn_\\\", \\\"bins_\\\", \\\"R^2\\\", \\\"component correlations\\\"\\n\";\n}\n\nvoid FeatureEval::enable() {\n    if(is_enabled_){\n        disable();\n        return;\n    }\n\n    mw_->options_dock_->show();\n    mw_->tooloptions_->setCurrentWidget(settings_);\n    emit enabling();\n    connect(core_, SIGNAL(endEdit()), this, SLOT(disable()));\n    is_enabled_ = true;\n}\n\nvoid FeatureEval::disable(){\n    enable_->setChecked(false);\n    disconnect(core_, SIGNAL(endEdit()), this, SLOT(disable()));\n    is_enabled_ = false;\n}\n\nint sum_calc(float * data, int vector_size, int size, float * sum, float * sum_of_squares, int stride = 0, int offset = 0){\n    stride = stride ? stride : vector_size;\n    int skipped = 0;\n    for(int j = 0; j < vector_size; j++){\n        sum[j] = 0.0f;\n        sum_of_squares[j] = 0.0f;\n    }\n\n    float val = 0;\n    for(int i = 0; i < size; i++){\n        for(int j = 0; j < vector_size; j++){\n            val = data[i*stride + j + offset];\n            if(val != val){\n                skipped++;\n                continue;\n            }\n            sum[j] += val;\n            sum_of_squares[j] += pow(val, 2);\n        }\n    }\n    return skipped;\n}\n\n// uses y value for the last row of mat\nvoid sum_productmat_calc(float * y_data, float * x_data, int x_vector_size, int size, Eigen::MatrixXf & sum_product, int stride = 0, int offset = 0){\n    stride = stride ? stride : x_vector_size;\n    sum_product.setIdentity();\n\n    float val1 = 0, val2 = 0;\n    for(int i = 0; i < size; i++){\n        for(int r = 0; r < x_vector_size; r++){\n            for(int c = r+1; c < x_vector_size; c++){\n                val1 = (x_data[i*stride + r + offset]);\n                val2 = (x_data[i*stride + c + offset]);\n\n                if(val1 != val1 || val1 != val1){\n                    continue;\n                }\n\n                sum_product(r, c) += val1*val2;\n                sum_product(c, r) = sum_product(r, c);\n            }\n\n            sum_product(r, x_vector_size) += y_data[i] * x_data[i*stride + r + offset];\n            sum_product(x_vector_size, r) = sum_product(r, x_vector_size);\n        }\n    }\n}\n\ninline float correlate(float sx, float sxx, float sy, float syy, float sxy, float n){\n    //qDebug() << \"sx: \" << sx << \"sxx: \" << sxx << \"sy: \" << sy << \"syy: \" << syy << \"sxy: \" << sxy << \"n: \" << n;\n    return (n*sxy-sx*sy)/sqrt((n*sxx-sx*sx) * (n*syy-sy*sy));\n}\n\n// blend the large segmentation to small!!!\n\n// correlate binaryish with vector\nEigen::MatrixXf  multi_correlate(std::vector<float> & y_data, float * x_data, int x_vector_size, int size, int stride, int offset){\n    std::vector<float> sum(x_vector_size + 1);\n    std::vector<float> sum_of_squares(x_vector_size + 1);\n\n    int skipped = sum_calc(x_data, x_vector_size, size, sum.data(), sum_of_squares.data(), stride, offset);\n    skipped += sum_calc(y_data.data(), 1, size, &sum[x_vector_size], &sum_of_squares[x_vector_size]);\n\n    //qDebug() << \"skipped: \" << skipped << \"size: \" << size;\n\n    Eigen::MatrixXf sum_productmat(x_vector_size + 1, x_vector_size + 1);\n    sum_productmat_calc(y_data.data(), x_data, x_vector_size, size, sum_productmat, stride, offset);\n\n    Eigen::MatrixXf correlation_mat(x_vector_size + 1, x_vector_size + 1);\n    correlation_mat.setIdentity();\n\n    for(int r = 0; r < x_vector_size + 1; r++){\n        for(int c = r+1; c < x_vector_size + 1; c++){\n            // qDebug() << r << c << \": \" <<  sum[c] << sum_of_squares[c] << sum[r] << sum_of_squares[r] << sum_productmat(r, c);\n            correlation_mat(r, c) = correlate(sum[c], sum_of_squares[c], sum[r], sum_of_squares[r], sum_productmat(r, c), size-skipped);\n            correlation_mat(c, r) = correlation_mat(r, c);\n        }\n    }\n\n    return correlation_mat;\n}\n\nstd::vector<float> get_scaled_layer_mask(\n        std::vector<uint16_t> labels_,\n        std::set<uint16_t> segment_labels,\n        std::vector<int> & big_to_small,\n        int small_size){\n\n    std::vector<float> mask(small_size, 0.0f);\n    std::vector<int> mask_count(small_size, 0);\n\n    for(uint big_idx = 0; big_idx < big_to_small.size(); big_idx++){\n        int small_idx = big_to_small[big_idx];\n        mask_count[small_idx]++;\n        uint16_t label = labels_[big_idx];\n        if(segment_labels.find(label) != segment_labels.end())\n            mask[small_idx]++;\n    }\n\n    for(int i = 0; i < small_size; i++){\n        mask[i] = mask_count[i] == 0 ? 0.0f : mask[i]/mask_count[i];\n    }\n\n    return mask;\n}\n\nint gridToCloudIdx(int x, int y, boost::shared_ptr<PointCloud> pc, int * lookup){\n    if(x < 0 || x > pc->scan_width())\n        return -1;\n    else if(y < 0 || y > pc->scan_height())\n        return -1;\n    return lookup[x + y*pc->scan_width()];\n}\n\n\nvoid FeatureEval::computeCorrelation(float * data, int vector_size, int size, std::vector<int> & big_to_small, int stride, int offset){\n\n    stride = stride ? stride : vector_size;\n\n    if(ll_->getSelection().size() == 0)\n        return;\n\n    std::set<uint16_t> labels;\n    for(boost::weak_ptr<Layer> wlayer: ll_->getSelection()){\n        for(uint16_t label : wlayer.lock()->getLabelSet())\n            labels.insert(label);\n    }\n\n    std::vector<float> layer = get_scaled_layer_mask(cl_->active_->labels_,\n                          labels,\n                          big_to_small,\n                          size);\n\n    Eigen::MatrixXf correlation_mat = multi_correlate(layer, data, vector_size, size, stride, offset);\n    Eigen::MatrixXf Rxx = correlation_mat.topLeftCorner(vector_size, vector_size);\n    Eigen::VectorXf c = correlation_mat.block(0, vector_size, vector_size, 1);\n\n    //std::cout << correlation_mat << std::endl;\n\n    float R = c.transpose() * (Rxx.inverse() * c);\n\n    qDebug() << \"R^2: \" << R;\n    //qDebug() << \"R: \" << sqrt(R);\n\n    reportResult(R, c.data(), vector_size);\n\n    //Eigen::VectorXf tmp = (Rxx.inverse() * c);\n\n    qDebug() << \"Y -> X correlation <<<<<<<<<<<<<\";\n    std::cout << c << std::endl;\n    //qDebug() << \"Coefs <<<<<<<<<<<<<\";\n    //std::cout << tmp << std::endl;\n\n}\n\n\nvoid FeatureEval::drawFloats(boost::shared_ptr<const std::vector<float> > out_img, boost::shared_ptr<PointCloud> cloud){\n    if(!visualise_on_)\n        return;\n\n    qDebug() << \"DRAW!\";\n    // translates grid idx to cloud idx\n    boost::shared_ptr<const std::vector<int>> lookup = cloud->gridToCloudMap();\n\n    if(image_ != nullptr)\n        delete image_;\n    image_ = new QImage(cloud->scan_width(), cloud->scan_height(), QImage::Format_Indexed8);\n\n    for(int i = 0; i < 256; i++) {\n        image_->setColor(i, qRgb(i, i, i));\n    }\n\n    float min, max;\n    min_max(*out_img, min, max);\n    qDebug() << \"Minmax\" << min << max;\n\n    // Draw image\n    auto select = boost::make_shared<std::vector<int> >();\n    for(int y = 0; y < cloud->scan_height(); y++){\n        for(int x = 0; x < cloud->scan_width(); x++){\n            int i = (cloud->scan_height() -1 - y) + x * cloud->scan_height();\n\n            // Mask disabled\n            if(lookup->at(i) == -2) {\n                image_->setPixel(x, y, 0);\n                continue;\n            }\n\n            //int intensity = 255 * (1 - distmap[i]/max_dist);\n            float mag = (*out_img)[i];\n            //int intensity = 255 * (1 - (mag - min)/(max - min));\n\n            int intensity = 255 * (mag - min)/(max - min);\n\n            if(intensity > 255 || intensity < 0) {\n                qDebug() << \"Nope, sorry > 255 || < 0: \" << mag;\n                qDebug() << \"Mag: \" << mag;\n                qDebug() << \"Intensity\" << intensity;\n                return;\n            }\n\n/*\n            // Select\n            if(lookup->at(i) != -1 && intensity > 100) {\n                select->push_back(lookup->at(i));\n            }\n\n            if(intensity < 40) {\n                intensity = 0;\n            } else {\n                intensity = 255;\n            }\n*/\n            image_->setPixel(x, y, intensity);\n        }\n    }\n\n    qDebug() << \"Done\";\n\n    core_->us_->beginMacro(\"Experiment\");\n    core_->us_->push(new Select(cloud, select));\n    core_->us_->endMacro();\n    qDebug() << \"Done1\";\n    image_container_->setPixmap(QPixmap::fromImage(*image_));\n    qDebug() << \"Done1.1\";\n    image_container_->resize(image_->size());\n    qDebug() << \"Done 2\";\n\n}\n\nvoid FeatureEval::drawVector3f(boost::shared_ptr<const std::vector<Eigen::Vector3f> > out_img, boost::shared_ptr<PointCloud> cloud){\n    if(!visualise_on_)\n        return;\n\n    // translates grid idx to cloud idx\n    boost::shared_ptr<const std::vector<int>> lookup = cloud->gridToCloudMap();\n\n    if(image_ != nullptr)\n        delete image_;\n    image_ = new QImage(cloud->scan_width(), cloud->scan_height(), QImage::Format_RGB32);\n\n    // Draw image\n    for(int y = 0; y < cloud->scan_height(); y++){\n        for(int x = 0; x < cloud->scan_width(); x++){\n            int i = (cloud->scan_height() -1 - y) + x * cloud->scan_height();\n\n            // Mask disabled\n            if(lookup->at(i) == -2) {\n                image_->setPixel(x, y, 0);\n                continue;\n            }\n\n            int r = (*out_img)[i][0] * 255;\n            int g = (*out_img)[i][1] * 255;\n            int b = (*out_img)[i][2] * 255;\n\n            QRgb value = qRgb(r, g, b);\n\n            image_->setPixel(x, y, value);\n        }\n    }\n\n\n    image_container_->setPixmap(QPixmap::fromImage(*image_));\n    image_container_->resize(image_->size());\n}\n\n// Kullback-Leibler distance\n\ninline double KLDist(float * feature1, float * feature2, int size) {\n    double kl = 0;\n\n    for(int i = 0; i < size; i++){\n        float p = feature1[i];\n        float q = feature2[i];\n        double tmp = p*log(p/q);\n\n        if(tmp != tmp || tmp >= FLT_MAX || tmp <= FLT_MIN)\n            continue;\n        kl += tmp;\n    }\n\n    /*\n    for(int i = 0; i < size; i++){\n        std::cout << feature1[i] << \"/\" << feature2[i] << \" \";\n    }\n\n    std::cout << std::endl << \"feature:\" << kl << std::endl;\n    fflush(stdout);\n    */\n    return kl;\n}\n\ninline float EuclidianDist(float * feature1, float * feature2, int size) {\n    float dist = 0;\n\n    for(int i = 0; i < size; i++){\n        dist += pow(feature1[i] - feature2[i], 2.0);\n    }\n\n    dist = sqrt(dist);\n\n    if(dist != dist || dist >= FLT_MAX || dist <= FLT_MIN) {\n        return 0;\n    }\n\n    return dist;\n}\n\npcl::PointCloud<pcl::PointXYZINormal>::Ptr zipNormals(\n        pcl::PointCloud<pcl::PointXYZI> & cloud,\n        pcl::PointCloud<pcl::Normal> & normals){\n\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr zipped (new pcl::PointCloud<pcl::PointXYZINormal>());\n    zipped->resize(cloud.size());\n\n    for(uint i = 0; i < cloud.size(); i ++){\n        pcl::PointXYZI & p = cloud[i];\n        pcl::Normal & n = normals[i];\n\n        pcl::PointXYZINormal & pn = (*zipped)[i];\n        pn.getNormalVector4fMap() = n.getNormalVector4fMap();\n        pn.getVector4fMap() = p.getVector4fMap();\n        pn.intensity = p.intensity;\n    }\n\n    return zipped;\n}\n\npcl::PointCloud<pcl::PointXYZINormal>::Ptr FeatureEval::gridDownsample(boost::shared_ptr<PointCloud> input, float resolution, std::vector<int>& sub_idxs) {\n    pcl::PointCloud<pcl::Normal>::Ptr normals = ne_->getNormals(input);\n\n    // HACK: Make sure normals are not NaN or inf\n    for (pcl::Normal & n : *normals) {\n      if (!pcl::isFinite<pcl::Normal>(n)){\n          n.normal_x = 0;\n          n.normal_y = 0;\n          n.normal_z = 1;\n      }\n    }\n\n\n    // Zipper up normals and xyzi\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr cloud = zipNormals(*input, *normals);\n\n    t_.start(); //qDebug() << \"Timer started (Subsample)\";\n    /////////////////////////\n\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr output(new pcl::PointCloud<pcl::PointXYZINormal>());\n    sub_idxs.resize(input->size(), 0);\n\n    pcl::VoxelGrid<pcl::PointXYZINormal> sor;\n    sor.setInputCloud(cloud);\n    sor.setLeafSize(resolution, resolution, resolution);\n    sor.setDownsampleAllData (true);\n    sor.setSaveLeafLayout(true);\n    sor.filter(*output);\n\n\n    for(uint i = 0; i < input->size(); i++) {\n        pcl::PointXYZINormal &p = (*cloud)[i];\n        int idx = sor.getCentroidIndex(p);\n        sub_idxs[i] = idx;\n    }\n\n\n    /////////////////////////\n    time = t_.elapsed();\n\n    return output;\n\n}\n\npcl::PointCloud<pcl::PointXYZINormal>::Ptr FeatureEval::downsample(\n        boost::shared_ptr<PointCloud> input,\n        float resolution,\n        std::vector<int>& sub_idxs){\n\n    pcl::PointCloud<pcl::Normal>::Ptr normals = ne_->getNormals(input);\n\n    // HACK: Make sure normals are not NaN or inf\n    for (pcl::Normal & n : *normals) {\n      if (!pcl::isFinite<pcl::Normal>(n)){\n          n.getNormalVector3fMap() << 0, 0, 1;\n      }\n    }\n\n    // Zipper up normals and xyzi\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr cloud = zipNormals(*input, *normals);\n\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr output = octreeDownsample(cloud.get(), subsample_res_, sub_idxs);\n\n    return output;\n\n}\n\n\ntemplate<typename PointT, typename NormalT>\npcl::PointCloud<pcl::Normal>::Ptr don(\n        pcl::PointCloud<PointT> & cloud,\n        pcl::PointCloud<NormalT> & normals, float radius1 = 0.2,\n        float radius2 = 0.5){\n\n    pcl::PointCloud<pcl::Normal>::Ptr donormals;\n    donormals.reset(new pcl::PointCloud<pcl::Normal>());\n    donormals->resize(cloud.size());\n\n    typename pcl::search::Search<PointT>::Ptr tree;\n    tree.reset (new pcl::search::KdTree<PointT> (false));\n\n    typename pcl::PointCloud<PointT>::ConstPtr cptr(&cloud, boost::serialization::null_deleter());\n    tree->setInputCloud(cptr);\n\n    std::vector<int> idxs;\n    std::vector<float> sq_dists;\n\n    auto avg_normal = [] (std::vector<int> idxs, pcl::PointCloud<NormalT> & normals) {\n        pcl::Normal sum;\n        for(int idx : idxs) {\n            sum.getNormalVector3fMap() += normals[idx].getNormalVector3fMap();\n        }\n        sum.getNormalVector3fMap() /= idxs.size();\n        return sum;\n    };\n\n    for(uint idx = 0; idx < cloud.size(); idx++){\n        std::vector<float> rads;\n        rads.push_back(radius1);\n        rads.push_back(radius2);\n        std::vector<pcl::Normal> avgs;\n        for(float rad : rads){\n            idxs.clear();\n            sq_dists.clear();\n            tree->radiusSearch(idx, rad, idxs, sq_dists);\n            idxs.push_back(idx);\n            avgs.push_back(avg_normal(idxs, normals));\n        }\n\n        (*donormals)[idx].getNormalVector3fMap() = (avgs[0].getNormalVector3fMap() - avgs[1].getNormalVector3fMap())/2.0;\n    }\n\n    return donormals;\n}\n\nvoid FeatureEval::difference_of_normals(){\n    boost::shared_ptr<PointCloud> _cloud = core_->cl_->active_;\n    if(_cloud == nullptr)\n        return;\n\n    int w = _cloud->scan_width();\n    int h = _cloud->scan_height();\n\n    pcl::PointCloud<pcl::Normal>::Ptr normals = ne_->getNormals(_cloud);\n\n    float res1 = subsample_res_;\n    float res2 = subsample_res_2_;\n\n    // Downsample\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr smaller_cloud;\n    std::vector<int> sub_idxs;\n    smaller_cloud = downsample(_cloud, res1, sub_idxs);\n\n    t_.start();\n    pcl::PointCloud<pcl::Normal>::Ptr donormals = don(*smaller_cloud, *smaller_cloud, res1, res2);\n    (time_ = t_.elapsed());\n\n    // Correlate\n    computeCorrelation(reinterpret_cast<float*>(donormals->points.data()), 3, donormals->points.size(), sub_idxs, 4);\n    if(!visualise_on_) return;\n\n    // Draw\n    pcl::PointCloud<pcl::Normal> big_donormals;\n    map_small_to_big((*donormals).points, big_donormals.points, sub_idxs);\n\n    const std::vector<int> & cloudtogrid = _cloud->cloudToGridMap();\n\n    boost::shared_ptr<std::vector<Eigen::Vector3f> > grid = boost::make_shared<std::vector<Eigen::Vector3f> >(w*h, Eigen::Vector3f(0.0f, 0.0f, 0.0f));\n    for(uint i = 0; i < normals->size(); i++){\n        int grid_idx = cloudtogrid[i];\n        (*grid)[grid_idx] = big_donormals[i].getNormalVector3fMap();\n    }\n\n    // Draw\n    drawVector3f(grid, _cloud);\n}\n\nvoid FeatureEval::intensity(){\n    boost::shared_ptr<PointCloud> _cloud = core_->cl_->active_;\n    if(_cloud == nullptr)\n        return;\n\n    // Subsample\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr smaller_cloud;\n    std::vector<int> sub_idxs;\n    smaller_cloud = downsample(_cloud, subsample_res_, sub_idxs);\n\n    time_ = 0;\n\n    // Copy to contigious structure\n    std::vector<float> tmp(smaller_cloud->size());\n    for(uint i = 0; i < smaller_cloud->size(); i++){\n        tmp[i] = smaller_cloud->points[i].intensity;\n    }\n\n    // Correlate\n    computeCorrelation(reinterpret_cast<float*>(tmp.data()), 1, tmp.size(), sub_idxs);\n}\n\nvoid FeatureEval::intensity_histogram(){\n    boost::shared_ptr<PointCloud> _cloud = core_->cl_->active_;\n    if(_cloud == nullptr)\n        return;\n\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr smaller_cloud;\n    std::vector<int> sub_idxs;\n    smaller_cloud = downsample(_cloud, subsample_res_, sub_idxs);\n\n    // Compute\n    t_.start(); qDebug() << \"Timer started (Intensity histogram)\";\n    boost::shared_ptr<std::vector<std::vector<float> > > hists = calcIntensityHist(*smaller_cloud, bins_, search_radius_, max_nn_);\n    qDebug() << \"Intensity histogram\" << (time_ = t_.elapsed()) << \" ms\";\n\n    // Copy to contigious structure\n    std::vector<float> tmp(bins_*smaller_cloud->size());\n    for(uint i = 0; i < smaller_cloud->size(); i++){\n        for(int j = 0; j < bins_; j++){\n            tmp[i*bins_+j] = (*hists)[i][j];\n        }\n    }\n\n    // Correlate\n    computeCorrelation(tmp.data(), bins_, tmp.size(), sub_idxs);\n    if(!visualise_on_) return;\n\n    // Draw, TODO; Multidimentional draw\n    boost::shared_ptr<std::vector<std::vector<float> > > hists2 = boost::make_shared<std::vector<std::vector<float> > >(_cloud->size());\n\n    // map back to cloud\n    for(uint i = 0; i < _cloud->size(); i++) {\n        int idx = sub_idxs[i];\n        (*hists2)[i] = (*hists)[idx];\n    }\n\n    hists.reset();\n\n    boost::shared_ptr<const std::vector<int>> grid_to_cloud = _cloud->gridToCloudMap();\n\n    int w = _cloud->scan_width();\n    int h = _cloud->scan_height();\n\n    // in the grid, subtract (x, y+1) from every (x, y)\n    boost::shared_ptr<std::vector<float>> diffs = boost::make_shared<std::vector<float>>(w*h, 0.0f);\n\n    //auto distfunc = EuclidianDist;\n    auto distfunc = KLDist;\n\n    /*\n    // Lambda\n    auto maxval = [] (float * array, int size) {\n        float max = FLT_MIN;\n        for(int i = 0; i < size; i++) {\n            if(array[i] > max)\n                max = array[i];\n        }\n        return max;\n    };\n    */\n\n    const int feature_size = bins_;\n\n    for(int x = 1; x < w-1; x ++) {\n        //qDebug() << \"yes\";\n        for(int y = 1; y < h-1; y ++) {\n            int center = (*grid_to_cloud)[x*h + y];\n            int up = (*grid_to_cloud)[x*h + y-1];\n            int down = (*grid_to_cloud)[x*h + y+1];\n            int left = (*grid_to_cloud)[(x-1)*h + y];\n            int right = (*grid_to_cloud)[(x+1)*h + y];\n\n\n            (*diffs)[center] = 0;\n\n            if(center == -1){\n                continue;\n            }\n\n            // NB! assumed histograms are normalised\n\n            if(up != -1 && down != -1){\n                float * feature1 = &((*hists2)[up][0]);\n                float * feature2 = &((*hists2)[down][0]);\n                //float max1 = maxval(feature1, feature_size);\n                //float max2 = maxval(feature2, feature_size);\n                //(*diffs)[center] += fabs(max1 - max2);\n                (*diffs)[center] += distfunc(feature1, feature2, feature_size);\n            }\n\n            if(left != -1 && right != -1){\n                float * feature1 = &((*hists2)[left][0]);\n                float * feature2 = &((*hists2)[right][0]);\n                //float max1 = maxval(feature1, feature_size);\n                //float max2 = maxval(feature2, feature_size);\n                //(*diffs)[center] += fabs(max1 - max2);\n                (*diffs)[center] += distfunc(feature1, feature2, feature_size);\n            }\n\n        }\n    }\n\n    boost::shared_ptr<const std::vector<float>> img = cloudToGrid(_cloud->cloudToGridMap(), w*h, diffs);\n\n    drawFloats(img, _cloud);\n    hists2.reset();\n}\n\nvoid FeatureEval::fast_point_feature_histogram(){\n    qDebug() << \"params used: \" << subsample_res_ << search_radius_;\n    qDebug() << \"-----------------------------------\";\n    boost::shared_ptr<PointCloud> _cloud = core_->cl_->active_;\n    if(_cloud == nullptr)\n        return;\n\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr filt_cloud;\n    std::vector<int> sub_idxs;\n    filt_cloud = downsample(_cloud, subsample_res_, sub_idxs);\n\n    // Compute\n    t_.start(); qDebug() << \"Timer started (FPFH)\";\n    pcl::FPFHEstimation<pcl::PointXYZINormal, pcl::PointXYZINormal, pcl::FPFHSignature33> fpfh;\n    fpfh.setInputCloud(filt_cloud);\n    fpfh.setInputNormals(filt_cloud);\n    pcl::search::KdTree<pcl::PointXYZINormal>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZINormal>);\n    fpfh.setSearchMethod(tree);\n    fpfh.setRadiusSearch(search_radius_);\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs (new pcl::PointCloud<pcl::FPFHSignature33> ());\n    fpfh.compute(*fpfhs);\n    qDebug() << \"FPFH in \" << (time_ = t_.elapsed()) << \" ms\";\n\n    // Correlate\n    computeCorrelation(reinterpret_cast<float*>(fpfhs->points.data()), 33, fpfhs->points.size(), sub_idxs);\n    if(!visualise_on_) return;\n}\n\nvoid FeatureEval::curvature(){\n    boost::shared_ptr<PointCloud> _cloud = core_->cl_->active_;\n    if(_cloud == nullptr)\n        return;\n\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr filt_cloud;\n    std::vector<int> big_to_small;\n    filt_cloud = downsample(_cloud, subsample_res_, big_to_small);\n\n    // Compute\n    t_.start(); qDebug() << \"Timer started (Curvature)\";\n\n    pcl::PrincipalCurvaturesEstimation<pcl::PointXYZINormal, pcl::PointXYZINormal, pcl::PrincipalCurvatures> principal_curvatures_estimation;\n    principal_curvatures_estimation.setInputCloud (filt_cloud);\n    principal_curvatures_estimation.setInputNormals (filt_cloud);\n    pcl::search::KdTree<pcl::PointXYZINormal>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZINormal>);\n    principal_curvatures_estimation.setSearchMethod (tree);\n    principal_curvatures_estimation.setRadiusSearch (search_radius_);\n    pcl::PointCloud<pcl::PrincipalCurvatures>::Ptr principal_curvatures (new pcl::PointCloud<pcl::PrincipalCurvatures> ());\n    principal_curvatures_estimation.compute (*principal_curvatures);\n    qDebug() << \"Curvature in \" << (time_ = t_.elapsed()) << \" ms\";\n\n    // Correlate\n    size_t csize = sizeof(pcl::PrincipalCurvatures)/sizeof(float);\n    computeCorrelation(reinterpret_cast<float*>(principal_curvatures->points.data()), 2, principal_curvatures->points.size(), big_to_small, csize, 3);\n    if(!visualise_on_) return;\n\n    // Draw\n    int w = _cloud->scan_width();\n    int h = _cloud->scan_height();\n\n    boost::shared_ptr<std::vector<float>> grid = boost::make_shared<std::vector<float>>(w*h, 0.0f);\n    const std::vector<int> & cloudtogrid = _cloud->cloudToGridMap();\n\n    for(uint big_idx = 0; big_idx < _cloud->size(); big_idx++) {\n        int small_idx = big_to_small[big_idx];\n        int grid_idx = cloudtogrid[big_idx];\n        pcl::PrincipalCurvatures & pc = (*principal_curvatures)[small_idx];\n        (*grid)[grid_idx] = pc.pc1 + pc.pc2;\n    }\n\n    drawFloats(grid, _cloud);\n\n}\n\nvoid FeatureEval::normal_standard_deviation(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n\n    pcl::PointCloud<pcl::Normal>::Ptr normals = ne_->getNormals(cloud);\n\n    // Downsample and zipper up normals and xyzi\n    std::vector<int> sub_idxs;\n    pcl::PointCloud<pcl::PointXYZINormal>::Ptr smaller_cloud = zipNormals(cloud, normals);\n    smaller_cloud = octreeDownsample(smaller_cloud.get(), subsample_res_, sub_idxs);\n\n    // Compute\n    t_.start(); qDebug() << \"Timer started (Normal stdev)\";\n    boost::shared_ptr<std::vector<float>> stdev = normal_stdev<pcl::PointXYZINormal, pcl::PointXYZINormal>(smaller_cloud, smaller_cloud, search_radius_, max_nn_);\n    qDebug() << \"Normal stdev in \" << (time_ = t_.elapsed()) << \" ms\";\n\n    // Correlate\n    computeCorrelation(stdev->data(), 1, stdev->size(), sub_idxs);\n    if(!visualise_on_) return;\n\n    // Draw\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n\n    boost::shared_ptr<std::vector<float>> grid = boost::make_shared<std::vector<float>>(w*h, 0.0f);\n    const std::vector<int> & cloudtogrid = cloud->cloudToGridMap();\n\n    for(uint big_idx = 0; big_idx < cloud->size(); big_idx++) {\n        int small_idx = sub_idxs[big_idx];\n        int grid_idx = cloudtogrid[big_idx];\n        (*grid)[grid_idx] = (*stdev)[small_idx];\n    }\n    drawFloats(grid, cloud);\n}\n\n\nvoid FeatureEval::distance_standard_deviation(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n\n    // Downsample\n    std::vector<int> sub_idxs;\n    pcl::PointCloud<pcl::PointXYZI>::Ptr smaller_cloud = octreeDownsample(cloud.get(), subsample_res_, sub_idxs);\n\n    t_.start(); qDebug() << \"Timer started (Dist stdev)\";\n    boost::shared_ptr<std::vector<float> > stdev = stdev_dist(smaller_cloud, search_radius_, max_nn_, false);\n    qDebug() << \"Dist stdev in \" << t_.elapsed() << \" ms\";\n\n    // Correlate\n    computeCorrelation(stdev->data(), 1, stdev->size(), sub_idxs);\n    if(!visualise_on_) return;\n\n    // Draw\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n\n    boost::shared_ptr<std::vector<float>> grid = boost::make_shared<std::vector<float>>(w*h, 0.0f);\n    const std::vector<int> & cloudtogrid = cloud->cloudToGridMap();\n\n    for(uint big_idx = 0; big_idx < cloud->size(); big_idx++) {\n        int small_idx = sub_idxs[big_idx];\n        int grid_idx = cloudtogrid[big_idx];\n        (*grid)[grid_idx] = (*stdev)[small_idx];\n    }\n\n    drawFloats(grid, cloud);\n}\n\n// TODO: THIS IS A 2D FEATURE CALCULATION! help!\n// Compute the distance for each point\n// Gaussian weighted average in neighbourhood\n// Subtract\nvoid FeatureEval::difference_of_gaussian_distances(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n\n    // Create distance map\n    boost::shared_ptr<std::vector<float>> distmap = makeDistmap(cloud);\n\n    //distmap = interpolate(distmap, w, h, 21);\n\n    boost::shared_ptr<std::vector<float> > smooth_grad_image = convolve(distmap, w, h, gaussian, 5);\n    smooth_grad_image = convolve(smooth_grad_image, w, h, gaussian, 5);\n    smooth_grad_image = convolve(smooth_grad_image, w, h, gaussian, 5);\n    smooth_grad_image = convolve(smooth_grad_image, w, h, gaussian, 5);\n\n    boost::shared_ptr<std::vector<float>> highfreq = distmap;\n\n    for(uint i = 0; i < distmap->size(); i++){\n        (*highfreq)[i] = (*distmap)[i] - (*smooth_grad_image)[i];\n    }\n\n    drawFloats(highfreq, cloud);\n}\n\n// PCA for each point, ratio of eigen values\nvoid FeatureEval::pca_eigen_value_ratio(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n\n    // Downsample\n    std::vector<int> sub_idxs;\n    pcl::PointCloud<pcl::PointXYZI>::Ptr smaller_cloud = octreeDownsample(cloud.get(), subsample_res_, sub_idxs);\n\n    // Compute PCA\n    t_.start(); qDebug() << \"Timer started (PCA and speculaion)\";\n    boost::shared_ptr<std::vector<Eigen::Vector3f> > pca = getPCA(smaller_cloud.get(), search_radius_, max_nn_);\n\n\n    // Compute ratio\n    boost::shared_ptr<std::vector<float>> likely_veg =\n               boost::make_shared<std::vector<float>>(pca->size(), 0.0f);\n\n    for(uint i = 0; i < pca->size(); i++) {\n        Eigen::Vector3f eig = (*pca)[i];\n\n        // Not enough neighbours\n        if(eig[1] < eig[2]) {\n            (*likely_veg)[i] = 0;\n            continue;\n        }\n\n        /*\n        float eig_sum = eig.sum();\n        eig /= eig_sum;\n        float fudge_factor = 5.0f;\n\n        bool is_planar = eig[1] < 0.05 * fudge_factor || eig[2] < 0.01 * fudge_factor;\n\n        if(!is_planar) {\n            (*likely_veg)[i] = 0;\n        } else {\n            (*likely_veg)[i] = 1;\n        }\n\n        */\n\n        float curvature;\n        if(eig[0] > eig[2])\n            curvature = eig[1] / (eig[0]);\n        else\n            curvature = 1;\n\n\n        (*likely_veg)[i] = curvature;\n\n    }\n\n    qDebug() << \"PCA in \" << (time_ = t_.elapsed()) << \" ms\";\n\n    computeCorrelation(likely_veg->data(), 1, likely_veg->size(), sub_idxs);\n    if(!visualise_on_) return;\n\n    // Draw\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n\n    boost::shared_ptr<std::vector<float>> likely_veg2 =\n               boost::make_shared<std::vector<float>>(cloud->size(), 0.0f);\n\n\n    for(uint i = 0; i < cloud->size(); i++) {\n        uint subidx = sub_idxs[i];\n        (*likely_veg2)[i] = (*likely_veg)[subidx];\n    }\n\n\n    boost::shared_ptr<const std::vector<float>> img = cloudToGrid(cloud->cloudToGridMap(), w*h, likely_veg2);\n\n    drawFloats(img, cloud);\n}\n\nvoid FeatureEval::pca(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n\n    std::vector<int> sub_idxs;\n    pcl::PointCloud<pcl::PointXYZI>::Ptr smaller_cloud = octreeDownsample(cloud.get(), subsample_res_, sub_idxs);\n\n    t_.start(); qDebug() << \"Timer started (PCA)\";\n    boost::shared_ptr<std::vector<Eigen::Vector3f> > pca = getPCA(smaller_cloud.get(), search_radius_, max_nn_);\n    qDebug() << \"PCA in \" << (time_ = t_.elapsed()) << \" ms\";\n\n\n    computeCorrelation(reinterpret_cast<float *>(pca->data()), 3, pca->size(), sub_idxs, sizeof(Eigen::Vector3f)/sizeof(float));\n    if(!visualise_on_) return;\n\n//    // Draw\n//    boost::shared_ptr<std::vector<Eigen::Vector3f> > grid = boost::make_shared<std::vector<Eigen::Vector3f> >(grid_to_cloud->size(), Eigen::Vector3f(0.0f, 0.0f, 0.0f));\n//    for(int i = 0; i < grid_to_cloud->size(); i++) {\n//        int idx = (*grid_to_cloud)[i];\n//        if(idx != -1)\n//            (*grid)[i] = (*pca)[idx];\n//    }\n\n//    drawVector3f(grid, cloud);\n\n\n}\n\nvoid FeatureEval::eigen_plane_consine_similarity(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n\n    std::vector<int> sub_idxs;\n    pcl::PointCloud<pcl::PointXYZI>::Ptr smaller_cloud = octreeDownsample(cloud.get(), subsample_res_, sub_idxs);\n\n    t_.start(); qDebug() << \"Timer started (eigen_plane_consine_similarity)\";\n    boost::shared_ptr<std::vector<Eigen::Vector3f> > pca = getPCA(smaller_cloud.get(), 0.05f, 20);\n\n    boost::shared_ptr<std::vector<float>> plane_likelyhood =\n               boost::make_shared<std::vector<float>>(pca->size(), 0.0f);\n\n    Eigen::Vector3f ideal_plane(1.0f, 0.0f, 0.0f);\n    ideal_plane.normalize();\n\n    for(uint i = 0; i < pca->size(); i++) {\n        Eigen::Vector3f & val = (*pca)[i];\n\n        // Not enough neighbours\n        if(val[1] < val[2]) {\n            (*plane_likelyhood)[i] = 0;\n            continue;\n        }\n\n        float similarity = cosine(val, ideal_plane);\n        (*plane_likelyhood)[i] = similarity;\n    }\n\n    qDebug() << \"eigen_plane_consine_similarity in \" << (time_ = t_.elapsed()) << \" ms\";\n\n    // Correlate\n    computeCorrelation(plane_likelyhood->data(), 1, plane_likelyhood->size(), sub_idxs);\n    if(!visualise_on_) return;\n\n    // Draw\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n/*\n    boost::shared_ptr<std::vector<Eigen::Vector3f> > grid = boost::make_shared<std::vector<Eigen::Vector3f> >(grid_to_cloud->size(), Eigen::Vector3f(0.0f, 0.0f, 0.0f));\n    for(int i = 0; i < grid_to_cloud->size(); i++) {\n        int idx = (*grid_to_cloud)[i];\n        if(idx != -1)\n            (*grid)[i] = (*pca)[idx];\n    }\n\n    drawVector3f(grid, cloud);\n*/\n\n    boost::shared_ptr<const std::vector<float>> img = cloudToGrid(cloud->cloudToGridMap(), w*h, plane_likelyhood);\n\n    drawFloats(img, cloud);\n}\n\nvoid FeatureEval::sobel_erode(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n\n    // Create distance map\n    boost::shared_ptr<std::vector<float>> distmap = makeDistmap(cloud);\n\n    boost::shared_ptr<std::vector<float> > grad_image = gradientImage(distmap, w, h);\n    boost::shared_ptr<std::vector<float> > smooth_grad_image = convolve(grad_image, w, h, gaussian, 5);\n\n    // Threshold && Erode\n\n    const int strct[] = {\n        0, 1, 0,\n        1, 0, 1,\n        0, 1, 0,\n    };\n\n    boost::shared_ptr<std::vector<float> > dilated_image =  morphology(\n            smooth_grad_image,\n            w, h, strct, 3, Morphology::ERODE,\n            grad_image); // <-- reuse\n\n    drawFloats(dilated_image, cloud);\n}\n\nvoid FeatureEval::sobel_blur(){\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n\n    // Create distance map\n    boost::shared_ptr<std::vector<float>> distmap = makeDistmap(cloud);\n\n    boost::shared_ptr<std::vector<float> > smooth_grad_image = gradientImage(distmap, w, h);\n    int blurs = 0;\n    for(int i = 0; i < blurs; i++)\n        smooth_grad_image = convolve(smooth_grad_image, w, h, gaussian, 5);\n\n    drawFloats(smooth_grad_image, cloud);\n}\n\nvoid FeatureEval::blurred_intensity() {\n    boost::shared_ptr<PointCloud> cloud = core_->cl_->active_;\n    if(cloud == nullptr)\n        return;\n    int h = cloud->scan_width();\n    int w = cloud->scan_height();\n\n    boost::shared_ptr<std::vector<float>> intensity = boost::make_shared<std::vector<float>>(cloud->size());\n\n    // Create intensity cloud\n    for(uint i = 0; i < intensity->size(); i++){\n        (*intensity)[i] = (*cloud)[i].intensity;\n    }\n\n    boost::shared_ptr<std::vector<float>> img = cloudToGrid(cloud->cloudToGridMap(), w*h, intensity);\n\n\n    boost::shared_ptr<std::vector<float> > smooth_grad_image = convolve(img, w, h, gaussian, 5);\n    smooth_grad_image = convolve(smooth_grad_image, w, h, gaussian, 5);\n    smooth_grad_image = convolve(smooth_grad_image, w, h, gaussian, 5);\n    smooth_grad_image = convolve(smooth_grad_image, w, h, gaussian, 5);\n/*\n    boost::shared_ptr<std::vector<float>> highfreq = img;\n\n    for(int i = 0; i < highfreq->size(); i++){\n        (*highfreq)[i] = (*highfreq)[i] - (*smooth_grad_image)[i];\n    }\n\n    drawFloats(highfreq, cloud);\n*/\n    drawFloats(smooth_grad_image, cloud);\n\n}\n\nQ_PLUGIN_METADATA(IID \"za.co.circlingthesun.cloudclean.featureeval\")\n", "meta": {"hexsha": "a9decfad2bd479e73f8bad14796315f0d898d4aa", "size": 43476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/featureeval/featureeval.cpp", "max_stars_repo_name": "circlingthesun/cloudclean", "max_stars_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-18T16:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T01:52:24.000Z", "max_issues_repo_path": "src/plugins/featureeval/featureeval.cpp", "max_issues_repo_name": "circlingthesun/cloudclean", "max_issues_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/featureeval/featureeval.cpp", "max_forks_repo_name": "circlingthesun/cloudclean", "max_forks_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:39:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T13:13:48.000Z", "avg_line_length": 32.7133182844, "max_line_length": 187, "alphanum_fraction": 0.6138559205, "num_tokens": 11744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.025957354937269382, "lm_q1q2_score": 0.012370747158539827}}
{"text": "// SPDX-License-Identifier: NASA-1.3\n/*******************************************************************************\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 <optional>\n#include <utility>\n#include <vector>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/functional/hash.hpp>\n\n#include \"crab/variable.hpp\"\n#include \"crab_utils/patricia_trees.hpp\"\n\nnamespace crab {\n\nclass linear_expression_t final {\n  private:\n    using map_t = boost::container::flat_map<variable_t, number_t>;\n    using pair_t = typename map_t::value_type;\n\n    const map_t _map;\n    const number_t _cst = 0;\n\n    linear_expression_t(map_t map, number_t cst) : _map(std::move(map)), _cst(std::move(cst)) {}\n\n    static void add(map_t& map, variable_t x, const number_t& n) {\n        typename map_t::iterator it = map.find(x);\n        if (it != map.end()) {\n            number_t r = it->second + n;\n            if (r == 0) {\n                map.erase(it);\n            } else {\n                it->second = r;\n            }\n        } else {\n            if (n != 0) {\n                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() = default;\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) : _cst(std::move(n)) {}\n\n    linear_expression_t(signed long long int n) : _cst(number_t(n)) {}\n\n    linear_expression_t(variable_t x) : _map{ {x, number_t(1)} } {\n    }\n\n    linear_expression_t(const number_t& n, variable_t x) : _map{ {x, n} } {\n    }\n\n    [[nodiscard]] const_iterator begin() const { return this->_map.begin(); }\n\n    [[nodiscard]] const_iterator end() const { return this->_map.end(); }\n\n    [[nodiscard]] 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    [[nodiscard]] bool equal(const linear_expression_t& o) const {\n        if (is_constant()) {\n            return o.is_constant() && constant() == o.constant();\n        }\n        if (constant() != o.constant() || size() != o.size()) {\n            return false;\n        }\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    [[nodiscard]] bool is_constant() const { return (this->_map.empty()); }\n\n    [[nodiscard]] number_t constant() const { return this->_cst; }\n\n    [[nodiscard]] 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    linear_expression_t operator+(const number_t& 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 { return this->operator+(number_t(n)); }\n\n    linear_expression_t operator+(variable_t x) const {\n        map_t map = this->_map;\n        add(map, x, number_t(1));\n        return linear_expression_t(map, this->_cst);\n    }\n\n    linear_expression_t operator+(const linear_expression_t& e) const {\n        map_t map = this->_map;\n        for (auto [k, v] : e._map) {\n            add(map, k, v);\n        }\n        return linear_expression_t(map, this->_cst + e._cst);\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        map_t map = this->_map;\n        add(map, x, number_t(-1));\n        return linear_expression_t(map, this->_cst);\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        map_t map = this->_map;\n        for (auto [k ,v] : e._map) {\n            add(map, k, -v);\n        }\n        return linear_expression_t(map, this->_cst - e._cst);\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_t map;\n            for (auto [k, v] : _map) {\n                number_t c = n * v;\n                if (c != 0) {\n                    map.insert(pair_t(k, 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    friend std::ostream& operator<<(std::ostream& o, const linear_expression_t& e) {\n        bool start = true;\n        for (auto [v, n] : e) {\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 (e._cst > 0 && !e._map.empty()) {\n            o << \"+\";\n        }\n        if (e._cst != 0 || e._map.empty()) {\n            o << e._cst;\n        }\n        return o;\n    }\n}; // class linear_expression_t\n\ninline std::size_t hash_value(const linear_expression_t& e) { return e.hash(); }\n\nenum class cst_kind { EQUALITY, DISEQUATION, INEQUALITY, STRICT_INEQUALITY };\n\nclass linear_constraint_t final {\n\n  public:\n    using iterator = typename linear_expression_t::iterator;\n    using const_iterator = typename linear_expression_t::const_iterator;\n\n  private:\n    const cst_kind _kind;\n    const 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    const 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, cst_kind kind)\n        : _kind(kind), _expr(std::move(expr)), _signedness(true) {}\n\n    linear_constraint_t(linear_expression_t expr, cst_kind kind, bool signedness)\n        : _kind(kind), _expr(std::move(expr)), _signedness(signedness) {\n        if (_kind != cst_kind::INEQUALITY && _kind != cst_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)), cst_kind::EQUALITY);\n        return res;\n    }\n\n    static linear_constraint_t get_false() {\n        linear_constraint_t res(linear_expression_t(number_t(0)), cst_kind::DISEQUATION);\n        return res;\n    }\n\n    [[nodiscard]] bool is_tautology() const {\n        if (!this->_expr.is_constant())\n            return false;\n        const number_t c = this->_expr.constant();\n        switch (this->_kind) {\n        case cst_kind::DISEQUATION: return c != 0;\n        case cst_kind::EQUALITY: return c == 0;\n        case cst_kind::INEQUALITY: return c <= 0;\n        case cst_kind::STRICT_INEQUALITY: return c < 0;\n        default: CRAB_ERROR(\"Unreachable\");\n        }\n    }\n\n    [[nodiscard]] bool is_contradiction() const {\n        if (!this->_expr.is_constant())\n            return false;\n        const number_t c = this->_expr.constant();\n        switch (this->_kind) {\n        case cst_kind::DISEQUATION: return c == 0;\n        case cst_kind::EQUALITY: return c != 0;\n        case cst_kind::INEQUALITY: return c > 0;\n        case cst_kind::STRICT_INEQUALITY: return c >= 0;\n        default: CRAB_ERROR(\"Unreachable\");\n        }\n    }\n\n    [[nodiscard]] bool is_inequality() const { return (this->_kind == cst_kind::INEQUALITY); }\n\n    [[nodiscard]] bool is_strict_inequality() const { return (this->_kind == cst_kind::STRICT_INEQUALITY); }\n\n    [[nodiscard]] bool is_equality() const { return (this->_kind == cst_kind::EQUALITY); }\n\n    [[nodiscard]] bool is_disequation() const { return (this->_kind == cst_kind::DISEQUATION); }\n\n    [[nodiscard]] const linear_expression_t& expression() const { return this->_expr; }\n\n    [[nodiscard]] cst_kind kind() const { return this->_kind; }\n\n    [[nodiscard]] bool is_signed() const {\n        if (_kind != cst_kind::INEQUALITY && _kind != cst_kind::STRICT_INEQUALITY) {\n            CRAB_WARN(\"Only inequalities have signedness\");\n        }\n        return _signedness;\n    }\n\n    [[nodiscard]] bool is_unsigned() const { return (!is_signed()); }\n\n    [[nodiscard]] const_iterator begin() const { return this->_expr.begin(); }\n\n    [[nodiscard]] const_iterator end() const { return this->_expr.end(); }\n\n    [[nodiscard]] std::size_t size() const { return this->_expr.size(); }\n\n    // syntactic equality\n    [[nodiscard]] bool equal(const linear_constraint_t& o) const {\n        return (_kind == o._kind && _signedness == o._signedness && _expr.equal(o._expr));\n    }\n\n    [[nodiscard]] size_t hash() const {\n        size_t res = 0;\n        boost::hash_combine(res, _expr);\n        boost::hash_combine(res, _kind);\n        if (_kind == cst_kind::INEQUALITY || _kind == cst_kind::STRICT_INEQUALITY) {\n            boost::hash_combine(res, _signedness);\n        }\n        return res;\n    }\n\n    number_t operator[](variable_t x) const { return this->_expr.operator[](x); }\n\n    [[nodiscard]] linear_constraint_t negate() const {\n        if (is_tautology()) {\n            return get_false();\n        } else if (is_contradiction()) {\n            return get_true();\n        } else {\n            switch (kind()) {\n            case cst_kind::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), cst_kind::INEQUALITY, is_signed());\n            }\n            case cst_kind::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, cst_kind::INEQUALITY, is_signed());\n            }\n            case cst_kind::EQUALITY: return linear_constraint_t(this->_expr, cst_kind::DISEQUATION);\n            case cst_kind::DISEQUATION: return linear_constraint_t(this->_expr, cst_kind::EQUALITY);\n            default: CRAB_ERROR(\"Cannot negate linear constraint\");\n            }\n        }\n    }\n\n    friend std::ostream& operator<<(std::ostream& o, const linear_constraint_t& cst) {\n        if (cst.is_contradiction()) {\n            o << \"false\";\n        } else if (cst.is_tautology()) {\n            o << \"true\";\n        } else {\n            linear_expression_t e = cst._expr - cst._expr.constant();\n            o << e;\n            switch (cst._kind) {\n            case cst_kind::INEQUALITY: {\n                if (cst.is_signed()) {\n                    o << \" <= \";\n                } else {\n                    o << \" <=_u \";\n                }\n                break;\n            }\n            case cst_kind::STRICT_INEQUALITY: {\n                if (cst.is_signed()) {\n                    o << \" < \";\n                } else {\n                    o << \" <_u \";\n                }\n                break;\n            }\n            case cst_kind::EQUALITY: {\n                o << \" = \";\n                break;\n            }\n            case cst_kind::DISEQUATION: {\n                o << \" != \";\n                break;\n            }\n            }\n            number_t c = -cst._expr.constant();\n            o << c;\n        }\n        return o;\n    }\n}; // class linear_constraint_t\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, const number_t& n) { return linear_expression_t(x).operator+(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": "a769e2393e87f1b8b8da70f0a5e68d9f1aa69fda", "size": 14822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crab/linear_constraints.hpp", "max_stars_repo_name": "poornagmsft/ebpf-verifier", "max_stars_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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": "src/crab/linear_constraints.hpp", "max_issues_repo_name": "poornagmsft/ebpf-verifier", "max_issues_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "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": "src/crab/linear_constraints.hpp", "max_forks_repo_name": "poornagmsft/ebpf-verifier", "max_forks_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8019323671, "max_line_length": 115, "alphanum_fraction": 0.5922952368, "num_tokens": 3615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.03308598053388778, "lm_q1q2_score": 0.012370048194315633}}
{"text": "/**\n * @file\n * This file is part of SeisSol.\n *\n * @author Carsten Uphoff (c.uphoff AT tum.de,\n *http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)\n * @author Sebastian Wolf (wolf.sebastian AT in.tum.de,\n *https://www5.in.tum.de/wiki/index.php/Sebastian_Wolf,_M.Sc.)\n *\n * @section LICENSE\n * Copyright (c) 2017 - 2020, 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 <Eigen/Eigenvalues>\n#include <Kernels/precision.hpp>\n#include <Initializer/typedefs.hpp>\n\n#include <PUML/PUML.h>\n#include <PUML/Downward.h>\n#include <PUML/Upward.h>\n#include \"LtsWeights.h\"\n#include \"WeightsModels.h\"\n\n#include <Initializer/ParameterDB.h>\n#include <Parallel/MPI.h>\n\n#include <generated_code/init.h>\n\nnamespace seissol::initializers::time_stepping {\n\nclass FaceSorter {\n  private:\n  std::vector<PUML::TETPUML::face_t> const& m_faces;\n\n  public:\n  FaceSorter(std::vector<PUML::TETPUML::face_t> const& faces) : m_faces(faces) {}\n\n  bool operator()(unsigned int a, unsigned int b) const {\n    return m_faces[a].gid() < m_faces[b].gid();\n  }\n};\n\nvoid LtsWeights::computeNodeWeights(PUML::TETPUML const& mesh, double maximumAllowedTimeStep) {\n  logInfo(seissol::MPI::mpi.rank()) << \"Computing LTS weights.\";\n\n  // Note: Return value optimization is guaranteed while returning temp. objects in C++17\n  m_mesh = &mesh;\n  m_details = collectGlobalTimeStepDetails(maximumAllowedTimeStep);\n  m_clusterIds = computeClusterIds();\n  m_ncon = evaluateNumberOfConstraints();\n  auto totalNumberOfReductions = enforceMaximumDifference();\n  m_cellCosts = computeCostsPerTimestep();\n\n  if (!m_vertexWeights.empty()) {\n    m_vertexWeights.clear();\n  }\n  m_vertexWeights.resize(m_clusterIds.size() * m_ncon);\n\n  // calling virtual functions\n  setVertexWeights();\n  setAllowedImbalances();\n\n  logInfo(seissol::MPI::mpi.rank()) << \"Computing LTS Node Weights. Done. \" << utils::nospace << '('\n                                    << totalNumberOfReductions << \" reductions.)\";\n}\n\nvoid LtsWeights::computeEdgeWeights(std::tuple<const std::vector<idx_t>&, const std::vector<idx_t>&,\n                                               const std::vector<idx_t>&>& graph) {\n  if (!m_edgeWeights.empty()) {\n    m_edgeWeights.clear();\n  }\n\n  size_t edge_count = std::get<2>(graph).size();\n\n  m_edgeWeights.resize(edge_count);\n\n  setEdgeWeights(graph);\n\n  logInfo(seissol::MPI::mpi.rank()) << \"Computing LTS Edge Weights. Done. \" << utils::nospace;\n}\n\nconst int* LtsWeights::vertexWeights() const {\n  assert(!m_vertexWeights.empty() && \"vertex weights are not initialized\");\n  return m_vertexWeights.data();\n}\n\nconst int* LtsWeights::edgeWeights() const {\n  assert(!m_edgeWeights.empty() && \"edge weights are not initialized\");\n  return m_edgeWeights.data();\n}\n\nint LtsWeights::edgeCount() const {\n  assert(!m_edgeWeights.empty() && \"edge weights are not initialized\");\n  return m_edgeWeights.size();\n}\n\nconst double* LtsWeights::imbalances() const {\n  assert(!m_imbalances.empty() && \"weight imbalances are not initialized\");\n  return m_imbalances.data();\n}\n\nint LtsWeights::nWeightsPerVertex() const {\n  assert(m_ncon != std::numeric_limits<int>::infinity() &&\n         \"num. constrains has not been initialized yet\");\n  return m_ncon;\n}\n\nvoid LtsWeights::computeMaxTimesteps(std::vector<double> const& pWaveVel,\n                                     std::vector<double>& timeSteps,\n                                     double maximumAllowedTimeStep) {\n  std::vector<PUML::TETPUML::cell_t> const& cells = m_mesh->cells();\n  std::vector<PUML::TETPUML::vertex_t> const& vertices = m_mesh->vertices();\n\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    // Compute insphere radius\n    Eigen::Vector3d barycentre(0., 0., 0.);\n    Eigen::Vector3d x[4];\n    unsigned vertLids[4];\n    PUML::Downward::vertices(*m_mesh, cells[cell], vertLids);\n    for (unsigned vtx = 0; vtx < 4; ++vtx) {\n      for (unsigned d = 0; d < 3; ++d) {\n        x[vtx](d) = vertices[vertLids[vtx]].coordinate()[d];\n      }\n    }\n    Eigen::Matrix4d A;\n    A << x[0](0), x[0](1), x[0](2), 1.0, x[1](0), x[1](1), x[1](2), 1.0, x[2](0), x[2](1), x[2](2),\n        1.0, x[3](0), x[3](1), x[3](2), 1.0;\n\n    double alpha = A.determinant();\n    double Nabc = ((x[1] - x[0]).cross(x[2] - x[0])).norm();\n    double Nabd = ((x[1] - x[0]).cross(x[3] - x[0])).norm();\n    double Nacd = ((x[2] - x[0]).cross(x[3] - x[0])).norm();\n    double Nbcd = ((x[2] - x[1]).cross(x[3] - x[1])).norm();\n    double insphere = std::fabs(alpha) / (Nabc + Nabd + Nacd + Nbcd);\n\n    // Compute maximum timestep (CFL=1)\n    timeSteps[cell] = std::fmin(maximumAllowedTimeStep,\n                                2.0 * insphere / (pWaveVel[cell] * (2 * CONVERGENCE_ORDER - 1)));\n  }\n}\n\nint LtsWeights::getCluster(double timestep, double globalMinTimestep, unsigned rate) {\n  if (rate == 1) {\n    return 0;\n  }\n\n  double upper = rate * globalMinTimestep;\n\n  int cluster = 0;\n  while (upper <= timestep) {\n    upper *= rate;\n    ++cluster;\n  }\n  return cluster;\n}\n\nint LtsWeights::getBoundaryCondition(int const* boundaryCond, unsigned cell, unsigned face) {\n  int bcCurrentFace = ((boundaryCond[cell] >> (face * 8)) & 0xFF);\n  if (bcCurrentFace > 64) {\n    bcCurrentFace = 3;\n  }\n  return bcCurrentFace;\n}\n\nint LtsWeights::ipow(int x, int y) {\n  assert(y >= 0);\n\n  if (y == 0) {\n    return 1;\n  }\n  int result = x;\n  while (--y) {\n    result *= x;\n  }\n  return result;\n}\n\nLtsWeights::GlobalTimeStepDetails\nLtsWeights::collectGlobalTimeStepDetails(double maximumAllowedTimeStep) {\n\n  const auto& cells = m_mesh->cells();\n  std::vector<double> pWaveVel;\n  pWaveVel.resize(cells.size());\n\n  seissol::initializers::ElementBarycentreGeneratorPUML queryGen(*m_mesh);\n  // up to now we only distinguish between anisotropic elastic any other isotropic material\n#ifdef USE_ANISOTROPIC\n  std::vector<seissol::model::AnisotropicMaterial> materials(cells.size());\n  seissol::initializers::MaterialParameterDB<seissol::model::AnisotropicMaterial> parameterDB;\n#elif defined(USE_POROELASTIC)\n  std::vector<seissol::model::PoroElasticMaterial> materials(cells.size());\n  seissol::initializers::MaterialParameterDB<seissol::model::PoroElasticMaterial> parameterDB;\n#else\n  std::vector<seissol::model::ElasticMaterial> materials(cells.size());\n  seissol::initializers::MaterialParameterDB<seissol::model::ElasticMaterial> parameterDB;\n#endif\n  parameterDB.setMaterialVector(&materials);\n  parameterDB.evaluateModel(m_velocityModel, queryGen);\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    pWaveVel[cell] = materials[cell].getMaxWaveSpeed();\n  }\n\n  GlobalTimeStepDetails details{};\n  details.timeSteps.resize(cells.size());\n  computeMaxTimesteps(pWaveVel, details.timeSteps, maximumAllowedTimeStep);\n\n  double localMinTimestep = *std::min_element(details.timeSteps.begin(), details.timeSteps.end());\n  double localMaxTimestep = *std::max_element(details.timeSteps.begin(), details.timeSteps.end());\n\n#ifdef USE_MPI\n  MPI_Allreduce(&localMinTimestep, &details.globalMinTimeStep, 1, MPI_DOUBLE, MPI_MIN,\n                seissol::MPI::mpi.comm());\n  MPI_Allreduce(&localMaxTimestep, &details.globalMaxTimeStep, 1, MPI_DOUBLE, MPI_MAX,\n                seissol::MPI::mpi.comm());\n#else\n  details.globalMinTimeStep = localMinTimestep;\n  details.globalMaxTimeStep = localMaxTimestep;\n#endif\n  return details;\n}\n\nstd::vector<int> LtsWeights::computeClusterIds() {\n  const auto& cells = m_mesh->cells();\n  std::vector<int> clusterIds(cells.size(), 0);\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    clusterIds[cell] = getCluster(m_details.timeSteps[cell], m_details.globalMinTimeStep, m_rate);\n  }\n  return clusterIds;\n}\n\nstd::vector<int> LtsWeights::computeCostsPerTimestep() {\n  const auto& cells = m_mesh->cells();\n\n  std::vector<int> cellCosts(cells.size());\n  int const* boundaryCond = m_mesh->cellData(1);\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    int dynamicRupture = 0;\n    int freeSurfaceWithGravity = 0;\n\n    unsigned int faceids[4];\n    PUML::Downward::faces(*m_mesh, cells[cell], faceids);\n\n    for (unsigned face = 0; face < 4; ++face) {\n      const auto faceType = static_cast<FaceType>(getBoundaryCondition(boundaryCond, cell, face));\n      dynamicRupture += (faceType == FaceType::dynamicRupture) ? 1 : 0;\n      freeSurfaceWithGravity += (faceType == FaceType::freeSurfaceGravity) ? 1 : 0;\n    }\n\n    const int costDynamicRupture = m_vertexWeightDynamicRupture * dynamicRupture;\n    const int costDisplacement = m_vertexWeightFreeSurfaceWithGravity * freeSurfaceWithGravity;\n    cellCosts[cell] = m_vertexWeightElement + costDynamicRupture + costDisplacement;\n  }\n  return cellCosts;\n}\n\nint LtsWeights::enforceMaximumDifference() {\n  int totalNumberOfReductions = 0;\n  int globalNumberOfReductions;\n  do {\n    int localNumberOfReductions = enforceMaximumDifferenceLocal();\n\n#ifdef USE_MPI\n    MPI_Allreduce(&localNumberOfReductions, &globalNumberOfReductions, 1, MPI_INT, MPI_SUM,\n                  seissol::MPI::mpi.comm());\n#else\n    globalNumberOfReductions = localNumberOfReductions;\n#endif\n    totalNumberOfReductions += globalNumberOfReductions;\n  } while (globalNumberOfReductions > 0);\n  return totalNumberOfReductions;\n}\n\nint LtsWeights::enforceMaximumDifferenceLocal(int maxDifference) {\n  int numberOfReductions = 0;\n\n  std::vector<PUML::TETPUML::cell_t> const& cells = m_mesh->cells();\n  std::vector<PUML::TETPUML::face_t> const& faces = m_mesh->faces();\n  int const* boundaryCond = m_mesh->cellData(1);\n\n#ifdef USE_MPI\n  std::unordered_map<int, std::vector<int>> rankToSharedFaces;\n  std::unordered_map<int, int> localFaceIdToLocalCellId;\n#endif\n\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    int timeCluster = m_clusterIds[cell];\n\n    unsigned int faceids[4];\n    PUML::Downward::faces(*m_mesh, cells[cell], faceids);\n    for (unsigned f = 0; f < 4; ++f) {\n      int difference = maxDifference;\n      int boundary = getBoundaryCondition(boundaryCond, cell, f);\n      // Continue for regular, dynamic rupture, and periodic boundary cells\n      if (boundary == 0 || boundary == 3 || boundary == 6) {\n        // We treat MPI neighbours later\n        auto const& face = faces[faceids[f]];\n        if (!face.isShared()) {\n          int cellIds[2];\n          PUML::Upward::cells(*m_mesh, face, cellIds);\n\n          int neighbourCell = (cellIds[0] == static_cast<int>(cell)) ? cellIds[1] : cellIds[0];\n          int otherTimeCluster = m_clusterIds[neighbourCell];\n\n          if (boundary == 3) {\n            difference = 0;\n          }\n\n          if (timeCluster > otherTimeCluster + difference) {\n            timeCluster = otherTimeCluster + difference;\n            ++numberOfReductions;\n          }\n        }\n#ifdef USE_MPI\n        else {\n          rankToSharedFaces[face.shared()[0]].push_back(faceids[f]);\n          localFaceIdToLocalCellId[faceids[f]] = cell;\n        }\n#endif\n      }\n    }\n    m_clusterIds[cell] = timeCluster;\n  }\n\n#ifdef USE_MPI\n  FaceSorter faceSorter(faces);\n  for (auto& sharedFaces : rankToSharedFaces) {\n    std::sort(sharedFaces.second.begin(), sharedFaces.second.end(), faceSorter);\n  }\n\n  auto numExchanges = rankToSharedFaces.size();\n  std::vector<MPI_Request> requests(2 * numExchanges);\n  std::vector<std::vector<int>> ghost(numExchanges);\n  std::vector<std::vector<int>> copy(numExchanges);\n\n  auto exchange = rankToSharedFaces.begin();\n  for (unsigned ex = 0; ex < numExchanges; ++ex) {\n    auto exchangeSize = exchange->second.size();\n    ghost[ex].resize(exchangeSize);\n    copy[ex].resize(exchangeSize);\n\n    for (unsigned n = 0; n < exchangeSize; ++n) {\n      copy[ex][n] = m_clusterIds[localFaceIdToLocalCellId[exchange->second[n]]];\n    }\n    MPI_Isend(copy[ex].data(), exchangeSize, MPI_INT, exchange->first, 0, seissol::MPI::mpi.comm(),\n              &requests[ex]);\n    MPI_Irecv(ghost[ex].data(), exchangeSize, MPI_INT, exchange->first, 0, seissol::MPI::mpi.comm(),\n              &requests[numExchanges + ex]);\n    ++exchange;\n  }\n\n  MPI_Waitall(2 * numExchanges, requests.data(), MPI_STATUSES_IGNORE);\n\n  exchange = rankToSharedFaces.begin();\n  for (unsigned ex = 0; ex < numExchanges; ++ex) {\n    auto exchangeSize = exchange->second.size();\n    for (unsigned n = 0; n < exchangeSize; ++n) {\n      int difference = maxDifference;\n      int otherTimeCluster = ghost[ex][n];\n\n      int cellIds[2];\n      PUML::Upward::cells(*m_mesh, faces[exchange->second[n]], cellIds);\n      int cell = (cellIds[0] >= 0) ? cellIds[0] : cellIds[1];\n\n      unsigned int faceids[4];\n      PUML::Downward::faces(*m_mesh, cells[cell], faceids);\n      unsigned f = 0;\n      for (; f < 4 && static_cast<int>(faceids[f]) != exchange->second[n]; ++f)\n        ;\n      assert(f != 4);\n\n      int boundary = getBoundaryCondition(boundaryCond, cell, f);\n      if (boundary == 3) {\n        difference = 0;\n      }\n\n      if (m_clusterIds[cell] > otherTimeCluster + difference) {\n        m_clusterIds[cell] = otherTimeCluster + difference;\n        ++numberOfReductions;\n      }\n    }\n    ++exchange;\n  }\n\n#endif\n\n  return numberOfReductions;\n}\n\nconst LtsWeights::GlobalTimeStepDetails& LtsWeights::getDetails() const { return m_details; }\n\nconst std::string& LtsWeights::getVelocityModel() const { return m_velocityModel; }\n\nunsigned LtsWeights::getRate() const { return m_rate; }\n\nstd::vector<int>& LtsWeights::getVertexWeights() { return m_vertexWeights; }\n\nstd::vector<double>& LtsWeights::getImbalances() { return m_imbalances; }\n\nconst std::vector<int>& LtsWeights::getCellCosts() const { return m_cellCosts; }\n\nint LtsWeights::getVertexWeightElement() const { return m_vertexWeightElement; }\n\nint LtsWeights::getVertexWeightDynamicRupture() const { return m_vertexWeightDynamicRupture; }\n\nint LtsWeights::getVertexWeightFreeSurfaceWithGravity() const {\n  return m_vertexWeightFreeSurfaceWithGravity;\n}\n\nint LtsWeights::getNcon() const { return m_ncon; }\n\nconst PUML::TETPUML* LtsWeights::getMesh() const { return m_mesh; }\n\nconst std::vector<int>& LtsWeights::getClusterIds() const { return m_clusterIds; }\n\nLtsWeights::LtsWeights(const LtsWeightsConfig& config) noexcept\n    : m_velocityModel(config.velocityModel), m_rate(config.rate),\n      m_vertexWeightElement(config.vertexWeightElement),\n      m_vertexWeightDynamicRupture(config.vertexWeightDynamicRupture),\n      m_vertexWeightFreeSurfaceWithGravity(config.vertexWeightFreeSurfaceWithGravity),\n      m_nodeWeightModel(nullptr), m_edgeWeightModel(nullptr) {}\n\nvoid LtsWeights::setVertexWeights() { m_nodeWeightModel->setVertexWeights(); }\n\nvoid LtsWeights::setAllowedImbalances() { m_nodeWeightModel->setAllowedImbalances(); }\n\nint LtsWeights::evaluateNumberOfConstraints() const {\n  return m_nodeWeightModel->evaluateNumberOfConstraints();\n}\n\nvoid LtsWeights::setEdgeWeights(std::tuple<const std::vector<idx_t>&, const std::vector<idx_t>&,\n                                           const std::vector<idx_t>&>& graph) {\n  m_edgeWeightModel->setEdgeWeights(graph);\n}\n\nLtsWeights::~LtsWeights() noexcept {\n  delete m_nodeWeightModel;\n  delete m_edgeWeightModel;\n}\n\nvoid LtsWeights::addWeightModels(NodeWeightModel* nwm, EdgeWeightModel* ewm) {\n  m_nodeWeightModel = nwm;\n  m_edgeWeightModel = ewm;\n}\n\nstd::vector<int>& LtsWeights::getEdgeWeights() { return m_edgeWeights; }\n\nint LtsWeights::find_rank(const std::vector<idx_t>& vrtxdist, idx_t elemId){\n  assert(!vrtxdist.empty());\n  assert(elemId < vrtxdist.back());\n  assert(elemId >= 0);\n  assert(vrtxdist[0] == 0);\n\n  for (size_t i = 0; i < vrtxdist.size()-1; i++){\n    if (elemId >= vrtxdist[i] && elemId < vrtxdist[i+1])\n    {\n      return i;\n    }\n  }\n\n  throw std::runtime_error(\"element id is not in valid range!\");\n}\n\n\nstd::vector<std::unordered_map<idx_t, int>>\nLtsWeights::exchangeGhostLayer(std::tuple<const std::vector<idx_t>&, const std::vector<idx_t>&,\n                                          const std::vector<idx_t>&>& graph) {\n  // fails with intel compiler, mpi standard says use mpi size of\n  // static_assert(sizeof(idx_t) <= sizeof(MPI_LONG_LONG_INT));\n\n  const std::vector<idx_t>& vrtxdist = std::get<0>(graph);\n  const std::vector<idx_t>& xadj = std::get<1>(graph);\n  const std::vector<idx_t>& adjncy = std::get<2>(graph);\n\n  const int rank = seissol::MPI::mpi.rank();\n  const int size = seissol::MPI::mpi.size();\n\n  assert(vrtxdist.size() == static_cast<size_t>(size + 1) && !xadj.empty() && !adjncy.empty());\n  assert(vrtxdist[0] == 0);\n\n  const size_t vertex_id_begin = vrtxdist[rank];\n  // const size_t vertex_id_end = vrtxdist[rank + 1];\n\n  assert(!m_clusterIds.empty());\n\n  // gather all the ranks that have neighbors to these ranks\n  std::set<int> neighbor_ranks;\n\n  // ghost layers of other ranks\n  // ghost_layer_to_send[i] means the actors and their cluster to send to rank i!\n  // using a vector because we need continous data and therefore we will have\n  // a vector of idx_t the length of element count * 2\n  std::vector<std::vector<idx_t>> ghost_layer_to_send;\n  std::vector<std::vector<idx_t>> ghost_layer_received;\n  std::vector<std::unordered_map<idx_t, int>> ghost_layer_mapped;\n  std::vector<MPI_Request> send_requests;\n  std::vector<MPI_Status> recv_stats;\n\n  // the at(my_rank) will be empty but it makes coding much easier\n  ghost_layer_to_send.resize(size);\n  ghost_layer_received.resize(size);\n  ghost_layer_mapped.resize(size);\n\n  for (size_t i = 0; i < xadj.size() - 1; i++) {\n    //[xadj[i] .. xadj[i+1]) describes to offsets neighbor ids of local vertex i\n    const size_t neighbors_offset_begin = xadj[i];\n    const size_t neighbors_offset_end = xadj[i + 1];\n\n    const int cluster_id = m_clusterIds[i];\n\n    for (size_t j = neighbors_offset_begin; j < neighbors_offset_end; j++) {\n      const idx_t neighbor_id = adjncy[j];\n\n      const int neighbor_rank = find_rank(vrtxdist, neighbor_id);\n\n      // if neighbor's rank is different than mine\n      if (neighbor_rank != rank) {\n        neighbor_ranks.insert(neighbor_rank);\n        ghost_layer_to_send[neighbor_rank].push_back(\n            static_cast<idx_t>(i + vertex_id_begin)); // send global id\n        ghost_layer_to_send[neighbor_rank].push_back(static_cast<idx_t>(cluster_id));\n      }\n    }\n  }\n\n  //std::cout << \"Neighbors of \" << rank << \" are: \";\n  //for (int nb : neighbor_ranks) {\n  //  std::cout << nb << \" \";\n  //}\n  //std::cout << std::endl;\n\n  // if we add empty requests and stats waiting becomes problematic\n  send_requests.resize(neighbor_ranks.size());\n  recv_stats.resize(neighbor_ranks.size());\n\n  // now send ghost_layer_to_send to neighbors\n  // per default sets are stored in ascending order\n  {\n    int offset = 0;\n    for (int neighbor_rank : neighbor_ranks) {\n      const std::vector<idx_t>& layer_ref = ghost_layer_to_send[neighbor_rank];\n\n      assert(!layer_ref.empty());\n\n      if (sizeof(idx_t) != 8)\n      {\n        if (rank == 0)\n        {\n          std::cerr << \"If the size of idx_t is not 64 bits the ghost layer exchange will crush with a segmentation fault!\" << std::endl;\n        }\n      } \n\n      MPI_Isend(layer_ref.data(), layer_ref.size(), MPI_LONG_LONG_INT, neighbor_rank, rank,\n                MPI_COMM_WORLD, &send_requests[offset]);\n      \n\n      offset += 1;\n    }\n  }\n\n  volatile unsigned int got = 0;\n  std::vector<bool> skip;\n  skip.resize(neighbor_ranks.size());\n  std::fill(skip.begin(), skip.end(), false);\n\n  // now lets probe and try to get the ghost layer\n  while (got < neighbor_ranks.size()) {\n    int offset = 0;\n    for (int neighbor_rank : neighbor_ranks) {\n      if (neighbor_rank == rank) {\n        throw std::runtime_error(\"A neighbor's rank should not be the same as self rank!\");\n      }\n\n      if (skip[offset]) {\n\n        offset += 1;\n\n      } else {\n\n        int flag = 0;\n        MPI_Iprobe(neighbor_rank, neighbor_rank, MPI_COMM_WORLD, &flag, &recv_stats[offset]);\n\n        if (flag) {\n          int count = 0;\n\n          MPI_Get_count(&recv_stats[offset], MPI_LONG_LONG_INT, &count);\n\n          assert(ghost_layer_received[neighbor_rank].empty());\n          ghost_layer_received[neighbor_rank].resize(count);\n          assert(ghost_layer_mapped[neighbor_rank].empty());\n          MPI_Recv(ghost_layer_received[neighbor_rank].data(), count, MPI_LONG_LONG_INT, neighbor_rank,\n                   neighbor_rank, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n          got += 1;\n\n          skip[offset] = true;\n\n          // lets move the data here\n        }\n\n        offset += 1;\n      }\n    }\n  }\n\n  // wait for the communication to be completed\n  MPI_Waitall(send_requests.size(), send_requests.data(), MPI_STATUS_IGNORE);\n\n  // not sure if necessary as waiting for all send implies the loop will\n  // completed too and the rest of communication is totally local\n  // MPI_Barrier(MPI_COMM_WORLD);\n\n  for (int i : neighbor_ranks) {\n    assert(i != rank);\n    assert(!ghost_layer_received[i].empty());\n    assert(ghost_layer_received[i].size() % 2 == 0);\n\n    for (unsigned int j = 0; j < ghost_layer_received[i].size(); j += 2) {\n      ghost_layer_mapped[i].emplace(ghost_layer_received[i][j], ghost_layer_received[i][j + 1]);\n    }\n    //std::cout << \"Ghost received from rank: \" << i << \" to \" << rank << \" has \"\n    //          << ghost_layer_received[i].size() / 2 << \" elements\" << std::endl;\n  }\n\n  return ghost_layer_mapped;\n}\n\n} // namespace seissol::initializers::time_stepping\n", "meta": {"hexsha": "b2e988611021a211ae2084fe5e8b7660163d4ef2", "size": 22796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Initializer/time_stepping/LtsWeights/LtsWeights.cpp", "max_stars_repo_name": "ThrudPrimrose/SeisSol", "max_stars_repo_head_hexsha": "72b6d30cc62c8f8e2d601afc92c12fb026cad423", "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/time_stepping/LtsWeights/LtsWeights.cpp", "max_issues_repo_name": "ThrudPrimrose/SeisSol", "max_issues_repo_head_hexsha": "72b6d30cc62c8f8e2d601afc92c12fb026cad423", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/time_stepping/LtsWeights/LtsWeights.cpp", "max_forks_repo_name": "ThrudPrimrose/SeisSol", "max_forks_repo_head_hexsha": "72b6d30cc62c8f8e2d601afc92c12fb026cad423", "max_forks_repo_licenses": ["BSD-3-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.75, "max_line_length": 137, "alphanum_fraction": 0.678320758, "num_tokens": 6086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.03308597755446607, "lm_q1q2_score": 0.012370047080381889}}
{"text": "#include <stdint.h>\n#include <alloca.h>\n#include <Eigen/Core>\n#include <omp.h>\n#include \"mex.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\n// NOTE: mxSetProperty and possibly mxGetProperty make copies, even with\n// classdef < handle! lame! I believe mxGetField does NOT make a copy, though I\n// haven't tested it recently\n\n// TODO if we aren't outputting gamma, don't need to write it to memory (just\n// need t and t+1), so we can save the stack array for each HMM at the cost of\n// a branch\n\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )\n{\n\n    /* SETUP */\n    //Only acceptable if we have at least the 5 basic args and some number of\n    //name:value argument pairs\n    if (nrhs < 5 || nrhs % 2 == 0) { mexErrMsgTxt(\"wrong number of arguments\\n\"); }\n\n    //// pull out inputs\n    IOFormat CleanFmt(4, 0, \", \", \"\\n\", \"[\", \"]\");\n    // data\n    if (!mxGetField(prhs[0],0,\"data\")) { mexErrMsgTxt(\"data missing 'data' field\\n\"); }\n    int8_t *alldata = (int8_t *) mxGetData(mxGetField(prhs[0],0,\"data\"));\n    int bigT = mxGetN(mxGetField(prhs[0],0,\"data\")); // total length of the data\n    int num_subparts = mxGetM(mxGetField(prhs[0],0,\"data\")); // number of sub-parts\n\n    if (!mxGetField(prhs[0],0,\"resources\")) { mexErrMsgTxt(\"data missing 'resources' field\\n\"); }\n    int16_t *allresources = (int16_t *) mxGetData(mxGetField(prhs[0],0,\"resources\"));\n\n    if (!mxGetField(prhs[0],0,\"starts\")) { mexErrMsgTxt(\"data missing 'starts' field\\n\"); }\n    int32_t *starts = (int32_t *) mxGetData(mxGetField(prhs[0],0,\"starts\"));\n    \n    //TYPO WAS HERE\n    int num_sequences = max(mxGetN(mxGetField(prhs[0],0,\"starts\")),\n            mxGetM(mxGetField(prhs[0],0,\"starts\")));\n\n\n    if (!mxGetField(prhs[0],0,\"lengths\")) { mexErrMsgTxt(\"data missing 'lengths' field\\n\"); }\n    int32_t *lengths = (int32_t *) mxGetData(mxGetField(prhs[0],0,\"lengths\"));\n\n    // parameters struct\n    if (!mxGetField(prhs[1],0,\"learns\")) { mexErrMsgTxt(\"model missing 'learns' field\\n\"); }\n    double *learns = mxGetPr(mxGetField(prhs[1],0,\"learns\"));\n    int num_resources = max(mxGetM(mxGetField(prhs[1],0,\"learns\")),\n            mxGetN(mxGetField(prhs[1],0,\"learns\")));\n\n    if (!mxGetField(prhs[1],0,\"forgets\")) { mexErrMsgTxt(\"model missing 'forgets' field\\n\"); }\n    double *forgets = mxGetPr(mxGetField(prhs[1],0,\"forgets\"));\n\n    if (!mxGetField(prhs[1],0,\"guesses\")) { mexErrMsgTxt(\"model missing 'guesses' field\\n\"); }\n    double *guess = mxGetPr(mxGetField(prhs[1],0,\"guesses\"));\n\n    if (!mxGetField(prhs[1],0,\"slips\")) { mexErrMsgTxt(\"model missing 'slips' field\\n\"); }\n    double *slip = mxGetPr(mxGetField(prhs[1],0,\"slips\"));\n\n    if (!mxGetField(prhs[1],0,\"prior\")) { mexErrMsgTxt(\"model missing 'prior' field\\n\"); }\n    double prior = mxGetScalar(mxGetField(prhs[1],0,\"prior\"));\n    \n    \n    /*CHECK FOR OPTIONAL NAME:VALUE PARAMS*/\n    bool normalizeLengths = false;\n    if (nrhs >= 7) {\n        int i = 5;\n        char* optName;\n        for(i; i + 1 < nrhs; i+= 2) {\n            if(mxIsChar(prhs[i])) {\n                optName = mxArrayToString(prhs[i]);\n                if(optName != NULL) {\n                    if(strcmp(optName, \"normalize length\") == 0) {\n                        if(mxIsLogical(prhs[i + 1])) {\n                            normalizeLengths = *mxGetLogicals(prhs[i + 1]);\n                        } \n                        else {\n                            mexErrMsgIdAndTxt(\"E_Step:invalidInputValue\",\n                                    \"Expected boolean value for normalize length\");\n                        }\n                        \n                    } \n                    //other options here, if you want\n                    //If no matches, this is an unexpected param, so yell\n                    else {\n                        mexErrMsgIdAndTxt(\"E_Step:invalidInput\",\n                                \"invalid named parameter\");\n                    }\n                }\n                \n                mxFree(optName);\n            } else {\n                mexErrMsgIdAndTxt( \"E_Step:invalidInputType\",\n                \"Expected string for name:value pair.\");\n            }\n        }\n    }\n    \n   \n    \n    Array2d initial_distn;\n    initial_distn << 1-prior, prior;\n\n    MatrixXd As(2,2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        As.col(2*n) << 1-learns[n], learns[n];\n        As.col(2*n+1) << forgets[n], 1-forgets[n];\n    }\n\n    Array2Xd Bn(2,2*num_subparts);\n    for (int n=0; n<num_subparts; n++) {\n        Bn.col(2*n) << 1-guess[n], slip[n]; // incorrect\n        Bn.col(2*n+1) << guess[n], 1-slip[n]; // correct\n    }\n\n    //// outputs\n\n    // rhs outputs\n    Map<ArrayXXd,Aligned> all_trans_softcounts(mxGetPr(prhs[2]),2,2*num_resources);\n    all_trans_softcounts.setZero();\n    Map<Array2Xd,Aligned> all_emission_softcounts(mxGetPr(prhs[3]),2,2*num_subparts);\n    all_emission_softcounts.setZero();\n    Map<Array2d,Aligned> all_initial_softcounts(mxGetPr(prhs[4]));\n    all_initial_softcounts.setZero();\n\n    // lhs outputs\n    Map<Array2Xd,Aligned> likelihoods_out(NULL,2,bigT);\n    Map<Array2Xd,Aligned> gamma_out(NULL,2,bigT);\n    Map<Array2Xd,Aligned> alpha_out(NULL,2,bigT);\n    double s_total_loglike = 0;\n    double *total_loglike = &s_total_loglike;\n    switch (nlhs)\n    {\n        case 4:\n            plhs[3] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&likelihoods_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[3]),2,bigT);\n        case 3:\n            plhs[2] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&gamma_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[2]),2,bigT);\n        case 2:\n            plhs[1] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&alpha_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[1]),2,bigT);\n        case 1:\n            plhs[0] = mxCreateDoubleScalar(0.);\n            total_loglike = mxGetPr(plhs[0]);\n    }\n\n    /* COMPUTATION */\n    Eigen::initParallel();\n    /* omp_set_dynamic(0); */\n    /* omp_set_num_threads(6); */\n    #pragma omp parallel\n    {\n        double s_trans_softcounts[2*2*num_resources] __attribute__((aligned(16)));\n        double s_emission_softcounts[2*2*num_subparts] __attribute__((aligned(16)));\n        Map<ArrayXXd,Aligned> trans_softcounts(s_trans_softcounts,2,2*num_resources);\n        Map<ArrayXXd,Aligned> emission_softcounts(s_emission_softcounts,2,2*num_subparts);\n        Array2d init_softcounts;\n        double loglike;\n\n        trans_softcounts.setZero();\n        emission_softcounts.setZero();\n        init_softcounts.setZero();\n        loglike = 0;\n        int num_threads = omp_get_num_threads();\n        int blocklen = 1 + ((num_sequences - 1) / num_threads);\n        int sequence_idx_start = blocklen * omp_get_thread_num();\n        int sequence_idx_end = min(sequence_idx_start+blocklen,num_sequences);\n        //mexPrintf(\"start:%d   end:%d\\n\", sequence_idx_start, sequence_idx_end);\n\n\n        for (int sequence_index=sequence_idx_start; sequence_index < sequence_idx_end; sequence_index++) {\n\n            // NOTE: -1 because Matlab indexing starts at 1\n            int32_t sequence_start = starts[sequence_index] - 1;\n \n            int32_t T = lengths[sequence_index];\n\n            int8_t *data = alldata + num_subparts*sequence_start;\n            int16_t *resources = allresources + sequence_start;\n\n            //// likelihoods\n            double s_likelihoods[2*T];\n            Map<Array2Xd,Aligned> likelihoods(s_likelihoods,2,T);\n\n            likelihoods.setOnes();\n             for (int t=0; t<T; t++) {\n                 for (int n=0; n<num_subparts; n++) {\n                     if (data[n+num_subparts*t] != 0) {                         \n                         likelihoods.col(t) *= Bn.col(2*n + (data[n+num_subparts*t] == 2));\n                     }\n                 }\n             }\n\n            //// forward messages\n            double norm;\n            double s_alpha[2*T] __attribute__((aligned(16)));\n            double contribution;\n            Map<MatrixXd,Aligned> alpha(s_alpha,2,T);\n            alpha.col(0) = initial_distn * likelihoods.col(0);\n            norm = alpha.col(0).sum();\n            alpha.col(0) /= norm;\n            contribution = log(norm);\n            if(normalizeLengths) {\n                contribution = contribution / T;\n            }\n            loglike += contribution;\n                \n            for (int t=0; t<T-1; t++) {\n                alpha.col(t+1) = (As.block(0,2*(resources[t]-1),2,2) * alpha.col(t)).array()\n                    * likelihoods.col(t+1);\n                norm = alpha.col(t+1).sum();\n                alpha.col(t+1) /= norm;\n                contribution = log(norm);\n                if(normalizeLengths) {\n                    contribution = contribution / T;\n                }\n                loglike += contribution;\n            }\n\n            //// backward messages and statistic counting\n\n            double s_gamma[2*T] __attribute__((aligned(16)));\n            Map<Array2Xd,Aligned> gamma(s_gamma,2,T);\n            gamma.col(T-1) = alpha.col(T-1);\n            for (int n=0; n<num_subparts; n++) {\n                if (data[n+num_subparts*(T-1)] != 0) {\n                    emission_softcounts.col(2*n + (data[n+num_subparts*(T-1)] == 2)) += gamma.col(T-1);\n                }\n            }\n\n            for (int t=T-2; t>=0; t--) {\n\n                Matrix2d A = As.block(0,2*(resources[t]-1),2,2);\n                Array22d pair = A.array();\n                pair.rowwise() *= alpha.col(t).transpose().array();\n                pair.colwise() *= gamma.col(t+1);\n                pair.colwise() /= (A*alpha.col(t)).array();\n                pair = (pair != pair).select(0.,pair); // NOTE: replace NaNs\n                trans_softcounts.block(0,2*(resources[t]-1),2,2) += pair;\n\n                gamma.col(t) = pair.colwise().sum().transpose();\n                // NOTE: we have to touch the data again here\n                for (int n=0; n<num_subparts; n++) {\n                    if (data[n+num_subparts*t] != 0) {\n                        emission_softcounts.col(2*n + (data[n+num_subparts*t] == 2)) += gamma.col(t);\n                    }\n                }\n            }\n            init_softcounts += gamma.col(0);\n\n            switch (nlhs)\n            {\n                case 4:\n                    likelihoods_out.block(0,sequence_start,2,T) = likelihoods;\n                case 3:\n                    gamma_out.block(0,sequence_start,2,T) = gamma;\n                case 2:\n                    alpha_out.block(0,sequence_start,2,T) = alpha;\n            }\n        }\n\n        #pragma omp critical\n        {\n            all_trans_softcounts += trans_softcounts;\n            all_emission_softcounts += emission_softcounts;\n            all_initial_softcounts += init_softcounts;\n            *total_loglike += loglike;\n        }\n    }\n     \n }\n\n", "meta": {"hexsha": "4611817743a62717689133b035afbcb73628f320", "size": 10789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "+fit/E_step.cpp", "max_stars_repo_name": "CAHLR/xBKT", "max_stars_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-10-10T19:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T06:28:17.000Z", "max_issues_repo_path": "+fit/E_step.cpp", "max_issues_repo_name": "CAHLR/xBKT", "max_issues_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "+fit/E_step.cpp", "max_forks_repo_name": "CAHLR/xBKT", "max_forks_repo_head_hexsha": "73fae02218094a8cf1896992308e2b495d7c610a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-01T21:14:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-18T09:39:08.000Z", "avg_line_length": 38.9494584838, "max_line_length": 106, "alphanum_fraction": 0.5484289554, "num_tokens": 2847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.031143832558095677, "lm_q1q2_score": 0.01233508065203075}}
{"text": "// (C) Copyright 2007-2009 Andrew Sutton\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GRAPH_DEGREE_CENTRALITY_HPP\r\n#define BOOST_GRAPH_DEGREE_CENTRALITY_HPP\r\n\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/concept/assert.hpp>\r\n\r\nnamespace boost\r\n{\r\n\r\ntemplate < typename Graph > struct degree_centrality_measure\r\n{\r\n    typedef typename graph_traits< Graph >::degree_size_type degree_type;\r\n    typedef typename graph_traits< Graph >::vertex_descriptor vertex_type;\r\n};\r\n\r\ntemplate < typename Graph >\r\nstruct influence_measure : public degree_centrality_measure< Graph >\r\n{\r\n    typedef degree_centrality_measure< Graph > base_type;\r\n    typedef typename base_type::degree_type degree_type;\r\n    typedef typename base_type::vertex_type vertex_type;\r\n\r\n    inline degree_type operator()(vertex_type v, const Graph& g)\r\n    {\r\n        BOOST_CONCEPT_ASSERT((IncidenceGraphConcept< Graph >));\r\n        return out_degree(v, g);\r\n    }\r\n};\r\n\r\ntemplate < typename Graph >\r\ninline influence_measure< Graph > measure_influence(const Graph&)\r\n{\r\n    return influence_measure< Graph >();\r\n}\r\n\r\ntemplate < typename Graph >\r\nstruct prestige_measure : public degree_centrality_measure< Graph >\r\n{\r\n    typedef degree_centrality_measure< Graph > base_type;\r\n    typedef typename base_type::degree_type degree_type;\r\n    typedef typename base_type::vertex_type vertex_type;\r\n\r\n    inline degree_type operator()(vertex_type v, const Graph& g)\r\n    {\r\n        BOOST_CONCEPT_ASSERT((BidirectionalGraphConcept< Graph >));\r\n        return in_degree(v, g);\r\n    }\r\n};\r\n\r\ntemplate < typename Graph >\r\ninline prestige_measure< Graph > measure_prestige(const Graph&)\r\n{\r\n    return prestige_measure< Graph >();\r\n}\r\n\r\ntemplate < typename Graph, typename Vertex, typename Measure >\r\ninline typename Measure::degree_type degree_centrality(\r\n    const Graph& g, Vertex v, Measure measure)\r\n{\r\n    BOOST_CONCEPT_ASSERT((DegreeMeasureConcept< Measure, Graph >));\r\n    return measure(v, g);\r\n}\r\n\r\ntemplate < typename Graph, typename Vertex >\r\ninline typename graph_traits< Graph >::degree_size_type degree_centrality(\r\n    const Graph& g, Vertex v)\r\n{\r\n    return degree_centrality(g, v, measure_influence(g));\r\n}\r\n\r\n// These are alias functions, intended to provide a more expressive interface.\r\n\r\ntemplate < typename Graph, typename Vertex >\r\ninline typename graph_traits< Graph >::degree_size_type influence(\r\n    const Graph& g, Vertex v)\r\n{\r\n    return degree_centrality(g, v, measure_influence(g));\r\n}\r\n\r\ntemplate < typename Graph, typename Vertex >\r\ninline typename graph_traits< Graph >::degree_size_type prestige(\r\n    const Graph& g, Vertex v)\r\n{\r\n    return degree_centrality(g, v, measure_prestige(g));\r\n}\r\n\r\ntemplate < typename Graph, typename CentralityMap, typename Measure >\r\ninline void all_degree_centralities(\r\n    const Graph& g, CentralityMap cent, Measure measure)\r\n{\r\n    BOOST_CONCEPT_ASSERT((VertexListGraphConcept< Graph >));\r\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n    typedef typename graph_traits< Graph >::vertex_iterator VertexIterator;\r\n    BOOST_CONCEPT_ASSERT((WritablePropertyMapConcept< CentralityMap, Vertex >));\r\n    typedef typename property_traits< CentralityMap >::value_type Centrality;\r\n\r\n    VertexIterator i, end;\r\n    for (boost::tie(i, end) = vertices(g); i != end; ++i)\r\n    {\r\n        Centrality c = degree_centrality(g, *i, measure);\r\n        put(cent, *i, c);\r\n    }\r\n}\r\n\r\ntemplate < typename Graph, typename CentralityMap >\r\ninline void all_degree_centralities(const Graph& g, CentralityMap cent)\r\n{\r\n    all_degree_centralities(g, cent, measure_influence(g));\r\n}\r\n\r\n// More helper functions for computing influence and prestige.\r\n// I hate the names of these functions, but influence and prestige\r\n// don't pluralize too well.\r\n\r\ntemplate < typename Graph, typename CentralityMap >\r\ninline void all_influence_values(const Graph& g, CentralityMap cent)\r\n{\r\n    all_degree_centralities(g, cent, measure_influence(g));\r\n}\r\n\r\ntemplate < typename Graph, typename CentralityMap >\r\ninline void all_prestige_values(const Graph& g, CentralityMap cent)\r\n{\r\n    all_degree_centralities(g, cent, measure_prestige(g));\r\n}\r\n\r\n} /* namespace boost */\r\n\r\n#endif\r\n", "meta": {"hexsha": "a9611623b17a6da5cd2a930e8bb6e4b0208920eb", "size": 4371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/degree_centrality.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/degree_centrality.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/degree_centrality.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": 32.1397058824, "max_line_length": 81, "alphanum_fraction": 0.7275223061, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.396068180531364, "lm_q2_score": 0.031143829073493886, "lm_q1q2_score": 0.01233507971591852}}
{"text": "/*******************************************************************************\n *\n * Construction and management of weak topological orderings (WTOs).\n *\n * The construction of weak topological orderings is based on F. Bourdoncle's\n * paper: \"Efficient chaotic iteration strategies with widenings\", Formal\n * Methods in Programming and Their Applications, 1993, pages 128-141.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n * Contributors: 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 <vector>\n#include <set>\n#include <unordered_map>\n#include <memory>\n#include <boost/iterator/indirect_iterator.hpp>\n#include <boost/container/slist.hpp>\n\n#include <crab/common/types.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/domains/interval.hpp>\n\n// Define RECURSIVE_WTO to use older, recursive version.  It is\n// retained for a while for performance comparison purposes.\n// #define RECURSIVE_WTO\n\nnamespace ikos {\n\n  template<typename G>\n  class wto;\n\n  template<typename G>\n  class wto_vertex;\n\n  template<typename G>\n  class wto_cycle;\n\n  template<typename G>\n  class wto_component_visitor;\n\n  template<typename G>\n  class wto_nesting {\n    \n    friend class wto<G>;\n    friend class wto_vertex<G>;\n    friend class wto_cycle<G>;\n    \n  public:\n    typedef wto_nesting<G> wto_nesting_t;\n    \n  private:\n    typedef std::vector<typename boost::graph_traits<G>::vertex_descriptor> node_list_t;\n    typedef std::shared_ptr<node_list_t> node_list_ptr;\n\n    node_list_ptr _nodes;\n    \n  public:\n    typedef typename node_list_t::iterator iterator;\n    typedef typename node_list_t::const_iterator const_iterator;\n    \n  private:\n    wto_nesting(node_list_ptr l): _nodes(std::make_shared<node_list_t>(*l)) { }\n\n    int compare(wto_nesting_t& other) const {\n      const_iterator this_it = this->begin(), other_it = other.begin();\n      while (this_it != this->end()) {\n\tif (other_it == other.end()) {\n\t  return 1;\n\t} else if (*this_it == *other_it) {\n\t  ++this_it;\n\t  ++other_it;\n\t} else {\n\t  return 2; // Nestings are not comparable\n\t}\n      }\n      if (other_it == other.end()) {\n\treturn 0;\n      } else {\n\treturn -1;\n      }\n    }\n    \n  public:\n    wto_nesting(): _nodes(std::make_shared<node_list_t>()) { }\n\n    void operator+=(typename boost::graph_traits<G>::vertex_descriptor n) {\n      this->_nodes = std::make_shared<node_list_t>(*(this->_nodes));\n      this->_nodes->push_back(n);\n    }\n    \n    wto_nesting_t operator+(typename boost::graph_traits<G>::vertex_descriptor n) {\n      wto_nesting_t res(this->_nodes);\n      res._nodes->push_back(n);\n      return res;\n    }\n\n    iterator begin() {\n      return _nodes->begin();\n    }\n\n    iterator end() {\n      return _nodes->end();\n    }\n\n    const_iterator begin() const {\n      return _nodes->begin();\n    }\n\n    const_iterator end() const {\n      return _nodes->end();\n    }\n    \n    wto_nesting_t operator^(wto_nesting_t other) const {\n      wto_nesting_t res;\n      for (const_iterator this_it = this->begin(), other_it = other.begin(); \n           this_it != this->end() && other_it != other.end(); \n           ++this_it, ++other_it) {\n        if (*this_it == *other_it) {\n          res._nodes->push_back(*this_it);\n        } else {\n          break;\n        }\n      }\n      return res;\n    }\n    \n    bool operator<=(wto_nesting_t other) const {\n      return this->compare(other) <= 0;\n    }\n    \n    bool operator==(wto_nesting_t other) const {\n      return this->compare(other) == 0;\n    }\n    \n    bool operator>=(wto_nesting_t other) const {\n      return this->operator<=(other, *this);\n    }\n    \n    bool operator>(wto_nesting_t other) const {\n      return this->compare(other) == 1;\n    }\n    \n    void write(crab::crab_os& o) const {\n      o << \"[\";\n      for (const_iterator it = this->begin(); it != this->end(); ) {\n\ttypename boost::graph_traits<G>::vertex_descriptor n = *it;\n\to << n;\n\t++it;\n\tif (it != this->end()) {\n\t  o << \", \";\n\t}\n      }\n      o << \"]\";\n    }\n  }; // class nesting\n\n  template<typename G>\n  inline crab::crab_os& operator<<(crab::crab_os& o, const wto_nesting<G>& n) {\n    n.write(o);\n    return o;\n  }\n\n  template<typename G>\n  class wto_component {\n\n  public:\n    typedef wto_nesting<G> wto_nesting_t;\n    \n    virtual void accept(wto_component_visitor<G> *) = 0;\n\n    virtual ~wto_component() { }\n\n    virtual void write(crab::crab_os& os) const = 0;\n\n  }; // class wto_component\n\n  template<typename G>\n  inline crab::crab_os& operator<<(crab::crab_os& o, const wto_component<G>& c) {\n    c.write(o);\n    return o;\n  }\n\n  template<typename G>\n  class wto_vertex: public wto_component<G> {\n\n    friend class wto<G>;\n\n  private:\n    typename boost::graph_traits<G>::vertex_descriptor _node;\n\n    wto_vertex(typename boost::graph_traits<G>::vertex_descriptor node): _node(node) { }\n\n  public:\n    typename boost::graph_traits<G>::vertex_descriptor node() {\n      return this->_node;\n    }\n\n    void accept(wto_component_visitor<G> *v) {\n      v->visit(*this);\n    }\n    \n    void write(crab::crab_os& o) const {\n      o <<this->_node;\n    }   \n\n  }; // class wto_vertex\n\n  template<typename G>\n  class wto_cycle: public wto_component<G> {\n\n    friend class wto<G>;\n    \n  public:\n    typedef wto_component<G> wto_component_t;\n    \n  private:\n    typedef std::shared_ptr<wto_component_t> wto_component_ptr;\n    typedef boost::container::slist<wto_component_ptr> wto_component_list_t;\n    typedef std::shared_ptr<wto_component_list_t> wto_component_list_ptr;\n\n    typename boost::graph_traits<G>::vertex_descriptor _head;\n    wto_component_list_ptr _wto_components;\n    // number of times the wto cycle is analyzed by the fixpoint iterator\n    unsigned _num_fixpo;\n    \n    wto_cycle(typename boost::graph_traits<G>::vertex_descriptor head, \n              wto_component_list_ptr wto_components): \n      _head(head), _wto_components(wto_components), _num_fixpo(0) { }\n    \n  public:\n\n    typedef boost::indirect_iterator<typename wto_component_list_t::iterator> iterator;\n    typedef boost::indirect_iterator<typename wto_component_list_t::const_iterator> const_iterator;\n    \n    typename boost::graph_traits<G>::vertex_descriptor head() {\n      return this->_head;\n    }\n    \n    void accept(wto_component_visitor<G> *v) {\n      v->visit(*this);\n    }\n    \n    iterator begin() {\n      return boost::make_indirect_iterator(_wto_components->begin());\n    }\n    \n    iterator end() {\n      return boost::make_indirect_iterator(_wto_components->end());      \n    }\n\n    const_iterator begin() const {\n      return boost::make_indirect_iterator(_wto_components->begin());\n    }\n    \n    const_iterator end() const {\n      return boost::make_indirect_iterator(_wto_components->end());      \n    }\n    \n    void increment_fixpo_visits () {\n      _num_fixpo++;\n    }\n\n    unsigned get_fixpo_visits () const {\n      return _num_fixpo;\n    }\n    \n    void write(crab::crab_os& o) const {\n      o << \"(\" << this->_head;\n      if (!this->_wto_components->empty()) {\n\to << \" \";\n\tfor (const_iterator it = this->begin(); it != this->end(); ) {\n\t  const wto_component_t& c = *it;\n\t  o << c;\n\t  ++it;\n\t  if (it != this->end()) {\n\t    o << \" \";\n\t  }\n\t}\n      }\n      o << \")\";\n      if (this->_num_fixpo > 0)\n\to << \"^{\" << this->_num_fixpo << \"}\";\n    }\n    \n  }; // class wto_cycle\n  \n  template<typename G>\n  class wto_component_visitor {\n\n  public:\n    typedef wto_vertex<G> wto_vertex_t;\n    typedef wto_cycle<G> wto_cycle_t;\n\n    virtual void visit(wto_vertex_t&) = 0;\n    virtual void visit(wto_cycle_t&) = 0;\n    virtual ~wto_component_visitor() {}\n\n  }; // class wto_component_visitor\n\n  template<typename G>\n  class wto {\n    \n  public:\n    typedef wto_nesting<G> wto_nesting_t;\n    typedef wto_component<G> wto_component_t;\n    typedef wto_vertex<G> wto_vertex_t;\n    typedef wto_cycle<G> wto_cycle_t;\n    typedef wto<G> wto_t;\n    \n  private:\n    typedef std::shared_ptr<wto_component_t> wto_component_ptr;\n    typedef std::shared_ptr<wto_vertex_t> wto_vertex_ptr;\n    typedef std::shared_ptr<wto_cycle_t> wto_cycle_ptr;\n    typedef boost::container::slist<wto_component_ptr> wto_component_list_t;\n    typedef std::shared_ptr<wto_component_list_t> wto_component_list_ptr;\n    typedef bound<z_number> dfn_t;\n    typedef std::unordered_map<typename boost::graph_traits<G>::vertex_descriptor, dfn_t> dfn_table_t;\n    typedef std::shared_ptr<dfn_table_t> dfn_table_ptr;\n    typedef std::vector<typename boost::graph_traits<G>::vertex_descriptor> stack_t;\n    typedef std::shared_ptr<stack_t> stack_ptr;\n    typedef std::unordered_map<typename boost::graph_traits<G>::vertex_descriptor, wto_nesting_t> nesting_table_t;\n    typedef std::shared_ptr<nesting_table_t> nesting_table_ptr;\n    \n    wto_component_list_ptr _wto_components;\n    dfn_table_ptr _dfn_table;\n    dfn_t _num;\n    stack_ptr _stack;\n    nesting_table_ptr _nesting_table;\n\n    class nesting_builder: public wto_component_visitor<G> {\n      \n    public:\n      typedef wto_vertex<G> wto_vertex_t;\n      typedef wto_cycle<G> wto_cycle_t;\n      \n    private:\n      wto_nesting_t _nesting;\n      nesting_table_ptr _nesting_table;\n      \n    public:\n      nesting_builder(nesting_table_ptr nesting_table): \n\t_nesting_table(nesting_table) { }\n\n      void visit(wto_cycle_t& cycle) {\n        typename boost::graph_traits<G>::vertex_descriptor head = cycle.head();\n        wto_nesting_t previous_nesting = this->_nesting;\n        this->_nesting_table->insert(std::make_pair(head, this->_nesting));\n        this->_nesting += head;\n        for (typename wto_cycle_t::iterator it = cycle.begin(); it != cycle.end(); ++it) {\n          it->accept(this);\n        }\n        this->_nesting = previous_nesting;\n      }\n      \n      void visit(wto_vertex_t& vertex) {\n        this->_nesting_table->insert(std::make_pair(vertex.node(), this->_nesting));\n      }\n      \n    }; // class nesting_builder\n\n    dfn_t get_dfn(typename boost::graph_traits<G>::vertex_descriptor n) {\n      typename dfn_table_t::iterator it = this->_dfn_table->find(n);\n      if (it == this->_dfn_table->end()) {\n        return 0;\n      } else {\n        return it->second;\n      }\n    }\n    \n    void set_dfn(typename boost::graph_traits<G>::vertex_descriptor n, dfn_t dfn) {\n      std::pair<typename dfn_table_t::iterator, bool> res = \n\tthis->_dfn_table->insert(std::make_pair(n, dfn));\n      if (!res.second) {\n        (res.first)->second = dfn;\n      }\n    }\n    \n    typename boost::graph_traits<G>::vertex_descriptor pop() {\n      if (this->_stack->empty()) {\n        CRAB_ERROR(\"WTO computation: empty stack\");\n      } else {\n        typename boost::graph_traits<G>::vertex_descriptor top = this->_stack->back();\n        this->_stack->pop_back();\n        return top;\n      }\n    }\n\n    void push(typename boost::graph_traits<G>::vertex_descriptor n) {\n      this->_stack->push_back(n);\n    }\n\n    wto_cycle_ptr component(G g, typename boost::graph_traits<G>::vertex_descriptor vertex) {\n      auto partition = std::make_shared<wto_component_list_t>();\n      std::pair<typename boost::graph_traits<G>::out_edge_iterator,\n\t\ttypename boost::graph_traits<G>::out_edge_iterator>\n\tsucc_edges = out_edges(vertex, g);\n      for (typename boost::graph_traits<G>::out_edge_iterator it = succ_edges.first,\n\t     et = succ_edges.second; it!=et; ++it) {\n\ttypename boost::graph_traits<G>::vertex_descriptor succ = target(*it, g);\n        if (this->get_dfn(succ) == 0) {\n          this->visit(g, succ, partition);\n        }\n      }\n      return wto_cycle_ptr(new wto_cycle_t(vertex, partition));\n    }\n    \n    #ifndef RECURSIVE_WTO\n    struct visit_stack_elem {\n      typedef typename boost::graph_traits<G>::out_edge_iterator succ_iterator;\n      typename boost::graph_traits<G>::vertex_descriptor _node;\n      succ_iterator _it; // begin iterator for node's successors\n      succ_iterator _et; // end iterator for node's successors\n      dfn_t _min;        // smallest dfn number of any (direct or\n\t\t\t // indirect) node's successor through node's\n\t\t\t // DFS subtree, included node.\n      \n      visit_stack_elem(typename boost::graph_traits<G>::vertex_descriptor node,\n\t\t       std::pair<succ_iterator, succ_iterator> succs, dfn_t min)\n\t: _node(node)\n\t, _it(succs.first)\n\t, _et(succs.second)\n\t, _min(min) {}\n    };\n    \n    void visit(G g, typename boost::graph_traits<G>::vertex_descriptor vertex,\n\t       wto_component_list_ptr partition) {\n      \n      std::vector<visit_stack_elem> visit_stack;\n      std::set<typename boost::graph_traits<G>::vertex_descriptor> loop_nodes;\n      \n      /* discover vertex */\n      push(vertex);\n      _num += 1;\n      set_dfn(vertex, _num);\n      \n      visit_stack.push_back(visit_stack_elem(vertex, out_edges(vertex, g), _num));\n      CRAB_LOG(\"wto-nonrec\",\n\t       crab::outs() << \"WTO: Node \" << vertex << \": dfs num=\" << _num << \"\\n\";);      \n      while (!visit_stack.empty()) {\n\t/*\n\t * Perform dfs.\n\t * \n\t * When this loop terminates, visit_stack.back()_node's children\n\t * have been processed.  For each loop iteration we push in\n\t * visit_stack one more descendant.\n\t */\n\twhile (visit_stack.back()._it != visit_stack.back()._et) {\n\t  typename boost::graph_traits<G>::edge_descriptor e = *visit_stack.back()._it++;\n\t  typename boost::graph_traits<G>::vertex_descriptor child = target(e, g);\n\t  dfn_t child_dfn = get_dfn(child);\n\t  if (child_dfn == 0) {\n\t    /* discover new vertex */\n\t    push(child);\n\t    _num += 1;\n\t    set_dfn(child, _num);\n\t    visit_stack.push_back(visit_stack_elem(child, out_edges(child, g), _num));\n\t    CRAB_LOG(\"wto-nonrec\",\n\t\t     crab::outs() << \"WTO: Node \" << child << \": dfs num=\" << _num << \"\\n\";);\n\t  } else {\n\t    if (child_dfn <= visit_stack.back()._min) {\n\t      visit_stack.back()._min = child_dfn;\n\t      CRAB_LOG(\"wto-nonrec\",\n\t\t       crab::outs() << \"WTO: loop found \" << child << \"\\n\";);\n\t      loop_nodes.insert(child);\n\t    }\n\t  }\n\t}\n\t\n\n\t// propagate min from child to parent\n\ttypename boost::graph_traits<G>::vertex_descriptor visiting_node =\n\t  visit_stack.back()._node;\n\tdfn_t min_visiting_node = visit_stack.back()._min;\n\tbool is_loop = loop_nodes.count(visiting_node)> 0;\n\tvisit_stack.pop_back();\n\tif (!visit_stack.empty() && visit_stack.back()._min > min_visiting_node) {\n\t  visit_stack.back()._min = min_visiting_node;\n\t}\n\n\tauto dfn_visiting_node = get_dfn(visiting_node);\n\tCRAB_LOG(\"wto-nonrec\",\n\t    crab::outs() << \"WTO: popped node \" << visiting_node\n\t                 << \" dfs num= \" <<  dfn_visiting_node \n\t                 << \": min=\" << min_visiting_node << \"\\n\";);\n\t\n\tif (min_visiting_node == get_dfn(visiting_node)) {\n\t  CRAB_LOG(\"wto-nonrec\",\n\t\t   crab::outs() << \"WTO: BEGIN building partition for node \"\n\t                        << visiting_node << \"\\n\";);\n\t  set_dfn(visiting_node, dfn_t::plus_infinity());\n\t  typename boost::graph_traits<G>::vertex_descriptor element = pop();\n\t  if (is_loop) {\n\t    while (!(element == visiting_node)) {\n\t      set_dfn(element, 0);\n\t      CRAB_LOG(\"wto-nonrec\",\n\t\t       crab::outs () << \"\\tWTO: node \" << element << \": dfn num=0\\n\";);\n\t      element = pop();\n\t    }\n\t    CRAB_LOG(\"wto-nonrec\",\n\t\t     crab::outs() << \"\\tWTO: adding component starting from \"\n\t\t                 << visiting_node << \"\\n\";);\n\t    partition->push_front(std::static_pointer_cast<wto_component_t,wto_cycle_t> \n\t\t\t\t  (component(g, visiting_node)));\n\t  } else {\n\t    CRAB_LOG(\"wto-nonrec\",\n\t\t     crab::outs() << \"\\tWTO: adding vertex \" << visiting_node << \"\\n\";);\n\t    partition->push_front(std::static_pointer_cast< wto_component_t, wto_vertex_t>\n\t\t\t\t  (wto_vertex_ptr(new wto_vertex_t(visiting_node))));\n\t  }\n\t  CRAB_LOG(\"wto-nonrec\", crab::outs() << \"WTO: END building partition\\n\";);\n\t}\n      } // end while (!visit_stack.empty())\n    }\n    \n    #else\n    dfn_t visit(G g,\n\t\ttypename boost::graph_traits<G>::vertex_descriptor vertex,\n\t\twto_component_list_ptr partition) {\n      dfn_t head = 0, min = 0;\n      bool loop;\n      typename boost::graph_traits<G>::vertex_descriptor element;\n\n      this->push(vertex);\n      this->_num += 1;\n      head = this->_num;\n      this->set_dfn(vertex, head);\n      loop = false;\n\n      std::pair<typename boost::graph_traits<G>::out_edge_iterator,\n\t\ttypename boost::graph_traits<G>::out_edge_iterator>\n\tsucc_edges = out_edges(vertex, g);\n      for (typename boost::graph_traits<G>::out_edge_iterator it = succ_edges.first,\n\t     et = succ_edges.second; it!=et; ++it) {\n\ttypename boost::graph_traits<G>::vertex_descriptor succ = target(*it, g);\n        dfn_t succ_dfn = this->get_dfn(succ);\n        if (succ_dfn == 0) {\n          min = this->visit(g, succ, partition);\n        } else {\n          min = succ_dfn;\n        }\n        if (min <= head) {\n          head = min;\n\t  loop = true;\n        }\n      }\n      if (head == this->get_dfn(vertex)) {\n        this->set_dfn(vertex, dfn_t::plus_infinity());\n        element = this->pop();\n        if (loop) {\n          while (!(element == vertex)) {\n            this->set_dfn(element, 0);\n            element = this->pop();\n          }\n          partition->push_front(std::static_pointer_cast<wto_component_t, \n                                wto_cycle_t>(this->component(g, vertex)));\n        } else {\n          partition->push_front(std::static_pointer_cast<wto_component_t, \n                                wto_vertex_t>(wto_vertex_ptr(new wto_vertex_t(vertex))));\n\t}\n      }\n      return head;\n    }\n    #endif\n    \n    void build_nesting() {\n      nesting_builder builder(this->_nesting_table);\n      for (iterator it = this->begin(); it != this->end(); ++it) {\n        it->accept(&builder);\n      }\n    }\n\n  public:\n\n    typedef boost::indirect_iterator<typename wto_component_list_t::iterator> iterator;\n    typedef boost::indirect_iterator<typename wto_component_list_t::const_iterator> const_iterator;\n    \n    wto(G g): \n      _wto_components(std::make_shared<wto_component_list_t>()), \n      _dfn_table(std::make_shared<dfn_table_t>()), \n      _num(0), _stack(std::make_shared<stack_t>()), \n      _nesting_table(std::make_shared<nesting_table_t>()) {\n      crab::ScopedCrabStats __st__(\"Fixpo.WTO\");\n\n      this->visit(g, entry(g), this->_wto_components);\n      this->_dfn_table.reset();\n      this->_stack.reset();\n      this->build_nesting();\n    }\n\n    // deep copy\n    wto(const wto_t &other):\n      _wto_components(std::make_shared<wto_component_list_t>(*other._wto_components)),\n      _dfn_table(other._dfn_table ?\n\t\t std::make_shared<dfn_table_t>(*other._dfn_table):\n\t\t nullptr),\n      _num(other._num),\n      _stack(other._stack ?\n\t     std::make_shared<stack_t>(*other._stack):\n\t     nullptr),\n      _nesting_table(std::make_shared<nesting_table_t>(*other._nesting_table)) { }\n\n    wto(const wto_t &&other):\n      _wto_components(std::move(other._wto_components)),\n      _dfn_table(std::move(other._dfn_table)),\n      _num(other._num),\n      _stack(std::move(other._stack)),\n      _nesting_table(std::move(other._nesting_table)) { }      \n      \n    wto_t& operator=(const wto_t &other) {\n      if (this != &other) {\n\tthis->_wto_components = other._wto_components;\n\tthis->_dfn_table = other._dfn_table;\n\tthis->_num = other._num;\n\tthis->_stack = other._stack;\n\tthis->_nesting_table = other._nesting_table;\n      }\n      return *this;\n    }\n\n    iterator begin() {\n      return boost::make_indirect_iterator(_wto_components->begin());\n    }\n    \n    iterator end() {\n      return boost::make_indirect_iterator(_wto_components->end());      \n    }\n\n    const_iterator begin() const {\n      return boost::make_indirect_iterator(_wto_components->begin());\n    }\n    \n    const_iterator end() const {\n      return boost::make_indirect_iterator(_wto_components->end());      \n    }\n\n\n    wto_nesting_t nesting(typename boost::graph_traits<G>::vertex_descriptor n) {\n      typename nesting_table_t::iterator it = this->_nesting_table->find(n);\n      if (it == this->_nesting_table->end()) {\n        CRAB_ERROR(\"WTO nesting: node \", n,\" not found\");\n      } else {\n        return it->second;\n      }\n    }\n\n    void accept(wto_component_visitor<G> *v) {\n      for (iterator it = this->begin(); it != this->end(); ++it) {\n        it->accept(v);\n      }\n    }\n    \n    void write(crab::crab_os& o) const {\n      for (const_iterator it = this->begin(); it != this->end(); ) {\n        const wto_component_t& c = *it;\n        o << c;\n        ++it;\n        if (it != this->end()) {\n          o << \" \";\n        }\n      }      \n    }\n    \n    friend crab::crab_os& operator<<(crab::crab_os &o, const wto_t &wto) {\n      wto.write(o);\n      return o;\n    }    \n    \n  }; // class wto\n\n} // namespace ikos\n\n", "meta": {"hexsha": "04c69429efd8148587d3c86aeb6557f9447216b7", "size": 22522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/iterators/wto.hpp", "max_stars_repo_name": "numairmansur/crab", "max_stars_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "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/iterators/wto.hpp", "max_issues_repo_name": "numairmansur/crab", "max_issues_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_issues_repo_licenses": ["Apache-2.0"], "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/iterators/wto.hpp", "max_forks_repo_name": "numairmansur/crab", "max_forks_repo_head_hexsha": "316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7658674189, "max_line_length": 114, "alphanum_fraction": 0.6398188438, "num_tokens": 5828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069439597968646, "lm_q2_score": 0.039638840235472976, "lm_q1q2_score": 0.01231556552429557}}
{"text": "/*  $Id: voronoidiagram.cpp 752 2011-06-07 12:51:45Z anders.e.e.wallin $\n * \n *  Copyright 2010-2011 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 <boost/foreach.hpp>\n\n#include \"voronoidiagram.hpp\"\n#include \"numeric.h\"\n\nnamespace ocl\n{\n\nint VertexProps::count = 0;\n\nVoronoiDiagram::VoronoiDiagram(double far, unsigned int n_bins) {\n    fgrid = new FaceGrid(far, n_bins);\n    far_radius=far;\n    gen_count=3;\n    init();\n}\n\nVoronoiDiagram::~VoronoiDiagram() { \n    delete fgrid; \n}\n\n// add one vertex at origo and three vertices at 'infinity' and their associated edges\nvoid VoronoiDiagram::init() {\n    //std::cout << \"VD init() \\n\";\n    double far_multiplier = 6;\n    // add vertices\n    HEVertex v0;\n    VertexProps v0prop(Point(0,0), UNDECIDED);\n    VertexProps v1prop(Point(0, far_multiplier*far_radius), OUT);\n    VertexProps v2prop(Point( cos(-5*PI/6)*far_multiplier*far_radius, sin(-5*PI/6)*far_multiplier*far_radius), OUT);\n    VertexProps v3prop(Point( cos(-PI/6)*far_multiplier*far_radius, sin(-PI/6)*far_multiplier*far_radius), OUT);\n    v0  = hedi::add_vertex( v0prop, g );\n    v01 = hedi::add_vertex( v1prop, g );\n    v02 = hedi::add_vertex( v2prop, g );\n    v03 = hedi::add_vertex( v3prop, g );\n\n    // the locations of the initial generators:\n    double gen_mutliplier = 3;\n    gen2 = Point(cos(PI/6)*gen_mutliplier*far_radius, sin(PI/6)*gen_mutliplier*far_radius);\n    gen3 = Point(cos(5*PI/6)*gen_mutliplier*far_radius, sin(5*PI/6)*gen_mutliplier*far_radius);\n    gen1 = Point( 0,-gen_mutliplier*far_radius);\n    g[v0].set_J( gen1, gen2, gen3 ); // this sets J2,J3,J4 and pk, so that detH(pl) can be called later\n        \n    // add face 1: v0-v1-v2\n    HEEdge e1 =  hedi::add_edge( v0 , v01 , g);   \n    HEEdge e2 =  hedi::add_edge( v01, v02 , g);\n    HEEdge e3 =  hedi::add_edge( v02, v0  , g); \n    HEFace f1 =  hedi::add_face( FaceProps(e2, gen3, NONINCIDENT), g ); \n    fgrid->add_face( g[f1] );\n    g[e1].face = f1;\n    g[e2].face = f1;\n    g[e3].face = f1;\n    g[e1].next = e2;\n    g[e2].next = e3;\n    g[e3].next = e1;\n    \n    // add face 2: v0-v2-v3\n    HEEdge e4 = hedi::add_edge( v0, v02  , g );   \n    HEEdge e5 = hedi::add_edge( v02, v03 , g );\n    HEEdge e6 = hedi::add_edge( v03, v0  , g ); \n    HEFace f2 =  hedi::add_face( FaceProps(e5, gen1, NONINCIDENT), g );\n    fgrid->add_face( g[f2] );\n    g[e4].face = f2;\n    g[e5].face = f2;\n    g[e6].face = f2;\n    g[e4].next = e5;\n    g[e5].next = e6;\n    g[e6].next = e4;\n    \n    // add face 3: v0-v3-v1 \n    HEEdge e7 = hedi::add_edge( v0 , v03 , g);   \n    HEEdge e8 = hedi::add_edge( v03, v01 , g);\n    HEEdge e9 = hedi::add_edge( v01, v0  , g); \n    HEFace f3 =  hedi::add_face( FaceProps(e8, gen2, NONINCIDENT), g );\n    fgrid->add_face( g[f3] );\n    g[e7].face = f3;\n    g[e8].face = f3;\n    g[e9].face = f3;\n    g[e7].next = e8;\n    g[e8].next = e9;\n    g[e9].next = e7;\n    \n    // twin edges\n    g[e1].twin = e9;\n    g[e9].twin = e1;\n    g[e2].twin = HEEdge(); // the outermost edges have invalid twins\n    g[e5].twin = HEEdge();\n    g[e8].twin = HEEdge();\n    g[e3].twin = e4;\n    g[e4].twin = e3;\n    g[e6].twin = e7;\n    g[e7].twin = e6;\n    \n    assert( vdChecker.isValid(this) );\n    //std::cout << \" VD init() done.\\n\";\n}\n\n\n\n// comments relate to Sugihara-Iri paper\n// this is roughly \"algorithm A\" from the paper, page 15/50\nvoid VoronoiDiagram::addVertexSite(const Point& p) {\n    // only add vertices within the far_radius circle\n    assert( p.xyNorm() < far_radius );\n    \n    // 1) find the closest face and associated generator\n    gen_count++;\n    HEFace closest_face = fgrid->grid_find_closest_face( p );\n    \n    // 2) among the vertices on the closest_face\n    //    find the seed, which has the lowest detH\n    HEVertex v_seed = findSeedVertex(closest_face, p);\n    g[v_seed].type = IN;\n    VertexVector v0;\n    v0.push_back(v_seed); \n    \n    // 3) augment the vertex set to be deleted\n    //    vertex set must remain a tree\n    //    must not delete cycles\n    augment_vertex_set_M(v0, p); \n    \n    // 4) add new vertices on all edges that connect v0 IN edges to OUT edges\n    add_new_voronoi_vertices(v0, p);\n    \n    // 5) generate new edges that form a loop around the region to be deleted\n    HEFace newface = split_faces(p);\n    \n    // 6) fix the next-pointers in newface, then remove set v0\n    remove_vertex_set(v0, newface);\n    \n    // 7) reset IN/OUT/UNDECIDED for verts, and INCIDENT/NONINCIDENT for faces\n    reset_labels();\n\n    assert( vdChecker.isValid(this) );\n}\n\nHEFace VoronoiDiagram::split_faces(const Point& p) {\n    HEFace newface =  hedi::add_face( FaceProps( HEEdge(), p, NONINCIDENT ), g );\n    fgrid->add_face( g[newface] );\n    BOOST_FOREACH( HEFace f, incident_faces ) {\n        split_face(newface, f); // each INCIDENT face is split into two parts: newface and f\n    }\n    return newface;\n}\n\nvoid VoronoiDiagram::reset_labels() {\n    BOOST_FOREACH( HEVertex v, in_vertices ) {\n        g[v].reset();\n    }\n    in_vertices.clear();\n    g[v01].type = OUT; // the outer vertices are special.\n    g[v02].type = OUT;\n    g[v03].type = OUT;\n    BOOST_FOREACH(HEFace f, incident_faces ) { \n        g[f].type = NONINCIDENT; \n    }\n    incident_faces.clear();\n}\n\n// remove vertices in the set v0\nvoid VoronoiDiagram::remove_vertex_set(VertexVector& v0 , HEFace newface) {\n    HEEdge current_edge = g[newface].edge; \n    HEEdge start_edge = current_edge;\n    // this repairs the next-pointers for newface that are broken.\n    bool done = false;\n    while (!done) {\n        HEVertex current_target = hedi::target( current_edge , g); // an edge on the new face\n        HEVertex current_source = hedi::source( current_edge , g);\n        BOOST_FOREACH( HEEdge edge, hedi::out_edges( current_target, g ) ) { // loop through potential \"next\" candidates\n            HEVertex out_target = hedi::target( edge , g);\n            if ( g[out_target].type == NEW ) { // the next vertex along the face should be \"NEW\"\n                if ( out_target != current_source ) { // but not where we came from\n                    g[current_edge].next = edge; // this is the edge we want to take\n                    \n                    // current and next should belong on the same face\n                    \n                    if (g[current_edge].face !=  g[ g[current_edge].next ].face) {\n                        std::cout << \" VD remove_vertex_set() ERROR.\\n\";\n                        std::cout << \"current.face = \" << g[current_edge].face << \" IS NOT next_face = \" << g[ g[current_edge].next ].face << std::endl;\n                        HEVertex c_trg = hedi::target( current_edge , g);\n                        HEVertex c_src = hedi::source( current_edge , g);\n                        HEVertex n_trg = hedi::target( g[current_edge].next , g);\n                        HEVertex n_src = hedi::source( g[current_edge].next , g);\n                        \n                        std::cout << \"current_edge = \" << g[c_src].index << \" - \" << g[c_trg].index << \"\\n\";\n                        std::cout << \"next_edge = \" << g[n_src].index << \" - \" << g[n_trg].index << \"\\n\";\n                        \n                        printFaceVertexTypes( g[current_edge].face );\n                        printFaceVertexTypes( g[ g[current_edge].next ].face );\n                        \n                        std::cout << \" printing all incident faces for debug: \\n\";\n                        BOOST_FOREACH( HEFace f, incident_faces ) {\n                            printFaceVertexTypes( f );\n                        } \n                    }\n                    assert( g[current_edge].face ==  g[ g[current_edge].next ].face );\n                }\n            }\n        }\n\n        current_edge = g[current_edge].next; // jump to the next edge\n        if ( g[current_edge].next == start_edge )\n            done = true;\n    }\n    // it should now be safe to delete v0\n    BOOST_FOREACH( HEVertex v, v0 ) { \n        assert( g[v].type == IN );\n        hedi::delete_vertex(v,g); // this also removes edges connecting to v\n    }\n}\n\n// split the face f into one part which is newface, and the other part is the old f\nvoid VoronoiDiagram::split_face(HEFace newface, HEFace f) {\n    HEVertex new_source; // this is found as OUT-NEW-IN\n    HEVertex new_target; // this is found as IN-NEW-OUT\n    // the new vertex on face f connects new_source -> new_target\n    HEEdge current_edge = g[f].edge;                             \n    assert( f == g[current_edge].face );\n    HEEdge start_edge = current_edge;\n    VoronoiVertexType currentType = OUT;\n    VoronoiVertexType nextType  = NEW;\n    HEEdge new_previous;\n    HEEdge new_next;\n    HEEdge twin_next;\n    HEEdge twin_previous;\n    bool found = false;\n    while (!found) {\n        HEVertex current_vertex = hedi::target( current_edge , g);\n        HEEdge next_edge = g[current_edge].next;\n        HEVertex next_vertex = hedi::target( next_edge , g);\n        if ( g[current_vertex].type == currentType ) {\n            if ( g[next_vertex].type == nextType ) {\n                new_source = next_vertex;\n                new_previous = next_edge;\n                twin_next = g[next_edge].next;\n                found = true;\n            }\n        }\n        current_edge = g[current_edge].next;   \n    }\n    found = false;\n    currentType = IN;\n    nextType = NEW;\n    current_edge = g[f].edge; \n    while (!found) {\n        HEVertex current_vertex = hedi::target( current_edge , g);\n        HEEdge next_edge = g[current_edge].next;\n        HEVertex next_vertex = hedi::target( next_edge , g);\n        if ( g[current_vertex].type == currentType ) {\n            if ( g[next_vertex].type == nextType ) {\n                new_target = next_vertex;\n                new_next = g[next_edge].next;\n                twin_previous = next_edge;\n                found = true;\n            }\n        }\n        current_edge = g[current_edge].next;\n    }\n    // now connect new_previous -> new_source -> new_target -> new_next\n    HEEdge e_new = hedi::add_edge( new_source, new_target , g); // face,next,twin\n    g[new_previous].next = e_new;\n    g[e_new].next = new_next;\n    g[e_new].face = f;\n    g[f].edge = e_new; \n    \n    // the twin edge that bounds the new face\n    HEEdge e_twin = hedi::add_edge( new_target, new_source , g);\n    g[twin_previous].next = e_twin;\n    g[e_twin].next = twin_next;\n    g[e_twin].face = newface;\n    g[newface].edge = e_twin; \n    \n    g[e_twin].twin = e_new;\n    g[e_new].twin = e_twin;\n    \n    //assert( isDegreeThree() );\n}\n\nEdgeVector VoronoiDiagram::find_edges(VertexVector& inVertices, VoronoiVertexType vtype) {\n    assert( !inVertices.empty() );\n    EdgeVector output; // new vertices generated on these edges\n    BOOST_FOREACH( HEVertex v, inVertices ) {                                   \n        assert( g[v].type == IN ); // all verts in v0 are IN\n        BOOST_FOREACH( HEEdge edge, hedi::out_edges( v , g) ) {\n            HEVertex adj_vertex = hedi::target( edge , g);\n            if ( g[adj_vertex].type == vtype ) \n                output.push_back(edge); // this is an IN-vtype edge\n        }\n    }\n    return output;\n}\n\n// the set v0 are IN vertices that should be removed\n// generate new voronoi-vertices on all edges connecting v0 to OUT-vertices\nvoid VoronoiDiagram::add_new_voronoi_vertices(VertexVector& v0, const Point& p) {\n    assert( !v0.empty() );\n    EdgeVector q_edges = find_edges(v0, OUT); // new vertices generated on these IN-OUT edges\n    assert( !q_edges.empty() );\n    \n    for( unsigned int m=0; m<q_edges.size(); ++m )  {  // create new vertices on all edges q_edges[]\n        HEVertex q = hedi::add_vertex(g);\n        g[q].type = NEW;\n        in_vertices.push_back(q);\n        HEFace face = g[q_edges[m]].face;     assert(  g[face].type == INCIDENT);\n        HEEdge twin = g[q_edges[m]].twin;\n        HEFace twin_face = g[twin].face;      assert( g[twin_face].type == INCIDENT);\n        g[q].set_J( g[face].generator  , g[twin_face].generator  , p); \n        g[q].set_position();\n        \n        // check new vertex position, should lie between endpoints of q_edges[m]\n        HEVertex trg = hedi::target(q_edges[m], g);\n        HEVertex src = hedi::source(q_edges[m], g);\n        Point trgP = g[trg].position;\n        Point srcP = g[src].position;\n        Point newP = g[q].position;\n        if (( trgP - srcP ).xyNorm() <= 0 ) {\n            /*\n            std::cout << \"add_new_voronoi_vertices() WARNING ( trgP - srcP ).xyNorm()= \" << ( trgP - srcP ).xyNorm() << \"\\n\";\n            std::cout << \" src = \" << srcP << \"\\n\";\n            std::cout << \" trg= \" << trgP << \"\\n\";\n            */\n            //std::cout << \"add_new_voronoi_vertices() WARNING zero-length edge! \\n\";\n            g[q].position = srcP;\n        } else {\n            assert( ( trgP - srcP ).xyNorm() > 0.0 ); // edge has finite length\n            assert( ( trgP - srcP ).dot( trgP - srcP ) > 0.0 ); // length squared\n            double t = ((newP - srcP).dot( trgP - srcP )) / ( trgP - srcP ).dot( trgP - srcP ) ;\n            bool warn = false;\n            //double t_orig=t;\n            if (t < 0.0) {\n                warn = true;\n                t=0.0;\n            } else if (t> 1.0) {\n                warn = true;\n                t=1.0;\n            }\n            if ( warn ) {\n                //std::cout << \"add_new_voronoi_vertices() WARNING positioning vertex outside edge! t_orig= \" << t_orig << \"\\n\";\n                // CORRECT the position....\n                g[q].position = srcP + t*( trgP-srcP);\n                t = ( g[q].position - srcP).dot( trgP - srcP ) / ( trgP - srcP ).dot( trgP - srcP ) ;\n                //std::cout << \"add_new_voronoi_vertices() CORRECTED t= \" << t << \"\\n\";\n            }\n            assert( t >= 0.0 );\n            assert( t <= 1.0 );\n            \n            double dtl = g[q].position.xyDistanceToLine(srcP, trgP);\n            if (dtl > 1e-3* ( trgP - srcP ).xyNorm() ) {\n                //std::cout << \"add_new_voronoi_vertices() WARNING new point far from edge!\\n\";\n                //std::cout << \"add_new_voronoi_vertices() WARNING edge length= \" << ( trgP - srcP ).xyNorm()  << \"\\n\";\n                //std::cout << \"add_new_voronoi_vertices() WARNING distance to edge= \" << dtl  << \"\\n\";\n                t = ( g[q].position - srcP).dot( trgP - srcP ) / ( trgP - srcP ).dot( trgP - srcP ) ;\n                g[q].position = srcP + t*( trgP-srcP);\n                //newP = hed[q].position;\n                dtl = g[q].position.xyDistanceToLine(srcP, trgP);\n                //std::cout << \"add_new_voronoi_vertices() WARNING corrected distance to edge= \" << dtl  << \"\\n\";\n            }\n            assert( dtl < 1e-3* ( trgP - srcP ).xyNorm() );\n        }\n\n        hedi::insert_vertex_in_edge( q, q_edges[m] , g);\n        // sanity check on new vertex\n        assert( g[q].position.xyNorm() < 6.1*far_radius); // see init() for placement of the three initial vertices\n    }\n}\n\n\n\n\n\n\n\n\nint VoronoiDiagram::outVertexCount(HEFace f) {\n    int outCount = 0;\n    VertexVector face_verts = hedi::face_vertices(f, g);\n    BOOST_FOREACH( HEVertex v, face_verts ) {\n        if (g[v].type == OUT )\n            ++outCount;\n    }\n    return outCount;\n}\n\n// check that the vertices TYPE are connected\nbool VoronoiDiagram::faceVerticesConnected( HEFace f, VoronoiVertexType Vtype ) {\n    VertexVector face_verts = hedi::face_vertices(f,g);\n    VertexVector type_verts;\n    BOOST_FOREACH( HEVertex v, face_verts ) {\n        if ( g[v].type == Vtype )\n            type_verts.push_back(v);\n    }\n    assert( !type_verts.empty() );\n    if (type_verts.size()==1) // set of 1 is allways connected\n        return true;\n    \n    // check that type_verts are connected\n    HEEdge currentEdge = g[f].edge;\n    HEVertex endVertex = hedi::source(currentEdge, g); // stop when target here\n    EdgeVector startEdges;\n    bool done = false;\n    while (!done) { \n        HEVertex src = hedi::source( currentEdge, g );\n        HEVertex trg = hedi::target( currentEdge, g );\n        if ( g[src].type != Vtype ) { // seach ?? - Vtype\n            if ( g[trg].type == Vtype ) {\n                // we have found ?? - Vtype\n                startEdges.push_back( currentEdge );\n            }\n        }\n        currentEdge = g[currentEdge].next;\n        if ( trg == endVertex ) {\n            done = true;\n        }\n    }\n    assert( !startEdges.empty() );\n    if ( startEdges.size() != 1 ) // when the Vtype vertices are connected, there is exactly one startEdge\n        return false;\n    else \n        return true;\n}\n\nvoid VoronoiDiagram::printFaceVertexTypes(HEFace f) {\n    std::cout << \" Face \" << f << \": \";\n    VertexVector face_verts = hedi::face_vertices(f,g);    \n    unsigned count=1;\n    BOOST_FOREACH( HEVertex v, face_verts ) {\n        std::cout << g[v].index  << \"(\" << g[v].type  << \")\";\n        if (count != face_verts.size() )\n            std::cout << \"-\";\n        count++;\n    }\n    std::cout << \"\\n\";\n}\n\nvoid VoronoiDiagram::printVertices(VertexVector& q) {\n    BOOST_FOREACH( HEVertex v, q) {\n        std::cout << g[v].index << \" \";\n    }\n    std::cout << std::endl;\n}\n\nvoid VoronoiDiagram::pushAdjacentVertices(  HEVertex v , std::queue<HEVertex>& Q) {\n    VertexVector adj_verts = hedi::adjacent_vertices(v,g);\n    BOOST_FOREACH( HEVertex w, adj_verts ) {\n        if ( g[w].type == UNDECIDED ) {\n            if ( !g[w].in_queue ) { \n                Q.push(w); // push adjacent undecided verts for testing.\n                g[w].in_queue=true;\n            }\n        }\n    }\n}\n\nint VoronoiDiagram::adjacentInCount(HEVertex v) {\n    VertexVector adj_v = hedi::adjacent_vertices(v,g);\n    int in_count=0;\n    BOOST_FOREACH( HEVertex w, adj_v) {\n        if ( g[w].type == IN )\n            in_count++;\n    }\n    return in_count;\n}\nFaceVector VoronoiDiagram::adjacentIncidentFaces(HEVertex v) {\n    FaceVector adj_faces = hedi::adjacent_faces(v,g);\n    assert( adj_faces.size() == 3 );\n    FaceVector inc_faces;\n    BOOST_FOREACH( HEFace f, adj_faces ) {\n        if ( g[f].type == INCIDENT )\n            inc_faces.push_back( f );\n    }\n    assert( !inc_faces.empty() );\n    return inc_faces;\n}\n\nbool VoronoiDiagram::incidentFacesHaveAdjacentInVertex(HEVertex v) {\n    bool all_found = true;\n    BOOST_FOREACH( HEFace f, adjacentIncidentFaces(v) ) { // check each face f\n        // v should be adjacent to an IN vertex on the face\n        // VertexVector face_verts = hed.face_vertices(f);\n        bool face_found=false;\n        BOOST_FOREACH( HEVertex w, hedi::face_vertices(f,g) ) {\n            if ( w != v && g[w].type == IN && hedi::has_edge(w,v,g) ) \n                face_found = true;\n        }\n        if (!face_found)\n            all_found=false;\n    }\n    return all_found;\n}\n\n// from the \"one million\" paper, growing the tree by breadth-first search\nvoid VoronoiDiagram::augment_vertex_set_M(VertexVector& v0, const Point& p) {\n    assert(v0.size()==1);\n    std::queue<HEVertex> Q;\n    // a priority_queue could/should be used here instead.\n    // this woiuld allways examine and decide on the vertex with largest detH, \n    // since that vertex has the most reliable detH sign.\n    in_vertices.push_back( v0[0] );\n    markAdjecentFacesIncident( v0[0] );\n    assert( Q.empty() );\n    pushAdjacentVertices( v0[0] , Q);\n    while( !Q.empty() ) {\n        HEVertex v = Q.front();\n        assert( g[v].type == UNDECIDED );\n        // add to v0 if detH<0 and passes tests. otherwise OUT\n        double h = g[v].detH( p );\n        if ( h < 0.0 ) { // try to mark IN\n            // (C4) v should not be adjacent to two or more IN vertices\n            // (C5) for an incident face containing v: v is adjacent to an IN vertex on this face\n            if ( (adjacentInCount(v) >= 2) || (!incidentFacesHaveAdjacentInVertex(v)) ) {\n                assert( g[v].type == UNDECIDED );\n                g[v].type = OUT;\n                //std::cout << \" v \" << hed[v].index << \" decision is \" << hed[v].type << \" IN_COUNT>=2 \\n\";\n                in_vertices.push_back( v );\n            } else {\n                g[v].type = IN;\n                //std::cout << \" v \" << hed[v].index << \" decision is \" << hed[v].type << \" (h<0)\\n\";\n                in_vertices.push_back( v );\n                v0.push_back( v );\n                markAdjecentFacesIncident( v );\n                pushAdjacentVertices( v , Q);\n            }\n        } else { // mark OUT\n            //std::cout << \" v \" << hed[v].index << \" decision is \" << hed[v].type << \" (h>0)\\n\";\n            assert( h >= 0.0 );\n            assert( g[v].type == UNDECIDED );\n            g[v].type = OUT;\n            in_vertices.push_back( v );\n        }\n        Q.pop(); // delete from queue\n    }\n    \n    BOOST_FOREACH( HEFace f, incident_faces ) {\n        if ( !faceVerticesConnected( f, IN ) ) {\n            std::cout << \" augment_vertex_set_M() ERROR, IN-vertices not connected.\\n\";\n            std::cout << \" printing all incident faces for debug: \\n\";\n            BOOST_FOREACH( HEFace f, incident_faces ) {\n                printFaceVertexTypes( f );\n            } \n        }\n        assert( faceVerticesConnected( f, IN ) );\n    }\n    //std::cout << \" augment_M done:\\n\";\n    //printVertices(v0);\n}\n\n// used by augment_M\nvoid VoronoiDiagram::markAdjecentFacesIncident( HEVertex v) {\n    assert( g[v].type == IN );\n    FaceVector new_adjacent_faces = hedi::adjacent_faces( v, g ); \n    assert( new_adjacent_faces.size()==3 );\n    BOOST_FOREACH( HEFace adj_face, new_adjacent_faces ) {\n        if ( g[adj_face].type  != INCIDENT ) {\n            g[adj_face].type = INCIDENT; \n            incident_faces.push_back(adj_face);\n        }\n    }\n}\n\n// evaluate H on all face vertices and return\n// vertex with the lowest H\nHEVertex VoronoiDiagram::findSeedVertex(HEFace f, const Point& p) {\n    VertexVector face_verts = hedi::face_vertices(f,g);                 \n    assert( face_verts.size() >= 3 ); \n    double minimumH; // safe, because we expect the min H to be negative...\n    HEVertex minimalVertex;\n    double h;\n    bool first = true;\n    BOOST_FOREACH( HEVertex q, face_verts) {\n        if ( g[q].type != OUT ) {\n            h = g[q].detH( p ); \n            //std::cout << \"  detH = \" << h << \" ! \\n\";\n            if ( first || (h<minimumH) ) {\n                minimumH = h;\n                minimalVertex = q;\n                first = false;\n            }\n        }\n    }\n    \n    if (!(minimumH < 0) ) {\n        std::cout << \" VD find_seed_vertex() WARNING\\n\";\n        std::cout << \" WARNING: searching for seed when inserting \" << p  << \"  \\n\";\n        std::cout << \" WARNING: closest face is  \" << f << \" with generator \" << g[f].generator  << \" \\n\";\n        std::cout << \" WARNING: minimal vd-vertex \" << g[minimalVertex].index << \" has deth= \" << g[minimalVertex].detH( p ) << \"\\n\";\n    }\n    //assert( minimumH < 0 );\n    return minimalVertex;\n}\n\nstd::string VoronoiDiagram::str() const {\n    std::ostringstream o;\n    o << \"VoronoiDiagram (nVerts=\"<< hedi::num_vertices(g) << \" , nEdges=\"<< hedi::num_edges(g) <<\"\\n\";\n    return o.str();\n}\n\n} // end namespace\n// end file voronoidiagram.cpp\n", "meta": {"hexsha": "0c81e72380dd4f5cae163e4ddd9963dace7b8fe5", "size": 23722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib-read-only/src/voronoi/voronoidiagram.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/voronoi/voronoidiagram.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/voronoi/voronoidiagram.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": 38.3231017771, "max_line_length": 152, "alphanum_fraction": 0.5672371638, "num_tokens": 6615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.02716923055104719, "lm_q1q2_score": 0.012314775648723738}}
{"text": "#include \"Vertex.h\"\r\n\r\n#include <algorithm>\r\n\r\n#include <boost/spirit/include/qi.hpp>\r\n\r\n#include \"Matrix.h\"\r\n#include \"Vector.h\"\r\n\r\n\r\nVertex::Vertex()\r\n{\r\n\tvertex_[0] = std::numeric_limits<double>::quiet_NaN();\r\n\tvertex_[1] = std::numeric_limits<double>::quiet_NaN();\r\n\tvertex_[2] = std::numeric_limits<double>::quiet_NaN();\r\n}\r\n\r\nVertex::Vertex(double x, double y, double z)\r\n{\r\n\tvertex_[0] = x;\r\n\tvertex_[1] = y;\r\n\tvertex_[2] = z;\r\n}\r\n\r\nVertex::Vertex(std::string_view str)\r\n{\r\n\tparsestr(str);\r\n}\r\n\r\nconst Vertex Vertex::unitX = { 1, 0, 0 };\r\nconst Vertex Vertex::unitY = { 0, 1, 0 };\r\nconst Vertex Vertex::unitZ = { 0, 0, 1 };\r\n\r\nvoid Vertex::x(double x)\r\n{\r\n\tvertex_[0] = x;\r\n}\r\n\r\nvoid Vertex::y(double y)\r\n{\r\n\tvertex_[1] = y;\r\n}\r\n\r\nvoid Vertex::z(double z)\r\n{\r\n\tvertex_[2] = z;\r\n}\r\n\r\ndouble Vertex::x() const\r\n{\r\n\treturn vertex_[0];\r\n}\r\n\r\ndouble Vertex::y() const\r\n{\r\n\treturn vertex_[1];\r\n}\r\n\r\ndouble Vertex::z() const\r\n{\r\n\treturn vertex_[2];\r\n}\r\n\r\nVertex Vertex::rotate(const Matrix3d& rotmat) const\r\n{\r\n\tauto th = this->toMat();\r\n\tauto res = rotmat * th;\r\n\treturn Vertex(res.get(0, 0), res.get(1, 0), res.get(2, 0));\r\n}\r\n\r\nVertex Vertex::rotate(const Vertex& point, const Matrix3d& rotmat) const\r\n{\r\n\tVector vec = Vector::diff(point, *this);\r\n\tvec.rotate(rotmat);\r\n\treturn Vertex(vec.end());\r\n}\r\n\r\nvoid Vertex::rotateInPlace(const Vertex& point, const Matrix3d& rotmat)\r\n{\r\n\tVector vec = Vector::diff(point, *this);\r\n\tvec.rotate(rotmat);\r\n\t*this = vec.end();\r\n}\r\n\r\nvoid Vertex::rotateInPlace(const Matrix3d& rotmat)\r\n{\r\n\tauto vecmat = toMat();\r\n\tauto res = rotmat * vecmat;\r\n\tx(res.get(0, 0));\r\n\ty(res.get(1, 0));\r\n\tz(res.get(2, 0));\r\n}\r\n\r\ndouble Vertex::length() const\r\n{\r\n\treturn sqrt(\r\n\t\t  x() * x()\r\n\t\t+ y() * y()\r\n\t\t+ z() * z());\r\n}\r\n\r\ndouble Vertex::length(const Vertex& v)\r\n{\r\n\treturn v.length();\r\n}\r\n\r\ndouble Vertex::dotProduct(const Vertex& lhs, const Vertex& rhs)\r\n{\r\n\treturn lhs.x() * rhs.x() + lhs.y() * rhs.y() + lhs.z() * rhs.z();\r\n}\r\n\r\ndouble Vertex::dotProduct2D(const Vertex& lhs, const Vertex& rhs)\r\n{\r\n\treturn lhs.x() * rhs.x() + lhs.y() * rhs.y();\r\n}\r\n\r\nVertex Vertex::absolute(const Vertex& v)\r\n{\r\n\treturn { fabs(v.x()), fabs(v.y()), fabs(v.z()) };\r\n}\r\n\r\nVertex Vertex::normalize(const Vertex& v)\r\n{\r\n\tdouble len = v.length();\r\n\tif (doubleeq(len, 0.0)) return v;\r\n\treturn {\r\n\t\tv.x() / len,\r\n\t\tv.y() / len,\r\n\t\tv.z() / len\r\n\t};\r\n}\r\n\r\nVertex Vertex::normalize() const\r\n{\r\n\tdouble len = length();\r\n\tif (doubleeq(len, 0.0)) return Vertex(*this);\r\n\treturn Vertex(\r\n\t\tvertex_[0] / len,\r\n\t\tvertex_[1] / len,\r\n\t\tvertex_[2] / len);\r\n}\r\n\r\nVertex Vertex::crossProduct(const Vertex& lhs, const Vertex& rhs)\r\n{\r\n\treturn Vertex(\r\n\t\tlhs.vertex_[1] * rhs.vertex_[2] - lhs.vertex_[2] * rhs.vertex_[1],\r\n\t\tlhs.vertex_[2] * rhs.vertex_[0] - lhs.vertex_[0] * rhs.vertex_[2],\r\n\t\tlhs.vertex_[0] * rhs.vertex_[1] - lhs.vertex_[1] * rhs.vertex_[0]);\r\n}\r\n\r\nsize_t Vertex::countDifferentAxes(const Vertex& lhs, const Vertex& rhs)\r\n{\r\n\tsize_t ret = 0;\r\n\r\n\tif (!doubleeq(lhs.x(), rhs.x()))\r\n\t\t++ret;\r\n\r\n\tif (!doubleeq(lhs.y(), rhs.y()))\r\n\t\t++ret;\r\n\r\n\tif (!doubleeq(lhs.z(), rhs.z()))\r\n\t\t++ret;\r\n\r\n\treturn ret;\r\n}\r\n\r\nvoid Vertex::parsestr(std::string_view str)\r\n{\r\n\tnamespace qi = boost::spirit::qi;\r\n\tnamespace ascii = boost::spirit::ascii;\r\n\r\n\t//size_t fspos = str.find_first_of(' '), espos = str.find_last_of(' ');\r\n\t//if (fspos == std::string::npos || espos == std::string::npos || fspos == espos)\r\n\t//{\r\n\t//\tvertex_[0] = std::numeric_limits<double>::quiet_NaN();\r\n\t//\tvertex_[1] = std::numeric_limits<double>::quiet_NaN();\r\n\t//\tvertex_[2] = std::numeric_limits<double>::quiet_NaN();\r\n\t//\treturn;\r\n\t//}\r\n\t//size_t pos = 0;\r\n\t//auto xstr = nextword(pos, str);\r\n\t//auto ystr = nextword(pos, str);\r\n\t//auto zstr = nextword(pos, str);\r\n\r\n\tif (!qi::phrase_parse(str.cbegin(), str.cend(), qi::double_ >> qi::double_ >> qi::double_, ascii::space | qi::lit('(') | qi::lit(')'),  vertex_[0], vertex_[1], vertex_[2]))\r\n\t{\r\n\t\tvertex_[0] = std::numeric_limits<double>::quiet_NaN();\r\n\t\tvertex_[1] = std::numeric_limits<double>::quiet_NaN();\r\n\t\tvertex_[2] = std::numeric_limits<double>::quiet_NaN();\r\n\t}\r\n}\r\n\r\nVertex& Vertex::operator=(const Vertex& rhs)\r\n{\r\n\tthis->vertex_[0] = rhs.vertex_[0];\r\n\tthis->vertex_[1] = rhs.vertex_[1];\r\n\tthis->vertex_[2] = rhs.vertex_[2];\r\n\treturn *this;\r\n}\r\n\r\nVertex& Vertex::operator+=(const Vertex& rhs)\r\n{\r\n\tthis->vertex_[0] += rhs.vertex_[0];\r\n\tthis->vertex_[1] += rhs.vertex_[1];\r\n\tthis->vertex_[2] += rhs.vertex_[2];\r\n\treturn *this;\r\n}\r\n\r\nVertex& Vertex::operator-=(const Vertex& rhs)\r\n{\r\n\tthis->vertex_[0] -= rhs.vertex_[0];\r\n\tthis->vertex_[1] -= rhs.vertex_[1];\r\n\tthis->vertex_[2] -= rhs.vertex_[2];\r\n\treturn *this;\r\n}\r\n\r\nVertex& Vertex::operator*=(double mod)\r\n{\r\n\tvertex_[0] *= mod;\r\n\tvertex_[1] *= mod;\r\n\tvertex_[2] *= mod;\r\n\treturn *this;\r\n}\r\n\r\nVertex & Vertex::operator/=(double mod)\r\n{\r\n\tvertex_[0] /= mod;\r\n\tvertex_[1] /= mod;\r\n\tvertex_[2] /= mod;\r\n\treturn *this;\r\n}\r\n\r\nbool Vertex::operator==(const Vertex& rhs) const\r\n{\r\n\treturn doubleeq(x(), rhs.x()) && doubleeq(y(), rhs.y()) && doubleeq(z(), rhs.z());\r\n}\r\n\r\nbool Vertex::operator!=(const Vertex& rhs) const\r\n{\r\n\treturn !(*this == rhs);\r\n}\r\n\r\nbool Vertex::operator<(const Vertex& rhs) const\r\n{\r\n\tif (!doubleeq(x(), rhs.x()) && x() < rhs.x())\r\n\t\treturn true;\r\n\r\n\tif (!doubleeq(y(), rhs.y()) && y() < rhs.y())\r\n\t\treturn true;\r\n\r\n\tif (!doubleeq(z(), rhs.z()) && z() < rhs.z())\r\n\t\treturn true;\r\n\r\n\treturn false;\r\n}\r\n\r\nbool Vertex::parallel(const Vertex& lhs, const Vertex& rhs)\r\n{\r\n\t//crossproduct of parallel vectors is (0, 0, 0)\r\n\tVertex pvert = crossProduct(normalize(lhs), normalize(rhs));\r\n\treturn doubleeq(pvert.x(), 0.0)\r\n\t\t&& doubleeq(pvert.y(), 0.0)\r\n\t\t&& doubleeq(pvert.z(), 0.0);\r\n}\r\n\r\nbool Vertex::equals(const Vertex& lhs, const Vertex& rhs)\r\n{\r\n\treturn doubleeq(lhs.x(), rhs.x())\r\n\t\t&& doubleeq(lhs.y(), rhs.y())\r\n\t\t&& doubleeq(lhs.z(), rhs.z());\r\n}\r\n\r\ndouble Vertex::dotProduct(const Vertex& rhs) const\r\n{\r\n\treturn\r\n\t\tx() * rhs.x() +\r\n\t\ty() * rhs.y() +\r\n\t\tz() * rhs.z();\r\n}\r\n\r\nVertex Vertex::closestAxis() const\r\n{\r\n\tVertex abs = absolute(*this);\r\n\r\n\tif (abs.x() >= abs.y() && abs.x() >= abs.z()) return unitX;\r\n\tif (abs.y() >= abs.z()) return unitY;\r\n\treturn unitZ;\r\n}\r\n\r\nVertex Vertex::crossProduct(const Vertex& rhs) const\r\n{\r\n\treturn Vertex(\r\n\t\tvertex_[1] * rhs.vertex_[2] - vertex_[2] * rhs.vertex_[1],\r\n\t\tvertex_[2] * rhs.vertex_[0] - vertex_[0] * rhs.vertex_[2],\r\n\t\tvertex_[0] * rhs.vertex_[1] - vertex_[1] * rhs.vertex_[0]);\r\n}\r\n\r\ndouble Vertex::operator[](size_t pos) const\r\n{\r\n\treturn vertex_[pos];\r\n}\r\n\r\ndouble& Vertex::operator[](size_t pos)\r\n{\r\n\treturn vertex_[pos];\r\n}\r\n\r\nMatrix<double, 3, 1> Vertex::toMat() const\r\n{\r\n\tMatrix<double, 3, 1> ret;\r\n\tret.set(0, 0, x());\r\n\tret.set(1, 0, y());\r\n\tret.set(2, 0, z());\r\n\treturn ret;\r\n}\r\n\r\nstd::string Vertex::toStr() const\r\n{\r\n\t//static std::ostringstream os;\r\n\t//os.str(\"\");\r\n\t//os << x() << \" \" << y() << \" \" << z();\r\n\t//return os.str();\r\n\r\n\treturn std::to_string(x()) + ' ' + std::to_string(y()) + ' ' + std::to_string(z());\r\n}\r\n\r\nVertex Vertex::allmin(const Vertex& v1, const Vertex& v2)\r\n{\r\n\tVertex v;\r\n\tv.x(std::min(v1.x(), v2.x()));\r\n\tv.y(std::min(v1.y(), v2.y()));\r\n\tv.z(std::min(v1.z(), v2.z()));\r\n\treturn v;\r\n}\r\n\r\nVertex Vertex::allmax(const Vertex& v1, const Vertex& v2)\r\n{\r\n\tVertex v;\r\n\tv.x(std::max(v1.x(), v2.x()));\r\n\tv.y(std::max(v1.y(), v2.y()));\r\n\tv.z(std::max(v1.z(), v2.z()));\r\n\treturn v;\r\n}\r\n\r\n\r\nbool Vertex::isVertex(const Vertex& v)\r\n{\r\n\treturn (v.x() == v.x() && v.y() == v.y() && v.z() == v.z());\r\n}\r\n", "meta": {"hexsha": "d1aa9fef80d289478057f7a88900926c7f20e72b", "size": 7482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rndlevelsource/Vertex.cpp", "max_stars_repo_name": "Telefragged/rndlevelsource", "max_stars_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rndlevelsource/Vertex.cpp", "max_issues_repo_name": "Telefragged/rndlevelsource", "max_issues_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rndlevelsource/Vertex.cpp", "max_forks_repo_name": "Telefragged/rndlevelsource", "max_forks_repo_head_hexsha": "17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1", "max_forks_repo_licenses": ["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.3771428571, "max_line_length": 174, "alphanum_fraction": 0.5844693932, "num_tokens": 2220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.028870907886314256, "lm_q1q2_score": 0.01230829142838539}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MP_COMPARE_HPP\n#define BOOST_MP_COMPARE_HPP\n\n#include <boost/multiprecision/traits/is_backend.hpp>\n\n//\n// Comparison operators for number.\n//\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost{ namespace multiprecision{\n\nnamespace default_ops{\n\n//\n// The dispatching mechanism used here to deal with differently typed arguments\n// could be better replaced with enable_if overloads, but that breaks MSVC-12\n// under strange and hard to reproduce circumstances.\n//\ntemplate <class B>\ninline bool eval_eq(const B& a, const B& b)\n{\n   return a.compare(b) == 0;\n}\ntemplate <class T, class U>\ninline bool eval_eq_imp(const T& a, const U& b, const mpl::true_&)\n{\n   typename geofeatures_boost::multiprecision::detail::number_from_backend<T, U>::type t(b);\n   return eval_eq(a, t.backend());\n}\ntemplate <class T, class U>\ninline bool eval_eq_imp(const T& a, const U& b, const mpl::false_&)\n{\n   typename geofeatures_boost::multiprecision::detail::number_from_backend<U, T>::type t(a);\n   return eval_eq(t.backend(), b);\n}\ntemplate <class T, class U>\ninline bool eval_eq(const T& a, const U& b)\n{\n   typedef mpl::bool_<geofeatures_boost::multiprecision::detail::is_first_backend<T, U>::value> tag_type;\n   return eval_eq_imp(a, b, tag_type());\n}\n\ntemplate <class B>\ninline bool eval_lt(const B& a, const B& b)\n{\n   return a.compare(b) < 0;\n}\ntemplate <class T, class U>\ninline bool eval_lt_imp(const T& a, const U& b, const mpl::true_&)\n{\n   typename geofeatures_boost::multiprecision::detail::number_from_backend<T, U>::type t(b);\n   return eval_lt(a, t.backend());\n}\ntemplate <class T, class U>\ninline bool eval_lt_imp(const T& a, const U& b, const mpl::false_&)\n{\n   typename geofeatures_boost::multiprecision::detail::number_from_backend<U, T>::type t(a);\n   return eval_lt(t.backend(), b);\n}\ntemplate <class T, class U>\ninline bool eval_lt(const T& a, const U& b)\n{\n   typedef mpl::bool_<geofeatures_boost::multiprecision::detail::is_first_backend<T, U>::value> tag_type;\n   return eval_lt_imp(a, b, tag_type());\n}\n\ntemplate <class B>\ninline bool eval_gt(const B& a, const B& b)\n{\n   return a.compare(b) > 0;\n}\ntemplate <class T, class U>\ninline bool eval_gt_imp(const T& a, const U& b, const mpl::true_&)\n{\n   typename geofeatures_boost::multiprecision::detail::number_from_backend<T, U>::type t(b);\n   return eval_gt(a, t.backend());\n}\ntemplate <class T, class U>\ninline bool eval_gt_imp(const T& a, const U& b, const mpl::false_&)\n{\n   typename geofeatures_boost::multiprecision::detail::number_from_backend<U, T>::type t(a);\n   return eval_gt(t.backend(), b);\n}\ntemplate <class T, class U>\ninline bool eval_gt(const T& a, const U& b)\n{\n   typedef mpl::bool_<geofeatures_boost::multiprecision::detail::is_first_backend<T, U>::value> tag_type;\n   return eval_gt_imp(a, b, tag_type());\n}\n\n} // namespace default_ops\n\nnamespace detail{\n\ntemplate <class Num, class Val>\nstruct is_valid_mixed_compare : public mpl::false_ {};\n\ntemplate <class B, expression_template_option ET, class Val>\nstruct is_valid_mixed_compare<number<B, ET>, Val> : public is_convertible<Val, number<B, ET> > {};\n\ntemplate <class B, expression_template_option ET>\nstruct is_valid_mixed_compare<number<B, ET>, number<B, ET> > : public mpl::false_ {};\n\ntemplate <class B, expression_template_option ET, class tag, class Arg1, class Arg2, class Arg3, class Arg4>\nstruct is_valid_mixed_compare<number<B, ET>, expression<tag, Arg1, Arg2, Arg3, Arg4> > \n   : public mpl::bool_<is_convertible<expression<tag, Arg1, Arg2, Arg3, Arg4>, number<B, ET> >::value> {};\n\ntemplate <class tag, class Arg1, class Arg2, class Arg3, class Arg4, class B, expression_template_option ET>\nstruct is_valid_mixed_compare<expression<tag, Arg1, Arg2, Arg3, Arg4>, number<B, ET> > \n   : public mpl::bool_<is_convertible<expression<tag, Arg1, Arg2, Arg3, Arg4>, number<B, ET> >::value> {};\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline BOOST_CONSTEXPR typename geofeatures_boost::enable_if_c<number_category<Backend>::value != number_kind_floating_point, bool>::type is_unordered_value(const number<Backend, ExpressionTemplates>&)\n{\n   return false;\n}\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline BOOST_CONSTEXPR typename geofeatures_boost::enable_if_c<number_category<Backend>::value == number_kind_floating_point, bool>::type is_unordered_value(const number<Backend, ExpressionTemplates>& a)\n{\n   using default_ops::eval_fpclassify;\n   return eval_fpclassify(a.backend()) == FP_NAN;\n}\n\ntemplate <class Arithmetic>\ninline BOOST_CONSTEXPR typename geofeatures_boost::enable_if_c<number_category<Arithmetic>::value != number_kind_floating_point, bool>::type is_unordered_value(const Arithmetic&)\n{\n   return false;\n}\ntemplate <class Arithmetic>\ninline BOOST_CONSTEXPR typename geofeatures_boost::enable_if_c<number_category<Arithmetic>::value == number_kind_floating_point, bool>::type is_unordered_value(const Arithmetic& a)\n{\n   return (geofeatures_boost::math::isnan)(a);\n}\n\ntemplate <class T, class U>\ninline BOOST_CONSTEXPR bool is_unordered_comparison(const T& a, const U& b)\n{\n   return is_unordered_value(a) || is_unordered_value(b);\n}\n\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Backend2, expression_template_option ExpressionTemplates2>\ninline bool operator == (const number<Backend, ExpressionTemplates>& a, const number<Backend2, ExpressionTemplates2>& b)\n{\n   using default_ops::eval_eq;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_eq(a.backend(), b.backend());\n}\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator == (const number<Backend, ExpressionTemplates>& a, const Arithmetic& b)\n{\n   using default_ops::eval_eq;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_eq(a.backend(), number<Backend, ExpressionTemplates>::canonical_value(b));\n}\ntemplate <class Arithmetic, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator == (const Arithmetic& a, const number<Backend, ExpressionTemplates>& b)\n{\n   using default_ops::eval_eq;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_eq(b.backend(), number<Backend, ExpressionTemplates>::canonical_value(a));\n}\ntemplate <class Arithmetic, class Tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator == (const Arithmetic& a, const detail::expression<Tag, A1, A2, A3, A4>& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_eq;\n   result_type t(b);\n   if(detail::is_unordered_comparison(a, t)) return false;\n   return eval_eq(t.backend(), result_type::canonical_value(a));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator == (const detail::expression<Tag, A1, A2, A3, A4>& a, const Arithmetic& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_eq;\n   result_type t(a);\n   if(detail::is_unordered_comparison(t, b)) return false;\n   return eval_eq(t.backend(), result_type::canonical_value(b));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Tagb, class A1b, class A2b, class A3b, class A4b>\ninline typename enable_if<is_same<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type>, bool>::type \n   operator == (const detail::expression<Tag, A1, A2, A3, A4>& a, const detail::expression<Tagb, A1b, A2b, A3b, A4b>& b)\n{\n   using default_ops::eval_eq;\n   typename detail::expression<Tag, A1, A2, A3, A4>::result_type t(a);\n   typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type t2(b);\n   if(detail::is_unordered_comparison(t, t2)) return false;\n   return eval_eq(t.backend(), t2.backend());\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Backend2, expression_template_option ExpressionTemplates2>\ninline bool operator != (const number<Backend, ExpressionTemplates>& a, const number<Backend2, ExpressionTemplates2>& b)\n{\n   using default_ops::eval_eq;\n   if(detail::is_unordered_comparison(a, b)) return true;\n   return !eval_eq(a.backend(), b.backend());\n}\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator != (const number<Backend, ExpressionTemplates>& a, const Arithmetic& b)\n{\n   using default_ops::eval_eq;\n   if(detail::is_unordered_comparison(a, b)) return true;\n   return !eval_eq(a.backend(), number<Backend, et_on>::canonical_value(b));\n}\ntemplate <class Arithmetic, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator != (const Arithmetic& a, const number<Backend, ExpressionTemplates>& b)\n{\n   using default_ops::eval_eq;\n   if(detail::is_unordered_comparison(a, b)) return true;\n   return !eval_eq(b.backend(), number<Backend, et_on>::canonical_value(a));\n}\ntemplate <class Arithmetic, class Tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator != (const Arithmetic& a, const detail::expression<Tag, A1, A2, A3, A4>& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_eq;\n   result_type t(b);\n   if(detail::is_unordered_comparison(a, t)) return true;\n   return !eval_eq(t.backend(), result_type::canonical_value(a));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator != (const detail::expression<Tag, A1, A2, A3, A4>& a, const Arithmetic& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_eq;\n   result_type t(a);\n   if(detail::is_unordered_comparison(t, b)) return true;\n   return !eval_eq(t.backend(), result_type::canonical_value(b));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Tagb, class A1b, class A2b, class A3b, class A4b>\ninline typename enable_if<is_same<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type>, bool>::type \n   operator != (const detail::expression<Tag, A1, A2, A3, A4>& a, const detail::expression<Tagb, A1b, A2b, A3b, A4b>& b)\n{\n   using default_ops::eval_eq;\n   typename detail::expression<Tag, A1, A2, A3, A4>::result_type t(a);\n   typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type t2(b);\n   if(detail::is_unordered_comparison(t, t2)) return true;\n   return !eval_eq(t.backend(), t2.backend());\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Backend2, expression_template_option ExpressionTemplates2>\ninline bool operator < (const number<Backend, ExpressionTemplates>& a, const number<Backend2, ExpressionTemplates2>& b)\n{\n   using default_ops::eval_lt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_lt(a.backend(), b.backend());\n}\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator < (const number<Backend, ExpressionTemplates>& a, const Arithmetic& b)\n{\n   using default_ops::eval_lt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_lt(a.backend(), number<Backend, ExpressionTemplates>::canonical_value(b));\n}\ntemplate <class Arithmetic, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator < (const Arithmetic& a, const number<Backend, ExpressionTemplates>& b)\n{\n   using default_ops::eval_gt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_gt(b.backend(), number<Backend, ExpressionTemplates>::canonical_value(a));\n}\ntemplate <class Arithmetic, class Tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator < (const Arithmetic& a, const detail::expression<Tag, A1, A2, A3, A4>& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_gt;\n   result_type t(b);\n   if(detail::is_unordered_comparison(a, t)) return false;\n   return eval_gt(t.backend(), result_type::canonical_value(a));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator < (const detail::expression<Tag, A1, A2, A3, A4>& a, const Arithmetic& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_lt;\n   result_type t(a);\n   if(detail::is_unordered_comparison(t, b)) return false;\n   return eval_lt(t.backend(), result_type::canonical_value(b));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Tagb, class A1b, class A2b, class A3b, class A4b>\ninline typename enable_if<is_same<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type>, bool>::type \n   operator < (const detail::expression<Tag, A1, A2, A3, A4>& a, const detail::expression<Tagb, A1b, A2b, A3b, A4b>& b)\n{\n   using default_ops::eval_lt;\n   typename detail::expression<Tag, A1, A2, A3, A4>::result_type t(a);\n   typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type t2(b);\n   if(detail::is_unordered_comparison(t, t2)) return false;\n   return eval_lt(t.backend(), t2.backend());\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Backend2, expression_template_option ExpressionTemplates2>\ninline bool operator > (const number<Backend, ExpressionTemplates>& a, const number<Backend2, ExpressionTemplates2>& b)\n{\n   using default_ops::eval_gt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_gt(a.backend(), b.backend());\n}\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator > (const number<Backend, ExpressionTemplates>& a, const Arithmetic& b)\n{\n   using default_ops::eval_gt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_gt(a.backend(), number<Backend, ExpressionTemplates>::canonical_value(b));\n}\ntemplate <class Arithmetic, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator > (const Arithmetic& a, const number<Backend, ExpressionTemplates>& b)\n{\n   using default_ops::eval_lt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return eval_lt(b.backend(), number<Backend, ExpressionTemplates>::canonical_value(a));\n}\ntemplate <class Arithmetic, class Tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator > (const Arithmetic& a, const detail::expression<Tag, A1, A2, A3, A4>& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_lt;\n   result_type t(b);\n   if(detail::is_unordered_comparison(a, t)) return false;\n   return a > t;\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator > (const detail::expression<Tag, A1, A2, A3, A4>& a, const Arithmetic& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_gt;\n   result_type t(a);\n   if(detail::is_unordered_comparison(t, b)) return false;\n   return t > b;\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Tagb, class A1b, class A2b, class A3b, class A4b>\ninline typename enable_if<is_same<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type>, bool>::type \n   operator > (const detail::expression<Tag, A1, A2, A3, A4>& a, const detail::expression<Tagb, A1b, A2b, A3b, A4b>& b)\n{\n   using default_ops::eval_gt;\n   typename detail::expression<Tag, A1, A2, A3, A4>::result_type t(a);\n   typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type t2(b);\n   if(detail::is_unordered_comparison(t, t2)) return false;\n   return t > t2;\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Backend2, expression_template_option ExpressionTemplates2>\ninline bool operator <= (const number<Backend, ExpressionTemplates>& a, const number<Backend2, ExpressionTemplates2>& b)\n{\n   using default_ops::eval_gt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return !eval_gt(a.backend(), b.backend());\n}\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator <= (const number<Backend, ExpressionTemplates>& a, const Arithmetic& b)\n{\n   using default_ops::eval_gt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return !eval_gt(a.backend(), number<Backend, ExpressionTemplates>::canonical_value(b));\n}\ntemplate <class Arithmetic, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator <= (const Arithmetic& a, const number<Backend, ExpressionTemplates>& b)\n{\n   using default_ops::eval_lt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return !eval_lt(b.backend(), number<Backend, ExpressionTemplates>::canonical_value(a));\n}\ntemplate <class Arithmetic, class Tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator <= (const Arithmetic& a, const detail::expression<Tag, A1, A2, A3, A4>& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_lt;\n   if(detail::is_unordered_value(a) || detail::is_unordered_value(b))\n      return false;\n   result_type t(b);\n   if(detail::is_unordered_comparison(a, t)) return false;\n   return !eval_lt(t.backend(), result_type::canonical_value(a));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator <= (const detail::expression<Tag, A1, A2, A3, A4>& a, const Arithmetic& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_gt;\n   result_type t(a);\n   if(detail::is_unordered_comparison(t, b)) return false;\n   return !eval_gt(t.backend(), result_type::canonical_value(b));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Tagb, class A1b, class A2b, class A3b, class A4b>\ninline typename enable_if<is_same<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type>, bool>::type \n   operator <= (const detail::expression<Tag, A1, A2, A3, A4>& a, const detail::expression<Tagb, A1b, A2b, A3b, A4b>& b)\n{\n   using default_ops::eval_gt;\n   typename detail::expression<Tag, A1, A2, A3, A4>::result_type t(a);\n   typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type t2(b);\n   if(detail::is_unordered_comparison(t, t2)) return false;\n   return !eval_gt(t.backend(), t2.backend());\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Backend2, expression_template_option ExpressionTemplates2>\ninline bool operator >= (const number<Backend, ExpressionTemplates>& a, const number<Backend2, ExpressionTemplates2>& b)\n{\n   using default_ops::eval_lt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return !eval_lt(a.backend(), b.backend());\n}\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator >= (const number<Backend, ExpressionTemplates>& a, const Arithmetic& b)\n{\n   using default_ops::eval_lt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return !eval_lt(a.backend(), number<Backend, ExpressionTemplates>::canonical_value(b));\n}\ntemplate <class Arithmetic, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<detail::is_valid_mixed_compare<number<Backend, ExpressionTemplates>, Arithmetic>::value, bool>::type \n   operator >= (const Arithmetic& a, const number<Backend, ExpressionTemplates>& b)\n{\n   using default_ops::eval_gt;\n   if(detail::is_unordered_comparison(a, b)) return false;\n   return !eval_gt(b.backend(), number<Backend, ExpressionTemplates>::canonical_value(a));\n}\ntemplate <class Arithmetic, class Tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator >= (const Arithmetic& a, const detail::expression<Tag, A1, A2, A3, A4>& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_gt;\n   result_type t(b);\n   if(detail::is_unordered_comparison(a, t)) return false;\n   return !eval_gt(t.backend(), result_type::canonical_value(a));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Arithmetic>\ninline typename enable_if_c<detail::is_valid_mixed_compare<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, Arithmetic>::value, bool>::type \n   operator >= (const detail::expression<Tag, A1, A2, A3, A4>& a, const Arithmetic& b)\n{\n   typedef typename detail::expression<Tag, A1, A2, A3, A4>::result_type result_type;\n   using default_ops::eval_lt;\n   result_type t(a);\n   if(detail::is_unordered_comparison(t, b)) return false;\n   return !eval_lt(t.backend(), result_type::canonical_value(b));\n}\ntemplate <class Tag, class A1, class A2, class A3, class A4, class Tagb, class A1b, class A2b, class A3b, class A4b>\ninline typename enable_if<is_same<typename detail::expression<Tag, A1, A2, A3, A4>::result_type, typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type>, bool>::type \n   operator >= (const detail::expression<Tag, A1, A2, A3, A4>& a, const detail::expression<Tagb, A1b, A2b, A3b, A4b>& b)\n{\n   using default_ops::eval_lt;\n   typename detail::expression<Tag, A1, A2, A3, A4>::result_type t(a);\n   typename detail::expression<Tagb, A1b, A2b, A3b, A4b>::result_type t2(b);\n   if(detail::is_unordered_comparison(t, t2)) return false;\n   return !eval_lt(t.backend(), t2.backend());\n}\n\n\n}} // namespaces\n\n#endif // BOOST_MP_COMPARE_HPP\n\n", "meta": {"hexsha": "1082c7dc3d40658ebd1f84fb66f425c0efdaaef8", "size": 25015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/multiprecision/detail/number_compare.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pods/Headers/Private/GeoFeatures/boost/multiprecision/detail/number_compare.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pods/Headers/Private/GeoFeatures/boost/multiprecision/detail/number_compare.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.2233820459, "max_line_length": 203, "alphanum_fraction": 0.7476314211, "num_tokens": 6624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.03258974711501865, "lm_q1q2_score": 0.012303954465271794}}
{"text": "/*\n// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n#ifndef STAPL_ALGORITHMS_GENERATOR_HPP\n#define STAPL_ALGORITHMS_GENERATOR_HPP\n\n#include <type_traits>\n#include <random>\n\n#include <boost/mpl/has_xxx.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\nnamespace stapl {\n\nnamespace generator_impl {\n\nBOOST_MPL_HAS_XXX_TRAIT_DEF(state_type)\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Static polymorphic functor that either returns a provided\n/// generator or adjusts its state for a given starting offset through\n/// the offsetting constructor interface.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Index, typename Generator, bool HasState>\nstruct state_adjust_impl\n{\n  static Generator apply(Generator const& gen, Index const&)\n  {\n    return gen;\n  };\n};\n\n\ntemplate<typename Index, typename Generator>\nstruct state_adjust_impl<Index, Generator, true>\n{\n  static Generator apply(Generator const& gen, Index const& offset)\n  {\n    return Generator(gen, offset);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Wrapper around @ref state_adjust_impl that detects presence of\n/// @p state_type nested typename and either forwards its corresponding boolean\n/// value to @ref state_adjust_impl or @p false if the typename does not exist.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Index, typename Generator,\n         bool = has_state_type<Generator>::value>\nstruct state_adjust\n  : state_adjust_impl<Index, Generator, false>\n{ };\n\n\ntemplate<typename Index, typename Generator>\nstruct state_adjust<Index, Generator, true>\n  : state_adjust_impl<Index, Generator, Generator::state_type::value>\n{ };\n\n} // namespace generator_impl\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Wrapper around a generator functor that calls the generator's\n///   constructor to update its state to a specified offset, if the generator\n///   has implemented the method.\n///\n/// This is used in the @ref generate() pAlgorithm to support generators that\n/// produce values that vary based on the number of times the generator's\n/// function operator has been invoked.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Index, typename Value, typename Generator>\nclass offset_gen\n{\nprivate:\n  Generator m_gen;\n\npublic:\n  using index_type  = Index;\n  using result_type = Value;\n\n  offset_gen(Generator gen)\n    : m_gen(std::move(gen))\n  { }\n\n  result_type operator()(index_type const& i) const\n  {\n    return generator_impl::state_adjust<Index, Generator>::apply(m_gen, i)();\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_gen);\n  }\n}; // struct offset_gen\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Generates a sequence of consecutive values.\n/// @tparam T The value type of the elements generated.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename T>\nclass sequence\n{\nprivate:\n  T counter, oldCtr, step;\n\npublic:\n  using state_type = std::true_type;\n\n  sequence(T start = 0, T st = 1)\n    : counter(start), oldCtr(start), step(st)\n  { }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Creates a functor that is initialized to generate elements\n  ///   beginning at the offset position in the sequence.\n  /// @param seq The sequence functor is passed in to allow offset-independent\n  ///   state to be copied.\n  /// @param offset The offset to be copied.\n  //////////////////////////////////////////////////////////////////////\n  sequence(sequence const& seq, std::size_t offset)\n    : counter(seq.counter+offset * seq.step), oldCtr(counter), step(seq.step)\n  { }\n\n  void define_type(typer& t)\n  {\n    t.member(counter);\n    t.member(oldCtr);\n    t.member(step);\n  }\n\n  T operator()(void)\n  {\n    oldCtr = counter;\n    counter += step;\n    return oldCtr;\n  }\n}; // class sequence\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Generates a sequence of random values.\n///\n/// @bug This is hacked to work deterministically with the testing framework\n///   still doesn't work for parallel generation, but guarantees that two\n///   successive sequentially generated sequences are the same.  Since functors\n///   are both created before either is used.  call srand() once iteration\n///   via operator() has begun.\n//////////////////////////////////////////////////////////////////////\nclass random_sequence\n{\nprivate:\n  int m_r;\n  int m_offset;\n  std::mt19937 m_gen;\n\npublic:\n  using state_type = std::true_type;\n\n  random_sequence(void)\n    : m_r(RAND_MAX), m_offset(0), m_gen(std::random_device()())\n  { }\n\n  random_sequence(int i)\n    : m_r(i), m_offset(0), m_gen(std::random_device()())\n  { }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Creates a functor that is initialized to generate elements\n  ///   beginning at the offset position in the sequence.\n  /// @param seq The sequence functor is passed in to allow offset-independent\n  ///   state to be copied.\n  /// @param offset The offset to be copied.\n  //////////////////////////////////////////////////////////////////////\n  random_sequence(random_sequence const& seq, std::size_t offset)\n    : m_r(seq.m_r), m_offset(offset)\n  { }\n\n  void define_type(typer& t)\n  {\n    t.member(m_r);\n    t.member(m_offset);\n    t.member(m_gen);\n  }\n\n  int operator()(void)\n  { return std::uniform_int_distribution<int>(0, m_r)(m_gen); }\n}; // class random_sequence\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Generates a sequence of std::pair<K, V> elements.\n/// @tparam KeyGenerator    Key's generator type.\n/// @tparam ValueGenerator  Value's generator type.\n/// @tparam Key             Key's value type.\n/// @tparam Value           Value's value type.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename KeyGenerator, typename ValueGenerator,\n         typename Key, typename Value>\nclass associative_sequence\n{\nprivate:\n  using result_type = std::pair<Key, Value>;\n\n  KeyGenerator   m_key_gen;\n  ValueGenerator m_value_gen;\n  std::size_t    m_offset;\n\npublic:\n  using state_type = std::true_type;\n\n  associative_sequence(KeyGenerator& kg, ValueGenerator& vg)\n    : m_key_gen(kg), m_value_gen(vg), m_offset(0)\n  { }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Creates a functor that is initialized to generate elements\n  ///   beginning at the offset position in the sequence.\n  /// @param seq The sequence functor is passed in to allow offset-independent\n  ///   state to be copied.\n  /// @param offset The offset to be copied.\n  //////////////////////////////////////////////////////////////////////\n  associative_sequence(associative_sequence const& seq, std::size_t offset)\n    : m_key_gen(seq.m_key_gen, offset), m_value_gen(seq.m_value_gen, offset),\n      m_offset(offset)\n  { }\n\n  result_type operator()(void)\n  {\n    return std::make_pair(m_key_gen(), m_value_gen());\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_offset);\n    t.member(m_key_gen);\n    t.member(m_value_gen);\n  }\n}; // class associative_sequence\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Generates a repeating sequence of values.\n/// @tparam T Value type of the used counter for the sequence.\n///\n/// This differs from the repetitive_sequence by providing the start and end\n/// values of the sequence to be repeated while repetitive_sequence accepts the\n/// start value and the number of elements before the repeat occurs.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename T>\nclass block_sequence\n{\nprivate:\n  T init, counter, end_counter, step;\n\npublic:\n  using state_type = std::true_type;\n\n  block_sequence(T start, T end, T st = 1)\n    : init(start), counter(start), end_counter(end), step(st)\n  { }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Creates a functor that is initialized to generate elements\n  ///   beginning at the offset position in the sequence.\n  /// @param seq The sequence functor is passed in to allow offset-independent\n  ///   state to be copied.\n  /// @param offset The offset to be copied.\n  //////////////////////////////////////////////////////////////////////\n  block_sequence(block_sequence const& seq, std::size_t offset)\n    : init(seq.init),\n      counter(init + (offset % (seq.end_counter - init + 1))),\n      end_counter(seq.end_counter), step(seq.step)\n  { }\n\n  void define_type(typer &t)\n  {\n    t.member(init);\n    t.member(counter);\n    t.member(end_counter);\n    t.member(step);\n  }\n\n  T operator()(void)\n  {\n    T oldCtr = counter;\n    counter  = (counter <= (end_counter-step) ? counter + step : init);\n    return oldCtr;\n  }\n}; // class block_sequence\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Generates a sequence of unique random sorted values.\n//////////////////////////////////////////////////////////////////////\nclass unique_sorted_sequence\n{\nprivate:\n  using result_type = int;\n\n  std::vector<result_type> m_data;\n  std::size_t              m_offset;\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Functor that binds a random number generator and a\n  /// distribution together.\n  ///\n  /// Boost.Random doesn't provide this interface, and it is needed to\n  /// generate a sequence of random numbers using std::generate.\n  //////////////////////////////////////////////////////////////////////\n  struct rand_wrapper\n  {\n    boost::random::mt19937 m_gen;\n    boost::random::uniform_int_distribution<int> m_dist;\n\n    // the seed used for the generator is a literal to ensure all locations\n    // generate the same sequence.\n    rand_wrapper()\n      : m_gen(0),\n        m_dist(std::numeric_limits<int>::min(), std::numeric_limits<int>::max())\n    { }\n\n    int operator()()\n    {\n      return m_dist(m_gen);\n    }\n  };\n\npublic:\n  using state_type = std::true_type;\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Generates the values in its constructor.\n  //////////////////////////////////////////////////////////////////////\n  template<typename Compare>\n  unique_sorted_sequence(std::size_t n, Compare comp)\n    : m_data(n), m_offset(0)\n  {\n    rand_wrapper rand_wrap;\n    std::generate(m_data.begin(), m_data.end(), rand_wrap);\n\n    // generate the # of missing data until the array is full\n    std::size_t nb_unique = 0;\n    do {\n      std::sort(m_data.begin(), m_data.end(), comp);\n\n      nb_unique = std::distance(m_data.begin(),\n                         std::unique(m_data.begin() + nb_unique, m_data.end()));\n      std::generate(m_data.begin() + nb_unique, m_data.end(), rand);\n    } while (nb_unique != n);\n  }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Creates a functor that is initialized to generate elements\n  ///   beginning at the offset position in the sequence.\n  /// @param seq The sequence functor is passed in to allow offset-independent\n  ///   state to be copied.\n  /// @param offset The offset to be copied.\n  //////////////////////////////////////////////////////////////////////\n  unique_sorted_sequence(unique_sorted_sequence const& seq, std::size_t offset)\n    : m_data(seq.m_data), m_offset(offset)\n  { }\n\n  result_type operator()(void)\n  {\n    return m_data[m_offset++];\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_data);\n    t.member(m_offset);\n  }\n}; // class unique_sorted_sequence\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Functor to generate a sequence of default-constructed values.\n/// @tparam T Returned value type for the sequence.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename T>\nstruct null_sequence\n{\n  T operator()(void) const { return T(); }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Functor to generate a sequence of default-constructed values.\n/// @tparam int Returned value type for the sequence.\n//////////////////////////////////////////////////////////////////////\ntemplate<>\nstruct null_sequence<int>\n{\n  int operator()(void) const { return 0; }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief A sequence that repeats itself every 'repeat' elements.\n/// @tparam T value type of the used counter for the sequence.\n///\n/// This differs from the block_sequence by providing the start value and the\n/// number of elements before the repeat occurs while block_sequence accepts the\n/// start and end values of the sequence to be repeated.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename T>\nclass repetitive_sequence\n{\nprivate:\n  T counter, step, init;\n  size_t el, restart_el;\n\npublic:\n  using state_type = std::true_type;\n\n  repetitive_sequence(T start, T st, size_t repeat)\n    : counter(start), step(st), init(start), el(0), restart_el(repeat)\n  { }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Creates a functor that is initialized to generate elements\n  ///   beginning at the offset position in the sequence.\n  /// @param seq The sequence functor is passed in to allow offset-independent\n  ///   state to be copied.\n  /// @param offset The offset to be copied.\n  //////////////////////////////////////////////////////////////////////\n  repetitive_sequence(repetitive_sequence const& seq, const std::size_t offset)\n    : counter(seq.init + seq.step * offset % seq.restart_el),\n      step(seq.step),\n      init(seq.init),\n      el(offset % seq.restart_el),\n      restart_el(seq.restart_el)\n  { }\n\n  void define_type(typer& t)\n  {\n    t.member(counter);\n    t.member(step);\n    t.member(init);\n    t.member(el);\n    t.member(restart_el);\n  }\n\n  T operator()(void)\n  {\n    if (el==restart_el)\n    {\n      el = 0;\n      counter = init;\n    }\n\n    T oldCtr = counter;\n    counter += step;\n    ++el;\n    return oldCtr;\n  }\n}; // class repetitive_sequence\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Generates a pattern of values that ranges from start to end by\n/// step, then from end to start by -step. This pattern is repeated. The\n/// start and end values can be repeated, or not, as specified.\n/// Example sequence: 0 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 0...     (no repeat)\n/// Example sequence: 0 1 2 3 4 4 3 2 1 0 1 2 3 4 4 3 2 1 0... (repeat end)\n///\n/// @tparam T Value type of the used counter for the sequence.\n/// @param start The starting value to generate the sequence.\n/// @param end The end value to generate the sequence.\n/// @param step The increment to increase or decrease the value by while\n/// moving from start to stop or stop to start, respectively.\n/// @param repeat Whether to repeat the start or stop values when they are\n/// reached. Provided as an enumeration wave_sequence::None, Start, Stop, Both\n///\n/// @example wave_sequence<int>(0, 4, 1, wave_sequence<int>::None)\n/// @example wave_sequence<int>(0, 4, 1, wave_sequence<int>::Stop)\n///\n///\n/// This differs from the repetitive_sequence by providing the start and end\n/// values of the sequence to be repeated while repetitive_sequence accepts the\n/// start value and the number of elements before the repeat occurs.\n//////////////////////////////////////////////////////////////////////\ntemplate<typename T>\nclass wave_sequence\n{\n  public:\n  // Used to specify that the start value, stop value, or both are repeated\n  // when the step direction changes.\n  enum Repeat\n  {\n    None, Start, Stop, Both\n  };\n\n  private:\n  T init, counter, end_counter, step;\n  bool repeatStart=false;\n  bool repeatStop=false;\n  bool repeated=true; // Have we repeated whatever end we are now at?\n\n  public:\n  using state_type = std::true_type;\n\n  wave_sequence(T start, T end, T st = 1, Repeat r = Repeat::None)\n    : init(start), counter(start+st), end_counter(end), step(-st)\n  {\n    if (r== Start || r==Both)\n      repeatStart = true;\n    if (r== Stop || r==Both)\n      repeatStop  = true;\n  }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Creates a functor that is initialized to generate elements\n  ///   beginning at the offset position in the sequence.\n  /// @param seq The sequence functor is passed in to allow offset-independent\n  ///   state to be copied.\n  /// @param offset The offset to be copied.\n  //////////////////////////////////////////////////////////////////////\n  wave_sequence(wave_sequence const& seq, std::size_t offset)\n    : init(seq.init),\n      counter(init + (offset % (seq.end_counter - init + 1))),\n      end_counter(seq.end_counter), step(seq.step),\n      repeatStart(seq.repeatStart), repeatStop(seq.repeatStop),\n      repeated(seq.repeated)\n  { }\n\n  void define_type(typer &t)\n  {\n    t.member(init);\n    t.member(counter);\n    t.member(end_counter);\n    t.member(step);\n    t.member(repeatStart);\n    t.member(repeatStop);\n    t.member(repeated);\n  }\n\n  T operator()(void)\n  {\n    if (counter == end_counter)\n    {\n      if (repeatStop && !repeated)\n      {\n        repeated=true; // This value is a repeat.\n      }\n      else\n      {\n        step = -step; // Reverse our stepping direction.\n        repeated = false; // Not a repeated value.\n        counter += step;\n      }\n    }\n    else if (counter == init)\n    {\n      if (repeatStart && !repeated)\n      {\n        repeated=true; // This value is a repeat.\n      }\n      else\n      {\n        step = -step; // Reverse our stepping direction.\n        repeated = false; // Not a repeated value.\n        counter += step;\n      }\n    }\n    else\n    {\n      counter += step;\n    }\n    return counter;\n  }\n}; // class wave_sequence\n\n\n} // stapl namespace\n\n#endif\n\n", "meta": {"hexsha": "dc5a0137046d584f0af77c0da18480cc58aae24e", "size": 18362, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stapl_release/stapl/algorithms/generator.hpp", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": "stapl_release/stapl/algorithms/generator.hpp", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/stapl/algorithms/generator.hpp", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-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.1220338983, "max_line_length": 80, "alphanum_fraction": 0.5715608322, "num_tokens": 3800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.037892427172852926, "lm_q1q2_score": 0.012286066737613545}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2018 John Maddock. 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_MULTIPRECISION_COMPLEX_ADAPTOR_HPP\r\n#define BOOST_MULTIPRECISION_COMPLEX_ADAPTOR_HPP\r\n\r\n#include <boost/multiprecision/number.hpp>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/multiprecision/detail/digits.hpp>\r\n#include <boost/functional/hash_fwd.hpp>\r\n#include <boost/type_traits/is_complex.hpp>\r\n#include <cmath>\r\n#include <algorithm>\r\n#include <complex>\r\n\r\nnamespace boost {\r\nnamespace multiprecision {\r\nnamespace backends {\r\n\r\ntemplate <class Backend>\r\nstruct complex_adaptor\r\n{\r\n protected:\r\n   Backend m_real, m_imag;\r\n\r\n public:\r\n   Backend& real_data()\r\n   {\r\n      return m_real;\r\n   }\r\n   const Backend& real_data() const\r\n   {\r\n      return m_real;\r\n   }\r\n   Backend& imag_data()\r\n   {\r\n      return m_imag;\r\n   }\r\n   const Backend& imag_data() const\r\n   {\r\n      return m_imag;\r\n   }\r\n\r\n   typedef typename Backend::signed_types   signed_types;\r\n   typedef typename Backend::unsigned_types unsigned_types;\r\n   typedef typename Backend::float_types    float_types;\r\n   typedef typename Backend::exponent_type  exponent_type;\r\n\r\n   complex_adaptor() {}\r\n   complex_adaptor(const complex_adaptor& o) : m_real(o.real_data()), m_imag(o.imag_data()) {}\r\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\r\n   complex_adaptor(complex_adaptor&& o) : m_real(std::move(o.real_data())), m_imag(std::move(o.imag_data()))\r\n   {}\r\n#endif\r\n   complex_adaptor(const Backend& val)\r\n       : m_real(val)\r\n   {}\r\n\r\n   complex_adaptor(const std::complex<float>& val)\r\n   {\r\n      m_real = (long double)val.real();\r\n      m_imag = (long double)val.imag();\r\n   }\r\n   complex_adaptor(const std::complex<double>& val)\r\n   {\r\n      m_real = (long double)val.real();\r\n      m_imag = (long double)val.imag();\r\n   }\r\n   complex_adaptor(const std::complex<long double>& val)\r\n   {\r\n      m_real = val.real();\r\n      m_imag = val.imag();\r\n   }\r\n\r\n   complex_adaptor& operator=(const complex_adaptor& o)\r\n   {\r\n      m_real = o.real_data();\r\n      m_imag = o.imag_data();\r\n      return *this;\r\n   }\r\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\r\n   complex_adaptor& operator=(complex_adaptor&& o) BOOST_NOEXCEPT\r\n   {\r\n      m_real = std::move(o.real_data());\r\n      m_imag = std::move(o.imag_data());\r\n      return *this;\r\n   }\r\n#endif\r\n   template <class V>\r\n   complex_adaptor& operator=(const V& v)\r\n   {\r\n      typedef typename mpl::front<unsigned_types>::type ui_type;\r\n      m_real = v;\r\n      m_imag = ui_type(0u);\r\n      return *this;\r\n   }\r\n   template <class T>\r\n   complex_adaptor& operator=(const std::complex<T>& val)\r\n   {\r\n      m_real = (long double)val.real();\r\n      m_imag = (long double)val.imag();\r\n      return *this;\r\n   }\r\n   complex_adaptor& operator=(const char* s)\r\n   {\r\n      typedef typename mpl::front<unsigned_types>::type ui_type;\r\n      ui_type                                           zero = 0u;\r\n\r\n      using default_ops::eval_fpclassify;\r\n\r\n      if (s && (*s == '('))\r\n      {\r\n         std::string part;\r\n         const char* p = ++s;\r\n         while (*p && (*p != ',') && (*p != ')'))\r\n            ++p;\r\n         part.assign(s, p);\r\n         if (part.size())\r\n            real_data() = part.c_str();\r\n         else\r\n            real_data() = zero;\r\n         s = p;\r\n         if (*p && (*p != ')'))\r\n         {\r\n            ++p;\r\n            while (*p && (*p != ')'))\r\n               ++p;\r\n            part.assign(s + 1, p);\r\n         }\r\n         else\r\n            part.erase();\r\n         if (part.size())\r\n            imag_data() = part.c_str();\r\n         else\r\n            imag_data() = zero;\r\n\r\n         if (eval_fpclassify(imag_data()) == (int)FP_NAN)\r\n         {\r\n            real_data() = imag_data();\r\n         }\r\n      }\r\n      else\r\n      {\r\n         real_data() = s;\r\n         imag_data() = zero;\r\n      }\r\n      return *this;\r\n   }\r\n\r\n   int compare(const complex_adaptor& o) const\r\n   {\r\n      // They are either equal or not:\r\n      return (m_real.compare(o.real_data()) == 0) && (m_imag.compare(o.imag_data()) == 0) ? 0 : 1;\r\n   }\r\n   template <class T>\r\n   int compare(const T& val) const\r\n   {\r\n      using default_ops::eval_is_zero;\r\n      return (m_real.compare(val) == 0) && eval_is_zero(m_imag) ? 0 : 1;\r\n   }\r\n   void swap(complex_adaptor& o)\r\n   {\r\n      real_data().swap(o.real_data());\r\n      imag_data().swap(o.imag_data());\r\n   }\r\n   std::string str(std::streamsize dig, std::ios_base::fmtflags f) const\r\n   {\r\n      using default_ops::eval_is_zero;\r\n      if (eval_is_zero(imag_data()))\r\n         return m_real.str(dig, f);\r\n      return \"(\" + m_real.str(dig, f) + \",\" + m_imag.str(dig, f) + \")\";\r\n   }\r\n   void negate()\r\n   {\r\n      m_real.negate();\r\n      m_imag.negate();\r\n   }\r\n};\r\n\r\ntemplate <class Backend, class T>\r\ninline typename enable_if<is_arithmetic<T>, bool>::type eval_eq(const complex_adaptor<Backend>& a, const T& b) BOOST_NOEXCEPT\r\n{\r\n   return a.compare(b) == 0;\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_add(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& o)\r\n{\r\n   eval_add(result.real_data(), o.real_data());\r\n   eval_add(result.imag_data(), o.imag_data());\r\n}\r\ntemplate <class Backend>\r\ninline void eval_subtract(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& o)\r\n{\r\n   eval_subtract(result.real_data(), o.real_data());\r\n   eval_subtract(result.imag_data(), o.imag_data());\r\n}\r\ntemplate <class Backend>\r\ninline void eval_multiply(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& o)\r\n{\r\n   Backend t1, t2, t3;\r\n   eval_multiply(t1, result.real_data(), o.real_data());\r\n   eval_multiply(t2, result.imag_data(), o.imag_data());\r\n   eval_subtract(t3, t1, t2);\r\n   eval_multiply(t1, result.real_data(), o.imag_data());\r\n   eval_multiply(t2, result.imag_data(), o.real_data());\r\n   eval_add(t1, t2);\r\n   result.real_data() = BOOST_MP_MOVE(t3);\r\n   result.imag_data() = BOOST_MP_MOVE(t1);\r\n}\r\ntemplate <class Backend>\r\ninline void eval_divide(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& z)\r\n{\r\n   // (a+bi) / (c + di)\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_divide;\r\n   using default_ops::eval_fabs;\r\n   using default_ops::eval_is_zero;\r\n   using default_ops::eval_multiply;\r\n   using default_ops::eval_subtract;\r\n   Backend t1, t2;\r\n\r\n   if (eval_is_zero(z.imag_data()))\r\n   {\r\n      eval_divide(result.real_data(), z.real_data());\r\n      eval_divide(result.imag_data(), z.real_data());\r\n      return;\r\n   }\r\n\r\n   eval_fabs(t1, z.real_data());\r\n   eval_fabs(t2, z.imag_data());\r\n   if (t1.compare(t2) < 0)\r\n   {\r\n      eval_divide(t1, z.real_data(), z.imag_data()); // t1 = c/d\r\n      eval_multiply(t2, z.real_data(), t1);\r\n      eval_add(t2, z.imag_data()); // denom = c * (c/d) + d\r\n      Backend t_real(result.real_data());\r\n      // real = (a * (c/d) + b) / (denom)\r\n      eval_multiply(result.real_data(), t1);\r\n      eval_add(result.real_data(), result.imag_data());\r\n      eval_divide(result.real_data(), t2);\r\n      // imag = (b * c/d - a) / denom\r\n      eval_multiply(result.imag_data(), t1);\r\n      eval_subtract(result.imag_data(), t_real);\r\n      eval_divide(result.imag_data(), t2);\r\n   }\r\n   else\r\n   {\r\n      eval_divide(t1, z.imag_data(), z.real_data()); // t1 = d/c\r\n      eval_multiply(t2, z.imag_data(), t1);\r\n      eval_add(t2, z.real_data()); // denom = d * d/c + c\r\n\r\n      Backend r_t(result.real_data());\r\n      Backend i_t(result.imag_data());\r\n\r\n      // real = (b * d/c + a) / denom\r\n      eval_multiply(result.real_data(), result.imag_data(), t1);\r\n      eval_add(result.real_data(), r_t);\r\n      eval_divide(result.real_data(), t2);\r\n      // imag = (-a * d/c + b) / denom\r\n      eval_multiply(result.imag_data(), r_t, t1);\r\n      result.imag_data().negate();\r\n      eval_add(result.imag_data(), i_t);\r\n      eval_divide(result.imag_data(), t2);\r\n   }\r\n}\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_add(complex_adaptor<Backend>& result, const T& scalar)\r\n{\r\n   using default_ops::eval_add;\r\n   eval_add(result.real_data(), scalar);\r\n}\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_subtract(complex_adaptor<Backend>& result, const T& scalar)\r\n{\r\n   using default_ops::eval_subtract;\r\n   eval_subtract(result.real_data(), scalar);\r\n}\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_multiply(complex_adaptor<Backend>& result, const T& scalar)\r\n{\r\n   using default_ops::eval_multiply;\r\n   eval_multiply(result.real_data(), scalar);\r\n   eval_multiply(result.imag_data(), scalar);\r\n}\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_divide(complex_adaptor<Backend>& result, const T& scalar)\r\n{\r\n   using default_ops::eval_divide;\r\n   eval_divide(result.real_data(), scalar);\r\n   eval_divide(result.imag_data(), scalar);\r\n}\r\n// Optimised 3 arg versions:\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_add(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& a, const T& scalar)\r\n{\r\n   using default_ops::eval_add;\r\n   eval_add(result.real_data(), a.real_data(), scalar);\r\n   result.imag_data() = a.imag_data();\r\n}\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_subtract(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& a, const T& scalar)\r\n{\r\n   using default_ops::eval_subtract;\r\n   eval_subtract(result.real_data(), a.real_data(), scalar);\r\n   result.imag_data() = a.imag_data();\r\n}\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_multiply(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& a, const T& scalar)\r\n{\r\n   using default_ops::eval_multiply;\r\n   eval_multiply(result.real_data(), a.real_data(), scalar);\r\n   eval_multiply(result.imag_data(), a.imag_data(), scalar);\r\n}\r\ntemplate <class Backend, class T>\r\ninline typename boost::disable_if_c<boost::is_same<complex_adaptor<Backend>, T>::value>::type eval_divide(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& a, const T& scalar)\r\n{\r\n   using default_ops::eval_divide;\r\n   eval_divide(result.real_data(), a.real_data(), scalar);\r\n   eval_divide(result.imag_data(), a.imag_data(), scalar);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline bool eval_is_zero(const complex_adaptor<Backend>& val) BOOST_NOEXCEPT\r\n{\r\n   using default_ops::eval_is_zero;\r\n   return eval_is_zero(val.real_data()) && eval_is_zero(val.imag_data());\r\n}\r\ntemplate <class Backend>\r\ninline int eval_get_sign(const complex_adaptor<Backend>&)\r\n{\r\n   BOOST_STATIC_ASSERT_MSG(sizeof(Backend) == UINT_MAX, \"Complex numbers have no sign bit.\"); // designed to always fail\r\n   return 0;\r\n}\r\n\r\ntemplate <class Result, class Backend>\r\ninline typename disable_if_c<boost::is_complex<Result>::value>::type eval_convert_to(Result* result, const complex_adaptor<Backend>& val)\r\n{\r\n   using default_ops::eval_convert_to;\r\n   using default_ops::eval_is_zero;\r\n   if (!eval_is_zero(val.imag_data()))\r\n   {\r\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Could not convert imaginary number to scalar.\"));\r\n   }\r\n   eval_convert_to(result, val.real_data());\r\n}\r\n\r\ntemplate <class Backend, class T>\r\ninline void assign_components(complex_adaptor<Backend>& result, const T& a, const T& b)\r\n{\r\n   result.real_data() = a;\r\n   result.imag_data() = b;\r\n}\r\n\r\n//\r\n// Native non-member operations:\r\n//\r\ntemplate <class Backend>\r\ninline void eval_sqrt(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& val)\r\n{\r\n   // Use the following:\r\n   // sqrt(z) = (s, zi / 2s)       for zr >= 0\r\n   //           (|zi| / 2s, +-s)   for zr <  0\r\n   // where s = sqrt{ [ |zr| + sqrt(zr^2 + zi^2) ] / 2 },\r\n   // and the +- sign is the same as the sign of zi.\r\n   using default_ops::eval_abs;\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_divide;\r\n   using default_ops::eval_get_sign;\r\n   using default_ops::eval_is_zero;\r\n\r\n   if (eval_is_zero(val.imag_data()) && (eval_get_sign(val.real_data()) >= 0))\r\n   {\r\n      static const typename mpl::front<typename Backend::unsigned_types>::type zero = 0u;\r\n      eval_sqrt(result.real_data(), val.real_data());\r\n      result.imag_data() = zero;\r\n      return;\r\n   }\r\n\r\n   const bool __my_real_part_is_neg(eval_get_sign(val.real_data()) < 0);\r\n\r\n   Backend __my_real_part_fabs(val.real_data());\r\n   if (__my_real_part_is_neg)\r\n      __my_real_part_fabs.negate();\r\n\r\n   Backend t, __my_sqrt_part;\r\n   eval_abs(__my_sqrt_part, val);\r\n   eval_add(__my_sqrt_part, __my_real_part_fabs);\r\n   eval_ldexp(t, __my_sqrt_part, -1);\r\n   eval_sqrt(__my_sqrt_part, t);\r\n\r\n   if (__my_real_part_is_neg == false)\r\n   {\r\n      eval_ldexp(t, __my_sqrt_part, 1);\r\n      eval_divide(result.imag_data(), val.imag_data(), t);\r\n      result.real_data() = __my_sqrt_part;\r\n   }\r\n   else\r\n   {\r\n      const bool __my_imag_part_is_neg(eval_get_sign(val.imag_data()) < 0);\r\n\r\n      Backend __my_imag_part_fabs(val.imag_data());\r\n      if (__my_imag_part_is_neg)\r\n         __my_imag_part_fabs.negate();\r\n\r\n      eval_ldexp(t, __my_sqrt_part, 1);\r\n      eval_divide(result.real_data(), __my_imag_part_fabs, t);\r\n      if (__my_imag_part_is_neg)\r\n         __my_sqrt_part.negate();\r\n      result.imag_data() = __my_sqrt_part;\r\n   }\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_abs(Backend& result, const complex_adaptor<Backend>& val)\r\n{\r\n   Backend t1, t2;\r\n   eval_multiply(t1, val.real_data(), val.real_data());\r\n   eval_multiply(t2, val.imag_data(), val.imag_data());\r\n   eval_add(t1, t2);\r\n   eval_sqrt(result, t1);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_pow(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& b, const complex_adaptor<Backend>& e)\r\n{\r\n   using default_ops::eval_acos;\r\n   using default_ops::eval_cos;\r\n   using default_ops::eval_exp;\r\n   using default_ops::eval_get_sign;\r\n   using default_ops::eval_is_zero;\r\n   using default_ops::eval_multiply;\r\n   using default_ops::eval_sin;\r\n\r\n   if (eval_is_zero(e))\r\n   {\r\n      typename mpl::front<typename Backend::unsigned_types>::type one(1);\r\n      result = one;\r\n      return;\r\n   }\r\n   else if (eval_is_zero(b))\r\n   {\r\n      if (eval_is_zero(e.real_data()))\r\n      {\r\n         Backend n          = std::numeric_limits<number<Backend> >::quiet_NaN().backend();\r\n         result.real_data() = n;\r\n         result.imag_data() = n;\r\n      }\r\n      else if (eval_get_sign(e.real_data()) < 0)\r\n      {\r\n         Backend n          = std::numeric_limits<number<Backend> >::infinity().backend();\r\n         result.real_data() = n;\r\n         typename mpl::front<typename Backend::unsigned_types>::type zero(0);\r\n         if (eval_is_zero(e.imag_data()))\r\n            result.imag_data() = zero;\r\n         else\r\n            result.imag_data() = n;\r\n      }\r\n      else\r\n      {\r\n         typename mpl::front<typename Backend::unsigned_types>::type zero(0);\r\n         result = zero;\r\n      }\r\n      return;\r\n   }\r\n   complex_adaptor<Backend> t;\r\n   eval_log(t, b);\r\n   eval_multiply(t, e);\r\n   eval_exp(result, t);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_exp(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_cos;\r\n   using default_ops::eval_exp;\r\n   using default_ops::eval_is_zero;\r\n   using default_ops::eval_multiply;\r\n   using default_ops::eval_sin;\r\n\r\n   if (eval_is_zero(arg.imag_data()))\r\n   {\r\n      eval_exp(result.real_data(), arg.real_data());\r\n      typename mpl::front<typename Backend::unsigned_types>::type zero(0);\r\n      result.imag_data() = zero;\r\n      return;\r\n   }\r\n   eval_cos(result.real_data(), arg.imag_data());\r\n   eval_sin(result.imag_data(), arg.imag_data());\r\n   Backend e;\r\n   eval_exp(e, arg.real_data());\r\n   if (eval_is_zero(result.real_data()))\r\n      eval_multiply(result.imag_data(), e);\r\n   else if (eval_is_zero(result.imag_data()))\r\n      eval_multiply(result.real_data(), e);\r\n   else\r\n      eval_multiply(result, e);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_log(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_atan2;\r\n   using default_ops::eval_get_sign;\r\n   using default_ops::eval_is_zero;\r\n   using default_ops::eval_log;\r\n   using default_ops::eval_multiply;\r\n\r\n   if (eval_is_zero(arg.imag_data()) && (eval_get_sign(arg.real_data()) >= 0))\r\n   {\r\n      eval_log(result.real_data(), arg.real_data());\r\n      typename mpl::front<typename Backend::unsigned_types>::type zero(0);\r\n      result.imag_data() = zero;\r\n      return;\r\n   }\r\n\r\n   Backend t1, t2;\r\n   eval_multiply(t1, arg.real_data(), arg.real_data());\r\n   eval_multiply(t2, arg.imag_data(), arg.imag_data());\r\n   eval_add(t1, t2);\r\n   eval_log(t2, t1);\r\n   eval_ldexp(result.real_data(), t2, -1);\r\n   eval_atan2(result.imag_data(), arg.imag_data(), arg.real_data());\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_log10(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_divide;\r\n   using default_ops::eval_log;\r\n\r\n   typedef typename mpl::front<typename Backend::unsigned_types>::type ui_type;\r\n\r\n   Backend ten;\r\n   ten = ui_type(10);\r\n   Backend l_ten;\r\n   eval_log(l_ten, ten);\r\n   eval_log(result, arg);\r\n   eval_divide(result, l_ten);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_sin(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_cos;\r\n   using default_ops::eval_cosh;\r\n   using default_ops::eval_sin;\r\n   using default_ops::eval_sinh;\r\n\r\n   Backend t1, t2;\r\n   eval_sin(t1, arg.real_data());\r\n   eval_cosh(t2, arg.imag_data());\r\n   eval_multiply(result.real_data(), t1, t2);\r\n\r\n   eval_cos(t1, arg.real_data());\r\n   eval_sinh(t2, arg.imag_data());\r\n   eval_multiply(result.imag_data(), t1, t2);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_cos(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_cos;\r\n   using default_ops::eval_cosh;\r\n   using default_ops::eval_sin;\r\n   using default_ops::eval_sinh;\r\n\r\n   Backend t1, t2;\r\n   eval_cos(t1, arg.real_data());\r\n   eval_cosh(t2, arg.imag_data());\r\n   eval_multiply(result.real_data(), t1, t2);\r\n\r\n   eval_sin(t1, arg.real_data());\r\n   eval_sinh(t2, arg.imag_data());\r\n   eval_multiply(result.imag_data(), t1, t2);\r\n   result.imag_data().negate();\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_tan(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   complex_adaptor<Backend> c;\r\n   eval_cos(c, arg);\r\n   eval_sin(result, arg);\r\n   eval_divide(result, c);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_asin(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_multiply;\r\n\r\n   if (eval_is_zero(arg))\r\n   {\r\n      result = arg;\r\n      return;\r\n   }\r\n\r\n   complex_adaptor<Backend> t1, t2;\r\n   assign_components(t1, arg.imag_data(), arg.real_data());\r\n   t1.real_data().negate();\r\n   eval_asinh(t2, t1);\r\n\r\n   assign_components(result, t2.imag_data(), t2.real_data());\r\n   result.imag_data().negate();\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_acos(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   typedef typename mpl::front<typename Backend::unsigned_types>::type ui_type;\r\n\r\n   using default_ops::eval_asin;\r\n\r\n   Backend half_pi, t1;\r\n   t1 = static_cast<ui_type>(1u);\r\n   eval_asin(half_pi, t1);\r\n   eval_asin(result, arg);\r\n   result.negate();\r\n   eval_add(result.real_data(), half_pi);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_atan(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   typedef typename mpl::front<typename Backend::unsigned_types>::type ui_type;\r\n   ui_type                                                             one = (ui_type)1u;\r\n\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_is_zero;\r\n   using default_ops::eval_log;\r\n   using default_ops::eval_subtract;\r\n\r\n   complex_adaptor<Backend> __my_z_times_i, t1, t2, t3;\r\n   assign_components(__my_z_times_i, arg.imag_data(), arg.real_data());\r\n   __my_z_times_i.real_data().negate();\r\n\r\n   eval_add(t1, __my_z_times_i, one);\r\n   eval_log(t2, t1);\r\n   eval_subtract(t1, one, __my_z_times_i);\r\n   eval_log(t3, t1);\r\n   eval_subtract(t1, t3, t2);\r\n\r\n   eval_ldexp(result.real_data(), t1.imag_data(), -1);\r\n   eval_ldexp(result.imag_data(), t1.real_data(), -1);\r\n   if (!eval_is_zero(result.real_data()))\r\n      result.real_data().negate();\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_sinh(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_cos;\r\n   using default_ops::eval_cosh;\r\n   using default_ops::eval_sin;\r\n   using default_ops::eval_sinh;\r\n\r\n   Backend t1, t2;\r\n   eval_cos(t1, arg.imag_data());\r\n   eval_sinh(t2, arg.real_data());\r\n   eval_multiply(result.real_data(), t1, t2);\r\n\r\n   eval_cosh(t1, arg.real_data());\r\n   eval_sin(t2, arg.imag_data());\r\n   eval_multiply(result.imag_data(), t1, t2);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_cosh(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_cos;\r\n   using default_ops::eval_cosh;\r\n   using default_ops::eval_sin;\r\n   using default_ops::eval_sinh;\r\n\r\n   Backend t1, t2;\r\n   eval_cos(t1, arg.imag_data());\r\n   eval_cosh(t2, arg.real_data());\r\n   eval_multiply(result.real_data(), t1, t2);\r\n\r\n   eval_sin(t1, arg.imag_data());\r\n   eval_sinh(t2, arg.real_data());\r\n   eval_multiply(result.imag_data(), t1, t2);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_tanh(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_divide;\r\n   complex_adaptor<Backend> s, c;\r\n   eval_sinh(s, arg);\r\n   eval_cosh(c, arg);\r\n   eval_divide(result, s, c);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_asinh(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   typedef typename mpl::front<typename Backend::unsigned_types>::type ui_type;\r\n   ui_type                                                             one = (ui_type)1u;\r\n\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_log;\r\n   using default_ops::eval_multiply;\r\n\r\n   complex_adaptor<Backend> t1, t2;\r\n   eval_multiply(t1, arg, arg);\r\n   eval_add(t1, one);\r\n   eval_sqrt(t2, t1);\r\n   eval_add(t2, arg);\r\n   eval_log(result, t2);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_acosh(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   typedef typename mpl::front<typename Backend::unsigned_types>::type ui_type;\r\n   ui_type                                                             one = (ui_type)1u;\r\n\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_divide;\r\n   using default_ops::eval_log;\r\n   using default_ops::eval_multiply;\r\n   using default_ops::eval_subtract;\r\n\r\n   complex_adaptor<Backend> __my_zp(arg);\r\n   eval_add(__my_zp.real_data(), one);\r\n   complex_adaptor<Backend> __my_zm(arg);\r\n   eval_subtract(__my_zm.real_data(), one);\r\n\r\n   complex_adaptor<Backend> t1, t2;\r\n   eval_divide(t1, __my_zm, __my_zp);\r\n   eval_sqrt(t2, t1);\r\n   eval_multiply(t2, __my_zp);\r\n   eval_add(t2, arg);\r\n   eval_log(result, t2);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_atanh(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   typedef typename mpl::front<typename Backend::unsigned_types>::type ui_type;\r\n   ui_type                                                             one = (ui_type)1u;\r\n\r\n   using default_ops::eval_add;\r\n   using default_ops::eval_divide;\r\n   using default_ops::eval_log;\r\n   using default_ops::eval_multiply;\r\n   using default_ops::eval_subtract;\r\n\r\n   complex_adaptor<Backend> t1, t2, t3;\r\n   eval_add(t1, arg, one);\r\n   eval_log(t2, t1);\r\n   eval_subtract(t1, one, arg);\r\n   eval_log(t3, t1);\r\n   eval_subtract(t2, t3);\r\n\r\n   eval_ldexp(result.real_data(), t2.real_data(), -1);\r\n   eval_ldexp(result.imag_data(), t2.imag_data(), -1);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_conj(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   result = arg;\r\n   result.imag_data().negate();\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_proj(complex_adaptor<Backend>& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   using default_ops::eval_get_sign;\r\n\r\n   typedef typename mpl::front<typename Backend::unsigned_types>::type ui_type;\r\n   ui_type                                                             zero = (ui_type)0u;\r\n\r\n   int c1 = eval_fpclassify(arg.real_data());\r\n   int c2 = eval_fpclassify(arg.imag_data());\r\n   if (c1 == FP_INFINITE)\r\n   {\r\n      result.real_data() = arg.real_data();\r\n      if (eval_get_sign(result.real_data()) < 0)\r\n         result.real_data().negate();\r\n      result.imag_data() = zero;\r\n      if (eval_get_sign(arg.imag_data()) < 0)\r\n         result.imag_data().negate();\r\n   }\r\n   else if (c2 == FP_INFINITE)\r\n   {\r\n      result.real_data() = arg.imag_data();\r\n      if (eval_get_sign(result.real_data()) < 0)\r\n         result.real_data().negate();\r\n      result.imag_data() = zero;\r\n      if (eval_get_sign(arg.imag_data()) < 0)\r\n         result.imag_data().negate();\r\n   }\r\n   else\r\n      result = arg;\r\n}\r\n\r\ntemplate <class Backend>\r\ninline void eval_real(Backend& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   result = arg.real_data();\r\n}\r\ntemplate <class Backend>\r\ninline void eval_imag(Backend& result, const complex_adaptor<Backend>& arg)\r\n{\r\n   result = arg.imag_data();\r\n}\r\n\r\ntemplate <class Backend, class T>\r\ninline void eval_set_imag(complex_adaptor<Backend>& result, const T& arg)\r\n{\r\n   result.imag_data() = arg;\r\n}\r\n\r\ntemplate <class Backend, class T>\r\ninline void eval_set_real(complex_adaptor<Backend>& result, const T& arg)\r\n{\r\n   result.real_data() = arg;\r\n}\r\n\r\ntemplate <class Backend>\r\ninline std::size_t hash_value(const complex_adaptor<Backend>& val)\r\n{\r\n   std::size_t result  = hash_value(val.real_data());\r\n   std::size_t result2 = hash_value(val.imag_data());\r\n   boost::hash_combine(result, result2);\r\n   return result;\r\n}\r\n\r\n} // namespace backends\r\n\r\nusing boost::multiprecision::backends::complex_adaptor;\r\n\r\ntemplate <class Backend>\r\nstruct number_category<complex_adaptor<Backend> > : public boost::mpl::int_<boost::multiprecision::number_kind_complex>\r\n{};\r\n\r\ntemplate <class Backend, expression_template_option ExpressionTemplates>\r\nstruct component_type<number<complex_adaptor<Backend>, ExpressionTemplates> >\r\n{\r\n   typedef number<Backend, ExpressionTemplates> type;\r\n};\r\n\r\ntemplate <class Backend, expression_template_option ExpressionTemplates>\r\nstruct complex_result_from_scalar<number<Backend, ExpressionTemplates> >\r\n{\r\n   typedef number<complex_adaptor<Backend>, ExpressionTemplates> type;\r\n};\r\n\r\n}\r\n\r\n} // namespace boost::multiprecision\r\n\r\n#endif\r\n", "meta": {"hexsha": "a37f3d497889e2ef76997edf9cd246848d240807", "size": 27377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/multiprecision/complex_adaptor.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/multiprecision/complex_adaptor.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/multiprecision/complex_adaptor.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": 31.7598607889, "max_line_length": 194, "alphanum_fraction": 0.650947876, "num_tokens": 6845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918075, "lm_q2_score": 0.039048289650934105, "lm_q1q2_score": 0.012263136645873814}}
{"text": "/**\n * \\file\n * \\author stvdedal@gmail.com\n *\n * \\brief\n * Program for testing gspan algorithm\n */\n\n#include \"gspan.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <list>\n#include <vector>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <functional>\n\n#include <cctype>\n#include <cstdlib>\n\nusing namespace boost;\n\nvoid\nprint_usage(std::ostream& s)\n{\n    // line width 80\n    // --------------------------------------------------------------------------------\n    s <<\n      \"Usage: gspan [options]\\n\"\n      \"Graph-based substructure pattern mining.\\n\"\n      \"Depending on the graph count in input, there are two modes:\\n\"\n      \"  1. input contains one graph. Mined patterns belong to this one;\\n\"\n      \"       in this case only --mincount=NUM option is used\\n\"\n      \"  2. input contains many graphs. Mined patterns belong to some graph in input;\\n\"\n      \"       in this case --minsupp=NUM option is used, as more useful.\\n\"\n      \"Options:\\n\"\n      \"  -i, --input FILE        file to read, default stdin\\n\"\n      \"  -o, --output FILE       file to write, default stdout\\n\"\n      \"  -c, --mincount NUM      minimal count, integer value, default 1\\n\"\n      \"  -s, --minsupp NUM       minimal support, 0..1\\n\"\n      \"  -l, --legacy            use tgf format for input and output (slower!)\\n\"\n      \"  -e, --embeddings [opts] none, autgrp, all. default is none\\n\"\n      \"  -h, --help              this help\"\n      << std::endl;\n}\n\nvoid error_usage()\n{\n    print_usage(std::cerr);\n    exit(1);\n}\n\nstd::ifstream input_fstream;\nstd::ofstream output_fstream;\nstd::istream* input_stream = &std::cin;\nstd::ostream* output_stream = &std::cout;\nbool no_output = false;\nbool use_legacy = false;\nenum OutputMappings {\n    OUTPUT_MAPPING_NONE,\n    OUTPUT_MAPPING_ONE_AUTOMORPH,\n    OUTPUT_MAPPING_ALL\n} output_mappings = OUTPUT_MAPPING_NONE;\n\nstatic std::size_t pattern_no = 0;\n\n/**\n * Vertex and edge properties are used by algorithm.\n * To optimize comparison, they are integers (not strings)\n *\n * vertex values are addressed by boost::vertex_name\n * edge values   are addressed by boost::edge_name\n */\nstd::vector<std::string> v_values;\nstd::vector<std::string> e_values;\n\nstd::size_t\nmap_string_to_integer(std::vector<std::string>& values,\n                      const std::string& value)\n{\n    auto valit = std::find(values.begin(), values.end(), value);\n    if (valit == values.end()) {\n        valit = values.insert(values.end(), value);\n    }\n    return valit - values.begin();\n}\n\nusing VP = property<vertex_name_t, std::size_t>;\nusing EP =\n    property<edge_index_t, std::size_t, property<edge_name_t, std::size_t> >;\n\nusing InputGraph = adjacency_list<vecS, vecS, undirectedS, VP, EP, std::size_t>;\nusing InputGraphVertex = graph_traits<InputGraph>::vertex_descriptor;\nusing InputGraphEdge = graph_traits<InputGraph>::edge_descriptor;\nusing GspanTraits = gspan_traits<InputGraph, vertex_name_t, edge_name_t>;\n\ntemplate <typename MG, typename SBG>\nvoid\nprint_mapping(const MG& mg,\n              const SBG& s,\n              std::size_t map_no,\n              std::size_t autmorph_no)\n{\n    std::ostream& os = *output_stream;\n\n    //os << std::endl;\n    const InputGraph& ig = *s.input_graph();\n    os << \"m \" << map_no << \" #automorh \" << autmorph_no << \" \"<<ig[graph_bundle]<< std::endl;\n    for (auto v_mg : vertices(mg)) {\n        auto v_ig = get_v_ig(s, v_mg);\n        os << \"v \" << v_index(mg, v_mg) << \" \";\n        //os << ig[graph_bundle] << \" \";\n        os << get(get(vertex_index, ig), v_ig) << std::endl;\n    }\n    for (auto e_mg : edges(mg)) {\n        auto e_ig = get_e_ig(s, e_mg);\n        os << \"e \" << e_index(mg, e_mg) << \" \";\n        //os << ig[graph_bundle] << \" \";\n        os << get(get(edge_index, ig), e_ig) << std::endl;\n    }\n}\n\nvoid\nwrite_egf(const GspanTraits::MG& mg, const GspanTraits::SG& sg, int support)\n{\n    ++pattern_no;\n\n    if (no_output)\n        return;\n\n    std::ostream& os = *output_stream;\n\n    //os << std::endl;\n    os << \"p \" << pattern_no << \" # occurence \" << support << std::endl;\n    for (auto v : vertices(mg))\n        os << \"v \" << v_index(mg, v) << \" \" << v_values[v_bundle(mg, v)]\n           << std::endl;\n    for (auto e : edges(mg))\n        os << \"e \" << e_index(mg, e) << \" \" << source_index(mg, e) << \" \"\n           << target_index(mg, e) << \" \" << e_values[e_bundle(mg, e)] << std::endl;\n\n    if (output_mappings != OUTPUT_MAPPING_NONE) {\n        std::size_t map_no = 0;\n        for (const auto& g_sbgs : sg) {\n            for (const auto& grp : g_sbgs.second.aut_list) {\n                std::size_t autmorph_no = 0;\n                for (const auto& s : grp) {\n                    print_mapping(mg, *s, ++map_no, ++autmorph_no);\n                    if (output_mappings == OUTPUT_MAPPING_ONE_AUTOMORPH)\n                        break;\n                }\n            }\n        }\n    }\n}\n\nvoid\nwrite_tgf(const GspanTraits::MG& mg, const GspanTraits::SG& sg, int support)\n{\n    ++pattern_no;\n\n    if (no_output)\n        return;\n    std::ostream& os = *output_stream;\n\n    using MGE = GspanTraits::MG::edge_descriptor;\n    std::vector<MGE> mg_edges; // to reverse (for matching with gbolt)\n\n    mg_edges.reserve(num_edges(mg));\n    for (auto e : edges(mg))\n        mg_edges.push_back(e);\n\n    os << \"t # \" << pattern_no - 1 << \" * \" << support << std::endl;\n    for (auto v : vertices(mg))\n        os << \"v \" << v_index(mg, v) << \" \" << v_bundle(mg, v) << std::endl;\n\n    using RevIt = std::vector<MGE>::const_reverse_iterator;\n    for (RevIt ei = mg_edges.rbegin(); ei != mg_edges.rend(); ++ei) {\n        MGE e = *ei;\n        os << \"e \" << source_index(mg, e) << \" \" << target_index(mg, e)\n           << \" \" << e_bundle(mg, e) << std::endl;\n    }\n\n    std::set<std::size_t> graph_ids;\n    for (const auto& g_sbgs : sg) {\n        const InputGraph& ig = *g_sbgs.first;\n        graph_ids.insert(ig[graph_bundle]);\n    }\n\n    os << \"x \";\n    for (std::size_t graph_id : graph_ids) {\n        os << graph_id << \" \";\n    }\n\n    os << std::endl << std::endl;\n}\n\ninline\nstd::string&\nremove_comment(std::string& s)\n{\n    s.erase(std::find(s.begin(), s.end(), '#'), s.end());\n    return s;\n}\n\ninline\nstd::string&\nremove_whitespaces_left(std::string& s)\n{\n    using namespace std;\n    s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun(&::isblank))));\n    return s;\n}\n\ninline\nstd::string&\nremove_whitespaces_right(std::string& s)\n{\n    using namespace std;\n    auto rit = find_if(s.rbegin(), s.rend(), not1(ptr_fun(&::isblank)));\n    s.erase(rit.base(), s.end());\n    return s;\n}\n\nbool read_egf(std::list<InputGraph>& container, std::istream& is)\n{\n    std::map<std::size_t, InputGraphVertex> vmap;\n    std::size_t line_no = 0;\n    std::string line;\n\n    while (getline(is, line)) {\n        ++line_no;\n        remove_comment(line);\n        remove_whitespaces_left(line);\n        remove_whitespaces_right(line);\n        if (line.empty())\n            continue;\n        char tag = 0;\n        std::stringstream ss(line);\n        ss >> tag;\n        switch (tag) {\n        case 't': {\n            vmap.clear();\n            container.push_back(InputGraph());\n            std::size_t graph_id = 0;\n            ss >> graph_id;\n            if (!ss) {\n                std::cerr << \"invalid or missed <graph_id>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n            container.back()[graph_bundle] = graph_id;\n        }\n        break;\n        case 'v': {\n            if (container.empty()) {\n                std::cerr << \"invalid format: 't' tag missed\" << std::endl;\n                return false;\n            }\n            InputGraph& g = container.back();\n            InputGraphVertex v = add_vertex(g);\n            std::size_t vertex_id = 0;\n            ss >> vertex_id;\n            if (!ss) {\n                std::cerr << \"invalid or missed <vertex_id>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n\n            std::string value;\n            getline(ss, value);\n            remove_whitespaces_left(value);\n            put(get(vertex_name, g), v, map_string_to_integer(v_values, value));\n            vmap[vertex_id] = v;\n        }\n        break;\n        case 'e': {\n            if (container.empty()) {\n                std::cerr << \"invalid format: 't' tag missed\" << std::endl;\n                return false;\n            }\n            InputGraph& g = container.back();\n            std::size_t edge_id = 0;\n            if (!(ss >> edge_id)) {\n                std::cerr << \"invalid or missed <edge_id>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n            std::size_t src_id;\n            if (!(ss >> src_id) || vmap.find(src_id) == vmap.end()) {\n                std::cerr << \"invalid or missed <vertex_id_1>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n            std::size_t dst_id;\n            if (!(ss >> dst_id) || vmap.find(dst_id) == vmap.end()) {\n                std::cerr << \"invalid or missed <vertex_id_2>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n\n            InputGraphVertex u = vmap[src_id];\n            InputGraphVertex v = vmap[dst_id];\n            InputGraphEdge e = add_edge(u, v, g).first;\n            put(get(edge_index, g), e, edge_id);\n\n            std::string value;\n            getline(ss, value);\n            remove_whitespaces_left(value);\n            put(get(edge_name, g), e, map_string_to_integer(e_values, value));\n        }\n        break;\n        default:\n            std::cerr << \"invalid or missed <tag>, at line \" << line_no << std::endl;\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool read_tgf(std::list<InputGraph>& container, std::istream& is)\n{\n    std::map<std::size_t, InputGraphVertex> vmap;\n    std::size_t line_no = 0;\n    std::string line;\n\n    while (getline(is, line)) {\n        ++line_no;\n        if (line.empty())\n            continue;\n        char tag = 0;\n        std::stringstream ss(line);\n        ss >> tag;\n        switch (tag) {\n        case 't': {\n            vmap.clear();\n            container.push_back(InputGraph());\n            char nsign = 0;\n            std::size_t graph_id = 0;\n            ss >> nsign >> graph_id;\n            if (!ss || nsign != '#') {\n                std::cerr << \"invalid or missed <graph_id>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n            container.back()[graph_bundle] = graph_id;\n        }\n        break;\n        case 'v': {\n            if (container.empty()) {\n                std::cerr << \"invalid format: 't' tag missed\" << std::endl;\n                return false;\n            }\n            InputGraph& g = container.back();\n            InputGraphVertex v = add_vertex(g);\n            std::size_t vertex_id = 0;\n            ss >> vertex_id;\n            if (!ss || vertex_id >= num_vertices(g)) {\n                std::cerr << \"invalid or missed <vertex_id>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n\n            std::size_t ival;\n            if (!(ss >> ival)) {\n                std::cerr << \"invalid or missed vertex value (integer), at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n            put(get(vertex_name, g), v, ival);\n            vmap[vertex_id] = v;\n        }\n        break;\n        case 'e': {\n            if (container.empty()) {\n                std::cerr << \"invalid format: 't' tag missed\" << std::endl;\n                return false;\n            }\n            InputGraph& g = container.back();\n            std::size_t src_id;\n            if (!(ss >> src_id) || vmap.find(src_id) == vmap.end()) {\n                std::cerr << \"invalid or missed <vertex_id_1>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n            std::size_t dst_id;\n            if (!(ss >> dst_id) || vmap.find(dst_id) == vmap.end()) {\n                std::cerr << \"invalid or missed <vertex_id_2>, at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n\n            InputGraphVertex u = vmap[src_id];\n            InputGraphVertex v = vmap[dst_id];\n            InputGraphEdge e = add_edge(u, v, g).first;\n            put(get(edge_index, g), e, num_edges(g) - 1);\n\n            std::size_t ival;\n            if (!(ss >> ival)) {\n                std::cerr << \"invalid or missed edge value (integer), at line \" << line_no\n                          << std::endl;\n                return false;\n            }\n            put(get(edge_name, g), e, ival);\n        }\n        break;\n        default:\n            std::cerr << \"invalid or missed <tag>, at line \" << line_no << std::endl;\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstruct input_statistics {\n    std::size_t graph_count;\n    struct {\n        std::size_t avg;\n        std::size_t min;\n        std::size_t max;\n    } v, e;\n};\n\nvoid calculate_statistics(const std::list<InputGraph>& container,\n                          input_statistics* stat)\n{\n    stat->graph_count = 0;\n    stat->v.avg = 0;\n    stat->v.min = 0;\n    stat->v.max = 0;\n    stat->e.avg = 0;\n    stat->e.min = 0;\n    stat->e.max = 0;\n    if (container.empty()) {\n        return;\n    }\n    stat->v.max = stat->v.min = num_vertices(container.front());\n    stat->e.max = stat->e.min = num_edges(container.front());\n    for (const InputGraph& g : container) {\n        ++stat->graph_count;\n        std::size_t vn = num_vertices(g);\n        std::size_t en = num_edges(g);\n        stat->v.avg += vn;\n        stat->e.avg += en;\n        if (stat->v.min > vn) {\n            stat->v.min = vn;\n        }\n        if (stat->v.max < vn) {\n            stat->v.max = vn;\n        }\n        if (stat->e.min > en) {\n            stat->e.min = en;\n        }\n        if (stat->e.max < en) {\n            stat->e.max = en;\n        }\n    }\n    stat->v.avg /= stat->graph_count;\n    stat->e.avg /= stat->graph_count;\n}\n\nint\nmain(int argc, char** argv)\n{\n    std::size_t mincount = 0;\n    bool minsupp_exist = true;\n    double minsupp = 1.0;\n\n    for (int i = 1; i < argc; ++i) {\n        std::string opt(argv[i]);\n        if (opt == \"--help\" || opt == \"-h\") {\n            print_usage(std::cout);\n            return 0;\n        }\n        else if (opt == \"--input\" || opt == \"-i\") {\n            if (++i >= argc || input_fstream.is_open())\n                error_usage();\n            input_fstream.open(argv[i]);\n            input_stream = &input_fstream;\n            continue;\n        }\n        else if (opt == \"--output\" || opt == \"-o\") {\n            if (++i >= argc || output_fstream.is_open())\n                error_usage();\n            std::string file(argv[i]);\n            if (file != \"/dev/null\") {\n                output_fstream.open(file);\n                output_stream = &output_fstream;\n            }\n            else {\n                no_output = true;\n            }\n            continue;\n        }\n        else if (opt == \"--mincount\" || opt == \"-c\") {\n            if (++i >= argc)\n                error_usage();\n            if (! (std::stringstream(argv[i]) >> mincount)) {\n                error_usage();\n            }\n            continue;\n        }\n        else if (opt == \"--minsupp\" || opt == \"-s\") {\n            if (++i >= argc)\n                error_usage();\n            if (! (std::stringstream(argv[i]) >> minsupp)) {\n                error_usage();\n            }\n            minsupp_exist = true;\n            continue;\n        }\n        else if (opt == \"--legacy\" || opt == \"-l\") {\n            use_legacy = true;\n        }\n        else if (opt == \"--embeddings\" || opt == \"-e\") {\n            if (++i >= argc)\n                error_usage();\n            std::string param(argv[i]);\n            if (param == \"all\")\n                output_mappings = OUTPUT_MAPPING_ALL;\n            else if (param == \"autgrp\")\n                output_mappings = OUTPUT_MAPPING_ONE_AUTOMORPH;\n            else if (param == \"none\")\n                output_mappings = OUTPUT_MAPPING_NONE;\n            else\n                error_usage();\n            continue;\n        }\n        else {\n            error_usage();\n        }\n    }\n\n    std::list<InputGraph> input_graphs;\n\n    if (!(use_legacy ? read_tgf : read_egf)(input_graphs, *input_stream))\n        return 1;\n\n    input_statistics stat;\n    calculate_statistics(input_graphs, &stat);\n\n    if (minsupp_exist) {\n        mincount = stat.graph_count * minsupp;\n    }\n\n    std::cerr << std::endl;\n    std::cerr << \"# input data statistics:\\n\"\n              << \"# graph count          = \" << stat.graph_count << std::endl\n              << \"# vertices avg,min,max = \"\n              << stat.v.avg << \", \" << stat.v.min << \", \" << stat.v.max << std::endl\n              << \"# edges avg,min,max    = \"\n              << stat.e.avg << \", \" << stat.e.min << \", \" << stat.e.max << std::endl\n              << \"# min_count            = \" << mincount << std::endl << std::endl;\n\n    if (input_graphs.size() == 1)\n        gspan_one_graph(input_graphs.back(),\n                        mincount,\n                        use_legacy ? write_tgf : write_egf,\n                        vertex_name,\n                        edge_name);\n    else\n        gspan_many_graphs(input_graphs.begin(),\n                          input_graphs.end(),\n                          mincount,\n                          use_legacy ? write_tgf : write_egf,\n                          vertex_name,\n                          edge_name);\n\n    std::cerr << std::endl;\n    std::cerr << \"# mined \" << pattern_no << \" patterns\" << std::endl;\n}\n", "meta": {"hexsha": "9f0ac5378cb78d23176f24bfe52eb54d3a81594d", "size": 17879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gspan/example/test_gspan.cpp", "max_stars_repo_name": "dtchuink/DFG-Pattern-Generator", "max_stars_repo_head_hexsha": "a57b46dd3439b316f98e856bbd1841cc1b34bb29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gspan/example/test_gspan.cpp", "max_issues_repo_name": "dtchuink/DFG-Pattern-Generator", "max_issues_repo_head_hexsha": "a57b46dd3439b316f98e856bbd1841cc1b34bb29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gspan/example/test_gspan.cpp", "max_forks_repo_name": "dtchuink/DFG-Pattern-Generator", "max_forks_repo_head_hexsha": "a57b46dd3439b316f98e856bbd1841cc1b34bb29", "max_forks_repo_licenses": ["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.825862069, "max_line_length": 94, "alphanum_fraction": 0.4950500587, "num_tokens": 4472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.03622005222376973, "lm_q1q2_score": 0.012245171575492134}}
{"text": "#include \"modeling.hpp\"\n#include \"utils/logging.hpp\"\n#include <boost/format.hpp>\n#include <boost/foreach.hpp>\n#include <cstdio>\n#include \"expr_ops.hpp\"\n#include \"sco_common.hpp\"\n#include \"macros.h\"\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\nnamespace sco {\n\nvoid ConvexObjective::addAffExpr(const AffExpr& affexpr) {\n  exprInc(quad_, affexpr);\n}\nvoid ConvexObjective::addQuadExpr(const QuadExpr& quadexpr) {\n  exprInc(quad_, quadexpr);\n}\nvoid ConvexObjective::addHinge(const AffExpr& affexpr, double coeff) {\n  Var hinge = model_->addVar(\"hinge\", 0, INFINITY);\n  vars_.push_back(hinge);\n  ineqs_.push_back(affexpr);\n  exprDec(ineqs_.back(), hinge);\n  AffExpr hinge_cost = exprMult(AffExpr(hinge), coeff);\n  exprInc(quad_, hinge_cost);\n}\nvoid ConvexObjective::addAbs(const AffExpr& affexpr, double coeff) {\n  Var neg = model_->addVar(\"neg\", 0, INFINITY);\n  Var pos = model_->addVar(\"pos\", 0, INFINITY);\n  vars_.push_back(neg);\n  vars_.push_back(pos);\n  AffExpr neg_plus_pos;\n  neg_plus_pos.coeffs = vector<double>(2, coeff);\n  neg_plus_pos.vars.push_back(neg);\n  neg_plus_pos.vars.push_back(pos);\n  exprInc(quad_, neg_plus_pos);\n  AffExpr affeq = affexpr;\n  affeq.vars.push_back(neg);\n  affeq.vars.push_back(pos);\n  affeq.coeffs.push_back(1);\n  affeq.coeffs.push_back(-1);\n  eqs_.push_back(affeq);\n}\nvoid ConvexObjective::addHinges(const AffExprVector& ev) {\n  for (size_t i=0; i < ev.size(); ++i) addHinge(ev[i],1);\n}\nvoid ConvexObjective::addL1Norm(const AffExprVector& ev) {\n  for (size_t i=0; i < ev.size(); ++i) addAbs(ev[i],1);\n}\nvoid ConvexObjective::addL2Norm(const AffExprVector& ev) {\n  for (size_t i=0; i < ev.size(); ++i) exprInc(quad_, exprSquare(ev[i]));\n}\nvoid ConvexObjective::addMax(const AffExprVector& ev) {\n  Var m = model_->addVar(\"max\", -INFINITY, INFINITY);\n  for (size_t i=0; i < ev.size(); ++i) {\n    ineqs_.push_back(ev[i]);\n    exprDec(ineqs_.back(), m);\n  }\n}\n\nvoid ConvexObjective::addConstraintsToModel() {\n  cnts_.reserve(eqs_.size() + ineqs_.size());\n  BOOST_FOREACH(const AffExpr& aff, eqs_) {\n    cnts_.push_back(model_->addEqCnt(aff, \"\"));\n  }\n  BOOST_FOREACH(const AffExpr& aff, ineqs_) {\n    cnts_.push_back(model_->addIneqCnt(aff, \"\"));\n  }\n}\n\nvoid ConvexObjective::removeFromModel() {\n  model_->removeCnts(cnts_);\n  model_->removeVars(vars_);\n  model_ = NULL;\n}\nConvexObjective::~ConvexObjective() {\n  if (inModel()) removeFromModel();\n}\n\nvoid ConvexConstraints::addEqCnt(const AffExpr& aff) {\n  eqs_.push_back(aff);\n}\n\nvoid ConvexConstraints::addIneqCnt(const AffExpr& aff) {\n  ineqs_.push_back(aff);\n}\n\nvoid ConvexConstraints::addConstraintsToModel() {\n  cnts_.reserve(eqs_.size() + ineqs_.size());\n  BOOST_FOREACH(const AffExpr& aff, eqs_) {\n    cnts_.push_back(model_->addEqCnt(aff, \"\"));\n  }\n  BOOST_FOREACH(const AffExpr& aff, ineqs_) {\n    cnts_.push_back(model_->addIneqCnt(aff, \"\"));\n  }\n}\n\nvoid ConvexConstraints::removeFromModel() {\n  model_->removeCnts(cnts_);\n  model_ = NULL;\n}\n\nvector<double> ConvexConstraints::violations(const vector<double>& x) {\n  DblVec out;\n  out.reserve(eqs_.size() + ineqs_.size());\n  BOOST_FOREACH(const AffExpr& aff, eqs_) out.push_back(fabs(aff.value(x.data())));\n  BOOST_FOREACH(const AffExpr& aff, ineqs_) out.push_back(pospart(aff.value(x.data())));\n  return out;\n}\ndouble ConvexConstraints::violation(const vector<double>& x) {\n  return vecSum(violations(x));\n}\n\nConvexConstraints::~ConvexConstraints() {\n  if (inModel()) removeFromModel();\n}\n\ndouble ConvexObjective::value(const vector<double>& x)  {\n  return quad_.value(x);\n}\n\n\nvector<double> Constraint::violations(const DblVec& x) {\n  DblVec val = value(x);\n  DblVec out(val.size());\n\n  if (type() == EQ) {\n    for (size_t i=0; i < val.size(); ++i) out[i] = fabs(val[i]);\n  }\n  else { // type() == INEQ\n    for (size_t i=0; i < val.size(); ++i) out[i] = pospart(val[i]);\n  }\n\n  return out;\n}\n\ndouble Constraint::violation(const DblVec& x) {\n  return vecSum(violations(x));\n}\n\nOptProb::OptProb() : model_(createModel()) {}\n\nVarVector OptProb::createVariables(const vector<string>& var_names) {\n  return createVariables(var_names, DblVec(var_names.size(), -INFINITY), DblVec(var_names.size(), INFINITY));\n}\nVarVector OptProb::createVariables(const vector<string>& var_names, const DblVec& lb, const DblVec& ub) {\n  size_t n_add = var_names.size(), n_cur = vars_.size();\n  assert(lb.size() == n_add);\n  assert(ub.size() == n_add);\n  vars_.reserve(n_cur + n_add);\n  lower_bounds_.reserve(n_cur + n_add);\n  upper_bounds_.reserve(n_cur + n_add);\n  for (size_t i=0; i < var_names.size(); ++i) {\n    vars_.push_back(model_->addVar(var_names[i], lb[i], ub[i]));\n    lower_bounds_.push_back(lb[i]);\n    upper_bounds_.push_back(ub[i]);\n  }\n  model_->update();\n  return VarVector(vars_.end()-n_add, vars_.end());\n}\nvoid OptProb::setLowerBounds(const vector<double>& lb) {\n  assert(lb.size() == vars_.size());\n  lower_bounds_ = lb;\n}\nvoid OptProb::setUpperBounds(const vector<double>& ub) {\n  assert(ub.size() == vars_.size());\n  upper_bounds_ = ub;\n}\nvoid OptProb::setLowerBounds(const vector<double>& lb, const vector<Var>& vars) {\n  setVec(lower_bounds_, vars, lb);\n}\nvoid OptProb::setUpperBounds(const vector<double>& ub, const vector<Var>& vars) {\n  setVec(upper_bounds_, vars, ub);\n}\n\nvoid OptProb::addCost(CostPtr cost) {\n  costs_.push_back(cost);\n}\nvoid OptProb::addConstraint(ConstraintPtr cnt) {\n  if (cnt->type() == EQ) addEqConstraint(cnt);\n  else addIneqConstraint(cnt);\n}\nvoid OptProb::addEqConstraint(ConstraintPtr cnt) {\n  assert (cnt->type() == EQ);\n  eqcnts_.push_back(cnt);\n}\nvoid OptProb::addIneqConstraint(ConstraintPtr cnt) {\n  assert (cnt->type() == INEQ);\n  ineqcnts_.push_back(cnt);\n}\nvector<ConstraintPtr> OptProb::getConstraints() const {\n  vector<ConstraintPtr> out;\n  out.reserve(eqcnts_.size() + ineqcnts_.size());\n  out.insert(out.end(), eqcnts_.begin(), eqcnts_.end());\n  out.insert(out.end(), ineqcnts_.begin(), ineqcnts_.end());\n  return out;\n}\nvoid OptProb::addLinearConstraint(const AffExpr& expr, ConstraintType type) {\n  if (type == EQ) model_->addEqCnt(expr, \"\");\n  else model_->addIneqCnt(expr, \"\");\n}\n\nvector<double> OptProb::getCentralFeasiblePoint(const vector<double>& x) {\n  assert(x.size() == lower_bounds_.size());\n  DblVec center(x.size());\n  for (int i=0; i < x.size(); ++i) center[i] = (lower_bounds_[i] + upper_bounds_[i])/2;\n  return getClosestFeasiblePoint(center);\n}\nvector<double> OptProb::getClosestFeasiblePoint(const vector<double>& x) {\n  LOG_DEBUG(\"getClosestFeasiblePoint\");\n  assert(vars_.size() == x.size());\n  QuadExpr obj;\n  printf(\" ---Inside modelling.cpp---\");\n  for (int i = 0; i < x.size(); i++){\n      printf(\"\\nX[%d] = %f\",i,x[i]);\n  }\n\n  for (int i=0; i < x.size(); ++i) {\n    exprInc(obj, exprSquare(exprSub(AffExpr(vars_[i]),x[i])));\n  }\n  model_->setVarBounds(vars_, lower_bounds_, upper_bounds_);\n  model_->setObjective(obj);\n  CvxOptStatus status = model_->optimize();\n  if(status != CVX_SOLVED) {\n    model_->writeToFile(\"/tmp/fail.lp\");\n    PRINT_AND_THROW(\"couldn't find a feasible point. there's probably a problem with variable bounds (e.g. joint limits). wrote to /tmp/fail.lp\");\n  }\n  return model_->getVarValues(vars_);\n}\n\n\n\n}\n", "meta": {"hexsha": "4fca8f5b93f7c586f85ab4e925eb4ad5d80dbc2f", "size": 7159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sco/modeling.cpp", "max_stars_repo_name": "pratyusv/trajopt", "max_stars_repo_head_hexsha": "35cd7ce2d8e21cd3513ef4578735f42f2ce054a3", "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/sco/modeling.cpp", "max_issues_repo_name": "pratyusv/trajopt", "max_issues_repo_head_hexsha": "35cd7ce2d8e21cd3513ef4578735f42f2ce054a3", "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/sco/modeling.cpp", "max_forks_repo_name": "pratyusv/trajopt", "max_forks_repo_head_hexsha": "35cd7ce2d8e21cd3513ef4578735f42f2ce054a3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2067510549, "max_line_length": 146, "alphanum_fraction": 0.6918564045, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.03210070961065096, "lm_q1q2_score": 0.012237418594286982}}
{"text": "// Copyright (C) 2012 Benjamin Kehlet\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// First added:  2012-10-31\n// Last changed: 2012-11-14\n\n//#ifdef HAS_CGAL\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n#include <cassert>\n\n#include \"PolyhedronUtils.h\"\n//#include <dolfin/common/constants.h>\n//#include <dolfin/geometry/Point.h>\n//#include <dolfin/log/log.h>\n//#include <dolfin/log/LogStream.h>\n\n#include <CGAL/Cartesian_d.h>\n#include <CGAL/Polyhedron_incremental_builder_3.h>\n#include <CGAL/Min_sphere_of_spheres_d.h>\n#include <CGAL/Min_sphere_of_spheres_d_traits_3.h>\n\n//#define BOOST_FILESYSTEM_NO_DEPRECATED\n//#include <boost/filesystem.hpp>\n//#include <boost/tuple/tuple.hpp>\n//#include <boost/tuple/tuple_comparison.hpp>\n//#include <boost/tokenizer.hpp>\n//#include <boost/algorithm/string.hpp>\n\nnamespace polyhcsg\n{\n\n//static inline double strToDouble(const std::string& s, bool print=false)\n//{\n//  std::istringstream is(s);\n//  double val;\n//  is >> val;\n//\n//  if (print)\n//    std::cout << \"to_double \" << s << \" : \" << val << std::endl;\n//\n//  return val;\n//}\n//\n//dolfin::LogStream& operator << (dolfin::LogStream& stream,\n//                                const boost::tuple<double,\n//                                double, double>& obj)\n//{\n//  stream << obj.get<0>() << \" \" << obj.get<1>() << \" \" << obj.get<2>();\n//  return stream;\n//}\n//\n//template <class HDS>\n//class BuildFromSTL : public CGAL::Modifier_base<HDS>\n//{\n//public:\n//  BuildFromSTL(std::string filename) : _filename(filename){}\n//  void operator()(HDS& hds)\n//  {\n//    std::cout << \"Reading surface from \" << _filename << std::endl;\n//\n//    CGAL::Polyhedron_incremental_builder_3<HDS> builder( hds, true);\n//    builder.begin_surface(100000, 100000);\n//\n//    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;\n//\n//    std::ifstream file(_filename.c_str());\n//    if (!file.is_open())\n//    {\n//      dolfin_error(\"PolyhedronUtils.cpp\",\n//                   \"open .stl file to read 3D surface\",\n//                   \"Failed to open file\");\n//    }\n//\n//    std::size_t num_vertices = 0;\n//    std::map<boost::tuple<double, double, double>, std::size_t> vertex_map;\n//    std::vector<std::vector<std::size_t> > facets;\n//    std::string line;\n//    const boost::char_separator<char> sep(\" \");\n//\n//    // Read the first line and trim away whitespaces\n//    std::getline(file, line);\n//    boost::algorithm::trim(line);\n//\n//    if (line.substr(0, 5) != \"solid\")\n//    {\n//      dolfin_error(\"PolyhedronUtils.cpp\",\n//                   \"open .stl file to read 3D surface\",\n//                   \"File does not start with \\\"solid\\\"\");\n//    }\n//\n//    // TODO: Read name of solid\n//\n//    std::getline(file, line);\n//    boost::algorithm::trim(line);\n//\n//    while (file.good())\n//    {\n//      //bool has_normal = false;\n//      //Point normal;\n//\n//      // Read the line \"facet normal n1 n2 n3\"\n//      {\n//        tokenizer tokens(line, sep);\n//        tokenizer::iterator tok_iter = tokens.begin();\n//\n//        if (*tok_iter != \"facet\")\n//          dolfin_error(\"PolyhedronUtils.cpp\",\n//                       \"open .stl file to read 3D surface\",\n//                       \"Expected keyword \\\"facet\\\"\");\n//        ++tok_iter;\n//\n//        // Check if a normal different from zero is given\n//        if (tok_iter != tokens.end())\n//        {\n//          //std::cout << \"Expecting normal\" << std::endl;\n//\n//          if  (*tok_iter != \"normal\")\n//            dolfin_error(\"PolyhedronUtils.cpp\",\n//                         \"open .stl file to read 3D surface\",\n//                         \"Expected keyword \\\"normal\\\"\");\n//          ++tok_iter;\n//\n//          //std::cout << \"Read line: \" << line << std::endl;\n//\n//          // for (std::size_t i = 0; i < 3; ++i)\n//          // {\n//          //   normal[i] = strToDouble(*tok_iter);\n//          //   ++tok_iter;\n//          // }\n//\n//\n//          //std::cout << \"Normal: \" << normal << std::endl;\n//          // if (normal.norm() > DOLFIN_EPS)\n//          //   has_normal = true;\n//\n//          // if (tok_iter != tokens.end())\n//          //   dolfin_error(\"PolyhedronUtils.cpp\",\n//          //                \"open .stl file to read 3D surface\",\n//          //                \"Expected end of line\");\n//        }\n//      }\n//\n//      // Read \"outer loop\" line\n//      std::getline(file, line);\n//      boost::algorithm::trim(line);\n//\n//      if (line != \"outer loop\")\n//        dolfin_error(\"PolyhedronUtils.cpp\",\n//                     \"open .stl file to read 3D surface\",\n//                     \"Expected key word outer loop\");\n//\n//      std::vector<std::size_t> v_indices(3);\n//\n//      // Read lines with vertices\n//      for (std::size_t i = 0; i < 3; ++i)\n//      {\n//        std::getline(file, line);\n//        boost::algorithm::trim(line);\n//\n//        //std::cout << \"read line: \" << line << std::endl;\n//\n//        tokenizer tokens(line, sep);\n//        tokenizer::iterator tok_iter = tokens.begin();\n//\n//        if (*tok_iter != \"vertex\")\n//        {\n//          dolfin_error(\"PolyhedronUtils.cpp\",\n//                       \"open .stl file to read 3D surface\",\n//                       \"Expected key word vertex\");\n//        }\n//        ++tok_iter;\n//\n//        const double x = strToDouble(*tok_iter); ++tok_iter;\n//        const double y = strToDouble(*tok_iter); ++tok_iter;\n//        const double z = strToDouble(*tok_iter); ++tok_iter;\n//\n//        boost::tuple<double, double, double> v(x, y, z);\n//\n//        if (vertex_map.count(v) > 0)\n//          v_indices[i] = vertex_map[v];\n//        else\n//        {\n//          vertex_map[v] = num_vertices;\n//          v_indices[i] = num_vertices;\n//          builder.add_vertex(csg::Exact_Point_3(x, y, z));\n//          num_vertices++;\n//        }\n//      }\n//\n//      // TODO\n//      // if (has_normal)\n//      // {\n//      //   std::cout << \"Has normal\" << std::endl;\n//      // }\n//\n//      builder.add_facet(v_indices.begin(), v_indices.end());\n//\n//      // Read 'endloop' line\n//      std::getline(file, line);\n//      boost::algorithm::trim(line);\n//      if (line != \"endloop\")\n//      {\n//        dolfin_error(\"PolyhedronUtils.cpp\",\n//                     \"open .stl file to read 3D surface\",\n//                     \"Expected key word endloop\");\n//      }\n//\n//      std::getline(file, line);\n//      boost::algorithm::trim(line);\n//      if (line != \"endfacet\")\n//      {\n//        dolfin_error(\"PolyhedronUtils.cpp\",\n//                     \"open .stl file to read 3D surface\",\n//                     \"Expected key word endfacet\");\n//      }\n//\n//      std::getline(file, line);\n//      boost::algorithm::trim(line);\n//\n//      if (line.substr(0, 5) != \"facet\")\n//        break;\n//    }\n//\n//    // Read the 'endsolid' line\n//    tokenizer tokens(line, sep);\n//    tokenizer::iterator tok_iter = tokens.begin();\n//\n//    if (*tok_iter != \"endsolid\")\n//    {\n//      dolfin_error(\"PolyhedronUtils.cpp\",\n//                   \"open .stl file to read 3D surface\",\n//                   \"Expected key word endsolid\");\n//    }\n//    ++tok_iter;\n//\n//    builder.end_surface();\n//\n//    // TODO: Check name of solid\n//\n//    std::cout << \"Done reading surface\" << std::endl;\n//  }\n//    const std::string _filename;\n//};\n////-----------------------------------------------------------------------------\n//void PolyhedronUtils::readSurfaceFile(std::string filename,\n//                                      csg::Exact_Polyhedron_3& p)\n//{\n//  boost::filesystem::path fpath(filename);\n//  if (fpath.extension() == \".stl\")\n//  {\n//    readSTLFile(filename, p);\n//  }\n//  else if(fpath.extension() == \".off\")\n//  {\n//    // TODO: Let cgal parse the file\n//  }\n//  else\n//  {\n//    dolfin_error(\"PolyhedronUtils.cpp\",\n//                 \"open file to read 3D surface\",\n//                 \"Unknown file type\");\n//  }\n//}\n////-----------------------------------------------------------------------------\n//void PolyhedronUtils::readSTLFile(std::string filename,\n//                                  csg::Exact_Polyhedron_3& p)\n//{\n//  BuildFromSTL<csg::Exact_HalfedgeDS> stl_builder(filename);\n//  p.delegate(stl_builder);\n//}\n////-----------------------------------------------------------------------------\n//CGAL::Bbox_3 PolyhedronUtils::getBoundingBox(csg::Polyhedron_3& polyhedron)\n//{\n//  csg::Polyhedron_3::Vertex_iterator it = polyhedron.vertices_begin();\n//\n//  // Initialize bounding box with the first point\n//  csg::Polyhedron_3::Point_3 p0 = it->point();\n//  CGAL::Bbox_3 b(p0[0], p0[1], p0[2], p0[0], p0[1], p0[2]);\n//  ++it;\n//\n//  for (; it != polyhedron.vertices_end(); ++it)\n//  {\n//    csg::Polyhedron_3::Point_3 p1 = it->point();\n//    b = b + CGAL::Bbox_3(p1[0], p1[1], p1[2], p1[0], p1[1], p1[2]);\n//  }\n//\n//  return b;\n//}\n//-----------------------------------------------------------------------------\n//double PolyhedronUtils::getBoundingSphereRadius(csg::Polyhedron_3& polyhedron)\n//{\n//  typedef double FT;\n//  typedef CGAL::Cartesian_d<FT> K;\n//  typedef CGAL::Min_sphere_of_spheres_d_traits_d<K, FT, 3> MinSphereTraits;\n//  typedef CGAL::Min_sphere_of_spheres_d<MinSphereTraits> Min_sphere;\n//  typedef MinSphereTraits::Sphere Sphere;\n//  typedef K::Point_d Point_d;\n//\n//  std::vector<Sphere> S;\n//  FT coord[3];\n//\n//  for (csg::Polyhedron_3::Vertex_iterator it=polyhedron.vertices_begin();\n//       it != polyhedron.vertices_end(); ++it)\n//  {\n//    coord[0] = it->point().x();\n//    coord[1] = it->point().y();\n//    coord[2] = it->point().z();\n//    Point_d p(3, coord,coord+3);\n//    S.push_back(Sphere(p, 0.0));\n//  }\n//\n//  Min_sphere ms(S.begin(), S.end());\n//  CGAL_assertion(ms.is_valid());\n//\n//  return CGAL::to_double(ms.radius());\n//}\n//-----------------------------------------------------------------------------\ntemplate<typename Polyhedron>\nstatic inline double\nget_edge_length(typename Polyhedron::Halfedge::Halfedge_handle halfedge)\n{\n  return CGAL::to_double((halfedge->vertex()->point() -\n    halfedge->opposite()->vertex()->point()).squared_length());\n}\n//-----------------------------------------------------------------------------\ntemplate <typename Polyhedron>\nstatic inline double get_triangle_area(typename Polyhedron::Facet_handle facet)\n{\n  const typename Polyhedron::Halfedge_handle edge = facet->halfedge();\n  const typename Polyhedron::Point_3 a = edge->vertex()->point();\n  const typename Polyhedron::Point_3 b = edge->next()->vertex()->point();\n  const typename Polyhedron::Point_3 c\n    = edge->next()->next()->vertex()->point();\n  return CGAL::to_double(CGAL::cross_product(b-a, c-a).squared_length());\n}\n//-----------------------------------------------------------------------------\ntemplate<typename Polyhedron>\nstatic inline double\nget_min_edge_length(typename Polyhedron::Facet_handle facet)\n{\n  typename Polyhedron::Facet::Halfedge_around_facet_circulator half_edge\n    = facet->facet_begin();\n  double min_length = CGAL::to_double((half_edge->vertex()->point()\n      - half_edge->opposite()->vertex()->point()).squared_length());\n\n  half_edge++;\n  min_length = std::min(min_length, get_edge_length<Polyhedron>(half_edge));\n\n  half_edge++;\n  min_length = std::min(min_length, get_edge_length<Polyhedron>(half_edge));\n\n  return min_length;\n}\n//-----------------------------------------------------------------------------\ntemplate<typename Polyhedron>\nbool facet_is_degenerate(typename Polyhedron::Facet_handle facet,\n                         const double threshold)\n{\n  return get_min_edge_length<Polyhedron>(facet) < threshold\n      || get_triangle_area<Polyhedron>(facet) < threshold;\n}\n//-----------------------------------------------------------------------------\ntemplate<typename Polyhedron>\nstatic int number_of_degenerate_facets(Polyhedron& p, const double threshold)\n{\n  int count = 0;\n  for (typename Polyhedron::Facet_iterator facet = p.facets_begin();\n       facet != p.facets_end(); facet++)\n  {\n    assert(facet->is_triangle());\n    if ( facet_is_degenerate<Polyhedron>(facet, threshold) )\n      count++;\n  }\n  return count;\n}\n//-----------------------------------------------------------------------------\ntemplate <typename Polyhedron>\nstatic typename Polyhedron::Halfedge_handle\nget_longest_edge(typename Polyhedron::Facet_handle facet)\n{\n  typename Polyhedron::Halfedge_handle edge = facet->halfedge();\n  double length = get_edge_length<Polyhedron>(edge);\n\n  {\n    typename Polyhedron::Halfedge_handle e_tmp = edge->next();\n    if (get_edge_length<Polyhedron>(e_tmp) > length)\n    {\n      length = get_edge_length<Polyhedron>(e_tmp);\n      edge = e_tmp;\n    }\n  }\n\n  {\n    typename Polyhedron::Halfedge_handle e_tmp = edge->next()->next();\n    if ( get_edge_length<Polyhedron>(e_tmp) > length )\n    {\n      length = get_edge_length<Polyhedron>(e_tmp);\n      edge = e_tmp;\n    }\n  }\n\n  return edge;\n}\n//-----------------------------------------------------------------------------\ntemplate <typename Polyhedron>\ndouble shortest_edge(Polyhedron& p)\n{\n  double shortest = std::numeric_limits<double>::max();\n  for (typename Polyhedron::Halfedge_iterator halfedge = p.halfedges_begin();\n       halfedge != p.halfedges_end(); halfedge++)\n  {\n    const double length = get_edge_length<Polyhedron>(halfedge);\n    shortest = std::min(shortest, length);\n  }\n\n  return shortest;\n}\n//-----------------------------------------------------------------------------\ntemplate <typename Polyhedron>\nstatic void remove_edge(Polyhedron& p, typename\n                        Polyhedron::Halfedge_handle& edge)\n{\n\n  // // FIXME: Is it possible to do this in a smarter way than a linear scan\n  // for (csg::Polyhedron_3::Facet_iterator facet = p.facets_begin();\n  //      facet != p.facets_end(); facet++)\n  // {\n  //   if ( facet_is_degenerate<csg::Polyhedron_3>(facet, threshold) )\n  //   {\n  //     //print_facet(facet);\n\n  //     // Find a short edge\n  //     csg::Polyhedron_3::Halfedge::Halfedge_handle shortest_edge = facet->facet_begin();\n  //     csg::Polyhedron_3::Facet::Halfedge_around_facet_circulator current_edge = facet->facet_begin();\n  //     double min_length = get_edge_length(current_edge);\n\n  //     for (int i = 0; i < 2; i++)\n  //     {\n  //     current_edge++;\n  //     if (get_edge_length(current_edge) < min_length)\n  //     {\n  //       shortest_edge = current_edge;\n  //       min_length = get_edge_length(current_edge);\n  //     }\n  //     }\n\n  // Join small triangles with neighbor facets\n  edge = p.join_facet(edge->next());\n  p.join_facet(edge->opposite()->prev());\n\n  // The joined facets are now quads\n  // Join the two close vertices\n  p.join_vertex(edge);\n}\n//-----------------------------------------------------------------------------\ntemplate <typename Polyhedron>\nstatic void remove_short_edges(Polyhedron& p, const double threshold)\n{\n  while (true)\n  {\n    bool removed = false;\n    for (typename Polyhedron::Halfedge_iterator halfedge = p.halfedges_begin();\n     halfedge != p.halfedges_end(); halfedge++)\n    {\n      if (get_edge_length<Polyhedron>(halfedge) < threshold)\n      {\n    remove_edge<Polyhedron>(p, halfedge);\n    removed = true;\n    break;\n      }\n    }\n\n    if (!removed)\n      break;\n  }\n}\n//-----------------------------------------------------------------------------\ntemplate <typename Polyhedron>\nstatic typename Polyhedron::Point_3\nfacet_midpoint(typename Polyhedron::Facet_handle facet)\n{\n  typename Polyhedron::Point_3 p(CGAL::ORIGIN);\n\n  typename Polyhedron::Facet::Halfedge_around_facet_circulator half_edge\n    = facet->facet_begin();\n\n  for (std::size_t i = 0; i < facet->facet_degree(); i++)\n  {\n    p = p + (half_edge->vertex()->point() - CGAL::ORIGIN);\n    half_edge++;\n  }\n\n  p = CGAL::ORIGIN\n    + (p - CGAL::ORIGIN)/static_cast<double>(facet->facet_degree());\n\n  // std::std::cout << \"Center coordinates computed: \" << p << std::endl;\n\n  // half_edge = facet->facet_begin();\n  // for (std::size_t i = 0; i < facet->facet_degree(); i++)\n  // {\n  //   std::std::cout << \"Distance to point << \" << half_edge->vertex()->point() << \" = \" << (half_edge->vertex()->point() - p).squared_length() << std::endl;\n  //   half_edge++;\n  // }\n\n  return p;\n}\n//-----------------------------------------------------------------------------\ntemplate <typename Polyhedron>\nstatic void\nremove_triangle(Polyhedron& p, typename Polyhedron::Facet_handle facet)\n{\n  assert(facet->is_triangle());\n\n  // std::cout << \"Removing triangle\" << endl;\n  // print_facet<Polyhedron>(facet);\n\n  // Find the longest edge\n  typename Polyhedron::Halfedge_handle edge = get_longest_edge<Polyhedron>(facet);\n\n  // std::cout << \"Longest edge\" << std::endl;\n  // print_halfedge<Polyhedron>(edge);\n\n  // std::cout << \"Opposite triangle\" << std::endl;\n  // print_facet<Polyhedron>(edge->opposite()->facet());\n\n  edge = p.join_facet(edge);\n  // std::cout << \"Edge after join: \" << std::endl;\n  // print_halfedge<Polyhedron>(edge);\n\n  // std::cout << \"Facet after join\" << std::endl;\n  // print_facet<Polyhedron>(edge->facet());\n\n  typename Polyhedron::Point_3 new_center = facet_midpoint<Polyhedron>(edge->facet());\n\n  edge = p.create_center_vertex(edge);\n\n  edge->vertex()->point() = new_center;\n\n  // std::std::cout << \"Center vertex: \" << edge->vertex()->point() << std::endl;\n\n  // for (std::size_t i=0; i < 4; i++)\n  // {\n  //   print_facet<Polyhedron>(edge->facet());\n  //   edge = edge->next()->opposite();\n  // }\n}\n//-----------------------------------------------------------------------------\ntemplate<typename Polyhedron>\nvoid remove_small_triangles(Polyhedron& p, const double threshold)\n{\n  int n = number_of_degenerate_facets(p, threshold);\n\n  while ((n > 0) && (p.size_of_facets() > 0))\n  {\n    for ( typename Polyhedron::Facet_iterator facet = p.facets_begin();\n            facet != p.facets_end();\n            facet++ )\n    {\n      assert(facet->is_triangle());\n\n      std::cout << \"Number of facets: \" << p.size_of_facets() << std::endl;\n\n      if (get_triangle_area<Polyhedron>(facet) < threshold)\n      {\n        std::cout << \"Small triangle detected\" << std::endl;\n        //print_facet<Polyhedron>(facet);\n        remove_triangle<Polyhedron>(p, facet);\n        std::cout << \"Number of facets: \" << p.size_of_facets() << std::endl;\n        remove_short_edges(p, threshold);\n        std::cout << \"Number of facets: \" << p.size_of_facets() << std::endl;\n        n = number_of_degenerate_facets<Polyhedron>(p, threshold);\n        break;\n      }\n    }\n  }\n}\n//-----------------------------------------------------------------------------\nvoid remove_degenerate_facets(Polyhedron& p, const double threshold)\n{\n  int degenerate_facets = number_of_degenerate_facets(p, threshold);\n\n  //std::cout << \"Number of degenerate facets: \" << degenerate_facets << std::endl;\n  // FIXME: Use has_degenerate_facets() when debugging is done\n  if (degenerate_facets > 0)\n  {\n    assert(p.is_pure_triangle());\n\n    shortest_edge(p);\n\n    //std::cout << \"Removing triangles with short edges\" << std::endl;\n    remove_short_edges(p, threshold);\n\n    //std::cout << \"Number of degenerate facets: \"\n         << number_of_degenerate_facets(p, threshold) << std::endl;\n\n    //std::cout << \"Removing small triangles\" << std::endl;\n    //remove_small_triangles(p, threshold);\n\n    //std::cout << \"Number of degenerate facets: \"\n    //     << number_of_degenerate_facets(p, threshold) << std::endl;\n\n    // Removal of triangles should preserve the triangular structure\n    // of the polyhedron\n    assert(p.is_pure_triangle());\n  }\n}\n//-----------------------------------------------------------------------------\nbool has_degenerate_facets(Polyhedron& p, double threshold)\n{\n  for (Polyhedron::Facet_iterator facet = p.facets_begin();\n       facet != p.facets_end(); facet++)\n  {\n    assert(facet->is_triangle());\n    if (facet_is_degenerate<Polyhedron>(facet, threshold))\n      return true;\n  }\n  return false;\n}\n\n} // namespace polyhcsg\n", "meta": {"hexsha": "959d1456c2e08dc10eea4345588ea0f49cc3dab1", "size": 20541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libpolyhcsg/source/PolyhedronUtils.cpp", "max_stars_repo_name": "crobarcro/pyPolyCSG", "max_stars_repo_head_hexsha": "38e6e065de9a5b4837a1b3a1823248f02a6f9199", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-16T10:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:20:04.000Z", "max_issues_repo_path": "libpolyhcsg/source/PolyhedronUtils.cpp", "max_issues_repo_name": "crobarcro/pyPolyCSG", "max_issues_repo_head_hexsha": "38e6e065de9a5b4837a1b3a1823248f02a6f9199", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libpolyhcsg/source/PolyhedronUtils.cpp", "max_forks_repo_name": "crobarcro/pyPolyCSG", "max_forks_repo_head_hexsha": "38e6e065de9a5b4837a1b3a1823248f02a6f9199", "max_forks_repo_licenses": ["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.0953125, "max_line_length": 158, "alphanum_fraction": 0.5627768853, "num_tokens": 5276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.028436034074054463, "lm_q1q2_score": 0.01223168466125121}}
{"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/render/bsdf.h>\n#include <mitsuba/hw/basicshader.h>\n#include <mitsuba/core/warp.h>\n#include <boost/algorithm/string.hpp>\n\nMTS_NAMESPACE_BEGIN\n\n/*!\\plugin{ward}{Anisotropic Ward BRDF}\n * \\order{15}\n * \\parameters{\n *     \\parameter{variant}{\\String}{\n *         Determines the variant of the Ward model to use:\n *         \\begin{enumerate}[(i)]\n *             \\item \\code{ward}: The original model by Ward \\cite{Ward1992Measuring}\n *             --- suffers from energy loss at grazing angles.\n *             \\item \\code{ward-duer}: Corrected Ward model with lower energy loss\n *             at grazing angles \\cite{Dur2006Improved}.\n *             Does not always conserve energy.\n *             \\item \\code{balanced}: Improved version of the \\code{ward-duer}\n *             model with energy balance at all angles \\cite{Geisler2010New}.\n *         \\end{enumerate}\n *         Default: \\texttt{balanced}\n *     }\n *     \\parameter{alphaU, alphaV}{\\Float\\Or\\Texture}{\n *         Specifies the anisotropic roughness values along the tangent and\n *         bitangent directions.\n *         \\default{0.1}.\n *     }\n *     \\parameter{specular\\showbreak Reflectance}{\\Spectrum\\Or\\Texture}{\n *         Specifies the weight of the specular reflectance component.\\default{0.2}}\n *     \\parameter{diffuse\\showbreak Reflectance}{\\Spectrum\\Or\\Texture}{\n *         Specifies the weight of the diffuse reflectance component\\default{0.5}}\n * }\n * \\renderings{\n *     \\rendering{$\\alpha_u=0.1,\\ \\alpha_v=0.3$}{bsdf_ward_01_03}\n *     \\rendering{$\\alpha_u=0.3,\\ \\alpha_v=0.1$}{bsdf_ward_03_01}\n * }\n\n * This plugin implements the anisotropic Ward reflectance model and\n * several extensions. They are described in the papers\n * \\begin{enumerate}[(i)]\n *    \\item ``Measuring and Modeling Anisotropic Reflection''\n *      by Greg Ward \\cite{Ward1992Measuring}\n *    \\item ``Notes on the Ward BRDF'' by Bruce Walter \\cite{Walter2005Notes}\n *    \\item ``An Improved Normalization for the Ward Reflectance Model''\n *      by Arne D\\\"ur \\cite{Dur2006Improved}\n *    \\item ``A New Ward BRDF Model with Bounded Albedo'' by\n *      Geisler-Moroder et al. \\cite{Geisler2010New}\n * \\end{enumerate}\n *\n * Like the Phong BRDF, the Ward model does not take the Fresnel reflectance\n * of the material into account. In an experimental study by Ngan et al.\n * \\cite{Ngan2005Experimental}, the Ward model performed noticeably worse than\n * models based on microfacet theory.\n *\n * For this reason, it is usually preferable to switch to a microfacet model\n * that incorporates knowledge about the material's index of refraction. In Mitsuba,\n * two such alternatives to \\pluginref{ward} are given by the plugins\n * \\pluginref{roughconductor} and \\pluginref{roughplastic} (depending on the\n * material type).\n *\n * When using this plugin, note that the diffuse and specular reflectance\n * components should add up to a value less than or equal to one (for each\n * color channel). Otherwise, they will automatically be scaled appropriately\n * to ensure energy conservation.\n */\nclass Ward : public BSDF {\npublic:\n\t/// Supported model types\n\tenum EModelVariant {\n\t\t/// The original Ward model\n\t\tEWard = 0,\n\t\t/// Ward model with correction by Arne Duer\n\t\tEWardDuer = 1,\n\t\t/// Energy-balanced Ward model\n\t\tEBalanced = 2\n\t};\n\n\tWard(const Properties &props)\n\t\t: BSDF(props) {\n\t\tm_diffuseReflectance = new ConstantSpectrumTexture(\n\t\t\tprops.getSpectrum(\"diffuseReflectance\", Spectrum(0.5f)));\n\t\tm_specularReflectance = new ConstantSpectrumTexture(\n\t\t\tprops.getSpectrum(\"specularReflectance\", Spectrum(0.2f)));\n\n\t\tstd::string type =\n\t\t\tboost::to_lower_copy(props.getString(\"variant\", \"balanced\"));\n\t\tif (type == \"ward\")\n\t\t\tm_modelVariant = EWard;\n\t\telse if (type == \"ward-duer\")\n\t\t\tm_modelVariant = EWardDuer;\n\t\telse if (type == \"balanced\")\n\t\t\tm_modelVariant = EBalanced;\n\t\telse\n\t\t\tLog(EError, \"Specified an invalid model type \\\"%s\\\", must be \"\n\t\t\t\t\"\\\"ward\\\", \\\"ward-duer\\\", or \\\"balanced\\\"!\", type.c_str());\n\n\t\tFloat alpha = props.getFloat(\"alpha\", 0.1f),\n\t\t\t  alphaU = props.getFloat(\"alphaU\", alpha),\n\t\t\t  alphaV = props.getFloat(\"alphaV\", alpha);\n\n\t\tm_alphaU = new ConstantFloatTexture(alphaU);\n\t\tif (alphaU == alphaV)\n\t\t\tm_alphaV = m_alphaU;\n\t\telse\n\t\t\tm_alphaV = new ConstantFloatTexture(alphaV);\n\t\tm_specularSamplingWeight = 0.0f;\n\t}\n\n\tWard(Stream *stream, InstanceManager *manager)\n\t : BSDF(stream, manager) {\n\t\tm_modelVariant = (EModelVariant) stream->readUInt();\n\t\tm_diffuseReflectance = static_cast<Texture *>(manager->getInstance(stream));\n\t\tm_specularReflectance = static_cast<Texture *>(manager->getInstance(stream));\n\t\tm_alphaU = static_cast<Texture *>(manager->getInstance(stream));\n\t\tm_alphaV = static_cast<Texture *>(manager->getInstance(stream));\n\n\t\tconfigure();\n\t}\n\n\tvoid configure() {\n\t\tunsigned int extraFlags = 0;\n\t\tif (m_alphaU != m_alphaV)\n\t\t\textraFlags |= EAnisotropic;\n\n\t\tm_components.clear();\n\t\tm_components.push_back(EGlossyReflection | EFrontSide | extraFlags\n\t\t\t| ((!m_specularReflectance->isConstant() || !m_alphaU->isConstant()\n\t\t\t  || !m_alphaV->isConstant()) ? ESpatiallyVarying : 0));\n\t\tm_components.push_back(EDiffuseReflection | EFrontSide | extraFlags\n\t\t\t| (m_diffuseReflectance->isConstant() ? 0 : ESpatiallyVarying));\n\n\t\t/* Verify the input parameters and fix them if necessary */\n\t\tstd::pair<Texture *, Texture *> result = ensureEnergyConservation(\n\t\t\tm_specularReflectance, m_diffuseReflectance,\n\t\t\t\"specularReflectance\", \"diffuseReflectance\", 1.0f);\n\t\tm_specularReflectance = result.first;\n\t\tm_diffuseReflectance = result.second;\n\n\t\t/* Compute weights that steer samples towards\n\t\t   the specular or diffuse components */\n\t\tFloat dAvg = m_diffuseReflectance->getAverage().getLuminance(),\n\t\t\t  sAvg = m_specularReflectance->getAverage().getLuminance();\n\t\tm_specularSamplingWeight = sAvg / (dAvg + sAvg);\n\n\t\tm_usesRayDifferentials =\n\t\t\tm_diffuseReflectance->usesRayDifferentials() ||\n\t\t\tm_specularReflectance->usesRayDifferentials() ||\n\t\t\tm_alphaU->usesRayDifferentials() ||\n\t\t\tm_alphaV->usesRayDifferentials();\n\n\t\tBSDF::configure();\n\t}\n\n\tSpectrum getDiffuseReflectance(const Intersection &its) const {\n\t\treturn m_diffuseReflectance->eval(its);\n\t}\n\n\n\tSpectrum eval(const BSDFSamplingRecord &bRec, EMeasure measure) const {\n\t\tif (Frame::cosTheta(bRec.wi) <= 0 ||\n\t\t\tFrame::cosTheta(bRec.wo) <= 0 || measure != ESolidAngle)\n\t\t\treturn Spectrum(0.0f);\n\n\t\tbool hasSpecular = (bRec.typeMask & EGlossyReflection)\n\t\t\t\t&& (bRec.component == -1 || bRec.component == 0);\n\t\tbool hasDiffuse  = (bRec.typeMask & EDiffuseReflection)\n\t\t\t\t&& (bRec.component == -1 || bRec.component == 1);\n\n\t\tSpectrum result(0.0f);\n\t\tif (hasSpecular) {\n\t\t\tVector H = bRec.wi+bRec.wo;\n\t\t\tFloat alphaU = m_alphaU->eval(bRec.its).average();\n\t\t\tFloat alphaV = m_alphaV->eval(bRec.its).average();\n\n\t\t\tFloat factor1 = 0.0f;\n\t\t\tswitch (m_modelVariant) {\n\t\t\t\tcase EWard:\n\t\t\t\t\tfactor1 = 1.0f / (4.0f * M_PI * alphaU * alphaV *\n\t\t\t\t\t\tstd::sqrt(Frame::cosTheta(bRec.wi)*Frame::cosTheta(bRec.wo)));\n\t\t\t\t\tbreak;\n\t\t\t\tcase EWardDuer:\n\t\t\t\t\tfactor1 = 1.0f / (4.0f * M_PI * alphaU * alphaV *\n\t\t\t\t\t\tFrame::cosTheta(bRec.wi)*Frame::cosTheta(bRec.wo));\n\t\t\t\t\tbreak;\n\t\t\t\tcase EBalanced:\n\t\t\t\t\tfactor1 = dot(H,H) / (M_PI * alphaU * alphaV\n\t\t\t\t\t\t* std::pow(Frame::cosTheta(H),4));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tLog(EError, \"Unknown model type!\");\n\t\t\t}\n\n\t\t\tFloat factor2 = H.x / alphaU, factor3 = H.y / alphaV;\n\t\t\tFloat exponent = -(factor2*factor2+factor3*factor3)/(H.z*H.z);\n\t\t\tFloat specRef = factor1 * math::fastexp(exponent);\n\t\t\t/* Important to prevent numeric issues when evaluating the\n\t\t\t   sampling density of the Ward model in places where it takes\n\t\t\t   on miniscule values (Veach-MLT does this for instance) */\n\t\t\tif (specRef > 1e-10f)\n\t\t\t\tresult += m_specularReflectance->eval(bRec.its) * specRef;\n\t\t}\n\n\t\tif (hasDiffuse)\n\t\t\tresult += m_diffuseReflectance->eval(bRec.its) * INV_PI;\n\n\t\treturn result * Frame::cosTheta(bRec.wo);\n\t}\n\n\tFloat pdf(const BSDFSamplingRecord &bRec, EMeasure measure) const {\n\t\tif (Frame::cosTheta(bRec.wi) <= 0 ||\n\t\t\tFrame::cosTheta(bRec.wo) <= 0 || measure != ESolidAngle)\n\t\t\treturn 0.0f;\n\n\t\tbool hasSpecular = (bRec.typeMask & EGlossyReflection)\n\t\t\t\t&& (bRec.component == -1 || bRec.component == 0);\n\t\tbool hasDiffuse  = (bRec.typeMask & EDiffuseReflection)\n\t\t\t\t&& (bRec.component == -1 || bRec.component == 1);\n\n\t\tFloat diffuseProb = 0.0f, specProb = 0.0f;\n\n\t\tif (hasSpecular) {\n\t\t\tFloat alphaU = m_alphaU->eval(bRec.its).average();\n\t\t\tFloat alphaV = m_alphaV->eval(bRec.its).average();\n\t\t\tVector H = normalize(bRec.wi+bRec.wo);\n\t\t\tFloat factor1 = 1.0f / (4.0f * M_PI * alphaU * alphaV *\n\t\t\t\tdot(H, bRec.wi) * std::pow(Frame::cosTheta(H), 3));\n\t\t\tFloat factor2 = H.x / alphaU, factor3 = H.y / alphaV;\n\n\t\t\tFloat exponent = -(factor2*factor2+factor3*factor3)/(H.z*H.z);\n\t\t\tspecProb = factor1 * math::fastexp(exponent);\n\t\t}\n\n\t\tif (hasDiffuse)\n\t\t\tdiffuseProb = warp::squareToCosineHemispherePdf(bRec.wo);\n\n\t\tif (hasDiffuse && hasSpecular)\n\t\t\treturn m_specularSamplingWeight * specProb +\n\t\t\t\t   (1-m_specularSamplingWeight) * diffuseProb;\n\t\telse if (hasDiffuse)\n\t\t\treturn diffuseProb;\n\t\telse if (hasSpecular)\n\t\t\treturn specProb;\n\t\telse\n\t\t\treturn 0.0f;\n\t}\n\n\tinline Spectrum sample(BSDFSamplingRecord &bRec, Float &_pdf, const Point2 &_sample) const {\n\t\tPoint2 sample(_sample);\n\n\t\tbool hasSpecular = (bRec.typeMask & EGlossyReflection)\n\t\t\t\t&& (bRec.component == -1 || bRec.component == 0);\n\t\tbool hasDiffuse  = (bRec.typeMask & EDiffuseReflection)\n\t\t\t\t&& (bRec.component == -1 || bRec.component == 1);\n\n\t\tif (!hasSpecular && !hasDiffuse)\n\t\t\treturn Spectrum(0.0f);\n\n\t\tbool choseSpecular = hasSpecular;\n\n\t\tif (hasDiffuse && hasSpecular) {\n\t\t\tif (sample.x <= m_specularSamplingWeight) {\n\t\t\t\tsample.x /= m_specularSamplingWeight;\n\t\t\t} else {\n\t\t\t\tsample.x = (sample.x - m_specularSamplingWeight)\n\t\t\t\t\t/ (1-m_specularSamplingWeight);\n\t\t\t\tchoseSpecular = false;\n\t\t\t}\n\t\t}\n\n\t\tif (choseSpecular) {\n\t\t\tFloat alphaU = m_alphaU->eval(bRec.its).average();\n\t\t\tFloat alphaV = m_alphaV->eval(bRec.its).average();\n\n\t\t\tFloat phiH = std::atan(alphaV/alphaU\n\t\t\t\t* std::tan(2.0f * M_PI * sample.y));\n\t\t\tif (sample.y > 0.5f)\n\t\t\t\tphiH += M_PI;\n\t\t\tFloat cosPhiH = std::cos(phiH);\n\t\t\tFloat sinPhiH = math::safe_sqrt(1.0f-cosPhiH*cosPhiH);\n\n\t\t\tFloat thetaH = std::atan(math::safe_sqrt(\n\t\t\t\t-math::fastlog(sample.x) / (\n\t\t\t\t\t(cosPhiH*cosPhiH) / (alphaU*alphaU) +\n\t\t\t\t\t(sinPhiH*sinPhiH) / (alphaV*alphaV)\n\t\t\t)));\n\t\t\tVector H = sphericalDirection(thetaH, phiH);\n\t\t\tbRec.wo = H * (2.0f * dot(bRec.wi, H)) - bRec.wi;\n\n\t\t\tbRec.sampledComponent = 1;\n\t\t\tbRec.sampledType = EGlossyReflection;\n\n\t\t\tif (Frame::cosTheta(bRec.wo) <= 0.0f)\n\t\t\t\treturn Spectrum(0.0f);\n\t\t} else {\n\t\t\tbRec.wo = warp::squareToCosineHemisphere(sample);\n\t\t\tbRec.sampledComponent = 0;\n\t\t\tbRec.sampledType = EDiffuseReflection;\n\t\t}\n\t\tbRec.eta = 1.0f;\n\n\t\t_pdf = pdf(bRec, ESolidAngle);\n\n\t\tif (_pdf == 0)\n\t\t\treturn Spectrum(0.0f);\n\t\telse\n\t\t\treturn eval(bRec, ESolidAngle) / _pdf;\n\t}\n\n\tSpectrum sample(BSDFSamplingRecord &bRec, const Point2 &sample) const {\n\t\tFloat pdf;\n\t\treturn Ward::sample(bRec, pdf, sample);\n\t}\n\n\tvoid addChild(const std::string &name, ConfigurableObject *child) {\n\t\tif (child->getClass()->derivesFrom(MTS_CLASS(Texture))) {\n\t\t\tif (name == \"alphaU\")\n\t\t\t\tm_alphaU = static_cast<Texture *>(child);\n\t\t\telse if (name == \"alphaV\")\n\t\t\t\tm_alphaV = static_cast<Texture *>(child);\n\t\t\telse if (name == \"diffuseReflectance\")\n\t\t\t\tm_diffuseReflectance = static_cast<Texture *>(child);\n\t\t\telse if (name == \"specularReflectance\")\n\t\t\t\tm_specularReflectance = static_cast<Texture *>(child);\n\t\t\telse\n\t\t\t\tBSDF::addChild(name, child);\n\t\t} else {\n\t\t\tBSDF::addChild(name, child);\n\t\t}\n\t}\n\n\tvoid serialize(Stream *stream, InstanceManager *manager) const {\n\t\tBSDF::serialize(stream, manager);\n\n\t\tstream->writeUInt(m_modelVariant);\n\t\tmanager->serialize(stream, m_diffuseReflectance.get());\n\t\tmanager->serialize(stream, m_specularReflectance.get());\n\t\tmanager->serialize(stream, m_alphaU.get());\n\t\tmanager->serialize(stream, m_alphaV.get());\n\t}\n\n\tFloat getRoughness(const Intersection &its, int component) const {\n\t\tAssert(component == 0 || component == 1);\n\n\t\tif (component == 0)\n\t\t\treturn 0.5f * (m_alphaU->eval(its).average()\n\t\t\t\t+ m_alphaV->eval(its).average());\n\t\telse\n\t\t\treturn std::numeric_limits<Float>::infinity();\n\t}\n\n\tShader *createShader(Renderer *renderer) const;\n\n\tstd::string toString() const {\n\t\tstd::ostringstream oss;\n\t\toss << \"Ward[\" << endl\n\t\t\t<< \"  id = \\\"\" << getID() << \"\\\",\" << endl\n\t\t\t<< \"  variant = \";\n\n\t\tswitch (m_modelVariant) {\n\t\t\tcase EWard: oss << \"ward,\" << endl; break;\n\t\t\tcase EWardDuer: oss << \"wardDuer,\" << endl; break;\n\t\t\tcase EBalanced: oss << \"balanced,\" << endl; break;\n\t\t\tdefault: Log(EError, \"Unknown model type!\");\n\t\t}\n\n\t\toss << \"  diffuseReflectance = \" << indent(m_diffuseReflectance->toString()) << \",\" << endl\n\t\t\t<< \"  specularReflectance = \" << indent(m_specularReflectance->toString()) << \",\" << endl\n\t\t\t<< \"  specularSamplingWeight = \" << m_specularSamplingWeight << \",\" << endl\n\t\t\t<< \"  alphaU = \" << indent(m_alphaU->toString()) << \",\" << endl\n\t\t\t<< \"  alphaV = \" << indent(m_alphaV->toString()) << endl\n\t\t\t<< \"]\";\n\t\treturn oss.str();\n\t}\n\n\tMTS_DECLARE_CLASS()\nprivate:\n\tEModelVariant m_modelVariant;\n\tref<Texture> m_diffuseReflectance;\n\tref<Texture> m_specularReflectance;\n\tref<Texture> m_alphaU;\n\tref<Texture> m_alphaV;\n\tFloat m_specularSamplingWeight;\n};\n\n// ================ Hardware shader implementation ================\n\n/**\n * GLSL port of the Ward shader. This version only implements the variant\n * with energy balance. When the roughness is lower than\n * \\alpha < 0.2, the shader clamps it to 0.2 so that it will still perform\n * reasonably well in a VPL-based preview.\n */\nclass WardShader : public Shader {\npublic:\n\tWardShader(Renderer *renderer,\n\t\t\tconst Texture *diffuseColor,\n\t\t\tconst Texture *specularColor,\n\t\t\tconst Texture *alphaU,\n\t\t\tconst Texture *alphaV) : Shader(renderer, EBSDFShader),\n\t\t\tm_diffuseReflectance(diffuseColor),\n\t\t\tm_specularReflectance(specularColor),\n\t\t\tm_alphaU(alphaU), m_alphaV(alphaV) {\n\t\tm_diffuseReflectanceShader = renderer->registerShaderForResource(m_diffuseReflectance.get());\n\t\tm_specularReflectanceShader = renderer->registerShaderForResource(m_specularReflectance.get());\n\t\tm_alphaUShader = renderer->registerShaderForResource(m_alphaU.get());\n\t\tm_alphaVShader = renderer->registerShaderForResource(m_alphaV.get());\n\t}\n\n\tbool isComplete() const {\n\t\treturn m_diffuseReflectanceShader.get() != NULL &&\n\t\t\t   m_specularReflectanceShader.get() != NULL &&\n\t\t\t   m_alphaU.get() != NULL &&\n\t\t\t   m_alphaV.get() != NULL;\n\t}\n\n\tvoid putDependencies(std::vector<Shader *> &deps) {\n\t\tdeps.push_back(m_diffuseReflectanceShader.get());\n\t\tdeps.push_back(m_specularReflectanceShader.get());\n\t\tdeps.push_back(m_alphaUShader.get());\n\t\tdeps.push_back(m_alphaVShader.get());\n\t}\n\n\tvoid cleanup(Renderer *renderer) {\n\t\trenderer->unregisterShaderForResource(m_diffuseReflectance.get());\n\t\trenderer->unregisterShaderForResource(m_specularReflectance.get());\n\t\trenderer->unregisterShaderForResource(m_alphaU.get());\n\t\trenderer->unregisterShaderForResource(m_alphaV.get());\n\t}\n\n\tvoid generateCode(std::ostringstream &oss,\n\t\t\tconst std::string &evalName,\n\t\t\tconst std::vector<std::string> &depNames) const {\n\t\toss << \"vec3 \" << evalName << \"(vec2 uv, vec3 wi, vec3 wo) {\" << endl\n\t\t\t<< \"    if (wi.z <= 0.0 || wo.z <= 0.0)\" << endl\n\t\t\t<< \"    \treturn vec3(0.0);\" << endl\n\t\t\t<< \"    vec3 H = wi + wo;\" << endl\n\t\t\t<< \"    float cosSqr = H.z * H.z;\" << endl\n\t\t\t<< \"    float alphaU = max(0.3, \" << depNames[2] << \"(uv)[0]);\" << endl\n\t\t\t<< \"    float alphaV = max(0.3, \" << depNames[3] << \"(uv)[0]);\" << endl\n\t\t\t<< \"    float factor1 = dot(H, H)/(3.1415*alphaU*alphaV*cosSqr*cosSqr);\"  << endl\n\t\t\t<< \"    float factor2 = H.x / alphaU, factor3 = H.y / alphaV;\" << endl\n\t\t\t<< \"    float exponent = -(factor2*factor2 + factor3*factor3)/(H.z*H.z);\" << endl\n\t\t\t<< \"    float specRef = factor1 * exp(exponent);\" << endl\n\t\t\t<< \"    return (\" << depNames[0] << \"(uv) * inv_pi\" << endl\n\t\t\t<< \"           + \" << depNames[1] << \"(uv) * specRef) * cosTheta(wo);\" << endl\n\t\t\t<< \"}\" << endl\n\t\t\t<< \"vec3 \" << evalName << \"_diffuse(vec2 uv, vec3 wi, vec3 wo) {\" << endl\n\t\t\t<< \"    if (wi.z <= 0.0 || wo.z <= 0.0)\" << endl\n\t\t\t<< \"    \treturn vec3(0.0);\" << endl\n\t\t\t<< \"    return \" << depNames[0] << \"(uv) * (inv_pi * cosTheta(wo));\" << endl\n\t\t\t<< \"}\" << endl;\n\t}\n\n\tMTS_DECLARE_CLASS()\nprivate:\n\tref<const Texture> m_diffuseReflectance;\n\tref<const Texture> m_specularReflectance;\n\tref<const Texture> m_alphaU;\n\tref<const Texture> m_alphaV;\n\tref<Shader> m_diffuseReflectanceShader;\n\tref<Shader> m_specularReflectanceShader;\n\tref<Shader> m_alphaUShader;\n\tref<Shader> m_alphaVShader;\n};\n\nShader *Ward::createShader(Renderer *renderer) const {\n\treturn new WardShader(renderer, m_diffuseReflectance.get(),\n\t\tm_specularReflectance.get(), m_alphaU.get(), m_alphaV.get());\n}\n\nMTS_IMPLEMENT_CLASS(WardShader, false, Shader)\nMTS_IMPLEMENT_CLASS_S(Ward, false, BSDF);\nMTS_EXPORT_PLUGIN(Ward, \"Anisotropic Ward BRDF\");\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "4dde99631ced20fb8938d0ec49204b2e710bbf1a", "size": 17700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/bsdfs/ward.cpp", "max_stars_repo_name": "NTForked-ML/pbrs", "max_stars_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T00:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:33:10.000Z", "max_issues_repo_path": "mitsuba-af602c6fd98a/src/bsdfs/ward.cpp", "max_issues_repo_name": "NTForked-ML/pbrs", "max_issues_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-08-15T18:22:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-01T05:44:41.000Z", "max_forks_repo_path": "mitsuba-af602c6fd98a/src/bsdfs/ward.cpp", "max_forks_repo_name": "NTForked-ML/pbrs", "max_forks_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-21T03:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T06:55:34.000Z", "avg_line_length": 35.8299595142, "max_line_length": 97, "alphanum_fraction": 0.6762711864, "num_tokens": 5182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766828768970446, "lm_q2_score": 0.03732689015525377, "lm_q1q2_score": 0.012230838181953689}}
{"text": "//Tencent is pleased to support the open source community by making FeatherCNN available.\n\n//Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.\n\n//Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n//in compliance with the License. You may obtain a copy of the License at\n//\n//https://opensource.org/licenses/BSD-3-Clause\n//\n//Unless required by applicable law or agreed to in writing, software distributed\n//under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n//CONDITIONS OF ANY KIND, either express or implied. See the License for the\n//specific language governing permissions and limitations under the License.\n\n#include <booster/sgemv.h>\n\n#include <assert.h>\n#include <arm_neon.h>\n#include <string.h>\n\ntemplate <bool fuseBias, bool fuseRelu>\nvoid fully_connected_inference_direct(const int input_size, const int output_size, const float *x, const float *y, float *z, const int num_threads, float* bias_arr)\n{\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int i = 0; i < output_size; i++)\n    {\n        float sum = 0;\n        for (int j = 0; j < input_size; j++)\n            sum += x[j] * y[i * input_size + j];\n        if (fuseBias)\n            sum += bias_arr[i];\n        if (fuseRelu)\n            sum = (sum > 0.f) ? sum : 0.f;\n        z[i] = sum;\n    }\n}\n\ntemplate <bool fuseBias, bool fuseRelu>\nvoid fully_connected_transpose_inference(const int input_size, const int output_size, const float *x, const float *y, float *z, const int num_threads, float* bias_arr)\n{\n    assert(input_size % 8 == 0);\n    assert(output_size % 8 == 0);\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int k = 0; k < output_size / 8; k++)\n    {\n        float32x4_t vBias = vld1q_f32(bias_arr + k * 8);\n        float32x4_t vBias1 = vld1q_f32(bias_arr + k * 8 + 4);\n        float32x4_t vZero = vdupq_n_f32(0.f);\n        const float *yPtr = y + k * 8 * input_size;\n        float32x4_t res = {0.0, 0.0, 0.0, 0.0};\n        float32x4_t res1 = {0.0, 0.0, 0.0, 0.0};\n        float32x4_t va, vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7;\n        for (int i = 0; i < input_size; i += 4)\n        {\n            //          float32x4_t v1, v2;\n            va = vld1q_f32(x + i);\n\n            vb0 = vld1q_f32(yPtr);\n            vb1 = vld1q_f32(yPtr + 4);\n            vb2 = vld1q_f32(yPtr + 8);\n            vb3 = vld1q_f32(yPtr + 12);\n            vb4 = vld1q_f32(yPtr + 16);\n            vb5 = vld1q_f32(yPtr + 20);\n            vb6 = vld1q_f32(yPtr + 24);\n            vb7 = vld1q_f32(yPtr + 28);\n\n#if __aarch64__\n            res = vfmaq_laneq_f32(res, vb0, va, 0);\n            res1 = vfmaq_laneq_f32(res1, vb1, va, 0);\n            res = vfmaq_laneq_f32(res, vb2, va, 1);\n            res1 = vfmaq_laneq_f32(res1, vb3, va, 1);\n            res = vfmaq_laneq_f32(res, vb4, va, 2);\n            res1 = vfmaq_laneq_f32(res1, vb5, va, 2);\n            res = vfmaq_laneq_f32(res, vb6, va, 3);\n            res1 = vfmaq_laneq_f32(res1, vb7, va, 3);\n#else\n            res = vmlaq_f32(res, vb0, vld1q_dup_f32(x + i + 0));\n            res1 = vmlaq_f32(res1, vb1, vld1q_dup_f32(x + i + 0));\n            res = vmlaq_f32(res, vb2, vld1q_dup_f32(x + i + 1));\n            res1 = vmlaq_f32(res1, vb3, vld1q_dup_f32(x + i + 1));\n            res = vmlaq_f32(res, vb4, vld1q_dup_f32(x + i + 2));\n            res1 = vmlaq_f32(res1, vb5, vld1q_dup_f32(x + i + 2));\n            res = vmlaq_f32(res, vb6, vld1q_dup_f32(x + i + 3));\n            res1 = vmlaq_f32(res1, vb7, vld1q_dup_f32(x + i + 3));\n#endif\n            yPtr += 32;\n        }\n\n        if (fuseBias)\n        {\n            res = vaddq_f32(res, vBias);\n            res1 = vaddq_f32(res1, vBias1);\n        }\n        if (fuseRelu)\n        {\n            res = vmaxq_f32(res, vZero);\n            res1 = vmaxq_f32(res1, vZero);\n        }\n        vst1q_f32((float32_t *)(z + 8 * k), res);\n        vst1q_f32((float32_t *)(z + 8 * k + 4), res1);\n    }\n}\n\ntemplate void fully_connected_inference_direct<false, false>(const int, const int, const float *, const float *, float *, const int, float*);\ntemplate void fully_connected_inference_direct<false,  true>(const int, const int, const float *, const float *, float *, const int, float*);\ntemplate void fully_connected_inference_direct<true,  false>(const int, const int, const float *, const float *, float *, const int, float*);\ntemplate void fully_connected_inference_direct<true,   true>(const int, const int, const float *, const float *, float *, const int, float*);\n\ntemplate void fully_connected_transpose_inference<false, false>(const int, const int, const float *, const float *, float *, const int, float*);\ntemplate void fully_connected_transpose_inference<false,  true>(const int, const int, const float *, const float *, float *, const int, float*);\ntemplate void fully_connected_transpose_inference<true,  false>(const int, const int, const float *, const float *, float *, const int, float*);\ntemplate void fully_connected_transpose_inference<true,   true>(const int, const int, const float *, const float *, float *, const int, float*);\n\n#if 0\nvoid fully_connected_inference_direct_BiasReLU(int input_size, int output_size, float *x, float *y, float *z, float* biasArr, int num_threads)\n{\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int i = 0; i < output_size; i++)\n    {\n        float sum = 0.f;\n        for (int j = 0; j < input_size; j++)\n            sum += x[j] * y[i * input_size + j];\n\n        sum += biasArr[i];\n        if (sum < 0.f) sum = 0.f;\n        z[i] = sum;\n    }\n}\n\nvoid fully_connected_transpose_inference_neon8_BiasReLU(int input_size, int output_size, float *x, float *y, float *z, float* biasArr, int num_threads)\n{\n    assert(input_size % 8 == 0);\n    assert(output_size % 8 == 0);\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int k = 0; k < output_size / 8; k++)\n    {\n        float *yPtr = y + k * 8 * input_size;\n        const float32x4_t vzero = vdupq_n_f32(0.f);\n\n        float32x4_t res  = vld1q_f32(biasArr + k * 8);\n        float32x4_t res1 = vld1q_f32(biasArr + k * 8 + 4);\n\n        float32x4_t va, vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7;\n        for (int i = 0; i < input_size; i += 4)\n        {\n            va = vld1q_f32(x + i);\n\n            vb0 = vld1q_f32(yPtr);\n            vb1 = vld1q_f32(yPtr + 4);\n            vb2 = vld1q_f32(yPtr + 8);\n            vb3 = vld1q_f32(yPtr + 12);\n            vb4 = vld1q_f32(yPtr + 16);\n            vb5 = vld1q_f32(yPtr + 20);\n            vb6 = vld1q_f32(yPtr + 24);\n            vb7 = vld1q_f32(yPtr + 28);\n\n#if __aarch64__\n            res = vfmaq_laneq_f32(res, vb0, va, 0);\n            res1 = vfmaq_laneq_f32(res1, vb1, va, 0);\n            res = vfmaq_laneq_f32(res, vb2, va, 1);\n            res1 = vfmaq_laneq_f32(res1, vb3, va, 1);\n            res = vfmaq_laneq_f32(res, vb4, va, 2);\n            res1 = vfmaq_laneq_f32(res1, vb5, va, 2);\n            res = vfmaq_laneq_f32(res, vb6, va, 3);\n            res1 = vfmaq_laneq_f32(res1, vb7, va, 3);\n#else\n            res = vmlaq_f32(res, vb0, vld1q_dup_f32(x + i + 0));\n            res1 = vmlaq_f32(res1, vb1, vld1q_dup_f32(x + i + 0));\n            res = vmlaq_f32(res, vb2, vld1q_dup_f32(x + i + 1));\n            res1 = vmlaq_f32(res1, vb3, vld1q_dup_f32(x + i + 1));\n            res = vmlaq_f32(res, vb4, vld1q_dup_f32(x + i + 2));\n            res1 = vmlaq_f32(res1, vb5, vld1q_dup_f32(x + i + 2));\n            res = vmlaq_f32(res, vb6, vld1q_dup_f32(x + i + 3));\n            res1 = vmlaq_f32(res1, vb7, vld1q_dup_f32(x + i + 3));\n#endif\n            yPtr += 32;\n        }\n\n        //res  = vaddq_f32(res, vBias);\n        //res1 = vaddq_f32(res, vBias1);\n\n        res  = vmaxq_f32(res, vzero);\n        res1 = vmaxq_f32(res1, vzero);\n\n        vst1q_f32((float32_t *)(z + 8 * k), res);\n        vst1q_f32((float32_t *)(z + 8 * k + 4), res1);\n    }\n}\n/*\nvoid fully_connected_transpose_inference_neon(int input_size, int output_size, float *x, float *y, float *z)\n{\n    assert(input_size %4==0);\n    assert(output_size%4==0);\n//#pragma omp parallel for num_threads(32) schedule(static)\n    for(int k=0; k<output_size/4; k++)\n    {\n        float *yPtr = y + k*4*input_size;\n        float32x4_t res = {0.0,0.0,0.0,0.0};\n\n        for(int i=0; i<input_size; i+=4)\n        {\n            float32x4_t v1, v2;\n            v2 = vld1q_f32(x + i);\n\n#if __aarch64__\n            v1 = vld1q_f32(yPtr);\n            res = vfmaq_laneq_f32(res, v1, v2, 0);\n\n            v1 = vld1q_f32(yPtr + 4);\n            res = vfmaq_laneq_f32(res, v1, v2, 1);\n\n            v1 = vld1q_f32(yPtr + 8);\n            res = vfmaq_laneq_f32(res, v1, v2, 2);\n\n            v1 = vld1q_f32(yPtr + 12);\n            res = vfmaq_laneq_f32(res, v1, v2, 3);\n#else\n            v1 = vld1q_f32(yPtr);\n            res = vmlaq_f32(res, v1, vld1q_dup_f32(x + i + 0));\n\n            v1 = vld1q_f32(yPtr + 4);\n            res = vmlaq_f32(res, v1, vld1q_dup_f32(x + i + 1));\n\n            v1 = vld1q_f32(yPtr + 8);\n            res = vmlaq_f32(res, v1, vld1q_dup_f32(x + i + 2));\n\n            v1 = vld1q_f32(yPtr + 12);\n            res = vmlaq_f32(res, v1, vld1q_dup_f32(x + i + 3));\n#endif\n            yPtr += 16;\n        }\n        vst1q_f32((float32_t *) (z+4*k), res);\n    }\n}\n*/\n#endif\nvoid matrixTranspose(float* array, size_t m, size_t n, float *buffer)//  A[m][n] -> A[n][m]\n{\n    for (int i = 0; i < m; i++)    for (int j = 0; j < n; j++)\n            buffer[j * m + i] = array[i * n + j];\n    memcpy(array, buffer, m * n * sizeof(float));\n}\n", "meta": {"hexsha": "2df1cfc380bf9c92955974625112737e088d1faa", "size": 9585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/booster/arm/sgemv.cpp", "max_stars_repo_name": "chenaili6/FeatherCNN", "max_stars_repo_head_hexsha": "52cd8c8749ed584461a88b1f04749bb35a48f9a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-14T09:00:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:11:54.000Z", "max_issues_repo_path": "src/booster/arm/sgemv.cpp", "max_issues_repo_name": "nihui/FeatherCNN", "max_issues_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/booster/arm/sgemv.cpp", "max_forks_repo_name": "nihui/FeatherCNN", "max_forks_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4444444444, "max_line_length": 167, "alphanum_fraction": 0.5775691184, "num_tokens": 3260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.024423087258135485, "lm_q1q2_score": 0.012211543629067742}}
{"text": "#pragma once\n\n// #include <any>\n// #include <boost/coroutine2/all.hpp>\n#include <cassert>\n#include <py2cpp/py2cpp.hpp>\n// #include <range/v3/view/enumerate.hpp>\n#include <type_traits>\n#include <utility>\n#include <vector>\n#include <xnetwork/classes/coreviews.hpp>  // import AtlasView, AdjacencyView\n#include <xnetwork/classes/graph.hpp>\n#include <xnetwork/classes/reportviews.hpp>  // import NodeView, EdgeView, DegreeView\n\n#if __cplusplus > 201703L\n#    include <cppcoro/generator.hpp>\n#endif\n\nnamespace xnetwork {\n\n    /** Base class for directed graphs.\n\n        A DiGraphS stores nodes and edges with optional data, or attributes.\n\n        DiGraphSs hold directed edges.  Self loops are allowed but multiple\n        (parallel) edges are not.\n\n        Nodes can be arbitrary (hashable) C++ objects with optional\n        key/value attributes. By convention `None` is not used as a node.\n\n        Edges are represented as links between nodes with optional\n        key/value attributes.\n\n        Parameters\n        ----------\n        node_container : input graph (optional, default: None)\n            Data to initialize graph. If None (default) an empty\n            graph is created.  The data can be any format that is supported\n            by the to_networkx_graph() function, currently including edge list,\n            dict of dicts, dict of lists, NetworkX graph, NumPy matrix\n            or 2d ndarray, SciPy sparse matrix, or PyGraphviz graph.\n\n        See Also\n        --------\n        Graph\n        DiGraph\n        MultiGraph\n        MultiDiGraph\n        OrderedGraph\n\n        Examples\n        --------\n        Create an empty graph structure (a \"null graph\") with 5 nodes and\n        no edges.\n\n            > auto v = std::vector{3, 4, 2, 8};\n            > auto G = xnetwork::DiGraphS(v);\n\n            > auto va = py::dict{{3, 0.1}, {4, 0.5}, {2, 0.2}};\n            > auto G = xnetwork::DiGraphS(va);\n\n            > auto r = py::range(100);\n            > auto G = xnetwork::DiGraphS(r);\n\n        G can be grown in several ways.\n\n        **Nodes:**\n\n        Add one node at a time:\n\n            > G.add_node(1)\n\n        Add the nodes from any container (a list, dict, set or\n        even the lines from a file or the nodes from another graph).\n\n            > G.add_nodes_from([2, 3])\n            > G.add_nodes_from(range(100, 110))\n            > H = xnetwork::path_graph(10)\n            > G.add_nodes_from(H)\n\n        In addition to strings and integers any hashable C++ object\n        (except None) can represent a node, e.g. a customized node object,\n        or even another DiGraphS.\n\n            > G.add_node(H)\n\n        **Edges:**\n\n        G can also be grown by adding edges.\n\n        Add one edge,\n\n            > G.add_edge(1, 2);\n\n        a list of edges,\n\n            > G.add_edges_from([(1, 2), (1, 3)]);\n\n        or a collection of edges,\n\n            > G.add_edges_from(H.edges());\n\n        If some edges connect nodes not yet in the graph, the nodes\n        are added automatically.  There are no errors when adding\n        nodes or edges that already exist.\n\n        **Attributes:**\n\n        Each graph can hold key/value attribute pairs\n        in an associated attribute dictionary (the keys must be hashable).\n        By default these are empty, but can be added or changed using\n        direct manipulation of the attribute\n        dictionaries named graph, node and edge respectively.\n\n            > G.graph[\"day\"] = std::any(\"Friday\");\n        {'day': 'Friday'}\n\n        **Subclasses (Advanced):**\n\n        The DiGraphS class uses a container-of-container-of-container data\n       structure. The outer dict (node_dict) holds adjacency information keyed by\n       node. The next dict (adjlist_dict) represents the adjacency information and\n       holds edge data keyed by neighbor.  The inner dict (edge_attr_dict)\n       represents the edge data and holds edge attribute values keyed by attribute\n       names.\n\n        Each of these three dicts can be replaced in a subclass by a user defined\n        dict-like object. In general, the dict-like features should be\n        maintained but extra features can be added. To replace one of the\n        dicts create a new graph class by changing the class(!) variable\n        holding the factory for that dict-like structure. The variable names are\n        node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,\n        adjlist_outer_dict_factory, edge_attr_dict_factory and\n       graph_attr_dict_factory.\n\n        node_dict_factory : function, (default: dict)\n            Factory function to be used to create the dict containing node\n            attributes, keyed by node id.\n            It should require no arguments and return a dict-like object\n\n        node_attr_dict_factory: function, (default: dict)\n            Factory function to be used to create the node attribute\n            dict which holds attribute values keyed by attribute name.\n            It should require no arguments and return a dict-like object\n\n        adjlist_outer_dict_factory : function, (default: dict)\n            Factory function to be used to create the outer-most dict\n            in the data structure that holds adjacency info keyed by node.\n            It should require no arguments and return a dict-like object.\n\n        adjlist_inner_dict_factory : function, (default: dict)\n            Factory function to be used to create the adjacency list\n            dict which holds edge data keyed by neighbor.\n            It should require no arguments and return a dict-like object\n\n        edge_attr_dict_factory : function, (default: dict)\n            Factory function to be used to create the edge attribute\n            dict which holds attribute values keyed by attribute name.\n            It should require no arguments and return a dict-like object.\n\n        graph_attr_dict_factory : function, (default: dict)\n            Factory function to be used to create the graph attribute\n            dict which holds attribute values keyed by attribute name.\n            It should require no arguments and return a dict-like object.\n\n        Typically, if your extension doesn't impact the data structure all\n        methods will inherit without issue except: `to_directed/to_undirected`.\n        By default these methods create a DiGraph/DiGraphS class and you probably\n        want them to create your extension of a DiGraph/DiGraphS. To facilitate\n        this we define two class variables that you can set in your subclass.\n\n        to_directed_class : callable, (default: DiGraph or MultiDiGraph)\n            Class to create a new graph structure in the `to_directed` method.\n            If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.\n\n        to_undirected_class : callable, (default: DiGraphS or MultiGraph)\n            Class to create a new graph structure in the `to_undirected` method.\n            If `None`, a NetworkX class (DiGraphS or MultiGraph) is used.\n\n        Examples\n        --------\n\n        Create a low memory graph class that effectively disallows edge\n        attributes by using a single attribute dict for all edges.\n        This reduces the memory used, but you lose edge attributes.\n\n            > class ThinGraph(xnetwork::DiGraphS):\n        ...     all_edge_dict = {'weight': 1}\n        ...     def single_edge_dict(self):\n        ...         return self.all_edge_dict\n        ...     edge_attr_dict_factory = single_edge_dict\n            > G = ThinGraph()\n            > G.add_edge(2, 1)\n            > G[2][1]\n        {'weight': 1}\n            > G.add_edge(2, 2)\n            > G[2][1] is G[2][2]\n        True\n\n        Please see :mod:`~networkx.classes.ordered` for more examples of\n        creating graph subclasses by overwriting the base class `dict` with\n        a dictionary-like object.\n    */\n    template <typename nodeview_t, typename adjlist_t = py::dict<Value_type<nodeview_t>, int>,\n              typename adjlist_outer_dict_factory = py::dict<Value_type<nodeview_t>, adjlist_t>>\n    class DiGraphS : public Graph<nodeview_t, adjlist_t, adjlist_outer_dict_factory> {\n        using _Base = Graph<nodeview_t, adjlist_t, adjlist_outer_dict_factory>;\n\n      public:\n        using Node = typename _Base::Node;  // luk\n        using edge_t = std::pair<Node, Node>;\n        // using graph_attr_dict_factory = typename _Base::graph_attr_dict_factory;\n        // using adjlist_outer_dict_factory =\n        //     typename _Base::adjlist_outer_dict_factory;\n        using key_type = typename _Base::key_type;\n        using value_type = typename _Base::value_type;\n\n      public:\n        adjlist_outer_dict_factory& _succ;  // successor\n\n        /** Initialize a graph with edges, name, or graph attributes.\n\n            Parameters\n            ----------\n            node_container : input nodes\n\n            Examples\n            --------\n                > v = std::vector{5, 3, 2};\n                > G = xnetwork::DiGraphS(v);  // or DiGraph, MultiGraph, MultiDiGraph, etc\n\n                > r = py::range(100);\n                > G = xnetwork::DiGraphS(r, r);  // or DiGraph, MultiGraph, MultiDiGraph,\n           etc\n        */\n        explicit DiGraphS(const nodeview_t& Nodes) : _Base{Nodes}, _succ{_Base::_adj} {}\n\n        explicit DiGraphS(uint32_t num_nodes) : _Base{num_nodes}, _succ{_Base::_adj} {}\n\n        /** DiGraphS adjacency object holding the neighbors of each node.\n\n            This object is a read-only dict-like structure with node keys\n            and neighbor-dict values.  The neighbor-dict is keyed by neighbor\n            to the edge-data-dict.  So `G.adj[3][2]['color'] = 'blue'` sets\n            the color of the edge `(3, 2)` to `\"blue\"`.\n\n            Iterating over G.adj behaves like a dict. Useful idioms include\n            `for nbr, datadict in G.adj[n].items():`.\n\n            The neighbor information is also provided by subscripting the graph.\n            So `for nbr, foovalue in G[node].data('foo', default=1):` works.\n\n            For directed graphs, `G.adj` holds outgoing (successor) info.\n        */\n        auto adj() const {\n            using T = decltype(this->_succ);\n            return AdjacencyView<T>(this->_succ);\n        }\n\n        /** Graph adjacency object holding the successors of each node.\n\n            This object is a read-only dict-like structure with node keys\n            and neighbor-dict values.  The neighbor-dict is keyed by neighbor\n            to the edge-data-dict.  So `G.succ[3][2]['color'] = 'blue'` sets\n            the color of the edge `(3, 2)` to `\"blue\"`.\n\n            Iterating over G.succ behaves like a dict. Useful idioms include\n            `for nbr, datadict in G.succ[n].items():`.  A data-view not provided\n            by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):`\n            and a default can be set via a `default` argument to the `data` method.\n\n            The neighbor information is also provided by subscripting the graph.\n            So `for nbr, foovalue in G[node].data('foo', default=1):` works.\n\n            For directed graphs, `G.adj` is identical to `G.succ`.\n        */\n        auto succ() const {\n            using T = decltype(this->_succ);\n            return AdjacencyView<T>(this->_succ);\n        }\n\n        /** Add an edge between u and v.\n\n            The nodes u and v will be automatically added if (they are\n            not already : the graph.\n\n            Edge attributes can be specified with keywords or by directly\n            accessing the edge\"s attribute dictionary. See examples below.\n\n            Parameters\n            ----------\n            u, v : nodes\n                Nodes can be, for example, strings or numbers.\n                Nodes must be hashable (and not None) C++ objects.\n\n            See Also\n            --------\n            add_edges_from : add a collection of edges\n\n            Notes\n            -----\n            Adding an edge that already exists updates the edge data.\n\n            Many XNetwork algorithms designed for weighted graphs use\n            an edge attribute (by default `weight`) to hold a numerical value.\n\n            Examples\n            --------\n            The following all add the edge e=(1, 2) to graph G) {\n\n                > G = xnetwork::DiGraphS()   // or DiGraph, MultiGraph, MultiDiGraph, etc\n                > e = (1, 2);\n                > G.add_edge(1, 2)           // explicit two-node form\n                > G.add_edges_from([(1, 2)]);  // add edges from iterable container\n\n            Associate data to edges using keywords) {\n\n                > G.add_edge(1, 2);\n\n            For non-string attribute keys, use subscript notation.\n\n                > G.add_edge(1, 2);\n                > G[1][2].update({0: 5});\n                > G.edges()[1, 2].update({0: 5});\n         */\n        template <typename U = key_type> auto add_edge(const Node& u, const Node& v) ->\n            typename std::enable_if<std::is_same<U, value_type>::value>::type {\n            // auto [u, v] = u_of_edge, v_of_edge;\n            // add nodes\n            // assert(this->s->_node.contains(u));\n            // assert(this->s->_node.contains(v));\n            // add the edge\n            // datadict = this->_adj[u].get(v, this->edge_attr_dict_factory());\n            // datadict.update(attr);\n            this->_succ[u].insert(v);\n            // this->_prev[v].insert(u);\n            // this->_num_of_edges += 1;\n        }\n\n        template <typename U = key_type> auto add_edge(const Node& u, const Node& v) ->\n            typename std::enable_if<!std::is_same<U, value_type>::value>::type {\n            // auto [u, v] = u_of_edge, v_of_edge;\n            // add nodes\n            // assert(this->s->_node.contains(u));\n            // assert(this->s->_node.contains(v));\n            // add the edge\n            // datadict = this->_adj[u].get(v, this->edge_attr_dict_factory());\n            // datadict.update(attr);\n            using T = typename adjlist_t::mapped_type;\n            auto data = this->_adj[u].get(v, T{});\n            this->_succ[u][v] = data;\n            // this->_prev[v][u] = data;\n            // this->_num_of_edges += 1;\n        }\n\n        template <typename T> auto add_edge(const Node& u, const Node& v, const T& data) {\n            // assert(this->s->_node.contains(u));\n            // assert(this->s->_node.contains(v));\n            this->_succ[u][v] = data;\n            // this->_num_of_edges += 1;\n        }\n\n        template <typename C1, typename C2> auto add_edges_from(const C1& edges, const C2& data) {\n            auto N = edges.size();\n            for (auto i = 0U; i != N; ++i) {\n                const auto& e = edges[i];\n                this->add_edge(e.first, e.second, data[i]);\n            }\n        }\n\n        /** Returns True if node u has successor v.\n\n            This is true if graph has the edge u->v.\n        */\n        auto has_successor(const Node& u, const Node& v) -> bool {\n            return this->_node.contains(u) && this->_succ[u].contains(v);\n        }\n\n        /** Returns an iterator over successor nodes of n.\n\n            A successor of n is a node m such that there exists a directed\n            edge from n to m.\n\n            Parameters\n            ----------\n            n : node\n               A node in the graph\n\n            Raises\n            -------\n            NetworkXError\n               If n is not in the graph.\n\n            See Also\n            --------\n            predecessors\n\n            Notes\n            -----\n            neighbors() and successors() are the same.\n        */\n        auto successors(const Node& n) -> auto& { return this->_succ[n]; }\n\n        auto successors(const Node& n) const -> const auto& { return this->_succ[n]; }\n\n        /** An OutEdgeView of the DiGraph as G.edges().\n\n            edges(self, nbunch=None, data=False, default=None)\n\n            The OutEdgeView provides set-like operations on the edge-tuples\n            as well as edge attribute lookup. When called, it also provides\n            an EdgeDataView object which allows control of access to edge\n            attributes (but does not provide set-like operations).\n            Hence, `G.edges()[u, v]['color']` provides the value of the color\n            attribute for edge `(u, v)` while\n            `for (u, v, c) in G.edges().data('color', default='red'):`\n            iterates through all the edges yielding the color attribute\n            with default `'red'` if no color attribute exists.\n\n            Parameters\n            ----------\n            nbunch : single node, container, or all nodes (default= all nodes)\n                The view will only report edges incident to these nodes.\n            data : string or bool, optional (default=False)\n                The edge attribute returned in 3-tuple (u, v, ddict[data]).\n                If True, return edge attribute dict in 3-tuple (u, v, ddict).\n                If False, return 2-tuple (u, v).\n            default : value, optional (default=None)\n                Value used for edges that don't have the requested attribute.\n                Only relevant if data is not True or False.\n\n            Returns\n            -------\n            edges : OutEdgeView\n                A view of edge attributes, usually it iterates over (u, v)\n                or (u, v, d) tuples of edges, but can also be used for\n                attribute lookup as `edges[u, v]['foo']`.\n\n            See Also\n            --------\n            in_edges, out_edges\n\n            Notes\n            -----\n            Nodes in nbunch that are not in the graph will be (quietly) ignored.\n            For directed graphs this returns the out-edges.\n\n            Examples\n            --------\n                > G = nx.DiGraph()   # or MultiDiGraph, etc\n                > nx.add_path(G, [0, 1, 2])\n                > G.add_edge(2, 3, weight=5)\n                > [e for e in G.edges()]\n            [(0, 1), (1, 2), (2, 3)]\n                > G.edges().data()  # default data is {} (empty dict)\n            OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])\n                > G.edges().data('weight', default=1)\n            OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])\n                > G.edges()([0, 2])  # only edges incident to these nodes\n            OutEdgeDataView([(0, 1), (2, 3)])\n                > G.edges()(0)  # only edges incident to a single node (use G.adj[0]?)\n            OutEdgeDataView([(0, 1)])\n\n        */\n        // using coro_t = boost::coroutines2::coroutine<edge_t>;\n        // using pull_t = typename coro_t::pull_type;\n\n        // /// @TODO: sync with networkx\n        // auto edges() const -> pull_t {\n        //     auto func = [&](typename coro_t::push_type& yield) {\n        //         if constexpr (std::is_same_v<nodeview_t, decltype(py::range<uint32_t>(\n        //                                                      uint32_t{}))>) {  // this->_succ???\n        //             for (auto&& [n, nbrs] : py::enumerate(this->_adj)) {\n        //                 for (auto&& nbr : nbrs) {\n        //                     yield(edge_t{Node(n), Node(nbr)});\n        //                 }\n        //             }\n        //         } else {\n        //             for (auto&& [n, nbrs] : this->_adj.items()) {\n        //                 for (auto&& nbr : nbrs) {\n        //                     yield(edge_t{n, nbr});\n        //                 }\n        //             }\n        //         }\n        //     };\n\n        //     return pull_t(func);\n        // }\n\n#if __cplusplus > 201703L\n        auto edges() const -> cppcoro::generator<edge_t> {\n            if constexpr (std::is_same_v<nodeview_t, decltype(py::range<uint32_t>(\n                                                         uint32_t{}))>) {  // this->_succ???\n                for (auto&& [n, nbrs] : py::enumerate(this->_adj)) {\n                    for (auto&& nbr : nbrs) {\n                        co_yield edge_t{Node(n), Node(nbr)};\n                    }\n                }\n            } else {\n                for (auto&& [n, nbrs] : this->_adj.items()) {\n                    for (auto&& nbr : nbrs) {\n                        co_yield edge_t{n, nbr};\n                    }\n                }\n            }\n        }\n#endif\n\n        // cppcoro::generator<edge_t> edges() const\n        // {\n        //     for (auto&& [n, nbrs] : this->_nodes_nbrs())\n        //     {\n        //         for (auto&& nbr : nbrs)\n        //         {\n        //             co_yield edge_t{Node(n), Node(nbr)};\n        //         }\n        //     }\n        // }\n\n        // auto edges() {\n        //     return OutEdgeView(*this);\n        // }\n\n        // auto in_edges() {\n        //     return InEdgeView(*this);\n        // }\n\n        auto degree(const Node& n) const { return this->_succ[n].size(); }\n\n        /** Remove all nodes and edges from the graph.\n\n            This also removes the name, and all graph, node, and edge attributes.\n\n            Examples\n            --------\n                > G = xnetwork::path_graph(4);  // or DiGraph, MultiGraph, MultiDiGraph, etc\n                > G.clear();\n                > list(G.nodes);\n            [];\n                > list(G.edges());\n            [];\n\n        */\n        auto clear() {\n            this->_succ.clear();\n            // this->_pred.clear()\n            // this->_node.clear();\n            this->graph.clear();\n        }\n\n        /** Return true if (graph is a multigraph, false otherwise. */\n        auto is_multigraph() { return false; }\n\n        /** Return true if (graph is directed, false otherwise. */\n        auto is_directed() { return true; }\n    };\n\n    using SimpleDiGraphS = DiGraphS<decltype(py::range<uint32_t>(uint32_t{})),\n                                    py::dict<uint32_t, int>, std::vector<py::dict<uint32_t, int>>>;\n\n    // template <typename nodeview_t,\n    //           typename adjlist_t> DiGraphS(int )\n    // -> DiGraphS<decltype(py::range<int>(1)), py::set<int>>;\n\n}  // namespace xnetwork\n", "meta": {"hexsha": "d289689fdebe6f5aacfe36fbddf9c2b6caf359f5", "size": 21968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/xnetwork/classes/digraphs.hpp", "max_stars_repo_name": "luk036/xnetwork-cpp", "max_stars_repo_head_hexsha": "3a4d490422d271f9844e44304c2533555d494b9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/xnetwork/classes/digraphs.hpp", "max_issues_repo_name": "luk036/xnetwork-cpp", "max_issues_repo_head_hexsha": "3a4d490422d271f9844e44304c2533555d494b9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/xnetwork/classes/digraphs.hpp", "max_forks_repo_name": "luk036/xnetwork-cpp", "max_forks_repo_head_hexsha": "3a4d490422d271f9844e44304c2533555d494b9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8127208481, "max_line_length": 99, "alphanum_fraction": 0.5497997087, "num_tokens": 5048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.02887090663294579, "lm_q1q2_score": 0.012198091863707286}}
{"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 essential matrix template implementations\n */\n\n#include \"essential_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/// Compute the twisted pair rotation from the rotation and translation\nrotation_d\nessential_matrix\n::twisted_rotation() const\n{\n  // The quaternion representation of a 180 degree rotation about\n  // unit vector [X,Y,Z] is simply [X, Y, Z, 0]\n  vector_3d t = this->translation();\n  return rotation_d(vector_4d(t.x(), t.y(), t.z(), 0.0)) * this->rotation();\n}\n\n\n\n\n/// Construct from a provided matrix\ntemplate <typename T>\nessential_matrix_<T>\n::essential_matrix_( Eigen::Matrix<T,3,3> const &mat )\n{\n  const matrix_t W = (matrix_t() << T(0), T(-1), T(0),\n                                    T(1), T( 0), T(0),\n                                    T(0), T( 0), T(1)).finished();\n  Eigen::JacobiSVD<matrix_t> svd(mat, Eigen::ComputeFullU |\n                                      Eigen::ComputeFullV);\n  const matrix_t& U = svd.matrixU();\n  const matrix_t& V = svd.matrixV();\n  trans_ = U.col(2);\n  matrix_t R = U*W*V.transpose();\n  if( R.determinant() < T(0) )\n  {\n    R *= T(-1);\n  }\n  rot_ = rotation_<T>(R);\n}\n\n/// Construct from a rotation and translation\ntemplate <typename T>\nessential_matrix_<T>\n::essential_matrix_( rotation_<T> const &rot,\n                     vector_t const &trans )\n  : rot_( rot ),\n    trans_( trans.normalized() )\n{\n}\n\n/// Conversion Copy constructor -- float specialization\ntemplate <>\ntemplate <>\nessential_matrix_<float>\n::essential_matrix_( essential_matrix_<float> const &other )\n  : rot_( other.rot_ ),\n    trans_( other.trans_ )\n{\n}\n\n/// Conversion Copy constructor -- double specialization\ntemplate <>\ntemplate <>\nessential_matrix_<double>\n::essential_matrix_( essential_matrix_<double> const &other )\n  : rot_( other.rot_ ),\n    trans_( other.trans_ )\n{\n}\n\n/// Construct from a generic essential_matrix\ntemplate <typename T>\nessential_matrix_<T>\n::essential_matrix_( essential_matrix const &base )\n  : rot_( static_cast<rotation_<T> >(base.rotation()) ),\n    trans_( base.translation().template cast<T>() )\n{\n}\n\n/// Construct from a generic essential_matrix -- double specialization\ntemplate <>\nessential_matrix_<double>\n::essential_matrix_( essential_matrix const &base )\n  : rot_( base.rotation() ),\n    trans_( base.translation() )\n{\n}\n\n/// Create a clone of outself as a shared pointer\ntemplate <typename T>\nessential_matrix_sptr\nessential_matrix_<T>\n::clone() const\n{\n  return essential_matrix_sptr( new essential_matrix_<T>( *this ) );\n}\n\n/// Get a double-typed copy of the underlying matrix\ntemplate <typename T>\nEigen::Matrix<double,3,3>\nessential_matrix_<T>\n::matrix() const\n{\n  return this->compute_matrix().template cast<double>();\n}\n\n/// Specialization for matrices with native double type\ntemplate <>\nEigen::Matrix<double,3,3>\nessential_matrix_<double>\n::matrix() const\n{\n  return this->compute_matrix();\n}\n\n/// Return the one of two possible 3D rotations that can parameterize E\ntemplate <typename T>\nrotation_d\nessential_matrix_<T>\n::rotation() const\n{\n  return static_cast<rotation_d>(this->rot_);\n}\n\n/// Return the second possible rotation that can parameterize E\ntemplate <typename T>\nrotation_d\nessential_matrix_<T>\n::twisted_rotation() const\n{\n  return static_cast<rotation_d>(this->compute_twisted_rotation());\n}\n\n/// Return a unit translation vector (up to a sign) that parameterizes E\ntemplate <typename T>\nvector_3d\nessential_matrix_<T>\n::translation() const\n{\n  return this->trans_.template cast<double>();\n}\n\n/// Get the underlying matrix\ntemplate <typename T>\ntypename essential_matrix_<T>::matrix_t\nessential_matrix_<T>\n::compute_matrix() const\n{\n  matrix_t t_cross;\n  t_cross << T(0), -trans_[2], trans_[1],\n             trans_[2], T(0), -trans_[0],\n            -trans_[1], trans_[0], T(0);\n  return t_cross * matrix_t(rot_.matrix());\n}\n\n/// Compute the twisted pair rotation from the rotation and translation\ntemplate <typename T>\nrotation_<T>\nessential_matrix_<T>\n::compute_twisted_rotation() const\n{\n  typedef Eigen::Matrix<T,4,1> vector_4;\n  // The quaternion representation of a 180 degree rotation about\n  // unit vector [X,Y,Z] is simply [X, Y, Z, 0]\n  const vector_t& t = trans_;\n  return rotation_<T>(vector_4(t.x(), t.y(), t.z(), T(0))) * rot_;\n}\n\n/// Get a const reference to the underlying rotation\ntemplate <typename T>\nrotation_<T> const&\nessential_matrix_<T>\n::get_rotation() const\n{\n  return rot_;\n}\n\n/// Get a const reference to the underlying translation\ntemplate <typename T>\ntypename essential_matrix_<T>::vector_t const&\nessential_matrix_<T>\n::get_translation() const\n{\n  return trans_;\n}\n\n// ===========================================================================\n// Other Functions\n// ---------------------------------------------------------------------------\n\n/// essential_matrix_<T> output stream operator\ntemplate <typename T>\nstd::ostream&\noperator<<( std::ostream &s, essential_matrix_<T> const &e )\n{\n  s << e.compute_matrix();\n  return s;\n}\n\n/// Output stream operator for \\p essential_matrix instances\nstd::ostream&\noperator<<( std::ostream &s, essential_matrix const &e )\n{\n  s << e.matrix();\n  return s;\n}\n\n// ===========================================================================\n// Template class instantiation\n// ---------------------------------------------------------------------------\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_ESSENTIAL_MATRIX(T)                                 \\\n  template class essential_matrix_<T>;                                  \\\n  template VITAL_EXPORT std::ostream& operator<<( std::ostream &,       \\\n                        essential_matrix_<T> const & )\n\nINSTANTIATE_ESSENTIAL_MATRIX(float);\nINSTANTIATE_ESSENTIAL_MATRIX(double);\n#undef INSTANTIATE_ESSENTIAL_MATRIX\n/// \\endcond\n\n\n} } // end vital namespace\n", "meta": {"hexsha": "b8d092013a48a120d22ccd1f546f638db3f2b4f2", "size": 7449, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vital/types/essential_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/essential_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/essential_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.0037593985, "max_line_length": 81, "alphanum_fraction": 0.6714995301, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.02517884307215325, "lm_q1q2_score": 0.012196130129286557}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Class:       EffGlobalMinimizer\n//- Description: Implementation code for the EffGlobalMinimizer class\n//- Owner:       Barron J Bichon, Vanderbilt University\n\n#include \"EffGlobalMinimizer.hpp\"\n#include \"dakota_system_defs.hpp\"\n#include \"dakota_data_io.hpp\"\n#include \"NonDLHSSampling.hpp\"\n#include \"RecastModel.hpp\"\n#include \"DataFitSurrModel.hpp\"\n#include \"DakotaApproximation.hpp\"\n#include \"ProblemDescDB.hpp\"\n#include \"DakotaGraphics.hpp\"\n#ifdef HAVE_NCSU\n#include \"NCSUOptimizer.hpp\"\n#endif\n#include \"DakotaModel.hpp\"\n#include \"DakotaResponse.hpp\"\n#include \"pecos_stat_util.hpp\"\n#include <boost/lexical_cast.hpp>\n\n//#define DEBUG\n//#define DEBUG_PLOTS\n\nnamespace Dakota {\n\nEffGlobalMinimizer* EffGlobalMinimizer::effGlobalInstance(NULL);\n\n\n// This constructor accepts a Model\nEffGlobalMinimizer::\nEffGlobalMinimizer(ProblemDescDB& problem_db, Model& model): \n  SurrBasedMinimizer(problem_db, model, std::shared_ptr<TraitsBase>(new EffGlobalTraits())),\n  setUpType(\"model\"), dataOrder(1)\n{\n  bestVariablesArray.push_back(iteratedModel.current_variables().copy());\n\n  // initialize augmented Lagrange multipliers\n  size_t num_multipliers = numNonlinearEqConstraints;\n  for (size_t i=0; i<numNonlinearIneqConstraints; i++) {\n    if (origNonlinIneqLowerBnds[i] > -bigRealBoundSize) // g has a lower bound\n      ++num_multipliers;\n    if (origNonlinIneqUpperBnds[i] <  bigRealBoundSize) // g has an upper bound\n      ++num_multipliers;\n  }\n  augLagrangeMult.resize(num_multipliers);\n  augLagrangeMult = 0.;\n\n  truthFnStar.resize(numFunctions);\n\n  // Always build a global Gaussian process model.  No correction is needed.\n  String approx_type = \"global_kriging\";\n  if (probDescDB.get_short(\"method.nond.emulator\") == GP_EMULATOR)\n    approx_type = \"global_gaussian\";\n\n  String sample_reuse = \"none\";\n  UShortArray approx_order; // empty\n  short corr_order = -1, corr_type = NO_CORRECTION;\n  if (probDescDB.get_bool(\"method.derivative_usage\")) {\n    if (approx_type == \"global_gaussian\") {\n      Cerr << \"\\nError: efficient_global does not support gaussian_process \"\n\t   << \"when derivatives present; use kriging instead.\" << std::endl;\n      abort_handler(METHOD_ERROR);\n    }\n    if (iteratedModel.gradient_type() != \"none\") dataOrder |= 2;\n    if (iteratedModel.hessian_type()  != \"none\") dataOrder |= 4;\n  }\n  int db_samples = probDescDB.get_int(\"method.samples\");  \n  int samples = (db_samples > 0) ? db_samples : \n    (numContinuousVars+1)*(numContinuousVars+2)/2;\n  int lhs_seed = probDescDB.get_int(\"method.random_seed\");\n  unsigned short sample_type = SUBMETHOD_DEFAULT;\n  String rng; // empty string: use default\n  //int symbols = samples; // symbols needed for DDACE\n  bool vary_pattern = false;// for consistency across any outer loop invocations\n  // get point samples file\n  const String& import_pts_file\n    = probDescDB.get_string(\"method.import_build_points_file\");\n  if (!import_pts_file.empty())\n    { samples = 0; sample_reuse = \"all\"; }\n\n  Iterator dace_iterator;\n  // The following uses on the fly derived ctor:\n  dace_iterator.assign_rep(new NonDLHSSampling(iteratedModel, sample_type,\n    samples, lhs_seed, rng, vary_pattern, ACTIVE_UNIFORM), false);\n  // only use derivatives if the user requested and they are available\n  ActiveSet dace_set = dace_iterator.active_set(); // copy\n  dace_set.request_values(dataOrder);\n  dace_iterator.active_set(dace_set);\n\n  // Construct f-hat using a GP approximation for each response function over\n  // the active/design vars (same view as iteratedModel: not the typical All\n  // view for DACE).\n  //const Variables& curr_vars = iteratedModel.current_variables();\n  ActiveSet gp_set = iteratedModel.current_response().active_set(); // copy\n  gp_set.request_values(1); // no surr deriv evals, but GP may be grad-enhanced\n  fHatModel.assign_rep(new DataFitSurrModel(dace_iterator, iteratedModel,\n    gp_set, approx_type, approx_order, corr_type, corr_order, dataOrder,\n    outputLevel, sample_reuse, import_pts_file,\n    probDescDB.get_ushort(\"method.import_build_format\"),\n    probDescDB.get_bool(\"method.import_build_active_only\"),\n    probDescDB.get_string(\"method.export_approx_points_file\"),\n    probDescDB.get_ushort(\"method.export_approx_format\")), false);\n\n  // Following this ctor, IteratorScheduler::init_iterator() initializes the\n  // parallel configuration for EffGlobalMinimizer + iteratedModel using\n  // EffGlobalMinimizer's maxEvalConcurrency.  During fHatModel construction\n  // above, DataFitSurrModel::derived_init_communicators() initializes the\n  // parallel config for dace_iterator + iteratedModel using dace_iterator's\n  // maxEvalConcurrency.  The only iteratedModel concurrency currently exercised\n  // is that used by dace_iterator within the initial GP construction, but the\n  // EffGlobalMinimizer maxEvalConcurrency must still be set so as to avoid\n  // parallel config errors resulting from avail_procs > max_concurrency within\n  // IteratorScheduler::init_iterator().  A max of the local derivative\n  // concurrency and the DACE concurrency is used for this purpose.\n  maxEvalConcurrency = std::max(maxEvalConcurrency,\n\t\t\t\tdace_iterator.maximum_evaluation_concurrency());\n\n  // Configure a RecastModel with one objective and no constraints using the\n  // alternate minimalist constructor: the recast fn pointers are reset for\n  // each level within the run fn.\n  SizetArray recast_vars_comps_total; // default: empty; no change in size\n  BitArray all_relax_di, all_relax_dr; // default: empty; no discrete relaxation\n  short recast_resp_order = 1; // nongradient-based optimizers\n  eifModel.assign_rep(\n    new RecastModel(fHatModel, recast_vars_comps_total, all_relax_di,\n\t\t    all_relax_dr, 1, 0, 0, recast_resp_order), false);\n\n  // must use alternate NoDB ctor chain\n  int max_iterations = 10000, max_fn_evals = 50000;\n  double min_box_size = 1.e-15, vol_box_size = 1.e-15;\n#ifdef HAVE_NCSU\n  approxSubProbMinimizer.assign_rep(new NCSUOptimizer(eifModel, max_iterations, \n    max_fn_evals, min_box_size, vol_box_size), false);\n#else\n  Cerr << \"NCSU DIRECT is not available to optimize the GP subproblems. \" \n       << \"Aborting process.\" << std::endl;\n  abort_handler(METHOD_ERROR);\n#endif //HAVE_NCSU\n}\n\n\n/* This is an alternate constructor for instantiations on the fly\n    using a Model but no ProblemDescDB.\nEffGlobalMinimizer::\nEffGlobalMinimizer(Model& model, int max_iter, int max_eval) :\n  SurrBasedMinimizer(EFFICIENT_GLOBAL, model), setUpType(\"model\")\n{ maxIterations = max_iter; maxFunctionEvals = max_eval; }\n*/\n\n\nEffGlobalMinimizer::~EffGlobalMinimizer() \n{ }\n\n\n/*\n// SurrBasedMinimizer implementation of derived_{init,set,free} is sufficient\n\nvoid EffGlobalMinimizer::derived_init_communicators(ParLevLIter pl_iter)\n{\n  // iteratedModel is evaluated to add truth data (single evaluate())\n  iteratedModel.init_communicators(pl_iter, maxEvalConcurrency);\n\n  // approxSubProbMinimizer.init_communicators() recursion is currently\n  // sufficient for fHatModel.  An additional fHatModel.init_communicators()\n  // call would be motivated by special parallel usage of fHatModel below that\n  // is not otherwise covered by the recursion.\n  //fHatMaxConcurrency = maxEvalConcurrency; // local derivative concurrency\n  //fHatModel.init_communicators(pl_iter, fHatMaxConcurrency);\n\n  // approxSubProbMinimizer uses NoDBBaseConstructor, so no need to\n  // manage DB list nodes at this level\n  approxSubProbMinimizer.init_communicators(pl_iter);\n}\n\n\nvoid EffGlobalMinimizer::derived_free_communicators(ParLevLIter pl_iter)\n{\n  // deallocate communicators for DIRECT on eifModel\n  approxSubProbMinimizer.free_communicators(pl_iter);\n\n  // approxSubProbMinimizer.free_communicators() recursion is currently\n  // sufficient for fHatModel.  An additional fHatModel.free_communicators()\n  // call would be motivated by special parallel usage of fHatModel below that\n  // is not otherwise covered by the recursion.\n  //fHatModel.free_communicators(pl_iter, fHatMaxConcurrency);\n\n  // iteratedModel is evaluated to add truth data (single evaluate())\n  iteratedModel.free_communicators(pl_iter, maxEvalConcurrency);\n}\n*/\n\n\nvoid EffGlobalMinimizer::core_run()\n{\n  if (setUpType==\"model\")\n    minimize_surrogates_on_model();\n  else if (setUpType==\"user_functions\") {\n    //minimize_surrogates_on_user_functions();\n    Cerr << \"Error: bad setUpType in EffGlobalMinimizer::core_run().\"\n\t << std::endl;\n    abort_handler(METHOD_ERROR);\n  }\n  else {\n    Cerr << \"Error: bad setUpType in EffGlobalMinimizer::core_run().\"\n\t << std::endl;\n    abort_handler(METHOD_ERROR);\n  }\n}\n\n\nvoid EffGlobalMinimizer::minimize_surrogates_on_model()\n{\n  //------------------------------------------------------------------\n  //     Solve the problem.\n  //------------------------------------------------------------------\n\n  // set the object instance pointers for use within the static member fns\n  EffGlobalMinimizer* prev_instance = effGlobalInstance;\n  effGlobalInstance = this;\n\n  // now that variables/labels/bounds/targets have flowed down at run-time from\n  // any higher level recursions, propagate them up the instantiate-on-the-fly\n  // Model recursion so that they are correct when they propagate back down.\n  eifModel.update_from_subordinate_model(); // depth = max\n\n  // Build initial GP once for all response functions\n  fHatModel.build_approximation();\n\n  // Iterate until EGO converges\n  unsigned short eif_convergence_cntr = 0, dist_convergence_cntr = 0,\n    eif_convergence_limit = 2, dist_convergence_limit = 1;\n  globalIterCount = 0;\n  bool approx_converged = false;\n  convergenceTol = 1.e-12; Real dist_tol = 1.e-8;\n  // Decided for now (10-25-2013) to have EGO take the maxIterations \n  // as the default from minimizer, so it will be initialized as 100\n  //  maxIterations  = 25*numContinuousVars;\n  RealVector prev_cv_star;\n  while (!approx_converged) {\n    ++globalIterCount;\n\n    // initialize EIF recast model\n    Sizet2DArray vars_map, primary_resp_map(1), secondary_resp_map;\n    BoolDequeArray nonlinear_resp_map(1, BoolDeque(numFunctions, true));\n    primary_resp_map[0].resize(numFunctions);\n    for (size_t i=0; i<numFunctions; i++)\n      primary_resp_map[0][i] = i;\n    RecastModel* eif_model_rep = (RecastModel*)eifModel.model_rep();\n    eif_model_rep->init_maps(vars_map, false, NULL, NULL,\n      primary_resp_map, secondary_resp_map, nonlinear_resp_map,\n      EIF_objective_eval, NULL);\n\n    // determine fnStar from among sample data\n    get_best_sample();\n\n    // Execute GLOBAL search and retrieve results\n    Cout << \"\\n>>>>> Initiating global optimization\\n\";\n    ParLevLIter pl_iter = methodPCIter->mi_parallel_level_iterator(miPLIndex);\n    approxSubProbMinimizer.run(pl_iter);\n    const Variables&  vars_star = approxSubProbMinimizer.variables_results();\n    const RealVector& c_vars    = vars_star.continuous_variables();\n    const Response&   resp_star = approxSubProbMinimizer.response_results();\n    const Real&       eif_star  = resp_star.function_value(0);\n\n    // Get expected value for output\n    fHatModel.continuous_variables(c_vars);\n    fHatModel.evaluate();\n    const RealVector& mean = fHatModel.current_response().function_values();\n    Real aug_lag = augmented_lagrangian_merit(mean,\n      iteratedModel.primary_response_fn_sense(),\n      iteratedModel.primary_response_fn_weights(), origNonlinIneqLowerBnds,\n      origNonlinIneqUpperBnds, origNonlinEqTargets);\n\n    Cout << \"\\nResults of EGO iteration:\\nFinal point =\\n\";\n    write_data(Cout, c_vars);\n    Cout << \"Expected Improvement    =\\n                     \"\n\t << std::setw(write_precision+7) << -eif_star\n\t << \"\\n                     \" << std::setw(write_precision+7)\n\t << aug_lag << \" [merit]\\n\";\n\n#ifdef DEBUG\n    RealVector variance = fHatModel.approximation_variances(vars_star);\n    RealVector ev = expected_violation(mean,variance);\n    RealVector stdv(numFunctions);\n    for (size_t i=0; i<numFunctions; i++)\n      stdv[i] = std::sqrt(variance[i]);\n    Cout << \"\\nexpected values    =\\n\" << mean\n\t << \"\\nstandard deviation =\\n\" << stdv\n\t << \"\\nexpected violation =\\n\" << ev << std::endl;\n#endif //DEBUG\n\n    // Check for convergence based on max EIF\n    if ( -eif_star < convergenceTol )\n      ++eif_convergence_cntr;\n\n    // Check for convergence based in distance between successive points.\n    // If the dist between successive points is very small, then there is\n    // little value in updating the GP since the new training point will\n    // essentially be the previous optimal point.\n\n    Real dist_cstar = (prev_cv_star.empty()) ? DBL_MAX :\n      rel_change_L2(c_vars, prev_cv_star);\n    // update prev_cv_star\n    copy_data(c_vars, prev_cv_star);\n    if (dist_cstar < dist_tol)\n      ++dist_convergence_cntr;\n\n    // If DIRECT failed to find a point with EIF>0, it returns the\n    //   center point as the optimal solution. EGO may have converged,\n    //   but DIRECT may have just failed to find a point with a good\n    //   EIF value. Adding this midpoint can alter the GPs enough to\n    //   to allow DIRECT to find something useful, so we force \n    //   max(EIF)<tol twice to make sure. Note that we cannot make\n    //   this check more than 2 because it would cause EGO to add\n    //   the center point more than once, which will damage the GPs.\n    //   Unfortunately, when it happens the second time, it may still\n    //   be that DIRECT failed and not that EGO converged.\n\n#ifdef DEBUG\n    Cout << \"EGO Iteration \" << globalIterCount << \"\\neif_star \" << eif_star\n\t << \"\\ndist_cstar \"  << dist_cstar      << \"\\ndist_convergence_cntr \"\n\t << dist_convergence_cntr << '\\n';\n#endif //DEBUG\n\n    if ( dist_convergence_cntr >= dist_convergence_limit ||\n\t eif_convergence_cntr  >= eif_convergence_limit || \n\t globalIterCount       >= maxIterations )\n      approx_converged = true;\n    else {\n      // Evaluate response_star_truth\n      fHatModel.component_parallel_mode(TRUTH_MODEL);\n      iteratedModel.continuous_variables(c_vars);\n      ActiveSet set = iteratedModel.current_response().active_set();\n      set.request_values(dataOrder);\n      iteratedModel.evaluate(set);\n      IntResponsePair resp_star_truth(iteratedModel.evaluation_id(),\n\t\t\t\t      iteratedModel.current_response());\n    \n      if (numNonlinearConstraints) {\n\t// Update the merit function parameters\n\t// Logic follows Conn, Gould, and Toint, section 14.4:\n\tconst RealVector& fns_star_truth\n\t  = resp_star_truth.second.function_values();\n\tReal norm_cv_star = std::sqrt(constraint_violation(fns_star_truth, 0.));\n\tif (norm_cv_star < etaSequence)\n\t  update_augmented_lagrange_multipliers(fns_star_truth);\n\telse\n\t  update_penalty();\n      }\n\n      // Update the GP approximation\n      fHatModel.append_approximation(vars_star, resp_star_truth, true);\n    }\n\n  } // end approx convergence while loop\n\n  // Set best variables and response for use by strategy level.\n  // c_vars, fmin contain the optimal design \n  get_best_sample(); // pull optimal result from sample data\n  bestVariablesArray.front().continuous_variables(varStar);\n  bestResponseArray.front().function_values(truthFnStar);\n\n  // restore in case of recursion\n  effGlobalInstance = prev_instance;\n\n#ifdef DEBUG_PLOTS\n  // DEBUG - output set of samples used to build the GP\n  // If problem is 2d, output a grid of points on the GP \n  //   and truth (if requested)\n  for (size_t i=0; i<numFunctions; i++) {\n    std::string samsfile(\"ego_sams\");\n    std::string tag = \"_\" + boost::lexical_cast<std::string>(i+1) + \".out\";\n    samsfile += tag;\n    std::ofstream samsOut(samsfile.c_str(),std::ios::out);\n    samsOut << std::scientific;\n    const Pecos::SurrogateData& gp_data = fHatModel.approximation_data(i);\n    size_t num_data_pts = gp_data.size(), num_vars = fHatModel.cv();\n    for (size_t j=0; j<num_data_pts; ++j) {\n      samsOut << '\\n';\n      const RealVector& sams = gp_data.continuous_variables(j);\n      for (size_t k=0; k<num_vars; k++)\n\tsamsOut << std::setw(13) << sams[k] << ' ';\n      samsOut << std::setw(13) << gp_data.response_function(j);\n    }\n    samsOut << std::endl;\n\n    // Plotting the GP over a grid is intended for visualization and\n    //   is therefore only available for 2D problems\n    if (num_vars==2) {\n      std::string gpfile(\"ego_gp\");\n      std::string varfile(\"ego_var\");\n      gpfile  += tag;\n      varfile += tag;\n      std::ofstream  gpOut(gpfile.c_str(),  std::ios::out);\n      std::ofstream varOut(varfile.c_str(), std::ios::out);\n      std::ofstream eifOut(\"ego_eif.out\",   std::ios::out);\n      gpOut  << std::scientific;\n      varOut << std::scientific;\n      eifOut << std::scientific;\n      RealVector test_pt(2);\n      const RealVector& lbnd = fHatModel.continuous_lower_bounds();\n      const RealVector& ubnd = fHatModel.continuous_upper_bounds();\n      Real interval0 = (ubnd[0]-lbnd[0])/100.,\n\t   interval1 = (ubnd[1]-lbnd[1])/100.;\n      for (size_t j=0; j<101; j++){\n\ttest_pt[0] = lbnd[0] + float(j)*interval0;\n\tfor (size_t k=0; k<101; k++){\n\t  test_pt[1] = lbnd[1] + float(k)*interval1;\n      \n\t  fHatModel.continuous_variables(test_pt);\n\t  fHatModel.evaluate();\n\t  const Response& gp_resp = fHatModel.current_response();\n\t  const RealVector& gp_fn = gp_resp.function_values();\n\t  \n\t  gpOut << '\\n' << std::setw(13) << test_pt[0] << ' ' << std::setw(13)\n\t\t<< test_pt[1] << ' ' << std::setw(13) << gp_fn[i];\n\n\t  RealVector variances\n\t    = fHatModel.approximation_variances(fHatModel.current_variables());\n\n\t  varOut << '\\n' << std::setw(13) << test_pt[0] << ' ' << std::setw(13)\n\t\t << test_pt[1] << ' ' << std::setw(13) << variances[i];\n\n\t  if (i==numFunctions-1) {\n\t    Real m = augmented_lagrangian_merit(gp_fn,\n\t      iteratedModel.primary_response_fn_sense(),\n\t      iteratedModel.primary_response_fn_weights(),\n\t      origNonlinIneqLowerBnds, origNonlinIneqUpperBnds,\n\t      origNonlinEqTargets);\n\t    RealVector merit(1);\n\t    merit[0] = m;\n\n\t    Real ei = expected_improvement(merit, test_pt);\n\n\t    eifOut << '\\n' << std::setw(13) << test_pt[0] << ' ' \n\t\t   << std::setw(13) << test_pt[1] << ' ' << std::setw(13) << ei;\n\t  }\n\t}\n\tgpOut  << std::endl;\n\tvarOut << std::endl;\n\tif (i==numFunctions-1)\n\t  eifOut << std::endl;\n      }\n    }\n  }\n#endif //DEBUG_PLOTS\n}\n\n\nvoid EffGlobalMinimizer::\nEIF_objective_eval(const Variables& sub_model_vars,\n\t\t   const Variables& recast_vars,\n\t\t   const Response& sub_model_response,\n\t\t   Response& recast_response)\n{\n  // Means are passed in, but must retrieve variance from the GP\n  const RealVector& means = sub_model_response.function_values();\n  const RealVector& variances\n    = effGlobalInstance->fHatModel.approximation_variances(recast_vars);\n\n  const ShortArray& recast_asv = recast_response.active_set_request_vector();\n  if (recast_asv[0] & 1) { // return -EI since we are maximizing\n    Real neg_ei = -effGlobalInstance->expected_improvement(means, variances);\n    recast_response.function_value(neg_ei, 0);\n  }\n}\n\n\nReal EffGlobalMinimizer::\nexpected_improvement(const RealVector& means, const RealVector& variances)\n{\n  Real mean = objective(means, iteratedModel.primary_response_fn_sense(),\n\t\t\titeratedModel.primary_response_fn_weights()), stdv;\n\n  if ( numNonlinearConstraints ) {\n    // mean_M = mean_f + lambda*EV + r_p*EV*EV\n    // stdv_M = stdv_f\n    const RealVector& ev = expected_violation(means, variances);\n    for (size_t i=0; i<numNonlinearConstraints; ++i)\n      mean += augLagrangeMult[i]*ev[i] + penaltyParameter*ev[i]*ev[i];\n    stdv = std::sqrt(variances[0]); // ***\n  }\n  else { // extend for NLS/MOO ***\n    // mean_M = M(mu_f)\n    // stdv_M = sqrt(var_f)\n    stdv = std::sqrt(variances[0]); // *** sqrt(sum(variances(1:nUsrPrimaryFns))\n  }\n\n  // Calculate the expected improvement\n  Real cdf, pdf;\n  Real snv = (meritFnStar - mean); // standard normal variate\n  if(std::fabs(snv)>=std::fabs(stdv)*50.0) {\n    //this will trap the denominator=0.0 case even if numerator=0.0\n    pdf=0.0;\n    cdf=(snv>0.0)?1.0:0.0;\n  }\n  else{\n    snv/=stdv; \n    cdf = Pecos::NormalRandomVariable::std_cdf(snv);\n    pdf = Pecos::NormalRandomVariable::std_pdf(snv);\n  }\n\n  Real ei  = (meritFnStar - mean)*cdf + stdv*pdf;\n\n  return ei;\n}\n\n\nRealVector EffGlobalMinimizer::\nexpected_violation(const RealVector& means, const RealVector& variances)\n{\n  RealVector ev(numNonlinearConstraints);\n\n  size_t i, cntr=0;\n  // inequality constraints\n  for (i=0; i<numNonlinearIneqConstraints; i++) {\n    const Real& mean = means[numUserPrimaryFns+i];\n    const Real& stdv = std::sqrt(variances[numUserPrimaryFns+i]);\n    const Real& lbnd = origNonlinIneqLowerBnds[i];\n    const Real& ubnd = origNonlinIneqUpperBnds[i];\n    if (lbnd > -bigRealBoundSize) {\n      Real cdf, pdf;\n      Real snv = (lbnd-mean);\n      if(std::fabs(snv)>=std::fabs(stdv)*50.0){\n\tpdf=0.0;\n\tcdf=(snv>0.0)?1.0:0.0;\n      }\n      else{\n\tsnv/=stdv; //now snv is the standard normal variate\n\tcdf = Pecos::NormalRandomVariable::std_cdf(snv);\n\tpdf = Pecos::NormalRandomVariable::std_pdf(snv);\n      }\n      ev[cntr++] = (lbnd-mean)*cdf + stdv*pdf;\n    }\n    if (ubnd < bigRealBoundSize) {\n      Real cdf, pdf;\n      Real snv = (ubnd-mean);\n      if(std::fabs(snv)>=std::fabs(stdv)*50.0){\n\tpdf=0.0;\n\tcdf=(snv>0.0)?1.0:0.0;\n      }\n      else{\n\tsnv/=stdv;\n\tcdf = Pecos::NormalRandomVariable::std_cdf(snv);\n\tpdf = Pecos::NormalRandomVariable::std_pdf(snv);\n      }\n      ev[cntr++] = (mean-ubnd)*(1.-cdf) + stdv*pdf;\n    }\n  }\n  // equality constraints\n  for (i=0; i<numNonlinearEqConstraints; i++) {\n    const Real& mean = means[numUserPrimaryFns+numNonlinearIneqConstraints+i];\n    const Real& stdv\n      = std::sqrt(variances[numUserPrimaryFns+numNonlinearIneqConstraints+i]);\n    const Real& zbar = origNonlinEqTargets[i];\n    Real cdf, pdf;\n    Real snv = (zbar-mean);\n    if(std::fabs(snv)*50.0>=std::fabs(stdv)) {\n      pdf=0.0;\n      cdf=(snv>=0.0)?1.0:0.0;\n    }\n    else{\n      snv/=stdv;\n      cdf = Pecos::NormalRandomVariable::std_cdf(snv);\n      pdf = Pecos::NormalRandomVariable::std_pdf(snv);\n    }\n    ev[cntr++] = (zbar-mean)*(2.*cdf-1.) + 2.*stdv*pdf;\n  }\n\n  return ev;\n}\n\n\nvoid EffGlobalMinimizer::get_best_sample()\n{\n  // Pull the samples and responses from data used to build latest GP\n  // to determine fnStar for use in the expected improvement function\n\n  const Pecos::SurrogateData& gp_data_0 = fHatModel.approximation_data(0);\n\n  size_t i, sam_star_idx = 0, num_data_pts = gp_data_0.points();\n  Real fn, fn_star = DBL_MAX;\n  for (i=0; i<num_data_pts; ++i) {\n    const RealVector& sams = gp_data_0.continuous_variables(i);\n\n    fHatModel.continuous_variables(sams);\n    fHatModel.evaluate();\n    const RealVector& f_hat = fHatModel.current_response().function_values();\n    fn = augmented_lagrangian_merit(f_hat,\n      iteratedModel.primary_response_fn_sense(),\n      iteratedModel.primary_response_fn_weights(), origNonlinIneqLowerBnds,\n      origNonlinIneqUpperBnds, origNonlinEqTargets);\n\n    if (fn < fn_star) {\n      copy_data(sams, varStar);\n      sam_star_idx   = i;\n      fn_star        = fn;\n      meritFnStar    = fn;\n      truthFnStar[0] = gp_data_0.response_function(i);\n    }\n  }\n\n  // update truthFnStar with all additional primary/secondary fns corresponding\n  // to lowest merit function value\n  for (i=1; i<numFunctions; ++i)\n    truthFnStar[i]\n      = fHatModel.approximation_data(i).response_function(sam_star_idx);\n}\n\n\nvoid EffGlobalMinimizer::update_penalty()\n{\n  // Logic follows Conn, Gould, and Toint, section 14.4, step 3\n  //   CGT use mu *= tau with tau = 0.01 ->   r_p *= 50\n  //   Rodriguez, Renaud, Watson:             r_p *= 10\n  //   Robinson, Willcox, Eldred, and Haimes: r_p *= 5\n  penaltyParameter *= 10.;\n  //penaltyParameter = std::min(penaltyParameter, 1.e+20); // cap the max penalty?\n  Real mu = 1./2./penaltyParameter; // conversion between r_p and mu penalties\n  etaSequence = eta*std::pow(mu, alphaEta);\n\n#ifdef DEBUG\n  Cout << \"Penalty updated: \" << penaltyParameter << '\\n'\n       << \"eta updated:     \" << etaSequence      << '\\n'\n       << \"Augmented Lagrange multipliers:\\n\" << augLagrangeMult;\n#endif\n}\n\n} // namespace Dakota\n", "meta": {"hexsha": "24d447ca56bbe31675e63290c553747a4dee68f9", "size": 24424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/EffGlobalMinimizer.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/EffGlobalMinimizer.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/EffGlobalMinimizer.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2222222222, "max_line_length": 92, "alphanum_fraction": 0.7058630855, "num_tokens": 6585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.02931223191730985, "lm_q1q2_score": 0.012161611190219065}}
{"text": "/*\n * Copyright (C) 2011-2012, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n */\n\n#include <urbi/object/global.hh>\n#include <urbi/object/matrix.hh>\n#include <boost/numeric/ublas/lu.hpp> // boost::numeric::ublas::row\n#include <kernel/uvalue-cast.hh>\n\n#define FORWARD_EXCEPTION(Command)              \\\n  do {                                          \\\n    try                                         \\\n    {                                           \\\n      Command;                                  \\\n    }                                           \\\n    catch (const std::runtime_error& e)         \\\n    {                                           \\\n      FRAISE(e.what());                         \\\n    }                                           \\\n  } while (false)\n\nnamespace urbi\n{\n  namespace object\n  {\n\n    namespace ublas = boost::numeric::ublas;\n\n    ATTRIBUTE_NORETURN\n    static inline void\n    raise_incompatible_sizes(const matrix_type& m1, const matrix_type& m2,\n                             const std::string& hint = \"\")\n    {\n      FRAISE(\"incompatible sizes: %sx%s, %sx%s%s%s\",\n             m1.size1(), m1.size2(), m2.size1(), m2.size2(),\n             hint.empty() ? \"\" : \": \",\n             hint);\n    }\n\n    ATTRIBUTE_NORETURN\n    static inline void\n    raise_incompatible_sizes(const matrix_type& m, const vector_type& v,\n                             const std::string& hint = \"\")\n    {\n      FRAISE(\"incompatible sizes: %sx%s, %s%s%s\",\n             m.size1(), m.size2(), v.size(),\n             hint.empty() ? \"\" : \": \",\n             hint);\n    }\n\n#define CHECK_SIZE(Matrix1, Matrix2, Assertion)         \\\n    do {                                                \\\n      if (!(Assertion))                                 \\\n        raise_incompatible_sizes((Matrix1), (Matrix2)); \\\n    } while (0);\n\n\n    static inline\n    void\n    check_equal_size(const matrix_type& m1, const matrix_type& m2)\n    {\n      CHECK_SIZE(m1, m2, m1.size1() == m2.size1() && m1.size2() == m2.size2());\n    }\n\n    static inline\n    void\n    check_equal_size2(const matrix_type& m1, const matrix_type& m2)\n    {\n      CHECK_SIZE(m1, m2, m1.size2() == m2.size2());\n    }\n\n    static inline\n    void\n    check_equal_size1(const matrix_type& m, const vector_type& v)\n    {\n      CHECK_SIZE(m, v, m.size1() == v.size());\n    }\n\n    static inline\n    void\n    check_equal_size2(const matrix_type& m, const vector_type& v)\n    {\n      CHECK_SIZE(m, v, m.size2() == v.size());\n    }\n\n    /*---------.\n    | Matrix.  |\n    `---------*/\n\n    Matrix::Matrix()\n      : value_()\n    {\n      proto_add(proto);\n    }\n\n    Matrix::Matrix(size_t i, size_t j)\n      : value_(i, j)\n    {\n      proto_add(proto);\n    }\n\n    Matrix::Matrix(value_type v)\n      : value_(v)\n    {\n      proto_add(proto);\n    }\n\n    Matrix::Matrix(const Matrix& model)\n      : CxxObject()\n      , super_comparable_type()\n      , value_(model.value_)\n    {\n      proto_add(proto);\n    }\n\n    Matrix::Matrix(const rMatrix& model)\n      : CxxObject()\n      , value_(model->value_)\n    {\n      proto_add(proto);\n    }\n\n    Matrix::Matrix(const objects_type& model)\n      : CxxObject()\n      , value_()\n    {\n      proto_add(proto);\n      fromList(model);\n    }\n\n    rMatrix\n    Matrix::init(const objects_type& args)\n    {\n      rMatrix self = args[0]->as<Matrix>();\n      if (!self)\n        runner::raise_type_error(args[1], Matrix::proto);\n\n      if (args.size() == 1)\n        runner::raise_arity_error(0, 1);\n      else if (args.size() == 2)\n      {\n        // Lists of non-floats.\n        if (rList l = args[1]->as<List>())\n        {\n          const objects_type& list = l->value_get();\n          if (list.empty() || !list[0]->as<Float>())\n          {\n            self->fromList(list);\n            return self;\n          }\n          // Process list of floats such as [1, 2] in the fallback,\n          // i.e., as [[1, 2]] so that we support \"init([1], [2])\" but\n          // also \"init([1, 2])\".\n        }\n        else if (rMatrix v = args[1]->as<Matrix>())\n        {\n          self->value_ = v->value_;\n          return self;\n        }\n      }\n      else if (args.size() == 3\n               && args[1]->as<Float>()\n               && args[2]->as<Float>())\n      {\n        self->value_ = create_zeros(self,\n                                    from_urbi<unsigned>(args[1]),\n                                    from_urbi<unsigned>(args[2]));\n        return self;\n      }\n\n      objects_type effective_args(args.begin() + 1, args.end());\n      return self->fromList(effective_args);\n    }\n\n    Matrix::value_type\n    Matrix::create_zeros(rObject, size_t size1, size_t size2)\n    {\n      return ublas::zero_matrix<ufloat>(size1, size2);\n    }\n\n    Matrix::value_type\n    Matrix::create_identity(rObject, size_t size)\n    {\n      return ublas::identity_matrix<ufloat>(size);\n    }\n\n    Matrix::value_type\n    Matrix::create_scalars(rObject, size_t size1, size_t size2, ufloat v)\n    {\n      return ublas::scalar_matrix<ufloat>(size1, size2, v);\n    }\n\n    Matrix::value_type\n    Matrix::create_ones(rObject self, size_t size1, size_t size2)\n    {\n      return create_scalars(self, size1, size2, 1.0);\n    }\n\n    Matrix::value_type\n    Matrix::transpose() const\n    {\n      return trans(value_);\n    }\n\n    Matrix::value_type\n    Matrix::inverse() const\n    {\n      FORWARD_EXCEPTION(return ublas::inverse(value_));\n    }\n\n    Matrix::value_type\n    Matrix::dot_times(const value_type& m) const\n    {\n      value_type res(size1(), size2());\n      for (size_t i = 0; i < size1(); ++i)\n        for (size_t j = 0; j < size2(); ++j)\n          res(i, j) = value_(i, j) * m(i, j);\n      return res;\n    }\n\n    Matrix*\n    Matrix::fromList(const objects_type& args)\n    {\n      size_type width;\n      // For the first iteration, register and the matrix width and\n      // resize, for following iterations make sure the sizes are\n      // correct.\n#define CHECK_WIDTH(Width)                                              \\\n      do {                                                              \\\n        size_t _width = Width;                                          \\\n        if (!i)                                                         \\\n        {                                                               \\\n          width = _width;                                               \\\n          value_.resize(height, width, false);                          \\\n        }                                                               \\\n        else if (width != _width)                                       \\\n          FRAISE(\"expecting rows of size %d, got size %d for row %d\",   \\\n                 width, _width, i + 1);                                 \\\n      } while (false)\n\n      const size_type height = args.size();\n      for (unsigned i = 0; i < height; ++i)\n      {\n        if (rList l = args[i]->as<List>())\n        {\n          CHECK_WIDTH(l->size());\n          unsigned j = 0;\n          foreach (const rObject& o, l->value_get())\n          {\n            if (rFloat f = o->as<Float>())\n              value_(i, j) = f->value_get();\n            else\n              runner::raise_type_error(args[i], Float::proto);\n            ++j;\n          }\n        }\n        else if (rVector l = args[i]->as<Vector>())\n        {\n          CHECK_WIDTH(l->size());\n          unsigned j = 0;\n          foreach (ufloat v, l->value_get())\n            value_(i, j++) = v;\n        }\n        else\n          runner::raise_type_error(args[i], List::proto);\n      }\n      return this;\n#undef CHECK_WIDTH\n    }\n\n\n// FIXME: We should be able to return value_type, but then, it is\n// bind_variadic that does not manage to bind minus and so forth.\n// In that case, get rid of Conversion.\n#define OP(Op, Res, Conversion, Name, Sym)                      \\\n    Res                                                         \\\n    Matrix::Name(const objects_type& args)                      \\\n    {                                                           \\\n      rMatrix self = args[0]->as<Matrix>();                     \\\n      check_arg_count(args, 1);                                 \\\n      if (rFloat f = args[1]->as<Float>())                      \\\n        return Conversion(self->operator Op(f->value_get()));   \\\n      else if (rMatrix m = args[1]->as<Matrix>())               \\\n        return Conversion(self->operator Op(m->value_get()));   \\\n      runner::raise_argument_type_error                         \\\n        (1, args[1], Matrix::proto, to_urbi(SYMBOL(Sym)));      \\\n    }\n\n    OP(+,  Matrix*, new Matrix, plus,         PLUS)\n    OP(-,  Matrix*, new Matrix, minus,        MINUS)\n    OP(/,  Matrix*, new Matrix, div,          SLASH)\n    OP(*,  Matrix*, new Matrix, times,        STAR)\n\n    OP(+=, Matrix*,           , plus_assign,  PLUS_EQ)\n    OP(-=, Matrix*,           , minus_assign, MINUS_EQ)\n    OP(/=, Matrix*,           , div_assign,   SLASH_EQ)\n    OP(*=, Matrix*,           , times_assign, STAR_EQ)\n\n#undef OP\n\n    /*------------------------------------------------------.\n    | Arithmetic and in-place arithmetic between matrices.  |\n    `------------------------------------------------------*/\n\n#define OP(Op)                                          \\\n    Matrix::value_type                                  \\\n    Matrix::operator Op(const value_type& m) const      \\\n    {                                                   \\\n      check_equal_size(value_, m);                      \\\n      value_type res(value_);                           \\\n      res Op##= m;                                      \\\n      return res;                                       \\\n    }                                                   \\\n                                                        \\\n    Matrix*                                             \\\n    Matrix::operator Op##=(const value_type& m)         \\\n    {                                                   \\\n      check_equal_size(value_, m);                      \\\n      value_ Op##= m;                                   \\\n      return this;                                      \\\n    }\n\n    OP(+)\n    OP(-)\n#undef OP\n\n    Matrix::value_type\n    Matrix::operator /(const value_type& rhs) const\n    {\n      FORWARD_EXCEPTION(return prod(value_, ublas::inverse(rhs)));\n    }\n\n    Matrix*\n    Matrix::operator /=(const value_type& rhs)\n    {\n      FORWARD_EXCEPTION(value_ = prod(value_, ublas::inverse(rhs)));\n      return this;\n    }\n\n    Matrix::value_type\n    Matrix::operator *(const value_type& rhs) const\n    {\n      CHECK_SIZE(value_, rhs, value_.size2() == rhs.size1());\n      return prod(value_, rhs);\n    }\n\n    Matrix*\n    Matrix::operator *=(const value_type& rhs)\n    {\n      value_ = *this * rhs;\n      return this;\n    }\n\n\n    /*--------------------------.\n    | Arithmetic between rows.  |\n    `--------------------------*/\n\n#define OP(Name, Op)                            \\\n    Matrix::value_type                          \\\n    Matrix::Name(const vector_type& rhs) const  \\\n    {                                           \\\n      check_equal_size1(value_, rhs);           \\\n      const size_t height = size1();            \\\n      const size_t width = size2();             \\\n      value_type res = value_;                  \\\n      for (unsigned i = 0; i < height; ++i)     \\\n        for (unsigned j = 0; j < width; ++j)    \\\n          res(i, j) Op ## = rhs(i);             \\\n      return res;                               \\\n    }\n\n    OP(rowAdd, +)\n    OP(rowSub, -)\n    OP(rowMul, *)\n    OP(rowDiv, /)\n#undef OP\n\n\n    /*--------------------------.\n    | Arithmetic with scalars.  |\n    `--------------------------*/\n\n#define OP(Op)                                  \\\n    Matrix::value_type                          \\\n    Matrix::operator Op(ufloat s) const         \\\n    {                                           \\\n      value_type res(value_);                   \\\n      res Op##= s;                              \\\n      return res;                               \\\n    }                                           \\\n                                                \\\n    Matrix*                                     \\\n    Matrix::operator Op##=(ufloat s)            \\\n    {                                           \\\n      value_ Op##= s;                           \\\n      return this;                              \\\n    }\n\n    OP(*)\n    OP(/)\n\n#undef OP\n\n#define OP(Op)                                                  \\\n    Matrix::value_type                                          \\\n    Matrix::operator Op(ufloat s) const                         \\\n    {                                                           \\\n      value_type copy(value_);                                  \\\n      value_type ones = create_scalars(0, size1(), size2(), s); \\\n      value_type res = copy Op ones;                            \\\n      return res;                                               \\\n    }                                                           \\\n                                                                \\\n    Matrix*                                                     \\\n    Matrix::operator Op##=(ufloat s)                            \\\n    {                                                           \\\n      value_ = operator Op(s);                                  \\\n      return this;                                              \\\n    }\n\n    OP(+)\n    OP(-)\n#undef OP\n\n    URBI_CXX_OBJECT_INIT(Matrix)\n      : value_()\n    {\n      BIND_VARIADIC(MINUS, minus);\n      BIND_VARIADIC(MINUS_EQ, minus_assign);\n      BIND_VARIADIC(PLUS, plus);\n      BIND_VARIADIC(PLUS_EQ, plus_assign);\n      BIND_VARIADIC(SLASH, div);\n      BIND_VARIADIC(SLASH_EQ, div_assign);\n      BIND_VARIADIC(STAR, times);\n      BIND_VARIADIC(STAR_EQ, times_assign);\n\n      //BIND(dot_times, dotWiseMult);\n      //BIND(solve);\n      BIND(EQ_EQ, operator==, bool, (const rObject&) const);\n      BIND(SBL_SBR, operator());\n      BIND(SBL_SBR_EQ, set);\n      BIND(appendRow);\n      BIND(asPrintable);\n      BIND(asString);\n      BIND(asTopLevelPrintable);\n      BIND(column);\n      BIND(createIdentity, create_identity);\n      BIND(createOnes, create_ones);\n      BIND(createScalars, create_scalars);\n      BIND(createZeros, create_zeros);\n      BIND(distanceMatrix);\n      BIND(inverse);\n      BIND(resize);\n      BIND(row);\n      BIND(rowAdd);\n      BIND(rowDiv);\n      BIND(rowMul);\n      BIND(rowNorm);\n      BIND(rowSub);\n      BIND(set, fromList);\n      BIND(setRow);\n      BINDG(size, size, rObject, () const);\n      BIND(transpose);\n      BIND(uvalueSerialize);\n      slot_set_value(SYMBOL(init), new Primitive(&init));\n    }\n\n    std::string\n    Matrix::asString() const\n    {\n      return make_string('<', '>', \"<\", \">\");\n    }\n\n    std::string\n    Matrix::asPrintable() const\n    {\n      return make_string('[', ']', \"Matrix([\", \"])\");\n    }\n\n    std::string\n    Matrix::make_string(char col_lsep, char col_rsep,\n                        const std::string row_lsep,\n                        const std::string row_rsep) const\n    {\n      const size_t height = size1();\n      const size_t width = size2();\n\n      std::ostringstream s;\n      s << row_lsep;\n      for (unsigned i = 0; i < height; ++i)\n      {\n        if (i)\n          s << \", \";\n        s << col_lsep;\n        for (unsigned j = 0; j < width; ++j)\n        {\n          if (j)\n            s << \", \";\n          s << value_(i, j);\n        }\n        s << col_rsep;\n      }\n      s << row_rsep;\n      return s.str();\n    }\n\n\n    std::string\n    Matrix::asTopLevelPrintable() const\n    {\n      const size_t height = size1();\n      const size_t width = size2();\n\n      std::ostringstream s;\n      s << \"Matrix([\";\n\n      for (unsigned i = 0; i < height; ++i)\n      {\n        if (i)\n          s << ',';\n        s << std::endl;\n        s << \"  [\";\n        for (unsigned j = 0; j < width; ++j)\n        {\n          if (j)\n            s << \", \";\n          s << value_(i, j);\n        }\n        s << \"]\";\n      }\n\n      s << \"])\";\n\n      return s.str();\n    }\n\n    ufloat\n    Matrix::operator()(int i, int j) const\n    {\n      return get(i, j);\n    }\n\n    ufloat\n    Matrix::set(int i, int j, ufloat v)\n    {\n      return value_(index1(i), index2(j)) = v;\n    }\n\n    ufloat\n    Matrix::get(int i, int j) const\n    {\n      return value_(index1(i), index2(j));\n    }\n\n    rObject\n    Matrix::size() const\n    {\n      CAPTURE_GLOBAL(Pair);\n      return Pair->call(SYMBOL(new), new Float(size1()), new Float(size2()));\n    }\n\n    Matrix::vector_type\n    Matrix::row(int i) const\n    {\n      return boost::numeric::ublas::row(value_, index1(i));\n    }\n\n    Matrix::vector_type\n    Matrix::column(int i) const\n    {\n      return boost::numeric::ublas::column(value_, index2(i));\n    }\n\n    Matrix::value_type\n    Matrix::distanceMatrix(const value_type& b) const\n    {\n      check_equal_size2(value_, b);\n      const size_t height = size1();\n      const size_t width = size2();\n      const size_t height2 = b.size1();\n      value_type res(height, height2);\n      for (unsigned p1 = 0; p1 < height; ++p1)\n        for (unsigned p2 = 0; p2 < height2; ++p2)\n        {\n          ufloat v = 0;\n          for (unsigned i=0; i < width; ++i)\n          {\n            ufloat t = value_(p1, i) - b(p2, i);\n            v += t*t;\n          }\n          res(p1, p2) = sqrt(v);\n        }\n      return res;\n    }\n\n    Matrix::vector_type\n    Matrix::rowNorm() const\n    {\n      // FIXME: there might be something in Boost to do that.\n      const size_t height = size1();\n      const size_t width = size2();\n      vector_type res(height);\n      for (unsigned p1 = 0; p1<height; ++p1)\n      {\n        ufloat v = 0;\n        for (unsigned i=0; i<width; ++i)\n        {\n          ufloat t = value_(p1, i);\n          v += t*t;\n        }\n        res[p1] = sqrt(v);\n      }\n      return res;\n    }\n\n    Matrix*\n    Matrix::setRow(int r, const vector_type& v)\n    {\n      check_equal_size2(value_, v);\n      int j = index1(r);\n      for (unsigned i = 0; i< v.size(); ++i)\n        value_(j, i) = v(i);\n      return this;\n    }\n\n    Matrix*\n    Matrix::appendRow(const vector_type& v)\n    {\n      check_equal_size2(value_, v);\n      value_.resize(size1()+1, size2());\n      setRow(size1()-1, v);\n      return this;\n    }\n\n    Matrix*\n    Matrix::resize(size_t ns1, size_t ns2)\n    {\n      size_t s1 = value_.size1();\n      size_t s2 = value_.size2();\n      value_.resize(ns1, ns2);\n      // Boost does not ensure that we have 0 for new members.\n      for (size_t i = 0; i < ns1; ++i)\n        for (size_t j = i < s1 ? s2 : 0; j < ns2; ++j)\n          value_(i, j) = 0;\n      return this;\n    }\n\n    rObject\n    Matrix::uvalueSerialize() const\n    {\n      CAPTURE_GLOBAL(Binary);\n      // This is ugly: we cannot go through object-cast as it would give us\n      // back the vector. So make the Binary ourselve.\n      // This is also a duplicate of Vector::uvalueSerialize.\n      rObject o(const_cast<Matrix*>(this));\n      urbi::UValue v = ::uvalue_cast(o);\n      rObject res = new object::Object();\n      res->proto_add(Binary);\n      res->slot_set_value(SYMBOL(keywords),\n                    new object::String(v.binary->getMessage()));\n      res->slot_set_value(SYMBOL(data),\n                    new object::String\n                    (std::string(static_cast<char*>(v.binary->common.data),\n\t\t\t\t v.binary->common.size)));\n      return res;\n    }\n  }\n}\n", "meta": {"hexsha": "1212899e3d23682723c4444984d1c413378654a2", "size": 19568, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/object/matrix.cc", "max_stars_repo_name": "jcbaillie/urbi", "max_stars_repo_head_hexsha": "fb17359b2838cdf8d3c0858abb141e167a9d4bdb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2016-05-10T05:50:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T22:16:13.000Z", "max_issues_repo_path": "src/object/matrix.cc", "max_issues_repo_name": "jcbaillie/urbi", "max_issues_repo_head_hexsha": "fb17359b2838cdf8d3c0858abb141e167a9d4bdb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-09-05T10:08:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-13T10:51:07.000Z", "max_forks_repo_path": "src/object/matrix.cc", "max_forks_repo_name": "jcbaillie/urbi", "max_forks_repo_head_hexsha": "fb17359b2838cdf8d3c0858abb141e167a9d4bdb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T20:27:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T19:26:08.000Z", "avg_line_length": 28.9467455621, "max_line_length": 79, "alphanum_fraction": 0.4415883074, "num_tokens": 4591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.029312231069343643, "lm_q1q2_score": 0.012161610838398862}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"../include/structures.h\"\n#include \"../include/transformations.h\"\n#include \"../../example_func_xy_jacobian.h\"\n#include \"../../constraints_jacobian.h\"\n#include \"../../relative_pose_tait_bryan_wc_jacobian.h\"\n#include \"../../point_to_point_source_to_target_tait_bryan_wc_jacobian.h\"\n#include \"../include/cauchy.h\"\n#include \"../../smoothness_tait_bryan_wc_jacobian.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -50.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nstd::vector<Eigen::Vector3d> reference_points;\n\nstd::vector<Eigen::Affine3d> vertices;\nstd::vector<Eigen::Affine3d> vertices_odo;\nint number_rows = 0;\nint number_cols = 0;\nstd::vector<std::pair<int, int>> odo_edges;\n\nstruct TripletIndexes{\n\tint index_before;\n\tint index_curr;\n\tint index_after;\n};\n\nstd::vector<TripletIndexes> smoothness_indexes;\n\nbool find_nearest_neighbour(Eigen::Vector3d &p_t, Eigen::Affine3d vertex, const std::vector<Eigen::Vector3d>& reference_points){\n\tdouble min_dist_xy = 1000000.0;\n\tdouble search_radious = 1.0;\n\tbool found = false;\n\n\tfor(size_t i = 0 ; i < reference_points.size(); i++){\n\t\tfloat dist = sqrt ( (vertex(0,3) - reference_points[i].x()) * (vertex(0,3) - reference_points[i].x()) + (vertex(1,3) - reference_points[i].y()) * (vertex(1,3) - reference_points[i].y()) );\n\n\t\tif( dist < search_radious  ) {\n\t\t\tif( dist < min_dist_xy){\n\t\t\t\tmin_dist_xy = dist;\n\t\t\t\tp_t = reference_points[i];\n\t\t\t\tp_t.x() = vertex(0,3) + ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\t\tp_t.y() = vertex(1,3) + ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\t\tfound = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn found;\n}\n\nint main(int argc, char *argv[]){\n\n\tfor(size_t i = 0; i < 10000; i++){\n\t\tdouble x = ((float(rand()%1000000)/1000000.0f - 0.5) * 2.0) * 20.0;\n\t\tdouble y = ((float(rand()%1000000)/1000000.0f - 0.5) * 2.0) * 20.0;\n\t\tdouble z;\n\t\texample_func_xy(z, x, y);\n\n\t\tif( (x-4)*(x-4) + (y-5)*(y-5) > 49){\n\t\t\treference_points.emplace_back(x,y,z*10 + ((float(rand()%1000000)/1000000.0f - 0.5) * 2.0) * 0.1);\n\t\t}\n\t}\n\n\tfor(int x = -20; x <= 20; x += 1){\n\t\tfor(int y = -20; y <= 20; y += 1){\n\t\t\tif(number_rows == 0){\n\t\t\t\tnumber_cols ++;\n\t\t\t}\n\t\t\tEigen::Affine3d pose = Eigen::Affine3d::Identity();\n\t\t\tpose(0,3) = x;\n\t\t\tpose(1,3) = y;\n\t\t\tpose(2,3) = -10;\n\t\t\tvertices.push_back(pose);\n\t\t}\n\t\tnumber_rows ++;\n\t}\n\tvertices_odo = vertices;\n\n\tfor(int row = 0; row < number_rows; row++){\n\t\tfor(int col = 0; col < number_cols; col++){\n\t\t\tint index = row + col * number_rows;\n\t\t\tif(row + 1 < number_rows){\n\t\t\t\tint index_next_row = (row + 1) + col * number_rows;\n\t\t\t\todo_edges.emplace_back(index, index_next_row);\n\t\t\t}\n\n\t\t\tif(col + 1 < number_cols){\n\t\t\t\tint index_next_col = (row) + (col + 1) * number_rows;\n\t\t\t\todo_edges.emplace_back(index, index_next_col);\n\t\t\t}\n\n\t\t\tif(row + 1 < number_rows && row - 1 >= 0){\n\t\t\t\tint index_prev_row = (row - 1) + col * number_rows;\n\t\t\t\tint index_next_row = (row + 1) + col * number_rows;\n\t\t\t\tTripletIndexes tr;\n\t\t\t\ttr.index_curr = index;\n\t\t\t\ttr.index_before = index_prev_row;\n\t\t\t\ttr.index_after = index_next_row;\n\t\t\t\tsmoothness_indexes.push_back(tr);\n\t\t\t}\n\t\t\tif(col + 1 < number_cols && col - 1 >= 0){\n\t\t\t\tint index_next_col = (row) + (col + 1) * number_rows;\n\t\t\t\tint index_prev_col = (row) + (col - 1) * number_rows;\n\t\t\t\tTripletIndexes tr;\n\t\t\t\ttr.index_curr = index;\n\t\t\t\ttr.index_before = index_prev_col;\n\t\t\t\ttr.index_after = index_next_col;\n\t\t\t\tsmoothness_indexes.push_back(tr);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\n\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"surface_reconstruction_from_lidar_point_cloud\");\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\tglPointSize(3);\n\tglColor3f(1,0,0);\n\tglBegin(GL_POINTS);\n\tfor(size_t i = 0; i < reference_points.size(); i++){\n\t\tglVertex3f(reference_points[i].x(), reference_points[i].y(), reference_points[i].z());\n\t}\n\tglEnd();\n\tglPointSize(1);\n\n\tglPointSize(2);\n\tglColor3f(0,0,0);\n\tglBegin(GL_POINTS);\n\tfor(int row = 0; row < number_rows; row++){\n\t\tfor(int col = 0; col < number_cols; col++){\n\t\t\tint index = row + col * number_rows;\n\t\t\tglVertex3f(vertices[index](0,3), vertices[index](1,3), vertices[index](2,3));\n\t\t}\n\t}\n\tglEnd();\n\tglPointSize(1);\n\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < odo_edges.size(); i++){\n\t\tglVertex3f(vertices[odo_edges[i].first](0,3), vertices[odo_edges[i].first](1,3), vertices[odo_edges[i].first](2,3));\n\t\tglVertex3f(vertices[odo_edges[i].second](0,3), vertices[odo_edges[i].second](1,3), vertices[odo_edges[i].second](2,3));\n\t}\n\tglEnd();\n\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 'n':{\n\t\t\tfor(size_t i = 0 ; i < vertices.size(); i++){\n\t\t\t\tTaitBryanPose pose;\n\t\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\n\t\t\t\tvertices[i] = vertices[i] * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<TaitBryanPose> poses_odo;\n\n\t\t\tfor(size_t i = 0 ; i < vertices.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(vertices[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < vertices_odo.size(); i++){\n\t\t\t\tposes_odo.push_back(pose_tait_bryan_from_affine_matrix(vertices_odo[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].om,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].om,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\tTaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\n\t\t\t\tEigen::Vector3d p_t;//(georeference_data[i].first(0,3), georeference_data[i].first(1,3), georeference_data[i].first(2,3));\n\t\t\t\tif(!find_nearest_neighbour(p_t, vertices[i], reference_points)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tEigen::Vector3d p_s(0,0,0);\n\t\t\t\tdouble delta_x;\n\t\t\t\tdouble delta_y;\n\t\t\t\tdouble delta_z;\n\t\t\t\tpoint_to_point_source_to_target_tait_bryan_wc(delta_x, delta_y, delta_z, pose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka, p_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\t\t\t\tEigen::Matrix<double, 3, 6, Eigen::RowMajor> jacobian;\n\t\t\t\tpoint_to_point_source_to_target_tait_bryan_wc_jacobian(jacobian, pose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka, p_s.x(), p_s.y(), p_s.z());\n\n\t\t\t\tint ic = i * 6;\n\t\t\t\ttripletListA.emplace_back(ir     , ic + 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 1, -jacobian(1,1));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 2, -jacobian(2,2));\n\n\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  1);\n\n\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(vertices.size() * 6 , vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(vertices.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * vertices.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tvertices[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'y':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<TaitBryanPose> poses_odo;\n\n\t\t\tfor(size_t i = 0 ; i < vertices.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(vertices[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < vertices_odo.size(); i++){\n\t\t\t\tposes_odo.push_back(pose_tait_bryan_from_affine_matrix(vertices_odo[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].om,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes_odo[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].om,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes_odo[odo_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\tTaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\n\t\t\t\tEigen::Vector3d p_t;\n\t\t\t\tif(!find_nearest_neighbour(p_t, vertices[i], reference_points)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic = i * 6;\n\t\t\t\tdouble delta;\n\t\t\t\tdouble a = 1;\n\t\t\t\tEigen::Matrix<double, 1, 1> jacobian;\n\t\t\t\tobservation_equation_constraint(delta, a, vertices[i](0,3), p_t.x());\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, vertices[i](0,3), p_t.x());\n\n\t\t\t\ttripletListA.emplace_back(ir, ic,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir, ir,  1);\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, vertices[i](1,3), p_t.y());\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, vertices[i](1,3), p_t.y());\n\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic + 1,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, vertices[i](2,3), p_t.z());\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, vertices[i](2,3), p_t.z());\n\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic + 2,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  1);\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(vertices.size() * 6 , vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(vertices.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * vertices.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tvertices[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'x':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\n\t\t\tfor(size_t i = 0 ; i < vertices.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(vertices[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < smoothness_indexes.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\tsmoothness_obs_eq_tait_bryan_wc(delta,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 18, Eigen::RowMajor> jacobian;\n\t\t\t\tsmoothness_obs_eq_tait_bryan_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = smoothness_indexes[i].index_before * 6;\n\t\t\t\tint ic_2 = smoothness_indexes[i].index_curr * 6;\n\t\t\t\tint ic_3 = smoothness_indexes[i].index_after * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3    , -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 1, -jacobian(row,13));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 2, -jacobian(row,14));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 3, -jacobian(row,15));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 4, -jacobian(row,16));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 5, -jacobian(row,17));\n\t\t\t\t}\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\tTaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\n\t\t\t\tEigen::Vector3d p_t;//(georeference_data[i].first(0,3), georeference_data[i].first(1,3), georeference_data[i].first(2,3));\n\t\t\t\tif(!find_nearest_neighbour(p_t, vertices[i], reference_points)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tEigen::Vector3d p_s(0,0,0);\n\t\t\t\tdouble delta_x;\n\t\t\t\tdouble delta_y;\n\t\t\t\tdouble delta_z;\n\t\t\t\tpoint_to_point_source_to_target_tait_bryan_wc(delta_x, delta_y, delta_z, pose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka, p_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\t\t\t\tEigen::Matrix<double, 3, 6, Eigen::RowMajor> jacobian;\n\t\t\t\tpoint_to_point_source_to_target_tait_bryan_wc_jacobian(jacobian, pose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka, p_s.x(), p_s.y(), p_s.z());\n\n\t\t\t\tint ic = i * 6;\n\t\t\t\ttripletListA.emplace_back(ir     , ic + 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , ic + 1, -jacobian(1,1));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , ic + 2, -jacobian(2,2));\n\n\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  1);\n\n\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(vertices.size() * 6 , vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(vertices.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * vertices.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tvertices[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'z':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\n\t\t\tfor(size_t i = 0 ; i < vertices.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(vertices[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < smoothness_indexes.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\tsmoothness_obs_eq_tait_bryan_wc(delta,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 18, Eigen::RowMajor> jacobian;\n\t\t\t\tsmoothness_obs_eq_tait_bryan_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_before].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_curr].ka,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].px,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].py,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].pz,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].om,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].fi,\n\t\t\t\t\t\tposes[smoothness_indexes[i].index_after].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = smoothness_indexes[i].index_before * 6;\n\t\t\t\tint ic_2 = smoothness_indexes[i].index_curr * 6;\n\t\t\t\tint ic_3 = smoothness_indexes[i].index_after * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3    , -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 1, -jacobian(row,13));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 2, -jacobian(row,14));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 3, -jacobian(row,15));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 4, -jacobian(row,16));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_3 + 5, -jacobian(row,17));\n\t\t\t\t}\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\tTaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\n\t\t\t\tEigen::Vector3d p_t;\n\t\t\t\tif(!find_nearest_neighbour(p_t, vertices[i], reference_points)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic = i * 6;\n\t\t\t\tdouble delta;\n\t\t\t\tdouble a = 1;\n\t\t\t\tEigen::Matrix<double, 1, 1> jacobian;\n\t\t\t\tobservation_equation_constraint(delta, a, vertices[i](0,3), p_t.x());\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, vertices[i](0,3), p_t.x());\n\n\t\t\t\ttripletListA.emplace_back(ir, ic,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir, ir,  1);\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, vertices[i](1,3), p_t.y());\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, vertices[i](1,3), p_t.y());\n\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic + 1,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta);\n\n\t\t\t\tobservation_equation_constraint(delta, a, vertices[i](2,3), p_t.z());\n\t\t\t\tobservation_equation_constraint_jacobian(jacobian, a, vertices[i](2,3), p_t.z());\n\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic + 2,  -jacobian(0,0));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  1);\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(vertices.size() * 6 , vertices.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(vertices.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * vertices.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < vertices.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(vertices[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tvertices[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\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 << \"t: optimize (relative pose constraint and source to target)\" << std::endl;\n\tstd::cout << \"y: optimize (relative pose constraint and linear function constraint)\" << std::endl;\n\tstd::cout << \"x: optimize (smoothness constraint and source to target)\" << std::endl;\n\tstd::cout << \"z: optimize (smoothness constraint and linear function constraint)\" << std::endl;\n\tstd::cout << \"n: add noise to mesh\" << std::endl;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "276a2ad53f16f69a29d8a4548b2a892fd44645f4", "size": 39479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/surface_reconstruction_from_lidar_point_cloud.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/surface_reconstruction_from_lidar_point_cloud.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/surface_reconstruction_from_lidar_point_cloud.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": 35.630866426, "max_line_length": 197, "alphanum_fraction": 0.6533346843, "num_tokens": 13014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.028007520301746292, "lm_q1q2_score": 0.012154744686076784}}
{"text": "#include \"MeshCuboidRelation.h\"\n\n#include \"Utilities.h\"\n\n#include <cstdint>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <sstream>\n#include <Eigen/Eigenvalues> \n#include <Eigen/LU> \n\n\n// Note:\n// Assume that z = 0 plane is the ground plane, and +z-axis is the normal direction.\nconst MyMesh::Normal MeshCuboidAttributes::k_up_direction = MyMesh::Normal(0.0, 0.0, 1.0);\n\nMeshCuboidAttributes::MeshCuboidAttributes()\n\t: object_name_(\"\")\n{\n\tinitialize();\n}\n\nMeshCuboidAttributes::MeshCuboidAttributes(const std::string _object_name)\n\t: object_name_(_object_name)\n{\n\tinitialize();\n}\n\nMeshCuboidAttributes::MeshCuboidAttributes(const MeshCuboidAttributes& _other)\n\t: object_name_(_other.object_name_)\n\t, attributes_(_other.attributes_)\n{\n}\n\nMeshCuboidAttributes::~MeshCuboidAttributes()\n{\n}\n\nvoid MeshCuboidAttributes::initialize()\n{\n\t// Note:\n\t// Initialized with NaN.\n\tif (!std::numeric_limits<Real>::has_quiet_NaN)\n\t{\n\t\tstd::cerr << \"Error: \" << typeid(Real).name() << \" does not support quiet NaN.\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\tconst int num_attributes = static_cast<int>(k_num_attributes);\n\n\tattributes_ = Eigen::VectorXd::Zero(num_attributes);\n\tfor (int attribute_index = 0; attribute_index < num_attributes; ++attribute_index)\n\t{\n\t\tattributes_[attribute_index] = std::numeric_limits<Real>::quiet_NaN();\n\t}\n}\n\nvoid MeshCuboidAttributes::compute_attributes(const MeshCuboid *_cuboid)\n{\n\tassert(attributes_.size() == static_cast<int>(k_num_attributes));\n\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t{\n\t\t//attributes_[k_center_index + i] = _cuboid->get_bbox_center()[i];\n\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t\tattributes_[k_corner_index + 3 * corner_index + i] = _cuboid->get_bbox_corner(corner_index)[i];\n\t}\n}\n\nvoid MeshCuboidAttributes::get_attribute_collection_matrix(const std::list<MeshCuboidAttributes *>& _stats,\n\tEigen::MatrixXd& _values)\n{\n\tunsigned int num_objects = _stats.size();\n\n\tconst int num_attributes = static_cast<int>(k_num_attributes);\n\t_values = Eigen::MatrixXd(num_objects, num_attributes);\n\n\tunsigned int object_index = 0;\n\tfor (std::list<MeshCuboidAttributes *>::const_iterator stat_it = _stats.begin(); stat_it != _stats.end();\n\t\t++stat_it, ++object_index)\n\t{\n\t\tassert(*stat_it);\n\n\t\tfor (int attribute_index = 0; attribute_index < num_attributes; ++attribute_index)\n\t\t\t_values(object_index, attribute_index) = (*stat_it)->attributes_[attribute_index];\n\t}\n}\n\nbool MeshCuboidAttributes::save_attribute_collection(const std::list<MeshCuboidAttributes *>& _stats,\n\tconst char* _filename)\n{\n\tconst int num_attributes = static_cast<int>(k_num_attributes);\n\n\tstd::ofstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't save file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\tstd::setprecision(std::numeric_limits<long double>::digits10 + 1);\n\tstd::cout << std::scientific;\n\n\t//unsigned int num_objects = _stats.size();\n\n\t// Write attribute values.\n\tunsigned int object_index = 0;\n\tfor (std::list<MeshCuboidAttributes *>::const_iterator stat_it = _stats.begin(); stat_it != _stats.end();\n\t\t++stat_it, ++object_index)\n\t{\n\t\tassert(*stat_it);\n\n\t\tfor (int attribute_index = 0; attribute_index < num_attributes; ++attribute_index)\n\t\t{\n\t\t\tReal value = (*stat_it)->attributes_[attribute_index];\n\t\t\tif (std::isnan(value))\n\t\t\t{\n\t\t\t\t// Note:\n\t\t\t\t// Undefined attributes are recorded as NaN.\n\t\t\t\tfile << \"NaN,\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfile << value << \",\";\n\t\t\t}\n\t\t}\n\t\tfile << std::endl;\n\t}\n\n\tfile.close();\n\treturn true;\n}\n\n\nMeshCuboidFeatures::MeshCuboidFeatures()\n\t: object_name_(\"\")\n{\n\tinitialize();\n}\n\nMeshCuboidFeatures::MeshCuboidFeatures(const std::string _object_name)\n\t: object_name_(_object_name)\n{\n\tinitialize();\n}\n\nMeshCuboidFeatures::MeshCuboidFeatures(const MeshCuboidFeatures& _other)\n\t: object_name_(_other.object_name_)\n\t, features_(_other.features_)\n{\n}\n\nMeshCuboidFeatures::~MeshCuboidFeatures()\n{\n}\n\nvoid MeshCuboidFeatures::initialize()\n{\n\t// Note:\n\t// Initialized with NaN.\n\tif (!std::numeric_limits<Real>::has_quiet_NaN)\n\t{\n\t\tstd::cerr << \"Error: \" << typeid(Real).name() << \" does not support quiet NaN.\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\tfeatures_ = Eigen::VectorXd::Zero(MeshCuboidFeatures::k_num_features);\n\tfor (int attribute_index = 0; attribute_index < MeshCuboidFeatures::k_num_features; ++attribute_index)\n\t{\n\t\tfeatures_[attribute_index] = std::numeric_limits<Real>::quiet_NaN();\n\t}\n}\n\nvoid MeshCuboidFeatures::compute_features(const MeshCuboid *_cuboid,\n\tEigen::MatrixXd *_attributes_to_features_map)\n{\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\tassert(features_.size() == static_cast<int>(MeshCuboidFeatures::k_num_features));\n\n\n\t// Linear map.\n\tEigen::MatrixXd attributes_to_features_map = \n\t\tEigen::MatrixXd::Zero(MeshCuboidFeatures::k_num_features, num_attributes);\n\n\tEigen::RowVector3d up_direction_vec;\n\tfor (unsigned int axis_index = 0; axis_index < 3; ++axis_index)\n\t\tup_direction_vec(axis_index) = MeshCuboidAttributes::k_up_direction[axis_index];\n\n\tunsigned int next_feature_index = 0;\n\n\n\t// Center point.\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t{\n\t\tfeatures_[next_feature_index] = _cuboid->get_bbox_center()[i];\n\n\t\t//attributes_to_features_map.row(next_feature_index)(\n\t\t//\tMeshCuboidAttributes::k_center_index + i) = 1.0;\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t{\n\t\t\tattributes_to_features_map.row(next_feature_index)(\n\t\t\t\tMeshCuboidAttributes::k_corner_index + 3 * corner_index + i) =\n\t\t\t\t1.0 / MeshCuboid::k_num_corners;\n\t\t}\n\n\t\t++next_feature_index;\n\t}\n\n\n\t// Corner points.\n\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t{\n\t\tMyMesh::Point corner = _cuboid->get_bbox_corner(corner_index);\n\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tfeatures_[next_feature_index] = corner[i];\n\t\t\tattributes_to_features_map.row(next_feature_index)(\n\t\t\t\tMeshCuboidAttributes::k_corner_index + 3 * corner_index + i) = 1.0;\n\t\t\t++next_feature_index;\n\t\t}\n\t}\n\n\n\t// Center height.\n\tfeatures_[next_feature_index] = dot(MeshCuboidAttributes::k_up_direction, _cuboid->get_bbox_center());\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t{\n\t\t//attributes_to_features_map.row(next_feature_index)(\n\t\t//\tMeshCuboidAttributes::k_center_index + i) = MeshCuboidAttributes::k_up_direction[i];\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t{\n\t\t\tattributes_to_features_map.row(next_feature_index)(\n\t\t\t\tMeshCuboidAttributes::k_corner_index + 3 * corner_index + i) =\n\t\t\t\t(1.0 / MeshCuboid::k_num_corners) * MeshCuboidAttributes::k_up_direction[i];\n\t\t}\n\t}\n\t++next_feature_index;\n\n\n\t// Corner height.\n\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t{\n\t\tMyMesh::Point corner = _cuboid->get_bbox_corner(corner_index);\n\t\tfeatures_[next_feature_index] = dot(MeshCuboidAttributes::k_up_direction, corner);\n\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tattributes_to_features_map.row(next_feature_index)(\n\t\t\t\tMeshCuboidAttributes::k_corner_index + 3 * corner_index + i) =\n\t\t\t\tMeshCuboidAttributes::k_up_direction[i];\n\t\t}\n\t\t++next_feature_index;\n\t}\n\n\tassert(next_feature_index == static_cast<int>(MeshCuboidFeatures::k_num_features));\n\n\n#ifdef DEBUG_TEST\n\tMeshCuboidAttributes attributes;\n\tattributes.compute_attributes(_cuboid);\n\tEigen::VectorXd same_features = attributes_to_features_map * attributes.get_attributes();\n\n\tassert(same_features.rows() == MeshCuboidFeatures::k_num_features);\n\tReal error = (same_features - features_).array().abs().sum();\n\n\tCHECK_NUMERICAL_ERROR(__FUNCTION__, error);\n#endif\n\n\t// Optional.\n\tif (_attributes_to_features_map)\n\t\t(*_attributes_to_features_map) = attributes_to_features_map;\n}\n\nvoid MeshCuboidFeatures::get_feature_collection_matrix(const std::list<MeshCuboidFeatures *>& _stats,\n\tEigen::MatrixXd& _values)\n{\n\tunsigned int num_objects = _stats.size();\n\n\tconst int num_features = static_cast<int>(k_num_features);\n\t_values = Eigen::MatrixXd(num_objects, num_features);\n\n\tunsigned int object_index = 0;\n\tfor (std::list<MeshCuboidFeatures *>::const_iterator stat_it = _stats.begin(); stat_it != _stats.end();\n\t\t++stat_it, ++object_index)\n\t{\n\t\tassert(*stat_it);\n\n\t\tfor (int feature_index = 0; feature_index < num_features; ++feature_index)\n\t\t\t_values(object_index, feature_index) = (*stat_it)->features_[feature_index];\n\t}\n}\n\nbool MeshCuboidFeatures::load_feature_collection(const char* _filename,\n\tstd::list<MeshCuboidFeatures *>& _stats)\n{\n\tfor (std::list<MeshCuboidFeatures *>::iterator it = _stats.begin(); it != _stats.end(); ++it)\n\t\tdelete (*it);\n\t_stats.clear();\n\n\tstd::ifstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't load file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tstd::string buffer;\n\tstd::stringstream strstr;\n\tstd::string token;\n\tbool succeded = true;\n\n\twhile (!file.eof())\n\t{\n\t\tstd::getline(file, buffer);\n\t\tif (buffer == \"\") break;\n\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tMeshCuboidFeatures *new_features = new MeshCuboidFeatures();\n\t\tassert(new_features);\n\n\t\tfor (int feature_index = 0; feature_index < MeshCuboidFeatures::k_num_features; ++feature_index)\n\t\t{\n\t\t\tstd::getline(strstr, token, ',');\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\tsucceded = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (token == \"NaN\")\n\t\t\t{\n\t\t\t\t// Note:\n\t\t\t\t// Undefined attributes are recorded as NaN.\n\t\t\t\tnew_features->features_[feature_index] = std::numeric_limits<Real>::quiet_NaN();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnew_features->features_[feature_index] = std::stof(token);\n\t\t\t}\n\t\t}\n\n\t\tif (!succeded) break;\n\t\t_stats.push_back(new_features);\n\t}\n\n\tif (!succeded)\n\t{\n\t\tfor (std::list<MeshCuboidFeatures *>::iterator it = _stats.begin(); it != _stats.end(); ++it)\n\t\t\tdelete (*it);\n\t\t_stats.clear();\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool MeshCuboidFeatures::save_feature_collection(const char* _filename,\n\tconst std::list<MeshCuboidFeatures *>& _stats)\n{\n\tstd::ofstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't save file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\tstd::setprecision(std::numeric_limits<long double>::digits10 + 1);\n\tstd::cout << std::scientific;\n\n\t//unsigned int num_objects = _stats.size();\n\n\t// Write attribute values.\n\tunsigned int object_index = 0;\n\tfor (std::list<MeshCuboidFeatures *>::const_iterator stat_it = _stats.begin(); stat_it != _stats.end();\n\t\t++stat_it, ++object_index)\n\t{\n\t\tassert(*stat_it);\n\n\t\tfor (int feature_index = 0; feature_index < MeshCuboidFeatures::k_num_features; ++feature_index)\n\t\t{\n\t\t\tReal value = (*stat_it)->features_[feature_index];\n\t\t\tif (std::isnan(value))\n\t\t\t{\n\t\t\t\t// Note:\n\t\t\t\t// Undefined attributes are recorded as NaN.\n\t\t\t\tfile << \"NaN,\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfile << value << \",\";\n\t\t\t}\n\t\t}\n\t\tfile << std::endl;\n\t}\n\n\tfile.close();\n\treturn true;\n}\n\nMeshCuboidTransformation::MeshCuboidTransformation()\n: object_name_(\"\")\n{\n\tinitialize();\n}\n\nMeshCuboidTransformation::MeshCuboidTransformation(const std::string _object_name)\n: object_name_(_object_name)\n{\n\tinitialize();\n}\n\nMeshCuboidTransformation::~MeshCuboidTransformation()\n{\n}\n\nvoid MeshCuboidTransformation::initialize()\n{\n\tfirst_translation_ = Eigen::Vector3d::Zero();\n\tsecond_rotation_ = Eigen::Matrix3d::Identity();\n}\n\nvoid MeshCuboidTransformation::compute_transformation(const MeshCuboid *_cuboid)\n{\n\tassert(_cuboid);\n\n\tfor (unsigned int axis_index = 0; axis_index < 3; ++axis_index)\n\t{\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tsecond_rotation_.row(axis_index)(i) = _cuboid->get_bbox_axis(axis_index)[i];\n\t\t}\n\t\tfirst_translation_(axis_index) = -_cuboid->get_bbox_center()[axis_index];\n\t};\n}\n\nEigen::VectorXd\nMeshCuboidTransformation::get_transformed_features(\nconst MeshCuboidFeatures& _other_features)const\n{\n\tEigen::VectorXd transformed_features = _other_features.get_features();\n\n\tfor (unsigned int i = 0; i < MeshCuboidFeatures::k_num_local_points; ++i)\n\t{\n\t\tEigen::VectorXd sub_values = transformed_features.block(3 * i, 0, 3, 1);\n\t\tsub_values = first_translation_ + sub_values;\n\t\tsub_values = second_rotation_ * sub_values;\n\t\ttransformed_features.block(3 * i, 0, 3, 1) = sub_values;\n\t}\n\n//#ifdef DEBUG_TEST\n//\tEigen::MatrixXd rotation;\n//\tEigen::MatrixXd translation;\n//\tget_linear_map_transformation(rotation, translation);\n//\tEigen::VectorXd same_transformed_features = rotation * (translation * _other_features.get_features());\n//\n//\tassert(same_transformed_features.rows() == MeshCuboidFeatures::k_num_features);\n//\tReal error = (same_transformed_features - transformed_features).array().abs().sum();\n//\n//\tCHECK_NUMERICAL_ERROR(__FUNCTION__, error);\n//#endif\n\n\treturn transformed_features;\n}\n\nEigen::VectorXd\nMeshCuboidTransformation::get_transformed_features(const MeshCuboid *_other_cuboid)const\n{\n\tassert(_other_cuboid);\n\n\tMeshCuboidFeatures other_features;\n\tother_features.compute_features(_other_cuboid);\n\n\treturn get_transformed_features(other_features);\n}\n\nEigen::VectorXd\nMeshCuboidTransformation::get_inverse_transformed_features(\n\tconst MeshCuboidFeatures& _other_features)const\n{\n\tEigen::VectorXd inverse_transformed_features = _other_features.get_features();\n\n\tfor (unsigned int i = 0; i < MeshCuboidFeatures::k_num_local_points; ++i)\n\t{\n\t\tEigen::VectorXd sub_values = inverse_transformed_features.block(3 * i, 0, 3, 1);\n\t\tsub_values = second_rotation_.transpose() * sub_values;\n\t\tsub_values = -first_translation_ + sub_values;\n\t\tinverse_transformed_features.block(3 * i, 0, 3, 1) = sub_values;\n\t}\n\n//#ifdef DEBUG_TEST\n//\tEigen::MatrixXd rotation;\n//\tEigen::MatrixXd translation;\n//\tget_linear_map_inverse_transformation(rotation, translation);\n//\tEigen::VectorXd same_transformed_features = rotation * (translation * _other_features.get_features());\n//\n//\tassert(same_transformed_features.rows() == MeshCuboidFeatures::k_num_features);\n//\tReal error = (same_transformed_features - inverse_transformed_features).array().abs().sum();\n//\n//\tCHECK_NUMERICAL_ERROR(__FUNCTION__, error);\n//#endif\n\n\treturn inverse_transformed_features;\n}\n\nEigen::VectorXd\nMeshCuboidTransformation::get_inverse_transformed_features(const MeshCuboid *_other_cuboid)const\n{\n\tassert(_other_cuboid);\n\n\tMeshCuboidFeatures other_features;\n\tother_features.compute_features(_other_cuboid);\n\n\treturn get_inverse_transformed_features(other_features);\n}\n\nvoid MeshCuboidTransformation::get_transformation(\n\tEigen::Matrix3d &_rotation, Eigen::Vector3d &_translation) const\n{\n\t_rotation = second_rotation_;\n\t_translation = first_translation_;\n\t_translation = _rotation * _translation;\n}\n\nvoid MeshCuboidTransformation::get_inverse_transformation(\n\tEigen::Matrix3d &_rotation, Eigen::Vector3d &_translation) const\n{\n\t_rotation = second_rotation_.transpose();\n\t_translation = -first_translation_;\n}\n\nvoid MeshCuboidTransformation::get_linear_map_transformation(\n\tEigen::MatrixXd &_rotation, Eigen::MatrixXd &_translation) const\n{\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\t_rotation = Eigen::MatrixXd::Identity(num_features, num_features);\n\t_translation = Eigen::MatrixXd::Zero(num_features, MeshCuboidAttributes::k_num_attributes);\n\n\tfor (unsigned int k = 0; k < MeshCuboidFeatures::k_num_local_points; ++k)\n\t{\n\t\t_rotation.block<3, 3>(3 * k, 3 * k) = second_rotation_;\n\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t{\n\t\t\t//_translation(3 * k + i, MeshCuboidAttributes::k_center_index + i) = -1;\n\t\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t\t{\n\t\t\t\t_translation(3 * k + i, MeshCuboidAttributes::k_corner_index + 3 * corner_index + i) =\n\t\t\t\t\t-1.0 / MeshCuboid::k_num_corners;\n\t\t\t}\n\t\t}\n\t}\n\n\t_translation = _rotation * _translation;\n}\n\nvoid MeshCuboidTransformation::get_linear_map_inverse_transformation(\n\tEigen::MatrixXd &_rotation, Eigen::MatrixXd &_translation) const\n{\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\t_rotation = Eigen::MatrixXd::Identity(num_features, num_features);\n\t_translation = Eigen::MatrixXd::Zero(num_features, MeshCuboidAttributes::k_num_attributes);\n\n\tfor (unsigned int k = 0; k < MeshCuboidFeatures::k_num_local_points; ++k)\n\t{\n\t\t_rotation.block<3, 3>(3 * k, 3 * k) = second_rotation_.transpose();\n\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t{\n\t\t\t//_translation(3 * k + i, MeshCuboidAttributes::k_center_index + i) = 1;\n\t\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t\t{\n\t\t\t\t_translation(3 * k + i, MeshCuboidAttributes::k_corner_index + 3 * corner_index + i) =\n\t\t\t\t\t1.0 / MeshCuboid::k_num_corners;\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool MeshCuboidTransformation::load_transformation_collection(const char* _filename,\n\tstd::list<MeshCuboidTransformation *>& _stats)\n{\n\tfor (std::list<MeshCuboidTransformation *>::iterator it = _stats.begin(); it != _stats.end(); ++it)\n\t\tdelete (*it);\n\t_stats.clear();\n\n\tstd::ifstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't load file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tstd::string buffer;\n\tstd::stringstream strstr;\n\tstd::string token;\n\tbool succeded = true;\n\n\twhile (!file.eof())\n\t{\n\t\tstd::getline(file, buffer);\n\t\tif (buffer == \"\") break;\n\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tMeshCuboidTransformation *new_transformation = new MeshCuboidTransformation();\n\t\tassert(new_transformation);\n\n\t\tfor (unsigned int axis_index = 0; axis_index < 3; ++axis_index)\n\t\t{\n\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\tstd::getline(strstr, token, ',');\n\t\t\t\tif (strstr.eof())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\t\tsucceded = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (!succeded) break;\n\t\t\t\tnew_transformation->second_rotation_.col(axis_index)(i) = std::stof(token);\n\t\t\t}\n\t\t}\n\n\t\tfor (unsigned int axis_index = 0; axis_index < 3; ++axis_index)\n\t\t{\n\t\t\tstd::getline(strstr, token, ',');\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\tsucceded = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tnew_transformation->first_translation_(axis_index) = std::stof(token);\n\t\t}\n\n\t\tif (!succeded) break;\n\t\t_stats.push_back(new_transformation);\n\t}\n\n\tif (!succeded)\n\t{\n\t\tfor (std::list<MeshCuboidTransformation *>::iterator it = _stats.begin(); it != _stats.end(); ++it)\n\t\t\tdelete (*it);\n\t\t_stats.clear();\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool MeshCuboidTransformation::save_transformation_collection(const char* _filename,\n\tconst std::list<MeshCuboidTransformation *>& _stats)\n{\n\tstd::ofstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't save file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\tstd::setprecision(std::numeric_limits<long double>::digits10 + 1);\n\tstd::cout << std::scientific;\n\n\t//unsigned int num_objects = _stats.size();\n\n\t// Write attribute values.\n\tunsigned int object_index = 0;\n\tfor (std::list<MeshCuboidTransformation *>::const_iterator stat_it = _stats.begin(); stat_it != _stats.end();\n\t\t++stat_it, ++object_index)\n\t{\n\t\tassert(*stat_it);\n\n\t\tfor (unsigned int axis_index = 0; axis_index < 3; ++axis_index)\n\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t\tfile << (*stat_it)->second_rotation_.col(axis_index)(i) << \",\";\n\n\t\tfor (unsigned int axis_index = 0; axis_index < 3; ++axis_index)\n\t\t\tfile << (*stat_it)->first_translation_(axis_index) << \",\";\n\n\t\tfile << std::endl;\n\t}\n\n\tfile.close();\n\treturn true;\n}\n\nMeshCuboidJointNormalRelations::MeshCuboidJointNormalRelations()\n{\n\tmean_ = Eigen::VectorXd::Zero(k_mat_size);\n\tinv_cov_ = Eigen::MatrixXd::Zero(k_mat_size, k_mat_size);\n}\n\nMeshCuboidJointNormalRelations::~MeshCuboidJointNormalRelations()\n{\n\n}\n\nbool MeshCuboidJointNormalRelations::load_joint_normal_csv(const char* _filename)\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \", \", \"\", \"\", \"\", \"\", \"\");\n\n\tstd::ifstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't open file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tstd::string buffer;\n\tstd::stringstream strstr;\n\tstd::string token;\n\n\tstd::getline(file, buffer);\n\tstrstr.str(std::string());\n\tstrstr.clear();\n\tstrstr.str(buffer);\n\n\tfor (int j = 0; j < k_mat_size; ++j)\n\t{\n\t\tif (strstr.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(strstr, token, ',');\n\n\t\t// Transposed.\n\t\tmean_(j) = std::stof(token);\n\t}\n\n\tfor (int i = 0; i < k_mat_size; ++i)\n\t{\n\t\tif (file.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(file, buffer);\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tfor (int j = 0; j < k_mat_size; ++j)\n\t\t{\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstd::getline(strstr, token, ',');\n\t\t\tinv_cov_(i, j) = std::stof(token);\n\t\t}\n\t}\n\n\tfile.close();\n\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(inv_cov_);\n\tReal min_eigenvalue = es.eigenvalues().minCoeff();\n\tif (min_eigenvalue < -1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not positive-semidefinite: (\"\n\t\t\t<< _filename << \" = \" << min_eigenvalue << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\tReal symmetry_diff = (inv_cov_ - inv_cov_.transpose()).array().abs().sum();\n\tif (symmetry_diff > 1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not symmetric: (\"\n\t\t\t<< _filename << \" = \" << symmetry_diff << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\treturn true;\n}\n\nbool MeshCuboidJointNormalRelations::save_joint_normal_csv(const char* _filename)const\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\n\tstd::ofstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't save file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\tstd::setprecision(std::numeric_limits<long double>::digits10 + 1);\n\tstd::cout << std::scientific;\n\n\tfile << mean_.transpose().format(csv_format) << std::endl;\n\tfile << inv_cov_.format(csv_format) << std::endl;\n\n\tfile.close();\n\treturn true;\n}\n\nbool MeshCuboidJointNormalRelations::load_joint_normal_dat(const char* _filename)\n{\n\tstd::ifstream file(_filename, std::ios::in | std::ios::binary);\n\tif (!file.good())\n\t{\n\t\tstd::cerr << \"Can't open file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tint16_t rows, cols;\n\n\trows = 0, cols = 0;\n\tfile.read((char*)(&rows), sizeof(int16_t));\n\tfile.read((char*)(&cols), sizeof(int16_t));\n\tassert(static_cast<int>(rows) == k_mat_size);\n\tassert(static_cast<int>(cols) == 1);\n\tmean_.resize(rows);\n\tfile.read((char *)mean_.data(), rows*cols*sizeof(Eigen::MatrixXd::Scalar));\n\t\n\trows = 0, cols = 0;\n\tfile.read((char*)(&rows), sizeof(int16_t));\n\tfile.read((char*)(&cols), sizeof(int16_t));\n\tassert(static_cast<int>(rows) == k_mat_size);\n\tassert(static_cast<int>(cols) == k_mat_size);\n\tinv_cov_.resize(rows, cols);\n\tfile.read((char *)inv_cov_.data(), rows*cols*sizeof(Eigen::MatrixXd::Scalar));\n\n\tfile.close();\n\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(inv_cov_);\n\tReal min_eigenvalue = es.eigenvalues().minCoeff();\n\tif (min_eigenvalue < -1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not positive-semidefinite: (\"\n\t\t\t<< _filename << \" = \" << min_eigenvalue << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\tReal symmetry_diff = (inv_cov_ - inv_cov_.transpose()).array().abs().sum();\n\tif (symmetry_diff > 1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not symmetric: (\"\n\t\t\t<< _filename << \" = \" << symmetry_diff << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\treturn true;\n}\n\nvoid MeshCuboidJointNormalRelations::get_pairwise_cuboid_features(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tEigen::VectorXd &_pairwise_features_vec)\n{\n\tassert(_cuboid_1);\n\tassert(_cuboid_2);\n\n\tMeshCuboidFeatures features_1;\n\tfeatures_1.compute_features(_cuboid_1);\n\n\tMeshCuboidFeatures features_2;\n\tfeatures_2.compute_features(_cuboid_2);\n\n\tget_pairwise_cuboid_features(features_1, features_2,\n\t\t_transformation_1, _transformation_2, _pairwise_features_vec);\n}\n\nvoid MeshCuboidJointNormalRelations::get_pairwise_cuboid_features(\n\tconst MeshCuboidFeatures &_features_1, const MeshCuboidFeatures &_features_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tEigen::VectorXd &_pairwise_features_vec)\n{\n\tassert(_transformation_1);\n\tassert(_transformation_2);\n\n\tEigen::VectorXd transformed_features_vec_11 = _transformation_1->get_transformed_features(_features_1);\n\tassert(std::abs(transformed_features_vec_11[0]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(std::abs(transformed_features_vec_11[1]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(std::abs(transformed_features_vec_11[2]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(transformed_features_vec_11.rows() == MeshCuboidFeatures::k_num_features);\n\n\tEigen::VectorXd transformed_features_vec_12 = _transformation_1->get_transformed_features(_features_2);\n\tassert(transformed_features_vec_12.rows() == MeshCuboidFeatures::k_num_features);\n\n\n\tEigen::VectorXd transformed_features_vec_22 = _transformation_2->get_transformed_features(_features_2);\n\tassert(std::abs(transformed_features_vec_22[0]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(std::abs(transformed_features_vec_22[1]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(std::abs(transformed_features_vec_22[2]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(transformed_features_vec_22.rows() == MeshCuboidFeatures::k_num_features);\n\n\tEigen::VectorXd transformed_features_vec_21 = _transformation_2->get_transformed_features(_features_1);\n\tassert(transformed_features_vec_21.rows() == MeshCuboidFeatures::k_num_features);\n\n\n\t// NOTE:\n\t// Since the center point is always the origin in the local coordinates,\n\t// it is not used as the feature values.\n\tassert(k_mat_size == 2 * (2 * MeshCuboidFeatures::k_num_features - MeshCuboidFeatures::k_corner_index));\n\t_pairwise_features_vec.resize(k_mat_size);\n\t_pairwise_features_vec <<\n\t\ttransformed_features_vec_11.bottomRows(MeshCuboidFeatures::k_num_features - MeshCuboidFeatures::k_corner_index),\n\t\ttransformed_features_vec_12,\n\t\ttransformed_features_vec_22.bottomRows(MeshCuboidFeatures::k_num_features - MeshCuboidFeatures::k_corner_index),\n\t\ttransformed_features_vec_21;\n}\n\ndouble MeshCuboidJointNormalRelations::compute_error(const MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2) const\n{\n\tEigen::VectorXd pairwise_cuboid_feature;\n\tget_pairwise_cuboid_features(_cuboid_1, _cuboid_2, _transformation_1, _transformation_2,\n\t\tpairwise_cuboid_feature);\n\n\tassert(mean_.rows() == pairwise_cuboid_feature.rows());\n\tassert(inv_cov_.rows() == pairwise_cuboid_feature.rows());\n\tassert(inv_cov_.cols() == pairwise_cuboid_feature.rows());\n\n\tEigen::VectorXd diff = pairwise_cuboid_feature - mean_;\n\n\t// Mahalanobis norm.\n\tdouble error = diff.transpose() * inv_cov_ * diff;\n\tassert(error >= 0);\n\n\t//std::cerr << \"Negative error value (error = \" << error << \")\" << std::endl;\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\n\t//Real inv_cov_det = inv_cov_.determinant();\n\t//std::cout << \"inv_cov_det = \" << inv_cov_det << std::endl;\n\n\t//Real symmetry_diff = (inv_cov_ - inv_cov_.transpose()).array().abs().sum();\n\t//std::cerr << \"symmetry_diff = \" << symmetry_diff << std::endl;\n\n\t//std::cout << \"Norm(diff) = \" << diff.transpose() * diff << std::endl;\n\n\t//std::cout << \"diff = \" << std::endl;\n\t//std::cout << diff.format(csv_format) << std::endl;\n\n\t//do {\n\t//\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t//} while (std::cin.get() != '\\n');\n\n\treturn error;\n}\n\ndouble MeshCuboidJointNormalRelations::compute_conditional_error(const MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidTransformation *_transformation_1) const\n{\n\tEigen::VectorXd conditional_pairwise_cuboid_feature;\n\tassert(_transformation_1);\n\n\tMeshCuboidFeatures features_1;\n\tfeatures_1.compute_features(_cuboid_1);\n\n\tMeshCuboidFeatures features_2;\n\tfeatures_2.compute_features(_cuboid_2);\n\n\tEigen::VectorXd transformed_features_vec_11 = _transformation_1->get_transformed_features(features_1);\n\tassert(std::abs(transformed_features_vec_11[0]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(std::abs(transformed_features_vec_11[1]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(std::abs(transformed_features_vec_11[2]) < NUMERIAL_ERROR_THRESHOLD);\n\tassert(transformed_features_vec_11.rows() == MeshCuboidFeatures::k_num_features);\n\n\tEigen::VectorXd transformed_features_vec_12 = _transformation_1->get_transformed_features(features_2);\n\tassert(transformed_features_vec_12.rows() == MeshCuboidFeatures::k_num_features);\n\n\t// NOTE:\n\t// Since the center point is always the origin in the local coordinates,\n\t// it is not used as the feature values.\n\tconst int num_rows = 2 * MeshCuboidFeatures::k_num_features - MeshCuboidFeatures::k_corner_index;\n\tconditional_pairwise_cuboid_feature.resize(num_rows);\n\tconditional_pairwise_cuboid_feature <<\n\t\ttransformed_features_vec_11.bottomRows(MeshCuboidFeatures::k_num_features - MeshCuboidFeatures::k_corner_index),\n\t\ttransformed_features_vec_12;\n\n\tEigen::VectorXd conditional_mean = mean_.segment(0, num_rows);\n\tEigen::MatrixXd conditional_inv_cov = inv_cov_.block(0, 0, num_rows, num_rows);\n\tEigen::VectorXd diff = conditional_pairwise_cuboid_feature - conditional_mean;\n\n\t// Mahalanobis norm.\n\tdouble error = diff.transpose() * conditional_inv_cov * diff;\n\tassert(error >= 0);\n\n\treturn error;\n}\n\nMeshCuboidCondNormalRelations::MeshCuboidCondNormalRelations()\n{\n\tassert(MeshCuboidFeatures::k_num_global_feature_values > 0);\n\n\tmean_A_ = Eigen::MatrixXd::Zero(MeshCuboidFeatures::k_num_features, MeshCuboidFeatures::k_num_global_feature_values);\n\tmean_b_ = Eigen::VectorXd::Zero(MeshCuboidFeatures::k_num_features);\n\tinv_cov_ = Eigen::MatrixXd::Zero(MeshCuboidFeatures::k_num_features, MeshCuboidFeatures::k_num_features);\n}\n\nMeshCuboidCondNormalRelations::~MeshCuboidCondNormalRelations()\n{\n\n}\n\nbool MeshCuboidCondNormalRelations::load_cond_normal_csv(const char* _filename)\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \", \", \"\", \"\", \"\", \"\", \"\");\n\n\tstd::ifstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't open file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tstd::string buffer;\n\tstd::stringstream strstr;\n\tstd::string token;\n\n\tfor (int i = 0; i < MeshCuboidFeatures::k_num_global_feature_values; ++i)\n\t{\n\t\tif (file.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(file, buffer);\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t\t{\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstd::getline(strstr, token, ',');\n\n\t\t\t// Transposed.\n\t\t\tmean_A_(j, i) = std::stof(token);\n\t\t}\n\t}\n\n\tstd::getline(file, buffer);\n\tstrstr.str(std::string());\n\tstrstr.clear();\n\tstrstr.str(buffer);\n\n\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t{\n\t\tif (strstr.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(strstr, token, ',');\n\n\t\t// Transposed.\n\t\tmean_b_(j) = std::stof(token);\n\t}\n\n\tfor (int i = 0; i < MeshCuboidFeatures::k_num_features; ++i)\n\t{\n\t\tif (file.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(file, buffer);\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t\t{\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstd::getline(strstr, token, ',');\n\t\t\tinv_cov_(i, j) = std::stof(token);\n\t\t}\n\t}\n\n\tfile.close();\n\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(inv_cov_);\n\tReal min_eigenvalue = es.eigenvalues().minCoeff();\n\tif (min_eigenvalue < -1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not positive-semidefinite: (\"\n\t\t\t<< _filename << \" = \" << min_eigenvalue << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\tReal symmetry_diff = (inv_cov_ - inv_cov_.transpose()).array().abs().sum();\n\tif (symmetry_diff > 1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not symmetric: (\"\n\t\t\t<< _filename << \" = \" << symmetry_diff << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\treturn true;\n}\n\nbool MeshCuboidCondNormalRelations::save_cond_normal_csv(const char* _filename)const\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\n\tstd::ofstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't save file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\tstd::setprecision(std::numeric_limits<long double>::digits10 + 1);\n\tstd::cout << std::scientific;\n\n\t// NOTE:\n\t// mean_A_. mean_b_: Transposed.\n\tfile << mean_A_.transpose().format(csv_format) << std::endl;\n\tfile << mean_b_.transpose().format(csv_format) << std::endl;\n\tfile << inv_cov_.format(csv_format) << std::endl;\n\n\tfile.close();\n\treturn true;\n}\n\nbool MeshCuboidCondNormalRelations::load_cond_normal_dat(const char* _filename)\n{\n\tstd::ifstream file(_filename, std::ios::in | std::ios::binary);\n\tif (!file.good())\n\t{\n\t\tstd::cerr << \"Can't open file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tint16_t rows, cols;\n\n\trows = 0, cols = 0;\n\tfile.read((char*)(&rows), sizeof(int16_t));\n\tfile.read((char*)(&cols), sizeof(int16_t));\n\tassert(static_cast<int>(rows) == MeshCuboidFeatures::k_num_features);\n\tassert(static_cast<int>(cols) == MeshCuboidFeatures::k_num_global_feature_values);\n\tmean_A_.resize(rows, cols);\n\tfile.read((char *)mean_A_.data(), rows*cols*sizeof(Eigen::MatrixXd::Scalar));\n\n\n\trows = 0, cols = 0;\n\tfile.read((char*)(&rows), sizeof(int16_t));\n\tfile.read((char*)(&cols), sizeof(int16_t));\n\tassert(static_cast<int>(rows) == MeshCuboidFeatures::k_num_features);\n\tassert(static_cast<int>(cols) == 1);\n\tmean_b_.resize(rows);\n\tfile.read((char *)mean_b_.data(), rows*cols*sizeof(Eigen::MatrixXd::Scalar));\n\n\n\trows = 0, cols = 0;\n\tfile.read((char*)(&rows), sizeof(int16_t));\n\tfile.read((char*)(&cols), sizeof(int16_t));\n\tassert(static_cast<int>(rows) == MeshCuboidFeatures::k_num_features);\n\tassert(static_cast<int>(cols) == MeshCuboidFeatures::k_num_features);\n\tinv_cov_.resize(rows, cols);\n\tfile.read((char *)inv_cov_.data(), rows*cols*sizeof(Eigen::MatrixXd::Scalar));\n\n\tfile.close();\n\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(inv_cov_);\n\tReal min_eigenvalue = es.eigenvalues().minCoeff();\n\tif (min_eigenvalue < -1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not positive-semidefinite: (\"\n\t\t\t<< _filename << \" = \" << min_eigenvalue << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\tReal symmetry_diff = (inv_cov_ - inv_cov_.transpose()).array().abs().sum();\n\tif (symmetry_diff > 1.0E-6)\n\t{\n\t\tstd::cerr << \"Error: The inverse covariance matrix is not symmetric: (\"\n\t\t\t<< _filename << \" = \" << symmetry_diff << \")\" << std::endl;\n\t\tdo {\n\t\t\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t\t} while (std::cin.get() != '\\n');\n\t}\n\n\treturn true;\n}\n\nvoid MeshCuboidCondNormalRelations::get_pairwise_cuboid_features(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tEigen::VectorXd &_global_features_vec_1, Eigen::VectorXd &_transformed_features_vec_12)\n{\n\tassert(_cuboid_1);\n\tassert(_cuboid_2);\n\n\tMeshCuboidFeatures features_1;\n\tfeatures_1.compute_features(_cuboid_1);\n\n\tMeshCuboidFeatures features_2;\n\tfeatures_2.compute_features(_cuboid_2);\n\n\tget_pairwise_cuboid_features(features_1, features_2,\n\t\t_transformation_1, _transformation_2,\n\t\t_global_features_vec_1, _transformed_features_vec_12);\n}\n\nvoid MeshCuboidCondNormalRelations::get_pairwise_cuboid_features(\n\tconst MeshCuboidFeatures &_features_1, const MeshCuboidFeatures &_features_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tEigen::VectorXd &_global_features_vec_1, Eigen::VectorXd &_transformed_features_vec_12)\n{\n\tassert(_transformation_1);\n\tassert(_transformation_2);\n\n\tEigen::VectorXd features_vec_1 = _features_1.get_features();\n\tassert(features_vec_1.rows() == MeshCuboidFeatures::k_num_features);\n\n\t_transformed_features_vec_12 = _transformation_1->get_transformed_features(_features_2);\n\tassert(_transformed_features_vec_12.rows() == MeshCuboidFeatures::k_num_features);\n\n\t_global_features_vec_1 = features_vec_1.bottomRows(MeshCuboidFeatures::k_num_global_feature_values);\n}\n\ndouble MeshCuboidCondNormalRelations::compute_error(const MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2)const\n{\n\tEigen::VectorXd global_features_vec_1, transformed_features_vec_12;\n\tget_pairwise_cuboid_features(_cuboid_1, _cuboid_2, _transformation_1, _transformation_2,\n\t\tglobal_features_vec_1, transformed_features_vec_12);\n\n\tassert(mean_A_.rows() == transformed_features_vec_12.rows());\n\tassert(mean_A_.cols() == global_features_vec_1.rows());\n\tassert(mean_b_.rows() == transformed_features_vec_12.rows());\n\tassert(inv_cov_.rows() == transformed_features_vec_12.rows());\n\tassert(inv_cov_.cols() == transformed_features_vec_12.rows());\n\n\tconst Eigen::VectorXd mean_2 = mean_A_ * global_features_vec_1 + mean_b_;\n\tEigen::VectorXd diff = transformed_features_vec_12 - mean_2;\n\n\t// Mahalanobis norm.\n\tdouble error = diff.transpose() * inv_cov_ * diff;\n\tassert(error >= 0);\n\n\t//std::cerr << \"Negative error value (error = \" << error << \")\" << std::endl;\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\n\t//Real inv_cov_det = inv_cov_.determinant();\n\t//std::cout << \"inv_cov_det = \" << inv_cov_det << std::endl;\n\n\t//std::cout << \"Norm(diff) = \" << diff.transpose() * diff << std::endl;\n\n\t//std::cout << \"diff = \" << std::endl;\n\t//std::cout << diff.format(csv_format) << std::endl;\n\n\t//do {\n\t//\tstd::cout << '\\n' << \"Press the Enter key to continue.\";\n\t//} while (std::cin.get() != '\\n');\n\n\treturn error;\n}\n\n/*\nMeshCuboidPCARelations::MeshCuboidPCARelations()\n{\n\tmean_ = Eigen::VectorXd::Zero(k_mat_size);\n\tpca_bases_ = Eigen::MatrixXd::Zero(k_mat_size, k_mat_size);\n}\n\nMeshCuboidPCARelations::~MeshCuboidPCARelations()\n{\n\n}\n\nbool MeshCuboidPCARelations::load_pca_csv(const char* _filename)\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \", \", \"\", \"\", \"\", \"\", \"\");\n\n\tstd::ifstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't open file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tstd::string buffer;\n\tstd::stringstream strstr;\n\tstd::string token;\n\n\tstd::getline(file, buffer);\n\tstrstr.str(std::string());\n\tstrstr.clear();\n\tstrstr.str(buffer);\n\n\tfor (int j = 0; j < k_mat_size; ++j)\n\t{\n\t\tif (strstr.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(strstr, token, ',');\n\t\tmean_(j) = std::stof(token);\n\t}\n\n\tfor (int i = 0; i < k_mat_size; ++i)\n\t{\n\t\tif (file.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(file, buffer);\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tfor (int j = 0; j < k_mat_size; ++j)\n\t\t{\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstd::getline(strstr, token, ',');\n\t\t\tpca_bases_(i, j) = std::stof(token);\n\t\t}\n\t}\n\n\tfile.close();\n\n\treturn true;\n}\n\nbool MeshCuboidPCARelations::save_pca_csv(const char* _filename)const\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\n\tstd::ofstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't save file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\tstd::setprecision(std::numeric_limits<long double>::digits10 + 1);\n\tstd::cout << std::scientific;\n\n\tfile << mean_.transpose().format(csv_format) << std::endl;\n\tfile << pca_bases_.format(csv_format) << std::endl;\n\n\tfile.close();\n\treturn true;\n}\n\ndouble MeshCuboidPCARelations::compute_error(\n\tconst Eigen::VectorXd &_features_vec_1, const Eigen::VectorXd &_features_vec_2) const\n{\n\tassert(_features_vec_1.rows() == MeshCuboidFeatures::k_num_features);\n\tassert(_features_vec_2.rows() == MeshCuboidFeatures::k_num_features);\n\n\tEigen::VectorXd concat_features(2 * MeshCuboidFeatures::k_num_features);\n\tconcat_features << _features_vec_1, _features_vec_2;\n\tassert(mean_.rows() == concat_features.rows());\n\tassert(pca_bases_.rows() == concat_features.rows());\n\tassert(pca_bases_.cols() == concat_features.rows());\n\n\tEigen::VectorXd diff = concat_features - mean_;\n\tdiff = diff - (pca_bases_ * diff);\n\n\tdouble error = diff.transpose() * diff;\n\treturn error;\n}\n\nMeshCuboidCCARelations::MeshCuboidCCARelations()\n{\n\tmean_1_ = Eigen::VectorXd::Zero(MeshCuboidFeatures::k_num_features);\n\tmean_2_ = Eigen::VectorXd::Zero(MeshCuboidFeatures::k_num_features);\n\tcorrelations_ = Eigen::VectorXd::Zero(MeshCuboidFeatures::k_num_features);\n\tbases_12_ = Eigen::MatrixXd::Zero(MeshCuboidFeatures::k_num_features, MeshCuboidFeatures::k_num_features);\n\tbases_21_ = Eigen::MatrixXd::Zero(MeshCuboidFeatures::k_num_features, MeshCuboidFeatures::k_num_features);\n}\n\nMeshCuboidCCARelations::~MeshCuboidCCARelations()\n{\n\n}\n\nbool MeshCuboidCCARelations::load_cca_bases(const char* _filename)\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\n\tstd::ifstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't open file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\n\tstd::string buffer;\n\tstd::stringstream strstr;\n\tstd::string token;\n\n\tstd::getline(file, buffer);\n\tstrstr.str(std::string());\n\tstrstr.clear();\n\tstrstr.str(buffer);\n\n\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t{\n\t\tif (strstr.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(strstr, token, ',');\n\t\tmean_1_(j) = std::stof(token);\n\t}\n\n\tstd::getline(file, buffer);\n\tstrstr.str(std::string());\n\tstrstr.clear();\n\tstrstr.str(buffer);\n\n\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t{\n\t\tif (strstr.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(strstr, token, ',');\n\t\tmean_2_(j) = std::stof(token);\n\t}\n\n\tstd::getline(file, buffer);\n\tstrstr.str(std::string());\n\tstrstr.clear();\n\tstrstr.str(buffer);\n\n\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t{\n\t\tif (strstr.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(strstr, token, ',');\n\t\tcorrelations_(j) = std::stof(token);\n\t}\n\n\tfor (int i = 0; i < MeshCuboidFeatures::k_num_features; ++i)\n\t{\n\t\tif (file.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(file, buffer);\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t\t{\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstd::getline(strstr, token, ',');\n\t\t\tbases_12_(i, j) = std::stof(token);\n\t\t}\n\t}\n\n\tfor (int i = 0; i < MeshCuboidFeatures::k_num_features; ++i)\n\t{\n\t\tif (file.eof())\n\t\t{\n\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::getline(file, buffer);\n\t\tstrstr.str(std::string());\n\t\tstrstr.clear();\n\t\tstrstr.str(buffer);\n\n\t\tfor (int j = 0; j < MeshCuboidFeatures::k_num_features; ++j)\n\t\t{\n\t\t\tif (strstr.eof())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Wrong file format: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tstd::getline(strstr, token, ',');\n\t\t\tbases_21_(i, j) = std::stof(token);\n\t\t}\n\t}\n\n\tfile.close();\n\treturn true;\n}\n\nbool MeshCuboidCCARelations::save_cca_bases(const char* _filename)const\n{\n\tEigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\n\tstd::ofstream file(_filename);\n\tif (!file)\n\t{\n\t\tstd::cerr << \"Can't save file: \\\"\" << _filename << \"\\\"\" << std::endl;\n\t\treturn false;\n\t}\n\tstd::setprecision(std::numeric_limits<long double>::digits10 + 1);\n\tstd::cout << std::scientific;\n\n\tfile << mean_1_.transpose().format(csv_format) << std::endl;\n\tfile << mean_2_.transpose().format(csv_format) << std::endl;\n\tfile << correlations_.transpose().format(csv_format) << std::endl;\n\tfile << bases_12_.format(csv_format) << std::endl;\n\tfile << bases_21_.format(csv_format) << std::endl;\n\n\n\tfile.close();\n\treturn true;\n}\n\ndouble MeshCuboidCCARelations::compute_error(\n\tconst Eigen::VectorXd &_features_vec_1, const Eigen::VectorXd &_features_vec_2) const\n{\n\tassert(bases_12_.cols() == _features_vec_1.rows());\n\tassert(bases_21_.cols() == _features_vec_2.rows());\n\n\tEigen::VectorXd transformed_attributes_1 = bases_12_ * (_features_vec_1 - mean_1_);\n\tEigen::VectorXd transformed_attributes_2 = bases_21_ * (_features_vec_2 - mean_2_);\n\tEigen::VectorXd diff = transformed_attributes_1 - transformed_attributes_2;\n\n\t// Mahalanobis norm.\n\tdouble error = diff.transpose() * correlations_.asDiagonal() * diff;\n\treturn error;\n}\n*/", "meta": {"hexsha": "77a3bc3295a1ee96da9827f51c5af0f0db18e517", "size": 46139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MeshCuboidRelation.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/MeshCuboidRelation.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/MeshCuboidRelation.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": 29.1465571699, "max_line_length": 122, "alphanum_fraction": 0.7039164265, "num_tokens": 13007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.026355349882714086, "lm_q1q2_score": 0.01215025852057807}}
{"text": "//\n// Created by kobus on 2017/04/06.\n//\n\n#include <opencv2/imgproc.hpp>\n#include <opencv2/photo.hpp>\n#include <list>\n#include <deque>\n#include <iomanip>\n#include <cv.hpp>\n#include \"cpuDsp.h\"\n#include <armadillo>\n//#include <Eigen/Dense>\n//#include <Eigen/Sparse>\n//#include <Eigen/IterativeLinearSolvers>\n//#include <Eigen/SparseLU>\n\nvoid printMat(cv::Mat image)\n{\n    std::cout << \"Mat:\" << std::endl;\n    for (int i = 0; i < image.cols; i++)\n    {\n        std::cout << \"  \" << std::setfill('0') << std::setw(5) << i << \"  \";\n    }\n    std::cout << std::endl;\n\n    for (int i = 0; i < image.rows; i++)\n    {\n        std::cout << \"  \" << std::setfill('0') << std::setw(5) << i << \"  \";\n        for (int j = 0; j < image.cols; j++)\n        {\n            std::cout << (image.at<int>(i, j) & 0xFF) << \" \";\n        }\n        std::cout << std::endl;\n    }\n    std::cout << std::endl;\n}\n\nvoid printMatFloat(cv::Mat image)\n{\n    std::cout << \"Mat:\" << std::endl;\n    for (int i = 0; i < image.cols; i++)\n    {\n        std::cout << \"  \" << std::setfill('0') << std::setw(5) << i << \"  \";\n    }\n    std::cout << std::endl;\n\n    for (int i = 0; i < image.rows; i++)\n    {\n        std::cout << \"  \" << std::setfill('0') << std::setw(5) << i << \"  \";\n        for (int j = 0; j < image.cols; j++)\n        {\n            std::cout << image.at<double>(i, j) << \" \";\n        }\n        std::cout << std::endl;\n    }\n    std::cout << std::endl;\n}\n\nvoid printArray(double array[1280][720])\n{\n    std::cout << \"Mat:\" << std::endl;\n    for (int i = 0; i < 1280; i++)\n    {\n        std::cout << \"  \" << std::setfill('0') << std::setw(5) << i << \"  \";\n    }\n    std::cout << std::endl;\n\n    for (int i = 0; i < 720; i++)\n    {\n        std::cout << \"  \" << std::setfill('0') << std::setw(5) << i << \"  \";\n        for (int j = 0; j < 1280; j++)\n        {\n            std::cout << ((int)(array[i][j])) << \" \";\n        }\n        std::cout << std::endl;\n    }\n    std::cout << std::endl;\n}\n\nvoid cpuDsp::executeTiPipeline(cv::Mat& frame,\n                               cv::Mat& originalFrame,\n                               cv::Mat& nnFrame,\n                               cv::Mat& biqFrame,\n                               cv::Mat& nediFrame,\n                               cv::Mat& bilinearFrame,\n                               TiDspParameters params)\n{\n    static bool showStabilisation = false;\n    static int stabFrame = 0;\n    cv::Mat temp1;\n    cv::Mat temp2;\n\n    cv::cvtColor(frame, frame, CV_BGR2GRAY);\n    originalFrame = frame.clone();\n\n    if (params.outputSelect == OutputSelect::Raw)\n    {\n        frame.copyTo(nnFrame);\n        frame.copyTo(biqFrame);\n        frame.copyTo(nediFrame);\n        frame.copyTo(bilinearFrame);\n        return;\n    }\n\n    //    if (params.eZoomOn)\n//    {\n//        eZoom(frame, params);\n//        if (showComparisonWindows)\n//        {\n//            eZoom(originalFrame, params);\n//        }\n//    }\n//    if (params.outputSelect == OutputSelect::Ezoom)\n//        frame.copyTo(outputFrame);\n\n    if (params.downScaleOn)\n    {\n        if (params.ezoom == Ezoom::x2)\n        {\n            cv::pyrDown(frame, frame, cv::Size(frame.cols / 2, frame.rows / 2));\n        }\n        else if (params.ezoom == Ezoom::x4)\n        {\n            cv::pyrDown(frame, frame, cv::Size(frame.cols / 2, frame.rows / 2));\n            cv::pyrDown(frame, frame, cv::Size(frame.cols / 2, frame.rows / 2));\n        }\n        else if (params.ezoom == Ezoom::x8)\n        {\n            cv::pyrDown(frame, frame, cv::Size(frame.cols / 2, frame.rows / 2));\n            cv::pyrDown(frame, frame, cv::Size(frame.cols / 2, frame.rows / 2));\n            cv::pyrDown(frame, frame, cv::Size(frame.cols / 2, frame.rows / 2));\n        }\n    }\n    if (params.outputSelect == OutputSelect::Downscale)\n    {\n        frame.copyTo(nnFrame);\n        frame.copyTo(biqFrame);\n        frame.copyTo(nediFrame);\n        frame.copyTo(bilinearFrame);\n        return;\n    }\n\n    if (params.upscaleOn)\n    {\n        if (params.ezoom == Ezoom::NoZoom)\n        {\n            frame.copyTo(nnFrame);\n            frame.copyTo(biqFrame);\n            frame.copyTo(nediFrame);\n            frame.copyTo(bilinearFrame);\n        }\n        else if (params.ezoom == Ezoom::x2)\n        {\n            cv::resize(frame, nnFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_NEAREST);\n\n            cv::resize(frame, biqFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_CUBIC);\n\n            cv::resize(frame, bilinearFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_LINEAR);\n\n            nediUpscale(frame, nediFrame);\n        }\n        else if (params.ezoom == Ezoom::x4)\n        {\n            cv::resize(frame, temp1, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_NEAREST);\n            cv::resize(temp1, nnFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_NEAREST);\n\n            cv::resize(frame, temp1, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_CUBIC);\n            cv::resize(temp1, biqFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_CUBIC);\n\n            cv::resize(frame, temp1, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_LINEAR);\n            cv::resize(temp1, bilinearFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_LINEAR);\n\n            nediUpscale(frame, temp1);\n            nediUpscale(temp1, nediFrame);\n        }\n        else if (params.ezoom == Ezoom::x8)\n        {\n            cv::resize(frame, temp1, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_NEAREST);\n            cv::resize(temp1, temp2, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_NEAREST);\n            cv::resize(temp2, nnFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_NEAREST);\n\n            cv::resize(frame, temp1, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_CUBIC);\n            cv::resize(temp1, temp2, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_CUBIC);\n            cv::resize(temp2, biqFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_CUBIC);\n\n            cv::resize(frame, temp1, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_LINEAR);\n            cv::resize(temp1, temp2, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_LINEAR);\n            cv::resize(temp2, bilinearFrame, cv::Size(originalFrame.cols, originalFrame.rows), 0, 0, cv::INTER_LINEAR);\n\n\n            nediUpscale(frame, temp1);\n            nediUpscale(temp1, temp2);\n            nediUpscale(temp2, nediFrame);\n        }\n    }\n    else\n    {\n        frame.copyTo(nnFrame);\n        frame.copyTo(biqFrame);\n        frame.copyTo(nediFrame);\n        frame.copyTo(bilinearFrame);\n    }\n\n    if (params.outputSelect == OutputSelect::Upscale)\n        return;\n\n    if (params.edgeEnhancementOn)\n    {\n        edgeEnhance(originalFrame, params);\n        edgeEnhance(nnFrame, params);\n        edgeEnhance(biqFrame, params);\n        edgeEnhance(nediFrame, params);\n        edgeEnhance(bilinearFrame, params);\n    }\n    if (params.outputSelect == OutputSelect::EdgeEnhance)\n        return;\n\n\n    return;\n}\n\nvoid cpuDsp::edgeEnhance(cv::Mat& frame, TiDspParameters params)\n{\n    switch (params.edgeEnhanceType)\n    {\n        case EdgeEnhanceType::Sharpen:\n        {\n            cv::Mat kernel = (cv::Mat_<float>(3,3) <<\n                     0,-1, 0,\n                    -1, 5,-1,\n                     0,-1, 0);\n\n            filter2D(frame, frame, CV_32F, kernel);\n        }\n\n        case EdgeEnhanceType::Gaussian:\n        {\n            cv::Mat kernel = (cv::Mat_<float>(5,5) <<\n                    -1,-1,-1,-1,-1,\n                    -1, 2, 2, 2,-1,\n                    -1, 2, 8, 2,-1,\n                    -1, 2, 2, 2,-1,\n                    -1,-1,-1,-1,-1) / 8.0;\n\n            filter2D(frame, frame, CV_32F, kernel);\n            break;\n        }\n\n        case EdgeEnhanceType::Unsharp_mask:\n        {\n            cv::Mat kernel = (cv::Mat_<float>(5,5) <<\n                    1, 4,   6, 4, 1,\n                    4,16,  24,16, 4,\n                    6,24,-476,24, 6,\n                    4,16,  24,16, 4,\n                    1, 4,   6, 4, 1) / -256.0;\n\n            filter2D(frame, frame, CV_32F, kernel);\n            break;\n        }\n\n        default:\n        {\n            break;\n        }\n    }\n    frame.convertTo(frame, CV_8U);\n    convertScaleAbs(frame, frame);\n}\n\nvoid cpuDsp::eZoom(cv::Mat &frame, TiDspParameters params)\n{\n    cv::Mat dest;\n    switch (params.ezoom)\n    {\n        case Ezoom::NoZoom:\n            break;\n        case Ezoom::x2:\n            cv::pyrUp(frame, dest, cv::Size(frame.cols * 2, frame.rows * 2));\n            moveFrame(frame, dest, params);\n            break;\n        case Ezoom::x4:\n            cv::pyrUp(frame, dest, cv::Size(frame.cols * 2, frame.rows * 2));\n            cv::pyrUp(dest, dest, cv::Size(dest.cols * 2, dest.rows * 2));\n            moveFrame(frame, dest, params);\n            break;\n        case Ezoom::x8:\n            cv::pyrUp(frame, dest, cv::Size(frame.cols * 2, frame.rows * 2));\n            cv::pyrUp(dest, dest, cv::Size(dest.cols * 2, dest.rows * 2));\n            cv::pyrUp(dest, dest, cv::Size(dest.cols * 2, dest.rows * 2));\n            moveFrame(frame, dest, params);\n            break;\n    }\n\n}\n\nvoid cpuDsp::moveFrame(const cv::Mat &frame, const cv::Mat &dest, TiDspParameters params)\n{\n    double availableXPixels, availableYPixels;\n    double xMove, yMove;\n\n    availableXPixels = dest.cols - frame.cols;\n    availableYPixels = dest.rows - frame.rows;\n    xMove = params.horisontalOffset / 100.0;\n    yMove = params.verticalOffset / 100.0;\n    dest(cv::Rect(xMove * availableXPixels, yMove * availableYPixels, frame.cols, frame.rows)).copyTo(frame);\n}\n\nvoid cpuDsp::sharpen(cv::Mat& frame)\n{\n    cv::Mat blurred; double sigma = 1, threshold = 5, amount = 1;\n    GaussianBlur(frame, blurred, cv::Size(), sigma, sigma);\n    cv::Mat lowContrastMask = cv::abs(frame - blurred) < threshold;\n    cv::Mat sharpened = frame*(1+amount) + blurred*(-amount);\n    frame.copyTo(frame, lowContrastMask);\n}\n\nvoid cpuDsp::nediUpscale(const cv::Mat &frame, cv::Mat &dest) {\n    const int upscaleFactor = 2;\n    dest = cv::Mat::zeros(cv::Size(frame.cols * upscaleFactor, frame.rows * upscaleFactor), CV_8UC1);\n\n    for (int y = 0; y < frame.rows; y++)\n    {\n        for (int x = 0; x < frame.cols; x++)\n        {\n            dest.ptr<unsigned char>(y * upscaleFactor)[x * upscaleFactor] = frame.ptr<unsigned char>(y)[x];\n        }\n    }\n\n    arma::mat Y = arma::zeros(25, 1);\n    arma::mat C = arma::zeros(25, 4);\n    arma::mat CtC;\n    arma::mat Cty;\n    arma::mat Cinv;\n    arma::mat a;\n    int temp;\n    //int m = 5; //todo review size of filter\n\n    //Solve the \"b\" pixels\n    //todo edge conditions not handled yet\n    for (int i = 4; i < (dest.rows - 4) / 2; i++)\n    {\n        for (int j = 4; j < (dest.cols - 4) / 2; j++)\n        {\n            temp = 0;\n            for (int ii = i - 2; ii <= i + 2; ii++)\n            {\n                for (int jj = j - 2; jj <= j + 2; jj++)\n                {\n                    Y(temp, 0) = (dest.ptr<unsigned char>(2*ii)[2*jj]);\n\n                    C(temp, 0) = (dest.ptr<unsigned char>(2*ii - 2)[2*jj - 2]);\n                    C(temp, 1) = (dest.ptr<unsigned char>(2*ii + 2)[2*jj - 2]);\n                    C(temp, 2) = (dest.ptr<unsigned char>(2*ii + 2)[2*jj + 2]);\n                    C(temp, 3) = (dest.ptr<unsigned char>(2*ii - 2)[2*jj + 2]);\n                    temp++;\n                }\n            }\n\n            Cty = C.t() * Y;\n            CtC = C.t() * C;\n            if (arma::solve(a, Cty, CtC))\n            {\n                (dest.ptr<unsigned char>(2*i + 1)[2*j + 1]) = (unsigned char) (a(0, 0) / 4 * (dest.ptr<unsigned char>(2*i)[2*j]) + \\\n                a(0, 1) / 4 * (dest.ptr<unsigned char>(2*i + 2)[2*j]) + \\\n                a(0, 2) / 4 * (dest.ptr<unsigned char>(2*i + 2)[2*j + 2]) + \\\n                a(0, 3) / 4  * (dest.ptr<unsigned char>(2*i)[2*j + 2]));\n            }\n            else\n            {\n                (dest.ptr<unsigned char>(2*i + 1)[2*j + 1]) = 0;//(unsigned char) (dest.ptr<unsigned char>(y - 1)[x - 1]);\n            }\n        }\n    }\n\n    for (int i = 4; i < (dest.rows - 4) / 2; i++)\n    {\n        for (int j = 4; j < (dest.cols - 4) / 2; j++)\n        {\n            temp = 0;\n            for (int ii = i - 2; ii <= i + 2; ii++)\n            {\n                for (int jj = j - 2; jj <= j + 2; jj++)\n                {\n                    Y(temp, 0) = (dest.ptr<unsigned char>(2*ii + 1)[2*jj - 1]);\n\n                    C(temp, 0) = (dest.ptr<unsigned char>(2*ii - 1)[2*jj - 1]);\n                    C(temp, 1) = (dest.ptr<unsigned char>(2*ii + 1)[2*jj - 3]);\n                    C(temp, 2) = (dest.ptr<unsigned char>(2*ii + 3)[2*jj - 1]);\n                    C(temp, 3) = (dest.ptr<unsigned char>(2*ii + 1)[2*jj + 1]);\n                    temp++;\n                }\n            }\n\n            Cty = C.t() * Y;\n            CtC = C.t() * C;\n            if (arma::solve(a, Cty, CtC))\n            {\n                (dest.ptr<unsigned char>(2*i + 1)[2*j]) = (unsigned char) (a(0, 0) / 4 * (dest.ptr<unsigned char>(2*i)[2*j]) + \\\n                a(0, 1) / 4 * (dest.ptr<unsigned char>(2*i + 1)[2*j - 1]) + \\\n                a(0, 2) / 4 * (dest.ptr<unsigned char>(2*i + 2)[2*j]) + \\\n                a(0, 3) / 4  * (dest.ptr<unsigned char>(2*i + 1)[2*j + 1]));\n            }\n            else\n            {\n                (dest.ptr<unsigned char>(2*i + 1)[2*j]) = 0;//(unsigned char) (dest.ptr<unsigned char>(y - 1)[x - 1]);\n            }\n        }\n    }\n\n\n    for (int i = 4; i < (dest.rows - 4) / 2; i++)\n    {\n        for (int j = 4; j < (dest.cols - 4) / 2; j++)\n        {\n            temp = 0;\n            for (int ii = i - 2; ii <= i + 2; ii++)\n            {\n                for (int jj = j - 2; jj <= j + 2; jj++)\n                {\n                    Y(temp, 0) = (dest.ptr<unsigned char>(2*ii + 1)[2*jj - 1]);\n\n                    C(temp, 0) = (dest.ptr<unsigned char>(2*ii - 1)[2*jj - 1]);\n                    C(temp, 1) = (dest.ptr<unsigned char>(2*ii + 1)[2*jj - 3]);\n                    C(temp, 2) = (dest.ptr<unsigned char>(2*ii + 3)[2*jj - 1]);\n                    C(temp, 3) = (dest.ptr<unsigned char>(2*ii + 1)[2*jj + 1]);\n                    temp++;\n                }\n            }\n\n            Cty = C.t() * Y;\n            CtC = C.t() * C;\n            if (arma::solve(a, Cty, CtC))\n            {\n                (dest.ptr<unsigned char>(2*i)[2*j + 1]) = (unsigned char) (a(0, 0) / 4 * (dest.ptr<unsigned char>(2*i - 1)[2*j + 1]) + \\\n                a(0, 1) / 4 * (dest.ptr<unsigned char>(2*i)[2*j]) + \\\n                a(0, 2) / 4 * (dest.ptr<unsigned char>(2*i + 1)[2*j + 1]) + \\\n                a(0, 3) / 4  * (dest.ptr<unsigned char>(2*i)[2*j + 2]));\n            }\n            else\n            {\n                (dest.ptr<unsigned char>(2*i)[2*j + 1]) = 0;//(unsigned char) (dest.ptr<unsigned char>(y - 1)[x - 1]);\n            }\n        }\n    }\n}\n\n", "meta": {"hexsha": "19df9bc2abc012a39fd885a708e27fb321e876f7", "size": 15150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/imageProcessing/cpuDsp.cpp", "max_stars_repo_name": "kabousvlieg/Nedi-image-upscaling", "max_stars_repo_head_hexsha": "033e9de180c02c720c24063d7ba30479e4cae5cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-30T11:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T13:43:44.000Z", "max_issues_repo_path": "src/imageProcessing/cpuDsp.cpp", "max_issues_repo_name": "kabousvlieg/Nedi-image-upscaling", "max_issues_repo_head_hexsha": "033e9de180c02c720c24063d7ba30479e4cae5cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/imageProcessing/cpuDsp.cpp", "max_forks_repo_name": "kabousvlieg/Nedi-image-upscaling", "max_forks_repo_head_hexsha": "033e9de180c02c720c24063d7ba30479e4cae5cd", "max_forks_repo_licenses": ["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.7416481069, "max_line_length": 136, "alphanum_fraction": 0.4801980198, "num_tokens": 4599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.02675928531985176, "lm_q1q2_score": 0.012128963115647002}}
{"text": "/* Copyright 2018 Ignacio Torroba (ignaciotb@kth.se)\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *\n * 2. 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 *\n * 3. Neither the name of the copyright holder nor the names of its contributors may be used 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 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef EKF_LOCALIZATION_HPP\n#define EKF_LOCALIZATION_HPP\n\n#include <ros/timer.h>\n#include <ros/ros.h>\n\n#include \"gazebo_msgs/GetWorldProperties.h\"\n#include \"gazebo_msgs/GetModelState.h\"\n\n#include \"utils_matrices/utils_matrices.hpp\"\n#include \"correspondence_class/correspondence_class.hpp\"\n#include \"noise_oneD_kf/noise_oneD_kf.hpp\"\n\n#include <queue>\n#include <math.h>\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/assign.hpp>\n#include <boost/bind.hpp>\n#include <ros/transport_hints.h>\n#include <boost/scoped_ptr.hpp>\n\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/inverse_chi_squared.hpp>\n\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <std_msgs/UInt32.h>\n#include <sensor_msgs/Image.h>\n\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <geometry_msgs/TwistWithCovarianceStamped.h>\n#include <geometry_msgs/Quaternion.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <visualization_msgs/MarkerArray.h>\n#include <visualization_msgs/Marker.h>\n#include <geometry_msgs/PoseArray.h>\n\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <tf/transform_broadcaster.h>\n\ntypedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Imu,\n        geometry_msgs::TwistWithCovarianceStamped> MsgTimingPolicy;\n\n/**\n * @brief The EKFLocalization class\n * EKF-based localization node for LoLo\n * Inputs:\n * IMU, DVL and landmarks positions from measurements\n * Map as a collection of landmarks with respect to world frame\n * Outputs:\n * nav_msgs/Odometry with an estimate of the 6DOF pose of LoLo\n * updated tf transform odom --> base_link\n */\n\nclass EKFLocalization{\n\npublic:\n\n    EKFLocalization(std::string node_name, ros::NodeHandle &nh);\n    void ekfLocalize(const ros::TimerEvent& e);\n    ~EKFLocalization();\n    void init(std::vector<double> sigma_diag, std::vector<double> r_diag, std::vector<double> q_diag, double delta);\n\nprivate:\n\n    // ROS variables\n    ros::NodeHandle *nh_;\n    std::string node_name_;\n    message_filters::Synchronizer<MsgTimingPolicy>* msg_synch_ptr_;\n    message_filters::Subscriber<sensor_msgs::Imu>* imu_subs_;\n    message_filters::Subscriber<geometry_msgs::TwistWithCovarianceStamped>* dvl_subs_;\n    ros::Timer timer_;\n\n    // Comms\n    ros::Subscriber fast_imu_sub_;\n    ros::Subscriber fast_dvl_sub_;\n    ros::Subscriber tf_gt_subs_;\n    ros::Subscriber observs_subs_;\n    ros::Subscriber rpt_subs_;\n    ros::Publisher odom_pub_;\n    ros::Publisher odom_inertial_pub_;\n    ros::Publisher vis_pub_;\n    visualization_msgs::MarkerArray markers_;\n    ros::ServiceClient gazebo_client_;\n    ros::ServiceClient landmarks_client_;\n\n    // Handlers for sensors\n    std::deque<sensor_msgs::ImuPtr> imu_readings_; // TODO: add limit size to queues\n    std::deque<geometry_msgs::TwistWithCovarianceStampedPtr> dvl_readings_;\n    std::deque<nav_msgs::OdometryPtr> gt_readings_;\n    std::deque<geometry_msgs::PoseArrayPtr> measurements_t_;\n    boost::mutex msg_lock_;\n    std::vector<boost::numeric::ublas::vector<double>> map_odom_;\n    bool init_filter_;\n\n    // System state variables\n    boost::numeric::ublas::vector<double> mu_;\n    boost::numeric::ublas::vector<double> mu_hat_;\n    boost::numeric::ublas::vector<double> mu_pred_;\n    boost::numeric::ublas::matrix<double> Sigma_;\n    boost::numeric::ublas::matrix<double> Sigma_hat_;\n    boost::numeric::ublas::matrix<double> G_t_;\n    double delta_m_;\n    double lambda_M_;\n\n    // Noise models\n    boost::numeric::ublas::matrix<double> R_;\n    boost::numeric::ublas::matrix<double> Q_;\n\n    // Aux\n    double t_prev_;\n    bool coord_;\n    unsigned int size_imu_q_;\n    unsigned int size_dvl_q_;\n\n    OneDKF* dvl_x_kf;\n    OneDKF* dvl_y_kf;\n    OneDKF* dvl_z_kf;\n\n    // tf\n    tf::TransformBroadcaster odom_bc_;\n    tf::StampedTransform transf_dvl_base_;\n    tf::StampedTransform transf_world_odom_;    \n    tf::Transform transf_odom_world_;\n    tf::StampedTransform transf_base_sssr_;\n    std::string odom_frame_;\n    std::string world_frame_;\n    std::string base_frame_;\n    std::string dvl_frame_;\n    std::string sssr_frame_;\n    std::string map_srv_name_;\n    std::string lm_srv_name_;\n\n    // Input callbacks\n    void gtCB(const nav_msgs::OdometryPtr &pose_msg);\n    void synchSensorsCB(const sensor_msgs::ImuConstPtr &imu_msg,\n                        const geometry_msgs::TwistWithCovarianceStampedConstPtr &dvl_msg);\n    void fastIMUCB(const sensor_msgs::ImuPtr &imu_msg);\n    void fastDVLCB(const geometry_msgs::TwistWithCovarianceStampedPtr &dvl_msg);\n    void observationsCB(const geometry_msgs::PoseArrayPtr &observ_msg);\n\n    /**\n     * @brief EKFLocalization::computeOdom\n     * @param dvl_msg\n     * @param gt_pose\n     * @param q_auv\n     * @param u_t\n     * Integrates IMU and DVL to predict an estimate of the pose\n     */\n    void computeOdom(const geometry_msgs::TwistWithCovarianceStampedPtr &dvl_msg, const tf::Quaternion &q_auv,\n                     boost::numeric::ublas::vector<double> &u_t);\n\n\n    /**\n     * @brief EKFLocalization::predictMotion\n     * @param u_t\n     * Prediction step for the EKF\n     */\n    void predictMotion(boost::numeric::ublas::vector<double> &u_t);\n\n    /**\n     * @brief predictMeasurement\n     * @param landmark_j\n     * @param z_i\n     * @param ml_i_list\n     * Measurement prediction for a given pair measurement-landmark at time t\n     */\n    void predictMeasurement(const boost::numeric::ublas::vector<double> &landmark_j,\n                                 boost::numeric::ublas::vector<double> &z_i,\n                                 std::vector<CorrespondenceClass *> &ml_i_list);\n\n    /**\n     * @brief dataAssociation\n     * Maximum likelihood data association with outlier rejection\n     */\n    void dataAssociation();\n\n    /**\n     * @brief sequentialUpdate\n     * @param c_i_j\n     * Sequential update for a given match observation-landmark\n     */\n    void sequentialUpdate(CorrespondenceClass *c_i_j);\n\n\n    /**\n     * @brief createMapMarkers\n     * Publishes the map as an array of markers for visualization in RVIZ\n     */\n    void createMapMarkers(std::vector<boost::numeric::ublas::vector<double> > map_world);\n\n    /**\n     * @brief EKFLocalization::sendOutput\n     * @param t\n     * @return\n     * Publishes AUV odometry info and tf odom --> base_link\n     */\n    bool sendOutput(ros::Time t);\n\n    /**\n     * @brief EKFLocalization::interpolateDVL\n     * @param t_now\n     * @param dvl_msg_ptr\n     * Interpolates DVL (slower) inputs through Bezier curves to synch to faster sensors\n     */\n    void interpolateDVL(ros::Time t_now, geometry_msgs::TwistWithCovarianceStampedPtr &dvl_msg_ptr);\n\n\n};\n\n#endif // EKF_LOCALIZATION_HPP\n", "meta": {"hexsha": "ffba0800222d9f0c834c60c7f5ac1efb2a02d72a", "size": 8386, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "auv_ekf_localization/include/ekf_localization/ekf_localization.hpp", "max_stars_repo_name": "nilsbore/smarc_navigation", "max_stars_repo_head_hexsha": "97d0a30498e72506e7472c98c5fa0d86d19f0f04", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-01-24T10:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T10:22:41.000Z", "max_issues_repo_path": "auv_ekf_localization/include/ekf_localization/ekf_localization.hpp", "max_issues_repo_name": "nilsbore/smarc_navigation", "max_issues_repo_head_hexsha": "97d0a30498e72506e7472c98c5fa0d86d19f0f04", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T09:46:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T09:40:26.000Z", "max_forks_repo_path": "auv_ekf_localization/include/ekf_localization/ekf_localization.hpp", "max_forks_repo_name": "nilsbore/smarc_navigation", "max_forks_repo_head_hexsha": "97d0a30498e72506e7472c98c5fa0d86d19f0f04", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-01-25T14:42:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T15:18:28.000Z", "avg_line_length": 36.1465517241, "max_line_length": 758, "alphanum_fraction": 0.7309802051, "num_tokens": 2050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.02442309027600974, "lm_q1q2_score": 0.012116144382539648}}
{"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// This file is generated by a script.  Do not edit directly.  Edit the\n// wrapQuat.template.cpp file to make changes.\n\n#include \"pxr/base/gf/quath.h\"\n\n#include \"pxr/base/tf/pyUtils.h\"\n#include \"pxr/base/tf/wrapTypeHelpers.h\"\n#include \"pxr/base/tf/pyContainerConversions.h\"\n\n#include <boost/python/class.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/implicit.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/python/operators.hpp>\n#include <boost/python/overloads.hpp>\n#include <boost/python/return_arg.hpp>\n\n#include <string>\n\nusing namespace boost::python;\n\nusing std::string;\n\nstatic string __repr__(GfQuath const &self) {\n    return TF_PY_REPR_PREFIX + \"Quath(\" +\n        TfPyRepr(self.GetReal()) + \", \" +\n        TfPyRepr(self.GetImaginary()) + \")\";\n}\n\n// Zero-initialized default ctor for python.\nstatic GfQuath *__init__() { return new GfQuath(0); }\n\nvoid wrapQuath()\n{    \n    object getImaginary =\n        make_function(&GfQuath::GetImaginary,\n                      return_value_policy<return_by_value>());\n\n    object setImaginaryVec =\n        make_function((void (GfQuath::*)(const GfVec3h &))\n                      &GfQuath::SetImaginary);\n\n    object setImaginaryScl =\n        make_function((void (GfQuath::*)(half, half, half))\n                      &GfQuath::SetImaginary,\n                      default_call_policies(),\n                      (arg(\"i\"), arg(\"j\"), arg(\"k\")));\n\n    def(\"Slerp\",\n        (GfQuath (*)(double, const GfQuath&, const GfQuath&))\n        GfSlerp);\n    \n    class_<GfQuath>(\"Quath\", no_init)\n        .def(\"__init__\", make_constructor(__init__))\n                          \n        .def(TfTypePythonClass())\n\n        .def(init<half>(arg(\"real\")))\n        .def(init<half, const GfVec3h &>(\n                 (arg(\"real\"), arg(\"imaginary\"))))\n        .def(init<half, half, half, half>(\n                 (arg(\"real\"), arg(\"i\"), arg(\"j\"), arg(\"k\"))))\n\n        .def(\"GetIdentity\", &GfQuath::GetIdentity)\n        .staticmethod(\"GetIdentity\")\n\n        .def(\"GetReal\", &GfQuath::GetReal)\n        .def(\"SetReal\", &GfQuath::SetReal)\n        .add_property(\"real\", &GfQuath::GetReal, &GfQuath::SetReal)\n\n        .def(\"GetImaginary\", getImaginary)\n        .def(\"SetImaginary\", setImaginaryVec)\n        .def(\"SetImaginary\", setImaginaryScl)\n        .add_property(\"imaginary\", getImaginary, setImaginaryVec)\n\n        .def(\"GetLength\", &GfQuath::GetLength)\n\n        .def(\"GetNormalized\", &GfQuath::GetNormalized,\n             (arg(\"eps\")=GF_MIN_VECTOR_LENGTH))\n        .def(\"Normalize\", &GfQuath::Normalize,\n             (arg(\"eps\")=GF_MIN_VECTOR_LENGTH), return_self<>())\n\n        .def(\"GetConjugate\", &GfQuath::GetConjugate)\n        .def(\"GetInverse\", &GfQuath::GetInverse)\n\n        .def(str(self))\n        .def(-self)\n        .def(self == self)\n        .def(self != self)\n        .def(self *= self)\n        .def(self *= half())\n        .def(self /= half())\n        .def(self += self)\n        .def(self -= self)\n        .def(self + self)\n        .def(self - self)\n        .def(self * self)\n        .def(self * half())\n        .def(half() * self)\n        .def(self / half())\n\n        .def(\"__repr__\", __repr__)\n\n        ;\n\n\n    to_python_converter<std::vector<GfQuath>,\n        TfPySequenceToPython<std::vector<GfQuath> > >();\n    \n}\n", "meta": {"hexsha": "4f697f925a5dc9b43b355a80061a26aac51dc988", "size": 4489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pxr/base/lib/gf/wrapQuath.cpp", "max_stars_repo_name": "marsupial/USD", "max_stars_repo_head_hexsha": "98d49911893d59be5a9904a29e15959affd530ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-03-31T21:23:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:29:27.000Z", "max_issues_repo_path": "pxr/base/lib/gf/wrapQuath.cpp", "max_issues_repo_name": "unity3d-jp/USD", "max_issues_repo_head_hexsha": "0f146383613e1efe872ea7c85aa3536f170fcda2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pxr/base/lib/gf/wrapQuath.cpp", "max_forks_repo_name": "unity3d-jp/USD", "max_forks_repo_head_hexsha": "0f146383613e1efe872ea7c85aa3536f170fcda2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-12-13T00:53:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T07:32:53.000Z", "avg_line_length": 33.0073529412, "max_line_length": 75, "alphanum_fraction": 0.6152818, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.027169234588046234, "lm_q1q2_score": 0.012104696453393316}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python/module.hpp>\n#include <boost/python/scope.hpp>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/tuple.hpp>\n#include <boost/python/enum.hpp>\n\n#include <cctbx/sgtbx/space_group.h>\n#include <rstbx/dps_core/dps_core.h>\n#include <rstbx/dps_core/direction.h>\n#include <rstbx/diffraction/ewald_sphere.h>\n#include <rstbx/diffraction/partial_spot_position_partial_H.h>\n\n#include <scitbx/array_family/flex_types.h>\n#include <vector>\n#include <rstbx/backplane.h>\n\nusing namespace boost::python;\n\nnamespace rstbx {\n\n/* SimpleSamplerTool samples the unit sphere; outputting a list of surface\n   points that are spaced apart a specified number of radians.\n*/\n\nclass SimpleSamplerTool {\n typedef scitbx::af::shared<Direction > flex_Direction;\n\n public:\n  double incr;  //initial directional spacing in radians\n  flex_Direction angles;\n\n  SimpleSamplerTool(const double& characteristic_grid):\n    // The maximum allowable characteristic grid should be about 0.029 radians,\n    // corresponding to the grid sampling used in the Rossman DPS paper;\n    // approx 7900 directions; 0.03 seconds in C++ code.\n    // But the characteristic grid sampling should be reflective of the problem at hand =\n    // approximately: the observed resolution limit /\n    //                most conservative (largest) cell estimate\n\n    incr(characteristic_grid) {\n    //construct_hemisphere_grid(incr);\n  }\n\n  flex_Direction construct_hemisphere_grid(const double& sampling){\n    // psi is the equivalent of latitude, measured as an angle from the North pole\n    // rounding:\n    int psi_index_range = int (0.5 + scitbx::constants::pi_2/sampling);\n    // adjust for integral number\n    double adjusted_psi_incr = scitbx::constants::pi_2/psi_index_range;\n    angles = flex_Direction();\n    angles.reserve(4*psi_index_range*psi_index_range);\n\n    for (int x = 0; x <= psi_index_range; ++x){\n      double psi = x * adjusted_psi_incr;\n      if (psi > scitbx::constants::pi){\n        double eps = 1E-4; psi=scitbx::constants::pi-eps;\n      }\n\n      // phi is the equivalent of longitude\n      if (psi==0){\n        double phi=0.;\n        angles.push_back(Direction(psi,phi));\n      } else {\n        int phi_index_range = int (0.5 + 2.*scitbx::constants::pi*std::sin(psi)/sampling);\n        double adjusted_phi_incr = 2.*scitbx::constants::pi/phi_index_range;\n        for (int y =0; y < phi_index_range; ++y) {\n          double phi = y * adjusted_phi_incr;\n          angles.push_back(Direction(psi,phi));\n        }\n      }\n    }\n    return angles;\n  }\n};\n\nstatic boost::python::tuple\nobserved_indices_and_angles_from_rotation_angles_range(rotation_angles& ra,\n  double const& phi_start_rad,double const& phi_end_rad,\n  const scitbx::af::shared<cctbx::miller::index<> >& indices){\n    // This is going to require some revision to assure it works in an arbitrary\n    // principle value region for phi_start_rad and phi_end_rad\n\n    scitbx::af::shared<scitbx::vec3<double> > return_indices;\n    scitbx::af::shared<double> return_angles_rad;\n\n    for (int ihkl = 0; ihkl < indices.size(); ++ihkl) {\n       scitbx::vec3<double> test_index( // convert integer Miller index to double type\n         indices[ihkl][0],indices[ihkl][1],indices[ihkl][2]);\n       if (ra( test_index )) {\n         scitbx::vec2<Angle> intersection_angles = ra.get_intersection_angles();\n         for (int iangle = 0; iangle < 2; ++iangle){\n           if (intersection_angles[iangle] >= phi_start_rad &&\n               intersection_angles[iangle] <= phi_end_rad){\n                 return_indices.push_back(test_index);\n                 return_angles_rad.push_back(intersection_angles[iangle]);\n           }\n         }\n       }\n     }\n     return make_tuple(return_indices,return_angles_rad);\n}\n\nstatic boost::python::tuple\nrp_predict(reflection_prediction& rp,\n  scitbx::af::shared<scitbx::vec3<double> > const& observed_indices,\n  scitbx::af::shared<double> const& observed_angles){\n\n    scitbx::af::shared<scitbx::vec3<double> > return_indices;\n    scitbx::af::shared<double> return_fast_px;\n    scitbx::af::shared<double> return_slow_px;\n    scitbx::af::shared<double> return_angle_rad;\n    scitbx::af::shared<double> return_angle_full_width_rad;\n    scitbx::af::shared<double> return_lorentz_factor;\n    scitbx::af::shared<scitbx::vec3<double> > return_s;\n\n    if (rp.use_gh1982a){\n      for (int ihkl = 0; ihkl < observed_indices.size(); ++ihkl) {\n        if (rp( observed_indices[ihkl], observed_angles[ihkl] )) {\n           scitbx::vec2<double> xy = rp.get_prediction();\n           scitbx::vec3<double> s = rp.get_s();\n           return_indices.push_back(observed_indices[ihkl]);\n           return_angle_rad.push_back(observed_angles[ihkl]);\n           return_fast_px.push_back(xy[0]);\n           return_slow_px.push_back(xy[1]);\n           return_lorentz_factor.push_back(rp.lorentz_factor());\n           return_angle_full_width_rad.push_back(rp.get_full_width());\n           return_s.push_back(s);\n         }\n       }\n       return make_tuple(return_indices,return_fast_px,return_slow_px,return_angle_rad,\n                         return_lorentz_factor, return_angle_full_width_rad, return_s);\n    }\n    for (int ihkl = 0; ihkl < observed_indices.size(); ++ihkl) {\n       if (rp( observed_indices[ihkl], observed_angles[ihkl] )) {\n         scitbx::vec2<double> xy = rp.get_prediction();\n         scitbx::vec3<double> s = rp.get_s();\n\n                 return_indices.push_back(observed_indices[ihkl]);\n                 return_angle_rad.push_back(observed_angles[ihkl]);\n                 return_fast_px.push_back(xy[0]);\n                 return_slow_px.push_back(xy[1]);\n           return_s.push_back(s);\n       }\n     }\n      return make_tuple(return_indices,return_fast_px,return_slow_px,return_angle_rad, return_s);\n}\n\nstatic af::shared<cctbx::miller::index<> >\nfull_sphere_indices(cctbx::uctbx::unit_cell const& uc,\n                    double const& resolution_limit,\n                    cctbx::sgtbx::space_group const& sg){\n\n  cctbx::miller::index<> maxhkl = uc.max_miller_indices(resolution_limit);\n\n  af::shared<cctbx::miller::index<> > present;\n\n  for (int h = -maxhkl[0]; h <= maxhkl[0]; ++h){\n    for (int k = -maxhkl[1]; k <= maxhkl[1]; ++k){\n      for (int l = -maxhkl[2]; l <= maxhkl[2]; ++l){\n\n        if (h == 0 && k == 0 && l == 0) { continue; }\n\n        if (uc.d(cctbx::miller::index<>(h, k, l)) < resolution_limit){\n                    continue;}\n\n        if (sg.is_sys_absent(cctbx::miller::index<>(h, k, l))){\n                    continue;}\n\n        present.push_back(cctbx::miller::index<>(h, k, l));\n      }\n    }\n  }\n  return present;\n}\n\nnamespace boost_python { namespace {\n\n  boost::python::tuple\n  foo()\n  {\n    return boost::python::make_tuple(1,2,3,4);\n  }\n\n  Direction\n  fft_result(dps_core& ai,Direction& angle){\n      fftptr dfft( ai.fft_factory(angle) );\n      angle.extract_directional_properties(dfft,true);\n      return angle;\n  }\n\n  void\n  init_module() {\n    using namespace boost::python;\n\n    typedef return_value_policy<return_by_value> rbv;\n    typedef default_call_policies dcp;\n\n    def(\"foo\", &foo);\n\n    class_<corrected_backplane>(\"corrected_backplane\",init<const int&, const int&>())\n      .def(\"accumulate\",&corrected_backplane::accumulate)\n      .def(\"finish\",&corrected_backplane::finish)\n      .def(\"localmean\",&corrected_backplane::localmean)\n      .def_readonly(\"rmsd\",&corrected_backplane::boxstd)\n    ;\n\n    class_<dps_core>(\"dps_core\",init<>())\n      .def(\"setMaxcell\",&dps_core::setMaxcell)\n      .def(\"setXyzData\",&dps_core::setXyzData)\n      .def(\"getXyzSize\",&dps_core::getXyzSize)\n      .def(\"getXyzData\",&dps_core::getXyzData)\n      .def(\"fft_result\",fft_result)\n      .def(\"setSolutions\",&dps_core::setSolutions)\n      .def(\"set_presorted_solutions\",&dps_core::set_presorted_solutions)\n      .def(\"getSolutions\",&dps_core::getSolutions)\n      .def(\"n_candidates\",&dps_core::n_candidates)\n      .def(\"__getitem__\",&dps_core::candidate)\n      .def(\"setOrientation\",&dps_core::setOrientation)\n      .def(\"set_orientation_direct_matrix\",\n          &dps_core::set_orientation_direct_matrix)\n      .def(\"set_orientation_reciprocal_matrix\",\n          &dps_core::set_orientation_reciprocal_matrix)\n      .def(\"getOrientation\",&dps_core::getOrientation)\n      .def(\"rmsdev\",&dps_core::rmsdev)\n      .def(\"hklobserved\",(hkllistmm(dps_core::*)()const) &dps_core::hklobserved)\n      .def(\"hklobserved\",\n(hkllistmm (dps_core::*)(const pointlistmm&)const) &dps_core::hklobserved)\n      .def(\"observed\",&dps_core::observed)\n      .def_readonly(\"granularity\",&dps_core::granularity)\n      .def_readonly(\"amax\",&dps_core::amax)\n\n    ;\n\n    class_<Direction>(\"Direction\", init<const point &>())\n      .def(init<const double &, const double &>((arg(\"psi\"),arg(\"phi\"))))\n      .def_readonly(\"kmax\",&Direction::kmax)\n      .add_property(\"kval\",make_getter(&Direction::kval, rbv()),\n                           make_setter(&Direction::kval, dcp()))\n      .def_readonly(\"kval0\",&Direction::kval0)\n      .def_readonly(\"kval2\",&Direction::kval2)\n      .def_readonly(\"kval3\",&Direction::kval3)\n      .def_readonly(\"psi\",&Direction::psi)\n      .def_readonly(\"phi\",&Direction::phi)\n      .def_readonly(\"m\",&Direction::m)\n      .def_readonly(\"delta_p\",&Direction::delta_p)\n      .def(\"bvec\",&Direction::bvec)\n      .def(\"getff\",&Direction::getff)\n      .add_property(\"dvec\",make_getter(&Direction::dvec, rbv()))\n      .add_property(\"real\",make_getter(&Direction::uc_length, rbv()))\n      .def(\"is_nearly_collinear\",&Direction::is_nearly_collinear)\n   ;\n    class_<Directional_FFT>(\"Directional_FFT\", no_init)\n      .def(init<const Direction&, const af::shared<scitbx::vec3<double> >&,\n                const double&, const double&,\n                const sztype&>((arg(\"angle\"),arg(\"xyzdata\"),\n                                arg(\"granularity\"),arg(\"amax\"),\n                                arg(\"F0_cutoff\"))))\n      .def_readonly(\"pmin\",&Directional_FFT::pmin)\n      .def_readonly(\"delta_p\",&Directional_FFT::delta_p)\n      .def_readonly(\"fft_result\",&Directional_FFT::fft_result)\n      .def(\"kval\",&Directional_FFT::kval)\n      .def(\"kmax\",&Directional_FFT::kmax)\n   ;\n\n    class_<SimpleSamplerTool >(\"SimpleSamplerTool\", init<const double &>())\n      .add_property(\"incr\",make_getter(&SimpleSamplerTool::incr, rbv()),\n                           make_setter(&SimpleSamplerTool::incr, dcp()))\n      .add_property(\"angles\",make_getter(&SimpleSamplerTool::angles, rbv()),\n                             make_setter(&SimpleSamplerTool::angles, dcp()))\n      .def(\"construct_hemisphere_grid\",&SimpleSamplerTool::construct_hemisphere_grid)\n   ;\n\n    class_<ewald_sphere_base_model>(\"ewald_sphere_base_model\",\n      init<const double&, const ewald_sphere_base_model::matrix&, const double&,\n           const ewald_sphere_base_model::point&>(\n           (arg(\"limiting_resolution\"),arg(\"orientation\"),\n            arg(\"wavelength\"),arg(\"axial_direction\"))))\n      .def(\"setH\",(void(ewald_sphere_base_model::*)\n           (const ewald_sphere_base_model::point&)) &ewald_sphere_base_model::setH)\n      .def(\"setH\",(void(ewald_sphere_base_model::*)\n           (const cctbx::miller::index<>&)) &ewald_sphere_base_model::setH)\n      .add_property(\"H\",make_getter(&ewald_sphere_base_model::H, rbv()))\n    ;\n\n    class_<rotation_angles, bases<ewald_sphere_base_model> >(\"rotation_angles\",\n      init<const double&, const ewald_sphere_base_model::matrix&, const double&,\n           const ewald_sphere_base_model::point&>(\n           (arg(\"limiting_resolution\"),arg(\"orientation\"),\n            arg(\"wavelength\"),arg(\"axial_direction\"))))\n      .def(init<const ewald_sphere_base_model&>())\n      .def(\"__call__\", &rotation_angles::operator())\n      .def(\"axis\", &rotation_angles::axis)\n      .def(\"offsetdot\", &rotation_angles::offsetdot)\n      .def(\"get_intersection_angles\", &rotation_angles::get_intersection_angles)\n      .def(\"observed_indices_and_angles_from_angle_range\",\n            &observed_indices_and_angles_from_rotation_angles_range,\n           (arg(\"phi_start_rad\"),arg(\"phi_end_rad\"),arg(\"indices\")))\n    ;\n\n    class_<reflection_prediction>(\"reflection_prediction\",\n                                  init<const scitbx::vec3<double> &,\n                                  const scitbx::vec3<double> &,\n                                  const scitbx::mat3<double> &,\n                                  const reflection_prediction::sensor_type &>\n      ((arg(\"axis\"), arg(\"s0\"), arg(\"ub\"), arg(\"sensor\"))))\n      .def(\"__call__\", & reflection_prediction::operator())\n      .def(\"get_prediction\", & reflection_prediction::get_prediction)\n      .def(\"get_s\", & reflection_prediction::get_s)\n      .def(\"set_rocking_curve\", & reflection_prediction::set_rocking_curve)\n      .def(\"set_mosaicity\", & reflection_prediction::set_mosaicity,\n            (arg(\"mos\"),arg(\"degrees\")))\n      .def(\"predict\",\n            &rp_predict,\n           (arg(\"observed_indices\"),arg(\"observed_angles\")));\n\n    def(\"full_sphere_indices\",&full_sphere_indices,\n      (arg(\"unit_cell\"), arg(\"resolution_limit\"),\n       arg(\"space_group\")));\n\n    class_<partial_spot_position_partial_H, bases<rotation_angles> >(\n      \"partial_spot_position_partial_H\",\n      init<const double&, const ewald_sphere_base_model::matrix&, const double&,\n           const ewald_sphere_base_model::point&>((arg(\"limiting_resolution\"),\n             arg(\"orientation\"),\n             arg(\"wavelength\"),arg(\"axial_direction\")\n      )))\n      .def(\"__call__\", &partial_spot_position_partial_H::operator())\n      .def(\"dangle_\", &partial_spot_position_partial_H::dangle_)\n    ;\n\n    class_<scattering_list >(\"scattering_list\",\n      init<scitbx::af::shared<cctbx::miller::index<> >,\n                           const cctbx::crystal_orientation&,\n                           scitbx::vec3<double>,\n                           scitbx::vec2<double>,\n                           const double&,\n                           const double&>())\n      .def(\"mm_coord\", &scattering_list::mm_coord)\n      .def(\"reflections\", &scattering_list::reflections)\n\n      .def(\"vec3\", &scattering_list::mm_coord) // when used as a spot positions container\n      .def(\"hkl\", &scattering_list::reflections) // when used as a spot positions container\n    ;\n}\n}}} // namespace omptbx::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(rstbx_ext)\n{\n  rstbx::boost_python::init_module();\n\n  // Expose SpotClass to Python\n  enum_<rstbx::SpotClass>(\"SpotClass\")\n    .value(\"GOOD\",rstbx::GOOD)\n    .value(\"OVERLAP\",rstbx::OVERLAP)\n    .value(\"SPINDLE\",rstbx::SPINDLE)\n    .value(\"ICE\",rstbx::ICE)\n    .value(\"OTHERIMAGE\",rstbx::OTHERIMAGE)\n    .value(\"FULL_ENTER\",rstbx::FULL_ENTER)\n    .value(\"FULL_EXIT\",rstbx::FULL_EXIT)\n    .value(\"ENTER1\",rstbx::ENTER1)\n    .value(\"ENTER2\",rstbx::ENTER2)\n    .value(\"EXIT3\",rstbx::EXIT3)\n    .value(\"EXIT4\",rstbx::EXIT4)\n    .value(\"NONE\",rstbx::NONE)\n    .value(\"OUTLIER\",rstbx::OUTLIER)\n    .export_values()\n    ;\n}\n", "meta": {"hexsha": "56cba935b77bf23bdcc8ced6345d8a12a9f3d674", "size": 15024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rstbx/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": "rstbx/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": "rstbx/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": 40.3870967742, "max_line_length": 97, "alphanum_fraction": 0.6490947817, "num_tokens": 3909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.025565216057740234, "lm_q1q2_score": 0.01208425520672517}}
{"text": "/*\n    SapecNG - Next Generation Symbolic Analysis Program for Electric Circuit\n    Copyright (C) 2009, Michele Caini\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//  Two Graphs Common Spanning Trees Algorithm\n\n#ifndef MRT_H\n#define MRT_H\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      class TreeMap,\n      class PredMap,\n      class DistMap,\n      class LowMap,\n      class 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      ): tree_(tree), pred_(pred), dist_(dist), low_(low), buffer_(buffer)\n    { num_ = -1; }\n\n    template <class Vertex, class Graph>\n    void initialize_vertex(const Vertex& u, const Graph& g)\n    {\n      put(pred_, u, u);\n      put(dist_, u, -1);\n    }\n\n    template <class Vertex, class Graph>\n    void discover_vertex(const Vertex& u, const Graph& g)\n    {\n      put(dist_, u, ++num_);\n      put(low_, u, get(dist_, u));\n    }\n\n    template <class Edge, class Graph>\n    void tree_edge(const Edge& e, const Graph& g)\n    {\n      put(pred_, target(e, g), source(e, g));\n      put(tree_, target(e, g), e);\n    }\n\n    template <class Edge, class Graph>\n    void back_edge(const Edge& e, const Graph& g)\n    {\n      put(low_, source(e, g),\n        std::min(get(low_, source(e, g)), get(dist_, target(e, g))));\n    }\n\n    template <class Vertex, class Graph>\n    void finish_vertex(const Vertex& u, const Graph& g)\n    {\n      Vertex parent = get(pred_, u);\n      if(get(low_, u) > get(dist_, parent))\n        buffer_.push(get(tree_, u));\n      put(low_, parent,\n        std::min(get(low_, parent), get(low_, u)));\n    }\n\n    TreeMap tree_;\n    PredMap pred_;\n    DistMap dist_;\n    LowMap low_;\n    Buffer& buffer_;\n    int num_;\n  };\n\n\n  template <class Buffer>\n  struct cycle_finder: public base_visitor< cycle_finder<Buffer> >\n  {\n    typedef on_back_edge event_filter;\n    cycle_finder(): buffer_(0) { }\n    cycle_finder(Buffer* buffer)\n      : buffer_(buffer) { }\n    template <class Edge, class Graph>\n    void operator()(const Edge& e, const Graph& g)\n      {\n        if(buffer_)\n          buffer_->push(e);\n      }\n    Buffer* buffer_;\n  };\n\n\n  template <class DeletedMap>\n  struct deleted_edge_status\n  {\n    deleted_edge_status() { }\n    deleted_edge_status(DeletedMap map): map_(map) { }\n    template <class Edge>\n    bool operator()(const Edge& e) const\n      { return (!get(map_, e)); }\n    DeletedMap map_;\n  };\n\n\n  template <class InLMap>\n  struct inL_edge_status\n  {\n    inL_edge_status() { }\n    inL_edge_status(InLMap map): map_(map) { }\n    template <class Edge>\n    bool operator()(const Edge& e) const\n      { return get(map_, e); }\n    InLMap map_;\n  };\n\n\n  template <\n    class Graph,\n    class Func,\n    class Seq,\n    class Map\n  >\n  void rec_mrt_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//  Using (edges != 0) condition drives to accidental non-tree\n//    ((V-1+1)-fake-tree, named here fat-tree) submission.\n//  Remove this condition acts as a workaround to the fat-trees problem.\n//  Please do not add that condition to improve performance.\n//\n//  Here previous (wrong) guard is presented:\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< 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              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_MRT\n        detail::rec_mrt_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_MRT\n          detail::rec_mrt_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 <class Coll, class 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): seqs_(seqs) { }\n\n  inline void operator()(Seq seq)\n    { seqs_.push_back(seq); }\n\nprivate:\n  Coll& seqs_;\n\n};\n\n\n\ntemplate <\n  class Graph,\n  class Order,\n  class Func,\n  class 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)\nmrt_two_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  tie(current, last) = edges(iG);\n  for(; current != last; ++current)\n    if(iG_bimap.right.find(*current) == iG_bimap.right.end())\n      return;\n  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    tie(current, last) = edges(iG);\n    for(;current != last; ++current)\n      put(diG, *current, false);\n    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_MRT\n    detail::rec_mrt_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  class Graph,\n  class Func,\n  class Seq\n>\nBOOST_CONCEPT_REQUIRES(\n  ((IncidenceGraphConcept<Graph>))\n  ((EdgeListGraphConcept<Graph>)),\n  (void)\n)\nmrt_two_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  tie(curr, last) = edges(iG);\n  for(; curr != last; ++curr)\n    iGO.push_back(*curr);\n\n  tie(curr, last) = edges(vG);\n  for(; curr != last; ++curr)\n    vGO.push_back(*curr);\n\n  mrt_two_graphs_common_spanning_trees(iG, iGO, vG, vGO, func, inL);\n}\n\n\n} // namespace boost\n\n\n#endif // MRT_H\n", "meta": {"hexsha": "8b7edf11f7f2d435991e800d943a9e3d7bc9fd69", "size": 28896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Apps/NetlistEditor/src/boost-sapecng/mrt.hpp", "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": "Apps/NetlistEditor/src/boost-sapecng/mrt.hpp", "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": "Apps/NetlistEditor/src/boost-sapecng/mrt.hpp", "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": 32.9486887115, "max_line_length": 82, "alphanum_fraction": 0.6084233112, "num_tokens": 7123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.025565211139177715, "lm_q1q2_score": 0.012084252881801939}}
{"text": "// Copyright (c) 2020 ICLUE @ UIUC. All rights reserved.\n\n#include <gflags/gflags.h>\n#include <coxeter_properness/search.h>\n#include <prettyprint.hpp>\n#include <coxeter/constants.h>\n#include <coxeter/coxtypes.h>\n#include <coxeter/interactive.h>\n#include <coxeter/type.h>\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <indicators/indicators.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <vector>\n\n\nDEFINE_string(type, \"\", \"type\");\nDEFINE_uint32(rank, 0, \"rank\");\nDEFINE_string(in_file, \"\", \"in-file\");\nDEFINE_string(out_file, \"\", \"out-file\");\n\nusing coxeter_properness::Transformer;\nusing coxeter_properness::proper;\n\n\nint main(int argc, char** argv) {\n  gflags::SetUsageMessage(\"Iterate over elements of a finite Coxeter group.\");\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n  const auto type = FLAGS_type;\n  const auto rank = FLAGS_rank;\n  const auto in_file = FLAGS_in_file;\n  const auto out_file = FLAGS_out_file;\n\n  if (type.empty() || rank == 0 || in_file.empty() || out_file.empty()) {\n    std::cout << \"Need to set each of --type, --rank, --out-file, and --in-file flags.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  std::ifstream ifs{in_file};\n  if (!ifs.is_open()) {\n    std::cout << \"Could not open input file '\" << in_file << \"'\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  std::ofstream ofs{out_file};\n  if (!ofs.is_open()) {\n    std::cout << \"Could not open output file '\" << out_file << \"'\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // Always need to run this line first.\n  constants::initConstants();\n  const std::shared_ptr<CoxGroup> group{\n    interactive::coxeterGroup(type.c_str(), rank)\n  };\n  Transformer transformer(group);\n  CoxWord word;\n\n  // indicators::ProgressSpinner spinner;\n  std::string line;\n  for (int numLinesProcessed = 0; std::getline(ifs, line); ++numLinesProcessed) {\n    if (numLinesProcessed % 100000 == 0) {\n      std::cout << \"processed: \" + std::to_string(numLinesProcessed) << std::endl;\n    }\n\n    if (!transformer.parse(line, &word)) {\n      std::cout << \"could not parse line '\" << line << \"'\" << std::endl;\n      continue;\n    }\n    if (!proper(*group, word)) continue;\n\n    for (int i = 0; i < word.length(); ++i) {\n      ofs << std::to_string(word[i]);\n    }\n    ofs << '\\n';\n    // ofs << std::endl;\n\n    // spinner.set_option(indicators::option::PrefixText{\n    //   \"processed: \" + std::to_string(numLinesProcessed)\n    // });\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0a95ba56ea4cebf429b4262e6c427227d036716a", "size": 2522, "ext": "cc", "lang": "C++", "max_stars_repo_path": "apps/run.cc", "max_stars_repo_name": "iclue-summer-2020/coxeter_properness", "max_stars_repo_head_hexsha": "dbdaa15da6c2e9a59db817d3413e614d072c7a76", "max_stars_repo_licenses": ["MIT"], "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/run.cc", "max_issues_repo_name": "iclue-summer-2020/coxeter_properness", "max_issues_repo_head_hexsha": "dbdaa15da6c2e9a59db817d3413e614d072c7a76", "max_issues_repo_licenses": ["MIT"], "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/run.cc", "max_forks_repo_name": "iclue-summer-2020/coxeter_properness", "max_forks_repo_head_hexsha": "dbdaa15da6c2e9a59db817d3413e614d072c7a76", "max_forks_repo_licenses": ["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.4130434783, "max_line_length": 101, "alphanum_fraction": 0.6526566217, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.027585282026933125, "lm_q1q2_score": 0.012077484701083966}}
{"text": "//\n//  main.cpp\n//  Andrews-Curtis Conjecture\n//\n//  Created by Kelly Davis on 8/19/11.\n//\n//\n\n#include <iostream>\n#include <boost/mpi/environment.hpp>\n\n#include \"relator.h\"\n#include \"searcher.h\"\n#include \"arguments.h\"\n#include \"binary_tree.h\"\n#include \"balanced_presentation.h\"\n\nusing namespace andrews_curtis;\n\nint main (int argc,char * argv[])\n{\n    // Initialize the MPI environment\n    boost::mpi::environment environment(argc,argv);\n    \n    // Initialize the user arguments\n    Arguments arguments(argc,argv);\n    \n    // Determine if arguments is not valid\n    if(!arguments.is_valid()) \n    {\n        // Print error message for invalid arguments\n        std::cout << arguments.get_message() << std::endl;\n        \n        // Return error\n        return arguments.get_return_code();\n    }\n    \n    // Create searcher\n    Searcher searcher(arguments);\n    \n    // Search\n    searcher.search();\n    \n    // Is Andrews-Curtis trivial\n    if(searcher.is_trivial())\n    {\n        // Print derivation\n        searcher.print_derivation();\n    }\n    else \n    {\n        // Print Andrews-Curtis counterexample\n        searcher.print_counterexample();\n    }\n    \n    // Clean up Relators\n    Binary_tree<Relator>::clear();\n    \n    // Clean up Balanced_presentation's\n    Binary_tree<Balanced_presentation>::clear();\n    \n    // Return success\n    return 0;\n}\n\n", "meta": {"hexsha": "d20715abd325ba72f16df9933f823749ffc81888", "size": 1359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "KellyJDavis/Andrews-Curtis", "max_stars_repo_head_hexsha": "1838a14ae03ca2c920f68d1afcf2d8ffc7c550dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-09T15:02:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-16T02:03:55.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "KellyJDavis/Andrews-Curtis", "max_issues_repo_head_hexsha": "1838a14ae03ca2c920f68d1afcf2d8ffc7c550dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-05-16T10:06:58.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-16T10:06:58.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "KellyJDavis/Andrews-Curtis", "max_forks_repo_head_hexsha": "1838a14ae03ca2c920f68d1afcf2d8ffc7c550dc", "max_forks_repo_licenses": ["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.5909090909, "max_line_length": 58, "alphanum_fraction": 0.6261957322, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.03567854908333911, "lm_q1q2_score": 0.012062101743834375}}
{"text": "/*\n * GeosTools.cpp\n */\n\n#include \"PathAdapter.h\"\n\n#include <boost/numeric/conversion/cast.hpp>\n#include <geos/geom/Coordinate.h>\n#include <geos/geom/CoordinateSequence.h>\n#include <geos/geom/LineString.h>\n#include <geos/geom/LinearRing.h>\n#include <geos/geom/MultiLineString.h>\n#include <geos/geom/MultiPoint.h>\n#include <geos/geom/MultiPolygon.h>\n#include <geos/geom/Point.h>\n#include <geos/geom/Polygon.h>\n#include <stdexcept>\n\nusing namespace geos::geom;\nusing namespace frontier;\n\nnamespace\n{\n// ----------------------------------------------------------------------\n/*!\n * \\brief Handle LinearRing\n */\n// ----------------------------------------------------------------------\n\nvoid contourFromLinearRing(const LinearRing *geom, PathAdapter &pathAdapter)\n{\n  if (geom == nullptr || geom->isEmpty()) return;\n\n  for (unsigned long i = 0, n = geom->getNumPoints(); i < n - 1; ++i)\n  {\n    if (i == 0)\n      pathAdapter.moveto(geom->getCoordinateN(boost::numeric_cast<int>(i)));\n    else\n      pathAdapter.lineto(geom->getCoordinateN(boost::numeric_cast<int>(i)));\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Handle LineString\n */\n// ----------------------------------------------------------------------\n\nvoid contourFromLineString(const LineString *geom, PathAdapter &pathAdapter)\n{\n  if (geom == nullptr || geom->isEmpty()) return;\n\n  unsigned long n = geom->getNumPoints();\n\n  for (unsigned long i = 0; i < n; ++i)\n  {\n    if (i == 0)\n      pathAdapter.moveto(geom->getCoordinateN(boost::numeric_cast<int>(i)));\n    else\n      pathAdapter.lineto(geom->getCoordinateN(boost::numeric_cast<int>(i)));\n  }\n\n  //\tif ((!(geom->isClosed())) && (n > 2))\n  //\t\tpathAdapter.lineto(geom->getCoordinateN(boost::numeric_cast<int>(0)));\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Handle Polygon\n */\n// ----------------------------------------------------------------------\n\nvoid contoursFromPolygon(const Polygon *geom, PathAdapter &pathAdapter)\n{\n  if (geom == nullptr || geom->isEmpty()) return;\n\n  contourFromLineString(geom->getExteriorRing(), pathAdapter);\n\n  for (size_t i = 0, n = geom->getNumInteriorRing(); i < n; ++i)\n    contourFromLineString(geom->getInteriorRingN(i), pathAdapter);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Handle MultiLineString\n */\n// ----------------------------------------------------------------------\n\nvoid contoursFromMultiLineString(const MultiLineString *geom, PathAdapter &pathAdapter)\n{\n  if (geom == nullptr || geom->isEmpty()) return;\n\n  for (size_t i = 0, n = geom->getNumGeometries(); i < n; ++i)\n    contourFromLineString(dynamic_cast<const LineString *>(geom->getGeometryN(i)), pathAdapter);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Handle MultiPolygon\n */\n// ----------------------------------------------------------------------\n\nvoid contoursFromMultiPolygon(const MultiPolygon *geom, PathAdapter &pathAdapter)\n{\n  if (geom == nullptr || geom->isEmpty()) return;\n\n  for (size_t i = 0, n = geom->getNumGeometries(); i < n; ++i)\n    contoursFromPolygon(dynamic_cast<const Polygon *>(geom->getGeometryN(i)), pathAdapter);\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Handle GeometryCollection\n */\n// ----------------------------------------------------------------------\n\nvoid contoursFromGeometryCollection(const GeometryCollection *geom, PathAdapter &pathAdapter)\n{\n  if (geom == nullptr || geom->isEmpty()) return;\n\n  for (size_t i = 0, n = geom->getNumGeometries(); i < n; ++i)\n    frontier::GeosTools::getContours(geom->getGeometryN(i), pathAdapter);\n}\n}  // namespace\n\nnamespace frontier\n{\nnamespace GeosTools\n{\n// ----------------------------------------------------------------------\n/*!\n * \\brief Extract contours from geos geometry\n */\n// ----------------------------------------------------------------------\n\nconst Path &getContours(const Geometry *geom, PathAdapter &pathAdapter)\n{\n  if (const LinearRing *lr = dynamic_cast<const LinearRing *>(geom))\n    contourFromLinearRing(lr, pathAdapter);\n  else if (const LineString *ls = dynamic_cast<const LineString *>(geom))\n    contourFromLineString(ls, pathAdapter);\n  else if (const Polygon *p = dynamic_cast<const Polygon *>(geom))\n    contoursFromPolygon(p, pathAdapter);\n  else if (const MultiLineString *ml = dynamic_cast<const MultiLineString *>(geom))\n    contoursFromMultiLineString(ml, pathAdapter);\n  else if (const MultiPolygon *mpg = dynamic_cast<const MultiPolygon *>(geom))\n    contoursFromMultiPolygon(mpg, pathAdapter);\n  else if (const GeometryCollection *g = dynamic_cast<const GeometryCollection *>(geom))\n    contoursFromGeometryCollection(g, pathAdapter);\n  else if (dynamic_cast<const Point *>(geom))\n    ;\n  else if (dynamic_cast<const MultiPoint *>(geom))\n    ;\n  else\n    throw std::runtime_error(\"Encountered an unsupported GEOS geometry component\");\n\n  return pathAdapter.getPath();\n}\n}  // namespace GeosTools\n}  // namespace frontier\n", "meta": {"hexsha": "9284ff1c01c035e9cc98fbd04080e704a832eef5", "size": 5105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/GeosTools.cpp", "max_stars_repo_name": "fmidev/smartmet-frontier", "max_stars_repo_head_hexsha": "b36dff7d6fac2528b3d47c5d1ef210b789f911be", "max_stars_repo_licenses": ["MIT"], "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/GeosTools.cpp", "max_issues_repo_name": "fmidev/smartmet-frontier", "max_issues_repo_head_hexsha": "b36dff7d6fac2528b3d47c5d1ef210b789f911be", "max_issues_repo_licenses": ["MIT"], "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/GeosTools.cpp", "max_forks_repo_name": "fmidev/smartmet-frontier", "max_forks_repo_head_hexsha": "b36dff7d6fac2528b3d47c5d1ef210b789f911be", "max_forks_repo_licenses": ["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.7080745342, "max_line_length": 96, "alphanum_fraction": 0.561410382, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.026355351221026283, "lm_q1q2_score": 0.012047998728015461}}
{"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_IEXP_IEXP_CWISE_BINARY_HPP\n#define AMA_TENSOR_IEXP_IEXP_CWISE_BINARY_HPP 1\n\n#include <ama/tensor/iexp/iexp_base.hpp>\n#include <ama/tensor/iexp/is_same_iexp.hpp>\n#include <boost/mpl/assert.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 iexp_cwise_binary;\n\n\n    /* specialization of iexp_traits */\n    template <typename LEFT, typename RIGHT, typename OPERATOR>\n    struct iexp_traits< iexp_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_list controvariant_list;\n      typedef typename LEFT::covariant_list covariant_list;\n\n      typedef ::boost::mpl::false_ is_assignable;\n    };\n\n\n    /* class declaration */\n    template <typename LEFT, typename RIGHT, typename OPERATOR>\n    class iexp_cwise_binary:\n        public iexp_base< iexp_cwise_binary<LEFT, RIGHT, OPERATOR> >\n    {\n      BOOST_MPL_ASSERT_MSG(\n            (is_same_iexp<LEFT,RIGHT>::value)\n          , COMPONENT_WISE_BINARY_OPERATION_BETWEEN_DIFFERENT_EXPRESSION_ARE_NOT_ALLOWED\n          , (LEFT, RIGHT));\n\n    protected:\n      typedef iexp_base< iexp_cwise_binary<LEFT, RIGHT, OPERATOR> > base_type;\n      typedef iexp_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      iexp_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 IMAP>\n      value_type at() const\n      {\n        return m_operator(\n                 m_left_operand.template at<IMAP>(),\n                 m_right_operand.template at<IMAP>());\n      }\n\n    protected:\n      /* members */\n      left_operand_type m_left_operand;\n      right_operand_type m_right_operand;\n      operator_type const m_operator;\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_IEXP_IEXP_CWISE_BINARY_HPP */\n", "meta": {"hexsha": "4e25749d848adc597ad670d67ff8fa4e9cc6c494", "size": 4106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/iexp/iexp_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/iexp/iexp_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/iexp/iexp_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": 36.6607142857, "max_line_length": 88, "alphanum_fraction": 0.7133463225, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.030675803039923136, "lm_q1q2_score": 0.012035247327513989}}
{"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 <algorithm>\n#include <stdexcept>\n#include <map>\n#include <utility>\n#include <algorithm>\n#include <string>\n#include <iostream>\n#include <time.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <hashclash/saveload_bz2.hpp>\n#include <hashclash/sha1detail.hpp>\n#include <hashclash/rng.hpp>\n#include <hashclash/sha1differentialpath.hpp>\n#include <hashclash/progress_display.hpp>\n\n#include \"main.hpp\"\n\n\n\nvoid random_permutation(vector<sha1differentialpath>& paths, path_container_autobalance& container)\n{\n\t// use a pseudo-random permutation fixed by inputs\n\tseed(paths.size()); addseed(container.t); addseed(container.modn);\n\tfor (unsigned i = 0; i < paths.size(); ++i)\n\t{\n\t\tunsigned k = xrng64() % paths.size();\n\t\tpaths[i].swap(paths[k]);\n\t}\n\taddseed(time(NULL));\n}\n\ninline std::string pathsstring(const std::string& basepath, unsigned modi, unsigned modn)\n{\n\treturn workdir +  \"/\"  + basepath \n\t\t+ \"_\" + boost::lexical_cast<std::string>(modi) \n\t\t+ \"of\" + boost::lexical_cast<std::string>(modn);\n}\n\nbool beginpathless(const sha1differentialpath& l, const sha1differentialpath& r)\n{\n\tfor (int i = 0; i < 3; ++i)\n\t\tif (l[l.tbegin()+i] != r[r.tbegin()+i])\n\t\t\treturn l[l.tbegin()+i] < r[r.tbegin()+i];\n\tfor (int i = 3; i < 5; ++i)\n\t\tif (l[l.tbegin()+i].getsdr() != r[r.tbegin()+i].getsdr())\n\t\t\treturn l[l.tbegin()+i].getsdr() < r[r.tbegin()+i].getsdr();\n\treturn false;\n}\n\nbool beginpatheq(const sha1differentialpath& l, const sha1differentialpath& r)\n{\n\tfor (int i = 0; i < 3; ++i)\n\t\tif (l[l.tbegin()+i] != r[r.tbegin()+i])\n\t\t\treturn false;\n\tfor (int i = 3; i < 5; ++i)\n\t\tif (l[l.tbegin()+i].getsdr() != r[r.tbegin()+i].getsdr())\n\t\t\treturn false;\n\treturn true;\n}\n\nvoid best_filter(vector<sha1differentialpath>& pathsout)\n{\n\tvector<sha1differentialpath> ret;\n\tstd::cout << \"Filtering best paths (insize=\" << pathsout.size() << \" sorting...\" << std::flush;\n\tstd::sort(pathsout.begin(), pathsout.end(), beginpathless);\n\tstd::cout << \"filtering...\" << std::flush;\n\tstd::size_t i = 0;\n\twhile (i < pathsout.size())\n\t{\n\t\tunsigned nrcondi = pathsout[i].nrcond();\n\t\tstd::size_t e = i + 1;\n\t\twhile (e < pathsout.size() && beginpatheq(pathsout[i],pathsout[e]))\n\t\t{\n\t\t\tunsigned nrconde = pathsout[e].nrcond();\n\t\t\tif (nrconde < nrcondi)\n\t\t\t{\n\t\t\t\tstd::swap(pathsout[i], pathsout[e]);\n\t\t\t\tnrcondi = nrconde;\n\t\t\t}\n\t\t\t++e;\n\t\t}\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n\t\tret.push_back(pathsout[i]);\n#else\n\t\tret.push_back(std::move(pathsout[i]));\n#endif\n\t\ti = e;\n\t}\n\tpathsout = std::move(ret);\n\tstd::cout << \" outsize=\" << pathsout.size() << \")\" << std::endl;\n}\n\n\nvector<sha1differentialpath> pathscache;\nvoid dostep(path_container_autobalance& container, bool savetocache)\n{\n\tconst unsigned t = container.t;\n\tconst unsigned modn = container.modn;\n\tconst unsigned modi = container.modi;\n\n\tvector< sha1differentialpath > pathsin, pathstmp, pathsout;\n\tif (pathscache.size() != 0) {\n\t\tpathsin.swap(pathscache);\n\t\trandom_permutation(pathsin, container);\n\t} else if (container.newinputpath) {\n\t\tsha1differentialpath path;\n\t\tpath.offset = - int(t) + 4;\n\t\tpath.path.resize(6);\n\t\tpath.me.resize(6);\n\t\tpathsin.push_back( path );\n\t\tcout << \"Generated 1 new path.\" << endl;\n\t} else if (container.inputfile.size() == 0) {\n\t\tfor (unsigned k = 0; k < modn; ++k)\n\t\t{\n\t\t\ttry {\n\t\t\t\tstd::string filename = pathsstring(\"paths\" + boost::lexical_cast<std::string>(t+1), k, modn);\n\t\t\t\tcout << \"Loading \" << filename << \"...\" << flush;\n\t\t\t\tload_bz2(pathstmp, filename, binary_archive);\n\t\t\t\trandom_permutation(pathstmp, container);\n\t\t\t\tfor (unsigned j = modi; j < pathstmp.size(); j += modn)\n\t\t\t\t\tpathsin.push_back(pathstmp[j]);\n\t\t\t\tcout << \"done: \" << pathstmp.size() << \" (work:\" << pathsin.size() << \").\" << endl;\n\t\t\t} catch(...) {\n\t\t\t\tcout << \"failed.\" << endl;\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttry {\n\t\t\tcout << \"Loading \" << container.inputfile << \"...\" << flush;\n\t\t\tload_bz2(pathstmp, binary_archive, container.inputfile);\n\t\t\trandom_permutation(pathstmp, container);\n\t\t\tfor (unsigned j = modi; j < pathstmp.size(); j += modn)\n\t\t\t\tpathsin.push_back(pathstmp[j]);\n\t\t\tcout << \"done: \" << pathsin.size() << \".\" << endl;\n\t\t} catch(...) {\n\t\t\tcout << \"failed.\" << endl;\n\t\t}\n\t}\n\tif (container.showinputpaths)\n\t\tfor (unsigned r = 0; r < pathsin.size(); ++r)\n\t\t\tshow_path(pathsin[r]);\n\n\tstd::string tstring = \"t=\" + boost::lexical_cast<std::string>(t) + \": \";\n\tif (tstring.size() == 5) tstring += \" \";\n\t\n\tif (container.estimatefactor != 0) {\n\t\tcout << \"Estimating maxcond for upper bound \" << unsigned(double(container.ubound)*container.estimatefactor)\n\t\t\t<< \" (=\" << container.ubound << \" * \" << container.estimatefactor << \")...\" << endl;\n\t\tprogress_display show_progress(pathsin.size(), true, cout, tstring, \"      \", \"e     \");\n\t\tfor (unsigned k = 0; k < pathsin.size(); ++k,++show_progress) {\n\t\t\tif (container.t < 79 && container.expandprevmessagediff) {\n\t\t\t\tsdr mmask = pathsin[k].getme(t+1);\n\t\t\t\tuint32 deltam = mmask.adddiff();\n\t\t\t\tuint32 dqtm3 = pathsin[k][t-3].getsdr().rotate_left(30).adddiff();\n\n\t\t\t\tuint32 addmask = (~mmask.mask)+1; \n\t\t\t\tuint32 andmask = mmask.mask & 0x7FFFFFF;\n\t\t\t\tmmask.sign = 0;\n\t\t\t\tdo {\n\t\t\t\t\tmmask.sign += addmask; mmask.sign &= andmask;\n\t\t\t\t\tpathsin[k].getme(t+1) = mmask;\n\t\t\t\t\tpathsin[k][t-3] = naf(dqtm3 + deltam - mmask.adddiff()).rotate_right(30);\n\t\t\t\t\tsha1_backward_differential_step(pathsin[k], container);\n\t\t\t\t} while (mmask.sign != 0);\n\t\t\t} else\n\t\t\t\tsha1_backward_differential_step(pathsin[k], container);\n\t\t}\t\t\t\n\t\tcontainer.finish_estimate();\n\t\tcout << \"Found maxcond = \" << container.maxcond << endl;\n\t}\n\n\tprogress_display show_progress(pathsin.size(), true, cout, tstring, \"      \", \"      \");\n\tfor (unsigned k = 0; k < pathsin.size(); ++k,++show_progress) {\n\t\tif (container.t < 79 && container.expandprevmessagediff) {\n\t\t\tsdr mmask = pathsin[k].getme(t+1);\n\t\t\tuint32 deltam = mmask.adddiff();\n\t\t\tuint32 dqtm3 = pathsin[k][t-3].getsdr().rotate_left(30).adddiff();\n\n\t\t\tuint32 addmask = (~mmask.mask)+1; \n\t\t\tuint32 andmask = mmask.mask & 0x7FFFFFF;\n\t\t\tmmask.sign = 0;\n\t\t\tdo {\n\t\t\t\tmmask.sign += addmask; mmask.sign &= andmask;\n\t\t\t\tpathsin[k].getme(t+1) = mmask;\n\t\t\t\tpathsin[k][t-3] = naf(dqtm3 + deltam - mmask.adddiff()).rotate_right(30);\n\t\t\t\tsha1_backward_differential_step(pathsin[k], container);\n\t\t\t} while (mmask.sign != 0);\n\t\t} else\n\t\t\tsha1_backward_differential_step(pathsin[k], container);\n\t}\n\n\tpathstmp.swap(pathsout);\t\n\tcontainer.export_results(pathsout);\n\t\n\tbest_filter(pathsout);\n\t\n\tif (pathsout.size() > 0)\n\t\tshow_path(pathsout[0]);\n\tstd::string filenameout = pathsstring(\"paths\" + boost::lexical_cast<std::string>(t), modi, modn);\n\tcout << \"Saving \" << pathsout.size() << \" paths...\" << flush;\n\tif (savetocache)\n\t\tpathsout.swap(pathscache);\n\telse\n\t\tsave_bz2(pathsout, filenameout, binary_archive);\n\tcout << \"done.\" << endl;\n}\n", "meta": {"hexsha": "2d61de10c887a9a975def51aa424137368cfb357", "size": 7601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sha1backward/dostep.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/dostep.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/dostep.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": 33.192139738, "max_line_length": 110, "alphanum_fraction": 0.6395211156, "num_tokens": 2258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668680822513, "lm_q2_score": 0.02976009609727703, "lm_q1q2_score": 0.01201018877580492}}
{"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_PROPERTY_MAP_IMPL_INCLUDE\n#define MTL_PROPERTY_MAP_IMPL_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/static_assert.hpp>\n\nnamespace mtl { namespace detail {\n\n// functor with matrix reference to access rows \ntemplate <class Matrix> struct indexer_row_ref\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    indexer_row_ref(const matrix_type& ma) : ma(ma) {} \n    \n    typename Matrix::size_type operator() (key_type const& key) const\n    {\n\treturn ma.indexer.row(ma, key);\n    }\n    const matrix_type& ma;\n};\n\n\n// functor to access rows using the key itself\ntemplate <class Matrix> struct row_in_key\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    row_in_key(const matrix_type&) {} \n    \n    typename Matrix::size_type operator() (key_type const& key) const\n    {\n\treturn key.row();\n    }\n};\n\n// functor to access rows using the key itself\ntemplate <class Matrix> struct row_in_element_key\n{\n    typedef Matrix                        matrix_type;\n    row_in_element_key(const matrix_type&) {} \n    \n    template <typename Key>\n    typename Matrix::size_type operator() (Key const& key) const\n    {\n\treturn key.indices[0];\n    }\n};\n\n\n// functor access the major dimension in key itself\ntemplate <class Matrix> struct major_in_key\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    major_in_key(const matrix_type&) {} \n\n    typename Matrix::size_type operator() (key_type const& key) const\n    {\n\treturn key.major;\n    }\n};\n\n// functor to access rows using the key itself\ntemplate <class Matrix> struct major_in_element_key\n{\n    typedef Matrix                      matrix_type;\n    major_in_element_key(const matrix_type&) {} \n    \n    template <typename Key>\n    typename Matrix::size_type operator() (Key const& key) const\n    {\n\treturn key.indices[0];\n    }\n};\n\ntemplate <class Matrix> struct indexer_minor_ref\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    indexer_minor_ref(const matrix_type& ma) : ma(ma) {} \n    \n    typename Matrix::size_type operator() (key_type const& key) const\n    {\n\treturn ma.indexer.minor_from_offset(ma, key.offset);\n    }\n    const matrix_type& ma;\n};\n\n    \ntemplate <class Matrix> struct indexer_col_ref\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    indexer_col_ref(const matrix_type& ma) : ma(ma) {} \n    \n    typename Matrix::size_type operator() (key_type const& key) const\n    {\n\treturn ma.indexer.col(ma, key);\n    }\n    const matrix_type& ma;\n};\n\n\ntemplate <class Matrix> struct col_in_key\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    col_in_key(const matrix_type&) {} \n    \n    typename Matrix::size_type operator() (key_type const& key) const\n    {\n\treturn key.col();\n    }\n};\n\n// functor to access columns using the key itself\ntemplate <class Matrix> struct col_in_element_key\n{\n    typedef Matrix                      matrix_type;\n    col_in_element_key(const matrix_type&) {} \n    \n    template <typename Key>\n    typename Matrix::size_type operator() (Key const& key) const\n    {\n\treturn key.indices[1];\n    }\n};\n\n// Collection must be derived from contiguous_memory_block\n// key must contain pointer\ntemplate <class Collection> struct index_from_offset\n{\n    typedef Collection                      collection_type;\n    \n    index_from_offset(const collection_type& coll) : coll(coll) {} \n\n    template <typename Key>\n    typename Collection::size_type operator() (Key const& key) const\n    {\n\treturn coll.offset(&*key);\n    }\nprivate:\n    const collection_type& coll;\n};\n\ntemplate <typename Matrix>\nstruct const_value_from_other\n{\n    typedef typename Matrix::other     other;\n    typedef typename other::key_type   key_type;\n    typedef typename other::value_type value_type;\n\n    explicit const_value_from_other(Matrix const& matrix) \n\t: its_const_value(matrix.ref) {}\n\n    const value_type operator() (key_type const& key) const\n    {\n\treturn its_const_value(key);\n    }\n\n  protected:\n    typename traits::const_value<typename boost::remove_const<other>::type>::type  its_const_value;\n};\n\n\n\n\ntemplate <typename Matrix>\nstruct value_from_other\n{\n    typedef typename Matrix::other     other;\n    typedef typename other::key_type   key_type;\n    typedef typename other::value_type value_type;\n\n    explicit value_from_other(Matrix const& matrix) \n\t: its_value(matrix.ref) {}\n\n    const value_type operator() (key_type const& key) const\n    {\n\treturn its_value(key);\n    }\n\n    void operator() (key_type const& key, value_type value) const\n    {\n\tits_value(key, value);\n    }\n\n  protected:\n    typename traits::value<other>::type  its_value;\n};\n\n\n// property map to read value if key is referring to value, e.g. pointer\ntemplate <class Matrix> struct direct_const_value\n{\n    direct_const_value(const Matrix&) {} // for compatibility\n    typename Matrix::value_type const operator() (const typename Matrix::key_type key) const\n    {\n\treturn *key;\n    }\n};\n\n    \n// same with writing\ntemplate <class Matrix> struct direct_value \n  : public direct_const_value<Matrix>\n{\n    typedef typename Matrix::value_type value_type;\n\n    direct_value(const Matrix& ma) \n      : direct_const_value<Matrix>(ma) \n    {} // for compatibility\n\n    // May be to be replaced by inserter\n    void operator() (typename Matrix::key_type const& key, value_type value)\n    {\n\t* const_cast<value_type *>(key) = value;\n    }\n\n    // should be inherited\n    typename Matrix::value_type operator() (typename Matrix::key_type const& key) const\n    {\n\treturn *key;\n    }\n};\n\n    \ntemplate <class Matrix> struct matrix_const_value_ref\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    matrix_const_value_ref(const matrix_type& ma) : ma(ma) {} \n    \n    typename Matrix::value_type operator() (key_type const& key) const\n    {\n\treturn ma(key);\n    }\n    const matrix_type& ma;\n};\n\n\ntemplate <class Matrix> struct matrix_value_ref\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    typedef typename Matrix::value_type value_type;\n    matrix_value_ref(matrix_type& ma) : ma(ma) {} \n    \n    typename Matrix::value_type operator() (key_type const& key) const\n    {\n\treturn ma(key);\n    }\n\n    // Much better with inserters\n    void operator() (typename Matrix::key_type const& key, value_type const& value)\n    {\n\tma(key, value);\n    }\n\n    matrix_type& ma;\n};\n\n\ntemplate <class Matrix> struct matrix_offset_const_value\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    matrix_offset_const_value(const matrix_type& ma) : ma(ma) {} \n    \n    typename Matrix::value_type operator() (key_type const& key) const\n    {\n\treturn ma.value_from_offset(key.offset);\n    }\n    const matrix_type& ma;\n};\n\n\ntemplate <class Matrix> struct matrix_offset_value\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    typedef typename Matrix::value_type value_type;\n    matrix_offset_value(matrix_type& ma) : ma(ma) {} \n    \n    typename Matrix::value_type operator() (key_type const& key) const\n    {\n\treturn ma.value_from_offset(key.offset);\n    }\n\n    // Much better with inserters\n    void operator() (typename Matrix::key_type const& key, value_type const& value)\n    {\n\tma.value_from_offset(key.offset) = value;\n    }\n\n    matrix_type& ma;\n};\n\ntemplate <class Matrix> struct offset_from_key\n{\n    typedef Matrix                      matrix_type;\n    typedef typename Matrix::key_type   key_type;\n    typedef typename Matrix::size_type  size_type;\n    offset_from_key(const matrix_type& ) {} \n    \n    size_type operator() (key_type const& key) const\n    {\n\treturn key.offset;\n    }\n};\n\n// functor to access columns using the key itself\ntemplate <class Matrix> struct const_value_in_element_key\n{\n    typedef Matrix                      matrix_type;\n    const_value_in_element_key(const matrix_type&) {} \n    \n    template <typename Key>\n    typename Matrix::value_type operator() (Key const& key) const\n    {\n\treturn key.ref[key.indices[0]][key.indices[1]];\n    }\n};\n\ntemplate <class Value, class Parameters>\nstruct coordinate2D_row\n{\n    typedef const mtl::mat::coordinate2D<Value, Parameters>&       matrix_ref_type;\n    explicit coordinate2D_row(matrix_ref_type A) : A(A) {}\n\n    template <typename Key>\n    typename Parameters::size_type operator() (Key key) const \n    { return A.row_index_array()[key.offset]; }\n\n    matrix_ref_type A;\n};\n\ntemplate <class Value, class Parameters>\nstruct coordinate2D_col\n{\n    typedef const mtl::mat::coordinate2D<Value, Parameters>&       matrix_ref_type;\n    explicit coordinate2D_col(matrix_ref_type A) : A(A) {}\n\n    template <typename Key>\n    typename Parameters::size_type operator() (Key key) const \n    { return A.column_index_array()[key.offset]; }\n\n    matrix_ref_type A;\n};\n\ntemplate <class Value, class Parameters>\nstruct coordinate2D_const_value\n{\n    typedef const mtl::mat::coordinate2D<Value, Parameters>&       matrix_ref_type;\n    explicit coordinate2D_const_value(matrix_ref_type A) : A(A) {}\n\n    template <typename Key>\n    Value operator() (Key key) const \n    { return A.value_array()[key.offset]; }\n\n    matrix_ref_type A;\n};\n\ntemplate <class Value, class Parameters>\nstruct sparse_banded_row  // maybe refactor into sparse_banded_major\n{\n    MTL_STATIC_ASSERT((mtl::traits::is_row_major<Parameters>::value), \"Only row-major sparse banded matrices supported so far.\");\n    typedef const mtl::mat::sparse_banded<Value, Parameters>&  matrix_ref_type;\n    typedef typename Parameters::size_type                        size_type; \n    explicit sparse_banded_row(matrix_ref_type A) : A(A) {}\n\n    template <typename Key>\n    size_type operator() (Key key) const \n    { return key.offset / A.ref_bands().size(); }\n\n    matrix_ref_type A;\n};\n\ntemplate <class Value, class Parameters>\nstruct sparse_banded_col // maybe refactor into sparse_banded_minor\n{\n    MTL_STATIC_ASSERT((mtl::traits::is_row_major<Parameters>::value), \"Only row-major sparse banded matrices supported so far.\");\n    typedef const mtl::mat::sparse_banded<Value, Parameters>&  matrix_ref_type;\n    typedef typename Parameters::size_type                        size_type; \n\n    explicit sparse_banded_col(matrix_ref_type A) : A(A) {}\n\n    template <typename Key>\n    size_type operator() (Key key) const \n    { \n\tsize_type bs= A.ref_bands().size(), major= key.offset / bs, b= key.offset % bs;\n\treturn major + A.ref_bands()[b];\n    }\n\n    matrix_ref_type A;\n};\n\ntemplate <class Value, class Parameters>\nstruct sparse_banded_const_value\n{\n    typedef const mtl::mat::sparse_banded<Value, Parameters>&       matrix_ref_type;\n    explicit sparse_banded_const_value(matrix_ref_type A) : A(A) {}\n\n    template <typename Key>\n    Value operator() (Key key) const \n    { return A.ref_data()[key.offset]; }\n\n    matrix_ref_type A;\n};\n\n\n}} // namespace mtl::detail\n\n\n#endif // MTL_PROPERTY_MAP_IMPL_INCLUDE\n\n\n", "meta": {"hexsha": "21630509a2bda8fc29be205bec8edeb82cc3bf0e", "size": 11770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/utility/property_map_impl.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/utility/property_map_impl.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/utility/property_map_impl.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": 27.2453703704, "max_line_length": 129, "alphanum_fraction": 0.6829226848, "num_tokens": 2685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.03514484829564469, "lm_q1q2_score": 0.012004865123206787}}
{"text": "/****************************************************************************/\n/* Copyright 2005-2006, Francis Russell                                     */\n/*                                                                          */\n/* Licensed under the Apache License, Version 2.0 (the License);            */\n/* you may not use this file except in compliance with the License.         */\n/* You may obtain a copy of the License at                                  */\n/*                                                                          */\n/*     http://www.apache.org/licenses/LICENSE-2.0                           */\n/*                                                                          */\n/* Unless required by applicable law or agreed to in writing, software      */\n/* distributed under the License is distributed on an AS IS BASIS,          */\n/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */\n/* See the License for the specific language governing permissions and      */\n/* limitations under the License.                                           */\n/*                                                                          */\n/****************************************************************************/\n\n#ifndef DESOLA_TG_CODE_GENERATOR_HPP\n#define DESOLA_TG_CODE_GENERATOR_HPP\n\n#include <cstddef>\n#include <utility>\n#include <string>\n#include <map>\n#include <algorithm>\n#include <boost/bind.hpp>\n#include <boost/ref.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <TaskGraph>\n#include \"Desola_tg_fwd.hpp\"\n\n//NOTE: The storage for the results is uninitialized, so make sure that\n//      setExpression is used before calling addExpression on any result\n//      element.\n\nnamespace desola\n{\n\nnamespace detail\n{\n\ntemplate<typename T_element>\nclass TGCodeGenerator : public TGExpressionNodeVisitor<T_element>\n{\nprivate:\n  const std::string prefix;\n  NameGenerator& generator;\n\t\n  inline std::string getIndexName()\n  {\n    return generator.getName(prefix);\n  }\n\t\n  static void setMatrixElement(NameGenerator& generator, TGMatrix<T_element>& matrix, const std::pair<const TGElementIndex<tg_matrix>, TGOutputReference<tg_scalar, T_element> >& pair)\n  {\n    matrix.setExpression(generator, tg::TaskExpression(pair.first.getRow()), tg::TaskExpression(pair.first.getCol()), pair.second.getInternal().getExpression());\n  }\n\n  static void setVectorElement(NameGenerator& generator, TGVector<T_element>& vector, const std::pair<const TGElementIndex<tg_vector>, TGOutputReference<tg_scalar, T_element> >& pair)\n  {\n    vector.setExpression(tg::TaskExpression(pair.first.getRow()), pair.second.getInternal().getExpression());\n  }\n\n  static void matrixVectorMultKernel(NameGenerator& generator, \n    TGVector<T_element>& lhs, TGVector<T_element>& rhs, \n    const tg::TaskExpression& row, const tg::TaskExpression& col, \n    const TGScalarExpr<T_element>& value, const bool transpose)\n  {\n    if (!transpose)\n      rhs.addExpression(row, value.mul(lhs.getExpression(col)));\n    else\n      rhs.addExpression(col, value.mul(lhs.getExpression(row)));\n\n  }\n\n  static void matrixMultiVectorMultKernel(NameGenerator& generator, \n    const std::vector<boost::tuple<TGVector<T_element>*, TGVector<T_element>*, bool> >& vectors, \n    const tg::TaskExpression& row, const tg::TaskExpression& col, \n    const TGScalarExpr<T_element>& value)\n  {\n    for(std::size_t index=0; index<vectors.size(); ++index)\n    {\n      if (!boost::get<2>(vectors[index]))\n        boost::get<1>(vectors[index])->addExpression(row, value.mul(boost::get<0>(vectors[index])->getExpression(col)));\n      else\n        boost::get<1>(vectors[index])->addExpression(col, value.mul(boost::get<0>(vectors[index])->getExpression(row)));\n    }\n  }\n\n\n  static void matrixMultKernel(NameGenerator& generator, TGMatrix<T_element>& b, TGMatrix<T_element>& c, const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_element>& value)\n  {\n    using namespace tg;\n\n    tVarNamed(unsigned, j, generator.getName(\"mat_mult_inner\").c_str());\n    tFor(j, 0u, c.getCols()-1)\n    {\n      c.addExpression(generator, row, j, value.mul(b.getExpression(generator, col, j)));\n    }\n  }\n\npublic:\n  TGCodeGenerator(TGExpressionGraph<T_element>& g) : prefix(\"index\"), generator(g.getNameGenerator())\n  {\n  }\n  \n  virtual void visit(TGElementSet<tg_vector, T_element>& e)\n  {\n    using namespace tg;\n\n    TGVector<T_element>&  newVector(e.getInternal());\n    TGVector<T_element>&  vector(e.getOperand().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tFor(i, 0u, vector.getRows()-1)\n    {\n      newVector.setExpression(i, vector.getExpression(i));\n    }\n\n    const std::map<TGElementIndex<tg_vector>, TGOutputReference<tg_scalar, T_element> > assignments(e.getAssignments());\n    std::for_each(assignments.begin(), assignments.end(), boost::bind(setVectorElement, boost::ref(generator), boost::ref(newVector), _1));\n  }\n\n  virtual void visit(TGElementSet<tg_matrix, T_element>& e)\n  {\n    using namespace tg;\n\n    TGMatrix<T_element>& newMatrix(e.getInternal());\n    TGMatrix<T_element>& matrix(e.getOperand().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n\n    tFor(i, 0u, matrix.getRows()-1)\n    {\n      tFor(j, 0u, matrix.getCols()-1)\n      {\n        newMatrix.setExpression(generator, i, j, matrix.getExpression(generator, i, j));\n      }\n    }\n\n    const std::map<TGElementIndex<tg_matrix>, TGOutputReference<tg_scalar, T_element> > assignments(e.getAssignments());\n    std::for_each(assignments.begin(), assignments.end(), boost::bind(setMatrixElement, boost::ref(generator), boost::ref(newMatrix), _1));\n  }\n\n  virtual void visit(TGElementGet<tg_vector, T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGVector<T_element>& vector(e.getOperand().getInternal());\n\n    result.setExpression(vector.getExpression(TaskExpression(e.getIndex().getRow())));\n  }\n \n  virtual void visit(TGElementGet<tg_matrix, T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGMatrix<T_element>& matrix(e.getOperand().getInternal());\n\n    result.setExpression(matrix.getExpression(generator, TaskExpression(e.getIndex().getRow()), TaskExpression(e.getIndex().getCol())));\n  }\n\n  virtual void visit(TGLiteral<tg_scalar, T_element>& e)\n  {\n  }\n  virtual void visit(TGLiteral<tg_vector, T_element>& e)\n  {\n  }\n \n  virtual void visit(TGLiteral<tg_matrix, T_element>& e)\n  {\n  }\n\n\n  //NOTE: These loops have been structured to try to obtain good cache usage assuming\n  //      row major storage.  If IR optimisation works, a more naive implementation\n  //      of matrix multiply can be used instead and it will be automatically\n  //      optimised for best cache locality.\n\n  virtual void visit(TGMatrixMult<T_element>& e)\n  {\n    using namespace tg;\n\t \n    TGMatrix<T_element>& a(e.getLeft().getInternal());\n    TGMatrix<T_element>& b(e.getRight().getInternal());\n    TGMatrix<T_element>& c(e.getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n    tVarNamed(unsigned, k, getIndexName().c_str());\n\n    tFor(i, 0u, c.getRows()-1)\n    {\n      tFor(j, 0u, c.getCols()-1)\n      {\n        c.setExpression(generator, i, j, TGScalarExpr<T_element>());\n      }\n    }\n    \n    typename TGMatrix<T_element>::MatrixIterationCallback kernel;\n    kernel = boost::bind(matrixMultKernel, _1, boost::ref(b), boost::ref(c), _2, _3, _4);\n    a.iterateSparse(generator, kernel);\n  }\n \n  virtual void visit(TGMatrixVectorMult<T_element>& e)\n  {\n    using namespace tg;\n\n    TGVector<T_element>& result(e.getInternal());\n    TGMatrix<T_element>& matrix(e.getLeft().getInternal());\n    TGVector<T_element>& vector(e.getRight().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n\n    tFor(i, 0u, matrix.getRows()-1)\n    {\n      result.setExpression(i, TGScalarExpr<T_element>());\n    }\n\n    typename TGMatrix<T_element>::MatrixIterationCallback kernel =\n      boost::bind(matrixVectorMultKernel, _1, boost::ref(vector), boost::ref(result), _2, _3, _4, e.isTranspose());\n\n    matrix.iterateSparse(generator, kernel);\n  }\n  \n  virtual void visit(TGMatrixMultiVectorMult<T_element>& e)\n  {\n    using namespace tg;\n\n    TGMatrix<T_element>& matrix(e.getMatrix().getInternal());\n    std::vector< boost::tuple<TGVector<T_element>*, TGVector<T_element>*, bool> > vectors;\n\n    const std::size_t numVectors = e.getNumVectors();\n\n    for(std::size_t index = 0; index < numVectors; ++index)\n      vectors.push_back(boost::make_tuple(&e.getVector(index).getInternal(), \n                        boost::get<TGVector<T_element>*>(e.getInternal(index)),\n                        e.isTranspose(index)));\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n\n    tFor(i, 0u, matrix.getRows()-1)\n    {\n      for(std::size_t index = 0; index < numVectors; ++index)\n        boost::get<1>(vectors[index])->setExpression(i, TGScalarExpr<T_element>());\n    }\n\n    typename TGMatrix<T_element>::MatrixIterationCallback kernel =\n      boost::bind(matrixMultiVectorMultKernel, _1, boost::ref(vectors), _2, _3, _4);\n\n    matrix.iterateSparse(generator, kernel);\n  }\n\n  virtual void visit(TGVectorDot<T_element>& e)\n  {\n    using namespace tg;\n\t \n    TGScalar<T_element>& result(e.getInternal());\n    TGVector<T_element>& left(e.getLeft().getInternal());\n    TGVector<T_element>& right(e.getRight().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n\n    result.setExpression(TGScalarExpr<T_element>());\n    tFor(i, 0u, left.getRows()-1)\n    {\n      result.addExpression(left.getExpression(i).mul(right.getExpression(i)));\n    }\n  }\n \n  virtual void visit(TGVectorCross<T_element>& e)\n  {\n    using namespace tg;\n\n    TGVector<T_element>& result(e.getInternal());\n    TGVector<T_element>& left(e.getLeft().getInternal());\n    TGVector<T_element>& right(e.getRight().getInternal());\n\n    result.setExpression(TaskExpression(0), left.getExpression(1).mul(right.getExpression(2)).sub(right.getExpression(1).mul(left.getExpression(2))));\n    result.setExpression(TaskExpression(1), left.getExpression(2).mul(right.getExpression(0)).sub(right.getExpression(2).mul(left.getExpression(0))));\n    result.setExpression(TaskExpression(2), left.getExpression(0).mul(right.getExpression(1)).sub(right.getExpression(0).mul(left.getExpression(1))));\n  }\n \n  virtual void visit(TGVectorTwoNorm<T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGVector<T_element>& vector(e.getOperand().getInternal());\n   \n    tVarNamed(unsigned, i, getIndexName().c_str());\n\n    result.setExpression(TGScalarExpr<T_element>());\n    tFor(i, 0u, vector.getRows()-1)\n    {\n      result.addExpression(vector.getExpression(i).mul(vector.getExpression(i)));\n    }\n    result.setExpression(result.getExpression().sqrt());\n  }\n \n  virtual void visit(TGMatrixTranspose<T_element>& e)\n  {\n    using namespace tg;\n\n    TGMatrix<T_element>& result(e.getInternal());\n    TGMatrix<T_element>& matrix(e.getOperand().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n\n    tFor(i, 0u, matrix.getRows()-1)\n    {\n      tFor(j, 0u, matrix.getCols()-1)\n      {\n        result.setExpression(generator, j, i, matrix.getExpression(generator, i, j));\n      }\n    }\n  }\n\n  virtual void visit(TGPairwise<tg_scalar, T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGScalar<T_element>& left(e.getLeft().getInternal());\n    TGScalar<T_element>& right(e.getRight().getInternal());\n\n    result.setExpression(performOp(e.getOperation(), left.getExpression(), right.getExpression()));\n  }\n \n  virtual void visit(TGPairwise<tg_vector, T_element>& e)\n  {\n     using namespace tg;\n\n     TGVector<T_element>& result(e.getInternal());\n     TGVector<T_element>& left(e.getLeft().getInternal());\n     TGVector<T_element>& right(e.getRight().getInternal());\n\n     tVarNamed(unsigned, i, getIndexName().c_str());\n     tFor(i, 0u, result.getRows()-1)\n     {\n       result.setExpression(i, performOp(e.getOperation(), left.getExpression(i), right.getExpression(i)));\n     }\n  }\n \n  virtual void visit(TGPairwise<tg_matrix, T_element>& e)\n  {\n    using namespace tg;\n\n    TGMatrix<T_element>& result(e.getInternal());\n    TGMatrix<T_element>& left(e.getLeft().getInternal());\n    TGMatrix<T_element>& right(e.getRight().getInternal());\n   \n      \n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n    tFor(i, 0u, result.getRows()-1)\n    {\n      tFor(j, 0u, result.getCols()-1)\n      {\n        result.setExpression(generator, i, j, performOp(e.getOperation(), left.getExpression(generator, i, j), right.getExpression(generator, i, j)));\n      }\n    }\n  }\n\n  virtual void visit(TGScalarPiecewise<tg_scalar, T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGScalar<T_element>& left(e.getLeft().getInternal());\n    TGScalar<T_element>& right(e.getRight().getInternal());\n\n    result.setExpression(performOp(e.getOperation(), left.getExpression(), right.getExpression()));\t       \n  }\n \n  virtual void visit(TGScalarPiecewise<tg_vector, T_element>& e)\n  {\n     using namespace tg;\n\n     TGVector<T_element>& result(e.getInternal());\n     TGVector<T_element>& left(e.getLeft().getInternal());\n     TGScalar<T_element>& right(e.getRight().getInternal());\n\n     tVarNamed(unsigned, i, getIndexName().c_str());\n     tFor(i, 0u, result.getRows()-1)\n     {\n       result.setExpression(i, performOp(e.getOperation(), left.getExpression(i), right.getExpression()));\n     }\t\t\t\n  }\n \n  virtual void visit(TGScalarPiecewise<tg_matrix, T_element>& e)\n  {\n    using namespace tg;\n\n    TGMatrix<T_element>& result(e.getInternal());\n    TGMatrix<T_element>& left(e.getLeft().getInternal());\n    TGScalar<T_element>& right(e.getRight().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n    tFor(i, 0u, result.getRows()-1)\n    {\n      tFor(j, 0u, result.getCols()-1)\n      {\n        result.setExpression(generator, i, j, performOp(e.getOperation(), left.getExpression(generator, i, j), right.getExpression()));\n      }\n    }\t\t    \n  }\n\n  virtual void visit(TGNegate<tg_scalar, T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGScalar<T_element>& operand(e.getOperand().getInternal());\n\n    result.setExpression(operand.getExpression().negate()); \n  }\n  \n  virtual void visit(TGNegate<tg_vector, T_element>& e)\n  {\n    using namespace tg;\n\n    TGVector<T_element>& result(e.getInternal());\n    TGVector<T_element>& operand(e.getOperand().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tFor(i, 0u, result.getRows()-1)\n    {\n      result.setExpression(i, operand.getExpression(i).negate());\n    }\n  }\n  \n  virtual void visit(TGNegate<tg_matrix, T_element>& e)\n  {\n    using namespace tg;\n\n    TGMatrix<T_element>& result(e.getInternal());\n    TGMatrix<T_element>& operand(e.getOperand().getInternal());\n\n    tVarNamed(unsigned, i, getIndexName().c_str());\n    tVarNamed(unsigned, j, getIndexName().c_str());\n    tFor(i, 0u, result.getRows()-1)\n    {\n      tFor(j, 0u, result.getCols()-1)\n      {\n        result.setExpression(generator, i, j, operand.getExpression(generator, i, j).negate());\n      }\n    }\n  }\n\n  virtual void visit(TGAbsolute<T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGScalar<T_element>& operand(e.getOperand().getInternal());\n\n    result.setExpression(operand.getExpression().abs());\n  }\n\n  virtual void visit(TGSquareRoot<T_element>& e)\n  {\n    using namespace tg;\n\n    TGScalar<T_element>& result(e.getInternal());\n    TGScalar<T_element>& operand(e.getOperand().getInternal());\n    \n    result.setExpression(operand.getExpression().sqrt());\n  }\n\nprivate:\n  static inline TGScalarExpr<T_element> performOp(const TGPairwiseOp op, const TGScalarExpr<T_element>& left, const TGScalarExpr<T_element>& right)\n  {\n    switch(op)\n    {\n      case tg_pair_add: return left.add(right);\n      case tg_pair_sub: return left.sub(right);\n      case tg_pair_mul: return left.mul(right);\n      case tg_pair_div: return left.div(right);\n      default: throw TGInvalidOperationError(\"Unrecognised TaskGraph Evaluator Pairwise Operation\"); \n    }\n  }\n\n  static inline TGScalarExpr<T_element> performOp(const TGScalarPiecewiseOp op, const TGScalarExpr<T_element>& left, const TGScalarExpr<T_element>& right)\n  {\n    switch(op)\n    {\n      case tg_piecewise_multiply: return left.mul(right);\n      case tg_piecewise_divide: return left.div(right);\n      case tg_piecewise_assign: return right;\n      default: throw TGInvalidOperationError(\"Unrecognised TaskGraph Evaluator ScalarPiecewise Operation\");\n    }\n  }\n};\n\n}\n\n}\n#endif\n", "meta": {"hexsha": "cbb8ccb464b6b2257e41356f1950a1a18c5952aa", "size": 17140, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/desola/tg/CodeGenerator.hpp", "max_stars_repo_name": "FrancisRussell/desola", "max_stars_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T10:46:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T11:53:50.000Z", "max_issues_repo_path": "include/desola/tg/CodeGenerator.hpp", "max_issues_repo_name": "FrancisRussell/desola", "max_issues_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "max_issues_repo_licenses": ["Apache-2.0"], "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/desola/tg/CodeGenerator.hpp", "max_forks_repo_name": "FrancisRussell/desola", "max_forks_repo_head_hexsha": "a469428466e4849c7c0e2009a0c50b89184cae01", "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.8067061144, "max_line_length": 204, "alphanum_fraction": 0.6599766628, "num_tokens": 4097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.03210070590678825, "lm_q1q2_score": 0.012001677384551195}}
{"text": "// Copyright (C) 2009-2011 Anders Logg\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// Modified by Marie E. Rognes, 2010\n// Modified by Garth N. Wells, 2010\n//\n// First added:  2009-12-08\n// Last changed: 2011-11-12\n//\n\n#include <vector>\n#include <armadillo>\n\n#include <dolfin/common/Array.h>\n#include <dolfin/common/Timer.h>\n#include <dolfin/fem/BasisFunction.h>\n#include <dolfin/fem/DofMap.h>\n#include <dolfin/fem/DirichletBC.h>\n#include <dolfin/function/Function.h>\n#include <dolfin/function/FunctionSpace.h>\n#include <dolfin/la/GenericVector.h>\n#include <dolfin/log/log.h>\n#include <dolfin/mesh/BoundaryMesh.h>\n#include <dolfin/mesh/Cell.h>\n#include <dolfin/mesh/FacetCell.h>\n#include \"Extrapolation.h\"\n\nusing namespace dolfin;\n\n//-----------------------------------------------------------------------------\nvoid Extrapolation::extrapolate(Function& w, const Function& v)\n{\n  // Using set_local for simplicity here\n  not_working_in_parallel(\"Extrapolation\");\n\n  // Too verbose\n  //info(\"Extrapolating function: %s --> %s\",\n  //     v.function_space().element().signature().c_str(),\n  //     w.function_space().element().signature().c_str());\n\n  // Check that the meshes are the same\n  if (w.function_space()->mesh() != v.function_space()->mesh())\n  {\n    dolfin_error(\"Extrapolation.cpp\",\n                 \"compute extrapolation\",\n                 \"Extrapolation must be computed on the same mesh\");\n  }\n\n  // Extract mesh and function spaces\n  const FunctionSpace& V = *v.function_space();\n  const FunctionSpace& W = *w.function_space();\n  dolfin_assert(V.mesh());\n  const Mesh& mesh = *V.mesh();\n\n  // Initialize cell-cell connectivity\n  const uint D = mesh.topology().dim();\n  mesh.init(D, D);\n\n  // UFC cell view of center cell\n  UFCCell c0(mesh);\n\n  // List of values for each dof of w (multivalued until we average)\n  std::vector<std::vector<double> > coefficients;\n  coefficients.resize(W.dim());\n\n  // Local array for dof indices\n  dolfin_assert(W.dofmap());\n  std::vector<uint> dofs(W.dofmap()->max_cell_dimension());\n\n  // Iterate over cells in mesh\n  for (CellIterator cell0(mesh); !cell0.end(); ++cell0)\n  {\n    // Update UFC view\n    c0.update(*cell0);\n\n    // Tabulate dofs for w on cell and store values\n    W.dofmap()->tabulate_dofs(&dofs[0], *cell0);\n\n    // Compute coefficients on this cell\n    uint offset = 0;\n    compute_coefficients(coefficients, v, V, W, *cell0, c0, dofs, offset);\n  }\n\n  // Average coefficients\n  average_coefficients(w, coefficients);\n}\n//-----------------------------------------------------------------------------\nvoid Extrapolation::compute_coefficients(std::vector<std::vector<double> >& coefficients,\n                                         const Function& v,\n                                         const FunctionSpace& V,\n                                         const FunctionSpace& W,\n                                         const Cell& cell0,\n                                         const ufc::cell& c0,\n                                         const std::vector<uint>& dofs,\n                                         uint& offset)\n{\n  // Call recursively for mixed elements\n  dolfin_assert(V.element());\n  const uint num_sub_spaces = V.element()->num_sub_elements();\n  if (num_sub_spaces > 0)\n  {\n    for (uint k = 0; k < num_sub_spaces; k++)\n    {\n      compute_coefficients(coefficients, v[k], *V[k], *W[k], cell0, c0,\n                           dofs, offset);\n    }\n    return;\n  }\n\n  // Build data structures for keeping track of unique dofs\n  std::map<uint, std::map<uint, uint> > cell2dof2row;\n  std::set<uint> unique_dofs;\n  build_unique_dofs(unique_dofs, cell2dof2row, cell0, c0, V);\n\n  // Compute size of linear system\n  dolfin_assert(W.element());\n  const uint N = W.element()->space_dimension();\n  const uint M = unique_dofs.size();\n\n  // Check size of system\n  if (M < N)\n  {\n    dolfin_error(\"Extrapolation.cpp\",\n                 \"compute extrapolation\",\n                 \"Not enough degrees of freedom on local patch to build extrapolation\");\n  }\n\n  // Create matrix and vector for linear system\n  arma::mat A(M, N);\n  arma::vec b(M);\n\n  // Add equations on cell and neighboring cells\n  add_cell_equations(A, b, cell0, cell0, c0, c0, V, W, v, cell2dof2row[cell0.index()]);\n  dolfin_assert(V.mesh());\n  UFCCell c1(*V.mesh());\n  for (CellIterator cell1(cell0); !cell1.end(); ++cell1)\n  {\n    if (cell2dof2row[cell1->index()].size() == 0)\n      continue;\n\n    c1.update(*cell1);\n    add_cell_equations(A, b, cell0, *cell1, c0, c1, V, W, v, cell2dof2row[cell1->index()]);\n  }\n\n  // Solve least squares system\n  arma::Col<double> x = arma::solve(A, b);\n\n  // Insert resulting coefficients into global coefficient vector\n  dolfin_assert(W.dofmap());\n  for (uint i = 0; i < W.dofmap()->cell_dimension(cell0.index()); ++i)\n    coefficients[dofs[i + offset]].push_back(x[i]);\n\n  // Increase offset\n  offset += W.dofmap()->cell_dimension(cell0.index());\n}\n//-----------------------------------------------------------------------------\nvoid Extrapolation::build_unique_dofs(std::set<uint>& unique_dofs,\n                                      std::map<uint, std::map<uint, uint> >& cell2dof2row,\n                                      const Cell& cell0,\n                                      const ufc::cell& c0,\n                                      const FunctionSpace& V)\n{\n  // Counter for matrix row index\n  uint row = 0;\n  dolfin_assert(V.mesh());\n  UFCCell c1(*V.mesh());\n\n  // Compute unique dofs on center cell\n  cell2dof2row[cell0.index()] = compute_unique_dofs(cell0, c0, V, row, unique_dofs);\n\n  // Compute unique dofs on neighbouring cells\n  for (CellIterator cell1(cell0); !cell1.end(); ++cell1)\n  {\n    c1.update(*cell1);\n    cell2dof2row[cell1->index()] = compute_unique_dofs(*cell1, c1, V, row, unique_dofs);\n  }\n}\n//-----------------------------------------------------------------------------\nvoid Extrapolation::add_cell_equations(arma::Mat<double>& A,\n                                       arma::Col<double>& b,\n                                       const Cell& cell0,\n                                       const Cell& cell1,\n                                       const ufc::cell& c0,\n                                       const ufc::cell& c1,\n                                       const FunctionSpace& V,\n                                       const FunctionSpace& W,\n                                       const Function& v,\n                                       std::map<uint, uint>& dof2row)\n{\n  // Extract coefficents for v on patch cell\n  dolfin_assert(V.element());\n  std::vector<double> dof_values(V.element()->space_dimension());\n  v.restrict(&dof_values[0], *V.element(), cell1, c1);\n\n  // Iterate over given local dofs for V on patch cell\n  dolfin_assert(W.element());\n  for (std::map<uint, uint>::iterator it = dof2row.begin(); it!= dof2row.end(); it++)\n  {\n    const uint i = it->first;\n    const uint row = it->second;\n\n    // Iterate over basis functions for W on center cell\n    for (uint j = 0; j < W.element()->space_dimension(); ++j)\n    {\n\n      // Create basis function\n      const BasisFunction phi(j, *W.element(), c0);\n\n      // Evaluate dof on basis function\n      const double dof_value = V.element()->evaluate_dof(i, phi, c1);\n\n      // Insert dof_value into matrix\n      A(row, j) = dof_value;\n    }\n\n    // Insert coefficient into vector\n    b[row] = dof_values[i];\n  }\n}\n//-----------------------------------------------------------------------------\nstd::map<dolfin::uint, dolfin::uint>\nExtrapolation::compute_unique_dofs(const Cell& cell, const ufc::cell& c,\n                                   const FunctionSpace& V,\n                                   uint& row,\n                                   std::set<uint>& unique_dofs)\n{\n  dolfin_assert(V.dofmap());\n\n  std::vector<uint> dofs(V.dofmap()->cell_dimension(cell.index()));\n  V.dofmap()->tabulate_dofs(&dofs[0], cell);\n\n  // Data structure for current cell\n  std::map<uint, uint> dof2row;\n\n  for (uint i = 0; i < V.dofmap()->cell_dimension(cell.index()); ++i)\n  {\n    // Ignore if this degree of freedom is already considered\n    if (unique_dofs.find(dofs[i]) != unique_dofs.end())\n      continue;\n\n    // Put global index into unique_dofs\n    unique_dofs.insert(dofs[i]);\n\n    // Map local dof index to current matrix row-index\n    dof2row[i] = row;\n\n    // Increase row index\n    row++;\n  }\n\n  return dof2row;\n}\n//-----------------------------------------------------------------------------\nvoid Extrapolation::average_coefficients(Function& w,\n                               std::vector<std::vector<double> >& coefficients)\n{\n  const FunctionSpace& W = *w.function_space();\n  Array<double> dof_values(W.dim());\n\n  for (uint i = 0; i < W.dim(); i++)\n  {\n    double s = 0.0;\n    for (uint j = 0; j < coefficients[i].size(); ++j)\n      s += coefficients[i][j];\n    s /= static_cast<double>(coefficients[i].size());\n    dof_values[i] = s;\n  }\n\n  // Update dofs for w\n  dolfin_assert(w.vector());\n  w.vector()->set_local(dof_values);\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "2303b32526e3cf05c8d0e173ed78ae3f0d662e02", "size": 9736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/adaptivity/Extrapolation.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/adaptivity/Extrapolation.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/adaptivity/Extrapolation.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.8055555556, "max_line_length": 91, "alphanum_fraction": 0.5678923583, "num_tokens": 2367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.03622005742549128, "lm_q1q2_score": 0.011993175984075791}}
{"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/build_manifold.hpp\n * @brief Macro to automatically construct compound manifolds.\n *\n */\n#ifndef MTK_AUTOCONSTRUCT_HPP_\n#define MTK_AUTOCONSTRUCT_HPP_\n\n#include <vector>\n\n#include <Eigen/Core>\n#include <boost/preprocessor/cat.hpp>\n#include <boost/preprocessor/seq.hpp>\n\n#include \"src/SubManifold.hpp\"\n#include \"startIdx.hpp\"\n\n#ifndef PARSED_BY_DOXYGEN\n//////// internals //////\n\n#define MTK_APPLY_MACRO_ON_TUPLE(r, macro, tuple) macro tuple\n\n#define MTK_TRANSFORM_COMMA(macro, entries) \\\n    BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM_S(1, MTK_APPLY_MACRO_ON_TUPLE, macro, entries))\n\n#define MTK_TRANSFORM(macro, entries) BOOST_PP_SEQ_FOR_EACH_R(1, MTK_APPLY_MACRO_ON_TUPLE, macro, entries)\n\n#define MTK_CONSTRUCTOR_ARG(type, id) const type& id = type()\n#define MTK_CONSTRUCTOR_COPY(type, id) id(id)\n#define MTK_BOXPLUS(type, id) id.boxplus(MTK::subvector(__vec, &self::id), __scale);\n#define MTK_OPLUS(type, id) id.oplus(MTK::subvector_(__vec, &self::id), __scale);\n#define MTK_BOXMINUS(type, id) id.boxminus(MTK::subvector(__res, &self::id), __oth.id);\n#define MTK_S2_hat(type, id) \\\n    if (id.IDX == idx) {     \\\n        id.S2_hat(res);      \\\n    }\n#define MTK_S2_Nx_yy(type, id) \\\n    if (id.IDX == idx) {       \\\n        id.S2_Nx_yy(res);      \\\n    }\n#define MTK_S2_Mx(type, id) \\\n    if (id.IDX == idx) {    \\\n        id.S2_Mx(res, dx);  \\\n    }\n#define MTK_OSTREAM(type, id) << __var.id << \" \"\n#define MTK_ISTREAM(type, id) >> __var.id\n#define MTK_S2_state(type, id)                              \\\n    if (id.TYP == 1) {                                      \\\n        S2_state.push_back(std::make_pair(id.IDX, id.DIM)); \\\n    }\n#define MTK_SO3_state(type, id)                                \\\n    if (id.TYP == 2) {                                         \\\n        (SO3_state).push_back(std::make_pair(id.IDX, id.DIM)); \\\n    }\n#define MTK_vect_state(type, id)                                                           \\\n    if (id.TYP == 0) {                                                                     \\\n        (vect_state).push_back(std::make_pair(std::make_pair(id.IDX, id.DIM), type::DOF)); \\\n    }\n\n#define MTK_SUBVARLIST(seq, S2state, SO3state)                                                                \\\n    BOOST_PP_FOR_1(                                                                                           \\\n        (BOOST_PP_SEQ_SIZE(seq), BOOST_PP_SEQ_HEAD(seq), BOOST_PP_SEQ_TAIL(seq)(~), 0, 0, S2state, SO3state), \\\n        MTK_ENTRIES_TEST, MTK_ENTRIES_NEXT, MTK_ENTRIES_OUTPUT)\n\n#define MTK_PUT_TYPE(type, id, dof, dim, S2state, SO3state) MTK::SubManifold<type, dof, dim> id;\n#define MTK_PUT_TYPE_AND_ENUM(type, id, dof, dim, S2state, SO3state) \\\n    MTK_PUT_TYPE(type, id, dof, dim, S2state, SO3state)              \\\n    enum { DOF = type::DOF + dof };                                  \\\n    enum { DIM = type::DIM + dim };                                  \\\n    typedef type::scalar scalar;\n\n#define MTK_ENTRIES_OUTPUT(r, state) MTK_ENTRIES_OUTPUT_I state\n#define MTK_ENTRIES_OUTPUT_I(s, head, seq, dof, dim, S2state, SO3state)                            \\\n    MTK_APPLY_MACRO_ON_TUPLE(~, BOOST_PP_IF(BOOST_PP_DEC(s), MTK_PUT_TYPE, MTK_PUT_TYPE_AND_ENUM), \\\n                             (BOOST_PP_TUPLE_REM_2 head, dof, dim, S2state, SO3state))\n\n#define MTK_ENTRIES_TEST(r, state) MTK_TUPLE_ELEM_4_0 state\n\n//! this used to be BOOST_PP_TUPLE_ELEM_4_0:\n#define MTK_TUPLE_ELEM_4_0(a, b, c, d, e, f, g) a\n\n#define MTK_ENTRIES_NEXT(r, state) MTK_ENTRIES_NEXT_I state\n#define MTK_ENTRIES_NEXT_I(len, head, seq, dof, dim, S2state, SO3state)                                          \\\n    (BOOST_PP_DEC(len), BOOST_PP_SEQ_HEAD(seq), BOOST_PP_SEQ_TAIL(seq), dof + BOOST_PP_TUPLE_ELEM_2_0 head::DOF, \\\n     dim + BOOST_PP_TUPLE_ELEM_2_0 head::DIM, S2state, SO3state)\n\n#endif /* not PARSED_BY_DOXYGEN */\n\n/**\n * Construct a manifold.\n * @param name is the class-name of the manifold,\n * @param entries is the list of sub manifolds\n *\n * Entries must be given in a list like this:\n * @code\n * typedef MTK::trafo<MTK::SO3<double> > Pose;\n * typedef MTK::vect<double, 3> Vec3;\n * MTK_BUILD_MANIFOLD(imu_state,\n *    ((Pose, pose))\n *    ((Vec3, vel))\n *    ((Vec3, acc_bias))\n * )\n * @endcode\n * Whitespace is optional, but the double parentheses are necessary.\n * Construction is done entirely in preprocessor.\n * After construction @a name is also a manifold. Its members can be\n * accessed by names given in @a entries.\n *\n * @note Variable types are not allowed to have commas, thus types like\n *       @c vect<double, 3> need to be typedef'ed ahead.\n */\n#define MTK_BUILD_MANIFOLD(name, entries)                                                                 \\\n    struct name {                                                                                         \\\n        typedef name self;                                                                                \\\n        std::vector<std::pair<int, int> > S2_state;                                                       \\\n        std::vector<std::pair<int, int> > SO3_state;                                                      \\\n        std::vector<std::pair<std::pair<int, int>, int> > vect_state;                                     \\\n        MTK_SUBVARLIST(entries, S2_state, SO3_state)                                                      \\\n        name(MTK_TRANSFORM_COMMA(MTK_CONSTRUCTOR_ARG, entries))                                           \\\n            : MTK_TRANSFORM_COMMA(MTK_CONSTRUCTOR_COPY, entries) {}                                       \\\n        int getDOF() const { return DOF; }                                                                \\\n        void boxplus(const MTK::vectview<const scalar, DOF>& __vec, scalar __scale = 1) {                 \\\n            MTK_TRANSFORM(MTK_BOXPLUS, entries)                                                           \\\n        }                                                                                                 \\\n        void oplus(const MTK::vectview<const scalar, DIM>& __vec, scalar __scale = 1) {                   \\\n            MTK_TRANSFORM(MTK_OPLUS, entries)                                                             \\\n        }                                                                                                 \\\n        void boxminus(MTK::vectview<scalar, DOF> __res, const name& __oth) const {                        \\\n            MTK_TRANSFORM(MTK_BOXMINUS, entries)                                                          \\\n        }                                                                                                 \\\n        friend std::ostream& operator<<(std::ostream& __os, const name& __var) {                          \\\n            return __os MTK_TRANSFORM(MTK_OSTREAM, entries);                                              \\\n        }                                                                                                 \\\n        void build_S2_state() { MTK_TRANSFORM(MTK_S2_state, entries) }                                    \\\n        void build_vect_state() { MTK_TRANSFORM(MTK_vect_state, entries) }                                \\\n        void build_SO3_state() { MTK_TRANSFORM(MTK_SO3_state, entries) }                                  \\\n        void S2_hat(Eigen::Matrix<scalar, 3, 3>& res, int idx) { MTK_TRANSFORM(MTK_S2_hat, entries) }     \\\n        void S2_Nx_yy(Eigen::Matrix<scalar, 2, 3>& res, int idx) { MTK_TRANSFORM(MTK_S2_Nx_yy, entries) } \\\n        void S2_Mx(Eigen::Matrix<scalar, 3, 2>& res, Eigen::Matrix<scalar, 2, 1> dx, int idx) {           \\\n            MTK_TRANSFORM(MTK_S2_Mx, entries)                                                             \\\n        }                                                                                                 \\\n        friend std::istream& operator>>(std::istream& __is, name& __var) {                                \\\n            return __is MTK_TRANSFORM(MTK_ISTREAM, entries);                                              \\\n        }                                                                                                 \\\n    };\n\n#endif /*MTK_AUTOCONSTRUCT_HPP_*/\n", "meta": {"hexsha": "90d5dfa30927905114d377c55f5693e38b97344e", "size": 11991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/IKFoM_toolkit/mtk/build_manifold.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/build_manifold.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/build_manifold.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": 54.257918552, "max_line_length": 120, "alphanum_fraction": 0.5635893587, "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.031143828623867872, "lm_q1q2_score": 0.011987638302544994}}
{"text": "#include \"CircuitSimulator.hpp\"\n#include \"GroverSimulator.hpp\"\n#include \"HybridSchrodingerFeynmanSimulator.hpp\"\n#include \"ShorFastSimulator.hpp\"\n#include \"ShorSimulator.hpp\"\n#include \"Simulator.hpp\"\n#include \"algorithms/Entanglement.hpp\"\n#include \"algorithms/Grover.hpp\"\n#include \"algorithms/QFT.hpp\"\n#include \"dd/Export.hpp\"\n#include \"nlohmann/json.hpp\"\n\n#include <boost/program_options.hpp>\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n\nnamespace nl = nlohmann;\n\nint main(int argc, char** argv) {\n    namespace po = boost::program_options;\n    // variables initialized by boost program_options default values\n    unsigned long long seed;\n    unsigned int       shots;\n\n    unsigned int                         approx_steps;\n    double                               step_fidelity;\n    ApproximationInfo::ApproximationWhen approx_when;\n\n    HybridSchrodingerFeynmanSimulator::Mode mode = HybridSchrodingerFeynmanSimulator::Mode::Amplitude;\n    unsigned int                            nthreads;\n\n    po::options_description description(\"JKQ DDSIM by https://iic.jku.at/eda/ -- Allowed options\");\n    // clang-format off\n    description.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"seed\", po::value<>(&seed)->default_value(0), \"seed for random number generator (default zero is possibly directly used as seed!)\")\n        (\"shots\", po::value<>(&shots)->default_value(0), \"number of measurements (if the algorithm does not contain non-unitary gates, weak simulation is used)\")\n        (\"pv\", \"display the state vector\")\n        (\"ps\", \"print simulation stats (applied gates, sim. time, and maximal size of the DD)\")\n        (\"pm\", \"print measurement results\")\n        (\"pcomplex\", \"print additional statistics on complex numbers\")\n        (\"dump_complex\", po::value<std::string>(), \"dump edge weights in final state DD to file\")\n        (\"verbose\", \"Causes some simulators to print additional information to STDERR\")\n        (\"simulate_file\", po::value<std::string>(), \"simulate a quantum circuit given by file (detection by the file extension)\")\n        (\"simulate_file_hybrid\", po::value<std::string>(), \"simulate a quantum circuit given by file (detection by the file extension) using the hybrid Schrodinger-Feynman simulator\")\n        (\"hybrid_mode\", po::value<std::string>(), \"mode used for hybrid Schrodinger-Feynman simulation (*amplitude*, dd)\")\n        (\"nthreads\", po::value<>(&nthreads)->default_value(2), \"#threads used for hybrid simulation\")\n        (\"simulate_qft\", po::value<unsigned int>(), \"simulate Quantum Fourier Transform for given number of qubits\")\n        (\"simulate_ghz\", po::value<unsigned int>(), \"simulate state preparation of GHZ state for given number of qubits\")\n        (\"step_fidelity\", po::value<>(&step_fidelity)->default_value(1.0), \"target fidelity for each approximation run (>=1 = disable approximation)\")\n        (\"steps\", po::value<>(&approx_steps)->default_value(1), \"number of approximation steps\")\n        (\"approx_when\", po::value<>(&approx_when)->default_value(ApproximationInfo::FidelityDriven), \"approximation method ('fidelity' (default) or 'memory'\")\n        (\"approx_state\", \"do excessive approximation runs at the end of the simulation to see how the quantum state behaves\")\n        (\"simulate_grover\", po::value<unsigned int>(), \"simulate Grover's search for given number of qubits with random oracle\")\n        (\"simulate_grover_emulated\", po::value<unsigned int>(), \"simulate Grover's search for given number of qubits with random oracle and emulation\")\n        (\"simulate_grover_oracle_emulated\", po::value<std::string>(), \"simulate Grover's search for given number of qubits with given oracle and emulation\")\n        (\"simulate_shor\", po::value<unsigned int>(), \"simulate Shor's algorithm factoring this number\")\n        (\"simulate_shor_coprime\", po::value<unsigned int>()->default_value(0), \"coprime number to use with Shor's algorithm (zero randomly generates a coprime)\")\n        (\"simulate_shor_no_emulation\", \"Force Shor simulator to do modular exponentiation instead of using emulation (you'll usually want emulation)\")\n        (\"simulate_fast_shor\", po::value<unsigned int>(), \"simulate Shor's algorithm factoring this number with intermediate measurements\")\n        (\"simulate_fast_shor_coprime\", po::value<unsigned int>()->default_value(0),\"coprime number to use with Shor's algorithm (zero randomly generates a coprime)\");\n    // clang-format on\n    po::variables_map vm;\n    try {\n        po::store(po::parse_command_line(argc, argv, description), vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << description;\n            return 0;\n        }\n        po::notify(vm);\n    } catch (const po::error& e) {\n        std::cerr << \"[ERROR] \" << e.what() << \"! Try option '--help' for available commandline options.\\n\";\n        std::exit(1);\n    }\n\n    std::unique_ptr<qc::QuantumComputation> quantumComputation;\n    std::unique_ptr<Simulator>              ddsim{nullptr};\n    ApproximationInfo                       approx_info(step_fidelity, approx_steps, approx_when);\n    const bool                              verbose = vm.count(\"verbose\") > 0;\n\n    if (vm.count(\"simulate_file\")) {\n        const std::string fname = vm[\"simulate_file\"].as<std::string>();\n        quantumComputation      = std::make_unique<qc::QuantumComputation>(fname);\n        ddsim                   = std::make_unique<CircuitSimulator>(std::move(quantumComputation), approx_info, seed);\n    } else if (vm.count(\"simulate_file_hybrid\")) {\n        const std::string fname = vm[\"simulate_file_hybrid\"].as<std::string>();\n        quantumComputation      = std::make_unique<qc::QuantumComputation>(fname);\n        if (vm.count(\"hybrid_mode\")) {\n            const std::string mname = vm[\"hybrid_mode\"].as<std::string>();\n            if (mname == \"amplitude\") {\n                mode = HybridSchrodingerFeynmanSimulator::Mode::Amplitude;\n            } else if (mname == \"dd\") {\n                mode = HybridSchrodingerFeynmanSimulator::Mode::DD;\n            }\n        }\n        if (seed != 0) {\n            ddsim = std::make_unique<HybridSchrodingerFeynmanSimulator>(std::move(quantumComputation), approx_info, seed, mode, nthreads);\n        } else {\n            ddsim = std::make_unique<HybridSchrodingerFeynmanSimulator>(std::move(quantumComputation), mode, nthreads);\n        }\n    } else if (vm.count(\"simulate_qft\")) {\n        const unsigned int n_qubits = vm[\"simulate_qft\"].as<unsigned int>();\n        quantumComputation          = std::make_unique<qc::QFT>(n_qubits);\n        ddsim                       = std::make_unique<CircuitSimulator>(std::move(quantumComputation), approx_info, seed);\n    } else if (vm.count(\"simulate_fast_shor\")) {\n        const unsigned int composite_number = vm[\"simulate_fast_shor\"].as<unsigned int>();\n        const unsigned int coprime          = vm[\"simulate_fast_shor_coprime\"].as<unsigned int>();\n        if (seed == 0) {\n            ddsim = std::make_unique<ShorFastSimulator>(composite_number, coprime, verbose);\n        } else {\n            ddsim = std::make_unique<ShorFastSimulator>(composite_number, coprime, seed, verbose);\n        }\n    } else if (vm.count(\"simulate_shor\")) {\n        const unsigned int composite_number = vm[\"simulate_shor\"].as<unsigned int>();\n        const unsigned int coprime          = vm[\"simulate_shor_coprime\"].as<unsigned int>();\n        const bool         emulate          = vm.count(\"simulate_shor_no_emulation\") == 0;\n        if (seed == 0) {\n            ddsim = std::make_unique<ShorSimulator>(composite_number, coprime, emulate, verbose, step_fidelity < 1);\n        } else {\n            ddsim = std::make_unique<ShorSimulator>(composite_number, coprime, seed, emulate, verbose,\n                                                    step_fidelity < 1);\n        }\n    } else if (vm.count(\"simulate_grover\")) {\n        const unsigned int n_qubits = vm[\"simulate_grover\"].as<unsigned int>();\n        quantumComputation          = std::make_unique<qc::Grover>(n_qubits, seed);\n        ddsim                       = std::make_unique<CircuitSimulator>(std::move(quantumComputation), approx_info, seed);\n    } else if (vm.count(\"simulate_grover_emulated\")) {\n        ddsim = std::make_unique<GroverSimulator>(vm[\"simulate_grover_emulated\"].as<unsigned int>(), seed);\n    } else if (vm.count(\"simulate_grover_oracle_emulated\")) {\n        ddsim = std::make_unique<GroverSimulator>(vm[\"simulate_grover_oracle_emulated\"].as<std::string>(), seed);\n    } else if (vm.count(\"simulate_ghz\")) {\n        const unsigned int n_qubits = vm[\"simulate_ghz\"].as<unsigned int>();\n        quantumComputation          = std::make_unique<qc::Entanglement>(n_qubits);\n        ddsim                       = std::make_unique<CircuitSimulator>(std::move(quantumComputation), approx_info, seed);\n    } else {\n        std::cerr << \"Did not find anything to simulate. See help below.\\n\"\n                  << description << \"\\n\";\n        std::exit(1);\n    }\n\n    if (ddsim->getNumberOfQubits() > 100) {\n        std::clog << \"[WARNING] Quantum computation contains quite a few qubits. You're jumping into the deep end.\\n\";\n    }\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n    auto m  = ddsim->Simulate(shots);\n    auto t2 = std::chrono::high_resolution_clock::now();\n\n    std::chrono::duration<float> duration_simulation = t2 - t1;\n\n    if (vm.count(\"approx_state\")) {\n        // TargetFidelity\n        ddsim->ApproximateByFidelity(1 / 100.0, false, false, true);\n        ddsim->ApproximateByFidelity(2 / 100.0, false, false, true);\n        ddsim->ApproximateByFidelity(3 / 100.0, false, false, true);\n        ddsim->ApproximateByFidelity(4 / 100.0, false, false, true);\n        for (int i = 6; i <= 95; i += 2) {\n            ddsim->ApproximateByFidelity(i / 100.0, false, false, true);\n        }\n        ddsim->ApproximateByFidelity(96 / 100.0, false, false, true);\n        ddsim->ApproximateByFidelity(97 / 100.0, false, false, true);\n        ddsim->ApproximateByFidelity(98 / 100.0, false, false, true);\n        ddsim->ApproximateByFidelity(99 / 100.0, false, false, true);\n        ddsim->ApproximateByFidelity(100 / 100.0, false, false, true);\n\n        // TargetFidelityPerLevel\n        ddsim->ApproximateByFidelity(1 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(5 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(10 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(20 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(30 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(40 / 1000.0, true, false, true);\n        for (int i = 50; i <= 950; i += 10) {\n            ddsim->ApproximateByFidelity(i / 1000.0, true, false, true);\n        }\n        ddsim->ApproximateByFidelity(960 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(970 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(980 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(985 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(990 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(995 / 1000.0, true, false, true);\n        ddsim->ApproximateByFidelity(1000 / 1000.0, true, false, true);\n\n        // Traversal\n        for (int i = 1; i < 10; i += 1) {\n            ddsim->ApproximateBySampling(i, 0, false, true);\n        }\n        for (int i = 10; i < 100; i += 10) {\n            ddsim->ApproximateBySampling(i, 0, false, true);\n        }\n        for (int i = 100; i < 1000; i += 100) {\n            ddsim->ApproximateBySampling(i, 0, false, true);\n        }\n        for (int i = 1000; i < 100000; i += 1000) {\n            ddsim->ApproximateBySampling(i, 0, false, true);\n        }\n        for (int i = 100000; i <= 1000000; i += 10000) {\n            ddsim->ApproximateBySampling(i, 0, false, true);\n        }\n\n        // Traversal+Threshold\n        for (int i = 1; i < 10; i += 1) {\n            ddsim->ApproximateBySampling(1000000, i, false, true);\n        }\n        for (int i = 10; i < 100; i += 10) {\n            ddsim->ApproximateBySampling(1000000, i, false, true);\n        }\n\n        for (int i = 100; i <= 5000; i += 100) {\n            ddsim->ApproximateBySampling(1000000, i, false, true);\n        }\n    }\n\n    nl::json output_obj;\n\n    if (vm.count(\"pm\")) {\n        output_obj[\"measurement_results\"] = m;\n    }\n\n    if (vm.count(\"pv\")) {\n        output_obj[\"state_vector\"] = ddsim->getVectorPair();\n    }\n\n    if (vm.count(\"ps\")) {\n        output_obj[\"statistics\"] = {\n                {\"simulation_time\", duration_simulation.count()},\n                {\"benchmark\", ddsim->getName()},\n                {\"n_qubits\", +ddsim->getNumberOfQubits()},\n                {\"applied_gates\", ddsim->getNumberOfOps()},\n                {\"max_nodes\", ddsim->getMaxNodeCount()},\n                {\"shots\", shots},\n                {\"distinct_results\", m.size()},\n                {\"seed\", ddsim->getSeed()},\n        };\n\n        for (const auto& [stat, value]: ddsim->AdditionalStatistics()) {\n            output_obj[\"statistics\"][stat] = value;\n        }\n    }\n\n    if (vm.count(\"pcomplex\")) {\n        output_obj[\"complex_stats\"] = ddsim->dd->cn.complexTable.getStatistics();\n    }\n\n    if (vm.count(\"dump_complex\")) {\n        auto filename = vm[\"dump_complex\"].as<std::string>();\n        auto ostream  = std::fstream(filename, std::fstream::out);\n        dd::exportEdgeWeights(ddsim->root_edge, ostream);\n    }\n\n    std::cout << std::setw(2) << output_obj << std::endl;\n}\n", "meta": {"hexsha": "a602b9862107464853d29df6e24c4864ef8eb01a", "size": 13567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/simple.cpp", "max_stars_repo_name": "iic-jku/ddsim", "max_stars_repo_head_hexsha": "36661b7ec71a6c6f0cbf7abfb67fbba3f192926c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-02-25T16:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T14:31:39.000Z", "max_issues_repo_path": "apps/simple.cpp", "max_issues_repo_name": "iic-jku/ddsim", "max_issues_repo_head_hexsha": "36661b7ec71a6c6f0cbf7abfb67fbba3f192926c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T23:07:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T16:58:49.000Z", "max_forks_repo_path": "apps/simple.cpp", "max_forks_repo_name": "iic-jku/ddsim", "max_forks_repo_head_hexsha": "36661b7ec71a6c6f0cbf7abfb67fbba3f192926c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T00:44:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T21:28:05.000Z", "avg_line_length": 52.7898832685, "max_line_length": 183, "alphanum_fraction": 0.6241615685, "num_tokens": 3581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.02887090579736684, "lm_q1q2_score": 0.011978505492434744}}
{"text": "//------------------------------------------------------------------------------\n/// \\file\n/// \\brief\n/// \\copyright (C) Copyright Aquaveo 2018. Distributed under FreeBSD License\n/// (See accompanying file LICENSE or https://aqaveo.com/bsd/license.txt)\n//------------------------------------------------------------------------------\n\n//----- Included files ---------------------------------------------------------\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <boost/shared_ptr.hpp>\n#include <xmscore/misc/DynBitset.h>\n#include <xmscore/misc/XmError.h>\n#include <xmscore/python/misc/PyUtils.h>\n#include <xmsinterp/triangulate/TrTin.h>\n#include <xmsmesh/meshing/MeMeshUtils.h>\n#include <xmsmesh/meshing/MeMultiPolyMesher.h>\n#include <xmsmesh/meshing/MeMultiPolyMesherIo.h>\n#include <xmsmesh/meshing/MeMultiPolyTo2dm.h>\n#include <xmsmesh/meshing/MePolyRedistributePts.h>\n\n\n//----- Namespace declaration --------------------------------------------------\nnamespace py = pybind11;\n\n//----- Python Interface -------------------------------------------------------\nPYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>);\n\nvoid initMeMeshUtils(py::module &m) {\n\n    py::module modMeshUtils = m.def_submodule(\"mesh_utils\");\n\n\n  // ---------------------------------------------------------------------------\n  // function: size_function_from_depth\n  // ---------------------------------------------------------------------------\n  const char* size_function_from_depth_doc = R\"pydoc(\n      Creates a size at each point based on the depth at the point and the min \n      and max sizes the equation is  min_depth + ( (depth - min_depth) / \n      (max_depth - min_depth) ) * (max_size - min_size). This is often useful for\n      coastal numerical model simulations.\n\n      Args:\n          depths (iterable): The measured depths at point locations\n          min_size (float): The minimum element edge size\n          max_size (float): The maximum element edge size\n\n      Returns:\n        iterable: Array of sizes based on depth\n  )pydoc\";\n    modMeshUtils.def(\"size_function_from_depth\", [](py::iterable depths, double min_size,\n                                         double max_size) -> py::iterable {\n\n        xms::VecDbl vec_depths, vec_size;\n        vec_depths = *xms::VecDblFromPyIter(depths);\n        xms::meSizeFunctionFromDepth(vec_depths, vec_size, min_size, max_size);\n        return xms::PyIterFromVecDbl(vec_size);\n    },size_function_from_depth_doc,py::arg(\"depths\"),py::arg(\"min_size\"),\n    py::arg(\"max_size\"));\n  // ---------------------------------------------------------------------------\n  // function: smooth_size_function\n  // ---------------------------------------------------------------------------\n  const char* smooth_size_function_doc = R\"pydoc(\n      Smooths a size function. Ensures that the size function transitions over a\n      sufficient distance so that the area change of adjacent elements meets the\n      size ratio passed in.\n\n      Args:\n          tin (:class:`Tin <xmsinterp.triangulate.Tin>`): Points and triangles defining the connectivity of the size function.\n          sizes (iterable): Array of the current sizes\n          size_ratio (float): Allowable size difference between adjacent elements\n          min_size (float): Minimum specified element size\n          anchor_type (int): The minimum element edge size\n          pts_flag (iterable): Flag to indicate if the value at the point should be adjusted (a value of true will skip the point). Leave the bitset empty to process all points.\n\n      Returns:\n        iterable: Array of smoothed sizes\n  )pydoc\";\n    modMeshUtils.def(\"smooth_size_function\", [](boost::shared_ptr<xms::TrTin> tin, py::iterable sizes,\n                                    double size_ratio, double min_size, int anchor_type,\n                                    py::iterable pts_flag) -> py::iterable {\n        xms::VecFlt vec_sizes, vec_smooth_sizes;\n        for (auto item : sizes) {\n          vec_sizes.push_back(item.cast<float>());\n        }\n        xms::DynBitset bitset;\n        std::vector<unsigned char> bitvals;\n        for (auto item : pts_flag) {\n          py::bool_ flag = item.cast<py::bool_>();\n          if (flag) {\n            bitvals.push_back(1);\n          } else {\n            bitvals.push_back(0);\n          }\n        }\n        xms::VecBooleanToDynBitset(bitvals, bitset);\n\n        xms::meSmoothSizeFunction(tin, vec_sizes, size_ratio, min_size, anchor_type, bitset, vec_smooth_sizes);\n\n        if (py::isinstance<py::array>(sizes)) {\n          // NOTE: This is a copy operation\n          return py::array(vec_smooth_sizes.size(), vec_smooth_sizes.data());\n        } else {\n          // NOTE: This is a copy operation\n          auto tuple_ret = py::tuple(vec_smooth_sizes.size());\n          for (size_t i = 0; i < vec_smooth_sizes.size(); ++i) {\n            tuple_ret[i] = vec_smooth_sizes.at(i);\n          }\n          return tuple_ret;\n        }\n    },smooth_size_function_doc, py::arg(\"tin\"),py::arg(\"sizes\"),\n      py::arg(\"size_ratio\"),py::arg(\"min_size\"), py::arg(\"anchor_type\"),\n      py::arg(\"pts_flag\")  \n    );\n  // ---------------------------------------------------------------------------\n  // function: smooth_elev_by_slope\n  // ---------------------------------------------------------------------------\n  const char* smooth_elev_by_slope_doc = R\"pydoc(\n      Smooths a elevations based on max specified slope (max_slope) preserving\n      either the min or max based on anchor_type\n\n      Args:\n          tin (:class:`Tin <xmsinterp.triangulate.Tin>`): Points and triangles defining the connectivity of the elevations.\n          elevations (iterable): Array of the current elevations\n          max_slope (Float): Maximum allowable slope\n          anchor_to_max (Bool): Indicates if you are anchoring to the max slope.\n          pts_flag (iterable): Flag to indicate if the value at the point should be adjusted (a value of true will skip the point). Leave the bitset empty to process all points.\n\n      Returns:\n        iterable: Array of smoothed elevations\n  )pydoc\";\n    modMeshUtils.def(\"smooth_elev_by_slope\", [](boost::shared_ptr<xms::TrTin> tin, py::iterable elevations,\n                                    double max_slope, bool anchor_to_max,\n                                    py::iterable pts_flag) -> py::iterable {\n        xms::VecFlt vec_elevations, vec_smooth_elevations;\n        for (auto item : elevations) {\n          vec_elevations.push_back(item.cast<float>());\n        }\n        xms::DynBitset bitset;\n        std::vector<unsigned char> bitvals;\n        for (auto item : pts_flag) {\n          py::bool_ flag = item.cast<py::bool_>();\n          if (flag) {\n            bitvals.push_back(1);\n          } else {\n            bitvals.push_back(0);\n          }\n        }\n        xms::VecBooleanToDynBitset(bitvals, bitset);\n\n        xms::meSmoothElevBySlope(tin, vec_elevations, max_slope, anchor_to_max? 1 : 0, bitset, vec_smooth_elevations);\n\n        if (py::isinstance<py::array>(elevations)) {\n          // NOTE: This is a copy operation\n          return py::array(vec_smooth_elevations.size(), vec_smooth_elevations.data());\n        } else {\n          // NOTE: This is a copy operation\n          auto tuple_ret = py::tuple(vec_smooth_elevations.size());\n          for (size_t i = 0; i < vec_smooth_elevations.size(); ++i) {\n            tuple_ret[i] = vec_smooth_elevations.at(i);\n          }\n          return tuple_ret;\n        }\n    },smooth_elev_by_slope_doc, py::arg(\"tin\"),py::arg(\"elevations\"),\n    py::arg(\"max_slope\"),py::arg(\"anchor_to_max\"),py::arg(\"pts_flag\"));\n\n  // ---------------------------------------------------------------------------\n  // function: check_mesh_input_topology\n  // ---------------------------------------------------------------------------\n  const char* check_mesh_input_topology_doc = R\"pydoc(\n      Checks if the input polygons intersect one another\n\n      Args:\n          mesh_io (:class:`MultiPolyMesherIo <xmsmesh.meshing.MultiPolyMesherIo>`): Input polygons and options for generating a mesh.\n\n      Returns:\n        tuple: true if mesh inputs are topologically correct, and a string of messages.\n  )pydoc\";\n    modMeshUtils.def(\"check_mesh_input_topology\",\n     [](xms::MeMultiPolyMesherIo &mesh_io) -> py::iterable\n     {\n       BSHP<xms::MeMultiPolyMesher> multiPolyMesher = xms::MeMultiPolyMesher::New();\n       std::string errors;\n       multiPolyMesher->CheckForIntersections(mesh_io, errors);\n       bool rval(errors.empty());\n       return py::make_tuple(rval, errors);\n     },check_mesh_input_topology_doc, py::arg(\"mesh_io\"));\n  // ---------------------------------------------------------------------------\n  // function: generate_mesh\n  // ---------------------------------------------------------------------------\n  const char* generate_mesh_doc = R\"pydoc(\n      Creates a mesh from the input polygons.\n\n      Args:\n          mesh_io (:class:`MultiPolyMesherIo <xmsmesh.meshing.MultiPolyMesherIo>`): Input polygons and options for generating a mesh.\n\n      Returns:\n        tuple: true if the mesh was generated successfully false otherwise, and a string of messages.\n  )pydoc\";\n    modMeshUtils.def(\"generate_mesh\",\n     [](xms::MeMultiPolyMesherIo &mesh_io) -> py::iterable\n     {\n       BSHP<xms::MeMultiPolyMesher> multiPolyMesher = xms::MeMultiPolyMesher::New();\n       bool rval = multiPolyMesher->MeshIt(mesh_io);\n       std::string errors = xms::XmLog::Instance().GetAndClearStackStr();\n       return py::make_tuple(rval, errors);\n     },generate_mesh_doc, py::arg(\"mesh_io\"));\n  // ---------------------------------------------------------------------------\n  // function: generate_2dm\n  // ---------------------------------------------------------------------------\n    const char* generate_2dm_doc = R\"pydoc(\n        Creates a mesh from the input polygons and writes it to a 2dm file.\n\n        Args:\n            mesh_io (:class:`MultiPolyMesherIo <xmsmesh.meshing.MultiPolyMesherIo>`): Input polygons and options for generating a mesh.\n            file_name (str): The file name of the output 2dm file.\n            precision (int, optional): The decimal point precision of the resulting mesh.\n\n        Returns:\n            tuple: true if the mesh was generated successfully false otherwise, and a string of messages.\n    )pydoc\";\n    modMeshUtils.def(\"generate_2dm\",\n     [](xms::MeMultiPolyMesherIo &mesh_io,\n        std::string file_name, int precision) -> py::tuple {\n        BSHP<xms::MeMultiPolyTo2dm> mesher = xms::MeMultiPolyTo2dm::New();\n        if (file_name.empty()) {\n          throw py::value_error(\"file_name not specifed. Aborting mesh procedure.\");\n        }\n        bool result = mesher->Generate2dm(mesh_io, file_name, precision);\n        std::string errors = xms::XmLog::Instance().GetAndClearStackStr();\n        return py::make_tuple(result, errors);\n        },generate_2dm_doc,py::arg(\"mesh_io\"),py::arg(\"file_name\"),py::arg(\"precision\")=15);\n\n  // ---------------------------------------------------------------------------\n  // function: redistribute_line\n  // ---------------------------------------------------------------------------\n    const char* redistribute_poly_line_doc = R\"pydoc(\n        Redistributes the points along a line to a constant spacing\n\n        Args:\n            poly_lin (iterable): Input poly line locations.\n            size (Float): The desired spacing for point redistribution\n\n        Returns:\n            iterable: redistributed poly line locations\n    )pydoc\";\n    modMeshUtils.def(\"redistribute_poly_line\",\n     [](py::iterable poly_line, double size) -> py::iterable {\n        BSHP<xms::MePolyRedistributePts> redist(xms::MePolyRedistributePts::New());\n        redist->SetConstantSizeFunc(size);\n        BSHP<xms::VecPt3d> vPolyLine = xms::VecPt3dFromPyIter(poly_line);\n        xms::VecPt3d rval = redist->Redistribute(*vPolyLine);\n        return xms::PyIterFromVecPt3d(rval);\n        },redistribute_poly_line_doc,py::arg(\"poly_line\"),py::arg(\"size\"));\n\n}", "meta": {"hexsha": "f9376c3fdcdd616ccb1fa2b299c0e6435ddc3cd2", "size": 12017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xmsmesh/python/meshing/MeMeshUtils_py.cpp", "max_stars_repo_name": "kwryankrattiger/xmsmesh", "max_stars_repo_head_hexsha": "5c24da6cb93dbfa08f6502917e1fb23e2d2ecbe7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-10T16:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-26T15:06:03.000Z", "max_issues_repo_path": "xmsmesh/python/meshing/MeMeshUtils_py.cpp", "max_issues_repo_name": "kwryankrattiger/xmsmesh", "max_issues_repo_head_hexsha": "5c24da6cb93dbfa08f6502917e1fb23e2d2ecbe7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-08-27T23:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-23T14:57:14.000Z", "max_forks_repo_path": "xmsmesh/python/meshing/MeMeshUtils_py.cpp", "max_forks_repo_name": "kwryankrattiger/xmsmesh", "max_forks_repo_head_hexsha": "5c24da6cb93dbfa08f6502917e1fb23e2d2ecbe7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-26T15:41:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T20:20:03.000Z", "avg_line_length": 46.94140625, "max_line_length": 177, "alphanum_fraction": 0.5754348007, "num_tokens": 2707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.027585281627219398, "lm_q1q2_score": 0.011971500927608745}}
{"text": "/*\n * readmatrix.cpp\n *\n *  Created on: 5-sep-2017\n *      Author: M. El-Kebir\n */\n\n#include \"readmatrix.h\"\n#include <boost/math/distributions/beta.hpp>\n\nReadMatrix::ReadMatrix()\n  : BaseMatrix()\n  , _var()\n  , _ref()\n{\n}\n\nReadMatrix ReadMatrix::poolReads(const IntMatrix& clustering,\n                                 bool relabel) const\n{\n  ReadMatrix newR(*this);\n  newR._k = _k;\n  newR._m = _m;\n  newR._n = 0;\n  newR._indexToCharacter.clear();\n  newR._characterToIndex.clear();\n  \n  char buf[1024];\n  \n  // 1. infer character labeling\n  IntVector oldCharacterToNewCharacter(_n, -1);\n  int idx = 0;\n  for (const IntVector& cluster : clustering)\n  {\n    std::string label;\n    for (int i : cluster)\n    {\n      if (!label.empty())\n        label += \"_\";\n      \n      label += indexToCharacter(i);\n      oldCharacterToNewCharacter[i] = idx;\n    }\n    \n    if (relabel)\n    {\n      snprintf(buf, 1024, \"cluster_%d\", idx + 1);\n      label = buf;\n    }\n    \n    newR._indexToCharacter.push_back(label);\n    newR._characterToIndex[label] = idx;\n    \n    ++idx;\n    ++newR._n;\n  }\n  \n  // 2. pool reads\n  newR._ref = IntMatrix(_k, IntVector(newR._n, 0));\n  newR._var = IntMatrix(_k, IntVector(newR._n, 0));\n  \n  for (const IntVector& cluster : clustering)\n  {\n    for (int i : cluster)\n    {\n      for (int p = 0; p < _k; ++p)\n      {\n        int new_i = oldCharacterToNewCharacter[i];\n        assert(new_i != -1);\n        newR._ref[p][new_i] += _ref[p][i];\n        newR._var[p][new_i] += _var[p][i];\n      }\n    }\n  }\n  \n  return newR;\n}\n\nFrequencyMatrix ReadMatrix::toFrequencyMatrix(double alpha,\n                                              int threshold) const\n{\n  FrequencyMatrix resF(*this);\n  \n  // compute confidence intervals\n  for (int p = 0; p < _k; ++p)\n  {\n    for (int i = 0; i < _n; ++i)\n    {\n      int var = getVar(p, i);\n      int ref = getRef(p, i);\n      \n      boost::math::beta_distribution<> beta_dist(1 + var, 1 + ref);\n      \n      double f_lb = boost::math::quantile(beta_dist, alpha / 2);\n      double f_ub = boost::math::quantile(beta_dist, 1 - alpha / 2);\n      \n      if (var < threshold || var <= (var + ref) * 0.01)\n      {\n        f_lb = f_ub = 0;\n      }\n      \n      f_lb *= 2;\n      f_ub *= 2;\n      \n      if (f_lb > 1)\n      {\n        f_lb = 1;\n      }\n      if (f_ub > 1)\n      {\n        f_ub = 1;\n      }\n      \n      resF.set(p, i, f_lb, f_ub);\n    }\n  }\n  \n  return resF;\n}\n\nReadMatrix ReadMatrix::downSample(int nrSamplesPerAnatomicalSite,\n                                  int coverage,\n                                  double purity,\n                                  double seqErrorRate,\n                                  double fracSNVs) const\n{\n  std::poisson_distribution<> poisson(coverage >= 0 ? coverage : 0);\n  \n  const int new_n = _n * fracSNVs;\n  IntVector snvIndices(_n, 0);\n  for (int i = 1; i < _n; ++i)\n  {\n    snvIndices[i] = snvIndices[i-1] + 1;\n  }\n  std::shuffle(snvIndices.begin(), snvIndices.end(), g_rng);\n  snvIndices.erase(snvIndices.begin() + new_n, snvIndices.end());\n  \n  ReadMatrix newR;\n  newR._m = _m;\n  newR._n = new_n;\n  if (nrSamplesPerAnatomicalSite < 0)\n  {\n    newR._k = _k;\n    newR._var = IntMatrix(_k,\n                          IntVector(new_n, 0));\n    newR._ref = IntMatrix(_k,\n                          IntVector(new_n, 0));\n  }\n  else\n  {\n    newR._k = nrSamplesPerAnatomicalSite * _m;\n    newR._var = IntMatrix(nrSamplesPerAnatomicalSite * _m,\n                          IntVector(new_n, 0));\n    newR._ref = IntMatrix(nrSamplesPerAnatomicalSite * _m,\n                          IntVector(new_n, 0));\n  }\n  \n  newR._indexToAnatomicalSite = _indexToAnatomicalSite;\n  newR._anatomicalSiteToIndex = _anatomicalSiteToIndex;\n  \n  newR._anatomicalSiteIndexToSampleIndices = IntSetVector(_m);\n  \n  newR._indexToCharacter = StringVector(new_n);\n  for (int i = 0; i < new_n; ++i)\n  {\n    newR._indexToCharacter[i] = _indexToCharacter[snvIndices[i]];\n    newR._characterToIndex[newR._indexToCharacter[i]] = i;\n  }\n  \n  int newP = 0;\n  for (int s = 0; s < _m; ++s)\n  {\n    IntVector sampleIndices(anatomicalSiteIndexToSampleIndices(s).begin(),\n                            anatomicalSiteIndexToSampleIndices(s).end());\n    \n    std::shuffle(sampleIndices.begin(), sampleIndices.end(), g_rng);\n    \n    \n    int nrSamplesPerAnatomicalSite_s = nrSamplesPerAnatomicalSite < 0 ? anatomicalSiteIndexToSampleIndices(s).size() : nrSamplesPerAnatomicalSite;\n    assert(nrSamplesPerAnatomicalSite_s <= sampleIndices.size());\n    for (int pp = 0; pp < nrSamplesPerAnatomicalSite_s; ++pp)\n    {\n      int p = sampleIndices[pp];\n      const std::string& pStr = _indexToSample[p];\n      \n      newR._sampleToIndex[pStr] = newP;\n      newR._indexToSample.push_back(pStr);\n      \n      newR._anatomicalSiteIndexToSampleIndices[s].insert(newP);\n      newR._sampleIndexToAnatomicalSiteIndex.push_back(s);\n      \n      for (int i = 0; i < new_n; ++i)\n      {\n        int old_i = snvIndices[i];\n        if (coverage < 0)\n        {\n          newR._var[newP][i] = _var[p][old_i];\n          newR._ref[newP][i] = _ref[p][old_i];\n        }\n        else\n        {\n          double vaf_pi = purity * double(_var[p][old_i]) / double(_var[p][old_i] + _ref[p][old_i]);\n          int newCoverage = poisson(g_rng);\n          \n          std::binomial_distribution<> binom(newCoverage, vaf_pi);\n          int org_var = binom(g_rng);\n          int org_ref = newCoverage - org_var;\n          \n          if (g_tol.nonZero(seqErrorRate))\n          {\n            std::binomial_distribution<> binom_noise_var(org_var,\n                                                         seqErrorRate);\n            std::binomial_distribution<> binom_noise_ref(org_ref,\n                                                         seqErrorRate);\n            \n            int flips_var = binom_noise_var(g_rng);\n            int flips_ref = binom_noise_ref(g_rng);\n            \n            newR._var[newP][i] = org_var - flips_var + flips_ref;\n            newR._ref[newP][i] = newCoverage - newR._var[newP][i];\n          }\n          else\n          {\n            newR._var[newP][i] = org_var;\n            newR._ref[newP][i] = newCoverage - newR._var[newP][i];\n          }\n        }\n      }\n      ++newP;\n    }\n  }\n  \n  return newR;\n}\n\nstd::ostream& operator<<(std::ostream& out,\n                         const ReadMatrix& R)\n{\n  out << R._m << \" #anatomical sites\" << std::endl;\n  out << R._k << \" #samples\" << std::endl;\n  out << R._n << \" #characters\" << std::endl;\n  out << \"#sample_index\\tsample_label\\tanatomical_site_index\\t\"\\\n         \"anatomical_site_label\\tcharacter_index\\tcharacter_label\\tref\\tvar\"\n      << std::endl;\n  for (int p = 0; p < R._k; ++p)\n  {\n    int s = R.sampleIndexToAnatomicalSiteIndex(p);\n    const std::string sStr = R.indexToAnatomicalSite(s);\n    \n    const std::string& pStr = R.indexToSample(p);\n    for (int c = 0; c < R._n; ++c)\n    {\n      const std::string& cStr = R.indexToCharacter(c);\n      out << p << \"\\t\" << pStr << \"\\t\"\n          << s << \"\\t\" << sStr << \"\\t\"\n          << c << \"\\t\" << cStr << \"\\t\"\n          << R._ref[p][c] << \"\\t\" << R._var[p][c] << std::endl;\n    }\n  }\n  \n  return out;\n}\n\nstd::istream& operator>>(std::istream& in, ReadMatrix& R)\n{\n  std::string line;\n  getline(in, line);\n  \n  int m = -1;\n  int k = -1;\n  int n = -1;\n  \n  std::stringstream ss(line);\n  ss >> m;\n  \n  if (m <= 0)\n  {\n    throw std::runtime_error(\"Error: m should be nonnegative\");\n  }\n  \n  getline(in, line);\n  ss.clear();\n  ss.str(line);\n  ss >> k;\n  \n  if (k < m)\n  {\n    throw std::runtime_error(\"Error: k should be at least m\");\n  }\n  \n  getline(in, line);\n  ss.clear();\n  ss.str(line);\n  ss >> n;\n  \n  if (n <= 0)\n  {\n    throw std::runtime_error(\"Error: n should be nonnegative\");\n  }\n  \n  R._m = m;\n  R._k = k;\n  R._n = n;\n  \n  R._indexToAnatomicalSite = StringVector(m);\n  R._indexToSample = StringVector(k);\n  R._indexToCharacter = StringVector(n);\n  R._sampleIndexToAnatomicalSiteIndex = IntVector(k, -1);\n  R._anatomicalSiteIndexToSampleIndices = IntSetVector(m);\n  \n  R._var = IntMatrix(k, IntVector(n, 0));\n  R._ref = IntMatrix(k, IntVector(n, 0));\n  \n  std::vector<std::vector<bool> > present(k, std::vector<bool>(n, false));\n  while (in.good())\n  {\n    getline(in, line);\n    if (line == \"\" || line[0] == '#')\n      continue;\n    \n    ss.clear();\n    ss.str(line);\n    \n    int p = -1;\n    std::string pStr;\n    int s = -1;\n    std::string sStr;\n    int c = -1;\n    std::string cStr;\n    int ref = -1;\n    int var = -1;\n    \n    ss >> p >> pStr >> s >> sStr >> c >> cStr >> ref >> var;\n    \n    if (!(0 <= p && p < k) || !(0 <= s && s < m) || !(0 <= c && c < n)\n        || ref < 0 || var < 0)\n    {\n      throw std::runtime_error(\"Invalid character (\"\n                               + boost::lexical_cast<std::string>(p)\n                               + \",\"\n                               + boost::lexical_cast<std::string>(c)\n                               + \")\");\n    }\n    \n    if (present[p][c])\n    {\n      throw std::runtime_error(\"Duplicate character (\"\n                               + boost::lexical_cast<std::string>(p)\n                               + \",\"\n                               + boost::lexical_cast<std::string>(c)\n                               + \")\");\n    }\n    \n    R._indexToAnatomicalSite[s] = sStr;\n    R._anatomicalSiteToIndex[sStr] = s;\n    R._indexToSample[p] = pStr;\n    R._sampleToIndex[pStr] = p;\n    R._indexToCharacter[c] = cStr;\n    R._characterToIndex[cStr] = c;\n    R._var[p][c] = var;\n    R._ref[p][c] = ref;\n    R._sampleIndexToAnatomicalSiteIndex[p] = s;\n    R._anatomicalSiteIndexToSampleIndices[s].insert(p);\n    \n    present[p][c] = true;\n  }\n  \n  return in;\n}\n", "meta": {"hexsha": "633307aee8760a50062f0691804dd03424473729", "size": 9662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cluster/readmatrix.cpp", "max_stars_repo_name": "elkebir-group/machina", "max_stars_repo_head_hexsha": "822330bdd26819d861b7dda1f9e97a5ca0f6bb38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-04-14T18:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T14:06:11.000Z", "max_issues_repo_path": "src/cluster/readmatrix.cpp", "max_issues_repo_name": "elkebir-group/machina", "max_issues_repo_head_hexsha": "822330bdd26819d861b7dda1f9e97a5ca0f6bb38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2018-04-24T09:42:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T16:59:27.000Z", "max_forks_repo_path": "src/cluster/readmatrix.cpp", "max_forks_repo_name": "elkebir-group/machina", "max_forks_repo_head_hexsha": "822330bdd26819d861b7dda1f9e97a5ca0f6bb38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-07-18T11:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T14:06:14.000Z", "avg_line_length": 26.1135135135, "max_line_length": 146, "alphanum_fraction": 0.530531981, "num_tokens": 2860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398145016252104, "lm_q2_score": 0.02758528062793511, "lm_q1q2_score": 0.011971500090051379}}
{"text": "// Copyright (C) 2012-2015 Internet Systems Consortium, Inc. (\"ISC\")\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include <stdint.h>\n\n#include <cassert>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <vector>\n\n#include <boost/noncopyable.hpp>\n#include <boost/scoped_ptr.hpp>\n\n#include <exceptions/exceptions.h>\n\n#include <util/buffer.h>\n#include <util/encode/base32hex.h>\n\n#include <cryptolink/cryptolink.h>\n#include <cryptolink/crypto_hash.h>\n\n#include <dns/name.h>\n#include <dns/labelsequence.h>\n#include <dns/nsec3hash.h>\n#include <dns/rdataclass.h>\n#include <dns/name_internal.h>\n\nusing namespace std;\nusing namespace isc::util;\nusing namespace isc::util::encode;\nusing namespace isc::cryptolink;\nusing namespace isc::dns;\nusing namespace isc::dns::rdata;\n\nnamespace {\n\n/// \\brief A derived class of \\c NSEC3Hash that implements the standard hash\n/// calculation specified in RFC5155.\n///\n/// Currently the only pre-defined algorithm in the RFC is SHA1.  So we don't\n/// over-generalize it at the moment, and rather hardcode it and assume that\n/// specific algorithm.\n///\n/// The implementation details are only open within this file, but to avoid\n/// an accidental error in this implementation we explicitly make it non\n/// copyable.\nclass NSEC3HashRFC5155 : boost::noncopyable, public NSEC3Hash {\nprivate:\n    // This is the algorithm number for SHA1/NSEC3 as defined in RFC5155.\n    static const uint8_t NSEC3_HASH_SHA1 = 1;\n    // For digest_ allocation\n    static const size_t DEFAULT_DIGEST_LENGTH = 32;\n\npublic:\n    NSEC3HashRFC5155(uint8_t algorithm, uint16_t iterations,\n                     const uint8_t* salt_data, size_t salt_length) :\n        algorithm_(algorithm), iterations_(iterations),\n        salt_data_(NULL), salt_length_(salt_length),\n        digest_(DEFAULT_DIGEST_LENGTH), obuf_(Name::MAX_WIRE)\n    {\n        if (algorithm_ != NSEC3_HASH_SHA1) {\n            isc_throw(UnknownNSEC3HashAlgorithm, \"Unknown NSEC3 algorithm: \" <<\n                      static_cast<unsigned int>(algorithm_));\n        }\n\n        if (salt_length > 0) {\n            salt_data_ = static_cast<uint8_t*>(std::malloc(salt_length));\n            if (salt_data_ == NULL) {\n                throw std::bad_alloc();\n            }\n            std::memcpy(salt_data_, salt_data, salt_length);\n        }\n    }\n\n    virtual ~NSEC3HashRFC5155() {\n        std::free(salt_data_);\n    }\n\n    virtual std::string calculate(const Name& name) const;\n    virtual std::string calculate(const LabelSequence& ls) const;\n\n    virtual bool match(const generic::NSEC3& nsec3) const;\n    virtual bool match(const generic::NSEC3PARAM& nsec3param) const;\n    bool match(uint8_t algorithm, uint16_t iterations,\n               const vector<uint8_t>& salt) const;\n\nprivate:\n    std::string calculateForWiredata(const uint8_t* data, size_t length) const;\n\n    const uint8_t algorithm_;\n    const uint16_t iterations_;\n    uint8_t* salt_data_;\n    const size_t salt_length_;\n\n    // The following members are placeholder of work place and don't hold\n    // any state over multiple calls so can be mutable without breaking\n    // constness.\n    mutable OutputBuffer digest_;\n    mutable vector<uint8_t> vdigest_;\n    mutable OutputBuffer obuf_;\n};\n\ninline void\niterateSHA1(const uint8_t* input, size_t inlength,\n            const uint8_t* salt, size_t saltlen,\n            OutputBuffer& output)\n{\n    boost::scoped_ptr<Hash> hash(CryptoLink::getCryptoLink().createHash(SHA1));\n    hash->update(input, inlength);\n    hash->update(salt, saltlen); // this works whether saltlen == or > 0\n    hash->final(output, hash->getOutputLength());\n}\n\nstring\nNSEC3HashRFC5155::calculateForWiredata(const uint8_t* data,\n                                       size_t length) const\n{\n    // We first need to normalize the name by converting all upper case\n    // characters in the labels to lower ones.\n\n    uint8_t name_buf[256];\n    assert(length < sizeof (name_buf));\n\n    const uint8_t *p1 = data;\n    uint8_t *p2 = name_buf;\n    while (*p1 != 0) {\n        char len = *p1;\n\n        *p2++ = *p1++;\n        while (len--) {\n            *p2++ = isc::dns::name::internal::maptolower[*p1++];\n        }\n    }\n\n    *p2 = *p1;\n\n    digest_.clear();\n    iterateSHA1(name_buf, length,\n                salt_data_, salt_length_, digest_);\n    const uint8_t* dgst_data = static_cast<const uint8_t*>(digest_.getData());\n    size_t dgst_len = digest_.getLength();\n    for (unsigned int n = 0; n < iterations_; ++n) {\n        digest_.clear();\n        iterateSHA1(dgst_data, dgst_len, salt_data_, salt_length_, digest_);\n    }\n\n    vdigest_.resize(dgst_len);\n    std::memcpy(&vdigest_[0], dgst_data, dgst_len);\n    return (encodeBase32Hex(vdigest_));\n}\n\nstring\nNSEC3HashRFC5155::calculate(const Name& name) const {\n    obuf_.clear();\n    name.toWire(obuf_);\n\n    return (calculateForWiredata(static_cast<const uint8_t*>(obuf_.getData()),\n                                 obuf_.getLength()));\n}\n\nstring\nNSEC3HashRFC5155::calculate(const LabelSequence& ls) const {\n    assert(ls.isAbsolute());\n\n    size_t length;\n    const uint8_t* data = ls.getData(&length);\n\n    return (calculateForWiredata(data, length));\n}\n\nbool\nNSEC3HashRFC5155::match(uint8_t algorithm, uint16_t iterations,\n                        const vector<uint8_t>& salt) const\n{\n    return (algorithm_ == algorithm && iterations_ == iterations &&\n            salt_length_ == salt.size() &&\n            ((salt_length_ == 0) ||\n             memcmp(salt_data_, &salt[0], salt_length_) == 0));\n}\n\nbool\nNSEC3HashRFC5155::match(const generic::NSEC3& nsec3) const {\n    return (match(nsec3.getHashalg(), nsec3.getIterations(),\n                  nsec3.getSalt()));\n}\n\nbool\nNSEC3HashRFC5155::match(const generic::NSEC3PARAM& nsec3param) const {\n    return (match(nsec3param.getHashalg(), nsec3param.getIterations(),\n                  nsec3param.getSalt()));\n}\n\n// A static pointer that refers to the currently usable creator.\n// Only get/setNSEC3HashCreator are expected to get access to this variable\n// directly.\nconst NSEC3HashCreator* creator;\n\n// The accessor to the current creator.  If it's not explicitly set or has\n// been reset from a customized one, the default creator will be used.\nconst NSEC3HashCreator*\ngetNSEC3HashCreator() {\n    static DefaultNSEC3HashCreator default_creator;\n    if (creator == NULL) {\n        creator = &default_creator;\n    }\n    return (creator);\n}\n\n} // end of unnamed namespace\n\nnamespace isc {\nnamespace dns {\n\nNSEC3Hash*\nNSEC3Hash::create(const generic::NSEC3PARAM& param) {\n    return (getNSEC3HashCreator()->create(param));\n}\n\nNSEC3Hash*\nNSEC3Hash::create(const generic::NSEC3& nsec3) {\n    return (getNSEC3HashCreator()->create(nsec3));\n}\n\nNSEC3Hash*\nNSEC3Hash::create(uint8_t algorithm, uint16_t iterations,\n                  const uint8_t* salt_data, size_t salt_length) {\n    return (getNSEC3HashCreator()->create(algorithm, iterations,\n                                          salt_data, salt_length));\n}\n\nNSEC3Hash*\nDefaultNSEC3HashCreator::create(const generic::NSEC3PARAM& param) const {\n    const vector<uint8_t>& salt = param.getSalt();\n    return (new NSEC3HashRFC5155(param.getHashalg(), param.getIterations(),\n                                 salt.empty() ? NULL : &salt[0],\n                                 salt.size()));\n}\n\nNSEC3Hash*\nDefaultNSEC3HashCreator::create(const generic::NSEC3& nsec3) const {\n    const vector<uint8_t>& salt = nsec3.getSalt();\n    return (new NSEC3HashRFC5155(nsec3.getHashalg(), nsec3.getIterations(),\n                                 salt.empty() ? NULL : &salt[0],\n                                 salt.size()));\n}\n\nNSEC3Hash*\nDefaultNSEC3HashCreator::create(uint8_t algorithm, uint16_t iterations,\n                                const uint8_t* salt_data,\n                                size_t salt_length) const\n{\n    return (new NSEC3HashRFC5155(algorithm, iterations,\n                                 salt_data, salt_length));\n}\n\nvoid\nsetNSEC3HashCreator(const NSEC3HashCreator* new_creator) {\n    creator = new_creator;\n}\n\n} // namespace dns\n} // namespace isc\n", "meta": {"hexsha": "4f787d39367e3499525bf3b206a6de24562f46e6", "size": 8230, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lib/dns/nsec3hash.cc", "max_stars_repo_name": "sebschrader/debian-pkg-isc-kea", "max_stars_repo_head_hexsha": "1bdb18f90c48dd9674374fb8454d0efb846656bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-24T19:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-24T19:55:21.000Z", "max_issues_repo_path": "src/lib/dns/nsec3hash.cc", "max_issues_repo_name": "sebschrader/debian-pkg-isc-kea", "max_issues_repo_head_hexsha": "1bdb18f90c48dd9674374fb8454d0efb846656bc", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/dns/nsec3hash.cc", "max_forks_repo_name": "sebschrader/debian-pkg-isc-kea", "max_forks_repo_head_hexsha": "1bdb18f90c48dd9674374fb8454d0efb846656bc", "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.8239700375, "max_line_length": 79, "alphanum_fraction": 0.6608748481, "num_tokens": 2058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748935136303, "lm_q2_score": 0.03358950806865572, "lm_q1q2_score": 0.011950303656301214}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"../include/structures.h\"\n#include \"../include/transformations.h\"\n#include \"../../relative_pose_tait_bryan_wc_jacobian.h\"\n#include \"../include/cauchy.h\"\n#include \"../../constraint_fixed_parameter_jacobian.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nstd::vector<Eigen::Affine3d> m_poses;\nstd::vector<Eigen::Affine3d> m_poses_desired;\n\nstd::vector<std::pair<int, int>> odo_edges;\nstd::vector<std::pair<int, int>> loop_edges;\n\nstd::vector<std::pair<Eigen::Affine3d, int>> georeference_data;\n\nint main(int argc, char *argv[]){\n\n\tfor(size_t i = 0 ; i < 100; i++){\n\t\tTaitBryanPose p;\n\t\tp.px = i;\n\t\tp.py = -1;\n\t\tp.pz = 0.0;\n\t\tp.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\n\t\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p);\n\t\tm_poses.push_back(m);\n\t}\n\tfor(size_t i = 0 ; i < 100; i++){\n\t\tTaitBryanPose p;\n\t\tp.px = i;\n\t\tp.py = 1;\n\t\tp.pz = 0.0;\n\t\tp.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\n\t\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p);\n\t\tm_poses.push_back(m);\n\t}\n\tm_poses_desired = m_poses;\n\n\tfor(size_t i = 1; i < 100; i++){\n\t\todo_edges.emplace_back(i-1,i);\n\t}\n\n\tfor(size_t i = 101; i < 200; i++){\n\t\todo_edges.emplace_back(i-1,i);\n\t}\n\n\tfor(size_t i = 0; i < 100; i+=10){\n\t\tloop_edges.emplace_back(i,i+100);\n\t}\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tTaitBryanPose p;\n\tp.px = 0;\n\tp.py = 5;\n\tp.pz = 5;\n\tp.om = 0;\n\tp.fi = 0;\n\tp.ka = 0;\n\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p);\n\tgeoreference_data.emplace_back(m, 4);\n\n\tp.px = 50;\n\tp.py = 3;\n\tp.pz = 4;\n\tm = affine_matrix_from_pose_tait_bryan(p);\n\tgeoreference_data.emplace_back(m, 54);\n\n\tp.px = 0;\n\tp.py = 8;\n\tp.pz = 5;\n\tm = affine_matrix_from_pose_tait_bryan(p);\n\tgeoreference_data.emplace_back(m, 102);\n\n\tp.px = 110;\n\tp.py = 8;\n\tp.pz = 7;\n\tm = affine_matrix_from_pose_tait_bryan(p);\n\tgeoreference_data.emplace_back(m, 197);\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"georeference-case2\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\tglColor3f(0.0f, 1.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\tglColor3f(0.0f, 0.0f, 1.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();\n\n\tglColor3f(1,0,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < odo_edges.size(); i++){\n\t\tglVertex3f(m_poses[odo_edges[i].first](0,3), m_poses[odo_edges[i].first](1,3), m_poses[odo_edges[i].first](2,3) );\n\t\tglVertex3f(m_poses[odo_edges[i].second](0,3), m_poses[odo_edges[i].second](1,3), m_poses[odo_edges[i].second](2,3) );\n\t}\n\tglEnd();\n\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < loop_edges.size(); i++){\n\t\tglVertex3f(m_poses[loop_edges[i].first](0,3), m_poses[loop_edges[i].first](1,3), m_poses[loop_edges[i].first](2,3) );\n\t\tglVertex3f(m_poses[loop_edges[i].second](0,3), m_poses[loop_edges[i].second](1,3), m_poses[loop_edges[i].second](2,3) );\n\t}\n\tglEnd();\n\n\tfor(size_t i = 0 ; i < georeference_data.size(); i++){\n\t\tglBegin(GL_LINES);\n\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\tglVertex3f(georeference_data[i].first(0,3), georeference_data[i].first(1,3), georeference_data[i].first(2,3));\n\t\tglVertex3f(georeference_data[i].first(0,3) + georeference_data[i].first(0,0), georeference_data[i].first(1,3) + georeference_data[i].first(1,0), georeference_data[i].first(2,3) + georeference_data[i].first(2,0));\n\n\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\tglVertex3f(georeference_data[i].first(0,3), georeference_data[i].first(1,3), georeference_data[i].first(2,3));\n\t\tglVertex3f(georeference_data[i].first(0,3) + georeference_data[i].first(0,1), georeference_data[i].first(1,3) + georeference_data[i].first(1,1), georeference_data[i].first(2,3) + georeference_data[i].first(2,1));\n\n\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\tglVertex3f(georeference_data[i].first(0,3), georeference_data[i].first(1,3), georeference_data[i].first(2,3));\n\t\tglVertex3f(georeference_data[i].first(0,3) + georeference_data[i].first(0,2), georeference_data[i].first(1,3) + georeference_data[i].first(1,2), georeference_data[i].first(2,3) + georeference_data[i].first(2,2));\n\t\tglEnd();\n\t}\n\n\tglColor3f(0.0f, 0.0f, 0.0f);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0 ; i < georeference_data.size(); i++){\n\t\tglVertex3f(georeference_data[i].first(0,3), georeference_data[i].first(1,3), georeference_data[i].first(2,3));\n\t\tglVertex3f(m_poses[georeference_data[i].second](0,3), m_poses[georeference_data[i].second](1,3), m_poses[georeference_data[i].second](2,3) );\n\t}\n\tglEnd();\n\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\tpose.px += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.py += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.pz += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.om += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\t\t\tpose.fi += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\t\t\tpose.ka += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<TaitBryanPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_tait_bryan_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1000);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1000);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < georeference_data.size(); i++){\n\t\t\t\tTaitBryanPose pose_gps = pose_tait_bryan_from_affine_matrix(georeference_data[i].first);\n\t\t\t\tTaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_poses[georeference_data[i].second]);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement;\n\t\t\t\trelative_pose_measurement(0,0) = 0.0;\n\t\t\t\trelative_pose_measurement(1,0) = 0.0;\n\t\t\t\trelative_pose_measurement(2,0) = 0.0;\n\t\t\t\trelative_pose_measurement(3,0) = 0.0;\n\t\t\t\trelative_pose_measurement(4,0) = 0.0;\n\t\t\t\trelative_pose_measurement(5,0) = 0.0;\n\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tpose_s.px,\n\t\t\t\t\t\tpose_s.py,\n\t\t\t\t\t\tpose_s.pz,\n\t\t\t\t\t\tpose_s.om,\n\t\t\t\t\t\tpose_s.fi,\n\t\t\t\t\t\tpose_s.ka,\n\t\t\t\t\t\tpose_gps.px,\n\t\t\t\t\t\tpose_gps.py,\n\t\t\t\t\t\tpose_gps.pz,\n\t\t\t\t\t\tpose_gps.om,\n\t\t\t\t\t\tpose_gps.fi,\n\t\t\t\t\t\tpose_gps.ka,\n\t\t\t\t\t\trelative_pose_measurement(0,0),\n\t\t\t\t\t\trelative_pose_measurement(1,0),\n\t\t\t\t\t\trelative_pose_measurement(2,0),\n\t\t\t\t\t\trelative_pose_measurement(3,0),\n\t\t\t\t\t\trelative_pose_measurement(4,0),\n\t\t\t\t\t\trelative_pose_measurement(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tpose_s.px,\n\t\t\t\t\t\tpose_s.py,\n\t\t\t\t\t\tpose_s.pz,\n\t\t\t\t\t\tpose_s.om,\n\t\t\t\t\t\tpose_s.fi,\n\t\t\t\t\t\tpose_s.ka,\n\t\t\t\t\t\tpose_gps.px,\n\t\t\t\t\t\tpose_gps.py,\n\t\t\t\t\t\tpose_gps.pz,\n\t\t\t\t\t\tpose_gps.om,\n\t\t\t\t\t\tpose_gps.fi,\n\t\t\t\t\t\tpose_gps.ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic_1 = georeference_data[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     cauchy(delta(0,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, cauchy(delta(1,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, cauchy(delta(2,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, cauchy(delta(3,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, cauchy(delta(4,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, cauchy(delta(5,0), 1));\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 , m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'y':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<TaitBryanPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_tait_bryan_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1000);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1000);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1000);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < georeference_data.size(); i++){\n\t\t\t\tTaitBryanPose pose_gps = pose_tait_bryan_from_affine_matrix(georeference_data[i].first);\n\t\t\t\tTaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_poses[georeference_data[i].second]);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement;\n\t\t\t\trelative_pose_measurement(0,0) = 0.0;\n\t\t\t\trelative_pose_measurement(1,0) = 0.0;\n\t\t\t\trelative_pose_measurement(2,0) = 0.0;\n\t\t\t\trelative_pose_measurement(3,0) = 0.0;\n\t\t\t\trelative_pose_measurement(4,0) = 0.0;\n\t\t\t\trelative_pose_measurement(5,0) = 0.0;\n\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tpose_s.px,\n\t\t\t\t\t\tpose_s.py,\n\t\t\t\t\t\tpose_s.pz,\n\t\t\t\t\t\tpose_s.om,\n\t\t\t\t\t\tpose_s.fi,\n\t\t\t\t\t\tpose_s.ka,\n\t\t\t\t\t\tpose_gps.px,\n\t\t\t\t\t\tpose_gps.py,\n\t\t\t\t\t\tpose_gps.pz,\n\t\t\t\t\t\tpose_gps.om,\n\t\t\t\t\t\tpose_gps.fi,\n\t\t\t\t\t\tpose_gps.ka,\n\t\t\t\t\t\trelative_pose_measurement(0,0),\n\t\t\t\t\t\trelative_pose_measurement(1,0),\n\t\t\t\t\t\trelative_pose_measurement(2,0),\n\t\t\t\t\t\trelative_pose_measurement(3,0),\n\t\t\t\t\t\trelative_pose_measurement(4,0),\n\t\t\t\t\t\trelative_pose_measurement(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tpose_s.px,\n\t\t\t\t\t\tpose_s.py,\n\t\t\t\t\t\tpose_s.pz,\n\t\t\t\t\t\tpose_s.om,\n\t\t\t\t\t\tpose_s.fi,\n\t\t\t\t\t\tpose_s.ka,\n\t\t\t\t\t\tpose_gps.px,\n\t\t\t\t\t\tpose_gps.py,\n\t\t\t\t\t\tpose_gps.pz,\n\t\t\t\t\t\tpose_gps.om,\n\t\t\t\t\t\tpose_gps.fi,\n\t\t\t\t\t\tpose_gps.ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic_1 = georeference_data[i].second * 6;\n\t\t\t\tint ic_2 = m_poses.size() * 6 + i * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     cauchy(delta(0,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, cauchy(delta(1,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, cauchy(delta(2,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, cauchy(delta(3,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, cauchy(delta(4,0), 1));\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, cauchy(delta(5,0), 1));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0; i < georeference_data.size(); i++){\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic = m_poses.size() * 6 + i * 6;\n\t\t\t\tTaitBryanPose pose_gps = pose_tait_bryan_from_affine_matrix(georeference_data[i].first);\n\t\t\t\tdouble residual;\n\t\t\t\tresidual_constraint_fixed_optimization_parameter(residual, pose_gps.px, pose_gps.px);\n\t\t\t\tEigen::Matrix<double, 1, 1> jacobian;\n\t\t\t\tresidual_constraint_fixed_optimization_parameter_jacobian(jacobian, pose_gps.px, pose_gps.px);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic  , -jacobian(0,0));\n\t\t\t\ttripletListB.emplace_back(ir, 0, residual);\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000000);\n\n\t\t\t\tresidual_constraint_fixed_optimization_parameter(residual, pose_gps.py, pose_gps.py);\n\t\t\t\tresidual_constraint_fixed_optimization_parameter_jacobian(jacobian, pose_gps.py, pose_gps.py);\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic + 1, -jacobian(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, residual);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1000000000);\n\n\t\t\t\tresidual_constraint_fixed_optimization_parameter(residual, pose_gps.pz, pose_gps.pz);\n\t\t\t\tresidual_constraint_fixed_optimization_parameter_jacobian(jacobian, pose_gps.pz, pose_gps.pz);\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic + 2, -jacobian(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, residual);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1000000000);\n\n\t\t\t\tresidual_constraint_fixed_optimization_parameter(residual, pose_gps.om, pose_gps.om);\n\t\t\t\tresidual_constraint_fixed_optimization_parameter_jacobian(jacobian, pose_gps.om, pose_gps.om);\n\t\t\t\ttripletListA.emplace_back(ir + 3, ic + 3, -jacobian(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, residual);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1000000000);\n\n\t\t\t\tresidual_constraint_fixed_optimization_parameter(residual, pose_gps.fi, pose_gps.fi);\n\t\t\t\tresidual_constraint_fixed_optimization_parameter_jacobian(jacobian, pose_gps.fi, pose_gps.fi);\n\t\t\t\ttripletListA.emplace_back(ir + 4, ic + 4, -jacobian(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, residual);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1000000000);\n\n\t\t\t\tresidual_constraint_fixed_optimization_parameter(residual, pose_gps.ka, pose_gps.ka);\n\t\t\t\tresidual_constraint_fixed_optimization_parameter_jacobian(jacobian, pose_gps.ka, pose_gps.ka);\n\t\t\t\ttripletListA.emplace_back(ir + 5, ic + 5, -jacobian(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, residual);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1000000000);\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 6 + georeference_data.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 + georeference_data.size() * 6, m_poses.size() * 6 + georeference_data.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 + georeference_data.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size() + georeference_data.size() * 6){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: add noise to poses\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan and relative pose to GPS (half A))\" << std::endl;\n\tstd::cout << \"y: optimize (Tait-Bryan and relative pose to GPS (full A))\" << std::endl;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "81adb312a35ecba8fbe9435df9f60f8bd0770809", "size": 36922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/georeference-case2.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/georeference-case2.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/georeference-case2.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": 36.4122287968, "max_line_length": 214, "alphanum_fraction": 0.6599046639, "num_tokens": 12724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.02635535141221375, "lm_q1q2_score": 0.01194587528619492}}
{"text": "/***\n *  $Id$\n **\n *  File: graph_cc.hpp\n *  Created: May 9, 2012\n *\n *  Author: Olga Wodo, Baskar Ganapathysubramanian\n *  Copyright (c) 2012 Olga Wodo, Baskar Ganapthysubramanian\n *  See accompanying LICENSE.\n *\n *  This file is part of GraSPI.\n */\n\n#ifndef GRAPH_CC_HPP\n#define GRAPH_CC_HPP\n\n#include \"graspi_types.hpp\"\n#include \"graspi_predicates.hpp\"\n\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n\nnamespace graspi{\n    /// find the connected components\n    ///\n    /// This function finds the connected components where each component consists of vertices of the same color\n    /// @param G is the graph\n    /// @param C is the vector with the colors of vertices\n    /// @param cVV is the vector storing the indices of the connected component of each vertex, this vector is initialized and filled as a result of this function execution\n    inline void identify_connected_components(\n                                              graspi::graph_t* G,\n                                              const vertex_colors_t& C,\n                                              vertex_ccs_t& vCC ){\n\n        connect_same_color pred(*G, C);\n        boost::filtered_graph<graspi::graph_t,connect_same_color> FG(*G, pred);\n\n        int size_of_G = boost::num_vertices(*G);\n        vCC.resize(size_of_G, 0);\n\n        boost::connected_components(FG, &vCC[0]);\n    }//identify_connected_components\n\n\n    /// This function determines the number of connected components\n    ///\n    /// This function determines the number of connected components once the connected components are identified for each vertex in the graph\n    /// @param vCC is the vector storing the indices of the connected component of each vertex\n    /// @param d_g is the structure storing basic informations about the graph dimensionality\n    /// return the number of connected components (without the meta vertices)\n    inline int determine_number_of_CCs(\n                                       const graspi::vertex_ccs_t& vCC,\n                                       const graspi::dim_g_t& d_g){\n\n        int max_index = 0;\n        // find max index\n        for (unsigned int i = 0; i < vCC.size(); ++i) {\n            std::cout << \"id,cc: \" << i << \" \" << vCC[i] << std::endl;\n            if(vCC[i] > max_index)\n                max_index = vCC[i];\n        }\n        int number_of_conn_comp =  max_index + 1;\n        // correct nOfCC - subtract meta vertices that are identified as separate CC\n        return number_of_conn_comp - d_g.n_meta_total();\n    }//determine_number_of_CCs\n\n\n    /// This function determines the basic statistics of graph in terms of connected components\n    ///\n    /// This function determines the statistics of the graph related to the connected components\n    /// @param G is the input graph\n    /// @param d_g is the structure storing basic informations about the graph dimensionality\n    /// @param CCs is structure storing information about individual components (e.g. if the CC is connected to meta vertex)\n    /// @param C is the vector with the colors of vertices\n    /// @param vCC is the vector storing the indices of the connected component of each vertex\n    inline void\n    determine_basic_stats_of_ccs( graspi::graph_t* G,\n                                 const graspi::dim_g_t& d_g,\n                                 graspi::ccs_t& CCs,\n                                 const graspi::vertex_colors_t& C,\n                                 const graspi::vertex_ccs_t&   vCCs ){\n\n        std::vector<int>::const_iterator it = max_element( vCCs.begin(),\n                                                          vCCs.end() );\n        CCs.resize( (*it)+1 );\n\n#ifdef DEBUG\n        std::cout << \"Total number of connected components\" << *it << std::endl;\n#endif\n        for (unsigned int  i = 0; i < vCCs.size(); i++){\n            CCs[vCCs[i]].color = C[i];\n            CCs[vCCs[i]].size++;\n        }\n\n//        unsigned int size_of_G = boost::num_vertices(*G);\n\n        // determine all vertices connected to the bottom electrode\n        std::set<int> comp_conn_to_electrode;\n        graspi::vertex_t source = d_g.id_blue(); // bottom electrode index\n        graspi::graph_t::adjacency_iterator u, u_end;\n        boost::tie(u, u_end) = boost::adjacent_vertices(source, *G);\n        for (; u != u_end; ++u) {\n            comp_conn_to_electrode.insert(vCCs[*u]);\n        }\n\n#ifdef DEBUG\n        std::cout << \"Id of connected components connected to bottom \" << std::endl;\n        copy(comp_conn_to_electrode.begin(), comp_conn_to_electrode.end(),\n             std::ostream_iterator<int>(std::cout, \" \"));\n        std::cout << std::endl;\n#endif\n\n        // pass info about connectivity to bottom electrode to data of components\n        for(unsigned int  i = 0; i < CCs.size(); i++ ){\n            if( comp_conn_to_electrode.find(i) != comp_conn_to_electrode.end() )\n                CCs[i].if_connected_to_electrode += 1;\n        }\n\n        // determine all vertices connected to the top electrode\n        comp_conn_to_electrode.clear();\n        source = d_g.id_red(); // top electrode index\n        boost::tie(u, u_end) = boost::adjacent_vertices(source, *G);\n        for (; u != u_end; ++u) {\n            comp_conn_to_electrode.insert(vCCs[*u]);\n        }\n\n#ifdef DEBUG\n        std::cout << \"Id of connected components conn to top \" << std::endl;\n        std::set<int>::iterator its = comp_conn_to_electrode.begin();\n        for (int i = 0; i < comp_conn_to_electrode.size(); i++){\n            int id = *its;\n            std::cout << id << \" \" << CCs[id].color << std::endl;\n            its++;\n        }\n        std::cout << std::endl;\n#endif\n\n\n        // pass info about connectivity to top electrode to data of components\n        for(unsigned int  i = 0; i < CCs.size(); i++ ){\n            if( comp_conn_to_electrode.find(i) != comp_conn_to_electrode.end() )\n                CCs[i].if_connected_to_electrode += 2;\n        }\n    }//determine_basic_stats_of_ccs\n\n\n\n\n}\n#endif\n", "meta": {"hexsha": "cae7c3182d0133f47960099b59dcb7f974be03e9", "size": 6008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graph_cc.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/graph_cc.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/graph_cc.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": 39.7880794702, "max_line_length": 172, "alphanum_fraction": 0.6013648469, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894545235253, "lm_q2_score": 0.035678547160777, "lm_q1q2_score": 0.01193766563271625}}
{"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/rotation.h\"\n#include \"pxr/base/tf/pyUtils.h\"\n#include \"pxr/base/tf/wrapTypeHelpers.h\"\n#include \"pxr/base/tf/pyContainerConversions.h\"\n\n#include <boost/python/class.hpp>\n#include <boost/python/copy_const_reference.hpp>\n#include <boost/python/operators.hpp>\n#include <boost/python/return_arg.hpp>\n\n#include <string>\n\nusing namespace boost::python;\n\nusing std::string;\n\nPXR_NAMESPACE_USING_DIRECTIVE\n\nnamespace {\n\nvoid SetAxisHelper( GfRotation &rotation, const GfVec3d &axis )\n{\n    rotation.SetAxisAngle( axis, rotation.GetAngle() );\n}\n\nvoid SetAngleHelper( GfRotation &rotation, double angle )\n{\n    rotation.SetAxisAngle( rotation.GetAxis(), angle );\n}\n\nstatic tuple\n_DecomposeRotation3(const GfMatrix4d &rot,\n                    const GfVec3d &TwAxis,\n                    const GfVec3d &FBAxis,\n                    const GfVec3d &LRAxis,\n                    double handedness,\n                    double thetaTwHint,\n                    double thetaFBHint,\n                    double thetaLRHint,\n                    bool useHint)\n{\n    double angle[3] = {thetaTwHint, thetaFBHint, thetaLRHint};\n\n    GfRotation::DecomposeRotation(rot, TwAxis, FBAxis, LRAxis, handedness,\n                                  &(angle[0]),\n                                  &(angle[1]),\n                                  &(angle[2]),\n                                  NULL /* thetaSwHint */, \n                                  useHint,\n                                  NULL /* swShift */);\n\n    return make_tuple(angle[0], angle[1], angle[2]);\n}\n\nstatic tuple\n_DecomposeRotation(const GfMatrix4d &rot,\n                    const GfVec3d &TwAxis,\n                    const GfVec3d &FBAxis,\n                    const GfVec3d &LRAxis,\n                    double handedness,\n                    const object &thetaTwHint,\n                    const object &thetaFBHint,\n                    const object &thetaLRHint,\n                    const object &thetaSwHint,\n                    bool useHint,\n                    const object & swShiftIn)\n{\n    double angle[4] = {\n        thetaTwHint.ptr() != Py_None ? \n            boost::python::extract<double>(thetaTwHint) : 0.0,\n        thetaFBHint.ptr() != Py_None ? \n            boost::python::extract<double>(thetaFBHint) : 0.0,\n        thetaLRHint.ptr() != Py_None ? \n            boost::python::extract<double>(thetaLRHint) : 0.0,\n        thetaSwHint.ptr() != Py_None ? \n            boost::python::extract<double>(thetaSwHint) : 0.0\n        };\n    double swShift = swShiftIn.ptr() != Py_None ? \n        boost::python::extract<double>(swShiftIn) : 0.0;\n\n    GfRotation::DecomposeRotation(\n        rot, TwAxis, FBAxis, LRAxis, handedness,\n        thetaTwHint.ptr() != Py_None ? &(angle[0]) : NULL,\n        thetaFBHint.ptr() != Py_None ? &(angle[1]) : NULL,\n        thetaLRHint.ptr() != Py_None ? &(angle[2]) : NULL,\n        thetaSwHint.ptr() != Py_None ? &(angle[3]) : NULL,\n        useHint,\n        swShiftIn.ptr() != Py_None ? &swShift : NULL);\n\n    return make_tuple(angle[0], angle[1], angle[2], angle[3]);\n}\n\nstatic string _Repr(GfRotation const &self) {\n    return TF_PY_REPR_PREFIX + \"Rotation(\" + TfPyRepr(self.GetAxis()) + \", \" +\n        TfPyRepr(self.GetAngle()) + \")\";\n}\n\n#if PY_MAJOR_VERSION == 2\nstatic GfRotation __truediv__(const GfRotation &self, double value)\n{\n    return self / value;\n}\n\nstatic GfRotation __itruediv__(GfRotation &self, double value)\n{\n    return self /= value;\n}\n#endif\n\n} // anonymous namespace \n\nvoid wrapRotation()\n{    \n    typedef GfRotation This;\n\n    class_<This> ( \"Rotation\", \"3-space rotation\", init<>())\n\n        .def(init<const GfVec3d &, double>())\n        .def(init<const GfQuaternion &>())\n        .def(init<const GfQuatd &>())\n        .def(init<const GfVec3d &, const GfVec3d &>())\n\n        .def( TfTypePythonClass() )\n\n        .def(\"SetAxisAngle\", &This::SetAxisAngle, return_self<>(),\n             (args(\"axis\"), args(\"angle\")))\n        .def(\"SetQuat\", &This::SetQuat, return_self<>(), (args(\"quat\")))\n        .def(\"SetQuaternion\", &This::SetQuaternion, return_self<>(),\n             (args(\"quaternion\")))\n        .def(\"SetRotateInto\", &This::SetRotateInto, return_self<>(),\n             (args(\"rotateFrom\"), args(\"rotateTo\")))\n        .def(\"SetIdentity\", &This::SetIdentity, return_self<>())\n\n        .add_property(\"axis\", make_function(&This::GetAxis, return_value_policy<copy_const_reference>()),\n                      SetAxisHelper )\n        .add_property(\"angle\", &This::GetAngle, SetAngleHelper)\n\n        .def(\"GetAxis\", &This::GetAxis, return_value_policy<copy_const_reference>())\n        .def(\"GetAngle\", &This::GetAngle)\n\n        .def(\"GetQuaternion\", &This::GetQuaternion)\n        .def(\"GetQuat\", &This::GetQuat)\n\n        .def(\"GetInverse\", &This::GetInverse)\n\n        .def(\"Decompose\", &This::Decompose)\n\n        .def(\"DecomposeRotation3\", _DecomposeRotation3,\n             (arg(\"rot\"),\n              arg(\"twAxis\"),\n              arg(\"fbAxis\"),\n              arg(\"lrAxis\"),\n              arg(\"handedness\"),\n              arg(\"thetaTwHint\") = 0.0,\n              arg(\"thetaFBHint\") = 0.0,\n              arg(\"thetaLRHint\") = 0.0,\n              arg(\"useHint\") = false)\n             )\n        .staticmethod(\"DecomposeRotation3\")\n\n        .def(\"DecomposeRotation\", _DecomposeRotation,\n             (arg(\"rot\"),\n              arg(\"twAxis\"),\n              arg(\"fbAxis\"),\n              arg(\"lrAxis\"),\n              arg(\"handedness\"),\n              arg(\"thetaTwHint\"),\n              arg(\"thetaFBHint\"),\n              arg(\"thetaLRHint\"),\n              arg(\"thetaSwHint\") = object(),\n              arg(\"useHint\") = false,\n              arg(\"swShift\") = object())\n             )\n        .staticmethod(\"DecomposeRotation\")\n\n        .def(\"RotateOntoProjected\", &This::RotateOntoProjected)\n        .staticmethod(\"RotateOntoProjected\")\n\n        .def(\"TransformDir\", (GfVec3f (This::*)( const GfVec3f & ) const)&This::TransformDir )\n        .def(\"TransformDir\", (GfVec3d (This::*)( const GfVec3d & ) const)&This::TransformDir )\n\n        .def( str(self) )\n        .def( self == self )\n        .def( self != self )\n        .def( self *= self )\n        .def( self *= double() )\n        .def( self /= double() )\n        .def( self * self )\n        .def( self * double() )\n        .def( double() * self )\n        .def( self / double() )\n\n #if PY_MAJOR_VERSION == 2\n        // Needed only to support \"from __future__ import division\" in\n        // python 2. In python 3 builds boost::python adds this for us.\n        .def(\"__truediv__\", __truediv__ )\n        .def(\"__itruediv__\", __itruediv__ )\n#endif\n\n       .def(\"__repr__\", _Repr)\n        \n        ;\n    to_python_converter<std::vector<This>,\n        TfPySequenceToPython<std::vector<This> > >();\n    \n}\n", "meta": {"hexsha": "73f78c4f07cef1908cf7bf10b2efb233e67ec42c", "size": 7847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pxr/base/gf/wrapRotation.cpp", "max_stars_repo_name": "DougRogers-DigitalFish/USD", "max_stars_repo_head_hexsha": "d8a405a1344480f859f025c4f97085143efacb53", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T18:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T11:30:28.000Z", "max_issues_repo_path": "pxr/base/gf/wrapRotation.cpp", "max_issues_repo_name": "DougRogers-DigitalFish/USD", "max_issues_repo_head_hexsha": "d8a405a1344480f859f025c4f97085143efacb53", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-12-16T03:19:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:14:02.000Z", "max_forks_repo_path": "pxr/base/gf/wrapRotation.cpp", "max_forks_repo_name": "DougRogers-DigitalFish/USD", "max_forks_repo_head_hexsha": "d8a405a1344480f859f025c4f97085143efacb53", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-08-10T02:40:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:30:10.000Z", "avg_line_length": 33.8232758621, "max_line_length": 105, "alphanum_fraction": 0.5779278705, "num_tokens": 1977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.024423088767072568, "lm_q1q2_score": 0.011925388706797754}}
{"text": "// Copyright (c) 2018, The Remix Project\n//\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other\n//    materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    used to endorse or promote products derived from this software without specific\n//    prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers\n\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <cstdint>\n#include <vector>\n\n#include \"common/int-util.h\"\n#include \"crypto/hash.h\"\n#include \"cryptonote_config.h\"\n#include \"difficulty.h\"\n#include <boost/math/special_functions/round.hpp>\n\n#undef REMIX_DEFAULT_LOG_CATEGORY\n#define REMIX_DEFAULT_LOG_CATEGORY \"difficulty\"\n\nnamespace cryptonote {\n\n  using std::size_t;\n  using std::uint64_t;\n  using std::vector;\n\n\n#if defined(__x86_64__)\n  static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n    low = mul128(a, b, &high);\n  }\n\n#else\n\n  static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n    // __int128 isn't part of the standard, so the previous function wasn't portable. mul128() in Windows is fine,\n    // but this portable function should be used elsewhere. Credit for this function goes to latexi95.\n\n    uint64_t aLow = a & 0xFFFFFFFF;\n    uint64_t aHigh = a >> 32;\n    uint64_t bLow = b & 0xFFFFFFFF;\n    uint64_t bHigh = b >> 32;\n\n    uint64_t res = aLow * bLow;\n    uint64_t lowRes1 = res & 0xFFFFFFFF;\n    uint64_t carry = res >> 32;\n\n    res = aHigh * bLow + carry;\n    uint64_t highResHigh1 = res >> 32;\n    uint64_t highResLow1 = res & 0xFFFFFFFF;\n\n    res = aLow * bHigh;\n    uint64_t lowRes2 = res & 0xFFFFFFFF;\n    carry = res >> 32;\n\n    res = aHigh * bHigh + carry;\n    uint64_t highResHigh2 = res >> 32;\n    uint64_t highResLow2 = res & 0xFFFFFFFF;\n\n    //Addition\n\n    uint64_t r = highResLow1 + lowRes2;\n    carry = r >> 32;\n    low = (r << 32) | lowRes1;\n    r = highResHigh1 + highResLow2 + carry;\n    uint64_t d3 = r & 0xFFFFFFFF;\n    carry = r >> 32;\n    r = highResHigh2 + carry;\n    high = d3 | (r << 32);\n  }\n\n#endif\n\n  static inline bool cadd(uint64_t a, uint64_t b) {\n    return a + b < a;\n  }\n\n  static inline bool cadc(uint64_t a, uint64_t b, bool c) {\n    return a + b < a || (c && a + b == (uint64_t) -1);\n  }\n\n  bool check_hash(const crypto::hash &hash, difficulty_type difficulty) {\n    uint64_t low, high, top, cur;\n    // First check the highest word, this will most likely fail for a random hash.\n    mul(swap64le(((const uint64_t *) &hash)[3]), difficulty, top, high);\n    if (high != 0) {\n      return false;\n    }\n    mul(swap64le(((const uint64_t *) &hash)[0]), difficulty, low, cur);\n    mul(swap64le(((const uint64_t *) &hash)[1]), difficulty, low, high);\n    bool carry = cadd(cur, low);\n    cur = high;\n    mul(swap64le(((const uint64_t *) &hash)[2]), difficulty, low, high);\n    carry = cadc(cur, low, carry);\n    carry = cadc(high, top, carry);\n    return !carry;\n  }\n  \n  difficulty_type next_difficulty(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {\n\n    const int64_t T = static_cast<int64_t>(target_seconds);\n    size_t N = DIFFICULTY_WINDOW;\n    int64_t FTL = static_cast<int64_t>(CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT);\n\n    // Return a difficulty of 1 for first 3 blocks if it's the start of the chain.\n    if (timestamps.size() < 4) {\n      return 1;    \n    }\n    // Otherwise, use a smaller N if the start of the chain is less than N+1.\n    else if ( timestamps.size() < N+1 ) {\n      N = timestamps.size() - 1;\n    }\n    // Otherwise make sure timestamps and cumulative_difficulties are correct size.\n    else {\n      timestamps.resize(N+1);\n      cumulative_difficulties.resize(N+1);\n    }\n    // To get an average solvetime to within +/- ~0.1%, use an adjustment factor.\n    // adjust=0.998 for N = 60\n    const double adjust = 0.998;\n    // The divisor k normalizes the LWMA sum to a standard LWMA.\n    const double k = N * (N + 1) / 2;    \n    \n    double LWMA(0), sum_inverse_D(0), harmonic_mean_D(0), nextDifficulty(0);\n    int64_t solveTime(0);\n    uint64_t difficulty(0), next_difficulty(0);\n\n    // Loop through N most recent blocks. N is most recently solved block.\n    for (size_t i = 1; i <= N; i++) {\n      solveTime = static_cast<int64_t>(timestamps[i]) - static_cast<int64_t>(timestamps[i - 1]);\n      solveTime = std::min<int64_t>((T * 10), std::max<int64_t>(solveTime, -FTL));\n      difficulty = cumulative_difficulties[i] - cumulative_difficulties[i - 1];\n      LWMA += (int64_t)(solveTime * i) / k;\n      sum_inverse_D += 1 / static_cast<double>(difficulty);\n    }\n\n    harmonic_mean_D = N / sum_inverse_D;\n\n    // Limit LWMA same as Bitcoin's 1/4 in case something unforeseen occurs.\n    if (static_cast<int64_t>(boost::math::round(LWMA)) < T / 4)\n      LWMA = static_cast<double>(T / 4);\n\n    nextDifficulty = harmonic_mean_D * T / LWMA * adjust;\n\n    // No limits should be employed, but this is correct way to employ a 20% symmetrical limit:\n    // nextDifficulty=max(previous_Difficulty*0.8,min(previous_Difficulty/0.8, next_Difficulty));\n    next_difficulty = static_cast<uint64_t>(nextDifficulty);\n    return next_difficulty;\n  }\n\n\n  // LWMA-2 difficulty algorithm (commented version)\n  // Copyright (c) 2017-2018 Zawy\n  // https://github.com/zawy12/difficulty-algorithms/issues/3\n  // Bitcoin clones must lower their FTL. \n  // Cryptonote et al coins must make the following changes:\n  // #define BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW    11\n  // #define CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT        3 * DIFFICULTY_TARGET \n  // #define DIFFICULTY_WINDOW                      60 + 1\n  // Do not sort timestamps.  CN coins must deploy the Jagerman MTP Patch. See:\n  // https://github.com/loki-project/loki/pull/26   or\n  // https://github.com/wownero/wownero/commit/1f6760533fcec0d84a6bd68369e0ea26716b01e7\n\n  // New coins:  \"return 100;\" should have the 100 changed based on expected hashrate.\n\n  difficulty_type next_difficulty_v2(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds, size_t height) {\n    \n    \n    double T = DIFFICULTY_TARGET; // target solvetime seconds\n    double N = DIFFICULTY_WINDOW - 1; //  N=45, 60, and 90 for T=600, 120, 60.\n    double FTL = CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT; // < 3xT\n    double L(0), sum_6_ST(0), sum_9_ST(0), ST, next_D, prev_D, SMAn, SMAd;\n\n    // If expecting a 10x decrease or 1000x increase in D after a fork, consider: \n    // if ( height >= fork_height && height < fork_height+62 )  { return uint64_t difficulty_guess; }\n\n    // TS and CD vectors should be size 61 after startup.\n    if ( timestamps.size() > N  ) { timestamps.resize(N+1); cumulative_difficulties.resize(N+1);  }\n    else if (timestamps.size() < 4)  {  return 100;  } // start up\n    else  {  N = timestamps.size() - 1;  } // start up\n\n    // N is most recently solved block. i must be signed\n    for ( int64_t i = 1; i <= N; i++) {  \n        // +/- FTL limits are bad timestamp protection.  6xT limits drop in D to reduce oscillations.\n        ST = std::max(-FTL, std::min(double(timestamps[i] - timestamps[i-1]), 6*T));\n        L +=  ST * i ; // Give more weight to most recent blocks.\n        // Do these inside loop to capture -FTL and +6*T limitations.\n        if ( i > N-6 ) { sum_6_ST += ST; }      \n        if ( i > N-9 ) { sum_9_ST += ST; }     \n    }\n    if (L < T*N) { L= T*N*6; } // sanity limit. Accidentally limits D rise at startup for ~60 blocks.\n\n    // Calculate next_D = avgD * T / LWMA(STs) \n    next_D = (cumulative_difficulties[N] - cumulative_difficulties[0]) * T*(N+1)*0.991 / (L*2);\n\n    // LWMA-2 change from LWMA\n    // Trigger sudden increase in D if hash attack is detected. Also limit rate of fall in D.\n    // ====  begin LWMA-2 trigger and fall limitations  ====\n\n    prev_D = cumulative_difficulties[N] - cumulative_difficulties[N-1];\n\n    // Use Digishield-type tempered SMA to get long-term (~4*N) avg D to limit how high \n    // consecutive triggers can send D.\n    SMAn = (cumulative_difficulties[N] - cumulative_difficulties[0]) * 4 *T;\n    SMAd = 3*N + double( timestamps[N] - timestamps[0] ); \n\n    // If a trigger would send D>1.7*avgD, then don't do it.\n    // 1.70 allows 30% increase for 2 consecutive blocks and 14% for 4 blocks.\n    // Tempered SMA = SMAn / SMAd, but do not divide for round off protection\n\n    if  ( 1.14*next_D*SMAd > 1.70*SMAn ) {  \n        if ( next_D < 0.7*prev_D ) { next_D = 0.7*prev_D; }\n    }\n    else if  ( 1.3*next_D*SMAd < 1.70*SMAn && sum_6_ST < 1.2*T )   {\n        next_D = 1.3*prev_D; \n    }\n    else if (sum_9_ST < 3.4*T )   {  next_D = 1.14*prev_D;  }\n    // Prevent D falling too much after triggers, as long as D is not > 1.7*avgD\n    else if  ( next_D < 0.9*prev_D )  { next_D = 0.9*prev_D;  }\n\n    // ==== end LWMA-2's trigger and fall limitations ====\n\n    // Prevent round off difference between systems to prevent chain split.\n    // Theoretically not needed by C++ standard.  Requires D > 1. Needs 1E12 > D > 100.\n\n    if  ( ceil(next_D + 0.01) > ceil(next_D) ) { next_D = ceil(next_D + 0.03);  }\n\n    // next_Target = sumTargets*L*2/0.998/T/(N+1)/N/N; // To show the difference.\n\n    return static_cast<uint64_t>(next_D);\n    \n  }\n}\n\n\n\n\n\n", "meta": {"hexsha": "88f12a9d2b8b3f062040393de96a067e6c75e4ac", "size": 10603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_stars_repo_name": "devopsralf/remix", "max_stars_repo_head_hexsha": "12220615d3011b4a86184bd83a390b50d1ee56cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-01T10:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T05:31:47.000Z", "max_issues_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_issues_repo_name": "devopsralf/remix", "max_issues_repo_head_hexsha": "12220615d3011b4a86184bd83a390b50d1ee56cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-09-28T06:10:04.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-19T21:44:03.000Z", "max_forks_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_forks_repo_name": "devopsralf/remix", "max_forks_repo_head_hexsha": "12220615d3011b4a86184bd83a390b50d1ee56cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T22:50:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-23T23:02:15.000Z", "avg_line_length": 40.1628787879, "max_line_length": 169, "alphanum_fraction": 0.6675469207, "num_tokens": 3077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.024423088234506524, "lm_q1q2_score": 0.011925388446754599}}
{"text": "/*\n\nCopyright (c) 2005-2015, 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#include \"PottsMeshGenerator.hpp\"\n\n#include <boost/scoped_array.hpp>\n\ntemplate<unsigned DIM>\nPottsMeshGenerator<DIM>::PottsMeshGenerator(unsigned numNodesAcross, unsigned numElementsAcross, unsigned elementWidth,\n                                            unsigned numNodesUp, unsigned numElementsUp, unsigned elementHeight,\n                                            unsigned numNodesDeep, unsigned numElementsDeep, unsigned elementDepth,\n                                            bool startAtBottomLeft, bool isPeriodicInX, bool isPeriodicInY ,bool isPeriodicInZ)\n{\n    assert(numNodesAcross > 0);\n    assert(numNodesUp > 0);\n    assert(numNodesDeep > 0);\n\n    assert(numElementsAcross*elementWidth <= numNodesAcross);\n    assert(numElementsUp*elementHeight <= numNodesUp);\n    assert(numElementsDeep*elementDepth <= numNodesDeep);\n\n    std::vector<Node<DIM>*> nodes;\n    std::vector<PottsElement<DIM>*>  elements;\n    std::vector<std::set<unsigned> > moore_neighbours;\n    std::vector<std::set<unsigned> > von_neumann_neighbours;\n\n    unsigned num_nodes = numNodesAcross*numNodesUp*numNodesDeep;\n\n    unsigned next_node_index = 0;\n    boost::scoped_array<unsigned> node_indices(new unsigned[elementWidth*elementHeight*elementDepth]);\n    unsigned element_index;\n\n    unsigned index_offset = 0;\n\n    if (!startAtBottomLeft) // Elements in centre of mesh\n    {\n        // Calculate the width of the medium on the edge and offset the node index so that the elements are in the centre of the mesh.\n        unsigned across_gap = (numNodesAcross -  numElementsAcross*elementWidth)/2;\n        unsigned up_gap = (numNodesUp -  numElementsUp*elementHeight)/2;\n        unsigned deep_gap = (numNodesDeep -  numElementsDeep*elementDepth)/2;\n\n        index_offset = deep_gap*numNodesAcross*numNodesUp + up_gap*numNodesAcross + across_gap;\n    }\n\n    /*\n     * Create the nodes, row by row, from the bottom up\n     * On the first and last row we have numNodesAcross nodes, all of which are boundary\n     * nodes. On each interior row we have numNodesAcross nodes, the first and last nodes\n     * are boundary nodes.\n     */\n    for (unsigned k=0; k<numNodesDeep; k++)\n    {\n        for (unsigned j=0; j<numNodesUp; j++)\n        {\n            for (unsigned i=0; i<numNodesAcross; i++)\n            {\n                bool is_boundary_node=false;\n                if (DIM==2)\n                {\n                    is_boundary_node = (j==0 || j==numNodesUp-1 || (i==0 && !isPeriodicInX) || (i==numNodesAcross-1 && !isPeriodicInX) ) ? true : false;\n                }\n                if (DIM==3)\n                {\n                    is_boundary_node = (j==0 || j==numNodesUp-1 || (i==0 && !isPeriodicInX) || (i==numNodesAcross-1 && !isPeriodicInX) || k==0 || k==numNodesDeep-1) ? true : false;\n                }\n                Node<DIM>* p_node = new Node<DIM>(next_node_index, is_boundary_node, i, j, k);\n                nodes.push_back(p_node);\n                next_node_index++;\n            }\n        }\n    }\n    assert(nodes.size()==num_nodes);\n\n    /*\n     * Create the elements. The array node_indices contains the\n     * global node indices, in increasing order.\n     */\n    for (unsigned n=0; n<numElementsDeep; n++)\n    {\n        for (unsigned j=0; j<numElementsUp; j++)\n        {\n            for (unsigned i=0; i<numElementsAcross; i++)\n            {\n                for (unsigned m=0; m<elementDepth; m++)\n                {\n                    for (unsigned l=0; l<elementHeight; l++)\n                    {\n                        for (unsigned k=0; k<elementWidth; k++)\n                        {\n                            node_indices[m*elementHeight*elementWidth + l*elementWidth + k] = n*elementDepth*numNodesUp*numNodesAcross +\n                                                                                              j*elementHeight*numNodesAcross +\n                                                                                              i*elementWidth +\n                                                                                              m*numNodesAcross*numNodesUp +\n                                                                                              l*numNodesAcross +\n                                                                                              k + index_offset;\n                        }\n                    }\n                }\n                std::vector<Node<DIM>*> element_nodes;\n                for (unsigned k=0; k<elementDepth*elementHeight*elementWidth; k++)\n                {\n                   element_nodes.push_back(nodes[node_indices[k]]);\n                }\n\n                element_index = n*numElementsAcross*numElementsUp + j*numElementsAcross + i;\n                PottsElement<DIM>* p_element = new PottsElement<DIM>(element_index, element_nodes);\n                elements.push_back(p_element);\n            }\n        }\n    }\n\n    /*\n     * Create the neighborhoods of each node\n     */\n\n    moore_neighbours.resize(num_nodes);\n    von_neumann_neighbours.resize(num_nodes);\n\n    for (unsigned node_index=0; node_index<num_nodes; node_index++)\n    {\n        // Clear the set of neighbouring node indices\n\n        moore_neighbours[node_index].clear();\n\n        switch (DIM)\n        {\n            case 2:\n            {\n                assert(DIM == 2);\n                /*\n                 * This stores the available neighbours using the following numbering:\n                 *\n                 *  1-----0-----7\n                 *  |     |     |\n                 *  |     |     |\n                 *  2-----x-----6\n                 *  |     |     |\n                 *  |     |     |\n                 *  3-----4-----5\n                 */\n\n                // Create a vector of possible neighbouring node indices\n                std::vector<unsigned> moore_neighbour_indices_vector(8, node_index);\n                moore_neighbour_indices_vector[0] += numNodesAcross;\n                moore_neighbour_indices_vector[1] += numNodesAcross - 1;\n                moore_neighbour_indices_vector[2] -= 1;\n                moore_neighbour_indices_vector[3] -= numNodesAcross + 1;\n                moore_neighbour_indices_vector[4] -= numNodesAcross;\n                moore_neighbour_indices_vector[5] -= numNodesAcross - 1;\n                moore_neighbour_indices_vector[6] += 1;\n                moore_neighbour_indices_vector[7] += numNodesAcross + 1;\n\n                // Work out whether this node lies on any edge of the mesh\n                bool on_south_edge = (node_index < numNodesAcross);\n                bool on_north_edge = ((int) node_index > (int)numNodesAcross*((int)numNodesUp - 1) - 1);\n                bool on_west_edge = (node_index%numNodesAcross == 0);\n                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);\n\n                if (isPeriodicInX)\n                {\n                    if (on_west_edge)\n                    {\n                        moore_neighbour_indices_vector[1] = node_index + 2*numNodesAcross - 1;\n                        moore_neighbour_indices_vector[2] = node_index + numNodesAcross - 1;\n                        moore_neighbour_indices_vector[3] = node_index - 1;\n                    }\n\n                    if (on_east_edge)\n                    {\n                        moore_neighbour_indices_vector[5] = node_index - 2*numNodesAcross + 1;\n                        moore_neighbour_indices_vector[6] = node_index - numNodesAcross + 1;\n                        moore_neighbour_indices_vector[7] = node_index + 1;\n                    }\n                }\n\n                if (isPeriodicInY)\n                {\n                    if (on_north_edge)\n                    {\n                        moore_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);\n                        moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[0] - 1;\n                        moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[0] + 1;\n\n                        if (on_west_edge)\n                        {\n                            moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[1] + numNodesAcross;\n                        }\n                        if (on_east_edge)\n                        {\n                            moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[7] - numNodesAcross;\n                        }\n                    }\n\n                    if (on_south_edge)\n                    {\n                        moore_neighbour_indices_vector[4] = node_index + numNodesAcross*(numNodesUp-1);\n                        moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[4] - 1;\n                        moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[4] + 1;\n\n                        if (on_west_edge)\n                        {\n                            moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[3] + numNodesAcross;\n                        }\n                        if (on_east_edge)\n                        {\n                            moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[5] - numNodesAcross;\n                        }\n                    }\n                }\n\n                if (isPeriodicInX)\n                {\n                    on_east_edge = false;\n                    on_west_edge = false;\n                }\n                if (isPeriodicInY)\n                {\n                    on_south_edge = false;\n                    on_north_edge = false;\n                }\n\n                // Create a vector of booleans for which neighbours are available\n                // Use the order N, NW, W, SW, S, SE, E, NE\n                std::vector<bool> available_neighbours = std::vector<bool>(8, true);\n                available_neighbours[0] = !on_north_edge;\n                available_neighbours[1] = !(on_north_edge || on_west_edge);\n                available_neighbours[2] = !on_west_edge;\n                available_neighbours[3] = !(on_south_edge || on_west_edge);\n                available_neighbours[4] = !on_south_edge;\n                available_neighbours[5] = !(on_south_edge || on_east_edge);\n                available_neighbours[6] = !on_east_edge;\n                available_neighbours[7] = !(on_north_edge || on_east_edge);\n\n                // Using neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours\n                for (unsigned i=0; i<8; i++)\n                {\n                    if (available_neighbours[i])\n                    {\n                        assert(moore_neighbour_indices_vector[i] < nodes.size());\n                        moore_neighbours[node_index].insert(moore_neighbour_indices_vector[i]);\n                    }\n                }\n                break;\n            }\n            case 3:\n            {\n                assert(DIM ==3);\n                /*\n                 * This stores the available neighbours using the following numbering:\n                 *                      FRONT           BACK\n                 *  1-----0-----7   10-----9---16   19----18---25\n                 *  |     |     |   |     |     |   |     |     |\n                 *  |     |     |   |     |     |   |     |     |\n                 *  2-----x-----6   11----8-----15  20----17---24\n                 *  |     |     |   |     |     |   |     |     |\n                 *  |     |     |   |     |     |   |     |     |\n                 *  3-----4-----5   12----13----14  21---22----23\n                 */\n\n                // Create a vector of possible neighbouring node indices\n                std::vector<unsigned> moore_neighbour_indices_vector(26, node_index);\n                moore_neighbour_indices_vector[0] += numNodesAcross;\n                moore_neighbour_indices_vector[1] += numNodesAcross - 1;\n                moore_neighbour_indices_vector[2] -= 1;\n                moore_neighbour_indices_vector[3] -= numNodesAcross + 1;\n                moore_neighbour_indices_vector[4] -= numNodesAcross;\n                moore_neighbour_indices_vector[5] -= numNodesAcross - 1;\n                moore_neighbour_indices_vector[6] += 1;\n                moore_neighbour_indices_vector[7] += numNodesAcross + 1;\n                moore_neighbour_indices_vector[8] -= numNodesAcross*numNodesUp;\n                for (unsigned i=9; i<17; i++)\n                {\n                    moore_neighbour_indices_vector[i] = moore_neighbour_indices_vector[i-9]-numNodesAcross*numNodesUp;\n                }\n                moore_neighbour_indices_vector[17] += numNodesAcross*numNodesUp;\n                for (unsigned i=18; i<26; i++)\n                {\n                    moore_neighbour_indices_vector[i]=moore_neighbour_indices_vector[i-18]+numNodesAcross*numNodesUp;\n                }\n\n                // Work out whether this node lies on any edge of the mesh\n                bool on_south_edge = (node_index%(numNodesAcross*numNodesUp)<numNodesAcross);\n                bool on_north_edge = (node_index%(numNodesAcross*numNodesUp)>(numNodesAcross*numNodesUp-numNodesAcross-1));\n                bool on_west_edge = (node_index%numNodesAcross == 0);\n                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);\n                bool on_front_edge = (node_index < numNodesAcross*numNodesUp);\n                bool on_back_edge = (node_index > numNodesAcross*numNodesUp*(numNodesDeep-1)-1);\n\n                if (isPeriodicInX)\n                {\n                    if (on_west_edge)\n                    {\n                        moore_neighbour_indices_vector[1] = node_index + 2*numNodesAcross - 1;\n                        moore_neighbour_indices_vector[2] = node_index + numNodesAcross - 1;\n                        moore_neighbour_indices_vector[3] = node_index - 1;\n\n                        moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[1] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[11] = moore_neighbour_indices_vector[2] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[3] - numNodesAcross*numNodesUp;\n\n                        moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[1] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[20] = moore_neighbour_indices_vector[2] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[3] + numNodesAcross*numNodesUp;\n                    }\n\n                    if (on_east_edge)\n                    {\n                        moore_neighbour_indices_vector[5] = node_index - 2*numNodesAcross + 1;\n                        moore_neighbour_indices_vector[6] = node_index - numNodesAcross + 1;\n                        moore_neighbour_indices_vector[7] = node_index + 1;\n\n                        moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[5] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[15] = moore_neighbour_indices_vector[6] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[7] - numNodesAcross*numNodesUp;\n\n                        moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[5] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[24] = moore_neighbour_indices_vector[6] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[7] + numNodesAcross*numNodesUp;\n                    }\n                }\n\n                if (isPeriodicInY)\n                {\n                    if (on_north_edge)\n                    {\n                        moore_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);\n                        moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[0] - 1;\n                        moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[0] + 1;\n\n                        moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[1] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[9] = moore_neighbour_indices_vector[0] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[7] - numNodesAcross*numNodesUp;\n\n                        moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[1] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[18] = moore_neighbour_indices_vector[0] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[7] + numNodesAcross*numNodesUp;\n\n                        if (on_west_edge)\n                        {\n                            moore_neighbour_indices_vector[1] = moore_neighbour_indices_vector[1] + numNodesAcross;\n                            moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[10] + numNodesAcross;\n                            moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[19] + numNodesAcross;\n                        }\n                        if (on_east_edge)\n                        {\n                            moore_neighbour_indices_vector[7] = moore_neighbour_indices_vector[7] - numNodesAcross;\n                            moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[16] - numNodesAcross;\n                            moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[25] - numNodesAcross;\n                        }\n                    }\n\n                    if (on_south_edge)\n                    {\n                        moore_neighbour_indices_vector[4] = node_index + numNodesAcross*(numNodesUp-1);\n                        moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[4] - 1;\n                        moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[4] + 1;\n\n                        moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[3] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[13] = moore_neighbour_indices_vector[4] - numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[5] - numNodesAcross*numNodesUp;\n\n                        moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[3] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[22] = moore_neighbour_indices_vector[4] + numNodesAcross*numNodesUp;\n                        moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[5] + numNodesAcross*numNodesUp;\n\n                        if (on_west_edge)\n                        {\n                            moore_neighbour_indices_vector[3] = moore_neighbour_indices_vector[3] + numNodesAcross;\n                            moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[12] + numNodesAcross;\n                            moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[21] + numNodesAcross;\n                        }\n                        if (on_east_edge)\n                        {\n                            moore_neighbour_indices_vector[5] = moore_neighbour_indices_vector[5] - numNodesAcross;\n                            moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[14] - numNodesAcross;\n                            moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[23] - numNodesAcross;\n                        }\n                    }\n                }\n\n                if (isPeriodicInZ)\n                {\n                    if (on_back_edge)\n                    {\n                        moore_neighbour_indices_vector[17] = node_index - numNodesAcross*numNodesUp*(numNodesDeep-1);\n                        moore_neighbour_indices_vector[20] = moore_neighbour_indices_vector[17] - 1;\n                        moore_neighbour_indices_vector[24] = moore_neighbour_indices_vector[17] + 1;\n\n                        moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[20] - numNodesAcross;\n                        moore_neighbour_indices_vector[22] = moore_neighbour_indices_vector[17] - numNodesAcross;\n                        moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[24] - numNodesAcross;\n\n                        moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[20] + numNodesAcross;\n                        moore_neighbour_indices_vector[18] = moore_neighbour_indices_vector[17] + numNodesAcross;\n                        moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[24] + numNodesAcross;\n\n                        if (on_west_edge)\n                        {\n                            moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[19] + numNodesAcross;\n                            moore_neighbour_indices_vector[20] = moore_neighbour_indices_vector[20] + numNodesAcross;\n                            moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[21] + numNodesAcross;\n                        }\n                        if (on_east_edge)\n                        {\n                            moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[23] - numNodesAcross;\n                            moore_neighbour_indices_vector[24] = moore_neighbour_indices_vector[24] - numNodesAcross;\n                            moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[25] - numNodesAcross;\n                        }\n\n                        if (on_south_edge)\n                        {\n                            moore_neighbour_indices_vector[21] = moore_neighbour_indices_vector[21] + numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[22] = moore_neighbour_indices_vector[22] + numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[23] = moore_neighbour_indices_vector[23] + numNodesAcross*numNodesUp;\n                        }\n\n                        if (on_north_edge)\n                        {\n                            moore_neighbour_indices_vector[18] = moore_neighbour_indices_vector[18] - numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[19] = moore_neighbour_indices_vector[19] - numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[25] = moore_neighbour_indices_vector[25] - numNodesAcross*numNodesUp;\n                        }\n                    }\n\n                    if (on_front_edge)\n                    {\n                        moore_neighbour_indices_vector[8] = node_index + numNodesAcross*numNodesUp*(numNodesDeep-1);\n                        moore_neighbour_indices_vector[11] = moore_neighbour_indices_vector[8] - 1;\n                        moore_neighbour_indices_vector[15] = moore_neighbour_indices_vector[8] + 1;\n\n                        moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[11] - numNodesAcross;\n                        moore_neighbour_indices_vector[13] = moore_neighbour_indices_vector[8] - numNodesAcross;\n                        moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[15] - numNodesAcross;\n\n                        moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[11] + numNodesAcross;\n                        moore_neighbour_indices_vector[9] = moore_neighbour_indices_vector[8] + numNodesAcross;\n                        moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[15] + numNodesAcross;\n\n                        if (on_west_edge)\n                        {\n                            moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[10] + numNodesAcross;\n                            moore_neighbour_indices_vector[11] = moore_neighbour_indices_vector[11] + numNodesAcross;\n                            moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[12] + numNodesAcross;\n                        }\n                        if (on_east_edge)\n                        {\n                            moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[14] - numNodesAcross;\n                            moore_neighbour_indices_vector[15] = moore_neighbour_indices_vector[15] - numNodesAcross;\n                            moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[16] - numNodesAcross;\n                        }\n\n                        if (on_south_edge)\n                        {\n                            moore_neighbour_indices_vector[12] = moore_neighbour_indices_vector[12] + numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[13] = moore_neighbour_indices_vector[13] + numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[14] = moore_neighbour_indices_vector[14] + numNodesAcross*numNodesUp;\n                        }\n\n                        if (on_north_edge)\n                        {\n                            moore_neighbour_indices_vector[9] = moore_neighbour_indices_vector[9] - numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[10] = moore_neighbour_indices_vector[10] - numNodesAcross*numNodesUp;\n                            moore_neighbour_indices_vector[16] = moore_neighbour_indices_vector[16] - numNodesAcross*numNodesUp;\n                        }\n                    }\n                }\n\n                if (isPeriodicInX)\n                {\n                    on_east_edge = false;\n                    on_west_edge = false;\n                }\n                if (isPeriodicInY)\n                {\n                    on_south_edge = false;\n                    on_north_edge = false;\n                }\n                if (isPeriodicInZ)\n                {\n                    on_front_edge = false;\n                    on_back_edge = false;\n                }\n\n                // Create a vector of booleans for which neighbours are available\n                // Use the order N, NW, W, SW, S, SE, E, NE\n                std::vector<bool> available_neighbours = std::vector<bool>(26, true);\n                available_neighbours[0] = !on_north_edge;\n                available_neighbours[1] = !(on_north_edge || on_west_edge);\n                available_neighbours[2] = !on_west_edge;\n                available_neighbours[3] = !(on_south_edge || on_west_edge);\n                available_neighbours[4] = !on_south_edge;\n                available_neighbours[5] = !(on_south_edge || on_east_edge);\n                available_neighbours[6] = !on_east_edge;\n                available_neighbours[7] = !(on_north_edge || on_east_edge);\n                available_neighbours[8] = !(on_front_edge);\n                for (unsigned i=9; i<17; i++)\n                {\n                    available_neighbours[i] = (available_neighbours[i-9] && !(on_front_edge));\n                }\n                available_neighbours[17] = !(on_back_edge);\n                for (unsigned i=18; i<26; i++)\n                {\n                    available_neighbours[i] = (available_neighbours[i-18] && !(on_back_edge));\n                }\n\n                // Using neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours\n                for (unsigned i=0; i<26; i++)\n                {\n                    if (available_neighbours[i] && moore_neighbour_indices_vector[i] < numNodesAcross*numNodesUp*numNodesDeep)\n                    {\n                        assert(moore_neighbour_indices_vector[i] < nodes.size());\n                        moore_neighbours[node_index].insert(moore_neighbour_indices_vector[i]);\n                    }\n                }\n                break;\n            }\n            default:\n                NEVER_REACHED;\n        }\n\n        // Clear the set of neighbouring node indices\n        von_neumann_neighbours[node_index].clear();\n\n        switch (DIM)\n        {\n            case 2:\n            {\n                assert(DIM == 2);\n                /*\n                 * This stores the available neighbours using the following numbering:\n                 *\n                 *        0\n                 *        |\n                 *        |\n                 *  1-----x-----3\n                 *        |\n                 *        |\n                 *        2\n                 */\n                // Create a vector of possible neighbouring node indices\n                std::vector<unsigned> von_neumann_neighbour_indices_vector(4, node_index);\n                von_neumann_neighbour_indices_vector[0] += numNodesAcross;\n                von_neumann_neighbour_indices_vector[1] -= 1;\n                von_neumann_neighbour_indices_vector[2] -= numNodesAcross;\n                von_neumann_neighbour_indices_vector[3] += 1;\n\n                // Work out whether this node lies on any edge of the mesh\n                bool on_south_edge = (node_index < numNodesAcross);\n                bool on_north_edge = ((int)node_index > (int)numNodesAcross*((int)numNodesUp - 1) - 1);\n                bool on_west_edge = (node_index%numNodesAcross == 0);\n                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);\n\n                if (isPeriodicInX)\n                {\n                    if (on_west_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[1] = node_index + numNodesAcross - 1;\n                        on_west_edge = false;\n                    }\n\n                    if (on_east_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[3] = node_index - numNodesAcross + 1;\n                        on_east_edge = false;\n                    }\n                }\n\n                if (isPeriodicInY)\n                {\n                    if (on_north_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);\n                        on_north_edge = false;\n                    }\n\n                    if (on_south_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[2] = node_index + numNodesAcross*(numNodesUp-1);\n                        on_south_edge = false;\n                    }\n                }\n\n                // Create a vector of booleans for which neighbours are available\n                // Use the order N, W, S, E\n                std::vector<bool> available_neighbours = std::vector<bool>(2*DIM, true);\n                available_neighbours[0] = !on_north_edge;\n                available_neighbours[1] = !on_west_edge;\n                available_neighbours[2] = !on_south_edge;\n                available_neighbours[3] = !on_east_edge;\n\n                // Using von_neumann_neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours\n                for (unsigned i=0; i<4; i++)\n                {\n                    if (available_neighbours[i])\n                    {\n                        assert(von_neumann_neighbour_indices_vector[i] < nodes.size());\n                        von_neumann_neighbours[node_index].insert(von_neumann_neighbour_indices_vector[i]);\n                    }\n                }\n                break;\n            }\n            case 3:\n            {\n                assert(DIM == 3);\n\n                /*\n                 * This stores the available neighbours using the following numbering:\n                 *\n                 *        0  5\n                 *        | /\n                 *        |/\n                 *  1-----x-----3\n                 *      / |\n                 *     /  |\n                 *    4   2\n                 */\n                // Create a vector of possible neighbouring node indices\n                std::vector<unsigned> von_neumann_neighbour_indices_vector(6, node_index);\n                von_neumann_neighbour_indices_vector[0] += numNodesAcross;\n                von_neumann_neighbour_indices_vector[1] -= 1;\n                von_neumann_neighbour_indices_vector[2] -= numNodesAcross;\n                von_neumann_neighbour_indices_vector[3] += 1;\n                von_neumann_neighbour_indices_vector[4] -= numNodesAcross*numNodesUp;\n                von_neumann_neighbour_indices_vector[5] += numNodesAcross*numNodesUp;\n\n                // Work out whether this node lies on any edge of the mesh\n                bool on_south_edge = (node_index%(numNodesAcross*numNodesUp)<numNodesAcross);\n                bool on_north_edge = (node_index%(numNodesAcross*numNodesUp)>(numNodesAcross*numNodesUp-numNodesAcross-1));\n                bool on_west_edge = (node_index%numNodesAcross== 0);\n                bool on_east_edge = (node_index%numNodesAcross == numNodesAcross - 1);\n                bool on_front_edge = (node_index < numNodesAcross*numNodesUp);\n                bool on_back_edge = (node_index > numNodesAcross*numNodesUp*(numNodesDeep-1)-1);\n\n                if (isPeriodicInX)\n                {\n                    if (on_west_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[1] = node_index + numNodesAcross - 1;\n                        on_west_edge = false;\n                    }\n\n                    if (on_east_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[3] = node_index - numNodesAcross + 1;\n                        on_east_edge = false;\n                    }\n                }\n\n                if (isPeriodicInY)\n                {\n                    if (on_north_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[0] = node_index - numNodesAcross*(numNodesUp-1);\n                        on_north_edge = false;\n                    }\n\n                    if (on_south_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[2] = node_index + numNodesAcross*(numNodesUp-1);\n                        on_south_edge = false;\n                    }\n                }\n\n                if (isPeriodicInZ)\n                {\n                    if (on_front_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[4] = node_index + numNodesAcross*numNodesUp*(numNodesDeep-1);\n                        on_front_edge = false;\n                    }\n\n                    if (on_back_edge)\n                    {\n                        von_neumann_neighbour_indices_vector[5] = node_index - numNodesAcross*numNodesUp*(numNodesDeep-1);\n                        on_back_edge = false;\n                    }\n                }\n\n                // Create a vector of booleans for which neighbours are available\n                // Use the order N, W, S, E, F, B\n                std::vector<bool> available_neighbours = std::vector<bool>(2*DIM, true);\n                available_neighbours[0] = !on_north_edge;\n                available_neighbours[1] = !on_west_edge;\n                available_neighbours[2] = !on_south_edge;\n                available_neighbours[3] = !on_east_edge;\n                available_neighbours[4] = !on_front_edge;\n                available_neighbours[5] = !on_back_edge;\n\n                // Using von_neumann_neighbour_indices_vector and available_neighbours, store the indices of all available neighbours to the set all_neighbours\n                for (unsigned i=0; i<6; i++)\n                {\n                    if (available_neighbours[i] && von_neumann_neighbour_indices_vector[i]<numNodesAcross*numNodesUp*numNodesDeep)\n                    {\n                        assert(von_neumann_neighbour_indices_vector[i] < nodes.size());\n                        von_neumann_neighbours[node_index].insert(von_neumann_neighbour_indices_vector[i]);\n                    }\n                }\n                break;\n            }\n            default:\n                NEVER_REACHED;\n        }\n    }\n\n    mpMesh = new PottsMesh<DIM>(nodes, elements, von_neumann_neighbours, moore_neighbours);\n}\n\ntemplate<unsigned DIM>\nPottsMeshGenerator<DIM>::~PottsMeshGenerator()\n{\n    delete mpMesh;\n}\n\ntemplate<unsigned DIM>\nPottsMesh<DIM>* PottsMeshGenerator<DIM>::GetMesh()\n{\n    return mpMesh;\n}\n\n// Explicit instantiation\ntemplate class PottsMeshGenerator<1>;\ntemplate class PottsMeshGenerator<2>;\ntemplate class PottsMeshGenerator<3>;\n", "meta": {"hexsha": "10180afdb1130888964ea98d8e23a7fbfbfd105a", "size": 38453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/mesh/PottsMeshGenerator.cpp", "max_stars_repo_name": "ktunya/ChasteMod", "max_stars_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "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/mesh/PottsMeshGenerator.cpp", "max_issues_repo_name": "ktunya/ChasteMod", "max_issues_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_issues_repo_licenses": ["Apache-2.0"], "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/mesh/PottsMeshGenerator.cpp", "max_forks_repo_name": "ktunya/ChasteMod", "max_forks_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "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": 50.8637566138, "max_line_length": 180, "alphanum_fraction": 0.5471094583, "num_tokens": 8075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.02843603180981054, "lm_q1q2_score": 0.011906078633107666}}
{"text": "#include \"tkdCmdParser.h\"\n\n#include <algorithm>\n#include <iterator>\n#include <functional>\n#include <numeric>\n\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include \"itkImage.h\"\n#include \"itkImageLinearIteratorWithIndex.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkExtractImageFilter.h\"\n\n#include \"graphCommon.h\"\n#include \"annCommon.h\"\n#include \"annRelabel.h\"\n\n/**\n * Circular bootstrap.\n *\n * Neuroimage (2010) Pierre Bellec et al,\n * \"Multi-level bootstrap analysis of stable cluster in resting-state fMRI\".\n *\n * wim@invivonmr.uu.nl, 06-04-2010.\n *\n */\nnamespace bootstrap\n{\n\ttypedef float PixelType;\n\n\ttypedef std::vector< unsigned int > VectorType;\n\n\ttypedef itk::Image< PixelType, 3 > Image3DType;\n\ttypedef itk::Image< PixelType, 4 > Image4DType;\n\n\ttypedef itk::ImageRegionConstIteratorWithIndex< Image4DType > ConstIterator4DType;\n\ttypedef itk::ImageRegionIteratorWithIndex< Image4DType > Iterator4DType;\n\ttypedef itk::ExtractImageFilter< Image4DType, Image4DType > ExtractImageFilterType;\n\ttypedef itk::ImageFileWriter< Image4DType > ImageFileWriterType;\n\n\ttypedef boost::mt19937 random_number_type;\n\ttypedef boost::uniform_int< int > int_distribution_type;\n\ttypedef boost::variate_generator< random_number_type&, int_distribution_type > int_generator_type;\n\n\t// *******************************************************************************\n\n\t/**\n\t * Option list.\n\t */\n\tstruct parameters\n\t{\n\t\tstd::string inputFileName;\n\t\tstd::string maskFileName;\n\t\tstd::string outputFileName;\n\t\tint iterations;\n    int clusters;\n    int repeat;\n  };\n\n  // *******************************************************************************\n\n  /**\n   * Construct similarity matrix using circular block boostrapping.\n   */\n  class Bootstrap\n  {\n\n    private:\n\n      Image4DType::Pointer m_Data;\n      Image4DType::Pointer m_DoubleData;\n      Image3DType::Pointer m_Mask;\n      std::vector< Image4DType::Pointer > m_BootstrapContainer;\n\n    public:\n\n      /**\n       * Run.\n       */\n      void Run( const parameters& list )\n      {\n        // [ 1 ] Read data ...\n        Read4D( list.inputFileName );\n        ReadMask( list.maskFileName );\n\n        // [ 2 ] Get list of random blocksizes and random offsets ...\n        random_number_type generator( time( 0 ) );\n\n        // [ 3 ] Construct circular bootstrap 4D images ...\n        FillBootstrapContainer( list.iterations, generator );\n\n        // [ 4 ] DEBUG TODO Write all different 4D images to disk...\n        typedef itk::ImageFileWriter< Image4DType > ImageFileWriterType;\n        ImageFileWriterType::Pointer writer = ImageFileWriterType::New();\n\n        for( unsigned int i = 0; i < m_BootstrapContainer.size(); i++ )\n        {\n          std::stringstream ss;\n          ss << \"test_\" << i << \".nii.gz\";\n\n          writer->SetFileName( ss.str() );\n          writer->SetInput( m_BootstrapContainer.at( i ) );\n          writer->Update();\n        }\n      }\n\n    private:\n\n      /**\n       * Fill bootstrap container.\n       */\n      void FillBootstrapContainer( unsigned int n, random_number_type& generator )\n      {\n        Image4DType::SizeType size = m_Data->GetLargestPossibleRegion().GetSize();\n        unsigned int max = size[3];\n\n        for ( unsigned int i = 0; i < n; i++ )\n        {\n          std::cout << \"Bootstrap nr: \" << i << std::endl;\n          m_BootstrapContainer.push_back( GetBootstrapImage( generator, max ) );\n        }\n      }\n\n      /**\n       * Return bootstrapped 4D image.\n       */\n      Image4DType::Pointer GetBootstrapImage( random_number_type& generator, unsigned int max )\n      {\n        // get number of blocks, sufficient to occupy full 4D image ...\n        VectorType blockSizes;\n        VectorType offsets;\n\n        while ( std::accumulate( blockSizes.begin(), blockSizes.end(), static_cast< unsigned int > ( 0 ) ) < max )\n        {\n          offsets.push_back( GetRandomNumber( generator, max ) );\n          blockSizes.push_back( GetRandomNumber( generator, 3 * sqrt( max ) ) ); // TODO manual set?\n        }\n\n        std::vector< Image4DType::Pointer > blocks = GetBlocks( blockSizes, offsets );\n\n        return MergeBlocks( blocks );\n      }\n\n      /**\n       * Return circular blocks, taken from input images.\n       */\n      std::vector< Image4DType::Pointer > GetBlocks( const VectorType& blockSizes, const VectorType& offsets )\n      {\n        std::vector< Image4DType::Pointer > blocks;\n\n        for ( unsigned int i = 0; i < blockSizes.size(); i++ )\n        {\n          unsigned int blockSize = blockSizes.at( i );\n          unsigned int offset = offsets.at( i );\n\n          ExtractImageFilterType::Pointer filter = ExtractImageFilterType::New();\n          filter->SetInput( m_DoubleData );\n\n          Image4DType::RegionType region = m_DoubleData->GetLargestPossibleRegion();\n          Image4DType::SizeType size = region.GetSize();\n          Image4DType::IndexType index = region.GetIndex();\n\n          size[3] = blockSize;\n          index[3] = offset;\n\n          region.SetSize( size );\n          region.SetIndex( index );\n\n          filter->SetExtractionRegion( region );\n\n          filter->Update();\n          blocks.push_back( filter->GetOutput() );\n\n          m_DoubleData->DisconnectPipeline();\n        }\n        return blocks;\n      }\n\n      /**\n       * Merge blocks until size is equal to input 4D Image.\n       */\n      Image4DType::Pointer MergeBlocks( const std::vector< Image4DType::Pointer >& blocks )\n      {\n        Image4DType::Pointer image = Image4DType::New();\n\n        image->SetRegions( m_DoubleData->GetLargestPossibleRegion() );\n        image->SetOrigin( m_DoubleData->GetOrigin() );\n        image->SetSpacing( m_DoubleData->GetSpacing() );\n\n        image->Allocate();\n        image->FillBuffer( 0 );\n\n        typedef itk::ImageRegionConstIteratorWithIndex< Image4DType > ConstIterator4D;\n        typedef itk::ImageRegionIteratorWithIndex< Image4DType > Iterator4D;\n\n        Image4DType::IndexType index = m_DoubleData->GetLargestPossibleRegion().GetIndex();\n\n        for ( unsigned int i = 0; i < blocks.size(); i++ )\n        {\n          Image4DType::RegionType region = blocks.at( i )->GetLargestPossibleRegion();\n          Image4DType::SizeType size = region.GetSize();\n          region.SetIndex( index );\n\n          Iterator4D it4( image, region );\n          it4.GoToBegin();\n\n          ConstIterator4D it3( blocks.at( i ), blocks.at( i )->GetLargestPossibleRegion() );\n          it3.GoToBegin();\n\n          while ( !it3.IsAtEnd(), !it4.IsAtEnd() )\n          {\n            it4.Set( it3.Get() );\n            ++it3;\n            ++it4;\n          }\n          index[ 3 ] += size[ 3 ];\n        }\n\n        // Extract first block from image and return ...\n        ExtractImageFilterType::Pointer filter = ExtractImageFilterType::New();\n        filter->SetInput( image );\n\n        Image4DType::RegionType cropRegion = image->GetLargestPossibleRegion();\n        Image4DType::SizeType cropSize = cropRegion.GetSize();\n        Image4DType::IndexType cropIndex = cropRegion.GetIndex();\n\n        cropSize[3] = ( m_Data->GetLargestPossibleRegion().GetSize() )[ 3 ];\n        cropIndex[3] = 0;\n\n        cropRegion.SetSize( cropSize );\n        cropRegion.SetIndex( cropIndex );\n\n        filter->SetExtractionRegion( cropRegion );\n        filter->Update();\n\n        return filter->GetOutput();\n      }\n\n      /**\n       * Return random number.\n       */\n      int GetRandomNumber( random_number_type& generator, unsigned int max )\n      {\n        // uniform distribution: 0 -> 4D image size ...\n        int_distribution_type int_uni_dist( 0, max - 1 );\n        int_generator_type int_distribution( generator, int_uni_dist );\n\n        int value = int_distribution();\n        while ( value < 2 )\n          value = int_distribution();\n\n        return value;\n      }\n\n      /**\n       * Read 3D volume.\n       */\n      void ReadMask( const std::string& inputFileName )\n      {\n        if ( !inputFileName.empty() )\n        {\n          typedef itk::ImageFileReader< Image3DType > ReaderType;\n          ReaderType::Pointer reader = ReaderType::New();\n          reader->SetFileName( inputFileName );\n          reader->Update();\n          m_Mask = reader->GetOutput();\n        } else\n        {\n          // use 4D input data as reference for full mask...\n          Image4DType::SizeType size4D = m_Data->GetLargestPossibleRegion().GetSize();\n          Image4DType::IndexType index4D = m_Data->GetLargestPossibleRegion().GetIndex();\n          Image3DType::SizeType size3D;\n          Image3DType::IndexType index3D;\n          size3D[0] = size4D[0];\n          size3D[1] = size4D[1];\n          size3D[2] = size4D[2];\n          index3D[0] = index4D[0];\n          index3D[1] = index4D[1];\n          index3D[2] = index4D[2];\n          Image3DType::RegionType region3D;\n          region3D.SetSize( size3D );\n          region3D.SetIndex( index3D );\n          m_Mask = Image3DType::New();\n          m_Mask->SetRegions( region3D );\n          m_Mask->Allocate();\n          m_Mask->FillBuffer( 1 );\n        }\n      }\n\n      /**\n       * Read 4D data, and set double data object (for wrapping).\n       */\n      void Read4D( const std::string& inputFileName )\n      {\n        typedef itk::ImageFileReader< Image4DType > ReaderType;\n        ReaderType::Pointer reader = ReaderType::New();\n        reader->SetFileName( inputFileName );\n        reader->Update();\n        m_Data = reader->GetOutput();\n\n        Image4DType::RegionType region = m_Data->GetLargestPossibleRegion();\n        Image4DType::SizeType size = region.GetSize();\n        size[3] *= 2;\n        region.SetSize( size );\n\n        m_DoubleData = Image4DType::New();\n        m_DoubleData->SetRegions( region );\n        m_DoubleData->SetSpacing( m_Data->GetSpacing() );\n        m_DoubleData->SetOrigin( m_Data->GetOrigin() );\n        m_DoubleData->Allocate();\n        m_DoubleData->FillBuffer( 0 );\n\n        ConstIterator4DType it( m_Data, m_Data->GetLargestPossibleRegion() );\n        Iterator4DType nit( m_DoubleData, m_DoubleData->GetLargestPossibleRegion() );\n\n        it.GoToBegin();\n        nit.GoToBegin();\n\n        // first round ...\n        while( !nit.IsAtEnd(), !it.IsAtEnd() )\n        {\n          nit.Set( it.Get() );\n          ++nit;\n          ++it;\n        }\n\n        // second round ...\n        it.GoToBegin();\n        while( !nit.IsAtEnd(), !it.IsAtEnd() )\n        {\n          nit.Set( it.Get() );\n          ++nit;\n          ++it;\n        }\n      }\n  };\n} // end namespace bootstrap\n\n/**\n * Main.\n */\nint main( int argc, char ** argv )\n{\n  tkd::CmdParser p( argv[0], \"Circular block boostrap.\" );\n\n  bootstrap::parameters args;\n  args.iterations = 10;\n\n  p.AddArgument( args.inputFileName, \"input\" ) ->AddAlias( \"i\" )->SetDescription( \"4D input image\" )->SetMinMax( 1, 1 )->SetRequired(\n      true );\n\n  p.AddArgument( args.outputFileName, \"output\" ) ->AddAlias( \"o\" )->SetDescription( \"Similarity matrix output file\" )->SetMinMax( 1, 1 )->SetRequired(\n      true );\n\n  p.AddArgument( args.maskFileName, \"mask\" ) ->AddAlias( \"m\" )->SetDescription( \"Mask 3D image\" )->SetMinMax( 1, 1 );\n\n  p.AddArgument( args.iterations, \"iterations\" )->AddAlias( \"n\" )->SetDescription( \"Bootstrap iterations (default: 10)\" )->SetMinMax( 1,\n      1 );\n\n  if ( !p.Parse( argc, argv ) )\n  {\n    p.PrintUsage( std::cout );\n    return EXIT_FAILURE;\n  }\n\n  bootstrap::Bootstrap boostrapObj;\n\n  boostrapObj.Run( args );\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "105c42b1b1b59d2ce247bc4c509870ec70307810", "size": 11619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/knn/bootstrap.cpp", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/knn/bootstrap.cpp", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/knn/bootstrap.cpp", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["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.5763157895, "max_line_length": 150, "alphanum_fraction": 0.6021172218, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.027169230747973956, "lm_q1q2_score": 0.011895327674319124}}
{"text": "// Copyright 2004 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: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_BRANDES_BETWEENNESS_CENTRALITY_HPP\n#define BOOST_GRAPH_BRANDES_BETWEENNESS_CENTRALITY_HPP\n\n#include <stack>\n#include <vector>\n#include <boost/graph/overloading.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/type_traits/is_convertible.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <algorithm>\n\nnamespace boost {\n\nnamespace detail { namespace graph {\n\n  /**\n   * Customized visitor passed to Dijkstra's algorithm by Brandes'\n   * betweenness centrality algorithm. This visitor is responsible for\n   * keeping track of the order in which vertices are discovered, the\n   * predecessors on the shortest path(s) to a vertex, and the number\n   * of shortest paths.\n   */\n  template<typename Graph, typename WeightMap, typename IncomingMap,\n           typename DistanceMap, typename PathCountMap>\n  struct brandes_dijkstra_visitor : public bfs_visitor<>\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n\n    brandes_dijkstra_visitor(std::stack<vertex_descriptor>& ordered_vertices,\n                             WeightMap weight,\n                             IncomingMap incoming,\n                             DistanceMap distance,\n                             PathCountMap path_count)\n      : ordered_vertices(ordered_vertices), weight(weight), \n        incoming(incoming), distance(distance),\n        path_count(path_count)\n    { }\n\n    /**\n     * Whenever an edge e = (v, w) is relaxed, the incoming edge list\n     * for w is set to {(v, w)} and the shortest path count of w is set to\n     * the number of paths that reach {v}.\n     */\n    void edge_relaxed(edge_descriptor e, const Graph& g) \n    { \n      vertex_descriptor v = source(e, g), w = target(e, g);\n      incoming[w].clear();\n      incoming[w].push_back(e);\n      put(path_count, w, get(path_count, v));\n    }\n\n    /**\n     * If an edge e = (v, w) was not relaxed, it may still be the case\n     * that we've found more equally-short paths, so include {(v, w)} in the\n     * incoming edges of w and add all of the shortest paths to v to the\n     * shortest path count of w.\n     */\n    void edge_not_relaxed(edge_descriptor e, const Graph& g) \n    {\n      typedef typename property_traits<WeightMap>::value_type weight_type;\n      typedef typename property_traits<DistanceMap>::value_type distance_type;\n      vertex_descriptor v = source(e, g), w = target(e, g);\n      distance_type d_v = get(distance, v), d_w = get(distance, w);\n      weight_type w_e = get(weight, e);\n\n      closed_plus<distance_type> combine;\n      if (d_w == combine(d_v, w_e)) {\n        put(path_count, w, get(path_count, w) + get(path_count, v));\n        incoming[w].push_back(e);\n      }\n    }\n\n    /// Keep track of vertices as they are reached\n    void examine_vertex(vertex_descriptor w, const Graph&) \n    { \n      ordered_vertices.push(w);\n    }\n\n  private:\n    std::stack<vertex_descriptor>& ordered_vertices;\n    WeightMap weight;\n    IncomingMap incoming;\n    DistanceMap distance;\n    PathCountMap path_count;\n  };\n\n  /**\n   * Function object that calls Dijkstra's shortest paths algorithm\n   * using the Dijkstra visitor for the Brandes betweenness centrality\n   * algorithm.\n   */\n  template<typename WeightMap>\n  struct brandes_dijkstra_shortest_paths\n  {\n    brandes_dijkstra_shortest_paths(WeightMap weight_map) \n      : weight_map(weight_map) { }\n\n    template<typename Graph, typename IncomingMap, typename DistanceMap, \n             typename PathCountMap, typename VertexIndexMap>\n    void \n    operator()(Graph& g, \n               typename graph_traits<Graph>::vertex_descriptor s,\n               std::stack<typename graph_traits<Graph>::vertex_descriptor>& ov,\n               IncomingMap incoming,\n               DistanceMap distance,\n               PathCountMap path_count,\n               VertexIndexMap vertex_index)\n    {\n      typedef brandes_dijkstra_visitor<Graph, WeightMap, IncomingMap, \n                                       DistanceMap, PathCountMap> visitor_type;\n      visitor_type visitor(ov, weight_map, incoming, distance, path_count);\n\n      dijkstra_shortest_paths(g, s, \n                              boost::weight_map(weight_map)\n                              .vertex_index_map(vertex_index)\n                              .distance_map(distance)\n                              .visitor(visitor));\n    }\n\n  private:\n    WeightMap weight_map;\n  };\n\n  /**\n   * Function object that invokes breadth-first search for the\n   * unweighted form of the Brandes betweenness centrality algorithm.\n   */\n  struct brandes_unweighted_shortest_paths\n  {\n    /**\n     * Customized visitor passed to breadth-first search, which\n     * records predecessor and the number of shortest paths to each\n     * vertex.\n     */\n    template<typename Graph, typename IncomingMap, typename DistanceMap, \n             typename PathCountMap>\n    struct visitor_type : public bfs_visitor<>\n    {\n      typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n      typedef typename graph_traits<Graph>::vertex_descriptor \n        vertex_descriptor;\n      \n      visitor_type(IncomingMap incoming, DistanceMap distance, \n                   PathCountMap path_count, \n                   std::stack<vertex_descriptor>& ordered_vertices)\n        : incoming(incoming), distance(distance), \n          path_count(path_count), ordered_vertices(ordered_vertices) { }\n\n      /// Keep track of vertices as they are reached\n      void examine_vertex(vertex_descriptor v, Graph&)\n      {\n        ordered_vertices.push(v);\n      }\n\n      /**\n       * Whenever an edge e = (v, w) is labelled a tree edge, the\n       * incoming edge list for w is set to {(v, w)} and the shortest\n       * path count of w is set to the number of paths that reach {v}.\n       */\n      void tree_edge(edge_descriptor e, Graph& g)\n      {\n        vertex_descriptor v = source(e, g);\n        vertex_descriptor w = target(e, g);\n        put(distance, w, get(distance, v) + 1);\n        \n        put(path_count, w, get(path_count, v));\n        incoming[w].push_back(e);\n      }\n\n      /**\n       * If an edge e = (v, w) is not a tree edge, it may still be the\n       * case that we've found more equally-short paths, so include (v, w)\n       * in the incoming edge list of w and add all of the shortest\n       * paths to v to the shortest path count of w.\n       */\n      void non_tree_edge(edge_descriptor e, Graph& g)\n      {\n        vertex_descriptor v = source(e, g);\n        vertex_descriptor w = target(e, g);\n        if (get(distance, w) == get(distance, v) + 1) {\n          put(path_count, w, get(path_count, w) + get(path_count, v));\n          incoming[w].push_back(e);\n        }\n      }\n\n    private:\n      IncomingMap incoming;\n      DistanceMap distance;\n      PathCountMap path_count;\n      std::stack<vertex_descriptor>& ordered_vertices;\n    };\n\n    template<typename Graph, typename IncomingMap, typename DistanceMap, \n             typename PathCountMap, typename VertexIndexMap>\n    void \n    operator()(Graph& g, \n               typename graph_traits<Graph>::vertex_descriptor s,\n               std::stack<typename graph_traits<Graph>::vertex_descriptor>& ov,\n               IncomingMap incoming,\n               DistanceMap distance,\n               PathCountMap path_count,\n               VertexIndexMap vertex_index)\n    {\n      typedef typename graph_traits<Graph>::vertex_descriptor\n        vertex_descriptor;\n\n      visitor_type<Graph, IncomingMap, DistanceMap, PathCountMap>\n        visitor(incoming, distance, path_count, ov);\n      \n      std::vector<default_color_type> \n        colors(num_vertices(g), color_traits<default_color_type>::white());\n      boost::queue<vertex_descriptor> Q;\n      breadth_first_visit(g, s, Q, visitor, \n                          make_iterator_property_map(colors.begin(), \n                                                     vertex_index));\n    }\n  };\n\n  // When the edge centrality map is a dummy property map, no\n  // initialization is needed.\n  template<typename Iter>\n  inline void \n  init_centrality_map(std::pair<Iter, Iter>, dummy_property_map) { }\n\n  // When we have a real edge centrality map, initialize all of the\n  // centralities to zero.\n  template<typename Iter, typename Centrality>\n  void \n  init_centrality_map(std::pair<Iter, Iter> keys, Centrality centrality_map)\n  {\n    typedef typename property_traits<Centrality>::value_type \n      centrality_type;\n    while (keys.first != keys.second) {\n      put(centrality_map, *keys.first, centrality_type(0));\n      ++keys.first;\n    }\n  }\n\n  // When the edge centrality map is a dummy property map, no update\n  // is performed.\n  template<typename Key, typename T>\n  inline void \n  update_centrality(dummy_property_map, const Key&, const T&) { }\n\n  // When we have a real edge centrality map, add the value to the map\n  template<typename CentralityMap, typename Key, typename T>\n  inline void \n  update_centrality(CentralityMap centrality_map, Key k, const T& x)\n  { put(centrality_map, k, get(centrality_map, k) + x); }\n\n  template<typename Iter>\n  inline void \n  divide_centrality_by_two(std::pair<Iter, Iter>, dummy_property_map) {}\n\n  template<typename Iter, typename CentralityMap>\n  inline void\n  divide_centrality_by_two(std::pair<Iter, Iter> keys, \n                           CentralityMap centrality_map)\n  {\n    typename property_traits<CentralityMap>::value_type two(2);\n    while (keys.first != keys.second) {\n      put(centrality_map, *keys.first, get(centrality_map, *keys.first) / two);\n      ++keys.first;\n    }\n  }\n\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\n           typename IncomingMap, typename DistanceMap, \n           typename DependencyMap, typename PathCountMap,\n           typename VertexIndexMap, typename ShortestPaths>\n  void \n  brandes_betweenness_centrality_impl(const Graph& g, \n                                      CentralityMap centrality,     // C_B\n                                      EdgeCentralityMap edge_centrality_map,\n                                      IncomingMap incoming, // P\n                                      DistanceMap distance,         // d\n                                      DependencyMap dependency,     // delta\n                                      PathCountMap path_count,      // sigma\n                                      VertexIndexMap vertex_index,\n                                      ShortestPaths shortest_paths)\n  {\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n    typedef typename graph_traits<Graph>::edge_iterator edge_iterator;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n\n    // Initialize centrality\n    init_centrality_map(vertices(g), centrality);\n    init_centrality_map(edges(g), edge_centrality_map);\n\n    std::stack<vertex_descriptor> ordered_vertices;\n    vertex_iterator s, s_end;\n    for (boost::tie(s, s_end) = vertices(g); s != s_end; ++s) {\n      // Initialize for this iteration\n      vertex_iterator w, w_end;\n      for (boost::tie(w, w_end) = vertices(g); w != w_end; ++w) {\n        incoming[*w].clear();\n        put(path_count, *w, 0);\n        put(dependency, *w, 0);\n      }\n      put(path_count, *s, 1);\n      \n      // Execute the shortest paths algorithm. This will be either\n      // Dijkstra's algorithm or a customized breadth-first search,\n      // depending on whether the graph is weighted or unweighted.\n      shortest_paths(g, *s, ordered_vertices, incoming, distance,\n                     path_count, vertex_index);\n      \n      while (!ordered_vertices.empty()) {\n        vertex_descriptor w = ordered_vertices.top();\n        ordered_vertices.pop();\n        \n        typedef typename property_traits<IncomingMap>::value_type\n          incoming_type;\n        typedef typename incoming_type::iterator incoming_iterator;\n        typedef typename property_traits<DependencyMap>::value_type \n          dependency_type;\n        \n        for (incoming_iterator vw = incoming[w].begin();\n             vw != incoming[w].end(); ++vw) {\n          vertex_descriptor v = source(*vw, g);\n          dependency_type factor = dependency_type(get(path_count, v))\n            / dependency_type(get(path_count, w));\n          factor *= (dependency_type(1) + get(dependency, w));\n          put(dependency, v, get(dependency, v) + factor);\n          update_centrality(edge_centrality_map, *vw, factor);\n        }\n        \n        if (w != *s) {\n          update_centrality(centrality, w, get(dependency, w));\n        }\n      }\n    }\n\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    const bool is_undirected = \n      is_convertible<directed_category*, undirected_tag*>::value;\n    if (is_undirected) {\n      divide_centrality_by_two(vertices(g), centrality);\n      divide_centrality_by_two(edges(g), edge_centrality_map);\n    }\n  }\n\n} } // end namespace detail::graph\n\ntemplate<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\n         typename IncomingMap, typename DistanceMap, \n         typename DependencyMap, typename PathCountMap, \n         typename VertexIndexMap>\nvoid \nbrandes_betweenness_centrality(const Graph& g, \n                               CentralityMap centrality,     // C_B\n                               EdgeCentralityMap edge_centrality_map,\n                               IncomingMap incoming, // P\n                               DistanceMap distance,         // d\n                               DependencyMap dependency,     // delta\n                               PathCountMap path_count,      // sigma\n                               VertexIndexMap vertex_index\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  detail::graph::brandes_unweighted_shortest_paths shortest_paths;\n\n  detail::graph::brandes_betweenness_centrality_impl(g, centrality, \n                                                     edge_centrality_map,\n                                                     incoming, distance,\n                                                     dependency, path_count,\n                                                     vertex_index, \n                                                     shortest_paths);\n}\n\ntemplate<typename Graph, typename CentralityMap, typename EdgeCentralityMap, \n         typename IncomingMap, typename DistanceMap, \n         typename DependencyMap, typename PathCountMap, \n         typename VertexIndexMap, typename WeightMap>    \nvoid \nbrandes_betweenness_centrality(const Graph& g, \n                               CentralityMap centrality,     // C_B\n                               EdgeCentralityMap edge_centrality_map,\n                               IncomingMap incoming, // P\n                               DistanceMap distance,         // d\n                               DependencyMap dependency,     // delta\n                               PathCountMap path_count,      // sigma\n                               VertexIndexMap vertex_index,\n                               WeightMap weight_map\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  detail::graph::brandes_dijkstra_shortest_paths<WeightMap>\n    shortest_paths(weight_map);\n\n  detail::graph::brandes_betweenness_centrality_impl(g, centrality, \n                                                     edge_centrality_map,\n                                                     incoming, distance,\n                                                     dependency, path_count,\n                                                     vertex_index, \n                                                     shortest_paths);\n}\n\nnamespace detail { namespace graph {\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\n           typename WeightMap, typename VertexIndexMap>\n  void \n  brandes_betweenness_centrality_dispatch2(const Graph& g,\n                                           CentralityMap centrality,\n                                           EdgeCentralityMap edge_centrality_map,\n                                           WeightMap weight_map,\n                                           VertexIndexMap vertex_index)\n  {\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n    typedef typename mpl::if_c<(is_same<CentralityMap, \n                                        dummy_property_map>::value),\n                                         EdgeCentralityMap, \n                               CentralityMap>::type a_centrality_map;\n    typedef typename property_traits<a_centrality_map>::value_type \n      centrality_type;\n\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\n    \n    std::vector<std::vector<edge_descriptor> > incoming(V);\n    std::vector<centrality_type> distance(V);\n    std::vector<centrality_type> dependency(V);\n    std::vector<degree_size_type> path_count(V);\n\n    brandes_betweenness_centrality(\n      g, centrality, edge_centrality_map,\n      make_iterator_property_map(incoming.begin(), vertex_index),\n      make_iterator_property_map(distance.begin(), vertex_index),\n      make_iterator_property_map(dependency.begin(), vertex_index),\n      make_iterator_property_map(path_count.begin(), vertex_index),\n      vertex_index,\n      weight_map);\n  }\n  \n\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\n           typename VertexIndexMap>\n  void \n  brandes_betweenness_centrality_dispatch2(const Graph& g,\n                                           CentralityMap centrality,\n                                           EdgeCentralityMap edge_centrality_map,\n                                           VertexIndexMap vertex_index)\n  {\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n    typedef typename mpl::if_c<(is_same<CentralityMap, \n                                        dummy_property_map>::value),\n                                         EdgeCentralityMap, \n                               CentralityMap>::type a_centrality_map;\n    typedef typename property_traits<a_centrality_map>::value_type \n      centrality_type;\n\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\n    \n    std::vector<std::vector<edge_descriptor> > incoming(V);\n    std::vector<centrality_type> distance(V);\n    std::vector<centrality_type> dependency(V);\n    std::vector<degree_size_type> path_count(V);\n\n    brandes_betweenness_centrality(\n      g, centrality, edge_centrality_map,\n      make_iterator_property_map(incoming.begin(), vertex_index),\n      make_iterator_property_map(distance.begin(), vertex_index),\n      make_iterator_property_map(dependency.begin(), vertex_index),\n      make_iterator_property_map(path_count.begin(), vertex_index),\n      vertex_index);\n  }\n\n  template<typename WeightMap>\n  struct brandes_betweenness_centrality_dispatch1\n  {\n    template<typename Graph, typename CentralityMap, \n             typename EdgeCentralityMap, typename VertexIndexMap>\n    static void \n    run(const Graph& g, CentralityMap centrality, \n        EdgeCentralityMap edge_centrality_map, VertexIndexMap vertex_index,\n        WeightMap weight_map)\n    {\n      brandes_betweenness_centrality_dispatch2(g, centrality, edge_centrality_map,\n                                               weight_map, vertex_index);\n    }\n  };\n\n  template<>\n  struct brandes_betweenness_centrality_dispatch1<error_property_not_found>\n  {\n    template<typename Graph, typename CentralityMap, \n             typename EdgeCentralityMap, typename VertexIndexMap>\n    static void \n    run(const Graph& g, CentralityMap centrality, \n        EdgeCentralityMap edge_centrality_map, VertexIndexMap vertex_index,\n        error_property_not_found)\n    {\n      brandes_betweenness_centrality_dispatch2(g, centrality, edge_centrality_map,\n                                               vertex_index);\n    }\n  };\n\n  template <typename T>\n  struct is_bgl_named_params {\n    BOOST_STATIC_CONSTANT(bool, value = false);\n  };\n\n  template <typename Param, typename Tag, typename Rest>\n  struct is_bgl_named_params<bgl_named_params<Param, Tag, Rest> > {\n    BOOST_STATIC_CONSTANT(bool, value = true);\n  };\n\n} } // end namespace detail::graph\n\ntemplate<typename Graph, typename Param, typename Tag, typename Rest>\nvoid \nbrandes_betweenness_centrality(const Graph& g, \n                               const bgl_named_params<Param,Tag,Rest>& params\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  typedef bgl_named_params<Param,Tag,Rest> named_params;\n\n  typedef typename property_value<named_params, edge_weight_t>::type ew;\n  detail::graph::brandes_betweenness_centrality_dispatch1<ew>::run(\n    g, \n    choose_param(get_param(params, vertex_centrality), \n                 dummy_property_map()),\n    choose_param(get_param(params, edge_centrality), \n                 dummy_property_map()),\n    choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\n    get_param(params, edge_weight));\n}\n\n// disable_if is required to work around problem with MSVC 7.1 (it seems to not\n// get partial ordering getween this overload and the previous one correct)\ntemplate<typename Graph, typename CentralityMap>\ntypename disable_if<detail::graph::is_bgl_named_params<CentralityMap>,\n                    void>::type\nbrandes_betweenness_centrality(const Graph& g, CentralityMap centrality\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  detail::graph::brandes_betweenness_centrality_dispatch2(\n    g, centrality, dummy_property_map(), get(vertex_index, g));\n}\n\ntemplate<typename Graph, typename CentralityMap, typename EdgeCentralityMap>\nvoid \nbrandes_betweenness_centrality(const Graph& g, CentralityMap centrality,\n                               EdgeCentralityMap edge_centrality_map\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  detail::graph::brandes_betweenness_centrality_dispatch2(\n    g, centrality, edge_centrality_map, get(vertex_index, g));\n}\n\n/**\n * Converts \"absolute\" betweenness centrality (as computed by the\n * brandes_betweenness_centrality algorithm) in the centrality map\n * into \"relative\" centrality. The result is placed back into the\n * given centrality map.\n */\ntemplate<typename Graph, typename CentralityMap>\nvoid \nrelative_betweenness_centrality(const Graph& g, CentralityMap centrality)\n{\n  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n  typedef typename property_traits<CentralityMap>::value_type centrality_type;\n\n  typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);\n  centrality_type factor = centrality_type(2)/centrality_type(n*n - 3*n + 2);\n  vertex_iterator v, v_end;\n  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {\n    put(centrality, *v, factor * get(centrality, *v));\n  }\n}\n\n// Compute the central point dominance of a graph.\ntemplate<typename Graph, typename CentralityMap>\ntypename property_traits<CentralityMap>::value_type\ncentral_point_dominance(const Graph& g, CentralityMap centrality\n                        BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  using std::max;\n\n  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n  typedef typename property_traits<CentralityMap>::value_type centrality_type;\n\n  typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);\n\n  // Find max centrality\n  centrality_type max_centrality(0);\n  vertex_iterator v, v_end;\n  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {\n    max_centrality = (max)(max_centrality, get(centrality, *v));\n  }\n\n  // Compute central point dominance\n  centrality_type sum(0);\n  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {\n    sum += (max_centrality - get(centrality, *v));\n  }\n  return sum/(n-1);\n}\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_BRANDES_BETWEENNESS_CENTRALITY_HPP\n", "meta": {"hexsha": "052f0633c136603754121d7e2a30c616f7ca436c", "size": 24913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_44_0/boost/graph/betweenness_centrality.hpp", "max_stars_repo_name": "RaptDept/slimtune", "max_stars_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "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": "Boost_1_49/boost/graph/betweenness_centrality.hpp", "max_issues_repo_name": "jjzhang166/WinUtil4", "max_issues_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "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": "Boost_1_49/boost/graph/betweenness_centrality.hpp", "max_forks_repo_name": "jjzhang166/WinUtil4", "max_forks_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "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": 40.1822580645, "max_line_length": 94, "alphanum_fraction": 0.6448039176, "num_tokens": 5318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.033085976124343754, "lm_q1q2_score": 0.011889913526712335}}
{"text": "#pragma once\n#pragma GCC diagnostic ignored \"-Wsign-compare\"\n\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <cmath>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/lexical_cast.hpp>\n\nusing std::vector;\nusing std::string;\nusing std::set;\nusing std::map;\nusing std::istream;\nusing std::ifstream;\nusing std::exception;\nusing std::invalid_argument;\nusing std::runtime_error;\n\n\nclass Variable{\nprivate:\n  string fName;\n  vector<string> fDomainNames;\n  \npublic: //formerly protected\n  Variable(string name, vector<string> domainNames){\n    fName = name;\n    fDomainNames.assign(domainNames.begin(), domainNames.end());\n  }\n  \npublic:\n  string name() const {\n    return fName;\n  }\n  \n  vector<string> domainNames() const {\n    return fDomainNames;\n  }\n  \n  //TODO overload << instead\n  string toString() {\n    return name();\n  }\n  \n  // functions to be used by std::map\n\n  bool operator< (const Variable& other) const {\n    return this->fName < other.name();\n  }\n  \n  Variable(){\n  }\n  \n  Variable(const Variable& other){\n    fName = other.name();\n    fDomainNames = other.domainNames();\n  }\n};\n\nclass Potential {\nprivate:\n    string fName;\n    int fNumPositions;\n    \npublic: //formerly protected\n    Potential(string name, int numPositions) {\n        fName = name;\n        fNumPositions = numPositions;\n    }\n    \npublic:\n    string name() const{\n        return fName;\n    }\n    \n    int numPositions() const{\n        return fNumPositions;\n    }\n    \n    //TODO overload << instead\n    string toString() {\n        return \"T (\" + name() + \")\";\n    }\n    \n    \n    // functions to be used by std::map\n    \n    bool operator<(const Potential& other) const {\n      return this->fName < other.name();\n    }\n    \n    Potential(){\n    }\n    \n    Potential(const Potential& other){\n      fName = other.name();\n      fNumPositions = other.numPositions();\n    }\n    \n};\n\nclass OnlineEngine;\n\nclass Evidence {\n  \nprivate:\n  OnlineEngine& fEngine;\n  \npublic: //formerly protected:\n  vector<double> fVarToCurrentNegWeight;\n  vector<double> fVarToCurrentPosWeight;\n  \nprivate:\n  double defaultWeight (int l);\n  void setCurrentWeight (int l, double w);\n  void setCurrentWeightToDefault (int l);\n  void setCurrentWeightsToDefaults (const vector<int>&);\n  void setCurrentWeights (double w, const vector<int>&);\n  \npublic:\n  void retractAll ();\n  Evidence (OnlineEngine& engine);\n  void varCommit (Variable v, int u);\n  void valCommit (Variable v, int u, bool allow);\n  void varRetract (Variable v);\n  void varSet (Variable v, double w);\n  void parmCommit (Potential t, int p, double w);\n  void parmRetract (Potential t, int p);\n  \n};\n\nclass OnlineEngine {\npublic: // formerly protected:\n    static const char CONSTANT = 0;\n    static const char LITERAL = 1;\n    static const char MULTIPLY = 2;\n    static const char ADD = 3;\n    vector<char> fNodeToType;\n    vector<int> fNodeToLastEdge;\n    vector<int> fNodeToLit;\n    vector<int> fEdgeToTailNode;\n    vector<int> fVarToNegLitNode;\n    vector<int> fVarToPosLitNode;\n    string READ_DELIMITER;\n    string DELIMITER;\n    set<Variable> fVariables;\n    set<Potential> fPotentials;\n    map<string, Variable> fNameToSrcVar;\n    map<string, Potential> fNameToSrcPot;\n    vector<double> fLogicVarToDefaultNegWeight;\n    vector<double> fLogicVarToDefaultPosWeight;\n    map<Variable, vector<int>* > fSrcVarToSrcValToIndicator;\n    map<Potential, vector<int>* > fSrcPotToSrcPosToParameter;\n    vector<double> fNodeToValue;\n    vector<double> fNodeToDerivative;\n    vector<bool> fNodeToOneZero;\n    bool fUpwardPassCompleted;\n    bool fTwoPassesCompleted;\n    vector<double> fAcVarToMostRecentNegWeight;\n    vector<double> fAcVarToMostRecentPosWeight;\n\n    vector<double> clone(vector<double> a);\n    void readArithmeticCircuit(istream& r);\n    void readLiteralMap(istream& r);\n    void upwardPass (Evidence ev);\n    void twoPasses (Evidence ev);\n    double computedValue (int n);\n    int first (int n);\n    int rootNode ();\n    int numAcNodes ();\n\npublic:    \n    OnlineEngine (string acFilename, string lmFilename);\n    void initialize(istream& acReader, istream& lmReader);\n    Variable varForName (string n);\n    Potential potForName (string n);\n    set<Variable> variables ();\n    set<Potential> potentials ();\n    void assertEvidence (Evidence e, bool secondPass);\n    double probOfEvidence ();\n    vector<double> varPartials (Variable v);\n    map<Variable,vector<double> > varPartials (set<Variable> vs);\n    vector<double> varMarginals (Variable v);\n    map<Variable,vector<double> > varMarginals (set<Variable> vs);\n    vector<double> varPosteriors (Variable v);\n    map<Variable,vector<double> > varPosteriors (set<Variable> vs);\n    vector<double> potPartials (Potential pot);\n    map<Potential,vector<double> > potPartials (set<Potential> ps);\n    vector<double> potMarginals (Potential p);\n    map<Potential,vector<double> > potMarginals (set<Potential> ps);\n    vector<double> potPosteriors (Potential p);\n    map<Potential,vector<double> > potPosteriors (set<Potential> ps);\n};\n\ninline\ndouble Evidence::defaultWeight (int l) {\n    return l < 0 ? fEngine.fLogicVarToDefaultNegWeight[-l]:\n           fEngine.fLogicVarToDefaultPosWeight[l];\n}\n\ninline\nvoid Evidence::setCurrentWeight (int l, double w) {\n    if (l < 0) {\n        fVarToCurrentNegWeight[-l] = w;\n    } else {\n        fVarToCurrentPosWeight[l] = w;\n    }\n}\n\ninline\nvoid Evidence::setCurrentWeightToDefault (int l) {\n    setCurrentWeight (l, defaultWeight (l));\n}\n\ninline\nvoid Evidence::setCurrentWeightsToDefaults (const vector<int>& lits) {\n    for (int l : lits) {\n        setCurrentWeightToDefault (l);\n    }\n}\n\ninline\nvoid Evidence::setCurrentWeights (double w, const vector<int>& lits) {\n    for (int l : lits) {\n        setCurrentWeight (l, w);\n    }\n}\n\n\ninline\nvoid Evidence::retractAll () {\n    fVarToCurrentNegWeight.assign(fEngine.fLogicVarToDefaultNegWeight.begin(),\n                                  fEngine.fLogicVarToDefaultNegWeight.end());\n    fVarToCurrentPosWeight.assign(fEngine.fLogicVarToDefaultPosWeight.begin(),\n                                  fEngine.fLogicVarToDefaultPosWeight.end());\n}\n\ninline\nEvidence::Evidence (OnlineEngine& engine) : fEngine(engine){\n    fVarToCurrentNegWeight.resize(\n        fEngine.fLogicVarToDefaultNegWeight.size());\n    fVarToCurrentPosWeight.resize(\n        fEngine.fLogicVarToDefaultPosWeight.size());\n    retractAll ();\n}\n\ninline\nvoid Evidence::varCommit (Variable v, int u) {\n    varSet (v, 0.0);\n    setCurrentWeightToDefault (\n        fEngine.fSrcVarToSrcValToIndicator[v]->at(u));\n}\n\ninline\nvoid Evidence::valCommit (Variable v, int u, bool allow) {\n    int l = fEngine.fSrcVarToSrcValToIndicator[v]->at(u);\n    if (allow) {\n        setCurrentWeightToDefault (l);\n    } else {\n        setCurrentWeight (l, 0.0);\n    }\n}\n\ninline\nvoid Evidence::varRetract (Variable v) {\n    setCurrentWeightsToDefaults (*(fEngine.fSrcVarToSrcValToIndicator[v]));\n}\n\ninline\nvoid Evidence::varSet (Variable v, double w) {\n    setCurrentWeights (w, *(fEngine.fSrcVarToSrcValToIndicator[v]));\n}\n\ninline\nvoid Evidence::parmCommit (Potential t, int p, double w) {\n    int l = fEngine.fSrcPotToSrcPosToParameter[t]->at(p);\n    if (p == 0) {\n        throw invalid_argument(\"Attempt to set value of parameter illegally!\");\n    }\n    setCurrentWeight (l, w);\n}\n\ninline\nvoid Evidence::parmRetract (Potential t, int p) {\n    int l = fEngine.fSrcPotToSrcPosToParameter[t]->at(p);\n    if (p == 0) {\n        throw invalid_argument(\"Attempt to set value of parameter illegally!\");\n    }\n    setCurrentWeightToDefault (l);\n}\n\ninline\nvector<double> OnlineEngine::clone(vector<double> a) {\n    vector<double> ans;\n    ans.reserve(a.size());\n    ans.assign(a.begin(), a.end());\n    return ans;\n}\n\ninline\nvoid OnlineEngine::upwardPass (Evidence ev) {\n    vector<double>& negValues = ev.fVarToCurrentNegWeight;\n    vector<double>& posValues = ev.fVarToCurrentPosWeight;\n    int numNodes = numAcNodes ();\n    for (int n = 0; n < numNodes; n++) {\n        char type = fNodeToType[n];\n        if (type == MULTIPLY) {\n            double v = 1.0;\n            int last = fNodeToLastEdge[n];\n            for (int e = first (n); e < last; e++) {\n                int ch = fEdgeToTailNode[e];\n                double chVal = fNodeToValue[ch];\n                if (chVal == 0.0) {\n                    v = 0.0;\n                    break;\n                }\n                v *= chVal;\n                if (v == 0.0) {\n\t\t  throw runtime_error(\"Underflow\");\n                }\n            }\n            fNodeToValue[n] = v;\n        } else if (type == ADD) {\n            double v = 0.0;\n            int last = fNodeToLastEdge[n];\n            for (int e = first (n); e < last; e++) {\n                int ch = fEdgeToTailNode[e];\n                v += fNodeToValue[ch];\n            }\n            fNodeToValue[n] = v;\n        } else if (type == LITERAL) {\n            int l = fNodeToLit[n];\n            fNodeToValue[n] = (l < 0 ? negValues[-l] : posValues[l]);\n        }\n        // do nothing for a constant\n    }\n}\n\ninline\nvoid OnlineEngine::twoPasses (Evidence ev) {\n\n    // Upward pass.\n\n    vector<double>& negValues = ev.fVarToCurrentNegWeight;\n    vector<double>& posValues = ev.fVarToCurrentPosWeight;\n    int numNodes = numAcNodes ();\n    for (int n = 0; n < numNodes; n++) {\n        fNodeToDerivative[n] = 0.0;\n        char type = fNodeToType[n];\n        if (type == MULTIPLY) {\n            int numZeros = 0;\n            double v = 1.0;\n            int last = fNodeToLastEdge[n];\n            for (int e = first (n); e < last; e++) {\n                int ch = fEdgeToTailNode[e];\n                double chVal = computedValue (ch);\n                if (chVal == 0.0) {\n                    if (++numZeros > 1) {\n                        v = 0;\n                        break;\n                    }\n                } else {\n                    v *= chVal;\n                    if (v == 0.0) {\n                        throw runtime_error(\"Underflow\");\n                    }\n                }\n            }\n            fNodeToValue[n] = v;\n            fNodeToOneZero[n] = numZeros == 1;\n        } else if (type == ADD) {\n            double v = 0.0;\n            int last = fNodeToLastEdge[n];\n            for (int e = first (n); e < last; e++) {\n                int ch = fEdgeToTailNode[e];\n                double chVal = computedValue (ch);\n                v += chVal;\n            }\n            fNodeToValue[n] = v;\n        } else if (type == LITERAL) {\n            int l = fNodeToLit[n];\n            fNodeToValue[n] = (l < 0 ? negValues[-l] : posValues[l]);\n        }\n        // do nothing for a constant\n    }\n\n    // Downward pass.\n\n    fNodeToDerivative[numNodes - 1] = 1.0;\n    for (int n = numNodes - 1; n >= 0; n--) {\n        char type = fNodeToType[n];\n        if (type == LITERAL || type == CONSTANT) {\n            continue;\n        }\n        int last = fNodeToLastEdge[n];\n        if (type == MULTIPLY) {\n            double value = fNodeToValue[n];\n            if (value == 0.0) {\n                continue;   // more than one zero\n            }\n            double x = fNodeToDerivative[n];\n            if (x == 0.0) {\n                continue;\n            }\n            x *= value;\n            if (x == 0.0) {\n                throw runtime_error(\"Underflow\");\n            }\n            if (fNodeToOneZero[n]) { // exactly one zero\n                for (int e = first (n); e < last; e++) {\n                    int ch = fEdgeToTailNode[e];\n                    double chVal = computedValue (ch);\n                    if (chVal == 0.0) {\n                        fNodeToDerivative[ch] += x;\n                        break;\n                    }\n                }\n            } else { // no zeros\n                for (int e = first (n); e < last; e++) {\n                    int ch = fEdgeToTailNode[e];\n                    double chVal = computedValue (ch);\n                    fNodeToDerivative[ch] += x / chVal;\n                }\n            }\n        } else { /* PLUS NODE */\n            double x = fNodeToDerivative[n];\n            for (int e = first (n); e < last; e++) {\n                int ch = fEdgeToTailNode[e];\n                fNodeToDerivative[ch] += x;\n            }\n        }\n    }\n\n}\n\ninline\ndouble OnlineEngine::computedValue (int n) {\n    return fNodeToOneZero[n] ? 0 : fNodeToValue[n];\n}\n\ninline\nint OnlineEngine::first (int n) {\n    return (n == 0) ? 0 : fNodeToLastEdge[n-1];\n}\n\ninline\nint OnlineEngine::rootNode () {\n    return fNodeToType.size() - 1;\n}\n\ninline\nint OnlineEngine::numAcNodes () {\n    return fNodeToType.size();\n}\n\ninline\nOnlineEngine::OnlineEngine (string acFilename, string lmFilename) {\n\tREAD_DELIMITER  = \"\\\\$\";\n\tDELIMITER = \"$\";  \n\tifstream ac_fs (acFilename, ifstream::in);\n        ifstream lm_fs (lmFilename, ifstream::in);\n        initialize (ac_fs, lm_fs);\n        ac_fs.close();\n        lm_fs.close();\n}\n\ninline\nvoid OnlineEngine::initialize (istream& acReader, istream& lmReader) {\n    readArithmeticCircuit(acReader);\n    readLiteralMap(lmReader);\n    fNodeToValue.resize(numAcNodes());\n    fNodeToDerivative.resize(numAcNodes());\n    fNodeToOneZero.resize(numAcNodes());\n    fUpwardPassCompleted = false;\n    fTwoPassesCompleted = false;\n}\n\ninline\nVariable OnlineEngine::varForName (string n) {\n    return fNameToSrcVar[n];\n}\n\ninline\nPotential OnlineEngine::potForName (string n) {\n    return fNameToSrcPot[n];\n}\n\ninline\nset<Variable> OnlineEngine::variables () {\n    return fVariables;\n}\n\ninline\nset<Potential> OnlineEngine::potentials () {\n    return fPotentials;\n}\n\ninline\nvoid OnlineEngine::assertEvidence (Evidence e, bool secondPass) {\n    if (secondPass) {\n        fAcVarToMostRecentNegWeight = clone (e.fVarToCurrentNegWeight);\n        fAcVarToMostRecentPosWeight = clone (e.fVarToCurrentPosWeight);\n        twoPasses (e);\n    } else {\n        fAcVarToMostRecentNegWeight.clear();\n        fAcVarToMostRecentPosWeight.clear();\n        upwardPass (e);\n    }\n    fUpwardPassCompleted = true;\n    fTwoPassesCompleted = secondPass;\n}\n\ninline\ndouble OnlineEngine::probOfEvidence () {\n    if (!fUpwardPassCompleted) {\n        throw runtime_error (\"assertEvidence () must be called!\");\n    }\n    int root = rootNode ();\n    return fTwoPassesCompleted ? computedValue (root) : fNodeToValue[root];\n}\n\ninline\nvector<double> OnlineEngine::varPartials (Variable v) {\n    if (!fTwoPassesCompleted) {\n        throw runtime_error (\n            \"assertEvidence () must be called with second pass flag set!\");\n    }\n    vector<double> ans(v.domainNames().size());\n    vector<int>& inds = *(fSrcVarToSrcValToIndicator[v]);\n    for (int u = 0; u < ans.size(); u++) {\n        int l = inds[u];\n        ans[u] =\n            (l < 0) ?\n            fNodeToDerivative[fVarToNegLitNode[-l]] :\n            fNodeToDerivative[fVarToPosLitNode[l]];\n    }\n    return ans;\n}\n\ninline\nmap<Variable,vector<double> > OnlineEngine::varPartials (set<Variable> vs) {\n    map<Variable,vector<double> > ans;\n    for (Variable v : vs) {\n        ans[v] = varPartials (v);\n    }\n    return ans;\n}\n\ninline\nvector<double> OnlineEngine::varMarginals (Variable v) {\n    if (!fTwoPassesCompleted) {\n        throw runtime_error (\n            \"assertEvidence () must be called with marginals flag set!\");\n    }\n    vector<double> ans(v.domainNames ().size ());\n    vector<int>& inds = *(fSrcVarToSrcValToIndicator[v]);\n    for (int u = 0; u < ans.size(); u++) {\n        int l = inds[u];\n        ans[u] =\n            (l < 0) ?\n            fAcVarToMostRecentNegWeight[-l] *\n            fNodeToDerivative[fVarToNegLitNode[-l]] :\n            fAcVarToMostRecentPosWeight[l] *\n            fNodeToDerivative[fVarToPosLitNode[l]];\n    }\n    return ans;\n}\n\ninline\nmap<Variable,vector<double> > OnlineEngine::varMarginals (set<Variable> vs) {\n    map<Variable,vector<double> > ans;\n    for (Variable v : vs) {\n        ans[v] = varMarginals (v);\n    }\n    return ans;\n}\n\ninline\nvector<double> OnlineEngine::varPosteriors (Variable v) {\n    double pe = probOfEvidence ();\n    vector<double> ans = varMarginals (v);\n    for (int i = 0; i < ans.size(); i++) {\n        ans[i] /= pe;\n    }\n    return ans;\n}\n\ninline\nmap<Variable,vector<double> > OnlineEngine::varPosteriors (set<Variable> vs) {\n    map<Variable,vector<double> > ans;\n    for (Variable v : vs) {\n        ans[v] = varPosteriors (v);\n    }\n    return ans;\n}\n\ninline\nvector<double> OnlineEngine::potPartials (Potential pot) {\n    vector<int>& parms = *(fSrcPotToSrcPosToParameter[pot]);\n    vector<double> ans(parms.size());\n    for (int pos = 0; pos < ans.size(); pos++) {\n        int l = parms[pos];\n        ans[pos] =\n            l == 0  ? NAN :\n            l < 0 ? fNodeToDerivative[fVarToNegLitNode[-l]] :\n            fNodeToDerivative[fVarToPosLitNode[l]];\n    }\n    return ans;\n}\n\ninline\nmap<Potential,vector<double> > OnlineEngine::potPartials (\n    set<Potential> ps) {\n    map<Potential,vector<double> > ans;\n    for (Potential p : ps) {\n        ans[p] = potPartials (p);\n    }\n    return ans;\n}\n\ninline\nvector<double> OnlineEngine::potMarginals (Potential p) {\n    vector<int>& parms = *(fSrcPotToSrcPosToParameter[p]);\n    vector<double> ans = potPartials (p);\n    for (int pos = 0; pos < ans.size(); pos++) {\n        int l = parms[pos];\n        if (!isnan (ans[pos])) {\n            ans[pos] *=\n                l < 0 ?\n                fAcVarToMostRecentNegWeight[-l] : fAcVarToMostRecentPosWeight[l];\n        }\n    }\n    return ans;\n}\n\ninline\nmap<Potential,vector<double> > OnlineEngine::potMarginals (set<Potential> ps) {\n    map<Potential,vector<double> > ans;\n    for (Potential p : ps) {\n        ans[p] = potMarginals (p);\n    }\n    return ans;\n}\n\ninline\nvector<double> OnlineEngine::potPosteriors (Potential p) {\n    vector<double> ans = potMarginals (p);\n    double pe = probOfEvidence ();\n    for (int pos = 0; pos < ans.size(); pos++) {\n        if (!isnan (ans[pos])) {\n            ans[pos] /= pe;\n        }\n    }\n    return ans;\n}\n\ninline\nmap<Potential,vector<double> > OnlineEngine::potPosteriors (\n    set<Potential> ps) {\n    map<Potential,vector<double> > ans;\n    for (Potential p : ps) {\n        ans[p] = potPosteriors (p);\n    }\n    return ans;\n}\n\n\n\ninline\nvoid OnlineEngine::readArithmeticCircuit(istream& r) {\n\n    int numNodes = __INT_MAX__;\n    int nextEdge = 0;\n    int nextNode = 0;\n    \n    // Process each line.\n    \n    while (nextNode < numNodes) {\n      \n      // Read the line.  Quit if eof.  Skip if comment or blank line.\n      // Otherwise, split into tokens.\n      \n      string line;\n      if (!getline(r, line)) {break;} // eof\n      if (boost::starts_with(line, \"c\")) {continue;} // comment\n      boost::trim(line);\n      if (line.length () == 0) {continue;} // blank line\n      vector<string> tokens;\n      boost::split(tokens, line, boost::is_any_of(\"\\t \"), boost::token_compress_on);\n      \n      // A header line looks like: \"nnf\" numNodes numEdges numVars\n      \n      if (tokens[0] == \"nnf\") {\n\tnumNodes = boost::lexical_cast<int>(tokens[1]);\n        int numEdges = boost::lexical_cast<int>(tokens[2]);\n        int numAcVars = boost::lexical_cast<int>(tokens[3]);\n        fEdgeToTailNode.resize(numEdges);\n        fNodeToLastEdge.resize(numNodes);\n        fNodeToType.resize(numNodes);\n        fNodeToLit.resize(numNodes, 0);\n        fVarToNegLitNode.assign(numAcVars + 1, -1);\n        fVarToPosLitNode.assign(numAcVars + 1, -1);\n        continue;\n      }\n      \n      // This is not a header line, so it must be a node line, which looks\n      // like one of the following:\n      //   \"A\" numChildren child+\n      //   \"O\" splitVar numChildren child+\n      //   \"L\" literal\n      char ch = tokens[0].at(0);\n      if (ch == 'A') {\n        fNodeToType[nextNode] = MULTIPLY;\n        for (int chIndex = 2; chIndex < tokens.size(); chIndex++) {\n          fEdgeToTailNode[nextEdge++] = boost::lexical_cast<int> (tokens[chIndex]);\n        }\n      } else if (ch == 'O') {\n        fNodeToType[nextNode] = ADD;\n        for (int chIndex = 3; chIndex < tokens.size(); chIndex++) {\n          fEdgeToTailNode[nextEdge++] = boost::lexical_cast<int> (tokens[chIndex]);\n        }\n      } else /* ch == 'L' */ {\n        fNodeToType[nextNode] = LITERAL;\n        int l = boost::lexical_cast<int> (tokens[1]);\n        fNodeToLit[nextNode] = l;\n        (l < 0 ? fVarToNegLitNode : fVarToPosLitNode)[abs (l)] =\n          nextNode;\n      }\n      fNodeToLastEdge[nextNode] = nextEdge;\n      nextNode++;\n\n    }\n\n}\n\ninline\nvoid OnlineEngine::readLiteralMap(istream& r) {\n    \n    // Prepare to parse.\n    \n    int numLits = __INT_MAX__;\n    int litsFinished = 0;\n\n    // Process each line.\n    \n    while (litsFinished < numLits) {\n      \n      // Read the line.  Quit if eof.  Skip if comment (including blank\n      // lines).  Otherwise, split into tokens.\n      \n      \n      string line;\n      if (!getline(r, line)) {break;} // eof\n      if (!boost::starts_with(line, (\"cc\" + DELIMITER))) {continue;} // comment\n      boost::trim(line);\n      vector<string> tokens;\n      boost::split(tokens, line, boost::is_any_of(READ_DELIMITER), boost::token_compress_on);\n      \n      // If the line is a header, it is of the form: \"cc\" \"N\" numLogicVars.\n      string type = tokens[1];\n      if (type == \"N\") {\n\tint n = boost::lexical_cast<int>(tokens[2]);\n        numLits = n * 2;\n        fLogicVarToDefaultNegWeight.resize(n+1);\n        fLogicVarToDefaultPosWeight.resize(n+1);\n        continue;\n      }\n      \n      // If the line is a variable line, then it is of the form:\n      // \"cc\" \"V\" srcVarName numSrcVals (srcVal)+\n\n      if (type == \"V\") {\n        string vn = tokens[2];\n        int valCount = boost::lexical_cast<int>(tokens[3]);\n        vector<string> valNames(valCount, \"\");\n        for (int i = 0; i < valCount; i++) {valNames[i] = tokens[4 + i];}\n        Variable v(vn, valNames);\n        fSrcVarToSrcValToIndicator[v] = new vector<int>(valCount);\n        fNameToSrcVar[vn] = v;\n        continue;\n      }\n      \n      // If the line is a potential line, then it is of the form:\n      // \"cc\" \"T\" srcPotName parameterCnt.\n      \n      if (type == \"T\") {\n        string tn = tokens[2];\n        int parmCount = boost::lexical_cast<int> (tokens[3]);\n        Potential pot(tn, parmCount);\n        fSrcPotToSrcPosToParameter[pot] = new vector<int>(parmCount);\n        fNameToSrcPot[tn] = pot;\n        continue;\n      }\n\n      // This is not a header line, a variable line, or potential line, so\n      // it must be a literal description, which looks like one of the\n      // following:\n      //   \"cc\" \"I\" literal weight srcVarName srcValName srcVal\n      //   \"cc\" \"P\" literal weight srcPotName pos+\n      //   \"cc\" \"A\" literal weight\n      \n      int l = boost::lexical_cast<int>(tokens[2]);\n      double w = boost::lexical_cast<double>(tokens[3]);\n      (l < 0 ? fLogicVarToDefaultNegWeight : fLogicVarToDefaultPosWeight)\n        [abs (l)] = w;\n      if (type == \"I\") {\n        string vn = tokens[4];\n        //String un = tokens[5];\n        int u = boost::lexical_cast<int>(tokens[6]);\n        fSrcVarToSrcValToIndicator[fNameToSrcVar[vn]]->at(u) = l;\n      } else if (type == \"P\") {\n        string tn = tokens[4];\n\tvector<string> posStrings;\n\tboost::split(posStrings, tokens[5], boost::is_any_of(\",\"));\n        if (posStrings.size() == 1) {\n\t  int pos = boost::lexical_cast<int>(posStrings[0]);\n          fSrcPotToSrcPosToParameter[fNameToSrcPot[tn]]->at(pos) = l;\n        }\n      } else if (type == \"A\") {\n      } else {\n        throw runtime_error (\n          \"\\\"cc\\\" must be followed by \\\"N\\\", \\\"V\\\", \\\"T\\\", \\\"I\\\", \\\"P\\\", or \\\"A\\\"\");\n      }\n      ++litsFinished;\n      \n    }\n\n    // Now create the variables, the map from variable name to variable, and\n    // the map from variable to value to indicator.\n    for (auto p : fNameToSrcVar)\n      fVariables.insert(p.second);\n    for (auto p : fNameToSrcPot)\n      fPotentials.insert(p.second);\n\n}\n", "meta": {"hexsha": "17c892d21b271a30eda26c992e74a14ed33db190", "size": 23967, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AceEvalCpp/AceEvalCpp.hpp", "max_stars_repo_name": "Behrouz-Babaki/AceEvalCpp", "max_stars_repo_head_hexsha": "6d5b0d79ab0da953d10b0a19ee48d598612db823", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AceEvalCpp/AceEvalCpp.hpp", "max_issues_repo_name": "Behrouz-Babaki/AceEvalCpp", "max_issues_repo_head_hexsha": "6d5b0d79ab0da953d10b0a19ee48d598612db823", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AceEvalCpp/AceEvalCpp.hpp", "max_forks_repo_name": "Behrouz-Babaki/AceEvalCpp", "max_forks_repo_head_hexsha": "6d5b0d79ab0da953d10b0a19ee48d598612db823", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3969194313, "max_line_length": 93, "alphanum_fraction": 0.5901447824, "num_tokens": 6367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.03514484690608696, "lm_q1q2_score": 0.011881669239477647}}
{"text": "//!\n//! Contains the implementation of Monte Carlo Markov Chain simulations.\n//!\n//! \\file infer/mcmc.cpp\n//! \\author Lachlan McCalman\n//! \\author Darren Shen\n//! \\date 2014\n//! \\license Affero General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#pragma once\n\n#include <limits>\n#include <random>\n#include <iomanip>\n#include <chrono>\n#include <Eigen/Dense>\n#include <boost/circular_buffer.hpp>\n#include <iostream>\n#include <glog/logging.h>\n\n#include \"db/db.hpp\"\n#include \"app/settings.hpp\"\n#include \"infer/chainarray.hpp\"\n#include \"infer/diagnostics.hpp\"\n#include \"comms/transport.hpp\"\n\nnamespace stateline\n{\n  namespace mcmc\n  {\n    //! Represents a Markov Chain Monte Carlo sampler that returns samples from\n    //! a distribution.\n    //!\n    class Sampler\n    {\n    public:\n      //! Create a new sampler.\n      //!\n      //! \\param s Settings to tune various parameters of the MCMC.\n      //! \\param d Settings for configuring the database for storing samples.\n      //! \\param stateDim The number of dimensions in each sample.\n      //! \\param interrupted A flag used to monitor whether the sampler has been interrupted.\n      //!\n      Sampler(const MCMCSettings& s, const DBSettings& d, uint stateDim, volatile bool& interrupted)\n          : db_(d),\n            chains_(s.stacks, s.chains, s.initialTempFactor, s.proposalInitialSigma, s.initialSigmaFactor, db_, s.cacheLength, d.recover),\n            lengths_(s.stacks * s.chains, 0),\n            propStates_(s.stacks * s.chains, stateDim),\n            locked_(s.stacks * s.chains, false),\n            nextChainBeta_(s.stacks * s.chains),\n            nAcceptsGlobal_(s.stacks * s.chains, 0),\n            nSwapsGlobal_(s.stacks * (s.chains), 0),\n            nSwapAttemptsGlobal_(s.stacks * s.chains, 0),\n            sigmas_(s.stacks * s.chains),\n            betas_(s.stacks * s.chains),\n            acceptRates_(s.stacks * s.chains),\n            swapRates_(s.stacks * s.chains),\n            lowestEnergies_(s.stacks * s.chains),\n            s_(s),\n            recover_(d.recover),\n            numOutstandingJobs_(0),\n            interrupted_(interrupted),\n            context_(1)\n      {\n        // Initialise for logging purposes\n        for (uint i = 0; i < s.chains * s.stacks; i++)\n        {\n          lengths_[i] = chains_.length(i);\n          sigmas_[i] = chains_.sigma(i);\n          betas_[i] = chains_.beta(i);\n          nextChainBeta_[i] = chains_.beta(i);\n          acceptRates_[i] = 1;\n          swapRates_[i] = 0;\n          lowestEnergies_[i] = std::numeric_limits<double>::infinity();\n          acceptBuffers_.push_back(boost::circular_buffer<bool>(s.adaptionLength));\n          swapBuffers_.push_back(boost::circular_buffer<bool>(s.adaptionLength / s.swapInterval + 1));\n          nAcceptsGlobal_[i] = 1;\n          acceptBuffers_[i].push_back(true); // first state always accepts\n          nSwapsGlobal_[i] = 0;\n          nSwapAttemptsGlobal_[i] = 1;\n          swapBuffers_[i].push_back(false); // gets rid of a nan, not really needed\n        }\n      }\n\n      //! Run the sampler for a period of time.\n      //!\n      //! \\param policy Async policy to evaluate states.\n      //! \\param initialStates Initial chain states. Ignored if recovering.\n      //! \\param propFn The proposal function.\n      //! \\param numSeconds The number of seconds to run the MCMC for.\n      //!\n      template<class AsyncPolicy, class PropFn>\n      void run(AsyncPolicy &policy, const std::vector<Eigen::VectorXd>& initialStates, PropFn &propFn, uint numSeconds)\n      {\n        using namespace std::chrono;\n\n        // Used for publishing statistics to visualisation server.\n        zmq::socket_t publisher(context_, ZMQ_PUB);\n        publisher.bind(\"tcp://*:5556\");\n\n        // Record the starting time of the MCMC\n        steady_clock::time_point startTime = steady_clock::now();\n\n        // Initialise the chains if we're not recovering\n        if (!recover_)\n        {\n          initialise(policy, initialStates);\n        }\n\n        // Start all the chains from hottest to coldest\n        for (uint i = 0; i < chains_.numTotalChains(); i++)\n        {\n          uint c = chains_.numTotalChains() - i - 1;\n          propose(policy, c, propFn);\n        }\n\n        // Initialise the convergence criteria\n        uint stateDim = initialStates[0].size();\n        EpsrConvergenceCriteria cc(chains_.numStacks(), stateDim);\n\n        // Listen for replies. As soon as a new state comes back,\n        // add it to the corresponding chain, and submit a new proposed state\n        auto lastLogTime = steady_clock::now();\n        auto lastPrintTime = steady_clock::now();\n        while (duration_cast<seconds>(steady_clock::now() - startTime).count() < numSeconds && !interrupted_)\n        {\n          std::pair<uint, double> result;\n\n          // Wait a for reply\n          try\n          {\n            result = policy.retrieve();\n          }\n          catch (...)\n          {\n            VLOG(3) << \"Comms error -- probably shutting down\";\n          }\n\n          // If we weree interrupted this state will be garbage\n          if (interrupted_)\n            break;\n\n          numOutstandingJobs_--;\n          uint id = result.first;\n          double energy = result.second;\n\n          // Check if this chain is either the coldest or the hottest\n          bool isHottestChainInStack = id % chains_.numChains() == chains_.numChains() - 1;\n          bool isColdestChainInStack = id % chains_.numChains() == 0;\n\n          // Handle the new proposal and add a new state to the chain\n          State propState { propStates_.row(id), energy, chains_.beta(id), false, SwapType::NoAttempt };\n          bool propAccepted = chains_.append(id, propState);\n          lengths_[id] += 1;\n          updateAccepts(id, propAccepted);\n\n          // Update the convergence test if this is the coldest chain in a stack\n          if (isColdestChainInStack && chains_.numChains() > 1 && chains_.numStacks() > 1)\n          {\n            cc.update(id / chains_.numChains(), chains_.lastState(id).sample);\n          }\n\n          // Check if this chain was locked. If it was locked, it means that\n          // the chain above (hotter) locked it so that it can swap with it\n          if (locked_[id])\n          {\n            // Try swapping this chain with the one above it\n            bool swapAccepted = chains_.swap(id, id + 1);\n            updateSwaps(id + 1, swapAccepted);\n            // Unlock this chain, propgating the lock downwards\n            unlock(policy, id, propFn);\n          }\n          else if (isHottestChainInStack && lengths_[id] % s_.swapInterval == 0 && chains_.numChains() > 1)\n          {\n            // The hottest chain is ready to swap. Lock the next chain\n            // to prevent it from proposing any more\n            locked_[id - 1] = true;\n          }\n          else\n          {\n            // This chain is not locked, so we can propose\n            try\n            {\n              propose(policy, id, propFn);\n            }\n            catch (...)\n            {\n              VLOG(3) << \"Comms error -- probably shutting down\";\n            }\n          }\n\n          // Check again after a new interaction with comms\n          if (interrupted_)\n            break;\n\n          // Log the best energy state so far\n          lowestEnergies_[id] = std::min(lowestEnergies_[id], chains_.lastState(id).energy);\n\n          // Check if we need to adapt the step size for this chain\n          if (lengths_[id] % s_.proposalAdaptInterval == 0)\n          {\n            adaptSigma(id);\n          }\n\n          // Update the temperature which might have changed while waiting\n          chains_.setBeta(id, nextChainBeta_[id]);\n          betas_[id] = nextChainBeta_[id];\n          // Check for adapting the temperatures of all the chains but the 1st\n          if (lengths_[id] % s_.betaAdaptInterval == 0 && !isColdestChainInStack)\n          {\n            adaptBeta(id);\n          }\n\n          // Update the accept and swap rates\n          if (duration_cast<milliseconds>(steady_clock::now() - lastLogTime).count() > 50)\n          {\n            lastLogTime = steady_clock::now();\n\n            std::stringstream s;\n            s << \"\\n\\nChainID  Length  MinEngy  CurrEngy    Sigma      AcptRt    GlbAcptRt    Beta     SwapRt   GlbSwapRt\\n\";\n            s << \"-----------------------------------------------------------------------------------------------------\\n\";\n            for (uint i = 0; i < chains_.numTotalChains(); i++)\n            {\n              if (i % chains_.numChains() == 0 && i != 0)\n                s << '\\n';\n              s << std::setprecision(6) << std::showpoint << i << \" \" << std::setw(9) << lengths_[i] << \" \" << std::setw(10)\n                  << lowestEnergies_[i] << \" \" << std::setw(10) << chains_.lastState(i).energy << \" \" << std::setw(10) << sigmas_[i] << \" \"\n                  << std::setw(10) << acceptRates_[i] << \" \" << std::setw(10) << nAcceptsGlobal_[i] / (double) lengths_[i] << \" \"\n                  << std::setw(10) << betas_[i] << \" \" << std::setw(10) << swapRates_[i] << \" \" << std::setw(10)\n                  << nSwapsGlobal_[i] / (double) nSwapAttemptsGlobal_[i] << \" \\n\";\n            }\n\n            // Quick and dirty way to get the data to the visualisation server\n            comms::sendString(publisher, s.str());\n\n            if (duration_cast<milliseconds>(steady_clock::now() - lastPrintTime).count() > 500)\n            {\n              lastPrintTime = steady_clock::now();\n\n              LOG(INFO)<< s.str() << \"\\n\";\n\n              if (chains_.numStacks() > 1 && chains_.numChains() > 1)\n              {\n                if (cc.hasConverged())\n                {\n                  LOG(INFO)<< \"converged: true (\"<< cc.rHat().transpose() << \" < 1.1)\";\n                }\n                else\n                {\n                  LOG(INFO) << \"converged: false (\"<< cc.rHat().transpose() << \" > 1.1)\";\n                }\n              }\n            }\n          }\n        }\n\n        // Time limit reached. We need to now retrieve all outstanding job results.\n        if (!interrupted_)\n        {\n          while (numOutstandingJobs_--)\n          {\n            auto result = policy.retrieve();\n            uint id = result.first;\n            double energy = result.second;\n            State propState { propStates_.row(id), energy, chains_.beta(id), false, SwapType::NoAttempt };\n            bool propAccepted = chains_.append(id, propState);\n            lengths_[id] += 1;\n            updateAccepts(id, propAccepted);\n          }\n        }\n        else\n        {\n          LOG(INFO)<< \"Inference interrupted by user: Exiting.\";\n        }\n\n        // Manually flush any chain states that are in memory to disk\n        for (uint i = 0; i < chains_.numTotalChains(); i++)\n        {\n          chains_.flushCache(i);\n        }\n\n        if (cc.hasConverged())\n        {\n          LOG(INFO)<< \"MCMC has converged\";\n        }\n        else\n        {\n          LOG(INFO) << \"WARNING: MCMC has not converged\";\n        }\n\n        LOG(INFO)<<\"Length of chain 0: \" << lengths_[0];\n    }\n\n    //! Get the MCMC chain array.\n    //!\n    //! \\return A copy of the chain array.\n    //!\n    ChainArray chains()\n    {\n      return chains_;\n    }\n\n    //! Get the MCMC chain array.\n    //!\n    //! \\return A const reference to the chain array.\n    //!\n    const ChainArray &chains() const\n    {\n      return chains_;\n    }\n\n  private:\n\n    //! Initialise the sampler.\n    //!\n    //! \\param policy Async policy to evaluate states.\n    //! \\param initialStates A list containing the initial states of the chains.\n    //!\n    template <class AsyncPolicy>\n    void initialise(AsyncPolicy &policy, const std::vector<Eigen::VectorXd>& initialStates)\n    {\n      // Evaluate the initial states of the chains\n      for (uint i = 0; i < chains_.numTotalChains(); i++)\n      {\n        propStates_.row(i) = initialStates[i];\n        policy.submit(i, propStates_.row(i));\n      }\n\n      // Retrieve the energies and temperatures for the initial states\n      for (uint i = 0; i < chains_.numTotalChains(); i++)\n      {\n        auto result = policy.retrieve();\n        uint id = result.first;\n        double energy = result.second;\n        State s\n        { initialStates[id], energy, chains_.beta(id), true, SwapType::NoAttempt};\n        chains_.initialise(id, s);\n      }\n    }\n\n    //! Propose a new state through an async policy.\n    //!\n    //! \\param policy Async policy to evaluate proposals.\n    //! \\param id The id of the chain that is proposing.\n    //! \\param propFn The proposal function.\n    //!\n    template <class AsyncPolicy, class PropFn>\n    void propose(AsyncPolicy &policy, uint id, PropFn &propFn)\n    {\n      propStates_.row(id) = propFn(chains_.lastState(id).sample, chains_.sigma(id));\n      policy.submit(id, propStates_.row(id));\n      numOutstandingJobs_++;\n    }\n\n    //! Unlock a chain and reactivate any chains that were waiting for it.\n    //!\n    //! \\param policy Async policy to evulate proposals.\n    //! \\param id The id of the chain to unlock.\n    //! \\param propFn The proposal function.\n    //!\n    template <class AsyncPolicy, class PropFn>\n    void unlock(AsyncPolicy &policy, uint id, PropFn &propFn)\n    {\n      // Unlock this chain\n      locked_[id] = false;\n\n      // The hotter chain no longer has to wait for this chain, so\n      // it can propose new state\n      propose(policy, id + 1, propFn);\n\n      // Check if this was the coldest chain\n      if (id % chains_.numChains() != 0)\n      {\n        // Lock the chain that is below (colder) than this.\n        locked_[id - 1] = true;\n      }\n      else\n      {\n        // This is the coldest chain and there is no one to swap with\n        propose(policy, id, propFn);\n      }\n    }\n\n    //! Return a new proposal step size for a chain.\n    //!\n    //! \\param id The id of the chain to be adapted.\n    //! \\return The new proposal step size.\n    //!\n    double adaptSigma(uint id)\n    {\n      double acceptRate = acceptRates_[id];\n      double oldSigma= chains_.sigma(id);\n      double factor = std::pow(acceptRate / s_.proposalOptimalAccept, s_.proposalAdaptRate);\n      double boundFactor = std::min(std::max(factor, s_.proposalMinFactor), s_.proposalMaxFactor);\n      double gamma = s_.adaptionLength/(double)(s_.adaptionLength+lengths_[id]);\n\n      double newSigma = oldSigma * std::pow(boundFactor, gamma);\n      VLOG(2) << \"Adapting Sigma\" << id <<\":\" << oldSigma << \"->\" << newSigma << \" @acceptrate:\" << acceptRate;\n      chains_.setSigma(id, newSigma);\n      sigmas_[id] = newSigma;\n\n      // Ensure higher temperature chains have larger sigmas than chains colder than it\n      if (id % chains_.numChains() != 0 && newSigma < chains_.sigma(id - 1))\n      {\n        newSigma = chains_.sigma(id - 1);\n      }\n\n      return newSigma;\n    }\n\n    //! Adapt a new temperature for a chain.\n    //!\n    //! \\param id The id of the chain to be adapted.\n    //!\n    void adaptBeta(uint id)\n    {\n      // Adapt the temperature\n      double swapRate = swapRates_[id];\n      double rawFactor = std::pow(swapRate/s_.betaOptimalSwapRate, s_.betaAdaptRate);\n      double boundedFactor = std::min( std::max(rawFactor, s_.betaMinFactor), s_.betaMaxFactor);\n      double beta = chains_.beta(id);\n      double lowerBeta = chains_.beta(id-1);// temperature changes propogate UP\n      double factor = 1.0/std::max(boundedFactor, 2*beta/(beta + lowerBeta));\n\n      // Set the temperature for this chain (because it hasn't proposed yet)\n      double gamma = s_.adaptionLength/(double)(s_.adaptionLength+lengths_[id]);\n      double newbeta = chains_.beta(id) * std::pow(factor, gamma);\n      chains_.setBeta(id,newbeta);\n      nextChainBeta_[id] = newbeta;\n      betas_[id] = newbeta;\n\n      // Just for logging\n      VLOG(2) << \"Adapting Beta\" << id << \":\" << beta << \"->\" << newbeta << \" @swaprate:\" << swapRate;\n\n      // Loop through the other temperatures\n      uint coldestChainId = (uint)(id / (double)chains_.numChains()) * chains_.numChains();\n      uint hottestChainId = coldestChainId + chains_.numChains()-1;\n\n      // Set the next temperatures for the other chains (as they're busy)\n      for (uint i = id+1; i <= hottestChainId; i++)\n      {\n        nextChainBeta_[i] = nextChainBeta_[i] * std::pow(factor, gamma);\n      }\n    }\n\n    void updateAccepts(uint id, bool acc)\n    {\n      uint oldSize = acceptBuffers_[id].size();\n      double oldRate = acceptRates_[id];\n      bool isFull = acceptBuffers_[id].full();\n      bool lastAcc = acceptBuffers_[id].front();\n\n      // Now push on the new state\n      acceptBuffers_[id].push_back(acc);\n\n      // Compute the new rate\n      uint newSize = acceptBuffers_[id].size();\n      double delta = ((int)acc - (int)(lastAcc&&isFull))/(double)newSize;\n      double scale = oldSize/(double)newSize;\n      acceptRates_[id] = std::max(oldRate*scale + delta, 0.0);\n      nAcceptsGlobal_[id] += acc;\n      if (acceptRates_[id] > 1.0)\n      {\n        std::cout << \"oldSize: \" << oldSize << \"\\n\"\n        << \"isFull:\" << isFull << \"\\n\"\n        << \"newSize:\" << newSize << \"\\n\"\n        << \"lastAcc:\" << lastAcc << \"\\n\"\n        << \"delta:\" << delta << \"\\n\"\n        << \"scale:\" << scale << \"\\n\"\n        << \"oldRate:\" << oldRate << \"\\n\"\n        << \"rate:\" << acceptRates_[id] << \"\\n\"\n        << std::endl;\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    void updateSwaps(uint id, bool sw)\n    {\n      uint oldSize = swapBuffers_[id].size();\n      double oldRate = swapRates_[id];\n      bool isFull = swapBuffers_[id].full();\n      bool lastSw = swapBuffers_[id].front();\n\n      // Now push back the new state\n      swapBuffers_[id].push_back(sw);\n\n      // Compute the new rate\n      uint newSize = swapBuffers_[id].size();\n      double delta = ((int)sw - (int)(lastSw&&isFull))/(double)newSize;\n      double scale = oldSize/(double)newSize;\n      swapRates_[id] = std::max(oldRate*scale + delta, 0.0);\n      nSwapsGlobal_[id] += sw;// for global rate\n      nSwapAttemptsGlobal_[id] += 1;\n    }\n\n    // The MCMC chain database\n    db::Database db_;\n\n    // The MCMC chain wrapper\n    ChainArray chains_;\n\n    // lengths of the chains\n    std::vector<uint> lengths_;\n\n    // Matrix of proposed states\n    Eigen::MatrixXd propStates_;\n\n    // Whether a chain is locked. A locked chain will wait for any outstanding\n    // job results and propagate the lock.\n    std::vector<bool> locked_;\n\n    // Cache the next temperature as computed by lower chains in the stack\n    std::vector<double> nextChainBeta_;\n\n    // Keep track of the swaps and accepts for adaption\n    std::vector<unsigned long long> nAcceptsGlobal_;\n    std::vector<unsigned long long> nSwapsGlobal_;\n    std::vector<unsigned long long> nSwapAttemptsGlobal_;\n\n    std::vector<boost::circular_buffer<bool>> acceptBuffers_;\n    std::vector<boost::circular_buffer<bool>> swapBuffers_;\n\n    // For logging purposes\n    std::vector<double> sigmas_;\n    std::vector<double> betas_;\n    std::vector<double> acceptRates_;\n    std::vector<double> swapRates_;\n    std::vector<double> lowestEnergies_;\n\n    // The MCMC settings\n    MCMCSettings s_;\n\n    // Recovering?\n    bool recover_;\n\n    // How many jobs haven't been retrieved?\n    uint numOutstandingJobs_;\n\n    // Whether an interrupt signal has been sent to the sampler.\n    volatile bool& interrupted_;\n\n    zmq::context_t context_;\n  };\n}\n// namespace mcmc\n}// namespace obsidian\n", "meta": {"hexsha": "427316540e1af3c1a0d438368e3c8623c70d9a37", "size": 19382, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/infer/mcmc.hpp", "max_stars_repo_name": "NICTA/obsidian", "max_stars_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T01:03:57.000Z", "max_issues_repo_path": "src/infer/mcmc.hpp", "max_issues_repo_name": "NICTA/obsidian", "max_issues_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/infer/mcmc.hpp", "max_forks_repo_name": "NICTA/obsidian", "max_forks_repo_head_hexsha": "911984dae2116415cc30621691d4020c34ea9e15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T05:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T21:37:47.000Z", "avg_line_length": 35.3041894353, "max_line_length": 139, "alphanum_fraction": 0.5770302342, "num_tokens": 4827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766828768970435, "lm_q2_score": 0.036220052483855784, "lm_q1q2_score": 0.011868162577416248}}
{"text": "#include <float.h>\n#include <math.h>\n#include <time.h>\n#include <functional>\n#include <iostream>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/serialization/string.hpp>\n#include <boost/serialization/unordered_map.hpp>\n#include <boost/serialization/utility.hpp>\n\n#include <clipper/datatypes.hpp>\n#include <clipper/logging.hpp>\n#include <clipper/selection_policies.hpp>\n#include <clipper/util.hpp>\n\nnamespace clipper {\n\n// *********\n// * State *\n// *********\n\nvoid BanditPolicyState::set_model_map(Map map) { model_map_ = map; }\nvoid BanditPolicyState::add_model(VersionedModelId id, ModelInfo model) {\n  model_map_.insert({id, model});\n}\nvoid BanditPolicyState::set_weight_sum(double sum) { weight_sum_ = sum; }\n\nstd::string BanditPolicyState::serialize() const {\n  std::stringstream ss;\n  boost::archive::binary_oarchive oa(ss);\n  oa << weight_sum_ << model_map_.size()\n     << model_map_;  // save weight_sum, map size and map\n  return ss.str();\n}\n\nBanditPolicyState BanditPolicyState::deserialize(const std::string& bytes) {\n  std::stringstream ss;\n  ss.str(bytes);\n  boost::archive::binary_iarchive ia(ss);\n  BanditPolicyState state;\n  double sum;\n  size_t size;\n  ia >> sum >> size;  // load weight_sum and map size\n  Map map(size, &versioned_model_hash);\n  ia >> map;\n  state.set_model_map(map);\n  state.set_weight_sum(sum);\n\n  return state;\n}\n\nstd::string BanditPolicyState::debug_string() const {\n  /** State string representation:\n    *  For each model: Model Name, Model ID, Model Property Value 1, Model\n   * Property Value 2\n    *  Different models are separated by semi-colon\n    *  e.g. \"3.0;classification,00001,1.0,0.4;regression,203422,1.0,0.4;.......\"\n    */\n\n  std::string string_state = \"Exp3State;\";\n  if (model_map_.empty()) {\n    std::cout << \"State is empty\" << std::endl;\n    return string_state;\n  }\n  string_state += std::to_string(weight_sum_) + \";\";  // Weight Sum\n  for (auto it : model_map_) {\n    string_state +=\n        it.first.first + std::to_string(it.first.second);  // Model Name\n    for (auto model_info_it : it.second) {                 // Model information\n      string_state += \",\" + std::to_string(model_info_it.second);\n    }\n    string_state += \";\";\n  }\n  return string_state;\n}\n\n// ********\n// * EXP3 *\n// ********\n\nBanditPolicyState Exp3Policy::initialize(\n    const std::vector<VersionedModelId>& candidate_models_) {\n  Map map(candidate_models_.size(), &versioned_model_hash);\n  for (VersionedModelId id : candidate_models_) {\n    ModelInfo info = {{\"weight\", 1.0}};\n    map.insert({id, info});\n  }\n  BanditPolicyState state;\n  state.set_model_map(map);\n  state.set_weight_sum(map.size() * 1.0);\n  return state;\n}\n\nBanditPolicyState Exp3Policy::add_models(\n    BanditPolicyState state, const std::vector<VersionedModelId>& new_models) {\n  double avg;\n  if (state.model_map_.empty()) {  // State hasn't been initiated or no models\n    avg = 1.0;\n  } else {\n    avg = state.weight_sum_ / state.model_map_.size();\n  }\n\n  for (VersionedModelId id : new_models) {\n    ModelInfo info = {{\"weight\", avg}};\n    state.add_model(id, info);\n    state.set_weight_sum(state.weight_sum_ + avg);\n  }\n  return state;\n}\n\nVersionedModelId Exp3Policy::select(BanditPolicyState& state) {\n  // Helper function for randomly drawing an arm based on its normalized weight\n  VersionedModelId selected_model;\n  if (state.model_map_.empty()) {\n    std::cout << \"No models to select from\" << std::endl;\n    return selected_model;\n  }\n  double rand_num =\n      (double)rand() / (RAND_MAX);  // Pick random number between [0, 1]\n  for (auto it = state.model_map_.begin();\n       it != state.model_map_.end() && rand_num >= 0; ++it) {\n    rand_num -= it->second[\"weight\"] / state.weight_sum_;\n    selected_model = it->first;\n  }\n  return selected_model;\n}\n\nstd::vector<PredictTask> Exp3Policy::select_predict_tasks(\n    BanditPolicyState state, Query query, long query_id) {\n  auto selected_model = select(state);\n  auto task = PredictTask(query.input_, selected_model, 1.0, query_id,\n                          query.latency_micros_);\n  std::vector<PredictTask> tasks{task};\n  return tasks;\n}\n\nOutput Exp3Policy::combine_predictions(BanditPolicyState /*state*/,\n                                       Query /*query*/,\n                                       std::vector<Output> predictions) {\n  if (predictions.empty()) {\n    std::cout << \"No predictions to combine\" << std::endl;\n    Output output;\n    return output;\n  }\n  return predictions.front();\n}\n\nstd::pair<std::vector<PredictTask>, std::vector<FeedbackTask>>\nExp3Policy::select_feedback_tasks(BanditPolicyState& state,\n                                  FeedbackQuery feedback, long query_id) {\n  // Predict Task\n  auto selected_model = select(state);\n  auto predict_task =\n      PredictTask(feedback.feedback_.input_, selected_model, -1, query_id, -1);\n  std::vector<PredictTask> predict_tasks{predict_task};\n  // Feedback Task\n  std::vector<FeedbackTask> feedback_tasks;\n\n  return make_pair(predict_tasks, feedback_tasks);\n}\n\nBanditPolicyState Exp3Policy::process_feedback(\n    BanditPolicyState state, Feedback feedback,\n    std::vector<Output> predictions) {\n  if (predictions.empty()) {  // Edge case\n    std::cout << \"No predictions, so can't update state.\" << std::endl;\n    return state;\n  }\n\n  // Compute loss and find which model to update\n  auto loss = std::abs(predictions.front().y_hat_ - feedback.y_);\n  auto model_id = predictions.front().models_used_.front();\n  // Update arm weight and weight_sum\n  auto s_i = state.model_map_[model_id][\"weight\"];\n  if (s_i != 0) {\n    auto update = exp(-eta * loss / (s_i / state.weight_sum_));\n    state.model_map_[model_id][\"weight\"] = s_i * update;\n    state.set_weight_sum(state.weight_sum_ - s_i +\n                         state.model_map_[model_id][\"weight\"]);\n  }\n  return state;\n}\n\nstd::string Exp3Policy::serialize_state(BanditPolicyState state) {\n  return state.serialize();\n}\n\nBanditPolicyState Exp3Policy::deserialize_state(const std::string& bytes) {\n  return BanditPolicyState::deserialize(bytes);\n}\n\nstd::string Exp3Policy::state_debug_string(const BanditPolicyState& state) {\n  return state.debug_string();\n}\n\n//// ********\n//// * EXP4 *\n//// ********\n\nBanditPolicyState Exp4Policy::initialize(\n    const std::vector<VersionedModelId>& candidate_models_) {\n  return Exp3Policy::initialize(candidate_models_);\n}\n\nBanditPolicyState Exp4Policy::add_models(\n    BanditPolicyState state, const std::vector<VersionedModelId>& new_models) {\n  return Exp3Policy::add_models(state, new_models);\n}\n\nstd::vector<PredictTask> Exp4Policy::select_predict_tasks(\n    BanditPolicyState& /*state*/, Query query, long query_id) {\n  // Pass along all models selected\n  std::vector<PredictTask> tasks;\n  for (VersionedModelId id : query.candidate_models_) {\n    auto task =\n        PredictTask(query.input_, id, 1.0, query_id, query.latency_micros_);\n    tasks.push_back(task);\n  }\n  return tasks;\n}\n\nOutput Exp4Policy::combine_predictions(BanditPolicyState state, Query /*query*/,\n                                       std::vector<Output> predictions) {\n  // Weighted Combination of All predictions\n  auto y_hat = 0;\n  std::vector<VersionedModelId> models;\n  for (auto p : predictions) {\n    auto model_id = (p.models_used_).front();\n    y_hat +=\n        (state.model_map_[model_id][\"weight\"] / state.weight_sum_) * p.y_hat_;\n    models.push_back(model_id);\n  }\n  // Turn y_hat into either 0 or 1\n  if (y_hat < 0.5) {\n    y_hat = 0;\n  } else {\n    y_hat = 1;\n  }\n\n  auto output = Output(y_hat, models);\n  return output;\n}\n\nstd::pair<std::vector<PredictTask>, std::vector<FeedbackTask>>\nExp4Policy::select_feedback_tasks(BanditPolicyState& /*state*/,\n                                  FeedbackQuery feedback, long query_id) {\n  std::vector<PredictTask> predict_tasks;\n  std::vector<FeedbackTask> feedback_tasks;\n  for (VersionedModelId id : feedback.candidate_models_) {\n    auto predict_task =\n        PredictTask(feedback.feedback_.input_, id, -1, query_id, -1);\n    predict_tasks.push_back(predict_task);\n  }\n  return std::make_pair(predict_tasks, feedback_tasks);\n}\n\nBanditPolicyState Exp4Policy::process_feedback(\n    BanditPolicyState state, Feedback feedback,\n    std::vector<Output> predictions) {\n  if (predictions.empty()) {  // Edge case\n    std::cout << \"No predictions, so can't update state.\" << std::endl;\n    return state;\n  }\n  // Update every individual model's distribution\n  for (auto p : predictions) {\n    // Compute loss and find which model to update\n    auto loss = std::abs(feedback.y_ - p.y_hat_);\n    auto model_id = p.models_used_.front();\n\n    // Update arm weight and weight_sum\n    auto s_i = state.model_map_[model_id][\"weight\"];\n    if (s_i != 0) {\n      double update = exp(-eta * loss / (s_i / state.weight_sum_));\n      state.model_map_[model_id][\"weight\"] *= update;\n      state.set_weight_sum(state.weight_sum_ - s_i +\n                           state.model_map_[model_id][\"weight\"]);\n    }\n  }\n  return state;\n}\n\nstd::string Exp4Policy::serialize_state(BanditPolicyState state) {\n  return state.serialize();\n}\n\nBanditPolicyState Exp4Policy::deserialize_state(const std::string& bytes) {\n  return BanditPolicyState::deserialize(bytes);\n}\n\nstd::string Exp4Policy::state_debug_string(const BanditPolicyState& state) {\n  return state.debug_string();\n}\n\n// ******************\n// * Epsilon Greedy *\n// ******************\n\nBanditPolicyState EpsilonGreedyPolicy::initialize(\n    const std::vector<VersionedModelId>& candidate_models_) {\n  BanditPolicyState state;\n  Map map(candidate_models_.size(), &versioned_model_hash);\n  for (VersionedModelId id : candidate_models_) {\n    ModelInfo info = {{\"expected_loss\", 0.0}, {\"times_selected\", 0.0}};\n    map.insert({id, info});\n  }\n  state.set_model_map(map);\n  return state;\n}\n\nBanditPolicyState EpsilonGreedyPolicy::add_models(\n    BanditPolicyState state, const std::vector<VersionedModelId>& new_models) {\n  // Calculate expected loss from old models\n  auto sum = 0.0;\n  for (auto model : state.model_map_) {\n    sum += model.second.at(\"expected_loss\");\n  }\n  auto avg = sum / state.model_map_.size();\n  // Add new model with average reward\n  for (auto id : new_models) {\n    ModelInfo info = {{\"expected_loss\", avg}, {\"times_selected\", 0.0}};\n    state.add_model(id, info);\n  }\n  return state;\n}\n\nVersionedModelId EpsilonGreedyPolicy::select(BanditPolicyState& state) {\n  // Helper function for selecting an arm based on lowest expected loss\n  VersionedModelId selected_model;\n  if (state.model_map_.empty()) {  // Edge case\n    std::cout << \"No models to select from.\" << std::endl;\n    return selected_model;\n  }\n  double rand_num = (double)rand() / RAND_MAX;\n  if (rand_num >= epsilon) {  // Select best model\n    auto min_loss = DBL_MAX;\n    for (auto id = state.model_map_.begin(); id != state.model_map_.end();\n         ++id) {\n      auto model_loss = id->second[\"expected_loss\"];\n      if (model_loss < min_loss) {\n        min_loss = model_loss;\n        selected_model = id->first;\n      }\n    }\n  } else {  // Randomly select\n    int rand_draw = rand() % state.model_map_.size();\n    auto random_it = next(begin(state.model_map_), rand_draw);\n    selected_model = random_it->first;\n  }\n\n  return selected_model;\n}\n\nstd::vector<PredictTask> EpsilonGreedyPolicy::select_predict_tasks(\n    BanditPolicyState& state, Query query, long query_id) {\n  auto selected_model = select(state);\n  auto task = PredictTask(query.input_, selected_model, 1.0, query_id,\n                          query.latency_micros_);\n  std::vector<PredictTask> tasks{task};\n  return tasks;\n}\n\nOutput EpsilonGreedyPolicy::combine_predictions(\n    BanditPolicyState state, Query query, std::vector<Output> predictions) {\n  return Exp3Policy::combine_predictions(state, query, predictions);\n}\n\nstd::pair<std::vector<PredictTask>, std::vector<FeedbackTask>>\nEpsilonGreedyPolicy::select_feedback_tasks(BanditPolicyState& state,\n                                           FeedbackQuery feedback,\n                                           long query_id) {\n  return Exp3Policy::select_feedback_tasks(state, feedback, query_id);\n}\n\nBanditPolicyState EpsilonGreedyPolicy::process_feedback(\n    BanditPolicyState state, Feedback feedback,\n    std::vector<Output> predictions) {\n  // Edge case\n  if (predictions.empty()) {\n    return state;\n  }\n  auto model_id = predictions.front().models_used_.front();\n  auto new_loss = std::abs(feedback.y_ - predictions.front().y_hat_);\n  // Update expected loss\n  int times = state.model_map_[model_id][\"times_selected\"];\n  state.model_map_[model_id][\"expected_loss\"] =\n      (state.model_map_[model_id][\"expected_loss\"] * times + new_loss) /\n      (times + 1);\n  // Update times selected\n  state.model_map_[model_id][\"times_selected\"] = times + 1;\n\n  return state;\n}\n\nstd::string EpsilonGreedyPolicy::serialize_state(BanditPolicyState state) {\n  return state.serialize();\n}\n\nBanditPolicyState EpsilonGreedyPolicy::deserialize_state(\n    const std::string& bytes) {\n  return BanditPolicyState::deserialize(bytes);\n}\n\nstd::string EpsilonGreedyPolicy::state_debug_string(\n    const BanditPolicyState& state) {\n  return state.debug_string();\n}\n\n// ********\n// * UCB1 *\n// ********\n\nBanditPolicyState UCBPolicy::initialize(\n    const std::vector<VersionedModelId>& candidate_models_) {\n  return EpsilonGreedyPolicy::initialize(candidate_models_);\n}\n\nBanditPolicyState UCBPolicy::add_models(\n    BanditPolicyState state, const std::vector<VersionedModelId>& new_models) {\n  return EpsilonGreedyPolicy::add_models(state, new_models);\n}\n\nVersionedModelId UCBPolicy::select(BanditPolicyState& state) {\n  // Helper function for selecting an arm based on lowest upper confidence bound\n  VersionedModelId selected_model;\n  if (state.model_map_.empty()) {  // Edge case\n    std::cout << \"No models to select from.\" << std::endl;\n  } else {\n    auto min_upper_bound = DBL_MAX;\n    for (auto id = state.model_map_.begin(); id != state.model_map_.end();\n         ++id) {\n      auto model_loss = id->second[\"expected_loss\"];\n      auto bound =\n          sqrt(2 * log(state.model_map_.size()) / id->second[\"times_selected\"]);\n      if (model_loss + bound < min_upper_bound) {\n        min_upper_bound = model_loss + bound;\n        selected_model = id->first;\n      }\n    }\n  }\n\n  return selected_model;\n}\n\nstd::vector<PredictTask> UCBPolicy::select_predict_tasks(\n    BanditPolicyState& state, Query query, long query_id) {\n  auto selected_model = select(state);\n  auto task = PredictTask(query.input_, selected_model, 1.0, query_id,\n                          query.latency_micros_);\n  std::vector<PredictTask> tasks{task};\n  return tasks;\n}\n\nOutput UCBPolicy::combine_predictions(BanditPolicyState state, Query query,\n                                      std::vector<Output> predictions) {\n  return Exp3Policy::combine_predictions(state, query, predictions);\n}\n\nstd::pair<std::vector<PredictTask>, std::vector<FeedbackTask>>\nUCBPolicy::select_feedback_tasks(BanditPolicyState& state,\n                                 FeedbackQuery feedback, long query_id) {\n  return Exp3Policy::select_feedback_tasks(state, feedback, query_id);\n}\n\nBanditPolicyState UCBPolicy::process_feedback(BanditPolicyState state,\n                                              Feedback feedback,\n                                              std::vector<Output> predictions) {\n  return EpsilonGreedyPolicy::process_feedback(state, feedback, predictions);\n}\n\nstd::string UCBPolicy::serialize_state(BanditPolicyState state) {\n  return state.serialize();\n}\n\nBanditPolicyState UCBPolicy::deserialize_state(const std::string& bytes) {\n  return BanditPolicyState::deserialize(bytes);\n}\n\nstd::string UCBPolicy::state_debug_string(const BanditPolicyState& state) {\n  return state.debug_string();\n}\n\n}  // namespace clipper\n", "meta": {"hexsha": "08863eca7c367fe1b1507b591c016bbe862cb627", "size": 15938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libclipper/src/selection_policies.cpp", "max_stars_repo_name": "jegonzal/clipper", "max_stars_repo_head_hexsha": "de3df520c6905bcd33a1c848afd0e9136155e87e", "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/libclipper/src/selection_policies.cpp", "max_issues_repo_name": "jegonzal/clipper", "max_issues_repo_head_hexsha": "de3df520c6905bcd33a1c848afd0e9136155e87e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libclipper/src/selection_policies.cpp", "max_forks_repo_name": "jegonzal/clipper", "max_forks_repo_head_hexsha": "de3df520c6905bcd33a1c848afd0e9136155e87e", "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.5265306122, "max_line_length": 80, "alphanum_fraction": 0.6837746267, "num_tokens": 3952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.02758527972857928, "lm_q1q2_score": 0.011865734935247178}}
{"text": "/*\n * Software License Agreement (Apache License)\n *\n * Copyright (c) 2021, Southwest Research Institute\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#pragma once\n\n#include <descartes_light/descartes_macros.h>\nDESCARTES_IGNORE_WARNINGS_PUSH\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <console_bridge/console.h>\n#include <omp.h>\nDESCARTES_IGNORE_WARNINGS_POP\n\n#include <descartes_light/solvers/bgl/bgl_ladder_graph_solver.h>\n#include <descartes_light/types.h>\n\n#define UNUSED(x) (void)(x)\n\nstatic void reportFailedEdges(const std::vector<std::size_t>& indices)\n{\n  if (indices.empty())\n    CONSOLE_BRIDGE_logInform(\"No failed edges\");\n  else\n  {\n    std::stringstream ss;\n    ss << \"Failed edges:\\n\";\n    for (const auto& i : indices)\n      ss << \"\\t\" << i << \"\\n\";\n\n    CONSOLE_BRIDGE_logWarn(ss.str().c_str());\n  }\n}\n\nstatic void reportFailedVertices(const std::vector<std::size_t>& indices)\n{\n  if (indices.empty())\n    CONSOLE_BRIDGE_logInform(\"No failed vertices\");\n  else\n  {\n    std::stringstream ss;\n    ss << \"Failed vertices:\\n\";\n    for (const auto& i : indices)\n      ss << \"\\t\" << i << \"\\n\";\n\n    CONSOLE_BRIDGE_logWarn(ss.str().c_str());\n  }\n}\n\nnamespace descartes_light\n{\ntemplate <typename FloatType>\nBGLLadderGraphSolver<FloatType>::BGLLadderGraphSolver(unsigned num_threads) : num_threads_{ num_threads } {};\n\ntemplate <typename FloatType>\nBuildStatus BGLLadderGraphSolver<FloatType>::buildImpl(\n    const std::vector<typename WaypointSampler<FloatType>::ConstPtr>& trajectory,\n    const std::vector<typename EdgeEvaluator<FloatType>::ConstPtr>& edge_evaluators,\n    const std::vector<typename StateEvaluator<FloatType>::ConstPtr>& state_evaluators)\n{\n  BuildStatus status;\n\n  // Build Vertices\n  ladder_rungs_.resize(trajectory.size());\n  long cnt = 0;\n\n  using Clock = std::chrono::high_resolution_clock;\n  std::chrono::time_point<Clock> start_time = Clock::now();\n#pragma omp parallel for num_threads(num_threads_)\n  for (long i = 0; i < static_cast<long>(trajectory.size()); ++i)\n  {\n    std::vector<StateSample<FloatType>> samples = trajectory[static_cast<size_t>(i)]->sample();\n    if (!samples.empty())\n    {\n      for (StateSample<FloatType>& sample : samples)\n      {\n        VertexDesc<FloatType> vd;\n        if (state_evaluators.empty())\n        {\n          vd = add_vertex(sample, graph_);\n          ladder_rungs_[static_cast<size_t>(i)].push_back(vd);\n        }\n        else\n        {\n          std::pair<bool, FloatType> results = state_evaluators[static_cast<size_t>(i)]->evaluate(*sample.state);\n          if (results.first)\n          {\n            sample.cost += results.second;\n            vd = add_vertex(sample, graph_);\n            ladder_rungs_[static_cast<size_t>(i)].push_back(vd);\n          }\n        }\n      }\n    }\n    else\n    {\n#pragma omp critical\n      {\n        status.failed_vertices.push_back(static_cast<size_t>(i));\n      }\n    }\n#ifndef NDEBUG\n#pragma omp critical\n    {\n      ++cnt;\n      std::stringstream ss;\n      ss << \"Descartes Processed: \" << cnt << \" of \" << trajectory.size() << \" vertices\";\n      CONSOLE_BRIDGE_logInform(ss.str().c_str());\n    }\n#endif\n  }\n  double duration = std::chrono::duration<double>(Clock::now() - start_time).count();\n  CONSOLE_BRIDGE_logDebug(\"Descartes took %0.4f seconds to build vertices.\", duration);\n\n  // Build Edges\n  cnt = 0;\n  start_time = Clock::now();\n#pragma omp parallel for num_threads(num_threads_)\n  for (long i = 1; i < static_cast<long>(trajectory.size()); ++i)\n  {\n    auto& from = ladder_rungs_[static_cast<size_t>(i) - 1];\n    const auto& to = ladder_rungs_[static_cast<size_t>(i)];\n\n    bool found = false;\n    for (long j = 0; j < static_cast<long>(from.size()); ++j)\n    {\n      StateSample<FloatType> from_sample = graph_[from[static_cast<size_t>(j)]];\n      for (long k = 0; k < static_cast<long>(to.size()); ++k)\n      {\n        // Consider the edge:\n        StateSample<FloatType> to_sample = graph_[to[static_cast<size_t>(k)]];\n        std::pair<bool, FloatType> results =\n            edge_evaluators[static_cast<size_t>(i - 1)]->evaluate(*from_sample.state, *to_sample.state);\n        if (results.first)\n        {\n          found = true;\n          if (i == 1)\n          {\n            // first edge captures first rung weights\n            boost::add_edge(from[static_cast<size_t>(j)],\n                            to[static_cast<size_t>(k)],\n                            from_sample.cost + results.second + to_sample.cost,\n                            graph_);\n          }\n          else\n          {\n            boost::add_edge(\n                from[static_cast<size_t>(j)], to[static_cast<size_t>(k)], results.second + to_sample.cost, graph_);\n          }\n        }\n      }\n    }  // node loop\n\n    if (!found)\n    {\n#pragma omp critical\n      {\n        status.failed_edges.push_back(static_cast<size_t>(i) - 1);\n      }\n    }\n#ifndef NDEBUG\n#pragma omp critical\n    {\n      ++cnt;\n      std::stringstream ss;\n      ss << \"Descartes Processed: \" << cnt << \" of \" << (trajectory.size() - 1) << \" edges\";\n      CONSOLE_BRIDGE_logInform(ss.str().c_str());\n    }\n#endif\n  }  // rung loop\n  UNUSED(cnt);\n  duration = std::chrono::duration<double>(Clock::now() - start_time).count();\n  CONSOLE_BRIDGE_logDebug(\"Descartes took %0.4f seconds to build edges.\", duration);\n\n  // Create a zero-value, zero-cost start node and connect it with a zero-cost edge to each node in the first rung\n  {\n    auto arr = std::make_shared<State<FloatType>>();\n    StateSample<FloatType> start_sample = StateSample<FloatType>{ arr, static_cast<FloatType>(0.0) };\n    source_ = add_vertex(start_sample, graph_);\n    for (const VertexDesc<FloatType>& target : ladder_rungs_[0])\n    {\n      boost::add_edge(source_, target, static_cast<FloatType>(0.0), graph_);\n    }\n  }\n\n  std::sort(status.failed_vertices.begin(), status.failed_vertices.end());\n  std::sort(status.failed_edges.begin(), status.failed_edges.end());\n\n  // todo: move these to a utilites function\n  reportFailedVertices(status.failed_vertices);\n  reportFailedEdges(status.failed_edges);\n\n  if (!status)\n  {\n    CONSOLE_BRIDGE_logError(\"LadderGraphSolver failed to build graph.\");\n  }\n\n  return status;\n}\n\ntemplate <typename FloatType>\nstd::vector<typename State<FloatType>::ConstPtr> BGLLadderGraphSolver<FloatType>::reconstructPath(\n    const VertexDesc<FloatType>& source,\n    const VertexDesc<FloatType>& target,\n    const std::map<VertexDesc<FloatType>, VertexDesc<FloatType>>& predecessor_map) const\n{\n  // Reconstruct the path from predecessors\n  std::vector<typename State<FloatType>::ConstPtr> path;\n\n  VertexDesc<FloatType> v = target;\n  path.push_back(graph_[v].state);\n\n  for (VertexDesc<FloatType> u = predecessor_map.at(v); u != v; v = u, u = predecessor_map.at(v))\n  {\n    path.push_back(graph_[u].state);\n  }\n  std::reverse(path.begin(), path.end());\n\n  // Check that the last traversed vertex is the source vertex\n  if (v != source)\n    throw std::runtime_error(\"Failed to find path through the graph\");\n\n  return path;\n}\n\ntemplate <typename FloatType>\nSearchResult<FloatType> BGLLadderGraphSolver<FloatType>::search()\n{\n  SearchResult<FloatType> result;\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\n  result.cost = std::numeric_limits<FloatType>::max();\n  result.trajectory = {};\n\n  std::map<VertexDesc<FloatType>, VertexDesc<FloatType>> predecessor_map;\n  boost::associative_property_map<std::map<VertexDesc<FloatType>, VertexDesc<FloatType>>> predecessor_prop_map(\n      predecessor_map);\n\n  std::map<VertexDesc<FloatType>, FloatType> distance_map;\n  boost::associative_property_map<std::map<VertexDesc<FloatType>, FloatType>> distance_prop_map(distance_map);\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\n  // Find lowest cost node in last rung\n  auto target = std::min_element(ladder_rungs_.back().begin(),\n                                 ladder_rungs_.back().end(),\n                                 [&distance_map](const VertexDesc<FloatType>& a, const VertexDesc<FloatType>& b) {\n                                   return distance_map.at(a) < distance_map.at(b);\n                                 });\n\n  // Reconstruct the path from the predecesor map; remove the artificial start state\n  result.trajectory = reconstructPath(source_, *target, predecessor_map);\n  result.trajectory.erase(result.trajectory.begin());\n\n  result.cost = distance_map.at(*target);\n\n  return result;\n}\n\n}  // namespace descartes_light\n", "meta": {"hexsha": "ca3696dddf6bdd7d01c9f4334e40d7842fa98da0", "size": 9576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "descartes_light/solvers/include/descartes_light/solvers/bgl/impl/bgl_ladder_graph_solver.hpp", "max_stars_repo_name": "jrgnicho/descartes_light", "max_stars_repo_head_hexsha": "16bbc4254af028bffee20361145b106fb7db2b2c", "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_ladder_graph_solver.hpp", "max_issues_repo_name": "jrgnicho/descartes_light", "max_issues_repo_head_hexsha": "16bbc4254af028bffee20361145b106fb7db2b2c", "max_issues_repo_licenses": ["Apache-2.0"], "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_ladder_graph_solver.hpp", "max_forks_repo_name": "jrgnicho/descartes_light", "max_forks_repo_head_hexsha": "16bbc4254af028bffee20361145b106fb7db2b2c", "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.6, "max_line_length": 115, "alphanum_fraction": 0.6410818713, "num_tokens": 2246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.03021459045126771, "lm_q1q2_score": 0.011854297071805015}}
{"text": "// Copyright (C) 2019  Rhys Mainwaring\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 <https://www.gnu.org/licenses/>.\n\n#include \"asv_wave_sim_gazebo_plugins/Wavefield.hh\"\n#include \"asv_wave_sim_gazebo_plugins/CGALTypes.hh\"\n#include \"asv_wave_sim_gazebo_plugins/Convert.hh\"\n#include \"asv_wave_sim_gazebo_plugins/Geometry.hh\"\n#include \"asv_wave_sim_gazebo_plugins/Grid.hh\"\n#include \"asv_wave_sim_gazebo_plugins/Physics.hh\"\n#include \"asv_wave_sim_gazebo_plugins/Utilities.hh\"\n\n#include <CGAL/Aff_transformation_3.h>\n#include <CGAL/number_utils.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Timer.h>\n\n#include <Eigen/Dense>\n\n#include <gazebo/gazebo.hh>\n#include <gazebo/common/common.hh>\n#include <gazebo/msgs/msgs.hh>\n\n#include <ignition/math/Pose3.hh>\n#include <ignition/math/Vector2.hh>\n#include <ignition/math/Vector3.hh>\n\n#include <tbb/tbb.h>\n\n#include <array>\n#include <iostream>\n#include <cmath>\n#include <string>\n\nnamespace asv \n{\n  typedef CGAL::Aff_transformation_2<Kernel> TransformMatrix;\n\n///////////////////////////////////////////////////////////////////////////////\n// Utilities\n\n  std::ostream& operator<<(std::ostream& os, const std::vector<double>& _vec)\n  { \n    for (auto&& v : _vec )\n      os << v << \", \";\n    return os;\n  }\n\n///////////////////////////////////////////////////////////////////////////////\n// WaveParametersPrivate\n\n  /// \\internal\n  /// \\brief Private data for the WavefieldParameters.\n  class WaveParametersPrivate\n  {\n    /// \\brief Constructor.\n    public: WaveParametersPrivate():\n      number(1), \n      scale(2.0),\n      angle(2.0*M_PI/10.0),\n      steepness(1.0),\n      amplitude(0.0), \n      period(1.0), \n      phase(0.0), \n      direction(1, 0),\n      angularFrequency(2.0*M_PI),\n      wavelength(2*M_PI/Physics::DeepWaterDispersionToWavenumber(2.0*M_PI)), \n      wavenumber(Physics::DeepWaterDispersionToWavenumber(2.0*M_PI))\n    {\n    }\n\n    /// \\brief The number of component waves.\n    public: size_t number;\n\n    /// \\brief Set the scale of the largest and smallest waves. \n    public: double scale;\n\n    /// \\brief Set the angle between component waves and the mean direction.\n    public: double angle;\n\n    /// \\brief Control the wave steepness. 0 is sine waves, 1 is Gerstner waves.\n    public: double steepness;\n\n    /// \\brief The mean wave amplitude [m].\n    public: double amplitude;\n\n    /// \\brief The mean wave period [s]\n    public: double period;\n\n    /// \\brief The mean wve phase (not currently enabled).\n    public: double phase;\n\n    /// \\brief The mean wave direction.\n    public: Vector2 direction;\n\n    /// \\brief The mean wave angular frequency (derived).    \n    public: double angularFrequency;\n\n    /// \\brief The mean wavelength (derived).\n    public: double wavelength;\n\n    /// \\brief The mean wavenumber (derived).\n    public: double wavenumber;\n  \n    /// \\brief The component wave angular frequencies (derived).\n    public: std::vector<double> angularFrequencies;\n\n    /// \\brief The component wave amplitudes (derived).\n    public: std::vector<double> amplitudes;\n\n    /// \\brief The component wave phases (derived).\n    public: std::vector<double> phases;\n\n    /// \\brief The component wave steepness factors (derived).\n    public: std::vector<double> steepnesses;\n\n    /// \\brief The component wavenumbers (derived).\n    public: std::vector<double> wavenumbers;\n\n    /// \\brief The component wave dirctions (derived).\n    public: std::vector<Vector2> directions;\n\n    /// \\brief Recalculate all derived quantities from inputs.\n    public: void Recalculate()\n    {\n      // Normalize direction\n      this->direction = Geometry::Normalize(this->direction);\n\n      // Derived mean values\n      this->angularFrequency = 2.0 * M_PI / this->period;\n      this->wavenumber = Physics::DeepWaterDispersionToWavenumber(this->angularFrequency);\n      this->wavelength = 2.0 * M_PI / this->wavenumber;\n\n      // Update components\n      this->angularFrequencies.clear();\n      this->amplitudes.clear();\n      this->phases.clear();\n      this->wavenumbers.clear();\n      this->steepnesses.clear();\n      this->directions.clear();\n\n      for (size_t i=0; i<this->number; ++i)\n      {\n        const int n = i - this->number/2;\n        const double scaleFactor = std::pow(this->scale, n);\n        const double a = scaleFactor * this->amplitude;\n        const double k = this->wavenumber / scaleFactor;\n        const double omega = Physics::DeepWaterDispersionToOmega(k);\n        const double phi = this->phase;\n        double q = 0.0;\n        if (a != 0)\n        {\n          q = std::min(1.0, this->steepness / (a * k * this->number));\n        }\n\n        this->amplitudes.push_back(a);        \n        this->angularFrequencies.push_back(omega);\n        this->phases.push_back(phi);\n        this->steepnesses.push_back(q);\n        this->wavenumbers.push_back(k);\n      \n        // Direction\n        const double c = std::cos(n * this->angle);\n        const double s = std::sin(n * this->angle);\n        const TransformMatrix T(\n          c, -s,\n          s,  c\n        );\n        const Vector2 d = T(this->direction);\n        directions.push_back(d);\n      }\n    }\n  };\n\n///////////////////////////////////////////////////////////////////////////////\n// WaveParameters\n\n  WaveParameters::~WaveParameters()\n  {\n  }\n\n  WaveParameters::WaveParameters()\n    : data(new WaveParametersPrivate())\n  {\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::FillMsg(gazebo::msgs::Param_V& _msg) const\n  {\n    // Clear \n    _msg.mutable_param()->Clear();\n\n    // \"number\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"number\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::INT32);\n      nextParam->mutable_value()->set_int_value(this->data->number);\n    }\n    // \"scale\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"scale\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->scale);\n    }\n    // \"angle\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"angle\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->angle);\n    }\n    // \"steepness\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"steepness\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->steepness);\n    }\n    // \"amplitude\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"amplitude\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->amplitude);\n    }\n    // \"period\"\n    {\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"period\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::DOUBLE);\n      nextParam->mutable_value()->set_double_value(this->data->period);\n    }\n    // \"direction\"\n    {\n      const auto& direction = this->data->direction;\n      auto nextParam = _msg.add_param();\n      nextParam->set_name(\"direction\");\n      nextParam->mutable_value()->set_type(gazebo::msgs::Any::VECTOR3D);\n      nextParam->mutable_value()->mutable_vector3d_value()->set_x(direction.x());\n      nextParam->mutable_value()->mutable_vector3d_value()->set_y(direction.y());\n      nextParam->mutable_value()->mutable_vector3d_value()->set_z(0);\n    }\n  }\n\n  void WaveParameters::SetFromMsg(const gazebo::msgs::Param_V& _msg)\n  {\n    this->data->number    = Utilities::MsgParamSizeT(_msg,    \"number\",     this->data->number);\n    this->data->amplitude = Utilities::MsgParamDouble(_msg,   \"amplitude\",  this->data->amplitude);\n    this->data->period    = Utilities::MsgParamDouble(_msg,   \"period\",     this->data->period);\n    this->data->phase     = Utilities::MsgParamDouble(_msg,   \"phase\",      this->data->phase);\n    this->data->direction = Utilities::MsgParamVector2(_msg,  \"direction\",  this->data->direction);\n    this->data->scale     = Utilities::MsgParamDouble(_msg,   \"scale\",      this->data->scale);\n    this->data->angle     = Utilities::MsgParamDouble(_msg,   \"angle\",      this->data->angle);\n    this->data->steepness = Utilities::MsgParamDouble(_msg,   \"steepness\",  this->data->steepness);\n\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetFromSDF(sdf::Element& _sdf)\n  {\n    this->data->number    = Utilities::SdfParamSizeT(_sdf,    \"number\",     this->data->number);\n    this->data->amplitude = Utilities::SdfParamDouble(_sdf,   \"amplitude\",  this->data->amplitude);\n    this->data->period    = Utilities::SdfParamDouble(_sdf,   \"period\",     this->data->period);\n    this->data->phase     = Utilities::SdfParamDouble(_sdf,   \"phase\",      this->data->phase);\n    this->data->direction = Utilities::SdfParamVector2(_sdf,  \"direction\",  this->data->direction);\n    this->data->scale     = Utilities::SdfParamDouble(_sdf,   \"scale\",      this->data->scale);\n    this->data->angle     = Utilities::SdfParamDouble(_sdf,   \"angle\",      this->data->angle);\n    this->data->steepness = Utilities::SdfParamDouble(_sdf,   \"steepness\",  this->data->steepness);\n\n    this->data->Recalculate();\n  }\n\n  size_t WaveParameters::Number() const\n  {\n    return this->data->number;\n  }\n\n  double WaveParameters::Angle() const\n  {\n    return this->data->angle;\n  }\n\n  double WaveParameters::Scale() const\n  {\n    return this->data->scale;\n  }\n\n  double WaveParameters::Steepness() const\n  {\n    return this->data->steepness;\n  }\n\n  double WaveParameters::AngularFrequency() const\n  {\n    return this->data->angularFrequency;\n  }\n\n  double WaveParameters::Amplitude() const\n  {\n    return this->data->amplitude;\n  }\n  \n  double WaveParameters::Period() const\n  {\n    return this->data->period;\n  }\n  \n  double WaveParameters::Phase() const\n  {\n    return this->data->phase;\n  }\n\n  double WaveParameters::Wavelength() const\n  {\n    return this->data->wavelength;\n  }\n\n  double WaveParameters::Wavenumber() const\n  {\n    return this->data->wavenumber;\n  }    \n\n  Vector2 WaveParameters::Direction() const\n  {\n    return this->data->direction;\n  }\n  \n  void WaveParameters::SetNumber(size_t _number)\n  {\n    this->data->number = _number;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetAngle(double _angle)\n  {\n    this->data->angle = _angle;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetScale(double _scale)\n  {\n    this->data->scale = _scale;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetSteepness(double _steepness)\n  {\n    this->data->steepness = _steepness;\n    this->data->Recalculate();\n  }\n\n  void WaveParameters::SetAmplitude(double _amplitude)\n  {\n    this->data->amplitude = _amplitude;\n    this->data->Recalculate();\n  }\n  \n  void WaveParameters::SetPeriod(double _period)\n  {\n    this->data->period = _period;\n    this->data->Recalculate();\n  }\n    \n  void WaveParameters::SetPhase(double _phase)\n  {\n    this->data->phase = _phase;\n    this->data->Recalculate();\n  }\n  \n  void WaveParameters::SetDirection(const Vector2& _direction)\n  {\n    this->data->direction = _direction;\n    this->data->Recalculate();\n  }\n\n  const std::vector<double>& WaveParameters::AngularFrequency_V() const\n  {\n    return this->data->angularFrequencies;\n  }\n\n  const std::vector<double>& WaveParameters::Amplitude_V() const\n  {\n    return this->data->amplitudes;\n  }\n  \n  const std::vector<double>& WaveParameters::Phase_V() const\n  {\n    return this->data->phases;\n  }\n  \n  const std::vector<double>& WaveParameters::Steepness_V() const\n  {\n    return this->data->steepnesses;\n  }\n\n  const std::vector<double>& WaveParameters::Wavenumber_V() const\n  {\n    return this->data->wavenumbers;\n  }\n\n  const std::vector<Vector2>& WaveParameters::Direction_V() const\n  {\n    return this->data->directions;\n  }\n \n  void WaveParameters::DebugPrint() const\n  {\n    gzmsg << \"number:     \" << this->data->number << std::endl;\n    gzmsg << \"scale:      \" << this->data->scale << std::endl;\n    gzmsg << \"angle:      \" << this->data->angle << std::endl;\n    gzmsg << \"period:     \" << this->data->period << std::endl;\n    gzmsg << \"amplitude:  \" << this->data->amplitudes << std::endl;\n    gzmsg << \"wavenumber: \" << this->data->wavenumbers << std::endl;\n    gzmsg << \"omega:      \" << this->data->angularFrequencies << std::endl;\n    gzmsg << \"phase:      \" << this->data->phases << std::endl;\n    gzmsg << \"steepness:  \" << this->data->steepnesses << std::endl;\n    for (auto&& d : this->data->directions)\n    {\n      gzmsg << \"direction:  \" << d << std::endl;\n    }\n  }\n\n///////////////////////////////////////////////////////////////////////////////\n// WavefieldPrivate\n\n  /// \\internal\n  /// \\brief Private data for the WavefieldParameters.\n  class WavefieldPrivate\n  {\n    /// \\brief Constructor.\n    public: WavefieldPrivate() :\n      params(new WaveParameters()),\n      size({ 1000, 1000 }),\n      cellCount({ 50, 50 })\n      // isDirty(false)\n    {\n    }\n\n    /// \\brief Constructor.\n    ///\n    /// \\brief param[in] _size      The dimensions of the wave field [m].\n    /// \\brief param[in] _cellCount The number of cells in each direction.\n    public: WavefieldPrivate(\n      const std::array<double, 2>& _size,\n      const std::array<size_t, 2>& _cellCount \n    ) :\n      params(new WaveParameters()),\n      size(_size),\n      cellCount(_cellCount)\n      // isDirty(false)\n    {\n    }\n\n    /// \\brief Wave parameters\n    public: std::shared_ptr<WaveParameters> params;\n\n    /// brief The dimensions of the wave field in each direction [m].    \n    public: std::array<double, 2> size;\n\n    /// \\brief The number of grid cells in each direction.\n    public: std::array<size_t, 2> cellCount;\n\n    /// \\brief The initial wave field mesh. This is a triangulated regular grid.\n    public: std::shared_ptr<const Grid> initialGrid;\n\n    /// \\brief The current position of the wave field.\n    public: std::shared_ptr<Grid> grid;\n    \n    /// \\brief Retain the Gazebo mesh as it's required to update visuals.\n    // public: std::string name;\n    // public: std::shared_ptr<gazebo::common::Mesh> gzMesh;\n    // public: gazebo::common::SubMesh* gzSubMesh;\n    // public: bool isDirty;\n  };\n\n///////////////////////////////////////////////////////////////////////////////\n// Wavefield\n\n  Wavefield::~Wavefield()\n  {\n  }\n\n  Wavefield::Wavefield(\n    const std::string& _name) : \n    data(new WavefieldPrivate())\n  {\n    // Grid\n    this->data->initialGrid.reset(new Grid(\n      this->data->size, this->data->cellCount));\n    this->data->grid.reset(new Grid(\n      this->data->size, this->data->cellCount));\n    \n    // GzMesh\n    // this->data->name = _name;\n    // this->data->gzMesh = std::make_shared<gazebo::common::Mesh>();\n    // this->InitGzMesh();\n\n    // Update\n    this->Update(0.0);\n  }\n\n  Wavefield::Wavefield(\n    const std::string& _name,\n    const std::array<double, 2>& _size,\n    const std::array<size_t, 2>& _cellCount) : \n    data(new WavefieldPrivate(_size, _cellCount))\n  {\n    // Grid\n    this->data->initialGrid.reset(new Grid(\n      this->data->size, this->data->cellCount));\n    this->data->grid.reset(new Grid(\n      this->data->size, this->data->cellCount));\n    \n    // GzMesh\n    // this->data->name = _name;\n    // this->data->gzMesh = std::make_shared<gazebo::common::Mesh>();\n    // this->InitGzMesh();\n\n    // Update\n    this->Update(0.0);\n  }\n\n  std::shared_ptr<const Mesh> Wavefield::GetMesh() const\n  {\n    return this->data->grid->GetMesh();\n  }\n\n  std::shared_ptr<const Grid> Wavefield::GetGrid() const\n  {\n    return this->data->grid;\n  }\n\n  // std::shared_ptr<const gazebo::common::Mesh> Wavefield::GetGzMesh() const\n  // {\n  //   this->LazyUpdateGzMesh();\n  //   return this->data->gzMesh;\n  // }\n\n  std::shared_ptr<const WaveParameters> Wavefield::GetParameters() const\n  {\n    return this->data->params;\n  }\n\n  void Wavefield::SetParameters(std::shared_ptr<WaveParameters> _params) const\n  {\n    GZ_ASSERT(_params != nullptr, \"Invalid parameter _params\");\n    this->data->params = _params;    \n  }\n\n  void Wavefield::Update(double _time)\n  {\n    this->UpdateGerstnerWave(_time);\n  \n    // this->data->isDirty = true;\n  }\n\n  void Wavefield::UpdateGerstnerWave(double _time)\n  {\n    // Single wave params\n    // auto amplitude  = this->data->params->Amplitude();\n    // auto wavenumber = this->data->params->Wavenumber();\n    // auto omega      = this->data->params->AngularFrequency();\n    // auto phase      = this->data->params->Phase();\n    // auto q          = this->data->params->Steepness();\n    // auto direction  = this->data->params->Direction();\n\n    // Multiple wave params\n    const auto  number     = this->data->params->Number();\n    const auto& amplitude  = this->data->params->Amplitude_V();\n    const auto& wavenumber = this->data->params->Wavenumber_V();\n    const auto& omega      = this->data->params->AngularFrequency_V();\n    const auto& phase      = this->data->params->Phase_V();\n    const auto& q          = this->data->params->Steepness_V();\n    const auto& direction  = this->data->params->Direction_V();\n\n    const auto& initMesh = *this->data->initialGrid->GetMesh();\n    auto& mesh = *this->data->grid->GetMesh();\n\n    // Reset points to original positions\n    for (\n      auto&& it = std::make_pair(std::begin(initMesh.vertices()), std::begin(mesh.vertices()));\n      it.first != std::end(initMesh.vertices()) && it.second != std::end(mesh.vertices());\n      ++it.first, ++it.second)\n    {\n      auto& vtx0 = *it.first;\n      auto& vtx1 = *it.second;\n      mesh.point(vtx1) = initMesh.point(vtx0);\n    }\n    \n    // Multiple wave update \n    for (size_t i=0; i<number; ++i)\n    // size_t i = 2;\n    {        \n      const auto& amplitude_i = amplitude[i];\n      const auto& wavenumber_i = wavenumber[i];\n      const auto& omega_i = omega[i];\n      const auto& phase_i = phase[i];\n      const auto& direction_i = direction[i];\n      const auto& q_i = q[i];\n\n      for (\n        auto&& it = std::make_pair(std::begin(initMesh.vertices()), std::begin(mesh.vertices()));\n        it.first != std::end(initMesh.vertices()) && it.second != std::end(mesh.vertices());\n        ++it.first, ++it.second)\n      {\n        auto& vtx0 = *it.first;\n        auto& vtx1 = *it.second;\n\n        const Point3& p0 = initMesh.point(vtx0);\n        Vector2 v0(p0.x(), p0.y()); // - CGAL::ORIGIN;        \n\n        // Multiple waves\n        const double angle  = CGAL::to_double(direction_i * v0) * wavenumber_i - omega_i * _time + phase_i;\n        const double s = std::sin(angle);\n        const double c = std::cos(angle);\n        Vector3 v1(\n          - direction_i.x() * q_i * amplitude_i * s,\n          - direction_i.y() * q_i * amplitude_i * s,\n          + amplitude_i * c\n        );\n\n        mesh.point(vtx1) += v1;\n      }\n    }\n\n    // Single wave update \n    // for (\n    //   auto&& it = std::make_pair(std::begin(initMesh.vertices()), std::begin(mesh.vertices()));\n    //   it.first != std::end(initMesh.vertices()) && it.second != std::end(mesh.vertices());\n    //   ++it.first, ++it.second)\n    // {\n    //   auto& vtx0 = *it.first;\n    //   auto& vtx1 = *it.second;\n\n    //   const Point3& p0 = initMesh.point(vtx0);\n    //   Vector3 v0 = p0 - CGAL::ORIGIN;\n    //   Vector3 v1 = CGAL::NULL_VECTOR;\n\n    //   auto prj    = direction * v0;\n    //   double ang  = CGAL::to_double(prj) * wavenumber - omega * _time + phase;\n    //   double sang = std::sin(ang);\n    //   double cang = std::cos(ang);\n    //   v1 += Vector3(\n    //     - direction.x() * q * amplitude * sang,\n    //     - direction.y() * q * amplitude * sang,\n    //     + amplitude * cang\n    //   );\n      \n    //   mesh.point(vtx1) = p0 + v1;\n    // }\n  \n  }\n\n  // void Wavefield::InitGzMesh()\n  // {\n  //   auto& grid = *this->data->grid;\n  //   auto& mesh = *grid.GetMesh();\n\n  //   // Update Normals\n  //   grid.RecalculateNormals();\n\n  //   // Make GzMesh\n  //   auto& name = this->data->name;\n  //   this->data->gzMesh.reset(new gazebo::common::Mesh());\n  //   this->data->gzMesh->SetName(name);\n\n  //   const double Lx = this->data->size[0];\n  //   const double Ly = this->data->size[1];\n\n  //   // Create the submesh and retain a pointer \n  //   std::unique_ptr<gazebo::common::SubMesh> gzSubMesh(new gazebo::common::SubMesh());\n  //   this->data->gzSubMesh = gzSubMesh.get();\n\n  //   size_t iv = 0;\n  //   size_t it = 0;\n  //   for(auto&& face : mesh.faces())\n  //   {\n  //     Triangle tri  = Geometry::MakeTriangle(mesh, face);\n  //     auto& normal = grid.GetNormal(it++);\n\n  //     ignition::math::Vector3d ignP0(ToIgn(tri[0]));\n  //     ignition::math::Vector3d ignP1(ToIgn(tri[1]));\n  //     ignition::math::Vector3d ignP2(ToIgn(tri[2]));\n  //     ignition::math::Vector3d ignNormal(ToIgn(normal));\n\n  //     // Vertices\n  //     gzSubMesh->AddVertex(ignP0);\n  //     gzSubMesh->AddVertex(ignP1);\n  //     gzSubMesh->AddVertex(ignP2);\n\n  //     // Vertex normals\n  //     gzSubMesh->AddNormal(ignNormal);\n  //     gzSubMesh->AddNormal(ignNormal);\n  //     gzSubMesh->AddNormal(ignNormal);\n\n  //     // Face\n  //     gzSubMesh->AddIndex(iv++);\n  //     gzSubMesh->AddIndex(iv++);\n  //     gzSubMesh->AddIndex(iv++);\n\n  //     // Vertex texture coordinates\n  //     gzSubMesh->AddTexCoord(0.5 + ignP0.X()/Lx, 0.5 - ignP0.Y()/Ly);\n  //     gzSubMesh->AddTexCoord(0.5 + ignP1.X()/Lx, 0.5 - ignP1.Y()/Ly);\n  //     gzSubMesh->AddTexCoord(0.5 + ignP2.X()/Lx, 0.5 - ignP2.Y()/Ly);\n  //   }\n\n  //   this->data->gzMesh->AddSubMesh(gzSubMesh.release());      \n  // }\n\n  // void Wavefield::LazyUpdateGzMesh() const\n  // {\n  //   // Update the Gazebo mesh vertices\n  //   if (this->data->isDirty)\n  //   {\n  //     auto& grid = *this->data->grid;\n  //     auto& mesh = *grid.GetMesh();\n  //     auto& gzSubMesh = *this->data->gzSubMesh;\n\n  //     // Update Normals\n  //     grid.RecalculateNormals();\n\n  //     // Update GzMesh\n  //     size_t iv = 0;\n  //     size_t it = 0;\n  //     for(auto&& face : mesh.faces())\n  //     {\n  //       Triangle tri  = Geometry::MakeTriangle(mesh, face);\n  //       auto& normal = grid.GetNormal(it++);\n\n  //       ignition::math::Vector3d ignP0(ToIgn(tri[0]));\n  //       ignition::math::Vector3d ignP1(ToIgn(tri[1]));\n  //       ignition::math::Vector3d ignP2(ToIgn(tri[2]));\n  //       ignition::math::Vector3d ignNormal(ToIgn(normal));\n\n  //       // Update Vertices and Normals\n  //       gzSubMesh.SetVertex(iv, ignP0);\n  //       gzSubMesh.SetNormal(iv++, ignNormal);\n\n  //       gzSubMesh.SetVertex(iv, ignP1);\n  //       gzSubMesh.SetNormal(iv++, ignNormal);\n\n  //       gzSubMesh.SetVertex(iv, ignP2);\n  //       gzSubMesh.SetNormal(iv++, ignNormal);\n  //     }\n  //     this->data->isDirty = false;\n  //   }\n  // }\n\n///////////////////////////////////////////////////////////////////////////////    \n// WavefieldSamplerPrivate\n\n  /// \\internal\n  /// \\brief Private data for the WavefieldSampler.\n  class WavefieldSamplerPrivate\n  {\n    /// \\brief The wavefield grid.\n    public: std::shared_ptr<const Wavefield> wavefield;\n\n    /// \\brief A sample of the wavefield. This copy is located at the initial pose. \n    public: std::shared_ptr<const Grid> initWaterPatch;\n\n    /// \\brief A sample of the wavefield. This copy is updated.\n    public: std::shared_ptr<Grid> waterPatch;    \n  };\n\n///////////////////////////////////////////////////////////////////////////////    \n// WavefieldSampler\n\n  WavefieldSampler::~WavefieldSampler()\n  {        \n  }\n\n  WavefieldSampler::WavefieldSampler(\n    std::shared_ptr<const Wavefield> _wavefield,\n    std::shared_ptr<const Grid> _waterPatch\n  ) : data(new WavefieldSamplerPrivate())\n  {\n    this->data->wavefield = _wavefield;\n    this->data->initWaterPatch = _waterPatch;\n    this->data->waterPatch.reset(new Grid(*_waterPatch));\n  }\n\n  std::shared_ptr<const Grid> WavefieldSampler::GetWaterPatch() const\n  {\n    return this->data->waterPatch;\n  }\n\n  void WavefieldSampler::ApplyPose(const ignition::math::Pose3d& _pose)\n  {\n    // @TODO_FRAGILE - Move to Grid as changing internal state \n    // Apply pose to center\n    const Point3& c0 = this->data->initWaterPatch->GetCenter();\n    Point3 c1(c0.x() + _pose.Pos().X(), c0.y() + _pose.Pos().Y(), c0.z());\n    this->data->waterPatch->SetCenter(c1);\n\n    // Iterate over vertices\n    auto& source = *this->data->initWaterPatch->GetMesh();\n    auto& target = *this->data->waterPatch->GetMesh();\n    for (\n      auto&& it = std::make_pair(std::begin(source.vertices()), std::begin(target.vertices()));\n      it.first != std::end(source.vertices()) && it.second != std::end(target.vertices());\n      ++it.first, ++it.second)\n    {\n      auto& v0 = *it.first;\n      auto& v1 = *it.second;\n      const Point3& p0 = source.point(v0);\n\n      // Transformation: slide the patch in the xy - plane only\n      Point3 p1(p0.x() + _pose.Pos().X(), p0.y() + _pose.Pos().Y(), p0.z());\n      target.point(v1) = p1;\n    }\n  }\n\n  void WavefieldSampler::UpdatePatch()\n  {\n    // Direction of the line search (i.e. positive z-axis)\n    Direction3 direction(0, 0, 1);\n\n    // Update the water patch Mesh\n    const auto& target = this->data->waterPatch->GetMesh();\n    for (\n      auto&& vb = std::begin(target->vertices()); \n      vb != std::end(target->vertices());\n      ++vb\n    )\n    {\n      auto& v1 = *vb;\n\n      Point3& origin = target->point(v1);\n      Point3 point = CGAL::ORIGIN;\n\n      auto& wavefieldGrid = *this->data->wavefield->GetGrid();\n      std::array<size_t, 3> cellIndex = { 0, 0, 0 };\n      bool isFound = GridTools::FindIntersectionIndex(\n        wavefieldGrid, origin.x(), origin.y(), cellIndex);\n      if (!isFound)\n      {\n        // @DEBUG_INFO\n        gzmsg << \"origin:   \" << origin << std::endl;\n        gzerr << \"Wavefield is too small\" << std::endl;\n        return;\n      }\n      isFound = GridTools::FindIntersectionGrid(\n        wavefieldGrid, origin, direction, cellIndex, point);\n\n      if (!isFound)\n      {\n        // @DEBUG_INFO\n        gzmsg << \"origin:   \" << origin << std::endl;\n        gzerr << \"Wavefield is too small\" << std::endl;\n        return;\n      }\n\n      target->point(v1) = point;\n    }\n  }\n\n  double WavefieldSampler::ComputeDepth(const Point3& _point) const\n  {\n    auto& grid = *this->data->waterPatch;\n    return WavefieldSampler::ComputeDepth(grid, _point);\n\n    // @TODO_EXPERIMENTAL - direct calculation (currently static only)\n    // auto& waveParams = *this->data->wavefield->GetParameters();\n    // return WavefieldSampler::ComputeDepthDirectly(waveParams, _point, 0.0);\n  }\n  \n  double WavefieldSampler::ComputeDepth(  \n    const Grid& _patch,\n    const Point3& _point\n  )\n  {\n    // Calculate the depth\n    Direction3 direction(0, 0, 1);\n    Point3 wavePoint = CGAL::ORIGIN;\n    std::array<size_t, 3> index;\n    bool isFound = GridTools::FindIntersectionIndex(\n      _patch, _point.x(), _point.y(), index);\n    if (!isFound)\n    {\n      // @DEBUG_INFO\n      gzerr << \"point:  \" << _point << std::endl;\n      // _patch.DebugPrint();\n      gzerr << \"Water patch is too small\" << std::endl;\n      return 0;\n    }\n    isFound = GridTools::FindIntersectionGrid(\n      _patch, _point, direction, index, wavePoint);\n    if (!isFound)\n    {\n      // @DEBUG_INFO\n      gzerr << \"point:  \" << _point << std::endl;\n      // _patch.DebugPrint();\n      gzerr << \"Water patch is too small\" << std::endl;\n      return 0;\n    }\n    double h = wavePoint.z() - _point.z();\n    return h;\n  }\n\n  double WavefieldSampler::ComputeDepthDirectly(  \n    const WaveParameters& _waveParams,\n    const Point3& _point,\n    double time\n  )\n  {\n    // Struture for passing wave parameters to lambdas\n    struct WaveParams\n    {\n      WaveParams(\n        const std::vector<double>& _a,\n        const std::vector<double>& _k,\n        const std::vector<double>& _omega,\n        const std::vector<double>& _phi,\n        const std::vector<double>& _q,\n        const std::vector<Vector2>& _dir) :\n        a(_a), k(_k), omega(_omega), phi(_phi), q(_q), dir(_dir) {}\n\n      const std::vector<double>& a;\n      const std::vector<double>& k;\n      const std::vector<double>& omega;\n      const std::vector<double>& phi;\n      const std::vector<double>& q;\n      const std::vector<Vector2>& dir;\n    };\n\n    // Compute the target function and Jacobian. Also calculate pz,\n    // the z-componen of the Gerstner wave, which we essentially get for free.\n    auto wave_fdf = [=](auto x, auto p, auto t, auto& wp, auto& F, auto& J)\n    {\n      double pz = 0;\n      F(0) = p.x() - x.x();\n      F(1) = p.y() - x.y();\n      J(0, 0) = -1;\n      J(0, 1) =  0;\n      J(1, 0) =  0;\n      J(1, 1) = -1;\n      const size_t n = wp.a.size();\n      for (auto&& i=0; i<n; ++i)\n      {\n        const double dx = wp.dir[i].x();\n        const double dy = wp.dir[i].y();\n        const double q = wp.q[i];\n        const double a = wp.a[i];\n        const double k = wp.k[i];\n        const double dot = x.x() * dx + x.y() * dy;\n        const double theta = k * dot - wp.omega[i] * t;\n        const double s = std::sin(theta);\n        const double c = std::cos(theta);\n        const double qakc = q * a * k * c;\n        const double df1x = qakc * dx * dx;\n        const double df1y = qakc * dx * dy;\n        const double df2x = df1y;\n        const double df2y = qakc * dy * dy;\n        pz += a * c;\n        F(0) += a * dx * s;\n        F(1) += a * dy * s;\n        J(0, 0) += df1x;\n        J(0, 1) += df1y;\n        J(1, 0) += df2x;\n        J(1, 1) += df2y;\n      }\n      return pz;\n    };\n\n    // Simple multi-variate Newton solver - this version returns the z-component of the\n    // wave field at the desired point p.\n    auto solver = [=](auto& fdfunc, auto x0, auto p, auto t, auto& wp, auto tol, auto nmax)\n    {\n      int n = 0;\n      double err = 1;\n      double pz = 0;\n      auto xn = x0;\n      Eigen::Vector2d F;\n      Eigen::Matrix2d J;\n      while (std::abs(err) > tol && n < nmax)\n      {\n        pz = fdfunc(x0, p, t, wp, F, J);\n        xn = x0 - J.inverse() * F;\n        x0 = xn;\n        err = F.norm();\n        n++;\n      }\n      return pz;\n    };\n\n    // Set up parameter references\n    WaveParams wp(\n      _waveParams.Amplitude_V(),\n      _waveParams.Wavenumber_V(),\n      _waveParams.AngularFrequency_V(),\n      _waveParams.Phase_V(),\n      _waveParams.Steepness_V(),\n      _waveParams.Direction_V()\n    );\n\n    // Tolerances etc.\n    const double tol = 1.0E-10;\n    const double nmax = 30;\n\n    // Use the target point as the initial guess (this is within sum{amplitudes} of the solution)\n    Eigen::Vector2d p2(_point.x(), _point.y());\n    const double pz = solver(wave_fdf, p2, p2, time, wp, tol, nmax);\n    const double h = pz - _point.z();\n    return h;\n  }\n\n///////////////////////////////////////////////////////////////////////////////\n\n} // namespace asv\n", "meta": {"hexsha": "abd982f8aa47dfa91c957c70c9a2dcf348d6ddbe", "size": 31407, "ext": "cc", "lang": "C++", "max_stars_repo_path": "asv_wave_sim_gazebo_plugins/src/Wavefield.cc", "max_stars_repo_name": "srmainwaring/asv_wave_sim", "max_stars_repo_head_hexsha": "524a6bdab819ed422c85d19ccff0ceef2fddcdf5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T04:55:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:07:07.000Z", "max_issues_repo_path": "asv_wave_sim_gazebo_plugins/src/Wavefield.cc", "max_issues_repo_name": "srmainwaring/asv_wave_sim", "max_issues_repo_head_hexsha": "524a6bdab819ed422c85d19ccff0ceef2fddcdf5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T16:26:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:44:33.000Z", "max_forks_repo_path": "asv_wave_sim_gazebo_plugins/src/Wavefield.cc", "max_forks_repo_name": "srmainwaring/asv_wave_sim", "max_forks_repo_head_hexsha": "524a6bdab819ed422c85d19ccff0ceef2fddcdf5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-29T04:55:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T11:55:32.000Z", "avg_line_length": 30.6409756098, "max_line_length": 107, "alphanum_fraction": 0.5940077053, "num_tokens": 8699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.026355350073901544, "lm_q1q2_score": 0.011843900201951611}}
{"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_python_interface.hh\"\n\n#include <boost/python.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_util.hh\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\n\nclass BFVisitorWrapper\n{\npublic:\n    BFVisitorWrapper(python::object gi, python::object vis)\n        : _gi(gi), _vis(vis) {}\n\n    template <class Edge, class Graph>\n    void examine_edge(Edge e, const Graph&)\n    {\n        _vis.attr(\"examine_edge\")\n            (PythonEdge<Graph>(_gi, e));\n    }\n\n    template <class Edge, class Graph>\n    void edge_relaxed(Edge e, const Graph&)\n    {\n        _vis.attr(\"edge_relaxed\")\n            (PythonEdge<Graph>(_gi, e));\n    }\n\n    template <class Edge, class Graph>\n    void edge_not_relaxed(Edge e, const Graph&)\n    {\n        _vis.attr(\"edge_not_relaxed\")\n            (PythonEdge<Graph>(_gi, e));\n    }\n\n    template <class Edge, class Graph>\n    void edge_minimized(Edge e, const Graph&)\n    {\n        _vis.attr(\"edge_minimized\")\n            (PythonEdge<Graph>(_gi, e));\n    }\n\n    template <class Edge, class Graph>\n    void edge_not_minimized(Edge e, const Graph&)\n    {\n        _vis.attr(\"edge_not_minimized\")\n            (PythonEdge<Graph>(_gi, e));\n    }\n\nprivate:\n    python::object _gi, _vis;\n};\n\n\nclass BFCmp\n{\npublic:\n    BFCmp(python::object cmp): _cmp(cmp) {}\n\n    template <class Value1, class Value2>\n    bool operator()(const Value1& v1, const Value2& v2) const\n    {\n        return python::extract<bool>(_cmp(v1, v2));\n    }\n\nprivate:\n    python::object _cmp;\n};\n\nclass BFCmb\n{\npublic:\n    BFCmb(python::object cmb): _cmb(cmb) {}\n\n    template <class Value1, class Value2 >\n    Value1 operator()(const Value1& v1, const Value2& v2) const\n    {\n        return python::extract<Value1>(_cmb(v1, v2));\n    }\n\nprivate:\n    python::object _cmb;\n};\n\nstruct do_bf_search\n{\n    template <class Graph, class DistanceMap>\n    void operator()(const Graph& g, size_t s, DistanceMap dist,\n                    boost::any pred_map, boost::any aweight,\n                    BFVisitorWrapper vis, pair<BFCmp, BFCmb> cm,\n                    pair<python::object, python::object> range, bool& ret) const\n    {\n        typedef typename property_traits<DistanceMap>::value_type dtype_t;\n        dtype_t z = python::extract<dtype_t>(range.first);\n        dtype_t i = python::extract<dtype_t>(range.second);\n\n        typedef typename property_map_type::\n            apply<int32_t, typeof(get(vertex_index, g))>::type pred_t;\n        pred_t pred = any_cast<pred_t>(pred_map);\n        typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n        DynamicPropertyMapWrap<dtype_t, edge_t> weight(aweight,\n                                                       edge_properties());\n        ret = bellman_ford_shortest_paths\n            (g, HardNumVertices()(g),\n             root_vertex(vertex(s, g)).visitor(vis).weight_map(weight).\n             distance_map(dist).\n             predecessor_map(pred).\n             distance_compare(cm.first).\n             distance_combine(cm.second).distance_inf(i).\n             distance_zero(z));\n    }\n};\n\n\nbool bellman_ford_search(GraphInterface& g, python::object gi, size_t source,\n                         boost::any dist_map, boost::any pred_map,\n                         boost::any weight, python::object vis,\n                         python::object cmp, python::object cmb,\n                         python::object zero, python::object inf)\n{\n    bool ret = false;\n    run_action<graph_tool::detail::all_graph_views,mpl::true_>()\n        (g, std::bind(do_bf_search(),  placeholders::_1, source,\n                      placeholders::_2, pred_map, weight,\n                      BFVisitorWrapper(gi, vis),\n                      make_pair(BFCmp(cmp), BFCmb(cmb)), make_pair(zero, inf),\n                      std::ref(ret)),\n         writable_vertex_properties())\n        (dist_map);\n    return ret;\n}\n\nvoid export_bellman_ford()\n{\n    using namespace boost::python;\n    def(\"bellman_ford_search\", &bellman_ford_search);\n}\n", "meta": {"hexsha": "1b4c532596c5405a601ed6cd4a4cf26820587b46", "size": 4888, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/search/graph_bellman_ford.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/search/graph_bellman_ford.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/search/graph_bellman_ford.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": 30.1728395062, "max_line_length": 80, "alphanum_fraction": 0.6301145663, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.0293122296913986, "lm_q1q2_score": 0.011829443891987422}}
{"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\n#include \"PyImathShear.h\"\n\n#include \"PyImathPlane.h\"\n#include \"PyImathDecorators.h\"\n#include \"PyImathExport.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include \"PyImath.h\"\n#include \"PyImathMathExc.h\"\n#include <Iex.h>\n\n\nnamespace PyImath{\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\n\ntemplate <class T> struct ShearName {static const char *value;};\ntemplate <> const char *ShearName<float>::value = \"Shear6f\";\ntemplate <> const char *ShearName<double>::value = \"Shear6d\";\n\ntemplate <class T>\nstatic std::string Shear_str(const Shear6<T> &v)\n{\n    std::stringstream stream;\n    stream << ShearName<T>::value << \"(\" \n           << v[0] << \", \" << v[1] << \", \" << v[2] << \", \"\n           << v[3] << \", \" << v[4] << \", \" << v[5] << \")\";\n    return stream.str();\n}\n\n// Non-specialized repr is same as str\ntemplate <class T>\nstatic std::string Shear_repr(const Shear6<T> &v)\n{\n    return Shear_str(v);\n}\n\n// Specialization for float to full precision\ntemplate <>\nstd::string Shear_repr(const Shear6<float> &v)\n{\n    return (boost::format(\"%s(%.9g, %.9g, %.9g, %.9g, %.9g, %.9g)\")\n                        % ShearName<float>::value\n                        % v[0] % v[1] % v[2]\n                        % v[3] % v[4] % v[5]).str();\n}\n\n// Specialization for double to full precision\ntemplate <>\nstd::string Shear_repr(const Shear6<double> &v)\n{\n    return (boost::format(\"%s(%.17g, %.17g, %.17g, %.17g, %.17g, %.17g)\")\n                        % ShearName<double>::value\n                        % v[0] % v[1] % v[2]\n                        % v[3] % v[4] % v[5]).str();\n}\n\ntemplate <class T>\nstatic Shear6<T> * shearTupleConstructor(tuple t)\n{\n    if(t.attr(\"__len__\")() == 3){\n        return new Shear6<T>(extract<T>(t[0]), extract<T>(t[1]), extract<T>(t[2]),\n                             T(0), T(0), T(0));\n    }\n    else if(t.attr(\"__len__\")() == 6){\n        return new Shear6<T>(extract<T>(t[0]), extract<T>(t[1]), extract<T>(t[2]),\n                             extract<T>(t[3]), extract<T>(t[4]), extract<T>(t[5]));        \n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Shear6 expects tuple of length 3 or 6\");\n}\n\ntemplate <class T>\nstatic Shear6<T> * shearConstructor1(T a)\n{\n    return new Shear6<T>(a, a, a, a, a, a);\n}\n\ntemplate <class T, class S>\nstatic Shear6<T> * shearConversionConstructor(const Shear6<S> &shear)\n{\n    Shear6<T> *s = new Shear6<T>;\n    *s = shear;\n    return s;\n}\n\ntemplate <class T>\nstatic const Shear6<T> &\niadd(Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear += other;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nadd(const Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear + other;\n}\n\ntemplate <class T>\nstatic const Shear6<T> &\nisub(Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear -= other;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nsub(const Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear - other;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nneg(const Shear6<T> &shear)\n{\n    MATH_EXC_ON;\n    return -shear;\n}\n\ntemplate <class T>\nstatic const Shear6<T> &\nimul(Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear *= other;\n}\n\ntemplate <class T>\nstatic const Shear6<T> &\nimulT(Shear6<T> &shear, T t)\n{\n    MATH_EXC_ON;\n    return shear *= t;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nmul(const Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear * other;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nmulT(const Shear6<T> &shear, T t)\n{\n    MATH_EXC_ON;\n    return shear * t;\n}\n\ntemplate <class T>\nstatic const Shear6<T> &\nidiv(Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear /= other;\n}\n\ntemplate <class T>\nstatic const Shear6<T> &\nidivT(Shear6<T> &shear, T t)\n{\n    MATH_EXC_ON;\n    return shear /= t;\n}\n\ntemplate <class T>\nstatic Shear6<T>\ndiv(const Shear6<T> &shear, const Shear6<T> &other)\n{\n    MATH_EXC_ON;\n    return shear / other;\n}\n\ntemplate <class T>\nstatic Shear6<T>\ndivT(const Shear6<T> &shear, T t)\n{\n    MATH_EXC_ON;\n    return shear / t;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nsubtract1(Shear6<T> &v, tuple t)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n    \n    if(t.attr(\"__len__\")() == 6){\n        w[0] = v[0] - extract<T>(t[0]);\n        w[1] = v[1] - extract<T>(t[1]);   \n        w[2] = v[2] - extract<T>(t[2]);\n        w[3] = v[3] - extract<T>(t[3]);\n        w[4] = v[4] - extract<T>(t[4]);   \n        w[5] = v[5] - extract<T>(t[5]);\n    }        \n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"tuple must have length of 6\");\n    \n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nsubtract2(Shear6<T> &v, tuple t)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n    \n    if(t.attr(\"__len__\")() == 6){\n        w[0] = extract<T>(t[0]) - v[0];\n        w[1] = extract<T>(t[1]) - v[1];   \n        w[2] = extract<T>(t[2]) - v[2];\n        w[3] = extract<T>(t[3]) - v[3];\n        w[4] = extract<T>(t[4]) - v[4];   \n        w[5] = extract<T>(t[5]) - v[5];\n    }        \n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"tuple must have length of 6\");\n    \n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nsubtractT1(Shear6<T> &v, T a)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n    \n    w[0] = v[0] - a;\n    w[1] = v[1] - a;   \n    w[2] = v[2] - a;\n    w[3] = v[3] - a;\n    w[4] = v[4] - a;   \n    w[5] = v[5] - a;\n\n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nsubtractT2(Shear6<T> &v, T a)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n\n     w[0] = a - v[0];\n     w[1] = a - v[1];   \n     w[2] = a - v[2];\n     w[3] = a - v[3];\n     w[4] = a - v[4];   \n     w[5] = a - v[5];\n\n    return w;\n}\n\n\ntemplate <class T>\nstatic Shear6<T>\naddTuple(Shear6<T> &v, tuple t)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n    \n    if(t.attr(\"__len__\")() == 6){\n        w[0] = v[0] + extract<T>(t[0]);\n        w[1] = v[1] + extract<T>(t[1]);   \n        w[2] = v[2] + extract<T>(t[2]);\n        w[3] = v[3] + extract<T>(t[3]);\n        w[4] = v[4] + extract<T>(t[4]);   \n        w[5] = v[5] + extract<T>(t[5]);\n    }        \n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"tuple must have length of 6\");\n    \n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\naddT(Shear6<T> &v, T a)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n\n     w[0] = v[0] + a;\n     w[1] = v[1] + a;   \n     w[2] = v[2] + a;\n     w[3] = v[3] + a;\n     w[4] = v[4] + a;   \n     w[5] = v[5] + a;\n    \n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nmultTuple(Shear6<T> &v, tuple t)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n    \n    if(t.attr(\"__len__\")() == 6){\n        w[0] = v[0] * extract<T>(t[0]);\n        w[1] = v[1] * extract<T>(t[1]);   \n        w[2] = v[2] * extract<T>(t[2]);\n        w[3] = v[3] * extract<T>(t[3]);\n        w[4] = v[4] * extract<T>(t[4]);   \n        w[5] = v[5] * extract<T>(t[5]);\n    }        \n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"tuple must have length of 6\");\n    \n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nrdiv(Shear6<T> &v, T a)\n{\n    MATH_EXC_ON;\n    Shear6<T> w;\n    \n    if(v != Shear6<T>()){\n        w[0] = a/v[0];\n        w[1] = a/v[1];\n        w[2] = a/v[2];\n        w[3] = a/v[3];\n        w[4] = a/v[4];\n        w[5] = a/v[5];\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Division by Zero\");\n    \n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\ndivTuple(Shear6<T> &v, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() != 6)\n        THROW(IEX_NAMESPACE::LogicExc, \"Shear6 expects tuple of length 6\");\n    \n    Shear6<T> w;\n    for(int i = 0; i < 6; ++i)\n    {\n        T a = extract<T>(t[i]);\n        if(a != T (0))\n            w[i] = v[i] / a;\n        else\n            THROW(IEX_NAMESPACE::LogicExc, \"Division by Zero\"); \n    }\n    \n    return w;\n}\n\ntemplate <class T>\nstatic Shear6<T>\nrdivTuple(Shear6<T> &v, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() != 6)\n        THROW(IEX_NAMESPACE::LogicExc, \"Shear6 expects tuple of length 6\");\n    \n    Shear6<T> w;\n    for(int i = 0; i < 6; ++i)\n    {\n        T a = extract<T>(t[i]);\n        if(v[i] != T (0))\n            w[i] = a / v[i];\n        else\n            THROW(IEX_NAMESPACE::LogicExc, \"Division by Zero\"); \n    }\n    \n    return w;\n}\n\ntemplate <class T>\nstatic bool\nlessThan(Shear6<T> &v, const Shear6<T> &w)\n{\n    bool isLessThan = (v[0] <= w[0] && v[1] <= w[1] && v[2] <= w[2] \n                    && v[3] <= w[3] && v[4] <= w[4] && v[5] <= w[5])\n                    && v != w;\n                   \n   return isLessThan;\n}\n\ntemplate <class T>\nstatic bool\ngreaterThan(Shear6<T> &v, const Shear6<T> &w)\n{\n    bool isGreaterThan = (v[0] >= w[0] && v[1] >= w[1] && v[2] >= w[2] \n                       && v[3] >= w[3] && v[4] >= w[4] && v[5] >= w[5])\n                       && v != w;\n                   \n   return isGreaterThan;\n}\n\ntemplate <class T>\nstatic bool\nlessThanEqual(Shear6<T> &v, const Shear6<T> &w)\n{\n    bool isLessThanEqual = (v[0] <= w[0] && v[1] <= w[1] && v[2] <= w[2] \n                         && v[3] <= w[3] && v[4] <= w[4] && v[5] <= w[5]);\n                   \n   return isLessThanEqual;\n}\n\ntemplate <class T>\nstatic bool\ngreaterThanEqual(Shear6<T> &v, const Shear6<T> &w)\n{\n    bool isGreaterThanEqual = (v[0] >= w[0] && v[1] >= w[1] && v[2] >= w[2] \n                            && v[3] >= w[3] && v[4] >= w[4] && v[5] >= w[5]);\n                   \n   return isGreaterThanEqual;\n}\n\ntemplate <class T>\nstatic T\ngetitem(Shear6<T> &shear, int i)\n{\n    return shear[i];\n}\n\ntemplate <class T>\nstatic void\nsetitem(Shear6<T> &shear, int i, T a)\n{\n    if(i < 0 || i > 5)\n        THROW(IEX_NAMESPACE::LogicExc, \"Index out of range\");\n    \n    shear[i] = a;\n}\n\ntemplate <class T>\nstatic int\nlen(Shear6<T> &shear)\n{\n    return 6;\n}\n\n\n\ntemplate <class T>\nclass_<Shear6<T> >\nregister_Shear()\n{\n    const char *name = ShearName<T>::value;\n    \n    void (IMATH_NAMESPACE::Shear6<T>::*setValue1)(T,T,T,T,T,T) = &IMATH_NAMESPACE::Shear6<T>::setValue;\n    void (IMATH_NAMESPACE::Shear6<T>::*setValue2)(const Shear6<T> &) = &IMATH_NAMESPACE::Shear6<T>::setValue;\n    void (IMATH_NAMESPACE::Shear6<T>::*getValue1)(Shear6<T> &) const = &IMATH_NAMESPACE::Shear6<T>::getValue;\n    \n    class_<Shear6<T> > shear_class(name, name, init<Shear6<T> >(\"copy construction\"));\n    shear_class\n        .def(init<>(\"default construction: (0 0 0 0 0 0)\"))\n        .def(init<T,T,T>(\"Shear(XY,XZ,YZ) construction: (XY XZ YZ 0 0 0)\"))\n        .def(init<const Vec3<float> &>(\"Shear(v) construction: (v.x v.y v.z 0 0 0)\"))\n        .def(init<const Vec3<double> &>(\"Shear(v) construction: (v.x v.y v.z 0 0 0)\"))\n        .def(init<const Vec3<int> &>(\"Shear(v) construction: (v.x v.y v.z 0 0 0)\"))\n        .def(init<T,T,T,T,T,T>(\"Shear(XY, XZ, YZ, YX, ZX, ZY) construction\"))\n        .def(\"__init__\", make_constructor(shearConstructor1<T>))\n        .def(\"__init__\", make_constructor(shearTupleConstructor<T>),\"Construction from tuple\")\n        .def(\"__init__\", make_constructor(shearConversionConstructor<T,float>))\n        .def(\"__init__\", make_constructor(shearConversionConstructor<T,double>))\n        .def(\"__init__\", make_constructor(shearConversionConstructor<T,int>))\n        .def(\"__iadd__\",&iadd<T>,return_internal_reference<>())\n        .def(\"__add__\",&add<T>)\n        .def(\"__isub__\",&isub<T>,return_internal_reference<>())\n        .def(\"__sub__\",&sub<T>)\n        .def(\"__neg__\",&neg<T>)\n        .def(\"__imul__\",&imul<T>,return_internal_reference<>())\n        .def(\"__imul__\",&imulT<T>,return_internal_reference<>())\n        .def(\"__mul__\",&mul<T>)\n        .def(\"__mul__\",&mulT<T>)\n        .def(\"__rmul__\",&mulT<T>)\n        .def(\"__idiv__\",&idiv<T>,return_internal_reference<>())\n        .def(\"__idiv__\",&idivT<T>,return_internal_reference<>())\n        .def(\"__itruediv__\",&idiv<T>,return_internal_reference<>())\n        .def(\"__itruediv__\",&idivT<T>,return_internal_reference<>())\n        .def(\"__div__\",&div<T>)\n        .def(\"__div__\",&divT<T>)\n        .def(\"__truediv__\",&div<T>)\n        .def(\"__truediv__\",&divT<T>)\n        .def(self == self)\n        .def(self != self)\n        .def(\"__str__\",&Shear_str<T>)\n        .def(\"__repr__\",&Shear_repr<T>)\n        .def(\"setValue\", setValue1)\n        .def(\"setValue\", setValue2)\n        .def(\"getValue\", getValue1)\n        .def(\"negate\", &Shear6<T>::negate, return_internal_reference<>())\n        .def(\"baseTypeMin\", &Shear6<T>::baseTypeMin)\n        .staticmethod(\"baseTypeMin\")\n        .def(\"baseTypeMax\", &Shear6<T>::baseTypeMax)\n        .staticmethod(\"baseTypeMax\")\n        .def(\"baseTypeSmallest\", &Shear6<T>::baseTypeSmallest)\n        .staticmethod(\"baseTypeSmallest\")\n        .def(\"baseTypeEpsilon\", &Shear6<T>::baseTypeEpsilon)\n        .staticmethod(\"baseTypeEpsilon\")\n        .def(\"equalWithAbsError\", &Shear6<T>::equalWithAbsError)\n        .def(\"equalWithRelError\", &Shear6<T>::equalWithRelError)\n        .def(\"__sub__\", &subtract1<T>)\n        .def(\"__sub__\", &subtractT1<T>)\n        .def(\"__rsub__\", &subtract2<T>)\n        .def(\"__rsub__\", &subtractT2<T>)\n        .def(\"__add__\", &addTuple<T>)\n        .def(\"__add__\", &addT<T>)\n        .def(\"__radd__\", &addTuple<T>)\n        .def(\"__radd__\", &addT<T>)\n        .def(\"__mul__\", &multTuple<T>)\n        .def(\"__rmul__\", &multTuple<T>)\n        .def(\"__div__\", &divTuple<T>)\n        .def(\"__truediv__\", &divTuple<T>)\n        .def(\"__rdiv__\", &rdiv<T>)\n        .def(\"__rdiv__\", &rdivTuple<T>)\n        .def(\"__lt__\", &lessThan<T>)\n        .def(\"__gt__\", &greaterThan<T>)\n        .def(\"__le__\", &lessThanEqual<T>)\n        .def(\"__ge__\", &greaterThanEqual<T>)\n        .def(\"__getitem__\", &getitem<T>)\n        .def(\"__setitem__\", &setitem<T>)\n        .def(\"__len__\", &len<T>)\n        ;\n\n    decoratecopy(shear_class);\n\n    return shear_class;\n}\n\ntemplate PYIMATH_EXPORT class_<Shear6<float> > register_Shear();\ntemplate PYIMATH_EXPORT class_<Shear6<double> > register_Shear();\n\n}//namespace PyIMath\n", "meta": {"hexsha": "c809e0c8cb6ec2fe0104e29929f6509f832e44f2", "size": 15680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathShear.cpp", "max_stars_repo_name": "tangent-devops/openexr", "max_stars_repo_head_hexsha": "2f7847e3faf7146f2be8c1c0c3053c50b7ee9d97", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-27T03:39:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-16T16:03:02.000Z", "max_issues_repo_path": "PyIlmBase/PyImath/PyImathShear.cpp", "max_issues_repo_name": "tangent-devops/openexr", "max_issues_repo_head_hexsha": "2f7847e3faf7146f2be8c1c0c3053c50b7ee9d97", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/PyImathShear.cpp", "max_forks_repo_name": "tangent-devops/openexr", "max_forks_repo_head_hexsha": "2f7847e3faf7146f2be8c1c0c3053c50b7ee9d97", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-16T04:34:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-26T00:51:41.000Z", "avg_line_length": 26.7576791809, "max_line_length": 109, "alphanum_fraction": 0.5573341837, "num_tokens": 5068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.03461883846567403, "lm_q1q2_score": 0.011825189370756288}}
{"text": "//=======================================================================\n// Copyright 2015 Tsinghua University.\n// Authors: Fuan Pu (Pu.Fuan@gmail.com)\n// \n// Dung's abstract argumentation framework\n//=======================================================================\n\n#ifndef DUNG_ARGUMENTATION_FRAMEWORK_HPP\n#define DUNG_ARGUMENTATION_FRAMEWORK_HPP\n\n//boost\n#include <boost/config.hpp>\n//#include <boost/graph/graph_traits.hpp> \n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/iteration_macros.hpp>\n//#include <boost/graph/named_graph.hpp> \n//#include <boost/property_map/property_map.hpp>\n\n#include <iostream>\n#include <string>\n#include <utility>   \n#include <algorithm>   \n\n#include \"config/config.hpp\"\n#include \"ArgumentProperty.hpp\"\n#include \"AttackProperty.hpp\"\n#include \"bitmatrix/bitvector.hpp\"\n#include \"bitmatrix/bitmatrix.hpp\"\n\n\n/************************************************************************/\n/* Use the label of ArgumentProperty as a key for indexing Arguments    */\n/* in a graph. This approach is referred from:                          */\n/* [Named vertices](http://svn.boost.org/svn/boost/trunk/libs/graph/test/named_vertices_test.cpp) */\n/* and [Name Graph](http://www.boost.org/doc/libs/1_49_0/boost/graph/named_graph.hpp) */ \n/************************************************************************/\nnamespace boost{\n\tnamespace graph {\n\n\t\t/// Use the label of ArgumentProperty as a key for indexing Arguments in a graph\n\t\ttemplate<>\n\t\tstruct internal_vertex_name<argumatrix::ArgumentProperty>\n\t\t{\n\t\t\ttypedef multi_index::member<argumatrix::ArgumentProperty, \n\t\t\t\tstd::string, &argumatrix::ArgumentProperty::label> type;\n\t\t};\n\n\t\t/// Allow the graph to build Arguments given only their labels (filling in\n\t\t/// the defaults for fields).\n\t\ttemplate<>\n\t\tstruct internal_vertex_constructor<argumatrix::ArgumentProperty>\n\t\t{\n\t\t\ttypedef vertex_from_name<argumatrix::ArgumentProperty> type;\n\t\t};\n\t} // end namespace boost::graph\n}  // end namespace boost\n\n\n\nnamespace argumatrix{\n\nusing namespace std;\nusing namespace boost;\n\n/**\n* An abstract argumentation framework is a directed graph, called Argument Graph.\n* Here, we use the boost graph to define the argument graph. \n*   typedef adjacency_list\n*   < setS, // edge container\n*   vecS, // vertex container\n*   undirectedS,\n*   boost::no_property,  // vertex property\n*   boost::no_property // edge property\n*   > graph;\n*/\ntypedef boost::adjacency_list<boost::listS, boost::vecS,\n\tboost::directedS, ArgumentProperty, AttackProperty> ArgumentGraph;\n\n// The definition of the argument (descriptor)\ntypedef boost::graph_traits<ArgumentGraph>::vertex_descriptor Argument;\n\n// The definition of the attack relation (descriptor)\ntypedef boost::graph_traits<ArgumentGraph>::edge_descriptor Attack;\n\n// Iterators\ntypedef boost::graph_traits<ArgumentGraph>::vertex_iterator ArgumentIterator;\ntypedef boost::graph_traits<ArgumentGraph>::edge_iterator AttackIterator;\ntypedef boost::graph_traits<ArgumentGraph>::adjacency_iterator AdjacencyIterator;\ntypedef boost::graph_traits<ArgumentGraph>::out_edge_iterator OutEdgeIterator;\n\n// The index property of the vertices. Using to get the index of an vertex.\ntypedef boost::property_map<ArgumentGraph, boost::vertex_index_t, size_type>::type IdxMapType;\n\n/************************************************************************/\n/* The concepts of Dung's argumentation framework.                       */\n/************************************************************************/\nclass DungAF\n{\npublic:\n\tDungAF();\n\t~DungAF();\n\n\n\t// Note that: this method just copy the properties of an argument\n\t// Add a new Argument to the argument graph and copy ap into property \n\t// object for the new argument.\n\tArgument addArgument(const ArgumentProperty& _argProp);\n\tArgument addArgument(string _label, string _title=\"\", string _description=\"\");\n\n\t// Add an attack to argument graph with an AttackProperty. Here _arg1 attacks _arg2.\n\tAttack addAttack(const std::string& _arg1_label, const std::string& _arg2_label, const AttackProperty& _attProp = AttackProperty());\n\tAttack addAttack(const Argument& _arg1, const std::string& _arg2_label, const AttackProperty& _attProp = AttackProperty());\n\tAttack addAttack(const std::string& _arg1_label, const Argument& _arg2, const AttackProperty& _attProp = AttackProperty());\n\tAttack addAttack(const Argument& _arg1, const Argument& _arg2, const AttackProperty& _attProp = AttackProperty());\n\tAttack addAttack(const std::pair<Argument&, Argument&>& _edge, const AttackProperty& _attProp = AttackProperty());\n\n\n\t/**\n\t* Get the Property of the Argument or the Attack\n\t* Note that the return value must be const since all external changes\n\t* on properties are not safe. Let the label of argument a is \"A\" and assume\n\t* the returned property is not constant, for instance, if an argument b, \n\t* whose label is 'B', then we can modify the label of argument b as \"A\", which\n\t* may contradict with the restriction that each argument has a unique label. \n\t* The return value of constant may avoid this issue. We also provide a series \n\t* of methods to change the property of some argument or attack with safety-check.\n\t* \n\t* @param Argument or Attack, or the unique argument label\n\t* @return no return. The results are stored in m_extensions.\n\t*/\n\tconst ArgumentProperty& getArgumentProperty(const Argument& _arg) const;\n\tconst ArgumentProperty& getArgumentProperty(const std::string& _arg_label) const;\n\tsize_type getArgumentIdx(const std::string& _arg_label) const;\n\tsize_type getArgumentIdx(const Argument& _arg) const;\n\tconst AttackProperty& getAttackProperty(const Attack& _atk) const;\n\t\n\t// Get a vector of argument labels, vector[i] is the label of the argument indexed by i\n\tstd::vector<std::string> getArgumentLabels() const;\n\n\t// Clear the argument graph\n\tvoid clear();\n\n\t// Update the bit matrix when changing (of Argument and Attack) occurs\n\t//void update();\n\n\n\t/**\n\t * Method:    set2bv\n\t * FullName:  argumatrix::DungAF::set2bv\n\t * Access:    public \n\t * @param     const set<Argument> & sa\n\t * @return    argumatrix::bitvector\n\t */\n\tbitvector set2bv(const set<Argument>& sa) const;\n\tset<Argument> bv2set(const bitvector& bv) const;\n\tset<string> bv2label_set(const bitvector& bv) const;\n\tbitvector labelSet2bv(const set<string>& _ls) const;\n\tset<bitvector> label_ext2bv_ext(const set< set<string> >& _le) const;\n\n\tstd::string toString() const;\n\n\tbitmatrix getAttackMatrix() const;\n\n\tsize_type getNumberOfArguments() const;\n\n\tvoid showSet(const set<Argument>& as, std::ostream& os = std::cout) const; \n\n\t/**\n\t* Output a bitvector. A bitvector represent a set of arguments in bool \n\t* vector form. This function will output a bitvector in string, but not \n\t* the string with 0 and 1. \n\t* @param bitvector _bv: A bitvector.\n\t* @param ostream& os: The out put stream. The default value is cout.\n\t* @return no return. The results are stored in m_extensions.\n\t*/\n\tvoid outputBv(const bitvector& _bv, std::ostream& os = std::cout) const; \n\n\t/**\n\t* Output a set of bitvector set<bitvector>. We know that one bitvector \n\t* represent a set of arguments in bool vector form. Therefore, a set of bitvector \n\t* may represent a set of a set of arguments. This function will output a set\n\t* of bitvector in string.\n\t* @param set< bitvector >& _bv_set: A set of bitvector.\n\t* @param ostream& os: The out put stream. The default value is cout.\n\t* @return no return. The results are stored in m_extensions.\n\t*/\n\tvoid outputBvSet(const std::set< bitvector >& _bv_set, std::ostream& os = std::cout) const;\n\nprivate:\n\t/* Dung'a abstract argumentation framework can be seen as a direct graph.\n\t * */\n\tArgumentGraph\tm_ag;\n\tIdxMapType\tm_idxMap;\n\t//bitmatrix\tm_bm;  \n}; // end DungAF\n\nDungAF::DungAF()\n{\n\tm_idxMap = boost::get(boost::vertex_index, m_ag);\n}\n\nDungAF::~DungAF()\n{\n\t\n}\n\n__inline\nArgument DungAF::addArgument(const ArgumentProperty& _ap)\n{\n\treturn boost::add_vertex(_ap, m_ag);\n}\n\n__inline\nArgument DungAF::addArgument(string _label, string _title/*=\"\"*/, string _description/*=\"\"*/)\n{\n\t//// Approach 1\n\t//Argument arg = boost::add_vertex( _label, m_ag );\n\t//ArgumentProperty& _ap = m_ag[arg];\n\t//_ap.description = _description;\n\t//_ap.title = _title;\n\n\t//return arg;\n\n\t// This approach maybe more efficient.\n\t// Argument arg = boost::add_vertex(m_ag);\n\t// ArgumentProperty& _ap = m_ag[arg];\n\t// _ap.setLabel(_attack_label);\n\t// _ap.setTitle(_title);\n\t// _ap.setDescription(_description);\n\n\t//return arg;\n\n\t// Approch 3 \n\tArgumentProperty _ap(_label, _title, _description);\n\treturn addArgument(_ap);\n}\n\n__inline\nAttack DungAF::addAttack(const std::pair<Argument&, Argument&>& _edge,\n\t\t\t             const AttackProperty& _attProp /*= AttackProperty()*/)\n{\n\tAttack atk;\n\tbool  inserted = false;\n\tboost::tie(atk, inserted) = boost::add_edge(_edge.first, _edge.second, _attProp, m_ag);\n\n\tassert(inserted);  // Was this attack inserted?\n\n\treturn atk;\n}\n\n__inline\nAttack DungAF::addAttack(const Argument& _arg1, const std::string& _arg2_label,\n\t\t\t\t\t\t const AttackProperty& _attProp /*= AttackProperty()*/)\n{\n\tAttack atk;\n\tbool  inserted = false;\n\tboost::tie(atk, inserted) = add_edge(_arg1, _arg2_label, _attProp, m_ag);\n\n\tassert(inserted);  // Was this attack inserted?\n\n\treturn atk;\n}\n\n__inline\nAttack DungAF::addAttack(const std::string& _arg1_label, const Argument& _arg2,\n\t\t\t\t\t\t const AttackProperty& _attProp /*= AttackProperty()*/)\n{\n\tAttack atk;\n\tbool  inserted = false;\n\tboost::tie(atk, inserted) = add_edge(_arg1_label, _arg2, _attProp, m_ag);\n\n\tassert(inserted);  // Was this attack inserted?\n\n\treturn atk;\n}\n\n__inline\nAttack DungAF::addAttack(const Argument& _arg1, const Argument& _arg2, \n\t\t\t\t\t\t const AttackProperty& _attProp /*= AttackProperty()*/)\n{\n\tAttack atk;\n\tbool  inserted = false;\n\tboost::tie(atk, inserted) = boost::add_edge(_arg1, _arg2, _attProp, m_ag);\n\n\tassert(inserted);  // Was this attack inserted?\n\n\treturn atk;\n}\n\n__inline\nAttack DungAF::addAttack(const std::string& _arg1_label, const std::string& _arg2_label, \n\t\t\t\t\t\t const AttackProperty& _attProp /*= AttackProperty()*/)\n{\n\tAttack atk;\n\tbool  inserted = false;\n\tboost::tie(atk, inserted) = add_edge(_arg1_label, _arg2_label, _attProp, m_ag);\n\n\tassert(inserted);  // Was this attack inserted?\n\n\treturn atk;\n}\n\ninline\nconst ArgumentProperty& DungAF::getArgumentProperty(const Argument& _arg) const\n{\n\treturn m_ag[_arg];\n}\n\n__inline\nconst ArgumentProperty& DungAF::getArgumentProperty(const std::string& _arg_label) const\n{\n\treturn m_ag[*find_vertex(_arg_label, m_ag)];\n}\n\ninline\nconst AttackProperty& DungAF::getAttackProperty(const Attack& _atk) const\n{\n\treturn m_ag[_atk];\n}\n\nbitvector DungAF::set2bv(const set<Argument>& sa) const\n{\n\tbitvector bv( boost::num_vertices(m_ag), 0 );\n\n\tset<Argument>::iterator sa_itr;\n\tfor (sa_itr = sa.begin(); sa_itr != sa.end(); sa_itr++)\t{\n\t\tbv.set(m_idxMap[*sa_itr], true);\n\t}\n\n\treturn bv;\n}\n\nset<Argument> DungAF::bv2set(const bitvector& bv) const\n{\n\tassert(bv.size() == boost::num_vertices(m_ag));\n\tset<Argument> sa;\n\tfor (size_type i=bv.find_first(); i < bitvector::npos; i=bv.find_next(i)) {\n\t\tsa.insert(boost::get(m_idxMap, i));\n\t}\n\n\treturn sa;\n}\n\nstd::string DungAF::toString() const\n{\n\tstd::string s(\"[\");\n\n\t// arguments to string\n\ts += \"{\";\n\tstd::pair<ArgumentIterator, ArgumentIterator> ai = vertices(m_ag);\n\tif ( ai.first != ai.second )\n\t{\n\t\tArgumentIterator ait = ai.first;\n\t\ts +=  m_ag[*ait].label; \n\n\t\tfor ( ++ait; ait!=ai.second; ++ait) {\n\t\t\ts += ( \",\" + m_ag[*ait].label); \n\t\t}\n\t}\n\ts += \"},\";\n\n\t// Attacks to string\n\ts += \"{\";\n\tstd::pair<AttackIterator, AttackIterator> ei = edges(m_ag);\n\tif( ei.first != ei.second )\n\t{\n\t\tAttackIterator eit = ei.first;\n\t\ts += \"(\" + m_ag[source(*eit, m_ag)].label + \",\"\n\t\t\t + m_ag[target(*eit, m_ag)].label + \")\";\n\n\t\tfor (++eit; eit != ei.second; ++eit) {\n\t\t\ts += \",(\" + m_ag[source(*eit, m_ag)].label + \",\"\n\t\t\t\t + m_ag[target(*eit, m_ag)].label + \")\";\n\t\t}\n\t}\n\ts += \"}\";\n\n\ts += \"]\"; \n\n\treturn s;\n}\n\nbitmatrix DungAF::getAttackMatrix() const\n{\n\tbitmatrix bm( boost::num_vertices(m_ag) );\n\n\tstd::pair<AttackIterator, AttackIterator> ei = edges(m_ag);\n\tfor (AttackIterator eit = ei.first; eit != ei.second; ++eit) {\n\t\tsize_type i = m_idxMap[target(*eit, m_ag)];\n\t\tsize_type j = m_idxMap[source(*eit, m_ag)];\n\n\t\tbm[i][j] = true;\t\t\n\t}\n\n\treturn bm;\n}\n\ninline\nsize_type DungAF::getNumberOfArguments() const\n{\n\treturn boost::num_vertices(m_ag);\n}\n\nvoid DungAF::showSet(const set<Argument>& sa, std::ostream& os /*= std::cout*/) const\n{\n\tstd::set<Argument>::iterator sa_itr;\n\tbool is_first = true;\n\n\tos << LEFT_LIMITER;\n\tfor (sa_itr = sa.begin(); sa_itr != sa.end(); sa_itr++)\n\t{\n\t\tif (is_first)\n\t\t{\n\t\t\tos<< m_ag[*sa_itr].label;\n\t\t\tis_first = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tos << DELIMITER << m_ag[*sa_itr].label;\n\t\t}\n\t}\n\n\tos << RIGHT_LIMITER << std::endl;\n}\n\nvoid DungAF::outputBv(const bitvector& _bv, std::ostream& os /*= std::cout*/) const\n{\n\tbool first = true;\n\n\tos << LEFT_LIMITER;\n\tfor ( size_type i = _bv.find_first(); \n\t\ti != bitvector::npos; \n\t\ti = _bv.find_next(i) )\n\t{\n\t\tif(first){\n\t\t\tfirst = false;\n\t\t}else{\n\t\t\tos << DELIMITER; // \",\"\n\t\t}\n\t\tos << m_ag[boost::get(m_idxMap, i)].label;\n\t}\n\tos << RIGHT_LIMITER;\n}\n\nvoid DungAF::outputBvSet(const std::set< bitvector >& _bv_set, std::ostream& os /*= std::cout*/) const\n{\n\tos << LEFT_LIMITER;\n\n\tbool first = true;\n\n\tstd::set<bitvector>::iterator _bv_set_itr = _bv_set.begin();\t\n\n\tfor ( ; _bv_set_itr != _bv_set.end(); ++_bv_set_itr) {\n\t\tif(first){\n\t\t\tfirst = false;\n\t\t}else{\n\t\t\tos << DELIMITER; // \",\"\n\t\t}\n\t\toutputBv(*_bv_set_itr, os);\n\t}\n\n\tos << RIGHT_LIMITER;\n}\n\ninline\nvoid DungAF::clear()\n{\n\tm_ag.clear();\n}\n\nset<string> DungAF::bv2label_set(const bitvector& _bv) const\n{\n\tset<string> _ss;\n\tfor (size_type i = _bv.find_first(); i != bitvector::npos; i = _bv.find_next(i))\n\t{\n\t\t_ss.insert( m_ag[boost::get(m_idxMap, i)].label );\n\t}\n\n\treturn _ss;\n}\n\nbitvector DungAF::labelSet2bv(const set<string>& _ls) const\n{\n\tbitvector _bv( getNumberOfArguments(), 0); // bitvector with 0s\n\tset<string>::iterator _ls_itr;\n\tfor (_ls_itr = _ls.begin(); _ls_itr != _ls.end(); ++_ls_itr)\n\t{\n\t\t_bv[getArgumentIdx(*_ls_itr)] = true;\n\n\t\t// This approach is not safe, and can be solved by boost::optional.\n\t\t// _bv[ m_idxMap[*find_vertex(*_ls_itr, m_ag)] ] = true;\n\t}\n\n\treturn _bv;\n}\n\nset<bitvector> DungAF::label_ext2bv_ext(const set< set<string> >& _le) const\n{\n\tset<bitvector> _sb;\n\tset< set<string> >::iterator _le_itr;\n\tfor (_le_itr = _le.begin(); _le_itr != _le.end(); ++_le_itr)\n\t{\n\t\t_sb.insert( labelSet2bv( *_le_itr ) );\n\t}\n\n\treturn _sb;\n}\n\nstd::vector<std::string> DungAF::getArgumentLabels() const\n{\n\tvector<string> _label_vector;\n\tfor (size_type i=0; i<getNumberOfArguments(); ++i)\n\t{\n\t\t_label_vector.push_back(m_ag[boost::get(m_idxMap, i)].label);\n\t}\n\n\treturn _label_vector;\n}\n\nsize_type DungAF::getArgumentIdx(const std::string& _arg_label) const\n{\n\t// argumatrix::IdxMapType::npos;\n\t// boost::vertex_index_t::\n\tboost::optional<Argument> opt_arg = find_vertex(_arg_label, m_ag);\n\tif ( opt_arg ) { return m_idxMap[*opt_arg]; }\n\telse {\n\t\tstd::cerr << \"Argument [\" << _arg_label << \"] is not in this framework.\" << endl;\n\t\texit(1);\n\t}\n}\n\nsize_type DungAF::getArgumentIdx(const Argument& _arg) const\n{\n\treturn m_idxMap[_arg];\n}\n\n} // namespace argumatrix\n\n\n\n#endif  //DUNG_ARGUMENTATION_FRAMEWORK_HPP", "meta": {"hexsha": "f16b7ca6d57793202ffc0b9d9a99618c60cb79e7", "size": 15262, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dung_theory/DungAF.hpp", "max_stars_repo_name": "xixicat/argmat-clpb", "max_stars_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-01-09T21:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-28T05:52:14.000Z", "max_issues_repo_path": "dung_theory/DungAF.hpp", "max_issues_repo_name": "xixicat/argmat-clpb", "max_issues_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dung_theory/DungAF.hpp", "max_forks_repo_name": "xixicat/argmat-clpb", "max_forks_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_forks_repo_licenses": ["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.2107208872, "max_line_length": 133, "alphanum_fraction": 0.6856899489, "num_tokens": 4133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.038466193947322924, "lm_q1q2_score": 0.011822893088003791}}
{"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 SHAPEFUNCTIONCACHE_HH\n#define SHAPEFUNCTIONCACHE_HH\n#include <map>\n#include <tuple>\n\n#include \"boost/multi_array.hpp\"\n#include \"boost/signals2.hpp\"\n\n#ifndef KASKADE_SEQUENTIAL\n#include \"boost/thread.hpp\"\n#include \"utilities/threading.hh\"\n#endif\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/range_c.hpp>\n\n#include <boost/fusion/algorithm.hpp>\n#include <boost/fusion/sequence.hpp>\n\n#include \"dune/geometry/quadraturerules.hh\"\n#include \"dune/istl/bvector.hh\"\n\n#include \"fem/fetransfer.hh\"\n#include \"fem/pshapefunctions.hh\"\n\n\n//---------------------------------------------------------------------\nnamespace Kaskade\n{\n  /**\n   * \\ingroup fem\n   * \\brief A class that stores values, gradients, and Hessians of evaluated\n   * FE functions / test functions.\n   *\n   * This is the argument type used during assembly to provide test\n   * function values and derivatives to variational functionals.\n   */\n  template <typename Scalar, int dim, int components=1>\n  struct VariationalArg\n  {\n    VariationalArg(): gradient(derivative) {}\n    \n    /**\n     * \\brief Constructor\n     * \n     * This initializes the value as provied and initializes derivative and hessian to zero.\n     */\n    VariationalArg(Dune::FieldVector<Scalar,components> const& value_)\n    : value(value_), derivative(0), gradient(derivative), hessian(0) {}\n    \n    \n    VariationalArg(Dune::FieldVector<Scalar,components> const& value_,\n                   Dune::FieldMatrix<Scalar,components,dim> const& derivative_)\n    : value(value_), derivative(derivative_), gradient(derivative), hessian(0) {}\n    \n    VariationalArg(Dune::FieldVector<Scalar,components> const& value_,\n                   Dune::FieldMatrix<Scalar,components,dim> const& derivative_,\n                   Tensor3<Scalar,components,dim,dim> const& hessian_)\n    : value(value_), derivative(derivative_), gradient(derivative), hessian(hessian_) {}\n    \n    // required due to gradient backwards compatibility reference that has always to refer to the *own* derivatives vector\n    VariationalArg(VariationalArg<Scalar,dim,components> const& other)\n    : value(other.value), derivative(other.derivative), gradient(derivative), hessian(other.hessian) {}\n    VariationalArg& operator=(VariationalArg<Scalar,dim,components> const& other) { value = other.value; derivative = other.derivative; hessian = other.hessian; return *this; }\n    \n    Dune::FieldVector<Scalar,components>     value;\n    Dune::FieldMatrix<Scalar,components,dim> derivative;\n    Dune::FieldMatrix<Scalar,components,dim>& gradient; // deprecated, reference for backwards compatibility only\n    Tensor3<Scalar,components,dim,dim>       hessian;\n  };\n\n  //---------------------------------------------------------------------\n  //---------------------------------------------------------------------\n\n  /**\n   * \\ingroup fem\n   * \\brief This class caches values and derivatives of shape functions at quadrature points.\n   *\n   * Limitations are:\n   *\n   * - The number of components of shape functions is limited (to one\n   *   below the template parameter ComponentsEnd).\n   *\n   * - Since evaluating the shape functions may modify the internal cache\n   *   data structure, this is NOT thread safe. Every thread should use\n   *   its own ShapeFunctionCache.\n   *\n   * \\tparam G the grid type \n   * \\tparam T the scalar field type\n   * \n   * \\todo make shape function cache independent of grid type - only coordinate type and dimension are required\n   */\n  template <class G, class T, int ComponentsEnd=4>\n  class ShapeFunctionCache\n  {\n\n  private:\n    typedef typename boost::mpl::range_c<int,1,ComponentsEnd>::type ComponentRange;\n\n    // This is a functor that, given a number of\n    // components (a boost::mpl integer), defines an associative\n    // container type with a tuple (shape function set address,\n    // quadrature rule address) as key\n    // and a twodimensional boost::multi_array of pairs of vector and\n    // matrix with given components as value type.\n    struct MakeMapType {\n      template <class Int>\n      auto operator()(Int i) \n      {\n        static int const nComp = Int::value;\n\n        typedef VariationalArg<T,G::dimension,nComp> EntryType;\n        typedef boost::multi_array<EntryType,2> DataType;\n        typedef ShapeFunctionSet<typename G::ctype,G::dimension,T,Int::value> Sfs;\n        typedef std::tuple<Sfs const*,void const*> KeyType;\n        return std::map<KeyType,DataType>();\n      }\n    };\n\n    typedef typename boost::fusion::result_of::as_vector<\n                typename boost::fusion::result_of::transform<ComponentRange,MakeMapType>::type\n        >::type MapsType;\n\n  public:\n\n    /**\n     * \\brief Defines the type returned by evaluate(sfs,qr,subId).\n     *\n     * This is a two-dimensional array type to be indexed by integration point and shape function number. The entries\n     * are VariationalArg structures containing shape function values, derivatives, and hessians at the integration points.\n     */\n    template <int nComp>\n    struct DataType \n    {\n      typedef typename std::result_of<MakeMapType(boost::mpl::int_<nComp>)>::type::mapped_type type;\n    };\n    \n    /**\n     * \\brief Defines the type returned by evaluate(sfs,qr,ip,subId).\n     *\n     * This is a one-dimensional array type to be indexed by shape function number. The entries\n     * are pairs of shape function values and derivatives at the integration points.\n     */\n    template <int nComp>\n    struct LocalDataType \n    {\n      typedef typename DataType<nComp>::type::template const_array_view<1>::type type;\n    };\n\n    \n    /**\n     * \\brief Evaluate comp-th component of isf-th shape function of the shape\n     * function set sfs ath the ip-th integration point of quadrature\n     * rule qr.\n     *\n     * This method is explicitly NOT thread safe. Use one cache object per thread.\n     */\n    template <int nComp, int subDim>\n    Dune::FieldVector<T,nComp> evaluateFunction(ShapeFunctionSet<typename G::ctype,G::dimension,T,nComp> const& sfs, int isf,\n                                                Dune::QuadratureRule<typename G::ctype,subDim> const& qr, int ip, int subId)\n    {\n      assert(0<=isf && isf<sfs.size());\n      assert(0<=ip && ip<qr.size());\n      return get(sfs,qr,subId)[ip][isf].value;\n    }\n\n    /**\n     * \\brief Evaluate derivative of comp-th component of isf-th shape function\n     * of the shape function set sfs ath the ip-th integration point of\n     * quadrature rule qr.\n     *\n     * This method is explicitly NOT thread safe. Use one cache object per thread.\n     */\n    template <int nComp, int subDim>\n    Dune::FieldMatrix<T,nComp,G::dimension> const& evaluateDerivative(ShapeFunctionSet<typename G::ctype,G::dimension,T,nComp> const& sfs, int isf,\n                                                                      Dune::QuadratureRule<typename G::ctype,subDim> const& qr, int ip,\n                                                                      int subId)\n    {\n      assert(0<=isf && isf<sfs.size());\n      assert(0<=ip && ip<qr.size());\n      return get(sfs,qr,subId)[ip][isf].derivative;\n    }\n\n    /**\n     * \\brief Returns the values of all shape functions at given integration point. \n     *\n     * The return value can be indexed by shape function number,\n     * yielding a pair of value and derivative of the shape function's\n     * component.\n     *\n     * E.g., the value can be obtained by evaluate(sfs,qr,ip,subId)[isf].value\n     *\n     * This method is explicitly NOT thread safe. Use one cache object per thread.\n     *\n     * \\param subId the index of the subentity in the cell (has to be between 0 and the maximum supported subentity number)\n     */\n    template <int nComp, int subDim>\n    typename LocalDataType<nComp>::type\n    evaluate(ShapeFunctionSet<typename G::ctype,G::dimension,T,nComp> const& sfs,\n             Dune::QuadratureRule<typename G::ctype,subDim> const& qr, int ip, int subId)\n    {\n      typedef typename DataType<nComp>::type DType;\n      typedef typename DType::index_range range;\n      typename DType::index_gen indices;\n      assert(sfs.size()>=0);\n      return get(sfs,qr,subId)[indices[ip][range(0,sfs.size())]];\n    }\n\n  \n   /**\n    * \\brief Returns the values of all shape functions. \n    *\n    * The return value can be indexed by shape function number,\n    * yielding a pair of value and derivative of the shape function's\n    * component.\n    *\n    * E.g., the value can be obtained by evaluate(sfs,qr,subId)[ip][isf].value\n    * \n    * This method is explicitly NOT thread safe. Use one cache object per thread.\n    *\n    * \\param subId the index of the subentity in the cell (has to be between 0 and the maximum supported subentity number)\n    */\n   template <int nComp, int subDim>\n   typename DataType<nComp>::type const& evaluate(ShapeFunctionSet<typename G::ctype,G::dimension,T,nComp> const& sfs,\n                                                  Dune::QuadratureRule<typename G::ctype,subDim> const& qr, int subId) \n   {\n     return get(sfs,qr,subId);\n   }\n   \n   \n \n  /**\n   * \\brief Reports the maximum subentity number that is allowed.\n   */\n  int maximumSubentityIndex() const \n  {\n    return maxSubId;\n  }\n\n  private:\n    // TODO: use boost::container::flat_map from boost 1.49 on\n    static int const maxSubId = 11; // 12 edges in a cube - that's the upper limit (up to 3d, of course...)\n    \n    // For each subentity number, we maintain a different cache for direct access\n    MapsType caches[maxSubId+1];\n    \n    template <int nComp, int subDim>\n    typename DataType<nComp>::type const&\n    get(ShapeFunctionSet<typename G::ctype,G::dimension,T,nComp> const& sfs, Dune::QuadratureRule<typename G::ctype,subDim> const& qr, int subId)\n    {\n      assert(0<=subId && subId<=maxSubId);\n      using MapType = typename std::result_of<MakeMapType(boost::mpl::int_<nComp>)>::type;\n      typedef typename MapType::key_type KeyType;\n      typedef typename DataType<nComp>::type DType;\n      MapType& cache = boost::fusion::at_c<nComp-1>(caches[subId]);\n\n      typename MapType::const_iterator i = cache.find(KeyType(&sfs,&qr));\n      \n      // check whether the shape functions' values are already available\n      if (i==cache.end()) {\n        // No, they are not. Evaluate shape functions and store the result.\n        Dune::FieldVector<T,G::dimension> pos;\n        auto const& refElem = sfs.referenceElement();\n        assert(sfs.size()>=0);\n        DType data(boost::extents[qr.size()][sfs.size()]);\n#ifndef KASKADE_SEQUENTIAL     \n        if(G::dimension != subDim)\n          for (int isf=0; isf<sfs.size(); ++isf)\n            for (int ip=0; ip<qr.size(); ++ip) {\n              {\n                boost::mutex::scoped_lock lock(refElementMutex);\n                pos = refElem.template geometry<G::dimension-subDim>(subId).global(qr[ip].position());\n              }\n              data[ip][isf].value = sfs[isf].evaluateFunction(pos);\n              data[ip][isf].derivative = sfs[isf].evaluateDerivative(pos);\n              data[ip][isf].hessian = sfs[isf].evaluate2ndDerivative(pos);\n            }\n        else\n#endif\n          for (int isf=0; isf<sfs.size(); ++isf)\n            for (int ip=0; ip<qr.size(); ++ip) {\n              pos = refElem.template geometry<G::dimension-subDim>(subId).global(qr[ip].position());\n              data[ip][isf].value = sfs[isf].evaluateFunction(pos);\n              data[ip][isf].derivative = sfs[isf].evaluateDerivative(pos);\n              data[ip][isf].hessian = sfs[isf].evaluate2ndDerivative(pos);\n            }\n\n        // store the values, obtaining an iterator pointing to the newly inserted values\n        i = cache.insert(cache.begin(),typename MapType::value_type(KeyType(&sfs,&qr),data));\n      }\n      \n      // From here on, the values are in the map (at the position pointed to by i).\n      return i->second;\n    }\n  };\n} // end of namespace Kaskade\n//---------------------------------------------------------------------\n//---------------------------------------------------------------------\n\n\n#endif\n", "meta": {"hexsha": "7dd7c266bc3260616738053f7859ca4ff6578bd7", "size": 12877, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/shapefunctioncache.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/shapefunctioncache.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/shapefunctioncache.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": 41.0095541401, "max_line_length": 176, "alphanum_fraction": 0.6056534907, "num_tokens": 3050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.026759285998981808, "lm_q1q2_score": 0.011818854276609626}}
{"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_CLOSENESS_CENTRALITY_HPP\n#define BOOST_GRAPH_CLOSENESS_CENTRALITY_HPP\n\n#include <boost/graph/detail/geodesic.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/concept/assert.hpp>\n\nnamespace boost\n{\ntemplate <typename Graph,\n          typename DistanceType,\n          typename ResultType,\n          typename Reciprocal = detail::reciprocal<ResultType> >\nstruct closeness_measure\n    : public geodesic_measure<Graph, DistanceType, ResultType>\n{\n    typedef geodesic_measure< Graph, DistanceType, ResultType> base_type;\n    typedef typename base_type::distance_type distance_type;\n    typedef typename base_type::result_type result_type;\n\n    result_type operator ()(distance_type d, const Graph&)\n    {\n        BOOST_CONCEPT_ASSERT(( NumericValueConcept<DistanceType> ));\n        BOOST_CONCEPT_ASSERT(( NumericValueConcept<ResultType> ));\n        BOOST_CONCEPT_ASSERT(( AdaptableUnaryFunctionConcept<Reciprocal,ResultType,ResultType> ));\n        return (d == base_type::infinite_distance())\n            ? base_type::zero_result()\n            : rec(result_type(d));\n    }\n    Reciprocal rec;\n};\n\ntemplate <typename Graph, typename DistanceMap>\ninline closeness_measure<\n        Graph, typename property_traits<DistanceMap>::value_type, double,\n        detail::reciprocal<double> >\nmeasure_closeness(const Graph&, DistanceMap)\n{\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n    return closeness_measure<Graph, Distance, double, detail::reciprocal<double> >();\n}\n\ntemplate <typename T, typename Graph, typename DistanceMap>\ninline closeness_measure<\n        Graph, typename property_traits<DistanceMap>::value_type, T,\n        detail::reciprocal<T> >\nmeasure_closeness(const Graph&, DistanceMap)\n{\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n    return closeness_measure<Graph, Distance, T, detail::reciprocal<T> >();\n}\n\ntemplate <typename T, typename Graph, typename DistanceMap, typename Reciprocal>\ninline closeness_measure<\n        Graph, typename property_traits<DistanceMap>::value_type, T,\n        Reciprocal>\nmeasure_closeness(const Graph&, DistanceMap)\n{\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n    return closeness_measure<Graph, Distance, T, Reciprocal>();\n}\n\ntemplate <typename Graph,\n          typename DistanceMap,\n          typename Measure,\n          typename Combinator>\ninline typename Measure::result_type\ncloseness_centrality(const Graph& g,\n                     DistanceMap dist,\n                     Measure measure,\n                     Combinator combine)\n{\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph> ));\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<DistanceMap,Vertex> ));\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n    BOOST_CONCEPT_ASSERT(( NumericValueConcept<Distance> ));\n    BOOST_CONCEPT_ASSERT(( DistanceMeasureConcept<Measure,Graph> ));\n\n    Distance n = detail::combine_distances(g, dist, combine, Distance(0));\n    return measure(n, g);\n}\n\ntemplate <typename Graph, typename DistanceMap, typename Measure>\ninline typename Measure::result_type\ncloseness_centrality(const Graph& g, DistanceMap dist, Measure measure)\n{\n    BOOST_CONCEPT_ASSERT(( GraphConcept<Graph> ));\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<DistanceMap,Vertex> ));\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n\n    return closeness_centrality(g, dist, measure, std::plus<Distance>());\n}\n\ntemplate <typename Graph, typename DistanceMap>\ninline double closeness_centrality(const Graph& g, DistanceMap dist)\n{ return closeness_centrality(g, dist, measure_closeness(g, dist)); }\n\ntemplate <typename T, typename Graph, typename DistanceMap>\ninline T closeness_centrality(const Graph& g, DistanceMap dist)\n{ return closeness_centrality(g, dist, measure_closeness<T>(g, dist)); }\n\ntemplate <typename Graph,\n          typename DistanceMatrixMap,\n          typename CentralityMap,\n          typename Measure>\ninline void\nall_closeness_centralities(const Graph& g,\n                           DistanceMatrixMap dist,\n                           CentralityMap cent,\n                           Measure measure)\n{\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph> ));\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<DistanceMatrixMap,Vertex> ));\n    typedef typename property_traits<DistanceMatrixMap>::value_type DistanceMap;\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<DistanceMap,Vertex> ));\n    BOOST_CONCEPT_ASSERT(( WritablePropertyMapConcept<CentralityMap,Vertex> ));\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n    typedef typename property_traits<CentralityMap>::value_type Centrality;\n\n    typename graph_traits<Graph>::vertex_iterator i, end;\n    for(boost::tie(i, end) = vertices(g); i != end; ++i) {\n        DistanceMap dm = get(dist, *i);\n        Centrality c = closeness_centrality(g, dm, measure);\n        put(cent, *i, c);\n    }\n}\n\ntemplate <typename Graph,\n          typename DistanceMatrixMap,\n          typename CentralityMap>\ninline void\nall_closeness_centralities(const Graph& g,\n                            DistanceMatrixMap dist,\n                            CentralityMap cent)\n{\n    BOOST_CONCEPT_ASSERT(( GraphConcept<Graph> ));\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<DistanceMatrixMap,Vertex> ));\n    typedef typename property_traits<DistanceMatrixMap>::value_type DistanceMap;\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<DistanceMap,Vertex> ));\n    typedef typename property_traits<DistanceMap>::value_type Distance;\n    typedef typename property_traits<CentralityMap>::value_type Result;\n\n    all_closeness_centralities(g, dist, cent, measure_closeness<Result>(g, DistanceMap()));\n}\n\n} /* namespace boost */\n\n#endif\n", "meta": {"hexsha": "44d478ab2bad304732e0ab312fb7e23cda8a8e74", "size": 6316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/closeness_centrality.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/closeness_centrality.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/closeness_centrality.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 39.7232704403, "max_line_length": 98, "alphanum_fraction": 0.7352754908, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906414693485, "lm_q2_score": 0.025178840877671055, "lm_q1q2_score": 0.011803604966498068}}
{"text": "#include <string>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <stdint.h>\n#include \"opencv2/core/core.hpp\"\n#include \"ferLocalFunctions.h\"\n#include <fstream>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n#include <fstream>\n#include <Windows.h>\n#include <map>\n#include <boost/filesystem.hpp>\n\nnamespace fer\n{\n\n    using namespace std;\n    using namespace cv;\n\n    std::string to_string(int val)\n    {\n        std::stringstream str;\n        str << val;\n        return str.str();\n    }\n\n    vector<string> get_all_files_names_within_folder(string folder)\n    {\n        vector<string> names;\n\n        namespace fs = boost::filesystem;\n        fs::directory_iterator end_iter;\n        if (fs::exists(folder) && fs::is_directory(folder))\n        {\n            for (fs::directory_iterator dir_iter(folder) ; dir_iter != end_iter ; ++dir_iter)\n            {\n                if (fs::is_regular_file(dir_iter->status()))\n                {\n                }\n            }\n        }\n\n        return names;\n    }\n\n\n    Mat RV_readCSVMat(string csvFrameName, int lin, int col)\n    {\n        Mat output(lin, col, CV_64FC1);\n        ifstream inFile(csvFrameName);\n        string line;\n        int linenum = 0;\n        while (getline(inFile, line))\n        {\n            linenum++;\n            //cout << \"\\nLine #\" << linenum << \":\" << endl;\n            istringstream linestream(line);\n            string item;\n            int itemnum = 0;\n            while (getline(linestream, item, ','))\n            {\n                itemnum++;\n                //cout << \"Item #\" << itemnum << \": \" << item << endl;\n                double temp = (double)atof(item.c_str());\n                output.at<double>(linenum - 1, itemnum - 1) = (double)temp;\n            }\n        }\n        return output;\n    }\n\n    void RV_readParamList(const string foldername, paramList *p)\n    {\n        cout << \"Reading params from: \" << foldername << \"...\";\n        ifstream in(foldername + \"config.txt\");\n        string dummy;\n\n        if (in.is_open()) {\n\n            in >> dummy;\n            in >> p->d;\n\n            in >> dummy;\n            in >> p->patchSize;\n\n            in >> dummy;\n            in >> p->stride;\n\n            in >> dummy;\n            in >> p->featSize;\n\n            in >> dummy;\n            in >> p->noPatches;\n\n            in >> dummy;\n            in >> p->noChannels;\n\n            in >> dummy;\n            in >> p->noTrees;\n\n        }\n        else {\n            cerr << \"File not found \" << foldername + \"config.txt\" << endl;\n            exit(-1);\n        }\n        in.close();\n\n        Mat dummyMat(p->d, 16, CV_64FC1);\n        dummyMat.setTo(0);\n        for (int i = 0; i < p->noPatches; i++)\n        {\n            p->patchFeats.push_back(dummyMat);\n        }\n\n        Mat paramsPatchCoords = RV_readCSVMat(foldername + \"paramsPatchCoords.csv\", p->noPatches, 2);\n        p->patchCoords = paramsPatchCoords;\n\n        for (int i = 0; i < p->noPatches; i++)\n        {\n            // rectangle coordinates are imported from Matlab as they are, which means they obey Matlab indexing (starting from 1)\n            // this will be taken care of explicitly at feature computation stage ...\n            Mat patchFeatsAux = RV_readCSVMat(foldername + \"patchFeats/patchFeats_\" + to_string(i + 1) + \".csv\", p->d, 16);\n            Mat patchFeatsAuxInt(patchFeatsAux.rows, patchFeatsAux.cols, CV_8UC1);\n            patchFeatsAux.convertTo(patchFeatsAuxInt, CV_8UC1);\n            p->patchFeats[i] = patchFeatsAuxInt;\n        }\n\n        cout << \"done!\" << endl;\n        cout << endl << \"------------------------------------\" << endl;\n        cout << \"Parameter List:\" << endl << endl;\n        cout << \"d:             \" << p->d << endl;\n        cout << \"patchSize:     \" << p->patchSize << endl;\n        cout << \"stride:        \" << p->stride << endl;\n        cout << \"featSize:      \" << p->featSize << endl;\n        cout << \"noPatches:     \" << p->noPatches << endl;\n        cout << \"noChannels:    \" << p->noChannels << endl;\n        cout << endl << \"------------------------------------\" << endl << endl;\n    }\n\n    vector<vector<randomTree>> RV_readAllForests(string forestDir, paramList params)\n    {\n        vector<vector<randomTree>> allForests(params.noPatches, vector<randomTree>(params.noTrees));\n        cout << \"Reading forests from: \" << forestDir << \"...\";\n        for (int i = 0; i < params.noPatches; i++)\n        {\n            for (int j = 0; j < params.noTrees; j++)\n            {\n                Mat dummySize = RV_readCSVMat(forestDir + \"patch_\" + to_string(i + 1) + \"_tree_\" + to_string(j + 1) + \"_size.csv\", 1, 1);\n                Mat dummyMat = RV_readCSVMat(forestDir + \"patch_\" + to_string(i + 1) + \"_tree_\" + to_string(j + 1) + \".csv\", 4, (int)dummySize.at<double>(0, 0));\n                allForests[i][j].cutVar.reserve(dummyMat.cols);\n                allForests[i][j].cutValue.reserve(dummyMat.cols);\n                allForests[i][j].rightChild.reserve(dummyMat.cols);\n                allForests[i][j].leafVal.reserve(dummyMat.cols);\n                dummyMat.row(0).copyTo(allForests[i][j].cutVar);\n                dummyMat.row(1).copyTo(allForests[i][j].cutValue);\n                dummyMat.row(2).copyTo(allForests[i][j].rightChild);\n                dummyMat.row(3).copyTo(allForests[i][j].leafVal);\n                //cout << \"patch: \" << i << \" tree: \" << j << endl;\n            }\n        }\n        cout << \"done!\" << endl;\n        return allForests;\n    }\n\n    vector<double> RV_computeHist(vector<double> vec, int noBins)\n    {\n        // supposedly vec has exactly noBins unique values\n        const double eps = 1.0 / vec.size();\n        vector<double> out(noBins);\n        out.assign(noBins, 0);\n        for (int i = 0; i < (int)vec.size(); i++)\n        {\n            out[(int)vec[i] - 1] += eps;\n        }\n        return out;\n    }\n\n    vector<double> RV_testForest(Mat localData, vector<randomTree> &localForest, paramList params, int numberOfClasses)\n    {\n        vector<double> votes(params.noTrees);\n        votes.assign(params.noTrees, 0);\n        for (int k = 0; k < params.noTrees; k++)\n        {\n            randomTree tree = localForest[k];\n            int currNode = 0;\n            while (tree.cutVar[currNode] > 0)\n            {\n                if (localData.at<double>(tree.cutVar[currNode] - 1) > tree.cutValue[currNode])\n                {\n                    currNode = tree.rightChild[currNode];\n                }\n                else\n                {\n                    currNode = tree.rightChild[currNode] - 1;\n                }\n            }\n            votes[k] = tree.leafVal[currNode];\n        }\n        vector<double> probs = RV_computeHist(votes, numberOfClasses);\n        return probs;\n    }\n\n\n    Rect RV_getBoundingBox(const Mat &im3D, paramList p) {\n\n        Rect bbox;\n        int min_x = im3D.cols;\n        int min_y = im3D.rows;\n        int max_x = 0;\n        int max_y = 0;\n        int p_width = p.patchSize;\n        int p_height = p.patchSize;\n\n        for (int y = 0; y < im3D.rows; y++)\n        {\n            const double *Mi = im3D.ptr<double>(y);\n            for (int x = 0; x < im3D.cols; x++) {\n\n                if (Mi[x] > 0) {\n\n                    min_x = MIN(min_x, x);\n                    min_y = MIN(min_y, y);\n                    max_x = MAX(max_x, x);\n                    max_y = MAX(max_y, y);\n                }\n\n            }\n        }\n\n        int new_w = max_x - min_x;\n        int new_h = max_y - min_y;\n\n        bbox.x = MIN(im3D.cols - 1, MAX(0 , min_x));\n        bbox.y = MIN(im3D.rows - 1, MAX(0 , min_y));\n\n        //int new_w = max_x - min_x + p_width;\n        //int new_h = max_y - min_y + p_height;\n\n        //bbox.x = MIN( im3D.cols-1, MAX( 0 , min_x - p_width/2 ) );\n        //bbox.y = MIN( im3D.rows-1, MAX( 0 , min_y - p_height/2) );\n\n        bbox.width  = MAX(0, MIN(new_w, im3D.cols - bbox.x));\n        bbox.height = MAX(0, MIN(new_h, im3D.rows - bbox.y));\n\n        return bbox;\n    }\n\n    double RV_computeNorm(vector<double> vec1, vector<double> vec2)\n    {\n        double result = 0;\n        int dim = vec1.size();\n        vector<double> diff(dim);\n        double sumSq = 0;\n        for (int i = 0; i < dim; i++)\n        {\n            diff[i] = vec1[i] - vec2[i];\n            sumSq += pow(diff[i], 2);\n        }\n        result = sqrt(sumSq);\n        return result;\n    }\n\n    double RV_computeMean(vector<double> vec)\n    {\n        double sum = 0;\n        for (int k = 0; k < (int)vec.size(); k++)\n        {\n            sum += vec[k];\n        }\n        return sum / vec.size();\n    }\n\n    Mat meanShift(Mat dataPts, double bandWidth, int *maxClustPointer)\n    {\n        *maxClustPointer = -1;\n        int biggestClusterSize = 0;\n        int numDim = dataPts.cols;\n        int numPts = dataPts.rows;\n        int numClust = -1;\n        double bandSq = bandWidth * bandWidth;\n        std::vector<int> initPtInds(numPts);\n        for (int k = 0; k < (int)initPtInds.size(); k++)\n            initPtInds[k] = k;\n\n        double stopThresh = 1e-3 * bandWidth;\n\n        Mat clustCent(0, numDim, CV_64FC1);\n\n        vector<bool> beenVisitedFlag(numPts);\n        int numInitPts = numPts;\n        //vector<int> clusterVotes(numPts);\n\n        while (numInitPts > 0)\n        {\n            int tempInd = (int)std::ceil((numInitPts - 1 - 1e-6) * std::rand() / RAND_MAX);\n            int stInd = initPtInds[tempInd];\n\n            std::vector<double> myMean(numDim);\n            for (int i = 0; i < numDim; i++)\n            {\n                myMean[i] = (double)dataPts.at<double>(stInd, i);\n            }\n\n            vector<int> thisClusterVotes(numPts);\n\n            while (1)\n            {\n                vector<double> sqDistToAll(numPts);\n                for (int i = 0; i < numPts; i++)\n                {\n                    double result = 0;\n                    for (int j = 0; j < numDim; j++)\n                    {\n                        double diff = (double)dataPts.at<double>(i, j) - myMean[j];\n                        result += pow(diff, 2);\n                    }\n                    sqDistToAll[i] = result;\n                }\n                vector<bool> inInds(numPts);\n                for (int i = 0; i < numPts; i++)\n                {\n                    inInds[i] = sqDistToAll[i] < bandSq;\n                    if (inInds[i] == true)\n                    {\n                        thisClusterVotes[i]++;\n                    }\n                }\n\n                int countTrues = count_if(inInds.begin(), inInds.end(), [](bool b) {\n                    return b == true;\n                });\n                vector<double> myOldMean = myMean;\n                cv::Mat tempData(countTrues, numDim, CV_64FC1);\n                int localIdx = 0;\n                for (int i = 0; i < (int)inInds.size(); i++)\n                {\n                    if (inInds[i] == true)\n                    {\n                        for (int j = 0; j < numDim; j++)\n                        {\n                            tempData.at<double>(localIdx, j) = (double)dataPts.at<double>(i, j);\n                        }\n                        localIdx++;\n                        beenVisitedFlag[i] = true;\n                    }\n                }\n                Mat myMeanMat;\n                reduce(tempData, myMeanMat, 0, CV_REDUCE_AVG);\n                myMeanMat.copyTo(myMean);\n\n                // compute the 2-norm of the difference-between-means vector\n                double meanNorm = RV_computeNorm(myOldMean, myMean);\n\n                if (meanNorm < stopThresh)\n                {\n                    int mergeWith = -1;\n                    for (int cn = 0; cn <= numClust; cn++)\n                    {\n                        vector<double> localClustCent(numDim);\n                        clustCent.row(cn).copyTo(localClustCent);\n                        double distToOther = RV_computeNorm(myMean, localClustCent);\n\n                        if (distToOther < bandWidth / 2)\n                        {\n                            mergeWith = cn;\n                            break;\n                        }\n                    }\n\n                    if (mergeWith >= 0)\n                    {\n                        Mat localMat = 0.5 * (myMeanMat + clustCent.row(mergeWith));\n                        localMat.copyTo(clustCent.row(mergeWith));\n                    }\n                    else\n                    {\n                        numClust++;\n                        clustCent.push_back(myMeanMat);\n                        if (tempData.rows > biggestClusterSize)\n                        {\n                            biggestClusterSize = tempData.rows;\n                            *maxClustPointer = *maxClustPointer + 1;\n                        }\n                        //myMeanMat.copyTo(clustCent.row(numClust));\n                    }\n                    break;\n                }\n            }\n\n            initPtInds.clear();\n            for (int i = 0; i < (int)beenVisitedFlag.size(); i++)\n            {\n                if (beenVisitedFlag[i] == false)\n                {\n                    initPtInds.push_back(i);\n                }\n            }\n            numInitPts = initPtInds.size();\n        }\n        return clustCent;\n    }\n\n    Mat RV_preprocessDepthFrame(Mat frame)\n    {\n        Mat output;\n        double minVal = 100;\n        double maxVal = -100;\n        Point minLoc, maxLoc;\n\n        for (int i = 0; i < frame.rows; i++)\n        {\n            for (int j = 0; j < frame.cols; j++)\n            {\n                if ((frame.at<double>(i, j) < minVal) & (frame.at<double>(i, j) != -100))\n                {\n                    minVal = frame.at<double>(i, j);\n                    minLoc.x = i;\n                    minLoc.y = j;\n                }\n\n                if (frame.at<double>(i, j) > maxVal)\n                {\n                    maxVal = frame.at<double>(i, j);\n                    maxLoc.x = i;\n                    maxLoc.y = j;\n                }\n            }\n        }\n\n        for (int i = 0; i < frame.rows; i++)\n        {\n            for (int j = 0; j < frame.cols; j++)\n            {\n                if (frame.at<double>(i, j) != -100)\n                {\n                    frame.at<double>(i, j) = 255 - (frame.at<double>(i, j) - minVal) / (maxVal - minVal) * 254;\n                }\n                else\n                {\n                    frame.at<double>(i, j) = 0;\n                }\n            }\n        }\n\n        transpose(frame, output);\n        return output;\n    }\n\n    void RV_featExtractionSingleFrame(Mat frame, paramList params, vector<double> *bgPerc, vector<Mat> &featData)\n    {\n        featData.clear();\n        featData.resize((unsigned int)params.noPatches);\n        for (int k = 0; k < params.noPatches; k++)\n        {\n            Mat dummyMat(1, (int)(params.d * params.noChannels), CV_64FC1);\n            dummyMat.setTo(0);\n            featData[k] = dummyMat;\n        }\n\n        int rows = frame.rows;\n        int cols = frame.cols;\n\n        vector<Mat> channels = RV_channelsExtractionSingleFrame(frame, params);\n        vector<Mat> channelsInt(params.noChannels);\n        vector<Mat> maskInt(params.noChannels);\n\n        for (int i = 0; i < params.noChannels; i++)\n        {\n            Mat localChannel = channels[i];\n            Mat localChannelInt(rows + 1, cols + 1, CV_64FC1);\n            localChannelInt.setTo(0);\n            integral(localChannel, localChannelInt);\n\n            Mat localMask(rows, cols, CV_32FC1);\n            localMask.setTo(0);\n            localChannel.convertTo(localChannel, CV_32FC1); // for some (probably) stupid reason,\n            // m***** f***** \"threshold\" function does not work with CV_64FC1...\n            threshold(localChannel, localMask, 0.001, 1, THRESH_BINARY);\n\n            Mat localMaskInt(rows + 1, cols + 1, CV_64FC1);\n            localMaskInt.setTo(0);\n            integral(localMask, localMaskInt);\n            channelsInt[i] = localChannelInt;\n            maskInt[i] = localMaskInt;\n        }\n\n        for (int k = 0; k < params.patchCoords.rows; k++)\n        {\n            Mat frameAux(frame, Rect((int)params.patchCoords.at<double>(k, 1),\n                                     (int)params.patchCoords.at<double>(k, 0),\n                                     (int)params.patchSize,\n                                     (int)params.patchSize));\n            double countBG = 0;\n            for (int i = 1; i < frameAux.rows; i++) // first row and column are not covered by the rectangular features\n                // so yes, index should start from 1\n            {\n                for (int j = 1; j < frameAux.cols; j++) // same here\n                {\n                    if (frameAux.at<double>(i, j) == 0)\n                    {\n                        countBG++;\n                    }\n                }\n            }\n            (*bgPerc)[k] = countBG / (params.patchSize - 1) / (params.patchSize - 1);\n\n            vector<Mat> localImageInt(params.noChannels);\n            vector<Mat> localMaskInt(params.noChannels);\n            for (int i = 0; i < params.noChannels; i++)\n            {\n                Mat dummyMat1(channelsInt[i], Rect((int)params.patchCoords.at<double>(k, 1) + 1,\n                                                   (int)params.patchCoords.at<double>(k, 0) + 1,\n                                                   (int)params.patchSize,\n                                                   (int)params.patchSize));\n                localImageInt[i] = dummyMat1;\n                Mat dummyMat2(maskInt[i], Rect((int)params.patchCoords.at<double>(k, 1) + 1,\n                                               (int)params.patchCoords.at<double>(k, 0) + 1,\n                                               (int)params.patchSize,\n                                               (int)params.patchSize));\n                localMaskInt[i] = dummyMat2;\n            }\n\n            Mat feats = RV_computeDiffFeats(localImageInt, localMaskInt, params.patchFeats[k]);\n            featData[k] = feats;\n        }\n        // return featData;\n    }\n\n    Mat RV_computeDiffFeats(vector<Mat> imageInt, vector<Mat> maskInt, Mat localFeat)\n    {\n        Mat feats(1, localFeat.rows * imageInt.size(), CV_64FC1);\n        feats.setTo(0);\n\n        //int numRectangles = params.patchFeats[0].cols / 4;\n        for (int i = 0; i < (int)imageInt.size(); i++)\n        {\n            Mat localImg = imageInt[i];\n            Mat localMask = maskInt[i];\n            for (int k = 0; k < localFeat.rows; k++)\n            {\n                //vector<int> v(localFeat.cols);\n                //localFeat.row(k).copyTo(v);\n\n                // keep in mind that the coordinates of the rectangles are obeying Matlab indexing, therefore adaptation is performed explicitly here\n\n                double a1 = localImg.at<double>(localFeat.at<uchar>(k, 3) - 1, localFeat.at<uchar>(k, 2) - 1) -\n                            localImg.at<double>(localFeat.at<uchar>(k, 3) - 1, localFeat.at<uchar>(k, 0) - 2) -\n                            localImg.at<double>(localFeat.at<uchar>(k, 1) - 2, localFeat.at<uchar>(k, 2) - 1) +\n                            localImg.at<double>(localFeat.at<uchar>(k, 1) - 2, localFeat.at<uchar>(k, 0) - 2);\n                double a2 = localImg.at<double>(localFeat.at<uchar>(k, 7) - 1, localFeat.at<uchar>(k, 6) - 1) -\n                            localImg.at<double>(localFeat.at<uchar>(k, 7) - 1, localFeat.at<uchar>(k, 4) - 2) -\n                            localImg.at<double>(localFeat.at<uchar>(k, 5) - 2, localFeat.at<uchar>(k, 6) - 1) +\n                            localImg.at<double>(localFeat.at<uchar>(k, 5) - 2, localFeat.at<uchar>(k, 4) - 2);\n                /*double a3 = localImg.at<double>(localFeat.at<uchar>(k, 11) - 1, localFeat.at<uchar>(k, 10) - 1) -\n                    localImg.at<double>(localFeat.at<uchar>(k, 11) - 1, localFeat.at<uchar>(k, 8) - 2) -\n                    localImg.at<double>(localFeat.at<uchar>(k, 9) - 2, localFeat.at<uchar>(k, 10) - 1) +\n                    localImg.at<double>(localFeat.at<uchar>(k, 9) - 2, localFeat.at<uchar>(k, 8) - 2);\n                double a4 = localImg.at<double>(localFeat.at<uchar>(k, 15) - 1, localFeat.at<uchar>(k, 14) - 1) -\n                    localImg.at<double>(localFeat.at<uchar>(k, 15) - 1, localFeat.at<uchar>(k, 12) - 2) -\n                    localImg.at<double>(localFeat.at<uchar>(k, 13) - 2, localFeat.at<uchar>(k, 14) - 1) +\n                    localImg.at<double>(localFeat.at<uchar>(k, 13) - 2, localFeat.at<uchar>(k, 12) - 2);*/\n\n                double z1 = localMask.at<double>(localFeat.at<uchar>(k, 3) - 1, localFeat.at<uchar>(k, 2) - 1) -\n                            localMask.at<double>(localFeat.at<uchar>(k, 3) - 1, localFeat.at<uchar>(k, 0) - 2) -\n                            localMask.at<double>(localFeat.at<uchar>(k, 1) - 2, localFeat.at<uchar>(k, 2) - 1) +\n                            localMask.at<double>(localFeat.at<uchar>(k, 1) - 2, localFeat.at<uchar>(k, 0) - 2);\n                double z2 = localMask.at<double>(localFeat.at<uchar>(k, 7) - 1, localFeat.at<uchar>(k, 6) - 1) -\n                            localMask.at<double>(localFeat.at<uchar>(k, 7) - 1, localFeat.at<uchar>(k, 4) - 2) -\n                            localMask.at<double>(localFeat.at<uchar>(k, 5) - 2, localFeat.at<uchar>(k, 6) - 1) +\n                            localMask.at<double>(localFeat.at<uchar>(k, 5) - 2, localFeat.at<uchar>(k, 4) - 2);\n                /*double z3 = localMask.at<double>(localFeat.at<uchar>(k, 11) - 1, localFeat.at<uchar>(k, 10) - 1) -\n                    localMask.at<double>(localFeat.at<uchar>(k, 11) - 1, localFeat.at<uchar>(k, 8) - 2) -\n                    localMask.at<double>(localFeat.at<uchar>(k, 9) - 2, localFeat.at<uchar>(k, 10) - 1) +\n                    localMask.at<double>(localFeat.at<uchar>(k, 9) - 2, localFeat.at<uchar>(k, 8) - 2);\n                double z4 = localMask.at<double>(localFeat.at<uchar>(k, 15) - 1, localFeat.at<uchar>(k, 14) - 1) -\n                    localMask.at<double>(localFeat.at<uchar>(k, 15) - 1, localFeat.at<uchar>(k, 12) - 2) -\n                    localMask.at<double>(localFeat.at<uchar>(k, 13) - 2, localFeat.at<uchar>(k, 14) - 1) +\n                    localMask.at<double>(localFeat.at<uchar>(k, 13) - 2, localFeat.at<uchar>(k, 12) - 2);*/\n\n                double mz1 = (z1 > 1) ? z1 : 1;\n                double mz2 = (z2 > 1) ? z2 : 1;\n                /*double mz3 = (z3 > 1) ? z3 : 1;\n                double mz4 = (z4 > 1) ? z4 : 1;*/\n\n                //double featVal = a1 / mz1 + a3 / mz3 - a2 / mz2 - a4 / mz4;\n                double featVal = a1 / mz1 - a2 / mz2;\n                feats.at<double>(0, i * localFeat.rows + k) = featVal;\n            }\n        }\n\n        return feats;\n    }\n\n    vector<Mat> RV_channelsExtractionSingleFrame(Mat frame, paramList params)\n    {\n        vector<Mat> output(params.noChannels);\n        for (int i = 0; i < params.noChannels; i++)\n        {\n            Mat buff(frame.rows, frame.cols, CV_64FC1);\n            buff.setTo(0);\n            output[i] = buff;\n        }\n\n        output[0] = frame;\n        Mat dx(frame.rows, frame.cols, CV_64FC1);\n        Mat dy(frame.rows, frame.cols, CV_64FC1);\n\n        Sobel(frame, dx, CV_64FC1, 0, 1);\n        Sobel(frame, dy, CV_64FC1, 1, 0);\n\n        Mat magnitudeAux(frame.rows, frame.cols, CV_64FC1);\n        Mat orientation(frame.rows, frame.cols, CV_64FC1);\n\n        for (int i = 0; i < frame.rows; i++)\n        {\n            for (int j = 0; j < frame.cols; j++)\n            {\n                magnitudeAux.at<double>(i, j) = sqrt(pow(dx.at<double>(i, j), 2) + pow(dy.at<double>(i, j), 2));\n                orientation.at<double>(i, j) = atan2(dx.at<double>(i, j), dy.at<double>(i, j));\n            }\n        }\n\n        Mat magnitude(frame.rows, frame.cols, CV_64FC1);\n        log(magnitudeAux + 1.0, magnitude); // switch to log scale to attenuate differences...\n\n        output[1] = magnitude;\n\n        /*namedWindow(\"frame\", CV_WINDOW_AUTOSIZE);\n        int flag = RV_imshow(\"frame\", frame);\n        namedWindow(\"magnitude\", CV_WINDOW_AUTOSIZE);\n        flag = RV_imshow(\"magnitude\", magnitude);\n        namedWindow(\"orientation\", CV_WINDOW_AUTOSIZE);\n        flag = RV_imshow(\"orientation\", orientation);*/\n\n        //setMouseCallback(\"image2\", onMouse, 0);\n\n        // compute gradient histograms for each of the 6 discrete orientation intervals\n        // if an orient falls inside a particular interval, we assign the pixel a value proportional\n        // to the gradient magnitude weighted by a peaked Gaussian whose mean is the center of the\n        // orientation interval and std = 1/(sqrt(2*pi))/5 (5 comes from the attempt of replicating Dollars toolbox)\n        // of course, pdf(mu) should be 1, so we compensate the small std by dividing the pdf by 5\n\n        // using Sobel gradient results in orients in the range (-pi;pi) therefore we split this interval in 6 complementary subintervals\n\n        double sigma = 1 / sqrt(2 * M_PI) / 5;\n        for (int k = 0; k < 6; k++)\n        {\n            double mu = -5 * M_PI / 6 + k * 2 * M_PI / 6;\n            Mat localChannel(frame.rows, frame.cols, CV_64FC1);\n            for (int i = 0; i < frame.rows; i++)\n            {\n                for (int j = 0; j < frame.cols; j++)\n                {\n                    double valuePdf = RV_gaussPdf(orientation.at<double>(i, j), mu, sigma) / 5;\n                    localChannel.at<double>(i, j) = magnitude.at<double>(i, j) * valuePdf;\n                }\n            }\n            output[k + 2] = localChannel;\n        }\n\n        // compute the LBP map of the original (grayscaled) depth image\n        Mat lbpMap = RV_lbp(frame);\n        Mat lbpMap64(lbpMap.rows, lbpMap.cols, CV_64FC1);\n        lbpMap.convertTo(lbpMap64, CV_64FC1);\n\n        for (int i = 1; i < frame.rows - 1; i++)\n        {\n            for (int j = 1; j < frame.cols - 1; j++)\n            {\n                output[8].at<double>(i, j) = lbpMap64.at<double>(i - 1, j - 1);\n            }\n        }\n        return output;\n    }\n\n    double RV_gaussPdf(double x, double mu, double sigma)\n    {\n        /*\n            x = double(int(x * 10)) / 10;\n            static map<double, double> pdfMap;\n            if (pdfMap.find(x) != pdfMap.end())\n            {\n                return pdfMap[x];\n            }*/\n        double aux = -pow(x - mu, 2) / (2 * pow(sigma, 2));\n        double out = 1 / (sqrt(2 * M_PI) * sigma) * exp(aux);\n        /*pdfMap[x] = out;*/\n        return out;\n\n    }\n\n    int RV_imshow(string windowName, Mat img)\n    {\n        double minVal, maxVal;\n        Mat draw(img.rows, img.cols, CV_8UC1);\n        minMaxLoc(img, &minVal, &maxVal);\n        img.convertTo(draw, CV_8UC1, 255.0 / (maxVal - minVal), -minVal * 255.0 / (maxVal - minVal));\n        imshow(windowName, draw);\n        return 1;\n    }\n\n    Mat RV_lbp(const Mat &src)\n    {\n        Mat dst;\n        dst = Mat::zeros(src.rows - 2, src.cols - 2, CV_8UC1);\n        for (int i = 1; i < src.rows - 1; i++) {\n            for (int j = 1; j < src.cols - 1; j++) {\n                uchar center = (uchar)src.at<double>(i, j);\n                unsigned char code = 0;\n                code |= ((uchar)src.at<double>(i - 1, j - 1) > center) << 7;\n                code |= ((uchar)src.at<double>(i - 1, j) > center) << 6;\n                code |= ((uchar)src.at<double>(i - 1, j + 1) > center) << 5;\n                code |= ((uchar)src.at<double>(i, j + 1) > center) << 4;\n                code |= ((uchar)src.at<double>(i + 1, j + 1) > center) << 3;\n                code |= ((uchar)src.at<double>(i + 1, j) > center) << 2;\n                code |= ((uchar)src.at<double>(i + 1, j - 1) > center) << 1;\n                code |= ((uchar)src.at<double>(i, j - 1) > center) << 0;\n                dst.at<uchar>(i - 1, j - 1) = code;\n            }\n        }\n        return 255 - dst;\n    }\n\n}", "meta": {"hexsha": "db02254b21584c61c0a9bc86269677a22f7e1f0a", "size": 27849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FaceCept3D/HeadPoseEstimationFramework/FacialExpressions/ferLocalFunctions.cpp", "max_stars_repo_name": "Ajithsj96/FaceCept3d", "max_stars_repo_head_hexsha": "f13c791af154a289442ee9d1349c86ba07e24855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 192.0, "max_stars_repo_stars_event_min_datetime": "2015-08-14T13:44:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T05:36:43.000Z", "max_issues_repo_path": "FaceCept3D/HeadPoseEstimationFramework/FacialExpressions/ferLocalFunctions.cpp", "max_issues_repo_name": "Ajithsj96/FaceCept3d", "max_issues_repo_head_hexsha": "f13c791af154a289442ee9d1349c86ba07e24855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-02-26T15:11:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-01T09:42:55.000Z", "max_forks_repo_path": "FaceCept3D/HeadPoseEstimationFramework/FacialExpressions/ferLocalFunctions.cpp", "max_forks_repo_name": "Ajithsj96/FaceCept3d", "max_forks_repo_head_hexsha": "f13c791af154a289442ee9d1349c86ba07e24855", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82.0, "max_forks_repo_forks_event_min_datetime": "2015-10-08T03:29:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T08:22:07.000Z", "avg_line_length": 38.4124137931, "max_line_length": 161, "alphanum_fraction": 0.4772164171, "num_tokens": 7377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.02843603304485266, "lm_q1q2_score": 0.011798077289348147}}
{"text": "#include <stdlib.h>\n#include <iostream>\n#include <boost/optional/optional_io.hpp>\n#include <boost/optional.hpp>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <string>\n\n#include \"snark.hpp\"\n#include \"utils.cpp\"\n\nusing namespace libsnark;\nusing namespace std;\n\nint genProof(r1cs_ppzksnark_proving_key<default_r1cs_ppzksnark_pp> provingKey_in, string proofFileName, string publicInputs, string privateInputs)\n{\n  // Initialize bit_vectors for all of the variables involved.\n  vector<bool> h_startBalance_bv(256);\n  vector<bool> h_endBalance_bv(256);\n  vector<bool> h_incoming_bv(256);\n  vector<bool> h_outgoing_bv(256);\n  vector<bool> r_startBalance_bv(256);\n  vector<bool> r_endBalance_bv(256);\n  vector<bool> r_incoming_bv(256);\n  vector<bool> r_outgoing_bv(256);\n\n  vector<vector<unsigned long int>> publicValues = fillValuesFromfile(publicInputs);\n  h_startBalance_bv = int_list_to_bits_local(publicValues[0], 8);\n  h_endBalance_bv = int_list_to_bits_local(publicValues[1], 8);\n  h_incoming_bv = int_list_to_bits_local(publicValues[2], 8);\n  h_outgoing_bv = int_list_to_bits_local(publicValues[3], 8);\n\n  vector<vector<unsigned long int>> privateValues = fillValuesFromfile(privateInputs);\n  r_startBalance_bv = int_list_to_bits_local(privateValues[0], 8);\n  r_endBalance_bv = int_list_to_bits_local(privateValues[1], 8);\n  r_incoming_bv = int_list_to_bits_local(privateValues[2], 8);\n  r_outgoing_bv = int_list_to_bits_local(privateValues[3], 8);\n\n  cout << \"Starting proof generation for \" + proofFileName << endl;\n  boost::optional<libsnark::r1cs_ppzksnark_proof<libff::alt_bn128_pp>> proof = generate_payment_in_out_proof<default_r1cs_ppzksnark_pp>(provingKey_in, h_startBalance_bv, h_endBalance_bv, h_incoming_bv, h_outgoing_bv, r_startBalance_bv, r_endBalance_bv, r_incoming_bv, r_outgoing_bv);\n\n  if(proof == boost::none)\n  {\n    return 1;\n  } else {\n    stringstream proofStream;\n    proofStream << proof;\n\n    ofstream fileOut;\n    fileOut.open(proofFileName);\n\n    fileOut << proofStream.rdbuf();\n    fileOut.close();\n    cout << \"Proof was generated!!\" << proofFileName << endl;\n    return 0;\n  }\n}\n\nint getUserInput(r1cs_ppzksnark_proving_key<default_r1cs_ppzksnark_pp> provingKey_in)\n{\n  string inputTemp = \"\";\n  int result=0;\n  cout << \"Press enter paymentId to generate a proof or q to quit\" << endl;\n  cin >> inputTemp;  \n  cout << \"Input from console: \" << inputTemp << endl;\n  if(inputTemp != \"q\")\n  {\n    string proofName = \"proof_single_\";\n    string proofNameWithId = proofName + inputTemp;\n    string publicInputs = \"publicInputParameters_single_\";\n    string publicInputsWithId = publicInputs + inputTemp;\n    string privateInputs = \"privateInputParameters_single_\";\n    string privateInputsWithId = privateInputs + inputTemp;\n\n    cout << proofNameWithId << endl;\n    result = genProof(provingKey_in, proofNameWithId, publicInputsWithId, privateInputsWithId);\n    if(result!=0)\n    {\n      cout << \"There was an error generating the proof\" << endl;\n      return getUserInput(provingKey_in);\n    }\n    else\n    {\n      return getUserInput(provingKey_in);\n    }\n  }\n  else\n  {\n    return 0;\n  }\n}\n\n\nint main(int argc, char *argv[])\n{\n  string keyFileName = \"provingKey_single\";\n\n  // Initialize the curve parameters.\n  default_r1cs_ppzksnark_pp::init_public_params();\n\n  r1cs_ppzksnark_proving_key<default_r1cs_ppzksnark_pp> provingKey_in;\n\n  ifstream fileIn(keyFileName);\n  stringstream provingKeyFromFile;\n  if (fileIn) {\n     provingKeyFromFile << fileIn.rdbuf();\n     fileIn.close();\n  }\n \n  provingKeyFromFile >> provingKey_in;\n \n  return getUserInput(provingKey_in);\n}\n", "meta": {"hexsha": "0862b0e9373c4107baf458caaf4a47185037d7b1", "size": 3617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/payment_in_out_generate_proof.cpp", "max_stars_repo_name": "agiletechvn/ZKP", "max_stars_repo_head_hexsha": "d1294da076585e2a906aa64560a71fc68114c75c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 118.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T05:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:59:39.000Z", "max_issues_repo_path": "src/payment_in_out_generate_proof.cpp", "max_issues_repo_name": "technologiespro/zero-knowledge-proofs", "max_issues_repo_head_hexsha": "6fdfb0c25ae24e33b6325baa2b261860e89ae087", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-08-29T03:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-10T23:39:26.000Z", "max_forks_repo_path": "src/payment_in_out_generate_proof.cpp", "max_forks_repo_name": "technologiespro/zero-knowledge-proofs", "max_forks_repo_head_hexsha": "6fdfb0c25ae24e33b6325baa2b261860e89ae087", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T01:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T13:38:35.000Z", "avg_line_length": 31.452173913, "max_line_length": 283, "alphanum_fraction": 0.7431573127, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.027169233308022084, "lm_q1q2_score": 0.011790944066409298}}
{"text": "#include<cstdlib>\n#include<algorithm>\n#include<complex>\n#include<iostream>\n#include<fstream>\n#include<map>\n#include<utility>\n#if defined(USE_MPI)\n#include<mpi.h>\n#endif\n\n#include \"OhmmsData/libxmldefs.h\"\n#include \"OhmmsData/AttributeSet.h\"\n#include \"OhmmsData/ParameterSet.h\"\n#include \"Utilities/SimpleParser.h\"\n#include \"Configuration.h\"\n#include \"io/hdf_archive.h\"\n#include \"Message/CommOperators.h\"\n\n#include <boost/interprocess/managed_shared_memory.hpp>\n#include <boost/interprocess/containers/vector.hpp>\n#include <boost/interprocess/allocators/allocator.hpp>\n#include <boost/interprocess/sync/interprocess_condition.hpp>\n#include <boost/interprocess/sync/interprocess_mutex.hpp>\n#include <boost/interprocess/sync/scoped_lock.hpp>\n\n#include \"AFQMC/config.h\"\n#include \"AFQMC/Hamiltonians/ProjectorBase.h\"\n#include \"AFQMC/Hamiltonians/DDProjector.h\"\n#include \"AFQMC/Numerics/DenseMatrixOperations.h\"\n#include \"AFQMC/Numerics/SparseMatrixOperations.h\"\n\nnamespace qmcplusplus\n{\n\n  bool DDProjector::initFromGuess()\n  {\n  \n    // start by just setting to zero\n    Pmat.resize(2*NMO,2*NMO); \n    Pmat=0;\n  \n    return true;\n  }\n\n  bool DDProjector::initFromHDF5(const std::string& fileName)\n  {\n\n    return true;\n\n/*\n    hdf_archive dump(myComm);\n    if(!dump.open(fileName,H5F_ACC_RDONLY)) {\n      app_error()<<\" Error opening integral file in SparseGeneralHamiltonian. \\n\";\n      return false;\n    }\n\n    std::string path = \"/Hamiltonian/SparseGeneralHamiltonian\";\n    if(!dump.is_group( path )) {\n      app_error()<<\" ERROR: H5Group /Hamiltonian/SparseGeneralHamiltonian does not exists in restart file. \\n\";\n      return false;\n    }\n\n    if(!dump.push(\"Hamiltonian\",false)) return false;\n    if(!dump.push(\"SparseGeneralHamiltonian\",false)) return false;\n\n    std::vector<int> Idata(7);\n    if(!dump.read(Idata,\"dims\")) return false;\n\n    H1.resize(Idata[0]);\n    V2.resize(Idata[1]);\n    V2_2bar.resize(Idata[2]);\n\n    if(NMO < 0) NMO = Idata[3];\n    if(NAEA < 0) NAEA = Idata[4];\n    if(NAEB < 0) NAEB = Idata[5];\n    if(Idata[3] != NMO) {\n      app_error()<<\" ERROR: NMO differs from value in integral file. \\n\"; \n      return false;\n    }\n    if(Idata[4] != NAEA) {\n      app_error()<<\" ERROR: NMO differs from value in integral file. \\n\"; \n      return false;\n    }\n    if(Idata[5] != NAEB) {\n      app_error()<<\" ERROR: NMO differs from value in integral file. \\n\"; \n      return false;\n    }\n    spinRestricted = (Idata[6]==0)?(true):(false);\n\n    occup_alpha.resize(NAEA);\n    occup_beta.resize(NAEB);\n    Idata.resize(NAEA+NAEB);\n    if(!dump.read(Idata,\"occups\")) return false;\n    for(int i=0; i<NAEA; i++) occup_alpha[i] = Idata[i];\n    for(int i=NAEA, j=0; i<NAEA+NAEB; i++, j++) occup_beta[j] = Idata[i];\n\n    std::vector<double> Rdata(2);\n    if(!dump.read(Rdata,\"Energies\")) return false;\n    NuclearCoulombEnergy = Rdata[0];\n    FrozenCoreEnergy = Rdata[0];\n\n    int sz = std::max( 2*H1.size(), std::max( 4*V2.size(), 4*V2_2bar.size() ) );\n    std::vector<IndexType> ivec;    \n    ivec.reserve(sz);\n\n    ivec.resize(2*H1.size());\n    if(!dump.read(ivec,\"H1_indx\")) return false;\n    for(int i=0, j=0; i<H1.size(); i++, j+=2)        \n      H1[i] = std::make_tuple(ivec[j],ivec[j+1],0);  \n\n    ivec.clear();\n    ivec.resize(4*V2.size());\n    if(!dump.read(ivec,\"V2_indx\")) return false;\n    for(int i=0, j=0; i<V2.size(); i++, j+=4)\n      V2[i] = std::make_tuple(ivec[j],ivec[j+1],ivec[j+2],ivec[j+3],0);  \n\n    ivec.clear();\n    ivec.resize(4*V2_2bar.size());\n    if(!dump.read(ivec,\"V2_2bar_indx\")) return false;\n    for(int i=0, j=0; i<V2_2bar.size(); i++, j+=4)\n      V2_2bar[i] = std::make_tuple(ivec[j],ivec[j+1],ivec[j+2],ivec[j+3],0);  \n\n    std::vector<IndexType>().swap(ivec);\n\n    sz = std::max( H1.size(), std::max( V2.size(), V2_2bar.size() ) );\n    std::vector<ValueType> vvec;\n    vvec.reserve(sz); \n\n    vvec.resize(H1.size());\n    if(!dump.read(vvec,\"H1\")) return false;\n    for(int i=0; i<H1.size(); i++)           \n      std::get<2>(H1[i]) = vvec[i]; \n\n    vvec.clear();\n    vvec.resize(V2.size());\n    if(!dump.read(vvec,\"V2\")) return false;\n    for(int i=0; i<V2.size(); i++)\n      std::get<4>(V2[i]) = vvec[i]; \n\n    vvec.clear();\n    vvec.resize(V2_2bar.size());\n    if(!dump.read(vvec,\"V2_2bar\")) return false;\n    for(int i=0; i<V2_2bar.size(); i++)\n      std::get<4>(V2_2bar[i]) = vvec[i]; \n\n    std::vector<ValueType>().swap(vvec);   \n\n    dump.pop();\n    dump.pop();\n\n    dump.close();\n\n    return true;\n*/\n  }\n\n  void DDProjector::hdf_write() {\n/*\n    if(hdf_write_file == std::string(\"\")) return;\n\n    hdf_archive dump(myComm);\n    if(!dump.create(hdf_write_file)) {\n      app_error()<<\" Error opening restart file in SparseGeneralHamiltonian. \\n\";\n      return;\n    }\n\n    std::string path = \"/Hamiltonian/SparseGeneralHamiltonian\";\n    if(dump.is_group( path )) {\n      app_error()<<\" ERROR: H5Group /Hamiltonian/SparseGeneralHamiltonian already exists in restart file. Not over-writing data in file. \\n\"; \n      return;\n    }\n\n    dump.push(\"Hamiltonian\");\n    dump.push(\"SparseGeneralHamiltonian\");\n\n    std::vector<int> Idata(7);\n    Idata[0]=H1.size();\n    Idata[1]=V2.size();\n    Idata[2]=V2_2bar.size();\n    Idata[3]=NMO;\n    Idata[4]=NAEA;\n    Idata[5]=NAEB;\n    Idata[6]=spinRestricted?(0):(1);\n    dump.write(Idata,\"dims\");\n    \n    Idata.resize(NAEA+NAEB);\n    for(int i=0; i<NAEA; i++) Idata[i] = occup_alpha[i];\n    for(int i=NAEA, j=0; i<NAEA+NAEB; i++, j++) Idata[i] = occup_beta[j];\n    dump.write(Idata,\"occups\");\n\n    std::vector<double> Rdata(2);\n    Rdata[0] = NuclearCoulombEnergy;\n    Rdata[1] = FrozenCoreEnergy; \n    dump.write(Rdata,\"Energies\");\n\n    int sz = std::max( 2*H1.size(), std::max( 4*V2.size(), 4*V2_2bar.size() ) );\n    std::vector<IndexType> ivec; \n    ivec.reserve(sz);\n\n    ivec.resize(2*H1.size());\n    for(int i=0, j=0; i<H1.size(); i++, j+=2) \n      std::tie (ivec[j],ivec[j+1],std::ignore) = H1[i];   \n    dump.write(ivec,\"H1_indx\");\n\n    ivec.clear();\n    ivec.resize(4*V2.size());\n    for(int i=0, j=0; i<V2.size(); i++, j+=4) \n      std::tie (ivec[j],ivec[j+1],ivec[j+2],ivec[j+3],std::ignore) = V2[i];   \n    dump.write(ivec,\"V2_indx\");\n\n    ivec.clear();\n    ivec.resize(4*V2_2bar.size());\n    for(int i=0, j=0; i<V2_2bar.size(); i++, j+=4) \n      std::tie (ivec[j],ivec[j+1],ivec[j+2],ivec[j+3],std::ignore) = V2_2bar[i];   \n    dump.write(ivec,\"V2_2bar_indx\");\n\n    std::vector<IndexType>().swap(ivec); \n\n    sz = std::max( H1.size(), std::max( V2.size(), V2_2bar.size() ) );\n    std::vector<ValueType> vvec;    \n    vvec.reserve(sz);    \n\n    vvec.resize(H1.size());\n    for(int i=0; i<H1.size(); i++)       \n      std::tie (std::ignore,std::ignore,vvec[i]) = H1[i];\n    dump.write(vvec,\"H1\");\n\n    vvec.clear();\n    vvec.resize(V2.size());\n    for(int i=0; i<V2.size(); i++)\n      std::tie (std::ignore,std::ignore,std::ignore,std::ignore,vvec[i]) = V2[i];\n    dump.write(vvec,\"V2\");\n\n    vvec.clear();\n    vvec.resize(V2_2bar.size());\n    for(int i=0; i<V2_2bar.size(); i++)\n      std::tie (std::ignore,std::ignore,std::ignore,std::ignore,vvec[i]) = V2_2bar[i];\n    dump.write(vvec,\"V2_2bar\");    \n\n    std::vector<ValueType>().swap(vvec); \n\n    dump.pop();\n    dump.pop();\n\n    dump.flush();\n    dump.close();\n*/\n  }\n\n  void DDProjector::calculateHSPotentials_Diagonalization(ComplexSMSpMat& Spvn)\n  {\n\n    int rnk=0;\n#if defined(USE_MPI)\n    rnk = rank();\n#endif\n\n      int NMO2 = 2*NMO; \n\n      Timer.reset(\"Generic\");       \n      Timer.start(\"Generic\");       \n\n      ValueMatrix eigVec(NMO2);\n      RealVector eigVal(NMO2);\n      if(!DenseMatrixOperators::symEigenSysAll(NMO2,Pmat.data(),NMO2,eigVal.data(),eigVec.data(),NMO2) ) {\n        app_error()<<\"Problems with eigenvalue/eigenvector calculation in DDProjector::calculateHSPotentials_Diagonalization.\\n\";\n        APP_ABORT(\"Problems with eigenvalue/eigenvector calculation in DDProjector::calculateHSPotentials_Diagonalization.\\n\");\n      }\n\n      Timer.stop(\"Generic\");       \n      if(rnk==0) app_log()<<\" -- Time to solve eigenvalue problem: \" <<Timer.average(\"Generic\") <<\"\\n\";\n\n      for(int i=0; i<NMO2; i++) { \n        RealType scl = std::sqrt( std::max(0.0,eigVal[i]) )  ;\n        for(int j=0; j<NMO2; j++)  \n          eigVec(j,i) *= scl; \n      }        \n\n      int cnt1=0;\n      int cnt2=0;\n      for(int i=0; i<NMO2; i++) { \n       if(eigVal[i] > std::abs(eigcut)) { \n         int cnt3=0;\n         for(int j=0; j<NMO2; j++) \n            if(std::abs(eigVec(j,i)) > cutoff_sparse) cnt3++;\n         if(cnt3 > 0) {\n           cnt1++;\n           cnt2 += cnt3;\n         }\n       }\n      }\n\n     // later on, instead of doing all ~M^4 terms, choose a few thousand randomly\n     if(test_breakup) {\n\n      if(rnk==0) app_log()<<\" -- Testing Projector factorization. \\n\";\n      Timer.reset(\"Generic\");\n      Timer.start(\"Generic\");\n\n      RealType s=0.0;\n      RealType max=0.0;\n      for(IndexType i=0; i<2*NMO; i++) {\n       for(IndexType j=0; j<2*NMO; j++) { \n           ValueType v2 = Pmat(i,j);\n           ValueType v2c = 0.0;\n           for(int n=0; n<NMO2; n++) v2c += eigVec(i,n)*myconj(eigVec(j,n));\n           s+=std::abs(v2-v2c);\n           if( max < std::abs(v2-v2c) ) max = std::abs(v2-v2c);\n           if( std::abs(v2-v2c) > 10*eigcut ) {\n             app_error()<<\" Problems with Projector decomposition, i,j,P,Pc: \"\n                       <<i <<\" \"\n                       <<j <<\" \"\n                       <<v2 <<\" \"\n                       <<v2c <<std::endl;\n           }\n         }\n      }\n      app_log()<<\"\\n ********************************************\\n Average error due to truncated eigenvalue factorization (in units of cutoff), max error : \" <<s/eigcut/NMO/NMO/4.0 <<\" \" <<max <<\" \\n ********************************************\\n\"<<std::endl; \n\n       Timer.stop(\"Generic\");\n       if(rnk==0) app_log()<<\" -- Time to test eigenvalue factorization: \" <<Timer.average(\"Generic\") <<\"\\n\";\n     }\n\n      Spvn.setDims(NMO2,cnt1);\n      Spvn.allocate_serial(cnt2);\n\n      ComplexType ifac = ComplexType(0.0,1.0);\n\n      cnt1=0;\n      for(int i=0; i<NMO2; i++) {\n       if(eigVal[i] > std::abs(eigcut)) {\n         int cnt3=0;\n         for(int j=0; j<2*NMO; j++) {\n           if(std::abs(ifac*eigVec(j,i)) > cutoff_sparse) {\n             cnt3++;\n             int jk = j*NMO+j;\n             if(j>=NMO) jk-=NMO;\n             Spvn.add(jk,cnt1,ifac*eigVec(j,i));\n           }\n         }\n         if(cnt3 > 0) \n           cnt1++;\n       }\n      }\n\n      app_log()<<\"Number of HS potentials in DDProjector: \" <<Spvn.cols() <<std::endl;\n      app_log()<<\"Number of terms in sparse representation of HS potentials: \" <<Spvn.size() <<std::endl;\n      app_log()<<\"Compressing Spvn. \\n\";\n      Spvn.compress();\n      app_log()<<\"Done Compressing Spvn. \\n\";\n\n  }\n\n  void DDProjector::calculateHSPotentials(ComplexSMSpMat& Spvn)\n  {\n    //if(use_eig)\n    calculateHSPotentials_Diagonalization(Spvn);\n  }\n\n\n  bool DDProjector::parse(xmlNodePtr cur)\n  {\n\n    if(cur == NULL)\n      return false;\n\n    xmlNodePtr curRoot=cur; \n    OhmmsAttributeSet oAttrib;\n    oAttrib.add(name,\"name\");\n    oAttrib.put(cur);\n\n    std::string bkp(\"no\"); \n    std::string use(\"no\"); \n    ParameterSet m_param;\n    m_param.add(eigcut,\"cutoff_decomp\",\"double\");\n    m_param.add(eigcut,\"cutoff_decomposition\",\"double\");\n    m_param.add(eigcut,\"cutoff_factorization\",\"double\");\n    m_param.add(eigcut,\"cutoff_cholesky\",\"double\");\n    m_param.add(cutoff_sparse,\"cutoff_sparse\",\"double\");\n    m_param.add(filetype,\"filetype\",\"std::string\");\n    m_param.add(filename,\"filename\",\"std::string\");\n    m_param.add(hdf_write_file,\"hdf_write_file\",\"std::string\");\n    m_param.add(bkp,\"test_breakup\",\"std::string\");\n    m_param.add(use,\"useCholesky\",\"std::string\");\n\n    std::string par(\"no\");\n    m_param.add(par,\"paral_fac\",\"std::string\");\n    m_param.add(par,\"parallel_fac\",\"std::string\");\n    m_param.add(par,\"parallel_factorization\",\"std::string\");\n\n    m_param.put(cur);\n\n    std::transform(par.begin(),par.end(),par.begin(),(int (*)(int)) tolower);\n    if(par == \"yes\" || par == \"true\") parallel_factorization = true;\n\n    use_eig=true;\n    std::transform(use.begin(),use.end(),use.begin(),(int (*)(int)) tolower);\n    if(use == \"true\" || use == \"yes\") use_eig = false;\n    std::transform(filetype.begin(),filetype.end(),filetype.begin(),(int (*)(int))tolower);\n    std::transform(bkp.begin(),bkp.end(),bkp.begin(),(int (*)(int))tolower);\n    if(bkp == \"yes\" || bkp == \"true\") test_breakup = true;  \n\n    if(use_eig)\n      app_log()<<\"Calculating factorization of 2 body interaction with direct diagonalization.\\n\";\n    else\n      app_log()<<\"Calculating factorization of 2 body interaction with Cholesky method.\\n\";\n\n    std::transform(par.begin(),par.end(),par.begin(),(int (*)(int)) tolower);\n    if(par == \"yes\" || par == \"true\") parallel_factorization = true;\n\n    if(parallel_factorization)\n      app_log()<<\"Calculating factorization of 2-bofy hamiltonian in parallel. \\n\";\n   \n    cur = curRoot->children;\n    while (cur != NULL) {\n      std::string cname((const char*)(cur->name));\n      if(cname ==\"something\") {\n      }\n      cur = cur->next;\n    }\n\n    return true;\n  } \n\n  // do a general check of parameters for consistency\n  // make sure object was build consistently and correctly \n  bool DDProjector::checkObject() \n  {\n    return true;\n  }\n\n}\n\n", "meta": {"hexsha": "eec12650481ce2db06df79b26c136a8932d41a71", "size": 13305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AFQMC/Hamiltonians/DDProjector.cpp", "max_stars_repo_name": "bwvdg/qmcpack", "max_stars_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AFQMC/Hamiltonians/DDProjector.cpp", "max_issues_repo_name": "bwvdg/qmcpack", "max_issues_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T15:33:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T15:35:59.000Z", "max_forks_repo_path": "src/AFQMC/Hamiltonians/DDProjector.cpp", "max_forks_repo_name": "bwvdg/qmcpack", "max_forks_repo_head_hexsha": "cd09fc54b36de2579c9802f5e64b7ec15506f3c3", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T17:44:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T17:44:39.000Z", "avg_line_length": 30.5862068966, "max_line_length": 262, "alphanum_fraction": 0.5878241263, "num_tokens": 4093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527604, "lm_q2_score": 0.0271692293694866, "lm_q1q2_score": 0.011790942357157838}}
{"text": "// Copyright 2015 National ICT Australia Limited (NICTA)\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 \"MatpowerParserPlugin.h\"\n\n#include \"Bus.h\"\n#include \"Branch.h\"\n#include \"CommonBranch.h\"\n#include \"Gen.h\"\n#include \"Network.h\"\n#include \"Zip.h\"\n#include \"YamlSupport.h\"\n\n#include <cmath>\n#include <fstream>\n#include <map>\n#include <numeric>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_function.hpp>\n#include <boost/spirit/include/phoenix_statement.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/spirit/include/support_multi_pass.hpp>\n\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\nnamespace phoenix = boost::phoenix;\n\ntypedef std::istreambuf_iterator<char> BaseIterator;\ntypedef boost::spirit::multi_pass<BaseIterator> ForwardIterator;\n\nusing namespace Sgt;\n\nnamespace\n{\n    typedef ForwardIterator Iterator;\n    typedef decltype(ascii::blank) SpaceType;\n    typedef std::vector<std::vector<double>> Matrix;\n    typedef Matrix::value_type Row;\n\n    struct MpData\n    {\n        double MVABase;\n        Matrix bus;\n        Matrix gen;\n        Matrix branch;\n        Matrix genCost;\n    };\n\n    struct Gram : qi::grammar<Iterator, SpaceType>\n    {\n        Gram(MpData& data) : Gram::base_type(start_)\n        {\n            statementTerm_ = (qi::eol | qi::lit(';'));\n\n            eol_ = -(qi::lit('%') >> *(qi::char_-qi::eol)) >> qi::eol;\n            ignore_ = -(qi::lit('%') >> *(qi::char_-qi::eol)) >> qi::eol;\n            other_ = (*(qi::char_-statementTerm_) >> statementTerm_);\n\n            rowSep_ = (qi::lit(';') >> -eol_) | eol_;\n            row_ = +(qi::double_ >> -qi::lit(','));\n            matrix_ = \"[\" >> -eol_ >> (row_ % rowSep_) >> -(eol_ ^ qi::lit(';')) >> \"]\";\n\n            topFunction_ = qi::lit(\"function\") >> qi::lit(\"mpc\") >> qi::lit(\"=\") >> *(qi::char_-statementTerm_)\n                           >> statementTerm_;\n            MVABase_ = (qi::lit(\"mpc.baseMVA\") >> qi::lit('=') >> qi::double_ >> statementTerm_)\n                       [phoenix::ref(data.MVABase) = qi::_1];\n            busMatrix_ = (qi::lit(\"mpc.bus\") >> qi::lit('=') >> matrix_ >> statementTerm_)\n                         [phoenix::ref(data.bus) = qi::_1];\n            genMatrix_ = (qi::lit(\"mpc.gen\") >> qi::lit('=') >> matrix_ >> statementTerm_)\n                         [phoenix::ref(data.gen) = qi::_1];\n            branchMatrix_ = (qi::lit(\"mpc.branch\") >> qi::lit('=') >> matrix_ >> statementTerm_)\n                            [phoenix::ref(data.branch) = qi::_1];\n            genCostMatrix_ = (qi::lit(\"mpc.gencost\") >> qi::lit('=') >> matrix_ >> statementTerm_)\n                             [phoenix::ref(data.genCost) = qi::_1];\n\n            start_ = *ignore_ >> topFunction_ >> *(ignore_ | MVABase_ | busMatrix_ | genMatrix_ | branchMatrix_ |\n                                                   genCostMatrix_ | other_);\n\n            // To debug: e.g.\n            // BOOST_SPIRIT_DEBUG_NODE(busMatrix_); debug(busMatrix_);\n        }\n\n        qi::rule<Iterator, SpaceType> statementTerm_;\n\n        qi::rule<Iterator, SpaceType> eol_;\n        qi::rule<Iterator, SpaceType> ignore_;\n        qi::rule<Iterator, SpaceType> other_;\n\n        // Matrix parser.\n        qi::rule<Iterator, SpaceType> rowSep_;\n        qi::rule<Iterator, Row(), SpaceType> row_;\n        qi::rule<Iterator, Matrix(), SpaceType> matrix_;\n\n        qi::rule<Iterator, SpaceType> topFunction_;\n        qi::rule<Iterator, SpaceType> MVABase_;\n        qi::rule<Iterator, SpaceType> busMatrix_;\n        qi::rule<Iterator, SpaceType> genMatrix_;\n        qi::rule<Iterator, SpaceType> branchMatrix_;\n        qi::rule<Iterator, SpaceType> genCostMatrix_;\n\n        qi::rule<Iterator, SpaceType> start_;\n    };\n\n    // Voltage is in p.u., with the base being specified in KV by the KVBase field.\n    template<typename T> T pu2kV(T V, double kVBase)\n    {\n        return V * kVBase;\n    }\n\n    // Shunt admittance is in MW @ 1 p.u. voltage.\n    template<typename T> T YBusShunt2Siemens(T Y, double kVBase)\n    {\n        return Y / (kVBase * kVBase);\n    }\n\n    // Branch admittance is in p.u., that is, KVBase^2/MVABase.\n    // KVBase is referenced to the \"from\" bus, the second bus, bus1.\n    template<typename T> T YBranch2Siemens(T Y, double kVBase, double MVABase)\n    {\n        return Y * MVABase / (kVBase * kVBase);\n    }\n\n    double deg2Rad(double deg)\n    {\n        return pi * deg / 180.0;\n    }\n}\n\nnamespace Sgt\n{\n\n    struct MpBusInfo\n    {\n        std::size_t id; // C1, Not nec. consecutive.\n        int type; // C2, 1 = PQ, 2 = PV, 3 = SL, 4 = isolated.\n        double Pd; // C3, MW\n        double Qd; // C4, MVAr\n        double Gs; // C5, MW demand @ V = 1 pu\n        double Bs; // C6, MVAr demand @ V = 1 pu\n        int busArea; // C7\n        double VMag; // C8, pu\n        double VAngDeg; // C9, pu\n        double kVBase; // C10, kV\n        int zone; // C11\n        double VMagMax; // C12, pu\n        double VMagMin; // C13, pu\n        double lam_P; // C14, u/pu\n        double lam_Q; // C15, u/pu\n        double mu_VMax; // C16, u/pu\n        double mu_VMin; // C17, u/pu\n    };\n\n    struct MpBranchInfo\n    {\n        std::size_t busIdF;\n        std::size_t busIdT;\n        double R;\n        double X;\n        double b;\n        double rateA;\n        double rateB;\n        double rateC;\n        double tap;\n        double shiftDeg;\n        int status;\n        double angMinDeg;\n        double angMaxDeg;\n    };\n\n    struct MpGenInfo\n    {\n        std::size_t busId;\n        double Pg; // MW\n        double Qg; // MVAr\n        double QMax; // MVAr\n        double QMin; // MVAr\n        double Vg; // pu\n        double MVABase; // MVA\n        int status;\n        double PMax; // MVA\n        double PMin; // MVA\n    };\n\n    struct MpGenCostInfo\n    {\n        int model;\n        double startup;\n        double shutdown;\n        std::vector<double> costs;\n    };\n\n    namespace\n    {\n        std::size_t nDigits(std::size_t n) \n        {\n            return n == 0 ? 1 : static_cast<std::size_t>(std::floor(std::log10(n)) + 1);\n        }\n\n        std::string zeroPadded(std::size_t n, std::size_t nDigits)\n        {\n            auto result = std::to_string(n);\n            size_t len = result.length();\n            if (len < nDigits) result.insert(0, nDigits - len, '0');\n            return result;\n        }\n\n        std::string getBusName(std::size_t id, std::map<std::size_t, std::string>& map, std::size_t nDigits)\n        {\n            return map.insert(std::make_pair(id, \"bus_\" + zeroPadded(id, nDigits))).first->second;\n        }\n\n        std::string getZipName(std::size_t iZip, const std::string& busName, std::size_t nDigits)\n        {\n            return \"zip_\" + zeroPadded(iZip, nDigits) + \"_\" + busName;\n        }\n        \n        std::string getGenName(std::size_t iGen, const std::string& busName, std::size_t nDigits)\n        {\n            return \"gen_\" + zeroPadded(iGen, nDigits) + \"_\" + busName;\n        }\n\n        std::string getBranchName(std::size_t iBranch, const std::string& busName0, const std::string& busName1, \n                std::size_t nDigits)\n        {\n            return \"branch_\" + zeroPadded(iBranch, nDigits) + \"_\" + busName0 + \"_\" + busName1;\n        }\n\n        bool checkNzCplx(Complex x)\n        {\n            static constexpr double eps = std::numeric_limits<double>::epsilon();\n            return std::abs(x.real()) >= eps || std::abs(x.imag()) >= eps;\n        }\n\n        bool checkNzZip(Complex SConst, Complex YConst)\n        {\n\n            return checkNzCplx(SConst) || checkNzCplx(YConst);\n        }\n    }\n\n    void MatpowerParserPlugin::parse(const YAML::Node& nd, Network& netw, const ParserBase& parser) const\n    {\n        assertFieldPresent(nd, \"default_kV_base\");\n\n        double default_kVBase = parser.expand<double>(nd[\"default_kV_base\"]);\n\n        double VScale = 1.0;\n        auto ndVScale = nd[\"scale_V_by\"];\n        if (ndVScale)\n        {\n            VScale = ndVScale.as<double>();\n        }\n        double PScale = 1.0;\n        auto ndPScale = nd[\"scale_P_by\"];\n        if (ndPScale)\n        {\n            PScale = ndPScale.as<double>();\n        }\n        double RScale = VScale * VScale / PScale;\n        double GScale = 1.0 / RScale;\n\n        YAML::Node busNamesNd = nd[\"bus_names\"];\n        std::map<size_t, std::string> busNames;\n        if (busNamesNd)\n        {\n            for (auto keyVal : busNamesNd)\n            {\n                busNames[keyVal.first.as<size_t>()] = keyVal.second.as<std::string>();\n            }\n        }\n\n        auto ndInputFile = nd[\"input_file\"];\n        auto ndEmbeddedInput = nd[\"embedded_input\"];\n\n        sgtAssert(static_cast<bool>(ndInputFile) != static_cast<bool>(ndEmbeddedInput),\n                \"Parsing matpower data: \\\"input_file\\\" or \\\"embedded_input\\\" must be present, but not both\");\n\n        std::unique_ptr<std::istream> inStream;\n        if (ndInputFile)\n        {\n            std::string inputFName = parser.expand<std::string>(ndInputFile);\n            auto inFStream = new std::fstream(inputFName);\n            sgtAssert(inFStream->is_open(), \"Could not open the matpower input file \" << inputFName << \".\");\n            inStream.reset(inFStream);\n            sgtLogMessage() << \"Parsing matpower input file \" << inputFName << \".\" << std::endl;\n        }\n        else\n        {\n            inStream.reset(new std::stringstream(ndEmbeddedInput.as<std::string>()));\n            sgtLogMessage() << \"Parsing matpower embedded input.\" << std::endl;\n        }\n\n        // Parse in the raw matpower data.\n        MpData data;\n\n        {\n            Gram gram(data);\n\n\n            // Iterate over stream input:\n            BaseIterator inBegin(*inStream);\n\n            ForwardIterator fwdBegin = boost::spirit::make_default_multi_pass(inBegin);\n            ForwardIterator fwdEnd;\n\n            while (fwdBegin != fwdEnd)\n            {\n                qi::phrase_parse(fwdBegin, fwdEnd, gram, ascii::blank);\n            }\n        }\n\n        sgtLogMessage() << \"Parsed \" << data.bus.size() << \" buses, \" << data.gen.size() << \" generators and \"\n                        << data.branch.size() << \" branches.\" << std::endl;\n\n        // Extract the bus data.\n        std::size_t maxBusId = 0;\n        std::vector<MpBusInfo> busVec;\n        {\n            busVec.reserve(data.bus.size());\n            for (const auto& row : data.bus)\n            {\n                busVec.push_back(MpBusInfo{});\n                MpBusInfo& busInfo = busVec.back();\n\n                busInfo.id = static_cast<std::size_t>(row[0]);\n                if (maxBusId < busInfo.id) maxBusId = busInfo.id;\n                busInfo.type = static_cast<int>(row[1]);\n                busInfo.Pd = row[2];\n                busInfo.Qd = row[3];\n                busInfo.Gs = row[4];\n                busInfo.Bs = row[5];\n                busInfo.busArea = static_cast<int>(row[6]);\n                busInfo.VMag = row[7];\n                busInfo.VAngDeg = row[8];\n                busInfo.kVBase = row[9] > 1e-6 ? row[9] : default_kVBase;\n                busInfo.zone = static_cast<int>(row[10]);\n                busInfo.VMagMax = row[11];\n                busInfo.VMagMin = row[12];\n                if (data.bus[0].size() > 13)\n                {\n                    busInfo.lam_P = row[13];\n                    busInfo.lam_Q = row[14];\n                    busInfo.mu_VMax = row[15];\n                    busInfo.mu_VMin = row[16];\n                }\n            }\n        }\n        std::size_t busNDigits = nDigits(maxBusId);\n        std::size_t zipNDigits = busNDigits; // Upper bound.\n\n        // Extract the gen data.\n        std::vector<MpGenInfo> genVec;\n        {\n            genVec.reserve(data.gen.size());\n            for (const auto& row : data.gen)\n            {\n                genVec.push_back(MpGenInfo{});\n                MpGenInfo& genInfo = genVec.back();\n\n                genInfo.busId = static_cast<std::size_t>(row[0]);\n                genInfo.Pg = row[1];\n                genInfo.Qg = row[2];\n                genInfo.QMax = row[3];\n                genInfo.QMin = row[4];\n                genInfo.Vg = row[5];\n                genInfo.MVABase = row[6];\n                genInfo.status = static_cast<int>(row[7]);\n                genInfo.PMax = row[8];\n                genInfo.PMin = row[9];\n                // There are other fields, but at present we are ignoring them.\n            }\n        }\n        std::size_t genNDigits = nDigits(genVec.size() - 1);\n\n        // Extract the branch data.\n        std::vector<MpBranchInfo> branchVec;\n        {\n            branchVec.reserve(data.branch.size());\n            for (const auto& row : data.branch)\n            {\n                branchVec.push_back(MpBranchInfo{});\n                MpBranchInfo& branchInfo = branchVec.back();\n\n                branchInfo.busIdF = static_cast<std::size_t>(row[0]);\n                branchInfo.busIdT = static_cast<std::size_t>(row[1]);\n                branchInfo.R = row[2];\n                branchInfo.X = row[3];\n                branchInfo.b = row[4];\n                branchInfo.rateA = row[5];\n                branchInfo.rateB = row[6];\n                branchInfo.rateC = row[7];\n                branchInfo.tap = row[8];\n                branchInfo.shiftDeg = row[9];\n                branchInfo.status = static_cast<int>(row[10]);\n                branchInfo.angMinDeg = row[11];\n                branchInfo.angMaxDeg = row[12];\n            }\n        }\n        std::size_t branchNDigits = nDigits(branchVec.size() - 1);\n\n        // Extract the genCost data.\n        if (data.genCost.size() > 0)\n        {\n            if (data.genCost.size() == 2 * data.gen.size())\n            {\n                sgtLogWarning() << \"Reactive generator costs not yet implemented. Ignoring them.\" << std::endl;\n            }\n            else\n            {\n                sgtAssert(data.genCost.size() == data.gen.size(),\n                        \"There are a different number of generators to generator costs.\");\n            }\n        }\n\n        std::vector<MpGenCostInfo> genCostVec;\n        {\n            genCostVec.reserve(data.gen.size());\n            if (data.genCost.size() > 0)\n            {\n                for (std::size_t i = 0; i < data.gen.size(); ++i)\n                {\n                    auto row = data.genCost[i];\n                    genCostVec.push_back(MpGenCostInfo{});\n                    MpGenCostInfo& genCostInfo = genCostVec.back();\n\n                    genCostInfo.model = static_cast<int>(row[0]);\n                    genCostInfo.startup = row[1];\n                    genCostInfo.shutdown = row[2];\n                    auto nCost = static_cast<size_t>(row[3]);\n                    genCostInfo.costs.reserve(nCost);\n                    for (std::size_t j = 0; j < nCost; ++j)\n                    {\n                        genCostInfo.costs.push_back(row[4 + j]);\n                    }\n                }\n            }\n        }\n\n        // Network:\n        netw.setPBase(data.MVABase);\n\n        // Buses:\n        std::size_t nZip = 0;\n        for (const auto& busInfo : busVec)\n        {\n            std::string busId = getBusName(busInfo.id, busNames, busNDigits);\n            std::unique_ptr<Bus> bus(\n                new Bus(busId, {Phase::BAL}, {VScale * Complex(busInfo.kVBase, 0.0)}, PScale * busInfo.kVBase));\n            BusType type = BusType::BAD;\n            bool isInService = true;\n            switch (busInfo.type)\n            {\n                case 1:\n                    type = BusType::PQ;\n                    break;\n                case 2:\n                    type = BusType::PV;\n                    break;\n                case 3:\n                    type = BusType::SL;\n                    break;\n                case 4:\n                    type = BusType::BAD;\n                    isInService = false;\n                    break;\n                default:\n                    break;\n            }\n            bus->setType(type);\n            bus->setIsInService(isInService);\n\n            bus->setVMagMin(busInfo.VMagMin <= -infinity\n                    ? -infinity\n                    : VScale * pu2kV(busInfo.VMagMin, busInfo.kVBase));\n            bus->setVMagMax(busInfo.VMagMax >= infinity\n                    ? infinity\n                    : VScale * pu2kV(busInfo.VMagMax, busInfo.kVBase));\n\n            double VMag = pu2kV(busInfo.VMag, busInfo.kVBase);\n            double VAng = deg2Rad(busInfo.VAngDeg);\n            bus->setV({VScale * std::polar(VMag, VAng)});\n\n            netw.addBus(std::move(bus));\n\n            Complex SConst = Complex(busInfo.Pd, busInfo.Qd); // Already in MW.\n            Complex YConst = YBusShunt2Siemens(Complex(busInfo.Gs, busInfo.Bs), busInfo.kVBase);\n            if (checkNzZip(SConst, YConst))\n            {\n                std::string zipId = getZipName(nZip++, getBusName(busInfo.id, busNames, busNDigits), zipNDigits);\n                std::unique_ptr<Zip> zip(new Zip(zipId, {Phase::BAL}));\n                zip->setYConst(arma::Mat<Complex>({GScale * YConst}));\n                zip->setSConst(arma::Mat<Complex>({PScale * SConst}));\n                netw.addZip(std::move(zip), busId);\n            }\n        } // Buses\n\n        // If there is no slack bus, Matpower assigns the first PV bus as slack. We need to do the same.\n        auto it = std::find_if(netw.buses().cbegin(), netw.buses().cend(),\n                [](const ConstComponentPtr<Bus>& bus)->bool{return bus->type() == BusType::SL;});\n        if (it == netw.buses().cend())\n        {\n            sgtLogWarning()\n                    << \"There is no slack bus defined on the network. Setting the type of the first PV bus to SL.\"\n                    << std::endl;\n            auto itb = std::find_if(netw.buses().begin(), netw.buses().end(),\n                                    [](const ComponentPtr<Bus>& bus)->bool{return bus->type() == BusType::PV;});\n            assert(itb != netw.buses().end());\n            (**itb).setType(BusType::SL);\n        }\n        else\n        {\n            sgtLogMessage() << \"The slack bus is \" << (**it).id() << std::endl;\n        }\n\n        // Gens:\n        std::vector<Gen*> genCompVec;\n        genCompVec.reserve(genVec.size());\n        for (std::size_t i = 0; i < genVec.size(); ++i)\n        {\n            MpGenInfo& genInfo = genVec[i];\n            std::string genId = getGenName(i, getBusName(genInfo.busId, busNames, busNDigits), genNDigits);\n            std::unique_ptr<Gen> gen(new Gen(genId, {Phase::BAL}));\n            genCompVec.push_back(gen.get());\n\n            std::string busId = busNames.at(genInfo.busId);\n\n            gen->setIsInService(genInfo.status);\n\n            gen->setInServiceS({PScale * Complex(genInfo.Pg, genInfo.Qg)});\n\n            gen->setPMin(genInfo.PMin <= -infinity ? -infinity : PScale * genInfo.PMin);\n            gen->setPMax(genInfo.PMax >= infinity ? infinity : PScale * genInfo.PMax);\n            gen->setQMin(genInfo.QMin <= -infinity ? -infinity : PScale * genInfo.QMin);\n            gen->setQMax(genInfo.QMax >= infinity ? infinity : PScale * genInfo.QMax);\n\n            gen->setC0(0.0);\n            gen->setC1(0.0);\n            gen->setC2(0.0);\n\n            if (gen->isInService())\n            {\n                auto bus = netw.buses()[busId];\n                bus->setVMagSetpoint({VScale * pu2kV(genInfo.Vg, bus->VBase())});\n            }\n\n            netw.addGen(std::move(gen), busId);\n        } // Gens\n\n        // Branches:\n        for (std::size_t i = 0; i < branchVec.size(); ++i)\n        {\n            const MpBranchInfo& branchInfo = branchVec[i];\n\n            std::string bus0Name = getBusName(branchInfo.busIdF, busNames, busNDigits);\n            std::string bus1Name = getBusName(branchInfo.busIdT, busNames, busNDigits);\n            std::string branchName = getBranchName(i, bus0Name, bus1Name, branchNDigits);\n\n            std::unique_ptr<CommonBranch> branch(new CommonBranch(branchName));\n\n            branch->setIsInService(branchInfo.status);\n\n            auto bus0 = netw.buses()[bus0Name];\n            auto bus1 = netw.buses()[bus1Name];\n\n            double tap = (std::abs(branchInfo.tap) < 1e-6 ? 1.0 : branchInfo.tap) * bus0->VBase() / bus1->VBase();\n            branch->setTapRatio(std::polar(tap, deg2Rad(branchInfo.shiftDeg)));\n            branch->setYSeries(GScale * YBranch2Siemens(1.0 / Complex(branchInfo.R, branchInfo.X), bus1->VBase(),\n                               data.MVABase));\n            branch->setYShunt(GScale * YBranch2Siemens(Complex(0.0, branchInfo.b), bus1->VBase(), data.MVABase));\n            branch->setRateA(branchInfo.rateA == 0.0 ? infinity : PScale * branchInfo.rateA);\n            branch->setRateB(branchInfo.rateB == 0.0 ? infinity : PScale * branchInfo.rateB);\n            branch->setRateC(branchInfo.rateC == 0.0 ? infinity : PScale * branchInfo.rateC);\n            branch->setAngMin(branchInfo.angMinDeg * pi / 180.0);\n            branch->setAngMax(branchInfo.angMaxDeg * pi / 180.0);\n\n            netw.addBranch(std::move(branch), bus0Name, bus1Name);\n        }\n\n        // Add generator costs, if they exist.\n        for (std::size_t i = 0; i < genCostVec.size(); ++i)\n        {\n            const MpGenCostInfo& genCostInfo = genCostVec[i];\n\n            bool isBad = false;\n\n            if (genCostInfo.costs.size() > 3)\n            {\n                sgtLogWarning() << \"Can't have more than three costs for generator. Ignoring costs.\" << std::endl;\n                isBad = true;\n            }\n\n            if (genCostInfo.model != 2)\n            {\n                sgtLogWarning() << \"Can only use model 2 for generator costs. Ignoring costs.\" << std::endl;\n                isBad = true;\n            }\n\n            if (!isBad)\n            {\n                Gen& gen = *genCompVec[i];\n                gen.setCStartup(genCostInfo.startup);\n                gen.setCShutdown(genCostInfo.shutdown);\n                auto nCost = genCostInfo.costs.size();\n                if (nCost >= 1)\n                {\n                    gen.setC0(genCostInfo.costs[2]);\n                }\n                if (nCost >= 2)\n                {\n                    gen.setC1(genCostInfo.costs[1]);\n                }\n                if (nCost >= 3)\n                {\n                    gen.setC2(genCostInfo.costs[0]);\n                }\n            }\n        }\n    } // parse(...)\n}\n", "meta": {"hexsha": "f09420f4f6b417d4c2a76c9cfb52e64ad85ceae3", "size": 22900, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SgtCore/MatpowerParserPlugin.cc", "max_stars_repo_name": "dexterurbane/SmartGridToolbox", "max_stars_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "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": "SgtCore/MatpowerParserPlugin.cc", "max_issues_repo_name": "dexterurbane/SmartGridToolbox", "max_issues_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SgtCore/MatpowerParserPlugin.cc", "max_forks_repo_name": "dexterurbane/SmartGridToolbox", "max_forks_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "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.2341772152, "max_line_length": 114, "alphanum_fraction": 0.5229694323, "num_tokens": 5834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658972248186, "lm_q2_score": 0.03210070567529684, "lm_q1q2_score": 0.011767788784978937}}
{"text": "//     Copyright (c) 2012 Vadym Kliuchnikov sqct(dot)software(at)gmail(dot)com, Dmitri Maslov, Michele Mosca\n//\n//     This file is part of SQCT.\n// \n//     SQCT 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//     SQCT 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 SQCT.  If not, see <http://www.gnu.org/licenses/>.\n// \n\n#include <fstream>\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include \"epsilonnet.h\"\n#include \"output.h\"\n\n#include <boost/range.hpp>\nusing boost::make_iterator_range;\n\nusing namespace std;\n\n/// \\brief Header of the file with epsilon net\nstruct epsilonnetHeader\n{\n    size_t nodes_count;\n};\n\nstd::ostream& operator<<(std::ostream& out, const enetNode& node )\n{\n    out << \"enetNode[\" << node.ipxx << \",\" << node.ipQxx << \",\"\n        << node.num_offset << \",\" << node.compl_offset << \"]\";\n    return out;\n}\n\nbool epsilonnet::loadFromFile(const char* filename)\n{\n    epsilonnetHeader eh;\n    ifstream ifs( filename, ios_base::binary );\n    if( !ifs )\n        return false;\n    ifs.read( (char*) &eh,sizeof(eh));\n    nodes.clear();\n    nodes.resize( eh.nodes_count );\n    ifs.read( (char*) &nodes[0], nodes.size() * sizeof(enetNode) );\n    numbers.clear();\n    numbers.resize( nodes.back().num_offset );\n    ifs.read( (char*) &numbers[0], numbers.size() * sizeof(ri) );\n    ifs.close();\n    denominator_exponent = denominatorExponent2();\n    return true;\n}\n\nepsilonnet::epsilonnet()\n{\n    enetNode nd={0,0,0,0};\n    nodes.push_back(nd);\n}\n\nsize_t epsilonnet::nodesCount(const char* filename) const\n{\n    epsilonnetHeader eh;\n    ifstream ifs( filename, ios_base::binary );\n    ifs.read( (char*) &eh,sizeof(eh));\n    ifs.close();\n    return eh.nodes_count;\n}\n\nvoid epsilonnet::saveToFile  (const char* filename) const\n{\n    if( numbers.size() == 0 )\n        return;\n\n    epsilonnetHeader eh;\n    eh.nodes_count = nodes.size();\n    ofstream ofs( filename, ios_base::binary );\n    ofs.write( (const char*) &eh,sizeof(eh));\n\n    assert( nodes.back().ipxx == 0 );\n    assert( nodes.back().ipQxx == 0 );\n    assert( nodes.back().num_offset == numbers.size() );\n\n    ofs.write( (const char*) &nodes[0], nodes.size() * sizeof(enetNode) );\n    ofs.write( (const char*) &numbers[0], numbers.size() * sizeof(ri) );\n\n    ofs.close();\n}\n\n/// \\brief Comparator based on pointers data\ntemplate< class T>\nstruct eq_ptr\n{\n    bool operator() ( const T* a , const T* b )\n    {\n        return *a == *b;\n    }\n};\n\n/// \\brief Modified stub of back_insert_iterator from http://www.cplusplus.com/reference/std/iterator/back_insert_iterator/\ntemplate <class Container>\n  class back_insert_iterator_ptr :\n    public iterator<output_iterator_tag,void,void,void,void>\n{\nprotected:\n  Container* container;\n\npublic:\n  typedef Container container_type;\n  explicit back_insert_iterator_ptr (Container& x) : container(&x) {}\n  back_insert_iterator_ptr<Container>& operator= (const typename Container::value_type* value)\n    { container->push_back(*value); return *this; }\n  back_insert_iterator_ptr<Container>& operator* ()\n    { return *this; }\n  back_insert_iterator_ptr<Container>& operator++ ()\n    { return *this; }\n  back_insert_iterator_ptr<Container> operator++ (int)\n    { return *this; }\n};\n\nvoid epsilonnet::addNode( const pair< ip_type,ip_type>& ip, const nodeRangesPtr &ranges)\n{\n    nodes.back().ipxx = ip.first;\n    nodes.back().ipQxx = ip.second;\n\n    eq_ptr< ri > eq_ri;\n    back_insert_iterator_ptr< vector<ri> > biit( numbers );\n\n    int size = numbers.size();\n    unique_copy( ranges.nums_begin, ranges.nums_end , biit , eq_ri );\n    nodes.back().compl_offset = numbers.size() - size;\n    unique_copy( ranges.nums_compl_begin, ranges.nums_compl_end , biit , eq_ri );\n\n    enetNode en = {0,0,numbers.size(),0};\n    nodes.push_back(en);\n}\n\nvoid epsilonnet::addNode(epsilonnet::ip_type ipxx, epsilonnet::ip_type ipQxx, const nodeRanges &ranges)\n{\n    nodes.back().ipxx = ipxx;\n    nodes.back().ipQxx = ipQxx;\n\n    auto bi = back_inserter( numbers );\n    int size = numbers.size();\n    unique_copy( ranges.nums_begin, ranges.nums_end ,bi );\n    nodes.back().compl_offset = numbers.size() - size;\n    unique_copy( ranges.nums_compl_begin, ranges.nums_compl_end , bi );\n\n    enetNode en = {0,0,numbers.size(),0};\n    nodes.push_back(en);\n}\n\nvoid epsilonnet::getNode(size_t node_id, nodeRanges &ranges) const\n{\n    const enetNode& node = nodes[ node_id ];\n    ranges.nums_begin = numbers.begin() + node.num_offset;\n    ranges.nums_end = numbers.begin() + complOffset( node_id );\n    ranges.nums_compl_begin = ranges.nums_end;\n    ranges.nums_compl_end = numbers.begin() + nodes[ node_id + 1 ].num_offset;\n}\n\nsize_t epsilonnet::complOffset(size_t nodeId) const\n{\n    const enetNode& node = nodes[ nodeId ];\n    return node.num_offset + node.compl_offset;\n}\n\nint epsilonnet::denominatorExponent2() const\n{\n    size_t offset = complOffset(0);\n    auto denom = numbers[offset].ipxx() + numbers[0].ipxx();\n    int val = ri::gde2( denom );\n    // overflow check\n    decltype( denom ) d = 1;\n    d <<= val;\n    assert( d == denom && \"Sum of ipxx for number and complementary number is not a power of 2.\" );\n    //denominator_exponent = val;\n    return val;\n}\n\nint epsilonnet::sde() const\n{\n    int res = ::sde( 2 * denominatorExponent2(), numbers[0].abs2().gde() );\n    if( res == std::numeric_limits<int>::max() ) res = 0;\n    return res;\n}\n\ndouble epsilonnet::findExhaustiveApproximation(const epsilonnet::vector2double &vec, epsilonnet::vi &result) const\n{\n    //denominator_exponent = denominatorExponent2();\n    vi current;\n    double current_dist = 1.0;\n    double best_dist = 1.0;\n    vector2double canonical_vec = vec;\n    bool conj_1 = false, conj_2 = false;\n    int w_pow1 = 0, w_pow2 = 0;\n    canonical_vec.first = canonical( vec.first, w_pow1, conj_1 );\n    canonical_vec.second = canonical( vec.second, w_pow2, conj_2 );\n\n    for( int i = 0; i < nodes.size(); ++i )\n    {\n        current_dist = findExhaustiveApproximation( canonical_vec, current, i );\n        if( best_dist > current_dist )\n        {\n            best_dist = current_dist;\n            result  = current;\n        }\n    }\n\n//    cout << result.de << \":\" << endl;\n//    cout <<  canonical_vec.first << result.d[0].toComplex( result.de ) << endl;\n//    cout <<  canonical_vec.second << result.d[1].toComplex( result.de ) << endl;\n\n    if( conj_1 ) result.d[0].conjugate_eq();\n    if( conj_2 ) result.d[1].conjugate_eq();\n    result.d[0].mul_eq_w( w_pow1 );\n    result.d[1].mul_eq_w( w_pow2 );\n    result.de = denominator_exponent;\n\n    return best_dist;\n}\n\ntypedef  epsilonnet::vector2double vd;\n\n/// \\brief Inline Euclidean distance computation\ninline double dist_squared( const vd& a, const vd& b )\n{\n    double d1 = a.first.real() - b.first.real();\n    double d2 = a.second.real() - b.second.real();\n    double d3 = a.first.imag() - b.first.imag();\n    double d4 = a.second.imag() - b.second.imag();\n    return d1*d1 +d2*d2 +d3*d3 + d4*d4;\n}\n\n/// \\brief Inline Euclidean distance computation\ninline double dist_squared( const vd& a, double fre,  double fim , double sre ,  double sim )\n{\n    double d1 = a.first.real() - fre;\n    double d2 = a.second.real() - sre;\n    double d3 = a.first.imag() - fim;\n    double d4 = a.second.imag() - sim;\n    return d1*d1 +d2*d2 +d3*d3 + d4*d4;\n}\n\n/// \\todo Remove code duplication by changing one of epsilonnet::findExhaustiveApproximation\ndouble epsilonnet::findExhaustiveApproximation(const epsilonnet::vector2double &vec, epsilonnet::vi &result, int node_id) const\n{\n    double best = 3.0;\n    nodeRanges nr;\n    getNode( node_id, nr );\n    auto ic = nr.nums_begin;\n    auto jc = nr.nums_compl_begin;\n    bool tw = true;\n    for( auto i = nr.nums_begin; i != nr.nums_end ;++i )\n    {\n        double iim, ire;\n        i->toComplex( denominator_exponent, ire, iim );\n        for( auto j = nr.nums_compl_begin; j != nr.nums_compl_end; ++j )\n        {\n            double jim, jre;\n            j->toComplex( denominator_exponent, jre, jim  );\n            double d1 = dist_squared( vec, ire, iim, jre, jim );\n            double d2 = dist_squared( vec, jre, jim, ire, iim );\n\n            if( d1 < best )\n            {\n                best = d1;\n                ic = i; jc = j;\n                tw = false;\n            }\n\n            if( d2 < best )\n            {\n                best = d2;\n                ic = i; jc = j;\n                tw = true;\n            }\n        }\n    }\n\n    if( tw )\n    {\n        result.d[0] = *jc;\n        result.d[1] = *ic;\n        //result.de = denominator_exponent; // -avoid extra operations\n    }\n    else\n    {\n        result.d[0] = *ic;\n        result.d[1] = *jc;\n        //result.de = denominator_exponent; // -avoid extra operations\n    }\n\n    return best;\n}\n\ndouble epsilonnet::findExhaustiveApproximation(const epsilonnet::vector2double &vec, epsilonnet::vi &result, int node_id, double &bdist) const\n{\n    nodeRanges nr;\n    getNode( node_id, nr );\n    bool found = false;\n    auto ic = nr.nums_begin;\n    auto jc = nr.nums_compl_begin;\n    bool tw = true;\n    for( auto i = nr.nums_begin; i != nr.nums_end ;++i )\n    {\n        double iim, ire;\n        i->toComplex( denominator_exponent, ire, iim );\n        for( auto j = nr.nums_compl_begin; j != nr.nums_compl_end; ++j )\n        {\n            double jim, jre;\n            j->toComplex( denominator_exponent, jre, jim  );\n            double d1 = dist_squared( vec, ire, iim, jre, jim );\n            double d2 = dist_squared( vec, jre, jim, ire, iim );\n\n            if( d1 < bdist )\n            {\n                found = true;\n                bdist = d1;\n                ic = i; jc = j;\n                tw = false;\n            }\n\n            if( d2 < bdist )\n            {\n                found = true;\n                bdist = d2;\n                ic = i; jc = j;\n                tw = true;\n            }\n        }\n    }\n\n    if( found )\n    {\n        if( tw )\n        {\n            result.d[0] = *jc;\n            result.d[1] = *ic;\n            result.de = denominator_exponent;\n        }\n        else\n        {\n            result.d[0] = *ic;\n            result.d[1] = *jc;\n            result.de = denominator_exponent;\n        }\n    }\n\n    return bdist;\n}\n\n//// Code that was used to iterate through epsilon net. Does not required now\n\n//private:\n//    /// \\brief Executes functor for all complex values in epsilon net\n//    template< class T>\n//    void for_all_complex( T& functor ) const;\n//    /// \\brief Executes functor for all complex values in epsilon net within node\n//    template< class T>\n//    void for_all_complex( T& functor, int node_id ) const;\n//    /// \\brief Executes functor for all complex values in epsilon net within node with fixed first element\n//    template< class T>\n//    void for_all_complex( T& functor, nodeRanges& nr, ri& a ) const;\n//    /// \\brief Executes functor for a, b and elements that are of the form \\f$ a\\omega^k, a\\omega^k \\f$\n//    template< class T>\n//    void for_all_complex( T& functor, std::complex<double>& a, ri& b ) const;\n\n//template< class T>\n//void epsilonnet::for_all_complex( T& functor ) const\n//{\n//    denominator_exponent = denominatorExponent2();\n//    for( int i = 0; i < nodes.size() - 1 ; ++i )\n//        for_all_complex( functor, i );\n//}\n\n//template< class T>\n//void epsilonnet::for_all_complex( T& functor, int node_id ) const\n//{\n//    nodeRanges nr;\n//    getNode( node_id, nr );\n//    for( auto i : make_iterator_range( nr.nums_begin, nr.nums_end) )\n//    {\n//        ri a(i);\n//        if( i.is_im_eq0() )\n//        {\n//            for_all_complex( functor, nr, a );\n//        }\n//        else\n//        {\n//            for_all_complex( functor, nr, a );\n//            a.conjugate_eq();\n//            for_all_complex( functor, nr, a );\n//        }\n//    }\n//}\n\n//template< class T>\n//void epsilonnet::for_all_complex( T& functor, nodeRanges& nr, ri& a ) const\n//{\n//    for( int i = 0; i < 8 ; ++i )\n//    {\n//        a.mul_eq_w();\n//        auto first = a.toComplex( denominator_exponent );\n//        for( auto j : make_iterator_range(nr.nums_compl_begin, nr.nums_compl_end) )\n//        {\n//            ri b(j);\n//            if( j.is_im_eq0() )\n//            {\n//                for_all_complex( functor, first, b );\n//            }\n//            else\n//            {\n//                for_all_complex( functor, first, b );\n//                b.conjugate_eq();\n//                for_all_complex( functor, first, b );\n//            }\n//        }\n//    }\n//}\n\n//template< class T>\n//void epsilonnet::for_all_complex( T& functor, std::complex<double>& first, ri& b ) const\n//{\n//    int max_ph = 1;\n//    if( all_phases ) max_ph = 8;\n\n//    for( int i = 0; i < max_ph ; ++i )\n//    {\n//        b.mul_eq_w();\n//        auto second = b.toComplex( denominator_exponent );\n//        functor( first, second );\n//        functor( second, first );\n//    }\n//}\n", "meta": {"hexsha": "1bf3a8f20344350dfbbee366f09f822ab48ce955", "size": 13377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rotations/sqct/epsilonnet.cpp", "max_stars_repo_name": "teaguetomesh/ScaffCC", "max_stars_repo_head_hexsha": "52b087a00ac19384a736b4c64631ca67bd1d8054", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-05T23:28:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T23:28:35.000Z", "max_issues_repo_path": "Rotations/sqct/epsilonnet.cpp", "max_issues_repo_name": "teaguetomesh/ScaffCC", "max_issues_repo_head_hexsha": "52b087a00ac19384a736b4c64631ca67bd1d8054", "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": "Rotations/sqct/epsilonnet.cpp", "max_forks_repo_name": "teaguetomesh/ScaffCC", "max_forks_repo_head_hexsha": "52b087a00ac19384a736b4c64631ca67bd1d8054", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-05T23:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T23:42:06.000Z", "avg_line_length": 30.1283783784, "max_line_length": 142, "alphanum_fraction": 0.5977423937, "num_tokens": 3624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.03622005586497474, "lm_q1q2_score": 0.01174382426449247}}
{"text": "//=======================================================================\n// Copyright 2014-2015 David Simmons-Duffin.\n// Distributed under the MIT License.\n// (See accompanying file LICENSE or copy at\n//  http://opensource.org/licenses/MIT)\n//=======================================================================\n\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <ostream>\n#include <string>\n#include \"omp.h\"\n//Tweak to allow Ubuntu-14.04/gcc-4.8.4 and similar environments to compile\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n#include <boost/filesystem.hpp>\n#undef BOOST_NO_CXX11_SCOPED_ENUMS\n#include \"boost/filesystem.hpp\"\n#include \"boost/date_time/posix_time/posix_time.hpp\"\n#include \"boost/program_options.hpp\"\n#include \"types.h\"\n#include \"Timers.h\"\n#include \"SDP.h\"\n#include \"parse.h\"\n#include \"SDPSolver.h\"\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::setfill;\nusing std::setw;\n\nusing boost::filesystem::path;\nusing boost::posix_time::second_clock;\n\nnamespace po = boost::program_options;\n\nTimers timers;\n\nint solveSDP(const vector<path> &sdpFiles,\n             const path &outFile,\n             const path &checkpointFileIn,\n             const path &checkpointFileOut,\n             SDPSolverParameters parameters) {\n  // Set the default precision of all Real numbers to that specified\n  // by the 'precision' parameter.\n  mpf_set_default_prec(parameters.precision);\n\n  // Set cout to print the appropriate number of digits\n  cout.precision(min(static_cast<int>(parameters.precision * 0.31 + 5), 30));\n\n  // Ensure all the Real parameters have the appropriate precision\n  parameters.resetPrecision();\n\n  // Set the maximum number of threads for parallel loops\n  omp_set_num_threads(parameters.maxThreads);\n\n  cout << \"SDPB started at \" << second_clock::local_time() << endl;\n  for (auto const& sdpFile: sdpFiles) {\n    cout << \"SDP file        : \" << sdpFile        << endl;\n  }\n  cout << \"out file        : \" << outFile        << endl;\n  cout << \"checkpoint in   : \" << checkpointFileIn << endl;\n  cout << \"checkpoint out  : \" << checkpointFileOut << endl;\n\n  cout << \"\\nParameters:\\n\";\n  cout << parameters << endl;\n\n  // Read an SDP from sdpFile and create a solver for it\n  SDPSolver solver(readBootstrapSDP(sdpFiles), parameters);\n\n  if (exists(checkpointFileIn))\n    solver.loadCheckpoint(checkpointFileIn);\n\n  timers[\"Solver runtime\"].start();\n  timers[\"Last checkpoint\"].start();\n  SDPSolverTerminateReason reason = solver.run(checkpointFileOut);\n  timers[\"Solver runtime\"].stop();\n\n  cout << \"-----\" << setfill('-') << setw(116) << std::left << reason << endl;\n  cout << endl;\n  cout << \"primalObjective = \" << solver.primalObjective << endl;\n  cout << \"dualObjective   = \" << solver.dualObjective   << endl;\n  cout << \"dualityGap      = \" << solver.dualityGap      << endl;\n  cout << \"primalError     = \" << solver.primalError     << endl;\n  cout << \"dualError       = \" << solver.dualError       << endl;\n  cout << endl;\n\n  if (!parameters.noFinalCheckpoint)\n    solver.saveCheckpoint(checkpointFileOut);\n  timers[\"Last checkpoint\"].stop();\n  solver.saveSolution(reason, outFile);\n\n  cout << endl << timers;\n\n  return 0;\n}\n\nint main(int argc, char** argv) {\n  vector<path> sdpFiles;\n  path outFile;\n  path checkpointFileIn;\n  path checkpointFileOut;\n  path paramFile;\n\n  SDPSolverParameters parameters;\n\n  po::options_description basicOptions(\"Basic options\");\n  basicOptions.add_options()\n    (\"help,h\", \"Show this helpful message.\")\n    (\"sdpFile,s\",\n     po::value< vector<path> >(&sdpFiles)->required(),\n     \"SDP data file(s) in XML format. Use this option repeatedly to specify multiple data files.\")\n    (\"paramFile,p\",\n     po::value<path>(&paramFile),\n     \"Any parameter can optionally be set via this file in key=value \"\n     \"format. Command line arguments override values in the parameter \"\n     \"file.\")\n    (\"outFile,o\",\n     po::value<path>(&outFile),\n     \"The optimal solution is saved to this file in Mathematica \"\n     \"format. Defaults to sdpFile with '.out' extension.\")\n    (\"checkpointFile,c\",\n     po::value<path>(&checkpointFileOut),\n     \"Checkpoints are saved to this file every checkpointInterval. Defaults \"\n     \"to sdpFile with '.ck' extension.\")\n    (\"initialCheckpointFile,i\",\n     po::value<path>(&checkpointFileIn),\n     \"The initial checkpoint to load. Defaults to checkpointFile.\")\n    ;\n\n  po::options_description solverParamsOptions(\"Solver parameters\");\n  solverParamsOptions.add_options()\n    (\"precision\",\n     po::value<int>(&parameters.precision)->default_value(400),\n     \"Precision in binary digits.  GMP will round up to the nearest \"\n     \"multiple of 64 (or 32 on older systems).\")\n    (\"maxThreads\",\n     po::value<int>(&parameters.maxThreads)->default_value(4),\n     \"Maximum number of threads to use for parallel calculation.\")\n    (\"checkpointInterval\",\n     po::value<int>(&parameters.checkpointInterval)->default_value(3600),\n     \"Save checkpoints to checkpointFile every checkpointInterval seconds.\")\n    (\"noFinalCheckpoint\",\n     po::bool_switch(&parameters.noFinalCheckpoint)->default_value(false),\n     \"Don't save a final checkpoint after terminating (useful when debugging).\")\n    (\"findPrimalFeasible\",\n     po::bool_switch(&parameters.findPrimalFeasible)->default_value(false),\n     \"Terminate once a primal feasible solution is found.\")\n    (\"findDualFeasible\",\n     po::bool_switch(&parameters.findDualFeasible)->default_value(false),\n     \"Terminate once a dual feasible solution is found.\")\n    (\"detectPrimalFeasibleJump\",\n     po::bool_switch(&parameters.detectPrimalFeasibleJump)->default_value(false),\n     \"Terminate if a primal-step of 1 is taken. This often indicates that a \"\n     \"primal feasible solution would be found if the precision were high \"\n     \"enough. Try increasing either primalErrorThreshold or precision \"\n     \"and run from the latest checkpoint.\")\n    (\"detectDualFeasibleJump\",\n     po::bool_switch(&parameters.detectDualFeasibleJump)->default_value(false),\n     \"Terminate if a dual-step of 1 is taken. This often indicates that a \"\n     \"dual feasible solution would be found if the precision were high \"\n     \"enough. Try increasing either dualErrorThreshold or precision \"\n     \"and run from the latest checkpoint.\")\n    (\"maxIterations\",\n     po::value<int>(&parameters.maxIterations)->default_value(500),\n     \"Maximum number of iterations to run the solver.\")\n    (\"maxRuntime\",\n     po::value<int>(&parameters.maxRuntime)->default_value(86400),\n     \"Maximum amount of time to run the solver in seconds.\")\n    (\"dualityGapThreshold\",\n     po::value<Real>(&parameters.dualityGapThreshold)->default_value(Real(\"1e-30\")),\n     \"Threshold for duality gap (roughly the difference in primal and dual \"\n     \"objective) at which the solution is considered \"\n     \"optimal. Corresponds to SDPA's epsilonStar.\")\n    (\"primalErrorThreshold\",\n     po::value<Real>(&parameters.primalErrorThreshold)->default_value(Real(\"1e-30\")),\n     \"Threshold for feasibility of the primal problem. Corresponds to SDPA's \"\n     \"epsilonBar.\")\n    (\"dualErrorThreshold\",\n     po::value<Real>(&parameters.dualErrorThreshold)->default_value(Real(\"1e-30\")),\n     \"Threshold for feasibility of the dual problem. Corresponds to SDPA's epsilonBar.\")\n    (\"initialMatrixScalePrimal\",\n     po::value<Real>(&parameters.initialMatrixScalePrimal)->default_value(Real(\"1e20\")),\n     \"The primal matrix X begins at initialMatrixScalePrimal times the \"\n     \"identity matrix. Corresponds to SDPA's lambdaStar.\")\n    (\"initialMatrixScaleDual\",\n     po::value<Real>(&parameters.initialMatrixScaleDual)->default_value(Real(\"1e20\")),\n     \"The dual matrix Y begins at initialMatrixScaleDual times the \"\n     \"identity matrix. Corresponds to SDPA's lambdaStar.\")\n    (\"feasibleCenteringParameter\",\n     po::value<Real>(&parameters.feasibleCenteringParameter)->default_value(Real(\"0.1\")),\n     \"Shrink the complementarity X Y by this factor when the primal and dual \"\n     \"problems are feasible. Corresponds to SDPA's betaStar.\")\n    (\"infeasibleCenteringParameter\",\n     po::value<Real>(&parameters.infeasibleCenteringParameter)->default_value(Real(\"0.3\")),\n     \"Shrink the complementarity X Y by this factor when either the primal \"\n     \"or dual problems are infeasible. Corresponds to SDPA's betaBar.\")\n    (\"stepLengthReduction\",\n     po::value<Real>(&parameters.stepLengthReduction)->default_value(Real(\"0.7\")),\n     \"Shrink each newton step by this factor (smaller means slower, more \"\n     \"stable convergence). Corresponds to SDPA's gammaStar.\")\n    (\"choleskyStabilizeThreshold\",\n     po::value<Real>(&parameters.choleskyStabilizeThreshold)->default_value(Real(\"1e-40\")),\n     \"Adds stabilizing terms to the cholesky decomposition of the schur complement \"\n     \"matrix for diagonal entries which are smaller than this threshold times the \"\n     \"geometric mean of other diagonal entries. Somewhat higher choleskyStabilizeThreshold \"\n     \"can improve numerical stability but if the threshold is large enough that a high \"\n     \"proportion of eigenvalues are being stabilized, the computation will slow substantially.\")\n    (\"maxComplementarity\",\n     po::value<Real>(&parameters.maxComplementarity)->default_value(Real(\"1e100\")),\n     \"Terminate if the complementarity mu = Tr(X Y)/dim(X) exceeds this value.\")\n    ;\n\n  po::options_description cmdLineOptions;\n  cmdLineOptions.add(basicOptions).add(solverParamsOptions);\n\n  po::variables_map variablesMap;\n\n  try {\n    po::store(po::parse_command_line(argc, argv, cmdLineOptions), variablesMap);\n\n    if (variablesMap.count(\"help\")) {\n      cout << cmdLineOptions << endl;\n      return 0;\n    }\n\n    if (variablesMap.count(\"paramFile\")) {\n      paramFile = variablesMap[\"paramFile\"].as<path>();\n      std::ifstream ifs(paramFile.string().c_str());\n      po::store(po::parse_config_file(ifs, solverParamsOptions), variablesMap);\n    }\n\n    po::notify(variablesMap);\n\n    if (!variablesMap.count(\"outFile\")) {\n      outFile = sdpFiles[0];\n      outFile.replace_extension(\"out\");\n    }\n\n    if (!variablesMap.count(\"checkpointFile\")) {\n      checkpointFileOut = sdpFiles[0];\n      checkpointFileOut.replace_extension(\"ck\");\n    }\n\n    if (!variablesMap.count(\"initialCheckpointFile\")) {\n      checkpointFileIn = checkpointFileOut;\n    }\n\n    std::ofstream ofs(outFile.string().c_str());\n    ofs.close();\n    if (!ofs) {\n      cerr << \"Cannot write to outFile.\" << endl;\n      return 1;\n    }\n  } catch(po::error& e) {\n    cerr << \"ERROR: \" << e.what() << endl;\n    cerr << cmdLineOptions << endl;\n    return 1;\n  }\n\n  return solveSDP(sdpFiles, outFile, checkpointFileIn, checkpointFileOut, parameters);\n}\n", "meta": {"hexsha": "db602eb3d0f7eb083c17b586c0fe3dd60fe340a0", "size": 10696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "rajeeves/sdpb", "max_stars_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_stars_repo_licenses": ["MIT"], "max_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": "rajeeves/sdpb", "max_issues_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_issues_repo_licenses": ["MIT"], "max_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": "rajeeves/sdpb", "max_forks_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_forks_repo_licenses": ["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.2105263158, "max_line_length": 98, "alphanum_fraction": 0.6891361257, "num_tokens": 2522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.03732688747799252, "lm_q1q2_score": 0.011722529355311423}}
{"text": "#include \"lir.hpp\"\n\n#include <iostream>\n#include <unordered_map>\n#include <unordered_set>\n\n#include <boost/range/adaptor/reversed.hpp>\n\nnamespace algrad {\nnamespace compiler {\n\nusing Live_set = std::unordered_set<unsigned>;\n\nLive_set\nget_live_out(std::vector<Live_set>& liveIn, lir::Program const& program, lir::Block& bb)\n{\n    Live_set ret;\n    for (int logical = 0; logical < 2; ++logical) {\n        for (auto succ : (logical ? bb.logicalSuccessors() : bb.linearizedSuccessors())) {\n            for (auto e : liveIn[succ->id()])\n                if ((logical && program.temp_info(e).reg_class == lir::RegClass::vgpr) ||\n                    (!logical && program.temp_info(e).reg_class != lir::RegClass::vgpr))\n                    ret.insert(e);\n            int index = -1;\n            unsigned i = 0;\n            for (auto pred : (logical ? succ->logicalPredecessors() : succ->linearizedPredecessors())) {\n                if (pred == &bb)\n                    index = i;\n                ++i;\n            }\n\n            for (auto& insn : succ->instructions()) {\n                if (insn->opCode() != lir::OpCode::phi)\n                    break;\n                auto reg_class = program.temp_info(insn->getDefinition(0).temp()).reg_class;\n                if ((logical && reg_class == lir::RegClass::vgpr) || (!logical && reg_class != lir::RegClass::vgpr))\n                    ret.insert(insn->getOperand(index).temp());\n            }\n        }\n    }\n    return ret;\n}\nstd::vector<Live_set>\ncompute_live_in(lir::Program& program)\n{\n    std::vector<Live_set> live_in(program.blocks().size());\n\n    for (;;) {\n        bool changed = false;\n        for (auto& bb : boost::adaptors::reverse(program.blocks())) {\n            auto live = get_live_out(live_in, program, *bb);\n            for (auto& insn : boost::adaptors::reverse(bb->instructions())) {\n                auto defCount = insn->definitionCount();\n                for (unsigned i = 0; i < defCount; ++i) {\n                    auto it = live.find(insn->getDefinition(i).temp());\n                    if (it != live.end())\n                        live.erase(it);\n                }\n\n                if (insn->opCode() != lir::OpCode::phi) {\n                    auto op_count = insn->operandCount();\n                    for (unsigned i = 0; i < op_count; ++i) {\n                        if (insn->getOperand(i).is_temp()) {\n                            insn->getOperand(i).setKill(live.find(insn->getOperand(i).temp()) == live.end());\n                        }\n                    }\n                    for (unsigned i = 0; i < op_count; ++i) {\n                        if (insn->getOperand(i).is_temp()) {\n                            if (live.find(insn->getOperand(i).temp()) == live.end())\n                                live.insert(insn->getOperand(i).temp());\n                        }\n                    }\n                }\n            }\n            if (live != live_in[bb->id()]) {\n                live_in[bb->id()] = live;\n                changed = true;\n            }\n        }\n        if (!changed)\n            break;\n    }\n    return live_in;\n}\n\nvoid\ninsert_copies(lir::Program& program)\n{\n    auto live_in = compute_live_in(program);\n    for (auto& bb : program.blocks()) {\n        std::vector<std::unique_ptr<lir::Inst>> instructions;\n        instructions.reserve(bb->instructions().size());\n        auto live = get_live_out(live_in, program, *bb);\n\n        for (auto it = bb->instructions().end(); it != bb->instructions().begin();) {\n            --it;\n            auto& insn = *it;\n            bool need_move = false;\n            auto def_count = insn->definitionCount();\n            for (std::size_t i = 0; i < def_count; ++i) {\n                auto const& def = insn->getDefinition(i);\n                if (def.is_temp() && def.isFixed())\n                    need_move = true;\n                auto it = live.find(def.temp());\n                if (it != live.end())\n                    live.erase(it);\n            }\n\n            auto op_count = insn->operandCount();\n            for (std::size_t i = 0; i < op_count; ++i) {\n                auto arg = insn->getOperand(i);\n                if (arg.is_temp()) {\n                    if (arg.isFixed())\n                        need_move = true;\n                    live.insert(arg.temp());\n                }\n            }\n\n            instructions.push_back(std::move(insn));\n            if (need_move && !live.empty()) {\n                auto copy = std::make_unique<lir::Inst>(lir::OpCode::parallel_copy, live.size(), live.size());\n                unsigned idx = 0;\n                for (auto e : live) {\n                    copy->getOperand(idx) = lir::Arg{e};\n                    copy->getDefinition(idx) = lir::Arg{e};\n                    ++idx;\n                }\n                instructions.push_back(std::move(copy));\n            }\n        }\n\n        std::reverse(instructions.begin(), instructions.end());\n        bb->instructions() = std::move(instructions);\n    }\n}\n\nvoid\nfix_ssa_rename_visit(lir::Program& program, lir::Block& block, std::vector<bool>& visited,\n                     std::vector<unsigned>& renames, std::vector<std::pair<unsigned, unsigned>>& undo, bool logical)\n{\n    if (visited[block.id()])\n        return;\n    visited[block.id()] = true;\n\n    auto undo_size = undo.size();\n    for (auto& insn : block.instructions()) {\n        if (insn->opCode() != lir::OpCode::phi) {\n            auto op_count = insn->operandCount();\n            for (std::size_t i = 0; i < op_count; ++i) {\n                auto id = insn->getOperand(i).temp();\n                if ((logical && program.temp_info(id).reg_class != lir::RegClass::vgpr) ||\n                    (!logical && program.temp_info(id).reg_class == lir::RegClass::vgpr))\n                    continue;\n                if (renames[id] == ~0U)\n                    std::terminate();\n\n                insn->getOperand(i).set_temp(renames[id]);\n            }\n        }\n\n        auto def_count = insn->definitionCount();\n        for (std::size_t i = 0; i < def_count; ++i) {\n            auto id = insn->getDefinition(i).temp();\n            if ((logical && program.temp_info(id).reg_class != lir::RegClass::vgpr) ||\n                (!logical && program.temp_info(id).reg_class == lir::RegClass::vgpr))\n                continue;\n            undo.push_back({id, renames[id]});\n            if (renames[id] == ~0U) {\n                renames[id] = id;\n            } else {\n                auto new_temp = program.allocate_temp(program.temp_info(id).reg_class, program.temp_info(id).size);\n                renames[id] = new_temp;\n                insn->getDefinition(i).set_temp(new_temp);\n            }\n        }\n    }\n\n    for (auto succ : (logical ? block.logicalSuccessors() : block.linearizedSuccessors())) {\n        auto index = lir::findBlock(logical ? succ->logicalPredecessors() : succ->linearizedPredecessors(), &block);\n        for (auto& inst : succ->instructions()) {\n            if (inst->opCode() != lir::OpCode::phi)\n                break;\n            if ((logical && program.temp_info(inst->getDefinition(0).temp()).reg_class != lir::RegClass::vgpr) ||\n                (!logical && program.temp_info(inst->getDefinition(0).temp()).reg_class == lir::RegClass::vgpr))\n                continue;\n\n            auto id = inst->getOperand(index).temp();\n            if (renames.at(id) == ~0U)\n                std::terminate();\n\n            inst->getOperand(index).set_temp(renames[id]);\n        }\n    }\n\n    if (logical) {\n        for (auto succ : block.logicalSuccessors())\n            fix_ssa_rename_visit(program, *succ, visited, renames, undo, logical);\n    } else {\n        for (auto succ : block.linearizedSuccessors())\n            fix_ssa_rename_visit(program, *succ, visited, renames, undo, logical);\n    }\n\n    for (std::size_t i = undo.size(); i > undo_size; --i) {\n        renames[undo[i - 1].first] = undo[i - 1].second;\n    }\n\n    undo.resize(undo_size);\n}\n\nvoid\nfix_ssa_rename(lir::Program& program)\n{\n    std::vector<bool> visited(program.blocks().size());\n    std::vector<unsigned> renames(program.allocated_temp_count(), ~0U);\n    std::vector<std::pair<unsigned, unsigned>> undo;\n    fix_ssa_rename_visit(program, *program.blocks()[0], visited, renames, undo, false);\n    std::fill(visited.begin(), visited.end(), false);\n    std::fill(renames.begin(), renames.end(), ~0U);\n    fix_ssa_rename_visit(program, *program.blocks()[0], visited, renames, undo, true);\n}\nvoid\nfix_ssa(lir::Program& program)\n{\n    fix_ssa_rename(program);\n}\nbool\nallowed(std::vector<bool> const& forbidden, unsigned index, unsigned size)\n{\n    for (unsigned i = 0; i < size; ++i)\n        if (forbidden[i + index])\n            return false;\n    return true;\n}\n\nvoid\nset_forbidden(std::vector<bool>& forbidden, unsigned index, unsigned size, bool value)\n{\n    for (unsigned i = 0; i < size; ++i)\n        forbidden[i + index] = value;\n}\n\nstd::vector<int>\ncolor_registers(lir::Program& program)\n{\n    std::vector<std::unordered_set<unsigned>> ig(program.allocated_temp_count());\n    std::vector<int> colors(program.allocated_temp_count(), -1);\n    auto live_in = compute_live_in(program);\n\n    for (auto& bb : program.blocks()) {\n        std::vector<bool> colors_used(2048);\n        for (auto e : live_in[bb->id()]) {\n            auto size = program.temp_info(e).size;\n            for (std::size_t i = 0; i < size; ++i)\n                colors_used[colors[e] + i] = true;\n        }\n        for (auto it = bb->instructions().begin(); it != bb->instructions().end(); ++it) {\n            if ((*it)->opCode() != lir::OpCode::phi) {\n                auto op_count = (*it)->operandCount();\n                for (std::size_t i = 0; i < op_count; ++i) {\n                    auto& arg = (*it)->getOperand(i);\n                    if (arg.is_temp()) {\n                        if (arg.kill()) {\n                            set_forbidden(colors_used, colors[arg.temp()], program.temp_info(arg.temp()).size, false);\n                        }\n                        arg.setFixed(lir::PhysReg{static_cast<unsigned>(colors[arg.temp()])});\n                    }\n                }\n            }\n\n            auto def_count = (*it)->definitionCount();\n            for (std::size_t i = 0; i < def_count; ++i) {\n                auto& def = (*it)->getDefinition(i);\n                if (colors[def.temp()] < 0) {\n                    std::vector<bool> forbidden = colors_used;\n                    int c = -1;\n                    if (def.isFixed()) {\n                        c = def.physReg().reg;\n                    }\n                    if (it + 1 != bb->instructions().end() && (*it)->opCode() == lir::OpCode::parallel_copy) {\n                        auto op_count_2 = it[1]->operandCount();\n                        for (unsigned j = 0; j < op_count_2; ++j) {\n                            auto const& arg2 = it[1]->getOperand(j);\n                            if (arg2.isFixed()) {\n                                if (def.temp() != arg2.temp())\n                                    set_forbidden(forbidden, arg2.physReg().reg, program.temp_info(arg2.temp()).size,\n                                                  true);\n                                else\n                                    c = arg2.physReg().reg;\n                            }\n                        }\n                    }\n                    if (c == -1 && (*it)->opCode() == lir::OpCode::parallel_copy) {\n                        auto& prev_arg = (*it)->getOperand(i);\n                        if (prev_arg.temp() && !prev_arg.kill()) {\n                            std::cerr << prev_arg.temp() << \" has no kill\\n\";\n                        }\n                        if (allowed(forbidden, prev_arg.physReg().reg, program.temp_info(prev_arg.temp()).size)) {\n                            c = prev_arg.physReg().reg;\n                        } else\n                            std::cerr << \"preferred move failed for \" << def.temp() << \" \" << prev_arg.temp() << \"\\n\";\n                    }\n                    if (c == -1 && (*it)->opCode() == lir::OpCode::phi) {\n                        int candidate = -1;\n                        auto op_count = (*it)->operandCount();\n                        for (std::size_t j = 0; j < op_count; ++j) {\n                            if ((*it)->getOperand(j).is_temp() && colors[(*it)->getOperand(j).temp()] >= 0)\n                                candidate = colors[(*it)->getOperand(j).temp()];\n                        }\n                        if (candidate >= 0 && allowed(forbidden, candidate, program.temp_info(def.temp()).size)) {\n                            c = candidate;\n                        }\n                    }\n\n                    if (c == -1) {\n                        c = program.temp_info(def.temp()).reg_class == lir::RegClass::vgpr ? 1024 : 0;\n                        while (!allowed(forbidden, c, program.temp_info(def.temp()).size))\n                            c += program.temp_info(def.temp()).size;\n                    }\n\n                    set_forbidden(colors_used, c, program.temp_info(def.temp()).size, true);\n                    colors[def.temp()] = c;\n                }\n                def.setFixed(lir::PhysReg{static_cast<unsigned>(colors[def.temp()])});\n            }\n        }\n    }\n    for (auto& bb : program.blocks()) {\n        for (auto it = bb->instructions().begin();\n             it != bb->instructions().end() && (*it)->opCode() == lir::OpCode::phi; ++it) {\n            auto op_count = (*it)->operandCount();\n            for (std::size_t i = 0; i < op_count; ++i) {\n                auto& arg = (*it)->getOperand(i);\n                if (arg.is_temp()) {\n                    arg.setFixed(lir::PhysReg{static_cast<unsigned>(colors[arg.temp()])});\n                }\n            }\n        }\n    }\n    return colors;\n}\n\nbool\nhas_logical_phis(lir::Program& program, lir::Block& block)\n{\n    for (auto it = block.instructions().begin();\n         it != block.instructions().end() && (*it)->opCode() == lir::OpCode::phi; ++it)\n        if (program.temp_info((*it)->getDefinition(0).temp()).reg_class == lir::RegClass::vgpr)\n            return true;\n    return false;\n}\n\nbool\nhas_linearized_phis(lir::Program& program, lir::Block& block)\n{\n    for (auto it = block.instructions().begin();\n         it != block.instructions().end() && (*it)->opCode() == lir::OpCode::phi; ++it)\n        if (program.temp_info((*it)->getDefinition(0).temp()).reg_class != lir::RegClass::vgpr)\n            return true;\n    return false;\n}\n\nvoid\ndestroy_phis(lir::Program& program)\n{\n    for (auto& bb : program.blocks()) {\n        for (auto succ : bb->linearizedSuccessors())\n            if (has_linearized_phis(program, *succ))\n                std::terminate();\n\n        std::vector<std::pair<lir::Arg, lir::Arg>> args;\n        for (auto succ : bb->logicalSuccessors()) {\n            auto index = lir::findOrInsertBlock(succ->logicalPredecessors(), bb.get());\n            for (auto it = succ->instructions().begin();\n                 it != succ->instructions().end() && (*it)->opCode() == lir::OpCode::phi; ++it) {\n                if (program.temp_info((*it)->getDefinition(0).temp()).reg_class != lir::RegClass::vgpr)\n                    continue;\n                // if ((*it)->getOperand(index).physReg().reg == (*it)->getDefinition(0).physReg().reg)\n                //    continue;\n                args.emplace_back((*it)->getOperand(index), (*it)->getDefinition(0));\n            }\n        }\n        if (args.empty())\n            continue;\n\n        auto inst = std::make_unique<lir::Inst>(lir::OpCode::parallel_copy, args.size(), args.size());\n        for (std::size_t i = 0; i < args.size(); ++i) {\n            inst->getOperand(i) = args[i].first;\n            inst->getDefinition(i) = args[i].second;\n        }\n\n        auto it = --bb->instructions().end();\n        bb->instructions().insert(it, std::move(inst));\n    }\n\n    for (auto& bb : program.blocks()) {\n        auto it = bb->instructions().begin();\n        while (it != bb->instructions().end() && (*it)->opCode() == lir::OpCode::phi)\n            ++it;\n        bb->instructions().erase(bb->instructions().begin(), it);\n    }\n}\n\nvoid\nallocateRegisters(lir::Program& program)\n{\n    insert_copies(program);\n    fix_ssa(program);\n    color_registers(program);\n    destroy_phis(program);\n}\n}\n}\n", "meta": {"hexsha": "643df9389bc633da2d945ba1f2c0e64505d6e595", "size": 16295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compiler/src/register_allocation.cpp", "max_stars_repo_name": "BNieuwenhuizen/algrad", "max_stars_repo_head_hexsha": "361b0ce84768534f9e110688cb74171abf95fcd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "compiler/src/register_allocation.cpp", "max_issues_repo_name": "BNieuwenhuizen/algrad", "max_issues_repo_head_hexsha": "361b0ce84768534f9e110688cb74171abf95fcd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compiler/src/register_allocation.cpp", "max_forks_repo_name": "BNieuwenhuizen/algrad", "max_forks_repo_head_hexsha": "361b0ce84768534f9e110688cb74171abf95fcd1", "max_forks_repo_licenses": ["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.4552058111, "max_line_length": 118, "alphanum_fraction": 0.4897207732, "num_tokens": 3833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.02931223340125078, "lm_q1q2_score": 0.011719372129901897}}
{"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_python_interface.hh\"\n\n#include <boost/python.hpp>\n#include <boost/graph/astar_search.hpp>\n\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_util.hh\"\n\n#include \"graph_astar.hh\"\n\n#include \"coroutine.hh\"\n#include \"graph_python_interface.hh\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\ntemplate <class T>\npython::object operator |(const python::object& a, const T& b)\n{\n    return a / b;\n}\n\nstruct do_astar_search\n{\n    template <class Graph, class DistanceMap, class PredMap, class Visitor>\n    void operator()(Graph& g, size_t s, DistanceMap dist, PredMap pred,\n                    boost::any aweight, Visitor vis, pair<AStarCmp, AStarCmb> cmp,\n                    pair<python::object, python::object> range,\n                    python::object h, GraphInterface& gi) const\n    {\n        typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n        typedef typename property_traits<DistanceMap>::value_type dtype_t;\n        dtype_t z = python::extract<dtype_t>(range.first);\n        dtype_t i = python::extract<dtype_t>(range.second);\n        checked_vector_property_map<default_color_type,\n                                    decltype(get(vertex_index, g))>\n            color(get(vertex_index, g));\n        checked_vector_property_map<dtype_t,\n                                    decltype(get(vertex_index, g))>\n            cost(get(vertex_index, g));\n        DynamicPropertyMapWrap<dtype_t, edge_t> weight(aweight,\n                                                       edge_properties());\n        astar_search(g, vertex(s, g), AStarH<Graph, dtype_t>(gi, g, h),\n                     vis, pred, cost, dist, weight, get(vertex_index, g), color,\n                     cmp.first, cmp.second, i, z);\n   }\n};\n\nstruct do_astar_search_fast\n{\n    template <class Graph, class DistanceMap, class WeightMap,\n              class Visitor>\n    void operator()(Graph& g, size_t s, DistanceMap dist,\n                    WeightMap weight, Visitor vis,\n                    pair<python::object, python::object> range,\n                    python::object h, GraphInterface& gi) const\n    {\n        typedef typename property_traits<DistanceMap>::value_type dtype_t;\n        dtype_t z = python::extract<dtype_t>(range.first);\n        dtype_t i = python::extract<dtype_t>(range.second);\n        astar_search(g, vertex(s, g), AStarH<Graph, dtype_t>(gi, g, h),\n                     weight_map(weight).distance_map(dist).distance_zero(z).\n                     distance_inf(i).visitor(vis));\n   }\n};\n\n\nvoid a_star_search(GraphInterface& g, size_t source, boost::any dist_map,\n                   boost::any pred_map, boost::any weight, python::object vis,\n                   python::object cmp, python::object cmb, python::object zero,\n                   python::object inf, python::object h)\n{\n    typedef typename property_map_type::\n        apply<int64_t, GraphInterface::vertex_index_map_t>::type pred_t;\n    pred_t pred = any_cast<pred_t>(pred_map);\n    run_action<graph_tool::all_graph_views,mpl::true_>()\n        (g, std::bind(do_astar_search(),  std::placeholders::_1, source,\n                      std::placeholders::_2, pred, weight,\n                      AStarVisitorWrapper(g, vis), make_pair(AStarCmp(cmp),\n                                                             AStarCmb(cmb)),\n                      make_pair(zero, inf), h, std::ref(g)),\n         writable_vertex_properties())(dist_map);\n}\n\n#ifdef HAVE_BOOST_COROUTINE\n\nclass AStarGeneratorVisitor : public astar_visitor<>\n{\npublic:\n    AStarGeneratorVisitor(GraphInterface& gi,\n                          coro_t::push_type& yield)\n        : _gi(gi), _yield(yield) {}\n\n    template <class Edge, class Graph>\n    void edge_relaxed(const Edge& e, Graph& g)\n    {\n        auto gp = retrieve_graph_view<Graph>(_gi, g);\n        _yield(boost::python::object(PythonEdge<Graph>(gp, e)));\n    }\n\nprivate:\n    GraphInterface& _gi;\n    coro_t::push_type& _yield;\n};\n\n#endif // HAVE_BOOST_COROUTINE\n\nboost::python::object astar_search_generator(GraphInterface& g,\n                                             size_t source,\n                                             boost::any dist_map,\n                                             boost::any weight,\n                                             python::object cmp,\n                                             python::object cmb,\n                                             python::object zero,\n                                             python::object inf,\n                                             python::object h)\n{\n#ifdef HAVE_BOOST_COROUTINE\n    auto dispatch = [&](auto& yield)\n        {\n            AStarGeneratorVisitor vis(g, yield);\n            run_action<graph_tool::all_graph_views,mpl::true_>()\n               (g, std::bind(do_astar_search(),  std::placeholders::_1, source,\n                             std::placeholders::_2, dummy_property_map(), weight,\n                             vis, make_pair(AStarCmp(cmp), AStarCmb(cmb)),\n                             make_pair(zero, inf), h, std::ref(g)),\n                writable_vertex_properties())(dist_map);\n        };\n    return boost::python::object(CoroGenerator(dispatch));\n#else\n    throw GraphException(\"This functionality is not available because boost::coroutine was not found at compile-time\");\n#endif\n}\n\nboost::python::object astar_search_generator_fast(GraphInterface& g,\n                                                  size_t source,\n                                                  boost::any dist_map,\n                                                  boost::any weight,\n                                                  python::object zero,\n                                                  python::object inf,\n                                                  python::object h)\n{\n#ifdef HAVE_BOOST_COROUTINE\n    auto dispatch = [&](auto& yield)\n        {\n            AStarGeneratorVisitor vis(g, yield);\n            run_action<graph_tool::all_graph_views,mpl::true_>()\n               (g, std::bind(do_astar_search_fast(),  std::placeholders::_1, source,\n                             std::placeholders::_2, std::placeholders::_3,\n                             vis, make_pair(zero, inf), h, std::ref(g)),\n                writable_vertex_scalar_properties(),\n                edge_scalar_properties())(dist_map, weight);\n        };\n    return boost::python::object(CoroGenerator(dispatch));\n#else\n    throw GraphException(\"This functionality is not available because boost::coroutine was not found at compile-time\");\n#endif\n}\n\nclass AStarArrayVisitor: public astar_visitor<>\n{\npublic:\n    AStarArrayVisitor(std::vector<std::array<size_t, 2>>& edges)\n        : _edges(edges) {}\n\n    template <class Edge, class Graph>\n    void edge_relaxed(const Edge& e, Graph& g)\n    {\n        _edges.push_back({{source(e, g), target(e,g)}});\n    }\n\nprivate:\n    std::vector<std::array<size_t, 2>>& _edges;\n};\n\nboost::python::object astar_search_array(GraphInterface& g,\n                                         size_t source,\n                                         boost::any dist_map,\n                                         boost::any weight,\n                                         python::object cmp,\n                                         python::object cmb,\n                                         python::object zero,\n                                         python::object inf,\n                                         python::object h)\n{\n    std::vector<std::array<size_t, 2>> edges;\n    AStarArrayVisitor vis(edges);\n    run_action<graph_tool::all_graph_views,mpl::true_>()\n        (g, std::bind(do_astar_search(),  std::placeholders::_1, source,\n                      std::placeholders::_2, dummy_property_map(), weight,\n                      vis, make_pair(AStarCmp(cmp), AStarCmb(cmb)),\n                      make_pair(zero, inf), h, std::ref(g)),\n         writable_vertex_properties())(dist_map);\n    return wrap_vector_owned<size_t,2>(edges);\n}\n\nboost::python::object astar_search_array_fast(GraphInterface& g,\n                                              size_t source,\n                                              boost::any dist_map,\n                                              boost::any weight,\n                                              python::object zero,\n                                              python::object inf,\n                                              python::object h)\n{\n    std::vector<std::array<size_t, 2>> edges;\n    AStarArrayVisitor vis(edges);\n    run_action<graph_tool::all_graph_views,mpl::true_>()\n        (g, std::bind(do_astar_search_fast(),  std::placeholders::_1, source,\n                      std::placeholders::_2, std::placeholders::_3,\n                      vis, make_pair(zero, inf), h, std::ref(g)),\n         writable_vertex_scalar_properties(),\n         edge_scalar_properties())(dist_map, weight);\n    return wrap_vector_owned<size_t,2>(edges);\n}\n\nvoid export_astar()\n{\n    using namespace boost::python;\n    def(\"astar_search\", &a_star_search);\n    def(\"astar_generator\", &astar_search_generator);\n    def(\"astar_generator_fast\", &astar_search_generator_fast);\n    def(\"astar_array\", &astar_search_array);\n    def(\"astar_array_fast\", &astar_search_array_fast);\n}\n", "meta": {"hexsha": "aed8668c8d9feeb8d8b2a6afa88534f7742e6690", "size": 10080, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/search/graph_astar.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/search/graph_astar.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/search/graph_astar.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": 41.1428571429, "max_line_length": 119, "alphanum_fraction": 0.562202381, "num_tokens": 2075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.026759280080849098, "lm_q1q2_score": 0.011715842031352614}}
{"text": "#include <mpi.h>\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <iostream>\n#include <fstream>\n\n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <memory>\n#include <cmath>\n#include <stdlib.h>\n\n#include <getopt.h>\n\n#include <unsupported/Eigen/SparseExtra>\n\n#include \"linop.h\"\n#include \"macau_mpi.h\"\n#include \"macau.h\"\n\nextern \"C\" {\n  #include \"dsparse.h\"\n}\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid usage() {\n   printf(\"Usage:\\n\");\n   printf(\"  macau_mpi --train <train_file> --row-features <feature-file> [options]\\n\");\n   printf(\"Optional:\\n\");\n   printf(\"  --test    test_file  test data (for computing RMSE)\\n\");\n   printf(\"  --burnin        200  number of samples to discard\\n\");\n   printf(\"  --nsamples      800  number of samples to collect\\n\");\n   printf(\"  --num-latent     96  number of latent dimensions\\n\");\n   printf(\"  --precision     5.0  precision of observations\\n\");\n   printf(\"  --lambda-beta  10.0  initial value of lambda beta\\n\");\n   printf(\"  --tol          1e-6  tolerance for CG\\n\");\n   printf(\"  --output    results  prefix for result files\\n\");\n}\n\nbool file_exists(const char *fileName)\n{\n   std::ifstream infile(fileName);\n   return infile.good();\n}\n\nint get_num_omp_threads() {\n   int nt = 0;\n#pragma omp parallel\n   {\n#pragma omp single\n      {\n         nt = omp_get_num_threads();\n      }\n   }\n   return nt;\n}\n\nvoid die(std::string message, int world_rank) {\n   if (world_rank == 0) {\n      std::cout << message;\n   }\n   MPI_Finalize();\n   exit(1);\n}\n\nstd::unique_ptr<SparseFeat> load_bcsr(const char* filename) {\n   SparseBinaryMatrix* A = read_sbm(filename);\n   SparseFeat* sf = new SparseFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols);\n   free_sbm(A);\n   std::unique_ptr<SparseFeat> sf_ptr(sf);\n   return sf_ptr;\n}\n\n// var for MPI\nint* rhs_for_rank = NULL;\ndouble* rec     = NULL;\nint* sendcounts = NULL;\nint* displs     = NULL;\n\nint main(int argc, char** argv) {\n   // Initialize the MPI environment\n   MPI_Init(NULL, NULL);\n   // Get the number of processes\n   int world_size, world_rank;\n   MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n   MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n\n   // Get the name of the processor\n   char processor_name[MPI_MAX_PROCESSOR_NAME];\n   int name_len;\n   MPI_Get_processor_name(processor_name, &name_len);\n\n   char* fname_train         = NULL;\n   char* fname_test          = NULL;\n   char* fname_row_features  = NULL;\n   std::string output_prefix = std::string(\"result\");\n   double precision   = 5.0;\n   double lambda_beta = 10.0;\n   double tol         = 1e-6;\n   int burnin     = 200;\n   int nsamples   = 800;\n   int num_latent = 96;\n\n   // reading command line arguments\n   while (1) {\n      static struct option long_options[] =\n      {\n         {\"train\",      required_argument, 0, 't'},\n         {\"test\",       required_argument, 0, 'e'},\n         {\"row-features\", required_argument, 0, 'r'},\n         {\"precision\",  required_argument, 0, 'p'},\n         {\"burnin\",     required_argument, 0, 'b'},\n         {\"nsamples\",   required_argument, 0, 'n'},\n         {\"output\",     required_argument, 0, 'o'},\n         {\"num-latent\", required_argument, 0, 'l'},\n         {\"lambda-beta\",required_argument, 0, 'a'},\n         {\"tol\",        required_argument, 0, 'c'},\n         {0, 0, 0, 0}\n      };\n      int option_index = 0;\n      int c = getopt_long(argc, argv, \"t:e:r:p:b:n:o:a:c:\", long_options, &option_index);\n      if (c == -1)\n         break;\n\n      switch (c) {\n         case 'a': lambda_beta   = strtod(optarg, NULL); break;\n         case 'b': burnin        = strtol(optarg, NULL, 10); break;\n         case 'c': tol           = atof(optarg); break;\n         case 'e': fname_test    = optarg; break;\n         case 'l': num_latent    = strtol(optarg, NULL, 10); break;\n         case 'n': nsamples      = strtol(optarg, NULL, 10); break;\n         case 'o': output_prefix = std::string(optarg); break;\n         case 'p': precision     = strtod(optarg, NULL); break;\n         case 'r': fname_row_features = optarg; break;\n         case 't': fname_train = optarg; break;\n         case '?':\n         default:\n           if (world_rank == 0)\n              usage();\n           MPI_Finalize();\n           exit(1);\n      }\n   }\n   if (fname_train == NULL || fname_row_features == NULL) {\n      if (world_rank == 0) {\n         printf(\"[ERROR]\\nMissing parameters '--matrix' or '--row-features'.\\n\");\n         usage();\n      }\n      MPI_Finalize();\n      exit(1);\n   }\n   if (world_rank == 0) {\n      printf(\"Train data:    '%s'\\n\", fname_train);\n      printf(\"Test data:     '%s'\\n\", fname_test==NULL ?\"\" :fname_test);\n      printf(\"Row features:  '%s'\\n\", fname_row_features);\n      printf(\"Output prefix: '%s'\\n\", output_prefix.c_str());\n      printf(\"Burn-in:       %d\\n\", burnin);\n      printf(\"Samples:       %d\\n\", nsamples);\n      printf(\"Num-latents:   %d\\n\", num_latent);\n      printf(\"Precision:     %.1f\\n\", precision);\n      printf(\"Lambda-beta:   %.1f\\n\", lambda_beta);\n      printf(\"tol:           %.1e\\n\", tol);\n   }\n   if ( ! file_exists(fname_train) ) {\n      die(std::string(\"[ERROR]\\nTrain data file '\") + fname_train + \"' not found.\\n\", world_rank);\n   }\n   if ( ! file_exists(fname_row_features) ) {\n      die(std::string(\"[ERROR]\\nRow feature file '\") + fname_row_features + \"' not found.\\n\", world_rank);\n   }\n   if ( (fname_test != NULL) && ! file_exists(fname_test) ) {\n      die(std::string(\"[ERROR]\\nTest data file '\") + fname_test + \"' not found.\\n\", world_rank);\n   }\n\n   int n_omp_threads = get_num_omp_threads();\n   rhs_for_rank = new int[world_size];\n   split_work_mpi(num_latent, world_size, rhs_for_rank);\n\n   // Print off a hello world message\n   printf(\"Processor %s, rank %d\"\n          \" out of %d processors using %d OpenMP threads for %d RHS.\\n\",\n          processor_name, world_rank, world_size, n_omp_threads, rhs_for_rank[world_rank]);\n\n   // Step 1. Loading data\n   //std::unique_ptr<SparseFeat> row_features = load_bcsr(fname_row_features);\n   auto row_features = load_bcsr(fname_row_features);\n   if (world_rank == 0) {\n      printf(\"Row features:   [%d x %d].\\n\", row_features->rows(), row_features->cols());\n   }\n   sendcounts = new int[world_size];\n   displs     = new int[world_size];\n   int sum = 0;\n   for (int n = 0; n < world_size; n++) {\n      sendcounts[n] = rhs_for_rank[n] * row_features->cols();\n      displs[n]     = sum;\n      sum          += sendcounts[n];\n   }\n   rec = new double[sendcounts[world_rank]];\n\n   SparseDoubleMatrix* Y     = NULL;\n   SparseDoubleMatrix* Ytest = NULL;\n\n   Macau* macau = new Macau(num_latent);\n   macau->setPrecision(precision);\n   macau->setSamples(burnin, nsamples);\n   macau->setVerbose(true);\n\n   // 1) row prior with side information\n   int nfeat    = row_features->rows();\n   auto prior_u = new MacauPrior<SparseFeat>(num_latent, row_features, false);\n   prior_u->setLambdaBeta(lambda_beta);\n   prior_u->setTol(tol);\n   auto prior_v = new BPMFPrior(num_latent);\n\n   // 2) activity data (read_sdm)\n   Y = read_sdm(fname_train);\n\n   if (nfeat != Y->nrow) {\n      die(std::string(\"[ERROR]\\nNumber of rows (\" +\n                      std::to_string(Y->nrow) +\n                      \") in train must be equal to number of rows in row-features (\" +\n                      std::to_string(row_features->rows()) +\n                      \").\"),\n          world_rank);\n   }\n\n   // 3) create Macau object\n   macau->setRelationData(Y->rows, Y->cols, Y->vals, Y->nnz, Y->nrow, Y->ncol);\n\n   // test data\n   if (fname_test != NULL) {\n      Ytest = read_sdm(fname_test);\n      if (Ytest->nrow != Y->nrow || Ytest->ncol != Y->ncol) {\n         die(std::string(\"[ERROR]\\nSize of train (\") +\n                         std::to_string(Y->nrow) + \" x \" +\n                         std::to_string(Y->ncol) + \") must be equal to size of test (\" +\n                         std::to_string(Ytest->nrow) + \" x \" +\n                         std::to_string(Ytest->ncol) + \").\",\n             world_rank);\n      }\n      macau->setRelationDataTest(Ytest->rows, Ytest->cols, Ytest->vals, Ytest->nnz, Ytest->nrow, Ytest->ncol);\n   }\n   std::unique_ptr<ILatentPrior> u_ptr(prior_u);\n   std::unique_ptr<ILatentPrior> v_ptr(prior_v);\n   macau->addPrior( u_ptr );\n   macau->addPrior( v_ptr );\n\n   if (world_rank == 0) {\n      printf(\"Training data:  %ld [%d x %d]\\n\", Y->nnz, Y->nrow, Y->ncol);\n      if (Ytest != NULL) {\n         printf(\"Test data:      %ld [%d x %d]\\n\", Ytest->nnz, Ytest->nrow, Ytest->ncol);\n      } else {\n         printf(\"Test data:      --\\n\");\n      }\n   }\n\n   run_macau_mpi(macau, world_rank);\n\n   // save results\n   if (world_rank == 0) {\n      VectorXd yhat_raw     = macau->getPredictions();\n      VectorXd yhat_sd_raw  = macau->getStds();\n      MatrixXd testdata_raw = macau->getTestData();\n\n      std::string fname_pred = output_prefix + \"-predictions.csv\";\n      std::ofstream predfile;\n      predfile.open(fname_pred);\n      predfile << \"row,col,y,y_pred,y_pred_std\\n\";\n      for (int i = 0; i < yhat_raw.size(); i++) {\n         predfile << to_string( (int)testdata_raw(i,0) );\n         predfile << \",\" << to_string( (int)testdata_raw(i,1) );\n         predfile << \",\" << to_string( testdata_raw(i,2) );\n         predfile << \",\" << to_string( yhat_raw(i) );\n         predfile << \",\" << to_string( yhat_sd_raw(i) );\n         predfile << \"\\n\";\n      }\n      predfile.close();\n      printf(\"Saved predictions into '%s'.\\n\", fname_pred.c_str());\n   }\n\n   // Finalize the MPI environment.\n   delete macau;\n   MPI_Finalize();\n   return 0;\n}\n\nvoid run_macau_mpi(\n      Macau* macau,\n      int world_rank)\n{\n   /* adapted from Macau.run() */\n   macau->init();\n   if (world_rank == 0 && macau->verbose) {\n      std::cout << \"Sampling\" << std::endl;\n   }\n\n   const int num_rows = macau->Y.rows();\n   const int num_cols = macau->Y.cols();\n   macau->predictions     = VectorXd::Zero( macau->Ytest.nonZeros() );\n   macau->predictions_var = VectorXd::Zero( macau->Ytest.nonZeros() );\n\n   auto start = tick();\n   for (int i = 0; i < macau->burnin + macau->nsamples; i++) {\n      if (world_rank == 0 && macau->verbose && i == macau->burnin) {\n         printf(\" ====== Burn-in complete, averaging samples ====== \\n\");\n      }\n      auto starti = tick();\n\n      if (world_rank == 0) {\n         // sample latent vectors\n         macau->noise->sample_latents(macau->priors[0], *macau->samples[0], macau->Yt, macau->mean_rating, *macau->samples[1], macau->num_latent);\n         macau->noise->sample_latents(macau->priors[1], *macau->samples[1], macau->Y,  macau->mean_rating, *macau->samples[0], macau->num_latent);\n         //macau->priors[0]->sample_latents(*macau->samples[0], macau->Yt, macau->mean_rating, *macau->samples[1], macau->alpha, macau->num_latent);\n         //macau->priors[1]->sample_latents(*macau->samples[1], macau->Y,  macau->mean_rating, *macau->samples[0], macau->alpha, macau->num_latent);\n      }\n\n      // Sample hyperparams\n      update_prior_mpi( *(MacauPrior<SparseFeat>*) macau->priors[0].get(), *macau->samples[0], world_rank);\n      if (world_rank == 0) {\n         macau->priors[1]->update_prior(*macau->samples[1]);\n\n         auto eval = eval_rmse(macau->Ytest, (i < macau->burnin) ? 0 : (i - macau->burnin), macau->predictions, macau->predictions_var,\n                               *macau->samples[1], *macau->samples[0], macau->mean_rating);\n\n         auto endi = tick();\n         auto elapsed = endi - start;\n         double samples_per_sec = (i + 1) * (num_rows + num_cols) / elapsed;\n         double elapsedi = endi - starti;\n\n         if (macau->verbose) {\n           macau->printStatus(i, eval.first, eval.second, elapsedi, samples_per_sec);\n         }\n         macau->rmse_test = eval.second;\n      }\n   }\n}\n\nvoid update_prior_mpi(MacauPrior<SparseFeat> &prior, const Eigen::MatrixXd &U, int world_rank) {\n   if (world_rank == 0) {\n      // residual (Uhat is later overwritten):\n      prior.Uhat.noalias() = U - prior.Uhat;\n      MatrixXd BBt = A_mul_At_combo(prior.beta);\n      // sampling Gaussian\n      std::tie(prior.mu, prior.Lambda) = CondNormalWishart(prior.Uhat, prior.mu0, prior.b0, prior.WI + prior.lambda_beta * BBt, prior.df + prior.beta.cols());\n   }\n   sample_beta_mpi(prior, U, world_rank);\n   if (world_rank == 0) { \n      compute_uhat(prior.Uhat, *prior.F, prior.beta);\n      prior.lambda_beta = sample_lambda_beta(prior.beta, prior.Lambda, prior.lambda_beta_nu0, prior.lambda_beta_mu0);\n   }\n}\n\nvoid sample_beta_mpi(MacauPrior<SparseFeat> &prior, const Eigen::MatrixXd &U, int world_rank) {\n   const int num_latent = prior.beta.rows();\n   const int num_feat = prior.beta.cols();\n   MatrixXd Ft_y(0,0);\n\n   if (world_rank == 0) {\n      // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + sqrt(lambda_beta) * Normal(0, Lambda^-1)\n      // Ft_y is [ D x F ] matrix\n      MatrixXd tmp = (U + MvNormal_prec_omp(prior.Lambda, U.cols())).colwise() - prior.mu;\n      Ft_y = A_mul_B(tmp, *prior.F);\n      MatrixXd tmp2 = MvNormal_prec_omp(prior.Lambda, num_feat);\n\n      #pragma omp parallel for schedule(static)\n      for (int f = 0; f < num_feat; f++) {\n         for (int d = 0; d < num_latent; d++) {\n            Ft_y(d, f) += sqrt(prior.lambda_beta) * tmp2(d, f);\n         }\n      }\n      Ft_y.transposeInPlace();\n   }\n\n   MPI_Bcast(& prior.lambda_beta, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n   MPI_Bcast(& prior.tol,         1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n   // sending Ft_y\n   MPI_Scatterv(Ft_y.data(), sendcounts, displs, MPI_DOUBLE, rec, sendcounts[world_rank], MPI_DOUBLE, 0, MPI_COMM_WORLD);\n   int nrhs = rhs_for_rank[world_rank];\n   MatrixXd RHS(nrhs, num_feat), result(nrhs, num_feat);\n\n#pragma omp parallel for schedule(static)\n   for (int f = 0; f < num_feat; f++) {\n      for (int d = 0; d < nrhs; d++) {\n         RHS(d, f) = rec[f + d * num_feat];\n      }\n   }\n   // solving\n   solve_blockcg(result, *prior.F, prior.lambda_beta, RHS, prior.tol, 32, 8);\n   result.transposeInPlace();\n   MPI_Gatherv(result.data(), nrhs*num_feat, MPI_DOUBLE, Ft_y.data(), sendcounts, displs, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n   if (world_rank == 0) {\n      //prior.beta = Ft_y.transpose();\n#pragma omp parallel for schedule(static)\n      for (int f = 0; f < num_feat; f++) {\n         for (int d = 0; d < num_latent; d++) {\n            prior.beta(d, f) = Ft_y(f, d);\n         }\n      }\n   }\n}\n", "meta": {"hexsha": "f76c942da0afe0e532e66c5f492c352ef2d30461", "size": 14353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/macau_mpi.cpp", "max_stars_repo_name": "edebrouwer/macau", "max_stars_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-02-27T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:17:39.000Z", "max_issues_repo_path": "lib/macau-cpp/macau_mpi.cpp", "max_issues_repo_name": "edebrouwer/macau", "max_issues_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-05-23T14:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T08:12:40.000Z", "max_forks_repo_path": "lib/macau-cpp/macau_mpi.cpp", "max_forks_repo_name": "edebrouwer/macau", "max_forks_repo_head_hexsha": "0b22d21ed954209406246e70178523102e98f922", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T12:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T15:05:59.000Z", "avg_line_length": 35.1789215686, "max_line_length": 158, "alphanum_fraction": 0.5907475789, "num_tokens": 4149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.02716922897563308, "lm_q1q2_score": 0.011686771806990225}}
{"text": "#include <iostream>\n#include <sstream>\n#include <cfloat>\n\n#include <armadillo>\n\n#include <cpp-argparse/OptionParser.h>\n#include <besiq/io/covariates.hpp>\n#include <besiq/stats/snp_count.hpp>\n\n#include <plink/plink_file.hpp>\n#include <dcdflib/libdcdf.hpp>\n\n#include \"gene_environment.hpp\"\n\nusing namespace arma;\nusing namespace optparse;\n\nconst std::string USAGE = \"besiq-lars [OPTIONS] plink_file\";\nconst std::string DESCRIPTION = \"Uses the LARS algorithm to find important loci.\";\nconst std::string VERSION = \"besiq 0.0.1\";\nconst std::string EPILOG = \"\";\n\nclass lars_variables;\nclass lars_result;\narma::vec lars(lars_variables &variable_set, lars_result &result, size_t max_vars = 15, bool lasso = true, double threshold = 1.0);\n\n/**\n * This class is responsible for keeping track which variables\n * are currently in the active and inactive sets, excluding those\n * that are currently in the ignored set.\n */\nclass active_set\n{\npublic:\n    /**\n     * Constructor.\n     *\n     * @param size Total number of variables ([0...size-1]).\n     */\n    active_set(size_t size)\n    {\n        m_active = std::set<unsigned int>( );\n        m_ignored = std::set<unsigned int>( );\n        m_size = size;\n        m_last_added = -1;\n    }\n\n    /**\n     * Add a variable to the active set. It is assumed that this\n     * variable is not ignored.\n     *\n     * @param x Index of variable to add.\n     */\n    void add(unsigned int x)\n    {\n        m_last_added = x;\n        m_active.insert( x );\n    }\n\n    /**\n     * Ignores a parameters, ignored parameters are neither\n     * active or inactive.\n     *\n     * @param x Index of variable to ignore.\n     */\n    void ignore(unsigned int x)\n    {\n        m_active.erase( x );\n        m_ignored.insert( x );\n    }\n\n    /**\n     * Move a variable from active to inactive.\n     *\n     * @param Index of the variable to move.\n     */\n    void drop(unsigned int x)\n    {\n        m_active.erase( x );\n    }\n\n    /**\n     * Returns a vector of indicies of the currently active variables\n     * suitable for the arma package.\n     *\n     * @return A vector of indicies of active variables.\n     */\n    arma::uvec get_active() const\n    {\n        arma::uvec active = arma::zeros<arma::uvec>( m_active.size( ) );\n        std::set<unsigned int>::const_iterator it;\n        unsigned int index = 0;\n        for(it = m_active.begin( ); it != m_active.end( ); ++it)\n        {\n            active[ index ] = *it;\n            index++;      \n        }\n\n        return active;\n    }\n\n    /**\n     * Returns a vector of indicies of the currently inactive variables\n     * suitable for the arma package.\n     *\n     * @return A vector of indicies of inactive variables.\n     */\n    arma::uvec get_inactive() const\n    {\n        arma::uvec inactive = arma::zeros<arma::uvec>( m_size - m_active.size( ) - m_ignored.size( ) );\n        unsigned int index = 0;\n        for(int i = 0; i < m_size; i++)\n        {\n            if( m_active.count( i ) > 0 || m_ignored.count( i ) > 0 )\n            {\n                continue;\n            }\n\n            inactive[ index ] = i;\n            index++;\n        }\n\n        return inactive;\n    }\n\n    /**\n     * Returns the last added variable to the active set.\n     *\n     * @return The last added variable to the active set.\n     */\n    unsigned int get_last_added() const\n    {\n        return m_last_added;\n    }\n\n    /**\n     * Returns the number of active variables.\n     *\n     * @return the number of active variables.\n \n*/\n    size_t size() const\n    {\n        return m_active.size( );\n    }\n\nprivate:\n    /**\n     * Total number of variables.\n     */\n    size_t m_size;\n\n    /**\n     * Set of active variables.\n     */\n    std::set<unsigned int> m_active;\n\n    /**\n     * Set of ignored variables.\n     */\n    std::set<unsigned int> m_ignored;\n\n    /**\n     * Last added index.\n     */\n    unsigned int m_last_added;\n};\n\nstruct knot_info\n{\n    std::string variable;\n    unsigned int variable_index;\n    double lambda;\n    arma::uvec active;\n    arma::mat X_active;\n    arma::vec beta_active;\n    arma::mat X_h0;\n};\n\nstruct lars_knot\n{\n    knot_info info;\n    bool remove;\n    double T;\n    double pvalue;\n    double explained_var;\n    bool valid_p;\n};\n\nclass lars_result\n{\npublic:\n    lars_result(const arma::vec &phenotype, bool calculate_p) :\n        m_phenotype( phenotype ),\n        m_calculate_p( calculate_p )\n    {\n        m_pheno_var = arma::accu( pow( phenotype, 2 ) ) / (phenotype.n_elem - 1);\n    }\n\n    void init(double lambda)\n    {\n        lars_knot start;\n        start.info.variable = \"NULL\";\n        start.info.variable_index = -1;\n        start.info.lambda = lambda;\n        start.remove = false;\n        start.T = 0.0;\n        start.pvalue = 1.0;\n        start.explained_var = 0.0;\n        start.valid_p = false;\n\n        m_knots.push_back( start );\n    }\n\n    void add_knot(bool remove, knot_info &info, double model_var)\n    {\n        lars_knot new_knot;\n        new_knot.info = info;\n        new_knot.remove = remove;\n        new_knot.explained_var = 1.0 - model_var / m_pheno_var;\n\n        if( remove || !m_calculate_p )\n        {\n            new_knot.T = 0;\n            new_knot.pvalue = 1.0;\n\n            m_knots.push_back( new_knot );\n\n            return;\n        }\n \n        /* Calculate p for new beta and add last component of the path */\n        double cur_cor = dot( info.X_active * info.beta_active, m_phenotype );\n\n        /* Compute h0 */\n        double prev_cor = 0;\n        if( info.X_active.n_cols > 1 )\n        {\n            null_lars null( info.X_h0, m_phenotype );\n            lars_result null_result( m_phenotype, false );\n            lars( null, null_result, info.X_h0.n_cols, true );\n\n            std::vector<lars_knot> null_knot = null_result.get_knots( );\n            \n            unsigned int knot_index = -1;\n            for(int i = 1; i < null_knot.size( ); i++)\n            {\n                if( info.lambda < null_knot[ i - 1 ].info.lambda && info.lambda > null_knot[ i ].info.lambda )\n                {\n                    knot_index = i;\n                }\n            }\n\n            lars_knot &prev = null_knot[ knot_index - 1 ];\n            lars_knot &next = null_knot[ knot_index ];\n\n            arma::vec beta_prev = arma::zeros<arma::vec>( info.X_h0.n_cols );\n            align_beta( prev.info.beta_active, prev.info.active, &beta_prev );\n\n            arma::vec beta_next = arma::zeros<arma::vec>( info.X_h0.n_cols );\n            align_beta( next.info.beta_active, next.info.active, &beta_next );\n\n            double lambda_prev = prev.info.lambda;\n            double lambda_next = next.info.lambda;\n\n            arma::vec k = (beta_next - beta_prev)/(lambda_next - lambda_prev);\n            arma::vec beta_h0 = beta_prev + (info.lambda - lambda_prev) * k;\n\n            prev_cor = dot( info.X_h0 * beta_h0, m_phenotype );\n        }\n\n        double T = (cur_cor - prev_cor ) / model_var;\n        double p = 1.0;\n        if( T > 0.0 )\n        {\n            p = 1 - exp_cdf( T, 1.0 );\n            new_knot.valid_p = true;\n        }\n        else\n        {\n            new_knot.valid_p = false;\n        }\n\n        new_knot.T = T;\n        new_knot.pvalue = p;\n            \n        m_knots.push_back( new_knot );\n    }\n\n    std::vector<lars_knot> get_knots()\n    {\n        return m_knots;\n    }\n\n    void align_beta(arma::vec &beta, arma::uvec &active, arma::vec *aligned_beta)\n    {\n        for(int i = 0; i < active.n_elem; i++)\n        {\n            (*aligned_beta)[ active[ i ] ] = beta[ i ];\n        }\n    }\n\n    void write_result(std::ostream &out, bool only_pvalues)\n    {\n        if( only_pvalues )\n        {\n            out << \"step\\tvariable\\taction\\tbeta\\tT\\tp\\tlambda\\tbeta_sum\\texplained_var\\n\";\n            for(int i = 1; i < m_knots.size( ); i++)\n            {\n                lars_knot &knot = m_knots[ i ];\n                std::string action = \"add\";\n                arma::vec this_beta = knot.info.beta_active.elem( find( knot.info.active == knot.info.variable_index ) );\n                if( knot.remove )\n                {\n                    action = \"remove\";\n                    this_beta = arma::zeros<arma::vec>( 1 );\n                }\n\n                out << i << \"\\t\" <<\n                    knot.info.variable << \"\\t\" <<\n                    action << \"\\t\" <<\n                    this_beta[ 0 ] << \"\\t\" <<\n                    knot.T << \"\\t\" <<\n                    knot.pvalue << \"\\t\" <<\n                    knot.info.lambda <<  \"\\t\" <<\n                    arma::sum( arma::abs( knot.info.beta_active ) ) <<  \"\\t\" <<\n                    knot.explained_var << \"\\n\";\n            }\n        }\n        else\n        {\n            int var = 0;\n            std::map<unsigned int, unsigned int> new_pos;\n            std::vector<std::string> name;\n            for(int i = 1; i < m_knots.size( ); i++)\n            {\n                lars_knot &knot = m_knots[ i ];\n                if( knot.remove )\n                {\n                    continue;\n                }\n\n                if( new_pos.count( knot.info.variable_index ) <= 0 )\n                {\n                    new_pos[ knot.info.variable_index ] = var;\n                    name.push_back( knot.info.variable );\n                    var++;\n                }\n            }\n\n            out << \"step\\tvariable\\tT\\tp\\tbeta_sum\\texplained_var\\tlambda\";\n            for(int i = 0; i < name.size( ); i++)\n            {\n                out <<  \"\\t\" << name[ i ];\n            }\n            out << \"\\n\";\n\n            for(int i = 1; i < m_knots.size( ); i++)\n            {\n                lars_knot &knot = m_knots[ i ];\n                arma::vec beta = arma::zeros<arma::vec>( new_pos.size( ) );\n\n                for(int j = 0; j < knot.info.active.n_elem; j++)\n                {\n                    beta[ new_pos[ knot.info.active[ j ] ] ] = knot.info.beta_active[ j ];\n                }\n                \n                out << i << \"\\t\" << knot.info.variable << \"\\t\" << knot.T << \"\\t\" << knot.pvalue << \"\\t\" << arma::sum( arma::abs( knot.info.beta_active ) ) << \"\\t\" << knot.explained_var << \"\\t\" << knot.info.lambda << \"\\t\";\n                for(int j = 0; j < beta.n_elem; j++)\n                {\n                    out << \"\\t\" << beta[ j ];\n                }\n                out << \"\\n\";\n            }\n\n        }\n    }\n\nprivate:\n    arma::vec m_phenotype;\n    bool m_calculate_p;\n    double m_pheno_var;\n    std::vector<lars_knot> m_knots;\n};\n\n\narma::vec\nnice_division(arma::vec &a, arma::vec &b)\n{\n    b.elem( find( b < DBL_MIN ) ).fill( DBL_MIN );\n    arma::vec x = a / b;\n    x.elem( find( x <= 0 ) ).fill( DBL_MAX );\n    \n    return x;\n}\n\n/**\n * Solves the lasso problem for a given lambda. Used for computing the\n * null model during significance testing. The algorithm is currently\n * a pathwise coordinate descent.\n *\n * @param X Covariates.\n * @param y Outcome.\n * @param lambda Shrinkage factor.\n * @param start Starting values for beta.\n * @max_num_iter Maximum number of iterations before giving up.\n */\narma::vec optimize_lars_gd(const arma::mat &X, const arma::mat &y, double lambda, const arma::vec &start, size_t max_num_iter = 50)\n{\n    arma::vec beta = start;\n    arma::vec r = y - X * beta;\n    double prev_rss = 0;\n    double cur_rss = sum( r % r );\n    int num_iter = 0;\n\n    while( std::abs( prev_rss - cur_rss ) / prev_rss > 1e-20 && num_iter++ < max_num_iter )\n    {\n        prev_rss = cur_rss;\n        for(int j = 0; j < X.n_cols; j++)\n        {\n            double beta_star = arma::dot( X.col( j ), r ) + beta[ j ];\n            double update = std::abs( beta_star ) - lambda;\n            update = (update > 0) ? update : 0;\n\n            double new_beta = (beta_star > 0) ? update : -update;\n            double beta_increase = new_beta - beta[ j ];\n\n            beta[ j ] = new_beta;\n\n            if( std::abs( beta_increase ) > 0 )\n            {\n                r = r - X.col( j ) * beta_increase;\n            }\n        }\n        cur_rss = sum( r % r );\n    }\n\n    return beta;\n}\n\n/**\n * Finds the maximum correlation and returns its index.\n *\n * @param v A vector of correlations.\n * @param inactive A subset of indicies to consider.\n * @param max_index The index of the maximum value in v will be stored here.\n *\n * @reutrn The maximum value of v restricted to the indicies in inactive.\n */\ndouble\nfind_max(const arma::vec &v, const arma::uvec &inactive, unsigned int *max_index)\n{\n    double max_value = 0;\n    *max_index = v.n_elem;\n    for(int i = 0; i < inactive.n_elem; i++)\n    {\n        unsigned int cur_index = inactive[ i ];\n        double cur_value = v[ cur_index ];\n\n        // Notice the order of these two statements\n        *max_index = ( cur_value > max_value ) ? cur_index : *max_index;\n        max_value = ( cur_value > max_value ) ? cur_value : max_value;\n    }\n\n    return max_value;\n}\n\narma::vec\nlars(lars_variables &variable_set, lars_result &result, size_t max_vars, bool lasso, double threshold)\n{\n    arma::vec phenotype = variable_set.get_centered_phenotype( );\n    size_t n = variable_set.get_num_samples( );\n    size_t m = variable_set.get_num_variables( );\n\n    arma::vec mu = arma::zeros<arma::vec>( n );\n    arma::vec beta = arma::zeros<arma::vec>( m );\n    arma::vec c = arma::zeros<arma::vec>( m );\n\n    active_set active( m );\n    arma::uvec inactive;\n    arma::uvec drop;\n    arma::uvec prev_active;\n    double eps = 1e-10;\n\n    /* It is the first lambda that needs to be added not the last... */\n    variable_set.calculate_cor( phenotype - mu, c );\n    result.init( arma::max( abs( c ) ) );\n\n    int i = 0;\n    while( active.size( ) < std::min( max_vars, m ) )\n    {\n        variable_set.calculate_cor( phenotype - mu, c );\n        arma::vec cabs = abs( c );\n        unsigned int max_index;\n        double C = find_max( cabs, active.get_inactive( ), &max_index );\n\n        if( C < eps )\n        {\n            break;\n        }\n       \n        /* If previous step was a drop we should not add\n         * more variables in this step only increase beta. */\n        bool prev_was_drop = drop.n_elem > 0;\n        if( !prev_was_drop )\n        {\n            prev_active = active.get_active( ); \n            active.add( max_index );\n        }\n        inactive = active.get_inactive( );\n\n        /* Create the active matrix */\n        arma::mat X_active = variable_set.get_active( active.get_active( ) );\n\n        /* Equation 2.4 */\n        arma::vec s = sign( c.elem( active.get_active( ) ) );\n\n        /* Equation 2.5 */\n        arma::mat G = X_active.t( ) * X_active;\n        arma::mat Ginv;\n        if( !pinv( Ginv, G ) )\n        {\n            active.ignore( max_index );\n            continue;\n        }\n        double A = 1.0 / sqrt( arma::accu( s.t( ) * Ginv * s ) );\n\n        /* Equation 2.6 */\n        arma::vec w = A * Ginv * s;\n        arma::vec u = X_active * w;\n\n        double gamma = C / A;\n        if( active.size( ) < m )\n        { \n            /* Equation 2.11 */\n            arma::vec a = variable_set.eig_prod( u );\n\n            /* Equation 2.13 */\n            arma::vec cc = c.elem( inactive );\n            arma::vec ac = a.elem( inactive );\n            \n            arma::vec a1 = C - cc;\n            arma::vec b1 = A - ac;\n\n            arma::vec gn = nice_division( a1, b1 );\n\n            arma::vec a2 = C + cc;\n            arma::vec b2 = A + ac;\n            arma::vec gp = nice_division( a2, b2 );\n\n            gamma = std::min( gn.min( ), gp.min( ) );\n        }\n\n        if( lasso )\n        {\n            drop.clear( );\n            /* Equation 3.4 */\n            arma::vec gammaj = -beta.elem( active.get_active( ) ) / w;\n\n            /* Equation 3.5 */\n            arma::uvec valid_elems = arma::find( gammaj > eps );\n            if( valid_elems.n_elem > 0 )\n            {\n                double gammatilde = std::min( arma::min( gammaj.elem( valid_elems ) ), gamma );\n\n                if( gammatilde < gamma )\n                {\n                    gamma = gammatilde;\n                    drop = active.get_active( ).elem( find( gammaj == gammatilde ) );\n                    assert( drop.n_elem == 1 );\n                }\n            }\n        }\n\n        beta.elem( active.get_active( ) ) = beta.elem( active.get_active( ) ) + w * gamma;\n        mu = mu + gamma * u;\n\n        bool cur_is_drop = drop.n_elem > 0;\n        knot_info info;\n        if( cur_is_drop )\n        {\n            /* This knot is a deletion, so zero out beta and remove the deleted\n             * variable from the active set, and in the next step we need to\n             * increase beta to get to the knot of the newly added variable. */\n            beta.elem( drop ).fill( 0.0 );\n            active.drop( drop[ 0 ] );\n        }\n        \n        /**\n         * If addition we use the max index, if deletion we use the\n         * drop index, if previous was a drop we use the last added\n         * variable because it is that one we are moving forward with.\n         */\n        if( !cur_is_drop && !prev_was_drop )\n        {\n            info.variable_index = max_index;\n        }\n        else if( cur_is_drop )\n        {\n            info.variable_index = drop[ 0 ];\n        }\n        else\n        {\n            info.variable_index = active.get_last_added( );\n        }\n        info.variable = variable_set.get_name( info.variable_index );\n\n        info.active = active.get_active( );\n        info.beta_active = beta.elem( info.active );\n        info.X_active = !cur_is_drop ? X_active : variable_set.get_active( info.active );\n\n        double model_var = sum( pow( phenotype - mu, 2 ) ) / (n - 1 - active.size( ) );\n        arma::vec r = phenotype - mu;\n        s = sign( c.elem( active.get_active( ) ) );\n        info.lambda = arma::max( s % ( info.X_active.t( ) * r ) );\n\n        if( prev_active.n_elem > 0 )\n        {\n            info.X_h0 = variable_set.get_active( prev_active );\n        }\n\n        result.add_knot( cur_is_drop, info, model_var );\n\n        i++;\n    }\n    \n    return beta;\n}\n\nint\nmain(int argc, char *argv[])\n{\n    OptionParser parser = OptionParser( ).usage( USAGE )\n                                         .version( VERSION )\n                                         .description( DESCRIPTION )\n                                         .epilog( EPILOG ); \n \n    parser.add_option( \"-p\", \"--pheno\" ).help( \"Read phenotypes from this file instead of a plink file.\" );\n    parser.add_option( \"-e\", \"--mpheno\" ).help( \"Name of the phenotype that you want to read (if there are more than one in the phenotype file).\" );\n    parser.add_option( \"-c\", \"--cov\" ).action( \"store\" ).type( \"string\" ).metavar( \"filename\" ).help( \"Performs the analysis by including the covariates in this file.\" );\n    parser.add_option( \"-o\", \"--out\" ).help( \"The output file that will contain the results (binary).\" );\n    parser.add_option( \"-m\", \"--max-variables\" ).help( \"Maximum number of variables in the model\" ).set_default( 10 );\n    parser.add_option( \"-t\", \"--threshold\" ).help( \"Stop after a variable has a p-value less than this threshold.\" ).set_default( 1.0 );\n    parser.add_option( \"-a\", \"--maf\" ).help( \"Filter variants with maf (it is important to set this to avoid interactions with monotonic snps)\" ).set_default( 0.05 );\n    parser.add_option( \"--only-pvalues\" ).help( \"Only output the beta that enters in each step along with its p-value.\" ).action( \"store_true\" );\n    parser.add_option( \"--only-main\" ).help( \"Only output the main effects.\" ).action( \"store_true\" );\n\n    Values options = parser.parse_args( argc, argv );\n    if( parser.args( ).size( ) != 1 )\n    {\n        parser.print_help( );\n        exit( 1 );\n    }\n\n    std::ios_base::sync_with_stdio( false );\n    \n    /* Read all genotypes */\n    plink_file_ptr genotype_file = open_plink_file( parser.args( )[ 0 ] );\n    genotype_matrix_ptr genotypes = create_filtered_genotype_matrix( genotype_file, (float) options.get( \"maf\" ) );\n    std::vector<std::string> order = genotype_file->get_sample_iids( );\n\n    /* Make error streams separate from stdout */\n    arma::set_stream_err1( std::cerr );\n    arma::set_stream_err2( std::cerr );\n\n    /* Parse phenotypes */\n    arma::uvec cov_missing = arma::zeros<arma::uvec>( genotype_file->get_samples( ).size( ) );\n    arma::uvec pheno_missing = arma::zeros<arma::uvec>( genotype_file->get_samples( ).size( ) );\n    arma::vec phenotype;\n    arma::mat cov;\n    std::vector<std::string> cov_names;\n    if( options.is_set( \"pheno\" ) )\n    {\n        std::ifstream phenotype_file( options[ \"pheno\" ].c_str( ) );\n        phenotype = parse_phenotypes( phenotype_file, pheno_missing, order, options[ \"mpheno\" ] );\n    }\n    else\n    {\n        phenotype = create_phenotype_vector( genotype_file->get_samples( ), pheno_missing );\n    }\n    if( options.is_set( \"cov\" ) )\n    {\n        std::ifstream covariate_file( options[ \"cov\" ].c_str( ) );\n        cov = parse_covariate_matrix( covariate_file, cov_missing, order, &cov_names );\n    }\n\n    /* Open output stream */\n    std::ofstream output_file;\n    if( options.is_set( \"out\" ) )\n    {\n        output_file.open( options[ \"out\" ].c_str( ) );\n    }\n    std::ostream &out = options.is_set( \"out\" ) ? output_file : std::cout;\n\n    bool only_pvalues = options.is_set( \"only_pvalues\" );\n    bool only_main = options.is_set( \"only_main\" );\n\n    gene_environment variable_set( genotypes, cov, phenotype, cov_names, only_main );\n    variable_set.impute_missing( );\n    lars_result result( variable_set.get_centered_phenotype( ), true );\n    lars( variable_set, result, (int) options.get( \"max_variables\" ), (double) options.get( \"threshold\" ) );\n    result.write_result( out, only_pvalues );\n\n    return 0;\n}\n", "meta": {"hexsha": "34ecee265172a547e202bf07bc9bbf7bd1c791fb", "size": 21582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/besiq_lars.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "src/besiq_lars.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "src/besiq_lars.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 30.5261669024, "max_line_length": 221, "alphanum_fraction": 0.539616347, "num_tokens": 5526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.023330767407859568, "lm_q1q2_score": 0.011665383703929784}}
{"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/property_map.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/concept/assert.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             typename ArticulationVector, typename IndexMap,\n             typename DFSVisitor>\n    struct biconnected_components_visitor : public dfs_visitor<>\n    {\n      biconnected_components_visitor\n        (ComponentMap comp, std::size_t& c, \n         std::size_t& children_of_root, DiscoverTimeMap dtm,\n         std::size_t& dfs_time, LowPointMap lowpt, PredecessorMap pred,\n         OutputIterator out, Stack& S,\n         ArticulationVector& is_articulation_point, IndexMap index_map,\n         DFSVisitor vis)\n          : comp(comp), c(c), children_of_root(children_of_root),\n            dtm(dtm), dfs_time(dfs_time), lowpt(lowpt),\n            pred(pred), out(out), S(S),\n            is_articulation_point(is_articulation_point),\n            index_map(index_map), vis(vis) { }\n\n      template <typename Vertex, typename Graph>\n      void initialize_vertex(const Vertex& u, Graph& g)\n      {\n        put(pred, u, u);\n        vis.initialize_vertex(u, g);\n      }\n\n      template <typename Vertex, typename Graph>\n      void start_vertex(const Vertex& u, Graph& g)\n      {\n        children_of_root = 0;\n        vis.start_vertex(u, g);\n      }\n\n      template <typename Vertex, typename Graph>\n      void discover_vertex(const Vertex& u, Graph& g)\n      {\n        put(dtm, u, ++dfs_time);\n        put(lowpt, u, get(dtm, u));\n        vis.discover_vertex(u, g);\n      }\n\n      template <typename Edge, typename Graph>\n      void examine_edge(const Edge& e, Graph& g)\n      {\n        vis.examine_edge(e, g);\n      }\n\n      template <typename Edge, typename Graph>\n      void tree_edge(const Edge& e, Graph& g)\n      {\n        typename boost::graph_traits<Graph>::vertex_descriptor src = source(e, g);\n        typename boost::graph_traits<Graph>::vertex_descriptor tgt = target(e, g);\n\n        S.push(e);\n        put(pred, tgt, src);\n        if ( get(pred, src) == src ) {\n          ++children_of_root;\n        }\n        vis.tree_edge(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        typename boost::graph_traits<Graph>::vertex_descriptor src = source(e, g);\n        typename boost::graph_traits<Graph>::vertex_descriptor tgt = target(e, g);\n        if ( tgt != get(pred, src) ) {\n          S.push(e);\n          put(lowpt, src,\n              min BOOST_PREVENT_MACRO_SUBSTITUTION(get(lowpt, src),\n                                                   get(dtm, tgt)));\n        }\n        vis.back_edge(e, g);\n      }\n\n      template <typename Edge, typename Graph>\n      void forward_or_cross_edge(const Edge& e, Graph& g)\n      {\n        vis.forward_or_cross_edge(e, g);\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        if (parent == u) { // Root of tree is special\n          is_articulation_point[get(index_map, u)] = (children_of_root > 1);\n        } else {\n          put(lowpt, parent,\n              min BOOST_PREVENT_MACRO_SUBSTITUTION(get(lowpt, parent),\n                                                 get(lowpt, u)));\n          if ( get(lowpt, u) >= get(dtm, parent) ) {\n            is_articulation_point[get(index_map, parent)] = true;\n            while ( get(dtm, source(S.top(), g)) >= get(dtm, u) ) {\n              put(comp, S.top(), c);\n              S.pop();\n            }\n            assert (source(S.top(), g) == parent);\n            assert (target(S.top(), g) == u);\n            put(comp, S.top(), c);\n            S.pop();\n            ++c;\n          }\n        }\n        if ( is_articulation_point[get(index_map, u)] ) {\n          *out++ = u;\n        }\n        vis.finish_vertex(u, g);\n      }\n\n      ComponentMap comp;\n      std::size_t& c;\n      std::size_t& children_of_root;\n      DiscoverTimeMap dtm;\n      std::size_t& dfs_time;\n      LowPointMap lowpt;\n      PredecessorMap pred;\n      OutputIterator out;\n      Stack& S;\n      ArticulationVector& is_articulation_point;\n      IndexMap index_map;\n      DFSVisitor vis;\n    };\n\n  template<typename Graph, typename ComponentMap, typename OutputIterator,\n        typename VertexIndexMap, typename DiscoverTimeMap, typename LowPointMap,\n        typename PredecessorMap, typename DFSVisitor>\n  std::pair<std::size_t, OutputIterator>\n    biconnected_components_impl(const Graph & g, ComponentMap comp,\n        OutputIterator out, VertexIndexMap index_map, DiscoverTimeMap dtm,\n        LowPointMap lowpt, PredecessorMap pred, DFSVisitor dfs_vis)\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph> ));\n    BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept<Graph> ));\n    BOOST_CONCEPT_ASSERT(( WritablePropertyMapConcept<ComponentMap, edge_t> ));\n    BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<DiscoverTimeMap,\n                                                  vertex_t> ));\n    BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<LowPointMap, vertex_t > ));\n    BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<PredecessorMap,\n                                                  vertex_t> ));\n\n    std::size_t num_components = 0;\n    std::size_t children_of_root;\n    std::size_t dfs_time = 0;\n    std::stack<edge_t> S;\n\tstd::vector<char> is_articulation_point(num_vertices(g));\n\n    biconnected_components_visitor<ComponentMap, DiscoverTimeMap,\n        LowPointMap, PredecessorMap, OutputIterator, std::stack<edge_t>, \n        std::vector<char>, VertexIndexMap, DFSVisitor>\n    vis(comp, num_components, children_of_root, dtm, dfs_time,\n        lowpt, pred, out, S, is_articulation_point, index_map, dfs_vis);\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 PredecessorMap>\n    struct bicomp_dispatch3\n    {\n  template<typename Graph, typename ComponentMap, typename OutputIterator,\n                typename VertexIndexMap, typename DiscoverTimeMap, \n                typename LowPointMap, class P, class T, class R>\n      static std::pair<std::size_t, OutputIterator> apply (const Graph & g, \n          ComponentMap comp, OutputIterator out, VertexIndexMap index_map, \n          DiscoverTimeMap dtm, LowPointMap lowpt, \n          const bgl_named_params<P, T, R>& params, PredecessorMap pred)\n      {\n        return biconnected_components_impl\n                (g, comp, out, index_map, dtm, lowpt, pred,\n                 choose_param(get_param(params, graph_visitor),\n                    make_dfs_visitor(null_visitor())));\n      }\n    };\n    \n    template <>\n    struct bicomp_dispatch3<error_property_not_found>\n    {\n      template<typename Graph, typename ComponentMap, typename OutputIterator,\n                typename VertexIndexMap, typename DiscoverTimeMap, \n                typename LowPointMap, class P, class T, class R>\n      static std::pair<std::size_t, OutputIterator> apply (const Graph & g, \n          ComponentMap comp, OutputIterator out, VertexIndexMap index_map, \n          DiscoverTimeMap dtm, LowPointMap lowpt, \n          const bgl_named_params<P, T, R>& params, \n          error_property_not_found)\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\n        return biconnected_components_impl\n                (g, comp, out, index_map, dtm, lowpt, \n              make_iterator_property_map(pred.begin(), index_map, vert),\n                 choose_param(get_param(params, graph_visitor),\n                    make_dfs_visitor(null_visitor())));\n  }\n    };\n\n    template <typename LowPointMap>\n    struct bicomp_dispatch2\n    {\n  template<typename Graph, typename ComponentMap, typename OutputIterator,\n                typename VertexIndexMap, typename DiscoverTimeMap, \n                typename P, typename T, typename R>\n      static std::pair<std::size_t, OutputIterator> apply (const Graph& g, \n          ComponentMap comp, OutputIterator out, VertexIndexMap index_map, \n          DiscoverTimeMap dtm, const bgl_named_params<P, T, R>& params, \n          LowPointMap lowpt)\n      {\n        typedef typename property_value< bgl_named_params<P,T,R>,\n            vertex_predecessor_t>::type dispatch_type;\n\n        return bicomp_dispatch3<dispatch_type>::apply\n            (g, comp, out, index_map, dtm, lowpt, params, \n             get_param(params, vertex_predecessor));\n      }\n    };\n\n\n    template <>\n    struct bicomp_dispatch2<error_property_not_found>\n    {\n      template<typename Graph, typename ComponentMap, typename OutputIterator,\n                typename VertexIndexMap, typename DiscoverTimeMap, \n                typename P, typename T, typename R>\n      static std::pair<std::size_t, OutputIterator> apply (const Graph& g, \n          ComponentMap comp, OutputIterator out, VertexIndexMap index_map, \n          DiscoverTimeMap dtm, const bgl_named_params<P, T, R>& params, \n          error_property_not_found)\n  {\n    typedef typename graph_traits<Graph>::vertices_size_type\n      vertices_size_type;\n    std::vector<vertices_size_type> lowpt(num_vertices(g));\n        vertices_size_type vst(0);\n\n        typedef typename property_value< bgl_named_params<P,T,R>,\n            vertex_predecessor_t>::type dispatch_type;\n  \n        return bicomp_dispatch3<dispatch_type>::apply\n            (g, comp, out, index_map, dtm,\n             make_iterator_property_map(lowpt.begin(), index_map, vst),\n             params, get_param(params, vertex_predecessor));\n      }\n    };\n\n    template <typename DiscoverTimeMap>\n    struct bicomp_dispatch1\n    {\n      template<typename Graph, typename ComponentMap, typename OutputIterator,\n                typename VertexIndexMap, class P, class T, class R>\n      static std::pair<std::size_t, OutputIterator> apply(const Graph& g, \n          ComponentMap comp, OutputIterator out, VertexIndexMap index_map, \n          const bgl_named_params<P, T, R>& params, DiscoverTimeMap dtm)\n      {\n        typedef typename property_value< bgl_named_params<P,T,R>,\n            vertex_lowpoint_t>::type dispatch_type;\n\n        return bicomp_dispatch2<dispatch_type>::apply\n            (g, comp, out, index_map, dtm, params, \n             get_param(params, vertex_lowpoint));\n      }\n    };\n\n    template <>\n    struct bicomp_dispatch1<error_property_not_found>\n    {\n      template<typename Graph, typename ComponentMap, typename OutputIterator,\n                typename VertexIndexMap, class P, class T, class R>\n      static std::pair<std::size_t, OutputIterator> apply(const Graph& g, \n          ComponentMap comp, OutputIterator out, VertexIndexMap index_map, \n          const bgl_named_params<P, T, R>& params, error_property_not_found)\n      {\n        typedef typename graph_traits<Graph>::vertices_size_type\n            vertices_size_type;\n        std::vector<vertices_size_type> discover_time(num_vertices(g));\n    vertices_size_type vst(0);\n\n        typedef typename property_value< bgl_named_params<P,T,R>,\n            vertex_lowpoint_t>::type dispatch_type;\n\n        return bicomp_dispatch2<dispatch_type>::apply\n            (g, comp, out, index_map, \n              make_iterator_property_map(discover_time.begin(), index_map, vst),\n             params, get_param(params, vertex_lowpoint));\n      }\n    };\n\n  }\n\n  template<typename Graph, typename ComponentMap, typename OutputIterator,\n      typename DiscoverTimeMap, typename LowPointMap>\n  std::pair<std::size_t, OutputIterator>\n  biconnected_components(const Graph& g, ComponentMap comp, \n      OutputIterator out, DiscoverTimeMap dtm, LowPointMap lowpt)\n  {\n    typedef detail::error_property_not_found dispatch_type;\n\n    return detail::bicomp_dispatch3<dispatch_type>::apply\n            (g, comp, out, \n             get(vertex_index, g), \n             dtm, lowpt, \n             bgl_named_params<int, buffer_param_t>(0), \n             detail::error_property_not_found());\n  }\n\n  template <typename Graph, typename ComponentMap, typename OutputIterator,\n      typename P, typename T, typename R>\n  std::pair<std::size_t, OutputIterator>\n  biconnected_components(const Graph& g, ComponentMap comp, OutputIterator out, \n      const bgl_named_params<P, T, R>& params)\n  {\n    typedef typename property_value< bgl_named_params<P,T,R>,\n        vertex_discover_time_t>::type dispatch_type;\n\n    return detail::bicomp_dispatch1<dispatch_type>::apply(g, comp, out, \n        choose_const_pmap(get_param(params, vertex_index), g, vertex_index), \n        params, get_param(params, vertex_discover_time));\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,  \n        bgl_named_params<int, buffer_param_t>(0));\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      typename P, typename T, typename R>\n  std::size_t\n  biconnected_components(const Graph& g, ComponentMap comp, \n      const bgl_named_params<P, T, R>& params)\n  {\n    return biconnected_components(g, comp,\n        graph_detail::dummy_output_iterator(), params).first;\n  }\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, \n      typename P, typename T, typename R>\n  OutputIterator\n  articulation_points(const Graph& g, OutputIterator out, \n      const bgl_named_params<P, T, R>& params)\n  {\n    return biconnected_components(g, dummy_property_map(), out, \n        params).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        bgl_named_params<int, buffer_param_t>(0)).second;\n  }\n\n}                               // namespace boost\n\n#endif  /* BOOST_GRAPH_BICONNECTED_COMPONENTS_HPP */\n", "meta": {"hexsha": "0fdbad0d291e147079778ab4d3d700f35c693c67", "size": 15889, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Qt-GL-Simple-Scene-master/include/boost_1_5/include/boost/graph/biconnected_components.hpp", "max_stars_repo_name": "nacsa/Retopology", "max_stars_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T23:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T17:41:27.000Z", "max_issues_repo_path": "Qt-GL-Simple-Scene-master/include/boost_1_5/include/boost/graph/biconnected_components.hpp", "max_issues_repo_name": "nacsa/Retopology", "max_issues_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Qt-GL-Simple-Scene-master/include/boost_1_5/include/boost/graph/biconnected_components.hpp", "max_forks_repo_name": "nacsa/Retopology", "max_forks_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T01:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:02:49.000Z", "avg_line_length": 37.6516587678, "max_line_length": 82, "alphanum_fraction": 0.6543520675, "num_tokens": 3657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.03308597958047281, "lm_q1q2_score": 0.011652940969042612}}
{"text": "#include \"context.h\"\n#include <stdio.h>\n#include <string.h>\n#include <vector>\n#include \"include/secp256k1.h\"\n#include \"include/secp256k1_ecdh.h\"\n#include \"include/secp256k1_schnorrsig.h\"\n#include \"include/secp256k1_generator.h\"\n#include \"include/secp256k1_rangeproof.h\"\n#include \"libsecp256k1-config.h\"\n\n#include \"log/log.h\"\n\n#include <boost/thread.hpp>\n\n#include \"hash_impl.h\"\n#include \"num_impl.h\"\n#include \"field_impl.h\"\n#include \"group_impl.h\"\n#include \"scalar_impl.h\"\n\nusing namespace qbit;\n\n#include <signal.h>\n\nContext::Context() {\n}\n\nContext::~Context() {\n\tif (context_) {\n\t\tsecp256k1_context_destroy(context_);\n\t\tsecp256k1_context_destroy(none_);\n\t}\n\n\tif (scratch_) {\n\t\tsecp256k1_scratch_space_destroy(scratch_);\n\t}\n}\n\nsecp256k1_context* Context::noneContext() {\n\tinitialize();\n\treturn none_;\n}\n\nsecp256k1_context* Context::signatureContext() {\n\tinitialize();\n\treturn context_;\n}\n\nContextPtr Context::instance() { \n\t//\n\tstatic boost::thread_specific_ptr<ContextPtr> tContext;\n\tif (!tContext.get()) {\n\t\ttContext.reset(new ContextPtr(new Context()));\n\t\treturn ContextPtr(*tContext.get()); \n\t}\n\n\treturn ContextPtr(*tContext.get());\n} \n\nsecp256k1_scratch_space* Context::signatureScratch() {\n\tif (!scratch_) scratch_ = secp256k1_scratch_space_create(context_, 1024 * 1024 * 1024); // magic digits\n\treturn scratch_; \n}\n\nvoid Context::initialize()\n{\n\tif (!context_) {\n\t\tnone_ = secp256k1_context_create(SECP256K1_CONTEXT_NONE);\n\t\tcontext_ = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN);\n\t}\n}\n\nbool Context::createCommitment(qbit::vector<unsigned char>& out, const uint256& blind, amount_t amount) {\n\tsecp256k1_pedersen_commitment lCommit;\n\tunsigned char lSerialized[33];\n\tif (secp256k1_pedersen_commit(signatureContext(), &lCommit, blind.begin(), amount, secp256k1_generator_h)) {\n\t\tsecp256k1_pedersen_commitment_serialize(signatureContext(), lSerialized, &lCommit);\n\t\tout.insert(out.end(), lSerialized, lSerialized + sizeof(lSerialized));\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool Context::createRangeProof(qbit::vector<unsigned char>& out, const qbit::vector<unsigned char>& commit, const uint256& blind, const uint256& nonce, amount_t amount) {\n\tunsigned char lProof[5134 + 1];\n\tsize_t lLen = 5134;\n\tsecp256k1_pedersen_commitment lCommit;\n\n\tif (secp256k1_pedersen_commitment_parse(signatureContext(), &lCommit, &commit[0]))\n\t\tif (secp256k1_rangeproof_sign(signatureContext(), lProof, &lLen, 0, &lCommit, blind.begin(), nonce.begin(), 0, 0, amount, NULL, 0, NULL, 0, secp256k1_generator_h)) {\n\t\t\tout.insert(out.end(), lProof, lProof + lLen);\n\t\t\treturn true;\n\t\t}\n\n\treturn false;\n}\n\nbool Context::verifyRangeProof(const unsigned char* commit, const unsigned char* proof, size_t size) {\n\tuint64_t lMinValue;\n\tuint64_t lMaxValue;\n\tsecp256k1_pedersen_commitment lCommit;\n\tif (secp256k1_pedersen_commitment_parse(signatureContext(), &lCommit, commit))\n\t\tif (secp256k1_rangeproof_verify(signatureContext(), &lMinValue, &lMaxValue, &lCommit, proof, size, NULL, 0, secp256k1_generator_h))\n\t\treturn true;\n\n\treturn false;\n}\n\nbool Context::rewindRangeProof(uint64_t* vout, uint256& blind, const uint256& nonce, const unsigned char* commit, const unsigned char* proof, size_t size) {\n\tuint64_t lMinValue;\n\tuint64_t lMaxValue;\n\n\tsecp256k1_pedersen_commitment lCommit;\n\tif (secp256k1_pedersen_commitment_parse(signatureContext(), &lCommit, commit))\n\t\tif (secp256k1_rangeproof_rewind(signatureContext(), blind.begin(), vout, NULL, NULL, nonce.begin(), &lMinValue, &lMaxValue, &lCommit, proof, size, NULL, 0, secp256k1_generator_h))\n\t\t\treturn true;\n\treturn false;\n}\n\nbool Context::verifyTally(const std::list<std::vector<unsigned char>>& in, const std::list<std::vector<unsigned char>>& out) {\n\tstd::vector<secp256k1_pedersen_commitment> lIn;\n\tstd::vector<secp256k1_pedersen_commitment> lOut;\n\n\tstd::vector<secp256k1_pedersen_commitment*> lInPtr;\n\tstd::vector<secp256k1_pedersen_commitment*> lOutPtr;\n\n\tlIn.resize(in.size());\n\tlOut.resize(out.size());\n\n\tlInPtr.resize(in.size());\n\tlOutPtr.resize(out.size());\n\n\tint lIdx = 0;\n\tfor (std::list<std::vector<unsigned char>>::const_iterator lInIter = in.begin(); lInIter != in.end(); lInIter++, lIdx++) {\n\t\tif (secp256k1_pedersen_commitment_parse(signatureContext(), &lIn[lIdx], &(*lInIter)[0])) {\n\t\t\tlInPtr[lIdx] = &lIn[lIdx];\n\t\t} else return false;\n\t}\n\n\tlIdx = 0;\n\tfor (std::list<std::vector<unsigned char>>::const_iterator lOutIter = out.begin(); lOutIter != out.end(); lOutIter++, lIdx++) {\n\t\tif (secp256k1_pedersen_commitment_parse(signatureContext(), &lOut[lIdx], &(*lOutIter)[0])) {\n\t\t\tlOutPtr[lIdx] = &lOut[lIdx];\n\t\t} else return false;\n\t}\n\n\tif (!secp256k1_pedersen_verify_tally(signatureContext(), &lInPtr[0], lInPtr.size(), &lOutPtr[0], lOutPtr.size())) return false;\n\treturn true;\n}\n\n\nbool Math::add(uint256& c, const uint256& a, const uint256& b) {\n\tint lOverflow;\n\tsecp256k1_scalar lA; secp256k1_scalar_set_b32(&lA, a.begin(), &lOverflow); if (lOverflow) return 0;\n\tsecp256k1_scalar lB; secp256k1_scalar_set_b32(&lB, b.begin(), &lOverflow); if (lOverflow) return 0;\n\tsecp256k1_scalar lC;\n\n\tsecp256k1_scalar_add(&lC, &lA, &lB);\n\n\tunsigned char lRawC[32];\n\tsecp256k1_scalar_get_b32(lRawC, &lC);\n\n\tc.set(lRawC);\n\n\treturn 1;\n}\n\nbool Math::mul(uint256& c, const uint256& a, const uint256& b) {\n\tint lOverflow;\n\tsecp256k1_scalar lA; secp256k1_scalar_set_b32(&lA, a.begin(), &lOverflow); if (lOverflow) return 0;\n\tsecp256k1_scalar lB; secp256k1_scalar_set_b32(&lB, b.begin(), &lOverflow); if (lOverflow) return 0;\n\tsecp256k1_scalar lC;\n\n\tsecp256k1_scalar_mul(&lC, &lA, &lB);\n\n\tunsigned char lRawC[32];\n\tsecp256k1_scalar_get_b32(lRawC, &lC);\n\n\tc.set(lRawC);\n\n\treturn 1;\n}\n\nbool Math::neg(uint256& c, const uint256& a) {\n\tint lOverflow;\n\tsecp256k1_scalar lA; secp256k1_scalar_set_b32(&lA, a.begin(), &lOverflow); if (lOverflow) return 0;\n\tsecp256k1_scalar lC;\n\n\tsecp256k1_scalar_negate(&lC, &lA);\n\n\tunsigned char lRawC[32];\n\tsecp256k1_scalar_get_b32(lRawC, &lC);\n\n\tc.set(lRawC);\n\n\treturn 1;\n}\n", "meta": {"hexsha": "5b8d236e0973b84adb51ec8aaf23c744a50697bb", "size": 5961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "context.cpp", "max_stars_repo_name": "qbit-t/qb", "max_stars_repo_head_hexsha": "c1fd82df3838f8526fc5e335254529ab6f953f78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-14T04:04:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T04:04:50.000Z", "max_issues_repo_path": "context.cpp", "max_issues_repo_name": "qbit-t/qb", "max_issues_repo_head_hexsha": "c1fd82df3838f8526fc5e335254529ab6f953f78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "context.cpp", "max_forks_repo_name": "qbit-t/qb", "max_forks_repo_head_hexsha": "c1fd82df3838f8526fc5e335254529ab6f953f78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-28T07:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T07:42:43.000Z", "avg_line_length": 29.6567164179, "max_line_length": 181, "alphanum_fraction": 0.7421573561, "num_tokens": 1824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.024053553550309536, "lm_q1q2_score": 0.011651062295859889}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Alexander Sokolov <asokolov@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#include <nil/crypto3/detail/reverser.hpp>\n\n#include <boost/integer.hpp>\n#include <boost/static_assert.hpp>\n\n#include <iterator>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n\n            // By definition, for all exploders, InputValueBits > OutputValueBits,\n            // so we're taking one value and splitting it into many smaller values\n\n            /*!\n             * @defgroup exploder Exploder functions\n             */\n\n            /*!\n             * @brief outvalue_helper trait is used to determine the output value type.\n             * If OutBits is not an exact power of two for which the type uint_t is defined, the type\n             * with the least power of two bits greater than OutBits is taken. Due to current exploder\n             * struct definition, this case is possible, when OutputBits is a factor of UnitBits less\n             * than UnitBits, and UnitBits is no more than CHAR_BIT.\n             *\n             * @ingroup exploder\n             *\n             * @tparam OutIter\n             * @tparam OutBits\n             * @tparam T\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            /*!\n             * @brief exploder_shift trait is used to determine whether the output elements are splitted\n             * from an input element in reverse order. Since the input and output types are integral now,\n             * this trait contains the shift indicating the position of output element derived from the\n             * input element when k output bits have already been processed.\n             *\n             * @ingroup exploder\n             *\n             * @tparam InputEndianness\n             * @tparam UnitBits\n             * @tparam InputBits\n             * @tparam OutputBits\n             * @tparam k\n             * @tparam IsLittleUnit\n             */\n            template<typename InputEndianness, int UnitBits, int InputBits, int OutputBits, int k,\n                     bool IsLittleUnit = is_little_unit<InputEndianness, UnitBits>::value>\n            struct exploder_shift;\n\n            template<typename InputEndianness, int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder_shift<InputEndianness, UnitBits, InputBits, OutputBits, k, false> {\n                constexpr static int const value = InputBits - (OutputBits + k);\n            };\n\n            template<typename InputEndianness, int UnitBits, int InputBits, int OutputBits, int k>\n            struct exploder_shift<InputEndianness, UnitBits, InputBits, OutputBits, k, true> {\n                constexpr static int const value = k;\n            };\n\n            /*!\n             * @brief exploder_step obtains an output value represented in OutputEndianness endianness\n             * from an input value represented in InputEndianness endianness when k output 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 output value, respectively. Shift constant is determined\n             * by the exploder_shift trait.\n             *\n             * @ingroup exploder\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 exploder_step {\n                constexpr static int const shift =\n                    exploder_shift<InputEndianness, UnitBits, InputBits, OutputBits, k>::value;\n\n                template<typename InputValue, typename OutputIterator>\n                inline static void step(InputValue const &in, OutputIterator &out) {\n                    typedef typename outvalue_helper<OutputIterator, OutputBits>::type OutValue;\n                    OutValue tmp = OutValue(low_bits<OutputBits>(unbounded_shr<shift>(in)));\n                    unit_reverser<InputEndianness, OutputEndianness, UnitBits>::reverse(tmp);\n                    bit_reverser<InputEndianness, OutputEndianness, UnitBits>::reverse(tmp);\n                    *out++ = tmp;\n                }\n            };\n\n            /*!\n             * @brief exploder forms a sequence of output values represented in OutputEndianness endianness\n             * from an input value represented in InputEndianness endianness. The function explode is\n             * invoked recursively, and the parameter k is used to track the number of already processed\n             * output values derived from the input value. The recursion ends when all elements the input\n             * value can hold have already been processed, i.e. when k == InputBits.\n             *\n             * @ingroup exploder\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 exploder;\n\n            template<template<int> class InputEndian, template<int> class OutputEndian, int UnitBits, int InputBits,\n                     int OutputBits, int k>\n            struct exploder<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 exploder_step<InputEndianness, OutputEndianness, UnitBits, InputBits, OutputBits, k> step_type;\n                typedef exploder<InputEndianness, OutputEndianness, InputBits, OutputBits, k + OutputBits> next_type;\n\n                template<typename InputValue, typename OutIter>\n                inline 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 InputEndian, template<int> class OutputEndian, int UnitBits, int InputBits,\n                     int OutputBits>\n            struct exploder<InputEndian<UnitBits>, OutputEndian<UnitBits>, InputBits, OutputBits, InputBits> {\n                template<typename InputValue, typename OutIter>\n                inline static void explode(InputValue const &, OutIter &) {\n                }\n            };\n\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_DETAIL_EXPLODER_HPP\n", "meta": {"hexsha": "a881b718429086f3aa9f69c794a27fef2c677221", "size": 9057, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/exploder.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-23T02:25:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T02:25:55.000Z", "max_issues_repo_path": "include/nil/crypto3/detail/exploder.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/exploder.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": 48.6935483871, "max_line_length": 119, "alphanum_fraction": 0.6141106327, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758367247085, "lm_q2_score": 0.031143834019380416, "lm_q1q2_score": 0.011643927002811293}}
{"text": "//  Copyright John Maddock 2008.\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// Wrapper that works with mpfr_class defined in gmpfrxx.h\r\n// See http://math.berkeley.edu/~wilken/code/gmpfrxx/\r\n// Also requires the gmp and mpfr libraries.\r\n//\r\n\r\n#ifndef BOOST_MATH_E_FLOAT_BINDINGS_HPP\r\n#define BOOST_MATH_E_FLOAT_BINDINGS_HPP\r\n\r\n#include <boost/config.hpp>\r\n\r\n\r\n#include <e_float/e_float.h>\r\n#include <functions/functions.h>\r\n\r\n#include <boost/math/tools/precision.hpp>\r\n#include <boost/math/tools/real_cast.hpp>\r\n#include <boost/math/policies/policy.hpp>\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n#include <boost/math/bindings/detail/big_digamma.hpp>\r\n#include <boost/math/bindings/detail/big_lanczos.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\n\r\nnamespace boost{ namespace math{ namespace ef{\r\n\r\nclass e_float\r\n{\r\npublic:\r\n   // Constructors:\r\n   e_float() {}\r\n   e_float(const ::e_float& c) : m_value(c){}\r\n   e_float(char c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\r\n   e_float(wchar_t c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n#endif\r\n   e_float(unsigned char c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n   e_float(signed char c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n   e_float(unsigned short c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n   e_float(short c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n   e_float(unsigned int c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n   e_float(int c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n   e_float(unsigned long c)\r\n   {\r\n      m_value = ::e_float((UINT64)c);\r\n   }\r\n   e_float(long c)\r\n   {\r\n      m_value = ::e_float((INT64)c);\r\n   }\r\n#ifdef BOOST_HAS_LONG_LONG\r\n   e_float(boost::ulong_long_type c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n   e_float(boost::long_long_type c)\r\n   {\r\n      m_value = ::e_float(c);\r\n   }\r\n#endif\r\n   e_float(float c)\r\n   {\r\n      assign_large_real(c);\r\n   }\r\n   e_float(double c)\r\n   {\r\n      assign_large_real(c);\r\n   }\r\n   e_float(long double c)\r\n   {\r\n      assign_large_real(c);\r\n   }\r\n\r\n   // Assignment:\r\n   e_float& operator=(char c) { m_value = ::e_float(c); return *this; }\r\n   e_float& operator=(unsigned char c) { m_value = ::e_float(c); return *this; }\r\n   e_float& operator=(signed char c) { m_value = ::e_float(c); return *this; }\r\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\r\n   e_float& operator=(wchar_t c) { m_value = ::e_float(c); return *this; }\r\n#endif\r\n   e_float& operator=(short c) { m_value = ::e_float(c); return *this; }\r\n   e_float& operator=(unsigned short c) { m_value = ::e_float(c); return *this; }\r\n   e_float& operator=(int c) { m_value = ::e_float(c); return *this; }\r\n   e_float& operator=(unsigned int c) { m_value = ::e_float(c); return *this; }\r\n   e_float& operator=(long c) { m_value = ::e_float((INT64)c); return *this; }\r\n   e_float& operator=(unsigned long c) { m_value = ::e_float((UINT64)c); return *this; }\r\n#ifdef BOOST_HAS_LONG_LONG\r\n   e_float& operator=(boost::long_long_type c) { m_value = ::e_float(c); return *this; }\r\n   e_float& operator=(boost::ulong_long_type c) { m_value = ::e_float(c); return *this; }\r\n#endif\r\n   e_float& operator=(float c) { assign_large_real(c); return *this; }\r\n   e_float& operator=(double c) { assign_large_real(c); return *this; }\r\n   e_float& operator=(long double c) { assign_large_real(c); return *this; }\r\n\r\n   // Access:\r\n   ::e_float& value(){ return m_value; }\r\n   ::e_float const& value()const{ return m_value; }\r\n\r\n   // Member arithmetic:\r\n   e_float& operator+=(const e_float& other)\r\n   { m_value += other.value(); return *this; }\r\n   e_float& operator-=(const e_float& other)\r\n   { m_value -= other.value(); return *this; }\r\n   e_float& operator*=(const e_float& other)\r\n   { m_value *= other.value(); return *this; }\r\n   e_float& operator/=(const e_float& other)\r\n   { m_value /= other.value(); return *this; }\r\n   e_float operator-()const\r\n   { return -m_value; }\r\n   e_float const& operator+()const\r\n   { return *this; }\r\n\r\nprivate:\r\n   ::e_float m_value;\r\n\r\n   template <class V>\r\n   void assign_large_real(const V& a)\r\n   {\r\n      using std::frexp;\r\n      using std::ldexp;\r\n      using std::floor;\r\n      if (a == 0) {\r\n         m_value = ::ef::zero();\r\n         return;\r\n      }\r\n\r\n      if (a == 1) {\r\n         m_value = ::ef::one();\r\n         return;\r\n      }\r\n\r\n      if ((boost::math::isinf)(a))\r\n      {\r\n         m_value = a > 0 ? m_value.my_value_inf() : -m_value.my_value_inf();\r\n         return;\r\n      }\r\n      if((boost::math::isnan)(a))\r\n      {\r\n         m_value = m_value.my_value_nan();\r\n         return;\r\n      }\r\n\r\n      int e;\r\n      long double f, term;\r\n      ::e_float t;\r\n      m_value = ::ef::zero();\r\n\r\n      f = frexp(a, &e);\r\n\r\n      ::e_float shift = ::ef::pow2(30);\r\n\r\n      while(f)\r\n      {\r\n         // extract 30 bits from f:\r\n         f = ldexp(f, 30);\r\n         term = floor(f);\r\n         e -= 30;\r\n         m_value *= shift;\r\n         m_value += ::e_float(static_cast<INT64>(term));\r\n         f -= term;\r\n      }\r\n      m_value *= ::ef::pow2(e);\r\n   }\r\n};\r\n\r\n\r\n// Non-member arithmetic:\r\ninline e_float operator+(const e_float& a, const e_float& b)\r\n{\r\n   e_float result(a);\r\n   result += b;\r\n   return result;\r\n}\r\ninline e_float operator-(const e_float& a, const e_float& b)\r\n{\r\n   e_float result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\ninline e_float operator*(const e_float& a, const e_float& b)\r\n{\r\n   e_float result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\ninline e_float operator/(const e_float& a, const e_float& b)\r\n{\r\n   e_float result(a);\r\n   result /= b;\r\n   return result;\r\n}\r\n\r\n// Comparison:\r\ninline bool operator == (const e_float& a, const e_float& b)\r\n{ return a.value() == b.value() ? true : false; }\r\ninline bool operator != (const e_float& a, const e_float& b)\r\n{ return a.value() != b.value() ? true : false;}\r\ninline bool operator < (const e_float& a, const e_float& b)\r\n{ return a.value() < b.value() ? true : false; }\r\ninline bool operator <= (const e_float& a, const e_float& b)\r\n{ return a.value() <= b.value() ? true : false; }\r\ninline bool operator > (const e_float& a, const e_float& b)\r\n{ return a.value() > b.value() ? true : false; }\r\ninline bool operator >= (const e_float& a, const e_float& b)\r\n{ return a.value() >= b.value() ? true : false; }\r\n\r\nstd::istream& operator >> (std::istream& is, e_float& f)\r\n{\r\n   return is >> f.value();\r\n}\r\n\r\nstd::ostream& operator << (std::ostream& os, const e_float& f)\r\n{\r\n   return os << f.value();\r\n}\r\n\r\ninline e_float fabs(const e_float& v)\r\n{\r\n   return ::ef::fabs(v.value());\r\n}\r\n\r\ninline e_float abs(const e_float& v)\r\n{\r\n   return ::ef::fabs(v.value());\r\n}\r\n\r\ninline e_float floor(const e_float& v)\r\n{\r\n   return ::ef::floor(v.value());\r\n}\r\n\r\ninline e_float ceil(const e_float& v)\r\n{\r\n   return ::ef::ceil(v.value());\r\n}\r\n\r\ninline e_float pow(const e_float& v, const e_float& w)\r\n{\r\n   return ::ef::pow(v.value(), w.value());\r\n}\r\n\r\ninline e_float pow(const e_float& v, int i)\r\n{\r\n   return ::ef::pow(v.value(), ::e_float(i));\r\n}\r\n\r\ninline e_float exp(const e_float& v)\r\n{\r\n   return ::ef::exp(v.value());\r\n}\r\n\r\ninline e_float log(const e_float& v)\r\n{\r\n   return ::ef::log(v.value());\r\n}\r\n\r\ninline e_float sqrt(const e_float& v)\r\n{\r\n   return ::ef::sqrt(v.value());\r\n}\r\n\r\ninline e_float sin(const e_float& v)\r\n{\r\n   return ::ef::sin(v.value());\r\n}\r\n\r\ninline e_float cos(const e_float& v)\r\n{\r\n   return ::ef::cos(v.value());\r\n}\r\n\r\ninline e_float tan(const e_float& v)\r\n{\r\n   return ::ef::tan(v.value());\r\n}\r\n\r\ninline e_float acos(const e_float& v)\r\n{\r\n   return ::ef::acos(v.value());\r\n}\r\n\r\ninline e_float asin(const e_float& v)\r\n{\r\n   return ::ef::asin(v.value());\r\n}\r\n\r\ninline e_float atan(const e_float& v)\r\n{\r\n   return ::ef::atan(v.value());\r\n}\r\n\r\ninline e_float atan2(const e_float& v, const e_float& u)\r\n{\r\n   return ::ef::atan2(v.value(), u.value());\r\n}\r\n\r\ninline e_float ldexp(const e_float& v, int e)\r\n{\r\n   return v.value() * ::ef::pow2(e);\r\n}\r\n\r\ninline e_float frexp(const e_float& v, int* expon)\r\n{\r\n   double d;\r\n   INT64 i;\r\n   v.value().extract_parts(d, i);\r\n   *expon = static_cast<int>(i);\r\n   return v.value() * ::ef::pow2(-i);\r\n}\r\n\r\ninline e_float sinh (const e_float& x)\r\n{\r\n   return ::ef::sinh(x.value());\r\n}\r\n\r\ninline e_float cosh (const e_float& x)\r\n{\r\n   return ::ef::cosh(x.value());\r\n}\r\n\r\ninline e_float tanh (const e_float& x)\r\n{\r\n   return ::ef::tanh(x.value());\r\n}\r\n\r\ninline e_float asinh (const e_float& x)\r\n{\r\n   return ::ef::asinh(x.value());\r\n}\r\n\r\ninline e_float acosh (const e_float& x)\r\n{\r\n   return ::ef::acosh(x.value());\r\n}\r\n\r\ninline e_float atanh (const e_float& x)\r\n{\r\n   return ::ef::atanh(x.value());\r\n}\r\n\r\ne_float fmod(const e_float& v1, const e_float& v2)\r\n{\r\n   e_float n;\r\n   if(v1 < 0)\r\n      n = ceil(v1 / v2);\r\n   else\r\n      n = floor(v1 / v2);\r\n   return v1 - n * v2;\r\n}\r\n\r\n} namespace detail{\r\n\r\ntemplate <>\r\ninline int fpclassify_imp< boost::math::ef::e_float> BOOST_NO_MACRO_EXPAND(boost::math::ef::e_float x, const generic_tag<true>&)\r\n{\r\n   if(x.value().isnan())\r\n      return FP_NAN;\r\n   if(x.value().isinf())\r\n      return FP_INFINITE;\r\n   if(x == 0)\r\n      return FP_ZERO;\r\n   return FP_NORMAL;\r\n}\r\n\r\n} namespace ef{\r\n\r\ntemplate <class Policy>\r\ninline int itrunc(const e_float& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   e_float r = boost::math::trunc(v, pol);\r\n   if(fabs(r) > (std::numeric_limits<int>::max)())\r\n      return static_cast<int>(policies::raise_rounding_error(\"boost::math::itrunc<%1%>(%1%)\", 0, 0, v, pol));\r\n   return static_cast<int>(r.value().extract_int64());\r\n}\r\n\r\ntemplate <class Policy>\r\ninline long ltrunc(const e_float& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   e_float r = boost::math::trunc(v, pol);\r\n   if(fabs(r) > (std::numeric_limits<long>::max)())\r\n      return static_cast<long>(policies::raise_rounding_error(\"boost::math::ltrunc<%1%>(%1%)\", 0, 0L, v, pol));\r\n   return static_cast<long>(r.value().extract_int64());\r\n}\r\n\r\n#ifdef BOOST_HAS_LONG_LONG\r\ntemplate <class Policy>\r\ninline boost::long_long_type lltrunc(const e_float& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   e_float r = boost::math::trunc(v, pol);\r\n   if(fabs(r) > (std::numeric_limits<boost::long_long_type>::max)())\r\n      return static_cast<boost::long_long_type>(policies::raise_rounding_error(\"boost::math::lltrunc<%1%>(%1%)\", 0, v, 0LL, pol).value().extract_int64());\r\n   return static_cast<boost::long_long_type>(r.value().extract_int64());\r\n}\r\n#endif\r\n\r\ntemplate <class Policy>\r\ninline int iround(const e_float& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   e_float r = boost::math::round(v, pol);\r\n   if(fabs(r) > (std::numeric_limits<int>::max)())\r\n      return static_cast<int>(policies::raise_rounding_error(\"boost::math::iround<%1%>(%1%)\", 0, v, 0, pol).value().extract_int64());\r\n   return static_cast<int>(r.value().extract_int64());\r\n}\r\n\r\ntemplate <class Policy>\r\ninline long lround(const e_float& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   e_float r = boost::math::round(v, pol);\r\n   if(fabs(r) > (std::numeric_limits<long>::max)())\r\n      return static_cast<long int>(policies::raise_rounding_error(\"boost::math::lround<%1%>(%1%)\", 0, v, 0L, pol).value().extract_int64());\r\n   return static_cast<long int>(r.value().extract_int64());\r\n}\r\n\r\n#ifdef BOOST_HAS_LONG_LONG\r\ntemplate <class Policy>\r\ninline boost::long_long_type llround(const e_float& v, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   e_float r = boost::math::round(v, pol);\r\n   if(fabs(r) > (std::numeric_limits<boost::long_long_type>::max)())\r\n      return static_cast<boost::long_long_type>(policies::raise_rounding_error(\"boost::math::llround<%1%>(%1%)\", 0, v, 0LL, pol).value().extract_int64());\r\n   return static_cast<boost::long_long_type>(r.value().extract_int64());\r\n}\r\n#endif\r\n\r\n}}}\r\n\r\nnamespace std{\r\n\r\n   template<>\r\n   class numeric_limits< ::boost::math::ef::e_float> : public numeric_limits< ::e_float>\r\n   {\r\n   public:\r\n      static const ::boost::math::ef::e_float (min) (void)\r\n      {\r\n         return (numeric_limits< ::e_float>::min)();\r\n      }\r\n      static const ::boost::math::ef::e_float (max) (void)\r\n      {\r\n         return (numeric_limits< ::e_float>::max)();\r\n      }\r\n      static const ::boost::math::ef::e_float epsilon (void)\r\n      {\r\n         return (numeric_limits< ::e_float>::epsilon)();\r\n      }\r\n      static const ::boost::math::ef::e_float round_error(void)\r\n      {\r\n         return (numeric_limits< ::e_float>::round_error)();\r\n      }\r\n      static const ::boost::math::ef::e_float infinity (void)\r\n      {\r\n         return (numeric_limits< ::e_float>::infinity)();\r\n      }\r\n      static const ::boost::math::ef::e_float quiet_NaN (void)\r\n      {\r\n         return (numeric_limits< ::e_float>::quiet_NaN)();\r\n      }\r\n      //\r\n      // e_float's supplied digits member is wrong \r\n      // - it should be same the same as digits 10\r\n      // - given that radix is 10.\r\n      //\r\n      static const int digits = digits10;\r\n   };\r\n\r\n} // namespace std\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace policies{\r\n\r\ntemplate <class Policy>\r\nstruct precision< ::boost::math::ef::e_float, Policy>\r\n{\r\n   typedef typename Policy::precision_type precision_type;\r\n   typedef digits2<((::std::numeric_limits< ::boost::math::ef::e_float>::digits10 + 1) * 1000L) / 301L> digits_2;\r\n   typedef typename mpl::if_c<\r\n      ((digits_2::value <= precision_type::value) \r\n      || (Policy::precision_type::value <= 0)),\r\n      // Default case, full precision for RealType:\r\n      digits_2,\r\n      // User customised precision:\r\n      precision_type\r\n   >::type type;\r\n};\r\n\r\n}\r\n\r\nnamespace tools{\r\n\r\ntemplate <>\r\ninline int digits< ::boost::math::ef::e_float>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC( ::boost::math::ef::e_float))\r\n{\r\n   return ((::std::numeric_limits< ::boost::math::ef::e_float>::digits10 + 1) * 1000L) / 301L;\r\n}\r\n\r\ntemplate <>\r\ninline  ::boost::math::ef::e_float root_epsilon< ::boost::math::ef::e_float>()\r\n{\r\n   return detail::root_epsilon_imp(static_cast< ::boost::math::ef::e_float const*>(0), boost::integral_constant<int, 0>());\r\n}\r\n\r\ntemplate <>\r\ninline  ::boost::math::ef::e_float forth_root_epsilon< ::boost::math::ef::e_float>()\r\n{\r\n   return detail::forth_root_epsilon_imp(static_cast< ::boost::math::ef::e_float const*>(0), boost::integral_constant<int, 0>());\r\n}\r\n\r\n}\r\n\r\nnamespace lanczos{\r\n\r\ntemplate<class Policy>\r\nstruct lanczos<boost::math::ef::e_float, Policy>\r\n{\r\n   typedef typename mpl::if_c<\r\n      std::numeric_limits< ::e_float>::digits10 < 22,\r\n      lanczos13UDT,\r\n      typename mpl::if_c<\r\n         std::numeric_limits< ::e_float>::digits10 < 36,\r\n         lanczos22UDT,\r\n         typename mpl::if_c<\r\n            std::numeric_limits< ::e_float>::digits10 < 50,\r\n            lanczos31UDT,\r\n            typename mpl::if_c<\r\n               std::numeric_limits< ::e_float>::digits10 < 110,\r\n               lanczos61UDT,\r\n               undefined_lanczos\r\n            >::type\r\n         >::type\r\n      >::type\r\n   >::type type;\r\n};\r\n\r\n} // namespace lanczos\r\n\r\ntemplate <class Policy>\r\ninline boost::math::ef::e_float skewness(const extreme_value_distribution<boost::math::ef::e_float, Policy>& /*dist*/)\r\n{\r\n   //\r\n   // This is 12 * sqrt(6) * zeta(3) / pi^3:\r\n   // See http://mathworld.wolfram.com/ExtremeValueDistribution.html\r\n   //\r\n   return boost::lexical_cast<boost::math::ef::e_float>(\"1.1395470994046486574927930193898461120875997958366\");\r\n}\r\n\r\ntemplate <class Policy>\r\ninline boost::math::ef::e_float skewness(const rayleigh_distribution<boost::math::ef::e_float, Policy>& /*dist*/)\r\n{\r\n  // using namespace boost::math::constants;\r\n  return boost::lexical_cast<boost::math::ef::e_float>(\"0.63111065781893713819189935154422777984404221106391\");\r\n  // Computed using NTL at 150 bit, about 50 decimal digits.\r\n  // return 2 * root_pi<RealType>() * pi_minus_three<RealType>() / pow23_four_minus_pi<RealType>();\r\n}\r\n\r\ntemplate <class Policy>\r\ninline boost::math::ef::e_float kurtosis(const rayleigh_distribution<boost::math::ef::e_float, Policy>& /*dist*/)\r\n{\r\n  // using namespace boost::math::constants;\r\n  return boost::lexical_cast<boost::math::ef::e_float>(\"3.2450893006876380628486604106197544154170667057995\");\r\n  // Computed using NTL at 150 bit, about 50 decimal digits.\r\n  // return 3 - (6 * pi<RealType>() * pi<RealType>() - 24 * pi<RealType>() + 16) /\r\n  // (four_minus_pi<RealType>() * four_minus_pi<RealType>());\r\n}\r\n\r\ntemplate <class Policy>\r\ninline boost::math::ef::e_float kurtosis_excess(const rayleigh_distribution<boost::math::ef::e_float, Policy>& /*dist*/)\r\n{\r\n  //using namespace boost::math::constants;\r\n  // Computed using NTL at 150 bit, about 50 decimal digits.\r\n  return boost::lexical_cast<boost::math::ef::e_float>(\"0.2450893006876380628486604106197544154170667057995\");\r\n  // return -(6 * pi<RealType>() * pi<RealType>() - 24 * pi<RealType>() + 16) /\r\n  //   (four_minus_pi<RealType>() * four_minus_pi<RealType>());\r\n} // kurtosis\r\n\r\nnamespace detail{\r\n\r\n//\r\n// Version of Digamma accurate to ~100 decimal digits.\r\n//\r\ntemplate <class Policy>\r\nboost::math::ef::e_float digamma_imp(boost::math::ef::e_float x, const boost::integral_constant<int, 0>* , const Policy& pol)\r\n{\r\n   //\r\n   // This handles reflection of negative arguments, and all our\r\n   // eboost::math::ef::e_floator handling, then forwards to the T-specific approximation.\r\n   //\r\n   BOOST_MATH_STD_USING // ADL of std functions.\r\n\r\n   boost::math::ef::e_float result = 0;\r\n   //\r\n   // Check for negative arguments and use reflection:\r\n   //\r\n   if(x < 0)\r\n   {\r\n      // Reflect:\r\n      x = 1 - x;\r\n      // Argument reduction for tan:\r\n      boost::math::ef::e_float remainder = x - floor(x);\r\n      // Shift to negative if > 0.5:\r\n      if(remainder > 0.5)\r\n      {\r\n         remainder -= 1;\r\n      }\r\n      //\r\n      // check for evaluation at a negative pole:\r\n      //\r\n      if(remainder == 0)\r\n      {\r\n         return policies::raise_pole_error<boost::math::ef::e_float>(\"boost::math::digamma<%1%>(%1%)\", 0, (1-x), pol);\r\n      }\r\n      result = constants::pi<boost::math::ef::e_float>() / tan(constants::pi<boost::math::ef::e_float>() * remainder);\r\n   }\r\n   result += big_digamma(x);\r\n   return result;\r\n}\r\nboost::math::ef::e_float bessel_i0(boost::math::ef::e_float x)\r\n{\r\n    static const boost::math::ef::e_float P1[] = {\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-2.2335582639474375249e+15\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-5.5050369673018427753e+14\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-3.2940087627407749166e+13\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-8.4925101247114157499e+11\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-1.1912746104985237192e+10\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-1.0313066708737980747e+08\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-5.9545626019847898221e+05\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-2.4125195876041896775e+03\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-7.0935347449210549190e+00\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-1.5453977791786851041e-02\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-2.5172644670688975051e-05\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-3.0517226450451067446e-08\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-2.6843448573468483278e-11\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-1.5982226675653184646e-14\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-5.2487866627945699800e-18\"),\r\n    };\r\n    static const boost::math::ef::e_float Q1[] = {\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-2.2335582639474375245e+15\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"7.8858692566751002988e+12\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-1.2207067397808979846e+10\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"1.0377081058062166144e+07\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-4.8527560179962773045e+03\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"1.0\"),\r\n    };\r\n    static const boost::math::ef::e_float P2[] = {\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-2.2210262233306573296e-04\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"1.3067392038106924055e-02\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-4.4700805721174453923e-01\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"5.5674518371240761397e+00\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-2.3517945679239481621e+01\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"3.1611322818701131207e+01\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-9.6090021968656180000e+00\"),\r\n    };\r\n    static const boost::math::ef::e_float Q2[] = {\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-5.5194330231005480228e-04\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"3.2547697594819615062e-02\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-1.1151759188741312645e+00\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"1.3982595353892851542e+01\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-6.0228002066743340583e+01\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"8.5539563258012929600e+01\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"-3.1446690275135491500e+01\"),\r\n        boost::lexical_cast<boost::math::ef::e_float>(\"1.0\"),\r\n    };\r\n    boost::math::ef::e_float value, factor, r;\r\n\r\n    BOOST_MATH_STD_USING\r\n    using namespace boost::math::tools;\r\n\r\n    if (x < 0)\r\n    {\r\n        x = -x;                         // even function\r\n    }\r\n    if (x == 0)\r\n    {\r\n        return static_cast<boost::math::ef::e_float>(1);\r\n    }\r\n    if (x <= 15)                        // x in (0, 15]\r\n    {\r\n        boost::math::ef::e_float y = x * x;\r\n        value = evaluate_polynomial(P1, y) / evaluate_polynomial(Q1, y);\r\n    }\r\n    else                                // x in (15, \\infty)\r\n    {\r\n        boost::math::ef::e_float y = 1 / x - boost::math::ef::e_float(1) / 15;\r\n        r = evaluate_polynomial(P2, y) / evaluate_polynomial(Q2, y);\r\n        factor = exp(x) / sqrt(x);\r\n        value = factor * r;\r\n    }\r\n\r\n    return value;\r\n}\r\n\r\nboost::math::ef::e_float bessel_i1(boost::math::ef::e_float x)\r\n{\r\n    static const boost::math::ef::e_float P1[] = {\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.4577180278143463643e+15\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.7732037840791591320e+14\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-6.9876779648010090070e+12\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.3357437682275493024e+11\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.4828267606612366099e+09\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.0588550724769347106e+07\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-5.1894091982308017540e+04\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.8225946631657315931e+02\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-4.7207090827310162436e-01\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-9.1746443287817501309e-04\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.3466829827635152875e-06\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.4831904935994647675e-09\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.1928788903603238754e-12\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-6.5245515583151902910e-16\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.9705291802535139930e-19\"),\r\n    };\r\n    static const boost::math::ef::e_float Q1[] = {\r\n        lexical_cast<boost::math::ef::e_float>(\"-2.9154360556286927285e+15\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"9.7887501377547640438e+12\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.4386907088588283434e+10\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"1.1594225856856884006e+07\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-5.1326864679904189920e+03\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"1.0\"),\r\n    };\r\n    static const boost::math::ef::e_float P2[] = {\r\n        lexical_cast<boost::math::ef::e_float>(\"1.4582087408985668208e-05\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-8.9359825138577646443e-04\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"2.9204895411257790122e-02\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-3.4198728018058047439e-01\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"1.3960118277609544334e+00\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-1.9746376087200685843e+00\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"8.5591872901933459000e-01\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-6.0437159056137599999e-02\"),\r\n    };\r\n    static const boost::math::ef::e_float Q2[] = {\r\n        lexical_cast<boost::math::ef::e_float>(\"3.7510433111922824643e-05\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-2.2835624489492512649e-03\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"7.4212010813186530069e-02\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-8.5017476463217924408e-01\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"3.2593714889036996297e+00\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"-3.8806586721556593450e+00\"),\r\n        lexical_cast<boost::math::ef::e_float>(\"1.0\"),\r\n    };\r\n    boost::math::ef::e_float value, factor, r, w;\r\n\r\n    BOOST_MATH_STD_USING\r\n    using namespace boost::math::tools;\r\n\r\n    w = abs(x);\r\n    if (x == 0)\r\n    {\r\n        return static_cast<boost::math::ef::e_float>(0);\r\n    }\r\n    if (w <= 15)                        // w in (0, 15]\r\n    {\r\n        boost::math::ef::e_float y = x * x;\r\n        r = evaluate_polynomial(P1, y) / evaluate_polynomial(Q1, y);\r\n        factor = w;\r\n        value = factor * r;\r\n    }\r\n    else                                // w in (15, \\infty)\r\n    {\r\n        boost::math::ef::e_float y = 1 / w - boost::math::ef::e_float(1) / 15;\r\n        r = evaluate_polynomial(P2, y) / evaluate_polynomial(Q2, y);\r\n        factor = exp(w) / sqrt(w);\r\n        value = factor * r;\r\n    }\r\n\r\n    if (x < 0)\r\n    {\r\n        value *= -value;                 // odd function\r\n    }\r\n    return value;\r\n}\r\n\r\n} // namespace detail\r\n\r\n}}\r\n#endif // BOOST_MATH_E_FLOAT_BINDINGS_HPP\r\n\r\n", "meta": {"hexsha": "9c35921ccbc07d6c0a016c11c96a0e4b47442e38", "size": 26603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/bindings/e_float.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/bindings/e_float.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/bindings/e_float.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": 32.8432098765, "max_line_length": 155, "alphanum_fraction": 0.6155696726, "num_tokens": 7630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.0351448448849122, "lm_q1q2_score": 0.01163715188759342}}
{"text": "// Copyright (c) 2008-2016 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 UUID_384AFF3AD23A11DFA80B754FE0D72085\n#define UUID_384AFF3AD23A11DFA80B754FE0D72085\n\n#include <boost/qvm/assert.hpp>\n#include <boost/qvm/detail/vec_assign.hpp>\n#include <boost/qvm/scalar_traits.hpp>\n#include <boost/qvm/vec_operations2.hpp>\n#include <boost/qvm/vec_operations3.hpp>\n#include <boost/qvm/vec_operations4.hpp>\n#include <string>\n\nnamespace boost {\nnamespace qvm {\nnamespace qvm_detail {\nBOOST_QVM_INLINE_CRITICAL\nvoid const *get_valid_ptr_vec_operations() {\n  static int const obj = 0;\n  return &obj;\n}\n} // namespace qvm_detail\n\n////////////////////////////////////////////////\n\nnamespace qvm_to_string_detail {\ntemplate <class T> std::string to_string(T const &x);\n}\n\nnamespace qvm_detail {\ntemplate <int D> struct to_string_v_defined {\n  static bool const value = false;\n};\n\ntemplate <int I, int DimMinusOne> struct to_string_vector_elements {\n  template <class A> static std::string f(A const &a) {\n    using namespace qvm_to_string_detail;\n    return to_string(vec_traits<A>::template read_element<I>(a)) + ',' +\n           to_string_vector_elements<I + 1, DimMinusOne>::f(a);\n  }\n};\n\ntemplate <int DimMinusOne>\nstruct to_string_vector_elements<DimMinusOne, DimMinusOne> {\n  template <class A> static std::string f(A const &a) {\n    using namespace qvm_to_string_detail;\n    return to_string(vec_traits<A>::template read_element<DimMinusOne>(a));\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class A>\ninline typename boost::enable_if_c<\n    is_vec<A>::value &&\n        !qvm_detail::to_string_v_defined<vec_traits<A>::dim>::value,\n    std::string>::type\nto_string(A const &a) {\n  return '(' +\n         qvm_detail::to_string_vector_elements<0, vec_traits<A>::dim - 1>::f(\n             a) +\n         ')';\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct convert_to_v_defined {\n  static bool const value = false;\n};\n} // namespace qvm_detail\n\ntemplate <class R, class A>\nBOOST_QVM_INLINE_TRIVIAL typename enable_if_c<\n    is_vec<R>::value && is_vec<A>::value &&\n        vec_traits<R>::dim == vec_traits<A>::dim &&\n        !qvm_detail::convert_to_v_defined<vec_traits<R>::dim>::value,\n    R>::type\nconvert_to(A const &a) {\n  R r;\n  assign(r, a);\n  return r;\n}\n\n////////////////////////////////////////////////\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_vec<A>::value && is_vec<B>::value &&\n                                  vec_traits<A>::dim == 3 &&\n                                  vec_traits<B>::dim == 3,\n                              deduce_vec2<A, B, 3>>::type\n    cross(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, 3>::type R;\n  R r;\n  vec_traits<R>::template write_element<0>(r) =\n      vec_traits<A>::template read_element<1>(a) *\n          vec_traits<B>::template read_element<2>(b) -\n      vec_traits<A>::template read_element<2>(a) *\n          vec_traits<B>::template read_element<1>(b);\n  vec_traits<R>::template write_element<1>(r) =\n      vec_traits<A>::template read_element<2>(a) *\n          vec_traits<B>::template read_element<0>(b) -\n      vec_traits<A>::template read_element<0>(a) *\n          vec_traits<B>::template read_element<2>(b);\n  vec_traits<R>::template write_element<2>(r) =\n      vec_traits<A>::template read_element<0>(a) *\n          vec_traits<B>::template read_element<1>(b) -\n      vec_traits<A>::template read_element<1>(a) *\n          vec_traits<B>::template read_element<0>(b);\n  return r;\n}\n\n////////////////////////////////////////////////\n\ntemplate <class A, class B, class Cmp>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_vec<A>::value && is_vec<B>::value &&\n                             vec_traits<A>::dim == vec_traits<B>::dim,\n                         bool>::type\n    cmp(A const &a, B const &b, Cmp f) {\n  typedef typename deduce_scalar<typename vec_traits<A>::scalar_type,\n                                 typename vec_traits<B>::scalar_type>::type T;\n  int const dim = vec_traits<A>::dim;\n  T v1[dim];\n  assign(v1, a);\n  T v2[dim];\n  assign(v2, b);\n  for (int i = 0; i != dim; ++i)\n    if (!f(v1[i], v2[i]))\n      return false;\n  return true;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T, int Dim> class zero_vec_ {\n  zero_vec_(zero_vec_ const &);\n  zero_vec_ &operator=(zero_vec_ const &);\n  ~zero_vec_();\n\npublic:\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class V> struct vec_traits;\n\ntemplate <class T, int Dim> struct vec_traits<qvm_detail::zero_vec_<T, Dim>> {\n  typedef qvm_detail::zero_vec_<T, Dim> this_vector;\n  typedef T scalar_type;\n  static int const dim = Dim;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_vector const &) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < Dim);\n    return scalar_traits<scalar_type>::value(0);\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_vector const &) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < Dim);\n    return scalar_traits<scalar_type>::value(0);\n  }\n};\n\ntemplate <class T, int Dim, int D>\nstruct deduce_vec<qvm_detail::zero_vec_<T, Dim>, D> {\n  typedef vec<T, D> type;\n};\n\ntemplate <class T, int Dim>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::zero_vec_<T, Dim> const &zero_vec() {\n  return *(qvm_detail::zero_vec_<T, Dim> const *)\n      qvm_detail::get_valid_ptr_vec_operations();\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_vec<A>::value, void>::type\nset_zero(A &a) {\n  assign(a,\n         zero_vec<typename vec_traits<A>::scalar_type, vec_traits<A>::dim>());\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalType, class Scalar> class vector_scalar_cast_ {\n  vector_scalar_cast_(vector_scalar_cast_ const &);\n  vector_scalar_cast_ &operator=(vector_scalar_cast_ const &);\n  ~vector_scalar_cast_();\n\npublic:\n  template <class T>\n  BOOST_QVM_INLINE_TRIVIAL vector_scalar_cast_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n\ntemplate <bool> struct scalar_cast_vector_filter {};\ntemplate <> struct scalar_cast_vector_filter<true> { typedef int type; };\n} // namespace qvm_detail\n\ntemplate <class OriginalType, class Scalar>\nstruct vec_traits<qvm_detail::vector_scalar_cast_<OriginalType, Scalar>> {\n  typedef Scalar scalar_type;\n  typedef qvm_detail::vector_scalar_cast_<OriginalType, Scalar> this_vector;\n  static int const dim = vec_traits<OriginalType>::dim;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_vector const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return scalar_type(vec_traits<OriginalType>::template read_element<I>(\n        reinterpret_cast<OriginalType const &>(x)));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_vector const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return scalar_type(vec_traits<OriginalType>::read_element_idx(\n        i, reinterpret_cast<OriginalType const &>(x)));\n  }\n};\n\ntemplate <class OriginalType, class Scalar, int D>\nstruct deduce_vec<qvm_detail::vector_scalar_cast_<OriginalType, Scalar>, D> {\n  typedef vec<Scalar, D> type;\n};\n\ntemplate <class Scalar, class T>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::vector_scalar_cast_<T, Scalar> const &\nscalar_cast(\n    T const &x,\n    typename qvm_detail::scalar_cast_vector_filter<is_vec<T>::value>::type =\n        0) {\n  return reinterpret_cast<qvm_detail::vector_scalar_cast_<T, Scalar> const &>(\n      x);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct div_eq_vs_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<\n    is_vec<A>::value && is_scalar<B>::value &&\n        !qvm_detail::div_eq_vs_defined<vec_traits<A>::dim>::value,\n    A &>::type\noperator/=(A &a, B b) {\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<A>::write_element_idx(i, a) /= b;\n  return a;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct div_vs_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_vec<A>::value && is_scalar<B>::value &&\n        !qvm_detail::div_vs_defined<vec_traits<A>::dim>::value,\n    deduce_vec<A>>::type\noperator/(A const &a, B b) {\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<R>::write_element_idx(i, r) =\n        vec_traits<A>::read_element_idx(i, a) / b;\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct dot_vv_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_vec<A>::value && is_vec<B>::value &&\n        vec_traits<A>::dim == vec_traits<B>::dim &&\n        !qvm_detail::dot_vv_defined<vec_traits<A>::dim>::value,\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 deduce_scalar<typename vec_traits<A>::scalar_type,\n                                 typename vec_traits<B>::scalar_type>::type T;\n  T m(scalar_traits<T>::value(0));\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    m += vec_traits<A>::read_element_idx(i, a) *\n         vec_traits<B>::read_element_idx(i, b);\n  return m;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct eq_vv_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<\n    is_vec<A>::value && is_vec<B>::value &&\n        vec_traits<A>::dim == vec_traits<B>::dim &&\n        !qvm_detail::eq_vv_defined<vec_traits<A>::dim>::value,\n    bool>::type\noperator==(A const &a, B const &b) {\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    if (vec_traits<A>::read_element_idx(i, a) !=\n        vec_traits<B>::read_element_idx(i, b))\n      return false;\n  return true;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct mag_sqr_v_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_vec<A>::value && !qvm_detail::mag_sqr_v_defined<\n                                                 vec_traits<A>::dim>::value,\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 m(scalar_traits<T>::value(0));\n  for (int i = 0; i != vec_traits<A>::dim; ++i) {\n    T x = vec_traits<A>::read_element_idx(i, a);\n    m += x * x;\n  }\n  return m;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct mag_v_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<\n    is_vec<A>::value && !qvm_detail::mag_v_defined<vec_traits<A>::dim>::value,\n    typename vec_traits<A>::scalar_type>::type\nmag(A const &a) {\n  typedef typename vec_traits<A>::scalar_type T;\n  T m(scalar_traits<T>::value(0));\n  for (int i = 0; i != vec_traits<A>::dim; ++i) {\n    T x = vec_traits<A>::read_element_idx(i, a);\n    m += x * x;\n  }\n  return sqrt<T>(m);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct minus_eq_vv_defined {\n  static bool const value = false;\n};\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<\n    is_vec<A>::value && is_vec<B>::value &&\n        vec_traits<A>::dim == vec_traits<B>::dim &&\n        !qvm_detail::minus_eq_vv_defined<vec_traits<A>::dim>::value,\n    A &>::type\noperator-=(A &a, B const &b) {\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<A>::write_element_idx(i, a) -=\n        vec_traits<B>::read_element_idx(i, b);\n  return a;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct minus_v_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_vec<A>::value && !qvm_detail::minus_v_defined<vec_traits<A>::dim>::value,\n    deduce_vec<A>>::type\noperator-(A const &a) {\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<R>::write_element_idx(i, r) =\n        -vec_traits<A>::read_element_idx(i, a);\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct minus_vv_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_vec<A>::value && is_vec<B>::value &&\n        vec_traits<A>::dim == vec_traits<B>::dim &&\n        !qvm_detail::minus_vv_defined<vec_traits<A>::dim>::value,\n    deduce_vec2<A, B, vec_traits<A>::dim>>::type\noperator-(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, vec_traits<A>::dim>::type R;\n  R r;\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<R>::write_element_idx(i, r) =\n        vec_traits<A>::read_element_idx(i, a) -\n        vec_traits<B>::read_element_idx(i, b);\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct mul_eq_vs_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<\n    is_vec<A>::value && is_scalar<B>::value &&\n        !qvm_detail::mul_eq_vs_defined<vec_traits<A>::dim>::value,\n    A &>::type\noperator*=(A &a, B b) {\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<A>::write_element_idx(i, a) *= b;\n  return a;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct mul_vs_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_vec<A>::value && is_scalar<B>::value &&\n        !qvm_detail::mul_vs_defined<vec_traits<A>::dim>::value,\n    deduce_vec<A>>::type\noperator*(A const &a, B b) {\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<R>::write_element_idx(i, r) =\n        vec_traits<A>::read_element_idx(i, a) * b;\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct mul_sv_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_scalar<A>::value && is_vec<B>::value &&\n        !qvm_detail::mul_sv_defined<vec_traits<B>::dim>::value,\n    deduce_vec<B>>::type\noperator*(A a, B const &b) {\n  typedef typename deduce_vec<B>::type R;\n  R r;\n  for (int i = 0; i != vec_traits<B>::dim; ++i)\n    vec_traits<R>::write_element_idx(i, r) =\n        a * vec_traits<B>::read_element_idx(i, b);\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct neq_vv_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<\n    is_vec<A>::value && is_vec<B>::value &&\n        vec_traits<A>::dim == vec_traits<B>::dim &&\n        !qvm_detail::neq_vv_defined<vec_traits<A>::dim>::value,\n    bool>::type\noperator!=(A const &a, B const &b) {\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    if (vec_traits<A>::read_element_idx(i, a) !=\n        vec_traits<B>::read_element_idx(i, b))\n      return true;\n  return false;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct normalize_v_defined {\n  static bool const value = false;\n};\n} // namespace qvm_detail\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_vec<A>::value &&\n        !qvm_detail::normalize_v_defined<vec_traits<A>::dim>::value,\n    deduce_vec<A>>::type\nnormalized(A const &a) {\n  typedef typename vec_traits<A>::scalar_type T;\n  T m(scalar_traits<T>::value(0));\n  for (int i = 0; i != vec_traits<A>::dim; ++i) {\n    T x = vec_traits<A>::read_element_idx(i, a);\n    m += x * x;\n  }\n  if (m == scalar_traits<T>::value(0))\n    BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n  T rm = scalar_traits<T>::value(1) / sqrt<T>(m);\n  typedef typename deduce_vec<A>::type R;\n  R r;\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<R>::write_element_idx(i, r) =\n        vec_traits<A>::read_element_idx(i, a) * rm;\n  return r;\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_vec<A>::value && !qvm_detail::normalize_v_defined<\n                                                 vec_traits<A>::dim>::value,\n                         void>::type\n    normalize(A &a) {\n  typedef typename vec_traits<A>::scalar_type T;\n  T m(scalar_traits<T>::value(0));\n  for (int i = 0; i != vec_traits<A>::dim; ++i) {\n    T x = vec_traits<A>::read_element_idx(i, a);\n    m += x * x;\n  }\n  if (m == scalar_traits<T>::value(0))\n    BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n  T rm = scalar_traits<T>::value(1) / sqrt<T>(m);\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<A>::write_element_idx(i, a) *= rm;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct plus_eq_vv_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<\n    is_vec<A>::value && is_vec<B>::value &&\n        vec_traits<A>::dim == vec_traits<B>::dim &&\n        !qvm_detail::plus_eq_vv_defined<vec_traits<A>::dim>::value,\n    A &>::type\noperator+=(A &a, B const &b) {\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<A>::write_element_idx(i, a) +=\n        vec_traits<B>::read_element_idx(i, b);\n  return a;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int D> struct plus_vv_defined { static bool const value = false; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_vec<A>::value && is_vec<B>::value &&\n        vec_traits<A>::dim == vec_traits<B>::dim &&\n        !qvm_detail::plus_vv_defined<vec_traits<A>::dim>::value,\n    deduce_vec2<A, B, vec_traits<A>::dim>>::type\noperator+(A const &a, B const &b) {\n  typedef typename deduce_vec2<A, B, vec_traits<A>::dim>::type R;\n  R r;\n  for (int i = 0; i != vec_traits<A>::dim; ++i)\n    vec_traits<R>::write_element_idx(i, r) =\n        vec_traits<A>::read_element_idx(i, a) +\n        vec_traits<B>::read_element_idx(i, b);\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T> class vref_ {\n  vref_(vref_ const &);\n  vref_ &operator=(vref_ const &);\n  ~vref_();\n\npublic:\n  template <class R> BOOST_QVM_INLINE_TRIVIAL vref_ &operator=(R const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class V> struct vec_traits<qvm_detail::vref_<V>> {\n  typedef typename vec_traits<V>::scalar_type scalar_type;\n  typedef qvm_detail::vref_<V> this_vector;\n  static int const dim = vec_traits<V>::dim;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_vector const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return vec_traits<V>::template read_element<I>(\n        reinterpret_cast<V const &>(x));\n  }\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_vector &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return vec_traits<V>::template write_element<I>(reinterpret_cast<V &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_vector const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return vec_traits<V>::read_element_idx(i, reinterpret_cast<V const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int i, this_vector &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return vec_traits<V>::write_element_idx(i, reinterpret_cast<V &>(x));\n  }\n};\n\ntemplate <class V, int D> struct deduce_vec<qvm_detail::vref_<V>, D> {\n  typedef vec<typename vec_traits<V>::scalar_type, D> type;\n};\n\ntemplate <class V>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_vec<V>::value, qvm_detail::vref_<V> const &>::type\n    vref(V const &a) {\n  return reinterpret_cast<qvm_detail::vref_<V> const &>(a);\n}\n\ntemplate <class V>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_vec<V>::value, qvm_detail::vref_<V> &>::type\n    vref(V &a) {\n  return reinterpret_cast<qvm_detail::vref_<V> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace sfinae {\nusing ::boost::qvm::assign;\nusing ::boost::qvm::cmp;\nusing ::boost::qvm::convert_to;\nusing ::boost::qvm::cross;\nusing ::boost::qvm::scalar_cast;\nusing ::boost::qvm::set_zero;\nusing ::boost::qvm::to_string;\nusing ::boost::qvm::operator/=;\nusing ::boost::qvm::operator/;\nusing ::boost::qvm::dot;\nusing ::boost::qvm::operator==;\nusing ::boost::qvm::mag;\nusing ::boost::qvm::mag_sqr;\nusing ::boost::qvm::operator-=;\nusing ::boost::qvm::operator-;\nusing ::boost::qvm::operator*=;\nusing ::boost::qvm::operator*;\nusing ::boost::qvm::operator!=;\nusing ::boost::qvm::normalize;\nusing ::boost::qvm::normalized;\nusing ::boost::qvm::operator+=;\nusing ::boost::qvm::operator+;\nusing ::boost::qvm::vref;\n} // namespace sfinae\n\n////////////////////////////////////////////////\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "c58669f89e3ab95f6c001288589aa8ac071e85b1", "size": 22648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/vec_operations.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/vec_operations.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/vec_operations.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": 31.4555555556, "max_line_length": 80, "alphanum_fraction": 0.6360385023, "num_tokens": 6026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.03021458968716716, "lm_q1q2_score": 0.011629962511189654}}
{"text": "/**\t\\file LatLongConversions.cpp\n*\t\\brief \n*/\n\n/****************************************************************************/\n/*\tLatLongConversions.cpp\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n/****************************************************************************/\n/*                                                                          */\n/*  Copyright 2008 - 2010 Paul Kohut                                        */\n/*  Licensed under the Apache License, Version 2.0 (the \"License\"); you may */\n/*  not use this file except in compliance with the License. You may obtain */\n/*  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\n//#include \"stdafx.h\"\n#include <boost/regex.hpp>\n#include \"LatLongConversions.h\"\n#include \"..\\GeoFormulas\\Conversions.h\"\n\nusing namespace boost;\nusing namespace std;\n\nvoid TrimWhitespace(string & szString)\n{\n\tregex pat(\"^[ \\t]+|[ \\t]+$\");\n\tszString = regex_replace(szString, pat, \"\");\n}\n\ndouble ParseLatitude( string szDeg )\n{\t\n\tregex_constants::syntax_option_type flags =  regex_constants::icase | regex_constants::perl;\n\tTrimWhitespace(szDeg);\n\tstring sPattern = \"[+-]|[sn]\";\n\tsmatch what;\n\tregex pat(sPattern, flags);\n\tif(!regex_search(szDeg, what, pat))\n\t{\n\t\t// did not find pattern so assume value is positive and North\n\t\t// and stuff 'N' at the beginning of the string\n\t\tszDeg = \"N\" + szDeg;\n\t\tregex_search(szDeg, what, pat);\n\t}\n\t\n\t// Replace all '+' 'n' and 'N' with 'N'\n\tpat.assign(\"[+N]\", flags);\n\tszDeg = regex_replace(szDeg, pat, \"N\");\n\n\t// Replace all '-' 's' and 'S' with 'S'\n\tpat.assign(\"[-S]\", flags);\n\tszDeg = regex_replace(szDeg, pat, \"S\");\n\n\t// determine if pattern above was found at the beginning or\n\t// end of the string.  If found at the end the swap it to the\n\t// beginning.\n\tsize_t pos = what.position();\n\tif(pos == szDeg.length() - 1)\n\t{\n\t\tszDeg = szDeg[pos] + szDeg.substr(0, pos);\n\t}\n\n\t// String has been normalized continue on with the parsing\n\treturn ParseLatitudeBegin(szDeg);\n}\n\n\ndouble ParseLatitudeBegin(string & sString)\n{\n\tregex_constants::syntax_option_type flags =  regex_constants::icase | regex_constants::perl;\n\tstring sPattern = \"[:. ]\";\n\n\tregex pat(sPattern, flags);\n\tsmatch matchResults;\n\tsString = regex_replace(sString, pat, \" \");\n\tpat.assign(\" \", flags);\n\n//\tif(!regex_match(sString, matchResults, pat))\n//\t\tthrow CRNavConversionException(\"regex match not found\");\n\n\t// Split the string into it's sub string tokens based on sPattern below.\n\t// Define the sub string match patterns that will be valid for the iterator\n\t// Note: If sPattern is changed then make sure the sub_matches are changed\n\t// accordingly too.\n\n\tint const sub_matches[] = {1, 2, 3, 4, 5, 6 };\n\tsPattern = \"([NS])(\\\\d+)[ ](\\\\d+)[ ](\\\\d+)[ ](\\\\d+)\";\n\tpat.assign(sPattern, flags);\n\tsregex_token_iterator it(sString.begin(), sString.end(), pat, sub_matches);\n\tif(it == sregex_token_iterator())\n\t{\n\t\tsPattern = \"([NS])(\\\\d+)[ ](\\\\d+)[ ](\\\\d+)()\";\n\t\tpat.assign(sPattern, flags);\n\t\tit = sregex_token_iterator(sString.begin(), sString.end(), pat, sub_matches);\n\t\tif(it == sregex_token_iterator())\n\t\t{\n\t\t\tsPattern = \"([NS])(\\\\d+)[ ](\\\\d+)()()\";\n\t\t\tpat.assign(sPattern, flags);\n\t\t\tit = sregex_token_iterator(sString.begin(), sString.end(), pat, sub_matches);\n\t\t\tif(it == sregex_token_iterator())\n\t\t\t{\n\t\t\t\tsPattern = \"([NS])(\\\\d+)()()()\";\n\t\t\t\tpat.assign(sPattern, flags);\n\t\t\t\tit = sregex_token_iterator(sString.begin(), sString.end(), pat, sub_matches);\n\t\t\t\tif(it == sregex_token_iterator())\n\t\t\t\t\tthrow CRNavConversionException(\"Value out of range, are you passing an angle greater than 90 degrees?\");\n\t\t\t}\t\t\t\n\t\t}\n\t}\n\n\t// Get each piece of the substring to build the final string that\n\t// can be converted to decimal\n\tstring sneg, sdeg, smin, ssec;\n\t// Make sure we convert 'S' and '-' to '-'\n\t// Don't need to do this if 'N' or '+'\n\tif((*it).str().compare(\"S\") == 0 || (*it).str().compare(\"s\") == 0 || (*it).str().compare(\"-\") == 0)\n\t\tsneg += \"-\";\n\n\tit++;\n\n\tsdeg = *it++;\n\tsmin = *it++;\n\tssec = *it++;\n//\tssec += \".\" + *it++;\n\tdouble dDeg = atof(sdeg.c_str());\n\tdouble dMin = atof(smin.c_str());\n\tdouble dSec = atof(ssec.c_str());\n//\tif(dDeg > 90.0 || dMin > 59.0 || dSec > 59.0)\n//\t\tthrow(CRNavConversionException(\"Degrees > 90 or Minutes > 59 or Seconds > 59\"));\n\n\tssec += \".\" + *it++;\n\tdSec = atof(ssec.c_str());\n\n\tdouble dVal;\n\tif(sneg[0] == '-')\n\t\tdVal = ConvertDmsToDd(-dDeg, dMin, dSec);\n\telse\n\t\tdVal = ConvertDmsToDd(dDeg, dMin, dSec);\n\tif(dVal > 90.0 || dVal < -90.0)\n\t\tthrow(CRNavConversionException(\"Latitude > 90.0 or < -90.0\"));\n\treturn dVal;\n}\n\n\ndouble ParseLongitude( string szDeg )\n{\t\n\tregex_constants::syntax_option_type flags =  regex_constants::icase | regex_constants::perl;\n\tTrimWhitespace(szDeg);\n\tstring sPattern = \"[+-]|[ew]\";\n\tsmatch what;\n\tregex pat(sPattern, flags);\n\tif(!regex_search(szDeg, what, pat))\n\t{\n\t\t// did not find pattern so assume value is positive and North\n\t\t// and stuff 'N' at the beginning of the string\n\t\tszDeg = \"E\" + szDeg;\n\t\tregex_search(szDeg, what, pat);\n\t}\n\n\t// Replace all '+' 'n' and 'N' with 'N'\n\tpat.assign(\"[+E]\", flags);\n\tszDeg = regex_replace(szDeg, pat, \"E\");\n\n\t// Replace all '-' 's' and 'S' with 'S'\n\tpat.assign(\"[-W]\", flags);\n\tszDeg = regex_replace(szDeg, pat, \"W\");\n\n\t// determine if pattern above was found at the beginning or\n\t// end of the string.  If found at the end the swap it to the\n\t// beginning.\n\tsize_t pos = what.position();\n\tif(pos == szDeg.length() - 1)\n\t{\n\t\tszDeg = szDeg[pos] + szDeg.substr(0, pos);\n\t}\n\n\t// String has been normalized continue on with the parsing\n\treturn ParseLongitudeBegin(szDeg);\n}\n\n\ndouble ParseLongitudeBegin(string & sString)\n{\n\tregex_constants::syntax_option_type flags =  regex_constants::icase | regex_constants::perl;\n\tstring sPattern = \"[:. ]\";\n\n\tregex pat(sPattern, flags);\n\tsmatch matchResults;\n\tsString = regex_replace(sString, pat, \" \");\n\tpat.assign(\" \", flags);\n\n\t//\tif(!regex_match(sString, matchResults, pat))\n\t//\t\tthrow CRNavConversionException(\"regex match not found\");\n\n\t// Split the string into it's sub string tokens based on sPattern below.\n\t// Define the sub string match patterns that will be valid for the iterator\n\t// Note: If sPattern is changed then make sure the sub_matches are changed\n\t// accordingly too.\n\n\tint const sub_matches[] = {1, 2, 3, 4, 5, 6 };\n\tsPattern = \"([EW])(\\\\d+)[ ](\\\\d+)[ ](\\\\d+)[ ](\\\\d+)\";\n\tpat.assign(sPattern, flags);\n\tsregex_token_iterator it(sString.begin(), sString.end(), pat, sub_matches);\n\tif(it == sregex_token_iterator())\n\t{\n\t\tsPattern = \"([EW])(\\\\d+)[ ](\\\\d+)[ ](\\\\d+)()\";\n\t\tpat.assign(sPattern, flags);\n\t\tit = sregex_token_iterator(sString.begin(), sString.end(), pat, sub_matches);\n\t\tif(it == sregex_token_iterator())\n\t\t{\n\t\t\tsPattern = \"([EW])(\\\\d+)[ ](\\\\d+)()()\";\n\t\t\tpat.assign(sPattern, flags);\n\t\t\tit = sregex_token_iterator(sString.begin(), sString.end(), pat, sub_matches);\n\t\t\tif(it == sregex_token_iterator())\n\t\t\t{\n\t\t\t\tsPattern = \"([EW])(\\\\d+)()()()\";\n\t\t\t\tpat.assign(sPattern, flags);\n\t\t\t\tit = sregex_token_iterator(sString.begin(), sString.end(), pat, sub_matches);\n\t\t\t\tif(it == sregex_token_iterator())\n\t\t\t\t\tthrow CRNavConversionException(\"Value out of range, are you passing an angle greater than 180 degrees?\");\n\t\t\t}\t\t\t\n\t\t}\n\t}\n\n\t// Get each piece of the substring to build the final string that\n\t// can be converted to decimal\n\tstring sneg, sdeg, smin, ssec;\n\t// Make sure we convert 'W' and '-' to '-'\n\t// Don't need to do this if 'E' or '+'\n\tif((*it).str().compare(\"W\") == 0 || (*it).str().compare(\"w\") == 0 || (*it).str().compare(\"-\") == 0)\n\t\tsneg += \"-\";\n\n\tit++;\n\n\tsdeg = *it++;\n\tsmin = *it++;\n\tssec = *it++;\n\t//\tssec += \".\" + *it++;\n\tdouble dDeg = atof(sdeg.c_str());\n\tdouble dMin = atof(smin.c_str());\n\tdouble dSec = atof(ssec.c_str());\n//\tif(dDeg > 180.0 || dMin > 59.0 || dSec > 59.0)\n//\t\tthrow(CRNavConversionException(\"Degrees > 180 or Minutes > 59 or Seconds > 59\"));\n\n\tssec += \".\" + *it++;\n\tdSec = atof(ssec.c_str());\n\n\tdouble dVal;\n\tif(sneg[0] == '-')\n\t\tdVal = ConvertDmsToDd(-dDeg, dMin, dSec);\n\telse\n\t\tdVal = ConvertDmsToDd(dDeg, dMin, dSec);\n\tif(dVal > 180.0 || dVal < -180.0)\n\t\tthrow(CRNavConversionException(\"Longitude > 180.0 or < -180.0\"));\n\treturn dVal;\n}\n\n\n\n// Pad0 will pad to the beginning of the string as many\n// '0' as needed until the length of szOrg is = nMinDigits\nstring Pad0(string szOrg, size_t nMinDigits)\n{\n\tfor(size_t pos = szOrg.length(); pos < nMinDigits; pos++)\n\t{\n\t\tszOrg = \"0\" + szOrg;\n\t}\n\treturn szOrg;\n}\n\ndouble ConvertDmsToDd(double const & dDeg, double const & dMin, double const & dSec)\n{\n//\tif(sign < 0)\n//\t\treturn -dDeg - ((dMin + (dSec / 60.0)) / 60.0);\n//\treturn dDeg + ((dMin + (dSec / 60.0)) / 60.0);\n\tint bSignBit = false;\n\tif(dDeg == 0)\n\t{\n\t\tunsigned long * pVal = (unsigned long*) &dDeg;\n\t\tbSignBit = *(++pVal) & 1 << 31;\n\t}\n\n\tif(dDeg < 0 || bSignBit)\n\t\treturn (-(fabs(dDeg)+ (dMin / 60.0) + (dSec / 3600.0)));\n\treturn (dDeg + (dMin / 60.0) + (dSec / 3600.0));\n}\n\ndouble ConvertDmsToDd(string const & sDeg, string const & sMin, string const & sSec)\n{\t\n\tdouble dNeg = atof(sDeg.c_str());\n\tdouble dDeg = fabs(dNeg);\n\tdouble dMin = atof(sMin.c_str());\n\tdouble dSec = atof(sSec.c_str());\n\tif(dNeg < 0.0)\n\t\treturn ConvertDmsToDd(-dDeg, dMin, dSec);\n\treturn ConvertDmsToDd(dDeg, dMin, dSec);\n}\n\nstring ConvertDdToDms(double const & dDeg)\n{\n\tchar szBuffer[25];\n\tint nDegrees = (int) dDeg;\n\tdouble dMinutes = (dDeg - nDegrees) * 60;\n\tdouble nSeconds = (dMinutes - (int) dMinutes) * 60;\n\tsprintf(szBuffer, \"%d:%02d:%08.5f\", nDegrees, (int) fabs(dMinutes), fabs(nSeconds));\n\treturn string(szBuffer);\t\n}\n\nstring ConvertLatitudeDdToDms(double const & dDeg)\n{\n\tbool bIsNeg = dDeg < 0.0;\n\tdouble dVal = fabs(dDeg);\n\tif(dVal > 90.0)\n\t\tdVal = 180.0 - dVal;\n\treturn (ConvertDdToDms(dVal) + (bIsNeg  ? \"S\" : \"N\"));\n}\n\nstring ConvertLongitudeDdToDms(double const & dDeg)\n{\n\tbool bIsNeg = dDeg < 0.0;\n\tdouble dVal = fabs(dDeg);\n\tif(dVal > 180.0)\n\t{\n\t\tdVal = 360.0 - dVal;\n\t\tbIsNeg = !bIsNeg;\n\t}\n\treturn (ConvertDdToDms(dVal) + (bIsNeg  ? \"W\" : \"E\"));\n}", "meta": {"hexsha": "b22d8963ea58c7dcf3c522eb1c2b9963f0e1488f", "size": 10697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TerpsTest/LatLongConversions.cpp", "max_stars_repo_name": "buffetboy2001/GeoFormulas", "max_stars_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "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": "TerpsTest/LatLongConversions.cpp", "max_issues_repo_name": "buffetboy2001/GeoFormulas", "max_issues_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TerpsTest/LatLongConversions.cpp", "max_forks_repo_name": "buffetboy2001/GeoFormulas", "max_forks_repo_head_hexsha": "d439b8941a84965d12078fad80307bc66444e46b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9313432836, "max_line_length": 110, "alphanum_fraction": 0.6006356923, "num_tokens": 3118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.028007518780537123, "lm_q1q2_score": 0.011620287620930751}}
{"text": "#include <math.h>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <io.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <sys/types.h>\n//#include <dirent.h>\n#include <boost/lexical_cast.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"caffe/blob.hpp\"\n#include \"caffe/filler.hpp\"\n#include \"caffe/layers/DenseBlock_layer.hpp\"\n\nnamespace caffe {\n\n  bool dirExists(string dirStr){\n    const char* dirCStr = dirStr.c_str();\n\treturn !_access(dirCStr, 0);\n    /*DIR* dir = opendir(dirCStr);\n    if (ENOENT == errno){\n      return false;\n    }\n    closedir(dir);\n    return true;*/\n  }\n\n  void tryCreateDirectory(string fileName){\n    vector<string> strVec;\n    boost::split(strVec,fileName,boost::is_any_of(\"/\"));\n    string newStr=\"\";\n    for (int i=0;i<strVec.size()-1;++i){\n      newStr += strVec[i] + (i==strVec.size()-2?\"\":\"/\");\n    }\n    boost::filesystem::path dirToCreate(newStr);\n    if (!dirExists(newStr)){\n      boost::filesystem::create_directories(dirToCreate);\n    }\n  }\n\n  template <typename Dtype>\n  void DenseBlockLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top){\n\tthis->cpuInited = false;\n\tthis->gpuInited = false;\n\tDenseBlockParameter dbParam = this->layer_param_.denseblock_param();\n        this->numTransition = dbParam.numtransition();\n        this->initChannel = dbParam.initchannel();\n        this->growthRate = dbParam.growthrate();\n        this->trainCycleIdx = 0; //initially, trainCycleIdx = 0\n        this->workspace_size_bytes = dbParam.workspace_mb()*1024*1024;\n\tthis->EMA_decay = dbParam.moving_average_fraction();\n        this->gpu_idx_ = dbParam.gpuidx();\n        this->useDropout = dbParam.use_dropout();\n\tthis->dropoutAmount = dbParam.dropout_amount();\n\tthis->DB_randomSeed = 124816;\n        this->useBC = dbParam.use_bc();\n        this->BC_ultra_spaceEfficient = dbParam.bc_ultra_space_efficient();\n        //Parameter Blobs\n\t//for transition i, \n\t//blobs_[i] is its filter blob\n\t//blobs_[numTransition + i] is its scaler blob\n\t//blobs_[2*numTransition + i] is its bias blob\n\t//blobs_[3*numTransition + i] is its globalMean\n\t//blobs_[4*numTransition + i] is its globalVar\n\tif (useBC){\n          this->blobs_.resize(10*this->numTransition + 1);\n\t}\n\telse {\n          this->blobs_.resize(5*this->numTransition + 1);\n\t}\n\tfor (int transitionIdx=0;transitionIdx < this->numTransition;++transitionIdx){\n\t    //filter\n\t    //No BC case\n\t    if (!useBC){\n\t      int inChannels = initChannel + transitionIdx * growthRate;\n\t      int filterShape_Arr[] = {growthRate,inChannels,3,3};\n\t      vector<int> filterShape (filterShape_Arr,filterShape_Arr+4);\n\t      this->blobs_[transitionIdx].reset(new Blob<Dtype>(filterShape));\n\t      shared_ptr<Filler<Dtype> > filter_Filler(GetFiller<Dtype>(dbParam.filter_filler()));\n\t      filter_Filler->Fill(this->blobs_[transitionIdx].get()); \n\t    }\n\t    else {\n\t      //3*3 kernel\n\t      int filter_33_shapeArr[] = {growthRate,4*growthRate,3,3};\n\t      vector<int> filter33Shape (filter_33_shapeArr,filter_33_shapeArr+4);\n\t      this->blobs_[transitionIdx].reset(new Blob<Dtype>(filter33Shape));\n\t      shared_ptr<Filler<Dtype> > filter_Filler3(GetFiller<Dtype>(dbParam.filter_filler()));\n\t      filter_Filler3->Fill(this->blobs_[transitionIdx].get());\n\t     \n\t      //1*1 kernel\n\t      int inChannels = initChannel + transitionIdx * growthRate;\n\t      int filter_11_shapeArr[] = {4*growthRate,inChannels,1,1};\n\t      vector<int> filter11Shape (filter_11_shapeArr,filter_11_shapeArr+4);\n              this->blobs_[5*numTransition+transitionIdx].reset(new Blob<Dtype>(filter11Shape));\n\t      shared_ptr<Filler<Dtype> > filter_Filler1(GetFiller<Dtype>(dbParam.filter_filler()));\n\t      filter_Filler1->Fill(this->blobs_[5*numTransition+transitionIdx].get()); \n\t    }\n\t    //scaler & bias\n\t    int inChannels = initChannel + transitionIdx * growthRate; \n\t    int BNparamShape_Arr [] = {1,inChannels,1,1};\n\t    vector<int> BNparamShape (BNparamShape_Arr,BNparamShape_Arr+4);\n\t    //scaler\n\t    this->blobs_[numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t    shared_ptr<Filler<Dtype> > weight_filler0(GetFiller<Dtype>(dbParam.bn_scaler_filler()));\n\t    weight_filler0->Fill(this->blobs_[numTransition+transitionIdx].get());\n            \n\t    int BN_4G_Shape[] = {1,4*growthRate,1,1};\n            vector<int> BN_4Gparam_ShapeVec (BN_4G_Shape,BN_4G_Shape+4);\n\t    //scaler BC\n            if (useBC){\n              this->blobs_[6*numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t      shared_ptr<Filler<Dtype> > weight_filler0_4G(GetFiller<Dtype>(dbParam.bn_scaler_filler()));\n              weight_filler0_4G->Fill(this->blobs_[6*numTransition+transitionIdx].get());\n\t    }\n\t    //bias\n\t    this->blobs_[2*numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t    shared_ptr<Filler<Dtype> > weight_filler1(GetFiller<Dtype>(dbParam.bn_bias_filler()));\n\t    weight_filler1->Fill(this->blobs_[2*numTransition+transitionIdx].get());\n\t    //bias BC\n\t    if (useBC){\n              this->blobs_[7*numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t      shared_ptr<Filler<Dtype> > weight_filler1_4G(GetFiller<Dtype>(dbParam.bn_bias_filler()));\n\t      weight_filler1_4G->Fill(this->blobs_[7*numTransition+transitionIdx].get()); \n\t    }\n\t    //globalMean\n\t    this->blobs_[3*numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t    for (int blobIdx=0;blobIdx<inChannels;++blobIdx){\n\t      shared_ptr<Blob<Dtype> > localB = this->blobs_[3*numTransition+transitionIdx];\n\t      localB->mutable_cpu_data()[localB->offset(0,blobIdx,0,0)] = 0;\n\t    }\n\t    //globalMean BC\n\t    if (useBC){\n\t      this->blobs_[8*numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t      shared_ptr<Blob<Dtype> > localB = this->blobs_[8*numTransition+transitionIdx]; \n\t      for (int blobIdx=0;blobIdx<4*growthRate;++blobIdx){\n\t\tlocalB->mutable_cpu_data()[localB->offset(0,blobIdx,0,0)] = 0;\n\t      }\n\t    }\n\t    //globalVar\n\t    this->blobs_[4*numTransition + transitionIdx].reset(new Blob<Dtype>(BNparamShape));\n\t    for (int blobIdx=0;blobIdx<inChannels;++blobIdx){\n\t      shared_ptr<Blob<Dtype> > localB = this->blobs_[4*numTransition+transitionIdx];\n\t      localB->mutable_cpu_data()[localB->offset(0,blobIdx,0,0)] = 1;\n\t    } \n\t    //globalVar BC\n\t    if (useBC){\n              this->blobs_[9*numTransition + transitionIdx].reset(new Blob<Dtype>(BN_4Gparam_ShapeVec));\n\t      shared_ptr<Blob<Dtype> > localB = this->blobs_[9*numTransition+transitionIdx]; \n\t      for (int blobIdx=0;blobIdx<4*growthRate;++blobIdx){\n\t\tlocalB->mutable_cpu_data()[localB->offset(0,blobIdx,0,0)] = 1;\n\t      }\n\t    }\n\t}\n     //final parameter for the equivalent of blobs_[2] in Caffe-BN\n     vector<int> singletonShapeVec;\n     singletonShapeVec.push_back(1);\n     int singletonIdx = useBC?10*numTransition:5*numTransition;\n     this->blobs_[singletonIdx].reset(new Blob<Dtype>(singletonShapeVec));\n     this->blobs_[singletonIdx]->mutable_cpu_data()[0] = Dtype(0);\n     //parameter specification: globalMean/Var weight decay and lr is 0\n     if (!useBC){\n       for (int i=0;i<this->blobs_.size();++i){\n         if (this->layer_param_.param_size()!=i){\n           CHECK_EQ(0, 1)\n             << \"Nope\";\n         }\n         ParamSpec* fixed_param_spec = this->layer_param_.add_param();  \n         //global Mean/Var\n         if (i>=3*this->numTransition){\n           fixed_param_spec->set_lr_mult(0.f);\n           fixed_param_spec->set_decay_mult(0.f);\n         }\n         //BN Scaler and Bias\n         else if (i>=this->numTransition){\n           fixed_param_spec->set_lr_mult(1.f);\n           fixed_param_spec->set_decay_mult(1.f);\n         }\n         else {\n           fixed_param_spec->set_lr_mult(1.f);\n\t   fixed_param_spec->set_decay_mult(1.f);\n         }\n       }\n    }\n    else {\n      for (int i=0;i<this->blobs_.size();++i){\n         if (this->layer_param_.param_size()!=i){\n           CHECK_EQ(0, 1)\n             << \"Nope\";\n         }\n         ParamSpec* fixed_param_spec = this->layer_param_.add_param();  \n         if ((i>=3*numTransition)&&(i<5*numTransition)){\n           fixed_param_spec->set_lr_mult(0.f);\n           fixed_param_spec->set_decay_mult(0.f);\n\t }\n\t else if (i>=8*numTransition){\n\t   fixed_param_spec->set_lr_mult(0.f);\n           fixed_param_spec->set_decay_mult(0.f);\n\t }\n\t else {\n           fixed_param_spec->set_lr_mult(1.f);\n           fixed_param_spec->set_decay_mult(1.f);\n\t } \n      }\n    }\n}\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top){ \n        this->N = bottom[0]->shape()[0]; \n        this->H = bottom[0]->shape()[2];\n        this->W = bottom[0]->shape()[3];\n\tint topShapeArr[] = {this->N,this->initChannel+this->numTransition*this->growthRate,this->H,this->W};\n\tvector<int> topShape(topShapeArr,topShapeArr+4);\n\ttop[0]->Reshape(topShape);\n}\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::syncBlobs(DenseBlockLayer<Dtype>* originLayer){\n    vector<shared_ptr<Blob<Dtype> > >& originBlobs = originLayer->blobs();\n    for (int blobIdx=0;blobIdx < originBlobs.size();++blobIdx){\n      shared_ptr<Blob<Dtype> > localBlob = originBlobs[blobIdx];\n      Blob<Dtype> * newBlob = new Blob<Dtype>(localBlob->shape());\n      newBlob->CopyFrom(*(localBlob.get()),false);\n      shared_ptr<Blob<Dtype> > sharedPtrBlob(newBlob);\n      this->blobs_[blobIdx] = sharedPtrBlob;\n    }\n}\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::setLogId(int uid){\n    this->logId = uid;\n}\n\ntemplate <typename Dtype>\nvoid logBlob(Blob<Dtype>* B,string fileName){\n    string dataNameStr = fileName + \"_data\";\n    string gradNameStr = fileName + \"_grad\";\n    const char* dataName = (dataNameStr).c_str();\n    const char* gradName = (gradNameStr).c_str();\n    \n    tryCreateDirectory(dataName);\n    tryCreateDirectory(gradName);\n    std::ofstream outWriter_data(dataName,std::ofstream::out);\n    std::ofstream outWriter_grad(gradName,std::ofstream::out); \n    for (int n=0;n<B->shape(0);++n){\n      for (int c=0;c<B->shape(1);++c){\n        for (int h=0;h<B->shape(2);++h){\n\t  for (int w=0;w<B->shape(3);++w){\n\t    outWriter_data<<B->data_at(n,c,h,w)<<\",\";\n\t    outWriter_grad<<B->diff_at(n,c,h,w)<<\",\";\n\t  }\n\t}\n      }\n    }\n    outWriter_data<<std::endl;\n    outWriter_grad<<std::endl;\n}\n\nstring itos(int i){\n  string output = boost::lexical_cast<string>(i);\n  return output;  \n}\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::logInternal_cpu(string dir){\n    string localDir = dir+\"/cpu_\"+itos(this->logId)+\"/\"; \n    //batch_Mean\n    for (int i=0;i<this->batch_Mean.size();++i){\n      string blobStr = localDir+\"batch_Mean_\"+itos(i);\n      logBlob(this->batch_Mean[i],blobStr);\n    }\n    //batch_Var\n    for (int i=0;i<this->batch_Var.size();++i){\n      string blobStr = localDir+\"batch_Var_\"+itos(i);\n      logBlob(this->batch_Var[i],blobStr);\n    }\n    if (useBC){\n      //batch_Mean\n      for (int i=0;i<this->batch_Mean4G.size();++i){\n        string blobStr = localDir+\"batch_Mean_BC_\"+itos(i);\n        logBlob(this->batch_Mean4G[i],blobStr);\n      }\n      //batch_Var\n      for (int i=0;i<this->batch_Var4G.size();++i){\n        string blobStr = localDir+\"batch_Var_BC_\"+itos(i);\n        logBlob(this->batch_Var4G[i],blobStr);\n      }\n    }\n    //merged_conv\n    for (int i=0;i<this->merged_conv.size();++i){\n      string blobStr = localDir+\"merged_conv_\"+itos(i);\n      logBlob(this->merged_conv[i],blobStr);\n    }\n    //BN_XhatVec\n    for (int i=0;i<this->BN_XhatVec.size();++i){\n      string blobStr = localDir+\"BN_XhatVec_\"+itos(i);\n      logBlob(this->BN_XhatVec[i],blobStr);\n    }\n    //postBN_blobVec\n    for (int i=0;i<this->postBN_blobVec.size();++i){\n      string blobStr = localDir+\"postBN_blobVec_\"+itos(i);\n      logBlob(this->postBN_blobVec[i],blobStr);\n    }\n    //postReLU_blobVec\n    for (int i=0;i<this->postReLU_blobVec.size();++i){\n      string blobStr = localDir+\"postReLU_blobVec_\"+itos(i);\n      logBlob(this->postReLU_blobVec[i],blobStr);\n    }\n    //postConv_blobVec\n    for (int i=0;i<this->postConv_blobVec.size();++i){\n      string blobStr = localDir+\"postConv_blobVec_\"+itos(i);\n      logBlob(this->postConv_blobVec[i],blobStr);\n    }\n    if (useBC){\n      //BC_BN_XhatVec\n      for (int i=0;i<this->BC_BN_XhatVec.size();++i){\n\tstring blobStr = localDir+\"BC_BN_XhatVec_\"+itos(i);\n\tlogBlob(this->BC_BN_XhatVec[i],blobStr);\n      }\n      //postBN_BCVec\n      for (int i=0;i<this->postBN_BCVec.size();++i){\n\tstring blobStr = localDir+\"postBN_BCVec_\"+itos(i);\n\tlogBlob(this->postBN_BCVec[i],blobStr);\n      }\n      //postReLU_BCVec\n      for (int i=0;i<this->postReLU_BCVec.size();++i){\n\tstring blobStr = localDir+\"postReLU_BCVec_\"+itos(i);\n        logBlob(this->postReLU_BCVec[i],blobStr);\n      }\n      //postConv_BCVec\n      for (int i=0;i<this->postConv_BCVec.size();++i){\n\tstring blobStr = localDir+\"postConv_BCVec_\"+itos(i);\n        logBlob(this->postConv_BCVec[i],blobStr);\n      }\n    }\n    //filter\n    for (int i=0;i<this->numTransition;++i){\n      string blobStr = localDir+\"filter_\"+itos(i);\n      logBlob(this->blobs_[i].get(),blobStr);\n    }\n    //scaler \n    for (int i=0;i<this->numTransition;++i){\n      string blobStr = localDir+\"scaler_\"+itos(i);\n      logBlob(this->blobs_[this->numTransition+i].get(),blobStr);\n    }\n    //bias\n    for (int i=0;i<this->numTransition;++i){\n      string blobStr = localDir+\"bias_\"+itos(i);\n      logBlob(this->blobs_[this->numTransition*2+i].get(),blobStr);\n    }\n    if (useBC){\n      //filter\n      for (int i=0;i<this->numTransition;++i){\n        string blobStr = localDir+\"filter_BC_\"+itos(i);\n        logBlob(this->blobs_[5*numTransition+i].get(),blobStr);\n      }\n      //scaler \n      for (int i=0;i<this->numTransition;++i){\n        string blobStr = localDir+\"scaler_BC_\"+itos(i);\n        logBlob(this->blobs_[6*numTransition+i].get(),blobStr);\n      }\n      //bias\n      for (int i=0;i<this->numTransition;++i){\n        string blobStr = localDir+\"bias_BC_\"+itos(i);\n        logBlob(this->blobs_[7*numTransition+i].get(),blobStr);\n      }\n      //Mean\n      for (int i=0;i<this->numTransition;++i){\n        string blobStr = localDir+\"Mean_BC_\"+itos(i);\n        logBlob(this->blobs_[8*numTransition+i].get(),blobStr);\n      }\n      //Var\n      for (int i=0;i<this->numTransition;++i){\n        string blobStr = localDir+\"Var_BC_\"+itos(i);\n        logBlob(this->blobs_[9*numTransition+i].get(),blobStr);\n      }\n    }\n}\n\ntemplate <typename Dtype>\nDtype getZeroPaddedValue(bool isDiff,Blob<Dtype>* inputData,int n,int c,int h,int w){\n    int n_blob = inputData->shape(0);\n    int c_blob = inputData->shape(1);\n    int h_blob = inputData->shape(2);\n    int w_blob = inputData->shape(3);\n    if ((n<0) || (n>=n_blob)) return 0;\n    if ((c<0) || (c>=c_blob)) return 0;\n    if ((h<0) || (h>=h_blob)) return 0;\n    if ((w<0) || (w>=w_blob)) return 0;\n    if (isDiff) return inputData->diff_at(n,c,h,w);\n    else return inputData->data_at(n,c,h,w);\n}\n\n//Assumption, h_filter and w_filter must be 3 for now\n//naivest possible implementation of convolution, CPU forward and backward should not be used in production.\n//CPU version of convolution assume img H,W does not change after convolution, which corresponds to denseBlock without BC\n//input of size N*c_input*h_img*w_img\ntemplate <typename Dtype>\nvoid convolution_Fwd(Blob<Dtype>* input, Blob<Dtype>* output, Blob<Dtype>* filter,int N,int c_output,int c_input,int h_img,int w_img,int h_filter,int w_filter){\n    int outputShape[] = {N,c_output,h_img,w_img};\n    vector<int> outputShapeVec (outputShape,outputShape + 4);\n    output->Reshape(outputShapeVec);\n    Dtype * outputPtr = output->mutable_cpu_data();\n    for (int n=0;n<N;++n){\n      for (int c_outIdx=0;c_outIdx<c_output;++c_outIdx){\n        for (int hIdx=0;hIdx<h_img;++hIdx){\n\t  for (int wIdx=0;wIdx<w_img;++wIdx){\n\t    outputPtr[output->offset(n,c_outIdx,hIdx,wIdx)]=0;\n\t    for (int c_inIdx=0;c_inIdx<c_input;++c_inIdx){\n\t      for (int filter_x=0;filter_x<h_filter;++filter_x){\n\t        for (int filter_y=0;filter_y<w_filter;++filter_y){\n\t\t  int localX = hIdx + (h_filter/2) - filter_x;\n\t          int localY = wIdx + (w_filter/2) - filter_y;\n\t          outputPtr[output->offset(n,c_outIdx,hIdx,wIdx)] += (filter->data_at(c_outIdx,c_inIdx,filter_x,filter_y) * getZeroPaddedValue(false,input,n,c_inIdx,localX,localY));\n\t\t}\n\t      } \n\t    }\n\t  }\n\t}\n      }\n    }\n}\n\n//beta = 1 Convolution for bottomDiff\ntemplate <typename Dtype>\nvoid convolution_Bwd(Blob<Dtype>* bottom,Blob<Dtype>* top,Blob<Dtype>* filter,int N,int c_output,int c_input,int h_img,int w_img,int h_filter,int w_filter){\n    Dtype * filterDiffPtr = filter->mutable_cpu_diff();\n    Dtype * bottomDiffPtr = bottom->mutable_cpu_diff();\n    //compute FilterGrad\n    for (int coutIdx=0;coutIdx<c_output;++coutIdx){\n      for (int cinIdx=0;cinIdx<c_input;++cinIdx){\n        for (int filter_x=0;filter_x<h_filter;++filter_x){\n\t  for (int filter_y=0;filter_y<w_filter;++filter_y){\n\t    Dtype localGradSum=0;\n\t    for (int n=0;n<N;++n){\n\t      for (int i_img=0;i_img<h_img;++i_img){\n\t        for (int j_img=0;j_img<w_img;++j_img){\n\t\t  int localX = i_img + (h_filter/2)  - filter_x;\n\t\t  int localY = j_img + (w_filter/2) - filter_y;\n\t\t  localGradSum += top->diff_at(n,coutIdx,i_img,j_img) * getZeroPaddedValue(false,bottom,n,cinIdx,localX,localY);\n\t\t}\n\t      } \n\t    }\n\t    filterDiffPtr[filter->offset(coutIdx,cinIdx,filter_x,filter_y)] = localGradSum;\n\t  }\n\t}\n      }\n    } \n    //compute BottomGrad\n    for (int n=0;n<N;++n){\n      for (int cinIdx=0;cinIdx<c_input;++cinIdx){\n        for (int i_img=0;i_img<h_img;++i_img){\n\t  for (int j_img=0;j_img<w_img;++j_img){\n\t    Dtype localGradSum=0;\n\t    for (int coutIdx=0;coutIdx<c_output;++coutIdx){\n\t      for (int x_img=0;x_img<h_img;++x_img){\n\t        for (int y_img=0;y_img<w_img;++y_img){\n\t\t  int localX = x_img-i_img+(h_filter/2);\n\t\t  int localY = y_img-j_img+(w_filter/2);\n\t\t  localGradSum += top->diff_at(n,coutIdx,x_img,y_img) * getZeroPaddedValue(false,filter,coutIdx,cinIdx,localX,localY); \n\t\t}\n\t      }\n\t    }\n\t    bottomDiffPtr[bottom->offset(n,cinIdx,i_img,j_img)] = localGradSum;\n\t  }\n\t}\n      }\n    } \n}\n\ntemplate <typename Dtype>\nvoid ReLU_Fwd(Blob<Dtype>* bottom,Blob<Dtype>* top,int N,int C,int h_img,int w_img){\n    //Reshape top\n    int topShapeArr[] = {N,C,h_img,w_img};\n    vector<int> topShapeVec(topShapeArr,topShapeArr+4);\n    top->Reshape(topShapeVec);\n    //ReLU Fwd\n    Dtype* topPtr = top->mutable_cpu_data();\n    for (int n=0;n<N;++n){\n      for (int cIdx=0;cIdx<C;++cIdx){\n        for (int hIdx=0;hIdx<h_img;++hIdx){\n\t  for (int wIdx=0;wIdx<w_img;++wIdx){\n            Dtype bottomData = bottom->data_at(n,cIdx,hIdx,wIdx);\n\t    topPtr[top->offset(n,cIdx,hIdx,wIdx)] = bottomData>=0?bottomData:0;\n\t  }\n\t}\n      } \n    }\n}\n\ntemplate <typename Dtype>\nvoid ReLU_Bwd(Blob<Dtype>* bottom,Blob<Dtype>* top,int N,int C,int h_img,int w_img){\n    Dtype* bottomDiffPtr = bottom->mutable_cpu_diff();\n    for (int n=0;n<N;++n){\n      for (int cIdx=0;cIdx<C;++cIdx){\n        for (int hIdx=0;hIdx<h_img;++hIdx){\n\t  for (int wIdx=0;wIdx<w_img;++wIdx){\n\t    bottomDiffPtr[bottom->offset(n,cIdx,hIdx,wIdx)] = bottom->data_at(n,cIdx,hIdx,wIdx)>=0?top->diff_at(n,cIdx,hIdx,wIdx):0; \n\t  }\n\t}\n      }\n    }\n}\n\ntemplate <typename Dtype>\nDtype getMean(Blob<Dtype>* A,int channelIdx){\n    int N = A->shape(0);\n    int H = A->shape(2);\n    int W = A->shape(3);\n    int totalCount = N*H*W;\n\n    Dtype sum = 0;\n    for (int n=0;n<N;++n){\n      for (int h=0;h<H;++h){\n\tfor (int w=0;w<W;++w){\n          sum += A->data_at(n,channelIdx,h,w);\n\t}\t\n      }\n    }\n    return sum/totalCount;\n}\n\ntemplate <typename Dtype>\nDtype getVar(Blob<Dtype>* A,int channelIdx){\n    int N = A->shape(0);\n    int H = A->shape(2);\n    int W = A->shape(3);\n    int totalCount = N*H*W;\n    Dtype mean = getMean(A,channelIdx);\n    \n    Dtype sum = 0;\n    for (int n=0;n<N;++n){\n      for (int h=0;h<H;++h){\n        for (int w=0;w<W;++w){\n\t  sum += (A->data_at(n,channelIdx,h,w)-mean) * (A->data_at(n,channelIdx,h,w)-mean);\n\t}\n      }\n    }\n    return sum / totalCount;\n}\n\ntemplate <typename Dtype>\nvoid BN_inf_Fwd(Blob<Dtype>* input,Blob<Dtype>* output,int N,int C,int h_img,int w_img,Blob<Dtype>* globalMean,Blob<Dtype>* globalVar,Blob<Dtype>* scaler,Blob<Dtype>* bias,Blob<Dtype>* factor_b){\n    int channelShape[] = {1,C,1,1};\n    vector<int> channelShapeVec(channelShape,channelShape+4);\n    Blob<Dtype>* localInf_Mean = new Blob<Dtype>(channelShapeVec);\n    Blob<Dtype>* localInf_Var = new Blob<Dtype>(channelShapeVec);\n    Dtype scale_factor = factor_b->cpu_data()[0] == 0 ? 0 : (1/factor_b->cpu_data()[0]);\n    caffe_cpu_scale(localInf_Mean->count(),scale_factor,globalMean->cpu_data(),localInf_Mean->mutable_cpu_data());\n    caffe_cpu_scale(localInf_Var->count(),scale_factor,globalVar->cpu_data(),localInf_Var->mutable_cpu_data());\n    //Reshape output\n    int outputShape[] = {N,C,h_img,w_img};\n    vector<int> outputShapeVec(outputShape,outputShape+4);\n    output->Reshape(outputShapeVec);\n    //BN Fwd inf\n    double epsilon = 1e-5;\n    Dtype* outputPtr = output->mutable_cpu_data();\n\n    for (int n=0;n<N;++n){\n      for (int cIdx=0;cIdx<C;++cIdx){\n        Dtype denom = 1.0 / sqrt(localInf_Var->data_at(0,cIdx,0,0) + epsilon);\n\tfor (int hIdx=0;hIdx<h_img;++hIdx){\n\t  for (int wIdx=0;wIdx<w_img;++wIdx){\n\t    outputPtr[output->offset(n,cIdx,hIdx,wIdx)] = scaler->data_at(0,cIdx,0,0) * (denom * (input->data_at(n,cIdx,hIdx,wIdx) - localInf_Mean->data_at(0,cIdx,0,0))) + bias->data_at(0,cIdx,0,0);\n\t  }\n\t}\n      }\n    }\n}\n\ntemplate <typename Dtype>\nvoid BN_train_Fwd(Blob<Dtype>* bottom,Blob<Dtype>* top,Blob<Dtype>* output_xhat,Blob<Dtype>* globalMean,Blob<Dtype>* globalVar,Blob<Dtype>* batchMean,Blob<Dtype>* batchVar,Blob<Dtype>* scaler,Blob<Dtype>* bias,int N,int C,int h_img,int w_img,Dtype EMA_decay){\n    //reshape output\n    int outputShape[] = {N,C,h_img,w_img};\n    vector<int> outputShapeVec(outputShape,outputShape+4);\n    top->Reshape(outputShapeVec);\n    output_xhat->Reshape(outputShapeVec);\n    //BN Fwd train\n    double epsilon = 1e-5;\n    //get batch/global Mean/Var\n    for (int channelIdx=0;channelIdx<C;++channelIdx){\n      int variance_adjust_m = N*h_img*w_img;\n      //batch\n      Dtype* batchMean_mutable = batchMean->mutable_cpu_data();\n      Dtype* batchVar_mutable = batchVar->mutable_cpu_data();\n      batchMean_mutable[channelIdx] = getMean(bottom,channelIdx);\n      batchVar_mutable[channelIdx] = (variance_adjust_m / (variance_adjust_m - 1.0)) * getVar(bottom,channelIdx);\n      //global\n      Dtype* globalMean_mutable = globalMean->mutable_cpu_data();\n      Dtype* globalVar_mutable = globalVar->mutable_cpu_data();\n      globalMean_mutable[channelIdx] = EMA_decay * globalMean->data_at(0,channelIdx,0,0) + batchMean->data_at(0,channelIdx,0,0);\n      globalVar_mutable[channelIdx] = EMA_decay * globalVar->data_at(0,channelIdx,0,0) + batchVar->data_at(0,channelIdx,0,0);\n    }\n    //process data\n    for (int n=0;n<N;++n){\n      for (int c=0;c<C;++c){\n        for (int h=0;h<h_img;++h){\n\t  for (int w=0;w<w_img;++w){\n\t    Dtype* xhat_mutable = output_xhat->mutable_cpu_data();\n\t    xhat_mutable[output_xhat->offset(n,c,h,w)] = (bottom->data_at(n,c,h,w) - batchMean->data_at(0,c,0,0))/sqrt(batchVar->data_at(0,c,0,0) + epsilon);\n\t    Dtype* output_mutable = top->mutable_cpu_data();\n\t    output_mutable[top->offset(n,c,h,w)] = (scaler->data_at(0,c,0,0)) * (output_xhat->data_at(n,c,h,w)) + bias->data_at(0,c,0,0);\n\t  }\n\t}\n      }\n    }\n}\n\ntemplate <typename Dtype>\nbool decide_channelDiffAllZero(Blob<Dtype>* B,int channelIdx,int N,int C,int H,int W){\n  bool output = true;\n  for (int n=0;n<N;++n){\n    for (int h=0;h<H;++h){\n      for (int w=0;w<W;++w){\n        output = output && (B->diff_at(n,channelIdx,h,w)<0.001) && (B->diff_at(n,channelIdx,h,w)>-0.001);\n      }\n    }\n  }\n  return output;\n}\n\ntemplate <typename Dtype>\nvoid BN_train_Bwd(Blob<Dtype>* bottom,Blob<Dtype>* bottom_xhat,Blob<Dtype>* top,Blob<Dtype>* batchMean,Blob<Dtype>* batchVar,Blob<Dtype>* scaler,Blob<Dtype>* bias,int N,int C,int h_img,int w_img,bool betaOneData){\n    double epsilon = 1e-5;\n    //bias and scaler grad\n    Dtype* biasGrad = bias->mutable_cpu_diff();\n    Dtype* scalerGrad = scaler->mutable_cpu_diff();\n    for (int channelIdx=0;channelIdx<C;++channelIdx){\n      biasGrad[channelIdx] = 0;\n      scalerGrad[channelIdx] = 0;\n      for (int n=0;n<N;++n){\n        for (int hIdx=0;hIdx<h_img;++hIdx){\n\t  for (int wIdx=0;wIdx<w_img;++wIdx){\n\t    biasGrad[channelIdx] += top->diff_at(n,channelIdx,hIdx,wIdx);\n\t    scalerGrad[channelIdx] += top->diff_at(n,channelIdx,hIdx,wIdx) * bottom_xhat->data_at(n,channelIdx,hIdx,wIdx);\n\t  }\n\t}\n      }\n    }\n    //bottom data grad\n    //helper 1:\n    Dtype* XhatGrad = bottom_xhat->mutable_cpu_diff();\n    for (int n=0;n<N;++n){\n      for (int c=0;c<C;++c){\n        for (int h=0;h<h_img;++h){\n\t  for (int w=0;w<w_img;++w){\n\t    XhatGrad[bottom_xhat->offset(n,c,h,w)] = top->diff_at(n,c,h,w) * scaler->data_at(0,c,0,0);\n\t  }\n\t}\n      }\n    } \n    //helper 2:\n    Dtype* varGrad = batchVar->mutable_cpu_diff();\n    for (int c=0;c<C;++c){\n      for (int n=0;n<N;++n){\n        for (int h=0;h<h_img;++h){\n\t  for (int w=0;w<w_img;++w){\n\t    //varGrad[c] += bottom_xhat->diff_at(n,c,h,w) * (bottom->data_at(n,c,h,w)-batchMean->data_at(0,c,0,0)) * (-0.5) * pow(batchVar->data_at(0,c,0,0) + epsilon,-1.5);\n\t    varGrad[c] += bottom_xhat->diff_at(n,c,h,w) * (bottom->data_at(n,c,h,w)-batchMean->data_at(0,c,0,0)) * (-0.5) * (1.0 / ((batchVar->data_at(0,c,0,0)+epsilon) * sqrt(batchVar->data_at(0,c,0,0) + epsilon)));\n\t    //flag\n\t    //if (decide_channelDiffAllZero<Dtype>(top,c,N,C,h_img,w_img)){\n\t    //  std::cout<<varGrad[c]<<std::endl;\n\t    //}\n \n\t  }\n\t}\n      }\n    }\n\n    //helper 3:\n    double m = N * h_img * w_img;\n    Dtype* meanGrad = batchMean->mutable_cpu_diff();\n    for (int c=0;c<C;++c){\n      for (int n=0;n<N;++n){\n        for (int h=0;h<h_img;++h){\n\t  for (int w=0;w<w_img;++w){\n\t    meanGrad[c] += bottom_xhat->diff_at(n,c,h,w) * (-1.0 / sqrt(batchVar->data_at(0,c,0,0) + epsilon)) + batchVar->diff_at(0,c,0,0) * (-2.0) * (bottom->data_at(n,c,h,w) - batchMean->data_at(0,c,0,0)) / m; \n            //if (decide_channelDiffAllZero<Dtype>(top,c,N,C,h_img,w_img)){\n\t    //  std::cout<<varGrad[c]<<std::endl;\n\t    //}\n\n\t  }\n\t}\n      }\n    }\n\n    //combine helpers\n    Dtype* bottomDataGrad = bottom->mutable_cpu_diff();\n    for (int n=0;n<N;++n){\n      for (int c=0;c<C;++c){\n        for (int h=0;h<h_img;++h){\n\t  for (int w=0;w<w_img;++w){\n\t    //Dtype term1=bottom_xhat->diff_at(n,c,h,w)*pow(batchVar->data_at(0,c,0,0)+epsilon,-0.5);\n\t    Dtype term1=bottom_xhat->diff_at(n,c,h,w) / (sqrt(batchVar->data_at(0,c,0,0) + epsilon));\n\t    Dtype term2=batchVar->diff_at(0,c,0,0)*2.0*(bottom->data_at(n,c,h,w) - batchMean->data_at(0,c,0,0)) / m;\n\t    Dtype term3=batchMean->diff_at(0,c,0,0)/m;\n\t    if (betaOneData){\n\t      bottomDataGrad[bottom->offset(n,c,h,w)] += term1 + term2 + term3;\n\t    }\n\t    else {\n\t      bottomDataGrad[bottom->offset(n,c,h,w)] = term1 + term2 + term3;\n\t    }\n\t    //std::cout<<term1<<\",\"<<term2<<\",\"<<term3<<std::endl;\n\t  }\n\t}\n      }\n    }\n    \n }\n\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::CPU_Initialization(){\n    this->batch_Mean.resize(this->numTransition);\n    this->batch_Var.resize(this->numTransition);\n    \n    this->merged_conv.resize(this->numTransition + 1);\n    this->BN_XhatVec.resize(this->numTransition);\n    this->postBN_blobVec.resize(this->numTransition);\n    this->postReLU_blobVec.resize(this->numTransition);\n    this->postConv_blobVec.resize(this->numTransition);\n    if (useBC){\n        BC_BN_XhatVec.resize(this->numTransition);\n        postBN_BCVec.resize(this->numTransition);\n        postReLU_BCVec.resize(this->numTransition);\n        postConv_BCVec.resize(this->numTransition);\n\tbatch_Mean4G.resize(numTransition);\n\tbatch_Var4G.resize(numTransition);\n    }\n    for (int transitionIdx=0;transitionIdx<this->numTransition;++transitionIdx){\n      int conv_y_Channels = this->growthRate;\n      int mergeChannels = this->initChannel + this->growthRate * transitionIdx;\n      int channelShapeArr[] = {1,mergeChannels,1,1};\n      int conv_y_ShapeArr[] = {this->N,conv_y_Channels,this->H,this->W};\n      int mergeShapeArr[] = {this->N,mergeChannels,this->H,this->W};\n      vector<int> channelShape(channelShapeArr,channelShapeArr+4);\n      vector<int> conv_y_Shape(conv_y_ShapeArr,conv_y_ShapeArr+4);\n      vector<int> mergeShape(mergeShapeArr,mergeShapeArr+4);\n      \n      this->batch_Mean[transitionIdx] = new Blob<Dtype>(channelShape);\n      this->batch_Var[transitionIdx] = new Blob<Dtype>(channelShape);\n      \n      this->merged_conv[transitionIdx] = new Blob<Dtype>(mergeShape);\n      this->BN_XhatVec[transitionIdx] = new Blob<Dtype>(mergeShape);\n      this->postBN_blobVec[transitionIdx] = new Blob<Dtype>(mergeShape);\n      this->postReLU_blobVec[transitionIdx] = new Blob<Dtype>(mergeShape);\n      this->postConv_blobVec[transitionIdx] = new Blob<Dtype>(conv_y_Shape);\n      if (useBC){\n        int quadGShapeArr[] = {N,4*growthRate,H,W};\n\tint quadChannelArr[] = {1,4*growthRate,1,1};\n        vector<int> quadGShape(quadGShapeArr,quadGShapeArr+4);\n\tvector<int> quadChannelShape(quadChannelArr,quadChannelArr+4);\n        this->BC_BN_XhatVec[transitionIdx] = new Blob<Dtype>(quadGShape);\n        this->postBN_BCVec[transitionIdx] = new Blob<Dtype>(quadGShape);        \n        this->postReLU_BCVec[transitionIdx] = new Blob<Dtype>(quadGShape);\n        this->postConv_BCVec[transitionIdx] = new Blob<Dtype>(quadGShape);\n\tbatch_Mean4G[transitionIdx] = new Blob<Dtype>(quadChannelShape);\n\tbatch_Var4G[transitionIdx] = new Blob<Dtype>(quadChannelShape);\n      }\n    }\n    //the last element of merged_conv serve as output of forward\n    int extraMergeOutputShapeArr[] = {this->N,this->initChannel+this->growthRate*this->numTransition,this->H,this->W};\n    vector<int> extraMergeOutputShapeVector(extraMergeOutputShapeArr,extraMergeOutputShapeArr+4);\n    this->merged_conv[this->numTransition] = new Blob<Dtype>(extraMergeOutputShapeVector);\n}\n\ntemplate <typename Dtype>\nvoid mergeChannelData(Blob<Dtype>* outputBlob,Blob<Dtype>* blobA,Blob<Dtype>* blobB){\n  int N = blobA->shape(0);\n  int frontC = blobA->shape(1); int backC = blobB->shape(1);\n  int H = blobA->shape(2);\n  int W = blobA->shape(3);\n\n  for (int n=0;n<N;++n){\n    for (int c=0;c<frontC+backC;++c){\n      for (int h=0;h<H;++h){\n        for (int w=0;w<W;++w){\n          Dtype inData;\n\t  if (c<frontC){\n\t    inData = blobA->cpu_data()[blobA->offset(n,c,h,w)];\n\t  }\n\t  else {\n\t    int readC = c - frontC;\n\t    inData = blobB->cpu_data()[blobB->offset(n,readC,h,w)];\n\t  }\n\t  outputBlob->mutable_cpu_data()[outputBlob->offset(n,c,h,w)] = inData;\n\t}\n      }\n    } \n  }\n}\n\ntemplate <typename Dtype>\nvoid distributeChannelDiff(Blob<Dtype>* inputBlob,Blob<Dtype>* blobA,Blob<Dtype>* blobB){\n  int N = blobA->shape(0);\n  int frontC = blobA->shape(1); int backC = blobB->shape(1);\n  int H = blobA->shape(2);\n  int W = blobA->shape(3);\n  \n  for (int n=0;n<N;++n){\n    for (int c=0;c<frontC+backC;++c){\n      for (int h=0;h<H;++h){\n        for (int w=0;w<W;++w){\n\t  Dtype readData = inputBlob->cpu_diff()[inputBlob->offset(n,c,h,w)];\n          if (c<frontC){\n\t    blobA->mutable_cpu_diff()[blobA->offset(n,c,h,w)] = readData;\n\t  }\n\t  else {\n            int writeC = c-frontC;\n\t    blobB->mutable_cpu_diff()[blobB->offset(n,writeC,h,w)] = readData;\n\t  }\n        }\n      }\n    }\n  }\n}\n\ntemplate <typename Dtype>\nvoid BlobSetZero(Blob<Dtype>* B,int count){\n    Dtype* B_mutable_data = B->mutable_cpu_data();\n    Dtype* B_mutable_diff = B->mutable_cpu_diff();\n    for (int i=0;i<count;++i) {\n      B_mutable_data[i] = 0;\n      B_mutable_diff[i] = 0;\n    }\n}\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::LoopEndCleanup_cpu(){\n    for (int transitionIdx=0;transitionIdx<this->numTransition;++transitionIdx){\n      int tensorCount = this->N * growthRate * this->H * this->W;\n      int tensorMergeCount = this->N * (this->initChannel + this->growthRate * transitionIdx) * this->H * this->W;\n      BlobSetZero<Dtype>(this->merged_conv[transitionIdx],tensorMergeCount);\n      BlobSetZero<Dtype>(this->BN_XhatVec[transitionIdx],tensorMergeCount);\n      BlobSetZero<Dtype>(this->postBN_blobVec[transitionIdx],tensorMergeCount);\n      BlobSetZero<Dtype>(this->postReLU_blobVec[transitionIdx],tensorMergeCount);\n      BlobSetZero<Dtype>(this->postConv_blobVec[transitionIdx],tensorCount);\n    }\n}\n\n  template <typename Dtype>\n  void DenseBlockLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n                                  const vector<Blob<Dtype>*>& top) \n  { \n    //init CPU\n    if (!this->cpuInited){  \n\t//std::cout<<\"fwd cpu init\"<<std::endl;\n\tthis->CPU_Initialization();\n        this->cpuInited = true;\n\t//std::cout<<\"fwd cpu init done\"<<std::endl;\n    }\n    int bnTimerIdx=useBC?10*numTransition:5*numTransition;\n    //deploy init data\n    this->merged_conv[0]->CopyFrom(*(bottom[0]));\n    //init CPU finish\n    for (int transitionIdx=0;transitionIdx<this->numTransition;++transitionIdx){\n      //BN\n      Blob<Dtype>* BN_bottom = this->merged_conv[transitionIdx];\n      Blob<Dtype>* BN_top = this->postBN_blobVec[transitionIdx];\n      Blob<Dtype>* Scaler = this->blobs_[numTransition + transitionIdx].get();\n      Blob<Dtype>* Bias = this->blobs_[2*numTransition + transitionIdx].get();\n      int localChannels = this->initChannel+transitionIdx*this->growthRate;\n      if (this->phase_ == TEST){\n\t//std::cout<<\"cpu BN test forward\"<<std::endl;\n        BN_inf_Fwd<Dtype>(BN_bottom,BN_top,this->N,localChannels,this->H,this->W,this->blobs_[3*this->numTransition+transitionIdx].get(),this->blobs_[4*this->numTransition+transitionIdx].get(),Scaler,Bias,this->blobs_[bnTimerIdx].get());\n      }\n      else {\n\t//std::cout<<\"cpu BN train forward\"<<std::endl;\n        BN_train_Fwd<Dtype>(BN_bottom,BN_top,this->BN_XhatVec[transitionIdx],this->blobs_[3*this->numTransition+transitionIdx].get(),this->blobs_[4*this->numTransition+transitionIdx].get(),this->batch_Mean[transitionIdx],this->batch_Var[transitionIdx],Scaler,Bias,this->N,localChannels,this->H,this->W,this->EMA_decay);\n      }\n      //ReLU\n      Blob<Dtype>* ReLU_top = this->postReLU_blobVec[transitionIdx];\n      ReLU_Fwd<Dtype>(BN_top,ReLU_top,this->N,localChannels,this->H,this->W);\n      //if useBC, Conv1*1-BN(BC)-ReLU(BC)\n      if (useBC){\n\t//BC Conv 1*1\n\tBlob<Dtype>* BC_filterBlob = this->blobs_[5*numTransition+transitionIdx].get();\n        Blob<Dtype>* BC_conv_x = postReLU_blobVec[transitionIdx];\n        Blob<Dtype>* BC_conv_y = postConv_BCVec[transitionIdx];\n\tint BC_conv_inChannel = initChannel+growthRate*transitionIdx;\n\tint BC_conv_outChannel = 4*growthRate;\n        convolution_Fwd<Dtype>(BC_conv_x,BC_conv_y,BC_filterBlob,N,BC_conv_outChannel,BC_conv_inChannel,H,W,1,1);\t\n\t//BC BN \n\tBlob<Dtype>* BC_BN_x = postConv_BCVec[transitionIdx];\n\tBlob<Dtype>* BC_BN_y = postBN_BCVec[transitionIdx];\n        Blob<Dtype>* BC_Scaler = this->blobs_[6*numTransition+transitionIdx].get();\n\tBlob<Dtype>* BC_Bias = this->blobs_[7*numTransition+transitionIdx].get(); \n\tBlob<Dtype>* BC_Mean = this->blobs_[8*numTransition+transitionIdx].get();\n\tBlob<Dtype>* BC_Var = this->blobs_[9*numTransition+transitionIdx].get();\n\tif (this->phase_ == TEST){\n\t  BN_inf_Fwd<Dtype>(BC_BN_x,BC_BN_y,N,4*growthRate,H,W,BC_Mean,BC_Var,BC_Scaler,BC_Bias,this->blobs_[bnTimerIdx].get());\n\t}\n\telse {\n\t  Blob<Dtype>* BC_xhat = BC_BN_XhatVec[transitionIdx];\n\t  Blob<Dtype>* BC_batchMean = batch_Mean4G[transitionIdx];\n\t  Blob<Dtype>* BC_batchVar = batch_Var4G[transitionIdx];\n\t  BN_train_Fwd<Dtype>(BC_BN_x,BC_BN_y,BC_xhat,BC_Mean,BC_Var,BC_batchMean,BC_batchVar,BC_Scaler,BC_Bias,N,4*growthRate,H,W,EMA_decay);\n\t}\t\n\t//BC ReLU \n\tBlob<Dtype>* ReLU_x = postBN_BCVec[transitionIdx];\n\tBlob<Dtype>* ReLU_y = postReLU_BCVec[transitionIdx];\n\tReLU_Fwd<Dtype>(ReLU_x,ReLU_y,N,4*growthRate,H,W);\t\n      }\n      //Conv\n      Blob<Dtype>* filterBlob = this->blobs_[transitionIdx].get();\n      Blob<Dtype>* conv_x = useBC?postReLU_BCVec[transitionIdx]:postReLU_blobVec[transitionIdx];\n      Blob<Dtype>* conv_y = this->postConv_blobVec[transitionIdx];\n      int inConvChannel = useBC?4*growthRate:initChannel+growthRate*transitionIdx;\n      convolution_Fwd<Dtype>(conv_x,conv_y,filterBlob,N,growthRate,inConvChannel,H,W,3,3);\n      //post Conv merge\n      Blob<Dtype>* mergeOutput = merged_conv[transitionIdx+1];\n      Blob<Dtype>* mergeInputA = merged_conv[transitionIdx];\n      Blob<Dtype>* mergeInputB = postConv_blobVec[transitionIdx];\n      mergeChannelData(mergeOutput,mergeInputA,mergeInputB);\n    }\n    //deploy output data\n    top[0]->CopyFrom(*(this->merged_conv[this->numTransition]));\n    if (this->phase_ == TRAIN){\n      this->blobs_[bnTimerIdx]->mutable_cpu_data()[0] *= this->EMA_decay;\n      this->blobs_[bnTimerIdx]->mutable_cpu_data()[0] += 1;\n      this->trainCycleIdx+=1;\n    }    \n    //logInternal_cpu(\"TC_TrueFwdlog\");\n  }\n\n\n  template <typename Dtype>\n  void DenseBlockLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n                                    const vector<bool>& propagate_down,\n                                    const vector<Blob<Dtype>*>& bottom) \n  {\n    if (!this->cpuInited){\n\tthis->CPU_Initialization();\n        this->cpuInited = true;\n    }\n    //deploy top diff\n    this->merged_conv[this->numTransition]->CopyFrom(*(top[0]),true);\n    for (int transitionIdx=this->numTransition-1;transitionIdx>=0;--transitionIdx){\n      //distribute diff\n      distributeChannelDiff(this->merged_conv[transitionIdx+1],this->merged_conv[transitionIdx],this->postConv_blobVec[transitionIdx]);\n      //Conv Bwd\n      Blob<Dtype>* conv_top=this->postConv_blobVec[transitionIdx];\n      Blob<Dtype>* conv_bottom=useBC?postReLU_BCVec[transitionIdx]:postReLU_blobVec[transitionIdx];\n      Blob<Dtype>* filter = this->blobs_[transitionIdx].get();\n      int c_input = useBC?4*growthRate:initChannel+growthRate*transitionIdx;\n      convolution_Bwd<Dtype>(conv_bottom,conv_top,filter,this->N,this->growthRate,c_input,this->H,this->W,3,3);\n      //BC ReLU_BC_Bwd - BN_BC_Bwd - Conv1*1_BC_Bwd\n      if (useBC){\n\t//ReLU BC Bwd\n        Blob<Dtype>* BC_ReLU_y = postReLU_BCVec[transitionIdx];\n\tBlob<Dtype>* BC_ReLU_x = postBN_BCVec[transitionIdx];\t\n\tReLU_Bwd<Dtype>(BC_ReLU_x,BC_ReLU_y,N,4*growthRate,H,W);\t\n\t//BN BC Bwd\n\tBlob<Dtype>* BC_BN_y = postBN_BCVec[transitionIdx];\n\tBlob<Dtype>* BC_BN_x = postConv_BCVec[transitionIdx];\n\tBlob<Dtype>* BC_BN_xhat = BC_BN_XhatVec[transitionIdx];\n\tBlob<Dtype>* BC_Scaler = this->blobs_[6*numTransition+transitionIdx].get();\n\tBlob<Dtype>* BC_Bias = this->blobs_[7*numTransition+transitionIdx].get();\n\tBlob<Dtype>* BC_batchMean = batch_Mean4G[transitionIdx];\n\tBlob<Dtype>* BC_batchVar = batch_Var4G[transitionIdx];\n\tBN_train_Bwd<Dtype>(BC_BN_x,BC_BN_xhat,BC_BN_y,BC_batchMean,BC_batchVar,BC_Scaler,BC_Bias,N,4*growthRate,H,W,false);\n\t//Conv1*1 BC Bwd\n\tBlob<Dtype>* BC_conv_x = postReLU_blobVec[transitionIdx];\n\tBlob<Dtype>* BC_conv_y = postConv_BCVec[transitionIdx];\n\tBlob<Dtype>* BC_filter = this->blobs_[5*numTransition+transitionIdx].get();\t\n\tint BC_c_input = initChannel+growthRate*transitionIdx;\n\tint BC_c_output = 4*growthRate;\n\tconvolution_Bwd<Dtype>(BC_conv_x,BC_conv_y,BC_filter,N,BC_c_output,BC_c_input,H,W,1,1);\t\t\n      }\n      //ReLU Bwd\n      int localChannel = this->initChannel+this->growthRate*transitionIdx;\n      ReLU_Bwd<Dtype>(postBN_blobVec[transitionIdx],postReLU_blobVec[transitionIdx],this->N,localChannel,this->H,this->W); \n      //BN Bwd\n      Blob<Dtype>* BN_bottom = this->merged_conv[transitionIdx];\n      Blob<Dtype>* scaler = this->blobs_[this->numTransition+transitionIdx].get();\n      Blob<Dtype>* bias = this->blobs_[2*this->numTransition+transitionIdx].get();\n      BN_train_Bwd<Dtype>(BN_bottom,this->BN_XhatVec[transitionIdx],this->postBN_blobVec[transitionIdx],this->batch_Mean[transitionIdx],this->batch_Var[transitionIdx],scaler,bias,this->N,localChannel,this->H,this->W,true);\n    }\n    bottom[0]->CopyFrom(*(this->merged_conv[0]),true);     \n    //logInternal_cpu(\"TC_TrueBwdlog\");\n    this->LoopEndCleanup_cpu();\n}\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::Forward_cpu_public(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top){\n  this->Forward_cpu(bottom,top);\n}\n\ntemplate <typename Dtype>\nvoid DenseBlockLayer<Dtype>::Backward_cpu_public(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom){\n  this->Backward_cpu(top,propagate_down,bottom);\n}\n\n#ifdef CPU_ONLY\nSTUB_GPU(DenseBlockLayer);\n#endif\n\nINSTANTIATE_CLASS(DenseBlockLayer);\nREGISTER_LAYER_CLASS(DenseBlock);\n\n}  // namespace caffe  \n", "meta": {"hexsha": "f5f9eab441e23fab76b61cd103709a8c228c84cb", "size": 40897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/DenseBlock_layer.cpp", "max_stars_repo_name": "GuohongWu/caffe-windows-happynear", "max_stars_repo_head_hexsha": "88602198ff6507909b8d2992efa79d8ec74d7dfe", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-11T11:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-08T13:12:57.000Z", "max_issues_repo_path": "src/caffe/layers/DenseBlock_layer.cpp", "max_issues_repo_name": "GuohongWu/caffe-windows-happynear", "max_issues_repo_head_hexsha": "88602198ff6507909b8d2992efa79d8ec74d7dfe", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/layers/DenseBlock_layer.cpp", "max_forks_repo_name": "GuohongWu/caffe-windows-happynear", "max_forks_repo_head_hexsha": "88602198ff6507909b8d2992efa79d8ec74d7dfe", "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.532210109, "max_line_length": 319, "alphanum_fraction": 0.6581900873, "num_tokens": 12355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.02675928318544315, "lm_q1q2_score": 0.01161303291392095}}
{"text": "#include <boost/property_tree/ptree.hpp>\r\n#include <boost/property_tree/xml_parser.hpp>\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/foreach.hpp>\r\n#include <tuple>\r\n#include <algorithm>\r\n#include <set>\r\n#include <queue>\r\n#include <map>\r\n#include <string>\r\n#include <sstream>\r\n#include <vector>\r\n#include <iostream>\r\n#include <fstream>\r\n#include \"cml.h\"\r\n#include \"Valences.h\"\r\n\r\nusing boost::property_tree::ptree;\r\nusing std::map;\r\nusing std::set;\r\nusing std::queue;\r\nusing std::string;\r\nusing std::pair;\r\nusing std::vector;\r\nusing std::ostringstream;\r\nusing std::logic_error;\r\n\r\nclass Atom\r\n{\r\n\tstring id;\r\n\tstring element;\r\n\tint valence; // 0 is it must be deduced from bonds number and standard valences\r\n\tint bondsCnt;   // to accumulate number of explicit bonds\r\n\tint charge;\r\npublic:\r\n\tAtom(const string& id, const string& element, int valence = 0, int charge = 0) : id(id), element(element), valence(valence), bondsCnt(0), charge(charge)\r\n\t{\r\n\t}\r\n\r\n\tvoid addBonds(int order)\r\n\t{\r\n\t\tbondsCnt += order;\r\n\r\n\t\tif (valence != 0 && bondsCnt > valence)\r\n\t\t{\r\n\t\t\tostringstream oss;\r\n\t\t\toss << \"Atom with id '\" << id << \"' has more bounds than valence.\";\r\n\t\t\tthrow logic_error(oss.str());\r\n\t\t}\r\n\t}\r\n\r\n\t// if valence == 0 then deduce it from bonds and standard valences for that element\r\n\tvoid correct_valence()\r\n\t{\r\n\t\tif (this->valence == 0)\r\n\t\t\tthis->valence = Valences::getCeilValence(this->element, this->bondsCnt);\r\n\t}\r\n\r\n\tint getImplicitHydrogenCnt() const {\r\n\t\treturn valence - bondsCnt + charge;\r\n\t}\r\n\r\n\tstring getElement() const { return element; }\r\n};\r\n\r\nclass Atoms\r\n{\r\n\tmap<string, Atom> atoms; // atom id => Atom\r\n\r\n\t// atom id => list of bound atom ids\r\n\tmap<string, vector<string> > graph;\r\n\r\n\tvoid addAtom(const string& id, const string& element, int valence = 0, int charge = 0)\r\n\t{\r\n\t\tif (atoms.find(id) != atoms.end())\r\n\t\t{\r\n\t\t\tostringstream oss;\r\n\t\t\toss << \"Atom with id '\" << id << \"' already exists.\";\r\n\t\t\tthrow logic_error(oss.str());\r\n\t\t}\r\n\r\n\t\tatoms.insert(make_pair(id, Atom(id, element, valence, charge)));\r\n\t\tgraph.insert(make_pair(id, vector<string>()));\r\n\t}\r\n\r\n\tvoid addBond(const string& id1, const string& id2, int order)\r\n\t{\r\n\t\tgraph[id1].push_back(id2);\r\n\t\tgraph[id2].push_back(id1);\r\n\t\tAtom& a1 = atoms.find(id1)->second;\r\n\t\tAtom& a2 = atoms.find(id2)->second;\r\n\t\ta1.addBonds(order);\r\n\t\ta2.addBonds(order);\r\n\t}\r\n\r\n\tvector<vector<string>> get_connected_components() const\r\n\t{\r\n\t\tvector<vector<string> > connected_components;\r\n\t\tset<string> visited;\r\n\t\t\r\n\t\tfor (auto it = graph.cbegin(); it != graph.cend(); ++it)\r\n\t\t{\r\n\t\t\tconst string& currentAtomID = it->first;\r\n\t\t\t\r\n\t\t\tif (visited.find(currentAtomID) == visited.end())\r\n\t\t\t{\r\n\t\t\t\tvector<string> component;\r\n\t\t\t\tqueue<string> q;\r\n\t\t\t\tq.push(currentAtomID);\r\n\t\t\t\tvisited.insert(currentAtomID);\r\n\t\t\t\tcomponent.push_back(currentAtomID);\r\n\r\n\t\t\t\twhile (!q.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tstring neighborID = q.front();\r\n\t\t\t\t\tq.pop();\r\n\t\t\t\t\tconst vector<string>& adjList = graph.find(neighborID)->second;\r\n\r\n\t\t\t\t\tfor (auto adjIt = adjList.cbegin(); adjIt != adjList.cend(); ++adjIt)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (visited.find(*adjIt) == visited.end())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvisited.insert(*adjIt);\r\n\t\t\t\t\t\t\tq.push(*adjIt);\r\n\t\t\t\t\t\t\tcomponent.push_back(*adjIt);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tconnected_components.push_back(component);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn connected_components;\r\n\t}\r\n\r\n\tstatic string getFormula(const map<string, int>& molecule)\r\n\t{\r\n\t\tstd::ostringstream oss;\r\n\t\tstd::map<string, int>::const_iterator tC, tH;\r\n\t\ttH = molecule.end();\r\n\t\ttC = molecule.find(\"C\");\r\n\t\tif(tC != molecule.end())\r\n\t\t{\r\n\t\t\tconst string& element = tC->first;\r\n\t\t\tint cnt = tC->second;\r\n\t\t\t\r\n\t\t\toss << element;\r\n\r\n\t\t\tif (cnt > 1)\r\n\t\t\t\toss << cnt;\r\n\t\t\t\r\n\t\t\ttH = molecule.find(\"H\");\r\n\t\t\t\r\n\t\t\tconst string& element1 = tH->first;\r\n\t\t\tcnt = tH->second;\r\n\t\t\t\r\n\t\t\toss << element1;\r\n\r\n\t\t\tif (cnt > 1)\r\n\t\t\t\toss << cnt;\r\n\t\t}\r\n\t\tfor (std::map<string, int>::const_iterator el = molecule.begin(); el != molecule.end(); ++el)\r\n\t\t{\r\n\t\t\tif(el == tC || el == tH)\r\n\t\t\t\tcontinue;\r\n\t\t\tconst string& element = el->first;\r\n\t\t\tint cnt = el->second;\r\n\r\n\t\t\toss << element;\r\n\r\n\t\t\tif (cnt > 1)\r\n\t\t\t\toss << cnt;\r\n\t\t}\r\n\r\n\t\treturn oss.str();\r\n\t}\r\n\r\n\t// vector of molecules, where molecule = { element => element count }\r\n\tvector<map<string, int>> getMolecules() const\r\n\t{\r\n\t\tvector<map<string, int>> molecules;\r\n\r\n\t\tvector<vector<string>> connected_components = this->get_connected_components();\r\n\t\tfor (std::vector<vector<string>>::const_iterator component = connected_components.begin(); component != connected_components.end(); ++component)\r\n\t\t{\r\n\t\t\tmap<string, int> molecule;\r\n\t\t\tint implicitHydrogenCnt = 0;\r\n\t\t\tfor (std::vector<string>::const_iterator id = (*component).begin(); id != (*component).end(); ++id)\r\n\t\t\t{\r\n\t\t\t\tconst Atom& a = atoms.find(*id)->second;\r\n\t\t\t\tmolecule[a.getElement()]++;\r\n\t\t\t\timplicitHydrogenCnt += a.getImplicitHydrogenCnt();\r\n\t\t\t}\r\n\r\n\t\t\tif (implicitHydrogenCnt)\r\n\t\t\t\tmolecule[\"H\"] += implicitHydrogenCnt;\r\n\r\n\t\t\tmolecules.push_back(molecule);\r\n\t\t}\r\n\r\n\t\treturn molecules;\r\n\t}\r\n\r\n\r\npublic:\r\n\tvoid readFromCML(const string& filename)\r\n\t{\r\n\t\tptree pt;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tread_xml(filename, pt);\r\n\t\t}\r\n\t\tcatch(std::exception &e)\r\n\t\t{\r\n\t\t\tthrow string(\"Error: no file exists\");\r\n\t\t}\r\n\t\tstd::ifstream chem_atom (\"table.txt\");\r\n\t\tif(!chem_atom.is_open())\r\n\t\t\tthrow string(\"Error: source file problem\");\r\n\t\tvector<string> atom_tab;\r\n\t\twhile(true)\r\n\t\t{\r\n\t\t\tif(chem_atom.eof())\r\n\t\t\t\tbreak;\r\n\t\t\tstring str;\r\n\t\t\tgetline(chem_atom, str, '\\n');\r\n\t\t\tatom_tab.push_back(str);\r\n\t\t}\r\n\t\tBOOST_FOREACH(ptree::value_type &i, pt.get_child(\"cml.molecule.atomArray\"))\r\n\t\t{\r\n\t\t\tstd::string name = i.first;\r\n\t\t\tptree& sub_pt = i.second;\r\n\t\t\tint valence = 0;\r\n\t\t\tint charge = 0;\r\n\r\n\t\t\tif (name == \"atom\")\r\n\t\t\t{\r\n\t\t\t\tstring id = sub_pt.get<string>(\"<xmlattr>.id\");\r\n\t\t\t\tstring elementType = sub_pt.get<string>(\"<xmlattr>.elementType\");\r\n\t\t\t\t\r\n\t\t\t\tif(find(atom_tab.begin(), atom_tab.end(), elementType) == atom_tab.end())\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow string(\"Error: non chemical atom in file\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tboost::optional<int> mrvValence = sub_pt.get_optional<int>(\"<xmlattr>.mrvValence\");\r\n\t\t\t\t\r\n\t\t\t\tif (mrvValence)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalence = mrvValence.value();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tboost::optional<int> formalcharge = sub_pt.get_optional<int>(\"<xmlattr>.formalCharge\");\r\n\t\t\t\t\r\n\t\t\t\tif (formalcharge)\r\n\t\t\t\t{\r\n\t\t\t\t\tcharge = formalcharge.value();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tboost::optional<int> hydrogenCount = sub_pt.get_optional<int>(\"<xmlattr>.hydrogenCount\");\r\n\t\t\t\t\r\n\t\t\t\tif (hydrogenCount)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalence -= hydrogenCount.value();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthis->addAtom(id, elementType, valence, charge);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tBOOST_FOREACH(ptree::value_type &i, pt.get_child(\"cml.molecule.bondArray\"))\r\n\t\t{\r\n\t\t\tstd::string name = i.first;\r\n\t\t\tptree& sub_pt = i.second;\r\n\r\n\t\t\tif (name == \"bond\")\r\n\t\t\t{\r\n\t\t\t\tstring atomRefs2 = sub_pt.get<string>(\"<xmlattr>.atomRefs2\");\r\n\t\t\t\tint order = sub_pt.get<int>(\"<xmlattr>.order\");\r\n\r\n\t\t\t\tvector<string> ids;\r\n\t\t\t\tboost::split(ids, atomRefs2, boost::is_any_of(\" \\t\\n\"));\r\n\t\t\t\tif (ids.size() != 2)\r\n\t\t\t\t{\r\n\t\t\t\t\tostringstream oss;\r\n\t\t\t\t\toss << \"Wrong bond '\" << atomRefs2 << \"'.\";\r\n\t\t\t\t\tthrow logic_error(oss.str());\r\n\t\t\t\t}\r\n\t\t\t\tthis->addBond(ids.at(0), ids.at(1), order);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tvoid correct_valences()\r\n\t{\r\n\t\tfor (std::map<string, Atom>::iterator id_atom = atoms.begin(); id_atom != atoms.end(); ++id_atom)\r\n\t\t{\r\n\t\t\tid_atom->second.correct_valence();\r\n\t\t}\r\n\t}\r\n\t\r\n\tstring getFormula()\r\n\t{\r\n\t\tvector<map<string, int>> molecules = this->getMolecules();\r\n\r\n\t\tvector<string> molecules_str;\r\n\t\tfor (std::vector<map<string, int>>::const_iterator molecule = molecules.begin(); molecule != molecules.end(); ++molecule)\r\n\t\t{\r\n\t\t\tmolecules_str.push_back(getFormula(*molecule));\r\n\t\t}\r\n\r\n\t\tstring formula = \"\";\r\n\t\tfor (unsigned i = 0; i < molecules_str.size(); ++i)\r\n\t\t{\r\n\t\t\tif (i > 0)\r\n\t\t\t\tformula += \".\";\r\n\t\t\tformula += molecules_str[i];\r\n\t\t}\r\n\t\treturn formula;\r\n\t}\r\n};\r\n\r\nstring getFormulaFromCML(const string& xmlfile)\r\n{\r\n\tAtoms atoms;\r\n\tatoms.readFromCML(xmlfile);\r\n\tatoms.correct_valences();\r\n\treturn atoms.getFormula();\r\n}\r\n", "meta": {"hexsha": "b48ce5c57444e4e875e5c69398d6b9eb6f929569", "size": 8054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cml.cpp", "max_stars_repo_name": "CML2DFormula/CmlFormula-Project", "max_stars_repo_head_hexsha": "82034730cdfb68fb41046175ab32baeaed4710de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cml.cpp", "max_issues_repo_name": "CML2DFormula/CmlFormula-Project", "max_issues_repo_head_hexsha": "82034730cdfb68fb41046175ab32baeaed4710de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cml.cpp", "max_forks_repo_name": "CML2DFormula/CmlFormula-Project", "max_forks_repo_head_hexsha": "82034730cdfb68fb41046175ab32baeaed4710de", "max_forks_repo_licenses": ["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.2590361446, "max_line_length": 154, "alphanum_fraction": 0.613608145, "num_tokens": 2187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.026759280468923338, "lm_q1q2_score": 0.011613031735001703}}
{"text": "/// @file tracker.hpp Tracking features in input partitions\n\n#ifndef BIGGLES_TRACKER_HPP___\n#define BIGGLES_TRACKER_HPP___\n#include <boost/tuple/tuple.hpp>\n#include <boost/assert.hpp>\n\n#include \"mh_moves/mh_moves.hpp\"\n#include \"model.hpp\"\n#include \"partition.hpp\"\n#include \"samplers.hpp\"\n#include \"partition_sampler.hpp\"\n#include \"sampling/gibbs.hpp\"\n#include \"sampling/metropolis_hastings.hpp\"\n\n#include \"tracker_detail.hpp\"\n\nnamespace biggles\n{\n\n/** \\brief a record for the move statistics\n *\n * this stores how often a proposed move was accepted, rejected or produced an identity move\n * the birth move has index 0, the number of *proper* moves is IDENTITY - BIRTH\n */\nstruct move_stats_t {\n    std::deque<uint64_t> rejected;\n    std::deque<uint64_t> accepted;\n    std::deque<uint64_t> identity;\n    move_stats_t () {\n        size_t len = static_cast<size_t>(mh_moves::IDENTITY - mh_moves::BIRTH);\n        rejected.assign(len, 0);\n        accepted.assign(len, 0);\n        identity.assign(len, 0);\n    }\n};\n\n/// @brief An implementation of the Biggles tracking algorithm.\n///\n/// The Biggles tracking algorithm is at it's highest level a sampler which maintains an optimum over the samples drawn.\n/// More specifically, the Biggles model specifies that there are three main components to the mathematical model used\n/// to represent the state of the world:\n///\n/// - the input observations from the feature detector, \\f$ D \\f$;\n/// - the association between these observations and one or more tracks, \\f$ T \\f$; and\n/// - parameters for the underlying dynamic model of molecule evolution, \\f$ \\theta \\f$.\n///\n/// The track association also includes a special 'track' known as the clutter which holds all observations we assert\n/// are due to spurious detection rather than a tracked molecule. This is the only track which may hold more than one\n/// observation per time stamp.\n///\n/// The value of \\f$ T \\f$ is represented in this code by biggles::partition which stores a collection of\n/// biggles::observation instances for the clutter and a collection of biggles::track instances for each track. The\n/// collection of tracks is implemented by biggles::track_collection which implicitly shares tracks between collections.\n///\n/// The tracking algorithm proceeds by drawing samples of \\f$ T \\f$ and \\f$ \\theta \\f$ from the joint distribution \\f$\n/// P(T, \\theta | D) \\f$. By definition of the mode, we expect more of these samples to be close to the optimum than far\n/// from it. We therefore maintain an 'optimal' sample 2-tuple, \\f$ ( \\hat{T}, \\hat{\\theta} ) \\f$, which serve as our\n/// current estimate for the 'true' tracks. After drawing each sample from the joint distribution, we compare the value\n/// of the distribution at that point to that of our 'best' sample. If the newly drawn sample has a higher posterior\n/// than the current best one, replace the best sample with the one just drawn.\n///\n/// Details of precisely how these samples are drawn and the mathematical model we use can be found elsewhere in the\n/// documentation as indicated by the 'see also' section below.\n///\n/// @sa biggles::model\n/// @sa biggles::partition\n/// @sa biggles::sampling\n/// @sa biggles::track\n/// @sa sampling::gibbs_sampler\n///\nclass tracker : public sampling::new_gibbs_sampler {\npublic:\n    /// @brief Default constructor.\n    tracker();\n\n    tracker(const tracker& t);\n    /// @brief Initialise the tracker with an initial set of model parameters and partition.\n    ///\n    /// @param initial_parameters\n    /// @param initial_partition\n    tracker(const model::parameters& initial_parameters,\n            const partition_ptr_t& initial_partition);\n\n    /// @brief Copy constructor.\n    ///\n    /// @param t\n\n    /// @brief Advance the tracking algorithm one step.\n    ///\n    /// This draws a single sample for \\f$ (T, \\theta) \\f$ and performs the necessary bookkeeping to maintain the 'best'\n    /// sample.\n    void advance();\n\n    /// @brief Equivalent to calling advance().\n    void operator () () { advance(); }\n\n    /// @name Access to the current tracker state\n    /// @{\n\n    /// @brief The number of iterations performed for the algorithm.\n    size_t n_iterations() const { return n_iterations_; }\n\n    /// @brief The last value of \\f$ T \\f$ drawn by the sampler.\n    const partition_ptr_t last_partition() const { return last_partition_sample().partition_sample_ptr; }\n\n    /// @brief The last move type accepted by the partition sampler.\n    const mh_moves::move_type last_move_type() const {\n        return last_proposal_accepted() ? last_partition_sample().executed_move : mh_moves::NONE;\n    }\n\n    /// @brief The last value of \\f$ \\theta \\f$ drawn by the sampler.\n    const model::parameters& last_parameters() const { return last_sample().get<1>(); }\n\n    /// @brief The last value of \\f$ P(T | \\theta) \\f$ for the last sample drawn.\n    float last_log_pdf() const\n        { return underlying_partition_sampler().current_sample_log_density(); }\n\n    /// \\brief the current state of the Metropolis Hastings sampler\n    sampling::mh_state_observer mh_state() const {\n        return underlying_partition_sampler().current_state();\n    }\n\n    internal_containers_observer mh_internals() const {\n        return underlying_partition_sampler().current_internals();\n    }\n\n    /// @brief The current best estimate of the true partition.\n    const partition_ptr_t best_partition() const { return best_partition_; }\n\n    /// @brief The current best estimate of the true model parameters.\n    const model::parameters& best_parameters() const { return best_parameters_; }\n\n    /// @brief The current value of \\f$ P(\\hat{T} | \\hat{\\theta}) \\f$.\n    float best_log_pdf() const { return best_log_pdf_; }\n\n    float acceptance_rate() const\n        { return underlying_partition_sampler().acceptance_rate(); }\n\n    void set_partition_is_valid(bool v)\n        { underlying_partition_sampler().set_partition_is_valid(v); }\n\n    bool last_proposal_accepted() const\n        { return underlying_partition_sampler().last_proposal_accepted(); }\n\n    /// \\brief the partition that was proposed in the latest sample (accepted or not)\n    const partition_ptr_t last_proposal_partition() const {\n        return underlying_partition_sampler().proposed_sample().partition_sample_ptr;\n    }\n    /// \\brief the move that was proposed in the latest sample (accepted or not)\n    mh_moves::move_type last_proposal_move() const {\n        return underlying_partition_sampler().proposed_sample().proposed_move;\n    }\n    partition_sampler_sample last_proposed_sample() const {\n        return underlying_partition_sampler().proposed_sample();\n    }\n\n    /// \\brief the proposal density of the last proposal\n    float last_proposal_density() const {\n        return underlying_partition_sampler().last_log_density();\n    }\n\n    /// \\brief the PDR of the last MH comparision\n    float last_pdr() const {\n        return underlying_partition_sampler().last_pdr();\n    }\n\n    /// \\brief the recent acceptance rate\n    float recent_acceptance_rate() const {\n        return underlying_partition_sampler().recent_acceptance_rate();\n    }\n\n    /// \\brief the log alpha of the last MH comparision\n    float last_log_alpha() const {\n        return underlying_partition_sampler().last_log_alpha();\n    }\n\n    /// @brief Return a reference to the histogram of accepted move types.\n    const std::deque<uint64_t>& move_histogram() const { return move_hist_; }\n\n    /// @brief Return a reference to the data of move type statistics (a/r/i).\n    const move_stats_t& move_statistics() const { return move_stats_; }\n\n    void set_temperature(float temperature) { underlying_partition_sampler().set_temperature(temperature); }\n\n    /// @}\n\n    /// @brief Assignment operator.\n    ///\n    /// @param t The tracker to copy state from.\n    ///\n    /// @return A reference to \\c *this.\n    const tracker& operator = (const tracker& t);\n\nprotected:\n    /// @brief The number of iterations which have currently been performed.\n    size_t n_iterations_;\n\n    /// @brief Our current estimate of \\f$ \\hat{T} \\f$.\n    partition_ptr_t best_partition_;\n\n    /// @brief Our current estimate of \\f$ \\hat{\\theta} \\f$.\n    model::parameters best_parameters_;\n\n    /// @brief The value of \\f$ P(T|\\theta) \\f$ for our current best estimate.\n    float best_log_pdf_;\n\n    /// @brief Histogram of accepted move types.\n    std::deque<uint64_t> move_hist_;\n\n    /// @brief data for move statistics ([a]ccepted/[r]ejected/[i]dentity)\n    move_stats_t move_stats_;\n\n    /// @brief Record an accepted move type in the move type histogram.\n    ///\n    /// @param mt\n    void record_move_type_(mh_moves::move_type mt);\n\n    /// @brief Record the the statistics ([a]ccepted/[r]ejected/[i]dentity) for each move.\n    ///\n    /// @param sample\n    void record_move_stats_(const partition_sampler_sample& sample);\n};\n\n}\n\n#endif // BIGGLES_TRACKER_HPP___\n", "meta": {"hexsha": "a3bfc84249b83d332833f5c5e67ae5b6576706bd", "size": 8885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/tracker.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/tracker.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/tracker.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9692982456, "max_line_length": 120, "alphanum_fraction": 0.703995498, "num_tokens": 2004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681805313639, "lm_q2_score": 0.029312232023305632, "lm_q1q2_score": 0.011609642404783842}}
{"text": "#include <memory>\n#include <iostream>\n#include <fstream>\n\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/mpi.h>\n\n#include \"framework/builder/framework_builder.h\"\n#include \"utility/reporter/mpi.h\"\n#include \"problem/parameters_dealii_handler.h\"\n\nint main(int argc, char* argv[]) {\n  try {\n    if (argc != 2) {\n      std::cerr\n          << \"Call the program as mpirun -np num_proc bart input_file_name\"\n          << std::endl;\n      return 1;\n    }\n\n    std::cout << \"BAY AREA RADIATION TRANSPORT\\n\"\n              << \"Developed at the University of California, Berkeley\"\n              << std::endl;\n\n    bart::problem::ParametersDealiiHandler prm;\n    dealii::ParameterHandler d2_prm;\n    const std::string filename{argv[1]};\n\n    prm.SetUp(d2_prm);\n    d2_prm.parse_input(filename, \"\");\n    prm.Parse(d2_prm);\n\n    dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n    double k_eff_final;\n\n    const int n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n    const int process_id = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n\n    // Open file for output, if there are multiple processes they will end with\n    // a number indicating the process number.\n    std::ofstream output_stream, master_output_stream;\n    const std::string output_filename_base{prm.OutputFilenameBase()};\n    if (n_processes > 1) {\n      const std::string full_filename = output_filename_base + dealii::Utilities::int_to_string(process_id, 4);\n      output_stream.open((full_filename + \".vtu\").c_str());\n      master_output_stream.open(output_filename_base + \".pvtu\");\n    } else {\n      output_stream.open((output_filename_base + \".vtu\").c_str());\n    }\n    std::vector<std::string> filenames;\n    // Write master pvtu record if multiple files are required\n    if ((n_processes > 1) && (process_id == 0)) {\n      for (int process = 0; process < n_processes; ++process) {\n        const std::string full_filename =\n            output_filename_base + dealii::Utilities::int_to_string(process, 4);\n        filenames.push_back(full_filename + \".vtu\");\n      }\n    }\n\n    auto reporter_ptr = std::make_shared<bart::utility::reporter::Mpi>(\n        std::make_unique<dealii::ConditionalOStream>(std::cout, process_id == 0));\n    switch(prm.SpatialDimension()) {\n      case 1: {\n        bart::framework::builder::FrameworkBuilder<1> builder(reporter_ptr);\n        auto framework_ptr = builder.BuildFramework(\"main\", prm);\n        framework_ptr->SolveSystem();\n        framework_ptr->OutputResults(output_stream);\n        if (n_processes > 1)\n          framework_ptr->OutputMasterFile(master_output_stream, filenames, process_id);\n        k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n        break;\n      }\n      case 2: {\n        bart::framework::builder::FrameworkBuilder<2> builder(reporter_ptr);\n        auto framework_ptr = builder.BuildFramework(\"main\", prm);\n        framework_ptr->SolveSystem();\n        framework_ptr->OutputResults(output_stream);\n        if (n_processes > 1)\n          framework_ptr->OutputMasterFile(master_output_stream, filenames, process_id);\n        k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n        break;\n      }\n      case 3: {\n        bart::framework::builder::FrameworkBuilder<3> builder(reporter_ptr);\n        auto framework_ptr = builder.BuildFramework(\"main\", prm);\n        framework_ptr->SolveSystem();\n        framework_ptr->OutputResults(output_stream);\n        if (n_processes > 1)\n          framework_ptr->OutputMasterFile(master_output_stream, filenames, process_id);\n        k_eff_final = framework_ptr->system()->k_effective.value_or(0);\n        break;\n      }\n    }\n\n    std::cout << \"Final k_effective: \" << k_eff_final << std::endl;\n\n  } catch (std::exception &exc) {\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    return 1;\n  } catch (...) {\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  return 0;\n}\n", "meta": {"hexsha": "c5988618a45d78ea1a00c4565c68ef5e14299373", "size": 4628, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "narang-amit/BART", "max_stars_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "narang-amit/BART", "max_issues_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_issues_repo_licenses": ["MIT"], "max_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": "narang-amit/BART", "max_forks_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_forks_repo_licenses": ["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.2479338843, "max_line_length": 111, "alphanum_fraction": 0.6013396716, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748935136303, "lm_q2_score": 0.03258974723246831, "lm_q1q2_score": 0.011594613851267541}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n  =============================================================================*/\n\n/*!\n * \\file niftkConvertRawDICOMMammogramsToPresentation.cxx \n * \\page niftkConvertRawDICOMMammogramsToPresentation\n * \\section niftkConvertRawDICOMMammogramsToPresentationSummary niftkConvertRawDICOMMammogramsToPresentation\n * \n * Search for raw \"For Processing\" DICOM mammograms in a directory and convert them to \"For Presentation\" versions by calculating the logarithm of their intensities and then the inverse.\n *\n */\n\n\n#include <niftkFileHelper.h>\n#include <niftkConversionUtils.h>\n#include <itkCommandLineHelper.h>\n\n#include <itkCreatePositiveMammogram.h>\n\n#include <itkImage.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkNifTKImageIOFactory.h>\n#include <itkMetaDataDictionary.h>\n#include <itkMetaDataObject.h>\n#include <itkGDCMImageIO.h>\n#include <itkCastImageFilter.h>\n#include <itkMammogramFatSubtractionImageFilter.h>\n#include <itkMammogramMaskSegmentationImageFilter.h>\n\n#include <boost/filesystem/path.hpp>\n\n#include <vector>\n\n#include <niftkConvertRawDICOMMammogramsToPresentationCLP.h>\n\n\nnamespace fs = boost::filesystem;\n\ntypedef itk::MetaDataDictionary DictionaryType;\ntypedef itk::MetaDataObject< std::string > MetaDataStringType;\n\n\n\nstruct arguments\n{\n  std::string dcmDirectoryIn;\n  std::string dcmDirectoryOut;\n  std::string strAdd2Suffix;  \n\n  bool flgOverwrite;\n  bool flgRescaleIntensitiesToMaxRange;\n  bool flgVerbose;\n  bool flgFatSubtract;\n\n  std::string iterFilename;\n};\n\n\n// -------------------------------------------------------------------------\n// PrintDictionary()\n// -------------------------------------------------------------------------\n\nvoid PrintDictionary( DictionaryType &dictionary )\n{\n  DictionaryType::ConstIterator tagItr = dictionary.Begin();\n  DictionaryType::ConstIterator end = dictionary.End();\n   \n  while ( tagItr != end )\n  {\n    MetaDataStringType::ConstPointer entryvalue = \n      dynamic_cast<const MetaDataStringType *>( tagItr->second.GetPointer() );\n    \n    if ( entryvalue )\n    {\n      std::string tagkey = tagItr->first;\n      std::string tagID;\n      bool found =  itk::GDCMImageIO::GetLabelFromTag( tagkey, tagID );\n\n      std::string tagValue = entryvalue->GetMetaDataObjectValue();\n      \n      std::cout << tagkey << \" \" << tagID <<  \": \" << tagValue << std::endl;\n    }\n\n    ++tagItr;\n  }\n};\n\n\n// -------------------------------------------------------------------------\n// AddPresentationFileSuffix\n// -------------------------------------------------------------------------\n\nstd::string AddPresentationFileSuffix( std::string fileName, std::string strAdd2Suffix )\n{\n  std::string suffix;\n  std::string newSuffix;\n\n  if ( ( fileName.length() >= 4 ) && \n       ( fileName.substr( fileName.length() - 4 ) == std::string( \".dcm\" ) ) )\n  {\n    suffix = std::string( \".dcm\" );\n  }\n\n  else if ( ( fileName.length() >= 4 ) && \n            ( fileName.substr( fileName.length() - 4 ) == std::string( \".DCM\" ) ) )\n  {\n    suffix = std::string( \".DCM\" );\n  }\n\n  else if ( ( fileName.length() >= 6 ) && \n            ( fileName.substr( fileName.length() - 6 ) == std::string( \".dicom\" ) ) )\n  {\n    suffix = std::string( \".dicom\" );\n  }\n\n  else if ( ( fileName.length() >= 6 ) && \n            ( fileName.substr( fileName.length() - 6 ) == std::string( \".DICOM\" ) ) )\n  {\n    suffix = std::string( \".DICOM\" );\n  }\n\n  else if ( ( fileName.length() >= 4 ) && \n            ( fileName.substr( fileName.length() - 4 ) == std::string( \".IMA\" ) ) )\n  {\n    suffix = std::string( \".IMA\" );\n  }\n\n  std::cout << \"Suffix: '\" << suffix << \"'\" << std::endl;\n\n  newSuffix = strAdd2Suffix + suffix;\n\n  if ( ( fileName.length() >= newSuffix.length() ) && \n       ( fileName.substr( fileName.length() - newSuffix.length() ) != newSuffix ) )\n  {\n    return fileName.substr( 0, fileName.length() - suffix.length() ) + newSuffix;\n  }\n  else\n  {\n    return fileName;\n  }\n};\n\n\n// -------------------------------------------------------------------------\n// main()\n// -------------------------------------------------------------------------\n\ntemplate <class OutputPixelType>\nint DoMain(arguments args, OutputPixelType min, OutputPixelType max)\n{\n  float progress = 0.;\n  float iFile = 0.;\n  float nFiles;\n \n\n  // Get the list of files in the directory\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  std::vector< std::string > fileNames;\n  niftk::GetRecursiveFilesInDirectory( args.dcmDirectoryIn, fileNames );\n\n  nFiles = fileNames.size();\n\n\n  // Iterate through each file and convert it\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  std::string fileInputFullPath;\n  std::string fileInputRelativePath;\n  std::string fileOutputRelativePath;\n  std::string fileOutputFullPath;\n  std::string dirOutputFullPath;\n    \n  std::vector< std::string >::iterator iterFileNames;       \n\n  typedef float InternalPixelType;\n\n  const unsigned int   InputDimension = 2;\n\n  typedef itk::Image< InternalPixelType, InputDimension > InternalImageType; \n  typedef itk::Image< OutputPixelType, InputDimension > OutputImageType;\n\n  typedef itk::RescaleIntensityImageFilter< InternalImageType, InternalImageType > RescalerType;\n  typedef itk::CastImageFilter< InternalImageType, OutputImageType > CastingFilterType;\n \n  typedef itk::ImageFileReader< InternalImageType > ReaderType;\n  typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n\n  ReaderType::Pointer reader = ReaderType::New();\n  InternalImageType::Pointer image;\n\n  typedef itk::GDCMImageIO           ImageIOType;\n  ImageIOType::Pointer gdcmImageIO = ImageIOType::New();\n\n  progress = iFile/nFiles;\n  std::cout << \"<filter-progress>\" << std::endl\n            << progress << std::endl\n            << \"</filter-progress>\" << std::endl;\n\n  // Read the image\n\n  reader->SetImageIO( gdcmImageIO );\n  reader->SetFileName( args.iterFilename );\n    \n  try\n  {\n    reader->UpdateLargestPossibleRegion();\n  }\n\n  catch (itk::ExceptionObject &ex)\n  {\n    std::cout << \"Skipping file (not DICOM?): \" << args.iterFilename << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  std::cout << \"File: \" << args.iterFilename << std::endl;\n\n  image = reader->GetOutput();\n  image->DisconnectPipeline();\n\n  DictionaryType dictionary = image->GetMetaDataDictionary();\n  \n\n  // Convert a raw DICOM mammogram to a presentation version by log inverting it\n\n  if ( ! itk::ConvertMammogramFromRawToPresentation< InternalImageType >( image, \n                                                                          dictionary ) )\n  {\n    return EXIT_FAILURE;\n  }\n\n\n\n  // Fat subtract the image?\n\n  if ( args.flgFatSubtract )\n  {\n    // First compute the mask\n\n    typedef unsigned char MaskPixelType;\n    typedef itk::Image< MaskPixelType, InputDimension > MaskImageType;   \n\n    typedef itk::MammogramMaskSegmentationImageFilter<InternalImageType, MaskImageType> \n      MammogramMaskSegmentationImageFilterType;\n\n    typename MammogramMaskSegmentationImageFilterType::Pointer \n      maskFilter = MammogramMaskSegmentationImageFilterType::New();\n\n    maskFilter->SetInput( image );\n\n    maskFilter->SetVerbose( args.flgVerbose );\n\n    maskFilter->SetIncludeBorderRegion( true );\n\n    try {\n      maskFilter->Update();\n    }\n    catch( itk::ExceptionObject & err ) \n    { \n      std::cerr << \"ERROR: Failed to segment image\" << std::endl\n                << err << std::endl; \n      return EXIT_FAILURE;\n    }                \n\n    typename MaskImageType::Pointer mask = maskFilter->GetOutput();\n\n    mask->DisconnectPipeline();\n    \n    // Then calculate the fat subtracted image\n\n    typedef itk::MammogramFatSubtractionImageFilter<InternalImageType> \n      MammogramFatSubtractionImageFilterType;\n\n    typename MammogramFatSubtractionImageFilterType::Pointer \n      fatFilter = MammogramFatSubtractionImageFilterType::New();\n\n    fatFilter->SetInput( image );  \n\n    fatFilter->SetVerbose( args.flgVerbose );\n\n    fatFilter->SetComputeFatEstimationFit( true );\n\n    fatFilter->SetMask( mask );\n  \n    try\n    {\n      fatFilter->Update(); \n    }\n    catch( itk::ExceptionObject & err ) \n    { \n      std::cerr << \"ERROR: Failed to calculate the fat subtraction: \" << err << std::endl; \n      return EXIT_FAILURE;\n    }                \n    \n    image = fatFilter->GetOutput( 0 );\n    image->DisconnectPipeline();\n  }\n\n\n  // Rescale the image to the maximum range\n\n  if ( args.flgRescaleIntensitiesToMaxRange )\n  {\n    itksys_ios::ostringstream value;\n\n    typename RescalerType::Pointer intensityRescaler = RescalerType::New();\n  \n    intensityRescaler->SetOutputMinimum( min );\n    intensityRescaler->SetOutputMaximum( max );\n\n    // Set the pixel intensity relationship sign to linear\n    value.str(\"\");\n    value << \"LIN\";\n    itk::EncapsulateMetaData<std::string>(dictionary,\"0028|1040\", value.str());\n\n    // Set the pixel intensity relationship sign to one\n    value.str(\"\");\n    value << 1;\n    itk::EncapsulateMetaData<std::string>(dictionary,\"0028|1041\", value.str());\n\n    // Set the new window centre tag value\n    value.str(\"\");\n    value << max / 2;\n    itk::EncapsulateMetaData<std::string>(dictionary,\"0028|1050\", value.str());\n\n    // Set the new window width tag value\n    value.str(\"\");\n    value << max;\n    itk::EncapsulateMetaData<std::string>(dictionary,\"0028|1051\", value.str());\n\n    // Set the rescale intercept and slope to zero and one \n    value.str(\"\");\n    value << 0;\n    itk::EncapsulateMetaData<std::string>(dictionary, \"0028|1052\", value.str());\n    value.str(\"\");\n    value << 1;\n    itk::EncapsulateMetaData<std::string>(dictionary, \"0028|1053\", value.str());\n\n    intensityRescaler->UpdateLargestPossibleRegion();\n\n    image = intensityRescaler->GetOutput();\n    image->DisconnectPipeline();\n  }\n\n\n  // Cast to the output type\n\n  typename CastingFilterType::Pointer caster = CastingFilterType::New();\n\n  caster->SetInput( image );\n\n  caster->UpdateLargestPossibleRegion();\n\n\n  // Create the output image filename\n\n  fileInputFullPath = args.iterFilename;\n\n  fileInputRelativePath = fileInputFullPath.substr( args.dcmDirectoryIn.length() );\n     \n  fileOutputRelativePath = AddPresentationFileSuffix( fileInputRelativePath,\n                                                      args.strAdd2Suffix );\n    \n  fileOutputFullPath = niftk::ConcatenatePath( args.dcmDirectoryOut, \n                                               fileOutputRelativePath );\n\n  dirOutputFullPath = fs::path( fileOutputFullPath ).branch_path().string();\n    \n  if ( ! niftk::DirectoryExists( dirOutputFullPath ) )\n  {\n    niftk::CreateDirAndParents( dirOutputFullPath );\n  }\n      \n  std::cout << \"Input relative filename: \" << fileInputRelativePath << std::endl\n            << \"Output relative filename: \" << fileOutputRelativePath << std::endl\n            << \"Output directory: \" << dirOutputFullPath << std::endl;\n\n\n  // Write the image to the output file\n\n  if ( niftk::FileIsRegular( fileOutputFullPath ) && ( ! args.flgOverwrite ) )\n  {\n    std::cerr << std::endl << \"ERROR: File \" << fileOutputFullPath << \" exists\"\n              << std::endl << \"       and can't be overwritten. Consider option: 'overwrite'.\"\n              << std::endl << std::endl;\n    return EXIT_FAILURE;\n  }\n  else\n  {\n  \n    if ( args.flgVerbose )\n    {\n      PrintDictionary( dictionary );\n    }\n\n    typename WriterType::Pointer writer = WriterType::New();\n\n    typename OutputImageType::Pointer outImage = caster->GetOutput();\n\n    writer->SetFileName( fileOutputFullPath );\n\n    outImage->DisconnectPipeline();\n    writer->SetInput( outImage );\n\n    gdcmImageIO->SetMetaDataDictionary( dictionary );\n    gdcmImageIO->KeepOriginalUIDOn( );\n    writer->SetImageIO( gdcmImageIO );\n\n    writer->UseInputMetaDataDictionaryOff();\n\n    try\n    {\n      std::cout << \"Writing image to file: \" << fileOutputFullPath << std::endl;\n      writer->Update();\n    }\n    catch (itk::ExceptionObject & e)\n    {\n      std::cerr << \"ERROR: Failed to write image: \" << std::endl << e << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n\n  std::cout << std::endl;\n\n\n  return EXIT_SUCCESS;\n}\n\n\n\n// -------------------------------------------------------------------------\n// main()\n// -------------------------------------------------------------------------\n\nint main( int argc, char *argv[] )\n{\n  itk::NifTKImageIOFactory::Initialize();\n\n  float progress = 0.;\n  float iFile = 0.;\n  float nFiles;\n\n  struct arguments args;\n\n  // Validate command line args\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  PARSE_ARGS;\n\n  if ( dcmDirectoryIn.length() == 0 )\n  {\n    commandLine.getOutput()->usage(commandLine);\n    std::cerr << \"ERROR: The input directory must be specified\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  if ( dcmDirectoryOut.length() == 0 )\n  {\n    dcmDirectoryOut = dcmDirectoryIn;\n  }\n\n  args.dcmDirectoryIn  = dcmDirectoryIn;                     \n  args.dcmDirectoryOut = dcmDirectoryOut;                    \n\n  args.strAdd2Suffix = strAdd2Suffix;                      \n\t\t\t\t   \t                                                 \n  args.flgOverwrite   = flgOverwrite;                       \n  args.flgVerbose     = flgVerbose;    \n  args.flgFatSubtract = flgFatSubtract;\n\n  args.flgRescaleIntensitiesToMaxRange = flgRescaleIntensitiesToMaxRange;\n\n\n  std::cout << std::endl << \"Examining directory: \" \n\t    << args.dcmDirectoryIn << std::endl << std::endl;\n\n\n  // Get the list of files in the directory\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  std::vector< std::string > fileNames;\n  std::vector< std::string >::iterator iterFileNames;       \n\n  niftk::GetRecursiveFilesInDirectory( dcmDirectoryIn, fileNames );\n\n  nFiles = fileNames.size();\n\n  for ( iterFileNames = fileNames.begin(); \n\titerFileNames < fileNames.end(); \n\t++iterFileNames, iFile += 1. )\n  {\n    args.iterFilename = *iterFileNames;\n    \n    std::cout << \"File: \" << args.iterFilename << std::endl;\n\n    progress = iFile/nFiles;\n    std::cout << \"<filter-progress>\" << std::endl\n\t      << progress << std::endl\n\t      << \"</filter-progress>\" << std::endl;\n\n  \n    itk::ImageIOBase::Pointer imageIO;\n    imageIO = itk::ImageIOFactory::CreateImageIO(args.iterFilename.c_str(), \n\t\t\t\t\t\t itk::ImageIOFactory::ReadMode);\n\n    if ( ( ! imageIO ) || ( ! imageIO->CanReadFile( args.iterFilename.c_str() ) ) )\n    {\n      std::cerr << \"WARNING: Unrecognised image type, skipping file: \" \n\t\t<< args.iterFilename << std::endl;\n      continue;\n    }\n\n\n    int result;\n\n    switch (itk::PeekAtComponentType(args.iterFilename))\n    {\n    case itk::ImageIOBase::UCHAR:\n      result = DoMain<unsigned char>( args,\n                                      itk::NumericTraits<unsigned char>::ZeroValue(),\n                                      itk::NumericTraits<unsigned char>::max() );  \n      break;\n    \n    case itk::ImageIOBase::CHAR:\n      result = DoMain<char>( args,\n                             itk::NumericTraits<char>::ZeroValue(),\n                             itk::NumericTraits<char>::max() );  \n      break;\n\n    case itk::ImageIOBase::USHORT:\n      result = DoMain<unsigned short>( args,\n                                       itk::NumericTraits<unsigned short>::ZeroValue(),\n                                       static_cast<unsigned short>( 32767 ) );\n      break;\n\n    case itk::ImageIOBase::SHORT:\n      result = DoMain<short>( args,\n                              itk::NumericTraits<short>::ZeroValue(),\n                              static_cast<short>( 32767 ) );  \n      break;\n\n    case itk::ImageIOBase::UINT:\n      result = DoMain<unsigned int>( args,\n                                     itk::NumericTraits<unsigned int>::ZeroValue(),\n                                     static_cast<unsigned int>( 32767 ) );  \n      break;\n\n    case itk::ImageIOBase::INT:\n      result = DoMain<int>( args,\n                            itk::NumericTraits<int>::ZeroValue(),\n                            static_cast<int>( 32767 ) );  \n      break;\n\n    case itk::ImageIOBase::ULONG:\n      result = DoMain<unsigned long>( args,\n                                      itk::NumericTraits<unsigned long>::ZeroValue(),\n                                      static_cast<unsigned long>( 32767 ) );  \n      break;\n\n    case itk::ImageIOBase::LONG:\n      result = DoMain<long>( args,\n                             itk::NumericTraits<long>::ZeroValue(),\n                             static_cast<long>( 32767 ) );  \n      break;\n\n    case itk::ImageIOBase::FLOAT:\n      result = DoMain<float>( args,\n                              itk::NumericTraits<float>::ZeroValue(),\n                              static_cast<float>( 32767 ) );  \n      break;\n\n    case itk::ImageIOBase::DOUBLE:\n      result = DoMain<double>( args,\n                               itk::NumericTraits<double>::ZeroValue(),\n                               static_cast<double>( 32767 ) );  \n      break;\n\n    default:\n      std::cerr << \"WARNING: Unrecognised pixel type, skipping file: \" \n\t\t<< args.iterFilename << std::endl;\n    }\n\n    std::cout << std::endl;\n  }\n\n  return EXIT_SUCCESS;\n}\n \n \n\n", "meta": {"hexsha": "c5a03238c0dcc60bdce2bdeb6d16427c5b41c649", "size": 17360, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Applications/ConvertRawDICOMMammogramsToPresentation/niftkConvertRawDICOMMammogramsToPresentation.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "Applications/ConvertRawDICOMMammogramsToPresentation/niftkConvertRawDICOMMammogramsToPresentation.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Applications/ConvertRawDICOMMammogramsToPresentation/niftkConvertRawDICOMMammogramsToPresentation.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 28.7417218543, "max_line_length": 186, "alphanum_fraction": 0.5939516129, "num_tokens": 4077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.03358950286876969, "lm_q1q2_score": 0.011591914488866997}}
{"text": "/*\n * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n//\n// calculates overlap integrals for molecular orbitals using libmoo\n// moo_overlap  --pos1 <coordinate file for mol1>\n//              --pos2 <coordinate file for mol2>\n//\t\t--conjseg <xml file defining conjugated segments>\n//\t\t--pdb geometry in which electronic coupling si calculated\n\n#include <boost/program_options.hpp>\n#include <string>\n#include <votca/moo/jcalc.h>\n#include <votca/moo/crgunit.h>\n#include <votca/tools/application.h>\n#include <votca/tools/globals.h>\n\nusing namespace std;\nusing namespace votca::moo;\n\nclass MOOApplication\n\t: public Application\n{\npublic:\n\t    virtual string ProgramName() { return \"moo_overlap\"; }\n\t    virtual void HelpText(std::ostream &out) { };\n\t    void Initialize();\n\t    bool EvaluateOptions();\n\t    void Run(void);\nprotected: \t\t\n\t    string _conjseg, _pos1, _pos2, _pdbfile;\n};\n\nvoid MOOApplication::Initialize()\n{\n\t// read in program options\n\tnamespace po = boost::program_options;\n\tAddProgramOptions(\"MOO Options\")\n\t\t(\"conjseg\", po::value<string>(), \" xml file describing two conjugated segments\")\n\t\t(\"pos1\", po::value<string>(), \" position and orientation of molecule 1\")\n\t\t(\"pos2\", po::value<string>(), \" position and orientation of molecule 2\")\t\t\n\t\t(\"pdb\", po::value<string>()->default_value(\"geometry.pdb\"), \" pdb file of two molecules\")\t\t\n\t\t; \n}\n\nbool MOOApplication::EvaluateOptions()\n{\n\tCheckRequired(\"conjseg\");\n\t _conjseg = OptionsMap()[\"conjseg\"].as<string>();\n\t _pos1 = OptionsMap()[\"pos1\"].as<string>();\n\t _pos2 = OptionsMap()[\"pos2\"].as<string>();\n\t _pdbfile = OptionsMap()[\"pdb\"].as<string>();\n\treturn true;\n}\n\nvoid MOOApplication::Run(void)\n{\n        //cout << \"Reading Crg unit Types\" << endl;\n        JCalc jcalc(_conjseg);\n        //cout << \"Finished reading Crg unit Types\" << endl;\n\n        ifstream in1(_pos1.c_str());\n        ifstream in2(_pos2.c_str());\n        int written=0;\n        while (in1 && in2) {\n            string name1, name2;\n            vec com1;\n            vec com2;\n            matrix or1;\n            matrix or2;\n            in1 >> name1 >> com1.x() >> com1.y() >> com1.z() >>\n                    or1[0][0] >> or1[0][1] >> or1[0][2] >>\n                    or1[1][0] >> or1[1][1] >> or1[1][2] >>\n                    or1[2][0] >> or1[2][1] >> or1[2][2];\n            in2 >> name2 >> com2.x() >> com2.y() >> com2.z() >>\n                    or2[0][0] >> or2[0][1] >> or2[0][2] >>\n                    or2[1][0] >> or2[1][1] >> or2[1][2] >>\n                    or2[2][0] >> or2[2][1] >> or2[2][2];\n\n            if (!in1 || !in2) break;\n\n            if (globals::verbose) {\n             \tcout << \"molecule A: \" << name1 << endl\n                     << \" translated by: \" << com1 << endl \n                     << \" rotated by: \" << endl << or1 << endl;\n                \n            \tcout << \"molecule B: \" << name2 << endl \n                     << \"translated by: \" << com2 << endl \n                     << \"rotated by: \" << endl << or2 << endl;\n            }\n\n            CrgUnit * A = jcalc.CreateCrgUnit(0, name1);\n            CrgUnit * B = jcalc.CreateCrgUnit(1, name2);\n            \n            A->SetPos(0, com1);           \n            A->SetNorm(0, or1[2]);\n            A->SetPlane(0, or1[1]);\n            \n            if (globals::verbose) {\n                cout << \"molecule A: \" << A->getName()  \n                 << \" position: \" <<  A->GetPos(0) \n                 << \" norm: \" << A->GetNorm(0) \n                 << \" plane: \" << A->GetPlane(0) << endl;\n            }\n            \n            B->SetPos(0, com2);\n            B->SetNorm(0, or2[2]);\n            B->SetPlane(0, or2[1]);\n            \n            if (globals::verbose) {\n                cout << \"molecule B: \" << B->getName()  \n                 << \" position: \" <<  B->GetPos(0) \n                 << \" norm: \" << B->GetNorm(0) \n                 << \" plane: \" << B->GetPlane(0) << endl;\n            }\n            \n           //write pdb file\n           mol_and_orb *molecule = ( A -> rotate_translate_beads() );\n           (*molecule).write_pdb(_pdbfile, \"m1\", written);\n           written += (*molecule).getN();\n           delete molecule;\n           molecule = ( B -> rotate_translate_beads() );\n           (*molecule).write_pdb(_pdbfile, \"m2\", written);\n           written += (*molecule).getN();\n           delete molecule;\n           ofstream fl;\n           fl.open(_pdbfile.c_str(), ios::app);\n           fl.setf(ios::fixed);\n           fl << \"END\" <<endl;\n\n           \n            //\tcout << \"Compute J\" <<endl;\n            vector <double> Js = jcalc.CalcJ(*A, *B);\n            //\tcout << \"Finished computing J\" <<endl;\n            vector <double>::iterator itJ = Js.begin();\n            for (; itJ != Js.end(); ++itJ) cout << '\\t' << *itJ << endl;\n\t};\n}\n\nint main(int argc, char **argv)\n{\n\tMOOApplication app;\n\treturn app.Exec(argc, argv);\n}\n", "meta": {"hexsha": "59e71cff6ce2cd90f5198ea167d0ca291ff31769", "size": 5445, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tools/moo_overlap.cc", "max_stars_repo_name": "jimbach/ctp", "max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "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/tools/moo_overlap.cc", "max_issues_repo_name": "jimbach/ctp", "max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/moo_overlap.cc", "max_forks_repo_name": "jimbach/ctp", "max_forks_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "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.2452830189, "max_line_length": 93, "alphanum_fraction": 0.5215794307, "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.025565211603193007, "lm_q1q2_score": 0.011587735056167654}}
{"text": "//\r\n//=======================================================================\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//\r\n\r\n#ifndef BOOST_GRAPH_STRONG_COMPONENTS_HPP\r\n#define BOOST_GRAPH_STRONG_COMPONENTS_HPP\r\n\r\n#include <stack>\r\n#include <boost/config.hpp>\r\n#include <boost/graph/depth_first_search.hpp>\r\n#include <boost/type_traits/conversion_traits.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/graph/overloading.hpp>\r\n#include <boost/graph/detail/mpi_include.hpp>\r\n#include <boost/concept/assert.hpp>\r\n\r\nnamespace boost\r\n{\r\n\r\n//==========================================================================\r\n// This is Tarjan's algorithm for strongly connected components\r\n// from his paper \"Depth first search and linear graph algorithms\".\r\n// It calculates the components in a single application of DFS.\r\n// We implement the algorithm as a dfs-visitor.\r\n\r\nnamespace detail\r\n{\r\n\r\n    template < typename ComponentMap, typename RootMap, typename DiscoverTime,\r\n        typename Stack >\r\n    class tarjan_scc_visitor : public dfs_visitor<>\r\n    {\r\n        typedef typename property_traits< ComponentMap >::value_type comp_type;\r\n        typedef typename property_traits< DiscoverTime >::value_type time_type;\r\n\r\n    public:\r\n        tarjan_scc_visitor(ComponentMap comp_map, RootMap r, DiscoverTime d,\r\n            comp_type& c_, Stack& s_)\r\n        : c(c_)\r\n        , comp(comp_map)\r\n        , root(r)\r\n        , discover_time(d)\r\n        , dfs_time(time_type())\r\n        , s(s_)\r\n        {\r\n        }\r\n\r\n        template < typename Graph >\r\n        void discover_vertex(\r\n            typename graph_traits< Graph >::vertex_descriptor v, const Graph&)\r\n        {\r\n            put(root, v, v);\r\n            put(comp, v, (std::numeric_limits< comp_type >::max)());\r\n            put(discover_time, v, dfs_time++);\r\n            s.push(v);\r\n        }\r\n        template < typename Graph >\r\n        void finish_vertex(\r\n            typename graph_traits< Graph >::vertex_descriptor v, const Graph& g)\r\n        {\r\n            typename graph_traits< Graph >::vertex_descriptor w;\r\n            typename graph_traits< Graph >::out_edge_iterator ei, ei_end;\r\n            for (boost::tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei)\r\n            {\r\n                w = target(*ei, g);\r\n                if (get(comp, w) == (std::numeric_limits< comp_type >::max)())\r\n                    put(root, v,\r\n                        this->min_discover_time(get(root, v), get(root, w)));\r\n            }\r\n            if (get(root, v) == v)\r\n            {\r\n                do\r\n                {\r\n                    w = s.top();\r\n                    s.pop();\r\n                    put(comp, w, c);\r\n                    put(root, w, v);\r\n                } while (w != v);\r\n                ++c;\r\n            }\r\n        }\r\n\r\n    private:\r\n        template < typename Vertex >\r\n        Vertex min_discover_time(Vertex u, Vertex v)\r\n        {\r\n            return get(discover_time, u) < get(discover_time, v) ? u : v;\r\n        }\r\n\r\n        comp_type& c;\r\n        ComponentMap comp;\r\n        RootMap root;\r\n        DiscoverTime discover_time;\r\n        time_type dfs_time;\r\n        Stack& s;\r\n    };\r\n\r\n    template < class Graph, class ComponentMap, class RootMap,\r\n        class DiscoverTime, class P, class T, class R >\r\n    typename property_traits< ComponentMap >::value_type strong_components_impl(\r\n        const Graph& g, // Input\r\n        ComponentMap comp, // Output\r\n        // Internal record keeping\r\n        RootMap root, DiscoverTime discover_time,\r\n        const bgl_named_params< P, T, R >& params)\r\n    {\r\n        typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n        BOOST_CONCEPT_ASSERT(\r\n            (ReadWritePropertyMapConcept< ComponentMap, Vertex >));\r\n        BOOST_CONCEPT_ASSERT((ReadWritePropertyMapConcept< RootMap, Vertex >));\r\n        typedef typename property_traits< RootMap >::value_type RootV;\r\n        BOOST_CONCEPT_ASSERT((ConvertibleConcept< RootV, Vertex >));\r\n        BOOST_CONCEPT_ASSERT(\r\n            (ReadWritePropertyMapConcept< DiscoverTime, Vertex >));\r\n\r\n        typename property_traits< ComponentMap >::value_type total = 0;\r\n\r\n        std::stack< Vertex > s;\r\n        detail::tarjan_scc_visitor< ComponentMap, RootMap, DiscoverTime,\r\n            std::stack< Vertex > >\r\n            vis(comp, root, discover_time, total, s);\r\n        depth_first_search(g, params.visitor(vis));\r\n        return total;\r\n    }\r\n\r\n    //-------------------------------------------------------------------------\r\n    // The dispatch functions handle the defaults for the rank and discover\r\n    // time property maps.\r\n    // dispatch with class specialization to avoid VC++ bug\r\n\r\n    template < class DiscoverTimeMap > struct strong_comp_dispatch2\r\n    {\r\n        template < class Graph, class ComponentMap, class RootMap, class P,\r\n            class T, class R >\r\n        inline static typename property_traits< ComponentMap >::value_type\r\n        apply(const Graph& g, ComponentMap comp, RootMap r_map,\r\n            const bgl_named_params< P, T, R >& params, DiscoverTimeMap time_map)\r\n        {\r\n            return strong_components_impl(g, comp, r_map, time_map, params);\r\n        }\r\n    };\r\n\r\n    template <> struct strong_comp_dispatch2< param_not_found >\r\n    {\r\n        template < class Graph, class ComponentMap, class RootMap, class P,\r\n            class T, class R >\r\n        inline static typename property_traits< ComponentMap >::value_type\r\n        apply(const Graph& g, ComponentMap comp, RootMap r_map,\r\n            const bgl_named_params< P, T, R >& params, param_not_found)\r\n        {\r\n            typedef\r\n                typename graph_traits< Graph >::vertices_size_type size_type;\r\n            size_type n = num_vertices(g) > 0 ? num_vertices(g) : 1;\r\n            std::vector< size_type > time_vec(n);\r\n            return strong_components_impl(g, comp, r_map,\r\n                make_iterator_property_map(time_vec.begin(),\r\n                    choose_const_pmap(\r\n                        get_param(params, vertex_index), g, vertex_index),\r\n                    time_vec[0]),\r\n                params);\r\n        }\r\n    };\r\n\r\n    template < class Graph, class ComponentMap, class RootMap, class P, class T,\r\n        class R, class DiscoverTimeMap >\r\n    inline typename property_traits< ComponentMap >::value_type scc_helper2(\r\n        const Graph& g, ComponentMap comp, RootMap r_map,\r\n        const bgl_named_params< P, T, R >& params, DiscoverTimeMap time_map)\r\n    {\r\n        return strong_comp_dispatch2< DiscoverTimeMap >::apply(\r\n            g, comp, r_map, params, time_map);\r\n    }\r\n\r\n    template < class RootMap > struct strong_comp_dispatch1\r\n    {\r\n\r\n        template < class Graph, class ComponentMap, class P, class T, class R >\r\n        inline static typename property_traits< ComponentMap >::value_type\r\n        apply(const Graph& g, ComponentMap comp,\r\n            const bgl_named_params< P, T, R >& params, RootMap r_map)\r\n        {\r\n            return scc_helper2(g, comp, r_map, params,\r\n                get_param(params, vertex_discover_time));\r\n        }\r\n    };\r\n    template <> struct strong_comp_dispatch1< param_not_found >\r\n    {\r\n\r\n        template < class Graph, class ComponentMap, class P, class T, class R >\r\n        inline static typename property_traits< ComponentMap >::value_type\r\n        apply(const Graph& g, ComponentMap comp,\r\n            const bgl_named_params< P, T, R >& params, param_not_found)\r\n        {\r\n            typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n            typename std::vector< Vertex >::size_type n\r\n                = num_vertices(g) > 0 ? num_vertices(g) : 1;\r\n            std::vector< Vertex > root_vec(n);\r\n            return scc_helper2(g, comp,\r\n                make_iterator_property_map(root_vec.begin(),\r\n                    choose_const_pmap(\r\n                        get_param(params, vertex_index), g, vertex_index),\r\n                    root_vec[0]),\r\n                params, get_param(params, vertex_discover_time));\r\n        }\r\n    };\r\n\r\n    template < class Graph, class ComponentMap, class RootMap, class P, class T,\r\n        class R >\r\n    inline typename property_traits< ComponentMap >::value_type scc_helper1(\r\n        const Graph& g, ComponentMap comp,\r\n        const bgl_named_params< P, T, R >& params, RootMap r_map)\r\n    {\r\n        return detail::strong_comp_dispatch1< RootMap >::apply(\r\n            g, comp, params, r_map);\r\n    }\r\n\r\n} // namespace detail\r\n\r\ntemplate < class Graph, class ComponentMap, class P, class T, class R >\r\ninline typename property_traits< ComponentMap >::value_type strong_components(\r\n    const Graph& g, ComponentMap comp,\r\n    const bgl_named_params< P, T, R >& params BOOST_GRAPH_ENABLE_IF_MODELS_PARM(\r\n        Graph, vertex_list_graph_tag))\r\n{\r\n    typedef typename graph_traits< Graph >::directed_category DirCat;\r\n    BOOST_STATIC_ASSERT(\r\n        (is_convertible< DirCat*, directed_tag* >::value == true));\r\n    return detail::scc_helper1(\r\n        g, comp, params, get_param(params, vertex_root_t()));\r\n}\r\n\r\ntemplate < class Graph, class ComponentMap >\r\ninline typename property_traits< ComponentMap >::value_type strong_components(\r\n    const Graph& g,\r\n    ComponentMap comp BOOST_GRAPH_ENABLE_IF_MODELS_PARM(\r\n        Graph, vertex_list_graph_tag))\r\n{\r\n    typedef typename graph_traits< Graph >::directed_category DirCat;\r\n    BOOST_STATIC_ASSERT(\r\n        (is_convertible< DirCat*, directed_tag* >::value == true));\r\n    bgl_named_params< int, int > params(0);\r\n    return strong_components(g, comp, params);\r\n}\r\n\r\ntemplate < typename Graph, typename ComponentMap, typename ComponentLists >\r\nvoid build_component_lists(const Graph& g,\r\n    typename graph_traits< Graph >::vertices_size_type num_scc,\r\n    ComponentMap component_number, ComponentLists& components)\r\n{\r\n    components.resize(num_scc);\r\n    typename graph_traits< Graph >::vertex_iterator vi, vi_end;\r\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        components[component_number[*vi]].push_back(*vi);\r\n}\r\n\r\n} // namespace boost\r\n\r\n#include <queue>\r\n#include <vector>\r\n#include <boost/graph/transpose_graph.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/graph/connected_components.hpp> // for components_recorder\r\n\r\nnamespace boost\r\n{\r\n\r\n//==========================================================================\r\n// This is the version of strongly connected components from\r\n// \"Intro. to Algorithms\" by Cormen, Leiserson, Rivest, which was\r\n// adapted from \"Data Structure and Algorithms\" by Aho, Hopcroft,\r\n// and Ullman, who credit the algorithm to S.R. Kosaraju and M. Sharir.\r\n// The algorithm is based on computing DFS forests the graph\r\n// and its transpose.\r\n\r\n// This algorithm is slower than Tarjan's by a constant factor, uses\r\n// more memory, and puts more requirements on the graph type.\r\n\r\ntemplate < class Graph, class DFSVisitor, class ComponentsMap,\r\n    class DiscoverTime, class FinishTime, class ColorMap >\r\ntypename property_traits< ComponentsMap >::value_type\r\nkosaraju_strong_components(\r\n    Graph& G, ComponentsMap c, FinishTime finish_time, ColorMap color)\r\n{\r\n    BOOST_CONCEPT_ASSERT((MutableGraphConcept< Graph >));\r\n    // ...\r\n\r\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n    typedef typename property_traits< ColorMap >::value_type ColorValue;\r\n    typedef color_traits< ColorValue > Color;\r\n    typename property_traits< FinishTime >::value_type time = 0;\r\n    depth_first_search(G,\r\n        make_dfs_visitor(stamp_times(finish_time, time, on_finish_vertex())),\r\n        color);\r\n\r\n    Graph G_T(num_vertices(G));\r\n    transpose_graph(G, G_T);\r\n\r\n    typedef typename property_traits< ComponentsMap >::value_type count_type;\r\n\r\n    count_type c_count(0);\r\n    detail::components_recorder< ComponentsMap > vis(c, c_count);\r\n\r\n    // initialize G_T\r\n    typename graph_traits< Graph >::vertex_iterator ui, ui_end;\r\n    for (boost::tie(ui, ui_end) = vertices(G_T); ui != ui_end; ++ui)\r\n        put(color, *ui, Color::white());\r\n\r\n    typedef typename property_traits< FinishTime >::value_type D;\r\n    typedef indirect_cmp< FinishTime, std::less< D > > Compare;\r\n\r\n    Compare fl(finish_time);\r\n    std::priority_queue< Vertex, std::vector< Vertex >, Compare > Q(fl);\r\n\r\n    typename graph_traits< Graph >::vertex_iterator i, j, iend, jend;\r\n    boost::tie(i, iend) = vertices(G_T);\r\n    boost::tie(j, jend) = vertices(G);\r\n    for (; i != iend; ++i, ++j)\r\n    {\r\n        put(finish_time, *i, get(finish_time, *j));\r\n        Q.push(*i);\r\n    }\r\n\r\n    while (!Q.empty())\r\n    {\r\n        Vertex u = Q.top();\r\n        Q.pop();\r\n        if (get(color, u) == Color::white())\r\n        {\r\n            depth_first_visit(G_T, u, vis, color);\r\n            ++c_count;\r\n        }\r\n    }\r\n    return c_count;\r\n}\r\n\r\n} // namespace boost\r\n\r\n#include BOOST_GRAPH_MPI_INCLUDE(< boost / graph / distributed / strong_components.hpp >)\r\n\r\n#endif // BOOST_GRAPH_STRONG_COMPONENTS_HPP\r\n", "meta": {"hexsha": "28c77ac2412900c933480be1ffecc64c9406a7cb", "size": 13364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/strong_components.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/strong_components.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/strong_components.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 38.4022988506, "max_line_length": 90, "alphanum_fraction": 0.6072283747, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.028436030780608818, "lm_q1q2_score": 0.011582945101676116}}
{"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 followig 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#include \"ApplyTransformationToGeometry.h\"\n\n#include <Eigen/Dense>\n\n#include \"SIMPLib/Common/Constants.h\"\n#include \"SIMPLib/FilterParameters/AbstractFilterParametersReader.h\"\n#include \"SIMPLib/FilterParameters/DataArraySelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DataContainerSelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DynamicTableFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/FloatFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedChoicesFilterParameter.h\"\n#include \"SIMPLib/Geometry/EdgeGeom.h\"\n#include \"SIMPLib/Geometry/IGeometry2D.h\"\n#include \"SIMPLib/Geometry/IGeometry3D.h\"\n#include \"SIMPLib/Geometry/VertexGeom.h\"\n\n#include \"OrientationLib/OrientationMath/OrientationTransforms.hpp\"\n\n#include \"DREAM3DReview/DREAM3DReviewConstants.h\"\n#include \"DREAM3DReview/DREAM3DReviewVersion.h\"\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nApplyTransformationToGeometry::ApplyTransformationToGeometry()\n: m_ComputedTransformationMatrix(\"\", \"\", \"TransformationMatrix\")\n, m_GeometryToTransform(\"\")\n, m_TransformationMatrixType(1)\n{\n  m_RotationAngle = 0.0f;\n  m_RotationAxis[0] = 0.0f;\n  m_RotationAxis[1] = 0.0f;\n  m_RotationAxis[2] = 1.0f;\n\n  m_Translation[0] = 0.0f;\n  m_Translation[1] = 0.0f;\n  m_Translation[2] = 0.0f;\n\n  m_Scale[0] = 0.0f;\n  m_Scale[1] = 0.0f;\n  m_Scale[2] = 0.0f;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nApplyTransformationToGeometry::~ApplyTransformationToGeometry()\n= default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setupFilterParameters()\n{\n  FilterParameterVectorType parameters;\n  {\n    LinkedChoicesFilterParameter::Pointer parameter = LinkedChoicesFilterParameter::New();\n    parameter->setHumanLabel(\"Transformation Type\");\n    parameter->setPropertyName(\"TransformationMatrixType\");\n    parameter->setSetterCallback(SIMPL_BIND_SETTER(ApplyTransformationToGeometry, this, TransformationMatrixType));\n    parameter->setGetterCallback(SIMPL_BIND_GETTER(ApplyTransformationToGeometry, this, TransformationMatrixType));\n    QVector<QString> choices;\n    choices.push_back(\"No Transformation\");\n    choices.push_back(\"Pre-Computed Transformation Matrix\");\n    choices.push_back(\"Manual Transformation Matrix\");\n    choices.push_back(\"Rotation\");\n    choices.push_back(\"Translation\");\n    choices.push_back(\"Scale\");\n    parameter->setChoices(choices);\n    QStringList linkedProps = {\"ComputedTransformationMatrix\", \"ManualTransformationMatrix\", \"RotationAngle\", \"RotationAxis\", \"Translation\", \"Scale\"};\n    parameter->setLinkedProperties(linkedProps);\n    parameter->setEditable(false);\n    parameter->setCategory(FilterParameter::Parameter);\n    parameters.push_back(parameter);\n  }\n  {\n    QStringList rHeaders, cHeaders;\n    std::vector<std::vector<double>> defaultTable;\n    for(size_t i = 0; i < 4; i++)\n    {\n      std::vector<double> row(4, 0);\n      row[i] = 1.0;\n      defaultTable.push_back(row);\n    }\n    m_ManualTransformationMatrix.setTableData(defaultTable);\n    parameters.push_back(SIMPL_NEW_DYN_TABLE_FP(\"Transformation Matrix\", ManualTransformationMatrix, FilterParameter::Parameter, ApplyTransformationToGeometry, 2));\n  }\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Rotation Angle (Degrees)\", RotationAngle, FilterParameter::Parameter, ApplyTransformationToGeometry, 3));\n  parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP(\"Rotation Axis (ijk)\", RotationAxis, FilterParameter::Parameter, ApplyTransformationToGeometry, 3));\n  parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP(\"Translation\", Translation, FilterParameter::Parameter, ApplyTransformationToGeometry, 4));\n  parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP(\"Scale\", Scale, FilterParameter::Parameter, ApplyTransformationToGeometry, 5));\n  DataContainerSelectionFilterParameter::RequirementType dcReq;\n  IGeometry::Types geomTypes = {IGeometry::Type::Vertex, IGeometry::Type::Edge, IGeometry::Type::Triangle, IGeometry::Type::Quad, IGeometry::Type::Tetrahedral};\n  dcReq.dcGeometryTypes = geomTypes;\n  parameters.push_back(SIMPL_NEW_DC_SELECTION_FP(\"Geometry to Transform\", GeometryToTransform, FilterParameter::RequiredArray, ApplyTransformationToGeometry, dcReq));\n  {\n    DataArraySelectionFilterParameter::RequirementType dasReq =\n        DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Float, SIMPL::Defaults::AnyComponentSize, AttributeMatrix::Type::Generic, IGeometry::Type::Any);\n    parameters.push_back(SIMPL_NEW_DA_SELECTION_FP(\"Transformation Matrix\", ComputedTransformationMatrix, FilterParameter::RequiredArray, ApplyTransformationToGeometry, dasReq, 1));\n  }\n  setFilterParameters(parameters);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::readFilterParameters(AbstractFilterParametersReader* reader, int index)\n{\n  reader->openFilterGroup(this, index);\n  setManualTransformationMatrix(reader->readDynamicTableData(\"ManualTransformationMatrix\", getManualTransformationMatrix()));\n  setComputedTransformationMatrix(reader->readDataArrayPath(\"ComputedTransformationMatrix\", getComputedTransformationMatrix()));\n  setGeometryToTransform(reader->readDataArrayPath(\"GeometryToTransform\", getGeometryToTransform()));\n  setTransformationMatrixType(reader->readValue(\"TransformationMatrixType\", getTransformationMatrixType()));\n  setRotationAxis(reader->readFloatVec3(\"RotationAxis\", getRotationAxis()));\n  setRotationAngle(reader->readValue(\"RotationAngle\", getRotationAngle()));\n  setTranslation(reader->readFloatVec3(\"Translation\", getTranslation()));\n  setScale(reader->readFloatVec3(\"Scale\", getScale()));\n  reader->closeFilterGroup();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::dataCheck()\n{\n  clearErrorCode();\n  clearWarningCode();\n\n  IGeometry::Pointer igeom = getDataContainerArray()->getPrereqGeometryFromDataContainer<IGeometry, AbstractFilter>(this, getGeometryToTransform());\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  if(!std::dynamic_pointer_cast<IGeometry2D>(igeom) && !std::dynamic_pointer_cast<IGeometry3D>(igeom) && !std::dynamic_pointer_cast<VertexGeom>(igeom) && !std::dynamic_pointer_cast<EdgeGeom>(igeom))\n  {\n    QString ss =\n        QObject::tr(\"Geometry to transform must be an unstructured geometry (Vertex, Edge, Triangle, Quadrilateral, or Tetrahedral), but the type is %1\").arg(igeom->getGeometryTypeAsString());\n    setErrorCondition(-702, ss);\n  }\n\n  std::vector<size_t> cDims = {4, 4};\n\n  switch(getTransformationMatrixType())\n  {\n  case 0: // No-Op\n  {\n    QString ss = QObject::tr(\"No transformation has been selected, so this filter will perform no operations\");\n    setWarningCondition(-701, ss);\n  }\n  case 1: // Transformation matrix from array\n  {\n    m_TransformationMatrixPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<float>, AbstractFilter>(this, getComputedTransformationMatrix(), cDims);\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n    }\n    break;\n  }\n  case 2: // Manual transformation matrix\n  {\n    if(getManualTransformationMatrix().getNumRows() != 4)\n    {\n      QString ss = QObject::tr(\"Manually entered transformation matrix must have exactly 4 rows\");\n      setErrorCondition(-702, ss);\n      return;\n    }\n    if(getManualTransformationMatrix().getNumCols() != 4)\n    {\n      QString ss = QObject::tr(\"Manually entered transformation matrix must have exactly 4 columns\");\n      setErrorCondition(-703, ss);\n      return;\n    }\n    std::vector<std::vector<double>> tableData = getManualTransformationMatrix().getTableData();\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      for(size_t i = 0; i < tableData.size(); i++)\n      {\n        std::vector<double> row = tableData[i];\n        for(size_t j = 0; j < row.size(); j++)\n        {\n          m_TransformationMatrix[4 * i + j] = static_cast<float>(row[j]);\n        }\n      }\n    }\n    break;\n  }\n  case 3: // Rotation via axis-angle\n  {\n    float rotAngle = m_RotationAngle * SIMPLib::Constants::k_Pi / 180.0;\n    FOrientArrayType om(9);\n    FOrientTransformsType::ax2om(FOrientArrayType(m_RotationAxis[0], m_RotationAxis[1], m_RotationAxis[2], rotAngle), om);\n\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      for(size_t i = 0; i < 3; i++)\n      {\n        m_TransformationMatrix[4 * i + 0] = om[3 * i + 0];\n        m_TransformationMatrix[4 * i + 1] = om[3 * i + 1];\n        m_TransformationMatrix[4 * i + 2] = om[3 * i + 2];\n        m_TransformationMatrix[4 * i + 3] = 0.0f;\n      }\n      m_TransformationMatrix[4 * 3 + 3] = 1.0f;\n    }\n    break;\n  }\n  case 4: // Translation\n  {\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      m_TransformationMatrix[4 * 0 + 0] = 1.0f;\n      m_TransformationMatrix[4 * 1 + 1] = 1.0f;\n      m_TransformationMatrix[4 * 2 + 2] = 1.0f;\n      m_TransformationMatrix[4 * 0 + 3] = m_Translation[0];\n      m_TransformationMatrix[4 * 1 + 3] = m_Translation[1];\n      m_TransformationMatrix[4 * 2 + 3] = m_Translation[2];\n      m_TransformationMatrix[4 * 3 + 3] = 1.0f;\n    }\n    break;\n  }\n  case 5: // Scale\n  {\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      m_TransformationMatrix[4 * 0 + 0] = m_Scale[0];\n      m_TransformationMatrix[4 * 1 + 1] = m_Scale[1];\n      m_TransformationMatrix[4 * 2 + 2] = m_Scale[2];\n      m_TransformationMatrix[4 * 3 + 3] = 1.0f;\n    }\n    break;\n  }\n  default:\n  {\n    QString ss = QObject::tr(\"Invalid selection for transformation type\");\n    setErrorCondition(-701, ss);\n    break;\n  }\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::preflight()\n{\n  // These are the REQUIRED lines of CODE to make sure the filter behaves correctly\n  setInPreflight(true);              // Set the fact that we are preflighting.\n  emit preflightAboutToExecute();    // Emit this signal so that other widgets can do one file update\n  emit updateFilterParameters(this); // Emit this signal to have the widgets push their values down to the filter\n  dataCheck();                       // Run our DataCheck to make sure everthing is setup correctly\n  emit preflightExecuted();          // We are done preflighting this filter\n  setInPreflight(false);             // Inform the system this filter is NOT in preflight mode anymore.\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::applyTransformation()\n{\n  IGeometry::Pointer igeom = getDataContainerArray()->getDataContainer(m_GeometryToTransform)->getGeometry();\n\n  int64_t numVertices = 0;\n  float* vertices = nullptr;\n\n  if(IGeometry2D::Pointer igeom2D = std::dynamic_pointer_cast<IGeometry2D>(igeom))\n  {\n    numVertices = igeom2D->getNumberOfVertices();\n    vertices = igeom2D->getVertexPointer(0);\n  }\n  else if(IGeometry3D::Pointer igeom3D = std::dynamic_pointer_cast<IGeometry3D>(igeom))\n  {\n    numVertices = igeom3D->getNumberOfVertices();\n    vertices = igeom3D->getVertexPointer(0);\n  }\n  else if(VertexGeom::Pointer vertex = std::dynamic_pointer_cast<VertexGeom>(igeom))\n  {\n    numVertices = vertex->getNumberOfVertices();\n    vertices = vertex->getVertexPointer(0);\n  }\n  else if(EdgeGeom::Pointer edge = std::dynamic_pointer_cast<EdgeGeom>(igeom))\n  {\n    numVertices = edge->getNumberOfVertices();\n    vertices = vertex->getVertexPointer(0);\n  }\n  else\n  {\n    return;\n  }\n\n  typedef Eigen::Matrix<float, 4, 4, Eigen::RowMajor> ProjectiveMatrix;\n  Eigen::Map<ProjectiveMatrix> transformation(m_TransformationMatrix);\n\n  int64_t progIncrement = numVertices / 100;\n  int64_t prog = 1;\n  int64_t progressInt = 0;\n  int64_t counter = 0;\n\n  for(int64_t i = 0; i < numVertices; i++)\n  {\n    if(getCancel())\n    {\n      return;\n    }\n    Eigen::Vector4f position(vertices[3 * i + 0], vertices[3 * i + 1], vertices[3 * i + 2], 1);\n    Eigen::Vector4f transformedPosition = transformation * position;\n    std::memcpy(vertices + (3 * i), transformedPosition.data(), sizeof(float) * 3);\n\n    if(counter > prog)\n    {\n      progressInt = static_cast<int64_t>((static_cast<float>(counter) / numVertices) * 100.0f);\n      QString ss = QObject::tr(\"Transforming Geometry || %1% Completed\").arg(progressInt);\n      notifyStatusMessage(ss);\n      prog = prog + progIncrement;\n    }\n    counter++;\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::execute()\n{\n  clearErrorCode();\n  clearWarningCode();\n  dataCheck();\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n  if(getWarningCode() < 0)\n  {\n    return;\n  }\n\n  if(m_TransformationMatrixType == 0)\n  {\n    return;\n  }\n  \n  \n    applyTransformation();\n  \n\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nAbstractFilter::Pointer ApplyTransformationToGeometry::newFilterInstance(bool copyFilterParameters) const\n{\n  ApplyTransformationToGeometry::Pointer filter = ApplyTransformationToGeometry::New();\n  if(copyFilterParameters)\n  {\n    copyFilterParameterInstanceVariables(filter.get());\n  }\n  return filter;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ApplyTransformationToGeometry::getCompiledLibraryName() const\n{\n  return DREAM3DReviewConstants::DREAM3DReviewBaseName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ApplyTransformationToGeometry::getBrandingString() const\n{\n  return \"DREAM3DReview\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ApplyTransformationToGeometry::getFilterVersion() const\n{\n  QString version;\n  QTextStream vStream(&version);\n  vStream << DREAM3DReview::Version::Major() << \".\" << DREAM3DReview::Version::Minor() << \".\" << DREAM3DReview::Version::Patch();\n  return version;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ApplyTransformationToGeometry::getGroupName() const\n{\n  return DREAM3DReviewConstants::FilterGroups::DREAM3DReviewFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QUuid ApplyTransformationToGeometry::getUuid()\n{\n  return QUuid(\"{c681caf4-22f2-5885-bbc9-a0476abc72eb}\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ApplyTransformationToGeometry::getSubGroupName() const\n{\n  return DREAM3DReviewConstants::FilterSubGroups::RotationTransformationFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nconst QString ApplyTransformationToGeometry::getHumanLabel() const\n{\n  return \"Apply Transformation to Geometry\";\n}\n", "meta": {"hexsha": "3deae5fc6962ac356ade64c3cf3e613c38975853", "size": 19405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DREAM3DReviewFilters/ApplyTransformationToGeometry.cpp", "max_stars_repo_name": "tuks188/DREAM3DReview", "max_stars_repo_head_hexsha": "81e921fd70c7050df361bf8626136d1c29faffe9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DREAM3DReviewFilters/ApplyTransformationToGeometry.cpp", "max_issues_repo_name": "tuks188/DREAM3DReview", "max_issues_repo_head_hexsha": "81e921fd70c7050df361bf8626136d1c29faffe9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DREAM3DReviewFilters/ApplyTransformationToGeometry.cpp", "max_forks_repo_name": "tuks188/DREAM3DReview", "max_forks_repo_head_hexsha": "81e921fd70c7050df361bf8626136d1c29faffe9", "max_forks_repo_licenses": ["BSD-3-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.2872340426, "max_line_length": 198, "alphanum_fraction": 0.6357639784, "num_tokens": 4226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.0259573592699472, "lm_q1q2_score": 0.011564769824190453}}
{"text": "/*=============================================================================\n  Copyright (c) 2010-2016 Bolero MURAKAMI\n  https://github.com/bolero-MURAKAMI/Sprig\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 SPRIG_NTL_SIGNIFICANT_HPP\n#define SPRIG_NTL_SIGNIFICANT_HPP\n\n#include <sprig/config/config.hpp>\n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include <cstddef>\n#include <cmath>\n#include <string>\n#include <algorithm>\n#include <utility>\n#include <boost/range.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_float.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/mpl/or.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <sprig/external/ntl/zz.hpp>\n#include <sprig/external/ntl/rr.hpp>\n#include <sprig/math.hpp>\n#include <sprig/type_traits/is_call_copy_param.hpp>\n#include <sprig/type_traits/is_char_type.hpp>\n#include <sprig/type_traits/is_wchar_type.hpp>\n#include <sprig/type_traits/is_c_str.hpp>\n#include <sprig/type_traits/is_basic_string.hpp>\n#include <sprig/type_traits/c_str_element.hpp>\n#include <sprig/type_traits/remove_const_reference.hpp>\n#include <sprig/str_cast.hpp>\n#include <sprig/ntl/to_ZZ.hpp>\n#include <sprig/ntl/to_RR.hpp>\n\nnamespace sprig {\n\t//\n\t// significant\n\t//\n\ttemplate<typename T, typename Enable = void>\n\tclass significant {};\n\n\t//\n\t// significant_base\n\t//\n\ttemplate<typename T>\n\tclass significant_base {\n\tpublic:\n\t\ttypedef T type;\n\t\ttypedef typename boost::call_traits<type>::param_type param_type;\n\t\ttypedef std::size_t digits_type;\n\t\ttypedef NTL::ZZ digits_ZZ_type;\n\t\ttypedef NTL::RR digits_RR_type;\n\tprotected:\n\t\t~significant_base();\n\t//public:\n\t//\tstatic digits_type digits();\n\t//\tstatic digits_ZZ_type const& digits_ZZ();\n\t//\tstatic digits_RR_type const& digits_RR();\n\t//\tstatic digits_type digits(param_type target);\n\t//\tstatic digits_ZZ_type const& digits_ZZ(param_type target);\n\t//\tstatic digits_RR_type const& digits_RR(param_type target);\n\t//\tstatic digits_type digits10();\n\t//\tstatic digits_ZZ_type const& digits10_ZZ();\n\t//\tstatic digits_RR_type const& digits10_RR();\n\t};\n\n\t//\n\t// significant_float_base\n\t//\n\ttemplate<typename T, std::size_t N>\n\tclass significant_float_base\n\t\t: public significant_base<T>\n\t{\n\tprivate:\n\t\ttypedef significant_base<T> base_type;\n\tpublic:\n\t\ttypedef typename base_type::param_type param_type;\n\t\ttypedef typename base_type::digits_type digits_type;\n\t\ttypedef typename base_type::digits_ZZ_type digits_ZZ_type;\n\t\ttypedef typename base_type::digits_RR_type digits_RR_type;\n\tpublic:\n\t\tstatic digits_type digits() {\n\t\t\treturn N;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ() {\n\t\t\tstatic digits_ZZ_type const digits_(NTL::to_ZZ(N));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR() {\n\t\t\tstatic digits_RR_type const digits_(NTL::to_RR(N));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_type digits(param_type) {\n\t\t\treturn digits();\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ(param_type) {\n\t\t\treturn digits_RR();\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR(param_type) {\n\t\t\treturn digits_RR();\n\t\t}\n\t\tstatic digits_type digits10() {\n\t\t\tstatic digits_type const digits_(std::pow(10.0, static_cast<int>(N)));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits10_ZZ() {\n\t\t\tstatic digits_ZZ_type const digits_(NTL::power(NTL::to_ZZ(10), N));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_RR_type const& digits10_RR() {\n\t\t\tstatic digits_RR_type const digits_(NTL::power(NTL::to_RR(10), N));\n\t\t\treturn digits_;\n\t\t}\n\t};\n\n\t//\n\t// significant_float_utils\n\t//\n\ttemplate<typename Char, typename Enable = void>\n\tclass significant_float_utils {};\n\ttemplate<typename Char>\n\tclass significant_float_utils<\n\t\tChar,\n\t\ttypename boost::enable_if<\n\t\t\tis_char_type<Char>\n\t\t>::type\n\t> {\n\tpublic:\n\t\ttypedef Char char_type;\n\tpublic:\n\t\tstatic char_type const e = 'e';\n\t\tstatic char_type const point = '.';\n\tpublic:\n\t\ttemplate<typename IntType, typename Range>\n\t\tstatic IntType exponent(Range const& range) {\n\t\t\ttypedef std::basic_string<char_type> string_type;\n\t\t\ttypedef typename boost::range_iterator<Range>::type iterator;\n\t\t\titerator i_e = std::find(boost::begin(range), boost::end(range), e);\n\t\t\treturn i_e != boost::end(range)\n\t\t\t\t? boost::lexical_cast<IntType>(string_type(i_e + 1, boost::end(range)))\n\t\t\t\t: 0\n\t\t\t\t;\n\t\t}\n\t\ttemplate<typename IntType, typename Range>\n\t\tstatic IntType integral(Range const& range) {\n\t\t\ttypedef std::basic_string<char_type> string_type;\n\t\t\ttypedef typename boost::range_iterator<Range>::type iterator;\n\t\t\titerator i_point = std::find(boost::begin(range), boost::end(range), point);\n\t\t\titerator i_e = std::find(boost::begin(range), boost::end(range), e);\n\t\t\treturn i_point != boost::end(range)\n\t\t\t\t? boost::lexical_cast<IntType>(string_type(boost::begin(range), i_point))\n\t\t\t\t: i_e != boost::end(range)\n\t\t\t\t\t? boost::lexical_cast<IntType>(string_type(boost::begin(range), i_e))\n\t\t\t\t\t: boost::lexical_cast<IntType>(string_type(boost::begin(range), boost::end(range)))\n\t\t\t\t;\n\t\t}\n\t\ttemplate<typename IntType, typename Range>\n\t\tstatic IntType fractional(Range const& range) {\n\t\t\ttypedef std::basic_string<char_type> string_type;\n\t\t\ttypedef typename boost::range_iterator<Range>::type iterator;\n\t\t\titerator i_point = std::find(boost::begin(range), boost::end(range), point);\n\t\t\titerator i_e = std::find(boost::begin(range), boost::end(range), e);\n\t\t\treturn i_point != boost::end(range)\n\t\t\t\t? boost::lexical_cast<IntType>(string_type(i_point + 1, i_e))\n\t\t\t\t: 0\n\t\t\t\t;\n\t\t}\n\t};\n\ttemplate<typename Char>\n\tclass significant_float_utils<\n\t\tChar,\n\t\ttypename boost::enable_if<\n\t\t\tis_wchar_type<Char>\n\t\t>::type\n\t> {\n\tpublic:\n\t\ttypedef Char char_type;\n\tpublic:\n\t\tstatic char_type const e = L'e';\n\t\tstatic char_type const point = L'.';\n\t};\n\n\t//\n\t// significant_c_str_impl\n\t//\n\ttemplate<typename Char>\n\tclass significant_c_str_impl\n\t\t: public significant_base<Char const*>\n\t{\n\tprivate:\n\t\ttypedef significant_base<Char const*> base_type;\n\tpublic:\n\t\ttypedef typename base_type::param_type param_type;\n\t\ttypedef typename base_type::digits_type digits_type;\n\t\ttypedef typename base_type::digits_ZZ_type digits_ZZ_type;\n\t\ttypedef typename base_type::digits_RR_type digits_RR_type;\n\tpublic:\n\t\ttypedef Char char_type;\n\tpublic:\n\t\tstatic digits_type digits() {\n\t\t\treturn 0;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ() {\n\t\t\tstatic digits_ZZ_type const digits_(NTL::to_ZZ(0));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR() {\n\t\t\tstatic digits_RR_type const digits_(NTL::to_RR(0));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_type digits(param_type target) {\n\t\t\treturn digits<std::basic_string<char_type> >(target);\n\t\t}\n\t\ttemplate<typename String>\n\t\tstatic digits_type digits(String const& target) {\n\t\t\ttypedef String string_type;\n\t\t\ttypedef typename string_type::iterator iterator;\n\t\t\tdigits_type result = 0;\n\t\t\tstring_type value(target);\n\t\t\titerator i_e = std::find(value.begin(), value.end(), significant_float_utils<char_type>::e);\n\t\t\titerator i_point = std::find(value.begin(), value.end(), significant_float_utils<char_type>::point);\n\t\t\tif (i_point != value.end()) {\n\t\t\t\tresult += std::distance(i_point + 1, i_e);\n\t\t\t}\n\t\t\tif (i_e != value.end()) {\n\t\t\t\tresult -= boost::lexical_cast<digits_type>(string_type(i_e + 1, value.end()));\n\t\t\t}\n\t\t\treturn result >= 0 ? result : 0;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ(param_type target) {\n\t\t\treturn NTL::to_ZZ(digits(target));\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR(param_type target) {\n\t\t\treturn NTL::to_RR(digits(target));\n\t\t}\n\t\tstatic digits_type digits10() {\n\t\t\treturn 1;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits10_ZZ() {\n\t\t\tstatic digits_ZZ_type const digits_(NTL::to_ZZ(1));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_RR_type const& digits10_RR() {\n\t\t\tstatic digits_RR_type const digits_(NTL::to_RR(1));\n\t\t\treturn digits_;\n\t\t}\n\t};\n\n\t//\n\t// specialization significant: is_integral(T)\n\t//\n\ttemplate<typename T>\n\tclass significant<\n\t\tT,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_integral<T>\n\t\t>::type\n\t>\n\t\t: public significant_base<T>\n\t{\n\tprivate:\n\t\ttypedef significant_base<T> base_type;\n\tpublic:\n\t\ttypedef typename base_type::param_type param_type;\n\t\ttypedef typename base_type::digits_type digits_type;\n\t\ttypedef typename base_type::digits_ZZ_type digits_ZZ_type;\n\t\ttypedef typename base_type::digits_RR_type digits_RR_type;\n\tpublic:\n\t\tstatic digits_type digits() {\n\t\t\treturn 1;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ() {\n\t\t\tstatic digits_ZZ_type const digits_(NTL::to_ZZ(1));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR() {\n\t\t\tstatic digits_RR_type const digits_(NTL::to_RR(1));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_type digits(param_type) {\n\t\t\treturn 1;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ(param_type) {\n\t\t\treturn digits_ZZ();\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR(param_type) {\n\t\t\treturn digits_RR();\n\t\t}\n\t\tstatic digits_type digits10() {\n\t\t\treturn 10;\n\t\t}\n\t\tstatic digits_ZZ_type const& digits10_ZZ() {\n\t\t\tstatic digits_ZZ_type const digits_(NTL::to_ZZ(10));\n\t\t\treturn digits_;\n\t\t}\n\t\tstatic digits_RR_type const& digits10_RR() {\n\t\t\tstatic digits_RR_type const digits_(NTL::to_RR(10));\n\t\t\treturn digits_;\n\t\t}\n\t};\n\t//\n\t// specialization significant: is_same(T, float), is_same(T, double), is_same(T, long double)\n\t//\n\ttemplate<typename T>\n\tclass significant<\n\t\tT,\n\t\ttypename boost::enable_if<\n\t\t\tboost::is_same<T, float>\n\t\t>::type\n\t>\n\t\t: public significant_float_base<T, 7>\n\t{};\n\ttemplate<typename T>\n\tclass significant<T, typename boost::enable_if<boost::is_same<T, double> >::type>\n\t\t: public significant_float_base<T, 15>\n\t{};\n\ttemplate<typename T>\n\tclass significant<T, typename boost::enable_if<boost::is_same<T, long double> >::type>\n\t\t: public significant_float_base<T, 15>\n\t{};\n\t//\n\t// specialization significant: is_c_str(T)\n\t//\n\ttemplate<typename T>\n\tclass significant<\n\t\tT,\n\t\ttypename boost::enable_if<\n\t\t\tis_c_str<T>\n\t\t>::type\n\t>\n\t\t: public significant_base<T>\n\t{\n\tprivate:\n\t\ttypedef significant_base<T> base_type;\n\tpublic:\n\t\ttypedef typename base_type::param_type param_type;\n\t\ttypedef typename base_type::digits_type digits_type;\n\t\ttypedef typename base_type::digits_ZZ_type digits_ZZ_type;\n\t\ttypedef typename base_type::digits_RR_type digits_RR_type;\n\tprivate:\n\t\ttypedef significant_c_str_impl<\n\t\t\ttypename c_str_element_value<T>::type\n\t\t> impl_type;\n\tpublic:\n\t\tstatic digits_type digits() {\n\t\t\treturn impl_type::digits();\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ() {\n\t\t\treturn impl_type::digits_ZZ();\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR() {\n\t\t\treturn impl_type::digits_RR();\n\t\t}\n\t\tstatic digits_type digits(param_type target) {\n\t\t\treturn impl_type::digits(target);\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ(param_type target) {\n\t\t\treturn impl_type::digits_ZZ(target);\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR(param_type target) {\n\t\t\treturn impl_type::digits_RR(target);\n\t\t}\n\t\tstatic digits_type digits10() {\n\t\t\treturn impl_type::digits10();\n\t\t}\n\t\tstatic digits_ZZ_type const& digits10_ZZ() {\n\t\t\treturn impl_type::digits10_ZZ();\n\t\t}\n\t\tstatic digits_RR_type const& digits10_RR() {\n\t\t\treturn impl_type::digits10_RR();\n\t\t}\n\t};\n\n\t//\n\t// specialization significant: is_basic_string(T)\n\t//\n\ttemplate<typename T>\n\tclass significant<\n\t\tT,\n\t\ttypename boost::enable_if<\n\t\t\tis_basic_string<T>\n\t\t>::type\n\t>\n\t\t: public significant_base<T>\n\t{\n\tprivate:\n\t\ttypedef significant_base<T> base_type;\n\tpublic:\n\t\ttypedef typename base_type::param_type param_type;\n\t\ttypedef typename base_type::digits_type digits_type;\n\t\ttypedef typename base_type::digits_ZZ_type digits_ZZ_type;\n\t\ttypedef typename base_type::digits_RR_type digits_RR_type;\n\tprivate:\n\t\ttypedef significant_c_str_impl<\n\t\t\ttypename remove_const_reference<T>::type::value_type\n\t\t> impl_type;\n\tpublic:\n\t\tstatic digits_type digits() {\n\t\t\treturn impl_type::digits();\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ() {\n\t\t\treturn impl_type::digits_ZZ();\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR() {\n\t\t\treturn impl_type::digits_RR();\n\t\t}\n\t\tstatic digits_type digits(param_type target) {\n\t\t\treturn impl_type::template digits<typename remove_const_reference<T>::type>(target);\n\t\t}\n\t\tstatic digits_ZZ_type const& digits_ZZ(param_type target) {\n\t\t\treturn impl_type::digits_ZZ(target);\n\t\t}\n\t\tstatic digits_RR_type const& digits_RR(param_type target) {\n\t\t\treturn impl_type::digits_RR(target);\n\t\t}\n\t\tstatic digits_type digits10() {\n\t\t\treturn impl_type::digits10();\n\t\t}\n\t\tstatic digits_ZZ_type const& digits10_ZZ() {\n\t\t\treturn impl_type::digits10_ZZ();\n\t\t}\n\t\tstatic digits_RR_type const& digits10_RR() {\n\t\t\treturn impl_type::digits10_RR();\n\t\t}\n\t};\n\n\t//\n\t// significant_digits\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_call_copy_param<typename significant<T>::param_type>,\n\t\ttypename significant<T>::digits_type\n\t>::type\n\tsignificant_digits(T const target) {\n\t\treturn significant<T>::digits(target);\n\t}\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::disable_if<\n\t\tis_call_copy_param<typename significant<T>::param_type>,\n\t\ttypename significant<T>::digits_type\n\t>::type\n\tsignificant_digits(T const& target) {\n\t\treturn significant<T>::digits(target);\n\t}\n\n\t//\n\t// to_ZZ_full_significant\n\t//\n\t// specialization to_ZZ_full_significant: is_integral(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_integral<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_full_significant(T const target) {\n\t\treturn to_ZZ(target);\n\t}\n\t//\n\t// specialization to_ZZ_full_significant: is_float(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_float<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_full_significant(T const target) {\n\t\ttypename significant<T>::digits_type digits = integer_digits(target);\n\t\treturn to_ZZ(NTL::trunc(to_RR(target) * NTL::power(to_RR(10), static_cast<long>(significant<T>::digits() - digits))))\n\t\t\t* NTL::power(to_ZZ(10), static_cast<long>(digits));\n\t}\n\t//\n\t// specialization to_ZZ_full_significant: is_c_str(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_c_str<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_full_significant(T const target) {\n\t\ttypename significant<T>::digits_type digits = significant<T>::digits(target);\n\t\treturn to_ZZ(to_RR(target) * NTL::power(to_RR(10), digits));\n\t}\n\t//\n\t// specialization to_ZZ_full_significant: is_basic_string(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_basic_string<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_full_significant(T const& target) {\n\t\ttypename significant<T>::digits_type digits = significant<T>::digits(target);\n\t\treturn to_ZZ(to_RR(target) * NTL::power(to_RR(10), digits));\n\t}\n\n\t//\n\t// to_RR_full_significant\n\t//\n\t// specialization to_RR_full_significant: is_integral(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_integral<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_full_significant(T const target) {\n\t\treturn to_ZZ(target);\n\t}\n\t//\n\t// specialization to_RR_full_significant: is_float(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_float<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_full_significant(T const target) {\n\t\ttypename significant<T>::digits_type digits10 = significant<T>::digits10();\n\t\treturn NTL::trunc(to_RR(target) * digits10);\n\t}\n\t//\n\t// specialization to_RR_full_significant: is_c_str(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_c_str<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_full_significant(T const target) {\n\t\ttypename significant<T>::digits_type digits10 = significant<T>::digits10(target);\n\t\treturn NTL::trunc(to_RR(target) * digits10);\n\t}\n\t//\n\t// specialization to_RR_full_significant: is_basic_string(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_basic_string<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_full_significant(T const& target) {\n\t\ttypename significant<T>::digits_type digits = significant<T>::digits(target);\n\t\treturn NTL::trunc(to_RR(target) * NTL::power(to_RR(10), digits));\n\t}\n\n\t//\n\t// to_ZZ_significant\n\t//\n\t// specialization to_ZZ_significant: is_integral(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_integral<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_significant(T const target) {\n\t\treturn to_ZZ(target);\n\t}\n\t//\n\t// specialization to_ZZ_significant: is_float(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_float<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_significant(T const target) {\n\t\treturn to_ZZ(target);\n\t}\n\t//\n\t// specialization to_ZZ_significant: is_c_str(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_c_str<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_significant(T const target) {\n\t\treturn to_ZZ(target);\n\t}\n\t//\n\t// specialization to_ZZ_significant: is_basic_string(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_basic_string<T>,\n\t\tNTL::ZZ\n\t>::type\n\tto_ZZ_significant(T const& target) {\n\t\treturn to_ZZ(target);\n\t}\n\n\t//\n\t// to_RR_significant\n\t//\n\t// specialization to_RR_significant: is_integral(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_integral<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_significant(T const target) {\n\t\treturn to_RR(target);\n\t}\n\t//\n\t// specialization to_RR_significant: is_float(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tboost::is_float<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_significant(T const target) {\n\t\ttypename significant<T>::digits_type digits10 = significant<T>::digits10();\n\t\treturn to_RR_full_significant(target) / digits10;\n\t}\n\t//\n\t// specialization to_RR_significant: is_c_str(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_c_str<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_significant(T const target) {\n\t\treturn to_RR(target);\n\t}\n\t//\n\t// specialization to_RR_significant: is_basic_string(T)\n\t//\n\ttemplate<typename T>\n\tSPRIG_INLINE typename boost::enable_if<\n\t\tis_basic_string<T>,\n\t\tNTL::RR\n\t>::type\n\tto_RR_significant(T const& target) {\n\t\treturn to_RR(target);\n\t}\n} // namespace sprig\n\n#endif\t// #ifndef SPRIG_NTL_SIGNIFICANT_HPP\n", "meta": {"hexsha": "f47bc6218dc42dbff773683540162dc7828a600d", "size": 18149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/ntl/significant.hpp", "max_stars_repo_name": "bolero-MURAKAMI/Sprig", "max_stars_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-24T13:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-28T13:21:22.000Z", "max_issues_repo_path": "sprig/ntl/significant.hpp", "max_issues_repo_name": "bolero-MURAKAMI/Sprig", "max_issues_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "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": "sprig/ntl/significant.hpp", "max_forks_repo_name": "bolero-MURAKAMI/Sprig", "max_forks_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T03:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-28T13:21:22.000Z", "avg_line_length": 27.7083969466, "max_line_length": 119, "alphanum_fraction": 0.7224640476, "num_tokens": 4921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.03676946779082354, "lm_q1q2_score": 0.011547471398766843}}
{"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 <boost/algorithm/string.hpp>\n#include <cmath>\n\n#include \"Netcdf_interface.h\"\n#include \"Array.h\"\n#include \"Gas_concs.h\"\n#include \"Gas_optics.h\"\n#include \"Optical_props.h\"\n#include \"Source_functions.h\"\n#include \"Fluxes.h\"\n#include \"Rte_lw.h\"\n#include \"Rte_sw.h\"\n\n#ifdef FLOAT_SINGLE_RRTMGP\n#define FLOAT_TYPE float\n#else\n#define FLOAT_TYPE double\n#endif\n\nnamespace\n{\n    std::vector<std::string> get_variable_string(\n            const std::string& var_name,\n            std::vector<int> i_count,\n            Netcdf_handle& input_nc,\n            const int string_len,\n            bool trim=true)\n    {\n        // Multiply all elements in i_count.\n        int total_count = std::accumulate(i_count.begin(), i_count.end(), 1, std::multiplies<>());\n\n        // Add the string length as the rightmost dimension.\n        i_count.push_back(string_len);\n\n        // Multiply all elements in i_count.\n        // int total_count_char = std::accumulate(i_count.begin(), i_count.end(), 1, std::multiplies<>());\n\n        // Read the entire char array;\n        std::vector<char> var_char;\n        var_char = input_nc.get_variable<char>(var_name, i_count);\n\n        std::vector<std::string> var;\n\n        for (int n=0; n<total_count; ++n)\n        {\n            std::string s(var_char.begin()+n*string_len, var_char.begin()+(n+1)*string_len);\n            if (trim)\n                boost::trim(s);\n            var.push_back(s);\n        }\n\n        return var;\n    }\n\n    template<typename TF>\n    Gas_optics<TF> load_and_init_gas_optics(\n            Master& master,\n            const Gas_concs<TF>& gas_concs,\n            const std::string& coef_file)\n    {\n        // READ THE COEFFICIENTS FOR THE OPTICAL SOLVER.\n        Netcdf_file coef_nc(master, coef_file, Netcdf_mode::Read);\n\n        // Read k-distribution information.\n        int n_temps = coef_nc.get_dimension_size(\"temperature\");\n        int n_press = coef_nc.get_dimension_size(\"pressure\");\n        int n_absorbers = coef_nc.get_dimension_size(\"absorber\");\n\n        // CvH: I hardcode the value to 32 now, because coef files\n        // CvH: changed dimension name inconsistently.\n        // int n_char = coef_nc.get_dimension_size(\"string_len\");\n        constexpr int n_char = 32;\n\n        int n_minorabsorbers = coef_nc.get_dimension_size(\"minor_absorber\");\n        int n_extabsorbers = coef_nc.get_dimension_size(\"absorber_ext\");\n        int n_mixingfracs = coef_nc.get_dimension_size(\"mixing_fraction\");\n        int n_layers = coef_nc.get_dimension_size(\"atmos_layer\");\n        int n_bnds = coef_nc.get_dimension_size(\"bnd\");\n        int n_gpts = coef_nc.get_dimension_size(\"gpt\");\n        int n_pairs = coef_nc.get_dimension_size(\"pair\");\n        int n_minor_absorber_intervals_lower = coef_nc.get_dimension_size(\"minor_absorber_intervals_lower\");\n        int n_minor_absorber_intervals_upper = coef_nc.get_dimension_size(\"minor_absorber_intervals_upper\");\n        int n_contributors_lower = coef_nc.get_dimension_size(\"contributors_lower\");\n        int n_contributors_upper = coef_nc.get_dimension_size(\"contributors_upper\");\n\n        // Read gas names.\n        Array<std::string,1> gas_names(\n                get_variable_string(\"gas_names\", {n_absorbers}, coef_nc, n_char, true), {n_absorbers});\n\n        Array<int,3> key_species(\n                coef_nc.get_variable<int>(\"key_species\", {n_bnds, n_layers, 2}),\n                {2, n_layers, n_bnds});\n        Array<TF,2> band_lims(coef_nc.get_variable<TF>(\"bnd_limits_wavenumber\", {n_bnds, 2}), {2, n_bnds});\n        Array<int,2> band2gpt(coef_nc.get_variable<int>(\"bnd_limits_gpt\", {n_bnds, 2}), {2, n_bnds});\n        Array<TF,1> press_ref(coef_nc.get_variable<TF>(\"press_ref\", {n_press}), {n_press});\n        Array<TF,1> temp_ref(coef_nc.get_variable<TF>(\"temp_ref\", {n_temps}), {n_temps});\n\n        TF temp_ref_p = coef_nc.get_variable<TF>(\"absorption_coefficient_ref_P\");\n        TF temp_ref_t = coef_nc.get_variable<TF>(\"absorption_coefficient_ref_T\");\n        TF press_ref_trop = coef_nc.get_variable<TF>(\"press_ref_trop\");\n\n        Array<TF,3> kminor_lower(\n                coef_nc.get_variable<TF>(\"kminor_lower\", {n_temps, n_mixingfracs, n_contributors_lower}),\n                {n_contributors_lower, n_mixingfracs, n_temps});\n        Array<TF,3> kminor_upper(\n                coef_nc.get_variable<TF>(\"kminor_upper\", {n_temps, n_mixingfracs, n_contributors_upper}),\n                {n_contributors_upper, n_mixingfracs, n_temps});\n\n        Array<std::string,1> gas_minor(get_variable_string(\"gas_minor\", {n_minorabsorbers}, coef_nc, n_char),\n                {n_minorabsorbers});\n\n        Array<std::string,1> identifier_minor(\n                get_variable_string(\"identifier_minor\", {n_minorabsorbers}, coef_nc, n_char), {n_minorabsorbers});\n\n        Array<std::string,1> minor_gases_lower(\n                get_variable_string(\"minor_gases_lower\", {n_minor_absorber_intervals_lower}, coef_nc, n_char),\n                {n_minor_absorber_intervals_lower});\n        Array<std::string,1> minor_gases_upper(\n                get_variable_string(\"minor_gases_upper\", {n_minor_absorber_intervals_upper}, coef_nc, n_char),\n                {n_minor_absorber_intervals_upper});\n\n        Array<int,2> minor_limits_gpt_lower(\n                coef_nc.get_variable<int>(\"minor_limits_gpt_lower\", {n_minor_absorber_intervals_lower, n_pairs}),\n                {n_pairs, n_minor_absorber_intervals_lower});\n        Array<int,2> minor_limits_gpt_upper(\n                coef_nc.get_variable<int>(\"minor_limits_gpt_upper\", {n_minor_absorber_intervals_upper, n_pairs}),\n                {n_pairs, n_minor_absorber_intervals_upper});\n\n        Array<int,1> minor_scales_with_density_lower(\n                coef_nc.get_variable<int>(\"minor_scales_with_density_lower\", {n_minor_absorber_intervals_lower}),\n                {n_minor_absorber_intervals_lower});\n        Array<int,1> minor_scales_with_density_upper(\n                coef_nc.get_variable<int>(\"minor_scales_with_density_upper\", {n_minor_absorber_intervals_upper}),\n                {n_minor_absorber_intervals_upper});\n\n        Array<int,1> scale_by_complement_lower(\n                coef_nc.get_variable<int>(\"scale_by_complement_lower\", {n_minor_absorber_intervals_lower}),\n                {n_minor_absorber_intervals_lower});\n        Array<int,1> scale_by_complement_upper(\n                coef_nc.get_variable<int>(\"scale_by_complement_upper\", {n_minor_absorber_intervals_upper}),\n                {n_minor_absorber_intervals_upper});\n\n        Array<std::string,1> scaling_gas_lower(\n                get_variable_string(\"scaling_gas_lower\", {n_minor_absorber_intervals_lower}, coef_nc, n_char),\n                {n_minor_absorber_intervals_lower});\n        Array<std::string,1> scaling_gas_upper(\n                get_variable_string(\"scaling_gas_upper\", {n_minor_absorber_intervals_upper}, coef_nc, n_char),\n                {n_minor_absorber_intervals_upper});\n\n        Array<int,1> kminor_start_lower(\n                coef_nc.get_variable<int>(\"kminor_start_lower\", {n_minor_absorber_intervals_lower}),\n                {n_minor_absorber_intervals_lower});\n        Array<int,1> kminor_start_upper(\n                coef_nc.get_variable<int>(\"kminor_start_upper\", {n_minor_absorber_intervals_upper}),\n                {n_minor_absorber_intervals_upper});\n\n        Array<TF,3> vmr_ref(\n                coef_nc.get_variable<TF>(\"vmr_ref\", {n_temps, n_extabsorbers, n_layers}),\n                {n_layers, n_extabsorbers, n_temps});\n\n        Array<TF,4> kmajor(\n                coef_nc.get_variable<TF>(\"kmajor\", {n_temps, n_press+1, n_mixingfracs, n_gpts}),\n                {n_gpts, n_mixingfracs, n_press+1, n_temps});\n\n        // Keep the size at zero, if it does not exist.\n        Array<TF,3> rayl_lower;\n        Array<TF,3> rayl_upper;\n\n        if (coef_nc.variable_exists(\"rayl_lower\"))\n        {\n            rayl_lower.set_dims({n_gpts, n_mixingfracs, n_temps});\n            rayl_upper.set_dims({n_gpts, n_mixingfracs, n_temps});\n            rayl_lower = coef_nc.get_variable<TF>(\"rayl_lower\", {n_temps, n_mixingfracs, n_gpts});\n            rayl_upper = coef_nc.get_variable<TF>(\"rayl_upper\", {n_temps, n_mixingfracs, n_gpts});\n        }\n\n        // Is it really LW if so read these variables as well.\n        if (coef_nc.variable_exists(\"totplnk\"))\n        {\n            int n_internal_sourcetemps = coef_nc.get_dimension_size(\"temperature_Planck\");\n\n            Array<TF,2> totplnk(\n                    coef_nc.get_variable<TF>( \"totplnk\", {n_bnds, n_internal_sourcetemps}),\n                    {n_internal_sourcetemps, n_bnds});\n            Array<TF,4> planck_frac(\n                    coef_nc.get_variable<TF>(\"plank_fraction\", {n_temps, n_press+1, n_mixingfracs, n_gpts}),\n                    {n_gpts, n_mixingfracs, n_press+1, n_temps});\n\n            // Construct the k-distribution.\n            return Gas_optics<TF>(\n                    gas_concs,\n                    gas_names,\n                    key_species,\n                    band2gpt,\n                    band_lims,\n                    press_ref,\n                    press_ref_trop,\n                    temp_ref,\n                    temp_ref_p,\n                    temp_ref_t,\n                    vmr_ref,\n                    kmajor,\n                    kminor_lower,\n                    kminor_upper,\n                    gas_minor,\n                    identifier_minor,\n                    minor_gases_lower,\n                    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,\n                    scaling_gas_upper,\n                    scale_by_complement_lower,\n                    scale_by_complement_upper,\n                    kminor_start_lower,\n                    kminor_start_upper,\n                    totplnk,\n                    planck_frac,\n                    rayl_lower,\n                    rayl_upper);\n        }\n        else\n        {\n            Array<TF,1> solar_src_quiet(\n                    coef_nc.get_variable<TF>(\"solar_source_quiet\", {n_gpts}), {n_gpts});\n            Array<TF,1> solar_src_facular(\n                    coef_nc.get_variable<TF>(\"solar_source_facular\", {n_gpts}), {n_gpts});\n            Array<TF,1> solar_src_sunspot(\n                    coef_nc.get_variable<TF>(\"solar_source_sunspot\", {n_gpts}), {n_gpts});\n\n            TF tsi = coef_nc.get_variable<TF>(\"tsi_default\");\n            TF mg_index = coef_nc.get_variable<TF>(\"mg_default\");\n            TF sb_index = coef_nc.get_variable<TF>(\"sb_default\");\n\n            return Gas_optics<TF>(\n                    gas_concs,\n                    gas_names,\n                    key_species,\n                    band2gpt,\n                    band_lims,\n                    press_ref,\n                    press_ref_trop,\n                    temp_ref,\n                    temp_ref_p,\n                    temp_ref_t,\n                    vmr_ref,\n                    kmajor,\n                    kminor_lower,\n                    kminor_upper,\n                    gas_minor,\n                    identifier_minor,\n                    minor_gases_lower,\n                    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,\n                    scaling_gas_upper,\n                    scale_by_complement_lower,\n                    scale_by_complement_upper,\n                    kminor_start_lower,\n                    kminor_start_upper,\n                    solar_src_quiet,\n                    solar_src_facular,\n                    solar_src_sunspot,\n                    tsi,\n                    mg_index,\n                    sb_index,\n                    rayl_lower,\n                    rayl_upper);\n        }\n        // End reading of k-distribution.\n    }\n}\n\ntemplate<typename TF>\nvoid load_gas_concs(Gas_concs<TF>& gas_concs, Netcdf_file& input_nc)\n{\n    // This part is contained in the create\n    Netcdf_group rad_nc = input_nc.get_group(\"radiation\");\n\n    const int n_lay = rad_nc.get_dimension_size(\"lay\");\n\n    gas_concs.set_vmr(\"h2o\",\n            Array<TF,1>(rad_nc.get_variable<TF>(\"h2o\", {n_lay}), {n_lay}));\n    gas_concs.set_vmr(\"co2\",\n            rad_nc.get_variable<TF>(\"co2\"));\n    gas_concs.set_vmr(\"o3\",\n            Array<TF,1>(rad_nc.get_variable<TF>(\"o3\", {n_lay}), {n_lay}));\n    gas_concs.set_vmr(\"n2o\",\n            rad_nc.get_variable<TF>(\"n2o\"));\n    gas_concs.set_vmr(\"ch4\",\n            rad_nc.get_variable<TF>(\"ch4\"));\n    gas_concs.set_vmr(\"o2\",\n            rad_nc.get_variable<TF>(\"o2\"));\n    gas_concs.set_vmr(\"n2\",\n            rad_nc.get_variable<TF>(\"n2\"));\n}\n\ntemplate<typename TF>\nvoid solve_radiation(Master& master)\n{\n    // We are doing a single column run.\n    const int n_col = 1;\n\n    // These are the global variables that need to be contained in a class.\n    Gas_concs<TF> gas_concs;\n\n    std::unique_ptr<Gas_optics<TF>> kdist_lw;\n    std::unique_ptr<Gas_optics<TF>> kdist_sw;\n\n    // This is the part that is done in the initialization.\n    Netcdf_file file_nc(master, \"test_rcemip_input.nc\", Netcdf_mode::Read);\n\n    load_gas_concs<TF>(gas_concs, file_nc);\n    kdist_lw = std::make_unique<Gas_optics<TF>>(\n            load_and_init_gas_optics(master, gas_concs, \"coefficients_lw.nc\"));\n    kdist_sw = std::make_unique<Gas_optics<TF>>(\n            load_and_init_gas_optics(master, gas_concs, \"coefficients_sw.nc\"));\n\n    // LOAD THE LONGWAVE SPECIFIC BOUNDARY CONDITIONS.\n    // Set the surface temperature and emissivity.\n    Array<TF,1> t_sfc({1});\n    t_sfc({1}) = TF(300.);\n\n    const int n_bnd = kdist_lw->get_nband();\n    Array<TF,2> emis_sfc({n_bnd, 1});\n    for (int ibnd=1; ibnd<=n_bnd; ++ibnd)\n        emis_sfc({ibnd, 1}) = 1.;\n\n    const int n_ang = 1;\n\n    // LOAD THE SHORTWAVE SPECIFIC BOUNDARY CONDITIONS.\n    Array<TF,1> sza({n_col});\n    Array<TF,2> sfc_alb_dir({n_bnd, n_col});\n    Array<TF,2> sfc_alb_dif({n_bnd, n_col});\n\n    sza({1}) = TF(0.7339109504636155);\n\n    for (int ibnd=1; ibnd<=n_bnd; ++ibnd)\n    {\n        sfc_alb_dir({ibnd, 1}) = 0.07;\n        sfc_alb_dif({ibnd, 1}) = 0.07;\n    }\n\n    Array<TF,1> mu0({n_col});\n    mu0({1}) = std::cos(sza({1}));\n\n    // Solve the full column once.\n    Netcdf_group input_nc = file_nc.get_group(\"radiation\");\n\n    const int n_lay = input_nc.get_dimension_size(\"lay\");\n    const int n_lev = input_nc.get_dimension_size(\"lev\");\n\n    Array<TF,2> p_lay(input_nc.get_variable<TF>(\"p_lay\", {n_lay, n_col}), {n_col, n_lay});\n    Array<TF,2> t_lay(input_nc.get_variable<TF>(\"t_lay\", {n_lay, n_col}), {n_col, n_lay});\n    Array<TF,2> p_lev(input_nc.get_variable<TF>(\"p_lev\", {n_lev, n_col}), {n_col, n_lev});\n    Array<TF,2> t_lev(input_nc.get_variable<TF>(\"t_lev\", {n_lev, n_col}), {n_col, n_lev});\n\n    Array<TF,2> col_dry({n_col, n_lay});\n    if (input_nc.variable_exists(\"col_dry\"))\n        col_dry = input_nc.get_variable<TF>(\"col_dry\", {n_lay, n_col});\n    else\n    {\n        kdist_lw->get_col_dry(col_dry, gas_concs.get_vmr(\"h2o\"), p_lev);\n        kdist_sw->get_col_dry(col_dry, gas_concs.get_vmr(\"h2o\"), p_lev);\n    }\n\n    // Solve the longwave first.\n    std::unique_ptr<Optical_props_arry<TF>> optical_props_lw =\n            std::make_unique<Optical_props_1scl<TF>>(n_col, n_lay, *kdist_lw);\n\n    Source_func_lw<TF> sources(n_col, n_lay, *kdist_lw);\n\n    kdist_lw->gas_optics(\n            p_lay,\n            p_lev,\n            t_lay,\n            t_sfc,\n            gas_concs,\n            optical_props_lw,\n            sources,\n            col_dry,\n            t_lev);\n\n    std::unique_ptr<Fluxes_broadband<TF>> fluxes =\n            std::make_unique<Fluxes_broadband<TF>>(n_col, n_lev);\n\n    const int top_at_1 = p_lay({1, 1}) < p_lay({1, n_lay});\n\n    const int n_gpt_lw = optical_props_lw->get_ngpt();\n    Array<TF,3> lw_gpt_flux_up({n_col, n_lev, n_gpt_lw});\n    Array<TF,3> lw_gpt_flux_dn({n_col, n_lev, n_gpt_lw});\n\n    Rte_lw<TF>::rte_lw(\n            optical_props_lw,\n            top_at_1,\n            sources,\n            emis_sfc,\n            Array<TF,2>(), // Add an empty array, no inc_flux.\n            lw_gpt_flux_up,\n            lw_gpt_flux_dn,\n            n_ang);\n\n    fluxes->reduce(\n            lw_gpt_flux_up, lw_gpt_flux_dn,\n            optical_props_lw, top_at_1);\n\n    Array<TF,2> lw_flux_up ({n_col, n_lev});\n    Array<TF,2> lw_flux_dn ({n_col, n_lev});\n    Array<TF,2> lw_flux_net({n_col, n_lev});\n    Array<TF,2> lw_heating ({n_col, n_lay});\n\n    // Copy the data to the output.\n    for (int ilev=1; ilev<=n_lev; ++ilev)\n    {\n        lw_flux_up ({1, ilev}) = fluxes->get_flux_up ()({1, ilev});\n        lw_flux_dn ({1, ilev}) = fluxes->get_flux_dn ()({1, ilev});\n        lw_flux_net({1, ilev}) = fluxes->get_flux_net()({1, ilev});\n    }\n\n    const int n_gpt_sw = kdist_sw->get_ngpt();\n    Array<TF,2> toa_src({n_col, n_gpt_sw});\n\n    std::unique_ptr<Optical_props_arry<TF>> optical_props_sw =\n            std::make_unique<Optical_props_2str<TF>>(n_col, n_lay, *kdist_sw);\n\n    kdist_sw->gas_optics(\n            p_lay,\n            p_lev,\n            t_lay,\n            gas_concs,\n            optical_props_sw,\n            toa_src,\n            col_dry);\n\n    const TF tsi_scaling = 0.4053176301654965;\n    for (int igpt=1; igpt<=n_gpt_sw; ++igpt)\n        toa_src({1, igpt}) *= tsi_scaling;\n\n    Array<TF,3> sw_gpt_flux_up    ({n_col, n_lev, n_gpt_sw});\n    Array<TF,3> sw_gpt_flux_dn    ({n_col, n_lev, n_gpt_sw});\n    Array<TF,3> sw_gpt_flux_dn_dir({n_col, n_lev, n_gpt_sw});\n\n    Rte_sw<TF>::rte_sw(\n            optical_props_sw,\n            top_at_1,\n            mu0,\n            toa_src,\n            sfc_alb_dir,\n            sfc_alb_dif,\n            Array<TF,2>(), // Add an empty array, no inc_flux.\n            sw_gpt_flux_up,\n            sw_gpt_flux_dn,\n            sw_gpt_flux_dn_dir);\n\n    fluxes->reduce(\n            sw_gpt_flux_up, sw_gpt_flux_dn, sw_gpt_flux_dn_dir,\n            optical_props_sw, top_at_1);\n\n    Array<TF,2> sw_flux_up ({n_col, n_lev});\n    Array<TF,2> sw_flux_dn ({n_col, n_lev});\n    Array<TF,2> sw_flux_net({n_col, n_lev});\n    Array<TF,2> sw_heating ({n_col, n_lay});\n\n    // Copy the data to the output.\n    for (int ilev=1; ilev<=n_lev; ++ilev)\n    {\n        sw_flux_up ({1, ilev}) = fluxes->get_flux_up ()({1, ilev});\n        sw_flux_dn ({1, ilev}) = fluxes->get_flux_dn ()({1, ilev});\n        sw_flux_net({1, ilev}) = fluxes->get_flux_net()({1, ilev});\n    }\n\n    // Compute the heating rates.\n    constexpr TF g = 9.80655;\n    constexpr TF cp = 1005.;\n\n    Array<TF,2> heating ({n_col, n_lay});\n\n    for (int ilay=1; ilay<=n_lay; ++ilay)\n    {\n        lw_heating({1, ilay}) =\n                ( lw_flux_up({1, ilay+1}) - lw_flux_up({1, ilay})\n                - lw_flux_dn({1, ilay+1}) + lw_flux_dn({1, ilay}) )\n                * g / ( cp * (p_lev({1, ilay+1}) - p_lev({1, ilay})) ) * 86400.;\n\n        sw_heating({1, ilay}) =\n                ( sw_flux_up({1, ilay+1}) - sw_flux_up({1, ilay})\n                - sw_flux_dn({1, ilay+1}) + sw_flux_dn({1, ilay}) )\n                * g / ( cp * (p_lev({1, ilay+1}) - p_lev({1, ilay})) ) * 86400.;\n\n        heating({1, ilay}) = lw_heating({1, ilay}) + sw_heating({1, ilay});\n    }\n\n    // Store the radiation fluxes to a file\n    Netcdf_file output_nc(master, \"test_rcemip_output.nc\", Netcdf_mode::Create);\n    output_nc.add_dimension(\"col\", n_col);\n    output_nc.add_dimension(\"lev\", n_lev);\n    output_nc.add_dimension(\"lay\", n_lay);\n\n    auto nc_p_lev = output_nc.add_variable<TF>(\"lev\", {\"lev\"});\n    auto nc_p_lay = output_nc.add_variable<TF>(\"lay\", {\"lay\"});\n    nc_p_lev.insert(p_lev.v(), {0});\n    nc_p_lay.insert(p_lay.v(), {0});\n\n    auto nc_lw_flux_up  = output_nc.add_variable<TF>(\"lw_flux_up\" , {\"lev\", \"col\"});\n    auto nc_lw_flux_dn  = output_nc.add_variable<TF>(\"lw_flux_dn\" , {\"lev\", \"col\"});\n    auto nc_lw_flux_net = output_nc.add_variable<TF>(\"lw_flux_net\", {\"lev\", \"col\"});\n    auto nc_lw_heating  = output_nc.add_variable<TF>(\"lw_heating\" , {\"lay\", \"col\"});\n\n    nc_lw_flux_up .insert(lw_flux_up .v(), {0, 0});\n    nc_lw_flux_dn .insert(lw_flux_dn .v(), {0, 0});\n    nc_lw_flux_net.insert(lw_flux_net.v(), {0, 0});\n    nc_lw_heating .insert(lw_heating .v(), {0, 0});\n\n    auto nc_sw_flux_up  = output_nc.add_variable<TF>(\"sw_flux_up\" , {\"lev\", \"col\"});\n    auto nc_sw_flux_dn  = output_nc.add_variable<TF>(\"sw_flux_dn\" , {\"lev\", \"col\"});\n    auto nc_sw_flux_net = output_nc.add_variable<TF>(\"sw_flux_net\", {\"lev\", \"col\"});\n    auto nc_sw_heating  = output_nc.add_variable<TF>(\"sw_heating\" , {\"lay\", \"col\"});\n\n    nc_sw_flux_up .insert(sw_flux_up .v(), {0, 0});\n    nc_sw_flux_dn .insert(sw_flux_dn .v(), {0, 0});\n    nc_sw_flux_net.insert(sw_flux_net.v(), {0, 0});\n    nc_sw_heating .insert(sw_heating .v(), {0, 0});\n\n    auto nc_heating = output_nc.add_variable<TF>(\"heating\", {\"lay\", \"col\"});\n    nc_heating.insert(heating.v(), {0, 0});\n}\n\nint main()\n{\n    Master master;\n    try\n    {\n        master.start();\n        master.init();\n\n        solve_radiation<FLOAT_TYPE>(master);\n    }\n\n    // Catch any exceptions and return 1.\n    catch (const std::exception& e)\n    {\n        master.print_message(\"EXCEPTION: %s\\n\", e.what());\n        return 1;\n    }\n    catch (...)\n    {\n        master.print_message(\"UNHANDLED EXCEPTION!\\n\");\n        return 1;\n    }\n\n    // Return 0 in case of normal exit.\n    return 0;\n}\n", "meta": {"hexsha": "ea99fc7f423aab4ceec7cdccd431844b651f3e38", "size": 22362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src_test/test_rcemip.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_test/test_rcemip.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_test/test_rcemip.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.3567753002, "max_line_length": 114, "alphanum_fraction": 0.6018692425, "num_tokens": 6118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.032100706832753886, "lm_q1q2_score": 0.011535843069987645}}
{"text": "// $Id$\n//\n//  Copyright (C) 2004-2014 Greg Landrum and Rational Discovery LLC\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n//\n#include <list>\n#include <RDGeneral/RDLog.h>\n#include \"MolFileStereochem.h\"\n#include <Geometry/point.h>\n#include <boost/dynamic_bitset.hpp>\n#include <algorithm>\n#include \"MolFileStereochem.h\"\n#include <RDGeneral/Ranking.h>\n\nnamespace RDKit {\ntypedef std::list<double> DOUBLE_LIST;\n\n// ----------------------------------- -----------------------------------\n// This algorithm is identical to that used in the CombiCode Mol file\n//  parser (also developed by RD).\n//\n//\n// SUMMARY:\n//   Derive a chiral code for an atom that has a wedged (or dashed) bond\n//   drawn to it.\n//\n// RETURNS:\n//   The chiral type\n//\n// CAVEATS:\n//   This is careful to ensure that the central atom has 4 neighbors and\n//   only single bonds to it, but that's about it.\n//\n// NOTE: this isn't careful at all about checking to make sure that\n// things actually *should* be chiral. e.g. if the file has a\n// 3-coordinate N with a wedged bond, it will make some erroneous\n// assumptions about the chirality.\n//\n// ----------------------------------- -----------------------------------\n\nAtom::ChiralType FindAtomStereochemistry(const RWMol &mol, const Bond *bond,\n                                         const Conformer *conf) {\n  PRECONDITION(bond, \"no bond\");\n  PRECONDITION(conf, \"no conformer\");\n  Bond::BondDir bondDir = bond->getBondDir();\n  PRECONDITION(bondDir == Bond::BEGINWEDGE || bondDir == Bond::BEGINDASH,\n               \"bad bond direction\");\n\n  // NOTE that according to the CT file spec, wedging assigns chirality\n  // to the atom at the point of the wedge, (atom 1 in the bond).\n  const Atom *atom = bond->getBeginAtom();\n  PRECONDITION(atom, \"no atom\");\n\n  // we can't do anything with atoms that have more than 4 neighbors:\n  if (atom->getDegree() > 4) {\n    return Atom::CHI_UNSPECIFIED;\n  }\n  const Atom *bondAtom = bond->getEndAtom();\n\n  Atom::ChiralType res = Atom::CHI_UNSPECIFIED;\n\n  INT_LIST neighborBondIndices;\n  RDGeom::Point3D centerLoc, tmpPt;\n  centerLoc = conf->getAtomPos(atom->getIdx());\n  tmpPt = conf->getAtomPos(bondAtom->getIdx());\n  centerLoc.z = 0.0;\n  tmpPt.z = 0.0;\n\n  RDGeom::Point3D refVect = centerLoc.directionVector(tmpPt);\n\n  //----------------------------------------------------------\n  //\n  //  start by ensuring that all the bonds to neighboring atoms\n  //  are single bonds and collecting a list of neighbor indices:\n  //\n  //----------------------------------------------------------\n  bool hSeen = false;\n\n  neighborBondIndices.push_back(bond->getIdx());\n  if (bondAtom->getAtomicNum() == 1 && bondAtom->getIsotope() == 0)\n    hSeen = true;\n\n  bool allSingle = true;\n  ROMol::OEDGE_ITER beg, end;\n  boost::tie(beg, end) = mol.getAtomBonds(atom);\n  while (beg != end) {\n    Bond *nbrBond = mol[*beg].get();\n    if (nbrBond->getBondType() != Bond::SINGLE) {\n      allSingle = false;\n      // break;\n    }\n    if (nbrBond != bond) {\n      if ((nbrBond->getOtherAtom(atom)->getAtomicNum() == 1 &&\n           nbrBond->getOtherAtom(atom)->getIsotope() == 0))\n        hSeen = true;\n      neighborBondIndices.push_back(nbrBond->getIdx());\n    }\n    ++beg;\n  }\n  int nNbrs = neighborBondIndices.size();\n\n  //----------------------------------------------------------\n  //\n  //  Return now if there aren't at least 3 non-H bonds to the atom.\n  //  (we can implicitly add a single H to 3 coordinate atoms, but\n  //  we're horked otherwise).\n  //\n  //----------------------------------------------------------\n  if (nNbrs < 3 || (hSeen && nNbrs < 4)) {\n    return Atom::CHI_UNSPECIFIED;\n  }\n\n  //----------------------------------------------------------\n  //\n  //  Continue if there are all single bonds or if we're considering\n  //  4-coordinate P or S\n  //\n  //----------------------------------------------------------\n  if (allSingle || atom->getAtomicNum() == 15 || atom->getAtomicNum() == 16) {\n    //------------------------------------------------------------\n    //\n    //  Here we need to figure out the rotation direction between\n    //  the neighbor bonds and the wedged bond:\n    //\n    //------------------------------------------------------------\n    bool isCCW = true;\n    double angle0, angle1, angle2;\n    const Bond *bond1, *bond2, *bond3;\n    RDGeom::Point3D atomVect0, atomVect1, atomVect2;\n    INT_LIST::const_iterator bondIter = neighborBondIndices.begin();\n    ++bondIter;\n    bond1 = mol.getBondWithIdx(*bondIter);\n    int oaid = bond1->getOtherAtom(atom)->getIdx();\n    tmpPt = conf->getAtomPos(oaid);\n    tmpPt.z = 0;\n    atomVect0 = centerLoc.directionVector(tmpPt);\n    angle0 = refVect.signedAngleTo(atomVect0);\n    if (angle0 < 0) angle0 += 2. * M_PI;\n\n    ++bondIter;\n    bond2 = mol.getBondWithIdx(*bondIter);\n    oaid = bond2->getOtherAtom(atom)->getIdx();\n    tmpPt = conf->getAtomPos(oaid);\n    tmpPt.z = 0;\n    atomVect1 = centerLoc.directionVector(tmpPt);\n    angle1 = refVect.signedAngleTo(atomVect1);\n    if (angle1 < 0) angle1 += 2. * M_PI;\n\n    // We proceed differently for 3 and 4 coordinate atoms:\n    double firstAngle, secondAngle;\n    if (nNbrs == 4) {\n      bool flipIt = false;\n      // grab the angle to the last neighbor:\n      ++bondIter;\n      bond3 = mol.getBondWithIdx(*bondIter);\n      oaid = bond3->getOtherAtom(atom)->getIdx();\n      tmpPt = conf->getAtomPos(oaid);\n      tmpPt.z = 0;\n      atomVect2 = centerLoc.directionVector(tmpPt);\n      angle2 = refVect.signedAngleTo(atomVect2);\n      if (angle2 < 0) angle2 += 2. * M_PI;\n\n      // find the lowest and second-lowest angle and keep track of\n      // whether or not we have to do a non-cyclic permutation to\n      // get there:\n      if (angle0 < angle1) {\n        if (angle1 < angle2) {\n          // order is angle0 -> angle1 -> angle2\n          firstAngle = angle0;\n          secondAngle = angle1;\n        } else if (angle0 < angle2) {\n          // order is angle0 -> angle2 -> angle1\n          firstAngle = angle0;\n          secondAngle = angle2;\n          flipIt = true;\n        } else {\n          // order is angle2 -> angle0 -> angle1\n          firstAngle = angle2;\n          secondAngle = angle0;\n        }\n      } else if (angle0 < angle2) {\n        // order is angle1 -> angle0 -> angle2\n        firstAngle = angle1;\n        secondAngle = angle0;\n        flipIt = true;\n      } else {\n        if (angle1 < angle2) {\n          // order is angle1 -> angle2 -> angle0\n          firstAngle = angle1;\n          secondAngle = angle2;\n        } else {\n          // order is angle2 -> angle1 -> angle0\n          firstAngle = angle2;\n          secondAngle = angle1;\n          flipIt = true;\n        }\n      }\n      if (flipIt) {\n        isCCW = !isCCW;\n      }\n    } else {\n      // it's three coordinate.  Things are a bit different here\n      // because we have to at least kind of figure out where the\n      // hydrogen might be.\n\n      // before getting started with that, use some of the inchi rules\n      // for contradictory stereochemistry\n      // (Table 10 in the InChi v1 technical manual)\n\n      angle2 = atomVect0.signedAngleTo(atomVect1);\n      if (angle2 < 0) angle2 += 2. * M_PI;\n\n      //  this one is never allowed:\n      //     0   2\n      //      \\ /\n      //       C\n      //       *\n      //       1\n      if (angle0 < (M_PI - 1e-3) && angle1 < (M_PI - 1e-3) &&\n          angle2 < (M_PI - 1e-3)) {\n        if ((bond1->getBondDir() != Bond::NONE &&\n             bond1->getBeginAtomIdx() == bond->getBeginAtomIdx() &&\n             (bond1->getBondDir() != bond->getBondDir() ||\n              (bond2->getBondDir() != Bond::NONE &&\n               bond2->getBeginAtomIdx() == bond->getBeginAtomIdx() &&\n               bond2->getBondDir() != bond1->getBondDir()))) ||\n            (bond2->getBondDir() != Bond::NONE &&\n             bond2->getBeginAtomIdx() == bond->getBeginAtomIdx() &&\n             bond2->getBondDir() != bond->getBondDir())) {\n          BOOST_LOG(rdWarningLog)\n              << \"Warning: conflicting stereochemistry at atom \"\n              << bond->getBeginAtomIdx() << \" ignored.\"\n              << std::endl;  // by rule 1.\" << std::endl;\n          return Atom::CHI_UNSPECIFIED;\n        }\n      }\n      if (bond1->getBondDir() != Bond::NONE &&\n          bond1->getBeginAtomIdx() == bond->getBeginAtomIdx()) {\n        if (!(bond2->getBondDir() != Bond::NONE &&\n              bond2->getBeginAtomIdx() == bond->getBeginAtomIdx())) {\n          BOOST_LOG(rdWarningLog)\n              << \"Warning: conflicting stereochemistry at atom \"\n              << bond->getBeginAtomIdx() << \" ignored.\"\n              << std::endl;  // by rule 2a.\" << std::endl;\n        }\n        if (bond1->getBondDir() != bond->getBondDir()) {\n          // bond1 has a spec and does not match the bond0 spec.\n          // the only cases this is allowed are:\n          //      1        0 1 2\n          //      *         \\*/\n          //  0 - C - 2      C\n          //    and\n          //      1        2 1 0\n          //      *         \\*/\n          //  2 - C - 0      C\n          //\n          if ((angle0 > M_PI && angle0 < angle1) ||\n              (angle0 < M_PI && angle0 > angle1)) {\n            BOOST_LOG(rdWarningLog)\n                << \"Warning: conflicting stereochemistry at atom \"\n                << bond->getBeginAtomIdx() << \" ignored.\"\n                << std::endl;  // by rule 2b.\" << std::endl;\n            return Atom::CHI_UNSPECIFIED;\n          }\n        } else {\n          // bond1 matches, what about bond2 ?\n          if (bond2->getBondDir() != bond->getBondDir()) {\n            // the only cases this is allowed are:\n            //      2        0 2 1\n            //      *         \\*/\n            //  0 - C - 1      C\n            //    and\n            //      2        1 2 0\n            //      *         \\*/\n            //  1 - C - 0      C\n            //\n            if ((angle1 > M_PI && angle1 < angle0) ||\n                (angle1 < M_PI && angle1 > angle0)) {\n              BOOST_LOG(rdWarningLog)\n                  << \"Warning: conflicting stereochemistry at atom \"\n                  << bond->getBeginAtomIdx() << \" ignored.\"\n                  << std::endl;  // by rule 2c.\" << std::endl;\n              return Atom::CHI_UNSPECIFIED;\n            }\n          }\n        }\n      } else if (bond2->getBondDir() != Bond::NONE &&\n                 bond2->getBeginAtomIdx() == bond->getBeginAtomIdx() &&\n                 bond2->getBondDir() != bond->getBondDir()) {\n        // bond2 has a spec and does not match the bond0 spec, but bond1\n        // is not set: this is never allowed.\n        BOOST_LOG(rdWarningLog)\n            << \"Warning: conflicting stereochemistry at atom \"\n            << bond->getBeginAtomIdx() << \" ignored.\"\n            << std::endl;  // by rule 3.\" << std::endl;\n        return Atom::CHI_UNSPECIFIED;\n      }\n\n      if (angle0 < angle1) {\n        firstAngle = angle0;\n        secondAngle = angle1;\n        isCCW = true;\n      } else {\n        firstAngle = angle1;\n        secondAngle = angle0;\n        isCCW = false;\n      }\n      if (secondAngle - firstAngle >= (M_PI - 1e-4)) {\n        // it's a situation like one of these:\n        //\n        //      0        1 0 2\n        //      *         \\*/\n        //  1 - C - 2      C\n        //\n        // In each of these cases, the implicit H is between atoms 1\n        // and 2, so we need to flip the rotation direction (go\n        // around the back).\n        isCCW = !isCCW;\n      }\n    }\n    // reverse the rotation direction if the reference is wedged down:\n    if (bondDir == Bond::BEGINDASH) {\n      isCCW = !isCCW;\n    }\n\n    // ----------------\n    //\n    // We now have the rotation direction using mol-file order.\n    // We need to convert that into the appropriate label for the\n    // central atom\n    //\n    // ----------------\n    int nSwaps = atom->getPerturbationOrder(neighborBondIndices);\n    if (nSwaps % 2) isCCW = !isCCW;\n    if (isCCW)\n      res = Atom::CHI_TETRAHEDRAL_CCW;\n    else\n      res = Atom::CHI_TETRAHEDRAL_CW;\n  }\n\n  return res;\n}\n\nvoid WedgeMolBonds(ROMol &mol, const Conformer *conf) {\n  PRECONDITION(conf, \"no conformer\");\n  INT_MAP_INT wedgeBonds = pickBondsToWedge(mol);\n  for (ROMol::BondIterator bondIt = mol.beginBonds(); bondIt != mol.endBonds();\n       ++bondIt) {\n    Bond *bond = *bondIt;\n    if (bond->getBondType() == Bond::SINGLE) {\n      Bond::BondDir dir = DetermineBondWedgeState(bond, wedgeBonds, conf);\n      if (dir == Bond::BEGINWEDGE || dir == Bond::BEGINDASH) {\n        bond->setBondDir(dir);\n      }\n    }\n  }\n}\n\nINT_MAP_INT pickBondsToWedge(const ROMol &mol) {\n  // we need ring information; make sure findSSSR has been called before\n  // if not call now\n  if (!mol.getRingInfo()->isInitialized()) {\n    MolOps::findSSSR(mol);\n  }\n\n  static int noNbrs = 100;\n  INT_VECT nChiralNbrs(mol.getNumAtoms(), noNbrs);\n\n  // start by looking for bonds that are already wedged\n  for (ROMol::ConstBondIterator cbi = mol.beginBonds(); cbi != mol.endBonds();\n       ++cbi) {\n    const Bond *bond = *cbi;\n    if (bond->getBondDir() == Bond::BEGINWEDGE ||\n        bond->getBondDir() == Bond::BEGINDASH ||\n        bond->getBondDir() == Bond::UNKNOWN) {\n      if (bond->getBeginAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW ||\n          bond->getBeginAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW)\n        nChiralNbrs[bond->getBeginAtomIdx()] = noNbrs + 1;\n      else if (bond->getEndAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW ||\n               bond->getEndAtom()->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW)\n        nChiralNbrs[bond->getEndAtomIdx()] = noNbrs + 1;\n    }\n  }\n\n  // now rank atoms by the number of chiral neighbors or Hs they have:\n  bool chiNbrs = false;\n  for (ROMol::ConstAtomIterator cai = mol.beginAtoms(); cai != mol.endAtoms();\n       ++cai) {\n    const Atom *at = *cai;\n    if (nChiralNbrs[at->getIdx()] > noNbrs) {\n      // std::cerr << \" SKIPPING1: \" << at->getIdx() << std::endl;\n      continue;\n    }\n    Atom::ChiralType type = at->getChiralTag();\n    if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW)\n      continue;\n    nChiralNbrs[at->getIdx()] = 0;\n    chiNbrs = true;\n    ROMol::ADJ_ITER nbrIdx, endNbrs;\n    boost::tie(nbrIdx, endNbrs) = mol.getAtomNeighbors(at);\n    while (nbrIdx != endNbrs) {\n      const ATOM_SPTR nat = mol[*nbrIdx];\n      ++nbrIdx;\n      if (nat->getAtomicNum() == 1) {\n        // special case: it's an H... we weight these especially high:\n        nChiralNbrs[at->getIdx()] -= 10;\n        continue;\n      }\n      type = nat->getChiralTag();\n      if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW)\n        continue;\n      nChiralNbrs[at->getIdx()] -= 1;\n    }\n  }\n  std::vector<unsigned int> indices(mol.getNumAtoms());\n  for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) indices[i] = i;\n  if (chiNbrs) {\n    std::sort(indices.begin(), indices.end(),\n              Rankers::argless<INT_VECT>(nChiralNbrs));\n  }\n#if 0\n  std::cerr << \"  nbrs: \";\n  std::copy(nChiralNbrs.begin(), nChiralNbrs.end(),\n            std::ostream_iterator<int>(std::cerr, \" \"));\n  std::cerr << std::endl;\n  std::cerr << \"  order: \";\n  std::copy(indices.begin(), indices.end(),\n            std::ostream_iterator<int>(std::cerr, \" \"));\n  std::cerr << std::endl;\n#endif\n  // picks a bond for each atom that we will wedge when we write the mol file\n  // here is what we are going to do\n  // - at each chiral center look for a bond that is begins at the atom and\n  //   is not yet picked to be wedged for a different chiral center, preferring\n  //   bonds to Hs\n  // - if we do not find a bond that begins at the chiral center - we will take\n  //   the first bond that is not yet picked by any other chiral centers\n  // we use the orders calculated above to determine which order to do the\n  // wedging\n  INT_MAP_INT res;\n  BOOST_FOREACH (unsigned int idx, indices) {\n    if (nChiralNbrs[idx] > noNbrs) {\n      // std::cerr << \" SKIPPING2: \" << idx << std::endl;\n      continue;  // already have a wedged bond here\n    }\n    const Atom *atom = mol.getAtomWithIdx(idx);\n    Atom::ChiralType type = atom->getChiralTag();\n    // the indices are ordered such that all chiral atoms come first. If\n    // this has no chiral flag, we can stop the whole loop:\n    if (type != Atom::CHI_TETRAHEDRAL_CW && type != Atom::CHI_TETRAHEDRAL_CCW)\n      break;\n    RDKit::ROMol::OBOND_ITER_PAIR atomBonds = mol.getAtomBonds(atom);\n    std::vector<std::pair<int, int> > nbrScores;\n    while (atomBonds.first != atomBonds.second) {\n      const Bond *bond = mol[*atomBonds.first].get();\n      ++atomBonds.first;\n\n      // can only wedge single bonds:\n      if (bond->getBondType() != Bond::SINGLE) continue;\n\n      int bid = bond->getIdx();\n      if (res.find(bid) == res.end()) {\n        // very strong preference for Hs:\n        if (bond->getOtherAtom(atom)->getAtomicNum() == 1) {\n          nbrScores.push_back(std::make_pair(\n              -1000000, bid));  // lower than anything else can be\n          continue;\n        }\n        // prefer lower atomic numbers with lower degrees and no specified\n        // chirality:\n        const Atom *oatom = bond->getOtherAtom(atom);\n        int nbrScore = oatom->getAtomicNum() + 10 * oatom->getDegree() +\n                       100 * ((oatom->getChiralTag() != Atom::CHI_UNSPECIFIED));\n        // prefer neighbors that are nonchiral or have as few chiral neighbors\n        // as possible:\n        int oIdx = oatom->getIdx();\n        if (nChiralNbrs[oIdx] < noNbrs) {\n          // the counts are negative, so we have to subtract them off\n          nbrScore -= 10000 * nChiralNbrs[oIdx];\n        }\n        // prefer bonds to non-ring atoms:\n        nbrScore += 1000 * mol.getRingInfo()->numAtomRings(oIdx);\n        // prefer non-ring bonds;\n        nbrScore += 1000 * mol.getRingInfo()->numBondRings(bid);\n        // std::cerr << \"    nrbScore: \" << idx << \" - \" << oIdx << \" : \"\n        //           << nbrScore << \" nChiralNbrs: \" << nChiralNbrs[oIdx]\n        //           << std::endl;\n        nbrScores.push_back(std::make_pair(nbrScore, bid));\n      }\n    }\n    // There's still one situation where this whole thing can fail: an unlucky\n    // situation where all neighbors of all neighbors of an atom are chiral and\n    // that atom ends up being the last one picked for stereochem assignment.\n    //\n    // We'll catch that as an error here and hope that it's as unlikely to occur\n    // as it seems like it is. (I'm going into this knowing that it's bound to\n    // happen; I'll kick myself and do the hard solution at that point.)\n    CHECK_INVARIANT(nbrScores.size(),\n                    \"no eligible neighbors for chiral center\");\n    std::sort(nbrScores.begin(), nbrScores.end(),\n              Rankers::pairLess<int, int>());\n    res[nbrScores[0].second] = idx;\n  }\n  return res;\n}\n\n//\n// Determine bond wedge state\n///\nBond::BondDir DetermineBondWedgeState(const Bond *bond,\n                                      const INT_MAP_INT &wedgeBonds,\n                                      const Conformer *conf) {\n  PRECONDITION(bond, \"no bond\");\n  PRECONDITION(bond->getBondType() == Bond::SINGLE,\n               \"bad bond order for wedging\");\n  const ROMol *mol = &(bond->getOwningMol());\n  PRECONDITION(mol, \"no mol\");\n\n  Bond::BondDir res = bond->getBondDir();\n  if (!conf) {\n    return res;\n  }\n\n  int bid = bond->getIdx();\n  INT_MAP_INT_CI wbi = wedgeBonds.find(bid);\n  if (wbi == wedgeBonds.end()) {\n    return res;\n  }\n\n  unsigned int waid = wbi->second;\n\n  Atom *atom, *bondAtom;  // = bond->getBeginAtom();\n  if (bond->getBeginAtom()->getIdx() == waid) {\n    atom = bond->getBeginAtom();\n    bondAtom = bond->getEndAtom();\n  } else {\n    atom = bond->getEndAtom();\n    bondAtom = bond->getBeginAtom();\n  }\n\n  Atom::ChiralType chiralType = atom->getChiralTag();\n  CHECK_INVARIANT(chiralType == Atom::CHI_TETRAHEDRAL_CW ||\n                      chiralType == Atom::CHI_TETRAHEDRAL_CCW,\n                  \"\");\n\n  // if we got this far, we really need to think about it:\n  INT_LIST neighborBondIndices;\n  DOUBLE_LIST neighborBondAngles;\n  RDGeom::Point3D centerLoc, tmpPt;\n  centerLoc = conf->getAtomPos(atom->getIdx());\n  tmpPt = conf->getAtomPos(bondAtom->getIdx());\n  centerLoc.z = 0.0;\n  tmpPt.z = 0.0;\n  RDGeom::Point3D refVect = centerLoc.directionVector(tmpPt);\n\n  neighborBondIndices.push_back(bond->getIdx());\n  neighborBondAngles.push_back(0.0);\n\n  ROMol::OEDGE_ITER beg, end;\n  boost::tie(beg, end) = mol->getAtomBonds(atom);\n  while (beg != end) {\n    Bond *nbrBond = (*mol)[*beg].get();\n    Atom *otherAtom = nbrBond->getOtherAtom(atom);\n    if (nbrBond != bond) {\n      tmpPt = conf->getAtomPos(otherAtom->getIdx());\n      tmpPt.z = 0.0;\n      RDGeom::Point3D tmpVect = centerLoc.directionVector(tmpPt);\n      double angle = refVect.signedAngleTo(tmpVect);\n      if (angle < 0.0) angle += 2. * M_PI;\n      INT_LIST::iterator nbrIt = neighborBondIndices.begin();\n      DOUBLE_LIST::iterator angleIt = neighborBondAngles.begin();\n      // find the location of this neighbor in our angle-sorted list\n      // of neighbors:\n      while (angleIt != neighborBondAngles.end() && angle > (*angleIt)) {\n        ++angleIt;\n        ++nbrIt;\n      }\n      neighborBondAngles.insert(angleIt, angle);\n      neighborBondIndices.insert(nbrIt, nbrBond->getIdx());\n    }\n    ++beg;\n  }\n\n  // at this point, neighborBondIndices contains a list of bond\n  // indices from the central atom.  They are arranged starting\n  // at the reference bond in CCW order (based on the current\n  // depiction).\n  int nSwaps = atom->getPerturbationOrder(neighborBondIndices);\n\n  // in the case of three-coordinated atoms we may have to worry about\n  // the location of the implicit hydrogen - Issue 209\n  // Check if we have one of these situation\n  //\n  //      0        1 0 2\n  //      *         \\*/\n  //  1 - C - 2      C\n  //\n  // here the hydrogen will be between 1 and 2 and we need to add an additional\n  // swap\n  if (neighborBondAngles.size() == 3) {\n    // three coordinated\n    DOUBLE_LIST::iterator angleIt = neighborBondAngles.begin();\n    ++angleIt;  // the first is the 0 (or reference bond - we will ignoire that\n    double angle1 = (*angleIt);\n    ++angleIt;\n    double angle2 = (*angleIt);\n    if (angle2 - angle1 >= (M_PI - 1e-4)) {\n      // we have the above situation\n      nSwaps++;\n    }\n  }\n\n#ifdef VERBOSE_STEREOCHEM\n  BOOST_LOG(rdDebugLog) << \"--------- \" << nSwaps << std::endl;\n  std::copy(neighborBondIndices.begin(), neighborBondIndices.end(),\n            std::ostream_iterator<int>(BOOST_LOG(rdDebugLog), \" \"));\n  BOOST_LOG(rdDebugLog) << std::endl;\n  std::copy(neighborBondAngles.begin(), neighborBondAngles.end(),\n            std::ostream_iterator<double>(BOOST_LOG(rdDebugLog), \" \"));\n  BOOST_LOG(rdDebugLog) << std::endl;\n#endif\n  if (chiralType == Atom::CHI_TETRAHEDRAL_CCW) {\n    if (nSwaps % 2 == 1) {  // ^ reverse) {\n      res = Bond::BEGINDASH;\n    } else {\n      res = Bond::BEGINWEDGE;\n    }\n  } else {\n    if (nSwaps % 2 == 1) {  // ^ reverse) {\n      res = Bond::BEGINWEDGE;\n    } else {\n      res = Bond::BEGINDASH;\n    }\n  }\n\n  return res;\n}\n\n// handles stereochem markers set by the Mol file parser and\n// converts them to the RD standard:\nvoid DetectAtomStereoChemistry(RWMol &mol, const Conformer *conf) {\n  PRECONDITION(conf, \"no conformer\");\n\n  for (RWMol::BondIterator bondIt = mol.beginBonds(); bondIt != mol.endBonds();\n       ++bondIt) {\n    Bond *bond = *bondIt;\n    if (bond->getBondDir() != Bond::UNKNOWN) {\n      Bond::BondDir dir = bond->getBondDir();\n      // the bond is marked as chiral:\n      if (dir == Bond::BEGINWEDGE || dir == Bond::BEGINDASH) {\n        Atom *atom = bond->getBeginAtom();\n        if (atom->getImplicitValence() == -1) {\n          atom->calcExplicitValence();\n          atom->calcImplicitValence(false);\n        }\n        Atom::ChiralType code = FindAtomStereochemistry(mol, bond, conf);\n        atom->setChiralTag(code);\n        // within the RD representation, if a three-coordinate atom\n        // is chiral and has an implicit H, that H needs to be made explicit:\n        if (atom->getDegree() == 3 && !atom->getNumExplicitHs() &&\n            atom->getNumImplicitHs() == 1) {\n          atom->setNumExplicitHs(1);\n          // recalculated number of implicit Hs:\n          atom->updatePropertyCache();\n        }\n      }\n    }\n  }\n}\n\nvoid setBondDirRelativeToAtom(Bond *bond, Atom *atom, Bond::BondDir dir,\n                              bool reverse, boost::dynamic_bitset<> &needsDir) {\n  PRECONDITION(bond, \"bad bond\");\n  PRECONDITION(atom, \"bad atom\");\n  PRECONDITION(dir == Bond::ENDUPRIGHT || dir == Bond::ENDDOWNRIGHT, \"bad dir\");\n  PRECONDITION(atom == bond->getBeginAtom() || atom == bond->getEndAtom(),\n               \"atom doesn't belong to bond\");\n  // std::cerr << \"\\t\\t>sbdra :  bond \" << bond->getIdx() << \" atom \"\n  //           << atom->getIdx() << \" dir : \" << dir << \" reverse: \" << reverse\n  //           << std::endl;\n  Atom *oAtom;\n  if (bond->getBeginAtom() != atom) {\n    reverse = !reverse;\n    oAtom = bond->getBeginAtom();\n  } else {\n    oAtom = bond->getEndAtom();\n  }\n  if (reverse) {\n    dir = (dir == Bond::ENDUPRIGHT ? Bond::ENDDOWNRIGHT : Bond::ENDUPRIGHT);\n  }\n  // to ensure maximum compatibility, even when a bond has unknown stereo (set\n  // explicitly and recorded in _UnknownStereo property), I will still let a\n  // direction to be computed. You must check the _UnknownStereo property to\n  // make sure whether this bond is explictly set to have no direction info.\n  // This makes sense because the direction info are all derived from\n  // coordinates, the _UnknownStereo property is like extra metadata to be\n  // used with the direction info.\n  bond->setBondDir(dir);\n  // std::cerr<<\"\\t\\t\\t\\t -> dir \"<<dir<<std::endl;\n  // check for other single bonds around the other atom who need their\n  // direction set and set it as demanded by the direction of this one:\n  ROMol::OEDGE_ITER beg, end;\n  boost::tie(beg, end) = oAtom->getOwningMol().getAtomBonds(oAtom);\n  while (beg != end) {\n    Bond *nbrBond = oAtom->getOwningMol()[*beg].get();\n    ++beg;\n    if (nbrBond != bond && nbrBond->getBondType() != Bond::DOUBLE &&\n        needsDir[nbrBond->getIdx()]) {\n      Bond::BondDir nbrDir = Bond::NONE;\n      if ((nbrBond->getBeginAtom() == oAtom && bond->getBeginAtom() == oAtom) ||\n          (nbrBond->getEndAtom() == oAtom && bond->getEndAtom() == oAtom)) {\n        // both bonds either start or end here; they *must* have different\n        // directions:\n        nbrDir =\n            (dir == Bond::ENDUPRIGHT ? Bond::ENDDOWNRIGHT : Bond::ENDUPRIGHT);\n      } else {\n        // one starts here, the other ends here, they need to have the same\n        // direction:\n        nbrDir = dir;\n      }\n      nbrBond->setBondDir(nbrDir);\n      needsDir[nbrBond->getIdx()] = 0;\n      // std::cerr << \"\\t\\t\\t\\t update bond \" << nbrBond->getIdx() << \" to dir \"\n      //           << nbrDir << std::endl;\n    }\n  }\n}\n\nbool isLinearArrangement(const RDGeom::Point3D &v1, const RDGeom::Point3D &v2,\n                         double tol = 0.035) {  // tolerance of 2 degrees\n  return fabs(v2.angleTo(v1) - M_PI) < tol;\n}\n\nvoid updateDoubleBondNeighbors(ROMol &mol, Bond *dblBond, const Conformer *conf,\n                               boost::dynamic_bitset<> &needsDir,\n                               std::vector<unsigned int> &singleBondCounts,\n                               const VECT_INT_VECT &singleBondNbrs) {\n  // we want to deal only with double bonds:\n  PRECONDITION(dblBond, \"bad bond\");\n  PRECONDITION(dblBond->getBondType() == Bond::DOUBLE, \"not a double bond\");\n  PRECONDITION(conf, \"no conformer\");\n  if (!needsDir[dblBond->getIdx()]) return;\n  needsDir.set(dblBond->getIdx(), 0);\n#if 0\n  std::cerr << \"**********************\\n\";\n  std::cerr << \"**********************\\n\";\n  std::cerr << \"**********************\\n\";\n  std::cerr << \"UDBN: \" << dblBond->getIdx() << \" \"\n            << dblBond->getBeginAtomIdx() << \"=\" << dblBond->getEndAtomIdx()\n            << \"\\n\";\n#endif\n\n  ROMol::OEDGE_ITER beg, end;\n  std::vector<Bond *> followupBonds;\n\n  Bond *bond1 = 0, *obond1 = 0;\n  bool squiggleBondSeen = false;\n  boost::tie(beg, end) = mol.getAtomBonds(dblBond->getBeginAtom());\n  while (beg != end) {\n    Bond *tBond = mol[*beg].get();\n    if (tBond->getBondType() == Bond::SINGLE ||\n        tBond->getBondType() == Bond::AROMATIC) {\n      // prefer bonds that already have their directionality set\n      // or that are adjacent to more double bonds:\n      if (!bond1) {\n        bond1 = tBond;\n      } else if (needsDir[tBond->getIdx()]) {\n        if (singleBondCounts[tBond->getIdx()] >\n            singleBondCounts[bond1->getIdx()]) {\n          obond1 = bond1;\n          bond1 = tBond;\n        } else {\n          obond1 = tBond;\n        }\n      } else {\n        obond1 = bond1;\n        bond1 = tBond;\n      }\n    }\n    if (tBond->getBondType() == Bond::SINGLE &&\n        tBond->getBondDir() == Bond::UNKNOWN) {\n      squiggleBondSeen = true;\n      break;\n    }\n\n    ++beg;\n  }\n  // Don't do any direction setting if we've seen a squiggle bond, but do mark\n  // the double bond as a crossed bond and return\n  if (!bond1 || squiggleBondSeen) {\n    dblBond->setBondDir(Bond::EITHERDOUBLE);\n    return;\n  }\n\n  Bond *bond2 = 0, *obond2 = 0;\n  boost::tie(beg, end) = mol.getAtomBonds(dblBond->getEndAtom());\n  while (beg != end) {\n    Bond *tBond = mol[*beg].get();\n    if (tBond->getBondType() == Bond::SINGLE ||\n        tBond->getBondType() == Bond::AROMATIC) {\n      if (!bond2) {\n        bond2 = tBond;\n      } else if (needsDir[tBond->getIdx()]) {\n        if (singleBondCounts[tBond->getIdx()] >\n            singleBondCounts[bond2->getIdx()]) {\n          obond2 = bond2;\n          bond2 = tBond;\n        } else {\n          obond2 = tBond;\n        }\n      } else {\n        // we already had a bond2 and we don't need to set the direction\n        // on the new one, so swap.\n        obond2 = bond2;\n        bond2 = tBond;\n      }\n    }\n    if (tBond->getBondType() == Bond::SINGLE &&\n        tBond->getBondDir() == Bond::UNKNOWN) {\n      squiggleBondSeen = true;\n      break;\n    }\n\n    ++beg;\n  }\n  // Don't do any direction setting if we've seen a squiggle bond, but do mark\n  // the double bond as a crossed bond and return\n  if (!bond2 || squiggleBondSeen) {\n    dblBond->setBondDir(Bond::EITHERDOUBLE);\n    return;\n  }\n\n  CHECK_INVARIANT(bond1 && bond2, \"no bonds found\");\n  RDGeom::Point3D beginP = conf->getAtomPos(dblBond->getBeginAtomIdx());\n  RDGeom::Point3D endP = conf->getAtomPos(dblBond->getEndAtomIdx());\n  RDGeom::Point3D bond1P =\n      conf->getAtomPos(bond1->getOtherAtomIdx(dblBond->getBeginAtomIdx()));\n  RDGeom::Point3D bond2P =\n      conf->getAtomPos(bond2->getOtherAtomIdx(dblBond->getEndAtomIdx()));\n  // check for a linear arrangement of atoms on either end:\n  bool linear = false;\n  RDGeom::Point3D p1;\n  RDGeom::Point3D p2;\n  p1 = bond1P - beginP;\n  p2 = endP - beginP;\n  if (isLinearArrangement(p1, p2)) {\n    if (!obond1) {\n      linear = true;\n    } else {\n      // one of the bonds was linear; what about the other one?\n      Bond *tBond = bond1;\n      bond1 = obond1;\n      obond1 = tBond;\n      bond1P =\n          conf->getAtomPos(bond1->getOtherAtomIdx(dblBond->getBeginAtomIdx()));\n      p1 = bond1P - beginP;\n      if (isLinearArrangement(p1, p2)) {\n        linear = true;\n      }\n    }\n  }\n  if (!linear) {\n    p1 = bond2P - endP;\n    p2 = beginP - endP;\n    if (isLinearArrangement(p1, p2)) {\n      if (!obond2) {\n        linear = true;\n      } else {\n        Bond *tBond = bond2;\n        bond2 = obond2;\n        obond2 = tBond;\n        bond2P =\n            conf->getAtomPos(bond2->getOtherAtomIdx(dblBond->getEndAtomIdx()));\n        p1 = bond2P - beginP;\n        if (isLinearArrangement(p1, p2)) {\n          linear = true;\n        }\n      }\n    }\n  }\n  if (linear) {\n    dblBond->setBondDir(Bond::EITHERDOUBLE);\n    return;\n  }\n\n  double ang = RDGeom::computeDihedralAngle(bond1P, beginP, endP, bond2P);\n  bool sameTorsionDir;\n  if (ang < M_PI / 2) {\n    sameTorsionDir = false;\n  } else {\n    sameTorsionDir = true;\n  }\n  // std::cerr << \"   angle: \" << ang << \" sameTorsionDir: \" << sameTorsionDir\n  // << \"\\n\";\n\n  /*\n     Time for some clarificatory text, because this gets really\n     confusing really fast.\n\n     The dihedral angle analysis above is based on viewing things\n     with an atom order as follows:\n\n     1\n      \\\n       2 = 3\n            \\\n             4\n\n     so dihedrals > 90 correspond to sameDir=true\n\n     however, the stereochemistry representation is\n     based on something more like this:\n\n     2\n      \\\n       1 = 3\n            \\\n             4\n     (i.e. we consider the direction-setting single bonds to be\n      starting at the double-bonded atom)\n\n  */\n  bool reverseBondDir = sameTorsionDir;\n\n  Atom *atom1 = dblBond->getBeginAtom(), *atom2 = dblBond->getEndAtom();\n  if (needsDir[bond1->getIdx()]) {\n    BOOST_FOREACH (int bidx, singleBondNbrs[bond1->getIdx()]) {\n      // std::cerr << \"       neighbor from: \" << bond1->getIdx() << \" \" << bidx\n      //           << \": \" << needsDir[bidx] << std::endl;\n      if (needsDir[bidx]) followupBonds.push_back(mol.getBondWithIdx(bidx));\n    }\n  }\n  if (needsDir[bond2->getIdx()]) {\n    BOOST_FOREACH (int bidx, singleBondNbrs[bond2->getIdx()]) {\n      // std::cerr << \"       neighbor from: \" << bond2->getIdx() << \" \" << bidx\n      //           << \": \" << needsDir[bidx] << std::endl;\n      if (needsDir[bidx]) followupBonds.push_back(mol.getBondWithIdx(bidx));\n    }\n  }\n  if (!needsDir[bond1->getIdx()]) {\n    if (!needsDir[bond2->getIdx()]) {\n      // check that we agree\n    } else {\n      if (bond1->getBeginAtom() != atom1) {\n        reverseBondDir = !reverseBondDir;\n      }\n      setBondDirRelativeToAtom(bond2, atom2, bond1->getBondDir(),\n                               reverseBondDir, needsDir);\n    }\n  } else if (!needsDir[bond2->getIdx()]) {\n    if (bond2->getBeginAtom() != atom2) {\n      reverseBondDir = !reverseBondDir;\n    }\n    setBondDirRelativeToAtom(bond1, atom1, bond2->getBondDir(), reverseBondDir,\n                             needsDir);\n  } else {\n    setBondDirRelativeToAtom(bond1, atom1, Bond::ENDDOWNRIGHT, false, needsDir);\n    setBondDirRelativeToAtom(bond2, atom2, Bond::ENDDOWNRIGHT, reverseBondDir,\n                             needsDir);\n  }\n  needsDir[bond1->getIdx()] = 0;\n  needsDir[bond2->getIdx()] = 0;\n  if (obond1 && needsDir[obond1->getIdx()]) {\n    setBondDirRelativeToAtom(obond1, atom1, bond1->getBondDir(),\n                             bond1->getBeginAtom() == atom1, needsDir);\n    needsDir[obond1->getIdx()] = 0;\n  }\n  if (obond2 && needsDir[obond2->getIdx()]) {\n    setBondDirRelativeToAtom(obond2, atom2, bond2->getBondDir(),\n                             bond2->getBeginAtom() == atom2, needsDir);\n    needsDir[obond2->getIdx()] = 0;\n  }\n#if 0\n  std::cerr << \"  1:\" << bond1->getIdx() << \" \";\n  if (obond1)\n    std::cerr << obond1->getIdx() << std::endl;\n  else\n    std::cerr << \"N/A\" << std::endl;\n  std::cerr << \"  2:\" << bond2->getIdx() << \" \";\n  if (obond2)\n    std::cerr << obond2->getIdx() << std::endl;\n  else\n    std::cerr << \"N/A\" << std::endl;\n  std::cerr << \"**********************\\n\";\n  std::cerr << \"**********************\\n\";\n  std::cerr << \"**********************\\n\";\n#endif\n  BOOST_FOREACH (Bond *oDblBond, followupBonds) {\n    // std::cerr << \"FOLLOWUP: \" << oDblBond->getIdx() << \" \"\n    //           << needsDir[oDblBond->getIdx()] << std::endl;\n    updateDoubleBondNeighbors(mol, oDblBond, conf, needsDir, singleBondCounts,\n                              singleBondNbrs);\n  }\n}\n\nvoid ClearSingleBondDirFlags(ROMol &mol) {\n  for (RWMol::BondIterator bondIt = mol.beginBonds(); bondIt != mol.endBonds();\n       ++bondIt) {\n    if ((*bondIt)->getBondType() == Bond::SINGLE) {\n      if ((*bondIt)->getBondDir() == Bond::UNKNOWN)\n        (*bondIt)->setProp(common_properties::_UnknownStereo, 1);\n      (*bondIt)->setBondDir(Bond::NONE);\n    }\n  }\n}\n\nvoid DetectBondStereoChemistry(ROMol &mol, const Conformer *conf) {\n  PRECONDITION(conf, \"no conformer\");\n#if 0\n    std::cerr << \">>>>>>>>>>>>>>>>>>>>>*\\n\";\n    std::cerr << \">>>>>>>>>>>>>>>>>>>>>*\\n\";\n    std::cerr << \">>>>>>>>>>>>>>>>>>>>>*\\n\";\n    std::cerr << \"DBSN: \"<<\"\\n\";\n    std::cerr << \">>>>>>>>>>>>>>>>>>>>>*\\n\";\n    std::cerr << \">>>>>>>>>>>>>>>>>>>>>*\\n\";\n    std::cerr << \">>>>>>>>>>>>>>>>>>>>>*\\n\";\n#endif\n  // used to store the number of single bonds a given\n  // single bond is adjacent to\n  std::vector<unsigned int> singleBondCounts(mol.getNumBonds(), 0);\n  std::vector<Bond *> bondsInPlay;\n  // keeps track of which single bonds are adjacent to each double bond:\n  VECT_INT_VECT dblBondNbrs(mol.getNumBonds());\n  // keeps track of which double bonds are adjacent to each single bond:\n  VECT_INT_VECT singleBondNbrs(mol.getNumBonds());\n  // keeps track of which single bonds need a dir set and which double bonds\n  // need to have their neighbors' dirs set\n  boost::dynamic_bitset<> needsDir(mol.getNumBonds());\n\n  // find double bonds that should be considered for\n  // stereochemistry\n  // NOTE that we are explicitly excluding double bonds in rings\n  // with this test.\n  bool resetRings = false;\n  if (!mol.getRingInfo()->isInitialized()) {\n    resetRings = true;\n    MolOps::fastFindRings(mol);\n  }\n\n  for (RWMol::BondIterator bondIt = mol.beginBonds(); bondIt != mol.endBonds();\n       ++bondIt) {\n    if ((*bondIt)->getBondType() == Bond::DOUBLE &&\n        (*bondIt)->getStereo() != Bond::STEREOANY &&\n        (*bondIt)->getBondDir() != Bond::EITHERDOUBLE &&\n        (*bondIt)->getBeginAtom()->getDegree() > 1 &&\n        (*bondIt)->getEndAtom()->getDegree() > 1 &&\n        !(mol.getRingInfo()->numBondRings((*bondIt)->getIdx()))) {\n      const Atom *a1 = (*bondIt)->getBeginAtom();\n      const Atom *a2 = (*bondIt)->getEndAtom();\n\n      ROMol::OEDGE_ITER beg, end;\n      boost::tie(beg, end) = mol.getAtomBonds(a1);\n      while (beg != end) {\n        const Bond *nbrBond = mol[*beg].get();\n        if (nbrBond->getBondType() == Bond::SINGLE ||\n            nbrBond->getBondType() == Bond::AROMATIC) {\n          singleBondCounts[nbrBond->getIdx()] += 1;\n          needsDir[nbrBond->getIdx()] = 1;\n          needsDir[(*bondIt)->getIdx()] = 1;\n          dblBondNbrs[(*bondIt)->getIdx()].push_back(nbrBond->getIdx());\n          // the search may seem inefficient, but these vectors are going to be\n          // at most 2 long (with very few exceptions). It's just not worth\n          // using a different data structure\n          if (std::find(singleBondNbrs[nbrBond->getIdx()].begin(),\n                        singleBondNbrs[nbrBond->getIdx()].end(),\n                        (*bondIt)->getIdx()) ==\n              singleBondNbrs[nbrBond->getIdx()].end()) {\n            singleBondNbrs[nbrBond->getIdx()].push_back((*bondIt)->getIdx());\n          }\n        }\n        ++beg;\n      }\n      boost::tie(beg, end) = mol.getAtomBonds(a2);\n      while (beg != end) {\n        const Bond *nbrBond = mol[*beg].get();\n        if (nbrBond->getBondType() == Bond::SINGLE ||\n            nbrBond->getBondType() == Bond::AROMATIC) {\n          singleBondCounts[nbrBond->getIdx()] += 1;\n          needsDir[nbrBond->getIdx()] = 1;\n          needsDir[(*bondIt)->getIdx()] = 1;\n          dblBondNbrs[(*bondIt)->getIdx()].push_back(nbrBond->getIdx());\n\n          // the search may seem inefficient, but these vectors are going to be\n          // at most 2 long (with very few exceptions). It's just not worth\n          // using a different data structure\n          if (std::find(singleBondNbrs[nbrBond->getIdx()].begin(),\n                        singleBondNbrs[nbrBond->getIdx()].end(),\n                        (*bondIt)->getIdx()) ==\n              singleBondNbrs[nbrBond->getIdx()].end()) {\n            singleBondNbrs[nbrBond->getIdx()].push_back((*bondIt)->getIdx());\n          }\n        }\n        ++beg;\n      }\n      bondsInPlay.push_back(*bondIt);\n    }\n  }\n\n  if (!bondsInPlay.size()) {\n    if (resetRings) mol.getRingInfo()->reset();\n    return;\n  }\n\n  // order the double bonds based on the singleBondCounts of their neighbors:\n  std::vector<std::pair<unsigned int, Bond *> > orderedBondsInPlay;\n  for (unsigned int i = 0; i < bondsInPlay.size(); ++i) {\n    Bond *dblBond = bondsInPlay[i];\n    unsigned int countHere =\n        std::accumulate(dblBondNbrs[dblBond->getIdx()].begin(),\n                        dblBondNbrs[dblBond->getIdx()].end(), 0);\n    // and favor double bonds that are *not* in rings. The combination of using\n    // the sum\n    // above (instead of the max) and this ring-membershipt test seem to fix\n    // sf.net issue 3009836\n    if (!(mol.getRingInfo()->numBondRings(dblBond->getIdx()))) countHere *= 10;\n    orderedBondsInPlay.push_back(std::make_pair(countHere, dblBond));\n  }\n  std::sort(orderedBondsInPlay.begin(), orderedBondsInPlay.end());\n\n  // oof, now loop over the double bonds in that order and\n  // update their neighbor directionalities:\n  std::vector<std::pair<unsigned int, Bond *> >::reverse_iterator pairIter;\n  for (pairIter = orderedBondsInPlay.rbegin();\n       pairIter != orderedBondsInPlay.rend(); ++pairIter) {\n    updateDoubleBondNeighbors(mol, pairIter->second, conf, needsDir,\n                              singleBondCounts, singleBondNbrs);\n  }\n  if (resetRings) mol.getRingInfo()->reset();\n}\n}\n", "meta": {"hexsha": "9747edebe4f870c2932431795087e32b13e5625e", "size": 41504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/FileParsers/MolFileStereochem.cpp", "max_stars_repo_name": "darkreactions/rdkit", "max_stars_repo_head_hexsha": "0c388029c1f9386d832f6c321e59a11589c373d8", "max_stars_repo_licenses": ["PostgreSQL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/GraphMol/FileParsers/MolFileStereochem.cpp", "max_issues_repo_name": "darkreactions/rdkit", "max_issues_repo_head_hexsha": "0c388029c1f9386d832f6c321e59a11589c373d8", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/GraphMol/FileParsers/MolFileStereochem.cpp", "max_forks_repo_name": "darkreactions/rdkit", "max_forks_repo_head_hexsha": "0c388029c1f9386d832f6c321e59a11589c373d8", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-04T02:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T01:18:46.000Z", "avg_line_length": 36.5030782762, "max_line_length": 80, "alphanum_fraction": 0.5726917887, "num_tokens": 11784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022537869825406, "lm_q2_score": 0.031143832895315225, "lm_q1q2_score": 0.011530237327783221}}
{"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 <algorithm>\n#include <stdexcept>\n#include <map>\n#include <utility>\n#include <algorithm>\n#include <string>\n#include <iostream>\n#include <time.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <hashclash/saveload_bz2.hpp>\n#include <hashclash/sha1detail.hpp>\n#include <hashclash/rng.hpp>\n#include <hashclash/sha1differentialpath.hpp>\n#include <hashclash/progress_display.hpp>\n\n#include \"main.hpp\"\n\nunsigned int lowpathindex;\n\nvoid random_permutation(vector<sha1differentialpath>& paths, path_container& container)\n{\n\t// use a pseudo-random permutation fixed by inputs\n\tseed(paths.size()); addseed(container.t); addseed(container.modn);\n\tfor (unsigned i = 0; i < paths.size(); ++i)\n\t{\n\t\tunsigned k = xrng64() % paths.size();\n\t\tpaths[i].swap(paths[k]);\n\t}\n\taddseed(time(NULL));\n}\n\ninline std::string pathsstring(const std::string& basepath, unsigned modi, unsigned modn)\n{\n\treturn workdir +  \"/\"  + basepath \n\t\t+ \"_\" + boost::lexical_cast<std::string>(modi) \n\t\t+ \"of\" + boost::lexical_cast<std::string>(modn);\n}\n\nunsigned lower_eqbits(const sha1differentialpath& _Left, const sha1differentialpath& _Right)\n{\n\tunsigned t = _Left.tend() - 1;\n\tuint32 LdFt = 0 - _Left[t].getsdr().rotate_left(5).adddiff() - _Left[t-4].getsdr().rotate_left(30).adddiff();\n\tuint32 LdFtp1 = 0 - _Left[t-3].getsdr().rotate_left(30).adddiff();\n\tuint32 LdFtp2 = 0 - _Left[t-2].getsdr().rotate_left(30).adddiff();\n\tuint32 LdFtp3 = 0 - _Left[t-1].getsdr().rotate_left(30).adddiff();\n\tuint32 LdFtp4 = 0 - _Left[t].getsdr().rotate_left(30).adddiff();\n\tuint32 LdQtm1 = _Left[t-1].diff();\n\tuint32 LdQt = _Left[t].diff();\n\tuint32 RdFt = 0 - _Right[t].getsdr().rotate_left(5).adddiff() - _Right[t-4].getsdr().rotate_left(30).adddiff();\n\tuint32 RdFtp1 = 0 - _Right[t-3].getsdr().rotate_left(30).adddiff();\n\tuint32 RdFtp2 = 0 - _Right[t-2].getsdr().rotate_left(30).adddiff();\n\tuint32 RdFtp3 = 0 - _Right[t-1].getsdr().rotate_left(30).adddiff();\n\tuint32 RdFtp4 = 0 - _Right[t].getsdr().rotate_left(30).adddiff();\n\tuint32 RdQtm1 = _Right[t-1].diff();\n\tuint32 RdQt = _Right[t].diff();\n\tunsigned b = 0;\n\twhile (b < 32+8) {\n\t\tif (b < 32) {\n\t\t\tif (_Left(t-3,(b+2)&31)!=_Right(t-3,(b+2)&31)) break;\n\t\t\tif (_Left(t-2,(b+2)&31)!=_Right(t-2,(b+2)&31)) break;\n\t\t\tif ((LdFt^RdFt)&(1<<b)) break;\n\t\t\tif ((LdQtm1^RdQtm1)&(1<<b)) break;\n\t\t}\n\t\tif (b >= 2 && b-2 < 32) {\n\t\t\tif ((LdFtp1^RdFtp1)&(1<<(b-2))) break;\n\t\t\tif ((LdQt^RdQt)&(1<<(b-2))) break;\n\t\t}\n\t\tif (b >= 4 && b-4 < 32 && ((LdFtp2^RdFtp2)&(1<<(b-4)))) break;\n\t\tif (b >= 6 && b-6 < 32 && ((LdFtp3^RdFtp3)&(1<<(b-6)))) break;\n\t\tif (b >= 8 && b-8 < 32 && ((LdFtp4^RdFtp4)&(1<<(b-8)))) break;\n\t\t++b;\n\t}\n\treturn b;\n}\n\n\n\n\n\nprogress_display* dostep_progress = 0;\nunsigned dostep_index = 0;\nstruct dostep_thread {\n\tdostep_thread(vector<sha1differentialpath>& inlow, vector<sha1differentialpath>& inhigh, path_container& out, bool randomize)\n\t\t: pathsinlow(inlow), pathsinhigh(inhigh), container(out), random(randomize), worker(0)\n\t{}\n\t~dostep_thread()\n\t{ if (worker) delete worker; }\n\tvector<sha1differentialpath>& pathsinlow;\n\tvector<sha1differentialpath>& pathsinhigh;\n\tpath_container& container;\n\tsha1_connect_thread* worker;\n\tsha1differentialpath prelowpath;\n\tvector<sha1differentialpath> lowpaths;\n\tbool random;\n\tvoid operator()() {\n\t\ttry {\n\t\t\tworker = new sha1_connect_thread;\n\t\t\twhile (true) {\n\t\t\t\tmut.lock();\n\t\t\t\tif (dostep_index >= pathsinlow.size())\n\t\t\t\t{\n\t\t\t\t\tmut.unlock();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// obtain a stripe of consecutive lowpaths\n\t\t\t\tstatic const unsigned stripe = (1<<5); // must be a power of 2\n\t\t\t\tunsigned count = stripe;\n\t\t\t\tif (dostep_index+count >= pathsinlow.size())\n\t\t\t\t\tcount = pathsinlow.size() - dostep_index;\n\t\t\t\tdostep_index += count;\n\t\t\t\t(*dostep_progress) += count;\n\t\t\t\tlowpaths.clear();\n\t\t\t\tif (random) {\n\t\t\t\t\tunsigned kr;\n\t\t\t\t\tdo {\n\t\t\t\t\t\tkr = (xrng128()%pathsinlow.size());\n\t\t\t\t\t\tkr &= ~(stripe-1); // set kr to beginning of stripe (set necessary low bits to zero)\n\t\t\t\t\t} while (pathsinlow[kr].path.size() == 0);\n\t\t\t\t\tfor (unsigned i = 0; i < count; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tlowpaths.push_back(pathsinlow[kr+i]);\n\t\t\t\t\t\tpathsinlow[kr+i].clear();\n\t\t\t\t\t\tworker->lowpathindex = kr;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tunsigned kr = dostep_index - count;\n\t\t\t\t\tfor (unsigned i = 0; i < count; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tlowpaths.push_back(pathsinlow[kr+i]);\n\t\t\t\t\t\tpathsinlow[kr+i].clear();\n\t\t\t\t\t\tworker->lowpathindex = kr;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmut.unlock();\n\n\t\t\t\tfor (unsigned i = 0; i < lowpaths.size(); ++i,++worker->lowpathindex)\n\t\t\t\t{\n\t\t\t\t\tif (prelowpath.path.size())\n\t\t\t\t\t\tworker->sha1_connect(lowpaths[i], pathsinhigh, container, lower_eqbits(lowpaths[i],prelowpath));\n\t\t\t\t\telse\n\t\t\t\t\t\tworker->sha1_connect(lowpaths[i], pathsinhigh, container, 0);\n\t\t\t\t\tprelowpath.swap(lowpaths[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\t\tcatch (std::exception & e) { cerr << \"Worker thread: caught exception:\" << endl << e.what() << endl; } \n\t\tcatch (...) { cerr << \"Worker thread: caught unknown exception:\" << endl; }\n\t}       \n};\nvoid dostep_threaded(vector<sha1differentialpath>& inlow, vector<sha1differentialpath>& inhigh, path_container& out, bool randomize = true)\n{\n\tmut.lock();\n\tdostep_index = 0;\n\tcout << \"Starting threads...\" << flush;\n\tboost::thread_group mythreads;\n\tfor (unsigned i = 0; i < out.threads; ++i) {\n\t\tcout << i << flush;\n\t\tmythreads.create_thread(*new dostep_thread(inlow,inhigh,out,randomize));\n\t\tcout << i << flush;\n\t}\n\tcout << endl;\n\tstd::string tstring = \"t=\" + boost::lexical_cast<std::string>(out.t) + \": \";\n\tif (tstring.size() == 5) tstring += \" \";\n\tdostep_progress = new progress_display(inlow.size(), true, cout, tstring, \"      \", \"      \");\n\tmut.unlock();\n\tmythreads.join_all();\n\tdelete dostep_progress;\n}\n\n\n\n\n\nvoid load_upper_paths(vector<sha1differentialpath>& pathsinhigh, path_container& container)\n{\n        const unsigned t = container.t;\n        const unsigned modn = container.modn;\n        const unsigned modi = container.modi;\n        const unsigned mode = container.splitmode; \n        // 0 = split upperpath sorted, 1 = split upperpath random, 2 = split lowerpath sorted, 3 = split lowerpath random\n        try {\n                cout << \"Loading \" << container.inputfilehigh << \"...\" << flush;\n                if (modn > 1 && mode <= 1) {\n                        vector<sha1differentialpath> tmp;\n                        load_bz2(tmp, binary_archive, container.inputfilehigh);\n                        if (mode == 1) {\n                                random_permutation(tmp, container);\n                                pathsinhigh.reserve((tmp.size()+modn)/modn); \n                                for (unsigned j = modi; j < tmp.size(); j += modn) {\n                                        pathsinhigh.push_back(tmp[j]);\n                                }\n                                sort(pathsinhigh.begin(), pathsinhigh.end(), diffpathupper_less());\n                        } else {\n                                sort(tmp.begin(), tmp.end(), diffpathupper_less());\n                                unsigned blockstart = (modi*tmp.size())/modn;\n                                unsigned blockend = ((modi+1)*tmp.size())/modn;\n                                pathsinhigh.reserve(blockend - blockstart);   \n                                for (unsigned k = blockstart; k < blockend; ++k)\n                                        pathsinhigh.push_back(tmp[k]);\n                        }\n                } else {\n                        load_bz2(pathsinhigh, binary_archive, container.inputfilehigh);\n                        sort(pathsinhigh.begin(), pathsinhigh.end(), diffpathupper_less());\n                }\n                cout << \"done: \" << pathsinhigh.size() << \".\" << endl;\n        } catch(exception& e) {\n                cout << \"failed.\\n(\" << e.what() << \")\" << endl;\n        } catch(...) {\n                cout << \"failed.\" << endl;\n        }\n}\n\nvoid load_lower_paths(vector<sha1differentialpath>& pathsinlow, path_container& container)\n{\n        const unsigned t = container.t;\n        const unsigned modn = container.modn;\n        const unsigned modi = container.modi;\n        const unsigned mode = container.splitmode;\n        try {\n                cout << \"Loading \" << container.inputfilelow << \"...\" << flush;\n                if (modn > 1 && mode >= 2) {\n                        vector< sha1differentialpath > pathstmp2;\n                        load_bz2(pathstmp2, binary_archive, container.inputfilelow);\n                        if (mode == 3) {\n                                random_permutation(pathstmp2, container);\n                                pathsinlow.reserve((pathstmp2.size()/modn)+1);\n                                for (unsigned j = modi; j < pathstmp2.size(); j += modn)\n                                        pathsinlow.push_back(pathstmp2[j]);\n                                sort(pathsinlow.begin(), pathsinlow.end(), diffpathlower_less());\n                        } else {\n                                sort(pathstmp2.begin(), pathstmp2.end(), diffpathlower_less());\n                                unsigned blockstart = (modi*pathstmp2.size())/modn;\n                                unsigned blockend = ((modi+1)*pathstmp2.size())/modn;\n                                pathsinlow.reserve(blockend - blockstart);\n                                for (unsigned k = blockstart; k < blockend; ++k)\n                                        pathsinlow.push_back(pathstmp2[k]);\n                        }                       \n                } else {                        \n                        load_bz2(pathsinlow, binary_archive, container.inputfilelow);\n                        sort(pathsinlow.begin(), pathsinlow.end(), diffpathlower_less());\n                }\n                cout << \"done: \" << pathsinlow.size() << \".\" << endl;\n        } catch(exception& e) {\n                cout << \"failed.\\n(\" << e.what() << \")\" << endl;\n        } catch(...) {\n                cout << \"failed.\" << endl;\n        }\n}\n\n\n\nvoid dostep(path_container& container)\n{\n        const unsigned t = container.t;\n        const unsigned modn = container.modn;\n        const unsigned modi = container.modi;\n        const unsigned mode = container.splitmode;\n        // 0 = split upperpath sorted, 1 = split upperpath random, 2 = split lowerpath sorted, 3 = split lowerpath random\n        vector< sha1differentialpath > pathsinhigh, pathsinlow, pathsout;\n        if (mode <= 1) {\n                load_upper_paths(pathsinhigh, container);\n                load_lower_paths(pathsinlow, container); \n        } else {\n                load_lower_paths(pathsinlow, container);\n                load_upper_paths(pathsinhigh, container);\n        }\n        if (container.showinputpaths) {\n                for (unsigned r = 0; r < pathsinlow.size(); ++r)\n                        show_path(pathsinlow[r]);\n                for (unsigned r = 0; r < pathsinhigh.size(); ++r)\n                        show_path(pathsinhigh[r]);\n        } else {\n                if (pathsinlow.size())\n                        show_path(pathsinlow[0]);\n                if (pathsinhigh.size())\n                        show_path(pathsinhigh[0]);\n        }\n        unsigned badcount = 0;\n        for (unsigned i = 0; i < pathsinlow.size(); ++i)\n                if (!test_path(pathsinlow[i]))\n                        ++badcount;\n        if (badcount) {\n                cout << \"Bad lowerpaths: \" << badcount << \" out of \" << pathsinlow.size() << endl;\n                for (unsigned i = 0; i < pathsinlow.size(); ++i)\n                        if (!test_path(pathsinlow[i]) || pathsinlow[i].path.size()==0) {\n                                show_path(pathsinlow[i]);\n                                break;\n                        }\n        }\n        badcount = 0;\n        for (unsigned i = 0; i < pathsinhigh.size(); ++i)\n                if (!test_path(pathsinhigh[i]))\n                        ++badcount;\n        if (badcount) {\n                cout << \"Bad upperpaths: \" << badcount << \" out of \" << pathsinhigh.size() << endl;\n                for (unsigned i = 0; i < pathsinhigh.size(); ++i)\n                        if (!test_path(pathsinhigh[i]) || pathsinhigh[i].path.size()==0) {\n                                show_path(pathsinhigh[i]);\n                                break;\n                        }\n        }\n\n\tvector< sha1differentialpath > pathsredo, pathsredohigh, pathsredolow;\n\tif (container.inputfileredo.size()) {\n\t\tcout << \"Loading redo inputs: \" << flush;\n\t\ttry {\n\t\t\tload_bz2(pathsredo, binary_archive, container.inputfileredo);\n\t\t\tcout << \"done: \" << pathsredo.size() << \".\" << endl;\n\t\t} catch (exception& e) {\n\t\t\tcout << \"failed.\\n(\" << e.what() << \")\" << endl;\n\t\t\tpathsredo.clear();\n\t\t} catch (...) {\n\t\t\tcout << \"failed.\" << endl;\n\t\t\tpathsredo.clear();\n\t\t}\n\t}\n\tif (pathsredo.size() > 0) {\n\t\tcout << \"Filtering...\" << endl;\n\t\tprogress_display pd(pathsinlow.size()+pathsinhigh.size());\n\t\tint lowtend = pathsinlow[0].tend()-1, hightbegin = pathsinhigh[0].tbegin();\n\t\tvector<uint32> redolowtend(pathsredo.size()), redohightbegin(pathsredo.size());\n\t\tif (lowtend+1 != hightbegin) {\n\t\t\tcout << \"lowtend+1 != hightend: \" << lowtend << \" \" << hightbegin << endl << endl;\n\t\t}\n\t\tfor (unsigned i = 0; i < pathsredo.size(); ++i) {\n\t\t\tredolowtend[i] = pathsredo[i][lowtend].diff();\n\t\t\tredohightbegin[i] = pathsredo[i][hightbegin].diff();\n\t\t}\n\t\tfor (unsigned k = 0; k < pathsinlow.size(); ++k,++pd) {\n\t\t\tbool redolow = false;\n\t\t\tuint32 tmp = pathsinlow[k][ pathsinlow[k].tend()-1 ].diff();\n\t\t\tfor (unsigned j = 0; j < pathsredo.size(); ++j) {\n\t\t\t\tif (pathsinlow[k].tend()-1 != lowtend)\n\t\t\t\t\tthrow std::runtime_error(\"tend()-1 != lowtend\");\n\t\t\t\tif (tmp != redolowtend[j])\n\t\t\t\t\tcontinue;\n//\t\t\t\tif (pathsredo[j].tbegin() > pathsinlow[k].tbegin() || pathsredo[j].tend() < pathsinlow[k].tend())\n//\t\t\t\t\tcontinue;\n\t\t\t\tbool ok = true;\n/*\t\t\t\tfor (int t = pathsinlow[k].tend()-2; t >= pathsinlow[k].tbegin(); --t)\n\t\t\t\t\tif (pathsinlow[k][t].diff() != pathsredo[j][t].diff()) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n*/\t\t\t\tif (ok) {\n\t\t\t\t\tredolow = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (redolow) {\n\t\t\t\tpathsredolow.push_back(pathsinlow[k]);\n\t\t\t}\n\t\t}\n\t\tfor (unsigned k = 0; k < pathsinhigh.size(); ++k,++pd) {\n\t\t\tbool redohigh = false;\n\t\t\tuint32 tmp = pathsinhigh[k][ pathsinhigh[k].tbegin() ].diff();\n\t\t\tfor (unsigned j = 0; j < pathsredo.size(); ++j) {\n\t\t\t\tif (pathsinhigh[k].tbegin() != hightbegin) \n\t\t\t\t\tthrow std::runtime_error(\"pathsinhigh[k].tbegin() != hightbegin\");\n\t\t\t\tif (tmp != redohightbegin[j])\n\t\t\t\t\tcontinue;\n//\t\t\t\tif (pathsredo[j].tbegin() > pathsinhigh[k].tbegin() || pathsredo[j].tend() < pathsinhigh[k].tend())\n//\t\t\t\t\tthrow std::runtime_error(\"blaaat\");\n//\t\t\t\t\tcontinue;\n\t\t\t\tbool ok = true;\n/*\t\t\t\tfor (int t = pathsinhigh[k].tbegin()+1; t < pathsinhigh[k].tend(); ++t)\n\t\t\t\t\tif (pathsinhigh[k][t].diff() != pathsredo[j][t].diff()) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n*/\t\t\t\tif (ok) {\n\t\t\t\t\tredohigh = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (redohigh) {\n\t\t\t\tpathsredohigh.push_back(pathsinhigh[k]);\n\t\t\t}\n\t\t}\n\t\tcout << \"# Lowerpaths to redo: \" << pathsredolow.size() << endl;\n\t\tcout << \"# Upperpaths to redo: \" << pathsredohigh.size() << endl;\n\t\tcout << \"Processing selected lowerpaths...\" << endl;\n\t\tdostep_threaded(pathsredolow, pathsinhigh, container, false);\n\t\tcontainer.save_bestpaths();\n\t\t\n\t\tcout << \"Processing selected upperpaths...\" << endl;\n\t\tdostep_threaded(pathsinlow, pathsredohigh, container, false);\n\t\tcontainer.save_bestpaths();\n\t\treturn;\n\t}\n\tif (container.loworder == 0)\n\t\tdostep_threaded(pathsinlow, pathsinhigh, container, true);\n\telse\n\t{\n\t\tif (container.loworder == 2)\n\t\t\tsort(pathsinlow.begin(), pathsinlow.end(), diffpathlower_less_weight());\n\t\tdostep_threaded(pathsinlow, pathsinhigh, container, false);\n\t}\n\tcontainer.save_bestpaths();\n}\n", "meta": {"hexsha": "31c6dc8c98e043305fd01e2690deb6f7daf98e75", "size": 16539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sha1connect/dostep.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/dostep.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/dostep.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": 39.0992907801, "max_line_length": 139, "alphanum_fraction": 0.5604329161, "num_tokens": 4514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.024798159429825065, "lm_q1q2_score": 0.011528703286093483}}
{"text": "/* main.cpp -- part of the fractal flames implementation\n *\n * Copyright (C) 2015 Alrik Firl\n *\n * This software may be modified and distributed under the terms\n * of the MIT license.  See the LICENSE file for details.\n */\n\n#include \"fflame_generator.hpp\"\n#include \"fractal_flame.hpp\"\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace bfs = boost::filesystem;\n\n//--------------------------------------------------------------------------------------------------------\n// for debugging with gdb\ndouble get_mat_pixel(cv::Mat_<cv::Vec<double, 3>> &image, int row, int col,\n                     int channel) {\n  auto px = image(row, col);\n  return px(channel);\n}\n//--------------------------------------------------------------------------------------------------------\n\n// generates num_frames frames in interpolating between the lhs and rhs frames\ntemplate <typename pixel_t>\nint interpolate_frames(const cv::Mat_<pixel_t> &lhs_img,\n                       const cv::Mat_<pixel_t> &rhs_img, const int num_frames,\n                       const bfs::path out_filebasepath, int frame_idx) {\n  auto output_fpath = out_filebasepath;\n  output_fpath /= std::to_string(frame_idx++) + \".png\";\n  const std::string out_filepath = output_fpath.native();\n\n  {\n    // NOTE: we'll 'lose' the last frame generated in this manner?\n    auto output_keyframe_fpath = out_filebasepath;\n    output_keyframe_fpath /=\n        \"baseframe_\" + std::to_string(frame_idx++) + \".png\";\n    const std::string out_keyframe_filepath = output_keyframe_fpath.native();\n    cv::imwrite(out_keyframe_filepath, lhs_img);\n  }\n\n  // std::cout << \"saving \" << out_filepath << std::endl;\n  cv::imwrite(out_filepath, lhs_img);\n\n  cv::Mat_<pixel_t> pixel_diffimg =\n      (rhs_img - lhs_img) / static_cast<double>(num_frames);\n  // note: this is just a reference to lhs_img, not a clone\n  cv::Mat_<pixel_t> working_frame = lhs_img;\n  for (int i = 0; i < num_frames; ++i) {\n    working_frame += pixel_diffimg;\n    output_fpath = out_filebasepath;\n    output_fpath /= std::to_string(frame_idx++) + \".png\";\n    const std::string out_filepath = output_fpath.native();\n    cv::imwrite(out_filepath, working_frame);\n    // std::cout << \"saving \" << out_filepath << std::endl;\n  }\n\n  // at this point, working_frame should be 1 step off from rhs_img\n  return frame_idx;\n}\n\ntemplate <typename pixel_t>\nint interpolate_frames(const FFlames::flame_frame<pixel_t> &lhs_frame,\n                       const FFlames::flame_frame<pixel_t> &rhs_frame,\n                       const int num_frames, const bfs::path out_filebasepath,\n                       int frame_idx) {\n  cv::Mat_<pixel_t> lhs_img(lhs_frame.rows, lhs_frame.cols, lhs_frame.data);\n  cv::Mat_<pixel_t> rhs_img(rhs_frame.rows, rhs_frame.cols, rhs_frame.data);\n  return interpolate_frames(lhs_img, rhs_img, num_frames, out_filebasepath,\n                            frame_idx);\n}\n\ntemplate <class framequeue_t, template <class> class frame_t, typename pixel_t>\nvoid run_frame_generation(framequeue_t &bg_framequeue,\n                          const bfs::path output_dir, const int num_images,\n                          bool do_interpolation) {\n  int output_index = 0;\n  std::unique_ptr<frame_t<pixel_t>> prev_image;\n  // frame_t<pixel_t> prev_image;\n  for (int frame_idx = 0; frame_idx < num_images; ++frame_idx) {\n\n    bool got_frame = false;\n    std::unique_ptr<frame_t<pixel_t>> fflame_frame;\n    while (!got_frame) {\n      fflame_frame = bg_framequeue.pop(got_frame);\n    }\n\n    if (got_frame && fflame_frame) {\n      // save the frames out, in whatever configuration is specified\n      if (do_interpolation) {\n        if (frame_idx > 0) {\n          output_index =\n              interpolate_frames(*(prev_image.get()), *(fflame_frame.get()), 30,\n                                 output_dir, output_index);\n        }\n        prev_image.swap(fflame_frame);\n      } else {\n        /*\n        //Q: how do we normalize? We could get the maximum R, G, and B hcannels?\n        pixel_t min_pxval;\n        pixel_t max_pxval;\n        std::for_each(fflame_frame->data, fflame_frame->data +\n        fflame_frame->rows * fflame_frame->cols,\n                    [&min_pxval, &max_pxval] (const pixel_t& pxval) {\n                        for (int k = 0; k < pixel_t::channels; k++) {\n                            if(pxval[k] > max_pxval[k]) {\n                                max_pxval[k] = pxval[k];\n                            }\n                            if(pxval[k] < min_pxval[k]) {\n                                min_pxval[k] = pxval[k];\n                            }\n                        }\n                    });\n\n        std::cout << \"Per-channel MIN: {\" << min_pxval[0] << \", \" <<\n        min_pxval[1] << \", \" << min_pxval[2] << \"}\" << std::endl; std::cout <<\n        \"Per-channel MAX: {\" << max_pxval[0] << \", \" << max_pxval[1] << \", \" <<\n        max_pxval[2] << \"}\" << std::endl; pixel_t dynamic_channel_range =\n        max_pxval - min_pxval; cv::divide(255, dynamic_channel_range,\n        dynamic_channel_range); std::for_each(fflame_frame->data,\n        fflame_frame->data + fflame_frame->rows * fflame_frame->cols,\n                [min_pxval, dynamic_channel_range](pixel_t& pxval) {\n                    pxval = (pxval - min_pxval).mul(dynamic_channel_range);\n                });\n        */\n        cv::Mat_<pixel_t> keyframe_img(fflame_frame->rows, fflame_frame->cols,\n                                       fflame_frame->data);\n\n        // NOTE: we'll 'lose' the last frame generated in this manner?\n        auto output_keyframe_fpath = output_dir;\n        output_keyframe_fpath /= \"baseframe_\" + std::to_string(frame_idx);\n        const std::string out_keyframe_filepath =\n            output_keyframe_fpath.native();\n\n        // write out the yml file...\n        cv::FileStorage keyframe_ymlfile(out_keyframe_filepath + \".yml\",\n                                         cv::FileStorage::WRITE);\n        keyframe_ymlfile << \"baseframe_\" + std::to_string(frame_idx)\n                         << keyframe_img;\n\n        cv::Mat logged_image;\n        keyframe_img.convertTo(logged_image, CV_8UC3);\n        //... and the image file\n        cv::imwrite(out_keyframe_filepath + \".png\", logged_image);\n      }\n    }\n  }\n}\n\ntemplate <template <class> class frame_t, typename pixel_t, typename data_t>\nvoid generate_fractal_flames(const bfs::path output_dir,\n                             const int render_height, const int render_width,\n                             const int num_working_variants,\n                             const int num_images,\n                             const bool do_interpolation = true) {\n  using flame_gen_t = FFlames::fflame_generator<frame_t, data_t, pixel_t>;\n  const int num_generator_threads = 4;\n  auto bg_generator = std::unique_ptr<flame_gen_t>(\n      new flame_gen_t(render_height, render_width, num_working_variants,\n                      num_generator_threads));\n\n  // pass in a queue to hold the finished flame frames\n  // auto bg_framequeue = std::unique_ptr<EventQueue<frame_t<pixel_t>>>(new\n  // EventQueue<frame_t<pixel_t>>(num_images));\n  using bg_queue_t =\n      typename flame_gen_t::template ts_queue_t<frame_t<pixel_t>>;\n  bg_queue_t bg_framequeue;\n  auto bg_framequeue_p = &bg_framequeue;\n  bg_generator->register_framequeue(bg_framequeue_p);\n\n  bg_generator->start_generation();\n  run_frame_generation<bg_queue_t, frame_t, pixel_t>(\n      bg_framequeue, output_dir, num_images, do_interpolation);\n  bg_generator->stop_generation();\n}\n\ntemplate <template <class> class frame_t, typename pixel_t, typename data_t>\nvoid generate_fractal_flames(const bfs::path output_dir,\n                             const int render_height, const int render_width,\n                             std::vector<std::string> &&manual_variants,\n                             const int num_images,\n                             const bool do_interpolation = true) {\n  using flame_gen_t = FFlames::fflame_generator<frame_t, data_t, pixel_t>;\n  const int num_generator_threads = 4;\n  auto bg_generator = std::unique_ptr<flame_gen_t>(\n      new flame_gen_t(render_height, render_width, std::move(manual_variants),\n                      num_generator_threads));\n\n  // pass in a queue to hold the finished flame frames\n  // auto bg_framequeue = std::unique_ptr<EventQueue<frame_t<pixel_t>>>(new\n  // EventQueue<frame_t<pixel_t>>(num_images));\n  using bg_queue_t =\n      typename flame_gen_t::template ts_queue_t<frame_t<pixel_t>>;\n  bg_queue_t bg_framequeue;\n  auto bg_framequeue_p = &bg_framequeue;\n  bg_generator->register_framequeue(bg_framequeue_p);\n\n  bg_generator->start_generation();\n  run_frame_generation<bg_queue_t, frame_t, pixel_t>(\n      bg_framequeue, output_dir, num_images, do_interpolation);\n  bg_generator->stop_generation();\n}\n\n//------------------------------------------------------------------------------------------------------\ntemplate <typename pixel_t>\nusing frame_t = FFlames::flame_frame<pixel_t>; // cv::Mat_<pixel_t>;\n\nint main(int argc, char *argv[]) {\n  std::vector<std::string> manual_variant_list;\n\n  namespace bpo = boost::program_options;\n  bpo::options_description bpo_desc(\"fractal flames options\");\n  bpo_desc.add_options()(\"help,h\", \"Print help message\")(\n      \"output-path,o\", bpo::value<std::string>(), \"output flame-image path\")(\n      \"num-variants,n\", bpo::value<int>(),\n      \"number of working variants\")(\"total-frames,t\", bpo::value<int>(),\n                                    \"total number of keyframes to generate\")(\n      \"variant-list,v\",\n      bpo::value<std::vector<std::string>>(&manual_variant_list)->multitoken(),\n      \"list of variants to use\")(\"do-interpolation,i\", bpo::value<int>(),\n                                 \"flag for writing out interpolated frames \"\n                                 \"between keyframes (1: yes, 0: no)\");\n\n  bpo::variables_map vm;\n  bpo::store(bpo::command_line_parser(argc, argv).options(bpo_desc).run(), vm);\n  bpo::notify(vm);\n\n  std::string output_path;\n  int num_working_variants, num_images, do_interpolation;\n\n  if (vm.count(\"help\")) {\n    std::cout << bpo_desc << std::endl;\n    return 0;\n  }\n\n  if (vm.count(\"output-path\")) {\n    output_path = vm[\"output-path\"].as<std::string>();\n  } else {\n    std::cout << bpo_desc << std::endl;\n    return 0;\n  }\n\n  if (vm.count(\"num-variants\")) {\n    num_working_variants = vm[\"num-variants\"].as<int>();\n  } else {\n    std::cout << bpo_desc << std::endl;\n    return 0;\n  }\n\n  if (vm.count(\"total-frames\")) {\n    num_images = vm[\"total-frames\"].as<int>();\n  } else {\n    std::cout << bpo_desc << std::endl;\n    return 0;\n  }\n\n  if (vm.count(\"do-interpolation\")) {\n    do_interpolation = vm[\"do-interpolation\"].as<int>();\n  } else {\n    std::cout << bpo_desc << std::endl;\n    return 0;\n  }\n\n  using data_t = double;\n  using pixel_t = cv::Vec<data_t, 3>;\n  const int render_height = 1024;\n  const int render_width = 1024;\n\n  const bool use_manual_variants = manual_variant_list.size() > 0;\n  if (use_manual_variants) {\n    // invoke via something like\n    //./fflame_gen -o ff_frames/ff_v13 -n 10 -t 100 -i 0 -v fisheye -v eyefish\n    //-v swirl -v this -v is -v a -v drill\n    //\n    //... where the -v are the manually provided variants, given in sequential\n    //order next we just have to figure out how to pass these in...\n    std::cout << \"Given Variant (\" << manual_variant_list.size()\n              << \") List: \" << std::endl;\n    num_working_variants = manual_variant_list.size();\n    for (auto variant_id : manual_variant_list) {\n      // search the list of variant names to make sure the provided ones are\n      // valid\n      std::string manual_var = variant_id;\n      std::transform(manual_var.begin(), manual_var.end(), manual_var.begin(),\n                     [](unsigned char c) { return std::tolower(c); });\n      auto var_it = std::find(\n          FFlames::affine_fcns::variant_list<data_t>::variant_names.begin(),\n          FFlames::affine_fcns::variant_list<data_t>::variant_names.end(), manual_var);\n      if (var_it != FFlames::affine_fcns::variant_list<data_t>::variant_names.end()) {\n        std::cout << variant_id << std::endl;\n      } else {\n        std::cout << \"ERROR -- variant \" << manual_var\n                  << \" is not valid. Valid variants list: \" << std::endl;\n        for (auto var_name : FFlames::affine_fcns::variant_list<data_t>::variant_names) {\n          std::cout << var_name << std::endl;\n        }\n        return 0;\n      }\n    }\n  }\n\n  // check the output directory path (if it doesn't exist, create it)\n  bfs::path output_dir(output_path);\n  if (!(bfs::exists(output_dir) && bfs::is_directory(output_dir))) {\n    if (!boost::filesystem::create_directory(output_path)) {\n      std::cout << \"Invalid output file directory -- \" << output_path\n                << std::endl;\n      throw std::invalid_argument(\"Invalid output file directory \" +\n                                  output_path);\n    }\n  }\n\n  bool do_interpolation_flag = do_interpolation != 0;\n  if (use_manual_variants) {\n    generate_fractal_flames<frame_t, pixel_t, data_t>(\n        output_dir, render_height, render_width, std::move(manual_variant_list),\n        num_images, do_interpolation_flag);\n  } else {\n    generate_fractal_flames<frame_t, pixel_t, data_t>(\n        output_dir, render_height, render_width, num_working_variants,\n        num_images, do_interpolation_flag);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "6b752fc575ecd21f55ab778b1026d07ce7f23ad7", "size": 13491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "alrikai/fflames", "max_stars_repo_head_hexsha": "cf07d993f18c93fb528892b2396eb6d1c03d7de5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T18:37:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-12T18:37:27.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "alrikai/fflames", "max_issues_repo_head_hexsha": "cf07d993f18c93fb528892b2396eb6d1c03d7de5", "max_issues_repo_licenses": ["MIT"], "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": "alrikai/fflames", "max_forks_repo_head_hexsha": "cf07d993f18c93fb528892b2396eb6d1c03d7de5", "max_forks_repo_licenses": ["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.3922155689, "max_line_length": 106, "alphanum_fraction": 0.613594248, "num_tokens": 3278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.03789242921002377, "lm_q1q2_score": 0.011520877645566955}}
{"text": "/*\n==============================================================================\nKratosStructuralApplication\nA library based on:\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, Janosch Stascheit, Felix Nagel\npooyan@cimne.upc.edu\nrrossi@cimne.upc.edu\njanosch.stascheit@rub.de\nnagel@sd.rub.de\n- CIMNE (International Center for Numerical Methods in Engineering),\nGran Capita' s/n, 08034 Barcelona, Spain\n- Ruhr-University Bochum, Institute for Structural Mechanics, Germany\n\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 OWNERS.\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: anonymous $\n//   Date:                $Date: 2008-10-23 14:27:01 $\n//   Revision:            $Revision: 1.20 $\n//\n//\n\n\n#if !defined(KRATOS_ADD_CUSTOM_UTILITIES_TO_PYTHON_H_INCLUDED )\n#define  KRATOS_ADD_CUSTOM_UTILITIES_TO_PYTHON_H_INCLUDED\n\n\n// System includes\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n// External includes\n#include \"boost/smart_ptr.hpp\"\n\n\n// Project includes\n#include \"custom_python/add_custom_utilities_to_python.h\"\n#include \"includes/define.h\"\n#include \"custom_utilities/deactivation_utility.h\"\n#include \"custom_utilities/variable_transfer_utility.h\"\n\n#ifdef _OPENMP\n#include \"custom_utilities/parallel_variable_transfer_utility.h\"\n#endif\n\n#include \"spaces/ublas_space.h\"\n#include \"linear_solvers/linear_solver.h\"\n#include \"custom_utilities/contact_utility.h\"\n#include \"custom_utilities/volume_utility.h\"\n#include \"custom_utilities/restart_utility.h\"\n#include \"custom_utilities/node_snapping_utility.h\"\n#include \"custom_elements/rigid_body_3D.h\"\n#include \"custom_utilities/output_utility.h\"\n#include \"custom_utilities/dof_utility.h\"\n#include \"custom_utilities/smoothing_utility.h\"\n\n//#include \"custom_utilities/detect_elements_utility.h\"\n#include \"custom_utilities/intra_fracture_triangle_utility.h\"\n#include \"custom_utilities/inter_fracture_triangle_utility.h\"\n#include \"custom_utilities/inter_fracture_tetrahedra_utility.h\"\n//#include \"custom_utilities/mark_element_for_refinement.h\"\n#include \"custom_utilities/disconnect_utility.h\"\n\nnamespace Kratos\n{\n\nnamespace Python\n{\n\nusing namespace boost::python;\n\nvoid AddNewRigidBody3D( ModelPart& structural_model_part,\n                        ModelPart& skin_model_part,\n                        Variable<double>& rSelectionVariable,\n                        double selection_value,\n                        Node<3>::Pointer CenterNode,\n                        Element::PropertiesType::Pointer pProperties,\n                        double nodal_mass,\n                        Matrix& Inertia\n                      )\n{\n    Geometry<Node<3> >::Pointer skin_nodes_geometry( new Geometry<Node<3> > ); ;\n\n    //selecting the nodes in the model part having rSelectionVariable==selection_value\n\n    for ( ModelPart::NodesContainerType::iterator it = skin_model_part.NodesBegin(); it != skin_model_part.NodesEnd(); it++ )\n    {\n        if ( it->FastGetSolutionStepValue( rSelectionVariable ) == selection_value )\n            skin_nodes_geometry->push_back( *( it.base() ) );\n    }\n\n    //creating a geometry containing the center node\n    Geometry<Node<3> >::Pointer center_node_geometry( new Geometry<Node<3> > ) ;\n\n    center_node_geometry->push_back( Node<3>::Pointer( CenterNode ) );\n\n    unsigned int last_id = 1;\n\n    if ( structural_model_part.Elements().size() != 0 )\n        last_id = ( structural_model_part.ElementsEnd() - 1 )->Id() + 1;\n\n    array_1d<double, 3> zero = ZeroVector( 3 );\n\n    Element::Pointer new_el = RigidBody3D::Pointer( new  RigidBody3D( last_id,\n                              center_node_geometry,\n                              pProperties,\n                              skin_nodes_geometry,\n                              nodal_mass,\n                              Inertia, zero, zero ) );\n\n    structural_model_part.Elements().push_back(\n        new_el\n    );\n}\n\nvoid AddNewRigidBodyAndSpring3D( ModelPart& structural_model_part,\n                                 ModelPart& skin_model_part,\n                                 Variable<double>& rSelectionVariable,\n                                 double selection_value,\n                                 Node<3>::Pointer CenterNode,\n                                 Element::PropertiesType::Pointer pProperties,\n                                 double nodal_mass,\n                                 Matrix& Inertia,\n                                 array_1d<double, 3>& translational_stiffness,\n                                 array_1d<double, 3>& rotational_stiffness\n                               )\n{\n    Geometry<Node<3> >::Pointer skin_nodes_geometry( new Geometry<Node<3> > ); ;\n\n    //selecting the nodes in the model part having rSelectionVariable==selection_value\n\n    for ( ModelPart::NodesContainerType::iterator it = skin_model_part.NodesBegin(); it != skin_model_part.NodesEnd(); it++ )\n    {\n        if ( it->FastGetSolutionStepValue( rSelectionVariable ) == selection_value )\n            skin_nodes_geometry->push_back( *( it.base() ) );\n    }\n\n    //creating a geometry containing the center node\n    Geometry<Node<3> >::Pointer center_node_geometry( new Geometry<Node<3> > ) ;\n\n    center_node_geometry->push_back( Node<3>::Pointer( CenterNode ) );\n\n    unsigned int last_id = 1;\n\n    if ( structural_model_part.Elements().size() != 0 )\n        last_id = ( structural_model_part.ElementsEnd() - 1 )->Id() + 1;\n\n    array_1d<double, 3> zero = ZeroVector( 3 );\n\n    Element::Pointer new_el = RigidBody3D::Pointer( new  RigidBody3D( last_id,\n                              center_node_geometry,\n                              pProperties,\n                              skin_nodes_geometry,\n                              nodal_mass,\n                              Inertia,\n                              translational_stiffness,\n                              rotational_stiffness ) );\n\n    structural_model_part.Elements().push_back(\n        new_el\n    );\n}\n\nvoid DoubleTransferVariablesToNodes(VariableTransferUtility& dummy,\n        ModelPart& model_part, Variable<double>& rThisVariable)\n{\n    dummy.TransferVariablesToNodes(model_part, rThisVariable);\n}\n\nvoid VectorTransferVariablesToNodes(VariableTransferUtility& dummy,\n        ModelPart& model_part, Variable<Vector>& rThisVariable)\n{\n    dummy.TransferVariablesToNodes(model_part, rThisVariable);\n}\n\nvoid DoubleTransferVariablesToGaussPoints(VariableTransferUtility& dummy,\n        ModelPart& source_model_part, ModelPart& target_model_part, Variable<double>& rThisVariable)\n{\n    dummy.TransferVariablesToGaussPoints(source_model_part, target_model_part, rThisVariable);\n}\n\nvoid VectorTransferVariablesToGaussPoints(VariableTransferUtility& dummy,\n        ModelPart& source_model_part, ModelPart& target_model_part, Variable<Vector>& rThisVariable)\n{\n    dummy.TransferVariablesToGaussPoints(source_model_part, target_model_part, rThisVariable);\n}\n\nvoid  AddCustomUtilitiesToPython()\n{\n    class_<DeactivationUtility, boost::noncopyable >\n    ( \"DeactivationUtility\", init<>() )\n    .def( init<int>() )\n    .def( \"Deactivate\", &DeactivationUtility::Deactivate )\n    .def( \"Reactivate\", &DeactivationUtility::Reactivate )\n    .def( \"ReactivateStressFree\", &DeactivationUtility::ReactivateStressFree )\n    .def( \"ReactivateAll\", &DeactivationUtility::ReactivateAll )\n    .def( \"Initialize\", &DeactivationUtility::Initialize )\n    .def( \"GetName\", &DeactivationUtility::GetName<Element> )\n    .def( \"GetName\", &DeactivationUtility::GetName<Condition> )\n    ;\n\n    class_<VariableTransferUtility, boost::noncopyable >\n    ( \"VariableTransferUtility\", init<>() )\n    .def(init<VariableTransferUtility::LinearSolverType::Pointer>())\n    .def( \"TransferNodalVariables\", &VariableTransferUtility::TransferNodalVariables )\n    .def( \"TransferConstitutiveLawVariables\", &VariableTransferUtility::TransferConstitutiveLawVariables )\n    .def( \"TransferInSituStress\", &VariableTransferUtility::TransferInSituStress )\n    .def( \"TransferPrestress\", &VariableTransferUtility::TransferPrestress )\n    .def( \"TransferPrestressIdentically\", &VariableTransferUtility::TransferPrestressIdentically )\n    .def( \"TransferSpecificVariable\", &VariableTransferUtility::TransferSpecificVariable )\n    .def( \"InitializeModelPart\", &VariableTransferUtility::InitializeModelPart )\n    .def(\"TransferVariablesToNodes\", &DoubleTransferVariablesToNodes)\n    .def(\"TransferVariablesToNodes\", &VectorTransferVariablesToNodes)\n    .def(\"TransferVariablesToGaussPoints\", &DoubleTransferVariablesToGaussPoints)\n    .def(\"TransferVariablesToGaussPoints\", &VectorTransferVariablesToGaussPoints)\n    ;\n\n\n#ifdef _OPENMP\n    class_<ParallelVariableTransferUtility, boost::noncopyable >\n    ( \"ParallelVariableTransferUtility\",\n      init<>() )\n    .def( \"TransferNodalVariables\", &ParallelVariableTransferUtility::TransferNodalVariables )\n    .def( \"TransferConstitutiveLawVariables\", &ParallelVariableTransferUtility::TransferConstitutiveLawVariables )\n    .def( \"TransferInSituStress\", &ParallelVariableTransferUtility::TransferInSituStress )\n    .def( \"InitializeModelPart\", &ParallelVariableTransferUtility::InitializeModelPart )\n    ;\n#endif\n\n    class_<ContactUtility, boost::noncopyable >\n    ( \"ContactUtility\",\n      init<int>() )\n    .def( \"SetUpContactConditions\", &ContactUtility::SetUpContactConditions )\n    .def( \"SetUpContactConditionsLagrangeTying\", &ContactUtility::SetUpContactConditionsLagrangeTying )\n    .def( \"Update\", &ContactUtility::Update )\n    .def( \"IsConverged\", &ContactUtility::IsConverged )\n    .def( \"Clean\", &ContactUtility::Clean )\n    .def( \"CleanLagrangeTying\", &ContactUtility::CleanLagrangeTying )\n    ;\n// VM\n    class_<VolumeUtility, boost::noncopyable >\n    ( \"VolumeUtility\",\n      init<int>() )\n    .def( \"Calculate_this_Volume\", &VolumeUtility::CalculateVolume ) // VM\n    ;\n//VM\n\n    class_<RestartUtility, boost::noncopyable >\n    ( \"RestartUtility\",\n      init< std::string const& >() )\n    .def( \"ChangeFileName\", &RestartUtility::ChangeFileName )\n    .def( \"StoreNodalVariables\", &RestartUtility::StoreNodalVariables )\n    .def( \"WriteNodalVariables\", &RestartUtility::WriteNodalVariables )\n    .def( \"StoreInSituStress\", &RestartUtility::StoreInSituStress )\n    .def( \"WriteConstitutiveLawVariables\", &RestartUtility::WriteConstitutiveLawVariables )\n    .def( \"StoreConstitutiveLawVariables\", &RestartUtility::StoreConstitutiveLawVariables )\n    .def( \"WriteInSituStress\", &RestartUtility::WriteInSituStress )\n    ;\n\n    class_<NodeSnappingUtility, boost::noncopyable >\n    ( \"NodeSnappingUtility\",\n      init<>() )\n    .def( \"MoveNode\", &NodeSnappingUtility::MoveNode )\n    .def( \"AdjustNodes\", &NodeSnappingUtility::AdjustNodes )\n    .def( \"AdjustToCircle\", &NodeSnappingUtility::AdjustToCircle )\n    .def( \"AdjustToCylinder\", &NodeSnappingUtility::AdjustToCylinder )\n    .def( \"AdjustToClosedCylinder\", &NodeSnappingUtility::AdjustToClosedCylinder )\n    .def( \"IdentifyInsideElements\", &NodeSnappingUtility::IdentifyInsideElements )\n    .def( \"SetInsituStress\", &NodeSnappingUtility::SetInsituStress )\n    .def( \"ExtractCapNodes\", &NodeSnappingUtility::ExtractCapNodes )\n    .def( \"TestElements\", &NodeSnappingUtility::TestElements )\n    ;\n\n    class_<OutputUtility, boost::noncopyable >\n    ( \"OutputUtility\",\n      init<>() )\n    .def( \"GetStrain\", &OutputUtility::GetStrain )\n    .def( \"GetStress\", &OutputUtility::GetStress )\n    .def( \"GetInternalVariables\", &OutputUtility::GetInternalVariables )\n    ;\n\n\n    def( \"AddNewRigidBody3D\", AddNewRigidBody3D );\n    def( \"AddNewRigidBodyAndSpring3D\", AddNewRigidBodyAndSpring3D );\n    ;\n\n    /*\n                class_<Detect_Elements_And_Nodes, boost::noncopyable >\n                        (\"DetectElementsAndNodes\", init<ModelPart&, int >() )\n          .def(\"DetectNode\",              &Detect_Elements_And_Nodes::Detect_Node_To_Be_Splitted)\n                        .def(\"DetectElements\",          &Detect_Elements_And_Nodes::Detect_Elements_To_Be_Splitted)\n                        .def(\"CalculateMapFailure\",     &Detect_Elements_And_Nodes::Calculate_Map_Failure)\n                        .def(\"Finalize\",                &Detect_Elements_And_Nodes::Finalize)\n                        ;\n    */\n    class_<Smoothing_Utility, boost::noncopyable >\n    ( \"SmoothingUtility\", init<ModelPart&, int >() )\n    .def( \"WeightedRecoveryGradients\", &Smoothing_Utility::WeightedRecoveryGradients<double> )\n    .def( \"WeightedRecoveryGradients\", &Smoothing_Utility::WeightedRecoveryGradients<Matrix> ) // for matrices\n    .def( \"InterpolatedRecoveryGradients\", &Smoothing_Utility::InterpolatedRecoveryGradients<Matrix> )\n    .def( \"SettingNodalValues\", &Smoothing_Utility::SettingNodalValues )\n    .def( \"RecomputeValuesForNewMesh\", &Smoothing_Utility::Recompute_Values_For_New_Mesh )\n    .def( \"Finalize\", &Smoothing_Utility::Finalize )\n    .def( \"SettingNodalValues\", &Smoothing_Utility::SettingNodalValues )\n    ;\n\n\n\n\n    class_<Disconnect_Triangle_Utilities, boost::noncopyable >\n    ( \"DisconnectTriangle\", init<ModelPart&>() )\n    .def( \"DisconnectElements\", &Disconnect_Triangle_Utilities::Disconnect_Elements )\n    ;\n\n\n    class_<Intra_Fracture_Triangle, boost::noncopyable >\n    ( \"IntraFractureTriangle\", init<ModelPart&, int >() )\n    .def( \"DetectAndSplitElements\",              &Intra_Fracture_Triangle::Detect_And_Split_Elements )\n    ;\n\n    class_<Inter_Fracture_Triangle, boost::noncopyable >\n    ( \"InterFractureTriangle\", init<ModelPart&, int >() )\n    .def( \"DetectAndSplitElementsHeuristicFormula\", &Inter_Fracture_Triangle::Detect_And_Split_Elements_Heuristic_Formula )\n    .def( \"DetectAndSplitElements\",              &Inter_Fracture_Triangle::Detect_And_Split_Elements )\n    .def( \"Finalize\",                            &Inter_Fracture_Triangle::Finalize )\n    ;\n\n    class_<Inter_Fracture_Tetrahedra, boost::noncopyable >\n    ( \"InterFractureTetrahedra\", init<ModelPart&, int >() )\n    .def( \"DetectAndSplitElements\",              &Inter_Fracture_Tetrahedra::Detect_And_Split_Elements )\n    ;\n\n    class_<DofUtility, boost::noncopyable >\n    ( \"DofUtility\", init<>() )\n    .def( \"ListDofs\", &DofUtility::ListDofs )\n    ;\n}\n}  // namespace Python.\n}  // namespace Kratos.\n\n#endif // KRATOS_ADD_CUSTOM_UTILITIES_TO_PYTHON_H_INCLUDED  defined \n", "meta": {"hexsha": "c10aed5578d72accac67c44f6762a92e9bac30f5", "size": 15609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/structural_application/custom_python/add_custom_utilities_to_python.cpp", "max_stars_repo_name": "AndreaVoltan/MyKratos7.0", "max_stars_repo_head_hexsha": "e977752722e8ef1b606f25618c4bf8fd04c434cc", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-30T19:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T19:40:47.000Z", "max_issues_repo_path": "applications/structural_application/custom_python/add_custom_utilities_to_python.cpp", "max_issues_repo_name": "AndreaVoltan/MyKratos7.0", "max_issues_repo_head_hexsha": "e977752722e8ef1b606f25618c4bf8fd04c434cc", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-30T19:19:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-02T14:22:36.000Z", "max_forks_repo_path": "applications/structural_application/custom_python/add_custom_utilities_to_python.cpp", "max_forks_repo_name": "AndreaVoltan/MyKratos7.0", "max_forks_repo_head_hexsha": "e977752722e8ef1b606f25618c4bf8fd04c434cc", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-12T08:51:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T08:51:24.000Z", "avg_line_length": 41.9596774194, "max_line_length": 125, "alphanum_fraction": 0.6924210391, "num_tokens": 3728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.03789242608636186, "lm_q1q2_score": 0.011520876695843556}}
{"text": "/* Copyright (c) AIRBUS and its affiliates.\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 * This is the scikit-decide implementation of MCTS and UCT from\n * \"A Survey of Monte Carlo Tree Search Methods\" by Browne et al\n * (IEEE Transactions on Computational Intelligence  and AI in games,\n * 2012). We additionnally implement a heuristic value estimate as in\n * \"Monte-Carlo tree search and rapid action value estimation in \n * computer Go\" by Gelly and Silver (Artificial Intelligence, 2011)\n * except that the heuristic estimate is called on states but not\n * on state-action pairs to be more in line with heuristic search\n * algorithms in the literature and other implementations of\n * heuristic search algorithms in scikit-decide.\n */\n#ifndef SKDECIDE_MCTS_HH\n#define SKDECIDE_MCTS_HH\n\n#include <functional>\n#include <memory>\n#include <unordered_set>\n#include <unordered_map>\n#include <vector>\n#include <queue>\n#include <list>\n#include <chrono>\n#include <random>\n\n#include <boost/range/irange.hpp>\n\n#include \"spdlog/spdlog.h\"\n#include \"spdlog/sinks/stdout_color_sinks.h\"\n\n#include \"utils/associative_container_deducer.hh\"\n#include \"utils/string_converter.hh\"\n#include \"utils/execution.hh\"\n\nnamespace skdecide {\n\n/** Use Environment domain knowledge for transitions */\ntemplate <typename Tsolver>\nstruct StepTransitionMode {\n    void init_rollout(Tsolver& solver, const std::size_t* thread_id) const {\n        solver.domain().reset(thread_id);\n        std::for_each(solver.action_prefix().begin(), solver.action_prefix().end(),\n                      [&solver, &thread_id](const typename Tsolver::Domain::Event& a){solver.domain().step(a, thread_id);});\n    }\n\n    typename Tsolver::Domain::TransitionOutcome random_next_outcome(\n            Tsolver& solver,\n            const std::size_t* thread_id,\n            const typename Tsolver::Domain::State& state,\n            const typename Tsolver::Domain::Event& action) const {\n        return solver.domain().step(action, thread_id);\n    }\n\n    typename Tsolver::StateNode* random_next_node(\n            Tsolver& solver,\n            const std::size_t* thread_id,\n            typename Tsolver::ActionNode& action) const {\n        auto outcome = solver.domain().step(action.action, thread_id);\n        typename Tsolver::StateNode* n = nullptr;\n\n        solver.execution_policy().protect([&n, &solver, &outcome](){\n            auto si = solver.graph().find(typename Tsolver::StateNode(outcome.state()));\n            if (si != solver.graph().end()) {\n                // we won't change the real key (ActionNode::action) so we are safe\n                n = &const_cast<typename Tsolver::StateNode&>(*si);\n            }\n        });\n\n        return n;\n    }\n};\n\n\n/** Use Simulation domain knowledge for transitions */\ntemplate <typename Tsolver>\nstruct SampleTransitionMode {\n    void init_rollout(Tsolver& solver, const std::size_t* thread_id) const {}\n\n    typename Tsolver::Domain::TransitionOutcome random_next_outcome(\n            Tsolver& solver,\n            const std::size_t* thread_id,\n            const typename Tsolver::Domain::State& state,\n            const typename Tsolver::Domain::Event& action) const {\n        return solver.domain().sample(state, action, thread_id);\n    }\n\n    typename Tsolver::StateNode* random_next_node(\n            Tsolver& solver,\n            const std::size_t* thread_id,\n            typename Tsolver::ActionNode& action) const {\n        typename Tsolver::StateNode* n = nullptr;\n\n        solver.execution_policy().protect([&n, &action, &solver](){\n            solver.execution_policy().protect([&n, &action, &solver](){\n                n = action.dist_to_outcome[action.dist(solver.gen())]->first;\n            }, solver.gen_mutex());\n        }, action.parent->mutex);\n\n        return n;\n    }\n};\n\n\n/** Use uncertain transitions domain knowledge for transitions */\ntemplate <typename Tsolver>\nstruct DistributionTransitionMode {\n    void init_rollout(Tsolver& solver, const std::size_t* thread_id) const {}\n\n    typename Tsolver::Domain::TransitionOutcome random_next_outcome(\n            Tsolver& solver,\n            const std::size_t* thread_id,\n            const typename Tsolver::Domain::State& state,\n            const typename Tsolver::Domain::Event& action) const {\n        return solver.domain().sample(state, action, thread_id);\n    }\n\n    typename Tsolver::StateNode* random_next_node(\n            Tsolver& solver,\n            const std::size_t* thread_id,\n            typename Tsolver::ActionNode& action) const {\n        typename Tsolver::StateNode* n = nullptr;\n\n        solver.execution_policy().protect([&n, &action, &solver](){\n            solver.execution_policy().protect([&n, &action, &solver](){\n                n = action.dist_to_outcome[action.dist(solver.gen())]->first;\n            }, solver.gen_mutex());\n        }, action.parent->mutex);\n\n        return n;\n    }\n};\n\n\n/** Default tree policy as used in UCT */\ntemplate <typename Tsolver>\nclass DefaultTreePolicy {\npublic :\n    typename Tsolver::StateNode* operator()(Tsolver& solver,\n                                            const std::size_t* thread_id, // for parallelisation\n                                            const typename Tsolver::Expander& expander,\n                                            const typename Tsolver::ActionSelectorOptimization& action_selector,\n                                            typename Tsolver::StateNode& n,\n                                            std::size_t& d) const {\n        try {\n            if (solver.debug_logs()) {\n                solver.execution_policy().protect([&n](){\n                    spdlog::debug(\"Launching default tree policy from state \" + n.state.print() +\n                                  Tsolver::ExecutionPolicy::print_thread());\n                }, n.mutex);\n            }\n\n            solver.transition_mode().init_rollout(solver, thread_id);\n            typename Tsolver::StateNode* current_node = &n;\n\n            while(!(current_node->terminal) && d < solver.max_depth()) {\n                typename Tsolver::StateNode* next_node = expander(solver, thread_id, *current_node);\n                d++;\n\n                if (next_node == nullptr) { // node fully expanded\n                    typename Tsolver::ActionNode* action = action_selector(solver, thread_id, *current_node);\n                    \n                    if (action == nullptr) {\n                        // It might happen in parallel execution mode when the current node's actions are all being\n                        // expanded by concurrent threads that claim the node is expanded but not yet backpropagated\n                        // and a new thread meantime comes and sees the node as expanded, thus all action visits counts\n                        // are still equal to zero (implying action_selector to return nullptr).\n                        // This shall NOT happen in sequential execution mode.\n                        break;\n                    } else {\n                        next_node = solver.transition_mode().random_next_node(solver, thread_id, *action);\n\n                        if (next_node == nullptr) { // might happen with step transition mode and stochastic environments\n                            break;\n                        } else {\n                            current_node = next_node;\n                        }\n                    }\n                } else {\n                    current_node = next_node;\n                    break;\n                }\n            }\n\n            return current_node;\n        } catch (const std::exception& e) {\n            solver.execution_policy().protect([&n, &e](){\n                spdlog::error(\"SKDECIDE exception in MCTS when simulating the tree policy from state \" + n.state.print() + \": \" + e.what() +\n                              Tsolver::ExecutionPolicy::print_thread());\n            }, n.mutex);\n            throw;\n        }\n    }\n};\n\n\n/** Test if a given node needs to be expanded by assuming that applicable actions and next states\n *  can be enumerated. Returns nullptr if all actions and outcomes have already been tried, otherwise a\n *  sampled unvisited outcome according to its probability (among only unvisited outcomes).\n *  REQUIREMENTS: returns nullptr if all actions have been already tried, and set the terminal\n *  flag of the returned next state\n */\ntemplate <typename Tsolver>\nclass FullExpand {\npublic :\n    typedef std::function<std::pair<double, std::size_t>\n                          (typename Tsolver::Domain&, const typename Tsolver::Domain::State&, const std::size_t*)> HeuristicFunctor;\n\n    FullExpand(const HeuristicFunctor& heuristic = [](typename Tsolver::Domain& domain,\n                                                      const typename Tsolver::Domain::State& state,\n                                                      const std::size_t* thread_id) {\n        return std::make_pair(0.0, 0);\n    })\n    : _heuristic(heuristic), _checked_transition_mode(false) {}\n\n    FullExpand(const FullExpand& other)\n    : _heuristic(other._heuristic), _checked_transition_mode(false) {}\n\n    typename Tsolver::StateNode* operator()(Tsolver& solver,\n                                            const std::size_t* thread_id,\n                                            typename Tsolver::StateNode& n) const {\n        try {\n            if (solver.debug_logs()) {\n                solver.execution_policy().protect([&n](){\n                    spdlog::debug(\"Testing expansion of state \" + n.state.print() +\n                                  Tsolver::ExecutionPolicy::print_thread());\n                }, n.mutex);\n            }\n\n            if (n.expanded) {\n                if (solver.debug_logs()) { spdlog::debug(\"State already fully expanded\" +\n                                                         Tsolver::ExecutionPolicy::print_thread()); }\n                return nullptr;\n            }\n\n            // Generate applicable actions if not already done\n            solver.execution_policy().protect([&n, &solver, &thread_id](){\n                if (n.actions.empty()) {\n                    if (solver.debug_logs()) { spdlog::debug(\"State never expanded, generating all next actions\" +\n                                                             Tsolver::ExecutionPolicy::print_thread()); }\n                    auto applicable_actions = solver.domain().get_applicable_actions(n.state, thread_id).get_elements();\n\n                    for (const auto& a : applicable_actions) {\n                        auto i = n.actions.emplace(typename Tsolver::ActionNode(a));\n\n                        if (i.second) {\n                            // we won't change the real key (ActionNode::action) so we are safe\n                            const_cast<typename Tsolver::ActionNode&>(*i.first).parent = &n;\n                        }\n                    }\n                }\n            }, n.mutex);\n\n            // Check for untried outcomes\n            if (solver.debug_logs()) { spdlog::debug(\"Checking for untried outcomes\" +\n                                                     Tsolver::ExecutionPolicy::print_thread()); }\n            std::vector<std::pair<typename Tsolver::ActionNode*, typename Tsolver::StateNode*>> untried_outcomes;\n            std::vector<double> weights;\n\n            solver.execution_policy().protect([&n, &untried_outcomes, &weights](){\n                for (auto& a : n.actions) {\n                    // we won't change the real key (ActionNode::action) so we are safe\n                    typename Tsolver::ActionNode& ca = const_cast<typename Tsolver::ActionNode&>(a);\n\n                    if (a.outcomes.empty()) {\n                        // we won't change the real key (ActionNode::action) so we are safe\n                        untried_outcomes.push_back(std::make_pair(&ca, nullptr));\n                        weights.push_back(1.0);\n                    } else {\n                        // Check if there are next states that have been never visited\n                        std::vector<double> probs = a.dist.probabilities();\n\n                        for (std::size_t p = 0 ; p < probs.size() ; p++) {\n                            typename Tsolver::StateNode* on = ca.dist_to_outcome[p]->first;\n\n                            if (on->visits_count == 0) {\n                                untried_outcomes.push_back(std::make_pair(&ca, on));\n                                weights.push_back(probs[p]);\n                            }\n                        }\n                    }\n                }\n            }, n.mutex);\n\n            if (untried_outcomes.empty()) { // nothing to expand\n                if (solver.debug_logs()) { spdlog::debug(\"All outcomes already tried\" +\n                                                         Tsolver::ExecutionPolicy::print_thread()); }\n                n.expanded = true;\n                return nullptr;\n            } else {\n                std::discrete_distribution<> odist(weights.begin(), weights.end());\n                std::size_t outcome_id = 0;\n                solver.execution_policy().protect([&outcome_id, &odist, &solver](){\n                    outcome_id = odist(solver.gen());\n                }, solver.gen_mutex());\n                auto& uo = untried_outcomes[outcome_id];\n\n                if (uo.second == nullptr) { // unexpanded action\n                    if (solver.debug_logs()) { spdlog::debug(\"Found one unexpanded action: \" + uo.first->action.print() +\n                                                             Tsolver::ExecutionPolicy::print_thread()); }\n                    return expand_action(solver, thread_id, solver.transition_mode(), n, *(uo.first));\n                } else { // expanded action, just return the selected next state\n                    if (solver.debug_logs()) {\n                        solver.execution_policy().protect([&uo](){\n                            spdlog::debug(\"Found one untried outcome: action \" + uo.first->action.print() +\n                                          \" and next state \" + uo.second->state.print() +\n                                          Tsolver::ExecutionPolicy::print_thread());\n                        }, uo.second->mutex);\n                    }\n                    return uo.second;\n                }\n            }\n        } catch (const std::exception& e) {\n            solver.execution_policy().protect([&n, &e](){\n                spdlog::error(\"SKDECIDE exception in MCTS when expanding state \" + n.state.print() + \": \" + e.what() +\n                              Tsolver::ExecutionPolicy::print_thread());\n            }, n.mutex);\n            throw;\n        }\n    }\n\n    template <typename Ttransition_mode,\n              std::enable_if_t<std::is_same<Ttransition_mode, DistributionTransitionMode<Tsolver>>::value, int> = 0>\n    typename Tsolver::StateNode* expand_action(Tsolver& solver,\n                                               const std::size_t* thread_id,\n                                               const Ttransition_mode& transition_mode,\n                                               typename Tsolver::StateNode& state,\n                                               typename Tsolver::ActionNode& action) const {\n        try {\n            // Generate the next states of this action\n            auto next_states = solver.domain().get_next_state_distribution(state.state, action.action, thread_id).get_values();\n            std::vector<typename Tsolver::StateNode*> untried_outcomes;\n            std::vector<double> weights;\n            std::vector<double> outcome_weights;\n\n            for (auto ns : next_states) {\n                std::pair<typename Tsolver::Graph::iterator, bool> i;\n\n                solver.execution_policy().protect([&i, &solver, &ns](){\n                    i = solver.graph().emplace(ns.state());\n                });\n\n                typename Tsolver::StateNode& next_node = const_cast<typename Tsolver::StateNode&>(*(i.first)); // we won't change the real key (StateNode::state) so we are safe\n                double reward = 0.0;\n\n                solver.execution_policy().protect([&reward, &solver, &state, &action, &next_node, &thread_id](){\n                    reward = solver.domain().get_transition_reward(state.state, action.action, next_node.state, thread_id);\n                }, next_node.mutex);\n\n                solver.execution_policy().protect([&action, &next_node, &outcome_weights, &reward, &ns](){\n                    auto ii = action.outcomes.insert(std::make_pair(&next_node, std::make_pair(reward, 1)));\n\n                    if (ii.second) { // new outcome\n                        action.dist_to_outcome.push_back(ii.first);\n                        outcome_weights.push_back(ns.probability());\n                    } else { // existing outcome (following code not efficient but hopefully very rare case if domain is well defined)\n                        for (unsigned int oid = 0 ; oid < outcome_weights.size() ; oid++) {\n                            if (action.dist_to_outcome[oid]->first == ii.first->first) { // found my outcome!\n                                std::pair<double, std::size_t>& mp = ii.first->second;\n                                mp.first = ((double) (outcome_weights[oid] * mp.first) + (reward * ns.probability())) / ((double) (outcome_weights[oid] + ns.probability()));\n                                outcome_weights[oid] += ns.probability();\n                                mp.second += 1; // useless in this mode a priori, but just keep track for coherency\n                                break;\n                            }\n                        }\n                    }\n                }, action.parent->mutex);\n\n                solver.execution_policy().protect([this, &next_node, &action, &i, &solver, &thread_id, &untried_outcomes, &weights, &ns](){\n                    next_node.parents.insert(&action);\n\n                    if (i.second) { // new node\n                        next_node.terminal = solver.domain().is_terminal(next_node.state, thread_id);\n                        std::pair<double, std::size_t> h = _heuristic(solver.domain(), next_node.state, thread_id);\n                        next_node.value = h.first;\n                        next_node.visits_count = h.second;\n                    }\n\n                    if (next_node.actions.empty()) {\n                        if (solver.debug_logs()) spdlog::debug(\"Candidate next state: \" + next_node.state.print() +\n                                                               Tsolver::ExecutionPolicy::print_thread());\n                        untried_outcomes.push_back(&next_node);\n                        weights.push_back(ns.probability());\n                    }\n                }, next_node.mutex);\n            }\n\n            // Record the action's outcomes distribution\n            solver.execution_policy().protect([&action, &outcome_weights](){\n                action.dist = std::discrete_distribution<>(outcome_weights.begin(), outcome_weights.end());\n            }, action.parent->mutex);\n\n            // Pick a random next state\n            if (untried_outcomes.empty()) {\n                // All next states already visited => pick a random next state using action.dist\n                std::size_t outcome_id = 0;\n\n                solver.execution_policy().protect([&outcome_id, &action, &solver](){\n                    outcome_id = action.dist(solver.gen());\n                }, solver.gen_mutex());\n\n                typename Tsolver::StateNode* outcome = nullptr;\n\n                solver.execution_policy().protect([&action, &outcome, &outcome_id](){\n                    outcome = action.dist_to_outcome[outcome_id]->first;\n                }, action.parent->mutex);\n\n                return outcome;\n            } else {\n                // Pick a random next state among untried ones\n                std::discrete_distribution<> odist(weights.begin(), weights.end());\n                std::size_t outcome_id = 0;\n\n                solver.execution_policy().protect([&outcome_id, &odist, &solver](){\n                    outcome_id = odist(solver.gen());\n                }, solver.gen_mutex());\n\n                return untried_outcomes[outcome_id];\n            }\n        } catch (const std::exception& e) {\n            solver.execution_policy().protect([&action, &e](){\n                spdlog::error(\"SKDECIDE exception in MCTS when expanding action \" + action.action.print() + \": \" + e.what() +\n                              Tsolver::ExecutionPolicy::print_thread());\n            }, action.parent->mutex);\n            throw;\n        }\n    }\n\n    template <typename Ttransition_mode,\n              std::enable_if_t<std::is_same<Ttransition_mode, StepTransitionMode<Tsolver>>::value ||\n                               std::is_same<Ttransition_mode, SampleTransitionMode<Tsolver>>::value, int> = 0>\n    typename Tsolver::StateNode* expand_action(Tsolver& solver,\n                                               const std::size_t* thread_id,\n                                               const Ttransition_mode& transition_mode,\n                                               typename Tsolver::StateNode& state,\n                                               typename Tsolver::ActionNode& action) const {\n        try {\n            if (!_checked_transition_mode) {\n                spdlog::warn(\"Using MCTS full expansion mode with step() or sample() domain's transition mode assumes the domain is deterministic (unpredictable result otherwise).\");\n                _checked_transition_mode = true;\n            }\n            // Generate the next state of this action\n            typename Tsolver::Domain::TransitionOutcome to = transition_mode.random_next_outcome(solver, thread_id, state.state, action.action);\n            std::pair<typename Tsolver::Graph::iterator, bool> i;\n\n            solver.execution_policy().protect([&i, &solver, &to](){\n                i = solver.graph().emplace(to.state());\n            });\n            \n            typename Tsolver::StateNode& next_node = const_cast<typename Tsolver::StateNode&>(*(i.first)); // we won't change the real key (StateNode::state) so we are safe\n            \n            solver.execution_policy().protect([&action, &next_node, &to](){\n                auto ii = action.outcomes.insert(std::make_pair(&next_node, std::make_pair(to.reward(), 1)));\n                action.dist_to_outcome.push_back(ii.first);\n            }, action.parent->mutex);\n\n            solver.execution_policy().protect([this, &next_node, &action, &i, &to, &solver, &thread_id](){\n                next_node.parents.insert(&action);\n\n                if (i.second) { // new node\n                    next_node.terminal = to.terminal();\n                    std::pair<double, std::size_t> h = _heuristic(solver.domain(), next_node.state, thread_id);\n                    next_node.value = h.first;\n                    next_node.visits_count = h.second;\n                }\n            }, next_node.mutex);\n\n            // Record the action's outcomes distribution\n            solver.execution_policy().protect([&action](){\n                action.dist = std::discrete_distribution<>({1.0});\n            }, action.parent->mutex);\n\n            if (solver.debug_logs()) {\n                solver.execution_policy().protect([&next_node](){\n                    spdlog::debug(\"Candidate next state: \" + next_node.state.print() +\n                                  Tsolver::ExecutionPolicy::print_thread());\n                }, next_node.mutex);\n            }\n            \n            return &next_node;\n        } catch (const std::exception& e) {\n            solver.execution_policy().protect([&action, &e](){\n                spdlog::error(\"SKDECIDE exception in MCTS when expanding action \" + action.action.print() + \": \" + e.what() +\n                              Tsolver::ExecutionPolicy::print_thread());\n            }, action.parent->mutex);\n            throw;\n        }\n    }\n\nprivate :\n    HeuristicFunctor _heuristic;\n    mutable typename Tsolver::ExecutionPolicy::template atomic<bool> _checked_transition_mode;\n};\n\n\n/** Test if a given node needs to be expanded by sampling applicable actions and next states.\n *  Tries to sample new outcomes with a probability proportional to the number of actual expansions.\n *  Returns nullptr if we cannot sample new outcomes, otherwise a sampled unvisited outcome\n *  according to its probability (among only unvisited outcomes).\n *  REQUIREMENTS: returns nullptr if all actions have been already tried, and set the terminal\n *  flag of the returned next state\n */\ntemplate <typename Tsolver>\nclass PartialExpand {\npublic :\n    typedef std::function<std::pair<double, std::size_t>\n                          (typename Tsolver::Domain&, const typename Tsolver::Domain::State&, const std::size_t*)> HeuristicFunctor;\n\n    PartialExpand(const HeuristicFunctor& heuristic = [](typename Tsolver::Domain& domain,\n                                                         const typename Tsolver::Domain::State& state,\n                                                         const std::size_t* thread_id) {\n        return std::make_pair(0.0, 0);\n    })\n    : _heuristic(heuristic) {}\n\n    PartialExpand(const PartialExpand& other)\n    : _heuristic(other._heuristic) {}\n\n    typename Tsolver::StateNode* operator()(Tsolver& solver,\n                                            const std::size_t* thread_id,\n                                            typename Tsolver::StateNode& n) const {\n        try {\n            if (solver.debug_logs()) {\n                solver.execution_policy().protect([&n](){\n                    spdlog::debug(\"Test expansion of state \" + n.state.print() +\n                                  Tsolver::ExecutionPolicy::print_thread());\n                }, n.mutex);\n            }\n\n            // Sample an action\n            std::bernoulli_distribution dist_state_expansion((n.visits_count > 0)?\n                                                             (((double) n.expansions_count) / ((double) n.visits_count)):\n                                                             1.0);\n            typename Tsolver::ActionNode* action_node = nullptr;\n            bool dist_res = false;\n\n            solver.execution_policy().protect([&dist_res, &solver, &dist_state_expansion](){\n                dist_res = dist_state_expansion(solver.gen());\n            }, solver.gen_mutex());\n\n            if (dist_res) {\n                typename Tsolver::Domain::Action action = solver.domain().get_applicable_actions(n.state, thread_id).sample();\n                solver.execution_policy().protect([&n, &action, &action_node, &solver](){\n                    auto a = n.actions.emplace(typename Tsolver::ActionNode(action));\n\n                    if (a.second) { // new action\n                        n.expansions_count += 1;\n                    }\n\n                    action_node = &const_cast<typename Tsolver::ActionNode&>(*(a.first)); // we won't change the real key (ActionNode::action) so we are safe\n                    if (solver.debug_logs()) { spdlog::debug(\"Tried to sample a new action: \" + action_node->action.print() +\n                                                             Tsolver::ExecutionPolicy::print_thread()); }\n                }, n.mutex);\n            } else {\n                std::vector<typename Tsolver::ActionNode*> actions;\n\n                solver.execution_policy().protect([&n, &actions](){\n                    for (auto& a : n.actions) {\n                        actions.push_back(&a);\n                    }\n                }, n.mutex);\n\n                std::uniform_int_distribution<> dist_known_actions(0, actions.size()-1);\n                std::size_t action_id = 0;\n\n                solver.execution_policy().protect([&action_id, &solver, &dist_known_actions](){\n                    action_id = dist_known_actions(solver.gen());\n                }, solver.gen_mutex());\n\n                action_node = actions[action_id];\n                if (solver.debug_logs()) {\n                    solver.execution_policy().protect([&action_node](){\n                        spdlog::debug(\"Sampled among known actions: \" + action_node->action.print() +\n                                      Tsolver::ExecutionPolicy::print_thread());\n                    }, action_node->parent.mutex);\n                }\n            }\n\n            // Sample an outcome\n            std::bernoulli_distribution dist_action_expansion((action_node->visits_count > 0)?\n                                                              (((double) action_node->expansions_count) / ((double) action_node->visits_count)):\n                                                              1.0);\n            typename Tsolver::StateNode* ns = nullptr;\n            \n            solver.execution_policy().protect([&dist_res, &solver, &dist_action_expansion](){\n                dist_res = dist_action_expansion(solver.gen());\n            }, solver.gen_mutex());\n\n            if (dist_res) {\n                std::unique_ptr<typename Tsolver::Domain::TransitionOutcome> to = solver.transition_mode().random_next_outcome(solver, thread_id, n.state, action_node->action);\n                std::pair<typename Tsolver::Graph::iterator, bool> s;\n\n                solver.execution_policy().protect([&s, &solver, &to](){\n                    s = solver.graph().emplace(to->state());\n                });\n                \n                ns = &const_cast<typename Tsolver::StateNode&>(*(s.first)); // we won't change the real key (StateNode::state) so we are safe\n\n                if (s.second) { // new state\n                    solver.execution_policy().protect([this, &ns, &to, &solver, &thread_id](){\n                        ns->terminal = to->termination();\n                        std::pair<double, std::size_t> h = _heuristic(solver.domain(), ns->state, thread_id);\n                        ns->value = h.first;\n                        ns->visits_count = h.second;\n                    }, ns->mutex);\n                }\n\n                std::pair<typename Tsolver::ActionNode::OutcomeMap::iterator, bool> ins;\n                solver.execution_policy().protect([&action_node, &ns, &to, ins](){\n                    ins = action_node->outcomes.emplace(std::make_pair(ns, std::make_pair(to->reward(), 1)));\n                }, action_node->parent->mutex);\n\n                // Update the outcome's reward and visits count\n                if (ins.second) { // new outcome\n                    solver.execution_policy().protect([&action_node, &ins](){\n                        action_node->dist_to_outcome.push_back(ins.first);\n                        action_node->expansions_count += 1;\n                    }, action_node->parent->mutex);\n\n                    solver.execution_policy().protect([&ns, &action_node](){\n                        ns->parents.insert(action_node);\n                    }, ns->mutex);\n                } else { // known outcome\n                    solver.execution_policy().protect([&ins, &to, &ns](){\n                        std::pair<double, std::size_t>& mp = ins.first->second;\n                        mp.first = ((double) (mp.second * mp.first) + to->reward()) / ((double) (mp.second + 1));\n                        mp.second += 1;\n                        ns = nullptr; // we have not discovered anything new\n                    }, action_node->parent->mutex);\n                }\n\n                // Reconstruct the probability distribution\n                solver.execution_policy().protect([&action_node](){\n                    std::vector<double> weights(action_node->dist_to_outcome.size());\n\n                    for (unsigned int oid = 0 ; oid < weights.size() ; oid++) {\n                        weights[oid] = action_node->dist_to_outcome[oid]->second.second;\n                    }\n\n                    action_node->dist = std::discrete_distribution<>(weights.begin(), weights.end());\n                }, action_node->parent->mutex);\n\n                if (solver.debug_logs()) {\n                    solver.execution_policy().protect([&ns](){\n                        spdlog::debug(\"Tried to sample a new outcome: \" + ns->state.print() +\n                                      Tsolver::ExecutionPolicy::print_thread());\n                    });\n                }\n            } else {\n                ns = nullptr; // we have not discovered anything new\n\n                if (solver.debug_logs()) {\n                    solver.execution_policy().protect([&ns](){\n                        spdlog::debug(\"Sampled among known outcomes: \" + ns->state.print() +\n                                      Tsolver::ExecutionPolicy::print_thread());\n                    });\n                }\n            }\n\n            return ns;\n        } catch (const std::exception& e) {\n            solver.execution_policy().protect([&n, &e](){\n                spdlog::error(\"SKDECIDE exception in MCTS when expanding state \" + n.state.print() + \": \" + e.what() +\n                              Tsolver::ExecutionPolicy::print_thread());\n            }, n.mutex);\n            throw;\n        }\n    }\n\nprivate :\n    HeuristicFunctor _heuristic;\n};\n\n\n/** UCB1 Best Child */\ntemplate <typename Tsolver>\nclass UCB1ActionSelector {\npublic :\n    // 1/sqrt(2) is a good compromise for rewards in [0;1]\n    UCB1ActionSelector(double ucb_constant = 1.0 / std::sqrt(2.0))\n    : _ucb_constant(ucb_constant) {}\n\n    UCB1ActionSelector(const UCB1ActionSelector& other)\n    : _ucb_constant((double) other._ucb_constant) {}\n\n    typename Tsolver::ActionNode* operator()(Tsolver& solver,\n                                             const std::size_t* thread_id,\n                                             const typename Tsolver::StateNode& n) const {\n        double best_value = -std::numeric_limits<double>::max();\n        typename Tsolver::ActionNode* best_action = nullptr;\n\n        solver.execution_policy().protect([this, &n, &best_value, &best_action, &solver](){\n            for (const auto& a : n.actions) {\n                if (a.visits_count > 0) {\n                    double tentative_value = a.value + (2.0 * _ucb_constant * std::sqrt((2.0 * std::log((double) n.visits_count)) / ((double) a.visits_count)));\n\n                    if (tentative_value > best_value) {\n                        best_value = tentative_value;\n                        best_action = &const_cast<typename Tsolver::ActionNode&>(a); // we won't change the real key (ActionNode::action) so we are safe\n                    }\n                }\n            }\n\n            if (solver.debug_logs()) { spdlog::debug(\"UCB1 selection from state \" + n.state.print() +\n                                                     \": value=\" + StringConverter::from(best_value) +\n                                                     \", action=\" + ((best_action != nullptr)?(best_action->action.print()):(\"nullptr\")) +\n                                                     Tsolver::ExecutionPolicy::print_thread()); }\n        }, n.mutex);\n        \n        return best_action;\n    }\n\nprivate :\n    typename Tsolver::ExecutionPolicy::template atomic<double> _ucb_constant;\n};\n\n\n/** Select action with maximum Q-value */\ntemplate <typename Tsolver>\nclass BestQValueActionSelector {\npublic :\n    typename Tsolver::ActionNode* operator()(Tsolver& solver,\n                                             const std::size_t* thread_id,\n                                             const typename Tsolver::StateNode& n) const {\n        double best_value = -std::numeric_limits<double>::max();\n        typename Tsolver::ActionNode* best_action = nullptr;\n\n        solver.execution_policy().protect([&n, &best_value, &best_action, &solver](){\n            for (const auto& a : n.actions) {\n                if (a.visits_count > 0) {\n                    if (a.value > best_value) {\n                        best_value = a.value;\n                        best_action = &const_cast<typename Tsolver::ActionNode&>(a); // we won't change the real key (ActionNode::action) so we are safe\n                    }\n                }\n            }\n\n            if (solver.debug_logs()) { spdlog::debug(\"Best Q-value selection from state \" + n.state.print() +\n                                                     \": value=\" + StringConverter::from(best_value) +\n                                                     \", action=\" + ((best_action != nullptr)?(best_action->action.print()):(\"nullptr\")) +\n                                                     Tsolver::ExecutionPolicy::print_thread()); }\n        }, n.mutex);\n        \n        return best_action;\n    }\n};\n\n\n/** Default rollout policy */\ntemplate <typename Tsolver>\nclass DefaultRolloutPolicy {\npublic :\n    typedef std::function<typename Tsolver::Domain::Action\n                          (typename Tsolver::Domain&, const typename Tsolver::Domain::State&, const std::size_t*)> PolicyFunctor;\n\n    DefaultRolloutPolicy(const PolicyFunctor& policy = [](typename Tsolver::Domain& domain,\n                                                          const typename Tsolver::Domain::State& state,\n                                                          const std::size_t* thread_id) {\n        return domain.get_applicable_actions(state, thread_id).sample();\n    })\n    : _policy(policy) {}\n\n    void operator()(Tsolver& solver,\n                    const std::size_t* thread_id,\n                    typename Tsolver::StateNode& n,\n                    std::size_t d) const {\n        try {\n            typename Tsolver::Domain::State current_state;\n\n            solver.execution_policy().protect([&solver, &n, &current_state](){\n                if (solver.debug_logs()) { spdlog::debug(\"Launching default rollout policy from state \" + n.state.print() +\n                                                         Tsolver::ExecutionPolicy::print_thread()); }\n                current_state = n.state;\n            }, n.mutex);\n\n            bool termination = false;\n            std::size_t current_depth = d;\n            double reward = 0.0;\n            double gamma_n = 1.0;\n\n            while(!termination && current_depth < solver.max_depth()) {\n                typename Tsolver::Domain::Action action = _policy(solver.domain(), current_state, thread_id);\n                typename Tsolver::Domain::TransitionOutcome o = solver.transition_mode().random_next_outcome(solver, thread_id, current_state, action);\n                reward += gamma_n * (o.reward());\n                gamma_n *= solver.discount();\n                current_state = o.state();\n                termination = o.terminal();\n                current_depth++;\n                if (solver.debug_logs()) { spdlog::debug(\"Sampled transition: action=\" + action.print() +\n                                                         \", next state=\" + current_state.print() +\n                                                         \", reward=\" + StringConverter::from(o.reward()) +\n                                                         Tsolver::ExecutionPolicy::print_thread()); }\n            }\n\n            // since we can come to state n after exhausting the depth, n might be already visited\n            // so don't erase its value but rather update it\n            solver.execution_policy().protect([&n, &reward](){\n                n.value = ((n.visits_count * n.value)  + reward) / ((double) (n.visits_count + 1));\n                n.visits_count += 1;\n            }, n.mutex);\n        } catch (const std::exception& e) {\n            solver.execution_policy().protect([&n, &e](){\n                spdlog::error(\"SKDECIDE exception in MCTS when simulating the random default policy from state \" + n.state.print() + \": \" + e.what() +\n                              Tsolver::ExecutionPolicy::print_thread());\n            }, n.mutex);\n            throw;\n        }\n    }\n\nprivate :\n    PolicyFunctor _policy;\n};\n\n\n/** Graph backup: update Q values using the graph ancestors (rather than only the trajectory leading to n) */\ntemplate <typename Tsolver>\nstruct GraphBackup {\n    void operator()(Tsolver& solver,\n                    const std::size_t* thread_id,\n                    typename Tsolver::StateNode& n) const {\n        if (solver.debug_logs()) {\n            solver.execution_policy().protect([&n](){\n                spdlog::debug(\"Back-propagating values from state \" + n.state.print() +\n                              Tsolver::ExecutionPolicy::print_thread());\n            }, n.mutex);\n        }\n\n        std::size_t depth = 0; // used to prevent infinite loop in case of cycles\n        std::unordered_set<typename Tsolver::StateNode*> frontier;\n        frontier.insert(&n);\n\n        while (!frontier.empty() && depth <= solver.max_depth()) {\n            depth++;\n            std::unordered_set<typename Tsolver::StateNode*> new_frontier;\n            \n            for (auto& f : frontier) {\n                update_frontier(solver, new_frontier, f, &solver.execution_policy());\n            }\n\n            frontier = new_frontier;\n        }\n    }\n\n    template <typename Texecution_policy,\n              std::enable_if_t<std::is_same<Texecution_policy, SequentialExecution>::value, int> = 0>\n    static void update_frontier(Tsolver& solver,\n                                std::unordered_set<typename Tsolver::StateNode*>& new_frontier, typename Tsolver::StateNode* f,\n                                [[maybe_unused]] Texecution_policy* execution_policy) {\n        for (auto& a : f->parents) {\n            double q_value = a->outcomes[f].first + (solver.discount() * (f->value));\n            a->value = (((a->visits_count) * (a->value))  + q_value) / ((double) (a->visits_count + 1));\n            a->visits_count += 1;\n            typename Tsolver::StateNode* parent_node = a->parent;\n            parent_node->value = (((parent_node->visits_count) * (parent_node->value))  + (a->value)) / ((double) (parent_node->visits_count + 1));\n            parent_node->visits_count += 1;\n            new_frontier.insert(parent_node);\n            if (solver.debug_logs()) { spdlog::debug(\"Updating state \" + parent_node->state.print() +\n                                                    \": value=\" + StringConverter::from(parent_node->value) +\n                                                    \", visits=\" + StringConverter::from(parent_node->visits_count) +\n                                                    Tsolver::ExecutionPolicy::print_thread()); }\n        }\n    }\n\n    template <typename Texecution_policy,\n              std::enable_if_t<std::is_same<Texecution_policy, ParallelExecution>::value, int> = 0>\n    static void update_frontier(Tsolver& solver,\n                                std::unordered_set<typename Tsolver::StateNode*>& new_frontier, typename Tsolver::StateNode* f,\n                                [[maybe_unused]] Texecution_policy* execution_policy) {\n        std::list<typename Tsolver::ActionNode*> parents;\n        solver.execution_policy().protect([&f, &parents](){\n            std::copy(f->parents.begin(), f->parents.end(), std::inserter(parents, parents.end()));\n        }, f->mutex);\n        for (auto& a : parents) {\n            solver.execution_policy().protect([&a, &solver, &f, &new_frontier](){\n                double q_value = a->outcomes[f].first + (solver.discount() * (f->value));\n                a->value = (((a->visits_count) * (a->value))  + q_value) / ((double) (a->visits_count + 1));\n                a->visits_count += 1;\n                typename Tsolver::StateNode* parent_node = a->parent;\n                parent_node->value = (((parent_node->visits_count) * (parent_node->value))  + (a->value)) / ((double) (parent_node->visits_count + 1));\n                parent_node->visits_count += 1;\n                new_frontier.insert(parent_node);\n                if (solver.debug_logs()) { spdlog::debug(\"Updating state \" + parent_node->state.print() +\n                                                        \": value=\" + StringConverter::from(parent_node->value) +\n                                                        \", visits=\" + StringConverter::from(parent_node->visits_count) +\n                                                        Tsolver::ExecutionPolicy::print_thread()); }\n            }, a->parent->mutex);\n        }\n    }\n};\n\n\ntemplate <typename Tdomain,\n          typename TexecutionPolicy = SequentialExecution,\n          template <typename Tsolver> class TtransitionMode = DistributionTransitionMode,\n          template <typename Tsolver> class TtreePolicy = DefaultTreePolicy,\n          template <typename Tsolver> class Texpander = FullExpand,\n          template <typename Tsolver> class TactionSelectorOptimization = UCB1ActionSelector,\n          template <typename Tsolver> class TactionSelectorExecution = BestQValueActionSelector,\n          template <typename Tsolver> class TrolloutPolicy = DefaultRolloutPolicy,\n          template <typename Tsolver> class TbackPropagator = GraphBackup>\nclass MCTSSolver {\npublic :\n    typedef MCTSSolver<Tdomain, TexecutionPolicy,\n                       TtransitionMode, TtreePolicy, Texpander,\n                       TactionSelectorOptimization, TactionSelectorExecution,\n                       TrolloutPolicy, TbackPropagator> Solver;\n\n    typedef Tdomain Domain;\n    typedef typename Domain::State State;\n    typedef typename Domain::Event Action;\n    typedef TexecutionPolicy ExecutionPolicy;\n    typedef TtransitionMode<Solver> TransitionMode;\n    typedef TtreePolicy<Solver> TreePolicy;\n    typedef Texpander<Solver> Expander;\n    typedef TactionSelectorOptimization<Solver> ActionSelectorOptimization;\n    typedef TactionSelectorExecution<Solver> ActionSelectorExecution;\n    typedef TrolloutPolicy<Solver> RolloutPolicy;\n    typedef TbackPropagator<Solver> BackPropagator;\n\n    typedef typename ExecutionPolicy::template atomic<std::size_t> atomic_size_t;\n    typedef typename ExecutionPolicy::template atomic<double> atomic_double;\n    typedef typename ExecutionPolicy::template atomic<bool> atomic_bool;\n\n    struct StateNode;\n\n    struct ActionNode {\n        Action action;\n        typedef std::unordered_map<StateNode*, std::pair<double, std::size_t>> OutcomeMap; // next state nodes owned by _graph\n        OutcomeMap outcomes;\n        std::vector<typename OutcomeMap::iterator> dist_to_outcome;\n        std::discrete_distribution<> dist;\n        atomic_size_t expansions_count; // used only for partial expansion mode\n        atomic_double value;\n        atomic_size_t visits_count;\n        StateNode* parent;\n\n        ActionNode(const Action& a)\n            : action(a), expansions_count(0), value(0.0),\n              visits_count(0), parent(nullptr) {}\n        \n        ActionNode(const ActionNode& a)\n            : action(a.action), outcomes(a.outcomes), dist_to_outcome(a.dist_to_outcome),\n              dist(a.dist), expansions_count((std::size_t) a.expansions_count),\n              value((double) a.value), visits_count((std::size_t) a.visits_count),\n              parent(a.parent) {}\n        \n        struct Key {\n            const Action& operator()(const ActionNode& an) const { return an.action; }\n        };\n    };\n\n    struct StateNode {\n        typedef typename SetTypeDeducer<ActionNode, Action>::Set ActionSet;\n        State state;\n        atomic_bool terminal;\n        atomic_bool expanded; // used only for full expansion mode\n        atomic_size_t expansions_count; // used only for partial expansion mode\n        ActionSet actions;\n        atomic_double value;\n        atomic_size_t visits_count;\n        std::unordered_set<ActionNode*> parents;\n        mutable typename ExecutionPolicy::Mutex mutex;\n\n        StateNode(const State& s)\n            : state(s), terminal(false), expanded(false),\n              expansions_count(0), value(0.0), visits_count(0) {}\n        \n        StateNode(const StateNode& s)\n            : state(s.state), terminal((bool) s.terminal), expanded((bool) s.expanded),\n              expansions_count((std::size_t) s.expansions_count), actions(s.actions),\n              value((double) s.value), visits_count((std::size_t) s.visits_count),\n              parents(s.parents) {}\n        \n        struct Key {\n            const State& operator()(const StateNode& sn) const { return sn.state; }\n        };\n    };\n\n    typedef typename SetTypeDeducer<StateNode, State>::Set Graph;\n\n    MCTSSolver(Domain& domain,\n               std::size_t time_budget = 3600000,\n               std::size_t rollout_budget = 100000,\n               std::size_t max_depth = 1000,\n               double discount = 1.0,\n               bool online_node_garbage = false,\n               bool debug_logs = false,\n               std::unique_ptr<TreePolicy> tree_policy = std::make_unique<TreePolicy>(),\n               std::unique_ptr<Expander> expander = std::make_unique<Expander>(),\n               std::unique_ptr<ActionSelectorOptimization> action_selector_optimization = std::make_unique<ActionSelectorOptimization>(),\n               std::unique_ptr<ActionSelectorExecution> action_selector_execution = std::make_unique<ActionSelectorExecution>(),\n               std::unique_ptr<RolloutPolicy> rollout_policy = std::make_unique<RolloutPolicy>(),\n               std::unique_ptr<BackPropagator> back_propagator = std::make_unique<BackPropagator>())\n    : _domain(domain),\n      _time_budget(time_budget), _rollout_budget(rollout_budget),\n      _max_depth(max_depth), _discount(discount), _nb_rollouts(0),\n      _online_node_garbage(online_node_garbage),\n      _debug_logs(debug_logs),\n      _tree_policy(std::move(tree_policy)),\n      _expander(std::move(expander)),\n      _action_selector_optimization(std::move(action_selector_optimization)),\n      _action_selector_execution(std::move(action_selector_execution)),\n      _rollout_policy(std::move(rollout_policy)),\n      _back_propagator(std::move(back_propagator)),\n      _current_state(nullptr) {\n        if (debug_logs) {\n            spdlog::set_level(spdlog::level::debug);\n        } else {\n            spdlog::set_level(spdlog::level::info);\n        }\n\n        std::random_device rd;\n        _gen = std::make_unique<std::mt19937>(rd());\n    }\n\n    // clears the solver (clears the search graph, thus preventing from reusing\n    // previous search results)\n    void clear() {\n        _graph.clear();\n    }\n\n    // solves from state s\n    void solve(const State& s) {\n        try {\n            spdlog::info(\"Running \" + ExecutionPolicy::print_type() + \" MCTS solver from state \" + s.print());\n            auto start_time = std::chrono::high_resolution_clock::now();\n            _nb_rollouts = 0;\n\n            // Get the root node\n            auto si = _graph.emplace(s);\n            StateNode& root_node = const_cast<StateNode&>(*(si.first)); // we won't change the real key (StateNode::state) so we are safe\n\n            boost::integer_range<std::size_t> parallel_rollouts(0, _domain.get_parallel_capacity());\n\n            std::for_each(ExecutionPolicy::policy, parallel_rollouts.begin(), parallel_rollouts.end(), [this, &start_time, &root_node] (const std::size_t& thread_id) {\n                \n                while (elapsed_time(start_time) < _time_budget && _nb_rollouts < _rollout_budget) {\n                \n                    std::size_t depth = 0;\n                    StateNode* sn = (*_tree_policy)(*this, &thread_id, *_expander, *_action_selector_optimization, root_node, depth);\n                    (*_rollout_policy)(*this, &thread_id, *sn, depth);\n                    (*_back_propagator)(*this, &thread_id, *sn);\n                    _nb_rollouts++;\n\n                }\n                \n            });\n\n            auto end_time = std::chrono::high_resolution_clock::now();\n            auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count();\n            spdlog::info(\"MCTS finished to solve from state \" + s.print() +\n                         \" in \" + StringConverter::from((double) duration / (double) 1e9) + \" seconds with \" +\n                         StringConverter::from(_nb_rollouts) + \" rollouts.\");\n        } catch (const std::exception& e) {\n            spdlog::error(\"MCTS failed solving from state \" + s.print() + \". Reason: \" + e.what());\n            throw;\n        }\n    }\n\n    bool is_solution_defined_for(const State& s) {\n        auto si = _graph.find(s);\n        if (si == _graph.end()) {\n            return false;\n        } else {\n            return (*_action_selector_execution)(*this, nullptr, *si) != nullptr;\n        }\n    }\n\n    Action get_best_action(const State& s) {\n        auto si = _graph.find(s);\n        ActionNode* action = nullptr;\n        if (si != _graph.end()) {\n            action = (*_action_selector_execution)(*this, nullptr, *si);\n        }\n        if (action == nullptr) {\n            spdlog::error(\"SKDECIDE exception: no best action found in state \" + s.print());\n            throw std::runtime_error(\"SKDECIDE exception: no best action found in state \" + s.print());\n        } else {\n            if (_debug_logs) {\n                std::string str = \"(\";\n                for (const auto& o : action->outcomes) {\n                    str += \"\\n    \" + o.first->state.print();\n                }\n                str += \"\\n)\";\n                spdlog::debug(\"Best action's known outcomes:\\n\" + str);\n            }\n            if (_online_node_garbage && _current_state) {\n                std::unordered_set<StateNode*> root_subgraph, child_subgraph;\n                compute_reachable_subgraph(_current_state, root_subgraph);\n                compute_reachable_subgraph(const_cast<StateNode*>(&(*si)), child_subgraph); // we won't change the real key (StateNode::state) so we are safe\n                remove_subgraph(root_subgraph, child_subgraph);\n            }\n            _current_state = const_cast<StateNode*>(&(*si)); // we won't change the real key (StateNode::state) so we are safe\n            _action_prefix.push_back(action->action);\n            return action->action;\n        }\n    }\n\n    double get_best_value(const State& s) {\n        auto si = _graph.find(StateNode(s));\n        ActionNode* action = nullptr;\n        if (si != _graph.end()) {\n            action = (*_action_selector_execution)(*this, nullptr, *si);\n        }\n        if (action == nullptr) {\n            spdlog::error(\"SKDECIDE exception: no best action found in state \" + s.print());\n            throw std::runtime_error(\"SKDECIDE exception: no best action found in state \" + s.print());\n        } else {\n            return action->value;\n        }\n    }\n\n    std::size_t nb_of_explored_states() const {\n        return _graph.size();\n    }\n\n    std::size_t nb_rollouts() const {\n        return _nb_rollouts;\n    }\n\n    typename MapTypeDeducer<State, std::pair<Action, double>>::Map policy() {\n        typename MapTypeDeducer<State, std::pair<Action, double>>::Map p;\n        for (auto& n : _graph) {\n            ActionNode* action = (*_action_selector_execution)(*this, nullptr, n);\n            if (action != nullptr) {\n                p.insert(std::make_pair(n.state, std::make_pair(action->action, (double) action->value)));\n            }\n        }\n        return p;\n    }\n\n    Domain& domain() { return _domain; }\n\n    std::size_t time_budget() const { return _time_budget; }\n\n    std::size_t rollout_budget() const { return _rollout_budget; }\n\n    std::size_t max_depth() const { return _max_depth; }\n\n    double discount() const { return _discount; }\n\n    ExecutionPolicy& execution_policy() { return _execution_policy; }\n\n    TransitionMode& transition_mode() { return _transition_mode; }\n\n    const TreePolicy& tree_policy() { return *_tree_policy; }\n\n    const Expander& expander() { return *_expander; }\n\n    const ActionSelectorOptimization& action_selector_optimization() { return *_action_selector_optimization; }\n\n    const ActionSelectorExecution& action_selector_execution() { return *_action_selector_execution; }\n\n    const RolloutPolicy& rollout_policy() { return *_rollout_policy; }\n\n    const BackPropagator& back_propagator() { return *_back_propagator; }\n\n    Graph& graph() { return _graph; }\n\n    const std::list<Action>& action_prefix() const { return _action_prefix; }\n\n    std::mt19937& gen() { return *_gen; }\n\n    typename ExecutionPolicy::Mutex& gen_mutex() { return _gen_mutex; }\n\n    bool debug_logs() const { return _debug_logs; }\n\nprivate :\n\n    Domain& _domain;\n    atomic_size_t _time_budget;\n    atomic_size_t _rollout_budget;\n    atomic_size_t _max_depth;\n    atomic_double _discount;\n    atomic_size_t _nb_rollouts;\n    bool _online_node_garbage;\n    atomic_bool _debug_logs;\n\n    ExecutionPolicy _execution_policy;\n    TransitionMode _transition_mode;\n\n    std::unique_ptr<TreePolicy> _tree_policy;\n    std::unique_ptr<Expander> _expander;\n    std::unique_ptr<ActionSelectorOptimization> _action_selector_optimization;\n    std::unique_ptr<ActionSelectorExecution> _action_selector_execution;\n    std::unique_ptr<RolloutPolicy> _rollout_policy;\n    std::unique_ptr<BackPropagator> _back_propagator;\n\n    Graph _graph;\n    StateNode* _current_state;\n    std::list<Action> _action_prefix;\n\n    std::unique_ptr<std::mt19937> _gen;\n    typename ExecutionPolicy::Mutex _gen_mutex;\n    typename ExecutionPolicy::Mutex _time_mutex;\n\n    void compute_reachable_subgraph(StateNode* node, std::unordered_set<StateNode*>& subgraph) {\n        std::unordered_set<StateNode*> frontier;\n        frontier.insert(node);\n        subgraph.insert(node);\n        while(!frontier.empty()) {\n            std::unordered_set<StateNode*> new_frontier;\n            for (auto& n : frontier) {\n                for (auto& action : n->actions) {\n                    for (auto& outcome : action.outcomes) {\n                        if (subgraph.find(outcome.first) == subgraph.end()) {\n                            new_frontier.insert(outcome.first);\n                            subgraph.insert(outcome.first);\n                        }\n                    }\n                }\n            }\n            frontier = new_frontier;\n        }\n    }\n\n    void remove_subgraph(std::unordered_set<StateNode*>& root_subgraph, std::unordered_set<StateNode*>& child_subgraph) {\n        std::unordered_set<StateNode*> removed_subgraph;\n        // First pass: look for nodes in root_subgraph but not child_subgraph and remove\n        // those nodes from their children's parents\n        // Don't actually remove those nodes in the first pass otherwise some children to remove\n        // won't exist anymore when looking for their parents\n        for (auto& n : root_subgraph) {\n            if (child_subgraph.find(n) == child_subgraph.end()) {\n                for (auto& action : n->actions) {\n                    for (auto& outcome : action.outcomes) {\n                        // we won't change the real key (ActionNode::action) so we are safe\n                        outcome.first->parents.erase(&const_cast<ActionNode&>(action));\n                    }\n                }\n                removed_subgraph.insert(n);\n            }\n        }\n        // Second pass: actually remove nodes in root_subgraph but not in child_subgraph\n        for (auto& n : removed_subgraph) {\n            _graph.erase(StateNode(n->state));\n        }\n    }\n\n    std::size_t elapsed_time(const std::chrono::time_point<std::chrono::high_resolution_clock>& start_time) {\n        std::size_t milliseconds_duration;\n        _execution_policy.protect([&milliseconds_duration, &start_time](){\n            milliseconds_duration = static_cast<std::size_t>(\n                std::chrono::duration_cast<std::chrono::milliseconds>(\n                    std::chrono::high_resolution_clock::now() - start_time\n                ).count()\n            );\n        }, _time_mutex);\n        return milliseconds_duration;\n    }\n}; // MCTSSolver class\n\n/** UCT is MCTS with the default template options */\ntemplate <typename Tdomain,\n          typename Texecution_policy,\n          template <typename Tsolver> typename TtransitionMode,\n          template <typename Tsolver> typename ...T>\nusing UCTSolver = MCTSSolver<Tdomain, Texecution_policy, TtransitionMode, T...>;\n\n} // namespace skdecide\n\n#endif // SKDECIDE_MCTS_HH\n", "meta": {"hexsha": "6a1f2ea71d78635440b3a6522c2bc86d7c08ddf0", "size": 60044, "ext": "hh", "lang": "C++", "max_stars_repo_path": "cpp/src/hub/solver/mcts.hh", "max_stars_repo_name": "jeromerobert/scikit-decide", "max_stars_repo_head_hexsha": "900916e627669fb3f7520edb2aaef55e08064b25", "max_stars_repo_licenses": ["MIT"], "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/hub/solver/mcts.hh", "max_issues_repo_name": "jeromerobert/scikit-decide", "max_issues_repo_head_hexsha": "900916e627669fb3f7520edb2aaef55e08064b25", "max_issues_repo_licenses": ["MIT"], "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/hub/solver/mcts.hh", "max_forks_repo_name": "jeromerobert/scikit-decide", "max_forks_repo_head_hexsha": "900916e627669fb3f7520edb2aaef55e08064b25", "max_forks_repo_licenses": ["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.503164557, "max_line_length": 182, "alphanum_fraction": 0.5581240424, "num_tokens": 12242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.03021458357436341, "lm_q1q2_score": 0.011518390444829012}}
{"text": "// @authors:     Ahmad Humayun\n// @contact:     ahumayun@cc.gatech.edu\n// @affiliation: Georgia Institute of Technology\n// @date:        Fall 2013 - Summer 2014\n\n/* precomptrees.cpp */\n\n#ifndef __PRECOMPTREESIMPL_HPP__\n#define __PRECOMPTREESIMPL_HPP__\n\n#include <iostream>\n#include <fstream>\n#include <boost/format.hpp>\n\n#include \"graph.h\"\n\nusing boost::format;\n\n\n/*\n  special constants for node->parent. Duplicated in graph.cpp, both should match!\n*/\n#define TERMINAL ( (arc *) 1 )    /* to terminal */\n#define ORPHAN   ( (arc *) 2 )    /* orphan */\n\n\ntemplate<typename captype, typename tcaptype, typename flowtype>\n void Graph<captype, tcaptype, flowtype>::transform_seed_trees(\n    const int keep_src_id, const SrcSeedList* remove_seed_list)\n{\n  node *i;\n\n  typename SrcSeedList::const_iterator it_orig_cap, it_new_cap;\n\n  // useful for maxflow_reuse_trees_init()\n  curr_src_origin_idx = keep_src_id;\n\n  // iterate over all the fg seed nodes which need to be converted from Seed S\n  // trees to T sink trees. This loop looks at the fg seeds which need to be\n  // discarded: it changes its residual capacities; adjusts the flow and adds\n  // to the queue for being marked as the sink tree\n  for (it_orig_cap = remove_seed_list[0].begin(),\n       it_new_cap = remove_seed_list[1].begin();\n       it_orig_cap != remove_seed_list[0].end(); ++it_orig_cap, ++it_new_cap) {\n    // get the pointer to the current node\n    i = nodes + it_orig_cap->first;\n\n    tcaptype new_sink_residual_cap, new_src_residual_cap;\n\n    // get all the capacities\n    tcaptype residual_cap = get_trcap(i - nodes);\n    tcaptype orig_src_cap = it_orig_cap->second.first;\n    //tcaptype orig_sink_cap = it_orig_cap->second.second;\n    tcaptype new_src_cap = it_new_cap->second.first;\n    tcaptype new_sink_cap = it_new_cap->second.second;\n\n    tcaptype flow_s = orig_src_cap - residual_cap;\n\n    // we can directly set the residual capacity on the sink link because\n    // we know there was no capacity on it originally i.e.\n    // c_{it} = r_{it} = f_{it} = 0   /   orig_sink_cap := 0\n    new_sink_residual_cap = new_sink_cap;\n\n    // if the capacity is reduced only to the extent that it can still\n    // accomodate the old flow (see Kohli and Torr, PAMI 2007)\n    if (new_src_cap >= flow_s) {\n      new_src_residual_cap = new_src_cap - flow_s;\n    } else {\n      /* if not then add an alpha value to the sink capacity */\n      new_src_residual_cap = 0;\n      new_sink_residual_cap += flow_s - new_src_cap;\n      flow -= flow_s - new_src_cap;\n    }\n\n    set_trcap(it_orig_cap->first, new_src_residual_cap - new_sink_residual_cap);\n\n    //std::cout << \"Node \" << (node_id)(i - nodes) << \": Old \" << residual_cap << \", New \" << get_trcap(i - nodes) << std::endl;\n\n    // push to queue according to whether they have positive residual capacity\n    // or negative. If they have negative residual capacity on its t link then\n    // the node and its children can be converted to Sink T tree in the\n    // upcoming while loop. Otherwise it needs to be added to the Source S\n    // tree\n    /*\n    i->parent = TERMINAL;\n    if (get_trcap(i - nodes) < 0)\n      t_tree_children.push(i);\n    else if (get_trcap(i - nodes) > 0)\n      s_tree_children.push(i);\n    */\n    if (get_trcap(i - nodes) != 0)\n      i->parent = TERMINAL;\n    else {\n      i->src_origin_idx = INVALID_SRC_ID;\n      i->parent = NULL;\n    }\n  }\n\n  node* n_ptr;\n  NodeEditSet tree_nodes;\n\n  // iterate over all nodes and add terminal and free nodes to the tree_nodes\n  // list (and indicate as root in orig_root_nodes)\n  for (n_ptr = nodes; n_ptr < node_last; ++n_ptr) {\n    // skip node if its not a terminal or free node\n    if (n_ptr->parent == TERMINAL || n_ptr->parent == NULL) {\n      tree_nodes.insert(n_ptr);\n    }\n  }\n\n  normalize_tree(tree_nodes);\n\n  // iterate over all the nodes and set as free if they were neither part of\n  // seed src or the converted sink trees\n  /*for (i = nodes; i < node_last; i++) {\n    if (i->src_origin_idx != keep_src_id && i->src_origin_idx != INVALID_SRC_ID &&\n        i->is_sink != 1 && i->tr_cap == 0) {\n      //if (PRINT_DEBUG && ((node_id)(i - nodes) == 41 || (node_id)(i - nodes) == 69 || (node_id)(i - nodes) == 99 || (node_id)(i - nodes) == 70))\n      //  std::cout << \"\\tMarking \" << i - nodes << \" as free\" << std::endl;\n\n      i->parent = NULL;\n      i->src_origin_idx = INVALID_SRC_ID;\n      //mark_node(i - nodes);\n\n      // mark all the neighboring nodes as active too\n      for (arc* a = i->first; a; a = a->next) {\n        mark_node(a->head - nodes);\n        //std::cout << a->head - nodes << \", \";\n      }\n    }\n  } */\n}\n\ntemplate<typename captype, typename tcaptype, typename flowtype>\n  void Graph<captype, tcaptype, flowtype>::set_active_normalization()\n{\n  node* n_ptr;\n  node* neigh_ptr;\n\n  // iterate over all nodes to see which ones should be set to active\n  for (n_ptr = nodes; n_ptr < node_last; ++n_ptr) {\n    //set_active(n_ptr);\n    // if node doesn't belong to a tree after normalization, don't mark it\n    //  active. A neighboring node, which belongs to a tree, and hence can\n    //  grow into it would be marked when it sees this node\n    if (n_ptr->parent == NULL || n_ptr->parent == ORPHAN) {\n      continue;\n    } else {\n      // we now know that n_ptr belongs to a valid tree\n\n      // iterate over each neighbor to see if there is a reason to set this\n      // node active\n      for (arc* a = n_ptr->first; a; a = a->next) {\n        neigh_ptr = a->head;\n\n        // neighbor is free or orphan (i.e. it doesnt belong to a tree) set\n        // this node as active, so that the neighbor can be grown into\n        if (neigh_ptr->parent == NULL || neigh_ptr->parent == ORPHAN) {\n          set_active(n_ptr);\n          break;\n        } else {\n          // if the neighbor belongs to an opposite tree\n          if (n_ptr->is_sink != neigh_ptr->is_sink) {\n            // if there is an unsaturated path between the nodes\n            //  if u is in src then the arc u->v should be unsaturated\n            //  if u is in sink then the arc v->u should be unsaturated\n            if ((!n_ptr->is_sink && a->r_cap) ||\n                (n_ptr->is_sink && a->sister->r_cap)) {\n              // if the neighbor is active, then no need to set this node\n              //  to active. It will get noticed anyways by neighbor anyways\n              //if (!neigh_ptr->next) {\n                set_active(n_ptr);\n                break;\n              //}\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\ntemplate<typename captype, typename tcaptype, typename flowtype>\n  void Graph<captype, tcaptype, flowtype>::normalize_node(node* const n_ptr)\n{\n  captype up_rcap, dwn_rcap;\n\n  bool is_root = (n_ptr->parent == TERMINAL || n_ptr->parent == NULL || n_ptr->parent == ORPHAN);\n\n  // note down the original sink/src value\n  int old_is_sink = -1;\n  if (n_ptr->parent != NULL && n_ptr->parent != ORPHAN)\n    old_is_sink = n_ptr->is_sink;\n\n  // check if the parent was sink/src\n  int parent_is_sink = -1;\n  if (!is_root && n_ptr->parent->head->parent != NULL &&\n                  n_ptr->parent->head->parent != ORPHAN)\n    parent_is_sink = n_ptr->parent->head->is_sink;\n\n  // note the residual capacities both on tr and n links\n  if (!is_root) {\n    up_rcap = n_ptr->parent->r_cap;\n    dwn_rcap = n_ptr->parent->sister->r_cap;\n  }\n  tcaptype trcap = get_trcap(n_ptr-nodes);\n\n  /*\n  if (trcap != 0) {\n    n_ptr->next = NULL;\n    n_ptr->is_marked = 0;\n    std::cout << \" | \" << (!n_ptr->next);\n    set_active(n_ptr);\n  }*/\n\n  // if the node can be connected to the parent, then update values,\n  // otherwise either set to free or connect to terminal if t residual\n  // capacity preset TIME\n  if ((parent_is_sink == 0 && dwn_rcap > 0 && trcap >= 0) ||\n      (parent_is_sink == 1 && up_rcap > 0 && trcap <= 0)) {\n    n_ptr->is_sink = parent_is_sink;\n    n_ptr->src_origin_idx = n_ptr->parent->head->src_origin_idx;\n    n_ptr->TS = TIME + 1;\n    n_ptr->DIST = n_ptr->parent->head->DIST + 1;\n  } else if (trcap != 0) {\n    // directly connect to terminal\n    n_ptr->is_sink = trcap < 0;\n    n_ptr->src_origin_idx = n_ptr->is_sink ? INVALID_SRC_ID : curr_src_origin_idx;\n    n_ptr->parent = TERMINAL;\n    n_ptr->TS = TIME + 1;\n    n_ptr->DIST = 1;\n  } else {\n    // set free\n    n_ptr->parent = NULL;\n    n_ptr->src_origin_idx = INVALID_SRC_ID;\n\n    // also mark node so it comes in active list\n    //mark_node(n_ptr - nodes);\n  }\n\n  // get the new src/sink value\n  int new_is_sink = -1;\n  if (n_ptr->parent != NULL && n_ptr->parent != ORPHAN)\n    new_is_sink = n_ptr->is_sink;\n\n  // if the src/sink value change, then mark itself and all the neighboring\n  // nodes\n  if (new_is_sink != old_is_sink) {\n    //mark_node(n_ptr - nodes);\n    add_to_changed_list(n_ptr);\n\n    // mark all neighboring nodes with different src/sink id as active too\n   /* for (arc* a = n_ptr->first; a; a = a->next) {\n      int neigh_is_sink = -1;\n      if (a->head->parent != NULL && a->head->parent != ORPHAN)\n        neigh_is_sink = a->head->is_sink;\n\n      if (neigh_is_sink != new_is_sink)\n        mark_node(a->head - nodes);\n    }*/\n  }\n}\n\n\ntemplate<typename captype, typename tcaptype, typename flowtype>\n  void Graph<captype, tcaptype, flowtype>::normalize_tree(NodeEditSet& tree_nodes)\n{\n  node* n_ptr;\n  node* tree_ptr;\n  captype up_rcap, dwn_rcap;\n\n  // BFS over all trees\n  for (n_ptr = nodes; n_ptr < node_last; ++n_ptr) {\n    // check if\n    bool is_root = (n_ptr->parent == TERMINAL || n_ptr->parent == NULL);\n\n    // skip node if its not a terminal node\n    if (is_root) {\n      // if src root node, then explore the whole tree\n      std::queue<node*> tree_queue;\n\n      tree_queue.push(n_ptr);\n\n      // BFS over whole tree\n      while (!tree_queue.empty()) {\n        tree_ptr = tree_queue.front();\n        tree_queue.pop();\n\n        bool node_normalized = false;\n\n        // if it was suggested that the node was changed\n        if (tree_nodes.count(tree_ptr) != 0) {\n          normalize_node(tree_ptr);\n          node_normalized = true;\n\n          tree_nodes.erase(tree_ptr);\n        }\n\n        // iterate over all the nodes connected to this node, and add children\n        for (arc* a=tree_ptr->first; a; a=a->next) {\n          if (a->head->parent != TERMINAL && a->head->parent != ORPHAN &&\n              a->head->parent != NULL && a->head->parent->head == tree_ptr) {\n            // if the current arc points to a node which is a child\n            tree_queue.push(a->head);\n\n            if (node_normalized) {\n              tree_nodes.insert(a->head);\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // mark the relevant nodes active\n  set_active_normalization();\n}\n\ntemplate<typename captype, typename tcaptype, typename flowtype>\n  void Graph<captype, tcaptype, flowtype>::update_capacities(\n                                            const tcaptype* const prv_cap_s,\n                                            const tcaptype* const prv_cap_t,\n                                            const tcaptype* const new_cap_s,\n                                            const tcaptype* const new_cap_t,\n                                            const bool do_normalize_tree)\n{\n  NodeEditSet tree_nodes;\n\n  /* update unary capacity edges (t-links) */\n  for (node_id var_i = 0; var_i < node_num; ++var_i) {\n    // the previous unary capacities\n    tcaptype old_cap_diff = prv_cap_s[var_i] - prv_cap_t[var_i];\n\n    // the new unary capacities\n    tcaptype new_cap_diff = new_cap_s[var_i] - new_cap_t[var_i];\n    \n    // reparameterize the unary\n    reparam_unary(var_i, old_cap_diff, new_cap_diff);\n    \n    if (do_normalize_tree) {\n      if ((nodes[var_i].tr_cap > 0 && nodes[var_i].is_sink) ||\n          (nodes[var_i].tr_cap < 0 && !nodes[var_i].is_sink)) {\n        tree_nodes.insert(nodes + var_i);\n        add_to_changed_list(nodes + var_i);\n      }\n    } else {\n      mark_node(var_i);\n    }\n  }\n\n  if (do_normalize_tree)\n    normalize_tree(tree_nodes);\n}\n\n\ntemplate<typename captype, typename tcaptype, typename flowtype>\n  bool Graph<captype, tcaptype, flowtype>::check_tree_integrity(const std::string& filename) const\n{\n  //std::cout << \"Checking integrity of trees [should be run after maxflow() \"\n  //          << \"or transform_seed_trees()] - \" << filename << std::endl;\n\n  std::ofstream tree_out;\n  if (!filename.empty()) tree_out.open(filename.c_str(), std::ios::trunc);\n\n  /* vector to check if each node is accounted for */\n  std::vector<int> nodes_checked(node_num, 0);\n  int num_nodes_checked = 0;\n  tcaptype trcap;\n  node_id curr_i;\n\n  /* iterate over all nodes */\n  for (node_id i = 0; i < node_num; ++i) {\n    node* n_ptr = nodes + i;\n    const int curr_src_idx = n_ptr->src_origin_idx;\n\n    // skip node if its not a terminal node\n    if (n_ptr->parent == TERMINAL) {\n      if (!n_ptr->is_sink) {\n        // if src tree\n        if (!filename.empty()) tree_out << \"Source (\" << n_ptr->src_origin_idx << \") rooted at \";\n\n        // if src root node, then explore the whole tree\n        std::queue<node*> src_nodes;\n\n        curr_i = n_ptr - nodes;\n        src_nodes.push(n_ptr);\n\n        // this node shouldn't have been encountered before\n        if (nodes_checked[curr_i] != 0)\n          std::cerr << \"I have encountered node \" << curr_i << \" before\"\n                    << std::endl;\n        // check if the src_idx is a valid one\n        if (curr_src_idx == INVALID_SRC_ID) {\n          std::cerr << curr_i << \" should be part of some source \"\n                    << \" tree, not \" << INVALID_SRC_ID << std::endl;\n          nodes_checked[curr_i] = -1;\n        }\n\n        // BFS over whole tree\n        while (!src_nodes.empty()) {\n          n_ptr = src_nodes.front();\n          curr_i = n_ptr - nodes;\n          src_nodes.pop();\n\n          if (!filename.empty()) tree_out << curr_i << \", \";\n\n          // iterate over all the arcs of this node and search for children\n          for (arc* a=n_ptr->first; a; a=a->next) {\n            if (a->head->parent != TERMINAL && a->head->parent != ORPHAN &&\n                a->head->parent != NULL && a->head->parent->head == n_ptr) {\n              // if the current arc points to a node which is a child\n              node_id conn_i = (node_id)(a->head - nodes);\n              src_nodes.push(a->head);\n\n              // this node shouldn't have been encountered before\n              if (nodes_checked[conn_i] != 0)\n                std::cerr << \"I have encountered node \" << conn_i << \" before\"\n                          << std::endl;\n\n              // there should be positive residual on the edge connecting\n              // to the parent\n              if (a->r_cap <= 0) {\n                std::cerr << curr_i << \"->\" << conn_i << \" needs to have \"\n                          << \"positive residual capacity because the edge is\"\n                          << \" part of the source tree (\" << a->r_cap << \")\"\n                          << std::endl;\n                nodes_checked[conn_i] = -1;\n              }\n            }\n          }\n\n          trcap = get_trcap(curr_i);\n          // check if the node connecting to terminal has positive tr cap\n          if (trcap < 0) {\n            std::cerr << curr_i << \" cannot have residual capacity to the sink \"\n                      << \"(\" << trcap << \") since it is part of the src tree\"\n                      << std::endl;\n            nodes_checked[curr_i] = -1;\n          }\n          // check the id of the src origin idx\n          if (n_ptr->src_origin_idx != curr_src_idx) {\n            std::cerr << curr_i << \" should be part of the \" << curr_src_idx\n                      << \" source tree, not \" << n_ptr->src_origin_idx << std::endl;\n            nodes_checked[curr_i] = -1;\n          }\n          // check if the node is not sink\n          if (n_ptr->is_sink) {\n            std::cerr << curr_i << \" should not be part of the sink side of the cut\"\n                      << \" because it is part of the src tree\" << std::endl;\n            nodes_checked[curr_i] = -1;\n          }\n\n          // if node still good, mark it as having good integrity\n          if (nodes_checked[curr_i] == 0)\n            nodes_checked[curr_i] = 1;\n\n          ++num_nodes_checked;\n        }\n\n        if (!filename.empty()) tree_out << std::endl;\n      } else {\n        // if sink tree\n        if (!filename.empty()) tree_out << \"Sink rooted at \";\n\n        // if sink root node, then explore the whole tree\n        std::queue<node*> sink_nodes;\n\n        curr_i = n_ptr - nodes;\n        sink_nodes.push(n_ptr);\n\n        // this node shouldn't have been encountered before\n        if (nodes_checked[curr_i] != 0)\n          std::cerr << \"I have encountered node \" << curr_i << \" before\"\n                    << std::endl;\n        // check if the src_idx is invalid since we are sink\n        if (curr_src_idx != INVALID_SRC_ID) {\n          std::cerr << curr_i << \" should be part of sink tree, not \"\n                    << INVALID_SRC_ID << std::endl;\n          nodes_checked[curr_i] = -1;\n        }\n\n        // BFS over whole tree\n        while (!sink_nodes.empty()) {\n          n_ptr = sink_nodes.front();\n          curr_i = n_ptr - nodes;\n          sink_nodes.pop();\n\n          if (!filename.empty()) tree_out << curr_i << \", \";\n\n          // iterate over all the arcs of this node and search for children\n          for (arc* a=n_ptr->first; a; a=a->next) {\n            if (a->head->parent != TERMINAL && a->head->parent != ORPHAN &&\n                a->head->parent != NULL && a->head->parent->head == n_ptr) {\n              // if the current arc points to a node which is a child\n              node_id conn_i = (node_id)(a->head-nodes);\n              sink_nodes.push(a->head);\n\n              // this node shouldn't have been encountered before\n              if (nodes_checked[conn_i] != 0)\n                std::cerr << \"I have encountered node \" << conn_i << \" before\"\n                          << std::endl;\n\n              // there should be positive residual on the edge connecting\n              // to the parent\n              if (a->sister->r_cap <= 0) {\n                std::cerr << conn_i << \"->\" << curr_i << \" needs to have \"\n                          << \"positive residual capacity because the edge is\"\n                          << \" part of the sink tree (\" << a->r_cap << \")\"\n                          << std::endl;\n                nodes_checked[conn_i] = -1;\n              }\n            }\n          }\n\n          trcap = get_trcap(curr_i);\n          // check if the node connecting to terminal has negative tr cap\n          if (trcap > 0) {\n            std::cerr << curr_i << \" cannot have residual capacity to the src \"\n                      << \"(\" << trcap << \") since it is part of the sink tree\"\n                      << std::endl;\n            nodes_checked[curr_i] = -1;\n          }\n          // check the id of the src origin idx\n          if (n_ptr->src_origin_idx != curr_src_idx) {\n            std::cerr << curr_i << \" should be part of the \" << curr_src_idx\n                      << \" sink tree, not \" << n_ptr->src_origin_idx << std::endl;\n            nodes_checked[curr_i] = -1;\n          }\n          // check if the node is not sink\n          if (!n_ptr->is_sink) {\n            std::cerr << curr_i << \" should not be part of the src side of the cut\"\n                      << \" because it is part of the sink tree\" << std::endl;\n            nodes_checked[curr_i] = -1;\n          }\n\n          // if node still good, mark it as having good integrity\n          if (nodes_checked[curr_i] == 0)\n            nodes_checked[curr_i] = 1;\n\n          ++num_nodes_checked;\n        }\n\n        if (!filename.empty()) tree_out << std::endl;\n      }\n    }\n  }\n\n  /* all remaining nodes which are not part of some tree should be free */\n  for (node_id i=0; i < node_num; ++i) {\n    node* n_ptr = nodes + i;\n\n    if (nodes_checked[i] == 0) {\n      nodes_checked[i] = 1;\n\n      if (n_ptr->parent != NULL) {\n        std::cerr << i << \" should be a free node because it is not part of \"\n                  << \"any tree\" << std::endl;\n        nodes_checked[i] = -1;\n      }\n\n      tcaptype trcap = get_trcap(i);\n      if (trcap != 0) {\n        std::cerr << i << \" is a free node at the end of maxflow so should \"\n                  << \"have zero t residual capacity (\" << trcap << \")\"\n                  << std::endl;\n        nodes_checked[i] = -1;\n      }\n\n      // check if the src_idx is invalid since we are free\n      if (n_ptr->src_origin_idx != INVALID_SRC_ID) {\n        std::cerr << curr_i << \" should be free, not part of tree \"\n                  << INVALID_SRC_ID << std::endl;\n        nodes_checked[curr_i] = -1;\n      }\n\n      if (!filename.empty()) tree_out << \"Free node \" << i << std::endl;\n\n      ++num_nodes_checked;\n    }\n  }\n\n  int nodes_wrong = 0;\n  for (node_id i=0; i < node_num; ++i) {\n    if (nodes_checked[i] == -1)\n      ++nodes_wrong;\n  }\n\n  if (!filename.empty()) tree_out.close();\n\n  test_consistency();\n\n  gassert(nodes_wrong == 0, \"errors while checking tree integrity\");\n\n  return (nodes_wrong == 0);\n}\n\n#endif", "meta": {"hexsha": "bc122d918d742b300d382a11ce4a4733a70a4314", "size": 21006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/precomptrees-impl.hpp", "max_stars_repo_name": "ajmalk/RIGOR-cpp", "max_stars_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/precomptrees-impl.hpp", "max_issues_repo_name": "ajmalk/RIGOR-cpp", "max_issues_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/precomptrees-impl.hpp", "max_forks_repo_name": "ajmalk/RIGOR-cpp", "max_forks_repo_head_hexsha": "19300c2bd7d7a963d16ebd6b2544eb6e09967520", "max_forks_repo_licenses": ["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.1859296482, "max_line_length": 146, "alphanum_fraction": 0.572360278, "num_tokens": 5441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.025178841974912127, "lm_q1q2_score": 0.011510173153929645}}
{"text": "#pragma once\n\n#include <string>\n#include <memory>\n#include <string>\n#include <armadillo>\n\nclass Config;\nclass Physics;\nclass BatchTracking;\nclass Pipeline;\nclass GoverningEquationSolverBase;\nclass BoundaryConditions;\nclass TimeStep;\n\n/*!\n * \\brief The Solver class combines GoverningEquationSolver and BatchTracking\n * to advance the governing equations forward in time, and advect the\n * gas composition.\n *\n * It operates on Pipeline instances, and returns a copy of the input, with\n * updated flow, pressure, temperature, and composition (if batch tracking is\n * enabled).\n */\nclass Solver\n{\npublic:\n    //! Declared to avoid the inline compiler-generated default destructor.\n    virtual ~Solver();\n\n    /*!\n     * \\brief Construct from Config.\n     * \\param nGridPoints Number of grid points\n     * \\param config Config instance\n     */\n    Solver(\n            const arma::uword nGridPoints,\n            const Config& config);\n\n    /*!\n     * \\brief Construct from number of grid points and string to select\n     * discretizer.\n     * \\param nGridPoints Number of grid points.\n     * \\param energyEquation Type of energy equation (\"InternalEnergy\" or \"Enthalpy\")\n     * \\param relaxationFactors Relaxation factors, typically around 1.\n     * \\param toleranceType Tolerance type (\"absolute\" or \"relative\")\n     * \\param tolerances Convergence criteria\n     * \\param bruteForce Will always do maxIterations iterations and not check\n     * for convergence\n     * \\param maxIterations The maximum number of iterations to perform\n     */\n    explicit Solver(\n            const arma::uword nGridPoints,\n            const std::string& energyEquation = \"InternalEnergy\",\n            const arma::vec& relaxationFactors = {1, 1, 2/3.0},\n            const std::string& toleranceType = \"relative\",\n            const arma::vec& tolerances = {0.001, 0.001, 0.001},\n            const bool bruteForce = false,\n            const arma::uword maxIterations = 200);\n\n    /*!\n     * \\brief Solve the governing equations.\n     *\n     * \\see solveWithIterations()\n     *\n     * \\param dt Time step [s]\n     * \\param current Current pipeline state\n     * \\param boundaryConditions Boundary conditions with time stamp\n     * \\param physics Physics instance to update derived properties and heat transfer\n     * \\return Copy of current with updated properties.\n     */\n    virtual Pipeline solve(\n            const arma::uword dt,\n            const Pipeline& current,\n            const TimeStep& boundaryConditions,\n            const Physics& physics) const;\n\n    /*!\n     * \\brief Solve the governing equations.\n     *\n     * \\see solveWithIterations()\n     *\n     * \\param dt Time step [s]\n     * \\param current Current pipeline state\n     * \\param boundaryConditions Boundary conditions\n     * \\param physics Physics instance to update derived properties and heat transfer\n     * \\return Copy of current with updated properties.\n     */\n    virtual Pipeline solve(\n            const arma::uword dt,\n            const Pipeline& current,\n            const BoundaryConditions& boundaryConditions,\n            const Physics& physics) const;\n\n    /*!\n     * \\brief Check if differences between an old and a new state are within\n     * tolerances. This will either compare relative or absolute differences.\n     *\n     * This is used to see if the iteration over solution of the governing\n     * equations have converged, by comparing differences between the two last\n     * iterations.\n     *\n     * In the case of relative differences, we can run into issues if we have\n     * zero flow, so this is handled explicitly (temperature and pressure is\n     * never expected to reach zero in well-behaved simulations).\n     *\n     * \\param guess\n     * \\param previous\n     * \\param tolerances\n     * \\param toleranceType\n     * \\param relaxationFactors\n     * \\return\n     */\n    static arma::uword differencesWithinTolerance(\n            const Pipeline& guess,\n            const Pipeline& previous,\n            const arma::vec& tolerances,\n            const std::string& toleranceType,\n            const arma::vec& relaxationFactors);\n\n    /*!\n     * \\brief Solve the governing equations.\n     *\n     * TODO: Some more documentation here\n     *\n     * \\param dt Time step [s]\n     * \\param current Pipeline state\n     * \\param boundaryConditions Boundary conditions\n     * \\param physics Physics instance to update derived properties and heat transfer\n     * \\return Copy of current with updated properties.\n     */\n    Pipeline solveWithIterations(\n            const arma::uword dt,\n            const Pipeline& current,\n            const BoundaryConditions& boundaryConditions,\n            const Physics& physics) const;\n\n    //! Enable brute force solver, which always does m_maxIterations iterations.\n    void enableBruteForce();\n\n    //! Set max iterations.\n    void setMaxIterations(const arma::uword maxIterations);\n\n    //! Return the number of iterations performed during previous solution attempt\n    arma::uword nIterations() const { return m_nIterations; }\n\n    //! Get (const ref) relaxation factors\n    const arma::vec& relaxationFactors() const { return m_relaxationFactor;}\n    //! Get (const ref) tolerance type\n    const std::string& toleranceType() const { return m_toleranceType; }\n    //! Get (const ref) tolerances\n    const arma::vec& tolerances() const { return m_tolerances; }\n    //! Get (const ref) GoverningEquationSolver\n    const GoverningEquationSolverBase& governingEquationSolver() const { return *m_governingEquationSolver; }\n\nprivate:\n    //! Relaxation factors for each property (flow, pressure and temperature).\n    arma::vec m_relaxationFactor;\n\n    //! What kind of tolerance to use when checking convergence (\"relative\" or\n    //! \"absolute\").\n    std::string m_toleranceType;\n\n    //! Convergence tolerances for each property (flow, pressure and temperature).\n    arma::vec m_tolerances;\n\n//    arma::uword m_maxNumberOfIterations = 20; // not used\n//    bool m_hardLimitOnNumberOfIterations = true; // not used\n//    bool m_bruteForce = false; // not used\n\n    //! If we should use brute-force solving, which means not checking for\n    //! convergence, but always performing m_maxIterations iterations.\n    bool m_bruteForce;\n    //! The maximum number of iterations to perform, or (if m_bruteForce is\n    //! true) the exact number of iterations to perform.\n    arma::uword m_maxIterations;\n    //! The number of iterations performed during the previous solution attempt.\n    //! This is mutable, and is updated in Solver::solve().\n    mutable arma::uword m_nIterations = 0;\n\n    //! GoverningEquationSolver instance used for solving the governing equations.\n    std::unique_ptr<GoverningEquationSolverBase> m_governingEquationSolver;\n\n    //! BatchTracking instance used to advect composition in the pipeline.\n    std::unique_ptr<BatchTracking> m_compositionSolver;\n\n    /*!\n     * \\brief Private method for making GoverningEquationSolverBase instance\n     * from Config and nGridPoints.\n     * \\param config Config instance\n     * \\param nGridPoints Number of grid points\n     * \\return unique_ptr to GoverningEquationSolverBase\n     */\n    std::unique_ptr<GoverningEquationSolverBase> makeGoverningEquationSolver(\n            const arma::uword nGridPoints,\n            const Config& config);\n\n    /*!\n     * \\brief Private method for making GoverningEquationSolverBase from string\n     * and nGridPoints.\n     * \\param discretizer Discretizer type (\"InternalEnergy\" or \"Enthalpy\")\n     * \\param nGridPoints Number of grid points\n     * \\return unique_ptr to GoverningEquationSolverBase\n     */\n    std::unique_ptr<GoverningEquationSolverBase> makeGoverningEquationSolver(\n            const arma::uword nGridPoints,\n            const std::string& discretizer);\n};\n", "meta": {"hexsha": "c881fbac3e4294b24d33d24cbabb1cb18a05e0a6", "size": 7781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/solver.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/solver/solver.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/solver/solver.hpp", "max_forks_repo_name": "kewin1983/transient-pipeline-flow", "max_forks_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2296650718, "max_line_length": 109, "alphanum_fraction": 0.6832026732, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.025178838866062533, "lm_q1q2_score": 0.01151017173276035}}
{"text": "﻿// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-\n/* Author : willien at Tue Apr  1 14:50:50 2008\n * Generated by createNew\n */\n\n#include \"Utils/Utils.h\"\n\n#include <boost/shared_ptr.hpp>\n\n#include \"Utils/ItemGroupMap.h\"\n#include \"Utils/ItemGroupBuilder.h\"\n\n#include \"Numerics/DiscreteOperator/IDivKGradDiscreteOperator.h\"\n#include \"Numerics/DiscreteOperator/IAdvectionOperator.h\"\n\n#include \"NumericalModel/Utils/ICollector.h\"\n#include \"NumericalModel/Utils/IOp.h\"\n#include \"NumericalModel/Models/INumericalModel.h\"\n#include \"NumericalModel/Operators/INumericalModelVisitor.h\"\n#include \"NumericalModel/SubDomainModel/INumericalDomain.h\"\n#include \"NumericalModel/Algorithms/ITimeIntegrator.h\"\n#include \"NumericalModel/Algorithms/IIntegrator.h\"\n#include \"NumericalModel/Algorithms/ICouplingModelSolver.h\"\n\n#include \"NumericalModel/Algorithms/CouplingModelSolver/CouplingModelSolverT.h\"\n\n#include \"NumericalModel/Utils/BaseCollector.h\"\n#include \"NumericalModel/Utils/OpT.h\"\n#include \"NumericalModel/SubDomainModel/NumericalDomain/NumericalDomainImpl.h\"\n#include \"NumericalModel/SubDomainModel/SubDomainModelProperty.h\"\n#include \"NumericalModel/SubDomainModel/CollectorT.h\"\n#include \"NumericalModel/SubDomainModel/SDMBoundaryCondition.h\"\n#include \"NumericalModel/SubDomainModel/SDMBoundaryConditionMng.h\"\n#include \"NumericalModel/Models/ISubDomainModel.h\"\n\n#include \"TimeUtils/ITimeMng.h\"\n#include \"TimeUtils/ITimeStepMng.h\"\n\n#include \"Mesh/GroupCreator/IGroupCreator.h\"\n\n#include \"Appli/IAppServiceMng.h\"\n\n#include \"Mesh/Geometry/IGeometryMng.h\"\n\n#include \"ToyReactiveTransport/ToyReactiveTransportCouplageDtLocal/TypesDtLocal.h\"\n\n#include \"NumericalModel/Models/IIterativeTimeModel.h\"\n#include \"NumericalModel/Algorithms/TimeIntegrator/TimeIntegrator.h\"\n#include \"NumericalModel/Algorithms/Integrator/IntegratorT.h\"\n#include \"NumericalModel/FluxModel/FluxModel.h\"\n#include \"NumericalModel/FluxModel/FluxModelT.h\"\n\n#include \"ToyReactiveTransport/ToyReactiveTransportCouplageDtLocal/ToyReactiveTransportCouplageDtLocalModule.h\"\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nToyReactiveTransportCouplageDtLocalModule::~ToyReactiveTransportCouplageDtLocalModule()\n  {\n    delete m_global_collector;\n    delete m_reservoir_collector;\n    delete m_coarse_window_collector;\n    delete m_fine_window_collector;\n    delete m_time_integrator;\n    delete m_solver;\n    delete m_u_concentration_fine;\n    delete m_u_concentration_fine_tn;\n    delete m_u_concentration_coarse;\n    delete m_u_concentration_coarse_tn;\n    delete m_v_concentration_fine;\n    delete m_v_concentration_fine_tn;\n    delete m_v_concentration_coarse;\n    delete m_v_concentration_coarse_tn;\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid ToyReactiveTransportCouplageDtLocalModule::init()\n  {\n    info() << \"init\";\n    m_output_level = options()->outputLevel();\n\n    // lecture du choix de l'algo\n    m_computation_opt = options()->computationOpt();\n\n    IServiceMng* service_mng = subDomain()->serviceMng();\n    IAppServiceMng* app_service_mng = IAppServiceMng::instance(service_mng);\n\n    // lecture des sous domaines et schemas associes\n    m_dom_global = options()->DomainGlobal();\n    m_dom_global->init();\n    m_dom_reservoir = options()->DomainReservoir();\n    m_dom_reservoir->init();\n    m_dom_window = options()->DomainWindow();\n    m_dom_window->init();\n\n    // initialisation\n\n    //Domain management\n    initModelDomains();\n\n    //Time step management\n    //  IAppServiceMng* app_service_mng = IAppServiceMng::instance(subDomain()->serviceMng()) ;\n    m_coarse_time_mng = app_service_mng->find<ITimeMng> (true);\n    m_fine_time_mng = options()->fineTimeMng();\n    // m_fine_time_mng->init() ; /// pourquoi pas de init ? pris en charge dans les sous-boucles ?\n    m_fine_time_mng->setParent(m_coarse_time_mng);\n\n    m_time_step_mng = options()->timeStepMng();\n    m_time_step_mng->init();\n\n      {\n        //\n        // GLOBAL DOMAIN MODEL\n        //\n        IIterativeTimeModel* model =\n            dynamic_cast<IIterativeTimeModel*> (m_dom_global);\n        if (model)\n          model->setTimeMng(m_coarse_time_mng);\n\n        ISubDomainModel* sd_model =\n            dynamic_cast<ISubDomainModel*> (m_dom_global);\n        if (sd_model)\n          {\n            ISubDomainModel::FaceBoundaryConditionMng* bc_mng =\n                sd_model->getFaceBoundaryConditionMng();\n\n            setBoundaryCondition(sd_model, m_bc_group_g);\n\n            m_global_collector = new ISubDomainModel::Collector(\n                m_coarse_time_mng, bc_mng);\n            m_dom_global->prepare(m_global_collector, CoarseDtSeq);\n          }\n      }\n\n      {\n        //\n        // RESERVOIR DOMAIN MODEL\n        //\n        IIterativeTimeModel* model =\n            dynamic_cast<IIterativeTimeModel*> (m_dom_reservoir);\n        if (model)\n          model->setTimeMng(m_coarse_time_mng);\n\n        ISubDomainModel* sd_model =\n            dynamic_cast<ISubDomainModel*> (m_dom_reservoir);\n        if (sd_model)\n          {\n            ISubDomainModel::FaceBoundaryConditionMng* bc_mng =\n                sd_model->getFaceBoundaryConditionMng();\n\n            setBoundaryCondition(sd_model, m_bc_group_r);\n\n            /// Collecteur spécialisé (au delà de l'interface ICollector)\n            ISubDomainModel::Collector * reservoir_collector =\n                new ISubDomainModel::Collector(m_coarse_time_mng, bc_mng);\n            m_reservoir_collector = reservoir_collector;\n            reservoir_collector->setRealVar(\n                SubDomainModelProperty::UConcentration, &m_u_concentration); /// metier (UConcentration) dans interface ! utiliser ref du model métier itself\n\n            switch (m_computation_opt)\n              {\n            case TypesDtLocal::GlobalCoarseDt:\n              break;\n            case TypesDtLocal::GlobalFineDt:\n              break;\n            case TypesDtLocal::DFVF1:\n              {\n                // CREATE INTERFACE BOUNDARY CONDITION BC0 for interface boundary and OPERATORS to init them\n                // INTERFACE BOUNDARY CONDITION : OVERLAP DIRICHLET\n                m_r_bc_dirichlet = new ISubDomainModel::FaceBoundaryCondition(\n                    m_interface_id, SubDomainModelProperty::OverlapDirichlet,\n                    m_interface_id);\n                //Record to bc manager\n                bc_mng->addNew(m_r_bc_dirichlet, new ISubDomainModel::FaceBCOp(\n                    sd_model, &ISubDomainModel::initBoundaryCondition,\n                    m_r_bc_dirichlet));\n                m_r_bc_dirichlet->activate(true);\n\n                /// Ok connection à des actions requises par le collecteur\n                //\n                // initialisation avec la solution au temps DT precedent\n                // ------------------------------------------------------------------\n                m_reservoir_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::initCoarsePressure));\n                //\n                // Mise a jour de la cdt raccord en temps  Dirichlet sur le reservoir\n                // ------------------------------------------------------------------\n                m_reservoir_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computeDirichletOverlapForReservoir));\n                m_reservoir_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computeReservoirInterfaceFacePressure));\n                //\n                // Etape 3 : Resolution  dans reservoir avec une CL a pression imposee dans overlap\n                // --------------------------------------------------------------------------------\n                // mise a jour des CL\n                reservoir_collector->addBCUpdateOp(\n                    new ISubDomainModel::FaceBCOp(sd_model,\n                        &ISubDomainModel::initBoundaryCondition,\n                        m_r_bc_dirichlet)); /// utilise spécialisation du collecteur pour atteindre BC\n              }\n              break;\n            case TypesDtLocal::DFVF2:\n              {\n                // CREATE INTERFACE BOUNDARY CONDITION BC1 for interface boundary and OPERATORS to init them\n                m_r_bc_neumann = new ISubDomainModel::FaceBoundaryCondition(\n                    m_interface_id, SubDomainModelProperty::Neumann,\n                    m_interface_id);\n                //Record to bc manager\n                bc_mng->addNew(m_r_bc_neumann, new ISubDomainModel::FaceBCOp(\n                    sd_model, &ISubDomainModel::initBoundaryCondition,\n                    m_r_bc_neumann));\n                m_r_bc_neumann->activate(true);\n                //m_reservoir_collector->addOperator(ICollector::Start,new OpT<ToyReactiveTransportCouplageDtLocalModule>(this,&ToyReactiveTransportCouplageDtLocalModule::computePressureOnOverlap)) ;\n                m_reservoir_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computeAverageFluxOnOverlap));\n                m_reservoir_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::initCoarsePressure));\n                m_reservoir_collector->addOperator(\n                    ICollector::Finalize,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::updateCoarsePressureOnOverlap));\n                reservoir_collector->addBCUpdateOp(\n                    new ISubDomainModel::FaceBCOp(sd_model,\n                        &ISubDomainModel::initBoundaryCondition, m_r_bc_neumann)); /// acces à la spécialisation\n              }\n              break;\n            case TypesDtLocal::VFVF1:\n              m_r_bc_neumann->activate(true);\n              break;\n            case TypesDtLocal::VFVF2:\n              m_r_bc_dirichlet->activate(true);\n              break;\n              }\n            //\n            // Mise a jour des solutions sur le reservoir\n            // ------------------------------------------------------------------\n            if (m_output_level > 3)\n              m_reservoir_collector->addOperator(ICollector::FinalizeCompute,\n                  new OpT<ToyReactiveTransportCouplageDtLocalModule> (this,\n                      &ToyReactiveTransportCouplageDtLocalModule::writeoutput));\n\n            m_reservoir_collector->addOperator(\n                ICollector::Finalize,\n                new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                    this,\n                    &ToyReactiveTransportCouplageDtLocalModule::updatePressureFromReservoir));\n\n            m_dom_reservoir->prepare(m_reservoir_collector, CoarseDtSeq);\n            //m_dom_reservoir->addObs(new ReservoirInterfaceUpdater(this),CoarseDtSeq) ;\n          }\n      }\n      {\n        //\n        // WINDOW DOMAIN MODEL\n        //\n        IIterativeTimeModel* model =\n            dynamic_cast<IIterativeTimeModel*> (m_dom_window);\n        if (model)\n          model->setTimeMng(m_fine_time_mng);\n        ISubDomainModel* sd_model =\n            dynamic_cast<ISubDomainModel*> (m_dom_window);\n        if (sd_model)\n          {\n            ISubDomainModel::FaceBoundaryConditionMng* bc_mng =\n                sd_model->getFaceBoundaryConditionMng();\n\n            setBoundaryCondition(sd_model, m_bc_group_w);\n\n            ISubDomainModel::Collector* coarse_collector =\n                new ISubDomainModel::Collector(m_coarse_time_mng, bc_mng);\n            m_coarse_window_collector = coarse_collector;\n\n            ISubDomainModel::Collector* fine_collector =\n                new ISubDomainModel::Collector(m_fine_time_mng, bc_mng);\n            m_fine_window_collector = fine_collector;\n            m_time_integrator = new TimeIntegrator();\n            fine_collector->setTimeIntegrator(m_time_integrator);\n            fine_collector->activateTimeIntegrator(true);\n            fine_collector->setRealVar(SubDomainModelProperty::UConcentration,\n                &m_u_concentration);\n\n            switch (m_computation_opt)\n              {\n            case TypesDtLocal::GlobalCoarseDt:\n              break;\n            case TypesDtLocal::GlobalFineDt:\n              break;\n            case TypesDtLocal::DFVF1:\n              {\n                // CREATE INTERFACE BOUNDARY CONDITION BC1 for interface boundary and OPERATORS to init them\n                // INTERFACE BOUNDARY CONDITION : NEUNMANN\n                m_w_bc_neumann = new ISubDomainModel::FaceBoundaryCondition(\n                    m_interface_id, SubDomainModelProperty::Neumann,\n                    m_interface_id);\n                //Record to bc manager\n                bc_mng->addNew(m_w_bc_neumann, new ISubDomainModel::FaceBCOp(\n                    sd_model, &ISubDomainModel::initBoundaryCondition,\n                    m_w_bc_neumann));\n                m_w_bc_neumann->activate(true);\n                m_fine_window_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computePressureOnOverlap));\n                m_fine_window_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computeFluxOnOverlap));\n                m_fine_window_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::initFinePressure));\n                fine_collector->addBCUpdateOp(new ISubDomainModel::FaceBCOp(\n                    sd_model, &ISubDomainModel::initBoundaryCondition,\n                    m_w_bc_neumann));\n              }\n              break;\n            case TypesDtLocal::DFVF2:\n              {\n                // CREATE INTERFACE BOUNDARY CONDITION BC0 for interface boundary and OPERATORS to init them\n                m_w_bc_dirichlet = new ISubDomainModel::FaceBoundaryCondition(\n                    m_interface_id, SubDomainModelProperty::OverlapDirichlet,\n                    m_interface_id);\n                //Record to bc manager\n                bc_mng->addNew(m_w_bc_dirichlet, new ISubDomainModel::FaceBCOp(\n                    sd_model, &ISubDomainModel::initBoundaryCondition,\n                    m_w_bc_dirichlet));\n                m_w_bc_dirichlet->activate(true);\n                m_fine_window_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::initAverageFluxOnOverlap));\n                m_fine_window_collector->addOperator(\n                    ICollector::Start,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::initFinePressure));\n                m_fine_window_collector->addOperator(\n                    ICollector::StartCompute,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computeWindowDirichletCellPressure));\n                m_fine_window_collector->addOperator(\n                    ICollector::StartCompute,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computeWindowInterfaceFacePressure));\n                m_fine_window_collector->addOperator(\n                    ICollector::FinalizeCompute,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::computeReservoirPressureOnOverlap));\n                m_fine_window_collector->addOperator(\n                    ICollector::FinalizeCompute,\n                    new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                        this,\n                        &ToyReactiveTransportCouplageDtLocalModule::integrateFluxOnOverlap));\n                fine_collector->addBCUpdateOp(new ISubDomainModel::FaceBCOp(\n                    sd_model, &ISubDomainModel::initBoundaryCondition,\n                    m_w_bc_dirichlet));\n              }\n              break;\n            case TypesDtLocal::VFVF1:\n              m_fine_window_collector->addOperator(\n                  ICollector::StartCompute,\n                  new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                      this,\n                      &ToyReactiveTransportCouplageDtLocalModule::computeVFDirichletOverlapForWindow));\n              break;\n            case TypesDtLocal::VFVF2:\n              m_fine_window_collector->addOperator(\n                  ICollector::StartCompute,\n                  new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                      this,\n                      &ToyReactiveTransportCouplageDtLocalModule::computeVFDirichletOverlapForWindow));\n              break;\n              }\n            //\n            // Mise a jour des solutions du domain window\n            // ------------------------------------------------------------------\n\n            if (m_output_level > 3)\n              m_fine_window_collector->addOperator(ICollector::FinalizeCompute,\n                  new OpT<ToyReactiveTransportCouplageDtLocalModule> (this,\n                      &ToyReactiveTransportCouplageDtLocalModule::writeoutput));\n\n            m_fine_window_collector->addOperator(\n                ICollector::Finalize,\n                new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n                    this,\n                    &ToyReactiveTransportCouplageDtLocalModule::updatePressureFromWindow));\n\n            m_dom_window->prepare(m_coarse_window_collector, CoarseDtSeq);\n            m_dom_window->prepare(m_fine_window_collector, FineDtSeq);\n            //m_dom_window->addObs(new WindowInterfaceUpdater(this),FineDtSeq) ;\n          }\n      }\n      {\n        // OVERLAP DOMAIN\n        IAppServiceMng* app_service_mng = IAppServiceMng::instance(\n            subDomain()->serviceMng());\n\n        // Retrieve shared geometry service\n        IGeometryMng* geometry = app_service_mng->find<IGeometryMng> (true);\n        m_overlap_diff_flux_scheme = options()->overlapDiffFluxScheme();\n        m_overlap_diff_flux_scheme->init();\n        m_overlap_diff_flux_model = new DiffFluxModelType(m_overlap_domain,\n            m_overlap_diff_flux_scheme, geometry);\n        m_overlap_diff_flux_model->init();\n        m_overlap_adv_flux_scheme = options()->overlapAdvFluxScheme();\n        m_overlap_adv_flux_scheme->init();\n        m_overlap_adv_flux_model = new AdvFluxModelType(m_overlap_domain,\n            m_overlap_adv_flux_scheme, geometry);\n        m_overlap_adv_flux_model->init();\n        if (m_r_bc_dirichlet)\n          {\n            m_r_bc_dirichlet->setAdvFluxModel(m_overlap_adv_flux_model);\n            m_r_bc_dirichlet->setDiffFluxModel(m_overlap_diff_flux_model);\n          }\n        if (m_w_bc_dirichlet)\n          {\n            m_w_bc_dirichlet->setAdvFluxModel(m_overlap_adv_flux_model);\n            m_w_bc_dirichlet->setDiffFluxModel(m_overlap_diff_flux_model);\n          }\n      }\n    switch (m_computation_opt)\n      {\n    case TypesDtLocal::DFVF1:\n      {\n        IIntOp\n            * stop_criteria =\n                new IntOpT<ToyReactiveTransportCouplageDtLocalModule> (\n                    this,\n                    &ToyReactiveTransportCouplageDtLocalModule::updateConvergenceOnReservoirOverlap);\n        IOp* update_op = new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n            this, &ToyReactiveTransportCouplageDtLocalModule::updatePressureTN);\n        m_solver = new CouplingModelSolverT<\n            ToyReactiveTransportCouplageDtLocalModule> (this, stop_criteria,\n            update_op, options()->maxIter());\n        if (m_output_level > 0)\n          m_solver->setVerbose(true);\n      }\n      break;\n    case TypesDtLocal::DFVF2:\n      {\n        IIntOp\n            * stop_criteria =\n                new IntOpT<ToyReactiveTransportCouplageDtLocalModule> (\n                    this,\n                    &ToyReactiveTransportCouplageDtLocalModule::updateConvergenceOnWindowOverlap);\n        IOp* update_op = new OpT<ToyReactiveTransportCouplageDtLocalModule> (\n            this, &ToyReactiveTransportCouplageDtLocalModule::updatePressureTN);\n        m_solver = new CouplingModelSolverT<\n            ToyReactiveTransportCouplageDtLocalModule> (this, stop_criteria,\n            update_op, options()->maxIter());\n        if (m_output_level > 0)\n          m_solver->setVerbose(true);\n      }\n      break;\n    case TypesDtLocal::VFVF1:\n    case TypesDtLocal::VFVF2:\n    default:\n//      fatal() << \"Solver not yet defined\";\n      break;\n      }\n\n    //WINDOW VARIABLE MANAGEMENT\n\n    m_u_concentration_fine = new PartialVariableCellReal(VariableBuildInfo(\n        this, \"FineUConcentration\", m_window_group.itemFamily()->name(),\n        m_window_group.name(), IVariable::PPrivate | IVariable::PTemporary));\n    m_u_concentration_fine_tn = new PartialVariableCellReal(VariableBuildInfo(\n        this, \"FineUConcentrationTN\", m_window_group.itemFamily()->name(),\n        m_window_group.name(), IVariable::PPrivate | IVariable::PTemporary));\n    //RESERVOIR VARIABLE MANAGEMENT\n    m_u_concentration_coarse = new PartialVariableCellReal(VariableBuildInfo(\n        this, \"CoarseUConcentration\", m_reservoir_group.itemFamily()->name(),\n        m_reservoir_group.name(), IVariable::PPrivate | IVariable::PTemporary));\n    m_u_concentration_coarse_tn = new PartialVariableCellReal(\n        VariableBuildInfo(this, \"CoarseUConcentrationTN\",\n            m_reservoir_group.itemFamily()->name(), m_reservoir_group.name(),\n            IVariable::PPrivate | IVariable::PTemporary));\n    m_v_concentration_fine = new PartialVariableCellReal(VariableBuildInfo(\n        this, \"FineVConcentration\", m_window_group.itemFamily()->name(),\n        m_window_group.name(), IVariable::PPrivate | IVariable::PTemporary));\n    m_v_concentration_fine_tn = new PartialVariableCellReal(VariableBuildInfo(\n        this, \"FineVConcentrationTN\", m_window_group.itemFamily()->name(),\n        m_window_group.name(), IVariable::PPrivate | IVariable::PTemporary));\n    //RESERVOIR VARIABLE MANAGEMENT\n    m_v_concentration_coarse = new PartialVariableCellReal(VariableBuildInfo(\n        this, \"CoarseVConcentration\", m_reservoir_group.itemFamily()->name(),\n        m_reservoir_group.name(), IVariable::PPrivate | IVariable::PTemporary));\n    m_v_concentration_coarse_tn = new PartialVariableCellReal(\n        VariableBuildInfo(this, \"CoarseVConcentrationTN\",\n            m_reservoir_group.itemFamily()->name(), m_reservoir_group.name(),\n            IVariable::PPrivate | IVariable::PTemporary));\n\n    //OVERLAP VARIABLE MANAGEMENT\n    m_u_concentration_overlap.init(m_overlap_group);\n    m_old_u_concentration_overlap.init(m_overlap_group);\n    m_coarse_u_concentration_overlap.init(m_overlap_group);\n    m_coarse_u_concentration_overlap_tn.init(m_overlap_group);\n    m_v_concentration_overlap.init(m_overlap_group);\n    m_old_v_concentration_overlap.init(m_overlap_group);\n    m_coarse_v_concentration_overlap.init(m_overlap_group);\n    m_coarse_v_concentration_overlap_tn.init(m_overlap_group);\n    m_flux_overlap.init(m_interface_face_group);\n    m_flux_ratio.init(m_interface_face_group);\n    m_average_flux.init(m_interface_face_group);\n    m_integral_flux.init(m_interface_face_group);\n    /*\n     VariableBuildInfo overlap_flux_vb(this,\n     \"OverlapFlux\",\n     m_overlap_inner_group.itemFamily()->name(),\n     m_overlap_inner_group.name(),\n     IVariable::PPrivate|IVariable::PTemporary);\n     m_flux_overlap =  new PartialVariableFaceReal(overlap_flux_vb);\n     VariableBuildInfo average_flux_vb(this,\n     \"AverageFlux\",\n     m_overlap_inner_group.itemFamily()->name(),\n     m_overlap_inner_group.name(),\n     IVariable::PPrivate|IVariable::PTemporary);\n     m_average_flux =  new PartialVariableFaceReal(average_flux_vb);*/\n\n    //Initial state computation\n    computeInitialState();\n\n    //////////////////////////////\n    //    START COMPUTATION     //\n    //////////////////////////////\n    m_error = 0;\n    m_first_iter = true;\n    m_dom_global->start();\n    m_face_normal_flux_velocity.synchronize();\n    m_dom_reservoir->start();\n    m_face_normal_flux_velocity.synchronize();\n    m_dom_window->start();\n    m_face_normal_flux_velocity.synchronize();\n    \n\n    //OVERLAP FLUX MODEL\n      {\n        m_cell_permx.synchronize();\n        m_cell_permy.synchronize();\n        m_cell_permz.synchronize();\n        const CellGroup& internal_cells = m_overlap_domain->internalCells();\n        ENUMERATE_CELL(icell, internal_cells)\n          {\n            m_cell_perm_k[icell].x.x = m_cell_permx[icell];\n            ;\n            m_cell_perm_k[icell].y.y = m_cell_permy[icell];\n            ;\n            m_cell_perm_k[icell].z.z = m_cell_permz[icell];\n            ;\n          }\n        m_overlap_diff_flux_model->start(m_cell_perm_k);\n        m_face_normal_flux_velocity.synchronize();\n        m_overlap_adv_flux_model->start(m_face_normal_flux_velocity);\n      }\n\n    ENUMERATE_CELL(icell, m_window_group)\n      {\n        m_domainwindow[icell] = 1.;\n      }\n    ENUMERATE_CELL(icell, m_reservoir_group)\n      {\n        m_domainreservoir[icell] = 1.;\n      }\n    ENUMERATE_CELL(icell, m_overlap_group)\n      {\n        m_domainoverlap[icell] = 1.;\n      }\n\n  }\n\n/*---------------------------------------------------------------------------*/\n// Lecture des groupes de mailles : reservoir et window\n// puis construction du groupe de maille overlap et de tous les groupes de\n// faces et de nodes  necessaires aux calculs\n/*---------------------------------------------------------------------------*/\nvoid ToyReactiveTransportCouplageDtLocalModule::readGroup()\n  {\n    String window_str = options()->window();\n    String reservoir_str = options()->reservoir();\n\n    m_window_group = ownCells().itemFamily()->findGroup(window_str, false);\n    m_reservoir_group\n        = ownCells().itemFamily()->findGroup(reservoir_str, false);\n\n    //m_window_group = options()->window();\n    //m_reservoir_group = options()->reservoir();\n\n    // Construction d'un groupe des cells global\n    ItemGroupBuilder<Cell> cell_builderGlobal(allCells().mesh(),\n        \"GLOBALCELLGROUP\");\n    ItemGroupBuilder<Face> face_builderGlobal(allFaces().mesh(),\n        \"GLOBALFACEGROUP\");\n\n    // Construction d'un groupe des faces internes\n    ItemGroupBuilder<Face> iface_builderGlobal(allFaces().mesh(),\n        \"GLOBALINTERNALFACEGROUP\");\n    ItemGroupBuilder<Face> bface_builderGlobal(allFaces().mesh(),\n        \"GLOBALBOUNDARYFACEGROUP\");\n\n    // ======== //\n    //  WINDOW\n    // ======== //\n\n    // faces de la window\n    ItemGroupBuilder<Face> face_builder(m_window_group.mesh(),\n        \"WINDOWFACEGROUP\");\n    ENUMERATE_CELL(icell, m_window_group)\n      {\n        const Cell &cell = *icell;\n        cell_builderGlobal.add(cell);\n        face_builder.add(cell.faces()); // on ajoute ttes les faces de  la cellule\n        face_builderGlobal.add(cell.faces());\n      }\n    m_windowFaceGp = face_builder.buildGroup();\n\n    // maille interne a la zone window\n    ItemGroupMapT<Cell, Integer> isInnerCellW(m_window_group);\n    // face interne et de bord\n    ItemGroupBuilder<Face> b_window_builder(m_window_group.mesh(),\n        \"WINDOWBOUNDARYFACEGROUP\");\n    ItemGroupBuilder<Face> i_window_builder(m_window_group.mesh(),\n        \"WINDOWINTERNALFACEGROUP\");\n\n    ENUMERATE_FACE(iface, m_windowFaceGp)\n      {\n        const Face &face = *iface;\n        if (isInnerCellW.hasKey(face.frontCell()) and isInnerCellW.hasKey(\n            face.backCell()))\n          {\n            i_window_builder.add(face);\n          }\n        else\n          {\n            ARCANE_ASSERT( (isInnerCellW.hasKey(face.frontCell()) xor\n                    isInnerCellW.hasKey(face.backCell()) ),\n                (\"group Internal and edge computation\") );\n            b_window_builder.add(face);\n          }\n      }\n    m_window_boundary_face = b_window_builder.buildGroup();\n    m_window_internal_face = i_window_builder.buildGroup();\n\n    // ========== //\n    // RESERVOIR  //\n    // ========== //\n\n    // faces  du reservoir\n    ItemGroupBuilder<Face> faceR_builder(m_reservoir_group.mesh(),\n        \"RESERVOIRFACEGROUP\");\n\n    ENUMERATE_CELL(icell, m_reservoir_group)\n      {\n        const Cell &cell = *icell;\n        cell_builderGlobal.add(cell);\n        faceR_builder.add(cell.faces()); // on ajoute ttes les faces de  la cellule\n        face_builderGlobal.add(cell.faces());\n      }\n    m_reservoirFaceGp = faceR_builder.buildGroup();\n\n    // maille interne a la zone reservoir\n    ItemGroupMapT<Cell, Integer> isInnerCellR(m_reservoir_group);\n    ItemGroupBuilder<Face> b_reservoir_builder(m_reservoir_group.mesh(),\n        \"RESERVOIRBOUNDARYFACEGROUP\");\n    ItemGroupBuilder<Face> i_reservoir_builder(m_reservoir_group.mesh(),\n        \"RESERVOIRINTERNALFACEGROUP\");\n\n    ENUMERATE_FACE(iface, m_reservoirFaceGp)\n      {\n        const Face &face = *iface;\n        if (isInnerCellR.hasKey(face.frontCell()) and isInnerCellR.hasKey(\n            face.backCell()))\n          {\n            i_reservoir_builder.add(face);\n          }\n        else\n          {\n            ARCANE_ASSERT( (isInnerCellR.hasKey(face.frontCell()) xor\n                    isInnerCellR.hasKey(face.backCell()) ),\n                (\"Reservoir internal face group problem\") ) ;\n            b_reservoir_builder.add(face);\n          }\n      }\n\n    m_reservoir_boundary_face = b_reservoir_builder.buildGroup();\n    m_reservoir_internal_face = i_reservoir_builder.buildGroup();\n\n    //\n    // maillage global :\n    //\n    m_global_cell_group = cell_builderGlobal.buildGroup();\n    m_global_face_group = face_builderGlobal.buildGroup();\n    // Ensemble des cellules internes (Integer est une valeur fictive)\n    ItemGroupMapT<Cell, Integer> isInnerCellGlobal(m_global_cell_group);\n\n    ENUMERATE_FACE(iface, m_global_face_group)\n      {\n        const Face & face = *iface;\n        if (isInnerCellGlobal.hasKey(face.frontCell())\n            and isInnerCellGlobal.hasKey(face.backCell()))\n          {\n            iface_builderGlobal.add(face);\n          }\n        else\n          {\n            ARCANE_ASSERT((isInnerCellGlobal.hasKey(face.frontCell()) xor\n                    isInnerCellGlobal.hasKey(face.backCell())),\n                (\"Group edge computation\") );\n            bface_builderGlobal.add(face);\n          }\n      }\n    m_global_internal_face = iface_builderGlobal.buildGroup();\n    m_global_boundary_face = bface_builderGlobal.buildGroup();\n\n    // ======= //\n    // OVERLAP //\n    // ======= //\n\n    ItemGroupBuilder<Cell> overlap_builder(m_global_cell_group.mesh(),\n        \"OVERLAP\");\n\n    ENUMERATE_FACE(iface, m_global_internal_face)\n      {\n        const Face &face = *iface;\n        if ((isInnerCellR.hasKey(face.frontCell()) and isInnerCellW.hasKey(\n            face.backCell()) or (isInnerCellR.hasKey(face.backCell())\n            and isInnerCellW.hasKey(face.frontCell()))))\n          {\n            overlap_builder.add(face.frontCell());\n            overlap_builder.add(face.backCell());\n          }\n      }\n    m_overlap_group = overlap_builder.buildGroup();\n\n    // maintenant on construit a partir de l'overlap la zone de recouvrement\n\n    ItemGroupBuilder<Face> faceInter_builder(m_overlap_group.mesh(),\n        \"OVERLAPFACEGROUP\");\n\n    ENUMERATE_CELL(icell, m_overlap_group)\n      {\n        const Cell &cell = *icell;\n        faceInter_builder.add(cell.faces()); // on ajoute les cellules de la face overlap\n      }\n    m_overlapFaceGp = faceInter_builder.buildGroup();\n\n    // on veut  les faces internes de l'overlap = les faces de l'interface\n\n    // Ensemble des cellules internes (Integer est une valeur fictive)\n    ItemGroupMapT<Cell, Integer> isInnerCell(m_overlap_group);\n    // Construction d'un groupe des faces internes\n    ItemGroupBuilder<Face> iface_builder(m_overlapFaceGp.mesh(),\n        \"OVERLAPINNERFACEGROUP\");\n    ItemGroupBuilder<Face> interface_face_builder(m_overlapFaceGp.mesh(),\n        \"INTERFACEFACEGROUP\");\n    ItemGroupBuilder<Face> bface_builder(m_overlapFaceGp.mesh(),\n        \"OVERLAPBORDERFACEGROUP\");\n\n    ENUMERATE_FACE(iface, m_overlapFaceGp)\n      {\n        const Face &face = *iface;\n        /*if ((isInnerCellW.hasKey(face.frontCell()) and isInnerCellR.hasKey(face.backCell()))\n         or\n         (isInnerCellR.hasKey(face.frontCell()) and isInnerCellW.hasKey(face.backCell())))\n         {\n         iface_builder.add(face);\n         }\n         else if (not (isInnerCell.hasKey(face.frontCell()) xor\n         isInnerCell.hasKey(face.backCell())))\n         {\n         //            ARCANE_ASSERT( (isInnerCell.hasKey(face.frontCell()) xor\n         //                    isInnerCell.hasKey(face.backCell()) ),\n         //                (\"boundary face group problem\") );\n\n\n         bface_builder.add(face);\n         }*/\n        // OLD VERSION\n        if (isInnerCell.hasKey(face.frontCell()) and isInnerCell.hasKey(\n            face.backCell()))\n          {\n            iface_builder.add(face);\n            if ((isInnerCellW.hasKey(face.frontCell()) and isInnerCellR.hasKey(\n                face.backCell())) or (isInnerCellR.hasKey(face.frontCell())\n                and isInnerCellW.hasKey(face.backCell())))\n              {\n                interface_face_builder.add(face);\n              }\n          }\n        else\n          {\n            ARCANE_ASSERT( (isInnerCell.hasKey(face.frontCell()) xor\n                    isInnerCell.hasKey(face.backCell()) ),\n                (\"boundary face group problem\") );\n            bface_builder.add(face);\n          }\n      }\n\n    m_overlap_inner_group = iface_builder.buildGroup();\n    m_overlap_border_group = bface_builder.buildGroup();\n    m_interface_face_group = interface_face_builder.buildGroup();\n\n    // il faut ajouter reservoir+overlap\n    // OVERLAP + RESERVOIR\n    // CELL\n    ItemGroupBuilder<Cell> cell_builder(allCells().mesh(), \"OVER_RES\");\n\n    ENUMERATE_CELL(icell, m_reservoir_group)\n      {\n        const Cell &cell = *icell;\n        cell_builder.add(cell);\n      }\n\n    ENUMERATE_CELL(icell, m_overlap_group)\n      {\n        const Cell &cell = *icell;\n        cell_builder.add(cell);\n      }\n    m_overlap_reservoirGp = cell_builder.buildGroup();\n\n    // faces et nodes de reservoir+overlap\n    //\n    ItemGroupBuilder<Face> faceO_builder(m_overlap_reservoirGp.mesh(),\n        IMPLICIT_NAME);\n\n    ENUMERATE_CELL(icell, m_overlap_reservoirGp)\n      {\n        const Cell &cell = *icell;\n        faceO_builder.add(cell.faces()); // on ajoute ttes les faces de  la cellule\n      }\n    m_overlap_reservoirFaceGp = faceO_builder.buildGroup();\n\n    // a partir de m_overlap et m_window on veut recuperer les mailles interface pour\n    // la reservoir et la window qui auront des CL de Dirichlet\n\n    // maille interne a la zone reservoir\n    //\n    // maille interface pour la window : CL de Dirichlet\n    ItemGroupBuilder<Cell> interfaceW_cell_builder(m_overlap_group.mesh(),\n        IMPLICIT_NAME);\n    // maille interface pour le reservoir : CL de Dirichlet\n    ItemGroupBuilder<Cell> interfaceR_cell_builder(m_overlap_group.mesh(),\n        IMPLICIT_NAME);\n\n    ENUMERATE_CELL(icell, m_overlap_group)\n      {\n        const Cell &cell = *icell;\n        // la cellule cell de l'overlap  est  dans la window  , c'est donc une maille a BC pour la reservoir\n        if (isInnerCellW.hasKey(cell))\n          {\n            interfaceR_cell_builder.add(cell);\n          }\n        else\n          {\n            interfaceW_cell_builder.add(cell);\n          }\n      }\n    m_cell_interfaceW_group = interfaceW_cell_builder.buildGroup();\n    m_cell_interfaceR_group = interfaceR_cell_builder.buildGroup();\n\n    m_r_interface_cells.init(m_interface_face_group);\n    m_w_interface_cells.init(m_interface_face_group);\n    ENUMERATE_FACE(iface,m_interface_face_group)\n      {\n        const Face& face = *iface;\n        if (isInnerCellW.hasKey(face.frontCell()))\n          {\n            m_r_interface_cells[face] = face.frontCell();\n            m_w_interface_cells[face] = face.backCell();\n          }\n        else\n          {\n            m_w_interface_cells[face] = face.frontCell();\n            m_r_interface_cells[face] = face.backCell();\n          }\n      }\n\n    //\n    // CREATE USERDEFINED BOUNDARIES\n    //\n    ItemGroupMapT<Face, Integer> isBoundaryFaceW(m_window_boundary_face);\n    ItemGroupMapT<Face, Integer> isBoundaryFaceR(m_reservoir_boundary_face);\n    ItemGroupMapT<Face, Integer> isBoundaryFaceG(m_global_boundary_face);\n    // boucle sur les conditions aux limites\n    Integer nb_boundary_condition = options()->boundaryCondition.size();\n    m_bc_group_w.resize(nb_boundary_condition + 1);\n    m_bc_group_r.resize(nb_boundary_condition + 1);\n    m_bc_group_g.resize(nb_boundary_condition + 1);\n    for (int i = 0; i < nb_boundary_condition; ++i)\n      {\n        String face_group_str = options()->boundaryCondition[i]->surface();\n        FaceGroup face_group = ownFaces().itemFamily()->findGroup(\n            face_group_str, false);\n        m_bc_group_g[i] = face_group;\n        String w_name = face_group.name() + \"_W\" + i;\n        String r_name = face_group.name() + \"_R\" + i;\n        ItemGroupBuilder<Face> reservoir_builder(face_group.mesh(), r_name);\n        ItemGroupBuilder<Face> window_builder(face_group.mesh(), w_name);\n        ENUMERATE_FACE(iface,face_group)\n          {\n            const Face& face = *iface;\n            if (isBoundaryFaceW.hasKey(face))\n              {\n                window_builder.add(face);\n                isBoundaryFaceW[face] = 1;\n              }\n            else\n              {\n                reservoir_builder.add(face);\n                isBoundaryFaceR[face] = 1;\n              }\n            isBoundaryFaceG[face] = 1;\n          }\n        m_bc_group_w[i] = window_builder.buildGroup();\n        m_bc_group_r[i] = reservoir_builder.buildGroup();\n      }\n\n    //Mark interface boundary\n    ENUMERATE_FACE(iface,m_overlap_inner_group)\n      {\n        const Face& face = *iface;\n        if (isBoundaryFaceW.hasKey(face))\n          isBoundaryFaceW[face] = 1;\n        if (isBoundaryFaceR.hasKey(face))\n          isBoundaryFaceR[face] = 1;\n      }\n\n    //CREATE DEFAULT BOUNDARY GROUP ( not defined in previous boundary and interface\n    String w_name(\"defaultWINDOWBOUNDARY\");\n    ItemGroupBuilder<Face>\n        window_builder(m_window_boundary_face.mesh(), w_name);\n    ENUMERATE_FACE(iface,m_window_boundary_face)\n      {\n        const Face& face = *iface;\n        if (isBoundaryFaceW[face] == 0)\n          window_builder.add(face);\n      }\n    m_bc_group_w[nb_boundary_condition] = window_builder.buildGroup();\n    String r_name(\"DefaultRESERVOIRBOUNDARY\");\n    ItemGroupBuilder<Face> reservoir_builder(m_reservoir_boundary_face.mesh(),\n        r_name);\n    ENUMERATE_FACE(iface,m_reservoir_boundary_face)\n      {\n        const Face& face = *iface;\n        if (isBoundaryFaceR[face] == 0)\n          reservoir_builder.add(face);\n      }\n    m_bc_group_r[nb_boundary_condition] = reservoir_builder.buildGroup();\n    String g_name(\"DefaultGLOBALBOUNDARY\");\n    ItemGroupBuilder<Face>\n        global_builder(m_global_boundary_face.mesh(), g_name);\n    ENUMERATE_FACE(iface,m_global_boundary_face)\n      {\n        const Face& face = *iface;\n        if (isBoundaryFaceG[face] == 0)\n          global_builder.add(face);\n      }\n    m_bc_group_g[nb_boundary_condition] = global_builder.buildGroup();\n\n    m_interface_id = nb_boundary_condition + 2;\n  }\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid ToyReactiveTransportCouplageDtLocalModule::initModelDomains()\n  {\n    // lecture des groupes de mailles\n    readGroup();\n      {\n        ISubDomainModel::NumericalDomain\n            * domain =\n                dynamic_cast<ISubDomainModel::NumericalDomain*> (m_dom_global->getINumericalDomain());\n        if (domain)\n          {\n            domain->setName(\"GlobalDomain\");\n            domain->setInternalItems(m_global_cell_group,\n                m_global_internal_face);\n            domain->setBoundary(m_global_boundary_face);\n            for (Integer i = 0; i < m_bc_group_g.size(); i++)\n              if (m_bc_group_g[i].size() > 0)\n                domain->addFaceBoundary(m_bc_group_g[i], i);\n            //domain->setInterfaceItems(m_overlap_group, m_overlap_inner_group) ;\n\n//            if (m_output_level > 1)\n//              domain->printInfo();\n          }\n        else\n          fatal() << \"Numerical model should be a domain model\";\n      }\n\n      {\n        ISubDomainModel::NumericalDomain\n            * domain =\n                dynamic_cast<ISubDomainModel::NumericalDomain*> (m_dom_reservoir->getINumericalDomain());\n        if (domain)\n          {\n            domain->setName(\"ReservoirDomain\");\n            domain->setInternalItems(m_reservoir_group,\n                m_reservoir_internal_face);\n            domain->setBoundary(m_reservoir_boundary_face);\n            for (Integer i = 0; i < m_bc_group_r.size(); i++)\n              if (m_bc_group_r[i].size() > 0)\n                domain->addFaceBoundary(m_bc_group_r[i], i);\n            domain->addFaceBoundary(m_interface_face_group, m_interface_id);\n            domain->setInterfaceItems(m_overlap_group, m_overlap_inner_group,\n                m_cell_interfaceR_group);\n//            if (m_output_level > 1)\n//              domain->printInfo();\n          }\n        else\n          fatal() << \"Numerical model should be a domain model\";\n      }\n\n      {\n        ISubDomainModel::NumericalDomain\n            * domain =\n                dynamic_cast<ISubDomainModel::NumericalDomain*> (m_dom_window->getINumericalDomain()); /// y a aussi getNumericalDomain : conflict ?\n        if (domain)\n          {\n            domain->setName(\"WindowDomain\");\n            domain->setInternalItems(m_window_group, m_window_internal_face);\n            domain->setBoundary(m_window_boundary_face);\n            for (Integer i = 0; i < m_bc_group_w.size(); i++)\n              if (m_bc_group_w[i].size() > 0)\n                domain->addFaceBoundary(m_bc_group_w[i], i);\n            domain->addFaceBoundary(m_interface_face_group, m_interface_id);\n            domain->setInterfaceItems(m_overlap_group, m_overlap_inner_group,\n                m_cell_interfaceW_group);\n//            if (m_output_level > 1)\n//              domain->printInfo();\n          }\n        else\n          fatal() << \"Numerical model should be a domain model\";\n      }\n      {\n        m_overlap_domain = new ISubDomainModel::NumericalDomain(traceMng());\n        m_overlap_domain->setName(\"OverlapDomain\");\n        m_overlap_domain->setInternalItems(m_overlap_group,\n            m_overlap_inner_group);\n        m_overlap_domain->setBoundary(m_overlap_border_group);\n//        if (m_output_level > 1)\n//          m_overlap_domain->printInfo();\n      }\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::setBoundaryCondition(\n    ISubDomainModel* sd_model, Array<FaceGroup>& bc_group)\n  {\n    ISubDomainModel::FaceBoundaryConditionMng* bc_mng =\n        sd_model->getFaceBoundaryConditionMng();\n    // boucle sur les conditions aux limites\n    Integer nb_boundary_condition = options()->boundaryCondition.size();\n    for (int i = 0; i < nb_boundary_condition; ++i)\n      {\n        FaceGroup face_group = bc_group[i];\n        if (face_group.size() > 0)\n          {\n            Real valeurBC = options()->boundaryCondition[i]->value();\n            SubDomainModelProperty::eBoundaryConditionType typeBC =\n                options()->boundaryCondition[i]->type();\n\n            // CREATE BOUNDARY CONDITION BC0 for boundary 0 and OPERATORS to init them\n            ISubDomainModel::FaceBoundaryCondition* bc =\n                new ISubDomainModel::FaceBoundaryCondition(i, typeBC, i);\n            bc->setValue(valeurBC);\n            bc->activate(true);\n            //Record to bc manager\n            bc_mng->addNew(bc, new ISubDomainModel::FaceBCOp(sd_model,\n                &ISubDomainModel::initBoundaryCondition, bc));\n          }\n      }\n      {\n        Integer i = nb_boundary_condition;\n        FaceGroup face_group = bc_group[i];\n        if (face_group.size() > 0)\n          {\n            SubDomainModelProperty::eBoundaryConditionType typeBC =\n                SubDomainModelProperty::NullFlux;\n\n            // CREATE BOUNDARY CONDITION BC0 for boundary 0 and OPERATORS to init them\n            ISubDomainModel::FaceBoundaryCondition* bc =\n                new ISubDomainModel::FaceBoundaryCondition(i, typeBC, i);\n            bc->setValue(0);\n            //Record to bc manager\n            bc_mng->addNew(bc, new ISubDomainModel::FaceBCOp(sd_model,\n                &ISubDomainModel::initBoundaryCondition, bc));\n          }\n      }\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeInitialState()\n  {\n    _copy(m_global_cell_group, m_u_concentration_tn, m_u_concentration);\n    _copy(m_reservoir_group, *m_u_concentration_coarse, m_u_concentration);\n    _copy(m_reservoir_group, *m_u_concentration_coarse_tn, m_u_concentration);\n    _copy(m_window_group, *m_u_concentration_fine, m_u_concentration);\n    _copy(m_window_group, *m_u_concentration_fine_tn, m_u_concentration);\n    _copy(m_overlap_group, m_u_concentration_overlap, m_u_concentration);\n    _copy(m_overlap_group, m_old_u_concentration_overlap, m_u_concentration);\n    _copy(m_overlap_group, m_coarse_u_concentration_overlap, m_u_concentration);\n    _copy(m_overlap_group, m_coarse_u_concentration_overlap_tn,\n        m_u_concentration);\n\n    _copy(m_global_cell_group, m_v_concentration_tn, m_v_concentration);\n    _copy(m_reservoir_group, *m_v_concentration_coarse, m_v_concentration);\n    _copy(m_reservoir_group, *m_v_concentration_coarse_tn, m_v_concentration);\n    _copy(m_window_group, *m_v_concentration_fine, m_v_concentration);\n    _copy(m_window_group, *m_v_concentration_fine_tn, m_v_concentration);\n    _copy(m_overlap_group, m_v_concentration_overlap, m_v_concentration);\n    _copy(m_overlap_group, m_old_v_concentration_overlap, m_v_concentration);\n    _copy(m_overlap_group, m_coarse_v_concentration_overlap, m_v_concentration);\n    _copy(m_overlap_group, m_coarse_v_concentration_overlap_tn,\n        m_v_concentration);\n\n  }\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid ToyReactiveTransportCouplageDtLocalModule::compute()\n  {\n    info() << \"compute\";\n    //m_u_concentration_fine->synchronize();\n    //m_u_concentration_coarse->synchronize();\n    m_u_concentration.synchronize();\n    //m_v_concentration_fine->synchronize();\n    //m_v_concentration_coarse->synchronize();\n    m_v_concentration.synchronize();\n    m_permeability.synchronize();\n\n    switch (m_computation_opt)\n      {\n    case TypesDtLocal::GlobalCoarseDt:\n      computeGlobalDomainWithCoarseDt();\n      break;\n    case TypesDtLocal::GlobalFineDt:\n      computeGlobalDomainWithFineDt();\n      break;\n    case TypesDtLocal::DFVF1:\n      computeDFVF1();\n      break;\n    case TypesDtLocal::DFVF2:\n      computeDFVF2();\n      break;\n    case TypesDtLocal::VFVF1:\n      computeVFVF1();\n      break;\n    case TypesDtLocal::VFVF2:\n      computeVFVF2();\n      break;\n      }\n    m_first_iter = false;\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeDeltaT()\n  {\n    // Mise ? jour du pas de temps\n    if (m_coarse_time_mng->isCurrentTimeStepOk())\n      {\n        Real deltat = m_coarse_time_mng->getCurrentTimeStep();\n        bool timeStepOk = m_time_step_mng->manageTimeStep(&deltat);\n        m_coarse_time_mng->setNewTimeStep(deltat);\n        if (!timeStepOk)\n          m_coarse_time_mng->disableCurrentTimeStep();\n      }\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeGlobalDomainWithCoarseDt()\n  {\n    if (m_output_level > 0)\n      {\n        info() << \" Global domain resolution with large time step \";\n        info() << \"############################################\";\n        info() << \"          COARSE DT on GLOBAL MESH           \";\n        info() << \"############################################\";\n      }\n    //\n    // resolution a  m_coarse_dt;\n    //\n    m_dom_global->compute(CoarseDtSeq);\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeGlobalDomainWithFineDt()\n  {\n    //(choix == 0)\n    if (m_output_level > 0)\n      {\n        info() << \" Global domain resolution with small time step \";\n        info() << \"############################################\";\n        info() << \"           FINE DT on GLOBAL MESH           \";\n        info() << \"############################################\";\n      }\n    //\n    // resolution a m_fine_dt\n    //\n    m_dom_global->compute(FineDtSeq);\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n//\n// Methode 1 DF/VF\n//\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nvoid ToyReactiveTransportCouplageDtLocalModule::computeDFVF1()\n  {\n\n    // on sauvegarde le temps courant\n    if (m_output_level > 0)\n      info() << \" METHODE DF/VF 1\";\n    m_error = 0;\n    m_first_solver_step = true;\n    //\n    // etape 1 : resolution sur le maillage global pour un grand pas de temps\n    // ----------------------------------------------------------------------\n    if (m_output_level > 0)\n      info() << \" COMPUTE GLOBAL DOMAIN ON COARSE TIME STEP\";\n    //    m_dom_global->compute(CoarseDtSeq);\n\n    //\n    // etape 2 : integration en temps sur le maillage window pour des sous pas de temps\n    // --------------\n    if (m_output_level > 0)\n      info() << \" INTEGRATE WINDOW DOMAIN ON FINE TIME STEP\";\n    //    m_dom_window->compute(FineDtSeq);\n\n    if (m_output_level > 3)\n      writeoutput();\n    m_solver->solve(m_dom_reservoir, CoarseDtSeq, m_dom_window, FineDtSeq);\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeDFVF2()\n  {\n\n    // on sauvegarde le temps courant\n    if (m_output_level > 0)\n      info() << \" METHODE DF/VF 2\";\n    m_error = 0;\n    m_first_solver_step = true;\n    //\n    // etape 1 : resolution sur le maillage global pour un grand pas de temps\n    // ----------------------------------------------------------------------\n    if (m_output_level > 0)\n      info() << \" COMPUTE GLOBAL DOMAIN ON COARSE TIME STEP\";\n    //    initCoarsePressureOnOverlap();\n    //    m_dom_global->compute(CoarseDtSeq);\n    //    computePressureOnOverlap();\n    //    updateCoarsePressureOnOverlap();\n\n    if (m_output_level > 0)\n      info() << \" COUPLING SOLVER ON TWO SUBDOMAINS\";\n    if (m_output_level > 3)\n      writeoutput();\n    m_solver->solve(m_dom_window, FineDtSeq, m_dom_reservoir, CoarseDtSeq);\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n// on met a jour le flux sur les faces internes de la zone de recouvrement\n//\nvoid ToyReactiveTransportCouplageDtLocalModule::computeFluxOnOverlap()\n  {\n    ItemGroupMapT<Face, Real> adv_flux_overlap;\n    adv_flux_overlap.init(m_interface_face_group);\n    ItemGroupMapT<Face, Real> diff_flux_overlap;\n    diff_flux_overlap.init(m_interface_face_group);\n    m_overlap_adv_flux_model->computeFlux<ItemGroupMapT<Face, Real> ,\n        ItemGroupMapT<Cell, Real> > (adv_flux_overlap,\n        m_u_concentration_overlap, m_interface_face_group);\n    m_overlap_diff_flux_model->computeFlux<ItemGroupMapT<Face, Real> ,\n        ItemGroupMapT<Cell, Real> > (diff_flux_overlap,\n        m_u_concentration_overlap, m_interface_face_group);\n    //    Real local_time_step = m_fine_time_mng->getCurrentTimeStep();\n    //    Real global_time_step = m_coarse_time_mng->getCurrentTimeStep();\n    //    Real time_step_ratio = local_time_step / global_time_step;\n    ENUMERATE_FACE(iface,m_interface_face_group)\n      {\n        //        info() << \"=======================\";\n        //        info() << \"FLUXADV = \" << adv_flux_overlap[iface];\n        //        info() << \"FLUXDIF = \" << diff_flux_overlap[iface];\n        m_flux_ratio[iface] = adv_flux_overlap[iface]\n            * (adv_flux_overlap[iface] + diff_flux_overlap[iface]);\n        //        m_flux_overlap[iface] = (adv_flux_overlap[iface] + diff_flux_overlap[iface])/(1.+ time_step_ratio);\n        m_flux_overlap[iface] = (adv_flux_overlap[iface]\n            + diff_flux_overlap[iface]);\n      }\n    //    if (m_w_bc_neumann)\n    //      m_w_bc_neumann->setValues<ItemGroupMapT<Face, Real> ,\n    //          IDiscreteVarTypes::Scalar> (m_flux_overlap);\n    //    if (m_r_bc_neumann)\n    //      m_r_bc_neumann->setValues<ItemGroupMapT<Face, Real> ,\n    //          IDiscreteVarTypes::Scalar> (m_flux_overlap);\n    ItemGroupMapT<Cell, Integer> isInnerCellW(m_window_group);\n    ItemGroupMapT<Cell, Integer> isInnerCellR(m_reservoir_group);\n    if (m_w_bc_neumann)\n      {\n        ENUMERATE_FACE(iface,m_interface_face_group)\n          {\n            const Face& F = *iface;\n            if (isInnerCellW.hasKey(F.backCell()) && isInnerCellR.hasKey(F.frontCell()))\n              m_flux_overlap[iface] = m_flux_overlap[iface];\n            else\n              m_flux_overlap[iface] = -m_flux_overlap[iface];\n          }\n        m_w_bc_neumann->setValues<ItemGroupMapT<Face, Real> ,\n            IDiscreteVarTypes::Scalar> (m_flux_overlap);\n      }\n    if (m_r_bc_neumann)\n      {\n        ENUMERATE_FACE(iface,m_interface_face_group)\n          {\n            const Face& F = *iface;\n            if (isInnerCellR.hasKey(F.backCell()) && isInnerCellW.hasKey(F.frontCell()))\n              m_flux_overlap[iface] = m_flux_overlap[iface];\n            else\n              m_flux_overlap[iface] = -m_flux_overlap[iface];\n          }\n        m_r_bc_neumann->setValues<ItemGroupMapT<Face, Real> ,\n            IDiscreteVarTypes::Scalar> (m_flux_overlap);\n      }\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::initAverageFluxOnOverlap()\n  {\n    debug(Trace::Medium) << \"initAverageFluxOnOverlap\";\n    m_integral_length = 0;\n    ENUMERATE_FACE(iface,m_interface_face_group)\n      {\n        m_average_flux[iface] = 0.;\n        m_integral_flux[iface] = 0.;\n      }\n  }\nvoid ToyReactiveTransportCouplageDtLocalModule::integrateFluxOnOverlap()\n  {\n    debug(Trace::Medium) << \"integrateFluxOnOverlap\";\n    ItemGroupMapT<Face, Real> adv_flux_overlap;\n    adv_flux_overlap.init(m_interface_face_group);\n    ItemGroupMapT<Face, Real> diff_flux_overlap;\n    diff_flux_overlap.init(m_interface_face_group);\n    m_overlap_adv_flux_model->computeFlux<ItemGroupMapT<Face, Real> ,\n        ItemGroupMapT<Cell, Real> > (adv_flux_overlap,\n        m_u_concentration_overlap, m_interface_face_group);\n    m_overlap_diff_flux_model->computeFlux<ItemGroupMapT<Face, Real> ,\n        ItemGroupMapT<Cell, Real> > (diff_flux_overlap,\n        m_u_concentration_overlap, m_interface_face_group);\n    Real local_time_step = m_fine_time_mng->getCurrentTimeStep();\n    //    Real global_time_step = m_coarse_time_mng->getCurrentTimeStep();\n    //    Real time_step_ratio = local_time_step / global_time_step;\n    ENUMERATE_FACE(iface,m_interface_face_group)\n      {\n        //        info() << \"=======================\";\n        //        info() << \"FLUXADV = \" << adv_flux_overlap[iface];\n        //        info() << \"FLUXDIF = \" << diff_flux_overlap[iface];\n        m_flux_ratio[iface] = adv_flux_overlap[iface]\n            * (adv_flux_overlap[iface] + diff_flux_overlap[iface]);\n        //        m_flux_overlap[iface] = (adv_flux_overlap[iface] + diff_flux_overlap[iface])/(1.+ time_step_ratio);\n        m_flux_overlap[iface] = (adv_flux_overlap[iface]\n            + diff_flux_overlap[iface]);\n      }\n    info() << \" old integral length = \" << m_integral_length << \" adding \"\n        << local_time_step;\n    m_integral_length += local_time_step;\n    info() << \" new integral length = \" << m_integral_length;\n    ENUMERATE_FACE(iface,m_interface_face_group)\n      {\n        m_integral_flux[iface] += m_flux_overlap[iface] * local_time_step;\n        info() << \"LOCAL TIME STEP = \" << local_time_step;\n        info() << \"m_flux_overlap =  \" << m_flux_overlap[iface];\n      }\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeAverageFluxOnOverlap()\n  {\n    debug(Trace::Medium) << \"computeAverageFluxOnOverlap\";\n    Real coarse_time_step = m_coarse_time_mng->getCurrentTimeStep();\n    if (fabs(m_integral_length - coarse_time_step) > 1e-12)\n      {\n        info() << \" m_integral_length \" << m_integral_length;\n        info() << \" coarse_time_step \" << coarse_time_step;\n        info() << \" integral difference \" << m_integral_length\n            - coarse_time_step;\n        fatal() << \"Inconsistent integral length\";\n      }\n        ENUMERATE_FACE(iface,m_interface_face_group)\n          {\n            m_average_flux[iface] = m_integral_flux[iface] / coarse_time_step;\n          }\n        \n    // ATTENTION : Flux est stocké selon l'orientation de la normale du point de vue global\n    // dans m_average_flux.\n    // Par contre, dans les sous-modèles, les flux sont toujours stockés\n    // dans la direction sortant pour une face de bord\n        \n        \n    ItemGroupMapT<Cell, Integer> isInnerCellW(m_window_group);\n    ItemGroupMapT<Cell, Integer> isInnerCellR(m_reservoir_group);\n    if (m_w_bc_neumann)\n      {\n        ENUMERATE_FACE(iface,m_interface_face_group)\n          {\n            const Face& F = *iface;\n            if (isInnerCellW.hasKey(F.backCell()) && isInnerCellR.hasKey(F.frontCell()))\n              m_average_flux[iface] = m_average_flux[iface];\n            else\n              m_average_flux[iface] = -m_average_flux[iface];\n          }\n        m_w_bc_neumann->setValues<ItemGroupMapT<Face, Real> ,\n            IDiscreteVarTypes::Scalar> (m_average_flux);\n      }\n    if (m_r_bc_neumann)\n      {\n        ENUMERATE_FACE(iface,m_interface_face_group)\n          {\n            const Face& F = *iface;\n            if (isInnerCellR.hasKey(F.backCell()) && isInnerCellW.hasKey(F.frontCell()))\n              m_average_flux[iface] = m_average_flux[iface];\n            else\n              m_average_flux[iface] = -m_average_flux[iface];\n          }\n        m_r_bc_neumann->setValues<ItemGroupMapT<Face, Real> ,\n            IDiscreteVarTypes::Scalar> (m_average_flux);\n      }\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nvoid ToyReactiveTransportCouplageDtLocalModule::computePressureOnOverlap()\n  {\n    info() << \" computePressureOnOverlap \";\n    _copy(m_overlap_group, m_u_concentration_overlap, m_u_concentration);\n    _copy(m_overlap_group, m_v_concentration_overlap, m_v_concentration);\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeWindowPressureOnOverlap()\n  {\n    info() << \"=========INIT COMPUTEWINDOWPRESSUREOVERLAP\";\n    _copy2(m_cell_interfaceW_group, m_u_concentration_overlap,\n        m_u_concentration);\n    _copy2(m_cell_interfaceW_group, m_v_concentration_overlap,\n        m_v_concentration);\n\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeReservoirPressureOnOverlap()\n  {\n    info() << \" computeReservoirPressureOnOverlap \";\n    _copy2(m_cell_interfaceR_group, m_u_concentration_overlap,\n        m_u_concentration);\n    _copy2(m_cell_interfaceR_group, m_v_concentration_overlap,\n        m_v_concentration);\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nvoid ToyReactiveTransportCouplageDtLocalModule::initCoarsePressureOnOverlap()\n  {\n    info() << \"=========INIT INITCOARSEPRESSUREONOVERLAP\";\n    _copy(m_overlap_group, m_coarse_u_concentration_overlap,\n        m_coarse_u_concentration_overlap_tn);\n    _copy(m_overlap_group, m_coarse_v_concentration_overlap,\n        m_coarse_v_concentration_overlap_tn);\n  }\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid ToyReactiveTransportCouplageDtLocalModule::updateCoarsePressureOnOverlap()\n  {\n    info() << \"=========INIT UPDATECOARSEPRESSUREONOVERLAP\";\n    _copysave(m_overlap_group, m_coarse_u_concentration_overlap_tn,\n        m_coarse_u_concentration_overlap, m_u_concentration);\n    _copysave(m_overlap_group, m_coarse_v_concentration_overlap_tn,\n        m_coarse_v_concentration_overlap, m_v_concentration);\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nvoid ToyReactiveTransportCouplageDtLocalModule::restore()\n  {\n    info() << \"restore\";\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeInterfaceFacePressure(\n    const FaceGroup& group, const ItemGroupMapT<Cell, Real>& u_concentration,\n    ItemGroupMapT<Face, Cell>& exterior_cells,\n    ItemGroupMapT<Face, Real>& face_u_concentration)\n  {\n    info() << \"computeInterfaceFacePressure\";\n    ENUMERATE_FACE(iface, group)\n      {\n        face_u_concentration[iface] = u_concentration[exterior_cells[iface]];\n      }\n  }\nvoid ToyReactiveTransportCouplageDtLocalModule::computeReservoirInterfaceFacePressure()\n  {\n    info() << \"computeReservoirInterfaceFacePressure\";\n    ItemGroupMapT<Face, Real> face_u_concentration;\n    face_u_concentration.init(m_interface_face_group);\n    computeInterfaceFacePressure(m_interface_face_group,\n        m_u_concentration_overlap, m_r_interface_cells, face_u_concentration);\n    m_r_bc_dirichlet->setValues<ItemGroupMapT<Face, Real> ,\n        IDiscreteVarTypes::Scalar> (face_u_concentration);\n  }\nvoid ToyReactiveTransportCouplageDtLocalModule::computeWindowInterfaceFacePressure()\n  {\n    info() << \"computeWindowInterfaceFacePressure\";\n    ItemGroupMapT<Face, Real> face_u_concentration;\n    face_u_concentration.init(m_interface_face_group);\n    computeInterfaceFacePressure(m_interface_face_group,\n        m_u_concentration_overlap, m_w_interface_cells, face_u_concentration);\n    m_w_bc_dirichlet->setValues<ItemGroupMapT<Face, Real> ,\n        IDiscreteVarTypes::Scalar> (face_u_concentration);\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::updatePressureFromWindow()\n  {\n    info() << \"=========INIT UPDATEPRESSUREFROMWINDOW\";\n    //    writeoutput();\n    _copy(m_window_group, *m_u_concentration_fine, m_u_concentration);\n    _copy(m_overlap_group, m_old_u_concentration_overlap, m_u_concentration);\n    _copy(m_window_group, *m_v_concentration_fine, m_v_concentration);\n    _copy(m_overlap_group, m_old_v_concentration_overlap, m_v_concentration);\n    //    writeoutput();\n  }\nvoid ToyReactiveTransportCouplageDtLocalModule::updatePressureFromReservoir()\n  {\n    info() << \"=========INIT UPDATEPRESSUREFROMRESERVOIR\";\n    //    writeoutput();\n    _copy(m_reservoir_group, *m_u_concentration_coarse, m_u_concentration);\n    _copy(m_overlap_group, m_old_u_concentration_overlap, m_u_concentration);\n    _copy(m_reservoir_group, *m_v_concentration_coarse, m_v_concentration);\n    _copy(m_overlap_group, m_old_v_concentration_overlap, m_v_concentration);\n    //    writeoutput();\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::updatePressureTN()\n  {\n    info() << \"=========INIT UPDATEPRESSURETN\";\n    _copy(m_global_cell_group, m_u_concentration_tn, m_u_concentration);\n    _copy(m_window_group, *m_u_concentration_fine_tn, m_u_concentration);\n    _copy(m_reservoir_group, *m_u_concentration_coarse_tn, m_u_concentration);\n    _copy(m_global_cell_group, m_v_concentration_tn, m_v_concentration);\n    _copy(m_window_group, *m_v_concentration_fine_tn, m_v_concentration);\n    _copy(m_reservoir_group, *m_v_concentration_coarse_tn, m_v_concentration);\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::initFinePressure()\n  {\n    info() << \"=========INIT INITFINEPRESSURE\";\n    //    writeoutput();\n    _copy(m_window_group, m_u_concentration, *m_u_concentration_fine_tn);\n    _copy(m_window_group, m_v_concentration, *m_v_concentration_fine_tn);\n    //    writeoutput();\n  }\nvoid ToyReactiveTransportCouplageDtLocalModule::initCoarsePressure()\n  {\n    info() << \"=========INIT INITCOARSEPRESSURE\";\n    //    writeoutput();\n    _copy(m_reservoir_group, m_u_concentration, *m_u_concentration_coarse_tn);\n    _copy(m_reservoir_group, m_v_concentration, *m_v_concentration_coarse_tn);\n    //    writeoutput();\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeWindowDirichletCellPressure()\n  {\n    if (m_first_solver_step)\n      {\n        m_val_limit1.resize(m_cell_interfaceW_group.size());\n        m_val_limit2.resize(m_cell_interfaceW_group.size());\n        m_teta = 1.;\n      }\n    computeDirichletCellPressure(m_val_limit1, m_val_limit2,\n        m_cell_interfaceW_group);\n  }\nvoid ToyReactiveTransportCouplageDtLocalModule::computeReservoirDirichletCellPressure()\n  {\n    if (m_first_solver_step)\n      {\n        m_val_limit1.resize(m_cell_interfaceR_group.size());\n        m_val_limit2.resize(m_cell_interfaceR_group.size());\n        m_teta = 1.;\n      }\n    computeDirichletCellPressure(m_val_limit1, m_val_limit2,\n        m_cell_interfaceR_group);\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeDirichletCellPressure(\n    Array<Real>& Value_Limit1, Array<Real>& Value_Limit2,\n    const CellGroup& interface_group)\n  {\n    Real coarse_current_time = m_coarse_time_mng->getCurrentTime();\n    Real coarse_deltat = m_coarse_time_mng->getCurrentTimeStep();\n    Real fine_current_time = m_fine_time_mng->getCurrentTime();\n\n    //ATTENTION NE MARCHE PAS AVEC LES VARIABLES PARTIELS\n    Integer ival = 0;\n    ENUMERATE_CELL(icell, interface_group)\n      {\n        const Cell& cell = *icell;\n        Value_Limit1[ival] = m_coarse_u_concentration_overlap_tn[cell];\n        Value_Limit2[ival] = m_u_concentration[icell];\n        m_u_concentration_overlap[cell] = Value_Limit1[ival]\n            + (Value_Limit2[ival] - Value_Limit1[ival]) * ((fine_current_time\n                - coarse_current_time) / coarse_deltat + 1.);\n        ival++;\n      }\n    if (m_first_solver_step)\n      {\n        m_teta = 1.0;\n        m_first_solver_step = false;\n      }\n    /* OLD VERSION\n     //ATTENTION NE MARCHE PAS AVEC LES VARIABLES PARTIELS\n     Integer ival = 0;\n     ENUMERATE_CELL(icell, interface_group)\n     {\n     const Cell& cell = *icell ;\n     // demi somme des valeurs aux temps N et N-1\n     m_old_pressure_overlap[icell] = Value_Limit2[ival];\n     Value_Limit1[ival] = m_coarse_pressure_overlap_tn[cell];\n     Value_Limit2[ival] = m_teta * m_pressure[icell] + (1. - m_teta)\n     *Value_Limit2[ival];\n     m_pressure_overlap[cell] = Value_Limit2[ival];\n     info()<<\"OVERLAP DIRICHLET PRESSURE\"<<m_pressure_overlap[cell];\n     ival++;\n     }\n     if(m_first_solver_step)\n     {\n     m_teta = 0.5 ;\n     m_first_solver_step = false ;\n     }*/\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n//\n// Schema  VF en Temps et VF en Espace pour la methode des pas de temps locaux 1\n//\n//         Window = CL en Flux et Reservoir CL en Pression\n//\nvoid ToyReactiveTransportCouplageDtLocalModule::computeVFVF1()\n  {\n    fatal() << \"Not yet implemented\";\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n//\n// Methode 2 VF/VF\n//\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeVFVF2()\n  {\n    fatal() << \"Not yet implemented\";\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeDirichletOverlapForReservoir()\n  {\n    Real teta = 1.;\n    if (m_first_solver_step)\n      {\n        teta = 1.0;\n        m_first_solver_step = false;\n      }\n    // on veut recuperer la pression a imposer sur la zone reservoir\n    ENUMERATE_CELL(icell, m_cell_interfaceR_group)\n      {\n        const Cell &cell = *icell;\n        m_u_concentration_overlap[cell] = (1. - teta)\n            * m_u_concentration_overlap[cell] + teta * m_u_concentration[icell]; //  m_pressure[icell];\n      }\n    /* OLD VERSION\n     Real teta =0.5;\n     // on veut recuperer la pression a imposer sur la zone reservoir\n     ENUMERATE_CELL(icell, m_cell_interfaceR_group)\n     {\n     const Cell &cell = *icell;\n     m_old_pressure_overlap[cell] = m_pressure_overlap[cell];\n     m_pressure_overlap[cell] = (1.-teta) * m_old_pressure_overlap[cell]\n     + teta*m_pressure[icell]; //  m_pressure[icell];\n     }*/\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n// calcul du critere de convergence de l'algorithme\n//\nInteger ToyReactiveTransportCouplageDtLocalModule::updateConvergenceOnReservoirOverlap()\n  {\n    Integer cv = updateConvergenceOnOverlap(m_cell_interfaceR_group);\n    return 1 - cv;\n  }\n\nInteger ToyReactiveTransportCouplageDtLocalModule::updateConvergenceOnWindowOverlap()\n  {\n    Integer cv = updateConvergenceOnOverlap(m_cell_interfaceW_group);\n    return 1 - cv;\n  }\n\nInteger ToyReactiveTransportCouplageDtLocalModule::updateConvergenceOnOverlap(\n    const CellGroup& cell_group)\n  {\n    Integer CV = 0;\n    Real stopping_criteria = options()->stoppingCriteria();\n    Real Val = -10000.;\n    Real ValTmp1 = -10000.;\n    Real ValTmp2 = -10000.;\n    ENUMERATE_CELL(icell, cell_group)\n      {\n        const Cell& cell = *icell;\n        ValTmp1 = m_u_concentration_overlap[cell] - m_u_concentration[icell];\n        ValTmp2 = m_old_u_concentration_overlap[cell]\n            - m_u_concentration_overlap[cell];\n        if (math::abs(ValTmp2) > Val)\n          {\n            Val = math::abs(ValTmp2);\n          }\n      }\n    if (m_output_level > 0)\n      {\n        info();\n        info() << \"-------------------------------------------------\";\n        info() << \"| Solver convergence criteria : \" << Val;\n        info() << \"-------------------------------------------------\";\n        info();\n      }\n    if (Val <= stopping_criteria)\n      CV = 1;\n    return CV;\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nvoid ToyReactiveTransportCouplageDtLocalModule::initPressureOnReservoir()\n  {\n    info() << \"=========INIT PRESSUREONRESERVOIR\";\n    _copy(m_reservoir_group, m_u_concentration, *m_u_concentration_coarse_tn);\n    _copy(m_reservoir_group, m_v_concentration, *m_v_concentration_coarse_tn);\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nvoid ToyReactiveTransportCouplageDtLocalModule::initPressureOnWindow()\n  {\n    info() << \"=========INIT PRESSUREONWINDOW\";\n    _copy(m_window_group, m_u_concentration, *m_u_concentration_fine_tn);\n    _copy(m_window_group, m_v_concentration, *m_v_concentration_fine_tn);\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nInteger ToyReactiveTransportCouplageDtLocalModule::updateVFConvergenceOnOverlap(\n    const CellGroup& cell_group)\n  {\n    Integer CV = 0;\n    Real stopping_criteria = options()->stoppingCriteria();\n    Real Val = -10000.;\n    Real ValTmp1 = -10000.;\n    Real ValTmp2 = -10000.;\n    ENUMERATE_CELL(icell, cell_group)\n      {\n        const Cell& cell = *icell;\n        ValTmp1 = math::abs(m_u_concentration_overlap[cell]\n            - m_u_concentration[icell]);\n        ValTmp2 = math::abs(m_old_u_concentration_overlap[cell]\n            - m_u_concentration_overlap[cell]);\n        if (ValTmp2 > Val)\n          {\n            Val = ValTmp2;\n          }\n      }\n    if (Val <= stopping_criteria)\n      CV = 1;\n    return CV;\n  }\n\n/*-----------------------------------------------------------------------------------------*/\n/*-----------------------------------------------------------------------------------------*/\n\n//\n//\nvoid ToyReactiveTransportCouplageDtLocalModule::computeVFDirichletOverlapForReservoir()\n  {\n    Real teta = 0.5;\n    // on veut recuperer la pression a imposer sur la zone reservoir\n    //\n    //\n    ENUMERATE_CELL(icell, m_cell_interfaceR_group)\n      {\n        const Cell &cell = *icell;\n        //florian m_old_pressure_overlap[cell] = m_pressure_overlap[cell];\n        m_u_concentration_overlap[cell] = (1. - teta)\n            * m_old_u_concentration_overlap[cell] + teta\n            * m_average_u_concentration[cell]; //  m_pressure[icell];\n      }\n  }\n//\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n//\n// calcul de la condition de raccord de type Dirichlet au cours des petits pas de temps\n// entre 2 valeurs limites données par la resolution reservoir a grand pas de temps\n//\n// _____|______________________ Val_Lim2   en T2  Val_Lim2 = 1/2(3*Val_X - Val_A)\n//\n//   x  | x\n//   x  | x\n//   x  | x\n//   x  | x\n//   x  | x          X                     en T1 + 1/2 DT\n//   x  | x\n//   x  | x\n//   x  | x\n// _____|______________________ Val_Lim1   en T1  Val_Lim1 = 1/2(Val_A + Val_X)\n//\n//   x  | x\n//   x  | x\n//   x  | x\n//   x  | x\n//   x  | x          A                     en T0 + 1/2 DT\n//   x  | x\n//   x  | x\n//   x  | x\n//\n//\n//   CL(x) = Val_Lim1 + (Val_Lim2 - Val_Lim1) * (current=_time/dt_local)\n//\n//\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeVFDirichletOverlapForWindow()\n  {\n    Real current_time = m_fine_time_mng->getCurrentTime();\n    Real dt_local = m_fine_time_mng->getCurrentTimeStep();\n    computeVFDirichletOverlapForWindow(current_time, dt_local, m_val_limit1,\n        m_val_limit2);\n  }\n\nvoid ToyReactiveTransportCouplageDtLocalModule::computeVFDirichletOverlapForWindow(\n    Real current_time, Real dt_local, Array<Real> Val_Lim1,\n    Array<Real> Val_Lim2)\n  {\n    Integer ival = 0;\n    Real coarse_current_time = m_coarse_time_mng->getCurrentTime();\n    Real coarse_deltat = m_coarse_time_mng->getCurrentTimeStep();\n    // on veut recuperer la pression a imposer sur la zone window\n    //\n    ENUMERATE_CELL(icell, m_cell_interfaceW_group)\n      {\n        const Cell &cell = *icell;\n        m_u_concentration_overlap[cell] = Val_Lim1[ival] + (Val_Lim2[ival]\n            - Val_Lim1[ival]) * ((current_time - coarse_current_time)\n            / coarse_deltat + 1.);\n\n        ival++;\n      }\n  }\n\n/*-----------------------------------------------------------------------------------------*/\n/*-----------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n// calcul de la pression moyenne au cours du temps dans la zone window\n//  a la fin  des petits pas de temps, il faut diviser par le grand  pas de temps\n//\n// average_flux = Sommme_dt (dt * flux)\n//\nvoid ToyReactiveTransportCouplageDtLocalModule::computeAverageFluxOnOverlap(\n    Real deltat)\n  {\n    // calcul des flux moyens sur la zone raffinee\n    ENUMERATE_FACE(iface, m_interface_face_group)\n      {\n        m_average_flux[iface] += m_flux_overlap[iface] * deltat;\n      }\n  }\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n// calcul de la pression moyenne au cours du temps dans la zone window\n//  a la fin  des petits pas de temps, il faut diviser par le grand  pas de temps\n//\n// average_pressure = Sommme_dt (dt * pressure)\n//\nvoid ToyReactiveTransportCouplageDtLocalModule::computeAveragePressureOnWindow(\n    Real deltat)\n  {\n    cout << \" computeAveragePressureOnWindow \" << endl;\n\n    // calcul des pressions moyennes sur la zone raffinee\n    ENUMERATE_CELL(icell, m_window_group)\n      {\n        const Cell &cell = *icell;\n        m_average_u_concentration[cell] += (*m_u_concentration_fine)[icell]\n            * deltat;\n      }\n  }\nvoid ToyReactiveTransportCouplageDtLocalModule::writeoutput()\n  {\n/* DEBUG\n    ENUMERATE_CELL(icell, m_global_cell_group)\n      {\n        const Cell &cell = *icell;\n        cout << \"MATLABUCONCENTRATION(\" << m_iteration << \",\"\n            << cell.uniqueId() << \"+1\" << \")=\" << m_u_concentration[icell]\n            << \";\" << endl;\n        cout << \"MATLABVCONCENTRATION(\" << m_iteration << \",\"\n            << cell.uniqueId() << \"+1\" << \")=\" << m_v_concentration[icell]\n            << \";\" << endl;\n      }\n*/\n    cout << \"MATLABTEMPS(\" << m_iteration << \")=\" << m_coarse_time_mng->getCurrentTime() << \";\" << endl;\n    m_iteration++;\n  }\nusing namespace Arcane;\nARCANE_REGISTER_MODULE_TOYREACTIVETRANSPORTCOUPLAGEDTLOCAL\n    ( ToyReactiveTransportCouplageDtLocalModule);\n", "meta": {"hexsha": "e3f17ea944c1992b1ec5431836d4173f1e01821f", "size": 78976, "ext": "cc", "lang": "C++", "max_stars_repo_path": "arcane/extras/NumericalModel/src/ToyReactiveTransport/ToyReactiveTransportCouplageDtLocal/ToyReactiveTransportCouplageDtLocalModule.cc", "max_stars_repo_name": "cedricga91/framework", "max_stars_repo_head_hexsha": "143eeccb5bf375df4a3f11b888681f84f60380c6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T12:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:19:14.000Z", "max_issues_repo_path": "arcane/extras/NumericalModel/src/ToyReactiveTransport/ToyReactiveTransportCouplageDtLocal/ToyReactiveTransportCouplageDtLocalModule.cc", "max_issues_repo_name": "cedricga91/framework", "max_issues_repo_head_hexsha": "143eeccb5bf375df4a3f11b888681f84f60380c6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2021-09-17T13:49:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:24:07.000Z", "max_forks_repo_path": "arcane/extras/NumericalModel/src/ToyReactiveTransport/ToyReactiveTransportCouplageDtLocal/ToyReactiveTransportCouplageDtLocalModule.cc", "max_forks_repo_name": "cedricga91/framework", "max_forks_repo_head_hexsha": "143eeccb5bf375df4a3f11b888681f84f60380c6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T16:48:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T19:06:56.000Z", "avg_line_length": 40.5005128205, "max_line_length": 199, "alphanum_fraction": 0.6120720219, "num_tokens": 18057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326705, "lm_q2_score": 0.025565213923269596, "lm_q1q2_score": 0.011488819212682024}}
{"text": "// Copyright (c) 2016 Richard Glennie, University of St Andrews \n// \n// Permission is hereby granted, free of charge, to any person obtaining a \n// copy of this software and associated documentation files, to deal in the\n// software without restriction, including without limitation the right to use,\n// copy, modify, publish, distribute, sublicense, and/or sell copies of the software,\n// and to permit persons to whom the software is furnished to do so, subject to the \n// 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 THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE\n//\n// ============================================================================\n//\n// Project: Distance Sampling with movement simulation engine \n// File contains cpp code to be included using Rcpp\n//\n// ============================================================================\n//\n// [[Rcpp::depends(RcppArmadillo)]]\n#include <iostream>\n#include <fstream>\n#include <cmath> \n#include <armadillo> \n#include <errno.h> \n#include <RcppArmadillo.h> \n#include <vector> \n#include <string> \n#include <sstream> \n\nusing arma::mat; \nusing arma::vec;\nusing arma::rowvec;\nusing arma::field; \nusing arma::cx_mat;\nusing arma::cx_cube; \nusing arma::randu;\nusing arma::randn; \n\nusing std::cout;\nusing std::string; \n\n// Class Declarations\n// ============================================================================\nclass SurveyRegion;\nclass LineTransect;\nclass Animal;\nclass Observer; \n\n// The survey region is the area the population lives in and contains \n// the total population. \n// An region is specified by its width and length (it is assumed to be rectangular). \nclass SurveyRegion { \n  public:\n    // constructors\n    SurveyRegion(); \n    SurveyRegion(double width, double length) : length_(length), width_(width) {} \n    SurveyRegion(vec size) : length_(size(1)), width_(size(0)){}\n\n    // accessors \n    const double width() const {return width_;}\n    const double length() const {return length_;} \n\n  private: \n    double length_; \n    double width_; \n};\n\n// Line transect is tranversed by the observer.\n// It is specified by its length and its width (full width, not half-width). \n// For the simulation, it is assumed the transect is placed (w / 2, 0) where \n// w is the width of the survey region. As animals are on average uniformly\n// placed with respect to the line, where the line does not matter. \n// Adding a starting coordinate for the line transect is an obvious extension.  \nclass LineTransect {\n  public:  \n    // Default constructor is empty (does nothing)\n    LineTransect(); \n    LineTransect(double width, double length) : length_(length), width_(width) {} \n    LineTransect(vec size) : length_(size(1)), width_(size(0)) {} \n\n    // Accessor functions \n    const double length() const {return length_;} \n    const double width() const {return width_;}\n\n  private: \n    double length_; \n    double width_; \n};\n\n// Animals are assumed to move according to behaviour: \n//   0 = no movement\n//   1 = random direction, constant speed \n//   2 = OU process with home center\n// Animals also have a accumulated hazard and a threshold hazard. An animal\n// accumulates hazard by being surveyed by an observer. When the accumulated \n// hazard exceeds the threshold, the animal is seen by an observer. \n// The accumulation is setup for only one observer. \n// Animals can only accumulate hazard when they are available for detection. \n// It is assumed that animals are reflected off the boundary of the survey region. \nclass Animal {\n  public:\n    // constructors\n    Animal(){}  \n    // place animal at (x,y), not moving\n    Animal(double x, double y) : behaviour_(0), available_(true) {\n      x_ = x; \n      y_ = y;\n      threshold_hazard_ = -log(arma::as_scalar(randu(1))); \n      accumulated_hazard_ = 0;  \n    }\n    // place animal at (x,y) moving in direction at velocity v\n    Animal(double x, double y, double v, double direction) : x_(x), y_(y), v_(v),\n    direction_(direction), behaviour_(1), available_(true) {\n      threshold_hazard_ = -log(arma::as_scalar(randu(1)));\n      accumulated_hazard_ = 0;  \n    }\n    // place animal at home center (x_home, y_home) and \n    // move as OU process with parameters theta = (tau, c)\n    // See Gillespie et al. (1996) for parameterisation.\n    Animal(double x_home, double y_home, vec theta) : x_(x_home), y_(y_home), behaviour_(2), available_(true), x_home_(x_home), y_home_(y_home), movement_parameter_(theta) {\n      threshold_hazard_ = -log(arma::as_scalar(randu(1))); \n      accumulated_hazard_ = 0; \n    } \n    // accessor functions \n    const double x() const {return x_;}\n    const double y() const {return y_;} \n    const double v() const {return v_;} \n    const double direction() const {return direction_;} \n    const int behaviour() const {return behaviour_;} \n    const double x_home() const {return x_home_;} \n    const double y_home() const {return y_home_;} \n    const bool available() const {return available_;}\n    const double hazard() const {return accumulated_hazard_;}\n    const double threshold_hazard() const {return threshold_hazard_;} \n    const vec movement_parameter() const {return movement_parameter_;}  \n\n    // mutator functions \n    void set_x(double x){x_ = x;} \n    void set_y(double y){y_ = y;} \n    void set_v(double v){v_ = v;} \n    void set_direction(double direction){direction_ = direction;}\n    void set_behaviour(int behaviour){behaviour_ = behaviour;} \n    void set_home(double x_home, double y_home){x_home_ = x_home; y_home_ = y_home;}  \n    void set_available(bool available){available_ = available;} \n    void set_movement_parameter(vec movement_parameter){movement_parameter_ = movement_parameter;}  \n    void reset_threshold() {threshold_hazard_ = -log(arma::as_scalar(randu(1)));} \n    void reset_hazard(){accumulated_hazard_ = 0;}\n    void accumulate_hazard(const Observer observer, double dt);  \n    void move(const SurveyRegion& region, double dt);  \n  private: \n    double x_;\n    double y_; \n    double v_;\n    double direction_; \n    int behaviour_; \n    double x_home_; \n    double y_home_; \n    bool available_;\n    double accumulated_hazard_;\n    double threshold_hazard_;  \n    vec movement_parameter_;  \n}; \n\n// Observer moves along transect, detecting animals.  \n// Assumes observer starts at beginning of transect\n// Detection functions is 2D hazard, so detection_parameter = (c, b) \n// See advanced distance sampling book p350 by Buckland et al.   \nclass Observer {\n  public:\n    Observer(); \n    Observer(double v, vec detection_parameter) : x_(0), y_(0), v_(v), see_behind_(false), detection_parameter_(detection_parameter){}  \n    Observer(double v, vec detection_parameter, bool see_behind) : x_(0), y_(0), v_(v), see_behind_(see_behind), detection_parameter_(detection_parameter){}   \n\n    // accessor functions \n    const double x() const {return x_;}\n    const double y() const {return y_;} \n    const double speed() const {return v_;} \n    const bool see_behind() const {return see_behind_;}\n    const vec detection_parameter() const {return detection_parameter_;} \n\n    // mutator functions\n    void set_x(double x){x_ = x;} \n    void set_y(double y){y_ = y;} \n    void set_speed(double v){v_ = v;}\n    void set_detection_parameter(vec theta) {detection_parameter_ = theta;} \n\n    void move(double dt); \n    bool detect(Animal& animal, double dt); \n\n  private: \n    double x_;\n    double y_; \n    double v_;\n    bool see_behind_; \n    vec detection_parameter_;  \n}; \n\n// SurveyDat is a data structure used to package information\n// together for brevity.\nstruct SurveyDat {\n  int population_size; \n  vec region_size;\n  vec line_size; \n  int behaviour; \n  vec movement_parameter;   \n  double observer_speed;\n  bool see_behind; \n  vec detection_parameter;  \n  int num_transects; \n};\n\n\n\n// Class Member function definitions \n// ============================================================================\n\n// Accumulates hazard of detection based on relative distance between \n// observer and animal. \n// Inputs: \n//   observer: an Observer object, the observer who is surveying \n//   dt: time step for simulation \nvoid Animal::accumulate_hazard(const Observer observer, double dt) {\n  double rel_x = x() - observer.x(); \n  double rel_y = y() - observer.y(); \n  if (available() & (observer.see_behind() || (!observer.see_behind() && rel_y > 0))) {\n    double r0 = rel_x * rel_x + rel_y * rel_y;\n    double y1 = rel_y - observer.speed() * dt;\n    // if y1 < 0 but y > 0, animal lies in front of observer now \n    // but observeer will pass the animal abeam in this time step, so \n    // only survey up until y1 = 0  \n    if (y1 < 0) y1 = 0; \t\n    double r1 = rel_x * rel_x + y1 * y1;\n    // if animal behind observer for whole time-step, then switch r0 and r1 as\n    // you want to integrate from higher r to lower r \n    if (rel_y < 0) {\n      double temp = r0; \n      r0 = r1; \n      r1 = temp; \n    }\n    // animals at same position as observer causes overflow in hazard, \n    // so handle seperately.  \n    if (r1 < 1e-10) accumulated_hazard_ = arma::datum::inf; \n    else {  \n      double alpha = observer.detection_parameter()(0); \n      double beta = observer.detection_parameter()(1); \n      double abeta = 0.5 * (beta - 1); \n      // hazard is integral over time, if x is small or \n      // abeta is small, then integral differs from usual case\n      if (fabs(rel_x) < 1e-10) {\n        if (fabs(abeta) < 1e-10) accumulated_hazard_ += alpha * 0.5 * (log(r1) - log(r0)); \n        else accumulated_hazard_ += beta / (alpha - 1) * (1 / pow(r1, abeta) - 1 / pow(r0,abeta)); \n      }\n      else {\n        double hazard = R::pbeta(rel_x * rel_x / r1, abeta, 0.5, 1, 0) - R::pbeta(rel_x * rel_x / r0, abeta, 0.5, 1, 0); \n        hazard *= R::beta(abeta, 0.5) * alpha / (2 * pow(fabs(rel_x), beta - 1)); \n        accumulated_hazard_ += hazard; \n      }\n    }      \n  }\n}\n\n// Move animal over a time interval of length dt\n// Inputs: \n//   region: a SurveyRegion object\n//   dt: time step \nvoid Animal::move(const SurveyRegion& region, double dt) {\n  double new_x = x(); \n  double new_y = y();\n  double new_direction = direction();  \n  switch (behaviour()) { \n    // straight-line, random-direction, constant-speed movement\n    case 1: \n      new_x = x() + v() * cos(direction()) * dt; \n      new_y = y() + v() * sin(direction()) * dt; \n      break; \n      // OU home-range process \n    case 2:\n      double var = movement_parameter()(1) * movement_parameter()(0) / 2; \n      var *= 1 - exp(-2 * dt / movement_parameter()(0)); \n      var = sqrt(var); \n      new_x = x_home() + (x() - x_home()) * exp(-dt / movement_parameter()(0)); \n      new_x += var * as_scalar(randn(1)); \n      new_y = y_home() + (y() - y_home()) * exp(-dt / movement_parameter()(0)); \n      new_y += var * as_scalar(randn(1)); \n      break; \n  }\n  // check if animal has moved outside region, if so, reflect off boundary \n  // and reverse direction \n  if (new_x > region.width()) {\n    new_x = 2 * region.width() - new_x;\n    if (behaviour() == 1) new_direction = fmod(new_direction + M_PI, 2 * M_PI);  \n  }\n  if (new_y > region.length()) {\n    new_y = 2 * region.length() - new_y; \n    if (behaviour() == 1) new_direction = fmod(new_direction + M_PI, 2 * M_PI);  \n  }\n  if (new_x < 0) {\n    new_x *= -1;\n    if (behaviour() == 1) new_direction = fmod(new_direction + M_PI, 2 * M_PI);  \n  }\n  if (new_y < 0) {\n    new_y *= -1; \n    if (behaviour() == 1) new_direction = fmod(new_direction + M_PI, 2 * M_PI);  \n  }\n  set_x(new_x);\n  set_y(new_y);\n  if (behaviour() == 1) set_direction(new_direction); \n} \n\nvoid Observer::move(double dt) {\n  set_y(y() + speed() * dt); \n}\n\nbool Observer::detect(Animal& animal, double dt) {\n  // if hazard > threshold already, the animal has already been detected, \n  // you don't detect it again. \n  if (animal.hazard() > animal.threshold_hazard()) return false;\n  animal.accumulate_hazard(*this,  dt); \n  // if hazard > threshold now, animal is seen at this time\n  if (animal.hazard() > animal.threshold_hazard()) return true; \n  return false; \t\n}  \n\n// Standalone Functions \n// ============================================================================\n\n// Respawn animals for a new transect\n// Inputs: \n//   population: pointer to array of animals\n//   num_animals: number of animals in population\n//   region: SurveyRegion object \nvoid SpawnAnimals(std::vector<Animal>& population, const int& num_animals, const SurveyRegion& region) {\n  // animals are assumed to be randomly distributed about the region\n  // (and hence line)  \n  vec randx = randu(num_animals) * region.width(); \n  vec randy = randu(num_animals) * region.length(); \n  for (int animal = 0; animal < num_animals; ++animal) {\n    population[animal].set_x(randx(animal));\n    population[animal].set_y(randy(animal)); \n    population[animal].reset_hazard(); \n    population[animal].reset_threshold();\n    population[animal].set_available(true);\n    switch (population[animal].behaviour()) {\n      case 1:\n        population[animal].set_direction(as_scalar(randu(1)) * M_PI * 2);\n        population[animal].set_v(population[animal].movement_parameter()(0)); \n        break; \n      case 2: \n        // home ranges are assumed to be randomly distributed\n        population[animal].set_home(randx(animal), randy(animal));\t\n        break;\n    }    \n  }\n}\n\n// Respawn observer for new transect. Observer is placed at (width/2, 0) \n//  coordinates.  \n// Inputs: \n//   observer: Observer object to be respawned \n//   region: SurveyRegion object \nvoid SpawnObserver(Observer& observer, const SurveyRegion& region) {\n  observer.set_x(region.width() / 2); \n  observer.set_y(0); \n}\t\n\n// Simulate distance sampling survey with moving animals\n// Inputs: \n//   simdat: SimulationDat object\n//   dt: time step \n// Output: \n//   file \"data.txt\" is written to mcds directory with tabulated fields\n//   \"transect\", \"effort\", \"perpendicular distance\" for each recorded detection.\nvoid SimulateSurvey(SurveyDat survey_dat, double dt) {\n  // create objects involved\n  SurveyRegion region(survey_dat.region_size); \n  LineTransect line(survey_dat.line_size);\n  int num_animals = survey_dat.population_size;  \n  std::vector<Animal> population(num_animals);\n  Observer observer(survey_dat.observer_speed, survey_dat.detection_parameter, survey_dat.see_behind); \n  for (int animal = 0; animal < num_animals; ++animal) {\n    population[animal].set_behaviour(survey_dat.behaviour);\n    population[animal].set_movement_parameter(survey_dat.movement_parameter); \n  }\n\n  // open file to write data to\n  std::ofstream dat(\"../mcds/data.txt\");\n\n  // perform survey \n  double num_timesteps = floor(line.length() / (dt * observer.speed()));\n  vec randx(num_animals); \n  vec randy(num_animals);\n  int num_detected;  \n  for (int transect = 0; transect < survey_dat.num_transects; ++transect) {\n    SpawnAnimals(population, num_animals, region); \n    SpawnObserver(observer, region);  \n    num_detected = 0; \n    for (int t = 0; t < num_timesteps; ++t) {\n      for (int animal = 0; animal < num_animals; ++animal) { \n        // animal detection is recorded if animal is seen INSIDE transect only\n        // (but notice this does not ignore animals seen outside transect, it merely doesn't record them)  \n        if (observer.detect(population[animal], dt) && fabs(population[animal].x() - observer.x()) <= line.width()/2.0 && population[animal].y() < line.length()) {\n          dat << transect << \"\\t\"  << line.length() << \"\\t\" << fabs(population[animal].x() - observer.x()) << \"\\n\";\n          ++num_detected; \n        } \n        population[animal].move(region, dt); \n      } \n      observer.move(dt); \n    } \n    // if no animals seen on a transect, write a line to indicate this for MCDS \n    if (num_detected == 0) dat << transect << \"\\t\" << line.length() << \"\\n\"; \n  }\n}\n\n// Fit distance sampling model\n// Assumes there is a file named \"data.csv\" with fields \n// transect, perpendicular distance.\n// This function runs the external MCDS engine; the engine must \n// be in the directory \"./mcds\", and the command file for the \n// MCDS engine must be correctly filled out. \n// Current runs MCDS using WINE! \n// Outputs:\n//   writes a file named \"output.txt\" with the model results\nvoid FitModel() {\n  int r = system(\"cd ../mcds; wine MCDS 0, command.txt\"); \n}\n\n\n// Save the data and fitted model of simulated survey to \n// a subdirectory. \n// The function renames \"data.txt\" to \"../results/data_<num>.csv\"\n// and output from mcds \"output.txt\" to \"../results/output_<num>.txt\"\n// where \"<num>\" is the simulation number. \n// Note this function assumes the directiory \"results\" exists.\n// Input: \n//   num: the number to appended to each file name \n//   save_log: if TRUE, the MCDS log files are saved also (to check for convergence problems)\nvoid Clean(int num, bool save_log = false) {\n  std::stringstream cmd; \n  cmd << \"mv ../mcds/data.txt ../results/data_\" << num << \".txt\"; \n  int r = system(cmd.str().c_str()); \n  cmd.str(\"\"); \n  cmd << \"mv ../mcds/output.txt ../results/output_\" << num << \".txt\"; \n  r = system(cmd.str().c_str());  \n  if (save_log) {\n    cmd.str(\"\");\n    cmd << \"mv ./mcds/log.txt ../results/log_\" << num << \".txt\";\n    r = system(cmd.str().c_str());  \n  }\n}\n\n// Perform Simulation study\n// Inputs:\n//   num_simulations: number of simulated surveys to do\n//   parameter: vector of detection parameters (c,d) and \n//     if behaviour=1 (speed, angle sd)\n//     if behaviour=2 (tau, sigma) of OU process \n//   simulation_dat: vector containing (in this order)  \n//     population_size: size of population to simulate\n//     region_size: (width, length) of rectangular study region\n//     line_size: (width, length) of a single transect \n//     behaviour: 0(no movement), 1(straight-line movement), 2(home-range movement) \n//     observer_speed: speed of the observer \n//     num_transects: number of transects per surveyed simulation \n//   dt: time step\n//   seed: random seed (set in Armadillo) \n// [[Rcpp::export]] \nvoid Simulate(int num_simulations, vec parameter, vec simulation_dat, double dt = 1, int seed = -1) {\n  if (seed > 0) arma::arma_rng::set_seed(seed); \n  // unpack simulation data from input and then\n  // package into a data structure  \n  int population_size = simulation_dat(0); \n  vec region_size = simulation_dat.rows(1,2); \n  vec line_size = simulation_dat.rows(3,4); \n  int behaviour = simulation_dat(5); \n  double observer_speed = simulation_dat(6); \n  int num_transects = simulation_dat(7);\n  vec detection_parameter = parameter.rows(0,1); \n  vec movement_parameter = arma::zeros<vec>(2); \n  bool see_behind = simulation_dat(8); \n  switch (behaviour) {\n    case 1: \n      movement_parameter(0) = parameter(2); \n      break; \n    case 2:\n      movement_parameter = parameter.rows(2,3);\n      break;  \n  }\n  SurveyDat survey_dat = {population_size, region_size, line_size, behaviour, movement_parameter, observer_speed, see_behind, detection_parameter, num_transects}; \t\n\n  for (int sim = 0; sim < num_simulations; ++sim) {\n    cout << sim + 1 << \" / \" << num_simulations << \"\\n\"; \n    SimulateSurvey(survey_dat, dt);\n    FitModel(); \n    Clean(sim + 1); \t\n  }\n}\t\n", "meta": {"hexsha": "9a227c13e177f6ab374f1ddf222089d6bdb5d9bc", "size": 19693, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/simds.cc", "max_stars_repo_name": "r-glennie/SimDs", "max_stars_repo_head_hexsha": "e265cc80d6ac315034d271d65e02f907c385b237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simds.cc", "max_issues_repo_name": "r-glennie/SimDs", "max_issues_repo_head_hexsha": "e265cc80d6ac315034d271d65e02f907c385b237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simds.cc", "max_forks_repo_name": "r-glennie/SimDs", "max_forks_repo_head_hexsha": "e265cc80d6ac315034d271d65e02f907c385b237", "max_forks_repo_licenses": ["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.918972332, "max_line_length": 173, "alphanum_fraction": 0.6563753618, "num_tokens": 5172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.03161876715458074, "lm_q1q2_score": 0.011476638793607927}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis\t\t\t\t\t\t  |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford\t  |\n|\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  |\n|  This program is free software; you can redistribute it and/or modify\t\t  |\n|  it under the terms of the GNU General Public License as published by\t\t  |\n|  the Free Software Foundation; either version 2 of the License, or\t\t  |\n|  (at your option) any later version.\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\t  |\n|  This program is distributed in the hope that it will be useful,\t\t\t  |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of\t\t\t  |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\t\t\t  |\n|  GNU General Public License for more details.\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\t  |\n|  You should have received a copy of the GNU General Public License along\t  |\n|  with this program; if not, write to the Free Software Foundation, Inc.,\t  |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\t\t\t\t  |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#include \"square_matrix.hpp\"\n#include \"rectangular_matrix.hpp\"\n\n#include <boost/format.hpp>\n#include <iostream> //temporary!\n#include <iterator> //temporary!\n\n#include \"ncl/nxsallocatematrix.h\"\n\nnamespace phycas\n{\n\nunsigned RectangularMatrix::_k = 0;\t//temporary!\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tRectangularMatrix default constructor. Sets `_nrows', '_ncols' and `_m' data members to 0.\n*/\nRectangularMatrix::RectangularMatrix()\n  :\t _id(++_k),  _m(0), _nrows(0), _ncols(0), _varcov(0), _dirty_mean(true), _dirty_varcov(true)\n\t{\n\t//std::cerr << \"====> constructing default RectangularMatrix \" << _id << \" <====\" << (this) << std::endl;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tRectangularMatrix constructor. Creates rectangular matrix `_m' with row dimension `_nrows', column dimension\n|   '_ncols', and sets all elements of `_m' to `value'.\n*/\nRectangularMatrix::RectangularMatrix(\n  unsigned nrows,   /**< the row dimension of the matrix */\n  unsigned ncols,   /**< the column dimension of the matrix */\n  double value)\t\t/**< the value to which to set all elements */\n  : _id(++_k), _m(0), _nrows(nrows), _ncols(ncols), _varcov(0), _dirty_mean(true), _dirty_varcov(true)\n\t{\n\t//std::cerr << \"====> constructing RectangularMatrix \" << _id << \" of size \" << _nrows << \" rows, \" << _ncols << \" columns, with all values set to \" << value << \" <====\" << (this) << std::endl;\n\tCreateMatrix(_nrows, _ncols, value);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tRectangularMatrix copy constructor. This is necessary because the standard vector resize function in some\n|   implementations of the standard template library creates only one element with the default constructor, then creates\n|   the remaining elements using the copy constructor.\n*/\nRectangularMatrix::RectangularMatrix(\n  const RectangularMatrix & other)\t/**< is the RectangularMatrix to copy */\n  : _id(++_k), _m(0), _nrows(other._nrows), _ncols(other._ncols), _varcov(0), _dirty_mean(true), _dirty_varcov(true)\n  \t{\n\t//std::cerr << \"====> copy constructing RectangularMatrix \" << _id << \" from \" << other._id << \" <====\" << (this) << std::endl;\n\tif (_nrows > 0 && _ncols > 0)\n\t\t{\n\t\tCreateMatrix(_nrows, _ncols, 0.0);\n\t\tdouble * pother = &other._m[0][0];\n\t\tdouble * p = &_m[0][0];\n\t\tunsigned last = _nrows*_ncols;\n\t\tfor (unsigned i = 0; i < last; ++i)\n\t\t\t*p++ = *pother++;\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tRectangularMatrix destructor. If `_m' exists, deletes it.\n*/\nRectangularMatrix::~RectangularMatrix()\n\t{\n\t//std::cerr << \"====> destroying RectangularMatrix \" << _id << \" <====\" << (this) << std::endl;\n\tif (_m)\n\t\tDeleteTwoDArray<double>(_m);\n\tif (_varcov)\n\t\tdelete _varcov;\n\t_m = 0;\n\t_nrows = 0;\n\t_ncols = 0;\n\t_varcov = 0;\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t_id = UINT_MAX;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAllocates memory for `_m' data member.\n*/\nvoid RectangularMatrix::CreateMatrix(\n  unsigned nrows,   /**< is the row dimension of the rectangular matrix to be created */\n  unsigned ncols,   /**< is the column dimension of the rectangular matrix to be created */\n  double value)\t\t/**< is the value to which each element will be set */\n\t{\n\t//std::cerr << \"----> RectangularMatrix::CreateMatrix \" << _id << \", _nrows = \" << nrows << \", _ncols = \" << ncols << \", value = \" << value << \" <----\" << std::endl;\n    _dirty_mean = true;\n    _dirty_varcov = true;\n    _nrows = nrows;\n    _ncols = ncols;\n\tif (_m)\n\t\tDeleteTwoDArray<double>(_m);\n\t_m = 0;\n\tif (_varcov)\n\t\tdelete _varcov;\n\t_varcov = 0;\n\tif (_nrows > 0 && _ncols > 0)\n\t\t{\n\t\t_m = NewTwoDArray<double>(_nrows, _ncols);\n\t\tFill(value);\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the dimensions of the data member `_m' as a std::pair<unsigned,unsigned> (number of rows, number of columns).\n*/\nstd::pair<unsigned, unsigned> RectangularMatrix::GetDimensions() const\n\t{\n\treturn std::pair<unsigned, unsigned>(_nrows, _ncols);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the number of rows of the data member `_m'.\n*/\nunsigned RectangularMatrix::GetNRows() const\n\t{\n\treturn _nrows;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the number of columns of the data member `_m'.\n*/\nunsigned RectangularMatrix::GetNCols() const\n\t{\n\treturn _ncols;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAccessor function that simply returns `_m'. This allows `_m' to be passed to functions that expect a two-dimensional\n|\tarray of doubles, but keep in mind that this is somewhat unsafe.\n*/\ndouble * * RectangularMatrix::GetMatrixAsRawPointer() const\n\t{\n\treturn _m;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tOperator that allows access to this RectangularMatrix object as if it were a two-dimensional array of doubles.\n*/\ndouble * RectangularMatrix::operator[](\n  unsigned row) const\n\t{\n\tPHYCAS_ASSERT(row < _nrows);\n\treturn _m[row];\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns element at row `i', column `'j of the matrix.\n*/\ndouble RectangularMatrix::GetElement(unsigned i, unsigned j) const\n\t{\n\tPHYCAS_ASSERT(i < _nrows);\n\tPHYCAS_ASSERT(j < _ncols);\n    return _m[i][j];\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets element at row `i', column `j' of the matrix to the value `v'.\n*/\nvoid RectangularMatrix::SetElement(unsigned i, unsigned j, double v)\n\t{\n\tPHYCAS_ASSERT(i < _nrows);\n\tPHYCAS_ASSERT(j < _ncols);\n    _m[i][j] = v;\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets element at row `i', column `j' of the matrix to the current value plus `v'.\n*/\nvoid RectangularMatrix::AddToElement(unsigned i, unsigned j, double v)\n\t{\n\tPHYCAS_ASSERT(i < _nrows);\n\tPHYCAS_ASSERT(j < _ncols);\n    _m[i][j] += v;\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns row `i' of the matrix as a vector.\n*/\nstd::vector<double> RectangularMatrix::GetRow(unsigned i) const\n\t{\n\tPHYCAS_ASSERT(i < _nrows);\n    double * first = &_m[i][0];\n    double * last = first + _ncols;\n    return std::vector<double>(first, last);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets row `i' of the matrix to the values in the vector `v'.\n*/\nvoid RectangularMatrix::SetRow(unsigned i, const std::vector<double> & v)\n\t{\n\tPHYCAS_ASSERT(i < _nrows);\n\tPHYCAS_ASSERT(v.size() == _ncols);\n    unsigned j = 0;\n    for (std::vector<double>::const_iterator it = v.begin(); it != v.end(); ++it)\n        {\n        double value = *it;\n        _m[i][j++] = value;\n        }\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the entire matrix as a vector by row.\n*/\nstd::vector<double> RectangularMatrix::GetMatrix() const\n\t{\n    std::vector<double> v;\n    double * ptr = (double *)&_m[0];\n    for (unsigned i = 0; i < _nrows*_ncols; ++i)\n        v.push_back(ptr[i]);\n    return v;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCopies supplied vector `v' into this matrix. Vector `v' is expected to have length `nrows'*`ncols', and matrix is\n|   read from `v' by row. The data member `_nrows' is set equal to `nrows', and the data member '_ncols' is set equal to\n|   'ncols'.\n*/\nvoid RectangularMatrix::SetMatrix(unsigned nrows, unsigned ncols, std::vector<double> v)\n\t{\n\tPHYCAS_ASSERT(nrows*ncols == (unsigned)v.size());\n    CreateMatrix(nrows, ncols, 0.0);\n    double * ptr = (double *)&_m[0][0];\n    for (std::vector<double>::iterator it = v.begin(); it != v.end(); ++it)\n        {\n        double val = *it;\n        *ptr++ = val;\n        }\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tFills all cells of matrix `_m' with `value'.\n*/\nvoid RectangularMatrix::Fill(\n  double value) /**< is the value to which every element in matrix is to be set */\n\t{\n    std::pair<unsigned,unsigned> dim = GetDimensions();\n\tunsigned last = dim.first*dim.second;\n\tdouble * p = &_m[0][0];\n\tfor (unsigned i = 0; i < last; ++i)\n\t\t*p++ = value;\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAssumes '_nrows' > 0, '_ncols' > 0, and `_m' exists. Multiplies each element of `_m' by the supplied `scalar'.\n*/\nvoid RectangularMatrix::ScalarMultiply(\n  double scalar)\t/**< is the scalar value multiplied by each element */\n\t{\n\t//std::cerr << \"----> RectangularMatrix::ScalarMultiply \" << _id << \", scalar = \" << scalar << \" <----\" << std::endl;\n\tPHYCAS_ASSERT(_nrows > 0);\n\tPHYCAS_ASSERT(_ncols > 0);\n\tunsigned last = _nrows*_ncols;\n\tdouble * p = &_m[0][0];\n\tfor (unsigned i = 0; i < last; ++i)\n\t\t*p++ *= scalar;\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAssumes '_nrows' > 0, '_ncols' > 0, and `_m' exists. Sets each element of `_m' to the supplied `scalar'.\n*/\nvoid RectangularMatrix::SetToScalar(\n  double scalar)\t/**< is the scalar value to which each element is set */\n\t{\n\t//std::cerr << \"----> RectangularMatrix::SetToScalar \" << _id << \", scalar = \" << scalar << \" <----\" << std::endl;\n\tPHYCAS_ASSERT(_nrows > 0);\n\tPHYCAS_ASSERT(_ncols > 0);\n\tunsigned last = _nrows*_ncols;\n\tdouble * p = &_m[0][0];\n\tfor (unsigned i = 0; i < last; ++i)\n\t\t*p++ = scalar;\n    _dirty_mean = true;\n    _dirty_varcov = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSaves a representation of the matrix to the supplied string for use in debugging. The caller should supply a format\n|\tstring suitable for representing a single value of the matrix: e.g. \"%12.5f\\t\".\n*/\nvoid RectangularMatrix::MatrixToString(\n  std::string & s,\t\t /**< the string to which a representation will be saved */\n  std::string fmt) const /**< the format string */\n\t{\n    std::pair<unsigned,unsigned> dim = GetDimensions();\n\t//s += boost::str(boost::format(\"This is RectangularMatrix %d\\n\") % _id);\n\tfor (unsigned i = 0; i < dim.first; ++i)\n\t\t{\n\t\tfor (unsigned j = 0; j < dim.second; ++j)\n\t\t\t{\n\t\t\ts += str(boost::format(fmt) % _m[i][j]);\n\t\t\t}\n\t\ts += '\\n';\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns string representation of the matrix.\n*/\nstd::string RectangularMatrix::GetStringRepresentation() const\n\t{\n    std::string s;\n    std::string fmt = \"\\t%g\";\n    MatrixToString(s, fmt);\n    return s;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns string representation of the matrix.\n*/\nstd::string RectangularMatrix::GetFormattedStringRepresentation(std::string fmt = \"%g\") const\n\t{\n    std::string s;\n    MatrixToString(s, fmt);\n    return s;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the data member `_mean'. Calls ComputeMean() first if `_mean' is not up-to-date.\n*/\nstd::vector<double> RectangularMatrix::GetMean()\n\t{\n    if (_dirty_mean || _mean.size() != _ncols)\n        ComputeMean();\n    return _mean;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns a copy of the data member `_varcov'. Calls ComputeVarCovMatrix() first if  `_varcov' is not up-to-date.\n*/\nSquareMatrix * RectangularMatrix::GetVarCovMatrix()\n\t{\n    if (_dirty_varcov || !_varcov || _varcov->GetDimension() != _ncols)\n        ComputeVarCovMatrix();\n    PHYCAS_ASSERT(_varcov);\n    return new SquareMatrix(*_varcov);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tRecomputes the mean vector `_mean'.\n*/\nvoid RectangularMatrix::ComputeMean()\n\t{\n    if (_nrows == 0)\n        {\n        _mean.clear();\n        _dirty_mean = false;\n        return;\n        }\n\n    // compute sample mean vector\n    double n = (double)(_nrows);\n    _mean.assign(_ncols, 0.0);\n    for (unsigned i = 0; i < _nrows; ++i)\n        {\n        for (unsigned j = 0; j < _ncols; ++j)\n            {\n            double v = _m[i][j];\n            _mean[j] += v/n;\n            }\n        }\n\n    _dirty_mean = false;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tRecomputes the variance-covariance matrix `_varcov'.\n*/\nvoid RectangularMatrix::ComputeVarCovMatrix()\n\t{\n    if (_nrows == 0)\n        {\n        _varcov->Clear();\n        }\n    else if (_nrows == 1)\n        {\n        _varcov->SetToScalar(0.0);\n        }\n    else\n        {\n        // compute sample mean vector\n        double n = (double)(_nrows);\n        //_mean.assign(_ncols, 0.0);\n        //std::vector<double> sample_sum(_ncols, 0.0);\n        //std::vector<double> sample_ss(_ncols, 0.0);\n        //for (unsigned i = 0; i < _nrows; ++i)\n        //    {\n        //    for (unsigned j = 0; j < _ncols; ++j)\n        //        {\n        //        double v = _m[i][j];\n        //        _mean[j] += v/n;\n        //        sample_sum[j] += v;\n        //        sample_ss[j] += v*v;\n        //        }\n        //    }\n\n        if (_dirty_mean)\n            ComputeMean();\n\n        // compute sample variance-covariance matrix\n        if (_varcov && _varcov->GetDimension() == _ncols)\n            _varcov->SetToScalar(0.0);\n        else\n            {\n            delete _varcov;\n            _varcov = new SquareMatrix(_ncols, 0.0);\n            }\n\n        for (unsigned i = 0; i < _ncols; ++i)\n            {\n            for (unsigned j = i; j < _ncols; ++j)\n                {\n                for (unsigned k = 0; k < _nrows; ++k)\n                    {\n                    double tmp = (_m[k][i] - _mean[i])*(_m[k][j] - _mean[j])/(n - 1.0);\n                    _varcov->AddToElement(i, j, tmp);\n                    }\n                if (j != i)\n                    {\n                    double tmp = _varcov->GetElement(i, j);\n                    _varcov->SetElement(j, i, tmp);\n                    }\n                }\n            }\n        }\n    _dirty_varcov = false;\n\t}\n\n} // namespace phycas\n", "meta": {"hexsha": "98066cd7d5a201876c7dd8d1f0a5fde2f33f1788", "size": 16784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/rectangular_matrix.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/rectangular_matrix.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/rectangular_matrix.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 36.4078091106, "max_line_length": 194, "alphanum_fraction": 0.4863560534, "num_tokens": 3941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824860330003, "lm_q2_score": 0.0335895023850594, "lm_q1q2_score": 0.011473585729299983}}
{"text": "/// @file  embed_from_ref.cpp\n/// @brief Embed from an embedded subset\n\n#include <boost/program_options.hpp>\n#include <ogt/ogt.hpp>\n#include <future>\n#include <iomanip>\n#include <iostream>\n#include <thread>\n#include <vector>\n\nusing namespace boost::program_options;\nusing dlib::find_min;\nusing dlib::newton_search_strategy;\nusing dlib::bfgs_search_strategy;\nusing dlib::objective_delta_stop_strategy;\nusing Eigen::Index;\nusing Eigen::MatrixXd;\nusing Eigen::SparseMatrix;\nusing Eigen::VectorXd;\nusing ogt::core::AB_LT_AC;\nusing ogt::core::Collection;\nusing ogt::core::createCosinePosOracle;\nusing ogt::core::createEuclideanPosOracle;\nusing ogt::core::createJaccardPosOracle;\nusing ogt::core::Oracle;\nusing ogt::embed::dlib_matrix;\nusing ogt::embed::dlib_vector;\nusing ogt::embed::dlib_to_eigen_matrix;\nusing ogt::embed::eigen_to_dlib_matrix;\nusing ogt::embed::dlib_to_eigen_vector;\nusing ogt::embed::eigen_to_dlib_vector;\nusing ogt::embed::CmpConstraint;\nusing ogt::embed::embedCmpWithSOE;\nusing ogt::embed::EmbedConfig;\nusing ogt::embed::EmbedErr;\nusing ogt::embed::EmbedResult;\nusing ogt::embed::sphere_intersection_margin;\nusing ogt::io::isSparseFile;\nusing ogt::io::loadDenseMatrix;\nusing ogt::io::loadSparseMatrix;\nusing ogt::io::openSink;\nusing ogt::io::saveEmbedding;\nusing ogt::linalg::DenseNZIterator;\nusing ogt::linalg::posToDist;\nusing ogt::util::random_nchoosek;\nusing ogt::util::random_subset;\nusing std::async;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::future;\nusing std::make_shared;\nusing std::map;\nusing std::min;\nusing std::set;\nusing std::shared_ptr;\nusing std::string;\nusing std::stringstream;\nusing std::vector;\n\nstd::ostream& log() {\n\tstd::time_t t = std::time(nullptr);\n    std::tm tm = *std::localtime(&t);\n    cerr << std::put_time(&tm, \"%c %Z\") << ' ';\n    return cerr;\n}\n\nconst char * DIST_EUCLIDEAN = \"EUCLIDEAN\";\nconst char * DIST_COSINE = \"COSINE\";\nconst char * DIST_JACCARD = \"JACCARD\";\n\nstruct pt_pos {\n\tpt_pos(size_t pt, VectorXd pos, vector<CmpConstraint> cmps)\n\t\t: pt(pt), pos(pos), cmps(cmps), createdAt(clock()) {}\n\tconst size_t pt;\n\tconst VectorXd pos;\n\tconst vector<CmpConstraint> cmps;\n\tconst clock_t createdAt;\n};\n\nstruct idx_dist {\n\tidx_dist(size_t idx, double dist) : idx(idx), dist(dist) {}\n\tsize_t idx;\n\tdouble dist;\n};\n\nstruct fft_idx {\n\tfft_idx(size_t idx, double dist) : idx(idx), dist(dist) {}\n\n\tvoid findDists(const vector<size_t>& subset, const MatrixXd& refD) {\n\t\t// Prepare the sorted distance vector\n\t\tdists.clear();\n\t\tdists.reserve(refD.rows());\n\t\tfor (Index i = 0; i < refD.cols(); i++) {\n\t\t\tdists.emplace_back(subset[i], refD(idx, i));\n\t\t}\n\t\tstd::sort(dists.begin(), dists.end(), [](const auto& a, const auto& b) {\n\t\t\treturn a.dist < b.dist;\n\t\t});\n\t}\n\n\tsize_t idx;\n\tdouble dist;\n\tvector<idx_dist> dists;\n};\n\nstruct pt_shell {\n\tpt_shell() : center(0), minDist(0), maxDist(0) {}\n\tsize_t center;\n\tdouble minDist;\n\tdouble maxDist;\n};\n\n/// Find a farthest-first traversal of a set\nvector<fft_idx> fft(const vector<size_t>& subset, const MatrixXd& refD) {\n\tvector<fft_idx> order;\n\tsize_t nObj = refD.rows();\n\torder.reserve(nObj);\n\n\t// Find the first point, on the convex hull\n\tVectorXd dist = refD.row(0);\n\tfft_idx choice(0, 0);\n\tfor (size_t i = 1; i < nObj; i++) {\n\t\tif (dist(i) > choice.dist) {\n\t\t\tchoice.idx = i;\n\t\t\tchoice.dist = dist(i);\n\t\t}\n\t}\n\tchoice.findDists(subset, refD);\n\torder.push_back(choice);\n\tvector<fft_idx> minDist;\n\tfor (size_t i = 0; i < nObj; i++) {\n\t\tif (i != choice.idx) {\n\t\t\tminDist.emplace_back(i, refD(choice.idx, i));\n\t\t}\n\t}\n\n\t// Iterate through the other points until done\n\twhile (!minDist.empty()) {\n\t\tstd::sort(minDist.begin(), minDist.end(), [](const auto& a, const auto& b) {\n\t\t\treturn a.dist < b.dist;\n\t\t});\n\t\tchoice = minDist.back();\n\t\tchoice.findDists(subset, refD);\n\t\tminDist.pop_back();\n\t\torder.push_back(choice);\n\t\tfor (auto& ptd : minDist) {\n\t\t\tptd.dist = std::min(ptd.dist, refD(choice.idx, ptd.idx));\n\t\t}\n\t}\n\n\treturn order;\n}\n\n\n/// Tries to use the suggested anchor and pick distance bounds to the point.\nbool find_anchor(size_t pt, const fft_idx& ptd,\n\tconst vector<size_t>& subset, shared_ptr<Oracle> oracle,\n\tpt_shell& anchor, vector<CmpConstraint>& cmps) {\n\tanchor.center = ptd.idx;\n\tsize_t center = subset[ptd.idx];\n\n\t// Make sure the point can be compared to the proposed anchor\n\tif ((*oracle)(center, ptd.dists.front().idx, pt) != AB_LT_AC ||\n\t\t(*oracle)(center, pt, ptd.dists.back().idx) != AB_LT_AC) {\n\t\treturn false;\n\t}\n\n\t// Find the point in the vector\n\tauto ref = ptd.dists.begin();\n\tauto pre = ref;\n\tfor (; (*oracle)(center, ref->idx, pt) == AB_LT_AC; ref = next(ref)) {\n\t\t// cmps.emplace_back(center, ref->idx, pt);\n\t\tpre = ref;\n\t\tanchor.minDist = ref->dist;\n\t}\n\tfor (; ref != ptd.dists.end() \n\t\t&& (*oracle)(center, pt, ref->idx) != AB_LT_AC; ref = next(ref)) {}\n\tif (ref == ptd.dists.end()) {\n\t\treturn false;\n\t}\n\tanchor.maxDist = ref->dist;\n\tcmps.emplace_back(center, pre->idx, pt);\n\tcmps.emplace_back(center, pt, ref->idx);\n\t// auto post = std::lower_bound(ptd.dists.begin(), ptd.dists.end(), pt,\n\t// \t[&](const idx_dist& ref, size_t pt) {\n\t// \t\treturn (*oracle)(center, ref.idx, pt) == AB_LT_AC;\n\t// \t});\n\t// if (post == ptd.dists.begin() || post == ptd.dists.end()) {\n\t// \treturn false;\n\t// }\n\t// cmps.emplace_back(center, pt, ref->idx);\n\t// anchor.maxDist = post->dist;\n\n\t// auto pre = prev(post);\n\t// for (; (*oracle)(center, pre->idx, pt) != AB_LT_AC; pre = prev(pre)) {}\n\t// anchor.minDist = pre->dist;\n\t// cmps.emplace_back(center, pre->idx, pt);\n\t// cmps.emplace_back(center, pt, post->idx);\n\treturn true;\n}\n\n/// The least-squares objective for sphere_intersection_opt\nstruct opt_objective {\n\topt_objective(const MatrixXd& center, const VectorXd& radius,\n\t\tconst VectorXd& margin)\n\t\t: center(center), radius(radius), margin(margin) {}\n\tconst MatrixXd& center;\n\tconst VectorXd& radius;\n\tconst VectorXd& margin;\n\n\tdouble operator()(const dlib_vector& dy) const {\n\t\tdouble res = 0;\n\t\tVectorXd y = dlib_to_eigen_vector(dy);\n\t\tfor (Index j = 0; j < center.cols(); j++) {\n\t\t\tdouble val = (y - center.col(j)).norm() - radius(j);\n\t\t\tif (fabs(val) > margin(j)) {\n\t\t\t\tres += val * val;\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n};\n\n/// The gradient of the least-squares objective for sphere_intersection_opt\nstruct opt_objective_gradient {\n\topt_objective_gradient(const MatrixXd& center, const VectorXd& radius,\n\t\tconst VectorXd& margin)\n\t\t: center(center), radius(radius), margin(margin) {}\n\tconst MatrixXd& center;\n\tconst VectorXd& radius;\n\tconst VectorXd& margin;\n\n\tdlib_vector operator()(const dlib_vector& dy) const {\n\t\tVectorXd y = dlib_to_eigen_vector(dy);\n\t\tVectorXd res = VectorXd::Zero(y.size());\n\t\tfor (Index j = 0; j < center.cols(); j++) {\n\t\t\tVectorXd diff = y - center.col(j);\n\t\t\tdouble dist = diff.norm();\n\t\t\tif (fabs(dist - radius(j)) > margin(j)) {\n\t\t\t\tres += ((dist - radius(j)) / dist) * diff;\n\t\t\t}\n\t\t}\n\t\treturn eigen_to_dlib_vector(2 * res);\n\t}\n};\n\n// /// The Hessian of the least-squares objective for sphere_intersection_opt\n// struct opt_objective_hessian {\n// \topt_objective_hessian(const MatrixXd& center, const VectorXd& radius)\n// \t\t: center(center), radius(radius) {}\n// \tconst MatrixXd& center;\n// \tconst VectorXd& radius;\n\n// \tdlib_matrix operator()(const dlib_vector& dy) const {\n// \t\tVectorXd y = dlib_to_eigen_vector(dy);\n// \t\tMatrixXd res = MatrixXd::Zero(dy.size(), dy.size());\n// \t\tfor (Index j = 0; j < center.cols(); j++) {\n// \t\t\tVectorXd diff = y - center.col(j);\n// \t\t\tdouble dist = diff.norm();\n// \t\t\tdouble sqdist = diff.squaredNorm();\n// \t\t\tdouble scale = (1 - ((dist - radius(j)) / dist)) / sqdist;\n// \t\t\tfor (Index i = 0; i < center.rows(); i++) {\n// \t\t\t\tdouble val1 = y(i) - center(i,j);\n// \t\t\t\tfor (Index k = 0; k <= i; k++) {\n// \t\t\t\t\tres(i,k) += val1 * diff(k) * scale;\n// \t\t\t\t\tres(k,i) = res(i,k);\n// \t\t\t\t}\n// \t\t\t}\n// \t\t}\n// \t\treturn 2 * eigen_to_dlib_matrix(res);\n// \t}\n// };\n\n/// Embed a point based on shell intersection\nVectorXd shell_intersection(const Eigen::MatrixXd &center,\n\tconst Eigen::VectorXd& radius, const Eigen::VectorXd& margin, double /*eps*/,\n\tdouble min_delta, size_t max_iter, bool verbose) {\n\n\t// Using sphere intersection plus margin\n\t// auto locs = sphere_intersection_margin(centers, radii, thickness,\n\t// \teps, minDelta, maxIter, verbose);\n\t// return locs[0];\n\n\t// Direct method\n\tconst Index nDim = center.rows();\n\tdlib_vector dx = eigen_to_dlib_vector(VectorXd::Random(nDim));\n\tobjective_delta_stop_strategy stopper =\n\t\tobjective_delta_stop_strategy(min_delta, max_iter);\n\tif (verbose) {\n\t\tstopper = stopper.be_verbose();\n\t}\n\ttry {\n\t\tfind_min(\n\t\t\t// newton_search_strategy() may produce NaN in some cases?\n\t\t\t// newton_search_strategy(opt_objective_hessian(center, radius)),\n\t\t\tbfgs_search_strategy(),\n\t\t\tstopper,\n\t\t\topt_objective(center, radius, margin),\n\t\t\topt_objective_gradient(center, radius, margin),\n\t\t\tdx,\n\t\t\t0);\n\t} catch (dlib::error err) {\n\t\tthrow EmbedErr(err.what());\n\t}\n\treturn dlib_to_eigen_vector(dx);\n}\n\n/// Run a single embedding, perhaps in a thread pool.\nvector<pt_pos> embed(vector<size_t> pts, size_t nDim, size_t numAnchors,\n\tconst MatrixXd& refX,\n\tconst vector<size_t>& subset, const vector<fft_idx>& refFFT,\n\tshared_ptr<Oracle> oracle) {\n\tvector<pt_pos> result;\n\tfor (size_t pt : pts) {\n\n\t\t// Identify 2(d+1) ref. points close to pt in FFT order\n\t\tif (numAnchors == 0) {\n\t\t\tnumAnchors = 2 * (nDim + 1);\n\t\t}\n\t\tsize_t nextAnchor = 0;\n\t\tMatrixXd centers(nDim, numAnchors);\n\t\tVectorXd radii(numAnchors);\n\t\tVectorXd thickness(numAnchors);\n\t\tvector<CmpConstraint> cmps;\n\t\tfor (const auto& ptd : refFFT) {\n\t\t\tpt_shell anchor;\n\t\t\tif (find_anchor(pt, ptd, subset, oracle, anchor, cmps)) {\n\t\t\t\tcenters.col(nextAnchor) = refX.row(ptd.idx);\n\t\t\t\tradii(nextAnchor) = (anchor.minDist + anchor.maxDist) / 2;\n\t\t\t\tthickness(nextAnchor) = (anchor.maxDist - anchor.minDist) / 2;\n\n\t\t\t\tnextAnchor++;\n\t\t\t\tif (nextAnchor >= numAnchors) break;\n\t\t\t}\n\t\t}\n\n\t\t// Now embed the point using the spherical shell intersection\n\t\ttry {\n\t\t\tconst double eps = 1e-6;\n\t\t\tconst double minDelta = 1e-9;\n\t\t\tconst size_t maxIter = 1000;\n\t\t\tconst bool verbose = false;\n\t\t\tauto loc = shell_intersection(centers, radii, thickness, eps, minDelta,\n\t\t\t\tmaxIter, verbose);\n\t\t\tcerr << \"Done embedding \" << pt << endl;\n\t\t\tresult.emplace_back(pt, loc, cmps);\n\t\t} catch(std::invalid_argument e) {\n\t\t\tlog() << \"Could not embed \" << pt << \": \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t} catch (ogt::embed::EmbedErr e) {\n\t\t\tlog() << \"Could not embed \" << pt << \": \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t} catch(...) {\n\t\t\tlog() << \"Could not embed \" << pt << \": unknown exception\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn result;\n}\n\n/// Run the program.\nint run_embed_from_ref(string posPath, string refPath, size_t numToEmbed,\n\tstring distType, string soeCmpPath, string embPath, string orderPath,\n\tsize_t numAnchors, double noise) {\n\n\t// Prepare to save the output order\n\tconst clock_t started = clock();\n\tauto fOrder = openSink(orderPath);\n\tif (!fOrder) {\n\t\tlog() << \"Invalid --order path: could not open \" << orderPath << endl;\n\t\treturn 1;\n\t}\n\tauto saveOrder = [&](const pt_pos& pt) {\n\t\t(*fOrder) << static_cast<float>(pt.createdAt - started) / CLOCKS_PER_SEC\n\t\t\t<< \",\" << pt.pt << endl;\n\t};\n\n\t// Load the true position matrix and create a distance oracle\n\tlog() << \"Loading position matrix\" << endl;\n\tMatrixXd truePos;\n\tEigen::SparseMatrix<double, Eigen::RowMajor> spTruePos;\n\tshared_ptr<Oracle> oracle;\n\tsize_t nObj, trueDim;\n\tif (isSparseFile(posPath)) {\n\t\tspTruePos = loadSparseMatrix(posPath);\n\t\tif (distType == DIST_EUCLIDEAN) {\n\t\t\toracle = createEuclideanPosOracle(spTruePos);\n\t\t} else if (distType == DIST_COSINE) {\n\t\t\toracle = createCosinePosOracle(spTruePos);\n\t\t} else if (distType == DIST_JACCARD) {\n\t\t\toracle = createJaccardPosOracle<SparseMatrix<double, Eigen::RowMajor>, \n\t\t\t\tEigen::SparseVector<double>,\n\t\t\t\tEigen::SparseVector<double>::InnerIterator>(spTruePos);\n\t\t} else {\n\t\t\tlog() << \"Invalid distance function: \" << distType << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tnObj = spTruePos.rows();\n\t\ttrueDim = spTruePos.cols();\n\t} else {\n\t\ttruePos = loadDenseMatrix(posPath);\n\t\tif (distType == DIST_EUCLIDEAN) {\n\t\t\toracle = createEuclideanPosOracle(truePos);\n\t\t} else if (distType == DIST_COSINE) {\n\t\t\toracle = createCosinePosOracle(truePos);\n\t\t} else if (distType == DIST_JACCARD) {\n\t\t\toracle = createJaccardPosOracle<MatrixXd, VectorXd,\n\t\t\t\tDenseNZIterator<VectorXd>>(truePos);\n\t\t} else {\n\t\t\tlog() << \"Invalid distance function: \" << distType << endl;\n\t\t\treturn 1;\n\t\t}\n\t\tnObj = truePos.rows();\n\t\ttrueDim = truePos.cols();\n\t}\n\tlog() << \"Position matrix is \" << nObj << \"x\" << trueDim << endl;\n\tif (nObj < 1) {\n\t\tlog() << \"Error: empty position matrix from \" << posPath << endl;\n\t\treturn 1;\n\t}\n\tif (noise > 0) {\n\t\toracle = createUniformNoisyOracle(oracle, noise);\n\t}\n\n\t// Load the reference embedding\n\tlog() << \"Loading reference embedding\" << endl;\n\tVectorXd objects;\n\tMatrixXd refX;\n\ttry {\n\t\tauto emb = loadDenseMatrix(refPath);\n\t\tobjects = emb.col(0);\n\t\trefX = emb.rightCols(emb.cols() - 1);\n\t} catch(std::runtime_error e) {\n\t\tlog() << e.what() << endl;\n\t\treturn 1;\n\t}\n\tconst size_t nDim = refX.cols();\n\tlog() << \"Reference embedding is \" << refX.rows() << \"x\" << nDim << endl;\n\n\tlog() << \"Finding distances for reference embedding\" << endl;\n\tMatrixXd refD = posToDist(refX);\n\n\t// Load the SOE comparisons\n\tvector<CmpConstraint> cmps;\n\tif (!soeCmpPath.empty()) {\n\t\tauto soeCmp = loadDenseMatrix(soeCmpPath);\n\t\tfor (Index ii = 0; ii < soeCmp.rows(); ii++) {\n\t\t\tcmps.emplace_back(soeCmp(ii, 0), soeCmp(ii, 1), soeCmp(ii, 2));\n\t\t}\n\t}\n\n\t// Construct the collection\n\tvector<size_t> subset;\n\tmap<size_t, size_t> refIdx;\n\tfor (Index i = 0; i < objects.size(); i++) {\n\t\tsubset.push_back(objects(i));\n\t\trefIdx[objects(i)] = i;\n\t}\n\tlog() << \"Running FFT\" << endl;\n\tvector<fft_idx> refFFT = fft(subset, refD);\n\n\t// Choose points for the final embedding\n\t// numToEmbed = min(nObj - subset.size(), numToEmbed);\n\t// numToEmbed = subset.size();\n\tnumToEmbed = 0; // embed all points\n\tvector<size_t> embedded(subset);\n\tmap<size_t, size_t> embIdx(refIdx);\n\tMatrixXd embX(refX);\n\twhile (embedded.size() < nObj) {\n\t\tnumToEmbed *= 2;\n\t\tnumToEmbed = min(nObj - embedded.size(), numToEmbed);\n\t\tvector<size_t> embedPts;\n\t\tif (numToEmbed > 0 && numToEmbed < nObj - embedded.size()) {\n\t\t\tvector<size_t> options;\n\t\t\tfor (size_t pt = 0; pt < nObj; pt++) {\n\t\t\t\tif (embIdx.find(pt) == embIdx.end()) {\n\t\t\t\t\toptions.push_back(pt);\n\t\t\t\t}\n\t\t\t}\n\t\t\tauto ss = random_subset<size_t>(options.begin(), options.end(), numToEmbed);\n\t\t\tembedPts.insert(embedPts.begin(), ss.begin(), ss.end());\n\t\t\tembedPts.insert(embedPts.begin(), embedded.begin(), embedded.end());\n\t\t\tsort(embedPts.begin(), embedPts.end());\n\t\t} else {\n\t\t\tembedPts.resize(nObj);\n\t\t\tiota(embedPts.begin(), embedPts.end(), 0);\n\t\t}\n\n\t\t// Embed each point which is not in the reference\n\t\tlog() << \"Embedding \" << embedPts.size() << \" / \" << nObj << \" points\" << endl;\n\t\tMatrixXd Xhat = MatrixXd::Random(embedPts.size(), nDim);\n\t\tvector<future<vector<pt_pos>>> futures;\n\t\tmap<size_t, size_t> ptIdx;\n\t\tconst size_t batch = std::thread::hardware_concurrency();\n\t\tauto from = embedPts.begin();\n\t\tauto to = from;\n\t\tfor (size_t ib = 0; ib < batch; ib++) {\n\t\t\tfrom = to;\n\t\t\tif (ib == batch - 1) {\n\t\t\t\tto = embedPts.end();\n\t\t\t} else {\n\t\t\t\tto = next(from, embedPts.size() / batch);\n\t\t\t}\n\t\t\tvector<size_t> points;\n\t\t\tfor (auto it = from; it != to; it++) {\n\t\t\t\tptIdx[*it] = distance(embedPts.begin(), it);\n\t\t\t\tauto fit = embIdx.find(*it);\n\t\t\t\tif (fit == embIdx.end()) {\n\t\t\t\t\tpoints.push_back(*it);\n\t\t\t\t} else {\n\t\t\t\t\t// Save reference point positions\n\t\t\t\t\tXhat.row(ptIdx[*it]) = embX.row(fit->second);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfutures.push_back(async(std::launch::async, embed, points, nDim,\n\t\t\t\tnumAnchors, refX, subset, refFFT, oracle));\n\t\t}\n\t\tfor (auto& future : futures) {\n\t\t\tfor (const pt_pos& result : future.get()) {\n\t\t\t\ttry {\n\t\t\t\t\tlog() << \"Saved \" << result.pt << endl;\n\t\t\t\t\tXhat.row(ptIdx[result.pt]) = result.pos;\n\t\t\t\t\tcmps.insert(cmps.end(), result.cmps.begin(), result.cmps.end());\n\t\t\t\t\tsaveOrder(result);\n\t\t\t\t} catch(...) {\n\t\t\t\t\t// skip it, sad\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (numToEmbed > 0 && !soeCmpPath.empty()) {\n\n\t\t\t// Use SOE to finish the embedding\n\t\t\tlog() << \"Saving embedding\" << endl;\n\t\t\tstringstream ss;\n\t\t\tss << embPath << \"_\" << numToEmbed << \".pre.csv\";\n\t\t\tsaveEmbedding(Xhat, embedPts, ss.str());\n\n\t\t\t// Convert point indexes for the triples\n\t\t\tvector<CmpConstraint> localCmps(cmps);\n\t\t\tstringstream sscmp;\n\t\t\tsscmp << embPath << \"_\" << numToEmbed << \".cmps.csv\";\n\t\t\tauto cmpFile = openSink(sscmp.str());\n\t\t\tfor (auto& cmp : localCmps) {\n\t\t\t\t(*cmpFile) << cmp.a << \",\" << cmp.b << \",\" << cmp.c << endl;\n\t\t\t\tcmp.a = ptIdx[cmp.a];\n\t\t\t\tcmp.b = ptIdx[cmp.b];\n\t\t\t\tcmp.c = ptIdx[cmp.c];\n\t\t\t\tcmp.d = ptIdx[cmp.d];\n\t\t\t}\n\t\t\tcmpFile.reset();\n\n\t\t\tlog() << \"Using as \" << Xhat.rows() << \" x \" << Xhat.cols()\n\t\t\t\t<< \" initialization for SOE embedding\" << endl;\n\t\t\tEmbedConfig config;\n\t\t\tconfig.nDim = nDim;\n\t\t\tconfig.minDelta = 1e-12;\n\t\t\tconfig.maxIter = 1e4;\n\t\t\tconfig.verbose = true;\n\t\t\tconfig.margin = 1e-2;\n\t\t\tauto result = embedCmpWithSOE(localCmps, Xhat, config);\n\t\t\tlog() << \"SOE embedding for \" << numToEmbed << \" achieved loss \" << result.loss << endl;\n\t\t\tXhat = result.X;\n\n\t\t\tauto Xrand = MatrixXd::Random(Xhat.rows(), Xhat.cols());\n\t\t\tauto result2 = embedCmpWithSOE(localCmps, Xrand, config);\n\t\t\tlog() << \"SOE for \" << numToEmbed << \" from random loss: \" << result2.loss\n\t\t\t\t<< \" init: \" << result.loss << endl;\n\t\t}\n\n\t\t// Save the embedding.\n\t\tlog() << \"Saving embedding\" << endl;\n\t\t// stringstream ss2;\n\t\t// ss2 << embPath << \"_\" << numToEmbed << \".post.csv\";\n\t\t// saveEmbedding(Xhat, embedPts, ss2.str());\n\t\tsaveEmbedding(Xhat, embedPts, embPath);\n\n\t\t// Prepare for the next round\n\t\tembedded = embedPts;\n\t\tembIdx = ptIdx;\n\t\tembX = Xhat;\n\t}\n\n\tlog() << \"Done\" << endl;\n\treturn 0;\n}\n\n/// Program entry point.\nint main(int argc, char * argv[]) {\n\ttry {\n\t\tstringstream distDesc;\n\t\tdistDesc << \"Distance function: \" << DIST_EUCLIDEAN << \", \" << DIST_COSINE << \", or \" << DIST_JACCARD;\n\t\toptions_description desc{\"eval_embedding options\"};\n\t\tdesc.add_options()\n\t\t\t(\"help,h\", \"Show this usage message\")\n\t\t\t(\"posfile\", value<string>(), \"Input file containing dataset\")\n\t\t\t(\"ref\", value<string>(), \"Input embedding of reference subset\")\n\t\t\t(\"num_pts\", value<size_t>()->default_value(0), \"Embed at most this many randomly-selected points\")\n\t\t\t(\"dist\", value<string>()->default_value(\"EUCLIDEAN\"), distDesc.str().c_str())\n\t\t\t(\"soe_cmp\", value<string>()->default_value(\"\"), \"Use SOE with the specified triples after the shell embedding\")\n\t\t\t(\"embedding\", value<string>(), \"Output file for the embedding\")\n\t\t\t(\"order\", value<string>(), \"Output file for the point embedding order and timing\")\n\t\t\t(\"anchors\", value<size_t>()->default_value(0), \"Number of anchors to use\")\n\t\t\t(\"noise\", value<double>()->default_value(0), \"Prob. of flipping a comparison outcome\")\n\t\t\t;\n\n\t\tvariables_map vm;\n\t\tstore(parse_command_line(argc, argv, desc), vm);\n\t\tnotify(vm);\n\n\t\tbool valid = true;\n\t\tif (vm.count(\"help\")) {\n\t\t\tcerr << desc << endl;\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!vm.count(\"posfile\")) {\n\t\t\tcerr << \"--posfile is required\" << endl;\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!vm.count(\"ref\")) {\n\t\t\tcerr << \"--ref is required\" << endl;\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!vm.count(\"embedding\")) {\n\t\t\tcerr << \"--embedding is required\" << endl;\n\t\t\tvalid = false;\n\t\t}\n\t\tif (!vm.count(\"order\")) {\n\t\t\tcerr << \"--order is required\" << endl;\n\t\t\tvalid = false;\n\t\t}\n\t\tif (valid) {\n\t\t\treturn run_embed_from_ref(\n\t\t\t\tvm[\"posfile\"].as<string>(),\n\t\t\t\tvm[\"ref\"].as<string>(),\n\t\t\t\tvm[\"num_pts\"].as<size_t>(),\n\t\t\t\tvm[\"dist\"].as<string>(),\n\t\t\t\tvm[\"soe_cmp\"].as<string>(),\n\t\t\t\tvm[\"embedding\"].as<string>(),\n\t\t\t\tvm[\"order\"].as<string>(),\n\t\t\t\tvm[\"anchors\"].as<size_t>(),\n\t\t\t\tvm[\"noise\"].as<double>());\n\t\t}\n\t} catch (const error &ex) {\n\t\tcerr << ex.what() << endl;\n\t}\n\treturn 1;\n}\n", "meta": {"hexsha": "5e18cae83261a2f74d61aa2188b01f7af6fd0947", "size": 19776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/embed_from_ref/embed_from_ref.cpp", "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": "src/tools/embed_from_ref/embed_from_ref.cpp", "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": "src/tools/embed_from_ref/embed_from_ref.cpp", "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": 30.3778801843, "max_line_length": 114, "alphanum_fraction": 0.6499797735, "num_tokens": 5886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.025957359364135856, "lm_q1q2_score": 0.011464664929474698}}
{"text": "#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/mpi/collectives/gather.hpp>\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/environment.hpp>\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n#include <vector>\n\ntemplate <typename T> class Centroid {\npublic:\n  T _mean;\n  T _weight;\n  T _meansq;\n  Centroid() : Centroid(0.0, 0.0, 0.0) {}\n  Centroid(T mean) : Centroid(mean, 1.0, mean * mean) {}\n  Centroid(T mean, T weight, T meansq)\n      : _mean(mean), _weight(weight), _meansq(meansq) {}\n\n  inline T mean() const { return _mean; }\n  inline T weight() const  { return _weight; }\n  inline T meansq() const { return _meansq; }\n  inline void add(const Centroid<T> &c) {\n    _weight += c._weight;\n    _mean += c._weight * (c._mean - _mean) / _weight;\n    _meansq += c._meansq;\n  }\n};\n\nstd::ostream &operator<<(std::ostream &stream, const Centroid<float> &centroid) {\n  stream << \"(\" << centroid.mean() << \", \" << centroid.weight() << \", \"\n         << centroid.meansq() << \")\\n\";\n  return stream;\n}\n\nnamespace boost {\nnamespace serialization {\ntemplate <class A>\nvoid serialize(A &ar, Centroid<float> &c, const unsigned int version) {\n  ar &c._mean;\n  ar &c._weight;\n  ar &c._meansq;\n}\n} // namespace serialization\n} // namespace boost\n\nnamespace bmpi = boost::mpi;\n\nclass Distributor {\n  const bmpi::environment env;\n\npublic:\n  const bmpi::communicator world;\n  const int rank;\n  const int size;\n  inline bool isMaster() { return rank == 0; }\n  Distributor(int argc, char **argv)\n      : env(argc, argv), world(), rank(world.rank()), size(world.size()) {}\n};\n\nint main(int argc, char **argv) {\n  Distributor dist(argc, argv);\n\n  Centroid<float> centroid(dist.rank * 10.0);\n\n  if (dist.isMaster()) {\n    std::vector<Centroid<float>> list;\n    bmpi::gather(dist.world, centroid, list, 0);\n    for (auto c : list) {\n      std::cout << c;\n    }\n  } else {\n    bmpi::gather(dist.world, centroid, 0);\n  }\n}\n", "meta": {"hexsha": "2ea2a20ead76ae380d19aa9b208a79c39f787a1f", "size": 1971, "ext": "cc", "lang": "C++", "max_stars_repo_path": "chapter-multi-process/exp-5/exp-5.cc", "max_stars_repo_name": "Mark1626/road-to-plus-plus", "max_stars_repo_head_hexsha": "500db757051e32e6ccd144b70171c826527610d4", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-04T12:41:16.000Z", "max_issues_repo_path": "chapter-multi-process/exp-5/exp-5.cc", "max_issues_repo_name": "Mark1626/road-to-plus-plus", "max_issues_repo_head_hexsha": "500db757051e32e6ccd144b70171c826527610d4", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter-multi-process/exp-5/exp-5.cc", "max_forks_repo_name": "Mark1626/road-to-plus-plus", "max_forks_repo_head_hexsha": "500db757051e32e6ccd144b70171c826527610d4", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5974025974, "max_line_length": 81, "alphanum_fraction": 0.6478944698, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.02405355346285842, "lm_q1q2_score": 0.011463434116170538}}
{"text": "/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// (C) Copyright Ion Gaztanaga  2007-2014\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//          http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// See http://www.boost.org/libs/intrusive for documentation.\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n// The implementation of splay trees is based on the article and code published\r\n// in C++ Users Journal \"Implementing Splay Trees in C++\" (September 1, 2005).\r\n//\r\n// The splay code has been modified and (supposedly) improved by Ion Gaztanaga.\r\n//\r\n// Here is the copyright notice of the original file containing the splay code:\r\n//\r\n//  splay_tree.h -- implementation of a STL compatible splay tree.\r\n//\r\n//  Copyright (c) 2004 Ralf Mattethat\r\n//\r\n//  Permission to copy, use, modify, sell and distribute this software\r\n//  is granted provided this copyright notice appears in all copies.\r\n//  This software is provided \"as is\" without express or implied\r\n//  warranty, and with no claim as to its suitability for any purpose.\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n#ifndef BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\r\n#define BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\r\n\r\n#include <boost/intrusive/detail/config_begin.hpp>\r\n#include <boost/intrusive/intrusive_fwd.hpp>\r\n#include <boost/intrusive/detail/assert.hpp>\r\n#include <boost/intrusive/detail/algo_type.hpp>\r\n#include <boost/intrusive/detail/uncast.hpp>\r\n#include <boost/intrusive/bstree_algorithms.hpp>\r\n\r\n#include <cstddef>\r\n\r\n#if defined(BOOST_HAS_PRAGMA_ONCE)\r\n#  pragma once\r\n#endif\r\n\r\nnamespace boost {\r\nnamespace intrusive {\r\n\r\n/// @cond\r\nnamespace detail {\r\n\r\ntemplate<class NodeTraits>\r\nstruct splaydown_assemble_and_fix_header\r\n{\r\n   typedef typename NodeTraits::node_ptr node_ptr;\r\n\r\n   splaydown_assemble_and_fix_header(const node_ptr & t, const node_ptr & header, const node_ptr &leftmost, const node_ptr &rightmost)\r\n      : t_(t)\r\n      , null_node_(header)\r\n      , l_(null_node_)\r\n      , r_(null_node_)\r\n      , leftmost_(leftmost)\r\n      , rightmost_(rightmost)\r\n   {}\r\n\r\n   ~splaydown_assemble_and_fix_header()\r\n   {\r\n      this->assemble();\r\n\r\n      //Now recover the original header except for the\r\n      //splayed root node.\r\n      //\"t_\" is the current root and \"null_node_\" is the header node\r\n      NodeTraits::set_parent(null_node_, t_);\r\n      NodeTraits::set_parent(t_, null_node_);\r\n      //Recover leftmost/rightmost pointers\r\n      NodeTraits::set_left (null_node_, leftmost_);\r\n      NodeTraits::set_right(null_node_, rightmost_);\r\n   }\r\n\r\n   private:\r\n\r\n   void assemble()\r\n   {\r\n      //procedure assemble;\r\n      //    left(r), right(l) := right(t), left(t);\r\n      //    left(t), right(t) := right(null), left(null);\r\n      //end assemble;\r\n      {  //    left(r), right(l) := right(t), left(t);\r\n\r\n         node_ptr const old_t_left  = NodeTraits::get_left(t_);\r\n         node_ptr const old_t_right = NodeTraits::get_right(t_);\r\n         NodeTraits::set_right(l_, old_t_left);\r\n         NodeTraits::set_left (r_, old_t_right);\r\n         if(old_t_left){\r\n            NodeTraits::set_parent(old_t_left, l_);\r\n         }\r\n         if(old_t_right){\r\n            NodeTraits::set_parent(old_t_right, r_);\r\n         }\r\n      }\r\n      {  //    left(t), right(t) := right(null), left(null);\r\n         node_ptr const null_right = NodeTraits::get_right(null_node_);\r\n         node_ptr const null_left  = NodeTraits::get_left(null_node_);\r\n         NodeTraits::set_left (t_, null_right);\r\n         NodeTraits::set_right(t_, null_left);\r\n         if(null_right){\r\n            NodeTraits::set_parent(null_right, t_);\r\n         }\r\n         if(null_left){\r\n            NodeTraits::set_parent(null_left, t_);\r\n         }\r\n      }\r\n   }\r\n\r\n   public:\r\n   node_ptr t_, null_node_, l_, r_, leftmost_, rightmost_;\r\n};\r\n\r\n}  //namespace detail {\r\n/// @endcond\r\n\r\n//!   A splay tree is an implementation of a binary search tree. The tree is\r\n//!   self balancing using the splay algorithm as described in\r\n//!\r\n//!      \"Self-Adjusting Binary Search Trees\r\n//!      by Daniel Dominic Sleator and Robert Endre Tarjan\r\n//!      AT&T Bell Laboratories, Murray Hill, NJ\r\n//!      Journal of the ACM, Vol 32, no 3, July 1985, pp 652-686\r\n//!\r\n//! splaytree_algorithms is configured with a NodeTraits class, which encapsulates the\r\n//! information about the node to be manipulated. NodeTraits must support the\r\n//! following interface:\r\n//!\r\n//! <b>Typedefs</b>:\r\n//!\r\n//! <tt>node</tt>: The type of the node that forms the binary search tree\r\n//!\r\n//! <tt>node_ptr</tt>: A pointer to a node\r\n//!\r\n//! <tt>const_node_ptr</tt>: A pointer to a const node\r\n//!\r\n//! <b>Static functions</b>:\r\n//!\r\n//! <tt>static node_ptr get_parent(const_node_ptr n);</tt>\r\n//!\r\n//! <tt>static void set_parent(node_ptr n, node_ptr parent);</tt>\r\n//!\r\n//! <tt>static node_ptr get_left(const_node_ptr n);</tt>\r\n//!\r\n//! <tt>static void set_left(node_ptr n, node_ptr left);</tt>\r\n//!\r\n//! <tt>static node_ptr get_right(const_node_ptr n);</tt>\r\n//!\r\n//! <tt>static void set_right(node_ptr n, node_ptr right);</tt>\r\ntemplate<class NodeTraits>\r\nclass splaytree_algorithms\r\n   #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n   : public bstree_algorithms<NodeTraits>\r\n   #endif\r\n{\r\n   /// @cond\r\n   private:\r\n   typedef bstree_algorithms<NodeTraits> bstree_algo;\r\n   /// @endcond\r\n\r\n   public:\r\n   typedef typename NodeTraits::node            node;\r\n   typedef NodeTraits                           node_traits;\r\n   typedef typename NodeTraits::node_ptr        node_ptr;\r\n   typedef typename NodeTraits::const_node_ptr  const_node_ptr;\r\n\r\n   //! This type is the information that will be\r\n   //! filled by insert_unique_check\r\n   typedef typename bstree_algo::insert_commit_data insert_commit_data;\r\n\r\n   public:\r\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::get_header(const const_node_ptr&)\r\n   static node_ptr get_header(const const_node_ptr & n);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::begin_node\r\n   static node_ptr begin_node(const const_node_ptr & header);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::end_node\r\n   static node_ptr end_node(const const_node_ptr & header);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::swap_tree\r\n   static void swap_tree(const node_ptr & header1, const node_ptr & header2);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::swap_nodes(const node_ptr&,const node_ptr&)\r\n   static void swap_nodes(const node_ptr & node1, const node_ptr & node2);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::swap_nodes(const node_ptr&,const node_ptr&,const node_ptr&,const node_ptr&)\r\n   static void swap_nodes(const node_ptr & node1, const node_ptr & header1, const node_ptr & node2, const node_ptr & header2);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::replace_node(const node_ptr&,const node_ptr&)\r\n   static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & new_node);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::replace_node(const node_ptr&,const node_ptr&,const node_ptr&)\r\n   static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & header, const node_ptr & new_node);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::unlink(const node_ptr&)\r\n   static void unlink(const node_ptr & node);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::unlink_leftmost_without_rebalance\r\n   static node_ptr unlink_leftmost_without_rebalance(const node_ptr & header);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::unique(const const_node_ptr&)\r\n   static bool unique(const const_node_ptr & node);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::size(const const_node_ptr&)\r\n   static std::size_t size(const const_node_ptr & header);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::next_node(const node_ptr&)\r\n   static node_ptr next_node(const node_ptr & node);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::prev_node(const node_ptr&)\r\n   static node_ptr prev_node(const node_ptr & node);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::init(const node_ptr&)\r\n   static void init(const node_ptr & node);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::init_header(const node_ptr&)\r\n   static void init_header(const node_ptr & header);\r\n\r\n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::erase(const node_ptr&,const node_ptr&)\r\n   //! Additional notes: the previous node of z is splayed to speed up range deletions.\r\n   static void erase(const node_ptr & header, const node_ptr & z)\r\n   {\r\n      //posibility 1\r\n      if(NodeTraits::get_left(z)){\r\n         splay_up(bstree_algo::prev_node(z), header);\r\n      }\r\n\r\n      //possibility 2\r\n      //if(NodeTraits::get_left(z)){\r\n      //   node_ptr l = NodeTraits::get_left(z);\r\n      //   splay_up(l, header);\r\n      //}\r\n\r\n      //if(NodeTraits::get_left(z)){\r\n      //   node_ptr l = bstree_algo::prev_node(z);\r\n      //   splay_up_impl(l, z);\r\n      //}\r\n\r\n      //possibility 4\r\n      //splay_up(z, header);\r\n\r\n      bstree_algo::erase(header, z);\r\n   }\r\n\r\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::clone(const const_node_ptr&,const node_ptr&,Cloner,Disposer)\r\n   template <class Cloner, class Disposer>\r\n   static void clone\r\n      (const const_node_ptr & source_header, const node_ptr & target_header, Cloner cloner, Disposer disposer);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::clear_and_dispose(const node_ptr&,Disposer)\r\n   template<class Disposer>\r\n   static void clear_and_dispose(const node_ptr & header, Disposer disposer);\r\n\r\n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::count(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional notes: an element with key `key` is splayed.\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::size_t count\r\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {\r\n      std::pair<node_ptr, node_ptr> ret = equal_range(header, key, comp);\r\n      std::size_t n = 0;\r\n      while(ret.first != ret.second){\r\n         ++n;\r\n         ret.first = next_node(ret.first);\r\n      }\r\n      return n;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::count(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional note: no splaying is performed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::size_t count\r\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {  return bstree_algo::count(header, key, comp);  }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::lower_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional notes: the first node of the range is splayed.\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr lower_bound\r\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {\r\n      splay_down(detail::uncast(header), key, comp);\r\n      node_ptr y = bstree_algo::lower_bound(header, key, comp);\r\n      //splay_up(y, detail::uncast(header));\r\n      return y;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::lower_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional note: no splaying is performed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr lower_bound\r\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {  return bstree_algo::lower_bound(header, key, comp);  }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::upper_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional notes: the first node of the range is splayed.\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr upper_bound\r\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {\r\n      splay_down(detail::uncast(header), key, comp);\r\n      node_ptr y = bstree_algo::upper_bound(header, key, comp);\r\n      //splay_up(y, detail::uncast(header));\r\n      return y;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::upper_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional note: no splaying is performed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr upper_bound\r\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {  return bstree_algo::upper_bound(header, key, comp);  }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::find(const const_node_ptr&, const KeyType&,KeyNodePtrCompare)\r\n   //! Additional notes: the found node of the lower bound is splayed.\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr find\r\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {\r\n      splay_down(detail::uncast(header), key, comp);\r\n      return bstree_algo::find(header, key, comp);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::find(const const_node_ptr&, const KeyType&,KeyNodePtrCompare)\r\n   //! Additional note: no splaying is performed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr find\r\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {  return bstree_algo::find(header, key, comp);  }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::equal_range(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional notes: the first node of the range is splayed.\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, node_ptr> equal_range\r\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {\r\n      splay_down(detail::uncast(header), key, comp);\r\n      std::pair<node_ptr, node_ptr> ret = bstree_algo::equal_range(header, key, comp);\r\n      //splay_up(ret.first, detail::uncast(header));\r\n      return ret;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::equal_range(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional note: no splaying is performed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, node_ptr> equal_range\r\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {  return bstree_algo::equal_range(header, key, comp);  }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::lower_bound_range(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional notes: the first node of the range is splayed.\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, node_ptr> lower_bound_range\r\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {\r\n      splay_down(detail::uncast(header), key, comp);\r\n      std::pair<node_ptr, node_ptr> ret = bstree_algo::lower_bound_range(header, key, comp);\r\n      //splay_up(ret.first, detail::uncast(header));\r\n      return ret;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::lower_bound_range(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\r\n   //! Additional note: no splaying is performed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, node_ptr> lower_bound_range\r\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\r\n   {  return bstree_algo::lower_bound_range(header, key, comp);  }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::bounded_range(const const_node_ptr&,const KeyType&,const KeyType&,KeyNodePtrCompare,bool,bool)\r\n   //! Additional notes: the first node of the range is splayed.\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, node_ptr> bounded_range\r\n      (const node_ptr & header, const KeyType &lower_key, const KeyType &upper_key, KeyNodePtrCompare comp\r\n      , bool left_closed, bool right_closed)\r\n   {\r\n      splay_down(detail::uncast(header), lower_key, comp);\r\n      std::pair<node_ptr, node_ptr> ret =\r\n         bstree_algo::bounded_range(header, lower_key, upper_key, comp, left_closed, right_closed);\r\n      //splay_up(ret.first, detail::uncast(header));\r\n      return ret;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::bounded_range(const const_node_ptr&,const KeyType&,const KeyType&,KeyNodePtrCompare,bool,bool)\r\n   //! Additional note: no splaying is performed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, node_ptr> bounded_range\r\n      (const const_node_ptr & header, const KeyType &lower_key, const KeyType &upper_key, KeyNodePtrCompare comp\r\n      , bool left_closed, bool right_closed)\r\n   {  return bstree_algo::bounded_range(header, lower_key, upper_key, comp, left_closed, right_closed);  }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal_upper_bound(const node_ptr&,const node_ptr&,NodePtrCompare)\r\n   //! Additional note: the inserted node is splayed\r\n   template<class NodePtrCompare>\r\n   static node_ptr insert_equal_upper_bound\r\n      (const node_ptr & header, const node_ptr & new_node, NodePtrCompare comp)\r\n   {\r\n      splay_down(header, new_node, comp);\r\n      return bstree_algo::insert_equal_upper_bound(header, new_node, comp);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal_lower_bound(const node_ptr&,const node_ptr&,NodePtrCompare)\r\n   //! Additional note: the inserted node is splayed\r\n   template<class NodePtrCompare>\r\n   static node_ptr insert_equal_lower_bound\r\n      (const node_ptr & header, const node_ptr & new_node, NodePtrCompare comp)\r\n   {\r\n      splay_down(header, new_node, comp);\r\n      return bstree_algo::insert_equal_lower_bound(header, new_node, comp);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal(const node_ptr&,const node_ptr&,const node_ptr&,NodePtrCompare)\r\n   //! Additional note: the inserted node is splayed\r\n   template<class NodePtrCompare>\r\n   static node_ptr insert_equal\r\n      (const node_ptr & header, const node_ptr & hint, const node_ptr & new_node, NodePtrCompare comp)\r\n   {\r\n      splay_down(header, new_node, comp);\r\n      return bstree_algo::insert_equal(header, hint, new_node, comp);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_before(const node_ptr&,const node_ptr&,const node_ptr&)\r\n   //! Additional note: the inserted node is splayed\r\n   static node_ptr insert_before\r\n      (const node_ptr & header, const node_ptr & pos, const node_ptr & new_node)\r\n   {\r\n      bstree_algo::insert_before(header, pos, new_node);\r\n      splay_up(new_node, header);\r\n      return new_node;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::push_back(const node_ptr&,const node_ptr&)\r\n   //! Additional note: the inserted node is splayed\r\n   static void push_back(const node_ptr & header, const node_ptr & new_node)\r\n   {\r\n      bstree_algo::push_back(header, new_node);\r\n      splay_up(new_node, header);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::push_front(const node_ptr&,const node_ptr&)\r\n   //! Additional note: the inserted node is splayed\r\n   static void push_front(const node_ptr & header, const node_ptr & new_node)\r\n   {\r\n      bstree_algo::push_front(header, new_node);\r\n      splay_up(new_node, header);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_check(const const_node_ptr&,const KeyType&,KeyNodePtrCompare,insert_commit_data&)\r\n   //! Additional note: nodes with the given key are splayed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, bool> insert_unique_check\r\n      (const node_ptr & header, const KeyType &key\r\n      ,KeyNodePtrCompare comp, insert_commit_data &commit_data)\r\n   {\r\n      splay_down(header, key, comp);\r\n      return bstree_algo::insert_unique_check(header, key, comp, commit_data);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_check(const const_node_ptr&,const node_ptr&,const KeyType&,KeyNodePtrCompare,insert_commit_data&)\r\n   //! Additional note: nodes with the given key are splayed\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static std::pair<node_ptr, bool> insert_unique_check\r\n      (const node_ptr & header, const node_ptr &hint, const KeyType &key\r\n      ,KeyNodePtrCompare comp, insert_commit_data &commit_data)\r\n   {\r\n      splay_down(header, key, comp);\r\n      return bstree_algo::insert_unique_check(header, hint, key, comp, commit_data);\r\n   }\r\n\r\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_commit(const node_ptr&,const node_ptr&,const insert_commit_data&)\r\n   static void insert_unique_commit\r\n      (const node_ptr & header, const node_ptr & new_value, const insert_commit_data &commit_data);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::is_header\r\n   static bool is_header(const const_node_ptr & p);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::rebalance\r\n   static void rebalance(const node_ptr & header);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree_algorithms::rebalance_subtree\r\n   static node_ptr rebalance_subtree(const node_ptr & old_root);\r\n\r\n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n\r\n   // bottom-up splay, use data_ as parent for n    | complexity : logarithmic    | exception : nothrow\r\n   static void splay_up(const node_ptr & node, const node_ptr & header)\r\n   {  priv_splay_up<true>(node, header); }\r\n\r\n   // top-down splay | complexity : logarithmic    | exception : strong, note A\r\n   template<class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr splay_down(const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool *pfound = 0)\r\n   {  return priv_splay_down<true>(header, key, comp, pfound);   }\r\n\r\n   private:\r\n\r\n   /// @cond\r\n\r\n   // bottom-up splay, use data_ as parent for n    | complexity : logarithmic    | exception : nothrow\r\n   template<bool SimpleSplay>\r\n   static void priv_splay_up(const node_ptr & node, const node_ptr & header)\r\n   {\r\n      // If (node == header) do a splay for the right most node instead\r\n      // this is to boost performance of equal_range/count on equivalent containers in the case\r\n      // where there are many equal elements at the end\r\n      node_ptr n((node == header) ? NodeTraits::get_right(header) : node);\r\n      node_ptr t(header);\r\n\r\n      if( n == t ) return;\r\n\r\n      for( ;; ){\r\n         node_ptr p(NodeTraits::get_parent(n));\r\n         node_ptr g(NodeTraits::get_parent(p));\r\n\r\n         if( p == t )   break;\r\n\r\n         if( g == t ){\r\n            // zig\r\n            rotate(n);\r\n         }\r\n         else if ((NodeTraits::get_left(p) == n && NodeTraits::get_left(g) == p)    ||\r\n                  (NodeTraits::get_right(p) == n && NodeTraits::get_right(g) == p)  ){\r\n            // zig-zig\r\n            rotate(p);\r\n            rotate(n);\r\n         }\r\n         else {\r\n            // zig-zag\r\n            rotate(n);\r\n            if(!SimpleSplay){\r\n               rotate(n);\r\n            }\r\n         }\r\n      }\r\n   }\r\n\r\n   template<bool SimpleSplay, class KeyType, class KeyNodePtrCompare>\r\n   static node_ptr priv_splay_down(const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool *pfound = 0)\r\n   {\r\n      //Most splay tree implementations use a dummy/null node to implement.\r\n      //this function. This has some problems for a generic library like Intrusive:\r\n      //\r\n      // * The node might not have a default constructor.\r\n      // * The default constructor could throw.\r\n      //\r\n      //We already have a header node. Leftmost and rightmost nodes of the tree\r\n      //are not changed when splaying (because the invariants of the tree don't\r\n      //change) We can back up them, use the header as the null node and\r\n      //reassign old values after the function has been completed.\r\n      node_ptr const old_root  = NodeTraits::get_parent(header);\r\n      node_ptr const leftmost  = NodeTraits::get_left(header);\r\n      node_ptr const rightmost = NodeTraits::get_right(header);\r\n      if(leftmost == rightmost){ //Empty or unique node\r\n         if(pfound){\r\n            *pfound = old_root && !comp(key, old_root) && !comp(old_root, key);\r\n         }\r\n         return old_root ? old_root : header;\r\n      }\r\n      else{\r\n         //Initialize \"null node\" (the header in our case)\r\n         NodeTraits::set_left (header, node_ptr());\r\n         NodeTraits::set_right(header, node_ptr());\r\n         //Class that will backup leftmost/rightmost from header, commit the assemble(),\r\n         //and will restore leftmost/rightmost to header even if \"comp\" throws\r\n         detail::splaydown_assemble_and_fix_header<NodeTraits> commit(old_root, header, leftmost, rightmost);\r\n         bool found = false;\r\n\r\n         for( ;; ){\r\n            if(comp(key, commit.t_)){\r\n               node_ptr const t_left = NodeTraits::get_left(commit.t_);\r\n               if(!t_left)\r\n                  break;\r\n               if(comp(key, t_left)){\r\n                  bstree_algo::rotate_right_no_parent_fix(commit.t_, t_left);\r\n                  commit.t_ = t_left;\r\n                  if( !NodeTraits::get_left(commit.t_) )\r\n                     break;\r\n                  link_right(commit.t_, commit.r_);\r\n               }\r\n               else{\r\n                  link_right(commit.t_, commit.r_);\r\n                  if(!SimpleSplay && comp(t_left, key)){\r\n                     if( !NodeTraits::get_right(commit.t_) )\r\n                        break;\r\n                     link_left(commit.t_, commit.l_);\r\n                  }\r\n               }\r\n            }\r\n            else if(comp(commit.t_, key)){\r\n               node_ptr const t_right = NodeTraits::get_right(commit.t_);\r\n               if(!t_right)\r\n                  break;\r\n\r\n               if(comp(t_right, key)){\r\n                     bstree_algo::rotate_left_no_parent_fix(commit.t_, t_right);\r\n                     commit.t_ = t_right;\r\n                     if( !NodeTraits::get_right(commit.t_) )\r\n                        break;\r\n                     link_left(commit.t_, commit.l_);\r\n               }\r\n               else{\r\n                  link_left(commit.t_, commit.l_);\r\n                  if(!SimpleSplay && comp(key, t_right)){\r\n                     if( !NodeTraits::get_left(commit.t_) )\r\n                        break;\r\n                     link_right(commit.t_, commit.r_);\r\n                  }\r\n               }\r\n            }\r\n            else{\r\n               found = true;\r\n               break;\r\n            }\r\n         }\r\n\r\n         //commit.~splaydown_assemble_and_fix_header<NodeTraits>() will first\r\n         //\"assemble()\" + link the new root & recover header's leftmost & rightmost\r\n         if(pfound){\r\n            *pfound = found;\r\n         }\r\n         return commit.t_;\r\n      }\r\n   }\r\n\r\n   // break link to left child node and attach it to left tree pointed to by l   | complexity : constant | exception : nothrow\r\n   static void link_left(node_ptr & t, node_ptr & l)\r\n   {\r\n      //procedure link_left;\r\n      //    t, l, right(l) := right(t), t, t\r\n      //end link_left\r\n      NodeTraits::set_right(l, t);\r\n      NodeTraits::set_parent(t, l);\r\n      l = t;\r\n      t = NodeTraits::get_right(t);\r\n   }\r\n\r\n   // break link to right child node and attach it to right tree pointed to by r | complexity : constant | exception : nothrow\r\n   static void link_right(node_ptr & t, node_ptr & r)\r\n   {\r\n      //procedure link_right;\r\n      //    t, r, left(r) := left(t), t, t\r\n      //end link_right;\r\n      NodeTraits::set_left(r, t);\r\n      NodeTraits::set_parent(t, r);\r\n      r = t;\r\n      t = NodeTraits::get_left(t);\r\n   }\r\n\r\n   // rotate n with its parent                     | complexity : constant    | exception : nothrow\r\n   static void rotate(const node_ptr & n)\r\n   {\r\n      //procedure rotate_left;\r\n      //    t, right(t), left(right(t)) := right(t), left(right(t)), t\r\n      //end rotate_left;\r\n      node_ptr p = NodeTraits::get_parent(n);\r\n      node_ptr g = NodeTraits::get_parent(p);\r\n      //Test if g is header before breaking tree\r\n      //invariants that would make is_header invalid\r\n      bool g_is_header = bstree_algo::is_header(g);\r\n\r\n      if(NodeTraits::get_left(p) == n){\r\n         NodeTraits::set_left(p, NodeTraits::get_right(n));\r\n         if(NodeTraits::get_left(p))\r\n            NodeTraits::set_parent(NodeTraits::get_left(p), p);\r\n         NodeTraits::set_right(n, p);\r\n      }\r\n      else{ // must be ( p->right == n )\r\n         NodeTraits::set_right(p, NodeTraits::get_left(n));\r\n         if(NodeTraits::get_right(p))\r\n            NodeTraits::set_parent(NodeTraits::get_right(p), p);\r\n         NodeTraits::set_left(n, p);\r\n      }\r\n\r\n      NodeTraits::set_parent(p, n);\r\n      NodeTraits::set_parent(n, g);\r\n\r\n      if(g_is_header){\r\n         if(NodeTraits::get_parent(g) == p)\r\n            NodeTraits::set_parent(g, n);\r\n         else{//must be ( g->right == p )\r\n            BOOST_INTRUSIVE_INVARIANT_ASSERT(false);\r\n            NodeTraits::set_right(g, n);\r\n         }\r\n      }\r\n      else{\r\n         if(NodeTraits::get_left(g) == p)\r\n            NodeTraits::set_left(g, n);\r\n         else  //must be ( g->right == p )\r\n            NodeTraits::set_right(g, n);\r\n      }\r\n   }\r\n\r\n   /// @endcond\r\n};\r\n\r\n/// @cond\r\n\r\ntemplate<class NodeTraits>\r\nstruct get_algo<SplayTreeAlgorithms, NodeTraits>\r\n{\r\n   typedef splaytree_algorithms<NodeTraits> type;\r\n};\r\n\r\ntemplate <class ValueTraits, class NodePtrCompare, class ExtraChecker>\r\nstruct get_node_checker<SplayTreeAlgorithms, ValueTraits, NodePtrCompare, ExtraChecker>\r\n{\r\n   typedef detail::bstree_node_checker<ValueTraits, NodePtrCompare, ExtraChecker> type;\r\n};\r\n\r\n/// @endcond\r\n\r\n} //namespace intrusive\r\n} //namespace boost\r\n\r\n#include <boost/intrusive/detail/config_end.hpp>\r\n\r\n#endif //BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\r\n", "meta": {"hexsha": "a02a91f87d9b2ddb395f0860d635ec72ecc59ef0", "size": 30244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "build/lua-reader/include/boost-1.60.0/boost/intrusive/splaytree_algorithms.hpp", "max_stars_repo_name": "LazyPlanet/MX-Client", "max_stars_repo_head_hexsha": "07ac4ada4507fb7fd341094d733204f8c0170491", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-05-29T19:17:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:47:48.000Z", "max_issues_repo_path": "build/lua-reader/include/boost-1.60.0/boost/intrusive/splaytree_algorithms.hpp", "max_issues_repo_name": "LazyPlanet/MX-Client", "max_issues_repo_head_hexsha": "07ac4ada4507fb7fd341094d733204f8c0170491", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-24T10:34:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-24T10:34:41.000Z", "max_forks_repo_path": "build/lua-reader/include/boost-1.60.0/boost/intrusive/splaytree_algorithms.hpp", "max_forks_repo_name": "LazyPlanet/MX-Client", "max_forks_repo_head_hexsha": "07ac4ada4507fb7fd341094d733204f8c0170491", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-03-01T14:34:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-14T12:13:55.000Z", "avg_line_length": 41.543956044, "max_line_length": 167, "alphanum_fraction": 0.6519640259, "num_tokens": 7311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.04023794363068103, "lm_q1q2_score": 0.011450753216309052}}
{"text": "#include <deque>\n#include <unordered_set>\n#include <set>\n#include <iostream>\n#include <memory>\n#include <algorithm>\n\n#include <boost/log/trivial.hpp>\n\n#include \"de_bruijn/graph.h\"\n#include \"noise_filtering.h\"\n\nusing namespace debruijn;\n\n// Define a debruijn graph with s-mers of genes as nodes\ndebruijn::Graph::Graph(uint8_t s)\n    : next_id(0)\n    , size(s)\n{\n    nodes.reserve(200000);\n};\n\ndebruijn::Graph::~Graph() { nodes.clear(); }\n\n// Add a node in dbg corresponding to a fixed size deque of pangenome graph\n// node/orientation ids and labelled with the read_ids which cover it\nOrientedNodePtr debruijn::Graph::add_node(\n    const std::deque<uint_least32_t>& node_ids, uint32_t read_id)\n{\n    const bool correct_number_of_nodes_to_add = node_ids.size() == size;\n    if (!correct_number_of_nodes_to_add) {\n        fatal_error(\"Error adding node to de Bruijn Graph: expected node of size \",\n            size, \", received node of size \", node_ids.size());\n    }\n\n    if (node_hash.find(node_ids) != node_hash.end()) {\n        nodes[node_hash[node_ids]]->read_ids.insert(read_id);\n        return make_pair(nodes[node_hash[node_ids]], true);\n    } else if (node_hash.find(rc_hashed_node_ids(node_ids)) != node_hash.end()) {\n        auto rc = rc_hashed_node_ids(node_ids);\n        nodes[node_hash[rc]]->read_ids.insert(read_id);\n        return make_pair(nodes[node_hash[rc]], false);\n    }\n\n    NodePtr n;\n    n = std::make_shared<Node>(next_id, node_ids, read_id);\n    nodes[next_id] = n;\n    node_hash[node_ids] = next_id;\n\n    if (next_id % 1000 == 0) {\n        BOOST_LOG_TRIVIAL(debug) << \"added node \" << next_id;\n    }\n\n    next_id++;\n    return make_pair(n, true);\n}\n\n// An edge is valid if the kmer of node/orientation ids for from\n// overlaps the first k-1 nodes/orientations of to\n// Note that forward and reverse complement kmers are treated as\n// equal, but an edge is only valid if the orientation they were found\n// in in the read allows the overlap\nbool edge_is_valid(OrientedNodePtr from, OrientedNodePtr to)\n{\n    std::deque<uint_least32_t> hashed_node_ids_from = from.first->hashed_node_ids;\n    std::deque<uint_least32_t> hashed_node_ids_to = to.first->hashed_node_ids;\n    if (!from.second) {\n        hashed_node_ids_from = rc_hashed_node_ids(hashed_node_ids_from);\n    }\n\n    if (!to.second) {\n        hashed_node_ids_to = rc_hashed_node_ids(hashed_node_ids_to);\n    }\n\n    return overlap_forwards(hashed_node_ids_from, hashed_node_ids_to);\n}\n\n// Add directed edge between from and to\nvoid debruijn::Graph::add_edge(OrientedNodePtr from, OrientedNodePtr to)\n{\n    const bool nodes_are_valid = from.first != nullptr and to.first != nullptr;\n    if (!nodes_are_valid) {\n        fatal_error(\"Error adding edge to de Bruijn Graph: from or to node is invalid\");\n    }\n\n    if (!edge_is_valid(from, to)) {\n        fatal_error(\"Error adding edge to de Bruijn Graph: edge from \", *from.first,\n            \" to \", *to.first, \" is invalid\");\n    }\n\n    if (from.second\n        and from.first->out_nodes.find(to.first->id) == from.first->out_nodes.end()) {\n        from.first->out_nodes.insert(to.first->id);\n    } else if (!from.second\n        and from.first->in_nodes.find(to.first->id) == from.first->in_nodes.end()) {\n        from.first->in_nodes.insert(to.first->id);\n    }\n\n    if (to.second\n        and to.first->in_nodes.find(from.first->id) == to.first->in_nodes.end()) {\n        to.first->in_nodes.insert(from.first->id);\n    } else if (!to.second\n        and to.first->out_nodes.find(from.first->id) == to.first->out_nodes.end()) {\n        to.first->out_nodes.insert(from.first->id);\n    }\n}\n\n// Remove all mentions of de bruijn node with id given from graph\nvoid debruijn::Graph::remove_node(const uint32_t dbg_node_id)\n{\n    auto it = nodes.find(dbg_node_id);\n    if (it != nodes.end()) {\n        // remove this node from lists of out nodes from other graph nodes\n        for (const auto& n : it->second->out_nodes) {\n            nodes[n]->in_nodes.erase(dbg_node_id);\n            nodes[n]->out_nodes.erase(dbg_node_id);\n        }\n        for (const auto& n : it->second->in_nodes) {\n            nodes[n]->out_nodes.erase(dbg_node_id);\n            nodes[n]->in_nodes.erase(dbg_node_id);\n        }\n\n        // and remove from nodes\n        nodes.erase(dbg_node_id);\n    }\n}\n\n// Remove all copies of read from de bruijn node\nvoid debruijn::Graph::remove_read_from_node(\n    const uint32_t read_id, const uint32_t dbg_node_id)\n{\n    auto it = nodes.find(dbg_node_id);\n    bool found_read_intersect;\n    if (it != nodes.end()) {\n        auto rit = it->second->read_ids.find(read_id);\n        if (rit != it->second->read_ids.end()) {\n            it->second->read_ids.erase(rit);\n\n            // if there are no more reads covering it, remove the node\n            if (it->second->read_ids.empty()) {\n                remove_node(dbg_node_id);\n            } else {\n                // otherwise, remove any outnodes which no longer share a read\n                for (std::unordered_set<uint32_t>::iterator nit\n                     = it->second->out_nodes.begin();\n                     nit != it->second->out_nodes.end();) {\n                    found_read_intersect = false;\n                    for (const auto& r : it->second->read_ids) {\n                        if (nodes[*nit]->read_ids.find(r)\n                            != nodes[*nit]->read_ids.end()) {\n                            found_read_intersect = true;\n                            break;\n                        }\n                    }\n                    if (!found_read_intersect) {\n                        nodes[*nit]->in_nodes.erase(dbg_node_id);\n                        nit = it->second->out_nodes.erase(nit);\n                    } else {\n                        nit++;\n                    }\n                }\n                for (std::unordered_set<uint32_t>::iterator nit\n                     = it->second->in_nodes.begin();\n                     nit != it->second->in_nodes.end();) {\n                    found_read_intersect = false;\n                    for (const auto& r : it->second->read_ids) {\n                        if (nodes[*nit]->read_ids.find(r)\n                            != nodes[*nit]->read_ids.end()) {\n                            found_read_intersect = true;\n                            break;\n                        }\n                    }\n                    if (!found_read_intersect) {\n                        nodes[*nit]->out_nodes.erase(dbg_node_id);\n                        nit = it->second->in_nodes.erase(nit);\n                    } else {\n                        nit++;\n                    }\n                }\n            }\n        }\n    }\n}\n\n// Get the dbg node ids corresponding to leaves\nstd::unordered_set<uint32_t> debruijn::Graph::get_leaves(uint_least32_t covg_thresh)\n{\n    std::unordered_set<uint32_t> s;\n    for (const auto& c : nodes) {\n        BOOST_LOG_TRIVIAL(debug)\n            << \"node \" << *c.second << \" has \" << c.second->out_nodes.size() << \" + \"\n            << c.second->in_nodes.size() << \" outnodes\";\n        if (c.second->read_ids.size() > covg_thresh) {\n            continue;\n        } else if (c.second->out_nodes.size() + c.second->in_nodes.size() <= 1) {\n            s.insert(c.second->id);\n        }\n    }\n    return s;\n}\n\n// Get deques of dbg node ids corresponding to maximal non-branching paths in dbg\nstd::set<std::deque<uint32_t>> debruijn::Graph::get_unitigs()\n{\n    std::set<std::deque<uint32_t>> all_tigs;\n    std::set<uint32_t> seen;\n\n    for (const auto& node_entry : nodes) {\n        const auto& id = node_entry.first;\n        const auto& node_ptr = node_entry.second;\n\n        const bool node_seen = seen.find(id) != seen.end();\n        const bool at_branch\n            = (node_ptr->out_nodes.size() > 1) or (node_ptr->in_nodes.size() > 1);\n        if (node_seen or at_branch)\n            continue;\n\n        std::deque<uint32_t> tig = { id };\n        extend_unitig(tig);\n        for (const auto& other_id : tig)\n            seen.insert(other_id);\n        all_tigs.insert(tig);\n    }\n    return all_tigs;\n}\n\n// Extend a dbg path on either end until reaching a branch point\nvoid debruijn::Graph::extend_unitig(std::deque<uint32_t>& tig)\n{\n    const bool tig_is_empty = (tig.empty());\n    const bool node_is_isolated = (tig.size() == 1\n        and (nodes[tig.back()]->out_nodes.size() + nodes[tig.back()]->in_nodes.size())\n            == 0);\n    if (tig_is_empty or node_is_isolated) {\n        return;\n    }\n\n    bool can_extend = nodes[tig.back()]->out_nodes.size() == 1;\n    bool use_outnodes = true;\n    while (can_extend) {\n\n        if (use_outnodes) {\n            tig.push_back(*nodes[tig.back()]->out_nodes.begin());\n        } else {\n            tig.push_back(*nodes[tig.back()]->in_nodes.begin());\n        }\n\n        if (std::find(nodes[tig.back()]->in_nodes.begin(),\n                nodes[tig.back()]->in_nodes.end(), *----tig.end())\n            != nodes[tig.back()]->in_nodes.end()) {\n            can_extend = nodes[tig.back()]->out_nodes.size() == 1\n                and nodes[tig.back()]->in_nodes.size() <= 1\n                and tig.front() != tig.back();\n            use_outnodes = true;\n        } else if (std::find(nodes[tig.back()]->out_nodes.begin(),\n                       nodes[tig.back()]->out_nodes.end(), *----tig.end())\n            != nodes[tig.back()]->out_nodes.end()) {\n            can_extend = nodes[tig.back()]->in_nodes.size() == 1\n                and nodes[tig.back()]->out_nodes.size() <= 1\n                and tig.front() != tig.back();\n            use_outnodes = false;\n        } else {\n            can_extend = false;\n        }\n    }\n\n    if (tig.size() == 1) {\n        can_extend = nodes[tig.front()]->in_nodes.size() == 1\n            and nodes[tig.front()]->out_nodes.size() <= 1;\n        use_outnodes = false;\n    } else {\n\n        if (std::find(nodes[tig.front()]->in_nodes.begin(),\n                nodes[tig.front()]->in_nodes.end(), *++tig.begin())\n            != nodes[tig.front()]->in_nodes.end()) {\n            can_extend = nodes[tig.front()]->out_nodes.size() == 1\n                and nodes[tig.front()]->in_nodes.size() <= 1\n                and tig.front() != tig.back();\n            use_outnodes = true;\n        } else if (std::find(nodes[tig.front()]->out_nodes.begin(),\n                       nodes[tig.front()]->out_nodes.end(), *++tig.begin())\n            != nodes[tig.front()]->out_nodes.end()) {\n            can_extend = nodes[tig.front()]->in_nodes.size() == 1\n                and nodes[tig.front()]->out_nodes.size() <= 1\n                and tig.front() != tig.back();\n            use_outnodes = false;\n        } else {\n            can_extend = false;\n        }\n    }\n\n    while (can_extend) {\n        if (use_outnodes) {\n            tig.push_front(*nodes[tig.front()]->out_nodes.begin());\n        } else {\n            tig.push_front(*nodes[tig.front()]->in_nodes.begin());\n        }\n\n        if (std::find(nodes[tig.front()]->in_nodes.begin(),\n                nodes[tig.front()]->in_nodes.end(), *++tig.begin())\n            != nodes[tig.front()]->in_nodes.end()) {\n            can_extend = nodes[tig.front()]->out_nodes.size() == 1\n                and nodes[tig.front()]->in_nodes.size() <= 1\n                and tig.front() != tig.back();\n            use_outnodes = true;\n        } else if (std::find(nodes[tig.front()]->out_nodes.begin(),\n                       nodes[tig.front()]->out_nodes.end(), *++tig.begin())\n            != nodes[tig.front()]->out_nodes.end()) {\n            can_extend = nodes[tig.front()]->in_nodes.size() == 1\n                and nodes[tig.front()]->out_nodes.size() <= 1\n                and tig.front() != tig.back();\n            use_outnodes = false;\n        } else {\n            can_extend = false;\n        }\n    }\n\n    while (tig.size() > 1 and tig.front() == tig.back()) {\n        tig.pop_back();\n    }\n\n    std::stringstream tig_ss;\n    for (const auto& n : tig)\n        tig_ss << n << \" \";\n    BOOST_LOG_TRIVIAL(debug) << \"got tig of length \" << tig.size() << \": \"\n                             << tig_ss.str();\n}\n\n// Search the outnodes of node_ptr_to_search for node_ptr_to_find\nbool debruijn::Graph::found_in_out_nodes(\n    const NodePtr node_ptr_to_search, const NodePtr node_ptr_to_find) const\n{\n    for (const auto& i : node_ptr_to_search->out_nodes) {\n        if (*nodes.at(i) == *node_ptr_to_find) {\n            return true;\n        }\n    }\n    return false;\n}\n\n// Search the innodes of node_ptr_to_search for node_ptr_to_find\nbool debruijn::Graph::found_in_in_nodes(\n    const NodePtr node_ptr_to_search, const NodePtr node_ptr_to_find) const\n{\n    for (const auto& i : node_ptr_to_search->in_nodes) {\n        if (*nodes.at(i) == *node_ptr_to_find) {\n            return true;\n        }\n    }\n    return false;\n}\n\n// Graphs are equal if they have nodes corresponding to the same kmer\n// of node/orientations, with outnodes and innodes the same\nbool debruijn::Graph::operator==(const Graph& y) const\n{\n    // want the graphs to have the same nodes, even if\n    // the ids given them is different.\n    if (nodes.size() != y.nodes.size()) {\n        BOOST_LOG_TRIVIAL(debug) << \"different num nodes\";\n        return false;\n    }\n\n    for (const auto& t : nodes) {\n        bool found = false;\n        for (const auto& s : y.nodes) {\n            if (*t.second == *s.second) {\n                found = true;\n\n                // also check the outnodes are the same\n                if (t.second->out_nodes.size() + t.second->in_nodes.size()\n                    != s.second->out_nodes.size() + s.second->in_nodes.size()) {\n                    BOOST_LOG_TRIVIAL(debug) << \"node has different number of outnodes\";\n                    return false;\n                }\n\n                for (const auto& i : t.second->out_nodes) {\n                    if (not y.found_in_out_nodes(s.second, nodes.at(i))\n                        and not y.found_in_in_nodes(s.second, nodes.at(i))) {\n                        BOOST_LOG_TRIVIAL(debug)\n                            << \"did not find \" << i << \" in outnode or innodes\";\n                        return false;\n                    }\n                }\n                for (const auto& i : t.second->in_nodes) {\n                    if (not y.found_in_out_nodes(s.second, nodes.at(i))\n                        and not y.found_in_in_nodes(s.second, nodes.at(i))) {\n                        BOOST_LOG_TRIVIAL(debug)\n                            << \"did not find \" << i << \" in outnode or innodes\";\n                        return false;\n                    }\n                }\n                break;\n            }\n        }\n        if (!found) {\n            BOOST_LOG_TRIVIAL(debug)\n                << \"did not find node \" << t.first << \" \" << *t.second;\n            return false;\n        }\n    }\n\n    // nodes can't be equal within a graph so don't need to check vice versa\n    return true;\n}\n\nbool debruijn::Graph::operator!=(const Graph& y) const { return !(*this == y); }\n\nnamespace debruijn {\nstd::ostream& operator<<(std::ostream& out, const Graph& m)\n{\n    for (const auto& n : m.nodes) {\n        out << n.first << \": \" << *(n.second) << std::endl;\n        for (const auto& o : n.second->out_nodes) {\n            out << n.first << \" -> \" << o << std::endl;\n        }\n    }\n    return out;\n}\n}\n", "meta": {"hexsha": "bb7543fb248c4c33f16adcb34a73fa70ff124c28", "size": 15257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/de_bruijn/graph.cpp", "max_stars_repo_name": "rmcolq/pandora", "max_stars_repo_head_hexsha": "93c541017a5c1ea45f999f5eabdb58be061711e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2018-07-06T00:13:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T03:58:20.000Z", "max_issues_repo_path": "src/de_bruijn/graph.cpp", "max_issues_repo_name": "rmcolq/pandora", "max_issues_repo_head_hexsha": "93c541017a5c1ea45f999f5eabdb58be061711e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 215.0, "max_issues_repo_issues_event_min_datetime": "2018-07-09T16:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T22:44:36.000Z", "max_forks_repo_path": "src/de_bruijn/graph.cpp", "max_forks_repo_name": "mbhall88/pandora", "max_forks_repo_head_hexsha": "16de553795267a55af223748b24510a904ca5ef9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-07-06T13:09:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T15:01:09.000Z", "avg_line_length": 36.2399049881, "max_line_length": 88, "alphanum_fraction": 0.547420856, "num_tokens": 3737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.026355355283760137, "lm_q1q2_score": 0.011437735691473392}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_R1CS_GG_PPZKSNARK_IPP2_PROVE_HPP\n#define CRYPTO3_R1CS_GG_PPZKSNARK_IPP2_PROVE_HPP\n\n#include <algorithm>\n#include <memory>\n#include <vector>\n#include <tuple>\n\n#include <boost/iterator/zip_iterator.hpp>\n\n#include <nil/crypto3/detail/pack_numeric.hpp>\n\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n#include <nil/crypto3/hash/sha2.hpp>\n\n#include <nil/crypto3/algebra/multiexp/multiexp.hpp>\n#include <nil/crypto3/algebra/multiexp/policies.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/proof.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/srs.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace snark {\n                /// Returns the vector used for the linear combination fo the inner pairing product\n                /// between A and B for the Groth16 aggregation: A^r * B. It is required as it\n                /// is not enough to simply prove the ipp of A*B, we need a random linear\n                /// combination of those.\n                template<typename FieldType>\n                std::vector<typename FieldType::value_type>\n                    structured_scalar_power(std::size_t num, const typename FieldType::value_type &s) {\n                    std::vector<typename FieldType::value_type> powers = {FieldType::value_type::one()};\n                    for (int i = 1; i < num; i++) {\n                        powers.emplace_back(powers[i - 1] * s);\n                    }\n                    return powers;\n                }\n\n                /// compress is similar to commit::{V,W}KEY::compress: it modifies the `vec`\n                /// vector by setting the value at index $i:0 -> split$  $vec[i] = vec[i] +\n                /// vec[i+split]^scaler$. The `vec` vector is half of its size after this call.\n                template<typename CurveAffine>\n                void compress(std::vector<typename CurveAffine::value_type> &vec, std::size_t split,\n                              const typename CurveAffine::scalar &scaler) {\n                    std::vector<typename CurveAffine::value_type> left = {vec.begin(), vec.begin() + split},\n                                                                  right = {vec.begin() + split, vec.end()};\n                    std::for_each(boost::make_zip_iterator(std::make_tuple(left.begin(), right.begin())),\n                                  boost::make_zip_iterator(std::make_tuple(left.end(), right.end())),\n                                  [&](const std::tuple<const typename CurveAffine::value_type &,\n                                                       const typename CurveAffine::value_type &> &t) {\n                                      auto x = std::get<1>(t).to_projective() * scaler;\n                                      x += std::get<0>(t);\n                                      std::get<0>(t) = x.to_affine();\n                                  });\n\n                    vec.resize(left.size());\n                }\n\n                /// Aggregate `n` zkSnark proofs, where `n` must be a power of two.\n                template<typename CurveType, typename InputProofIterator, typename Hash = hashes::sha2<256>>\n                typename std::enable_if<std::is_same<typename std::iterator_traits<InputProofIterator>::value_type,\n                                                     r1cs_gg_ppzksnark_aggregate_proof<CurveType>>::value,\n                                        r1cs_gg_ppzksnark_aggregate_proof<CurveType>>::type\n                    aggregate_proofs(const r1cs_gg_ppzksnark_proving_srs<CurveType> &srs, InputProofIterator first,\n                                     InputProofIterator last) {\n                    std::size_t size = std::distance(first, last);\n                    BOOST_ASSERT((size & (size - 1)) == 0);\n                    BOOST_ASSERT(srs.valid(size));\n\n                    std::vector<typename CurveType::g1_type::value_type> a, c;\n                    std::vector<typename CurveType::g2_type::value_type> b;\n\n                    // We first commit to A B and C - these commitments are what the verifier\n                    // will use later to verify the TIPP and MIPP proofs\n                    while (first != last) {\n                        a.emplace_back(*first.g_A);\n                        b.emplace_back(*first.g_B);\n                        c.emplace_back(*first.g_C);\n                        ++first;\n                    }\n\n                    // A and B are committed together in this scheme\n                    // we need to take the reference so the macro doesn't consume the value\n                    // first\n                    r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType> com_ab =\n                        r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(srs.vkey, srs.wkey, a.begin(), a.end(),\n                                                                           b.begin(), b.end());\n                    r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType> com_c =\n                        r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(srs.vkey, c.begin(), c.end());\n\n                    // Random linear combination of proofs\n                    std::size_t counter_nonce = 1;\n                    std::array<std::uint8_t, sizeof(std::size_t)> counter_nonce_bytes;\n                    detail::pack<stream_endian::big_byte_big_bit>({counter_nonce}, counter_nonce_bytes);\n                    accumulator_set<Hash> acc;\n\n                    hash<Hash>(counter_nonce_bytes, acc);\n                    hash<Hash>(std::get<0>(com_ab), acc);\n                    hash<Hash>(std::get<1>(com_ab), acc);\n                    hash<Hash>(std::get<0>(com_c), acc);\n                    hash<Hash>(std::get<1>(com_c), acc);\n\n                    typename Hash::digest_type d = accumulators::extract::hash<Hash>(acc);\n                    typename CurveType::scalar_field_type::value_type r;\n                    detail::pack(d, r.data);\n                    r = r.inversed();\n\n                    // r, r^2, r^3, r^4 ...\n                    std::vector<typename CurveType::scalar_field_type::value_type> r_vec =\n                        structured_scalar_power<typename CurveType::scalar_field_type>(std::distance(first, last), r);\n                    // r^-1, r^-2, r^-3\n                    std::vector<typename CurveType::scalar_field_type::value_type> r_inv;\n                    for (const typename CurveType::scalar_field_type::value_type &ri : r_vec) {\n                        r_inv.emplace_back(ri.inversed());\n                    }\n\n                    // B^{r}\n                    std::vector<typename CurveType::scalar_field_type::value_type> b_r;\n                    std::for_each(boost::make_zip_iterator(std::make_tuple(b.begin(), r_vec.begin())),\n                                  boost::make_zip_iterator(std::make_tuple(b.end(), r_vec.end())),\n                                  [&](const std::tuple<const typename CurveType::g2_type::value_type &,\n                                                       const typename CurveType::scalar_field_type::value_type &> &t) {\n                                      b_r.emplace_back((std::get<0>(t).to_projective() * std::get<1>(t)).to_affine());\n                                  });\n\n                    // w^{r^{-1}}\n                    auto wkey_r_inv = srs.wkey.scale(r_inv);\n\n                    // we prove tipp and mipp using the same recursive loop\n                    tipp_mipp_proof<CurveType> proof =\n                        prove_tipp_mipp(srs, wkey_r_inv, a.begin(), a.end(), b_r.begin(), b_r.end(), c.begin(), c.end(),\n                                        r_vec.begin(), r_vec.end());\n                    // compute A * B^r for the verifier\n                    auto ip_ab = algebra::pair<CurveType>(a, b_r);\n                    // compute C^r for the verifier\n                    auto agg_c = algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(c, r_vec);\n\n                    // debug assert\n                    auto computed_com_ab = r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(\n                        srs.vkey, wkey_r_inv, a.begin(), a.end(), b_r.begin(), b_r.end());\n                    BOOST_ASSERT(com_ab == computed_com_ab);\n\n                    return {com_ab, com_c, ip_ab, agg_c, proof};\n                }\n\n                /// Proves a TIPP relation between A and B as well as a MIPP relation with C and\n                /// r. Commitment keys must be of size of A, B and C. In the context of Groth16\n                /// aggregation, we have that B = B^r and wkey is scaled by r^{-1}. The\n                /// commitment key v is used to commit to A and C recursively in GIPA such that\n                /// only one KZG proof is needed for v. In the original paper version, since the\n                /// challenges of GIPA would be different, two KZG proofs would be needed.\n                template<typename CurveType, typename InputG1Iterator, typename InputG2Iterator,\n                         typename InputScalarIterator, typename Hash = hashes::sha2<256>>\n                tipp_mipp_proof<CurveType> prove_tipp_mipp(const r1cs_gg_ppzksnark_proving_srs<CurveType> &srs,\n                                                           const r1cs_gg_ppzksnark_ipp2_wkey<CurveType> &wkey,\n                                                           InputG1Iterator afirst, InputG1Iterator alast,\n                                                           InputG2Iterator bfirst, InputG2Iterator blast,\n                                                           InputG1Iterator cfirst, InputG1Iterator clast,\n                                                           InputScalarIterator rfirst, InputScalarIterator rlast) {\n                    std::size_t asize = std::distance(afirst, alast);\n                    std::size_t bsize = std::distance(bfirst, blast);\n\n                    BOOST_ASSERT((asize & (asize - 1)) == 0 || asize == bsize);\n                    typename std::iterator_traits<InputScalarIterator>::value_type r_shift = *rfirst + 1;\n\n                    // Run GIPA\n                    std::tuple<gipa_proof<CurveType>, std::vector<typename CurveType::scalar_field_type::value_type>,\n                               std::vector<typename CurveType::scalar_field_type::value_type>>\n                        gtm =\n                            gipa_tipp_mipp(afirst, alast, bfirst, blast, cfirst, clast, rfirst, rlast, srs.vkey, wkey);\n\n                    // Prove final commitment keys are wellformed\n                    // we reverse the transcript so the polynomial in kzg opening is constructed\n                    // correctly - the formula indicates x_{l-j}. Also for deriving KZG\n                    // challenge point, input must be the last challenge.\n                    std::reverse(std::get<1>(gtm).begin(), std::get<1>(gtm).end());\n                    std::reverse(std::get<2>(gtm).begin(), std::get<2>(gtm).end());\n                    typename std::iterator_traits<InputScalarIterator>::value_type r_inverse = r_shift.inverse();\n\n                    // KZG challenge point\n                    std::size_t counter_nonce = 1;\n                    std::array<std::uint8_t, sizeof(std::size_t)> counter_nonce_bytes;\n                    detail::pack<stream_endian::big_byte_big_bit>({counter_nonce}, counter_nonce_bytes);\n                    accumulator_set<Hash> acc;\n\n                    hash<Hash>(counter_nonce_bytes, acc);\n                    hash<Hash>(*std::get<1>(gtm).begin(), acc);\n                    hash<Hash>(std::get<0>(std::get<0>(gtm).final_vkey), acc);\n                    hash<Hash>(std::get<1>(std::get<0>(gtm).final_vkey), acc);\n                    hash<Hash>(std::get<0>(std::get<0>(gtm).final_wkey), acc);\n                    hash<Hash>(std::get<1>(std::get<0>(gtm).final_wkey), acc);\n\n                    typename Hash::digest_type d = accumulators::extract::hash<Hash>(acc);\n                    typename CurveType::scalar_field_type::value_type z;\n                    multiprecision::import_bits(z.data, d);\n                    z = z.inversed();\n\n                    // Complete KZG proofs\n                    kzg_opening<typename CurveType::g2_type> vkey_opening = prove_commitment_key_kzg_opening(\n                        srs.h_alpha_powers_table, srs.h_beta_powers_table, srs.n, std::get<2>(gtm),\n                        CurveType::scalar_field_type::value_type::one(), z);\n                    kzg_opening<typename CurveType::g1_type> wkey_opening = prove_commitment_key_kzg_opening(\n                        srs.g_alpha_powers_table, srs.g_beta_powers_table, srs.n, std::get<1>(gtm), r_inverse, z);\n\n                    return {std::get<0>(gtm), vkey_opening, wkey_opening};\n                }\n\n                /*\n                 * @brief gipa_tipp_mipp peforms the recursion of the GIPA protocol for TIPP and MIPP.\n                 * It returns a proof containing all intermdiate committed values, as well as\n                 * the challenges generated necessary to do the polynomial commitment proof\n                 * later in TIPP.\n                 * @param wkey scaled key w^r^-1\n                 */\n                template<typename CurveType, typename InputG1Iterator, typename InputG2Iterator,\n                         typename InputScalarIterator, typename Hash = hashes::sha2<256>>\n                std::tuple<gipa_proof<CurveType>, std::vector<typename CurveType::scalar_field_type::value_type>,\n                           std::vector<typename CurveType::scalar_field_type::value_type>>\n                    gipa_tipp_mipp(InputG1Iterator afirst, InputG1Iterator alast, InputG2Iterator bfirst,\n                                   InputG2Iterator blast, InputG1Iterator cfirst, InputG1Iterator clast,\n                                   InputScalarIterator rfirst, InputScalarIterator rlast,\n                                   const r1cs_gg_ppzksnark_ipp2_vkey<CurveType> &vkey,\n                                   const r1cs_gg_ppzksnark_ipp2_wkey<CurveType> &wkey) {\n\n                    std::vector<typename std::iterator_traits<InputG1Iterator>::value_type> m_a = {afirst, alast},\n                                                                                            m_c = {cfirst, clast};\n                    std::vector<typename std::iterator_traits<InputG2Iterator>::value_type> m_b = {bfirst, blast};\n                    std::vector<typename std::iterator_traits<InputScalarIterator>::value_type> m_r = {rfirst, rlast};\n\n                    r1cs_gg_ppzksnark_ipp2_vkey<CurveType> vkey = vkey;\n                    r1cs_gg_ppzksnark_ipp2_wkey<CurveType> wkey = wkey;\n\n                    // storing the values for including in the proof\n                    std::vector<std::tuple<typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type,\n                                           typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type>>\n                        comms_ab;\n                    std::vector<std::tuple<typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type,\n                                           typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type>>\n                        comms_c;\n                    std::vector<typename CurveType::pairing::gt_type::value_type> z_ab;\n                    std::vector<typename std::iterator_traits<InputG1Iterator>::value_type> z_c;\n                    std::vector<typename CurveType::scalar_field_type::value_type> challenges, challenges_inv;\n\n                    while (m_a.size() > 1) {\n                        // recursive step\n                        // Recurse with problem of half size\n                        std::size_t split = m_a.size() / 2;\n\n                        // TIPP ///\n                        std::vector<typename std::iterator_traits<InputG1Iterator>::value_type>\n                            a_left = {m_a.begin(), m_a.begin() + split},\n                            a_right = {m_a.begin() + split, m_a.end()};\n                        std::vector<typename std::iterator_traits<InputG2Iterator>::value_type>\n                            b_left = {m_b.begin(), m_b.begin() + split},\n                            b_right = {m_b.begin() + split, m_b.end()};\n                        // MIPP ///\n                        // c[:n']   c[n':]\n                        std::vector<typename std::iterator_traits<InputG1Iterator>::value_type>\n                            c_left = {m_c.begin() + m_c.begin() + split},\n                            c_right = {m_c.begin() + split, m_c.end()};\n                        // r[:n']   r[:n']\n                        std::vector<typename std::iterator_traits<InputScalarIterator>::value_type>\n                            r_left = {m_r.begin(), m_r.begin() + split},\n                            r_right = {m_r.begin() + split, m_r.end()};\n\n                        r1cs_gg_ppzksnark_ipp2_vkey<CurveType> vk_left = {{vkey.a.begin(), vkey.a.begin() + split},\n                                                                          {vkey.b.begin(), vkey.b.begin() + split}},\n                                                               vk_right = {{vkey.a.begin() + split, vkey.a.end()},\n                                                                           {vkey.b.begin() + split, vkey.b.end()}};\n\n                        r1cs_gg_ppzksnark_ipp2_wkey<CurveType> wk_left = {{wkey.a.begin(), wkey.a.begin() + split},\n                                                                          {wkey.b.begin(), wkey.b.begin() + split}},\n                                                               wk_right = {{wkey.a.begin() + split, wkey.a.end()},\n                                                                           {wkey.b.begin() + split, wkey.b.end()}};\n\n                        // See section 3.3 for paper version with equivalent names\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tab_l =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(vk_left, wk_right, a_right, b_left);\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tab_r =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(vk_right, wk_left, a_left, b_right);\n\n                        // TIPP part\n                        typename CurveType::pairing::gt_type::value_type zab_l =\n                            algebra::pair<CurveType>(a_right, b_left);\n                        typename CurveType::pairing::gt_type::value_type zab_r =\n                            algebra::pair<CurveType>(a_left, b_right);\n\n                        // MIPP part\n                        // z_l = c[n':] ^ r[:n']\n                        typename std::iterator_traits<InputG1Iterator>::value_type zc_l =\n                            algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(c_right, r_left);\n                        // Z_r = c[:n'] ^ r[n':]\n                        typename std::iterator_traits<InputG1Iterator>::value_type zc_r =\n                            algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(c_left, r_right);\n                        // u_l = c[n':] * v[:n']\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tuc_l =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(vk_left, c_right);\n                        // u_r = c[:n'] * v[n':]\n                        typename r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::output_type tuc_r =\n                            r1cs_gg_ppzksnark_ipp2_commitment<CurveType>::pair(vk_right, c_left);\n\n                        // Fiat-Shamir challenge\n                        typename CurveType::scalar_field_type::value_type default_transcript =\n                            CurveType::scalar_field_type::value_type::zero();\n                        auto transcript = challenges.empty() ? default_transcript : *(challenges.end() - 1);\n\n                        // combine both TIPP and MIPP transcript\n                        std::size_t counter_nonce = 1;\n                        std::array<std::uint8_t, sizeof(std::size_t)> counter_nonce_bytes;\n                        detail::pack<stream_endian::big_byte_big_bit>({counter_nonce}, counter_nonce_bytes);\n                        accumulator_set<Hash> acc;\n\n                        hash<Hash>(counter_nonce_bytes, acc);\n                        hash<Hash>(transcript, acc);\n                        hash<Hash>(std::get<0>(tab_l), acc);\n                        hash<Hash>(std::get<1>(tab_l), acc);\n                        hash<Hash>(std::get<0>(tab_r), acc);\n                        hash<Hash>(std::get<1>(tab_r), acc);\n                        hash<Hash>(zab_l, acc);\n                        hash<Hash>(zab_r, acc);\n                        hash<Hash>(zc_l, acc);\n                        hash<Hash>(zc_r, acc);\n                        hash<Hash>(std::get<0>(tuc_l), acc);\n                        hash<Hash>(std::get<1>(tuc_l), acc);\n                        hash<Hash>(std::get<0>(tuc_r), acc);\n                        hash<Hash>(std::get<1>(tuc_r), acc);\n\n                        typename hashes::sha2<256>::digest_type d = accumulators::extract::hash<hashes::sha2<256>>(acc);\n                        typename CurveType::scalar_field_type::value_type c_inv;\n                        detail::pack(d, c_inv.data);\n                        c_inv = c_inv.inversed();\n\n                        // Optimization for multiexponentiation to rescale G2 elements with\n                        // 128-bit challenge Swap 'c' and 'c_inv' since can't control bit size\n                        // of c_inv\n                        typename CurveType::scalar_field_type::value_type c = c_inv.inversed();\n\n                        // Set up values for next step of recursion\n                        // A[:n'] + A[n':] ^ x\n                        compress(m_a, split, c);\n                        // B[:n'] + B[n':] ^ x^-1\n                        compress(m_b, split, c_inv);\n\n                        // c[:n'] + c[n':]^x\n                        compress(m_c, split, c);\n                        std::for_each(\n                            boost::make_zip_iterator(std::make_tuple(r_left.begin(), r_right.begin())),\n                            boost::make_zip_iterator(std::make_tuple(r_left.end(), r_right.end())),\n                            [&](const std::tuple<typename std::iterator_traits<InputScalarIterator>::value_type &,\n                                                 typename std::iterator_traits<InputScalarIterator>::value_type &> &t) {\n                                // r[:n'] + r[n':]^x^-1\n                                std::get<1>(t) *= c_inv;\n                                std::get<0>(t) += std::get<1>(t);\n                            });\n                        std::size_t len = r_left.size();\n                        m_r.resize(len);    // shrink to new size\n\n                        // v_left + v_right^x^-1\n                        vkey = vk_left.compress(vk_right, c_inv);\n                        // w_left + w_right^x\n                        wkey = wk_left.compress(wk_right, c);\n\n                        comms_ab.emplace_back({tab_l, tab_r});\n                        comms_c.emplace_back({tuc_l, tuc_r});\n                        z_ab.emplace_back({zab_l, zab_r});\n                        z_c.emplace_back({zc_l, zc_r});\n                        challenges.emplace_back(c);\n                        challenges_inv.emplace_back(c_inv);\n                    }\n\n                    BOOST_ASSERT(m_a.size() == 1 && m_b.size() == 1);\n                    BOOST_ASSERT(m_c.size() == 1 && m_r.size() == 1);\n                    BOOST_ASSERT(vkey.a.size() == 1 && vkey.b.size() == 1);\n                    BOOST_ASSERT(wkey.a.size() == 1 && wkey.b.size() == 1);\n\n                    return std::make_tuple({a.size(), comms_ab, comms_c, z_ab, z_c, m_a[0], m_b[0], m_c[0], m_r[0],\n                                            *vkey.begin(), *wkey.begin()},\n                                           challenges, challenges_inv);\n                }\n\n                /// It returns the evaluation of the polynomial $\\prod (1 + x_{l-j}(rX)^{2j}$ at\n                /// the point z, where transcript contains the reversed order of all challenges (the x).\n                /// The challenges must be in reversed order for the correct evaluation of the\n                /// polynomial in O(logn)\n                template<typename FieldType, typename InputFieldValueIterator>\n                typename std::enable_if<std::is_same<typename std::iterator_traits<InputFieldIterator>::value_type,\n                                                     typename FieldType::value_type>::value,\n                                        typename FieldType::value_type>::type\n                    polynomial_evaluation_product_form_from_transcript(InputFieldValueIterator transcript_first,\n                                                                       InputFieldValueIterator transcript_last,\n                                                                       const typename FieldType::value_type &z,\n                                                                       const typename FieldType::value_type &r_shift) {\n                    // this is the term (rz) that will get squared at each step to produce the\n                    // $(rz)^{2j}$ of the formula\n                    typename FieldType::value_type power_zr = z;\n                    power_zr *= r_shift;\n\n                    // 0 iteration\n                    typename FieldType::value_type res =\n                        FieldType::value_type::one() + (*transcript_first * power_zr);\n                    power_zr *= power_zr;\n                    ++transcript_first;\n\n                    // the rest\n                    while (transcript_first != transcript_last) {\n                        res *= FieldType::value_type::one() + (*transcript_first * power_zr);\n                        power_zr *= power_zr;\n                        ++transcript_first;\n                    }\n\n                    return res;\n                }\n\n                // Compute the coefficients of the polynomial $\\prod_{j=0}^{l-1} (1 + x_{l-j}(rX)^{2j})$\n                // It does this in logarithmic time directly; here is an example with 2\n                // challenges:\n                //\n                //     We wish to compute $(1+x_1ra)(1+x_0(ra)^2) = 1 +  x_1ra + x_0(ra)^2 + x_0x_1(ra)^3$\n                //     Algorithm: $c_{-1} = [1]$; $c_j = c_{i-1} \\| (x_{l-j} * c_{i-1})$; $r = r*r$\n                //     $c_0 = c_{-1} \\| (x_1 * r * c_{-1}) = [1] \\| [rx_1] = [1, rx_1]$, $r = r^2$\n                //     $c_1 = c_0 \\| (x_0 * r^2c_0) = [1, rx_1] \\| [x_0r^2, x_0x_1r^3] = [1, x_1r, x_0r^2, x_0x_1r^3]$\n                //     which is equivalent to $f(a) = 1 + x_1ra + x_0(ra)^2 + x_0x_1r^2a^3$\n                //\n                // This method expects the coefficients in reverse order so transcript[i] =\n                // x_{l-j}.\n                template<typename FieldType, typename InputFieldValueIterator>\n                typename std::enable_if<std::is_same<typename std::iterator_traits<InputFieldValueIterator>::value_type,\n                                                     typename FieldType::value_type>::value,\n                                        std::vector<typename FieldType::value_type>>::type\n                    polynomial_coefficients_from_transcript(InputFieldValueIterator transcript_first,\n                                                            InputFieldValueIterator transcript_last,\n                                                            const typename FieldType::value_type &r_shift) {\n                    std::vector<typename FieldType::value_type> coefficients = {FieldType::value_type::one()};\n                    typename FieldType::value_type power_2_r = r_shift;\n\n                    while (transcript_first != transcript_last) {\n                        std::size_t n = coefficients.size();\n                        for (int j = 0; j < n; j++) {\n                            coefficients.emplace_back(coefficients[j] * (*transcript_first * power_2_r));\n                        }\n                        power_2_r *= power_2_r;\n\n                        ++transcript_first;\n                    }\n\n                    return coefficients;\n                }\n\n                /// Returns the KZG opening proof for the given commitment key. Specifically, it\n                /// returns $g^{f(alpha) - f(z) / (alpha - z)}$ for $a$ and $b$.\n                template<typename CurveAffine, typename InputScalarIterator>\n                kzg_opening<CurveAffine> prove_commitment_key_kzg_opening(\n                    MultiscalarPrecomp<CurveAffine> &srs_powers_alpha_table,\n                    MultiscalarPrecomp<CurveAffine> &srs_powers_beta_table, std::size_t srs_powers_len,\n                    InputScalarIterator transcript_first, InputScalarIterator transcript_last,\n                    const typename std::iterator_traits<InputScalarIterator>::value_type &r_shift,\n                    const typename std::iterator_traits<InputScalarIterator>::value_type &kzg_challenge) {\n                    // f_v\n                    DensePolynomial vkey_poly(\n                        polynomial_coefficients_from_transcript(transcript_first, transcript_last, r_shift));\n\n                    BOOST_ASSERT_MSG(srs_powers_len != vkey_poly.coeffs().size(), \"Malformed SRS\");\n                    // f_v(z)\n                    std::vector<typename std::iterator_traits<InputScalarIterator>::value_type> vkey_poly_z =\n                        polynomial_evaluation_product_form_from_transcript(transcript_first, transcript_last,\n                                                                           kzg_challenge, r_shift);\n\n                    typename std::iterator_traits<InputScalarIterator>::value_type neg_kzg_challenge =\n                        kzg_challenge.negate();\n\n                    // f_v(X) - f_v(z) / (X - z)\n                    DensePolynomial quotient_polynomial =\n                        (vkey_poly - DensePolynomial(vkey_poly_z)) /\n                        (DensePolynomial({neg_kzg_challenge,\n                                          std::iterator_traits<InputScalarIterator>::value_type::one()}));\n\n                    std::vector<typename std::iterator_traits<InputScalarIterator>::value_type>\n                        quotient_polynomial_coeffs = quotient_polynomial.into_coeffs();\n\n                    // multiexponentiation inner_product, inlined to optimize\n                    std::size_t quotient_polynomial_coeffs_len = quotient_polynomial_coeffs.size();\n                    auto getter = [&](std::size_t i) -> typename CurveAffine::scalar_field_type::value_type {\n                        return i >= quotient_polynomial_coeffs_len ?\n                                   std::iterator_traits<InputScalarIterator>::value_type::zero() :\n                                   quotient_polynomial_coeffs[i];\n                    };\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": "0dd8fa7ef4bf829f60fe332290190cad11a36a76", "size": 32717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/prove.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/prove.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/prove.hpp", "max_forks_repo_name": "NoamDev/crypto3-zk", "max_forks_repo_head_hexsha": "5f03e49b737994a3cecf673b029a4e32a2a8aaa5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.9173076923, "max_line_length": 120, "alphanum_fraction": 0.5117828652, "num_tokens": 6927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.026355351412213745, "lm_q1q2_score": 0.01143773401129402}}
{"text": "#include \"trajopt/problem_description.hpp\"\n#include \"trajopt/common.hpp\"\n#include <boost/foreach.hpp>\n#include \"utils/logging.hpp\"\n#include \"sco/expr_ops.hpp\"\n#include \"trajopt/kinematic_constraints.hpp\"\n#include \"trajopt/belief_constraints.hpp\"\n#include \"trajopt/collision_avoidance.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"trajopt/plot_callback.hpp\"\n#include \"trajopt/rave_utils.hpp\"\n#include \"utils/eigen_conversions.hpp\"\n#include \"utils/eigen_slicing.hpp\"\n#include <boost/algorithm/string.hpp>\nusing namespace Json;\nusing namespace std;\nusing namespace OpenRAVE;\nusing namespace trajopt;\nusing namespace util;\n\nnamespace {\n\n\nbool gRegisteredMakers = false;\nvoid RegisterMakers() {\n\n\tCostInfo::RegisterMaker(\"pose\", &PoseCostInfo::create);\n\tCostInfo::RegisterMaker(\"joint_pos\", &JointPosCostInfo::create);\n\tCostInfo::RegisterMaker(\"joint_vel\", &JointVelCostInfo::create);\n\tCostInfo::RegisterMaker(\"collision\", &CollisionCostInfo::create);\n\tCostInfo::RegisterMaker(\"continuous_collision\", &ContinuousCollisionCostInfo::create);\n\n\tCntInfo::RegisterMaker(\"joint\", &JointConstraintInfo::create);\n\tCntInfo::RegisterMaker(\"pose\", &PoseCntInfo::create);\n\tCntInfo::RegisterMaker(\"collision\", &CollisionCntInfo::create);\n\tCntInfo::RegisterMaker(\"continuous_collision\", &ContinuousCollisionCntInfo::create);\n\tCntInfo::RegisterMaker(\"cart_vel\", &CartVelCntInfo::create);\n\n\t// belief costs and controls\n\tCostInfo::RegisterMaker(\"control\", &ControlCostInfo::create);\n\tCostInfo::RegisterMaker(\"covariance\", &CovarianceCostInfo::create);\n\n\tCntInfo::RegisterMaker(\"control\", &ControlCntInfo::create);\n\n\tgRegisteredMakers = true;\n}\n\nBeliefRobotAndDOFPtr RADFromName(const string& name, RobotBasePtr robot) {\n\tif (name == \"active\") {\n\t\treturn BeliefRobotAndDOFPtr(new BeliefRobotAndDOF(robot, robot->GetActiveDOFIndices(), robot->GetAffineDOF(), robot->GetAffineRotationAxis()));\n\t}\n\tvector<int> dof_inds;\n\tint affinedofs = 0;\n\tVector rotationaxis(0,0,1);\n\tvector<string> components;\n\tboost::split(components, name, boost::is_any_of(\"+\"));\n\tfor (int i=0; i < components.size(); ++i) {\n\t\tstd::string& component = components[i];\n\t\tif (RobotBase::ManipulatorPtr manip = GetManipulatorByName(*robot, component)) {\n\t\t\tvector<int> inds = manip->GetArmIndices();\n\t\t\tdof_inds.insert(dof_inds.end(), inds.begin(), inds.end());\n\t\t}\n\t\telse if (component == \"base\") {\n\t\t\taffinedofs |= DOF_X | DOF_Y | DOF_RotationAxis;\n\t\t}\n\t\telse if (component == \"base_point\") {\n\t\t\taffinedofs |= DOF_X | DOF_Y;\n\t\t}\n\t\telse if (KinBody::JointPtr joint = robot->GetJoint(component)) {\n\t\t\tdof_inds.push_back(joint->GetDOFIndex());\n\t\t}\n\t\telse PRINT_AND_THROW( boost::format(\"error in reading manip description: %s must be a manipulator, link, or 'base'\")%component );\n\t}\n\treturn BeliefRobotAndDOFPtr(new BeliefRobotAndDOF(robot, dof_inds, affinedofs, rotationaxis));\n}\n\nBoolVec toMask(const VectorXd& x) {\n\tBoolVec out(x.size());\n\tfor (int i=0; i < x.size(); ++i) out[i] = (x[i] > 0);\n\treturn out;\n}\n\nbool allClose(const VectorXd& a, const VectorXd& b) {\n\treturn (a-b).array().abs().maxCoeff() < 1e-4;\n}\n\n}\n\nnamespace Json { //funny thing with two-phase lookup\n\nvoid fromJson(const Json::Value& v, Vector3d& x) {\n\tvector<double> vx;\n\tfromJsonArray(v, vx, 3);\n\tx = Vector3d(vx[0], vx[1], vx[2]);\n}\nvoid fromJson(const Json::Value& v, Vector4d& x) {\n\tvector<double> vx;\n\tfromJsonArray(v, vx, 4);\n\tx = Vector4d(vx[0], vx[1], vx[2], vx[3]);\n}\ntemplate <class T>\ninline void fromJson(const Json::Value& v, Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& m) {\n\tint nRows = v.size();\n\tif (nRows != 0) {\n\t\tint nCols = v[0].size();\n\t\tm.resize(nRows, nCols);\n\t\tfor (int i=0; i<nRows; i++) {\n\t\t\tif (v[i].size() != nCols)\n\t\t\t\tPRINT_AND_THROW(boost::format(\"matrix with variable number of cols not supported. expected %i cols at the %ith row, but got %i cols\\n\")%nCols%i%v[i].size());\n\t\t\tstd::vector<T> row;\n\t\t\tfromJsonArray(v[i], row, nCols);\n\t\t\tfor (int j=0; j<nCols; j++) m(i,j) = row[j];\n\t\t}\n\t} else {\n\t\tm.resize(0,0);\n\t}\n}\n\n}\n\nnamespace trajopt {\n\nTRAJOPT_API ProblemConstructionInfo* gPCI;\n\nvoid BasicInfo::fromJson(const Json::Value& v) {\n\tchildFromJson(v, start_fixed, \"start_fixed\", true);\n\tchildFromJson(v, n_steps, \"n_steps\");\n\tchildFromJson(v, manip, \"manip\");\n\tchildFromJson(v, robot, \"robot\", string(\"\"));\n\tchildFromJson(v, dofs_fixed, \"dofs_fixed\", IntVec());\n\tchildFromJson(v, belief_space, \"belief_space\", false);\n}\n\n\n////\nvoid fromJson(const Json::Value& v, CostInfoPtr& cost) {\n\tstring type;\n\tchildFromJson(v, type, \"type\");\n\tcost = CostInfo::fromName(type);\n\tif (!cost) PRINT_AND_THROW( boost::format(\"failed to construct cost named %s\")%type );\n\tcost->fromJson(v);\n\tchildFromJson(v, cost->name, \"name\", type);\n}\nCostInfoPtr CostInfo::fromName(const string& type) {\n\tif (!gRegisteredMakers) RegisterMakers();\n\tif (name2maker.find(type) != name2maker.end()) {\n\t\treturn (*name2maker[type])();\n\t}\n\telse {\n\t\tRAVELOG_ERROR(\"There is no cost of type%s\\n\", type.c_str());\n\t\treturn CostInfoPtr();\n\t}\n}\nmap<string, CostInfo::MakerFunc> CostInfo::name2maker;\n\nvoid CostInfo::RegisterMaker(const std::string& type, MakerFunc f) {\n\tname2maker[type] = f;\n}\n\n\n////\n//// almost copied\n\n\nvoid fromJson(const Json::Value& v, CntInfoPtr& cnt) {\n\tstring type;\n\tchildFromJson(v, type, \"type\");\n\tLOG_DEBUG(\"reading constraint: %s\", type.c_str());\n\tcnt = CntInfo::fromName(type);\n\tif (!cnt) PRINT_AND_THROW( boost::format(\"failed to construct constraint named %s\")%type );\n\tcnt->fromJson(v);\n\tchildFromJson(v, cnt->name, \"name\", type);\n}\nCntInfoPtr CntInfo::fromName(const string& type) {\n\tif (!gRegisteredMakers) RegisterMakers();\n\tif (name2maker.find(type) != name2maker.end()) {\n\t\treturn (*name2maker[type])();\n\t}\n\telse {\n\t\tRAVELOG_ERROR(\"There is no constraint of type%s\\n\", type.c_str());\n\t\treturn CntInfoPtr();\n\t}\n}\nmap<string,CntInfo::MakerFunc> CntInfo::name2maker;\n\nvoid InitInfo::fromJson(const Json::Value& v) {\n\tstring type_str;\n\tchildFromJson(v, type_str, \"type\");\n\tint n_steps = gPCI->basic_info.n_steps;\n\tint n_dof = gPCI->rad->GetDOF();\n\tint b_dim = gPCI->rad->GetBDim(), u_dim = gPCI->rad->GetUDim();\n\n\tbool belief_space = gPCI->basic_info.belief_space;\n\tMatrixXd rt_Sigma0;\n\tif (belief_space && (type_str == \"stationary\" || type_str == \"given_traj\")) {\n\t\tFAIL_IF_FALSE(v.isMember(\"initial_rt_sigma\"));\n\t\tconst Value& rt_Sigma0_v = v[\"initial_rt_sigma\"];\n\t\tJson::fromJson(rt_Sigma0_v, rt_Sigma0);\n\t\tif (rt_Sigma0.rows()!=n_dof) PRINT_AND_THROW(\"initial square root of sigma has wrong number of rows\");\n\t\tif (rt_Sigma0.cols()!=n_dof) PRINT_AND_THROW(\"initial square root of sigma has wrong number of cols\");\n\t}\n\n\tif (type_str == \"stationary\") {\n\t\tif (!belief_space) {\n\t\t\tdata = toVectorXd(gPCI->rad->GetDOFValues()).transpose().replicate(n_steps, 1);\n\t\t} else {\n\t\t\tdata.resize(n_steps, b_dim+u_dim);\n\t\t\tVectorXd theta;\n\t\t\t//gPCI->rad->composeBelief(toVectorXd(gPCI->rad->GetDOFValues()), rt_Sigma0, theta);\n\t\t\tVectorXd x;\n\t\t\tconst DblVec& xvec = gPCI->rad->GetDOFValues();\n\t\t\tfor(int i = 0; i < xvec.size(); ++i) { x[i] = xvec[i]; }\n\n\t\t\t//cout << x << endl;\n\t\t\t//cout << rt_Sigma0 << endl;\n\t\t\t//cout << theta << endl;\n\n\t\t\tgPCI->rad->composeBelief(x, rt_Sigma0, theta);\n\t\t\tfor (int i=0; i < n_steps; i++) {\n\t\t\t\tdata.block(i,0,1,b_dim) = theta.transpose();\n\t\t\t\tif (i != (n_steps-1)) {\n\t\t\t\t\tVectorXd u = VectorXd::Zero(u_dim);\n\t\t\t\t\tdata.block(i,b_dim,1,u_dim) = u.transpose();\n\t\t\t\t\ttheta = gPCI->rad->BeliefDynamics(theta,u);\n\t\t\t\t} else {\n\t\t\t\t\tdata.block(i,b_dim,1,u_dim) = VectorXd::Zero(u_dim).transpose();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if (type_str == \"given_traj\") {\n\t\tFAIL_IF_FALSE(v.isMember(\"data\"));\n\t\tconst Value& data_v = v[\"data\"];\n\t\tTrajArray x_data;\n\t\tJson::fromJson(data_v, x_data);\n\t\tif (x_data.rows()!=n_steps) PRINT_AND_THROW(\"x data has wrong number of rows\");\n\n\t\tif (!belief_space) {\n\t\t\tif (x_data.cols()!=n_dof) PRINT_AND_THROW(\"x data has wrong number of cols\");\n\t\t\tdata = x_data;\n\t\t} else {\n\t\t\tif (x_data.cols() == b_dim+u_dim) {\n\t\t\t\tdata = x_data;\n\t\t\t} else if (x_data.cols() == n_dof) {\n\t\t\t\tdata.resize(n_steps, b_dim+u_dim);\n\t\t\t\tVectorXd theta;\n\t\t\t\tgPCI->rad->composeBelief(x_data.row(0).transpose(), rt_Sigma0, theta);\n\t\t\t\tfor (int i=0; i < n_steps; i++) {\n\t\t\t\t\tdata.block(i,0,1,b_dim) = theta.transpose();\n\t\t\t\t\tif (i != (n_steps-1)) {\n\t\t\t\t\t\tVectorXd u = x_data.row(i+1).transpose() - x_data.row(i).transpose();\n\t\t\t\t\t\tdata.block(i,b_dim,1,u_dim) = u.transpose();\n\t\t\t\t\t\ttheta = gPCI->rad->BeliefDynamics(theta,u);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdata.block(i,b_dim,1,u_dim) = VectorXd::Zero(u_dim).transpose();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tPRINT_AND_THROW(\"x data has wrong number of cols\");\n\t\t\t}\n\t\t}\n\t}\n\telse if (type_str == \"straight_line\") {\n\t\tFAIL_IF_FALSE(!belief_space);\n\t\tFAIL_IF_FALSE(v.isMember(\"endpoint\"));\n\t\tDblVec endpoint;\n\t\tchildFromJson(v, endpoint, \"endpoint\");\n\t\tif (endpoint.size() != n_dof) {\n\t\t\tPRINT_AND_THROW(boost::format(\"wrong number of dof values in initialization. expected %i got %j\")%n_dof%endpoint.size());\n\t\t}\n\t\tdata = TrajArray(n_steps, n_dof);\n\t\tDblVec start = gPCI->rad->GetDOFValues();\n\t\tfor (int idof = 0; idof < n_dof; ++idof) {\n\t\t\tdata.col(idof) = VectorXd::LinSpaced(n_steps, start[idof], endpoint[idof]);\n\t\t}\n\t}\n}\n\nvoid ProblemConstructionInfo::fromJson(const Value& v) {\n\tchildFromJson(v, basic_info, \"basic_info\");\n\n\tRobotBasePtr robot = (basic_info.robot==\"\") ? GetRobot(*env) : GetRobotByName(*env, basic_info.robot);\n\tif (!robot) {\n\t\tPRINT_AND_THROW(\"couldn't get robot\");\n\t}\n\trad = RADFromName(basic_info.manip, robot);\n\tif (!rad) {\n\t\tPRINT_AND_THROW( boost::format(\"couldn't get manip %s\")%basic_info.manip );\n\t}\n\n\tgPCI = this;\n\tif (v.isMember(\"costs\")) fromJsonArray(v[\"costs\"], cost_infos);\n\tif (v.isMember(\"constraints\")) fromJsonArray(v[\"constraints\"], cnt_infos);\n\n\tchildFromJson(v, init_info, \"init_info\");\n\tgPCI = NULL;\n\n}\nvoid CntInfo::RegisterMaker(const std::string& type, MakerFunc f) {\n\tname2maker[type] = f;\n}\n\nTrajOptResult::TrajOptResult(OptResults& opt, TrajOptProb& prob) :\n\t\t\t\t  cost_vals(opt.cost_vals),\n\t\t\t\t  cnt_viols(opt.cnt_viols) {\n\tBOOST_FOREACH(const CostPtr& cost, prob.getCosts()) {\n\t\tcost_names.push_back(cost->name());\n\t}\n\tBOOST_FOREACH(const ConstraintPtr& cnt, prob.getConstraints()) {\n\t\tcnt_names.push_back(cnt->name());\n\t}\n\ttraj = getTraj(opt.x, prob.GetVars());\n}\n\nVector3d endEffectorPosition(BeliefRobotAndDOFPtr brad, VectorXd dofs) {\n\tVector3d eetrans;\n\tbrad->ForwardKinematics(dofs, eetrans);\n\n\tdouble c6 = cos((double)dofs[6]);\n\tdouble s6 = sin((double)dofs[6]);\n\n\teetrans[0] = c6*eetrans[0] - s6*eetrans[1];\n\teetrans[0] = s6*eetrans[0] + c6*eetrans[1];\n\teetrans[2] = eetrans[2] + 0.16;\n\n\treturn eetrans;\n}\n\nvoid renderSigmaPts(BeliefRobotAndDOFPtr rad, const MatrixXd& sigma_pts, const osg::Vec4f& colorvec, vector<GraphHandlePtr>& handles, OSGViewerPtr viewer) {\n\tvector<KinBody::LinkPtr> links;\n\tvector<int> joint_inds;\n\trad->GetAffectedLinks(links, true, joint_inds);\n\n\t// render sigma points\n\t//\tfor (int j=0; j<sigma_pts.cols(); j++) {\n\t//\t\trad->SetDOFValues(toDblVec(sigma_pts.col(j)));\n\t//\t\thandles.push_back(viewer->PlotKinBody(rad->GetRobot()));\n\t////\t\tif (j==0) SetColor(handles.back(), osg::Vec4f(0,0,1,1));\n\t////\t\telse //SetColor(handles.back(), osg::Vec4f(0,0,1,1));\n\t//\t\tSetColor(handles.back(), colorvec);\n\t//\t}\n\n\t// render convex hulls of sigma points\n\tvector<DblVec> dofvals(sigma_pts.cols());\n\tfor (int i=0; i<sigma_pts.cols(); i++)\n\t\tdofvals[i] = toDblVec(sigma_pts.col(i));\n\t//cc->SetContactDistance(100);\n\tboost::shared_ptr<CollisionChecker> cc = CollisionChecker::GetOrCreate(*rad->GetRobot()->GetEnv());\n\tcc->PlotCastHull(*rad, links, dofvals, handles);\n}\n\nvoid renderTrajectory(BeliefRobotAndDOFPtr brad, OSGViewerPtr viewer, const TrajArray& traj, vector<GraphHandlePtr>& handles, int sample_rate = 1) {\n\t//\tviewer->GetEnv()->Load(\"/home/alex/rll/trajopt/data/barrett_sensor_wall.env.xml\");\n\t//\tKinBodyPtr wall = viewer->GetEnv()->GetKinBody(\"wall\");\n\t//\thandles.push_back(viewer->PlotKinBody(wall));\n\t//\tSetColor(handles.back(), osg::Vec4f(0.8,0.8,0,1));\n\t//\tSetTransparency(handles.back(), 0.1);\n\t//\tviewer->GetEnv()->Remove(wall);\n\n\tint n_skipped = sample_rate;\n\tint n_dof = brad->GetDOF();\n\tint b_dim = brad->GetBDim();\n\tVector3d last_ee_pos = endEffectorPosition(brad, traj.block(0,0,1,n_dof).transpose());\n\tfor (int i=0; i<traj.rows(); i++) {\n\t\tif ((n_skipped < sample_rate) && ((endEffectorPosition(brad, traj.block(i,0,1,n_dof).transpose())-last_ee_pos).norm()<0.1) && (i != (traj.rows()-1))) {\n\t\t\tn_skipped++;\n\t\t\tcontinue;\n\t\t}\n\t\tn_skipped = 0;\n\t\tlast_ee_pos = endEffectorPosition(brad, traj.block(i,0,1,n_dof).transpose());\n\n\t\tbrad->SetDOFValues(toDblVec(traj.block(i,0,1,n_dof).transpose()));\n\t\thandles.push_back(viewer->PlotKinBody(brad->GetRobot()));\n\t\tif (i==0 || i==(traj.rows()-1)) renderSigmaPts(brad, brad->sigmaPoints(traj.block(i,0,1,b_dim).transpose()), osg::Vec4f(0,1,0,0.2), handles, viewer);\n\t\tviewer->Idle();\n\t}\n\n\tviewer->Idle();\n\tviewer->Idle();\n\tviewer->Idle();\n\tviewer->Idle();\n}\n\nbool isTrajectoryInCollision(CollisionCheckerPtr cc, TrajArray traj, BeliefRobotAndDOFPtr rad) {\n\tvector<Collision> collisions;\n\tcc->DiscreteCheckTrajectory(traj, rad, collisions);\n\tfor (int i=0; i<collisions.size(); i++) {\n\t\tif (collisions[i].distance < 0) return true;\n\t}\n\treturn false;\n}\n\ndouble calcTrajectoryCost(BeliefRobotAndDOFPtr brad, const TrajArray& traj) {\n\tint x_dim = brad->GetXDim(), b_dim = brad->GetBDim(), u_dim = brad->GetUDim();\n\tVectorXd theta(b_dim);\n\tVectorXd u(u_dim);\n\tVectorXd x(x_dim);\n\tMatrixXd rt_Sigma(x_dim,x_dim);\n\tMatrixXd Sigma(x_dim,x_dim);\n\tMatrixXd Q = MatrixXd::Identity(x_dim,x_dim)*10;\n\tMatrixXd R = MatrixXd::Identity(u_dim,u_dim)*0.1;\n\tdouble total_cost = 0;\n\tfor (int i=0; i<traj.rows(); i++) {\n\t\ttheta = traj.block(i,0,1,b_dim).transpose();\n\t\tu = traj.block(i,b_dim,1,u_dim).transpose();\n\t\tbrad->decomposeBelief(theta, x, rt_Sigma);\n\t\ttotal_cost += ((MatrixXd) (Q*rt_Sigma*rt_Sigma.transpose())).trace() + u.transpose()*R*u;\n\t}\n\treturn total_cost;\n}\n\nVectorXd SimulateAndReplan(const Json::Value& root, OpenRAVE::EnvironmentBasePtr env, bool sigma_pts_scale, bool interactive) {\n\tProblemConstructionInfo pci(env);\n\tpci.fromJson(root);\n\n\tTrajArray& traj = pci.init_info.data;\n\tTrajArray init_traj = traj;\n\tBeliefRobotAndDOFPtr brad = pci.rad;\n\tbrad->SetSigmaPointsScale(sigma_pts_scale);\n\tint n_steps = pci.basic_info.n_steps;\n\tint x_dim = brad->GetXDim(), b_dim = brad->GetBDim(), u_dim = brad->GetUDim(), q_dim = brad->GetQDim(), r_dim = brad->GetRDim();\n\tTrajArray plan_traj = TrajArray::Zero(n_steps, b_dim+u_dim);\n\tTrajArray exec_mpc_traj = TrajArray::Zero(n_steps, b_dim+u_dim);\n\tTrajArray exec_mpc_gt_traj = TrajArray::Zero(n_steps, x_dim);\n\tTrajArray exec_open_traj = TrajArray::Zero(n_steps, b_dim+u_dim);\n\tTrajArray exec_open_gt_traj = TrajArray::Zero(n_steps, x_dim);\n\t//\tTrajArray exec_mpc_traj(n_steps, b_dim);\n\t//\tTrajArray plan_traj(n_steps, b_dim+u_dim);\n\t//\tTrajArray exec_open_traj(n_steps, b_dim);\n\tdouble mpc_trans_err, open_trans_err;\n\n\tVectorXd theta_init = traj.block(0,0,1,b_dim).transpose();\n\tVectorXd x_init;\n\tMatrixXd rt_Sigma_init;\n\tbrad->decomposeBelief(theta_init, x_init, rt_Sigma_init);\n\tx_init = brad->mvnrnd(x_init, rt_Sigma_init * rt_Sigma_init.transpose());\n\tbrad->composeBelief(x_init, rt_Sigma_init, theta_init);\n\n\tMatrixXd qq(q_dim, n_steps);\n\tfor (int j=0; j<n_steps; j++) {\n\t\tqq.col(j) = brad->VectorXdRand(q_dim);\n\t}\n\tMatrixXd rr(r_dim, n_steps);\n\tfor (int j=0; j<n_steps; j++) {\n\t\trr.col(j) = brad->VectorXdRand(r_dim);\n\t}\n\n\n\tVectorXd x;\n\tVectorXd x_gt;\n\tMatrixXd rt_Sigma;\n\tVectorXd theta;\n\tVector3d trans_gt, trans_est;\n\n\tstruct timeval startTimeStruct;\n\tgettimeofday(&startTimeStruct, NULL);\n\tunsigned long int startTime = startTimeStruct.tv_sec*(long unsigned int)(1e6) + startTimeStruct.tv_usec;\n\n\t// MPC\n\tx = x_init;\n\tx_gt = x_init;\n\trt_Sigma = rt_Sigma_init;\n\ttheta = theta_init;\n\tint i=0;\n\tdo {\n\t\tgPCI = &pci;\n\t\tif (root.isMember(\"costs\")) fromJsonArray(root[\"costs\"], pci.cost_infos);\n\t\tif (root.isMember(\"constraints\")) fromJsonArray(root[\"constraints\"], pci.cnt_infos);\n\t\tgPCI = NULL;\n\n\t\tTrajOptProbPtr prob = ConstructProblem(pci);\n\t\tTrajOptResultPtr result = OptimizeProblem(prob, interactive);\n\t\tif (i==0) plan_traj = result->traj;\n\t\tVectorXd u = result->traj.block(0,b_dim,1,u_dim).transpose();\n\t\texec_mpc_traj.block(i,0,1,b_dim) = theta.transpose();\n\t\texec_mpc_traj.block(i,b_dim,1,u_dim) = u.transpose();\n\n\t\t// simulate dynamics and observe\n\t\tVectorXd q = qq.col(i);\n\t\tVectorXd r = rr.col(i);\n\t\tx_gt = brad->Dynamics(x_gt,u,q);\n\t\tVectorXd z = brad->Observe(x_gt,r);\n\t\texec_mpc_gt_traj.row(i) = x_gt.transpose();\n\n\t\tbrad->ekfUpdate(u, x, rt_Sigma, x, rt_Sigma, true, z);\n\n\t\tDblVec lower, upper;\n\t\tbrad->GetDOFLimits(lower, upper);\n\t\tfor (int j=0; j<x.size(); j++) {\n\t\t\tif (x(j) < lower[j]) x(j) = lower[j] + STEP;\n\t\t\tif (x(j) > upper[j]) x(j) = upper[j] - STEP;\n\t\t}\n\n\t\tbrad->composeBelief(x, rt_Sigma, theta);\n\n\t\tbrad->SetDOFValues(toDblVec(x));\n\t\tcout << \"setting robot with dofs values \" << endl;\n\t\tcout << x.transpose() << endl;\n\t\tcout << \"actual robot dofs values are \" << endl;\n\t\tcout << toVectorXd(brad->GetDOFValues()).transpose() << endl;\n\t\ttraj = result->traj.bottomRows(result->traj.rows()-1);\n\t\ttraj.block(0,0,1,b_dim) = theta.transpose();\n\t\tpci.basic_info.n_steps--;\n\n\t\tcout << \"-------------------------------------------\" << endl;\n\n\t\ti++;\n\t} while (pci.basic_info.n_steps > 1);\n\texec_mpc_traj.block(n_steps-1,0,1,b_dim) = theta.transpose();\n\texec_mpc_traj.block(n_steps-1,b_dim,1,u_dim) = VectorXd::Zero(u_dim).transpose();\n\texec_mpc_gt_traj.row(n_steps-1) = x_gt.transpose();\n\tmpc_trans_err = (endEffectorPosition(brad, x) - endEffectorPosition(brad, x_gt)).norm();\n\n\tgettimeofday(&startTimeStruct, NULL);\n\tunsigned long int curTime = startTimeStruct.tv_sec*(long unsigned int)(1e6) + startTimeStruct.tv_usec;\n\n\tcout << \"Total MPC time (s): \" << (1e-6) * (curTime - startTime) << endl;\n\n\t// non MPC\n\tx = x_init;\n\tx_gt = x_init;\n\trt_Sigma = rt_Sigma_init;\n\ttheta = theta_init;\n\tfor (int i=0; i<n_steps-1; i++) {\n\t\tVectorXd u = plan_traj.block(i,b_dim,1,u_dim).transpose();\n\n\t\texec_open_traj.block(i,0,1,b_dim) = theta.transpose();\n\t\texec_open_traj.block(i,b_dim,1,u_dim) = u.transpose();\n\n\t\tVectorXd q = qq.col(i);\n\t\tVectorXd r = rr.col(i);\n\t\tx_gt = brad->Dynamics(x_gt,u,q);\n\t\tVectorXd z = brad->Observe(x_gt,r);\n\t\texec_open_gt_traj.row(i) = x_gt.transpose();\n\n\t\tbrad->ekfUpdate(u, x, rt_Sigma, x, rt_Sigma, true, z);\n\t\tbrad->composeBelief(x, rt_Sigma, theta);\n\t}\n\texec_open_traj.block(n_steps-1,0,1,b_dim) = theta.transpose();\n\texec_open_traj.block(n_steps-1,b_dim,1,u_dim) = VectorXd::Zero(u_dim).transpose();\n\texec_open_gt_traj.row(n_steps-1) = x_gt.transpose();\n\topen_trans_err = (endEffectorPosition(brad, x) - endEffectorPosition(brad, x_gt)).norm();\n\n\tcout << \"-------------------------------------------\" << endl;\n\tcout << \"cost exec_mpc_traj \" << calcTrajectoryCost(brad, exec_mpc_traj) << \"\\t\" << mpc_trans_err << endl;\n\tcout << \"cost exec_open_traj \" << calcTrajectoryCost(brad, exec_open_traj) << \"\\t\" << open_trans_err << endl;\n\tcout << \"cost plan_traj \" << calcTrajectoryCost(brad, plan_traj) << endl;\n\n\tboost::shared_ptr<CollisionChecker> cc = CollisionChecker::GetOrCreate(*brad->GetRobot()->GetEnv());\n\tcout << isTrajectoryInCollision(cc, exec_mpc_gt_traj.leftCols(x_dim), brad) << endl;\n\tcout << isTrajectoryInCollision(cc, exec_open_gt_traj.leftCols(x_dim), brad) << endl;\n\tcout << isTrajectoryInCollision(cc, plan_traj.leftCols(x_dim), brad) << endl;\n\n\tVectorXd stats(8);\n\tstats << calcTrajectoryCost(brad, exec_mpc_traj), calcTrajectoryCost(brad, exec_open_traj), calcTrajectoryCost(brad, plan_traj), mpc_trans_err, open_trans_err,\n\t\t\tisTrajectoryInCollision(cc, exec_mpc_gt_traj.leftCols(x_dim), brad), isTrajectoryInCollision(cc, exec_open_gt_traj.leftCols(x_dim), brad),\n\t\t\tisTrajectoryInCollision(cc, plan_traj.leftCols(x_dim), brad);\n\n\tOSGViewerPtr viewer = OSGViewer::GetOrCreate(brad->GetRobot()->GetEnv());\n\tvector<GraphHandlePtr> handles;\n\n\tbool inter = false;\n\tif (inter) {\n\t\tbool gen_figs = false;\n\t\twhile (true) {\n\t\t\tcout << \"executed MPC\" << endl;\n\t\t\tif (gen_figs) dynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(0,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,1,0));\n\t\t\trenderTrajectory(brad, viewer, exec_mpc_traj, handles, 3);\n\t\t\tif (gen_figs) {\n\t\t\t\tviewer->Idle();\n\t\t\t\tdynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(4,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,0,1));\n\t\t\t\tviewer->Idle();\n\t\t\t}\n\t\t\thandles.clear();\n\n\t\t\tcout << \"executed open loop\" << endl;\n\t\t\tif (gen_figs) dynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(0,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,1,0));\n\t\t\trenderTrajectory(brad, viewer, exec_open_traj, handles, 3);\n\t\t\tif (gen_figs) {\n\t\t\t\tviewer->Idle();\n\t\t\t\tdynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(4,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,0,1));\n\t\t\t\tviewer->Idle();\n\t\t\t}\n\t\t\thandles.clear();\n\n\t\t\tcout << \"planned\" << endl;\n\t\t\tif (gen_figs) dynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(0,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,1,0));\n\t\t\trenderTrajectory(brad, viewer, plan_traj, handles, 3);\n\t\t\tif (gen_figs) {\n\t\t\t\tviewer->Idle();\n\t\t\t\tdynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(4,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,0,1));\n\t\t\t\tviewer->Idle();\n\t\t\t}\n\t\t\thandles.clear();\n\n\t\t\tcout << \"RRT\" << endl;\n\t\t\tif (gen_figs) dynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(0,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,1,0));\n\t\t\trenderTrajectory(brad, viewer, init_traj, handles, 3);\n\t\t\tif (gen_figs) {\n\t\t\t\tviewer->Idle();\n\t\t\t\tdynamic_cast<OSGViewer::EventHandler*>(viewer->GetViewer().getCameraManipulator())->setTransformation(osg::Vec3d(4,0,4), osg::Vec3d(0,0,0), osg::Vec3d(0,0,1));\n\t\t\t\tviewer->Idle();\n\t\t\t}\n\t\t\thandles.clear();\n\t\t}\n\t}\n\treturn stats;\n}\n\nTrajOptResultPtr OptimizeProblem(TrajOptProbPtr prob, bool plot) {\n\tRobotBase::RobotStateSaver saver = prob->GetRAD()->Save();\n\tBasicTrustRegionSQP opt(prob);\n\topt.max_iter_ = 100;\n\topt.min_approx_improve_frac_ = .001;\n\topt.merit_error_coeff_ = 20;\n\topt.max_merit_coeff_increases_ = 10;\n\n\tif (plot) opt.addCallback(PlotCallback(*prob));\n\t//  opt.addCallback(boost::bind(&PlotCosts, boost::ref(prob->getCosts()),boost::ref(*prob->GetRAD()), boost::ref(prob->GetVars()), _1));\n\topt.initialize(trajToDblVec(prob->GetInitTraj()));\n\n\tstruct timeval startTimeStruct;\n\tgettimeofday(&startTimeStruct, NULL);\n\tunsigned long int startTime = startTimeStruct.tv_sec*(long unsigned int)(1e6) + startTimeStruct.tv_usec;\n\n\topt.optimize();\n\n\tgettimeofday(&startTimeStruct, NULL);\n\tunsigned long int curTime = startTimeStruct.tv_sec*(long unsigned int)(1e6) + startTimeStruct.tv_usec;\n\n\tcout << \"Total optimization time (s): \" << (1e-6) * (curTime - startTime) << endl;\n\tTrajOptResultPtr result(new TrajOptResult(opt.results(), *prob));\n\n\treturn result;\n}\n\nTrajOptProbPtr ConstructProblem(const ProblemConstructionInfo& pci) {\n\tTrajOptProbPtr prob(new TrajOptProb());\n\tconst BasicInfo& bi = pci.basic_info;\n\tprob->belief_space = bi.belief_space;\n\tint n_steps = bi.n_steps;\n\n\tprob->m_rad = pci.rad;\n\tint n_dof = prob->m_rad->GetDOF();\n\tint x_dim = prob->m_rad->GetXDim(), b_dim = prob->m_rad->GetBDim(), u_dim = prob->m_rad->GetUDim();\n\n\tDblVec lower, upper;\n\tprob->m_rad->GetDOFLimits(lower, upper);\n\tvector<double> vlower, vupper;\n\tvector<string> names;\n\tfor (int i=0; i < n_steps; ++i) {\n\t\tvlower.insert(vlower.end(), lower.data(), lower.data()+lower.size());\n\t\tvupper.insert(vupper.end(), upper.data(), upper.data()+upper.size());\n\t\tfor (unsigned j=0; j < n_dof; ++j) {\n\t\t\tnames.push_back( (boost::format(\"j_%i_%i\")%i%j).str() );\n\t\t}\n\t\tif (bi.belief_space) {\n\t\t\tfor (unsigned jj=0; jj< n_dof; ++jj) {\n\t\t\t\tfor (unsigned ii=jj; ii < n_dof; ++ii) {\n\t\t\t\t\tnames.push_back( (boost::format(\"cov_%i_%i_%i\")%i%ii%jj).str() );\n\t\t\t\t\tvlower.push_back(-INFINITY);\n\t\t\t\t\tvupper.push_back(INFINITY);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (unsigned j=0; j < n_dof; ++j) {\n\t\t\t\tnames.push_back( (boost::format(\"u_%i_%i\")%i%j).str() );\n\t\t\t\tvlower.push_back(-INFINITY);\n\t\t\t\tvupper.push_back(INFINITY);\n\t\t\t}\n\t\t}\n\t}\n\tprob->createVariables(names, vlower, vupper);\n\n\tif (bi.belief_space)\n\t\tprob->m_traj_vars = VarArray(n_steps, b_dim + u_dim, prob->vars_.data());\n\telse\n\t\tprob->m_traj_vars = VarArray(n_steps, n_dof, prob->vars_.data());\n\n\tDblVec cur_dofvals = prob->m_rad->GetDOFValues();\n\n\tif (bi.start_fixed) {\n\t\tif (pci.init_info.data.rows() > 0 && !allClose(toVectorXd(cur_dofvals), pci.init_info.data.block(0,0,1,n_dof).transpose())) {\n\t\t\tcout << toVectorXd(cur_dofvals).transpose() << endl;\n\t\t\tcout << pci.init_info.data.block(0,0,1,n_dof) << endl;\n\t\t\tLOG_WARN(\"robot dof values don't match initialization. I don't know what you want me to use for the dof values\");\n\t\t}\n\t\tint n_fixed_terms = n_dof;\n\t\tif (bi.belief_space) n_fixed_terms = b_dim;\n\t\tfor (int j=0; j < n_fixed_terms; ++j) {\n\t\t\tprob->addLinearConstr(exprSub(AffExpr(prob->m_traj_vars(0,j)), pci.init_info.data(0,j)), EQ);\n\t\t}\n\t}\n\n\tif (!bi.dofs_fixed.empty()) {\n\t\tBOOST_FOREACH(const int& dof_ind, bi.dofs_fixed) {\n\t\t\tfor (int i=1; i < prob->GetNumSteps(); ++i) {\n\t\t\t\tprob->addLinearConstr(exprSub(AffExpr(prob->m_traj_vars(i,dof_ind)), AffExpr(prob->m_traj_vars(0,dof_ind))), EQ);\n\t\t\t}\n\t\t}\n\t}\n\n\tBOOST_FOREACH(const CostInfoPtr& ci, pci.cost_infos) {\n\t\tci->hatch(*prob);\n\t}\n\tBOOST_FOREACH(const CntInfoPtr& ci, pci.cnt_infos) {\n\t\tci->hatch(*prob);\n\t}\n\n\tif (bi.belief_space) {\n\t\tfor (int i=0; i < n_steps-1; i++) {\n\t\t\tVarVector theta0_vars = prob->m_traj_vars.block(0,0,n_steps,b_dim).row(i);\n\t\t\tVarVector theta1_vars = prob->m_traj_vars.block(0,0,n_steps,b_dim).row(i+1);\n\t\t\tVarVector u_vars = prob->m_traj_vars.block(0,b_dim,n_steps,u_dim).row(i);\n\t\t\tprob->addConstr(ConstraintPtr(new BeliefDynamicsConstraint(theta0_vars, theta1_vars, u_vars, prob->GetRAD())));\n\t\t}\n\t}\n\n\tprob->SetInitTraj(pci.init_info.data);\n\n\treturn prob;\n\n}\nTrajOptProbPtr ConstructProblem(const Json::Value& root, OpenRAVE::EnvironmentBasePtr env) {\n\tProblemConstructionInfo pci(env);\n\tpci.fromJson(root);\n\treturn ConstructProblem(pci);\n}\n\n\nTrajOptProb::TrajOptProb(int n_steps, BeliefRobotAndDOFPtr rad) : m_rad(rad) {\n\tDblVec lower, upper;\n\tm_rad->GetDOFLimits(lower, upper);\n\tint n_dof = m_rad->GetDOF();\n\tvector<double> vlower, vupper;\n\tvector<string> names;\n\tfor (int i=0; i < n_steps; ++i) {\n\t\tvlower.insert(vlower.end(), lower.data(), lower.data()+lower.size());\n\t\tvupper.insert(vupper.end(), upper.data(), upper.data()+upper.size());\n\t\tfor (unsigned j=0; j < n_dof; ++j) {\n\t\t\tnames.push_back( (boost::format(\"j_%i_%i\")%i%j).str() );\n\t\t}\n\t}\n\tcreateVariables(names, vlower, vupper);\n\tm_traj_vars = VarArray(n_steps, n_dof, getVars().data());\n\n}\n\n\nTrajOptProb::TrajOptProb() {\n}\n\nvoid PoseCostInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\tchildFromJson(params, timestep, \"timestep\", gPCI->basic_info.n_steps-1);\n\tchildFromJson(params, xyz,\"xyz\");\n\tchildFromJson(params, wxyz,\"wxyz\");\n\tchildFromJson(params, pos_coeffs,\"pos_coeffs\", (Vector3d)Vector3d::Ones());\n\tchildFromJson(params, rot_coeffs,\"rot_coeffs\", (Vector3d)Vector3d::Ones());\n\n\tstring linkstr;\n\tchildFromJson(params, linkstr, \"link\");\n\tlink = gPCI->rad->GetRobot()->GetLink(linkstr);\n\tif (!link) {\n\t\tPRINT_AND_THROW(boost::format(\"invalid link name: %s\")%linkstr);\n\t}\n}\nCostInfoPtr PoseCostInfo::create() {\n\treturn CostInfoPtr(new PoseCostInfo());\n}\nvoid PoseCostInfo::hatch(TrajOptProb& prob) {\n\tprob.addCost(CostPtr(new CartPoseCost(prob.GetVarRow(timestep), toRaveTransform(wxyz, xyz), rot_coeffs, pos_coeffs, prob.GetRAD(), link)));\n\tprob.getCosts().back()->setName(name);\n}\n\nvoid PoseCntInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\tchildFromJson(params, timestep, \"timestep\", gPCI->basic_info.n_steps-1);\n\tchildFromJson(params, xyz,\"xyz\");\n\tchildFromJson(params, wxyz,\"wxyz\");\n\tchildFromJson(params, pos_coeffs,\"pos_coeffs\", (Vector3d)Vector3d::Ones());\n\tchildFromJson(params, rot_coeffs,\"rot_coeffs\", (Vector3d)Vector3d::Ones());\n\n\tstring linkstr;\n\tchildFromJson(params, linkstr, \"link\");\n\tlink = gPCI->rad->GetRobot()->GetLink(linkstr);\n\tif (!link) {\n\t\tPRINT_AND_THROW(boost::format(\"invalid link name: %s\")%linkstr);\n\t}\n}\n\nvoid JointPosCostInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tint n_steps = gPCI->basic_info.n_steps;\n\tconst Value& params = v[\"params\"];\n\tchildFromJson(params, vals, \"vals\");\n\tchildFromJson(params, coeffs, \"coeffs\");\n\tif (coeffs.size() == 1) coeffs = DblVec(n_steps, coeffs[0]);\n\n\tint n_dof = gPCI->rad->GetDOF();\n\tif (vals.size() != n_dof) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong number of dof vals. expected %i got %i\")%n_dof%vals.size());\n\t}\n\tchildFromJson(params, timestep, \"timestep\", gPCI->basic_info.n_steps-1);\n}\nvoid JointPosCostInfo::hatch(TrajOptProb& prob) {\n\tprob.addCost(CostPtr(new JointPosCost(prob.GetVarRow(timestep), toVectorXd(vals), toVectorXd(coeffs))));\n\tprob.getCosts().back()->setName(name);\n}\nCostInfoPtr JointPosCostInfo::create() {\n\treturn CostInfoPtr(new JointPosCostInfo());\n}\n\n\nCntInfoPtr PoseCntInfo::create() {\n\treturn CntInfoPtr(new PoseCntInfo());\n}\nvoid PoseCntInfo::hatch(TrajOptProb& prob) {\n\tVectorXd coeffs(6); coeffs << rot_coeffs, pos_coeffs;\n\tprob.addConstr(ConstraintPtr(new CartPoseConstraint(prob.GetVarRow(timestep), toRaveTransform(wxyz, xyz), prob.GetRAD(), link, coeffs)));\n\tprob.getEqConstraints().back()->setName(name);\n}\n\nvoid CartVelCntInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\tchildFromJson(params, first_step, \"first_step\");\n\tchildFromJson(params, last_step, \"last_step\");\n\tchildFromJson(params, distance_limit,\"distance_limit\");\n\n\tFAIL_IF_FALSE((first_step >= 0) && (first_step <= gPCI->basic_info.n_steps-1) && (first_step < last_step));\n\tFAIL_IF_FALSE((last_step > 0) && (last_step <= gPCI->basic_info.n_steps-1));\n\n\tstring linkstr;\n\tchildFromJson(params, linkstr, \"link\");\n\tlink = gPCI->rad->GetRobot()->GetLink(linkstr);\n\tif (!link) {\n\t\tPRINT_AND_THROW( boost::format(\"invalid link name: %s\")%linkstr);\n\t}\n}\nCntInfoPtr CartVelCntInfo::create() {\n\treturn CntInfoPtr(new CartVelCntInfo());\n}\nvoid CartVelCntInfo::hatch(TrajOptProb& prob) {\n\tfor (int iStep = first_step; iStep < last_step; ++iStep) {\n\t\tprob.addConstr(ConstraintPtr(new CartVelConstraint(prob.GetVarRow(iStep), prob.GetVarRow(iStep+1), prob.GetRAD(), link, distance_limit)));\n\t\tprob.getIneqConstraints().back()->setName(name);\n\t}\n}\n\nvoid JointVelCostInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\n\tchildFromJson(params, coeffs,\"coeffs\");\n\tint n_dof = gPCI->rad->GetDOF();\n\tif (coeffs.size() == 1) coeffs = DblVec(n_dof, coeffs[0]);\n\telse if (coeffs.size() != n_dof) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong number of coeffs. expected %i got %i\")%n_dof%coeffs.size());\n\t}\n}\nCostInfoPtr JointVelCostInfo::create() {\n\treturn CostInfoPtr(new JointVelCostInfo());\n}\nvoid JointVelCostInfo::hatch(TrajOptProb& prob) {\n\t// belief-alex take the submatrix because we want joint-vel only on the joint variables\n\tprob.addCost(CostPtr(new JointVelCost(prob.GetVars().block(0,0,prob.GetVars().m_nRow, prob.GetRAD()->GetDOF()), toVectorXd(coeffs))));\n\tprob.getCosts().back()->setName(name);\n}\n\nvoid CollisionCostInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\n\tint n_steps = gPCI->basic_info.n_steps;\n\tchildFromJson(params, coeffs,\"coeffs\");\n\tif (coeffs.size() == 1) coeffs = DblVec(n_steps, coeffs[0]);\n\telse if (coeffs.size() != n_steps) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong size: coeffs. expected %i got %i\")%n_steps%coeffs.size() );\n\t}\n\tchildFromJson(params, dist_pen,\"dist_pen\");\n\tif (dist_pen.size() == 1) dist_pen = DblVec(n_steps, dist_pen[0]);\n\telse if (dist_pen.size() != n_steps) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong size: dist_pen. expected %i got %i\")%n_steps%dist_pen.size() );\n\t}\n\tchildFromJson(params, belief_space,\"belief_space\", false);\n}\nvoid CollisionCostInfo::hatch(TrajOptProb& prob) {\n\tfor (int i=0; i < prob.GetNumSteps(); ++i) {\n\t\tif (belief_space)\n\t\t\tprob.addCost(CostPtr(new CollisionCost(dist_pen[i], coeffs[i], prob.GetRAD(), prob.GetVars().rblock(i,0,prob.GetRAD()->GetBDim()))));\n\t\telse\n\t\t\tprob.addCost(CostPtr(new CollisionCost(dist_pen[i], coeffs[i], prob.GetRAD(), prob.GetVars().rblock(i,0,prob.GetRAD()->GetDOF()))));\n\t\tprob.getCosts().back()->setName( (boost::format(\"%s_%i\")%name%i).str() );\n\t}\n\tCollisionCheckerPtr cc = CollisionChecker::GetOrCreate(*prob.GetEnv());\n\tcc->SetContactDistance(*std::max_element(dist_pen.begin(), dist_pen.end()) + .04);\n}\nCostInfoPtr CollisionCostInfo::create() {\n\treturn CostInfoPtr(new CollisionCostInfo());\n}\n\n\nvoid ContinuousCollisionCostInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\n\tint n_steps = gPCI->basic_info.n_steps;\n\tchildFromJson(params, first_step, \"first_step\", 0);\n\tchildFromJson(params, last_step, \"last_step\", n_steps-1);\n\tchildFromJson(params, coeffs, \"coeffs\");\n\tint n_terms = last_step - first_step;\n\tif (coeffs.size() == 1) coeffs = DblVec(n_terms, coeffs[0]);\n\telse if (coeffs.size() != n_terms) {\n\t\tPRINT_AND_THROW (boost::format(\"wrong size: coeffs. expected %i got %i\")%n_terms%coeffs.size());\n\t}\n\tchildFromJson(params, dist_pen,\"dist_pen\");\n\tif (dist_pen.size() == 1) dist_pen = DblVec(n_terms, dist_pen[0]);\n\telse if (dist_pen.size() != n_terms) {\n\t\tPRINT_AND_THROW(boost::format(\"wrong size: dist_pen. expected %i got %i\")%n_terms%dist_pen.size());\n\t}\n}\nvoid ContinuousCollisionCostInfo::hatch(TrajOptProb& prob) {\n\tfor (int i=first_step; i < last_step; ++i) {\n\t\tprob.addCost(CostPtr(new CollisionCost(dist_pen[i], coeffs[i], prob.GetRAD(), prob.GetVars().rblock(i,0,prob.GetRAD()->GetDOF()), prob.GetVars().rblock(i+1,0,prob.GetRAD()->GetDOF()))));\n\t\tprob.getCosts().back()->setName( (boost::format(\"%s_%i\")%name%i).str() );\n\t}\n\tCollisionCheckerPtr cc = CollisionChecker::GetOrCreate(*prob.GetEnv());\n\tcc->SetContactDistance(*std::max_element(dist_pen.begin(), dist_pen.end()) + .04);\n}\nCostInfoPtr ContinuousCollisionCostInfo::create() {\n\treturn CostInfoPtr(new ContinuousCollisionCostInfo());\n}\n\n\nvoid CollisionCntInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\n\tint n_steps = gPCI->basic_info.n_steps;\n\tchildFromJson(params, coeffs,\"coeffs\");\n\tif (coeffs.size() == 1) coeffs = DblVec(n_steps, coeffs[0]);\n\telse if (coeffs.size() != n_steps) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong size: coeffs. expected %i got %i\")%n_steps%coeffs.size() );\n\t}\n\tchildFromJson(params, dist_pen,\"dist_pen\");\n\tif (dist_pen.size() == 1) dist_pen = DblVec(n_steps, dist_pen[0]);\n\telse if (dist_pen.size() != n_steps) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong size: dist_pen. expected %i got %i\")%n_steps%dist_pen.size() );\n\t}\n\tchildFromJson(params, belief_space,\"belief_space\", false);\n}\nvoid CollisionCntInfo::hatch(TrajOptProb& prob) {\n\tfor (int i=0; i < prob.GetNumSteps(); ++i) {\n\t\tif (belief_space)\n\t\t\tprob.addConstr(ConstraintPtr(new CollisionConstraint(dist_pen[i], coeffs[i], prob.GetRAD(), prob.GetVars().rblock(i,0,prob.GetRAD()->GetBDim()))));\n\t\telse\n\t\t\tprob.addConstr(ConstraintPtr(new CollisionConstraint(dist_pen[i], coeffs[i], prob.GetRAD(), prob.GetVars().rblock(i,0,prob.GetRAD()->GetDOF()))));\n\t\tprob.getConstraints().back()->setName( (boost::format(\"%s_%i\")%name%i).str() );\n\t}\n\tCollisionCheckerPtr cc = CollisionChecker::GetOrCreate(*prob.GetEnv());\n\tcc->SetContactDistance(*std::max_element(dist_pen.begin(), dist_pen.end()) + .04);\n}\nCntInfoPtr CollisionCntInfo::create() {\n\treturn CntInfoPtr(new CollisionCntInfo());\n}\n\n\nvoid ContinuousCollisionCntInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\n\tint n_steps = gPCI->basic_info.n_steps;\n\tchildFromJson(params, first_step, \"first_step\", 0);\n\tchildFromJson(params, last_step, \"last_step\", n_steps-1);\n\tchildFromJson(params, coeffs, \"coeffs\");\n\tint n_terms = last_step - first_step;\n\tif (coeffs.size() == 1) coeffs = DblVec(n_terms, coeffs[0]);\n\telse if (coeffs.size() != n_terms) {\n\t\tPRINT_AND_THROW (boost::format(\"wrong size: coeffs. expected %i got %i\")%n_terms%coeffs.size());\n\t}\n\tchildFromJson(params, dist_pen,\"dist_pen\");\n\tif (dist_pen.size() == 1) dist_pen = DblVec(n_terms, dist_pen[0]);\n\telse if (dist_pen.size() != n_terms) {\n\t\tPRINT_AND_THROW(boost::format(\"wrong size: dist_pen. expected %i got %i\")%n_terms%dist_pen.size());\n\t}\n}\nvoid ContinuousCollisionCntInfo::hatch(TrajOptProb& prob) {\n\tfor (int i=first_step; i < last_step; ++i) {\n\t\tprob.addConstr(ConstraintPtr(new CollisionConstraint(dist_pen[i], coeffs[i], prob.GetRAD(), prob.GetVars().rblock(i,0,prob.GetRAD()->GetDOF()), prob.GetVars().rblock(i+1,0,prob.GetRAD()->GetDOF()))));\n\t\tprob.getConstraints().back()->setName( (boost::format(\"%s_%i\")%name%i).str() );\n\t}\n\tCollisionCheckerPtr cc = CollisionChecker::GetOrCreate(*prob.GetEnv());\n\tcc->SetContactDistance(*std::max_element(dist_pen.begin(), dist_pen.end()) + .04);\n}\nCntInfoPtr ContinuousCollisionCntInfo::create() {\n\treturn CntInfoPtr(new ContinuousCollisionCntInfo());\n}\n\n\nvoid JointConstraintInfo::fromJson(const Value& v) {\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\tchildFromJson(params, vals, \"vals\");\n\n\tint n_dof = gPCI->rad->GetDOF();\n\tif (vals.size() != n_dof) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong number of dof vals. expected %i got %i\")%n_dof%vals.size());\n\t}\n\tchildFromJson(params, timestep, \"timestep\", gPCI->basic_info.n_steps-1);\n}\n\nvoid JointConstraintInfo::hatch(TrajOptProb& prob) {\n\tVarVector vars = prob.GetVarRow(timestep);\n\tint n_dof = vars.size();\n\tfor (int j=0; j < n_dof; ++j) {\n\t\tprob.addLinearConstr(exprSub(AffExpr(vars[j]), vals[j]), EQ);\n\t}\n}\nCntInfoPtr JointConstraintInfo::create() {\n\treturn CntInfoPtr(new JointConstraintInfo());\n}\n\n\n\nvoid ControlCostInfo::fromJson(const Value& v) {\n\tbelief_space = gPCI->basic_info.belief_space;\n\tif (!belief_space) {\n\t\tLOG_WARN(\"control cost can only be used in belief space. ignoring.\");\n\t\treturn;\n\t}\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\n\tchildFromJson(params, coeffs,\"coeffs\");\n\tint n_dof = gPCI->rad->GetDOF();\n\tif (coeffs.size() == 1) coeffs = DblVec(n_dof, coeffs[0]);\n\telse if (coeffs.size() != n_dof) {\n\t\tPRINT_AND_THROW( boost::format(\"wrong number of coeffs. expected %i got %i\")%n_dof%coeffs.size());\n\t}\n}\nCostInfoPtr ControlCostInfo::create() {\n\treturn CostInfoPtr(new ControlCostInfo());\n}\nvoid ControlCostInfo::hatch(TrajOptProb& prob) {\n\tif (!belief_space) return;\n\tprob.addCost(CostPtr(new ControlCost(prob.GetVars().block(0,prob.GetRAD()->GetBDim(),prob.GetVars().m_nRow-1, prob.GetRAD()->GetDOF()), toVectorXd(coeffs))));\n}\n\nvoid ControlCntInfo::fromJson(const Value& v) {\n\tbelief_space = gPCI->basic_info.belief_space;\n\tif (!belief_space) {\n\t\tLOG_WARN(\"control constraint can only be used in belief space. ignoring.\");\n\t\treturn;\n\t}\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\tchildFromJson(params, u_min, \"u_min\");\n\tchildFromJson(params, u_max, \"u_max\");\n}\nCntInfoPtr ControlCntInfo::create() {\n\treturn CntInfoPtr(new ControlCntInfo());\n}\nvoid ControlCntInfo::hatch(TrajOptProb& prob) {\n\tif (!belief_space) return;\n\tint b_dim = prob.GetRAD()->GetBDim(), u_dim = prob.GetRAD()->GetUDim();\n\tfor (int i=0; i < prob.GetVars().m_nRow-1; i++) {\n\t\tfor (int j=b_dim; j < b_dim+u_dim; j++) {\n\t\t\tprob.addLinearConstr(exprSub(AffExpr(prob.GetVars()(i,j)), u_max), INEQ);\n\t\t\tprob.addLinearConstr(exprMult(exprSub(AffExpr(prob.GetVars()(i,j)), u_min), -1), INEQ);\n\t\t}\n\t}\n}\n\nvoid CovarianceCostInfo::fromJson(const Value& v) {\n\tbelief_space = gPCI->basic_info.belief_space;\n\tif (!belief_space) {\n\t\tLOG_WARN(\"covariance cost can only be used in belief space. ignoring.\");\n\t\treturn;\n\t}\n\tFAIL_IF_FALSE(v.isMember(\"params\"));\n\tconst Value& params = v[\"params\"];\n\n\tFAIL_IF_FALSE(params.isMember(\"Q\"));\n\tconst Value& Q_array = params[\"Q\"];\n\tJson::fromJson(Q_array, Q);\n\n\tint n_dof = gPCI->rad->GetDOF();\n\tif (Q.rows()!=n_dof) PRINT_AND_THROW(\"cost matrix for the covariance has wrong number of rows\");\n\tif (Q.cols()!=n_dof) PRINT_AND_THROW(\"cost matrix for the covariance has wrong number of cols\");\n}\nCostInfoPtr CovarianceCostInfo::create() {\n\treturn CostInfoPtr(new CovarianceCostInfo());\n}\nvoid CovarianceCostInfo::hatch(TrajOptProb& prob) {\n\tif (!belief_space) return;\n\tint n_steps = prob.GetVars().m_nRow;\n\tint b_dim = prob.GetRAD()->GetBDim(), u_dim = prob.GetRAD()->GetUDim();\n\tfor (int i=0; i < n_steps; ++i) {\n\t\tVarVector rtSigma_vars = prob.GetVars().rblock(i,u_dim,b_dim-u_dim);\n\t\tprob.addCost(CostPtr(new CovarianceCost(rtSigma_vars, Q, prob.GetRAD())));\n\t}\n}\n\n}\n", "meta": {"hexsha": "7d64d79f66a10d1b336dc57947d538a67b4234f4", "size": 41012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trajopt/problem_description.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/problem_description.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/problem_description.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": 37.0478771454, "max_line_length": 202, "alphanum_fraction": 0.6995025846, "num_tokens": 12448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.03410042669392811, "lm_q1q2_score": 0.011409642714016635}}
{"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 used to build full BZ collision operators as well as the functions and\n/// classes used to take and store the exponential of such operator in an\n/// efficient way\n\n#include <vector>\n#include <tuple>\n#include <utilities.hpp>\n#include <bulk_hdf5.hpp>\n#include <boost/mpi.hpp>\n#include <isotopic_scattering.hpp>\n#include <Eigen/Dense>\n#include <unordered_map>\n#if BOOST_VERSION >= 106700\n#include <boost/container_hash/hash.hpp>\n#else\n#include <boost/functional/hash.hpp>\n#endif\n/// Specialization of std space used for collision_operator.cpp\nnamespace std {\n/// Creating a std template specialization of less functional\ntemplate <> struct less<std::array<std::size_t, 3>> {\n    bool operator()(const std::array<std::size_t, 3>& a,\n                    const std::array<std::size_t, 3>& b) const {\n        return std::tuple<std::size_t, std::size_t, std::size_t>(\n                   {a[0], a[1], a[2]}) <\n               std::tuple<std::size_t, std::size_t, std::size_t>(\n                   {b[0], b[1], b[2]});\n    }\n};\n/// Trivial implementation of std::hash for pairs,\n/// required to create an unordered_map with pair as key.\ntemplate <typename T> struct hash<std::pair<T, T>> {\n    std::size_t operator()(const std::pair<T, T>& key) const {\n        hash<T> backend;\n        std::size_t nruter = 0;\n        boost::hash_combine(nruter, backend(key.first));\n        boost::hash_combine(nruter, backend(key.second));\n        return nruter;\n    }\n};\n/// Trivial implementation of std::hash for arrays,\n/// required to create an unordered_set of arrays.\ntemplate <typename T, std::size_t S> struct hash<std::array<T, S>> {\n    std::size_t operator()(const array<T, S>& key) const {\n        hash<T> backend;\n        std::size_t nruter = 0;\n\n        for (auto& e : key)\n            boost::hash_combine(nruter, backend(e));\n        return nruter;\n    }\n};\n} // namespace std\n\n\n/// This boost specialization of serialization is required to\n/// perform MPI operations of the matrix stored quantities\nnamespace boost {\nnamespace serialization {\n/// This one is for three phonon elements\ntemplate <typename Archive, typename T1, typename T2, typename T3>\nvoid serialize(Archive& ar,\n               std::tuple<T1, T2, T3>& t,\n               const unsigned int version) {\n    ar& std::get<0>(t);\n    ar& std::get<1>(t);\n    ar& std::get<2>(t);\n}\n\n\ntemplate <typename Archive>\nvoid serialize(Archive& ar,\n               std::pair<std::size_t, double>& t,\n               const unsigned int version) {\n    ar& std::get<0>(t);\n    ar& std::get<1>(t);\n}\n\n/// Eigen Matrix serialization:\ntemplate <class Archive>\nvoid serialize(Archive& ar,\n               Eigen::Matrix<double, -1, 1>& t,\n               const unsigned int version) {\n    Eigen::MatrixXd::Index rows = t.rows();\n    Eigen::MatrixXd::Index cols = t.cols();\n\n    ar& rows;\n    ar& cols;\n    // Because our matrix is dynamic we need to ensure resizing\n    if (rows * cols != t.size())\n        t.resize(rows, cols);\n\n    ar& boost::serialization::make_array(t.data(), rows * cols);\n}\n\ntemplate <class Archive>\nvoid serialize(Archive& ar,\n               Eigen::Matrix<double, -1, -1>& t,\n               const unsigned int version) {\n    Eigen::MatrixXd::Index rows = t.rows();\n    Eigen::MatrixXd::Index cols = t.cols();\n\n    ar& rows;\n    ar& cols;\n    // Because our matrix is dynamic we need to ensure resizing\n    if (rows * cols != t.size())\n        t.resize(rows, cols);\n\n    ar& boost::serialization::make_array(t.data(), rows * cols);\n}\n\n\n} // namespace serialization\n} // namespace boost\n\nnamespace alma {\n\n/// Chunck vectors and scatter them\n///@param[in] v2c - vector to chunck and scatter\n///@param[in] world - MPI communicator\ntemplate <class T>\nvoid chunck_and_scatter(std::vector<T>& v2c, boost::mpi::communicator world) {\n    broadcast(world, v2c, 0);\n    auto ranges = parrange(0, v2c.size(), world);\n    std::vector<T> vproc(0);\n    vproc.insert(\n        vproc.begin(), v2c.begin() + ranges.first, v2c.begin() + ranges.second);\n    std::swap(v2c, vproc);\n}\n\n/// Gather data from procs to given rank\n///@param[in] v2c - vector to gather from each proc, the gather data is then\n/// inserted in the selected process\n///@param[in] world - MPI communicator\n///@param[in] where - the id-process in which the vector is gathered\ntemplate <class T>\nvoid gather_from_procs(std::vector<T>& v2c,\n                       boost::mpi::communicator world,\n                       std::size_t where) {\n    std::vector<std::vector<T>> chunckedv;\n\n    gather(world, v2c, chunckedv, where);\n    v2c.clear();\n    if ((std::size_t)world.rank() == where) {\n        for (auto& chunk : chunckedv)\n            std::move(chunk.begin(), chunk.end(), std::back_inserter(v2c));\n        v2c.shrink_to_fit();\n    }\n    else {\n        v2c.shrink_to_fit();\n    }\n}\n\n\n/// It gives the id-process for a given index\n/// @param[in] index - index to look for\n/// @param[in] container_size - the size of the container\n/// @param[in] world_size - the number of processes in that MPI communicator\ninline std::size_t index_proc(std::size_t index,\n                              std::size_t container_size,\n                              std::size_t world_size) {\n    for (std::size_t ip = 0; ip < world_size; ip++) {\n        auto limits = alma::my_jobs(container_size, world_size, ip);\n        if (index >= limits[0] and index < limits[1])\n            return ip;\n    }\n    return world_size;\n}\n\n/// Defining alias for long tuples used to store the full BZ elements to build\n/// collision operator\nusing matel3part = std::tuple<std::size_t, std::size_t, double>;\nusing matel2part = std::pair<std::size_t, double>;\n// template <class T> using std2dvec_<T> = std::vector<std::vector<T>>;\n\n\n/// This is to build B matrix as defined in\n/// [http://dx.doi.org/10.1063/1.4898090] with the inclusion of isotopic\n/// scattering terms\n///@param[in] grid       - qpoint grid\n///@param[in] cell       - crystal structure information\n///@param[in] processes  - three phonon processes in irreductible wedge\n///@param[in] anhIFC     - Anharmonic force constants\n///@param[in] Treference - reference temperature\n///@param[in] world      - MPI communicator\nEigen::MatrixXd get_collision_operator_dense(\n    const Gamma_grid& grid,\n    const Crystal_structure& cell,\n    std::vector<alma::Thirdorder_ifcs>& anhIFC,\n    double Treference,\n    boost::mpi::communicator& world);\n\n/// This calculates the upper bound error for the m-th sized krylov\n/// approximation of exponential with a normalized vector\n///@param[in] A -  matrix from which the exponential is requested\n///@param[in] n -  the krylov subspace size\n///@param[in] t -  real scalar constant multiplying the matrix i.e.: exp(t*A)\ninline long double error_bound(const Eigen::MatrixXd& A, int n, double t = 1.0) {\n    long double At_norm = (t * A).norm();\n    return 2.0 * std::pow(At_norm, n) * std::exp(At_norm) / std::tgamma(n);\n}\n\n\n/// Arnoldi algorithm used to compute the basis n-th krylov subspace generated\n/// by Ab {b,A**2 * b,...,A**(n-1)* b}\n///@param[in]     A - matrix A (see function purpose)\n///@param[in]     b - vector b (see function purpose)\n///@param[in]     n - krylov subspace order\n///@param[in,out] B - Matrix to store the basis (each vector of the basis is\n/// stored in different column)\n///@param[in,out] H - A in the krylov subspace basis\n///@param[in]     t - constant multiplying the A matrix so that the real matrix\n/// is A' = t*A\nvoid Arnoldi_algorithm(const Eigen::MatrixXd& A,\n                       const Eigen::VectorXd& b,\n                       int n,\n                       Eigen::MatrixXd& B,\n                       Eigen::MatrixXd& H,\n                       double t = 1.0);\n\n\n/// Storage of propagator as histogram\nclass propagator_H {\nprivate:\n    mutable Eigen::VectorXd signed_cumm; /// Signed cummulative function\n    double\n        pcol_abssum; /// The summ of abs value of original matrix - this is only\n                     /// requested to be able to reconstruct P from histograms\n    \n    /// Some definitions to serialize the class\n    friend class boost::serialization::access;\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int version) {\n        ar& signed_cumm;\n        ar& pcol_abssum;\n    }\n\n    struct abs_less {\n        bool operator()(const double& a, const double& b) const {\n            return std::abs(a) < std::abs(b);\n        }\n    };\n\n    /// Adaptation of lower bound to work with signed cumm\n    template <class T> std::size_t lower_bound(T value) const {\n        auto it = std::lower_bound(this->signed_cumm.data(),\n                                   this->signed_cumm.data() + this->signed_cumm.rows(),\n                                   value,\n                                   abs_less());\n        return std::distance(signed_cumm.data(),it);\n    }\n\n    friend alma::propagator_H lirp(\n        alma::propagator_H& H1,\n        alma::propagator_H& H2,\n        double T1, \n        double T2, \n        double Tx);\n    \npublic:\n    /// Empty constructor\n    propagator_H();\n\n    /// Constructor\n    ///@param[in]  data      - pointer to data to construct the histogram\n    propagator_H(Eigen::VectorXd& b);\n    ///@param[in] signed_cumm_ - the signed cummulative function\n    ///@param[in] pcol_abssum_ - the abs sum of column values\n    propagator_H(Eigen::VectorXd& signed_cumm_, double pcol_abssum_)\n        : signed_cumm(signed_cumm_), pcol_abssum(pcol_abssum_){};\n\n\n    /// Destructor is compiler default\n    ~propagator_H() = default;\n    /// Move constructor\n    propagator_H(propagator_H&& B);\n\n    /// Copy constructor\n    propagator_H(const propagator_H& B);\n\n    /// Assignement operator\n    propagator_H& operator=(const propagator_H& B);\n\n    /// comparison operator is dummy constructed\n    bool operator<(const propagator_H& B) const;\n\n    /// Given a random number it selects a mode\n    ///@param[in] - R - number [0,1] not [0,1) as the last bit will not be\n    /// selected with proper probability\n    std::pair<int, std::size_t> get(double R) const;\n\n    /// Returns the vector with the info\n    Eigen::VectorXd get_signed_cumm() const;\n\n    /// Returns the abs col summ\n    double get_pcol_abssum() const {\n        return this->pcol_abssum;\n    }\n\n    /// It return the size in bytes of all class\n    std::size_t byte_size() const;\n\n    /// It return the number of non-zero elements\n    std::size_t size() const;\n};\n\n/// Function to interpolate two historgrams at different temperatures:\n///@param[in] H1 - histogram at low  temperature\n///@param[in] H2 - histogram at high temperature\n///@param[in] T1 - low  T\n///@param[in] T2 - high T\n///@param[in] Tx - T at which the histogram must be interpolated\nalma::propagator_H lirp(alma::propagator_H& H1,\n                        alma::propagator_H& H2,\n                        double T1,\n                        double T2,\n                        double Tx);\n\n/// Function to interpolate two propagators at different temperatures:\n///@param[in] P1 - propagator at low  temperature\n///@param[in] P2 - propagator at high temperature\n///@param[in] T1 - low  T\n///@param[in] T2 - high T\n///@param[in] Tx - T at which the propagator must be interpolated\ninline Eigen::MatrixXd lirp(Eigen::MatrixXd& P1,\n                            Eigen::MatrixXd& P2,\n                            double T1,\n                            double T2,\n                            double Tx) {\n    return P1 + (Tx - T1) * (P2 - P1) / (T2 - T1);\n}\n\n/// Function to dump P matrix to eigen binary from histogram:\n///@param[in] fname  - File name without format extension\n///@param[in] data   - reference to P to save\n///@param[in] world  - MPI communicator\nvoid save_P(std::string fname,\n            Eigen::MatrixXd& data,\n            boost::mpi::communicator& world);\n\n\n/// Function to load P matrix from eigen binary:\n///@param[in]     fname  - File name without format extension\n///@param[in,out] pmat   - Pmatrix\n///@param[in]     world  - MPI communicator\nvoid load_P(std::string fname,\n            Eigen::MatrixXd& pmat,\n            boost::mpi::communicator& world);\n\n/// Builds up a histogram of propagator matrix.\n///@param[in]     A - Collision operator in energy form\n///@param[in,out] modes_histo - histogram of propagator matrix\n///@param[in]     t - time step\n///@param[in]     world - MPI communicator\n///@param[in]     eps   - tolerance to select the order of krylov subspace\n///@param[in]     print_info - print_info\nvoid build_histogram(Eigen::MatrixXd& A,\n                     std::unordered_map<std::size_t, propagator_H>& modes_histo,\n                     double t,\n                     boost::mpi::communicator& world,\n                     double eps = 1.0e-8,\n                     bool print_info = false);\n\n\n/// Builds up propagator matrix.\n///@param[in]     A - Collision operator in energy form\n///@param[in,out] modes_histo - histogram of propagator matrix\n///@param[in]     t - time step\n///@param[in]     world - MPI communicator\n///@param[in]     eps   - tolerance to select the order of krylov subspace\nvoid build_P(Eigen::MatrixXd& A,\n             Eigen::MatrixXd& P,\n             double t,\n             boost::mpi::communicator& world,\n             double eps = 1.0e-8);\n\n\n} // namespace alma\n", "meta": {"hexsha": "358f6a92fb2b836b918c8e67c0c6d7f6b677129b", "size": 13859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/collision_operator.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/collision_operator.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/collision_operator.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": 34.9093198992, "max_line_length": 87, "alphanum_fraction": 0.6268129014, "num_tokens": 3518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.03021458379267781, "lm_q1q2_score": 0.011407234172545187}}
{"text": "#include <fstream>\n#include <algorithm>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n//#include <boost/numeric/ublas/assignment.hpp> //for easy initialization of vectors with <<=\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/format.hpp>\n\n#include <ctime>\n#include <math.h> /*acos*/\n#include <sstream> // for concatenating strings\n#include <iomanip>\n\n#include \"simulation.hpp\"\n\n#include \"defs.hpp\"\n\n#include <boost/algorithm/string.hpp>\n\n\nnamespace ublas = boost::numeric::ublas;\nusing namespace std;\n\nSimulation::Simulation(unsigned int nParticles, double dt, double relGamma, double gamma0, double omega, int seed, string file, bool cont): \n\t epot2(0),epot3(0), msd(0),\n\t nParticles_(nParticles), t_(0), dt_(dt),\n\t rng_(seed),rndm_(0,1),dice_(rng_,rndm_),\n\t T_(0.001),gamma1_(1),gamma2_(0.5),\n\t NN(1,4),GB(1,4),WBX(1,4),WBY(1,4),WBZ(1,4),RR(1,4),\n\t posX(1,3),posY(1,3),posZ(1,3),\n\t gamma0_(gamma0), omega_(omega),\n\t stress(0), gStorage(0), gLoss(0),\n\t t_startShear_(0),\n\t nAv(40), eTotAveraged(0),\n\t relGamma_(relGamma),\n\t nCross(0),inFile(file), CONTINUE(cont),\n\t cut_(0.05)\n     {\n     \tstring folder = \"/usr/scratch1/fischer.andreas/results/runs/\";\n    \t//string folder = \"/home/andreas/polymer/results/\";\n     \toutFolder = createTimeDir(folder);\n\n\t \tinitStreams_();\n\t \t//initialize_();\n\t \t\n\t \t//inFile = \"xonly_lc1.000000_L1.000000_xp6_nx1000.0_relGamma1_equilibrated.txt\";\n\n\t \t//\"xonly_lc1.000000_L1.000000_xp6_nx1000.0.txt\";\n\t \t//\"xonly_lc1.000000_L1.000000_xp6_nx1000.0_relD1_equilibrated.txt\";\n\t \t//\"xonly_lc1.000000_L1.000000_xp6_nx1000.0.txt\";\n\t \t//\"xonly_lc1.000000_L1.000000_xp6_nx1000.0_equilibrated.txt\"\n\t \t//\"xonly_lc1.000000_L1.000000_xp6_nx1000.0_relD0.001_equilibrated.txt\";\n\n\t \tloadNetwork(file);\n\n\t \tdouble totFil=0;\n\t \tfor(int i=0; i<NATOMS;i++)\n\t \t{\n\t \t\tfor(int j=0; j<4;j++)\n\t \t\t{\n\t \t\t\ttotFil+=RR(i,j);\n\t \t\t}\n\t \t}\n\t \tcout << \"totFil1: \" << totFil << \"\\n\";\n\n\n\t \tif(CONTINUE==false)\n\t \t{\n\t \t\tcorrectRR_(0); // corrects RR=0 entries to a random entry between 0 and 0.1\n\t \t}\n\n\t \ttotFil=0;\n\t \tfor(int i=0; i<NATOMS;i++)\n\t \t{\n\t \t\tfor(int j=0; j<4;j++)\n\t \t\t{\n\t \t\t\ttotFil+=RR(i,j);\n\t \t\t}\n\t \t}\n\t \tcout << \"totFil2: \" << totFil << \"\\n\";\n\n\t \tcreateCrosslinks();\n\n\t \tcreatePairList();\n\n\t \tcreateTripleList();\n\n\t \ttotFil=0;\n\n\t \tfor(unsigned int i=0; i<particlePairs2_.size(); i++)\n\t \t{\n\t \t\ttotFil+=particlePairs2_.at(i).getContourLength();\n\t \t}\n\t \tcout << \"totFil: \" << totFil << \"\\t\" << \"nPairs:\"<< particlePairs2_.size() << \"\\n\";\n\n\t \tint NN2=0, NN3=0, NN4=0;\n\t \tint nn;\n\t \tfor(int i=0; i<NATOMS;i++)\n\t \t{\n\t \t\tnn=0;\n\t \t\tfor(int j=0; j<4;j++)\n\t \t\t{\n\t \t\t\tnn+=1-GB(i,j);\n\t \t\t}\n\t \t\tif(nn==2)\n\t \t\t{\n\t \t\t\tNN2+=1;\n\t \t\t}\n\t \t\telse if(nn==3)\n\t \t\t{\n\t \t\t\tNN3+=1;\n\t \t\t}\n\t \t\telse if(nn==4)\n\t \t\t{\n\t \t\t\tNN4+=1;\n\t \t\t}\n\t \t}\n\t \tcout << NN2 << \"\\t\" << NN3 << \"\\t\" << NN4 << \"\\n\";\n\n\t \t//sampleCoordinates();\n\t \tsampleRR();\n\n\t \tcout << \"continue: \" << CONTINUE << \"\\n\";\n\n\t \tcout << \"gamma0: \" << gamma0 << \", omega: \" << omega << \", relGamma: \" << relGamma_ << \", dt: \" << dt << \"\\n\";\n\n\n\t \tif (CONTINUE==false)\n\t \t{\n\t \t\trngseed(seed);\n\t \t}\n\t \telse\n\t \t{\n\t \t\trnginit(rIA, rpp, rp);\n\t \t}\n\n\n\t \tstringstream ss;\n\t\tss << outFolder << \"network\" << \"_str\" << gamma0_ << \"_w\" << omega_ << \"_dt\" << dt_ << \"_rg\" << relGamma_ ;\n\t\toutFolderNW = ss.str();\n\t\tstring sys_command = \"mkdir \" + outFolderNW;\n\n\t\tconst char * comm = sys_command.c_str();\n\n\t \tsystem(comm);\n\n\t \tsampleNetwork();\n\t \tsampleTriples();\n\t }\n\nvoid Simulation::initStreams_() {\n\tstringstream ss;\n\tss << \"_str\" << gamma0_ << \"_w\" << omega_ << \"_dt\" << dt_ << \"_rg\" << relGamma_ << \"_cut\" << cut_;\n\tstring s = ss.str();\n\n\tstring coordinateFile, energyFile, energyAvFile, rrFile, pairFile, tripleFile, debugFile, filLengthFile, angleFile, clDistFile;//, networkFile;\n\tcoordinateFile=outFolder + \"coord\" + s +\".dat\";\n\tenergyFile=outFolder + \"energy\" + s +\".dat\";\n\tenergyAvFile= outFolder + \"energyAv\" + s +\".dat\";\n\n\trrFile= outFolder + \"rr\" + s + \".dat\";\n\n\tpairFile= outFolder + \"pairs\" + s + \".dat\";\n\ttripleFile= outFolder + \"triples\" + s + \".dat\";\n\n\tdebugFile= outFolder + \"debug\" + s + \".dat\";\n\n\tfilLengthFile = outFolder + \"filLength\" + s + \".dat\";\n\n\tangleFile = outFolder + \"angles\" + s + \".dat\";\n\n\tclDistFile = outFolder + \"clDist\" + s + \".dat\";\n\n\t//coordinatesStream_.open (coordinateFile);\n  \t//coordinatesStream_<< \"# id \\t r[0] \\t r[1] \\t r[2]\" << endl;\n\n\tenergyStream_.open(energyFile);\t\n  \tenergyStream_<< \"# t \\t epot2 \\t epot3  \\t etot \\t FXY \\t stress2 \\t stress3 \\t stress \\t ghostFilLength \\t pairFilLength \\t totFilLength\" << endl;\n  \tenergyStream_.precision(9);\n\n    debugStream.open(debugFile);\n\n    filLengthStream_.open(filLengthFile);\n\n    angleStream_.open(angleFile);\n\n  \trrStream_.open(rrFile);\n  \trrStream_<< \"# id \\t RR0 \\t RR1 \\t RR2 \\t RR3\" << endl;\n\n  \tclDistStream_.open(clDistFile);\n\n  \t//pairStream_.open(pairFile);\n  \t//pairStream_ << \"# id1 \\t id2 \\t l12 \\t k2 \\t Leq \\t r12Abs\" << endl;\n   \t\n   \ttripleStream_.open(tripleFile);\n  \ttripleStream_ << \"# id1 \\t id2 \\t id3 \\t angle\" << endl; \t\n  \t\n  \t//energyAveragedStream_.open (energyAvFile);\n  \t//energyAveragedStream_ << \"# t  \\t etot \\t FXY\"<< endl;\n  \t//energyAveragedStream_.precision(9);\n}\n\n\nvoid Simulation::integrate(unsigned int nSteps) {\n\tublas::vector<double> r(3,0);\n\n\n\tfor(size_t i=1;i<=nSteps;i++) {\n\n\t\t/*if(i==1){\n\t\t\tt_startShear_=t_;\n\t\t}*/\n\n\t\t//if(i>400000){\n\t\tshear_();\n\t\t\t//cout << FXY << \"\\n\";\n\t\t//}\n\t\tstress=0;\n\t\tstress2=0;\n\t\tstress3=0;\n\n        force_(); // force calculation\n       \n        if (relGamma_>0){\n        \tcalcPullProperties();\n        }\n        //cout << RR(10,3) << \"\\n\";\n        //if(i>50000){\n        stress=stress2+stress3;\n        //}\n\n        sampleEnergy();\n\n        vector<double> elong,springC,contLength,fPull,theta,clDist; \n        ublas::vector<double> r1(3,0),r2(3,0);\n        ublas::vector<int> WB(3,0);\n\t\tublas::vector<double> FtimesWB(3,0);\n        double r12Abs;\n        if(i%1 == 0)\n        {\n        \tfor( unsigned int i=0; i<particlePairs2_.size(); i++)\n        \t{\t\n        \t\t//cout << particlePairs2_.size();\n        \t\tCrosslinkPair2 clpair = particlePairs2_.at(i);\n        \t\telong.push_back(clpair.r12Abs-clpair.Leq);\n        \t\tspringC.push_back(clpair.k2);\n        \t\tcontLength.push_back(clpair.getContourLength());\n\n        \t\tr1=clpair.getCrosslink(1)->getPosition();\n        \t\tr2=clpair.getCrosslink(2)->getPosition();\n        \t\tWB[0]=clpair.getWBX(); WB[1]=clpair.getWBY(); WB[2]=clpair.getWBZ();\n\t\t\t\tFtimesWB[0]=FXX*WB[0]+FXY*WB[1]; FtimesWB[1]=FYY*WB[1]; FtimesWB[2]=FZZ*WB[2]; // F*WB (F=matrix, WB=vector)\n\t\t\t\tr2 += FtimesWB;  \n        \t\tr12Abs=ublas::norm_2(r1-r2);\n        \t\tclDist.push_back(r12Abs);\n\t        }\n\n\t        for( unsigned int i=0;i<particleTriples2_.size(); i++)\n\t        {\n\t        \tCrosslinkTriple2 cltriple = particleTriples2_.at(i);\n\t        \tfPull.push_back(abs(cltriple.getfPull()));\n\t        \tif(cltriple.getDummy()==0)\n\t        \t{\n\t        \t\ttheta.push_back(cltriple.getAngle());\n\t        \t}\n\t        }\n\n      \t\tdebugStream << t_ << \"\\t\" << *max_element(elong.begin(),elong.end()) << \"\\t\" << *max_element(springC.begin(),springC.end()) << \"\\t\" <<\n      \t    *min_element(contLength.begin(),contLength.end()) << \"\\t\" << *max_element(contLength.begin(),contLength.end()) <<\"\\t\" << *max_element(fPull.begin(),fPull.end()) << \"\\t\" << epot2 << \"\\n\";\n    \t}\n        \n\n        euler_(); // integrate equations of motion;\n\n        t_ += dt_;\n        //applyPeriodicBC_();\n        \n        if (i%1000 == 0)\n        {\n        \t//sampleCoordinates();\n        \tsampleRR();\n        \t//sampleTriples();\n        \t//samplePairs();\n        \tsampleNetwork();\n        \tsampleFilLength(contLength);\n        \tsampleAngles(theta);\n        \tsampleClDist(clDist);\n        \tcout << t_ << \"\\n\";\t\n        \t//cout << nCross << \"\\n\";\n        \t//cout << FXY << \"\\n\";\n        \t//compareForces_();\n\n        }\n\n        /*for(int i=0;i<NATOMS;i++)\n        {\n        \tfor(int j=0;j<4;j++)\n        \t\tif(RR(i,j)<0){cout << \"some negative RR\" << \"\\n\";}\n        }*/\n        // check if arclength is conserved\n        /*if (i%100 == 0){\n        double RRSUM=0;\n\t        for(int i=0; i<NATOMS;i++)\n\t        {\n\t        \tfor(int j=0; j<4;j++)\n\t        \t{\n\t        \t\tRRSUM+=RR(i,j);\n\t        \t}\n\t        }\n\t        cout << RRSUM << \"\\n\";\n\t    }*/\n\t}\n\n}\n\n\nvoid Simulation::resetForce_() {\n\tublas::vector<double> f(3,0);\n\tfor (std::vector<Crosslink>::iterator particlei = particles_.begin(); particlei != particles_.end(); ++particlei)\n\t{\n\t\tparticlei->updateForce(f);\n\t\tparticlei->updateFilForce(f,1);\n\t\tparticlei->updateFilForce(f,2);\n\t\t//particlei->filament1_.updateForce(f);\n\t\t//particlei->filament2_.updateForce(f);\n\t}\n}\n\n\nvoid Simulation::force_() {\n\tresetForce_(); //sets force to zero;\n\n\tepot2=0;\n\tepot3=0;\n\n\t//for (std::vector<Crosslink>::iterator particlei = particles_.begin(); particlei != particles_.end(); ++particlei)\n\tfor ( unsigned int i=0; i<particlePairs2_.size(); i++)\n\t{\t\n\n\t\tforce2_(particlePairs2_.at(i));\n\n\t\t\n\t}\n\tfor ( unsigned int i=0; i<particleTriples2_.size(); i++)\n\t{\t\n\t\tforce3_(particleTriples2_.at(i));\n\n\t}\n}\n\n\nvoid Simulation::force2_(CrosslinkPair2 &clPair){\n\t\n\tublas::vector<double> r1(3,0),r2(3,0);\n\tublas::vector<double> f1(3,0),f2(3,0);\n\tublas::vector<double> r12(3,0);\n\tdouble r12Abs=0;\n\tdouble epotPair=0;\n\tublas::vector<int> WB(3,0);\n\tublas::vector<double> FtimesWB(3,0);\n\tint filId1, filId2;\n\n\tdouble l12; // length of polymer between cl 1 and 2\n\tdouble k2; // spring constant\n\tdouble Leq; //equilibrium length\n\n\tCrosslink *cl1 = clPair.getCrosslink(1);\n\tCrosslink *cl2 = clPair.getCrosslink(2);\n\t//int filId = clPair.getFilId();\n\n\tr1=cl1->getPosition();\n\tr2=cl2->getPosition();\n\t//!!!!periodic boundary conditions!!!!\n\tWB[0]=clPair.getWBX(); WB[1]=clPair.getWBY(); WB[2]=clPair.getWBZ();\n\t\n\tFtimesWB[0]=FXX*WB[0]+FXY*WB[1]; FtimesWB[1]=FYY*WB[1]; FtimesWB[2]=FZZ*WB[2]; // F*WB (F=matrix, WB=vector)\n\t//cout << FtimesWB << \"\\n\";\n\tr2 += FtimesWB;  \n\t//!!!!!//\n\n\tr12 = r2-r1;\n\tr12Abs=ublas::norm_2(r12);\n\t//calculate k2 and Leq\n\tl12=clPair.getContourLength();\n\tk2=90./pow(l12,4);\n\tLeq=l12*(1-l12/6.);\n\n\tclPair.k2=k2;\n\tclPair.r12Abs=r12Abs;\n\tclPair.Leq=Leq;\n\n\t// pair force: harmonic spring with spring constant k2\n\tf1=k2*(r12Abs-Leq)*r12/r12Abs; \t\n\tf2=-f1;\n\n\tclPair.f1=ublas::norm_2(f1);\n\n\n\tfilId1=clPair.getFilId(1);\n\tfilId2=clPair.getFilId(2);\n\n\tcl2->incrForce(f2,filId2);\t\n\n\t//cl2->incrForceFil(f,filId);\n\tcl1->incrForce(f1,filId1);\n\t//cl1->incrForceFil(-1*f,filId);\n\t\n\tepotPair=0.5*k2*pow(r12Abs-Leq,2);\n\tclPair.updateEpotPair(epotPair);\n\tepot2+=epotPair;\n\n\t//cout << \"k2: \" << k2 << \"  Leq: \" << Leq << \"    deltaRabs: \" << deltaRabs << \"    f: \" << f << \"\\n\";\n\n\t// compute stress sigma_xy=- (r2[0]-r1[0])*f1[1]\t\n\tstress2+=r12[0]*f1[1];\n}\n\nvoid Simulation::force3_(CrosslinkTriple2 &clTriple){\n\t\n\tint iDummy;\n\tdouble angle;//,r12abs,r13abs,r23abs;\n\tublas::vector<double> f1(3,0),f2(3,0),f3(3,0);\n\tublas::vector<double> r1(3,0),r2(3,0),r3(3,0);\n\tublas::vector<double> r12(3,0),r23(3,0),e12(3,0),e23(3,0);\n\tdouble r12abs, r23abs;\n\tdouble epotTriple=0;\n\tublas::vector<int> WB12(3,0),WB23(3,0);\n\tublas::vector<double> FtimesWB12(3,0);\n\tublas::vector<double> FtimesWB23(3,0);\n\n\tdouble l12,l23; // contour lengths between 1,2 and 2,3\n\tdouble k3; // prefactor of force\n\n\tint filId1,filId2,filId3;\n\n\tdouble pref;\n\tdouble angTol=M_PI/100.;\n\n\tCrosslink *cl1 = clTriple.getCrosslink(1);\n\tCrosslink *cl2 = clTriple.getCrosslink(2);\n\tCrosslink *cl3 = clTriple.getCrosslink(3);\n\n\t//int filId = clTriple.getFilId();\n\t\n\n\tiDummy=clTriple.getDummy();\n\tif(iDummy==0) // 3-cl force only if no dummies in triple\n\t{\n\t\tr1=cl1->getPosition();\n\t\tr2=cl2->getPosition();\n\t\tr3=cl3->getPosition();\n\n\t\t///!!!! periodic boundary conditions !!!!\n\t\tWB12[0]=clTriple.getWBX(12); WB12[1]=clTriple.getWBY(12); WB12[2]=clTriple.getWBZ(12);\n\t\tWB23[0]=clTriple.getWBX(23); WB23[1]=clTriple.getWBY(23); WB23[2]=clTriple.getWBZ(23);\n\n\t\tFtimesWB12[0]=FXX*WB12[0]+FXY*WB12[1]; FtimesWB12[1]=FYY*WB12[1]; FtimesWB12[2]=FZZ*WB12[2]; // F*WB (F=matrix, WB=vector)\n\t\tFtimesWB23[0]=FXX*WB23[0]+FXY*WB23[1]; FtimesWB23[1]=FYY*WB23[1]; FtimesWB23[2]=FZZ*WB23[2]; // F*WB (F=matrix, WB=vector)\n\n\n\t\tr1+=FtimesWB12; //was r2!!\n\t\tr3+=FtimesWB23;\n\t\t///!!!\n\n\t\tr12=r2-r1;\n\t\tr23=r3-r2;\n\t\t//cout << ublas::inner_prod(r12,r23) << \"\\n\";\n\t\tr12abs=ublas::norm_2(r12);\n\t\tr23abs=ublas::norm_2(r23);\n\n\t\tangle= acos(ublas::inner_prod(r12,r23)/(r12abs*r23abs));\n\t\t//cout << acos(1) << \"\\n\";\n\n\t\tl12=clTriple.getContourLength(12);\n\t\tl23=clTriple.getContourLength(23);\n\n\t\tk3=1.5/(l12+l23);\n\n\t\tif(angle>angTol)\n\t\t{  // need this condition, because for angle=0, divison by 0 (sin(0)=0)\n\t\t\tpref=angle/sin(angle);\n\t\t}\n\t\telse //taylor expand sin(angle) for small angles\n\t\t{\n\t\t\tpref=1./(1-1./6.*angle*angle+1./120.*angle*angle*angle*angle-1./5040.*angle*angle*angle*angle*angle*angle);\n\t\t}\n\n\n\t\te12=r12/r12abs;\n\t\te23=r23/r23abs;\n\n\t\tf1=(-e23+cos(angle)*e12)/r12abs;\n\t\tf3=(e12-cos(angle)*e23)/r23abs;\n\t\t//f2=k3*2*pref/r12abs/r23abs*(r23-r12-cos(angle)*(r12/r12abs-r23/r23abs));\n\t\tf2=(e23-cos(angle)*e12)/r12abs+(e23*cos(angle)-e12)/r23abs; //10.03.2016\n\n\t\tf1=f1*k3*2*pref;\n\t\tf2=f2*k3*2*pref;\n\t\tf3=f3*k3*2*pref;\n\t\t//cout << f1 << \"\\t\" << f2 << \"\\t\" << f3 << \"\\n\";\n\n\t\t// new forces (!!!WRONG!!!)\n\t\t//f1=-k3*(r12/r12abs/pow((r12abs+r23abs),2)*angle*angle-2*angle/sin(angle)/r12abs*(-r23/r23abs+cos(angle)*r12/r12abs));\n\t\t//f3=-k3*(r23/r23abs/pow((r12abs+r23abs),2)*angle*angle-2*angle/sin(angle)/r23abs*(r12/r12abs-cos(angle)*r23/r23abs));\n\t\t//f2=-k3*((r23/r23abs-r12/r12abs)/pow((r12abs+r23abs),2)*angle*angle-2*angle/sin(angle)/r12abs/r23abs*(r23-r12-cos(angle)*(r12/r12abs-r23/r23abs)));\n\n\t\tfilId1=clTriple.getFilId(1);\n\t\tfilId2=clTriple.getFilId(2);\n\t\tfilId3=clTriple.getFilId(3);\n\n\t\tcl1->incrForce(f1,filId1);\n\t\t//cl1->incrForceFil(f1,filId);\n\t\tcl2->incrForce(f2,filId2);\n\t\t//cl2->incrForceFil(f2,filId);\n\t\tcl3->incrForce(f3,filId3);\n\t\t//cl3->incrForceFil(f3,filId);\n\n\t\t//epotTriple=k3/(r12abs+r23abs)*angle*angle;\n\t\tepotTriple=k3*angle*angle;\n\n\t\tclTriple.updateEpotTriple(epotTriple);\n\t\tclTriple.updateAngle(angle);\n\t\tepot3+=epotTriple;\n\t\t//cout << angle << \"\\n\";\n\n\t\t// compute stress sigma_xy=-((r1[0]-r2[0])*f1[1]+(r3[0]-r2[0])*f3[1]), WRONG!! virial stress is zero for 3-body forces that depend on bond angle only\n\t\tstress3+= (r2[0]-r1[0])*f1[1]+(r2[0]-r3[0])*f3[1]; \n\t}\n}\n\n\nvoid Simulation::euler_() {\n\tublas::vector<double>  noise(3,0);\n\tdouble noise2;\n\tdouble ds;\n\tdouble sigma1;\n\tdouble sigma2=sqrt(2*dt_);//*T_/gamma1_);\n\tdouble l12, l23;\n\tublas::vector<double>  r1(3,0),r2(3,0),r3(3,0);\n\tdouble r12,r23;\n\tint iDummy;\n\t//double cut=0.05;\n\n\t\n\tif(relGamma_!=-1)\n\t{\t\n\t\tint d=0;\n\t\tfor (std::vector<CrosslinkTriple2> ::iterator triplei = particleTriples2_.begin(); triplei != particleTriples2_.end(); triplei++)\n\t\t{\t\n\t\t\tiDummy=triplei->getDummy();\n\t\t\t\n\t\t\t//if(triplei->getDummy() == 0){\n\t\t\t//noise2=dice_();\n\t\t\tnoise2=gaussian_random_number_();\n\t\t\tds=dt_*triplei->getfPull()+sigma2*noise2;\n\t\t\t//cout << ds << \"\\n\";\n\n\t\t\t// FOR DEBUGGING ONLY\n\t\t\tr1=triplei->getCrosslink(1)->getPosition();\n\t\t\tr2=triplei->getCrosslink(2)->getPosition();\n\t\t\tr3=triplei->getCrosslink(3)->getPosition();\n\t\t\tr12=ublas::norm_2(r1-r2);\n\t\t\tr23=ublas::norm_2(r3-r2);\n\t\t\t// FOR DEBUGGING ONLY\n\t\t\tl12=triplei->getContourLength(12);\n\t\t\tl23=triplei->getContourLength(23);\n\t\t\t//cout << l12 << \"\\t\" << l23 << \"\\n\";\n\t\t\t//if( (l12+ds >= r12) && (l23-ds >= r23))\n\t\t\t//{\n\t\t\n\t\t\tif(iDummy==0)\n\t\t\t{\n\t\t\t\t//bool a = (l23-ds>cut_) && (l12+ds>=cut_);\n\n\t\t\t\t//cout << triplei->getCrosslink(1)->getId() << \"\\t\"<< triplei->getCrosslink(2)->getId()<< \"\\t\" << triplei->getCrosslink(3)->getId() << \"\\t\" << a << \"\\t\" << l12 << \"\\t\" << l23 << \"\\t\" << ds << \"\\n\";\n\t\t\t\tif( (l12+ds>cut_) && (l23-ds>cut_) ) // contour length between two crosslinks must be > cut_\n\t\t\t\t{\n\t\t\t\t\ttriplei->incrContourLength(ds,12);\n\t\t\t\t\ttriplei->incrContourLength(-ds,23);\t\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(iDummy==1)\n\t\t\t{\t\n\t\t\t\t//bool a = (l23-ds>cut_) && (l12+ds>=0);\n\t\t\t\t//cout << triplei->getCrosslink(1)->getId() << \"\\t\"<< triplei->getCrosslink(2)->getId()<< \"\\t\" << triplei->getCrosslink(3)->getId() << \"\\t\" << a << \"\\t\" << l12 << \"\\t\" << l23 << \"\\t\" << ds << \"\\n\";\n\t\t\t\tif((l23-ds>cut_) && (l12+ds>=0) )\n\t\t\t\t{\t\n\t\t\t\t\t//cout << l12+ds << \"\\n\";\n\t\t\t\t\t//cout << l23-ds << \"\\n\";\n\t\t\t\t\ttriplei->incrContourLength(ds,12);\n\t\t\t\t\ttriplei->incrContourLength(-ds,23);\n\t\t\t\t\t//cout << triplei->getContourLength(12) << \"\\n\";\n\t\t\t\t\t//cout << triplei->getContourLength(23) << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(iDummy==3)\n\t\t\t{\n\t\t\t\tif( (l12+ds>cut_) && (l23-ds>=0))\n\t\t\t\t{\n\t\t\t\t\ttriplei->incrContourLength(ds,12);\n\t\t\t\t\ttriplei->incrContourLength(-ds,23);\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\n\t\t\tl12=triplei->getContourLength(12);\n\t\t\tl23=triplei->getContourLength(23);\n\n\t\t\tif(l12 < 0 || l23 <0){cout << \"some RR smaller cut\" << \"\\t\" << ds << \"\\n\";}\n\t\t\tif( (l12 < r12) || (l23 < r23))\n\t\t\t{\n\t\t\t\tnCross++;\n\t\t\t}\n\t\t//}\n\t\t\t\n\t\t}\n\t}\n\n\tint id;\n\tublas::vector<double> dr,r,rN;\n\tdouble drN;\n\tint check;\n\n\tdouble rG;\n\n\tfor (std::vector<Crosslink>::iterator particlei = particles_.begin(); particlei != particles_.end(); particlei++)\n\t{\t\n\t\tcheck=1;\n\t\tnoise=gaussian_random_vector2_();\n\n\t\tif(relGamma_==-1){rG=1;}\n\t\telse{rG=relGamma_;}\n\n\t\tsigma1=sqrt(2*rG*dt_);\n\n\t\tdr=\trG*dt_*particlei->getForce()+sigma1*noise;\t\n\n\t\t//cout << sigma1*noise << \"\\t\" << noise << \"\\n\";\n\t\t//cout << relGamma_*dt_*particlei->getForce() << \"\\n\";\n\t\t// check whether step doesn't bring cls too close\n\t\tid=particlei->getId();\n\t\tr=particlei->getPosition();\n\t\tfor(int i=0;i<4;i++)\n\t\t{\n\t\t\tif(GB(id,i)==0)\n\t\t\t{\n\t\t\t\trN=particles_.at(NN(id,i)).getPosition();\n\t\t\t\tdrN=ublas::norm_2(rN-(r+dr));\n\t\t\t\t//cout << drN << \"\\n\";\n\t\t\t\tif(drN<0.001)\n\t\t\t\t{\n\t\t\t\t\tcheck=0;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(check==1)\n\t\t{\n\t\t\tparticlei->incrPosition(dr);\n\t\t}\n\t\t\n\t\t\n\t\t//particlei->incrPosition(sigma1*noise);\n\t\t//DeltaS1=1/gamma*Force1+noise1;\n\t\t//DeltaS2=1/gamma*Force2+noise2;\n\t\t//DeltaR=0.5*(DeltaS1*particlei->filament1_.getPullDirection()+DeltaS2*particlei->filament2_.getPullDirection());\n\t\t//particlei->incrPosition(deltaR);\t\t\n\t}\n}\n\nvoid Simulation::applyPeriodicBC_(){\n\tublas::vector<double> r(3,0);\n\tublas::matrix<int> conTabSelf;\n\tublas::matrix<int> conTabOther;\n\tint k,l;\n\tint deltaWBX, deltaWBY, deltaWBZ;\n\tublas::vector<double> eX(3), eY(3), eZ(3);\n\teX[0]=1;eX[1]=0;ex[2]=0; eY[0]=0;eY[1]=1;eY[2]=0; eZ[0]=0;eZ[1]=0;eZ[2]=1;  \n\tdouble dxPbc, dyPbc, dzPbc;\n\tublas::vector<double> drPbc(3,0);\n\n\tfor (std::vector<Crosslink>::iterator particlei = particles_.begin(); particlei != particles_.end(); particlei++)\n\t{\t\n\t\tdeltaWBX=0; deltaWBY=0; deltaWBZ=0;\n\t\tdxPbc=0; dyPbc=0; dzPbc=0;\n\t\tr=particlei->getPosition();\n\t\tif(r[0] > 0.5*L || r[0] < -0.5*L || r[1] > 0.5*L || r[1] < -0.5*L || r[2] > 0.5*L || r[2] < -0.5*L)\n\t\t{\n\t\t\tconTabSelf=particlei->getConTabSelf();\n\t\t\tconTabOther=particlei->getConTabOther();\n\t\t\tif(r[0]>0.5*L){\n\t\t\t\tdeltaWBX=1;\n\t\t\t\tdxPbc= -L;\n\t\t\t}\n\t\t\telse if(r[0]<-0.5*L){\n\t\t\t\tdeltaWBX=-1;\n\t\t\t\tdxPbc=L;\n\t\t\t}\n\t\t\tif(r[1]>0.5*L){\n\t\t\t\tdeltaWBY=1;\n\t\t\t\tdyPbc= -L;\n\t\t\t}\n\t\t\telse if(r[1]<-0.5*L){\n\t\t\t\tdeltaWBY=-1;\n\t\t\t\tdyPbc=L;\n\t\t\t}\t\n\t\t\tif(r[2]>0.5*L){\n\t\t\t\tdeltaWBZ=1;\n\t\t\t\tdzPbc = -L;\n\t\t\t}\n\t\t\telse if(r[2]<-0.5*L){\n\t\t\t\tdeltaWBZ=-1;\n\t\t\t\tdzPbc = L;\n\t\t\t}\t\n\t\t\tdrPbc <<= dxPbc, dyPbc, dzPbc;\n\t\t\tparticlei->incrPosition(drPbc);\n\n\t\t\tfor(int i=0; i<conTabSelf.size1(); i++){\n\t\t\t\tk=conTabSelf(i,0); \n\t\t\t\tl=conTabSelf(i,1);\n\t\t\t\tWBX(k,l) -= deltaWBX;\n\t\t\t\tWBY(k,l) -= deltaWBY;\n\t\t\t\tWBZ(k,l) -= deltaWBZ;\n\t\t\t\tif(abs(WBX(k,l))>1 || abs(WBY(k,l)) > 1 || abs(WBZ(k,l)) > 1){\n\t\t\t\t\tcout << \"some abs(WB) > 2, probably something went wrong!!\" <<\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor(int i=0; i<conTabOther.size1(); i++){\n\t\t\t\tk=conTabOther(i,0);\n\t\t\t\tl=conTabOther(i,1);\n\t\t\t\tWBX(k,l) += deltaWBX;\n\t\t\t\tWBY(k,l) += deltaWBY;\n\t\t\t\tWBZ(k,l) += deltaWBZ;\n\t\t\t\tif(abs(WBX(k,l))>1 || abs(WBY(k,l)) > 1 || abs(WBZ(k,l)) > 1){\n\t\t\t\t\tcout << \"some abs(WB) > 2, probably something went wrong!!\" <<\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Simulation::sampleCoordinates() {\n\tublas::vector<double> r(3);//, forceFil1(3), forceFil2(3), force(3), pullDir1(3), pullDir2(3);\n\tint id;//,filId1,filId2,filClId11,filClId12,filClId21,filClId22;\n\t//double pullForce1,pullForce2;\n\t//Crosslink* particlei;\n\tcoordinatesStream_ << \"# t=\" << t_ << \"##################\" << \"\\n\"; \n\tfor (std::vector<Crosslink>::iterator particlei = particles_.begin(); particlei != particles_.end(); particlei++)\n\t{\t\t\n\t\tid = particlei->getId();\n\t\tr = particlei->getPosition();\n\t\t//coordinatesStream_ << id << \"\\t\" << r[0] << \"\\t\" << r[1] << \"\\t\" << r[2] << \"\\n\";\n\t\tcoordinatesStream_ << r[0] << \"\\t\" << r[1] << \"\\t\" << r[2] << \"\\n\";\n\t\t/*if(abs(r[0])>0.5 || abs(r[1])>0.5 || abs(r[2])>0.5){\n\t\t\tcout << \"some coordinate outside box --> problem with periodic boundaries\" << \"\\n\";\n\t\t}*/\n\t}\n}\n\n\nvoid Simulation::sampleEnergy() {\n\tdouble ghostFilLength=0, pairFilLength=0, totFilLength=0;\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tfor(int j=0;j<4;j++)\n\t\t{\n\t\t\tif(GB(i,j)==1)\n\t\t\t{\n\t\t\t\tghostFilLength += RR(i,j);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpairFilLength += RR(i,j);\n\t\t\t}\n\t\t}\n\t}\n\tpairFilLength/=2.;\n\n\ttotFilLength=ghostFilLength+pairFilLength;\n\n\tenergyStream_ << t_ << \"\\t\" << epot2 << \"\\t\" << epot3 << \"\\t\" << epot2+epot3 << \"\\t\" << FXY << \"\\t\" << stress2 << \"\\t\" << stress3 << \"\\t\" << stress << \"\\t\" << ghostFilLength << \"\\t\" << pairFilLength << \"\\t\" << totFilLength << endl;\n\t//if(i % nAv == 0){\n\t//energyAveragedStream_ << t_ << \"\\t\" << epot2+epot3 << \"\\t\" << FXY << endl;\n\t//}\n}\n\nvoid Simulation::sampleTriples() {\n\tint id1,id2,id3;\n\tdouble angle;\n\tint iDummy;\n\n\tfor (std::vector<CrosslinkTriple2>::iterator triplei = particleTriples2_.begin(); triplei != particleTriples2_.end(); triplei++)\n\t{\n\t\tiDummy=triplei->getDummy();\n\n\t\t//if(iDummy==0)\n\t\t//{\n\t\t\tid1=triplei->getCrosslink(1)->getId();id2=triplei->getCrosslink(2)->getId();id3=triplei->getCrosslink(3)->getId();\n\t\t\tangle=triplei->getAngle();\n\t\t\ttripleStream_ << t_ << \"\\t\" << id1 << \"\\t\" << id2 << \"\\t\" << id3 << \"\\t\" << angle << \"\\t\" << triplei->getContourLength(12) << \"\\t\" << triplei->getContourLength(23) << endl;\n\t\t//}\t\n\t}\n}\n\nvoid Simulation::samplePairs() {\n\tint id1,id2;\n\tpairStream_ << \"# t=\" << t_ << \"##################\" << \"\\n\"; \n\tfor (std::vector<CrosslinkPair2>::iterator pairi = particlePairs2_.begin(); pairi != particlePairs2_.end(); pairi++)\n\t{\n\t\tid1=pairi->getCrosslink(1)->getId();id2=pairi->getCrosslink(2)->getId();\n\t\tpairStream_ << id1 << \"\\t\" << id2 << \"\\t\" << pairi->getContourLength() << \"\\t\" << pairi->k2 << \"\\t\" << pairi->r12Abs - pairi->Leq << \"\\t\"\n\t\t<< pairi->f1 << \"\\t\" << pairi->Leq << \"\\t\" << pairi-> r12Abs << endl;\n\t}\n}\n\nvoid Simulation::sampleRR() {\n\trrStream_ << \"#t=\" << t_ << \"##################\" << \"\\n\"; \n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\trrStream_ << RR(i,0) << \"\\t\" << RR(i,1) << \"\\t\" << RR(i,2) << \"\\t\" << RR(i,3) << endl;\n\t}\n}\n\nvoid Simulation::sampleFilLength(vector<double> contLength)\n{\t\n\tfilLengthStream_ << \"#t=\" << t_ << \"###############\" << endl;\n\tdouble binSize=0.005;\n\tint nBins=(int) (1./binSize);\n\t//cout << nBins << \"\\n\";\n\tdouble xHist [nBins];\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\txHist[i] = (i+1)*binSize;\n\t}\n\tint yHist [nBins];\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\tyHist[i]=0;\n\t}\n\tint n;\n\n\tfor (int i=0; i<contLength.size(); i++)\n\t{\n\t\tn=floor(contLength[i]/binSize);\n\t\tyHist[n]++;\n\t}\n\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\tfilLengthStream_ << xHist[i] << \"\\t\" << yHist[i] << endl;\n\t}\n\n}\n\nvoid Simulation::sampleAngles(vector<double> theta)\n{\n\tangleStream_ << \"#t=\" << t_ << \"###############\" << endl;\n\n\n\tdouble binSize = 0.02;\n\tint nBins = (int) (1.6/binSize);\n\n\tdouble xHist [nBins];\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\txHist[i] = (i+1)*binSize;\n\t}\n\tint yHist [nBins];\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\tyHist[i]=0;\n\t}\n\tint n;\n\n\tfor (int i=0; i<theta.size(); i++)\n\t{\n\t\tn=floor(theta[i]/binSize);\n\t\tyHist[n]++;\n\t}\n\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\tangleStream_ << xHist[i] << \"\\t\" << yHist[i] << endl;\n\t}\n}\n\nvoid Simulation::sampleClDist(vector<double> clDist)\n{\n\tclDistStream_ << \"#t=\" << t_ << \"###############\" << endl;\n\n\tdouble binSize = 0.005;\n\tint nBins = (int) (1./binSize);\n\n\tdouble xHist [nBins];\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\txHist[i] = (i+1)*binSize;\n\t}\n\tint yHist [nBins];\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\tyHist[i]=0;\n\t}\n\tint n;\n\n\tfor (int i=0; i<clDist.size(); i++)\n\t{\n\t\tn=floor(clDist[i]/binSize);\n\t\tyHist[n]++;\n\t}\n\n\tfor(int i=0;i<nBins;i++)\n\t{\n\t\tclDistStream_ << xHist[i] << \"\\t\" << yHist[i] << endl;\n\t}\n}\n\n\n\nvoid Simulation::sampleNetwork() \n{\n\tstring outFile;\n\n\tstringstream ss;\n\n\t//inFile = \"xonly_lc1.000000_L1.000000_xp6_nx1000.0_relGamma1_equilibrated.txt\";\n\n\tss.precision(9);\n\n\tsize_t txtPos = inFile.find(\".txt\");\n\tstring nw_str = inFile.substr(0,txtPos);\n\n\tss << nw_str << \"_t\" << fixed << t_;\n\tss.precision(4);\n\tss << defaultfloat << \"_str\" << gamma0_ << \"_w\" << defaultfloat << omega_ << \"_dt\" << dt_ << \"_rg\" << relGamma_ ;\n\tstring s = ss.str();\n\n\toutFile= outFolderNW + \"/\" +  s + \".dat\";\n\tnetworkStream_.open(outFile);\n\n\t//networkStream_ << \"###############################\" << endl; \n\t//networkStream_ << defaultfloat << \"#t=\" << t_  << endl; \n\n\tnetworkStream_ << \"#NATOMS=\" << dec << NATOMS << endl;\n\tnetworkStream_ << \"#FEC=1\" << endl;\n\n\tnetworkStream_<<  \"#FXX=\" << std::hexfloat << FXX << endl;\n\tnetworkStream_<< \"#FYY=\" <<  FYY << endl;\n\tnetworkStream_<< \"#FZZ=\" <<  FZZ << endl;\n\tnetworkStream_<< \"#FXY=\" <<  FXY << endl;\n\tnetworkStream_<< \"#FXZ=\" <<  FXZ << endl;\n\tnetworkStream_<< \"#FYZ=\" <<  FYZ << endl;\n\tnetworkStream_<< \"#FYX=\" <<  FYX << endl;\n\tnetworkStream_<< \"#FZX=\" <<  FZX << endl;\n\tnetworkStream_<< \"#FZY=\" <<  FZY << endl;\n\tnetworkStream_<< \"Lp=\" << dec << Lp << endl;\n\tnetworkStream_<< \"#BENDING_PF=0x1.8p+0\" << endl;\n\tnetworkStream_<< \"#StretchEps=0x1.0c6f7a0b5ed8dp-20\" << endl;\n\tnetworkStream_<< \"#rp=\" << rng_p << endl;\n\tnetworkStream_<< \"#rpp=\" << rng_pp << endl;\n\n\tnetworkStream_<< \"#rIA=\";\n\tfor(int i=0; i<54;i++)\n\t{\n\t\tnetworkStream_<< rng_ia[i] << \" \";\n\t}\n\tnetworkStream_<< rng_ia[54] << endl; \n\n\n\tublas::vector<double> r(3,0);\n\n\tfor (std::vector<Crosslink>::iterator particlei = particles_.begin(); particlei != particles_.end(); particlei++)\n\t{\t\t\n\t\tr = particlei->getPosition();\n\t\tnetworkStream_ << hexfloat << r[0] << \"\\t\" << r[1] << \"\\t\" << r[2] << \"\\n\";\n\t}\n\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tnetworkStream_ << dec << NN(i,0) << \" \" << NN(i,1) << \" \" << NN(i,2) << \" \" << NN(i,3) << endl;\n\t}\n\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tnetworkStream_ << dec << GB(i,0) << \" \" << GB(i,1) << \" \" << GB(i,2) << \" \" << GB(i,3) << endl;\n\t}\n\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tnetworkStream_ << hexfloat << RR(i,0) << \" \" << RR(i,1) << \" \" << RR(i,2) << \" \" << RR(i,3) << endl;\n\t}\n\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tnetworkStream_ << dec << WBX(i,0) << \" \" << WBX(i,1) << \" \" << WBX(i,2) << \" \" << WBX(i,3) << endl;\n\t}\n\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tnetworkStream_ << dec << WBY(i,0) << \" \" << WBY(i,1) << \" \" << WBY(i,2) << \" \" << WBY(i,3) << endl;\n\t}\n\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tnetworkStream_ << dec << WBZ(i,0) << \" \" << WBZ(i,1) << \" \" << WBZ(i,2) << \" \" << WBZ(i,3) << endl;\n\t}\n\n\tnetworkStream_.close();\n\n\n}\n\n\n\n\n/* void Simulation::gaussian_random_number_(){\n\tublas::vector<double> randVec(3,0);\n    double f1,f2,p;\n\n    //uniform_real_distribution<double> dis(0.0, 1.0);\n\t\n    //f1=dis(generator_);\n    //f2=dis(generator_);\n    \n    f1=dice_();\n    f2=dice_();\n    p=sqrt(-2.*log(f1));\n\n    randVec[0]=p*cos(2.*M_PI*f2);\n    randVec[1]=p*sin(2.*M_PI*f2);\n\n    //rand_no1_=p*cos(2.*M_PI*f2);\n    //rand_no2_=p*sin(2.*M_PI*f2);\n    // randomStream << rand_no[1] << \"\\n\";\n    // randomStream << rand_no[2] << \"\\n\";\n}*/\n\nublas::vector<double> Simulation::gaussian_random_vector_(){\n\tublas::vector<double> randVector(3,0);\n\trandVector[0]=dice_();\n\trandVector[1]=dice_();\n\trandVector[2]=dice_();\n\treturn randVector;\n}\n\n ublas::vector<double> Simulation::gaussian_random_vector2_(){\n\n \tublas::vector<double> randVec(3,0);\n\n     double f1,f2,f3,f4,p1,p2;\n     \n\n     //f1=dice_();\n     f1=rngmit;\n     //f2=dice_();\n     f2=rngmit;\n\n     p1=sqrt(-2.*log(f1));\n\n     f3=rngmit;\n     //f2=dice_();\n     f4=rngmit;\n\n     p2=sqrt(-2.*log(f3));\n\n     randVec[0]=p1*cos(2.*M_PI*f2);\n\n     randVec[1]=p1*sin(2.*M_PI*f2);\n\n     randVec[2]=p2*cos(2.*M_PI*f4);\n\n     //cout << randVec << \"\\n\";\n\n     return randVec;\n\n \n\n     //rand_no1_=p*cos(2.*M_PI*f2);\n\n     //rand_no2_=p*sin(2.*M_PI*f2);\n\n     // randomStream << rand_no[1] << \"\\n\";\n\n     // randomStream << rand_no[2] << \"\\n\";\n\n }\n\n double Simulation::gaussian_random_number_()\n {\n \tdouble f1,f2,p;\n \tdouble randNo;\n\n \tf1=rngmit;\n \tf2=rngmit;\n\n \tp=sqrt(-2.*log(f1));\n\n \trandNo=p*cos(2.*M_PI*f2);\n\n \treturn randNo;\n }\n\n\nvoid Simulation::mean_square_displacement(){\n\tublas::vector<double> r(3),deltaR(3),r0(3,1);\n\tdouble msd1;\n\tint i=0;\n\tfor (std::vector<Crosslink>::iterator particle = particles_.begin(); particle != particles_.end(); particle++)\n\t{\n\t\ti++;\n\t\tr = particle->getPosition();\n\t\tdeltaR = r-i*r0;\n\t\tmsd1=pow(ublas::norm_2(deltaR),2);\n\t\tmsd+=msd1;\n\t}\t\t\n\tmsd=msd/3000;\n}\n\n\nvoid Simulation::calcPullProperties(){\n\tublas::vector<double> r1(3,0),r2(3,0),r3(3,0);\n\tublas::vector<double> r21(3,0),r23(3,0),r13(3,0);\n\tublas::vector<double> e21(3,0),e23(3,0),e13(3,0);\n\tublas::vector<int> WB12(3,0),WB23(3,0);\n\tublas::vector<double> FtimesWB12(3,0);\n\tublas::vector<double> FtimesWB23(3,0);\n\tublas::vector<double> f2(3,0);\t\n\tdouble f21,f23, f13;\n\tdouble pullforce;\n\tint iDummy;\n\tint filId2;\n\tublas::vector<double> fOtherFil(3,0);\n\t\n\tfor (std::vector<CrosslinkTriple2> ::iterator clTriple = particleTriples2_.begin(); clTriple != particleTriples2_.end(); clTriple++)\n\t{\t\n\t\tCrosslink *cl1 = clTriple->getCrosslink(1);\n\t\tCrosslink *cl2 = clTriple->getCrosslink(2);\n\t\tCrosslink *cl3 = clTriple->getCrosslink(3);\n\t\n\t\tr1=cl1->getPosition();\n\t\tr2=cl2->getPosition();\n\t\tr3=cl3->getPosition();\n\n\t\tiDummy=clTriple->getDummy();\n\n\t\t//if(iDummy==0){\n\t\t///!!!! periodic boundary conditions !!!!\n\t\tWB12[0]=clTriple->getWBX(12); WB12[1]=clTriple->getWBY(12); WB12[2]=clTriple->getWBZ(12);\n\t\tWB23[0]=clTriple->getWBX(23); WB23[1]=clTriple->getWBY(23); WB23[2]=clTriple->getWBZ(23);\n\n\t\tFtimesWB12[0]=FXX*WB12[0]+FXY*WB12[1]; FtimesWB12[1]=FYY*WB12[1]; FtimesWB12[2]=FZZ*WB12[2]; // F*WB (F=matrix, WB=vector)\n\t\tFtimesWB23[0]=FXX*WB23[0]+FXY*WB23[1]; FtimesWB23[1]=FYY*WB23[1]; FtimesWB23[2]=FZZ*WB23[2]; // F*WB (F=matrix, WB=vector)\n\n\n\t\tr1+=FtimesWB12; // was r2!! \n\t\tr3+=FtimesWB23;\n\n\n\t\t// !!! WHEN DUMMY TRIPLE, TAKE CARE!!\n\t\t\n\t\tr21=r1-r2;\n\t\tr23=r3-r2;\n\n\t\tif(iDummy==0)\n\t\t{ \t\n\t\t\te21=r21/ublas::norm_2(r21);\n\t\t\te23=r23/ublas::norm_2(r23);\n\t\t}\n\t\t// set projection direction for dummy crosslinks\n\t\telse if(iDummy==1) \n\t\t{\n\t\t\te23=r23/ublas::norm_2(r23);\n\t\t\te21=-e23;\n\t\t}\n\t\telse if(iDummy==3)\n\t\t{\n\t\t\te21=r21/ublas::norm_2(r21);\n\t\t\te23=-e21;\n\t\t}\n\t\t// !!! CHANGE TO FORCE FROM OTHER FILAMENT !!!\n\t\tfilId2=clTriple->getFilId(2);\n\n\t\tif(filId2==1)\n\t\t{\n\t\t\tfOtherFil=(cl2->getFilForce(2)-cl2->getFilForce(1))*0.5;\n\t\t\t//cout << fOtherFil << \"\\t\" << cl2->getFilForce(2) << \"\\t\" << cl2->getFilForce(1) << \"\\t\" << cl2->getForce() << \"\\n\";\n\n\t\t}\n\t\telse if(filId2==2)\n\t\t{\n\t\t\tfOtherFil=(cl2->getFilForce(1)-cl2->getFilForce(2))*0.5;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"filId Error3\" << \"\\n\";\n\t\t}\n\t\t//fOtherFil=cl2->getForce();\n\t\t// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\t\tr13=r3-r1;\n\t\te13=r13/ublas::norm_2(r13);\n\n\t\tf13=ublas::inner_prod(fOtherFil,e13);\n\n\t\tf21=ublas::inner_prod(fOtherFil,e21);  // project pull force\n\t\tf23=ublas::inner_prod(fOtherFil,e23);\n\n\n\t\tpullforce=f13;\n\n\t\t/*if(f23>f21){\n\t\t\t//pullforce=f23*1;\n\t\t\tpullforce=ublas::norm_2(fOtherFil);\n\t\t}\n\t\telse{\n\t\t\t//pullforce=f21*(-1);\n\t\t\tpullforce=ublas::norm_2(fOtherFil)*(-1);\n\t\t}*/\n\n\t\tclTriple->updatefPull(pullforce);\n\t\t///!! case f23==f21 !! missing\n\t\t/*if(iDummy==0)\n\t\t{\n\t\t\tcout << pullforce << \"\\n\";\n\t\t}*/\n\t//}\n\t}\n\n}\n\n\n\nvoid Simulation::loadNetwork(string file){\t\n\t\n\t// read Lc, L from filename\n\tsize_t lcPos = file.find(\"lc\");\n\tstring Lc_str = file.substr(lcPos+2,8);\n\tLc = stod(Lc_str); // convert string to double\n\tcout << Lc << \"\\n\";\n\n\tsize_t LPos = file.find(\"L\");\n\tstring L_str = file.substr(LPos+1,8);\n\tL = stod(L_str);\n\tcout << L << \"\\n\";\t\n\n\tif(CONTINUE==1){\n\t\tsize_t tPos = file.find(\"_t\");\n\t\tsize_t strPos = file.find(\"_str\");\n\t\tstring t_str = file.substr(tPos+2,strPos-tPos);\n\t\tt_=stod(t_str);\n\t\tcout << t_ << \"\\n\";\n\t}\n\n\t// read parameters from file\n\tifstream infile(file);\n\tstring str;\n\n\n\tstr=readNumber(infile);\n\tNATOMS = stoi(str);  // convert string to int\n\tcout << NATOMS << \"\\n\";\n\tstr=readNumber(infile);\n\tFEC=stoi(str);\n\tcout << FEC << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FXX); // convert hexa-string to double\n\tcout << FXX << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FYY);\n\tcout << FYY << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FZZ);\n\tcout << FZZ << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FXY);\n\tcout << FXY << \"\\n\";\t\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FXZ); \n\tcout << FXZ << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FYX);\n\tcout << FYX << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FYZ);\n\tcout << FYZ << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FZX);\n\tcout << FZX << \"\\n\";\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &FZY);\n\tcout << FZY << \"\\n\";\t\n\tstr=readNumber(infile);\n\t//Lp=stod(str);\n\t::sscanf(str.c_str(), \"%lA\", &Lp);\n\tcout << Lp << \"\\n\";\t\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &BENDING_PF);\n\tcout << BENDING_PF << \"\\n\";\t\n\tstr=readNumber(infile);\n\t::sscanf(str.c_str(), \"%lA\", &StretchEps);\n\tcout << StretchEps << \"\\n\";\t\n\tstr=readNumber(infile);\n\trp=stoi(str);\n\tcout << rp << \"\\n\";\n\tstr=readNumber(infile);\n\trpp=stoi(str);\n\tcout << rpp << \"\\n\";\n\t\n\tstr=readNumber(infile);\n\tcout << str << \"\\n\";\n\tvector<string> strs;\n  \tboost::split(strs,str,boost::is_any_of(\" \"));\n  \tconst char * c;\n  \tfor (size_t i = 0; i < strs.size(); i++){\n  \t\tc = strs[i].c_str();\n  \t\trIA[i]=strtoul(c,NULL,10);\n  \t\t//cout << rIA[i] << endl;\n  \t}\n    //\n\n\t//size_t spacePos=str.find(\" \");\n\t//strtoul\n\n\t//getline(infile,str); // not reading rIA yet!!!\n\n\n\tposX.resize(NATOMS,0); posY.resize(NATOMS,0); posZ.resize(NATOMS,0);\n\n\tstring posX_hex,posY_hex,posZ_hex;\n\n\tNN.resize(NATOMS,4);\n\tGB.resize(NATOMS,4);\n\tRR.resize(NATOMS,4);\n\tWBX.resize(NATOMS,4);WBY.resize(NATOMS,4);WBZ.resize(NATOMS,4);\n\n\n\tstring RR1_hex, RR2_hex, RR3_hex, RR4_hex;\n\n\tfor(int i=0; i<NATOMS; i++){\n\t\tinfile >> posX_hex >> posY_hex >> posZ_hex;\n\t\t//cout << posX_hex << \"\\t\" <<  posY_hex << \"\\t\" << posZ_hex << \"\\n\";\n\t\t\n\t\t//posX(i)=stod(posX_hex);\n\t\t//posY(i)=stod(posY_hex);\n\t\t//posZ(i)=stod(posZ_hex);\n\t\t\n\t\t::sscanf(posX_hex.c_str(), \"%lA\", &posX(i));\n\t\t::sscanf(posY_hex.c_str(), \"%lA\", &posY(i));\n\t\t::sscanf(posZ_hex.c_str(), \"%lA\", &posZ(i));\n\t\t\n\t\t//cout << posX(i) << \"\\t\" <<  posY(i) << \"\\t\" << posZ(i) << \"\\n\";\n\t}\n\tfor(int i=0; i<NATOMS; i++){\n\t\tinfile >> NN(i,0) >> NN(i,1) >> NN(i,2) >> NN(i,3);\n\n\t\t//cout << NN(i,0) << \"\\t\" << NN(i,1) << \"\\t\" << NN(i,2) << \"\\t\" << NN(i,3) << \"\\n\";\n\t}\n\n\tfor(int i=0; i<NATOMS; i++){\n\t\tinfile >>  GB(i,0) >> GB(i,1) >> GB(i,2) >> GB(i,3);\n\n\t\t//cout << GB(i,0) << \"\\t\" << GB(i,1) << \"\\t\" << GB(i,2) << \"\\t\" << GB(i,3) << \"\\n\";\n\t}\n\n\tfor(int i=0; i<NATOMS; i++){\n\t\tinfile >> RR1_hex >> RR2_hex >> RR3_hex >> RR4_hex;\n\n\t\t//cout << RR1_hex << \"\\t\" << RR2_hex<< \"\\t\" << RR3_hex << \"\\t\" << RR4_hex << \"\\n\";\n\t\t//RR(i,0)=stod(RR1_hex);\n\t\t//RR(i,1)=stod(RR2_hex);\n\t\t//RR(i,2)=stod(RR3_hex);\n\t\t//RR(i,3)=stod(RR4_hex);\n\n\t\t::sscanf(RR1_hex.c_str(), \"%lA\", &RR(i,0));\n\t\t::sscanf(RR2_hex.c_str(), \"%lA\", &RR(i,1));\n\t\t::sscanf(RR3_hex.c_str(), \"%lA\", &RR(i,2));\n\t\t::sscanf(RR4_hex.c_str(), \"%lA\", &RR(i,3));\n\n\t\t//cout << RR(i,0) << \"\\t\" << RR(i,1) << \"\\t\" << RR(i,2) << \"\\t\" << RR(i,3) << \"\\n\";\n\t}\n\n\tfor(int i=0; i<NATOMS; i++){\n\t\tinfile >> WBX(i,0) >> WBX(i,1) >> WBX(i,2) >> WBX(i,3);\n\t\t//cout << WBX(i,0) << \"\\t\" << WBX(i,1) << \"\\t\" << WBX(i,2) << \"\\t\" << WBX(i,3) << \"\\n\";\n\t}\n\t\n\tfor(int i=0; i<NATOMS; i++){\n\t\tinfile >> WBY(i,0) >> WBY(i,1) >> WBY(i,2) >> WBY(i,3);\n\t\t//cout << WBY(i,0) << \"\\t\" << WBY(i,1) << \"\\t\" << WBY(i,2) << \"\\t\" << WBY(i,3) << \"\\n\";\n\t}\n\n\tfor(int i=0; i<NATOMS; i++){\n\t\tinfile >> WBZ(i,0) >> WBZ(i,1) >> WBZ(i,2) >> WBZ(i,3);\n\t\t//cout << WBZ(i,0) << \"\\t\" << WBZ(i,1) << \"\\t\" << WBZ(i,2) << \"\\t\" << WBZ(i,3) << \"\\n\";\n\t}\n}\n\nstd::vector<ublas::matrix<int>> Simulation::createConTabSO(int i){\n\tstd::vector<ublas::matrix<int>> result;\n\tublas::matrix<int> conTabSelf(1,2), conTabOther(1,2);\n\tint numbCon = 0;\n\tint line = 0;\n\tint neighLine = 0;\n\tfor(int j=0; j<4; j++)\n\t\t{\n\t\t\tif(GB(i,j)==0)\n\t\t\t{\n\t\t\t\tnumbCon++;\n\t\t\t}\t\n\t\t}\n\t\tconTabSelf.resize(numbCon,2);\n\t\tconTabOther.resize(numbCon,2);\n\t\tfor(int j=0;j<4;j++)\n\t\t{\n\t\t\tif(GB(i,j)==0)\n\t\t\t{\t\t\t\n\t\t\t\tconTabSelf(line,0)=i;\n\t\t\t\tconTabSelf(line,1)=j;\n\t\t\t\tneighLine=NN(i,j);\n\t\t\t\tconTabOther(line,0)=neighLine;\n\t\t\t\tfor(int k=0;k<4;k++)\n\t\t\t\t{\n\t\t\t\t\tif(NN(neighLine,k)==i)\n\t\t\t\t\t{\n\t\t\t\t\t\tconTabOther(line,1)=k;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tline++;\n\t\t\t}\n\t\t}\n\t\tresult.push_back(conTabSelf);\n\t\tresult.push_back(conTabOther);\n\t\treturn result;\n}\n\nvoid Simulation::createCrosslinks(){\n\tublas::vector<double> r(3,0);\n\tstd::vector<ublas::matrix<int>> conTabs;\n\tublas::matrix<int> conTabSelf, conTabOther;\n\n\tfor(int i=0;i<NATOMS;i++){\n\t\tr[0]=posX[i]; r[1]=posY[i]; r[2]=posZ[i];\n\n\t\tconTabs=createConTabSO(i);\n\n\t\tconTabSelf = conTabs.at(0);\n\t\tconTabOther = conTabs.at(1);\n\n\t\tCrosslink cl = Crosslink(i,r,conTabSelf,conTabOther);\n\t\tparticles_.push_back(cl);\n\t\t//cout << cl.getPosition() << \"\\n\";\n\t\t//cout << cl.getForce() << \"\\n\";\n\t}\n\n\t/*for(int i=0; i<4;i++){\n\n\t\tcout << particles_.at(i).getConTabSelf() <<  \"\\t\" << particles_.at(i).getConTabOther() << \"\\n\";\n\t}*/\n}\n\nvoid Simulation::createPairList(){\n\tint clId1, clId2;\n\tint nn, gb;\n\tublas::vector<int> wb(3,0);\n\tint filId1,filId2;\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tfor(int j=0;j<4;j++)\n\t\t{\n\t\t\tclId1=i;\n\t\t\tnn=NN(i,j);\n\t\t\tgb=GB(i,j);\n\t\t\tif(nn>clId1 && gb==0)\n\t\t\t{\n\t\t\t\tclId2=nn;\n\t\t\t\tif(j<2){\n\t\t\t\t\tfilId1=1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tfilId1=2;\n\t\t\t\t}\n\t\t\t\t// check which filament is cl1 for cl2 on\n\t\t\t\tfor(int k=0;k<4;k++)\n\t\t\t\t{\n\t\t\t\t\tif (NN(nn,k)==i && GB(nn,k)==0) //find cl1 in cl2-line of NN table\n\t\t\t\t\t{\n\t\t\t\t\t\tif(k<2){filId2=1;}\n\t\t\t\t\t\t\n\t\t\t\t\t\telse{filId2=2;}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tCrosslinkPair2 clpair=CrosslinkPair2(particles_.at(clId1), particles_.at(clId2),RR(i,j),WBX(i,j),WBY(i,j),WBZ(i,j), filId1, filId2);\n\t\t\t\tparticlePairs2_.push_back(clpair);\t\t\n\t\t\t}\n\t\t}\n\t}\n\t//WBX(1,1)=5;\n\t//RR(1,1)=7;\n\t/*for(int i=0; i<particlePairs2_.size(); i++){\n\t\tcout << particlePairs2_.at(i).getCrosslink(1)->getId() << \"\\t\" << particlePairs2_.at(i).getCrosslink(2)->getId() << \"\\t\"\n\t\t\t << particlePairs2_.at(i).getContourLength() << \"\\t\" << particlePairs2_.at(i).getWBX() << \"\\t\" << particlePairs2_.at(i).getWBY() <<\n\t\t\t \"\\t\" << particlePairs2_.at(i).getWBZ() << \"\\t\" << particlePairs2_.at(i).getFilId(1) << \"\\t\" << particlePairs2_.at(i).getFilId(2) <<  \n\t\t\t \"\\t\" << particlePairs2_.at(i).getContourLength() << \"\\n\";\n\t}*/\n}\n\nvoid Simulation::createTripleList(){\n\tint clId1, clId2, clId3;\n\tublas::vector<int> wb1(3,0),wb2(3,0);\n\tint iDummy; // index of dummy crosslink, 0=no dummy\n\tint filId1,filId2,filId3;\n\n\tfor(int i=0; i<NATOMS; i++)\n\t{\n\t\tif(GB(i,0)==0 && GB(i,1)==0){\n\t\t\tclId1=NN(i,0);\n\t\t\tclId2=i;\n\t\t\tclId3=NN(i,1);\n\n\t\t\tiDummy=0;\n\t\t}\n\t\t// if cl is the end of a polyer, then one GB=1, that crosslink becomes dummy crosslink\n\t\telse if(GB(i,0)==1 && GB(i,1)==0){\n\t\t\tclId1=i; // dummy crosslink\n\t\t\tclId2=i;\n\t\t\tclId3=NN(i,1);\n\n\t\t\tiDummy=1;\n\t\t}\n\t\telse if(GB(i,0)==0 && GB(i,1)==1){\n\t\t\tclId1=NN(i,0); \n\t\t\tclId2=i;\n\t\t\tclId3=i;// dummy crosslink\n\n\t\t\tiDummy=3;\n\t\t}\n\n\t\tfilId2=1;\n\n\t\tfilId1=-1;\n\t\tfilId3=-1;\n\n\n\t\tfor(int k=0;k<4;k++)\n\t\t{\tif(iDummy!=1)\n\t\t\t{\n\t\t\t\tif (NN(clId1,k)==i && GB(clId1,k)==0) \n\t\t\t\t{\n\t\t\t\t\tif(k<2){filId1=1;}\n\t\t\t\t\t\t\t\n\t\t\t\t\telse{filId1=2;}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(iDummy!=3)\n\t\t\t{\n\t\t\t\tif (NN(clId3,k)==i && GB(clId3,k)==0) \n\t\t\t\t{\n\t\t\t\t\tif(k<2){filId3=1;}\n\t\t\t\t\t\t\t\n\t\t\t\t\telse{filId3=2;}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tint n1a, n1b, n3a, n3b;\n\n\t\tif (iDummy==0)\n\t\t{\n\t\t\tn1a=clId1;\n\t\t\tn3a=clId3;\n\t\t\tfor(int k=0;k<4;k++)\n\t\t\t{\n\t\t\t\tif (NN(clId1,k)==i && GB(clId1,k)==0){ n1b=k;}\n\t\t\t\tif (NN(clId3,k)==i && GB(clId3,k)==0){ n3b=k;}\n\t\t\t}\n\t\t}\n\n\t\tif (iDummy==1)\n\t\t{\n\t\t\tn1a=i;\n\t\t\tn1b=0;\n\t\t\tn3a=clId3;\n\t\t\tfor(int k=0;k<4;k++)\n\t\t\t{\n\t\t\t\tif (NN(clId3,k)==i && GB(clId3,k)==0){ n3b=k;}\n\t\t\t}\n\t\t}\n\n\t\tif (iDummy==3)\n\t\t{\n\t\t\tn3a=i;\n\t\t\tn3b=1;\n\t\t\tn1a=clId1;\n\t\t\tfor(int k=0;k<4;k++)\n\t\t\t{\n\t\t\t\tif (NN(clId1,k)==i && GB(clId1,k)==0){ n1b=k;}\n\t\t\t}\n\t\t}\n\n\n\t\t//CrosslinkTriple2 cltriple=CrosslinkTriple2(particles_.at(clId1), particles_.at(clId2), particles_.at(clId3));\n\t\tCrosslinkTriple2 cltriple=CrosslinkTriple2(particles_.at(clId1), particles_.at(clId2), particles_.at(clId3), RR(i,0), RR(i,1), RR(n1a,n1b), RR(n3a,n3b),\n\t\t\t\tWBX(i,0), WBY(i,0), WBZ(i,0), WBX(i,1), WBY(i,1), WBZ(i,1),iDummy,filId1,filId2,filId3);\n\n\t\tparticleTriples2_.push_back(cltriple);\t\n\t\t\n\n\t\tif(GB(i,2)==0 && GB(i,3)==0){\n\t\t\tclId1=NN(i,2);\n\t\t\tclId2=i;\n\t\t\tclId3=NN(i,3);\n\n\t\t\tiDummy=0;\n\t\t}\n\t\t// if cl is the end of a polyer, then one GB=1, that crosslink becomes dummy crosslink\n\t\telse if(GB(i,2)==1 && GB(i,3)==0){\n\t\t\tclId1=i; // dummy crosslink\n\t\t\tclId2=i;\n\t\t\tclId3=NN(i,3);\n\n\t\t\tiDummy=1;\n\t\t}\n\t\telse if(GB(i,2)==0 && GB(i,3)==1){\n\t\t\tclId1=NN(i,2); \n\t\t\tclId2=i;\n\t\t\tclId3=i;// dummy crosslink\n\n\t\t\tiDummy=3;\n\t\t}\n\t\t\t//CrosslinkTriple2 cltriple=CrosslinkTriple2(particles_.at(clId1), particles_.at(clId2), particles_.at(clId3));\n\n\t\tfilId2=2;\n\n\t\tfilId1=-1;\n\t\tfilId3=-1;\n\n\t\tfor(int k=0;k<4;k++)\n\t\t{\tif(iDummy!=1)\n\t\t\t{\n\t\t\t\tif (NN(clId1,k)==i && GB(clId1,k)==0) \n\t\t\t\t{\n\t\t\t\t\tif(k<2){filId1=1;}\n\t\t\t\t\t\t\t\n\t\t\t\t\telse{filId1=2;}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(iDummy!=3)\n\t\t\t{\n\t\t\t\tif (NN(clId3,k)==i && GB(clId3,k)==0) \n\t\t\t\t{\n\t\t\t\t\tif(k<2){filId3=1;}\n\t\t\t\t\t\t\t\n\t\t\t\t\telse{filId3=2;}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif (iDummy==0)\n\t\t{\n\t\t\tn1a=clId1;\n\t\t\tn3a=clId3;\n\t\t\tfor(int k=0;k<4;k++)\n\t\t\t{\n\t\t\t\tif (NN(clId1,k)==i && GB(clId1,k)==0){ n1b=k;}\n\t\t\t\tif (NN(clId3,k)==i && GB(clId3,k)==0){ n3b=k;}\n\t\t\t}\n\t\t}\n\n\t\tif (iDummy==1)\n\t\t{\n\t\t\tn1a=i;\n\t\t\tn1b=2;\n\t\t\tn3a=clId3;\n\t\t\tfor(int k=0;k<4;k++)\n\t\t\t{\n\t\t\t\tif (NN(clId3,k)==i && GB(clId3,k)==0){ n3b=k;}\n\t\t\t}\n\t\t}\n\n\t\tif (iDummy==3)\n\t\t{\n\t\t\tn3a=i;\n\t\t\tn3b=3;\n\t\t\tn1a=clId1;\n\t\t\tfor(int k=0;k<4;k++)\n\t\t\t{\n\t\t\t\tif (NN(clId1,k)==i && GB(clId1,k)==0){ n1b=k;}\n\t\t\t}\n\t\t}\n\n\t\tCrosslinkTriple2 cltriple2=CrosslinkTriple2(particles_.at(clId1), particles_.at(clId2), particles_.at(clId3), RR(i,2), RR(i,3), RR(n1a,n1b), RR(n3a,n3b),\n\t\t\tWBX(i,2), WBY(i,2), WBZ(i,2), WBX(i,3), WBY(i,3), WBZ(i,3),iDummy,filId1,filId2,filId3);\n\n\t\tparticleTriples2_.push_back(cltriple2);\t\n\t}\t\n\t\n\t\n\t\n\t/*for(int i=0; i<particleTriples2_.size(); i++){\n\t\tcout << particleTriples2_.at(i).getCrosslink(1)->getId() << \"\\t\" << particleTriples2_.at(i).getCrosslink(2)->getId() \n\t\t<< \"\\t\" << particleTriples2_.at(i).getCrosslink(3)->getId()<< \"\\t\" << particleTriples2_.at(i).getContourLength(12)\n\t\t<< \"\\t\" << particleTriples2_.at(i).getContourLength(23) << \"\\t\" << particleTriples2_.at(i).getWBX(12) << \"\\t\" <<\n\t\tparticleTriples2_.at(i).getWBY(12) <<  \"\\t\" << particleTriples2_.at(i).getWBZ(12) << \"\\t\" << particleTriples2_.at(i).getWBX(23) << \"\\t\" <<\n\t\tparticleTriples2_.at(i).getWBY(23) <<  \"\\t\" << particleTriples2_.at(i).getWBZ(23) << \"\\t\" << particleTriples2_.at(i).getDummy() << \"\\t\" <<\n\t\tparticleTriples2_.at(i).getFilId(1)<<  \"\\t\" << particleTriples2_.at(i).getFilId(2)<< \"\\t\" << particleTriples2_.at(i).getFilId(3) << \n\t\t\"\\t\" << particleTriples2_.at(i).getContourLength(12) << \"\\t\" <<particleTriples2_.at(i).getContourLength(23) <<\"\\n\";\n\t}*/\n}\n\n\nvoid Simulation::shear_(){\n\tFXY=gamma0_*sin(omega_*t_);\n}\n\nvoid Simulation::correctRR_(int opt)\n{\n\tdouble randNo;\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\tfor(int j=0;j<4;j++)\n\t\t{\n\t\t\tif(GB(i,j)==1){\n\t\t\t\tif(opt==1)\n\t\t\t\t{\n\t\t\t\t\trandNo=0.001 + 0.09*((double) rand() / (RAND_MAX));\n\t\t\t\t}\n\t\t\t\telse{randNo=0;}\n\t\t\t\tRR(i,j)=randNo;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid Simulation::compareForces_()\n{\n\tublas::vector<double> Ftot(3,0);\n\tublas::vector<double> r_i, r_j;\n\tdouble Ftot_ij=0;\n\tdouble F=0;\n\tfor(int i=0;i<NATOMS;i++)\n\t{\n\t\t//Ftot += ublas::norm_2(particles_.at(i).getForce());\n\t\tFtot = particles_.at(i).getForce();\n\t\tr_i = particles_.at(i).getPosition();\n\t\tfor(int j=0;j<4;j++)\n\t\t{\n\t\t\tif(GB(i,j)==0)\n\t\t\t{\n\t\t\t\tr_j=particles_.at(NN(i,j)).getPosition();\n\t\t\t\tFtot_ij=abs(ublas::inner_prod(Ftot,r_i-r_j));\n\t\t\t\tF+=Ftot_ij;\n\t\t\t}\n\t\t}\n\t}\n\tF=F/NATOMS;\n\n\tdouble Fpull=0;\n\tint nTriples=0;\n\tfor (std::vector<CrosslinkTriple2> ::iterator triplei = particleTriples2_.begin(); triplei != particleTriples2_.end(); triplei++)\n\t{\n\t\tFpull+=abs(triplei->getfPull());\n\t\tnTriples++;\n\t}\n\tFpull=Fpull/nTriples;\n\n\tcout << F << \"\\t\" << Fpull << \"\\n\";\n}", "meta": {"hexsha": "1fb662335ae92021f067f435dea03a7e2c25c40a", "size": 44239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation.cpp", "max_stars_repo_name": "lepoisson1712/polyNetRheology", "max_stars_repo_head_hexsha": "8629c0d8997689bc3f0e0caa79b1967cf2866481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation.cpp", "max_issues_repo_name": "lepoisson1712/polyNetRheology", "max_issues_repo_head_hexsha": "8629c0d8997689bc3f0e0caa79b1967cf2866481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation.cpp", "max_forks_repo_name": "lepoisson1712/polyNetRheology", "max_forks_repo_head_hexsha": "8629c0d8997689bc3f0e0caa79b1967cf2866481", "max_forks_repo_licenses": ["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.9374295378, "max_line_length": 232, "alphanum_fraction": 0.5758041547, "num_tokens": 17110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.02297736986821033, "lm_q1q2_score": 0.01139893140909018}}
{"text": "/*\n * Copyright 2018 University of Leeds\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 <chrono>\n#include <fstream>\n#include <sstream>\n#include <jsoncpp/json/json.h>\n#include <NTL/ZZ.h>\n#include \"inner.h\"\n#include \"InnerMapTask.h\"\n\nvoid run_map_task(int numPerLine, file parametersPath, file inputPath, file resultsPath){\n\tauto start = std::chrono::high_resolution_clock::now();\n\tInnerMapTask mapTask(numPerLine, parametersPath, inputPath);\n\tNTL::ZZ result = mapTask.run();\n\tauto finish = std::chrono::high_resolution_clock::now();\n\tauto totalTaskTime = std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();\n\tJson::Value root;\n\tstd::stringstream ss;\n\tss << result;\n\troot[\"result\"] = ss.str();\n\troot[\"task_execution_time\"] = Json::UInt64(totalTaskTime);\n\troot[\"number_additions\"] = Json::UInt64(mapTask.numberAdditions);\n\troot[\"total_sum_time\"] = Json::UInt64(mapTask.totalSumTime);\n\troot[\"number_multiplications\"] = Json::UInt64(mapTask.numberMultiplications);\n\troot[\"total_product_time\"] = Json::UInt64(mapTask.totalProductTime);\n\tstd::ofstream results_ofs(resultsPath);\n\tif(results_ofs.is_open()){\n\t\tresults_ofs << root;\n\t\tresults_ofs.close();\n\t}\n}\n\nvoid run_map_task_GPU(int numPerLine, file parametersPath, file inputPath, file resultsPath){\n\tauto start = std::chrono::high_resolution_clock::now();\n\tInnerMapTask mapTask_GPU(numPerLine, parametersPath, inputPath);\n\tNTL::ZZ result = mapTask_GPU.run();\n\tauto finish = std::chrono::high_resolution_clock::now();\n\tauto totalTaskTime = std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();\n\tJson::Value root;\n\tstd::stringstream ss;\n\tss << result;\n\troot[\"result\"] = ss.str();\n\troot[\"task_execution_time\"] = Json::UInt64(totalTaskTime);\n\troot[\"number_additions\"] = Json::UInt64(mapTask_GPU.numberAdditions);\n\troot[\"total_sum_time\"] = Json::UInt64(mapTask_GPU.totalSumTime);\n\troot[\"number_multiplications\"] = Json::UInt64(mapTask_GPU.numberMultiplications);\n\troot[\"total_product_time\"] = Json::UInt64(mapTask_GPU.totalProductTime);\n\tstd::ofstream results_ofs(resultsPath);\n\tif(results_ofs.is_open()){\n\t\tresults_ofs << root;\n\t\tresults_ofs.close();\n\t}\n}\n", "meta": {"hexsha": "744c5e78adb3cd4f009aa1dea10296c26d982f5c", "size": 2741, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/inner_product/inner/inner-functions.cc", "max_stars_repo_name": "TANGO-Project/cryptango", "max_stars_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/inner_product/inner/inner-functions.cc", "max_issues_repo_name": "TANGO-Project/cryptango", "max_issues_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_issues_repo_licenses": ["Apache-2.0"], "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/inner_product/inner/inner-functions.cc", "max_forks_repo_name": "TANGO-Project/cryptango", "max_forks_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "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.1571428571, "max_line_length": 97, "alphanum_fraction": 0.7508208683, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.02333076893580967, "lm_q1q2_score": 0.011392027070839734}}
{"text": "// Copyright (C) 2017 roki\n#ifndef INCLUDED_JPEZY_DECODER_HPP\n#define INCLUDED_JPEZY_DECODER_HPP\n\n#include <array>\n#include <cassert>\n#include <iostream>\n#include <srook/string/string_view.hpp>\n#include <type_traits>\n#include <vector>\n\n#include <boost/range/algorithm/copy.hpp>\n#include <boost/range/algorithm/generate.hpp>\n\n#include <srook/algorithm/for_each.hpp>\n#include <srook/config/attribute/fallthrough.hpp>\n#include <srook/config/feature/if_constexpr.hpp>\n#include <srook/config/feature/deduced_typename.hpp>\n#include <srook/config/feature/decltype.hpp>\n#include <srook/io/bifstream.hpp>\n#include <srook/iterator/ostream_joiner.hpp>\n#include <srook/iterator/range_access.hpp>\n#include <srook/math/constants/algorithm/cos.hpp>\n#include <srook/math/constants/algorithm/sqrt.hpp>\n#include <srook/mpl/constant_sequence/math/make_costable.hpp>\n#include <srook/optional.hpp>\n#include <srook/type_traits/is_arithmetic.hpp>\n#include <srook/type_traits/remove_reference.hpp>\n#include <srook/type_traits/is_same.hpp>\n\n#include \"../jpezy.hpp\"\n#include \"tables.hpp\"\n\nnamespace jpezy {\n\ntemplate <class>\nstruct decoder;\n\ntemplate <class BuildMode = Release>\nstruct decoder {\n    explicit decoder(const char *filename)\n\t: pr{\n\t      jpezy::make_property(\n\t\t  (\n\t\t      label::_width = 0,\n\t\t      label::_height = 0,\n\t\t      label::_dimension = 0,\n\t\t      label::_sample_precision = 0,\n\t\t      label::_comment = \"\",\n\t\t      label::_format = property::Format::undefined,\n\t\t      label::_major_rev = srook::byte(0),\n\t\t      label::_minor_rev = srook::byte(0),\n\t\t      label::_units = property::Units::undefined,\n\t\t      label::_width_density = 1,\n\t\t      label::_height_density = 1,\n\t\t      label::_width_thumbnail = 0,\n\t\t      label::_height_thumbnail = 0,\n\t\t      label::_extension_code = property::ExtensionCodes::undefined,\n\t\t      label::_decodable = property::AnalyzedResult::Yet))},\n\t  restart_interval{0},\n\t  rgb{},\n\t  comp{},\n\t  pred_dct{},\n\t  dct{},\n\t  block{},\n\t  ht{},\n\t  qt{},\n\t  bifs{filename},\n\t  hmax{},\n\t  vmax{},\n\t  enable{false}\n    {}\n    \n    static SROOK_CONSTEXPR bool is_release_mode = srook::is_same<Release, BuildMode>();\n\n    template <class MODE_TAG = COLOR_MODE>\n    srook::optional<srook::array<std::vector<srook::byte>, 3>, srook::optionally::safe_optional_payload> decode()\n    {\n        raii_messenger mes(\"process started...\");\n        std::cout << '\\n';\n\n        try {\n            analyze_header();\n\t    } catch (const std::runtime_error &er) {\n\t        return {};\n\t    }\n\n        disp_info(\"\\t\");\n        if (!(pr.get<property::At::Decodable>() & (property::AnalyzedResult::is_htable | property::AnalyzedResult::is_qtable | property::AnalyzedResult::is_start_data))) return {};\n        std::unique_ptr<raii_messenger> mes_dec;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>())\n            mes_dec = std::make_unique<raii_messenger>(\"decoding started...\", \"\\t\");\n\n        const std::size_t Vblock = get_blocks(pr.get<property::At::VSize>());\n        const std::size_t Hblock = get_blocks(pr.get<property::At::HSize>());\n\n        const std::size_t h_unit = (Hblock / hmax) + ((Hblock % hmax) ? 1 : 0);\n        const std::size_t v_unit = (Vblock / vmax) + ((Vblock % vmax) ? 1 : 0);\n        const std::size_t rgb_s = (v_unit * vmax) * block_size * (h_unit * hmax) * block_size;\n\n        for (auto &&v : rgb) v.resize(rgb_s);\n\n        const std::size_t unit_size = hmax * vmax * blocks_size;\n\t    comp[0].resize(unit_size);\n        for (std::size_t i = 1; i < 3; ++i) comp[i].resize(unit_size, 0x80);\n\n        for (std::size_t uy = 0, restart_counter = 0; uy < v_unit; ++uy) {\n            for (std::size_t ux = 0; ux < h_unit; ++ux) {\n                try {\n                    decode_mcu();\n                } catch (const std::runtime_error &er) {\n                    std::cerr << \"decode_mcu(): throw exception from \" << er.what() << std::endl;\n                    return {};\n                }\n                try {\n                    make_rgb<MODE_TAG>(ux, uy);\n                } catch (const std::runtime_error &er) {\n                    std::cerr << \"make_rgb(): throw exception from \" << er.what() << std::endl;\n                    return {};\n                }\n\t\t   \n                try {\n                    restart_interval_check(restart_counter);\n                } catch (const std::runtime_error &er) {\n                    std::cerr << \"restart_interval_check(): throw exception from \" << er.what() << std::endl;\n                } catch (const std::out_of_range &er) {\n                    std::cerr << \"restart_interval_check(): throw exception from \" << er.what() << std::endl;\n                }\n            }\n        }\n        for (auto &&v : comp) v.clear();\n        \n        return { rgb };\n    }\n    \n    property pr;\n\nprivate:\n    inline void disp_info(const char *indent = \"\")\n    {\n        std::cout << indent << \"Loaded JPEG: \";\n        std::cout << pr.get<jpezy::property::At::HSize>() << \"x\" << pr.get<jpezy::property::At::VSize>() << \", \";\n        std::cout << \"presicion \" << pr.get<jpezy::property::At::SamplePrecision>() << \", \";\n        std::cout << \"\\\"\" << pr.get<jpezy::property::At::Comment>() << \"\\\"\" << \", \";\n        std::cout << ((pr.get<jpezy::property::At::Format>() == jpezy::property::Format::JFIF) ? \"JFIF\" : (pr.get<jpezy::property::At::Format>() == jpezy::property::Format::JFXX) ? \"JFXX\" : \"undefined\") << \" standart \";\n        std::cout << srook::to_integer<unsigned int>(pr.get<jpezy::property::At::MajorRevisions>()) << \".0\" << srook::to_integer<unsigned int>(pr.get<jpezy::property::At::MinorRevisions>()) << \", \";\n        std::cout << ((pr.get<jpezy::property::At::Units>() == jpezy::property::Units::dots_inch) ? \"dots inch\" : (pr.get<jpezy::property::At::Units>() == jpezy::property::Units::dots_cm) ? \"dots cm\" : \"undefined\") << \", \";\n        std::cout << \"frames \" << pr.get<jpezy::property::At::Dimension>() << \", \";\n        std::cout << \"density \" << pr.get<jpezy::property::At::HDensity>() << \"x\" << pr.get<jpezy::property::At::VDensity>() << \"\\n\" << std::endl;\n    }\n\n    void restart_interval_check(std::size_t &restart_counter)\n\tSROOK_NOEXCEPT(get_marker())\n    {\n        if (restart_interval) {\n            if (++restart_counter >= restart_interval) {\n                restart_counter = 0;\n                const MARKER mark = get_marker();\n                if (mark >= MARKER::RST0 && mark <= MARKER::RST7)\n                    pred_dct[0] = pred_dct[1] = pred_dct[2] = 0;\n            }\n        }\n    }\n\n    template <class T, SROOK_REQUIRES(srook::is_arithmetic<T>::value)>\n    static SROOK_CONSTEXPR T get_blocks(T x) SROOK_NOEXCEPT_TRUE\n    {\n        return (x >> 3) + ((x & 0x07) > 0);\n    }\n\n    void analyze_header()\n    {\n        std::unique_ptr<raii_messenger> mes;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>())\n            mes = std::make_unique<raii_messenger>(\"analyzing header...\", \"\\t\");\n\t\n        do {\n            if (get_marker() == MARKER::SOI)\n                enable = true;\n        } while (!enable);\n\t\n        while (enable) {\n            pr.get<property::At::Decodable>() |= analyze_marker();\n            if (pr.get<property::At::Decodable>() & property::AnalyzedResult::is_start_data)\n                return;\n        }\n        throw std::runtime_error(__func__);\n    }\n\n    void analyze_dht(std::size_t size)\n    {\n        std::unique_ptr<raii_messenger> mes;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) mes = std::make_unique<raii_messenger>(\"analyzing DHT...\", \"\\t\\t\\t\");\n        \n        const srook::byte *end_add = bifs.next_address();\n        if (!end_add) throw std::out_of_range(__func__);\n        end_add += size;\n        \n        do {\n            std::underlying_type_t<srook::byte> uc{};\n            (bifs | srook::io::jpeg::bifstream::Byte) >> uc;\n            const std::size_t tc = uc >> 4, th = uc & 0x0f;\n\t    \n            if (tc > 1) throw std::runtime_error(\"DC format error\");\n            if (th > 3) throw std::runtime_error(\"AC format error\");\n\t    \n            huffman_table &ht_ = ht[tc][th];\n            srook::array<std::underlying_type_t<srook::byte>, block_size * 2> cc{};\n            std::size_t n_ = 0;\n            \n            boost::generate(cc, [this, &n_]() {std::underlying_type_t<srook::byte> b{}; (bifs | srook::io::jpeg::bifstream::Byte) >> b; n_ += b; return b; });\n            SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>())\n                std::cout << \" size: \" << n_ << std::endl;\n            const std::size_t &n = n_;\n\n            ht_.sizeTP.clear();\n            ht_.codeTP.clear();\n            ht_.valueTP.clear();\n            ht_.sizeTP.resize(n);\n            ht_.codeTP.resize(n);\n            ht_.valueTP.resize(n);\n\t    \n            for (std::size_t i = 1, k = 0; i <= (block_size * 2); ++i) {\n                for (std::size_t j = 1; j <= cc[i - 1]; ++j, ++k) {\n                    if (k >= n) throw std::out_of_range(\"invalid size table\");\n                    ht_.sizeTP[k] = i;\n                }\n            }\n\t   \n            for (auto[k, code, si] = std::make_tuple(0u, 0, ht_.sizeTP[0]);;) {\n                for (; ht_.sizeTP[k] == si; ++k, ++code)\n                    ht_.codeTP[k] = code;\n            \n                if (k >= n) break;\n                do {\n                    code <<= 1;\n                    ++si;\n                } while (ht_.sizeTP[k] != si);\n            }\n            for (std::size_t k = 0; k < n; ++k) (bifs | srook::io::jpeg::bifstream::Byte) >> ht_.valueTP[k];\n\t   \n            SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) {\n                switch (n) {\n                    case 12:\n                        std::cout << \"found DC Huffman Table... \";\n                        break;\n                    case 162:\n                        std::cout << \"found AC Huffman Table... \";\n\t\t\t            break;\n                    default:\n                        std::cerr << n_ << std::endl;\n                        throw std::out_of_range(\"invalid size table\");\n                }\n            }\n        } while (bifs.next_address() < end_add);\n    }\n\n    void analyze_dqt(std::size_t size)\n    {\n        std::unique_ptr<raii_messenger> mes;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) mes = std::make_unique<raii_messenger>(\"\\t\\t\\tanalyzing DQT...\");\n        const srook::byte *const end_add = bifs.next_address() + size;\n        std::underlying_type_t<srook::byte> c{};\n\t\n        do {\n            (bifs | srook::io::jpeg::bifstream::Byte) >> c;\n            if (SROOK_DEDUCED_TYPENAME SROOK_DECLTYPE(qt)::value_type::iterator iter = srook::begin(qt[c & 0x3]); !(c >> 4)) {\n                std::underlying_type_t<srook::byte> t{};\n                for (std::size_t i = 0; i < blocks_size; ++i) {\n                    (bifs | srook::io::jpeg::bifstream::Byte) >> t;\n                    iter[ZZ[i]] = int(t);\n                }\n            } else {\n                for (std::size_t i = 0; i < blocks_size; ++i) (bifs | srook::io::jpeg::bifstream::Word) >> iter[ZZ[i]];\n            }\n        } while (bifs.next_address() < end_add);\n    }\n\n    void analyze_frame()\n    {\n        std::unique_ptr<raii_messenger> mes;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) mes = std::make_unique<raii_messenger>(\"\\t\\t\\tanalyzing frames...\");\n\n        using namespace srook::literals::byte_literals;\n\t\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::SamplePrecision>();\n        (bifs | srook::io::jpeg::bifstream::Word) >> pr.get<property::At::VSize>();\n        (bifs | srook::io::jpeg::bifstream::Word) >> pr.get<property::At::HSize>();\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::Dimension>();\n        if (pr.get<property::At::Dimension>() != 3 && pr.get<property::At::Dimension>() != 1) throw std::runtime_error(\"Sorry, this dimension size is not supported\");\n\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"VSize: \" << pr.get<property::At::VSize>() << \" HSize: \" << pr.get<property::At::HSize>() << \" \";\n\t\n        for (auto [i, c] = std::make_tuple(0u, 0_byte); i < std::size_t(pr.get<property::At::Dimension>()); ++i) {\n            (bifs | srook::io::jpeg::bifstream::Byte) >> fcomp[i].C;\n            (bifs | srook::io::jpeg::bifstream::Byte) >> c;\n\t    \n            fcomp[i].H = SROOK_DEDUCED_TYPENAME get_character<srook::byte>::type(c >> 4);\n\t    \n            if (fcomp[i].H > hmax) hmax = fcomp[i].H;\n            fcomp[i].V = (std::underlying_type_t<srook::byte>(c) & 0xf);\n            if (fcomp[i].V > vmax) vmax = fcomp[i].V;\n            (bifs | srook::io::jpeg::bifstream::Byte) >> fcomp[i].Tq;\n        }\n    }\n\n    void analyze_scan()\n    {\n        std::unique_ptr<raii_messenger> mes;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) mes = std::make_unique<raii_messenger>(\"\\t\\t\\tanalyzing scan data...\");\n\t\n        srook::byte c{};\n        (bifs | srook::io::jpeg::bifstream::Byte) >> s_header.scan_comp;\n        for (std::size_t i = 0; i < srook::to_integer<std::size_t>(s_header.scan_comp); ++i) {\n            (bifs | srook::io::jpeg::bifstream::Byte) >> scomp[i].Cs;\n            (bifs | srook::io::jpeg::bifstream::Byte) >> c;\n\t    \n            scomp[i].Td = srook::to_integer<std::underlying_type_t<srook::byte>>(c >> 4);\n            if (scomp[i].Td > 2) throw std::out_of_range(__func__);\n\t    \n            scomp[i].Ta = (srook::to_integer<std::underlying_type_t<srook::byte>>(c) & 0xf);\n            if (scomp[i].Ta > 2) throw std::out_of_range(__func__);\n\t\n        }\n\n        // unused for DCT\n        {\n            (bifs | srook::io::jpeg::bifstream::Byte) >> s_header.spectral_begin;\n            (bifs | srook::io::jpeg::bifstream::Byte) >> s_header.spectral_end;\n            (bifs | srook::io::jpeg::bifstream::Byte) >> c;\n            s_header.Ah = srook::to_integer<SROOK_DEDUCED_TYPENAME get_character<srook::byte>::type>(c >> 4);\n            s_header.Al = srook::to_integer<std::underlying_type_t<srook::byte>>(c) & 0xf;\n        }\n    }\n\n    void analyze_jfif()\n    {\n        std::unique_ptr<raii_messenger> mes;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) mes = std::make_unique<raii_messenger>(\"\\t\\t\\tanalyzing jfif...\");\n\t\n        pr.get<property::At::Format>() = property::Format::JFIF;\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::MajorRevisions>();\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::MinorRevisions>();\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::Units>();\n        (bifs | srook::io::jpeg::bifstream::Word) >> pr.get<property::At::HDensity>();\n        (bifs | srook::io::jpeg::bifstream::Word) >> pr.get<property::At::VDensity>();\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::HThumbnail>();\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::VThumbnail>();\n        pr.get<property::At::Decodable>() |= property::AnalyzedResult::is_jfif;\n    }\n\n    void analyze_jfxx()\n    {\n        std::unique_ptr<raii_messenger> mes;\n        SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) mes = std::make_unique<raii_messenger>(\"\\t\\t\\tanalyzing jfxx...\");\n        pr.get<property::At::Format>() = property::Format::JFXX;\n        (bifs | srook::io::jpeg::bifstream::Byte) >> pr.get<property::At::ExtensionCode>();\n    }\n\n    int analyze_marker()\n    {\n        int length{};\n        MARKER mark = get_marker();\n        const auto param_offset = [](int &len_) { len_ -= 2; };\n\t\n        switch (mark) {\n\t    \n            case MARKER::SOF0:\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [SOF0]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                analyze_frame();\n                break;\n            case MARKER::DHT:\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [DHT]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                param_offset(length);\n                analyze_dht(length);\n                return property::AnalyzedResult::is_htable;\n            case MARKER::DNL:\n\t\t\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [DNL]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                (bifs | srook::io::jpeg::bifstream::Word) >> pr.get<property::At::VSize>();\n                break;\n            case MARKER::DQT:\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [DQT]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                param_offset(length);\n                analyze_dqt(length);\n                return property::AnalyzedResult::is_qtable;\n            case MARKER::EOI:\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [EOI]\" << std::endl;\n                enable = false;\n                break;\n            case MARKER::SOS:\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [SOS]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                analyze_scan();\n                return property::AnalyzedResult::is_start_data;\n            case MARKER::DRI:\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [DRI]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                (bifs | srook::io::jpeg::bifstream::Word) >> restart_interval;\n                break;\n            case MARKER::COM:\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\t\\tfound marker: [COM]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                param_offset(length);\n                (bifs | srook::io::jpeg::bifstream::Byte_n(length)) >> pr.get<property::At::Comment>();\n                return property::AnalyzedResult::is_comment;\n            // Not supported frames\n            case MARKER::SOF1: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::SOF2: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::SOF3: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::SOF5: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::SOF6: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::SOF7: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::SOF9: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::SOF10: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::SOF11: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::SOF13: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::SOF14: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::SOF15: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::EXP: SROOK_ATTRIBUTE_FALLTHROUGH;      case MARKER::DAC: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::DHP:\n                std::runtime_error(\"Not supported\");\n                break;\n            case MARKER::APP0: {\n                SROOK_IF_CONSTEXPR (srook::is_same<BuildMode, Debug>()) std::cout << \"\\n\\t\\tfound marker: [APP0]\" << std::endl;\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                param_offset(length);\n\t\t\n                if (static SROOK_CONSTEXPR char JFIF[] = \"JFIF\", JFXX[] = \"JFXX\"; srook::string_view(JFIF).size() == srook::string_view(JFXX).size()) {\n                    if (const std::size_t size = srook::string_view(JFIF).size(); length >= signed(size)) {\n                        std::string id;\n                        id.resize(size + 1);\n                        (bifs | srook::io::jpeg::bifstream::Bytes) >> id;\n                        id.pop_back();\n\t\t\t\n                        if (id == JFIF) {\n                            analyze_jfif();\n                            bifs.skip_byte(length - 14);\n                        } else if (JFXX == id) {\n                            analyze_jfxx();\n                            bifs.skip_byte(length - 1);\n                        } else {\n                            bifs.skip_byte(length - size);\n                        }\n                    } else {\n                        bifs.skip_byte(length);\n                    }\n                }\n                break;\n            }\n\n            // Not supported markers\n            case MARKER::APP1: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::APP2: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::APP3: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::APP4: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::APP5: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::APP6: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::APP7: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::APP8: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::APP9: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::APP10: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::APP11: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::APP12: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::APP13: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::APP14: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::APP15:\n                (bifs | srook::io::jpeg::bifstream::Word) >> length;\n                param_offset(length);\n                bifs.skip_byte(length);\n                break;\n\n\t        // reserves and other\n            case MARKER::JPG: SROOK_ATTRIBUTE_FALLTHROUGH;      case MARKER::JPG0: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::JPG1: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::JPG2: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::JPG3: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::JPG4: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::JPG5: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::JPG6: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::JPG7: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::JPG8: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::JPG9: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::JPG10: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::JPG11: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::JPG12: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::JPG13: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::TEM: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::Error: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::RST0: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::RST1: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::RST2: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::RST3: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::RST4: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::RST5: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::RST6: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::RST7: SROOK_ATTRIBUTE_FALLTHROUGH;     case MARKER::SOI: SROOK_ATTRIBUTE_FALLTHROUGH;\n            case MARKER::RESst: SROOK_ATTRIBUTE_FALLTHROUGH;    case MARKER::RESnd: SROOK_ATTRIBUTE_FALLTHROUGH;\n\t    \n            default:\n                throw std::runtime_error(\"Marker error\");\n        }\n        return property::AnalyzedResult::Yet;\n    }\n\n    MARKER get_marker()\n    {\n        for (std::underlying_type_t<srook::byte> c{};;) {\n            (bifs | srook::io::jpeg::bifstream::Byte) >> c;\n            if (c == std::underlying_type_t<srook::byte>(MARKER::Marker)) {\n                (bifs | srook::io::jpeg::bifstream::Byte) >> c;\n                if (c) {\n                    if ((c > std::underlying_type_t<srook::byte>(MARKER::RESst)) && (c < std::underlying_type_t<srook::byte>(MARKER::SOF0))) {\n                        return MARKER::Error;\n                    } else {\n                        return MARKER(c);\n                    }\n                }\n            }\n        }\n        return MARKER::Error;\n    }\n\n    void decode_mcu()\n    {\n        for (std::size_t sc = 0; sc < std::size_t(pr.get<property::At::Dimension>()); ++sc) {\n            const std::size_t num_v = fcomp[sc].V;\n            const std::size_t num_h = fcomp[sc].H;\n            const std::size_t dupc_y = vmax / num_v;\n            const std::size_t dupc_x = hmax / num_h;\n            const std::size_t v_step = hmax * block_size;\n\t    \n            for (std::size_t ky = 0; ky < num_v; ++ky) {\n                for (std::size_t kx = 0; kx < num_h; ++kx) {\n                    decode_huffman(sc);\n                    inverse_quantization(sc);\n                    inverse_dct();\n\n                    SROOK_DEDUCED_TYPENAME srook::remove_reference_t<SROOK_DECLTYPE(comp)>::value_type::iterator tp = std::next(srook::begin(comp[sc]), ky * v_step * block_size + kx * block_size);\n                    for (std::size_t y_u = 0; y_u < block_size * dupc_y; ++y_u) {\n                        for (std::size_t x_u = 0; x_u < block_size * dupc_x; ++x_u) {\n                            tp[y_u * v_step + x_u] = block[(y_u / dupc_y) * block_size + (x_u / dupc_x)];\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n\n    template <class MODE_TAG>\n    void make_rgb(const std::size_t ux, const std::size_t uy) noexcept\n    {\n        SROOK_DEDUCED_TYPENAME srook::remove_reference_t<SROOK_DECLTYPE(comp)>::value_type::iterator yp = srook::begin(comp[0]), up = srook::begin(comp[1]), vp = srook::begin(comp[2]);\n        const std::size_t line = uy * vmax * block_size;\n        const std::size_t offset_v = line * pr.get<property::At::HSize>();\n        const std::size_t offset_h = ux * hmax * block_size;\n        const std::size_t offset = offset_v + offset_h;\n\t\n        std::vector<srook::byte>::iterator rp = std::next(srook::begin(rgb[0]), offset), gp = std::next(srook::begin(rgb[1]), offset), bp = std::next(srook::begin(rgb[2]), offset);\n        const std::size_t end_x = (hmax * block_size);\n        const std::size_t end_y = (vmax * block_size);\n\t\n        for (std::size_t pic_y = 0; pic_y < end_y; ++pic_y) {\n            for (std::size_t pic_x = 0; pic_x < end_x; ++pic_x) {\n                if (pic_x + offset_h >= pr.get<property::At::HSize>()) {\n                    yp += end_x - pic_x;\n                    up += end_x - pic_x;\n                    vp += end_x - pic_x;\n                    break;\n                }\n\n                SROOK_IF_CONSTEXPR (const std::size_t index = pic_y * pr.get<property::At::HSize>() + pic_x; srook::is_same<MODE_TAG, COLOR_MODE>()) {\n                    rp[index] = revise_value(to_r(*yp, *vp));\n                    gp[index] = revise_value(to_g(*yp, *up, *vp));\n                    bp[index] = revise_value(to_b(*yp, *up));\n                    ++yp;\n                    ++vp;\n                    ++up;\n                } else {\n                    gp[index] = bp[index] = rp[index] = revise_value(*yp++);\n                }\n            }\n        }\n    }\n\n    SROOK_CONSTEXPR double to_r(const double yp, const double vp) const noexcept\n    {\n        return yp + (vp - 0x80) * 1.4020;\n    }\n    SROOK_CONSTEXPR double to_g(const double yp, const double up, const double vp) const noexcept\n    {\n        return yp - (up - 0x80) * 0.3441 - (vp - 0x80) * 0.7139;\n    }\n    SROOK_CONSTEXPR double to_b(const double yp, const double up) const noexcept\n    {\n        return yp + (up - 0x80) * 1.7718;\n    }\n\n    struct DC;\n    struct AC;\n\n    void decode_huffman(std::size_t sc)\n    {\n        // DC\n        int dc_diff = 0;\n        int category = decode_huffman_impl<DC>(sc);\n        if (category > 0) {\n            (bifs | srook::io::jpeg::bifstream::Bits(category)) >> dc_diff;\n            if ((dc_diff & (1 << (category - 1))) == 0) {\n                dc_diff -= (1 << category) - 1;\n            }\n        } else if (category < 0) {\n            throw std::runtime_error(__func__);\n        }\n        pred_dct[sc] += dc_diff;\n        dct[0] = pred_dct[sc];\n\t\n        // AC\n        for (std::size_t k = 1; k < blocks_size;) {\n            category = decode_huffman_impl<AC>(sc);\n            if (!category) {\n                for (; k < blocks_size; ++k) dct[ZZ[k]] = 0;\n                break;\n            } else if (category < 0) {\n                throw std::runtime_error(__func__);\n            }\n\n            int run = category >> 4, acv = 0;\n            category &= 0x0f;\n            if (category) {\n                (bifs | srook::io::jpeg::bifstream::Bits(category)) >> acv;\n                if (!(acv & (1 << (category - 1)))) {\n                    acv -= (1 << category) - 1;\n                }\n            } else if (run != 15) {\n                std::runtime_error(__func__);\n            }\n            if ((run + k) > int(blocks_size - 1)) throw std::runtime_error(__func__);\n\t    \n            for (; run-- > 0; ++k) dct[ZZ[k]] = 0;\n            dct[ZZ[k++]] = acv;\n        }\n    }\n\n    template <class TC>\n    int decode_huffman_impl(std::size_t sc)\n    {\n        SROOK_ST_ASSERT(srook::is_same<TC, DC>() or srook::is_same<TC, AC>());\n        huffman_table &ht_ = ht[srook::is_same<TC, AC>()][scomp[sc].Td];\n        for (auto[code, length, next, k] = std::make_tuple(0, 0u, 0, 0u); k < ht_.size() && length < (block_size * 2);) {\n            ++length;\n            code <<= 1;\n            (bifs | srook::io::jpeg::bifstream::Bits(1)) >> next;\n            if (next < 0) return next;\n            code |= next;\n            for (; ht_.sizeTP[k] == length; ++k) {\n                if (ht_.codeTP[k] == code) return ht_.valueTP[k];\n            }\n        }\n        throw std::runtime_error(__func__);\n    }\n\n\n    void inverse_quantization(std::size_t sc) noexcept\n    {\n        SROOK_DEDUCED_TYPENAME srook::remove_reference_t<SROOK_DECLTYPE(dct)>::iterator p = srook::begin(dct);\n        SROOK_DEDUCED_TYPENAME srook::remove_reference_t<SROOK_DECLTYPE(qt)>::value_type::const_iterator iter = srook::begin(qt[fcomp[sc].Tq]);\n        for (std::size_t i = 0; i < blocks_size; ++i) *p++ *= *iter++;\n    }\n\n    void inverse_dct() noexcept\n    {\n        const int sl = pr.get<property::At::SamplePrecision>() == block_size ? 128 : 2048;\n        SROOK_CONSTEXPR double disqrt2 = (1.0 / srook::sqrt(2));\n\t\n        for (std::size_t y = 0; y < block_size; ++y) {\n            for (std::size_t x = 0; x < block_size; ++x) {\n                double sum = 0;\n                for (std::size_t v = 0; v < block_size; ++v) {\n                    const double cv = (!v) ? disqrt2 : 1.0;\n                    for (std::size_t u = 0; u < block_size; ++u) {\n                        const double cu = (!u) ? disqrt2 : 1.0;\n                        sum += cu * cv * dct[v * block_size + u] * cos_table[u * block_size + x] * cos_table[v * block_size + y];\n                    }\n                }\n                block[y * block_size + x] = int(sum / 4 + sl);\n            }\n        }\n    }\n\n    SROOK_CONSTEXPR srook::byte revise_value(double v) const noexcept\n    {\n        using namespace srook::literals::byte_literals;\n        return (v < 0.0) ? 0_byte : (v > 255.0) ? 255_byte : srook::byte(v);\n    }\n\npublic:\n    static SROOK_CONSTEXPR std::size_t rgb_size = 3;\n    static SROOK_CONSTEXPR std::size_t block_size = 8;\n    static SROOK_CONSTEXPR std::size_t blocks_size = block_size * block_size;\n    static SROOK_CONSTEXPR std::size_t mcu_size = 4;\n\nprivate:\n    Scan_header s_header;\n    srook::array<Frame_component, 3> fcomp;\n    srook::array<Scan_component, 3> scomp;\n\n    std::size_t restart_interval;\n    srook::array<std::vector<srook::byte>, rgb_size> rgb;\n    srook::array<std::vector<int>, rgb_size> comp;\n    srook::array<int, rgb_size> pred_dct;\n    srook::array<int, blocks_size> dct;\n    srook::array<int, blocks_size> block;\n\n    srook::array<srook::array<huffman_table, 4>, 2> ht;\n    srook::array<srook::array<int, blocks_size>, mcu_size> qt;\n    static SROOK_CONSTEXPR srook::array<const double, block_size * block_size> cos_table = srook::constant_sequence::math::unwrap_costable::array<srook::constant_sequence::math::make_costable_t<8,8>>::value;\n\n    srook::io::jpeg::bifstream bifs;\n    std::make_signed_t<std::underlying_type_t<srook::byte>> hmax, vmax;\n    bool enable;\n};\n\n} // namespace jpezy\n#endif\n", "meta": {"hexsha": "8085c94f82ac0b9bc076db9717275e2b9d1a77f8", "size": 32076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/decoder/jpezy_decoder.hpp", "max_stars_repo_name": "falgon/jpezy", "max_stars_repo_head_hexsha": "d6d05cad9c0b69e30800f82fac87d080c682d3b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-15T14:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T07:12:40.000Z", "max_issues_repo_path": "src/decoder/jpezy_decoder.hpp", "max_issues_repo_name": "falgon/jpezy", "max_issues_repo_head_hexsha": "d6d05cad9c0b69e30800f82fac87d080c682d3b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/decoder/jpezy_decoder.hpp", "max_forks_repo_name": "falgon/jpezy", "max_forks_repo_head_hexsha": "d6d05cad9c0b69e30800f82fac87d080c682d3b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-07-02T06:46:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-02T06:46:41.000Z", "avg_line_length": 45.369165488, "max_line_length": 223, "alphanum_fraction": 0.5499438833, "num_tokens": 9058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.02931223244728875, "lm_q1q2_score": 0.011391261932008508}}
{"text": "/*\n *   This file is part of SRS project.\n *\n *   SRS 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 *   SRS 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 SRS. If not, see <http://www.gnu.org/licenses/>.\n *\n *   Created by: Yifang Sun, Jianbin Qin\n *   Last modified by: Yifang Sun, Jianbin Qin\n */\n\n#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <getopt.h>\n#include <cstdlib>\n#include <dirent.h>\n#include <vector>\n#include <time.h>\n#include <sys/time.h>\n#include <boost/math/distributions/chi_squared.hpp>\n#include \"SRSInMemory.h\"\n\n#define no_argument 0\n#define required_argument 1\n#define optional_argument 2\n\nvoid usage();\nbool file_exists(const char *);\nbool dir_exists(const char *foldername);\ndouble cal_thres(double c, double p_thres, int m);\n\ntemplate<class T>\nvoid query_workload(SRS_In_Memory<T> * searcher, int k, int t, double thres,\n                    char *query_file_path, char *ground_truth_file_path,\n                    char *output_file_path);\n\nfloat diff_timeval(timeval t1, timeval t2) {\n  return (float) (t1.tv_sec - t2.tv_sec) + (t1.tv_usec - t2.tv_usec) * 1e-6;\n}\n\nint main(int argc, char * argv[]) {\n  const struct option longopts[] ={\n    {\"help\",                        no_argument,       0, 'h'},\n    {\"page-size\",                   required_argument, 0, 'b'},\n    {\"approximation-ratio\",         required_argument, 0, 'c'},\n    {\"dimension\",                   required_argument, 0, 'd'},\n    {\"seed\",                        required_argument, 0, 'e'},\n    {\"ground-truth-file-path\",      required_argument, 0, 'g'},\n    {\"index-dir-path\",              required_argument, 0, 'i'},\n    {\"is-index\",                    no_argument,       0, 'I'},\n    {\"k\",                           required_argument, 0, 'k'},\n    {\"m\",                           required_argument, 0, 'm'},\n    {\"cardinality\",                 required_argument, 0, 'n'},\n    {\"output-file-path\",            required_argument, 0, 'o'},\n    {\"query-file-path\",             required_argument, 0, 'q'},\n    {\"is-query\",                    no_argument,       0, 'Q'},\n    {\"threshold\",                   required_argument, 0, 'r'},\n    {\"dataset-file-path\",           required_argument, 0, 's'},\n    {\"max-number-of-points\",        required_argument, 0, 't'},\n    {\"data-type\",                   required_argument, 0, 'y'},\n    {0, 0, 0, 0},\n  };\n\n  srand(1000);\n  int index;\n  int iarg = 0;\n  opterr = 1;    //getopt error message (off: 0)\n\n  int d = -1;\n  long long n = -1;\n  int k = -1;\n  int b = -1;\n  int m = -1;\n  int t = -1;\n\n  double c = -1.0;\n  double p_thres = -1.0;\n\n  char ground_truth_file_path[100] = \"\";\n  char query_file_path[100] = \"\";\n  char data_file_path[100] = \"\";\n  char output_file_path[100] = \"\";  //output file, currently not used.\n  char index_dir_path[100] = \"\";\n  char data_type[100] = \"\";\n\n  bool is_valid_command = true;\n  bool is_index = false;\n  bool is_query = false;\n  bool is_integer = true;\n\n  while (iarg != -1) {\n    iarg = getopt_long(argc, argv, \"b:c:d:e:g:i:k:m:n:o:q:r:s:t:y:hIQ\",\n                       longopts, &index);\n\n    switch (iarg) {\n      case 'b':\n        if (optarg) {\n          b = atoi(optarg);\n        }\n        break;\n      case 'c':\n        if (optarg) {\n          c = atof(optarg);\n        }\n        break;\n      case 'd':\n        if (optarg) {\n          d = atoi(optarg);\n        }\n        break;\n      case 'e':\n        if (optarg) {\n          srand (atoi(optarg));}\n          break;\n          case 'g':\n          if (optarg) {\n            strcpy(ground_truth_file_path, optarg);\n          }\n          break;\n          case 'h':\n          usage();\n          return 0;\n          case 'i':\n          if (optarg) {\n            strcpy(index_dir_path, optarg);\n          }\n          break;\n          case 'I':\n          is_index = true;\n          break;\n          case 'k':\n          if (optarg) {\n            k = atoi(optarg);\n          }\n          break;\n          case 'm':\n          if (optarg) {\n            m = atoi(optarg);\n          }\n          break;\n          case 'n':\n          if (optarg) {\n            n = atoi(optarg);\n          }\n          break;\n          case 'o':\n          if (optarg) {\n            strcpy(output_file_path, optarg);\n          }\n          break;\n          case 'q':\n          if (optarg) {\n            strcpy(query_file_path, optarg);\n          }\n          break;\n          case 'Q':\n          is_query = true;\n          break;\n          case 'r':\n          if (optarg) {\n            p_thres = atof(optarg);\n          }\n          break;\n          case 's':\n          if (optarg) {\n            strcpy(data_file_path, optarg);\n          }\n          break;\n          case 't':\n          if (optarg) {\n            t = atoi(optarg);\n          }\n          break;\n          case 'y':\n          if (optarg) {\n            if (strcmp(optarg, \"f\") == 0) {\n              is_integer = false;\n            } else if (strcmp(optarg, \"i\") != 0) {\n              is_valid_command = false;\n            }\n          }\n          break;\n\n        }\n      }\n\n  if (is_index == is_query) {\n    is_valid_command = false;\n  }\n  if (is_index) {\n    if (!is_valid_command || d < 0 || m < 0 || n < 0\n        || !file_exists(data_file_path) || !dir_exists(index_dir_path)) {\n      is_valid_command = false;\n    } else if (b < 0) {\n      if (is_integer) {\n        SRS_In_Memory<int> * indexer = new SRS_In_Memory<int>(index_dir_path);\n        indexer->build_index(n, d, m, data_file_path);\n        delete indexer;\n      } else {\n        SRS_In_Memory<float> * indexer = new SRS_In_Memory<float>(\n            index_dir_path);\n        indexer->build_index(n, d, m, data_file_path);\n        delete indexer;\n      }\n    } else {\n      printf(\"use R-tree here\\n\");\n    }\n  }\n  if (is_query) {\n    if (!is_valid_command || k < 0 || c < 1 || t < 0 || p_thres < 0\n        || !file_exists(query_file_path) || !file_exists(ground_truth_file_path)\n        || !dir_exists(index_dir_path)) {\n      is_valid_command = false;\n    } else {\n      char * type = new char[10];\n      float * temp = readParamFile(index_dir_path, n, d, m, b, type);\n      delete[] temp;\n      if (b == -1) {\n        if (strcmp(type, \"int\") == 0) {\n          SRS_In_Memory<int> * searcher = new SRS_In_Memory<int>(\n              index_dir_path);\n          searcher->restore_index();\n          query_workload(searcher, k, t, cal_thres(c, p_thres, m),\n                         query_file_path, ground_truth_file_path,\n                         output_file_path);\n          delete searcher;\n        } else if (strcmp(type, \"float\") == 0) {\n          SRS_In_Memory<float> * searcher = new SRS_In_Memory<float>(\n              index_dir_path);\n          searcher->restore_index();\n          query_workload(searcher, k, t, cal_thres(c, p_thres, m),\n                         query_file_path, ground_truth_file_path,\n                         output_file_path);\n          delete searcher;\n        }\n        delete[] type;\n      } else {\n        printf(\"use R-tree here\\n\");\n      }\n    }\n  }\n\n  if (!is_valid_command) {\n    usage();\n  }\n\n  return 0;\n}\n\nvoid usage() {\n  printf(\"SRS-Mem (v1.0)\\n\");\n  printf(\"Options\\n\");\n  //printf(\"-b {value}\\tpage size in bytes (need to be a multiple of 4)\\n\");\n  printf(\"-c {value}\\tapproximation ratio (>= 1)\\n\");\n  printf(\"-d {value}\\tdimensionality of data\\n\");\n  printf(\"-e {value}\\tseed for random generators\\n\");\n  printf(\"-g {string}\\tground truth file\\n\");\n  printf(\"-i {string}\\tsrs index path (dir)\\n\");\n  printf(\"-I (function)\\tindex data\\n\");\n  printf(\"-k {value}\\tnumber of neighbors wanted\\n\");\n  printf(\"-m {value}\\tdimensionality of the projected space\\n\");\n  printf(\"-n {value}\\tcardinality\\n\");\n  //printf(\"-o {string}\\toutput file\\n\");\n  printf(\"-q {string}\\tquery file\\n\");\n  printf(\"-Q (function)\\tprocess queries\\n\");\n  printf(\"-r {value}\\tthreshold of early termination condition\\n\");\n  printf(\"-s {string}\\tdataset file\\n\");\n  printf(\"-t {value}\\tmaximum number of verify points\\n\");\n  printf(\n      \"-y {string}\\tdata type (i: integer; f: floating number), default value: integer\\n\");\n  printf(\"\\n\");\n  printf(\"Usage:\\n\");\n\n  // printf(\"Index data (using R-tree)\\n\");\n  // printf(\"-I -b -d -i -m -n -s\\n\");\n\n  printf(\"Index data (using cover-tree)\\n\");\n  printf(\"-I -d -i -m -n -s [-y]\\n\");\n\n  printf(\"Process queries\\n\");\n  printf(\"-Q -c -g -i -k -q -r -t\\n\");\n}\n\nbool file_exists(const char *filename) {\n  std::ifstream ifile(filename);\n  if (!ifile) {\n    fprintf(stderr, \"cannot open file %s\\n\", filename);\n  }\n  return bool(ifile);\n}\n\nbool dir_exists(const char *dirname) {\n  DIR * dir = opendir(dirname);\n  if (dir) {\n    closedir(dir);\n    return true;\n  }\n  fprintf(stderr, \"cannot open dir %s\\n\", dirname);\n  return false;\n}\n\ntemplate<class T>\nvoid query_workload(SRS_In_Memory<T> * searcher, int k, int t, double thres,\n                    char *query_file_path, char *ground_truth_file_path,\n                    char *output_file_path) {\n  typedef typename Accumulator<T>::Type ResultType;\n  int qn, d, gn, gk, tmp;\n  FILE *qfp = fopen(query_file_path, \"r\");\n  FILE *gfp = fopen(ground_truth_file_path, \"r\");\n\n  fscanf(qfp, \"%d %d\", &qn, &d);\n  fscanf(gfp, \"%d %d\", &gn, &gk);\n  if (gn != qn || gk < k) {\n    fprintf(\n        stderr,\n        \"Ground truth file not correct! Please re-generate ground truth with correct parameters.\\n\");\n    return;\n  }\n  double overall_ratio = 0.0;\n  double overall_time = 0.0;\n\n  T * query = new T[d];\n  float * gt = new float[gk];\n  std::vector<res_pair_raw<ResultType> > res;\n  for (int i = 0; i < qn; ++i) {\n    fscanf(qfp, \"%d\", &tmp);\n    for (int j = 0; j < d; ++j) {\n      fscanf(qfp, type_format<T>::format(), &query[j]);\n    }\n    fscanf(gfp, \"%d\", &tmp);\n    for (int j = 0; j < gk; ++j) {\n      fscanf(gfp, \"%f\", &gt[j]);\n    }\n\n    timeval start;\n    gettimeofday(&start, NULL);\n    searcher->knn_search(query, k, t + k - 1, thres, res);\n    timeval end;\n    gettimeofday(&end, NULL);\n    overall_time += diff_timeval(end, start);\n\n    double ratio = 0.0;\n    std::sort(res.begin(), res.end());\n    for (int j = 0; j < k; ++j) {\n      ratio += sqrt(res[j].dist) / gt[j];\n    }\n    // de-comment the following line to print out the average ratio for each query\n    // printf(\"%f\\n\", ratio / k);\n    overall_ratio += ratio;\n  }\n\n  //printf(\"=================\\n\");\n  printf(\"Overall Ratio: %f\\n\", overall_ratio / k / qn);\n  printf(\"Average Time (s):  %f\\n\", overall_time / qn);\n\n  delete[] query;\n  delete[] gt;\n  fclose(qfp);\n  fclose(gfp);\n}\n\ndouble cal_thres(double c, double p_thres, int m) {\n  if (p_thres >= 1) {\n    return -1;\n  }\n  boost::math::chi_squared chi(m);\n  return boost::math::quantile(chi, p_thres) / c / c;\n}\n", "meta": {"hexsha": "6440e9390befe096d1ed1afce3d577dd5df1a324", "size": 11144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SRS/srs.cpp", "max_stars_repo_name": "1flei/lccs-lsh", "max_stars_repo_head_hexsha": "c903e557587de366e6ad67e8681b04061989bd6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-07-18T18:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T13:34:51.000Z", "max_issues_repo_path": "SRS/srs.cpp", "max_issues_repo_name": "HuangQiang/lccs-lsh", "max_issues_repo_head_hexsha": "08a74e198f9068b07f67d08369ac5daa790ee106", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRS/srs.cpp", "max_forks_repo_name": "HuangQiang/lccs-lsh", "max_forks_repo_head_hexsha": "08a74e198f9068b07f67d08369ac5daa790ee106", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-06T08:16:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T02:39:23.000Z", "avg_line_length": 29.4036939314, "max_line_length": 101, "alphanum_fraction": 0.5381371141, "num_tokens": 3052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.0362200550847165, "lm_q1q2_score": 0.011374928038988503}}
{"text": "//------------------------------------------------------------------------------\n// @file   : tms_rp_voronoi_map.cpp\n// @brief  : voronoi map for robot's path planning\n// @author : Yoonseok Pyo, Kouhei Nakashima\n// @version: Ver0.0.3 (since 2015.08.10)\n// @date   : 2015.09.03\n//------------------------------------------------------------------------------\n// include for ROS\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <visualization_msgs/Marker.h>\n\n#include <tms_msg_db/TmsdbGetData.h>\n#include <tms_msg_db/TmsdbStamped.h>\n#include <tms_msg_db/Tmsdb.h>\n\n#include <tms_msg_ss/tracking_points.h>\n\n#include <tms_msg_rp/rps_map_full.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n// include for std\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <vector>\n\nnamespace tms_rp\n{\nusing namespace std;\nusing Eigen::Vector3d;\nusing Eigen::Matrix3d;\ntypedef Eigen::Vector3d Vector3;\ntypedef Eigen::Matrix3d Matrix3;\n\nclass CollisionMapData\n{\npublic:\n  bool object_;\n  double dist_from_obj_;\n  bool collision_;\n  bool voronoi_;\n  int thinning_flg_;\n  double dist_from_voronoi_;\n  bool path_;\n  double dist_from_path_;\n  double dist_from_goal_;\n  bool person_view_;\n  double table_height_;\n};\n\nclass TmsRpVoronoiMap\n{\nprivate:\n  // ROS NodeHandle\n  ros::NodeHandle nh;\n  ros::NodeHandle nh_priv;\n  // ROS Timer\n  ros::Timer static_map_update_timer;\n  ros::Timer dynamic_map_update_timer;\n  // ROS Topic Subscriber\n  ros::Publisher static_map_pub_;\n  ros::Publisher dynamic_map_pub_;\n  vector< vector< CollisionMapData > > collision_map_;\n  tms_msg_rp::rps_map_full static_map_;\n  tms_msg_rp::rps_map_full dynamic_map_;\n  string result_msg_;\n  ros::ServiceClient get_data_client_;\n  ros::Publisher nonvoronoi_map_marker_pub, static_map_marker_pub, dynamic_marker_pub;\n  // ROS Parameters:\n  double update_time;\n  bool is_debug;\n\npublic:\n  TmsRpVoronoiMap()\n    : nh_priv(\"~\")\n    , update_time(1)\n    ,  // sec\n    is_debug(false)\n  {\n    // Init parameter\n    nh_priv.param(\"update_time\", update_time, update_time);\n    nh_priv.param(\"is_debug\", is_debug, is_debug);\n    ROS_ASSERT(initTmsRpVoronoiMap());\n    // Subscriber for tms_db_data topic\n    get_data_client_ = nh.serviceClient< tms_msg_db::TmsdbGetData >(\"/tms_db_reader\");\n    static_map_pub_ = nh.advertise< tms_msg_rp::rps_map_full >(\"rps_map_data\", 1);\n    dynamic_map_pub_ = nh.advertise< tms_msg_rp::rps_map_full >(\"rps_dynamic_map\", 1);\n    nonvoronoi_map_marker_pub = nh.advertise< visualization_msgs::Marker >(\"nonvoronoi_map_marker\", 1);\n    static_map_marker_pub = nh.advertise< visualization_msgs::Marker >(\"voronoi_map_marker\", 1);\n    dynamic_marker_pub = nh.advertise< visualization_msgs::Marker >(\"dynamic_map_marker\", 1);\n    // TimerEvent\n    static_map_update_timer = nh.createTimer(ros::Duration(update_time), &TmsRpVoronoiMap::staticMapPublish, this);\n    dynamic_map_update_timer = nh.createTimer(ros::Duration(update_time), &TmsRpVoronoiMap::dynamicMapPublish, this);\n\n    initCollisionMap(collision_map_);\n    setVoronoiLine(collision_map_, result_msg_);\n    calcDistFromObj(collision_map_, result_msg_);\n    convertMap(collision_map_, static_map_);\n  }\n\n  ~TmsRpVoronoiMap()\n  {\n    ROS_ASSERT(shutdownTmsRpVoronoiMap());\n  }\n\nprivate:\n  double x_llimit_, x_ulimit_, y_llimit_, y_ulimit_, cell_size_;  // Meter\n  bool initTmsRpVoronoiMap()\n  {\n    ROS_INFO(\"tms_rp_voronoi_map : Init OK!\\n\");\n    return true;\n  }\n\n  bool shutdownTmsRpVoronoiMap()\n  {\n    return true;\n  }\n\n  bool initCollisionMap(vector< vector< CollisionMapData > >& map)\n  {\n    FILE* fp;\n    string file_name;\n    char home_dir[255];\n    const char* fname;\n\n    //      strcpy(home_dir, getenv(\"HOME\"));\n    //      file_name = home_dir;\n    //      file_name += \"/catkin_ws/src/ros_tms/tms_rp/tms_rp_action/map/use_collision_map.csv\";\n    file_name = ros::package::getPath(\"tms_rp_voronoi_map\") + \"/map/use_collision_map.csv\";\n    ROS_INFO(file_name.c_str());\n    fname = file_name.c_str();\n\n    while (1)\n    {\n      if ((fp = fopen(fname, \"r\")) == NULL)\n      {\n        cout << \"Error: collision map cannot open\" << endl;\n        return false;\n      }\n      else\n        break;\n    }\n\n    map.clear();\n    vector< CollisionMapData > tempMapLine;\n    CollisionMapData tempMapData;\n\n    char* tp, buff[4096];\n\n    if (fgets(buff, 4096, fp) == NULL)\n      return false;\n\n    tp = strtok(buff, \",\");\n    x_llimit_ = atof(tp);\n    tp = strtok(NULL, \",\");\n    x_ulimit_ = atof(tp);\n    tp = strtok(NULL, \",\");\n    y_llimit_ = atof(tp);\n    tp = strtok(NULL, \",\");\n    y_ulimit_ = atof(tp);\n    tp = strtok(NULL, \",\");\n    cell_size_ = atof(tp);\n\n    int CommaCount = 0;\n\n    while (fgets(buff, 4096, fp) != NULL)  // collision\n    {\n      CommaCount = 0;\n      tp = strtok(buff, \",\");\n      tempMapData.object_ = atof(tp);\n\n      if (tempMapData.object_)\n      {\n        tempMapData.dist_from_obj_ = 0.0;\n        tempMapData.collision_ = true;\n      }\n      else\n      {\n        tempMapData.dist_from_obj_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n        tempMapData.collision_ = false;\n      }\n\n      tempMapData.voronoi_ = false;\n      tempMapData.path_ = false;\n      tempMapData.thinning_flg_ = 0;\n      tempMapData.dist_from_voronoi_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n      tempMapData.dist_from_goal_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n      tempMapData.dist_from_path_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n      tempMapLine.push_back(tempMapData);\n\n      CommaCount++;\n\n      while (tp != NULL)\n      {\n        if (CommaCount == int(round((y_ulimit_ - y_llimit_) / cell_size_)) + 1)\n          break;\n\n        tp = strtok(NULL, \",\");\n        CommaCount++;\n\n        if (tp != NULL)\n        {\n          tempMapData.object_ = atof(tp);\n          if (tempMapData.object_)\n          {\n            tempMapData.dist_from_obj_ = 0.0;\n            tempMapData.collision_ = true;\n          }\n          else\n          {\n            tempMapData.dist_from_obj_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n            tempMapData.collision_ = false;\n          }\n\n          tempMapData.voronoi_ = false;\n          tempMapData.path_ = false;\n          tempMapData.thinning_flg_ = 0;\n          tempMapData.dist_from_voronoi_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n          tempMapData.dist_from_goal_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n          tempMapData.dist_from_path_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n          tempMapLine.push_back(tempMapData);\n        }\n      }\n\n      map.push_back(tempMapLine);\n      tempMapLine.clear();\n    }\n\n    fclose(fp);\n\n    return true;\n  }\n\n  bool setVoronoiLine(vector< vector< CollisionMapData > >& map, string& message)\n  {\n    if (map.empty())\n    {\n      message = \"Error : Map is empty\";\n      cout << message << endl;\n      return false;\n    }\n\n    for (unsigned int x = 0; x < map.size(); x++)\n    {\n      for (unsigned int y = 0; y < map[x].size(); y++)\n      {\n        map[x][y].voronoi_ = false;\n        if (!map[x][y].collision_)\n          map[x][y].thinning_flg_ = 1;\n        else\n          map[x][y].thinning_flg_ = 0;\n      }\n    }\n\n    bool flg = true;\n\n    while (flg)\n    {\n      flg = false;\n      for (int k = 0; k < 4; k++)\n      {\n        for (int x = 1; x < map.size() - 1; x++)\n        {\n          for (int y = 1; y < map[x].size() - 1; y++)\n          {\n            int i, j;\n\n            switch (k)\n            {\n              case 0:\n                i = x + 1;\n                j = y;\n                break;\n              case 1:\n                i = x;\n                j = y - 1;\n                break;\n              case 2:\n                i = x - 1;\n                j = y;\n                break;\n              case 3:\n                i = x;\n                j = y + 1;\n                break;\n            }\n\n            if ((map[x][y].thinning_flg_ == 1) && (map[i][j].thinning_flg_ == 0))\n            {\n              if (((map[x][y - 1].thinning_flg_ == 0) && (map[x + 1][y].thinning_flg_ == 1) &&\n                   (map[x][y + 1].thinning_flg_ == 1) && (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x][y - 1].thinning_flg_ == 1) &&\n                   (map[x - 1][y].thinning_flg_ == 1) && (map[x + 1][y].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x][y - 1].thinning_flg_ == 1) &&\n                   (map[x - 1][y].thinning_flg_ == 1) && (map[x][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y].thinning_flg_ == 0) && (map[x + 1][y].thinning_flg_ == 1) &&\n                   (map[x][y + 1].thinning_flg_ == 1) && (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y].thinning_flg_ == 0) && (map[x + 1][y].thinning_flg_ == 0) &&\n                   (map[x][y + 1].thinning_flg_ == 1)) ||\n                  ((map[x][y - 1].thinning_flg_ == 0) && (map[x - 1][y].thinning_flg_ == 1) &&\n                   (map[x][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x][y - 1].thinning_flg_ == 1) && (map[x - 1][y].thinning_flg_ == 0) &&\n                   (map[x + 1][y].thinning_flg_ == 0)) ||\n                  ((map[x][y - 1].thinning_flg_ == 0) && (map[x + 1][y].thinning_flg_ == 1) &&\n                   (map[x][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y].thinning_flg_ == 0) && (map[x - 1][y + 1].thinning_flg_ == 1) &&\n                   (map[x][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 1) && (map[x][y - 1].thinning_flg_ == 0) &&\n                   (map[x - 1][y].thinning_flg_ == 0)) ||\n                  ((map[x][y - 1].thinning_flg_ == 0) && (map[x + 1][y - 1].thinning_flg_ == 1) &&\n                   (map[x + 1][y].thinning_flg_ == 0)) ||\n                  ((map[x + 1][y].thinning_flg_ == 0) && (map[x][y + 1].thinning_flg_ == 0) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 1)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x][y - 1].thinning_flg_ == 1) &&\n                   (map[x + 1][y - 1].thinning_flg_ == 0) && (map[x - 1][y].thinning_flg_ == 1) &&\n                   (map[x + 1][y].thinning_flg_ == 1) && (map[x - 1][y + 1].thinning_flg_ == 0) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x][y - 1].thinning_flg_ == 1) &&\n                   (map[x + 1][y - 1].thinning_flg_ == 0) && (map[x + 1][y].thinning_flg_ == 1) &&\n                   (map[x - 1][y + 1].thinning_flg_ == 0) && (map[x][y + 1].thinning_flg_ == 1) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x + 1][y - 1].thinning_flg_ == 0) &&\n                   (map[x - 1][y].thinning_flg_ == 1) && (map[x + 1][y].thinning_flg_ == 1) &&\n                   (map[x - 1][y + 1].thinning_flg_ == 0) && (map[x][y + 1].thinning_flg_ == 1) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x][y - 1].thinning_flg_ == 1) &&\n                   (map[x + 1][y - 1].thinning_flg_ == 0) && (map[x - 1][y].thinning_flg_ == 1) &&\n                   (map[x - 1][y + 1].thinning_flg_ == 0) && (map[x][y + 1].thinning_flg_ == 1) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x][y - 1].thinning_flg_ == 0) &&\n                   (map[x + 1][y - 1].thinning_flg_ == 0) && (map[x - 1][y].thinning_flg_ == 0) &&\n                   (map[x - 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x][y - 1].thinning_flg_ == 0) &&\n                   (map[x + 1][y - 1].thinning_flg_ == 0) && (map[x + 1][y].thinning_flg_ == 0) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x - 1][y - 1].thinning_flg_ == 0) && (map[x - 1][y].thinning_flg_ == 0) &&\n                   (map[x - 1][y + 1].thinning_flg_ == 0) && (map[x][y + 1].thinning_flg_ == 0) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 0)) ||\n                  ((map[x + 1][y - 1].thinning_flg_ == 0) && (map[x + 1][y].thinning_flg_ == 0) &&\n                   (map[x - 1][y + 1].thinning_flg_ == 0) && (map[x][y + 1].thinning_flg_ == 0) &&\n                   (map[x + 1][y + 1].thinning_flg_ == 0)))\n                map[x][y].thinning_flg_ = 1;\n              else\n              {\n                flg = true;\n                map[x][y].thinning_flg_ = 3;\n              }\n            }\n          }\n        }\n        for (int x = 1; x < map.size() - 1; x++)\n        {\n          for (int y = 1; y < map[x].size() - 1; y++)\n          {\n            if (map[x][y].thinning_flg_ == 3)\n              map[x][y].thinning_flg_ = 0;\n          }\n        }\n      }\n    }\n\n    for (int x = 0; x < map.size(); x++)\n    {\n      for (int y = 0; y < map[x].size(); y++)\n      {\n        if (map[x][y].thinning_flg_ == 1)\n        {\n          map[x][y].voronoi_ = 1;\n          map[x][y].dist_from_voronoi_ = 0.0;\n        }\n        else\n        {\n          map[x][y].voronoi_ = 0;\n        }\n      }\n    }\n    return true;\n  }\n\n  bool calcDistFromObj(vector< vector< CollisionMapData > >& map, string& message)\n  {\n    if (map.empty())\n    {\n      message = \"Error : Map is empty\";\n      cout << message << endl;\n      return false;\n    }\n\n    for (int x = 0; x < map.size(); x++)\n    {\n      for (int y = 0; y < map[x].size(); y++)\n      {\n        if (map[x][y].object_)\n          map[x][y].dist_from_obj_ = 0.0;\n        else\n          map[x][y].dist_from_obj_ = (x_ulimit_ - x_llimit_) * (y_ulimit_ - y_llimit_);\n      }\n    }\n\n    for (int x = 1; x < map.size() - 1; x++)\n    {\n      for (int y = 1; y < map[x].size() - 1; y++)\n      {\n        if (!map[x][y].object_)\n        {\n          map[x][y].dist_from_obj_ = min(min(min(map[x - 1][y - 1].dist_from_obj_ + sqrt(2.0) * cell_size_,\n                                                 map[x][y - 1].dist_from_obj_ + 1.0 * cell_size_),\n                                             min(map[x - 1][y + 1].dist_from_obj_ + sqrt(2.0) * cell_size_,\n                                                 map[x - 1][y].dist_from_obj_ + 1.0 * cell_size_)),\n                                         map[x][y].dist_from_obj_);\n        }\n      }\n    }\n\n    for (int x = map.size() - 2; x > 0; x--)\n    {\n      for (int y = map[x].size() - 2; y > 0; y--)\n      {\n        if (!map[x][y].object_)\n        {\n          map[x][y].dist_from_obj_ = min(min(min(map[x + 1][y].dist_from_obj_ + 1.0 * cell_size_,\n                                                 map[x + 1][y - 1].dist_from_obj_ + sqrt(2.0) * cell_size_),\n                                             min(map[x][y + 1].dist_from_obj_ + 1.0 * cell_size_,\n                                                 map[x + 1][y + 1].dist_from_obj_ + sqrt(2.0) * cell_size_)),\n                                         map[x][y].dist_from_obj_);\n        }\n      }\n    }\n\n    return true;\n  }\n\n  void convertMap(vector< vector< CollisionMapData > > map, tms_msg_rp::rps_map_full& pp_map)\n  {\n    pp_map.rps_map_x.clear();\n\n    pp_map.x_llimit = x_llimit_;\n    pp_map.x_ulimit = x_ulimit_;\n    pp_map.y_llimit = y_llimit_;\n    pp_map.y_ulimit = y_ulimit_;\n    pp_map.cell_size = cell_size_;\n\n    tms_msg_rp::rps_map_data temp_map_d;\n    tms_msg_rp::rps_map_y temp_map_y;\n\n    for (unsigned int x = 0; x < map.size(); x++)\n    {\n      temp_map_y.rps_map_y.clear();\n      for (unsigned int y = 0; y < map[x].size(); y++)\n      {\n        temp_map_d.object = map[x][y].object_;\n        temp_map_d.voronoi = map[x][y].voronoi_;\n        temp_map_d.dist_from_obj_f = map[x][y].dist_from_obj_;\n\n        temp_map_y.rps_map_y.push_back(temp_map_d);\n      }\n      pp_map.rps_map_x.push_back(temp_map_y);\n    }\n  }\n\n  void staticMapPublish(const ros::TimerEvent& e)\n  {\n    static_map_pub_.publish(static_map_);\n\n    uint32_t shape = visualization_msgs::Marker::POINTS;\n\n    visualization_msgs::Marker voronoi_marker;\n    voronoi_marker.header.frame_id = \"world_link\";\n    voronoi_marker.header.stamp = ros::Time::now();\n    voronoi_marker.ns = \"voronoi_map\";\n    voronoi_marker.id = 0;\n    voronoi_marker.type = shape;\n    voronoi_marker.action = visualization_msgs::Marker::ADD;\n\n    voronoi_marker.pose.orientation.x = 0.0;\n    voronoi_marker.pose.orientation.y = 0.0;\n    voronoi_marker.pose.orientation.z = 0.0;\n    voronoi_marker.pose.orientation.w = 1.0;\n\n    // Set the scale of the marker -- 1x1x1 here means 1m on a side\n    voronoi_marker.scale.x = 0.1;\n    voronoi_marker.scale.y = 0.1;\n    voronoi_marker.scale.z = 0.1;\n\n    // Set the color -- be sure to set alpha to something non-zero!\n    voronoi_marker.color.r = 0.0f;\n    voronoi_marker.color.g = 1.0f;\n    voronoi_marker.color.b = 0.0f;\n    voronoi_marker.color.a = 1.0;\n\n    visualization_msgs::Marker nonvoronoi_marker;\n    nonvoronoi_marker.header.frame_id = \"world_link\";\n    nonvoronoi_marker.header.stamp = ros::Time::now();\n    nonvoronoi_marker.ns = \"nonvoronoi_map\";\n    nonvoronoi_marker.id = 0;\n    nonvoronoi_marker.type = shape;\n    nonvoronoi_marker.action = visualization_msgs::Marker::ADD;\n\n    nonvoronoi_marker.pose.orientation.x = 0.0;\n    nonvoronoi_marker.pose.orientation.y = 0.0;\n    nonvoronoi_marker.pose.orientation.z = 0.0;\n    nonvoronoi_marker.pose.orientation.w = 1.0;\n\n    // Set the scale of the marker -- 1x1x1 here means 1m on a side\n    nonvoronoi_marker.scale.x = 0.1;\n    nonvoronoi_marker.scale.y = 0.1;\n    nonvoronoi_marker.scale.z = 0.1;\n\n    // Set the color -- be sure to set alpha to something non-zero!\n    nonvoronoi_marker.color.r = 0.65;\n    nonvoronoi_marker.color.g = 0.65;\n    nonvoronoi_marker.color.b = 0.65;\n    nonvoronoi_marker.color.a = 1.0;\n\n    geometry_msgs::Point p;\n\n    for (unsigned int x = 0; x < static_map_.rps_map_x.size(); x++)\n    {\n      for (unsigned int y = 0; y < static_map_.rps_map_x[x].rps_map_y.size(); y++)\n      {\n        if (static_map_.rps_map_x[x].rps_map_y[y].voronoi)\n        {\n          // p.x = x*0.1 - 0.3;\n          // p.y = y*0.1 - 0.5;\n          p.x = x * 0.1;\n          p.y = y * 0.1;\n          p.z = 0.01;\n          voronoi_marker.points.push_back(p);\n        }\n\n        if (!static_map_.rps_map_x[x].rps_map_y[y].object)\n        {\n          p.x = x * 0.1;\n          p.y = y * 0.1;\n          p.z = 0.005;\n          nonvoronoi_marker.points.push_back(p);\n        }\n      }\n    }\n    static_map_marker_pub.publish(voronoi_marker);\n    nonvoronoi_map_marker_pub.publish(nonvoronoi_marker);\n  }\n\n  void dynamicMapPublish(const ros::TimerEvent& e)\n  {\n    int map_x = 0, map_y = 0;\n    vector< vector< CollisionMapData > > temp_Map;\n    string result_msg;\n\n    temp_Map.clear();\n    temp_Map = collision_map_;\n\n    Vector3 object_pos = Vector3(0, 0, 0);\n    Matrix3 object_ori;\n    Vector3 object_rpy;\n    //    BodyItemPtr item;\n    //    TmsRpController trc;\n\n    //    // add current position of obstacle (wagon)\n    //    item = trc.objTag2Item()[\"wagon\"];\n    //    if(!item){\n    //      ROS_INFO(\"Error: The tagId is not recorded.\");\n    //    }\n    //    object_pos = item->body()->link(0)->p();\n    //    object_ori = item->body()->link(0)->R();\n    //    item->calcForwardKinematics();\n    //    item->notifyKinematicStateChange();\n\n    //    object_rpy = grasp::rpyFromRot(object_ori);\n\n    //    map_x = (int)round( ( object_pos(0) - x_llimit_ ) / cell_size_ );\n    //    map_y = (int)round( ( object_pos(1) - y_llimit_ ) / cell_size_ );\n\n    //    for(int check_x_size=map_x-2;check_x_size<=map_x+2;check_x_size++)\n    //    {\n    //      for(int check_y_size=map_y-2;check_y_size<=map_y+2;check_y_size++)\n    //      {\n    //        if (check_x_size < 0 || check_y_size < 0 || check_x_size > 80 || check_y_size > 45) continue;\n    //        temp_Map[check_x_size][check_y_size].object_        = 1;\n    //        temp_Map[check_x_size][check_y_size].dist_from_obj_ = 0.0;\n    //        temp_Map[check_x_size][check_y_size].collision_     = true;\n    //      }\n    //    }\n\n    setVoronoiLine(temp_Map, result_msg);\n    calcDistFromObj(temp_Map, result_msg);\n    convertMap(temp_Map, dynamic_map_);\n\n    dynamic_map_pub_.publish(dynamic_map_);\n\n    uint32_t shape = visualization_msgs::Marker::POINTS;\n    visualization_msgs::Marker marker;\n    marker.header.frame_id = \"world_link\";\n    marker.header.stamp = ros::Time::now();\n    marker.ns = \"dynamic_map\";\n    marker.id = 0;\n    marker.type = shape;\n    marker.action = visualization_msgs::Marker::ADD;\n\n    marker.pose.orientation.x = 0.0;\n    marker.pose.orientation.y = 0.0;\n    marker.pose.orientation.z = 0.0;\n    marker.pose.orientation.w = 1.0;\n\n    // Set the scale of the marker -- 1x1x1 here means 1m on a side\n    marker.scale.x = 0.1;\n    marker.scale.y = 0.1;\n    marker.scale.z = 0.1;\n\n    // Set the color -- be sure to set alpha to something non-zero!\n    marker.color.r = 1.0f;\n    marker.color.g = 0.0f;\n    marker.color.b = 0.0f;\n    marker.color.a = 1.0;\n\n    geometry_msgs::Point p;\n\n    for (unsigned int x = 0; x < dynamic_map_.rps_map_x.size(); x++)\n    {\n      for (unsigned int y = 0; y < dynamic_map_.rps_map_x[x].rps_map_y.size(); y++)\n      {\n        if (dynamic_map_.rps_map_x[x].rps_map_y[y].voronoi)\n        {\n          marker.id = 0;\n          // Set the pose of the marker.  This is a full 6DOF pose relative to the frame/time specified in the header\n          p.x = x * 0.1;\n          p.y = y * 0.1;\n          p.z = 0.01;\n          marker.points.push_back(p);\n        }\n      }\n    }\n\n    dynamic_marker_pub.publish(marker);\n  }\n\n  void dynamicMapPublish(tms_msg_ss::tracking_points unknown_moving_object_pos)\n  {\n    int map_x = 0, map_y = 0;\n    int obstacle_pos_x = 0, obstacle_pos_y = 0;\n    vector< vector< CollisionMapData > > temp_Map;\n    string result_msg;\n\n    temp_Map.clear();\n    temp_Map = collision_map_;\n\n    Vector3 object_pos = Vector3(0, 0, 0);\n    Matrix3 object_ori;\n    Vector3 object_rpy;\n    //    BodyItemPtr item;\n    //    TmsRpController trc;\n\n    //    // add current position of obstacle (wagon)\n    //    item = trc.objTag2Item()[\"wagon\"];\n    //    if(!item){\n    //      ROS_INFO(\"Error: The tagId is not recorded.\");\n    //    }\n    //    object_pos = item->body()->link(0)->p();\n    //    object_ori = item->body()->link(0)->R();\n    //    item->calcForwardKinematics();\n    //    item->notifyKinematicStateChange();\n\n    //    object_rpy = grasp::rpyFromRot(object_ori);\n\n    //    map_x = (int)round( ( object_pos(0) - x_llimit_ ) / cell_size_ );\n    //    map_y = (int)round( ( object_pos(1) - y_llimit_ ) / cell_size_ );\n\n    //    for(int check_x_size=map_x-2;check_x_size<=map_x+2;check_x_size++)\n    //    {\n    //      for(int check_y_size=map_y-2;check_y_size<=map_y+2;check_y_size++)\n    //      {\n    //        if (check_x_size < 0 || check_y_size < 0 || check_x_size > 80 || check_y_size > 45) continue;\n    //        temp_Map[check_x_size][check_y_size].object_        = 1;\n    //        temp_Map[check_x_size][check_y_size].dist_from_obj_ = 0.0;\n    //        temp_Map[check_x_size][check_y_size].collision_     = true;\n    //      }\n    //    }\n\n    //    // add current position of unknown moving object (umo)\n    //    for(unsigned int i=0;i<unknown_moving_object_pos.tracking_grid.size();i++)\n    //    {\n\n    //      obstacle_pos_x = unknown_moving_object_pos.tracking_grid[i].x/1000;\n    //      obstacle_pos_y = unknown_moving_object_pos.tracking_grid[i].y/1000;\n\n    //      map_x = (int)round( ( obstacle_pos_x - x_llimit_ ) / cell_size_ );\n    //      map_y = (int)round( ( obstacle_pos_y - y_llimit_ ) / cell_size_ );\n\n    //      for(int check_x_size=map_x-2;check_x_size<=map_x+2;check_x_size++)\n    //      {\n    //        for(int check_y_size=map_y-2;check_y_size<=map_y+2;check_y_size++)\n    //        {\n    //        if (check_x_size < 0 || check_y_size < 0 || check_x_size > 80 || check_y_size > 45) continue;\n    //          temp_Map[check_x_size][check_y_size].object_        = 1;\n    //          temp_Map[check_x_size][check_y_size].dist_from_obj_ = 0.0;\n    //          temp_Map[check_x_size][check_y_size].collision_     = true;\n    //        }\n    //      }\n    //    }\n\n    setVoronoiLine(temp_Map, result_msg);\n    calcDistFromObj(temp_Map, result_msg);\n    convertMap(temp_Map, dynamic_map_);\n\n    dynamic_map_pub_.publish(dynamic_map_);\n  }\n};\n}  // namespace tms_rp\n\nint main(int argc, char** argv)\n{\n  // Init ROS node\n  ros::init(argc, argv, \"tms_rp_voronoi_map\");\n  tms_rp::TmsRpVoronoiMap vm;\n  ros::spin();\n  return 0;\n}\n// EOF\n", "meta": {"hexsha": "02a7089f8ea82792c43ab6153c7f04bbd681f62f", "size": 24752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tms_rp/tms_rp_voronoi_map/src/voronoi_map.cpp", "max_stars_repo_name": "robotpilot/ros_tms", "max_stars_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T07:49:37.000Z", "max_issues_repo_path": "tms_rp/tms_rp_voronoi_map/src/voronoi_map.cpp", "max_issues_repo_name": "robotpilot/ros_tms", "max_issues_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 114.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T06:42:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:54:04.000Z", "max_forks_repo_path": "tms_rp/tms_rp_voronoi_map/src/voronoi_map.cpp", "max_forks_repo_name": "robotpilot/ros_tms", "max_forks_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-03-27T08:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T13:05:31.000Z", "avg_line_length": 34.0936639118, "max_line_length": 117, "alphanum_fraction": 0.5446024564, "num_tokens": 7692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.02595735512564666, "lm_q1q2_score": 0.011364740048860586}}
{"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/// Computes effective conductivities versus temperature for\n/// nanosystems (nanowires and nanoribbons)\n/// Material information and sweep settings provided via XML input.\n\n#include <iostream>\n#include <functional>\n#include <boost/filesystem.hpp>\n#include <boost/mpi.hpp>\n#include <utilities.hpp>\n#include <vasp_io.hpp>\n#include <qpoint_grid.hpp>\n#include <processes.hpp>\n#include <isotopic_scattering.hpp>\n#include <bulk_hdf5.hpp>\n#include <analytic1d.hpp>\n#include <io_utils.hpp>\n#include <bulk_properties.hpp>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <nanos.hpp>\n\n#define TBB_PREVIEW_GLOBAL_CONTROL true\n#include <tbb/global_control.h>\n\nint main(int argc, char** argv) {\n    // set up MPI environment\n    boost::mpi::environment env;\n    boost::mpi::communicator world;\n\n    if (world.size() > 1) {\n        std::cout\n            << \"*** ERROR: kappa_Tsweep does not run in parallel mode. ***\"\n            << std::endl;\n        world.abort(1);\n    }\n\n    if (argc < 2) {\n        std::cout << \"USAGE: kappa_Tsweep <inputfile.xml>\" << std::endl;\n        return 1;\n    }\n\n    else {\n        // Set parallelism\n        std::size_t nthreadsTBB = 1;\n        if (argc > 2)\n            nthreadsTBB = std::atoi(argv[2]);\n\n        tbb::global_control control(\n            tbb::global_control::max_allowed_parallelism, nthreadsTBB);\n\n\n        // define variables\n        std::string target_directory = \"AUTO\";\n        std::string target_filename = \"AUTO\";\n        std::string h5_repository = \".\";\n        std::string mat_directory;\n        std::string mat_base;\n        int gridDensityA = -1;\n        int gridDensityB = -1;\n        int gridDensityC = -1;\n        bool logsweep = false;\n        double Tmin = -1.0;\n        double Tmax = -1.0;\n        int NT = -1;\n        // bool Gductivity = false;\n        bool fullBTE = false;\n        bool fullBTE_iterative = true;\n        // bool outputCapacity = false;\n        bool superlattice = false;\n        std::string superlattice_UID = \"NULL\";\n\n        /// Variables about nanoribbons and nanowires\n        std::string system_name = \"NULL\";\n        Eigen::Vector3d uvector(0.0, 0.0, 0.0);\n        Eigen::Vector3d u_norm(0.0, 0.0, 0.0);\n        /// Limiting length (nanoribbon width or nanowire radii in nm)\n        double limiting_length = -1.0;\n        /// Name for anhIFCs\n        std::string AIFCfile = \"NULL\";\n        double scalebroad_three = -1;\n\n        std::cout << \"*************************************\" << std::endl;\n        std::cout << \"This is ALMA/kappa_Tsweep_nanos version \"\n                  << ALMA_VERSION_MAJOR << \".\" << ALMA_VERSION_MINOR\n                  << std::endl;\n        std::cout << \"*************************************\" << std::endl;\n        std::cout << std::endl\n                  << \" # TBB threads : \" << nthreadsTBB << std::endl;\n\n        // verify that input file exists.\n        if (!boost::filesystem::exists(boost::filesystem::path{argv[1]})) {\n            std::cout << \"ERROR: input file \" << argv[1] << \" does not exist.\"\n                      << std::endl;\n            exit(1);\n        }\n\n        /////////////////////////\n        /// PARSE INPUT FILE  ///\n        /////////////////////////\n\n        std::string xmlfile(argv[1]);\n        std::cout << \"PARSING \" << xmlfile << \" ...\" << std::endl;\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(xmlfile, tree);\n\n        for (const auto& v : tree.get_child(\"Tsweep\")) {\n            if (v.first == \"H5repository\") {\n                h5_repository =\n                    alma::parseXMLfield<std::string>(v, \"root_directory\");\n            }\n\n            if (v.first == \"target\") {\n                target_directory =\n                    alma::parseXMLfield<std::string>(v, \"directory\");\n                target_filename = alma::parseXMLfield<std::string>(v, \"file\");\n            }\n\n            if (v.first == \"compound\") {\n                mat_directory =\n                    alma::parseXMLfield<std::string>(v, \"directory\");\n                mat_base = alma::parseXMLfield<std::string>(v, \"base\");\n\n                gridDensityA = alma::parseXMLfield<int>(v, \"gridA\");\n                gridDensityB = alma::parseXMLfield<int>(v, \"gridB\");\n                gridDensityC = alma::parseXMLfield<int>(v, \"gridC\");\n            }\n\n            if (v.first == \"system\") {\n                system_name = alma::parseXMLfield<std::string>(v, \"name\");\n                limiting_length = alma::parseXMLfield<double>(v, \"L\");\n            }\n\n\n            if (v.first == \"superlattice\") {\n                superlattice_UID = alma::parseXMLfield<std::string>(v, \"UID\");\n            }\n\n            if (v.first == \"sweep\") {\n                std::string sweepID =\n                    alma::parseXMLfield<std::string>(v, \"type\");\n\n                if (sweepID.compare(\"log\") == 0) {\n                    logsweep = true;\n                }\n\n                Tmin = alma::parseXMLfield<double>(v, \"start\");\n                Tmax = alma::parseXMLfield<double>(v, \"stop\");\n                NT = alma::parseXMLfield<int>(v, \"points\");\n            }\n\n            if (v.first == \"fullBTE\") {\n                fullBTE = true;\n                fullBTE_iterative = alma::parseXMLfield<bool>(v, \"iterative\");\n            }\n\n            if (v.first == \"transportAxis\") {\n                double ux = alma::parseXMLfield<double>(v, \"x\");\n                double uy = alma::parseXMLfield<double>(v, \"y\");\n                double uz = alma::parseXMLfield<double>(v, \"z\");\n\n                uvector << ux, uy, uz;\n            }\n            if (v.first == \"AnharmonicIFC\") {\n                AIFCfile = alma::parseXMLfield<std::string>(v, \"name\");\n                scalebroad_three = alma::parseXMLfield<double>(v, \"scalebroad\");\n            }\n\n        } // end XML parsing\n\n        // Ensure that provided information is within expected bounds\n\n        bool badinput = false;\n\n        if (gridDensityA < 1) {\n            std::cout << \"ERROR: provided gridA is \" << gridDensityA\n                      << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (gridDensityB < 1) {\n            std::cout << \"ERROR: provided gridB is \" << gridDensityB\n                      << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (gridDensityC < 1) {\n            std::cout << \"ERROR: provided gridC is \" << gridDensityC\n                      << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (Tmin <= 0.0) {\n            std::cout << \"ERROR: provided start temperature is \" << Tmin\n                      << std::endl;\n            std::cout << \"Value must be positive.\" << std::endl;\n            badinput = true;\n        }\n\n        if ((Tmax < Tmin) || (Tmax <= 0.0)) {\n            std::cout << \"ERROR: provided end temperature is \" << Tmax\n                      << std::endl;\n            std::cout << \"Value must be positive and >= start temperature.\"\n                      << std::endl;\n            badinput = true;\n        }\n\n        if (NT <= 0) {\n            std::cout << \"ERROR: provided number of temperature values is \"\n                      << NT << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (uvector.norm() < 1e-12) {\n            std::cout << \"ERROR: provided transport axis vector has zero norm.\"\n                      << std::endl;\n            badinput = true;\n        }\n\n\n        if (system_name != \"nanowire\" and system_name != \"nanoribbon\") {\n            std::cout << \"ERROR: only supported nanosystems options are:\"\n                      << std::endl\n                      << \"nanoribbon and nanowire\" << std::endl;\n\n            badinput = true;\n        }\n\n        if (system_name == \"nanoribbon\" and gridDensityC > 1) {\n            std::cout << \"ERROR: nanoribbons are expected to exist in xy plane\"\n                      << std::endl;\n\n            badinput = true;\n        }\n\n\n        if (limiting_length <= 0.) {\n            std::cout\n                << \"ERROR: limiting length of nanosystems cannot be negative\"\n                << std::endl;\n\n            badinput = true;\n        }\n\n        if (AIFCfile == \"NULL\" and fullBTE) {\n            std::cout << \"ERROR: Need to provide anharmonic IFC file\"\n                      << std::endl;\n\n            badinput = true;\n        }\n\n        if (scalebroad_three < 0. and fullBTE) {\n            std::cout << \"ERROR: scalebroad need to be supplied\" << std::endl;\n\n            badinput = true;\n        }\n\n\n        if (badinput) {\n            world.abort(1);\n        }\n\n        // Initialise file system and verify that directories actually exist\n        auto launch_path = boost::filesystem::current_path();\n        auto basedir = boost::filesystem::path(h5_repository);\n\n        if (!(boost::filesystem::exists(boost::filesystem::path(basedir)))) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"Repository directory \" << basedir\n                      << \" does not exist.\" << std::endl;\n            world.abort(1);\n        }\n\n        if (!(boost::filesystem::exists(\n                boost::filesystem::path(basedir / mat_directory)))) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"Material directory \" << mat_directory\n                      << \" does not exist within the HDF5 repository.\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n        // Resolve name of HDF5 file\n        std::stringstream h5namebuilder;\n        h5namebuilder << mat_base << \"_\" << gridDensityA << \"_\" << gridDensityB\n                      << \"_\" << gridDensityC << \".h5\";\n        std::string h5filename = h5namebuilder.str();\n\n        // obtain phonon data from HDF5 file\n        auto hdf5_path = basedir / boost::filesystem::path(mat_directory) /\n                         boost::filesystem::path(h5filename);\n\n        if (!(boost::filesystem::exists(hdf5_path))) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"H5 file \" << h5filename\n                      << \" does not exist within the material directory.\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n        std::cout << \"Opening HDF5 file \" << hdf5_path << std::endl;\n\n        auto hdf5_data =\n            alma::load_bulk_hdf5(hdf5_path.string().c_str(), world);\n        auto description = std::get<0>(hdf5_data);\n        auto poscar = std::move(std::get<1>(hdf5_data));\n        auto syms = std::move(std::get<2>(hdf5_data));\n        auto grid = std::move(std::get<3>(hdf5_data));\n        auto processes = std::move(std::get<4>(hdf5_data));\n\n        if (processes->size() == 0) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"List of 3-phonon processes is missing in H5 file.\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n        // Check if we are dealing with a superlattice.\n        // If so, load the applicable scattering data.\n\n        auto subgroups =\n            alma::list_scattering_subgroups(hdf5_path.string().c_str(), world);\n\n        int superlattice_count = 0;\n\n        for (std::size_t ngroup = 0; ngroup < subgroups.size(); ngroup++) {\n            if (subgroups.at(ngroup).find(\"superlattice\") !=\n                std::string::npos) {\n                superlattice_count++;\n            }\n        }\n\n        superlattice_count /= 2;\n\n        if (superlattice_count > 0) {\n            superlattice = true;\n        }\n\n        Eigen::ArrayXXd w0_SLdisorder;\n        Eigen::ArrayXXd w0_SLbarriers;\n\n        if (superlattice) {\n            // complain if there are multiple possibilities\n\n            if ((superlattice_count > 1) && (superlattice_UID == \"NULL\")) {\n                std::cout << \"ERROR:\" << std::endl;\n                std::cout << \"H5 file contains scattering information for \"\n                             \"multiple superlattices.\"\n                          << std::endl;\n                std::cout << \"Must provide the superlattice UID via the \"\n                             \"<superlattice> XML tag.\"\n                          << std::endl;\n                world.abort(1);\n            }\n\n            // if the user provided a UID, verify that corresponding data exists\n\n            if (superlattice_UID != \"NULL\") {\n                int UIDcount = 0;\n\n                for (std::size_t ngroup = 0; ngroup < subgroups.size();\n                     ngroup++) {\n                    if (subgroups.at(ngroup).find(superlattice_UID) !=\n                        std::string::npos) {\n                        UIDcount++;\n                    }\n                }\n\n                if (UIDcount != 2) {\n                    std::cout << \"ERROR:\" << std::endl;\n                    std::cout << \"H5 file does not contain any superlattice \"\n                                 \"data with provided UID \"\n                              << superlattice_UID << \".\" << std::endl;\n                    world.abort(1);\n                }\n            }\n\n            // load the scattering rates from the H5 file\n\n            bool UIDmatch = true;\n\n            for (std::size_t ngroup = 0; ngroup < subgroups.size(); ngroup++) {\n                bool contains_SLdisorder =\n                    (subgroups.at(ngroup).find(\"superlattice\") !=\n                     std::string::npos) &&\n                    (subgroups.at(ngroup).find(\"disorder\") !=\n                     std::string::npos);\n\n                bool contains_SLbarriers =\n                    (subgroups.at(ngroup).find(\"superlattice\") !=\n                     std::string::npos) &&\n                    (subgroups.at(ngroup).find(\"barriers\") !=\n                     std::string::npos);\n\n                if (superlattice_count > 1) {\n                    UIDmatch = (subgroups.at(ngroup).find(superlattice_UID) !=\n                                std::string::npos);\n                }\n\n                if (contains_SLdisorder && UIDmatch) {\n                    auto mysubgroup = alma::load_scattering_subgroup(\n                        hdf5_path.string().c_str(),\n                        subgroups.at(ngroup),\n                        world);\n                    w0_SLdisorder = mysubgroup.w0;\n                }\n\n                if (contains_SLbarriers && UIDmatch) {\n                    auto mysubgroup = alma::load_scattering_subgroup(\n                        hdf5_path.string().c_str(),\n                        subgroups.at(ngroup),\n                        world);\n                    w0_SLbarriers = mysubgroup.w0;\n                }\n            }\n        }\n\n        // Build list of temperature values\n        Eigen::VectorXd Tlist;\n\n        if (logsweep) {\n            Tlist = alma::logSpace(Tmin, Tmax, NT);\n        }\n\n        else {\n            Tlist.setLinSpaced(NT, Tmin, Tmax);\n        }\n\n        // Create output writer\n        std::stringstream outputbuffer;\n\n        // Write file header\n\n\n        outputbuffer << \"Temp[K],kappaRTA<\" << uvector(0) << \",\" << uvector(1)\n                     << \",\" << uvector(2) << \">[W/m-K]\";\n\n        if (fullBTE) {\n            outputbuffer << \",kappaBTE<\" << uvector(0) << \",\" << uvector(1)\n                         << \",\" << uvector(2) << \">[W/m-K]\";\n        }\n\n        outputbuffer << std::endl;\n\n        // RUN CALCULATIONS\n\n        std::cout << \"Running Tsweep for \" << mat_base << std::endl;\n\n        auto twoph_processes = alma::find_allowed_twoph(*grid, world);\n\n        // temperature-independent scattering rates\n        Eigen::ArrayXXd w_elastic;\n\n        if (superlattice) {\n            w_elastic = w0_SLbarriers.array() + w0_SLdisorder.array();\n        }\n        else {\n            w_elastic =\n                alma::calc_w0_twoph(*poscar, *grid, twoph_processes, world);\n        }\n\n        u_norm = uvector.array() / uvector.norm();\n\n        /// processes list\n        std::unordered_map<std::array<std::size_t, 3>, alma::Threeph_process>\n            emission_processes;\n        std::unordered_map<std::array<std::size_t, 3>, alma::Threeph_process>\n            absorption_processes;\n        std::unordered_map<std::pair<std::size_t, std::size_t>, double>\n            isotopic_processes;\n\n        if (fullBTE) {\n            std::cout << \"# Recalculating processes list in full BZ\\n\";\n            std::cout << \"# for symmetry reasons\\n\";\n\n            alma::nanos::get_fullBZ_processes(*grid,\n                                              *poscar,\n                                              AIFCfile,\n                                              emission_processes,\n                                              absorption_processes,\n                                              isotopic_processes,\n                                              world,\n                                              scalebroad_three);\n            std::cout << \"# Recalculation => DONE\" << std::endl;\n            std::cout.flush();\n        }\n\n        for (int nT = 0; nT < NT; nT++) {\n            double T = Tlist(nT);\n\n            std::cout << \" Processing \" << T << \" K (temperature \" << nT + 1\n                      << \" of \" << NT << \")\" << std::endl;\n\n            Eigen::ArrayXXd w3(\n                alma::calc_w0_threeph(*grid, *processes, T, world));\n            Eigen::ArrayXXd w(w3 + w_elastic);\n\n            double kappa_RTA = alma::nanos::calc_kappa_RTA(\n                *poscar, *grid, w, u_norm, system_name, limiting_length, T);\n\n            double kappa_BTE;\n\n            if (fullBTE) {\n                kappa_BTE = alma::nanos::calc_kappa_nanos(*poscar,\n                                                          *grid,\n                                                          *syms,\n                                                          emission_processes,\n                                                          absorption_processes,\n                                                          isotopic_processes,\n                                                          w,\n                                                          u_norm,\n                                                          system_name,\n                                                          limiting_length,\n                                                          T,\n                                                          fullBTE_iterative,\n                                                          world);\n            }\n\n            outputbuffer << T << \",\" << kappa_RTA;\n\n            if (fullBTE) {\n                outputbuffer << \",\" << kappa_BTE;\n            }\n\n            outputbuffer << std::endl;\n        } // END CALCULATIONS\n\n        // WRITE FILE\n\n        // go to the launch directory\n        boost::filesystem::current_path(launch_path);\n\n        // resolve output directory if AUTO is selected\n        if (target_directory.compare(\"AUTO\") == 0) {\n            target_directory = \"output/kappa_Tsweep\";\n        }\n\n        // create output directory if it doesn't exist yet\n        auto outputfolder = boost::filesystem::path(target_directory);\n\n        if (!(boost::filesystem::exists(outputfolder))) {\n            boost::filesystem::create_directories(outputfolder);\n        }\n\n        boost::filesystem::current_path(launch_path);\n\n        // resolve file name if AUTO selected\n\n        if (target_filename.compare(\"AUTO\") == 0) {\n            std::stringstream filenamebuilder;\n            filenamebuilder << mat_base << \"_\" << gridDensityA << \"_\"\n                            << gridDensityB << \"_\" << gridDensityC;\n\n            std::string lstring = std::to_string(limiting_length);\n            lstring.resize(7);\n\n            filenamebuilder << \"_\" << system_name << \"_L_\";\n            filenamebuilder << lstring;\n            filenamebuilder << \"_\" << uvector(0) << \",\" << uvector(1) << \",\"\n                            << uvector(2);\n\n            filenamebuilder << \"_\" << Tmin << \"_\" << Tmax;\n\n            filenamebuilder << \".Tsweep\";\n            target_filename = filenamebuilder.str();\n        }\n\n        // save file\n\n        std::cout << std::endl;\n        std::cout << \"Writing to file \" << target_filename << std::endl;\n        std::cout << \"in subdirectory \" << target_directory << std::endl;\n        std::cout << \"under root directory \" << launch_path << std::endl;\n\n        std::ofstream outputwriter;\n        outputwriter.open(\"./\" + target_directory + \"/\" + target_filename);\n        outputwriter << outputbuffer.str();\n        outputwriter.close();\n\n        std::cout << std::endl << \"[DONE.]\" << std::endl;\n\n        return 0;\n    }\n}\n", "meta": {"hexsha": "0b88ec7bbceeab8f82f3b416033e3bde09c60d87", "size": 21487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kappa_Tsweep_nanos.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/kappa_Tsweep_nanos.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/kappa_Tsweep_nanos.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": 35.2245901639, "max_line_length": 80, "alphanum_fraction": 0.4831758738, "num_tokens": 4817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.0316187690936814, "lm_q1q2_score": 0.011362651926365468}}
{"text": "/* \n * File:   auto_win_q.cpp\n * Author: root\n * \n * Created on February 10, 2010, 4:36 PM\n */\n\n#include <limits>\n#include <iostream>\n#include <map>\n#include <string>\n#include <cmath>\n\n\n\n//for random number generator\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"auto_win_q.h\"\n#include \"q_func_calc.h\"\n#include \"distance_measures.h\"\n#include \"BipartNj.h\"\n\n\nusing namespace std;\nusing namespace uqam_doc;\n\nusing uqam_doc::AutoWinQ;\nusing uqam_doc::qFuncCalc;\nusing uqam_doc::BipartNj;\n\n//give context msa and position to extract data himself\n//AutoWinQ::AutoWinQ(qFuncCalc& ctx, int win_pos) : ctx_(ctx) {\n\nAutoWinQ::AutoWinQ(qFuncCalc& ctx, int win_pos) {\n\n    ctx_ = &ctx;\n\n    win_pos_ = win_pos;\n\n    //\n\n    //a window has exactly the same types that its context\n    //not all sequences, could be filtered with ids_work\n    //using copy constructor\n    ident_all_ = ctx_->all_types_;\n\n\n    NB_GROUPS_ = 2;\n    //empty before.\n    //initialize group containers\n    //we are in constructor\n    v_1g_cumul_.resize(NB_GROUPS_, 0.0);\n    v_1g_nb_.resize(NB_GROUPS_, 0.0);\n    v_1g_inv_nb_.resize(NB_GROUPS_, 0.0);\n    v_1g_inv_prop_.resize(NB_GROUPS_, 0.0);\n    v_1g_.resize(NB_GROUPS_, 0.0);\n\n    //initialize group containers\n    vector<float> vd(NB_GROUPS_, 0.0);\n    d_2g_cumul_.resize(NB_GROUPS_, vd);\n    d_2g_nb_.resize(NB_GROUPS_, vd);\n    d_2g_inv_nb_.resize(NB_GROUPS_, vd);\n    d_2g_inv_prop_.resize(NB_GROUPS_, vd);\n    d_2g_.resize(NB_GROUPS_, vd);\n\n    //differences\n    new_v_1g_cumul_.resize(NB_GROUPS_, 0.0);\n    new_v_1g_nb_.resize(NB_GROUPS_, 0.0);\n    new_v_1g_inv_nb_.resize(NB_GROUPS_, 0.0);\n    new_v_1g_inv_prop_.resize(NB_GROUPS_, 0.0);\n    new_v_1g_.resize(NB_GROUPS_, 0.0);\n\n    new_d_2g_cumul_.resize(NB_GROUPS_, vd);\n    new_d_2g_nb_.resize(NB_GROUPS_, vd);\n    new_d_2g_inv_nb_.resize(NB_GROUPS_, vd);\n    new_d_2g_inv_prop_.resize(NB_GROUPS_, vd);\n    new_d_2g_.resize(NB_GROUPS_, vd);\n\n    //and by functions\n    NB_FUNC_ = 8;\n    //initialize functions\n    q_func_.resize(NB_FUNC_, 0.0);\n    q_p_val_inf_.resize(NB_FUNC_, 0.0);\n    q_p_val_sup_.resize(NB_FUNC_, 0.0);\n    //differences\n    new_q_func_.resize(NB_FUNC_, 0.0);\n    //\n    NB_RANDOM_SEEDS_ = 100;\n\n    //optimize context function\n    q_func_opt_max_idx_ = ctx_->appl_data_->q_func_opt_max_idx_;\n    q_func_opt_max_val_ = -numeric_limits<float>::max();\n    //\n    simple_window_ = NULL;\n    best_window_ = NULL;\n    //results\n    uncalculable_ = false;\n\n    //calculate gap proportion\n    MAX_GAP_PROPORTION_ = 1;\n    //gap_proportion_ = 0;\n    gap_proportion_ = calculateGapProportion();\n    //cout << \"gap proporiton: \" << gap_proportion_ << endl;\n\n\n\n    if (gap_proportion_ >= MAX_GAP_PROPORTION_) {\n        uncalculable_ = true;\n    }\n\n}\n\n//copy constructor\n//AutoWinQ::AutoWinQ(qFuncCalc& ctx, AutoWinQ& orig): ctx_(ctx) {\n\nAutoWinQ::AutoWinQ(qFuncCalc& ctx, AutoWinQ& orig) {\n    //cout << \"=====================: copy constructor \" << endl;\n\n    //cout << \"ident_grouped : size \" << orig.ident_grouped_.size() << endl;\n\n    ctx_ = orig.ctx_;\n\n    win_pos_ = orig.win_pos_;\n\n    ident_all_ = orig.ident_all_;\n    ident_grouped_ = orig.ident_grouped_;\n\n    NB_GROUPS_ = orig.NB_GROUPS_;\n\n    //nb positions valides\n    v_1g_nb_ = orig.v_1g_nb_;\n    d_2g_nb_ = orig.d_2g_nb_;\n    v_all_nb_ = orig.v_all_nb_;\n\n    //nb positions invalides\n    v_1g_inv_nb_ = orig.v_1g_inv_nb_;\n    d_2g_inv_nb_ = orig.d_2g_inv_nb_;\n    v_all_inv_nb_ = orig.v_all_nb_;\n\n    //proportion invalides\n    v_1g_inv_prop_ = orig.v_1g_inv_prop_;\n    d_2g_inv_prop_ = orig.d_2g_inv_prop_;\n    v_all_inv_prop_ = orig.v_all_inv_prop_;\n\n    //valeurs finales à transformer en fonctions qui scalent\n    v_1g_ = orig.v_1g_;\n    d_2g_ = orig.d_2g_;\n    v_all_ = orig.v_all_;\n\n    NB_FUNC_ = orig.NB_FUNC_;\n\n    //\n    q_func_ = orig.q_func_;\n    //cout << \"q_func4: \" << q_func_[4] << endl;\n\n\n    q_p_val_inf_ = orig.q_p_val_inf_;\n    q_p_val_sup_ = orig.q_p_val_sup_;\n\n    //\n    //q_func_opt_max_val_;\n    //q_func_opt_max_idx_;\n\n\n    //copy(orig.ident_grouped_.begin(), orig.ident_grouped_.end(), this->ident_grouped_.begin());\n    //\n    simple_window_ = NULL;\n    best_window_ = NULL;\n\n    MAX_GAP_PROPORTION_ = orig.MAX_GAP_PROPORTION_;\n    gap_proportion_ = orig.gap_proportion_;\n\n    //cout << \"ident_grouped : size \" << ident_grouped_.size() << endl;\n\n\n}\n\n//virtual destructor\n\nAutoWinQ::~AutoWinQ() {\n    ident_all_.clear();\n\n    if (simple_window_ != NULL) {\n        delete simple_window_;\n    }\n\n    if (best_window_ != NULL) {\n       delete best_window_;\n        \n    }\n\n\n}\n\nfloat AutoWinQ::calculateGapProportion() {\n\n    float gap_proportion = 0;\n\n    set<string>::iterator it1 = ident_all_.begin();\n    while (it1 != ident_all_.end()) {\n\n        //cout << \"*it1: \" << *it1 << endl;\n        //cout << \"ctx_->win_l_: \" << ctx_->win_l_ << endl;\n\n\n        string seq = ctx_->align_mult_types_[*it1].substr(win_pos_, ctx_->win_l_);\n        for (int i = 0; i < seq.length(); i++) {\n            if (seq[i] == '-') {\n                gap_proportion++;\n            }\n        }\n\n        ++it1;\n    }\n\n    gap_proportion /= (ctx_->win_l_ * ctx_->align_mult_types_.size());\n\n    return gap_proportion;\n}\n\n//calculate distance matrix\n\nvoid AutoWinQ::calculateDistMatrix() {\n\n    //map< string, map <string, DistAtom > >  dmap;\n    //DistAtom da = DistAtom(0,0,0,0.0);\n    //dmap[\"a\"][\"b\"]=da;\n\n    set<string>::iterator it1 = ident_all_.begin();\n    while (it1 != ident_all_.end()) {\n        set<string>::iterator it2 = ident_all_.begin();\n        while (it2 != ident_all_.end()) {\n\n            if (it2 != it1) {\n              //verify dist matrix\n            //string seq_a_test = ctx_.align_mult_types_[*it1].substr(win_pos_, ctx_.win_l_);\n            //string seq_b_test = ctx_.align_mult_types_[*it2].substr(win_pos_, ctx_.win_l_);\n            //cout << \"seq_a_test: \" << seq_a_test << endl;\n            DistAtom dist = ctx_->dist_calc_->dist_2seq(ctx_->align_mult_types_[*it1].substr(win_pos_, ctx_->win_l_), ctx_->align_mult_types_[*it2].substr(win_pos_, ctx_->win_l_));\n            //symetric matrix\n            dist_matrix_[*it1][*it2] = dist;\n            dist_matrix_[*it2][*it1] = dist_matrix_[*it1][*it2];  \n            } else {\n               dist_matrix_[*it1][*it2] = DistAtom(0,0,0,0);\n            }\n            \n\n            ++it2;\n        }\n        ++it1;\n    }\n\n\n}\n\n//Alix bipartitions of the distance matrix\nvoid AutoWinQ::calculateNjBipartitions() {\n\n    BipartNj *rb = new BipartNj(dist_matrix_);\n    cout << \"dist_matrix_.size(): \" << dist_matrix_.size() << endl;\n\n\n    //rb.lectureFichier();\n    //outputDistanceMatrix();\n\n    rb->recherche_bipartition();\n    rb->calculateBipartVector();\n\n    //rb->outputBipartVector();\n\n     cout << \"----------------calculateDistMatrix size 1: \" << bipart_matrix_.size() << endl;\n     bipart_matrix_.clear();\n\n     rb->getBipartVector(&bipart_matrix_);\n\n     cout << \"---------------calculateDistMatrix size 2: \" << bipart_matrix_.size() << endl;\n\n     //cout << \"--bla: \" << endl;\n\n    delete(rb);\n    //cout << \"--blaxxx: \" << endl;\n\n\n}\n\n\n//update distance matrix one step\n\nvoid AutoWinQ::updateDistMatrixOneStep() {\n\n    //map< string, map <string, DistAtom > >  dmap;\n    //DistAtom da = DistAtom(0,0,0,0.0);\n    //dmap[\"a\"][\"b\"]=da;\n\n    //advance position\n    win_pos_ += ctx_->appl_data_->win_step_;\n    calculateDistMatrix();\n}\n\nvoid AutoWinQ::outputDistanceMatrix() {\n\n    //output distance matrix\n    cout << \"outputDistanceMatrix(): \" << endl;\n    set<string>::iterator it1 = ident_all_.begin();\n    while (it1 != ident_all_.end()) {\n        set<string>::iterator it2 = ident_all_.begin();\n        while (it2 != ident_all_.end()) {\n            DistAtom da = dist_matrix_[*it1][*it2];\n            cout << *it1 << \"-\" << *it2 << \"= \" << da.real_dist_\n                    << \" seq_a: \" << ctx_->align_mult_types_[*it1].substr(win_pos_, ctx_->win_l_)\n                    << \" seq_b: \" << ctx_->align_mult_types_[*it2].substr(win_pos_, ctx_->win_l_)\n                    << endl;\n            ++it2;\n        }\n        ++it1;\n    }\n\n\n}\n\nvoid AutoWinQ::outputBipartMatrix() {\n\n    //vector< vector <set<string> > >\n\n    cout << \"outputBipartMatrix(): \" << endl;\n    for (int i = 0; i < bipart_matrix_.size(); i++) {\n        cout << \"outputBipartMatrix size: \" << bipart_matrix_.size() << endl;\n        cout << \"bipartition: \" << i << endl;\n        vector <set<string> > one_bipart = bipart_matrix_[i];\n        for (int j = 0; j < one_bipart.size(); j++) {\n            cout << \"  group: \" << j << endl;\n\n            set<string> one_group = one_bipart[j];\n            set<string>::iterator it1 = one_group.begin();\n            while (it1 != one_group.end()) {\n                cout << \"    ident: \" << *it1 << endl;\n                ++it1;\n            }\n\n        }\n\n    }\n\n\n}\n\nvoid AutoWinQ::outputGroupings(ostream & os) {\n\n    //output groupings\n    string type_ident = \"*\";\n\n    os << \"outputGroupings():\" << endl;\n    for (int i = 0; i < NB_GROUPS_; i++) {\n        os << \"group: \" << i << endl;\n        for (set<string>::iterator it = ident_grouped_[i].begin();\n                it != ident_grouped_[i].end();\n                ++it) {\n\n            if (ctx_->x_ident_.find(*it) != ctx_->x_ident_.end()) {\n                type_ident = \"*\";\n            } else {\n                type_ident = \" \";\n            }\n\n            os << type_ident << \" \" << *it\n                    << \" \" << ctx_->align_mult_types_[*it].substr(win_pos_, ctx_->win_l_)\n                    << endl;\n\n\n\n        }\n\n    }\n\n}\n\nvoid AutoWinQ::outputGroupingsToFiles(ostream& os_a, ostream & os_b) {\n\n\n\n    //output groupings\n    string type_ident = \"*\";\n\n\n    for (int i = 0; i < NB_GROUPS_; i++) {\n\n\n        if (i == 1) {\n\n        }\n\n        for (set<string>::iterator it = ident_grouped_[i].begin();\n                it != ident_grouped_[i].end();\n                ++it) {\n\n            if (ctx_->x_ident_.find(*it) != ctx_->x_ident_.end()) {\n                type_ident = \"*\";\n            } else {\n                type_ident = \" \";\n            }\n\n            if (i == 0) {\n                os_a << type_ident << \" \" << *it\n                        //<< \" \" << ctx_->align_mult_types_[*it].substr(win_pos_, ctx_->win_l_)\n                        << endl;\n\n            } else if (i == 1) {\n                os_b << type_ident << \" \" << *it\n                        //<< \" \" << ctx_->align_mult_types_[*it].substr(win_pos_, ctx_->win_l_)\n                        << endl;\n\n            }\n\n\n\n\n        }\n\n    }\n\n}\n\nfloat AutoWinQ::randIndex() {\n\n    float rand_index;\n    //calculated each time, no need to reinitialize\n    int calc_set[2];\n    int file_set[2];\n\n    int a, b, c, d;\n    //swap one group\n    int g0;\n\n    //swap groups\n    //for (g0 = 0; g0 < 2; g0++) {\n    g0 = 1;\n    rand_index = 0;\n    a = 0;\n    b = 0;\n    c = 0;\n    d = 0;\n\n\n    //for every pair of identifiers\n    set<string>::iterator it1, it2;\n    it1 = ident_all_.begin();\n    while (it1 != --(ident_all_.end())) {\n        it2 = it1;\n        it2++;\n\n        while (it2 != ident_all_.end()) {\n\n            // cout << \" \" << *it1\n            //         << \" \" << *it2;\n\n\n            //find calculated set\n            // *it1 in group 0\n            if (ident_grouped_[g0].find(*it1) != ident_grouped_[g0].end()) {\n                calc_set[0] = 0;\n            } else { // *it1 in group 1\n                calc_set[0] = 1;\n            }\n\n            // *it2 in group 0\n            if (ident_grouped_[g0].find(*it2) != ident_grouped_[g0].end()) {\n                calc_set[1] = 0;\n            } else { // *it1 in group 1\n                calc_set[1] = 1;\n            }\n\n            //find file set\n            // *it1 in group 0 (X)\n            if (ctx_-> x_ident_.find(*it1) != ctx_->x_ident_.end()) {\n                file_set[0] = 0;\n            } else { // *it1 in group 1\n                file_set[0] = 1;\n            }\n\n            // *it2 in group 0 (X)\n            if (ctx_->x_ident_.find(*it2) != ctx_->x_ident_.end()) {\n                file_set[1] = 0;\n            } else { // *it2 in group 1\n                file_set[1] = 1;\n            }\n\n\n            if (calc_set[0] == calc_set[1]) {\n                //same set in X (Rand wikipedia)\n                if (file_set[0] == file_set[1]) {\n                    //same set in Y (Rand wikipedia)\n                    //cout << \" a: same X, same Y\";\n                    a++;\n                } else {\n                    //different set in Y (Rand wikipedia)\n                    //cout << \" c: same X, different Y\";\n                    c++;\n                }\n            } else {\n                //different sets in X (Rand wikipedia)\n                if (file_set[0] == file_set[1]) {\n                    //same set in Y (Rand wikipedia)\n                    //cout << \" d: different X, same Y\";\n                    d++;\n                } else {\n                    //different set in Y (Rand wikipedia)\n                    //cout << \" b: different X, different Y\";\n                    b++;\n                }\n\n            }\n            //cout << endl;\n\n            ++it2;\n        }\n        ++it1;\n    }\n\n    rand_index = max(rand_index, (float(a + b) / float(a + b + c + d)));\n\n\n    /*\n    cout << \"a: \" << a\n            << \",b: \" << b\n            << \",c: \" << c\n            << \",d: \" << d\n            << \",float(a + b): \" << float(a + b)\n            << \",float(a + b + c + d): \" << float(a + b + c + d)\n            << \",rand_index: \" << rand_index\n            << endl;\n  */\n\n    //}\n\n    return rand_index;\n\n}\n\nfloat AutoWinQ::adjustedRandIndex() {\n\n    float adjusted_rand_index;\n    //calculated each time, no need to reinitialize\n    int calc_set[2];\n    int file_set[2];\n\n    int a, b, c, d;\n    //swap one group\n    int g0;\n\n    //swap groups\n    //for (g0 = 0; g0 < 2; g0++) {\n    g0 = 1;\n    adjusted_rand_index = 0;\n\n    a = 0;\n    b = 0;\n    c = 0;\n    d = 0;\n\n\n    //for every pair of identifiers\n    set<string>::iterator it1, it2;\n    it1 = ident_all_.begin();\n    while (it1 != --(ident_all_.end())) {\n        it2 = it1;\n        it2++;\n\n        while (it2 != ident_all_.end()) {\n\n            //cout << \" \" << *it1\n            //        << \" \" << *it2;\n\n\n            //find calculated set\n            // *it1 in group 0\n            if (ident_grouped_[g0].find(*it1) != ident_grouped_[g0].end()) {\n                calc_set[0] = 0;\n            } else { // *it1 in group 1\n                calc_set[0] = 1;\n            }\n\n            // *it2 in group 0\n            if (ident_grouped_[g0].find(*it2) != ident_grouped_[g0].end()) {\n                calc_set[1] = 0;\n            } else { // *it1 in group 1\n                calc_set[1] = 1;\n            }\n\n            //find file set\n            // *it1 in group 0 (X)\n            if (ctx_-> x_ident_.find(*it1) != ctx_->x_ident_.end()) {\n                file_set[0] = 0;\n            } else { // *it1 in group 1\n                file_set[0] = 1;\n            }\n\n            // *it2 in group 0 (X)\n            if (ctx_->x_ident_.find(*it2) != ctx_->x_ident_.end()) {\n                file_set[1] = 0;\n            } else { // *it2 in group 1\n                file_set[1] = 1;\n            }\n\n\n            if (calc_set[0] == calc_set[1]) {\n                //same group in U\n                if (file_set[0] == file_set[1]) {\n                    //same group in V\n                    //cout << \" a: same U, same V\";\n                    a++;\n                } else {\n                    //different set in V\n                    //cout << \" b: same U, different V\";\n                    b++;\n                }\n            } else {\n                //different sets in U\n                if (file_set[0] == file_set[1]) {\n                    //same set in V\n                    //cout << \" c: different U, same V\";\n                    c++;\n                } else {\n                    //different set in V\n                    //cout << \" d: different U, different V\";\n                    d++;\n                }\n\n            }\n            //cout << endl;\n\n            ++it2;\n        }\n        ++it1;\n    }\n\n    //n_2 = binom(n,2)\n    float n_2 = a + b + c + d;\n    float cor = ((a + b) * (a + c) + (c + d) * (b + d));\n\n    float num = n_2 * (a + d) - cor;\n    float den = (n_2 * n_2) - cor;\n    float ari_val = num / den;\n\n    adjusted_rand_index = ari_val;\n\n\n    /*\n    cout << \"a: \" << a\n            << \",b: \" << b\n            << \",c: \" << c\n            << \",d: \" << d\n            << \",cor: \" << cor\n            << \",num: \" << num\n            << \",den: \" << den\n            << \",adjusted_rand_index: \" << adjusted_rand_index\n            << endl;\n    */\n\n    //}\n\n    return adjusted_rand_index;\n\n}\n\nfloat AutoWinQ::groupHamIndex() {\n\n    float group_ham_idx;\n    string g_local;\n    string g_context;\n\n\n\n    group_ham_idx = 0;\n\n    //for every pair of identifiers\n    set<string>::iterator it, it1, it2;\n\n    it = ident_all_.begin();\n    while (it != ident_all_.end()) {\n\n        //local in group 0\n        if (ident_grouped_[0].find(*it) != ident_grouped_[0].end()) {\n            g_local.push_back('0');\n        } else { // local in group 1\n            g_local.push_back('1');\n        }\n\n        //context group\n        //local in group 0\n        if (ctx_-> x_ident_.find(*it) != ctx_->x_ident_.end()) {\n            g_context.push_back('0');\n        } else { // local in group 1\n            g_context.push_back('1');\n        }\n\n\n        ++it;\n    }\n\n\n    Hamming hm;\n\n    group_ham_idx = hm.dist_2seq(g_local, g_context).real_dist_;\n\n    //invert characters\n    for (int i = 0; i < g_local.length(); i++) {\n        if (g_local[i] == '0') {\n            g_local[i] = '1';\n\n        } else {\n            g_local[i] = '0';\n        }\n\n    }\n\n    group_ham_idx = min(group_ham_idx, hm.dist_2seq(g_local, g_context).real_dist_);\n\n    //cout << \"group_ham_idx, dist: \" << group_ham_idx << \"g_local: \" << g_local << \", context: \" << g_context << endl;\n\n    return group_ham_idx;\n\n}\n\nvoid AutoWinQ::test() {\n\n    outputDistanceMatrix();\n    outputGroupings(cout);\n    /*\n    for (int i = 0; i < ident_all_.size(); i++) {\n        for (int j = 0; j < ident_all_.size(); j++) {\n            DistAtom da = dist_matrix_[ident_all_[i]][ident_all_[j]];\n            cout << ident_all_[i] << \"-\" << ident_all_[j] << \"= \" << da.real_dist_ << endl;\n        }\n    }\n     */\n\n    //output groupings\n    /*\n    for (int i = 0; i < NB_GROUPS_; i++) {\n        cout << \"group: \" << i << endl;\n        for (int j = 0; j < ident_grouped_[i].size(); j++) {\n            cout << \"ident: \" << ident_grouped_[i][j] << endl;\n        }\n\n    }\n     */\n}\n\n//verify that each group contains more than one element\n\nvoid AutoWinQ::generateRandomInitGrouping() {\n\n    //initialize\n    ident_grouped_.clear();\n    ident_grouped_.reserve(NB_GROUPS_);\n\n    set<string> ss;\n    //vs.clear();\n    for (int i = 0; i < NB_GROUPS_; i++) {\n        ident_grouped_.push_back(ss);\n    }\n    //randomly distribute identifiers\n    set<string>::iterator it1 = ident_all_.begin();\n    while (it1 != ident_all_.end()) {\n        //random_integer = (rand()%10)+1;  1-10;\n        //random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));\n\n\n    \t///int rand_group_id = (int) ((float) rand() / ((float) RAND_MAX + 1) * 2);\n\n    \t//distribution, numbers between 0 and 1\n    \tboost::uniform_int<> dist(0, 1);\n    \t//use global generator with this distribution\n  \t    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(ctx_->appl_data_->random_number_gen_, dist);\n\n  \t    int rand_group_id = die() ;\n\n\n        ident_grouped_[rand_group_id].insert(*it1);\n        ++it1;\n    }\n\n    //not-empty groups\n    bool empty_groups = false;\n    for (int i = 0; i < NB_GROUPS_; i++) {\n        if (ident_grouped_[i].size() < 2) {\n            empty_groups = true;\n            //cout << \"emptyes groups\" << endl;\n        }\n    }\n\n    //terminal recursion to verify non-emptyness\n    //always possible\n    if (empty_groups) {\n        generateRandomInitGrouping();\n    }\n    //outputGroupings();\n}\n\nvoid AutoWinQ::getContextGrouping() {\n\n    //initialize\n    ident_grouped_.clear();\n    ident_grouped_.reserve(NB_GROUPS_);\n\n    set<string> ss;\n    //vs.clear();\n    for (int i = 0; i < NB_GROUPS_; i++) {\n        ident_grouped_.push_back(ss);\n    }\n\n\n    //same distribution of identifiers as in context\n    // X -> group 0\n    set<string>::iterator it0 = ctx_->x_ident_.begin();\n    while (it0 != ctx_->x_ident_.end()) {\n        ident_grouped_[0].insert(*it0);\n        ++it0;\n    }\n\n    // Y -> group 1\n    set<string>::iterator it1 = ctx_->y_ident_.begin();\n    while (it1 != ctx_->y_ident_.end()) {\n        ident_grouped_[1].insert(*it1);\n        ++it1;\n    }\n\n   // outputGroupings(cout);\n\n}\n\nvoid AutoWinQ::calcQRes() {\n\n    //cout << \"nx: \" << ident_grouped_[0].size() << endl;\n    //cout << \"ny: \" << ident_grouped_[1].size() << endl;\n\n    //vX, vY\n    //update running totals\n    for (int g = 0; g < NB_GROUPS_; g++) {\n\n\n        //    for (int i = 0; i < (ident_grouped_[g].size() - 1); i++) {\n        //       for (int j = (i + 1); j < ident_grouped_[g].size(); j++) {\n\n        //initialize group elements\n        v_1g_inv_nb_[g] = 0.0; //cumulative\n        v_1g_cumul_[g] = 0.0; //cumulative\n        v_1g_nb_[g] = 0.0; //cumulative\n        //non cumulative elements\n        //initialization optional (they will be overriten)\n        v_1g_[g] = 0.0;\n        v_1g_inv_prop_[g] = 0.0;\n\n        set<string>::iterator it1, it2;\n        it1 = ident_grouped_[g].begin();\n        while (it1 != --(ident_grouped_[g].end())) {\n            it2 = it1;\n            it2++;\n\n            while (it2 != ident_grouped_[g].end()) {\n\n                //skip same elements\n                if (it2 == it1) {\n                    // cout << \"it2 == it1\" << *it2 << \"-\" << *it1 << endl;\n                }\n                //float v_1g_elem = dist_matrix_[ident_grouped_[g][i]][ident_grouped_[g][j]].real_dist_;\n                float v_1g_elem = dist_matrix_[*it1][*it2].real_dist_;\n\n                if (v_1g_elem != numeric_limits<float>::max()) {\n                    //count it\n                    v_1g_nb_[g]++;\n                    //add value\n                    //v_1g_cumul_[g] += pow(v_1g_elem, 2.0);\n                    v_1g_cumul_[g] += v_1g_elem *v_1g_elem;\n                } else {\n                    //count invalid\n                    v_1g_inv_nb_[g]++;\n                }\n\n                ++it2;\n            }\n            ++it1;\n        }\n\n\n\n\n        //scale to valid number of elements\n        v_1g_[g] = v_1g_cumul_[g] / v_1g_nb_[g];\n        //proportion of invalid positions\n        v_1g_inv_prop_[g] = v_1g_inv_nb_[g] / (v_1g_nb_[g] + v_1g_inv_nb_[g]);\n\n        //cout << \"v_x: \" << v_1g_nb_[g] << \"v_x formula: \" << (ident_grouped_[g].size() * (ident_grouped_[g].size() - 1) / 2.0) << endl;\n    }\n\n\n\n\n\n    //dXY\n\n    //update running totals\n    for (int g1 = 0; g1 < (NB_GROUPS_ - 1); g1++) {\n        for (int g2 = (g1 + 1); g2 < NB_GROUPS_; g2++) {\n            //initialize group elements\n            d_2g_inv_nb_[g1][g2] = 0.0; //cumulative\n            d_2g_cumul_[g1][g2] = 0.0; //cumulative\n            d_2g_nb_[g1][g2] = 0.0; //cumulative\n            //non cumulative elements\n            //initialization optional (they will be overriten)\n            d_2g_[g1][g2] = 0.0;\n            d_2g_inv_prop_[g1][g2] = 0.0;\n\n            // for (int i = 0; i < ident_grouped_[g1].size(); i++) {\n            //    for (int j = 0; j < ident_grouped_[g2].size(); j++) {\n\n            for (set<string>::iterator it1 = ident_grouped_[g1].begin();\n                    it1 != ident_grouped_[g1].end();\n                    ++it1) {\n                for (set<string>::iterator it2 = ident_grouped_[g2].begin();\n                        it2 != ident_grouped_[g2].end();\n                        ++it2) {\n\n                    //      float d_2g_elem = dist_matrix_[ident_grouped_[g1][i]][ident_grouped_[g2][j]].real_dist_;\n                    float d_2g_elem = dist_matrix_[*it1][*it2].real_dist_;\n\n                    if (d_2g_elem != numeric_limits<float>::max()) {\n                        //count it\n                        d_2g_nb_[g1][g2]++;\n                        //add value\n                        //d_2g_cumul_[g1][g2] += pow(d_2g_elem, 2.0);\n                        d_2g_cumul_[g1][g2] += d_2g_elem * d_2g_elem;\n                    } else {\n                        //count invalid\n                        d_2g_inv_nb_[g1][g2]++;\n                    }\n\n\n\n                }\n            }\n\n\n            //scale to valid number of elements\n            d_2g_[g1][g2] = d_2g_cumul_[g1][g2] / d_2g_nb_[g1][g2];\n            //proportion of invalid positions\n            d_2g_inv_prop_[g1][g2] = d_2g_inv_nb_[g1][g2] / (d_2g_nb_[g1][g2] + d_2g_inv_nb_[g1][g2]);\n\n            // cout << \"d_xy: \" << d_2g_nb_[g1][g2] << \"d_xy formula: \" << (ident_grouped_[g1].size() * ident_grouped_[g2].size()) << endl;\n\n            //symetric results\n            d_2g_inv_nb_[g2][g1] = d_2g_inv_nb_[g1][g2]; //cumulative\n            d_2g_cumul_[g2][g1] = d_2g_cumul_[g1][g2]; //cumulative\n            d_2g_nb_[g2][g1] = d_2g_nb_[g1][g2]; //cumulative\n            //non cumulative elements\n            //initialization optional (they will be overriten)\n            d_2g_[g2][g1] = d_2g_[g1][g2];\n            d_2g_inv_prop_[g2][g1] = d_2g_inv_prop_[g1][g2];\n\n        }\n\n    }\n\n    //debug\n    //cout << \"d_2d_[0][1] \" << d_2g_[0][1] << endl;\n    //cout << \"v_1g_[0] \" << v_1g_[0] << endl;\n    //cout << \"v_1g_[1] \" << v_1g_[1] << endl;\n\n\n\n\n    //vAll\n    //initialize group elements\n     v_all_inv_nb_ = 0.0; //cumulative\n     v_all_cumul_ = 0.0; //cumulative\n     v_all_nb_ = 0.0; //cumulative\n     //non cumulative elements\n     //initialization optional (they will be overriten)\n     v_all_ = 0.0;\n     v_all_inv_prop_ = 0.0;\n\n\n     set<string>::iterator it1, it2;\n     it1 = ident_all_.begin();\n      while (it1 != --(ident_all_.end())) {\n                it2 = it1;\n                it2++;\n\n                while (it2 != ident_all_.end()) {\n\n                    //skip same elements\n                    if (it2 == it1) {\n                        // cout << \"it2 == it1\" << *it2 << \"-\" << *it1 << endl;\n                    }\n\n                    float v_all_elem = dist_matrix_[*it1][*it2].real_dist_;\n\n                    if (v_all_elem != numeric_limits<float>::max()) {\n                        //count it\n                        v_all_nb_++;\n                        //add value\n                        v_all_cumul_ += v_all_elem * v_all_elem;\n                    } else {\n                        //count invalid\n                        v_all_inv_nb_++;\n                    }\n\n                    ++it2;\n                }\n                ++it1;\n            }\n            //scale to valid number of elements\n            v_all_ = v_all_cumul_ / v_all_nb_;\n            //proportion of invalid positions\n            v_all_inv_prop_ = v_all_inv_nb_ / (v_all_nb_ + v_all_inv_nb_);\n\n\n\n\n\n    //recalculate all functions\n    //no need to reinitialize\n\n    //reinitialize functions\n    q_func_.resize(NB_FUNC_, 0.0);\n\n    q_func_[0] = log(1 + d_2g_[0][1] - v_1g_[0]);\n    q_func_[1] = d_2g_[0][1] - v_1g_[0];\n    q_func_[2] = d_2g_[0][1] - v_1g_[1];\n    q_func_[3] = 2 * d_2g_[0][1] - v_1g_[0] - v_1g_[1];\n    q_func_[4] = d_2g_[0][1];\n    q_func_[5] = abs(v_1g_[0] - v_1g_[1]); ///// d_2g_[0][1]\n    q_func_[6] = abs(v_1g_[0] / v_1g_[1]); ///// d_2g_[0][1]\n    \n    //q_func_[7] = 0; //v_all_;\n    //q_func_[6] = fabs(v_1g_[0] - v_1g_[1]);\n    //q_func_[6] = abs ( log(v_1g_[0]) - log(v_1g_[1]))  ; ///// d_2g_[0][1]\n     \n    \n\n\n}\n\nvoid AutoWinQ::testOneCycleTransfers() {\n\n    string cand_ident;\n    //transfer identifiers group 0 -> 1\n\n    float dist_cand_new_source_cumul;\n    float dist_cand_new_source_cumul_inv_nb;\n\n    float dist_cand_old_dest_cumul;\n    float dist_cand_old_dest_cumul_inv_nb;\n\n    int g0 = 1;\n    int g1 = 0;\n    int cycle_transfered = 0;\n    int nb_null_cycles = 0;\n\n    do {\n        cycle_transfered = 0;\n        int tmp = g0;\n        g0 = g1;\n        g1 = tmp;\n\n        set<string>::iterator it1, it2;\n        it1 = ident_grouped_[g0].begin();\n        while (it1 != ident_grouped_[g0].end()) {\n            cand_ident = *it1;\n\n            //cout << \"candidate: \" << cand_ident << endl;\n\n            //calculate candidate -> new_source\n            dist_cand_new_source_cumul = 0;\n            dist_cand_new_source_cumul_inv_nb = 0;\n            it2 = ident_grouped_[g0].begin();\n            while (it2 != ident_grouped_[g0].end()) {\n                if (it2 != it1) {\n                    //cout << \"               \" << \"---------->\" << *it2 << endl;\n                    float v_1g_elem = dist_matrix_[*it1][*it2].real_dist_;\n\n                    if (v_1g_elem != numeric_limits<float>::max()) {\n                        //add value\n                        dist_cand_new_source_cumul += pow(v_1g_elem, 2);\n                    } else {\n                        //count invalid\n                        dist_cand_new_source_cumul_inv_nb++;\n                    }\n\n                }\n                ++it2;\n            }\n\n            //calculate candidate -> old_dest\n            dist_cand_old_dest_cumul = 0;\n            dist_cand_old_dest_cumul_inv_nb = 0;\n            it2 = ident_grouped_[g1].begin();\n            while (it2 != ident_grouped_[g1].end()) {\n                // cout << \"               \" << \"---------->\" << *it2 << endl;\n                float d_2g_elem = dist_matrix_[*it1][*it2].real_dist_;\n\n                if (d_2g_elem != numeric_limits<float>::max()) {\n                    //dist_cand_old_dest_cumul += pow(d_2g_elem, 2.0);\n                    dist_cand_old_dest_cumul += d_2g_elem*d_2g_elem;\n                } else {\n                    //count invalid\n                    dist_cand_old_dest_cumul_inv_nb++;\n                }\n\n                ++it2;\n            }\n\n\n\n            //calculate differences\n            new_v_1g_cumul_[g0] = v_1g_cumul_[g0] - dist_cand_new_source_cumul;\n            //we do not substract invalid positions (they do not move)\n            new_v_1g_nb_[g0] = v_1g_nb_[g0] - (ident_grouped_[g0].size() - 1 - dist_cand_new_source_cumul_inv_nb);\n            //invalid positions move\n            new_v_1g_inv_nb_[g0] = v_1g_inv_nb_[g0] - dist_cand_new_source_cumul_inv_nb;\n            //update\n            new_v_1g_[g0] = new_v_1g_cumul_[g0] / new_v_1g_nb_[g0];\n            new_v_1g_inv_prop_[g0] = new_v_1g_inv_nb_[g0] / (new_v_1g_nb_[g0] + new_v_1g_inv_nb_[g0]);\n\n            //\n            new_v_1g_cumul_[g1] = v_1g_cumul_[g1] + dist_cand_old_dest_cumul;\n            //we do not add invalid positions (they do not move)\n            new_v_1g_nb_[g1] = v_1g_nb_[g1] + (ident_grouped_[g1].size() - dist_cand_old_dest_cumul_inv_nb);\n            //invalid positions move\n            new_v_1g_inv_nb_[g1] = v_1g_inv_nb_[g1] + dist_cand_old_dest_cumul_inv_nb;\n            //update\n            new_v_1g_[g1] = new_v_1g_cumul_[g1] / new_v_1g_nb_[g1];\n            new_v_1g_inv_prop_[g1] = new_v_1g_inv_nb_[g1] / (new_v_1g_nb_[g1] + new_v_1g_inv_nb_[g1]);\n\n\n\n            //\n            new_d_2g_cumul_[g0][g1] = d_2g_cumul_[g0][g1] - dist_cand_old_dest_cumul + dist_cand_new_source_cumul;\n            //we do not add invalid positions (they do not move)\n            new_d_2g_nb_[g0][g1] = d_2g_nb_[g0][g1] -(ident_grouped_[g1].size() - dist_cand_old_dest_cumul_inv_nb)\n                    + (ident_grouped_[g0].size() - 1 - dist_cand_new_source_cumul_inv_nb);\n            //invalid positions move\n            new_d_2g_inv_nb_[g0][g1] = d_2g_inv_nb_[g0][g1] - dist_cand_old_dest_cumul_inv_nb + dist_cand_new_source_cumul_inv_nb;\n            //update\n            new_d_2g_[g0][g1] = new_d_2g_cumul_[g0][g1] / new_d_2g_nb_[g0][g1];\n            new_d_2g_inv_prop_[g0][g1] = new_d_2g_inv_nb_[g0][g1] / (new_d_2g_nb_[g0][g1] + new_d_2g_inv_nb_[g0][g1]);\n            //symetric results\n            new_d_2g_cumul_[g1][g0] = new_d_2g_cumul_[g0][g1];\n            new_d_2g_nb_[g1][g0] = new_d_2g_nb_[g0][g1];\n            new_d_2g_inv_nb_[g1][g0] = new_d_2g_inv_nb_[g0][g1];\n            new_d_2g_[g1][g0] = new_d_2g_[g0][g1];\n            new_d_2g_inv_prop_[g1][g0] = new_d_2g_inv_prop_[g0][g1];\n\n            //\n            //q_func_[0] = log(1 + d_2g_[0][1] - v_1g_[0]);\n\n            //reinitialize functions\n            new_q_func_.resize(NB_FUNC_, 0.0);\n\n\n            new_q_func_[0] = log(1 + new_d_2g_[0][1] - new_v_1g_[0]);\n            new_q_func_[1] = new_d_2g_[0][1] - new_v_1g_[0];\n            new_q_func_[2] = new_d_2g_[0][1] - new_v_1g_[1];\n            new_q_func_[3] = 2 * new_d_2g_[0][1] - new_v_1g_[0] - new_v_1g_[1];\n            new_q_func_[4] = new_d_2g_[0][1];\n            new_q_func_[5] =  abs(new_v_1g_[0] - new_v_1g_[1]);\n            new_q_func_[6] =  abs(new_v_1g_[0] / new_v_1g_[1]);\n       \n            //q_func[5]   is invariable\n            //new_q_func_[6] = abs ( log (new_v_1g_[0]) - log( new_v_1g_[1])) ;  //// new_d_2g_[0][1]\n            //new_q_func_[7] = new_d_2g_[0][1] * (new_v_1g_[1] * new_v_1g_[0]);\n\n\n            //cout << \"q_func_[1]: \" << q_func_[1] << \" new_q_func_[1]: \" << new_q_func_[1] << \"diff: \" << (new_q_func_[1] - q_func_[1]) << endl;\n\n\n\n\n\n            //move the element if usefull\n            if (new_q_func_[q_func_opt_max_idx_] > q_func_[q_func_opt_max_idx_]\n                    && ident_grouped_[g0].size() > 0\n                    && new_v_1g_nb_[g0] > 0\n                    && new_v_1g_nb_[g1] > 0\n                    && new_d_2g_nb_[g0][g1] > 0\n                    ) {\n                cycle_transfered++;\n                //update sets\n                ident_grouped_[g1].insert(*it1);\n                //workaround for\n                //iterator toDelete = itr2;\n                //++itr2;   // increment before erasing!\n                //container.erase(toDelete);\n                ident_grouped_[g0].erase(it1++);\n\n                //debug\n                //calcQRes();\n                //cout << \"after calcQRes(): q_func_[1]: \" << q_func_[4] << \" new_q_func_[1]: \" << new_q_func_[4] << \"diff: \" << (new_q_func_[4] - q_func_[4]) << endl;\n                //cout << \"q_func_[q_func_opt_max_idx_]: \" << q_func_[q_func_opt_max_idx_] << \" new_q_func_[q_func_opt_max_idx_]: \" << new_q_func_[q_func_opt_max_idx_] << \"diff: \" << (new_q_func_[q_func_opt_max_idx_] - q_func_[q_func_opt_max_idx_]) << endl;\n\n\n                //cout << \" go : \" << ident_grouped_[g0].size() << \" g1 : \" << ident_grouped_[g1].size() << endl;\n                //update group information\n                v_1g_cumul_[g0] = new_v_1g_cumul_[g0];\n                v_1g_nb_[g0] = new_v_1g_nb_[g0];\n                v_1g_inv_nb_[g0] = new_v_1g_inv_nb_[g0];\n                v_1g_[g0] = new_v_1g_[g0];\n                v_1g_inv_prop_[g0] = new_v_1g_inv_prop_[g0];\n\n                v_1g_cumul_[g1] = new_v_1g_cumul_[g1];\n                v_1g_nb_[g1] = new_v_1g_nb_[g1];\n                v_1g_inv_nb_[g1] = new_v_1g_inv_nb_[g1];\n                v_1g_[g1] = new_v_1g_[g1];\n                v_1g_inv_prop_[g1] = new_v_1g_inv_prop_[g1];\n\n\n                d_2g_cumul_[g0][g1] = new_d_2g_cumul_[g0][g1];\n                d_2g_nb_[g0][g1] = new_d_2g_nb_[g0][g1];\n                d_2g_inv_nb_[g0][g1] = new_d_2g_inv_nb_[g0][g1];\n                d_2g_[g0][g1] = new_d_2g_[g0][g1];\n                d_2g_inv_prop_[g0][g1] = new_d_2g_inv_prop_[g0][g1];\n                //\n                //symetric results\n                d_2g_cumul_[g1][g0] = d_2g_cumul_[g0][g1];\n                d_2g_nb_[g1][g0] = d_2g_nb_[g0][g1];\n                d_2g_inv_nb_[g1][g0] = d_2g_inv_nb_[g0][g1];\n                d_2g_[g1][g0] = d_2g_[g0][g1];\n                d_2g_inv_prop_[g1][g0] = new_d_2g_inv_prop_[g0][g1];\n                //functions 0-4 change with groupings\n                q_func_[0] = new_q_func_[0];\n                q_func_[1] = new_q_func_[1];\n                q_func_[2] = new_q_func_[2];\n                q_func_[3] = new_q_func_[3];\n                q_func_[4] = new_q_func_[4];\n                q_func_[5] = new_q_func_[5];\n                q_func_[6] = new_q_func_[6];\n                q_func_[7] = new_q_func_[7];\n                //function 5 is invariable of groupings\n\n\n\n\n            } else {\n                ++it1;\n            }\n\n\n        }\n        //cout << \"cycle tranfered: \" << cycle_transfered << \" direction: \" << g0 << \":\" << g1 << \" end q_func_[1] : \" << q_func_[1]\n        //       << \" nx: \" << ident_grouped_[0].size()\n        //       << \" ny: \" << ident_grouped_[1].size()\n        //      << endl;\n        if (cycle_transfered == 0) {\n            nb_null_cycles++;\n        }\n        //cout << \"nb_null_cycles: \" << nb_null_cycles << endl;\n    } while (nb_null_cycles != 2);\n\n\n\n\n\n\n    /*\n\n      set<string>::iterator it = ident_all_.begin();\n      while (it != ident_all_.end()) {\n          if (*it == 2)\n              it = ident_all_.erase(it);\n          else\n              ++it;\n      }\n     */\n\n    //float d_2g_elem = dist_matrix_[ident_grouped_[0][i]][ident_grouped_[1][j]].real_dist_;\n\n\n    //for (int j = 0; j < ident_grouped_[1].size(); j++) {\n\n    //}\n\n\n\n\n}\n\n\n// with nj optimisation\n\nvoid AutoWinQ::testNjBipartitions() {\n\n\t//calculate NJ bipartitions\n    calculateNjBipartitions();\n\n    float q_cycle = 0;\n    \n   cout << \"q_func_opt_max_val_: \" << q_func_opt_max_val_ << endl;\n\n    //outputBipartMatrix();\n\n\n    //all bipartitions are in bipart_matrix_ member variable\n\n\n    //iterate over all bipartitions and CalcQRes()\n\n    // vector < set<string> >\n\n    cout << \"outputBipartMatrix(): \" << endl;\n    for (int i = 0; i < bipart_matrix_.size(); i++) {\n\n\n        cout << \"bipartition: \" << i << endl;\n\n        //activate this bipartition\n        //like generateRandomInitGrouping();\n        ident_grouped_.clear();\n        ident_grouped_ = bipart_matrix_[i];\n\n        //reject trivial partitions\n        if (ident_grouped_[0].size() < 2 || ident_grouped_[1].size() < 2) {\n            continue;\n        }\n\n        //calculate\n        calcQRes();\n\n        q_cycle = q_func_[q_func_opt_max_idx_];\n        cout << \"q_cycle: \" << q_cycle << endl;\n\n        if (q_cycle > q_func_opt_max_val_) {\n            //save decision position\n            q_func_opt_max_val_ = q_cycle;\n            //save all associated data\n\n            if (best_window_ != NULL) {\n                delete best_window_;\n            }\n            best_window_ = new AutoWinQ(*ctx_, *this);\n\n        }\n\n\n    }\n\n    \n\n}\n\n\n//with k-means optimisation\n\nvoid AutoWinQ::testManyRandomSeeds() {\n\n\n    //advance position\n    // win_pos_ += ctx_->win_step_;\n\n\n\n    float q_init = 0;\n    float q_cycle = 0;\n\n    for (int i = 0; i < NB_RANDOM_SEEDS_ && !uncalculable_; i++) {\n        //for (int i = 0; i < 1; i++) {\n\n        int initial_wait = 0;\n        //wait for decent values\n        do {\n            initial_wait++;\n            //wait for decent grouping dimensions\n            //at least two per group\n            generateRandomInitGrouping();\n\n            calcQRes();\n            if (initial_wait >= NB_RANDOM_SEEDS_) {\n                uncalculable_ = true;\n                break;\n            }\n        } while (v_1g_nb_[0] < 1\n                || v_1g_nb_[1] < 1\n                || d_2g_nb_[0][1] < 1);\n\n\n\n        /*\n                q_init = q_func_[q_func_opt_max_idx_];\n                if ( win_pos_ == 29 && i == 0) {\n                    cout << \"win_pos_: \" << win_pos_ << \"i: \" << i << \"q_init: \" << q_init << endl;\n            \n                    if (q_init == numeric_limits<float>::signaling_NaN()) {\n                       cout << \"signaling nan: \" << i << endl;\n                      }\n\n                    if (q_init == numeric_limits<float>::quiet_NaN()) {\n                       cout << \"QUIET nan: \" << i << endl;\n                      }\n\n\n                }\n         */\n\n        testOneCycleTransfers();\n        q_cycle = q_func_[q_func_opt_max_idx_];\n\n        if (q_cycle > q_func_opt_max_val_) {\n            //save decision position\n            q_func_opt_max_val_ = q_cycle;\n            //save all associated data\n\n            if (best_window_ != NULL) {\n                delete best_window_;\n            }\n            best_window_ = new AutoWinQ(*ctx_, *this);\n\n        }\n\n        if (!uncalculable_) {\n\n            //cout << \"i: \" << i << \" q_init: \" << q_init << \" q_cycle: \" << q_cycle\n            //       << \" q_func_opt_max_val_: \" << q_func_opt_max_val_\n            //       << \" go : \" << ident_grouped_[0].size() << \" g1 : \" << ident_grouped_[1].size()\n            //       << endl;\n            /*\n            cout << \"best_window_: size \" << best_window_->ident_grouped_.size()\n                    << \" go : \" << best_window_->ident_grouped_[0].size() << \" g1 : \" << best_window_->ident_grouped_[1].size()\n                    << endl;\n             */\n\n        }\n\n    }\n\n    //cout << \"--------------------------------> \" << best_window.q_func_[1] << endl;\n\n\n    //outputGroupings(cout);\n\n    //test();\n\n}\n\nvoid AutoWinQ::calcSimple() {\n\n    getContextGrouping();\n    calcQRes();\n\n    simple_window_ = new AutoWinQ(*ctx_, *this);\n\n\n}\n\n", "meta": {"hexsha": "b47e08cbaaee65f7d511d29970d5ca1edb3e1112", "size": 41060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter3/Main/q_funcb/src/auto_win_q.cpp", "max_stars_repo_name": "dunarel/dunphd-thesis", "max_stars_repo_head_hexsha": "7c6286b5134024a8a67f97c4bfba8d6b94dc21c9", "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": "Chapter3/Main/q_funcb/src/auto_win_q.cpp", "max_issues_repo_name": "dunarel/dunphd-thesis", "max_issues_repo_head_hexsha": "7c6286b5134024a8a67f97c4bfba8d6b94dc21c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter3/Main/q_funcb/src/auto_win_q.cpp", "max_forks_repo_name": "dunarel/dunphd-thesis", "max_forks_repo_head_hexsha": "7c6286b5134024a8a67f97c4bfba8d6b94dc21c9", "max_forks_repo_licenses": ["BSD-3-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.2199312715, "max_line_length": 257, "alphanum_fraction": 0.5032878714, "num_tokens": 12355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.032589744766025344, "lm_q1q2_score": 0.011362255533323987}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include \"MolData3Ddescriptors.h\"\n#include <GraphMol/RDKitBase.h>\n#include <boost/math/special_functions/round.hpp>\n\n#include \"GraphMol/PartialCharges/GasteigerCharges.h\"\n#include \"GraphMol/PartialCharges/GasteigerParams.h\"\n\nusing namespace std;\n\nMolData3Ddescriptors::MolData3Ddescriptors() {}\n\nstd::vector<double> MolData3Ddescriptors::GetUn(int numAtoms) {\n  std::vector<double> u(numAtoms, 1.0);\n\n  return u;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetRelativeMW(\n    const RDKit::ROMol& mol) {\n  double* relativeMw = data3D.getMW();\n  int numAtoms = mol.getNumAtoms();\n\n  std::vector<double> pol(numAtoms, 0.0);\n  for (int i = 0; i < numAtoms; ++i) {\n    pol[i] = relativeMw[mol.getAtomWithIdx(i)->getAtomicNum() - 1];\n  }\n  return pol;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetRelativePol(\n    const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n  double* relativePol = data3D.getPOL();\n\n  std::vector<double> pol(numAtoms, 0.0);\n  for (int i = 0; i < numAtoms; ++i) {\n    pol[i] = relativePol[mol.getAtomWithIdx(i)->getAtomicNum() - 1];\n  }\n  return pol;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetRelativeVdW(\n    const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n  double* relativeVdW = data3D.getVDW();\n\n  std::vector<double> vdw(numAtoms, 0.0);\n  for (int i = 0; i < numAtoms; ++i) {\n    vdw[i] = relativeVdW[mol.getAtomWithIdx(i)->getAtomicNum() - 1];\n  }\n  return vdw;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetRelativeRcov(\n    const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n  double* rcov = data3D.getRCOV();\n\n  std::vector<double> wroc(numAtoms, 0.0);\n  for (int i = 0; i < numAtoms; ++i) {\n    wroc[i] = rcov[mol.getAtomWithIdx(i)->getAtomicNum() - 1] / rcov[5];\n  }\n  return wroc;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetRelativeENeg(\n    const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n  double* relativeNeg = data3D.getNEG();\n\n  std::vector<double> neg(numAtoms, 0.0);\n  for (int i = 0; i < numAtoms; ++i) {\n    neg[i] = relativeNeg[mol.getAtomWithIdx(i)->getAtomicNum() - 1];\n  }\n  return neg;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetRelativeIonPol(\n    const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n  double* absionpol = data3D.getIonPOL();\n\n  std::vector<double> ionpols(numAtoms, 0.0);\n  for (int i = 0; i < numAtoms; ++i) {\n    ionpols[i] = absionpol[mol.getAtomWithIdx(i)->getAtomicNum() - 1];\n  }\n  return ionpols;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetCustomAtomProp(\n      const RDKit::ROMol& mol, const std::string &customAtomPropName) {\n    int numAtoms = mol.getNumAtoms();\n\n    std::vector<double> customAtomarray(numAtoms, 0.0);\n    for (int i = 0; i < numAtoms; ++i) {\n\n        if (mol.getAtomWithIdx(i)->hasProp(customAtomPropName)) {\n            customAtomarray[i] = mol.getAtomWithIdx(i)->getProp<double>(customAtomPropName);\n        }\n        else {\n            customAtomarray[i] =1;\n        }\n    }\n    return customAtomarray;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetCharges(const RDKit::ROMol& mol) {\n  std::vector<double> charges(mol.getNumAtoms(), 0);\n  // use 12 iterations... can be more\n  RDKit::computeGasteigerCharges(mol, charges, 12, true);\n  return charges;\n}\n\nint MolData3Ddescriptors::GetPrincipalQuantumNumber(int AtomicNum) {\n  if (AtomicNum <= 2)\n    return 1;\n  else if (AtomicNum <= 10)\n    return 2;\n  else if (AtomicNum <= 18)\n    return 3;\n  else if (AtomicNum <= 36)\n    return 4;\n  else if (AtomicNum <= 54)\n    return 5;\n  else if (AtomicNum <= 86)\n    return 6;\n  else\n    return 7;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetIState(const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n  std::vector<double> Is(numAtoms, 1.0);  // values set to 1 for Hs\n\n  for (int i = 0; i < numAtoms; ++i) {\n    const RDKit::Atom* atom = mol.getAtomWithIdx(i);\n    int atNum = atom->getAtomicNum();\n    int degree = atom->getDegree();  // number of substituants (heavy of not?)\n    if (degree > 0 && atNum > 1) {\n      int h = atom->getTotalNumHs(\n          true);  // caution getTotalNumHs(true) to count h !!!!\n      int dv = RDKit::PeriodicTable::getTable()->getNouterElecs(atNum) -\n               h;  // number of valence (explicit with Hs)\n      int N = GetPrincipalQuantumNumber(atNum);  // principal quantum number\n      double d = (double)degree - h;             // degree-h\n      if (d > 0) {\n        Is[i] =\n            boost::math::round(1000 * (4.0 / (N * N) * dv + 1.0) / d) / 1000;\n      }\n    }\n  }\n\n  return Is;\n}\n\nstd::vector<double> MolData3Ddescriptors::GetIStateDrag(\n    const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n  std::vector<double> Is(numAtoms, 1.0);\n\n  for (int i = 0; i < numAtoms; ++i) {\n    const RDKit::Atom* atom = mol.getAtomWithIdx(i);\n    int atNum = atom->getAtomicNum();\n    int degree = atom->getDegree();  // number of substituants\n    if (degree > 0 && atNum > 1) {\n      int h = atom->getTotalNumHs(true);\n      int Zv = RDKit::PeriodicTable::getTable()->getNouterElecs(\n          atNum);                  // number of valence (explicit with Hs)\n      double dv = (double)Zv - h;  // number of valence electron without Hs\n      int N = GetPrincipalQuantumNumber(atNum);  // principal quantum number\n      double d = (double)degree - h;             // degree-h\n      if (d > 0) {\n        Is[i] =\n            boost::math::round(1000 * (4.0 / (N * N) * dv + 1.0) / d) / 1000;\n      }\n    }\n  }\n\n  return Is;\n}\n\n// adaptation from EState.py\n// we need the Is value only there\nstd::vector<double> MolData3Ddescriptors::GetEState(const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n\n  std::vector<double> Is = GetIState(mol);\n\n  double tmp, p;\n  double* dist = RDKit::MolOps::getDistanceMat(mol, false, false);\n  std::vector<double> accum(numAtoms, 0.0);\n\n  for (int i = 0; i < numAtoms; i++) {\n    for (int j = i + 1; j < numAtoms; j++) {\n      p = dist[i * numAtoms + j] + 1;\n      if (p < 1e6) {\n        tmp = (Is[i] - Is[j]) / (p * p);\n        accum[i] += tmp;\n        accum[j] -= tmp;\n      }\n    }\n  }\n\n  for (int i = 0; i < numAtoms; i++) {\n    Is[i] += accum[i];\n  }\n\n  return Is;\n}\n\n// modification of previous code to follow documentation from Padel code\nstd::vector<double> MolData3Ddescriptors::GetEState2(const RDKit::ROMol& mol) {\n  int numAtoms = mol.getNumAtoms();\n\n  std::vector<double> Si = GetIState(mol);\n\n  // in WHIM definition it's write:\n  double tmp, p, d;\n  double* dist = RDKit::MolOps::getDistanceMat(mol, false, false);\n  std::vector<double> accum(numAtoms, 0.0);\n\n  for (int i = 0; i < numAtoms; i++) {\n    for (int j = i + 1; j < numAtoms; j++) {\n      d = dist[i * numAtoms + j];\n      p = dist[i * numAtoms + j] + 1;\n      if (d == 1) {\n        tmp = (Si[i] - Si[j]) / (p * p);\n        accum[i] += tmp;\n        accum[j] -= tmp;\n      }\n    }\n  }\n\n  // add the Accum to the Si\n  // WHIM Si values\n  // electrotopological indices are scaled thus: Si'=Si + 7 => Si' > 0\n  // In this case, only the nonhydrogen atoms are considered,\n  // and the atomic electrotopological charge of each atom depends on its atom\n  // neighbor.\n  // So we should not use all the terms in the sum but only Adj matrix cases!\n\n  // Correct the Si adding the rescaling parameter for WHIM only\n  for (int i = 0; i < numAtoms; i++) {\n    Si[i] += accum[i] + 7.0;\n  }\n\n  return Si;\n}\n", "meta": {"hexsha": "a7fc46cb4a288c4698b0b9564897eda4b5b41a3e", "size": 7388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modified_rdkit/Code/GraphMol/Descriptors/MolData3Ddescriptors.cpp", "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/Descriptors/MolData3Ddescriptors.cpp", "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/Descriptors/MolData3Ddescriptors.cpp", "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": 29.4342629482, "max_line_length": 92, "alphanum_fraction": 0.6224959394, "num_tokens": 2380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.03461884244969336, "lm_q1q2_score": 0.011343497281871026}}
{"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_IEXP_IEXP_FACTORY_HPP\n#define AMA_TENSOR_IEXP_IEXP_FACTORY_HPP 1\n\n#include <ama/tensor/iexp/iexp_mutable.hpp>\n#include <ama/tensor/iexp/iexp_constant.hpp>\n#include <ama/tensor/iexp/iexp_temporary.hpp>\n#include <ama/tensor/iexp/tensor_reducer.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/vector/vector0_c.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    namespace mpl = ::boost::mpl;\n\n    /* forward declaration */\n    template <typename WHAT>\n    struct iexp_factory\n    {\n      template <typename ILIST, typename TENSOR>\n      static\n      WHAT apply(TENSOR const & t)\n      {\n        BOOST_MPL_ASSERT_MSG(\n              (mpl::equal<WHAT, typename TENSOR::value_type>::type::value)\n            , THIS_STRUCT_CAN_BE_CALLED_ONLY_TO_REDUCE_OVER_ALL_INDICES\n            , (WHAT));\n\n        return tensor_reducer<TENSOR,ILIST>(t).template at< ::boost::mpl::vector0_c<size_t> >();\n      }\n    };\n\n\n\n\n    /* specialization for mutable index expression */\n    template <typename DERIVED, typename CTLIST, typename COLIST>\n    struct iexp_factory< iexp_temporary<DERIVED, CTLIST, COLIST> >\n    {\n      template <typename ILIST, typename TENSOR>\n      static\n      iexp_temporary<DERIVED,CTLIST,COLIST>\n      apply(TENSOR const & t)\n      {\n        return iexp_temporary<DERIVED,CTLIST,COLIST>(tensor_reducer<TENSOR, ILIST>(t));\n      }\n    };\n\n\n\n\n    /* specialization for mutable index expression */\n    template <typename DERIVED, typename CTLIST, typename COLIST>\n    struct iexp_factory< iexp_mutable<DERIVED, CTLIST, COLIST> >\n    {\n      template <typename ULIST>\n      static\n      iexp_mutable<DERIVED,CTLIST,COLIST>\n      apply(DERIVED & t)\n      {\n        return iexp_mutable<DERIVED,CTLIST,COLIST>(t);\n      }\n    };\n\n\n\n\n    /* specialization for constant index expression */\n    template <typename DERIVED, typename CTLIST, typename COLIST>\n    struct iexp_factory< iexp_constant<DERIVED, CTLIST, COLIST> >\n    {\n      template <typename ULIST>\n      static\n      iexp_constant<DERIVED,CTLIST,COLIST>\n      apply(DERIVED const & t)\n      {\n        return iexp_constant<DERIVED,CTLIST,COLIST>(t);\n      }\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_IEXP_IEXP_FACTORY_HPP */\n", "meta": {"hexsha": "9b8036a934205a1dd59448e63aedf41e08068baa", "size": 3865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/iexp/iexp_factory.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/iexp/iexp_factory.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/iexp/iexp_factory.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": 33.3189655172, "max_line_length": 96, "alphanum_fraction": 0.7068564036, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.038466193671751685, "lm_q1q2_score": 0.011317329624252375}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include <finley/DomainFactory.h>\n\n#include <escript/index.h>\n#include <escript/SubWorld.h>\n\n#ifdef ESYS_HAVE_NETCDF\n #ifdef NETCDF4\n  #include <ncDim.h>\n  #include <ncVar.h>\n  #include <ncFile.h>\n  \n #include <escript/NCHelper.h>  \n  \n #else\n  #include <netcdfcpp.h>\n #endif\n#endif\n\n\n#include <boost/python/extract.hpp>\n#include <boost/scoped_array.hpp>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace escript;\nnamespace bp = boost::python;\n\n#ifdef NETCDF4\nusing namespace netCDF;\n#endif\n\nnamespace finley {\n\n#ifdef ESYS_HAVE_NETCDF\n#ifdef NETCDF4\n\n// A convenience method to retrieve an integer attribute from a NetCDF file\ntemplate<typename T>\nT ncReadAtt(NcFile& dataFile, const string& fName, const string& attrName)\n{\n    NcGroupAtt attr = dataFile.getAtt(attrName.c_str());\n    if (attr.isNull()) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving integer attribute '\" << attrName\n            << \"' from NetCDF file '\" << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    T value;\n    attr.getValues(&value);\n    return value;\n}\n#else    \n    \n// A convenience method to retrieve an integer attribute from a NetCDF file\ntemplate<typename T>\nT ncReadAtt(NcFile* dataFile, const string& fName, const string& attrName)\n{\n    NcAtt* attr = dataFile->get_att(attrName.c_str());\n    if (!attr) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving integer attribute '\" << attrName\n            << \"' from NetCDF file '\" << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    T value = (sizeof(T) > 4 ? attr->as_long(0) : attr->as_int(0));\n    delete attr;\n    return value;\n}\n\n#endif\n#endif\n\ninline void cleanupAndThrow(FinleyDomain* dom, string msg)\n{\n    delete dom;\n    string msgPrefix(\"loadMesh: NetCDF operation failed - \");\n    throw IOError(msgPrefix+msg);\n}\n\n#ifdef NETCDF4\n\nDomain_ptr FinleyDomain::load(const string& fileName)\n{\n#ifdef ESYS_HAVE_NETCDF\n    JMPI mpiInfo = makeInfo(MPI_COMM_WORLD);\n    const string fName(mpiInfo->appendRankToFileName(fileName));\n\n    // Open NetCDF file for reading\n    NcGroupAtt attr;\n    NcVar nc_var_temp;\n    NcFile dataFile;\n    // Create the NetCDF file.\n    if (!openNcFile(dataFile, fileName))\n    {\n        throw IOError(\"load: opening of netCDF file for input failed.\");\n    }    \n    // Read NetCDF integer attributes\n\n    // index_size was only introduced with 64-bit index support so fall back\n    // to 32 bits if not found.\n    int index_size;\n    try {\n        index_size = ncReadAtt<int>(dataFile, fName, \"index_size\");\n    } catch (IOError& e) {\n        index_size = 4;\n    }\n    // technically we could cast if reading 32-bit data on 64-bit escript\n    // but cost-benefit analysis clearly favours this implementation for now\n    if (sizeof(index_t) != index_size) {\n        throw IOError(\"loadMesh: size of index types at runtime differ from dump file\");\n    }\n\n    int mpi_size = ncReadAtt<int>(dataFile, fName, \"mpi_size\");\n    int mpi_rank = ncReadAtt<int>(dataFile, fName, \"mpi_rank\");\n    int numDim = ncReadAtt<int>(dataFile, fName, \"numDim\");\n    int order = ncReadAtt<int>(dataFile, fName, \"order\");\n    int reduced_order = ncReadAtt<int>(dataFile, fName, \"reduced_order\");\n    dim_t numNodes = ncReadAtt<dim_t>(dataFile, fName, \"numNodes\");\n    dim_t num_Elements = ncReadAtt<dim_t>(dataFile, fName, \"num_Elements\");\n    dim_t num_FaceElements = ncReadAtt<dim_t>(dataFile, fName, \"num_FaceElements\");\n    dim_t num_ContactElements = ncReadAtt<dim_t>(dataFile, fName, \"num_ContactElements\");\n    dim_t num_Points = ncReadAtt<dim_t>(dataFile, fName, \"num_Points\");\n    int num_Elements_numNodes = ncReadAtt<int>(dataFile, fName, \"num_Elements_numNodes\");\n    int Elements_TypeId = ncReadAtt<int>(dataFile, fName, \"Elements_TypeId\");\n    int num_FaceElements_numNodes = ncReadAtt<int>(dataFile, fName, \"num_FaceElements_numNodes\");\n    int FaceElements_TypeId = ncReadAtt<int>(dataFile, fName, \"FaceElements_TypeId\");\n    int num_ContactElements_numNodes = ncReadAtt<int>(dataFile, fName, \"num_ContactElements_numNodes\");\n    int ContactElements_TypeId = ncReadAtt<int>(dataFile, fName, \"ContactElements_TypeId\");\n    int Points_TypeId = ncReadAtt<int>(dataFile, fName, \"Points_TypeId\");\n    int num_Tags = ncReadAtt<int>(dataFile, fName, \"num_Tags\");\n\n    // Verify size and rank\n    if (mpiInfo->size != mpi_size) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' can only be read on \" << mpi_size\n            << \" CPUs. Currently running: \" << mpiInfo->size;\n        throw FinleyException(msg.str());\n    }\n    if (mpiInfo->rank != mpi_rank) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' should be read on CPU #\" << mpi_rank\n            << \" and NOT on #\" << mpiInfo->rank;\n        throw FinleyException(msg.str());\n    }\n\n    // Read mesh name\n    if ((attr=dataFile.getAtt(\"Name\")).isNull() ) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving mesh name from NetCDF file '\"\n            << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    string name;\n    attr.getValues(name);\n\n    // allocate mesh\n    FinleyDomain* dom = new FinleyDomain(name, numDim, mpiInfo);\n\n    // read nodes\n    NodeFile* nodes = dom->getNodes();\n    nodes->allocTable(numNodes);\n\n    try\n    {\n        // Nodes_Id\n        nc_var_temp = dataFile.getVar(\"Nodes_Id\");\n        nc_var_temp.getVar(&nodes->Id[0]); // numNodes values read\n        // Nodes_Tag\n        nc_var_temp = dataFile.getVar(\"Nodes_Tag\");\n        nc_var_temp.getVar(&nodes->Tag[0]);   // numNodes\n        // Nodes_gDOF\n        nc_var_temp = dataFile.getVar(\"Nodes_gDOF\");\n        nc_var_temp.getVar(&nodes->globalDegreesOfFreedom[0]);   //numNodes\n        // Nodes_gNI\n        nc_var_temp = dataFile.getVar(\"Nodes_gNI\");\n        nc_var_temp.getVar(&nodes->globalNodesIndex[0]); // numNodes\n        // Nodes_grDfI\n        nc_var_temp = dataFile.getVar(\"Nodes_grDfI\");\n        nc_var_temp.getVar(&nodes->globalReducedDOFIndex[0]); // numNodes\n        // Nodes_grNI\n        nc_var_temp = dataFile.getVar(\"Nodes_grNI\");\n        nc_var_temp.getVar(&nodes->globalReducedNodesIndex[0]);  // numNodes\n        // Nodes_Coordinates\n        nc_var_temp = dataFile.getVar(\"Nodes_Coordinates\");\n        nc_var_temp.getVar(&nodes->Coordinates[0]); // (numNodes, numDim) \n    }\n    catch (exceptions::NcException& e)\n    {\n        cleanupAndThrow(dom, \"Read vars from file\");\n    }\n    nodes->updateTagList();\n\n    // read elements\n    const_ReferenceElementSet_ptr refElements(new ReferenceElementSet(\n                (ElementTypeId)Elements_TypeId, order, reduced_order));\n    ElementFile* elements = new ElementFile(refElements, mpiInfo);\n    dom->setElements(elements);\n    elements->allocTable(num_Elements);\n    elements->minColor = 0;\n    elements->maxColor = num_Elements-1;\n    if (num_Elements > 0) {\n        try\n        {\n            // Elements_Id\n            nc_var_temp = dataFile.getVar(\"Elements_Id\");\n            nc_var_temp.getVar(&elements->Id[0]);    // num_Elements\n            // Elements_Tag\n            nc_var_temp = dataFile.getVar(\"Elements_Tag\");\n            nc_var_temp.getVar(&elements->Tag[0]); // num_Elements\n            // Elements_Owner\n            nc_var_temp = dataFile.getVar(\"Elements_Owner\");\n            nc_var_temp.getVar(&elements->Owner[0]);  // num_Elements\n            // Elements_Color\n            nc_var_temp = dataFile.getVar(\"Elements_Color\");\n            nc_var_temp.getVar(&elements->Color[0]); // num_Elements\n        }\n        catch (exceptions::NcException& e)\n        {\n            cleanupAndThrow(dom, \"Readig element vars\");            \n        }\n       // Now we need to adjust maxColor\n       index_t mc = elements->Color[0];\n       for (index_t i = 1; i < num_Elements; ++i) {\n           if (mc < elements->Color[i]) {\n               mc = elements->Color[i];\n           }\n       }\n       elements->maxColor = mc;\n       // Elements_Nodes\n       int* Elements_Nodes = new int[num_Elements*num_Elements_numNodes];       \n       try\n       {\n            nc_var_temp = dataFile.getVar(\"Elements_Nodes\");\n            nc_var_temp.getVar(&Elements_Nodes[0]);    // (num_Elements, num_Elements_numNodes) )             \n       }\n       catch (exceptions::NcException& e)\n       {\n           delete[] Elements_Nodes;\n           cleanupAndThrow(dom, \"get_var(Elements_Nodes)\");\n       }\n       // Copy temp array into elements->Nodes\n       for (index_t i = 0; i < num_Elements; i++) {\n           for (int j = 0; j < num_Elements_numNodes; j++) {\n               elements->Nodes[INDEX2(j,i,num_Elements_numNodes)]\n                    = Elements_Nodes[INDEX2(j,i,num_Elements_numNodes)];\n           }\n       }\n       delete[] Elements_Nodes;\n    } // num_Elements > 0\n    elements->updateTagList();\n\n    // get the face elements\n    const_ReferenceElementSet_ptr refFaceElements(\n            new ReferenceElementSet((ElementTypeId)FaceElements_TypeId,\n                order, reduced_order));\n    ElementFile* faces = new ElementFile(refFaceElements, mpiInfo);\n    dom->setFaceElements(faces);\n    faces->allocTable(num_FaceElements);\n    faces->minColor = 0;\n    faces->maxColor = num_FaceElements-1;\n    if (num_FaceElements > 0) {\n        try\n        {\n            // FaceElements_Id\n            nc_var_temp = dataFile.getVar(\"FaceElements_Id\");\n            nc_var_temp.getVar(&faces->Id[0]); // num_FaceElements\n            // FaceElements_Tag\n            nc_var_temp = dataFile.getVar(\"FaceElements_Tag\");\n            nc_var_temp.getVar(&faces->Tag[0]); // num_FaceElements\n            // FaceElements_Owner\n            nc_var_temp = dataFile.getVar(\"FaceElements_Owner\");\n            nc_var_temp.getVar(&faces->Owner[0]);   // num_FaceElements\n            // FaceElements_Color\n            nc_var_temp = dataFile.getVar(\"FaceElements_Color\");\n            nc_var_temp.getVar(&faces->Color[0]); // num_FaceElements\n        }\n        catch (exceptions::NcException& e)\n        {\n            cleanupAndThrow(dom, \"read face variables\");\n        }\n        // Now we need to adjust maxColor\n        index_t mc = faces->Color[0];\n        for (index_t i = 1; i < num_FaceElements; ++i) {\n            if (mc < faces->Color[i]) {\n                mc = faces->Color[i];\n            }\n        }\n        faces->maxColor = mc;\n        // FaceElements_Nodes\n        int* FaceElements_Nodes = new int[num_FaceElements*num_FaceElements_numNodes];\n        try\n        {\n            nc_var_temp = dataFile.getVar(\"FaceElements_Nodes\");\n            nc_var_temp.getVar(&(FaceElements_Nodes[0])); // num_FaceElements, num_FaceElements_numNodes) ) \n        }\n        catch (exceptions::NcException& e)\n        {\n            delete[] FaceElements_Nodes;\n            cleanupAndThrow(dom, \"read face elements\");\n        }\n        if ((nc_var_temp = dataFile.getVar(\"FaceElements_Nodes\")), nc_var_temp.isNull()) {\n            delete[] FaceElements_Nodes;\n            cleanupAndThrow(dom, \"get_var(FaceElements_Nodes)\");\n        }\n        nc_var_temp.getVar(&(FaceElements_Nodes[0]));  // num_FaceElements, num_FaceElements_numNodes\n        // Copy temp array into faces->Nodes\n        for (index_t i = 0; i < num_FaceElements; i++) {\n            for (int j = 0; j < num_FaceElements_numNodes; j++) {\n                faces->Nodes[INDEX2(j,i,num_FaceElements_numNodes)] = FaceElements_Nodes[INDEX2(j,i,num_FaceElements_numNodes)];\n            }\n        }\n        delete[] FaceElements_Nodes;\n    } // num_FaceElements > 0\n    faces->updateTagList();\n\n    // get the Contact elements\n    const_ReferenceElementSet_ptr refContactElements(\n         new ReferenceElementSet((ElementTypeId)ContactElements_TypeId,\n             order, reduced_order));\n    ElementFile* contacts = new ElementFile(refContactElements, mpiInfo);\n    dom->setContactElements(contacts);\n    contacts->allocTable(num_ContactElements);\n    contacts->minColor = 0;\n    contacts->maxColor = num_ContactElements-1;\n    if (num_ContactElements > 0) {\n        // ContactElements_Id\n        if (( nc_var_temp = dataFile.getVar(\"ContactElements_Id\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Id)\");\n        nc_var_temp.getVar(&contacts->Id[0]);       // num_ContactElements\n        // ContactElements_Tag\n        if (( nc_var_temp = dataFile.getVar(\"ContactElements_Tag\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Tag)\");\n        nc_var_temp.getVar(&contacts->Tag[0]);  //, num_ContactElements\n        // ContactElements_Owner\n        if (( nc_var_temp = dataFile.getVar(\"ContactElements_Owner\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Owner)\");\n        nc_var_temp.getVar(&contacts->Owner[0]);    //, num_ContactElements)\n        // ContactElements_Color\n        if (( nc_var_temp = dataFile.getVar(\"ContactElements_Color\")), nc_var_temp.isNull() )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Color)\");\n        nc_var_temp.getVar(&contacts->Color[0]);  //, num_ContactElements\n        // Now we need to adjust maxColor\n        index_t mc = contacts->Color[0];\n        for (index_t i = 1; i < num_ContactElements; ++i) {\n            if (mc < contacts->Color[i]) {\n                mc = contacts->Color[i];\n            }\n        }\n        contacts->maxColor = mc;\n        // ContactElements_Nodes\n        int* ContactElements_Nodes = new int[num_ContactElements*num_ContactElements_numNodes];\n        if ((nc_var_temp = dataFile.getVar(\"ContactElements_Nodes\")), nc_var_temp.isNull()) {\n            delete[] ContactElements_Nodes;\n            cleanupAndThrow(dom, \"get_var(ContactElements_Nodes)\");\n        }\n        nc_var_temp.getVar(&ContactElements_Nodes[0]);    // num_ContactElements, num_ContactElements_numNodes\n        // Copy temp array into contacts->Nodes\n        for (index_t i = 0; i < num_ContactElements; i++) {\n            for (int j = 0; j < num_ContactElements_numNodes; j++) {\n                contacts->Nodes[INDEX2(j,i,num_ContactElements_numNodes)] = ContactElements_Nodes[INDEX2(j,i,num_ContactElements_numNodes)];\n            }\n        }\n        delete[] ContactElements_Nodes;\n    } // num_ContactElements > 0\n    contacts->updateTagList();\n\n    // get the Points (nodal elements)\n    const_ReferenceElementSet_ptr refPoints(new ReferenceElementSet(\n                (ElementTypeId)Points_TypeId, order, reduced_order));\n    ElementFile* points = new ElementFile(refPoints, mpiInfo);\n    dom->setPoints(points);\n    points->allocTable(num_Points);\n    points->minColor = 0;\n    points->maxColor = num_Points-1;\n    if (num_Points > 0) {\n        // Points_Id\n        if (( nc_var_temp = dataFile.getVar(\"Points_Id\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Id)\");\n        nc_var_temp.getVar(&points->Id[0]); // num_Points\n        // Points_Tag\n        if (( nc_var_temp = dataFile.getVar(\"Points_Tag\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Tag)\");\n        nc_var_temp.getVar(&points->Tag[0]);    // num_Points\n        // Points_Owner\n        if (( nc_var_temp = dataFile.getVar(\"Points_Owner\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Owner)\");\n        nc_var_temp.getVar(&points->Owner[0]);  // num_Points\n        // Points_Color\n        if (( nc_var_temp = dataFile.getVar(\"Points_Color\")), nc_var_temp.isNull())\n            cleanupAndThrow(dom, \"get_var(Points_Color)\");\n        nc_var_temp.getVar(&points->Color[0]);  // num_Points\n        // Now we need to adjust maxColor\n        index_t mc = points->Color[0];\n        for (index_t i = 1; i < num_Points; ++i) {\n            if (mc < points->Color[i]) {\n                mc = points->Color[i];\n            }\n        }\n        points->maxColor = mc;\n        // Points_Nodes\n        int* Points_Nodes = new int[num_Points];\n        if ((nc_var_temp = dataFile.getVar(\"Points_Nodes\")), nc_var_temp.isNull()) {\n            delete[] Points_Nodes;\n            cleanupAndThrow(dom, \"get_var(Points_Nodes)\");\n        }\n        nc_var_temp.getVar(&Points_Nodes[0]);  // num_Points\n        // Copy temp array into points->Nodes\n        for (index_t i = 0; i < num_Points; i++) {\n            points->Id[points->Nodes[INDEX2(0,i,1)]] = Points_Nodes[i];\n        }\n        delete[] Points_Nodes;\n    } // num_Points > 0\n    points->updateTagList();\n\n    // get the tags\n    if (num_Tags > 0) {\n        // Temp storage to gather node IDs\n        int *Tags_keys = new int[num_Tags];\n        char name_temp[4096];\n        int i;\n\n        // Tags_keys\n        if (( nc_var_temp = dataFile.getVar(\"Tags_keys\")), nc_var_temp.isNull() ) {\n            delete[] Tags_keys;\n            cleanupAndThrow(dom, \"get_var(Tags_keys)\");\n        }\n        nc_var_temp.getVar(&Tags_keys[0]); // num_Tags\n        for (i=0; i<num_Tags; i++) {\n          // Retrieve tag name\n          sprintf(name_temp, \"Tags_name_%d\", i);\n          if ((attr=dataFile.getAtt(name_temp)), attr.isNull() ) {\n              delete[] Tags_keys;\n              stringstream msg;\n              msg << \"get_att(\" << name_temp << \")\";\n              cleanupAndThrow(dom, msg.str());\n          }\n          std::string name;\n          attr.getValues(name);\n//           boost::scoped_array<char> name(attr->as_string(0));\n//           delete attr;\n//           dom->setTagMap(name.get(), Tags_keys[i]);\n          dom->setTagMap(name.c_str(), Tags_keys[i]);\n        }\n        delete[] Tags_keys;\n    }\n\n    // Nodes_DofDistribution\n    IndexVector first_DofComponent(mpi_size+1);\n    if ((nc_var_temp = dataFile.getVar(\"Nodes_DofDistribution\")), nc_var_temp.isNull() ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_DofDistribution)\");\n    }\n    nc_var_temp.getVar(&first_DofComponent[0]); // mpi_size+1\n\n    // Nodes_NodeDistribution\n    IndexVector first_NodeComponent(mpi_size+1);\n    if ((nc_var_temp = dataFile.getVar(\"Nodes_NodeDistribution\")), nc_var_temp.isNull() ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_NodeDistribution)\");\n    }\n    nc_var_temp.getVar(&first_NodeComponent[0]);    // mpi_size+1\n    dom->createMappings(first_DofComponent, first_NodeComponent);\n\n    return dom->getPtr();\n#else\n    throw FinleyException(\"loadMesh: not compiled with NetCDF. Please contact your installation manager.\");\n#endif // ESYS_HAVE_NETCDF\n}\n\n\n#else\n\nDomain_ptr FinleyDomain::load(const string& fileName)\n{\n#ifdef ESYS_HAVE_NETCDF\n    JMPI mpiInfo = makeInfo(MPI_COMM_WORLD);\n    const string fName(mpiInfo->appendRankToFileName(fileName));\n\n    // Open NetCDF file for reading\n    NcAtt *attr;\n    NcVar *nc_var_temp;\n    // netCDF error handler\n    NcError err(NcError::silent_nonfatal);\n    // Create the NetCDF file.\n    NcFile dataFile(fName.c_str(), NcFile::ReadOnly);\n    if (!dataFile.is_valid()) {\n        stringstream msg;\n        msg << \"loadMesh: Opening NetCDF file '\" << fName << \"' for reading failed.\";\n        throw IOError(msg.str());\n    }\n\n    // Read NetCDF integer attributes\n\n    // index_size was only introduced with 64-bit index support so fall back\n    // to 32 bits if not found.\n    int index_size;\n    try {\n        index_size = ncReadAtt<int>(&dataFile, fName, \"index_size\");\n    } catch (IOError& e) {\n        index_size = 4;\n    }\n    // technically we could cast if reading 32-bit data on 64-bit escript\n    // but cost-benefit analysis clearly favours this implementation for now\n    if (sizeof(index_t) != index_size) {\n        throw IOError(\"loadMesh: size of index types at runtime differ from dump file\");\n    }\n\n    int mpi_size = ncReadAtt<int>(&dataFile, fName, \"mpi_size\");\n    int mpi_rank = ncReadAtt<int>(&dataFile, fName, \"mpi_rank\");\n    int numDim = ncReadAtt<int>(&dataFile, fName, \"numDim\");\n    int order = ncReadAtt<int>(&dataFile, fName, \"order\");\n    int reduced_order = ncReadAtt<int>(&dataFile, fName, \"reduced_order\");\n    dim_t numNodes = ncReadAtt<dim_t>(&dataFile, fName, \"numNodes\");\n    dim_t num_Elements = ncReadAtt<dim_t>(&dataFile, fName, \"num_Elements\");\n    dim_t num_FaceElements = ncReadAtt<dim_t>(&dataFile, fName, \"num_FaceElements\");\n    dim_t num_ContactElements = ncReadAtt<dim_t>(&dataFile, fName, \"num_ContactElements\");\n    dim_t num_Points = ncReadAtt<dim_t>(&dataFile, fName, \"num_Points\");\n    int num_Elements_numNodes = ncReadAtt<int>(&dataFile, fName, \"num_Elements_numNodes\");\n    int Elements_TypeId = ncReadAtt<int>(&dataFile, fName, \"Elements_TypeId\");\n    int num_FaceElements_numNodes = ncReadAtt<int>(&dataFile, fName, \"num_FaceElements_numNodes\");\n    int FaceElements_TypeId = ncReadAtt<int>(&dataFile, fName, \"FaceElements_TypeId\");\n    int num_ContactElements_numNodes = ncReadAtt<int>(&dataFile, fName, \"num_ContactElements_numNodes\");\n    int ContactElements_TypeId = ncReadAtt<int>(&dataFile, fName, \"ContactElements_TypeId\");\n    int Points_TypeId = ncReadAtt<int>(&dataFile, fName, \"Points_TypeId\");\n    int num_Tags = ncReadAtt<int>(&dataFile, fName, \"num_Tags\");\n\n    // Verify size and rank\n    if (mpiInfo->size != mpi_size) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' can only be read on \" << mpi_size\n            << \" CPUs. Currently running: \" << mpiInfo->size;\n        throw FinleyException(msg.str());\n    }\n    if (mpiInfo->rank != mpi_rank) {\n        stringstream msg;\n        msg << \"loadMesh: The NetCDF file '\" << fName\n            << \"' should be read on CPU #\" << mpi_rank\n            << \" and NOT on #\" << mpiInfo->rank;\n        throw FinleyException(msg.str());\n    }\n\n    // Read mesh name\n    if (! (attr=dataFile.get_att(\"Name\")) ) {\n        stringstream msg;\n        msg << \"loadMesh: Error retrieving mesh name from NetCDF file '\"\n            << fName << \"'\";\n        throw IOError(msg.str());\n    }\n    boost::scoped_array<char> name(attr->as_string(0));\n    delete attr;\n\n    // allocate mesh\n    FinleyDomain* dom = new FinleyDomain(name.get(), numDim, mpiInfo);\n\n    // read nodes\n    NodeFile* nodes = dom->getNodes();\n    nodes->allocTable(numNodes);\n    // Nodes_Id\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_Id\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_Id)\");\n    if (! nc_var_temp->get(&nodes->Id[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_Id)\");\n    // Nodes_Tag\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_Tag\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_Tag)\");\n    if (! nc_var_temp->get(&nodes->Tag[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_Tag)\");\n    // Nodes_gDOF\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_gDOF\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_gDOF)\");\n    if (! nc_var_temp->get(&nodes->globalDegreesOfFreedom[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_gDOF)\");\n    // Nodes_gNI\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_gNI\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_gNI)\");\n    if (! nc_var_temp->get(&nodes->globalNodesIndex[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_gNI)\");\n    // Nodes_grDfI\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_grDfI\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_grDfI)\");\n    if (! nc_var_temp->get(&nodes->globalReducedDOFIndex[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_grDfI)\");\n    // Nodes_grNI\n    if (! ( nc_var_temp = dataFile.get_var(\"Nodes_grNI\")) )\n        cleanupAndThrow(dom, \"get_var(Nodes_grNI)\");\n    if (! nc_var_temp->get(&nodes->globalReducedNodesIndex[0], numNodes) )\n        cleanupAndThrow(dom, \"get(Nodes_grNI)\");\n    // Nodes_Coordinates\n    if (!(nc_var_temp = dataFile.get_var(\"Nodes_Coordinates\")))\n        cleanupAndThrow(dom, \"get_var(Nodes_Coordinates)\");\n    if (! nc_var_temp->get(&nodes->Coordinates[0], numNodes, numDim) )\n        cleanupAndThrow(dom, \"get(Nodes_Coordinates)\");\n\n    nodes->updateTagList();\n\n    // read elements\n    const_ReferenceElementSet_ptr refElements(new ReferenceElementSet(\n                (ElementTypeId)Elements_TypeId, order, reduced_order));\n    ElementFile* elements = new ElementFile(refElements, mpiInfo);\n    dom->setElements(elements);\n    elements->allocTable(num_Elements);\n    elements->minColor = 0;\n    elements->maxColor = num_Elements-1;\n    if (num_Elements > 0) {\n       // Elements_Id\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Id\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Id)\");\n       if (! nc_var_temp->get(&elements->Id[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Id)\");\n       // Elements_Tag\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Tag\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Tag)\");\n       if (! nc_var_temp->get(&elements->Tag[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Tag)\");\n       // Elements_Owner\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Owner\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Owner)\");\n       if (! nc_var_temp->get(&elements->Owner[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Owner)\");\n       // Elements_Color\n       if (! ( nc_var_temp = dataFile.get_var(\"Elements_Color\")) )\n           cleanupAndThrow(dom, \"get_var(Elements_Color)\");\n       if (! nc_var_temp->get(&elements->Color[0], num_Elements) )\n           cleanupAndThrow(dom, \"get(Elements_Color)\");\n       // Now we need to adjust maxColor\n       index_t mc = elements->Color[0];\n       for (index_t i = 1; i < num_Elements; ++i) {\n           if (mc < elements->Color[i]) {\n               mc = elements->Color[i];\n           }\n       }\n       elements->maxColor = mc;\n       // Elements_Nodes\n       int* Elements_Nodes = new int[num_Elements*num_Elements_numNodes];\n       if (!(nc_var_temp = dataFile.get_var(\"Elements_Nodes\"))) {\n           delete[] Elements_Nodes;\n           cleanupAndThrow(dom, \"get_var(Elements_Nodes)\");\n       }\n       if (! nc_var_temp->get(&Elements_Nodes[0], num_Elements, num_Elements_numNodes) ) {\n           delete[] Elements_Nodes;\n           cleanupAndThrow(dom, \"get(Elements_Nodes)\");\n       }\n\n       // Copy temp array into elements->Nodes\n       for (index_t i = 0; i < num_Elements; i++) {\n           for (int j = 0; j < num_Elements_numNodes; j++) {\n               elements->Nodes[INDEX2(j,i,num_Elements_numNodes)]\n                    = Elements_Nodes[INDEX2(j,i,num_Elements_numNodes)];\n           }\n       }\n       delete[] Elements_Nodes;\n    } // num_Elements > 0\n    elements->updateTagList();\n\n    // get the face elements\n    const_ReferenceElementSet_ptr refFaceElements(\n            new ReferenceElementSet((ElementTypeId)FaceElements_TypeId,\n                order, reduced_order));\n    ElementFile* faces = new ElementFile(refFaceElements, mpiInfo);\n    dom->setFaceElements(faces);\n    faces->allocTable(num_FaceElements);\n    faces->minColor = 0;\n    faces->maxColor = num_FaceElements-1;\n    if (num_FaceElements > 0) {\n        // FaceElements_Id\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Id\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Id)\");\n        if (! nc_var_temp->get(&faces->Id[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Id)\");\n        // FaceElements_Tag\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Tag\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Tag)\");\n        if (! nc_var_temp->get(&faces->Tag[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Tag)\");\n        // FaceElements_Owner\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Owner\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Owner)\");\n        if (! nc_var_temp->get(&faces->Owner[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Owner)\");\n        // FaceElements_Color\n        if (! ( nc_var_temp = dataFile.get_var(\"FaceElements_Color\")) )\n            cleanupAndThrow(dom, \"get_var(FaceElements_Color)\");\n        if (! nc_var_temp->get(&faces->Color[0], num_FaceElements) )\n            cleanupAndThrow(dom, \"get(FaceElements_Color)\");\n        // Now we need to adjust maxColor\n        index_t mc = faces->Color[0];\n        for (index_t i = 1; i < num_FaceElements; ++i) {\n            if (mc < faces->Color[i]) {\n                mc = faces->Color[i];\n            }\n        }\n        faces->maxColor = mc;\n        // FaceElements_Nodes\n        int* FaceElements_Nodes = new int[num_FaceElements*num_FaceElements_numNodes];\n        if (!(nc_var_temp = dataFile.get_var(\"FaceElements_Nodes\"))) {\n            delete[] FaceElements_Nodes;\n            cleanupAndThrow(dom, \"get_var(FaceElements_Nodes)\");\n        }\n        if (! nc_var_temp->get(&(FaceElements_Nodes[0]), num_FaceElements, num_FaceElements_numNodes) ) {\n            delete[] FaceElements_Nodes;\n            cleanupAndThrow(dom, \"get(FaceElements_Nodes)\");\n        }\n        // Copy temp array into faces->Nodes\n        for (index_t i = 0; i < num_FaceElements; i++) {\n            for (int j = 0; j < num_FaceElements_numNodes; j++) {\n                faces->Nodes[INDEX2(j,i,num_FaceElements_numNodes)] = FaceElements_Nodes[INDEX2(j,i,num_FaceElements_numNodes)];\n            }\n        }\n        delete[] FaceElements_Nodes;\n    } // num_FaceElements > 0\n    faces->updateTagList();\n\n    // get the Contact elements\n    const_ReferenceElementSet_ptr refContactElements(\n         new ReferenceElementSet((ElementTypeId)ContactElements_TypeId,\n             order, reduced_order));\n    ElementFile* contacts = new ElementFile(refContactElements, mpiInfo);\n    dom->setContactElements(contacts);\n    contacts->allocTable(num_ContactElements);\n    contacts->minColor = 0;\n    contacts->maxColor = num_ContactElements-1;\n    if (num_ContactElements > 0) {\n        // ContactElements_Id\n        if (! ( nc_var_temp = dataFile.get_var(\"ContactElements_Id\")) )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Id)\");\n        if (! nc_var_temp->get(&contacts->Id[0], num_ContactElements) )\n            cleanupAndThrow(dom, \"get(ContactElements_Id)\");\n        // ContactElements_Tag\n        if (! ( nc_var_temp = dataFile.get_var(\"ContactElements_Tag\")) )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Tag)\");\n        if (! nc_var_temp->get(&contacts->Tag[0], num_ContactElements) )\n            cleanupAndThrow(dom, \"get(ContactElements_Tag)\");\n        // ContactElements_Owner\n        if (! ( nc_var_temp = dataFile.get_var(\"ContactElements_Owner\")) )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Owner)\");\n        if (! nc_var_temp->get(&contacts->Owner[0], num_ContactElements) )\n            cleanupAndThrow(dom, \"get(ContactElements_Owner)\");\n        // ContactElements_Color\n        if (! ( nc_var_temp = dataFile.get_var(\"ContactElements_Color\")) )\n            cleanupAndThrow(dom, \"get_var(ContactElements_Color)\");\n        if (! nc_var_temp->get(&contacts->Color[0], num_ContactElements) )\n            cleanupAndThrow(dom, \"get(ContactElements_Color)\");\n        // Now we need to adjust maxColor\n        index_t mc = contacts->Color[0];\n        for (index_t i = 1; i < num_ContactElements; ++i) {\n            if (mc < contacts->Color[i]) {\n                mc = contacts->Color[i];\n            }\n        }\n        contacts->maxColor = mc;\n        // ContactElements_Nodes\n        int* ContactElements_Nodes = new int[num_ContactElements*num_ContactElements_numNodes];\n        if (!(nc_var_temp = dataFile.get_var(\"ContactElements_Nodes\"))) {\n            delete[] ContactElements_Nodes;\n            cleanupAndThrow(dom, \"get_var(ContactElements_Nodes)\");\n        }\n        if (! nc_var_temp->get(&ContactElements_Nodes[0], num_ContactElements, num_ContactElements_numNodes) ) {\n            delete[] ContactElements_Nodes;\n            cleanupAndThrow(dom, \"get(ContactElements_Nodes)\");\n        }\n        // Copy temp array into contacts->Nodes\n        for (index_t i = 0; i < num_ContactElements; i++) {\n            for (int j = 0; j < num_ContactElements_numNodes; j++) {\n                contacts->Nodes[INDEX2(j,i,num_ContactElements_numNodes)] = ContactElements_Nodes[INDEX2(j,i,num_ContactElements_numNodes)];\n            }\n        }\n        delete[] ContactElements_Nodes;\n    } // num_ContactElements > 0\n    contacts->updateTagList();\n\n    // get the Points (nodal elements)\n    const_ReferenceElementSet_ptr refPoints(new ReferenceElementSet(\n                (ElementTypeId)Points_TypeId, order, reduced_order));\n    ElementFile* points = new ElementFile(refPoints, mpiInfo);\n    dom->setPoints(points);\n    points->allocTable(num_Points);\n    points->minColor = 0;\n    points->maxColor = num_Points-1;\n    if (num_Points > 0) {\n        // Points_Id\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Id\")))\n            cleanupAndThrow(dom, \"get_var(Points_Id)\");\n        if (! nc_var_temp->get(&points->Id[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Id)\");\n        // Points_Tag\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Tag\")))\n            cleanupAndThrow(dom, \"get_var(Points_Tag)\");\n        if (! nc_var_temp->get(&points->Tag[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Tag)\");\n        // Points_Owner\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Owner\")))\n            cleanupAndThrow(dom, \"get_var(Points_Owner)\");\n        if (!nc_var_temp->get(&points->Owner[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Owner)\");\n        // Points_Color\n        if (! ( nc_var_temp = dataFile.get_var(\"Points_Color\")))\n            cleanupAndThrow(dom, \"get_var(Points_Color)\");\n        if (!nc_var_temp->get(&points->Color[0], num_Points))\n            cleanupAndThrow(dom, \"get(Points_Color)\");\n        // Now we need to adjust maxColor\n        index_t mc = points->Color[0];\n        for (index_t i = 1; i < num_Points; ++i) {\n            if (mc < points->Color[i]) {\n                mc = points->Color[i];\n            }\n        }\n        points->maxColor = mc;\n        // Points_Nodes\n        int* Points_Nodes = new int[num_Points];\n        if (!(nc_var_temp = dataFile.get_var(\"Points_Nodes\"))) {\n            delete[] Points_Nodes;\n            cleanupAndThrow(dom, \"get_var(Points_Nodes)\");\n        }\n        if (! nc_var_temp->get(&Points_Nodes[0], num_Points) ) {\n            delete[] Points_Nodes;\n            cleanupAndThrow(dom, \"get(Points_Nodes)\");\n        }\n        // Copy temp array into points->Nodes\n        for (index_t i = 0; i < num_Points; i++) {\n            points->Id[points->Nodes[INDEX2(0,i,1)]] = Points_Nodes[i];\n        }\n        delete[] Points_Nodes;\n    } // num_Points > 0\n    points->updateTagList();\n\n    // get the tags\n    if (num_Tags > 0) {\n        // Temp storage to gather node IDs\n        int *Tags_keys = new int[num_Tags];\n        char name_temp[4096];\n        int i;\n\n        // Tags_keys\n        if (! ( nc_var_temp = dataFile.get_var(\"Tags_keys\")) ) {\n            delete[] Tags_keys;\n            cleanupAndThrow(dom, \"get_var(Tags_keys)\");\n        }\n        if (! nc_var_temp->get(&Tags_keys[0], num_Tags) ) {\n            delete[] Tags_keys;\n            cleanupAndThrow(dom, \"get(Tags_keys)\");\n        }\n        for (i=0; i<num_Tags; i++) {\n          // Retrieve tag name\n          sprintf(name_temp, \"Tags_name_%d\", i);\n          if (! (attr=dataFile.get_att(name_temp)) ) {\n              delete[] Tags_keys;\n              stringstream msg;\n              msg << \"get_att(\" << name_temp << \")\";\n              cleanupAndThrow(dom, msg.str());\n          }\n          boost::scoped_array<char> name(attr->as_string(0));\n          delete attr;\n          dom->setTagMap(name.get(), Tags_keys[i]);\n        }\n        delete[] Tags_keys;\n    }\n\n    // Nodes_DofDistribution\n    IndexVector first_DofComponent(mpi_size+1);\n    if (! (nc_var_temp = dataFile.get_var(\"Nodes_DofDistribution\")) ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_DofDistribution)\");\n    }\n    if (!nc_var_temp->get(&first_DofComponent[0], mpi_size+1)) {\n        cleanupAndThrow(dom, \"get(Nodes_DofDistribution)\");\n    }\n\n    // Nodes_NodeDistribution\n    IndexVector first_NodeComponent(mpi_size+1);\n    if (! (nc_var_temp = dataFile.get_var(\"Nodes_NodeDistribution\")) ) {\n        cleanupAndThrow(dom, \"get_var(Nodes_NodeDistribution)\");\n    }\n    if (!nc_var_temp->get(&first_NodeComponent[0], mpi_size+1)) {\n        cleanupAndThrow(dom, \"get(Nodes_NodeDistribution)\");\n    }\n    dom->createMappings(first_DofComponent, first_NodeComponent);\n\n    return dom->getPtr();\n#else\n    throw FinleyException(\"loadMesh: not compiled with NetCDF. Please contact your installation manager.\");\n#endif // ESYS_HAVE_NETCDF\n}\n\n#endif\n\nDomain_ptr readMesh_driver(const bp::list& args)\n{\n    int l = len(args);\n    if (l < 7) {\n        throw ValueError(\"Insufficient arguments to readMesh_driver\");\n    }\n    string fileName = bp::extract<string>(args[0])();\n    int integrationOrder = bp::extract<int>(args[1])();\n    int reducedIntegrationOrder = bp::extract<int>(args[2])();\n    bool optimize = bp::extract<bool>(args[3])();\n    vector<double> points;\n    vector<int> tags;\n\n    // we need to convert lists to stl vectors\n    bp::list pypoints = bp::extract<bp::list>(args[4]);\n    bp::list pytags = bp::extract<bp::list>(args[5]);\n    int numpts = bp::extract<int>(pypoints.attr(\"__len__\")());\n    int numtags = bp::extract<int>(pytags.attr(\"__len__\")());\n\n    bp::object pworld = args[6];\n    JMPI info;\n    if (!pworld.is_none()) {\n        bp::extract<SubWorld_ptr> ex(pworld);\n        if (!ex.check()) {\n            throw ValueError(\"Invalid escriptWorld parameter.\");\n        }\n        info = ex()->getMPI();\n    } else {\n        info = makeInfo(MPI_COMM_WORLD);\n    }\n    Domain_ptr dom(FinleyDomain::read(info, fileName, integrationOrder,\n                                      reducedIntegrationOrder, optimize));\n\n    FinleyDomain* fd = dynamic_cast<FinleyDomain*>(dom.get());\n\n    for (int i = 0; i < numpts; ++i) {\n        bp::object temp = pypoints[i];\n        int l = bp::extract<int>(temp.attr(\"__len__\")());\n        for (int k = 0; k < l; ++k) {\n              points.push_back(bp::extract<double>(temp[k]));\n        }\n    }\n    // bricks use up to 200 but the existing tag check will find that\n    int curmax = 40;\n    const TagMap& tagmap = fd->getTagMap();\n    // first we work out what tags are already in use\n    for (TagMap::const_iterator it = tagmap.begin(); it != tagmap.end(); ++it) {\n        if (it->second > curmax) {\n            curmax = it->second+1;\n        }\n    }\n\n    tags.resize(numtags, -1);\n    for (int i = 0; i < numtags; ++i) {\n        bp::extract<int> ex_int(pytags[i]);\n        bp::extract<string> ex_str(pytags[i]);\n        if (ex_int.check()) {\n            tags[i] = ex_int();\n            if (tags[i] >= curmax) {\n                curmax = tags[i]+1;\n            }\n        } else if (ex_str.check()) {\n            string s = ex_str();\n            TagMap::const_iterator it = tagmap.find(s);\n            if (it != tagmap.end()) {\n                // we have the tag already so look it up\n                tags[i] = it->second;\n            } else {\n                fd->setTagMap(s, curmax);\n                tags[i] = curmax;\n                curmax++;\n            }\n        } else {\n            throw FinleyException(\"Unable to extract tag value.\");\n        }\n    }\n    // now we need to add the dirac points\n    fd->addDiracPoints(points, tags);\n    return dom;\n}\n\nDomain_ptr readGmsh_driver(const bp::list& args)\n{\n    int l = len(args);\n    if (l < 7) {\n        throw ValueError(\"Insufficient arguments to readMesh_driver\");\n    }\n    string fileName = bp::extract<string>(args[0])();\n    int numDim = bp::extract<int>(args[1])();\n    int integrationOrder = bp::extract<int>(args[2])();\n    int reducedIntegrationOrder = bp::extract<int>(args[3])();\n    bool optimize = bp::extract<bool>(args[4])();\n    bool useMacroElements = bp::extract<bool>(args[5])();\n    vector<double> points;\n    vector<int> tags;\n\n    // we need to convert lists to stl vectors\n    bp::list pypoints = bp::extract<bp::list>(args[6]);\n    bp::list pytags = bp::extract<bp::list>(args[7]);\n    int numpts = bp::extract<int>(pypoints.attr(\"__len__\")());\n    int numtags = bp::extract<int>(pytags.attr(\"__len__\")());\n    bp::object pworld = args[8];\n    JMPI info;\n    if (!pworld.is_none()) {\n        bp::extract<SubWorld_ptr> ex(pworld);\n        if (!ex.check()) {\n            throw ValueError(\"Invalid escriptWorld parameter.\");\n        }\n        info = ex()->getMPI();\n    } else {\n        info = makeInfo(MPI_COMM_WORLD);\n    }\n    Domain_ptr dom(FinleyDomain::readGmsh(info, fileName, numDim,\n                                     integrationOrder, reducedIntegrationOrder,\n                                     optimize, useMacroElements));\n    FinleyDomain* fd = dynamic_cast<FinleyDomain*>(dom.get());\n\n    for (int i = 0; i < numpts; ++i) {\n        bp::object temp = pypoints[i];\n        int l = bp::extract<int>(temp.attr(\"__len__\")());\n        for (int k = 0; k < l; ++k) {\n            points.push_back(bp::extract<double>(temp[k]));\n        }\n    }\n    int curmax = 40; // bricks use up to 30\n    const TagMap& tagmap = fd->getTagMap();\n    // first we work out what tags are already in use\n    for (TagMap::const_iterator it = tagmap.begin(); it != tagmap.end(); ++it) {\n        if (it->second > curmax) {\n            curmax = it->second+1;\n        }\n    }\n\n    tags.resize(numtags, -1);\n    for (int i = 0; i < numtags; ++i) {\n        bp::extract<int> ex_int(pytags[i]);\n        bp::extract<string> ex_str(pytags[i]);\n        if (ex_int.check()) {\n            tags[i] = ex_int();\n            if (tags[i] >= curmax) {\n                curmax = tags[i]+1;\n            }\n        } else if (ex_str.check()) {\n            string s = ex_str();\n            TagMap::const_iterator it = tagmap.find(s);\n            if (it != tagmap.end()) {\n                // we have the tag already so look it up\n                tags[i] = it->second;\n            } else {\n                fd->setTagMap(s, curmax);\n                tags[i] = curmax;\n                curmax++;\n            }\n        } else {\n            throw FinleyException(\"Unable to extract tag value\");\n        }\n    }\n    // now we need to add the dirac points\n    fd->addDiracPoints(points, tags);\n    return dom;\n}\n\nDomain_ptr brick(JMPI info, dim_t n0, dim_t n1, dim_t n2, int order,\n                 double l0, double l1, double l2,\n                 bool periodic0, bool periodic1, bool periodic2,\n                 int integrationOrder, int reducedIntegrationOrder,\n                 bool useElementsOnFace, bool useFullElementOrder,\n                 bool optimize, const std::vector<double>& points,\n                 const std::vector<int>& tags,\n                 const std::map<std::string, int>& tagNamesToNums)\n{\n    Domain_ptr dom;\n    if (order == 1) {\n        dom = FinleyDomain::createHex8(n0, n1, n2, l0, l1, l2, periodic0,\n                   periodic1, periodic2, integrationOrder,\n                   reducedIntegrationOrder, useElementsOnFace, optimize, info);\n    } else if (order == 2) {\n        dom = FinleyDomain::createHex20(n0, n1, n2, l0, l1, l2, periodic0,\n                                   periodic1, periodic2, integrationOrder,\n                                   reducedIntegrationOrder, useElementsOnFace,\n                                   useFullElementOrder, false, optimize, info);\n    } else if (order == -1) {\n        dom = FinleyDomain::createHex20(n0, n1, n2, l0, l1, l2, periodic0,\n                                   periodic1, periodic2, integrationOrder,\n                                   reducedIntegrationOrder, useElementsOnFace,\n                                   useFullElementOrder, true, optimize, info);\n    } else {\n        stringstream message;\n        message << \"Illegal interpolation order \" << order;\n        throw ValueError(message.str());\n    }\n\n    FinleyDomain* fd = dynamic_cast<FinleyDomain*>(dom.get());\n    fd->addDiracPoints(points, tags);\n    for (TagMap::const_iterator it = tagNamesToNums.begin(); it != tagNamesToNums.end(); ++it) {\n        fd->setTagMap(it->first, it->second);\n    }\n    fd->getPoints()->updateTagList();\n    return dom;\n}\n\nDomain_ptr brick_driver(const bp::list& args)\n{\n    // we need to convert lists to stl vectors\n    bp::list pypoints = bp::extract<bp::list>(args[15]);\n    bp::list pytags = bp::extract<bp::list>(args[16]);\n    int numpts = bp::extract<int>(pypoints.attr(\"__len__\")());\n    int numtags = bp::extract<int>(pytags.attr(\"__len__\")());\n    vector<double> points;\n    vector<int> tags;\n    tags.resize(numtags, -1);\n    for (int i = 0; i < numpts; ++i) {\n        bp::object temp = pypoints[i];\n        int l = bp::extract<int>(temp.attr(\"__len__\")());\n        for (int k = 0; k < l; ++k) {\n            points.push_back(bp::extract<double>(temp[k]));\n        }\n    }\n    map<string, int> namestonums;\n    int curmax = 40; // bricks use up to 30\n    for (int i = 0; i < numtags; ++i) {\n        bp::extract<int> ex_int(pytags[i]);\n        bp::extract<string> ex_str(pytags[i]);\n        if (ex_int.check()) {\n            tags[i] = ex_int();\n            if (tags[i] >= curmax) {\n                curmax = tags[i]+1;\n            }\n        } else if (ex_str.check()) {\n            string s = ex_str();\n            TagMap::iterator it = namestonums.find(s);\n            if (it != namestonums.end()) {\n                // we have the tag already so look it up\n                tags[i] = it->second;\n            } else {\n                namestonums[s] = curmax;\n                tags[i] = curmax;\n                curmax++;\n            }\n        } else {\n            throw FinleyException(\"Unable to extract tag value.\");\n        }\n    }\n    bp::object pworld = args[17];\n    JMPI info;\n    if (!pworld.is_none()) {\n        bp::extract<SubWorld_ptr> ex(pworld);\n        if (!ex.check()) {\n            throw ValueError(\"Invalid escriptWorld parameter.\");\n        }\n        info = ex()->getMPI();\n    } else {\n        info = makeInfo(MPI_COMM_WORLD);\n    }\n    return brick(info, static_cast<dim_t>(bp::extract<float>(args[0])),\n                 static_cast<dim_t>(bp::extract<float>(args[1])),\n                 static_cast<dim_t>(bp::extract<float>(args[2])),\n                 bp::extract<int>(args[3]), bp::extract<double>(args[4]),\n                 bp::extract<double>(args[5]), bp::extract<double>(args[6]),\n                 bp::extract<int>(args[7]), bp::extract<int>(args[8]),\n                 bp::extract<int>(args[9]), bp::extract<int>(args[10]),\n                 bp::extract<int>(args[11]), bp::extract<int>(args[12]),\n                 bp::extract<int>(args[13]), bp::extract<int>(args[14]),\n                 points, tags, namestonums);\n}\n\nDomain_ptr rectangle(JMPI info, dim_t n0, dim_t n1, int order,\n                     double l0, double l1, bool periodic0, bool periodic1,\n                     int integrationOrder, int reducedIntegrationOrder,\n                     bool useElementsOnFace, bool useFullElementOrder,\n                     bool optimize, const vector<double>& points,\n                     const vector<int>& tags,\n                     const std::map<std::string, int>& tagNamesToNums)\n{\n    Domain_ptr dom;\n    if (order == 1) {\n        dom = FinleyDomain::createRec4(n0, n1, l0, l1, periodic0, periodic1,\n                                     integrationOrder, reducedIntegrationOrder,\n                                     useElementsOnFace, optimize, info);\n    } else if (order == 2) {\n        dom = FinleyDomain::createRec8(n0, n1, l0, l1, periodic0, periodic1,\n                 integrationOrder, reducedIntegrationOrder,\n                 useElementsOnFace,useFullElementOrder, false, optimize, info);\n    } else if (order == -1) {\n        dom = FinleyDomain::createRec8(n0, n1, l0, l1, periodic0, periodic1,\n                 integrationOrder, reducedIntegrationOrder,\n                 useElementsOnFace, useFullElementOrder, true, optimize, info);\n    } else {\n        stringstream message;\n        message << \"Illegal interpolation order \" << order;\n        throw ValueError(message.str());\n    }\n\n    FinleyDomain* fd = dynamic_cast<FinleyDomain*>(dom.get());\n    fd->addDiracPoints(points, tags);\n    for (TagMap::const_iterator it = tagNamesToNums.begin(); it != tagNamesToNums.end(); ++it)\n    {\n        fd->setTagMap(it->first, it->second);\n    }\n    fd->getPoints()->updateTagList();\n    return dom;\n}\n\nDomain_ptr rectangle_driver(const bp::list& args)\n{\n    // we need to convert lists to stl vectors\n    bp::list pypoints = bp::extract<bp::list>(args[12]);\n    bp::list pytags = bp::extract<bp::list>(args[13]);\n    int numpts = bp::extract<int>(pypoints.attr(\"__len__\")());\n    int numtags = bp::extract<int>(pytags.attr(\"__len__\")());\n    vector<double> points;\n    vector<int> tags;\n    tags.resize(numtags, -1);\n    for (int i = 0; i < numpts; ++i) {\n        bp::object temp = pypoints[i];\n        int l = bp::extract<int>(temp.attr(\"__len__\")());\n        for (int k = 0; k < l; ++k) {\n            points.push_back(bp::extract<double>(temp[k]));\n        }\n    }\n    TagMap tagstonames;\n    int curmax = 40;\n    // but which order to assign tags to names?????\n    for (int i = 0; i < numtags; ++i) {\n        bp::extract<int> ex_int(pytags[i]);\n        bp::extract<string> ex_str(pytags[i]);\n        if (ex_int.check()) {\n            tags[i] = ex_int();\n            if (tags[i] >= curmax) {\n                curmax = tags[i]+1;\n            }\n        } else if (ex_str.check()) {\n            string s = ex_str();\n            TagMap::iterator it = tagstonames.find(s);\n            if (it != tagstonames.end()) {\n                // we have the tag already so look it up\n                tags[i] = it->second;\n            } else {\n                tagstonames[s] = curmax;\n                tags[i] = curmax;\n                curmax++;\n            }\n        } else {\n            throw FinleyException(\"Unable to extract tag value.\");\n        }\n    }\n    bp::object pworld = args[14];\n    JMPI info;\n    if (!pworld.is_none()) {\n        bp::extract<SubWorld_ptr> ex(pworld);\n        if (!ex.check()) {\n            throw ValueError(\"Invalid escriptWorld parameter.\");\n        }\n        info = ex()->getMPI();\n    } else {\n        info = makeInfo(MPI_COMM_WORLD);\n    }\n\n    return rectangle(info, static_cast<dim_t>(bp::extract<float>(args[0])),\n                     static_cast<dim_t>(bp::extract<float>(args[1])),\n                     bp::extract<int>(args[2]), bp::extract<double>(args[3]),\n                     bp::extract<double>(args[4]), bp::extract<int>(args[5]),\n                     bp::extract<int>(args[6]), bp::extract<int>(args[7]),\n                     bp::extract<int>(args[8]), bp::extract<int>(args[9]),\n                     bp::extract<int>(args[10]), bp::extract<int>(args[11]),\n                     points, tags, tagstonames);\n}\n\nDomain_ptr meshMerge(const bp::list& meshList)\n{\n    // extract the meshes from meshList\n    int num = bp::extract<int>(meshList.attr(\"__len__\")());\n    vector<const FinleyDomain*> meshes(num);\n    for (int i = 0; i < num; ++i) {\n        AbstractContinuousDomain& meshListMember = bp::extract<AbstractContinuousDomain&>(meshList[i]);\n        meshes[i] = dynamic_cast<const FinleyDomain*>(&meshListMember);\n    }\n\n    // merge the meshes\n    FinleyDomain* dom = FinleyDomain::merge(meshes);\n\n    return dom->getPtr();\n}\n\nDomain_ptr glueFaces(const bp::list& meshList, double safetyFactor,\n                     double tolerance, bool optimize)\n{\n    // merge the meshes\n    Domain_ptr merged_meshes = meshMerge(meshList);\n\n    // glue the faces\n    FinleyDomain* merged = dynamic_cast<FinleyDomain*>(merged_meshes.get());\n    merged->glueFaces(safetyFactor, tolerance, optimize);\n    return merged_meshes;\n}\n\nDomain_ptr joinFaces(const bp::list& meshList, double safetyFactor,\n                     double tolerance, bool optimize)\n{\n    // merge the meshes\n    Domain_ptr merged_meshes = meshMerge(meshList);\n\n    // join the faces\n    FinleyDomain* merged = dynamic_cast<FinleyDomain*>(merged_meshes.get());\n    merged->joinFaces(safetyFactor, tolerance, optimize);\n    return merged_meshes;\n}\n\n} // namespace finley\n", "meta": {"hexsha": "be5debb9e148b3a265a45a09b0c6bf9a608970cd", "size": 52729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "finley/src/DomainFactory.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "finley/src/DomainFactory.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "finley/src/DomainFactory.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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.1897865854, "max_line_length": 140, "alphanum_fraction": 0.6007699748, "num_tokens": 13393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.03846618802254169, "lm_q1q2_score": 0.011317328438268395}}
{"text": "/*\n *  python.cpp\n *\n *   Created on: 21-may-2018\n *       Author: M. El-Kebir\n */\n\n#include <boost/scoped_array.hpp>\n#include <boost/python.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <armadillo>\n#include <iostream>\n#include <fstream>\n#include \"utils.h\"\n#include \"simulation.h\"\n#include \"mutclonetree.h\"\n#include \"readmatrix.h\"\n#include \"generatemixture.h\"\n#include \"enumeratemutationtrees.h\"\n\nnamespace p = boost::python;\n\ntemplate<typename T>\ninline\nstd::vector< T > py_list_to_std_vector( const boost::python::object& iterable )\n{\n  return std::vector< T >( boost::python::stl_input_iterator< T >( iterable ),\n                          boost::python::stl_input_iterator< T >( ) );\n}\n\nvoid simulate(std::string outputDirectory = \".\",\n              p::dict args = p::dict())\n{\n  std::string filenameColorMap;\n  int seed = 0;\n  double carryingCapacity = 5e4;\n  double mutFreqThreshold = 0.05;\n  double migrationRate = 1e-6;\n  double mutationRate = 0.1;\n  double driverRate = 2e-7;\n  int maxNrAnatomicalSites = 3;\n  int migrationPattern = 0;\n  int nrTrials = -1;\n  int desiredNrMutationClusters = -1;\n  int sequencingDepth = 200;\n  int nrSamplesPerAnatomicalSite = 2;\n  int nrSamplesPrimary = 2;\n  double sequencingErrorRate = 0;\n  double purity = 1;\n  bool verbose = false;\n  \n  for (const std::string& key : py_list_to_std_vector<std::string>(args.keys()))\n  {\n    if (key == \"seed\")\n    {\n      seed = p::extract<int>(args.get(key));\n    }\n    else if (key == \"carryingCapacity\")\n    {\n      carryingCapacity = p::extract<double>(args.get(key));\n    }\n    else if (key == \"mutFreqThreshold\")\n    {\n      mutFreqThreshold = p::extract<double>(args.get(key));\n    }\n    else if (key == \"migrationRate\")\n    {\n      migrationRate = p::extract<double>(args.get(key));\n    }\n    else if (key == \"mutationRate\")\n    {\n      mutationRate = p::extract<double>(args.get(key));\n    }\n    else if (key == \"driverRate\")\n    {\n      driverRate = p::extract<double>(args.get(key));\n    }\n    else if (key == \"maxNrAnatomicalSites\")\n    {\n      maxNrAnatomicalSites = p::extract<int>(args.get(key));\n    }\n    else if (key == \"migrationPattern\")\n    {\n      migrationPattern = p::extract<int>(args.get(key));\n    }\n    else if (key == \"nrTrials\")\n    {\n      nrTrials = p::extract<int>(args.get(key));\n    }\n    else if (key == \"desiredNrMutationClusters\")\n    {\n      desiredNrMutationClusters = p::extract<int>(args.get(key));\n    }\n    else if (key == \"sequencingDepth\")\n    {\n      sequencingDepth = p::extract<int>(args.get(key));\n    }\n    else if (key == \"nrSamplesPerAnatomicalSite\")\n    {\n      nrSamplesPerAnatomicalSite = p::extract<int>(args.get(key));\n    }\n    else if (key == \"nrSamplesPrimary\")\n    {\n      nrSamplesPrimary = p::extract<int>(args.get(key));\n    }\n    else if (key == \"sequencingErrorRate\")\n    {\n      sequencingErrorRate = p::extract<double>(args.get(key));\n    }\n    else if (key == \"purity\")\n    {\n      purity = p::extract<double>(args.get(key));\n    }\n    else if (key == \"filenameColorMap\u0010\")\n    {\n      filenameColorMap = p::extract<std::string>(args.get(key));\n    }\n    else if (key == \"verbose\")\n    {\n      verbose = p::extract<bool>(args.get(key));\n    }\n  }\n  \n  Simulation::run(outputDirectory, filenameColorMap,\n                  seed, carryingCapacity, mutFreqThreshold,\n                  migrationRate, mutationRate, driverRate,\n                  maxNrAnatomicalSites, migrationPattern,\n                  nrTrials, desiredNrMutationClusters,\n                  sequencingDepth, nrSamplesPerAnatomicalSite, nrSamplesPrimary,\n                  sequencingErrorRate, purity, verbose);\n}\n\nstd::string visualizeMigrationGraph(std::string filenameInGraph,\n                                    std::string filenameInColorMap = \"\")\n{\n  std::ifstream inG(filenameInGraph);\n  if (!inG.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\"\n                             + filenameInGraph + \"' for reading\");\n  }\n  \n  MigrationGraph G;\n  if (!G.read(inG))\n  {\n    throw std::runtime_error(\"Error: invalid format '\"\n                             + filenameInGraph + \"'\");\n  }\n  \n  StringToIntMap colorMap;\n  if (!filenameInColorMap.empty())\n  {\n    std::ifstream inColorMap(filenameInColorMap.c_str());\n    if (!inColorMap.good())\n    {\n      throw std::runtime_error(\"Error: could not open '\"\n                               + filenameInColorMap + \"' for reading\");\n    }\n    if (!BaseTree::readColorMap(inColorMap, colorMap))\n    {\n      throw std::runtime_error(\"Error: error parsing '\"\n                               + filenameInColorMap + \"'\");\n    }\n  }\n  else\n  {\n    colorMap = G.generateColorMap();\n  }\n  \n  std::stringstream ss;\n  \n  G.writeDOT(ss, colorMap);\n  \n  return ss.str();\n}\n\nstd::string visualizeCloneTree(std::string filenameInTree,\n                               std::string filenameInColorMap = \"\",\n                               std::string filenameInVertexLabeling = \"\")\n{\n  std::ifstream inT(filenameInTree.c_str());\n  if (!inT.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\"\n                             + filenameInTree + \"' for reading\");\n  }\n  \n  MutCloneTree T;\n  inT >> T;\n\n  StringToIntMap colorMap;\n  if (!filenameInColorMap.empty())\n  {\n    std::ifstream inColorMap(filenameInColorMap.c_str());\n    if (!inColorMap.good())\n    {\n      throw std::runtime_error(\"Error: could not open '\"\n                               + filenameInColorMap + \"' for reading\");\n    }\n    if (!BaseTree::readColorMap(inColorMap, colorMap))\n    {\n      throw std::runtime_error(\"Error: error parsing '\"\n                               + filenameInColorMap + \"'\");\n    }\n  }\n  else\n  {\n    colorMap = T.generateColorMap();\n  }\n  \n  std::stringstream ss;\n  \n  if (filenameInVertexLabeling.empty())\n  {\n    T.writeDOT(ss, colorMap);\n  }\n  else\n  {\n    std::ifstream inVertexLabeling(filenameInVertexLabeling.c_str());\n    if (!inVertexLabeling.good())\n    {\n      throw std::runtime_error(\"Error: could not open '\"\n                               + filenameInVertexLabeling\n                               + \"' for reading\");\n    }\n    \n    StringNodeMap lPlus(T.tree());\n    if (!T.readVertexLabeling(inVertexLabeling, T, lPlus))\n    {\n      throw std::runtime_error(\"Error: error parsing '\"\n                               + filenameInVertexLabeling + \"'\");\n    }\n    \n    T.writeDOT(ss, lPlus, colorMap);\n  }\n  \n  return ss.str();\n}\n\nvoid mix(const std::string& filenameInTree,\n         const std::string& filenameOutTree,\n         int k,\n         bool partition,\n         int seed = 0)\n{\n  std::ifstream inT(filenameInTree.c_str());\n  if (!inT.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTree + \"' for reading\");\n  }\n  \n  MutCloneTree T;\n  inT >> T;\n\n  g_rng = std::mt19937(seed);\n  MutCloneTree sampledT = GenerateMixture(T).generate(k, partition);\n  \n  std::ofstream outT(filenameOutTree.c_str());\n  outT << sampledT;\n  outT.close();\n}\n\nvoid downSample(const std::string& filenameInR,\n                const std::string& filenameOutR,\n                int nrSamplesPerAnatomicalSite,\n                int coverage,\n                int seed = 0,\n                double purity = 1,\n                double sequencingErrorRate = 0,\n                double fractionSNVs = 1)\n{\n  ReadMatrix R;\n  std::ifstream inR(filenameInR.c_str());\n  if (!inR.good())\n  {\n    throw std::runtime_error(\"Error: failed to open '\" + filenameInR + \"' for reading\");\n  }\n  inR >> R;\n  \n  g_rng = std::mt19937(seed);\n  ReadMatrix newR = R.downSample(nrSamplesPerAnatomicalSite,\n                                 coverage,\n                                 purity,\n                                 sequencingErrorRate,\n                                 fractionSNVs);\n  \n  std::ofstream outR(filenameOutR.c_str());\n  outR << newR;\n  outR.close();\n}\n\nvoid treeToFreqs(const std::string& filenameInTree,\n                 const std::string& filenameOutFreqs)\n{\n  std::ifstream inT(filenameInTree.c_str());\n  if (!inT.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTree + \"' for reading\");\n  }\n  \n  MutCloneTree T;\n  inT >> T;\n  \n  std::ofstream outF(filenameOutFreqs.c_str());\n  outF << T.getFrequencies();\n  outF.close();\n}\n\nvoid readsToFreqs(const std::string& filenameInReads,\n                  const std::string& filenameOutFreqs,\n                  double alpha)\n{\n  std::ifstream inR(filenameInReads.c_str());\n  if (!inR.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInReads + \"' for reading\");\n  }\n  \n  ReadMatrix R;\n  inR >> R;\n  inR.close();\n  \n  std::ofstream outF(filenameOutFreqs.c_str());\n  outF << R.toFrequencyMatrix(alpha, 2);\n  outF.close();\n}\n\nvoid sequence(const std::string& filenameInTree,\n              const std::string& filenameOutReads,\n              int sequencingDepth,\n              int seed = 0,\n              int ploidy = 2,\n              double purity = 1.,\n              double sequencingErrorRate = 0.)\n{\n  std::ifstream inT(filenameInTree.c_str());\n  if (!inT.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTree + \"' for reading\");\n  }\n  \n  MutCloneTree T;\n  inT >> T;\n  \n  g_rng = std::mt19937(seed);\n  \n  std::ofstream outR(filenameOutReads.c_str());\n  outR << T.getReads(purity, sequencingDepth, sequencingErrorRate, ploidy, true, true);\n  outR.close();\n}\n\nvoid precluster(const std::string& filenameInFreqs,\n                const std::string& filenameInClustering,\n                const std::string& filenameOutFreqs)\n{\n  std::ifstream inF(filenameInFreqs.c_str());\n  if (!inF.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInFreqs + \"' for reading\");\n  }\n  \n  FrequencyMatrix F;\n  inF >> F;\n  inF.close();\n  \n  std::ifstream inC(filenameInClustering.c_str());\n  if (!inC.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInClustering + \"' for reading\");\n  }\n  \n  IntMatrix clustering = F.parseClustering(inC);\n  inC.close();\n  \n  FrequencyMatrix newF = F.cluster(clustering);\n  \n  std::ofstream outF(filenameOutFreqs);\n  outF << newF;\n  outF.close();\n}\n\nvoid enumerate(const std::string& filenameInFreqs,\n               const std::string& filenameOutTrees,\n               bool spanning,\n               int nrThreads,\n               int timeLimit,\n               bool dryRun)\n{\n  std::ifstream inF(filenameInFreqs.c_str());\n  if (!inF.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInFreqs + \"' for reading\");\n  }\n  \n  FrequencyMatrix F;\n  inF >> F;\n  inF.close();\n  \n  VerbosityLevel oldVerbosity = g_verbosity;\n  g_verbosity = VERBOSE_NONE;\n\n  std::ofstream outT(filenameOutTrees.c_str());\n  \n  EnumerateMutationTrees enumerate(F);\n  enumerate.enumerate(\"\",\n                      nrThreads,\n                      -1,\n                      timeLimit,\n                      spanning,\n                      dryRun,\n                      outT);\n  \n  g_verbosity = oldVerbosity;\n  \n  outT.close();\n}\n\ndouble countSpanningTrees(const std::string& filenameInFreqs,\n                          int root = 0)\n{\n  std::ifstream inF(filenameInFreqs.c_str());\n  if (!inF.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInFreqs + \"' for reading\");\n  }\n  \n  FrequencyMatrix F;\n  inF >> F;\n  inF.close();\n  \n  EnumerateMutationTrees mutT(F);\n  \n  const Digraph& G = mutT.getAncestryGraph().G();\n  lemon::DynArcLookUp<Digraph> arcLookUp(G);\n  \n  arma::mat L(F.getNrCharacters() - 1, F.getNrCharacters() - 1);\n  \n  for (int i = 0; i < F.getNrCharacters(); ++i)\n  {\n    for (int j = 0; j < F.getNrCharacters(); ++j)\n    {\n      if (i == root || j == root)\n      {\n        continue;\n      }\n      \n      int ii = i > root ? i - 1 : i;\n      int jj = j > root ? j - 1 : j;\n      \n      if (i == j)\n      {\n        Node v_j = mutT.getAncestryGraph().charStateToNode(j, 1);\n        L(ii, jj) = lemon::countInArcs(G, v_j) - 1;\n      }\n      else\n      {\n        Node v_i = mutT.getAncestryGraph().charStateToNode(i, 1);\n        Node v_j = mutT.getAncestryGraph().charStateToNode(j, 1);\n        \n        if (arcLookUp(v_i, v_j) != lemon::INVALID)\n        {\n          L(ii, jj) = -1.;\n        }\n        else\n        {\n          L(ii, jj) = 0.;\n        }\n      }\n    }\n  }\n  \n//  std::cout << L << std::endl;\n  \n  return arma::det(L);\n}\n\nCloneTree parseNextTree(std::istream& in)\n{\n  int nrEdges = -1;\n  std::string line;\n  std::stringstream ss;\n  \n  getline(in, line);\n  ss.clear();\n  ss.str(line);\n  ss >> nrEdges;\n  \n  if (nrEdges < 0)\n  {\n    throw std::runtime_error(\"Error: number of edges should be nonnegative\");\n  }\n  \n  ss.clear();\n  ss.str(\"\");\n  for (int j = 0; j < nrEdges; ++j)\n  {\n    getline(in, line);\n    ss << line << std::endl;\n  }\n  \n  CloneTree T;\n  if (!T.read(ss))\n    throw std::runtime_error(\"\");\n  \n  return T;\n}\n\nvoid filterSCS(const std::string& filenameInInferredTrees,\n               const std::string& filenameInTrueTree,\n               const std::string& filenameOutTrees,\n               int nrClones,\n               int seed)\n{\n  // 0. parse true clone tree\n  std::ifstream inTrueTree(filenameInTrueTree.c_str());\n  if (!inTrueTree.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTrueTree + \"' for reading\");\n  }\n  \n  MutCloneTree trueT;\n  inTrueTree >> trueT;\n  inTrueTree.close();\n  \n  // 1. collect clones\n  std::vector<StringVector> clones;\n  for (Node leaf : trueT.leafSet())\n  {\n    clones.push_back(StringVector());\n    Node u = leaf;\n    while ((u = trueT.parent(u)) != trueT.root())\n    {\n      clones.back().push_back(trueT.label(u));\n    }\n  }\n  \n  g_rng = std::mt19937(seed);\n  std::shuffle(clones.begin(), clones.end(), g_rng);\n  while (clones.size() > nrClones)\n  {\n    clones.pop_back();\n  }\n  \n  // 2. parse enumerated trees\n  std::ifstream inTrees(filenameInInferredTrees.c_str());\n  if (!inTrees.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInInferredTrees + \"' for reading\");\n  }\n  \n  int nrTrees = -1;\n  std::string line;\n  while (line.empty() || line[0] == '#')\n  {\n    getline(inTrees, line);\n  }\n  std::stringstream ss(line);\n  ss >> nrTrees;\n  \n  if (nrTrees < 0)\n  {\n    throw std::runtime_error(\"Error: number of trees should be nonnegative\");\n  }\n  \n  std::ofstream outTrees(filenameOutTrees);\n  for (const StringVector& clone : clones)\n  {\n    outTrees << \"#\";\n    for (const std::string& mut : clone)\n    {\n      outTrees << \" \" << mut;\n    }\n    outTrees << std::endl;\n  }\n  \n  for (int i = 0; i < nrTrees; ++i)\n  {\n    StringPairSet diff;\n    CloneTree T = parseNextTree(inTrees);\n    \n    bool ok = true;\n    for (const StringVector& clone : clones)\n    {\n      Node u = T.getNodeByLabel(clone[0]);\n      int idx = 0;\n      while (u != lemon::INVALID && ok)\n      {\n        ok &= (idx < clone.size()) && (T.label(u) == clone[idx]);\n        u = T.parent(u);\n        ++idx;\n      }\n    }\n    \n    if (ok)\n    {\n      outTrees << lemon::countArcs(T.tree()) << \" #edges\" << std::endl;\n      T.write(outTrees);\n    }\n  }\n  outTrees.close();\n}\n\nvoid filterLR(const std::string& filenameInInferredTrees,\n              const std::string& filenameInTrueTree,\n              const std::string& filenameOutTrees,\n              int nrPairs,\n              int seed)\n{\n  // 0. parse true clone tree\n  std::ifstream inTrueTree(filenameInTrueTree.c_str());\n  if (!inTrueTree.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTrueTree + \"' for reading\");\n  }\n  \n  MutCloneTree trueT;\n  inTrueTree >> trueT;\n  inTrueTree.close();\n  \n  // 1. collect clones\n  StringPairSet ancestralPairSet = trueT.getAncestralPairsNoRoot();\n  std::vector<StringPair> vec(ancestralPairSet.begin(), ancestralPairSet.end());\n  \n  g_rng = std::mt19937(seed);\n  std::shuffle(vec.begin(), vec.end(), g_rng);\n  while (vec.size() > nrPairs)\n  {\n    vec.pop_back();\n  }\n  ancestralPairSet = StringPairSet(vec.begin(), vec.end());\n  \n  // 2. parse enumerated trees\n  std::ifstream inTrees(filenameInInferredTrees.c_str());\n  if (!inTrees.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInInferredTrees + \"' for reading\");\n  }\n  \n  int nrTrees = -1;\n  std::string line;\n  while (line.empty() || line[0] == '#')\n  {\n    getline(inTrees, line);\n  }\n  std::stringstream ss(line);\n  ss >> nrTrees;\n  \n  if (nrTrees < 0)\n  {\n    throw std::runtime_error(\"Error: number of trees should be nonnegative\");\n  }\n  \n  std::ofstream outTrees(filenameOutTrees);\n  for (const StringPair& pair : ancestralPairSet)\n  {\n    outTrees << \"# \" << pair.first << \" \" << pair.second << std::endl;\n  }\n  \n  for (int i = 0; i < nrTrees; ++i)\n  {\n    StringPairSet diff;\n    CloneTree T = parseNextTree(inTrees);\n    StringPairSet ancestralPairSetT = T.getAncestralPairs();\n    \n    std::set_difference(ancestralPairSet.begin(), ancestralPairSet.end(),\n                        ancestralPairSetT.begin(), ancestralPairSetT.end(),\n                        std::inserter(diff, diff.begin()));\n    \n    if (diff.empty())\n    {\n      outTrees << lemon::countArcs(T.tree()) << \" #edges\" << std::endl;\n      T.write(outTrees);\n    }\n  }\n  outTrees.close();\n}\n\nvoid computeRecall(const std::string& filenameInInferredTrees,\n                   const std::string& filenameInTrueTree,\n                   const std::string& filenameOutRecall)\n{\n  std::ifstream inTrueTree(filenameInTrueTree.c_str());\n  if (!inTrueTree.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTrueTree + \"' for reading\");\n  }\n  \n  CloneTree trueT;\n  if (!trueT.read(inTrueTree))\n  {\n    throw std::runtime_error(\"Parse error: '\" + filenameInTrueTree + \"'\");\n  }\n  inTrueTree.close();\n  \n  StringPairSet trueParental = trueT.getParentalPairs();\n  StringPairSet trueAncestral = trueT.getAncestralPairs();\n  StringPairSet trueIncomparable = trueT.getIncomparablePairs();\n  \n  std::ifstream inTrees(filenameInInferredTrees.c_str());\n  if (!inTrees.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInInferredTrees + \"' for reading\");\n  }\n  \n  int nrTrees = -1;\n  std::string line;\n  while (line.empty() || line[0] == '#')\n  {\n    getline(inTrees, line);\n  }\n  \n  std::stringstream ss(line);\n  ss >> nrTrees;\n  if (nrTrees < 0)\n  {\n    throw std::runtime_error(\"Error: number of trees should be nonnegative\");\n  }\n  \n  std::ofstream outRecall(filenameOutRecall);\n  outRecall << \"solution\\tancestral\\tparental\\tincomparable\" << std::endl;\n  for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)\n  {\n    CloneTree T = parseNextTree(inTrees);\n    StringPairSet inferredParental = T.getParentalPairs();\n    StringPairSet inferredAncestral = T.getAncestralPairs();\n    StringPairSet inferredIncomparable = T.getIncomparablePairs();\n    \n    outRecall << treeIdx << \"\\t\"\n              << BaseTree::recall(inferredAncestral, trueAncestral)\n              << \"\\t\"\n              << BaseTree::recall(inferredParental, trueParental)\n              << \"\\t\"\n              << BaseTree::recall(inferredIncomparable, trueIncomparable)\n              << std::endl;\n  }\n  inTrees.close();\n  outRecall.close();\n}\n\ndouble getFractionOfIncomparablePairs(const std::string& filenameInFreqs)\n{\n  std::ifstream inF(filenameInFreqs.c_str());\n  if (!inF.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInFreqs + \"' for reading\");\n  }\n  \n  FrequencyMatrix F;\n  inF >> F;\n  inF.close();\n  \n  return EnumerateMutationTrees(F).getAncestryGraph().fracOfIncomparablePairs();\n}\n\nvoid summarize(const std::string& filenameInAllTrees,\n               const std::string& filenameInSampledTree,\n               const std::string& filenameOutSummary)\n{\n  // 1. Parse sampled trees\n  std::map<StringPairSet, int> sampledTreeHistogram;\n  \n  std::ifstream inTrees(filenameInSampledTree.c_str());\n  if (!inTrees.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInSampledTree + \"' for reading\");\n  }\n  \n  int nrTrees = -1;\n  std::string line;\n  while (line.empty() || line[0] == '#')\n  {\n    getline(inTrees, line);\n  }\n  \n  std::stringstream ss(line);\n  ss >> nrTrees;\n  if (nrTrees < 0)\n  {\n    throw std::runtime_error(\"Error: number of trees should be nonnegative\");\n  }\n  \n  for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)\n  {\n    CloneTree T = parseNextTree(inTrees);\n    StringPairSet edges;\n    for (ArcIt a(T.tree()); a != lemon::INVALID; ++a)\n    {\n      Node u = T.tree().source(a);\n      Node v = T.tree().target(a);\n      \n      edges.insert(StringPair(T.label(u), T.label(v)));\n    }\n    if (sampledTreeHistogram.count(edges) == 0)\n    {\n      sampledTreeHistogram[edges] = 1;\n    }\n    else\n    {\n      ++sampledTreeHistogram[edges];\n    }\n  }\n  inTrees.close();\n  \n  // 2. Parse all trees\n  std::map<StringPairSet, int> allTreeIndex;\n  \n  inTrees = std::ifstream(filenameInAllTrees.c_str());\n  if (!inTrees.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInAllTrees + \"' for reading\");\n  }\n  \n  nrTrees = -1;\n  line.clear();\n  while (line.empty() || line[0] == '#')\n  {\n    getline(inTrees, line);\n  }\n  \n  ss.clear();\n  ss.str(line);\n  ss >> nrTrees;\n  if (nrTrees < 0)\n  {\n    throw std::runtime_error(\"Error: number of trees should be nonnegative\");\n  }\n  \n  for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)\n  {\n    CloneTree T = parseNextTree(inTrees);\n    StringPairSet edges;\n    for (ArcIt a(T.tree()); a != lemon::INVALID; ++a)\n    {\n      Node u = T.tree().source(a);\n      Node v = T.tree().target(a);\n      \n      edges.insert(StringPair(T.label(u), T.label(v)));\n    }\n    if (allTreeIndex.count(edges) > 0)\n    {\n      throw std::runtime_error(\"Error: duplicate tree\");\n    }\n    \n    allTreeIndex[edges] = treeIdx;\n  }\n  inTrees.close();\n  \n  std::ofstream outSum(filenameOutSummary);\n  int incorrect = 0;\n  outSum << \"index\\tcount\" << std::endl;\n  for (const auto& kv : sampledTreeHistogram)\n  {\n    if (allTreeIndex.count(kv.first) == 0)\n    {\n      outSum << --incorrect << \"\\t\" << kv.second << std::endl;\n    }\n    else\n    {\n      outSum << allTreeIndex[kv.first] << \"\\t\" << kv.second << std::endl;\n    }\n  }\n  for (const auto& kv : allTreeIndex)\n  {\n    if (sampledTreeHistogram.count(kv.first) == 0)\n    {\n      outSum << kv.second << \"\\t\" << 0 << std::endl;\n    }\n  }\n  outSum.close();\n}\n\nint rejectionSample(const std::string& filenameInFreqs,\n                    const std::string& filenameOutTrees,\n                    int count,\n                    int seed = 0)\n{\n  g_rng = std::mt19937(seed);\n  \n  std::ifstream inF(filenameInFreqs.c_str());\n  if (!inF.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInFreqs + \"' for reading\");\n  }\n  \n  FrequencyMatrix F;\n  inF >> F;\n  inF.close();\n  \n  const int n = F.getNrCharacters();\n  const int k = F.getNrSamples();\n  \n  RealTensor FF(2, k, n);\n  for (int p = 0; p < k; ++p)\n  {\n    FF.setRowLabel(p, F.indexToSample(p));\n    for (int i = 0; i < n; ++i)\n    {\n      if (p == 0)\n      {\n        FF.setColLabel(i, F.indexToCharacter(i));\n      }\n      FF.set(1, p, i, F.min(p, i));\n      FF.set(0, p, i, 1 - F.max(p, i));\n    }\n  }\n  \n  StateTreeVector S(F.getNrCharacters(), StateTree({-1, 0}));\n  \n  gm::RootedCladisticAncestryGraph G(FF, S);\n  G.init();\n  \n  std::ofstream outTrees(filenameOutTrees);\n  outTrees << count << \" #trees\" << std::endl;\n  StringPairSet tree;\n  int sampleCount = 0;\n  while (count > 0)\n  {\n    ++sampleCount;\n    if (G.sample(tree))\n    {\n      outTrees << tree.size() << \" #edges\" << std::endl;\n      for (const StringPair& edge : tree)\n      {\n        outTrees << edge.first << \" \" << edge.second << std::endl;\n      }\n      --count;\n    }\n  }\n  \n  return sampleCount;\n}\n\nstd::string visualizeEnumeratedCloneTree(const std::string& filenameInFreqs,\n                                         const std::string& filenameInTrees,\n                                         int index,\n                                         bool showCharacterLabels = false,\n                                         int offset = 1,\n                                         bool showFrequencies = false)\n{\n  std::ifstream inF(filenameInFreqs.c_str());\n  if (!inF.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInFreqs + \"' for reading\");\n  }\n  \n  FrequencyMatrix F;\n  inF >> F;\n  inF.close();\n  \n  std::ifstream inTrees(filenameInTrees.c_str());\n  if (!inTrees.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTrees + \"' for reading\");\n  }\n  \n  int nrTrees = -1;\n  std::string line;\n  while (line.empty() || line[0] == '#')\n  {\n    getline(inTrees, line);\n  }\n  \n  std::stringstream ss(line);\n  ss >> nrTrees;\n  if (nrTrees < 0)\n  {\n    throw std::runtime_error(\"Error: number of trees should be nonnegative\");\n  }\n  \n  if (!(0 <= index && index < nrTrees))\n  {\n    throw std::runtime_error(\"Error: invalid index\");\n  }\n\n  std::stringstream ssOut;\n  for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)\n  {\n    CloneTree T = parseNextTree(inTrees);\n    if (index == treeIdx)\n    {\n      ssOut << \"digraph T_\" << index << \" {\" << std::endl;\n      \n      for (NodeIt v(T.tree()); v != lemon::INVALID; ++v)\n      {\n        ssOut << \"  \" << T.tree().id(v) << \" [label=\\\"\";\n        \n        const std::string& label_v = T.label(v);\n        if (showCharacterLabels)\n          ssOut << label_v;\n        else\n          ssOut << F.characterToIndex(label_v) + offset;\n        \n        if (showFrequencies)\n        {\n          for (int p = 0; p < F.getNrSamples(); ++p)\n          {\n            ssOut << \"\\\\n\" << F.min(p, F.characterToIndex(label_v)) << \" \" << F.max(p, F.characterToIndex(label_v));\n          }\n        }\n        \n        ssOut << \"\\\"]\" << std::endl;\n      }\n      \n      for (ArcIt a(T.tree()); a != lemon::INVALID; ++a)\n      {\n        Node u = T.tree().source(a);\n        Node v = T.tree().target(a);\n        \n        ssOut << \"  \" << T.tree().id(u) << \" -> \" << T.tree().id(v) << std::endl;\n      }\n      \n      ssOut << \"}\" << std::endl;\n      break;\n    }\n  }\n  inTrees.close();\n  \n  return ssOut.str();\n}\n\nint identifySolution(const std::string& filenameInTrees,\n                     const std::string& filenameInTree)\n{\n  std::ifstream inTrueTree(filenameInTree.c_str());\n  if (!inTrueTree.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTree + \"' for reading\");\n  }\n  \n  CloneTree trueT;\n  if (!trueT.read(inTrueTree))\n  {\n    throw std::runtime_error(\"Parse error: '\" + filenameInTree + \"'\");\n  }\n  inTrueTree.close();\n  StringPairSet edgesTrueT = trueT.getEdgeSet();\n  \n  std::ifstream inTrees(filenameInTrees.c_str());\n  if (!inTrees.good())\n  {\n    throw std::runtime_error(\"Error: could not open '\" + filenameInTrees + \"' for reading\");\n  }\n  \n  int nrTrees = -1;\n  std::string line;\n  while (line.empty() || line[0] == '#')\n  {\n    getline(inTrees, line);\n  }\n  \n  std::stringstream ss(line);\n  ss >> nrTrees;\n  if (nrTrees < 0)\n  {\n    throw std::runtime_error(\"Error: number of trees should be nonnegative\");\n  }\n  \n  int res = -1;\n  for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)\n  {\n    CloneTree T = parseNextTree(inTrees);\n    if (T.getEdgeSet() == edgesTrueT)\n    {\n      res = treeIdx;\n      break;\n    }\n  }\n  inTrees.close();\n  \n  return res;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(sequence_overloads, sequence, 3, 7);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(downSample_overloads, downSample, 4, 8);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(visualizeCloneTree_overloads, visualizeCloneTree, 1, 3);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(visualizeEnumeratedCloneTree_overloads, visualizeEnumeratedCloneTree, 3, 6);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(visualizeMigrationGraph_overloads, visualizeMigrationGraph, 1, 2);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(simulate_overloads, simulate, 0, 2);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(countSpanningTrees_overloads, countSpanningTrees, 1, 2);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(mix_overloads, mix, 4, 5);\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(rejectionSample_overloads, rejectionSample, 3, 4);\n\nBOOST_PYTHON_MODULE(oncolib)\n{\n  p::def(\"sequence\", sequence,\n         sequence_overloads(p::args(\"filenameInTree\",\n                                    \"filenameOutReads\",\n                                    \"sequencingDepth\",\n                                    \"seed=0\",\n                                    \"ploidy=2\",\n                                    \"purity=1.\",\n                                    \"sequencingErrorRate=0.\"),\n                            \"Generate NGS reads from clone tree\"));\n  \n  p::def(\"simulate\", simulate, simulate_overloads(p::args(\"outputDirectory='.'\",\n                                                          \"args={'filenameColorMap:'', \"\\\n                                                          \"'seed':0, \"\\\n                                                          \"'carryingCapacity':5e4, \"\\\n                                                          \"'mutFreqThreshold':0.05, \"\\\n                                                          \"'migrationRate':1e-6, \"\\\n                                                          \"'mutationRate':0.1, \"\\\n                                                          \"'driverRate':2e-7, \"\\\n                                                          \"'maxNrAnatomicalSites':3, \"\\\n                                                          \"'migrationPattern':0, \"\\\n                                                          \"'nrTrials':-1, \"\\\n                                                          \"'desiredNrMutationClusters':-1, \"\n                                                          \"'sequencingDepth':200, \"\\\n                                                          \"'nrSamplesPerAnatomicalSite':2, \"\\\n                                                          \"'nrSamplesPrimary':2, \"\\\n                                                          \"'sequencingErrorRate':0, \"\\\n                                                          \"'purity':1., \"\\\n                                                          \"'verbose':False}\"),\n                                                  \"Simulate a metastatic tumor\"));\n  \n  p::def(\"tree2dot\", visualizeCloneTree,\n         visualizeCloneTree_overloads(p::args(\"filenameInTree\",\n                                              \"filenameInColorMap=''\",\n                                              \"filenameInVertexLabeling=''\"),\n                                      \"Visualize clone tree in DOT format\"));\n  \n  p::def(\"enumeratedtree2dot\", visualizeEnumeratedCloneTree,\n         visualizeEnumeratedCloneTree_overloads(p::args(\"filenameInFreqs\",\n                                                        \"filenameInTrees\",\n                                                        \"index\",\n                                                        \"showCharacterLabels=False\",\n                                                        \"offset=1\",\n                                                        \"showFrequencies=False\"),\n                                                \"Visualize enumerated clone tree in DOT format\"));\n  \n  p::def(\"graph2dot\", visualizeMigrationGraph,\n         visualizeMigrationGraph_overloads(p::args(\"filenameInTree\",\n                                                   \"filenameInColorMap=''\"),\n                                      \"Visualize clone tree in DOT format\"));\n  \n  p::def(\"downsample\", downSample,\n         downSample_overloads(p::args(\"filenameInR\",\n                                      \"filenameOutR\",\n                                      \"nrSamplesPerAnatomicalSite\",\n                                      \"coverage\",\n                                      \"seed=0\",\n                                      \"purity=1.\",\n                                      \"sequencingErrorRate=0.\",\n                                      \"fractionSNVs=1.\"),\n                              \"Down sample reads\"));\n  \n  p::def(\"mix\", mix, mix_overloads(p::args(\"filenameInTree\",\n                                           \"filenameOutTree\",\n                                           \"k\",\n                                           \"partition\",\n                                           \"seed=0\"),\n                                   \"Generate mixture of clone tree leaves\"));\n  \n  p::def(\"tree2freqs\", treeToFreqs, \"Extract mutation frequencies from clone tree\");\n  \n  p::def(\"reads2freqs\", readsToFreqs, \"Extract mutation frequencies from reads\");\n  \n  p::def(\"precluster\", precluster, \"Cluster mutation frequencies given clustering\");\n  \n  p::def(\"enumerate\", enumerate, \"Enumerate mutation trees\");\n  \n  p::def(\"countSpanningTrees\", countSpanningTrees,\n         countSpanningTrees_overloads(p::args(\"filenameInF\",\n                                              \"root=0\"),\n                                      \"Compute number of spanning arborescence in ancestry graph\"));\n  \n  p::def(\"computeRecall\", computeRecall, \"Compute recall\");\n  \n  p::def(\"getFractionOfIncomparablePairs\", getFractionOfIncomparablePairs,\n         \"Compute fraction of incomparable pairs\");\n  \n  p::def(\"filterSCS\", filterSCS, \"Include SCS information\");\n  \n  p::def(\"filterLR\", filterLR, \"Include long read information\");\n  \n  p::def(\"summarize\", summarize, \"Compute histogram of sampled trees w.r.t. all trees\");\n  \n  p::def(\"identifySolution\", identifySolution, \"Determine whether specified tree occurs in specified trees\");\n  \n  p::def(\"rejectionSample\", rejectionSample,\n         rejectionSample_overloads(p::args(\"filenameInFreqs\",\n                                           \"filenameOutTrees\",\n                                           \"count\",\n                                           \"seed=0\"),\n                                   \"Rejection sampling of spanning trees satisfying SC\"));\n}\n", "meta": {"hexsha": "e1d7dc6aa99eb1da7ef743cbe01ac3697ee64444", "size": 33789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python.cpp", "max_stars_repo_name": "elkebir-group/OncoSim", "max_stars_repo_head_hexsha": "1707709c21f8f54ed7ebff9272f5b159f05a8ee5", "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/python.cpp", "max_issues_repo_name": "elkebir-group/OncoSim", "max_issues_repo_head_hexsha": "1707709c21f8f54ed7ebff9272f5b159f05a8ee5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python.cpp", "max_forks_repo_name": "elkebir-group/OncoSim", "max_forks_repo_head_hexsha": "1707709c21f8f54ed7ebff9272f5b159f05a8ee5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-08T19:53:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T01:44:37.000Z", "avg_line_length": 28.2516722408, "max_line_length": 116, "alphanum_fraction": 0.5531681908, "num_tokens": 8504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.028007519287606836, "lm_q1q2_score": 0.011302906038011887}}
{"text": "#include <cstdlib>\n#include <memory>\n#include <algorithm>\n#include <complex>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <utility>\n#include <vector>\n#include <numeric>\n#if defined(USE_MPI)\n#include <mpi.h>\n#endif\n\n#include <boost/version.hpp>\n#include \"hdf/hdf_multi.h\"\n#include \"hdf/hdf_archive.h\"\n\n#include \"AFQMC/config.h\"\n#include \"AFQMC/Hamiltonians/HamiltonianFactory.h\"\n#include \"AFQMC/Hamiltonians/HamiltonianFactory_Helper.h\"\n\n#include \"AFQMC/Hamiltonians/THCHamiltonian.h\"\n#include \"AFQMC/Hamiltonians/FactorizedSparseHamiltonian.h\"\n#include \"AFQMC/Hamiltonians/KPFactorizedHamiltonian.h\"\n#include \"AFQMC/Hamiltonians/RealDenseHamiltonian.h\"\n#include \"AFQMC/Hamiltonians/RealDenseHamiltonian_v2.h\"\n//#include \"AFQMC/Hamiltonians/KPTHCHamiltonian.h\"\n\n#include \"AFQMC/Utilities/readHeader.h\"\n#include \"AFQMC/Utilities/Utils.hpp\"\n\n#include \"AFQMC/Numerics/ma_operations.hpp\"\n#include \"AFQMC/Matrix/csr_matrix.hpp\"\n\n#include \"AFQMC/Matrix/hdf5_readers.hpp\"\n#include \"AFQMC/Utilities/hdf5_consistency_helper.hpp\"\n#include \"AFQMC/Matrix/array_partition.hpp\"\n\nnamespace qmcplusplus\n{\nnamespace afqmc\n{\nHamiltonian HamiltonianFactory::fromHDF5(GlobalTaskGroup& gTG, xmlNodePtr cur)\n{\n  if (cur == NULL)\n    APP_ABORT(\"Error: NULL xml pointer in HamiltonianFactory::parse(). \\n\");\n\n  std::string info(\"info0\");\n  OhmmsAttributeSet oAttrib;\n  oAttrib.add(info, \"info\");\n  oAttrib.put(cur);\n\n  if (InfoMap.find(info) == InfoMap.end())\n  {\n    app_error() << \"ERROR: Undefined info in execute block. \\n\";\n    APP_ABORT(\"ERROR: Undefined info in execute block. \\n\");\n  }\n\n  AFQMCInfo& AFinfo = InfoMap[info];\n\n  int NMO  = AFinfo.NMO;\n  int NAEA = AFinfo.NAEA;\n  int NAEB = AFinfo.NAEB;\n\n  // defaults\n  double cutoff1bar    = 1e-8;\n  std::string fileName = \"\";\n  int number_of_TGs    = 1;\n  int n_reading_cores  = -1;\n  std::string alt      = \"\";\n\n  ParameterSet m_param;\n  m_param.add(cutoff1bar, \"cutoff_1bar\", \"double\");\n  m_param.add(fileName, \"filename\", \"std::string\");\n  m_param.add(number_of_TGs, \"nblocks\", \"int\");\n  m_param.add(n_reading_cores, \"num_io_cores\", \"int\");\n  m_param.add(alt, \"alternate\", \"std::string\");\n  m_param.put(cur);\n\n  // make or get TG\n  number_of_TGs  = std::max(1, std::min(number_of_TGs, gTG.getTotalNodes()));\n  TaskGroup_& TG = getTG(gTG, number_of_TGs);\n\n  // processor info\n  int ncores = TG.getTotalCores(), coreid = TG.getCoreID();\n  int nread = (n_reading_cores <= 0) ? (ncores) : (std::min(n_reading_cores, ncores));\n  int head  = TG.getGlobalRank() == 0;\n\n  app_log() << \" Initializing Hamiltonian from file: \" << fileName << std::endl;\n\n  // FIX FIX FIX\n  hdf_archive dump(TG.Global());\n  // these cores will read from hdf file\n  if (coreid < nread)\n  {\n    if (!dump.open(fileName, H5F_ACC_RDONLY))\n    {\n      app_error() << \" Error opening integral file in SparseGeneralHamiltonian. \\n\";\n      APP_ABORT(\"\");\n    }\n    if (!dump.push(\"Hamiltonian\", false))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Group not Hamiltonian found. \\n\";\n      APP_ABORT(\"\");\n    }\n  }\n\n  HamiltonianTypes htype = UNKNOWN;\n  if (head)\n    htype = peekHamType(dump);\n  {\n    int htype_ = int(htype);\n    TG.Global().broadcast_n(&htype_, 1, 0);\n    htype = HamiltonianTypes(htype_);\n  }\n\n  int complex_integrals;\n  // Hamiltonian file may not contain flag.\n  bool have_complex_flag = true;\n  if (head)\n  {\n    if (!dump.readEntry(complex_integrals, \"ComplexIntegrals\"))\n    {\n      have_complex_flag = false;\n    }\n  }\n  TG.Global().broadcast_n(&have_complex_flag, 1, 0);\n  if (have_complex_flag && head)\n  {\n#ifdef QMC_COMPLEX\n    if (!complex_integrals)\n      app_log() << \" Note: Found real integrals with QMC_COMPLEX=1.\\n\";\n#else\n    if (complex_integrals)\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Found complex integrals but QMC_COMPLEX=0.\\n\";\n      app_error() << \" Please build QMCPACK with complex support or write real integrals if appropriate.\\n\";\n      APP_ABORT(\"\");\n    }\n#endif\n  }\n\n  int int_blocks, nvecs;\n  std::vector<int> Idata(8);\n  if (head)\n    if (!dump.readEntry(Idata, \"dims\"))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Problems reading dims. \\n\";\n      APP_ABORT(\"\");\n    }\n  TG.Global().broadcast(Idata.begin(), Idata.end());\n\n  int_blocks = Idata[2];\n  if (Idata[3] != NMO)\n  {\n    app_error() << \" ERROR: NMO differs from value in integral file. \\n\";\n    APP_ABORT(\" Error: NMO differs from value in integral file. \\n\");\n  }\n  if (Idata[4] != NAEA)\n  {\n    app_log() << \" WARNING: NAEA differs from value in integral file. \\n\";\n    //      APP_ABORT(\" \");\n  }\n  if (Idata[5] != NAEB)\n  {\n    app_log() << \" WARNING: NAEB differs from value in integral file. \\n\";\n    //      APP_ABORT(\" \");\n  }\n  nvecs = Idata[7];\n#ifdef QMC_COMPLEX\n  int nkpts = -1;\n  if (htype == KPFactorized || htype == KPTHC)\n    nkpts = Idata[2];\n#endif\n\n  // MAM: this is wrong in NONCOLLINEAR, but how do I know what \n  // walker type it is right here???\n  // Might need to read dimensions ahead of time from hdf5 file and check consistensy\n  // later\n  // Also, OneBodyHamiltonian doesn't make much sense now that you have KP classes.\n  // Consider refactoring this part of the code...\n  // It is not really used now, you can just read H1 in Sparse class too...  \n\n  // 1 body hamiltonian: Why isn't this in shared memory!!!\n  boost::multi::array<ValueType, 2> H1({NMO, NMO});\n\n  ValueType NuclearCoulombEnergy(0);\n  ValueType FrozenCoreEnergy(0);\n\n  if (head)\n  {\n    std::vector<RealType> Rdata(2);\n    if (!dump.readEntry(Rdata, \"Energies\"))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Problems reading  dataset. \\n\";\n      APP_ABORT(\" \");\n    }\n    if (Rdata.size() > 0)\n      NuclearCoulombEnergy = Rdata[0];\n    if (Rdata.size() > 1)\n      FrozenCoreEnergy = Rdata[1];\n  }\n\n  TG.Global().broadcast_n(&NuclearCoulombEnergy, 1, 0);\n  TG.Global().broadcast_n(&FrozenCoreEnergy, 1, 0);\n\n  if (head)\n  {\n    using ma::conj;\n    using std::imag;\n    bool foundH1 = false;\n#ifdef QMC_COMPLEX\n    if (htype == KPFactorized || htype == KPTHC)\n    {\n#else\n    if (htype == RealDenseFactorized)\n    {\n#endif\n      // nothing to do, H1 is read during construction of HamiltonianOperations object.\n    }\n    else\n    {\n      if (readComplexOrReal(dump, \"hcore\", H1)) {}\n      else\n      {\n        app_log() << \" Reading one-body Hamiltonian in sparse format.\\n\";\n        H1.reextent({NMO, NMO});\n        if (Idata[0] < 1)\n        {\n          app_error() << \" Error in HamiltonianFactory::fromHDF5(): Dimensions of H1 < 1.  \\n\";\n          APP_ABORT(\" \");\n        }\n\n        std::vector<OrbitalType> ivec(2 * Idata[0]);\n        if (!dump.readEntry(ivec, \"H1_indx\"))\n        {\n          app_error() << \" Error in HamiltonianFactory::fromHDF5(): Problems reading H1_indx. \\n\";\n          APP_ABORT(\" \");\n        }\n        std::vector<ValueType> vvec(Idata[0]);\n        if (!readComplexOrReal(dump, \"H1\", vvec))\n        {\n          app_error() << \" Error in HamiltonianFactory::fromHDF5(): Problems reading H1.  \\n\";\n          APP_ABORT(\" \");\n        }\n\n        for (int i = 0; i < Idata[0]; i++)\n        {\n          // keep i<=j by default\n          if (ivec[i] <= ivec[i])\n          {\n            H1[ivec[2 * i]][ivec[2 * i + 1]] = vvec[i];\n            H1[ivec[2 * i + 1]][ivec[2 * i]] = ma::conj(vvec[i]);\n          }\n          else\n          {\n            H1[ivec[2 * i]][ivec[2 * i + 1]] = ma::conj(vvec[i]);\n            H1[ivec[2 * i + 1]][ivec[2 * i]] = vvec[i];\n          }\n        }\n      }\n      app_log() << \" Successfully read one-body Hamiltonian.\\n\";\n      app_log() << \" Shape of one-body Hamiltonian: (\" << NMO << \", \" << NMO << \").\" << std::endl;\n    }\n  }\n  TG.Global().broadcast_n(to_address(H1.origin()), H1.num_elements(), 0);\n\n  // now read the integrals\n#ifdef QMC_COMPLEX\n  if (htype == KPTHC)\n  {\n    APP_ABORT(\" Error: KPTHC hamiltonian not yet working. \\n\");\n    if (coreid < nread && !dump.push(\"KPTHC\", false))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Group not KPTHC found. \\n\";\n      APP_ABORT(\"\");\n    }\n    if (coreid < nread)\n    {\n      dump.pop();\n      dump.pop();\n      dump.close();\n    }\n    TG.global_barrier();\n    return Hamiltonian{};\n    //      return Hamiltonian(KPTHCHamiltonian(AFinfo,cur,std::move(H1),TG,\n    //                                        NuclearCoulombEnergy,FrozenCoreEnergy));\n  }\n  else if (htype == KPFactorized)\n  {\n    if (coreid < nread && !dump.push(\"KPFactorized\", false))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Group not KPFactorized found. \\n\";\n      APP_ABORT(\"\");\n    }\n    if (coreid < nread)\n    {\n      dump.pop();\n      dump.pop();\n      dump.close();\n    }\n    TG.global_barrier();\n    // KPFactorizedHamiltonian matrices are read by THCHamiltonian object when needed,\n    // since their ownership is passed to the HamOps object.\n    return Hamiltonian(KPFactorizedHamiltonian(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));\n  }\n  else\n#else\n  if (htype == RealDenseFactorized)\n  {\n    if (coreid < nread && !dump.push(\"DenseFactorized\", false))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Group not DenseFactorized found. \\n\";\n      APP_ABORT(\"\");\n    }\n    if (coreid < nread)\n    {\n      dump.pop();\n      dump.pop();\n      dump.close();\n    }\n    TG.global_barrier();\n    // KPFactorizedHamiltonian matrices are read by THCHamiltonian object when needed,\n    // since their ownership is passed to the HamOps object.\n#if defined(ENABLE_CUDA) || defined(ENABLE_HIP)\n    //      if(alt == \"yes\" || alt == \"true\")\n    //        return Hamiltonian(RealDenseHamiltonian(AFinfo,cur,std::move(H1),TG,\n    //                                        NuclearCoulombEnergy,FrozenCoreEnergy));\n    //      else\n    return Hamiltonian(RealDenseHamiltonian_v2(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));\n#else\n    return Hamiltonian(RealDenseHamiltonian(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));\n#endif\n  }\n  else\n#endif\n      if (htype == THC)\n  {\n    if (coreid < nread && !dump.push(\"THC\", false))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Group not THC found. \\n\";\n      APP_ABORT(\"\");\n    }\n    if (coreid < nread)\n    {\n      dump.pop();\n      dump.pop();\n      dump.close();\n    }\n    TG.global_barrier();\n    // THC matrices are read by THCHamiltonian object when needed, since their ownership is\n    // passed to the HamOps object.\n    return Hamiltonian(THCHamiltonian(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));\n  }\n  else if (htype == Factorized)\n  {\n    if (coreid < nread && !dump.push(\"Factorized\", false))\n    {\n      app_error() << \" Error in HamiltonianFactory::fromHDF5(): Group Factorized not found. \\n\";\n      APP_ABORT(\"\");\n    }\n\n    if (TG.getNumberOfTGs() > 1)\n      APP_ABORT(\" Error: Distributed Factorized hamiltonian not yet implemented. \\n\\n\");\n\n    FactorizedSparseHamiltonian::shm_csr_matrix V2_fact =\n        read_V2fact(dump, TG, nread, NMO, nvecs, cutoff1bar, int_blocks);\n\n    app_log() << \" Memory used by factorized 2-el integral table (on head node): \"\n              << (V2_fact.capacity() * (sizeof(ValueType) + sizeof(IndexType)) +\n                  V2_fact.size(0) * (2 * sizeof(std::size_t))) /\n            1024.0 / 1024.0\n              << \" MB. \" << std::endl;\n\n    if (coreid < nread)\n    {\n      dump.pop();\n      dump.pop();\n      dump.close();\n    }\n    TG.global_barrier();\n\n    return Hamiltonian(FactorizedSparseHamiltonian(AFinfo, cur, std::move(H1), std::move(V2_fact), TG,\n                                                   NuclearCoulombEnergy, FrozenCoreEnergy));\n  }\n\n  app_error() << \" Error in HamiltonianFactory::fromHDF5(): Unknown Hamiltonian Type. \\n\";\n  APP_ABORT(\"\");\n  return Hamiltonian{};\n}\n} // namespace afqmc\n} // namespace qmcplusplus\n", "meta": {"hexsha": "a60790a1ae47f455e84c3a6b4645af41e26665b5", "size": 11954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AFQMC/Hamiltonians/HamiltonianFactory.cpp", "max_stars_repo_name": "Hyeondeok-Shin/qmcpack", "max_stars_repo_head_hexsha": "2b853b6eaa15a795eee9d92085e74b97bd69abc7", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AFQMC/Hamiltonians/HamiltonianFactory.cpp", "max_issues_repo_name": "Hyeondeok-Shin/qmcpack", "max_issues_repo_head_hexsha": "2b853b6eaa15a795eee9d92085e74b97bd69abc7", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AFQMC/Hamiltonians/HamiltonianFactory.cpp", "max_forks_repo_name": "Hyeondeok-Shin/qmcpack", "max_forks_repo_head_hexsha": "2b853b6eaa15a795eee9d92085e74b97bd69abc7", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3401015228, "max_line_length": 120, "alphanum_fraction": 0.619457922, "num_tokens": 3452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.029312227359491745, "lm_q1q2_score": 0.011282632292542595}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_ACCUMULATORS_ZK_SPARSE_HPP\n#define CRYPTO3_ACCUMULATORS_ZK_SPARSE_HPP\n\n#include <boost/container/static_vector.hpp>\n\n#include <boost/parameter/value_type.hpp>\n\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n\n#include <nil/crypto3/zk/snark/accumulators/parameters/offset.hpp>\n\n#include <nil/crypto3/algebra/multiexp/multiexp.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace accumulators {\n            namespace detail {\n                template<typename T>\n                struct sparse_impl : boost::accumulators::accumulator_base {\n                    typedef typename T::value_type value_type;\n                    typedef std::vector<std::size_t> indicies_type;\n\n                    typedef std::pair<value_type, std::pair<indicies_type, std::vector<T>>> result_type;\n\n                    template<typename Args>\n                    sparse_impl(const Args &args) : in_block(false), accumulated_value(value_type::zero()) {\n                    }\n\n                    template<typename ArgumentPack>\n                    inline void operator()(const ArgumentPack &args) {\n                        resolve_type(args[boost::accumulators::sample], args[::nil::crypto3::accumulators::offset]);\n                    }\n\n                    inline result_type result(boost::accumulators::dont_care) const {\n                    }\n\n                protected:\n                    template<typename SinglePassRange>\n                    inline result_type resolve_type(const SinglePassRange r, std::size_t offset) {\n                        const std::size_t chunks = 1;\n\n                        std::pair<indicies_type, std::vector<T>> resulting_vector;\n                        resulting_vector.domain_size_ = domain_size_;\n\n                        const std::size_t range_len = r.size();\n                        std::size_t first_pos = -1, last_pos = -1;\n                        for (std::size_t i = 0; i < indices.size(); ++i) {\n                            const bool matching_pos = (offset <= indices[i] && indices[i] < offset + range_len);\n                            bool copy_over;\n\n                            if (in_block) {\n                                if (matching_pos && last_pos == i - 1) {\n                                    // block can be extended, do it\n                                    last_pos = i;\n                                    copy_over = false;\n                                } else {\n                                    // block has ended here\n                                    in_block = false;\n                                    copy_over = true;\n\n                                    accumulated_value =\n                                        accumulated_value +\n                                        algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(\n                                            values.begin() + first_pos, values.begin() + last_pos + 1,\n                                            std::begin(r) + (indices[first_pos] - offset),\n                                            std::begin(r) + (indices[last_pos] - offset) + 1, chunks);\n                                }\n                            } else {\n                                if (matching_pos) {\n                                    // block can be started\n                                    first_pos = i;\n                                    last_pos = i;\n                                    in_block = true;\n                                    copy_over = false;\n                                } else {\n                                    copy_over = true;\n                                }\n                            }\n\n                            if (copy_over) {\n                                resulting_vector.first.emplace_back(indices[i]);\n                                resulting_vector.second.emplace_back(values[i]);\n                            }\n                        }\n\n                        if (in_block) {\n                            accumulated_value =\n                                accumulated_value + algebra::multiexp<algebra::policies::multiexp_method_bos_coster>(\n                                                        values.begin() + first_pos,\n                                                        values.begin() + last_pos + 1,\n                                                        std::begin(r) + (indices[first_pos] - offset),\n                                                        std::begin(r) + (indices[last_pos] - offset) + 1,\n                                                        chunks);\n                        }\n\n                        return std::make_pair(accumulated_value, resulting_vector);\n                    }\n\n                    bool in_block;\n\n                    value_type accumulated_value;\n\n                    indicies_type indices;\n                    std::vector<value_type> values;\n                    std::size_t domain_size_;\n                };\n            }    // namespace detail\n\n            namespace tag {\n                template<typename T>\n                struct sparse : boost::accumulators::depends_on<> {\n                    typedef T value_type;\n\n                    /// INTERNAL ONLY\n                    ///\n\n                    typedef boost::mpl::always<accumulators::detail::sparse_impl<value_type>> impl;\n                };\n            }    // namespace tag\n\n            namespace extract {\n                template<typename Mode, typename AccumulatorSet>\n                typename boost::mpl::apply<AccumulatorSet, tag::sparse<Mode>>::type::result_type\n                    sparse(const AccumulatorSet &acc) {\n                    return boost::accumulators::extract_result<tag::sparse<Mode>>(acc);\n                }\n            }    // namespace extract\n        }        // namespace accumulators\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ACCUMULATORS_SNARK_HPP\n", "meta": {"hexsha": "b42ea19d2646a53c9fb2a3201971988bc8501bf7", "size": 7509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/zk/snark/accumulators/sparse.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/accumulators/sparse.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/accumulators/sparse.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": 46.6397515528, "max_line_length": 117, "alphanum_fraction": 0.4874151019, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.02716923389880245, "lm_q1q2_score": 0.011272484178920598}}
{"text": "/**\n * Copyright (c) 2018 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/raw_function.hpp>\n#include <boost/python/slice.hpp>\n#include <boost/python/call.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n#include <stdint.h>\n\n#include \"dbglog/dbglog.hpp\"\n\n#include \"pysupport/package.hpp\"\n#include \"pysupport/converters.hpp\"\n\n#include \"../geometry_core.hpp\"\n#include \"../math.hpp\"\n#include \"../geometry.hpp\"\n#include \"../transform.hpp\"\n\nnamespace bp = boost::python;\n\nnamespace math { namespace py {\n\n// point2\n\ntemplate <typename T>\nbp::object repr_from_ostream(const T &t)\n{\n    std::ostringstream os;\n    os << std::fixed << t;\n    return bp::str(os.str());\n}\n\ntemplate <typename T, typename Point>\nT Point_getItem(const Point &p, int index)\n{\n    return p[index];\n}\n\ntemplate <typename T, typename Point>\nvoid Point_setItem(Point &p, int index, T value)\n{\n    p[index] = value;\n}\n\ntemplate <typename T, typename Points, typename Extents>\nExtents computeExtents(const Points &points)\n{\n    return math::computeExtents(points.begin(), points.end());\n}\n\n/** Constructor for creating Points* from any python sequence\n */\ntemplate <typename Point>\nvoid Points_create(const boost::python::object &self\n                   , const bp::object &iterable)\n{\n    // Create a constructor object.\n    const auto constructor\n        (boost::python::make_constructor\n         (+[](const bp::object &iterable) {\n             return std::make_shared<std::vector<Point>>\n                 (bp::stl_input_iterator<Point>(iterable)\n                  , bp::stl_input_iterator<Point>());\n         }));\n\n    // Invoke the constructor.\n    constructor(self, iterable);\n}\n\ntemplate <typename T, typename Point, typename Extents>\nbp::class_<Point> point(const char *name, const char *listName)\n{\n    using namespace bp;\n\n    typedef std::vector<Point> Points;\n\n    auto cls = class_<Point>\n        (name, init<const Point&>())\n        .def(init<>())\n\n        .def(\"__repr__\", &py::repr_from_ostream<Point>)\n        .def(\"__getitem__\", &Point_getItem<T, Point>)\n        .def(\"__setitem__\", &Point_setItem<T, Point>)\n        ;\n\n        // wrap vector of point2\n    class_<Points>(listName)\n        .def(init<const Points&>())\n        .def(vector_indexing_suite<Points>())\n        .def(\"__init__\", make_function(&py::Points_create<Point>))\n        ;\n\n    def(\"computeExtents\", &computeExtents<T, Points, Extents>);\n\n    return cls;\n}\n\n\ntemplate <typename T>\nbp::class_<Point2_<T>> point2(const char *name, const char *listName)\n{\n    using namespace bp;\n    auto cls(point<T, math::Point2_<T>, math::Extents2_<T>>(name, listName));\n    cls.def(init<T, T>());\n    return cls;\n}\n\n// point3\n\ntemplate <typename T>\nbp::class_<Point3_<T>> point3(const char *name, const char *listName)\n{\n    using namespace bp;\n    auto cls(point<T, math::Point3_<T>, math::Extents3_<T>>(name, listName));\n    cls.def(init<T, T, T>());\n    return cls;\n}\n\n// size2\n\ntemplate <typename T>\nbp::class_<Size2_<T>> size2(const char *name)\n{\n    using namespace bp;\n\n    typedef math::Size2_<T> Size;\n\n    auto cls = class_<Size>\n        (name, init<const Size&>())\n        .def(init<>())\n        .def(init<T, T>())\n\n        .def(\"__repr__\", &py::repr_from_ostream<Size>)\n        .def_readwrite(\"width\", &Size::width)\n        .def_readwrite(\"height\", &Size::height)\n        .template def<bool (*)(const Size&)\n                      >(\"empty\", &math::empty<T>)\n        ;\n    return cls;\n}\n\n// size3\n\ntemplate <typename T>\nbp::class_<Size3_<T>> size3(const char *name)\n{\n    using namespace bp;\n\n    typedef math::Size3_<T> Size;\n\n    auto cls = class_<Size>\n        (name, init<const Size&>())\n        .def(init<>())\n        .def(init<T, T, T>())\n\n        .def(\"__repr__\", &py::repr_from_ostream<Size>)\n        .def_readwrite(\"width\", &Size::width)\n        .def_readwrite(\"height\", &Size::height)\n        .def_readwrite(\"depth\", &Size::depth)\n        ;\n    return cls;\n}\n\n// extents2\n\ntemplate <typename Extents>\nstd::shared_ptr<Extents> invalidExtents(void*)\n{\n    return std::make_shared<Extents>(math::InvalidExtents{});\n}\n\ntemplate <typename Extents>\nauto Extents_center(const Extents &extents)\n    -> decltype(math::center(extents))\n{\n    return math::center(extents);\n}\n\ntemplate <typename Extents>\nauto Extents_size(const Extents &extents)\n    -> decltype(math::size(extents))\n{\n    return math::size(extents);\n}\n\ntemplate <typename T>\nbp::class_<Extents2_<T>> extents2(const char *name)\n{\n    using namespace bp;\n\n    typedef math::Extents2_<T> Extents;\n    typedef math::Point2_<T> Point;\n\n    auto cls = class_<Extents>\n        (name, init<const Extents&>())\n        .def(init<>())\n        .def(init<const Point&>())\n        .def(init<const Point&, const Point&>())\n        .def(init<T, T, T, T>())\n        .def(\"__init__\", make_constructor(&py::invalidExtents<Extents>))\n\n        .def(\"__repr__\", &py::repr_from_ostream<Extents>)\n        .def_readwrite(\"ll\", &Extents::ll)\n        .def_readwrite(\"ur\", &Extents::ur)\n        .template def<math::Size2_<T> (*)(const Extents&)\n                      >(\"size\", &math::size<T>)\n        .template def<bool (*)(const Extents&)\n                      >(\"empty\", &math::empty<T>)\n        .def(\"center\", &py::Extents_center<Extents>)\n        .def(\"size\", &py::Extents_size<Extents>)\n        ;\n    return cls;\n}\n\n// extents3\n\ntemplate <typename T>\nbp::class_<Extents3_<T>> extents3(const char *name)\n{\n    using namespace bp;\n\n    typedef math::Extents3_<T> Extents;\n    typedef math::Point3_<T> Point;\n\n    auto cls = class_<Extents>\n        (name, init<const Extents&>())\n        .def(init<>())\n        .def(init<const Point&>())\n        .def(init<const Point&, const Point&>())\n        .def(init<T, T, T, T, T, T>())\n        .def(\"__init__\", make_constructor(&py::invalidExtents<Extents>))\n\n        .def(\"__repr__\", &py::repr_from_ostream<Extents>)\n        .def_readwrite(\"ll\", &Extents::ll)\n        .def_readwrite(\"ur\", &Extents::ur)\n        .template def<math::Size3_<T> (*)(const Extents&)\n                      >(\"size\", &math::size<T>)\n        .template def<bool (*)(const math::Extents2_<T>&)\n                      >(\"empty\", &math::empty<T>)\n\n        .def(\"center\", &py::Extents_center<Extents>)\n        .def(\"size\", &py::Extents_size<Extents>)\n        ;\n    return cls;\n}\n\ntemplate <typename Matrix, int size>\nstd::shared_ptr<Matrix> Matrix_create()\n{\n    return std::make_shared<Matrix>\n        (boost::numeric::ublas::zero_matrix<double>(size));\n}\n\ntemplate <typename Matrix, int size>\nMatrix Matrix_eye()\n{\n    return Matrix(boost::numeric::ublas::identity_matrix<double>(size));\n}\n\ntemplate <typename Matrix>\ndouble Matrix_get(const Matrix &m, int j, int i)\n{\n    return m(j, i);\n}\n\ntemplate <typename Matrix>\ndouble Matrix_set(Matrix &m, int j, int i, double value)\n{\n    return m(j, i) = value;\n}\n\ntemplate <typename Matrix>\nMatrix Matrix_mul(const Matrix &m1, const Matrix &m2)\n{\n    return ublas::prod(m1, m2);\n}\n\ntemplate <typename Matrix>\nvoid Matrix_imul(Matrix &m1, const Matrix &m2)\n{\n    m1 = ublas::prod(m1, m2);\n}\n\ntemplate <typename Matrix>\nMatrix Matrix_invert(const Matrix &m)\n{\n    return math::matrixInvert(m);\n}\n\ntemplate <typename Matrix, int size>\nbp::class_<Matrix> matrix(const char *name)\n{\n    using namespace bp;\n\n    auto cls = class_<Matrix>\n        (name, init<const Matrix&>())\n        .def(\"__init__\", make_constructor(&py::Matrix_create<Matrix, size>))\n        .def(\"eye\", &py::Matrix_eye<Matrix, size>)\n        .staticmethod(\"eye\")\n        .def(\"__repr__\", &py::repr_from_ostream<Matrix>)\n        .def(\"__call__\", &py::Matrix_get<Matrix>)\n        .def(\"__call__\", &py::Matrix_set<Matrix>)\n        .def(\"__mul__\",  &py::Matrix_mul<Matrix>)\n        .def(\"__imul__\",  &py::Matrix_imul<Matrix>)\n        .def(\"invert\",  &py::Matrix_invert<Matrix>)\n        ;\n\n    return cls;\n}\n\n} } // namespace math::py\n\nBOOST_PYTHON_MODULE(melown_math)\n{\n    using namespace bp;\n    namespace py = math::py;\n\n    // geometry core: 2D stuff\n    py::point2<int>(\"Point2i\", \"Points2i\");\n    py::point2<float>(\"Point2f\", \"Points2f\");\n    py::point2<double>(\"Point2\", \"Points2\");\n\n    py::size2<int>(\"Size2\");\n    py::size2<double>(\"Size2f\");\n\n    py::extents2<int>(\"Extents2i\");\n    py::extents2<double>(\"Extents2\");\n\n    // geometry core: 3D stuff\n    py::point3<int>(\"Point3i\", \"Points3i\");\n    py::point3<float>(\"Point3f\", \"Points3f\");\n    py::point3<double>(\"Point3\", \"Points3\");\n\n    py::size3<int>(\"Size3\");\n    py::size3<double>(\"Size3f\");\n\n    py::extents3<int>(\"Extents3i\");\n    py::extents3<double>(\"Extents3\");\n\n    // matrices (only doubles)\n    py::matrix<math::Matrix2, 2>(\"Matrix2\");\n    py::matrix<math::Matrix3, 3>(\"Matrix3\");\n    py::matrix<math::Matrix4, 4>(\"Matrix4\");\n\n    // transform.hpp\n    def<math::Point3 (*)(const math::Matrix4&, const math::Point3&)>\n        (\"transform\", &math::transform);\n    def<math::Point2 (*)(const math::Matrix4&, const math::Point2&)>\n        (\"transform\", &math::transform);\n    def<math::Extents2 (*)(const math::Matrix4&, const math::Extents2&)>\n        (\"transform\", &math::transform);\n    def<void (*)(const math::Matrix4&, math::Points3&)>\n        (\"transform\", &math::transform);\n    def<void (*)(const math::Matrix4&, math::Points2&)>\n        (\"transform\", &math::transform);\n\n    PYSUPPORT_OPTIONAL(math::Size2_<int>);\n    PYSUPPORT_OPTIONAL(math::Size2_<double>);\n}\n\nnamespace math { namespace py {\nPYSUPPORT_MODULE_IMPORT(math)\n} } // namespace math::py\n", "meta": {"hexsha": "500e26d56da644a3f73d5c02703090b2714a3731", "size": 10958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/python/mathmodule.cpp", "max_stars_repo_name": "melowntech/libmath", "max_stars_repo_head_hexsha": "7a473801a93ba5e244d96e773b412a3abed4a400", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T08:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T08:42:59.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libmath/math/python/mathmodule.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-06-09T12:06:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-06T08:15:04.000Z", "max_forks_repo_path": "externals/browser/externals/browser/externals/libmath/math/python/mathmodule.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:20:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:20:17.000Z", "avg_line_length": 27.5326633166, "max_line_length": 78, "alphanum_fraction": 0.6382551561, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.025957356161721738, "lm_q1q2_score": 0.011265011829551953}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <memory>\n#include <variant>\n#include <vector>\n\nnamespace kdtreepp {\n\n// The EigenKdTreeNode represents one element of the k-d tree, which may be\n// either a leaf (containing an iterable sequence), or a branch (containing a\n// left and right child). All nodes have a bounding box.\n//\n// The node is constructed with an iterable range and two function objects.\n// The first transforms the dereferenced iterator into a sortable point (i.e.\n// the element centroid), and the second returns a point or aligned box that is\n// used to extend a bounding box.\ntemplate <typename Iterator, typename T, int N>\nclass alignas(sizeof(T) * 4 * (1 + ((N - 1) / 4))) EigenKdTreeNode {\npublic:\n  // Construct a EigenKdTreeNode from the iterable range.\n  // The node will compute a surrounding bounds for the range of objects,\n  // based on a bounding element returned from the \"boundsGetter\" functor. This\n  // element can be either a point or a box. If the node has too many elements\n  // (based on maxPerLeaf), and can be subdivided (based on maxSubDivs), it will\n  // median-sort, in-place, the iterator range around a midpoint chosen by\n  // comparing the \"sort point\" of the elements along the major axis dimension.\n  //\n  // This function *will* allocate memory for the child nodes, but does\n  // not require any allocation for the contained objects.\n  template <typename SortPointGetter, typename BoundsGetter>\n  explicit EigenKdTreeNode(Iterator itemBegin, Iterator itemEnd, SortPointGetter&& sortPointGetter,\n                           BoundsGetter&& boundsGetter, const int maxPerLeaf = 8,\n                           const int maxSubDivs = 16) {\n    const auto count = std::distance(itemBegin, itemEnd);\n\n    // Compute the bounds\n    _bounds.setEmpty();\n    for (auto iter = itemBegin; iter != itemEnd; ++iter) {\n      _bounds.extend(boundsGetter(*iter));\n    }\n\n    if (maxSubDivs > 0 && count > static_cast<decltype(count)>(maxPerLeaf)) {\n      // Subdivide\n      int majorAxis = 0;\n      _bounds.sizes().maxCoeff(&majorAxis);\n      Iterator itemMid = itemBegin;\n      std::advance(itemMid, count / 2);\n\n      // Median-sort items according to major axis of bounding box\n      std::nth_element(itemBegin, itemMid, itemEnd,\n                       [majorAxis, &sortPointGetter](auto& a, auto& b) -> bool {\n                         return sortPointGetter(a)[majorAxis] < sortPointGetter(b)[majorAxis];\n                       });\n\n      // Create a branch\n      _body = Branch{std::make_unique<this_type>(\n                         itemBegin, itemMid, std::forward<SortPointGetter>(sortPointGetter),\n                         std::forward<BoundsGetter>(boundsGetter), maxPerLeaf, maxSubDivs - 1),\n                     std::make_unique<this_type>(\n                         itemMid, itemEnd, std::forward<SortPointGetter>(sortPointGetter),\n                         std::forward<BoundsGetter>(boundsGetter), maxPerLeaf, maxSubDivs - 1)};\n    } else {\n      _body = Leaf{itemBegin, itemEnd};\n    }\n  }\n\n  [[nodiscard]] bool isLeaf() const { return _body.index() == 0; }\n\n  [[nodiscard]] bool isBranch() const { return _body.index() == 1; }\n\n  [[nodiscard]] const auto& bounds() const { return _bounds; }\n\n  // Recursively visit every item in this node and its children,\n  // provided the bounding box of each node passes the \"BoundsTest\" function\n  // passed in here - BoundsTest should take a const bounds as an argument and\n  // return a bool, based on whether we should consider the node.\n  //\n  // Once leaf nodes are reached, the iteration range with the leaf will\n  // be iterated over, and every item therein will be passed to visitor\n  template <typename BoundsTest, typename Visitor>\n  void visit(BoundsTest&& boundsTest, Visitor&& visitor) {\n    if (!boundsTest(_bounds)) {\n      return;\n    }\n\n    if (isLeaf()) {\n      auto& leaf = std::get<0>(_body);\n      for (auto iter = leaf.begin; iter != leaf.end; ++iter) {\n        visitor(*iter);\n      }\n    } else if (isBranch()) {\n      auto& branch = std::get<1>(_body);\n      branch.left->visit(std::forward<BoundsTest>(boundsTest), std::forward<Visitor>(visitor));\n      branch.right->visit(std::forward<BoundsTest>(boundsTest), std::forward<Visitor>(visitor));\n    }\n  }\n\n  // Recursively visit every item in this node and its children,\n  // provided the bounding box of each node passes the \"BoundsTest\" function\n  // passed in here - BoundsTest should take a const bounds as an argument and\n  // return a bool, based on whether we should consider the node.\n  //\n  // Once leaf nodes are reached, the iteration range with the leaf will\n  // be iterated over, and every item therein will be passed to visitor\n  //\n  // (const version)\n  template <typename BoundsTest, typename Visitor>\n  void visit(BoundsTest&& boundsTest, Visitor&& visitor) const {\n    if (!boundsTest(_bounds)) {\n      return;\n    }\n\n    if (isLeaf()) {\n      const auto& leaf = std::get<0>(_body);\n      for (auto iter = leaf.begin; iter != leaf.end; ++iter) {\n        visitor(*iter);\n      }\n    } else if (isBranch()) {\n      const auto& branch = std::get<1>(_body);\n      branch.left->visit(std::forward<BoundsTest>(boundsTest), std::forward<Visitor>(visitor));\n      branch.right->visit(std::forward<BoundsTest>(boundsTest), std::forward<Visitor>(visitor));\n    }\n  }\n\nprivate:\n  using this_type = EigenKdTreeNode<Iterator, T, N>;\n  Eigen::AlignedBox<T, N> _bounds;\n\n  struct Leaf {\n    Iterator begin;\n    Iterator end;\n  };\n\n  struct Branch {\n    std::unique_ptr<this_type> left;\n    std::unique_ptr<this_type> right;\n  };\n\n  std::variant<Leaf, Branch> _body;\n};\n\ntemplate <typename T, int N, typename Iterator, typename SortPointGetter, typename BoundsGetter>\nEigenKdTreeNode<Iterator, T, N> MakeEigenKdTreeNode(Iterator itemBegin, Iterator itemEnd,\n                                                    SortPointGetter&& sortPointGetter,\n                                                    BoundsGetter&& boundsGetter,\n                                                    const int maxPerLeaf = 8,\n                                                    const int maxSubDivs = 16) {\n  return EigenKdTreeNode<Iterator, T, N>{itemBegin,\n                                         itemEnd,\n                                         std::forward<SortPointGetter>(sortPointGetter),\n                                         std::forward<BoundsGetter>(boundsGetter),\n                                         maxPerLeaf,\n                                         maxSubDivs};\n}\n\n}  // namespace kdtreepp\n", "meta": {"hexsha": "bffb756f81355ff2c698ecafd0d501282e561caf", "size": 6556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kdtreepp/eigenkdtree.hpp", "max_stars_repo_name": "jhurliman/kdtreepp", "max_stars_repo_head_hexsha": "5fe3107219263f50069efd7c7dc8643b5dcc4d67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T13:12:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T21:38:22.000Z", "max_issues_repo_path": "include/kdtreepp/eigenkdtree.hpp", "max_issues_repo_name": "jhurliman/kdtreepp", "max_issues_repo_head_hexsha": "5fe3107219263f50069efd7c7dc8643b5dcc4d67", "max_issues_repo_licenses": ["MIT"], "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/kdtreepp/eigenkdtree.hpp", "max_forks_repo_name": "jhurliman/kdtreepp", "max_forks_repo_head_hexsha": "5fe3107219263f50069efd7c7dc8643b5dcc4d67", "max_forks_repo_licenses": ["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.4936708861, "max_line_length": 99, "alphanum_fraction": 0.6288895668, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.028436031912730718, "lm_q1q2_score": 0.011262607015785386}}
{"text": "// MIT License\n\n// Copyright (c) 2021 Daniel Kowalczyk\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#include \"PricerSolverSimpleDP.hpp\"\n#include <fmt/core.h>\n#include <gurobi_c++.h>                            // for GRBLinExpr, GRBModel\n#include <algorithm>                               // for fill, find, max\n#include <boost/graph/adjacency_list.hpp>          // for adjacency_list\n#include <boost/graph/detail/adjacency_list.hpp>   // for edges, get, num_edges\n#include <boost/graph/detail/edge.hpp>             // for operator!=, operat...\n#include <boost/graph/graph_selectors.hpp>         // for bidirectionalS\n#include <boost/graph/graphviz.hpp>                // for write_graphviz\n#include <boost/iterator/iterator_facade.hpp>      // for operator!=, operat...\n#include <boost/multiprecision/cpp_int.hpp>        // for cpp_int\n#include <boost/pending/property.hpp>              // for no_property\n#include <cstddef>                                 // for size_t\n#include <fstream>                                 // for operator<<, basic_...\n#include <iostream>                                // for cerr\n#include <limits>                                  // for numeric_limits\n#include <list>                                    // for operator==\n#include <range/v3/iterator/basic_iterator.hpp>    // for basic_iterator\n#include <range/v3/iterator/reverse_iterator.hpp>  // for reverse_cursor\n#include <range/v3/view/iota.hpp>                  // for iota_view, ints\n#include <range/v3/view/reverse.hpp>               // for reverse_fn, revers...\n#include <range/v3/view/view.hpp>                  // for operator|, view_cl...\n#include <span>                                    // for span\n#include <string>                                  // for char_traits, opera...\n#include <utility>                                 // for move\n#include <vector>                                  // for vector, vector<>::...\n#include \"Column.h\"                                // for ScheduleSet\n#include \"Instance.h\"                              // for Instance\n#include \"Job.h\"                                   // for Job\n#include \"ModelInterface.hpp\"                      // for ReformulationModel\n#include \"PricerSolverBase.hpp\"                    // for PricerSolverBase\n/**\n * Pricersolver for the TI index formulation\n */\nPricerSolverSimpleDp::PricerSolverSimpleDp(const Instance& instance)\n    : PricerSolverBase(instance),\n      Hmax(instance.H_max),\n      size_graph{},\n      A(Hmax + 1),\n      F(Hmax + 1),\n      backward_F(Hmax + 1),\n      TI_x(convex_constr_id * (Hmax + 1), GRBVar()),\n      take(convex_constr_id * (Hmax + 1), 0),\n      lp_x(convex_constr_id * (Hmax + 1), 0.0),\n      solution_x(convex_constr_id * (Hmax + 1), 0.0) {\n    init_table();\n}\n\nvoid PricerSolverSimpleDp::init_table() {\n    backward_graph = std::vector<std::vector<Job*>>(Hmax + 1);\n    forward_graph = std::vector<std::vector<Job*>>(Hmax + 1);\n\n    for (auto t = 0UL; t < Hmax + 1; t++) {\n        for (auto i = 1UL; i < convex_constr_id + 1; i++) {\n            auto  j = i - 1;\n            auto* job = jobs[j].get();\n\n            if (t >= static_cast<size_t>(job->processing_time)) {\n                forward_graph[t].push_back(job);\n                size_graph++;\n            }\n\n            if (t + job->processing_time <= Hmax) {\n                backward_graph[t].push_back(job);\n            }\n        }\n    }\n\n    fmt::print(\"Number of arcs in TI formulation = {}\\n\", size_graph);\n}\n\nbool PricerSolverSimpleDp::evaluate_nodes(\n    [[maybe_unused]] std::span<const double>& pi) {\n    forward_evaluator(pi);\n    backward_evaluator(pi);\n\n    auto counter = size_t{};\n    auto x = size_t{};\n    auto num_removed = 0;\n\n    for (auto t = size_t{}; t < Hmax + 1; ++t) {\n        auto it = forward_graph[t].begin();\n        while (it != forward_graph[t].end()) {\n            double result = F[t - (*it)->processing_time] +\n                            (*it)->weighted_tardiness(t) - pi[(*it)->job] +\n                            backward_F[t];\n\n            if (constLB + result +\n                    static_cast<double>(convex_rhs - 1) * F[Hmax] >\n                UB - 1.0 + RC_FIXING) {\n                --size_graph;\n                it = forward_graph[t].erase(it);\n                ++num_removed;\n            } else {\n                it++;\n            }\n        }\n\n        x += forward_graph[t].size();\n\n        auto iter = backward_graph[t].begin();\n        while (iter != backward_graph[t].end()) {\n            double result = F[t] + (*iter)->weighted_tardiness_start(t) -\n                            pi[(*iter)->job] +\n                            backward_F[t + (*iter)->processing_time];\n            if (constLB + result +\n                    static_cast<double>(convex_rhs - 1) * F[Hmax] >\n                UB - 1.0 + RC_FIXING) {\n                take[(*iter)->job * (Hmax + 1) + t] = false;\n                iter = backward_graph[t].erase(iter);\n            } else {\n                take[(*iter)->job * (Hmax + 1) + t] = true;\n                iter++;\n            }\n        }\n\n        counter += backward_graph[t].size();\n    }\n\n    return (num_removed > 0);\n}\n\nbool PricerSolverSimpleDp::evaluate_nodes([[maybe_unused]] double* pi) {\n    forward_evaluator(pi);\n    backward_evaluator(pi);\n\n    std::span aux_pi{pi, reformulation_model.size()};\n    auto      counter = size_t{};\n    auto      x = size_t{};\n    auto      num_removed = 0;\n\n    for (auto t = size_t{}; t < Hmax + 1; ++t) {\n        auto it = forward_graph[t].begin();\n        while (it != forward_graph[t].end()) {\n            double result = F[t - (*it)->processing_time] +\n                            (*it)->weighted_tardiness(t) - aux_pi[(*it)->job] +\n                            backward_F[t];\n\n            if (constLB + result +\n                    static_cast<double>(convex_rhs - 1) * F[Hmax] >\n                UB - 1.0 + RC_FIXING) {\n                --size_graph;\n                it = forward_graph[t].erase(it);\n                ++num_removed;\n            } else {\n                it++;\n            }\n        }\n\n        x += forward_graph[t].size();\n\n        auto iter = backward_graph[t].begin();\n        while (iter != backward_graph[t].end()) {\n            double result = F[t] + (*iter)->weighted_tardiness_start(t) -\n                            aux_pi[(*iter)->job] +\n                            backward_F[t + (*iter)->processing_time];\n            if (constLB + result +\n                    static_cast<double>(convex_rhs - 1) * F[Hmax] >\n                UB - 1.0 + RC_FIXING) {\n                take[(*iter)->job * (Hmax + 1) + t] = false;\n                iter = backward_graph[t].erase(iter);\n            } else {\n                take[(*iter)->job * (Hmax + 1) + t] = true;\n                iter++;\n            }\n        }\n\n        counter += backward_graph[t].size();\n    }\n\n    return (num_removed > 0);\n}\n\nvoid PricerSolverSimpleDp::build_mip() {\n    try {\n        fmt::print(\"Building Mip model for the TI formulation\\n\");\n\n        /** Constructing variables */\n        for (auto t = size_t{}; t < Hmax + 1; t++) {\n            for (auto& it : backward_graph[t]) {\n                double cost = it->weighted_tardiness_start(t);\n                double ub = take[(it->job) * (Hmax + 1) + t] ? 1.0 : 0.0;\n                TI_x[it->job * (Hmax + 1) + t] =\n                    model.addVar(0.0, ub, cost, 'B');\n            }\n        }\n\n        model.update();\n\n        /** Assignment variables */\n        std::vector<GRBLinExpr> assignment(convex_constr_id, GRBLinExpr());\n        std::vector<char>       sense(convex_constr_id, '=');\n        std::vector<double>     rhs(convex_constr_id, 1.0);\n\n        for (auto t = 0UL; t <= Hmax; t++) {\n            for (auto& it : backward_graph[t]) {\n                assignment[it->job] += TI_x[it->job * (Hmax + 1) + t];\n            }\n        }\n\n        std::unique_ptr<GRBConstr> assignment_constrs(\n            model.addConstrs(assignment.data(), sense.data(), rhs.data(),\n                             nullptr, static_cast<int>(convex_constr_id)));\n\n        model.update();\n\n        std::vector<GRBLinExpr> interval_constr(Hmax + 1, GRBLinExpr());\n        std::vector<char>       interval_sense(Hmax + 1);\n        std::vector<double>     interval_rhs(Hmax + 1);\n\n        for (auto t = 0UL; t <= Hmax; t++) {\n            auto add_constraint = false;\n            for (auto& it : backward_graph[t]) {\n                for (auto s = std::max(0UL, t - it->processing_time); s <= t;\n                     s++) {\n                    if (std::find(backward_graph[s].begin(),\n                                  backward_graph[s].end(),\n                                  it) != backward_graph[s].end()) {\n                        interval_constr[t] += TI_x[(it->job) * (Hmax + 1) + s];\n                        add_constraint = true;\n                    }\n                }\n            }\n\n            if (add_constraint) {\n                interval_sense[t] = '<';\n                interval_rhs[t] = static_cast<double>(convex_rhs);\n\n                model.addConstr(interval_constr[t], interval_sense[t],\n                                interval_rhs[t]);\n            }\n        }\n\n        model.update();\n\n    } catch (GRBException& e) {\n        std::cerr << e.getMessage() << '\\n';\n    }\n\n    for (auto t = 0UL; t <= Hmax; t++) {\n        for (auto& it : backward_graph[t]) {\n            TI_x[it->job * (Hmax + 1) + t].set(\n                GRB_DoubleAttr_Start, solution_x[(it->job) * (Hmax + 1) + t]);\n        }\n    }\n\n    model.write(\"ti_\" + problem_name + \"_\" + std::to_string(convex_rhs) +\n                \"correct.lp\");\n    model.optimize();\n}\n\nvoid PricerSolverSimpleDp::forward_evaluator(std::span<const double>& _pi) {\n    /** Initialisation */\n    F[0] = 0.0;\n    A[0] = nullptr;\n\n    for (auto t = 1UL; t < Hmax + 1; t++) {\n        F[t] = std::numeric_limits<double>::max() / 2;\n        A[t] = nullptr;\n    }\n\n    /** Recursion */\n    for (auto t = size_t{1}; t < Hmax + 1; t++) {\n        for (auto& it : forward_graph[t]) {\n            if (F[t - it->processing_time] +\n                    static_cast<double>(it->weighted_tardiness(t)) -\n                    _pi[it->job] <=\n                F[t]) {\n                F[t] = F[t - it->processing_time] + it->weighted_tardiness(t) -\n                       _pi[it->job];\n                A[t] = it;\n            }\n        }\n\n        if (F[t - 1] <= F[t]) {\n            F[t] = F[t - 1];\n        }\n    }\n}\n\nvoid PricerSolverSimpleDp::forward_evaluator(double* _pi) {\n    /** Initialisation */\n    std::span aux_pi{_pi, reformulation_model.size()};\n    F[0] = 0.0;\n    A[0] = nullptr;\n\n    for (auto t = 1UL; t < Hmax + 1; t++) {\n        F[t] = std::numeric_limits<double>::max() / 2;\n        A[t] = nullptr;\n    }\n\n    /** Recursion */\n    for (auto t = size_t{1}; t < Hmax + 1; t++) {\n        for (auto& it : forward_graph[t]) {\n            if (F[t - it->processing_time] +\n                    static_cast<double>(it->weighted_tardiness(t)) -\n                    aux_pi[it->job] <=\n                F[t]) {\n                F[t] = F[t - it->processing_time] + it->weighted_tardiness(t) -\n                       aux_pi[it->job];\n                A[t] = it;\n            }\n        }\n\n        if (F[t - 1] <= F[t]) {\n            F[t] = F[t - 1];\n        }\n    }\n}\n\nvoid PricerSolverSimpleDp::backward_evaluator(std::span<const double>& _pi) {\n    backward_F[Hmax] = 0.0;\n\n    for (auto t = 0UL; t < Hmax; t++) {\n        backward_F[t] = std::numeric_limits<double>::max() / 2;\n    }\n\n    for (auto t :\n         ranges::views::ints(size_t{}, Hmax) | ranges::views::reverse) {\n        for (auto& it : backward_graph[t]) {\n            auto tt = t + it->processing_time;\n            if (backward_F[tt] +\n                    static_cast<double>(it->weighted_tardiness(tt)) -\n                    _pi[it->job] <=\n                backward_F[t]) {\n                backward_F[t] =\n                    backward_F[tt] +\n                    static_cast<double>(it->weighted_tardiness(tt)) -\n                    _pi[it->job];\n            }\n        }\n\n        if (backward_F[t + 1] <= backward_F[t]) {\n            backward_F[t] = backward_F[t + 1];\n        }\n    }\n}\n\nvoid PricerSolverSimpleDp::backward_evaluator(double* _pi) {\n    backward_F[Hmax] = 0.0;\n    std::span aux_pi{_pi, reformulation_model.size()};\n\n    for (auto t = 0UL; t < Hmax; t++) {\n        backward_F[t] = std::numeric_limits<double>::max() / 2;\n    }\n\n    for (auto t :\n         ranges::views::ints(size_t{}, Hmax) | ranges::views::reverse) {\n        for (auto& it : backward_graph[t]) {\n            auto tt = t + it->processing_time;\n            if (backward_F[tt] +\n                    static_cast<double>(it->weighted_tardiness(tt)) -\n                    aux_pi[it->job] <=\n                backward_F[t]) {\n                backward_F[t] =\n                    backward_F[tt] +\n                    static_cast<double>(it->weighted_tardiness(tt)) -\n                    aux_pi[it->job];\n            }\n        }\n\n        if (backward_F[t + 1] <= backward_F[t]) {\n            backward_F[t] = backward_F[t + 1];\n        }\n    }\n}\n\nPricingSolution PricerSolverSimpleDp::pricing_algorithm(\n    std::span<const double>& _pi) {\n    PricingSolution opt_sol;\n    opt_sol.cost = 0;\n    std::vector<Job*> v;\n\n    forward_evaluator(_pi);\n\n    /** Find optimal solution */\n    opt_sol.obj = std::numeric_limits<double>::max();\n\n    for (auto i = 0UL; i < Hmax + 1; i++) {\n        if (F[i] < opt_sol.obj) {\n            opt_sol.C_max = i;\n            opt_sol.obj = F[i];\n        }\n    }\n\n    auto t_min = opt_sol.C_max;\n\n    /** Construct the solution */\n    while (A[t_min] != nullptr) {\n        Job* job = A[t_min];\n        v.push_back(A[t_min]);\n        opt_sol.cost += A[t_min]->weighted_tardiness(t_min);\n        t_min -= job->processing_time;\n    }\n\n    auto it = v.rbegin();\n\n    for (; it != v.rend(); ++it) {\n        opt_sol.jobs.push_back(*it);\n    }\n\n    /** Free the memory */\n    return opt_sol;\n}\n\nPricingSolution PricerSolverSimpleDp::pricing_algorithm(double* _pi) {\n    PricingSolution opt_sol;\n    opt_sol.cost = 0;\n    std::vector<Job*> v;\n\n    forward_evaluator(_pi);\n\n    /** Find optimal solution */\n    opt_sol.obj = std::numeric_limits<double>::max();\n\n    for (auto i = 0UL; i < Hmax + 1; i++) {\n        if (F[i] < opt_sol.obj) {\n            opt_sol.C_max = i;\n            opt_sol.obj = F[i];\n        }\n    }\n\n    auto t_min = opt_sol.C_max;\n\n    /** Construct the solution */\n    while (A[t_min] != nullptr) {\n        Job* job = A[t_min];\n        v.push_back(A[t_min]);\n        opt_sol.cost += A[t_min]->weighted_tardiness(t_min);\n        t_min -= job->processing_time;\n    }\n\n    auto it = v.rbegin();\n\n    for (; it != v.rend(); ++it) {\n        opt_sol.jobs.push_back(*it);\n    }\n\n    /** Free the memory */\n    return opt_sol;\n}\n\nPricingSolution PricerSolverSimpleDp::farkas_pricing(\n    [[maybe_unused]] double* _pi) {\n    PricingSolution opt_sol;\n\n    return opt_sol;\n}\n\nPricingSolution PricerSolverSimpleDp::farkas_pricing(\n    [[maybe_unused]] std::span<const double>& _pi) {\n    PricingSolution opt_sol;\n\n    return opt_sol;\n}\n\nvoid PricerSolverSimpleDp::construct_lp_sol_from_rmp(\n    const double*                               lambda,\n    const std::vector<std::shared_ptr<Column>>& columns) {\n    std::span aux_cols{lambda, columns.size()};\n    // std::span aux_columns{columns->pdata, columns->len};\n    std::fill(lp_x.begin(), lp_x.end(), 0.0);\n    for (auto k = 0UL; k < columns.size(); k++) {\n        if (aux_cols[k] > EPS_SOLVER) {\n            auto* tmp = columns[k].get();\n            int   t = 0;\n            // std::span aux_jobs{tmp->job_list->pdata, tmp->job_list->len};\n            for (auto& it : tmp->job_list) {\n                lp_x[(it->job) * (Hmax + 1) + t] += aux_cols[k];\n                t += it->processing_time;\n            }\n        }\n    }\n}\nvoid PricerSolverSimpleDp::construct_lp_sol_from_rmp(\n    const std::span<const double>&              lambda,\n    const std::vector<std::shared_ptr<Column>>& columns) {\n    // std::span aux_columns{columns->pdata, columns->len};\n    std::fill(lp_x.begin(), lp_x.end(), 0.0);\n    for (auto k = 0UL; k < columns.size(); k++) {\n        if (lambda[k] > EPS_SOLVER) {\n            auto* tmp = columns[k].get();\n            int   t = 0;\n            // std::span aux_jobs{tmp->job_list->pdata, tmp->job_list->len};\n            for (auto& it : tmp->job_list) {\n                lp_x[(it->job) * (Hmax + 1) + t] += lambda[k];\n                t += it->processing_time;\n            }\n        }\n    }\n}\n\n// void PricerSolverSimpleDp::create_dot_zdd([[maybe_unused]] const char* name)\n// {\n//     boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS>\n//         graph;\n//     for (auto t = 0UL; t <= Hmax; t++) {\n//         boost::add_vertex(graph);\n//     }\n\n//     for (auto t = 0UL; t < Hmax; t++) {\n//         for (auto& it : backward_graph[t]) {\n//             boost::add_edge(t, t + it->processing_time, graph);\n//         }\n//     }\n//     auto file_name = \"TI_representation_\" + problem_name + \"_\" +\n//                      std::to_string(convex_rhs) + \".gv\";\n//     auto otf = std::ofstream(file_name);\n//     boost::write_graphviz(otf, graph);\n//     otf.close();\n// }\n\nsize_t PricerSolverSimpleDp::get_nb_edges() {\n    size_t nb_edges = 0u;\n    for (auto& it : forward_graph) {\n        nb_edges += it.size();\n    }\n    return nb_edges;\n}\n\nsize_t PricerSolverSimpleDp::get_nb_vertices() {\n    size_t nb_vertices = 0u;\n    for (auto& it : forward_graph) {\n        if (!it.empty()) {\n            nb_vertices++;\n        }\n    }\n    return nb_vertices;\n}\n\nboost::multiprecision::cpp_int PricerSolverSimpleDp::print_num_paths() {\n    return 0;\n}\n\nbool PricerSolverSimpleDp::check_column([[maybe_unused]] Column const* set) {\n    // int t = 0;\n    // for(unsigned int j = 0; j < set->len; j++) {\n    //     Job* tmp_j = static_cast<Job*>() g_ptr_array_index()atic_cast<set,\n    //     j>())); t += tmp_j->processing_time;\n\n    //     if (t > Hmax) {\n    //         return false;\n    //     }\n\n    //     auto it = std::find(forward_graph[t].begin(),\n    //     forward_graph[t].end(),tmp_j); if (it == forward_graph[t].end()) {\n    //         return false;\n    //     }\n\n    // }\n\n    return true;\n}\n", "meta": {"hexsha": "3354efe92d58476cd3d14590273a503d61c9dd58", "size": 19302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PricerSolverSimpleDP.cpp", "max_stars_repo_name": "DanielKowalczyk1984/PM", "max_stars_repo_head_hexsha": "0738c662f7bf95792c86f493525d868d7b7346d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PricerSolverSimpleDP.cpp", "max_issues_repo_name": "DanielKowalczyk1984/PM", "max_issues_repo_head_hexsha": "0738c662f7bf95792c86f493525d868d7b7346d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PricerSolverSimpleDP.cpp", "max_forks_repo_name": "DanielKowalczyk1984/PM", "max_forks_repo_head_hexsha": "0738c662f7bf95792c86f493525d868d7b7346d8", "max_forks_repo_licenses": ["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.5104166667, "max_line_length": 80, "alphanum_fraction": 0.5119676717, "num_tokens": 4989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.024423089166497106, "lm_q1q2_score": 0.01125945427011614}}
{"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 MULTIVARIATIONALUTIL_HH\n#define MULTIVARIATIONALUTIL_HH\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <iostream>\n\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/type_traits/remove_const.hpp>\n\n#include <boost/fusion/algorithm.hpp>\n#include <boost/fusion/sequence.hpp>\n\n#include \"fem/fixdune.hh\"\n#include \"fem/functionspace.hh\"\n#include \"fem/linearspace.hh\"\n#include \"linalg/crsutil.hh\"\n\n/**\n * @file\n * @brief  Variables and their descriptions\n * @author Martin Weiser\n *\n * This file contains a number of core classes of Kaskade, needed to define a problem. The important ones are:\n *\n * - VariableDescription: elementary information about a single variable\n * - VariableSetDescription: information about a set of variables and associated FEFunctionSpace s\n * - VariableSet: a set of variables with all the data stored in FunctionSpaceElement s\n *\n * The other classes are auxilliary\n */\n\n\n//---------------------------------------------------------------------\n\nnamespace Kaskade\n{\n  /**\n   * \\brief A class storing elementary information about a single variable.\n   * \\ingroup variables\n   * This includes the number of components, the id and name of the\n   * variable, and the index of the associated FEFunctionSpace from\n   * which the variable comes.\n   *\n   * \\tparam spaceId the index of the FEFunctionSpace to which the variable belongs.\n   *   This references an external container of FE spaces.\n   * \\tparam components the number of components that this variable has\n   *   (1 indicates a scalar variable, values greater than 1 a vectorial\n   *   variable). Has to be greater than 0.\n   * \\tparam Id the index of the variable by which it can be retrieved from a\n   *   boost::fusion container of variables.\n   *\n   * Note that the order of template parameters is important. A more convenient interface\n   * is provided by \\ref Variable, where the order of template parameters can be arbitrary.\n   */\n  template <int spaceId, int components, int Id>\n  struct VariableDescription\n  {\n    /// number of this variable\n    static int const id = Id;\n    /// number of component of this variable\n    static int const m = components;\n    /// number of the space, this variable is associated with\n    static int const spaceIndex = spaceId;\n  };\n\n\n  /**\n   * \\brief Helper class for specifying the FE space index of a variable.\n   * \n   * This is intended to be used as template argument for \\ref Variable.\n   */\n  template <int spaceIndex>\n  struct SpaceIndex : public VariableDescription<spaceIndex,-1,-1> {};\n\n  /**\n   * \\brief Helper class for specifying the number of components of a variable.\n   * \n   * This is intended to be used as template argument for \\ref Variable.\n   */\n  template <int components>\n  struct Components : public VariableDescription<-1,components,-1> {};\n\n  /**\n   * \\brief Helper class for specifying the id of a variable.\n   * \n   * This is intended to be used as template argument for \\ref Variable.\n   */\n  template <int id>\n  struct VariableId : public VariableDescription<-1,-1,id> {};\n\n\n  /**\n   * \\brief A class storing elementary information about a single variable.\n   * \\ingroup variables\n   *\n   * This includes the number of components, the id and name of the\n   * variable, and the index of the associated FEFunctionSpace from\n   * which the variable comes.\n   *\n   * This class differs from \\ref VariableDescription only in how it is created. The template \n   * parameters should be \\ref SpaceIndex, \\ref Components, and \\ref VariableId, in arbitrary order (but one of each).\n   *\n   * Example (e.g. for a Stokes setting):\n   * \\code\n   * typedef boost::fusion::vector<Variable<SpaceIndex<0>,Components<3>,VariableId<0> >,\n   *                               Variable<Components<1>,VariableId<1>,SpaceIndex<1> > > VariableDescriptions;\n   * \\endcode\n   */\n  template <typename A, typename B, typename C>\n  struct Variable {\n    static int const spaceIndex = A::spaceIndex>=0? A::spaceIndex : B::spaceIndex>=0? B::spaceIndex : C::spaceIndex;\n    static int const m  = A::m>=0? A::m : B::m>=0? B::m : C::m;\n    static int const id = A::id>=0? A::id : B::id>=0? B::id : C::id;\n\n    static_assert(spaceIndex>=0,\"Space index has to be nonnegative (space indices cover a contiguous range from 0 to k-1).\");\n    static_assert(m>=0,\"Number of components has to be nonnegative (in fact, 0 makes rarely sense as well).\");\n    static_assert(id>=0,\"Variable Id has to be nonnegative (ids have to cover a contiguous range from 0 to n-1).\");\n  };\n\n  //---------------------------------------------------------------------\n\n  /**\n   * \\brief A boost::fusion functor for generating function space elements for given variables.\n   *\n   * \\tparam Spaces: a boost::fusion container of pointers to FEFunctionSpace s.\n   */\n  template <class Spaces>\n  struct ConstructElement\n  {\n    ConstructElement(Spaces const& spaces_):\n      spaces(spaces_)\n    {}\n\n    /**\n     * \\brief For a given variable, defines the correct FunctionSpaceElement type. \n     * \n     * This depends on the spaceIndex and the number of components defined by the Variable (which is a VariableDescription).\n     */\n    template <typename Arg> struct result {};\n\n    template <class Variable>\n    struct result<ConstructElement<Spaces>(Variable)>\n    {\n      typedef typename boost::remove_reference<Variable>::type Var;\n      typedef typename SpaceType<Spaces,Var::spaceIndex>::type Space;\n      typedef typename Space::template Element<Var::m>::type type;\n    };\n\n    /**\n     * \\brief Returns a FunctionSpaceElement element from the FEFunctionSpace associated to the Variable.\n     */\n    template <class Variable>\n    typename result<ConstructElement<Spaces>(Variable)>::type operator()(Variable const& variable) const\n    {\n      return typename result<ConstructElement<Spaces>(Variable)>::type(*boost::fusion::at_c<Variable::spaceIndex>(spaces));\n    }\n\n  private:\n    Spaces const& spaces;\n  };\n\n  /**\n   * \\brief A boost::fusion functor for generating coefficient vectors for given variables.\n   *\n   * \\tparam Spaces: a boost::fusion container of pointers to FEFunctionSpace s.\n   */\n  template <class Spaces>\n  struct ConstructCoefficientVector\n  {\n    ConstructCoefficientVector(Spaces const& spaces_):\n      spaces(spaces_)\n    {}\n\n    /**\n     * For a given variable (VariableDescription), defines the correct\n     * coefficient vector type. This depends on the space index and the\n     * number of components defined by the variable.\n     */\n    template <typename Arg> struct result {};\n\n    template <class Variable>\n    struct result<ConstructCoefficientVector<Spaces>(Variable)>\n    {\n      typedef typename boost::remove_reference<Variable>::type Var;\n      typedef typename SpaceType<Spaces,Var::spaceIndex>::type Space;\n      typedef typename Space::template Element<Var::m>::type::StorageType StorageType;\n\n      typedef Dune::BlockVector<typename StorageType::block_type> type;\n    };\n\n    /**\n     * \\brief Returns a FunctionSpaceElement from the FEFunctionSpace associated to the variable.\n     *\n     * This is currently not very efficient. This may change when Dune starts supporting\n     * move-semantics(C++11). Alternatively it may make sense to return only the dof instead\n     * of the full matrix and construct the latter later on.\n     */\n    template <class Variable>\n    typename result<ConstructCoefficientVector<Spaces>(Variable)>::type operator()(Variable const& variable) const\n    {\n      return typename result<ConstructCoefficientVector<Spaces>(Variable)>::type(boost::fusion::at_c<Variable::spaceIndex>(spaces)->degreesOfFreedom());\n    }\n\n  private:\n    Spaces const& spaces;\n  };\n\n  //---------------------------------------------------------------------\n  \n  /**\n   * \\cond internals\n   */\n  namespace Variables_Detail \n  {\n    \n    // A functor constructing representations of consecutive subsets of variables\n    template <class Variables, class RepresentationConstructor,\n              int first=0, int last=boost::fusion::result_of::size<Variables>::type::value>\n    class VariableRangeCreator\n    {\n      typedef typename boost::fusion::result_of::begin<Variables>::type       Begin;\n      typedef typename boost::fusion::result_of::advance_c<Begin,first>::type First;\n      typedef typename boost::fusion::result_of::advance_c<Begin,last>::type  Last;\n      \n    public:\n      typedef typename boost::fusion::transform_view<boost::fusion::iterator_range<First,Last> const,\n                                                     RepresentationConstructor> View;\n      typedef typename boost::fusion::result_of::as_vector<View>::type type;\n      \n      static View apply(RepresentationConstructor const& c)\n      {\n        using namespace boost::fusion;\n        Variables vars;\n        return transform(iterator_range<First,Last>(advance_c<first>(begin(vars)),advance_c<last>(begin(vars))),c);\n      }\n    };\n  }\n  /**\n   * \\endcond\n   */\n\n  //---------------------------------------------------------------------\n\n  /**\n   * \\ingroup variables\n   * \\brief A class for storing a heterogeneous collection of FunctionSpaceElement s.\n   * \\tparam Descriptions a VariableSetDescription class \n   *\n   * Basic vector operations and I/O are supported.\n   *\n   * The type of a VariableSet is defined via a VariableSetDescription, which contains information\n   * about the variables in form of a boost::fusion::vector of FEFunctionSpace s and VariableDescription s.\n   * The type of a VariableSet can be determined by VariableSetDescription::VariableSet.\n   *\n   * VariableSet s contains a collection of FunctionSpaceElement s (vars) and a reference to its VariableSetDescription (descriptions). \n   * Simultaneous evaluation of all functions is supported by \\ref evaluateVariables.\n   *\n   * Usually, solutions are stored in VariableSets. Access to data is via the public member\n   * variable data, which is a boost::fusion::vector of \\ref FunctionSpaceElement s\n   */\n  template <class VSDescriptions>\n  class VariableSet: public LinearProductSpace<typename VSDescriptions::Scalar, typename VSDescriptions::RepresentationData>\n  {\n  public:\n    /// Type of the VariableSetDescription\n    typedef VSDescriptions Descriptions;\n\n    /// boost::fusion::vector of data elements (of type FunctionSpaceElement)\n    typedef typename VSDescriptions::RepresentationData Functions;\n\n  private:\n    typedef VariableSet<Descriptions> Self;\n    typedef typename SpaceType<typename Descriptions::Spaces,0>::type::Scalar Scalar;\n    typedef LinearProductSpace<Scalar,Functions> Base;\n\n    /// Grid type\n    typedef typename Descriptions::Grid Grid;\n\n  public:\n    typedef LinearProductSpace<Scalar,Functions> LinearSpace;\n\n    /// Copy constructor\n    VariableSet(Self const& vs):\n      Base(vs.data), descriptions(vs.descriptions)\n    {}\n\n    /**\n     * \\brief Constructor\n     * \n     * \\param d the VariableSetDescription object (has to exist during the lifetime of this VariableSet).\n     */\n    explicit VariableSet(Descriptions const& d):\n        Base(Variables_Detail::VariableRangeCreator<typename Descriptions::Variables,ConstructElement<typename Descriptions::Spaces> >::apply(\n          ConstructElement<typename Descriptions::Spaces>(d.spaces))), \n        descriptions(d)\n    {}\n\n    /// Assignment\n    Self& operator=(Self const& v) {\n      if (this!=&v) this->data = v.data;\n      return *this;\n    }\n\n    /// Assignment forwarded to the linear space base class\n    template <class S>\n    Self& operator=(S const& s)\n    {\n      static_cast<Base&>(*this) = s;\n      return *this;\n    }\n\n\n    /// Descriptions of variable set, of type VariableSetDescription (lots of useful infos)\n    Descriptions const& descriptions;\n  };\n\n  //---------------------------------------------------------------------\n\n\n  /**\n   * \\ingroup variables\n   * \\brief A class that stores information about a set of variables.\n   *\n   * This includes in particular references to a list of variable\n   * descriptions, a list of FEFunctionSpace s, a Grid, and an IndexSet.\n   *\n   *\n   * \\tparam SpaceList a boost::fusion container of FEFunctionSpace s\n   * \\tparam VariableList a boost::fusion container of VariableDescription s. Note that\n   *   the variable id's have to be consecutive starting at 0, and shall be ordered.\n   */\n  template <class SpaceList, class VariableList>\n  class VariableSetDescription\n  {\n  public:\n    /// type of boost::fusion::vector of FEFunctionSpace s needed\n    typedef SpaceList Spaces;\n    /// type of boost::fusion vector of VariableDescription s\n    typedef VariableList Variables;\n\n    /**\n     * \\brief Type that contains a set of variables inside a boost vector, together with all the data\n     */\n    typedef typename Variables_Detail::VariableRangeCreator<Variables,ConstructElement<Spaces>>::type RepresentationData;\n\n    /**\n     * \\brief Type that contains a set of variable values with some\n     * functionality, such as simple vector arithmetic and so on\n     * (cf. class \\ref VariableSet)\n     *\n     * Construct an object r of this type from a given VariableSetDescription vsd by:\n     * \\code\n     * VariableSetDescription::VariableSet r(vsd);\n     * \\endcode\n     */\n    typedef Kaskade::VariableSet<VariableSetDescription<Spaces,Variables>> VariableSet;\n    \n    /// scalar field type\n    typedef typename SpaceType<Spaces,0>::type::Scalar   Scalar;\n    /// Grid type\n    typedef typename SpaceType<Spaces,0>::type::Grid     Grid;\n    /// Grid view type\n    typedef typename SpaceType<Spaces,0>::type::GridView GridView;\n    /// IndexSet type\n    typedef typename SpaceType<Spaces,0>::type::IndexSet IndexSet;\n\n    /// Number of variables in this set\n    static int const noOfVariables = boost::fusion::result_of::size<Variables>::type::value;\n    \n    /**\n     * \\brief The boost::fusion sequence of evaluators belonging to this variable set.\n     */\n    typedef typename boost::fusion::result_of::as_vector<\n          typename boost::fusion::result_of::transform<Spaces, GetEvaluators<ShapeFunctionCache<Grid,Scalar>> >::type\n          >::type Evaluators;\n\n\n    /// Constructor, giving each variable a name (e.g. for output purposes)\n    template <class RAIter>\n    VariableSetDescription(Spaces const& spaces_, RAIter nameIt):\n      VariableSetDescription(spaces_)\n    {\n      std::copy(nameIt,nameIt+noOfVariables,names.begin());\n    }\n\n    /**\n     * \\brief Constructor specifying for each variable a name.\n     */\n    VariableSetDescription(Spaces const& spaces_, std::vector<std::string> names_):\n      VariableSetDescription(spaces_)\n    {\n      std::copy(names_.begin(),names_.end(),names.begin());\n    }\n\n    /**\n     * \\brief Constructor specifying for each variable both a name and a role.\n     */\n    template <class RAIter>\n    VariableSetDescription(Spaces const& spaces_, RAIter nameIt, RAIter roleIt):\n      VariableSetDescription(spaces_,nameIt)\n    {\n      std::copy(roleIt,roleIt+noOfVariables,roles.begin());\n    }\n\n    /**\n     * \\brief Constructor specifying for each variable both a name and a role.\n     */\n    VariableSetDescription(Spaces const& spaces_, std::vector<std::string> names_, std::vector<std::string> roles_)\n      : VariableSetDescription(spaces_,names_)\n    {\n      std::copy(roles_.begin(),roles_.end(),roles.begin());\n    }\n\n    /// Constructor without naming the variables\n    VariableSetDescription(Spaces const& spaces_):\n      spaces(spaces_),\n      gridView(boost::fusion::at_c<0>(spaces_)->gridView()),\n      indexSet(boost::fusion::at_c<0>(spaces_)->indexSet())\n    {}\n\n    /**\n     * \\brief Computes the total number of scalar degrees of freedom collected in the variables [first,last).\n     * \n     * For each affected variable, the number of components is multiplied with the degrees of freedom of its FE space.\n     */\n    size_t degreesOfFreedom(int first=0, int last=noOfVariables) const\n    {\n      return degreesOfFreedom(spaces,first,last);\n    }\n\n    /**\n     * \\brief Computes the total number of scalar degrees of freedom collected in the variables [first,last).\n     * \n     * For each affected variable, the number of components is multiplied with the degrees of freedom of its FE space.\n     */\n    static size_t degreesOfFreedom(Spaces const& spaces, int first, int last)\n    {\n      auto dimensions = variableDimensions(spaces);\n      assert(0<=first && first<=last && last<=dimensions.size());\n      return std::accumulate(begin(dimensions)+first,begin(dimensions)+last,0);\n    }      \n    \n    /**\n     * \\brief Computes for each variable the number of scalar degrees of freedom.\n     */\n    static std::array<size_t,noOfVariables> variableDimensions(Spaces const& spaces, int first=0, int last=noOfVariables)\n    {\n      std::array<size_t,noOfVariables> dimensions;\n      boost::fusion::for_each(VariableList(),ComputeDimension<noOfVariables>(dimensions,spaces));\n      return dimensions;\n    }\n\n    /**\n     * \\brief number of components of idx'th variable\n     */\n    template <int idx>\n    struct Components { static int const m = boost::fusion::result_of::value_at_c<VariableList,idx>::type::m; };\n\n    /// space index of idx'th variable\n    template <int idx>\n    struct SpaceIndex { static int const spaceIndex = boost::fusion::result_of::value_at_c<VariableList,idx>::type::spaceIndex; };\n\n    /**\n     * \\brief Typedefs for coefficient vector representations of contiguous subranges of the variables.\n     * \n     * Note that the representation defined by this class does not consist of FE functions.\n     *\n     * Since in contrast to FE functions the linear algebra coefficient\n     * vectors are invalidated during mesh adaptation, the coefficient\n     * vectors should be copied to FE functions before mesh refinement.\n     */\n    template <int first=0, int last=noOfVariables>\n    class CoefficientVectorRepresentation \n    {\n      typedef Variables_Detail::VariableRangeCreator<Variables,ConstructCoefficientVector<Spaces>,first,last> Creator;\n\n    public:\n      /**\n       * \\brief A linear product space of FE coefficient vectors for the variables.\n       * Note that this is not a linear space of\n       * FE functions, only of coefficient vectors. In contrast to FE\n       * functions, coefficient vectors are invalidated during mesh\n       * adaptation.\n       */\n      typedef LinearProductSpace<Scalar,typename Creator::type> type;\n\n      /**\n       * \\brief DEPRECATED. Use init(spaces) instead. Will be removed after 2014-05-01.\n       */\n      static typename Creator::View init(VariableSetDescription const& vardesc) __attribute__((deprecated)) {\n        static bool called = false;\n        if (called==false)\n        {\n          called = true;\n          std::cerr << \"Deprecated function CoefficientVectorRepresentation::init(vardesc) called. Use init(spaces) instead.\\n\"\n                    << \"This method will cease to work at the end of 2014.\\n\";\n        }\n        return init(vardesc.spaces);\n      }\n      \n      /**\n       * \\brief Returns a (small) initializer object for coefficient vectors.\n       * \n       * The coeffcient vectors initialized with the returned initializer object are set to zero.\n       */\n      static typename Creator::View init(Spaces const& spaces) {\n        return Creator::apply(ConstructCoefficientVector<Spaces>(spaces));\n      }\n    };\n\n    /// spaces\n    Spaces const&      spaces;\n    \n    /**\n     * \\brief The grid view on which the variables live.\n     */\n    GridView const&    gridView;\n    \n    /**\n     * \\brief The gridManager keeping the grid on which we operate.\n     */\n    GridManagerBase<Grid> const& gridManager() const { return boost::fusion::at_c<0>(spaces)->gridManager(); }\n\n    /// index set\n    IndexSet const&    indexSet;\n    \n    /// names\n    std::array<std::string,noOfVariables>  names;\n\n    std::array<std::string,noOfVariables>  roles;\n\n  private:\n\n    struct CheckHasEqualGridAndIndexSet\n    {\n      CheckHasEqualGridAndIndexSet(GridManagerBase<Grid> const* gp_, IndexSet const* isp_):\n        gp(gp_), isp(isp_)\n      {}\n\n      template <class Space>\n      void operator()(Space const* space) const {\n        assert(&(space->gridManager())== gp);\n        assert(&(space->indexSet()) == isp);\n      }\n\n      GridManagerBase<Grid> const* gp;\n      IndexSet const* isp;\n    };\n\n    template <int nvars>\n    struct ComputeDimension\n    {\n      ComputeDimension(std::array<size_t,nvars>& dims, Spaces const& spaces_):\n        dims_(dims), spaces(spaces_)\n      {}\n\n      template <class Variable>\n      void operator()(Variable const& /* v */) const\n      {\n        assert(dims_.size()>Variable::id);\n        dims_[Variable::id] = Variable::m * boost::fusion::at_c<Variable::spaceIndex>(spaces)->degreesOfFreedom();\n      }\n\n      std::array<size_t,nvars>& dims_;\n      Spaces const&             spaces;\n    };\n\n  };\n\n  //---------------------------------------------------------------------\n  //---------------------------------------------------------------------\n  \n\n  /**\n   * \\ingroup variables\n   * \\brief A function evaulating all functions in a variable set using the provided method.\n   * \n   * \\tparam VariableSet a heterogeneous sequence of variable descriptions (defines the mapping of functions to evaluators)\n   * \\tparam Functions a heterogeneous sequence of FE functions (or function views)\n   * \\tparam Evaluators the heterogeneous container of evaluators for the variable set \n   * \\tparam Method a polymorphic Functor type with call operator (Function const&, Evaluator const&)\n   * \n   * \\param vars the variable set to be evaluated.\n   * \\param eval the evaluators to be used for function evaluation\n   * \\param method the functor performing the actual evaluation\n   * \n   *  evaluateVariables valueMethod ValueMethod derivativeMethod DerivativeMethod\n   */\n  template <class VariableDescriptions, class Functions, class Evaluators, class Method>\n  auto evaluateFunctions(Functions const& fs,\n                         Evaluators const& eval,\n                         Method const& method = Method())\n  {\n    using namespace boost::fusion;\n    \n    // Define the functor that evaluates the individual variables.\n    auto doEval = [&] (auto const& pair)\n    {\n      // Extract the space index from the second component of the pair provided by zip.\n      static int const sid = std::remove_reference_t<typename result_of::value_at_c<std::remove_reference_t<decltype(pair)>,1>::type>::spaceIndex;\n      // Evaluate with evaluator corresponding to the function's space.\n      return method(at_c<0>(pair),at_c<sid>(eval));\n    };\n    \n    // We need this as vector type to default construct an object for transform. This way we can submit\n    // views (such as joint_view) as template parameter.\n    using VarDesc = typename result_of::as_vector<VariableDescriptions>::type;\n    \n    // For evaluation, the corresponding evaluator must be used based on the space index of the variables. To provide this,\n    // we zip the functions with their variable descriptions to pairs from which we can extract both function and space index.\n    return as_vector(transform(zip(fs,VarDesc()),doEval));\n  }\n  \n  /**\n   * \\ingroup variables\n   * \\brief A function evaulating all functions in a variable set using the provided method.\n   * \n   * \\tparam VariableSet the type of the variable set to be evaluated (i.e. VariableSet<...>)\n   * \\tparam Method a polymorphic Functor type with call operator (Function const&, Evaluator const&)\n   * \n   * \\param vars the variable set to be evaluated.\n   * \\param eval a heterogeneous sequence of evaluators to be used for function evaluation\n   * \\param method the functor performing the actual evaluation\n   * \n   * \\see EvaluateVariables evaluateFunctions valueMethod ValueMethod derivativeMethod DerivativeMethod\n   */\n  template <class VariableSet, class Method>\n  auto evaluateVariables(VariableSet const& vars,\n                         typename VariableSet::Descriptions::Evaluators const& eval,\n                         Method const& method = Method())\n  {\n    return evaluateFunctions<typename VariableSet::Descriptions::Variables>(vars.data,eval,method);\n  }\n  \n  /**\n   * \\ingroup variables\n   * \\brief The type of evaluated variables as returned by \\ref evaluateVariables.\n   * \n   * This is a boost::fusion sequence of functions' values resulting from evaluating all functions in a given variable set.\n   * \\tparam VariableSet the type of the variable set (i.e. VariableSet<...>)\n   * \\tparam Method a polymorphic Functor type with call operator (Function const&, Evaluator const&) used for evaluating.\n   * \n   * \\related evaluateVariables\n   */\n  template <class VariableSet, class Method>\n  using EvaluateVariables = decltype(evaluateVariables(std::declval<VariableSet>(),\n                                                       std::declval<typename VariableSet::Descriptions::Evaluators>(),\n                                                       std::declval<Method>()));\n\n\n  /**\n   * \\ingroup variables\n   * \\brief Helper method for evaluating whole variable sets.\n   * \n   * Use this in calling evaluateVariables when evaluating the functions' values.\n   */\n  auto valueMethod = [](auto const& f, auto const& eval) { return f.value(eval); };\n  \n  /**\n   * \\ingroup variables\n   * \\brief Helper method for evaluating whole variable sets.\n   * \n   * Use this in calling evaluateVariables when evaluating the functions' derivatives.\n   */\n  auto derivativeMethod = [](auto const& f, auto const& eval) { return f.derivative(eval); };\n  \n  /**\n   * \\ingroup variables\n   * \\brief The type of the valueMethod helper functor.\n   */\n  using ValueMethod = decltype(valueMethod);\n  \n  /**\n   * \\ingroup variables\n   * \\brief The type of the derivativeMethod helper functor.\n   */\n  using DerivativeMethod = decltype(derivativeMethod);\n\n} // end of namespace Kaskade\n\n\n\n\n//---------------------------------------------------------------------\n//---------------------------------------------------------------------\n//---------------------------------------------------------------------\n\n#endif\n", "meta": {"hexsha": "34394c63c07e6b02eacad6c6a08faa73bae0af77", "size": 26894, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/variables.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/variables.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/variables.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": 38.2560455192, "max_line_length": 152, "alphanum_fraction": 0.653342753, "num_tokens": 5866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069437044942166, "lm_q2_score": 0.03622005521475954, "lm_q1q2_score": 0.011253367252593008}}
{"text": "#include <ros/ros.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <sepanta_msgs/upperbodymotors.h>\n#include <sepanta_msgs/upperbodymotorsfeedback.h>\n#include <sepanta_msgs/motorfeedback.h>\n#include <sepanta_msgs/motor.h>\n#include <sepanta_msgs/motorreset.h>\n#include <sepanta_msgs/motorpid.h>\n#include <sepanta_msgs/motortorque.h>\n#include <sepanta_msgs/grip.h>\n#include <std_msgs/String.h>\n#include <boost/thread.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <sepanta_msgs/command.h>\n#include <ik/simple_IK.h>\n#include <ik/traj_IK.h>\n#include <upperbody_core/sepanta_ik.h>\n\nIKSystem::IKSystem(ros::NodeHandle n)\n{\n   node_handle = n;\n   init();\n}\n\nvoid IKSystem::init_configs()\n{\n    motor_range m;\n\n    m.max = 1023;\n    m.min = 0;\n    m.degree = 300;\n    m.name = \"RX-28\";\n    list_motor_configs.push_back(m);\n    //===========================================\n   \n    m.max = 1023;\n    m.min = 0;\n    m.degree = 300;\n    m.name = \"RX-64\";\n    list_motor_configs.push_back(m);\n    //===========================================\n  \n    m.max = 4095;\n    m.min = 0;\n    m.degree = 360;\n    m.name = \"MX-28\";\n    list_motor_configs.push_back(m);\n    //===========================================\n    \n    m.max = 4095;\n    m.min = 0;\n    m.degree = 360;\n    m.name = \"MX-64\";\n    list_motor_configs.push_back(m);\n    //===========================================\n  \n    m.max = 4095;\n    m.min = 0;\n    m.degree = 360;\n    m.name = \"MX-106\";\n    list_motor_configs.push_back(m);\n}\n\nfloat IKSystem::convert_motor_to_degree(string model_name,float value)\n{\n    if ( model_name == \"MX-106\")\n    {\n        int max_deg = list_motor_configs.at(4).degree;\n        int min_pos = list_motor_configs.at(4).min;\n        int max_pos = list_motor_configs.at(4).max;\n        float result = roundf(((max_deg * float(value - min_pos)) / (max_pos - min_pos + 1)) - (max_deg / 2));\n        return result;\n    }\n    else\n    if ( model_name == \"MX-64\")\n    {\n        int max_deg = list_motor_configs.at(3).degree;\n        int min_pos = list_motor_configs.at(3).min;\n        int max_pos = list_motor_configs.at(3).max;\n        float result = roundf(((max_deg * float(value - min_pos)) / (max_pos - min_pos + 1)) - (max_deg / 2));\n        return result;\n    }\n\n    return -1;\n}\n\nfloat IKSystem::convert_degreeMotor_to_degreeIK(int index,float value)\n{\n    if ( index == 1) return (-1 * (value - 85) / 1.64); else\n    if ( index == 2) return (-1 * (value - 27) / 1.64); else\n    if ( index == 3) return (-1 * (value - 22) / 1.64); else \n    return -1;\n}\n\nfloat IKSystem::convert_degreeIK_to_degreeMotor(int index,float value)\n{\n    if ( index == 1) return (value * -1 * 1.64 + 85); else\n    if ( index == 2) return (value * -1 * 1.64 + 27); else\n    if ( index == 3) return (value * -1 * 1.64 + 22); else \n\n    return -1;\n}\n\nint IKSystem::convert_degree_to_motor(string model_name,float value)\n{\n    if ( model_name == \"MX-106\")\n    {\n        int max_deg = list_motor_configs.at(4).degree;\n        int min_pos = list_motor_configs.at(4).min;\n        int max_pos = list_motor_configs.at(4).max;\n        int pos = 0;\n        pos = (int)(roundf((max_pos - 1) * ((max_deg / 2 + float(value)) / max_deg)));\n        pos = min(max(pos, 0), max_pos - 1);\n        return pos;\n    }\n    else\n    if ( model_name == \"MX-64\")\n    {\n        int max_deg = list_motor_configs.at(3).degree;\n        int min_pos = list_motor_configs.at(3).min;\n        int max_pos = list_motor_configs.at(3).max;\n        int pos = 0;\n        pos = (int)(roundf((max_pos - 1) * ((max_deg / 2 + float(value)) / max_deg)));\n        pos = min(max(pos, 0), max_pos - 1);\n        return pos;\n    }\n\n   \n    return -1;\n}\n\nvoid IKSystem::scale_velocity(double * v1,double * v2 , double * v3,int size)\n{\n   double max = 0;\n   for ( int i = 0 ; i < size ; i++)\n   {\n   \t  if ( abs(v1[i]) > max ) max = abs(v1[i]);\n   \t  if ( abs(v2[i]) > max ) max = abs(v2[i]);\n   \t  if ( abs(v3[i]) > max ) max = abs(v3[i]);\n   }\n   \n   for  ( int i = 0 ; i < size ; i++)\n   {\n   \t   v1[i] = motor_max_speed * v1[i] / max;\n   \t   v2[i] = motor_max_speed * v2[i] / max;\n   \t   v3[i] = motor_max_speed * v3[i] / max;\n   }\n}\n\nbool IKSystem::convert_all_positions(double * positions,int size)\n{\n\n   for ( int i = 0 ; i < size ; i++)\n   {\n       positions[i] =  convert_degree_to_motor(\"MX-64\",convert_degreeIK_to_degreeMotor(1,Rad2Deg(positions[i])));\n       if ( positions[i] > current_data[0].max || positions[i] < current_data[0].min ) return false;\n       \n       positions[i + size] =  convert_degree_to_motor(\"MX-64\",convert_degreeIK_to_degreeMotor(2,Rad2Deg(positions[i + size])));\n       if ( positions[i + size] > current_data[1].max || positions[i + size] < current_data[1].min ) return false;\n       \n       positions[i + 2 * size] =  convert_degree_to_motor(\"MX-64\",convert_degreeIK_to_degreeMotor(3,Rad2Deg(positions[i + 2 * size])));\n       if ( positions[i + size * 2] > current_data[2].max || positions[i + 2 * size] < current_data[2].min ) return false;\n   }\n\n   return true;\n}\n\nint IKSystem::convert_radPerSecond_to_speedMotor(double value)\n{\n    int direction = 0;\n\n    if (value < 0) \n         direction = 1024 ;\n    \n \n    double max_value = 1023 * 0.114 * 6;\n\n    //value = min(max(value, -max_value), max_value);\n    int speed = (int)(round(direction + abs(value) / (6 * 0.114)));\n\n    return speed;\n}\n\nvoid IKSystem::motors_callback(const sepanta_msgs::upperbodymotorsfeedback::ConstPtr &msg)\n{\n   sepanta_msgs::motorfeedback m1 = msg->motorfeedbacks.at(0);\n   sepanta_msgs::motorfeedback m2 = msg->motorfeedbacks.at(1);\n   sepanta_msgs::motorfeedback m3 = msg->motorfeedbacks.at(2);\n \n   ros::Time timeNow = ros::Time::now();\n\n   current_data[0].position = m1.position;\n   current_data[0].speed = m1.speed;\n   current_data[0].min = m1.min;\n   current_data[0].init = m1.init;\n   current_data[0].max = m1.max;\n   current_data[0].timestamp = timeNow;\n\n   current_data[1].position = m2.position;\n   current_data[1].speed = m2.speed;\n   current_data[1].min = m2.min;\n   current_data[1].init = m2.init;\n   current_data[1].max = m2.max;\n   current_data[1].timestamp = timeNow;\n\n   current_data[2].position = m3.position;\n   current_data[2].speed = m3.speed;\n   current_data[2].min = m3.min;\n   current_data[2].init = m3.init;\n   current_data[2].max = m3.max;\n   current_data[2].timestamp = timeNow;\n\n   double p1  = Deg2Rad(convert_degreeMotor_to_degreeIK(1,convert_motor_to_degree(\"MX-64\",current_data[0].position)));\n   double p2  = Deg2Rad(convert_degreeMotor_to_degreeIK(2,convert_motor_to_degree(\"MX-64\",current_data[1].position)));\n   double p3  = Deg2Rad(convert_degreeMotor_to_degreeIK(3,convert_motor_to_degree(\"MX-64\",current_data[2].position)));\n  \n   current_data[0].position_rad_ik = p1;\n   current_data[1].position_rad_ik = p2;\n   current_data[2].position_rad_ik = p3;\n \n   double c1  = convert_degree_to_motor(\"MX-64\", convert_degreeIK_to_degreeMotor(1,Rad2Deg(p1)));\n   double c2  = convert_degree_to_motor(\"MX-64\", convert_degreeIK_to_degreeMotor(2,Rad2Deg(p2)));\n   double c3  = convert_degree_to_motor(\"MX-64\", convert_degreeIK_to_degreeMotor(3,Rad2Deg(p3)));\n  \n   //std::cout<<\"check 1 : \"<<current_data[0].position<<\" alireza 1 : \"<<p1<<\" motor 1 : \"<<c1<<std::endl;\n   //std::cout<<\"check 2 : \"<<current_data[1].position<<\" alireza 2 : \"<<p2<<\" motor 2 : \"<<c2<<std::endl;\n   //std::cout<<\"check 3 : \"<<current_data[2].position<<\" alireza 3 : \"<<p3<<\" motor 3 : \"<<c3<<std::endl;\n}\n\nvoid IKSystem::update_arm_motors(int positions[3],int speed[3])\n{\n    sepanta_msgs::motor _msg;\n\n    _msg.position = positions[0];\n    _msg.speed = abs(speed[0]);\n   // cout<<\"1 :\"<<_msg.position<<\" \"<<_msg.speed<<endl;\n    motor_pub[0].publish(_msg);\n\n    _msg.position = positions[1];\n    _msg.speed = abs(speed[1]);\n  //  cout<<\"2 :\"<<_msg.position<<\" \"<<_msg.speed<<endl;\n    motor_pub[1].publish(_msg);\n\n    _msg.position = positions[2];\n    _msg.speed = abs(speed[2]);\n  //  cout<<\"3 :\"<<_msg.position<<\" \"<<_msg.speed<<endl;\n    motor_pub[2].publish(_msg);\n}\n\nvoid IKSystem::update_pen_motor(int position,int speed)\n{\n    sepanta_msgs::motor _msg;\n    _msg.position = position;\n    _msg.speed = speed;\n    motor_pub[4].publish(_msg);\n}\n\nbool IKSystem::SepantaIK(double x0, double y0, double (&q_goal)[3])\n{\n    double l1 = 220;\n    double l2 = 246;\n    double c2 = ((x0*x0)+(y0*y0)-(l1*l1)-(l2*l2))/(2*l1*l2);\n    double q21 = atan2(sqrt(1-(c2*c2)),c2);\n    double q22 = atan2(-sqrt(1-(c2*c2)),c2);\n    double q2 = 0;\n    if(q21<3.313 && q21>0.217) q2 = q21;\n    else if(q22<3.313 && q22>0.217) q2 = q22;\n    else return false;\n\n    double k1 = l1+l2*cos(q2);\n    double k2 = l2*sin(q2);\n    double q1 = atan2(y0,x0)-atan2(k2,k1);    \n\n    q_goal[0] = q1;\n    q_goal[1] = q2;\n    q_goal[2] = 1.5707963267948966 - (q1+q2);\n\n    return true;\n}\n\nbool IKSystem::open_challange(double q0[3], double x0, double y0, double (&q_goal)[3])\n{\n  double T1[16] = {0};\n  int i0;\n  static const signed char iv0[4] = { 0, 0, -1, 0 };\n\n  static const signed char iv1[4] = { 0, 0, 0, 1 };\n\n  double E;\n  double q2;\n  double q3;\n  double er1;\n  double er2;\n  double B;\n  double x;\n\n  //  --- get next point and give to IK ---\n  //  -----------------------\n  T1[12] = x0;\n  T1[13] = y0;\n\n  for (i0 = 0; i0 < 4; i0++)\n  {\n    T1[2 + (i0 << 2)] = iv0[i0];\n    T1[3 + (i0 << 2)] = iv1[i0];\n  }\n\n  //  === newq = ik_sepanta(q0,T1,L) ===\n  E = 100.0;\n\n  //  ----------------------\n  q2 = q0[0];\n  q3 = q0[1];\n\n  //  ----------------------\n  //  ----------------------\n  //  ----------------------\n  int max_iteration = 100000;\n  while (ros::ok()) \n  {\n    //cout<<\"Error :\"<<E<<\" \"<<max_iteration<<endl;\n    er1 = (22.0 * cos(q2) + 24.8 * cos(q2 + q3)) - T1[12] + 8.5;\n    er2 = (22.0 * sin(q2) + 24.8 * sin(q2 + q3)) - T1[13] + 8;\n    E = er1 * er1 + er2 * er2;\n    B = q2 + q3;\n    x = q2 + q3;\n    q2 += -0.01 * (2.0 * er1 * (-22.0 * sin(q2) - 24.8 * sin(q2 + q3)) + 2.0 * er2 * (22.0 * cos(q2) + 24.8 * cos(q2 + q3)));\n    q3 += -0.01 * (2.0 * er1 * (-24.8 * sin(B)) + 2.0 * er2 * (24.8 * cos(x)));\n  \n    if((int)E<20 || max_iteration < 0) break;\n    max_iteration --;\n  }\n\n   // cout<<\"Error :\"<<E<<endl;\n\n  if ( max_iteration <= 0 )\n  {\n    //problem\n    return false;\n  }\n\n  //  ----------------------\n  q_goal[0] = q2;\n  q_goal[1] = q3;\n  q_goal[2] = (-1.5707963267948966 - q2) - q3;\n\n  \n  return true;\n}\n\nstring IKSystem::go_to_xy(int x,int y,int time)\n{\n     double q0[3] =  { current_data[0].position_rad_ik, \n                       current_data[1].position_rad_ik,\n                       current_data[2].position_rad_ik};\n\n     cout<<\"IK start \"<<q0[0]<<\" \"<<q0[1]<<\" \"<<q0[2]<<endl;\n\n     double f[2] = { x / 10 , y / 10};\n     int frq=40;\n     int TE=time;\n     int samples = frq*TE;\n     emxArray_real_T v1;\n     v1.data = new double[samples];\n     v1.size = new int[2];\n     v1.size[0]=1;\n     v1.size[1]=samples;\n     v1.allocatedSize=samples;\n     v1.numDimensions=2;\n     v1.canFreeData=false;\n     \n     emxArray_real_T v2;\n     v2.data = new double[samples];\n     v2.size = new int[2];\n     v2.size[0]=1;\n     v2.size[1]=samples;\n     v2.allocatedSize=samples;\n     v2.numDimensions=2;\n     v2.canFreeData=false;\n\n     emxArray_real_T v3;\n     v3.data = new double[samples];\n     v3.size = new int[2];\n     v3.size[0]=1;\n     v3.size[1]=samples;\n     v3.allocatedSize=samples;\n     v3.numDimensions=2;\n     v3.canFreeData=false;\n\n     emxArray_real_T q1;\n     q1.data = new double[samples * 3];\n     q1.size = new int[2];\n     q1.size[0]=3;\n     q1.size[1]=samples;\n     q1.allocatedSize=samples * 3;\n     q1.numDimensions=2;\n     q1.canFreeData=false;\n\n     bool result = traj_IK(q0, f,TE,frq,&q1, &v1, &v2,&v3);\n\n    if ( result )\n    {\n        bool result2 = convert_all_positions(q1.data,samples);\n        if ( result2 == false )\n        {\n           //cout<<\"Motor Limitation error - go to cancled\"<<endl;\n           return \"ERROR MOTOR LIMITATION\";\n        }\n        scale_velocity(v1.data,v2.data,v3.data,samples);\n\n        int speeds[3];\n        int positions[3];\n\n        for ( int i = 1 ; i < samples ; i++ )\n        {\n            positions[0] = (int)q1.data[i];\n            positions[1] = (int)q1.data[i + samples];\n            positions[2] = (int)q1.data[i + 2 * samples];\n              \n            speeds[0] = (int)v1.data[i];\n            speeds[1] = (int)v2.data[i];\n            speeds[2] = (int)v3.data[i];\n\n        \t  update_arm_motors(positions,speeds);\n\n            //cout<<\"step :\"<<i<<endl;\n        \t  boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / frq));\n        }\n\n        return \"DONE\";\n    }\n    else\n    {\n        return \"ERROR IK\";\n    }\n\n}\n\nvoid IKSystem::init()\n{\n  init_configs();\n\n  ros::NodeHandle n2;\n  sub_handles = n2.subscribe(\"/upperbodycoreout_feedback\", 10, &IKSystem::motors_callback,this);\n  //============================================================================================\n  motor_pub[0] = node_handle.advertise<sepanta_msgs::motor>(\"/upperbodycorein_right_1\", 1);\n  motor_pub[1] = node_handle.advertise<sepanta_msgs::motor>(\"/upperbodycorein_right_2\", 1);\n  motor_pub[2] = node_handle.advertise<sepanta_msgs::motor>(\"/upperbodycorein_right_3\", 1);\n  motor_pub[3] = node_handle.advertise<sepanta_msgs::motor>(\"/upperbodycorein_right_4\", 1);\n  motor_pub[4] = node_handle.advertise<sepanta_msgs::motor>(\"/upperbodycorein_right_5\", 1);\n  //============================================================================================\n  cout<<\"Init Done\"<<endl;\n}\n\n\n\n", "meta": {"hexsha": "f4611dcbb999659b5e443692d014aedd4cdee425", "size": 13538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DCM/upperbodycore/src/sepanta_ik.cpp", "max_stars_repo_name": "cxdcxd/sepanta3", "max_stars_repo_head_hexsha": "a65a3415f046631ac4d6b91f9342966b0c030226", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DCM/upperbodycore/src/sepanta_ik.cpp", "max_issues_repo_name": "cxdcxd/sepanta3", "max_issues_repo_head_hexsha": "a65a3415f046631ac4d6b91f9342966b0c030226", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DCM/upperbodycore/src/sepanta_ik.cpp", "max_forks_repo_name": "cxdcxd/sepanta3", "max_forks_repo_head_hexsha": "a65a3415f046631ac4d6b91f9342966b0c030226", "max_forks_repo_licenses": ["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.3665943601, "max_line_length": 135, "alphanum_fraction": 0.5738661545, "num_tokens": 4331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326186278634367, "lm_q2_score": 0.024798158573975014, "lm_q1q2_score": 0.011240059548911054}}
{"text": "/*\n* Copyright (c) 2015 André Tupinambá (andrelrt@gmail.com)\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\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 <map>\n#include <iostream>\n\n#include <boost/timer/timer.hpp>\n#include <boost/container/flat_map.hpp>\n\n#include \"soa_map.h\"\n\ntemplate< class MapType >\nvoid forwardFill( MapType& ret_map, size_t size )\n{\n    for( size_t i = 0; i < size; ++i )\n    {\n        ret_map.insert( std::make_pair( i, i ) );\n    }\n}\n\ntemplate< class MapType >\nvoid reverseFill( MapType& ret_map, size_t size )\n{\n    for( size_t i = 0; i < size; ++i )\n    {\n        ret_map.insert( std::make_pair( size - i, i ) );\n    }\n}\n\ntemplate< class MapType >\nvoid forwardFind( MapType& ret_map, size_t size )\n{\n    auto itEnd = ret_map.end();\n    for( size_t i = 0; i < size; ++i )\n    {\n        auto it = ret_map.lower_bound( i );\n        if( itEnd == it )\n        {\n            std::cout << \"ff Oops! \" << i << std::endl;\n        }\n    }\n}\n\ntemplate< class MapType >\nvoid reverseFind( MapType& ret_map, size_t size )\n{\n    auto itEnd = ret_map.end();\n    for( size_t i = 0; i < size; ++i )\n    {\n        auto it = ret_map.lower_bound( size - i );\n        if( itEnd == it )\n        {\n            std::cout << \"rew Oops! \" << i << std::endl;\n        }\n    }\n}\n\ntemplate< class T_XY >\nvoid least_square( const std::string& name )\n{\n    T_XY xy;\n\n    srand( 1 );\n\n    size_t size = 512 * 1024 * 1024;\n    xy.reserve( size );\n    for( size_t i = 0; i < size; ++i )\n    {\n        xy.push_back( i + ( 2.f * rand() - RAND_MAX / 2.f ) / RAND_MAX,\n            i + ( 4.f * rand() - RAND_MAX / 2.f ) / RAND_MAX );\n    }\n\n    boost::timer::cpu_timer timer;\n\n    timer.start();\n    float meanx = 0;\n    float meany = 0;\n    for( size_t i = 0; i < size; ++i )\n    {\n        meanx += xy.get_x( i );\n        meany += xy.get_y( i );\n    }\n\n    meanx /= size;\n    meany /= size;\n\n    float numerator = 0;\n    float denominator = 0;\n    for( size_t i = 0; i < size; ++i )\n    {\n        float diffx = ( xy.get_x( i ) - meanx );\n        numerator += diffx * ( xy.get_y( i ) - meany );\n        denominator += diffx * diffx;\n    }\n\n    float b = numerator / denominator;\n    float a = meany - b * meanx;\n    timer.stop();\n\n    std::cout << \"Least Square linear regression \" << name << \": y = \" << a << \" + \" << b << \"x + e : \"\n        << timer.format();\n}\n\nstruct XYZ\n{\n    float x;\n    float y;\n    XYZ( float x_, float y_ ) : x( x_ ), y( y_ ) {}\n};\nvoid scale_aos()\n{\n    std::vector< XYZ > xyz_a;\n    std::vector< XYZ > xyz_b;\n    std::vector< XYZ > ret_xyz;\n\n    srand( 1 );\n\n    size_t size = 512 * 1024;\n    xyz_a.reserve( size );\n    xyz_b.reserve( size );\n    for( size_t i = 0; i < size; ++i )\n    {\n        xyz_a.emplace_back(  static_cast<float>( i ),  static_cast<float>( i ) );\n        xyz_b.emplace_back( -static_cast<float>( i ), -static_cast<float>( i ) );\n    }\n    ret_xyz.resize( size, { 0.f, 0.f } );\n\n    boost::timer::cpu_timer timer;\n\n    XYZ* pxyza = xyz_a.data();\n    XYZ* pxyzb = xyz_b.data();\n    XYZ* prxyz = ret_xyz.data();\n    {\n        XYZ* mypxyza = pxyza;\n        XYZ* mypxyzb = pxyzb;\n        XYZ* myprxyz = prxyz;\n        for( size_t i = 0; i < size; ++i )\n        {\n            myprxyz->x = mypxyza->x + mypxyzb->x;\n            myprxyz->y = mypxyza->y + mypxyzb->y;\n            ++mypxyza; ++mypxyzb; ++myprxyz;\n        }\n    }\n\n    timer.start();\n    for( size_t j = 0; j < 20000; ++j )\n    {\n        XYZ* mypxyza = pxyza;\n        XYZ* mypxyzb = pxyzb;\n        XYZ* myprxyz = prxyz;\n        for( size_t i = 0; i < size; ++i )\n        {\n            myprxyz->x = mypxyza->x + mypxyzb->x;\n            myprxyz->y = mypxyza->y + mypxyzb->y;\n            ++mypxyza; ++mypxyzb; ++myprxyz;\n        }\n    }\n    timer.stop();\n\n    std::cout << \"scale \" << size << \" points aos: \" << timer.format();\n}\n\nvoid scale_soa()\n{\n    std::vector< float > x_a;\n    std::vector< float > y_a;\n    std::vector< float > x_b;\n    std::vector< float > y_b;\n    std::vector< float > ret_x;\n    std::vector< float > ret_y;\n\n    srand( 1 );\n\n    size_t size = 512 * 1024;\n    x_a.reserve( size );\n    y_a.reserve( size );\n    x_b.reserve( size );\n    y_b.reserve( size );\n    for( size_t i = 0; i < size; ++i )\n    {\n        x_a.push_back(  static_cast<float>( i ) );\n        y_a.push_back(  static_cast<float>( i ) );\n        x_b.push_back( -static_cast<float>( i ) );\n        y_b.push_back( -static_cast<float>( i ) );\n    }\n    ret_x.resize( size, 0.f );\n    ret_y.resize( size, 0. );\n\n    boost::timer::cpu_timer timer;\n\n    float *pxa = x_a.data();\n    float *pya = y_a.data();\n    float *pxb = x_b.data();\n    float *pyb = y_b.data();\n    float *prx = ret_x.data();\n    float *pry = ret_y.data();\n    {\n        float *mypxa = pxa;\n        float *mypya = pya;\n        float *mypxb = pxb;\n        float *mypyb = pyb;\n        float *myprx = prx;\n        float *mypry = pry;\n        for( size_t i = 0; i < size; ++i )\n        {\n            *myprx = *mypxa + *mypxb;\n            *mypry = *mypya + *mypyb;\n            ++mypxa; ++mypxb; ++myprx;\n            ++mypya; ++mypyb; ++mypry;\n        }\n    }\n    timer.start();\n    for( size_t j = 0; j < 20000; ++j )\n    {\n        float *mypxa = pxa;\n        float *mypya = pya;\n        float *mypxb = pxb;\n        float *mypyb = pyb;\n        float *myprx = prx;\n        float *mypry = pry;\n        for( size_t i = 0; i < size; ++i )\n        {\n            *myprx = *mypxa + *mypxb;\n            *mypry = *mypya + *mypyb;\n            ++mypxa; ++mypxb; ++myprx;\n            ++mypya; ++mypyb; ++mypry;\n        }\n    }\n    timer.stop();\n\n    std::cout << \"scale \" << size << \" points soa: \" << timer.format();\n}\n\nnamespace ccppbrasil {\n\nclass XY_aos\n{\npublic:\n    void reserve( size_t size )\n    {\n        xy_.reserve( size );\n    }\n\n    void push_back( float x, float y )\n    {\n        xy_.push_back( std::make_pair( x, y ) );\n    }\n\n    float get_x( size_t idx )\n    {\n        return xy_[ idx ].first;\n    }\n\n    float get_y( size_t idx )\n    {\n        return xy_[ idx ].second;\n    }\n\nprivate:\n    std::vector< std::pair< float, float > > xy_;\n};\n\nclass XY_soa\n{\npublic:\n    void reserve( size_t size )\n    {\n        x_.reserve( size );\n        y_.reserve( size );\n    }\n\n    void push_back( float x, float y )\n    {\n        x_.push_back( x );\n        y_.push_back( y );\n    }\n\n    float get_x( size_t idx )\n    {\n        return x_[ idx ];\n    }\n\n    float get_y( size_t idx )\n    {\n        return y_[ idx ];\n    }\n\nprivate:\n    std::vector< float > x_;\n    std::vector< float > y_;\n};\n\n}\n\nint main( int argc, char* argv[] )\n{\n    boost::timer::cpu_timer timer;\n\n    size_t ffsize = 100000000;\n    size_t rewsize = 100000;\n\n\n    // std::map\n    for( int i = 0; i < 10; ++i )\n    {\n        std::map<size_t, size_t> std_map1;\n        timer.start();\n        forwardFill( std_map1, ffsize );\n        timer.stop();\n        std::cout << \"forward fill std::map: \" << timer.format();\n\n        timer.start();\n        forwardFind( std_map1, ffsize );\n        timer.stop();\n        std::cout << \"forward find std::map: \" << timer.format();\n    }\n\n    for( int i = 0; i < 10; ++i )\n    {\n        std::map<size_t, size_t> std_map2;\n        timer.start();\n\t\treverseFill( std_map2, rewsize );\n        timer.stop();\n        std::cout << \"reverse fill std::map: \" << timer.format();\n\n        timer.start();\n\t\treverseFind( std_map2, rewsize );\n        timer.stop();\n        std::cout << \"reserve find std::map: \" << timer.format();\n    }\n\n\n    // boost::container::flat_map\n\tfor( int i = 0; i < 10; ++i )\n\t{\n        boost::container::flat_map<size_t, size_t> flat_map1;\n        flat_map1.reserve( ffsize );\n        timer.start();\n        forwardFill( flat_map1, ffsize );\n        timer.stop();\n        std::cout << \"forward fill boost::container::flat_map: \" << timer.format();\n\n        timer.start();\n        forwardFind( flat_map1, ffsize );\n        timer.stop();\n        std::cout << \"forward find boost::container::flat_map: \" << timer.format();\n    }\n\n\tfor( int i = 0; i < 10; ++i )\n\t{\n        boost::container::flat_map<size_t, size_t> flat_map2;\n        flat_map2.reserve( rewsize );\n        timer.start();\n        reverseFill( flat_map2, rewsize );\n        timer.stop();\n        std::cout << \"reverse fill boost::container::flat_map: \" << timer.format();\n\n        timer.start();\n        reverseFind( flat_map2, rewsize );\n        timer.stop();\n        std::cout << \"reverse find boost::container::flat_map: \" << timer.format();\n    }\n\n    // ccppbrasil::soa_map\n\tfor( int i = 0; i < 10; ++i )\n\t{\n        ccppbrasil::soa_map<size_t, size_t> soa_map1;\n        soa_map1.reserve( ffsize );\n        timer.start();\n        forwardFill( soa_map1, ffsize );\n        timer.stop();\n        std::cout << \"forward fill ccppbrasil::soa_map: \" << timer.format();\n\n        timer.start();\n        forwardFind( soa_map1, ffsize );\n        timer.stop();\n        std::cout << \"forward find ccppbrasil::soa_map: \" << timer.format();\n    }\n\n\tfor( int i = 0; i < 10; ++i )\n\t{\n        ccppbrasil::soa_map<size_t, size_t> soa_map2;\n        soa_map2.reserve( rewsize );\n        timer.start();\n        reverseFill( soa_map2, rewsize );\n        timer.stop();\n        std::cout << \"reverse fill ccppbrasil::soa_map: \" << timer.format();\n\n        timer.start();\n        reverseFind( soa_map2, rewsize );\n        timer.stop();\n        std::cout << \"reverse find ccppbrasil::soa_map: \" << timer.format();\n    }\n\n\tfor( int i = 0; i < 10; ++i )\n\t\tleast_square<ccppbrasil::XY_aos>( \"aos\" );\n\tfor( int i = 0; i < 10; ++i )\n\t\tleast_square<ccppbrasil::XY_soa>( \"soa\" );\n    for( int i = 0; i < 10; ++i )\n        scale_aos();\n    for( int i = 0; i < 10; ++i )\n        scale_soa();\n    return 0;\n}\n\n", "meta": {"hexsha": "d1275ad1c240548d285646a30c516e9bb310e42f", "size": 10666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "andrelrt/soaTest", "max_stars_repo_head_hexsha": "2de4007056f1bde14d79b1a3ab72943757307584", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "andrelrt/soaTest", "max_issues_repo_head_hexsha": "2de4007056f1bde14d79b1a3ab72943757307584", "max_issues_repo_licenses": ["MIT"], "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": "andrelrt/soaTest", "max_forks_repo_head_hexsha": "2de4007056f1bde14d79b1a3ab72943757307584", "max_forks_repo_licenses": ["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.0964705882, "max_line_length": 103, "alphanum_fraction": 0.5371273205, "num_tokens": 3205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.02758528152729097, "lm_q1q2_score": 0.011236406515735622}}
{"text": "/**\r\n* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n* \r\n* Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI)\r\n* This file is part of the SCAPI project.\r\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\r\n* \r\n* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\r\n* to deal in the Software without restriction, including without limitation 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 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 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 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n* 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.\r\n* \r\n* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to\r\n* http://crypto.biu.ac.il/SCAPI.\r\n* \r\n* Libscapi uses several open source libraries. Please see these projects for any further licensing issues.\r\n* For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD\r\n*\r\n* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n* \r\n*/\r\n\r\n\r\n#pragma once\r\n#include <NTL/GF2X.h>\r\n#include <NTL/GF2E.h>\r\n#include <NTL/GF2XFactoring.h>\r\n#include <NTL/vec_GF2E.h>\r\n#include <NTL/GF2EX.h>\r\n#include <NTL/ZZ.h>\r\n\r\n#include \"SigmaProtocol.hpp\"\r\n#include \"../primitives/Prg.hpp\"\r\n#include <map>\r\n\r\n/**\r\n* Concrete implementation of SigmaProtocol input, used by the SigmaProtocolORMultiple verifier and simulator.<p>\r\n* In SigmaProtocolORMultiple, the common input contains an array of inputs to all of\r\n* its underlying objects and k - number of true statements.\r\n*/\r\nclass SigmaOrMultipleCommonInput : public SigmaCommonInput {\r\npublic:\r\n\r\n\t/**\r\n\t* Sets the input array and the number of statements that have a witness.\r\n\t* @param input contains inputs for all the underlying sigma protocol.\r\n\t* @param k number of statements that have a witness.\r\n\t*/\r\n\tSigmaOrMultipleCommonInput(const vector<shared_ptr<SigmaCommonInput>> & input, int k) {\r\n\t\tsigmaInputs = input;\r\n\t\tthis->k = k;\r\n\t};\r\n\r\n\t/**\r\n\t* Returns the input array contains inputs for all the underlying sigma protocol.\r\n\t*/\r\n\tvector<shared_ptr<SigmaCommonInput>> getInputs() { return sigmaInputs; };\r\n\r\n\t/**\r\n\t* Returns the number of statements that have a witness.\r\n\t*/\r\n\tint getK() { return k; };\r\n\r\n\tstring toString() override;\r\n\r\nprivate:\r\n\tvector<shared_ptr<SigmaCommonInput>> sigmaInputs;\r\n\tint k; //number of statements that have a witness.\r\n};\r\n\r\n/**\r\n* Concrete implementation of SigmaProtocol input, used by the SigmaProtocolORMultipleProver.<p>\r\n* This input contains inputs for the true statements(including witnesses) and input for the false atatements(without witnesses).\r\n*/\r\nclass SigmaOrMultipleProverInput  : public SigmaProverInput {\r\nprivate:\r\n\t//hold the prover private input.\r\n\tmap<int, shared_ptr<SigmaProverInput>> proverInputs;\r\n\r\n\t//Hold the common parameters of the statement where the prover does not know the witness.\r\n\tmap<int, shared_ptr<SigmaCommonInput>> simulatorInputs;\r\n\r\npublic:\r\n\t/**\r\n\t* Sets the inputs for the underlying provers and simulators.\r\n\t* @param proverInputs\r\n\t* @param simulatorInputs\r\n\t*/\r\n\tSigmaOrMultipleProverInput(const map<int, shared_ptr<SigmaProverInput>> & proverInputs, const map<int, shared_ptr<SigmaCommonInput>> & simulatorInputs) {\r\n\t\tthis->proverInputs = proverInputs;\r\n\t\tthis->simulatorInputs = simulatorInputs;\r\n\t}\r\n\r\n\t/**\r\n\t* Returns an array holds the inputs for the underlying provers.\r\n\t* @return an array holds the inputs for the underlying provers.\r\n\t*/\r\n\tmap<int, shared_ptr<SigmaProverInput>> getProversInput() { return proverInputs; };\r\n\r\n\t/**\r\n\t* Returns an array holds the inputs for the underlying simulators.\r\n\t* @return an array holds the inputs for the underlying simulators.\r\n\t*/\r\n\tmap<int, shared_ptr<SigmaCommonInput>> getSimulatorsInput() { return simulatorInputs; };\r\n\r\n\tshared_ptr<SigmaCommonInput> getCommonInput() override;\r\n};\r\n\r\n/**\r\n* Concrete implementation of SigmaProtocol message.\r\n* This message contains an array the interpolated polynomial, array of SigmaProtocolMsg and challenges.\r\n* The prover used this message to send the first message to the verifier.\r\n*/\r\nclass SigmaOrMultipleSecondMsg : public SigmaProtocolMsg {\r\n\r\nprivate:\r\n\tvector<vector<byte>> polynomial;\r\n\tvector<shared_ptr<SigmaProtocolMsg>> z;\r\n\tvector<vector<byte>> challenges;\r\n\r\npublic:\r\n\tSigmaOrMultipleSecondMsg(const vector<vector<byte>> & polynomBytes, const vector<shared_ptr<SigmaProtocolMsg>> & z, const vector<vector<byte>> & challenges) {\r\n\t\tthis->polynomial = polynomBytes;\r\n\t\tthis->z = z;\r\n\t\tthis->challenges = challenges;\r\n\t};\r\n\r\n\tvector<vector<byte>> getPolynomial() { return polynomial; };\r\n\r\n\tvector<shared_ptr<SigmaProtocolMsg>> getMessages() { return z; };\r\n\r\n\tvector<vector<byte>> getChallenges() { return challenges; };\r\n\r\n\tstring toString() override;\r\n\tvoid initFromString(const string & raw) override;\r\n};\r\n\r\n//Initializes the field GF2E with a random irreducible polynomial with degree t.\r\nvoid initField(int t, int seed);\r\n//Samples random field elements to be the challenges.\r\nvector<vector<byte>> sampleRandomFieldElements(int numElements, int t, vector<shared_ptr<NTL::GF2E>> & elements, PrgFromOpenSSLAES*  random);\r\nvector<byte> convertElementToBytes(NTL::GF2E & element);\r\nNTL::GF2E convertBytesToGF2E(const vector<byte> & elementByts);\r\nNTL::GF2E generateIndexPolynomial(int i);\r\n//Interpolates the points to get a polynomial.\r\nNTL::GF2EX interpolate(const vector<byte> & challenge, vector<shared_ptr<NTL::GF2E>> & fieldElements, const vector<int> & sampledIndexes);\r\n//Calculates the challenges for the statements with the witnesses.\r\nvector<vector<byte>> getRestChallenges(NTL::GF2EX & polynomial, const vector<int> & indexesInI);\r\n//Returns the byteArray of the polynomial coefficients.\r\nvector<vector<byte>> getPolynomialBytes(NTL::GF2EX & polynomial);\r\n\r\n/**\r\n* Concrete implementation of Sigma Simulator.<p>\r\n* This implementation simulates the case that the prover convince a verifier that at least k out of n\r\n* statements is true, where each statement can be proven by an associated Sigma protocol.<p>\r\n*\r\n* The pseudo code of this protocol can be found in Protocol 1.16 of pseudo codes document at {@link http://cryptobiu.github.io/scapi/SDK_Pseudocode.pdf}.<p>\r\n*\r\n*\r\n* @author Cryptography and Computer Security Research Group Department of Computer Science Bar-Ilan University (Moriya Farbstein)\r\n*\r\n*/\r\nclass SigmaOrMultipleSimulator : public SigmaSimulator {\r\n\r\n\t/*\r\n\tThis class computes the following calculations:\r\n\tSAMPLE random points e1,...,en-k in GF[2t].\r\n\tCOMPUTE the polynomial Q and values en-k+1,...,en like in the protocol.\r\n\tRUN the simulator on each statement/challenge pair (xi,ei) for all i=1,...,n to obtain (ai,ei,zi).\r\n\tOUTPUT (a1,e1,z1),..., (an,en,zn).\r\n\t*/\r\n\r\nprivate:\r\n\tvector<shared_ptr<SigmaSimulator>> simulators;\t// Underlying simulators.\r\n\tint t;\t\t\t\t\t\t\t\t// Soundness parameter.\r\n\tint len;\t\t\t\t\t\t\t// Number of underlying simulators.\r\n\tshared_ptr<PrgFromOpenSSLAES> random;\r\n\r\n\t/**\r\n\t* Checks if the given challenge length is equal to the soundness parameter.\r\n\t* @return true if the challenge length is t; false, otherwise.\r\n\t*/\r\n\tbool checkChallengeLength(int size);\r\n\r\npublic:\r\n\t/**\r\n\t* Constructor that gets the underlying simulators.\r\n\t* @param simulators array of SigmaSimulator that contains underlying simulators.\r\n\t* @param t soundness parameter. t MUST be equal to both t values of the underlying simulators object.\r\n\t* @param random\r\n\t*/\r\n\tSigmaOrMultipleSimulator(const vector<shared_ptr<SigmaSimulator>> & simulators, int t, const shared_ptr<PrgFromOpenSSLAES> & random = get_seeded_prg());\r\n\r\n\t/**\r\n\t* Returns the soundness parameter for this Sigma protocol.\r\n\t* @return t soundness parameter\r\n\t*/\r\n\tint getSoundnessParam() override { return t; }\r\n\r\n\t/**\r\n\t* Computes the simulator computation with the given challenge.\r\n\t* @param input MUST be an instance of SigmaORMultipleCommonInput.\r\n\t* @param challenge\r\n\t* @return the output of the computation - (a, e, z).\r\n\t* @throws CheatAttemptException if the received challenge's length is not equal to the soundness parameter.\r\n\t* @throws IllegalArgumentException if the given input is not an instance of SigmaORMultipleCommonInput.\r\n\t*/\r\n\tshared_ptr<SigmaSimulatorOutput> simulate(SigmaCommonInput* input, const vector<byte> & challenge) override;\r\n\r\n\t/**\r\n\t* Computes the simulator computation with a randomly chosen challenge.\r\n\t* @param input MUST be an instance of SigmaORMultipleCommonInput.\r\n\t* @return the output of the computation - (a, e, z).\r\n\t* @throws IllegalArgumentException if the given input is not an instance of SigmaORMultipleCommonInput.\r\n\t*/\r\n\tshared_ptr<SigmaSimulatorOutput> simulate(SigmaCommonInput* input) override;\r\n};\r\n\r\n\r\n/**\r\n* Concrete implementation of Sigma Protocol prover computation.<p>\r\n*\r\n* This protocol is used for a prover to convince a verifier that at least k out of n statements are true,\r\n* where each statement can be proven by an associated Sigma protocol.<p>\r\n*\r\n* The pseudo code of this protocol can be found in Protocol 1.16 of pseudo codes document at {@link http://cryptobiu.github.io/scapi/SDK_Pseudocode.pdf}.<p>\r\n*\r\n* @author Cryptography and Computer Security Research Group Department of Computer Science Bar-Ilan University (Moriya Farbstein)\r\n*\r\n*/\r\nclass SigmaOrMultipleProverComputation : public SigmaProverComputation {\r\n\r\n\t/*\r\n\t* Let (ai,ei,zi) denote the steps of a Sigma protocol SigmaI for proving that xi is in LRi\r\n\t* Let I denote the set of indices for which P has witnesses\r\n\tThis class computes the following calculations:\r\n\tFor every j not in I, SAMPLE a random element ej <- GF[2^t]\r\n\tFor every j not in I, RUN the simulator on statement xj and challenge ej to get transcript (aj,ej,zj)\r\n\tFor every i in I, RUN the prover P on statement xi to get first message ai\r\n\tSET a=(a1,...,an)\r\n\r\n\tINTERPOLATE the points (0,e) and {(j,ej)} for every j not in I to obtain a degree n-k polynomial Q (s.t. Q(0)=e and Q(j)=ej for every j not in I)\r\n\tFor every i in I, SET ei = Q(i)\r\n\tFor every i in I, COMPUTE the response zi to (ai, ei) in SigmaI using input (xi,wi)\r\n\tThe message is Q,e1,z1,...,en,zn (where by Q we mean its coefficients)\r\n\t*/\r\n\r\nprivate:\r\n\tmap<int, shared_ptr<SigmaProverComputation>> provers;\t// Underlying Sigma protocol's provers to the OR calculation.\r\n\tmap<int, shared_ptr<SigmaSimulator>> simulators;\t\t// Underlying Sigma protocol's simulators to the OR calculation.\r\n\tint len;\t\t\t\t\t\t\t\t\t\t\t\t// Number of underlying provers.\r\n\tint t;\t\t\t\t\t\t\t\t\t\t\t\t\t// Soundness parameter.\r\n\tint k;\t\t\t\t\t\t\t\t\t\t\t\t\t//number of witnesses.\r\n\tshared_ptr<PrgFromOpenSSLAES> random;\t\t\t\t\t\t\t\t\t\t\t// The indexes of the statements which the prover knows the witnesses.\r\n\r\n\tshared_ptr<SigmaOrMultipleProverInput> input;\t\t\t// Used in computeFirstMsg function.\r\n\r\n\tvector<vector<byte>> challenges;\t\t\t\t\t\t// hold the challenges to the underlying simulators and provers.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Some will be calculate in sampleRandomValues function and some in compueSecondMsg. \r\n\r\n\tmap<int, shared_ptr<SigmaSimulatorOutput>> simulatorsOutput;\t\t// We save this because we calculate it in computeFirstMsg and using \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// it after that, in computeSecondMsg\r\n\r\n\tvector<shared_ptr<NTL::GF2E>> elements;\t\t\t\t\t//Will hold pointers to the sampled field elements, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//we save the pointers to save the creation of the elements again in computeSecondMsg function.\r\n\r\npublic:\r\n\t/**\r\n\t* Constructor that gets the underlying provers.\r\n\t* @param provers array of SigmaProverComputation, where each object represent a statement\r\n\t* \t\t  and the prover wants to prove to the verify that the OR of all statements are true.\r\n\t* @param t soundness parameter. t MUST be equal to all t values of the underlying provers object.\r\n\t* @throws IllegalArgumentException if the given t is not equal to all t values of the underlying provers object.\r\n\t*/\r\n\tSigmaOrMultipleProverComputation(const map<int, shared_ptr<SigmaProverComputation>> & provers, const map<int, shared_ptr<SigmaSimulator>> & simulators, int t, const shared_ptr<PrgFromOpenSSLAES> & random = get_seeded_prg());\r\n\r\n\t/**\r\n\t* Returns the soundness parameter for this Sigma protocol.\r\n\t* @return t soundness parameter\r\n\t*/\r\n\tint getSoundnessParam() override { return t; }\r\n\r\n\t/**\r\n\t* Computes the first message of the protocol.<p>\r\n\t* \"For every j not in I, SAMPLE a random element ej <- GF[2^t]<p>\r\n\t*  For every j not in I, RUN the simulator on statement xj and challenge ej to get transcript (aj,ej,zj)<p>\r\n\tFor every i in I, RUN the prover P on statement xi to get first message ai<p>\r\n\tSET a=(a1,...,an)\".\r\n\t* @param input MUST be an instance of SigmaORMultipleInput.\r\n\t* @return SigmaMultipleMsg contains a1, ..., am.\r\n\t* @throws IllegalArgumentException if input is not an instance of SigmaORMultipleInput.\r\n\t* @throws IllegalArgumentException if the number of given inputs is different from the number of underlying provers.\r\n\t*/\r\n\tshared_ptr<SigmaProtocolMsg> computeFirstMsg(const shared_ptr<SigmaProverInput> & input) override;\r\n\r\n\t/**\r\n\t* Computes the second message of the protocol.<p>\r\n\t* \"INTERPOLATE the points (0,e) and {(j,ej)} for every j not in I to obtain a degree n-k polynomial Q (s.t. Q(0)=e and Q(j)=ej for every j not in I)<p>\r\n\tFor every i in I, SET ei = Q(i)<p>\r\n\tFor every i in I, COMPUTE the response zi to (ai, ei) in Sigmai using input (xi,wi)<p>\r\n\tThe message is Q,e1,z1,...,en,zn (where by Q we mean its coefficients)\".<p>\r\n\t* @param challenge\r\n\t* @return SigmaMultipleMsg contains z1, ..., zm.\r\n\t* @throws CheatAttemptException if the received challenge's length is not equal to the soundness parameter.\r\n\t*/\r\n\tshared_ptr<SigmaProtocolMsg> computeSecondMsg(const vector<byte> & challenge) override;\r\n\r\n\t/**\r\n\t* Returns the simulator that matches this sigma protocol prover.\r\n\t* @return SigmaORMultipleSimulator\r\n\t*/\r\n\tshared_ptr<SigmaSimulator> getSimulator() override;\r\n};\r\n\r\n/**\r\n* Concrete implementation of Sigma Protocol verifier computation.<p>\r\n*\r\n* This protocol is used for a prover to convince a verifier that at least k out of n statements is true,\r\n* where each statement can be proven by an associated Sigma protocol.<p>\r\n*\r\n* The pseudo code of this protocol can be found in Protocol 1.16 of pseudo codes document at {@link http://cryptobiu.github.io/scapi/SDK_Pseudocode.pdf}.<p>\r\n*\r\n*\r\n* @author Cryptography and Computer Security Research Group Department of Computer Science Bar-Ilan University (Moriya Farbstein)\r\n*\r\n*/\r\nclass SigmaOrMultipleVerifierComputation : public SigmaVerifierComputation {\r\n\r\n\t/*\r\n\tLet (ai,ei,zi) denote the steps of a Sigma protocol Sigmai for proving that xi is in LRi\r\n\tThis class computes the following calculations:\r\n\tWAIT for messages a1,...,an\r\n\tSAMPLE a single random challenge  e <- GF[2^t]\r\n\r\n\tACC IFF Q is of degree n-k AND Q(i)=ei for all i=1,...,n AND Q(0)=e, and the verifier output on (ai,ei,zi) for all i=1,...,n is ACC\r\n\r\n\t*/\r\n\r\nprivate:\r\n\tvector<shared_ptr<SigmaVerifierComputation>> verifiers;\t// Underlying Sigma protocol verifiers to the OR calculation.\r\n\tint len;\t\t\t\t\t\t\t\t\t\t// Number of underlying verifiers.\r\n\tvector<byte> challengeBytes;\t\t\t\t\t\t\t\t\t\t// The challenge.\r\n\tint t;\t\t\t\t\t\t\t\t\t\t\t// Soundness parameter.\r\n\tNTL::GF2E challengeElement;\t\t\t\t\t\t\t// Pointer to the sampled challenge element.\r\n\tint k;\t\t\t\t\t\t\t\t\t\t\t// Number of true statements.\r\n\tshared_ptr<PrgFromOpenSSLAES> random;\r\n\r\n\tbool checkPolynomialValidity(const vector<vector<byte>> & polynomial, int k, const NTL::GF2E & challengeElement, const vector<vector<byte>> & challenges);\r\n\tNTL::GF2EX createPolynomial(const vector<vector<byte>> & polynomialBytes);\r\n\r\npublic:\r\n\t/**\r\n\t* Constructor that gets the underlying verifiers.\r\n\t* @param verifiers array of SigmaVerifierComputation, where each object represent a statement\r\n\t* \t\t  and the prover wants to convince a verifier that at least k out of n statements is true.\r\n\t* @param t soundness parameter. t MUST be equal to all t values of the underlying verifiers object.\r\n\t* @param random source of randomness\r\n\t* @throws IllegalArgumentException if the given t is not equal to all t values of the underlying verifiers object.\r\n\t*/\r\n\tSigmaOrMultipleVerifierComputation(const vector<shared_ptr<SigmaVerifierComputation>> & verifiers, int t, const shared_ptr<PrgFromOpenSSLAES> & random = get_seeded_prg());\r\n\r\n\t/**\r\n\t* Returns the soundness parameter for this Sigma protocol.\r\n\t* @return t soundness parameter\r\n\t*/\r\n\tint getSoundnessParam() override { return t; }\r\n\r\n\t/**\r\n\t* Samples the challenge of the protocol.<p>\r\n\t* \t\"SAMPLE a single random challenge  e <- GF[2^t]\".\r\n\t*/\r\n\tvoid sampleChallenge() override;\r\n\r\n\t/**\r\n\t* Sets the given challenge.\r\n\t* @param challenge\r\n\t*/\r\n\tvoid setChallenge(const vector<byte> & challenge) override;\r\n\r\n\t/**\r\n\t* Returns the sampled challenge.\r\n\t* @return the challenge.\r\n\t*/\r\n\tvector<byte> getChallenge() override { return challengeBytes; }\r\n\r\n\t/**\r\n\t* Computes the verification of the protocol.<p>\r\n\t* \t\"ACC IFF Q is of degree n-k AND Q(i)=ei for all i=1,...,n AND Q(0)=e, and the verifier output on (ai,ei,zi) for all i=1,...,n is ACC\".\r\n\t* @param input MUST be an instance of SigmaORMultipleCommonInput.\r\n\t* @param a first message from prover\r\n\t* @param z second message from prover\r\n\t* @return true if the proof has been verified; false, otherwise.\r\n\t* @throws IllegalArgumentException if input is not an instance of SigmaORMultipleCommonInput.\r\n\t* @throws IllegalArgumentException if the number of given inputs is different from the number of underlying verifier.\r\n\t* @throws IllegalArgumentException if the first message of the prover is not an instance of SigmaMultipleMsg\r\n\t* @throws IllegalArgumentException if the second message of the prover is not an instance of SigmaORMultipleSecondMsg\r\n\t*/\r\n\tbool verify(SigmaCommonInput* input, SigmaProtocolMsg* a, SigmaProtocolMsg* z) override;\r\n};\r\n", "meta": {"hexsha": "29102eb0fb1dd39012e77cb5b1d7dbef7a5f7742", "size": 18563, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/interactive_mid_protocols/SigmaProtocolOrMultiple.hpp", "max_stars_repo_name": "manel1874/libscapi", "max_stars_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "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": "include/interactive_mid_protocols/SigmaProtocolOrMultiple.hpp", "max_issues_repo_name": "cryptobiu/libscapi", "max_issues_repo_head_hexsha": "49eee7aee9eb3544a7facb199d0a6e98097b058a", "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": "include/interactive_mid_protocols/SigmaProtocolOrMultiple.hpp", "max_forks_repo_name": "manel1874/libscapi", "max_forks_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "max_forks_repo_licenses": ["MIT"], "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": 45.8345679012, "max_line_length": 226, "alphanum_fraction": 0.7300005387, "num_tokens": 4438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.029760092224914082, "lm_q1q2_score": 0.01123564512208855}}
{"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 <map>\n\n#include <functional>\n#include <boost/make_shared.hpp>\n\n\n#include \"tudat/simulation/estimation_setup/createObservationViability.h\"\n\nnamespace tudat\n{\n\nnamespace observation_models\n{\n\n\n//! Function to filter list of observationViabilitySettings, so that only those relevant for single set of link ends are retained\nObservationViabilitySettingsList filterObservationViabilitySettings(\n        const ObservationViabilitySettingsList& observationViabilitySettings,\n        const LinkEnds& linkEnds )\n{\n    ObservationViabilitySettingsList filteredViabilitySettings;\n\n    // Iterate over all viability settings\n    for( unsigned int i = 0; i < observationViabilitySettings.size( ); i++ )\n    {\n        // Iterate over all link ends\n        for( LinkEnds::const_iterator linkEndIterator = linkEnds.begin( ); linkEndIterator != linkEnds.end( ); linkEndIterator++ )\n        {\n            // Check if present viabilitytt setting is relevant\n            if( linkEndIterator->second == observationViabilitySettings.at( i )->getAssociatedLinkEnd( ) ||\n                    ( ( observationViabilitySettings.at( i )->getAssociatedLinkEnd( ).second == \"\" ) &&\n                      ( observationViabilitySettings.at( i )->getAssociatedLinkEnd( ).first == linkEndIterator->second.first ) ) )\n            {\n                filteredViabilitySettings.push_back( observationViabilitySettings.at( i ) );\n                break;\n            }\n        }\n    }\n\n    return filteredViabilitySettings;\n}\n\n\n//! Function to create an object to check if a minimum elevation angle condition is met for an observation\nstd::shared_ptr< MinimumElevationAngleCalculator > createMinimumElevationAngleCalculator(\n        const simulation_setup::SystemOfBodies& bodies,\n        const LinkEnds linkEnds,\n        const ObservableType observationType,\n        const std::shared_ptr< ObservationViabilitySettings > observationViabilitySettings,\n        const std::string& stationName )\n{\n    if( observationViabilitySettings->observationViabilityType_ != minimum_elevation_angle )\n    {\n        throw std::runtime_error( \"Error when making minimum elevation angle calculator, inconsistent input\" );\n    }\n\n    // If specific link end is specified\n    std::string groundStationNameToUse;\n    if( observationViabilitySettings->getAssociatedLinkEnd( ).second != \"\" )\n    {\n        groundStationNameToUse = observationViabilitySettings->getAssociatedLinkEnd( ).second;\n        if( groundStationNameToUse != stationName )\n        {\n            throw std::runtime_error( \"Error when making minimum elevation angle calculator, inconsistent station input\" );\n        }\n    }\n    else\n    {\n        groundStationNameToUse = stationName;\n    }\n\n    if( bodies.count( observationViabilitySettings->getAssociatedLinkEnd( ).first ) == 0 )\n    {\n        throw std::runtime_error( \"Error when making minimum elevation angle calculator, body \" +\n                                  observationViabilitySettings->getAssociatedLinkEnd( ).first + \" not found.\" );\n    }\n\n    // Retrieve pointing angles calculator\n    std::shared_ptr< ground_stations::PointingAnglesCalculator > pointingAngleCalculator =\n            bodies.at( observationViabilitySettings->getAssociatedLinkEnd( ).first )->\n            getGroundStation( groundStationNameToUse )->getPointingAnglesCalculator( );\n\n    // Create check object\n    double minimumElevationAngle = observationViabilitySettings->getDoubleParameter( );\n    return std::make_shared< MinimumElevationAngleCalculator >(\n                getLinkStateAndTimeIndicesForLinkEnd(\n                    linkEnds,observationType, observationViabilitySettings->getAssociatedLinkEnd( ) ),\n                minimumElevationAngle, pointingAngleCalculator );\n}\n\n//! Function to create an object to check if a body avoidance angle condition is met for an observation\nstd::shared_ptr< BodyAvoidanceAngleCalculator > createBodyAvoidanceAngleCalculator(\n        const simulation_setup::SystemOfBodies& bodies,\n        const LinkEnds linkEnds,\n        const ObservableType observationType,\n        const std::shared_ptr< ObservationViabilitySettings > observationViabilitySettings )\n{\n    if( observationViabilitySettings->observationViabilityType_ != body_avoidance_angle )\n    {\n        throw std::runtime_error( \"Error when making body avoidance angle calculator, inconsistent input\" );\n    }\n\n    if( bodies.count( observationViabilitySettings->getStringParameter( ) ) == 0 )\n    {\n        throw std::runtime_error( \"Error when making body avoidance angle calculator, body \" +\n                                  observationViabilitySettings->getStringParameter( ) + \" not found.\" );\n    }\n\n    // Create state function of body to be avoided.\n    std::function< Eigen::Vector6d( const double ) > stateFunctionOfBodyToAvoid =\n            std::bind( &simulation_setup::Body::getStateInBaseFrameFromEphemeris< double, double >,\n                         bodies.at( observationViabilitySettings->getStringParameter( ) ), std::placeholders::_1 );\n\n    // Create check object\n    double bodyAvoidanceAngle = observationViabilitySettings->getDoubleParameter( );\n    return std::make_shared< BodyAvoidanceAngleCalculator >(\n                getLinkStateAndTimeIndicesForLinkEnd(\n                    linkEnds,observationType, observationViabilitySettings->getAssociatedLinkEnd( ) ),\n                bodyAvoidanceAngle, stateFunctionOfBodyToAvoid, observationViabilitySettings->getStringParameter( ) );\n}\n\n//! Function to create an object to check if a body occultation condition is met for an observation\nstd::shared_ptr< OccultationCalculator > createOccultationCalculator(\n        const simulation_setup::SystemOfBodies& bodies,\n        const LinkEnds linkEnds,\n        const ObservableType observationType,\n        const std::shared_ptr< ObservationViabilitySettings > observationViabilitySettings )\n{\n    if( observationViabilitySettings->observationViabilityType_ != body_occultation )\n    {\n        throw std::runtime_error( \"Error when making occultation calculator, inconsistent input\" );\n    }\n\n    if( bodies.count( observationViabilitySettings->getStringParameter( ) ) == 0 )\n    {\n        throw std::runtime_error( \"Error when making occultation calculator, body \" +\n                                  observationViabilitySettings->getStringParameter( ) + \" not found.\" );\n    }\n\n    // Create state function of occulting body.\n    std::function< Eigen::Vector6d( const double ) > stateOfOccultingBody =\n            std::bind( &simulation_setup::Body::getStateInBaseFrameFromEphemeris< double, double >,\n                         bodies.at( observationViabilitySettings->getStringParameter( ) ), std::placeholders::_1 );\n\n    // Create check object\n    if( bodies.at( observationViabilitySettings->getStringParameter( ) )->getShapeModel( ) == nullptr )\n    {\n        throw std::runtime_error( \"Error when makig occultation calculator, no shape model found for \" +\n                                  observationViabilitySettings->getStringParameter( ) );\n    }\n    double occultingBodyRadius =\n            bodies.at( observationViabilitySettings->getStringParameter( ) )->getShapeModel( )->getAverageRadius( );\n    return std::make_shared< OccultationCalculator >(\n                getLinkStateAndTimeIndicesForLinkEnd(\n                    linkEnds, observationType, observationViabilitySettings->getAssociatedLinkEnd( ) ),\n                stateOfOccultingBody, occultingBodyRadius );\n}\n\n//! Function to create an list of obervation viability conditions for a single set of link ends\nstd::vector< std::shared_ptr< ObservationViabilityCalculator > > createObservationViabilityCalculators(\n        const simulation_setup::SystemOfBodies& bodies,\n        const LinkEnds linkEnds,\n        const ObservableType observationType,\n        const std::vector< std::shared_ptr< ObservationViabilitySettings > >& observationViabilitySettings )\n{\n    std::vector< std::shared_ptr< ObservationViabilityCalculator > > linkViabilityCalculators;\n\n    std::vector< std::shared_ptr< ObservationViabilitySettings > > relevantObservationViabilitySettings =\n            filterObservationViabilitySettings( observationViabilitySettings, linkEnds );\n\n    for( unsigned int i = 0; i < relevantObservationViabilitySettings.size( ); i++ )\n    {\n\n        switch( relevantObservationViabilitySettings.at( i )->observationViabilityType_ )\n        {\n        case minimum_elevation_angle:\n        {\n            // Create list of ground stations for which elevation angle check is to be made.\n            std::vector< std::string > listOfGroundStations;\n            for( LinkEnds::const_iterator linkEndIterator = linkEnds.begin( );\n                 linkEndIterator != linkEnds.end( ); linkEndIterator++ )\n            {\n                if( linkEndIterator->second.first == relevantObservationViabilitySettings.at( i )->getAssociatedLinkEnd( ).first )\n                {\n                    if( std::find( listOfGroundStations.begin( ), listOfGroundStations.end( ), linkEndIterator->second.second ) ==\n                            listOfGroundStations.end( ) )\n                    {\n                        listOfGroundStations.push_back( linkEndIterator->second.second );\n                    }\n                }\n            }\n\n            // Create elevation angle check separately for eah ground station: check requires different pointing angles calculator\n            for( unsigned int j = 0; j < listOfGroundStations.size( ); j++ )\n            {\n                linkViabilityCalculators.push_back(\n                            createMinimumElevationAngleCalculator(\n                                bodies, linkEnds, observationType, relevantObservationViabilitySettings.at( i ),\n                                listOfGroundStations.at( j ) ) );\n            }\n            break;\n        }\n        case body_avoidance_angle:\n\n            linkViabilityCalculators.push_back(\n                        createBodyAvoidanceAngleCalculator(\n                            bodies, linkEnds, observationType, relevantObservationViabilitySettings.at( i ) ) );\n            break;\n        case body_occultation:\n\n            linkViabilityCalculators.push_back(\n                        createOccultationCalculator(\n                            bodies, linkEnds, observationType, relevantObservationViabilitySettings.at( i ) ) );\n            break;\n        default:\n            throw std::runtime_error(\n                        \"Error when making observation viability calculator, type not recognized \" +\n                        std::to_string(\n                            relevantObservationViabilitySettings.at( i )->observationViabilityType_ ) );\n        }\n\n    }\n\n    return linkViabilityCalculators;\n}\n\n//! Function to create an list of obervation viability conditions for a number of sets of link ends, for a single observable type\nstd::map< LinkEnds, std::vector< std::shared_ptr< ObservationViabilityCalculator > > >\ncreateObservationViabilityCalculators(\n        const simulation_setup::SystemOfBodies& bodies,\n        const std::vector< LinkEnds > linkEnds,\n        const ObservableType observationType,\n        const std::vector< std::shared_ptr< ObservationViabilitySettings > >& observationViabilitySettings )\n{\n    std::map< LinkEnds, std::vector< std::shared_ptr< ObservationViabilityCalculator > > > viabilityCalculators;\n\n    for( unsigned int i = 0; i < linkEnds.size( ); i++ )\n    {\n        viabilityCalculators[ linkEnds.at( i ) ] =\n                createObservationViabilityCalculators(\n                    bodies, linkEnds.at( i ), observationType, observationViabilitySettings );\n    }\n\n    return viabilityCalculators;\n}\n\n\n} // namespace observation_models\n\n} // namespace tudat\n\n", "meta": {"hexsha": "09e0d419d3404be68cbbaf78c48d0dd7d94102b5", "size": 12151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/estimation_setup/createObservationViability.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/estimation_setup/createObservationViability.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation/estimation_setup/createObservationViability.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": 46.3778625954, "max_line_length": 130, "alphanum_fraction": 0.6787095712, "num_tokens": 2510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.028007523546992777, "lm_q1q2_score": 0.011197733942381626}}
{"text": "#ifndef STAN_MCMC_HMC_NUTS_BASE_NUTS_HPP\n#define STAN_MCMC_HMC_NUTS_BASE_NUTS_HPP\n\n#include <stan/callbacks/logger.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <stan/math/prim/scal.hpp>\n#include <stan/mcmc/hmc/base_hmc.hpp>\n#include <stan/mcmc/hmc/hamiltonians/ps_point.hpp>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <string>\n#include <vector>\n\nnamespace stan {\n  namespace mcmc {\n    /**\n     * The No-U-Turn sampler (NUTS) with multinomial sampling\n     */\n    template <class Model, template<class, class> class Hamiltonian,\n              template<class> class Integrator, class BaseRNG>\n    class base_nuts : public base_hmc<Model, Hamiltonian, Integrator, BaseRNG> {\n    public:\n      base_nuts(const Model& model, BaseRNG& rng)\n        : base_hmc<Model, Hamiltonian, Integrator, BaseRNG>(model, rng),\n          depth_(0), max_depth_(5), max_deltaH_(1000),\n          n_leapfrog_(0), divergent_(false), energy_(0) {\n      }\n\n      /**\n       * specialized constructor for specified diag mass matrix\n       */\n      base_nuts(const Model& model, BaseRNG& rng,\n                Eigen::VectorXd& inv_e_metric)\n        : base_hmc<Model, Hamiltonian, Integrator, BaseRNG>(model, rng,\n                                                            inv_e_metric),\n          depth_(0), max_depth_(5), max_deltaH_(1000),\n          n_leapfrog_(0), divergent_(false), energy_(0) {\n      }\n\n      /**\n       * specialized constructor for specified dense mass matrix\n       */\n      base_nuts(const Model& model, BaseRNG& rng,\n                Eigen::MatrixXd& inv_e_metric)\n        : base_hmc<Model, Hamiltonian, Integrator, BaseRNG>(model, rng,\n                                                            inv_e_metric),\n        depth_(0), max_depth_(5), max_deltaH_(1000),\n        n_leapfrog_(0), divergent_(false), energy_(0) {\n      }\n\n      ~base_nuts() {}\n\n      void set_metric(const Eigen::MatrixXd& inv_e_metric) {\n        this->z_.set_metric(inv_e_metric);\n      }\n\n      void set_metric(const Eigen::VectorXd& inv_e_metric) {\n        this->z_.set_metric(inv_e_metric);\n      }\n\n      void set_max_depth(int d) {\n        if (d > 0)\n          max_depth_ = d;\n      }\n\n      void set_max_delta(double d) {\n        max_deltaH_ = d;\n      }\n\n      int get_max_depth() { return this->max_depth_; }\n      double get_max_delta() { return this->max_deltaH_; }\n\n      sample\n      transition(sample& init_sample, callbacks::logger& logger) {\n        // Initialize the algorithm\n        this->sample_stepsize();\n\n        this->seed(init_sample.cont_params());\n\n        this->hamiltonian_.sample_p(this->z_, this->rand_int_);\n        this->hamiltonian_.init(this->z_, logger);\n\n        ps_point z_plus(this->z_);\n        ps_point z_minus(z_plus);\n\n        ps_point z_sample(z_plus);\n        ps_point z_propose(z_plus);\n\n        Eigen::VectorXd p_sharp_plus = this->hamiltonian_.dtau_dp(this->z_);\n        Eigen::VectorXd p_sharp_dummy = p_sharp_plus;\n        Eigen::VectorXd p_sharp_minus = p_sharp_plus;\n        Eigen::VectorXd rho = this->z_.p;\n\n        double log_sum_weight = 0;  // log(exp(H0 - H0))\n        double H0 = this->hamiltonian_.H(this->z_);\n        int n_leapfrog = 0;\n        double sum_metro_prob = 0;\n\n        // Build a trajectory until the NUTS criterion is no longer satisfied\n        this->depth_ = 0;\n        this->divergent_ = false;\n\n        while (this->depth_ < this->max_depth_) {\n          // Build a new subtree in a random direction\n          Eigen::VectorXd rho_subtree = Eigen::VectorXd::Zero(rho.size());\n          bool valid_subtree = false;\n          double log_sum_weight_subtree\n            = -std::numeric_limits<double>::infinity();\n\n          if (this->rand_uniform_() > 0.5) {\n            this->z_.ps_point::operator=(z_plus);\n            valid_subtree\n              = build_tree(this->depth_, z_propose,\n                           p_sharp_dummy, p_sharp_plus, rho_subtree,\n                           H0, 1, n_leapfrog,\n                           log_sum_weight_subtree, sum_metro_prob,\n                           logger);\n            z_plus.ps_point::operator=(this->z_);\n          } else {\n            this->z_.ps_point::operator=(z_minus);\n            valid_subtree\n              = build_tree(this->depth_, z_propose,\n                           p_sharp_dummy, p_sharp_minus, rho_subtree,\n                           H0, -1, n_leapfrog,\n                           log_sum_weight_subtree, sum_metro_prob,\n                           logger);\n            z_minus.ps_point::operator=(this->z_);\n          }\n\n          if (!valid_subtree) break;\n\n          // Sample from an accepted subtree\n          ++(this->depth_);\n\n          if (log_sum_weight_subtree > log_sum_weight) {\n            z_sample = z_propose;\n          } else {\n            double accept_prob\n              = std::exp(log_sum_weight_subtree - log_sum_weight);\n            if (this->rand_uniform_() < accept_prob)\n              z_sample = z_propose;\n          }\n\n          log_sum_weight\n            = math::log_sum_exp(log_sum_weight, log_sum_weight_subtree);\n\n          // Break when NUTS criterion is no longer satisfied\n          rho += rho_subtree;\n          if (!compute_criterion(p_sharp_minus, p_sharp_plus, rho))\n            break;\n        }\n\n        this->n_leapfrog_ = n_leapfrog;\n\n        // Compute average acceptance probabilty across entire trajectory,\n        // even over subtrees that may have been rejected\n        double accept_prob\n          = sum_metro_prob / static_cast<double>(n_leapfrog);\n\n        this->z_.ps_point::operator=(z_sample);\n        this->energy_ = this->hamiltonian_.H(this->z_);\n        return sample(this->z_.q, -this->z_.V, accept_prob);\n      }\n\n      void get_sampler_param_names(std::vector<std::string>& names) {\n        names.push_back(\"stepsize__\");\n        names.push_back(\"treedepth__\");\n        names.push_back(\"n_leapfrog__\");\n        names.push_back(\"divergent__\");\n        names.push_back(\"energy__\");\n      }\n\n      void get_sampler_params(std::vector<double>& values) {\n        values.push_back(this->epsilon_);\n        values.push_back(this->depth_);\n        values.push_back(this->n_leapfrog_);\n        values.push_back(this->divergent_);\n        values.push_back(this->energy_);\n      }\n\n      virtual bool compute_criterion(Eigen::VectorXd& p_sharp_minus,\n                                     Eigen::VectorXd& p_sharp_plus,\n                                     Eigen::VectorXd& rho) {\n        return    p_sharp_plus.dot(rho) > 0\n               && p_sharp_minus.dot(rho) > 0;\n      }\n\n      /**\n       * Recursively build a new subtree to completion or until\n       * the subtree becomes invalid.  Returns validity of the\n       * resulting subtree.\n       *\n       * @param depth Depth of the desired subtree\n       * @param z_propose State proposed from subtree\n       * @param p_sharp_left p_sharp from left boundary of returned tree\n       * @param p_sharp_right p_sharp from the right boundary of returned tree\n       * @param rho Summed momentum across trajectory\n       * @param H0 Hamiltonian of initial state\n       * @param sign Direction in time to built subtree\n       * @param n_leapfrog Summed number of leapfrog evaluations\n       * @param log_sum_weight Log of summed weights across trajectory\n       * @param sum_metro_prob Summed Metropolis probabilities across trajectory\n       * @param logger Logger for messages\n      */\n      bool build_tree(int depth, ps_point& z_propose,\n                      Eigen::VectorXd& p_sharp_left,\n                      Eigen::VectorXd& p_sharp_right,\n                      Eigen::VectorXd& rho,\n                      double H0, double sign, int& n_leapfrog,\n                      double& log_sum_weight, double& sum_metro_prob,\n                      callbacks::logger& logger) {\n        // Base case\n        if (depth == 0) {\n          this->integrator_.evolve(this->z_, this->hamiltonian_,\n                                   sign * this->epsilon_,\n                                   logger);\n          ++n_leapfrog;\n\n          double h = this->hamiltonian_.H(this->z_);\n          if (boost::math::isnan(h))\n            h = std::numeric_limits<double>::infinity();\n\n          if ((h - H0) > this->max_deltaH_) this->divergent_ = true;\n\n          log_sum_weight = math::log_sum_exp(log_sum_weight, H0 - h);\n\n          if (H0 - h > 0)\n            sum_metro_prob += 1;\n          else\n            sum_metro_prob += std::exp(H0 - h);\n\n          z_propose = this->z_;\n          rho += this->z_.p;\n\n          p_sharp_left = this->hamiltonian_.dtau_dp(this->z_);\n          p_sharp_right = p_sharp_left;\n\n          return !this->divergent_;\n        }\n        // General recursion\n        Eigen::VectorXd p_sharp_dummy(this->z_.p.size());\n\n        // Build the left subtree\n        double log_sum_weight_left = -std::numeric_limits<double>::infinity();\n        Eigen::VectorXd rho_left = Eigen::VectorXd::Zero(rho.size());\n\n        bool valid_left\n          = build_tree(depth - 1, z_propose,\n                       p_sharp_left, p_sharp_dummy, rho_left,\n                       H0, sign, n_leapfrog,\n                       log_sum_weight_left, sum_metro_prob,\n                       logger);\n\n        if (!valid_left) return false;\n\n        // Build the right subtree\n        ps_point z_propose_right(this->z_);\n\n        double log_sum_weight_right = -std::numeric_limits<double>::infinity();\n        Eigen::VectorXd rho_right = Eigen::VectorXd::Zero(rho.size());\n\n        bool valid_right\n          = build_tree(depth - 1, z_propose_right,\n                       p_sharp_dummy, p_sharp_right, rho_right,\n                       H0, sign, n_leapfrog,\n                       log_sum_weight_right, sum_metro_prob,\n                       logger);\n\n        if (!valid_right) return false;\n\n        // Multinomial sample from right subtree\n        double log_sum_weight_subtree\n          = math::log_sum_exp(log_sum_weight_left, log_sum_weight_right);\n        log_sum_weight\n          = math::log_sum_exp(log_sum_weight, log_sum_weight_subtree);\n\n        if (log_sum_weight_right > log_sum_weight_subtree) {\n          z_propose = z_propose_right;\n        } else {\n          double accept_prob\n            = std::exp(log_sum_weight_right - log_sum_weight_subtree);\n          if (this->rand_uniform_() < accept_prob)\n            z_propose = z_propose_right;\n        }\n\n        Eigen::VectorXd rho_subtree = rho_left + rho_right;\n        rho += rho_subtree;\n\n        return compute_criterion(p_sharp_left, p_sharp_right, rho_subtree);\n      }\n\n      int depth_;\n      int max_depth_;\n      double max_deltaH_;\n\n      int n_leapfrog_;\n      bool divergent_;\n      double energy_;\n    };\n\n  }  // mcmc\n}  // stan\n#endif\n", "meta": {"hexsha": "04444cd851867ab4f1c761c037c3d1c77b2e3a66", "size": 10751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/mcmc/hmc/nuts/base_nuts.hpp", "max_stars_repo_name": "drezap/stan", "max_stars_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-05T01:40:40.000Z", "max_issues_repo_path": "src/stan/mcmc/hmc/nuts/base_nuts.hpp", "max_issues_repo_name": "drezap/stan", "max_issues_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stan/mcmc/hmc/nuts/base_nuts.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": "2018-08-28T12:09:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-28T12:09:08.000Z", "avg_line_length": 35.2491803279, "max_line_length": 80, "alphanum_fraction": 0.5832015626, "num_tokens": 2533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.025565211092776187, "lm_q1q2_score": 0.011193050551292908}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_PositronionizationSubshellPositronatomicReaction_def.hpp\n//! \\author Luke Kersting\n//! \\brief  The positron-ionization subshell positron-atomic reaction class definition\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_POSITRONIONIZATION_SUBSHELL_POSITRONATOMIC_REACTION_DEF_HPP\n#define MONTE_CARLO_POSITRONIONIZATION_SUBSHELL_POSITRONATOMIC_REACTION_DEF_HPP\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_PositronionizationPositronatomicReaction.hpp\"\n#include \"MonteCarlo_PositronatomicReactionType.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace MonteCarlo{\n\n// Basic Constructor\ntemplate<typename InterpPolicy, bool processed_cross_section>\nPositronionizationSubshellPositronatomicReaction<InterpPolicy,processed_cross_section>::PositronionizationSubshellPositronatomicReaction(\n    const std::shared_ptr<const std::vector<double> >& incoming_energy_grid,\n    const std::shared_ptr<const std::vector<double> >& cross_section,\n    const size_t threshold_energy_index,\n    const Data::SubshellType interaction_subshell,\n    const std::shared_ptr<const ElectroionizationSubshellElectronScatteringDistribution>&\n            electroionization_subshell_distribution )\n  : BaseType( incoming_energy_grid,\n              cross_section,\n              threshold_energy_index ),\n    d_interaction_subshell( interaction_subshell ),\n    d_electroionization_subshell_distribution( electroionization_subshell_distribution ),\n    d_reaction_type( convertSubshellEnumToPositronionizationPositronatomicReactionEnum(\n                                                        interaction_subshell ) )\n{\n  // Make sure the interaction subshell is valid\n  testPrecondition( interaction_subshell != Data::INVALID_SUBSHELL );\n  testPrecondition( interaction_subshell !=Data::UNKNOWN_SUBSHELL );\n\n  // Make sure the distribution data is valid\n  testPrecondition( electroionization_subshell_distribution.use_count() > 0 );\n\n  // Make sure the threshold energy isn't less than the binding energy\n  testPrecondition( (*incoming_energy_grid)[threshold_energy_index] >=\n                    d_electroionization_subshell_distribution->getBindingEnergy() );\n}\n\n\n// Constructor\ntemplate<typename InterpPolicy, bool processed_cross_section>\nPositronionizationSubshellPositronatomicReaction<InterpPolicy,processed_cross_section>::PositronionizationSubshellPositronatomicReaction(\n    const std::shared_ptr<const std::vector<double> >& incoming_energy_grid,\n    const std::shared_ptr<const std::vector<double> >& cross_section,\n    const size_t threshold_energy_index,\n    const std::shared_ptr<const Utility::HashBasedGridSearcher<double>>& grid_searcher,\n    const Data::SubshellType interaction_subshell,\n    const std::shared_ptr<const ElectroionizationSubshellElectronScatteringDistribution>&\n            electroionization_subshell_distribution )\n  : BaseType( incoming_energy_grid,\n              cross_section,\n              threshold_energy_index,\n              grid_searcher ),\n    d_interaction_subshell( interaction_subshell ),\n    d_electroionization_subshell_distribution(\n            electroionization_subshell_distribution ),\n    d_reaction_type( convertSubshellEnumToPositronionizationPositronatomicReactionEnum(\n            interaction_subshell ) )\n{\n  // Make sure the interaction subshell is valid\n  testPrecondition( interaction_subshell != Data::INVALID_SUBSHELL );\n  testPrecondition( interaction_subshell !=Data::UNKNOWN_SUBSHELL );\n\n  // Make sure the distribution data is valid\n  testPrecondition( electroionization_subshell_distribution.use_count() > 0 );\n\n  // Make sure the threshold energy isn't less than the binding energy\n  testPrecondition( (*incoming_energy_grid)[threshold_energy_index] >=\n                    d_electroionization_subshell_distribution->getBindingEnergy() );\n}\n\n// Return the number of electrons emitted from the rxn at the given energy\n/*! \\details A knock-on electron from this subshell will be emitted.\n */\ntemplate<typename InterpPolicy, bool processed_cross_section>\nunsigned PositronionizationSubshellPositronatomicReaction<InterpPolicy,processed_cross_section>::getNumberOfEmittedElectrons( const double energy ) const\n{\n  if( energy >= this->getThresholdEnergy() )\n    return 1u;\n  else\n    return 0u;\n}\n\n// Return the differential cross section\ntemplate<typename InterpPolicy, bool processed_cross_section>\ndouble PositronionizationSubshellPositronatomicReaction<InterpPolicy,processed_cross_section>::getDifferentialCrossSection(\n    const double incoming_energy,\n    const double outgoing_energy ) const\n{\n  // Make sure the energies are valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( outgoing_energy >= 0.0 );\n  testPrecondition( outgoing_energy <= incoming_energy );\n\n  if ( !this->isEnergyWithinEnergyGrid( incoming_energy ) )\n    return 0.0;\n\n  // Evaluate the forward cross section at the incoming energy\n  double forward_cs = this->getCrossSection( incoming_energy );\n\n  // Sample the pdf using the energy of the knock-on electron\n  double pdf = d_electroionization_subshell_distribution->evaluatePDF(\n          incoming_energy,\n          outgoing_energy );\n\n  return forward_cs*pdf;\n}\n\n// Simulate the reaction\ntemplate<typename InterpPolicy, bool processed_cross_section>\nvoid PositronionizationSubshellPositronatomicReaction<InterpPolicy,processed_cross_section>::react(\n     PositronState& positron,\n     ParticleBank& bank,\n     Data::SubshellType& shell_of_interaction ) const\n{\n  // Make sure the positron energy isn't less than the binding energy\n  testPrecondition( positron.getEnergy() >=\n                    d_electroionization_subshell_distribution->getBindingEnergy() );\n\n  d_electroionization_subshell_distribution->scatterPositron(\n                                               positron,\n                                               bank,\n                                               shell_of_interaction);\n\n  positron.incrementCollisionNumber();\n\n  shell_of_interaction = d_interaction_subshell;\n}\n\n// Return the reaction type\ntemplate<typename InterpPolicy, bool processed_cross_section>\nPositronatomicReactionType PositronionizationSubshellPositronatomicReaction<InterpPolicy,processed_cross_section>::getReactionType() const\n{\n  return d_reaction_type;\n}\n\n// Get the interaction subshell (non-standard interface)\ntemplate<typename InterpPolicy, bool processed_cross_section>\nunsigned PositronionizationSubshellPositronatomicReaction<InterpPolicy,processed_cross_section>::getSubshell() const\n{\n  return d_interaction_subshell;\n}\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_POSITRONIONIZATION_SUBSHELL_POSITRONATOMIC_REACTION_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_PositronionizationSubshellPositronatomicReaction_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "750cec19d0ec77efbf99ab55704e4bcfbb15b244", "size": 7102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/electron/src/MonteCarlo_PositronionizationSubshellPositronatomicReaction_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/electron/src/MonteCarlo_PositronionizationSubshellPositronatomicReaction_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/electron/src/MonteCarlo_PositronionizationSubshellPositronatomicReaction_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": 43.3048780488, "max_line_length": 153, "alphanum_fraction": 0.7426077161, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.031143829972745927, "lm_q1q2_score": 0.0111919758351674}}
{"text": "/*\n * graph_solver.cpp\n *\n *  Created on: Aug 30, 2019\n *      Author: Jorge Nicho\n */\n\n#include <numeric>\n\n#include <fstream>\n\n#include <memory>\n\n#include <console_bridge/console.h>\n\n#include <boost/format.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n\n#include \"descartes_planner/bdsp_graph_planner.h\"\n\nstatic const int VIRTUAL_VERTEX_INDEX = -1;\n\nnamespace descartes_planner\n{\n\ntemplate<typename FloatT>\ndescartes_planner::BDSPGraphPlanner<FloatT>::BDSPGraphPlanner(typename std::shared_ptr< SamplesContainer<FloatT> > container,\n                                                    bool report_all_failures):\n  container_(container),\n  report_all_failures_(report_all_failures)\n{\n  if(container_ == nullptr)\n  {\n    // if no container is provided then use default implementation\n    container_ = std::make_shared< DefaultSamplesContainer<FloatT> >();\n  }\n}\n\ntemplate<typename FloatT>\ndescartes_planner::BDSPGraphPlanner<FloatT>::~BDSPGraphPlanner()\n{\n\n}\n\ntemplate<typename FloatT>\ntypename EdgeEvaluator<FloatT>::ConstPtr descartes_planner::BDSPGraphPlanner<FloatT>::getEdgeEvaluator(std::uint32_t idx)\n{\n  if(edge_evaluators_.size() == 1)\n  {\n    return edge_evaluators_.front();\n  }\n  else\n  {\n    return edge_evaluators_.at(idx);\n  }\n}\n\ntemplate<typename FloatT>\nvoid descartes_planner::BDSPGraphPlanner<FloatT>::setup(std::vector< typename PointSampler<FloatT>::Ptr >& points,\n                                                   std::vector<typename EdgeEvaluator<FloatT>::ConstPtr>& edge_evaluators)\n{\n\n  failed_points_.clear();\n  failed_edges_.clear();\n\n  // setting up point sampler container\n  points_.clear();\n  std::copy(points.begin(),points.end(),std::back_inserter(points_));\n  container_->clear();\n  container_->allocate(points_.size());\n\n  // setting up edge evaluators\n  edge_evaluators_.clear();\n  if(edge_evaluators.size() == 1)\n  {\n    edge_evaluators_ = edge_evaluators;\n  }\n  else if(edge_evaluators.size() == points_.size() - 1)\n  {\n    std::copy(edge_evaluators.begin(),edge_evaluators.end(),std::back_inserter(edge_evaluators_));\n  }\n  else if(edge_evaluators.empty())\n  {\n    throw std::runtime_error(\"Edge evaluators vector is empty\");\n  }\n  else if(edge_evaluators.size() > 1 && edge_evaluators.size() != points.size() - 1)\n  {\n    throw std::runtime_error(boost::str(\n        boost::format(\"Edge evaluators vector's size (%lu) must be one less than that of the points vector (%lu)\") %\n        edge_evaluators.size() % points.size() ) );\n  }\n}\n\ntemplate<typename FloatT>\nbool descartes_planner::BDSPGraphPlanner<FloatT>::build(std::vector< typename PointSampler<FloatT>::Ptr >& points,\n           typename EdgeEvaluator<FloatT>::ConstPtr edge_evaluator)\n{\n  // setting up edge evaluators\n  std::vector<typename EdgeEvaluator<FloatT>::ConstPtr> edge_evaluators = {edge_evaluator};\n  return build(points, edge_evaluators);\n}\n\ntemplate<typename FloatT>\nstd::vector< EdgeProperties<FloatT> > descartes_planner::BDSPGraphPlanner<FloatT>::filterDisconnectedEdges(\n    const std::vector< EdgeProperties<FloatT> >& edges,const std::map<std::size_t, VertexProperties>& connected_src_vertices,\n    std::uint32_t current_vertex_count) const\n{\n  auto new_edges = edges;\n  auto start_loc = new_edges.begin();\n  auto end_loc = new_edges.end();\n  auto new_end_loc = std::remove_if(new_edges.begin(), new_edges.end(), [&](const EdgeProperties<FloatT>& edge){\n    int src_idx = edge.src_vtx.sample_index + current_vertex_count;\n    return connected_src_vertices.count(src_idx) == 0;\n  });\n\n  new_edges.erase(new_end_loc, end_loc);\n  return new_edges;\n}\n\ntemplate<typename FloatT>\nbool descartes_planner::BDSPGraphPlanner<FloatT>::build(std::vector<typename PointSampler<FloatT>::Ptr>& points,\n                                                   std::vector<typename EdgeEvaluator<FloatT>::ConstPtr>& edge_evaluators)\n{\n  setup(points, edge_evaluators);\n\n  //// adding virtual vertex\n  graph_.clear();\n\n  // generating samples now\n  std::size_t max_num_samples = 0;\n  for(std::size_t  i = 0; i < points_.size(); i++)\n  {\n    typename PointSampleGroup<FloatT>::Ptr samples = points_[i]->generate();\n    if(!samples || samples->values.empty())\n    {\n      CONSOLE_BRIDGE_logError(\"Failed to generate samples for point %lu\",i);\n      failed_points_.push_back(i);\n      if(report_all_failures_)\n      {\n        continue;\n      }\n      return false;\n    }\n    container_->at(i) = samples;\n    max_num_samples = max_num_samples < samples->num_samples ? samples->num_samples : max_num_samples;\n  }\n\n  // no need to proceed if sample generation failed\n  if(!failed_points_.empty())\n  {\n    CONSOLE_BRIDGE_logError(\"Failed to generate one or more point samples, use getFailedPoints to get the failed points\");\n    return false;\n  }\n\n  // build the graph now\n  typename PointSampleGroup<FloatT>::Ptr samples1 = nullptr;\n  typename PointSampleGroup<FloatT>::Ptr samples2 = nullptr;\n\n  std::uint32_t vertex_count = 1;\n  bool add_virtual_vertex = true;\n  std::map<std::size_t, VertexProperties> src_vertices_added;\n  std::map<std::size_t, VertexProperties> dst_vertices_added;\n  std::vector<bool> dst_sample_indices_added(max_num_samples, false);\n  std::vector<std::size_t> src_vertices_disconnected;\n  src_vertices_disconnected.reserve(max_num_samples);\n\n  // use samples to populate edges in order to build the search graph\n  for(std::size_t i = 1; i < points_.size(); i++)\n  {\n\n    // geting samples for both points\n    std::size_t p1_idx = i -1;\n    std::size_t p2_idx = i;\n\n    samples1 = (*container_)[p1_idx];\n    samples2 = (*container_)[p2_idx];\n    samples1->point_id = p1_idx; // TODO: setting ids may not be necessary\n    samples2->point_id = p2_idx;\n\n    // validating vertex samples\n    using SampleMap = std::map< std::size_t, typename PointSampleGroup<FloatT>::Ptr >;\n    SampleMap sample_groups = {{p1_idx, samples1}, {p2_idx, samples2}};\n    if(!std::all_of(sample_groups.begin(), sample_groups.end(),[](typename SampleMap::value_type& kv){\n      if(kv.second == nullptr)\n      {\n        CONSOLE_BRIDGE_logError(\"Invalid samples received for point with index %lu\",kv.first);\n        return false;\n      }\n      if(kv.second->values.empty())\n      {\n        CONSOLE_BRIDGE_logError(\"No valid samples were found in point %lu\",kv.first);\n        return false;\n      }\n      return true;\n    }))\n    {\n      return false;\n    }\n\n    // updating vector of disconnected vertices in source point\n    src_vertices_disconnected.clear();\n    if(!dst_vertices_added.empty())\n    {\n      for(std::size_t ii = 0; ii < samples1->num_samples; ii++)\n      {\n        if(!dst_sample_indices_added[ii])\n        {\n          src_vertices_disconnected.push_back(ii);\n        }\n      }\n      CONSOLE_BRIDGE_logDebug(\"Found %lu disconnected samples of %lu in source point %lu\",\n                             src_vertices_disconnected.size(), samples1->num_samples, p1_idx);\n    }\n\n    // reseting array\n    std::fill(dst_sample_indices_added.begin(), dst_sample_indices_added.end(), false);\n\n    // evaluate edges\n    using EdgeProp = EdgeProperties<FloatT>;\n    auto edge_evaluator = getEdgeEvaluator(p1_idx);\n    std::vector< EdgeProperties<FloatT> > edges = edge_evaluator->evaluate(samples1, samples2, src_vertices_disconnected, {});\n\n    if(edges.empty())\n    {\n      CONSOLE_BRIDGE_logError(\"Edge evaluation between points %lu and %lu failed\", samples1->point_id,\n                              samples2->point_id);\n      failed_edges_.push_back(p1_idx);\n      if(report_all_failures_)\n      {\n        continue;\n      }\n      return false;\n    }\n\n    // no need to proceed if an edge has already failed\n    if(!failed_edges_.empty())\n    {\n      continue;\n    }\n\n    CONSOLE_BRIDGE_logDebug(\"Found %lu edges between nodes (%i, %i)\",edges.size(),samples1->point_id ,samples2->point_id );\n\n    // check that at least one is valid\n    std::size_t num_valid_edges = std::accumulate(edges.begin(), edges.end(),0,[](std::size_t c, const EdgeProperties<FloatT>& edge){\n      return c + (edge.valid ? 1 : 0);\n    });\n    if(num_valid_edges == 0)\n    {\n      CONSOLE_BRIDGE_logError(\"Not a single valid edge was found between points (%lu, %lu)\",p1_idx,p2_idx);\n      return false;\n    }\n    else\n    {\n      CONSOLE_BRIDGE_logDebug(\"Point (%lu, %lu) has %lu valid edges out of %lu = %i x %i\",p1_idx,p2_idx,num_valid_edges,edges.size(),\n                               samples1->num_samples, samples2->num_samples);\n    }\n\n    // filtering disconnected edges\n    if(!dst_vertices_added.empty())\n    {\n      edges = filterDisconnectedEdges(edges, dst_vertices_added, vertex_count);\n      if(edges.empty())\n      {\n        CONSOLE_BRIDGE_logError(\"Edge between points %lu and %lu has no continuous path\", samples1->point_id,\n                                samples2->point_id);\n        failed_edges_.push_back(p1_idx);\n        if(report_all_failures_)\n        {\n          continue;\n        }\n        return false;\n      }\n    }\n\n    src_vertices_added.clear();\n    dst_vertices_added.clear();\n    for(EdgeProp& edge: edges)\n    {\n      if(!edge.valid)\n      {\n        continue;\n      }\n\n      if(edge.weight >= std::numeric_limits<FloatT>::max())\n      {\n        CONSOLE_BRIDGE_logError(\"Found edge with very high weight value between points (%lu, %lu)\", p1_idx, p2_idx);\n        continue;\n      }\n\n      bool added;\n\n      std::uint32_t src_vtx_index = edge.src_vtx.sample_index + vertex_count;\n      std::uint32_t dst_vtx_index =  edge.dst_vtx.sample_index + vertex_count + samples1->num_samples;\n\n      if(src_vtx_index >= dst_vtx_index)\n      {\n        CONSOLE_BRIDGE_logError(\"Found equal source and destination vertices values at iteration\", i);\n        return false;\n      }\n\n      if(src_vtx_index <= 0)\n      {\n        CONSOLE_BRIDGE_logError(\"Source vertex is negative at iteration %i\", i);\n        return false;\n      }\n\n      // adding edge to virtual vertex first\n      if(add_virtual_vertex && (src_vertices_added.count(src_vtx_index) == 0))\n      {\n        typename GraphT::edge_descriptor e;\n\n\n        CONSOLE_BRIDGE_logDebug(\"Adding edge (0, %lu) to virtual vertex\",src_vtx_index);\n        VertexProperties virtual_vertex_props;\n        virtual_vertex_props.point_id = VIRTUAL_VERTEX_INDEX;\n        virtual_vertex_props.sample_index = 0;\n        EdgeProperties<FloatT> virtual_edge= { .weight = 0, .valid = edge.valid,\n                                               .src_vtx = virtual_vertex_props, .dst_vtx = edge.src_vtx};\n        boost::tie(e,added) = boost::add_edge(0, src_vtx_index, graph_);\n        if(!added)\n        {\n          CONSOLE_BRIDGE_logWarn(\"Edge (%lu, %lu) has already been added to the graphs\",0,\n                                 src_vtx_index);\n          return false;\n        }\n        graph_[e] = virtual_edge;\n\n      }\n\n      typename GraphT::edge_descriptor e;\n      boost::tie(e,added) = boost::add_edge(src_vtx_index, dst_vtx_index, graph_);\n      CONSOLE_BRIDGE_logDebug(\"Added edge (%lu, %lu)\",src_vtx_index, dst_vtx_index);\n      if(!added)\n      {\n        CONSOLE_BRIDGE_logError(\"Edge (%lu, %lu) has already been added to the graphs\",src_vtx_index,\n                                dst_vtx_index);\n        return false;\n      }\n      else\n      {\n        // setting edge properties\n        graph_[e]= edge;\n      }\n\n      src_vertices_added[src_vtx_index] = edge.src_vtx;\n      dst_vertices_added[dst_vtx_index] = edge.dst_vtx;\n      dst_sample_indices_added[edge.dst_vtx.sample_index] = true;\n    }\n\n    if(src_vertices_added.empty() || dst_vertices_added.empty())\n    {\n      CONSOLE_BRIDGE_logError(\"No continuous path could be found between points %i and %i\",p1_idx, p2_idx);\n      failed_edges_.push_back(p1_idx);\n      if(report_all_failures_)\n      {\n        continue;\n      }\n      return false;\n    }\n\n    vertex_count += samples1->num_samples;\n    add_virtual_vertex = false; // do not add edges for the virtual vertex anymore\n\n  }\n\n  if(!failed_edges_.empty())\n  {\n    CONSOLE_BRIDGE_logError(\"Failed to generate one or more point samples, use getFailedEdges to get the failed edges\");\n    return false;\n  }\n\n  end_vertices_ = dst_vertices_added;\n  return true;\n}\n\ntemplate<typename FloatT>\nvoid descartes_planner::BDSPGraphPlanner<FloatT>::getFailedEdges(std::vector<std::size_t>& failed_edges)\n{\n  failed_edges = failed_edges_;\n}\n\ntemplate<typename FloatT>\nvoid descartes_planner::BDSPGraphPlanner<FloatT>::getFailedPoints(std::vector<std::size_t>& failed_points)\n{\n  failed_points = failed_points_;\n}\n\ntemplate<typename FloatT>\nstd::shared_ptr< const SamplesContainer<FloatT> > descartes_planner::BDSPGraphPlanner<FloatT>::getContainer() const\n{\n  return container_;\n}\n\ntemplate<typename FloatT>\nvoid descartes_planner::BDSPGraphPlanner<FloatT>::writeGraphLogs(const std::vector<FloatT>& weights,\n                                                               const std::vector<typename GraphT::vertex_descriptor>& predecessors)\n{\n  typedef boost::graph_traits<GraphT> GraphTraits;\n\n  // declare file names\n  const std::string dot_file_name = \"dijkstra-no-color-map-eg.dot\";\n  const std::string txt_file_name = \"dijkstra_shortest_path_dump.txt\";\n\n  // writing dot file\n  std::ofstream dot_file(dot_file_name);\n\n  dot_file << \"digraph D {\\n\"\n    << \"  rankdir=LR\\n\"\n    << \"  size=\\\"4,3\\\"\\n\"\n    << \"  ratio=\\\"fill\\\"\\n\"\n    << \"  edge[style=\\\"bold\\\"]\\n\" << \"  node[shape=\\\"circle\\\"]\\n\";\n\n  typename GraphTraits::edge_iterator  ei, ei_end;\n  for (boost::tie(ei, ei_end) = edges(graph_); ei != ei_end; ++ei) {\n    typename GraphTraits::edge_descriptor e = *ei;\n    typename GraphTraits::vertex_descriptor u = source(e, graph_), v = target(e, graph_);\n    EdgeProperties<FloatT> edge_props = graph_[e];\n    VertexProperties u_vertex = edge_props.src_vtx;\n    VertexProperties v_vertex = edge_props.dst_vtx;\n\n    if(u_vertex.point_id < 0 || v_vertex.point_id < 0)\n    {\n      continue;\n    }\n\n    dot_file << \"\\tP\" << u_vertex.point_id << \"_S\" << u_vertex.sample_index <<\"_G\" << u << \" -> \";\n    dot_file << \"P\" << v_vertex.point_id << \"_S\" << v_vertex.sample_index <<\"_G\" << v;\n\n    //dot_file << u << \" -> \" << v;\n    dot_file << \" [label=\\\"\" << int(1e3 * edge_props.weight)  << \"\\\"\";\n    if (predecessors[v] == u)\n      dot_file << \", color=\\\"black\\\"\";\n    else\n      dot_file << \", color=\\\"red\\\"\";\n    dot_file << \"];\\n\";\n  }\n  dot_file << \"}\";\n\n  // writing text file\n  std::ofstream graph_file(txt_file_name);\n  std::ostream& ref = graph_file;\n  boost::print_graph(graph_, ref);\n  graph_file.close();\n\n  // print log names\n  const auto log_file_names = {dot_file_name, txt_file_name};\n  for(const auto& f : log_file_names)\n  {\n    CONSOLE_BRIDGE_logInform(\"wrote graph log file %s\", f.c_str());\n  }\n}\n\ntemplate<typename FloatT>\nbool descartes_planner::BDSPGraphPlanner<FloatT>::solve(\n    std::vector<typename PointData<FloatT>::ConstPtr>& solution_points)\n{\n  typename GraphT::vertex_descriptor virtual_vertex = vertex(0, graph_), current_vertex;\n  std::size_t num_vert = boost::num_vertices(graph_);\n  std::vector<typename GraphT::vertex_descriptor> predecessors(num_vert);\n  std::vector<FloatT> weights(num_vert, 0.0);\n\n/*  boost::dijkstra_shortest_paths(graph_, virtual_vertex,\n    weight_map(get(&EdgeProperties<FloatT>::weight, graph_))\n    .distance_map(boost::make_iterator_property_map(weights.begin(),get(boost::vertex_index, graph_)))\n    .predecessor_map(&predecessors[0]));*/\n\n  CONSOLE_BRIDGE_logDebug(\"Descartes Searching through graph now ...\");\n  boost::dijkstra_shortest_paths_no_color_map(graph_, virtual_vertex,\n   weight_map(get(&EdgeProperties<FloatT>::weight, graph_))\n   .distance_map(boost::make_iterator_property_map(weights.begin(),get(boost::vertex_index, graph_)))\n   .predecessor_map(boost::make_iterator_property_map(predecessors.begin(),get(boost::vertex_index, graph_))));\n  CONSOLE_BRIDGE_logDebug(\"Descartes graph search completed\");\n\n  CONSOLE_BRIDGE_logDebug(\"Num vertices %i\", num_vert);\n  CONSOLE_BRIDGE_logDebug(\"Predecessor array size %lu\",predecessors.size());\n  CONSOLE_BRIDGE_logDebug(\"Weights array size %lu\",weights.size());\n  CONSOLE_BRIDGE_logDebug(\"End vertices size %lu\", end_vertices_.size());\n\n  // iterating through out edges while inspecting the predecessor\n  typedef boost::graph_traits<GraphT> GraphTraits;\n  typename GraphT::vertex_descriptor cheapest_end_vertex = -1;\n  double cost = std::numeric_limits<FloatT>::infinity();\n\n  for(const auto& kv: end_vertices_)\n  {\n    typename GraphT::vertex_descriptor candidate_vertex = kv.first;\n    CONSOLE_BRIDGE_logDebug(\"Searching end vertex %i with cost %f\", candidate_vertex,\n                           weights[candidate_vertex]);\n    if(weights[candidate_vertex] > cost)\n    {\n      CONSOLE_BRIDGE_logDebug(\"cost too high, skipping to next end vertex\");\n      continue;\n    }\n    cost = weights[candidate_vertex];\n\n    // check if it is connected\n    typename GraphT::vertex_descriptor prev_vertex = predecessors[candidate_vertex];\n    typename GraphTraits::out_edge_iterator out_i, out_end;\n    for(boost::tie(out_i, out_end)= boost::out_edges(prev_vertex, graph_); out_i != out_end; out_i++)\n    {\n      typename GraphTraits::edge_descriptor e = *out_i;\n      typename GraphT::vertex_descriptor targ = boost::target(e, graph_);\n      if(targ == candidate_vertex)\n      {\n        cheapest_end_vertex = candidate_vertex;\n        break;\n      }\n    }\n  }\n  current_vertex = cheapest_end_vertex;\n  if(static_cast<int>(current_vertex) < 0 )\n  {\n    CONSOLE_BRIDGE_logError(\"Found no continuous solution path through graph\");\n    writeGraphLogs(weights, predecessors);\n    return false;\n  }\n\n  CONSOLE_BRIDGE_logInform(\"Found valid shortest path with end vertex: %i and cost %f\", current_vertex, cost);\n\n  solution_points.resize(container_->size(), nullptr);\n  auto add_solution = [&](VertexProperties& vp) -> bool{\n\n    if(vp.point_id  == VIRTUAL_VERTEX_INDEX)\n    {\n      // found virtual index, just return\n      return true;\n    }\n\n    if(vp.point_id >= points_.size())\n    {\n      CONSOLE_BRIDGE_logError(\"Source vertex index %i exceeds point buffer of size %lu\",vp.point_id, points_.size());\n      return false;\n    }\n\n    typename PointSampleGroup<FloatT>::Ptr  sample_group = container_->at(vp.point_id);\n\n    // recompute or retrieve the sample and storing it\n    if(solution_points[vp.point_id] != nullptr) // can not have more than one solutions\n    {\n      CONSOLE_BRIDGE_logDebug(\"Sample for point %i has already been assigned\", vp.point_id);\n      return true;\n    }\n\n    typename PointData<FloatT>::ConstPtr point_data = sample_group->at(vp.sample_index);\n    if(!point_data)\n    {\n      CONSOLE_BRIDGE_logError(\"SampleGroup %i has no sample %lu\", vp.point_id, vp.sample_index);\n      return false;\n    }\n    solution_points[vp.point_id] = point_data;\n    CONSOLE_BRIDGE_logDebug(\"Added %s solution point %i of %lu points\",(point_data != nullptr ? \"valid\" : \"null\"),\n                             vp.point_id, solution_points.size());\n    return true;\n  };\n\n  int vertex_counter = 0;\n  while(current_vertex != virtual_vertex)\n  {\n    typename GraphT::vertex_descriptor prev_vertex = predecessors[current_vertex];\n    typename GraphTraits::out_edge_iterator out_i, out_end;\n    bool found_next = false;\n    for(boost::tie(out_i, out_end)= boost::out_edges(prev_vertex, graph_); out_i != out_end; out_i++)\n    {\n      typename GraphTraits::edge_descriptor e = *out_i;\n      typename GraphT::vertex_descriptor targ = boost::target(e, graph_);\n      if(targ == current_vertex)\n      {\n        found_next = true;\n        current_vertex = prev_vertex;\n\n        // grab sampler\n        EdgeProperties<FloatT> edge_props = graph_[e];\n        CONSOLE_BRIDGE_logDebug(\"Points %lu and %lu connected by edge (%lu, %lu)\",\n                                 edge_props.src_vtx.point_id, edge_props.dst_vtx.point_id,\n                                 prev_vertex, targ);\n\n        if( !(add_solution(edge_props.dst_vtx) && add_solution(edge_props.src_vtx)))\n        {\n          break;\n        }\n      }\n    }\n\n    if(!found_next )\n    {\n      break;\n    }\n\n    vertex_counter++;\n  }\n\n  CONSOLE_BRIDGE_logDebug(\"Exiting vertex traversing loop with vertex count at %i\", vertex_counter);\n\n  for(std::size_t i = 0; i < solution_points.size(); i++)\n  {\n    typename PointData<FloatT>::ConstPtr point_data = solution_points[i];\n    if(point_data == nullptr)\n    {\n      CONSOLE_BRIDGE_logError(\"Invalid solution for point %lu was found\",i);\n      return false;\n    }\n  }\n  return true;\n}\n\n// explicit specializations\ntemplate class BDSPGraphPlanner<float>;\ntemplate class BDSPGraphPlanner<double>;\n\n} /* namespace descartes_planner */\n", "meta": {"hexsha": "4995330695eba90b0695f7f1653ca5298908aa01", "size": 20685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "descartes_planner/src/bdsp_graph_planner.cpp", "max_stars_repo_name": "jrgnicho/descartes", "max_stars_repo_head_hexsha": "c8940d5f07190fdd1c23bf1ac20b870f9b8032a8", "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_planner/src/bdsp_graph_planner.cpp", "max_issues_repo_name": "jrgnicho/descartes", "max_issues_repo_head_hexsha": "c8940d5f07190fdd1c23bf1ac20b870f9b8032a8", "max_issues_repo_licenses": ["Apache-2.0"], "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_planner/src/bdsp_graph_planner.cpp", "max_forks_repo_name": "jrgnicho/descartes", "max_forks_repo_head_hexsha": "c8940d5f07190fdd1c23bf1ac20b870f9b8032a8", "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.7438825449, "max_line_length": 133, "alphanum_fraction": 0.6723712835, "num_tokens": 5065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.03308597600516689, "lm_q1q2_score": 0.01118561161752292}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_IGH_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IGH_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/proj/gn_sinu.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/moll.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace igh\n    {\n\n            template <typename Geographic, typename Cartesian>\n            struct par_igh\n            {\n                boost::shared_ptr<projection<Geographic, Cartesian> > pj[12];\n                double dy0;\n            };\n\n            static const double d4044118 = (40 + 44/60. + 11.8/3600.) * geometry::math::d2r<double>(); // 40d 44' 11.8\" [degrees]\n\n            static const double d10  =  10 * geometry::math::d2r<double>();\n            static const double d20  =  20 * geometry::math::d2r<double>();\n            static const double d30  =  30 * geometry::math::d2r<double>();\n            static const double d40  =  40 * geometry::math::d2r<double>();\n            static const double d50  =  50 * geometry::math::d2r<double>();\n            static const double d60  =  60 * geometry::math::d2r<double>();\n            static const double d80  =  80 * geometry::math::d2r<double>();\n            static const double d90  =  90 * geometry::math::d2r<double>();\n            static const double d100 = 100 * geometry::math::d2r<double>();\n            static const double d140 = 140 * geometry::math::d2r<double>();\n            static const double d160 = 160 * geometry::math::d2r<double>();\n            static const double d180 = 180 * geometry::math::d2r<double>();\n\n            static const double EPSLN = 1.e-10; // allow a little 'slack' on zone edge positions\n\n            // Converted from #define SETUP(n, proj, x_0, y_0, lon_0)\n            template <template <typename, typename, typename> class Entry, typename Parameters, typename Geographic, typename Cartesian>\n            inline void do_setup(int n, Parameters const& par, par_igh<Geographic, Cartesian>& proj_parm, double x_0, double y_0, double lon_0)\n            {\n                Entry<Geographic, Cartesian, Parameters> entry;\n                proj_parm.pj[n-1].reset(entry.create_new(par));\n                proj_parm.pj[n-1]->mutable_params().x0 = x_0;\n                proj_parm.pj[n-1]->mutable_params().y0 = y_0;\n                proj_parm.pj[n-1]->mutable_params().lam0 = lon_0;\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_igh_spheroid : public base_t_fi<base_igh_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_igh<Geographic, Cartesian> m_proj_parm;\n\n                inline base_igh_spheroid(const Parameters& par)\n                    : base_t_fi<base_igh_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                        int z;\n                        if (lp_lat >=  d4044118) {          // 1|2\n                          z = (lp_lon <= -d40 ? 1: 2);\n                        }\n                        else if (lp_lat >=  0) {            // 3|4\n                          z = (lp_lon <= -d40 ? 3: 4);\n                        }\n                        else if (lp_lat >= -d4044118) {     // 5|6|7|8\n                               if (lp_lon <= -d100) z =  5; // 5\n                          else if (lp_lon <=  -d20) z =  6; // 6\n                          else if (lp_lon <=   d80) z =  7; // 7\n                          else z = 8;                       // 8\n                        }\n                        else {                              // 9|10|11|12\n                               if (lp_lon <= -d100) z =  9; // 9\n                          else if (lp_lon <=  -d20) z = 10; // 10\n                          else if (lp_lon <=   d80) z = 11; // 11\n                          else z = 12;                      // 12\n                        }\n\n                        lp_lon -= this->m_proj_parm.pj[z-1]->params().lam0;\n                        this->m_proj_parm.pj[z-1]->fwd(lp_lon, lp_lat, xy_x, xy_y);\n                        xy_x += this->m_proj_parm.pj[z-1]->params().x0;\n                        xy_y += this->m_proj_parm.pj[z-1]->params().y0;\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                        const double y90 = this->m_proj_parm.dy0 + sqrt(2.0); // lt=90 corresponds to y=y0+sqrt(2.0)\n\n                        int z = 0;\n                        if (xy_y > y90+EPSLN || xy_y < -y90+EPSLN) // 0\n                          z = 0;\n                        else if (xy_y >=  d4044118)       // 1|2\n                          z = (xy_x <= -d40? 1: 2);\n                        else if (xy_y >=  0)              // 3|4\n                          z = (xy_x <= -d40? 3: 4);\n                        else if (xy_y >= -d4044118) {     // 5|6|7|8\n                               if (xy_x <= -d100) z =  5; // 5\n                          else if (xy_x <=  -d20) z =  6; // 6\n                          else if (xy_x <=   d80) z =  7; // 7\n                          else z = 8;                     // 8\n                        }\n                        else {                            // 9|10|11|12\n                               if (xy_x <= -d100) z =  9; // 9\n                          else if (xy_x <=  -d20) z = 10; // 10\n                          else if (xy_x <=   d80) z = 11; // 11\n                          else z = 12;                    // 12\n                        }\n\n                        if (z)\n                        {\n                          int ok = 0;\n\n                          xy_x -= this->m_proj_parm.pj[z-1]->params().x0;\n                          xy_y -= this->m_proj_parm.pj[z-1]->params().y0;\n                          this->m_proj_parm.pj[z-1]->inv(xy_x, xy_y, lp_lon, lp_lat);\n                          lp_lon += this->m_proj_parm.pj[z-1]->params().lam0;\n\n                          switch (z) {\n                            case  1: ok = (lp_lon >= -d180-EPSLN && lp_lon <=  -d40+EPSLN) ||\n                                         ((lp_lon >=  -d40-EPSLN && lp_lon <=  -d10+EPSLN) &&\n                                          (lp_lat >=   d60-EPSLN && lp_lat <=   d90+EPSLN)); break;\n                            case  2: ok = (lp_lon >=  -d40-EPSLN && lp_lon <=  d180+EPSLN) ||\n                                         ((lp_lon >= -d180-EPSLN && lp_lon <= -d160+EPSLN) &&\n                                          (lp_lat >=   d50-EPSLN && lp_lat <=   d90+EPSLN)) ||\n                                         ((lp_lon >=  -d50-EPSLN && lp_lon <=  -d40+EPSLN) &&\n                                          (lp_lat >=   d60-EPSLN && lp_lat <=   d90+EPSLN)); break;\n                            case  3: ok = (lp_lon >= -d180-EPSLN && lp_lon <=  -d40+EPSLN); break;\n                            case  4: ok = (lp_lon >=  -d40-EPSLN && lp_lon <=  d180+EPSLN); break;\n                            case  5: ok = (lp_lon >= -d180-EPSLN && lp_lon <= -d100+EPSLN); break;\n                            case  6: ok = (lp_lon >= -d100-EPSLN && lp_lon <=  -d20+EPSLN); break;\n                            case  7: ok = (lp_lon >=  -d20-EPSLN && lp_lon <=   d80+EPSLN); break;\n                            case  8: ok = (lp_lon >=   d80-EPSLN && lp_lon <=  d180+EPSLN); break;\n                            case  9: ok = (lp_lon >= -d180-EPSLN && lp_lon <= -d100+EPSLN); break;\n                            case 10: ok = (lp_lon >= -d100-EPSLN && lp_lon <=  -d20+EPSLN); break;\n                            case 11: ok = (lp_lon >=  -d20-EPSLN && lp_lon <=   d80+EPSLN); break;\n                            case 12: ok = (lp_lon >=   d80-EPSLN && lp_lon <=  d180+EPSLN); break;\n                          }\n\n                          z = (!ok? 0: z); // projectable?\n                        }\n                     // if (!z) pj_errno = -15; // invalid x or y\n                        if (!z) lp_lon = HUGE_VAL;\n                        if (!z) lp_lat = HUGE_VAL;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"igh_spheroid\";\n                }\n\n            };\n\n            // Interrupted Goode Homolosine\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            void setup_igh(Parameters& par, par_igh<Geographic, Cartesian>& proj_parm)\n            {\n            /*\n              Zones:\n\n                -180            -40                       180\n                  +--------------+-------------------------+    Zones 1,2,9,10,11 & 12:\n                  |1             |2                        |      Mollweide projection\n                  |              |                         |\n                  +--------------+-------------------------+    Zones 3,4,5,6,7 & 8:\n                  |3             |4                        |      Sinusoidal projection\n                  |              |                         |\n                0 +-------+------+-+-----------+-----------+\n                  |5      |6       |7          |8          |\n                  |       |        |           |           |\n                  +-------+--------+-----------+-----------+\n                  |9      |10      |11         |12         |\n                  |       |        |           |           |\n                  +-------+--------+-----------+-----------+\n                -180    -100      -20         80          180\n            */\n\n\n                    double lp_lam = 0, lp_phi = d4044118;\n                    double xy1_x, xy1_y;\n                    double xy3_x, xy3_y;\n\n                    // sinusoidal zones\n                    do_setup<sinu_entry>(3, par, proj_parm, -d100, 0, -d100);\n                    do_setup<sinu_entry>(4, par, proj_parm,   d30, 0,   d30);\n                    do_setup<sinu_entry>(5, par, proj_parm, -d160, 0, -d160);\n                    do_setup<sinu_entry>(6, par, proj_parm,  -d60, 0,  -d60);\n                    do_setup<sinu_entry>(7, par, proj_parm,   d20, 0,   d20);\n                    do_setup<sinu_entry>(8, par, proj_parm,  d140, 0,  d140);\n\n                    // mollweide zones\n                    do_setup<moll_entry>(1, par, proj_parm, -d100, 0, -d100);\n\n                    // y0 ?\n                     proj_parm.pj[0]->fwd(lp_lam, lp_phi, xy1_x, xy1_y); // zone 1\n                     proj_parm.pj[2]->fwd(lp_lam, lp_phi, xy3_x, xy3_y); // zone 3\n                    // y0 + xy1_y = xy3_y for lt = 40d44'11.8\"\n                    proj_parm.dy0 = xy3_y - xy1_y;\n\n                    proj_parm.pj[0]->mutable_params().y0 = proj_parm.dy0;\n\n                    // mollweide zones (cont'd)\n                    do_setup<moll_entry>( 2, par, proj_parm,   d30,  proj_parm.dy0,   d30);\n                    do_setup<moll_entry>( 9, par, proj_parm, -d160, -proj_parm.dy0, -d160);\n                    do_setup<moll_entry>(10, par, proj_parm,  -d60, -proj_parm.dy0,  -d60);\n                    do_setup<moll_entry>(11, par, proj_parm,   d20, -proj_parm.dy0,   d20);\n                    do_setup<moll_entry>(12, par, proj_parm,  d140, -proj_parm.dy0,  d140);\n\n                    par.es = 0.;\n            }\n\n        }} // namespace detail::igh\n    #endif // doxygen\n\n    /*!\n        \\brief Interrupted 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_igh.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct igh_spheroid : public detail::igh::base_igh_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline igh_spheroid(const Parameters& par) : detail::igh::base_igh_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::igh::setup_igh(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 igh_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<igh_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void igh_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"igh\", new igh_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_IGH_HPP\n\n", "meta": {"hexsha": "d4eb9a09a57168a189fa2fbe97db57e5afee4174", "size": 15902, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/igh.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/igh.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/igh.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": 50.3227848101, "max_line_length": 143, "alphanum_fraction": 0.4883662432, "num_tokens": 3927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.02442308721375499, "lm_q1q2_score": 0.011164689903687523}}
{"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 EVO_FLOAT_IMAGE_HPP_\n#define EVO_FLOAT_IMAGE_HPP_\n\n#include <vector>\n#include <limits>\n#include <boost/foreach.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <sferes/stc.hpp>\n#include <sferes/misc.hpp>\n#include <sferes/dbg/dbg.hpp>\n#include <sferes/gen/float.hpp>\n#include <iostream>\n#include <cmath>\nnamespace sferes {\n  namespace gen {\n    namespace evo_float_image {\n      enum mutation_t { polynomial = 0, gaussian, uniform };\n      enum cross_over_t { recombination = 0, sbx, no_cross_over };\n\n      template<typename Ev, unsigned long int T>\n      struct Mutation_f {\n        void operator()(Ev& ev, size_t i) {\n          assert(0);\n        }\n      };\n      template<typename Ev, unsigned long int T>\n      struct CrossOver_f {\n        void operator()(const Ev& f1, const Ev& f2, Ev &c1, Ev &c2) {\n          assert(0);\n        }\n      };\n    }\n\n    /// in range [0;1]\n    template<unsigned long int Size, typename Params, typename Exact = stc::Itself>\n    class EvoFloatImage :\n      public Float<Size, Params,\n      typename stc::FindExact<Float<Size, Params, Exact>, Exact>::ret> {\n     public:\n      typedef Params params_t;\n      typedef EvoFloatImage<Size, Params, Exact> this_t;\n\n      EvoFloatImage() {}\n\n      //@{\n      void mutate() {\n        for (size_t i = 0; i < Size; i++)\n          if (misc::rand<float>() < Params::evo_float_image::mutation_rate)\n            _mutation_op(*this, i);\n        _check_invariant();\n      }\n      void cross(const EvoFloatImage& o, EvoFloatImage& c1, EvoFloatImage& c2) {\n        if (Params::evo_float_image::cross_over_type != evo_float_image::no_cross_over &&\n            misc::rand<float>() < Params::evo_float_image::cross_rate)\n          _cross_over_op(*this, o, c1, c2);\n        else if (misc::flip_coin()) {\n          c1 = *this;\n          c2 = o;\n        } else {\n          c1 = o;\n          c2 = *this;\n        }\n        _check_invariant();\n      }\n      void random() {\n        BOOST_FOREACH(float &v, this->_data) v = misc::rand<float>();\n        _check_invariant();\n      }\n      //@}\n\n     protected:\n      evo_float_image::Mutation_f<this_t, Params::evo_float_image::mutation_type> _mutation_op;\n      evo_float_image::CrossOver_f<this_t, Params::evo_float_image::cross_over_type> _cross_over_op;\n      void _check_invariant() const {\n#ifdef DBG_ENABLED\n        BOOST_FOREACH(float p, this->_data) {\n          assert(!std::isnan(p));\n          assert(!std::isinf(p));\n          assert(p >= 0 && p <= 1);\n        }\n#endif\n      }\n    };\n\n    // partial specialization for operators\n    namespace evo_float_image {\n      // polynomial mutation. Cf Deb 2001, p 124 ; param: eta_m\n      // perturbation of the order O(1/eta_m)\n      template<typename Ev>\n      struct Mutation_f<Ev, polynomial> {\n        void operator()(Ev& ev, size_t i) {\n          SFERES_CONST float eta_m = Ev::params_t::evo_float_image::eta_m;\n          assert(eta_m != -1.0f);\n          float ri = misc::rand<float>();\n          float delta_i = ri < 0.5 ?\n                          pow(2.0 * ri, 1.0 / (eta_m + 1.0)) - 1.0 :\n                          1 - pow(2.0 * (1.0 - ri), 1.0 / (eta_m + 1.0));\n          assert(!std::isnan(delta_i));\n          assert(!std::isinf(delta_i));\n          float f = ev.data(i) + delta_i;\n          ev.data(i, misc::put_in_range(f, 0.0f, 1.0f));\n        }\n      };\n\n      // gaussian mutation\n      template<typename Ev>\n      struct Mutation_f<Ev, gaussian> {\n        void operator()(Ev& ev, size_t i) {\n          SFERES_CONST float sigma = Ev::params_t::evo_float_image::sigma;\n          float f = ev.data(i)\n                    + misc::gaussian_rand<float>(0, sigma * sigma);\n          ev.data(i, misc::put_in_range(f, 0.0f, 1.0f));\n        }\n      };\n      // uniform mutation\n      template<typename Ev>\n      struct Mutation_f<Ev, uniform> {\n        void operator()(Ev& ev, size_t i) {\n          SFERES_CONST float max = Ev::params_t::evo_float_image::max;\n          float f = ev.data(i)\n                    + misc::rand<float>(max) - max / 2.0f;\n          ev.data(i, misc::put_in_range(f, 0.0f, 1.0f));\n        }\n      };\n\n      // recombination\n      template<typename Ev>\n      struct CrossOver_f<Ev, recombination> {\n        void operator()(const Ev& f1, const Ev& f2, Ev &c1, Ev &c2) {\n          size_t k = misc::rand<unsigned long int>(f1.size());\n          for (size_t i = 0; i < k; ++i) {\n            c1.data(i, f1.data(i));\n            c2.data(i, f2.data(i));\n          }\n          for (size_t i = k; i < f1.size(); ++i) {\n            c1.data(i, f2.data(i));\n            c2.data(i, f1.data(i));\n          }\n        }\n      };\n\n      // no cross-over\n      template<typename Ev>\n      struct CrossOver_f<Ev, no_cross_over> {\n        void operator()(const Ev& f1, const Ev& f2, Ev &c1, Ev &c2) {\n        }\n      };\n\n      // SBX (cf Deb 2001, p 113) Simulated Binary Crossover\n      // suggested eta : 15\n      /// WARNING : this code is from deb's code (different from the\n      // article ...)\n      // A large value ef eta gives a higher probablitity for\n      // creating a `near-parent' solutions and a small value allows\n      // distant solutions to be selected as offspring.\n      template<typename Ev>\n      struct CrossOver_f<Ev, sbx> {\n        void operator()(const Ev& f1, const Ev& f2, Ev &child1, Ev &child2) {\n          SFERES_CONST float eta_c = Ev::params_t::evo_float_image::eta_c;\n          assert(eta_c != -1);\n          for (unsigned long int i = 0; i < f1.size(); i++) {\n            float y1 = std::min(f1.data(i), f2.data(i));\n            float y2 = std::max(f1.data(i), f2.data(i));\n            SFERES_CONST float yl = 0.0;\n            SFERES_CONST float yu = 1.0;\n            if (fabs(y1 - y2) > std::numeric_limits<float>::epsilon()) {\n              float rand = misc::rand<float>();\n              float beta = 1.0 + (2.0 * (y1 - yl) / (y2 - y1));\n              float alpha = 2.0 - pow(beta, -(eta_c + 1.0));\n              float betaq = 0;\n              if (rand <= (1.0 / alpha))\n                betaq = pow((rand * alpha), (1.0 / (eta_c + 1.0)));\n              else\n                betaq = pow ((1.0 / (2.0 - rand * alpha)) , (1.0 / (eta_c + 1.0)));\n              float c1 = 0.5 * ((y1 + y2) - betaq * (y2 - y1));\n              beta = 1.0 + (2.0 * (yu - y2) / (y2 - y1));\n              alpha = 2.0 - pow(beta, -(eta_c + 1.0));\n              if (rand <= (1.0 / alpha))\n                betaq = pow ((rand * alpha), (1.0 / (eta_c + 1.0)));\n              else\n                betaq = pow ((1.0/(2.0 - rand * alpha)), (1.0 / (eta_c + 1.0)));\n              float c2 = 0.5 * ((y1 + y2) + betaq * (y2 - y1));\n\n              c1 = misc::put_in_range(c1, yl, yu);\n              c2 = misc::put_in_range(c2, yl, yu);\n\n              assert(!std::isnan(c1));\n              assert(!std::isnan(c2));\n\n              if (misc::flip_coin()) {\n                child1.data(i, c1);\n                child2.data(i, c2);\n              } else {\n                child1.data(i, c2);\n                child2.data(i, c1);\n              }\n            }\n          }\n        }\n      };\n\n    } //evo_float_image\n  } // gen\n} // sferes\n\n\n#endif\n", "meta": {"hexsha": "416a9ac2133310940907a740ecf75e6e0806c514", "size": 8990, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sferes/exp/images/gen/evo_float_image.hpp", "max_stars_repo_name": "Evolving-AI-Lab/innovation-engine", "max_stars_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-09-20T03:03:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T06:50:20.000Z", "max_issues_repo_path": "sferes/exp/images/gen/evo_float_image.hpp", "max_issues_repo_name": "Evolving-AI-Lab/innovation-engine", "max_issues_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T07:24:50.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-17T01:19:57.000Z", "max_forks_repo_path": "sferes/exp/images/gen/evo_float_image.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.5447154472, "max_line_length": 100, "alphanum_fraction": 0.5674082314, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510109, "lm_q2_score": 0.04146227389584788, "lm_q1q2_score": 0.01115092238888564}}
{"text": "#include <pa/stages/particle_tracer.hpp>\n\n#include <algorithm>\n#include <limits>\n\n#include <boost/serialization/vector.hpp>\n#include <boost/mpi.hpp>\n#include <tbb/tbb.h>\n\n#include <pa/math/integrators.hpp>\n\n#undef min\n#undef max\n\nnamespace pa\n{\nparticle_tracer::particle_tracer(partitioner* partitioner) : partitioner_(partitioner)\n{\n\n}\n\nvoid                         particle_tracer::set_local_vector_field    (std::optional<vector_field>*                local_vector_field    )\n{\n  local_vector_field_     = local_vector_field    ;\n}\nvoid                         particle_tracer::set_neighbor_vector_fields(std::array<std::optional<vector_field>, 6>* neighbor_vector_fields)\n{\n  neighbor_vector_fields_ = neighbor_vector_fields;\n}\nvoid                         particle_tracer::set_integrator            (const variant_integrator&                   integrator            )\n{\n  integrator_    = integrator   ;\n}\nvoid                         particle_tracer::set_step_size             (const scalar                                step_size             )\n{\n  step_size_     = step_size    ;\n}\n\nstd::vector<integral_curves> particle_tracer::trace                     (std::vector<particle>                       particles             )\n{\n  std::vector<integral_curves> integral_curves;\n\n  while (!check_completion(particles))\n  {\n                      load_balance_distribute (particles                             );\n    auto round_info = compute_round_info      (particles, integral_curves            );\n                      allocate                (           integral_curves, round_info);\n                      initialize              (particles, integral_curves, round_info);\n                      trace                   (particles, integral_curves, round_info);\n                      load_balance_collect    (                            round_info);\n                      out_of_bounds_distribute(particles,                  round_info);\n  }\n\n  prune (integral_curves);\n  return integral_curves;\n}\n\nvoid                         particle_tracer::load_balance_distribute   (      std::vector<particle>& particles                                                                                   )\n{\n  // Send/receive particle counts.\n  auto neighbors                = partitioner_->neighbor_rank_info();\n  auto neighbor_particle_counts = std::array<std::size_t, 6> {};\n  neighbor_particle_counts.fill(std::numeric_limits<std::size_t>::max());\n\n  std::vector<boost::mpi::request> requests;\n  for (auto i = 0; i < neighbors.size(); ++i)\n    if (neighbors[i])\n      requests.push_back(partitioner_->communicator()->isend(neighbors[i]->rank, 0, particles.size()));\n  for (auto i = 0; i < neighbors.size(); ++i)\n    if (neighbors[i])\n      partitioner_->communicator()->recv (neighbors[i]->rank, 0, neighbor_particle_counts[i]);\n\n  for (auto& request : requests)\n    request.wait();\n\n  /// Compute workload deficit.\n\n  // Compute average of neighbors with more workload than this process.\n  auto contributions     = std::array<std::size_t, 6> {};\n  auto contributor_count = 0;\n  contributions.fill(0);\n  for (auto i = 0; i < neighbors.size(); ++i)\n  {\n    if (!neighbors[i] || neighbor_particle_counts[i] < particles.size())\n      continue;\n    contributions[i] = neighbor_particle_counts[i];\n    contributor_count++;\n  }\n  auto average = (particles.size() + std::accumulate(contributions.begin(), contributions.end(), 0ull)) / (contributor_count + 1);\n\n  // Compute average of neighbors with more workload than the average until all contributing neighbors are above the average (i.e. only this process below the average).\n  for (auto i = 0; i < neighbors.size(); ++i)\n  {\n    contributions.fill(0);\n    contributor_count = 0;\n    for (auto i = 0; i < neighbors.size(); ++i)\n    {\n      if (!neighbors[i] || neighbor_particle_counts[i] < average)\n        continue;\n      contributions[i] = neighbor_particle_counts[i];\n      contributor_count++;\n    }\n\n    const auto next_average = (particles.size() + std::accumulate(contributions.begin(), contributions.end(), 0ull)) / (contributor_count + 1);\n    if (average == next_average)\n      break;\n    average = next_average;\n  }\n\n  const auto total_deficit       = average - particles.size();\n  const auto total_contributions = std::accumulate(contributions.begin(), contributions.end(), 0ull);\n  \n  auto deficits        = std::array<std::size_t, 6> {};\n  auto maximum_surplus = std::array<std::size_t, 6> {};\n  deficits       .fill(0);\n  maximum_surplus.fill(0);\n  for (auto i = 0; i < neighbors.size(); ++i)\n    if (neighbors[i] && total_contributions != 0)\n      deficits[i] = total_deficit * (contributions[i] / total_contributions);\n\n  // Send / receive partial deficits (as partial maximum surplus).\n  requests.clear();\n  for (auto i = 0; i < neighbors.size(); ++i)\n    if (neighbors[i])\n      requests.push_back(partitioner_->communicator()->isend(neighbors[i]->rank, 10, deficits[i]));\n  for (auto i = 0; i < neighbors.size(); ++i)\n    if (neighbors[i])\n      partitioner_->communicator()->recv (neighbors[i]->rank, 10, maximum_surplus[i]);\n\n  for (auto& request : requests)\n    request.wait();\n\n  /// Compute workload surplus.\n\n  // Compute average of neighbors with less workload than this process.\n  contributions     = std::array<std::size_t, 6> {};\n  contributor_count = 0;\n  contributions.fill(0);\n  for (auto i = 0; i < neighbors.size(); ++i)\n  {\n    if (!neighbors[i] || neighbor_particle_counts[i] > particles.size())\n      continue;\n    contributions[i] = neighbor_particle_counts[i];\n    contributor_count++;\n  }\n  average = (particles.size() + std::accumulate(contributions.begin(), contributions.end(), 0ull)) / (1 + contributor_count);\n  \n  // Compute average of neighbors with less workload than the average until all contributing neighbors are below the average (i.e. only this process above the average).\n  for (auto i = 0; i < neighbors.size(); ++i)\n  {\n    contributions.fill(0);\n    contributor_count = 0;\n    for (auto i = 0; i < neighbors.size(); ++i)\n    {\n      if (!neighbors[i] || neighbor_particle_counts[i] > average)\n        continue;\n      contributions[i] = neighbor_particle_counts[i];\n      contributor_count++;\n    }\n\n    const auto next_average = (particles.size() + std::accumulate(contributions.begin(), contributions.end(), 0ull)) / (1 + contributor_count);\n    if (average == next_average)\n      break;\n    average = next_average;\n  }\n  \n  // Compute surplus particles.\n  auto surplus_particles = std::array<std::vector<particle>, 6> {};\n  for (auto i = 0; i < neighbors.size(); ++i)\n  {\n    if (!neighbors[i] || neighbor_particle_counts[i] > average)\n      continue;\n\n    const auto particle_count = std::min(maximum_surplus[i], std::size_t(average - neighbor_particle_counts[i]));\n\n    if (particle_count > particles.size())\n      continue;\n\n    surplus_particles[i].insert(surplus_particles[i].end(), particles.end() - particle_count, particles.end());\n    particles.erase(particles.end() - particle_count, particles.end());\n\n    tbb::parallel_for(std::size_t(0), surplus_particles[i].size(), std::size_t(1), [&](const std::size_t index)\n    {\n      surplus_particles[i][index].vector_field_index = i % 2 == 0 ? i + 1 : i - 1; // This process' +X neighbor treats this process as its -X neighbor and so on. \n    });\n  }\n\n  // Send/receive particles.\n  requests.clear();\n  for (auto i = 0; i < neighbors.size(); ++i)\n  {\n    if (!neighbors[i])\n      continue;\n\n    requests.push_back(partitioner_->communicator()->isend(neighbors[i]->rank, 1, surplus_particles[i]));\n  }\n  for (auto i = 0; i < neighbors.size(); ++i)\n  {\n    if (!neighbors[i]) \n      continue;\n\n    std::vector<particle> temporary;\n    partitioner_->communicator()->recv (neighbors[i]->rank, 1, temporary);\n    particles.insert(particles.end(), temporary.begin(), temporary.end());\n  }\n\n  for (auto& request : requests)\n    request.wait();\n}\nparticle_tracer::round_info  particle_tracer::compute_round_info        (const std::vector<particle>& particles, const std::vector<integral_curves>& integral_curves                              )\n{\n  round_info round_info;\n\n  round_info.maximum_remaining_iterations        = std::max_element(particles.begin(), particles.end(), [ ] (const particle& lhs, const particle& rhs) { return lhs.remaining_iterations < rhs.remaining_iterations; })->remaining_iterations;\n \n  const auto maximum_vertices_per_integral_curve = std::numeric_limits<integer>::max() / sizeof(vector4);\n  const auto particles_per_integral_curve        = maximum_vertices_per_integral_curve / round_info.maximum_remaining_iterations;\n\n  round_info.vertices_per_integral_curve         =                    particles_per_integral_curve * round_info.maximum_remaining_iterations;\n  round_info.vertices_per_integral_curve_last    = particles.size() % particles_per_integral_curve * round_info.maximum_remaining_iterations;\n  round_info.integral_curve_offset               = integral_curves.size();\n  round_info.integral_curve_count                = particles.size() == 0 ? 0 : 1 + particles.size() / particles_per_integral_curve;\n  \n  for (auto& neighbor : partitioner_->neighbor_rank_info())\n  {\n    if (neighbor)\n    {\n      round_info.out_of_bounds_particles         .emplace(neighbor->rank, std::vector<particle>());\n      round_info.neighbor_out_of_bounds_particles.emplace(neighbor->rank, std::vector<particle>());\n    }\n  }\n\n  return     round_info;\n}\nvoid                         particle_tracer::allocate                  (                                              std::vector<integral_curves>& integral_curves, const round_info& round_info)\n{\n  integral_curves.resize(round_info.integral_curve_offset + round_info.integral_curve_count);\n  tbb::parallel_for(round_info.integral_curve_offset, integral_curves.size(), std::size_t(1), [&] (const std::size_t index)\n  {\n    integral_curves[index].vertices.resize(index != integral_curves.size() - 1 ? round_info.vertices_per_integral_curve : round_info.vertices_per_integral_curve_last, invalid_vertex);\n  });\n}\nvoid                         particle_tracer::initialize                (const std::vector<particle>& particles,       std::vector<integral_curves>& integral_curves, const round_info& round_info)\n{\n  tbb::parallel_for(std::size_t(0), particles.size(), std::size_t(1), [&] (const std::size_t index)\n  {\n    const auto absolute_vertex_index = index * round_info.maximum_remaining_iterations;\n    const auto relative_vertex_index = absolute_vertex_index % round_info.vertices_per_integral_curve;\n    const auto integral_curve_index  = absolute_vertex_index / round_info.vertices_per_integral_curve + round_info.integral_curve_offset;\n    integral_curves[integral_curve_index].vertices[relative_vertex_index] = particles[index].position;\n  });\n}\nvoid                         particle_tracer::trace                     (const std::vector<particle>& particles,       std::vector<integral_curves>& integral_curves,       round_info& round_info)\n{\n  auto& local     = partitioner_->local_rank_info   ();\n  auto& neighbors = partitioner_->neighbor_rank_info();\n\n  tbb::parallel_for(std::size_t(0), particles.size(), std::size_t(1), [&] (const std::size_t particle_index)\n  {\n    auto& particle      = particles[particle_index];\n    auto& vector_field  = particle.vector_field_index == -1 ? local_vector_field_->value() : neighbor_vector_fields_->at(particle.vector_field_index).value();\n    auto  minimum       = vector_field.offset;\n    auto  maximum       = vector_field.offset + vector_field.size;\n    auto  integrator    = integrator_;\n\n    for (std::size_t iteration_index = 1; iteration_index < particle.remaining_iterations; ++iteration_index)\n    {\n      const auto  absolute_vertex_index = particle_index * round_info.maximum_remaining_iterations + iteration_index;\n      const auto  relative_vertex_index = absolute_vertex_index % round_info.vertices_per_integral_curve;\n      const auto  integral_curve_index  = absolute_vertex_index / round_info.vertices_per_integral_curve + round_info.integral_curve_offset;\n\n      const auto& last_vertex           = integral_curves[integral_curve_index].vertices[relative_vertex_index - 1];\n            auto& vertex                = integral_curves[integral_curve_index].vertices[relative_vertex_index    ];\n      \n      vertex = termination_vertex;\n\n      if (iteration_index == particle.remaining_iterations - 1)\n        break;\n\n      if (!vector_field.contains(last_vertex))\n      {\n        pa::particle neighbor_particle {last_vertex, particle.remaining_iterations - iteration_index, -1};\n\n        if (particle.vector_field_index == -1)\n        {\n          auto neighbor_rank = -1;\n          \n          if      (neighbor_particle.position[0] < minimum[0] && neighbors[0]) neighbor_rank = neighbors[0]->rank;\n          else if (neighbor_particle.position[0] > maximum[0] && neighbors[1]) neighbor_rank = neighbors[1]->rank;\n          else if (neighbor_particle.position[1] < minimum[1] && neighbors[2]) neighbor_rank = neighbors[2]->rank;\n          else if (neighbor_particle.position[1] > maximum[1] && neighbors[3]) neighbor_rank = neighbors[3]->rank;\n          else if (neighbor_particle.position[2] < minimum[2] && neighbors[4]) neighbor_rank = neighbors[4]->rank;\n          else if (neighbor_particle.position[2] > maximum[2] && neighbors[5]) neighbor_rank = neighbors[5]->rank;\n          \n          round_info::particle_map::accessor accessor;\n          if (round_info.out_of_bounds_particles.find(accessor, neighbor_rank))\n            accessor->second.push_back(neighbor_particle);\n        }\n        else\n        {\n          auto neighbor_rank = neighbors[particle.vector_field_index]->rank;\n\n          round_info::particle_map::accessor accessor;\n          if (round_info.neighbor_out_of_bounds_particles.find(accessor, neighbor_rank))\n            accessor->second.push_back(neighbor_particle);\n        }\n\n        break;\n      }\n\n      const auto vector = vector_field.interpolate(last_vertex);\n      if (vector.isZero())\n        break;\n\n      const auto system = [&] (const vector4& x, vector4& dxdt, const float t) \n      { \n        dxdt = vector4(vector[0], vector[1], vector[2], scalar(0));\n      };\n      if      (std::holds_alternative<euler_integrator>                       (integrator))\n        std::get<euler_integrator>                       (integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n      else if (std::holds_alternative<modified_midpoint_integrator>           (integrator))\n        std::get<modified_midpoint_integrator>           (integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n      else if (std::holds_alternative<runge_kutta_4_integrator>               (integrator))\n        std::get<runge_kutta_4_integrator>               (integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n      else if (std::holds_alternative<runge_kutta_cash_karp_54_integrator>    (integrator))\n        std::get<runge_kutta_cash_karp_54_integrator>    (integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n      else if (std::holds_alternative<runge_kutta_dormand_prince_5_integrator>(integrator))\n        std::get<runge_kutta_dormand_prince_5_integrator>(integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n      else if (std::holds_alternative<runge_kutta_fehlberg_78_integrator>     (integrator))\n        std::get<runge_kutta_fehlberg_78_integrator>     (integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n      else if (std::holds_alternative<adams_bashforth_2_integrator>           (integrator))\n        std::get<adams_bashforth_2_integrator>           (integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n      else if (std::holds_alternative<adams_bashforth_moulton_2_integrator>   (integrator))\n        std::get<adams_bashforth_moulton_2_integrator>   (integrator).do_step(system, last_vertex, iteration_index * step_size_, vertex, step_size_);\n    }\n  });\n}\nvoid                         particle_tracer::load_balance_collect      (                                                                                                   round_info& round_info)\n{\n  auto& neighbors = partitioner_->neighbor_rank_info();\n  auto  minimum   = local_vector_field_->value().offset;\n  auto  maximum   = local_vector_field_->value().offset + local_vector_field_->value().size;\n\n  std::vector<boost::mpi::request> requests;\n  for (auto& neighbor : round_info.neighbor_out_of_bounds_particles)\n    requests.push_back(partitioner_->communicator()->isend(neighbor.first, 2, neighbor.second));\n\n  for (auto& neighbor : round_info.neighbor_out_of_bounds_particles)\n  {\n    std::vector<particle> temporary;\n    partitioner_->communicator()->recv (neighbor.first, 2, temporary);\n\n    tbb::parallel_for(std::size_t(0), temporary.size(), std::size_t(1), [&] (const std::size_t index)\n    {\n      auto& particle      = temporary[index];\n      auto  neighbor_rank = -1;\n\n      particle.vector_field_index = -1;\n\n      if      (particle.position[0] < minimum[0] && neighbors[0]) neighbor_rank = neighbors[0]->rank;\n      else if (particle.position[0] > maximum[0] && neighbors[1]) neighbor_rank = neighbors[1]->rank;\n      else if (particle.position[1] < minimum[1] && neighbors[2]) neighbor_rank = neighbors[2]->rank;\n      else if (particle.position[1] > maximum[1] && neighbors[3]) neighbor_rank = neighbors[3]->rank;\n      else if (particle.position[2] < minimum[2] && neighbors[4]) neighbor_rank = neighbors[4]->rank;\n      else if (particle.position[2] > maximum[2] && neighbors[5]) neighbor_rank = neighbors[5]->rank;\n\n      round_info::particle_map::accessor accessor;\n      if (round_info.out_of_bounds_particles.find(accessor, neighbor_rank))\n        accessor->second.push_back(particle);\n    });\n  }\n\n  for (auto& request : requests)\n    request.wait();\n}\nvoid                         particle_tracer::out_of_bounds_distribute  (      std::vector<particle>& particles,                                                      const round_info& round_info)\n{\n  particles.clear();\n\n  std::vector<boost::mpi::request> requests;\n  for (auto& neighbor : round_info.out_of_bounds_particles)\n    requests.push_back(partitioner_->communicator()->isend(neighbor.first, 3, neighbor.second));\n\n  for (auto& neighbor : round_info.out_of_bounds_particles)\n  {\n    std::vector<particle> temporary;\n    partitioner_->communicator()->recv (neighbor.first, 3, temporary);\n    particles.insert(particles.end(), temporary.begin(), temporary.end());\n  }\n\n  for (auto& request : requests)\n    request.wait();\n}\nbool                         particle_tracer::check_completion          (const std::vector<particle>& particles                                                                                   )\n{\n  std::vector<std::size_t> particle_sizes;\n  boost::mpi::gather   (*partitioner_->communicator(), particles.size(), particle_sizes, 0);\n  auto   complete = std::all_of(particle_sizes.begin(), particle_sizes.end(), std::bind(std::equal_to<std::size_t>(), std::placeholders::_1, 0));\n  boost::mpi::broadcast(*partitioner_->communicator(), complete, 0);\n  return complete;\n}\nvoid                         particle_tracer::prune                     (                                              std::vector<integral_curves>& integral_curves                              )\n{\n  tbb::parallel_for(std::size_t(0), integral_curves.size(), std::size_t(1), [&] (const std::size_t index)\n  {\n    auto& vertices = integral_curves[index].vertices;\n    vertices.erase(std::remove(vertices.begin(), vertices.end(), invalid_vertex), vertices.end());\n  });\n}\n}", "meta": {"hexsha": "4c9e5a91a198b10c596011132653e52bfcbc4d0e", "size": 19790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pa/source/stages/particle_tracer.cpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pa/source/stages/particle_tracer.cpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pa/source/stages/particle_tracer.cpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 48.2682926829, "max_line_length": 238, "alphanum_fraction": 0.6554320364, "num_tokens": 4476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.02228618383460819, "lm_q1q2_score": 0.011143091917304095}}
{"text": "#include \"find_initial_state.h\"\n\n#include \"session_param.h\"\n#include \"frames.h\"\n#include \"vox_grid.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 <thread>\n#include <chrono>\n#include <algorithm>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <dirent.h>\n#include <armadillo>\n#include <pcl/features/moment_of_inertia_estimation.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/vtk_lib_io.h>\n#include <pcl/point_types.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/surface/gp3.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <boost/thread/thread.hpp>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/console/parse.h>\n#include <pcl/common/transforms.h>\n#include <pcl/PCLPointCloud2.h>\n\n#include \"focal_grid.h\"\n\n#define PI 3.14159265\n\nusing namespace std;\n\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\n//-----------------------------------------------------------------------\n//\n// Find the initial state of the fly using minimum bounding boxes\n//\n//-----------------------------------------------------------------------\n\nInitState::InitState() {\n\t// empty\n}\n\nvoid InitState::SetWeightXsi(double WXsi) {\n\tw_xsi = WXsi;\n}\n\nvoid InitState::SetWeightTheta(double WTheta) {\n\tw_theta = WTheta;\n}\n\nvoid InitState::SetWeightLength(double WLength) {\n\tw_length = WLength;\n}\n\nvoid InitState::SetWeightVolume(double WVolume) {\n\tw_volume = WVolume;\n}\n\nvoid InitState::SetConeAngle(double ConeAngle) {\n\tcone_angle = (ConeAngle/180.0)*PI;\n}\n\nvoid InitState::SetConeHeight(double ConeHeight) {\n\tcone_height = ConeHeight;\n}\n\nvoid InitState::ProjectSingleFrame(FocalGrid &fg, frames &frame_in, vox_grid &vox) {\n\n\t// Project a single segmented frame to a set of pointclouds:\n\n\tframe_in.single_frame_pcl.clear();\n\n\tvector<tuple<int,double,double,double,double,double,double>> pcl_out = fg.ProjectImage2Cloud(frame_in.single_seg_frame, vox);\n\n\tframe_in.single_frame_pcl = pcl_out;\n\n}\n\nvoid InitState::ProjectFrameBatch(FocalGrid &fg, frames &frame_in, vox_grid &vox) {\n\n\t// Project a segmented frame batch to pointclouds:\n\n\tframe_in.frame_batch_pcl.clear();\n\n\tint N_frames = frame_in.seg_frames[0].n_cols;\n\n\tint N_cam = frame_in.seg_frames.size();\n\n\tfor (int i=0; i<N_frames; i++) {\n\n\t\tvector<arma::Col<int>> frame_now;\n\n\t\tfor (int j=0; j<N_cam; j++) {\n\t\t\tframe_now.push_back(frame_in.seg_frames[j].col(i));\n\t\t}\n\n\t\tvector<tuple<int,double,double,double,double,double,double>> pcl_out = fg.ProjectImage2Cloud(frame_now, vox);\n\n\t\tframe_in.frame_batch_pcl.push_back(pcl_out);\n\n\t}\n\n}\n\nvoid InitState::FindInitialStateSingleFrame(frames &frame_in, model &mod) {\n\n\tframe_in.pcl_init_single_frame.clear();\n\tframe_in.M_init_single_frame.clear();\n\n\tdouble wing_length = mod.wing_length;\n\n\tvector<tuple<int,double,double,double,double,double,double>> pcl_in = frame_in.single_frame_pcl;\n\n\tarma::Mat<double> pcl_mat = InitState::ConvertVectorPCLArma(pcl_in);\n\n\tvector<tuple<struct bbox, arma::Mat<double>>> bbox_vector = InitState::FindBoundingBoxes(pcl_mat);\n\n\tvector<tuple<arma::Mat<double>,arma::Mat<double>>> pcl_vector = InitState::FindBodyandWing(bbox_vector,wing_length);\n\n\tframe_in.pcl_init_single_frame.push_back(get<0>(pcl_vector[0]));\n\tframe_in.pcl_init_single_frame.push_back(get<0>(pcl_vector[1]));\n\tframe_in.pcl_init_single_frame.push_back(get<0>(pcl_vector[2]));\n\tframe_in.M_init_single_frame.push_back(get<1>(pcl_vector[0]));\n\tframe_in.M_init_single_frame.push_back(get<1>(pcl_vector[1]));\n\tframe_in.M_init_single_frame.push_back(get<1>(pcl_vector[2]));\n\n}\n\nvoid InitState::FindInitialStateFrameBatch(frames &frame_in, model &mod) {\n\n\tframe_in.pcl_init_frame_batch.clear();\n\tframe_in.M_init_frame_batch.clear();\n\n\tdouble wing_length = mod.wing_length;\n\n\tint N_batch = frame_in.raw_frames[0].n_cols;\n\n\tframe_in.pcl_init_frame_batch.resize(N_batch);\n\tframe_in.M_init_frame_batch.resize(N_batch);\n\n\tfor (int i=0; i<N_batch; i++) {\n\n\t\tvector<tuple<int,double,double,double,double,double,double>> pcl_in = frame_in.frame_batch_pcl[i];\n\n\t\tarma::Mat<double> pcl_mat = InitState::ConvertVectorPCLArma(pcl_in);\n\n\t\tvector<tuple<struct bbox, arma::Mat<double>>> bbox_vector = InitState::FindBoundingBoxes(pcl_mat);\n\n\t\tvector<tuple<arma::Mat<double>,arma::Mat<double>>> pcl_vector = InitState::FindBodyandWing(bbox_vector,wing_length);\n\n\t\tframe_in.pcl_init_frame_batch[i].push_back(get<0>(pcl_vector[0]));\n\t\tframe_in.pcl_init_frame_batch[i].push_back(get<0>(pcl_vector[1]));\n\t\tframe_in.pcl_init_frame_batch[i].push_back(get<0>(pcl_vector[2]));\n\t\tframe_in.M_init_frame_batch[i].push_back(get<1>(pcl_vector[0]));\n\t\tframe_in.M_init_frame_batch[i].push_back(get<1>(pcl_vector[1]));\n\t\tframe_in.M_init_frame_batch[i].push_back(get<1>(pcl_vector[2]));\n\n\t}\n\n}\n\nvector<tuple<arma::Mat<double>,arma::Mat<double>>> InitState::FindBodyandWing(vector<tuple<struct bbox, arma::Mat<double>>> &bbox_vector, double wing_length) {\n\n\tint N_segments = bbox_vector.size();\n\n\tarma::Mat<double> M_body;\n\tarma::Mat<double> M_wing_L;\n\tarma::Mat<double> M_wing_R;\n\n\tarma::Mat<double> body_pcl;\n\tarma::Mat<double> wing_L_pcl;\n\tarma::Mat<double> wing_R_pcl;\n\n\tif (N_segments>0) {\n\n\t\tstruct bbox body_box = get<0>(bbox_vector[0]);\n\t\tbody_pcl = get<1>(bbox_vector[0]);\n\n\t\tM_body = InitState::FindBodyRefFrame(body_box, body_pcl);\n\n\t\tif (N_segments>1) {\n\n\t\t\tvector<arma::Mat<double>> c_vector;\n\t\t\tvector<arma::Mat<double>> wing_pcl;\n\n\t\t\tfor (int i=1; i<N_segments; i++) {\n\t\t\t\tarma::Mat<double> c_points;\n\t\t\t\tc_points = InitState::FindRootTip(M_body, get<0>(bbox_vector[i]));\n\t\t\t\tc_vector.push_back(c_points);\n\t\t\t\twing_pcl.push_back(get<1>(bbox_vector[i]));\n\t\t\t}\n\n\t\t\tvector<arma::Mat<double>> wing_pcl_LR = InitState::FindWingPCL(wing_pcl, c_vector, wing_length);\n\t\t\twing_L_pcl = wing_pcl_LR[0];\n\t\t\twing_R_pcl = wing_pcl_LR[1];\t\t\t\n\t\t}\n\t\telse {\n\t\t\twing_L_pcl.zeros(7,1);\n\t\t\twing_R_pcl.zeros(7,1);\n\t\t}\n\t}\n\telse {\n\t\tbody_pcl.zeros(7,1);\n\t\twing_L_pcl.zeros(7,1);\n\t\twing_R_pcl.zeros(7,1);\n\t}\n\n\tbody_pcl.row(0).fill(1.0);\n\twing_L_pcl.row(0).fill(2.0);\n\twing_R_pcl.row(0).fill(3.0);\n\n\tvector<arma::Mat<double>> M_vector = InitState::FindWingRefFrame(M_body, wing_L_pcl, wing_R_pcl);\n\n\t//arma::Mat<double> wing_select_L = InitState::FindWingOrientation(M_vector[0], wing_L_pcl, 0);\n\t//arma::Mat<double> wing_select_R = InitState::FindWingOrientation(M_vector[1], wing_R_pcl, 1);\n\n\tvector<tuple<arma::Mat<double>,arma::Mat<double>>> vector_out;\n\n\tvector_out.push_back(make_tuple(body_pcl,M_body));\n\tvector_out.push_back(make_tuple(wing_L_pcl,M_vector[0]));\n\tvector_out.push_back(make_tuple(wing_R_pcl,M_vector[1]));\n\n\t//vector_out.push_back(make_tuple(body_pcl,M_body));\n\t//vector_out.push_back(make_tuple(wing_L_pcl,wing_select_L));\n\t//vector_out.push_back(make_tuple(wing_R_pcl,wing_select_R));\n\n\treturn vector_out;\n}\n\nvector<arma::Mat<double>> InitState::FindWingPCL(vector<arma::Mat<double>> wing_pcls, vector<arma::Mat<double>> wing_prop, double wing_length) {\n\n\tint N_c = wing_prop.size(); // it is expected that there is 1 candidate or more\n\n\tvector<arma::Mat<double>> wing_pcl_LR;\n\n\t// Try to find a left and right wing candidate first:\n\n\tdouble score = 0.0;\n\ttuple<int, int> LR_pair;\n\tLR_pair = make_tuple(-1,-1);\n\n\tfor (int i=0; i<N_c; i++) {\n\t\tfor (int j=0; j<i; j++) {\n\t\t\tif ((wing_prop[i](3,9)>(0.8*wing_length)) && (wing_prop[i](3,9)<(1.5*wing_length))) {\n\t\t\t\tif ((wing_prop[j](3,9)>(0.8*wing_length)) && (wing_prop[j](3,9)<(1.5*wing_length))) {\n\t\t\t\t\tarma::Col<double> tip_i = {wing_prop[i](0,9),wing_prop[i](1,9),wing_prop[i](2,9)};\n\t\t\t\t\tarma::Col<double> tip_j = {wing_prop[j](0,9),wing_prop[j](1,9),wing_prop[j](2,9)};\n\t\t\t\t\tdouble d_xsi = arma::dot(tip_i,tip_j)/(arma::norm(tip_i,2.0)*arma::norm(tip_j,2.0));\n\t\t\t\t\tdouble delta_xsi = 0.0;\n\t\t\t\t\tif (d_xsi >= -1.0 && d_xsi <= 1.0) {\n\t\t\t\t\t\tdelta_xsi = acos(d_xsi);\n\t\t\t\t\t}\n\t\t\t\t\tdouble xsi_i = wing_prop[i](0,10);\n\t\t\t\t\tdouble xsi_j = wing_prop[j](0,10);\n\t\t\t\t\tdouble theta_avg = sqrt(pow((wing_prop[i](1,10)+wing_prop[j](1,10))/2.0,2));\n\t\t\t\t\tdouble wing_span_avg = (wing_prop[i](2,10)+wing_prop[j](2,10))/2.0;\n\t\t\t\t\tdouble volume_avg = (wing_prop[i](3,10)+wing_prop[j](3,10));\n\t\t\t\t\tdouble score_now = w_xsi*(delta_xsi/PI)+w_length*(wing_span_avg/wing_length)+w_volume*volume_avg-w_theta*((2.0*theta_avg)/PI);\n\t\t\t\t\tif (score_now>score) {\n\t\t\t\t\t\tscore = score_now;\n\t\t\t\t\t\tif (xsi_i > xsi_j) {\n\t\t\t\t\t\t\tLR_pair = make_tuple(i,j);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (xsi_i<xsi_j) {\n\t\t\t\t\t\t\tLR_pair = make_tuple(j,i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tLR_pair = make_tuple(i,j);\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\tcout << \"left right pair\" << endl;\n\tcout << get<0>(LR_pair) << endl;\n\tcout << get<1>(LR_pair) << endl;\n\tcout << \"\" << endl;\n\n\t// If a pair has been found, form a pointcloud of all pointclouds in the vicinity of the wingtips:\n\n\tint ind_L = get<0>(LR_pair);\n\tint ind_R = get<1>(LR_pair);\n\n\tarma::Mat<double> wing_L_pcl;\n\tarma::Mat<double> wing_R_pcl;\n\n\tif (ind_L != -1) {\n\t\twing_L_pcl = wing_pcls[ind_L];\n\t\twing_R_pcl = wing_pcls[ind_R];\n\n\t\tarma::Col<double> tip_L = {wing_prop[ind_L](0,9),wing_prop[ind_L](1,9),wing_prop[ind_L](2,9)};\n\t\tarma::Col<double> tip_R = {wing_prop[ind_R](0,9),wing_prop[ind_R](1,9),wing_prop[ind_R](2,9)};\n\n\t\tfor (int i=0; i<N_c; i++) {\n\t\t\tarma::Col<double> tip_i = {wing_prop[i](0,9),wing_prop[i](1,9),wing_prop[i](2,9)};\n\t\t\t//arma::Col<double> root_i = {wing_prop[i](0,8),wing_prop[i](1,8),wing_prop[i](2,8)};\n\t\t\tarma::Col<double> root_i = {wing_prop[i](0,11),wing_prop[i](1,11),wing_prop[i](2,11)};\n\t\t\tif (i != ind_L) {\n\t\t\t\tdouble delta_angle_tip = arma::dot(tip_i,tip_L)/(arma::norm(tip_i,2.0)*arma::norm(tip_L,2.0));\n\t\t\t\tdouble tip_angle_L = -PI;\n\t\t\t\tif (delta_angle_tip >= -1.0 && delta_angle_tip <= 1.0) {\n\t\t\t\t\ttip_angle_L = acos(delta_angle_tip);\n\t\t\t\t}\n\t\t\t\tdouble delta_angle_root = arma::dot(root_i,tip_L)/(arma::norm(root_i,2.0)*arma::norm(tip_L,2.0));\n\t\t\t\tdouble root_angle_L = -PI;\n\t\t\t\tif (delta_angle_root >= -1.0 && delta_angle_root <= 1.0) {\n\t\t\t\t\troot_angle_L = acos(delta_angle_root);\n\t\t\t\t}\n\t\t\t\tdouble center_dist = wing_prop[i](3,11);\n\t\t\t\tif (tip_angle_L >= 0.0 && tip_angle_L <= cone_angle) {\n\t\t\t\t\tif (root_angle_L >= 0.0 && root_angle_L <= cone_angle) {\n\t\t\t\t\t\tif (center_dist > ((1.0-cone_height)*wing_length)) {\n\t\t\t\t\t\t\twing_L_pcl = arma::join_rows(wing_L_pcl,wing_pcls[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\tif (i != ind_R) {\n\t\t\t\tdouble delta_angle_tip = arma::dot(tip_i,tip_R)/(arma::norm(tip_i,2.0)*arma::norm(tip_R,2.0));\n\t\t\t\tdouble tip_angle_R = -PI;\n\t\t\t\tif (delta_angle_tip >= -1.0 && delta_angle_tip <= 1.0) {\n\t\t\t\t\ttip_angle_R = acos(delta_angle_tip);\n\t\t\t\t}\n\t\t\t\tdouble delta_angle_root = arma::dot(root_i,tip_R)/(arma::norm(root_i,2.0)*arma::norm(tip_R,2.0));\n\t\t\t\tdouble root_angle_R = -PI;\n\t\t\t\tif (delta_angle_root >= -1.0 && delta_angle_root <= 1.0) {\n\t\t\t\t\troot_angle_R = acos(delta_angle_root);\n\t\t\t\t}\n\t\t\t\tdouble center_dist = wing_prop[i](3,11);\n\t\t\t\tif (tip_angle_R >= 0.0 && tip_angle_R <= cone_angle) {\n\t\t\t\t\tif (root_angle_R >= 0.0 && root_angle_R <= cone_angle) {\n\t\t\t\t\t\tif (center_dist > ((1.0-cone_height)*wing_length)) {\n\t\t\t\t\t\t\twing_R_pcl = arma::join_rows(wing_R_pcl,wing_pcls[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\telse {\n\t\twing_L_pcl.zeros(7,1);\n\t\twing_R_pcl.zeros(7,1);\n\t}\n\n\twing_pcl_LR.push_back(wing_L_pcl);\n\twing_pcl_LR.push_back(wing_R_pcl);\n\n\treturn wing_pcl_LR;\n}\n\n/*\narma::Mat<double> InitState::FindWingOrientation(arma::Mat<double> M_vector, arma::Mat<double> &wing_pcl_in, int L_or_R) {\n\n\tint N_segs = 5;\n\n\tarma::Mat<double> M_out;\n\tM_out.zeros(4,8);\n\n\t// Get x,y,z coordinates from pcl:\n\n\tdouble theta_avg = 0.0;\n\n\tif (wing_pcl_in.n_cols>10 && arma::sum(M_vector.row(3)) != 0) {\n\n\t\tarma::Mat<double> wing_pcl;\n\n\t\twing_pcl.ones(4,wing_pcl_in.n_cols);\n\n\t\twing_pcl.row(0) = wing_pcl_in.row(1);\n\t\twing_pcl.row(1) = wing_pcl_in.row(2);\n\t\twing_pcl.row(2) = wing_pcl_in.row(3);\n\n\t\t// Project pcl into wing reference frame:\n\n\t\tarma::Mat<double> M_wing;\n\t\tM_wing.eye(4,4);\n\n\t\t// Transpose of the matrix\n\n\t\tM_wing(0,0) = M_vector(0,0);\n\t\tM_wing(0,1) = M_vector(1,0);\n\t\tM_wing(0,2) = M_vector(2,0);\n\t\tM_wing(0,3) = -M_vector(0,3);\n\t\tM_wing(1,0) = M_vector(0,1);\n\t\tM_wing(1,1) = M_vector(1,1);\n\t\tM_wing(1,2) = M_vector(2,1);\n\t\tM_wing(1,3) = -M_vector(1,3);\n\t\tM_wing(2,0) = M_vector(0,2);\n\t\tM_wing(2,1) = M_vector(1,2);\n\t\tM_wing(2,2) = M_vector(2,2);\n\t\tM_wing(2,3) = -M_vector(2,3);\n\n\t\tarma::Mat<double> wing_pcl_ref = M_wing*wing_pcl;\n\n\t\t// Perform svd on wing_pcl_ref:\n\n\t\tarma::Row<double> angle_y;\n\t\tangle_y.zeros(N_segs);\n\n\t\tarma::Row<double> chord_length;\n\t\tchord_length.zeros(N_segs);\n\n\t\tarma::Row<int> N_seg_points;\n\t\tN_seg_points.zeros(N_segs);\n\n\t\tif (L_or_R==0) {\n\n\t\t\tdouble y_tip = wing_pcl_ref.row(1).max();\n\n\t\t\t// Split the wing in N segments:\n\t\t\tfor (int i=0; i<N_segs; i++) {\n\n\t\t\t\t// Select y-slice elements\n\t\t\t\tarma::uvec slice_y_ids = arma::find((wing_pcl_ref.row(1) > (i*(y_tip/((N_segs+1)*1.0)))) && (wing_pcl_ref.row(1) < ((i+1)*(y_tip/((N_segs+1)*1.0)))));\n\n\t\t\t\tif (slice_y_ids.n_rows > 2) {\n\n\t\t\t\t\tarma::Mat<double> slice_points_y = wing_pcl_ref.cols(slice_y_ids);\n\n\t\t\t\t\t// Find the maximum radius from the mid point of the section\n\n\t\t\t\t\tarma::Row<double> R1;\n\t\t\t\t\tR1.zeros(slice_y_ids.n_rows);\n\n\t\t\t\t\tfor (int j=0; j<slice_y_ids.n_rows; j++) {\n\t\t\t\t\t\tR1(j) = sqrt(pow(slice_points_y(0,j),2.0)+pow(slice_points_y(2,j),2.0));\n\t\t\t\t\t}\n\n\t\t\t\t\tint max_R1 = R1.index_max();\n\n\t\t\t\t\tarma::Col<double> R1_point = slice_points_y.col(max_R1);\n\n\t\t\t\t\t// Find the maximum radius from R1:\n\n\t\t\t\t\tarma::Row<double> R2;\n\t\t\t\t\tR2.zeros(slice_y_ids.n_rows);\n\n\t\t\t\t\tfor (int j=0; j<slice_y_ids.n_rows; j++) {\n\t\t\t\t\t\tR2(j) = sqrt(pow(slice_points_y(0,j)-R1_point(0),2.0)+pow(slice_points_y(2,j)-R1_point(2),2.0));\n\t\t\t\t\t}\n\n\t\t\t\t\tint max_R2 = R2.index_max();\n\n\t\t\t\t\tarma::Col<double> R2_point = slice_points_y.col(max_R2);\n\n\t\t\t\t\t// Calculate the angle between the x-axis and the vector R1_point-R2_point:\n\n\t\t\t\t\tdouble theta = atan2(R1_point(2)-R2_point(2),R1_point(0)-R2_point(0));\n\n\t\t\t\t\tif (isfinite(theta)) {\n\t\t\t\t\t\tangle_y(i) = theta;\n\t\t\t\t\t\tchord_length(i) = sqrt(pow(R1_point(0)-R2_point(0),2.0)+pow(R1_point(2)-R2_point(2),2.0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\tif (slice_y_ids.n_rows > 10) {\n\n\t\t\t\t\t// Perform eigenvalue decomposition:\n\n\t\t\t\t\tarma::Mat<double> slice_points_y = wing_pcl_ref.cols(slice_y_ids);\n\n\t\t\t\t\tarma::Mat<double> X(3,slice_y_ids.n_rows);\n\n\t\t\t\t\tX.row(0) = slice_points_y.row(0);\n\t\t\t\t\tX.row(1) = slice_points_y.row(1);\n\t\t\t\t\tX.row(2) = slice_points_y.row(2);\n\n\t\t\t\t\tarma::mat U;\n\t\t\t\t\tarma::vec s;\n\t\t\t\t\tarma::mat V;\n\n\t\t\t\t\tarma::svd(U,s,V,X);\n\n\t\t\t\t\tarma::Col<double> eig_vec_1 = U.col(0);\n\n\t\t\t\t\tdouble theta = atan2(eig_vec_1(2),eig_vec_1(0));\n\n\t\t\t\t\tif (isfinite(theta)) {\n\t\t\t\t\t\tangle_y(i) = theta;\n\t\t\t\t\t\tN_seg_points(i) = slice_y_ids.n_rows;\n\t\t\t\t\t\t//chord_length(i) = sqrt(pow(R1_point(0)-R2_point(0),2.0)+pow(R1_point(2)-R2_point(2),2.0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\n\t\t\tdouble y_tip = wing_pcl_ref.row(1).min();\n\n\t\t\t// Split the wing in N segments:\n\t\t\tfor (int i=0; i<N_segs; i++) {\n\n\t\t\t\t// Select y-slice elements\n\t\t\t\tarma::uvec slice_y_ids = arma::find((wing_pcl_ref.row(1) < (i*(y_tip/((N_segs+1)*1.0)))) && (wing_pcl_ref.row(1) > ((i+1)*(y_tip/((N_segs+1)*1.0)))));\n\n\n\t\t\t\t\n\t\t\t\tif (slice_y_ids.n_rows > 2) {\n\n\t\t\t\t\tarma::Mat<double> slice_points_y = wing_pcl_ref.cols(slice_y_ids);\n\n\t\t\t\t\t// Find the maximum radius from the mid point of the section\n\n\t\t\t\t\tarma::Row<double> R1;\n\t\t\t\t\tR1.zeros(slice_y_ids.n_rows);\n\n\t\t\t\t\tfor (int j=0; j<slice_y_ids.n_rows; j++) {\n\t\t\t\t\t\tR1(j) = sqrt(pow(slice_points_y(0,j),2.0)+pow(slice_points_y(2,j),2.0));\n\t\t\t\t\t}\n\n\t\t\t\t\tint max_R1 = R1.index_max();\n\n\t\t\t\t\tarma::Col<double> R1_point = slice_points_y.col(max_R1);\n\n\t\t\t\t\t// Find the maximum radius from R1:\n\n\t\t\t\t\tarma::Row<double> R2;\n\t\t\t\t\tR2.zeros(slice_y_ids.n_rows);\n\n\t\t\t\t\tfor (int j=0; j<slice_y_ids.n_rows; j++) {\n\t\t\t\t\t\tR2(j) = sqrt(pow(slice_points_y(0,j)-R1_point(0),2.0)+pow(slice_points_y(2,j)-R1_point(2),2.0));\n\t\t\t\t\t}\n\n\t\t\t\t\tint max_R2 = R2.index_max();\n\n\t\t\t\t\tarma::Col<double> R2_point = slice_points_y.col(max_R2);\n\n\t\t\t\t\t// Calculate the angle between the x-axis and the vector R1_point-R2_point:\n\n\t\t\t\t\tdouble theta = atan2(R1_point(2)-R2_point(2),R1_point(0)-R2_point(0));\n\n\t\t\t\t\tif (isfinite(theta)) {\n\t\t\t\t\t\tangle_y(i) = theta;\n\t\t\t\t\t\tchord_length(i) = sqrt(pow(R1_point(0)-R2_point(0),2.0)+pow(R1_point(2)-R2_point(2),2.0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\tif (slice_y_ids.n_rows > 10) {\n\n\t\t\t\t\t// Perform eigenvalue decomposition:\n\n\t\t\t\t\tarma::Mat<double> slice_points_y = wing_pcl_ref.cols(slice_y_ids);\n\n\t\t\t\t\tarma::Mat<double> X(3,slice_y_ids.n_rows);\n\n\t\t\t\t\tX.row(0) = slice_points_y.row(0);\n\t\t\t\t\tX.row(1) = slice_points_y.row(1);\n\t\t\t\t\tX.row(2) = slice_points_y.row(2);\n\n\t\t\t\t\tarma::mat U;\n\t\t\t\t\tarma::vec s;\n\t\t\t\t\tarma::mat V;\n\n\t\t\t\t\tarma::svd(U,s,V,X);\n\n\t\t\t\t\tarma::Col<double> eig_vec_1 = U.col(0);\n\n\t\t\t\t\tdouble theta = atan2(eig_vec_1(2),eig_vec_1(0));\n\n\t\t\t\t\tif (isfinite(theta)) {\n\t\t\t\t\t\tangle_y(i) = theta;\n\t\t\t\t\t\tN_seg_points(i) = slice_y_ids.n_rows;\n\t\t\t\t\t\t//chord_length(i) = sqrt(pow(R1_point(0)-R2_point(0),2.0)+pow(R1_point(2)-R2_point(2),2.0));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tcout << angle_y << endl;\n\t\tcout << N_seg_points << endl;\n\n\t\t// Determine the average orientation angle:\n\t\tdouble cos_2_theta_avg = 0.0;\n\t\tdouble chord_length_sum = 0.0;\n\t\tfor (int i=0; i<N_segs; i++) {\n\t\t\tif (chord_length(i) > 0.0) {\n\t\t\t\tcos_2_theta_avg += chord_length(i)*0.5*acos(cos(2.0*angle_y(i)));\n\t\t\t\tchord_length_sum += chord_length(i);\n\t\t\t}\n\t\t}\n\n\t\tcout << cos_2_theta_avg << endl;\n\n\t\tdouble theta_avg = 0.0;\n\n\t\tif (chord_length_sum>0.0) {\n\t\t\ttheta_avg = cos_2_theta_avg/chord_length_sum;\n\t\t}\n\n\t\t/*\n\t\tdouble cos_2_theta_avg = 0.0;\n\t\tint N_seg_points_sum = 0;\n\n\t\tfor (int i=0; i<N_segs; i++) {\n\t\t\tif (N_seg_points(i) > 10) {\n\t\t\t\tcos_2_theta_avg += N_seg_points(i)*0.5*acos(cos(2.0*angle_y(i)));\n\t\t\t\tN_seg_points_sum += N_seg_points(i);\n\t\t\t}\n\t\t}\n\n\t\tcout << cos_2_theta_avg << endl;\n\n\t\tdouble theta_avg = 0.0;\n\n\t\tif (N_seg_points_sum>10) {\n\t\t\ttheta_avg = cos_2_theta_avg/(1.0*N_seg_points_sum);\n\t\t}\n\n\t\tcout << theta_avg << endl;\n\n\t\t// Rotate the pointcloud by theta_avg around the y-axis:\n\t\tarma::Mat<double> M_theta1;\n\t\tM_theta1.eye(4,4);\n\t\tM_theta1(0,0) = cos(theta_avg);\n\t\tM_theta1(0,2) = -sin(theta_avg);\n\t\tM_theta1(2,0) = sin(theta_avg);\n\t\tM_theta1(2,2) = cos(theta_avg);\n\n\t\tcout << \"M theta 1\" << endl;\n\t\tcout << M_theta1 << endl;\n\n\t\tarma::Mat<double> M_theta2;\n\t\tM_theta2.eye(4,4);\n\t\tM_theta2(0,0) = cos(theta_avg+PI);\n\t\tM_theta2(0,2) = -sin(theta_avg+PI);\n\t\tM_theta2(2,0) = sin(theta_avg+PI);\n\t\tM_theta2(2,2) = cos(theta_avg+PI);\n\n\t\tcout << \"M theta 2\" << endl;\n\t\tcout << M_theta2 << endl;\n\n\t\t// Return M_out, wing_grid and orient_ind:\n\n\t\tM_out(0,0) = M_vector(0,0);\n\t\tM_out(0,1) = M_vector(0,1);\n\t\tM_out(0,2) = M_vector(0,2);\n\t\tM_out(0,3) = M_vector(0,3);\n\t\tM_out(1,0) = M_vector(1,0);\n\t\tM_out(1,1) = M_vector(1,1);\n\t\tM_out(1,2) = M_vector(1,2);\n\t\tM_out(1,3) = M_vector(1,3);\n\t\tM_out(2,0) = M_vector(2,0);\n\t\tM_out(2,1) = M_vector(2,1);\n\t\tM_out(2,2) = M_vector(2,2);\n\t\tM_out(2,3) = M_vector(2,3);\n\t\tM_out(3,3) = 1.0;\n\n\t\tM_out.submat(0,0,3,3) = M_out.submat(0,0,3,3)*M_theta1;\n\n\t\tM_out(0,4) = M_vector(0,0);\n\t\tM_out(0,5) = M_vector(0,1);\n\t\tM_out(0,6) = M_vector(0,2);\n\t\tM_out(0,7) = M_vector(0,3);\n\t\tM_out(1,4) = M_vector(1,0);\n\t\tM_out(1,5) = M_vector(1,1);\n\t\tM_out(1,6) = M_vector(1,2);\n\t\tM_out(1,7) = M_vector(1,3);\n\t\tM_out(2,4) = M_vector(2,0);\n\t\tM_out(2,5) = M_vector(2,1);\n\t\tM_out(2,6) = M_vector(2,2);\n\t\tM_out(2,7) = M_vector(2,3);\n\t\tM_out(3,7) = 1.0;\n\n\t\tM_out.submat(0,4,3,7) = M_out.submat(0,4,3,7)*M_theta2;\n\n\t\tcout << M_out << endl;\n\n\t}\n\telse {\n\n\t\tM_out(0,0) = M_vector(0,0);\n\t\tM_out(0,1) = M_vector(0,1);\n\t\tM_out(0,2) = M_vector(0,2);\n\t\tM_out(0,3) = M_vector(0,3);\n\t\tM_out(1,0) = M_vector(1,0);\n\t\tM_out(1,1) = M_vector(1,1);\n\t\tM_out(1,2) = M_vector(1,2);\n\t\tM_out(1,3) = M_vector(1,3);\n\t\tM_out(2,0) = M_vector(2,0);\n\t\tM_out(2,1) = M_vector(2,1);\n\t\tM_out(2,2) = M_vector(2,2);\n\t\tM_out(2,3) = M_vector(2,3);\n\t\tM_out(3,3) = 1.0;\n\n\t\tM_out(0,4) = M_vector(0,8);\n\t\tM_out(0,5) = M_vector(0,9);\n\t\tM_out(0,6) = M_vector(0,10);\n\t\tM_out(0,7) = M_vector(0,11);\n\t\tM_out(1,4) = M_vector(1,8);\n\t\tM_out(1,5) = M_vector(1,9);\n\t\tM_out(1,6) = M_vector(1,10);\n\t\tM_out(1,7) = M_vector(1,11);\n\t\tM_out(2,4) = M_vector(2,8);\n\t\tM_out(2,5) = M_vector(2,9);\n\t\tM_out(2,6) = M_vector(2,10);\n\t\tM_out(2,7) = M_vector(2,11);\n\t\tM_out(3,7) = 1.0;\n\n\t}\n\n\treturn M_out;\n\n}\n*/\n\n\nvector<arma::Mat<double>> InitState::FindWingRefFrame(arma::Mat<double> M_body, arma::Mat<double> wing_L_pcl, arma::Mat<double> wing_R_pcl) {\n\n\t// Fit oriented bounding boxes to the pointclouds:\n\n\tarma::Mat<double> M_L(4,16); // 4 possible orientations left wing\n\n\tif (arma::sum(wing_L_pcl.row(1)) != 0.0) {\n\t\tstruct bbox bbox_L = InitState::BoundingBox(wing_L_pcl);\n\t\tarma::Mat<double> c_points_L = InitState::FindRootTip(M_body, bbox_L);\n\t\tarma::Col<double> root_L(3);\n\t\tarma::Col<double> tip_L(3);\n\t\troot_L(0) = 0.25*(c_points_L(0,0)+c_points_L(0,1)+c_points_L(0,2)+c_points_L(0,3));\n\t\troot_L(1) = 0.25*(c_points_L(1,0)+c_points_L(1,1)+c_points_L(1,2)+c_points_L(1,3));\n\t\troot_L(2) = 0.25*(c_points_L(2,0)+c_points_L(2,1)+c_points_L(2,2)+c_points_L(2,3));\n\t\ttip_L(0) = 0.25*(c_points_L(0,4)+c_points_L(0,5)+c_points_L(0,6)+c_points_L(0,7));\n\t\ttip_L(1) = 0.25*(c_points_L(1,4)+c_points_L(1,5)+c_points_L(1,6)+c_points_L(1,7));\n\t\ttip_L(2) = 0.25*(c_points_L(2,4)+c_points_L(2,5)+c_points_L(2,6)+c_points_L(2,7));\n\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tarma::Mat<double> base(3,3);\n\t\t\tarma::Col<double> x_vec(3);\n\t\t\tarma::Col<double> y_vec(3);\n\t\t\tarma::Col<double> z_vec(3);\n\n\t\t\tx_vec(0) = c_points_L(0,i)-root_L(0);\n\t\t\tx_vec(1) = c_points_L(1,i)-root_L(1);\n\t\t\tx_vec(2) = c_points_L(2,i)-root_L(2);\n\t\t\tbase.col(0) = x_vec/arma::norm(x_vec,2);\n\t\t\ty_vec(0) = tip_L(0)-root_L(0);\n\t\t\ty_vec(1) = tip_L(1)-root_L(1);\n\t\t\ty_vec(2) = tip_L(2)-root_L(2);\n\t\t\tbase.col(1) = y_vec/arma::norm(y_vec,2);\n\t\t\tz_vec = arma::cross(x_vec,y_vec);\n\t\t\tbase.col(2) = z_vec/arma::norm(z_vec,2);\n\n\t\t\tM_L(0,i*4) \t = base(0,0);\n\t\t\tM_L(0,i*4+1) = base(0,1);\n\t\t\tM_L(0,i*4+2) = base(0,2);\n\t\t\tM_L(0,i*4+3) = root_L(0);\n\t\t\tM_L(1,i*4) \t = base(1,0);\n\t\t\tM_L(1,i*4+1) = base(1,1);\n\t\t\tM_L(1,i*4+2) = base(1,2);\n\t\t\tM_L(1,i*4+3) = root_L(1);\n\t\t\tM_L(2,i*4) \t = base(2,0);\n\t\t\tM_L(2,i*4+1) = base(2,1);\n\t\t\tM_L(2,i*4+2) = base(2,2);\n\t\t\tM_L(2,i*4+3) = root_L(2);\n\t\t\tM_L(3,i*4) \t = 0.0;\n\t\t\tM_L(3,i*4+1) = 0.0;\n\t\t\tM_L(3,i*4+2) = 0.0;\n\t\t\tM_L(3,i*4+3) = 1.0;\n\t\t}\n\t}\n\telse {\n\t\tM_L.zeros(4,16);\n\t}\n\t\n\tarma::Mat<double> M_R(4,16); // 4 possible orientations right wing\n\n\tif (arma::sum(wing_R_pcl.row(1)) != 0.0) {\n\t\tstruct bbox bbox_R = InitState::BoundingBox(wing_R_pcl);\n\t\tarma::Mat<double> c_points_R = InitState::FindRootTip(M_body, bbox_R);\n\t\tarma::Col<double> root_R(3);\n\t\tarma::Col<double> tip_R(3);\n\t\troot_R(0) = 0.25*(c_points_R(0,0)+c_points_R(0,1)+c_points_R(0,2)+c_points_R(0,3));\n\t\troot_R(1) = 0.25*(c_points_R(1,0)+c_points_R(1,1)+c_points_R(1,2)+c_points_R(1,3));\n\t\troot_R(2) = 0.25*(c_points_R(2,0)+c_points_R(2,1)+c_points_R(2,2)+c_points_R(2,3));\n\t\ttip_R(0) = 0.25*(c_points_R(0,4)+c_points_R(0,5)+c_points_R(0,6)+c_points_R(0,7));\n\t\ttip_R(1) = 0.25*(c_points_R(1,4)+c_points_R(1,5)+c_points_R(1,6)+c_points_R(1,7));\n\t\ttip_R(2) = 0.25*(c_points_R(2,4)+c_points_R(2,5)+c_points_R(2,6)+c_points_R(2,7));\n\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tarma::Mat<double> base(3,3);\n\t\t\tarma::Col<double> x_vec(3);\n\t\t\tarma::Col<double> y_vec(3);\n\t\t\tarma::Col<double> z_vec(3);\n\n\t\t\tx_vec(0) = c_points_R(0,i)-root_R(0);\n\t\t\tx_vec(1) = c_points_R(1,i)-root_R(1);\n\t\t\tx_vec(2) = c_points_R(2,i)-root_R(2);\n\t\t\t//base.row(0) = arma::trans(x_vec/arma::norm(x_vec,2));\n\t\t\tbase.col(0) = x_vec/arma::norm(x_vec,2);\n\t\t\ty_vec(0) = -tip_R(0)+root_R(0);\n\t\t\ty_vec(1) = -tip_R(1)+root_R(1);\n\t\t\ty_vec(2) = -tip_R(2)+root_R(2);\n\t\t\tbase.col(1) = y_vec/arma::norm(y_vec,2);\n\t\t\tz_vec = arma::cross(x_vec,y_vec);\n\t\t\tbase.col(2) = z_vec/arma::norm(z_vec,2);\n\n\t\t\tM_R(0,i*4) \t = base(0,0);\n\t\t\tM_R(0,i*4+1) = base(0,1);\n\t\t\tM_R(0,i*4+2) = base(0,2);\n\t\t\tM_R(0,i*4+3) = root_R(0);\n\t\t\tM_R(1,i*4) \t = base(1,0);\n\t\t\tM_R(1,i*4+1) = base(1,1);\n\t\t\tM_R(1,i*4+2) = base(1,2);\n\t\t\tM_R(1,i*4+3) = root_R(1);\n\t\t\tM_R(2,i*4) \t = base(2,0);\n\t\t\tM_R(2,i*4+1) = base(2,1);\n\t\t\tM_R(2,i*4+2) = base(2,2);\n\t\t\tM_R(2,i*4+3) = root_R(2);\n\t\t\tM_R(3,i*4) \t = 0.0;\n\t\t\tM_R(3,i*4+1) = 0.0;\n\t\t\tM_R(3,i*4+2) = 0.0;\n\t\t\tM_R(3,i*4+3) = 1.0;\n\t\t}\n\t}\n\telse {\n\t\tM_R.zeros(4,16);\n\t}\n\n\tvector<arma::Mat<double>> output_vec;\n\n\toutput_vec.push_back(M_L);\n\toutput_vec.push_back(M_R);\n\n\treturn output_vec;\n}\n\n\narma::Mat<double> InitState::FindBodyRefFrame(struct bbox &body_box, arma::Mat<double> &body_pcl) {\n\n\t// I don't really like this, it assumes some properties of the body which are probably not universal\n\n\tarma::Mat<double> M_body = {{body_box.R_box[0][0],body_box.R_box[0][1],body_box.R_box[0][2],body_box.box_center[0]},\n\t\t\t{body_box.R_box[1][0],body_box.R_box[1][1],body_box.R_box[1][2],body_box.box_center[1]},\n\t\t\t{body_box.R_box[2][0],body_box.R_box[2][1],body_box.R_box[2][2],body_box.box_center[2]},\n\t\t\t{0.0, 0.0, 0.0 ,1.0}};\n\n\tarma::Mat<double> M_body_T = {{body_box.R_box[0][0],body_box.R_box[1][0],body_box.R_box[2][0]},\n\t\t\t{body_box.R_box[0][1],body_box.R_box[1][1],body_box.R_box[2][1]},\n\t\t\t{body_box.R_box[0][2],body_box.R_box[1][2],body_box.R_box[2][2]}};\n\n\t// Convert points to body reference frame:\n\n \tint N_points = body_pcl.n_cols;\n\n \tarma::Mat<double> body_points(3,N_points);\n\n \tbody_points.row(0) = body_pcl.row(1);\n \tbody_points.row(1) = body_pcl.row(2);\n \tbody_points.row(2) = body_pcl.row(3);\n\n \tarma::Col<double> body_center = {body_box.box_center[0], body_box.box_center[1], body_box.box_center[2]};\n\n \tbody_points.each_col() -= body_center;\n\n \tarma::Mat<double> body_points_T = M_body_T*body_points;\n\n \tarma::Mat<double> seg_x1;\n \tarma::Mat<double> seg_x2;\n \tarma::Mat<double> seg_y1;\n \tarma::Mat<double> seg_y2;\n\n \tseg_x1 = body_points_T.cols(arma::find(body_points_T.row(0)<((1.0/2.0)*body_box.box_corners[0][0])));\n \tseg_x2 = body_points_T.cols(arma::find(body_points_T.row(0)>((1.0/2.0)*body_box.box_corners[0][2])));\n \tseg_y1 = body_points_T.cols(arma::find(body_points_T.row(1)<((1.0/4.0)*body_box.box_corners[1][0])));\n \tseg_y2 = body_points_T.cols(arma::find(body_points_T.row(1)>((1.0/4.0)*body_box.box_corners[1][4])));\n\n \tarma::Col<double> cg_x1 = arma::mean(seg_x1,1);\n \tarma::Col<double> cg_x2 = arma::mean(seg_x2,1);\n \tarma::Col<double> cg_y1 = arma::mean(seg_y1,1);\n \tarma::Col<double> cg_y2 = arma::mean(seg_y2,1);\n\n \tdouble Ix_1 = 0.0;\n \tdouble Ix_2 = 0.0;\n \tdouble Iy_1 = 0.0;\n \tdouble Iy_2 = 0.0;\n\n \tfor (int i=0; i<seg_x1.n_cols; i++) {\n \t\tIx_1 = Ix_1+pow(seg_x1(1,i)-cg_x1(1),2.0)+pow(seg_x1(2,i)-cg_x1(2),2.0);\n \t}\n\n \tfor (int i=0; i<seg_x2.n_cols; i++) {\n \t\tIx_2 = Ix_2+pow(seg_x2(1,i)-cg_x2(1),2.0)+pow(seg_x2(2,i)-cg_x2(2),2.0);\n \t}\n\n\tfor (int i=0; i<seg_y1.n_cols; i++) {\n \t\tIy_1 = Iy_1+pow(seg_y1(1,i),2.0);\n \t}\n\n \tfor (int i=0; i<seg_y2.n_cols; i++) {\n \t\tIy_2 = Iy_2+pow(seg_y2(1,i),2.0);\n \t}\n\n \t//cout << M_body << endl;\n\n \tif (Ix_1 > Ix_2) {\n \t\t// Abdomen is located on negative x-axis: switch y and z axes\n \t\tM_body = {{M_body(0,0),M_body(0,2),M_body(0,1),M_body(0,3)},\n \t\t\t\t{M_body(1,0),M_body(1,2),M_body(1,1),M_body(1,3)},\n \t\t\t\t{M_body(2,0),M_body(2,2),M_body(2,1),M_body(2,3)},\n \t\t\t\t{M_body(3,0),M_body(3,2),M_body(3,1),M_body(3,3)}};\n \t}\n \telse if (Ix_1 < Ix_2) {\n \t\t// Abdomen is located on the positive x-axis: rotate by 180 degrees and switch y and z axes\n \t\tM_body = {{-M_body(0,0),M_body(0,2),M_body(0,1),M_body(0,3)},\n \t\t\t\t{-M_body(1,0),M_body(1,2),M_body(1,1),M_body(1,3)},\n \t\t\t\t{-M_body(2,0),M_body(2,2),M_body(2,1),M_body(2,3)},\n \t\t\t\t{-M_body(3,0),M_body(3,2),M_body(3,1),M_body(3,3)}};\n \t}\n \telse {\n \t\t// Don't know where the abdomen is located: switch y and z axes\n \t\tM_body = {{M_body(0,0),M_body(0,2),M_body(0,1),M_body(0,3)},\n \t\t\t\t{M_body(1,0),M_body(1,2),M_body(1,1),M_body(1,3)},\n \t\t\t\t{M_body(2,0),M_body(2,2),M_body(2,1),M_body(2,3)},\n \t\t\t\t{M_body(3,0),M_body(3,2),M_body(3,1),M_body(3,3)}};\n \t}\n\n \tif (Iy_1 > Iy_2) {\n \t\t// c.g. is located at the bottom, z-axis is oriented correctly\n \t}\n \telse if (Iy_1 < Iy_2) {\n \t\t// c.g is located at the top, rotate 180 degrees around x-axis\n \t\tM_body = {{M_body(0,0),M_body(0,1),-M_body(0,2),M_body(0,3)},\n \t\t\t\t{M_body(1,0),M_body(1,1),-M_body(1,2),M_body(1,3)},\n \t\t\t\t{M_body(2,0),M_body(2,1),-M_body(2,2),M_body(2,3)},\n \t\t\t\t{M_body(3,0),M_body(3,1),-M_body(3,2),M_body(3,3)}};\n \t}\n \telse {\n \t\t// Don't know where the c.g. is located: keep current M_body\n \t}\n\n \tarma::Col<double> x_axis = {M_body(0,0),M_body(1,0),M_body(2,0)};\n \tarma::Col<double> z_axis = {M_body(0,2),M_body(1,2),M_body(2,2)};\n\n \tarma::Col<double> y_axis_M = {M_body(0,1),M_body(1,1),M_body(2,1)};\n \tarma::Col<double> y_axis_cross = arma::cross(x_axis,z_axis);\n\n \tdouble y_dot = arma::dot(y_axis_M,y_axis_cross)/(arma::norm(y_axis_M,2)*arma::norm(y_axis_cross,2));\n\n \tif (y_dot > 0.5) {\n \t\t// Switch sign y-axis:\n \t\tM_body = {{M_body(0,0),-M_body(0,1),M_body(0,2),M_body(0,3)},\n \t\t\t\t{M_body(1,0),-M_body(1,1),M_body(1,2),M_body(1,3)},\n \t\t\t\t{M_body(2,0),-M_body(2,1),M_body(2,2),M_body(2,3)},\n \t\t\t\t{M_body(3,0),-M_body(3,1),M_body(3,2),M_body(3,3)}};\n \t}\n\n\treturn M_body;\n}\n\narma::Mat<double> InitState::FindRootTip(arma::Mat<double> M_body, struct bbox &seg_box) {\n\n\tarma::Mat<double> rot_body_T = {{M_body(0,0),M_body(1,0),M_body(2,0),0.0},\n\t\t\t{M_body(0,1),M_body(1,1),M_body(2,1),0.0},\n\t\t\t{M_body(0,2),M_body(1,2),M_body(2,2),0.0}};\n\n\tarma::Mat<double> rot_mat = {{seg_box.R_box[0][0], seg_box.R_box[0][1], seg_box.R_box[0][2], seg_box.box_center[0]},\n\t\t\t{seg_box.R_box[1][0], seg_box.R_box[1][1], seg_box.R_box[1][2], seg_box.box_center[1]},\n\t\t\t{seg_box.R_box[2][0], seg_box.R_box[2][1], seg_box.R_box[2][2], seg_box.box_center[2]},\n\t\t\t{0.0, 0.0, 0.0, 1.0}};\n\n\tarma::Col<double> body_center = {M_body(0,3), M_body(1,3), M_body(2,3), 1.0};\n\n\tarma::Mat<double> corners_seg(4,8);\n\tarma::Row<double> corner_dist(8);\n\n\tfor (int i=0; i<8; i++) {\n\t\tarma::Col<double> temp_corner = {seg_box.box_corners[0][i], seg_box.box_corners[1][i], seg_box.box_corners[2][i], 1.0};\n\t\tcorners_seg.col(i) = rot_mat*temp_corner;\n\t\tcorner_dist(i) = sqrt(pow(corners_seg(0,i)-body_center(0),2.0)+pow(corners_seg(1,i)-body_center(1),2.0)+pow(corners_seg(2,i)-body_center(2),2.0));\n\t}\n\n\t// Select the 4 corners which are closest to the body center and the 4 corners which are the furthest away:\n\n\tarma::uvec c_sorted = arma::sort_index(corner_dist);\n\n\tarma::Mat<double> c_points(4,12);\n\n\t// Sorted corners + distances\n\n\tc_points(0,0) = corners_seg(0,c_sorted(0));\n\tc_points(1,0) = corners_seg(1,c_sorted(0));\n\tc_points(2,0) = corners_seg(2,c_sorted(0));\n\tc_points(3,0) = corner_dist(c_sorted(0));\n\n\tc_points(0,1) = corners_seg(0,c_sorted(1));\n\tc_points(1,1) = corners_seg(1,c_sorted(1));\n\tc_points(2,1) = corners_seg(2,c_sorted(1));\n\tc_points(3,1) = corner_dist(c_sorted(1));\n\n\tc_points(0,2) = corners_seg(0,c_sorted(2));\n\tc_points(1,2) = corners_seg(1,c_sorted(2));\n\tc_points(2,2) = corners_seg(2,c_sorted(2));\n\tc_points(3,2) = corner_dist(c_sorted(2));\n\n\tc_points(0,3) = corners_seg(0,c_sorted(3));\n\tc_points(1,3) = corners_seg(1,c_sorted(3));\n\tc_points(2,3) = corners_seg(2,c_sorted(3));\n\tc_points(3,3) = corner_dist(c_sorted(3));\n\n\tc_points(0,4) = corners_seg(0,c_sorted(4));\n\tc_points(1,4) = corners_seg(1,c_sorted(4));\n\tc_points(2,4) = corners_seg(2,c_sorted(4));\n\tc_points(3,4) = corner_dist(c_sorted(4));\n\n\tc_points(0,5) = corners_seg(0,c_sorted(5));\n\tc_points(1,5) = corners_seg(1,c_sorted(5));\n\tc_points(2,5) = corners_seg(2,c_sorted(5));\n\tc_points(3,5) = corner_dist(c_sorted(5));\n\n\tc_points(0,6) = corners_seg(0,c_sorted(6));\n\tc_points(1,6) = corners_seg(1,c_sorted(6));\n\tc_points(2,6) = corners_seg(2,c_sorted(6));\n\tc_points(3,6) = corner_dist(c_sorted(6));\n\n\tc_points(0,7) = corners_seg(0,c_sorted(7));\n\tc_points(1,7) = corners_seg(1,c_sorted(7));\n\tc_points(2,7) = corners_seg(2,c_sorted(7));\n\tc_points(3,7) = corner_dist(c_sorted(7));\n\n\t// root point\n\n\tc_points(0,8) = 0.25*(corners_seg(0,c_sorted(0))+corners_seg(0,c_sorted(1))+corners_seg(0,c_sorted(2))+corners_seg(0,c_sorted(3)))-body_center(0);\n\tc_points(1,8) = 0.25*(corners_seg(1,c_sorted(0))+corners_seg(1,c_sorted(1))+corners_seg(1,c_sorted(2))+corners_seg(1,c_sorted(3)))-body_center(1);\n\tc_points(2,8) = 0.25*(corners_seg(2,c_sorted(0))+corners_seg(2,c_sorted(1))+corners_seg(2,c_sorted(2))+corners_seg(2,c_sorted(3)))-body_center(2);\n\tc_points(3,8) = sqrt(pow(c_points(0,8),2.0)+pow(c_points(1,8),2.0)+pow(c_points(2,8),2.0));\n\n\t// tip point\n\n\tc_points(0,9) = 0.25*(corners_seg(0,c_sorted(4))+corners_seg(0,c_sorted(5))+corners_seg(0,c_sorted(6))+corners_seg(0,c_sorted(7)))-body_center(0);\n\tc_points(1,9) = 0.25*(corners_seg(1,c_sorted(4))+corners_seg(1,c_sorted(5))+corners_seg(1,c_sorted(6))+corners_seg(1,c_sorted(7)))-body_center(1);\n\tc_points(2,9) = 0.25*(corners_seg(2,c_sorted(4))+corners_seg(2,c_sorted(5))+corners_seg(2,c_sorted(6))+corners_seg(2,c_sorted(7)))-body_center(2);\n\tc_points(3,9) = sqrt(pow(c_points(0,9),2.0)+pow(c_points(1,9),2.0)+pow(c_points(2,9),2.0));\n\n\t// angular orientation w.r.t. body ref frame and volume\n\tarma::Col<double> tip_body_ref = rot_body_T*c_points.col(9);\n\tdouble xsi = atan2(tip_body_ref(1),tip_body_ref(2));\n\tdouble theta = atan2(tip_body_ref(0),sqrt(pow(tip_body_ref(1),2)+pow(tip_body_ref(2),2)));\n\tdouble seg_L = sqrt(pow((c_points(0,9)-c_points(0,8)),2)+pow((c_points(1,9)-c_points(1,8)),2)+pow((c_points(2,9)-c_points(2,8)),2));\n\tc_points(0,10) = xsi;\n\tc_points(1,10) = theta;\n\tc_points(2,10) = seg_L;\n\tc_points(3,10) = seg_box.volume;\n\n\t// center point\n\tc_points(0,11) = seg_box.box_center[0]-body_center(0);\n\tc_points(1,11) = seg_box.box_center[1]-body_center(1);\n\tc_points(2,11) = seg_box.box_center[2]-body_center(2);\n\tc_points(3,11) = sqrt(pow(c_points(0,11),2.0)+pow(c_points(1,11),2.0)+pow(c_points(2,11),2.0));\n\n\t// Project a point one wing length away from the wing tip along the y-axis of the \n\n\treturn c_points;\n}\n\nvector<tuple<struct bbox, arma::Mat<double>>> InitState::FindBoundingBoxes(arma::Mat<double> &pcl_in) {\n\n\t// Find the bounding boxes for all the bounding boxes in the image:\n\tarma::Row<double> pcl_intensity = pcl_in.row(0);\n\tarma::Row<double> segment_id = arma::unique(pcl_intensity);\n\n\tdouble body_id = segment_id.min();\n\n\tint N_segments = segment_id.n_cols;\n\n\tarma::Mat<double> body_pcl;\n\tstruct bbox body_box;\n\tvector<arma::Mat<double>> segment_pcl;\n\tarma::Mat<double> seg_pcl;\n\tvector<struct bbox> segment_box;\n\n\tfor (int i=0; i<N_segments; i++) {\n\t\tif (segment_id(i)==body_id) {\n\t\t\tarma::uvec seg_indices = arma::find(pcl_intensity == segment_id(i));\n\t\t\tbody_pcl = pcl_in.cols(seg_indices);\n\t\t\tbody_box = InitState::BoundingBox(body_pcl);\n\t\t}\n\t\telse {\n\t\t\tarma::uvec seg_indices = arma::find(pcl_intensity == segment_id(i));\n\t\t\tif (seg_indices.n_rows > 10) {\n\t\t\t\tseg_pcl = pcl_in.cols(seg_indices);\n\t\t\t\tsegment_pcl.push_back(seg_pcl);\n\t\t\t\tsegment_box.push_back(InitState::BoundingBox(seg_pcl));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return bounding boxes with body bounding box as the first item:\n\tvector<tuple<struct bbox, arma::Mat<double>>> bbox_list;\n\tfor (int j=0; j<(segment_box.size()+1); j++) {\n\t\tif (j==0) {\n\t\t\tbbox_list.push_back(make_tuple(body_box,body_pcl));\n\t\t}\n\t\telse {\n\t\t\tbbox_list.push_back(make_tuple(segment_box[j-1],segment_pcl[j-1]));\n\t\t}\n\t}\n\n\treturn bbox_list;\n}\n\nbbox InitState::BoundingBox(arma::Mat<double> &pcl_in) {\n\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in (new pcl::PointCloud<pcl::PointXYZ>());\n\t*cloud_in = InitState::Convert_Mat_2_PCL_XYZ(pcl_in);\n\n\tpcl::MomentOfInertiaEstimation <pcl::PointXYZ> feature_extractor;\n  \tfeature_extractor.setInputCloud (cloud_in);\n  \tfeature_extractor.compute ();\n\n  \t// Oriented Bounding Box properties\n\n  \tvector<float> moment_of_inertia;\n  \tvector<float> eccentricity;\n\tpcl::PointXYZ min_point_OBB;\n\tpcl::PointXYZ max_point_OBB;\n\tpcl::PointXYZ position_OBB;\n\tEigen::Matrix3f rotational_matrix_OBB;\n  \tfloat major_value, middle_value, minor_value;\n  \tEigen::Vector3f major_vector, middle_vector, minor_vector;\n  \tEigen::Vector3f mass_center;\n\n  \tfeature_extractor.getMomentOfInertia(moment_of_inertia);\n\tfeature_extractor.getEccentricity(eccentricity);\n\tfeature_extractor.getOBB(min_point_OBB, max_point_OBB, position_OBB, rotational_matrix_OBB);\n\tfeature_extractor.getEigenValues(major_value, middle_value, minor_value);\n\tfeature_extractor.getEigenVectors(major_vector, middle_vector, minor_vector);\n\tfeature_extractor.getMassCenter(mass_center);\n\n\tEigen::Vector3f position(position_OBB.x, position_OBB.y, position_OBB.z);\n  \tEigen::Quaternionf quat(rotational_matrix_OBB);\n\n  \t// Return bounding box structure\n\n  \tstruct bbox bounding_box;\n\n  \tbounding_box.box_center[0] = (double) position_OBB.x;\n  \tbounding_box.box_center[1] = (double) position_OBB.y;\n  \tbounding_box.box_center[2] = (double) position_OBB.z;\n  \tbounding_box.box_corners[0][0] = (double) min_point_OBB.x;\n  \tbounding_box.box_corners[1][0] = (double) min_point_OBB.y;\n  \tbounding_box.box_corners[2][0] = (double) min_point_OBB.z;\n\tbounding_box.box_corners[0][1] = (double) min_point_OBB.x;\n  \tbounding_box.box_corners[1][1] = (double) min_point_OBB.y;\n  \tbounding_box.box_corners[2][1] = (double) max_point_OBB.z;\n  \tbounding_box.box_corners[0][2] = (double) max_point_OBB.x;\n  \tbounding_box.box_corners[1][2] = (double) min_point_OBB.y;\n  \tbounding_box.box_corners[2][2] = (double) max_point_OBB.z;\n  \tbounding_box.box_corners[0][3] = (double) max_point_OBB.x;\n  \tbounding_box.box_corners[1][3] = (double) min_point_OBB.y;\n  \tbounding_box.box_corners[2][3] = (double) min_point_OBB.z;\n  \tbounding_box.box_corners[0][4] = (double) min_point_OBB.x;\n  \tbounding_box.box_corners[1][4] = (double) max_point_OBB.y;\n  \tbounding_box.box_corners[2][4] = (double) min_point_OBB.z;\n  \tbounding_box.box_corners[0][5] = (double) min_point_OBB.x;\n  \tbounding_box.box_corners[1][5] = (double) max_point_OBB.y;\n  \tbounding_box.box_corners[2][5] = (double) max_point_OBB.z;\n  \tbounding_box.box_corners[0][6] = (double) max_point_OBB.x;\n  \tbounding_box.box_corners[1][6] = (double) max_point_OBB.y;\n  \tbounding_box.box_corners[2][6] = (double) max_point_OBB.z;\n  \tbounding_box.box_corners[0][7] = (double) max_point_OBB.x;\n  \tbounding_box.box_corners[1][7] = (double) max_point_OBB.y;\n  \tbounding_box.box_corners[2][7] = (double) min_point_OBB.z;\n\tbounding_box.q_box[0] = (double) quat.w();\n\tbounding_box.q_box[1] = (double) quat.x();\n\tbounding_box.q_box[2] = (double) quat.y();\n\tbounding_box.q_box[3] = (double) quat.z();\n\tbounding_box.R_box[0][0] = (double) rotational_matrix_OBB(0,0);\n\tbounding_box.R_box[0][1] = (double) rotational_matrix_OBB(0,1);\n\tbounding_box.R_box[0][2] = (double) rotational_matrix_OBB(0,2);\n\tbounding_box.R_box[1][0] = (double) rotational_matrix_OBB(1,0);\n\tbounding_box.R_box[1][1] = (double) rotational_matrix_OBB(1,1);\n\tbounding_box.R_box[1][2] = (double) rotational_matrix_OBB(1,2);\n\tbounding_box.R_box[2][0] = (double) rotational_matrix_OBB(2,0);\n\tbounding_box.R_box[2][1] = (double) rotational_matrix_OBB(2,1);\n\tbounding_box.R_box[2][2] = (double) rotational_matrix_OBB(2,2);\n\tbounding_box.mass_center[0] = (double)  mass_center(0);\n\tbounding_box.mass_center[1] = (double)  mass_center(1);\n\tbounding_box.mass_center[2] = (double)  mass_center(2);\n\tbounding_box.eigen_values[0] = (double) major_value;\n\tbounding_box.eigen_values[1] = (double) middle_value;\n\tbounding_box.eigen_values[2] = (double) minor_value;\n\tbounding_box.eigen_vectors[0][0] = (double) major_vector(0);\n\tbounding_box.eigen_vectors[0][1] = (double) major_vector(1);\n\tbounding_box.eigen_vectors[0][2] = (double) major_vector(2);\n\tbounding_box.eigen_vectors[1][0] = (double) middle_vector(0);\n\tbounding_box.eigen_vectors[1][1] = (double) middle_vector(1);\n\tbounding_box.eigen_vectors[1][2] = (double) middle_vector(2);\n\tbounding_box.eigen_vectors[2][0] = (double) minor_vector(0);\n\tbounding_box.eigen_vectors[2][1] = (double) minor_vector(1);\n\tbounding_box.eigen_vectors[2][2] = (double) minor_vector(2);\n\tbounding_box.moment_of_inertia[0] = (double) moment_of_inertia[0];\n\tbounding_box.moment_of_inertia[1] = (double) moment_of_inertia[1];\n\tbounding_box.moment_of_inertia[2] = (double) moment_of_inertia[2];\n\tbounding_box.eccentricity[0] = (double) eccentricity[0];\n\tbounding_box.eccentricity[1] = (double) eccentricity[1];\n\tbounding_box.eccentricity[2] = (double) eccentricity[2];\n\tbounding_box.volume = (max_point_OBB.x-min_point_OBB.x)*(max_point_OBB.y-min_point_OBB.y)*(max_point_OBB.z-min_point_OBB.z);\n\n\treturn bounding_box;\n}\n\nnp::ndarray InitState::ReturnBBoxSinglePCL(frames &frame_in) {\n\n\tarma::Mat<double> pcl_in = InitState::ConvertVectorPCLArma(frame_in.single_frame_pcl);\n\n\tvector<tuple<struct bbox, arma::Mat<double>>> bbox_list = InitState::FindBoundingBoxes(pcl_in);\n\n\tint N_boxes = bbox_list.size();\n\n\tp::tuple shape = p::make_tuple(24,N_boxes);\n\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\tnp::ndarray array_out = np::zeros(shape,dtype);\n\n\tfor (int i=0; i<N_boxes; i++) {\n\t\tarma::Mat<double> rot_mat = {{get<0>(bbox_list[i]).R_box[0][0], get<0>(bbox_list[i]).R_box[0][1], get<0>(bbox_list[i]).R_box[0][2], get<0>(bbox_list[i]).box_center[0]},\n\t\t\t{get<0>(bbox_list[i]).R_box[1][0], get<0>(bbox_list[i]).R_box[1][1], get<0>(bbox_list[i]).R_box[1][2], get<0>(bbox_list[i]).box_center[1]},\n\t\t\t{get<0>(bbox_list[i]).R_box[2][0], get<0>(bbox_list[i]).R_box[2][1], get<0>(bbox_list[i]).R_box[2][2], get<0>(bbox_list[i]).box_center[2]},\n\t\t\t{0.0, 0.0, 0.0, 1.0}};\n\t\tfor (int j=0; j<8; j++) {\n\t\t\tarma::Col<double> corner_point = {get<0>(bbox_list[i]).box_corners[0][j], get<0>(bbox_list[i]).box_corners[1][j],\n\t\t\t\tget<0>(bbox_list[i]).box_corners[2][j], 1.0};\n\t\t\tarma::Col<double> new_corner_point = rot_mat*corner_point;\n\n\t\t\tarray_out[j*3][i] = new_corner_point(0);\n\t\t\tarray_out[j*3+1][i] = new_corner_point(1);\n\t\t\tarray_out[j*3+2][i] = new_corner_point(2);\n\t\t}\t\t\n\t}\n\n\treturn array_out;\n}\n\nnp::ndarray InitState::ReturnSinglePCL(frames &frame_in) {\n\n\tvector<tuple<int,double,double,double,double,double,double>> pcl_out = frame_in.single_frame_pcl;\n\n\tint N_points = pcl_out.size();\n\n\tp::tuple shape = p::make_tuple(7,N_points);\n\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\tnp::ndarray array_out = np::zeros(shape,dtype);\n\n\tfor (int i=0; i<N_points; i++) {\n\t\tarray_out[0][i] = get<0>(pcl_out[i]);\n\t\tarray_out[1][i] = get<1>(pcl_out[i]);\n\t\tarray_out[2][i] = get<2>(pcl_out[i]);\n\t\tarray_out[3][i] = get<3>(pcl_out[i]);\n\t\tarray_out[4][i] = get<4>(pcl_out[i]);\n\t\tarray_out[5][i] = get<5>(pcl_out[i]);\n\t\tarray_out[6][i] = get<6>(pcl_out[i]);\n\t}\n\n\treturn array_out;\n}\n\nnp::ndarray InitState::ReturnBBoxBLR(frames &frame_in) {\n\n\tp::tuple shape = p::make_tuple(24,3);\n\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\tnp::ndarray array_out = np::zeros(shape,dtype);\n\n\tfor (int i=0; i<3; i++) {\n\t\tarma::Mat<double> pcl_now = frame_in.pcl_init_single_frame[i];\n\n\t\tif (pcl_now.n_cols>1) {\n\n\t\t\tstruct bbox bbox_now = InitState::BoundingBox(pcl_now);\n\n\t\t\tarma::Mat<double> rot_mat = {{bbox_now.R_box[0][0], bbox_now.R_box[0][1],bbox_now.R_box[0][2], bbox_now.box_center[0]},\n\t\t\t\t{bbox_now.R_box[1][0], bbox_now.R_box[1][1], bbox_now.R_box[1][2], bbox_now.box_center[1]},\n\t\t\t\t{bbox_now.R_box[2][0], bbox_now.R_box[2][1], bbox_now.R_box[2][2], bbox_now.box_center[2]},\n\t\t\t\t{0.0, 0.0, 0.0, 1.0}};\n\n\t\t\tfor (int j=0; j<8; j++) {\n\t\t\t\tarma::Col<double> corner_point = {bbox_now.box_corners[0][j],bbox_now.box_corners[1][j],bbox_now.box_corners[2][j], 1.0};\n\t\t\t\tarma::Col<double> new_corner_point = rot_mat*corner_point;\n\n\t\t\t\tarray_out[j*3][i] = new_corner_point(0);\n\t\t\t\tarray_out[j*3+1][i] = new_corner_point(1);\n\t\t\t\tarray_out[j*3+2][i] = new_corner_point(2);\n\t\t\t}\n\n\t\t}\n\t\telse {\n\t\t\tfor (int j=0; j<8; j++) {\n\t\t\t\tarray_out[j*3][i] = 0.0;\n\t\t\t\tarray_out[j*3+1][i] = 0.0;\n\t\t\t\tarray_out[j*3+2][i] = 0.0;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn array_out;\n}\n\nnp::ndarray InitState::ReturnBLRPCL(frames &frame_in) {\n\n\tarma::Mat<double> pcl_body = frame_in.pcl_init_single_frame[0];\n\tarma::Mat<double> pcl_wing_L = frame_in.pcl_init_single_frame[1];\n\tarma::Mat<double> pcl_wing_R = frame_in.pcl_init_single_frame[2];\n\n\tint N_points_body = pcl_body.n_cols;\n\tint N_points_wing_L = pcl_wing_L.n_cols;\n\tint N_points_wing_R = pcl_wing_R.n_cols;\n\n\tif (N_points_body < 2) {\n\t\tN_points_body = 0;\n\t}\n\tif (N_points_wing_L < 2) {\n\t\tN_points_wing_L = 0;\n\t}\n\tif (N_points_wing_R < 2) {\n\t\tN_points_wing_R = 0;\n\t}\n\n\tp::tuple shape = p::make_tuple(7,N_points_body+N_points_wing_L+N_points_wing_R);\n\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\tnp::ndarray array_out = np::zeros(shape,dtype);\n\n\tfor (int i=0; i<N_points_body; i++) {\n\t\tarray_out[0][i] = pcl_body(0,i);\n\t\tarray_out[1][i] = pcl_body(1,i);\n\t\tarray_out[2][i] = pcl_body(2,i);\n\t\tarray_out[3][i] = pcl_body(3,i);\n\t\tarray_out[4][i] = pcl_body(4,i);\n\t\tarray_out[5][i] = pcl_body(5,i);\n\t\tarray_out[6][i] = pcl_body(6,i);\n\t}\n\n\tfor (int j=0; j<N_points_wing_L; j++) {\n\t\tarray_out[0][j+N_points_body] = pcl_wing_L(0,j);\n\t\tarray_out[1][j+N_points_body] = pcl_wing_L(1,j);\n\t\tarray_out[2][j+N_points_body] = pcl_wing_L(2,j);\n\t\tarray_out[3][j+N_points_body] = pcl_wing_L(3,j);\n\t\tarray_out[4][j+N_points_body] = pcl_wing_L(4,j);\n\t\tarray_out[5][j+N_points_body] = pcl_wing_L(5,j);\n\t\tarray_out[6][j+N_points_body] = pcl_wing_L(6,j);\n\t}\n\n\tfor (int k=0; k<N_points_wing_R; k++) {\n\t\tarray_out[0][k+N_points_body+N_points_wing_L] = pcl_wing_R(0,k);\n\t\tarray_out[1][k+N_points_body+N_points_wing_L] = pcl_wing_R(1,k);\n\t\tarray_out[2][k+N_points_body+N_points_wing_L] = pcl_wing_R(2,k);\n\t\tarray_out[3][k+N_points_body+N_points_wing_L] = pcl_wing_R(3,k);\n\t\tarray_out[4][k+N_points_body+N_points_wing_L] = pcl_wing_R(4,k);\n\t\tarray_out[5][k+N_points_body+N_points_wing_L] = pcl_wing_R(5,k);\n\t\tarray_out[6][k+N_points_body+N_points_wing_L] = pcl_wing_R(6,k);\n\t}\n\n\treturn array_out;\n\n}\n\nnp::ndarray InitState::ReturnMBody(frames &frame_in) {\n\n\tarma::Mat<double> M_body = frame_in.M_init_single_frame[0];\n\n\tp::tuple shape = p::make_tuple(4,4);\n\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\tnp::ndarray array_out = np::zeros(shape,dtype);\n\n\tif (M_body(3,3)==1.0) {\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tfor (int j=0; j<4; j++) {\n\t\t\t\tarray_out[i][j] = M_body(i,j);\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tfor (int j=0; j<4; j++) {\n\t\t\t\tif (i==j) {\n\t\t\t\t\tarray_out[i][j] = 1.0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tarray_out[i][j] = 0.0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn array_out;\n}\n\nnp::ndarray InitState::ReturnMWingL(frames &frame_in) {\n\n\tarma::Mat<double> M_wing_L = frame_in.M_init_single_frame[1];\n\n\tp::tuple shape = p::make_tuple(4,4);\n\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\tnp::ndarray array_out = np::zeros(shape,dtype);\n\n\tif (M_wing_L(3,3)==1.0) {\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tfor (int j=0; j<4; j++) {\n\t\t\t\tarray_out[i][j] = M_wing_L(i,j);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn array_out;\n}\n\nnp::ndarray InitState::ReturnMWingR(frames &frame_in) {\n\n\tarma::Mat<double> M_wing_R = frame_in.M_init_single_frame[2];\n\n\tp::tuple shape = p::make_tuple(4,4);\n\tnp::dtype dtype = np::dtype::get_builtin<double>();\n\tnp::ndarray array_out = np::zeros(shape,dtype);\n\n\tif (M_wing_R(3,3)==1.0) {\n\t\tfor (int i=0; i<4; i++) {\n\t\t\tfor (int j=0; j<4; j++) {\n\t\t\t\tarray_out[i][j] = M_wing_R(i,j);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn array_out;\n}\n\npcl::PointCloud<pcl::PointXYZ> InitState::Convert_Mat_2_PCL_XYZ(arma::Mat<double> &pcl_mat) {\n\n\t// Convert an armadillo matrix to a PointCloud vector\n\n\tpcl::PointCloud<pcl::PointXYZ> pcl_vec;\n\n\tint N_points = pcl_mat.n_cols;\n\n\tfor (int i=0; i<N_points; i++) {\n\t\tpcl::PointXYZ point;\n\t\tpoint.x = pcl_mat(1,i);\n\t\tpoint.y = pcl_mat(2,i);\n\t\tpoint.z = pcl_mat(3,i);\n\n\t\tpcl_vec.push_back(point);\n\t}\n\n\treturn pcl_vec;\n}\n\narma::Mat<double> InitState::ConvertVectorPCLArma(vector<tuple<int,double,double,double,double,double,double>> &pcl_in) {\n\n\tint N_points = pcl_in.size();\n\n\tarma::Mat<double> pcl_out(7,N_points);\n\n\tfor (int i=0; i<N_points; i++) {\n\t\tpcl_out(0,i) = (double) get<0>(pcl_in[i]);\n\t\tpcl_out(1,i) = get<1>(pcl_in[i]);\n\t\tpcl_out(2,i) = get<2>(pcl_in[i]);\n\t\tpcl_out(3,i) = get<3>(pcl_in[i]);\n\t\tpcl_out(4,i) = get<4>(pcl_in[i]);\n\t\tpcl_out(5,i) = get<5>(pcl_in[i]);\n\t\tpcl_out(6,i) = get<6>(pcl_in[i]);\n\t}\n\n\treturn pcl_out;\n}", "meta": {"hexsha": "19a6c5e510d31fae3b217a9aebbef2fd869fe1de", "size": 47928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FlyTrackApp/find_initial_state.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/find_initial_state.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/find_initial_state.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": 32.493559322, "max_line_length": 170, "alphanum_fraction": 0.6631614088, "num_tokens": 17589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.022629198467576196, "lm_q1q2_score": 0.011137823006612212}}
{"text": "\n/******************************************************************************\n\n  Implementation of the complex propagation technique used in surface\n  reconstruction.\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 COMPLEX_PROPAGATOR_HPP_D90ED351_6A45_4523_85F3_DA99F52B87C2\n#define COMPLEX_PROPAGATOR_HPP_D90ED351_6A45_4523_85F3_DA99F52B87C2\n\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <boost/assert.hpp>\n#include <boost/noncopyable.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"bo/core/raw_image_2d.hpp\"\n#include \"bo/core/mesh.hpp\"\n#include \"bo/core/kdtree.hpp\"\n#include \"bo/math/functions.hpp\"\n#include \"bo/math/pca.hpp\"\n#include \"bo/math/mean.hpp\"\n#include \"bo/distances/distances_3d.hpp\"\n#include \"bo/surfaces/detail/total_propagation.hpp\"\n#include \"bo/surfaces/detail/propagation_result.hpp\"\n#include \"bo/surfaces/detail/arched_strip.hpp\"\n\nnamespace bo {\nnamespace surfaces {\n\ntemplate <typename RealType>\nclass ComplexPropagator: public boost::noncopyable\n{\npublic:\n    typedef ComplexPropagator<RealType> SelfType;\n    typedef boost::shared_ptr<SelfType> Ptr;\n    typedef std::vector<Ptr> Ptrs;\n\n    typedef Vector<RealType, 3> Point3D;\n\n    // Types for input data.\n    typedef std::vector<Point3D> Points3D;\n    typedef boost::shared_ptr<Points3D> Points3DPtr;\n    typedef boost::shared_ptr<const Points3D> Points3DConstPtr;\n    typedef std::vector<Points3DConstPtr> Points3DConstPtrs;\n\n    typedef std::vector<RealType> Weights;\n\n    // Used by factory functions.\n    typedef RawImage2D<RealType> Image2D;\n    typedef bo::Mesh<RealType> Mesh;\n\nprivate:\n    typedef std::pointer_to_binary_function<const Point3D&, const Point3D&, RealType> Metric;\n    typedef KDTree<3, Point3D, std::pointer_to_binary_function<const Point3D&,\n            std::size_t, RealType> > Tree;\n    typedef boost::shared_ptr<Tree> TreePtr;\n    typedef std::vector<TreePtr> TreePtrs;\n\n    typedef detail::TotalPropagation<RealType, Tree> PropagationDirector;\n    typedef detail::PropagationResult<RealType> PropagationResult;\n    typedef typename PropagationResult::PropagatedContour PropagatedContour;\n    typedef boost::shared_ptr<PropagatedContour> PropagatedContourPtr;\n\npublic:\n    // Factory functions. Create an instance of the class from either of the supported\n    // input with the provided parameters.\n    static Ptr create(const Points3D& plane, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius);\n\n    static Ptrs create(const Points3DConstPtrs& planes, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius);\n\n    static Ptr from_mesh(const Mesh& mesh, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius);\n\n    static Ptr from_raw_image(const Image2D& data, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius);\n\n    // A special factory. Creates a set of instances one per given plane. Additionally\n    // passes a set of neighbours with corresponding weights to each instance. These\n    // planes are used later in the calculation of the tangential component of the\n    // propagation, making it dependent of the neighbour planes. This may improve the result.\n    static Ptrs create(const Points3DConstPtrs& planes, const Weights& neighbour_weights,\n        RealType delta_min, RealType delta_max, RealType inertial_weight,\n        RealType centrifugal_weight, RealType tangential_radius);\n\n    // Performs propagation in either one or two steps depending on whether the\n    // contour has a hole.\n    void propagate();\n\n    // Accessor functions to the final contour and algorithm markers. Calling these\n    // functions makes sense only after calling propagate(). If is_aborted() marker\n    // is set to true, the algortihm is most probably stuck (e.g. jumping between two\n    // adjacent points or traversing the cosed contour multiple times).\n    bool is_aborted() const;\n    bool has_hole() const;\n    bool is_closed() const;\n    PropagatedContourPtr contour() const;\n\nprotected:\n    ComplexPropagator(RealType delta_min, RealType delta_max, TreePtr tree_ptr,\n                       const PropagationDirector& director, const Point3D& start_point);\n\n    // Helper function for KDTree instance.\n    static RealType point3D_accessor_(const Point3D& pt, std::size_t k);\n\n    // Helper function creating k-d tree shared_ptr from the given container of points.\n    static TreePtr tree_from_plane_(const Points3D& plane);\n\n    // Calculates neighbours and corresponding weights for the given plane. Uses the\n    // size of the weights container to determine how many planes \"before\" and \"after\"\n    // the current should be considered neighbours.\n    static void populate_neighbours_and_weights_(std::size_t plane_idx,\n            const Points3DConstPtrs& planes, const Weights& neighbour_weights,\n            Points3DConstPtrs& out_neighbours, Weights& out_weights);\n\n    // Calculates plane normal for the given container of samples. The samples are\n    // assumed to lie in a plane. PCA is used to estimate the vector purpendicular to\n    // plane represented by samples.\n    static Point3D get_plane_normal_(const Points3D& plane);\n\n    // Projects each of the given points onto the plane represented by its normal and\n    // center of mass.\n    static Points3DConstPtrs project_neighbour_onto_plane_(const Point3D& center_of_mass,\n            const Point3D& normal, const Points3DConstPtrs& neighbours);\n\n    // Tries performing propagation from the start point to the end point.\n    // Note that end point is not included in result, while start is always included.\n    PropagationResult propagate_(const Point3D& start, const Point3D& end,\n                                 Point3D total_prop, std::size_t max_size);\n\nprivate:\n    // Parameters and options of the propagation algorithm.\n    const RealType delta_min_;\n    const RealType delta_max_;\n    const Metric metric_;\n\n    // Algorithm data and helper obejcts.\n    const TreePtr tree_ptr_;\n    const PropagationDirector propagation_director_;\n    const Point3D start_;\n\n    // Markers and final contour.\n    bool aborted_;\n    bool has_hole_;\n    PropagatedContourPtr contour_;\n};\n\n\n// C-tor.\ntemplate <typename RealType>\nComplexPropagator<RealType>::ComplexPropagator(RealType delta_min,\n                                                 RealType delta_max,\n                                                 TreePtr tree_ptr,\n                                                 const PropagationDirector& director,\n                                                 const Point3D& start_point):\n    delta_min_(delta_min), delta_max_(delta_max),\n    metric_(std::ptr_fun(distances::euclidean_distance<RealType, 3>)),\n    tree_ptr_(tree_ptr),\n    propagation_director_(director),\n    start_(start_point),\n    aborted_(false), has_hole_(false),\n    contour_(boost::make_shared<PropagatedContour>())\n{\n    // If points number is less than 2, propagation cannot be initialized. And\n    // because there is no sense in doing propagation for 0 or 1 points, we throw\n    // an error instead of returning the plane unchanged.\n    if (tree_ptr->size() < 2)\n        throw std::logic_error(\"Cannot run propagation for planes consisting of \"\n                               \"less than 2 vertices.\");\n}\n\n\n// Factories. Note that the sum of inertial and centrifugal weights should be in [0; 1].\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::Ptr ComplexPropagator<RealType>::create(\n        const Points3D& plane, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius)\n{\n    // Build kd-tree from the given points.\n    TreePtr tree_ptr = tree_from_plane_(plane);\n\n    // Create the appropriate propagation director either with or without centrifugal\n    // component.\n    PropagationDirector direction = math::check_small(centrifugal_weight)\n            ? PropagationDirector::create_simple(inertial_weight, tree_ptr,\n                    tangential_radius)\n            : PropagationDirector::create_with_centrifugal(inertial_weight,\n                    centrifugal_weight, tree_ptr, tangential_radius, bo::math::mean(plane));\n\n    // C-tor is declared private, using boost::make_shared gets complicated.\n    Ptr ptr(new SelfType(delta_min, delta_max, tree_ptr, direction, plane.front()));\n    return ptr;\n}\n\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::Ptrs ComplexPropagator<RealType>::create(\n        const Points3DConstPtrs& planes, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius)\n{\n    // Cache values and prepare output container.\n    std::size_t planes_count = planes.size();\n    Ptrs propagators;\n    propagators.reserve(planes_count);\n\n    // Create an instance for each plane.\n    for (std::size_t idx = 0; idx < planes_count; ++idx)\n    {\n        // Create an instance, register neighbours and return.\n        Ptr propagator = create(*(planes[idx]), delta_min, delta_max, inertial_weight,\n                                centrifugal_weight, tangential_radius);\n        propagators.push_back(propagator);\n    }\n\n    return propagators;\n}\n\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::Ptr ComplexPropagator<RealType>::from_mesh(\n        const Mesh& mesh, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius)\n{\n    return\n        create(mesh.get_all_vertices(), delta_min, delta_max, inertial_weight,\n               centrifugal_weight, tangential_radius);\n}\n\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::Ptr ComplexPropagator<RealType>::from_raw_image(\n        const Image2D& data, RealType delta_min, RealType delta_max,\n        RealType inertial_weight, RealType centrifugal_weight, RealType tangential_radius)\n{\n    // Load plane data from an istance of RawImage2D.\n    Points3D plane;\n\n    for (std::size_t row = 0; row < data.height(); ++row)\n        for (std::size_t col = 0; col < data.width(); ++col)\n            if (data(col, row) > 0)\n                plane.push_back(Point3D(RealType(col), RealType(row), RealType(0)));\n\n    return\n        create(plane, delta_min, delta_max, inertial_weight, centrifugal_weight,\n               tangential_radius);\n}\n\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::Ptrs ComplexPropagator<RealType>::create(\n        const Points3DConstPtrs& planes, const Weights& neighbour_weights,\n        RealType delta_min, RealType delta_max, RealType inertial_weight,\n        RealType centrifugal_weight, RealType tangential_radius)\n{\n    // Check neighbours count (in one direction) is not greater than planes count - 1.\n    if (neighbour_weights.size() > planes.size() - 1)\n        throw std::logic_error(\"Neighbours count in one direction exceeds reasonable \"\n                               \"limit.\");\n\n    // Cache values and prepare output container.\n    std::size_t planes_count = planes.size();\n    std::size_t radius = neighbour_weights.size();\n    Ptrs propagators;\n    propagators.reserve(planes_count);\n\n    // Compute neighbours for each plane and create an instance of the class for it.\n    for (std::size_t idx = 0; idx < planes_count; ++idx)\n    {\n        // Cache current plane and prepare output containers.\n        Points3DConstPtr plane = planes[idx];\n\n        Points3DConstPtrs neighbours;\n        neighbours.reserve(2 * radius);\n\n        Weights weights;\n        weights.reserve(2 * radius);\n\n        // Add neighbours and weights to the instantiated containers.\n        populate_neighbours_and_weights_(idx, planes, neighbour_weights, neighbours, weights);\n\n        // Cache main plane origin and normal.\n        Point3D center_of_mass = bo::math::mean(*plane);\n        Point3D norm = get_plane_normal_(*plane);\n\n        // Project all neighbours to the current plane.\n        Points3DConstPtrs neighbour_projs = project_neighbour_onto_plane_(center_of_mass,\n                norm, neighbours);\n        neighbour_projs.reserve(neighbours.size());\n\n        // Compute k-d tree for the current plane.\n        TreePtr main_tree_ptr = tree_from_plane_(*plane);\n\n        // Compute k-d trees for projected neighbour planes.\n        TreePtrs neighbour_trees;\n        neighbour_trees.reserve(neighbour_projs.size());\n        for (typename Points3DConstPtrs::const_iterator plane_it =\n             neighbour_projs.begin(); plane_it != neighbour_projs.end(); ++plane_it)\n            neighbour_trees.push_back(tree_from_plane_(**plane_it));\n\n        // Create the appropriate propagation director with neighbour tangential\n        // componentseither and with or without centrifugal component.\n        PropagationDirector direction = math::check_small(centrifugal_weight)\n                ? PropagationDirector::create_with_neighbours(inertial_weight,\n                        main_tree_ptr, tangential_radius, neighbour_trees, weights)\n                : PropagationDirector::create_with_neighbours_and_centrifugal(\n                        inertial_weight, centrifugal_weight, main_tree_ptr, tangential_radius,\n                        center_of_mass, neighbour_trees, weights);\n\n        // C-tor is declared private, using boost::make_shared gets complicated.\n        Ptr ptr(new SelfType(delta_min, delta_max, main_tree_ptr, direction, plane->front()));\n\n        propagators.push_back(ptr);\n    }\n\n    return propagators;\n}\n\n\n// Public control functions.\ntemplate <typename RealType>\nvoid ComplexPropagator<RealType>::propagate()\n{\n    // Choose initial point and initial propagation. It solely consists of the\n    // tangential component, since inertial cannot be defined.\n    Point3D initial_prop = propagation_director_.initial(start_);\n\n    // Run propagation. It may bump into a hole or return a circuit.\n    PropagationResult attempt1 = propagate_(start_, start_, initial_prop, 1000);\n\n    // If the hole was detected, run propagation in a different direction.\n    PropagationResult attempt2;\n    if (attempt1.HasHole)\n        attempt2 = propagate_(start_, attempt1.Points.back(), - initial_prop, 1000);\n\n    // Glue propagation results together.\n    contour_->reserve(attempt1.Points.size() + attempt2.Points.size());\n    for (typename PropagatedContour::const_reverse_iterator rit = attempt2.Points.rbegin();\n         rit != attempt2.Points.rend(); ++rit)\n        contour_->push_back(*rit);\n    for (typename PropagatedContour::const_iterator it = attempt1.Points.begin() + 1;\n         it != attempt1.Points.end(); ++it)\n        contour_->push_back(*it);\n\n    // Set markers.\n    aborted_ = attempt1.Aborted || attempt2.Aborted;\n    has_hole_ = attempt1.HasHole;\n}\n\ntemplate <typename RealType> inline\nbool ComplexPropagator<RealType>::is_aborted() const\n{\n    return aborted_;\n}\n\ntemplate <typename RealType> inline\nbool ComplexPropagator<RealType>::has_hole() const\n{\n    return has_hole_;\n}\n\ntemplate <typename RealType> inline\nbool ComplexPropagator<RealType>::is_closed() const\n{\n    return !(this->has_hole());\n}\n\ntemplate <typename RealType> inline\ntypename ComplexPropagator<RealType>::PropagatedContourPtr\nComplexPropagator<RealType>::contour() const\n{\n    return contour_;\n}\n\n\n// Private static helper functions.\ntemplate <typename RealType> inline\nRealType ComplexPropagator<RealType>::point3D_accessor_(const Point3D &pt, std::size_t k)\n{\n    return pt[k];\n}\n\ntemplate <typename RealType> inline\ntypename ComplexPropagator<RealType>::TreePtr\nComplexPropagator<RealType>::tree_from_plane_(const Points3D& plane)\n{\n    // Build kd-tree from the given points.\n    // TODO: provide k-d tree with current metric?\n    TreePtr tree_ptr = boost::make_shared<Tree>(plane.begin(), plane.end(),\n                                                std::ptr_fun(point3D_accessor_));\n    return tree_ptr;\n}\n\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::Point3D\nComplexPropagator<RealType>::get_plane_normal_(const Points3D& plane)\n{\n    // Employ PCA to estimate plane normal.\n    typedef math::PCA<RealType, 3> PCAEngine;\n    typedef typename PCAEngine::Result PCAResult;\n    PCAEngine pca;\n    PCAResult result = pca(plane);\n    Point3D normal = result.template get<1>()[0];\n\n    return normal;\n}\n\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::Points3DConstPtrs\nComplexPropagator<RealType>::project_neighbour_onto_plane_(const Point3D& center_of_mass,\n        const Point3D& normal, const Points3DConstPtrs& neighbours)\n{\n    // Prepare output container.\n    Points3DConstPtrs neighbour_projs;\n    neighbour_projs.reserve(neighbours.size());\n\n    // Project all neighbours to the current plane.\n    for (typename Points3DConstPtrs::const_iterator neighbour =\n         neighbours.begin(); neighbour != neighbours.end(); ++neighbour)\n    {\n        // Prepare container for the projected plane.\n        Points3DPtr plane_proj = boost::make_shared<Points3D>();\n        plane_proj->reserve((*neighbour)->size());\n\n        // Project all points from the neighbour to the current plane.\n        for (typename Points3D::const_iterator point_it = (*neighbour)->begin();\n             point_it != (*neighbour)->end(); ++point_it)\n        {\n            plane_proj->push_back(distances::project_point_onto_plane(*point_it,\n                    center_of_mass, normal));\n        }\n\n        neighbour_projs.push_back(plane_proj);\n    }\n\n    return neighbour_projs;\n}\n\ntemplate <typename RealType>\nvoid ComplexPropagator<RealType>::populate_neighbours_and_weights_(std::size_t plane_idx,\n        const Points3DConstPtrs& planes, const Weights& neighbour_weights,\n        Points3DConstPtrs& out_neighbours, Weights& out_weights)\n{\n    std::size_t planes_count = planes.size();\n    std::size_t radius = neighbour_weights.size();\n\n    // Try add neighbours before the current idx. We add radius items at most,\n    // but less if no neighbours are available (close to container front).\n    std::size_t neighbour_idx = plane_idx - 1;\n    std::size_t added_count = 0;\n    std::size_t maxval = std::size_t(-1); // dirty hack to workaround int behaviour for size_t.\n    while ((neighbour_idx < maxval) && (added_count < radius))\n    {\n        out_neighbours.push_back(planes[neighbour_idx]);\n        out_weights.push_back(neighbour_weights[added_count]);\n        ++added_count;\n        --neighbour_idx;\n    }\n\n    // Try add neighbours after the current idx. We add radius items at most,\n    // but less if no neighbours are available (close to container end).\n    neighbour_idx = plane_idx + 1;\n    added_count = 0;\n    while ((neighbour_idx < planes_count) && (added_count < radius))\n    {\n        out_neighbours.push_back(planes[neighbour_idx]);\n        out_weights.push_back(neighbour_weights[added_count]);\n        ++added_count;\n        ++neighbour_idx;\n    }\n\n    BOOST_ASSERT((out_neighbours.size() == out_weights.size()) && \"Weights quantity doesn't\"\n                 \"correspond to planes number.\");\n}\n\ntemplate <typename RealType>\ntypename ComplexPropagator<RealType>::PropagationResult\nComplexPropagator<RealType>::propagate_(const Point3D& start, const Point3D& end,\n                                         Point3D total_prop, std::size_t max_size)\n{\n    typedef detail::ArchedStrip<RealType, 3> ArchedStrip;\n\n    PropagationResult retvalue;\n    retvalue.Points.push_back(start);\n\n    // Flag for so-called \"smooth-ending\". It is necessary to keep the distance\n    // between the points in the end phase as close to delta_min as possible,\n    // despite a delta_max point has been already found.\n    bool end_detected = false;\n\n    Point3D current = start;\n    do\n    {\n        // Restrict total length (to prevent looping).\n        if (retvalue.Points.size() > max_size)\n        {\n            retvalue.Aborted = true;\n            break;\n        }\n\n        // Search for the propagation candidate. It should lie on the arced strip\n        // bounded by delta_min and delta_max circumferences and a plane containing\n        // current point and normal to propagation vector.\n        Point3D phantom_candidate = current + total_prop * delta_min_;\n\n        // TODO: get rid of max radius.\n        std::pair<typename Tree::const_iterator, RealType> candidate_data =\n                tree_ptr_->find_nearest_if(phantom_candidate, delta_max_,\n                    ArchedStrip(current, delta_min_, delta_max_, total_prop, metric_));\n        RealType candidate_distance = candidate_data.second;\n        Point3D candidate = *(candidate_data.first);\n\n        // Check if we bump into a hole.\n        if (candidate_distance >= delta_max_)\n        {\n            retvalue.HasHole = true;\n            break;\n        }\n\n        // Check if the candidate \"sees\" the end point \"in front\".\n        if (!end_detected)\n        {\n            retvalue.Points.push_back(candidate);\n            if ((delta_max_ >= metric_(end, candidate)) &&\n                (total_prop * (end - candidate)) > 0)\n                end_detected = true;\n        }\n        else\n        {\n            RealType cur_dist = (end - retvalue.Points.back()).euclidean_norm();\n            RealType candidate_dist1 = (candidate - retvalue.Points.back()).euclidean_norm();\n            RealType candidate_dist2 = (end - candidate).euclidean_norm();\n\n            if (delta_min_ > metric_(end, candidate))\n            {\n                retvalue.Points.push_back(candidate);\n                candidate = end;\n            }\n            else if ((cur_dist > candidate_dist1) && (cur_dist > candidate_dist2))\n            {\n                retvalue.Points.push_back(candidate);\n            }\n            else\n            {\n                candidate = end;\n            }\n        }\n\n        // Update algortihm's state.\n        Point3D previous = current;\n        current = candidate;\n        total_prop = propagation_director_.next(current, previous);\n\n    } while (current != end);\n\n    return retvalue;\n}\n\n} // namespace surfaces\n} // namespace bo\n\n#endif // COMPLEX_PROPAGATOR_HPP_D90ED351_6A45_4523_85F3_DA99F52B87C2\n", "meta": {"hexsha": "4c63751832ebd2bd07ab616bc28299936b63a66f", "size": 23701, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/surfaces/complex_propagator.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/surfaces/complex_propagator.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/surfaces/complex_propagator.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": 40.3078231293, "max_line_length": 95, "alphanum_fraction": 0.6969748112, "num_tokens": 5300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.022977368237414256, "lm_q1q2_score": 0.01112977956330202}}
{"text": "/*\n * KDataBufferImp.cpp\n *\n *  Created on: 2013-2-4\n *      Author: fasiondog\n */\n\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/lambda/lambda.hpp>\n#include \"KDataBufferImp.h\"\n#include \"utilities/util.h\"\n\nnamespace hku {\n\nKDataBufferImp::KDataBufferImp(): KDataImp() {\n\n}\n\n\nKDataBufferImp::\nKDataBufferImp(const Stock& stock, const KQuery& query)\n: KDataImp(stock, query) {\n    if (m_stock.isNull() || empty()) {\n        return;\n    }\n\n    m_buffer = m_stock.getKRecordList(startPos(), endPos(), query.kType());\n\n    //日线以上不支持复权\n    if (query.recoverType() == KQuery::NO_RECOVER\n            || query.kType() == KQuery::WEEK\n            || query.kType() == KQuery::MONTH\n            || query.kType() == KQuery::QUARTER\n            || query.kType() == KQuery::HALFYEAR\n            || query.kType() == KQuery::YEAR) {\n        return;\n    }\n\n    switch(query.recoverType()) {\n    case KQuery::NO_RECOVER:\n        //do nothing\n        break;\n\n    case KQuery::FORWARD:\n        _recoverForward();\n        break;\n\n    case KQuery::BACKWARD:\n        _recoverBackward();\n        break;\n\n    case KQuery::EQUAL_FORWARD:\n        _recoverEqualForward();\n        break;\n\n    case KQuery::EQUAL_BACKWARD:\n        _recoverEqualBackward();\n        break;\n\n    default:\n        HKU_ERROR(\"Invalid RecvoerType! [KDataBufferImp::KDataBufferImp]\");\n        return;\n    }\n}\n\n\nKDataBufferImp::~KDataBufferImp() {\n\n}\n\n\nsize_t KDataBufferImp::getPos(const Datetime& datetime) const {\n    KRecordList::const_iterator iter;\n    KRecord comp_record;\n    comp_record.datetime = datetime;\n    boost::function<bool(const KRecord&, const KRecord&)> f =\n            boost::bind(&KRecord::datetime, _1) <\n            boost::bind(&KRecord::datetime, _2);\n\n    iter = lower_bound(m_buffer.begin(), m_buffer.end(), comp_record, f);\n    if (iter == m_buffer.end() || iter->datetime != datetime) {\n        return Null<size_t>();\n    }\n\n    return (iter - m_buffer.begin());\n}\n\n\n/******************************************************************************\n * 前复权公式:复权后价格＝[(复权前价格-现金红利)＋配(新)股价格×流通股份变动比例]÷(1＋流通股份变动比例)\n * 向前复权指以除权后的股价为基准（即除权后的股价不变），将除权前的股价降下来。\n * 复权计算时首先从上市日开始，逐日向后判断，遇到除权日，则将上市日到除权日之间（不包括除权日）的\n * 全部股价通过复权计算降下来；然后再继续向后判断，遇到下一个除权日，则再次将上市日到该除权日之间\n * （不包括除权日）的全部股价通过复权计算降下来。\n *****************************************************************************/\nvoid KDataBufferImp::_recoverForward() {\n    size_t total = m_buffer.size();\n    if (total == 0) {\n        return;\n    }\n\n    bd::date start_date = m_buffer.front().datetime.date();\n    bd::date end_date = m_buffer.back().datetime.date() + bd::days(1);\n    StockWeightList weightList = m_stock.getWeight(start_date, end_date);\n    StockWeightList::const_iterator weightIter = weightList.begin();\n    StockWeightList::const_iterator pre_weightIter = weightIter;\n\n    size_t pre_pos = 0;\n    for (; weightIter != weightList.end(); ++weightIter) {\n        size_t i = pre_pos;\n        while (i < total && m_buffer[i].datetime < weightIter->datetime()) {\n            i++;\n        }\n        pre_pos = i;  //除权日\n\n        //计算流通股份变动比例\n        price_t change = 0.0;\n        bool flag = false;\n        if (weightIter != weightList.begin()) {\n            pre_weightIter = weightIter - 1;\n            if (pre_weightIter->freeCount() != 0.0) {\n                change = (weightIter->freeCount()\n                       - pre_weightIter->freeCount())\n                       / pre_weightIter->freeCount();\n                flag = true;\n            }\n        }\n        if (!flag){\n            change = 0.1 * (weightIter->countAsGift()\n                           + weightIter->countForSell()\n                           + weightIter->increasement());\n        }\n\n        price_t denominator = 1.0 + change; //分母 = (1+流通股份变动比例)\n        price_t temp = weightIter->priceForSell() * change\n                     - 0.1 * weightIter->bonus();\n\n        for (i = 0; i < pre_pos; ++i) {\n            m_buffer[i].openPrice = roundEx((m_buffer[i].openPrice + temp) / denominator, m_stock.precision());\n            m_buffer[i].highPrice = roundEx((m_buffer[i].highPrice + temp) / denominator, m_stock.precision());\n            m_buffer[i].lowPrice = roundEx((m_buffer[i].lowPrice + temp) / denominator, m_stock.precision());\n            m_buffer[i].closePrice = roundEx((m_buffer[i].closePrice + temp) / denominator, m_stock.precision());\n        }\n    }\n}\n\n/******************************************************************************\n * 后复权公式:复权后价格＝复权前价格×(1＋流通股份变动比例)-配(新)股价格×流通股份变动比例＋现金红利\n * 向后复权指以除权前的股价为基准（即除权前的股价不变），将除权后的股价升上去。复权计算时首先从最新日开始，\n * 逐日向前判断，遇到除权日，则将除权日到最新日之间（包括除权日）的全部股价通过复权计算升上去；然后再继续\n * 向前判断，遇到下一个除权日，则再次将除权日到最新日之间（包括除权日）的全部股价通过复权计算升上去。\n *****************************************************************************/\nvoid KDataBufferImp::_recoverBackward() {\n    size_t total = m_buffer.size();\n    if (0 == total) {\n        return;\n    }\n\n    bd::date start_date = m_buffer.front().datetime.date();\n    bd::date end_date = m_buffer.back().datetime.date() + bd::days(1);\n    StockWeightList weightList = m_stock.getWeight(start_date, end_date);\n    StockWeightList::const_reverse_iterator weightIter = weightList.rbegin();\n    StockWeightList::const_reverse_iterator pre_weightIter;\n\n    size_t pre_pos = total - 1;\n    for (; weightIter != weightList.rend(); ++weightIter) {\n        size_t i = pre_pos;\n        while (i > 0 && m_buffer[i].datetime > weightIter->datetime()) {\n            i--;\n        }\n        pre_pos = i;\n\n        //流通股份变动比例\n        price_t change = 0.0;\n        bool flag = false;\n        pre_weightIter = weightIter + 1;\n        if (pre_weightIter != weightList.rend()\n                && pre_weightIter->freeCount() != 0.0) {\n            change = (weightIter->freeCount() - pre_weightIter->freeCount())\n                    / pre_weightIter->freeCount();\n            flag = true;\n        }\n        if (!flag){\n            change = 0.1 * (weightIter->countAsGift()\n                           + weightIter->countForSell()\n                           + weightIter->increasement());\n        }\n\n        price_t denominator = 1.0 + change; //(1+流通股份变动比例)\n        price_t temp = 0.1 * weightIter->bonus()\n                     - weightIter->priceForSell() * change;;\n\n        for (i = pre_pos; i < total; ++i) {\n            m_buffer[i].openPrice = roundEx(m_buffer[i].openPrice * denominator + temp, m_stock.precision());\n            m_buffer[i].highPrice = roundEx(m_buffer[i].highPrice * denominator + temp, m_stock.precision());\n            m_buffer[i].lowPrice = roundEx(m_buffer[i].lowPrice * denominator + temp, m_stock.precision());\n            m_buffer[i].closePrice = roundEx(m_buffer[i].closePrice * denominator + temp, m_stock.precision());\n        }\n    }\n}\n\n/******************************************************************************\n * 等比前复权公式:复权后价格＝复权前价格*复权率\n * 复权率＝｛[(股权登记日收盘价-现金红利)＋配(新)股价格×流通股份变动比例]÷(1＋流通股份变动比例)｝÷股权登记日收盘价\n * 向前复权指以除权后的股价为基准（即除权后的股价不变），将除权前的股价降下来。\n * 复权计算时首先从上市日开始，逐日向后判断，遇到除权日，则将上市日到除权日之间（不包括除权日）的\n * 全部股价通过复权计算降下来；然后再继续向后判断，遇到下一个除权日，则再次将上市日到该除权日之间\n * （不包括除权日）的全部股价通过复权计算降下来。\n *****************************************************************************/\nvoid KDataBufferImp::_recoverEqualForward() {\n    size_t total = m_buffer.size();\n    if (0 == total) {\n        return;\n    }\n\n    bd::date start_date = m_buffer.front().datetime.date();\n    bd::date end_date = m_buffer.back().datetime.date() + bd::days(1);\n    StockWeightList weightList = m_stock.getWeight(start_date, end_date);\n    if (weightList.empty()) {\n        return;\n    }\n\n    KRecordList kdata = m_buffer; //防止同一天两条权息记录\n    StockWeightList::const_iterator weightIter = weightList.begin();\n    StockWeightList::const_iterator pre_weightIter;\n    size_t pre_pos = 0;\n    for (; weightIter != weightList.end(); ++weightIter) {\n        size_t i = pre_pos;\n        while (i < total && m_buffer[i].datetime < weightIter->datetime()) {\n            i++;\n        }\n        pre_pos = i; //除权日\n\n        //股权登记日（即除权日的前一天数据）收盘价\n        if (pre_pos == 0) {\n            continue;\n        }\n        price_t closePrice = kdata[pre_pos - 1].closePrice;\n        if (closePrice == 0.0) {\n            continue;  //除零保护\n        }\n\n        //流通股份变动比例\n        price_t change = 0.0;\n        bool flag = false;\n        if (weightIter != weightList.begin()) {\n            pre_weightIter = weightIter - 1;\n            if (pre_weightIter->freeCount() != 0.0) {\n                change = (weightIter->freeCount() - pre_weightIter->freeCount())\n                        / pre_weightIter->freeCount();\n                flag = true;\n            }\n        }\n        if (!flag) {\n            change = 0.1 * (weightIter->countAsGift()\n                            + weightIter->countForSell()\n                            + weightIter->increasement());\n        }\n\n        price_t denominator = 1.0 + change; //(1+流通股份变动比例)\n        price_t temp = weightIter->priceForSell() * change\n                     -  0.1 * weightIter->bonus();\n\n        price_t k = (closePrice + temp) / (denominator * closePrice);\n\n        for (i = 0; i < pre_pos; ++i) {\n            m_buffer[i].openPrice = roundEx(k * m_buffer[i].openPrice, m_stock.precision());\n            m_buffer[i].highPrice = roundEx(k * m_buffer[i].highPrice, m_stock.precision());\n            m_buffer[i].lowPrice = roundEx(k * m_buffer[i].lowPrice, m_stock.precision());\n            m_buffer[i].closePrice = roundEx(k * m_buffer[i].closePrice, m_stock.precision());\n        }\n    }\n}\n\n/******************************************************************************\n * 等比后复权公式:复权后价格＝复权前价格÷复权率\n * 复权率＝｛[(股权登记日收盘价-现金红利)＋配(新)股价格×流通股份变动比例]÷(1＋流通股份变动比例)｝÷股权登记日收盘价\n * 向后复权指以除权前的股价为基准（即除权前的股价不变），将除权后的股价升上去。复权计算时首先从最新日开始，\n * 逐日向前判断，遇到除权日，则将除权日到最新日之间（包括除权日）的全部股价通过复权计算升上去；然后再继续\n * 向前判断，遇到下一个除权日，则再次将除权日到最新日之间（包括除权日）的全部股价通过复权计算升上去。\n *****************************************************************************/\nvoid KDataBufferImp::_recoverEqualBackward() {\n    size_t total = m_buffer.size();\n    if (0 == total) {\n        return;\n    }\n\n    bd::date start_date = m_buffer.front().datetime.date();\n    bd::date end_date = m_buffer.back().datetime.date() + bd::days(1);\n    StockWeightList weightList = m_stock.getWeight(start_date, end_date);\n    StockWeightList::const_reverse_iterator weightIter = weightList.rbegin();\n    StockWeightList::const_reverse_iterator pre_weightIter;\n\n    size_t pre_pos = total - 1;\n    for (; weightIter != weightList.rend(); ++weightIter) {\n        size_t i = pre_pos;\n        while (i > 0 && m_buffer[i].datetime > weightIter->datetime()) {\n            i--;\n        }\n        pre_pos = i; //除权日\n\n        //股权登记日（即除权日的前一天数据）收盘价\n        if (pre_pos == 0){\n            continue;\n        }\n        price_t closePrice = m_buffer[pre_pos - 1].closePrice;\n\n        //流通股份变动比例\n        price_t change = 0.0;\n        bool flag = false;\n        pre_weightIter = weightIter + 1;\n        if (pre_weightIter != weightList.rend()\n                && pre_weightIter->freeCount() != 0.0) {\n            change = (weightIter->freeCount() - pre_weightIter->freeCount())\n                    / pre_weightIter->freeCount();\n            flag = true;\n        }\n        if (!flag) {\n            change = 0.1 * (weightIter->countAsGift()\n                           + weightIter->countForSell()\n                           + weightIter->increasement());\n        }\n\n        price_t denominator = 1.0 + change; //(1+流通股份变动比例)\n        price_t temp = closePrice + weightIter->priceForSell() * change\n                     - 0.1 * weightIter->bonus();\n        if (temp == 0.0) {\n            continue;\n        }\n        price_t k =  (denominator * closePrice) / temp;\n\n        for (i = pre_pos; i < total; ++i) {\n            m_buffer[i].openPrice = roundEx(k * m_buffer[i].openPrice, m_stock.precision());\n            m_buffer[i].highPrice = roundEx(k * m_buffer[i].highPrice, m_stock.precision());\n            m_buffer[i].lowPrice =  roundEx(k * m_buffer[i].lowPrice, m_stock.precision());\n            m_buffer[i].closePrice = roundEx(k * m_buffer[i].closePrice, m_stock.precision());\n        }\n    }\n}\n\n\n} /* namespace hku */\n", "meta": {"hexsha": "616ffb5c79e1062c74dda3ae9b4ec4f890e80989", "size": 12090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/hikyuu/KDataBufferImp.cpp", "max_stars_repo_name": "koktf23/hikyuu", "max_stars_repo_head_hexsha": "7a728592465b5789dca381f75171fc5591e34671", "max_stars_repo_licenses": ["MIT"], "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/hikyuu/KDataBufferImp.cpp", "max_issues_repo_name": "koktf23/hikyuu", "max_issues_repo_head_hexsha": "7a728592465b5789dca381f75171fc5591e34671", "max_issues_repo_licenses": ["MIT"], "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/hikyuu/KDataBufferImp.cpp", "max_forks_repo_name": "koktf23/hikyuu", "max_forks_repo_head_hexsha": "7a728592465b5789dca381f75171fc5591e34671", "max_forks_repo_licenses": ["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.1453488372, "max_line_length": 113, "alphanum_fraction": 0.5544251447, "num_tokens": 3766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.02976009168708593, "lm_q1q2_score": 0.01112657876527038}}
{"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 HISTOGRAM_HH\n#define HISTOGRAM_HH\n\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <array>\n#define BOOST_DISABLE_ASSERTS\n#include <boost/multi_array.hpp>\n\n#include <boost/type_traits.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/int.hpp>\n\n#include <boost/python/object.hpp>\n\n//\n// This is a generic multidimensional histogram type\n//\n\ntemplate <class ValueType, class CountType, size_t Dim>\nclass Histogram\n{\npublic:\n    typedef std::array<ValueType,Dim> point_t; // point type to be\n                                               // histogrammed\n    typedef std::array<size_t,Dim> bin_t;      // bin type\n\n    typedef boost::multi_array<CountType,Dim> count_t; // the histogram itself\n\n    typedef boost::mpl::int_<Dim> dim;\n    typedef CountType count_type;\n    typedef ValueType value_type;\n\n    // floating point type to calculate the mean\n    typedef typename boost::mpl::if_<boost::is_floating_point<ValueType>,\n                                     ValueType, double>::type mean_t;\n\n    Histogram(const std::array<std::vector<ValueType>, Dim>& bins):\n        _bins(bins)\n    {\n        bin_t new_shape;\n        for (size_t j = 0; j < Dim; ++j)\n        {\n            if (_bins[j].size() < 1)\n                throw std::range_error(\"invalid bin edge number < 1!\");\n\n            _data_range[j] = std::make_pair(0, 0);\n            value_type delta = _bins[j][1] - _bins[j][0];\n\n            if (_bins[j].size() == 2)\n            {\n                _data_range[j] = std::make_pair(_bins[j][0], _bins[j][0]);\n                delta = _bins[j][1];\n                _const_width[j] = true;\n            }\n            else\n            {\n                // detect whether the given bins are of constant width, for faster\n                // binning\n                _const_width[j] = true;\n                for (size_t i = 2; i < _bins[j].size(); ++i)\n                {\n                    value_type d = _bins[j][i] - _bins[j][i-1];\n                    if (delta != d)\n                        _const_width[j] = false;\n                }\n\n                if (_const_width[j])\n                    _data_range[j] = std::make_pair(_bins[j].front(),\n                                                    _bins[j].back());\n            }\n            if (delta == 0)\n                throw std::range_error(\"invalid bin size of zero!\");\n\n            new_shape[j] = _bins[j].size() - 1;\n        }\n        _counts.resize(new_shape);\n    }\n\n    void PutValue(const point_t& v, const CountType& weight = 1)\n    {\n        bin_t bin;\n        for (size_t i = 0; i < Dim; ++i)\n        {\n            if (_const_width[i])\n            {\n                value_type delta;\n\n                if (_data_range[i].first == _data_range[i].second)\n                {\n                    delta = _bins[i][1];\n\n                    if (v[i] < _data_range[i].first)\n                        return; // out of bounds\n                }\n                else\n                {\n                    delta = _bins[i][1] - _bins[i][0];\n\n                    if (v[i] < _data_range[i].first ||\n                        v[i] >= _data_range[i].second)\n                        return; // out of bounds\n                }\n\n                bin[i] = size_t((v[i] - _data_range[i].first) / delta);\n                if (bin[i] >= _counts.shape()[i]) // modify shape\n                {\n                    bin_t new_shape;\n                    for (size_t j = 0; j < Dim; ++j)\n                        new_shape[j] = _counts.shape()[j];\n                    new_shape[i] = bin[i] + 1;\n                    _counts.resize(new_shape);\n                    while (_bins[i].size() < new_shape[i] + 1)\n                        _bins[i].push_back(_bins[i].back() + delta);\n                }\n            }\n            else // arbitrary bins widths. do a binary search\n            {\n                std::vector<ValueType>& bins = _bins[i];\n                typeof(bins.begin()) iter = upper_bound(bins.begin(),\n                                                        bins.end(), v[i]);\n                if (iter == bins.end())\n                {\n                    return;  // falls off from last bin, do not count\n                }\n                else\n                {\n                    bin[i] = iter - bins.begin();\n                    if (bin[i] == 0)\n                        return; // falls off from fist bin, do not count\n                    else\n                       --bin[i];\n                }\n            }\n        }\n        _counts(bin) += weight;\n    }\n\n    boost::multi_array<CountType,Dim>& GetArray() { return _counts; }\n\n    std::array<std::pair<ValueType,ValueType>,Dim>& GetDataRange()\n    { return _data_range; }\n\n    std::array<std::vector<ValueType>, Dim>& GetBins() { return _bins; }\n\nprotected:\n    boost::multi_array<CountType,Dim> _counts;\n    std::array<std::vector<ValueType>, Dim> _bins;\n    std::array<std::pair<ValueType,ValueType>,Dim> _data_range;\n    std::array<bool,Dim> _const_width;\n};\n\n\n// This class will encapsulate a histogram, and atomically sum it to a given\n// resulting histogram (which is shared among all copies) after it is\n// destructed, or when the Gather() member function is called. This enables, for\n// instance, a histogram to be built in parallel.\n\ntemplate <class Histogram>\nclass SharedHistogram: public Histogram\n{\npublic:\n\n    SharedHistogram(Histogram& hist): Histogram(hist), _sum(&hist) {}\n    ~SharedHistogram()\n    {\n        Gather();\n    }\n\n    void Gather()\n    {\n        if (_sum != 0)\n        {\n            #pragma omp critical\n            {\n                typename Histogram::bin_t idx;\n\n                typename Histogram::bin_t shape;\n                for (size_t i = 0; i <  this->_counts.num_dimensions(); ++i)\n                    shape[i] = std::max(this->_counts.shape()[i],\n                                        _sum->GetArray().shape()[i]);\n                _sum->GetArray().resize(shape);\n                for (size_t i = 0; i < this->_counts.num_elements(); ++i)\n                {\n                    size_t offset = 1;\n                    for (size_t j = 0; j < this->_counts.num_dimensions(); ++j)\n                    {\n                        size_t L = this->_counts.shape()[j];\n                        idx[j] = ((i / offset) % L);\n                        offset *= L;\n                    }\n                    _sum->GetArray()(idx) += this->_counts(idx);\n                }\n                for (int i = 0; i < Histogram::dim::value; ++i)\n                {\n                    if (_sum->GetBins()[i].size() < this->_bins[i].size())\n                        _sum->GetBins()[i] = this->_bins[i];\n                }\n            }\n            _sum = 0;\n        }\n    }\nprivate:\n    Histogram* _sum;\n};\n\n\n//\n// useful functions to get the the mean and standard deviations from simple\n// map-based, non-binned histograms. Not to be used with the above type.\n//\n\n// gets the mean value of a histogram\ntemplate <class Map>\ndouble GetMapMean (const Map &m)\n{\n    int total = 0;\n    double mean = 0;\n    for (typeof(m.begin()) iter = m.begin(); iter != m.end(); iter++)\n    {\n        mean += double(iter->first * iter->second);\n        total += iter->second;\n    }\n\n    return (total > 0)?mean/total:0.0;\n}\n\n// gets the standard deviation of a histogram\ntemplate <class Map>\ndouble GetMapDeviation (const Map &m, double avg)\n{\n    double dev = 0.0;\n    int total = 0;\n    for (typeof(m.begin()) iter = m.begin(); iter != m.end(); iter++)\n    {\n        dev += double( (iter->first - avg) *\n                       (iter->first - avg) * iter->second);\n        total += iter->second;\n    }\n    return (total > 1)?sqrt(dev/(total-1)):0.0;\n}\n\n#endif //HISTOGRAM_HH\n", "meta": {"hexsha": "42fc9b87c534a0663a388727cfd812bb7f16f5a5", "size": 8468, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/histogram.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/histogram.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/histogram.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": 32.320610687, "max_line_length": 82, "alphanum_fraction": 0.5038970241, "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.02333076889336661, "lm_q1q2_score": 0.011118969698247924}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <optional>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/DataBox/PrefixHelpers.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"DataStructures/VariablesTag.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Domain/TagsTimeDependent.hpp\"\n#include \"Evolution/BoundaryCorrectionTags.hpp\"\n#include \"Evolution/DgSubcell/NeighborData.hpp\"\n#include \"Evolution/DgSubcell/Projection.hpp\"\n#include \"Evolution/DgSubcell/Reconstruction.hpp\"\n#include \"Evolution/DgSubcell/Tags/Mesh.hpp\"\n#include \"Evolution/DgSubcell/Tags/NeighborData.hpp\"\n#include \"Evolution/DgSubcell/Tags/OnSubcellFaces.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Actions/NormalCovectorAndMagnitude.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Actions/PackageDataImpl.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryCorrections/BoundaryCorrection.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryCorrections/Factory.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/FiniteDifference/Reconstructor.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/FiniteDifference/Tag.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/Subcell/ComputeFluxes.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/System.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Tags.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"PointwiseFunctions/Hydro/Tags.hpp\"\n#include \"Utilities/FakeVirtual.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace grmhd::ValenciaDivClean::subcell {\n/*!\n * \\brief On elements using DG, reconstructs the interface data from a\n * neighboring element doing subcell.\n *\n * The neighbor's packaged data needed by the boundary correction is computed\n * and returned so that it can be used for solving the Riemann problem on the\n * interfaces.\n *\n * Note that for strict conservation the Riemann solve should be done on the\n * subcells, with the correction being projected back to the DG interface.\n * However, in practice such strict conservation doesn't seem to be necessary\n * and can be explained by that we only need strict conservation at shocks, and\n * if one element is doing DG, then we aren't at a shock.\n */\nstruct NeighborPackagedData {\n  template <typename DbTagsList>\n  static FixedHashMap<\n      maximum_number_of_neighbors(3), std::pair<Direction<3>, ElementId<3>>,\n      std::vector<double>, boost::hash<std::pair<Direction<3>, ElementId<3>>>>\n  apply(const db::DataBox<DbTagsList>& box,\n        const std::vector<std::pair<Direction<3>, ElementId<3>>>&\n            mortars_to_reconstruct_to) {\n    using evolved_vars_tag = typename System::variables_tag;\n    using evolved_vars_tags = typename evolved_vars_tag::tags_list;\n    using prim_tags = typename System::primitive_variables_tag::tags_list;\n    using recons_prim_tags = tmpl::push_back<\n        prim_tags,\n        hydro::Tags::LorentzFactorTimesSpatialVelocity<DataVector, 3>>;\n    using fluxes_tags = db::wrap_tags_in<::Tags::Flux, evolved_vars_tags,\n                                         tmpl::size_t<3>, Frame::Inertial>;\n\n    ASSERT(not db::get<domain::Tags::MeshVelocity<3>>(box).has_value(),\n           \"Haven't yet added support for moving mesh to DG-subcell. This \"\n           \"should be easy to generalize, but we will want to consider \"\n           \"storing the mesh velocity on the faces instead of \"\n           \"re-slicing/projecting.\");\n\n    FixedHashMap<maximum_number_of_neighbors(3),\n                 std::pair<Direction<3>, ElementId<3>>, std::vector<double>,\n                 boost::hash<std::pair<Direction<3>, ElementId<3>>>>\n        nhbr_package_data{};\n\n    const auto& nhbr_subcell_data =\n        db::get<evolution::dg::subcell::Tags::\n                    NeighborDataForReconstructionAndRdmpTci<3>>(box);\n    const Mesh<3>& subcell_mesh =\n        db::get<evolution::dg::subcell::Tags::Mesh<3>>(box);\n    const Mesh<3>& dg_mesh = db::get<domain::Tags::Mesh<3>>(box);\n\n    const auto volume_prims = evolution::dg::subcell::fd::project(\n        db::get<typename System::primitive_variables_tag>(box), dg_mesh,\n        subcell_mesh.extents());\n\n    const auto& recons =\n        db::get<grmhd::ValenciaDivClean::fd::Tags::Reconstructor>(box);\n    const auto& boundary_correction =\n        db::get<evolution::Tags::BoundaryCorrection<System>>(box);\n    using derived_boundary_corrections =\n        typename std::decay_t<decltype(boundary_correction)>::creatable_classes;\n    tmpl::for_each<\n        derived_boundary_corrections>([&box, &boundary_correction, &dg_mesh,\n                                       &mortars_to_reconstruct_to,\n                                       &nhbr_package_data, &nhbr_subcell_data,\n                                       &recons, &subcell_mesh, &volume_prims](\n                                          auto derived_correction_v) {\n      using DerivedCorrection = tmpl::type_from<decltype(derived_correction_v)>;\n      if (typeid(boundary_correction) == typeid(DerivedCorrection)) {\n        using dg_package_data_temporary_tags =\n            typename DerivedCorrection::dg_package_data_temporary_tags;\n        using dg_package_data_argument_tags = tmpl::append<\n            evolved_vars_tags, recons_prim_tags, fluxes_tags,\n            tmpl::remove_duplicates<tmpl::push_back<\n                dg_package_data_temporary_tags, gr::Tags::SpatialMetric<3>,\n                gr::Tags::SqrtDetSpatialMetric<DataVector>,\n                gr::Tags::InverseSpatialMetric<3, Frame::Inertial, DataVector>,\n                evolution::dg::Actions::detail::NormalVector<3>>>>;\n\n        const auto& element = db::get<domain::Tags::Element<3>>(box);\n        const auto& eos = get<hydro::Tags::EquationOfStateBase>(box);\n\n        using dg_package_field_tags =\n            typename DerivedCorrection::dg_package_field_tags;\n        Variables<dg_package_data_argument_tags> vars_on_face{0};\n        Variables<dg_package_field_tags> packaged_data{0};\n        for (const auto& mortar_id : mortars_to_reconstruct_to) {\n          const Direction<3>& direction = mortar_id.first;\n\n          Index<3> extents = subcell_mesh.extents();\n          // Switch to face-centered instead of cell-centered points on the FD.\n          // There are num_cell_centered+1 face-centered points.\n          ++extents[direction.dimension()];\n\n          // Computed prims and cons on face via reconstruction\n          const size_t num_face_pts = subcell_mesh.extents()\n                                          .slice_away(direction.dimension())\n                                          .product();\n          vars_on_face.initialize(num_face_pts);\n          // Copy spacetime vars over from volume.\n          using spacetime_vars_to_copy = tmpl::list<\n              gr::Tags::Lapse<DataVector>,\n              gr::Tags::Shift<3, Frame::Inertial, DataVector>,\n              gr::Tags::SpatialMetric<3>,\n              gr::Tags::SqrtDetSpatialMetric<DataVector>,\n              gr::Tags::InverseSpatialMetric<3, Frame::Inertial, DataVector>>;\n          tmpl::for_each<spacetime_vars_to_copy>(\n              [&direction, &extents, &vars_on_face,\n               &spacetime_vars_on_faces =\n                   db::get<evolution::dg::subcell::Tags::OnSubcellFaces<\n                       typename System::flux_spacetime_variables_tag, 3>>(box)](\n                  auto tag_v) {\n                using tag = tmpl::type_from<decltype(tag_v)>;\n                data_on_slice(make_not_null(&get<tag>(vars_on_face)),\n                              get<tag>(gsl::at(spacetime_vars_on_faces,\n                                               direction.dimension())),\n                              extents, direction.dimension(),\n                              direction.side() == Side::Lower\n                                  ? 0\n                                  : extents[direction.dimension()] - 1);\n              });\n\n          call_with_dynamic_type<void, typename grmhd::ValenciaDivClean::fd::\n                                           Reconstructor::creatable_classes>(\n              &recons,\n              [&element, &eos, &mortar_id, &nhbr_subcell_data, &subcell_mesh,\n               &vars_on_face, &volume_prims](const auto& reconstructor) {\n                reconstructor->reconstruct_fd_neighbor(\n                    make_not_null(&vars_on_face), volume_prims, eos, element,\n                    nhbr_subcell_data, subcell_mesh, mortar_id.first);\n              });\n\n          grmhd::ValenciaDivClean::subcell::compute_fluxes(\n              make_not_null(&vars_on_face));\n\n          // Note: since the spacetime isn't dynamical we don't need to\n          // worry about different normal vectors on the different sides\n          // of the element. If the spacetime is dynamical, then the normal\n          // covector needs to be sent, or at least the inverse spatial metric\n          // from the neighbor so that the normal covector can be computed\n          // correctly.\n          tnsr::i<DataVector, 3, Frame::Inertial> normal_covector =\n              get<evolution::dg::Tags::NormalCovector<3>>(\n                  *db::get<evolution::dg::Tags::NormalCovectorAndMagnitude<3>>(\n                       box)\n                       .at(mortar_id.first));\n          for (auto& t : normal_covector) {\n            t *= -1.0;\n          }\n          // Note: Only need to do the projection in 2d and 3d, but GRMHD is\n          // always 3d currently.\n          const auto dg_normal_covector = normal_covector;\n          for (size_t i = 0; i < 3; ++i) {\n            normal_covector.get(i) = evolution::dg::subcell::fd::project(\n                dg_normal_covector.get(i),\n                dg_mesh.slice_away(mortar_id.first.dimension()),\n                subcell_mesh.extents().slice_away(mortar_id.first.dimension()));\n          }\n\n          // Compute the packaged data\n          packaged_data.initialize(num_face_pts);\n          using dg_package_data_projected_tags = tmpl::append<\n              evolved_vars_tags, fluxes_tags, dg_package_data_temporary_tags,\n              typename DerivedCorrection::dg_package_data_primitive_tags>;\n          evolution::dg::Actions::detail::dg_package_data<System>(\n              make_not_null(&packaged_data),\n              dynamic_cast<const DerivedCorrection&>(boundary_correction),\n              vars_on_face, normal_covector, {std::nullopt}, box,\n              typename DerivedCorrection::dg_package_data_volume_tags{},\n              dg_package_data_projected_tags{});\n\n          // Reconstruct the DG solution.\n          // Really we should be solving the boundary correction and\n          // then reconstructing, but away from a shock this doesn't\n          // matter.\n          auto dg_packaged_data = evolution::dg::subcell::fd::reconstruct(\n              packaged_data, dg_mesh.slice_away(mortar_id.first.dimension()),\n              subcell_mesh.extents().slice_away(mortar_id.first.dimension()));\n          nhbr_package_data[mortar_id] = std::vector<double>{\n              dg_packaged_data.data(),\n              dg_packaged_data.data() + dg_packaged_data.size()};\n        }\n      }\n    });\n\n    return nhbr_package_data;\n  }\n};\n}  // namespace grmhd::ValenciaDivClean::subcell\n", "meta": {"hexsha": "298e5b08ddfd0164257d82226990a39bdfb6ad56", "size": 11831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/GrMhd/ValenciaDivClean/Subcell/NeighborPackagedData.hpp", "max_stars_repo_name": "kidder/spectre", "max_stars_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-02T16:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T16:49:35.000Z", "max_issues_repo_path": "src/Evolution/Systems/GrMhd/ValenciaDivClean/Subcell/NeighborPackagedData.hpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-02-27T22:13:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T16:21:08.000Z", "max_forks_repo_path": "src/Evolution/Systems/GrMhd/ValenciaDivClean/Subcell/NeighborPackagedData.hpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "max_forks_repo_licenses": ["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.5020920502, "max_line_length": 94, "alphanum_fraction": 0.6559039811, "num_tokens": 2675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.02333076740785957, "lm_q1q2_score": 0.0111189689902855}}
{"text": "/***\n第三节 完美转发\n（1）完美转发的概念和步骤演绎\na)直接调用：  funcLast();\nb)转发： 通过funcMiddle()间接调用funcLast。funcMiddle相当于一个跳板函数。如果有参数，那么参数也需要通过funcMiddle中转传递给funcLast()\nc)完美转发：const,左值，右值。实参的属性完全不丢失，原原本本的通过funcMiddle转发给funcLast，这种转发就是完美转发。\n万能引用：实参的所有信息都会传递到万能引用当中去从而让编译器推导出来函数模板最终的形参类型 (引用折叠)。\n完美转发：就是让程序员可以书写接受任意实参的函数模板（funcMiddle_Temp），并将其转发到目标函数（funcLast2)，目标函数会接收到与\n转发函数（funcMiddle_Temp）所接收的完全相同（当然包括类型相同比如保持参数的左值、右值特性）的参数。\n要实现完美转发，就要用到std::forward了。\n（2）std::forward ：C++11中专门为转发而存在的函数。这个函数要么返回一个左值，要么返回一个右值。\n万能引用类型才是forward能够发挥作用的重要条件。\n理解：\n(a)实参原来是个左值j，到了形参中还是左值t2。forward能够转化回原来该实参的左值或者右值性。所以，forward之后还是个左值。\n(b)实参原来是个右值20，到了形参中变成了左值t1。forward能够转化回原来该实参的左值或者右值性。所以，forward之后还是个右值。\nforward这个函数有强制把左值转换成右值的能力。所以：forward这个函数只对原来是个右值这种情况有用。\nforward的能力：保持原始实参的左值性或者右值性\n总结：完美转发：比较好的解决了参数转发的问题。\n（3）普通参数的完美转发:auto &&\n\n（4）在构造函数模板中使用完美转发范例\n（5）在可变参数模板中使用完美转发范例\n（5.1）常规的在可变参模板使用完美转发\n（5.2）将目标函数中的返回值通过转发函数返回给调用者函数\n用到的技术：auto结合decltype构成返回类型后置语法。\n（6）完美转发失败的情形一例\n使用NULL或者0作为空指针进行参数传递时导致完美转发失败的情况。\nC++11引入nullptr(空指针)\n***/\n\n#include <iostream>\n\n//#include <boost/type_index.hpp>\nusing namespace std;\n#pragma warning(disable : 4996) \n\n\n//函数模板\n//template <typename T>\n//void myfunc(T  tmprv)\n//{\n//\tcout << \"--------------------------------begin----------------\" << endl;\n//\tusing boost::typeindex::type_id_with_cvr;\n//\tcout << \"T=\" << type_id_with_cvr<T>().pretty_name() << endl; //显示T的类型\n//\tcout << \"tmprv=\" << type_id_with_cvr<decltype(tmprv)>().pretty_name() << endl; //显示tmprv的类型\n//\tcout << \"--------------------------------end------------------\" << endl;\n//}\n\nnamespace _nmsp1\n{\t\t\n\tclass Human\n\t{\n\tpublic:\n\t\t////构造函数\n\t\t//Human(const string& tmpname) :m_sname(tmpname)\n\t\t//{\n\t\t//\tcout << \"Human(const string &tmpname)执行\" << endl;\n\t\t//}\n\t\t////Human(string&& tmpname) :m_sname(tmpname)\n\t\t//Human(string&& tmpname) :m_sname(std::move(tmpname)) //move并不具备移动能力，把一个左值转换成一个右值。\n\t\t//{\n\t\t//\tcout << \"Human(string&& tmpname)执行\" << endl;\n\t\t//}\n\n\t\t//构造函数模板\n\t\ttemplate<typename T>\n\t\tHuman(T&& tmpname) : m_sname(std::forward<T>(tmpname))\n\t\t{\n\t\t\tcout << \"Human(T&& tmpname)执行\" << endl;\n\t\t}\n\n\t\t//拷贝构造函数\n\t\tHuman(const Human& th) : m_sname(th.m_sname)\n\t\t{\n\t\t\tcout << \"Human(const Human& th)拷贝构造函数执行\" << endl;\n\t\t}\n\n\t\t//移动构造函数\n\t\tHuman(Human&& th) : m_sname(std::move(th.m_sname))\n\t\t{\n\t\t\tcout << \"Human(Human&& th)移动构造函数执行\" << endl;\n\t\t}\n\n\tprivate:\n\t\tstring m_sname;\n\t};\n}\n\nnamespace _nmsp2\n{\n\t//void funcLast(int v1, int& v2) //目标函数\n\t//{\n\t//\t++v2; //改变v2的值，让其自增1\n\t//\tcout << v1 + v2 << endl;\n\t//}\n\n\tint funcLast(int v1, int& v2) //目标函数\n\t{\n\t\t++v2; //改变v2的值，让其自增1\n\t\tcout << v1 + v2 << endl;\n\t\treturn v1 + v2;\n\t}\n\n\t//\n\t//template<typename F, typename T1,typename T2>\t\n\t//void funcMiddle_Temp(F f, T1&& t1, T2&& t2)  //转发函数\n\t//{\t\t\n\t//\tf(\n\t//\t\tstd::forward<T1>(t1),\n\t//\t\tstd::forward<T2>(t2) \n\t//\t);\n\t//}\n\n\t//支持任意数量、类型参数的完美转发\n\t/*template <typename F, typename...T>\n\tvoid funcMiddle_Temp(F f, T&&... t)\n\t{\n\t\tf(std::forward<T>(t)...);\n\t}*/\n\n\ttemplate <typename F, typename...T>\n\t//auto funcMiddle_Temp(F f, T&&... t)->decltype(  f(std::forward<T>(t)...)   )\n\tdecltype(auto) funcMiddle_Temp(F f, T&&... t)\n\t{\n\t\treturn f(std::forward<T>(t)...);\n\t}\n\n}\n\nnamespace _nmsp3\n{\n\t//目标函数\n\tvoid funcLast4(char* p)\n\t{\n\t\t//if (p != NULL)\n\t\tif (p != nullptr)\n\t\t{\n\t\t\tstrncpy(p, \"abc\",3);\n\t\t}\n\t}\n\n\t//转发函数\n\ttemplate <typename F, typename...T>\n\tvoid funcMiddle_Temp(F f, T&&... t)\n\t{\n\t\tf(std::forward<T>(t)...);\n\t}\n\n}\n\nint main()\n{ \n\n\n\n\t/*\n\tstring sname = \"ZhangSan\";\n\t_nmsp1::Human myhuman1(sname);\n\t_nmsp1::Human myhuman2(string(\"LiSi\")); //\"LiSi\"是const char[5]类型，而string(\"LiSi\")是string类型。\n\n\t//_nmsp1::Human myhuman3(myhuman1); //实际编译器去调用了构造函数模板，而不是调用了拷贝构造函数。 std::enable_if\n\t_nmsp1::Human myhuman4(std::move(myhuman1));\n\n\tconst _nmsp1::Human myhuman5(string(\"WangWu\"));\n\t_nmsp1::Human myhuman6(myhuman5);\n\t*/\n\n\t/*\n\tint j = 70;\n\t_nmsp2::funcMiddle_Temp(_nmsp2::funcLast, 20, j);\n\tcout << \"j = \" << j << endl;\n\t*/\n\n\t/*\n\tint j = 70;\n\tint k = _nmsp2::funcMiddle_Temp(_nmsp2::funcLast, 20, j);\n\tcout << \"j = \" << j << endl;\n\tcout << \"k = \" << k << endl;\n\t*/\n\n\tchar* p = new char[100];\n\tmemset(p, 0, 100);\n\t//_nmsp3::funcMiddle_Temp(_nmsp3::funcLast4, NULL);  \n\t//_nmsp3::funcLast4(NULL);\n\t_nmsp3::funcMiddle_Temp(_nmsp3::funcLast4, nullptr);\n\n\t\n\treturn 0;\n}\n\n", "meta": {"hexsha": "662a31c64428dd69e01249df3b0bfdaceb898d4c", "size": 4179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/3/306.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/3/306.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/3/306.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 21.8795811518, "max_line_length": 94, "alphanum_fraction": 0.6434553721, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1403362530854946, "lm_q2_score": 0.07921032682610395, "lm_q1q2_score": 0.011116080472452865}}
{"text": "#ifndef ODE_STATE_HPP_INCLUDED\n#define ODE_STATE_HPP_INCLUDED\n\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <vector>\n#include <cassert>\n\nclass GState;\n\nstruct vector_proxy\n{\npublic:\n\tdouble& operator[](std::size_t idx)\n\t{\n\t\tassert( idx < mSize );\n\t\treturn mData[idx];\n\t};\n\tconst double& operator[](std::size_t idx) const\n\t{\n\t\tassert( idx < mSize );\n\t\treturn mData[idx];\n\t};\n\n\ttemplate<class T>\n\tvector_proxy& operator=(const T& other)\n\t{\n\t\tassert( other.size() == mSize );\n\t\tfor(unsigned i = 0; i < other.size(); ++i)\n\t\t\t(*this)[i] = other[i];\n\t\treturn *this;\n\t}\n\n\ttemplate<class T>\n\tvoid assignTo( T& other ) const\n\t{\n\t\tassert( other.size() == mSize );\n\t\tfor(int i = 0; i < other.size(); ++i)\n\t\t\tother[i] = (*this)[i];\n\t}\n\n\tstd::size_t size() const { return mSize;};\n\nprivate:\n\tdouble* mData;\n\tstd::size_t mSize;\n\tvector_proxy(double* ptr, std::size_t sz) : mData(ptr), mSize(sz) {};\n\n\tfriend class GState;\n};\n\nstruct const_vector_proxy\n{\npublic:\n\tconst double& operator[](std::size_t idx) const {\n\t\tassert( idx < mSize );\n\t\treturn mData[idx];\n\t};\n\tstd::size_t size() const { return mSize;};\n\n\ttemplate<class T>\n\tvoid assignTo( T& other ) const\n\t{\n\t\tassert( other.size() == mSize );\n\t\tfor(unsigned i = 0; i < mSize; ++i)\n\t\t\tother[i] = (*this)[i];\n\t}\nprivate:\n\tconst double* mData;\n\tstd::size_t mSize;\n\n\tconst_vector_proxy(const double* ptr, std::size_t sz) : mData(ptr), mSize(sz) {};\n\n\tfriend class GState;\n};\n\nclass GState\n{\npublic:\n\tGState();\n\t//~GState();\n\tGState( int D, bool m );\n\t//GState( const GState& cpy );\n\t//GState( GState&& mov );\n\n\ttypedef std::vector<double> container_type;\n\ttypedef container_type::iterator iterator;\n\ttypedef container_type::const_iterator const_iterator;\n\ttypedef double value_type;\n\n\tstd::size_t dimension() const { return mDimension; };\n\tbool monodromy() const { return mHasMonodromy; };\n\n\tvoid resize( std::size_t size, bool monodromy );\n\tvoid init_monodromy();\n\n\t// iterator access\n\tconst_iterator begin() const \t{ return mData.begin(); }\n\tconst_iterator end() const\t\t{ return mData.end(); }\n\titerator begin() \t\t\t\t{ return mData.begin(); }\n\titerator end() \t\t\t\t\t{ return mData.end(); }\n\n\t// accessing values outside of integration\n\tvector_proxy position() { return vector_proxy(&mData[0], mDimension); };\n\tconst_vector_proxy position() const { return const_vector_proxy(&mData[0], mDimension); };\n\n\tvector_proxy velocity() { return vector_proxy(&mData[0] + mDimension, mDimension);};\n\tconst_vector_proxy velocity() const { return const_vector_proxy(&mData[0] + mDimension, mDimension);};\n\n\tvector_proxy matrix() { return vector_proxy( &mData[0] + 2*mDimension, 4*mDimension*mDimension ); };\n\tconst_vector_proxy matrix() const { return const_vector_proxy( &mData[0] + 2*mDimension, 4*mDimension*mDimension ); };\nprivate:\n\tstd::vector<double> mData;\n\tstd::size_t mDimension = 0;\n\tbool mHasMonodromy = false;\n};\n\n// mark resizable\nnamespace boost { namespace numeric { namespace odeint {\n\ntemplate<>\nstruct is_resizeable< GState >\n{\n\ttypedef boost::true_type type;\n\tstatic const bool value = type::value;\n};\n\ntemplate <class U, class V>\nstruct same_size_impl;\n\ntemplate <>\nstruct same_size_impl< GState , GState >\n{\n    static bool same_size( const GState& x , const GState& y )\n    {\n        return x.dimension() == y.dimension() && x.monodromy() == y.monodromy();\n    }\n};\n\ntemplate <class U, class V>\nstruct resize_impl;\n\ntemplate <>\nstruct resize_impl< GState , GState >\n{\n    static void resize( GState& x , const GState& y )\n    {\n    \tx.resize( y.dimension(), y.monodromy() );\n    }\n};\n\n} } }\n\n\n#endif // ODE_STATE_HPP_INCLUDED\n", "meta": {"hexsha": "a7acc23667551465f200c20123bb502544bf132f", "size": 3591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tracer/ode_state.hpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tracer/ode_state.hpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tracer/ode_state.hpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1677419355, "max_line_length": 119, "alphanum_fraction": 0.679476469, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.02887090966191968, "lm_q1q2_score": 0.011112763343754243}}
{"text": "//\n//  Net.cpp\n//\n//\n//  Created by Guanglei Wang on 03/06/2017.\n//\n\n#include <gravity/Net.h>\n#include <algorithm>\n#include <map>\n#include <set>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <list>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <queue>\n#include <time.h>\n//#include <armadillo>\n#ifdef USE_BOOST\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <deque>\n#include <iterator>\n#endif\n\nusing namespace std;\nusing namespace gravity;\n\nstatic int max_line_len;\nstatic char* line = nullptr;\n\nNet::Net() {}\n\n/* returns true if an arc is already present between the given nodes */\nbool Net::duplicate(std::string n1, std::string n2, int id1) {\n    int id2 = get_arc(n1, n2)->_id;\n    \n    if (id2 < id1)\n        return true;\n    else\n        return false;\n}\n\n\nNet* Net::clone() const{\n    Net* copy_net = new Net();\n    Node* node = NULL;\n    \n    for (int i=0; i<nodes.size(); i++) {\n        node = this->nodes[i];\n        copy_net->add_node(node->clone());\n    }\n    \n    Arc* arc = NULL;\n    for (int i=0; i < arcs.size(); i++) {\n        \n        /* ignores if the arc is a paralel line to an already existing arc */\n        //if (duplicate(arcs[i]->_src->_name, arcs[i]->_dest->_name, arcs[i]->_id)) {\n//            continue;\n//        }\n        arc = arcs[i]->clone();\n        \n        /* Update the source and destination to the new nodes in copy_net */\n        arc->_src = copy_net->get_node(arc->_src->_name);\n        arc->_dest = copy_net->get_node(arc->_dest->_name);\n        \n        /* Add the new arc to the list of arcs */\n        copy_net->add_arc(arc);\n        \n        /* Connects it to its source and destination */\n        arc->connect();\n    }\n    return copy_net;\n}\n\nNet* Net::clone_undirected() {\n    Net* copy_net = new Net();\n    Node* node = NULL;\n    \n    for (int i=0; i<nodes.size(); i++) {\n        node = this->nodes[i];\n        copy_net->add_node(node->clone());\n    }\n    \n    Arc* arc = NULL;\n    for (int i=0; i < arcs.size(); i++) {\n        if (copy_net->get_arc(arcs[i]->_src->_name, arcs[i]->_dest->_name)!=nullptr) {\n            continue;\n        }\n        arc = arcs[i]->clone();\n        \n        /* Update the source and destination to the new nodes in copy_net */\n        arc->_src = copy_net->get_node(arc->_src->_name);\n        arc->_dest = copy_net->get_node(arc->_dest->_name);\n        \n        /* Add the undirected arc to the list of arcs */\n        copy_net->add_undirected_arc(arc);\n        \n        /* Connects it to its source and destination */\n        arc->connect();\n    }\n    return copy_net;\n}\n\nconst bool bag_compare(const vector<Node*> & a,const vector<Node*>& b) {\n    return a.size() > b.size();\n}\n\n\nconst bool node_compare(const Node* n1, const Node* n2) {\n    return n1->fill_in > n2->fill_in;\n}\n\nvoid Net::add_node(Node* node) {\n    node->_id = (int) nodes.size();\n    \n    if (!nodeID.insert(pair<string,Node*>(node->_name, node)).second) {\n        cerr << \"ERROR: adding the same node twice!\";\n    }\n    \n    nodes.push_back(node);\n}\n\nNode* Net::get_node(string name) const{\n    return nodeID.find(name)->second;\n}\n\n/* returns the undirected arc formed by node n1 and n2 */\nArc* Net::get_arc(Node* n1, Node* n2) {\n    string src, dest, key, inv_key;\n    src = n1->_name;\n    dest = n2->_name;\n    key.clear();\n    inv_key.clear();\n    key.append(src);\n    inv_key.append(dest);\n    key.append(\",\");\n    inv_key.append(\",\");\n    key.append(dest);\n    inv_key.append(src);\n    map<string, set<Arc*>*>::iterator it= arcID.find(key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            //   if (!a->parallel) {\n            return a;\n            // }\n        }\n    }\n    it = arcID.find(inv_key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            //   if (!a->parallel) {\n            return a;\n            // }\n        }\n    }\n    return nullptr;\n}\n\n/* returns the Id of the arc formed by nodes names n1 and n2 */\n// this assumes that the graph is undirected.\nArc* Net::get_arc(std::string src, std::string dest) {\n    std::string key, inv_key;\n    key.clear();\n    inv_key.clear();\n    key.append(src);\n    inv_key.append(dest);\n    key.append(\",\");\n    inv_key.append(\",\");\n    key.append(dest);\n    inv_key.append(src);\n    map<string, set<Arc*>*>::iterator it= arcID.find(key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            return a;\n        }\n    }\n    \n    it = arcID.find(inv_key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            return a;\n        }\n    }\n    \n    return nullptr;\n}\n\nArc* Net::get_directed_arc(std::string src, std::string dest) {\n    std::string key;\n    key.clear();\n    key.append(src);\n    key.append(\",\");\n    key.append(dest);\n    map<string, set<Arc*>*>::iterator it= arcID.find(key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            return a;\n        }\n    }\n\n    return nullptr;\n}\n\nbool Net::add_arc(Arc* a) {\n    bool parallel = false;\n    set<Arc*>* s = NULL;\n    string src, dest, key;\n    src = a->_src->_name;\n    dest = a->_dest->_name;\n    if (src == dest){\n        throw invalid_argument (\"It is now allowed to make a node self connected in gravity. \\n\");\n        \n    }\n    \n    \n    key.clear();\n    key.append(src);\n    key.append(\",\");\n    key.append(dest);\n    \n    if(arcID.find(key)==arcID.end()) {\n        s = new set<Arc*>;\n        s->insert(a);\n        arcID.insert(pair<string, set<Arc*>*>(key,s));\n    }\n    else {\n        if(arcID.find(key)!=arcID.end())\n            s = arcID[key];\n        s->insert(a);\n        Warning(\"\\nWARNING: adding another Directed line between same nodes! \\n Node ID: \" << src << \" and Node ID: \" << dest << endl);\n        a->_parallel = true;\n        parallel = true;\n    }\n    arcMap[a->_name] = a;\n    arcs.push_back(a);\n    return parallel;\n}\n// undirected\nvoid Net::add_undirected_arc(Arc* a) {\n//    bool parallel = false;\n    set<Arc*>* s = NULL;\n    string src, dest, key, key_inv;\n    src = a->_src->_name;\n    dest = a->_dest->_name;\n\n    if (src == dest){\n        throw invalid_argument (\"It is now allowed to make a node self connected in gravity. \\n\");\n    \n    }\n    \n    key.clear();\n    key.append(src);\n    key.append(\",\");\n    key.append(dest);\n    \n    key_inv.clear();\n    key_inv.append(dest);\n    key_inv.append(\",\");\n    key_inv.append(src);\n    \n    if(arcID.find(key)==arcID.end()&& arcID.find(key_inv)==arcID.end()) {\n        s = new set<Arc*>;\n        s->insert(a);\n        arcID.insert(pair<string, set<Arc*>*>(key,s));\n        arcs.push_back(a);\n    }\n}\n\n\n/** remove the arc by\n1. removing it from the arcs list, but without changing the arc id.\n2. removing it from the map container.\n*/\n\nvoid Net::remove_arc(Arc* a) {\n    arcs.erase(arcs.begin()+(a->_id));\n    //arcs[a->_id] = nullptr;\n    arcID.erase(a->_src->_name+\",\"+a->_dest->_name);\n}\n\n// Reading files\nchar* Net::readline(FILE *input)\n{\n    size_t len;\n    // line, max_line_len have been declared\n    if(std::fgets(line,max_line_len,input)==NULL) return NULL;\n\n    while(strrchr(line,'\\n') == NULL)\n    {\n        max_line_len *= 2;\n        line = (char *)realloc(line,max_line_len);\n        len = strlen(line);\n        if(fgets(line+len,max_line_len-len,input) == NULL)\n            break;\n    }\n    return line;\n}\n\nvoid Net::exit_input_error(int line_num) {\n    fprintf(stderr,\"Wrong input format at line %d\\n\", line_num);\n    exit(1);\n}\n\n// Reading graphs with rudy format\nvoid Net::readrudy(const char* fname) {\n    int Num_nodes=0;\n    int Num_edges=0;\n\n    ifstream infile(fname);\n\n    string sLine;\n\n    if (infile.good())\n    {\n        getline(infile, sLine);\n        istringstream iss(sLine);\n        iss >> Num_nodes;\n        iss >> Num_edges;\n    }\n    else{\n        fprintf(stderr,\"can’t open input file %s\\n\",fname);\n        exit(1);\n    }\n    // get nodes\n\n    string name;\n    Node* node = nullptr;\n\n    for (int i= 1; i< Num_nodes + 1; i++) {\n        name = to_string(i);\n        node = new Node(name,i-1);\n        add_node(node);\n    }\n\n\n    // get arcs\n    Arc* arc = NULL;\n\n    // note that src, dest are names of nodes.\n    string src, dest;\n    double weight;\n    while(getline(infile,sLine,'\\n'))\n    {\n        istringstream iss(sLine);\n        iss >> src >> dest >> weight;\n\n        name = (int)arcs.size()+1;\n        arc = new Arc(name);\n\n        arc->_id = (int)arcs.size();\n\n        arc->_src = get_node(src);\n        arc->_dest= get_node(dest);\n        arc->_weight=weight;\n        add_arc(arc);\n        arc->connect();\n    }\n    infile.close();\n}\n\n\n\n/** construct a graph by reading an adjacency matrix */\nvoid Net::read_adjacency_matrix(const string& fname) {\n    FILE *fp = fopen(fname.c_str(),\"r\");\n    if(fp == NULL)\n    {\n            cout << \"Can’t open input file \" << fname;\n            exit(1);\n    }\n    max_line_len = 1024;\n    line = new char[max_line_len];\n\n    vector<vector<int>> matrix;\n    int temp;\n    while(readline(fp)!=NULL)\n    {\n        vector<int> row;\n        stringstream linestream(line);\n        while (linestream>>temp)\n            row.push_back(temp);\n        matrix.push_back(row);\n    }\n    \n    int n=0;\n    n =matrix.size();\n\n    string name;\n    int id = 0;\n\n    Node* node = NULL;\n    for (int i= 0; i<n; i++) {\n        name = to_string(i);\n        node = new Node(name,i);\n        add_node(node);\n    }\n\n    Arc* arc = NULL;\n    string src, dest;\n    unsigned index = 0;\n    for (int i = 0; i <(n); i++)\n        for (int j=i+1; j<n; j++) {\n            if (matrix[i][j] > 0)\n            {\n                src = to_string(i);\n                dest = to_string(j);\n                id = index;\n                arc = new Arc(src + \",\" + dest);\n                arc->_id = id;\n                arc->_src = get_node(src);\n                arc->_dest= get_node(dest);\n                add_arc(arc);\n                arc->connect();\n            }\n            index++;\n        }\n    delete[] line;\n    fclose(fp);\n}\n\nvoid Net::get_complement(const char* fname) {\n    FILE *fp = fopen(fname,\"r\");\n    if(fp == NULL)\n    {\n        fprintf(stderr,\"can’t open input file %s\\n\",fname);\n        exit(1);\n    }\n\n    max_line_len = 1024;\n    line = new char[max_line_len];\n\n    vector<vector<int>> matrix;\n    int temp;\n    while(readline(fp)!=NULL)\n    {\n        vector<int> row;\n        stringstream linestream(line);\n        while (linestream>>temp)\n            row.push_back(temp);\n        matrix.push_back(row);\n    }\n    int n=0;\n    n =matrix.size();\n\n    string name;\n    int id = 0;\n\n    Node* node = NULL;\n    for (int i= 0; i<n; i++) {\n        name = to_string(i);\n        node = new Node(name,i);\n        add_node(node);\n    }\n\n    Arc* arc = NULL;\n    string src, dest;\n\n    for (int i = 0; i <(n-1); i++)\n        for (int j=i+1; j<n; j++) {\n            if (matrix[i][j] == 0)\n            {\n                src = to_string(i);\n                dest = to_string(j);\n                id = (int)arcs.size();\n                arc = new Arc(to_string(id));\n                arc->_id = id;\n                arc->_src = get_node(src);\n                arc->_dest= get_node(dest);\n                add_arc(arc);\n                arc->connect();\n            }\n        }\n    delete[] line;\n    fclose(fp);\n}\n\n\n\n/*  @brief Remove node and all incident arcs from the network\n @note Does not remove the incident arcs from the list of arcs in the network!\n @return the id of the node removed\n */\nstring Net::remove_end_node() {\n    Node* n = nodes.back();\n    Node * nn = nullptr;\n    string n_id = n->_name;\n    for (auto a: n->branches) {\n        nn = a->neighbour(n);\n        nn->removeArc(a);\n        for (auto aa: nn->branches) {\n            if (!aa->neighbour(nn)->is_connected(n)) {\n                nn->fill_in--;\n                assert(nn->fill_in >=0);\n            }\n        }\n    }\n    nodes.pop_back();\n    return n_id;\n}\n\n// use greedy fill-in algorithm.\nvoid Net::get_tree_decomp_bags(bool print_bags, bool decompose) {\n    Node* n = nullptr;\n    Node* u = nullptr;\n    Node* nn = nullptr;\n    Arc* arc = nullptr;\n    set<vector<Node*>> unique_bags;\n    string name=\"\";\n    Net* graph_clone = clone_undirected(); //\n    int nb = 0;\n    unsigned max_size = 0;\n    \n    /** cliques with less than 1 nodes are useless for us.*/\n    while (graph_clone->nodes.size()> 2) {\n        sort(graph_clone->nodes.begin(), graph_clone->nodes.end(),node_compare);\n        \n        // last element has the minimum fill-in.\n        n = graph_clone->nodes.back();\n        if(!n->_active) {\n            graph_clone->remove_end_node();\n            continue;\n        }\n        Debug(n->_name << endl);\n        Debug(graph_clone->nodes.size() << endl);\n        vector<Node*> bag_copy;\n        vector<Node*> bag;\n        DebugOff(\"new bag = { \");\n        for (auto nn: n->get_neighbours()) {\n            if(!nn->_active) continue;\n            bag_copy.push_back(nn);\n            bag.push_back(get_node(nn->_name)); // Note it takes original node.\n            DebugOff(nn->_name << \", \");\n        }\n        DebugOff(n->_name << \"}\\n\");\n        graph_clone->remove_end_node();\n        bag_copy.push_back(n);\n        bag.push_back(get_node(n->_name)); // node in this graph\n        sort(bag_copy.begin(), bag_copy.end(), [](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n        sort(bag.begin(), bag.end(), [](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n        \n        // update clone_graph and construct chordal extension.\n        for (int i = 0; i < bag_copy.size(); i++) {\n            u = bag_copy.at(i);\n            for (int j = i+1; j<bag_copy.size(); j++) {\n                nn = bag_copy.at(j);\n                if (u->is_connected(nn)) {\n                    if(get_arc(u,nn) && !get_arc(u,nn)->_active) {\n                        Arc* off_arc = get_arc(u,nn);\n                        off_arc->_imaginary = true;\n                        off_arc->_free = true;\n                    }\n                    continue;\n                }\n                name = to_string((int) graph_clone->arcs.size()+1);\n                arc = new Arc(name);\n                \n                arc->_id = arcs.size();\n                arc->_src = u;\n                arc->_dest = nn;\n                arc->_imaginary = true;\n                arc->_free = true;\n                arc->connect();\n                graph_clone->add_undirected_arc(arc);\n            }\n        }\n        \n//        if (true) {\n            //            DebugOn(\"bag_copy = {\");\n            //            for (int i=0; i<bag_copy.size();     i++) {\n            //                cout << bag_copy.at(i)->_name << \" \";\n            //            }\n            //            DebugOn(\"}\" << endl);\n//            DebugOff(\"bag = {\");\n//            for (int i=0; i<bag.size();     i++) {\n//                cout << bag.at(i)->_name << \" \";\n//            }\n//            DebugOff(\"}\" << endl);\n//        }\n        //        _bags_copy.push_back(bag_copy);\n        if(unique_bags.insert(bag).second){\n            _bags.push_back(bag); // bag original\n        }\n        \n        if (bag_copy.size()==3) {\n            nb++;\n        }\n        if (bag_copy.size()>max_size) {\n            max_size = bag_copy.size();\n        }\n        else if(decompose && bag_copy.size()>3){\n            DebugOff(\"Decomposing bigger bag into 3d bags\\n\");\n            \n            for (auto i = 0; i<bag_copy.size()-2; i++) {\n                for (auto j = i+1; j<bag_copy.size()-1; j++) {\n                    for (auto k = j+1; k<bag_copy.size(); k++) {\n                        vector<Node*> new_bag;\n                        new_bag.push_back(bag[i]);\n                        new_bag.push_back(bag[j]);\n                        new_bag.push_back(bag[k]);\n                        DebugOff(\"new bag = {\");\n//                        for (int i=0; i<new_bag.size();     i++) {\n//                            cout << new_bag.at(i)->_name << \" \";\n//                        }\n                        DebugOff(\"}\" << endl);\n                        if(unique_bags.insert(new_bag).second){\n                            _bags.push_back(new_bag);\n                        }\n                    }\n                }\n            }\n        }\n        delete n;\n    }\n    //    sort(_bags.begin(), _bags.end(), bag_compare);\n    \n    \n    Debug(\"\\n Number of 3D bags = \" << nb << endl);\n    DebugOn(\"\\n Max cliwue size = \" << max_size << endl);\n//    DebugOn(\"\\n Total number of bags = \" << _bags.size() << endl);\n    \n    delete graph_clone;\n    \n}\n\n/** Return the vector of arcs ignoring parallel lines **/\nindices Net::get_bus_pairs(){\n    indices bpairs(\"bus_pairs\");\n    for (auto a: arcs) {\n        if (!a->_parallel) {\n            bpairs.add(a->_src->_name+\",\"+a->_dest->_name);\n        }\n    }\n    return bpairs;\n}\n\n\n\n//Net* Net::get_chordal_extension() {\n//    Node* n = nullptr;\n//    Node* u = nullptr;\n//    Node* nn = nullptr;\n//    Arc* arc = nullptr;\n//    Arc* arc_chordal = nullptr;\n//\n//    Node* u_chordal = nullptr;\n//    Node* nn_chordal = nullptr;\n//\n//    string name=\"\";\n//    string name_chordal=\"\";\n//    Net* chordal_extension = clone();\n//    Net* graph_clone = clone_undirected();\n//    int nb = 0;\n//\n//    /** cliques with less than 1 nodes are useless for us.*/\n//    while (graph_clone->nodes.size() > 1) {\n//        sort(graph_clone->nodes.begin(), graph_clone->nodes.end(),node_compare);\n//        // last element has the minimum fill-in.\n//        n = graph_clone->nodes.back();\n//        Debug(n->_name << endl);\n//        Debug(_clone->nodes.size() << endl);\n//        vector<Node*> bag_copy;\n//        vector<Node*> bag;\n//        Debug(\"new bag_copy = { \");\n//\n//        for (auto nn: n->get_neighbours()) {\n//            bag_copy.push_back(nn);\n//            bag.push_back(get_node(nn->_name));\n//            Debug(nn->_name << \", \");\n//        }\n//\n//        graph_clone->remove_end_node();\n//        bag_copy.push_back(n);\n//        bag.push_back(get_node(n->_name)); // node in this graph\n//        sort(bag_copy.begin(), bag_copy.end(),[](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n//        sort(bag.begin(), bag.end(),[](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n//\n//        // update graph_graph and construct chordal extension.\n//        for (int i = 0; i < bag_copy.size() - 1; i++) {\n//            u = bag_copy.at(i);\n//            u_chordal = chordal_extension->get_node(u->_name);\n//            for (int j = i+1; j<bag_copy.size(); j++) {\n//                nn = bag_copy.at(j);\n//                nn_chordal=chordal_extension->get_node(nn->_name);\n//                if (u->is_connected(nn)) {\n//                    continue;\n//                }\n//                name = to_string((int) graph_clone->arcs.size()+1);\n//                name_chordal = to_string((int)chordal_extension->arcs.size()+1);\n//\n//                arc = new Arc(name);\n//                arc_chordal = new Arc(name_chordal);\n//\n//                arc->_id = arcs.size();\n//                arc->_src = u;\n//                arc->_dest = nn;\n//                arc->connect();\n//                graph_clone->add_undirected_arc(arc);\n//\n//                arc_chordal->_id = chordal_extension->arcs.size();\n//                arc_chordal->_src = u_chordal;\n//                arc_chordal->_dest = nn_chordal;\n//                arc_chordal->connect();\n//                chordal_extension->add_undirected_arc(arc_chordal);\n//            }\n//        }\n//        _bags_copy.push_back(bag_copy);\n//        _bags.push_back(bag);\n//        if (bag_copy.size()==3) {\n//            nb++;\n//        }\n//        delete n;\n//    }\n//    // sort the bags by its size (descending order)\n//    sort(_bags.begin(), _bags.end(), bag_compare);\n//    printf(\"With greedy fill-in algirithm, the chordal graph added  %lu edges \\n\", (chordal_extension->arcs.size() - arcs.size()));\n//\n//    delete graph_clone;\n//    return chordal_extension;\n//}\n\n// get cliques from the tree decomposition\n// Two methods\n// first one: check the inclusion relationship\n// second one: use the RIP property of the tree decomposition, thus just need to check every leaf..\n// One need to execute either get_tree_decomposition or get_chordal_extension first, then run get_clique_tree.\n\n// use _bags instead of bag_copy\n//void Net::get_cliquebags (bool print) {\n//    for (unsigned i = 0; i < _bags.size(); i++) {\n//        for (unsigned j = i+1; j < _bags.size();) {\n//            if (std::includes(_bags[i].begin(),_bags[i].end(),\n//                              _bags[j].begin(), _bags[j].end()))\n//            {\n//                _bags.erase(_bags.begin()+j);\n//            }\n//            else\n//                j++;\n//        }\n//    }\n//    cout << \"Number of maximal cliques of the chordal extension = \" << _bags.size() << endl <<endl;\n//}\n\n/* Destructors */\nNet::~Net() {\n    if (!nodes.empty()) {\n        for (vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); it++) {\n            delete (*it);\n        }\n        nodes.clear();\n    }\n    if(!arcs.empty()) {\n        for (vector<Arc*>::iterator it = arcs.begin(); it != arcs.end(); it++) {\n            if(*it)\n                delete (*it);\n        }\n        arcs.clear();\n    }\n\n    if(!cycle_basis.empty()) {\n        for (vector<Path*>::iterator it = cycle_basis.begin(); it != cycle_basis.end(); it++) {\n            delete (*it);\n        }\n        arcs.clear();\n    }\n    for (pair<string,set<Arc*>*> it:arcID) {\n        delete it.second;\n    }\n}\n\n//Net* Net::get_clique_tree(){\n//    Net* cliquetree = new Net();\n//    Node* node = nullptr;\n//    Arc*  a = nullptr;\n//    string name;\n//    get_cliquebags(true);\n//#ifdef USE_BOOST\n//    /** Note that we also need the edge information of the clique tree **/\n//    /** boost graph library or implement the expanded version of MCS algorithm by Blair and Peyton */\n//    typedef boost::adjacency_list <boost::vecS,\n//    boost::vecS,\n//    boost::undirectedS,\n//    boost::no_property,\n//    boost::property < boost::edge_weight_t, int >> Graph;\n//    typedef boost::graph_traits <Graph>::edge_descriptor Edge;\n//    //typedef boost::graph_traits <Graph>::vertex_descriptor Vertex;\n//\n//    // BUILD THE INTERSECTION GRAPH OF THE CLIQUES\n//    typedef std::pair<int, int> E;\n//    std::vector<E> edges;\n//    std::vector<int> weights;\n//    int nb_cliques = this->_bags.size();\n//    for (int i = 0; i < nb_cliques; i++) {\n//        DebugOn(\"bag \" << i << \" has \" << this->_bags[i].size() << \" nodes.\" <<endl);\n//        sort(this->_bags[i].begin(), this->_bags[i].end());\n//        for (int j = i +1; j < nb_cliques; j++) {\n//            vector<Node*> v3;\n//            sort(this->_bags[j].begin(), this->_bags[j].end());\n//            set_intersection(this->_bags[i].begin(), this->_bags[i].end(), this->_bags[j].begin(), this->_bags[j].end(), back_inserter(v3));\n//            if (v3.size() > 0) {\n//                edges.push_back(E(i, j));\n//                weights.push_back(-v3.size());\n//            }\n//        }\n//    }\n//    //size_t num_edges = edges.size();\n//\n//#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n//    Graph g(num_nodes);\n//    boost::property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\n//    for (std::size_t j = 0; j < num_edges; ++j) {\n//        Edge e;\n//        bool inserted;\n//        boost::tie(e, inserted) = boost::add_edge(edges[j].first, edges[j].second, g);\n//        boost::weightmap[e] = weights[j];\n//    }\n//#else\n//    Graph g(edges.begin(), edges.end(), weights.begin(), nb_cliques);\n//#endif\n//    boost::property_map < Graph, boost::edge_weight_t >::type weight = get(boost::edge_weight, g);\n//    std::vector < Edge > spanning_tree;\n//    boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n//\n//    DebugOn(\"Print the total \" << spanning_tree.size() << \" edges in the clique tree:\" << endl);\n//\n//    //////////CLIQUE TREE /////////////////////////////\n//    for (int i = 0; i < nb_cliques; i++) {\n//        node= new Node(to_string(i), i);\n//        cliquetree->add_node(node);\n//    }\n//\n//    for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n//         ei != spanning_tree.end(); ++ei) {\n//        int u = source(*ei, g);\n//        int v = target(*ei, g);\n//        DebugOn(u << \" <--> \" << v\n//                << \" with weight of \" << -weight[*ei]\n//                << endl);\n//        name = (int) cliquetree->arcs.size();\n//        a = new Arc(name);\n//        a->_id = cliquetree->arcs.size();\n//\n//        // intersection\n//        vector<Node*> v3;\n//        sort(this->_bags[u].begin(), this->_bags[u].end());\n//        sort(this->_bags[v].begin(), this->_bags[v].end());\n//        set_intersection(this->_bags[u].begin(), this->_bags[u].end(),\n//                         this->_bags[v].begin(), this->_bags[v].end(),\n//                         back_inserter(v3));\n//        a->_src = cliquetree->get_node(to_string(u));\n//        a->_dest = cliquetree->get_node(to_string(v));\n//        a->_weight = -weight[*ei];\n//        a->_intersection = v3;\n//        cliquetree->add_arc(a);\n//        a->connect();\n//\n//        for (int i = 0; i < v3.size(); i++){\n//                auto  node = v3.at(i);\n//            for (int j = i+1; j < v3.size(); j++){\n//                auto arc = get_arc(node, v3.at(j));\n//                if (arc != nullptr){\n//                    a->_intersection_clique.push_back(new index_pair(index_(arc->_src->_name), index_(arc->_dest->_name), arc->_active));\n//                }\n//             //   else\n//               //     a->_intersection_clique.push_back(new index_pair(index_(node->_name), index_(v3.at(j)->_name), true));\n//            }\n//        }\n//    }\n//#endif\n//    return cliquetree;\n//}\n\n\n//void Net::chol_decompose(bool print){\n//    arma::mat adjacency_matrix = arma::zeros(nodes.size(), nodes.size());\n//    for (auto &arc: arcs){\n//        adjacency_matrix(arc->_src->_id, arc->_dest->_id) = 1;\n//        adjacency_matrix(arc->_dest->_id, arc->_src->_id) = 1;\n//\n//    }\n//    arma::mat pertubation = arma::zeros(nodes.size(),nodes.size());\n//    // if fails,  make epsilon larger.\n//    unsigned epsilon = 2;\n//    arma::mat adjacency_matrix_psd = adjacency_matrix + epsilon*pertubation.eye();\n//    arma::mat chordal_sparsity = arma::zeros(nodes.size(),nodes.size());\n//    chordal_sparsity = arma::chol(adjacency_matrix_psd);\n//    if (print){\n//        cout << \"chordal sparsity matrix: \\n \" << chordal_sparsity << endl;\n//    }\n//    unsigned num_nonzeros = 0;\n//    for (int i = 0; i < nodes.size(); i++)\n//        for (int j = i+1; j< nodes.size(); j++){\n//            if (chordal_sparsity(i, j) != 0){\n//                num_nonzeros +=1;\n//            }\n//        }\n//    printf(\"With cholesky decomposition, the chordal graph added  %lu edges \\n\", (num_nonzeros - arcs.size()));\n//}\n\n\n//std::vector<gravity::index_pair*> Net::get_bus_pairs_all(){\n//    vector<gravity::index_pair*> res;\n//    string ni, nj;\n//    for(int i = 0; i < nodes.size()-1; i++) {\n//        for(int j = i+1; j < nodes.size(); j++) {\n//            ni = nodes[i]->_name;\n//            nj = nodes[j]->_name;\n//            res.push_back(new index_pair(index_(ni), index_(nj), 1));\n//        }\n//    }\n//    return res;\n//}\n", "meta": {"hexsha": "436b0eaba86242b9e26a9c1661fcb4b8225d9e03", "size": 27427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Net.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/Net.cpp", "max_issues_repo_name": "lanl-ansi/ODO", "max_issues_repo_head_hexsha": "d454eb226cd1861b622a381198ce4756709dfa95", "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/Net.cpp", "max_forks_repo_name": "lanl-ansi/ODO", "max_forks_repo_head_hexsha": "d454eb226cd1861b622a381198ce4756709dfa95", "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": 29.779587405, "max_line_length": 142, "alphanum_fraction": 0.5116491049, "num_tokens": 7139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.02887090830410376, "lm_q1q2_score": 0.01111276322853158}}
{"text": "#include <stdarg.h>\n#include <fstream>\n#include <boost/exception/all.hpp>\n#include <boost/math/special_functions.hpp>\n\n#include \"common.h\"\n\n#include \"Array.h\"\n\n// ArrayDescriptor implementation\n\n#define VAR_NAME_PRINTER(name) var_name_printer(#name)\n\nstd::string var_name_printer(char *name) { return std::string(name); }\n\nnamespace matCUDA\n{\n\tArrayDescriptor::ArrayDescriptor(int count)\n\t\t: m_count(count)\n\t{\n\t\t\tm_dim = new index_t[count];\n\t}\n\n\tArrayDescriptor::ArrayDescriptor(ArrayDescriptor &source)\n\t\t: m_count(source.m_count)\n\t{\n\t\tm_dim = new index_t[m_count];\n\t\tfor(index_t i = 0; i < m_count; i++)\n\t\t\tm_dim[i] = source.m_dim[i];\n\t}\n\n\tArrayDescriptor::ArrayDescriptor(std::vector<index_t> &source)\n\t\t: m_count((int)source.size())\n\t{\n\t\tm_dim = new index_t[m_count];\n\t\tindex_t i = 0;\n\t\tfor(std::vector<int>::iterator it = source.begin(); it != source.end(); ++it)\n\t\t\tm_dim[i++] = *it;\n\t}\n\n\tArrayDescriptor::ArrayDescriptor(int source[])\n\t\t: m_count(sizeof(source)/sizeof(int))\n\t{\n\t\tm_dim = new index_t[m_count];\n\t\tfor(index_t i = 0; i < m_count; i++)\n\t\t\tm_dim[i] = source[i];\n\t}\n\n\tArrayDescriptor::~ArrayDescriptor() { delete[] m_dim; }\n\n\tint ArrayDescriptor::GetDim(int dim) { return m_dim[dim]; }\n\n\tint ArrayDescriptor::GetNDim() { return m_count; }\n\n\tint ArrayDescriptor::GetNumberOfElements() \n\t{\n\t\tint NDim = ArrayDescriptor::GetNDim();\n\t\tint TotalDim = 1;\n\t\tfor (int i = 0; i < NDim; i++ )\n\t\t\tTotalDim *= ArrayDescriptor::GetDim( i );\n\t\treturn TotalDim;\n\t}\n\n\tvoid ArrayDescriptor::Swap()\n\t{\n\t\tif(m_count != 2)\n\t\t\treturn;\n\n\t\tindex_t temp = m_dim[0];\n\t\tm_dim[0] = m_dim[1];\n\t\tm_dim[1] = temp;\n\t}\n\n\tbool ArrayDescriptor::operator == (const ArrayDescriptor &other) const\n\t{\n\t\tif(m_count != other.m_count)\n\t\t\treturn false;\n\n\t\tfor(index_t i = 0; i < m_count; i++)\n\t\t\tif(m_dim[i] != other.m_dim[i])\n\t\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\tbool ArrayDescriptor::operator != (const ArrayDescriptor &other) const\n\t{\n\t\treturn !(*this == other);\n\t}\n\n\tArrayDescriptor& ArrayUtil::GetArrayDescriptor(int count, ...)\n\t{\n\t\tArrayDescriptor *arr_desc = new ArrayDescriptor(count);\n\n\t\tva_list args;\n\t\tva_start(args, count);\n\n\t\tfor(int i = 0; i < count; i++)\n\t\t\tarr_desc->m_dim[i] = va_arg(args, index_t);\n\n\t\tva_end(args);\n\n\t\treturn *arr_desc;\n\t}\n\n\tArrayDescriptor& ArrayUtil::GetArrayDescriptor(ArrayDescriptor &source)\n\t{\n\t\tArrayDescriptor *arr_desc = new ArrayDescriptor(source);\n\t\treturn *arr_desc;\n\t}\n\n\t// LinearIndexerND implementation\n\n\tLinearIndexer::LinearIndexer(ArrayDescriptor &descriptor)\n\t\t: m_descriptor(descriptor)\n\t{\n\t\tm_pos = new index_t[m_descriptor.m_count];\n\t}\n\n\tLinearIndexer::LinearIndexer(std::vector<index_t> &descriptor)\n\t\t: m_descriptor(descriptor)\n\t{\n\t\tm_pos = new index_t[m_descriptor.m_count];\n\t}\n\n\tLinearIndexer::~LinearIndexer()\n\t{\n\t\tdelete[] m_pos;\n\t}\n\n\tArrayDescriptor& LinearIndexer::GetDescriptor()\n\t{\n\t\treturn m_descriptor;\n\t}\n\n\tindex_t LinearIndexer::GetIndex() const\n\t{\n\t\tindex_t size = 1;\n\t\tindex_t idx = 0;\n\t\tfor(int i = 0; i < m_descriptor.m_count; i++)\n\t\t{\n\t\t\tidx = idx + (m_pos[i] * size);\n\t\t\tsize = size * m_descriptor.m_dim[i];\n\t\t}\n\n\t\treturn idx;\n\t}\n\n\tindex_t LinearIndexer::GetSize() const\n\t{\n\t\tindex_t size = 1;\n\t\tfor(int i = 0; i < m_descriptor.m_count; i++)\n\t\t{\n\t\t\tsize = size * m_descriptor.m_dim[i];\n\t\t}\n\n\t\treturn size;\n\t}\n\n\tindex_t LinearIndexer::GetNeededBufferCapacity(ArrayDescriptor &descriptor)\n\t{\n\t\tindex_t size = 1;\n\t\tfor(int i = 0; i < descriptor.m_count; i++) \n\t\t\tsize *= descriptor.m_dim[i];\n\t\t\n\t\treturn size;\n\t}\n\n\tindex_t LinearIndexer::GetNeededBufferCapacity(std::vector<index_t> &descriptor)\n\t{\n\t\tindex_t size = 1;\n\t\tfor(std::vector<int>::iterator it = descriptor.begin(); it != descriptor.end(); ++it)\n\t\t\tsize *= *it;\n\t\n\t\treturn size;\n\t}\n\n\t// ArrayData implementation\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator>::ArrayData(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\t\tconst TElement &defaulTElement,\n\t\t\t\t\t\t\t\t\t\t\t\tconst TAllocator &allocator)\n\t\t\t\t\t\t\t\t\t\t\t\t: m_data(0),\n\t\t\t\t\t\t\t\t\t\t\t\tm_numElements(LinearIndexer::GetNeededBufferCapacity(descriptor)),\n\t\t\t\t\t\t\t\t\t\t\t\tm_allocator(allocator),\n\t\t\t\t\t\t\t\t\t\t\t\tm_size(-1)\n\t{\n\t\t// TODO Find a better solution\n\t\tCudaDevice::getInstance();\n\n\t\t// MxN matrices will be rounded up to square\n\t\t// So transpose operation can use CUDA optimizations\n\t\t/*index_t elements = 0;\n\t\tif(descriptor.GetNDim() != 2)\n\t\t{\n\t\t\telements = m_numElements;\n\t\t} else\n\t\t{\n\t\t\tm_size = imax(((descriptor.GetDim(0)+(TILE_DIM-1))/TILE_DIM)*TILE_DIM,((descriptor.GetDim(1)+(TILE_DIM-1))/TILE_DIM)*TILE_DIM);\n\t\t\telements = m_size*m_size;\n\t\t}\n\n\t\tm_data = m_allocator.allocate(elements);\n\t\tfor(index_t i = 0; i < elements; i++)\n\t\t\tnew (&m_data[i]) TElement(defaulTElement);*/\n\n\t\tm_data = m_allocator.allocate(m_numElements);\n\t\tfor(index_t i = 0; i < m_numElements; i++)\n\t\t\tnew (&m_data[i]) TElement(defaulTElement);\n\t}\n\n\ttemplate ArrayData<int, std::allocator<int>>::ArrayData(ArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst int &defaulTElement,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<int> &allocator);\n\ttemplate ArrayData<float, std::allocator<float>>::ArrayData(ArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst float &defaulTElement,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<float> &allocator);\n\ttemplate ArrayData<double, std::allocator<double>>::ArrayData(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst double &defaulTElement,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<double> &allocator);\n\ttemplate ArrayData<ComplexFloat, std::allocator<ComplexFloat>>::ArrayData(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst ComplexFloat &defaulTElement,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<ComplexFloat> &allocator);\n\ttemplate ArrayData<ComplexDouble, std::allocator<ComplexDouble>>::ArrayData(ArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst ComplexDouble &defaulTElement,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<ComplexDouble> &allocator);\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator>::ArrayData(\tindex_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\tconst TAllocator &allocator)\n\t\t\t\t\t\t\t\t\t\t\t\t: m_data(0),\n\t\t\t\t\t\t\t\t\t\t\t\tm_numElements(numElements),\n\t\t\t\t\t\t\t\t\t\t\t\tm_allocator(allocator),\n\t\t\t\t\t\t\t\t\t\t\t\tm_size(-1)\n\t{\n\t\t// TODO Find a better solution\n\t\tCudaDevice::getInstance();\n\n\t\tm_data = m_allocator.allocate(m_numElements);\n\t}\n\n\ttemplate ArrayData<int, std::allocator<int>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<int> &allocator);\n\ttemplate ArrayData<float, std::allocator<float>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<float> &allocator);\n\ttemplate ArrayData<double, std::allocator<double>>::ArrayData(\tindex_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<double> &allocator);\n\ttemplate ArrayData<ComplexFloat, std::allocator<ComplexFloat>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<ComplexFloat> &allocator);\n\ttemplate ArrayData<ComplexDouble, std::allocator<ComplexDouble>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::allocator<ComplexDouble> &allocator);\n\n\ttemplate ArrayData<int, struct MappedHostAllocator<int>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst struct MappedHostAllocator<int> &allocator);\n\ttemplate ArrayData<float, struct MappedHostAllocator<float>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst struct MappedHostAllocator<float> &allocator);\n\ttemplate ArrayData<double, struct MappedHostAllocator<double>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst struct MappedHostAllocator<double> &allocator);\n\ttemplate ArrayData<ComplexFloat, struct MappedHostAllocator<ComplexFloat>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst struct MappedHostAllocator<ComplexFloat> &allocator);\n\ttemplate ArrayData<ComplexDouble, struct MappedHostAllocator<ComplexDouble>>::ArrayData(index_t numElements,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst struct MappedHostAllocator<ComplexDouble> &allocator);\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator>::ArrayData(ArrayData &source)\n\t\t\t: m_data(0),\n\t\t\tm_numElements(source.m_numElements),\n\t\t\tm_allocator(source.m_allocator),\n\t\t\tm_size(source.m_size)\n\t{\n\t\t// TODO Find a better solution\n\t\tCudaDevice::getInstance();\n\n\t\tm_data = m_allocator.allocate(m_numElements);\n\t\tfor(index_t i = 0; i < m_numElements; i++)\n\t\t\tnew (&m_data[i]) TElement(source.m_data[i]);\n\n\t\t// MxN matrices will be rounded up to square\n\t\t// So transpose operation can use CUDA optimizations\n\t\t/*index_t elements = (m_size == -1) ? source.m_numElements : (source.m_size*source.m_size);\n\t\tm_data = m_allocator.allocate(elements);\n\t\tfor(index_t i = 0; i < elements; i++)\n\t\t\tnew (&m_data[i]) TElement(source.m_data[i]);*/\n\t}\n\n\ttemplate ArrayData<int>::ArrayData(ArrayData &source);\n\ttemplate ArrayData<float>::ArrayData(ArrayData &source);\n\ttemplate ArrayData<double>::ArrayData(ArrayData &source);\n\ttemplate ArrayData<ComplexFloat>::ArrayData(ArrayData &source);\n\ttemplate ArrayData<ComplexDouble>::ArrayData(ArrayData &source);\n \n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator>::~ArrayData()\n\t{\n\t\tindex_t elments = (m_size == -1) ? m_numElements : (m_size*m_size);\n\t\tfor(index_t i = 0; i < elments; i++)\n\t\t\t(&m_data[i])->TElement::~TElement();\n\t\tm_allocator.deallocate(m_data, elments);\n\t}\n\n\ttemplate ArrayData<int>::~ArrayData();\n\ttemplate ArrayData<float>::~ArrayData();\n\ttemplate ArrayData<double>::~ArrayData();\n\ttemplate ArrayData<ComplexFloat>::~ArrayData();\n\ttemplate ArrayData<ComplexDouble>::~ArrayData();\n\n\ttemplate <typename TElement, class TAllocator>\n\tconst TElement& ArrayData<TElement, TAllocator>::operator [] (index_t index) const\n\t{\n\t\treturn m_data[index];\n\t}\n\n\ttemplate const int& ArrayData<int>::operator [] (index_t index) const;\n\ttemplate const float& ArrayData<float>::operator [] (index_t index) const;\n\ttemplate const double& ArrayData<double>::operator [] (index_t index) const;\n\ttemplate const ComplexFloat& ArrayData<ComplexFloat>::operator [] (index_t index) const;\n\ttemplate const ComplexDouble& ArrayData<ComplexDouble>::operator [] (index_t index) const;\n\n\ttemplate <typename TElement, class TAllocator>\n\tTElement& ArrayData<TElement, TAllocator>::operator [] (index_t index)\n\t{\n\t\treturn m_data[index];\n\t}\n\n\ttemplate int& ArrayData<int>::operator [] (index_t index);\n\ttemplate float& ArrayData<float>::operator [] (index_t index);\n\ttemplate double& ArrayData<double>::operator [] (index_t index);\n\ttemplate ComplexFloat& ArrayData<ComplexFloat>::operator [] (index_t index);\n\ttemplate ComplexDouble& ArrayData<ComplexDouble>::operator [] (index_t index);\n\n\ttemplate <typename TElement, class TAllocator>\n\tbool ArrayData<TElement, TAllocator>::operator == (ArrayData<TElement, TAllocator> &a)\n\t{\n\t\treturn !(*this!=a);\n\t}\n\n\ttemplate bool ArrayData<int>::operator == (ArrayData<int> &a);\n\ttemplate bool ArrayData<float>::operator == (ArrayData<float> &a);\n\ttemplate bool ArrayData<double>::operator == (ArrayData<double> &a);\n\ttemplate bool ArrayData<ComplexFloat>::operator == (ArrayData<ComplexFloat> &a);\n\ttemplate bool ArrayData<ComplexDouble>::operator == (ArrayData<ComplexDouble> &a);\n\n\ttemplate<> bool ArrayData<ComplexFloat>::operator != (ArrayData<ComplexFloat> &a)\n\t{\n\t\tbool auxReal, auxImag;\n\t\tfor(index_t i = 0; i < m_numElements; i++) {\n\t\t\tauxReal = AlmostEqual2sComplement(m_data[i].real(), a.m_data[i].real());\n\t\t\tauxImag = AlmostEqual2sComplement(m_data[i].imag(), a.m_data[i].imag());\n\t\t\tif( auxReal == false || auxImag == false )\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\ttemplate<> bool ArrayData<ComplexDouble>::operator != (ArrayData<ComplexDouble> &a)\n\t{\n\t\tbool auxReal, auxImag;\n\t\tfor(index_t i = 0; i < m_numElements; i++) {\n\t\t\tauxReal = AlmostEqual2sComplement(m_data[i].real(), a.m_data[i].real());\n\t\t\tauxImag = AlmostEqual2sComplement(m_data[i].imag(), a.m_data[i].imag());\n\t\t\tif( auxReal == false || auxImag == false )\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\ttemplate <typename TElement, class TAllocator>\n\tbool ArrayData<TElement, TAllocator>::operator != (ArrayData<TElement, TAllocator> &a)\n\t{\n\t\tfor(index_t i = 0; i < m_numElements; i++) {\n\t\t\tif( AlmostEqual2sComplement(m_data[i], a.m_data[i]) == false )\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t//template<> bool ArrayData<ComplexFloat>::operator != (ArrayData<ComplexFloat> &a)\n\t//{\n\t//\tbool auxReal, auxImag;\n\t//\tfor(index_t i = 0; i < m_numElements; i++) {\n\t//\t\tauxReal = AlmostEqual2sComplement(m_data[i].real(), a.m_data[i].real());\n\t//\t\tauxImag = AlmostEqual2sComplement(m_data[i].imag(), a.m_data[i].imag());\n\t//\t\tif( auxReal == false || auxImag == false )\n\t//\t\t\treturn true;\n\t//\t}\n\t//\n\t//\treturn false;\n\t//}\n\t//\n\t//template<> bool ArrayData<ComplexDouble>::operator != (ArrayData<ComplexDouble> &a)\n\t//{\n\t//\tbool auxReal, auxImag;\n\t//\tfor(index_t i = 0; i < m_numElements; i++) {\n\t//\t\tauxReal = AlmostEqual2sComplement(m_data[i].real(), a.m_data[i].real());\n\t//\t\tauxImag = AlmostEqual2sComplement(m_data[i].imag(), a.m_data[i].imag());\n\t//\t\tif( auxReal == false || auxImag == false )\n\t//\t\t\treturn true;\n\t//\t}\n\t//\n\t//\treturn false;\n\t//}\n\t//\n\t//template <typename TElement, class TAllocator>\n\t//bool ArrayData<TElement, TAllocator>::operator != (ArrayData<TElement, TAllocator> &a)\n\t//{\n\t//\tfor(index_t i = 0; i < m_numElements; i++) {\n\t//\t\tif( AlmostEqual2sComplement(m_data[i], a.m_data[i]) == false )\n\t//\t\t\treturn true;\n\t//\t}\n\t//\treturn false;\n\t//}\n\t////{\n\t////\tfor(index_t i = 0; i < m_numElements; i++) {\n\t////\t\tBOOST_CHECK_CLOSE(m_data[i], a.m_data[i], 0.0001f);\n\t////\t\t\treturn true;\n\t////\t}\n\t////\treturn false;\n\t////}\n\t////{\n\t////\tfor(index_t i = 0; i < m_numElements; i++) {\n\t////\t\tif (m_data[i] != a.m_data[i])\n\t////\t\t\treturn true;\n\t////\t}\n\t////\treturn false;\n\t////}\n\n\t//template bool ArrayData<int>::operator != (ArrayData<int> &a);\n\ttemplate bool ArrayData<float>::operator != (ArrayData<float> &a);\n\ttemplate bool ArrayData<double>::operator != (ArrayData<double> &a);\n\t//template bool ArrayData<ComplexFloat>::operator != (ArrayData<ComplexFloat> &a);\n\t//template bool ArrayData<ComplexDouble>::operator != (ArrayData<ComplexDouble> &a);\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator>& ArrayData<TElement, TAllocator>::operator = (ArrayData<TElement, TAllocator> &a)\n\t{\n\t\ttry\n\t\t{\n\t\t\tequal<TElement>(m_data, a.m_data, m_numElements, Type2Type<TElement>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\ttemplate ArrayData<int>& ArrayData<int>::operator = (ArrayData<int> &a);\n\ttemplate ArrayData<float>& ArrayData<float>::operator = (ArrayData<float> &a);\n\ttemplate ArrayData<double>& ArrayData<double>::operator = (ArrayData<double> &a);\n\ttemplate ArrayData<ComplexFloat>& ArrayData<ComplexFloat>::operator = (ArrayData<ComplexFloat> &a);\n\ttemplate ArrayData<ComplexDouble>& ArrayData<ComplexDouble>::operator = (ArrayData<ComplexDouble> &a);\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator> ArrayData<TElement, TAllocator>::operator - (ArrayData<TElement, TAllocator> &a)\n\t{\n\t\tArrayData<TElement> result(*this);\n\t\n\t\ttry\n\t\t{\n\t\t\tminus<TElement>(result.m_data, m_data, a.m_data, m_numElements, Type2Type<TElement>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate ArrayData<int> ArrayData<int>::operator - (ArrayData<int> &a);\n\ttemplate ArrayData<float> ArrayData<float>::operator - (ArrayData<float> &a);\n\ttemplate ArrayData<double> ArrayData<double>::operator - (ArrayData<double> &a);\n\ttemplate ArrayData<ComplexFloat> ArrayData<ComplexFloat>::operator - (ArrayData<ComplexFloat> &a);\n\ttemplate ArrayData<ComplexDouble> ArrayData<ComplexDouble>::operator - (ArrayData<ComplexDouble> &a);\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator>& ArrayData<TElement, TAllocator>::operator += (ArrayData<TElement, TAllocator> &a)\n\t{\n\t\ttry\n\t\t{\n\t\t\tadd<TElement>(m_data, m_data, a.m_data, m_numElements, Type2Type<TElement>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\ttemplate ArrayData<int>& ArrayData<int>::operator += (ArrayData<int> &a);\n\ttemplate ArrayData<float>& ArrayData<float>::operator += (ArrayData<float> &a);\n\ttemplate ArrayData<double>& ArrayData<double>::operator += (ArrayData<double> &a);\n\ttemplate ArrayData<ComplexFloat>& ArrayData<ComplexFloat>::operator += (ArrayData<ComplexFloat> &a);\n\ttemplate ArrayData<ComplexDouble>& ArrayData<ComplexDouble>::operator += (ArrayData<ComplexDouble> &a);\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator>& ArrayData<TElement, TAllocator>::operator -= (ArrayData<TElement, TAllocator> &a)\n\t{\n\t\ttry\n\t\t{\n\t\t\tminus<TElement>(m_data, m_data, a.m_data, m_numElements, Type2Type<TElement>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\ttemplate ArrayData<int>& ArrayData<int>::operator -= (ArrayData<int> &a);\n\ttemplate ArrayData<float>& ArrayData<float>::operator -= (ArrayData<float> &a);\n\ttemplate ArrayData<double>& ArrayData<double>::operator -= (ArrayData<double> &a);\n\ttemplate ArrayData<ComplexFloat>& ArrayData<ComplexFloat>::operator -= (ArrayData<ComplexFloat> &a);\n\ttemplate ArrayData<ComplexDouble>& ArrayData<ComplexDouble>::operator -= (ArrayData<ComplexDouble> &a);\n\n\ttemplate <typename TElement, class TAllocator>\n\tArrayData<TElement, TAllocator> ArrayData<TElement, TAllocator>::operator + (ArrayData<TElement, TAllocator> &a)\n\t{\n\t\tArrayData<TElement> result(*this);\n\t\n\t\ttry\n\t\t{\n\t\t\tadd<TElement>(result.m_data, m_data, a.m_data, m_numElements, Type2Type<TElement>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate ArrayData<int> ArrayData<int>::operator + (ArrayData<int> &a);\n\ttemplate ArrayData<float> ArrayData<float>::operator + (ArrayData<float> &a);\n\ttemplate ArrayData<double> ArrayData<double>::operator + (ArrayData<double> &a);\n\ttemplate ArrayData<ComplexFloat> ArrayData<ComplexFloat>::operator + (ArrayData<ComplexFloat> &a);\n\ttemplate ArrayData<ComplexDouble> ArrayData<ComplexDouble>::operator + (ArrayData<ComplexDouble> &a);\n\n\ttemplate <typename TElement, class TAllocator>\n\tvoid ArrayData<TElement, TAllocator>::conj()\n\t{\n\t}\n\n\ttemplate void ArrayData<int>::conj();\n\ttemplate void ArrayData<float>::conj();\n\ttemplate void ArrayData<double>::conj();\n\n\tvoid ArrayData<ComplexFloat>::conj()\n\t{\n\t\ttry\n\t\t{\n\t\t\tconjugate(m_data, m_data, m_numElements, Type2Type<ComplexFloat>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\tvoid ArrayData<ComplexDouble>::conj()\n\t{\n\t\ttry\n\t\t{\n\t\t\tconjugate(m_data, m_data, m_numElements, Type2Type<ComplexDouble>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate <typename TElement, class TAllocator>\n\tvoid ArrayData<TElement, TAllocator>::transpose(int width, int height)\n\t{\n\t\ttry\n\t\t{\n\t\t\ttransp<TElement>(m_data, m_data, (width*height), Type2Type<TElement>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate void ArrayData<int>::transpose(int width, int height);\n\ttemplate void ArrayData<float>::transpose(int width, int height);\n\ttemplate void ArrayData<double>::transpose(int width, int height);\n\ttemplate void ArrayData<ComplexFloat>::transpose(int width, int height);\n\ttemplate void ArrayData<ComplexDouble>::transpose(int width, int height);\n\n\ttemplate <typename TElement, class TAllocator>\n\tbool ArrayData<TElement, TAllocator>::AlmostEqual2sComplement(double A, double B)\n\t{\n\t\t// Make sure maxUlps is non-negative and small enough that the\n\t\t// default NAN won't compare as equal to anything.\n\t\tint maxUlps = CONFIDENCE_INTERVAL;\n\t\tdouble maxDiff = CONFIDENCE_INTERVAL_FLOAT;\n\t\tdouble maxRelDiff = 0.01;\n\t\tassert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024);\n\n\t\t// Check if the numbers are really close -- needed\n\t\t// when comparing numbers near zero.\n\t\tdouble diff = fabs(A - B);\n\t\tif (diff <= maxDiff)\n\t\t\treturn true;\n\n\t\tA = fabs(A);\n\t\tB = fabs(B);\n\t\tfloat largest = (B > A) ? B : A;\n \n\t\tif (diff <= largest * maxRelDiff)\n\t\t\treturn true;\n\t\treturn false;\n\n\t\t//int aInt = *(int*)&A;\n\t\t//// Make aInt lexicographically ordered as a twos-complement int\n\t\t//if (aInt < 0)\n\t\t//    aInt = 0x80000000 - aInt;\n\t\t//// Make bInt lexicographically ordered as a twos-complement int\n\t\t//int bInt = *(int*)&B;\n\t\t//if (bInt < 0)\n\t\t//    bInt = 0x80000000 - bInt;\n\t\t//int intDiff = abs(aInt - bInt);\n\t\t//if (intDiff <= maxUlps)\n\t\t//    return true;\n\t\t//return false;\n\t}\n\n\t//template bool ArrayData<int>::AlmostEqual2sComplement(int A, int B);\n\t//template bool ArrayData<float>::AlmostEqual2sComplement(float A, float B);\n\ttemplate bool ArrayData<double>::AlmostEqual2sComplement(double A, double B);\n\t//template bool ArrayData<ComplexFloat>::AlmostEqual2sComplement(ComplexFloat A, ComplexFloat B);\n\t//template bool ArrayData<ComplexDouble>::AlmostEqual2sComplement(ComplexDouble A, ComplexDouble B);\n\n\ttemplate <typename TElement, class TAllocator>\n\tbool ArrayData<TElement, TAllocator>::AlmostEqualRelativeAndAbs(TElement A, TElement B)\n\t{\n\t\t//TElement diff = boost::math::float_distance( A, B );\n\t\t//float maxDiff = 0.01, maxRelDiff = 0.01;\n\t //   // Check if the numbers are really close -- needed\n\t //   // when comparing numbers near zero.\n\t //   TElement diff = fabs(A - B);\n\t //   if (diff <= maxDiff)\n\t //       return true;\n\t //\n\t //   A = fabs(A);\n\t //   B = fabs(B);\n\t //   TElement largest = (B > A) ? B : A;\n\t //\n\t //   if (diff <= largest * maxRelDiff)\n\t //       return true;\n\t\treturn false;\n\t}\n\n\t//template bool ArrayData<int>::AlmostEqualRelativeAndAbs(int A, int B);\n\ttemplate bool ArrayData<float>::AlmostEqualRelativeAndAbs(float A, float B);\n\ttemplate bool ArrayData<double>::AlmostEqualRelativeAndAbs(double A, double B);\n\t//template bool ArrayData<ComplexFloat>::AlmostEqualRelativeAndAbs(ComplexFloat A, ComplexFloat B);\n\t//template bool ArrayData<ComplexDouble>::AlmostEqualRelativeAndAbs(ComplexDouble A, ComplexDouble B);\n\n\ttemplate<> bool ArrayData<ComplexFloat>::check_close(ArrayData<ComplexFloat> a)\n\t{\n\t\tbool auxReal, auxImag;\n\t\tfor(index_t i = 0; i < m_numElements; i++) {\n\t\t\tauxReal = AlmostEqual2sComplement(m_data[i].real(), a.m_data[i].real());\n\t\t\tauxImag = AlmostEqual2sComplement(m_data[i].imag(), a.m_data[i].imag());\n\t\t\tif( auxReal == false || auxImag == false )\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\ttemplate<> bool ArrayData<ComplexDouble>::check_close(ArrayData<ComplexDouble> a)\n\t{\n\t\tbool auxReal, auxImag;\n\t\tfor(index_t i = 0; i < m_numElements; i++) {\n\t\t\tauxReal = AlmostEqual2sComplement(m_data[i].real(), a.m_data[i].real());\n\t\t\tauxImag = AlmostEqual2sComplement(m_data[i].imag(), a.m_data[i].imag());\n\t\t\tif( auxReal == false || auxImag == false )\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\ttemplate <typename TElement, class TAllocator>\n\tbool ArrayData<TElement, TAllocator>::check_close (ArrayData<TElement, TAllocator> a)\n\t{\n\t\tfor(index_t i = 0; i < m_numElements; i++) {\n\t\t\tif( AlmostEqual2sComplement(m_data[i], a.m_data[i]) == false )\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\ttemplate bool ArrayData<int>::check_close(ArrayData<int> a);\n\ttemplate bool ArrayData<float>::check_close(ArrayData<float> a);\n\ttemplate bool ArrayData<double>::check_close(ArrayData<double> a);\n\n\t//template <typename TElement, class TAllocator>\n\t//bool ArrayData<TElement, TAllocator>::areEqualRel( TElement a, TElement b ) \n\t//{\n\t//    return (fabs(a - b) <= std::numeric_limits<TElement>::epsilon * std::max(fabs(a), fabs(b)));\n\t//}\n\t//\n\t//template bool ArrayData<int>::areEqualRel(int a, int b);\n\t//template bool ArrayData<float>::areEqualRel(float a, float b);\n\t//template bool ArrayData<double>::areEqualRel(double a, double b);\n\t//template bool ArrayData<ComplexFloat>::areEqualRel(ComplexFloat a, ComplexFloat b);\n\t//template bool ArrayData<ComplexDouble>::areEqualRel(ComplexDouble a, ComplexDouble b);\n\n\t// Array implementation\n\n\ttemplate <typename TElement>\n\tArray<TElement>::Array(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\tconst TElement& defaulTElement)\n\t\t\t\t\t\t\t: m_data(descriptor, defaulTElement),\n\t\t\t\t\t\t\tm_indexer(NULL),\n\t\t\t\t\t\t\tm_padded(false)\n\t{\n\t\tm_indexer = new LinearIndexer(descriptor);\n\t\n\t\t// TODO Pass description using pointer to avoid extra object instance\n\t\tArrayUtil::ReleaseArrayDescriptor(descriptor);\n\t}\n\n\ttemplate Array<int>::Array(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\tconst int& defaulTElement);\n\ttemplate Array<float>::Array(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\tconst float& defaulTElement);\n\ttemplate Array<double>::Array(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\tconst double& defaulTElement);\n\ttemplate Array<ComplexFloat>::Array(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\tconst ComplexFloat& defaulTElement);\n\ttemplate Array<ComplexDouble>::Array(\tArrayDescriptor &descriptor,\n\t\t\t\t\t\t\t\t\t\t\tconst ComplexDouble& defaulTElement);\n\n\ttemplate <typename TElement>\n\tArray<TElement>::Array(\tArray &source)\n\t\t\t\t\t\t\t: m_data(source.m_data),\n\t\t\t\t\t\t\tm_indexer(NULL),\n\t\t\t\t\t\t\tm_padded(false)\n\t{\n\t\tm_indexer = new LinearIndexer(source.m_indexer->m_descriptor);\n\t}\n\n\ttemplate Array<int>::Array(Array &source);\n\ttemplate Array<float>::Array(Array &source);\n\ttemplate Array<double>::Array(Array &source);\n\ttemplate Array<ComplexFloat>::Array(Array &source);\n\ttemplate Array<ComplexDouble>::Array(Array &source);\n\n\ttemplate <typename TElement>\n\tArray<TElement>::~Array() { delete m_indexer; }\n\n\ttemplate Array<int>::~Array();\n\ttemplate Array<float>::~Array();\n\ttemplate Array<double>::~Array();\n\ttemplate Array<ComplexFloat>::~Array();\n\ttemplate Array<ComplexDouble>::~Array();\n\n\ttemplate <typename TElement>\n\tArrayDescriptor& Array<TElement>::GetDescriptor()\n\t{\n\t\treturn m_indexer->GetDescriptor();\n\t}\n\n\ttemplate ArrayDescriptor& Array<int>::GetDescriptor();\n\ttemplate ArrayDescriptor& Array<float>::GetDescriptor();\n\ttemplate ArrayDescriptor& Array<double>::GetDescriptor();\n\ttemplate ArrayDescriptor& Array<ComplexFloat>::GetDescriptor();\n\ttemplate ArrayDescriptor& Array<ComplexDouble>::GetDescriptor();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator + (Array<TElement> &a)\n\t{\n\t\tArray<TElement> result(*this);\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn result;\n\t\n\t\tcublasOperations<TElement> op;\n\t\tcublasStatus_t stat;\n\t\ttry\n\t\t{\n\t\t\tstat = op.add( this, &a, &result, std::string(\"+\") );\n\t\t\t//stat = op.add_zerocopy( this, &a, &result, std::string(\"+\") );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::operator + (Array<int> &a);\n\ttemplate Array<float> Array<float>::operator + (Array<float> &a);\n\ttemplate Array<double> Array<double>::operator + (Array<double> &a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator + (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator + (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator + (TElement a)\n\t{ \n\t\tArray<TElement> result = *this;\n\t\tfor( int i = 0; i < result.m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] =  (this->m_data.m_data[i]) + a;\n\t\n\t\treturn result; \n\t}\n\n\ttemplate Array<int> Array<int>::operator + (int a);\n\ttemplate Array<float> Array<float>::operator + (float a);\n\ttemplate Array<double> Array<double>::operator + (double a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator + (ComplexFloat a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator + (ComplexDouble a);\n\n\ttemplate <typename TElement>\n\tbool Array<TElement>::operator == (Array<TElement> a)\n\t{\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn false;\n\n\t\tif(m_data != a.m_data)\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\ttemplate bool Array<int>::operator == (Array<int> a);\n\ttemplate bool Array<float>::operator == (Array<float> a);\n\ttemplate bool Array<double>::operator == (Array<double> a);\n\ttemplate bool Array<ComplexFloat>::operator == (Array<ComplexFloat> a);\n\ttemplate bool Array<ComplexDouble>::operator == (Array<ComplexDouble> a);\n\n\ttemplate <typename TElement>\n\tbool Array<TElement>::operator != (Array<TElement> a)\n\t{\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn true;\n\n\t\tif(m_data != a.m_data)\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\ttemplate bool Array<int>::operator != (Array<int> a);\n\ttemplate bool Array<float>::operator != (Array<float> a);\n\ttemplate bool Array<double>::operator != (Array<double> a);\n\ttemplate bool Array<ComplexFloat>::operator != (Array<ComplexFloat> a);\n\ttemplate bool Array<ComplexDouble>::operator != (Array<ComplexDouble> a);\n\n\t//template <typename TElement>\n\t//bool Array<TElement>::operator > (Array<TElement>& a)\n\t//{\n\t//\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t//\t\treturn false;\n\t//\n\t//\tif(m_data > a.m_data)\n\t//\t\treturn true;\n\t//\n\t//\treturn false;\n\t//}\n\t//\n\t//template bool Array<int>::operator > (Array<int>& a);\n\t//template bool Array<float>::operator > (Array<float>& a);\n\t//template bool Array<double>::operator > (Array<double>& a);\n\t//template bool Array<ComplexFloat>::operator > (Array<ComplexFloat>& a);\n\t//template bool Array<ComplexDouble>::operator > (Array<ComplexDouble>& a);\n\t//\n\t//template <typename TElement>\n\t//bool Array<TElement>::operator < (Array<TElement>& a)\n\t//{\n\t//\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t//\t\treturn false;\n\t//\n\t//\tif(m_data < a.m_data)\n\t//\t\treturn true;\n\t//\n\t//\treturn false;\n\t//}\n\t//\n\t//template bool Array<int>::operator < (Array<int>& a);\n\t//template bool Array<float>::operator < (Array<float>& a);\n\t//template bool Array<double>::operator < (Array<double>& a);\n\t//template bool Array<ComplexFloat>::operator < (Array<ComplexFloat>& a);\n\t//template bool Array<ComplexDouble>::operator < (Array<ComplexDouble>& a);\n\t//\n\t//template <typename TElement>\n\t//bool Array<TElement>::operator >= (Array<TElement>& a)\n\t//{\n\t//\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t//\t\treturn false;\n\t//\n\t//\tif(m_data >= a.m_data)\n\t//\t\treturn true;\n\t//\n\t//\treturn false;\n\t//}\n\t//\n\t//template bool Array<int>::operator >= (Array<int>& a);\n\t//template bool Array<float>::operator >= (Array<float>& a);\n\t//template bool Array<double>::operator >= (Array<double>& a);\n\t//template bool Array<ComplexFloat>::operator >= (Array<ComplexFloat>& a);\n\t//template bool Array<ComplexDouble>::operator >= (Array<ComplexDouble>& a);\n\t//\n\t//template <typename TElement>\n\t//bool Array<TElement>::operator <= (Array<TElement>& a)\n\t//{\n\t//\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t//\t\treturn false; // TODO EXIT_FAILURE!\n\t//\n\t//\tif(m_data <= a.m_data)\n\t//\t\treturn true;\n\t//\n\t//\treturn false;\n\t//}\n\t//\n\t//template bool Array<int>::operator <= (Array<int>& a);\n\t//template bool Array<float>::operator <= (Array<float>& a);\n\t//template bool Array<double>::operator <= (Array<double>& a);\n\t//template bool Array<ComplexFloat>::operator <= (Array<ComplexFloat>& a);\n\t//template bool Array<ComplexDouble>::operator <= (Array<ComplexDouble>& a);\n\t\n\ttemplate <typename TElement>\n\tconst TElement& Array<TElement>::operator () (index_t u, ...) const\n\t{\n\t\tva_list args;\n\t\tva_start(args, u);\n\n\t\tm_indexer->m_pos[0] = u;\n\n\t\tint count = m_indexer->m_descriptor.m_count;\n\t\tif(m_padded)\n\t\t{\n\t\t\tm_indexer->m_pos[1] = 0;\n\t\t\tcount--;\n\t\t}\n\n\t\tfor(int i = 1; i < count; i++)\n\t\t\tm_indexer->m_pos[i] = va_arg(args, index_t);\n\n\t\tva_end(args);\n\t\t\n\t\treturn m_data[m_indexer->GetIndex()];\n\t}\n\n\ttemplate const int& Array<int>::operator () (index_t u, ...) const;\n\ttemplate const float& Array<float>::operator () (index_t u, ...) const;\n\ttemplate const double& Array<double>::operator () (index_t u, ...) const;\n\ttemplate const ComplexFloat& Array<ComplexFloat>::operator () (index_t u, ...) const;\n\ttemplate const ComplexDouble& Array<ComplexDouble>::operator () (index_t u, ...) const;\n\n\ttemplate <typename TElement>\n\tTElement& Array<TElement>::operator () (index_t u, ...)\n\t{\n\t\tva_list args;\n\t\tva_start(args, u);\n\n\t\tm_indexer->m_pos[0] = u;\n\n\t\tint count = m_indexer->m_descriptor.m_count;\n\t\tif(m_padded)\n\t\t{\n\t\t\tm_indexer->m_pos[1] = 0;\n\t\t\tcount--;\n\t\t}\n\n\t\tfor(int i = 1; i < count; i++)\n\t\t\tm_indexer->m_pos[i] = va_arg(args, index_t);\n\n\t\tva_end(args);\n\t\t\n\t\treturn m_data[m_indexer->GetIndex()];\n\t}\n\n\ttemplate int& Array<int>::operator () (index_t u, ...);\n\ttemplate float& Array<float>::operator () (index_t u, ...);\n\ttemplate double& Array<double>::operator () (index_t u, ...);\n\ttemplate ComplexFloat& Array<ComplexFloat>::operator () (index_t u, ...);\n\ttemplate ComplexDouble& Array<ComplexDouble>::operator () (index_t u, ...);\n\n\ttemplate <typename TElement>\n\tArray<TElement>& Array<TElement>::operator = (Array<TElement> &a)\n\t{\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn *this;\n\n\t\tm_data = a.m_data;\n\t\t\n\t\treturn *this;\n\t}\n\n\ttemplate Array<int>& Array<int>::operator = (Array<int> &a);\n\ttemplate Array<float>& Array<float>::operator = (Array<float> &a);\n\ttemplate Array<double>& Array<double>::operator = (Array<double> &a);\n\ttemplate Array<ComplexFloat>& Array<ComplexFloat>::operator = (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble>& Array<ComplexDouble>::operator = (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement>& Array<TElement>::operator = (TElement a)\n\t{ \n\t\tfor( int i = 0; i < this->m_data.m_numElements; i++ )\n\t\t\tthis->m_data.m_data[i] = a;\n\t\t\n\t\treturn *this;\n\t}\n\n\ttemplate Array<int>& Array<int>::operator = (int a);\n\ttemplate Array<float>& Array<float>::operator = (float a);\n\ttemplate Array<double>& Array<double>::operator = (double a);\n\ttemplate Array<ComplexFloat>& Array<ComplexFloat>::operator = (ComplexFloat a);\n\ttemplate Array<ComplexDouble>& Array<ComplexDouble>::operator = (ComplexDouble a);\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator - (Array<TElement> &a)\n\t{\n\t\tArray<TElement> result(*this);\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn result;\n\t\n\t\tcublasOperations<TElement> op;\n\t\tcublasStatus_t stat;\n\t\ttry\n\t\t{\n\t\t\tstat = op.add( this, &a, &result, std::string(\"-\") );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::operator - (Array<int> &a);\n\ttemplate Array<float> Array<float>::operator - (Array<float> &a);\n\ttemplate Array<double> Array<double>::operator - (Array<double> &a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator - (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator - (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator - (TElement a)\n\t{ \n\t\tArray<TElement> result = *this;\n\t\tfor( int i = 0; i < result.m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = (this->m_data.m_data[i]) - a;\n\t\n\t\treturn result; \n\t}\n\n\ttemplate Array<int> Array<int>::operator - (int a);\n\ttemplate Array<float> Array<float>::operator - (float a);\n\ttemplate Array<double> Array<double>::operator - (double a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator - (ComplexFloat a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator - (ComplexDouble a);\n\n\t// C = A x B\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator * (Array<TElement> &a)\n\t{\n\t\tif( (m_indexer->GetDescriptor().GetNDim() != 2) || (a.GetDescriptor().GetNDim() != 2) )\n\t\t\tBOOST_ASSERT(\"operation defined for vector and matrices only\\n\");\n\n\t\tif(\t(m_indexer->GetDescriptor().GetDim(1) != a.m_indexer->m_descriptor.GetDim(0)) ||\n\t\t\t\t(m_indexer->GetDescriptor().GetNDim() != 2) ||\n\t\t\t\t\t(a.GetDescriptor().GetNDim() != 2))\n\t\t\treturn *this;\n\t\n\t\tcublasOperations<TElement> op;\n\t\tcublasStatus_t stat = CUBLAS_STATUS_NOT_INITIALIZED;\n\t\tArray<TElement> result( m_indexer->GetDescriptor().GetDim(0), a.m_indexer->GetDescriptor().GetDim(1) );\n\t\t//Array<TElement> result = *this;\n\n\t\ttry\n\t\t{\n\t\t\t// C = A x B\n\t\t\tstat = op.multiply_zerocopy( this, &a, &result );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::operator * (Array<int> &a);\n\ttemplate Array<float> Array<float>::operator * (Array<float> &a);\n\ttemplate Array<double> Array<double>::operator * (Array<double> &a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator * (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator * (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator * (TElement a)\n\t{ \n\t\tArray<TElement> result = *this;\n\t\tfor( int i = 0; i < result.m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] =  (this->m_data.m_data[i])*a;\n\t\n\t\treturn result; \n\t}\n\n\ttemplate Array<int> Array<int>::operator * (int a);\n\ttemplate Array<float> Array<float>::operator * (float a);\n\ttemplate Array<double> Array<double>::operator * (double a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator * (ComplexFloat a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator * (ComplexDouble a);\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator / (Array<TElement> &a)\n\t{\n\t\tif(\t(m_indexer->GetDescriptor().GetDim(1) != a.m_indexer->m_descriptor.GetDim(0)) ||\n\t\t\t\t(m_indexer->GetDescriptor().GetNDim() != 2) ||\n\t\t\t\t\t(a.GetDescriptor().GetNDim() != 2))\n\t\t\treturn *this;\n\n\t\tArray<TElement> result( m_indexer->GetDescriptor().GetDim(0), a.m_indexer->GetDescriptor().GetDim(1) );\n\n\t\ttry\n\t\t{\n\t\t\tresult = (*this)*a.invert();\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::operator / (Array<int> &a);\n\ttemplate Array<float> Array<float>::operator / (Array<float> &a);\n\ttemplate Array<double> Array<double>::operator / (Array<double> &a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator / (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator / (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::operator / (TElement a)\n\t{ \n\t\tArray<TElement> result = *this;\n\t\tfor( int i = 0; i < result.m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] =  (this->m_data.m_data[i])/a;\n\t\n\t\treturn result; \n\t}\n\n\ttemplate Array<int> Array<int>::operator / (int a);\n\ttemplate Array<float> Array<float>::operator / (float a);\n\ttemplate Array<double> Array<double>::operator / (double a);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::operator / (ComplexFloat a);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::operator / (ComplexDouble a);\n\n\t//template <typename TElement>\n\t//Array<TElement> Array<TElement>::operator * (float &a){ return *this; }\n\t//\n\t//template <typename TElement>\n\t//Array<TElement> Array<TElement>::operator * (double &a){ return *this; }\n\n\t//template Array<int> Array<int>::operator * (int &a);\n\t//template Array<float> Array<float>::operator * (int &a);\n\t//template Array<double> Array<double>::operator * (int &a);\n\t//template Array<ComplexFloat> Array<ComplexFloat>::operator * (int &a);\n\t//template Array<ComplexDouble> Array<ComplexDouble>::operator * (int &a);\n\t//template Array<int> Array<int>::operator * (float &a);\n\t//template Array<float> Array<float>::operator * (float &a);\n\t//template Array<double> Array<double>::operator * (float &a);\n\t//template Array<ComplexFloat> Array<ComplexFloat>::operator * (float &a);\n\t//template Array<ComplexDouble> Array<ComplexDouble>::operator * (float &a);\n\t//template Array<int> Array<int>::operator * (double &a);\n\t//template Array<float> Array<float>::operator * (double &a);\n\t//template Array<double> Array<double>::operator * (double &a);\n\t//template Array<ComplexFloat> Array<ComplexFloat>::operator * (double &a);\n\t//template Array<ComplexDouble> Array<ComplexDouble>::operator * (double &a);\n\t//template Array<ComplexFloat> Array<int>::operator * (ComplexFloat &a);\n\t//template Array<ComplexFloat> Array<float>::operator * (ComplexFloat &a);\n\t//template Array<ComplexFloat> Array<double>::operator * (ComplexFloat &a);\n\t//template Array<ComplexFloat> Array<ComplexFloat>::operator * (ComplexFloat &a);\n\t//template Array<ComplexFloat> Array<ComplexDouble>::operator * (ComplexFloat &a);\n\t//template Array<ComplexDouble> Array<int>::operator * (ComplexDouble &a);\n\t//template Array<ComplexDouble> Array<float>::operator * (ComplexDouble &a);\n\t//template Array<ComplexDouble> Array<double>::operator * (ComplexDouble &a);\n\t//template Array<ComplexDouble> Array<ComplexFloat>::operator * (ComplexDouble &a);\n\t//template Array<ComplexDouble> Array<ComplexDouble>::operator * (ComplexDouble &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement>& Array<TElement>::operator += (Array<TElement> &a)\n\t{\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn *this;\n\n\t\t*this = *this + a;\n\t\t//m_data += a.m_data;\n\t\t\n\t\treturn *this;\n\t}\n\n\ttemplate Array<int>& Array<int>::operator += (Array<int> &a);\n\ttemplate Array<float>& Array<float>::operator += (Array<float> &a);\n\ttemplate Array<double>& Array<double>::operator += (Array<double> &a);\n\ttemplate Array<ComplexFloat>& Array<ComplexFloat>::operator += (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble>& Array<ComplexDouble>::operator += (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement>& Array<TElement>::operator -= (Array<TElement> &a)\n\t{\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn *this;\n\n\t\t*this = *this - a;\n\t\t//m_data -= a.m_data;\n\t\t\n\t\treturn *this;\n\t}\n\n\ttemplate Array<int>& Array<int>::operator -= (Array<int> &a);\n\ttemplate Array<float>& Array<float>::operator -= (Array<float> &a);\n\ttemplate Array<double>& Array<double>::operator -= (Array<double> &a);\n\ttemplate Array<ComplexFloat>& Array<ComplexFloat>::operator -= (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble>& Array<ComplexDouble>::operator -= (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement>& Array<TElement>::operator *= (Array<TElement> &a)\n\t{\n\t\tif(\t(m_indexer->GetDescriptor().GetDim(1) != a.m_indexer->m_descriptor.GetDim(0)) ||\n\t\t\t\t(m_indexer->GetDescriptor().GetNDim() != 2) ||\n\t\t\t\t\t(a.GetDescriptor().GetNDim() != 2))\n\t\t\treturn *this;\n\n\t\t// TODO Resize this operand\n\t\t//if((m_indexer->GetDescriptor().GetDim(1) < a.m_indexer->m_descriptor.GetDim(1)))\n\t\t//\treturn *this;\n\n\t\tcublasOperations<TElement> op;\n\t\tcublasStatus_t stat;\n\t\tArray<TElement> aux = *this;\n\t\ttry\n\t\t{\t\n\t\t\tstat = op.multiply( &aux, &a, this );\n\t\t\t//multiply(\tm_data.GetElements(),\n\t\t\t//\t\t\tm_data.GetElements(),\n\t\t\t//\t\t\ta.m_data.GetElements(),\n\t\t\t//\t\t\tm_indexer->GetDescriptor().GetDim(1),\n\t\t\t//\t\t\tm_indexer->GetDescriptor().GetDim(0),\n\t\t\t//\t\t\ta.m_indexer->GetDescriptor().GetDim(1),\n\t\t\t//\t\t\tType2Type<TElement>());\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\ttemplate Array<int>& Array<int>::operator *= (Array<int> &a);\n\ttemplate Array<float>& Array<float>::operator *= (Array<float> &a);\n\ttemplate Array<double>& Array<double>::operator *= (Array<double> &a);\n\ttemplate Array<ComplexFloat>& Array<ComplexFloat>::operator *= (Array<ComplexFloat> &a);\n\ttemplate Array<ComplexDouble>& Array<ComplexDouble>::operator *= (Array<ComplexDouble> &a);\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::transpose()\n\t{\n\t\tif(m_indexer->GetDescriptor().GetNDim() != 2)\n\t\t\treturn *this;\n\n\t\tArray<TElement> result(this->getDim(1),this->getDim(0));\n\t\tcublasOperations<TElement> op;\n\t\tcublasStatus_t stat;\n\t\ttry\n\t\t{\n\t\t\t//CUBLAS_CALL( op.transpose( this, &result ) );\n\t\t\tCUBLAS_CALL( op.transpose_zerocopy( this, &result ) );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t\tresult = *this;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::transpose();\n\ttemplate Array<float> Array<float>::transpose();\n\ttemplate Array<double> Array<double>::transpose();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::transpose();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::transpose();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::conjugate()\n\t{\n\t\treturn this->conj();\n\t}\n\n\ttemplate Array<int> Array<int>::conjugate();\n\ttemplate Array<float> Array<float>::conjugate();\n\ttemplate Array<double> Array<double>::conjugate();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::conjugate();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::conjugate();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::conj()\n\t{\n\t\tArray<TElement> result = *this;\n\t\tresult.m_data.conj();\n\t\treturn result;\n\t}\n\t//{\n\t//\tif(m_indexer->GetDescriptor().GetNDim() != 2)\n\t//\t\treturn *this;\n\t//\n\t//\tcublasOperations<TElement> op;\n\t//\tcublasStatus_t stat;\n\t//\ttry\n\t//\t{\n\t//\t\tstat = op.conjugate( this );\n\t//\t}\n\t//\tcatch(std::exception &e)\n\t//\t{\n\t//\t\tstd::cerr << boost::diagnostic_information(e);\n\t//\t\treturn *this;\n\t//\t}\n\t//}\n\n\ttemplate Array<int> Array<int>::conj();\n\ttemplate Array<float> Array<float>::conj();\n\ttemplate Array<double> Array<double>::conj();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::conj();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::conj();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::hermitian()\n\t{\n\t\tif(m_indexer->GetDescriptor().GetNDim() != 2)\n\t\t\treturn *this;\n\n\t\tcublasOperations<TElement> op;\n\t\tcublasStatus_t stat;\n\t\tArray<TElement> result(this->getDim(1),this->getDim(0));\n\t\ttry\n\t\t{\n\t\t\tCUBLAS_CALL( op.hermitian_zerocopy( this, &result ) );\n\t\t\t//result.print();\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t\tresult = *this;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t//{\n\t//\ttranspose();\n\t//\tconj();\n\t//\treturn *this;\n\t//}\n\n\ttemplate Array<int> Array<int>::hermitian();\n\ttemplate Array<float> Array<float>::hermitian();\n\ttemplate Array<double> Array<double>::hermitian();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::hermitian();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::hermitian();\n\n\t// implementation of determinant\n\n\ttemplate<> ComplexFloat Array<ComplexFloat>::determinant()\n\t{\n\t\tcublasOperations<ComplexFloat> opCublas;\n\t\tcublasStatus_t statCublas;\n\t\tcusolverOperations<ComplexFloat> opCusolver;\n\t\tcusolverStatus_t statCusolver;\n\t\tComplexFloat det = ComplexFloat(1,0);\n\n\t\tif( m_data.m_numElements == 1)\n\t\t\treturn (*this)(0,0);\n\n\t\tArray<ComplexFloat> lu( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, &lu );\n\t\t\tstatCusolver = opCusolver.lu( this, &lu );\n\t\t\n\t\t\tfor( int i = 0; i < m_indexer->GetDescriptor().GetDim(1); i++ )\n\t\t\t\tdet *= lu(i,i);\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn det;\n\t}\n\n\ttemplate<> ComplexDouble Array<ComplexDouble>::determinant()\n\t{\n\t\tcublasOperations<ComplexDouble> opCublas;\n\t\tcublasStatus_t statCublas;\n\t\tcusolverOperations<ComplexDouble> opCusolver;\n\t\tcusolverStatus_t statCusolver;\n\t\tComplexDouble det = ComplexDouble(1,0);\n\n\t\tif( m_data.m_numElements == 1)\n\t\t\treturn (*this)(0,0);\n\n\t\tArray<ComplexDouble> lu( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, &lu );\n\t\t\tstatCusolver = opCusolver.lu( this, &lu );\n\t\t\n\t\t\tfor( int i = 0; i < m_indexer->GetDescriptor().GetDim(1); i++ )\n\t\t\t\tdet *= lu(i,i);\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn det;\n\t}\n\n\ttemplate <typename TElement>\n\tTElement Array<TElement>::determinant()\n\t{\n\t\tcublasOperations<TElement> opCublas;\n\t\tcublasStatus_t statCublas;\n\t\tcusolverOperations<TElement> opCusolver;\n\t\tcusolverStatus_t statCusolver;\n\t\tTElement det = 1;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t\treturn (*this)(0,0);\n\n\t\tArray<TElement> lu( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, &lu );\n\t\t\tstatCusolver = opCusolver.lu( this, &lu );\n\t\t\n\t\t\t//if( statCublas == CUBLAS_STATUS_SUCCESS ) {\n\t\t\tif( statCusolver == CUSOLVER_STATUS_SUCCESS ) {\n\t\t\t\tfor( int i = 0; i < m_indexer->GetDescriptor().GetDim(1); i++ )\n\t\t\t\t\tdet *= lu(i,i);\n\t\t\t}\n\t\t\telse\n\t\t\t\tdet = 0;\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn det;\n\t}\n\n\ttemplate int Array<int>::determinant();\n\ttemplate float Array<float>::determinant();\n\ttemplate double Array<double>::determinant();\n\n\t// implementation of lu decomposition\n\n\ttemplate<> void Array<ComplexFloat>::lu( Array<ComplexFloat> *L, Array<ComplexFloat> *U, Array<ComplexFloat> *P )\n\t{\n\t\tcublasOperations<ComplexFloat> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<ComplexFloat> opCusolver;\n\t\tcusolverStatus_t  statCusolver;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*L)(0) = ComplexFloat(1,0);\n\t\t\t(*U)(0) = (*this)(0);\n\t\t\treturn;\n\t\t}\n\n\t\t*P = eye<ComplexFloat>( this->GetDescriptor().GetDim(0) );\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, U, P );\n\t\t\t//if( statCublas == CUBLAS_STATUS_SUCCESS )\n\t\t\tstatCusolver = opCusolver.lu( this, U, P );\n\t\t\tif( statCusolver == CUSOLVER_STATUS_SUCCESS )\n\t\t\t{\n\t\t\t\t*L = eye<ComplexFloat>( std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t\tfor( int i = 0; i < U->getDim(0); i++ ) {\n\t\t\t\t\tfor( int j = 0; j < i; j++ )\n\t\t\t\t\t\t(*L)( i, j ) = (*U)( i, j );\n\t\t\t\t}\n\n\t\t\t\tzeros_under_diag( U->data(), std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::cout << \"lu decomposition failed\" << std::endl;\n\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate<> void Array<ComplexDouble>::lu( Array<ComplexDouble> *L, Array<ComplexDouble> *U, Array<ComplexDouble> *P )\n\t{\n\t\tcublasOperations<ComplexDouble> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<ComplexDouble> opCusolver;\n\t\tcusolverStatus_t  statCusolver;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*L)(0) = ComplexDouble(1,0);\n\t\t\t(*U)(0) = (*this)(0);\n\t\t\treturn;\n\t\t}\n\n\t\t*P = eye<ComplexDouble>( this->GetDescriptor().GetDim(0) );\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, U, P );\n\t\t\t//if( statCublas == CUBLAS_STATUS_SUCCESS )\n\t\t\tstatCusolver = opCusolver.lu( this, U, P );\n\t\t\tif( statCusolver == CUSOLVER_STATUS_SUCCESS )\n\t\t\t{\n\t\t\t\t*L = eye<ComplexDouble>( std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t\tfor( int i = 0; i < U->getDim(0); i++ ) {\n\t\t\t\t\tfor( int j = 0; j < i; j++ )\n\t\t\t\t\t\t(*L)( i, j ) = (*U)( i, j );\n\t\t\t\t}\n\n\t\t\t\tzeros_under_diag( U->data(), std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::cout << \"lu decomposition failed\" << std::endl;\n\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate <typename TElement>\n\tvoid Array<TElement>::lu( Array<TElement> *L, Array<TElement> *U, Array<TElement> *P )\n\t{\n\t\tcublasOperations<TElement> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<TElement> opCusolver;\n\t\tcusolverStatus_t  statCusolver;\n\n\t\tTElement det = 1;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*L)(0) = 1;\n\t\t\t(*U)(0) = (*this)(0);\n\t\t\treturn;\n\t\t}\n\n\t\t*P = eye<TElement>( this->GetDescriptor().GetDim(0) );\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, U, P );\n\t\t\t//if( statCublas == CUBLAS_STATUS_SUCCESS )\n\t\t\tstatCusolver = opCusolver.lu( this, U, P );\n\t\t\tif( statCusolver == CUSOLVER_STATUS_SUCCESS )\n\t\t\t{\n\t\t\t\t*L = eye<TElement>( std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t\tfor( int i = 0; i < U->getDim(0); i++ ) {\n\t\t\t\t\tfor( int j = 0; j < i; j++ )\n\t\t\t\t\t\t(*L)( i, j ) = (*U)( i, j );\n\t\t\t\t}\n\n\t\t\t\tzeros_under_diag( U->data(), std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::cout << \"lu decomposition failed\" << std::endl;\n\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate void Array<int>::lu( Array<int> *L, Array<int> *U, Array<int> *P );\n\ttemplate void Array<float>::lu( Array<float> *L, Array<float> *U, Array<float> *P );\n\ttemplate void Array<double>::lu( Array<double> *L, Array<double> *U, Array<double> *P );\n\n\ttemplate<> void Array<ComplexFloat>::lu( Array<ComplexFloat> *L, Array<ComplexFloat> *U )\n\t{\n\t\tcublasOperations<ComplexFloat> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<ComplexFloat> opCusolver;\n\t\tcusolverStatus_t  statCusolver;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*L)(0) = ComplexFloat(1,0);\n\t\t\t(*U)(0) = (*this)(0);\n\t\t\treturn;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, U );\n\t\t\t//if( statCublas == CUBLAS_STATUS_SUCCESS )\n\t\t\tstatCusolver = opCusolver.lu( this, U );\n\t\t\tif( statCusolver == CUSOLVER_STATUS_SUCCESS )\n\t\t\t{\n\t\t\t\t*L = eye<ComplexFloat>( std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t\tfor( int i = 0; i < U->getDim(0); i++ ) {\n\t\t\t\t\tfor( int j = 0; j < i; j++ )\n\t\t\t\t\t\t(*L)( i, j ) = (*U)( i, j );\n\t\t\t\t}\n\n\t\t\t\tzeros_under_diag( U->data(), std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::cout << \"lu decomposition failed\" << std::endl;\n\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate<> void Array<ComplexDouble>::lu( Array<ComplexDouble> *L, Array<ComplexDouble> *U )\n\t{\n\t\tcublasOperations<ComplexDouble> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<ComplexDouble> opCusolver;\n\t\tcusolverStatus_t  statCusolver;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*L)(0) = ComplexDouble(1,0);\n\t\t\t(*U)(0) = (*this)(0);\n\t\t\treturn;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, U );\n\t\t\t//if( statCublas == CUBLAS_STATUS_SUCCESS )\n\t\t\tstatCusolver = opCusolver.lu( this, U );\n\t\t\tif( statCusolver == CUSOLVER_STATUS_SUCCESS )\n\t\t\t{\n\t\t\t\t*L = eye<ComplexDouble>( std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t\tfor( int i = 0; i < U->getDim(0); i++ ) {\n\t\t\t\t\tfor( int j = 0; j < i; j++ )\n\t\t\t\t\t\t(*L)( i, j ) = (*U)( i, j );\n\t\t\t\t}\n\n\t\t\t\tzeros_under_diag( U->data(), std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::cout << \"lu decomposition failed\" << std::endl;\n\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate <typename TElement>\n\tvoid Array<TElement>::lu( Array<TElement> *L, Array<TElement> *U )\n\t{\n\t\tcublasOperations<TElement> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<TElement> opCusolver;\n\t\tcusolverStatus_t  statCusolver;\n\n\t\tTElement det = 1;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*L)(0) = 1;\n\t\t\t(*U)(0) = (*this)(0);\n\t\t\treturn;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.lu( this, U );\n\t\t\t//if( statCublas == CUBLAS_STATUS_SUCCESS )\n\t\t\tstatCusolver = opCusolver.lu( this, U );\n\t\t\tif( statCusolver == CUSOLVER_STATUS_SUCCESS )\n\t\t\t{\n\t\t\t\t*L = eye<TElement>( std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t\tfor( int i = 0; i < U->getDim(0); i++ ) {\n\t\t\t\t\tfor( int j = 0; j < i; j++ )\n\t\t\t\t\t\t(*L)( i, j ) = (*U)( i, j );\n\t\t\t\t}\n\n\t\t\t\tzeros_under_diag( U->data(), std::min(U->getDim(0),U->getDim(1)) );\n\t\t\t}\n\t\t\telse\n\t\t\t\tstd::cout << \"lu decomposition failed\" << std::endl;\n\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate void Array<int>::lu( Array<int> *L, Array<int> *U );\n\ttemplate void Array<float>::lu( Array<float> *L, Array<float> *U );\n\ttemplate void Array<double>::lu( Array<double> *L, Array<double> *U );\n\n\t// implementation of invert\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::invert()\n\t{\n\t\tcublasOperations<TElement> opCublas;\n\t\tcublasStatus_t statCublas = CUBLAS_STATUS_SUCCESS;\n\n\t\tcusolverOperations<TElement> opCusolver;\n\t\tcusolverStatus_t  statCusolver = CUSOLVER_STATUS_SUCCESS;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\tArray<TElement> result(1);\n\t\t\tresult(0) = (TElement)1.0/(*this)(0);\n\t\t\treturn result;\n\t\t}\n\t\n\t\tArray<TElement> result( this->getDim(0), this->getDim(1) );\n\n\t\ttry\n\t\t{\n\t\t\t//statCusolver = opCusolver.invert_zerocopy( &result, this );\n\t\t\tstatCusolver = opCusolver.invert( &result, this );\n\t\t\t//statCublas = opCublas.invert_zerocopy( &result, this );\n\t\t\t//statCublas = opCublas.invert( &result, this );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\tif( statCublas != CUBLAS_STATUS_SUCCESS || statCusolver != CUSOLVER_STATUS_SUCCESS )\n\t\t\tresult = *this;\n\n\t\t//result.print();\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::invert();\n\ttemplate Array<float> Array<float>::invert();\n\ttemplate Array<double> Array<double>::invert();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::invert();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::invert();\n\n\t// implementation of ls solution\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::ls( Array<TElement> *A )\n\t{\n\t\tcublasOperations<TElement> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<TElement> opCusolver;\n\t\tcusolverStatus_t statCusolver;\n\t\n\t\tArray<TElement> result( A->GetDescriptor().GetDim( 1 ), this->GetDescriptor().GetDim( 1 ) );\n\t\tArray<TElement> aux = *this;\n\n\t\ttry\n\t\t{\n\t\t\tstatCublas = opCublas.ls( A, &result, &aux );\n\t\t\t//statCusolver = opCusolver.ls( A, &result, &aux );\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::ls( Array<int> *A );\n\ttemplate Array<float> Array<float>::ls( Array<float> *A );\n\ttemplate Array<double> Array<double>::ls( Array<double> *A );\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::ls( Array<ComplexFloat> *A );\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::ls( Array<ComplexDouble> *A );\n\n\t// implementation of detrend\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::detrend()\n\t{\n\t\tArray<TElement> x( this->GetDescriptor().GetDim(0), 2 );\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\t\tArray<TElement> aux( this->GetDescriptor().GetDim(0) );\n\n\t\tfor( int i = 0; i < this->GetDescriptor().GetDim(1); i++ ) {\n\n\t\t\tfor( int j = 0; j < x.GetDescriptor().GetDim(0); j++ ) {\n\t\t\t\taux(j) = (*this)(j,i);\n\t\t\t\tx(j,0) = j;\n\t\t\t\tx(j,1) = 1;\n\t\t\t}\n\n\t\t\tArray<TElement> p = aux.ls( &x );\n\t\t\taux = aux - x*p;\n\n\t\t\tfor( int j = 0; j < x.GetDescriptor().GetDim(0); j++ )\n\t\t\t\tresult(j,i) = aux(j);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::detrend();\n\ttemplate Array<float> Array<float>::detrend();\n\ttemplate Array<double> Array<double>::detrend();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::detrend();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::detrend();\n\n\t// implementation of diff\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::diff()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0) - 1, this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < this->GetDescriptor().GetDim(1); i++ ) {\n\t\t\tfor( int j = 0; j < this->GetDescriptor().GetDim(0) - 1; j++ )\n\t\t\t\tresult(j,i) = (*this)(j+1,i) - (*this)(j,i);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::diff();\n\ttemplate Array<float> Array<float>::diff();\n\ttemplate Array<double> Array<double>::diff();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::diff();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::diff();\n\n\t// implementation of minor\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::minor( const int row, const int column )\n\t{\n\t\tif(m_indexer->GetDescriptor().GetNDim() != 2 ||\n\t\t   !( row >= 0 && row < m_indexer->GetDescriptor().GetDim(0) && column >= 0 && column < m_indexer->GetDescriptor().GetDim(1) ))\n\t\t\treturn *this;\n\t\n\t\tint dimRows = m_indexer->GetDescriptor().GetDim(0);\n\t\tint dimColumns = m_indexer->GetDescriptor().GetDim(1);\n\t \n\t\tArray<TElement> res( dimRows - 1, dimColumns - 1 );\n\t\ttry\n\t\t{   for ( int c = 0; c < m_indexer->GetDescriptor().GetDim(1); c++ )\n\t\t\t{\n\t\t\t\tif( c == column )\n\t\t\t\t\tcontinue;\n\t\t\t\tfor ( int r = 0; r < m_indexer->GetDescriptor().GetDim(0); r++ )\n\t\t\t\t{\n\t\t\t\t\tif( r == row )\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tres( r - ( r > row ), ( c - ( c > column) ) ) = m_data[ c*m_indexer->GetDescriptor().GetDim(0) + r ];\n\t\t\t\t}\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t\n\t\treturn res;\n\t}\n\n\ttemplate Array<int> Array<int>::minor(const int row, const int column);\n\ttemplate Array<float> Array<float>::minor(int row, const int column);\n\ttemplate Array<double> Array<double>::minor(const int row, const int column);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::minor(const int row, const int column);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::minor(const int row, const int column);\n\n\t// implementation of print\n\n\ttemplate <typename TElement>\n\tvoid Array<TElement>::print()\n\t{\n\t\tstd::cout << std::endl;\n\t\tswitch(GetDescriptor().GetNDim())\n\t\t{\n\t\t\tcase 1:\n\t\t\t\tfor(int i = 0; i < GetDescriptor().GetDim(0); i++)\n\t\t\t\t\tstd::cout << (*this)(i) << \" \";\t\t\t\n\t\t\t\tstd::cout << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tfor(int i = 0; i < GetDescriptor().GetDim(0); i++)\n\t\t\t\t{\n\t\t\t\t\tfor(int j = 0; j < GetDescriptor().GetDim(1); j++)\n\t\t\t\t\t\tstd::cout << (*this)(i, j) << \" \";\t\t\t\n\t\t\t\t\tstd::cout << std::endl;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tfor(int i = 0; i < GetDescriptor().GetDim(0); i++)\n\t\t\t\t{\n\t\t\t\t\tfor(int j = 0; j < GetDescriptor().GetDim(1); j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int k = 0; k < GetDescriptor().GetDim(2); k++)\n\t\t\t\t\t\t\tstd::cout << (*this)(i, j, k) << \" \";\t\t\t\n\t\t\t\t\t\tstd::cout << std::endl;\n\t\t\t\t\t}\n\t\t\t\t\tstd::cout << std::endl;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\t\n\t\tstd::cout << std::endl;\n\n\t\treturn;\n\t}\n\n\ttemplate void Array<int>::print();\n\ttemplate void Array<float>::print();\n\ttemplate void Array<double>::print();\n\ttemplate void Array<ComplexFloat>::print();\n\ttemplate void Array<ComplexDouble>::print();\n\n\t// implementation of norm\n\n\ttemplate <typename TElement>\n\tTElement Array<TElement>::norm()\n\t{\n\t\tif(\t(m_indexer->GetDescriptor().GetDim(1) != 1 &&\n\t\t\t m_indexer->GetDescriptor().GetDim(0) != 1) ||\n\t\t\t(m_indexer->GetDescriptor().GetNDim() != 2) )\n\t\t\treturn -1;\n\t\n\t\tcublasStatus_t stat = CUBLAS_STATUS_NOT_INITIALIZED;\n\t\tArray<TElement> A = *this;\n\t\tArray<TElement> B = this->hermitian();\n\t\tArray<TElement> result( 1 );\n\n\t\tif( A.GetDescriptor().GetDim(0) == 1 )\n\t\t\tresult = A*B;\n\t\telse\n\t\t\tresult = B*A;\n\n\t\treturn std::sqrt( result(0) );\n\t}\n\n\ttemplate int Array<int>::norm();\n\ttemplate float Array<float>::norm();\n\ttemplate double Array<double>::norm();\n\ttemplate ComplexFloat Array<ComplexFloat>::norm();\n\ttemplate ComplexDouble Array<ComplexDouble>::norm();\n\n\t// implementation of check_close\n\n\ttemplate <typename TElement>\n\tbool Array<TElement>::check_close(Array<TElement> a)\n\t{\t\n\t\tif(m_indexer->m_descriptor != a.m_indexer->m_descriptor)\n\t\t\treturn true;\n\n\t\tif( !m_data.check_close( a.m_data ) )\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\ttemplate bool Array<int>::check_close(Array<int> a);\n\ttemplate bool Array<float>::check_close(Array<float> a);\n\ttemplate bool Array<double>::check_close(Array<double> a);\n\ttemplate bool Array<ComplexFloat>::check_close(Array<ComplexFloat> a);\n\ttemplate bool Array<ComplexDouble>::check_close(Array<ComplexDouble> a);\n\n\t// implementation of fft\n\n\ttemplate<> Array<ComplexFloat> Array<ComplexFloat>::fft()\n\t{\n\t\tcufftOperations<ComplexFloat> op;\n\t\tcufftResult_t stat;\n\t\tArray<ComplexFloat> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\t\n\t\tstat = op.fft_stream( this, &result );\n\t\treturn result;\n\t}\n\n\ttemplate<> Array<ComplexDouble> Array<ComplexDouble>::fft()\n\t{\n\t\tcufftOperations<ComplexDouble> op;\n\t\tcufftResult_t stat;\n\t\tArray<ComplexDouble> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tstat = op.fft_stream( this, &result );\n\t\treturn result;\n\t}\n\n\t// implementation of trigonometric functions\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::sind()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = boost::math::sin_pi(this->m_data.m_data[i]/180);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::sind();\n\ttemplate Array<double> Array<double>::sind();\n\t//template Array<ComplexFloat> Array<ComplexFloat>::sind();\n\t//template Array<ComplexDouble> Array<ComplexDouble>::sind();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::sin()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = boost::math::sin_pi(this->m_data.m_data[i]/boost::math::constants::pi<TElement>());\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::sin();\n\ttemplate Array<double> Array<double>::sin();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::cosd()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = boost::math::cos_pi(this->m_data.m_data[i]/180);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::cosd();\n\ttemplate Array<double> Array<double>::cosd();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::cos()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = boost::math::cos_pi(this->m_data.m_data[i]/boost::math::constants::pi<TElement>());\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::cos();\n\ttemplate Array<double> Array<double>::cos();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::tand()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = boost::math::sin_pi(this->m_data.m_data[i]/180)/boost::math::cos_pi(this->m_data.m_data[i]/180);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::tand();\n\ttemplate Array<double> Array<double>::tand();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::tan()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = boost::math::sin_pi(this->m_data.m_data[i]/boost::math::constants::pi<TElement>())/boost::math::cos_pi(this->m_data.m_data[i]/boost::math::constants::pi<TElement>());\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::tan();\n\ttemplate Array<double> Array<double>::tan();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::asind()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = 180/boost::math::constants::pi<TElement>()*std::asin(this->m_data.m_data[i]);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::asind();\n\ttemplate Array<double> Array<double>::asind();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::asin()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = std::asin(this->m_data.m_data[i]);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::asin();\n\ttemplate Array<double> Array<double>::asin();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::acosd()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = 180/boost::math::constants::pi<TElement>()*std::acos(this->m_data.m_data[i]);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::acosd();\n\ttemplate Array<double> Array<double>::acosd();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::acos()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = std::acos(this->m_data.m_data[i]);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::acos();\n\ttemplate Array<double> Array<double>::acos();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::atand()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = 180/boost::math::constants::pi<TElement>()*std::atan(this->m_data.m_data[i]);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::atand();\n\ttemplate Array<double> Array<double>::atand();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::atan()\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim(0), this->GetDescriptor().GetDim(1) );\n\n\t\tfor( int i = 0; i < m_data.m_numElements; i++ )\n\t\t\tresult.m_data.m_data[i] = std::atan(this->m_data.m_data[i]);\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::atan();\n\ttemplate Array<double> Array<double>::atan();\n\n\t// implementation of getColumn\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::getColumn( index_t col )\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim( 0 ) );\n\n\t\tfor( int i = 0; i < this->GetDescriptor().GetDim( 0 ); i++ )\n\t\t\tresult( i ) = (*this)( i, col );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::getColumn(index_t col);\n\ttemplate Array<float> Array<float>::getColumn(index_t col);\n\ttemplate Array<double> Array<double>::getColumn(index_t col);\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::getColumn(index_t col);\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::getColumn(index_t col);\n\n\t// implementation of qr decomposition\n\n\ttemplate <typename TElement>\n\tvoid Array<TElement>::qr( Array<TElement> *Q, Array<TElement> *R )\n\t{\n\t\tcublasOperations<TElement> opCublas;\n\t\tcublasStatus_t statCublas;\n\n\t\tcusolverOperations<TElement> opCusolver;\n\t\tcusolverStatus_t statCusolver;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*Q)(0) = 1;\n\t\t\t(*R)(0) = (*this)(0);\n\t\t\treturn;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t//statCublas = opCublas.qr( this, Q, R );\n\t\t\t//if( statCublas != CUBLAS_STATUS_SUCCESS )\n\t\t\t//\tstd::cout << \"qr decomposition failed\" << std::endl;\n\t\t\t\t\t\t\n\t\t\tstatCusolver = opCusolver.qr( this, Q, R );\n\t\t\t// statCusolver = opCusolver.qr_zerocopy( this, Q, R );\n\t\t\tif( statCusolver != CUSOLVER_STATUS_SUCCESS )\n\t\t\t\tstd::cout << \"qr decomposition failed\" << std::endl;\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t}\n\n\ttemplate void Array<int>::qr( Array<int> *Q, Array<int> *R );\n\ttemplate void Array<float>::qr( Array<float> *Q, Array<float> *R );\n\ttemplate void Array<double>::qr( Array<double> *Q, Array<double> *R );\n\ttemplate void Array<ComplexFloat>::qr( Array<ComplexFloat> *Q, Array<ComplexFloat> *R );\n\ttemplate void Array<ComplexDouble>::qr( Array<ComplexDouble> *Q, Array<ComplexDouble> *R );\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::eig( Array<TElement> *eigenvectors )\n\t{\n\t\tArray<TElement> result( this->GetDescriptor().GetDim( 0 ) );\n\t\tArray<TElement> aux = *this;\n\n\t\tcublasOperations<TElement> opCublas;\n\t\tmixedOperations<TElement> opMixed;\n\t\tcublasStatus_t stat;\n\n\t\tif( m_data.m_numElements == 1)\n\t\t{\n\t\t\t(*eigenvectors)(0) = 1;\n\t\t\tresult(0) = (*this)(0);\n\t\t\treturn result;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t//stat = opCublas.eig( &aux, eigenvectors );\n\t\t\tstat = opMixed.eig( &aux, eigenvectors );\n\t\t\tif( stat != CUBLAS_STATUS_SUCCESS )\n\t\t\t\tstd::cout << \"eigenvalues/eigenvectors calculation failed\" << std::endl;\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor( int i = 0; i < this->GetDescriptor().GetDim(0); i++ )\n\t\t\t\t\tresult(i) = aux( i, i );\n\t\t\t}\n\t\t}\n\t\tcatch(std::exception &e)\n\t\t{\n\t\t\tstd::cerr << boost::diagnostic_information(e);\n\t\t}\n\t\n\t\treturn result;\n\t}\n\n\ttemplate Array<int> Array<int>::eig( Array<int> *eigenvectors );\n\ttemplate Array<float> Array<float>::eig( Array<float> *eigenvectors );\n\ttemplate Array<double> Array<double>::eig( Array<double> *eigenvectors );\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::eig( Array<ComplexFloat> *eigenvectors );\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::eig( Array<ComplexDouble> *eigenvectors );\n\n\ttemplate <typename TElement>\n\tvoid Array<TElement>::array2cuSparseCooMatrix( int n, int nnz, int *cooRowIndexHostPtr, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int *cooColIndexHostPtr, TElement *cooValHostPtr )\n\t{\n\t\tcooRowIndexHostPtr = (int *)malloc(nnz*sizeof(cooRowIndexHostPtr[0])); \n\t\tcooColIndexHostPtr = (int *)malloc(nnz*sizeof(cooColIndexHostPtr[0])); \n\t\tcooValHostPtr = (TElement *)malloc(nnz*sizeof(cooValHostPtr[0])); \n\t\tif ((!cooRowIndexHostPtr) || \n\t\t\t(!cooColIndexHostPtr) || \n\t\t\t(!cooValHostPtr))\n\t\t{ \n\t\t\tprintf(\"Host malloc failed (matrix)\\n\"); \n\t\t\texit(-1); \n\t\t}\n\n\t\tint N = this->GetDescriptor().GetDim(0);\n\t\tint row = 0, col = 0, counter = 0;\n\t\tfor (int i = 0; i < this->m_data.m_numElements; i++ ) {\n\t\t\tif( this->m_data.m_data[i] != 0 ) {\n\t\t\t\tcooColIndexHostPtr[counter] = i/this->GetDescriptor().GetDim(1);\n\t\t\t\tcooRowIndexHostPtr[counter] = i%this->GetDescriptor().GetDim(0);\n\t\t\t\tcooValHostPtr[counter++] = this->m_data.m_data[i];\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate void Array<int>::array2cuSparseCooMatrix( int n, int nnz, int *cooRowIndexHostPtr, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int *cooColIndexHostPtr, int *cooValHostPtr );\n\ttemplate void Array<float>::array2cuSparseCooMatrix( int n, int nnz, int *cooRowIndexHostPtr, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int *cooColIndexHostPtr, float *cooValHostPtr );\n\ttemplate void Array<double>::array2cuSparseCooMatrix( int n, int nnz, int *cooRowIndexHostPtr, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int *cooColIndexHostPtr, double *cooValHostPtr );\n\t//template void Array<ComplexFloat>::array2cuSparseCooMatrix( int n, int nnz, int *cooRowIndexHostPtr, \n\t//\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int *cooColIndexHostPtr, ComplexFloat *cooValHostPtr );\n\t//template void Array<ComplexDouble>::array2cuSparseCooMatrix( int n, int nnz, int *cooRowIndexHostPtr, \n\t//\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int *cooColIndexHostPtr, ComplexDouble *cooValHostPtr );\n\n\ttemplate <typename TElement>\n\tstd::string Array<TElement>::arrayname2str()\n\t{\n\t\treturn VAR_NAME_PRINTER(*this);\n\t}\n\n\ttemplate std::string Array<float>::arrayname2str();\n\ttemplate std::string Array<double>::arrayname2str();\n\ttemplate std::string Array<ComplexFloat>::arrayname2str();\n\ttemplate std::string Array<ComplexDouble>::arrayname2str();\n\n\ttemplate <typename TElement>\n\tvoid Array<TElement>::write2file( std::string s )\n\t{\n\t\tstd::ofstream myfile;\n\t\tmyfile.open( s );\n\t\tif( myfile.good() )\n\t\t{\n\t\t\tfor( int i = 0; i < this->GetDescriptor().GetDim( 0 ); i++ ) {\n\t\t\t\tfor( int j = 0; j < this->GetDescriptor().GetDim( 1 ); j++ )\n\t\t\t\t\tmyfile << (*this)( i, j ) << \" \";\n\t\t\t\tmyfile << std::endl;\n\t\t\t}\n\n\t\t\tmyfile.close();\n\t\t}\n\t}\n\n\ttemplate void Array<float>::write2file( std::string s );\n\ttemplate void Array<double>::write2file( std::string s );\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::submatrix( const index_t rowBegin,\n\t\t\t\t\t\t\t\t\t\t\t\tconst index_t rowEnd, \n\t\t\t\t\t\t\t\t\t\t\t\tconst index_t colBegin, \n\t\t\t\t\t\t\t\t\t\t\t\tconst index_t colEnd )\n\t{\n\t\tif( rowEnd < rowBegin || colEnd < colBegin ) {\n\t\t\tstd::cout << \"invalid paramenters for submatrix function\" << std::endl;\n\t\t\texit(-23);\n\t\t}\n\n\t\tArray<TElement> result( rowEnd - rowBegin + 1, colEnd - colBegin + 1 );\n\t\tfor( int i = rowBegin; i <= rowEnd; i++ ) {\n\t\t\tfor( int j = colBegin; j <= colEnd; j++ )\n\t\t\t\tresult( i - rowBegin, j - colBegin ) = (*this)( i, j );\n\t\t}\n\n\t\treturn result;\n\t}\n\t\n\ttemplate Array<int> Array<int>::submatrix( index_t rowBegin, index_t rowEnd, index_t colBegin, index_t colEnd );\n\ttemplate Array<float> Array<float>::submatrix( index_t rowBegin, index_t rowEnd, index_t colBegin, index_t colEnd );\n\ttemplate Array<double> Array<double>::submatrix( index_t rowBegin, index_t rowEnd, index_t colBegin, index_t colEnd );\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::submatrix( index_t rowBegin, index_t rowEnd, index_t colBegin, index_t colEnd );\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::submatrix( index_t rowBegin, index_t rowEnd, index_t colBegin, index_t colEnd );\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::max()\n\t{\n\t\tTElement *d_vec;\n\t\tArray<TElement> result( 1, this->GetDescriptor().GetDim( 1 ) );\n\t\tint rows = this->GetDescriptor().GetDim( 0 );\n\n\t\tCUDA_CALL( cudaMalloc((void**)&d_vec, rows * sizeof(TElement)) );\n\n\t\tTElement *pos = &(this->m_data.m_data[0]);\n\t\tint auxIdx;\n\n\t\tfor( int i = 0; i < this->GetDescriptor().GetDim( 1 ); i++ )\n\t\t{\n\t\t\tCUDA_CALL( cudaMemcpy( d_vec, (void*)(pos), rows * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\t\tauxIdx = -1;\n\t\t\tresult( 0, i ) = cuda_max( d_vec, &auxIdx, rows );\n\n\t\t\tpos += rows;\n\t\t}\n\n\t\tCUDA_CALL( cudaFree( d_vec ) );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::max();\n\ttemplate Array<double> Array<double>::max();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::max( Array<TElement> *idx )\n\t{\n\t\tTElement *d_vec;\n\t\tArray<TElement> result( 1, this->GetDescriptor().GetDim( 1 ) );\n\t\tint rows = this->GetDescriptor().GetDim( 0 );\n\n\t\tCUDA_CALL( cudaMalloc((void**)&d_vec, rows * sizeof(TElement)) );\n\n\t\tTElement *pos = &(this->m_data.m_data[0]);\n\t\tint auxIdx;\n\n\t\tfor( int i = 0; i < this->GetDescriptor().GetDim( 1 ); i++ )\n\t\t{\n\t\t\tCUDA_CALL( cudaMemcpy( d_vec, (void*)(pos), rows * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\t\tauxIdx = -1;\n\t\t\tresult( 0, i ) = cuda_max( d_vec, &auxIdx, rows );\n\t\t\t(*idx)( 0, i ) = auxIdx;\n\n\t\t\tpos += rows;\n\t\t}\n\n\t\tCUDA_CALL( cudaFree( d_vec ) );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::max( Array<float> *idx );\n\ttemplate Array<double> Array<double>::max( Array<double> *idx );\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::min()\n\t{\n\t\tTElement *d_vec;\n\t\tArray<TElement> result( 1, this->GetDescriptor().GetDim( 1 ) );\n\t\tint rows = this->GetDescriptor().GetDim( 0 );\n\n\t\tCUDA_CALL( cudaMalloc((void**)&d_vec, rows * sizeof(TElement)) );\n\n\t\tTElement *pos = &(this->m_data.m_data[0]);\n\t\tint auxIdx;\n\n\t\tfor( int i = 0; i < this->GetDescriptor().GetDim( 1 ); i++ )\n\t\t{\n\t\t\tCUDA_CALL( cudaMemcpy( d_vec, (void*)(pos), rows * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\t\tauxIdx = -1;\n\t\t\tresult( 0, i ) = cuda_min( d_vec, &auxIdx, rows );\n\n\t\t\tpos += rows;\n\t\t}\n\n\t\tCUDA_CALL( cudaFree( d_vec ) );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::min();\n\ttemplate Array<double> Array<double>::min();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::min( Array<TElement> *idx )\n\t{\n\t\tTElement *d_vec;\n\t\tArray<TElement> result( 1, this->GetDescriptor().GetDim( 1 ) );\n\t\tint rows = this->GetDescriptor().GetDim( 0 );\n\n\t\tCUDA_CALL( cudaMalloc((void**)&d_vec, rows * sizeof(TElement)) );\n\n\t\tTElement *pos = &(this->m_data.m_data[0]);\n\t\tint auxIdx;\n\n\t\tfor( int i = 0; i < this->GetDescriptor().GetDim( 1 ); i++ )\n\t\t{\n\t\t\tCUDA_CALL( cudaMemcpy( d_vec, (void*)(pos), rows * sizeof(TElement), cudaMemcpyHostToDevice) );\n\n\t\t\tauxIdx = -1;\n\t\t\tresult( 0, i ) = cuda_min( d_vec, &auxIdx, rows );\n\t\t\t(*idx)( 0, i ) = auxIdx;\n\n\t\t\tpos += rows;\n\t\t}\n\n\t\tCUDA_CALL( cudaFree( d_vec ) );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::min( Array<float> *idx );\n\ttemplate Array<double> Array<double>::min( Array<double> *idx );\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::removeRow( const index_t row )\n\t{\n\t\tArray<TElement> result( this->getDim(0) - 1, this->getDim(1) );\n\n\t\tsize_t auxIdx = -1;\n\t\tfor( int irow = 0; irow < this->getDim(0); irow++ )\n\t\t\tif( irow != row ) {\n\t\t\t\tauxIdx++;\n\t\t\t\tfor( int icol = 0; icol < this->getDim(1); icol++ )\n\t\t\t\t\tresult( auxIdx, icol ) = (*this)(irow,icol);\n\t\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\ttemplate Array<int> Array<int>::removeRow( const index_t row );\n\ttemplate Array<float> Array<float>::removeRow( const index_t row );\n\ttemplate Array<double> Array<double>::removeRow( const index_t row );\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::removeRow( const index_t row );\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::removeRow( const index_t row );\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::removeCol( const index_t col )\n\t{\n\t\tArray<TElement> result( this->getDim(0), this->getDim(1) - 1 );\n\n\t\tsize_t auxIdx = -1;\n\t\tfor( int icol = 0; icol < this->getDim(1); icol++ )\n\t\t\tif( icol != col ) { \n\t\t\t\tauxIdx++;\n\t\t\t\tfor( int irow = 0; irow < this->getDim(0); irow++ )\n\t\t\t\t\t\tresult( irow, auxIdx ) = (*this)(irow,icol);\n\t\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\ttemplate Array<int> Array<int>::removeCol( const index_t col );\n\ttemplate Array<float> Array<float>::removeCol( const index_t col );\n\ttemplate Array<double> Array<double>::removeCol( const index_t col );\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::removeCol( const index_t col );\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::removeCol( const index_t col );\n\n\t// TODO\n\t// find roots pf polynomial using bisection\n\t// method with tolerance TOL_BISECT_METHOD;\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::roots()\n\t{\n\t\tdouble TOL_BISECT_METHOD;\n\t\tif( (m_indexer->GetDescriptor().GetNDim() != 2) )\n\t\t\treturn *this;\n\n\t\tArray<TElement> result( this->GetDescriptor().GetDim( 0 ) );\n\n\t\treturn result;\n\t}\n\n\t//template Array<int> Array<int>::roots( Array<int> polynomial );\n\ttemplate Array<float> Array<float>::roots();\n\ttemplate Array<double> Array<double>::roots();\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::roots();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::roots();\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::elementWiseMultiply( Array<TElement> *A )\n\t{\n\t\tif (m_indexer->GetDescriptor().GetNDim() != A->m_indexer->GetDescriptor().GetNDim())\n\t\t\treturn *this;\n\t\telse if(m_indexer->GetDescriptor().GetNumberOfElements() != A->getNElements())\n\t\t\treturn *this;\t\t\n\n\t\tTElement *d_A, *d_B, *d_result;\n\n\t\tArray<TElement> result( this->getDim( 0 ), this->getDim( 1 ) );\n\n\t\t//// pass host pointer to device\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_A, A->m_data.GetElements(), 0 ) );\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_B, this->m_data.GetElements(), 0 ) );\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_result, result.m_data.GetElements(), 0 ) );\n\n\t\t// allocate memory\n\t\tCUDA_CALL( cudaMalloc<TElement>( &d_A, A->getNElements()*sizeof(TElement) ) );\n\t\tCUDA_CALL( cudaMalloc<TElement>( &d_B, A->getNElements()*sizeof(TElement) ) );\n\t\tCUDA_CALL( cudaMalloc<TElement>( &d_result, A->getNElements()*sizeof(TElement) ) );\n\n\t\t// copy to device\n\t\tCUDA_CALL( cudaMemcpy( (void*)d_A, A->data(), A->getNElements()*sizeof(TElement), cudaMemcpyHostToDevice ) );\n\t\tCUDA_CALL( cudaMemcpy( (void*)d_B, this->data(), this->getNElements()*sizeof(TElement), cudaMemcpyHostToDevice ) );\n\n\t\t// call function\n\t\tcuda_elementwise_multiplication<TElement>( d_A, d_B, d_result, A->getNElements() );\n\n\t\t// copy to host\n\t\tCUDA_CALL( cudaMemcpy( result.data(), d_result, A->getNElements()*sizeof(TElement), cudaMemcpyDeviceToHost ) );\n\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( d_B ) );\n\t\tCUDA_CALL( cudaFree( d_result ) );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::elementWiseMultiply( Array<float> *A );\n\ttemplate Array<double> Array<double>::elementWiseMultiply( Array<double> *A );\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::elementWiseMultiply( Array<ComplexFloat> *A );\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::elementWiseMultiply( Array<ComplexDouble> *A );\n\n\t//template <typename TElement>\n\t//Array<TElement> Array<TElement>::elementWiseDivide( Array<TElement> *A )\n\t//{\n\t//\tif (m_indexer->GetDescriptor().GetNDim() != A->m_indexer->GetDescriptor().GetNDim())\n\t//\t\treturn *this;\n\t//\telse if(m_indexer->GetDescriptor().GetNumberOfElements() != A->getNElements())\n\t//\t\treturn *this;\t\t\n\t//\n\t//\tTElement *d_A, *d_B, *d_result;\n\t//\n\t//\tArray<TElement> result( this->getDim( 0 ), this->getDim( 1 ) );\n\t//\n\t//\t// pass host pointer to device\n\t//\tCUDA_CALL( cudaHostGetDevicePointer( &d_A, A->m_data.GetElements(), 0 ) );\n\t//\tCUDA_CALL( cudaHostGetDevicePointer( &d_B, this->m_data.GetElements(), 0 ) );\n\t//\tCUDA_CALL( cudaHostGetDevicePointer( &d_result, result.m_data.GetElements(), 0 ) );\n\t//\n\t//\t//// allocate memory\n\t//\t//CUDA_CALL( cudaMalloc<TElement>( &d_A, A->getNElements()*sizeof(TElement) ) );\n\t//\t//CUDA_CALL( cudaMalloc<TElement>( &d_B, A->getNElements()*sizeof(TElement) ) );\n\t//\t//CUDA_CALL( cudaMalloc<TElement>( &d_result, A->getNElements()*sizeof(TElement) ) );\n\t//\n\t//\t//// copy to device\n\t//\t//CUDA_CALL( cudaMemcpy( (void*)d_A, A->data(), A->getNElements()*sizeof(TElement), cudaMemcpyHostToDevice ) );\n\t//\t//CUDA_CALL( cudaMemcpy( (void*)d_B, this->data(), this->getNElements()*sizeof(TElement), cudaMemcpyHostToDevice ) );\n\t//\n\t//\t// call function\n\t//\t//std::cout << A->getNElements() << std::endl;\n\t//\t//A->print();\n\t//\t//this->print();\n\t//\tcuda_elementwise_division<TElement>( d_A, d_B, d_result, A->getNElements() );\n\t//\n\t//\t//// copy to host\n\t//\t//CUDA_CALL( cudaMemcpy( result.data(), d_result, A->getNElements()*sizeof(TElement), cudaMemcpyDeviceToHost ) );\n\t//\n\t//\t//// free memory\n\t//\t//CUDA_CALL( cudaFree( d_A ) );\n\t//\t//CUDA_CALL( cudaFree( d_B ) );\n\t//\t//CUDA_CALL( cudaFree( d_result ) );\n\t//\n\t//\treturn result;\n\t//}\n\t//\n\t//template Array<float> Array<float>::elementWiseDivide( Array<float> *A );\n\t//template Array<double> Array<double>::elementWiseDivide( Array<double> *A );\n\t//template Array<ComplexFloat> Array<ComplexFloat>::elementWiseDivide( Array<ComplexFloat> *A );\n\t//template Array<ComplexDouble> Array<ComplexDouble>::elementWiseDivide( Array<ComplexDouble> *A );\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::elementWiseDivide( Array<TElement> *A )\n\t{\n\t\tif (m_indexer->GetDescriptor().GetNDim() != A->m_indexer->GetDescriptor().GetNDim())\n\t\t\treturn *this;\n\t\telse if(m_indexer->GetDescriptor().GetNumberOfElements() != A->getNElements())\n\t\t\treturn *this;\t\t\n\n\t\tArray<TElement> result( this->getDim( 0 ), this->getDim( 1 ) );\n\n\t\tfor( int i = 0; i < this->getDim( 0 ); i++ )\n\t\t\tfor( int j = 0; j < this->getDim( 1 ); j++ )\n\t\t\t\tresult( i, j ) = (*this)( i, j )/(*A)( i, j );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<float> Array<float>::elementWiseDivide( Array<float> *A );\n\ttemplate Array<double> Array<double>::elementWiseDivide( Array<double> *A );\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::elementWiseDivide( Array<ComplexFloat> *A );\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::elementWiseDivide( Array<ComplexDouble> *A );\n\n\t// implementation of abs\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::abs()\n\t{\n\t\tTElement *d_A, *d_result;\n\n\t\tArray<TElement> result( this->getDim( 0 ), this->getDim( 1 ) );\n\n\t\t//// pass host pointer to device\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_A, A->m_data.GetElements(), 0 ) );\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_B, this->m_data.GetElements(), 0 ) );\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_result, result.m_data.GetElements(), 0 ) );\n\n\t\t// allocate memory\n\t\tCUDA_CALL( cudaMalloc<TElement>( &d_A, this->getNElements()*sizeof(TElement) ) );\n\t\tCUDA_CALL( cudaMalloc<TElement>( &d_result, this->getNElements()*sizeof(TElement) ) );\n\n\t\t// copy to device\n\t\tCUDA_CALL( cudaMemcpy( (void*)d_A, this->data(), this->getNElements()*sizeof(TElement), cudaMemcpyHostToDevice ) );\n\n\t\t// call function\n\t\tcuda_abs<TElement>( d_A, d_result, this->getNElements() );\n\n\t\t// copy to host\n\t\tCUDA_CALL( cudaMemcpy( result.data(), d_result, this->getNElements()*sizeof(TElement), cudaMemcpyDeviceToHost ) );\n\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( d_result ) );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::abs();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::abs();\n\n\t// implementation of abs2\n\n\ttemplate <typename TElement>\n\tArray<TElement> Array<TElement>::abs2()\n\t{\n\t\tTElement *d_A, *d_result;\n\n\t\tArray<TElement> result( this->getDim( 0 ), this->getDim( 1 ) );\n\n\t\t//// pass host pointer to device\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_A, A->m_data.GetElements(), 0 ) );\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_B, this->m_data.GetElements(), 0 ) );\n\t\t//CUDA_CALL( cudaHostGetDevicePointer( &d_result, result.m_data.GetElements(), 0 ) );\n\n\t\t// allocate memory\n\t\tCUDA_CALL( cudaMalloc<TElement>( &d_A, this->getNElements()*sizeof(TElement) ) );\n\t\tCUDA_CALL( cudaMalloc<TElement>( &d_result, this->getNElements()*sizeof(TElement) ) );\n\n\t\t// copy to device\n\t\tCUDA_CALL( cudaMemcpy( (void*)d_A, this->data(), this->getNElements()*sizeof(TElement), cudaMemcpyHostToDevice ) );\n\n\t\t// call function\n\t\tcuda_abs2<TElement>( d_A, d_result, this->getNElements() );\n\n\t\t// copy to host\n\t\tCUDA_CALL( cudaMemcpy( result.data(), d_result, this->getNElements()*sizeof(TElement), cudaMemcpyDeviceToHost ) );\n\n\t\t// free memory\n\t\tCUDA_CALL( cudaFree( d_A ) );\n\t\tCUDA_CALL( cudaFree( d_result ) );\n\n\t\treturn result;\n\t}\n\n\ttemplate Array<ComplexFloat> Array<ComplexFloat>::abs2();\n\ttemplate Array<ComplexDouble> Array<ComplexDouble>::abs2();\n\n\tvoid ArrayUtil::ReleaseArrayDescriptor(ArrayDescriptor &descriptor)\n\t{\n\t\tdelete &descriptor;\n\t}\n}\n\n// CudaDevice implementation\nCudaDevice::CudaDevice()\n{\n\tcudaSetDevice(0);\n\tcudaSetDeviceFlags(cudaDeviceMapHost);\n};", "meta": {"hexsha": "514110accae3159b9cf93901313c3cb7c82dbfde", "size": 88758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matCUDA lib/src/Array.cpp", "max_stars_repo_name": "leomiquelutti/matCUDA", "max_stars_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matCUDA lib/src/Array.cpp", "max_issues_repo_name": "leomiquelutti/matCUDA", "max_issues_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matCUDA lib/src/Array.cpp", "max_forks_repo_name": "leomiquelutti/matCUDA", "max_forks_repo_head_hexsha": "95bd7917289288b0137ce23a952d4ccfd43e0d1d", "max_forks_repo_licenses": ["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.8929213079, "max_line_length": 195, "alphanum_fraction": 0.6781022556, "num_tokens": 25576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.03732688948593844, "lm_q1q2_score": 0.011103627208043716}}
{"text": "// Copyright (c) 2008-2016 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 UUID_5265FC7CA1C011DE9EBDFFA956D89593\n#define UUID_5265FC7CA1C011DE9EBDFFA956D89593\n\n#include <boost/qvm/assert.hpp>\n#include <boost/qvm/deduce_vec.hpp>\n#include <boost/qvm/enable_if.hpp>\n#include <boost/qvm/inline.hpp>\n#include <boost/qvm/mat_traits.hpp>\n\nnamespace boost {\nnamespace qvm {\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Col, class OriginalMatrix> class col_ {\n  col_(col_ const &);\n  col_ &operator=(col_ const &);\n  ~col_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL col_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int Col, class OriginalMatrix>\nstruct vec_traits<qvm_detail::col_<Col, OriginalMatrix>> {\n  typedef qvm_detail::col_<Col, OriginalMatrix> this_vector;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const dim = mat_traits<OriginalMatrix>::rows;\n  BOOST_QVM_STATIC_ASSERT(Col >= 0);\n  BOOST_QVM_STATIC_ASSERT(Col < mat_traits<OriginalMatrix>::cols);\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_vector const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template read_element<I, Col>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_vector &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template write_element<I, Col>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_vector const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        i, Col, reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int i, this_vector &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        i, Col, reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <int Col, class OriginalMatrix, int D>\nstruct deduce_vec<qvm_detail::col_<Col, OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <int Col, class OriginalMatrix, int D>\nstruct deduce_vec2<qvm_detail::col_<Col, OriginalMatrix>,\n                   qvm_detail::col_<Col, OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <int Col, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::col_<Col, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    col(A const &a) {\n  return reinterpret_cast<typename qvm_detail::col_<Col, A> const &>(a);\n}\n\ntemplate <int Col, class A>\ntypename boost::enable_if_c<is_mat<A>::value, qvm_detail::col_<Col, A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    col(A &a) {\n  return reinterpret_cast<typename qvm_detail::col_<Col, A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Row, class OriginalMatrix> class row_ {\n  row_(row_ const &);\n  row_ &operator=(row_ const &);\n  ~row_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL row_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int Row, class OriginalMatrix>\nstruct vec_traits<qvm_detail::row_<Row, OriginalMatrix>> {\n  typedef qvm_detail::row_<Row, OriginalMatrix> this_vector;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const dim = mat_traits<OriginalMatrix>::cols;\n  BOOST_QVM_STATIC_ASSERT(Row >= 0);\n  BOOST_QVM_STATIC_ASSERT(Row < mat_traits<OriginalMatrix>::rows);\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_vector const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template read_element<Row, I>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_vector &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template write_element<Row, I>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_vector const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        Row, i, reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int i, this_vector &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        Row, i, reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <int Row, class OriginalMatrix, int D>\nstruct deduce_vec<qvm_detail::row_<Row, OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <int Row, class OriginalMatrix, int D>\nstruct deduce_vec2<qvm_detail::row_<Row, OriginalMatrix>,\n                   qvm_detail::row_<Row, OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <int Row, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::row_<Row, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    row(A const &a) {\n  return reinterpret_cast<typename qvm_detail::row_<Row, A> const &>(a);\n}\n\ntemplate <int Row, class A>\ntypename boost::enable_if_c<is_mat<A>::value, qvm_detail::row_<Row, A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    row(A &a) {\n  return reinterpret_cast<typename qvm_detail::row_<Row, A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalMatrix> class diag_ {\n  diag_(diag_ const &);\n  diag_ &operator=(diag_ const &);\n  ~diag_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL diag_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n\ntemplate <int X, int Y, bool Which> struct diag_bool_dispatch;\n\ntemplate <int X, int Y> struct diag_bool_dispatch<X, Y, true> {\n  static int const value = X;\n};\n\ntemplate <int X, int Y> struct diag_bool_dispatch<X, Y, false> {\n  static int const value = Y;\n};\n} // namespace qvm_detail\n\ntemplate <class OriginalMatrix>\nstruct vec_traits<qvm_detail::diag_<OriginalMatrix>> {\n  typedef qvm_detail::diag_<OriginalMatrix> this_vector;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const dim = qvm_detail::diag_bool_dispatch<\n      mat_traits<OriginalMatrix>::rows, mat_traits<OriginalMatrix>::cols,\n      mat_traits<OriginalMatrix>::rows <=\n          mat_traits<OriginalMatrix>::cols>::value;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_vector const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template read_element<I, I>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_vector &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template write_element<I, I>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_vector const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        i, i, reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int i, this_vector &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        i, i, reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <class OriginalMatrix, int D>\nstruct deduce_vec<qvm_detail::diag_<OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <class OriginalMatrix, int D>\nstruct deduce_vec2<qvm_detail::diag_<OriginalMatrix>,\n                   qvm_detail::diag_<OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::diag_<A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    diag(A const &a) {\n  return reinterpret_cast<typename qvm_detail::diag_<A> const &>(a);\n}\n\ntemplate <class A>\ntypename boost::enable_if_c<is_mat<A>::value, qvm_detail::diag_<A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    diag(A &a) {\n  return reinterpret_cast<typename qvm_detail::diag_<A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalMatrix> class translation_ {\n  translation_(translation_ const &);\n  ~translation_();\n\npublic:\n  translation_ &operator=(translation_ const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class T>\n  BOOST_QVM_INLINE_TRIVIAL translation_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class OriginalMatrix>\nstruct vec_traits<qvm_detail::translation_<OriginalMatrix>> {\n  typedef qvm_detail::translation_<OriginalMatrix> this_vector;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const dim = mat_traits<OriginalMatrix>::rows - 1;\n  BOOST_QVM_STATIC_ASSERT(mat_traits<OriginalMatrix>::rows ==\n                          mat_traits<OriginalMatrix>::cols);\n  BOOST_QVM_STATIC_ASSERT(mat_traits<OriginalMatrix>::rows >= 3);\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_vector const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template read_element<I, dim>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_vector &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < dim);\n    return mat_traits<OriginalMatrix>::template write_element<I, dim>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_vector const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        i, dim, reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int i, this_vector &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < dim);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        i, dim, reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <class OriginalMatrix, int D>\nstruct deduce_vec<qvm_detail::translation_<OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <class OriginalMatrix, int D>\nstruct deduce_vec2<qvm_detail::translation_<OriginalMatrix>,\n                   qvm_detail::translation_<OriginalMatrix>, D> {\n  typedef vec<typename mat_traits<OriginalMatrix>::scalar_type, D> type;\n};\n\ntemplate <class A>\ntypename boost::enable_if_c<is_mat<A>::value &&\n                                mat_traits<A>::rows == mat_traits<A>::cols &&\n                                mat_traits<A>::rows >= 3,\n                            qvm_detail::translation_<A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    translation(A const &a) {\n  return reinterpret_cast<typename qvm_detail::translation_<A> const &>(a);\n}\n\ntemplate <class A>\ntypename boost::enable_if_c<is_mat<A>::value &&\n                                mat_traits<A>::rows == mat_traits<A>::cols &&\n                                mat_traits<A>::rows >= 3,\n                            qvm_detail::translation_<A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    translation(A &a) {\n  return reinterpret_cast<typename qvm_detail::translation_<A> &>(a);\n}\n\n////////////////////////////////////////////////\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "8cfbe9f5b719fc897a1f892eb2dd42961f5a8085", "size": 13169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/map_mat_vec.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/map_mat_vec.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/map_mat_vec.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": 32.5965346535, "max_line_length": 79, "alphanum_fraction": 0.6951932569, "num_tokens": 3347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988313272769, "lm_q2_score": 0.026759283379480286, "lm_q1q2_score": 0.011102395401301795}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2008 Matthew S Celnik.\n\n  Merged with the SubParticle class by Robert Patterson, October 2012\n\n  File purpose:\n    Implementation of the Particle class declared in the\n    swp_particle.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU General Public License\n    as published by the Free Software Foundation; either version 2\n    of the License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_particle.h\"\n\n#include \"swp_particle_model.h\"\n#include \"swp_particle_image.h\"\n#include \"string_functions.h\"\n\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/lognormal_distribution.hpp> \n\n#include <cmath>\n#include <stdexcept>\n#include <cassert>\n\nusing namespace Sweep;\nusing namespace std;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (protected).\nParticle::Particle(void)\n: m_Position(0.0)\n, m_PositionTime(0.0)\n, m_StatWeight(1.0)\n, m_primary(NULL)\n, m_CoagCount(0)\n, m_FragCount(0)\n, m_createt(0.0)\n, mLPDAtime(0.0)\n{\n}\n\n// Initialising constructor.\nParticle::Particle(double time, const Sweep::ParticleModel &model)\n: m_Position(0.0)\n, m_PositionTime(0.0)\n, m_StatWeight(1.0)\n, m_CoagCount(0)\n, m_FragCount(0)\n, m_createt(0.0)\n, mLPDAtime(0.0)\n{\n    m_primary = new AggModels::Primary(time, model);\n}\n\n/*!\n * @param[in]\ttime\tCreate time\n * @param[in]\tweight\tStatistical weight of new particle\n * @param[in]\tmodel\tParticle model that interprets contents of particle\n */\nParticle::Particle(double time, double weight, const Sweep::ParticleModel &model)\n: m_Position(0.0)\n, m_PositionTime(0.0)\n, m_StatWeight(weight)\n, m_CoagCount(0)\n, m_FragCount(0)\n, m_createt(0.0)\n, mLPDAtime(0.0)\n{\n    m_primary = new AggModels::Primary(time, model);\n}\n\n// Initialising constructor (from Primary particle).\nParticle::Particle(Sweep::AggModels::Primary &pri)\n: m_Position(0.0)\n, m_PositionTime(0.0)\n, m_StatWeight(1.0)\n, m_primary(&pri)\n, m_CoagCount(0)\n, m_FragCount(0)\n{\n    m_createt = pri.CreateTime();\n    mLPDAtime = pri.CreateTime();\n}\n\n// Copy constructor.\nParticle::Particle(const Sweep::Particle &copy)\n: m_primary(NULL)\n{\n    // Use assignment operator.\n    *this = copy;\n}\n\n/*!\n * @brief Read the particle from the binary stream. \n *\n * This method must read the data in the same way in which it is written in Serialize.\n *\n * @param[in,out]\t in\t\t             Input binary stream\n * @param[in]        model\t             Particle model defining interpretation of particle data\n * @param[in,out]    duplicates          Addresses of PAHs for use when reading primary particles\n *\n * @exception\t\t invalid_argument    Stream not ready\n */\nParticle::Particle(std::istream &in, const Sweep::ParticleModel &model, void *duplicates)\n{\n    if(in.good()) {\n        m_primary = ModelFactory::ReadPrimary(in, model, duplicates);\n\n        in.read(reinterpret_cast<char*>(&m_Position), sizeof(m_Position));\n        in.read(reinterpret_cast<char*>(&m_PositionTime), sizeof(m_PositionTime));\n        in.read(reinterpret_cast<char*>(&m_StatWeight), sizeof(m_StatWeight));\n        in.read(reinterpret_cast<char*>(&m_CoagCount), sizeof(m_CoagCount));\n        in.read(reinterpret_cast<char*>(&m_FragCount), sizeof(m_FragCount));\n        in.read(reinterpret_cast<char*>(&m_createt), sizeof(m_createt));\n        in.read(reinterpret_cast<char*>(&mLPDAtime), sizeof(mLPDAtime));\n    }\n    else {\n        throw std::invalid_argument(\"Input stream not ready \\\n        (Sweep::Particle stream reading constructor\");\n    }\n}\n\n// Default destructor.\nParticle::~Particle()\n{\n    // deleting a null pointer is not a problem - it just does nothing\n    delete m_primary;\n}\n\n/*!\n * @param[in]\t\txml\t\t\tXML node specifying the particle\n * @param[in]\t\tmodel\t\tParticle model that defines the interpretation of the particle data\n *\n * @return\t\tPointer to new particle constructed on the heap (caller must delete).\n *\n * @exception\truntime_error\tUnrecognised component\n * @exception\truntime_error\tUnrecognised tracker\n * @exception\truntime_error\tNon-positive statistical weight\n */\nParticle* Particle::createFromXMLNode(const CamXML::Element& xml, const Sweep::ParticleModel& model)\n{\n    // Read initial particle composition.\n    vector<CamXML::Element*> subitems; \n    xml.GetChildren(\"component\", subitems);\n    fvector components(model.ComponentCount(), 0);\n    \n    for (vector<CamXML::Element*>::iterator j=subitems.begin(); j!=subitems.end(); ++j) {\n        // Get component ID.\n        string str = (*j)->GetAttributeValue(\"id\");\n        int id = model.ComponentIndex(str);\n\n        if (id >= 0) {\n            // Get component value (XML uses dx to match format for inception).\n            str = (*j)->GetAttributeValue(\"dx\");\n            components[id] = Strings::cdble(str);\n        } else {\n            // Unknown component in mechanism.\n            throw std::runtime_error(str + \": Component not found in mechanism \\\n                                       (Sweep, Particle::createFromXMLNode).\");\n        }\n    }\n\n    // Read initial tracker variable values.\n    xml.GetChildren(\"track\", subitems);\n    fvector trackers(model.TrackerCount(), 0);\n    \n    for (vector<CamXML::Element*>::iterator j=subitems.begin(); j!=subitems.end(); j++) {\n        // Get tracker ID.\n        string str = (*j)->GetAttributeValue(\"id\");\n        int id = model.GetTrackerIndex(str);\n\n        if (id >= 0) {\n            // Get tracker value (XML uses dx to match format for inception).\n            str = (*j)->GetAttributeValue(\"dx\");\n            trackers[id] = Strings::cdble(str);\n        } else {\n            // Unknown tracker variable in mechanism.\n            throw std::runtime_error(str + \": Tracker variable not found in mechanism. \\\n                                       (Sweep, Particle::createFromXMLNode).\");\n        }\n    }\n\n    // Pointer to new particle\n    // \\TODO wrap in an auto_ptr for exception safety\n    Particle* pNew = model.CreateParticle(0.0);\n\n    // Read any statistical weight\n    const CamXML::Element* const pWeightNode = xml.GetFirstChild(\"weight\");\n    if(pWeightNode != NULL) {\n    \tstd::string str = pWeightNode->Data();\n    \tconst double wt = Strings::cdble(str);\n    \tif(wt <= 0) {\n    \t\tthrow std::runtime_error(\"Particle statistical weight must be >0, not \" + str +\n    \t\t\t\t                 \"(Sweep, Particle::createFromXMLNode).\");\n    \t}\n    \telse\n            pNew->setStatisticalWeight(wt);\n    }\n    \n    // Read SurfVol specific parameters\n    if (model.AggModel() == Sweep::AggModels::SurfVol_ID) {\n        const CamXML::Element* const pSurfNode = xml.GetFirstChild(\"surf\");\n        if (pSurfNode != NULL) {\n            std::string str = pSurfNode->Data();\n            const double surf = Strings::cdble(str);\n            if(surf <= 0) {\n                throw std::runtime_error(\"Particle surface area must be >0, not \" + str +\n                                         \"(Sweep, Particle::createFromXMLNode).\");\n            }\n            else\n                pNew->m_primary->SetSurfaceArea(surf);\n        }\n    }\n\n    // Initialise the new particle.\n    pNew->Primary()->SetComposition(components);\n    pNew->Primary()->SetValues(trackers);\n    pNew->UpdateCache();\n    \n    return pNew;\n}\n\n\n// Version of the above XML reader that will construct (bintree) particles given \n// (mean,std) number of primaries per particle and (mean,std) number of component\n// units per particle (assuming normal distributions).\n// To do: add sintering if required, switch to lognormal distribution when suitable parameters are known.\n/*!\n* @param[in]\t\txml\t\t\tXML node specifying the particle\n* @param[in]\t\tmodel\t\tParticle model that defines the interpretation of the particle data\n* @param[in]        rng         Random number generator \n*\n* @return\t\tPointer to new particle constructed on the heap (caller must delete).\n*\n* @exception\truntime_error\tUnrecognised component\n* @exception\truntime_error\tUnrecognised tracker\n* @exception\truntime_error\tNon-positive statistical weight\n*/\nParticle* Particle::createFromXMLNodeDetailed(const CamXML::Element& xml, const Sweep::ParticleModel& model, rng_type &rng)\n{\n\t// Read initial particle composition.\n\tvector<CamXML::Element*> subitems, subitems_pri;\n\txml.GetChildren(\"component\", subitems);\n\txml.GetChildren(\"nprimaries\", subitems_pri);\n\tfvector components(model.ComponentCount(), 0);\n\tfvector components_var(model.ComponentCount(), 0);\n\tfvector temp_components(model.ComponentCount(), 0);\n\n\tfor (vector<CamXML::Element*>::iterator j = subitems.begin(); j != subitems.end(); ++j) {\n\t\t// Get component ID.\n\t\tstring str = (*j)->GetAttributeValue(\"id\");\n\t\tint id = model.ComponentIndex(str);\n\n\t\tif (id >= 0) {\n\t\t\t// Get component value (XML uses dx to match format for inception).\n\t\t\tstr = (*j)->GetAttributeValue(\"dx\");\n\t\t\tcomponents[id] = Strings::cdble(str);\n\t\t\t// Get component std\n\t\t\tstd::string str2;\n\t\t\tstr2 = (*j)->GetAttributeValue(\"dx_var\");\n\t\t\tif (str2 != \"\") \n\t\t\t{\n\t\t\t\tcomponents_var[id] = Strings::cdble(str2);\n\t\t\t\tif (components_var[id] <= 0)\n\t\t\t\t\tthrow std::runtime_error(\"Component variance must be positive. \\\n\t\t\t\t\t\t\t\t\t\t\t \t(Sweep, Particle::createFromXMLNode).\");\n\t\t\t}\n\t\t\telse\n\t\t\t\tcomponents_var[id] = 0.0;\n\n\t\t\t/*cout << \"\\nIn particle fn\\n\";\n\t\t\tcout << \"==============\\n\";\n\t\t\tcout << \"ncomponent_ave = \" << components[0] << \"\\n\";*/\n\n\t\t\t// Convert to distribution parameters\n\t\t\tdouble ncomp_sqd = components[0] * components[0];\n\t\t\tdouble mu_ncomp = std::log(ncomp_sqd / sqrt(components_var[0] + ncomp_sqd));\n\t\t\tdouble sigma_sqd_ncomp = std::log(1.0 + (components_var[0] / ncomp_sqd));\n\n\t\t\t// Choose amount of component for this particle\n\t\t\tdouble ncomp_i = boost::random::lognormal_distribution<double>(mu_ncomp, sigma_sqd_ncomp)(rng);\n\n\t\t\t// Choosing a huge number of components is not memory sustainable, set some maximum\n\t\t\tdouble ncomp_max = 100000000000.0;\n\t\t\tif (ncomp_i > ncomp_max)\n\t\t\t{\n\t\t\t\tstd::cout << \"ncomp_i > ncomp_max, setting ncomp_i = \" << ncomp_max << \"\\n\";\n\t\t\t\tncomp_i = ncomp_max;\n\t\t\t}\n\n\t\t\tcomponents[id] = ncomp_i;\n\n\t\t\t// Scale any other components, assuming they must exist in stoichiometric amounts\n\t\t\t//double sf_i = ncomp_i / components[0];\n\t\t\t//for (size_t iter = 0; iter < components.size(); iter++)\n\t\t\t//\tcomponents[iter] *= sf_i;\n\n\t\t\t//cout << \"ncomponent = \" << components[0] << \"\\n\";\n\t\t}\n\t\telse {\n\t\t\t// Unknown component in mechanism.\n\t\t\tthrow std::runtime_error(str + \": Component not found in mechanism \\\n\t\t\t\t\t\t\t\t\t\t     (Sweep, Particle::createFromXMLNode).\");\n\t\t}\n\t}\n\n\t// Read initial tracker variable values.\n\txml.GetChildren(\"track\", subitems);\n\tfvector trackers(model.TrackerCount(), 0);\n\n\tfor (vector<CamXML::Element*>::iterator j = subitems.begin(); j != subitems.end(); j++) {\n\t\t// Get tracker ID.\n\t\tstring str = (*j)->GetAttributeValue(\"id\");\n\t\tint id = model.GetTrackerIndex(str);\n\n\t\tif (id >= 0) {\n\t\t\t// Get tracker value (XML uses dx to match format for inception).\n\t\t\tstr = (*j)->GetAttributeValue(\"dx\");\n\t\t\ttrackers[id] = Strings::cdble(str);\n\t\t}\n\t\telse {\n\t\t\t// Unknown tracker variable in mechanism.\n\t\t\tthrow std::runtime_error(str + \": Tracker variable not found in mechanism. \\\n\t\t\t\t\t\t\t\t\t\t     (Sweep, Particle::createFromXMLNode).\");\n\t\t}\n\t}\n\n\t//TODO wrap in an auto_ptr for exception safety\n\tParticle* pNew1 = model.CreateParticle(0.0);\n\n\t///////////////////////////////////////////////////////////////////////////////////////////\n\t// If bintree primary, read average number of primaries per particle and standard deviation\n\tif (model.AggModel() == Sweep::AggModels::BinTree_ID) \n\t{\n\t\tdouble npri, npri_var;\n\t\tstring str1, str2;\n\n\t\tfor (vector<CamXML::Element*>::iterator j = subitems_pri.begin(); j != subitems_pri.end(); ++j) \n\t\t{\n\t\t\t// Get mean number of primaries per particle\n\t\t\tstr1 = (*j)->GetAttributeValue(\"npri\");\n\t\t\tif (str1 != \"\") \n\t\t\t{\n\t\t\t\tnpri = Strings::cdble(str1);\n\t\t\t}\n\t\t\telse\n\t\t\t\tnpri = 1.0;\n\t\t\t\n\t\t\t// Get variance of number of primaries per particle\n\t\t\tstr2 = (*j)->GetAttributeValue(\"npri_var\");\n\t\t\tif (str2 != \"\") \n\t\t\t{\n\t\t\t\tnpri_var = Strings::cdble(str2);\n\t\t\t\tif (npri_var <= 0)\n\t\t\t\t\tthrow std::runtime_error(\"Particle primary count variance must be positive. \\\n\t\t\t\t\t\t\t\t\t\t\t \t(Sweep, Particle::createFromXMLNode).\");\n\t\t\t}\n\t\t\telse\n\t\t\t\tnpri_var = 0.07;\n\t\t}\n\n\t\t// Convert to distribution parameters\n\t\tdouble npri_sqd = npri * npri;\n\t\tdouble mu_npri = std::log(npri_sqd / sqrt(npri_var + npri_sqd));\n\t\tdouble sigma_sqd_npri = std::log(1.0 + (npri_var / npri_sqd));\n\n\t\t// Choose number of primaries for this particle\n\t\t// to do - give this an upper bound, same with npri\n\t\tunsigned int npri_i = ceil(boost::random::lognormal_distribution<double>(mu_npri, sigma_sqd_npri)(rng));\n\n\t\t// Choosing a huge number of primaries is not memory sustainable, set some maximum\n\t\tunsigned int npri_max = 1000;\n\t\tif (npri_i > npri_max)\n\t\t{\n\t\t\tstd::cout << \"npri_i > npri_max, setting npri_i = \" << npri_max << \"\\n\";\n\t\t\tnpri_i = npri_max;\n\t\t}\n\t\telse if (npri_i < 1)\n\t\t{\n\t\t\tstd::cout << \"npri_i < 1, setting npri_i = 1\" << \"\\n\";\n\t\t\tnpri_i = 1;\n\t\t}\n\n\t\t//cout << \"npri = \" << npri_i << \"\\n\";\n\n\t\t// Choose division of rutile amongst primaries\n\t\tboost::uniform_01<rng_type&, double> uniformGenerator(rng);\n\t\tfvector fracs(npri_i, 0);\n\t\tdouble fracs_total = 0.0;\n\t\tfor (unsigned int j = 0; j < npri_i; j++)\n\t\t{\n\t\t\tfracs[j] = uniformGenerator(); \n\t\t\tfracs_total += fracs[j];\n\t\t}\n\t\tfor (unsigned int j = 0; j < npri_i; j++)\n\t\t{\n\t\t\tfracs[j] *= (1.0 / fracs_total);\n\t\t\t//cout << \" * \" << fracs[j] << \"\\n\";\n\t\t}\n\t\t\n\t\t// Read any statistical weight\n\t\tconst CamXML::Element* const pWeightNode = xml.GetFirstChild(\"weight\");\n\t\tif (pWeightNode != NULL) {\n\t\t\tstd::string str = pWeightNode->Data();\n\t\t\tconst double wt = Strings::cdble(str);\n\t\t\tif (wt <= 0) {\n\t\t\t\tthrow std::runtime_error(\"Particle statistical weight must be >0, not \" + str +\n\t\t\t\t\t\"(Sweep, Particle::createFromXMLNode).\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpNew1->setStatisticalWeight(wt);\n\n\t\t\t\t// Initialise the first new particle, this will be the base particle.\n\t\t\t\tfor (size_t iter = 0; iter < temp_components.size(); iter++)\n\t\t\t\t\ttemp_components[iter] = ceil(components[iter] * fracs[0]);\n\n\t\t\t\t//cout << \"ncomp_i = \" << temp_components[0] << \"\\n\";\n\n\t\t\t\tpNew1->Primary()->SetComposition(temp_components);\n\t\t\t\tpNew1->Primary()->SetValues(trackers); // what is this?\n\t\t\t\tpNew1->UpdateCache();\n\n\t\t\t\t//TODO wrap in an auto_ptr for exception safety\n\t\t\t\tParticle* pNew2;\n\n\t\t\t\t// Initialise all other particles, coagulating with the base particle.\n\t\t\t\tfor (unsigned int j = 1; j < npri_i; j++)\n\t\t\t\t{\n\t\t\t\t\tpNew2 = model.CreateParticle(0.0);\n\t\t\t\t\tpNew2->setStatisticalWeight(wt);\n\t\t\t\t\t\n\t\t\t\t\t// Ensure there is a minimum number of components in the particle\n\t\t\t\t\tdouble ncomp_min = 2.0;\n\t\t\t\t\tdouble adjust = 0.0;\n\t\t\t\t\tif (ceil(components[0] * fracs[j]) < ncomp_min)\n\t\t\t\t\t\tadjust = ncomp_min;\n\t\t\t\t\tfor (size_t iter = 0; iter < temp_components.size(); iter++)\n\t\t\t\t\t\ttemp_components[iter] = ceil(components[iter] * fracs[j] + (adjust * components[iter] / components[0]));\n\t\t\t\t\tpNew2->Primary()->SetComposition(temp_components);\n\t\t\t\t\tpNew2->Primary()->SetValues(trackers); // what is this?\n\t\t\t\t\tpNew2->UpdateCache();\n\n\t\t\t\t\t//cout << \"ncomp_i = \" << temp_components[0] << \"\\n\";\n\n\t\t\t\t\t// Perform coagulation \n\t\t\t\t\t// To do: work out if the weight should be modified in the weighted case\n\t\t\t\t\tpNew1->Coagulate(*pNew2, rng);\n\t\t\t\t\tpNew1->UpdateCache();\n\t\t\t\t}\n\n\t\t\t\t//cout << \"Done: dcol(Pi) = \" << pNew1->CollDiameter() << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\t///////////////////////////////////////////////////////////////////////////////////////////\n\telse \n\t{\n\t\t//cout << \"Not using bintree model\\n\";\n\n\t\t// Read any statistical weight\n\t\tconst CamXML::Element* const pWeightNode = xml.GetFirstChild(\"weight\");\n\t\tif (pWeightNode != NULL) {\n\t\t\tstd::string str = pWeightNode->Data();\n\t\t\tconst double wt = Strings::cdble(str);\n\t\t\tif (wt <= 0) {\n\t\t\t\tthrow std::runtime_error(\"Particle statistical weight must be >0, not \" + str +\n\t\t\t\t\t\"(Sweep, Particle::createFromXMLNode).\");\n\t\t\t}\n\t\t\telse\n\t\t\t\tpNew1->setStatisticalWeight(wt);\n\t\t}\n\n\t\t// Read SurfVol specific parameters\n\t\tif (model.AggModel() == Sweep::AggModels::SurfVol_ID) {\n\t\t\tconst CamXML::Element* const pSurfNode = xml.GetFirstChild(\"surf\");\n\t\t\tif (pSurfNode != NULL) {\n\t\t\t\tstd::string str = pSurfNode->Data();\n\t\t\t\tconst double surf = Strings::cdble(str);\n\t\t\t\tif (surf <= 0) {\n\t\t\t\t\tthrow std::runtime_error(\"Particle surface area must be >0, not \" + str +\n\t\t\t\t\t\t\"(Sweep, Particle::createFromXMLNode).\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tpNew1->m_primary->SetSurfaceArea(surf);\n\t\t\t}\n\t\t}\n\n\t\tfor (size_t iter = 0; iter < components.size(); iter++)\n\t\t\tcomponents[iter] = ceil(components[iter]);\n\n\t\t//cout << \"ncomp_i = \" << components[0] << \"\\n\";\n\n\t\t// Initialise the new particle.\n\t\tpNew1->Primary()->SetComposition(components);\n\t\tpNew1->Primary()->SetValues(trackers);\n\t\tpNew1->UpdateCache();\n\n\t\t//cout << \"Done: dcol(Pi) = \" << pNew1->CollDiameter() << \"\\n\";\n\t}\n\n\treturn pNew1;\n}\n\n\n// Compound assignment (coagulation).\n// OPERATOR OVERLOADING.\n\n// Assignment operator.\nParticle &Particle::operator=(const Sweep::Particle &rhs)\n{\n    if (this != &rhs) {\n        // Copy primary.\n        if (rhs.m_primary != NULL) {\n            // Does not matter if m_primary is null\n            delete m_primary;\n            m_primary = rhs.m_primary->Clone();\n        } else {\n            delete m_primary;\n            m_primary = NULL;\n        }\n\n        // Copy remaining data\n        m_Position = rhs.m_Position;\n        m_PositionTime = rhs.m_PositionTime;\n        m_StatWeight = rhs.m_StatWeight;\n        m_CoagCount = rhs.m_CoagCount;\n        m_FragCount = rhs.m_FragCount;\n        m_createt = rhs.m_createt;\n        mLPDAtime = rhs.mLPDAtime;\n    }\n    return *this;\n}\n\n// PRIMARY PARTICLE CHILD.\n\n/*!\n * Access the child primary particle which contains the physical details\n * of the particle\n *\n *@return   Pointer to primary particle or Null if none present\n */\nSweep::AggModels::Primary *const Particle::Primary()\n{\n    return m_primary;\n}\n\n/*!\n * Access the child primary particle which contains the physical details\n * of the particle\n *\n *@return   Pointer to primary particle or Null if none present\n */\nconst Sweep::AggModels::Primary *const Particle::Primary() const\n{\n    return m_primary;\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::SphDiameter() const\n{\n    return m_primary->SphDiameter();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::CollDiameter() const\n{\n    return m_primary->CollDiameter();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::MobDiameter() const\n{\n    return m_primary->MobDiameter();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::SurfaceArea() const\n{\n    return m_primary->SurfaceArea();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::SphSurfaceArea() const\n{\n    return m_primary->SphSurfaceArea();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::Volume() const\n{\n    return m_primary->Volume();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::Mass(void) const\n{\n    return m_primary->Mass();\n}\n\n//! Pass through to primary particle.\nint Particle::NumCarbon(void) const\n{\n    return m_primary->NumCarbon();\n}\n\n//! Pass through to primary particle.\nint Particle::Frag(void) const\n{\n    return m_primary->Frag();\n}\n\nint Particle::NumRings() const\n{\n\treturn m_primary->NumRings();\n}\n/*!\n * Pass through to primary particle\n */\ndouble Particle::GetSites(void) const\n{\n    return m_primary->GetSites();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::GetSintRate(void) const\n{\n    return m_primary->GetSintRate();\n}\n\n/*!\n * Pass through to primary particle\n */\ndouble Particle::GetCoverageFraction(void) const\n{\n    return m_primary->GetCoverageFraction();\n}\n\n/*!\n * It is not clear to me why the number of primary particles is\n * not used as the number of sub-units (riap 01.10.2012).\n *\n * @param[in]   Reciprocal of number of sub-units in the aggregate\n *\n * @return      Geometric mean of sub-unit diameter\n */\ndouble Particle::avgeomdiam(double oneovernumsubpart) const\n{\n    return std::pow(m_primary->Property(Sweep::iDsph),oneovernumsubpart);\n}\n\n//! Phase composition term for phase transformation process\ndouble Particle::GetPhaseTerm(void) const\n{\n\treturn m_primary->GetPhaseTerm();\n}\n\n/*!\n * Provide an interface that allows run time specification of particle properties\n * for use in process rate calculations.  It is currently used for some surface\n * reactions.  Where possible, the use of specific accessors should be preferred.\n *\n *@param[in]    id      Symbolic index of property required\n *\n *@return       Requested particle property\n *\n *@pre          A valid primary particle is present (the data is not stored in SubParticle)\n */\ndouble Particle::Property(PropID id) const\n{\n    switch (id) {\n        case iDsph:      // Equivalent sphere diameter.\n            return SphDiameter();\n        case iDcol:   // Collision diameter.\n            return CollDiameter();\n        case iDmob:   // Mobility diameter.\n            return MobDiameter();\n        case iS:      // Surface area.\n            return SurfaceArea();\n        case iV:      // Volume.\n            return Volume();\n        case iM:      // Mass.\n            return Mass();\n        \n        //! Number of carbon atoms.\n        case iNumCarbon:\n            return NumCarbon();\n\n        //! Fragmentation flag.\n        case iFrag:\n            return Frag();\n\n        // Collision rate properties:\n        case iD2:\n            return CollDiameter() * CollDiameter();\n        case iD_1:\n            return 1.0 / CollDiameter();\n        case iD_2:\n            return 1.0 / CollDiameter() / CollDiameter();\n        case iM_1_2:\n            return 1.0 / std::sqrt(Mass());\n        case iD2_M_1_2:\n            return CollDiameter() * CollDiameter() / std::sqrt(Mass());\n        case iASN:\n            return GetSites();\n        case iSintRate:\n            return GetSintRate();\n        case iCoverage:\n            return GetCoverageFraction();\n        case iFS:\n            throw std::logic_error(\"Free surface no longer supported (Particle::Property)\");\n            return 0.0;       \n        case -1:\n            // Special case property, used to select particles\n            // uniformly.\n            return 1.0;\n\t\tcase iAn_2_3_comp:\n\t\t\treturn GetPhaseTerm();\n        default:\n            throw std::logic_error(\"Unrecognised property requested (Particle::Property)\");\n            return 0.0;\n    }\n}\n\n\n// PARTICLE COMPOSITION.\n\n// Returns the composition vector.\nconst fvector &Particle::Composition() const\n{\n    return m_primary->Composition();\n}\n\n// Returns the ith component value.  Returns 0.0 if i is invalid.\ndouble Particle::Composition(unsigned int i) const\n{\n    if (i < Composition().size()) {\n        return Composition()[i];\n    } else {\n        return 0.0;\n    }\n}\n\n// TRACKER VARIABLE VALUES.\n\n/*!\n * Returns the tracker value vector.\n */\nconst fvector &Particle::Values() const\n{\n    return m_primary->Values();\n}\n\n// Returns the ith tracker variable value.  Returns 0.0 if i is invalid.\ndouble Particle::Values(unsigned int i) const\n{\n    if (i < Values().size()) {\n        return Values()[i];\n    } else {\n        return 0.0;\n    }\n}\n\n/*!\n * Both position and the associated time must be updated together.  This is\n * because it makes no sense to specify a position without knowing when it\n * applies.\n *\n *@param[in]    x       New position of particle\n *@param[in]    t       Time at which new position is correct\n */\nvoid Particle::setPositionAndTime(const double x, const double t) {\n    m_Position = x;\n    m_PositionTime = t;\n}\n\n/*!\n * Set last LPDA update time; function name is historical (and confusing).\n *\n *@param[in]    t   Time to which LPDA has just been performed\n */\nvoid Particle::SetTime(double t)\n{\n    m_primary->SetTime(t);\n    mLPDAtime = t;\n}\n\n/*!\n *  Recalculates the derived properties from the unique properties.\n *  This function moves down the tree of subparticles from the top to the bottom.\n */\nvoid Particle::UpdateCache(void)\n{\n    // Get cache from primary particle.\n    m_primary->UpdateCache();\n\n    m_createt = m_primary->CreateTime();\n    mLPDAtime    = m_primary->LastUpdateTime();\n}\n\n/*!\n *@return   Number of coagulation events since counter was reset\n */\nunsigned int Particle::getCoagCount() const {\n    return m_CoagCount;\n}\n\n/*!\n *@return   Number of coagulation events since counter was reset\n */\nunsigned int Particle::getFragCount() const {\n    return m_FragCount;\n}\n\n// PARTICLE ADJUSTMENT AND PROCESSES.\n\n/*!\n * Apply the given composition and values changes n times\n *\n *@param[in]        n       Number of times to apply changes\n *\n *@return       Number of times changes actually applied\n */\nunsigned int Particle::Adjust(const fvector &dcomp,\n                              const fvector &dvalues,\n                              rng_type &rng,\n                              unsigned int n)\n{\n    unsigned int m = n;\n\n    // This is a leaf-node sub-particle as it contains a\n    // primary particle.  The adjustment is applied to\n    // the primary.\n    m = m_primary->Adjust(dcomp, dvalues, rng, n);\n\n    // Where-ever the adjustment has been applied this sub-particle must\n    // now update its cache.\n    UpdateCache();\n\n    return m;\n}\n\n/*!\n * Apply the given composition and values changes n times\n * while allowing for the special nature of IntParticleReaction.\n *\n *@param[in]        n       Number of times to apply changes\n *\n *@return       Number of times changes actually applied\n */\nunsigned int Particle::AdjustIntPar(const fvector &dcomp,\n                                    const fvector &dvalues,\n                                    rng_type &rng,\n                                    unsigned int n)\n{\n    unsigned int m = n;\n\n    // This is a leaf-node sub-particle as it contains a\n    // primary particle.  The adjustment is applied to\n    // the primary.\n    m = m_primary->AdjustIntPar(dcomp, dvalues, rng, n);\n\n    // Where-ever the adjustment has been applied this sub-particle must\n    // now update its cache.\n    UpdateCache();\n\n    return m;\n}\n\n/*!\n * Apply the given composition and values changes n times\n * for the phase transformation \n *\n *@param[in]        n       Number of times to apply changes\n *\n *@return       Number of times changes actually applied\n */\nunsigned int Particle::AdjustPhase(const fvector &dcomp,\n                              const fvector &dvalues,\n                              rng_type &rng,\n                              unsigned int n)\n{\n    \n\tunsigned int m = n;\n\n    // This is a leaf-node sub-particle as it contains a\n    // primary particle.  The adjustment is applied to\n    // the primary.\n    n = m_primary->AdjustPhase(dcomp, dvalues, rng, n);\n\n\t// Adjust phase may return n < m if the selected primary does not contain enough components.\n\t// The loop tries to apply the adjustment to other primaries (when using the bintree model).\n\tint loops = 0;\n\twhile (n<m && loops < 20){  //max number of loops set to 20\n\t\tn += m_primary->AdjustPhase(dcomp, dvalues, rng, m-n);\n\t\tloops ++;\n\t}\n\n    // Where-ever the adjustment has been applied this sub-particle must\n    // now update its cache.\n    UpdateCache();\n\n    return m;\n}\n\n// Phase transformation\nvoid Particle::Melt(rng_type &rng, Cell &sys)\n{\n\n\t// This is a leaf-node sub-particle as it contains a\n\t// primary particle.  The adjustment is applied to\n\t// the primary.\n\tm_primary->Melt(rng, sys);\n\n\t// Where-ever the adjustment has been applied this sub-particle must\n\t// now update its cache.\n\tUpdateCache();\n\n\treturn;\n}\n\n/*!\n * Combines this particle with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n * \\return      Reference to the current instance after rhs has been added\n */\nParticle &Particle::Coagulate(const Particle &rhs, rng_type &rng)\n{\n    m_primary->Coagulate(*rhs.m_primary, rng);\n    UpdateCache();\n\n    return *this;\n}\n\n/*!\n * Combines this particle with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n * \\return      Reference to the current instance after rhs has been added\n */\nParticle &Particle::Fragment(const Particle &rhs, rng_type &rng)\n{\n    m_primary->Fragment(*rhs.m_primary, rng);\n    UpdateCache();\n\n    return *this;\n}\n\n/*!\n * Sinter the particle over the specified amount of time\n *\n *@param[in]        dt      Length of sintering time\n *@param[in]        sys     Cell containing the particle and providing details of the environment\n *@param[in]        model   Sintering model to define sintering rate\n *@param[in,out]    rng     Random number generator object\n *@param[in]        wt      Statistical weight of particle\n */\nvoid Particle::Sinter(double dt, Cell &sys,\n                      const Processes::SinteringModel &model,\n                      rng_type &rng,\n                      double wt)\n{\n    m_primary->Sinter(dt, sys, model, rng, wt);\n}\n\n// Creates a clone of the particle.\nParticle *const Particle::Clone() const\n{\n    return new Particle(*this);\n}\n\n/*!\n * Perform checks on the internal data structure.  This is mainly for\n * testing and checking purposes; it should not be called from performance\n * critical sections.\n *\n * It was not quite clear in the old SubParticle code (now merged into this class)\n * to what extent this method should check the integrity\n * of the data structure and to what extent it should verify the physical\n * meaning.  I think the two purposes may have become a little mixed.\n * (riap2 24 Jan 2011)\n * \n * @return\ttrue iff internal structures pass tests\n */\nbool Particle::IsValid() const {\n\treturn (m_primary != NULL) && (m_primary->IsValid()) && (m_StatWeight > 0);\n}\n\nvoid Particle::writeParticlePOVRAY(std::ofstream &out) const\n{\n    // First construct the image\n    Sweep::Imaging::ParticleImage image;\n    image.Construct(*(this), *(Primary()->ParticleModel()));\n\n    // Write it to file\n    image.WritePOVRAY(out);\n\n    // Now we can delete the image\n}\n\n/*!\n * @brief Writes the object to a binary stream\n *\n * @param[in,out]\t out\t\t         Output binary stream\n * @param[in,out]    duplicates          Addresses of PAHs that have already been serialised\n * @exception\t\t invalid_argument    Output stream not ready\n *\n * @pre              IsValid             returns true indicating (amongst other things) that the primary particle is initialised\n */\nvoid Particle::Serialize(std::ostream &out, void *duplicates) const\n{\n\tassert(IsValid());\n\n    if (out.good()) {\n        ModelFactory::WritePrimary(*m_primary, out, duplicates);\n\n        // Output the data members in this class\n        out.write((char*)&m_Position, sizeof(m_Position));\n        out.write((char*)&m_PositionTime, sizeof(m_PositionTime));\n        out.write((char*)&m_StatWeight, sizeof(m_StatWeight));\n        out.write((char*)&m_CoagCount, sizeof(m_CoagCount));\n        out.write((char*)&m_FragCount, sizeof(m_FragCount));\n        out.write(reinterpret_cast<const char*>(&m_createt), sizeof(m_createt));\n        out.write(reinterpret_cast<const char*>(&mLPDAtime), sizeof(mLPDAtime));\n    }\n    else {\n        throw std::invalid_argument(\"Output stream not ready \\\n                                    (Sweep, Particle::Serialize).\");\n    }\n}\n\n//! Returns the frame position and orientation, and primary coordinates\n//! Used by particle tracking for videos\nvoid Particle::getFrameCoords(std::vector<fvector> &coords) const\n{\n\tm_primary->GetFrameCoords(coords);\n}\n\n//! Initialise primary particle tracking for videos\nvoid Particle::setTracking()\n{\n\tm_primary->setTracking();\n}\n\n//! Remove primary tracking\nvoid Particle::removeTracking()\n{\n\tm_primary->removeTracking();\n}", "meta": {"hexsha": "25ca965d5fa25eb846ad2eed31ea02499d0726a4", "size": 32606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_particle.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_particle.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_particle.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 29.6148955495, "max_line_length": 128, "alphanum_fraction": 0.6441452493, "num_tokens": 8208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658972248186, "lm_q2_score": 0.030214587176551188, "lm_q1q2_score": 0.011076357127955867}}
{"text": "/*///////////////////////////////////////////////////////////////////////////////////////\n//\n// THIS IS A MODIFICATION OF OPENCV SOURCE CODE\n//\n//*/\n\n/*///////////////////////////////////////////////////////////////////////////////////////\n//\n//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n//\n//  By downloading, copying, installing or using the software you agree to this license.\n//  If you do not agree to this license, do not download, install,\n//  copy or use the software.\n//\n//\n//                           License Agreement\n//                For Open Source Computer Vision Library\n//\n// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\n// Copyright (C) 2009, Willow Garage Inc., all rights reserved.\n// Third party copyrights are property of their respective owners.\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//   * Redistribution's of source code must retain the above copyright notice,\n//     this list of conditions and the following disclaimer.\n//\n//   * Redistribution's 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//   * The name of the copyright holders may not be used to endorse or promote products\n//     derived from this software without specific prior written permission.\n//\n// This software is provided by the copyright holders and contributors \"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 disclaimed.\n// In no event shall the Intel Corporation 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 services;\n// loss of use, data, or profits; or business interruption) however caused\n// and on any theory of liability, whether in contract, strict liability,\n// or tort (including negligence or otherwise) arising in any way out of\n// the use of this software, even if advised of the possibility of such damage.\n//\n//*/\n\n/*\n This is a variation of\n \"Stereo Processing by Semiglobal Matching and Mutual Information\"\n by Heiko Hirschmuller.\n\n This version was adapted from the OpenCV implementation to use\n a matching cost volume instead of two stereo rectified images.\n\n */\n\n#include <limits.h>\n#include \"semiGlobalMatching.h\"\n#include <iostream>\n#include <d3d_base/exception.h>\n#include <opencv2/core/internal.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <Eigen/Dense>\n\nusing std::cout;\nusing std::endl;\nusing Eigen::Matrix;\n\nusing namespace D3D;\n\nSemiGlobalMatching::SemiGlobalMatching()\n{\n    outputDepthMapEnabled = true;\n    outputLabelsEnabled =true;\n    outputUniquenessRatiosEnabled = false;\n    outputCostsEnabled = false;\n    subPixelEnabled = true;\n//    minDisparity = numberOfDisparities = 0;\n//    SADWindowSize = 0;\n    P1 = 5; P2 = 8;\n//    disp12MaxDiff = 0;\n//    preFilterCap = 0;\n//    uniquenessRatio = 0;\n//    speckleWindowSize = 0;\n//    speckleRange = 0;\n    fullDP = true;\n}\n\n\nSemiGlobalMatching::SemiGlobalMatching(int _P1, int _P2, bool _fullDP )\n{\n    outputDepthMapEnabled = true;\n    outputLabelsEnabled =true;\n    outputUniquenessRatiosEnabled = false;\n    outputCostsEnabled = false;\n    subPixelEnabled = true;\n    P1 = _P1;\n    P2 = _P2;\n    fullDP = _fullDP;\n}\n\n/*\n  This is an adaptation to the original open cv code to enable the semi global matching to mach on\n  a cost volume acquired by plane sweep. Thus the comments might make no sense sometimes and also too much\n  memory is allocated. But the implementation seems to be still fast.\n\n computes disparity for \"roi\" in img1 w.r.t. img2 and write it to disp1buf.\n that is, disp1buf(x, y)=d means that img1(x+roi.x, y+roi.y) ~ img2(x+roi.x-d, y+roi.y).\n minD <= d < maxD.\n disp2full is the reverse disparity map, that is:\n disp2full(x+roi.x,y+roi.y)=d means that img2(x+roi.x, y+roi.y) ~ img1(x+roi.x+d, y+roi.y)\n\n note that disp1buf will have the same size as the roi and\n disp2full will have the same size as img1 (or img2).\n On exit disp2buf is not the final disparity, it is an intermediate result that becomes\n final after all the tiles are processed.\n\n the disparity in disp1buf is written with sub-pixel accuracy\n (4 fractional bits, see CvStereoSGBM::DISP_SCALE),\n using quadratic interpolation, while the disparity in disp2buf\n is written as is, without interpolation.\n\n disp2cost also has the same size as img1 (or img2).\n It contains the minimum current cost, used to find the best disparity, corresponding to the minimal cost.\n */\nvoid SemiGlobalMatching::matchFromPlaneSweep(const Grid<float>& costVolume, const Grid<Eigen::Vector4d>& planes, const CameraMatrix<double>& cam, float costThresh)\n{\n    Matrix<double, 3, 3> refKinvT = Matrix<double, 3, 3>::Zero();\n    if (outputDepthMapEnabled)\n    {\n        result = DepthMap<float, double>(costVolume.getWidth(), costVolume.getHeight(), cam);\n        refKinvT  = cam.getK().inverse().transpose();\n    }\n//    for(int z=0; z<costVolume.getDepth(); ++z)\n//    {\n//        cout<<costVolume(847,247,z)<<\" - \";\n//    }\n//    cout<<endl;\n    if (outputUniquenessRatiosEnabled)\n    {\n        uniquenessRatios = Grid<float>(costVolume.getWidth(), costVolume.getHeight(), 1 ,1);\n    }\n\n    if (outputCostsEnabled)\n    {\n        costs = Grid<float>(costVolume.getWidth(), costVolume.getHeight(), 1, 0);\n    }\n\n    cv::Mat disp1(costVolume.getHeight(), costVolume.getWidth(), CV_16S );\n\n#if CV_SSE2\n    static const uchar LSBTab[] =\n    {\n        0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n        6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n        7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n        6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0\n    };\n\n    volatile bool useSIMD = cv::checkHardwareSupport(CV_CPU_SSE2);\n#endif\n\n    const int ALIGN = 16;\n    const int DISP_SCALE = SemiGlobalMatching::DISP_SCALE;\n    const CostType MAX_COST = SHRT_MAX;\n\n    int minD = 0, maxD = costVolume.getDepth();\n    int k, width = costVolume.getWidth(), height = costVolume.getHeight();\n    int minX1 = 0, maxX1 = width;\n    int D = maxD - minD, width1 = costVolume.getWidth();\n    int INVALID_DISP = minD - 1, INVALID_DISP_SCALED = INVALID_DISP*DISP_SCALE;\n    int npasses = fullDP ? 2 : 1;\n\n    if( minX1 >= maxX1 )\n    {\n        disp1 = cv::Scalar::all(INVALID_DISP_SCALED);\n        return;\n    }\n\n    if (D % 16 != 0)\n    {\n        D3D_THROW_EXCEPTION(\"Number of labels must be a multiple of 16 because of the alignment.\")\n    }\n\n    // NR - the number of directions. the loop on x below that computes Lr assumes that NR == 8.\n    // if you change NR, please, modify the loop as well.\n    int D2 = D+16, NRD2 = NR2*D2;\n\n    // the number of L_r(.,.) and min_k L_r(.,.) lines in the buffer:\n    // for 8-way dynamic programming we need the current row and\n    // the previous row, i.e. 2 rows in total\n    const int NLR = 2;\n    const int LrBorder = NLR - 1;\n\n    // for each possible stereo match (img1(x,y) <=> img2(x-d,y))\n    // we keep pixel difference cost (C) and the summary cost over NR directions (S).\n    // we also keep all the partial costs for the previous line L_r(x,d) and also min_k L_r(x, k)\n    size_t costBufSize = width1*D;\n    size_t CSBufSize = costBufSize*(fullDP ? height : 1);\n    size_t minLrSize = (width1 + LrBorder*2)*NR2, LrSize = minLrSize*D2;\n    int SH2 = 0;\n    int hsumBufNRows = SH2*2 + 2;\n    size_t totalBufSize = (LrSize + minLrSize)*NLR*sizeof(CostType) + // minLr[] and Lr[]\n            costBufSize*(hsumBufNRows + 1)*sizeof(CostType) +  // hsumBuf, pixdiff\n            CSBufSize*2*sizeof(CostType) + 1024;// C, S\n    if (totalBufSize > (unsigned int)std::numeric_limits<int>::max())\n    {\n        //std::cout << \"totalBufSize = \" << totalBufSize << std::endl;\n        D3D_THROW_EXCEPTION(\"Image too big for SGM\");\n    }\n    if( !buffer.data || !buffer.isContinuous() ||\n            buffer.cols*buffer.rows*buffer.elemSize() < totalBufSize )\n        buffer.create(1, (int)totalBufSize, CV_8U);\n\n    // summary cost over different (nDirs) directions\n    CostType* Cbuf = (CostType*)cv::alignPtr(buffer.data, ALIGN);\n    CostType* Sbuf = Cbuf + CSBufSize;\n    CostType* hsumBuf = Sbuf + CSBufSize;\n    CostType* pixDiff = hsumBuf + costBufSize*hsumBufNRows;\n\n    // add P2 to every C(x,y). it saves a few operations in the inner loops\n    for( k = 0; k < width1*D; k++ )\n        Cbuf[k] = (CostType)P2;\n\n    for( int pass = 1; pass <= npasses; pass++ )\n    {\n        int x1, y1, x2, y2, dx, dy;\n\n        if( pass == 1 )\n        {\n            y1 = 0; y2 = height; dy = 1;\n            x1 = 0; x2 = width1; dx = 1;\n        }\n        else\n        {\n            y1 = height-1; y2 = -1; dy = -1;\n            x1 = width1-1; x2 = -1; dx = -1;\n        }\n\n        CostType *Lr[NLR]={0}, *minLr[NLR]={0};\n\n        for( k = 0; k < NLR; k++ )\n        {\n            // shift Lr[k] and minLr[k] pointers, because we allocated them with the borders,\n            // and will occasionally use negative indices with the arrays\n            // we need to shift Lr[k] pointers by 1, to give the space for d=-1.\n            // however, then the alignment will be imperfect, i.e. bad for SSE,\n            // thus we shift the pointers by 8 (8*sizeof(short) == 16 - ideal alignment)\n            Lr[k] = pixDiff + costBufSize + LrSize*k + NRD2*LrBorder + 8;\n            memset( Lr[k] - LrBorder*NRD2 - 8, 0, LrSize*sizeof(CostType) );\n            minLr[k] = pixDiff + costBufSize + LrSize*NLR + minLrSize*k + NR2*2;\n            memset( minLr[k] - LrBorder*NR2, 0, minLrSize*sizeof(CostType) );\n        }\n\n        for( int y = y1; y != y2; y += dy )\n        {\n            int x, d;\n            DispType* disp1ptr = disp1.ptr<DispType>(y);\n            CostType* C = Cbuf + (!fullDP ? 0 : y*costBufSize);\n            CostType* S = Sbuf + (!fullDP ? 0 : y*costBufSize);\n\n            if( pass == 1 ) // compute C on the first pass, and reuse it on the second pass, if any.\n            {\n\n                // costs are copied in from given grid\n                for (int x = 0; x < width1; x++)\n                {\n                    for (int d = 0; d < D; d++)\n                    {\n                        // we assume that the given costs are in the range [0, 1]\n                        // so we multiply them by some constant to get a reasonable\n                        // resolution in the short values\n                        C[x*D + d] = std::min(costThresh,costVolume(x,y,d))*10000;\n                    }\n                }\n\n\n                // also, clear the S buffer\n                for( k = 0; k < width1*D; k++ )\n                    S[k] = 0;\n            }\n\n            // clear the left and the right borders\n            memset( Lr[0] - NRD2*LrBorder - 8, 0, NRD2*LrBorder*sizeof(CostType) );\n            memset( Lr[0] + width1*NRD2 - 8, 0, NRD2*LrBorder*sizeof(CostType) );\n            memset( minLr[0] - NR2*LrBorder, 0, NR2*LrBorder*sizeof(CostType) );\n            memset( minLr[0] + width1*NR2, 0, NR2*LrBorder*sizeof(CostType) );\n\n            /*\n             [formula 13 in the paper]\n             compute L_r(p, d) = C(p, d) +\n             min(L_r(p-r, d),\n             L_r(p-r, d-1) + P1,\n             L_r(p-r, d+1) + P1,\n             min_k L_r(p-r, k) + P2) - min_k L_r(p-r, k)\n             where p = (x,y), r is one of the directions.\n             we process all the directions at once:\n             0: r=(-dx, 0)\n             1: r=(-1, -dy)\n             2: r=(0, -dy)\n             3: r=(1, -dy)\n             4: r=(-2, -dy)\n             5: r=(-1, -dy*2)\n             6: r=(1, -dy*2)\n             7: r=(2, -dy)\n             */\n            for( x = x1; x != x2; x += dx )\n            {\n                int xm = x*NR2, xd = xm*D2;\n\n                int delta0 = minLr[0][xm - dx*NR2] + P2, delta1 = minLr[1][xm - NR2 + 1] + P2;\n                int delta2 = minLr[1][xm + 2] + P2, delta3 = minLr[1][xm + NR2 + 3] + P2;\n\n                CostType* Lr_p0 = Lr[0] + xd - dx*NRD2;\n                CostType* Lr_p1 = Lr[1] + xd - NRD2 + D2;\n                CostType* Lr_p2 = Lr[1] + xd + D2*2;\n                CostType* Lr_p3 = Lr[1] + xd + NRD2 + D2*3;\n\n                Lr_p0[-1] = Lr_p0[D] = Lr_p1[-1] = Lr_p1[D] =\n                        Lr_p2[-1] = Lr_p2[D] = Lr_p3[-1] = Lr_p3[D] = MAX_COST;\n\n                CostType* Lr_p = Lr[0] + xd;\n                const CostType* Cp = C + x*D;\n                //                cout << Cp[0] << \" \" << Cp[1] << endl;\n                CostType* Sp = S + x*D;\n\n#if CV_SSE2\n                if( useSIMD )\n                {\n                    __m128i _P1 = _mm_set1_epi16((short)P1);\n\n                    __m128i _delta0 = _mm_set1_epi16((short)delta0);\n                    __m128i _delta1 = _mm_set1_epi16((short)delta1);\n                    __m128i _delta2 = _mm_set1_epi16((short)delta2);\n                    __m128i _delta3 = _mm_set1_epi16((short)delta3);\n                    __m128i _minL0 = _mm_set1_epi16((short)MAX_COST);\n\n                    for( d = 0; d < D; d += 8 )\n                    {\n                        __m128i Cpd = _mm_load_si128((const __m128i*)(Cp + d));\n                        __m128i L0, L1, L2, L3;\n\n                        L0 = _mm_load_si128((const __m128i*)(Lr_p0 + d));\n                        L1 = _mm_load_si128((const __m128i*)(Lr_p1 + d));\n                        L2 = _mm_load_si128((const __m128i*)(Lr_p2 + d));\n                        L3 = _mm_load_si128((const __m128i*)(Lr_p3 + d));\n\n                        L0 = _mm_min_epi16(L0, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p0 + d - 1)), _P1));\n                        L0 = _mm_min_epi16(L0, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p0 + d + 1)), _P1));\n\n                        L1 = _mm_min_epi16(L1, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p1 + d - 1)), _P1));\n                        L1 = _mm_min_epi16(L1, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p1 + d + 1)), _P1));\n\n                        L2 = _mm_min_epi16(L2, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p2 + d - 1)), _P1));\n                        L2 = _mm_min_epi16(L2, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p2 + d + 1)), _P1));\n\n                        L3 = _mm_min_epi16(L3, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p3 + d - 1)), _P1));\n                        L3 = _mm_min_epi16(L3, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p3 + d + 1)), _P1));\n\n                        L0 = _mm_min_epi16(L0, _delta0);\n                        L0 = _mm_adds_epi16(_mm_subs_epi16(L0, _delta0), Cpd);\n\n                        L1 = _mm_min_epi16(L1, _delta1);\n                        L1 = _mm_adds_epi16(_mm_subs_epi16(L1, _delta1), Cpd);\n\n                        L2 = _mm_min_epi16(L2, _delta2);\n                        L2 = _mm_adds_epi16(_mm_subs_epi16(L2, _delta2), Cpd);\n\n                        L3 = _mm_min_epi16(L3, _delta3);\n                        L3 = _mm_adds_epi16(_mm_subs_epi16(L3, _delta3), Cpd);\n\n                        _mm_store_si128( (__m128i*)(Lr_p + d), L0);\n                        _mm_store_si128( (__m128i*)(Lr_p + d + D2), L1);\n                        _mm_store_si128( (__m128i*)(Lr_p + d + D2*2), L2);\n                        _mm_store_si128( (__m128i*)(Lr_p + d + D2*3), L3);\n\n                        __m128i t0 = _mm_min_epi16(_mm_unpacklo_epi16(L0, L2), _mm_unpackhi_epi16(L0, L2));\n                        __m128i t1 = _mm_min_epi16(_mm_unpacklo_epi16(L1, L3), _mm_unpackhi_epi16(L1, L3));\n                        t0 = _mm_min_epi16(_mm_unpacklo_epi16(t0, t1), _mm_unpackhi_epi16(t0, t1));\n                        _minL0 = _mm_min_epi16(_minL0, t0);\n\n                        __m128i Sval = _mm_load_si128((const __m128i*)(Sp + d));\n\n                        L0 = _mm_adds_epi16(L0, L1);\n                        L2 = _mm_adds_epi16(L2, L3);\n                        Sval = _mm_adds_epi16(Sval, L0);\n                        Sval = _mm_adds_epi16(Sval, L2);\n\n                        _mm_store_si128((__m128i*)(Sp + d), Sval);\n                    }\n\n                    _minL0 = _mm_min_epi16(_minL0, _mm_srli_si128(_minL0, 8));\n                    _mm_storel_epi64((__m128i*)&minLr[0][xm], _minL0);\n                }\n                else\n#endif\n                {\n                    int minL0 = MAX_COST, minL1 = MAX_COST, minL2 = MAX_COST, minL3 = MAX_COST;\n\n                    for( d = 0; d < D; d++ )\n                    {\n                        int Cpd = Cp[d], L0, L1, L2, L3;\n\n                        L0 = Cpd + std::min((int)Lr_p0[d], std::min(Lr_p0[d-1] + P1, std::min(Lr_p0[d+1] + P1, delta0))) - delta0;\n                        L1 = Cpd + std::min((int)Lr_p1[d], std::min(Lr_p1[d-1] + P1, std::min(Lr_p1[d+1] + P1, delta1))) - delta1;\n                        L2 = Cpd + std::min((int)Lr_p2[d], std::min(Lr_p2[d-1] + P1, std::min(Lr_p2[d+1] + P1, delta2))) - delta2;\n                        L3 = Cpd + std::min((int)Lr_p3[d], std::min(Lr_p3[d-1] + P1, std::min(Lr_p3[d+1] + P1, delta3))) - delta3;\n\n                        Lr_p[d] = (CostType)L0;\n                        minL0 = std::min(minL0, L0);\n\n                        Lr_p[d + D2] = (CostType)L1;\n                        minL1 = std::min(minL1, L1);\n\n                        Lr_p[d + D2*2] = (CostType)L2;\n                        minL2 = std::min(minL2, L2);\n\n                        Lr_p[d + D2*3] = (CostType)L3;\n                        minL3 = std::min(minL3, L3);\n\n                        Sp[d] = cv::saturate_cast<CostType>(Sp[d] + L0 + L1 + L2 + L3);\n                    }\n                    minLr[0][xm] = (CostType)minL0;\n                    minLr[0][xm+1] = (CostType)minL1;\n                    minLr[0][xm+2] = (CostType)minL2;\n                    minLr[0][xm+3] = (CostType)minL3;\n                }\n            }\n\n            if( pass == npasses )\n            {\n                for( x = 0; x < width; x++ )\n                {\n                    disp1ptr[x] = (DispType)INVALID_DISP_SCALED;\n                }\n\n                for( x = width1 - 1; x >= 0; x-- )\n                {\n                    CostType* Sp = S + x*D;\n                    int minS = MAX_COST, bestDisp = -1;\n\n                    if( npasses == 1 )\n                    {\n                        int xm = x*NR2, xd = xm*D2;\n\n                        int minL0 = MAX_COST;\n                        int delta0 = minLr[0][xm + NR2] + P2;\n                        CostType* Lr_p0 = Lr[0] + xd + NRD2;\n                        Lr_p0[-1] = Lr_p0[D] = MAX_COST;\n                        CostType* Lr_p = Lr[0] + xd;\n\n                        const CostType* Cp = C + x*D;\n\n#if CV_SSE2\n                        if( useSIMD )\n                        {\n                            __m128i _P1 = _mm_set1_epi16((short)P1);\n                            __m128i _delta0 = _mm_set1_epi16((short)delta0);\n\n                            __m128i _minL0 = _mm_set1_epi16((short)minL0);\n                            __m128i _minS = _mm_set1_epi16(MAX_COST), _bestDisp = _mm_set1_epi16(-1);\n                            __m128i _d8 = _mm_setr_epi16(0, 1, 2, 3, 4, 5, 6, 7), _8 = _mm_set1_epi16(8);\n\n                            for( d = 0; d < D; d += 8 )\n                            {\n                                __m128i Cpd = _mm_load_si128((const __m128i*)(Cp + d)), L0;\n\n                                L0 = _mm_load_si128((const __m128i*)(Lr_p0 + d));\n                                L0 = _mm_min_epi16(L0, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p0 + d - 1)), _P1));\n                                L0 = _mm_min_epi16(L0, _mm_adds_epi16(_mm_loadu_si128((const __m128i*)(Lr_p0 + d + 1)), _P1));\n                                L0 = _mm_min_epi16(L0, _delta0);\n                                L0 = _mm_adds_epi16(_mm_subs_epi16(L0, _delta0), Cpd);\n\n                                _mm_store_si128((__m128i*)(Lr_p + d), L0);\n                                _minL0 = _mm_min_epi16(_minL0, L0);\n                                L0 = _mm_adds_epi16(L0, *(__m128i*)(Sp + d));\n                                _mm_store_si128((__m128i*)(Sp + d), L0);\n\n                                __m128i mask = _mm_cmpgt_epi16(_minS, L0);\n                                _minS = _mm_min_epi16(_minS, L0);\n                                _bestDisp = _mm_xor_si128(_bestDisp, _mm_and_si128(_mm_xor_si128(_bestDisp,_d8), mask));\n                                _d8 = _mm_adds_epi16(_d8, _8);\n                            }\n\n                            short CV_DECL_ALIGNED(16) bestDispBuf[8];\n                            _mm_store_si128((__m128i*)bestDispBuf, _bestDisp);\n\n                            _minL0 = _mm_min_epi16(_minL0, _mm_srli_si128(_minL0, 8));\n                            _minL0 = _mm_min_epi16(_minL0, _mm_srli_si128(_minL0, 4));\n                            _minL0 = _mm_min_epi16(_minL0, _mm_srli_si128(_minL0, 2));\n\n                            __m128i qS = _mm_min_epi16(_minS, _mm_srli_si128(_minS, 8));\n                            qS = _mm_min_epi16(qS, _mm_srli_si128(qS, 4));\n                            qS = _mm_min_epi16(qS, _mm_srli_si128(qS, 2));\n\n                            minLr[0][xm] = (CostType)_mm_cvtsi128_si32(_minL0);\n                            minS = (CostType)_mm_cvtsi128_si32(qS);\n\n                            qS = _mm_shuffle_epi32(_mm_unpacklo_epi16(qS, qS), 0);\n                            qS = _mm_cmpeq_epi16(_minS, qS);\n                            int idx = _mm_movemask_epi8(_mm_packs_epi16(qS, qS)) & 255;\n\n                            bestDisp = bestDispBuf[LSBTab[idx]];\n                        }\n                        else\n#endif\n                        {\n                            for( d = 0; d < D; d++ )\n                            {\n                                int L0 = Cp[d] + std::min((int)Lr_p0[d], std::min(Lr_p0[d-1] + P1, std::min(Lr_p0[d+1] + P1, delta0))) - delta0;\n\n                                Lr_p[d] = (CostType)L0;\n                                minL0 = std::min(minL0, L0);\n\n                                int Sval = Sp[d] = cv::saturate_cast<CostType>(Sp[d] + L0);\n                                if( Sval < minS )\n                                {\n                                    minS = Sval;\n                                    bestDisp = d;\n                                }\n                            }\n                            minLr[0][xm] = (CostType)minL0;\n                        }\n                    }\n                    else\n                    {\n                        for( d = 0; d < D; d++ )\n                        {\n                            int Sval = Sp[d];\n                            if( Sval < minS )\n                            {\n                                minS = Sval;\n                                bestDisp = d;\n                            }\n                        }\n                    }\n\n                    if (outputUniquenessRatiosEnabled)\n                    {\n                        for (int d = 0; d < D; d++)\n                        {\n                            if (costVolume(x,y,d) == 0)\n                                uniquenessRatios(x,y) = 0;\n                            else if (costVolume(x,y,bestDisp)/costVolume(x,y,d) < uniquenessRatios(x,y))\n                                uniquenessRatios(x,y)  = costVolume(x,y,bestDisp)/costVolume(x,y,d);\n                        }\n                    }\n\n                    if (outputCostsEnabled)\n                    {\n                        costs(x,y) = costVolume(x,y,bestDisp);\n                    }\n\n                    if (outputDepthMapEnabled)\n                    {\n                        // compute depth from plane id\n                        double d = planes(bestDisp,0)(3);\n\n                        //std::cout << \"D = \" << D << \"  bestDisp = \" << bestDisp << \"  subPixelEnabled = \" << subPixelEnabled << std::endl;\n\n                        if (subPixelEnabled && bestDisp > 0 && bestDisp < D-1)\n                        {\n                            const double denom = Sp[bestDisp+1] + Sp[bestDisp-1] - 2*Sp[bestDisp];\n                           // std::cout << \"denom = \" << denom << std::endl;\n                            double offset = 0.0;\n                            if (denom > 1e-2)\n                            {\n                                offset = (Sp[bestDisp-1] - Sp[bestDisp])/denom - 0.5f;\n                            }\n\n                            if (offset < 0)\n                            {\n                                const int oPlaneIdx = bestDisp -1;\n\n                                float oPlaneD = planes(oPlaneIdx,0)(3);\n\n                                float dStep = (1.0f/oPlaneD - 1.0f/d)*offset;\n                                //std::cout << \"dStep = \" << dStep << std::endl;\n                                d = 1.0f/(1.0f/d - dStep);\n\n                            }\n                            if (offset > 0)\n                            {\n                                const int oPlaneIdx = bestDisp + 1;\n\n                                float oPlaneD = planes(oPlaneIdx,0)(3);\n\n                                float dStep = (1.0f/d - 1.0f/oPlaneD)*offset;\n                                //std::cout << \"dStep = \" << dStep << std::endl;\n                                d = 1.0f/(1.0f/d - dStep);\n                            }\n                        }\n                        Matrix<double, 3, 1> n = planes(bestDisp, 0).head(3);\n                        Matrix<double, 3, 1> pos;\n                        pos(0) = x; pos(1) = y; pos(2) = 1;\n\n                        double denom = pos.transpose()*refKinvT*n;\n                        result(x,y) = -d/denom;\n                    }\n                }\n            }\n\n            // now shift the cyclic buffers\n            std::swap( Lr[0], Lr[1] );\n            std::swap( minLr[0], minLr[1] );\n        }\n    }\n}\n\nvoid SemiGlobalMatching::setSmoothness(int P1, int P2)\n{\n    if (!(P2 > P1 && P1 > 0))\n    {\n        D3D_THROW_EXCEPTION(\"P2 must be bigger than P1 and both positive.\");\n    }\n\n    this->P1 = P1;\n    this->P2 = P2;\n}\n\nDepthMap<float, double> SemiGlobalMatching::getDepthMap()\n{\n    return result;\n}\n\nGrid<int> SemiGlobalMatching::getLabels()\n{\n    return labels;\n}\n\nvoid SemiGlobalMatching::enableOutputCostsEnabled(bool enabled)\n{\n    this->outputCostsEnabled = enabled;\n}\n\nvoid SemiGlobalMatching::enableOutputDepthMap(bool enabled)\n{\n    this->outputDepthMapEnabled = enabled;\n}\n\nvoid SemiGlobalMatching::enableOutputUniquenessRatios(bool enabled)\n{\n    this->outputUniquenessRatiosEnabled = enabled;\n}\n\nGrid<float> SemiGlobalMatching::getCosts()\n{\n    return costs;\n}\n\nGrid<float> SemiGlobalMatching::getUniquenessRatios()\n{\n    return uniquenessRatios;\n}\n\nvoid SemiGlobalMatching::enableOutputLabels(bool enabled)\n{\n    this->outputLabelsEnabled = enabled;\n}\n\nvoid SemiGlobalMatching::matchFromPlaneSweepWtihImage(const Grid<float> &costVolume, const Grid<Eigen::Vector4d> &planes, const CameraMatrix<double> &cam, cv::Mat image, float P1F, float P2F, float k)\n{\n    Matrix<double, 3, 3> refKinvT = Matrix<double, 3, 3>::Zero();\n    if (outputDepthMapEnabled)\n    {\n        result = DepthMap<float, double>(costVolume.getWidth(), costVolume.getHeight(), cam);\n        refKinvT  = cam.getK().inverse().transpose();\n    }\n\n    regularizeCostVolumeWithImage(costVolume, image, P1F, P2F, k);\n\n    if (outputDepthMapEnabled)\n    {\n        for (unsigned int y = 0; y < costVolume.getHeight(); y++)\n            for (unsigned int x = 0; x < costVolume.getWidth(); x++)\n            {\n                Matrix<double, 3, 1> n = planes(labels(x,y), 0).head(3);\n                double d = planes(labels(x,y),0)(3);\n\n                if (subPixelEnabled && labels(x,y) > 0 && labels(x,y) < (int)costVolume.getHeight()-1)\n                {\n\n                    if (offsets(x,y) < 0)\n                    {\n                        const int oPlaneIdx = labels(x,y) -1;\n\n                        float oPlaneD = planes(oPlaneIdx,0)(3);\n\n                        float dStep = (1.0f/oPlaneD - 1.0f/d)*offsets(x,y);\n                        //std::cout << \"dStep = \" << dStep << std::endl;\n                        d = 1.0f/(1.0f/d - dStep);\n\n                    }\n                    if (offsets(x,y) > 0)\n                    {\n                        const int oPlaneIdx = labels(x,y) + 1;\n\n                        float oPlaneD = planes(oPlaneIdx,0)(3);\n\n                        float dStep = (1.0f/d - 1.0f/oPlaneD)*offsets(x,y);\n                        //std::cout << \"dStep = \" << dStep << std::endl;\n                        d = 1.0f/(1.0f/d - dStep);\n                    }\n                }\n\n                Matrix<double, 3, 1> pos;\n                pos(0) = x; pos(1) = y; pos(2) = 1;\n\n                double denom = pos.transpose()*refKinvT*n;\n                result(x,y) = -d/denom;\n            }\n    }\n\n\n}\n\n\n// Non optimized but easy to change version of semi global matching\nvoid SemiGlobalMatching::regularizeCostVolumeWithImage(const Grid<float>& costVolume, cv::Mat image, float P1F, float P2F, float k)\n{\n    D3D::Grid<float> summedCosts = D3D::Grid<float>(costVolume.getWidth(), costVolume.getHeight(), costVolume.getDepth());\n    const int numPaths = 8;\n\n    D3D::Grid<float> pathCosts = D3D::Grid<float>(costVolume.getWidth(), costVolume.getHeight(), costVolume.getDepth());\n\n    int r1, r2;\n    int xS, yS;\n    int xR, yR;\n    int xE, yE;\n\n    for (int i = 0; i < numPaths; i++)\n    {\n        switch (i)\n        {\n        case 0:\n            r1 = -1;\n            r2 = 1;\n            xS = costVolume.getWidth()-1;\n            yS = 0;\n            xR = -1;\n            yR = 1;\n            xE = -1;\n            yE = costVolume.getHeight();\n            break;\n        case 1:\n            r1 = 1;\n            r2 = -1;\n            xS = 0;\n            yS = costVolume.getHeight()-1;\n            xR = 1;\n            yR = -1;\n            xE = costVolume.getWidth();\n            yE = -1;\n            break;\n        case 2:\n            r1 = -1;\n            r2 = -1;\n            xS = costVolume.getWidth()-1;\n            yS = costVolume.getHeight()-1;\n            xR = -1;\n            yR = -1;\n            xE = -1;\n            yE = -1;\n            break;\n        case 3:\n            r1 = 1;\n            r2 = 1;\n            xS = 0;\n            yS = 0;\n            xR = 1;\n            yR = 1;\n            xE = costVolume.getWidth();\n            yE = costVolume.getHeight();\n            break;\n        case 4:\n            r1 = 0;\n            r2 = -1;\n            xS = 0;\n            yS = costVolume.getHeight() - 1;\n            xR = 1;\n            yR = -1;\n            xE = costVolume.getWidth();\n            yE = -1;\n            break;\n        case 5:\n            r1 = 0;\n            r2 = 1;\n            xS = 0;\n            yS = 0;\n            xR = 1;\n            yR = 1;\n            xE = costVolume.getWidth();\n            yE = costVolume.getHeight();\n            break;\n        case 6:\n            r1 = -1;\n            r2 = 0;\n            xS = costVolume.getWidth() - 1;\n            yS = 0;\n            xR = -1;\n            yR = 1;\n            xE = -1;\n            yE = costVolume.getHeight();\n            break;\n        case 7:\n            r1 = 1;\n            r2 = 0;\n            xS = 0;\n            yS = 0;\n            xR = 1;\n            yR = 1;\n            xE = costVolume.getWidth();\n            yE = costVolume.getHeight();\n            break;\n        }\n\n        for (int y = yS; y != yE; y += yR)\n        {\n            std::cout << y << std::endl;\n            for (int x = xS; x != xE; x += xR)\n            {\n                // std::cout << xE << std::endl;\n                // std::cout << x << std::endl;\n\n                const int x0 = x - r1;\n                const int y0 = y - r2;\n\n                if (x0 < 0 || y0 < 0 || x0 >= (int) costVolume.getWidth() || y0 >= (int) costVolume.getHeight())\n                {\n                    for (int d = 0; d < (int) costVolume.getDepth(); d++)\n                        pathCosts(x,y,d) = costVolume(x,y,d);\n                }\n                else\n                {\n                    // compute P2' based on the image gradient\n//                    const float ib0 = (float) image.at<unsigned char>(y0,3*x0)/255.0f;\n//                    const float ib1 = (float) image.at<unsigned char>(y,3*x)/255.0f;\n//                    const float ig0 = (float) image.at<unsigned char>(y0,3*x0+1)/255.0f;\n//                    const float ig1 = (float) image.at<unsigned char>(y,3*x+1)/255.0f;\n//                    const float ir0 = (float) image.at<unsigned char>(y0,3*x0+2)/255.0f;\n//                    const float ir1 = (float) image.at<unsigned char>(y,3*x+2)/255.0f;\n\n//                    const float grad = std::fabs(ib0 - ib1) + std::fabs(ig0 - ig1) + std::fabs(ir0 - ir1);\n                    const float P2Fp = P2F; //std::max(P1F, k*P2F*3/grad);\n\n                    float lastMin = pathCosts(x0,y0,0);\n                    for (int d = 1; d < (int) costVolume.getDepth(); d++)\n                    {\n                        if (pathCosts(x0,y0,d) < lastMin)\n                            lastMin = pathCosts(x0,y0,d);\n                    }\n\n                    const float jumpCost = lastMin + P2Fp;\n\n                    for (int d = 0; d < (int) costVolume.getDepth(); d++)\n                    {\n                        float dispMinCost = std::min(jumpCost, pathCosts(x0,y0,d));\n                        if (d-1 >= 0)\n                        {\n                            const float m1Cost = pathCosts(x0,y0,d-1) + P1F;\n                            if (m1Cost < dispMinCost)\n                                dispMinCost = m1Cost;\n                        }\n                        if (d+1 < (int) costVolume.getDepth())\n                        {\n                            const float p1Cost = pathCosts(x0,y0,d+1) + P1F;\n                            if (p1Cost < dispMinCost)\n                                dispMinCost = p1Cost;\n                        }\n\n                        pathCosts(x,y,d) = costVolume(x,y,d) + dispMinCost - lastMin;\n                    }\n                }\n            }\n        }\n\n        for (int y = 0; y < (int) costVolume.getHeight(); y++)\n            for (int x = 0; x < (int) costVolume.getWidth(); x++)\n                for (int d = 0; d < (int) costVolume.getDepth(); d++)\n                {\n                    if (i == 0)\n                    {\n                        summedCosts(x,y,d) = pathCosts(x,y,d)/(float)numPaths;\n                    }\n                    else\n                    {\n                        summedCosts(x,y,d) += pathCosts(x,y,d)/(float)numPaths;\n                    }\n                }\n    }\n\n    pathCosts.resize(1,1,1);\n\n    labels.resize(costVolume.getWidth(), costVolume.getHeight(), 1);\n\n    if (subPixelEnabled)\n    {\n        offsets.resize(costVolume.getWidth(), costVolume.getHeight(), 1);\n    }\n\n    for (int y = 0; y < (int) costVolume.getHeight(); y++)\n        for (int x = 0; x < (int) costVolume.getWidth(); x++)\n        {\n            int bestLabel = 0;\n            float bestCost = summedCosts(x,y,0);\n\n            for (int d = 1; d < (int) costVolume.getDepth(); d++)\n            {\n                if (summedCosts(x,y,d) < bestCost)\n                {\n                    bestLabel = d;\n                    bestCost = summedCosts(x,y,d);\n                }\n            }\n\n            if (subPixelEnabled)\n            {\n                // if subpixel is enabled we need to compute the label offsets\n                offsets(x,y) = 0;\n\n                if (bestLabel > 0 && bestLabel < (int)costVolume.getDepth()-1)\n                {\n                    const float denom = summedCosts(x,y,bestLabel+1) + summedCosts(x,y,bestLabel-1) - 2*summedCosts(x,y,bestLabel);\n                    // std::cout << \"denom = \" << denom << std::endl;\n                    if (denom > 1e-2)\n                    {\n                        offsets(x,y) = (summedCosts(x,y,bestLabel-1) - summedCosts(x,y,bestLabel))/denom - 0.5f;\n                    }\n                }\n\n            }\n\n            labels(x,y) = bestLabel;\n        }\n}\n", "meta": {"hexsha": "d46fe111384ea978748b838b9998ff08072f6c0b", "size": 36887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vision-normal-fusion/libs/D3D/src/d3d_stereo/semiGlobalMatching.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/libs/D3D/src/d3d_stereo/semiGlobalMatching.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/libs/D3D/src/d3d_stereo/semiGlobalMatching.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": 39.1581740977, "max_line_length": 200, "alphanum_fraction": 0.4710331553, "num_tokens": 10782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.03308597529010575, "lm_q1q2_score": 0.0110702179856332}}
{"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#define BOOST_PYTHON_MAX_ARITY 40\n#include <boost/python.hpp>\n#include <cmath>\n#include <iostream>\n\n#include \"numpy_bind.hh\"\n\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n#include \"graph_filtering.hh\"\n\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_properties.hh\"\n#include \"graph_util.hh\"\n\n#include \"random.hh\"\n\n#include \"config.h\"\n\n#include \"graph_blockmodel_overlap.hh\"\n#include \"graph_blockmodel.hh\"\n\nusing namespace boost;\nusing namespace graph_tool;\n\n\n\n// ====================\n// Entropy calculation\n// ====================\n\n\n// Repeated computation of x*log(x) and log(x) actually adds up to a lot of\n// time. A significant speedup can be made by caching pre-computed values. This\n// is doable since the values of mrse are bounded in [0, 2E], where E is the\n// total number of edges in the network. Here we simply grow the cache as\n// needed.\n\nnamespace graph_tool\n{\n\nvector<double> __safelog_cache;\nvector<double> __xlogx_cache;\nvector<double> __lgamma_cache;\n\nvoid init_safelog(size_t x)\n{\n    size_t old_size = __safelog_cache.size();\n    if (x >= old_size)\n    {\n        __safelog_cache.resize(x + 1);\n        for (size_t i = old_size; i < __safelog_cache.size(); ++i)\n            __safelog_cache[i] = safelog(double(i));\n    }\n}\n\nvoid clear_safelog()\n{\n    vector<double>().swap(__safelog_cache);\n}\n\n\nvoid init_xlogx(size_t x)\n{\n    size_t old_size = __xlogx_cache.size();\n    if (x >= old_size)\n    {\n        __xlogx_cache.resize(x + 1);\n        for (size_t i = old_size; i < __xlogx_cache.size(); ++i)\n            __xlogx_cache[i] = i * safelog(i);\n    }\n}\n\nvoid clear_xlogx()\n{\n    vector<double>().swap(__xlogx_cache);\n}\n\nvoid init_lgamma(size_t x)\n{\n    size_t old_size = __lgamma_cache.size();\n    if (x >= old_size)\n    {\n        __lgamma_cache.resize(x + 1);\n        for (size_t i = old_size; i < __lgamma_cache.size(); ++i)\n            __lgamma_cache[i] = lgamma(i);\n    }\n}\n\nvoid clear_lgamma()\n{\n    vector<double>().swap(__lgamma_cache);\n}\n\n\n}\n\ndouble do_get_ent(GraphInterface& gi, boost::any omrs, boost::any omrp,\n                  boost::any omrm, boost::any owr, bool deg_corr)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    emap_t mrs = any_cast<emap_t>(omrs);\n    vmap_t mrp = any_cast<vmap_t>(omrp);\n    vmap_t mrm = any_cast<vmap_t>(omrm);\n    vmap_t wr = any_cast<vmap_t>(owr);\n\n    double S = 0;\n    run_action<>()\n        (gi, std::bind(entropy(), mrs, mrp, mrm, wr, deg_corr,\n                       placeholders::_1,\n                       std::ref(S)))();\n    return S;\n}\n\ndouble do_get_ent_dense(GraphInterface& gi, boost::any omrs, boost::any owr,\n                        bool multigraph)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    emap_t mrs = any_cast<emap_t>(omrs);\n    vmap_t wr = any_cast<vmap_t>(owr);\n\n    double S = 0;\n    run_action<>()\n        (gi, std::bind(entropy_dense(), mrs, wr, multigraph,\n                       placeholders::_1, std::ref(S)))();\n    return S;\n}\n\ndouble do_get_ent_parallel(GraphInterface& gi, boost::any oweight)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    emap_t weight = any_cast<emap_t>(oweight);\n\n    double S = 0;\n    run_action<>()\n        (gi, std::bind(entropy_parallel_edges(),\n                       placeholders::_1, weight, std::ref(S)))();\n    return S;\n}\n\n\nboost::any do_create_emat(GraphInterface& gi)\n{\n    boost::any emat;\n    run_action<>()(gi, std::bind<void>(create_emat(), placeholders::_1,\n                                       std::ref(emat)))();\n    return emat;\n}\n\nboost::any do_create_ehash(GraphInterface& gi)\n{\n    boost::any emat;\n    run_action<>()(gi, std::bind<void>(create_ehash(), placeholders::_1,\n                                       std::ref(emat)))();\n    return emat;\n}\n\n//============\n// Main loops\n//============\n\n\ntemplate <class Eprop, class Vprop, class VEprop>\nstruct move_sweep_dispatch\n{\n    move_sweep_dispatch(Eprop eweight, Vprop vweight, boost::any egroups,\n                        VEprop esrcpos, VEprop etgtpos, Vprop label,\n                        vector<int>& vlist, bool deg_corr, bool dense,\n                        bool multigraph, double beta, bool sequential,\n                        bool parallel, bool random_move, double c, bool verbose,\n                        size_t max_edge_index, size_t nmerges, size_t niter,\n                        Vprop merge_map, partition_stats_t& partition_stats,\n                        rng_t& rng, double& S, size_t& nmoves,\n                        GraphInterface& bgi)\n\n        : eweight(eweight), vweight(vweight), oegroups(egroups), esrcpos(esrcpos),\n          etgtpos(etgtpos), label(label), vlist(vlist),\n          deg_corr(deg_corr), dense(dense), multigraph(multigraph), beta(beta),\n          sequential(sequential), parallel(parallel), random_move(random_move),\n          c(c), verbose(verbose), max_edge_index(max_edge_index),\n          nmerges(nmerges), niter(niter), merge_map(merge_map),\n          partition_stats(partition_stats), rng(rng), S(S),\n          nmoves(nmoves), bgi(bgi)\n    {}\n\n    Eprop eweight;\n    Vprop vweight;\n    boost::any oegroups;\n    VEprop esrcpos;\n    VEprop etgtpos;\n    Vprop label;\n    size_t n;\n    vector<int>& vlist;\n    bool deg_corr;\n    bool dense;\n    bool multigraph;\n    double beta;\n    bool sequential;\n    bool parallel;\n    bool random_move;\n    double c;\n    bool verbose;\n    size_t max_edge_index;\n    size_t nmerges;\n    size_t niter;\n    Vprop merge_map;\n    partition_stats_t& partition_stats;\n    rng_t& rng;\n    double& S;\n    size_t& nmoves;\n    GraphInterface& bgi;\n\n    template <class Graph>\n    void operator()(Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b,\n                    Graph& g, boost::any& emat, boost::any sampler,\n                    boost::any cavity_sampler, bool weighted) const\n    {\n        if (is_directed::apply<Graph>::type::value)\n        {\n            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, cavity_sampler,\n                     bgi.GetGraph(), weighted);\n        }\n        else\n        {\n            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.GetGraph());\n            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, cavity_sampler, ug,\n                     weighted);\n        }\n    }\n\n    template <class Graph, class BGraph>\n    void dispatch(Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b, Graph& g,\n                  boost::any& aemat, boost::any asampler,\n                  boost::any acavity_sampler, BGraph& bg, bool weighted) const\n    {\n        if (weighted)\n        {\n            typedef typename property_map_type::apply<DynamicSampler<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,\n                                                      GraphInterface::vertex_index_map_t>::type vemap_t;\n            vemap_t egroups = any_cast<vemap_t>(oegroups);\n\n            try\n            {\n                typedef typename get_emat_t::apply<BGraph>::type emat_t;\n                emat_t& emat = any_cast<emat_t&>(aemat);\n                size_t B = num_vertices(bg);\n                size_t max_BE = is_directed::apply<Graph>::type::value ?\n                    B * B : (B * (B + 1)) / 2;\n                dispatch(mrs.get_unchecked(max_BE), mrp, mrm, wr, b, g,\n                         asampler, acavity_sampler, bg, egroups, emat);\n            }\n            catch (bad_any_cast&)\n            {\n                typedef typename get_ehash_t::apply<BGraph>::type emat_t;\n                emat_t& emat = any_cast<emat_t&>(aemat);\n\n                dispatch(mrs, mrp, mrm, wr, b, g, asampler, acavity_sampler, bg,\n                         egroups, emat);\n            }\n        }\n        else\n        {\n            typedef typename property_map_type::apply<vector<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,\n                                                      GraphInterface::vertex_index_map_t>::type vemap_t;\n            vemap_t egroups = any_cast<vemap_t>(oegroups);\n\n            try\n            {\n                typedef typename get_emat_t::apply<BGraph>::type emat_t;\n                emat_t& emat = any_cast<emat_t&>(aemat);\n                size_t B = num_vertices(bg);\n                size_t max_BE = is_directed::apply<Graph>::type::value ?\n                    B * B : (B * (B + 1)) / 2;\n                dispatch(mrs.get_unchecked(max_BE), mrp, mrm, wr, b, g,\n                         asampler, acavity_sampler, bg, egroups, emat);\n            }\n            catch (bad_any_cast&)\n            {\n                typedef typename get_ehash_t::apply<BGraph>::type emat_t;\n                emat_t& emat = any_cast<emat_t&>(aemat);\n\n                dispatch(mrs, mrp, mrm, wr, b, g, asampler, acavity_sampler, bg,\n                         egroups, emat);\n            }\n        }\n    }\n\n    template <class Graph, class BGraph, class Egroups, class Emat, class MEprop>\n    void dispatch(MEprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b, Graph& g,\n                  boost::any asampler, boost::any acavity_sampler, BGraph& bg,\n                  Egroups egroups, Emat& emat) const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n\n        size_t eidx = random_move ? 1 : max_edge_index;\n\n        typedef typename property_map<Graph, vertex_index_t>::type vindex_map_t;\n        typedef typename property_map_type::apply<Sampler<vertex_t, boost::mpl::false_>,\n                                                  vindex_map_t>::type::unchecked_t\n            sampler_map_t;\n        sampler_map_t sampler = any_cast<sampler_map_t>(asampler);\n        sampler_map_t cavity_sampler = any_cast<sampler_map_t>(acavity_sampler);\n\n        ConstantPropertyMap<std::array<int, 1>, typename graph_traits<Graph>::vertex_descriptor> cv({-1});\n        IdentityArrayPropertyMap<typename graph_traits<Graph>::vertex_descriptor> vmap;\n        boost::typed_identity_property_map<int> identity;\n\n        // make sure the properties are _unchecked_, since otherwise it\n        // affects performance\n\n        overlap_stats_t ostats;\n        vector<size_t> free_blocks;\n        auto state = make_block_state(g, eweight.get_unchecked(max_edge_index),\n                                      vweight.get_unchecked(num_vertices(g)),\n                                      b.get_unchecked(num_vertices(g)), bg,\n                                      emat, mrs,\n                                      mrp.get_unchecked(num_vertices(bg)),\n                                      mrm.get_unchecked(num_vertices(bg)),\n                                      wr.get_unchecked(num_vertices(bg)),\n                                      egroups.get_unchecked(num_vertices(bg)),\n                                      esrcpos.get_unchecked(eidx),\n                                      etgtpos.get_unchecked(eidx), sampler,\n                                      cavity_sampler, partition_stats, ostats,\n                                      identity, identity, free_blocks,\n                                      false, false, true);\n\n        vector<decltype(state)> states = {state};\n        vector<EntrySet<Graph>> m_entries = {EntrySet<Graph>(num_vertices(bg))};\n\n        move_sweep(states, m_entries,\n                   wr.get_unchecked(num_vertices(bg)),\n                   b.get_unchecked(num_vertices(g)),\n                   cv, vmap,\n                   label.get_unchecked(num_vertices(bg)), vlist, deg_corr,\n                   dense, multigraph, beta,\n                   eweight.get_unchecked(max_edge_index),\n                   vweight.get_unchecked(num_vertices(g)),\n                   g, sequential, parallel, random_move, c,\n                   nmerges,\n                   merge_map.get_unchecked(num_vertices(g)),\n                   niter, num_vertices(bg),\n                   verbose, rng, S, nmoves);\n    }\n};\n\n\nboost::python::object do_move_sweep(GraphInterface& gi, GraphInterface& bgi,\n                                    boost::any& emat, boost::any sampler,\n                                    boost::any cavity_sampler, boost::any omrs,\n                                    boost::any omrp, boost::any omrm,\n                                    boost::any owr, boost::any ob,\n                                    boost::any olabel, vector<int>& vlist,\n                                    bool deg_corr, bool dense, bool multigraph,\n                                    boost::any oeweight, boost::any ovweight,\n                                    boost::any oegroups, boost::any oesrcpos,\n                                    boost::any oetgtpos, double beta,\n                                    bool sequential, bool parallel,\n                                    bool random_move, double c, bool weighted,\n                                    size_t nmerges, boost::any omerge_map,\n                                    size_t niter,\n                                    partition_stats_t& partition_stats,\n                                    bool verbose, rng_t& rng)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        vemap_t;\n    emap_t mrs = any_cast<emap_t>(omrs);\n    vmap_t mrp = any_cast<vmap_t>(omrp);\n    vmap_t mrm = any_cast<vmap_t>(omrm);\n    vmap_t wr = any_cast<vmap_t>(owr);\n    vmap_t b = any_cast<vmap_t>(ob);\n    vmap_t label = any_cast<vmap_t>(olabel);\n    emap_t eweight = any_cast<emap_t>(oeweight);\n    vmap_t vweight = any_cast<vmap_t>(ovweight);\n\n    vemap_t esrcpos = any_cast<vemap_t>(oesrcpos);\n    vemap_t etgtpos = any_cast<vemap_t>(oetgtpos);\n\n    double S = 0;\n    size_t nmoves = 0;\n\n    vmap_t merge_map = any_cast<vmap_t>(omerge_map);\n\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind(move_sweep_dispatch<emap_t, vmap_t, vemap_t>\n                       (eweight, vweight, oegroups, esrcpos, etgtpos,\n                        label, vlist, deg_corr, dense, multigraph, beta,\n                        sequential, parallel, random_move, c, verbose,\n                        gi.GetMaxEdgeIndex(), nmerges, niter, merge_map,\n                        partition_stats, rng, S, nmoves, bgi),\n                       mrs, mrp, mrm, wr, b, placeholders::_1,\n                       std::ref(emat), sampler, cavity_sampler, weighted))();\n    return boost::python::make_tuple(S, nmoves);\n}\n\nstruct build_egroups\n{\n    template <class Eprop, class Vprop, class VEprop, class Graph, class VertexIndex>\n    void operator()(Vprop b, boost::any& oegroups, VEprop esrcpos,\n                    VEprop etgtpos, Eprop eweight, Graph& g,\n                    VertexIndex vertex_index, size_t B, bool weighted, bool empty) const\n    {\n        egroups_manage::build(b, oegroups, esrcpos, etgtpos, eweight, g,\n                              vertex_index, B, weighted, empty);\n    }\n};\n\nboost::any do_build_egroups(GraphInterface& gi, GraphInterface& bgi,\n                            boost::any ob, boost::any oeweights,\n                            boost::any oesrcpos, boost::any oetgtpos,\n                            bool weighted, bool empty)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        vemap_t;\n    vmap_t b = any_cast<vmap_t>(ob);\n\n    vemap_t esrcpos = any_cast<vemap_t>(oesrcpos);\n    vemap_t etgtpos = any_cast<vemap_t>(oetgtpos);\n    emap_t eweights = any_cast<emap_t>(oeweights);\n\n    boost::any oegroups;\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind<void>(build_egroups(), b, std::ref(oegroups),\n                             esrcpos.get_unchecked(gi.GetMaxEdgeIndex()),\n                             etgtpos.get_unchecked(gi.GetMaxEdgeIndex()),\n                             eweights.get_unchecked(gi.GetMaxEdgeIndex()),\n                             placeholders::_1, bgi.GetVertexIndex(),\n                             bgi.GetNumberOfVertices(), weighted, empty))();\n    return oegroups;\n}\n\nboost::any do_init_neighbour_sampler(GraphInterface& gi, boost::any oeweights,\n                                     bool self_loops, bool empty)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    emap_t eweights = any_cast<emap_t>(oeweights);\n\n    boost::any osampler;\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind(init_neighbour_sampler(), placeholders::_1, eweights,\n                       self_loops, empty, std::ref(osampler)))();\n    return osampler;\n}\n\nstruct collect_edge_marginals_dispatch\n{\n    template <class Graph, class Vprop, class MEprop>\n    void operator()(Graph& g, size_t B, Vprop cb, MEprop p,\n                    std::tuple<boost::any, GraphInterface&> abg) const\n    {\n        Graph& bg = *any_cast<Graph*>(get<0>(abg));\n        collect_edge_marginals(B, cb.get_unchecked(num_vertices(bg)), p, g, bg);\n    }\n};\n\nvoid do_collect_edge_marginals(GraphInterface& gi, GraphInterface& gbi,\n                               size_t B, boost::any ob, boost::any op)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    vmap_t b = any_cast<vmap_t>(ob);\n    emap_t p = any_cast<emap_t>(op);\n\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind<void>(collect_edge_marginals_dispatch(),\n                             placeholders::_1, B, b, p,\n                             std::tuple<boost::any, GraphInterface&>(gbi.GetGraphView(), gbi)))();\n}\n\nboost::python::tuple do_bethe_entropy(GraphInterface& gi, size_t B, boost::any op,\n                                      boost::any opv)\n{\n    typedef property_map_type::apply<vector<double>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    emap_t p = any_cast<emap_t>(op);\n    vmap_t pv = any_cast<vmap_t>(opv);\n\n    double H=0, sH=0, Hmf=0, sHmf=0;\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind<void>(bethe_entropy(),\n                             placeholders::_1, B, p, pv, std::ref(H), std::ref(sH),\n                             std::ref(Hmf), std::ref(sHmf)))();\n    return boost::python::make_tuple(H, sH, Hmf, sHmf);\n}\n\n\nstruct collect_vertex_marginals_dispatch\n{\n    template <class Graph, class Vprop, class MEprop>\n    void operator()(Graph& g, Vprop cb, MEprop p) const\n    {\n        collect_vertex_marginals(cb.get_unchecked(num_vertices(g)),\n                                 p.get_unchecked(num_vertices(g)), g);\n    }\n};\n\n\nvoid do_collect_vertex_marginals(GraphInterface& gi, boost::any ob,\n                                 boost::any op)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    vmap_t b = any_cast<vmap_t>(ob);\n\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind(collect_vertex_marginals_dispatch(),\n                       placeholders::_1, b, placeholders::_2),\n         vertex_scalar_vector_properties())(op);\n}\n\n\nstruct get_deg_entropy_term\n{\n    template <class Graph>\n    void operator()(Graph& g, double& S) const\n    {\n        for(auto v : vertices_range(g))\n        {\n            S -= lgamma_fast(out_degree(v, g) + 1);\n            S -= lgamma_fast(in_degreeS()(v, g) + 1);\n        }\n    }\n};\n\nstruct get_deg_entropy_term_overlap\n{\n\n    template <class Graph, class Vprop>\n    void operator()(Graph& g, Vprop b, overlap_stats_t& overlap_stats, size_t N,\n                    double& S) const\n    {\n#ifdef HAVE_SPARSEHASH\n        typedef dense_hash_map<int, int, std::hash<int>> map_t;\n#else\n        typedef unordered_map<int, int> map_t;\n#endif\n\n        map_t in_hist, out_hist;\n\n#ifdef HAVE_SPARSEHASH\n        in_hist.set_empty_key(numeric_limits<int>::max());\n        out_hist.set_empty_key(numeric_limits<int>::max());\n#endif\n\n        for (size_t v = 0; v < N; ++v)\n        {\n            in_hist.clear();\n            out_hist.clear();\n\n            auto& half_edges = overlap_stats.get_half_edges(v);\n            for (size_t u : half_edges)\n            {\n                in_hist[b[u]] += in_degreeS()(u, g);\n                out_hist[b[u]] += out_degree(u, g);\n            }\n\n            for (auto& k_c : in_hist)\n                S -= lgamma_fast(k_c.second + 1);\n            for (auto& k_c : out_hist)\n                S -= lgamma_fast(k_c.second + 1);\n        }\n    }\n};\n\ndouble do_get_deg_entropy_term(GraphInterface& gi, boost::any ob,\n                               overlap_stats_t& overlap_stats, size_t N)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n\n    double S = 0;\n\n    if (!ob.empty())\n    {\n        vmap_t b = any_cast<vmap_t>(ob);\n        run_action<>()\n            (gi, std::bind(get_deg_entropy_term_overlap(),\n                           placeholders::_1, b, std::ref(overlap_stats), N,\n                           std::ref(S)))();\n    }\n    else\n    {\n        run_action<>()\n            (gi, std::bind(get_deg_entropy_term(),\n                           placeholders::_1, std::ref(S)))();\n    }\n\n    return S;\n}\n\n\nvector<int32_t> get_vector(size_t n)\n{\n    return vector<int32_t>(n);\n}\n\ntemplate <class Value>\nvoid vector_map(boost::python::object ovals, boost::python::object omap)\n{\n\n    multi_array_ref<Value,1> vals = get_array<Value,1>(ovals);\n    multi_array_ref<Value,1> map = get_array<Value,1>(omap);\n\n    size_t pos = 0;\n    for (size_t i = 0; i < vals.size(); ++i)\n    {\n        Value v = vals[i];\n        if (map[v] == -1)\n            map[v] = pos++;\n        vals[i] = map[v];\n    }\n}\n\ntemplate <class Value>\nvoid vector_continuous_map(boost::python::object ovals)\n{\n\n    multi_array_ref<Value,1> vals = get_array<Value,1>(ovals);\n    unordered_map<Value, size_t> map;\n\n    for (size_t i = 0; i < vals.size(); ++i)\n    {\n        Value v = vals[i];\n        auto iter = map.find(v);\n        if (iter == map.end())\n            iter = map.insert(make_pair(v, map.size())).first;\n        vals[i] = iter->second;\n    }\n}\n\ntemplate <class Value>\nvoid vector_rmap(boost::python::object ovals, boost::python::object omap)\n{\n\n    multi_array_ref<Value,1> vals = get_array<Value,1>(ovals);\n    multi_array_ref<Value,1> map = get_array<Value,1>(omap);\n\n    for (size_t i = 0; i < vals.size(); ++i)\n    {\n        map[vals[i]] = i;\n    }\n}\n\npython::tuple python_get_mu_l(double N, double E, double epsilon=1e-8)\n{\n    double mu, l;\n    get_mu_l(N, E, mu, l, epsilon);\n    return python::make_tuple(mu, l);\n}\n\nstruct get_partition_stats\n{\n    template <class Graph, class Vprop, class Eprop>\n    void operator()(Graph& g, Vprop b, Eprop eweight, size_t N, size_t B,\n                    bool edges_dl, partition_stats_t& partition_stats) const\n    {\n        partition_stats = partition_stats_t(g, b, eweight, N, B, edges_dl);\n    }\n};\n\npartition_stats_t\ndo_get_partition_stats(GraphInterface& gi, boost::any ob, boost::any aeweight,\n                       size_t N, size_t B, bool edges_dl)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n\n    partition_stats_t partition_stats;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    emap_t eweight = any_cast<emap_t>(aeweight);\n\n    run_action<>()(gi, std::bind(get_partition_stats(),\n                                 placeholders::_1, b, eweight, N, B, edges_dl,\n                                 std::ref(partition_stats)))();\n    return partition_stats;\n}\n\nvoid export_blockmodel()\n{\n    using namespace boost::python;\n\n    class_<partition_stats_t>(\"partition_stats\")\n        .def(\"is_enabled\", &partition_stats_t::is_enabled)\n        .def(\"get_partition_dl\", &partition_stats_t::get_partition_dl)\n        .def(\"get_deg_dl\", &partition_stats_t::get_deg_dl);\n\n    def(\"init_partition_stats\", do_get_partition_stats);\n\n    def(\"init_safelog\", init_safelog);\n    def(\"clear_safelog\", clear_safelog);\n    def(\"init_xlogx\", init_xlogx);\n    def(\"clear_xlogx\", clear_xlogx);\n    def(\"init_lgamma\", init_lgamma);\n    def(\"clear_lgamma\", clear_lgamma);\n    def(\"get_xi\", get_xi<double,double>);\n    def(\"get_xi_fast\", get_xi_fast<double,double>);\n    def(\"get_mu_l\", python_get_mu_l);\n    def(\"polylog\", polylog<double>);\n    def(\"lbinom_careful\", lbinom_careful);\n    def(\"lbinom_fast\", lbinom_fast);\n    def(\"lbinom\", lbinom);\n\n    def(\"get_vector\", get_vector);\n    def(\"vector_map\", vector_map<int32_t>);\n    def(\"vector_map64\", vector_map<int64_t>);\n    def(\"vector_rmap\", vector_rmap<int32_t>);\n    def(\"vector_rmap64\", vector_rmap<int64_t>);\n    def(\"vector_continuous_map\", vector_continuous_map<int32_t>);\n    def(\"vector_continuous_map64\", vector_continuous_map<int64_t>);\n\n    def(\"create_emat\", do_create_emat);\n    def(\"create_ehash\", do_create_ehash);\n    def(\"build_egroups\", do_build_egroups);\n    def(\"init_neighbour_sampler\", do_init_neighbour_sampler);\n\n    def(\"move_sweep\", do_move_sweep);\n\n    def(\"entropy\", do_get_ent);\n    def(\"entropy_dense\", do_get_ent_dense);\n    def(\"entropy_parallel\", do_get_ent_parallel);\n    def(\"deg_entropy_term\", do_get_deg_entropy_term);\n\n    def(\"edge_marginals\", do_collect_edge_marginals);\n    def(\"bethe_entropy\", do_bethe_entropy);\n    def(\"vertex_marginals\", do_collect_vertex_marginals);\n}\n", "meta": {"hexsha": "a6cbad753aa08c2565f346365d2aa17191390b62", "size": 27817, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/community/graph_blockmodel.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/community/graph_blockmodel.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/community/graph_blockmodel.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": 35.3007614213, "max_line_length": 135, "alphanum_fraction": 0.5786030125, "num_tokens": 6757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.02442308898897509, "lm_q1q2_score": 0.011070054088634668}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <list>\n#include <stdio.h>\n\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\n#include \"configuration.hpp\"\n#include \"third_party/yaml/include/yaml/yaml.h\"\n\nnamespace color {\nconstexpr int kRed = 0;\nconstexpr int kBoldRed = 1;\nconstexpr int kGreen = 2;\nconstexpr int kBoldGreen = 3;\nconstexpr int kYellow = 4;\nconstexpr int kBoldYellow = 5;\nconstexpr int kBlue = 6;\nconstexpr int kBoldBlue = 7;\nconstexpr int kMagneta = 8;\nconstexpr int kBoldMagneta = 9;\nconstexpr int kCyan = 10;\nconstexpr int kBoldCyan = 11;\n}; // namespace color\n\nnamespace util {\nvoid SaveVector(const Eigen::VectorXd &vec_, std::string name_,\n                bool b_param = false);\nvoid SaveVector(double *_vec, std::string _name, int size,\n                bool b_param = false);\nvoid SaveVector(const std::vector<double> &_vec, std::string _name,\n                bool b_param = false);\nvoid SaveValue(double _value, std::string _name, bool b_param = false);\nvoid CleaningFile(std::string file_name_, std::string &ret_file_, bool b_param);\nstatic std::list<std::string> gs_fileName_string; // global & static\n\ntemplate <typename YamlType>\nYamlType ReadParameter(const YAML::Node &node, const std::string &name) {\n  try {\n    return node[name.c_str()].as<YamlType>();\n  } catch (...) {\n    throw std::runtime_error(name);\n  }\n};\n\ntemplate <typename YamlType>\nvoid ReadParameter(const YAML::Node &node, const std::string &name,\n                   YamlType &parameter) {\n  try {\n    parameter = ReadParameter<YamlType>(node, name);\n  } catch (...) {\n    throw std::runtime_error(name);\n  }\n};\n\nvoid PrettyConstructor(const int &_num_tab, const std::string &_name);\nvoid ColorPrint(const int &_color, const std::string &_name,\n                bool line_change = true);\n\nEigen::MatrixXd hStack(const Eigen::MatrixXd &a_, const Eigen::MatrixXd &b_);\nEigen::MatrixXd vStack(const Eigen::MatrixXd &a_, const Eigen::MatrixXd &b_);\nEigen::MatrixXd block_diag(const Eigen::MatrixXd &a, const Eigen::MatrixXd &b);\n\nEigen::Matrix3d SkewSymmetric(const Eigen::Vector3d &omg);\nEigen::MatrixXd Adjoint(const Eigen::MatrixXd &R, const Eigen::Vector3d &p);\n\nEigen::Vector3d QuatToExp(const Eigen::Quaternion<double> &quat);\nEigen::Quaternion<double> ExpToQuat(const Eigen::Vector3d &exp);\n\n// Euler ZYX\n//     Represents either:\n//     extrinsic XYZ rotations: Fixed-frame roll, then fixed-frame pitch, then\n//     fixed-frame yaw.\n//     or intrinsic ZYX rotations: Body-frame yaw, body-frame pitch, then\n//     body-frame roll\n//\n//     The equation is similar, but the values for fixed and body frame\n//     rotations are different.\n// World Orientation is R = Rz*Ry*Rx\nEigen::Quaterniond EulerZYXtoQuat(const double roll, const double pitch,\n                                  const double yaw);\n\n// Quaternion to Euler ZYX\nEigen::Vector3d QuatToEulerZYX(const Eigen::Quaterniond &quat_in);\n\n// ZYX extrinsic rotation rates to world angular velocity\n// angular vel = [wx, wy, wz]\nEigen::Vector3d EulerZYXRatestoAngVel(const double roll, const double pitch,\n                                      const double yaw, const double roll_rate,\n                                      const double pitch_rate,\n                                      const double yaw_rate);\n\nvoid AvoidQuatJump(const Eigen::Quaternion<double> &des_ori,\n                   Eigen::Quaternion<double> &act_ori);\n\ndouble Clamp(const double &s_in, double lo = 0.0, double hi = 1.0);\n\nvoid PseudoInverse(Eigen::MatrixXd const &matrix, double sigmaThreshold,\n                   Eigen::MatrixXd &invMatrix,\n                   Eigen::VectorXd *opt_sigmaOut = 0);\n\nEigen::MatrixXd PseudoInverse(const Eigen::MatrixXd &matrix,\n                              const double &threshold);\n\nEigen::MatrixXd NullSpace(const Eigen::MatrixXd &J,\n                          const double threshold = 0.00001);\n\nEigen::MatrixXd WeightedPseudoInverse(const Eigen::MatrixXd &J,\n                                      const Eigen::MatrixXd &W,\n                                      const double sigma_threshold = 0.0001);\n} // namespace util\n", "meta": {"hexsha": "0dcca575ae28ddb38dd78d47fc5eee429f14fb06", "size": 4116, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/util.hpp", "max_stars_repo_name": "junhyeokahn/PnC", "max_stars_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-01-31T13:51:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T13:19:01.000Z", "max_issues_repo_path": "utils/util.hpp", "max_issues_repo_name": "junhyeokahn/PnC", "max_issues_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T20:48:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T11:42:02.000Z", "max_forks_repo_path": "utils/util.hpp", "max_forks_repo_name": "junhyeokahn/PnC", "max_forks_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T22:37:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T17:17:27.000Z", "avg_line_length": 35.4827586207, "max_line_length": 80, "alphanum_fraction": 0.666180758, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.028436030883528987, "lm_q1q2_score": 0.011050754612006417}}
{"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @file math.hpp\n * @author Vaclav Blazek <vaclav.blazek@citationtech.net>\n *\n * 3D mesh representation and operations.\n */\n\n#ifndef geometry_mesh_hpp_included_\n#define geometry_mesh_hpp_included_\n\n#include <memory>\n#include <vector>\n#include <string>\n\n#include <boost/noncopyable.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/filesystem.hpp>\n\n#include \"math/geometry.hpp\"\n#include \"geometry/parse-obj.hpp\"\n\nnamespace geometry {\n\n/** Face in a mesh.\n */\nstruct Face {\n    typedef std::vector<Face> list;\n    typedef unsigned int index_type;\n\n    unsigned int imageId;\n\n    // Indices of vertices.\n    index_type a, b, c;\n    // Indices of texture coordinates.\n    index_type ta, tb, tc;\n\n    Face() : imageId(), a(), b(), c(), ta(), tb(), tc() {}\n\n    Face(index_type a, index_type b, index_type c, unsigned int imageId = 0)\n        : imageId(imageId), a(a), b(b), c(c), ta(), tb(), tc()\n    {}\n\n    Face(index_type a, index_type b, index_type c\n         , index_type ta, index_type tb, index_type tc\n         , unsigned int imageId = 0)\n        : imageId(imageId), a(a), b(b), c(c), ta(ta), tb(tb), tc(tc)\n    {}\n\n    index_type vertex(const int idx) const {\n        const index_type abc[] = { a, b, c };\n        return abc[idx];\n    }\n\n    /** Calculate normal of this face.\n     */\n    math::Point3 normal(const math::Points3 &vertices) const {\n        return math::normalize\n            (math::crossProduct(vertices[b] - vertices[a]\n                                , vertices[c] - vertices[b]));\n    }\n\n    void clear() {\n        a = b = c = 0;\n        ta = tb = tc = 0;\n    }\n\n    /** Is this face not a triangle?\n     */\n    bool degenerate() const {\n        return ((a == b) || (b == c) || (c == a));\n    }\n\n    // needed by python bindings\n    bool operator==(const Face &f) const;\n    bool operator<(const Face &f) const;\n};\n\n/** Textured 3D mesh representation.\n *\n * Vertices and texture coordinates are held in two arrays. Vertex at index I\n * has vertex coordinates at vertices[I] and texture coordinates at tCoords[I].\n *\n * Faces are defined as 3 indices to vertices and 3 indices to tCoords.\n */\nstruct Mesh {\n    typedef std::shared_ptr<Mesh> pointer;\n    typedef std::vector<Mesh> list;\n\n    /** vertices */\n    std::vector <int> vertecesClass;\n    math::Points3 vertices;\n\n    /** per-vertex texture coordinates */\n    math::Points2 tCoords;\n\n    /** Faces (triplets of indices to vertices and texture coordinates) */\n    Face::list faces;\n\n    /** Face normal. */\n    math::Point3 normal(const Face &face) const {\n        return face.normal(vertices);\n    }\n\n    /** Add new face.\n     */\n    void addFace(math::Points3::size_type a, math::Points3::size_type b\n                 , math::Points3::size_type c);\n\n    void addFace(math::Points3::size_type a, math::Points3::size_type b\n                 , math::Points3::size_type c, unsigned int imageId);\n\n    void addFace(math::Points3::size_type a, math::Points3::size_type b\n                 , math::Points3::size_type c, math::Points2::size_type ta\n                 , math::Points2::size_type tb, math::Points2::size_type tc );\n\n    void addFace(math::Points3::size_type a, math::Points3::size_type b\n                 , math::Points3::size_type c, math::Points2::size_type ta\n                 , math::Points2::size_type tb, math::Points2::size_type tc\n                 , unsigned int imageId);\n\n    /** First face point.\n    */\n    const math::Point3& a(const Face &face) const {\n        return vertices[face.a];\n    }\n\n    /** Second face point.\n     */\n    const math::Point3& b(const Face &face) const {\n        return vertices[face.b];\n    }\n\n    /** Third face point.\n     */\n    const math::Point3& c(const Face &face) const {\n        return vertices[face.c];\n    }\n\n    /** First face texture point.\n    */\n    const math::Point2& ta(const Face &face) const {\n        return tCoords[face.ta];\n    }\n\n    /** Second face texture point.\n     */\n    const math::Point2& tb(const Face &face) const {\n        return tCoords[face.tb];\n    }\n\n    /** Third face texture point.\n     */\n    const math::Point2& tc(const Face &face) const {\n        return tCoords[face.tc];\n    }\n\n    /** Is given face not a triangle?\n     */\n    bool degenerate(const Face &face) const {\n        return (face.degenerate() || (a(face) == b(face))\n                || (b(face) == c(face)) || (c(face) == a(face)));\n    }\n\n    /** Are face indices ok?\n     */\n    bool good(const Face &face) const {\n        return face.a < vertices.size() &&\n               face.b < vertices.size() &&\n               face.c < vertices.size();\n    }\n\n    /**\n     * @brief provide mesh with skirt\n     * @details skirt is a set quads pointing in the direction of the given\n     * vector and attached to odd edges (edges adjacent to a single face).\n     */\n    void skirt( const math::Point3 & down = math::Point3( 0.0, 0.0, -1.0 ) );\n\n    void sortFacesByImageId();\n\n    /** Iterator that iterates over face points (a->b->c->end)\n     */\n    struct FaceVertexConstIterator;\n    struct FaceVertexConstIteratorRange;\n\n    FaceVertexConstIterator begin(const Face &face) const;\n\n    FaceVertexConstIterator end(const Face&) const;\n\n    FaceVertexConstIteratorRange face(const Face &face) const;\n\n    /** Calculate face area (in 3D space).\n     */\n    double area(const Face &face) const;\n\n    /** Calculate face area (in UV space).;\n     */\n    double txArea(const Face &face) const;\n\n    /** Calculate face barycenter.\n     */\n    math::Point3 barycenter(const Face &face) const;\n};\n\n// inlines\n\ninline void Mesh::addFace(math::Points3::size_type a\n                          , math::Points3::size_type b\n                          , math::Points3::size_type c\n                          , unsigned int imageId)\n{\n    faces.emplace_back(a, b, c, imageId);\n}\n\ninline void Mesh::addFace(math::Points3::size_type a\n                          , math::Points3::size_type b\n                          , math::Points3::size_type c)\n{\n    faces.emplace_back(a, b, c);\n}\n\ninline void\nMesh::addFace(math::Points3::size_type a, math::Points3::size_type b\n              , math::Points3::size_type c, math::Points2::size_type ta\n              , math::Points2::size_type tb, math::Points2::size_type tc)\n{\n    faces.emplace_back(a, b, c, ta, tb, tc);\n}\n\ninline void\nMesh::addFace(math::Points3::size_type a, math::Points3::size_type b\n              , math::Points3::size_type c, math::Points2::size_type ta\n              , math::Points2::size_type tb, math::Points2::size_type tc\n              , unsigned int imageId)\n{\n    faces.emplace_back(a, b, c, ta, tb, tc, imageId);\n}\n\n\ninline void Mesh::sortFacesByImageId()\n{\n    std::sort(faces.begin(), faces.end()\n              , [](const Face &l, const Face &r) {\n                  return l.imageId < r.imageId;\n              });\n}\n\nstruct Mesh::FaceVertexConstIterator {\n    FaceVertexConstIterator() : face_(), vertices_(), index_() {}\n\n    FaceVertexConstIterator(const Mesh &mesh, const Face &face)\n        : face_(&face), vertices_(&mesh.vertices), index_()\n    {}\n\n    const math::Point3& operator*() const {\n        switch (index_) {\n        case 0: return (*vertices_)[face_->a];\n        case 1: return (*vertices_)[face_->b];\n        default: return (*vertices_)[face_->c];\n        }\n    }\n\n    const math::Point3* operator->() const {\n        switch (index_) {\n        case 0: return &(*vertices_)[face_->a];\n        case 1: return &(*vertices_)[face_->b];\n        default: return &(*vertices_)[face_->c];\n        }\n    }\n\n    FaceVertexConstIterator operator++() {\n        ++index_;\n        return *this;\n    }\n\n    bool operator==(const FaceVertexConstIterator &o) {\n        if (((index_ > 2) || !face_) && !o.face_) {\n            return true;\n        }\n\n        if (!face_ && ((o.index_ > 2) || !o.face_)) {\n            return true;\n        }\n\n        return ((index_ == o.index_) && (face_ == o.face_)\n                && (vertices_ == o.vertices_));\n    }\n\n    bool operator!=(const FaceVertexConstIterator &o) {\n        return !operator==(o);\n    }\n\nprivate:\n    const Face *face_;\n    const math::Points3 *vertices_;\n    unsigned int index_;\n};\n\ninline Mesh::FaceVertexConstIterator Mesh::begin(const Face &face) const {\n    return FaceVertexConstIterator(*this, face);\n}\n\ninline Mesh::FaceVertexConstIterator Mesh::end(const Face&) const {\n    return FaceVertexConstIterator();\n}\n\nclass Mesh::FaceVertexConstIteratorRange {\npublic:\n    FaceVertexConstIteratorRange(const Mesh &mesh, const Face &face)\n        : begin_(mesh, face), end_()\n    {}\n\n    const FaceVertexConstIterator& begin() const { return begin_; }\n    const FaceVertexConstIterator& end() const { return end_; }\n\nprivate:\n    FaceVertexConstIterator begin_;\n    FaceVertexConstIterator end_;\n};\n\ninline Mesh::FaceVertexConstIteratorRange Mesh::face(const Face &face) const\n{\n    return { *this, face };\n}\n\n// inlines\n\ninline bool Face::operator==(const Face &f) const {\n    return\n        (a == f.a) && (b == f.b) && (c == f.c)\n        && (ta == f.ta) && (tb == f.tb) && (tc == f.tc)\n        && (imageId == f.imageId)\n        ;\n}\n\ninline bool Face::operator<(const Face &f) const\n{\n    if (a < f.a) { return true; }\n    if (f.a < a) { return false; }\n    if (b < f.b) { return true; }\n    if (f.b < b) { return false; }\n    if (c < f.c) { return true; }\n    if (f.c < c) { return false; }\n\n    if (ta < f.ta) { return true; }\n    if (f.ta < ta) { return false; }\n    if (tb < f.tb) { return true; }\n    if (f.tb < tb) { return false; }\n    if (tc < f.tc) { return true; }\n    if (f.tc < tc) { return false; }\n\n    return imageId < f.imageId;\n}\n\n} // namespace geometry\n\n#endif // geometry_mesh_hpp_included_\n", "meta": {"hexsha": "1537fc748459c67054eaad49eeb2c68aa76be6c1", "size": 11023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/browser/externals/browser/externals/libgeometry/geometry/mesh.hpp", "max_stars_repo_name": "HanochZhu/vts-browser-unity-plugin", "max_stars_repo_head_hexsha": "32a22d41e21b95fb015326f95e401d87756d0374", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T08:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T08:42:59.000Z", "max_issues_repo_path": "externals/browser/externals/browser/externals/libgeometry/geometry/mesh.hpp", "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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/browser/externals/browser/externals/libgeometry/geometry/mesh.hpp", "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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7806788512, "max_line_length": 79, "alphanum_fraction": 0.6079107321, "num_tokens": 2791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.02843603036892814, "lm_q1q2_score": 0.011050754009320447}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\n//Copyright (c) 2019 agate-pris\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_384AFF3AD23A11DFA80B754FE0D72085\n#define BOOST_QVM_384AFF3AD23A11DFA80B754FE0D72085\n\n#include <boost/qvm/detail/vec_assign.hpp>\n#include <boost/qvm/vec_operations2.hpp>\n#include <boost/qvm/vec_operations3.hpp>\n#include <boost/qvm/vec_operations4.hpp>\n#include <boost/qvm/assert.hpp>\n#include <boost/qvm/scalar_traits.hpp>\n#include <string>\n\nnamespace\nboost\n    {\n    namespace\n    qvm\n        {\n        namespace\n        qvm_detail\n            {\n            BOOST_QVM_INLINE_CRITICAL\n            void const *\n            get_valid_ptr_vec_operations()\n                {\n                static int const obj=0;\n                return &obj;\n                }\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_to_string_detail\n            {\n            template <class T>\n            std::string to_string( T const & x );\n            }\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            to_string_v_defined\n                {\n                static bool const value=false;\n                };\n\n            template <int I,int DimMinusOne>\n            struct\n            to_string_vector_elements\n                {\n                template <class A>\n                static\n                std::string\n                f( A const & a )\n                    {\n                    using namespace qvm_to_string_detail;\n                    return to_string(vec_traits<A>::template read_element<I>(a))+','+to_string_vector_elements<I+1,DimMinusOne>::f(a);\n                    }\n                };\n\n            template <int DimMinusOne>\n            struct\n            to_string_vector_elements<DimMinusOne,DimMinusOne>\n                {\n                template <class A>\n                static\n                std::string\n                f( A const & a )\n                    {\n                    using namespace qvm_to_string_detail;\n                    return to_string(vec_traits<A>::template read_element<DimMinusOne>(a));\n                    }\n                };\n            }\n\n        template <class A>\n        inline\n        typename boost::enable_if_c<\n            is_vec<A>::value  &&\n            !qvm_detail::to_string_v_defined<vec_traits<A>::dim>::value,\n            std::string>::type\n        to_string( A const & a )\n            {\n            return '('+qvm_detail::to_string_vector_elements<0,vec_traits<A>::dim-1>::f(a)+')';\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            convert_to_v_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class R,class A>\n        BOOST_QVM_INLINE_TRIVIAL\n        typename enable_if_c<\n            is_vec<R>::value && is_vec<A>::value &&\n            vec_traits<R>::dim==vec_traits<A>::dim &&\n            !qvm_detail::convert_to_v_defined<vec_traits<R>::dim>::value,\n            R>::type\n        convert_to( A const & a )\n            {\n            R r; assign(r,a);\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==3 && vec_traits<B>::dim==3,\n            deduce_vec2<A,B,3> >::type\n        cross( A const & a, B const & b )\n            {\n            typedef typename deduce_vec2<A,B,3>::type R;\n            R r;\n            vec_traits<R>::template write_element<0>(r)=\n                vec_traits<A>::template read_element<1>(a)*vec_traits<B>::template read_element<2>(b)-\n                vec_traits<A>::template read_element<2>(a)*vec_traits<B>::template read_element<1>(b);\n            vec_traits<R>::template write_element<1>(r)=\n                vec_traits<A>::template read_element<2>(a)*vec_traits<B>::template read_element<0>(b)-\n                vec_traits<A>::template read_element<0>(a)*vec_traits<B>::template read_element<2>(b);\n            vec_traits<R>::template write_element<2>(r)=\n                vec_traits<A>::template read_element<0>(a)*vec_traits<B>::template read_element<1>(b)-\n                vec_traits<A>::template read_element<1>(a)*vec_traits<B>::template read_element<0>(b);\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        template <class A,class B,class Cmp>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim,\n            bool>::type\n        cmp( A const & a, B const & b, Cmp f )\n            {\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                if( !f(\n                    vec_traits<A>::read_element_idx(i,a),\n                    vec_traits<B>::read_element_idx(i,b)) )\n                    return false;\n            return true;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <class T,int Dim>\n            class\n            zero_vec_\n                {\n                zero_vec_( zero_vec_ const & );\n                zero_vec_ & operator=( zero_vec_ const & );\n                ~zero_vec_();\n\n                public:\n\n                template <class R>\n                BOOST_QVM_INLINE_TRIVIAL\n                operator R() const\n                    {\n                    R r;\n                    assign(r,*this);\n                    return r;\n                    }\n                };\n            }\n\n        template <class V>\n        struct vec_traits;\n\n        template <class T,int Dim>\n        struct\n        vec_traits< qvm_detail::zero_vec_<T,Dim> >\n            {\n            typedef qvm_detail::zero_vec_<T,Dim> this_vector;\n            typedef T scalar_type;\n            static int const dim=Dim;\n\n            template <int I>\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type\n            read_element( this_vector const & )\n                {\n                BOOST_QVM_STATIC_ASSERT(I>=0);\n                BOOST_QVM_STATIC_ASSERT(I<Dim);\n                return scalar_traits<scalar_type>::value(0);\n                }\n\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type\n            read_element_idx( int i, this_vector const & )\n                {\n                BOOST_QVM_ASSERT(i>=0);\n                BOOST_QVM_ASSERT(i<Dim);\n                return scalar_traits<scalar_type>::value(0);\n                }\n            };\n\n        template <class T,int Dim,int D>\n        struct\n        deduce_vec<qvm_detail::zero_vec_<T,Dim>,D>\n            {\n            typedef vec<T,D> type;\n            };\n\n        template <class T,int Dim>\n        BOOST_QVM_INLINE_TRIVIAL\n        qvm_detail::zero_vec_<T,Dim> const &\n        zero_vec()\n            {\n            return *(qvm_detail::zero_vec_<T,Dim> const *)qvm_detail::get_valid_ptr_vec_operations();\n            }\n\n        template <class A>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value,\n            void>::type\n        set_zero( A & a )\n            {\n            assign(a,zero_vec<typename vec_traits<A>::scalar_type,vec_traits<A>::dim>());\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <class OriginalType,class Scalar>\n            class\n            vector_scalar_cast_\n                {\n                vector_scalar_cast_( vector_scalar_cast_ const & );\n                vector_scalar_cast_ & operator=( vector_scalar_cast_ const & );\n                ~vector_scalar_cast_();\n\n                public:\n\n                template <class T>\n                BOOST_QVM_INLINE_TRIVIAL\n                vector_scalar_cast_ &\n                operator=( T const & x )\n                    {\n                    assign(*this,x);\n                    return *this;\n                    }\n\n                template <class R>\n                BOOST_QVM_INLINE_TRIVIAL\n                operator R() const\n                    {\n                    R r;\n                    assign(r,*this);\n                    return r;\n                    }\n                };\n\n            template <bool> struct scalar_cast_vector_filter { };\n            template <> struct scalar_cast_vector_filter<true> { typedef int type; };\n            }\n\n        template <class OriginalType,class Scalar>\n        struct\n        vec_traits< qvm_detail::vector_scalar_cast_<OriginalType,Scalar> >\n            {\n            typedef Scalar scalar_type;\n            typedef qvm_detail::vector_scalar_cast_<OriginalType,Scalar> this_vector;\n            static int const dim=vec_traits<OriginalType>::dim;\n\n            template <int I>\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type\n            read_element( this_vector const & x )\n                {\n                BOOST_QVM_STATIC_ASSERT(I>=0);\n                BOOST_QVM_STATIC_ASSERT(I<dim);\n                return scalar_type(vec_traits<OriginalType>::template read_element<I>(reinterpret_cast<OriginalType const &>(x)));\n                }\n\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type\n            read_element_idx( int i, this_vector const & x )\n                {\n                BOOST_QVM_ASSERT(i>=0);\n                BOOST_QVM_ASSERT(i<dim);\n                return scalar_type(vec_traits<OriginalType>::read_element_idx(i,reinterpret_cast<OriginalType const &>(x)));\n                }\n            };\n\n        template <class OriginalType,class Scalar,int D>\n        struct\n        deduce_vec<qvm_detail::vector_scalar_cast_<OriginalType,Scalar>,D>\n            {\n            typedef vec<Scalar,D> type;\n            };\n\n        template <class Scalar,class T>\n        BOOST_QVM_INLINE_TRIVIAL\n        qvm_detail::vector_scalar_cast_<T,Scalar> const &\n        scalar_cast( T const & x, typename qvm_detail::scalar_cast_vector_filter<is_vec<T>::value>::type=0 )\n            {\n            return reinterpret_cast<qvm_detail::vector_scalar_cast_<T,Scalar> const &>(x);\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            div_eq_vs_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value && is_scalar<B>::value &&\n            !qvm_detail::div_eq_vs_defined<vec_traits<A>::dim>::value,\n            A &>::type\n        operator/=( A & a, B b )\n            {\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<A>::write_element_idx(i,a)/=b;\n            return a;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            div_vs_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value && is_scalar<B>::value &&\n            !qvm_detail::div_vs_defined<vec_traits<A>::dim>::value,\n            deduce_vec<A> >::type\n        operator/( A const & a, B b )\n            {\n            typedef typename deduce_vec<A>::type R;\n            R r;\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<R>::write_element_idx(i,r)=vec_traits<A>::read_element_idx(i,a)/b;\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            dot_vv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim &&\n            !qvm_detail::dot_vv_defined<vec_traits<A>::dim>::value,\n            deduce_scalar<typename vec_traits<A>::scalar_type,typename vec_traits<B>::scalar_type> >::type\n        dot( A const & a, B const & b )\n            {\n            typedef typename deduce_scalar<typename vec_traits<A>::scalar_type,typename vec_traits<B>::scalar_type>::type T;\n            T m(scalar_traits<T>::value(0));\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                m+=vec_traits<A>::read_element_idx(i,a)*vec_traits<B>::read_element_idx(i,b);\n            return m;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            eq_vv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim &&\n            !qvm_detail::eq_vv_defined<vec_traits<A>::dim>::value,\n            bool>::type\n        operator==( A const & a, B const & b )\n            {\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                if( vec_traits<A>::read_element_idx(i,a)!=vec_traits<B>::read_element_idx(i,b) )\n                    return false;\n            return true;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            mag_sqr_v_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value &&\n            !qvm_detail::mag_sqr_v_defined<vec_traits<A>::dim>::value,\n            typename vec_traits<A>::scalar_type>::type\n        mag_sqr( A const & a )\n            {\n            typedef typename vec_traits<A>::scalar_type T;\n            T m(scalar_traits<T>::value(0));\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                {\n                T x=vec_traits<A>::read_element_idx(i,a);\n                m+=x*x;\n                }\n            return m;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            mag_v_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value &&\n            !qvm_detail::mag_v_defined<vec_traits<A>::dim>::value,\n            typename vec_traits<A>::scalar_type>::type\n        mag( A const & a )\n            {\n            typedef typename vec_traits<A>::scalar_type T;\n            T m(scalar_traits<T>::value(0));\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                {\n                T x=vec_traits<A>::read_element_idx(i,a);\n                m+=x*x;\n                }\n            return sqrt<T>(m);\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            minus_eq_vv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim &&\n            !qvm_detail::minus_eq_vv_defined<vec_traits<A>::dim>::value,\n            A &>::type\n        operator-=( A & a, B const & b )\n            {\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<A>::write_element_idx(i,a)-=vec_traits<B>::read_element_idx(i,b);\n            return a;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            minus_v_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value &&\n            !qvm_detail::minus_v_defined<vec_traits<A>::dim>::value,\n            deduce_vec<A> >::type\n        operator-( A const & a )\n            {\n            typedef typename deduce_vec<A>::type R;\n            R r;\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<R>::write_element_idx(i,r)=-vec_traits<A>::read_element_idx(i,a);\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            minus_vv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim &&\n            !qvm_detail::minus_vv_defined<vec_traits<A>::dim>::value,\n            deduce_vec2<A,B,vec_traits<A>::dim> >::type\n        operator-( A const & a, B const & b )\n            {\n            typedef typename deduce_vec2<A,B,vec_traits<A>::dim>::type R;\n            R r;\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<R>::write_element_idx(i,r)=vec_traits<A>::read_element_idx(i,a)-vec_traits<B>::read_element_idx(i,b);\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            mul_eq_vs_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value && is_scalar<B>::value &&\n            !qvm_detail::mul_eq_vs_defined<vec_traits<A>::dim>::value,\n            A &>::type\n        operator*=( A & a, B b )\n            {\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<A>::write_element_idx(i,a)*=b;\n            return a;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            mul_vs_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value && is_scalar<B>::value &&\n            !qvm_detail::mul_vs_defined<vec_traits<A>::dim>::value,\n            deduce_vec<A> >::type\n        operator*( A const & a, B b )\n            {\n            typedef typename deduce_vec<A>::type R;\n            R r;\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<R>::write_element_idx(i,r)=vec_traits<A>::read_element_idx(i,a)*b;\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            mul_sv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_scalar<A>::value && is_vec<B>::value &&\n            !qvm_detail::mul_sv_defined<vec_traits<B>::dim>::value,\n            deduce_vec<B> >::type\n        operator*( A a, B const & b )\n            {\n            typedef typename deduce_vec<B>::type R;\n            R r;\n            for( int i=0; i!=vec_traits<B>::dim; ++i )\n                vec_traits<R>::write_element_idx(i,r)=a*vec_traits<B>::read_element_idx(i,b);\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            neq_vv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim &&\n            !qvm_detail::neq_vv_defined<vec_traits<A>::dim>::value,\n            bool>::type\n        operator!=( A const & a, B const & b )\n            {\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                if( vec_traits<A>::read_element_idx(i,a)!=vec_traits<B>::read_element_idx(i,b) )\n                    return true;\n            return false;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            normalize_v_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value &&\n            !qvm_detail::normalize_v_defined<vec_traits<A>::dim>::value,\n            deduce_vec<A> >::type\n        normalized( A const & a )\n            {\n            typedef typename vec_traits<A>::scalar_type T;\n            T m(scalar_traits<T>::value(0));\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                {\n                T x=vec_traits<A>::read_element_idx(i,a);\n                m+=x*x;\n                }\n            if( m==scalar_traits<T>::value(0) )\n                BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n            T rm=scalar_traits<T>::value(1)/sqrt<T>(m);\n            typedef typename deduce_vec<A>::type R;\n            R r;\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<R>::write_element_idx(i,r)=vec_traits<A>::read_element_idx(i,a)*rm;\n            return r;\n            }\n\n        template <class A>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value &&\n            !qvm_detail::normalize_v_defined<vec_traits<A>::dim>::value,\n            void>::type\n        normalize( A & a )\n            {\n            typedef typename vec_traits<A>::scalar_type T;\n            T m(scalar_traits<T>::value(0));\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                {\n                T x=vec_traits<A>::read_element_idx(i,a);\n                m+=x*x;\n                }\n            if( m==scalar_traits<T>::value(0) )\n                BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n            T rm=scalar_traits<T>::value(1)/sqrt<T>(m);\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<A>::write_element_idx(i,a)*=rm;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            plus_eq_vv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim &&\n            !qvm_detail::plus_eq_vv_defined<vec_traits<A>::dim>::value,\n            A &>::type\n        operator+=( A & a, B const & b )\n            {\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<A>::write_element_idx(i,a)+=vec_traits<B>::read_element_idx(i,b);\n            return a;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <int D>\n            struct\n            plus_vv_defined\n                {\n                static bool const value=false;\n                };\n            }\n\n        template <class A,class B>\n        BOOST_QVM_INLINE_OPERATIONS\n        typename lazy_enable_if_c<\n            is_vec<A>::value && is_vec<B>::value &&\n            vec_traits<A>::dim==vec_traits<B>::dim &&\n            !qvm_detail::plus_vv_defined<vec_traits<A>::dim>::value,\n            deduce_vec2<A,B,vec_traits<A>::dim> >::type\n        operator+( A const & a, B const & b )\n            {\n            typedef typename deduce_vec2<A,B,vec_traits<A>::dim>::type R;\n            R r;\n            for( int i=0; i!=vec_traits<A>::dim; ++i )\n                vec_traits<R>::write_element_idx(i,r)=vec_traits<A>::read_element_idx(i,a)+vec_traits<B>::read_element_idx(i,b);\n            return r;\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        qvm_detail\n            {\n            template <class T>\n            class\n            vref_\n                {\n                vref_( vref_ const & );\n                vref_ & operator=( vref_ const & );\n                ~vref_();\n\n                public:\n\n                template <class R>\n                BOOST_QVM_INLINE_TRIVIAL\n                vref_ &\n                operator=( R const & x )\n                    {\n                    assign(*this,x);\n                    return *this;\n                    }\n\n                template <class R>\n                BOOST_QVM_INLINE_TRIVIAL\n                operator R() const\n                    {\n                    R r;\n                    assign(r,*this);\n                    return r;\n                    }\n                };\n            }\n\n        template <class V>\n        struct\n        vec_traits< qvm_detail::vref_<V> >\n            {\n            typedef typename vec_traits<V>::scalar_type scalar_type;\n            typedef qvm_detail::vref_<V> this_vector;\n            static int const dim=vec_traits<V>::dim;\n\n            template <int I>\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type\n            read_element( this_vector const & x )\n                {\n                BOOST_QVM_STATIC_ASSERT(I>=0);\n                BOOST_QVM_STATIC_ASSERT(I<dim);\n                return vec_traits<V>::template read_element<I>(reinterpret_cast<V const &>(x));\n                }\n\n            template <int I>\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type &\n            write_element( this_vector & x )\n                {\n                BOOST_QVM_STATIC_ASSERT(I>=0);\n                BOOST_QVM_STATIC_ASSERT(I<dim);\n                return vec_traits<V>::template write_element<I>(reinterpret_cast<V &>(x));\n                }\n\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type\n            read_element_idx( int i, this_vector const & x )\n                {\n                BOOST_QVM_ASSERT(i>=0);\n                BOOST_QVM_ASSERT(i<dim);\n                return vec_traits<V>::read_element_idx(i,reinterpret_cast<V const &>(x));\n                }\n\n            static\n            BOOST_QVM_INLINE_CRITICAL\n            scalar_type &\n            write_element_idx( int i, this_vector & x )\n                {\n                BOOST_QVM_ASSERT(i>=0);\n                BOOST_QVM_ASSERT(i<dim);\n                return vec_traits<V>::write_element_idx(i,reinterpret_cast<V &>(x));\n                }\n            };\n\n        template <class V,int D>\n        struct\n        deduce_vec<qvm_detail::vref_<V>,D>\n            {\n            typedef vec<typename vec_traits<V>::scalar_type,D> type;\n            };\n\n        template <class V>\n        BOOST_QVM_INLINE_TRIVIAL\n        typename enable_if_c<\n            is_vec<V>::value,\n            qvm_detail::vref_<V> const &>::type\n        vref( V const & a )\n            {\n            return reinterpret_cast<qvm_detail::vref_<V> const &>(a);\n            }\n\n        template <class V>\n        BOOST_QVM_INLINE_TRIVIAL\n        typename enable_if_c<\n            is_vec<V>::value,\n            qvm_detail::vref_<V> &>::type\n        vref( V & a )\n            {\n            return reinterpret_cast<qvm_detail::vref_<V> &>(a);\n            }\n\n        ////////////////////////////////////////////////\n\n        namespace\n        sfinae\n            {\n            using ::boost::qvm::to_string;\n            using ::boost::qvm::assign;\n            using ::boost::qvm::convert_to;\n            using ::boost::qvm::cross;\n            using ::boost::qvm::cmp;\n            using ::boost::qvm::set_zero;\n            using ::boost::qvm::scalar_cast;\n            using ::boost::qvm::operator/=;\n            using ::boost::qvm::operator/;\n            using ::boost::qvm::dot;\n            using ::boost::qvm::operator==;\n            using ::boost::qvm::mag_sqr;\n            using ::boost::qvm::mag;\n            using ::boost::qvm::operator-=;\n            using ::boost::qvm::operator-;\n            using ::boost::qvm::operator*=;\n            using ::boost::qvm::operator*;\n            using ::boost::qvm::operator!=;\n            using ::boost::qvm::normalized;\n            using ::boost::qvm::normalize;\n            using ::boost::qvm::operator+=;\n            using ::boost::qvm::operator+;\n            using ::boost::qvm::vref;\n            }\n\n        ////////////////////////////////////////////////\n        }\n    }\n\n#endif\n", "meta": {"hexsha": "0ed71a303f2427b24f989370a19a7cea8ec71565", "size": 30368, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/qvm/vec_operations.hpp", "max_stars_repo_name": "mamil/demo", "max_stars_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/boost/qvm/vec_operations.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/boost/qvm/vec_operations.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T04:03:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T18:53:47.000Z", "avg_line_length": 31.6004162331, "max_line_length": 134, "alphanum_fraction": 0.4575210748, "num_tokens": 6405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.024798158934332924, "lm_q1q2_score": 0.011048311854714938}}
{"text": "#include \"conex.h\"\n\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"conex/cone_program.h\"\n#include \"conex/constraint.h\"\n#include \"conex/dense_lmi_constraint.h\"\n#include \"conex/equality_constraint.h\"\n#include \"conex/hermitian_psd.h\"\n#include \"conex/linear_constraint.h\"\n#include \"conex/soc_constraint.h\"\n\n#include \"conex/error_checking_macros.h\"\n\n// TODO(FrankPermenter): check for null pointers.\n#define SAFER_CAST_TO_Program(x, prog)                                     \\\n  CONEX_DEMAND(x, \"Program pointer is null.\");                             \\\n  prog = static_cast<Program*>(x);                                         \\\n  if (prog->is_initialized) {                                              \\\n    if (prog->NumberOfConstraints() + 2 !=                                 \\\n        static_cast<int>(prog->workspaces.size())) {                       \\\n      CONEX_DEMAND(false, \"Program corrupted or invalid pointer.\");        \\\n    }                                                                      \\\n  } else {                                                                 \\\n    if (prog->workspaces.size() != 0 || prog->NumberOfConstraints() < 0) { \\\n      CONEX_DEMAND(false, \"Program corrupted or invalid pointer.\");        \\\n    }                                                                      \\\n  }                                                                        \\\n  CONEX_DEMAND(prog, \"Program corrupted or invalid pointer.\");\n\nusing DenseMatrix = Eigen::MatrixXd;\nusing conex::DenseLMIConstraint;\nusing conex::HermitianPsdConstraint;\nusing conex::LinearConstraint;\nusing conex::Program;\nusing conex::SolverConfiguration;\n\nnamespace {\n\nvoid NonZeroSubMat(const Eigen::MatrixXd& M, std::vector<int>* vars,\n                   Eigen::MatrixXd* Y) {\n  vars->clear();\n  for (int i = 0; i < M.rows(); i++) {\n    if (M(i, i) > 0) {\n      vars->push_back(i);\n    }\n  }\n\n  int row = 0;\n  Y->resize(vars->size(), vars->size());\n  for (auto& i : *vars) {\n    int col = 0;\n    for (auto& j : *vars) {\n      (*Y)(row, col) = (M(i, j) + M(j, i)) / 2.0;\n      (*Y)(col, row) = (*Y)(row, col);\n      col++;\n    }\n    row++;\n  }\n}\nSolverConfiguration APIConvertSolverConfiguration(\n    const CONEX_SolverConfiguration* config) {\n  SolverConfiguration c;\n  c.prepare_dual_variables = config->prepare_dual_variables;\n  c.initialization_mode = config->initialization_mode;\n  c.inv_sqrt_mu_max = config->inv_sqrt_mu_max;\n  c.minimum_mu = config->minimum_mu;\n  c.maximum_mu = config->maximum_mu;\n  c.divergence_upper_bound = config->divergence_upper_bound;\n  c.enable_line_search = config->enable_line_search;\n  c.dinf_upper_bound = config->dinf_upper_bound;\n  c.final_centering_steps = config->final_centering_steps;\n  c.final_centering_tolerance = config->final_centering_tolerance;\n  c.initial_centering_steps_warmstart =\n      config->initial_centering_steps_warmstart;\n  c.initial_centering_steps_coldstart =\n      config->initial_centering_steps_coldstart;\n  c.warmstart_abort_threshold = config->warmstart_abort_threshold;\n  c.max_iterations = config->max_iterations;\n  c.iterative_refinement_iterations = config->iterative_refinement_iterations;\n  c.infeasibility_threshold = config->infeasibility_threshold;\n  c.kkt_error_tolerance = config->kkt_error_tolerance;\n  c.enable_rescaling = config->enable_rescaling;\n  c.kkt_solver = config->kkt_solver;\n  return c;\n}\n}  // namespace\n\nint CONEX_Maximize(void* prog_ptr, const double* b, int br,\n                   const CONEX_SolverConfiguration* config_input, double* y,\n                   int yr) {\n  using InputMatrix = Eigen::Map<const DenseMatrix>;\n  InputMatrix bmap(b, br, 1);\n  DenseMatrix blinear = bmap;\n\n  SolverConfiguration config = APIConvertSolverConfiguration(config_input);\n\n  Program& prog = *reinterpret_cast<Program*>(prog_ptr);\n\n  return Solve(blinear, prog, config, y);\n}\n\nint CONEX_Solve(void* prog_ptr, const CONEX_SolverConfiguration* config_input,\n                double* y, int yr) {\n  SolverConfiguration config = APIConvertSolverConfiguration(config_input);\n  Program& prog = *reinterpret_cast<Program*>(prog_ptr);\n  return Solve(prog, config, y);\n}\n\nvoid CONEX_GetDualVariable(void* prog_ptr, int i, double* x, int xr, int xc) {\n  Program& prog = *reinterpret_cast<Program*>(prog_ptr);\n  assert(prog.GetDualVariableSize(i) == xr * xc);\n\n  using InputMatrix = Eigen::Map<DenseMatrix>;\n\n  InputMatrix xmap(x, xr, xc);\n  prog.GetDualVariable(i, &xmap);\n}\n\nint CONEX_GetDualVariableSize(void* prog_ptr, int i) {\n  Program& prog = *reinterpret_cast<Program*>(prog_ptr);\n  return prog.GetDualVariableSize(i);\n}\n\nvoid* CONEX_CreateConeProgram() {\n  return reinterpret_cast<void*>(new Program(0));\n}\n\nvoid CONEX_DeleteConeProgram(void* prog) {\n  delete reinterpret_cast<Program*>(prog);\n}\n\nint CONEX_AddDenseLMIConstraint(void* prog, const double* A, int Ar, int Ac,\n                                int m, const double* c, int cr, int cc) {\n  assert(Ar == Ac);\n  assert(Ar == cr);\n  assert(cc == cr);\n\n  using InputMatrix = Eigen::Map<const DenseMatrix>;\n  auto offset = A;\n  std::vector<DenseMatrix> Avect;\n  for (int i = 0; i < m; i++) {\n    InputMatrix Amap(offset, Ar, Ac);\n    Avect.push_back(Amap);\n    offset += Ar * Ac;\n  }\n  InputMatrix Cmap(c, cr, cc);\n\n  int n = cc;\n\n  DenseLMIConstraint T3{n, Avect, Cmap};\n  auto& program = *reinterpret_cast<Program*>(prog);\n  int constraint_id = program.NumberOfConstraints();\n  program.AddConstraint(T3);\n  return constraint_id;\n}\n\nint CONEX_AddSparseLMIConstraint(void* prog, const double* A, int Ar, int Ac,\n                                 int num_vars, const double* c, int cr, int cc,\n                                 const long* vars, int vars_rows) {\n  assert(Ar == Ac);\n  assert(Ar == cr);\n  assert(cc == cr);\n  assert(vars_rows == num_vars);\n\n  // TODO(FrankPermenter): Remove these copies.\n  using InputMatrix = Eigen::Map<const DenseMatrix>;\n  auto offset = A;\n  std::vector<DenseMatrix> Avect;\n  std::vector<int> variables(num_vars);\n  for (int i = 0; i < num_vars; i++) {\n    InputMatrix Amap(offset, Ar, Ac);\n    Avect.push_back(Amap);\n    offset += Ar * Ac;\n    variables.at(i) = *(vars + i);\n  }\n  InputMatrix Cmap(c, cr, cc);\n\n  conex::DenseLMIConstraint T3{Avect, Cmap};\n  auto& program = *reinterpret_cast<Program*>(prog);\n  int constraint_id = program.NumberOfConstraints();\n  program.AddConstraint(T3, variables);\n  return constraint_id;\n}\n\nint CONEX_AddLinearInequalities(void* prog, const double* A, int Ar, int Ac,\n                                const double* lb, int num_lb, const double* ub,\n                                int num_ub) {\n  assert(Ar == num_lb);\n  assert(Ar == num_ub);\n  Eigen::MatrixXd Ain = Eigen::Map<const Eigen::MatrixXd>(A, Ar, Ac);\n  Eigen::MatrixXd lbin = Eigen::Map<const Eigen::MatrixXd>(lb, Ar, 1);\n  Eigen::MatrixXd ubin = Eigen::Map<const Eigen::MatrixXd>(ub, Ar, 1);\n\n  Eigen::MatrixXd Aeq;\n  Eigen::MatrixXd beq;\n  Eigen::MatrixXd Aineq;\n  Eigen::MatrixXd bineq;\n  conex::PreprocessLinearInequality(Ain, lbin, ubin, &Aineq, &bineq, &Aeq,\n                                    &beq);\n\n  auto& program = *reinterpret_cast<Program*>(prog);\n  if (Aineq.rows() > 0) {\n    program.AddConstraint(conex::LinearConstraint(Aineq, bineq));\n  }\n  if (Aeq.rows() > 0) {\n    program.AddConstraint(conex::EqualityConstraints(Aeq, beq));\n  }\n  // TODO(FrankPermenter): Return the correct ID.\n  return -1;\n}\nint CONEX_AddDenseLinearConstraint(void* prog, const double* A, int Ar, int Ac,\n                                   const double* c, int cr) {\n  assert(Ar == cr);\n\n  int n = Ar;\n  int m = Ac;\n\n  conex::LinearConstraint T3{n, m, A, c};\n  auto& program = *reinterpret_cast<Program*>(prog);\n\n  int constraint_id = program.NumberOfConstraints();\n  program.AddConstraint(T3);\n  return constraint_id;\n}\n\nvoid CONEX_SetDefaultOptions(CONEX_SolverConfiguration* c) {\n  if (c == NULL) {\n    std::cerr << \"Received null pointer.\";\n    return;\n  }\n  SolverConfiguration config;\n\n  c->prepare_dual_variables = config.prepare_dual_variables;\n  c->initialization_mode = config.initialization_mode;\n  c->inv_sqrt_mu_max = config.inv_sqrt_mu_max;\n  c->minimum_mu = config.minimum_mu;\n  c->maximum_mu = config.maximum_mu;\n  c->divergence_upper_bound = config.divergence_upper_bound;\n  c->enable_line_search = config.enable_line_search;\n  c->dinf_upper_bound = config.dinf_upper_bound;\n  c->final_centering_steps = config.final_centering_steps;\n  c->final_centering_tolerance = config.final_centering_tolerance;\n  c->initial_centering_steps_warmstart =\n      config.initial_centering_steps_warmstart;\n  c->initial_centering_steps_coldstart =\n      config.initial_centering_steps_coldstart;\n  c->warmstart_abort_threshold = config.warmstart_abort_threshold;\n  c->max_iterations = config.max_iterations;\n  c->infeasibility_threshold = config.infeasibility_threshold;\n  c->kkt_error_tolerance = config.kkt_error_tolerance;\n  c->enable_rescaling = config.enable_rescaling;\n}\n\nvoid CONEX_GetIterationStats(void* prog, CONEX_IterationStats* stats,\n                             int iter_num_circular) {\n  if ((prog == NULL) || (stats == NULL)) {\n    std::cerr << \"Received null pointer.\";\n    return;\n  }\n\n  auto& program = *reinterpret_cast<Program*>(prog);\n\n  if (!program.stats->IsInitialized()) {\n    std::cerr << \"No statistics available.\";\n    return;\n  }\n\n  int iter_num = iter_num_circular;\n  if (iter_num_circular < 0) {\n    iter_num = program.stats->num_iter + iter_num_circular;\n  }\n\n  if ((program.stats->num_iter <= iter_num) || (iter_num < 0)) {\n    std::cerr << \"Specified iteration is out of bounds.\";\n    return;\n  }\n  stats->mu = 1.0 / (program.stats->sqrt_inv_mu[iter_num] *\n                     program.stats->sqrt_inv_mu[iter_num]);\n  stats->iteration_number = iter_num;\n}\n\nCONEX_STATUS CONEX_NewLinearMatrixInequality(void* p, int order,\n                                             int hyper_complex_dim,\n                                             int* constraint_id) {\n  CONEX_DEMAND(order >= 1, \"Invalid LMI dimensions.\");\n  CONEX_DEMAND(constraint_id, \"Received output null pointer.\");\n  CONEX_DEMAND(hyper_complex_dim == 1 || hyper_complex_dim == 2 ||\n                   hyper_complex_dim == 4 || hyper_complex_dim == 8,\n               \"Hypercomplex dimension must be 1, 2, 4, or 8.\");\n\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n\n  switch (hyper_complex_dim) {\n    case 1:\n      prg->AddConstraint(HermitianPsdConstraint<conex::Real>(order));\n      break;\n    case 2:\n      prg->AddConstraint(HermitianPsdConstraint<conex::Complex>(order));\n      break;\n    case 4:\n      prg->AddConstraint(HermitianPsdConstraint<conex::Quaternions>(order));\n      break;\n    case 8:\n      CONEX_DEMAND(order <= 3,\n                   \"Order of octonion algebra cannot be greater than 3.\");\n      prg->AddConstraint(HermitianPsdConstraint<conex::Octonions>(order));\n  }\n  *constraint_id = prg->NumberOfConstraints() - 1;\n  return CONEX_SUCCESS;\n}\n\nCONEX_STATUS CONEX_NewLinearInequality(void* program, int num_rows,\n                                       int* constraint_id) {\n  CONEX_DEMAND(constraint_id, \"Received output null pointer.\");\n  Program* prg;\n  SAFER_CAST_TO_Program(program, prg);\n  int n = prg->GetNumberOfVariables();\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(num_rows, n);\n  Eigen::MatrixXd b = Eigen::MatrixXd::Zero(num_rows, 1);\n  bool status = prg->AddConstraint(LinearConstraint{A, b});\n  *constraint_id = prg->NumberOfConstraints() - 1;\n  return status;\n}\n\nCONEX_STATUS CONEX_NewQuadraticCost(void* p, int* constraint_id) {\n  CONEX_DEMAND(constraint_id, \"Received output null pointer.\");\n\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n  int n = prg->GetNumberOfVariables();\n  Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(n, n);\n  bool status = prg->AddQuadraticCost(Q);\n  *constraint_id = prg->NumberOfConstraints() - 1;\n  return status;\n}\n\nCONEX_STATUS CONEX_AddQuadraticCost(void* p, const double* A, int Ar, int Ac) {\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n  int n = prg->GetNumberOfVariables();\n  Eigen::MatrixXd Q;\n  std::vector<int> vars;\n\n  Eigen::Map<const DenseMatrix> input(A, Ar, Ac);\n  NonZeroSubMat(input, &vars, &Q);\n  bool status = prg->AddQuadraticCost(Q, vars);\n  return status;\n}\n\nCONEX_STATUS CONEX_UpdateQuadraticCostMatrix(void* p, int constraint,\n                                             double value, int row, int col) {\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n  CONEX_DEMAND(constraint < prg->NumberOfConstraints(), \"Invalid Constraint.\");\n  return prg->UpdateAffineTermOfConstraint(constraint, value, row, col,\n                                           0 /*hyper complex dimension*/);\n}\n\nCONEX_STATUS CONEX_UpdateLinearOperator(void* p, int constraint, double value,\n                                        int variable, int row, int col,\n                                        int hyper_complex_dim) {\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n  CONEX_DEMAND(constraint < prg->NumberOfConstraints(), \"Invalid Constraint.\");\n  return prg->UpdateLinearOperatorOfConstraint(constraint, value, variable, row,\n                                               col, hyper_complex_dim);\n}\n\nCONEX_STATUS CONEX_UpdateAffineTerm(void* p, int constraint, double value,\n                                    int row, int col, int hyper_complex_dim) {\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n  CONEX_DEMAND(constraint < prg->NumberOfConstraints(), \"Invalid Constraint.\");\n  return prg->UpdateAffineTermOfConstraint(constraint, value, row, col,\n                                           hyper_complex_dim);\n}\n\nCONEX_STATUS CONEX_NewLorentzConeConstraint(void* p, int order,\n                                            int* constraint_id) {\n  CONEX_DEMAND(\n      order >= 1,\n      \"Received invalid n. Second order cone must have order (n + 1) >= 2.\");\n  CONEX_DEMAND(constraint_id, \"Received output null pointer.\");\n\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n\n  prg->AddConstraint(conex::SOCConstraint(order));\n  *constraint_id = prg->NumberOfConstraints() - 1;\n  return CONEX_SUCCESS;\n}\n\nCONEX_STATUS CONEX_SetNumberOfVariables(void* p, int number_of_variables) {\n  CONEX_DEMAND(number_of_variables >= 1, \"Number of variables must be > 0.\");\n  Program* prg;\n  SAFER_CAST_TO_Program(p, prg);\n  CONEX_DEMAND(prg->GetNumberOfVariables() == 0,\n               \"Number of variables already set.\");\n  prg->SetNumberOfVariables(number_of_variables);\n  return CONEX_SUCCESS;\n}\n", "meta": {"hexsha": "6ce14958ac7e0bb8a10f54ee5aa2e405d55da635", "size": 14471, "ext": "cc", "lang": "C++", "max_stars_repo_path": "interfaces/conex.cc", "max_stars_repo_name": "frankpermenter/conex", "max_stars_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T20:41:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T20:41:20.000Z", "max_issues_repo_path": "interfaces/conex.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interfaces/conex.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4681372549, "max_line_length": 80, "alphanum_fraction": 0.6508879829, "num_tokens": 3665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.026355353993244617, "lm_q1q2_score": 0.011034905261946577}}
{"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, 2019.\r\n// Modifications copyright (c) 2017-2019, 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_LABRD_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_LABRD_HPP\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.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 labrd\r\n    {\r\n            static const double epsilon = 1.e-10;\r\n\r\n            template <typename T>\r\n            struct par_labrd\r\n            {\r\n                T    Az, kRg, p0s, A, C, Ca, Cb, Cc, Cd;\r\n            };\r\n\r\n            template <typename T, typename Parameters>\r\n            struct base_labrd_ellipsoid\r\n            {\r\n                par_labrd<T> m_proj_parm;\r\n\r\n                // FORWARD(e_forward)\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(Parameters const& par, T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    static const T fourth_pi = detail::fourth_pi<T>();\r\n\r\n                    T V1, V2, ps, sinps, cosps, sinps2, cosps2;\r\n                    T I1, I2, I3, I4, I5, I6, x2, y2, t;\r\n\r\n                    V1 = this->m_proj_parm.A * log( tan(fourth_pi + .5 * lp_lat) );\r\n                    t = par.e * sin(lp_lat);\r\n                    V2 = .5 * par.e * this->m_proj_parm.A * log ((1. + t)/(1. - t));\r\n                    ps = 2. * (atan(exp(V1 - V2 + this->m_proj_parm.C)) - fourth_pi);\r\n                    I1 = ps - this->m_proj_parm.p0s;\r\n                    cosps = cos(ps);    cosps2 = cosps * cosps;\r\n                    sinps = sin(ps);    sinps2 = sinps * sinps;\r\n                    I4 = this->m_proj_parm.A * cosps;\r\n                    I2 = .5 * this->m_proj_parm.A * I4 * sinps;\r\n                    I3 = I2 * this->m_proj_parm.A * this->m_proj_parm.A * (5. * cosps2 - sinps2) / 12.;\r\n                    I6 = I4 * this->m_proj_parm.A * this->m_proj_parm.A;\r\n                    I5 = I6 * (cosps2 - sinps2) / 6.;\r\n                    I6 *= this->m_proj_parm.A * this->m_proj_parm.A *\r\n                        (5. * cosps2 * cosps2 + sinps2 * (sinps2 - 18. * cosps2)) / 120.;\r\n                    t = lp_lon * lp_lon;\r\n                    xy_x = this->m_proj_parm.kRg * lp_lon * (I4 + t * (I5 + t * I6));\r\n                    xy_y = this->m_proj_parm.kRg * (I1 + t * (I2 + t * I3));\r\n                    x2 = xy_x * xy_x;\r\n                    y2 = xy_y * xy_y;\r\n                    V1 = 3. * xy_x * y2 - xy_x * x2;\r\n                    V2 = xy_y * y2 - 3. * x2 * xy_y;\r\n                    xy_x += this->m_proj_parm.Ca * V1 + this->m_proj_parm.Cb * V2;\r\n                    xy_y += this->m_proj_parm.Ca * V2 - this->m_proj_parm.Cb * V1;\r\n                }\r\n\r\n                // INVERSE(e_inverse)  ellipsoid & spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(Parameters const& par, T xy_x, T xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    static const T fourth_pi = detail::fourth_pi<T>();\r\n\r\n                    /* t = 0.0 optimization is to avoid a false positive cppcheck warning */\r\n                    /* (cppcheck git beaf29c15867984aa3c2a15cf15bd7576ccde2b3). Might no */\r\n                    /* longer be necessary with later versions. */\r\n                    T x2, y2, V1, V2, V3, V4, t = 0.0, t2, ps, pe, tpe, s;\r\n                    T I7, I8, I9, I10, I11, d, Re;\r\n                    int i;\r\n\r\n                    x2 = xy_x * xy_x;\r\n                    y2 = xy_y * xy_y;\r\n                    V1 = 3. * xy_x * y2 - xy_x * x2;\r\n                    V2 = xy_y * y2 - 3. * x2 * xy_y;\r\n                    V3 = xy_x * (5. * y2 * y2 + x2 * (-10. * y2 + x2 ));\r\n                    V4 = xy_y * (5. * x2 * x2 + y2 * (-10. * x2 + y2 ));\r\n                    xy_x += - this->m_proj_parm.Ca * V1 - this->m_proj_parm.Cb * V2 + this->m_proj_parm.Cc * V3 + this->m_proj_parm.Cd * V4;\r\n                    xy_y +=   this->m_proj_parm.Cb * V1 - this->m_proj_parm.Ca * V2 - this->m_proj_parm.Cd * V3 + this->m_proj_parm.Cc * V4;\r\n                    ps = this->m_proj_parm.p0s + xy_y / this->m_proj_parm.kRg;\r\n                    pe = ps + par.phi0 - this->m_proj_parm.p0s;\r\n\r\n                    for ( i = 20; i; --i) {\r\n                        V1 = this->m_proj_parm.A * log(tan(fourth_pi + .5 * pe));\r\n                        tpe = par.e * sin(pe);\r\n                        V2 = .5 * par.e * this->m_proj_parm.A * log((1. + tpe)/(1. - tpe));\r\n                        t = ps - 2. * (atan(exp(V1 - V2 + this->m_proj_parm.C)) - fourth_pi);\r\n                        pe += t;\r\n                        if (fabs(t) < epsilon)\r\n                            break;\r\n                    }\r\n\r\n                    t = par.e * sin(pe);\r\n                    t = 1. - t * t;\r\n                    Re = par.one_es / ( t * sqrt(t) );\r\n                    t = tan(ps);\r\n                    t2 = t * t;\r\n                    s = this->m_proj_parm.kRg * this->m_proj_parm.kRg;\r\n                    d = Re * par.k0 * this->m_proj_parm.kRg;\r\n                    I7 = t / (2. * d);\r\n                    I8 = t * (5. + 3. * t2) / (24. * d * s);\r\n                    d = cos(ps) * this->m_proj_parm.kRg * this->m_proj_parm.A;\r\n                    I9 = 1. / d;\r\n                    d *= s;\r\n                    I10 = (1. + 2. * t2) / (6. * d);\r\n                    I11 = (5. + t2 * (28. + 24. * t2)) / (120. * d * s);\r\n                    x2 = xy_x * xy_x;\r\n                    lp_lat = pe + x2 * (-I7 + I8 * x2);\r\n                    lp_lon = xy_x * (I9 + x2 * (-I10 + x2 * I11));\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"labrd_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Laborde\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_labrd(Params const& params, Parameters const& par, par_labrd<T>& proj_parm)\r\n            {\r\n                static const T fourth_pi = detail::fourth_pi<T>();\r\n\r\n                T Az, sinp, R, N, t;\r\n\r\n                Az = pj_get_param_r<T, srs::spar::azi>(params, \"azi\", srs::dpar::azi);\r\n                sinp = sin(par.phi0);\r\n                t = 1. - par.es * sinp * sinp;\r\n                N = 1. / sqrt(t);\r\n                R = par.one_es * N / t;\r\n                proj_parm.kRg = par.k0 * sqrt( N * R );\r\n                proj_parm.p0s = atan( sqrt(R / N) * tan(par.phi0) );\r\n                proj_parm.A = sinp / sin(proj_parm.p0s);\r\n                t = par.e * sinp;\r\n                proj_parm.C = .5 * par.e * proj_parm.A * log((1. + t)/(1. - t)) +\r\n                    - proj_parm.A * log( tan(fourth_pi + .5 * par.phi0))\r\n                    + log( tan(fourth_pi + .5 * proj_parm.p0s));\r\n                t = Az + Az;\r\n                proj_parm.Ca = (1. - cos(t)) * ( proj_parm.Cb = 1. / (12. * proj_parm.kRg * proj_parm.kRg) );\r\n                proj_parm.Cb *= sin(t);\r\n                proj_parm.Cc = 3. * (proj_parm.Ca * proj_parm.Ca - proj_parm.Cb * proj_parm.Cb);\r\n                proj_parm.Cd = 6. * proj_parm.Ca * proj_parm.Cb;\r\n            }\r\n\r\n    }} // namespace detail::labrd\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Laborde 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         - Special for Madagascar\r\n        \\par Projection parameters\r\n         - no_rot: No rotation (boolean)\r\n         - azi: Azimuth (or Gamma) (degrees)\r\n        \\par Example\r\n        \\image html ex_labrd.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct labrd_ellipsoid : public detail::labrd::base_labrd_ellipsoid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline labrd_ellipsoid(Params const& params, Parameters const& par)\r\n        {\r\n            detail::labrd::setup_labrd(params, 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_FI(srs::spar::proj_labrd, labrd_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(labrd_entry, labrd_ellipsoid)\r\n        \r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(labrd_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(labrd, labrd_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_LABRD_HPP\r\n\r\n", "meta": {"hexsha": "740f5ab8580d34aad2d7b747229881e7ea599a8b", "size": 10977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/srs/projections/proj/labrd.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/geometry/srs/projections/proj/labrd.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/geometry/srs/projections/proj/labrd.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": 44.987704918, "max_line_length": 141, "alphanum_fraction": 0.517445568, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981164073979497, "lm_q2_score": 0.02758528112757725, "lm_q1q2_score": 0.011028916507885162}}
{"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 \"covering.h\"\n#include \"python/map.h\"\n#include <Eigen/Sparse>\nusing namespace Eigen;\n#include <iostream>\n#include <unordered_set>\n\nconst float RECALL_OVERLAP = 0.5;\n\nVectorXf bestOverlap( const std::vector<Polygons> & regions, const RMatrixXs &over_seg, const RMatrixXb &segments, VectorXf * area = NULL ) {\n\tconst int N_sp = over_seg.maxCoeff()+1, N_gt = regions.size();\n\t\n\t// Compute the sparse proposal matrix\n\tSparseMatrix<float> props( segments.rows(), segments.cols() );\n\tstd::vector< Triplet<float> > t;\n\tfor( int j=0; j<props.rows(); j++ )\n\t\tfor( int i=0; i<props.cols(); i++ ) \n\t\t\tif( segments(j,i) )\n\t\t\t\tt.push_back( Triplet<float>(j,i,1) );\n\tprops.setFromTriplets( t.begin(), t.end() );\n\t\n\t// Compute the superpixel areas\n\tVectorXf sp_area = VectorXf::Zero( N_sp );\n\tfor( int j=0; j<over_seg.rows(); j++ )\n\t\tfor( int i=0; i<over_seg.cols(); i++ )\n\t\t\tsp_area[ over_seg(j,i) ]++;\n\t\t\n\tif(area)\n\t\t*area = VectorXf::Zero( N_gt );\n\tVectorXf r( N_gt );\n\t// Compute the best overlap with each GT object\n\tfor( int i=0; i<N_gt; i++ ) {\n\t\tfloat gt_area = 0;\n\t\tVectorXf cur_sp_area = sp_area;\n\t\tSparseVector<float> intersection( N_sp );\n\t\trasterize( [&](int x,int y,RasterType t){\n\t\t\tif (0<=x && x<over_seg.cols() && 0<=y && y<over_seg.rows()) {\n\t\t\t\tconst int s = over_seg(y,x);\n\t\t\t\tif( t==INSIDE ){\n\t\t\t\t\tgt_area += 1;\n\t\t\t\t\tintersection.coeffRef( s ) += 1;\n\t\t\t\t}\n\t\t\t\t// Ignore boundary pixels\n\t\t\t\telse if (t==OUTSIDE_BOUNDARY)\n\t\t\t\t\tcur_sp_area[s]-=1;\n\t\t\t}\n\t\t}, regions[i] );\n\t\tVectorXf prop_area = props * cur_sp_area;\n\t\tSparseVector<float> prop_intersection = props * intersection;\n\t\t\n\t\tfloat bo = 0;\n\t\tfor( SparseVector<float>::InnerIterator it(prop_intersection); it; ++it )\n\t\t\tbo = std::max( bo, it.value() / (gt_area + prop_area[it.row()] - it.value()) );\n\t\t\n\t\tr[i] = bo;\n\t\tif(area)\n\t\t\t(*area)[i] = gt_area;\n\t}\n\treturn r;\n}\n\nVectorXf bestOverlap( const short * gt_seg, int W, int H, int D, const RMatrixXs &over_seg, const RMatrixXb &segments, VectorXf * area = NULL ) {\n\tif( W != over_seg.cols() || H != over_seg.rows() )\n\t\tthrow std::invalid_argument(\"Ground truth and over segmentation shape does not match!\");\n\tMap<const VectorXs> sp( (const short*)over_seg.data(), W*H );\n\tMap<const RMatrixXs> gt( gt_seg, D, W*H );\n\t\n\tVectorXs N_sgt = gt.array().rowwise().maxCoeff()+1;\n\tconst int N_gt = N_sgt.array().sum(), N_sp = sp.maxCoeff()+1;\n\tif( N_sp != segments.cols() )\n\t\tthrow std::invalid_argument(\"Number of superpixels does not match segment size!\");\n\t\n\tVectorXf gt_area = VectorXf::Zero( N_gt ), sp_area = VectorXf::Zero( N_sp );\n\tSparseMatrix<float> intersection( N_gt, N_sp );\n\tfor( int i=0; i<W*H; i++ ) {\n\t\tconst int s = sp[i];\n\t\tbool cnt_area = false;\n\t\tfor( int d=0,o=0; d<D; o+=N_sgt[d++] ) {\n\t\t\tif( !cnt_area )\n\t\t\t\tcnt_area = (gt(d,i)>=-1);\n\t\t\tif( gt(d,i)>=0 ){\n\t\t\t\tconst int t = o+gt(d,i);\n\t\t\t\tgt_area[t]++;\n\t\t\t\tif( s >= 0 ) {\n\t\t\t\t\tintersection.coeffRef(t,s) += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif( cnt_area && s >= 0 )\n\t\t\tsp_area[s]++;\n\t}\n\tintersection.makeCompressed();\n\t\n\tSparseMatrix<float> props( segments.rows(), segments.cols() );\n\tstd::vector< Triplet<float> > t;\n\tfor( int j=0; j<props.rows(); j++ )\n\t\tfor( int i=0; i<props.cols(); i++ ) \n\t\t\tif( segments(j,i) )\n\t\t\t\tt.push_back( Triplet<float>(j,i,1) );\n\tprops.setFromTriplets( t.begin(), t.end() );\n\t\n\tVectorXf seg_area = props * sp_area;\n\tSparseMatrix<float> seg_intersection = intersection * props.transpose();\n\t\n\tVectorXf r = VectorXf::Zero( N_gt );\n\tfor (int k=0; k<seg_intersection.outerSize(); ++k)\n\t\tfor (SparseMatrix<float>::InnerIterator it(seg_intersection,k); it; ++it)\n\t\t\tr[it.row()] = std::max( r[it.row()], it.value() / ( seg_area[ it.col() ] + gt_area[ it.row() ] - it.value() ) );\n\tif( area )\n\t\t*area = gt_area;\n\treturn r;\n}\n\nProposalEvaluation::ProposalEvaluation(const std::vector<Polygons> & regions, const std::vector<RMatrixXs> & over_seg, const std::vector<RMatrixXb> & props) {\n\tif( over_seg.size() != props.size() )\n\t\tthrow std::invalid_argument(\"Different number of over segmentations and proposals!\");\n\tif( over_seg.size() < 1 )\n\t\tthrow std::invalid_argument(\"At least one proposal required!\");\n\t\n\tVectorXf area, bo;\n\tpool_size_ = 0;\n\tfor( int k=0; k <over_seg.size(); k++ ) {\n\t\tVectorXf o = bestOverlap( regions, over_seg[k], props[k], &area );\n\t\tif( k )\n\t\t\tbo = bo.array().max( o.array() );\n\t\telse\n\t\t\tbo = o;\n\t\tpool_size_ += props[k].rows();\n\t}\n\tbo_ = bo;\n\tarea_ = area;\n}\nProposalEvaluation::ProposalEvaluation(const std::vector<Polygons> & regions, const RMatrixXs &over_seg, const RMatrixXb &props ):ProposalEvaluation( regions, std::vector<RMatrixXs>(1,over_seg), std::vector<RMatrixXb>( 1, props ) ) {\n}\nProposalEvaluation::ProposalEvaluation(const short int *gt_seg, int W, int H, int D, const std::vector<RMatrixXs> & over_seg, const std::vector<RMatrixXb> & props) {\n\tif( over_seg.size() != props.size() )\n\t\tthrow std::invalid_argument(\"Different number of over segmentations and proposals!\");\n\tif( over_seg.size() < 1 )\n\t\tthrow std::invalid_argument(\"At least one proposal required!\");\n\t\n\tVectorXf area, bo;\n\tpool_size_ = 0;\n\tfor( int k=0; k <over_seg.size(); k++ ) {\n\t\tVectorXf o = bestOverlap( gt_seg, W, H, D, over_seg[k], props[k], &area );\n\t\tif( k )\n\t\t\tbo = bo.array().max( o.array() );\n\t\telse\n\t\t\tbo = o;\n\t\tpool_size_ += props[k].rows();\n\t}\n\tbo_ = bo;\n\tarea_ = area;\n}\nProposalEvaluation::ProposalEvaluation( const short int *gt_seg, int W, int H, int D, const RMatrixXs &over_seg, const RMatrixXb &props ):ProposalEvaluation( gt_seg, W, H, D, std::vector<RMatrixXs>(1,over_seg), std::vector<RMatrixXb>( 1, props )/*, recall_overlap*/ ) {\n}\nfloat boxOverlap( const VectorXi & b1, const VectorXi & b2 ) {\n\tfloat intersec = (std::max(0,std::min(b1[2],b2[2]) - std::max(b1[0],b2[0]))*std::max(0,std::min(b1[3],b2[3]) - std::max(b1[1],b2[1])));\n\tfloat _union   = (std::max(0,std::max(b1[2],b2[2]) - std::min(b1[0],b2[0]))*std::max(0,std::max(b1[3],b2[3]) - std::min(b1[1],b2[1])));\n\tif( _union > 0 )\n\t\treturn intersec / _union;\n\treturn 0;\n}\nProposalBoxEvaluation::ProposalBoxEvaluation(const RMatrixXi &bbox, const std::vector<RMatrixXi> & prop_boxes) {\n\tif( prop_boxes.size() < 1 )\n\t\tthrow std::invalid_argument(\"At least one proposal required!\");\n\t\n\tif (bbox.rows() == 0) {\n\t\tbo_ = VectorXf::Zero(0);\n\t\tpool_size_ = NAN;\n\t\treturn;\n\t}\n\t\n\tVectorXf bo = VectorXf::Zero( bbox.rows() );\n\tpool_size_ = 0;\n\tfor( int k=0; k<prop_boxes.size(); k++ ) {\n\t\tconst int nProp = prop_boxes[k].rows();\n\t\t// Compute the pool size\n\t\tstd::unordered_set<uint64_t> ht;\n\t\tfor( int j=0; j<nProp; j++ ) {\n\t\t\tuint64_t h = 0;\n\t\t\tfor( int l=0; l<4; l++ )\n\t\t\t\th = (h<<16) + ((unsigned short)prop_boxes[k](j,l));\n\t\t\tif( !ht.count( h ) ) {\n\t\t\t\tht.insert( h );\n\t\t\t\tpool_size_++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor( int i=0; i<bo.size(); i++ )\n\t\t\tfor( int j=0; j<nProp; j++ )\n\t\t\t\tbo[i] = std::max( bo[i], boxOverlap( prop_boxes[k].row(j), bbox.row(i) ) );\n\t}\n\tbo_ = bo;\n}\nProposalBoxEvaluation::ProposalBoxEvaluation( const RMatrixXi &bbox, const RMatrixXi &prop_boxes):ProposalBoxEvaluation( bbox, std::vector<RMatrixXi>(1,prop_boxes) ) {\n}\n", "meta": {"hexsha": "b4cbaa4500fcb8b84070b6bf41570b81e62bd4ce", "size": 8577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sd_maskrcnn/gop/lib/python/dataset/covering.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/python/dataset/covering.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/python/dataset/covering.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": 38.4618834081, "max_line_length": 269, "alphanum_fraction": 0.6610703043, "num_tokens": 2597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.023330768299163782, "lm_q1q2_score": 0.011028068671874522}}
{"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 EPSMOEA_HPP_\n#define EPSMOEA_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/common.hpp>\nnamespace sferes {\n  namespace ea {\n    // param : eps (array)\n    // param : min_fit (array)\n    // param : grain\n    SFERES_EA(EpsMOEA, Ea) {\n    public:\n      void random_pop() {\n        parallel::init();\n        this->_pop.resize(Params::pop::size);\n        parallel::p_for(parallel::range_t(0, this->_pop.size()),\n                        random<Phen>(this->_pop));\n        this->_eval.eval(this->_pop, 0, this->_pop.size());\n\n        // create archive\n        add_to_archive(this->_pop.front());\n        for (typename pop_t :: const_iterator it = this->_pop.begin();\n             it != this->_pop.end(); ++it)\n          archive_acceptance(*it);\n        sync_archive();\n      }\n\n      void epoch() {\n        std::vector<indiv_t> indivs;\n\n        for (size_t i = 0; i < Params::pop::grain; ++i) {\n          indiv_t i1 = pop_selection();\n          indiv_t i2 = archive_selection();\n          indiv_t c1, c2;\n          i1->cross(i2, c1, c2);\n          indivs.push_back(c1);\n          indivs.push_back(c2);\n        }\n        parallel::p_for(parallel::range_t(0, indivs.size()),\n                        mutate<Phen>(indivs));\n\n        this->_eval.eval(indivs, 0, indivs.size());\n\n        BOOST_FOREACH(indiv_t i, indivs)\n        if (pop_acceptance(i))\n          archive_acceptance(i);\n        sync_archive();\n      }\n      const std::vector<boost::shared_ptr<Phen> >& pareto_front() const {\n        return _pareto_front;\n      }\n    protected:\n      typedef boost::shared_ptr<Phen> indiv_t;\n      typedef std::vector<indiv_t> pop_t;\n      typedef std::pair<indiv_t, std::vector<float> > elite_t;\n      typedef std::list<elite_t> archive_t;\n      typedef std::vector<std::vector<float> > id_t;\n\n      // elite\n      archive_t pop_e;\n\n      // identification vectors\n      id_t id_b;\n\n      pop_t _pareto_front;\n\n      // keep pareto_front & elite synchronized (for stat reporting)\n      void sync_archive() {\n        _pareto_front.clear();\n        BOOST_FOREACH(elite_t& i, pop_e)\n        _pareto_front.push_back(i.first);\n      }\n\n      /// return a random + tournament individual in P\n      indiv_t pop_selection() {\n\n        indiv_t i1 = this->_pop[misc::rand(this->_pop.size())];\n        indiv_t i2 = this->_pop[misc::rand(this->_pop.size())];\n\n        int flag = check_dominance(i1, i2);\n        switch (flag) {\n        case 1: // a dom b\n          return i1;\n        case -1:\n          return i2;\n        case 0:\n          if (misc::flip_coin())\n            return i1;\n          else\n            return i2;\n        }\n        assert(0);\n        return indiv_t();\n      }\n\n      ///  return a random individual in E\n      indiv_t archive_selection() {\n        return misc::rand_in_list(pop_e)->first;\n\n      }\n\n      /// try to insert the offspring in population\n      /// return true if accepted\n      bool pop_acceptance(indiv_t ind) {\n        dbg::out(dbg::info, \"epsmoea\")<<\"pop_acceptance :\"<<indiv_str(ind)<<std::endl;\n        int flag = 0;\n        std::vector<int> array;\n        int i = 0;\n\n        for (typename pop_t :: const_iterator it = this->_pop.begin();\n             it != this->_pop.end(); ++it) {\n          flag = check_dominance(ind, *it);\n          switch (flag) {\n          case 1:\n            array.push_back(i);\n            break;\n          case -1:\n            dbg::out(dbg::info, \"epsmoea\")<<\"pop_acceptance -> rejected\"<<std::endl;\n            return false;\n          case 0:\n            break;\n          default:\n            assert(0);\n          }\n          ++i;\n        }\n\n        int k;\n        if (array.size())\n          k = array[misc::rand(array.size())];\n        else\n          k = misc::rand(this->_pop.size());\n        dbg::out(dbg::info, \"epsmoea\")<<\"pop_acceptance, removing :\"\n                                      <<indiv_str(this->_pop[k])\n                                      <<\"  array.size()=\"<<array.size()<<std::endl;\n        this->_pop[k] = ind;\n        dbg::out(dbg::info, \"epsmoea\")<<\"pop_acceptance -> accepted (k=\"<<k<<\")\"<<std::endl;\n        return true;\n      }\n\n      ///  try to insert the offspring in pop_e\n      /// return true if accepted\n      bool archive_acceptance(indiv_t indiv) {\n        dbg::out(dbg::info, \"epsmoea\")<<\"archive_acceptance :\"<<indiv_str(indiv)<<std::endl;\n        elite_t ind = make_identification_vector(indiv);\n        typename archive_t :: iterator it = pop_e.begin();\n        bool same_box = false;\n        do {\n          assert(it != pop_e.end());\n          int flag = check_box_dominance(ind, *it);\n          switch (flag) {\n          case 1:\n            // if ind eps-dominates *it, we delete *it\n            it = pop_e.erase(it);\n            break;\n          case 2:\n            // *it eps-dominates ind, we stop the procedure\n            dbg::out(dbg::info, \"epsmoea\")<<\"archive_acceptance -> rejected\"<<std::endl;\n            return false;\n          case 3:\n            // both are non-dominated and are in different boxes, we\n            // continue\n            ++it;\n            break;\n          case 4:\n            // both are non-dominated and are in same hyper-box\n            same_box = true;\n            break;\n          default:\n            assert(0);\n          }\n        } while(!same_box && it != pop_e.end());\n\n        //=> the offspring (indiv) is eps-non-dominated\n        // if it isn't in any filled box, we add it to the archive\n        if (!same_box) {\n          add_to_archive(indiv);\n          return true;\n        }\n        assert(it != pop_e.end());\n        // else, they are in the same box and we do a dominance check\n        int flag = check_dominance(ind.first, it->first);\n        float d1, d2;\n        switch (flag) {\n        case 1:\n          pop_e.erase(it);\n          add_to_archive(indiv);\n          return true;\n        case -1:\n          return false;\n        case 0:\n          //both are non-dominated, we select the closest to the B\n          //vector\n          //  /!\\ -> loss of a archived individual !\n          d1 = dist_to_id(ind);\n          d2 = dist_to_id(*it);\n          if (d1 <= d2) {\n            pop_e.erase(it);\n            add_to_archive(indiv);\n            return true;\n          } else\n            return false;\n        default:\n          assert(0);\n        }\n        assert(0);\n        return false;\n      }\n\n      /// check dominance using the identification vector\n      /// returns the following:\n      ///\t* 1 if a dominates b\n      ///\t* 2 if b dominates a\n      ///\t* 3 if a and b are non-dominated and a!=b (identification arrays unequal)\n      ///\t* 4 if a and b are non-dominated and a=b\n      int check_box_dominance(const elite_t &a, const elite_t &b) const {\n        int flag1 = 0, flag2 = 0;\n\n        for (unsigned i = 0; i < Params::pop::eps_size(); ++i)\n          if (a.second[i] > b.second[i])\n            flag1 = 1;\n          else if (b.second[i] > a.second[i])\n            flag2 = 1;\n\n        // a dominates b\n        if (flag1 && !flag2)\n          return 1;\n        // b dominates a\n        if (!flag1 && flag2)\n          return 2;\n        // a and b are non-dominated and a!=b (identification arrays unequal)\n        if (flag1 && flag2)\n          return 3;\n        // a and b are non-dominated and a=b\n        assert(!flag1 && !flag2);\n        return 4;\n      }\n\n      /// standard dominance\n      /// * 1 if a dominates b\n      /// * -1 if b dominates a\n      /// * 0 if both a and b are non-dominated\n      int check_dominance(const indiv_t a, const indiv_t b) const {\n        assert(a->fit().objs().size() == b->fit().objs().size());\n        assert(a->fit().objs().size());\n        size_t nb_objs = a->fit().objs().size();\n        int flag1 = 0, flag2 = 0;\n        for (size_t i = 0; i < nb_objs; ++i)\n          if (a->fit().obj(i) > b->fit().obj(i))\n            flag1 = 1;\n          else if (a->fit().obj(i) < b->fit().obj(i))\n            flag2 = 1;\n\n        if (flag1 && !flag2)\n          return 1;\n\n        if (!flag1 && flag2)\n          return -1;\n\n        return 0;\n      }\n\n      /// compute an identification vector and return it\n      elite_t make_identification_vector(indiv_t indiv) const {\n        elite_t e;\n        e.first = indiv;\n        e.second.resize(Params::pop::eps_size());\n        dbg::out(dbg::info, \"epsmoea\")<<\"eps_size=\"<<Params::pop::eps_size()\n                                      <<\" fitsize:\"<<indiv->fit().objs().size()\n                                      <<std::endl;\n        assert(e.second.size() == indiv->fit().objs().size());\n        for (size_t i = 0; i < Params::pop::eps_size(); ++i)\n          e.second[i] =\n            ceil((indiv->fit().obj(i) - Params::pop::min_fit(i)) / Params::pop::eps(i));\n        return e;\n      }\n\n      /// compute a squared euclidean distance between a's fitness and\n      /// a's identification vector\n      float dist_to_id(const elite_t& a) const {\n        float res = 0;\n        assert(a.first->fit().objs().size() == a.second.size());\n        for (unsigned i = 0; i < a.first->fit().objs().size(); ++i)\n          res += powf(a.first->fit().obj(i) - a.second[i], 2.0);\n        return res;\n      }\n\n      /// make the identification vector and add to the archive / elite\n      /// list\n      void add_to_archive(indiv_t indiv) {\n        dbg::out(dbg::info, \"epsmoea\")<<\"add_to_archive :\"<<indiv_str(indiv)<<std::endl;\n        pop_e.push_back(make_identification_vector(indiv));\n      }\n\n      /// debug function\n      std::string indiv_str(indiv_t indiv) {\n        std::string s = \"\";\n        for (size_t i = 0; i < indiv->fit().objs().size(); ++i)\n          s += boost::lexical_cast<std::string>(indiv->fit().obj(i)) + \" \";\n        return s;\n      }\n\n    };\n  }\n}\n#endif\n\n\n", "meta": {"hexsha": "5cdbc32b4b6115a67ede9d3c363f5467ebb55c48", "size": 11701, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sferes/sferes/ea/eps_moea.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/ea/eps_moea.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/ea/eps_moea.hpp", "max_forks_repo_name": "Evolving-AI-Lab/innovation-engine", "max_forks_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-11-15T01:52:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-11T23:42:58.000Z", "avg_line_length": 33.0536723164, "max_line_length": 92, "alphanum_fraction": 0.552089565, "num_tokens": 2987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.03904828937136209, "lm_q1q2_score": 0.010988408060267811}}
{"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_CRTP_BASE_MATRIX_INCLUDE\n#define MTL_CRTP_BASE_MATRIX_INCLUDE\n\n#include <iostream>\n#include <algorithm>\n#include <boost/mpl/bool.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/matrix_bracket.hpp>\n#include <boost/numeric/mtl/operation/copy.hpp>\n#include <boost/numeric/mtl/operation/mult.hpp>\n#include <boost/numeric/mtl/operation/right_scale_inplace.hpp>\n#include <boost/numeric/mtl/operation/divide_by_inplace.hpp>\n#include <boost/numeric/mtl/matrix/all_mat_expr.hpp>\n#include <boost/numeric/mtl/matrix/diagonal_setup.hpp>\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/eval_dense.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/utility/iset.hpp>\n#include <boost/numeric/mtl/operation/mult_assign_mode.hpp>\n#include <boost/numeric/mtl/operation/compute_factors.hpp>\n#include <boost/numeric/mtl/operation/column_in_matrix.hpp>\n#include <boost/numeric/mtl/operation/row_in_matrix.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#ifdef MTL_WITH_INITLIST\n# include <initializer_list>\n#endif\n\nnamespace mtl { namespace matrix {\n\ntemplate <typename Source, typename Matrix>\nstruct crtp_assign \n{\n    Matrix& operator()(const Source& source, Matrix& matrix)\n    {\n\treturn assign(source, matrix, typename ashape::ashape<Source>::type());\n    }\nprivate:\n    /// Assign scalar to a matrix by setting the matrix to a multiple of unity matrix\n    /** Uses internally \\sa diagonal_setup, for details see there. **/\n    Matrix& assign(const Source& source, Matrix& matrix, ashape::scal)\n    {\n\tvampir_trace<3055> tracer;\n\tMTL_DEBUG_THROW_IF(num_rows(matrix) * num_cols(matrix) == 0, \n\t\t\t   range_error(\"Trying to initialize a 0 by 0 matrix with a value\"));\n\tdiagonal_setup(matrix, source);\n\treturn matrix;\n    }\n\n    /// Assign matrix expressions by copying except for some special expressions\n    Matrix& assign(const Source& source, Matrix& matrix, typename ashape::ashape<Matrix>::type)\n    {\n\tvampir_trace<3056> tracer;\n\t// Self-assignment between different types shouldn't happen.\t\n\tmatrix.checked_change_resource(source);\n\tmatrix_copy(source, matrix);\n\treturn matrix;\n    }\n};\n\n\n\n/// Assign sum by assigning first argument and adding second\n/*  Note that this is more special then assigning arbitrary expressions including matrices itself\n    because mat_mat_plus_expr <E1, E2> is a derived class from mat_expr < MatrixSrc >. **/\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_assign<mat_mat_plus_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_plus_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3056> tracer;\n\tmatrix.checked_change_resource(src.first);\n\tmatrix= src.first;\n\treturn matrix+= src.second;\n    }\n};\n\n/// Assign difference by assigning first argument and subtracting second\n/*  Note that this is more special then assigning arbitrary expressions including matrices itself\n    because mat_mat_minus_expr <E1, E2> is a derived class from mat_expr < MatrixSrc >. **/\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_assign<mat_mat_minus_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_minus_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3057> tracer;\n\tmatrix.checked_change_resource(src.first);\n\tmatrix= src.first;\n\treturn matrix-= src.second;\n    }\n};\n\n/// Assign product by calling mult\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_assign<mat_mat_times_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_times_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<4012> tracer;\n\toperation::compute_factors<Matrix, mat_mat_times_expr<E1, E2> > factors(src);\n\tmatrix.checked_change_resource(factors.first, factors.second);\n\tmult(factors.first, factors.second, matrix);\n\treturn matrix;\n    }\n}; \n\n\n/// Assign element-wise product \ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_assign<mat_mat_ele_times_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_ele_times_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3028> tracer;\n\toperation::compute_factors<Matrix, mat_mat_ele_times_expr<E1, E2> > factors(src);\n\tmatrix.checked_change_resource(factors.first);\n\tmatrix= factors.first;\n\treturn matrix.ele_rscale(factors.second);\n    }\n}; \n\n\n\n/// Assign c-style 2D-array, because it's easier to initialize.\ntemplate <typename Value, unsigned Rows, unsigned Cols, typename Matrix>\nstruct crtp_assign<Value[Rows][Cols], Matrix>\n{\n    Matrix& operator()(const Value src[Rows][Cols], Matrix& matrix)\n    {\n\tvampir_trace<3059> tracer;\n\ttypedef typename Collection<Matrix>::size_type size_type;\n\n\tmatrix.checked_change_dim(Rows, Cols);\n\tinserter<Matrix>  ins(matrix, matrix.dim2());\n\t\n\tfor (size_type r= 0; r < Rows; ++r)\n\t    for (size_type c= 0; c < Cols; ++c)\n\t\tins(r, c) << src[r][c];\n\treturn matrix;\n    }\n};\n\n#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n    /// Constructor for initializer list \\p values \n    template <typename Value2, typename Matrix>\n    struct crtp_assign<std::initializer_list<std::initializer_list<Value2> >, Matrix>\n    {\n\tMatrix& operator()(std::initializer_list<std::initializer_list<Value2> > values, Matrix& matrix)\n\t{\n\t    typedef typename Collection<Matrix>::size_type size_type;\n\t    size_type nr= values.size(), nc= nr > 0? values.begin()->size() : 0;\n\t    matrix.checked_change_dim(nr, nc);\n\t    inserter<Matrix>  ins(matrix, matrix.dim2());\n\n\t    size_t r= 0;\n\t    for (auto l : values) {\n\t\tsize_t c= 0;\t    \n\t\tMTL_THROW_IF(l.size() != nc, logic_error(\"All sub-lists must have same size!\"));\n\t\tfor (auto v : l)\n\t\t    ins(r, c++) << v;\n\t\tr++;\n\t    }\n\t    return matrix;\n\t}\n    };\n#endif\n\n\ntemplate <typename Vector, typename Matrix>\nstruct crtp_assign<multi_vector<Vector>, Matrix>\n{\n    Matrix& operator()(const multi_vector<Vector>& src, Matrix& matrix)\n    {\n\tvampir_trace<3060> tracer;\n\ttypedef typename Collection<Matrix>::size_type size_type;\n\n\tmatrix.checked_change_resource(src);\n\t// del checked_change_dim(num_rows(src), num_cols(src));\n\tinserter<Matrix>  ins(matrix);\n\t\n\tfor (size_type r= 0; r < num_rows(src); ++r)\n\t    for (size_type c= 0; c < num_cols(src); ++c)\n\t\tins(r, c) << src[r][c];\n\treturn matrix;\n    }\n};\n\n\n/// Assign content of a file to the matrix\ntemplate <typename IFStream, typename OFStream, typename Matrix>\nstruct crtp_assign<io::matrix_file<IFStream, OFStream>, Matrix>\n{\n    Matrix& operator()(const io::matrix_file<IFStream, OFStream>& file, Matrix& matrix)\n    {\n\tvampir_trace<3029> tracer;\n\tIFStream stream(file.file_name().c_str());\n\tstream >> matrix;\n\treturn matrix;\n    }\n};\n\t\n/// Assign-add matrix expressions by incrementally copying except for some special expressions\ntemplate <typename Source, typename Matrix>\nstruct crtp_plus_assign \n{\n    Matrix& operator()(const Source& source, Matrix& matrix)\n    {\n\tvampir_trace<3030> tracer;\n\treturn assign(source, matrix, typename ashape::ashape<Source>::type());\n    }\n  private:\n    Matrix& assign(const Source& source, Matrix& matrix, typename ashape::ashape<Matrix>::type)\n    {\n\tmatrix_copy_plus(source, matrix);\n\treturn matrix;\n    }\n};\n\n/// Assign-add sum by adding both arguments\n/** Note that this is more special then assigning arbitrary expressions including matrices itself\n\tbecause mat_mat_plus_expr <E1, E2> is a derived class from \n\tmat_expr < MatrixSrc >. **/\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_plus_assign<mat_mat_plus_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_plus_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3030> tracer;\n\tmatrix+= src.first;\n\treturn matrix+= src.second;\n    }\n};\n\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_plus_assign<mat_mat_minus_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_minus_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3030> tracer;\n\tmatrix+= src.first;\n\treturn matrix-= src.second;\n    }\n};\n\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_plus_assign<mat_mat_ele_times_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_ele_times_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3030> tracer;\n\tMatrix Prod(ele_prod(src.first, src.second));\n\treturn matrix+= Prod;\n    }\n};\n\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_plus_assign<mat_mat_times_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_times_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3030> tracer;\n\toperation::compute_factors<Matrix, mat_mat_times_expr<E1, E2> > factors(src);\n\tgen_mult(factors.first, factors.second, matrix, assign::plus_sum(), \n\t\t tag::flat<tag::matrix>(), tag::flat<tag::matrix>(), tag::flat<tag::matrix>());\n\treturn matrix;\n    }\n};\n\n\n/// Assign-subtract matrix expressions by decrementally copying except for some special expressions\ntemplate <typename Source, typename Matrix>\nstruct crtp_minus_assign \n{\n    Matrix& operator()(const Source& source, Matrix& matrix)\n    {\n\tvampir_trace<3031> tracer;\n\treturn assign(source, matrix, typename ashape::ashape<Source>::type());\n    }\nprivate:\n    Matrix& assign(const Source& source, Matrix& matrix, typename ashape::ashape<Matrix>::type)\n    {\n\tmatrix_copy_minus(source, matrix);\n\treturn matrix;\n    }\n};\n\n/// Assign-subtract sum by adding both arguments\n/** Note that this is more special then assigning arbitrary expressions including matrices itself\n\tbecause mat_mat_plus_expr <E1, E2> is a derived class from \n\tmat_expr < MatrixSrc >. **/\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_minus_assign<mat_mat_plus_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_plus_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3031> tracer;\n\tmatrix-= src.first;\n\treturn matrix-= src.second;\n    }\n};\n\n/// Assign-subtracting difference by subtracting first argument and adding the second one\n/** Note that this is more special then assigning arbitrary expressions including matrices itself\n\tbecause mat_mat_minus_expr <E1, E2> is a derived class from \n\tmat_expr < MatrixSrc >. **/\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_minus_assign<mat_mat_minus_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_minus_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3031> tracer;\n\tmatrix-= src.first;\n\treturn matrix+= src.second;\n    }\n};\n\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_minus_assign<mat_mat_ele_times_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_ele_times_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3031> tracer;\n\tMatrix Prod(ele_prod(src.first, src.second));\n\treturn matrix-= Prod;\n    }\n};\n\n/// Assign-subtract product by calling gen_mult\n/** Note that this does not work for arbitrary expressions. **/\ntemplate <typename E1, typename E2, typename Matrix>\nstruct crtp_minus_assign<mat_mat_times_expr<E1, E2>, Matrix> \n{\n    Matrix& operator()(const mat_mat_times_expr<E1, E2>& src, Matrix& matrix)\n    {\n\tvampir_trace<3031> tracer;\n\toperation::compute_factors<Matrix, mat_mat_times_expr<E1, E2> > factors(src);\n\tgen_mult(factors.first, factors.second, matrix, assign::minus_sum(), tag::flat<tag::matrix>(), tag::flat<tag::matrix>(), tag::flat<tag::matrix>());\n\treturn matrix;\n    }\n};\n\n\n\n/// Base class to provide matrix assignment operators generically \ntemplate <typename Matrix, typename ValueType, typename SizeType>\nstruct crtp_matrix_assign\n{\nprivate:\n\n    // For (compatible) dense matrices do a loop over all entries\n    template <typename Source>\n    Matrix& density_assign(const Source& src, boost::mpl::true_)\n    {\n\tvampir_trace<3032> tracer;\n\t// typedef typename Collection<Source>::size_type size_type;\n\ttypedef unsigned size_type;\n\n\t// std::cout << \"Dense assignment\\n\";\n\tchecked_change_resource(src);\n\n\tMatrix& matrix= static_cast<Matrix&>(*this);\n\tfor (size_type r= 0; r < num_rows(matrix); ++r)\n\t    for (size_type c= 0; c < num_cols(matrix); ++c)\n\t\tmatrix[r][c]= src[r][c];\n\treturn matrix;\n    }\n\n    // If sparse matrices are involved evaluate step-wise (or assignment from scalar)\n    template <typename Source>\n    Matrix& density_assign(const Source& src, boost::mpl::false_)\n    {\n\t// std::cout << \"Sparse assignment\\n\";\n\treturn crtp_assign<Source, Matrix>()(src, static_cast<Matrix&>(*this));\n    }\n\n    \n    // For (compatible) dense matrices do a loop over all entries\n    template <typename Source>\n    Matrix& density_plus_assign(const Source& src, boost::mpl::true_)\n    {\n\tvampir_trace<3033> tracer;\n\t// typedef typename Collection<Source>::size_type size_type;\n\ttypedef unsigned size_type;\n\n\t// std::cout << \"Dense assignment\\n\";\n\tchecked_change_resource(src);\n\t// del checked_change_dim(num_rows(src), num_cols(src));\n\n\tMatrix& matrix= static_cast<Matrix&>(*this);\n\tfor (size_type r= 0; r < num_rows(matrix); ++r)\n\t    for (size_type c= 0; c < num_cols(matrix); ++c)\n\t\tmatrix[r][c]+= src[r][c];\n\treturn matrix;\n    }\n\n    // If sparse matrices are involved evaluate step-wise (or assignment from scalar)\n    template <typename Source>\n    Matrix& density_plus_assign(const Source& src, boost::mpl::false_)\n    {\n\t// std::cout << \"Sparse assignment\\n\";\n\treturn crtp_plus_assign<Source, Matrix>()(src, static_cast<Matrix&>(*this));\n    }\n\n    // For (compatible) dense matrices do a loop over all entries\n    template <typename Source>\n    Matrix& density_minus_assign(const Source& src, boost::mpl::true_)\n    {\n\tvampir_trace<3034> tracer;\n\t// typedef typename Collection<Source>::size_type size_type;\n\ttypedef unsigned size_type;\n\n\t// std::cout << \"Dense assignment\\n\";\n\tchecked_change_resource(src);\n\n\tMatrix& matrix= static_cast<Matrix&>(*this);\n\tfor (size_type r= 0; r < num_rows(matrix); ++r)\n\t    for (size_type c= 0; c < num_cols(matrix); ++c)\n\t\tmatrix[r][c]-= src[r][c];\n\treturn matrix;\n    }\n\n    // If sparse matrices are involved evaluate step-wise (or assignment from scalar)\n    template <typename Source>\n    Matrix& density_minus_assign(const Source& src, boost::mpl::false_)\n    {\n\t// std::cout << \"Sparse assignment\\n\";\n\treturn crtp_minus_assign<Source, Matrix>()(src, static_cast<Matrix&>(*this));\n    }\n\n    // For (compatible) dense matrices do a loop over all entries\n    template <typename Source>\n    Matrix& density_ele_rscale(const Source& src, boost::mpl::true_)\n    {\n\tvampir_trace<3035> tracer;\n\t// typedef typename Collection<Source>::size_type size_type;\n\ttypedef unsigned size_type;\n\n\t// std::cout << \"Dense assignment\\n\";\n\tchecked_change_resource(src);\n\t// del checked_change_dim(num_rows(src), num_cols(src));\n\n\tMatrix& matrix= static_cast<Matrix&>(*this);\n\tfor (size_type r= 0; r < num_rows(matrix); ++r)\n\t    for (size_type c= 0; c < num_cols(matrix); ++c)\n\t\tmatrix[r][c]*= src[r][c];\n\treturn matrix;\n    }\n\n    // If sparse matrices are involved evaluate step-wise (or assignment from scalar)\n    template <typename Factor>\n    Matrix& density_ele_rscale(const Factor& alpha, boost::mpl::false_)\n    {\n\t// std::cout << \"Sparse assignment\\n\";\n\tmatrix_copy_ele_times(alpha, static_cast<Matrix&>(*this));\n\treturn static_cast<Matrix&>(*this);\n    }\n\n  public:\n\n    /// Check wether source and target have compatible resources, generalization of check_dim\n    /** For expressions like A= B + C, A can be set to the size of B and C if still is 0 by 0. **/\n    template <typename Src>\n    void check_resource(const Src& src) const \n    {\tcheck_resource(src, typename mtl::traits::category<Matrix>::type());    }\n\n    // Default case just check_dim\n    template <typename Src>\n    void check_resource(const Src& src, tag::universe) const \n    {\tcheck_dim(num_rows(src), num_cols(src));    }\n\n    /// Check wether source and target have compatible resources and wether target has already resources\n    /** For expressions like A+= B + C, A must be already larger then 0 by 0 and compatible to B and C. **/\n    //  Generalization with 2 arguments might be needed (check rows from first and columns from second)\n    template <typename Src>\n    void check_ready_resource(const Src& src) const \n    {\n\tMTL_DEBUG_THROW_IF(num_rows(src) * num_cols(src) == 0, need_nonempty());\n\tcheck_resource(src);\n    }\n\n    /// Check wether source and target have compatible resources and adapt empty target\n    /** For expressions like A= B + C, A can be set to the size of B and C if still is 0 by 0. **/\n    template <typename Src>\n    void checked_change_resource(const Src& src) \n    {\tchecked_change_resource(src, src);   }\n\n    /// Check whether source and target have compatible resources and adapt empty target\n    /** For expressions like A= B + C, A can be set to the size of B and C if still is 0 by 0. **/\n    template <typename Src1, typename Src2>\n    void checked_change_resource(const Src1& src1, const Src2& src2)\n    {   checked_change_resource_aux(src1, src2, typename mtl::traits::category<Matrix>::type());    }\n\n    template <typename Src1, typename Src2>\n    void checked_change_resource_aux(const Src1& src1, const Src2& src2, tag::universe) \n    {   checked_change_dim(num_rows(src1), num_cols(src2));  }\n\n\n    /// Check whether matrix sizes are compatible or if matrix is 0 by 0 change it to r by c.\n    /** Deprecated, superseded by checked_change_resource. **/ \n    void checked_change_dim(SizeType r, SizeType c)\n    {\n\tMatrix& matrix= static_cast<Matrix&>(*this);\n\tmatrix.check_dim(r, c);\n\tmatrix.change_dim(r, c);\n    }\n\n    /// Templated assignment implemented by functor to allow for partial specialization\n    // Despite there is only an untemplated assignment and despite the disable_if MSVC whines about ambiguity :-!\n    // Scalar assignment is also taking out because it has another return type\n    template <typename Source>\n    typename boost::disable_if_c<boost::is_same<Matrix, Source>::value \n                                   || boost::is_same<typename ashape::ashape<Source>::type, ashape::scal>::value,\n\t\t\t\t Matrix&>::type\n    operator=(const Source& src)\n    {\n\treturn density_assign(src, boost::mpl::bool_< boost::is_same<typename ashape::ashape<Matrix>::type, \n\t\t\t                                             typename ashape::ashape<Source>::type>::value \n\t\t\t                              && mtl::traits::eval_dense< mat_mat_asgn_expr<Matrix, Source> >::value >());\n    }\n\n    // Helper type for assigning scalars to handle both A= a; and A= a, b, c;\n    template <typename Source>\n    struct scalar_assign \n    {\n\tscalar_assign(Source src, Matrix& matrix) \n\t  : src(src), with_comma(false), r(0), c(0), matrix(matrix), ins(matrix, 1) {}\n\n\t~scalar_assign()\n\t{\n\t    vampir_trace<3047> tracer;\n\t    if (with_comma) {\n\t\tMTL_DEBUG_THROW_IF(r != num_rows(matrix), incompatible_size(\"Not all matrix entries initialized!\"));\n\t    } else {\n\t\tusing std::min;\n\t\tif (src == math::zero(src)) // it is already set to zero\n\t\t    return;\n\t\t// Otherwise set diagonal (if square)\n\t\tfor (SizeType i= 0, n= min(num_rows(matrix), num_cols(matrix)); i < n; i++)\n\t\t    ins[i][i] << src;\n\t    }\n\t}\n\n\ttemplate <typename ValueSource>\n\tscalar_assign& operator, (ValueSource val)\n\t{\n\t    if (!with_comma) {\n\t\twith_comma= true;\n\t\tassert(r == 0 && c == 0);\n\t\tins[r][c++] << src; // We haven't set v[0] yet\n\t\tif (c == num_cols(matrix)) \n\t\t    c= 0, r++;\n\t    }\n\t    ins[r][c++] << val;\n\t    if (c == num_cols(matrix)) \n\t\tc= 0, r++;\n\t    return *this;\n\t}\n\n\tSource         src;\n\tbool           with_comma;\n\tSizeType       r, c;\n\tMatrix&        matrix;\n\tinserter<Matrix> ins;\n    };\n\n    template <typename Source>\n    typename boost::enable_if<boost::is_same<typename ashape::ashape<Source>::type, ashape::scal>, \n\t\t\t      scalar_assign<Source> >::type\n    operator=(Source src)\n    {\n\tMatrix& matrix= static_cast<Matrix&>(*this);\n\tMTL_DEBUG_THROW_IF(num_rows(matrix) * num_cols(matrix) == 0, \n\t\t\t   range_error(\"Trying to initialize a 0 by 0 matrix with a value\"));\n\tset_to_zero(matrix);\n\treturn scalar_assign<Source>(src, static_cast<Matrix&>(*this));\n    }\n\n    template <typename Source>\n    Matrix& operator+=(const Source& src)\n    {\n\treturn density_plus_assign(src, mtl::traits::eval_dense< mat_mat_asgn_expr<Matrix, Source> >());\n    }\n    \n    template <typename Source>\n    Matrix& operator-=(const Source& src)\n    {\n\treturn density_minus_assign(src, mtl::traits::eval_dense< mat_mat_asgn_expr<Matrix, Source> >());\n    }\n    \n    /// Scale matrix (in place) with scalar value or other matrix\n    template <typename Factor>\n    Matrix& operator*=(const Factor& alpha)\n    {\n\tright_scale_inplace(static_cast<Matrix&>(*this), alpha);\n\treturn static_cast<Matrix&>(*this);\n    }\n\n    // Element-wise scaling from right (i.e. like *= as elementwise)\n    template <typename Factor>\n    Matrix& ele_rscale(const Factor& alpha)\n    {\n\treturn density_ele_rscale(alpha, mtl::traits::eval_dense< mat_mat_asgn_expr<Matrix, Factor> >());\n    }\n\n    /// Divide matrix (in place) by scalar value\n    // added by Hui Li\n    template <typename Factor>\n    Matrix& operator/=(const Factor& alpha)\n    {\n\tdivide_by_inplace(static_cast<Matrix&>(*this), alpha);\n\treturn static_cast<Matrix&>(*this);\n    }\n};\n\n\n\ntemplate <typename Matrix, typename ValueType, typename SizeType>\nstruct const_crtp_matrix_bracket\n{    \n    template <typename T>\n    typename boost::disable_if_c<boost::is_same<T, mtl::irange>::value || boost::is_same<T, mtl::iset>::value,\n\t\t\t\t operations::bracket_proxy<Matrix, const Matrix&, ValueType> >::type\n    operator[] (const T& row) const\n    {\n\treturn operations::bracket_proxy<Matrix, const Matrix&, ValueType>(static_cast<const Matrix&>(*this), row);\n    }\n\n    // Compiler error (later) if no sub_matrix function (or row vector resp.) available\n    template <typename T>\n    typename boost::enable_if<boost::is_same<T, mtl::irange>, operations::range_bracket_proxy<Matrix, const Matrix&, const Matrix> >::type\n    operator[] (const T& row_range) const\n    {\n\treturn operations::range_bracket_proxy<Matrix, const Matrix&, const Matrix>(static_cast<const Matrix&>(*this), row_range);\n    }\n\n    operations::set_bracket_proxy<Matrix, const Matrix&, const Matrix>\n    operator[] (const iset& row_set) const\n    {\n\treturn operations::set_bracket_proxy<Matrix, const Matrix&, const Matrix>(static_cast<const Matrix&>(*this), row_set);\n    }\n};\n\ntemplate <typename Matrix, typename ValueType, typename SizeType>\nstruct crtp_matrix_bracket \n{    \n    operations::bracket_proxy<Matrix, const Matrix&, const ValueType&>\n    operator[] (SizeType row) const\n    {\n        return operations::bracket_proxy<Matrix, const Matrix&, const ValueType&>(static_cast<const Matrix&>(*this), row);\n    }\n\n    template <typename T>\n    typename boost::disable_if_c<boost::is_same<T, mtl::irange>::value || boost::is_same<T, mtl::iset>::value, \n\t\t\t       operations::bracket_proxy<Matrix, Matrix&, ValueType&> >::type\n    // operations::bracket_proxy<Matrix, Matrix&, ValueType&>\n    operator[] (const T& row)\n    {\n        return operations::bracket_proxy<Matrix, Matrix&, ValueType&>(static_cast<Matrix&>(*this), row);\n    }\n\n    // Compiler error (later) if no sub_matrix function available\n    operations::range_bracket_proxy<Matrix, const Matrix&, const Matrix>\n    operator[] (const irange& row_range) const\n    {\n\treturn operations::range_bracket_proxy<Matrix, const Matrix&, const Matrix>(static_cast<const Matrix&>(*this), row_range);\n    }\n\n    // Compiler error (later) if no sub_matrix function available\n    template <typename T>\n    typename boost::enable_if<boost::is_same<T, mtl::irange>, operations::range_bracket_proxy<Matrix, Matrix&, Matrix> >::type\n    // operations::range_bracket_proxy<Matrix, Matrix&, Matrix>\n    operator[] (const T& row_range)\n    {\n\treturn operations::range_bracket_proxy<Matrix, Matrix&, Matrix>(static_cast<Matrix&>(*this), row_range);\n    }\n\n    operations::set_bracket_proxy<Matrix, const Matrix&, const Matrix>\n    operator[] (const iset& row_set) const\n    {\n\treturn operations::set_bracket_proxy<Matrix, const Matrix&, const Matrix>(static_cast<const Matrix&>(*this), row_set);\n    }\n};\n\ntemplate <typename Matrix, typename ValueType, typename SizeType>\nstruct crtp_matrix_lvalue \n{ \n    // Function must be overwritten by Matrix if m(row, col) does not return a reference\n    ValueType& lvalue(SizeType row, SizeType col)\n    {\n\treturn static_cast<Matrix&>(*this)(row, col);\n    }   \n};\n\ntemplate <typename Matrix, typename ValueType, typename SizeType>\nstruct const_crtp_base_matrix\n  : public const_crtp_matrix_bracket<Matrix, ValueType, SizeType>\n{};\n\ntemplate <typename Matrix, typename ValueType, typename SizeType>\nstruct mutable_crtp_base_matrix \n  : public crtp_matrix_bracket<Matrix, ValueType, SizeType>,\n    public crtp_matrix_assign<Matrix, ValueType, SizeType>\n{};\n\ntemplate <typename Matrix, typename ValueType, typename SizeType>\nstruct crtp_base_matrix \n  : boost::mpl::if_<boost::is_const<Matrix>,\n\t\t    const_crtp_base_matrix<Matrix, ValueType, SizeType>,\n\t\t    mutable_crtp_base_matrix<Matrix, ValueType, SizeType>\n                   >::type\n{};\n\n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_CRTP_BASE_MATRIX_INCLUDE\n", "meta": {"hexsha": "b8436d73f75d64d69e1166673053c22216c390b9", "size": 25835, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/matrix/crtp_base_matrix.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/matrix/crtp_base_matrix.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/matrix/crtp_base_matrix.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": 35.0067750678, "max_line_length": 148, "alphanum_fraction": 0.7067544029, "num_tokens": 6551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.0280075184762953, "lm_q1q2_score": 0.010988381417830609}}
{"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_BAYES_OPT_BO_BASE_HPP\n#define LIMBO_BAYES_OPT_BO_BASE_HPP\n\n#include <exception>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n// Quick hack for definition of 'I' in <complex.h>\n#undef I\n#include <boost/fusion/include/accumulate.hpp>\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/fusion/include/vector.hpp>\n#include <boost/parameter.hpp>\n#define BOOST_NO_SCOPED_ENUMS\n#include <boost/filesystem.hpp>\n\n#include <Eigen/Core>\n\n// we need everything to have the defaults\n#include <limbo/acqui/ucb.hpp>\n#include <limbo/init/random_sampling.hpp>\n#include <limbo/kernel/exp.hpp>\n#include <limbo/mean/data.hpp>\n#include <limbo/model/gp.hpp>\n#include <limbo/stat/aggregated_observations.hpp>\n#include <limbo/stat/console_summary.hpp>\n#include <limbo/stat/samples.hpp>\n#include <limbo/stop/chain_criteria.hpp>\n#include <limbo/stop/max_iterations.hpp>\n#include <limbo/tools/macros.hpp>\n#include <limbo/tools/math.hpp>\n#include <limbo/tools/sys.hpp>\n\nnamespace limbo {\n    namespace defaults {\n        struct bayes_opt_bobase {\n            BO_PARAM(bool, stats_enabled, true);\n            BO_PARAM(bool, bounded, true);\n        };\n    }\n    template <typename BO, typename AggregatorFunction>\n    struct RefreshStat_f {\n        RefreshStat_f(BO& bo, const AggregatorFunction& afun)\n            : _bo(bo), _afun(afun) {}\n\n        BO& _bo;\n        const AggregatorFunction& _afun;\n\n        template <typename T>\n        void operator()(T& x) const { x(_bo, _afun); }\n    };\n\n    struct FirstElem {\n        using result_type = double;\n        double operator()(const Eigen::VectorXd& x) const\n        {\n            return x(0);\n        }\n    };\n    class EvaluationError : public std::exception {\n    };\n\n    // we use optimal named template parameters\n    // see:\n    // http://www.boost.org/doc/libs/1_55_0/libs/parameter/doc/html/index.html#parameter-enabled-class-templates\n\n    BOOST_PARAMETER_TEMPLATE_KEYWORD(initfun)\n    BOOST_PARAMETER_TEMPLATE_KEYWORD(acquifun)\n    BOOST_PARAMETER_TEMPLATE_KEYWORD(modelfun)\n    BOOST_PARAMETER_TEMPLATE_KEYWORD(statsfun)\n    BOOST_PARAMETER_TEMPLATE_KEYWORD(stopcrit)\n\n    namespace bayes_opt {\n\n        using bobase_signature = boost::parameter::parameters<boost::parameter::optional<tag::statsfun>,\n            boost::parameter::optional<tag::initfun>,\n            boost::parameter::optional<tag::acquifun>,\n            boost::parameter::optional<tag::stopcrit>,\n            boost::parameter::optional<tag::modelfun>>;\n\n        // clang-format off\n        template <class Params,\n          class A1 = boost::parameter::void_,\n          class A2 = boost::parameter::void_,\n          class A3 = boost::parameter::void_,\n          class A4 = boost::parameter::void_,\n          class A5 = boost::parameter::void_,\n          class A6 = boost::parameter::void_>\n        // clang-format on\n        /**\n        \\rst\n\n        Base class for Bayesian optimizers\n\n        Parameters:\n          - ``bool Params::bayes_opt_bobase::stats_enabled``: activate / deactivate the statistics\n\n        This class is templated by several types with default values (thanks to boost::parameters).\n\n        +----------------+---------+---------+---------------+\n        |type            |typedef  | argument| default       |\n        +================+=========+=========+===============+\n        |init. func.     |init_t   | initfun | RandomSampling|\n        +----------------+---------+---------+---------------+\n        |model           |model_t  | modelfun| GP<...>       |\n        +----------------+---------+---------+---------------+\n        |acquisition fun.|aqui_t   | acquifun| GP_UCB        |\n        +----------------+---------+---------+---------------+\n        |statistics      | stat_t  | statfun | see below     |\n        +----------------+---------+---------+---------------+\n        |stopping crit.  | stop_t  | stopcrit| MaxIterations |\n        +----------------+---------+---------+---------------+\n\n        \\endrst\n\n        For GP, the default value is: ``model::GP<Params, kf_t, mean_t, opt_t>>``,\n          - with ``kf_t = kernel::SquaredExpARD<Params>``\n          - with ``mean_t = mean::Data<Params>``\n          - with ``opt_t = model::gp::KernelLFOpt<Params>``\n\n         (meaning: kernel with automatic relevance determination and mean equals to the mean of the input data, that is, center the data automatically)\n\n        For Statistics, the default value is: ``boost::fusion::vector<stat::Samples<Params>, stat::AggregatedObservations<Params>, stat::ConsoleSummary<Params>>``\n\n        Example of customization:\n          - ``using Kernel_t = kernel::MaternFiveHalves<Params>;``\n          - ``using Mean_t = mean::Data<Params>;``\n          - ``using GP_t = model::GP<Params, Kernel_t, Mean_t>;``\n          - ``using Acqui_t = acqui::UCB<Params, GP_t>;``\n          - ``bayes_opt::BOptimizer<Params, modelfun<GP_t>, acquifun<Acqui_t>> opt;``\n\n        */\n        class BoBase {\n        public:\n            using params_t = Params;\n            // defaults\n            struct defaults {\n                using init_t = init::RandomSampling<Params>; // 1\n                using model_t = model::GP<Params>; // 2\n                // WARNING: you have to specify the acquisition  function\n                // if you use a custom model\n                using acqui_t = acqui::UCB<Params, model_t>; // 3\n                using stat_t = boost::fusion::vector<stat::Samples<Params>, stat::AggregatedObservations<Params>, stat::ConsoleSummary<Params>>; // 4\n                using stop_t = boost::fusion::vector<stop::MaxIterations<Params>>; // 5\n            };\n\n            // extract the types\n            using args = typename bobase_signature::bind<A1, A2, A3, A4, A5, A6>::type;\n            using init_function_t = typename boost::parameter::binding<args, tag::initfun, typename defaults::init_t>::type;\n            using acquisition_function_t = typename boost::parameter::binding<args, tag::acquifun, typename defaults::acqui_t>::type;\n            using model_t = typename boost::parameter::binding<args, tag::modelfun, typename defaults::model_t>::type;\n            using Stat = typename boost::parameter::binding<args, tag::statsfun, typename defaults::stat_t>::type;\n            using StoppingCriteria = typename boost::parameter::binding<args, tag::stopcrit, typename defaults::stop_t>::type;\n\n            using stopping_criteria_t = typename boost::mpl::if_<boost::fusion::traits::is_sequence<StoppingCriteria>, StoppingCriteria, boost::fusion::vector<StoppingCriteria>>::type;\n            using stat_t = typename boost::mpl::if_<boost::fusion::traits::is_sequence<Stat>, Stat, boost::fusion::vector<Stat>>::type;\n\n            /// default constructor\n            BoBase() : _total_iterations(0) { _make_res_dir(); }\n\n            /// copy is disabled (dangerous and useless)\n            BoBase(const BoBase& other) = delete;\n            /// copy is disabled (dangerous and useless)\n            BoBase& operator=(const BoBase& other) = delete;\n\n            /// return true if the statitics are enabled (they can be disabled to avoid dumping data, e.g. for unit tests)\n            bool stats_enabled() const { return Params::bayes_opt_bobase::stats_enabled(); }\n\n            /// return the name of the directory in which results (statistics) are written\n            const std::string& res_dir() const { return _res_dir; }\n\n            /// return the vector of points of observations (observations can be multi-dimensional, hence the VectorXd) -- f(x)\n            const std::vector<Eigen::VectorXd>& observations() const { return _observations; }\n\n            /// return the list of the points that have been evaluated so far (x)\n            const std::vector<Eigen::VectorXd>& samples() const { return _samples; }\n\n            /// return the current iteration number\n            int current_iteration() const { return _current_iteration; }\n\n            int total_iterations() const { return _total_iterations; }\n\n            /// Add a new sample / observation pair\n            /// - does not update the model!\n            /// - we don't add NaN and inf observations\n            void add_new_sample(const Eigen::VectorXd& s, const Eigen::VectorXd& v)\n            {\n                if (tools::is_nan_or_inf(v))\n                    throw EvaluationError();\n                _samples.push_back(s);\n                _observations.push_back(v);\n            }\n\n            /// Evaluate a sample and add the result to the 'database' (sample / observations vectors) -- it does not update the model\n            template <typename StateFunction>\n            void eval_and_add(const StateFunction& seval, const Eigen::VectorXd& sample)\n            {\n                this->add_new_sample(sample, seval(sample));\n            }\n\n        protected:\n            template <typename StateFunction, typename AggregatorFunction>\n            void _init(const StateFunction& seval, const AggregatorFunction& afun, bool reset = true)\n            {\n                this->_current_iteration = 0;\n                if (reset) {\n                    this->_total_iterations = 0;\n                    this->_samples.clear();\n                    this->_observations.clear();\n                }\n\n                if (this->_total_iterations == 0)\n                    init_function_t()(seval, afun, *this);\n            }\n\n            template <typename BO, typename AggregatorFunction>\n            bool _stop(const BO& bo, const AggregatorFunction& afun) const\n            {\n                stop::ChainCriteria<BO, AggregatorFunction> chain(bo, afun);\n                return boost::fusion::accumulate(_stopping_criteria, false, chain);\n            }\n\n            template <typename BO, typename AggregatorFunction>\n            void _update_stats(BO& bo, const AggregatorFunction& afun)\n            { // not const, because some stat class\n                // modify the optimizer....\n                boost::fusion::for_each(_stat, RefreshStat_f<BO, AggregatorFunction>(bo, afun));\n            }\n\n            void _make_res_dir()\n            {\n                if (!Params::bayes_opt_bobase::stats_enabled())\n                    return;\n                _res_dir = tools::hostname() + \"_\" + tools::date() + \"_\" + tools::getpid();\n                boost::filesystem::path my_path(_res_dir);\n                boost::filesystem::create_directory(my_path);\n            }\n\n            std::string _res_dir;\n            int _current_iteration;\n            int _total_iterations;\n            stopping_criteria_t _stopping_criteria;\n            stat_t _stat;\n\n            std::vector<Eigen::VectorXd> _observations;\n            std::vector<Eigen::VectorXd> _samples;\n        };\n    }\n}\n\n#endif\n", "meta": {"hexsha": "f87bece842f8164192016867710be520eeb7486f", "size": 13099, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/bayes_opt/bo_base.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/bayes_opt/bo_base.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/bayes_opt/bo_base.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": 43.9563758389, "max_line_length": 184, "alphanum_fraction": 0.6163065883, "num_tokens": 2998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.0311438294107134, "lm_q1q2_score": 0.010968912218248736}}
{"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 \"heom/config.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/hermitian.hpp>\n\n#include \"heom/constants.hpp\"\n\nnamespace heom {\n\nnamespace bpo = ::boost::program_options;\nnamespace blas = ::boost::numeric::ublas;\n\nconfig::config(const std::string& config_file_name, bool parse_config)\n\t: config_base(config_file_name, false)\n{\n\tstd::stringstream observation_type_help;\n\tobservation_type_help << \"List of observations, pairs {(observation_type, filename), ...}. Valid observation_types are: \";\n\tparser::write_map_value_list(observation_type_names, observation_type_help);\n\n\t// generate help text for filtering strategy\n\tstd::stringstream filtering_strategy_help;\n\tfiltering_strategy_help << \"Strategy by which the hierarchy graph is filtered, one of: \";\n\tparser::write_map_value_list(filtering_strategy_names, filtering_strategy_help);\n\n\tstd::stringstream solver_stepper_type_help;\n\tsolver_stepper_type_help << \"Stepper type for numerical integration, one of: \";\n\tparser::write_map_value_list(num::stepper_type_names, solver_stepper_type_help);\n\n\t// initialise program options description\n\tdesc_.add_options()\n\t\t// program\n\t\t(\"program.observations\", bpo::value(&observations_)->required(), observation_type_help.str().c_str())\n\t\t(\"program.observe_steps\", bpo::value(&program_observe_steps_)->required(), \"Observe (i.e. generate ouput) every n steps.\")\n\n\t\t// filter\n\t\t(\"filtering.strategy\", bpo::value(&filtering_strategy_)->required(), filtering_strategy_help.str().c_str())\n\t\t(\"filtering.first_layer\", bpo::value(&filtering_first_layer_)->required(), \"Hierarchy layer where filtering begins.\")\n\n\t\t// solver\n\t\t(\"solver.stepper_type\", bpo::value(&solver_stepper_type_)->required(), solver_stepper_type_help.str().c_str())\n\t\t(\"solver.step_size\", bpo::value(&solver_step_size_)->required(), \"Simulation time step in [s]\")\n\t\t(\"solver.steps\", bpo::value(&solver_steps_)->required(), \"Simulated time [steps].\")\n\t\t(\"solver.track_flows\", bpo::value(&solver_track_flows_)->required(), \"Enable flow tracking [true or false].\")\n\t\t(\"solver.flow_filename\", bpo::value(&solver_flow_filename_)->required(), \"Output file for flow tracking.\")\n\n\t\t// system\n\t\t(\"system.sites\", bpo::value(&system_sites_)->required(), \"Number of sites in the input system.\")\n\t\t(\"system.ado_depth\", bpo::value(&system_ado_depth_)->required(), \"Depth of the hierarchy in the input system.\")\n\t\t(\"system.hamiltonian\", bpo::value(&system_hamiltonian_)->required(), \"Hamiltonian, complex matrix (num-sites x num-sites).\")\n\n\t\t// baths \n\t\t(\"baths.number\", bpo::value(&baths_number_)->required(), \"Total number of independent baths.\")\n\t\t(\"baths.max_per_site\", bpo::value(&baths_max_per_site_)->required(), \"Maximumexception number of baths coupled to a single site.\")\n\t\t(\"baths.coupling\", bpo::value(&baths_coupling_)->required(), \"Baths connections to sites (baths_max_persite x system_sites), -1 for n/a.\")\n\t\t(\"baths.lambda\", bpo::value(&baths_lambda_)->required(), \"Bath reorganization energies [lambda] for each bath [invcm].\")\n\t\t(\"baths.invnu\", bpo::value(&baths_invnu_)->required(), \"Bath correlation times [nu] for each bath [inv fs].\")\n\t\t(\"baths.Omega\", bpo::value(&baths_uppercase_omega_)->required(), \"Bath peak shift [Omega] for each bath [invcm].\")\n\t\t(\"baths.matsubaras\", bpo::value(&baths_matsubaras_)->required(), \"Number of Matsubara frequencies per bath.\")\n\t\t(\"baths.temperature\", bpo::value(&baths_temperature_)->required(), \"Temperature [K].\")\n\t\t;\n\n\tif (parse_config)\n\t\tparse(config_file_name);\n}\n\nvoid config::check()\n{\n\tconfig_base::check(); // call direct super-class' check()\n\n\t// observations\n\tif (observations().get().empty())\n\t\tthrow config_error(\"observations must at least contain one entry.\");\n\n\tDEBUG_ONLY( std::cout << \"heom::config_base::parse(): observations=\" << observations_ << std::endl; )\n\n\t// program_observe_steps\n\tif (!(program_observe_steps_ > 0))\n\t\tthrow config_error(\"program.observe_steps must be > 0\");\n\n\t// filtering_strategy\n\tif (filtering_strategy_ == filtering_strategy_t::NONE && filtering_first_layer_ != -1){\n\t\tthrow config_error(\"filtering.first_layer must be -1, because it has no effect for filtering_strategy = none\");\n\t}\n\n\t// filtering_first_layer\n\tif (filtering_strategy_ == filtering_strategy_t::SINGLE_EXCITATION && !(filtering_first_layer_ >= 0))\n\t\tthrow config_error(\"filtering.first_layer must be greater or equal to zero for filtering.strategy = single excitation filter\");\n\n\t// compare ADO cut off depth with filtering first layer\n\tif(system_ado_depth_ < filtering_first_layer_){\n\t\tthrow config_error(\"filtering.first_layer cannot be larger than system_ado_depth\");\n\t}\n\n\t// solver_step_size\n\tif (!(solver_step_size_ > 0.0)) // TODO: upper bound ?\n\t\tthrow config_error(\"solver.step_size must be > 0\");\n\n\t// solver_steps\n\tif (!(solver_steps_ > 0))\n\t\tthrow config_error(\"solver.steps must be > 0\");\n\n\tauto remainder_steps = solver_steps_ % program_observe_steps_;\n\tif (remainder_steps != 0)\n\t\tthrow config_error(\"there's a remainder when dividing solver.steps by program.observe_steps\");\n\n\t// solver_flow_filename\n\t// if (solver_track_flows_)\n\t// TODO: what happens if the path does not exist, what happens if the file exists already\n\n\t// system_sites\n\tif (!(system_sites_ > 0)) // TODO: upper bound\n\t\tthrow config_error(\"system.sites must be > 0\");\n\n\t// system_ado_depth\n\tif (!(system_ado_depth_ > 0)) // TODO: upper bound\n\t\tthrow config_error(\"system.ado_depth must be > 0\");\n\n\t// system_hamiltonian\n\tif (!(static_cast<int_t>(system_hamiltonian_.rows()) == system_sites_ &&\n\t      static_cast<int_t>(system_hamiltonian_.cols()) == system_sites_))\n\t\tthrow config_error(\"system.hamiltonien must be a system.sites by system.sites matrix\");\n\n\t// create boost ublas matrix from hamiltonian\n\tusing matrix_t = blas::matrix<complex_t>;\n\tmatrix_t hamiltonian_m(system_sites_, system_sites_);\n\tfor (int_t i = 0; i < system_sites_; ++i)\n\t\tfor (int_t j = 0; j < system_sites_; ++j)\n\t\t\thamiltonian_m(i,j) = system_hamiltonian_.at(i, j);\n\n\tif(!blas::is_hermitian(hamiltonian_m))\n\t\tthrow config_error(\"system.hamiltonien must be hermitian\");\n\n\t// baths_number\n\tif (!(baths_number_ > 0)) // TODO: upper bound\n\t\tthrow config_error(\"baths.number must be > 0\");\n\n\t// baths_max_per_site\n\tif (!(baths_max_per_site_ > 0)) // TODO: upper bound\n\t\tthrow config_error(\"baths.max_per_site must be > 0\");\n\tif (!(baths_max_per_site_ <= baths_number_)) // TODO: upper bound\n\t\tthrow config_error(\"baths.max_per_site must be <= baths.number\");\n\n\t// baths_coupling\n\tif (!(static_cast<int_t>(baths_coupling_.rows()) == system_sites_ &&\n\t      static_cast<int_t>(baths_coupling_.cols()) == baths_max_per_site_))\n\t\tthrow config_error(\"baths.coupling must be a system.sites by baths_max_per_site_ matrix\");\n\n\tfor (size_t i = 0; i < baths_coupling_.rows(); ++i)\n\t\tfor (size_t j = 0; j < baths_coupling_.cols(); ++j)\n\t\t\tif (!(baths_coupling_.at(i,j) < baths_number_))\n\t\t\t\tthrow config_error(\"baths.coupling values must between 0 and baths.number, or negative for non-coupling\");\n\n\t// baths_lambda\n\tif (!(static_cast<int_t>(baths_lambda_.size()) == baths_number_))\n\t\tthrow config_error(\"baths.lambda must have a length of baths.number\");\n\n\t// baths_invnu\n\tif (!(static_cast<int_t>(baths_invnu_.size()) == baths_number_))\n\t\tthrow config_error(\"baths.invnu must have a length of baths.number\");\n\tfor (size_t i = 0; i < baths_invnu_.size(); ++i)\n\t\tif (!(baths_invnu_.at(i) > 0)) // TODO: upper bound\n\t\t\tthrow config_error(\"baths.invnu must have values > 0\");\n\n\t// baths_uppercase_omage\n\tif (!(static_cast<int_t>(baths_uppercase_omega_.size()) == baths_number_))\n\t\tthrow config_error(\"baths.Omega must have a length of baths.number\");\n\t// TODO: if one Omega != 0, there must be a counterpart with same invnu, lambda, -Omega\n}\n\nvoid config::check_final()\n{\n\n}\n\nvoid config::post_process()\n{\n\tconfig_base::post_process(); // call direct super-class' post_process()\n\n\t// scale to SI units\n\tsystem_hamiltonian_.scale(constants::invcm_to_joule);\n\tbaths_lambda_.scale(constants::invcm_to_joule);\n\tbaths_uppercase_omega_.scale(constants::invcm_to_joule/constants::h_bar);\n\tbaths_invnu_.scale(1.0E-15); // TODO: maybe change input format to SI seconds\n}\n\n} // namespace heom\n", "meta": {"hexsha": "985de3182b7e4e3928dcd2934a6435656bc366a0", "size": 8443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dm-heom/src/heom/config.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/heom/config.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/heom/config.cpp", "max_forks_repo_name": "noma/dm-heom", "max_forks_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-04T15:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T15:16:40.000Z", "avg_line_length": 43.5206185567, "max_line_length": 140, "alphanum_fraction": 0.7362311974, "num_tokens": 2246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.032100705443805444, "lm_q1q2_score": 0.010965039199228253}}
{"text": "#include <iostream>\n#include <chrono>\n#include <cmath>\n#include <fstream>\n#include <stdlib.h>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n#include <cstdlib>\n#include <libconfig.h++>\n#include <vector>\n#include <netcdf>\n#include \"utils.h\"\n#include \"boris.h\"\n#include \"geometryCheck.h\"\n#include \"ionize.h\"\n#include \"recombine.h\"\n#include \"crossFieldDiffusion.h\"\n#include \"coulombCollisions.h\"\n#include \"thermalForce.h\"\n#include \"surfaceModel.h\"\n#include \"interp2d.hpp\"\n#include \"interpRateCoeff.hpp\"\n#include \"Particles.h\"\n#include \"Boundary.h\"\n#include \"curandInitialize.h\"\n#include \"spectroscopy.h\"\n#include \"fieldLineTrace.h\"\n#include \"history.h\"\n#include \"io.hpp\"\n#include \"hashGeom.h\"\n#include \"hashGeomSheath.h\"\n#include \"testRoutine.h\"\n#include \"testRoutineCuda.h\"\n#include \"boundaryInit.h\"\n#include \"array.h\"\n#include \"ompPrint.h\"\n\n#if USE_BOOST\n    #include <boost/timer/timer.hpp>\n    #include \"boost/filesystem.hpp\"\n#endif\n\n#ifdef __CUDACC__\n    #include <curand.h>\n    #include <curand_kernel.h>\n#endif\n\n#include <thrust/execution_policy.h>\n#include <thrust/sequence.h>\n#include <thrust/transform.h>\n#include <thrust/functional.h>\n\nusing namespace std;\nusing namespace libconfig;\n\n#if USE_BOOST\n    using namespace boost::timer;\n#endif\n\nusing namespace netCDF;\nusing namespace exceptions;\nusing namespace netCDF::exceptions;\n\nint main()\n{\n  //Prepare config files for import\n  Config cfg,cfg_geom;\n\n  //Parse and read input file\n  std::cout << \"Open configuration file gitrInput.cfg \" << std::endl;\n  try\n  {\n    cfg.readFile(\"gitrInput.cfg\");\n  }\n  catch(const FileIOException &fioex)\n  {\n    std::cerr << \"I/O error while reading file gitrInput.cfg\" << std::endl;\n    return(EXIT_FAILURE);\n  }\n  catch(const ParseException &pex)\n  {\n    std::cerr << \"Parse error at \" << pex.getFile() << \":\" << pex.getLine()\n              << \" - \" << pex.getError() << std::endl;\n    return(EXIT_FAILURE);\n  }\n  \n  // Parse and read geometry file\n  const char *geomFile; \n  if(cfg.lookupValue(\"geometry.fileString\", geomFile))\n  {\n    try\n    {\n      cfg_geom.readFile(geomFile);\n    }\n    catch(const FileIOException &fioex)\n    {\n      std::cerr << \"I/O error while reading GITR geometry file\" << std::endl;\n      return(EXIT_FAILURE);\n    }\n    catch(const ParseException &pex)\n    {\n      std::cerr << \"Parse error at \" << pex.getFile() << \":\" << pex.getLine()\n                << \" - \" << pex.getError() << std::endl;\n      return(EXIT_FAILURE);\n    }\n\n  }\n  \n  std::cout << \"Successfully staged input and geometry file \" << std::endl;\n  \n  //check binary compatibility with input file\n  #if CHECK_COMPATIBILITY>0\n    std::cout << \"Checking compatibility of compile flags with input file \" \n              << std::endl;\n   \n    const char *flags0[] = {\"flags.USE_CUDA\",\"flags.USEMPI\", \n              \"flags.USE_BOOST\",\"flags.USEIONIZATION\",\n              \"flags.USERECOMBINATION\",\"flags.USEPERPDIFFUSION\",\n              \"flags.USECOULOMBCOLLISIONS\",\n              \"flags.USETHERMALFORCE\",\"flags.USESURFACEMODEL\",\n              \"flags.USESHEATHEFIELD\",\n              \"flags.USEPRESHEATHEFIELD\",\"flags.BFIELD_INTERP\",\n              \"flags.LC_INTERP\",\"flags.GENERATE_LC\", \"flags.EFIELD_INTERP\",\n              \"flags.PRESHEATH_INTERP\",\"flags.DENSITY_INTERP\",\n              \"flags.TEMP_INTERP\",\n              \"flags.FLOWV_INTERP\",\"flags.GRADT_INTERP\",\n              \"flags.ODEINT\",\"flags.FIXEDSEEDS\",\n              \"flags.PARTICLESEEDS\",\"flags.GEOM_TRACE\",\"flags.GEOM_HASH\",\n              \"flags.GEOM_HASH_SHEATH\",\"flags.PARTICLE_TRACKS\",\n              \"flags.PARTICLE_SOURCE\",\n              \"flags.SPECTROSCOPY\",\"flags.USE3DTETGEOM\",\"flags.USECYLSYMM\"};\n    int flagValues[] =  {USE_CUDA, USEMPI, USE_BOOST,USEIONIZATION,\n           USERECOMBINATION,USEPERPDIFFUSION,USECOULOMBCOLLISIONS,\n           USETHERMALFORCE,USESURFACEMODEL,USESHEATHEFIELD,\n           USEPRESHEATHEFIELD,BFIELD_INTERP,LC_INTERP, GENERATE_LC,\n           EFIELD_INTERP,\n           PRESHEATH_INTERP,DENSITY_INTERP,TEMP_INTERP,\n           FLOWV_INTERP,GRADT_INTERP,ODEINT,FIXEDSEEDS,\n           PARTICLESEEDS,GEOM_TRACE,GEOM_HASH,\n           GEOM_HASH_SHEATH,PARTICLE_TRACKS,PARTICLE_SOURCE,\n           SPECTROSCOPY,USE3DTETGEOM,USECYLSYMM};\n    int check1;\n    for (int i=0; i<sizeof(flagValues)/sizeof(int); i++)\n    {\n      if(cfg.lookupValue(flags0[i], check1))\n      {  \n        if (flagValues[i] != check1)\n        { std::cout << \"incompatibility in \" << flags0[i]\n                  << \" between input file and binary\" << std::endl;\n          exit(0);\n        }\n        else\n        {\n          std::cout << flags0[i] <<\" = \" << check1<< std::endl;\n        }\n      }\n      else\n      {\n        std::cout << flags0[i] <<\" was not found\" << std::endl;\n      }\n    }\n  #endif\n  \n  // show memory usage of GPU\n  #if USE_CUDA \n    size_t free_byte ;\n    size_t total_byte ;\n    cudaError_t    cuda_status = cudaMemGetInfo( &free_byte, &total_byte ) ;\n  \n    if(cudaSuccess != cuda_status )\n    {\n  \n       printf(\"Error: cudaMemGetInfo fails, %s \\n\", cudaGetErrorString(cuda_status) );\n       exit(1);\n    }\n  \n    double free_db = (double)free_byte ;\n    double total_db = (double)total_byte ;\n    double used_db = total_db - free_db ;\n    \n    printf(\"GPU memory usage: used = %f, free = %f MB, total = %f MB\\n\",\n      used_db/1024.0/1024.0, free_db/1024.0/1024.0, total_db/1024.0/1024.0); \n  #endif\n  \n  // Background species info\n  float background_Z,background_amu;\n  getVariable(cfg,\"backgroundPlasmaProfiles.Z\",background_Z);\n  getVariable(cfg,\"backgroundPlasmaProfiles.amu\",background_amu);\n\n  //Bfield initialization\n  int nR_Bfield = 1;\n  int nY_Bfield = 1;\n  int nZ_Bfield = 1;\n  int n_Bfield = 1;\n  std::string bfieldCfg = \"backgroundPlasmaProfiles.Bfield.\";\n  #if BFIELD_INTERP > 0\n    std::string bfieldFile;\n    getVariable(cfg,bfieldCfg+\"fileString\",bfieldFile);\n    nR_Bfield = getDimFromFile(cfg,bfieldFile,bfieldCfg,\"gridNrString\");\n  #endif\n  #if BFIELD_INTERP > 1\n    nZ_Bfield = getDimFromFile(cfg,bfieldFile,bfieldCfg,\"gridNzString\");\n  #endif\n  #if BFIELD_INTERP > 2\n    nY_Bfield = getDimFromFile(cfg,bfieldFile,bfieldCfg,\"gridNyString\");\n  #endif\n  sim::Array<float> bfieldGridr(nR_Bfield),bfieldGridy(nY_Bfield),bfieldGridz(nZ_Bfield);\n  n_Bfield = nR_Bfield*nY_Bfield*nZ_Bfield;\n  sim::Array<float> br(n_Bfield),by(n_Bfield),bz(n_Bfield);\n  #if BFIELD_INTERP == 0\n    getVariable(cfg,bfieldCfg+\"r\",br[0]);\n    getVariable(cfg,bfieldCfg+\"y\",by[0]);\n    getVariable(cfg,bfieldCfg+\"z\",bz[0]);\n  #else\n    getVarFromFile(cfg,bfieldFile,bfieldCfg,\"gridRString\",bfieldGridr);\n    #if BFIELD_INTERP > 1\n      getVarFromFile(cfg,bfieldFile,bfieldCfg,\"gridZString\",bfieldGridz);\n    #endif\n    #if BFIELD_INTERP > 2\n      getVarFromFile(cfg,bfieldFile,bfieldCfg,\"gridYString\",bfieldGridy);\n    #endif\n\n    getVarFromFile(cfg,bfieldFile,bfieldCfg,\"rString\",br);\n    getVarFromFile(cfg,bfieldFile,bfieldCfg,\"yString\",by);\n    getVarFromFile(cfg,bfieldFile,bfieldCfg,\"zString\",bz);\n  #endif  \n  std::cout << \"Finished Bfield import\" << std::endl; \n\n  std::string profiles_folder = \"profiles\";  \n  \n  //Geometry Definition\n  Setting& geom = cfg_geom.lookup(\"geom\");\n  int nLines = geom[\"x1\"].getLength();\n  //int nMaterials = geom[\"nMaterials\"];\n  std::cout << \"Number of Geometric Objects To Load: \" << nLines << std::endl;\n  sim::Array<Boundary> boundaries(nLines+1);\n  importGeometry(cfg_geom, boundaries);\n\n  std::cout << \"Starting Boundary Init...\" << std::endl;\n  float biasPotential = 0.0;\n  \n  #if BIASED_SURFACE > 0\n    getVariable(cfg,\"backgroundPlasmaProfiles.biasPotential\",biasPotential);\n  #endif\n  \n  int nR_closeGeom = 1;\n  int nY_closeGeom = 1;\n  int nZ_closeGeom = 1;\n  int n_closeGeomElements = 1;\n  int nGeomHash = 1;\n  std::string geomHashCfg = \"geometry_hash.\";\n  #if GEOM_HASH == 1\n    getVariable(cfg,geomHashCfg+\"nR_closeGeom\",nR_closeGeom);\n    getVariable(cfg,geomHashCfg+\"nZ_closeGeom\",nZ_closeGeom);\n    getVariable(cfg,geomHashCfg+\"n_closeGeomElements\",n_closeGeomElements);\n    nGeomHash = nR_closeGeom*nZ_closeGeom*n_closeGeomElements;\n    #if USE3DTETGEOM > 0\n      getVariable(cfg,geomHashCfg+\"nY_closeGeom\",nY_closeGeom);\n      nGeomHash = nY_closeGeom*nGeomHash;\n    #endif\n  #endif\n\n  #if GEOM_HASH > 1\n    std::string hashFile;\n    getVariable(cfg,geomHashCfg+\"fileString\",hashFile);\n    nR_closeGeom = getDimFromFile(cfg,hashFile,geomHashCfg,\"gridNrString\");\n    nZ_closeGeom = getDimFromFile(cfg,hashFile,geomHashCfg,\"gridNzString\");\n    n_closeGeomElements = getDimFromFile(cfg,hashFile,geomHashCfg,\"nearestNelementsString\");\n    nGeomHash = nR_closeGeom*nZ_closeGeom*n_closeGeomElements;\n    #if USE3DTETGEOM > 0\n      nY_closeGeom = getDimFromFile(cfg,hashFile,geomHashCfg,\"gridNyString\");\n      nGeomHash = nY_closeGeom*nGeomHash;\n    #else\n    #endif\n  #endif\n  sim::Array<float> closeGeomGridr(nR_closeGeom), closeGeomGridy(nY_closeGeom),\n      closeGeomGridz(nZ_closeGeom);\n  sim::Array<int> closeGeom(nGeomHash);\n  #if GEOM_HASH == 1\n    float hashX0,hashX1,hashY0,hashY1,hashZ0,hashZ1;\n    getVariable(cfg,geomHashCfg+\"hashX0\",hashX0);\n    getVariable(cfg,geomHashCfg+\"hashX1\",hashX1);\n    getVariable(cfg,geomHashCfg+\"hashZ0\",hashZ0);\n    getVariable(cfg,geomHashCfg+\"hashZ1\",hashZ1);\n    #if USE3DTETGEOM > 0\n      getVariable(cfg,geomHashCfg+\"hashY0\",hashY0);\n      getVariable(cfg,geomHashCfg+\"hashY1\",hashY1);\n    #endif\n    \n    for(int i=0; i<nR_closeGeom; i++)\n    {  closeGeomGridr[i] = (hashX1 - hashX0)*i/(nR_closeGeom - 1)+ hashX0;}\n    for(int j=0; j<nY_closeGeom; j++)\n    {  closeGeomGridy[j] = (hashY1 - hashY0)*j/(nY_closeGeom - 1)+ hashY0;}\n    for(int k=0; k<nZ_closeGeom; k++)\n    {  closeGeomGridz[k] = (hashZ1 - hashZ0)*k/(nZ_closeGeom - 1)+ hashZ0;}\n  \n    thrust::counting_iterator<std::size_t> lines0(0);  \n    thrust::counting_iterator<std::size_t> lines1(nR_closeGeom*nY_closeGeom);\n    sim::Array<float> minDist1(nGeomHash,1e6);\n\n    for(int i=0; i<nZ_closeGeom; i++)\n    {\n       thrust::for_each(thrust::device, lines0,lines1,\n                        hashGeom(i,nLines, boundaries.data(), \n                        closeGeomGridr.data(), closeGeomGridy.data(),\n                        closeGeomGridz.data(),\n                        n_closeGeomElements, minDist1.data(), closeGeom.data(),\n                        nR_closeGeom,nY_closeGeom,nZ_closeGeom));\n       #if USE_CUDA\n         cudaDeviceSynchronize();\n       #endif\n    }\n    #if USE_CUDA\n      cudaDeviceSynchronize();\n    #endif\n    std::vector<int> geomHashDims(4);\n    geomHashDims[0] = nR_closeGeom;\n    geomHashDims[1] = nY_closeGeom;\n    geomHashDims[2] = nZ_closeGeom;\n    geomHashDims[3] = n_closeGeomElements;\n    std::vector<std::string> geomHashDimNames(4);\n    geomHashDimNames[0] = \"nR\";\n    geomHashDimNames[1] = \"nY\";\n    geomHashDimNames[2] = \"nZ\";\n    geomHashDimNames[3] = \"n_\";\n    std::vector<std::string> hashGridNames(2);\n    hashGridNames[0] = \"gridR\";\n    hashGridNames[1] = \"gridZ\";\n    std::vector<int> hashGridMapDim(2);\n    hashGridMapDim[0] = 0;\n    hashGridMapDim[1] = 2;\n    std::vector<std::vector<float>> hashGrids(2);\n    hashGrids[0].assign(&closeGeomGridr[0], &closeGeomGridr[0]+nR_closeGeom);\n    hashGrids[1].assign(&closeGeomGridz[0], &closeGeomGridz[0]+nZ_closeGeom);\n    std::vector<float*> hashGridPointers(2);\n    hashGridPointers[0] = &closeGeomGridr[0];\n    hashGridPointers[1] = &closeGeomGridz[0];\n    std::vector<std::string> intVarNames(1);\n    intVarNames[0] = \"hash\";\n    std::vector<vector<int>> intVarDimMap(1);\n    intVarDimMap[0].push_back(0);\n    intVarDimMap[0].push_back(2);\n    intVarDimMap[0].push_back(3);\n    std::vector<int*> intVarPointers(1);\n    intVarPointers[0] = &closeGeom[0];\n    std::string hashOutfile= \"GITRgeomHash\";\n    ncdfIO(1,hashOutfile,geomHashDimNames,geomHashDims,\n            hashGridNames,hashGridMapDim,hashGridPointers,\n            intVarNames,intVarDimMap,intVarPointers);\n  #elif GEOM_HASH > 1\n    getVarFromFile(cfg,hashFile,geomHashCfg,\"gridRString\",closeGeomGridr);\n    getVarFromFile(cfg,hashFile,geomHashCfg,\"gridZString\",closeGeomGridz);\n    #if USE3DTETGEOM >0\n      getVarFromFile(cfg,hashFile,geomHashCfg,\"gridYString\",closeGeomGridy);\n    #endif\n      getVarFromFile(cfg,hashFile,geomHashCfg,\"closeGeomString\",closeGeom);\n  #endif\n              \n  int nR_closeGeom_sheath = 1;\n  int nY_closeGeom_sheath = 1;\n  int nZ_closeGeom_sheath = 1;\n  int n_closeGeomElements_sheath = 1;\n  int nGeomHash_sheath = 1;\n  std::string geomHashSheathCfg= \"geometry_sheath.\";  \n  #if GEOM_HASH_SHEATH == 1\n    getVariable(cfg,geomHashSheathCfg+\"nR_closeGeom\",nR_closeGeom_sheath);\n    getVariable(cfg,geomHashSheathCfg+\"nZ_closeGeom\",nZ_closeGeom_sheath);\n    getVariable(cfg,geomHashSheathCfg+\"n_closeGeomElements\",n_closeGeomElements_sheath);\n    nGeomHash_sheath = nR_closeGeom_sheath*nZ_closeGeom_sheath*n_closeGeomElements_sheath;\n    #if USE3DTETGEOM > 0\n      getVariable(cfg,geomHashSheathCfg+\"nY_closeGeom\",nY_closeGeom_sheath);\n      nGeomHash_sheath = nY_closeGeom_sheath*nGeomHash_sheath;\n    #endif\n  #endif\n\n  #if GEOM_HASH_SHEATH > 1\n    std::string hashFile_sheath;\n    getVariable(cfg,geomHashSheathCfg+\"fileString\",hashFile_sheath);\n    nR_closeGeom_sheath = getDimFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"gridNrString\");\n    nZ_closeGeom_sheath = getDimFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"gridNzString\");\n    n_closeGeomElements_sheath = getDimFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"nearestNelementsString\");\n    nGeomHash_sheath = nR_closeGeom_sheath*nZ_closeGeom_sheath*n_closeGeomElements_sheath;\n    #if USE3DTETGEOM > 0\n      nY_closeGeom_sheath = getDimFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"gridNyString\");\n      nGeomHash_sheath = nY_closeGeom_sheath*nGeomHash_sheath;\n    #else\n    #endif\n  #endif\n  sim::Array<float> closeGeomGridr_sheath(nR_closeGeom_sheath), \n                    closeGeomGridy_sheath(nY_closeGeom_sheath),\n                    closeGeomGridz_sheath(nZ_closeGeom_sheath);\n  sim::Array<int> closeGeom_sheath(nGeomHash_sheath);\n  #if GEOM_HASH_SHEATH  ==1\n    float hashX0_s,hashX1_s,hashY0_s,hashY1_s,hashZ0_s,hashZ1_s;\n    getVariable(cfg,geomHashSheathCfg+\"hashX0\",hashX0_s);\n    getVariable(cfg,geomHashSheathCfg+\"hashX1\",hashX1_s);\n    getVariable(cfg,geomHashSheathCfg+\"hashZ0\",hashZ0_s);\n    getVariable(cfg,geomHashSheathCfg+\"hashZ1\",hashZ1_s);\n    #if USE3DTETGEOM > 0\n      getVariable(cfg,geomHashSheathCfg+\"hashY0\",hashY0_s);\n      getVariable(cfg,geomHashSheathCfg+\"hashY1\",hashY1_s);\n    #endif\n    \n    for(int i=0; i<nR_closeGeom_sheath; i++)\n    {  closeGeomGridr_sheath[i] = (hashX1_s - hashX0_s)*i/(nR_closeGeom_sheath - 1)+ hashX0_s;}\n    for(int j=0; j<nY_closeGeom_sheath; j++)\n    {  closeGeomGridy_sheath[j] = (hashY1_s - hashY0_s)*j/(nY_closeGeom_sheath - 1)+ hashY0_s;}\n    for(int k=0; k<nZ_closeGeom_sheath; k++)\n    {  closeGeomGridz_sheath[k] = (hashZ1_s - hashZ0_s)*k/(nZ_closeGeom_sheath - 1)+ hashZ0_s;}\n      \n    thrust::counting_iterator<std::size_t> lines0_s(0);  \n    thrust::counting_iterator<std::size_t> lines1_s(nR_closeGeom_sheath*nY_closeGeom_sheath);\n    sim::Array<float> minDist1_s(nGeomHash_sheath,1e6);\n    \n    for(int i=0; i<nZ_closeGeom_sheath; i++)\n      {\n              thrust::for_each(thrust::device, lines0_s,lines1_s,\n                               hashGeom_sheath(i,nLines, boundaries.data(), closeGeomGridr_sheath.data(),\n                               closeGeomGridy_sheath.data(),closeGeomGridz_sheath.data(),\n                               n_closeGeomElements_sheath, minDist1_s.data(), closeGeom_sheath.data(),\n                               nR_closeGeom_sheath,nY_closeGeom_sheath,nZ_closeGeom_sheath));\n              cudaDeviceSynchronize();\n      }\n              cudaDeviceSynchronize();\n\n    std::vector<int> geomHashDims_s(4);\n    geomHashDims_s[0] = nR_closeGeom_sheath;\n    geomHashDims_s[1] = nY_closeGeom_sheath;\n    geomHashDims_s[2] = nZ_closeGeom_sheath;\n    geomHashDims_s[3] = n_closeGeomElements_sheath;\n    std::vector<std::string> geomHashDimNames_s(4);\n    geomHashDimNames_s[0] = \"nR\";\n    geomHashDimNames_s[1] = \"nY\";\n    geomHashDimNames_s[2] = \"nZ\";\n    geomHashDimNames_s[3] = \"n_\";\n    std::vector<std::string> hashGridNames_s(2);\n    hashGridNames_s[0] = \"gridR\";\n    hashGridNames_s[1] = \"gridZ\";\n    std::vector<int> hashGridMapDim_s(2);\n    hashGridMapDim_s[0] = 0;\n    hashGridMapDim_s[1] = 2;\n    std::vector<float*> hashGridPointers_s(2);\n    hashGridPointers_s[0] = &closeGeomGridr_sheath[0];\n    hashGridPointers_s[1] = &closeGeomGridz_sheath[0];\n    std::vector<std::string> intVarNames_s(1);\n    intVarNames_s[0] = \"hash_sheath\";\n    std::vector<vector<int>> intVarDimMap_s(1);\n    intVarDimMap_s[0].push_back(0);\n    intVarDimMap_s[0].push_back(2);\n    intVarDimMap_s[0].push_back(3);\n    std::vector<int*> intVarPointers_s(1);\n    intVarPointers_s[0] = &closeGeom_sheath[0];\n    std::string hashOutfile_s= \"GITRgeomHash_sheath\";\n    ncdfIO(1,hashOutfile_s,geomHashDimNames_s,geomHashDims_s,\n            hashGridNames_s,hashGridMapDim_s,hashGridPointers_s,\n            intVarNames_s,intVarDimMap_s,intVarPointers_s);\n  #elif GEOM_HASH_SHEATH > 1\n    getVarFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"gridRString\",closeGeomGridr_sheath);\n    getVarFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"gridZString\",closeGeomGridz_sheath);\n    #if USE3DTETGEOM >0\n      getVarFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"gridYString\",closeGeomGridy_sheath);\n    #endif\n      getVarFromFile(cfg,hashFile_sheath,geomHashSheathCfg,\"closeGeomString\",closeGeom_sheath);\n  #endif\n\n  int nR_Lc = 1;\n  int nY_Lc = 1;\n  int nZ_Lc = 1;\n  int nTracers = 1;\n  std::string connLengthCfg= \"connectionLength.\";  \n  std::string lcFile;\n  getVariable(cfg,connLengthCfg+\"fileString\",lcFile);\n  #if GENERATE_LC == 1\n    getVariable(cfg,connLengthCfg+\"nX\",nR_Lc);\n    getVariable(cfg,connLengthCfg+\"nY\",nY_Lc);\n    getVariable(cfg,connLengthCfg+\"nZ\",nZ_Lc);\n    float r0_Lc, r1_Lc, y0_Lc,y1_Lc,z0_Lc,z1_Lc, dr;\n    int nTraceSteps;\n    getVariable(cfg,connLengthCfg+\"netx0\",r0_Lc);\n    getVariable(cfg,connLengthCfg+\"netx1\",r1_Lc);\n    getVariable(cfg,connLengthCfg+\"nety0\",y0_Lc);\n    getVariable(cfg,connLengthCfg+\"nety1\",y1_Lc);\n    getVariable(cfg,connLengthCfg+\"netz0\",z0_Lc);\n    getVariable(cfg,connLengthCfg+\"netz1\",z1_Lc);\n    getVariable(cfg,connLengthCfg+\"nTraceSteps\",nTraceSteps);\n    getVariable(cfg,connLengthCfg+\"dr\",dr);\n  #endif \n  #if GENERATE_LC > 1\n    nR_Lc = getDimFromFile(cfg,lcFile,connLengthCfg,\"gridNrString\");\n    nY_Lc = getDimFromFile(cfg,lcFile,connLengthCfg,\"gridNyString\");\n    nZ_Lc = getDimFromFile(cfg,lcFile,connLengthCfg,\"gridNzString\");\n  #endif\n  \n  #if USE3DTETGEOM > 0\n    nTracers = nR_Lc*nY_Lc*nZ_Lc;\n  #else\n    nTracers = nR_Lc*nZ_Lc;\n  #endif\n  \n  sim::Array<float> Lc(nTracers),s(nTracers);\n  sim::Array<float> gridRLc(nR_Lc),gridYLc(nY_Lc),gridZLc(nZ_Lc);\n  sim::Array<int> noIntersectionNodes(nTracers);\n  #if GENERATE_LC ==1\n    if( !boost::filesystem::exists( lcFile ) )\n    {\n       std::cout << \"No pre-existing connection length file found\" << std::endl;    \n      #if USE3DTETGEOM > 0\n        float dy_Lc = (y1_Lc-y0_Lc)/(nY_Lc-1);\n        for(int j=0;j<nY_Lc; j++)\n        {\n         gridYLc[j] = y0_Lc + j*dy_Lc;\n        }\n      #endif\n      float dr_Lc = (r1_Lc-r0_Lc)/(nR_Lc-1);\n      for(int i=0;i<nR_Lc; i++)\n      {\n       gridRLc[i] = r0_Lc + i*dr_Lc;\n      }\n\n      float dz_Lc = (z1_Lc-z0_Lc)/(nZ_Lc-1);\n      for(int j=0;j<nZ_Lc; j++)\n      {\n       gridZLc[j] = z0_Lc + j*dz_Lc;\n      }\n      std::cout << \"Creating tracer particles\" << std::endl;\n      thrust::counting_iterator<std::size_t> lcBegin(0);  \n      thrust::counting_iterator<std::size_t> lcEnd(nTracers);\n      auto forwardTracerParticles = new Particles(nTracers);\n      auto backwardTracerParticles = new Particles(nTracers);\n      int addIndex = 0;\n      std::cout << \"Initializing tracer particles\" << std::endl;\n   \n      for(int i=0;i<nR_Lc; i++)\n      {\n        for(int j=0;j<nY_Lc;j++)\n        {\n           for (int k=0;k<nZ_Lc;k++)\n           {\n              #if USE3DTETGEOM > 0\n                addIndex = i + j*nR_Lc + k*nR_Lc*nY_Lc;\n              #else\n                addIndex = i+k*nR_Lc;\n              #endif\n              forwardTracerParticles->setParticle(addIndex,gridRLc[i], gridYLc[j], gridZLc[k], \n                                                  0.0, 0.0, 0.0, 0, 0.0, 0.0);\n              backwardTracerParticles->setParticle(addIndex,gridRLc[i], gridYLc[j], gridZLc[k], \n                                                   0.0, 0.0, 0.0, 0, 0.0, 0.0);\n           }\n        }\n      }\n      \n                              \n      typedef std::chrono::high_resolution_clock Time_trace;\n      typedef std::chrono::duration<float> fsec_trace;\n      auto start_clock_trace = Time_trace::now();\n      std::cout << \"Starting trace loop\" << std::endl;\n      std::cout << \"nTraceSteps\"<< nTraceSteps << \" dr \"<< dr  << std::endl;\n      for (int ii=0;ii<nTraceSteps; ii++)\n      {\n        #if USE_CUDA \n          cudaDeviceSynchronize();\n        #endif\n        thrust::for_each(thrust::device, lcBegin,lcEnd,\n                 field_line_trace(1.0,forwardTracerParticles,dr,boundaries.data(), nLines,\n                     nR_Lc,nZ_Lc,gridRLc.data(),gridZLc.data(),Lc.data(),\n                     nR_Bfield,nZ_Bfield, bfieldGridr.data(),&bfieldGridz.front(),\n                     &br.front(),&bz.front(),&by.front()));\n        \n        thrust::for_each(thrust::device, lcBegin,lcEnd,\n                 field_line_trace(-1.0,backwardTracerParticles,dr,boundaries.data(), nLines,\n                     nR_Lc,nZ_Lc,gridRLc.data(),gridZLc.data(),Lc.data(),\n                     nR_Bfield,nZ_Bfield, bfieldGridr.data(),&bfieldGridz.front(),\n                     &br.front(),&bz.front(),&by.front()));\n            \n        thrust::for_each(thrust::device, lcBegin,lcEnd,\n                  geometry_check(forwardTracerParticles,nLines,&boundaries[0],dr,ii,\n                      nR_closeGeom,nY_closeGeom,nZ_closeGeom,n_closeGeomElements,\n                      &closeGeomGridr.front(),&closeGeomGridy.front(),&closeGeomGridz.front(),\n                      &closeGeom.front()) );\n        \n        thrust::for_each(thrust::device, lcBegin,lcEnd,\n                  geometry_check(backwardTracerParticles,nLines,&boundaries[0],dr,ii,\n                      nR_closeGeom,nY_closeGeom,nZ_closeGeom,n_closeGeomElements,\n                      &closeGeomGridr.front(),&closeGeomGridy.front(),&closeGeomGridz.front(),\n                      &closeGeom.front()) );\n      }\n      auto finish_clock_trace = Time_trace::now();\n      fsec_trace fstrace = finish_clock_trace - start_clock_trace;\n      printf(\"Time taken          is %6.3f (secs) \\n\", fstrace.count());\n      printf(\"Time taken per step is %6.3f (secs) \\n\", fstrace.count() / (float) nTraceSteps);\n      #if USE_CUDA \n         cudaDeviceSynchronize();\n      #endif\n      addIndex = 0;\n      float forwardDist = 0.0;\n      float backwardDist = 0.0;\n      for(int i=0;i<nR_Lc; i++)\n      {\n        for(int j=0;j<nY_Lc;j++)\n        {\n          for(int k=0;k<nZ_Lc;k++)\n          {\n            \n             #if USE3DTETGEOM > 0\n               addIndex = i + j*nR_Lc + k*nR_Lc*nY_Lc;\n             #else\n                   addIndex = i+k*nR_Lc;\n             #endif\n             if(forwardTracerParticles->hitWall[addIndex] > 0)\n             {\n                forwardDist = forwardTracerParticles->distanceTraveled[addIndex];\n             }\n             else\n             { forwardDist = 0.0;}\n\n             if(backwardTracerParticles->hitWall[addIndex] > 0)\n             {\n                backwardDist = backwardTracerParticles->distanceTraveled[addIndex];\n             }\n             else backwardDist = 0.0;\n             \n             Lc[addIndex] = forwardDist + backwardDist;\n             \n             if(forwardTracerParticles->distanceTraveled[addIndex] > \n                     backwardTracerParticles->distanceTraveled[addIndex])\n             {\n               s[addIndex] = -(0.5*Lc[addIndex]-backwardTracerParticles->distanceTraveled[addIndex]);\n             }\n             else\n             {\n               s[addIndex] = (0.5*Lc[addIndex]-forwardTracerParticles->distanceTraveled[addIndex]);\n             }\n             if(forwardTracerParticles->hitWall[addIndex] + backwardTracerParticles->hitWall[addIndex]<4.0)\n             {\n               noIntersectionNodes[addIndex] = 1;    \n             }\n          }\n        }\n      }\n\n      NcFile ncFileLC(\"LcS.nc\", NcFile::replace);\n      NcDim nc_nTracers = ncFileLC.addDim(\"nTracers\",nTracers);\n      NcDim nc_nRLc = ncFileLC.addDim(\"nR\",nR_Lc);\n      NcDim nc_nYLc = ncFileLC.addDim(\"nY\",nY_Lc);\n      NcDim nc_nZLc = ncFileLC.addDim(\"nZ\",nZ_Lc);\n      \n      NcVar nc_Lc = ncFileLC.addVar(\"Lc\",ncDouble,nc_nTracers);\n      NcVar nc_s = ncFileLC.addVar(\"s\",ncDouble,nc_nTracers);\n      NcVar nc_nI = ncFileLC.addVar(\"noIntersection\",ncDouble,nc_nTracers);\n      NcVar nc_gridRLc = ncFileLC.addVar(\"gridR\",ncDouble,nc_nRLc);\n      NcVar nc_gridYLc = ncFileLC.addVar(\"gridY\",ncDouble,nc_nYLc);\n      NcVar nc_gridZLc = ncFileLC.addVar(\"gridZ\",ncDouble,nc_nZLc);\n      \n      nc_Lc.putVar(&Lc[0]);\n      nc_s.putVar(&s[0]);\n      nc_nI.putVar(&noIntersectionNodes[0]);\n      nc_gridRLc.putVar(&gridRLc[0]);\n      nc_gridYLc.putVar(&gridYLc[0]);\n      nc_gridZLc.putVar(&gridZLc[0]);\n      #if USE_CUDA \n             cudaDeviceSynchronize();\n      #endif\n   }         \n  #endif    \n\n  #if GENERATE_LC > 1\n    std::cout << \"Importing pre-existing connection length file\" << std::endl;\n    getVariable(cfg,connLengthCfg+\"fileString\",r0_Lc);\n    getVarFromFile(cfg,lcFile,connLengthCfg,\"gridRString\",gridRLc);\n    getVarFromFile(cfg,lcFile,connLengthCfg,\"gridYString\",gridYLc);\n    getVarFromFile(cfg,lcFile,connLengthCfg,\"gridZString\",gridZLc);\n    getVarFromFile(cfg,lcFile,connLengthCfg,\"LcString\",Lc);\n    getVarFromFile(cfg,lcFile,connLengthCfg,\"SString\",s);\n  #endif\n  \n  //Background Plasma Temperature Initialization    \n  #if TEMP_INTERP == 0\n    int nR_Temp = 1;\n    int nZ_Temp = 1;\n    sim::Array<float> TempGridr(nR_Temp), TempGridz(nZ_Temp);\n    sim::Array<float> ti(nR_Temp*nZ_Temp), te(nR_Temp*nZ_Temp);\n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.ti\", ti[0]) && \n       cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.te\", te[0]))\n    {std::cout << \"Ti and Te = \" << ti[0] << \" \" << te[0] << std::endl;}\n    else\n    {std::cout << \"ERROR: Failed importing constant temperatures\" << std:: endl;}\n  #elif TEMP_INTERP == 2\n    int nR_Temp;\n    int nZ_Temp;\n    const char *tempFile, *tempNr, *tempNz, *tempGridR, *tempGridZ, *teChar, *tiChar;\n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.fileString\", tempFile) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.gridNrString\", tempNr) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.gridNzString\", tempNz) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.gridRString\",tempGridR) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.gridZString\",tempGridZ) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.IonTempString\", tiChar) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Temperature.ElectronTempString\", teChar))\n    { std::cout << \"Temperature file: \" << tempFile << std::endl;}\n    else\n    { std::cout << \"ERROR: Failed in acquiring Temperature file data from input file \" << std::endl;} \n    std::cout << \"read netcdf file\" << std::endl;\n    int t1 = read_profileNsChar(tempFile,tempNr,tempNz,nR_Temp,nZ_Temp);\n    std::cout << tempNr << nR_Temp << std::endl; \n    sim::Array<float> TempGridr(nR_Temp), TempGridz(nZ_Temp);\n    sim::Array<float> ti(nR_Temp*nZ_Temp), te(nR_Temp*nZ_Temp);\n    \n    int t2 = read_profile1d(tempFile,tempGridR, TempGridr);\n    \n    int t3 = read_profile1d(tempFile,tempGridZ, TempGridz);\n    \n    int t4 = read_profile2d(tempFile,tiChar, ti);\n    \n    int t5 = read_profile2d(tempFile,teChar, te);\n  #endif\n  std::string outnameTgridR = \"tGridR.m\";\n  std::string outnameTgridZ = \"tGridZ.m\";\n  std::string outnameTi = \"ti.m\";\n  std::string outnameTe = \"te.m\";\n  OUTPUT1d(profiles_folder,outnameTgridR, nR_Temp, &TempGridr.front());\n  OUTPUT1d(profiles_folder,outnameTgridZ, nZ_Temp, &TempGridz.front());\n  OUTPUT2d(profiles_folder,outnameTi, nR_Temp, nZ_Temp, &ti.front());\n  OUTPUT2d(profiles_folder,outnameTe, nR_Temp, nZ_Temp, &te.front());\n\n  float testVec = 0.0;\n  testVec = interp2dCombined(0.07,0.0,0.0,nR_Temp,\n                    nZ_Temp,TempGridr.data(),TempGridz.data(),ti.data());\n  std::cout << \"Finished Temperature import \"<< testVec << std::endl; \n  \n  //Background Plasma Density Initialization\n  #if DENSITY_INTERP == 0\n    int nR_Dens = 1;\n    int nZ_Dens = 1;\n    sim::Array<float> DensGridr(nR_Dens), DensGridz(nZ_Dens);\n    sim::Array<float> ni(nR_Dens*nZ_Dens), ne(nR_Dens*nZ_Dens);\n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.Density.ni\", ni[0]) && \n       cfg.lookupValue(\"backgroundPlasmaProfiles.Density.ne\", ne[0]))\n    {std::cout << \"Ni and Ne = \" << ni[0] << \" \" << ne[0] << std::endl;}\n    else\n    {std::cout << \"ERROR: Failed importing constant densities\" << std:: endl;}\n  #elif DENSITY_INTERP == 2\n    int nR_Dens;\n    int nZ_Dens;\n    \n    const char *densFile, *densNr, *densNz, *densGridR, *densGridZ, *neChar, *niChar;\n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.Density.fileString\", densFile) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Density.gridNrString\", densNr) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Density.gridNzString\", densNz) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Density.gridRString\",densGridR) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Density.gridZString\",densGridZ) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Density.IonDensityString\", niChar) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.Density.ElectronDensityString\", neChar))\n    { std::cout << \"Density file: \" << densFile << std::endl;}\n    else\n    { std::cout << \"ERROR: Failed in acquiring density file data from input file \" << std::endl;} \n    int n1 = read_profileNs(densFile,densNr,densNz,nR_Dens,nZ_Dens);\n    \n    sim::Array<float> DensGridr(nR_Dens), DensGridz(nZ_Dens);\n    sim::Array<float> ni(nR_Dens*nZ_Dens), ne(nR_Dens*nZ_Dens);\n    \n    int n2 = read_profile1d(densFile,densGridR, DensGridr);\n    \n    int n3 = read_profile1d(densFile,densGridZ, DensGridz);\n    \n    int n4 = read_profile2d(densFile,niChar, ni);\n    \n    int n5 = read_profile2d(densFile,neChar, ne);\n  #endif\n  \n  std::string outnameNgridR = \"nGridR.m\";\n  std::string outnameNgridZ = \"nGridZ.m\";\n  std::string outnameNi = \"ni.m\";\n  std::string outnameNe = \"ne.m\";\n  OUTPUT1d(profiles_folder,outnameNgridR, nR_Dens, &DensGridr.front());\n  OUTPUT1d(profiles_folder,outnameNgridZ, nZ_Dens, &DensGridz.front());\n  OUTPUT2d(profiles_folder,outnameNi, nR_Dens, nZ_Dens, &ni.front());\n  OUTPUT2d(profiles_folder,outnameNe, nR_Dens, nZ_Dens, &ne.front());\n\n  std::cout << \"Finished density import \"<< ne[0] << std::endl; \n  //Background Plasma flow velocity initialization    \n  #if FLOWV_INTERP == 0\n    int nR_flowV = 1;\n    int nZ_flowV = 1;\n    sim::Array<float> flowVGridr(nR_flowV), flowVGridz(nZ_flowV);\n    sim::Array<float> flowVr(nR_flowV*nZ_flowV), flowVz(nR_flowV*nZ_flowV),\n                        flowVt(nR_flowV*nZ_flowV);\n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.flowVr\", flowVr[0]) && \n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.flowVz\", flowVz[0]) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.flowVt\", flowVt[0]))\n    {std::cout << \"Flow velocity vector = \" << flowVr[0] << \" \" << \n                  flowVt[0]<< \" \" << flowVz[0] << std::endl;}\n    else\n    {std::cout << \"ERROR: Failed importing constant flow velocity\" << std:: endl;}\n  #elif FLOWV_INTERP == 1\n    int nR_flowV=nR_Lc;\n    int nZ_flowV=nZ_Lc;\n    sim::Array<float> flowVGridr(nR_flowV);//=gridRLc;\n    sim::Array<float> flowVGridz(nZ_flowV);//=gridZLc;\n    std::cout << \"nR_flowV \" << nR_flowV << \" \" << nZ_flowV << std::endl;\n    std::cout << \" !!! gridRLc \" << gridRLc[0] << std::endl;\n    std::cout << \" !!! gridZLc \" << gridZLc[0] << std::endl;\n    for(int i=0;i<nR_flowV;i++)\n    {\n        flowVGridr[i] = gridRLc[i];\n    }\n    for(int i=0;i<nZ_flowV;i++)\n    {\n        flowVGridz[i] = gridZLc[i];\n    }\n    std::cout << \" !!! flowvgridr0 \" << flowVGridr[0] << std::endl;\n    int nFlowVs = nR_Lc*nZ_Lc;\n    #if LC_INTERP == 3\n    int nY_flowV=nY_Lc;\n    sim::Array<float> flowVGridy(nY_flowV);//=gridYLc;\n    for(int i=0;i<nY_flowV;i++)\n        flowVGridy[i] = gridYLc[i];\n    nFlowVs = nR_Lc*nY_Lc*nZ_Lc;\n    #endif\n    sim::Array<float> flowVr(nFlowVs), flowVz(nFlowVs),\n                        flowVt(nFlowVs);\n    float thisY = 0.0;\n    float cs0=0.0;\n    float teLocal = 0.0;\n    float tiLocal = 0.0;\n    float BLocal[3] = {0.0,0.0,0.0};\n    float Bnorm[3] = {0.0,0.0,0.0};\n    float Bmag = 0.0;\n    int index = 0;\n    float cs = 0.0;\n    float absS = 0.0;\n    std::cout << \"Beginning analytic flowV calculation \"<< std::endl; \n    for(int i=0;i<nR_Lc; i++)\n    {\n     #if LC_INTERP == 3\n     for(int k=0;k < nY_Lc; k++)\n     { thisY = flowVGridy[k];\n     #endif\n\n         for(int j=0;j<nZ_Lc;j++)\n      { \n        //std::cout << \"debug here 1 \" << i << \" \" << j << std::endl;\n        //std::cout << \"debug here 2 \" << flowVGridr[i] << \" \" << thisY << \" \"  \n        //    << flowVGridz[j] << \" \" << nR_Temp << \" \"<<nZ_Temp << std::endl;\n        teLocal = interp2dCombined(flowVGridr[i],thisY,flowVGridz[j],nR_Temp,nZ_Temp, \n                &TempGridr.front(),&TempGridz.front(),&te.front());\n        tiLocal = interp2dCombined(flowVGridr[i],thisY,flowVGridz[j],nR_Temp,nZ_Temp, \n                &TempGridr.front(),&TempGridz.front(),&ti.front());\n        cs0 = sqrt((teLocal+tiLocal)*1.602e-19/(background_amu*1.66e-27));\n        interp2dVector(&BLocal[0],flowVGridr[i],thisY,flowVGridz[j],nR_Bfield,\n                    nZ_Bfield,bfieldGridr.data(),bfieldGridz.data(),br.data(),bz.data(),by.data());\n        Bmag = sqrt(BLocal[0]*BLocal[0] + BLocal[1]*BLocal[1] + BLocal[2]*BLocal[2]);\n        Bnorm[0] = BLocal[0]/Bmag;\n        Bnorm[1] = BLocal[1]/Bmag;\n        Bnorm[2] = BLocal[2]/Bmag;\n\n     #if LC_INTERP == 3\n        index = i+k*nR_Lc + j*nR_Lc*nY_Lc;\n        //std::cout << \"flowv calc index \" << index << std::endl;\n#else\n        index = i+j*nR_Lc;\n\n#endif\n        absS = abs(s[index]);\n        cs = cs0*(0.5*Lc[index]/absS - sqrt(0.25*Lc[index]*Lc[index]/absS/absS - 1.0));\n        if(std::isnan(cs)) cs = 0.0;\n        flowVr[index] = sgn(s[index])*Bnorm[0]*cs;\n        flowVt[index] = sgn(s[index])*Bnorm[1]*cs;\n        flowVz[index] = sgn(s[index])*Bnorm[2]*cs;\n     #if LC_INTERP == 3\n      }\n     #endif\n      }\n    }\n    std::cout << \"Done with initial calculation, beginning sorting\" << std::endl;\n    sim::Array<float> flowVrSub(nFlowVs), flowVzSub(nFlowVs),\n                        flowVySub(nFlowVs);\n    sim::Array<int> noIntersectionNearestMax(nFlowVs);\n    float surroundingMinimumR = 0.0;\n    float surroundingMinimumY = 0.0;\n    float surroundingMinimumZ = 0.0;\n    int iterIndex = 0;\n    for(int i=0; i<nR_Lc;i++)\n    {\n        std::cout << \"i of \" << i << \" \" << nR_Lc << std::endl;\n        for(int j=0;j<nY_Lc;j++)\n        {\n            for(int k=0;k<nZ_Lc;k++)\n            {\n               index = i+j*nR_Lc + k*nR_Lc*nY_Lc;\n               if(noIntersectionNodes[index] ==1)\n               {\n                   surroundingMinimumR = 0.0;\n                   surroundingMinimumY = 0.0;\n                   surroundingMinimumZ = 0.0;\n                       for(int ii=i-1; ii<i+2;ii++)\n                       {\n                         for(int jj=j-1;jj<j+2;jj++)\n                         {\n                           for(int kk=k-1;kk<k+2;kk++)\n                           {\n                               iterIndex = ii+jj*nR_Lc + kk*nR_Lc*nY_Lc;\n                               if(iterIndex > 0 && iterIndex < nFlowVs)\n                               {\n                               if(noIntersectionNodes[iterIndex] ==0)\n                               {\n                                 if(abs(flowVr[iterIndex])>abs(surroundingMinimumR))\n                                 {\n                                   surroundingMinimumR = flowVr[iterIndex];\n                                 }\n                                 if(abs(flowVt[iterIndex])>abs(surroundingMinimumY))\n                                 {\n                                   surroundingMinimumY = flowVt[iterIndex];\n                                 }\n                                 if(abs(flowVz[iterIndex])>abs(surroundingMinimumZ))\n                                 {\n                                   surroundingMinimumZ = flowVz[iterIndex];\n                                 }\n                               }\n                               }\n                           }\n                         }\n                       }\n                  flowVrSub[index] = surroundingMinimumR; \n                  flowVySub[index] = surroundingMinimumY; \n                  flowVzSub[index] = surroundingMinimumZ; \n\n               }\n            }\n        }\n    }\n    for(int i=0;i<nFlowVs;i++)\n    {\n            if(i ==282839)\n            {\n                std::cout<< \" noIntersectionNodes \" << noIntersectionNodes[i] << std::endl;\n            }\n               if(noIntersectionNodes[i] ==1)\n               {\n                  flowVr[i] =  flowVrSub[i];\n                  flowVt[i] =  flowVySub[i];\n                  flowVz[i] =  flowVzSub[i];\n               }\n\n    }\n\n        std::cout << \"Finished analytic flowV calculation \"<< std::endl; \n  #elif FLOWV_INTERP == 2\n    int nR_flowV;\n    int nZ_flowV;\n    \n    const char *flowVFile,*flowVNr,*flowVNz,*flowVGridR,\n               *flowVGridZ,*flowVrChar,*flowVzChar,*flowVtChar;\n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.fileString\", flowVFile) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.gridNrString\",flowVNr) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.gridNzString\",flowVNz) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.gridRString\",flowVGridR) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.gridZString\",flowVGridZ) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.flowVrString\",flowVrChar) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.flowVzString\",flowVzChar) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.FlowVelocity.flowVtString\",flowVtChar))\n    { std::cout << \"flowV file: \" << flowVFile << std::endl;}\n    else\n    { std::cout << \"ERROR: Could not get flowV string info from input file \" << std::endl;}\n    int f1 = read_profileNs(flowVFile,flowVNr,flowVNz,nR_flowV,nZ_flowV);\n    \n    sim::Array<float> flowVGridr(nR_flowV), flowVGridz(nZ_flowV);\n    sim::Array<float> flowVr(nR_flowV*nZ_flowV), flowVz(nR_flowV*nZ_flowV),\n                        flowVt(nR_flowV*nZ_flowV);\n    \n    int f2 = read_profile1d(flowVFile,flowVGridR, flowVGridr);\n    \n    int f3 = read_profile1d(flowVFile,flowVGridZ, flowVGridz);\n    \n    int f4 = read_profile2d(flowVFile,flowVrChar, flowVr);\n    \n    int f5 = read_profile2d(flowVFile,flowVzChar, flowVz);\n    \n    int f6 = read_profile2d(flowVFile,flowVtChar, flowVt);\n  #endif\n\n  std::string outnameFlowVr = \"flowVr.m\";\n  std::string outnameFlowVz = \"flowVz.m\";\n  std::string outnameFlowVt = \"flowVt.m\";\n #if LC_INTERP == 3\n  OUTPUT3d(profiles_folder,outnameFlowVr, nR_flowV,nY_flowV, nZ_flowV, &flowVr.front());\n  OUTPUT3d(profiles_folder,outnameFlowVz, nR_flowV,nY_flowV, nZ_flowV, &flowVz.front());\n  OUTPUT3d(profiles_folder,outnameFlowVt, nR_flowV,nY_flowV, nZ_flowV, &flowVt.front());\n#else\n  OUTPUT2d(profiles_folder,outnameFlowVr, nR_flowV, nZ_flowV, &flowVr.front());\n  OUTPUT2d(profiles_folder,outnameFlowVz, nR_flowV, nZ_flowV, &flowVz.front());\n  OUTPUT2d(profiles_folder,outnameFlowVt, nR_flowV, nZ_flowV, &flowVt.front());\n#endif\n  //Background plasma temperature gradient field intitialization    \n  #if GRADT_INTERP == 0\n    int nR_gradT = 1;\n    int nZ_gradT = 1;\n    sim::Array<float> gradTGridr(nR_gradT), gradTGridz(nZ_gradT);\n    sim::Array<float> gradTeR(nR_gradT*nZ_gradT), gradTeZ(nR_gradT*nZ_gradT),\n        gradTeT(nR_gradT*nZ_gradT,0.0),gradTiR(nR_gradT*nZ_gradT), \n        gradTiZ(nR_gradT*nZ_gradT),gradTiT(nR_gradT*nZ_gradT,0.0);    \n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTeR\", gradTeR[0]) && \n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTeZ\", gradTeZ[0]) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTiR\", gradTiR[0]) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTiZ\", gradTiZ[0]))\n    {std::cout << \"Temperature gradients TeR and TeZ = \" << gradTeR[0] << \" \" << \n                  gradTeZ[0] << \"\\nTemperature gradients TiR and TiZ = \" << \n                  gradTiR[0] << \" \" << gradTiZ[0] << std::endl;}\n    else\n    {std::cout << \"ERROR: Failed importing constant temperature gradients\" << std:: endl;}\n  #elif GRADT_INTERP == 2\n    int nR_gradT;\n    int nZ_gradT;\n    \n    const char *gradTFile,*gradTNr,*gradTNz,*gradTGridR,\n               *gradTGridZ,*gradTiRChar,*gradTiZChar,*gradTeRChar,*gradTeZChar;\n    if(cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.fileString\", gradTFile) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gridNrString\",gradTNr) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gridNzString\",gradTNz) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gridRString\",gradTGridR) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gridZString\",gradTGridZ) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTiRString\",gradTiRChar) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTiZString\",gradTiZChar) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTeRString\",gradTeRChar) &&\n       cfg.lookupValue(\"backgroundPlasmaProfiles.gradT.gradTeZString\",gradTeZChar))\n    { std::cout << \"gradT file: \" << gradTFile << std::endl;}\n    else\n    { std::cout << \"ERROR: Could not get gradT string info from input file \" << std::endl;}\n    int g1 = read_profileNs(gradTFile,gradTNr,gradTNz,nR_gradT,nZ_gradT);\n    \n    sim::Array<float> gradTGridr(nR_gradT), gradTGridz(nZ_gradT);\n    sim::Array<float> gradTeR(nR_gradT*nZ_gradT), gradTeZ(nR_gradT*nZ_gradT),\n        gradTeT(nR_gradT*nZ_gradT,0.0),gradTiR(nR_gradT*nZ_gradT), \n        gradTiZ(nR_gradT*nZ_gradT),gradTiT(nR_gradT*nZ_gradT,0.0);\n    \n    int g2 = read_profile1d(gradTFile,gradTGridR, gradTGridr);\n    \n    int g3 = read_profile1d(gradTFile,gradTGridZ, gradTGridz);\n    \n    int g4 = read_profile2d(gradTFile,gradTiRChar, gradTiR);\n    \n    int g5 = read_profile2d(gradTFile,gradTiZChar, gradTiZ);\n    \n    int g6 = read_profile2d(gradTFile,gradTeRChar, gradTeR);\n    \n    int g7 = read_profile2d(gradTFile,gradTeZChar, gradTeZ);\n  #endif\n\n  std::string outnameGradTiR = \"gradTiR.m\";\n  std::string outnameGradTiZ = \"gradTiZ.m\";\n  std::string outnameGradTeR = \"gradTeR.m\";\n  std::string outnameGradTeZ = \"gradTeZ.m\";\n  OUTPUT2d(profiles_folder,outnameGradTiR, nR_gradT, nZ_gradT, &gradTiR.front());\n  OUTPUT2d(profiles_folder,outnameGradTiZ, nR_gradT, nZ_gradT, &gradTiZ.front());\n  OUTPUT2d(profiles_folder,outnameGradTeR, nR_gradT, nZ_gradT, &gradTeR.front());\n  OUTPUT2d(profiles_folder,outnameGradTeZ, nR_gradT, nZ_gradT, &gradTeZ.front());\n\n\n  //Initialization of ionization and recombination coefficients    \n  int nCS_Ionize, nCS_Recombine;\n  const char *ionizeFile,*ionizeNcs,*ionizeNDens,*ionizeNTemp,\n             *ionizeDensGrid,*ionizeTempGrid,*ionizeRCvarChar,\n             *recombFile,*recombNcs,*recombNDens,*recombNTemp,\n             *recombDensGrid,*recombTempGrid,*recombRCvarChar;\n  if(cfg.lookupValue(\"impurityParticleSource.ionization.fileString\", ionizeFile) &&\n     cfg.lookupValue(\"impurityParticleSource.ionization.nChargeStateString\",ionizeNcs) &&\n     cfg.lookupValue(\"impurityParticleSource.ionization.DensGridString\",ionizeNDens) &&\n     cfg.lookupValue(\"impurityParticleSource.ionization.TempGridString\",ionizeNTemp) &&\n     cfg.lookupValue(\"impurityParticleSource.ionization.TempGridVarName\",ionizeTempGrid) &&\n     cfg.lookupValue(\"impurityParticleSource.ionization.DensGridVarName\",ionizeDensGrid) &&\n     cfg.lookupValue(\"impurityParticleSource.ionization.CoeffVarName\",ionizeRCvarChar))\n  { std::cout << \"Ionization rate coefficient file: \" << ionizeFile << std::endl;}\n  else\n  { std::cout << \"ERROR: Could not get ionization string info from input file \" << std::endl;}\n  if(cfg.lookupValue(\"impurityParticleSource.recombination.fileString\", recombFile) &&\n     cfg.lookupValue(\"impurityParticleSource.recombination.nChargeStateString\",recombNcs) &&\n     cfg.lookupValue(\"impurityParticleSource.recombination.DensGridString\",recombNDens) &&\n     cfg.lookupValue(\"impurityParticleSource.recombination.TempGridString\",recombNTemp) &&\n     cfg.lookupValue(\"impurityParticleSource.recombination.TempGridVarName\",recombTempGrid) &&\n     cfg.lookupValue(\"impurityParticleSource.recombination.DensGridVarName\",recombDensGrid) &&\n     cfg.lookupValue(\"impurityParticleSource.recombination.CoeffVarName\",recombRCvarChar))\n  { std::cout << \"Recombination rate coefficient file: \" << recombFile << std::endl;}\n  else\n  { std::cout << \"ERROR: Could not get ionization string info from input file \" << std::endl;}\n  int i0 = read_profileNs(ionizeFile,ionizeNcs,recombNcs,nCS_Ionize, nCS_Recombine);\n\n  int nTemperaturesIonize, nDensitiesIonize;\n  int i1 = read_profileNs(ionizeFile,ionizeNDens,ionizeNTemp,nDensitiesIonize,nTemperaturesIonize);\n\n  sim::Array<float> rateCoeff_Ionization(nCS_Ionize*nTemperaturesIonize*nDensitiesIonize);\n  sim::Array<float> gridTemperature_Ionization(nTemperaturesIonize),\n                        gridDensity_Ionization(nDensitiesIonize);\n\n  int i2 = read_profiles(ionizeFile,nTemperaturesIonize,nDensitiesIonize,ionizeTempGrid, \n                         gridTemperature_Ionization,ionizeDensGrid,gridDensity_Ionization,\n                         ionizeRCvarChar,rateCoeff_Ionization);\n   \n  int nTemperaturesRecombine, nDensitiesRecombine;\n  int i3 = read_profileNs(recombFile,recombNDens,recombNTemp,\n                          nDensitiesRecombine,nTemperaturesRecombine);\n\n  sim::Array<float> rateCoeff_Recombination(nCS_Recombine*nTemperaturesRecombine*nDensitiesRecombine);\n  sim::Array<float> gridTemperature_Recombination(nTemperaturesRecombine),\n                    gridDensity_Recombination(nDensitiesRecombine);\n\n  int i4 = read_profiles(recombFile,nTemperaturesRecombine,nDensitiesRecombine,\n             recombTempGrid,gridTemperature_Recombination,recombDensGrid,\n             gridDensity_Recombination,\n             recombRCvarChar,rateCoeff_Recombination);\n\n\n  //Applying background values at material boundaries\n  std::for_each(boundaries.begin(), boundaries.end()-1,\n            boundary_init(background_Z,background_amu,\n            nR_Dens,nZ_Dens,DensGridr.data(),DensGridz.data(),ni.data(),\n            nR_Bfield,nZ_Bfield,bfieldGridr.data(),\n            bfieldGridz.data(),br.data(),bz.data(), by.data(),\n            nR_Temp,nZ_Temp,TempGridr.data(),\n            TempGridz.data(),ti.data(), biasPotential ));\n\n   std::cout << \"Completed Boundary Init \" << std::endl;\n  \n  //Efield\n  #if USEPRESHEATHEFIELD > 0    \n\n   std::cout << \"Using presheath Efield \" << std::endl;\n    #if PRESHEATH_INTERP == 0\n      int nR_PreSheathEfield = 1;\n      int nZ_PreSheathEfield = 1;\n      sim::Array<float> preSheathEGridr(nR_PreSheathEfield), preSheathEGridz(nZ_PreSheathEfield);\n      sim::Array<float> PSEr(nR_PreSheathEfield*nZ_PreSheathEfield), \n          PSEz(nR_PreSheathEfield*nZ_PreSheathEfield),\n          PSEt(nR_PreSheathEfield*nZ_PreSheathEfield);\n      PSEr[0] = cfg.lookup(\"backgroundPlasmaProfiles.Efield.Er\");\n      PSEz[0] = cfg.lookup(\"backgroundPlasmaProfiles.Efield.Ez\");\n      PSEt[0] = cfg.lookup(\"backgroundPlasmaProfiles.Efield.Et\");\n      std::cout << \"PSEz \" << PSEz[0] << std::endl;\n    #elif PRESHEATH_INTERP == 1\n    \n    int nR_PreSheathEfield=nR_Lc;\n    int nZ_PreSheathEfield=nZ_Lc;\n    sim::Array<float> preSheathEGridr=gridRLc;\n    sim::Array<float> preSheathEGridz=gridZLc;\n    int nPSEs = nR_Lc*nZ_Lc;\n    #if LC_INTERP == 3\n    int nY_PreSheathEfield=nY_Lc;\n    sim::Array<float> preSheathEGridy=gridYLc;\n    nPSEs = nR_Lc*nY_Lc*nZ_Lc;\n    #endif\n    std::cout << \"length of PSE vec \" << nPSEs << std::endl;\n    sim::Array<float> PSEr(nPSEs), PSEz(nPSEs),PSEt(nPSEs);\n    float teLocal1 = 0.0;\n    float BLocal1[3] = {0.0,0.0,0.0};\n    float Bnorm1[3] = {0.0,0.0,0.0};\n    float Bmag1 = 0.0;\n    int index1 = 0;\n    float absS1 = 0.0;\n    float Epar = 0.0;\n    for(int i=0;i<nR_Lc; i++)\n    {\n     #if LC_INTERP == 3\n     for(int k=0;k < nY_Lc; k++)\n     { thisY = flowVGridy[k];\n     #endif\n      for(int j=0;j<nZ_Lc;j++)\n      { \n        teLocal1 = interp2dCombined(gridRLc[i],0.0,gridZLc[j],nR_Temp,nZ_Temp, \n                &TempGridr.front(),&TempGridz.front(),&te.front());\n        interp2dVector(&BLocal1[0],gridRLc[i],0.0,gridZLc[j],nR_Bfield,\n                    nZ_Bfield,bfieldGridr.data(),bfieldGridz.data(),br.data(),bz.data(),by.data());\n        Bmag1 = sqrt(BLocal1[0]*BLocal1[0] + BLocal1[1]*BLocal1[1] + BLocal1[2]*BLocal1[2]);\n        Bnorm1[0] = BLocal1[0]/Bmag1;\n        Bnorm1[1] = BLocal1[1]/Bmag1;\n        Bnorm1[2] = BLocal1[2]/Bmag1;\n\n     #if LC_INTERP == 3\n        index1 = i+k*nR_Lc + j*nR_Lc*nY_Lc;\n        //std::cout << \"flowv calc index \" << index << std::endl;\n#else\n        index1 = i+j*nR_Lc;\n#endif\n        absS1 = abs(s[index1]);\n        Epar = teLocal1*(0.5*Lc[index1]/absS1/sqrt(0.25*Lc[index1]*Lc[index1]-absS1*absS1)-1.0/absS1);\n        if(std::isnan(Epar)) Epar = 0.0;\n        PSEr[index1] = sgn(s[index1])*Bnorm1[0]*Epar;\n        PSEt[index1] = sgn(s[index1])*Bnorm1[1]*Epar;\n        PSEz[index1] = sgn(s[index1])*Bnorm1[2]*Epar;\n      }\n     #if LC_INTERP == 3\n     }     \n#endif\n    }\n    sim::Array<float> PSErSub(nFlowVs), PSEzSub(nFlowVs),\n                        PSEySub(nFlowVs);\n\n    for(int i=0; i<nR_Lc;i++)\n    {\n        for(int j=0;j<nY_Lc;j++)\n        {\n            for(int k=0;k<nZ_Lc;k++)\n            {\n               index = i+j*nR_Lc + k*nR_Lc*nY_Lc;\n               if(noIntersectionNodes[index] ==1)\n               {\n                   surroundingMinimumR = 0.0;\n                   surroundingMinimumY = 0.0;\n                   surroundingMinimumZ = 0.0;\n                       for(int ii=i-1; ii<i+2;ii++)\n                       {\n                         for(int jj=j-1;jj<j+2;jj++)\n                         {\n                           for(int kk=k-1;kk<k+2;kk++)\n                           {\n                               iterIndex = ii+jj*nR_Lc + kk*nR_Lc*nY_Lc;\n                               if(iterIndex > 0 && iterIndex < nFlowVs)\n                               {\n                               if(noIntersectionNodes[iterIndex] ==0)\n                               {\n                                 if(abs(PSEr[iterIndex])>abs(surroundingMinimumR))\n                                 {\n                                   surroundingMinimumR = PSEr[iterIndex];\n                                 }\n                                 if(abs(PSEt[iterIndex])>abs(surroundingMinimumY))\n                                 {\n                                   surroundingMinimumY = PSEt[iterIndex];\n                                 }\n                                 if(abs(PSEz[iterIndex])>abs(surroundingMinimumZ))\n                                 {\n                                   surroundingMinimumZ = PSEz[iterIndex];\n                                 }\n                               }\n                               }\n                           }\n                         }\n                       }\n                  PSErSub[index] = surroundingMinimumR; \n                  PSEySub[index] = surroundingMinimumY; \n                  PSEzSub[index] = surroundingMinimumZ; \n\n               }\n            }\n        }\n    }\n    for(int i=0;i<nFlowVs;i++)\n    {\n            if(i ==282839)\n            {\n                std::cout<< \" noIntersectionNodes \" << noIntersectionNodes[i] << std::endl;\n            }\n               if(noIntersectionNodes[i] ==1)\n               {\n                  PSEr[i] =  PSErSub[i];\n                  PSEt[i] =  PSEySub[i];\n                  PSEz[i] =  PSEzSub[i];\n               }\n\n    }\n    #elif PRESHEATH_INTERP == 2\n      int nR_PreSheathEfield;\n      int nZ_PreSheathEfield;\n      \n      const char *PSEFile,*PSENr,*PSENz,*PSEGridR,\n                 *PSEGridZ,*PSErChar,*PSEzChar,*PSEtChar;\n      if(cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.fileString\", PSEFile) &&\n         cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.gridNrString\",PSENr) &&\n         cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.gridNzString\",PSENz) &&\n         cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.gridRString\",PSEGridR) &&\n         cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.gridZString\",PSEGridZ) &&\n         cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.radialComponentString\",PSErChar) &&\n         cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.axialComponentString\",PSEzChar) &&\n         cfg.lookupValue(\"backgroundPlasmaProfiles.Efield.toroidalComponentString\",PSEtChar))\n      { std::cout << \"PS Electric field file: \" << PSEFile << std::endl;}\n      else\n      { std::cout << \"ERROR: Could not get PSE string info from input file \" << std::endl;}\n      int e1 = read_profileNs(PSEfile,PSENr,PSENz,nR_PreSheathEfield,nZ_PreSheathEfield);\n      \n      sim::Array<float> preSheathEGridr(nR_PreSheathEfield), preSheathEGridz(nZ_PreSheathEfield);\n      sim::Array<float> PSEr(nR_PreSheathEfield*nZ_PreSheathEfield), \n          PSEz(nR_PreSheathEfield*nZ_PreSheathEfield),\n          PSEt(nR_PreSheathEfield*nZ_PreSheathEfield,0.0);\n      \n      int e2 = read_profile1d(PSEFile,PSEGridR, preSheathEGridr);\n      \n      int e3 = read_profile1d(PSEFile,PSEGridZ, preSheathEGridz);\n      \n      int e4 = read_profile2d(PSEFile,PSErChar, PSEr);\n      \n      int e5 = read_profile2d(PSEFile,PSEzChar, PSEz);\n      \n      //int e6 = read_profile2d(PSEFile,PSEtChar, PSEt);\n    #endif\n    \n    std::string outnamePSEfieldR = \"PSEfieldR.m\";\n    std::string outnamePSEfieldZ = \"PSEfieldZ.m\";\n    std::string outnamePSEGridR = \"PSEgridR.m\";\n    std::string outnamePSEGridZ = \"PSEgridZ.m\";\n    OUTPUT1d(profiles_folder,outnamePSEGridR, nR_PreSheathEfield, &preSheathEGridr.front());\n    OUTPUT1d(profiles_folder,outnamePSEGridZ, nZ_PreSheathEfield, &preSheathEGridz.front());\n     #if LC_INTERP == 3\n    OUTPUT3d(profiles_folder,outnamePSEfieldR, nR_PreSheathEfield,nY_PreSheathEfield, nZ_PreSheathEfield, &PSEr.front());\n    OUTPUT3d(profiles_folder,outnamePSEfieldZ, nR_PreSheathEfield,nY_PreSheathEfield, nZ_PreSheathEfield, &PSEz.front());\n     #else\n    OUTPUT2d(profiles_folder,outnamePSEfieldR, nR_PreSheathEfield, nZ_PreSheathEfield, &PSEr.front());\n    OUTPUT2d(profiles_folder,outnamePSEfieldZ, nR_PreSheathEfield, nZ_PreSheathEfield, &PSEz.front());\n     #endif  \n#else\n    \n      int nR_PreSheathEfield = 1;\n      int nY_PreSheathEfield = 1;\n      int nZ_PreSheathEfield = 1;\n      int closestBoundaryIndex;\n      sim::Array<float> preSheathEGridr(nR_PreSheathEfield),preSheathEGridy(nR_PreSheathEfield), preSheathEGridz(nZ_PreSheathEfield);\n      sim::Array<float> PSEr(nR_PreSheathEfield*nZ_PreSheathEfield), \n          PSEz(nR_PreSheathEfield*nZ_PreSheathEfield),\n          PSEt(nR_PreSheathEfield*nZ_PreSheathEfield);\n  #endif\n    \n  std::cout << \"Completed presheath Efield Init \" << std::endl;\n  sim::Array<float> Efieldr(nR_Bfield*nZ_Bfield), Efieldz(nR_Bfield*nZ_Bfield),\n                    Efieldt(nR_Bfield*nZ_Bfield),minDist(nR_Bfield*nZ_Bfield);\n\n  #if USESHEATHEFIELD > 0\n    #if EFIELD_INTERP == 1\n      float thisE[3] = {0.0,0.0,0.0};\n    \n      for(int i=0;i<nR_Bfield;i++)\n      {\n         for(int j=0;j<nZ_Bfield;j++)\n         {\n             minDist[(nR_Bfield - 1 -i)*nZ_Bfield+(nZ_Bfield -1-j)] = \n                  getE ( bfieldGridr[i], 0.0, bfieldGridz[j],\n                  thisE, boundaries.data(),nLines,closestBoundaryIndex );\n             Efieldr[i*nZ_Bfield+j] = thisE[0];\n             Efieldz[i*nZ_Bfield+j] = thisE[2];\n             Efieldt[i*nZ_Bfield+j] = thisE[1];\n          }\n      }\n        \n      int nR_closeGeom;\n      int nZ_dtsEfield;\n      \n      int d1 = read_profileNs(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                  cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridNrString\"),\n                  cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridNzString\"),nR_dtsEfield,nZ_dtsEfield);\n      \n      sim::Array<float> dtsEfieldGridr(nR_dtsEfield), dtsEfieldGridz(nZ_dtsEfield);\n      sim::Array<float> dtsE(nR_dtsEfield*nZ_dtsEfield);\n      \n      int d2 = read_profile1d(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                  cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridRString\"), dtsEfieldGridr);\n      \n      std::cout << \"got first grid \" << dtsEfieldGridr.front() << std::endl;    \n      int d3 = read_profile1d(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                  cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridZString\"), dtsEfieldGridz);\n      \n      std::cout << \"got second grid\" << dtsEfieldGridz.front() << std::endl;    \n      \n      int d4 = read_profile2d(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                  cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.sheathDTS\"), dtsE);\n    #elif EFIELD_INTERP ==2\n        int nR_dtsEfield, nZ_dtsEfield;\n        \n        int d1 = read_profileNs(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                    cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridNrString\"),\n                    cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridNzString\"),\n                    nR_dtsEfield,nZ_dtsEfield);\n        \n        sim::Array<float> dtsEfieldGridr(nR_dtsEfield), dtsEfieldGridz(nZ_dtsEfield);\n        sim::Array<float> dtsE(nR_dtsEfield*nZ_dtsEfield);\n        \n        int d2 = read_profile1d(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                    cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridRString\"), dtsEfieldGridr);\n        \n        int d3 = read_profile1d(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                    cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.gridZString\"), dtsEfieldGridz);\n        \n        int d4 = read_profile2d(cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.fileString\"),\n                    cfg.lookup(\"backgroundPlasmaProfiles.dtsEfield.sheathDTS\"), dtsE);\n    #endif\n  #else\n    int nR_dtsEfield=1;\n    int nZ_dtsEfield=1;\n    sim::Array<float> dtsEfieldGridr(nR_dtsEfield), dtsEfieldGridz(nZ_dtsEfield);\n    sim::Array<float> dtsE(nR_dtsEfield*nZ_dtsEfield);\n  #endif\n\n  std::string outnameEfieldR = \"EfieldR.m\";\n  std::string outnameEfieldZ = \"EfieldZ.m\";\n  std::string outnameEfieldT = \"EfieldT.m\";\n  std::string outnameMinDist = \"DistToSurface.m\";\n  OUTPUT2d(profiles_folder,outnameEfieldR, nR_Bfield, nZ_Bfield, &Efieldr.front());\n  OUTPUT2d(profiles_folder,outnameEfieldZ, nR_Bfield, nZ_Bfield, &Efieldz.front());\n  OUTPUT2d(profiles_folder,outnameEfieldT, nR_Bfield, nZ_Bfield, &Efieldt.front());\n  OUTPUT2d(profiles_folder,outnameMinDist, nR_Bfield, nZ_Bfield, &minDist.front());\n\n#if SPECTROSCOPY > 0\n    float netX0=0.0,netX1=0.0,netY0=0.0,netY1=0.0,netZ0=0.0,netZ1=0.0;\n    int net_nX=0,net_nY=0,net_nZ=0;\n    int nBins=0;\n\n    if(cfg.lookupValue(\"diagnostics.netx0\", netX0) && \n       cfg.lookupValue(\"diagnostics.netx1\", netX1) && \n       cfg.lookupValue(\"diagnostics.nety0\", netY0) && \n       cfg.lookupValue(\"diagnostics.nety1\", netY1) && \n       cfg.lookupValue(\"diagnostics.netz0\", netZ0) && \n       cfg.lookupValue(\"diagnostics.netz1\", netZ1) && \n       cfg.lookupValue(\"diagnostics.nX\", net_nX) && \n       cfg.lookupValue(\"diagnostics.nY\", net_nY) && \n       cfg.lookupValue(\"diagnostics.nZ\", net_nZ) && \n       cfg.lookupValue(\"diagnostics.densityChargeBins\", nBins))\n       {std::cout << \"Spectroscopy net imported\" << std::endl;}\n    else\n    { std::cout << \"ERROR: Could not get spectroscopy net string info from input file \" << std::endl;}\n    std::cout << \"spec bin Ns \" << net_nX << \" \" << net_nY << \" \" << net_nZ << std::endl; \n    #if SPECTROSCOPY < 3\n\n      sim::Array<float> net_Bins((nBins+1)*net_nX*net_nZ);\n    #else\n      sim::Array<float> net_Bins((nBins+1)*net_nX*net_nY*net_nZ);\n    #endif\n\n      /*\n      for (int i=0; i<nBins*net_nX*net_nZ; i++)\n          {\n              std::cout << \"i \" << i << std::endl;\n            net_Bins[i] = 0;\n              std::cout << \"net bins \" << net_Bins[i] << std::endl;\n            \n          }\n      */\n      sim::Array<float> gridX_bins(net_nX),gridY_bins(net_nY),gridZ_bins(net_nZ);\n\n      for (int i=0; i< net_nX ; i++)\n      {\n         gridX_bins[i] = netX0 + 1.0/(net_nX-1)*i*(netX1-netX0);\n      }\n      for (int i=0; i< net_nY ; i++)\n      {\n         gridY_bins[i] = netY0 + 1.0/(net_nY-1)*i*(netY1-netY0);\n      }\n\n      for (int i=0; i< net_nZ ; i++)\n      {\n         gridZ_bins[i] = netZ0 + i*1.0/(net_nZ-1)*(netZ1-netZ0);\n      }\n  #endif    \n\n  // Perp DiffusionCoeff initialization - only used when Diffusion interpolator is = 0\n  float perpDiffusionCoeff;\n  if (cfg.lookupValue(\"backgroundPlasmaProfiles.Diffusion.Dperp\",perpDiffusionCoeff))\n  {}\n  else\n  {std::cout << \"ERROR: could not get perpendicular diffusion coefficient from input file\" << std::endl;}\n\n  // Particle time stepping control\n  int ionization_nDtPerApply  = cfg.lookup(\"timeStep.ionization_nDtPerApply\");\n  int collision_nDtPerApply  = cfg.lookup(\"timeStep.collision_nDtPerApply\");\n\n  #ifdef __CUDACC__\n    cout<<\"Using THRUST\"<<endl;\n  #else\n    cout<<\"Not using THRUST\"<<endl;\n    int nthreads, tid;\n    #pragma omp parallel private(nthreads, tid)\n    {\n        nthreads = omp_get_num_threads();\n          tid = omp_get_thread_num();\n          if(tid == 0)\n          {\n              std::cout << \"N Threads \" << nthreads << std::endl;\n          }\n          std::cout << \"Hello world\" << tid << std::endl;\n    }\n        //nthreads = omp_get_num_threads();\n        nthreads = 24;\n        std::cout << \"N threads \" << nthreads << std::endl;\n    thrust::counting_iterator<std::size_t> ex0(0);  \n    thrust::counting_iterator<std::size_t> ex1(nthreads-1);\n                  thrust::for_each(thrust::device, ex0,ex1,\n                                   ompPrint());\n  #endif\n\n  float dt;\n  const int nP = cfg.lookup(\"impurityParticleSource.nP\");\n  long nParticles = nP;\n  int nT;\n\n  if (cfg.lookupValue(\"timeStep.dt\",dt) &&\n      cfg.lookupValue(\"timeStep.nT\",nT))    \n  {\n  cout << \"Number of time steps: \" << nT << \" With dt = \" << dt << endl; \n  cout << \"Number of particles: \" << nP << endl;              \n  }\n  else\n  {std::cout << \"ERROR: could not get nT, dt, or nP from input file\" << std::endl;}\n\n  auto particleArray = new Particles(nParticles);\n  \n  #if PARTICLE_SOURCE == 0\n    float x,y,z,Ex,Ey,Ez,amu,Z,charge;\n    if (cfg.lookupValue(\"impurityParticleSource.initialConditions.x_start\",x) &&\n        cfg.lookupValue(\"impurityParticleSource.initialConditions.y_start\",y) &&\n        cfg.lookupValue(\"impurityParticleSource.initialConditions.z_start\",z) &&\n        cfg.lookupValue(\"impurityParticleSource.initialConditions.energy_eV_x_start\",Ex) &&\n        cfg.lookupValue(\"impurityParticleSource.initialConditions.energy_eV_y_start\",Ey) &&\n        cfg.lookupValue(\"impurityParticleSource.initialConditions.energy_eV_z_start\",Ez) &&  \n        cfg.lookupValue(\"impurityParticleSource.initialConditions.impurity_amu\",amu) && \n        cfg.lookupValue(\"impurityParticleSource.initialConditions.impurity_Z\",Z) &&\n        cfg.lookupValue(\"impurityParticleSource.initialConditions.charge\",charge))\n    { std::cout << \"Impurity point source: \" << x << \" \" << y << \" \" << z << std::endl;\n    }\n    else\n    { std::cout << \"ERROR: Could not get point source impurity initial conditions\" << std::endl;}\n    \n    for (int i=0; i< nP ; i++)\n    {\n      particleArray->setParticle(i,x, y, z, Ex, Ey, Ez, Z, amu, charge);\n    }\n  #elif PARTICLE_SOURCE == 1\n    float x;\n    float y;\n    float z;\n    \n    float Ex;\n    float Ey;\n    float Ez;\n    \n    float amu;\n    float Z;\n    float charge;\n    float impurity_Z = cfg.lookup(\"impurityParticleSource.Z\");\n    int nImpurityBoundaries = 0;\n    for (int i=0; i<nLines;i++)\n    {\n        if(boundaries[i].Z == impurity_Z)\n        {\n            nImpurityBoundaries++;\n        }\n    }\n    std::cout << \"n Impurity Boundaries to launch from \" << nImpurityBoundaries << std::endl;\n    sim::Array<int> boundaryIndex_ImpurityLaunch(nImpurityBoundaries);\n    \n    int count = 0;\n    for (int i=0; i<nLines;i++)\n    {\n        if(boundaries[i].Z == impurity_Z)\n        {\n            boundaryIndex_ImpurityLaunch[count] = i;\n            count++;\n            std::cout << \"Boundary indices \" << i << std::endl;\n        }\n    }\n    \n    int impuritiesPerBoundary = nP/nImpurityBoundaries;\n      \n    std::uniform_real_distribution<float> distributionForSeeds(0,1e6);\n    #if FIXEDSEEDS ==0\n        std::random_device randDevice;\n        std::default_random_engine generator0(randDevice());\n    #else\n        float randDevice = 6.5298E+5;\n        std::default_random_engine generator0(randDevice);\n    #endif\n    \n    sim::Array<float> boundarySeeds0(4*nImpurityBoundaries);\n    std::generate( boundarySeeds0.begin(), boundarySeeds0.end(), [&]() { return distributionForSeeds(generator0); } );\n    std::uniform_real_distribution<float> dist01(0.0, 1.0);\n    float rand0 = 0.0;\n    float rand1 = 0.0;\n    float rand2 = 0.0;\n    float rand3 = 0.0;\n\n    sim::Array<std::mt19937> s0(4*nImpurityBoundaries);\n    \n    float E0 = 0.0;\n//Create Thompson Distribution\n    float surfaceBindingEnergy = cfg.lookup(\"impurityParticleSource.source_material_SurfaceBindingEnergy\");\n    std::cout << \"surface binding energy \" << surfaceBindingEnergy << std::endl;\n    int nThompDistPoints = 200;\n    float max_Energy = 100.0;\n    sim::Array<float> ThompsonDist(nThompDistPoints),CumulativeDFThompson(nThompDistPoints);\n    for(int i=0;i<nThompDistPoints;i++)\n        {\n            ThompsonDist[i] = (i*max_Energy/nThompDistPoints)/pow((i*max_Energy/nThompDistPoints) + surfaceBindingEnergy,3);\n            if(i==0)\n            {\n                CumulativeDFThompson[i] = ThompsonDist[i]; \n            }\n            else\n            {\n                CumulativeDFThompson[i] = CumulativeDFThompson[i-1]+ThompsonDist[i];\n            }\n        }\n    for(int i=0;i<nThompDistPoints;i++)\n        {\n            CumulativeDFThompson[i] = CumulativeDFThompson[i]/CumulativeDFThompson[nThompDistPoints-1];\n            //std::cout << \"energy and CDF\" << i*max_Energy/nThompDistPoints << \" \" << CumulativeDFThompson[i] << std::endl;\n        }\n\n    for(int j=0; j<4*nImpurityBoundaries;j++)\n        {\n            std::mt19937  s(boundarySeeds0[j]);\n            s0[j] = s;\n        }\n    // Particle p1(0.0,0.0,0.0,0.0,0.0,0.0,0,0.0);\n    for (int i=0; i< nImpurityBoundaries;i++)\n    {\n        for(int j=0; j<impuritiesPerBoundary; j++)\n        {\n            //Set boundary interval, properties, and random number gen\n        if (i==0)\n        {\n            rand0 = dist01(s0[0]);\n            x = boundaries[boundaryIndex_ImpurityLaunch[i]].x1 + \n                boundaries[boundaryIndex_ImpurityLaunch[i]].length*rand0;//1.4290;\n            //std::cout << \"start pos 1 \" << x << std::endl;\n            z = -1.2540+0.00001;\n            rand1 = dist01(s0[1]);\n            rand2 = dist01(s0[2]);\n            rand3 = dist01(s0[3]);\n            E0 = interp1dUnstructured(rand2,nThompDistPoints, max_Energy, &CumulativeDFThompson.front());\n            Ex = E0*cos(3.1415*rand1)*sin(3.1415*rand3);\n            Ey = E0*cos(3.1415*rand3);\n            Ez = E0*sin(3.1415*rand1)*sin(3.1415*rand3);\n        }\n        else\n        {\n            rand0 = dist01(s0[4]);\n            x = boundaries[boundaryIndex_ImpurityLaunch[i]].x1 + boundaries[boundaryIndex_ImpurityLaunch[i]].length*rand0;\n            //x = 1.3450;\n            //std::cout << \"start pos 2 \" << x << std::endl;\n            z = -1.3660+0.00001;\n            rand1 = dist01(s0[5]);\n            rand2 = dist01(s0[6]);\n            rand3 = dist01(s0[7]);\n            E0 = interp1dUnstructured(rand2,nThompDistPoints, max_Energy, &CumulativeDFThompson.front());\n            Ex = E0*cos(3.1415*rand1)*sin(3.1415*rand3);\n            Ey = E0*cos(3.1415*rand3);\n            Ez = E0*sin(3.1415*rand1)*sin(3.1415*rand3);\n        }\n        particleArray->setParticle((i * impuritiesPerBoundary + j),x, 0.0, z, Ex, Ey, Ez, 74, 18400.0, charge);            \n        }\n    }\n  #elif PARTICLE_SOURCE == 2\n    std::cout << \"Read particle source \" << std::endl;\n    Config cfg_particles;\n    cfg_particles.readFile(\"particleSource.cfg\");\n    Setting& particleSource = cfg_particles.lookup(\"particleSource\");\n    std::cout << \"found setting particleSource \" << std::endl;\n    float rSample;\n    float angleSample;\n    float x;\n    float y;\n    float z;\n    \n    float Vr;\n    float Vx;\n    float Vy;\n    float Vz;\n    float V0;\n    float E0;\n    float amu;\n    float Z;\n    float charge= cfg.lookup(\"impurityParticleSource.initialConditions.charge\");\n    float impurity_Z = cfg.lookup(\"impurityParticleSource.Z\");\n    int nSources = particleSource[\"nSources\"];\n    int nSegments = particleSource[\"nSegments\"];\n    int nSegmentsAngle = particleSource[\"nSegmentsAngle\"];\n    int cylSymm = particleSource[\"cylSymm\"];\n    \n    sim::Array<float> sourceR(2*nSources);\n    sim::Array<float> sourceZ(2*nSources);\n    sim::Array<float> sourceRsegments(nSegments);\n    sim::Array<float> sourceZsegments(nSegments);\n    sim::Array<float> spaceCDF(nSegments);\n    sim::Array<float> sourceAngleSegments(nSegmentsAngle);\n    sim::Array<float> angleCDF(nSegmentsAngle);\n    \n    for (int i=0; i<(nSources*2); i++)\n    {\n        sourceR[i] = particleSource[\"r0\"][i];\n        sourceZ[i] = particleSource[\"z0\"][i];\n    }\n    \n    for (int i=0; i<(nSegments); i++)\n    {\n        sourceRsegments[i] = particleSource[\"r\"][i];\n        sourceZsegments[i] = particleSource[\"z\"][i];\n        spaceCDF[i] = particleSource[\"spaceCDF\"][i];\n    }\n    \n    for (int i=0; i<(nSegmentsAngle); i++)\n    {\n        sourceAngleSegments[i] = particleSource[\"angles\"][i];\n        angleCDF[i] = particleSource[\"angleCDF\"][i];\n    }\n    std::uniform_real_distribution<float> dist01(0.0, 1.0);\n    float rand0 = 0.0;\n    float rand1 = 0.0;\n    float rand2 = 0.0;\n    float rand3 = 0.0;\n    float rand4 = 0.0;\n\n    sim::Array<std::mt19937> s0(5);\n    std::mt19937 ss0(123314.234);\n     s0[0] =  ss0;\n    std::mt19937 ss1(389362.735);\n     s0[1] =  ss1;\n    std::mt19937 ss2(523563.108);\n     s0[2] =  ss2;\n    std::mt19937 ss3(752081.751);\n     s0[3] =  ss3;\n    std::mt19937 ss4(952381.034);\n     s0[4] =  ss4;\n\n    float surfaceBindingEnergy = cfg.lookup(\"impurityParticleSource.source_material_SurfaceBindingEnergy\");\n    std::cout << \"surface binding energy \" << surfaceBindingEnergy << std::endl;\n    int nThompDistPoints = 200;\n    float max_Energy = 100.0;\n    sim::Array<float> ThompsonDist(nThompDistPoints),CumulativeDFThompson(nThompDistPoints);\n    for(int i=0;i<nThompDistPoints;i++)\n    {\n       ThompsonDist[i] = (i*max_Energy/nThompDistPoints)/pow((i*max_Energy/nThompDistPoints) + surfaceBindingEnergy,3);\n       if(i==0)\n       {\n           CumulativeDFThompson[i] = ThompsonDist[i]; \n       }\n       else\n       {\n           CumulativeDFThompson[i] = CumulativeDFThompson[i-1]+ThompsonDist[i];\n       }\n    }\n    for(int i=0;i<nThompDistPoints;i++)\n    {\n       CumulativeDFThompson[i] = CumulativeDFThompson[i]/CumulativeDFThompson[nThompDistPoints-1];\n       //std::cout << \"energy and CDF\" << i*max_Energy/nThompDistPoints << \" \" << CumulativeDFThompson[i] << std::endl;\n    }\n\n    //rand0 = dist01(s0[0]);\n    //rand1 = dist01(s0[1]);\n    //rand2 = dist01(s0[2]);\n    //rand3 = dist01(s0[3]);\n    sim::Array<float> angleBins(180);\n    int angleBinNum = 0;\n    sim::Array<float> angleBins2(180);\n    int angleBinNum2 = 0;\n    int closestBoundaryIndex0;\n    float minDist0;\n    float thisE0[3] = {0.0,0.0,0.0};\n    for(int j=0; j<nParticles ; j++)\n    {\n      rand0 = dist01(s0[0]);\n      rSample = interp1dUnstructured2(rand0,nSegments,&sourceRsegments.front() , &spaceCDF.front());\n      rand4 = dist01(s0[4]);\n      x = rSample*cos(rand4*2.0*3.1415);\n      y = rSample*sin(rand4*2.0*3.1415);\n      z = sourceZ[0];\n      rand1 = dist01(s0[1]);\n      E0 = interp1dUnstructured(rand1,nThompDistPoints, max_Energy, &CumulativeDFThompson.front());\n      V0 = sqrt(2*E0*1.602e-19/(184.0*1.66e-27));\n      rand2 = dist01(s0[2]);\n      angleSample = interp1dUnstructured2(rand2,nSegmentsAngle,&sourceAngleSegments.front() , &angleCDF.front());\n      angleBinNum=floor(angleSample*180/3.1415);\n      angleBins[angleBinNum] = angleBins[angleBinNum]+1;\n      //std::cout << angleSample << std::endl;\n      //Ey = //E0*cos(angleSample)*sin(2.0*3.1415*rand3);\n      Vz = V0*cos(angleSample);\n      Vr = V0*sin(angleSample);//cos(2.0*3.1415*rand3)\n      //std::cout << \"Ez \" << Ez << \" Er \" << Er << std::endl; \n      rand3 = dist01(s0[3]);\n      //rand3 = j*1.0/nParticles;\n      Vx = Vr*cos(2.0*3.1415*rand3);\n      Vy = Vr*sin(2.0*3.1415*rand3);//E0*cos(angleSample)*sin(2.0*3.1415*rand3);\n      angleBinNum2=floor(rand3*180.0);\n      angleBins2[angleBinNum2] = angleBins2[angleBinNum2]+1;\n      //std::cout << \"rsample \" << rSample << \" E0 \" << E0 << \" angleSample \" << angleSample << std::endl;\n    particleArray->setParticleV(j,x,y,z,Vx,Vy,Vz,74, 184.0, charge);\n       minDist0 = getE ( x,y,z,thisE0, boundaries.data(),nLines,\n\n                        nR_closeGeom_sheath,nY_closeGeom_sheath,nZ_closeGeom_sheath,n_closeGeomElements_sheath,\n                        &closeGeomGridr_sheath.front(),&closeGeomGridy_sheath.front(),&closeGeomGridz_sheath.front(),\n                        &closeGeom_sheath.front(),\n                  closestBoundaryIndex0 );\n       //std::cout << \"closest Boundary \" << x << \" \" << y << \" \" << z <<\" \" \n       //          << closestBoundaryIndex0 << std::endl;\n       boundaries[closestBoundaryIndex0].startingParticles = boundaries[closestBoundaryIndex0].startingParticles + 1.0;\n    }\n  #endif\n\n  std::cout << \"finished loading particle source\" << std::endl;\n  #if USESURFACEMODEL > 0\n    //import text file\n      std::vector<float> spylGridE,spylGridAngle,spylGridRoughness,spyl;\n      std::string line;\n      std::string delimiter = \" \";\n      size_t pos = 0;\n      std::string token;\n      ifstream myfile (\"cumulativeEA.txt\");\n      int counter = 0;\n      int header = 0;\n      if (myfile.is_open())\n      {\n        while ( getline (myfile,line) )\n        {\n          cout << line << '\\n';\n          counter = 0;\n          if(header == 0)\n          {\n              header++;\n          }\n          else\n          {\n            while ((pos = line.find(delimiter)) != std::string::npos) \n            {\n                  token = line.substr(0, pos);\n                  if(token.empty()){}\n                  else\n                  {    \n                      counter++;\n                      std::cout <<counter << \" \" << token << std::endl;\n                      if(header == 1)\n                      {\n                        spylGridE.push_back(atof(token.c_str()));\n                      }\n                      else if(header == 2)\n                      {\n                        spylGridAngle.push_back(atof(token.c_str()));\n                      }\n                      else if (header == 3)\n                      {\n                        spylGridRoughness.push_back(atof(token.c_str()));\n                      }\n                      else{\n                      if(counter == 1)\n                      {  \n                        //spylGridE.push_back(atof(token.c_str()));\n                      }\n                      else if(counter==2)\n                      {\n                        //spylGridAngle.push_back(atof(token.c_str()));\n                      }\n                      else if(counter==3)\n                      {\n                        //spylGridRoughness.push_back(atof(token.c_str()));\n                      }\n                      else if(counter==4)\n                      {\n                        spyl.push_back(atof(token.c_str()));\n                      }\n                      }\n                  }\n                          line.erase(0, pos + delimiter.length());\n            }\n            header++;\n          }\n          std::cout << line << std::endl;\n        }\n        myfile.close();\n      }\n\n      else cout << \"Unable to open file\";\n\n      for(int i=0;i<spylGridE.size();i++)\n      {\n          std::cout << \"spylGridE \" << spylGridE[i] << std::endl;\n          //std::cout << \"spylGrida \" << spylGridAngle[i] << std::endl;\n          //std::cout << \"spylGridr \" << spylGridRoughness[i] << std::endl;\n          //std::cout << \"spyl \" << spyl[i] << std::endl;\n      }\n      for(int i=0;i<spylGridAngle.size();i++)\n      {\n          //std::cout << \"spylGridE \" << spylGridE[i] << std::endl;\n          std::cout << \"spylGrida \" << spylGridAngle[i] << std::endl;\n          //std::cout << \"spylGridr \" << spylGridRoughness[i] << std::endl;\n          //std::cout << \"spyl \" << spyl[i] << std::endl;\n      }\n      for(int i=0;i<spylGridRoughness.size();i++)\n      {\n          //std::cout << \"spylGridE \" << spylGridE[i] << std::endl;\n          //std::cout << \"spylGrida \" << spylGridAngle[i] << std::endl;\n          std::cout << \"spylGridr \" << spylGridRoughness[i] << std::endl;\n          //std::cout << \"spyl \" << spyl[i] << std::endl;\n      }\n      int nAngle = spylGridAngle.size();\n      int nEnergy = spylGridE.size();\n      //std::cout << \"interp spyl \" << spyl[2+1*nAngle] << \" \" << spyl[1] << std::endl;\n      //float temp21 = 0.0;\n      //temp21 = interp2dUnstructured(15.0,120.0,nAngle,nEnergy, \n      //        &spylGridAngle.front(),&spylGridE.front(), &spyl.front());\n      //std::cout << \"interp spyl 15, 120 \" << temp21 << std::endl;\n      sim::Array<float> spYlGridAngle(nAngle);\n      sim::Array<float> spYlGridE(nEnergy);\n      sim::Array<float> spYl(nAngle*nEnergy);\n      for(int i=0;i<nAngle;i++)\n      {\n        spYlGridAngle[i] = spylGridAngle[i];\n      }\n      for(int i=0;i<nEnergy;i++)\n      {\n        spYlGridE[i] = spylGridE[i];\n      }\n      for(int i=0;i<nAngle*nEnergy;i++)\n      {\n        spYl[i] = spyl[i];\n      }\n      //spYlGridAngle = spylGridAngle;\n      //spYlGridE = spYlGridE;\n      //spYl = spyl;\n  #endif\n\n  #if GEOM_TRACE > 0       \n    std::uniform_real_distribution<float> dist2(0,1);\n    //std::random_device rd2;\n    //std::default_random_engine generator2(rd2());\n    float randDevice02 = 6.52E+5;\n    std::default_random_engine generator2(randDevice02);\n    std::cout << \"Randomizing velocities to trace geometry. \" << std::endl;\n\n    for (int i=0 ; i<nParticles ; i++)\n    {   float theta = dist2(generator2)*2*3.1415;\n        float phi = dist2(generator2)*3.1415;\n        float mag = 2e3;\n        particleArray->vx[i] = mag*cos(theta)*sin(phi);\n        particleArray->vy[i] = mag*sin(theta)*sin(phi);\n        particleArray->vz[i] = mag*cos(phi);\n    }\n  #endif\n\n  #if PARTICLE_TRACKS > 0\n    int subSampleFac = 1;\n    #if USE_CUDA > 0\n      sim::Array<float> positionHistoryX(nP*nT/subSampleFac);\n      sim::Array<float> positionHistoryY(nP*nT/subSampleFac);\n      sim::Array<float> positionHistoryZ(nP*nT/subSampleFac);\n      sim::Array<float> velocityHistoryX(nP*nT/subSampleFac);\n      sim::Array<float> velocityHistoryY(nP*nT/subSampleFac);\n      sim::Array<float> velocityHistoryZ(nP*nT/subSampleFac);\n      sim::Array<float> chargeHistory(nP*nT/subSampleFac);\n    #else\n      float **positionHistoryX;\n      float **positionHistoryY;\n      float **positionHistoryZ;\n      float **velocityHistoryX;\n      float **velocityHistoryY;\n      float **velocityHistoryZ;\n      float **chargeHistory;\n      positionHistoryX = new float* [nP];\n      positionHistoryY = new float* [nP];\n      positionHistoryZ = new float* [nP];\n      velocityHistoryX = new float* [nP];\n      velocityHistoryY = new float* [nP];\n      velocityHistoryZ = new float* [nP];\n      chargeHistory = new float* [nP];\n      positionHistoryX[0] = new float [nT*nP/subSampleFac];\n      positionHistoryY[0] = new float [nT*nP/subSampleFac];\n      positionHistoryZ[0] = new float [nT*nP/subSampleFac];\n      velocityHistoryX[0] = new float [nT*nP/subSampleFac];\n      velocityHistoryY[0] = new float [nT*nP/subSampleFac];\n      velocityHistoryZ[0] = new float [nT*nP/subSampleFac];\n      chargeHistory[0] = new float [nT*nP/subSampleFac];\n      for(int i=0 ; i<nP ; i++)\n      {\n          positionHistoryX[i] = &positionHistoryX[0][i*nT/subSampleFac];\n          positionHistoryY[i] = &positionHistoryY[0][i*nT/subSampleFac];\n          positionHistoryZ[i] = &positionHistoryZ[0][i*nT/subSampleFac];\n          velocityHistoryX[i] = &velocityHistoryX[0][i*nT/subSampleFac];\n          velocityHistoryY[i] = &velocityHistoryY[0][i*nT/subSampleFac];\n          velocityHistoryZ[i] = &velocityHistoryZ[0][i*nT/subSampleFac];\n          chargeHistory[i] = &chargeHistory[0][i*nT/subSampleFac];\n          for(int j=0 ; j<nT/subSampleFac ; j++)\n          {\n              positionHistoryX[i][j] = 0.0;\n              positionHistoryY[i][j] = 0.0;\n              positionHistoryZ[i][j] = 0.0;\n              velocityHistoryX[i][j] = 0.0;\n              velocityHistoryY[i][j] = 0.0;\n              velocityHistoryZ[i][j] = 0.0;\n              chargeHistory[i][j] = 0.0;\n          }\n      }\n    #endif\n  #endif \n  float* finalPosX = new float[nP];\n  float* finalPosY = new float[nP];\n  float* finalPosZ = new float[nP];\n  float* finalVx = new float[nP];\n  float* finalVy = new float[nP];\n  float* finalVz = new float[nP];\n  float* transitTime = new float[nP];\n  float* hitWall = new float[nP];\n  #if USE_BOOST\n    //cpu_timer timer;\n  #endif\n\n  std::cout << \"beginning seeds\" << std::endl;\n  std::uniform_real_distribution<float> dist(0,1e6);\n\n  #if FIXEDSEEDS == 0\n    std::random_device rd;\n    std::default_random_engine generator(rd());\n    std::default_random_engine generator1(rd());\n    std::default_random_engine generator2(rd());\n    std::default_random_engine generator3(rd());\n    std::default_random_engine generator4(rd());\n    std::default_random_engine generator5(rd());\n    std::default_random_engine generator6(rd());\n  #endif\n\n  thrust::counting_iterator<std::size_t> particleBegin(0);  \n  thrust::counting_iterator<std::size_t> particleEnd(nParticles);\n\n  #if PARTICLESEEDS > 0\n    #if USEIONIZATION > 0\n      #if FIXEDSEEDS ==1\n        std::cout << \"ionization fixed seeds\" << std::endl;\n        float ionization_seeds = cfg.lookup(\"operators.ionization.seed\");\n        std::default_random_engine generator(ionization_seeds);\n      #endif\n      sim::Array<float> seeds0(nP);\n      std::generate( seeds0.begin(), seeds0.end(), [&]() { return dist(generator); } );\n      thrust::transform(thrust::device, particleArray->streams.begin(),  \n                        particleArray->streams.end(),seeds0.begin(), \n                        particleArray->streams.begin(), randInit(0) );\n    #endif\n\n    #if USERECOMBINATION > 0\n      #if FIXEDSEEDS ==1\n        std::cout << \"recombination fixed seeds\" << std::endl;\n        float recombination_seeds = cfg.lookup(\"operators.recombination.seed\");\n        std::cout << \"recombination fixed seeds middle\" << std::endl;\n        std::default_random_engine generator1(recombination_seeds);\n        std::cout << \"recombination fixed seeds end\" << std::endl;\n      #endif\n      sim::Array<float> seeds1(nP);\n      std::cout << \"generate\" << std::endl;\n      #if __CUDACC__\n        cudaDeviceSynchronize();\n      #endif\n      std::generate( seeds1.begin(), seeds1.end(), [&]() { return dist(generator1); } );\n      std::cout << \"transform\" << std::endl;\n      #if __CUDACC__\n        cudaDeviceSynchronize();\n      #endif\n      thrust::transform(thrust::device,particleArray->streams_rec.begin(), particleArray->streams_rec.end(),\n                    seeds1.begin(), particleArray->streams_rec.begin(), randInit(1) );\n      std::cout << \"finished transform\" << std::endl;\n    #endif\n\n    #if USEPERPDIFFUSION > 0\n      #if FIXEDSEEDS ==1\n        std::cout << \"diffusion fixed seeds\" << std::endl;\n        float diffusion_seeds = cfg.lookup(\"operators.perpDiffusion.seed\");\n        std::default_random_engine generator2(diffusion_seeds);\n      #endif\n      sim::Array<float> seeds2(nP);\n#if USE_CUDA  \n      cudaDeviceSynchronize();\n#endif\n      std::generate( seeds2.begin(), seeds2.end(), [&]() { return dist(generator2); } );\n      #if __CUDACC__\n        cudaDeviceSynchronize();\n      #endif\n      thrust::transform(thrust::device,particleArray->streams_diff.begin(), particleArray->streams_diff.end(),\n                    seeds2.begin(), particleArray->streams_diff.begin(), randInit(2) );\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n#endif\n\n    #if USECOULOMBCOLLISIONS > 0\n      #if FIXEDSEEDS ==1\n        std::cout << \"collision fixed seeds\" << std::endl;\n        float collision_seeds1 = cfg.lookup(\"operators.coulombCollisions.seed1\");\n        float collision_seeds2 = cfg.lookup(\"operators.coulombCollisions.seed2\");\n        float collision_seeds3 = cfg.lookup(\"operators.coulombCollisions.seed3\");\n        std::cout << \"debug 1\" << std::endl;\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::default_random_engine generator3(collision_seeds1);\n        std::cout << \"debug 2\" << std::endl;\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::default_random_engine generator4(collision_seeds2);\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::cout << \"debug 3\" << std::endl;\n        std::default_random_engine generator5(collision_seeds3);\n      #endif\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::cout << \"debug 4\" << std::endl;\n      sim::Array<float> seeds3(nP),seeds4(nP),seeds5(nP);\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::generate( seeds3.begin(), seeds3.end(), [&]() { return dist(generator3); } );\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::generate( seeds4.begin(), seeds4.end(), [&]() { return dist(generator4); } );\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::generate( seeds5.begin(), seeds5.end(), [&]() { return dist(generator5); } );\n#if USE_CUDA  \n      cudaDeviceSynchronize();\n#endif\n      std::cout << \"debug 5\" << std::endl;\n      thrust::transform(thrust::device,particleArray->streams_collision1.begin(), \n                                       particleArray->streams_collision1.end(),\n                                       seeds3.begin(), \n                                       particleArray->streams_collision1.begin(), randInit(3) );\n        std::cout << \"debug 6\" << std::endl;\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        thrust::transform(thrust::device,particleArray->streams_collision2.begin(), \n                                       particleArray->streams_collision2.end(),\n                                       seeds4.begin(),\n                                       particleArray->streams_collision2.begin(), randInit(4) );\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::cout << \"debug 7\" << std::endl;\n#if USE_CUDA  \n      cudaDeviceSynchronize();\n#endif\n      thrust::transform(thrust::device,particleArray->streams_collision3.begin(),\n                                       particleArray->streams_collision3.end(),\n                                       seeds5.begin(), \n                                       particleArray->streams_collision3.begin(), randInit(5) );\n#if USE_CUDA  \n        cudaDeviceSynchronize();\n#endif\n        std::cout << \"debug 8\" << std::endl;\n    #endif\n   std::cout<< \"finished collision seeds\" << std::endl;\n    #if USESURFACEMODEL > 0\n      #if FIXEDSEEDS ==1\n        std::cout << \"surface model fixed seeds\" << std::endl;\n        float surface_seeds = cfg.lookup(\"operators.surfaceModel.seed\");\n        std::default_random_engine generator6(surface_seeds);\n      #endif\n      sim::Array<float> seeds6(nP);\n#if USE_CUDA  \n      cudaDeviceSynchronize();\n#endif\n      std::generate( seeds6.begin(), seeds6.end(), [&]() { return dist(generator6); } );\n#if USE_CUDA  \n      cudaDeviceSynchronize();\n#endif\n      thrust::transform(thrust::device,particleArray->streams_surf.begin(), particleArray->streams_surf.end(),\n                    seeds6.begin(), particleArray->streams_surf.begin(), randInit(6) );\n#if USE_CUDA  \n      cudaDeviceSynchronize();\n#endif\n#endif\n\n    std::cout << \"at empty defns\" << std::endl;\n    #if __CUDACC__\n      sim::Array<curandState> state1(7);//Definition empty for passing to module\n    #else\n      sim::Array<std::mt19937> state1(7);//Empty definition\n    #endif\n\n    std::cout << \"finished empty defns\" << std::endl;\n  #else //ParticleSeeds == 0\n\n    #if __CUDACC__\n      sim::Array<curandState> state1(9);\n      curandInitialize<<<1,1>>>(&state1[0],19);\n      curandInitialize<<<1,1>>>(&state1[1],25);\n      curandInitialize<<<1,1>>>(&state1[2],32);\n      curandInitialize<<<1,1>>>(&state1[3],39);\n      curandInitialize<<<1,1>>>(&state1[4],43);\n      curandInitialize<<<1,1>>>(&state1[5],48);\n      curandInitialize<<<1,1>>>(&state1[6],51);\n      curandInitialize<<<1,1>>>(&state1[7],56);\n      curandInitialize<<<1,1>>>(&state1[8],60);\n    #else\n      sim::Array<std::mt19937> state1(9);\n      std::mt19937 s0(348763);\n      std::mt19937 s1(358763);\n      std::mt19937 s2(346763);\n      std::mt19937 s3(348263);\n      std::mt19937 s4(349763);\n      std::mt19937 s5(318763);\n      std::mt19937 s6(448763);\n      std::mt19937 s7(448963);\n      std::mt19937 s8(463763);\n      state1[0] = s0;\n      state1[1] = s1;\n      state1[2] = s2;\n      state1[3] = s3;\n      state1[4] = s4;\n      state1[5] = s5;\n      state1[6] = s6;\n      state1[7] = s7;\n      state1[8] = s8;\n    #endif\n  #endif\n\n    std::cout << \"at movetime\" << std::endl;\n    float moveTime = 0.0;\n    float geomCheckTime = 0.0;\n    float ionizTime = 0.0;\n\n#if USE_BOOST\n    //cpu_times copyToDeviceTime = timer.elapsed();\n    //std::cout << \"Initialize rand state and copyToDeviceTime: \" << copyToDeviceTime.wall*1e-9 << '\\n';\n#endif\n    typedef std::chrono::high_resolution_clock Time;\n    typedef std::chrono::duration<float> fsec;\n    auto start_clock = Time::now();\n    std::cout << \"Starting main loop\" << std::endl;\n    //std:: cout << \"particle value \" << particleArray->hitWall[0] << std::endl;\n//Main time loop\n    #if __CUDACC__\n      cudaDeviceSynchronize();\n    #endif\n    for(int tt=0; tt< nT; tt++)\n    {\n#ifdef __CUDACC__\n    cudaThreadSynchronize();\n#endif\n        thrust::for_each(thrust::device, particleBegin,particleEnd, \n                move_boris(particleArray,dt,boundaries.data(), nLines,\n                    nR_Bfield,nZ_Bfield, bfieldGridr.data(),&bfieldGridz.front(),\n                    &br.front(),&bz.front(),&by.front(),\n                    nR_PreSheathEfield,nY_PreSheathEfield,nZ_PreSheathEfield,\n                    &preSheathEGridr.front(),&preSheathEGridy.front(),&preSheathEGridz.front(),\n                    &PSEr.front(),&PSEz.front(),&PSEt.front(),\n                        nR_closeGeom_sheath,nY_closeGeom_sheath,nZ_closeGeom_sheath,n_closeGeomElements_sheath,\n                        &closeGeomGridr_sheath.front(),&closeGeomGridy_sheath.front(),&closeGeomGridz_sheath.front(),\n                        &closeGeom_sheath.front()) );\n        \n        \n        //try {\n            thrust::for_each(thrust::device, particleBegin,particleEnd,\n                    geometry_check(particleArray,nLines,&boundaries[0],dt,tt,\n                        nR_closeGeom,nY_closeGeom,nZ_closeGeom,n_closeGeomElements,\n                        &closeGeomGridr.front(),&closeGeomGridy.front(),&closeGeomGridz.front(),\n                        &closeGeom.front()) );\n       // }\n       /*\n            catch (thrust::system_error &e) {\n            std::cerr << \"Thrust system error: \" << e.what() << std::endl;\n            exit(-1);\n        }\n        */\n#if SPECTROSCOPY > 0\n            thrust::for_each(thrust::device, particleBegin,particleEnd,\n                    spec_bin(particleArray,nBins,net_nX,net_nY, net_nZ, &gridX_bins.front(),&gridY_bins.front(),\n                        &gridZ_bins.front(), &net_Bins.front(),dt) );\n#endif            \n#if USEIONIZATION > 0\n        thrust::for_each(thrust::device, particleBegin,particleEnd,\n                ionize(particleArray, dt,&state1.front(),\n                    nR_Dens,nZ_Dens,&DensGridr.front(),&DensGridz.front(),&ne.front(),  \n                    nR_Temp,nZ_Temp,&TempGridr.front(),&TempGridz.front(),&te.front(),\n                    nTemperaturesIonize, nDensitiesIonize,&gridTemperature_Ionization.front(),\n                    &gridDensity_Ionization.front(), &rateCoeff_Ionization.front(),tt));\n#endif\n#if USERECOMBINATION > 0\n        thrust::for_each(thrust::device, particleBegin,particleEnd,\n                recombine(particleArray, dt,&state1.front(),\n                    nR_Dens,nZ_Dens,&DensGridr.front(),&DensGridz.front(),&ne.front(),  \n                    nR_Temp,nZ_Temp,&TempGridr.front(),&TempGridz.front(),&te.front(),\n                    nTemperaturesRecombine,nDensitiesRecombine,\n                    gridTemperature_Recombination.data(),gridDensity_Recombination.data(),\n                    rateCoeff_Recombination.data(),tt));\n#endif\n#if USEPERPDIFFUSION > 0\n        thrust::for_each(thrust::device,particleBegin, particleEnd,\n                crossFieldDiffusion(particleArray,dt,&state1.front(),perpDiffusionCoeff,\n                    nR_Bfield,nZ_Bfield,bfieldGridr.data(),&bfieldGridz.front(),\n                                        &br.front(),&bz.front(),&by.front()));\n            \n            thrust::for_each(thrust::device, particleBegin,particleEnd,\n                    geometry_check(particleArray,nLines,&boundaries[0],dt,tt,\n                        nR_closeGeom,nY_closeGeom,nZ_closeGeom,n_closeGeomElements,\n                        &closeGeomGridr.front(),&closeGeomGridy.front(),&closeGeomGridz.front(),\n                        &closeGeom.front()) );\n#endif\n#if USECOULOMBCOLLISIONS > 0\n        thrust::for_each(thrust::device, particleBegin, particleEnd, \n                coulombCollisions(particleArray,dt,&state1.front(),\n                    nR_flowV,nZ_flowV,&flowVGridr.front(),&flowVGridz.front(),\n                    &flowVr.front(),&flowVz.front(),&flowVt.front(),\n                    nR_Dens,nZ_Dens,&DensGridr.front(),&DensGridz.front(),&ne.front(),    \n                    nR_Temp,nZ_Temp,&TempGridr.front(),&TempGridz.front(),&te.front(),\n                    background_Z,background_amu, \n                    nR_Bfield,nZ_Bfield,bfieldGridr.data(),&bfieldGridz.front(),\n                                        &br.front(),&bz.front(),&by.front()));\n\n#endif\n#if USETHERMALFORCE > 0\n        thrust::for_each(thrust::device,particleBegin, particleEnd,\n                thermalForce(particleArray,dt,background_amu,\n                    nR_gradT,nZ_gradT,gradTGridr.data(),gradTGridz.data(),\n                    gradTiR.data(),gradTiZ.data(), gradTiT.data(), \n                    gradTeR.data(), gradTeZ.data(), gradTeT.data(), \n                    nR_Bfield,nZ_Bfield, bfieldGridr.data(),&bfieldGridz.front(),\n                    &br.front(),&bz.front(),&by.front()));\n#endif\n\n#if USESURFACEMODEL > 0\n        thrust::for_each(thrust::device,particleBegin, particleEnd, \n                reflection(particleArray,dt,&state1.front(),nLines,&boundaries[0],nAngle,nEnergy,\n                      spYlGridAngle.data(),\n                            spYlGridE.data(), \n                                  spYl.data(),nSegmentsAngle,&sourceAngleSegments.front() , &angleCDF.front(),\n                   nThompDistPoints, max_Energy, &CumulativeDFThompson.front() ) );\n#endif        \n\n#if PARTICLE_TRACKS >0\n#if USE_CUDA > 0\n   thrust::for_each(thrust::device, particleBegin,particleEnd,\n      history(particleArray,tt,subSampleFac,nP,&positionHistoryX.front(),\n      &positionHistoryY.front(),&positionHistoryZ.front(),\n      &velocityHistoryX.front(),&velocityHistoryY.front(),\n      &velocityHistoryZ.front(),&chargeHistory.front()) );\n#else\nif (tt % subSampleFac == 0)  \n{    \n        for(int i=0;i<nP;i++)\n        {\n            positionHistoryX[i][tt/subSampleFac] = particleArray->xprevious[i];\n            positionHistoryY[i][tt/subSampleFac] = particleArray->yprevious[i];\n            positionHistoryZ[i][tt/subSampleFac] = particleArray->zprevious[i];\n            velocityHistoryX[i][tt/subSampleFac] = particleArray->vx[i];\n            velocityHistoryY[i][tt/subSampleFac] = particleArray->vy[i];\n            velocityHistoryZ[i][tt/subSampleFac] = particleArray->vz[i];\n            chargeHistory[i][tt/subSampleFac] = particleArray->charge[i];\n        }\n}\n#endif\n#endif\n    }\n// Ensure that all time step loop GPU kernels are complete before proceeding\n    #ifdef __CUDACC__\n        cudaDeviceSynchronize();\n    #endif\n\n    auto finish_clock = Time::now();\n    fsec fs = finish_clock - start_clock;\n    printf(\"Time taken          is %6.3f (secs) \\n\", fs.count());\n    printf(\"Time taken per step is %6.3f (secs) \\n\", fs.count() / (float) nT);\n#if USE_BOOST\n    //cpu_times ionizeTimeGPU = timer.elapsed();\n    //std::cout << \"Particle Moving Time: \" << ionizeTimeGPU.wall*1e-9 << '\\n';\n#endif\n    /*\nfor(int i=0; i<nP ; i++)\n{\n    std::cout << \"particle \" << i << \" first rnd# \" << \n        particleArray->test[i] << \" and x \" << particleArray->xprevious[i] << \n         \" hitwall \" << particleArray->hitWall[i] << \n         \" trans \" << particleArray->transitTime[i] << std::endl;\n}\n*/\n    std::cout << \"transit time counting \"<< nP << std::endl;\n    //float tmp202 =0.0;\n#if USE_CUDA\n    cudaDeviceSynchronize();\n#endif\n//    tmp202 =  particleArray->vx[0];\n    std::cout << \"memory access hitwall \" \n    << particleArray->xprevious[0] << std::endl;\n    std::cout << \"transit time counting \" << std::endl;\n#if USE3DTETGEOM > 0\n    float meanTransitTime0 = 0.0;\n    /*\n    for (int i=0; i<nP; i++)\n    {\n        std::cout << \"loop \" << i << std::endl;\n        if(particleArray->hitWall[i] == 1.0)\n        {\n            meanTransitTime0 = meanTransitTime0 + particleArray->transitTime[i];\n        }\n    }\n    */\nmeanTransitTime0 = meanTransitTime0/nP;\nstd::cout << \" mean transit time \" << meanTransitTime0 << std::endl;\n    int max_boundary = 0;\n    float max_impacts = 0.0;\n    int max_boundary1 = 0;\n    float max_impacts1 = 0.0;\n    float* impacts = new float[nLines];\n    float* startingParticles = new float[nLines];\n    for (int i=0; i<nLines; i++)\n    {\n        impacts[i] = boundaries[i].impacts;\n        startingParticles[i] = boundaries[i].startingParticles;\n        if (boundaries[i].impacts > max_impacts)\n        {\n            max_impacts = boundaries[i].impacts;\n            max_boundary = i;\n        }\n    }\n\n\nstd::cout << \"maximum boundary \" << max_boundary << std::endl;\nstd::cout << \"number of counts \" << max_impacts << std::endl;\n/*\nsim::Array<float> tally00(nLines,0);\nfor (int j=0; j<nP; j++)\n{\n    tally00[particleArray->wallHit[j]] = tally00[particleArray->wallHit[j]] + 1;\n}\n\nstd::cout << \"bound 164p \" << tally00[164] << std::endl;\nstd::cout << \"bound 255p \" << tally00[255] << std::endl;\n\nstd::cout << \"bound 164 \" << boundaries[164].impacts << std::endl;\nstd::cout << \"bound 255 \" << boundaries[255].impacts << std::endl;\n*/\n#else\n    float* impacts = new float[nLines];\n    float* startingParticles = new float[nLines];\n    for (int i=0; i<nLines; i++)\n    {\n        impacts[i] = boundaries[i].impacts;\n        startingParticles[i] = boundaries[i].startingParticles;\n    }\n#endif\n#if PARTICLE_SOURCE == 1\nint ring1 = 0;\nint ring2 = 0;\nint noWall = 0;\nfloat meanTransitTime = 0.0;\n\nfor(int i=0; i<nP ; i++)\n{\n\tif(particleArray->wallIndex[i] == boundaryIndex_ImpurityLaunch[0])\n\t{\n\t\tring1++;\n\t}\n\telse if(particleArray->wallIndex[i] == boundaryIndex_ImpurityLaunch[1])\n\t{\n\t\tring2++;\n\t}\n\t\n\tif(particleArray->wallIndex[i] == 0)\n\t{\n\t\tnoWall++;\n\t}\n\t\n\tmeanTransitTime = meanTransitTime + particleArray->transitTime[i];\n\t\n} \nmeanTransitTime = meanTransitTime/(nP-noWall);\nstd::cout << \"Number of impurity particles deposited on ring 1 \" << ring1 << std::endl;\nstd::cout << \"Number of impurity particles deposited on ring 2 \" << ring2 << std::endl;\nstd::cout << \"Number of impurity particles not deposited \" << noWall << std::endl;\nstd::cout << \"Mean transit time of deposited particles \" << meanTransitTime << std::endl;\n#endif\n    std::cout << \"positions.m writing \" << std::endl;\n    ofstream outfile2;\n    outfile2.open (\"positions.m\");\n    for(int i=1 ; i<=nP ; i++)\n      {\n        outfile2 << \"Pos( \" << i<< \",:) = [ \" ;\n        outfile2 << particleArray->x[i-1] << \" \" << particleArray->y[i-1] \n            << \" \" << particleArray->z[i-1] << \" ];\" << std::endl;\n      }\n       outfile2.close();\n// Write netCDF output for positions\nfor (int i=0; i<nP; i++)\n{\n    finalPosX[i] = particleArray->xprevious[i];\n    finalPosY[i] = particleArray->yprevious[i];\n    finalPosZ[i] = particleArray->zprevious[i];\n    finalVx[i] =   particleArray->vx[i];\n    finalVy[i] =   particleArray->vy[i];\n    finalVz[i] =   particleArray->vz[i];\n    transitTime[i] = particleArray->transitTime[i];\n    hitWall[i] = particleArray->hitWall[i];\n}\nNcFile ncFile0(\"positions.nc\", NcFile::replace);\nNcDim nc_nP0 = ncFile0.addDim(\"nP\",nP);\nvector<NcDim> dims0;\ndims0.push_back(nc_nP0);\n\nNcVar nc_x0 = ncFile0.addVar(\"x\",ncDouble,dims0);\nNcVar nc_y0 = ncFile0.addVar(\"y\",ncDouble,dims0);\nNcVar nc_z0 = ncFile0.addVar(\"z\",ncDouble,dims0);\nNcVar nc_vx0 = ncFile0.addVar(\"vx\",ncDouble,dims0);\nNcVar nc_vy0 = ncFile0.addVar(\"vy\",ncDouble,dims0);\nNcVar nc_vz0 = ncFile0.addVar(\"vz\",ncDouble,dims0);\nNcVar nc_trans0 = ncFile0.addVar(\"transitTime\",ncDouble,dims0);\nNcVar nc_impact0 = ncFile0.addVar(\"hitWall\",ncDouble,dims0);\n\nnc_x0.putVar(finalPosX);\nnc_y0.putVar(finalPosY);\nnc_z0.putVar(finalPosZ);\nnc_vx0.putVar(finalVx);\nnc_vy0.putVar(finalVy);\nnc_vz0.putVar(finalVz);\nnc_trans0.putVar(transitTime);\nnc_impact0.putVar(hitWall);\n\nNcFile ncFile1(\"surface.nc\", NcFile::replace);\nNcDim nc_nLines = ncFile1.addDim(\"nLines\",nLines);\nvector<NcDim> dims1;\ndims1.push_back(nc_nLines);\n\nNcVar nc_surfImpacts = ncFile1.addVar(\"impacts\",ncDouble,dims1);\nNcVar nc_surfStartingParticles = ncFile1.addVar(\"startingParticles\",ncDouble,dims1);\nnc_surfImpacts.putVar(impacts);\nnc_surfStartingParticles.putVar(startingParticles);\n#if PARTICLE_TRACKS > 0\n\n// Write netCDF output for histories\nNcFile ncFile_hist(\"history.nc\", NcFile::replace);\nNcDim nc_nT = ncFile_hist.addDim(\"nT\",nT/subSampleFac);\nNcDim nc_nP = ncFile_hist.addDim(\"nP\",nP);\nvector<NcDim> dims_hist;\n\n#if USE_CUDA\nNcDim nc_nPnT = ncFile_hist.addDim(\"nPnT\",nP*nT/subSampleFac);\ndims_hist.push_back(nc_nPnT);\n#else\nNcVar nc_z = ncFile_hist.addVar(\"z\",ncDouble,dims_hist);\n\nNcVar nc_vx = ncFile_hist.addVar(\"vx\",ncDouble,dims_hist);\nNcVar nc_vy = ncFile_hist.addVar(\"vy\",ncDouble,dims_hist);\nNcVar nc_vz = ncFile_hist.addVar(\"vz\",ncDouble,dims_hist);\n\nNcVar nc_charge = ncFile_hist.addVar(\"charge\",ncDouble,dims_hist);\n#if USE_CUDA > 0\nfloat *xPointer = &positionHistoryX[0];\nfloat *yPointer = &positionHistoryY[0];\nfloat *zPointer = &positionHistoryZ[0];\nfloat *vxPointer = &velocityHistoryX[0];\nfloat *vyPointer = &velocityHistoryY[0];\nfloat *vzPointer = &velocityHistoryZ[0];\nfloat *chargePointer = &chargeHistory[0];\nnc_x.putVar(xPointer);\nnc_y.putVar(yPointer);\nnc_z.putVar(zPointer);\n\nnc_vx.putVar(vxPointer);\nnc_vy.putVar(vyPointer);\nnc_vz.putVar(vzPointer);\n\nnc_charge.putVar(chargePointer);\n#else\nnc_x.putVar(positionHistoryX[0]);\nnc_y.putVar(positionHistoryY[0]);\nnc_z.putVar(positionHistoryZ[0]);\n\nnc_vx.putVar(velocityHistoryX[0]);\nnc_vy.putVar(velocityHistoryY[0]);\nnc_vz.putVar(velocityHistoryZ[0]);\n\nnc_charge.putVar(chargeHistory[0]);\n#endif\n#endif\n#endif\n#if SPECTROSCOPY > 0\n// Write netCDF output for density data\nNcFile ncFile(\"spec.nc\", NcFile::replace);\nNcDim nc_nBins = ncFile.addDim(\"nBins\",nBins+1);\nNcDim nc_nR = ncFile.addDim(\"nR\",net_nX);\nNcDim nc_nY = ncFile.addDim(\"nY\",net_nY);\nNcDim nc_nZ = ncFile.addDim(\"nZ\",net_nZ);\n\nvector<NcDim> dims;\ndims.push_back(nc_nBins);\ndims.push_back(nc_nZ);\ndims.push_back(nc_nY);\ndims.push_back(nc_nR);\n\nNcVar nc_n = ncFile.addVar(\"n\",ncDouble,dims);\nfloat *binPointer = &net_Bins[0];\nnc_n.putVar(binPointer);\n#endif\n#ifdef __CUDACC__\n    cudaThreadSynchronize();\n#endif\n#if USE_BOOST\n    /*\n    cpu_times copyToHostTime = timer.elapsed();\n\n    cpu_times createParticlesTimeCPU = timer.elapsed();\n    std::cout << \"Copy to host, bin and output time: \" << (createParticlesTimeCPU.wall-copyToHostTime.wall)*1e-9 << '\\n';\n    std::cout << \"Total ODE integration time: \" << moveTime*1e-9 << '\\n';\n    std::cout << \"Total geometry checking time: \" << geomCheckTime*1e-9 << '\\n';\n    std::cout << \"Total ionization time: \" << ionizTime*1e-9 << '\\n';\n    */\n#endif\n\n#ifdef __CUDACC__\n    cudaError_t err = cudaDeviceReset();\n//cudaProfilerStop();\n#endif\n    return 0;\n    }\n", "meta": {"hexsha": "74b43c66c79d39b95a247bd46c2af7174723fbbb", "size": 105579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gitr.cpp", "max_stars_repo_name": "tyounkin/gitr-1-intermediate", "max_stars_repo_head_hexsha": "4a57364594223fdc3831c07a3c36ec3a8268f7cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gitr.cpp", "max_issues_repo_name": "tyounkin/gitr-1-intermediate", "max_issues_repo_head_hexsha": "4a57364594223fdc3831c07a3c36ec3a8268f7cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gitr.cpp", "max_forks_repo_name": "tyounkin/gitr-1-intermediate", "max_forks_repo_head_hexsha": "4a57364594223fdc3831c07a3c36ec3a8268f7cf", "max_forks_repo_licenses": ["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.5605071072, "max_line_length": 133, "alphanum_fraction": 0.620710558, "num_tokens": 31439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.02517883914037278, "lm_q1q2_score": 0.010927149492200713}}
{"text": "/*\n * Copyright (c) 2011-2022, 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_OPTIMIZER_PROBLEM_HPP_\n#define DART_OPTIMIZER_PROBLEM_HPP_\n\n#include <cstddef>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/optimizer/Function.hpp\"\n\nnamespace dart {\nnamespace optimizer {\n\n/// \\brief class Problem\nclass Problem\n{\npublic:\n  /// \\brief Constructor\n  explicit Problem(std::size_t _dim = 0);\n\n  /// \\brief Destructor\n  virtual ~Problem() = default;\n\n  //--------------------------- Problem Setting --------------------------------\n  /// \\brief Set dimension. Note: Changing the dimension will clear out the\n  /// initial guess and any seeds that have been added.\n  void setDimension(std::size_t _dim);\n\n  /// \\brief Get dimension\n  std::size_t getDimension() const;\n\n  /// \\brief Set initial guess for opimization parameters\n  void setInitialGuess(const Eigen::VectorXd& _initGuess);\n\n  /// \\brief Set initial guess for opimization parameters\n  const Eigen::VectorXd& getInitialGuess() const;\n\n  /// \\brief Add a seed for the Solver to use as a hint for the neighborhood of\n  /// the solution.\n  void addSeed(const Eigen::VectorXd& _seed);\n\n  /// \\brief Get a mutable reference of the seed for the specified index. If an\n  /// out-of-bounds index is provided a warning will print, and a reference to\n  /// the initial guess will be returned instead.\n  Eigen::VectorXd& getSeed(std::size_t _index);\n\n  /// \\brief An immutable version of getSeed(std::size_t)\n  const Eigen::VectorXd& getSeed(std::size_t _index) const;\n\n  /// \\brief Get a mutable reference to the full vector of seeds that this\n  /// Problem currently contains\n  std::vector<Eigen::VectorXd>& getSeeds();\n\n  /// \\brief An immutable version of getSeeds()\n  const std::vector<Eigen::VectorXd>& getSeeds() const;\n\n  /// \\brief Clear the seeds that this Problem currently contains\n  void clearAllSeeds();\n\n  /// \\brief Set lower bounds for optimization parameters\n  void setLowerBounds(const Eigen::VectorXd& _lb);\n\n  /// \\brief Get lower bounds for optimization parameters\n  const Eigen::VectorXd& getLowerBounds() const;\n\n  /// \\brief Set upper bounds for optimization parameters\n  void setUpperBounds(const Eigen::VectorXd& _ub);\n\n  /// \\brief Get upper bounds for optimization parameters\n  const Eigen::VectorXd& getUpperBounds() const;\n\n  /// \\brief Set minimum objective function\n  void setObjective(FunctionPtr _obj);\n\n  /// \\brief Get objective function\n  FunctionPtr getObjective() const;\n\n  /// \\brief Add equality constraint\n  void addEqConstraint(FunctionPtr _eqConst);\n\n  /// \\brief Add inequality constraint. Inequality constraints must evaluate\n  /// to LESS THAN or equal to zero (within some tolerance) to be satisfied.\n  void addIneqConstraint(FunctionPtr _ineqConst);\n\n  /// \\brief Get number of equality constraints\n  std::size_t getNumEqConstraints() const;\n\n  /// \\brief Get number of inequality constraints\n  std::size_t getNumIneqConstraints() const;\n\n  /// \\brief Get equality constraint\n  FunctionPtr getEqConstraint(std::size_t _idx) const;\n\n  /// \\brief Get inequality constraint\n  FunctionPtr getIneqConstraint(std::size_t _idx) const;\n\n  /// \\brief Remove equality constraint\n  void removeEqConstraint(FunctionPtr _eqConst);\n\n  /// \\brief Remove inequality constraint\n  void removeIneqConstraint(FunctionPtr _ineqConst);\n\n  /// \\brief Remove all equality constraints\n  void removeAllEqConstraints();\n\n  /// \\brief Remove all inequality constraints\n  void removeAllIneqConstraints();\n\n  //------------------------------ Result --------------------------------------\n  /// \\brief Set optimum value of the objective function. This function called\n  ///        by Solver.\n  void setOptimumValue(double _val);\n\n  /// \\brief Get optimum value of the objective function\n  double getOptimumValue() const;\n\n  /// \\brief Set optimal solution. This function called by Solver.\n  void setOptimalSolution(const Eigen::VectorXd& _optParam);\n\n  /// \\brief Get optimal solution\n  const Eigen::VectorXd& getOptimalSolution();\n\nprotected:\n  /// \\brief Dimension of this problem\n  std::size_t mDimension;\n\n  /// \\brief Initial guess for optimization parameters\n  Eigen::VectorXd mInitialGuess;\n\n  /// \\brief Additional guess hints for the Solver.\n  std::vector<Eigen::VectorXd> mSeeds;\n\n  /// \\brief Lower bounds for optimization parameters\n  Eigen::VectorXd mLowerBounds;\n\n  /// \\brief Upper bounds for optimization parameters\n  Eigen::VectorXd mUpperBounds;\n\n  /// \\brief Objective function\n  FunctionPtr mObjective;\n\n  /// \\brief Equality constraint functions\n  std::vector<FunctionPtr> mEqConstraints;\n\n  /// \\brief Inequality constraint functions\n  std::vector<FunctionPtr> mIneqConstraints;\n\n  /// \\brief Optimal objective value\n  double mOptimumValue;\n\n  /// \\brief Optimal solution\n  Eigen::VectorXd mOptimalSolution;\n};\n\n} // namespace optimizer\n} // namespace dart\n\n#endif // #ifndef DART_OPTIMIZER_PROBLEM_HPP_\n", "meta": {"hexsha": "b411181d217deeea9456abc47cb96b18ef1cb2aa", "size": 6449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/optimizer/Problem.hpp", "max_stars_repo_name": "ibrahiminfinite/dart", "max_stars_repo_head_hexsha": "495c82120c836005f2d136d4a50c8cc997fb879b", "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/optimizer/Problem.hpp", "max_issues_repo_name": "ibrahiminfinite/dart", "max_issues_repo_head_hexsha": "495c82120c836005f2d136d4a50c8cc997fb879b", "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/optimizer/Problem.hpp", "max_forks_repo_name": "ibrahiminfinite/dart", "max_forks_repo_head_hexsha": "495c82120c836005f2d136d4a50c8cc997fb879b", "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.7643979058, "max_line_length": 80, "alphanum_fraction": 0.724918592, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.023689468585348504, "lm_q1q2_score": 0.010921242510837651}}
{"text": "﻿/***\r\n第四节 可变参模板\r\n英文：Variadic Templates ，C++11\r\n允许模板定义中包含 0 ，到多个（任意个）模板参数。\r\n\r\nC++17\r\n（1）可变参函数模板\r\n（1.1）基本含义\r\n可变参函数模板中，传递进来的一包实参怎样展开：一般都采用递归函数的方式展开参数包。\r\n要展开，要求，在可变参函数模板代码中，有一个参数包展开函数，以及一个同名的递归终止函数。\r\na)myvtfunct(10, \"abc\", 12.7);\r\nb)myvtfunct( \"abc\", 12.7);\r\nc)myvtfunct(12.7);\r\nd)myvtfunct();\r\n\r\nC++17中增加了一个语句，叫做“编译期间if语句(constexpr if)”。\r\nif constexpr()....   //constexpr，代表“常量”的意思，或者代表“编译时求值”的意思。\r\nmyvtfunct<int,char const *,double>(int,char const *,double)\r\nmyvtfunct<char const*, double>(char const*, double)\r\nmyvtfunct<double>(double)\r\n深入认识if constexpr\r\na)不满足条件的分支，也同样会被编译器编译(被编译器进行语法检查）。\r\nb)if constexpr所指定的条件必须是常量：理解成普通if语句，只是判断条件从执行期间挪到了编译期间\r\n总结：if constexpr的存在，完善了模板与泛型编程中的程序执行路径选择问题。\r\n\r\n（1.2）重载\r\n一般来说，调用普通函数和调用函数模板都合适的时候，编译器优先选择普通函数。\r\n把握不准时，可以多做测试。\r\n***/\r\n\r\n\r\n#include <iostream>\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\nnamespace _nmsp1\r\n{\r\n\tvoid myptfunct()\r\n\t{\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t//可变参函数模板\r\n\ttemplate <typename... T>       //...代表参数包\r\n\tvoid myvtfunct(T... args)      //T：一包类型，args：一包形参   ,T称为“可变参类型”,T中包含的是0到多个不同的类型（一包类型）\r\n\t\t                           //args称为一包/一堆 参数（函数模板的形参：0个到多个），每个参数的类型可以各不相同。\r\n\t{\r\n\t\t//收到的参数数量，sizeof...固定语法，C++11中引入，用于表示收到的模板参数个数或者类型数量。\r\n\t\t//sizeof...针对的只能是这种...的可变参，后面圆括号中可以是函数模板的形参args，也可以是类型模板参数T.\r\n\t\tcout << sizeof...(args) << endl;                                              \r\n\t\tcout << sizeof...(T) << endl;\r\n\t\t\r\n\t}\r\n\t\r\n\t//再实现一个同名的递归终止函数(这是个真正的函数)，位置放在参数包展开函数 的前面\r\n\tvoid myvtfunct() //这是个普通函数，而不是函数模板\r\n\t{\r\n\t\tcout << \"参数包展开时执行了递归终止函数myvtfunct()\" << endl;\r\n\t}\r\n\t***/\r\n\t\r\n\t//先实现参数包展开函数\r\n\ttemplate <typename T,typename...U>\r\n\tvoid myvtfunct(T firstarg, U...otherargs)       //(10, \"abc\", 12.7);\r\n\t{\r\n\t\tcout << \"收到的参数值：\" << firstarg << endl;\r\n\t\t//myvtfunct(otherargs...);                 //递归调用，注意塞进来的是一包形参，这里的...不能省略\r\n\t\tif constexpr (sizeof...(otherargs) > 0)    //constexpr必须有否则无法成功编译，圆括号中是常量表达式。\r\n\t\t{\r\n\t\t\tmyvtfunct(otherargs...);               //递归调用，注意塞进来的是一包形参，这里的...不能省略\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//不需要做什么，其实整个else都可以不要。\r\n\t\t}\r\n\r\n\r\n\t\t/*if constexpr (sizeof...(otherargs) > 100) //不管if constexpr条件是否成立，{}中的代码行都会被编译\r\n\t\t{\r\n\t\t\ttestfunc();\r\n\t\t}*/\r\n//#define _MYDEF_\r\n//#ifdef  _MYDEF_\r\n//\t\ttestfunc();\r\n//#endif\r\n\r\n\t\t/*int i = 8;\r\n\t\tif constexpr (i > 8)\r\n\t\t{\r\n\r\n\t\t}*/\r\n\t}\r\n}\r\n\r\nnamespace _nmsp2\r\n{\r\n\ttemplate<typename... T>\r\n\tvoid myfunc(T... arg)\r\n\t{\r\n\t\tcout << \"myfunc(T... arg)执行了!\" << endl;\r\n\t}\r\n\r\n\ttemplate<typename... T>\r\n\tvoid myfunc(T*... arg)\r\n\t{\r\n\t\tcout << \"myfunc(T*... arg)执行了!\" << endl;\r\n\t}\r\n\r\n\tvoid myfunc(int arg)\r\n\t{\r\n\t\tcout << \"myfunc(int arg)执行了!\" << endl;\r\n\t}\r\n\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\t//_nmsp1::myvtfunct();\r\n\t//_nmsp1::myvtfunct(10,20);\r\n\t//_nmsp1::myvtfunct(10, 25.8,\"abc\",68);\r\n\t//_nmsp1::myvtfunct<double,double>(10, 25.8, \"abc\", 68,73); //指定部分类型，让编译器去推断另一部分类型，是允许的。\r\n\r\n\t//_nmsp1::myvtfunct(10, \"abc\", 12.7);\r\n\r\n\r\n\t_nmsp2::myfunc(NULL);\r\n\t_nmsp2::myfunc(nullptr); //nullptr是空指针\r\n\t_nmsp2::myfunc((int *)nullptr);\r\n\r\n\r\n\r\n\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "688564b42d30e72511f62ea20565f3e55182eaac", "size": 2948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/213.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/213.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/213.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 21.2086330935, "max_line_length": 90, "alphanum_fraction": 0.6017639077, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053950871516, "lm_q2_score": 0.1037486268663797, "lm_q1q2_score": 0.010915449005900189}}
{"text": "/**\nBSD 3-Clause License\n\nThis file is part of the RootBA project.\nhttps://github.com/NikolausDemmel/rootba\n\nCopyright (c) 2021, Nikolaus Demmel.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n#pragma once\n\n#include <mutex>\n\n#include <Eigen/Dense>\n#include <glog/logging.h>\n#include <tbb/blocked_range.h>\n#include <tbb/parallel_for.h>\n#include <tbb/parallel_reduce.h>\n\n#include \"rootba/bal/bal_problem.hpp\"\n#include \"rootba/qr/landmark_block.hpp\"\n#include \"rootba/util/assert.hpp\"\n#include \"rootba/util/cast.hpp\"\n#include \"rootba/util/format.hpp\"\n\nnamespace rootba {\n\ntemplate <typename Scalar_, int POSE_SIZE_>\nclass LinearizationQR : public LinearOperator<Scalar_> {\n public:\n  using Scalar = Scalar_;\n  static constexpr int POSE_SIZE = POSE_SIZE_;\n\n  using Vec2 = Eigen::Matrix<Scalar, 2, 1>;\n  using Vec4 = Eigen::Matrix<Scalar, 4, 1>;\n  using VecP = Eigen::Matrix<Scalar, POSE_SIZE, 1>;\n\n  using VecX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n  using Mat36 = Eigen::Matrix<Scalar, 3, 6>;\n\n  using LandmarkBlockPtr = std::unique_ptr<LandmarkBlock<Scalar>>;\n\n  struct Options {\n    int reduction_alg = 0;\n    typename LandmarkBlock<Scalar>::Options lb_options;\n  };\n\n  LinearizationQR(BalProblem<Scalar>& bal_problem, const Options& options)\n      : options_(options),\n        bal_problem_(bal_problem),\n        pose_mutex_(bal_problem_.cameras().size()),\n        pose_damping_diagonal_(0),\n        pose_damping_diagonal_sqrt_(0) {\n    size_t num_landmakrs = bal_problem_.landmarks().size();\n\n    landmark_blocks_.resize(num_landmakrs);\n\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        auto& lb = landmark_blocks_[r];\n        auto& landmark = bal_problem_.landmarks()[r];\n\n        lb = LandmarkBlockFactory<Scalar, POSE_SIZE>::get_landmark_block(\n            landmark.obs.size());\n\n        lb->allocate_landmark(landmark, options.lb_options);\n      }\n    };\n\n    tbb::blocked_range<size_t> range(0, num_landmakrs);\n    tbb::parallel_for(range, body);\n\n    landmark_block_idx_.reserve(num_landmakrs);\n\n    num_rows_Q2Tr_ = 0;\n    for (size_t i = 0; i < num_landmakrs; i++) {\n      landmark_block_idx_.emplace_back(num_rows_Q2Tr_);\n      num_rows_Q2Tr_ += landmark_blocks_[i]->num_Q2T_rows();\n    }\n\n    num_cameras_ = bal_problem_.cameras().size();\n  }\n\n  ~LinearizationQR() override = default;\n\n  // return value `false` indicates numerical failure --> linearization at this\n  // state is unusable. Numeric check is only performed for residuals that were\n  // considered to be used (valid), which depends on use_valid_projections_only\n  // setting.\n  bool linearize_problem() {\n    ROOTBA_ASSERT(bal_problem_.landmarks().size() == landmark_blocks_.size());\n\n    size_t num_landmarks = landmark_blocks_.size();\n\n    auto body = [&](const tbb::blocked_range<size_t>& range,\n                    bool numerically_valid) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        landmark_blocks_[r]->linearize_landmark(bal_problem_.cameras());\n        numerically_valid &= !landmark_blocks_[r]->is_numerical_failure();\n      }\n      return numerically_valid;\n    };\n\n    tbb::blocked_range<size_t> range(0, num_landmarks);\n    const bool numerically_valid =\n        tbb::parallel_reduce(range, true, body, std::logical_and<>());\n\n    return numerically_valid;\n  }\n\n  void set_pose_damping(const Scalar lambda) {\n    ROOTBA_ASSERT(lambda >= 0);\n\n    pose_damping_diagonal_ = lambda;\n    pose_damping_diagonal_sqrt_ = std::sqrt(lambda);\n  }\n\n  bool has_pose_damping() const { return pose_damping_diagonal_ > 0; }\n\n  size_t num_rows_reduced() const {\n    return has_pose_damping() ? num_rows_Q2Tr_ + num_cameras_ * POSE_SIZE\n                              : num_rows_Q2Tr_;\n  }\n\n  size_t num_cols_reduced() const { return num_cameras_ * POSE_SIZE; }\n\n  void perform_qr() {\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        landmark_blocks_[r]->perform_qr();\n      }\n    };\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n  }\n\n  Scalar back_substitute(const VecX& pose_inc) {\n    ROOTBA_ASSERT(pose_inc.size() == signed_cast(num_cameras_ * POSE_SIZE));\n\n    auto body = [&](const tbb::blocked_range<size_t>& range, Scalar l_diff) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        landmark_blocks_[r]->back_substitute(pose_inc, l_diff);\n      }\n      return l_diff;\n    };\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    Scalar l_diff =\n        tbb::parallel_reduce(range, Scalar(0), body, std::plus<Scalar>());\n    return l_diff;\n  }\n\n  VecX get_Q2Tr() const {\n    VecX res(num_rows_reduced());\n\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        const auto& lb = landmark_blocks_[r];\n        res.segment(landmark_block_idx_[r], lb.numQ2rows()) = lb.getQ2r();\n      }\n    };\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n\n    if (has_pose_damping()) {\n      res.tail(num_cameras_ * POSE_SIZE).setZero();\n    }\n\n    return res;\n  }\n\n  Eigen::SparseMatrix<Scalar, Eigen::RowMajor> get_Q2TJp() const {\n    // Since we know exactly the sparsity, we can do better than triplets:\n    // https://stackoverflow.com/a/18160211/1813258\n    // https://eigen.tuxfamily.org/dox/group__SparseQuickRefPage.html\n    // But since it's for debugging, it probably doesn't matter...\n\n    // prepare triplet vector\n    size_t num_triplets = 0;\n    for (const auto& lb : landmark_blocks_) {\n      num_triplets += lb->num_reduced_cams() * POSE_SIZE * lb->num_Q2T_rows();\n    }\n    if (has_pose_damping()) {\n      num_triplets += num_cameras_ * POSE_SIZE;\n    }\n    std::vector<Eigen::Triplet<Scalar>> triplets;\n    triplets.reserve(num_triplets);\n\n    // generate all triplets\n    for (size_t i = 0; i < landmark_blocks_.size(); ++i) {\n      const auto& lb = landmark_blocks_[i];\n      lb->add_triplets_Q2TJp(landmark_block_idx_[i], triplets);\n    }\n\n    // add dapening entries\n    if (has_pose_damping()) {\n      for (size_t i = 0; i < num_cameras_ * POSE_SIZE; ++i) {\n        triplets.emplace_back(num_rows_Q2Tr_ + i, i,\n                              pose_damping_diagonal_sqrt_);\n      }\n    }\n\n    // build sparse matrix\n    Eigen::SparseMatrix<Scalar, Eigen::RowMajor> res(num_rows_reduced(),\n                                                     POSE_SIZE * num_cameras_);\n    if (!triplets.empty()) {\n      res.setFromTriplets(triplets.begin(), triplets.end());\n    }\n\n    return res;\n  }\n\n  VecX get_Q2TJp_postmult_x(const VecX& x_pose) const {\n    ROOTBA_ASSERT(x_pose.size() == signed_cast(num_cameras_ * POSE_SIZE));\n\n    VecX res(num_rows_reduced());\n\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        res.segment(landmark_block_idx_[r],\n                    landmark_blocks_[r]->num_Q2T_rows()) =\n            landmark_blocks_[r]->get_Q2TJp_postmult_x(x_pose);\n      }\n    };\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n\n    if (has_pose_damping()) {\n      res.tail(POSE_SIZE * num_cameras_) =\n          x_pose.array() * pose_damping_diagonal_sqrt_;\n    }\n\n    return res;\n  }\n\n  VecX get_Q2TJp_premult_x(const VecX& x_r) const {\n    ROOTBA_ASSERT(x_r.size() == signed_cast(num_rows_reduced()));\n\n    auto body = [&](const tbb::blocked_range<size_t>& range, VecX res) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        const auto& lb = landmark_blocks_[r];\n\n        lb->add_Q2TJp_premult_x(\n            res, x_r.segment(landmark_block_idx_[r], lb->num_Q2T_rows()));\n      }\n      return res;\n    };\n\n    auto join = [](const auto& x, const auto& y) { return x + y; };\n\n    VecX init;\n    init.setZero(POSE_SIZE * num_cameras_);\n\n    // go over all host frames\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    VecX res = tbb::parallel_reduce(range, init, body, join);\n\n    if (has_pose_damping()) {\n      res += (x_r.tail(POSE_SIZE * num_cameras_).array() *\n              pose_damping_diagonal_sqrt_)\n                 .matrix();\n    }\n\n    return res;\n  }\n\n  inline VecX get_Q2TJp_T_Q2TJp_mult_x(const VecX& x_pose) const {\n    switch (options_.reduction_alg) {\n      case 0:\n        return get_Q2TJp_T_Q2TJp_mult_x_v0(x_pose);\n        //      case 1:\n        //        return getQ2JpTQ2Jp_mult_x_v1(x_pose);\n        //      case 2:\n        //        return getQ2JpTQ2Jp_mult_x_v2(x_pose);\n      case 3:\n        return get_Q2TJp_T_Q2TJp_mult_x_v3(x_pose);\n\n      default:\n        LOG(FATAL) << \"options_.reduction_alg \" << options_.reduction_alg\n                   << \" is not supported.\";\n    }\n  }\n\n  VecX get_Q2TJp_T_Q2TJp_mult_x_v0(const VecX& x_pose) const {\n    ROOTBA_ASSERT(x_pose.size() == signed_cast(num_cameras_ * POSE_SIZE));\n\n    struct Reductor {\n      Reductor(const VecX& x_pose,\n               const std::vector<LandmarkBlockPtr>& landmark_blocks)\n          : x_pose(x_pose), landmark_blocks(landmark_blocks) {\n        res.setZero(x_pose.rows());\n      }\n\n      void operator()(const tbb::blocked_range<size_t>& range) {\n        for (size_t r = range.begin(); r != range.end(); ++r) {\n          const auto& lb = landmark_blocks[r];\n          lb->add_Q2TJp_T_Q2TJp_mult_x(res, x_pose);\n        }\n      }\n\n      Reductor(Reductor& a, tbb::split /*unused*/)\n          : x_pose(a.x_pose), landmark_blocks(a.landmark_blocks) {\n        res.setZero(x_pose.rows());\n      }\n\n      inline void join(const Reductor& b) { res += b.res; }\n\n      const VecX& x_pose;\n      const std::vector<LandmarkBlockPtr>& landmark_blocks;\n      VecX res;\n    };\n\n    Reductor r(x_pose, landmark_blocks_);\n\n    // go over all host frames\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_reduce(range, r);\n\n    if (has_pose_damping()) {\n      r.res += (x_pose.array() * pose_damping_diagonal_).matrix();\n    }\n\n    return r.res;\n  }\n\n  // Version with unordered_map and mutex guarded writes\n  VecX get_Q2TJp_T_Q2TJp_mult_x_v1(const VecX& x_pose) const {\n    ROOTBA_ASSERT(x_pose.size() == signed_cast(num_cameras_ * POSE_SIZE));\n\n    VecX res;\n    res.setZero(x_pose.rows());\n\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      std::unordered_map<int, VecP> partial_sum_map;\n      partial_sum_map.reserve(num_cameras_ / 8);\n\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        const auto& lb = landmark_blocks_[r];\n        // lb->mapQ2JpTQ2Jp_mult_x(partial_sum_map, x_pose);\n      }\n\n      for (const auto& [k, v] : partial_sum_map) {\n        std::scoped_lock<std::mutex> lock(pose_mutex_[k]);\n        res.template segment<POSE_SIZE>(k * POSE_SIZE) += v;\n      }\n\n      return res;\n    };\n\n    // go over all host frames\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n\n    if (has_pose_damping()) {\n      res += (x_pose.array() * pose_damping_diagonal_).matrix();\n    }\n\n    return res;\n  }\n\n  // Verstion with map and mutex guarded writes\n  VecX get_Q2TJp_T_Q2TJp_mult_x_v2(const VecX& x_pose) const {\n    ROOTBA_ASSERT(x_pose.size() == signed_cast(num_cameras_ * POSE_SIZE));\n\n    VecX res;\n    res.setZero(x_pose.rows());\n\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      std::map<int, VecP> partial_sum_map;\n\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        const auto& lb = landmark_blocks_[r];\n        // lb->mapQ2JpTQ2Jp_mult_x(partial_sum_map, x_pose);\n      }\n\n      for (const auto& [k, v] : partial_sum_map) {\n        std::scoped_lock<std::mutex> lock(pose_mutex_[k]);\n        res.template segment<POSE_SIZE>(k * POSE_SIZE) += v;\n      }\n\n      return res;\n    };\n\n    // go over all host frames\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n\n    if (has_pose_damping()) {\n      res += (x_pose.array() * pose_damping_diagonal_).matrix();\n    }\n\n    return res;\n  }\n\n  // Verstion with direct mutex guarded writes\n  VecX get_Q2TJp_T_Q2TJp_mult_x_v3(const VecX& x_pose) const {\n    ROOTBA_ASSERT(x_pose.size() == signed_cast(num_cameras_ * POSE_SIZE));\n\n    VecX res;\n    res.setZero(x_pose.rows());\n\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        const auto& lb = landmark_blocks_[r];\n        lb->add_Q2TJp_T_Q2TJp_mult_x(res, x_pose, &pose_mutex_);\n      }\n\n      return res;\n    };\n\n    // go over all host frames\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n\n    if (has_pose_damping()) {\n      res += (x_pose.array() * pose_damping_diagonal_).matrix();\n    }\n\n    return res;\n  }\n\n  VecX get_Q2TJp_T_Q2Tr() const {\n    auto body = [&](const tbb::blocked_range<size_t>& range, VecX res) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        const auto& lb = landmark_blocks_[r];\n        lb->add_Q2TJp_T_Q2Tr(res);\n      }\n      return res;\n    };\n\n    auto join = [](const auto& x, const auto& y) { return x + y; };\n\n    VecX init;\n    init.setZero(POSE_SIZE * num_cameras_);\n\n    // go over all host frames\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    VecX res = tbb::parallel_reduce(range, init, body, join);\n\n    // Note: No need to consider pose damping, since the residual part is 0\n\n    return res;\n  }\n\n  VecX get_Q2TJp_diag2() const {\n    struct Reductor {\n      Reductor(size_t num_rows,\n               const std::vector<LandmarkBlockPtr>& landmark_blocks)\n          : num_rows(num_rows), landmark_blocks(landmark_blocks) {\n        res.setZero(num_rows);\n      }\n\n      void operator()(const tbb::blocked_range<size_t>& range) {\n        for (size_t r = range.begin(); r != range.end(); ++r) {\n          const auto& lb = landmark_blocks[r];\n          lb->add_Q2TJp_diag2(res);\n        }\n      }\n\n      Reductor(Reductor& a, tbb::split /*unused*/)\n          : num_rows(a.num_rows), landmark_blocks(a.landmark_blocks) {\n        res.setZero(num_rows);\n      }\n\n      inline void join(const Reductor& b) { res += b.res; }\n\n      size_t num_rows;\n      const std::vector<LandmarkBlockPtr>& landmark_blocks;\n      VecX res;\n    };\n\n    Reductor r(num_cameras_ * POSE_SIZE, landmark_blocks_);\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_reduce(range, r);\n\n    if (has_pose_damping()) {\n      r.res.array() += pose_damping_diagonal_;\n    }\n\n    return r.res;\n  }\n\n  VecX get_Jp_diag2() const {\n    struct Reductor {\n      Reductor(size_t num_rows,\n               const std::vector<LandmarkBlockPtr>& landmark_blocks)\n          : num_rows(num_rows), landmark_blocks(landmark_blocks) {\n        res.setZero(num_rows);\n      }\n\n      void operator()(const tbb::blocked_range<size_t>& range) {\n        for (size_t r = range.begin(); r != range.end(); ++r) {\n          const auto& lb = landmark_blocks[r];\n          lb->add_Jp_diag2(res);\n        }\n      }\n\n      Reductor(Reductor& a, tbb::split /*unused*/)\n          : num_rows(a.num_rows), landmark_blocks(a.landmark_blocks) {\n        res.setZero(num_rows);\n      }\n\n      inline void join(const Reductor& b) { res += b.res; }\n\n      size_t num_rows;\n      const std::vector<LandmarkBlockPtr>& landmark_blocks;\n      VecX res;\n    };\n\n    Reductor r(num_cameras_ * POSE_SIZE, landmark_blocks_);\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_reduce(range, r);\n\n    // TODO: double check including vs not including pose damping here in usage\n    // and make it clear in API; see also getJpTJp_blockdiag\n\n    // Note: ignore damping here\n\n    return r.res;\n  }\n\n  IndexedBlocks<Scalar> get_Q2TJp_T_Q2TJp_blockdiag() const {\n    struct Reductor {\n      Reductor(const std::vector<LandmarkBlockPtr>& landmark_blocks)\n          : landmark_blocks(landmark_blocks) {}\n\n      Reductor(Reductor& a, tbb::split /*unused*/)\n          : landmark_blocks(a.landmark_blocks) {}\n\n      void operator()(const tbb::blocked_range<size_t>& range) {\n        for (size_t r = range.begin(); r != range.end(); ++r) {\n          const auto& lb = landmark_blocks[r];\n          lb->add_Q2TJp_T_Q2TJp_blockdiag(accum);\n        }\n      }\n\n      inline void join(Reductor& b) { accum.join(b.accum); }\n\n      BlockDiagonalAccumulator<Scalar> accum;\n      const std::vector<LandmarkBlockPtr>& landmark_blocks;\n    };\n\n    Reductor r(landmark_blocks_);\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_reduce(range, r);\n\n    if (has_pose_damping()) {\n      r.accum.add_diag(\n          num_cameras_, POSE_SIZE,\n          VecX::Constant(num_cameras_ * POSE_SIZE, pose_damping_diagonal_));\n    }\n\n    return r.accum.block_diagonal;\n  }\n\n  IndexedBlocks<Scalar> get_Jp_T_Jp_blockdiag() const {\n    struct Reductor {\n      Reductor(const std::vector<LandmarkBlockPtr>& landmark_blocks)\n          : landmark_blocks(landmark_blocks) {}\n\n      Reductor(Reductor& a, tbb::split /*unused*/)\n          : landmark_blocks(a.landmark_blocks) {}\n\n      void operator()(const tbb::blocked_range<size_t>& range) {\n        for (size_t r = range.begin(); r != range.end(); ++r) {\n          const auto& lb = landmark_blocks[r];\n          lb->add_Jp_T_Jp_blockdiag(accum);\n        }\n      }\n\n      inline void join(Reductor& b) { accum.join(b.accum); }\n\n      BlockDiagonalAccumulator<Scalar> accum;\n      const std::vector<LandmarkBlockPtr>& landmark_blocks;\n    };\n\n    Reductor r(landmark_blocks_);\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_reduce(range, r);\n\n    if (has_pose_damping()) {\n      r.accum.add_diag(\n          num_cameras_, POSE_SIZE,\n          VecX::Constant(num_cameras_ * POSE_SIZE, pose_damping_diagonal_));\n    }\n\n    // TODO: double check including vs not including pose damping here in usage\n    // and make it clear in API; see also getJp_diag2\n\n    return r.accum.block_diagonal;\n  }\n\n  void scale_Jl_cols() {\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        landmark_blocks_[r]->scale_Jl_cols();\n      }\n    };\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n  }\n\n  void scale_Jp_cols(const VecX& jacobian_scaling) {\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        landmark_blocks_[r]->scale_Jp_cols(jacobian_scaling);\n      }\n    };\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n  }\n\n  void set_landmark_damping(Scalar lambda) {\n    auto body = [&](const tbb::blocked_range<size_t>& range) {\n      for (size_t r = range.begin(); r != range.end(); ++r) {\n        landmark_blocks_[r]->set_landmark_damping(lambda);\n      }\n    };\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_for(range, body);\n  }\n\n  // Operations grouped into stages. Stage1 includes linearization, optional\n  // JACOBI preconditioner, QR and column norms computations for LM damping.\n  VecX get_stage1(IndexedBlocks<Scalar>* precond_block_diagonal) {\n    struct Reductor {\n      Reductor(size_t num_rows, bool precond_block_diagonal,\n               std::vector<LandmarkBlockPtr>& landmark_blocks,\n               const BalProblem<Scalar>& bal_problem)\n          : num_rows(num_rows),\n            landmark_blocks(landmark_blocks),\n            bal_problem(bal_problem) {\n        if (precond_block_diagonal) {\n          precond_block_diagonal_accum.reset(\n              new BlockDiagonalAccumulator<Scalar>());\n        }\n        res.setZero(num_rows);\n      }\n\n      void operator()(const tbb::blocked_range<size_t>& range) {\n        for (size_t r = range.begin(); r != range.end(); ++r) {\n          auto& lb = landmark_blocks[r];\n          lb->linearize_landmark(bal_problem.cameras());\n          if (!lb->is_numerical_failure()) {\n            if (precond_block_diagonal_accum) {\n              lb->add_Jp_T_Jp_blockdiag(*precond_block_diagonal_accum);\n            }\n            lb->add_Jp_diag2(res);\n            lb->scale_Jl_cols();\n            lb->perform_qr();\n          } else {\n            numerically_valid = false;\n          }\n        }\n      }\n\n      Reductor(Reductor& a, tbb::split /*unused*/)\n          : num_rows(a.num_rows),\n            landmark_blocks(a.landmark_blocks),\n            bal_problem(a.bal_problem) {\n        if (a.precond_block_diagonal_accum) {\n          precond_block_diagonal_accum.reset(\n              new BlockDiagonalAccumulator<Scalar>());\n        }\n        res.setZero(num_rows);\n      }\n\n      inline void join(Reductor& b) {\n        if (precond_block_diagonal_accum) {\n          precond_block_diagonal_accum->join(*b.precond_block_diagonal_accum);\n        }\n        res += b.res;\n        numerically_valid &= b.numerically_valid;\n      }\n\n      size_t num_rows;\n      std::vector<LandmarkBlockPtr>& landmark_blocks;\n      const BalProblem<Scalar>& bal_problem;\n      std::unique_ptr<BlockDiagonalAccumulator<Scalar>>\n          precond_block_diagonal_accum;\n      VecX res;\n      bool numerically_valid = true;\n    };\n\n    const bool compute_precond_block_diagonal = precond_block_diagonal;\n\n    Reductor r(num_cameras_ * POSE_SIZE, compute_precond_block_diagonal,\n               landmark_blocks_, bal_problem_);\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_reduce(range, r);\n\n    if (r.numerically_valid) {\n      if (compute_precond_block_diagonal) {\n        *precond_block_diagonal =\n            std::move(r.precond_block_diagonal_accum->block_diagonal);\n      }\n\n      return r.res;\n    } else {\n      return {};  // for now, return empty vector to indicate numerical failure\n    }\n  }\n\n  // Operations grouped into stages. Stage2 includes Landmark damping, bref and\n  // precondition computations.\n  void get_stage2(Scalar lambda, const VecX* jacobian_scaling,\n                  IndexedBlocks<Scalar>* precond_block_diagonal, VecX& bref) {\n    struct Reductor {\n      Reductor(size_t num_rows, Scalar lambda, const VecX* jacobian_scaling,\n               bool precond_block_diagonal,\n               std::vector<LandmarkBlockPtr>& landmark_blocks)\n          : num_rows(num_rows),\n            lambda(lambda),\n            jacobian_scaling(jacobian_scaling),\n            landmark_blocks(landmark_blocks) {\n        if (precond_block_diagonal) {\n          precond_block_diagonal_accum.reset(\n              new BlockDiagonalAccumulator<Scalar>());\n        }\n        bref.setZero(num_rows);\n      }\n\n      void operator()(const tbb::blocked_range<size_t>& range) {\n        for (size_t r = range.begin(); r != range.end(); ++r) {\n          auto& lb = landmark_blocks[r];\n\n          lb->stage2(lambda, jacobian_scaling,\n                     precond_block_diagonal_accum.get(), bref);\n\n          //          // 1. scale jacobian\n          //          if (jacobian_scaling_) {\n          //            lb->scaleJp_cols(*jacobian_scaling_);\n          //          }\n\n          //          // 2. dampen landmarks\n          //          lb->setLandmarkDamping(lambda_);\n\n          //          // 3. compute block diagonal preconditioner\n          //          (SCHUR_JACOBI) if (precond_block_diagonal_accum_) {\n          //            lb->addQ2JpTQ2Jp_blockdiag(*precond_block_diagonal_accum_);\n          //          }\n\n          //          // 4. compute rhs of reduced camera normal equations\n          //          lb->addQ2JpTQ2r(bref_);\n        }\n      }\n\n      Reductor(Reductor& a, tbb::split /*unused*/)\n          : num_rows(a.num_rows),\n            lambda(a.lambda),\n            jacobian_scaling(a.jacobian_scaling),\n            landmark_blocks(a.landmark_blocks) {\n        if (a.precond_block_diagonal_accum) {\n          precond_block_diagonal_accum.reset(\n              new BlockDiagonalAccumulator<Scalar>());\n        }\n        bref.setZero(num_rows);\n      }\n\n      inline void join(Reductor& b) {\n        if (precond_block_diagonal_accum) {\n          precond_block_diagonal_accum->join(*b.precond_block_diagonal_accum);\n        }\n        bref += b.bref;\n      }\n\n      size_t num_rows;\n      Scalar lambda;\n      const VecX* jacobian_scaling;\n      std::vector<LandmarkBlockPtr>& landmark_blocks;\n\n      std::unique_ptr<BlockDiagonalAccumulator<Scalar>>\n          precond_block_diagonal_accum;\n      VecX bref;\n    };\n\n    const bool compute_precond_block_diagonal = precond_block_diagonal;\n\n    Reductor r(num_cameras_ * POSE_SIZE, lambda, jacobian_scaling,\n               compute_precond_block_diagonal, landmark_blocks_);\n\n    tbb::blocked_range<size_t> range(0, landmark_block_idx_.size());\n    tbb::parallel_reduce(range, r);\n\n    // add pose damping to preconditioners\n    if (has_pose_damping()) {\n      if (compute_precond_block_diagonal) {\n        r.precond_block_diagonal_accum->add_diag(\n            num_cameras_, POSE_SIZE,\n            VecX::Constant(num_cameras_ * POSE_SIZE, pose_damping_diagonal_));\n      }\n    }\n\n    // TODO: try these kinds of optimizations with std::move here and elsewhere:\n    // precond_block_diagonal =\n    //   std::move(r.precond_block_diagonal_accum->block_diagonal);\n    // bref = std::move(r.bref);\n\n    // move compute results to output variables\n    if (compute_precond_block_diagonal) {\n      *precond_block_diagonal =\n          std::move(r.precond_block_diagonal_accum->block_diagonal);\n    }\n    bref = std::move(r.bref);\n  }\n\n  void print_block(const std::string& filename, size_t block_idx) {\n    landmark_blocks_[block_idx].printStorage(filename);\n  }\n\n  size_t num_cols() const override { return this->num_cols_reduced(); }\n\n  VecX right_multiply(const VecX& x) const override {\n    return this->get_Q2TJp_T_Q2TJp_mult_x(x);\n  }\n\n protected:\n  Options options_;\n\n  std::vector<LandmarkBlockPtr> landmark_blocks_;\n  std::vector<size_t> landmark_block_idx_;\n  BalProblem<Scalar>& bal_problem_;\n\n  mutable std::vector<std::mutex> pose_mutex_;\n\n  Scalar pose_damping_diagonal_;\n  Scalar pose_damping_diagonal_sqrt_;\n\n  size_t num_cameras_;\n  size_t num_rows_Q2Tr_;\n};\n\n}  // namespace rootba\n", "meta": {"hexsha": "f127b3a2fff9177671a7fb84c62662740934182f", "size": 27848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rootba/qr/linearization_qr.hpp", "max_stars_repo_name": "zeta1999/rootba", "max_stars_repo_head_hexsha": "d1a680a88980d7ac57cf2ff7459d00ac1cab6c9a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2021-06-20T17:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:15:38.000Z", "max_issues_repo_path": "src/rootba/qr/linearization_qr.hpp", "max_issues_repo_name": "zeta1999/rootba", "max_issues_repo_head_hexsha": "d1a680a88980d7ac57cf2ff7459d00ac1cab6c9a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-07-10T11:51:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T00:05:39.000Z", "max_forks_repo_path": "src/rootba/qr/linearization_qr.hpp", "max_forks_repo_name": "NikolausDemmel/rootba", "max_forks_repo_head_hexsha": "0762f36a0afa7196709bd0fa147ae75ee7c7632c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T03:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:41:54.000Z", "avg_line_length": 31.9357798165, "max_line_length": 83, "alphanum_fraction": 0.6434932491, "num_tokens": 7226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577487985229844, "lm_q2_score": 0.030675802929152382, "lm_q1q2_score": 0.010913680101491973}}
{"text": "#pragma once\r\n\r\n#include <string>\r\n#include <sstream>\r\n#include <math/math.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n\r\n\r\nnamespace boost\r\n{\r\n\r\n    namespace detail\r\n    {\r\n\r\n        template<class Type>\r\n        struct base_conversion\r\n        {\r\n            static std::string save_to_string(const Type &arg)\r\n            {\r\n                std::ostringstream str;\r\n\r\n                for\r\n                (\r\n                    typename Type::const_iterator begin = arg.begin(), it = begin, end = arg.end();\r\n                    it != end;\r\n                    ++it\r\n                )\r\n                {\r\n                    if (it != begin) str << ' ';\r\n                    str << *it;\r\n                }\r\n\r\n                return str.str();\r\n            }\r\n        };\r\n\r\n        template<class Type, typename InternalType = typename Type::value_type>\r\n        struct conversion\r\n        {\r\n            static Type load_from_cstr(char *start)\r\n            {\r\n                throw_exception(bad_lexical_cast(typeid(std::string), typeid(Type)));\r\n            }\r\n        };\r\n\r\n        template<class Type>\r\n        struct conversion<Type, float> : public base_conversion<Type>\r\n        {\r\n            static Type load_from_cstr(char *start)\r\n            {\r\n                Type r;\r\n\r\n                char *stop  = start;\r\n\r\n                for\r\n                (\r\n                    typename Type::iterator it = r.begin(), end = r.end();\r\n                    it != end;\r\n                    ++it\r\n                )\r\n                {\r\n                    *it = typename Type::value_type(strtod(start, &stop));\r\n                    if (start != stop)\r\n                        start = stop;\r\n                    else\r\n                        throw_exception(bad_lexical_cast(typeid(std::string), typeid(Type)));\r\n                }\r\n\r\n                return r;\r\n            }\r\n        };\r\n\r\n        template<class Type>\r\n        struct conversion<Type, double> : public base_conversion<Type>\r\n        {\r\n            static Type load_from_cstr(char *str)\r\n            {\r\n                Type r;\r\n\r\n                char *start = str;\r\n                char *stop  = start;\r\n\r\n                for\r\n                (\r\n                    typename Type::iterator it = r.begin(), end = r.end();\r\n                    it != end;\r\n                    ++it\r\n                )\r\n                {\r\n                    *it = typename Type::value_type(strtod(start, &stop));\r\n                    if (start != stop)\r\n                        start = stop;\r\n                    else\r\n                        throw_exception(bad_lexical_cast(typeid(std::string), typeid(Type)));\r\n                }\r\n\r\n                return r;\r\n            }\r\n        };\r\n\r\n        template<class Type>\r\n        struct conversion<Type, int> : public base_conversion<Type>\r\n        {\r\n            static Type load_from_cstr(char *str)\r\n            {\r\n                Type r;\r\n\r\n                char *start = str;\r\n                char *stop  = start;\r\n\r\n                for\r\n                (\r\n                    typename Type::iterator it = r.begin(), end = r.end();\r\n                    it != end;\r\n                    ++it\r\n                )\r\n                {\r\n                    *it = typename Type::value_type(strtol(start, &stop, 10));\r\n                    if (start != stop)\r\n                        start = stop;\r\n                    else\r\n                        throw bad_lexical_cast(typeid(std::string), typeid(Type));\r\n                }\r\n\r\n                return r;\r\n            }\r\n        };\r\n\r\n        template<class Type>\r\n        struct conversion<Type, long> : public base_conversion<Type>\r\n        {\r\n            static Type load_from_cstr(char *str)\r\n            {\r\n                Type r;\r\n\r\n                char *start = str;\r\n                char *stop  = start;\r\n\r\n                for\r\n                (\r\n                    typename Type::iterator it = r.begin(), end = r.end();\r\n                    it != end;\r\n                    ++it\r\n                )\r\n                {\r\n                    *it = typename Type::value_type(strtol(start, &stop, 10));\r\n                    if (start != stop)\r\n                        start = stop;\r\n                    else\r\n                        throw_exception(bad_lexical_cast(typeid(std::string), typeid(Type)));\r\n                }\r\n\r\n                return r;\r\n            }\r\n        };\r\n\r\n    }\r\n\r\n\r\n    template<>\r\n    inline nMath::Vector2f lexical_cast<nMath::Vector2f, std::string>(const std::string &str)\r\n    { return detail::conversion<nMath::Vector2f>::load_from_cstr(const_cast<char*>(str.c_str())); }\r\n\r\n    template<>\r\n    inline std::string lexical_cast<std::string, nMath::Vector2f>(const nMath::Vector2f &v)\r\n    { return detail::conversion<nMath::Vector2f>::save_to_string(v); }\r\n\r\n\r\n    template<>\r\n    inline nMath::Vector3f lexical_cast<nMath::Vector3f, std::string>(const std::string &str)\r\n    { return detail::conversion<nMath::Vector3f>::load_from_cstr(const_cast<char*>(str.c_str())); }\r\n\r\n    template<>\r\n    inline std::string lexical_cast<std::string, nMath::Vector3f>(const nMath::Vector3f &v)\r\n    { return detail::conversion<nMath::Vector3f>::save_to_string(v); }\r\n\r\n\r\n    template<>\r\n    inline nMath::Vector4f lexical_cast<nMath::Vector4f, std::string>(const std::string &str)\r\n    { return detail::conversion<nMath::Vector4f>::load_from_cstr(const_cast<char*>(str.c_str())); }\r\n\r\n    template<>\r\n    inline std::string lexical_cast<std::string, nMath::Vector4f>(const nMath::Vector4f &v)\r\n    { return detail::conversion<nMath::Vector4f>::save_to_string(v); }\r\n\r\n\r\n    template<>\r\n    inline nMath::Quatf lexical_cast<nMath::Quatf, std::string>(const std::string &str)\r\n    { return detail::conversion<nMath::Quatf>::load_from_cstr(const_cast<char*>(str.c_str())); }\r\n\r\n    template<>\r\n    inline std::string lexical_cast<std::string, nMath::Quatf>(const nMath::Quatf &v)\r\n    { return detail::conversion<nMath::Quatf>::save_to_string(v); }\r\n\r\n}\r\n", "meta": {"hexsha": "f1558c24c244118842a7fbb28e536bc6c79cea55", "size": 6011, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/lexical_cast.hpp", "max_stars_repo_name": "ViperCraft/GameMathLib", "max_stars_repo_head_hexsha": "5115bbb4f0109c46688b3ff1291df1caffa69232", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "math/lexical_cast.hpp", "max_issues_repo_name": "ViperCraft/GameMathLib", "max_issues_repo_head_hexsha": "5115bbb4f0109c46688b3ff1291df1caffa69232", "max_issues_repo_licenses": ["Apache-2.0"], "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/lexical_cast.hpp", "max_forks_repo_name": "ViperCraft/GameMathLib", "max_forks_repo_head_hexsha": "5115bbb4f0109c46688b3ff1291df1caffa69232", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-02-05T08:48:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-05T08:48:34.000Z", "avg_line_length": 30.6683673469, "max_line_length": 100, "alphanum_fraction": 0.4536682748, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.03161876441702708, "lm_q1q2_score": 0.010911802261491268}}
{"text": "﻿\r\n\r\n#include <iostream>\r\n//#include <map>\r\n//#include <vector>\r\n//#include <list>\r\n//#include <functional>\r\n//\r\n//#include <boost/type_index.hpp>\r\n\r\n\r\nusing namespace std;\r\n//\r\n//#pragma warning(disable : 4996) \r\n\r\nnamespace _nmsp1\r\n{\t\r\n\t//泛化：大众化，常规\r\n\ttemplate <typename T,typename U>\r\n\tstruct TC\r\n\t{\r\n\t\tTC()\r\n\t\t{\r\n\t\t\tcout << \"TC泛化版本构造函数\" << endl;\r\n\t\t}\r\n\t\tvoid functest1()\r\n\t\t{\r\n\t\t\tcout << \"functest1泛化版本\" << endl;\r\n\t\t}\r\n\r\n\t\tstatic int m_stc;  //声明一个静态成员变量\r\n\t};\t\r\n\r\n\ttemplate <>\r\n\tvoid TC<double, int>::functest1() //functest1成员函数的全特化版本\r\n\t{\r\n\t\tcout << \"普通成员函数TC<double,int>::functest1的全特化\" << endl;\r\n\t}\r\n\r\n\ttemplate <typename T, typename U>\r\n\tint TC<T,U>::m_stc = 50; //定义静态成员变量\r\n\r\n\ttemplate <>\r\n\tint TC<double, int>::m_stc = 100;\r\n\r\n\t//-------------------\r\n\t/*template <> \r\n\tstruct TC<double, int>\r\n\t{\r\n\r\n\t};*/\r\n\r\n\t//-------------------\r\n\ttemplate <> //全特化：所有类型模板参数都yoghurt具体类型代表，所以<>里就空了\r\n\tstruct TC<int, int>\r\n\t{\r\n\t\tTC()\r\n\t\t{\r\n\t\t\tcout << \"TC<int,int>特化版本构造函数\" << endl;\r\n\t\t}\r\n\t\tvoid functest1();\r\n\t\t/*{\r\n\t\t\tcout << \"functest1特化版本\" << endl;\r\n\t\t}*/\r\n\r\n\t\tvoid functest2();\r\n\t\t/*{\r\n\t\t\tcout << \"functest2特化版本\" << endl;\r\n\t\t}*/\r\n\t};\r\n\t//template <>\r\n\tvoid TC<int, int>::functest1()\r\n\t{\r\n\t\tcout << \"functest1特化版本\" << endl;\r\n\t}\r\n\tvoid TC<int, int>::functest2()\r\n\t{\r\n\t\tcout << \"functest2特化版本\" << endl;\r\n\t}\r\n\r\n\t//-------------------------\r\n\ttemplate <typename U>\r\n\tstruct TC<float, U>\r\n\t{\r\n\t\tTC()\r\n\t\t{\r\n\t\t\tcout << \"TC<float,U>偏特化版本构造函数\" << endl;\r\n\t\t}\r\n\t\tvoid functest1();\r\n\t};\r\n\ttemplate <typename U>\r\n\tvoid  TC<float, U>::functest1()\r\n\t{\r\n\t\tcout << \"TC<float,U>::functest1偏特化版本\" << endl;\r\n\t}\r\n\r\n\t//---------范围偏特化-------------\r\n\ttemplate <typename T, typename U>\r\n\tstruct TC<const T, U*>\r\n\t{\r\n\t\tTC()\r\n\t\t{\r\n\t\t\tcout << \"TC<const T,U*>偏特化版本构造函数\" << endl;\r\n\t\t}\r\n\t\tvoid functest1();\r\n\t};\r\n\ttemplate <typename T, typename U>\r\n\tvoid TC<const T, U*>::functest1()\r\n\t{\r\n\t\tcout << \"TC<const T,U*>::functest1偏特化版本\" << endl;\r\n\t}\r\n\r\n}\r\n\r\n\r\nint main()\r\n{\t\r\n\t/***\r\n\t二：类模板的各种特化\r\n\t一般来讲，所写的类模板都是泛化的类模板\r\n\t特化的类模板是通过泛化的类模板来生成的，所以：得先要有泛化版本，才能有特化版本。\r\n\t所谓特化版本，就是特殊对待的版本\r\n\r\n\t2.1 类模板的全特化\r\n\t全特化：就是把TC这个泛化版本中的所有模板参数都用具体的类型来代替构成一个特殊的版本（全特化版本）。\r\n\t在理解上：泛化版本的类模板与全特化版本的类模板，只是名字相同（都叫TC），在其他方面，\r\n\t可以把实例化后的他们理解成是两个完全不同的类。\r\n\r\n\t2.2 普通成员函数的全特化\r\n\r\n\t2.3 静态成员变量的全特化\r\n\t特别值得一提的是：如果进行了普通成员函数的全特化，或者是静态成员变量的全特化，\r\n\t那么，就无法用这些全特化时指定的类型来对整个类模板进行全特化了。\r\n\r\n\t2.4 类模板的偏特化（局部特化）\r\n\t一方面：模板参数数量上的偏特化，另一方面是模板参数范围上的偏特化\r\n\r\n\t2.4.1 模板参数数量上的偏特化\r\n\t2.4.2 模板参数范围上的偏特化\r\n\tint ->const int.   T->T*  ,  T->T&    ,T->T&& \r\n\r\n\t***/\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t/*_nmsp1::TC<int, float> mytc;\r\n\tmytc.functest1();\r\n\r\n\t_nmsp1::TC<int, int> mytc2;\r\n\tmytc2.functest1();\r\n\tmytc2.functest2();*/\r\n\r\n\t/*_nmsp1::TC<double, int> mytc3;\r\n\tmytc3.functest1();\r\n\r\n\tcout << \"mytc3.m_stc = \" << mytc3.m_stc << endl;*/\r\n\r\n\t//_nmsp1::TC<float, int> mytc4;\r\n\t//mytc4.functest1();\r\n\r\n\t_nmsp1::TC<const float, int *> mytc5;\r\n\tmytc5.functest1();\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "ee8067b648931c5d714df2453653673252e2ca59", "size": 2846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/205.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/205.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/205.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 16.7411764706, "max_line_length": 57, "alphanum_fraction": 0.5639494027, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124119472172639, "lm_q2_score": 0.09807931358431081, "lm_q1q2_score": 0.010910460020605584}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/Stereo/PyramidCorrelator.h>\n#include <vw/Stereo/OptimizedCorrelator.h>\n#include <vw/Image/ImageViewRef.h>\n#include <vw/FileIO/DiskImageResource.h>\n#include <boost/foreach.hpp>\n\nusing namespace vw;\nusing namespace stereo;\n\nstd::vector<vw::BBox2i>\nPyramidCorrelator::subdivide_bboxes(ImageView<PixelDisp > const& disparity_map,\n                                    ImageView<PixelMask<uint8> > const& valid_pad,\n                                    BBox2i const& box) {\n  std::vector<BBox2i> result;\n  BBox2i box_div_2 = box / 2;\n  BBox2f disp_range;\n  try {\n    disp_range = get_disparity_range(crop(disparity_map, box_div_2));\n  } catch (const std::exception& /*e*/) {\n    // If there are no good pixels, don't add this box\n    if (count_valid_pixels(crop(valid_pad, box_div_2)) == 0)\n      return result;\n\n    // Return a large bbox so that we keep dividing\n    disp_range = BBox2f();\n  }\n\n  if (disp_range.width()*disp_range.height() <= 4 ||\n      (box.width() < m_min_subregion_dim && box.height() < m_min_subregion_dim)) {\n    // The bounding box is small enough.\n    result.push_back(box);\n    return result;\n  } else {\n    BBox2i subbox1 = box, subbox2 = box;\n    if (box.width() > box.height()) {\n      subbox1.max().x() = box.min().x() + box.width()/2;\n      subbox2.min().x() = box.min().x() + box.width()/2;\n    } else {\n      subbox1.max().y() = box.min().y() + box.height()/2;\n      subbox2.min().y() = box.min().y() + box.height()/2;\n    }\n\n    result = subdivide_bboxes(disparity_map, valid_pad, subbox1);\n    std::vector<BBox2i> l2 = subdivide_bboxes(disparity_map, valid_pad, subbox2);\n    result.insert(result.end(), l2.begin(), l2.end());\n    return result;\n  }\n}\n\nvoid draw_bbox(ImageView<PixelRGB<float> > &view, BBox2i const& bbox) {\n  int32 u,v;\n  // Top\n  v = bbox.min().y();\n  for (u = bbox.min().x(); u < bbox.max().x(); ++u)\n    view(u,v) = vw::PixelRGB<float>(1.0,0.0,0.0);\n\n  // Bottom\n  v = bbox.max().y()-1;\n  for (u = bbox.min().x(); u < bbox.max().x(); ++u)\n    view(u,v) = vw::PixelRGB<float>(1.0,0.0,0.0);\n\n  // Left\n  u = bbox.min().x();\n  for (v = bbox.min().y(); v < bbox.max().y(); ++v)\n    view(u,v) = vw::PixelRGB<float>(1.0,0.0,0.0);\n\n  // Left\n  u = bbox.max().x()-1;\n  for (v = bbox.min().y(); v < bbox.max().y(); ++v)\n    view(u,v) = vw::PixelRGB<float>(1.0,0.0,0.0);\n}\n\nvoid PyramidCorrelator::write_debug_images(int32 n, ImageViewRef<PixelDisp> const& disparity_map,\n                                           std::vector<BBox2i> const& nominal_blocks) {\n  std::ostringstream current_level;\n  current_level << n;\n  BBox2f disp_range;\n  try {\n    disp_range = get_disparity_range(disparity_map);\n  } catch (const std::exception& /*e*/) {\n    // There was no good pixels\n    disp_range = BBox2f();\n  }\n  ImageView<PixelRGB<float> > horz = normalize(clamp(select_channel(disparity_map,0), disp_range.min().x(), disp_range.max().x() ));\n  ImageView<PixelRGB<float> > vert = normalize(clamp(select_channel(disparity_map,1), disp_range.min().y(), disp_range.max().y() ));\n\n  for (size_t i = 0; i < nominal_blocks.size(); ++i) {\n    draw_bbox(horz, nominal_blocks[i]);\n    draw_bbox(vert, nominal_blocks[i]);\n  }\n\n  write_image( m_debug_prefix+current_level.str()+\"-H.jpg\", horz);\n  write_image( m_debug_prefix+current_level.str()+\"-V.jpg\", vert);\n}\n\n// Iterate over the nominal blocks, creating output blocks for correlation\n//\n// To compute the block size, we must 1) Adjust the and size of\n// the blocks for the right image to account for the disparity\n// search range, 2) adjust the size of the left image blocks to\n// be equal to the size of the right image blocks, and 3) buffer\n// both blocks by the kernel size.\n//\n// Returns an updated search range that has been recentered for use in\n// comparing the left_blocks and right_blocks.\nBBox2f PyramidCorrelator::compute_matching_blocks(BBox2i const& nominal_block,\n                                                BBox2f const& search_range,\n                                                BBox2i &left_block, BBox2i &right_block) {\n\n  left_block = nominal_block;\n\n  // The bounds of the right box depend on the size of the requested search range.\n  right_block = BBox2i(Vector2i(nominal_block.min().x()+int(floor(search_range.min().x())),\n                                nominal_block.min().y()+int(floor(search_range.min().y()))),\n                       Vector2i(nominal_block.max().x()+int(ceil(search_range.max().x())),\n                                nominal_block.max().y()+int(ceil(search_range.max().y()))));\n\n  // Ensure that the left and right blocks are the same size.\n  left_block.max() = Vector2i(nominal_block.min().x() + right_block.width(),\n                              nominal_block.min().y() + right_block.height());\n\n  // Pad all blocks by the kernel size\n  right_block.min() -= Vector2i(m_kernel_size[0], m_kernel_size[1]);\n  right_block.max() += Vector2i(m_kernel_size[0], m_kernel_size[1]);\n  left_block.min() -= Vector2i(m_kernel_size[0], m_kernel_size[1]);\n  left_block.max() += Vector2i(m_kernel_size[0], m_kernel_size[1]);\n\n  return BBox2f(0,0,ceil(search_range.width()),ceil(search_range.height()));\n}\n\n//  Use the previous level's disparity map to narrow the search range\n//  for each nominal block. At each new level, we buffer the search\n//  range slightly so that we cover all feasible disparity levels at\n//  the higher level of resolution.\nstd::vector<BBox2f>\nPyramidCorrelator::compute_search_ranges(ImageView<PixelDisp > const& prev_disparity_map,\n                                         std::vector<BBox2i> const& nominal_blocks) {\n  std::vector<BBox2f> search_ranges(nominal_blocks.size());\n  std::vector<bool> is_good(nominal_blocks.size());\n\n  // Step 1: compute the search ranges from the disparity map.\n  for (size_t i = 0; i < nominal_blocks.size(); ++i) {\n    ImageViewRef<PixelDisp > crop_disparity =\n      crop(prev_disparity_map,(nominal_blocks[i])/2);\n    if (count_valid_pixels(crop_disparity) > 20 * 20) {\n      search_ranges[i] = get_disparity_range(crop_disparity);\n      is_good[i]=true;\n    } else {\n      // Not enough good pixels available\n      search_ranges[i] = BBox2f(0, 0, 0, 0);\n      is_good[i]=false;\n    }\n  }\n\n  // Step 2: adjust the search range or fix it if it came from a\n  // block with zero valid pixels.\n  std::list<size_t> was_corrected;\n  for (size_t r = 0; r < nominal_blocks.size(); ++r) {\n\n    // Pick a reasonable search range based on neighboring tiles rather\n    // than skipping out entirely here.\n    if ( !is_good[r] ) {\n      // Find adjancent tiles and use the search ranges of adjacent\n      // tiles to seed us with a reasonable search range of our own.\n      //\n      // To do this test, we expand this block by 1 pixel in every\n      // direction and then test for intersections with other blocks.\n      BBox2i this_bbox = nominal_blocks[r];\n      this_bbox.expand(1);\n      bool found_one_match = false;\n      for (size_t b = 0; b < nominal_blocks.size(); ++b)\n        if ( is_good[b] && this_bbox.intersects(nominal_blocks[b])) {\n          if (found_one_match) {\n            search_ranges[r].grow(search_ranges[b]);\n          } else {\n            found_one_match = true;\n            was_corrected.push_back( r );\n            search_ranges[r] = search_ranges[b];\n          }\n        }\n    }\n  }\n\n  // Step 2 1/2: Mark good the search ranges that have been corrected\n  BOOST_FOREACH( size_t const& i, was_corrected ) {\n    is_good[i] = true;\n  }\n\n  // Step 3: scale up the search range for the next pyramid\n  // level and pad it here.\n  for (size_t r = 0; r < nominal_blocks.size(); ++r)\n    if ( is_good[r] ) {\n      search_ranges[r] *= 2;\n      search_ranges[r].expand(2);\n    }\n\n  return search_ranges;\n}\n", "meta": {"hexsha": "734168aa3c389f3d2134263a5c26be6dcc14eb54", "size": 7913, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Stereo/PyramidCorrelator.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Stereo/PyramidCorrelator.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Stereo/PyramidCorrelator.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 38.4126213592, "max_line_length": 132, "alphanum_fraction": 0.6371793252, "num_tokens": 2157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.029760094698923687, "lm_q1q2_score": 0.010909745680489582}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_Estimator.hpp\n//! \\author Alex Robinson\n//! \\brief  Estimator base class declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef FACEMC_ESTIMATOR_HPP\n#define FACEMC_ESTIMATOR_HPP\n\n// Std Lib Includes\n#include <string>\n#include <set>\n#include <map>\n#include <vector>\n\n// Boost Includes\n#include <boost/unordered_map.hpp>\n\n// Trilinos Includes\n#include <Teuchos_Array.hpp>\n#include <Teuchos_TwoDArray.hpp>\n#include <Teuchos_ScalarTraits.hpp>\n#include <Teuchos_any.hpp>\n#include <Teuchos_Comm.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_ParticleType.hpp\"\n#include \"MonteCarlo_ResponseFunction.hpp\"\n#include \"MonteCarlo_PhaseSpaceDimension.hpp\"\n#include \"MonteCarlo_PhaseSpaceDimensionTraits.hpp\"\n#include \"MonteCarlo_EstimatorDimensionDiscretization.hpp\"\n#include \"MonteCarlo_ModuleTraits.hpp\"\n#include \"MonteCarlo_EstimatorHDF5FileHandler.hpp\"\n#include \"Utility_GlobalOpenMPSession.hpp\"\n#include \"Utility_PrintableObject.hpp\"\n#include \"Utility_Tuple.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace MonteCarlo{\n\n//! The estimator base class\nclass Estimator : public Utility::PrintableObject\n{\n\npublic:\n\n  //! Typedef for estimator id\n  typedef ModuleTraits::InternalEstimatorHandle idType;\n\n  //! Typedef for tuple of estimator moments (1st,2nd)\n  typedef Utility::Pair<double,double> TwoEstimatorMoments;\n\n  //! Typedef for tuple of estimator moments (1st,2nd,3rd,4th)\n  typedef Utility::Quad<double,double,double,double> FourEstimatorMoments;\n\n  //! Typedef for the array of estimator moments \n  typedef Teuchos::Array<TwoEstimatorMoments> TwoEstimatorMomentsArray;\n\n  //! Typedef for the array of estimator moments\n  typedef Teuchos::Array<FourEstimatorMoments> FourEstimatorMomentsArray;\n\nprotected:\n\n  //! Typedef for Teuchos::ScalarTraits\n  typedef Teuchos::ScalarTraits<double> ST;\n  \n  // Typedef for map of dimension values\n  typedef boost::unordered_map<PhaseSpaceDimension,Teuchos::any> \n  DimensionValueMap;\n\npublic:\n\n  //! Set the number of particle histories that will be simulated\n  static void setNumberOfHistories( const unsigned long long num_histories );\n  \n  //! Set the start time for the figure of merit calculation\n  static void setStartTime( const double start_time );\n  \n  //! Set the end time for the figure of merit calculation\n  static void setEndTime( const double end_time );\n\n  //! Constructor\n  Estimator( const idType id,\n\t     const double multiplier );\n\n  //! Destructor\n  virtual ~Estimator()\n  { /* ... */ }\n\n  //! Return the estimator id\n  idType getId() const;\n\n  //! Set the bin boundaries for a dimension of the phase space (floating pt)\n  template<PhaseSpaceDimension dimension, typename DimensionType>\n  void setBinBoundaries( const Teuchos::Array<DimensionType>& bin_boundaries );\n  \n  //! Return the number of bins for a dimension of the phase space\n  unsigned getNumberOfBins( const PhaseSpaceDimension dimension ) const;\n\n  //! Return the total number of bins\n  unsigned getNumberOfBins() const;\n\n  //! Set the response functions\n  virtual void setResponseFunctions( \n   const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_functions );\n\n  //! Return the number of response functions\n  unsigned getNumberOfResponseFunctions() const;\n\n  //! Set the particle types that can contribute to the estimator\n  virtual void setParticleTypes( \n\t\t\t  const Teuchos::Array<ParticleType>& particle_types );\n\n  //! Check if the particle type is assigned to the estimator\n  bool isParticleTypeAssigned( const ParticleType particle_type ) const;\n\n  //! Check if the estimator has uncommitted history contributions\n  bool hasUncommittedHistoryContribution( const unsigned thread_id ) const;\n\n  //! Check if the estimator has uncommitted history contributions\n  bool hasUncommittedHistoryContribution() const;\n\n  //! Enable support for multiple threads\n  virtual void enableThreadSupport( const unsigned num_threads );\n\n  //! Commit the contribution from the current history to the estimator\n  virtual void commitHistoryContribution() = 0;\n\n  //! Reset estimator data\n  virtual void resetData() = 0;\n\n  //! Reduce estimator data on all processes in comm and collect on the root \n  virtual void reduceData( \n\t    const Teuchos::RCP<const Teuchos::Comm<unsigned long long> >& comm,\n\t    const int root_process ) = 0;\n\n  //! Export the estimator data\n  virtual void exportData( EstimatorHDF5FileHandler& hdf5_file,\n\t\t\t   const bool process_data ) const;\n  \nprotected:\n\n  //! Set the has uncommited history contribution flag\n  void setHasUncommittedHistoryContribution( const unsigned thread_id );\n\n  //! Unset the has uncommited history contribution flag\n  void unsetHasUncommittedHistoryContribution( const unsigned thread_id );\n\n  //! Assign bin boundaries to an estimator dimension\n  virtual void assignBinBoundaries( \n\tconst Teuchos::RCP<EstimatorDimensionDiscretization>& bin_boundaries );\n\n  //! Return the estimator constant multiplier\n  double getMultiplier() const;\n\n  //! Return the response function name\n  const std::string& getResponseFunctionName( \n\t\t\t\tconst unsigned response_function_index ) const;\n\n  //! Return the name of the bin (with response function)\n  std::string getBinName( const unsigned bin_index ) const;\n\n  //! Print the estimator response function names\n  void printEstimatorResponseFunctionNames( std::ostream& os ) const;\n\n  //! Print the estimator bins\n  void printEstimatorBins( std::ostream& os ) const;\n\n  //! Print the estimator data stored in an array\n  void printEstimatorBinData( \n\t\t\t std::ostream& os,\n\t\t\t const TwoEstimatorMomentsArray& estimator_moment_data,\n\t\t\t const double norm_constant ) const;\n\n  //! Print the total estimator data stored in an array\n  void printEstimatorTotalData( \n\t\t std::ostream& os,\n\t\t const FourEstimatorMomentsArray& total_estimator_moments_data,\n\t\t const double norm_constant ) const;\n\n  //! Evaluate the desired response function\n  double evaluateResponseFunction( \n\t\t\t\tconst ParticleState& particle,\n\t\t\t\tconst unsigned response_function_index ) const;\n\n  //! Convert particle state to a generic map\n  void convertParticleStateToGenericMap( \n\t\t\t\t   const ParticleState& particle,\n\t\t\t\t   const double angle_cosine,\n\t\t\t\t   DimensionValueMap& dimension_values ) const;\n\n  //! Check if the point is in the estimator phase space\n  bool isPointInEstimatorPhaseSpace( \n\t\t             const DimensionValueMap& dimension_values ) const;\n\t\t\t        \n  //! Calculate the bin index for the desired response function\n  unsigned calculateBinIndex( const DimensionValueMap& dimension_values,\n\t\t\t      const unsigned response_function_index ) const;\n\n  //! Calculate the response function index given a bin index\n  unsigned calculateResponseFunctionIndex( const unsigned bin_index ) const;\n\n  //! Convert first and second moments to mean and relative error\n  void processMoments( const Utility::Pair<double,double>& moments,\n\t\t       const double norm_constant,\n\t\t       double& mean,\n\t\t       double& relative_error ) const;\n\n  //! Convert first, second, third, fourth moments to mean, rel. er., vov, fom\n  void processMoments( \n\t\t     const Utility::Quad<double,double,double,double>& moments,\n\t\t     const double norm_constant,\n\t\t     double& mean,\n\t\t     double& relative_error,\n\t\t     double& variance_of_variance,\n\t\t     double& figure_of_merit ) const;\n\nprivate:\n\n  // Convert a portion of the particle state to a generic map\n  template<PhaseSpaceDimension dimension>\n  void convertPartialParticleStateToGenericMap( \n\t\t\t\t   const ParticleState& particle,\n\t\t\t           DimensionValueMap& dimension_values ) const;\n\n  // Calculate the mean of a set of contributions\n  double calculateMean( const double first_moment_contributions ) const;\n\n  // Calculate the relative error of a set of contributions\n  double calculateRelativeError( \n\t\t\t      const double first_moment_contributions,\n\t\t\t      const double second_moment_contributions ) const;\n\n  // Calculate the variance of the variance (VOV) of a set of contributions\n  double calculateVOV( const double first_moment_contributions,\n\t\t       const double second_moment_contributions,\n\t\t       const double third_moment_contributions,\n\t\t       const double fourth_moment_contributions ) const;\n\n  // Calculate the figure of merit (FOM) of an estimator bin\n  double calculateFOM( const double relative_error ) const;\n\t\t\t     \n  // The tolerance used for relative error and vov calculations\n  static double tol;\n\n  // The number of particle histories that will be run\n  static unsigned long long num_histories;\n\n  // The start time used for the figure of merit calculation\n  static double start_time;\n\n  // The end time used for the figure of merit calculation\n  static double end_time;\n\n  // The estimator id\n  idType d_id;\n\n  // The constant multiplier for the estimator\n  double d_multiplier;\n\n  // Records if there is an uncommitted history contribution\n  Teuchos::Array<unsigned char> d_has_uncommitted_history_contribution;\n\n  // The response functions\n  Teuchos::Array<Teuchos::RCP<ResponseFunction> > d_response_functions;\n  \n  // The estimator phase space dimension bin boundaries map\n  boost::unordered_map<PhaseSpaceDimension,\n  \t\t       Teuchos::RCP<EstimatorDimensionDiscretization> >\n  d_dimension_bin_boundaries_map;\n\n  // The estimator phase space dimension index step size map\n  boost::unordered_map<PhaseSpaceDimension,unsigned>\n  d_dimension_index_step_size_map;\n\n  // The estimator phase space dimension ordering\n  Teuchos::Array<PhaseSpaceDimension> d_dimension_ordering;\n\n  // The particle types that this estimator will take contributions from\n  std::set<ParticleType> d_particle_types;\n};\n\n// Return the estimator id\ninline Estimator::idType Estimator::getId() const\n{\n  return d_id;\n}\n\n// Return the estimator constant multiplier\ninline double Estimator::getMultiplier() const\n{\n  return d_multiplier;\n}\n\n// Return the number of bins for a dimension of the phase space\ninline unsigned Estimator::getNumberOfBins( \n\t\t\t\t    const PhaseSpaceDimension dimension ) const\n{\n  if( d_dimension_bin_boundaries_map.count( dimension ) != 0 )\n    return d_dimension_bin_boundaries_map.find(dimension)->second->getNumberOfBins();\n  else\n    return 1u;\n}\n\n// Return the total number of bins\ninline unsigned Estimator::getNumberOfBins() const\n{\n  unsigned number_of_bins = 1u;\n  \n  for( unsigned i = 0u; i < d_dimension_ordering.size(); ++i )\n    number_of_bins *= getNumberOfBins( d_dimension_ordering[i] );\n  \n  return number_of_bins;\n}\n\n// Return the number of response functions\ninline unsigned Estimator::getNumberOfResponseFunctions() const\n{\n  return d_response_functions.size();\n}\n\n// Check if the particle type is assigned to the estimator\ninline bool Estimator::isParticleTypeAssigned( \n\t\t\t\t\tconst ParticleType particle_type) const\n{\n  return d_particle_types.count( particle_type );\n}\n\n// Return the response function name\ninline const std::string& Estimator::getResponseFunctionName( \n\t\t\t\t const unsigned response_function_index ) const\n{\n  // Make sure the response function index is valid\n  testPrecondition( response_function_index < getNumberOfResponseFunctions() );\n\n  return d_response_functions[response_function_index]->getName();\n}\n\n// Evaluate the desired response function\ninline double Estimator::evaluateResponseFunction( \n\t\t\t\t const ParticleState& particle,\n\t\t\t\t const unsigned response_function_index ) const\n{\n  // Make sure the response function index is valid\n  testPrecondition( response_function_index < getNumberOfResponseFunctions() );\n  \n  return d_response_functions[response_function_index]->evaluate( particle );\n}\n\n// Convert particle state to a generic map\ninline void Estimator::convertParticleStateToGenericMap( \n\t\t\t      const ParticleState& particle,\n\t\t\t      const double angle_cosine,\n\t\t\t      DimensionValueMap& dimension_values ) const\n{\n  // It may be useful to neglect the COSINE_DIMENSION in the future...\n  convertPartialParticleStateToGenericMap<DIMENSION_start>( particle,\n\t\t\t\t\t\t\t    dimension_values );\n\n  // Assign the cosine dimension value separately\n  dimension_values[COSINE_DIMENSION] = \n    PhaseSpaceDimensionTraits<COSINE_DIMENSION>::obfuscateValue( \n\t\t\t\t\t\t\t\tangle_cosine );\n}\n\n// Check if the estimator has uncommitted history contributions\ninline bool Estimator::hasUncommittedHistoryContribution() const\n{\n  return hasUncommittedHistoryContribution( \n\t\t\t\t Utility::GlobalOpenMPSession::getThreadId() );\n}\n\n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"MonteCarlo_Estimator_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end FACEMC_ESTIMATOR_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_Estimator.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "90415214d439103f8a787eae71fd08e40564cdae", "size": 13060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/estimator/native/src/MonteCarlo_Estimator.hpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/monte_carlo/estimator/native/src/MonteCarlo_Estimator.hpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/monte_carlo/estimator/native/src/MonteCarlo_Estimator.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": 33.4871794872, "max_line_length": 85, "alphanum_fraction": 0.7296324655, "num_tokens": 2777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.03258974359152876, "lm_q1q2_score": 0.010904184098874208}}
{"text": "//\n// $Id$\n//\n// The contents of this file are subject to the Mozilla Public License\n// Version 1.1 (the \"License\"); you may not use this file except in\n// compliance with the License. You may obtain a copy of the License at\n// http://www.mozilla.org/MPL/\n//\n// Software distributed under the License is distributed on an \"AS IS\"\n// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the\n// License for the specific language governing rights and limitations\n// under the License.\n//\n// The Original Code is the DirecTag peptide sequence tagger.\n//\n// The Initial Developer of the Original Code is Zeqiang Ma.\n//\n// Copyright 2009 Vanderbilt University\n//\n// Contributor(s):\n//\n\r\n// adjust ScanRanker scores by groups\r\n// use mean and IQR of all files in a group for score normalization\r\n// input: ScanRanker metrics files separated by comma, one line for one group\r\n\r\n#include <stdio.h>\r\n#include <vector>\r\n#include <string>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <stdexcept>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/filesystem.hpp>\r\n\r\nusing boost::lexical_cast;\r\nusing namespace std;\r\n\r\nstruct ScoreInfo\r\n{\r\n    float    bestTagScoreMean;\r\n    float    bestTagTICMean;\r\n    float    tagMzRangeMean;\r\n    float    bestTagScoreIQR;\r\n    float    bestTagTICIQR;\r\n    float    tagMzRangeIQR;\r\n    int        numTaggedSpectra;\r\n};\r\n\r\n///    <summary>\r\n///    extract ScanRanker subscore information from a metrics file\r\n///    </summary>\r\nvoid getHeader(const string& filename, ScoreInfo *scoreInfo )     \r\n{\r\n    // Open the input file\r\n    ifstream fileStream( filename.c_str() );\r\n    if( !fileStream.is_open() )\r\n        throw invalid_argument( string( \"unable to open file \\\"\" ) + filename + \"\\\"\" );\r\n\r\n    string headerLine;\r\n    getline(fileStream, headerLine); //discard the first header line: H    BestTagScoreMean    BestTagTICMean    TagMzRangeMean    BestTagScoreIQR    BestTagTICIQR    TagMzRangeIQR    numTaggedSpectra\r\n    getline(fileStream, headerLine); // get second line, e.g.: H    25.4616    7.06014    701.679    12.0654    4.52176    305.127    18587\r\n    stringstream lineStream(headerLine);\r\n    string segments;\r\n    vector<string> v;\r\n    while(getline(lineStream,segments,'\\t'))\r\n    {\r\n        v.push_back(segments);\r\n    }\r\n//    copy(v.begin(), v.end(), ostream_iterator<string>(cout, \"\\n\"));\r\n\r\n    scoreInfo->bestTagScoreMean = lexical_cast<float>( v[1] );\r\n    scoreInfo->bestTagTICMean = lexical_cast<float>( v[2] );\r\n    scoreInfo->tagMzRangeMean = lexical_cast<float>( v[3] );\r\n    scoreInfo->bestTagScoreIQR = lexical_cast<float>( v[4] );\r\n    scoreInfo->bestTagTICIQR = lexical_cast<float>( v[5] );\r\n    scoreInfo->tagMzRangeIQR = lexical_cast<float>( v[6] );\r\n    scoreInfo->numTaggedSpectra = lexical_cast<int>( v[7] );\r\n}\r\n\r\n\r\n///    <summary>\r\n///    adjust scores with global mean and IQR of a group, write new metrics file\r\n///    </summary>\r\nvoid adjustScore(    const string& filename,     \r\n                    float    gbBestTagScoreMean,\r\n                    float    gbBestTagTICMean,\r\n                    float    gbTagMzRangeMean,\r\n                    float    gbBestTagScoreIQRMean,\r\n                    float    gbBestTagTICIQRMean,\r\n                    float    gbTagMzRangeIQRMean)   \r\n{\r\n    cout << '\\t' << filename << '\\n';\r\n    namespace bfs = boost::filesystem;\r\n    bfs::path newFilename = bfs::basename(filename) + \"-adjusted.txt\";\r\n     string outputFilename = newFilename.string();\r\n    ofstream ofileStream( outputFilename.c_str() );\n\r\n    // Open the input file\r\n    ifstream fileStream( filename.c_str() );\r\n    if( !fileStream.is_open() )\r\n        throw invalid_argument( string( \"unable to open file \\\"\" ) + filename + \"\\\"\" );\r\n\r\n    string line;\r\n    while( getline(fileStream, line))\r\n    {\r\n        if (line.find(\"H\\tBestTagScoreMean\") != string::npos)\r\n        {\r\n            ofileStream << \"H\\tBestTagScoreMean\\tBestTagTICMean\\tTagMzRangeMean\\tBestTagScoreIQR\\tBestTagTICIQR\\tTagMzRangeIQR\\tnumTaggedSpectra\\tgbBestTagScoreMean\\tgbBestTagTICMean\\tgbTagMzRangeMean\\tgbBestTagScoreIQRMean\\tgbBestTagTICIQRMean\\tgbTagMzRangeIQRMean\\n\";\r\n        }\r\n        else if (line.find(\"H\\tIndex\") != string::npos)    // if header line, write out line, else extract subscores and compute the new score\r\n        {\n            ofileStream << line << \"\\tAdjustedScore\\n\"; \r\n        }\r\n        else if (line.find(\"H\\t\") != string::npos)\r\n        {\r\n            ofileStream << line << '\\t'\r\n                        << gbBestTagScoreMean << '\\t'\r\n                        << gbBestTagTICMean << '\\t'\r\n                        << gbTagMzRangeMean << '\\t'\r\n                        << gbBestTagScoreIQRMean << '\\t'\r\n                        << gbBestTagTICIQRMean << '\\t'\r\n                        << gbTagMzRangeIQRMean << '\\n';\r\n\r\n\r\n        }\r\n        else\r\n        {\r\n            stringstream lineStream(line);\r\n            string segments;\r\n            vector<string> v;\r\n            while(getline(lineStream,segments,'\\t'))\r\n            {\r\n                v.push_back(segments);\r\n            }\r\n            // metrics file format:\r\n            //H    NativeID    PrecursorMZ    Charge    PrecursorMass    BestTagScore    BestTagTIC    TagMzRange    ScanRankerScore\r\n            float bestTagScore = lexical_cast<float>( v[5] );\r\n            float bestTagTIC = lexical_cast<float>( v[6] );\r\n            float tagMzRange = lexical_cast<float>( v[7] );\r\n            float originalScore = lexical_cast<float>( v[8] );\r\n            float bestTagScoreNorm = ( bestTagScore - gbBestTagScoreMean ) / gbBestTagScoreIQRMean;\r\n            float bestTagTICNorm = ( bestTagTIC - gbBestTagTICMean ) / gbBestTagTICIQRMean;\r\n            float tagMzRangeNorm = ( tagMzRange - gbTagMzRangeMean ) / gbTagMzRangeIQRMean;\r\n            float adjustedScore = ( bestTagScoreNorm + bestTagTICNorm + tagMzRangeNorm) / 3;\r\n\r\n            ofileStream << line << '\\t' << adjustedScore << '\\n';\r\n        }\r\n    }\r\n}\r\n\r\n\r\nint main( int argc, char* argv[] )\n{\n    if (argc < 2)\n    {\n        cerr << \"Not enough arguments.\\n\" << \"Usage: \" << argv[0] << \"   groupFile\" << endl;\n        return 1;\n    }\n\n    ifstream  groupFile( argv[1] );\r\n    string line;\r\n    while(getline(groupFile,line))  //work on each group; one line one group, separated with \",\"\r\n    {\r\n        stringstream  lineStream(line);\r\n        string        file;\r\n        vector<ScoreInfo> scoreInfoVector;\r\n        //cout << \"Extracting subscore infomation from metrics files ... \\n\" << endl;\r\n        while(getline(lineStream,file,','))  //work on a sigle file in a group, extract mean and IQR from each file \r\n        {\r\n            ScoreInfo scoreInfo;\r\n            getHeader( file, &scoreInfo );\r\n            scoreInfoVector.push_back( scoreInfo );\r\n        }\r\n\r\n        // iterate scoreInforVector, compute global mean and IQR for normalization\r\n        float    gbBestTagScoreSum = 0.0;\r\n        float    gbBestTagTICSum = 0.0;\r\n        float    gbTagMzRangeSum = 0.0;\r\n        float    gbBestTagScoreIQRSum = 0.0;\r\n        float    gbBestTagTICIQRSum = 0.0;\r\n        float    gbTagMzRangeIQRSum = 0.0;\r\n        int        totalSpectra = 0;        \r\n\r\n        for( vector<ScoreInfo>::iterator itr = scoreInfoVector.begin(); itr != scoreInfoVector.end(); ++itr )\n        {\n            gbBestTagScoreSum += itr->bestTagScoreMean * itr->numTaggedSpectra ;\r\n            gbBestTagTICSum += itr->bestTagTICMean * itr->numTaggedSpectra ;\r\n            gbTagMzRangeSum += itr->tagMzRangeMean * itr->numTaggedSpectra ;\r\n            gbBestTagScoreIQRSum += itr->bestTagScoreIQR ;\r\n            gbBestTagTICIQRSum += itr->bestTagTICIQR ;\r\n            gbTagMzRangeIQRSum += itr->tagMzRangeIQR ;\r\n            totalSpectra +=  itr->numTaggedSpectra ;\r\n        }\r\n\r\n        int numFiles = (int) scoreInfoVector.size();\r\n        float gbBestTagScoreMean = gbBestTagScoreSum / (float) totalSpectra;\r\n        float gbBestTagTICMean = gbBestTagTICSum / (float) totalSpectra;\r\n        float gbTagMzRangeMean = gbTagMzRangeSum / (float) totalSpectra;\r\n        float gbBestTagScoreIQRMean = gbBestTagScoreIQRSum / (float) numFiles;\r\n        float gbBestTagTICIQRMean = gbBestTagTICIQRSum / (float) numFiles;\r\n        float gbTagMzRangeIQRMean = gbTagMzRangeIQRSum / (float) numFiles;\r\n        \r\n        lineStream.clear(); // reset lineStream for getline()\r\n        lineStream.seekg(0,std::ios::beg);\r\n        cout << \"Adjusting ScanRanker scores ...\\n\" << endl;\r\n        while(getline(lineStream,file,','))  //work on a sigle file in a group, add adjusted scores \r\n        {\r\n            adjustScore(    file, \r\n                            gbBestTagScoreMean,\r\n                            gbBestTagTICMean,\r\n                            gbTagMzRangeMean,\r\n                            gbBestTagScoreIQRMean,\r\n                            gbBestTagTICIQRMean,\r\n                            gbTagMzRangeIQRMean);\r\n        }\r\n\r\n    }\r\n}\r\n", "meta": {"hexsha": "a134eff222ce8711f9939d6e122895a08bb025ee", "size": 8960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz_tools/Bumbershoot/directag/adjustScanRankerScoreByGroup.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz_tools/Bumbershoot/directag/adjustScanRankerScoreByGroup.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz_tools/Bumbershoot/directag/adjustScanRankerScoreByGroup.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5429864253, "max_line_length": 270, "alphanum_fraction": 0.6003348214, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.02405355123285508, "lm_q1q2_score": 0.010902557083136664}}
{"text": "#include <boost/python.hpp>\n#include <numpy/arrayobject.h>\n#include <numpy_eigen.h>\n#include <omp.h>\n\n#include \"integrand.h\"\n\nusing namespace Eigen;\n\n\nPyObject* calc_Gavg(PyObject *pyw, const double &delta, const double &mu, \n    PyObject *pySE, PyObject *pyTB, const double &Hf, PyObject *py_bp, \n    PyObject *py_wf, const int nthreads) {\n  try {\n    if (nthreads > 0) omp_set_num_threads(nthreads);\n    MatrixXcd SE;\n    VectorXcd w;\n    VectorXd bp, wf;\n    VectorXd SlaterKosterCoeffs;\n\n    numpy::from_numpy(pySE, SE);\n    numpy::from_numpy(pyTB, SlaterKosterCoeffs);\n    numpy::from_numpy(py_bp, bp);\n    numpy::from_numpy(py_wf, wf);\n    numpy::from_numpy(pyw, w);\n    assert(w.size() == SE.rows());\n\n    double t = SlaterKosterCoeffs(0);\n    VectorXd xl(DIM), xh(DIM);\n    xl << -2*t;\n    xh << 2*t;\n    double BZ1 = 1.;\n\n    MatrixXcd result(SE.rows(), MSIZE*MSIZE);\n    VectorXcd tmp(MSIZE);\n    GreenIntegrand green_integrand(w, mu, SE, SlaterKosterCoeffs, Hf);\n    result.setZero();\n    for (int n = 0; n < w.size(); ++n) {\n      green_integrand.set_data(n);\n      tmp = md_int::Integrate(xl, xh, green_integrand, bp, wf);\n      for (int i = 0; i < MSIZE; ++i)\n        result(n, MSIZE*i + i) = tmp(i);\n    }\n    result /= BZ1;\n    return numpy::to_numpy(result);\n  } catch (const char *str) {\n      std::cerr << str << std::endl;\n      return Py_None;\n    }\n}\n\nPyObject* calc_Havg(const int &Norder, PyObject *pyTB, const double &Hf, \n    const double &delta, PyObject *py_bp, PyObject *py_wf) {\n  try {\n    MatrixXi R;\n    VectorXd bp, wf;\n    VectorXd SlaterKosterCoeffs;\n\n    numpy::from_numpy(pyTB, SlaterKosterCoeffs);\n    numpy::from_numpy(py_bp, bp);\n    numpy::from_numpy(py_wf, wf);\n\n    double t = SlaterKosterCoeffs(0);\n    VectorXd xl(DIM), xh(DIM);\n    xl << -2*t;\n    xh << 2*t;\n    double BZ1 = 1.;\n\n    HIntegrand h_integrand(Norder, SlaterKosterCoeffs, Hf);\n    VectorXd result = (md_int::Integrate(xl, xh, h_integrand, bp, wf)).real();\n    result /= BZ1;\n    VectorXd ret(Norder*MSIZE*MSIZE);\n    ret.setZero();\n    for (int i = 0; i < Norder; ++i)\n      for (int j = 0; j < MSIZE; ++j)\n        ret(MSIZE*MSIZE*i + MSIZE*j + j) = result(MSIZE*i + j);\n    return numpy::to_numpy(ret);\n  } catch (const char *str) {\n    std::cerr << str << std::endl;\n    return Py_None;\n  }\n}\n\nBOOST_PYTHON_MODULE(int_bethe_lattice)\n{\n  using namespace boost::python;\n  def(\"calc_Gavg\", calc_Gavg);\n  def(\"calc_Havg\", calc_Havg);\n}\n", "meta": {"hexsha": "4f3d724f0c3c0f5d686bd9c3b512f26b890c3995", "size": 2445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integrate_bethe_lattice/main.cpp", "max_stars_repo_name": "hungdt/scf_dmft", "max_stars_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T17:44:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:55:13.000Z", "max_issues_repo_path": "integrate_bethe_lattice/main.cpp", "max_issues_repo_name": "hungdt/scf_dmft", "max_issues_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integrate_bethe_lattice/main.cpp", "max_forks_repo_name": "hungdt/scf_dmft", "max_forks_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1666666667, "max_line_length": 78, "alphanum_fraction": 0.6253578732, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.025565213830466525, "lm_q1q2_score": 0.010899002674021616}}
{"text": "#include \"Delaunay.hpp\"\n#include <vector>\n#include <cmath>\n#include \"../misc/triplet.hpp\"\n#include <boost/foreach.hpp>\n#ifdef RICH_MPI\n#include <mpi.h>\n#endif // RICH_MPI\n\nnamespace {\n\tpair<int, int> find_diff(const facet& f1, const facet& f2)\n\t{\n\t\tif (f1.vertices.first != f2.vertices.first &&\n\t\t\tf1.vertices.first != f2.vertices.second &&\n\t\t\tf1.vertices.first != f2.vertices.third)\n\t\t\treturn pair<int, int>(f1.vertices.first, 0);\n\t\telse if (f1.vertices.second != f2.vertices.first &&\n\t\t\tf1.vertices.second != f2.vertices.second &&\n\t\t\tf1.vertices.second != f2.vertices.third)\n\t\t\treturn pair<int, int>(f1.vertices.second, 1);\n\t\telse if (f1.vertices.third != f2.vertices.first &&\n\t\t\tf1.vertices.third != f2.vertices.second &&\n\t\t\tf1.vertices.third != f2.vertices.third)\n\t\t\treturn pair<int, int>(f1.vertices.third, 2);\n\t\telse\n\t\t\tthrow UniversalError(\"Delaunay, Couldn't find difference bewteen two facets\");\n\t}\n}\n\nDelaunay::DataOnlyForBuild::DataOnlyForBuild() :copied(vector<vector<char> >())\n{}\n\nDelaunay::DataOnlyForBuild::DataOnlyForBuild(DataOnlyForBuild const& other) :copied(other.copied) {}\n\nDelaunay::DataOnlyForBuild& Delaunay::DataOnlyForBuild::operator=\n(DataOnlyForBuild const& other)\n{\n\tif (this != &other)\n\t{\n\t\tcopied = other.copied;\n\t}\n\treturn *this;\n}\n\nDelaunay::Delaunay(void) :\n\tlastFacet(0), CalcRadius(false),\n\tradius(vector<double>()), cell_points(vector<Vector2D>()),\n\tPointWasAdded(false),\n\tlast_facet_added(0),\n\tf(vector<facet>()),\n\tcor(vector<Vector2D>()),\n\tlength(0),\n\tolength(0), location_pointer(0), last_loc(0),\n\tlogger(0)\n#ifdef RICH_MPI\n\t,OrgIndex(vector<int>())\n#endif\n{}\n\nDelaunay::Delaunay(Delaunay const& other) :\n\tlastFacet(other.lastFacet),\n\tCalcRadius(other.CalcRadius),\n\tradius(other.radius), cell_points(other.cell_points),\n\tPointWasAdded(other.PointWasAdded),\n\tlast_facet_added(other.last_facet_added),\n\tf(other.f),\n\tcor(other.cor),\n\tlength(other.length),\n\tolength(other.olength),\n\tlocation_pointer(other.location_pointer),\n\tlast_loc(other.last_loc),\n\tlogger(other.logger)\n#ifdef RICH_MPI\n\t,OrgIndex(other.OrgIndex)\n#endif\n{}\n\nDelaunay::~Delaunay(void)\n{\n\tcor.clear();\n\tf.clear();\n\tcell_points.clear();\n}\n\nnamespace\n{\n\t// Checks if a point is inside a triangle\n\tbool InTriangle(const TripleConstRef<Vector2D>& tri,\n\t\tconst Vector2D& point)\n\t{\n\t\treturn (orient2d(TripleConstRef<Vector2D>(tri.first,\n\t\t\ttri.second,\n\t\t\tpoint)) > 0) &&\n\t\t\t(orient2d(TripleConstRef<Vector2D>(tri.second,\n\t\t\t\ttri.third,\n\t\t\t\tpoint)) > 0) &&\n\t\t\t(orient2d(TripleConstRef<Vector2D>(tri.third,\n\t\t\t\ttri.first,\n\t\t\t\tpoint)) > 0);\n\t}\n\n\t// Assume cell is orederd in convexhull counterclockwise\n\tbool InCell(vector<Vector2D> const& points, Vector2D const& p)\n\t{\n\t\tint n = static_cast<int>(points.size());\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (CrossProduct(points[static_cast<size_t>(i)] - p, points[static_cast<size_t>((i + 1) % n)] - p) < 0)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tvector<double> CellSize(vector<Vector2D> const& points)\n\t{\n\t\tint n = static_cast<int>(points.size());\n\t\tdouble minx = points[0].x;\n\t\tdouble miny = points[0].y;\n\t\tdouble maxx = minx;\n\t\tdouble maxy = miny;\n\t\tfor (int i = 1; i < n; ++i)\n\t\t{\n\t\t\tminx = min(points[static_cast<size_t>(i)].x, minx);\n\t\t\tminy = min(points[static_cast<size_t>(i)].y, miny);\n\t\t\tmaxx = max(points[static_cast<size_t>(i)].x, maxx);\n\t\t\tmaxy = max(points[static_cast<size_t>(i)].y, maxy);\n\t\t}\n\t\tvector<double> res(4);\n\t\tres[0] = minx;\n\t\tres[1] = maxx;\n\t\tres[2] = miny;\n\t\tres[3] = maxy;\n\t\treturn res;\n\t}\n\n\tsize_t find_index(facet const& fc, int i)\n\t{\n\t\tfor (size_t j = 0; j < 3; ++j)\n\t\t{\n\t\t\tif (fc.neighbors[j] == i)\n\t\t\t\treturn j;\n\t\t}\n\t\tthrow UniversalError(\"Error in find_index: Index not found\");\n\t}\n}\n\nvoid Delaunay::add_point(size_t index,stack<std::pair<size_t, size_t> > &flip_stack)\n{\n\t// Check if point is inside big triangle\n\tassert(InTriangle(TripleConstRef<Vector2D>(cor[olength],\n\t\tcor[olength + 1],\n\t\tcor[olength + 2]),\n\t\tcor[index]));\n\tconst size_t triangle = Walk(index);\n\tconst Triplet<int> outer(f[triangle].vertices);\n\tconst Triplet<int> temp_friends(f[triangle].neighbors);\n\tf[triangle].vertices.set(outer.third, outer.first, static_cast<int>(index));\n\tf[triangle].neighbors.set(temp_friends.third,\n\t\tlocation_pointer + 1,\n\t\tlocation_pointer + 2);\n\tf.push_back(facet(TripleConstRef<int>(outer.first,\n\t\touter.second,\n\t\tstatic_cast<int>(index)),\n\t\tTripleConstRef<int>(temp_friends.first,\n\t\t\tlocation_pointer + 2,\n\t\t\tstatic_cast<int>(triangle))));\n\tf.push_back(facet(TripleConstRef<int>(outer.second,\n\t\touter.third,\n\t\tstatic_cast<int>(index)),\n\t\tTripleConstRef<int>(temp_friends.second,\n\t\t\tstatic_cast<int>(triangle),\n\t\t\tlocation_pointer + 1)));\n\t// _update the friends list of the friends\n\tif (temp_friends.second != last_loc)\n\t{\n\t\tconst size_t i = find_index(f[static_cast<size_t>(temp_friends.second)], static_cast<int>(triangle));\n\t\tf[static_cast<size_t>(temp_friends.second)].neighbors[i] = location_pointer + 2;\n\t}\n\tif (temp_friends.first != last_loc)\n\t{\n\t\tconst size_t i = find_index(f[static_cast<size_t>(temp_friends.first)], static_cast<int>(triangle));\n\t\tf[static_cast<size_t>(temp_friends.first)].neighbors[i] = location_pointer + 1;\n\t}\n\t// Calculate radius if needed\n\tif (CalcRadius)\n\t{\n\t\tradius[static_cast<size_t>(triangle)] = CalculateRadius(static_cast<int>(triangle));\n\t\tint n = int(f.size());\n\t\tint m = int(radius.size());\n\t\tif (n > m - 1)\n\t\t{\n\t\t\tradius.push_back(CalculateRadius(location_pointer + 1));\n\t\t\tradius.push_back(CalculateRadius(location_pointer + 2));\n\t\t}\n\t\telse\n\t\t\tif (n > m)\n\t\t\t{\n\t\t\t\tradius[static_cast<size_t>(location_pointer) + 1] = CalculateRadius(location_pointer + 1);\n\t\t\t\tradius.push_back(CalculateRadius(location_pointer + 2));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tradius[static_cast<size_t>(location_pointer) + 1] = CalculateRadius(location_pointer + 1);\n\t\t\t\tradius[static_cast<size_t>(location_pointer) + 2] = CalculateRadius(location_pointer + 2);\n\t\t\t}\n\t}\n\n\t// check if flipping is needed\n\tflip(triangle, static_cast<size_t>(temp_friends.third),flip_stack);\n\tflip(static_cast<size_t>(location_pointer) + 1, static_cast<size_t>(temp_friends.first),flip_stack);\n\tflip(static_cast<size_t>(location_pointer) + 2, static_cast<size_t>(temp_friends.second),flip_stack);\n\n\t// _update number of facets\n\tlocation_pointer += 2;\n}\n\nvoid Delaunay::flip(size_t i, size_t j, stack<std::pair<size_t, size_t> > &flip_stack)\n{\n\tif (j == static_cast<size_t>(last_loc))\n\t\treturn;\n\tflip_stack.push(std::pair<size_t, size_t>(i, j));\n\twhile (!flip_stack.empty())\n\t{\n\t\tconst pair<size_t, size_t> indexes = flip_stack.top();\n\t\t// Returns the index to the point to check in coordinates and the index of the point in the facet\n\t\tconst pair<int, int> check = find_diff(f[indexes.second],\n\t\t\tf[indexes.first]);\n\t\tconst pair<int, int> other = find_diff(f[indexes.first],\n\t\t\tf[indexes.second]);\n\n\t\tfacet& prefetch_1 = f[indexes.first];\n\t\tif (incircle(cor[static_cast<size_t>(prefetch_1.vertices.first)],\n\t\t\tcor[static_cast<size_t>(prefetch_1.vertices.second)],\n\t\t\tcor[static_cast<size_t>(prefetch_1.vertices.third)],\n\t\t\tcor[static_cast<size_t>(check.first)]) > 0)\n\t\t{\n\t\t\t//The point is in a circle change the facets and their friends\n\t\t\tconst int v1 = prefetch_1.vertices[static_cast<size_t>(other.second + 1) % 3];\n\t\t\tconst int f1 = prefetch_1.neighbors[static_cast<size_t>(other.second)];\n\t\t\tconst int f12 = prefetch_1.neighbors[static_cast<size_t>(other.second + 2) % 3];\n\t\t\tfacet& prefetch_2 = f[indexes.second];\n\t\t\tconst int v2 = prefetch_2.vertices[static_cast<size_t>(check.second + 1) % 3];\n\t\t\tconst int f2 = prefetch_2.neighbors[static_cast<size_t>(check.second + 2) % 3];\n\t\t\tconst int f22 = prefetch_2.neighbors[static_cast<size_t>(check.second)];\n\t\t\tprefetch_1.vertices.set(other.first, v1, check.first);\n\t\t\tprefetch_2.vertices.set(check.first, v2, other.first);\n\t\t\tprefetch_1.neighbors.set(f1, f2, static_cast<int>(indexes.second));\n\t\t\tprefetch_2.neighbors.set(f22, f12, static_cast<int>(indexes.first));\n\t\t\t// change the friends of the friends if needed\n\t\t\tif (f2 != last_loc)\n\t\t\t{\n\t\t\t\tf[static_cast<size_t>(f2)].neighbors[static_cast<size_t>(find_index(f[static_cast<size_t>(f2)], static_cast<int>(indexes.second)))] = static_cast<int>(indexes.first);\n\t\t\t}\n\t\t\tif (f12 != last_loc)\n\t\t\t{\n\t\t\t\tf[static_cast<size_t>(f12)].neighbors[static_cast<size_t>(find_index(f[static_cast<size_t>(f12)], static_cast<int>(indexes.first)))] = static_cast<int>(indexes.second);\n\t\t\t}\n\t\t\t// Calculate the new radius if needed\n\t\t\tif (CalcRadius)\n\t\t\t{\n\t\t\t\tradius[indexes.first] = CalculateRadius(static_cast<int>(indexes.first));\n\t\t\t\tradius[indexes.second] = CalculateRadius(static_cast<int>(indexes.second));\n\t\t\t}\n\t\t\t// clear the checked facets\n\t\t\tflip_stack.pop();\n\t\t\t// push into the stack the new facets to check\n\t\t\tif (prefetch_2.neighbors.first != last_loc)\n\t\t\t\tflip_stack.push(std::pair<size_t, size_t>(indexes.second,\n\t\t\t\t\tstatic_cast<size_t>(prefetch_2.neighbors.first)));\n\t\t\tif (prefetch_1.neighbors.second != last_loc)\n\t\t\t\tflip_stack.push(std::pair<size_t, size_t>(indexes.first,\n\t\t\t\t\tstatic_cast<size_t>(prefetch_1.neighbors.second)));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// clear the checked facets\n\t\t\tflip_stack.pop();\n\t\t}\n\t}\n}\n\nvoid Delaunay::build_delaunay(vector<Vector2D>const& vp, vector<Vector2D> const& cpoints)\n{\n\tcell_points = cpoints;\n\tDataOnlyForBuild data;\n\tlastFacet = 0;\n\tCalcRadius = false;\n\tlength = int(vp.size() + 3);\n\tint len = length - 3;\n\tolength = static_cast<size_t>(len);\n\tf.clear();\n\tcor.clear();\n\tf.reserve(static_cast<size_t>(2 * length + 1 + static_cast<int>(17 * sqrt(1.*length))));\n\tcor.reserve(static_cast<size_t>(length + 9 * static_cast<int>(sqrt(1.*length))));\n\tlast_loc = INT_MAX;\n\tfor (int i = 0; i < len; i++)\n\t{\n\t\tcor.push_back(vp[static_cast<size_t>(i)]);\n\t}\n\t// Check point input\n\tCheckInput();\n\n\t// add the 3 extreme points\n\tVector2D p_temp;\n\tvector<double> cellsize = CellSize(cell_points);\n\tdouble width = cellsize[1] - cellsize[0];\n\tdouble height = cellsize[3] - cellsize[2];\n\twidth = max(width, height);\n\theight = max(width, height);\n\tp_temp.x = cellsize[0] - 100 * width;\n\tp_temp.y = cellsize[2] - 100 * height;\n\tcor.push_back(p_temp);\n\tp_temp.x = cellsize[1] + 100 * width;\n\tp_temp.y = cellsize[2] - 100 * height;\n\tcor.push_back(p_temp);\n\tp_temp.x = (cellsize[0] + cellsize[1]) / 2.0;\n\tp_temp.y = cellsize[3] + 100 * height;\n\tcor.push_back(p_temp);\n\t// Create the big triangle, and assign friends\n\tfacet f_temp;\n\tf.push_back(f_temp);\n\tf[0].vertices[0] = len;\n\tf[0].vertices[1] = len + 1;\n\tf[0].vertices[2] = len + 2;\n\tfor (size_t i = 0; i < 3; i++)\n\t\tf[0].neighbors[i] = last_loc;\n\tlocation_pointer = 0;\n\t// add the points\n\tsize_t nloop = static_cast<size_t>(length) - 3;\n\tstack<std::pair<size_t, size_t> > flip_stack;\n\tfor (size_t i = 0; i < nloop; i++)\n\t\tadd_point(i,flip_stack);\n\t// Calculate radius\n\tradius.resize(f.size());\n\tint n = int(f.size());\n\tfor (int i = 0; i < n; ++i)\n\t\tradius[static_cast<size_t>(i)] = CalculateRadius(i);\n\tCalcRadius = true;\n}\n\ndouble Delaunay::triangle_area(int index)\n{\n\tconst TripleConstRef<Vector2D> p\n\t\t(cor[static_cast<size_t>(f[static_cast<size_t>(index)].vertices.first)],\n\t\t\tcor[static_cast<size_t>(f[static_cast<size_t>(index)].vertices.second)],\n\t\t\tcor[static_cast<size_t>(f[static_cast<size_t>(index)].vertices.third)]);\n\tconst double x1 = p.third.x - p.first.x;\n\tconst double x2 = p.second.x - p.first.x;\n\tconst double y1 = p.third.y - p.first.y;\n\tconst double y2 = p.second.y - p.first.y;\n\treturn -0.5*(x1*y2 - x2*y1);\n}\n\nvoid Delaunay::update(const vector<Vector2D>& points, vector<Vector2D>\n\tconst& cpoints)\n{\n\tif (logger)\n\t\tlogger->output(cor, f);\n\tbuild_delaunay(points, cpoints);\n}\n\nnamespace {\n\n\tint Triplet<int>::* walk_condition(const vector<Vector2D>& cor,\n\t\tconst Triplet<int>& vertices,\n\t\tsize_t point)\n\t{\n\t\tif (orient2d(TripleConstRef<Vector2D>\n\t\t\t(cor[static_cast<size_t>(vertices.first)],\n\t\t\t\tcor[static_cast<size_t>(vertices.second)],\n\t\t\t\tcor[point])) < 0)\n\t\t\treturn &Triplet<int>::first;\n\t\telse if (orient2d(TripleConstRef<Vector2D>\n\t\t\t(cor[static_cast<size_t>(vertices.second)],\n\t\t\t\tcor[static_cast<size_t>(vertices.third)],\n\t\t\t\tcor[point])) < 0)\n\t\t\treturn &Triplet<int>::second;\n\t\telse if (orient2d(TripleConstRef<Vector2D>\n\t\t\t(cor[static_cast<size_t>(vertices.third)],\n\t\t\t\tcor[static_cast<size_t>(vertices.first)],\n\t\t\t\tcor[point])) < 0)\n\t\t\treturn &Triplet<int>::third;\n\t\telse\n\t\t\treturn 0;\n\t}\n\n\tclass WalkBookkeeper\n\t{\n\tpublic:\n\n\tprivate:\n\n\t};\n\n\tsize_t find_new_facet(const vector<Vector2D>& cor,\n\t\tconst vector<facet>& f,\n\t\tsize_t point,\n\t\tsize_t last_facet)\n\t{\n\t\tsize_t res = last_facet;\n\t\tint Triplet<int>::* next = walk_condition(cor,\n\t\t\tf[res].vertices,\n\t\t\tpoint);\n\t\twhile (next) {\n\t\t\tres = static_cast<size_t>(f[res].neighbors.*next);\n\t\t\tnext = walk_condition(cor,\n\t\t\t\tf[res].vertices,\n\t\t\t\tpoint);\n\t\t}\n\t\treturn res;\n\t}\n}\n\nsize_t Delaunay::Walk(size_t point)\n{\n\tlastFacet = static_cast<int>(find_new_facet(cor, f, point, static_cast<size_t>(lastFacet)));\n\treturn static_cast<size_t>(lastFacet);\n}\n\nvector<int> Delaunay::FindContainingTetras(int StartTetra, int point)\n{\n\tvector<int> res;\n\tFindContainingTetras(StartTetra, point, res);\n\treturn res;\n}\n\ndouble Delaunay::FindMaxRadius(int point)\n{\n\tconst vector<int> vec = FindContainingTetras(static_cast<int>(Walk(static_cast<size_t>(point))), point);\n\tdouble r = 0;\n\tfor (size_t i = 0; i < vec.size(); ++i)\n\t\tr = max(r, radius[static_cast<size_t>(vec[static_cast<size_t>(i)])]);\n\treturn 2 * r;\n}\n\nvoid Delaunay::FindContainingTetras(int StartFacet, int point, vector<int> &result)\n{\n\tresult.clear();\n\tint PointLocation = FindPointInFacet(StartFacet, point);\n\tint NextFacet = f[static_cast<size_t>(StartFacet)].neighbors[static_cast<size_t>(PointLocation)];\n\tresult.reserve(12);\n\tresult.push_back(NextFacet);\n\twhile (NextFacet != StartFacet)\n\t{\n\t\tPointLocation = FindPointInFacet(NextFacet, point);\n\t\tNextFacet = f[static_cast<size_t>(NextFacet)].neighbors[static_cast<size_t>(PointLocation)];\n\t\tresult.push_back(NextFacet);\n\t}\n}\n\nint Delaunay::FindPointInFacet(int facet, int point)\n{\n\tfor (int i = 0; i < 3; ++i)\n\t\tif (f[static_cast<size_t>(facet)].vertices[static_cast<size_t>(i)] == point)\n\t\t\treturn i;\n\tUniversalError eo(\"Error in Delaunay, FindPointInFacet\");\n\teo.AddEntry(\"Facet number\", facet);\n\teo.AddEntry(\"Point number\", point);\n\tthrow eo;\n}\n\nbool Delaunay::IsOuterFacet(int facet)const\n{\n\t//int PointNum=length-1;\n\tfor (int i = 0; i<3; ++i)\n\t\tfor (size_t j = 0; j < 3; ++j)\n\t\t\tif (f[static_cast<size_t>(facet)].vertices[static_cast<size_t>(i)] == static_cast<int>(olength + j))\n\t\t\t\treturn true;\n\treturn false;\n}\n\ndouble Delaunay::CalculateRadius(int facet)\n{\n\tconst double big = 1e10;\n\tconst double a = cor[static_cast<size_t>(f[static_cast<size_t>(facet)].vertices[0])].distance(cor[static_cast<size_t>(f[static_cast<size_t>(facet)].vertices[1])]);\n\tconst double b = cor[static_cast<size_t>(f[static_cast<size_t>(facet)].vertices[0])].distance(cor[static_cast<size_t>(f[static_cast<size_t>(facet)].vertices[2])]);\n\tconst double c = cor[static_cast<size_t>(f[static_cast<size_t>(facet)].vertices[2])].distance(cor[static_cast<size_t>(f[static_cast<size_t>(facet)].vertices[1])]);\n\tconst double temp1 = b + c - a;\n\tif (temp1 <= 0)\n\t{\n\t\tif (a > big*b || a>big*c) // Do we have a small edge?\n\t\t\treturn 0.5*a;\n\t\telse\n\t\t\treturn 0.5*(b + c); // we have 3 points on a line\n\t}\n\tconst double temp2 = c + a - b;\n\tif (temp2 <= 0)\n\t{\n\t\tif (b > big*a || b > big*c) // Do we have a small edge?\n\t\t\treturn 0.5*b;\n\t\telse\n\t\t\treturn 0.5*(a + c); // we have 3 points on a line\n\t}\n\tconst double temp3 = b - c + a;\n\tif (temp3 <= 0)\n\t{\n\t\tif (c > big*b || c > big*a) // Do we have a small edge?\n\t\t\treturn 0.5*c;\n\t\telse\n\t\t\treturn 0.5*(b + a); // we have 3 points on a line\n\t}\n\treturn a*b*c / sqrt((a + b + c)*temp1*temp2*temp3);\n}\n\nvoid Delaunay::CheckInput()\n{\n\tfor (size_t i = 0; i < cor.size(); ++i)\n\t\tassert(InCell(cell_points, cor[i]));\n}\n\nint Delaunay::GetOriginalIndex(int NewPoint) const\n{\n\treturn NewPoint;\n}\n\ndouble Delaunay::GetFacetRadius(int facet) const\n{\n\treturn radius[static_cast<size_t>(facet)];\n}\n\nvoid Delaunay::ChangeOlength(int n)\n{\n\tolength = static_cast<size_t>(n);\n}\n\nvoid Delaunay::Changelength(int n)\n{\n\tlength = n + 3;\n}\n\nvector<Vector2D>& Delaunay::ChangeCor(void)\n{\n\treturn cor;\n}\n\nconst vector<Vector2D>& Delaunay::getCor(void) const\n{\n\treturn cor;\n}\n\nconst facet& Delaunay::get_facet(int index) const\n{\n\treturn f[static_cast<size_t>(index)];\n}\n\ndouble Delaunay::get_facet_coordinate(int Facet, int vertice, int dim)\n{\n\tif (dim == 0)\n\t\treturn cor[static_cast<size_t>(f[static_cast<size_t>(Facet)].vertices[static_cast<size_t>(vertice)])].x;\n\telse\n\t\treturn cor[static_cast<size_t>(f[static_cast<size_t>(Facet)].vertices[static_cast<size_t>(vertice)])].y;\n}\n\nVector2D Delaunay::get_point(size_t index) const\n{\n\treturn cor[index];\n}\n\ndouble Delaunay::get_cor(int index, int dim) const\n{\n\tif (dim == 0)\n\t\treturn cor[static_cast<size_t>(index)].x;\n\telse if (dim == 1)\n\t\treturn cor[static_cast<size_t>(index)].y;\n\telse\n\t\tthrow UniversalError(\"Error in Delaunay::get_cor. Invalid index\");\n}\n\nint Delaunay::get_num_facet(void) const\n{\n\treturn static_cast<int>(f.size());\n}\n\nint Delaunay::get_length(void) const\n{\n\treturn length - 3;\n}\n\nint Delaunay::get_last_loc(void) const\n{\n\treturn last_loc;\n}\n\nvoid Delaunay::set_point(int index, Vector2D p)\n{\n\tcor[static_cast<size_t>(index)] = p;\n}\n\nint Delaunay::GetOriginalLength(void) const\n{\n\treturn static_cast<int>(olength);\n}\n\nvector<Vector2D>& Delaunay::GetMeshPoints(void)\n{\n\treturn cor;\n}\n\nint Delaunay::GetTotalLength(void)\n{\n\treturn static_cast<int>(cor.size());\n}\n\nvoid Delaunay::AddBoundaryPoints(vector<Vector2D> const& points)\n{\n\tint n = static_cast<int>(points.size());\n\tstack<std::pair<size_t, size_t> > flip_stack;\n\t//\tvector<int> order=HilbertOrder(points,n);\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tcor.push_back(points[static_cast<size_t>(i)]);\n\t\tadd_point(cor.size() - 1,flip_stack);\n\t}\n}\n\nvoid Delaunay::AddAditionalPoint(Vector2D const& vec)\n{\n\tcor.push_back(vec);\n}\n\nint Delaunay::GetCorSize(void)const\n{\n\treturn static_cast<int>(cor.size());\n}\n\nbool Delaunay::IsTripleOut(int index) const\n{\n\tint counter = 0;\n\tfor (size_t i = 0; i < 3; ++i)\n\t\tif (IsOuterFacet(f[static_cast<size_t>(index)].neighbors[static_cast<size_t>(i)]))\n\t\t\t++counter;\n\tif (counter > 1)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nint Delaunay::FindTripleLoc(facet const& fct)const\n{\n\tfor (size_t i = 0; i < 3; ++i)\n\t\tif (!IsOuterFacet(fct.neighbors[static_cast<size_t>(i)]))\n\t\t\treturn static_cast<int>((i + 1) % 3);\n\tthrow UniversalError(\"Trouble in constructing boundary triangles. No inner neighbor\");\n}\n\nnamespace\n{\n\tbool IsOuterQuick(facet const& f, int olength)\n\t{\n\t\tfor (size_t i = 0; i < 3; ++i)\n\t\t\tif (f.vertices[static_cast<size_t>(i)] >= olength)\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\tbool IsEdgeFacet(vector<facet> const& facets, facet const& f, int olength)\n\t{\n\t\tint counter = 0;\n\t\tfor (size_t i = 0; i < 3; ++i)\n\t\t{\n\t\t\tif (f.vertices[static_cast<size_t>(i)] >= olength)\n\t\t\t\treturn false;\n\t\t\tif (IsOuterQuick(facets[static_cast<size_t>(f.neighbors[static_cast<size_t>(i)])], olength))\n\t\t\t\t++counter;\n\t\t}\n\t\tif (counter > 0)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\tbool CircleSegmentIntersect(Edge const& edge, Vector2D const& center, double R)\n\t{\n\t\tVector2D AC = center - edge.vertices.first;\n\t\tVector2D AB = edge.vertices.second - edge.vertices.first;\n\t\tdouble d = ScalarProd(AC, AB);\n\t\tif (d<0)\n\t\t{\n\t\t\tif (abs(AC)>R)\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\treturn true;\n\t\t}\n\t\tdouble LAB = abs(AB);\n\t\tif (d > LAB*LAB)\n\t\t{\n\t\t\tif (abs(center - edge.vertices.second) > R)\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\treturn true;\n\t\t}\n\t\tVector2D closest = edge.vertices.first + AB*d / (LAB*LAB);\n\t\tif (abs(center - closest) > R)\n\t\t\treturn false;\n\t\telse\n\t\t\treturn true;\n\t}\n}\n\nvector<int> Delaunay::GetOuterFacets(int start_facet, int real_point, int olength2)\n{\n\tint cur_facet = start_facet;\n\tvector<int> f_temp, containing_facets;\n\tf_temp.reserve(static_cast<size_t>(10 * sqrt(1.0*olength2)));\n\tint point_index = FindPointInFacet(cur_facet, real_point);\n\tif (IsOuterQuick(f[static_cast<size_t>(f[static_cast<size_t>(cur_facet)].neighbors[static_cast<size_t>(point_index)])], olength2))\n\t{\n\t\tpoint_index = (point_index + 1) % 3;\n\t\treal_point = f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(point_index)];\n\t}\n\tif (IsOuterQuick(f[static_cast<size_t>(f[static_cast<size_t>(cur_facet)].neighbors[static_cast<size_t>(point_index)])], olength2))\n\t{\n\t\tpoint_index = (point_index + 1) % 3;\n\t\treal_point = f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(point_index)];\n\t}\n\tdo\n\t{\n\t\tFindContainingTetras(cur_facet, real_point, containing_facets);\n\t\tint old_current = cur_facet;\n\t\tfor (size_t i = 0; i < containing_facets.size(); ++i)\n\t\t{\n\t\t\tif (IsEdgeFacet(f, f[static_cast<size_t>(containing_facets[static_cast<size_t>(i)])], olength2) &&\n\t\t\t\tcontaining_facets[static_cast<size_t>(i)] != old_current)\n\t\t\t\tcur_facet = containing_facets[static_cast<size_t>(i)];\n\t\t\tif (!IsOuterQuick(f[static_cast<size_t>(containing_facets[static_cast<size_t>(i)])], olength2))\n\t\t\t\tf_temp.push_back(containing_facets[static_cast<size_t>(i)]);\n\t\t}\n\t\tpoint_index = (1 + FindPointInFacet(cur_facet, real_point)) % 3;\n\t\tif (IsTripleOut(cur_facet))\n\t\t\tpoint_index = (point_index + 1) % 3;\n\t\treal_point = f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(point_index)];\n\t} while (start_facet != cur_facet);\n\tsort(f_temp.begin(), f_temp.end());\n\tf_temp = unique(f_temp);\n\treturn f_temp;\n}\n\nvector<vector<int> > Delaunay::FindOuterPoints(vector<Edge> const& edges)\n{\n\t// We add the points in a counter clockwise fashion\n\tvector<vector<int> > res(edges.size());\n\tif (olength < 100)\n\t{\n\t\tfor (size_t j = 0; j < edges.size(); ++j)\n\t\t{\n\t\t\tres[static_cast<size_t>(j)].resize(static_cast<size_t>(olength));\n\t\t\tfor (size_t i = 0; i < olength; ++i)\n\t\t\t\tres[static_cast<size_t>(j)][i] = static_cast<int>(i);\n\t\t}\n\t\treturn res;\n\t}\n\tvector<int> res_temp, outer_points, f_temp, f_add(f.size(), 0);\n\tres_temp.reserve(static_cast<size_t>(20 * sqrt(1.0*static_cast<double>(olength))));\n\tf_temp.reserve(static_cast<size_t>(10 * sqrt(1.0*static_cast<double>(olength))));\n\touter_points.reserve(static_cast<size_t>(10 * sqrt(1.0*static_cast<double>(olength))));\n\t// Walk to an outer point\n\tint cur_facet = static_cast<int>(Walk(olength));\n\tvector<vector<int> > toduplicate(edges.size());\n\tvector<bool> checked(f.size(), false);\n\tAddOuterFacets(cur_facet, toduplicate, edges, checked);\n\tfor (size_t i = 0; i < edges.size(); ++i)\n\t{\n\t\tsort(toduplicate[static_cast<size_t>(i)].begin(), toduplicate[static_cast<size_t>(i)].end());\n\t\ttoduplicate[static_cast<size_t>(i)] = unique(toduplicate[static_cast<size_t>(i)]);\n\t}\n\treturn toduplicate;\n}\n\nvoid Delaunay::AddRigid(vector<Edge> const& edges,\n\tvector<vector<int> > &toduplicate)\n{\n\tvector<int> toremove;\n\tfor (size_t i = 0; i < edges.size(); ++i)\n\t{\n\t\ttoremove.clear();\n\t\tif (toduplicate[i].empty())\n\t\t\tcontinue;\n\t\tvector<Vector2D> toadd;\n\t\ttoadd.reserve(toduplicate[i].size());\n\t\tVector2D par(Parallel(edges[i]));\n\t\tpar = par / abs(par);\n\t\tfor (size_t j = 0; j < toduplicate[i].size(); ++j)\n\t\t{\n\t\t\tVector2D temp = cor[static_cast<size_t>(toduplicate[i][j])] - edges[i].vertices.first;\n\t\t\ttemp = 2 * par*ScalarProd(par, temp) - temp + edges[i].vertices.first;\n\t\t\tif (InTriangle(TripleConstRef<Vector2D>\n\t\t\t\t(cor[static_cast<size_t>(olength)],\n\t\t\t\t\tcor[static_cast<size_t>(olength + 1)],\n\t\t\t\t\tcor[static_cast<size_t>(olength + 2)]),\n\t\t\t\ttemp))\n\t\t\t\ttoadd.push_back(temp);\n\t\t\telse\n\t\t\t\ttoremove.push_back(static_cast<int>(j));\n\t\t}\n\t\tRemoveVector(toduplicate[i], toremove);\n\t\tvector<int> order = HilbertOrder(toadd, static_cast<int>(toadd.size()));\n\t\tReArrangeVector(toadd, order);\n\t\ttry\n\t\t{\n\t\t\tAddBoundaryPoints(toadd);\n\t\t}\n\t\tcatch (UniversalError &eo)\n\t\t{\n\t\t\teo.AddEntry(\"Error in AddRigid\", 0);\n\t\t\tthrow;\n\t\t}\n\t\tReArrangeVector(toduplicate[i], order);\n\t}\n}\n\nnamespace\n{\n\tvector<Edge> GetCornerEdges(OuterBoundary const* obc)\n\t{\n\t\tconst double dx = obc->GetGridBoundary(Right) - obc->GetGridBoundary(Left);\n\t\tconst double dy = obc->GetGridBoundary(Up) - obc->GetGridBoundary(Down);\n\t\tvector<Edge> res;\n\t\tconst Vector2D RU(obc->GetGridBoundary(Right), obc->GetGridBoundary(Up));\n\t\tconst Vector2D LU(obc->GetGridBoundary(Left), obc->GetGridBoundary(Up));\n\t\tconst Vector2D LD(obc->GetGridBoundary(Left), obc->GetGridBoundary(Down));\n\t\tconst Vector2D RD(obc->GetGridBoundary(Right), obc->GetGridBoundary(Down));\n\t\tres.push_back(Edge(RU, Vector2D(dx, 0) + RU, 0, 0));\n\t\tres.push_back(Edge(RU, Vector2D(0, dy) + RU, 0, 0));\n\t\tres.push_back(Edge(LU, Vector2D(0, dy) + LU, 0, 0));\n\t\tres.push_back(Edge(LU, Vector2D(-dx, 0) + LU, 0, 0));\n\t\tres.push_back(Edge(LD, Vector2D(-dx, 0) + LD, 0, 0));\n\t\tres.push_back(Edge(LD, Vector2D(0, -dy) + LD, 0, 0));\n\t\tres.push_back(Edge(RD, Vector2D(0, -dy) + RD, 0, 0));\n\t\tres.push_back(Edge(RD, Vector2D(dx, 0) + RD, 0, 0));\n\t\treturn res;\n\t}\n}\n\nvector<vector<int> > Delaunay::AddPeriodic(OuterBoundary const* obc, vector<Edge> const& edges,\n\tvector<vector<int> > &toduplicate)\n{\n\tconst double dx = obc->GetGridBoundary(Right) - obc->GetGridBoundary(Left);\n\tconst double dy = obc->GetGridBoundary(Up) - obc->GetGridBoundary(Down);\n\tfor (size_t i = 0; i < edges.size(); ++i)\n\t{\n\t\tif (toduplicate[static_cast<size_t>(i)].empty())\n\t\t\tcontinue;\n\t\tVector2D change;\n\t\tswitch (i)\n\t\t{\n\t\tcase(0) :\n\t\t\tchange.x = -dx;\n\t\t\tbreak;\n\t\tcase(1) :\n\t\t\tchange.y = -dy;\n\t\t\tbreak;\n\t\tcase(2) :\n\t\t\tchange.x = dx;\n\t\t\tbreak;\n\t\tcase(3) :\n\t\t\tchange.y = dy;\n\t\t\tbreak;\n\t\t}\n\t\tvector<Vector2D> toadd;\n\t\ttoadd.reserve(toduplicate[static_cast<size_t>(i)].size());\n\t\t//vector<int> pointstemp(toduplicate[static_cast<size_t>(i)].size());\n\t\tfor (size_t j = 0; j < toduplicate[static_cast<size_t>(i)].size(); ++j)\n\t\t{\n\t\t\ttoadd.push_back(cor[static_cast<size_t>(toduplicate[static_cast<size_t>(i)][static_cast<size_t>(j)])] + change);\n\t\t\t//\tpointstemp[j]=j;\n\t\t}\n\t\tvector<int> order = HilbertOrder(toadd, static_cast<int>(toadd.size()));\n\t\tReArrangeVector(toadd, order);\n\t\tAddBoundaryPoints(toadd);\n\t\tReArrangeVector(toduplicate[static_cast<size_t>(i)], order);\n\t\t//toduplicate[i]=pointstemp;\n\t}\n\t// Done with sides do corners now\n\tvector<Edge> corneredges = GetCornerEdges(obc);\n\tvector<vector<int> > corners(toduplicate.size());\n\tfor (size_t i = 0; i < toduplicate.size(); ++i)\n\t{\n\t\tfor (size_t j = 0; j < toduplicate[static_cast<size_t>(i)].size(); ++j)\n\t\t{\n\t\t\tconst int facet_loc = static_cast<int>(Walk(static_cast<size_t>(toduplicate[static_cast<size_t>(i)][static_cast<size_t>(j)])));\n\t\t\tconst Vector2D center = cor[static_cast<size_t>(toduplicate[static_cast<size_t>(i)][static_cast<size_t>(j)])];\n\t\t\tconst double R = 2 * GetMaxRadius(toduplicate[static_cast<size_t>(i)][static_cast<size_t>(j)], facet_loc);\n\t\t\tif (CircleSegmentIntersect(corneredges[2 * static_cast<size_t>(i)], center, R))\n\t\t\t\tcorners[static_cast<size_t>(i)].push_back(toduplicate[static_cast<size_t>(i)][static_cast<size_t>(j)]);\n\t\t\tif (CircleSegmentIntersect(corneredges[(2 * static_cast<size_t>(i) + 7) % 8], center, R))\n\t\t\t\tcorners[(static_cast<size_t>(i) + 3) % 4].push_back(toduplicate[static_cast<size_t>(i)][static_cast<size_t>(j)]);\n\t\t}\n\t}\n\tfor (size_t i = 0; i < corners.size(); ++i)\n\t{\n\t\tif (corners[static_cast<size_t>(i)].empty())\n\t\t\tcontinue;\n\t\tsort(corners[static_cast<size_t>(i)].begin(), corners[static_cast<size_t>(i)].end());\n\t\tcorners[static_cast<size_t>(i)] = unique(corners[static_cast<size_t>(i)]);\n\t\tVector2D change;\n\t\tswitch (i)\n\t\t{\n\t\tcase(0) :\n\t\t\tchange.x = -dx;\n\t\t\tchange.y = -dy;\n\t\t\tbreak;\n\t\tcase(1) :\n\t\t\tchange.y = -dy;\n\t\t\tchange.x = dx;\n\t\t\tbreak;\n\t\tcase(2) :\n\t\t\tchange.x = dx;\n\t\t\tchange.y = dy;\n\t\t\tbreak;\n\t\tcase(3) :\n\t\t\tchange.y = dy;\n\t\t\tchange.x = -dx;\n\t\t\tbreak;\n\t\t}\n\t\tvector<Vector2D> toadd;\n\t\ttoadd.reserve(corners[static_cast<size_t>(i)].size());\n\t\t//\t\tvector<int> pointstemp(corners[i].size());\n\t\tfor (size_t j = 0; j < corners[static_cast<size_t>(i)].size(); ++j)\n\t\t{\n\t\t\ttoadd.push_back(cor[static_cast<size_t>(corners[static_cast<size_t>(i)][static_cast<size_t>(j)])] + change);\n\t\t\t//\t\tpointstemp[j]=j;\n\t\t}\n\t\tvector<int> order = HilbertOrder(toadd, static_cast<int>(toadd.size()));\n\t\tReArrangeVector(toadd, order);\n\t\tAddBoundaryPoints(toadd);\n\t\tReArrangeVector(corners[static_cast<size_t>(i)], order);\n\t\t//\tcorners[i]=pointstemp;\n\t}\n\treturn corners;\n}\n\nvoid Delaunay::AddHalfPeriodic(OuterBoundary const* obc, vector<Edge> const& edges,\n\tvector<vector<int> > &toduplicate)\n{\n\tconst double dx = obc->GetGridBoundary(Right) - obc->GetGridBoundary(Left);\n\t//\tconst double dy=obc->GetGridBoundary(Up)-obc->GetGridBoundary(Down);\n\tfor (size_t i = 0; i < edges.size(); ++i)\n\t{\n\t\tif (toduplicate[static_cast<size_t>(i)].empty())\n\t\t\tcontinue;\n\t\tVector2D change;\n\t\tswitch (i)\n\t\t{\n\t\tcase(0) :\n\t\t\tchange.x = -dx;\n\t\t\tbreak;\n\t\tcase(1) :\n\t\t\tbreak;\n\t\tcase(2) :\n\t\t\tchange.x = dx;\n\t\t\tbreak;\n\t\tcase(3) :\n\t\t\tbreak;\n\t\t}\n\t\tvector<Vector2D> toadd;\n\t\ttoadd.reserve(toduplicate[static_cast<size_t>(i)].size());\n\t\t//vector<int> pointstemp(toduplicate[static_cast<size_t>(i)].size());\n\t\tVector2D par(Parallel(edges[static_cast<size_t>(i)]));\n\t\tpar = par / abs(par);\n\t\tfor (size_t j = 0; j < toduplicate[static_cast<size_t>(i)].size(); ++j)\n\t\t{\n\t\t\tVector2D temp = cor[static_cast<size_t>(toduplicate[static_cast<size_t>(i)][static_cast<size_t>(j)])];\n\t\t\tif (i % 2 == 1)\n\t\t\t{\n\t\t\t\ttemp -= edges[static_cast<size_t>(i)].vertices.first;\n\t\t\t\ttemp = 2 * par*ScalarProd(par, temp) - temp + edges[static_cast<size_t>(i)].vertices.first;\n\t\t\t}\n\t\t\ttoadd.push_back(temp + change);\n\t\t\t//pointstemp[j]=j;\n\t\t}\n\t\tvector<int> order = HilbertOrder(toadd, static_cast<int>(toadd.size()));\n\t\tReArrangeVector(toadd, order);\n\t\tAddBoundaryPoints(toadd);\n\t\tReArrangeVector(toduplicate[static_cast<size_t>(i)], order);\n\t\t//toduplicate[i]=pointstemp;\n\t}\n}\n\nvector<vector<int> > Delaunay::BuildBoundary(OuterBoundary const* obc, vector<Edge> const& edges)\n{\n\tvector<vector<int> > toduplicate = FindOuterPoints(edges);\n#ifdef RICH_MPI\n\tOrgIndex.clear();\n#endif\n\tif (obc->GetBoundaryType() == Rectengular)\n\t{\n\t\tAddRigid(edges, toduplicate);\n#ifdef RICH_MPI\n\t\tfor (size_t i = 0; i < toduplicate.size(); ++i)\n\t\t\tfor (size_t j = 0; j < toduplicate[i].size(); ++j)\n\t\t\t\tOrgIndex.push_back(toduplicate[i][j]);\n#endif\n\t}\n\telse\n\t{\n\t\tif (obc->GetBoundaryType() == Periodic)\n\t\t{\n\t\t\tvector<vector<int> > corners = AddPeriodic(obc, edges, toduplicate);\n\t\t\tfor (size_t i = 0; i < 4; ++i)\n\t\t\t\ttoduplicate.push_back(corners[static_cast<size_t>(i)]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tAddHalfPeriodic(obc, edges, toduplicate);\n\t\t}\n\t}\n\treturn toduplicate;\n}\n\nVector2D Delaunay::GetCircleCenter(int index)const\n{\n\tVector2D center;\n\tfacet const& F = f[static_cast<size_t>(index)];\n\tdouble x1 = cor[static_cast<size_t>(F.vertices[0])].x;\n\tdouble x2 = cor[static_cast<size_t>(F.vertices[1])].x;\n\tdouble x3 = cor[static_cast<size_t>(F.vertices[2])].x;\n\tdouble y1 = cor[static_cast<size_t>(F.vertices[0])].y;\n\tdouble y2 = cor[static_cast<size_t>(F.vertices[1])].y;\n\tdouble y3 = cor[static_cast<size_t>(F.vertices[2])].y;\n\t// Do we have a case where two point are very close compared to the third?\n\tdouble d12 = (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);\n\tdouble d23 = (x3 - x2)*(x3 - x2) + (y3 - y2)*(y3 - y2);\n\tdouble d13 = (x1 - x3)*(x1 - x3) + (y1 - y3)*(y1 - y3);\n\tint scenario = 0;\n\tif (d12 < 0.1*(d23 + d13))\n\t\tscenario = 1;\n\telse\n\t\tif (d23 < 0.1*(d13 + d12))\n\t\t\tscenario = 3;\n\t\telse\n\t\t\tif (d13 < 0.1*(d23 + d12))\n\t\t\t\tscenario = 2;\n\tswitch (scenario)\n\t{\n\tcase(0) :\n\tcase(1) :\n\tcase(2) :\n\t{\n\t\tx2 -= x1;\n\t\tx3 -= x1;\n\t\ty2 -= y1;\n\t\ty3 -= y1;\n\t\tdouble d_inv = 1 / (2 * (x2*y3 - y2*x3));\n\t\tcenter.Set((y3*(x2*x2 + y2*y2) - y2*(x3*x3 + y3*y3))*d_inv + x1,\n\t\t\t(-x3*(x2*x2 + y2*y2) + x2*(x3*x3 + y3*y3))*d_inv + y1);\n\t\tbreak;\n\t}\n\tcase(3) :\n\t{\n\t\tx1 -= x2;\n\t\tx3 -= x2;\n\t\ty1 -= y2;\n\t\ty3 -= y2;\n\t\tdouble d_inv = 1 / (2 * (x3*y1 - y3*x1));\n\t\tcenter.Set((y1*(x3*x3 + y3*y3) - y3*(x1*x1 + y1*y1))*d_inv + x2,\n\t\t\t(x3*(x1*x1 + y1*y1) - x1*(x3*x3 + y3*y3))*d_inv + y2);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tthrow UniversalError(\"Unhandled case in switch statement VoronoiMesh::get_center\");\n\t}\n\treturn center;\n}\n\ndouble Delaunay::GetMaxRadius(int point, int startfacet)\n{\n\tdouble res = 0;\n\tvector<int> neigh = FindContainingTetras(startfacet, point);\n\tfor (size_t i = 0; i < neigh.size(); ++i)\n\t\tres = max(res, radius[static_cast<size_t>(neigh[static_cast<size_t>(i)])]);\n\treturn res;\n}\n\nvoid Delaunay::AddOuterFacets(int tri, vector<vector<int> > &toduplicate,\n\tvector<Edge> const& edges, vector<bool> &checked)\n{\n\tstack<int> tocheck;\n\ttocheck.push(tri);\n\twhile (!tocheck.empty())\n\t{\n\t\tint cur_facet = tocheck.top();\n\t\ttocheck.pop();\n\t\tfor (size_t i = 0; i < 3; ++i)\n\t\t{\n\t\t\tbool added = false;\n\t\t\tif (checked[static_cast<size_t>(f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(i)])] || (f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(i)] >= static_cast<int>(olength)))\n\t\t\t\tcontinue;\n\t\t\tvector<int> neigh = FindContainingTetras(cur_facet, f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(i)]);\n\t\t\tfor (size_t k = 0; k < neigh.size(); ++k)\n\t\t\t{\n\t\t\t\tVector2D center = GetCircleCenter(neigh[static_cast<size_t>(k)]);\n\t\t\t\tfor (size_t l = 0; l < edges.size(); ++l)\n\t\t\t\t{\n\t\t\t\t\tif (CircleSegmentIntersect(edges[static_cast<size_t>(l)], center, radius[static_cast<size_t>(neigh[static_cast<size_t>(k)])]))\n\t\t\t\t\t{\n\t\t\t\t\t\ttoduplicate[static_cast<size_t>(l)].push_back(f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(i)]);\n\t\t\t\t\t\tadded = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tchecked[static_cast<size_t>(f[static_cast<size_t>(cur_facet)].vertices[static_cast<size_t>(i)])] = true;\n\t\t\tif (added)\n\t\t\t{\n\t\t\t\tfor (size_t j = 0; j < neigh.size(); ++j)\n\t\t\t\t\ttocheck.push(neigh[static_cast<size_t>(j)]);\n\t\t\t}\n\t\t}\n\t}\n}\n\n#ifdef RICH_MPI\nint Delaunay::findSomeOuterPoint(void)\n{\n\tconst size_t cur_facet = Walk(olength);\n\tfor (size_t i = 0; i < 3; ++i) {\n\t\tconst int candidate = f.at(cur_facet).vertices[i];\n\t\tif (candidate < static_cast<int>(olength))\n\t\t\treturn candidate;\n\t}\n\tassert(false && \"something went wrong\");\n}\n\nnamespace \n{\n\tvector<int>\n\t\tcalc_neighbors_own_edges\n\t\t(const Tessellation& t_proc,\n\t\t\tconst vector<Edge>& edge_list)\n\t{\n\t\tvector<int> res;\n\t\tint rank;\n\t\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\t\tBOOST_FOREACH(const Edge& edge, edge_list) \n\t\t{\n\t\t\tconst int other = (edge.neighbors.first + edge.neighbors.second) -\trank;\n\t\t\tif (other < t_proc.GetPointNo()) {\n\t\t\t\tres.push_back(other);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n\tstack<int> initialise_tocheck\n\t\t(const vector<int>& neightemp)\n\t{\n\t\tstack<int> res;\n\t\tfor (size_t i = 0; i < neightemp.size(); ++i)\n\t\t\tres.push(neightemp[i]);\n\t\treturn res;\n\t}\n\n\tvector<int> calc_self_intersection\n\t\t(const vector<Edge>& edge_list,\n\t\t\tconst Circle& circle)\n\t{\n\t\tvector<int> res;\n\t\tfor (size_t i = 0; i < edge_list.size(); ++i) {\n\t\t\tconst Edge& edge = edge_list.at(i);\n\t\t\tif (edge_circle_intersect(edge, circle))\n\t\t\t\tres.push_back(static_cast<int>(i));\n\t\t}\n\t\treturn res;\n\t}\n}\n\nvector<vector<int> > Delaunay::AddOuterFacetsMPI\n(int point,\n\tvector<vector<int> > &toduplicate,\n\tvector<int> &neigh,\n\tvector<bool> &checked,\n\tTessellation const &tproc,\n\tconst vector<Edge>& own_edges,\n\tbool recursive)\n{\n\tint rank;\n\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\tvector<vector<int> > res;\n\tvector<int> vtemp;\n\tif (!recursive)\n\t\tres.resize(own_edges.size());\n\tstack<int> tocheck = initialise_tocheck\n\t\t(FindContainingTetras\n\t\t\t(static_cast<int>(Walk(static_cast<size_t>(point))), point));\n\tif (recursive)\n\t{\n\t\tvector<int> allouter;\n\t\tfor (size_t i = 0; i < toduplicate.size(); ++i)\n\t\t{\n\t\t\tfor (size_t j = 0; j < toduplicate[i].size(); ++j)\n\t\t\t{\n\t\t\t\tvector<int> temp = FindContainingTetras\n\t\t\t\t\t(static_cast<int>(Walk(static_cast<size_t>(toduplicate[i][j]))), toduplicate[i][j]);\n\t\t\t\tfor (size_t k = 0; k < temp.size(); ++k)\n\t\t\t\t\tallouter.push_back(temp[k]);\n\t\t\t}\n\t\t}\n\t\tsort(allouter.begin(), allouter.end());\n\t\tallouter = unique(allouter);\n\t\tfor (size_t i = 0; i < allouter.size(); ++i)\n\t\t\ttocheck.push(allouter[i]);\n\t}\n\twhile (!tocheck.empty())\n\t{\n\t\tint cur_facet = tocheck.top();\n\t\ttocheck.pop();\n\t\tfor (size_t i = 0; i < 3; ++i)\n\t\t{\n\t\t\tbool added = false;\n\t\t\tint max_neigh = 0;\n\t\t\tif (f[static_cast<size_t>(cur_facet)].vertices[i] >=\n\t\t\t\tstatic_cast<int>(olength))\n\t\t\t\tcontinue;\n\t\t\tif (checked[static_cast<size_t>\n\t\t\t\t(f[static_cast<size_t>(cur_facet)].vertices[i])])\n\t\t\t\tcontinue;\n\t\t\tvector<int> neighs = FindContainingTetras(cur_facet, f[static_cast<size_t>(cur_facet)].vertices[i]);\n\t\t\tfor (size_t k = 0; k < neighs.size(); ++k)\n\t\t\t{\n\t\t\t\tCircle circ(GetCircleCenter(neighs[k]), radius[static_cast<size_t>(neighs[k])]);\n\t\t\t\tvector<int> cputosendto;\n\t\t\t\tif (recursive)\n\t\t\t\t\tfind_affected_cells_recursive(tproc,rank, circ, cputosendto);\n\t\t\t\telse\n\t\t\t\t\tcputosendto = find_affected_cells\n\t\t\t\t\t(tproc, rank, circ,vtemp);\n\t\t\t\tsort(cputosendto.begin(), cputosendto.end());\n\t\t\t\tcputosendto = unique(cputosendto);\n\n\t\t\t\tRemoveVal(cputosendto,rank);\n\t\t\t\tif (!recursive) \n\t\t\t\t{\n\t\t\t\t\tconst vector<int> self_intersection = calc_self_intersection(own_edges, circ);\n\t\t\t\t\tif (!self_intersection.empty())\n\t\t\t\t\t\tadded = true;\n\t\t\t\t\tBOOST_FOREACH(int sindex, self_intersection)\n\t\t\t\t\t\tres[static_cast<size_t>(sindex)].push_back(f[static_cast<size_t>(cur_facet)].vertices[i]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor (size_t jj = 0; jj < 3; ++jj)\n\t\t\t\t\t\tmax_neigh = max(max_neigh, f[static_cast<size_t>(neighs[k])].vertices[jj]);\n\t\t\t\t}\n\t\t\t\tif (!cputosendto.empty())\n\t\t\t\t{\n\t\t\t\t\tadded = true;\n\t\t\t\t\tfor (size_t j = 0; j < cputosendto.size(); ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t index = static_cast<size_t>(find(neigh.begin(), neigh.end(), cputosendto[j])\n\t\t\t\t\t\t\t- neigh.begin());\n\t\t\t\t\t\tif (index < neigh.size())\n\t\t\t\t\t\t\ttoduplicate.at(index).push_back(f[static_cast<size_t>(cur_facet)].vertices[i]);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tneigh.push_back(cputosendto[j]);\n\t\t\t\t\t\t\ttoduplicate.push_back\n\t\t\t\t\t\t\t\t(vector<int>(1, f[static_cast<size_t>(cur_facet)].vertices[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\tchecked[static_cast<size_t>(f[static_cast<size_t>(cur_facet)].vertices[i])] = true;\n\t\t\tif (added||(recursive&&static_cast<size_t>(max_neigh)>=olength))\n\t\t\t{\n\t\t\t\tfor (size_t j = 0; j < neighs.size(); ++j)\n\t\t\t\t{\n\t\t\t\t\t//if (!IsOuterFacet(neighs[j]))\n\t\t\t\t\t\ttocheck.push(neighs[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n\npair<vector<vector<int> >, vector<vector<int> > >\nDelaunay::findOuterPoints\n(const Tessellation& t_proc,\n\tconst vector<Edge>& edge_list,\n\tconst vector<Edge>& box_edges,\n\tvector<vector<int> > &NghostIndex)\n{\n\tvector<int> neighbors_own_edges =\n\t\tcalc_neighbors_own_edges(t_proc, edge_list);\n\tconst size_t some_outer_point = findSomeOuterPoint();\n\n\tvector<vector<int> > to_duplicate(neighbors_own_edges.size());\n\tvector<bool> checked(olength, false);\n\tvector<vector<int> > self_points =\n\t\tAddOuterFacetsMPI\n\t\t(static_cast<int>(some_outer_point),\n\t\t\tto_duplicate, // indices of points to send\n\t\t\tneighbors_own_edges, // Rank of processes to send to\n\t\t\tchecked,\n\t\t\tt_proc,\n\t\t\tbox_edges);\n\tBOOST_FOREACH(vector<int>& line, to_duplicate) \n\t{\n\t\tsort(line.begin(), line.end());\n\t\tline = unique(line);\n\t}\n\n\t// Communication\n\tvector<vector<Vector2D> > incoming(neighbors_own_edges.size());\n\tvector<MPI_Request> req(neighbors_own_edges.size());\n\tvector<vector<double> > tosend(neighbors_own_edges.size());\n\tdouble dtemp = 0;\n\tfor (size_t i = 0; i < neighbors_own_edges.size(); ++i)\n\t{\n\t\tconst int dest = neighbors_own_edges.at(i);\n\t\ttosend[i] = list_serialize(VectorValues(cor, to_duplicate[i]));\n\t\tint size = static_cast<int>(tosend[i].size());\n\t\tif (size == 0)\n\t\t\tMPI_Isend(&dtemp, 1, MPI_DOUBLE,dest, 1, MPI_COMM_WORLD, &req[i]);\n\t\telse\n\t\t{\n\t\t\tif (size < 2)\n\t\t\t\tthrow UniversalError(\"Wrong send size\");\n\t\t\tMPI_Isend(&tosend[i][0], size, MPI_DOUBLE, dest, 0, MPI_COMM_WORLD, &req[i]);\n\t\t}\n\t}\n\tfor (size_t i = 0; i < neighbors_own_edges.size(); ++i)\n\t{\n\t\tvector<double> temprecv;\n\t\tMPI_Status status;\n\t\tMPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n\t\tint count;\n\t\tMPI_Get_count(&status, MPI_DOUBLE, &count);\n\t\ttemprecv.resize(static_cast<size_t>(max(count, 1)));\n\t\tMPI_Recv(&temprecv[0], count, MPI_DOUBLE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\tif (status.MPI_TAG == 0)\n\t\t{\n\t\t\tsize_t location = static_cast<size_t>(std::find(neighbors_own_edges.begin(), neighbors_own_edges.end(),\n\t\t\t\tstatus.MPI_SOURCE) - neighbors_own_edges.begin());\n\t\t\tif (location >= neighbors_own_edges.size())\n\t\t\t\tthrow UniversalError(\"Bad location in mpi exchange\");\n\t\t\ttry\n\t\t\t{\n\t\t\t\tincoming[location] = list_unserialize(temprecv, cor[0]);\n\t\t\t}\n\t\t\tcatch (UniversalError &eo)\n\t\t\t{\n\t\t\t\teo.AddEntry(\"Error in first send in triangulation\", 0.0);\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tif (status.MPI_TAG != 1)\n\t\t\t\tthrow UniversalError(\"Wrong mpi tag\");\n\t}\n\tMPI_Waitall(static_cast<int>(req.size()), &req[0], MPI_STATUSES_IGNORE);\n\t// Incorporate points recieved into triangulation\n\tBOOST_FOREACH(vector<int> &line, self_points)\n\t{\n\t\tsort(line.begin(), line.end());\n\t\tline = unique(line);\n\t}\n\tAddRigid(box_edges,self_points);\n\tfor (size_t i = 0; i < self_points.size(); ++i)\n\t\tfor (size_t j = 0; j < self_points[i].size(); ++j)\n\t\t\tOrgIndex.push_back(self_points[i][j]);\n\n\tNghostIndex.clear();\n\tNghostIndex.resize(incoming.size());\n\tfor (size_t i = 0; i < incoming.size(); ++i)\n\t{\n\t\tfor (size_t j = 0; j < incoming.at(i).size(); ++j)\n\t\t{\n\t\t\tOrgIndex.push_back(static_cast<int>(cor.size() + j));\n\t\t\tNghostIndex[i].push_back(static_cast<int>(cor.size() + j));\n\t\t}\n\t\tAddBoundaryPoints(incoming.at(i));\n\t}\n\tMPI_Barrier(MPI_COMM_WORLD);\n\treturn pair<vector<vector<int> >, vector<vector<int> > >\n\t\t(to_duplicate, self_points);\n}\n\nnamespace {\n\ttemplate<class T> bool is_in\n\t\t(const T& t,\n\t\t\tconst vector<T>& v)\n\t{\n\t\tBOOST_FOREACH(const T&m, v) {\n\t\t\tif (t == m)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nvector<vector<int> >\nDelaunay::boundary_intersection_check\n(const vector<Edge>& edges,\n\tconst vector<vector<int> >& to_duplicate)\n{\n\tvector<vector<int> > res;\n\tres.reserve(edges.size());\n\tBOOST_FOREACH(const Edge& edge, edges) {\n\t\tres.push_back(vector<int>());\n\t\tBOOST_FOREACH(const vector<int>& line, to_duplicate) {\n\t\t\tBOOST_FOREACH(const int index, line) {\n\t\t\t\tconst Circle circle\n\t\t\t\t\t(GetCircleCenter(index), radius[index]);\n\t\t\t\tif (edge_circle_intersect(edge, circle))\n\t\t\t\t\tres.back().push_back(index);\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n\npair<vector<vector<int> >, vector<int> > Delaunay::FindOuterPoints2\n(const Tessellation& t_proc,\n\tconst vector<Edge>& edge_list,\n\tvector<vector<int> > &to_duplicate,\n\tvector<vector<int> >& self_points,\n\tconst vector<Edge>& box_edges,\n\tvector<vector<int> > &NghostIndex)\n{\n\tconst vector<vector<int> > boundary_points =\n\t\tboundary_intersection_check(box_edges, to_duplicate);\n\tvector<vector<int> > real_boundary_points\n\t\t(box_edges.size());\n\tfor (size_t i = 0; i < boundary_points.size(); ++i)\n\t{\n\t\tsort(self_points.at(i).begin(), self_points.at(i).end());\n\t\tBOOST_FOREACH(int bp, boundary_points.at(i))\n\t\t{\n\t\t\tif (!binary_search(self_points.at(i).begin(),\n\t\t\t\tself_points.at(i).end(),\n\t\t\t\tbp))\n\t\t\t{\n\t\t\t\treal_boundary_points.at(i).push_back(bp);\n\t\t\t}\n\t\t}\n\t\tsort(real_boundary_points.at(i).begin(),\n\t\t\treal_boundary_points.at(i).end());\n\t\treal_boundary_points.at(i) = unique(real_boundary_points.at(i));\n\t}\n\n\tvector<vector<int> > to_duplicate_2 = to_duplicate;\n\tBOOST_FOREACH(vector<int>& line, to_duplicate_2)\n\t\tsort(line.begin(), line.end());\n\tvector<int> neighbors_own_edges =\n\t\tcalc_neighbors_own_edges(t_proc, edge_list);\n\tvector<int> old_neighbors = neighbors_own_edges;\n\tassert(!to_duplicate.empty());\n\tBOOST_FOREACH(const vector<int>& line, to_duplicate)\n\t\tassert(!line.empty());\n\tvector<bool> checked(olength, false);\n\tconst size_t some_outer_point = to_duplicate[0][0];\n\tAddOuterFacetsMPI\n\t\t(static_cast<int>(some_outer_point),\n\t\t\tto_duplicate, // indices of points to send\n\t\t\tneighbors_own_edges, // Rank of processes to send to\n\t\t\tchecked,\n\t\t\tt_proc,\n\t\t\tedge_list,\n\t\t\ttrue); // recursive\n\n\t// Communication\n\tint wsize;\n\tMPI_Comm_size(MPI_COMM_WORLD, &wsize);\n\tvector<int> totalk(static_cast<size_t>(wsize), 0);\n\tvector<int> scounts(totalk.size(), 1);\n\tfor (size_t i = 0; i < neighbors_own_edges.size(); ++i)\n\t\ttotalk[neighbors_own_edges[i]] = 1;\n\tint nrecv;\n\tMPI_Reduce_scatter(&totalk[0], &nrecv, &scounts[0], MPI_INT, MPI_SUM,\n\t\tMPI_COMM_WORLD);\n\n\tvector<MPI_Request> req(neighbors_own_edges.size());\n\tfor (size_t i = 0; i < neighbors_own_edges.size(); ++i)\n\t\tMPI_Isend(&wsize, 1, MPI_INT, neighbors_own_edges[i], 3, MPI_COMM_WORLD, &req[i]);\n\tvector<int> talkwithme;\n\tfor (int i = 0; i < nrecv; ++i)\n\t{\n\t\tMPI_Status status;\n\t\tMPI_Recv(&wsize, 1, MPI_INT, MPI_ANY_SOURCE, 3, MPI_COMM_WORLD, &status);\n\t\ttalkwithme.push_back(status.MPI_SOURCE);\n\t}\n\tvector<size_t> indices;\n\tfor (size_t i = 0; i < neighbors_own_edges.size(); ++i)\n\t{\n\t\tif (is_in(neighbors_own_edges[i],talkwithme))\n\t\t\tindices.push_back(i);\n\t}\n\n\t// Symmetrisation\n\tneighbors_own_edges =\n\t\tVectorValues\n\t\t(neighbors_own_edges,\n\t\t\tindices);\n\tto_duplicate =\n\t\tVectorValues\n\t\t(to_duplicate,\n\t\t\tindices);\n\t// Get rid of duplicate points\n\tfor (size_t i = 0; i < to_duplicate.size(); ++i)\n\t{\n\t\tsort(to_duplicate[i].begin(), to_duplicate[i].end());\n\t\tto_duplicate[i] = unique(to_duplicate[i]);\n\t}\n\tvector<vector<int> > messages(to_duplicate.size());\n\tfor (size_t i = 0; i < to_duplicate.size(); ++i) {\n\t\tconst vector<int>::const_iterator it =\n\t\t\tfind(old_neighbors.begin(),\n\t\t\t\told_neighbors.end(),\n\t\t\t\tneighbors_own_edges.at(i));\n\t\tfor (size_t j = 0; j < to_duplicate.at(i).size(); ++j) {\n\n\t\t\tif (it != old_neighbors.end()) {\n\t\t\t\tconst size_t my_index = static_cast<size_t>(it - old_neighbors.begin());\n\t\t\t\tif (!binary_search\n\t\t\t\t\t(to_duplicate_2.at(my_index).begin(),\n\t\t\t\t\t\tto_duplicate_2.at(my_index).end(),\n\t\t\t\t\t\tto_duplicate.at(i).at(j)))\n\t\t\t\t\tmessages.at(i).push_back(to_duplicate.at(i).at(j));\n\t\t\t}\n\t\t\telse\n\t\t\t\tmessages.at(i).push_back(to_duplicate.at(i).at(j));\n\t\t}\n\t}\n\tMPI_Waitall(static_cast<int>(neighbors_own_edges.size()), &req[0], MPI_STATUSES_IGNORE);\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t// Point exchange\n\treq.clear();\n\treq.resize(neighbors_own_edges.size());\n\tdouble dtemp = 0;\n\tvector<vector<Vector2D> > incoming(neighbors_own_edges.size());\n\tvector<vector<double> > tosend(neighbors_own_edges.size());\n\tfor (size_t i = 0; i < neighbors_own_edges.size(); ++i)\n\t{\n\t\tconst int dest = neighbors_own_edges.at(i);\n\t\ttosend[i] = list_serialize(VectorValues(cor, messages.at(i)));\n\t\tint size = static_cast<int>(tosend[i].size());\n\t\tif (size > 0)\n\t\t{\n\t\t\tif (size < 2)\n\t\t\t\tthrow UniversalError(\"Wrong send size\");\n\t\t\tMPI_Isend(&tosend[i][0], size, MPI_DOUBLE, dest, 0, MPI_COMM_WORLD, &req[i]);\n\t\t}\n\t\telse\n\t\t\tMPI_Isend(&dtemp, 1, MPI_DOUBLE, dest,1, MPI_COMM_WORLD, &req[i]);\n\t}\n\tfor (size_t i = 0; i < neighbors_own_edges.size(); ++i)\n\t{\n\t\tvector<double> temprecv;\n\t\tMPI_Status status;\n\t\tMPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n\t\tint count;\n\t\tMPI_Get_count(&status, MPI_DOUBLE, &count);\n\t\ttemprecv.resize(static_cast<size_t>(count));\n\t\tMPI_Recv(&temprecv[0], count, MPI_DOUBLE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\tif (status.MPI_TAG == 0)\n\t\t{\n\t\t\tsize_t location = static_cast<size_t>(std::find(neighbors_own_edges.begin(), neighbors_own_edges.end(), status.MPI_SOURCE) -\n\t\t\t\tneighbors_own_edges.begin());\n\t\t\tif (location >= neighbors_own_edges.size())\n\t\t\t\tthrow UniversalError(\"Bad location in mpi exchange\");\n\t\t\ttry\n\t\t\t{\n\t\t\t\tincoming[location] = list_unserialize(temprecv, cor[0]);\n\t\t\t}\n\t\t\tcatch (UniversalError &eo)\n\t\t\t{\n\t\t\t\teo.AddEntry(\"Error in second send in triangulation\", 0.0);\n\t\t\t\teo.AddEntry(\"Mpi status\", static_cast<double>(status.MPI_SOURCE));\n\t\t\t\teo.AddEntry(\"Mpi tag\", static_cast<double>(status.MPI_TAG));\n\t\t\t\teo.AddEntry(\"Mpi count\", static_cast<double>(count));\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tif (status.MPI_TAG != 1)\n\t\t\t\tthrow UniversalError(\"Wrong mpi tag\");\n\t}\n\tMPI_Waitall(static_cast<int>(req.size()), &req[0], MPI_STATUSES_IGNORE);\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t// Incorporate points recieved into triangulation\n\tNghostIndex.resize(incoming.size());\n\tfor (size_t i = 0; i < incoming.size(); ++i)\n\t{\n\t\tfor (size_t j = 0; j < incoming.at(i).size(); ++j)\n\t\t{\n\t\t\tNghostIndex[i].push_back(static_cast<int>(cor.size() + j));\n\t\t\tOrgIndex.push_back(static_cast<int>(cor.size() + j));\n\t\t}\n\t\tAddBoundaryPoints(incoming.at(i));\n\t}\n\n\tAddRigid(box_edges,real_boundary_points);\n\tfor (size_t i = 0; i < real_boundary_points.size(); ++i)\n\t\tfor (size_t j = 0; j < real_boundary_points[i].size(); ++j)\n\t\t\tOrgIndex.push_back(real_boundary_points[i][j]);\n\n\tfor (size_t i = 0; i < self_points.size(); ++i)\n\t\tif (!real_boundary_points[i].empty())\n\t\t\tself_points[i].insert(self_points[i].end(), real_boundary_points[i].begin(),\n\t\t\t\treal_boundary_points[i].end());\n\n\treturn  pair<vector<vector<int> >,vector<int> > (to_duplicate,neighbors_own_edges);\n}\n\npair<vector<vector<int> >, vector<int> > Delaunay::BuildBoundary\n(OuterBoundary const* obc,\n\tTessellation const& tproc,\n\tvector<vector<int> >& Nghost)\n{\n\tvector<Edge> edges;\n\tOrgIndex.clear();\n\tint rank;\n\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\tvector<int> edge_index = tproc.GetCellEdges(rank);\n\tfor (size_t i = 0; i < edge_index.size(); ++i)\n\t\tedges.push_back(tproc.GetEdge(edge_index[i]));\n\tvector<Edge> box_edges = obc->GetBoxEdges();\n\tpair<vector<vector<int> >, vector<vector<int> > > to_duplicate =\n\t\tfindOuterPoints(tproc, edges, box_edges, Nghost);\n\treturn FindOuterPoints2(tproc,edges,to_duplicate.first, to_duplicate.second,box_edges, Nghost);\n}\n\nint Delaunay::GetOrgIndex(int index)const\n{\n\tif (index < static_cast<int>(olength))\n\t\treturn static_cast<int>(olength);\n\telse\n\t\treturn OrgIndex.at(index - 3 - static_cast<int>(olength));\n}\n\n#endif // RICH_MPI\n", "meta": {"hexsha": "d894ac994a6461854f52d4934e889189ceee8675", "size": 49356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/Delaunay.cpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/Delaunay.cpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/Delaunay.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": 30.2611894543, "max_line_length": 205, "alphanum_fraction": 0.6820244752, "num_tokens": 15185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.022286184118711062, "lm_q1q2_score": 0.010881973649672347}}
{"text": "// This file is distributed under the MIT license.\n// See the LICENSE file for details.\n\n#include <common/config.h>\n\n#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <exception>\n#include <fstream>\n#include <future>\n#include <iomanip>\n#include <iostream>\n#include <istream>\n#include <iterator>\n#include <map>\n#include <memory>\n#include <mutex>\n#include <new>\n#include <ostream>\n#include <set>\n#include <sstream>\n#include <string>\n#include <thread>\n\n#include <boost/filesystem.hpp>\n\n#include <imgui.h>\n\n#include <Support/CmdLine.h>\n#include <Support/CmdLineUtil.h>\n\n#include <visionaray/gl/bvh_outline_renderer.h>\n#include <visionaray/gl/debug_callback.h>\n#include <visionaray/math/math.h>\n#include <visionaray/texture/texture.h>\n#include <visionaray/aligned_vector.h>\n#include <visionaray/area_light.h>\n#include <visionaray/bvh.h>\n#include <visionaray/generic_material.h>\n#include <visionaray/kernels.h>\n#include <visionaray/material.h>\n#include <visionaray/pinhole_camera.h>\n#include <visionaray/point_light.h>\n#include <visionaray/scheduler.h>\n#include <visionaray/thin_lens_camera.h>\n\n#if defined(__INTEL_COMPILER) || defined(__MINGW32__) || defined(__MINGW64__)\n#include <visionaray/detail/tbb_sched.h>\n#endif\n\n#include <common/manip/arcball_manipulator.h>\n#include <common/manip/pan_manipulator.h>\n#include <common/manip/zoom_manipulator.h>\n#include <common/make_materials.h>\n#include <common/model.h>\n#include <common/sg.h>\n#include <common/timer.h>\n#include <common/viewer_glut.h>\n\n#ifdef __CUDACC__\n#include <common/cuda.h>\n#endif\n\n#if VSNRAY_COMMON_HAVE_PTEX\n#include <common/ptex.h>\n#endif\n\n#include \"call_kernel.h\"\n#include \"host_device_rt.h\"\n#include \"render.h\"\n\n\nusing namespace visionaray;\n\nusing viewer_type = viewer_glut;\n\n\n//-------------------------------------------------------------------------------------------------\n// Renderer, stores state, geometry, normals, ...\n//\n\nstruct renderer : viewer_type\n{\n    using primitive_type            = model::triangle_type;\n    using normal_type               = model::normal_type;\n    using tex_coord_type            = model::tex_coord_type;\n    using host_bvh_type             = index_bvh<primitive_type>;\n#ifdef __CUDACC__\n    using device_bvh_type           = cuda_index_bvh<primitive_type>;\n    using device_tex_type           = cuda_texture<vector<4, unorm<8>>, 2>;\n    using device_tex_ref_type       = typename device_tex_type::ref_type;\n#endif\n\n    enum bvh_build_strategy\n    {\n        Binned = 0,  // Binned SAH builder, no spatial splits\n        Split        // Split BVH, also binned and with SAH\n    };\n\n    enum texture_format { Ptex, UV };\n\n    renderer()\n        : viewer_type(800, 800, \"Visionaray Viewer\")\n        , host_sched(std::thread::hardware_concurrency())\n        , rt(\n            host_device_rt::CPU,\n            true /* double buffering */,\n            true /* direct rendering */,\n            host_device_rt::SRGB\n            )\n#ifdef __CUDACC__\n        , device_sched(8, 8)\n#endif\n        , mouse_pos(0)\n    {\n        using namespace support;\n\n        add_cmdline_option( cl::makeOption<std::set<std::string>&>(\n            cl::Parser<>(),\n            \"filenames\",\n            cl::Desc(\"Input files in wavefront obj format\"),\n            cl::Positional,\n            cl::OneOrMore,\n            cl::init(filenames)\n            ) );\n\n        add_cmdline_option( cl::makeOption<std::string&>(\n            cl::Parser<>(),\n            \"camera\",\n            cl::Desc(\"Text file with camera parameters\"),\n            cl::ArgRequired,\n            cl::init(this->initial_camera)\n            ) );\n\n        add_cmdline_option( cl::makeOption<algorithm&>({\n                { \"simple\",             Simple,         \"Simple ray casting kernel\" },\n                { \"whitted\",            Whitted,        \"Whitted style ray tracing kernel\" },\n                { \"pathtracing\",        Pathtracing,    \"Pathtracing global illumination kernel\" }\n            },\n            \"algorithm\",\n            cl::Desc(\"Rendering algorithm\"),\n            cl::ArgRequired,\n            cl::init(this->algo)\n            ) );\n\n        add_cmdline_option( cl::makeOption<bvh_build_strategy&>({\n                { \"default\",            Binned,         \"Binned SAH\" },\n                { \"split\",              Split,          \"Binned SAH with spatial splits\" }\n            },\n            \"bvh\",\n            cl::Desc(\"BVH build strategy\"),\n            cl::ArgRequired,\n            cl::init(this->builder)\n            ) );\n\n        add_cmdline_option( cl::makeOption<unsigned&>({\n                { \"1\",      1,      \"1x supersampling\" },\n                { \"2\",      2,      \"2x supersampling\" },\n                { \"4\",      4,      \"4x supersampling\" },\n                { \"8\",      8,      \"8x supersampling\" }\n            },\n            \"ssaa\",\n            cl::Desc(\"Supersampling anti-aliasing factor\"),\n            cl::ArgRequired,\n            cl::init(this->ssaa_samples)\n            ) );\n\n        add_cmdline_option( cl::makeOption<bool&>(\n            cl::Parser<>(),\n            \"headlight\",\n            cl::Desc(\"Activate headlight\"),\n            cl::ArgRequired,\n            cl::init(this->use_headlight)\n            ) );\n\n        add_cmdline_option( cl::makeOption<bool&>(\n            cl::Parser<>(),\n            \"dof\",\n            cl::Desc(\"Activate depth of field\"),\n            cl::ArgRequired,\n            cl::init(this->use_dof)\n            ) );\n\n        add_cmdline_option( cl::makeOption<unsigned&>(\n            cl::Parser<>(),\n            \"bounces\",\n            cl::Desc(\"Number of bounces for recursive ray tracing\"),\n            cl::ArgRequired,\n            cl::init(this->bounces)\n            ) );\n\n        add_cmdline_option( cl::makeOption<vec3&, cl::ScalarType>(\n            [&](StringRef name, StringRef /*arg*/, vec3& value)\n            {\n                cl::Parser<>()(name + \"-r\", cmd_line_inst().bump(), value.x);\n                cl::Parser<>()(name + \"-g\", cmd_line_inst().bump(), value.y);\n                cl::Parser<>()(name + \"-b\", cmd_line_inst().bump(), value.z);\n            },\n            \"ambient\",\n            cl::Desc(\"Ambient color\"),\n            cl::ArgDisallowed,\n            cl::init(this->ambient)\n            ) );\n\n        add_cmdline_option( cl::makeOption<host_device_rt::color_space_type&>({\n                { \"rgb\",  host_device_rt::RGB,  \"RGB color space for display\" },\n                { \"srgb\", host_device_rt::SRGB, \"sRGB color space for display\" },\n            },\n            \"colorspace\",\n            cl::Desc(\"Color space\"),\n            cl::ArgRequired,\n            cl::init(rt.color_space())\n            ) );\n\n#ifdef __CUDACC__\n        add_cmdline_option( cl::makeOption<host_device_rt::mode_type&>({\n                { \"cpu\", host_device_rt::CPU, \"Rendering on the CPU\" },\n                { \"gpu\", host_device_rt::GPU, \"Rendering on the GPU\" },\n            },\n            \"device\",\n            cl::Desc(\"Rendering device\"),\n            cl::ArgRequired,\n            cl::init(rt.mode())\n            ) );\n#endif\n    }\n\n\n    int                                         w               = 800;\n    int                                         h               = 800;\n    unsigned                                    frame_num       = 0;\n    unsigned                                    bounces         = 0;\n    unsigned                                    ssaa_samples    = 1;\n    algorithm                                   algo            = Simple;\n    bvh_build_strategy                          builder         = Binned;\n    bool                                        use_headlight   = true;\n    bool                                        use_dof         = false;\n    bool                                        show_hud        = true;\n    bool                                        show_hud_ext    = true;\n    bool                                        show_bvh        = false;\n\n\n    std::set<std::string>                       filenames;\n    std::string                                 initial_camera;\n\n    model                                       mod;\n    vec3                                        ambient         = vec3(-1.0f);\n\n    index_bvh<host_bvh_type::bvh_inst>          host_top_level_bvh;\n    aligned_vector<host_bvh_type>               host_bvhs;\n    aligned_vector<host_bvh_type::bvh_inst>     host_instances;\n    aligned_vector<plastic<float>>              plastic_materials;\n    aligned_vector<generic_material_t>          generic_materials;\n    aligned_vector<point_light<float>>          point_lights;\n    aligned_vector<area_light<float,\n                   basic_triangle<3, float>>>   area_lights;\n#if VSNRAY_COMMON_HAVE_PTEX\n    aligned_vector<ptex::face_id_t>             ptex_tex_coords;\n    aligned_vector<ptex::texture>               ptex_textures;\n#endif\n#ifdef __CUDACC__\n    device_bvh_type                             device_bvh;\n    thrust::device_vector<normal_type>          device_geometric_normals;\n    thrust::device_vector<normal_type>          device_shading_normals;\n    thrust::device_vector<tex_coord_type>       device_tex_coords;\n    thrust::device_vector<plastic<float>>       device_plastic_materials;\n    thrust::device_vector<generic_material_t>   device_generic_materials;\n    std::map<std::string, device_tex_type>      device_texture_map;\n    thrust::device_vector<device_tex_ref_type>  device_textures;\n#endif\n\n    host_sched_t<ray_type_cpu>                  host_sched;\n    host_device_rt                              rt;\n#ifdef __CUDACC__\n    cuda_sched<ray_type_gpu>                    device_sched;\n#endif\n    thin_lens_camera                            cam;\n\n    std::shared_ptr<visionaray::texture<vec4, 2>>\n                                                environment_map = nullptr;\n\n\n    // List of cameras, e.g. read from scene graph\n    aligned_vector<std::pair<\n            std::string, thin_lens_camera>>     cameras;\n\n    mouse::pos                                  mouse_pos;\n\n    texture_format                              tex_format = UV;\n\n    visionaray::frame_counter                   counter;\n    double                                      last_frame_time = 0.0;\n    gl::bvh_outline_renderer                    outlines;\n    gl::debug_callback                          gl_debug_callback;\n\n    bool                                        render_async  = false;\n    std::future<void>                           render_future;\n    std::mutex                                  display_mutex;\n\n    void build_bvhs();\n\nprotected:\n\n    void on_close();\n    void on_display();\n    void on_key_press(visionaray::key_event const& event);\n    void on_mouse_move(visionaray::mouse_event const& event);\n    void on_resize(int w, int h);\n\nprivate:\n\n    void load_camera(std::string filename);\n    void clear_frame();\n    void render_hud();\n    void render_impl();\n\n};\n\n\n//-------------------------------------------------------------------------------------------------\n// I/O utility for camera lookat only - not fit for the general case!\n//\n\nstd::istream& operator>>(std::istream& in, pinhole_camera& cam)\n{\n    vec3 eye;\n    vec3 center;\n    vec3 up;\n\n    in >> eye >> std::ws >> center >> std::ws >> up >> std::ws;\n    cam.look_at(eye, center, up);\n\n    return in;\n}\n\nstd::ostream& operator<<(std::ostream& out, pinhole_camera const& cam)\n{\n    out << cam.eye() << '\\n';\n    out << cam.center() << '\\n';\n    out << cam.up() << '\\n';\n    return out;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Reset triangle mesh flags to 0\n//\n\nstruct reset_flags_visitor : sg::node_visitor\n{\n    using node_visitor::apply;\n\n    void apply(sg::surface_properties& sp)\n    {\n        sp.flags() = 0;\n\n        node_visitor::apply(sp);\n    }\n\n    void apply(sg::triangle_mesh& tm)\n    {\n        tm.flags() = 0;\n\n        node_visitor::apply(tm);\n    }\n};\n\n\n//-------------------------------------------------------------------------------------------------\n// Traverse the scene graph to construct geometry, materials and BVH instances\n//\n\nstruct build_bvhs_visitor : sg::node_visitor\n{\n    using node_visitor::apply;\n\n    build_bvhs_visitor(\n            aligned_vector<renderer::host_bvh_type>& bvhs,\n            aligned_vector<size_t>& instance_indices,\n            aligned_vector<mat4>& instance_transforms,\n            aligned_vector<vec3>& shading_normals,\n            aligned_vector<vec3>& geometric_normals,\n            aligned_vector<vec2>& tex_coords,\n#if VSNRAY_COMMON_HAVE_PTEX\n            aligned_vector<ptex::face_id_t>& face_ids,\n#endif\n            aligned_vector<std::pair<std::string, thin_lens_camera>>& cameras\n            )\n        : bvhs_(bvhs)\n        , instance_indices_(instance_indices)\n        , instance_transforms_(instance_transforms)\n        , shading_normals_(shading_normals)\n        , geometric_normals_(geometric_normals)\n        , tex_coords_(tex_coords)\n#if VSNRAY_COMMON_HAVE_PTEX\n        , face_ids_(face_ids)\n#endif\n        , cameras_(cameras)\n        , environment_map(nullptr)\n    {\n    }\n\n    void apply(sg::camera& c)\n    {\n        cameras_.push_back(std::make_pair(c.name(), static_cast<thin_lens_camera>(c)));\n\n        node_visitor::apply(c);\n    }\n\n    void apply(sg::environment_light& el)\n    {\n        auto tex = std::dynamic_pointer_cast<sg::texture2d<vec4>>(el.texture());\n\n        if (tex != nullptr)\n        {\n            environment_map = std::make_shared<visionaray::texture<vec4, 2>>(tex->width(), tex->height());\n            environment_map->set_address_mode(tex->get_address_mode());\n            environment_map->set_filter_mode(tex->get_filter_mode());\n            environment_map->reset(tex->data());\n        }\n\n        node_visitor::apply(el);\n    }\n\n    void apply(sg::transform& t)\n    {\n        mat4 prev = current_transform_;\n\n        current_transform_ = current_transform_ * t.matrix();\n\n        node_visitor::apply(t);\n\n        current_transform_ = prev;\n    }\n\n    void apply(sg::surface_properties& sp)\n    {\n        unsigned prev = current_geom_id_;\n\n        if (sp.flags() == 0 && sp.material() && sp.textures().size() > 0)\n        {\n            std::shared_ptr<sg::material> material = sp.material();\n            std::shared_ptr<sg::texture> texture = sp.textures()[0];\n\n            auto surf = std::make_pair(material, texture);\n\n            auto it = std::find(surfaces.begin(), surfaces.end(), surf);\n            if (it == surfaces.end())\n            {\n                current_geom_id_ = static_cast<unsigned>(surfaces.size());\n                surfaces.push_back(surf);\n            }\n            else\n            {\n                current_geom_id_ = static_cast<unsigned>(std::distance(surfaces.begin(), it));\n            }\n\n            sp.flags() = ~sp.flags();\n        }\n\n        node_visitor::apply(sp);\n\n        current_geom_id_ = prev;\n    }\n\n    void apply(sg::triangle_mesh& tm)\n    {\n        if (tm.flags() == 0 && tm.vertices.size() > 0)\n        {\n            assert(tm.vertices.size() % 3 == 0);\n\n            aligned_vector<basic_triangle<3, float>> triangles(tm.vertices.size() / 3);\n\n            size_t first_geometric_normal = geometric_normals_.size();\n            geometric_normals_.resize(geometric_normals_.size() + tm.vertices.size() / 3);\n\n            shading_normals_.insert(shading_normals_.end(), tm.normals.begin(), tm.normals.end());\n\n            tex_coords_.insert(tex_coords_.end(), tm.tex_coords.begin(), tm.tex_coords.end());\n\n#if VSNRAY_COMMON_HAVE_PTEX\n            face_ids_.insert(face_ids_.end(), tm.face_ids.begin(), tm.face_ids.end());\n#endif\n\n            for (size_t i = 0; i < tm.vertices.size(); i += 3)\n            {\n                vec3 v1 = tm.vertices[i];\n                vec3 v2 = tm.vertices[i + 1];\n                vec3 v3 = tm.vertices[i + 2];\n\n                basic_triangle<3, float> tri(v1, v2 - v1, v3 - v1);\n                tri.prim_id = current_prim_id_++;\n                tri.geom_id = current_geom_id_;\n                triangles[i / 3] = tri;\n\n                vec3 gn = normalize(cross(v2 - v1, v3 - v1));\n\n                geometric_normals_[first_geometric_normal + i / 3] = gn;\n            }\n\n            // Build single bvh\n            bvhs_.emplace_back(build<renderer::host_bvh_type>(\n                    triangles.data(),\n                    triangles.size(),\n                    false//builder == Split\n                    ));\n\n            tm.flags() = ~(bvhs_.size() - 1);\n        }\n\n        instance_indices_.push_back(~tm.flags());\n        instance_transforms_.push_back(current_transform_);\n\n        node_visitor::apply(tm);\n    }\n\n    // List of surface properties to derive geom_ids from\n    std::vector<std::pair<std::shared_ptr<sg::material>, std::shared_ptr<sg::texture>>> surfaces;\n\n    // Current transform along the path\n    mat4 current_transform_ = mat4::identity();\n\n\n    // Storage bvhs\n    aligned_vector<renderer::host_bvh_type>& bvhs_;\n\n    // Indices to construct instances from\n    aligned_vector<size_t>& instance_indices_;\n\n    // Transforms to construct instances from\n    aligned_vector<mat4>& instance_transforms_;\n\n    // Shading normals\n    aligned_vector<vec3>& shading_normals_;\n\n    // Geometric normals\n    aligned_vector<vec3>& geometric_normals_;\n\n    // Texture coordinates\n    aligned_vector<vec2>& tex_coords_;\n\n#if VSNRAY_COMMON_HAVE_PTEX\n    // Ptex face ids\n    aligned_vector<ptex::face_id_t>& face_ids_;\n#endif\n\n    // Cameras\n    aligned_vector<std::pair<std::string, thin_lens_camera>>& cameras_;\n\n    // Environment map\n    std::shared_ptr<visionaray::texture<vec4, 2>> environment_map;\n\n    // Assign consecutive prim ids\n    unsigned current_prim_id_ = 0;\n\n    // Assign consecutive geom ids for each encountered material\n    unsigned current_geom_id_ = 0;\n\n    // Index into the bvh list\n    unsigned current_bvh_index_ = 0;\n\n    // Index into the instance list\n    unsigned current_instance_index_ = 0;\n\n};\n\n\n//-------------------------------------------------------------------------------------------------\n// Build bvhs\n//\n\nvoid renderer::build_bvhs()\n{\n//  timer t;\n\n    std::cout << \"Creating BVH...\\n\";\n\n    if (mod.scene_graph == nullptr)\n    {\n        // Single BVH\n        host_bvhs.resize(1);\n        host_bvhs[0] = build<host_bvh_type>(\n                mod.primitives.data(),\n                mod.primitives.size(),\n                builder == Split\n                );\n    }\n    else\n    {\n        reset_flags_visitor reset_visitor;\n        mod.scene_graph->accept(reset_visitor);\n\n        aligned_vector<size_t> instance_indices;\n        aligned_vector<mat4> instance_transforms;\n\n        build_bvhs_visitor build_visitor(\n                host_bvhs,\n                instance_indices,\n                instance_transforms,\n                mod.shading_normals, // TODO!!!\n                mod.geometric_normals,\n                mod.tex_coords,\n#if VSNRAY_COMMON_HAVE_PTEX\n                ptex_tex_coords,\n#endif\n                cameras\n                );\n        mod.scene_graph->accept(build_visitor);\n\n        host_instances.resize(instance_indices.size());\n        for (size_t i = 0; i < instance_indices.size(); ++i)\n        {\n            size_t index = instance_indices[i];\n            host_instances[i] = host_bvhs[index].inst(instance_transforms[i]);\n        }\n\n        host_top_level_bvh = build<index_bvh<host_bvh_type::bvh_inst>>(\n                host_instances.data(),\n                host_instances.size(),\n                false\n                );\n\n\n        tex_format = renderer::UV;\n\n#if VSNRAY_COMMON_HAVE_PTEX\n        // Simply check the first texture of the first surface\n        // Scene has either Ptex textures, or it doesn't\n        if (build_visitor.surfaces.size() > 0\n            && std::dynamic_pointer_cast<sg::ptex_texture>(build_visitor.surfaces[0].second) != nullptr)\n        {\n            tex_format = renderer::Ptex;\n            ptex_textures.resize(build_visitor.surfaces.size());\n        }\n#endif\n\n        if (tex_format == renderer::UV)\n        {\n            mod.textures.resize(build_visitor.surfaces.size());\n        }\n\n        for (size_t i = 0; i < build_visitor.surfaces.size(); ++i)\n        {\n            auto const& surf = build_visitor.surfaces[i];\n\n            auto disney = std::dynamic_pointer_cast<sg::disney_material>(surf.first);\n            assert(disney != nullptr);\n\n            model::material_type newmat = {};\n            newmat.cd = disney->base_color.xyz();\n            newmat.cs = vec3(0.0f);\n            newmat.ior = vec3(disney->ior);\n            newmat.transmission = disney->refractive; // TODO\n            if (newmat.transmission > 0.0f)\n            {\n                newmat.illum = 4;\n                newmat.cs = vec3(disney->spec_trans);\n            }\n            mod.materials.emplace_back(newmat); // TODO\n\n#if VSNRAY_COMMON_HAVE_PTEX\n            auto ptex_tex = std::dynamic_pointer_cast<sg::ptex_texture>(surf.second);\n            if (ptex_tex != nullptr)\n            {\n                ptex_textures[i] = { ptex_tex->filename(), ptex_tex->cache() };\n            }\n#else\n            auto tex = std::dynamic_pointer_cast<sg::texture2d<vector<4, unorm<8>>>>(surf.second);\n            if (tex != nullptr)\n            {\n                model::texture_type texture(tex->width(), tex->height());\n                texture.set_address_mode(tex->get_address_mode());\n                texture.set_filter_mode(tex->get_filter_mode());\n                texture.reset(tex->data());\n\n                auto it = mod.texture_map.insert(std::make_pair(tex->name(), std::move(texture)));\n                mod.textures[i] = model::texture_type::ref_type(it.first->second);\n            }\n#endif\n        }\n\n        environment_map = build_visitor.environment_map;\n\n        mod.bbox = host_top_level_bvh.node(0).get_bounds();\n        mod.materials.push_back({});\n\n#if 1\n        mod.scene_graph.reset();\n#endif\n    }\n\n//  std::cout << t.elapsed() << std::endl;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Load camera from file, reset frame counter and clear frame\n//\n\nvoid renderer::load_camera(std::string filename)\n{\n    std::ifstream file(filename);\n    if (file.good())\n    {\n        file >> cam;\n        counter.reset();\n        clear_frame();\n        std::cout << \"Load camera from file: \" << filename << '\\n';\n    }\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// If path tracing, clear frame buffer and reset frame counter\n//\n\nvoid renderer::clear_frame()\n{\n    if (render_future.valid() && render_async)\n    {\n        render_future.wait();\n    }\n\n    frame_num = 0;\n\n    if (algo == Pathtracing)\n    {\n        rt.clear_color_buffer();\n    }\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// HUD\n//\n\nvoid renderer::render_hud()\n{\n    if (!have_imgui_support())\n    {\n        return;\n    }\n\n    // gather data to render\n\n    int w = width();\n    int h = height();\n\n    int x = visionaray::clamp( mouse_pos.x, 0, w - 1 );\n    int y = visionaray::clamp( mouse_pos.y, 0, h - 1 );\n    auto color = rt.color();\n    auto rgba = color[(h - 1 - y) * w + x];\n\n    int num_nodes = 0;\n    int num_leaves = 0;\n\n    float focal_dist = cam.get_focal_distance();\n    float lens_radius = cam.get_lens_radius();\n\n    traverse_depth_first(\n        host_bvhs[0],\n        [&](renderer::host_bvh_type::node_type const& node)\n        {\n            ++num_nodes;\n\n            if (is_leaf(node))\n            {\n                ++num_leaves;\n            }\n        }\n        );\n\n\n    static const std::string camera_file_base = \"visionaray-camera\";\n    static const std::string camera_file_suffix = \".txt\";\n\n    std::vector<std::string> camera_names;\n\n    camera_names.push_back(\"<reset...>\");\n\n\n    // Cameras from scene graph\n    for (auto& c : cameras)\n    {\n        camera_names.push_back(c.first);\n    }\n\n\n    // Camera files\n    int inc = 0;\n    std::string inc_str = \"\";\n\n    std::string filename = camera_file_base + inc_str + camera_file_suffix;\n\n    while (boost::filesystem::exists(filename))\n    {\n        camera_names.push_back(filename);\n\n        ++inc;\n        inc_str = std::to_string(inc);\n\n        while (inc_str.length() < 4)\n        {\n            inc_str = std::string(\"0\") + inc_str;\n        }\n\n        inc_str = std::string(\"-\") + inc_str;\n\n        filename = camera_file_base + inc_str + camera_file_suffix;\n    }\n\n\n    ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver);\n    ImGui::Begin(\"Settings\", &show_hud);\n\n    ImGui::Text(\"X: %4d\", x);\n    ImGui::SameLine();\n    ImGui::Text(\"W: %4d\", w);\n    ImGui::SameLine();\n    ImGui::Spacing();\n    ImGui::SameLine();\n    ImGui::Text(\"# Triangles: %zu\", mod.primitives.size());\n\n    ImGui::Text(\"Y: %4d\", y);\n    ImGui::SameLine();\n    ImGui::Text(\"H: %4d\", h);\n    ImGui::SameLine();\n    ImGui::Spacing();\n    ImGui::SameLine();\n    ImGui::Text(\"# BVH Nodes/Leaves: %d/%d\", num_nodes, num_leaves);\n\n    ImGui::Text(\"R: %5.2f\", rgba.x);\n    ImGui::SameLine();\n    ImGui::Text(\"G: %5.2f\", rgba.y);\n    ImGui::SameLine();\n    ImGui::Text(\"B: %5.2f\", rgba.z);\n\n    ImGui::Text(\"FPS: %6.2f\", last_frame_time);\n    ImGui::SameLine();\n    ImGui::Spacing();\n    ImGui::SameLine();\n    if (algo == Pathtracing)\n    {\n        ImGui::Text(\"SPP: %7u\", std::max(1U, frame_num));\n    }\n    else\n    {\n        ImGui::Text(\"SPP: %dx SSAA\", ssaa_samples);\n    }\n    ImGui::SameLine();\n    ImGui::Spacing();\n    ImGui::SameLine();\n    ImGui::Text(\"Device: %s\", rt.mode() == host_device_rt::GPU ? \"GPU\" : \"CPU\");\n\n    ImGui::Spacing();\n\n    if (ImGui::Checkbox(\"Headlight\", &use_headlight))\n    {\n        clear_frame();\n    }\n    ImGui::SameLine();\n    if (ImGui::Checkbox(\"Render async\", &render_async))\n    {\n        if (render_future.valid() && !render_async)\n        {\n            render_future.wait();\n        }\n    }\n\n    vec3 amb = ambient.x < 0.0f ? vec3(0.0f) : ambient;\n    if (ImGui::InputFloat3(\"Ambient Intensity\", amb.data()))\n    {\n        ambient = amb;\n        clear_frame();\n    }\n\n    if (ImGui::Checkbox(\"DoF\", &use_dof) && algo == Pathtracing)\n    {\n        clear_frame();\n\n        if (algo != Pathtracing)\n        {\n            std::cerr << \"Warning: setting only affects pathtracing algorithm\\n\";\n        }\n    }\n    ImGui::SameLine();\n    ImGui::PushItemWidth(200);\n    if (ImGui::SliderFloat(\"\", &focal_dist, 0.1, 100.0f, \"Focal Dist. %.1f\"))\n    {\n        cam.set_focal_distance(focal_dist);\n        if (use_dof && algo == Pathtracing)\n        {\n            clear_frame();\n        }\n\n        if (algo != Pathtracing)\n        {\n            std::cerr << \"Warning: setting only affects pathtracing algorithm\\n\";\n        }\n    }\n    ImGui::SameLine();\n    ImGui::PushItemWidth(50);\n    if (ImGui::InputFloat(\"Lens radius\", &lens_radius))\n    {\n        cam.set_lens_radius(lens_radius);\n        if (use_dof && algo == Pathtracing)\n        {\n            clear_frame();\n        }\n\n        if (algo != Pathtracing)\n        {\n            std::cerr << \"Warning: setting only affects pathtracing algorithm\\n\";\n        }\n    }\n    ImGui::PopItemWidth();\n\n    // TODO: member?\n    static std::string current = camera_names[0]; // <reset...>\n\n    if (ImGui::BeginCombo(\"Cameras\", current.c_str()))\n    {\n        for (size_t i = 0; i < camera_names.size(); ++i)\n        {\n            bool selected = current == camera_names[i];\n\n            if (ImGui::Selectable(camera_names[i].c_str(), selected))\n            {\n                current = camera_names[i].c_str();\n\n                auto it = std::find_if(\n                        cameras.begin(),\n                        cameras.end(),\n                        [&](std::pair<std::string, thin_lens_camera> c)\n                        {\n                            return c.first == camera_names[i];\n                        }\n                        );\n\n                if (it != cameras.end())\n                {\n                    // Preloaded\n                    cam = it->second;\n\n                    // Reset viewport and aspect\n                    float fovy = cam.fovy();\n                    float aspect = width() / static_cast<float>(height());\n                    cam.set_viewport(0, 0, width(), height());\n                    cam.perspective(fovy, aspect, 0.001f, 1000.0f);\n\n                    counter.reset();\n                    clear_frame();\n                }\n                else if (current == camera_names[0])\n                {\n                    // Reset...\n                    float aspect = width() / static_cast<float>(height());\n\n                    cam.perspective(45.0f * constants::degrees_to_radians<float>(), aspect, 0.001f, 1000.0f);\n                    cam.set_lens_radius(0.1f);\n                    cam.set_focal_distance(10.0f);\n                    cam.view_all(mod.bbox);\n\n                    counter.reset();\n                    clear_frame();\n                }\n                else if (boost::filesystem::exists(current))\n                {\n                    // From file\n                    load_camera(current);\n                }\n            }\n\n            if (selected)\n            {\n                ImGui::SetItemDefaultFocus();\n            }\n        }\n\n        ImGui::EndCombo();\n    }\n\n    ImGui::End();\n}\n\nvoid renderer::render_impl()\n{\n    point_lights.clear();\n\n    if (use_headlight)\n    {\n        point_light<float> headlight;\n        headlight.set_cl( vec3(1.0, 1.0, 1.0) );\n        headlight.set_kl(1.0);\n        headlight.set_position( cam.eye() );\n        headlight.set_constant_attenuation(1.0);\n        headlight.set_linear_attenuation(0.0);\n        headlight.set_quadratic_attenuation(0.0);\n        point_lights.push_back(headlight);\n    }\n\n    auto bounds     = mod.bbox;\n    auto diagonal   = bounds.max - bounds.min;\n    auto bounces    = this->bounces ? this->bounces : algo == Pathtracing ? 10U : 4U;\n    auto epsilon    = std::max( 1E-3f, length(diagonal) * 1E-5f );\n    auto amb        = ambient.x >= 0.0f // if set via cmdline\n                            ? vec4(ambient, 1.0f)\n                            : vec4(0.0)\n                            ;\n\n    camera_t camx;\n    if (use_dof && algo == Pathtracing)\n    {\n        camx = cam;\n    }\n    else\n    {\n        camx = static_cast<pinhole_camera>(cam);\n    }\n\n    if (rt.mode() == host_device_rt::CPU)\n    {\n        if (host_top_level_bvh.num_primitives() > 0)\n        {\n            aligned_vector<generic_light_t> temp_lights;\n            for (auto pl : point_lights)\n            {\n                temp_lights.push_back(pl);\n            }\n\n            if (tex_format == renderer::UV)\n            {\n                render_instances_cpp(\n                        host_top_level_bvh,\n                        mod.geometric_normals,\n                        mod.shading_normals,\n                        mod.tex_coords,\n                        generic_materials,\n                        mod.textures,\n                        temp_lights,\n                        bounces,\n                        epsilon,\n                        vec4(background_color(), 1.0f),\n                        amb,\n                        rt,\n                        host_sched,\n                        camx,\n                        frame_num,\n                        algo,\n                        ssaa_samples\n                        );\n            }\n#if VSNRAY_COMMON_HAVE_PTEX\n            else if (tex_format == renderer::Ptex)\n            {\n                render_instances_ptex_cpp(\n                        host_top_level_bvh,\n                        mod.geometric_normals,\n                        mod.shading_normals,\n                        ptex_tex_coords,\n                        generic_materials,\n                        ptex_textures,\n                        temp_lights,\n                        bounces,\n                        epsilon,\n                        vec4(background_color(), 1.0f),\n                        amb,\n                        rt,\n                        host_sched,\n                        camx,\n                        frame_num,\n                        algo,\n                        ssaa_samples\n                        );\n            }\n#endif\n        }\n        else if (area_lights.size() > 0 && algo == Pathtracing)\n        {\n            render_generic_material_cpp(\n                    host_bvhs[0],\n                    mod.geometric_normals,\n                    mod.shading_normals,\n                    mod.tex_coords,\n                    generic_materials,\n                    mod.textures,\n                    area_lights,\n                    bounces,\n                    epsilon,\n                    vec4(background_color(), 1.0f),\n                    amb,\n                    rt,\n                    host_sched,\n                    camx,\n                    frame_num,\n                    algo,\n                    ssaa_samples\n                    );\n        }\n        else\n        {\n            render_plastic_cpp(\n                    host_bvhs[0],\n                    mod.geometric_normals,\n                    mod.shading_normals,\n                    mod.tex_coords,\n                    plastic_materials,\n                    mod.textures,\n                    point_lights,\n                    bounces,\n                    epsilon,\n                    vec4(background_color(), 1.0f),\n                    amb,\n                    rt,\n                    host_sched,\n                    camx,\n                    frame_num,\n                    algo,\n                    ssaa_samples\n                    );\n        }\n    }\n#ifdef __CUDACC__\n    else if (rt.mode() == host_device_rt::GPU)\n    {\n        if (area_lights.size() > 0 && algo == Pathtracing)\n        {\n            render_generic_material_cu(\n                    device_bvh,\n                    device_geometric_normals,\n                    device_shading_normals,\n                    device_tex_coords,\n                    device_generic_materials,\n                    device_textures,\n                    area_lights,\n                    bounces,\n                    epsilon,\n                    vec4(background_color(), 1.0f),\n                    amb,\n                    rt,\n                    device_sched,\n                    camx,\n                    frame_num,\n                    algo,\n                    ssaa_samples\n                    );\n        }\n        else\n        {\n            render_plastic_cu(\n                    device_bvh,\n                    device_geometric_normals,\n                    device_shading_normals,\n                    device_tex_coords,\n                    device_plastic_materials,\n                    device_textures,\n                    point_lights,\n                    bounces,\n                    epsilon,\n                    vec4(background_color(), 1.0f),\n                    amb,\n                    rt,\n                    device_sched,\n                    camx,\n                    frame_num,\n                    algo,\n                    ssaa_samples\n                    );\n        }\n    }\n#endif\n\n    last_frame_time = counter.register_frame();\n\n#if VSNRAY_COMMON_HAVE_PTEX\n//  if (ptex_textures.size() > 0)\n//  {\n//      PtexCache::Stats stats;\n//      ptex_textures[0].cache.get()->get()->getStats(stats);\n//      std::cout << \"Mem used:        \" << stats.memUsed << '\\n';\n//      std::cout << \"Peak mem used:   \" << stats.peakMemUsed << '\\n';\n//      std::cout << \"Files open:      \" << stats.filesOpen << '\\n';\n//      std::cout << \"Peak files open: \" << stats.peakFilesOpen << '\\n';\n//      std::cout << \"Files accessed:  \" << stats.filesAccessed << '\\n';\n//      std::cout << \"File reopens:    \" << stats.fileReopens << '\\n';\n//      std::cout << \"Block reads:     \" << stats.blockReads << '\\n';\n//  }\n#endif\n}\n\nvoid renderer::on_close()\n{\n    outlines.destroy();\n}\n\nvoid renderer::on_display()\n{\n    if (render_async)\n    {\n        if (!render_future.valid() || render_future.wait_for(std::chrono::seconds(0)) == std::future_status::ready)\n        {\n            render_future = std::async(\n                    std::launch::async,\n                    [this]()\n                    {\n                        render_impl();\n\n                        std::unique_lock<std::mutex> l(display_mutex);\n                        rt.swap_buffers();\n                    }\n                    );\n        }\n\n        if (rt.width() == width() && rt.height() == height())\n        {\n            std::unique_lock<std::mutex> l(display_mutex);\n            rt.display_color_buffer();\n        }\n    }\n    else\n    {\n        render_impl();\n\n        rt.swap_buffers();\n\n        rt.display_color_buffer();\n    }\n\n\n    // OpenGL overlay rendering\n\n    if (show_hud)\n    {\n        render_hud();\n    }\n\n    if (show_bvh)\n    {\n        outlines.frame(cam.get_view_matrix(), cam.get_proj_matrix());\n    }\n}\n\nvoid renderer::on_key_press(key_event const& event)\n{\n    static const std::string camera_file_base = \"visionaray-camera\";\n    static const std::string camera_file_suffix = \".txt\";\n\n    switch (event.key())\n    {\n    case '1':\n        std::cout << \"Switching algorithm: simple\\n\";\n        rt.set_double_buffering(true);\n        algo = Simple;\n        counter.reset();\n        clear_frame();\n        break;\n\n    case '2':\n        std::cout << \"Switching algorithm: whitted\\n\";\n        rt.set_double_buffering(true);\n        algo = Whitted;\n        counter.reset();\n        clear_frame();\n        break;\n\n    case '3':\n        std::cout << \"Switching algorithm: path tracing\\n\";\n        if (render_future.valid())\n        {\n            render_future.wait();\n        }\n        // Double buffering does not work in case of pathtracing\n        // because destination and source buffers need to be the same\n        rt.set_double_buffering(false);\n        algo = Pathtracing;\n        counter.reset();\n        clear_frame();\n        break;\n\n    case 'b':\n        show_bvh = !show_bvh;\n\n        if (show_bvh)\n        {\n            if (host_top_level_bvh.num_nodes() > 0)\n            {\n                outlines.init(host_top_level_bvh);\n            }\n            else\n            {\n                outlines.init(host_bvhs[0]);\n            }\n        }\n\n        break;\n\n    case 'c':\n        if (rt.color_space() == host_device_rt::RGB)\n        {\n            rt.color_space() = host_device_rt::SRGB;\n        }\n        else\n        {\n            rt.color_space() = host_device_rt::RGB;\n        }\n        break;\n\n     case 'h':\n        show_hud = !show_hud;\n        break;\n\n    case 'l':\n        use_headlight = !use_headlight;\n        counter.reset();\n        clear_frame();\n        break;\n\n   case 'm':\n#ifdef __CUDACC__\n        if (rt.mode() == host_device_rt::CPU)\n        {\n            rt.mode() = host_device_rt::GPU;\n        }\n        else\n        {\n            rt.mode() = host_device_rt::CPU;\n        }\n        counter.reset();\n        clear_frame();\n#endif\n        break;\n\n    case 's':\n        ssaa_samples *= 2;\n        if (ssaa_samples > 8)\n        {\n            ssaa_samples = 1;\n        }\n\n        if (algo != Pathtracing)\n        {\n            counter.reset();\n            clear_frame();\n        }\n        break;\n\n    case 'u':\n        {\n            int inc = 0;\n            std::string inc_str = \"\";\n\n            std::string filename = camera_file_base + inc_str + camera_file_suffix;\n\n            while (boost::filesystem::exists(filename))\n            {\n                ++inc;\n                inc_str = std::to_string(inc);\n\n                while (inc_str.length() < 4)\n                {\n                    inc_str = std::string(\"0\") + inc_str;\n                }\n\n                inc_str = std::string(\"-\") + inc_str;\n\n                filename = camera_file_base + inc_str + camera_file_suffix;\n            }\n\n            std::ofstream file(filename);\n            if (file.good())\n            {\n                std::cout << \"Storing camera to file: \" << filename << '\\n';\n                file << cam;\n            }\n        }\n        break;\n\n    case 'v':\n        {\n            std::string filename = camera_file_base + camera_file_suffix;\n\n            load_camera(filename);\n        }\n        break;\n\n    default:\n        break;\n    }\n\n    viewer_type::on_key_press(event);\n}\n\nvoid renderer::on_mouse_move(visionaray::mouse_event const& event)\n{\n    if (event.buttons() != mouse::NoButton)\n    {\n        clear_frame();\n    }\n\n    mouse_pos = event.pos();\n    viewer_type::on_mouse_move(event);\n}\n\nvoid renderer::on_resize(int w, int h)\n{\n    if (render_future.valid() && algo != Pathtracing)\n    {\n        render_future.wait();\n    }\n\n    cam.set_viewport(0, 0, w, h);\n    float fovy = cam.fovy();\n    float aspect = w / static_cast<float>(h);\n    float z_near = cam.z_near();\n    float z_far = cam.z_far();\n    cam.perspective(fovy, aspect, z_near, z_far);\n    rt.resize(w, h);\n    clear_frame();\n    viewer_type::on_resize(w, h);\n}\n\nint main(int argc, char** argv)\n{\n    renderer rend;\n\n#ifdef __CUDACC__\n    if (rend.rt.direct_rendering() && cuda::init_gl_interop() != cudaSuccess)\n    {\n        std::cerr << \"Cannot initialize CUDA OpenGL interop\\n\";\n        return EXIT_FAILURE;\n    }\n#endif\n\n    try\n    {\n        rend.init(argc, argv);\n    }\n    catch (std::exception const& e)\n    {\n        std::cerr << e.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n\n\tif (rend.filenames.empty())\n\t{\n\t\tstd::cout << rend.cmd_line_inst().help(argv[0]) << \"\\n\";\n\t\treturn EXIT_FAILURE;\n\t}\n\n    if (rend.algo == Pathtracing)\n    {\n        // Double buffering does not work in case of pathtracing\n        // because destination and source buffers need to be the same\n        rend.rt.set_double_buffering(false);\n    }\n\n    rend.gl_debug_callback.activate();\n\n    // Load the scene\n    std::cout << \"Loading model...\\n\";\n\n    std::vector<std::string> filenames;\n    std::copy(rend.filenames.begin(), rend.filenames.end(), std::back_inserter(filenames));\n\n    if (!rend.mod.load(filenames))\n    {\n        std::cerr << \"Failed loading model\\n\";\n        return EXIT_FAILURE;\n    }\n\n    rend.build_bvhs();\n\n    // Generate a list with plastic materials\n    rend.plastic_materials = make_materials(\n            plastic<float>{},\n            rend.mod.materials\n            );\n\n    // Generate another list with generic materials\n    rend.generic_materials = make_materials(\n            generic_material_t{},\n            rend.mod.materials,\n            [](aligned_vector<generic_material_t>& cont, model::material_type mat)\n            {\n                // Add emissive material if emissive component > 0\n                if (length(mat.ce) > 0.0f)\n                {\n                    emissive<float> em;\n                    em.ce() = from_rgb(mat.ce);\n                    em.ls() = 1.0f;\n                    cont.emplace_back(em);\n                }\n                else if (mat.illum == 1)\n                {\n                    matte<float> ma;\n                    ma.ca() = from_rgb(mat.ca);\n                    ma.cd() = from_rgb(mat.cd);\n                    ma.ka() = 1.0f;\n                    ma.kd() = 1.0f;\n                    cont.emplace_back(ma);\n                }\n                else if (mat.illum == 3)\n                {\n                    mirror<float> mi;\n                    mi.cr() = from_rgb(mat.cs);\n                    mi.kr() = 1.0f;\n                    mi.ior() = spectrum<float>(0.0f);\n                    mi.absorption() = spectrum<float>(0.0f);\n                    cont.emplace_back(mi);\n                }\n                else if (mat.illum == 4 && mat.transmission > 0.0f)\n                {\n                    glass<float> gl;\n                    gl.ct() = from_rgb(mat.cd);\n                    gl.kt() = 1.0f;\n                    gl.cr() = from_rgb(mat.cs);\n                    gl.kr() = 1.0f;\n                    gl.ior() = from_rgb(mat.ior);\n                    cont.push_back(gl);\n                }\n                else\n                {\n                    plastic<float> pl;\n                    pl.ca() = from_rgb(mat.ca);\n                    pl.cd() = from_rgb(mat.cd);\n                    pl.cs() = from_rgb(mat.cs);\n                    pl.ka() = 1.0f;\n                    pl.kd() = 1.0f;\n                    pl.ks() = 1.0f;\n                    pl.specular_exp() = mat.specular_exp;\n                    cont.emplace_back(pl);\n                }\n            }\n            );\n\n\n    // Loop over all triangles, check if their\n    // material is emissive, and if so, build\n    // BVHs to create area lights from.\n\n    struct range\n    {\n        std::size_t begin;\n        std::size_t end;\n        unsigned    geom_id;\n    };\n\n    std::vector<range> ranges;\n\n    for (std::size_t i = 0; i < rend.mod.primitives.size(); ++i)\n    {\n        auto pi = rend.mod.primitives[i];\n        if (rend.generic_materials[pi.geom_id].as<emissive<float>>() != nullptr)\n        {\n            range r;\n            r.begin = i;\n\n            std::size_t j = i + 1;\n            for (;j < rend.mod.primitives.size(); ++j)\n            {\n                auto pii = rend.mod.primitives[j];\n                if (rend.generic_materials[pii.geom_id].as<emissive<float>>() == nullptr\n                                || pii.geom_id != pi.geom_id)\n                {\n                    break;\n                }\n            }\n\n            r.end = j;\n            r.geom_id = pi.geom_id;\n            ranges.push_back(r);\n\n            i = r.end - 1;\n        }\n    }\n\n    // Build vector with area light sources\n    for (auto r : ranges)\n    {\n        for (std::size_t i = r.begin; i != r.end; ++i)\n        {\n            area_light<float, basic_triangle<3, float>> light(rend.mod.primitives[i]);\n            auto mat = *rend.generic_materials[r.geom_id].as<emissive<float>>();\n            light.set_cl(to_rgb(mat.ce()));\n            light.set_kl(mat.ls());\n            rend.area_lights.push_back(light);\n        }\n    }\n\n    std::cout << \"Ready\\n\";\n\n#ifdef __CUDACC__\n    // Copy data to GPU\n    try\n    {\n        rend.device_bvh = renderer::device_bvh_type(rend.host_bvhs[0]);\n        rend.device_geometric_normals = rend.mod.geometric_normals;\n        rend.device_shading_normals = rend.mod.shading_normals;\n        rend.device_tex_coords = rend.mod.tex_coords;\n        rend.device_plastic_materials = rend.plastic_materials;\n        rend.device_generic_materials = rend.generic_materials;\n\n\n        // Copy textures and texture references to the GPU\n\n        rend.device_textures.resize(rend.mod.textures.size());\n\n        for (auto const& pair_host_tex : rend.mod.texture_map)\n        {\n            auto const& host_tex = pair_host_tex.second;\n            renderer::device_tex_type device_tex(pair_host_tex.second);\n            auto const& p = rend.device_texture_map.emplace(pair_host_tex.first, std::move(device_tex));\n\n            assert(p.second /* inserted */);\n\n            auto it = p.first;\n\n            // Texture references ensure that we don't allocate storage\n            // for the same texture map more than once.\n            // By checking if the pointer in the ref contains the\n            // address of the first texel of the map, we can identify\n            // which texture_ref references which texture and recreate\n            // that relation on the GPU.\n            for (size_t i = 0; i < rend.mod.textures.size(); ++i)\n            {\n                if (rend.mod.textures[i].data() == host_tex.data())\n                {\n                    rend.device_textures[i] = renderer::device_tex_ref_type(it->second);\n                }\n            }\n        }\n\n        // Place some dummy textures where geometry has no texture\n        for (size_t i = 0; i < rend.mod.textures.size(); ++i)\n        {\n            if (rend.mod.textures[i].width() == 0 || rend.mod.textures[i].height() == 0)\n            {\n                vector<4, unorm<8>>* dummy = nullptr;\n                renderer::device_tex_type device_tex(dummy, 0, 0, Clamp, Nearest);\n\n                // Try to insert the dummy texture into the\n                // device texture map...\n                auto p = rend.device_texture_map.emplace(\"\", std::move(device_tex));\n\n                // ... but maybe a dummy texture was already\n                // inserted, then just find that\n                if (!p.second)\n                {\n                    auto it = rend.device_texture_map.find(\"\");\n                    rend.device_textures[i] = renderer::device_tex_ref_type(it->second);\n\n                }\n                else\n                {\n                    auto it = p.first;\n                    rend.device_textures[i] = renderer::device_tex_ref_type(it->second);\n                }\n            }\n        }\n    }\n    catch (std::bad_alloc const&)\n    {\n        std::cerr << \"GPU memory allocation failed\" << std::endl;\n        rend.device_bvh = renderer::device_bvh_type();\n        rend.device_geometric_normals.clear();\n        rend.device_geometric_normals.shrink_to_fit();\n        rend.device_shading_normals.clear();\n        rend.device_shading_normals.shrink_to_fit();\n        rend.device_tex_coords.clear();\n        rend.device_tex_coords.shrink_to_fit();\n        rend.device_plastic_materials.clear();\n        rend.device_plastic_materials.shrink_to_fit();\n        rend.device_generic_materials.clear();\n        rend.device_generic_materials.shrink_to_fit();\n        rend.device_texture_map.clear();\n        rend.device_textures.clear();\n        rend.device_textures.shrink_to_fit();\n    }\n#endif\n\n    float aspect = rend.width() / static_cast<float>(rend.height());\n\n    rend.cam.perspective(45.0f * constants::degrees_to_radians<float>(), aspect, 0.001f, 1000.0f);\n    rend.cam.set_lens_radius(0.1f);\n    rend.cam.set_focal_distance(10.0f);\n\n    // Load camera from file or set view-all\n    std::ifstream file(rend.initial_camera);\n    if (file.good())\n    {\n        file >> rend.cam;\n    }\n    else\n    {\n        rend.cam.view_all( rend.mod.bbox );\n    }\n\n    rend.add_manipulator( std::make_shared<arcball_manipulator>(rend.cam, mouse::Left) );\n    rend.add_manipulator( std::make_shared<pan_manipulator>(rend.cam, mouse::Middle) );\n    // Additional \"Alt + LMB\" pan manipulator for setups w/o middle mouse button\n    rend.add_manipulator( std::make_shared<pan_manipulator>(rend.cam, mouse::Left, keyboard::Alt) );\n    rend.add_manipulator( std::make_shared<zoom_manipulator>(rend.cam, mouse::Right) );\n\n    rend.event_loop();\n\n}\n", "meta": {"hexsha": "86266cb90b02aca67d87876f713bd3e58f90616f", "size": 50374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/viewer/viewer.cpp", "max_stars_repo_name": "stoeckley/visionaray", "max_stars_repo_head_hexsha": "226d6cdf870f658d0fd0d1e1e292a8324d65ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-23T19:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-23T19:58:11.000Z", "max_issues_repo_path": "src/viewer/viewer.cpp", "max_issues_repo_name": "stoeckley/visionaray", "max_issues_repo_head_hexsha": "226d6cdf870f658d0fd0d1e1e292a8324d65ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/viewer/viewer.cpp", "max_forks_repo_name": "stoeckley/visionaray", "max_forks_repo_head_hexsha": "226d6cdf870f658d0fd0d1e1e292a8324d65ff4d", "max_forks_repo_licenses": ["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.4757167934, "max_line_length": 115, "alphanum_fraction": 0.5064715925, "num_tokens": 11165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864514886966624, "lm_q2_score": 0.031143829860339423, "lm_q1q2_score": 0.010858145198029594}}
{"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// clang-format off\n\n#include \"PyImathConfigInternal.h\"\n\n#include \"PyImathPlane.h\"\n#include \"PyImathDecorators.h\"\n#include \"PyImathExport.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include \"PyImath.h\"\n#include \"PyImathVec.h\"\n#include \"PyImathMathExc.h\"\n\nnamespace PyImath{\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\n\ntemplate <class T> struct PlaneName {static const char *value;};\ntemplate <> const char *PlaneName<float>::value = \"Plane3f\";\ntemplate <> const char *PlaneName<double>::value = \"Plane3d\";\n\ntemplate <class T>\nstatic Plane3<T> *Plane3_construct_default()\n{\n    Vec3<T> normal(T (1), T (0), T (0));\n    return new Plane3<T>(normal, T (0));\n}\n\ntemplate <class T>\nstatic Plane3<T> *Plane3_plane_construct(const object &planeObj)\n{\n    MATH_EXC_ON;\n    extract < Plane3<float> > ef (planeObj);\n    extract < Plane3<double> > ed (planeObj);\n\n    Plane3<T> *p = 0;\n\n    if (ef.check())\n    {\n        Plane3<float> efp = ef();\n        p = new Plane3<T>;\n        p->normal = efp.normal;\n        p->distance = efp.distance;\n    }\n\n    else if (ed.check())\n    {\n        Plane3<double> edp = ed();\n        p = new Plane3<T>;\n        p->normal = edp.normal;\n        p->distance = edp.distance;\n    }\n\n    else\n    {\n      throw std::invalid_argument (\"invalid parameter passed to Plane constructor\");\n    }\n    \n    return p;\n}\n\ntemplate <class T>\nstatic Plane3<T> *Plane3_tuple_constructor1(const tuple &t, T distance)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> normal;\n        normal.x = extract<T>(t[0]);\n        normal.y = extract<T>(t[1]);\n        normal.z = extract<T>(t[2]);\n        \n        return new Plane3<T>(normal, distance);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuple of length 3\");\n}\n\ntemplate <class T>\nstatic Plane3<T> *Plane3_tuple_constructor2(const tuple &t0, const tuple &t1)\n{\n    MATH_EXC_ON;\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> point, normal;\n        point.x = extract<T>(t0[0]);\n        point.y = extract<T>(t0[1]);\n        point.z = extract<T>(t0[2]);\n        \n        normal.x = extract<T>(t1[0]);\n        normal.y = extract<T>(t1[1]);\n        normal.z = extract<T>(t1[2]);\n        \n        return new Plane3<T>(point, normal);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuples of length 3\");\n}\n\ntemplate <class T>\nstatic Plane3<T> *Plane3_tuple_constructor3(const tuple &t0, const tuple &t1, const tuple &t2)\n{\n    MATH_EXC_ON;\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3 && t2.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> point0, point1, point2;\n        point0.x = extract<T>(t0[0]);\n        point0.y = extract<T>(t0[1]);\n        point0.z = extract<T>(t0[2]);\n        \n        point1.x = extract<T>(t1[0]);\n        point1.y = extract<T>(t1[1]);\n        point1.z = extract<T>(t1[2]);\n\n        point2.x = extract<T>(t2[0]);\n        point2.y = extract<T>(t2[1]);\n        point2.z = extract<T>(t2[2]); \n        \n        return new Plane3<T>(point0, point1, point2);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuple of length 3\");\n}\n\ntemplate <class T>\nstatic Plane3<T>\nmul (const Plane3<T> &plane, const Matrix44<T> &M)\n{\n    MATH_EXC_ON;\n    return plane * M;\n}\n\ntemplate <class T>\nstatic void\nset1 (Plane3<T> &plane, const Vec3<T> &v, T t)\n{\n    MATH_EXC_ON;\n    plane.set (v, t);\n}\n\ntemplate <class T>\nstatic void\nset2 (Plane3<T> &plane, const Vec3<T> &v1, const Vec3<T> &v2)\n{\n    MATH_EXC_ON;\n    plane.set (v1, v2);\n}\n\ntemplate <class T>\nstatic void\nset3 (Plane3<T> &plane, const Vec3<T> &v1, const Vec3<T> &v2, const Vec3<T> &v3)\n{\n    MATH_EXC_ON;\n    plane.set (v1, v2, v3);\n}\n\ntemplate <class T>\nstatic std::string Plane3_str(const Plane3<T> &plane)\n{\n    std::stringstream stream;\n\n    PyObject *normalObj = V3<T>::wrap (plane.normal);\n    PyObject *normalReprObj = PyObject_Repr (normalObj);\n#if PY_MAJOR_VERSION > 2\n    std::string normalReprStr = PyUnicode_AsUTF8 (normalReprObj);\n#else\n    std::string normalReprStr = PyString_AsString (normalReprObj);\n#endif\n    Py_DECREF (normalReprObj);\n    Py_DECREF (normalObj);\n\n    stream << PlaneName<T>::value << \"(\" << normalReprStr << \", \" \n           << plane.distance << \")\";\n    return stream.str();\n}\n\n// Non-specialized repr is same as str\ntemplate <class T>\nstatic std::string Plane3_repr(const Plane3<T> &plane)\n{\n    return Plane3_str(plane);\n}\n\n// Specialization for float to full precision\ntemplate <>\nstd::string Plane3_repr(const Plane3<float> &plane)\n{\n    PyObject *normalObj = V3<float>::wrap (plane.normal);\n    PyObject *normalReprObj = PyObject_Repr (normalObj);\n#if PY_MAJOR_VERSION > 2\n    std::string normalReprStr = PyUnicode_AsUTF8 (normalReprObj);\n#else\n    std::string normalReprStr = PyString_AsString (normalReprObj);\n#endif\n    Py_DECREF (normalReprObj);\n    Py_DECREF (normalObj);\n\n    return (boost::format(\"%s(%s, %.9g)\")\n                        % PlaneName<float>::value\n                        % normalReprStr.c_str()\n                        % plane.distance).str();\n}\n\n// Specialization for double to full precision\ntemplate <>\nstd::string Plane3_repr(const Plane3<double> &plane)\n{\n    PyObject *normalObj = V3<double>::wrap (plane.normal);\n    PyObject *normalReprObj = PyObject_Repr (normalObj);\n#if PY_MAJOR_VERSION > 2\n    std::string normalReprStr = PyUnicode_AsUTF8 (normalReprObj);\n#else\n    std::string normalReprStr = PyString_AsString (normalReprObj);\n#endif\n    Py_DECREF (normalReprObj);\n    Py_DECREF (normalObj);\n\n    return (boost::format(\"%s(%s, %.17g)\")\n                        % PlaneName<double>::value\n                        % normalReprStr.c_str()\n                        % plane.distance).str();\n}\n\n\ntemplate <class T>\nstatic T\ndistance(Plane3<T> &plane)\n{\n    return plane.distance;\n}\n\ntemplate <class T>\nstatic Vec3<T>\nnormal(Plane3<T> &plane)\n{\n    return plane.normal;\n}\n\ntemplate <class T>\nstatic void\nsetNormal(Plane3<T> &plane, const Vec3<T> &normal)\n{\n    MATH_EXC_ON;\n    plane.normal = normal.normalized();\n}\n\ntemplate <class T>\nstatic void\nsetDistance(Plane3<T> &plane, const T &distance)\n{\n    plane.distance = distance;\n}\n\ntemplate <class T, class S>\nstatic object intersectT(const Plane3<T> &plane, const Line3<S> &line)\n{\n    MATH_EXC_ON;\n    T param;\n    Line3<T> l;\n    l.pos = line.pos;\n    l.dir = line.dir;\n\n    if(plane.intersectT(l, param))\n        return object(param);\n    \n    return object();\n}\n\ntemplate <class T>\nstatic bool\nintersect2(const Plane3<T> &plane, const Line3<T> &line, Vec3<T> &intersection)\n{\n    MATH_EXC_ON;\n    return plane.intersect(line, intersection);\n}\n\ntemplate <class T, class S>\nstatic object\nintersect1(const Plane3<T> &plane, const Line3<S> &line)\n{\n    MATH_EXC_ON;\n    Vec3<T> intersection;\n    Line3<T> l;\n    l.pos = line.pos;\n    l.dir = line.dir;\n    if(plane.intersect(l, intersection))\n        return object(intersection);\n    \n    return object();\n    \n}\n\ntemplate <class T>\nstatic void\nsetTuple1(Plane3<T> &plane, const tuple &t, T distance)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> normal;\n        normal.x = extract<T>(t[0]);\n        normal.y = extract<T>(t[1]);\n        normal.z = extract<T>(t[2]);\n        \n        plane.set(normal, distance);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuple of length 3\");    \n}\n\ntemplate <class T>\nstatic void\nsetTuple2(Plane3<T> &plane, const tuple &t0, const tuple &t1)\n{\n    MATH_EXC_ON;\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> point, normal;\n        point.x = extract<T>(t0[0]);\n        point.y = extract<T>(t0[1]);\n        point.z = extract<T>(t0[2]);\n        \n        normal.x = extract<T>(t1[0]);\n        normal.y = extract<T>(t1[1]);\n        normal.z = extract<T>(t1[2]);\n        \n        plane.set(point, normal);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuples of length 3\");\n}\n\ntemplate <class T>\nstatic void\nsetTuple3(Plane3<T> &plane, const tuple &t0, const tuple &t1, const tuple &t2)\n{\n    MATH_EXC_ON;\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3 && t2.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> point0, point1, point2;\n        point0.x = extract<T>(t0[0]);\n        point0.y = extract<T>(t0[1]);\n        point0.z = extract<T>(t0[2]);\n        \n        point1.x = extract<T>(t1[0]);\n        point1.y = extract<T>(t1[1]);\n        point1.z = extract<T>(t1[2]);\n\n        point2.x = extract<T>(t2[0]);\n        point2.y = extract<T>(t2[1]);\n        point2.z = extract<T>(t2[2]); \n        \n        plane.set(point0, point1, point2);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuple of length 3\");\n}\n\ntemplate <class T>\nstatic Vec3<T>\nreflectPoint(Plane3<T> &plane, const Vec3<T> &p)\n{\n    MATH_EXC_ON;\n    return plane.reflectPoint(p);\n}\n\ntemplate <class T>\nstatic Vec3<T>\nreflectPointTuple(Plane3<T> &plane, const tuple &t)\n{\n    MATH_EXC_ON;\n    Vec3<T> point;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        point.x = extract<T>(t[0]);\n        point.y = extract<T>(t[1]);\n        point.z = extract<T>(t[2]); \n        \n        return plane.reflectPoint(point);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuple of length 3\");\n}\n\ntemplate <class T>\nstatic T\ndistanceTo(Plane3<T> &plane, const Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return plane.distanceTo(v);\n}\n\ntemplate <class T>\nstatic T\ndistanceToTuple(Plane3<T> &plane, const tuple &t)\n{\n    MATH_EXC_ON;\n    Vec3<T> point;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        point.x = extract<T>(t[0]);\n        point.y = extract<T>(t[1]);\n        point.z = extract<T>(t[2]); \n        \n        return plane.distanceTo(point);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuple of length 3\");    \n}\n\ntemplate <class T>\nstatic Vec3<T>\nreflectVector(Plane3<T> &plane, const Vec3<T> &v)\n{\n    MATH_EXC_ON;\n    return plane.reflectVector(v);\n}\n\ntemplate <class T>\nstatic Vec3<T>\nreflectVectorTuple(Plane3<T> &plane, const tuple &t)\n{\n    MATH_EXC_ON;\n    Vec3<T> point;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        point.x = extract<T>(t[0]);\n        point.y = extract<T>(t[1]);\n        point.z = extract<T>(t[2]); \n        \n        return plane.reflectVector(point);\n    }\n    else\n        throw std::domain_error (\"Plane3 expects tuple of length 3\");\n}\n\ntemplate <class T>\nstatic bool\nequal(const Plane3<T> &p1, const Plane3<T> &p2)\n{\n    if(p1.normal == p2.normal && p1.distance == p2.distance)\n        return true;\n    else\n        return false;\n}\n\ntemplate <class T>\nstatic bool\nnotequal(const Plane3<T> &p1, const Plane3<T> &p2)\n{\n    if(p1.normal != p2.normal || p1.distance != p2.distance)\n        return true;\n    else\n        return false;\n}\n\ntemplate <class T>\nstatic Plane3<T>\nnegate(const Plane3<T> &plane)\n{\n    MATH_EXC_ON;\n    Plane3<T> p;\n    p.set(-plane.normal, -plane.distance);\n    \n    return p;\n}\n\n\n\ntemplate <class T>\nclass_<Plane3<T> >\nregister_Plane()\n{\n    const char *name = PlaneName<T>::value;\n    \n    class_< Plane3<T> > plane_class(name);\n    plane_class\n        .def(\"__init__\",make_constructor(Plane3_construct_default<T>),\"initialize normal to  (1,0,0), distance to 0\")\n        .def(\"__init__\",make_constructor(Plane3_tuple_constructor1<T>))\n        .def(\"__init__\",make_constructor(Plane3_tuple_constructor2<T>))\n        .def(\"__init__\",make_constructor(Plane3_tuple_constructor3<T>))\n        .def(\"__init__\",make_constructor(Plane3_plane_construct<T>))\n        .def(init<const Vec3<T> &, T>(\"Plane3(normal, distance) construction\"))\n        .def(init<const Vec3<T> &, const Vec3<T> &>(\"Plane3(point, normal) construction\"))\n        .def(init<const Vec3<T> &, const Vec3<T> &, const Vec3<T> &>(\"Plane3(point1, point2, point3) construction\"))\n        .def(\"__eq__\", &equal<T>)\n        .def(\"__ne__\", &notequal<T>)\n        .def(\"__mul__\", &mul<T>)\n        .def(\"__neg__\", &negate<T>)\n        .def(\"__str__\", &Plane3_str<T>)\n        .def(\"__repr__\", &Plane3_repr<T>)\n        \n        .def_readwrite(\"normal\", &Plane3<T>::normal)\n        .def_readwrite(\"distance\", &Plane3<T>::distance)\n        \n        .def(\"normal\", &normal<T>, \"normal()\",\n             \"pl.normal() -- returns the normal of plane pl\")\n             \n        .def(\"distance\", &distance<T>, \"distance()\",\n        \t \"pl.distance() -- returns the signed distance\\n\"\n\t\t\t \"of plane pl from the coordinate origin\")\n        \n        .def(\"setNormal\", &setNormal<T>, \"setNormal()\",\n        \t \"pl.setNormal(n) -- sets the normal of plane\\n\"\n\t\t\t \"pl to n.normalized()\")\n             \n        .def(\"setDistance\", &setDistance<T>, \"setDistance()\",\n        \t \"pl.setDistance(d) -- sets the signed distance\\n\"\n\t\t\t \"of plane pl from the coordinate origin to d\")\n             \n        .def(\"set\", &set1<T>, \"set()\",\n        \t \"pl.set(n,d) -- sets the normal and the signed\\n\"\n\t\t\t \"   distance of plane pl to n and d\\n\"\n\t\t\t \"\\n\"\n\t\t\t \"pl.set(p,n) -- sets the normal of plane pl to\\n\"\n\t\t\t \"   n.normalized() and adjusts the distance of\\n\"\n\t\t\t \"   pl from the coordinate origin so that pl\\n\"\n\t\t\t \"   passes through point p\\n\"\n\t\t\t \"\\n\"\n\t\t\t \"pl.set(p1,p2,p3) -- sets the normal of plane pl\\n\"\n\t\t\t \"   to (p2-p1)%(p3-p1)).normalized(), and adjusts\\n\"\n\t\t\t \"   the distance of pl from the coordinate origin\\n\"\n\t\t\t \"   so that pl passes through points p1, p2 and p3\")\n             \n        .def(\"set\", &set2<T>, \"set()\")\n        .def(\"set\", &set3<T>, \"set()\")\n        \n        .def(\"set\", &setTuple1<T>, \"set()\")\n        .def(\"set\", &setTuple2<T>, \"set()\")\n        .def(\"set\", &setTuple3<T>, \"set()\")        \n        \n        .def(\"intersect\", &intersect2<T>,\n        \t \"pl.intersect(ln, pt) -- returns true if the line intersects\\n\"\n             \"the plane, false if it doesn't.  The point where plane\\n\"\n\t\t\t \"pl and line ln intersect is stored in pt\")\n             \n        .def(\"intersect\", &intersect1<T,float>,\n        \t \"pl.intersect(ln) -- returns the point where plane\\n\"\n\t\t\t \"pl and line ln intersect, or None if pl and ln do\\n\"\n\t\t\t \"not intersect\")\n        .def(\"intersect\", &intersect1<T,double>,\n        \t \"pl.intersect(ln) -- returns the point where plane\\n\"\n\t\t\t \"pl and line ln intersect, or None if pl and ln do\\n\"\n\t\t\t \"not intersect\")\n             \n        .def(\"intersectT\", &intersectT<T, float>,\n             \"pl.intersectT(ln) -- computes the intersection,\\n\"\n\t\t\t \"i, of plane pl and line ln, and returns t, so that\\n\"\n\t\t\t \"ln.pos() + t * ln.dir() == i.\\n\"\n\t\t\t \"If pl and ln do not intersect, pl.intersectT(ln)\\n\"\n\t\t\t \"returns None.\\n\") \n             \n        .def(\"intersectT\", &intersectT<T,double>)\n             \n        .def(\"distanceTo\", &distanceTo<T>, \"distanceTo()\",\n        \t \"pl.distanceTo(p) -- returns the signed distance\\n\"\n\t\t\t \"between plane pl and point p (positive if p is\\n\"\n\t\t\t \"on the side of pl where the pl's normal points)\\n\")\n        \n        .def(\"distanceTo\", &distanceToTuple<T>)\n             \n        .def(\"reflectPoint\", &reflectPoint<T>, \"reflectPoint()\",\n        \t \"pl.reflectPoint(p) -- returns the image,\\n\"\n\t\t\t \"q, of point p after reflection on plane pl:\\n\"\n\t\t\t \"the distance between p and q is twice the\\n\"\n\t\t\t \"distance between p and pl, and the line from\\n\"\n\t\t\t \"p to q is parallel to pl's normal.\")\n             \n        .def(\"reflectPoint\", &reflectPointTuple<T>)\n             \n        .def(\"reflectVector\", &reflectVector<T>, \"reflectVector()\",\n        \t \"pl.reflectVector(v) -- returns the direction\\n\"\n\t\t\t \"of a ray with direction v after reflection on\\n\"\n\t\t\t \"plane pl\")\n        .def(\"reflectVector\", &reflectVectorTuple<T>)\n        \n        ;\n\n    decoratecopy(plane_class);\n\n    return plane_class;\n}\n\ntemplate PYIMATH_EXPORT class_<Plane3<float> > register_Plane<float>();\ntemplate PYIMATH_EXPORT class_<Plane3<double> > register_Plane<double>();\n\n} //namespace PyIMath\n", "meta": {"hexsha": "f2128a7e9e98986f800916ae48e807589b766f28", "size": 17683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/PyImath/PyImathPlane.cpp", "max_stars_repo_name": "methodstudios/Imath", "max_stars_repo_head_hexsha": "64810ce8ca9d980f1b397d895d20ad8d284f68ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-10T16:32:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T16:32:43.000Z", "max_issues_repo_path": "src/python/PyImath/PyImathPlane.cpp", "max_issues_repo_name": "oxt3479/Imath", "max_issues_repo_head_hexsha": "39c31ca077ab76a854c70f0d6810fb36eed37d73", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python/PyImath/PyImathPlane.cpp", "max_forks_repo_name": "oxt3479/Imath", "max_forks_repo_head_hexsha": "39c31ca077ab76a854c70f0d6810fb36eed37d73", "max_forks_repo_licenses": ["BSD-3-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.3381410256, "max_line_length": 117, "alphanum_fraction": 0.6038568116, "num_tokens": 4855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339457, "lm_q2_score": 0.03114382896108738, "lm_q1q2_score": 0.010858144462955568}}
{"text": "#include <indigox/algorithm/graph/connectivity.hpp>\n#include <indigox/algorithm/graph/paths.hpp>\n#include <indigox/classes/angle.hpp>\n#include <indigox/classes/atom.hpp>\n#include <indigox/classes/bond.hpp>\n#include <indigox/classes/dihedral.hpp>\n#include <indigox/classes/forcefield.hpp>\n#include <indigox/classes/molecule.hpp>\n#include <indigox/classes/molecule_impl.hpp>\n#include <indigox/classes/periodictable.hpp>\n#include <indigox/graph/condensed.hpp>\n#include <indigox/graph/molecular.hpp>\n#include <indigox/utils/serialise.hpp>\n\n#include <indigo-bondorder/indigo-bondorder.hpp>\n\n#include <algorithm>\n#include <array>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <boost/algorithm/string.hpp>\n#include <iomanip>\n\n#ifndef INDIGOX_DISABLE_SANITY_CHECKS\n#define _sanity_check_(x)                                                      \\\n  if (!x)                                                                      \\\n  throw std::runtime_error(                                                    \\\n      \"Attempting to access data from invalid molecule instance\")\n#else\n#define _sanity_check_(x)\n#endif\n\nnamespace indigox {\n\n  using Data = CalculatedData;\n\n  // =======================================================================\n  // == SERIALISATION ======================================================\n  // =======================================================================\n\n  template <typename Archive>\n  void Molecule::Impl::serialise(Archive &archive, const uint32_t) {\n    archive(INDIGOX_SERIAL_NVP(\"name\", name),\n            INDIGOX_SERIAL_NVP(\"next_uid\", next_unique_id),\n            INDIGOX_SERIAL_NVP(\"charge\", molecular_charge),\n            INDIGOX_SERIAL_NVP(\"atoms\", atoms),\n            INDIGOX_SERIAL_NVP(\"bonds\", bonds),\n            INDIGOX_SERIAL_NVP(\"angles\", angles),\n            INDIGOX_SERIAL_NVP(\"dihedrals\", dihedrals),\n            INDIGOX_SERIAL_NVP(\"forcefield\", forcefield),\n            INDIGOX_SERIAL_NVP(\"graph\", molecular_graph),\n            INDIGOX_SERIAL_NVP(\"formula\", cached_formula),\n            INDIGOX_SERIAL_NVP(\"calculated\", calculated_data),\n            INDIGOX_SERIAL_NVP(\"coordinates\", coordinates));\n  }\n\n  template <typename Archive>\n  void Molecule::serialise(Archive &archive, const uint32_t) {\n    archive(INDIGOX_SERIAL_NVP(\"data\", m_data));\n  }\n  INDIGOX_SERIALISE(Molecule);\n\n  // =======================================================================\n  // == OPERATORS ==========================================================\n  // =======================================================================\n\n  bool Molecule::operator==(const Molecule &mol) const {\n    _sanity_check_(*this);\n    _sanity_check_(mol);\n    return m_data == mol.m_data;\n  }\n\n  bool Molecule::operator<(const Molecule &mol) const {\n    _sanity_check_(*this);\n    _sanity_check_(mol);\n    return m_data < mol.m_data;\n  }\n\n  bool Molecule::operator>(const Molecule &mol) const {\n    _sanity_check_(*this);\n    _sanity_check_(mol);\n    return m_data > mol.m_data;\n  }\n\n  // =======================================================================\n  // == CONSTRUCTION =======================================================\n  // =======================================================================\n\n  Molecule::Impl::Impl(std::string n)\n      : name(n), next_unique_id(0), molecular_charge(0), calculated_data(0),\n        cached_formula(\"\") {}\n\n  Molecule::Molecule(const std::string& n) : m_data(std::make_shared<Impl>(n)) {\n    std::cout << \"Constructing new molecule \" << n << \".\" << std::endl;\n    m_data->molecular_graph = graph::MolecularGraph(*this);\n  }\n\n  // =======================================================================\n  // == STATE CHECKING =====================================================\n  // =======================================================================\n\n  int64_t Molecule::Impl::FindBond(const Atom &a, const Atom &b) const {\n    //    _sanity_check_(*this);\n    int64_t pos = 0;\n    for (const Bond &bnd : a.GetBonds()) {\n      if (bnd.GetAtoms()[0] == b || bnd.GetAtoms()[1] == b) break;\n      ++pos;\n    }\n    return pos == a.NumBonds() ? -1 : pos;\n  }\n\n  int64_t Molecule::Impl::FindAngle(const Atom &a, const Atom &b,\n                                    const Atom &c) const {\n    //    _sanity_check_(*this);\n    int64_t pos = 0;\n    for (const Angle &ang : b.GetAngles()) {\n      if ((ang.GetAtoms()[0] == a && ang.GetAtoms()[2] == c) ||\n          (ang.GetAtoms()[2] == a && ang.GetAtoms()[1] == c)) {\n        break;\n      }\n      ++pos;\n    }\n    return pos == b.NumAngles() ? -1 : pos;\n  }\n\n  int64_t Molecule::Impl::FindDihedral(const Atom &a, const Atom &b,\n                                       const Atom &c, const Atom &d) const {\n    //    _sanity_check_(*this);\n    int64_t pos = 0;\n    for (const Dihedral &dhd : a.GetDihedrals()) {\n      if ((dhd.GetAtoms()[0] == a && dhd.GetAtoms()[1] == b &&\n           dhd.GetAtoms()[2] == c && dhd.GetAtoms()[3] == d) ||\n          (dhd.GetAtoms()[3] == a && dhd.GetAtoms()[2] == b &&\n           dhd.GetAtoms()[1] == c && dhd.GetAtoms()[0] == d)) {\n        break;\n      }\n      ++pos;\n    }\n    return pos == a.NumDihedrals() ? -1 : pos;\n  }\n\n  bool Molecule::HasAtom(const Atom &atom) const {\n    _sanity_check_(*this);\n    return atom.GetMolecule() == *this;\n  }\n\n  bool Molecule::HasBond(const Bond &bond) const {\n    _sanity_check_(*this);\n    return bond.GetMolecule() == *this;\n  }\n\n  bool Molecule::HasBond(const Atom &a, const Atom &b) const {\n    _sanity_check_(*this);\n    return (HasAtom(a) && HasAtom(b)) ? (m_data->FindBond(a, b) != -1) : false;\n  }\n\n  bool Molecule::HasAngle(const Angle &angle) const {\n    _sanity_check_(*this);\n    return angle.GetMolecule() == *this;\n  }\n\n  bool Molecule::HasAngle(const Atom &a, const Atom &b, const Atom &c) {\n    _sanity_check_(*this);\n    PerceiveAngles();\n    return (HasAtom(a) && HasAtom(b) && HasAtom(c))\n               ? (m_data->FindAngle(a, b, c) != -1)\n               : false;\n  }\n\n  bool Molecule::HasDihedral(const Dihedral &dihedral) const {\n    _sanity_check_(*this);\n    return dihedral.GetMolecule() == *this;\n  }\n\n  bool Molecule::HasDihedral(const Atom &a, const Atom &b, const Atom &c,\n                             const Atom &d) {\n    _sanity_check_(*this);\n    PerceiveDihedrals();\n    return (HasAtom(a) && HasAtom(b) && HasAtom(c) && HasAtom(d))\n               ? (m_data->FindDihedral(a, b, c, d) != -1)\n               : false;\n  }\n\n  bool Molecule::HasForcefield() const {\n    _sanity_check_(*this);\n    return bool(m_data->forcefield);\n  }\n\n  int64_t Molecule::NumAtoms() const {\n    _sanity_check_(*this);\n    return static_cast<int64_t>(m_data->atoms.size());\n  }\n\n  int64_t Molecule::NumBonds() const {\n    _sanity_check_(*this);\n    return static_cast<int64_t>(m_data->bonds.size());\n  }\n\n  int64_t Molecule::NumAngles() {\n    _sanity_check_(*this);\n    PerceiveAngles();\n    return static_cast<int64_t>(m_data->angles.size());\n  }\n\n  int64_t Molecule::NumDihedrals() {\n    _sanity_check_(*this);\n    PerceiveDihedrals();\n    return static_cast<int64_t>(m_data->dihedrals.size());\n  }\n\n  void Molecule::ReserveAtoms(int64_t num) {\n    _sanity_check_(*this);\n    if (num > 0) { m_data->atoms.reserve(num); }\n  }\n\n  void Molecule::ReserveBonds(int64_t num) {\n    _sanity_check_(*this);\n    if (num > 0) { m_data->bonds.reserve(num); }\n  }\n\n  // =======================================================================\n  // == STATE GETTING ======================================================\n  // =======================================================================\n\n  Atom Molecule::GetAtom(uint32_t pos) const {\n    _sanity_check_(*this);\n    return (pos < NumAtoms()) ? m_data->atoms[pos] : Atom();\n  }\n\n  Atom Molecule::GetAtomID(int64_t id) const {\n    _sanity_check_(*this);\n    for (const Atom &atm : m_data->atoms) {\n      if (atm.GetID() == id) { return atm; }\n    }\n    return Atom();\n  }\n\n  Atom Molecule::GetAtomTag(int64_t tag) const {\n    _sanity_check_(*this);\n    for (const Atom &atm : m_data->atoms) {\n      if (atm.GetTag() == tag) { return atm; }\n    }\n    return Atom();\n  }\n\n  Bond Molecule::GetBond(uint32_t pos) const {\n    _sanity_check_(*this);\n    return (pos < NumBonds()) ? m_data->bonds[pos] : Bond();\n  }\n\n  Bond Molecule::GetBond(const Atom &a, const Atom &b) const {\n    _sanity_check_(*this);\n    int64_t pos = m_data->FindBond(a, b);\n    return (HasAtom(a) && pos != -1) ? a.GetBonds()[pos] : Bond();\n  }\n\n  Bond Molecule::GetBondID(int64_t id) const {\n    _sanity_check_(*this);\n    for (const Bond &bnd : m_data->bonds) {\n      if (bnd.GetID() == id) { return bnd; }\n    }\n    return Bond();\n  }\n\n  Bond Molecule::GetBondTag(int64_t tag) const {\n    _sanity_check_(*this);\n    for (const Bond &bnd : m_data->bonds) {\n      if (bnd.GetTag() == tag) { return bnd; }\n    }\n    return Bond();\n  }\n\n  Angle Molecule::GetAngle(uint32_t pos) {\n    _sanity_check_(*this);\n    PerceiveAngles();\n    return (pos < NumAngles()) ? m_data->angles[pos] : Angle();\n  }\n\n  Angle Molecule::GetAngle(const Atom &a, const Atom &b, const Atom &c) {\n    _sanity_check_(*this);\n    PerceiveAngles();\n    int64_t pos = m_data->FindAngle(a, b, c);\n    return (HasAtom(b) && pos != -1) ? b.GetAngles()[pos] : Angle();\n  }\n\n  Angle Molecule::GetAngleID(int64_t id) const {\n    _sanity_check_(*this);\n    for (const Angle &ang : m_data->angles) {\n      if (ang.GetID() == id) { return ang; }\n    }\n    return Angle();\n  }\n\n  Angle Molecule::GetAngleTag(int64_t tag) const {\n    _sanity_check_(*this);\n    for (const Angle &ang : m_data->angles) {\n      if (ang.GetTag() == tag) { return ang; }\n    }\n    return Angle();\n  }\n\n  Dihedral Molecule::GetDihedral(uint32_t pos) {\n    _sanity_check_(*this);\n    PerceiveDihedrals();\n    return (pos < NumDihedrals()) ? m_data->dihedrals[pos] : Dihedral();\n  }\n\n  Dihedral Molecule::GetDihedral(const Atom &a, const Atom &b, const Atom &c,\n                                 const Atom &d) {\n    _sanity_check_(*this);\n    PerceiveDihedrals();\n    int64_t pos = m_data->FindDihedral(a, b, c, d);\n    return (HasAtom(a) && pos != -1) ? a.GetDihedrals()[pos] : Dihedral();\n  }\n\n  Dihedral Molecule::GetDihedralID(int64_t id) const {\n    _sanity_check_(*this);\n    for (const Dihedral &ang : m_data->dihedrals) {\n      if (ang.GetID() == id) { return ang; }\n    }\n    return Dihedral();\n  }\n\n  Dihedral Molecule::GetDihedralTag(int64_t tag) const {\n    _sanity_check_(*this);\n    for (const Dihedral &ang : m_data->dihedrals) {\n      if (ang.GetTag() == tag) { return ang; }\n    }\n    return Dihedral();\n  }\n\n  Residue Molecule::GetResidueID(int32_t id) { return GetResidues()[id]; }\n\n  std::string Molecule::GetFormula() {\n    _sanity_check_(*this);\n    if (!m_data->Test(Data::Formula)) {\n      std::map<std::string, size_t> e_count;\n      for (const Atom &atm : m_data->atoms)\n        e_count[atm.GetElement().GetSymbol()]++;\n      std::stringstream ss;\n      if (e_count[\"C\"]) ss << \"C\";\n      if (e_count[\"C\"] > 1) ss << e_count[\"C\"];\n      if (e_count[\"H\"]) ss << \"H\";\n      if (e_count[\"H\"] > 1) ss << e_count[\"H\"];\n      for (auto &e : e_count) {\n        if (e.first != \"C\" && e.first != \"H\") {\n          ss << e.first;\n          if (e.second > 1) ss << e.second;\n        }\n      }\n      m_data->Set(Data::Formula);\n      m_data->cached_formula = ss.str();\n    }\n    return m_data->cached_formula;\n  }\n\n  const graph::MolecularGraph &Molecule::GetGraph() const {\n    _sanity_check_(*this);\n    return m_data->molecular_graph;\n  }\n\n  const graph::CondensedMolecularGraph &Molecule::GetCondensedGraph() const {\n    _sanity_check_(*this);\n    if (!m_data->Test(Data::CondensedGraph)) {\n      m_data->condensed_molecular_graph =\n          graph::Condense(m_data->molecular_graph);\n      m_data->Set(Data::CondensedGraph);\n    }\n    return m_data->condensed_molecular_graph;\n  }\n\n  const std::string &Molecule::GetName() const {\n    _sanity_check_(*this);\n    return m_data->name;\n  }\n\n  int32_t Molecule::GetMolecularCharge() const {\n    _sanity_check_(*this);\n    return m_data->molecular_charge;\n  }\n\n  const Molecule::MoleculeAtoms &Molecule::GetAtoms() const {\n    _sanity_check_(*this);\n    return m_data->atoms;\n  }\n\n  const Molecule::MoleculeBonds &Molecule::GetBonds() const {\n    _sanity_check_(*this);\n    return m_data->bonds;\n  }\n\n  const Molecule::MoleculeAngles &Molecule::GetAngles() {\n    _sanity_check_(*this);\n    PerceiveAngles();\n    return m_data->angles;\n  }\n\n  const Molecule::MoleculeDihedrals &Molecule::GetDihedrals() {\n    _sanity_check_(*this);\n    PerceiveDihedrals();\n    return m_data->dihedrals;\n  }\n\n  const Molecule::MoleculeResidues &Molecule::GetResidues() {\n    _sanity_check_(*this);\n    PerceiveResidues();\n    return m_data->residues;\n  }\n\n  const Forcefield &Molecule::GetForcefield() const {\n    _sanity_check_(*this);\n    return m_data->forcefield;\n  }\n\n  // =======================================================================\n  // == STATE MODIFYING ====================================================\n  // =======================================================================\n\n  void Molecule::ReorderAtoms(MoleculeAtoms &new_order) {\n    eastl::vector_set<Atom> all_atoms(m_data->atoms.begin(),\n                                      m_data->atoms.end());\n    MoleculeAtoms swap_order(new_order);\n    for (Atom atm : new_order) {\n      if (!HasAtom(atm)) {\n        throw std::runtime_error(\n            \"New atom order contains atoms not part of this molecule\");\n      }\n      all_atoms.erase(atm);\n    }\n    swap_order.insert(swap_order.end(), all_atoms.begin(), all_atoms.end());\n    m_data->atoms = swap_order;\n  }\n\n  /// \\todo Make unique on per residue basis\n  void Molecule::UniquifyAtomNames() {\n    eastl::vector_set<std::string> names, duplicate_names;\n    for (Atom atm : m_data->atoms) {\n      if (names.find(atm.GetName()) != names.end()) duplicate_names.insert(atm.GetName());\n      names.insert(atm.GetName());\n    }\n    \n    if (duplicate_names.empty()) return;\n    \n    eastl::vector_map<Element, uint32_t> element_counts;\n    std::stringstream ss;\n    for (Atom atm : m_data->atoms) {\n      if (duplicate_names.find(atm.GetName()) == duplicate_names.end()) continue;\n      do {\n        ss.str(\"\");\n        element_counts[atm.GetElement()] += 1;\n        ss << atm.GetElement().GetSymbol() << element_counts[atm.GetElement()];\n      } while (names.find(ss.str())!= names.end());\n      names.insert(ss.str());\n      atm.SetName(ss.str());\n    }\n    \n  }\n  \n  void Molecule::GiveAromaticBondsImpropers() {\n    Forcefield ff = GetForcefield();\n    for (Dihedral dhd : m_data->dihedrals) {\n      auto assigned_types = dhd.GetTypes();\n      if (assigned_types.empty()) continue;\n      if (assigned_types[0].GetType() == DihedralType::Improper) continue;\n      Bond bnd = GetBond(dhd.GetAtoms()[1], dhd.GetAtoms()[2]);\n      if (!bnd) continue;\n      if (bnd.GetOrder() == BondOrder::AROMATIC) {\n        assigned_types.clear();\n        assigned_types.push_back(ff.GetDihedralType(DihedralType::Improper, 1));\n        dhd.SetTypes(assigned_types);\n      }\n    }\n  }\n  \n  void Molecule::OptimiseChargeGroups() {\n    std::vector<std::vector<Atom>> charge_groups =\n        algorithm::OptimalChargeGroups(*this);\n    MoleculeAtoms new_order;\n    int32_t charge_group = -1;\n    for (std::vector<Atom> grp : charge_groups) {\n      ++charge_group;\n      new_order.insert(new_order.end(), grp.begin(), grp.end());\n      for (Atom atm : grp) atm.SetChargeGroupID(charge_group);\n    }\n    ReorderAtoms(new_order);\n  }\n\n  Atom Molecule::NewAtom() {\n    return NewAtom(GetPeriodicTable().GetUndefined(), 0.0, 0.0, 0.0);\n  }\n\n  Atom Molecule::NewAtom(const Element &element) {\n    return NewAtom(element, 0.0, 0.0, 0.0);\n  }\n\n  Atom Molecule::NewAtom(const Element &element, double x, double y, double z) {\n    _sanity_check_(*this);\n    m_data->ResetCalculatedData();\n    Atom atom = Atom(*this, element, \"\");\n    atom.m_data->unique_id = m_data->next_unique_id++;\n    atom.m_data->position = m_data->coordinates.Append(x, y, z);\n    m_data->atoms.emplace_back(atom);\n    m_data->molecular_graph.AddVertex(atom);\n    return atom;\n  }\n\n  Bond Molecule::NewBond(const Atom &a, const Atom &b) {\n    _sanity_check_(*this);\n    Bond bnd;\n\n    if (HasAtom(a) && HasAtom(b)) {\n      int64_t pos = m_data->FindBond(a, b);\n      if (pos != -1) {\n        bnd = a.GetBonds()[pos];\n      } else {\n        m_data->ResetCalculatedData();\n        bnd = Bond(a, b, *this, BondOrder::SINGLE);\n        bnd.m_data->unique_id = m_data->next_unique_id++;\n        bnd.m_data->atoms[0].AddBond(bnd);\n        bnd.m_data->atoms[1].AddBond(bnd);\n        m_data->molecular_graph.AddEdge(bnd);\n        m_data->bonds.emplace_back(bnd);\n      }\n    }\n\n    return bnd;\n  }\n\n  Angle Molecule::NewAngle(const Atom &a, const Atom &b, const Atom &c) {\n    // No need for logic checks as no ability for user to add angles\n    _sanity_check_(*this);\n    Angle ang = Angle(a, b, c, *this);\n    ang.m_data->unique_id = m_data->next_unique_id++;\n    ang.m_data->atoms[0].AddAngle(ang);\n    ang.m_data->atoms[1].AddAngle(ang);\n    ang.m_data->atoms[2].AddAngle(ang);\n    m_data->angles.emplace_back(ang);\n    return ang;\n  }\n\n  Dihedral Molecule::NewDihedral(const Atom &a, const Atom &b, const Atom &c,\n                                 const Atom &d, bool manual) {\n    Dihedral dhd;\n    if (manual) {\n      // Run sanity checks on manual\n      _sanity_check_(*this);\n      if (a == b || a == c || a == d || b == c || b == d || c == d) {\n        return dhd;\n      }\n      if (!(HasAtom(a) && HasAtom(b) && HasAtom(c) && HasAtom(d))) {\n        return dhd;\n      }\n    }\n\n    int64_t pos = m_data->FindDihedral(a, b, c, d);\n    if (pos != -1) {\n      dhd = a.GetDihedrals()[pos];\n    } else {\n      dhd = Dihedral(a, b, c, d, *this);\n      dhd.m_data->unique_id = m_data->next_unique_id++;\n      dhd.m_data->atoms[0].AddDihedral(dhd);\n      dhd.m_data->atoms[1].AddDihedral(dhd);\n      dhd.m_data->atoms[2].AddDihedral(dhd);\n      dhd.m_data->atoms[3].AddDihedral(dhd);\n      m_data->dihedrals.emplace_back(dhd);\n    }\n    return dhd;\n  }\n\n  Dihedral Molecule::NewDihedral(const Atom &a, const Atom &b, const Atom &c,\n                                 const Atom &d) {\n    return NewDihedral(a, b, c, d, true);\n  }\n\n  bool Molecule::RemoveAtom(const Atom &atom) {\n    _sanity_check_(*this);\n    if (!HasAtom(atom)) return false;\n    m_data->ResetCalculatedData();\n    // Remove all bonds this atom is part of from molecule\n    auto bnd_pred = [&atom](Bond bnd) { // Predicate checks if atom in bnd\n      return !(bnd.m_data->atoms[0] == atom || bnd.m_data->atoms[1] == atom);\n    };\n    // Partition so can remove bonds from other atoms\n    auto bnd_pos =\n        std::partition(m_data->bonds.begin(), m_data->bonds.end(), bnd_pred);\n    auto bnd_pos_erase = bnd_pos;\n    for (auto it = m_data->bonds.end(); bnd_pos != it; ++bnd_pos) {\n      Bond bnd = *bnd_pos;\n      bnd.m_data->atoms[0].RemoveBond(bnd);\n      bnd.m_data->atoms[1].RemoveBond(bnd);\n      bnd.Reset();\n    }\n    m_data->bonds.erase(bnd_pos_erase, m_data->bonds.end());\n\n    // Remove all angles this atom is part of from molecule\n    auto ang_pred = [&atom](Angle ang) {\n      return !(ang.m_data->atoms[0] == atom || ang.m_data->atoms[1] == atom ||\n               ang.m_data->atoms[2] == atom);\n    };\n    auto ang_pos =\n        std::partition(m_data->angles.begin(), m_data->angles.end(), ang_pred);\n    auto ang_pos_erase = ang_pos;\n    for (auto it = m_data->angles.end(); ang_pos != it; ++ang_pos) {\n      Angle ang = *ang_pos;\n      ang.m_data->atoms[0].RemoveAngle(ang);\n      ang.m_data->atoms[1].RemoveAngle(ang);\n      ang.m_data->atoms[2].RemoveAngle(ang);\n      ang.Reset();\n    }\n    m_data->angles.erase(ang_pos_erase, m_data->angles.end());\n\n    // Remove all dihedrals this atom is part of from molecule\n    auto dhd_pred = [&atom](Dihedral dhd) {\n      return !(dhd.m_data->atoms[0] == atom || dhd.m_data->atoms[1] == atom ||\n               dhd.m_data->atoms[2] == atom || dhd.m_data->atoms[3] == atom);\n    };\n    auto dhd_pos = std::partition(m_data->dihedrals.begin(),\n                                  m_data->dihedrals.end(), dhd_pred);\n    auto dhd_pos_erase = dhd_pos;\n    for (auto it = m_data->dihedrals.end(); dhd_pos != it; ++dhd_pos) {\n      Dihedral dhd = *dhd_pos;\n      dhd.m_data->atoms[0].RemoveDihedral(dhd);\n      dhd.m_data->atoms[1].RemoveDihedral(dhd);\n      dhd.m_data->atoms[2].RemoveDihedral(dhd);\n      dhd.m_data->atoms[3].RemoveDihedral(dhd);\n      dhd.Reset();\n    }\n    m_data->dihedrals.erase(dhd_pos_erase, m_data->dihedrals.end());\n\n    // Remove the atom from the molecule\n    Atom atm = atom;\n    graph::MGVertex v = m_data->molecular_graph.GetVertex(atm);\n    m_data->molecular_graph.RemoveVertex(v);\n\n    uint32_t remove_idx = atm.m_data->position;\n    Atom last_atm = m_data->atoms.back();\n\n    // shift last_atm into place of atom to be removed\n    m_data->atoms[remove_idx] = last_atm;\n    last_atm.m_data->position = remove_idx;\n    m_data->atoms.back().m_data.reset();\n    m_data->coordinates.Erase(remove_idx);\n    m_data->atoms.pop_back();\n\n    atm.Reset();\n    return true;\n  }\n\n#define Square(val) val *val\n\n  bool Molecule::RemoveBond(const Bond &bond) {\n    _sanity_check_(*this);\n    if (!HasBond(bond)) return false;\n    m_data->ResetCalculatedData();\n    Atom a = bond.GetAtoms()[0];\n    Atom b = bond.GetAtoms()[1];\n    // Remove the bond from each atom\n    a.RemoveBond(bond);\n    b.RemoveBond(bond);\n\n    // Remove all angles this bond is part of from molecule\n    auto ang_pred = [&](Angle ang) {\n      int64_t b1_pos =\n          m_data->FindBond(ang.m_data->atoms[1], ang.m_data->atoms[0]);\n      int64_t b2_pos =\n          m_data->FindBond(ang.m_data->atoms[1], ang.m_data->atoms[2]);\n      return (ang.GetAtoms()[1].GetBonds()[b1_pos] != bond &&\n              ang.GetAtoms()[1].GetBonds()[b2_pos] != bond);\n    };\n    auto ang_pos =\n        std::partition(m_data->angles.begin(), m_data->angles.end(), ang_pred);\n    auto ang_pos_erase = ang_pos;\n    for (auto it = m_data->angles.end(); it != ang_pos; ++ang_pos) {\n      Angle ang = *ang_pos;\n      ang.m_data->atoms[0].RemoveAngle(ang);\n      ang.m_data->atoms[1].RemoveAngle(ang);\n      ang.m_data->atoms[2].RemoveAngle(ang);\n      ang.Reset();\n    }\n    m_data->angles.erase(ang_pos_erase, m_data->angles.end());\n\n    // Remove all dihedrals this bond is part of from molecule\n    auto dhd_pred = [&](Dihedral dhd) {\n      int64_t b1_pos = m_data->FindBond(dhd.GetAtoms()[0], dhd.GetAtoms()[1]);\n      int64_t b2_pos = m_data->FindBond(dhd.GetAtoms()[1], dhd.GetAtoms()[2]);\n      int64_t b3_pos = m_data->FindBond(dhd.GetAtoms()[2], dhd.GetAtoms()[3]);\n      if (b1_pos == -1 || b2_pos == -1 || b3_pos == -1) { return true; }\n      Atom a = dhd.GetAtoms()[0];\n      return (a.GetBonds()[b1_pos] != bond && a.GetBonds()[b2_pos] != bond &&\n              a.GetBonds()[b3_pos] != bond);\n    };\n    auto dhd_pos = std::partition(m_data->dihedrals.begin(),\n                                  m_data->dihedrals.end(), dhd_pred);\n    auto dhd_pos_erase = dhd_pos;\n    for (auto it = m_data->dihedrals.end(); dhd_pos != it; ++dhd_pos) {\n      Dihedral dhd = *dhd_pos;\n      dhd.m_data->atoms[0].RemoveDihedral(dhd);\n      dhd.m_data->atoms[1].RemoveDihedral(dhd);\n      dhd.m_data->atoms[2].RemoveDihedral(dhd);\n      dhd.m_data->atoms[3].RemoveDihedral(dhd);\n      dhd.Reset();\n    }\n    m_data->dihedrals.erase(dhd_pos_erase, m_data->dihedrals.end());\n\n    // Remove the bond from the molecule\n    Bond bnd = bond;\n    graph::MGEdge e = m_data->molecular_graph.GetEdge(bnd);\n    m_data->molecular_graph.RemoveEdge(e);\n    m_data->bonds.erase(\n        std::find(m_data->bonds.begin(), m_data->bonds.end(), bond));\n    bnd.Reset();\n    return true;\n  }\n\n  bool Molecule::RemoveBond(const Atom &a, const Atom &b) {\n    return RemoveBond(GetBond(a, b));\n  }\n\n  AtomicCoordinates &Molecule::GetAtomicCoordinates() {\n    _sanity_check_(*this);\n    return m_data->coordinates;\n  }\n\n  int64_t Molecule::PerceiveAngles() {\n    _sanity_check_(*this);\n    if (m_data->Test(Data::AnglePerception)) { return 0; }\n    m_data->Set(Data::AnglePerception);\n\n    // Expected number of angles\n    auto sum = [&](size_t current, Atom v) -> size_t {\n      size_t degree = v.NumBonds();\n      if (degree < 2) return current;\n      return current + degree * (degree - 1) / 2;\n    };\n    size_t count =\n        std::accumulate(m_data->atoms.begin(), m_data->atoms.end(), 0, sum);\n    m_data->angles.reserve(count);\n    count = 0;\n\n    std::vector<Atom> nbrs;\n    nbrs.reserve(10);\n    // Adding new angles\n    for (Atom at : m_data->atoms) {\n      if (at.NumBonds() < 2) { continue; }\n      for (Bond bn : at.m_data->bonds) {\n        if (bn.GetAtoms()[0] == at) {\n          nbrs.emplace_back(bn.GetAtoms()[1]);\n        } else {\n          nbrs.emplace_back(bn.GetAtoms()[0]);\n        }\n      }\n\n      for (size_t i = 0; i < nbrs.size() - 1; ++i) {\n        for (size_t j = i + 1; j < nbrs.size(); ++j) {\n          if (m_data->FindAngle(nbrs[i], at, nbrs[j]) != -1) { continue; }\n          NewAngle(nbrs[i], at, nbrs[j]);\n          ++count;\n        }\n      }\n      nbrs.clear();\n    }\n    return count;\n  }\n\n  int64_t Molecule::PerceiveDihedrals() {\n    if (m_data->Test(Data::DihedralPerception)) { return 0; }\n    m_data->Set(Data::DihedralPerception);\n\n    // Expected number of dihedrals\n    auto sum = [&](size_t current, Bond b) -> size_t {\n      size_t b_degree = b.GetAtoms()[0].NumBonds();\n      if (b_degree < 2) { return current; }\n      size_t c_degree = b.GetAtoms()[1].NumBonds();\n      if (c_degree < 2) { return current; }\n      return current + (b_degree - 1) * (c_degree - 1);\n    };\n    size_t count =\n        std::accumulate(m_data->bonds.begin(), m_data->bonds.end(), 0, sum);\n    m_data->dihedrals.reserve(count);\n    count = 0;\n\n    // Adding new dihedrals\n    std::vector<Atom> B_nbrs, C_nbrs;\n    B_nbrs.reserve(10);\n    C_nbrs.reserve(10);\n    for (Bond bn : m_data->bonds) {\n      Atom B = bn.GetAtoms()[0];\n      Atom C = bn.GetAtoms()[1];\n      if (B.NumBonds() < 2 || C.NumBonds() < 2) { continue; }\n\n      for (Bond bn : B.GetBonds()) {\n        if (bn.GetAtoms()[0] == B) {\n          B_nbrs.emplace_back(bn.GetAtoms()[1]);\n        } else {\n          B_nbrs.emplace_back(bn.GetAtoms()[0]);\n        }\n      }\n      for (Bond bn : C.GetBonds()) {\n        if (bn.GetAtoms()[0] == C) {\n          C_nbrs.emplace_back(bn.GetAtoms()[1]);\n        } else {\n          C_nbrs.emplace_back(bn.GetAtoms()[0]);\n        }\n      }\n\n      for (size_t i = 0; i < B_nbrs.size(); ++i) {\n        if (B_nbrs[i] == C) { continue; }\n        for (size_t j = 0; j < C_nbrs.size(); ++j) {\n          if (C_nbrs[j] == B) { continue; }\n          if (m_data->FindDihedral(B_nbrs[i], B, C, C_nbrs[j]) != -1) continue;\n          NewDihedral(B_nbrs[i], B, C, C_nbrs[j], false);\n          ++count;\n        }\n      }\n      B_nbrs.clear();\n      C_nbrs.clear();\n    }\n\n    // Determining priorities\n    for (Bond bn : m_data->bonds) {\n      Atom B = bn.GetAtoms()[0];\n      Atom C = bn.GetAtoms()[1];\n      if (B.NumBonds() < 2 || C.NumBonds() < 2) { continue; }\n      std::vector<Dihedral> bnd_dhds;\n      for (Dihedral dhd : B.GetDihedrals()) {\n        Atom b = dhd.GetAtoms()[1];\n        Atom c = dhd.GetAtoms()[2];\n        if ((b == B && c == C) || (b == C && c == B)) {\n          bnd_dhds.emplace_back(dhd);\n        }\n      }\n      std::sort(bnd_dhds.begin(), bnd_dhds.end(), [](Dihedral a, Dihedral b) {\n        Atom a1 = a.GetAtoms()[0];\n        Atom a4 = a.GetAtoms()[3];\n        Atom b1 = b.GetAtoms()[0];\n        Atom b4 = b.GetAtoms()[3];\n        int32_t w_a = Square(a1.GetElement().GetAtomicNumber()) +\n                      Square(a4.GetElement().GetAtomicNumber());\n        int32_t w_b = Square(b1.GetElement().GetAtomicNumber()) +\n                      Square(b4.GetElement().GetAtomicNumber());\n        return w_a < w_b;\n      });\n      for (uint32_t i = 0; i < bnd_dhds.size(); ++i) {\n        // Only worry about the H's for now.\n        if (bnd_dhds[i].GetAtoms()[0].GetElement() != \"H\" &&\n            bnd_dhds[i].GetAtoms()[3].GetElement() != \"H\") {\n          continue;\n        }\n        bnd_dhds[i].m_data->priority = i;\n      }\n    }\n    return count;\n  }\n\n  //Use formal charge and bond order algo to assign electron, formal charge and bond order\n  int64_t Molecule::PerceiveElectrons(int32_t algorithmOption, bool silent) {\n    if (m_data->Test(Data::ElectronPerception)) { return 0; }\n    m_data->Set(Data::ElectronPerception);\n\n    std::cout << \"\\nStarting bond order and formal charge assignment.\\n\";\n\n    using namespace indigo_bondorder;\n\n    setElectronSettings(algorithmOption);\n\n    // Build the indigo-bondorder molecule\n    std::cout << \"Constructing bondorder molecule...\" << std::endl;\n    Molecule_p BO_mol = std::make_shared<indigo_bondorder::Molecule>();\n    BO_mol->SetTotalCharge(GetMolecularCharge());\n\n    //Initialise a periodic table\n    PeriodicTable_p PT = indigo_bondorder::PeriodicTable::GetInstance();\n    std::map<std::string, Element_p> common_elements;\n    common_elements[\"H\"] = PT->GetElement(\"H\");\n    common_elements[\"C\"] = PT->GetElement(\"C\");\n    common_elements[\"O\"] = PT->GetElement(\"O\");\n    common_elements[\"N\"] = PT->GetElement(\"N\");\n\n    //maps of original molecule entity\n    std::map<std::shared_ptr<indigox::Atom>, Atom_p> atom_map;\n    std::map<std::shared_ptr<indigox::Bond>, Bond_p> bond_map;\n\n    //Bondorder maps will be needed later\n    std::map<indigo_bondorder::BondOrder, indigox::Bond::Order> BO_enum_map = GetBondorderEnumMap();\n    std::map<indigox::Bond::Order, std::string> BO_name_map = GetBondorderNameMap();\n\n    for (const Atom& atom : m_data->atoms) {\n      //Create a bondorder atom copy of each atom, and add them to the bondorder molecule\n      String symbol = atom.GetElement().GetSymbol();\n      Element_p element = common_elements[symbol] ? common_elements[symbol] : PT->GetElement(symbol);\n      auto BO_atom = BO_mol->NewAtom(element);\n      BO_atom->SetName(atom.GetName());\n      BO_atom->SetIndex(atom.GetIndex());\n      atom_map[std::make_shared<indigox::Atom>(atom)] = BO_atom;\n    }\n\n    for (const indigox::Bond& bond : m_data->bonds) {\n      //Create a bondorder copy of each bond as well, adding them to the bondorder molecule\n      auto atom0 = BO_mol->GetAtomIndex(bond.GetAtoms()[0].GetIndex()); //I've verified the indices are consistent at this point, even though they are volatile\n      auto atom1 = BO_mol->GetAtomIndex(bond.GetAtoms()[1].GetIndex());\n      auto BO_bond = BO_mol->NewBond(atom0, atom1);\n      bond_map[std::make_shared<indigox::Bond>(bond)] = BO_bond;\n    }\n\n    std::cout << \"Molecule constructed. Starting electron placement calculation. This may take some time...\\n\";\n\n    Uint num_resonance_structures = BO_mol->AssignElectrons();\n\n    uint structure = 0;\n    if (!silent && num_resonance_structures > 1) {\n      structure = chooseResonanceStructure(BO_mol, BO_enum_map, BO_name_map, num_resonance_structures);\n    }\n\n    BO_mol->ApplyElectronAssignment(structure);\n\n    int longest_name = 5;\n    for (auto it = BO_mol->BeginAtom(); it != BO_mol->EndAtom(); ++it) {\n      std::shared_ptr <indigo_bondorder::Atom> atom = *it;\n\n      std::string name = getNameAndIndex(atom);\n      if ((int) name.length() > longest_name) longest_name = name.length();\n    }\n\n    bool formal_charge_overwritten = false;\n    for (auto const& [atom, BO_atom] : atom_map) {\n      int FC_current = atom->GetFormalCharge();\n      int FC_new = BO_atom->GetFormalCharge();\n\n      if (FC_current != FC_new) {\n        std::string name = trimOrFill(getNameAndIndex(BO_atom), longest_name);\n        std::cout << \"Overwriting charge of \" << name << \" from  \" << trimOrFill(std::to_string(FC_current), 3) << \" to  \" << trimOrFill(std::to_string(FC_new), 3) << std::endl;\n        formal_charge_overwritten = true;\n      }\n      atom->SetFormalCharge(BO_atom->GetFormalCharge());\n    }\n\n    if (formal_charge_overwritten) {\n      std::cout << std::endl;\n    }\n\n    bool bond_order_overwritten = false;\n    for (auto const& [bond, BO_bond] : bond_map) {\n      BondOrder BO_current = bond->GetOrder();\n      BondOrder BO_new = BO_enum_map.find(BO_bond->GetOrder())->second;\n\n      if (BO_current != BO_new) {\n        std::string from_name = trimOrFill(getNameAndIndex(BO_bond->GetSourceAtom()), longest_name);\n        std::string to_name = trimOrFill(getNameAndIndex(BO_bond->GetTargetAtom()), longest_name);\n        std::cout << \"Overwriting bond order between  \" << from_name << \" and  \" << to_name << \" from  \" << trimOrFill(BO_name_map.find(BO_current)->second, 14) << \" to  \" << trimOrFill(BO_name_map.find(BO_new)->second, 14) << std::endl;\n        bond_order_overwritten = true;\n      }\n      bond->SetOrder(BO_new);\n    }\n    if (bond_order_overwritten) {\n      std::cout << std::endl;\n    }\n\n    std::cout << \"Finished assigning formal charges and bond orders.\\n\" << std::endl;\n\n    return num_resonance_structures;\n  }\n\n  void Molecule::setElectronSettings(int32_t algorithmOption) {\n    using namespace indigo_bondorder;\n    using ElecOps = Options::AssignElectrons;\n\n    switch (algorithmOption) {\n      case 0:\n        ElecOps::ALGORITHM = ElecOps::Algorithm::LOCAL_OPTIMISATION;\n        break;\n      case 1:\n        ElecOps::ALGORITHM = ElecOps::Algorithm::ASTAR;\n        break;\n      case 2:\n      default: //default to FPT\n        ElecOps::ALGORITHM = ElecOps::Algorithm::FPT;\n    }\n    //Not sure what the first two options are for\n    ElecOps::FPT::ADD_EDGES_TO_TD = true; //add edges to tree decomposition\n    ElecOps::FPT::MINIMUM_PROPAGATION_DEPTH = 1;\n    ElecOps::USE_ELECTRON_PAIRS = true; // is default. Electrons calc'd as pairs\n    ElecOps::PREPLACE_ELECTRONS = true; // Puts 6 electrons on singly bonded halogens by default\n  }\n\n  std::map<indigo_bondorder::BondOrder, indigox::Bond::Order> Molecule::GetBondorderEnumMap() {\n    std::map<indigo_bondorder::BondOrder, indigox::Bond::Order> BO_enum_map;\n    BO_enum_map[indigo_bondorder::SINGLE_BOND] = indigox::BondOrder::SINGLE;\n    BO_enum_map[indigo_bondorder::DOUBLE_BOND] = indigox::BondOrder::DOUBLE;\n    BO_enum_map[indigo_bondorder::TRIPLE_BOND] = indigox::BondOrder::TRIPLE;\n    BO_enum_map[indigo_bondorder::QUADRUPLE_BOND] = indigox::BondOrder::QUADRUPLE;\n    BO_enum_map[indigo_bondorder::AROMATIC_BOND] = indigox::BondOrder::AROMATIC;\n    BO_enum_map[indigo_bondorder::ONEANDAHALF_BOND] = indigox::BondOrder::ONEANDAHALF;\n    BO_enum_map[indigo_bondorder::TWOANDAHALF_BOND] = indigox::BondOrder::TWOANDAHALF;\n    BO_enum_map[indigo_bondorder::UNDEFINED_BOND] = indigox::BondOrder::UNDEFINED;\n    return BO_enum_map;\n  }\n\n  std::map<indigox::Bond::Order, std::string> Molecule::GetBondorderNameMap() {\n    std::map<indigox::Bond::Order, std::string> BO_names;\n    BO_names[indigox::Bond::Order::SINGLE] = \"Single\";\n    BO_names[indigox::Bond::Order::DOUBLE] = \"Double\";\n    BO_names[indigox::Bond::Order::TRIPLE] = \"Triple\";\n    BO_names[indigox::Bond::Order::QUADRUPLE] = \"Quadruple\";\n    BO_names[indigox::Bond::Order::AROMATIC] = \"Aromatic\";\n    BO_names[indigox::Bond::Order::ONEANDAHALF] = \"One and a half\";\n    BO_names[indigox::Bond::Order::TWOANDAHALF] = \"Two and a half\";\n    BO_names[indigox::Bond::Order::UNDEFINED] = \"Undefined\";\n    return BO_names;\n  }\n\n  uint Molecule::chooseResonanceStructure(indigo_bondorder::Molecule_p &mol,\n                                          const std::map<indigo_bondorder::BondOrder, indigox::Bond::Order> &enum_map,\n                                          const std::map<indigox::Bond::Order, std::string> &name_map,\n                                          indigo_bondorder::Uint num_structures) {\n    std::cout << std::endl << \"Found \" << num_structures << \" resonance structure(s) with minimum score of \" << mol->GetMinimumElectronAssignmentScore() << std::endl << std::endl;\n\n    //Make this stand out so people hopefully don't miss it\n    std::string phrase = \"Would you like to print the structures and choose between them? If not, the first discovered structure will be used. Type Y or N and hit enter.\";\n    std::cout << \"|\" << std::string(phrase.length() + 4, '=') << \"|\" << std::endl;\n    std::cout << \"|= \" << phrase << \" =|\" << std::endl;\n    std::cout << \"|\" << std::string(phrase.length() + 4, '=') << \"|\" << std::endl;\n\n    std::string yesOrNo;\n    getline(std::cin, yesOrNo);\n\n    boost::algorithm::to_lower(yesOrNo);\n    uint i = yesOrNo.rfind('y');\n\n    uint structure = 0; // index of resonance structure to use\n\n    if (i == 0) { //If user typed Y or Yes (or anything else starting with Y)\n      displayResonanceStructures(mol, num_structures, enum_map, name_map);\n      structure = getChoiceOfStructure();\n    } else if ((int) yesOrNo.rfind('n') == -1) {\n      std::cout << \"Could not interpret the input. \";\n    }\n\n    if (structure < 0 || structure > num_structures) {\n      std::cout << \"Index \" << structure << \" is out of range. \";\n      structure = 0;\n    }\n\n    std::cout << \"Using resonance structure number \" << structure << \".\" << std::endl << std::endl;\n    return structure;\n  }\n\n\n  void Molecule::displayResonanceStructures(const indigo_bondorder::Molecule_p &mol, indigo_bondorder::Uint num_structures,\n                                            std::map<indigo_bondorder::BondOrder, indigox::Bond::Order> enum_map,\n                                            std::map<indigox::Bond::Order, std::string> string_map) {\n    using namespace std;\n    \n    int longest_name = 5;\n    for (indigo_bondorder::Uint a = 0; a < mol->NumAtoms(); a++) {\n      shared_ptr <indigo_bondorder::Atom> atom = mol->GetAtomIndex(a);\n\n      string name = getNameAndIndex(atom);\n      if (atom->GetFormalCharge() != 0 && (int) name.length() > longest_name) longest_name = name.length();\n    }\n\n    for (indigo_bondorder::Uint i = 0; i < num_structures; i++) {\n      cout << \"Printing resonance structure \" << i << \".\" << endl << endl;\n      mol->ApplyElectronAssignment(i);\n      bool printed = false;\n      for (auto it = mol->BeginAtom(); it != mol->EndAtom(); ++it) { //Print all atoms with charge != 0\n        shared_ptr <indigo_bondorder::Atom> atom = *it;\n        if (atom->GetFormalCharge() != 0) {\n          string name = trimOrFill(atom->GetName() + \"(\" + to_string(atom->GetIndex()) + \")\", longest_name);\n          cout << \"Atom \" << name << \" has charge  \" << atom->GetFormalCharge() << endl;\n          printed = true;\n        }\n      }\n      if (printed) { cout << endl; }\n\n      printed = false;\n      for (auto it = mol->BeginBond(); it != mol->EndBond(); ++it) { //Print all bonds with order != 1\n        shared_ptr <indigo_bondorder::Bond> bond = *it;\n        if (bond->GetOrder() != 1) {\n          string source = trimOrFill(getNameAndIndex(bond->GetSourceAtom()), longest_name);\n          string target = trimOrFill(getNameAndIndex(bond->GetTargetAtom()), longest_name);\n          cout << \"Bond from  \" << source << \" to  \" << target << \" has bond order: \" << string_map.find(enum_map.find(bond->GetOrder())->second)->second << endl;\n          printed = true;\n        }\n      }\n      if (printed) { cout << endl; }\n    }\n  }\n\n  std::string Molecule::getNameAndIndex(const std::shared_ptr<indigo_bondorder::Atom> &atom) {\n    return atom->GetName() + \"(\" + std::__cxx11::to_string(atom->GetIndex()) + \")\";\n  }\n\n  int32_t Molecule::getChoiceOfStructure() {\n    std::cout << \"Please type the number of the resonance structure you want to use, and then press enter.\" << std::endl;\n\n    std::string number;\n    std::getline(std::cin, number);\n\n    int32_t structure_to_use;\n    std::stringstream(number) >> structure_to_use; //if string can't be converted to int, defaults to 0.\n\n    return structure_to_use;\n  }\n\n  // Finds the edges of a graph corresponding to peptide bonds in a molecule\n  void PeptideBonds(const graph::MolecularGraph &G,\n                    std::vector<graph::MGEdge> &edges) {\n    for (graph::MGEdge e : G.GetEdges()) {\n      if (!e.GetBond().IsAmideBond()) continue;\n      for (Atom atm : e.GetBond().GetAtoms()) {\n        if (atm.GetElement() == \"N\" &&\n            atm.NumHydrogenBonds() + atm.GetImplicitCount() <= 1) {\n          edges.push_back(e);\n        }\n      }\n    }\n  }\n\n  int32_t Molecule::PerceiveResidues() {\n    using namespace graph;\n    _sanity_check_(*this);\n    if (m_data->Test(Data::ResiduePerception)) {\n      return (int32_t)m_data->residues.size();\n    }\n    m_data->Set(Data::ResiduePerception);\n\n    MolecularGraph graph = m_data->molecular_graph;\n\n    MolecularGraph::VertContain all_vertices = graph.GetVertices();\n    MolecularGraph residue_graph = graph.Subgraph(all_vertices);\n\n    // Identify peptide bonds\n    std::vector<graph::MGEdge> potential_remove, to_remove;\n    PeptideBonds(residue_graph, potential_remove);\n    //! \\todo Other types of bonds to break on for residue identification?\n\n    // Remove the peptide bonds to get the components of the graph as residues\n    std::vector<MGVertex> res_vert;\n    res_vert.reserve(2 * potential_remove.size());\n    for (MGEdge e : potential_remove) residue_graph.RemoveEdge(e);\n\n    // Re-add edges that create non-specific residues\n    eastl::vector_set<MGVertex> unspecified_residues;\n    for (auto c : residue_graph.GetConnectedComponents()) {\n      std::vector<Atom> atms;\n      atms.reserve(c.size());\n      for (MGVertex v : c) atms.emplace_back(v.GetAtom());\n      Residue tmp_res(atms, *this);\n      if (tmp_res.GetType() == ResidueType::NonSpecific)\n        unspecified_residues.insert(c.begin(), c.end());\n    }\n    for (MGEdge e : potential_remove) {\n      MGVertex u = graph.GetSourceVertex(e);\n      MGVertex v = graph.GetTargetVertex(e);\n      if (unspecified_residues.find(u) == unspecified_residues.end() ||\n          unspecified_residues.find(v) == unspecified_residues.end()) {\n        res_vert.emplace_back(u);\n        res_vert.emplace_back(v);\n        to_remove.emplace_back(e);\n      } else {\n        residue_graph.AddEdge(e.GetBond());\n      }\n    }\n\n    // Uniquify the residue vertices, just in case\n    std::sort(res_vert.begin(), res_vert.end());\n    auto last = std::unique(res_vert.begin(), res_vert.end());\n    res_vert.erase(last, res_vert.end());\n\n    // Make a graph of only the vertices of residue breaking bonds\n    MolecularGraph residue_ordering = graph.Subgraph(res_vert, to_remove);\n    // Add bonds between every atom pair within a component\n    for (auto component : residue_graph.GetConnectedComponents()) {\n      for (MGVertex source : component) {\n        if (!residue_ordering.HasVertex(source)) continue;\n        for (MGVertex target : component) {\n          if (!residue_ordering.HasVertex(target)) continue;\n          Bond tmp_bnd(source.GetAtom(), target.GetAtom(), *this,\n                       BondOrder::SINGLE);\n          residue_ordering.AddEdge(tmp_bnd);\n        }\n      }\n    }\n\n    // order vertices based on degree and element. carbons and d(1) first.\n    std::sort(res_vert.begin(), res_vert.end(),\n              [&residue_ordering](MGVertex u, MGVertex v) {\n                if (residue_ordering.Degree(u) != residue_ordering.Degree(v))\n                  return residue_ordering.Degree(u) <\n                         residue_ordering.Degree(v);\n                return u.GetAtom().GetElement().GetAtomicNumber() <\n                       v.GetAtom().GetElement().GetAtomicNumber();\n              });\n\n    //----\n    //- Order vertices to get sensible order for component storing\n    //---\n\n    // For every component, Do a depth first search starting from the first C\n    std::vector<MGVertex> ordered_vertices;\n    for (auto &component : residue_ordering.GetConnectedComponents()) {\n      MGVertex source;\n      for (MGVertex test : res_vert) {\n        if (std::find(component.begin(), component.end(), test) ==\n            component.end())\n          continue;\n        source = test;\n        break;\n      }\n      if (!source) throw std::runtime_error(\"Something went wrong\");\n\n      algorithm::TraversalResults<MGVertex> dfs =\n          algorithm::DepthFirstSearch(residue_ordering, source);\n      std::pair<MGVertex, int32_t> l_path =\n          std::make_pair(dfs.furthest, dfs.path_lengths[dfs.furthest]);\n\n      eastl::vector_set<MGVertex> seen;\n      while (component.size() > seen.size()) {\n        std::vector<MGVertex> current_path;\n        current_path.reserve(l_path.second);\n        while (l_path.first && seen.find(l_path.first) == seen.end()) {\n          current_path.push_back(l_path.first);\n          seen.insert(l_path.first);\n          l_path.first = dfs.predecessors[l_path.first];\n        }\n        ordered_vertices.insert(ordered_vertices.end(), current_path.rbegin(),\n                                current_path.rend());\n        l_path.second = -1;\n        for (auto &vl : dfs.path_lengths) {\n          if (seen.find(vl.first) != seen.end()) continue;\n          if (vl.second > l_path.second)\n            l_path = std::make_pair(vl.first, vl.second);\n        }\n      }\n    }\n\n    auto components = residue_graph.GetConnectedComponents();\n    // Figure out the order for the components\n    std::vector<int32_t> order;\n    for (MGVertex v : ordered_vertices) {\n      int32_t index = -1;\n      for (auto &component : components) {\n        ++index;\n        if (std::find(order.begin(), order.end(), index) != order.end())\n          continue;\n        if (std::find(component.begin(), component.end(), v) !=\n            component.end()) {\n          order.push_back(index);\n          break;\n        }\n      }\n    }\n\n    MoleculeAtoms new_order;\n    int32_t res_id = 1;\n    m_data->residues.clear();\n    for (int32_t index : order) {\n      MolecularGraph graph = residue_graph.Subgraph(components[index]);\n      // order component vertices. dfs from first in ordered_vertices\n      MGVertex source;\n      eastl::vector_set<MGVertex> comp_vert(graph.GetVertices().begin(),\n                                            graph.GetVertices().end());\n      for (MGVertex v : ordered_vertices) {\n        if (comp_vert.find(v) != comp_vert.end()) {\n          source = v;\n          break;\n        }\n      }\n      if (!source) throw std::runtime_error(\"Something went wrong\");\n      auto dfs = algorithm::DepthFirstSearch(graph, source);\n\n      std::vector<MGVertex> order;\n      eastl::vector_set<MGVertex> seen;\n      MGVertex start = dfs.furthest;\n      while (order.size() < dfs.discover_order.size()) {\n        std::vector<MGVertex> path_order;\n        while (start && seen.find(start) == seen.end()) {\n          for (MGVertex nbr : graph.GetNeighbours(start)) {\n            if (graph.Degree(nbr) != 1) continue;\n            if (seen.find(nbr) == seen.end()) {\n              seen.insert(nbr);\n              path_order.push_back(nbr);\n            }\n          }\n          path_order.push_back(start);\n          seen.insert(start);\n          start = dfs.predecessors[start];\n        }\n        order.insert(order.end(), path_order.rbegin(), path_order.rend());\n        int32_t furthest_length = -1;\n        for (MGVertex v : dfs.discover_order) {\n          if (seen.find(v) != seen.end()) continue;\n          if (dfs.path_lengths[v] > furthest_length) {\n            start = v;\n            furthest_length = dfs.path_lengths[v];\n          }\n        }\n      }\n\n      std::vector<Atom> ordered_atoms;\n      ordered_atoms.reserve(order.size());\n      for (MGVertex v : order) {\n        Atom atm = v.GetAtom();\n        new_order.emplace_back(atm);\n        ordered_atoms.emplace_back(atm);\n        atm.m_data->residue_id = res_id;\n        atm.m_data->residue_name = \"RS\" + std::to_string(res_id);\n      }\n      Residue res(ordered_atoms, *this);\n      m_data->residues.emplace_back(res);\n\n      ++res_id;\n    }\n    ReorderAtoms(new_order);\n\n    return (int32_t)m_data->residues.size();\n  }\n\n  void Molecule::ModificationMade() { m_data->ResetCalculatedData(); }\n\n  // =======================================================================\n  // == STATE SETTING ======================================================\n  // =======================================================================\n\n  void Molecule::SetName(std::string name) {\n    _sanity_check_(*this);\n    m_data->name = name;\n  }\n\n  void Molecule::SetMolecularCharge(int32_t q) {\n    _sanity_check_(*this);\n    m_data->ResetCalculatedData();\n    m_data->molecular_charge = q;\n  }\n\n  void Molecule::SetForcefield(const Forcefield &ff) {\n    _sanity_check_(*this);\n    if (HasForcefield()) {\n      throw std::runtime_error(\"Molecule already has a forcefield set.\");\n    }\n    m_data->forcefield = ff;\n  }\n\n  void Molecule::ResetForcefield(const Forcefield &ff) {\n    _sanity_check_(*this);\n    m_data->forcefield = ff;\n  }\n\n  std::string Molecule::trimOrFill(std::string str, int length) {\n    std::string to_return = str;\n    int paddingNeeded = length - (int) str.length();\n    if (paddingNeeded > 0) {\n      to_return = to_return + std::string(paddingNeeded, ' ');\n    } else if (paddingNeeded < 0) {\n      to_return = to_return.substr(0, length);\n    }\n    return to_return;\n  }\n\n  // =======================================================================\n  // == OUTPUTTING =========================================================\n  // =======================================================================\n\n  void SaveMolecule(const Molecule &mol, std::string path) {\n    using Archive = cereal::PortableBinaryOutputArchive;\n    std::ofstream os(path);\n    if (!os.is_open()) throw std::runtime_error(\"Unable to open output stream\");\n    Archive archive(os);\n    std::string stype(\"Molecule\");\n    std::cout << \"Saving molecule in binary format to location \" << path << std::endl;\n    archive(stype, mol);\n  }\n\n  Molecule LoadMolecule(std::string path) {\n    using Archive = cereal::PortableBinaryInputArchive;\n    std::ifstream is(path);\n    if (!is.is_open()) throw std::runtime_error(\"Unable to open input stream\");\n    std::string stype;\n    Archive archive(is);\n    archive(stype);\n    if (stype != \"Molecule\") throw std::runtime_error(\"Not a Molecule file\");\n    Molecule mol;\n    archive(mol);\n    return mol;\n  }\n\n} // namespace indigox\n", "meta": {"hexsha": "1ca9da8b689bf7d2050ef27ab064731abbdce33d", "size": 50211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classes/molecule.cpp", "max_stars_repo_name": "allison-group/indigox", "max_stars_repo_head_hexsha": "22657cb3ceb888049cc231e73d18fb2eac099604", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-11-24T15:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T05:18:42.000Z", "max_issues_repo_path": "src/classes/molecule.cpp", "max_issues_repo_name": "allison-group/indigox", "max_issues_repo_head_hexsha": "22657cb3ceb888049cc231e73d18fb2eac099604", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-17T00:55:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-11T01:47:04.000Z", "max_forks_repo_path": "src/classes/molecule.cpp", "max_forks_repo_name": "allison-group/indigox", "max_forks_repo_head_hexsha": "22657cb3ceb888049cc231e73d18fb2eac099604", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-21T01:26:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-02T00:00:42.000Z", "avg_line_length": 36.1230215827, "max_line_length": 237, "alphanum_fraction": 0.5931767939, "num_tokens": 13776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253786982541, "lm_q2_score": 0.0293122339312297, "lm_q1q2_score": 0.01085213290768133}}
{"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#include <hashclash/saveload_bz2.hpp>\n#include <hashclash/sdr.hpp>\n#include <hashclash/sha1differentialpath.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);\n\nstruct connect_bitdata {\n\tbitcondition rqtm2[2], rqtm1[2], rqt[2], rqtp1[2];\n\tbitcondition fqtm1[2], fqt[2], fqtp1[2], fqtp2[2];\n\tuint32 dQtm1;\n\tuint32 dQt;\n\tuint32 dQtp1;\n\tuint32 dFt;\n\tuint32 dFtp1;\n\tuint32 dFtp2;\n\tuint32 dFtp3;\n\tuint32 dFtp4;\n\n\tinline bool operator== (const connect_bitdata& r) const {\n\t\tfor (unsigned i = 0; i < 2; ++i)\n\t\t\tif (rqtm2[i] != r.rqtm2[i] || rqtm1[i] != r.rqtm1[i] || rqt[i] != r.rqt[i] || rqtp1[i] != r.rqtp1[i]\n\t\t\t\t|| fqtm1[i] != r.fqtm1[i] || fqt[i] != r.fqt[i] || fqtp1[i] != r.fqtp1[i] || fqtp2[i] != r.fqtp2[i]) \n\t\t\t\t\treturn false;\n\t\treturn dQtm1==r.dQtm1 && dQt==r.dQt && dQtp1==r.dQtp1\n\t\t\t&& dFt==r.dFt && dFtp1==r.dFtp1 && dFtp2==r.dFtp2 && dFtp3==r.dFtp3 && dFtp4==r.dFtp4\n\t\t\t;\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 (dQtm1 < r.dQtm1) return true;\n\t\tif (dQtm1 > r.dQtm1) return false;\n\t\tif (dFt < r.dFt) return true;\n\t\tif (dFt > r.dFt) return false;\n\t\tif (dQt < r.dQt) return true;\n\t\tif (dQt > r.dQt) return false;\n\t\tif (dFtp1 < r.dFtp1) return true;\n\t\tif (dFtp1 > r.dFtp1) return false;\n\t\tif (dQtp1 < r.dQtp1) return true;\n\t\tif (dQtp1 > r.dQtp1) 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\tif (dFtp3 > r.dFtp3) return false;\n\t\tif (dFtp4 < r.dFtp4) return true;\n\t\tif (dFtp4 > r.dFtp4) return false;\n\t\tfor (unsigned i = 0; i < 2; ++i) {\n\t\t\tif (rqtm2[i] < r.rqtm2[i]) return true;\n\t\t\tif (rqtm2[i] > r.rqtm2[i]) return false;\n\t\t\tif (rqtm1[i] < r.rqtm1[i]) return true;\n\t\t\tif (rqtm1[i] > r.rqtm1[i]) return false;\n\t\t\tif (rqt[i] < r.rqt[i]) return true;\n\t\t\tif (rqt[i] > r.rqt[i]) return false;\n\t\t\tif (rqtp1[i] < r.rqtp1[i]) return true;\n\t\t\tif (rqtp1[i] > r.rqtp1[i]) return false;\n\t\t\tif (fqtm1[i] < r.fqtm1[i]) return true;\n\t\t\tif (fqtm1[i] > r.fqtm1[i]) return false;\n\t\t\tif (fqt[i] < r.fqt[i]) return true;\n\t\t\tif (fqt[i] > r.fqt[i]) return false;\n\t\t\tif (fqtp1[i] < r.fqtp1[i]) return true;\n\t\t\tif (fqtp1[i] > r.fqtp1[i]) return false;\n\t\t\tif (fqtp2[i] < r.fqtp2[i]) return true;\n\t\t\tif (fqtp2[i] > r.fqtp2[i]) return false;\n\t\t}\n\t\treturn false;\n\t}\n};\n\nstruct sha1_connect_thread {\n\tsha1_connect_thread() {\n\t\ttestokcnt = 0; testbadcnt = 0;\n\t\tsw.start(); sw2.start();\n\t\tbcnt.assign(41,0);\n\t}\n\tvoid sha1_connect(const sha1differentialpath& lowerpath, const vector<sha1differentialpath>& upperpaths, path_container& container, unsigned prev_eq_b);\n\tvector<uint64> bcnt;\n\ttimer sw, sw2;\n\tvoid sha1_connect_clear_uppercache() {\n\t\tdpFt.clear();\n\t\tdpFtp1.clear();\n\t\tdpFtp2.clear();\n\t\tdpFtp3.clear();\n\t\tdpFtp4.clear();\n\t\tdQtp1.clear();\n\t}\n\tunsigned int lowpathindex;\n\tint t;\n\tuint32 mmaskt, mmasktp1, mmasktp2, mmasktp3, mmasktp4;\n\tbooleanfunction* Ft;\n\tbooleanfunction* Ftp1;\n\tbooleanfunction* Ftp2;\n\tbooleanfunction* Ftp3;\n\tbooleanfunction* Ftp4;\n\tvector<uint32> dFt, dFtp1, dFtp2, dFtp3, dFtp4;\n\tsha1differentialpath newpath;\n\n\tvector<uint32> dpFt, dpFtp1, dpFtp2, dpFtp3, dpFtp4, dQtp1;\n\tbitcondition Qtm1b31not, Qtb31not, Qtp1b31not;\n\tbitcondition Qtm1b31not2, Qtb31not2, Qtp1b31not2;\n\tuint32 dQtm1b2b31, dQtm1b27b31, dQtb2b31, dQtb27b31, dQtp1b2b31, dQtp1b27b31;\n\n\tuint32 Qtm3freemask, Qtm2freemask, Qtm1freemask, Qtfreemask, Qtp1freemask, Qtp2freemask, Qtp3freemask;\n\tuint64 testokcnt, testbadcnt;\n\tsha1differentialpath tbc;\n\tvector<connect_bitdata> connectbits_vec, connectbits_vec2;\n\tbool usedFtp1, usedFtp2, usedFtp3, usedFtp4;\n\tvector<unsigned> prevb;\n\n\ttemplate<int steps, bool storefdata, bool storenewconds, bool compmincond = false>\n\tvoid connectbits_01234(const pair<connect_bitdata,unsigned>& in, map<connect_bitdata,unsigned>& out, unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& dataend, vector<unsigned>& mincond);\n\ttemplate<bool storenewconds>\n\tvoid connectbits_1234(const pair<connect_bitdata,unsigned>& in, map<connect_bitdata,unsigned>& out, unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& dataend, vector<unsigned>& mincond);\n\ttemplate<bool storenewconds>\n\tvoid connectbits_234(const pair<connect_bitdata,unsigned>& in, map<connect_bitdata,unsigned>& out, unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& dataend, vector<unsigned>& mincond);\n\ttemplate<bool storenewconds>\n\tvoid connectbits_34(const pair<connect_bitdata,unsigned>& in, map<connect_bitdata,unsigned>& out, unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& dataend, vector<unsigned>& mincond);\n\ttemplate<bool storenewconds>\n\tvoid connectbits_4(const pair<connect_bitdata,unsigned>& in, map<connect_bitdata,unsigned>& out, unsigned b, const sha1differentialpath& lower, const sha1differentialpath& upper, vector< pair<byteconditions,byteconditions> >& newconds, vector<connect_bitdata>& dataend, vector<unsigned>& mincond);\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\n\n\tunsigned connect_paths(const sha1differentialpath& lowerpath, const sha1differentialpath& upperpath, connect_bitdata& startdata, path_container& container, bool returnb40);\n\tmap<connect_bitdata, unsigned> bitdataresults[41];\n\tvector<connect_bitdata> bitdataresults_vec[41];\n\tvector<connect_bitdata> bitdatastart[40];\n\tvector<connect_bitdata> bitdataend[40];\n\tvector< unsigned > bitdatamincond[40];\n\tvector< pair<byteconditions,byteconditions> >  bitdatanewcond[40];\n\tvector< unsigned > bitdatanewcondhw[40];\n\tvector< unsigned > mincond[41];\t\n\n};\n\nextern uint64 pbcount;// = 0;\nextern int lastlowpathindex;// = -1;\nextern vector< vector<unsigned> > badcounts;//(85, vector<unsigned>(32,0));\n\nclass path_container {\npublic:\n\tpath_container()\n\t\t: modn(1), modi(0), inputfilelow(), inputfilehigh()\n\t\t, t(0), bestpathcond(1<<20), lastsavecnt(0), determinelowestcond(false), splitmode(0), threads(1), showstats(false)\n\t\t, keepall(false)\n\t{\n\t\tfor (unsigned k = 0; k < 80; ++k)\n\t\t\tm_mask[k] = 0;\n\t\tshownbadpath = false;\n\t}\n\n\t~path_container() \n\t{\n\t\tcout << \"Best path: totcond=\" << bestpathcond << \" count=\" << bestpaths.size() << endl;\n\t\tsave_bestpaths();\n\t}\n\n\tvoid push_back(const sha1differentialpath& fullpath)\n\t{\n\t\tboost::lock_guard<boost::mutex> lock(mut);\n\t\tif (hw(++pbcount)==1) cout << \"{\" << pbcount << \"}\" << flush;\n\t\tunsigned cond = fullpath.nrcond();\n\t\tif (cond > bestpathcond) return;\n\t\tif (!test_path(fullpath)) {\n\t\t\tif (!shownbadpath) {\n\t\t\t\tshownbadpath = true;\n\t\t\t\tcout << \"bad path \" /*<< lowpathindex*/ << endl;\n\t\t\t\tshow_path(fullpath);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n//\t\tfor (int k = fullpath.tbegin(); k < fullpath.tend(); ++k)\n//\t\t\tcond += fullpath[k].hw();\n\t\tbool show = false, bad = false;\n                for (int k = tunnelconditions.tbegin(); k < tunnelconditions.tend() && !bad; ++k) {\n                    if (k >= fullpath.tbegin() && k < fullpath.tend())\n                        for (unsigned b = 0; b < 32 && !bad; ++b) {   \n                                bitcondition bc = tunnelconditions(k,b), bcpath = fullpath(k,b);\n                                if (bcpath == bc_constant && bc != bc_prev && bc != bc_prevn) continue;\n                                if (bcpath == bc_plus) bcpath = bc_zero;\n                                else if (bcpath == bc_minus) bcpath = bc_one;\n                                switch (bc) {\n                                        case bc_constant: break;\n                                        case bc_plus: { bad = true; ++badcounts[4+k][b]; break; }\n                                        case bc_minus: { bad = true; ++badcounts[4+k][b]; break; } \n                                        case bc_one:\n                                        case bc_zero:\n                                                if (bcpath == bc) break;\n                                                if (bcpath == bc_one || bcpath == bc_zero) { bad = true; ++badcounts[4+k][b]; break; }\n                                                if (bcpath == bc_plus || bcpath == bc_minus) { bad = true; ++badcounts[4+k][b]; break; }\n                                                break;\n                                        case bc_prev:{\n                                                bitcondition bcpathm1 = fullpath(k-1,b);\n                                                if (bcpathm1 == bc_plus) bcpathm1 = bc_zero;\n                                                else if (bcpathm1 == bc_minus) bcpathm1 = bc_one;\n                                                if (bcpathm1 == bc_next) break;\n\t\t\t\t\t\tif (bcpath == bc_prev) break;\n\t\t\t\t\t\tif (bcpathm1 == bc_nextn) { bad = true; ++badcounts[4+k][b]; break; }\n\t\t\t\t\t\tif (bcpath == bc_prevn) { bad = true; ++badcounts[4+k][b]; break; }\n//                                                if (bcpath == bc_plus || bcpath == bc_minus || bcpathm1 == bc_plus || bcpathm1 == bc_minus) return;\n                                                if (bcpathm1 == bc_constant) break;\n                                                if (bcpathm1 == bc_one && bcpath == bc_zero) { bad = true; ++badcounts[4+k][b]; break; }\n                                                if (bcpathm1 == bc_zero && bcpath == bc_one) { bad = true; ++badcounts[4+k][b]; break; }\n                                                break;}\n                                        case bc_prevn:{\n                                                bitcondition bcpathm1 = fullpath(k-1,b);\n                                                if (bcpathm1 == bc_plus) bcpathm1 = bc_zero;\n                                                else if (bcpathm1 == bc_minus) bcpathm1 = bc_one;\n                                                if (bcpathm1 == bc_nextn) break;\n                                                if (bcpath == bc_prevn) break;\n                                                if (bcpathm1 == bc_next) { bad = true; ++badcounts[4+k][b]; break; }\n                                                if (bcpath == bc_prev) { bad = true; ++badcounts[4+k][b]; break; }\n  //                                              if (bcpath == bc_plus || bcpath == bc_minus || bcpathm1 == bc_plus || bcpathm1 == bc_minus) return;\n                                                if (bcpathm1 == bc_constant) break;\n                                                if (bcpathm1 == bc_one && bcpath == bc_one) { bad = true; ++badcounts[4+k][b]; break; }\n                                                if (bcpathm1 == bc_zero && bcpath == bc_zero) { bad = true; ++badcounts[4+k][b]; break; }\n                                                break;}\n                                }\n                                if (bad && hw(uint32(badcounts[4+k][b])) == 1) show = true;\n                        }\n                }\n                if (show) {\n                \tfor (unsigned i = 0; i < badcounts.size(); ++i)\n                \t\tfor (unsigned b = 0; b < badcounts[i].size(); ++b)\n                \t\t\tif (badcounts[i][b])\n                \t\t\t\tcout << \"badcounts[\" << int(i)-4 << \",\" << b << \"] = \\t\" << badcounts[i][b] << endl;\n\t\t\tcout << endl;\n                }\n\t\tif (bad) {\n\t\t\tstatic bool badshown = false;\n\t\t\tif (!badshown) {\n\t\t\t\tbadshown = true;\n\t\t\t\tshow_path(fullpath);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (!keepall && (cond < bestpathcond || bestpaths.size() == 0))\n\t\t{\n\t\t\tbestpath = fullpath;\n\t\t\tbestpaths.clear();\n\t\t\tbestpaths.push_back(fullpath);\n\t\t\tbestpathcond = cond;\n\t\t\tshow_path(fullpath);\n\t\t\tlastsavecnt = 0;\n\t\t\tcout << \"Best path: totcond=\" << bestpathcond << endl;\n\t\t\tsave_bz2(fullpath, workdir + \"/bestpath_c\" + boost::lexical_cast<string>(bestpathcond), binary_archive);\n\t\t\tsave_bz2(fullpath, workdir + \"/bestpath\", binary_archive);\n\t\t} else if (keepall || cond == bestpathcond) {\n\t\t\tbestpaths.push_back(fullpath);\n\t\t\tif (hw(uint32(bestpaths.size()))==1)\n\t\t\t\tcout << \"Best path: totcond=\" << bestpathcond << \" count=\" << bestpaths.size() << endl;\n\t\t}\n\t}\n\n\tvoid save_bestpaths(bool silent = false) {\n\t\tmut.lock();\n\t\tif (lastsavecnt != bestpaths.size()) {\n\t\t\tsave_bz2(bestpaths, workdir + \"/bestpaths_c\" + boost::lexical_cast<string>(bestpathcond), binary_archive);\n\t\t\tsave_bz2(bestpaths, workdir + \"/bestpaths\", binary_archive);\n\t\t\tlastsavecnt = bestpaths.size();\n\t\t\tif (!silent)\n\t\t\t\tcout << \"Best path: totcond=\" << bestpathcond << \" count=\" << bestpaths.size() << endl;\n\t\t}\n\t\tmut.unlock();\n\t}\n\tbool shownbadpath;\n\t\n\tuint32 m_mask[80];\n\n\tunsigned t;\n\tint Qcondstart;\n\t\n\tbool showstats;\n\tbool determinelowestcond;\n\n\tunsigned modn;\n\tunsigned modi;\n\tstd::string inputfilelow, inputfilehigh, inputfileredo;\n\tbool showinputpaths;\n\n\tsha1differentialpath bestpath;\n\tvector<sha1differentialpath> bestpaths;\n\tunsigned bestpathcond;\n\tunsigned bestmaxtunnel;\n\tint bestmaxcomp;\n\tuint32 lastsavecnt;\n\tunsigned splitmode;\n\tunsigned loworder;\n\n\tbool keepall;\n\n\tsha1differentialpath tunnelconditions;\n\tint threads;\n};\n\nstruct diffpathupper_less\n\t: public std::binary_function<sha1differentialpath, sha1differentialpath, bool>\n{\n\tbool operator()(const sha1differentialpath& _Left, const sha1differentialpath& _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() < 4)\n\t\t\tthrow std::runtime_error(\"Upper differential paths of insufficient size\");\n\t\tunsigned t = _Left.tbegin() - 1;\n\t\tuint32 LdFt = _Left[t+1].diff();\n\t\tuint32 LdFtp1 = _Left[t+2].diff() - _Left[t+1].getsdr().rotate_left(5).adddiff();\n\t\tuint32 LdFtp2 = _Left[t+3].diff() - _Left[t+2].getsdr().rotate_left(5).adddiff();\n\t\tuint32 LdFtp3 = _Left[t+4].diff() - _Left[t+3].getsdr().rotate_left(5).adddiff();\n\t\tuint32 LdFtp4 = _Left[t+5].diff() - _Left[t+4].getsdr().rotate_left(5).adddiff();\n\t\tuint32 RdFt = _Right[t+1].diff();\n\t\tuint32 RdFtp1 = _Right[t+2].diff() - _Right[t+1].getsdr().rotate_left(5).adddiff();\n\t\tuint32 RdFtp2 = _Right[t+3].diff() - _Right[t+2].getsdr().rotate_left(5).adddiff();\n\t\tuint32 RdFtp3 = _Right[t+4].diff() - _Right[t+3].getsdr().rotate_left(5).adddiff();\n\t\tuint32 RdFtp4 = _Right[t+5].diff() - _Right[t+4].getsdr().rotate_left(5).adddiff();\n\t\tuint32 LdQtp1 = LdFt;\n\t\tuint32 RdQtp1 = RdFt;\n\t\tunsigned b = 0;\n\t\twhile (b < 32+8) {\n\t\t\tif (b < 32 && (LdFt^RdFt)&(1<<b)) break;\n\t\t\tif (b >= 2 && b-2 < 32 && ((LdFtp1^RdFtp1)&(1<<(b-2)))) break;\n\t\t\tif (b >= 4 && b-4 < 32 && ((LdQtp1^RdQtp1)&(1<<(b-4)))) break;\n\t\t\tif (b >= 4 && b-4 < 32 && ((LdFtp2^RdFtp2)&(1<<(b-4)))) break;\n\t\t\tif (b >= 6 && b-6 < 32 && _Left(t+2,b-6) != _Right(t+2,b-6)) break;\n\t\t\tif (b >= 6 && b-6 < 32 && ((LdFtp3^RdFtp3)&(1<<(b-6)))) break;\n\t\t\tif (b >= 8 && b-8 < 32 && _Left(t+3,b-8) != _Right(t+3,b-8)) break;\n\t\t\tif (b >= 8 && b-8 < 32 && ((LdFtp4^RdFtp4)&(1<<(b-8)))) break;\n\t\t\t++b;\n\t\t}\n\t\tif (b == 32+8)\n\t\t\treturn false;\n\t\tif (b < 32) {\n\t\t\tLdFt >>= b; LdFt &= 1; RdFt >>= b; RdFt &= 1;\n\t\t\tif (LdFt < RdFt) return true;\n\t\t\tif (LdFt > RdFt) return false;\n\t\t}\n\t\tif (b >= 2 && b-2 < 32) {\n\t\t\tLdFtp1 >>= b-2; LdFtp1 &= 1; RdFtp1 >>= b-2; RdFtp1 &= 1;\n\t\t\tif (LdFtp1 < RdFtp1) return true;\n\t\t\tif (LdFtp1 > RdFtp1) return false;\n\t\t}\n\t\tif (b >= 4 && b-4 < 32) {\n\t\t\tLdQtp1 >>= b-4; LdQtp1 &= 1; RdQtp1 >>= b-4; RdQtp1 &= 1;\n\t\t\tif (LdQtp1 < RdQtp1) return true;\n\t\t\tif (LdQtp1 > RdQtp1) return false;\t\t\n\t\t\tLdFtp2 >>= b-4; LdFtp2 &= 1; RdFtp2 >>= b-4; RdFtp2 &= 1;\n\t\t\tif (LdFtp2 < RdFtp2) return true;\n\t\t\tif (LdFtp2 > RdFtp2) return false;\n\t\t}\n\t\tif (b >= 6 && b-6 < 32) {\n\t\t\tif (_Left(t+2,b-6) < _Right(t+2,b-6)) return true;\n\t\t\tif (_Left(t+2,b-6) > _Right(t+2,b-6)) return false;\t\t\n\t\t\tLdFtp3 >>= b-6; LdFtp3 &= 1; RdFtp3 >>= b-6; RdFtp3 &= 1;\n\t\t\tif (LdFtp3 < RdFtp3) return true;\n\t\t\tif (LdFtp3 > RdFtp3) return false;\n\t\t}\n\t\tif (b >= 8 && b-8 < 32) {\n\t\t\tif (_Left(t+2,b-8) < _Right(t+2,b-8)) return true;\n\t\t\tif (_Left(t+2,b-8) > _Right(t+2,b-8)) return false;\t\t\n\t\t\tLdFtp4 >>= b-8; LdFtp4 &= 1; RdFtp4 >>= b-8; RdFtp4 &= 1;\n\t\t\tif (LdFtp4 < RdFtp4) return true;\n\t\t\tif (LdFtp4 > RdFtp4) return false;\n\t\t}\n\t\treturn false;\n\t}\n};\n\nstruct diffpathlower_less\n\t: public std::binary_function<sha1differentialpath, sha1differentialpath, bool>\n{\n\tbool operator()(const sha1differentialpath& _Left, const sha1differentialpath& _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() < 4)\n\t\t\tthrow std::runtime_error(\"Lower differential paths of insufficient size\");\n\t\tunsigned t = _Left.tend() - 1;\n\t\tuint32 LdFt = 0 - _Left[t].getsdr().rotate_left(5).adddiff() - _Left[t-4].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp1 = 0 - _Left[t-3].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp2 = 0 - _Left[t-2].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp3 = 0 - _Left[t-1].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp4 = 0 - _Left[t].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdQtm1 = _Left[t-1].diff();\n\t\tuint32 LdQt = _Left[t].diff();\n\t\tuint32 RdFt = 0 - _Right[t].getsdr().rotate_left(5).adddiff() - _Right[t-4].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp1 = 0 - _Right[t-3].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp2 = 0 - _Right[t-2].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp3 = 0 - _Right[t-1].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp4 = 0 - _Right[t].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdQtm1 = _Right[t-1].diff();\n\t\tuint32 RdQt = _Right[t].diff();\n\t\tunsigned b = 0;\n\t\twhile (b < 32+8) {\n\t\t\tif (b < 32) {\n\t\t\t\tif (_Left(t-3,(b+2)&31)!=_Right(t-3,(b+2)&31)) break;\n\t\t\t\tif (_Left(t-2,(b+2)&31)!=_Right(t-2,(b+2)&31)) break;\n\t\t\t\tif ((LdFt^RdFt)&(1<<b)) break;\n\t\t\t\tif ((LdQtm1^RdQtm1)&(1<<b)) break;\n\t\t\t}\n\t\t\tif (b >= 2 && b-2 < 32) {\n\t\t\t\tif ((LdFtp1^RdFtp1)&(1<<(b-2))) break;\n\t\t\t\tif ((LdQt^RdQt)&(1<<(b-2))) break;\n\t\t\t}\n\t\t\tif (b >= 4 && b-4 < 32 && ((LdFtp2^RdFtp2)&(1<<(b-4)))) break;\n\t\t\tif (b >= 6 && b-6 < 32 && ((LdFtp3^RdFtp3)&(1<<(b-6)))) break;\n\t\t\tif (b >= 8 && b-8 < 32 && ((LdFtp4^RdFtp4)&(1<<(b-8)))) break;\n\t\t\t++b;\n\t\t}\n\t\tif (b == 32+8)\n\t\t\treturn false;\n\t\tif (b < 32) {\n\t\t\tLdFt >>= b; LdFt &= 1; RdFt >>= b; RdFt &= 1;\n\t\t\tif (LdFt < RdFt) return true;\n\t\t\tif (LdFt > RdFt) return false;\n\t\t\tLdQtm1 >>= b; LdQtm1 &= 1; RdQtm1 >>= b; RdQtm1 &= 1;\n\t\t\tif (LdQtm1 < RdQtm1) return true;\n\t\t\tif (LdQtm1 > RdQtm1) return false;\n\t\t\tif (_Left(t-3,(b+2)&31) < _Right(t-3,(b+2)&31)) return true;\n\t\t\tif (_Left(t-3,(b+2)&31) > _Right(t-3,(b+2)&31)) return false;\n\t\t\tif (_Left(t-2,(b+2)&31) < _Right(t-2,(b+2)&31)) return true;\n\t\t\tif (_Left(t-2,(b+2)&31) > _Right(t-2,(b+2)&31)) return false;\n\t\t}\n\t\tif (b >= 2 && b-2 < 32) {\n\t\t\tLdFtp1 >>= b-2; LdFtp1 &= 1; RdFtp1 >>= b-2; RdFtp1 &= 1;\n\t\t\tif (LdFtp1 < RdFtp1) return true;\n\t\t\tif (LdFtp1 > RdFtp1) return false;\n\t\t\tLdQt >>= b-2; LdQt &= 1; RdQt >>= b-2; RdQt &= 1;\n\t\t\tif (LdQt < RdQt) return true;\n\t\t\tif (LdQt > RdQt) return false;\n\t\t}\n\t\tif (b >= 4 && b-4 < 32) {\n\t\t\tLdFtp2 >>= b-4; LdFtp2 &= 1; RdFtp2 >>= b-4; RdFtp2 &= 1;\n\t\t\tif (LdFtp2 < RdFtp2) return true;\n\t\t\tif (LdFtp2 > RdFtp2) return false;\n\t\t}\n\t\tif (b >= 6 && b-6 < 32) {\n\t\t\tLdFtp3 >>= b-6; LdFtp3 &= 1; RdFtp3 >>= b-6; RdFtp3 &= 1;\n\t\t\tif (LdFtp3 < RdFtp3) return true;\n\t\t\tif (LdFtp3 > RdFtp3) return false;\n\t\t}\n\t\tif (b >= 8 && b-8 < 32) {\n\t\t\tLdFtp4 >>= b-8; LdFtp4 &= 1; RdFtp4 >>= b-8; RdFtp4 &= 1;\n\t\t\tif (LdFtp4 < RdFtp4) return true;\n\t\t\tif (LdFtp4 > RdFtp4) return false;\n\t\t}\n\t\treturn false;\n\t}\n};\n\nstruct diffpathlower_less_weight\n\t: public std::binary_function<sha1differentialpath, sha1differentialpath, bool>\n{\n\tbool operator()(const sha1differentialpath& _Left, const sha1differentialpath& _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() < 4)\n\t\t\tthrow std::runtime_error(\"Lower differential paths of insufficient size\");\n\t\tunsigned t = _Left.tend() - 1;\n\t\tunsigned lw = _Left[t+1].getsdr().hw() + _Left[t].getsdr().hw();\n\t\tunsigned rw = _Right[t+1].getsdr().hw() + _Right[t].getsdr().hw();\n\t\tif (lw != rw)\n\t\t\treturn lw > rw;\n\t\tuint32 LdFt = 0 - _Left[t].getsdr().rotate_left(5).adddiff() - _Left[t-4].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp1 = 0 - _Left[t-3].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp2 = 0 - _Left[t-2].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp3 = 0 - _Left[t-1].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdFtp4 = 0 - _Left[t].getsdr().rotate_left(30).adddiff();\n\t\tuint32 LdQtm1 = _Left[t-1].diff();\n\t\tuint32 LdQt = _Left[t].diff();\n\t\tuint32 RdFt = 0 - _Right[t].getsdr().rotate_left(5).adddiff() - _Right[t-4].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp1 = 0 - _Right[t-3].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp2 = 0 - _Right[t-2].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp3 = 0 - _Right[t-1].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdFtp4 = 0 - _Right[t].getsdr().rotate_left(30).adddiff();\n\t\tuint32 RdQtm1 = _Right[t-1].diff();\n\t\tuint32 RdQt = _Right[t].diff();\n\t\tunsigned b = 0;\n\t\twhile (b < 32+8) {\n\t\t\tif (b < 32) {\n\t\t\t\tif (_Left(t-3,(b+2)&31)!=_Right(t-3,(b+2)&31)) break;\n\t\t\t\tif (_Left(t-2,(b+2)&31)!=_Right(t-2,(b+2)&31)) break;\n\t\t\t\tif ((LdFt^RdFt)&(1<<b)) break;\n\t\t\t\tif ((LdQtm1^RdQtm1)&(1<<b)) break;\n\t\t\t}\n\t\t\tif (b >= 2 && b-2 < 32) {\n\t\t\t\tif ((LdFtp1^RdFtp1)&(1<<(b-2))) break;\n\t\t\t\tif ((LdQt^RdQt)&(1<<(b-2))) break;\n\t\t\t}\n\t\t\tif (b >= 4 && b-4 < 32 && ((LdFtp2^RdFtp2)&(1<<(b-4)))) break;\n\t\t\tif (b >= 6 && b-6 < 32 && ((LdFtp3^RdFtp3)&(1<<(b-6)))) break;\n\t\t\tif (b >= 8 && b-8 < 32 && ((LdFtp4^RdFtp4)&(1<<(b-8)))) break;\n\t\t\t++b;\n\t\t}\n\t\tif (b == 32+8)\n\t\t\treturn false;\n\t\tif (b < 32) {\n\t\t\tLdFt >>= b; LdFt &= 1; RdFt >>= b; RdFt &= 1;\n\t\t\tif (LdFt < RdFt) return true;\n\t\t\tif (LdFt > RdFt) return false;\n\t\t\tLdQtm1 >>= b; LdQtm1 &= 1; RdQtm1 >>= b; RdQtm1 &= 1;\n\t\t\tif (LdQtm1 < RdQtm1) return true;\n\t\t\tif (LdQtm1 > RdQtm1) return false;\n\t\t\tif (_Left(t-3,(b+2)&31) < _Right(t-3,(b+2)&31)) return true;\n\t\t\tif (_Left(t-3,(b+2)&31) > _Right(t-3,(b+2)&31)) return false;\n\t\t\tif (_Left(t-2,(b+2)&31) < _Right(t-2,(b+2)&31)) return true;\n\t\t\tif (_Left(t-2,(b+2)&31) > _Right(t-2,(b+2)&31)) return false;\n\t\t}\n\t\tif (b >= 2 && b-2 < 32) {\n\t\t\tLdFtp1 >>= b-2; LdFtp1 &= 1; RdFtp1 >>= b-2; RdFtp1 &= 1;\n\t\t\tif (LdFtp1 < RdFtp1) return true;\n\t\t\tif (LdFtp1 > RdFtp1) return false;\n\t\t\tLdQt >>= b-2; LdQt &= 1; RdQt >>= b-2; RdQt &= 1;\n\t\t\tif (LdQt < RdQt) return true;\n\t\t\tif (LdQt > RdQt) return false;\n\t\t}\n\t\tif (b >= 4 && b-4 < 32) {\n\t\t\tLdFtp2 >>= b-4; LdFtp2 &= 1; RdFtp2 >>= b-4; RdFtp2 &= 1;\n\t\t\tif (LdFtp2 < RdFtp2) return true;\n\t\t\tif (LdFtp2 > RdFtp2) return false;\n\t\t}\n\t\tif (b >= 6 && b-6 < 32) {\n\t\t\tLdFtp3 >>= b-6; LdFtp3 &= 1; RdFtp3 >>= b-6; RdFtp3 &= 1;\n\t\t\tif (LdFtp3 < RdFtp3) return true;\n\t\t\tif (LdFtp3 > RdFtp3) return false;\n\t\t}\n\t\tif (b >= 8 && b-8 < 32) {\n\t\t\tLdFtp4 >>= b-8; LdFtp4 &= 1; RdFtp4 >>= b-8; RdFtp4 &= 1;\n\t\t\tif (LdFtp4 < RdFtp4) return true;\n\t\t\tif (LdFtp4 > RdFtp4) return false;\n\t\t}\n\t\treturn false;\n\t}\n};\n\n\n#endif // MAIN_HPP\n", "meta": {"hexsha": "adce3d3406d936b359e6068c6ed6ba2ad29589dc", "size": 24847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/sha1connect/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/sha1connect/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/sha1connect/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": 42.32879046, "max_line_length": 302, "alphanum_fraction": 0.5880790437, "num_tokens": 8821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.026355349978307813, "lm_q1q2_score": 0.010834971218813319}}
{"text": "// Copyright (C) 2007-2011 Garth N. Wells\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// Modified by Anders Logg 2008-2011\n// Modified by Martin Alnes 2008\n//\n// First added:  2007-12-10\n// Last changed: 2011-11-14\n\n#include <string>\n#include <boost/scoped_ptr.hpp>\n#include <dolfin/common/NoDeleter.h>\n#include <dolfin/fem/FiniteElement.h>\n#include <dolfin/function/Function.h>\n#include <dolfin/function/FunctionSpace.h>\n#include <dolfin/function/GenericFunction.h>\n#include <dolfin/log/log.h>\n#include <dolfin/log/LogStream.h>\n#include <dolfin/mesh/Mesh.h>\n#include <dolfin/mesh/MeshData.h>\n#include <dolfin/mesh/MeshEntity.h>\n#include <dolfin/mesh/MeshFunction.h>\n#include \"Form.h\"\n\nusing namespace dolfin;\n\n//-----------------------------------------------------------------------------\nForm::Form(uint rank, uint num_coefficients)\n  : Hierarchical<Form>(*this),\n    dx(*this), ds(*this), dS(*this),\n    _function_spaces(rank), _coefficients(num_coefficients), _rank(rank)\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nForm::Form(boost::shared_ptr<const ufc::form> ufc_form,\n           std::vector<boost::shared_ptr<const FunctionSpace> > function_spaces,\n           std::vector<boost::shared_ptr<const GenericFunction> > coefficients)\n  : Hierarchical<Form>(*this),\n    dx(*this), ds(*this), dS(*this), _ufc_form(ufc_form),\n    _function_spaces(function_spaces), _coefficients(coefficients),\n    _rank(ufc_form->rank())\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nForm::~Form()\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\ndolfin::uint Form::rank() const\n{\n  if (!_ufc_form)\n    return _rank;\n  else\n  {\n    dolfin_assert(_ufc_form->rank() == _rank);\n    return _rank;\n  }\n}\n//-----------------------------------------------------------------------------\ndolfin::uint Form::num_coefficients() const\n{\n  if (!_ufc_form)\n    return _coefficients.size();\n  else\n  {\n    dolfin_assert(_ufc_form->num_coefficients() == _coefficients.size());\n    return _coefficients.size();\n  }\n}\n//-----------------------------------------------------------------------------\nstd::vector<dolfin::uint> Form::coloring(uint entity_dim) const\n{\n  warning(\"Form::coloring does not properly consider form type.\");\n\n  // Get mesh\n  const Mesh& mesh = this->mesh();\n  const uint cell_dim = mesh.topology().dim();\n\n  std::vector<uint> _coloring;\n  if (entity_dim == cell_dim)\n  {\n    _coloring.push_back(cell_dim);\n    _coloring.push_back(0);\n    _coloring.push_back(cell_dim);\n  }\n  else if (entity_dim == cell_dim - 1)\n  {\n    _coloring.push_back(cell_dim - 1);\n    _coloring.push_back(cell_dim);\n    _coloring.push_back(0);\n    _coloring.push_back(cell_dim);\n    _coloring.push_back(cell_dim - 1);\n  }\n  else\n  {\n    dolfin_error(\"Form.cpp\",\n                 \"color form for multicore computing\",\n                 \"Only cell and facet coloring are currently supported\");\n  }\n\n  return _coloring;\n}\n//-----------------------------------------------------------------------------\nvoid Form::set_mesh(boost::shared_ptr<const Mesh> mesh)\n{\n  _mesh = mesh;\n}\n//-----------------------------------------------------------------------------\nconst Mesh& Form::mesh() const\n{\n  // In the case when there are no function spaces (in the case of a\n  // a functional) the (generated) subclass must set the mesh directly\n  // by calling set_mesh().\n\n  // Extract meshes from function spaces\n  std::vector<boost::shared_ptr<const Mesh> > meshes;\n  for (uint i = 0; i < _function_spaces.size(); i++)\n  {\n    if (_function_spaces[i])\n    {\n      dolfin_assert(_function_spaces[i]->mesh());\n      meshes.push_back(_function_spaces[i]->mesh());\n    }\n  }\n\n  // Add common mesh if any\n  if (_mesh)\n    meshes.push_back(_mesh);\n\n  // Extract meshes from coefficients. Note that this is only done\n  // when we don't already have a mesh sine it may otherwise conflict\n  // with existing meshes (if coefficient is defined on another mesh).\n  if (meshes.size() == 0)\n  {\n    for (uint i = 0; i < _coefficients.size(); i++)\n    {\n      const Function* function = dynamic_cast<const Function*>(&*_coefficients[i]);\n      if (function && function->function_space()->mesh())\n        meshes.push_back(function->function_space()->mesh());\n    }\n  }\n\n  // Check that we have at least one mesh\n  if (meshes.size() == 0)\n  {\n    dolfin_error(\"Form.cpp\",\n                 \"extract mesh from form\",\n                 \"No mesh was found. Try passing mesh to the assemble function\");\n  }\n\n  // Check that all meshes are the same\n  for (uint i = 1; i < meshes.size(); i++)\n  {\n    if (meshes[i] != meshes[i - 1])\n    {\n      dolfin_error(\"Form.cpp\",\n                   \"extract mesh from form\",\n                   \"Non-matching meshes for function spaces\");\n    }\n  }\n\n  // Return first mesh\n  dolfin_assert(meshes[0]);\n  return *meshes[0];\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const dolfin::Mesh> Form::mesh_shared_ptr() const\n{\n  return _mesh;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const FunctionSpace> Form::function_space(uint i) const\n{\n  dolfin_assert(i < _function_spaces.size());\n  return _function_spaces[i];\n}\n//-----------------------------------------------------------------------------\nstd::vector<boost::shared_ptr<const FunctionSpace> > Form::function_spaces() const\n{\n  return _function_spaces;\n}\n//-----------------------------------------------------------------------------\nvoid Form::set_coefficient(uint i,\n                           boost::shared_ptr<const GenericFunction> coefficient)\n{\n  dolfin_assert(i < _coefficients.size());\n  _coefficients[i] = coefficient;\n}\n//-----------------------------------------------------------------------------\nvoid Form::set_coefficient(std::string name,\n                           boost::shared_ptr<const GenericFunction> coefficient)\n{\n  set_coefficient(coefficient_number(name), coefficient);\n}\n//-----------------------------------------------------------------------------\nvoid Form::set_coefficients(std::map<std::string, boost::shared_ptr<const GenericFunction> > coefficients)\n{\n  std::map<std::string, boost::shared_ptr<const GenericFunction> >::iterator it;\n  for (it = coefficients.begin(); it != coefficients.end(); ++it)\n    set_coefficient(it->first, it->second);\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const GenericFunction> Form::coefficient(uint i) const\n{\n  dolfin_assert(i < _coefficients.size());\n  return _coefficients[i];\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const GenericFunction> Form::coefficient(std::string name) const\n{\n  return coefficient(coefficient_number(name));\n}\n//-----------------------------------------------------------------------------\nstd::vector<boost::shared_ptr<const GenericFunction> > Form::coefficients() const\n{\n  return _coefficients;\n}\n//-----------------------------------------------------------------------------\ndolfin::uint Form::coefficient_number(const std::string & name) const\n{\n  // TODO: Dissect name, assuming \"wi\", and return i.\n  dolfin_not_implemented();\n  return 0;\n}\n//-----------------------------------------------------------------------------\nstd::string Form::coefficient_name(uint i) const\n{\n  // Create name like \"w0\", overloaded by Form subclasses generated by form compilers\n  std::ostringstream name;\n  name << \"w\" << i;\n  return name.str();\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const MeshFunction<dolfin::uint> >\nForm::cell_domains_shared_ptr() const\n{\n  return _cell_domains;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const MeshFunction<dolfin::uint> >\nForm::exterior_facet_domains_shared_ptr() const\n{\n  return _exterior_facet_domains;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const MeshFunction<dolfin::uint> >\nForm::interior_facet_domains_shared_ptr() const\n{\n  return _interior_facet_domains;\n}\n//-----------------------------------------------------------------------------\nvoid Form::set_cell_domains\n(boost::shared_ptr<const MeshFunction<uint> > cell_domains)\n{\n  _cell_domains = cell_domains;\n}\n//-----------------------------------------------------------------------------\nvoid Form::set_exterior_facet_domains\n(boost::shared_ptr<const MeshFunction<uint> > exterior_facet_domains)\n{\n  _exterior_facet_domains = exterior_facet_domains;\n}\n//-----------------------------------------------------------------------------\nvoid Form::set_interior_facet_domains\n(boost::shared_ptr<const MeshFunction<uint> > interior_facet_domains)\n{\n  _interior_facet_domains = interior_facet_domains;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const ufc::form> Form::ufc_form() const\n{\n  return _ufc_form;\n}\n//-----------------------------------------------------------------------------\nvoid Form::check() const\n{\n  dolfin_assert(_ufc_form);\n\n  // Check that the number of argument function spaces is correct\n  if (_ufc_form->rank() != _function_spaces.size())\n  {\n    dolfin_error(\"Form.cpp\",\n                 \"assemble form\",\n                 \"Expecting %d function spaces (not %d)\",\n                 _ufc_form->rank(), _function_spaces.size());\n  }\n\n  // Check that the number of coefficient function spaces is correct\n  if (_ufc_form->num_coefficients() != _coefficients.size())\n  {\n   dolfin_error(\"Form.cpp\",\n                \"assemble form\",\n                \"Expecting %d coefficient (not %d)\",\n                _ufc_form->num_coefficients(), _coefficients.size());\n  }\n\n  // Check argument function spaces\n  for (uint i = 0; i < _function_spaces.size(); ++i)\n  {\n    boost::scoped_ptr<ufc::finite_element> element(_ufc_form->create_finite_element(i));\n    dolfin_assert(element);\n    dolfin_assert(_function_spaces[i]->element());\n    if (element->signature() != _function_spaces[i]->element()->signature())\n    {\n      log(ERROR, \"Expected element: %s\", element->signature());\n      log(ERROR, \"Input element:    %s\", _function_spaces[i]->element()->signature().c_str());\n      dolfin_error(\"Form.cpp\",\n                   \"assemble form\",\n                   \"Wrong type of function space for argument %d\", i);\n    }\n  }\n}\n//-----------------------------------------------------------------------------\nEquation Form::operator==(const Form& rhs) const\n{\n  Equation equation(reference_to_no_delete_pointer(*this),\n                    reference_to_no_delete_pointer(rhs));\n  return equation;\n}\n//-----------------------------------------------------------------------------\nEquation Form::operator==(int rhs) const\n{\n  Equation equation(reference_to_no_delete_pointer(*this), 0);\n  return equation;\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "dbe82bc8c8963d789bd95a1eb3199bed7dac497b", "size": 11751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/fem/Form.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/fem/Form.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/fem/Form.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.1598837209, "max_line_length": 106, "alphanum_fraction": 0.5471023743, "num_tokens": 2422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535942, "lm_q2_score": 0.044680865661299037, "lm_q1q2_score": 0.010821957159488254}}
{"text": "// Copyright (c) 2014, Sailing Lab\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\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 <ORGANIZATION> nor the names of its contributors\n// may be used to endorse or promote products derived from this software\n// without specific prior written permission.\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 * Least-squares Matrix Factorization application built on Petuum Parameter Server.\n *\n * Author: qho\n */\n#include <vector>\n#include <fstream>\n#include <cstdint>\n#include <random>\n\n#include <petuum_ps_common/include/petuum_ps.hpp>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <pthread.h>\n\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include \"matrixloader.hpp\"\n\n// Command-line flags\nDEFINE_string(hostfile, \"\", \"Path to Petuum PS server configuration file\");\nDEFINE_int32(ps_row_in_memory_limit, 1000, \"Single-machine version only: max # rows of L, R that can be held in memory\");\nDEFINE_int32(ps_row_cache_size, 0, \"Max # rows of L, R that can be cached per client; set to 0 (default) to cache all rows. If you are running out of memory due to big L, R, consider limiting the cache size. No effect for single-machine version.\");\nDEFINE_string(datafile, \"\", \"Input sparse matrix\");\nDEFINE_string(offsetsfile, \"\", \"Offsets file for datafile - if provided, the program will run in disk-based mode to save memory\");\nDEFINE_string(output_prefix, \"\", \"Output results with this prefix. If the prefix is X, the output will be called X.L and X.R\");\nDEFINE_double(lambda, 0.0, \"L2 regularization strength; 0 disables\");\nDEFINE_double(init_step_size, 0.5, \"SGD step size at iteration t is init_step_size * (step_size_offset + t)^(-step_size_pow)\");\nDEFINE_double(step_size_offset, 100.0, \"SGD step size at iteration t is init_step_size * (step_size_offset + t)^(-step_size_pow)\");\nDEFINE_double(step_size_pow, 0.5, \"SGD step size at iteration t is init_step_size * (step_size_offset + t)^(-step_size_pow)\");\nDEFINE_int32(rng_seed, 967234, \"RNG seed for initializing factor matrices L, R\");\nDEFINE_int32(num_clients, 1, \"Total number of clients\");\nDEFINE_int32(num_worker_threads, 1, \"Number of worker threads per client\");\nDEFINE_int32(client_id, 0, \"This client's ID\");\nDEFINE_int32(K, 100, \"Factorization rank\");\nDEFINE_int32(num_iterations, 100, \"Number of iterations\");\nDEFINE_int32(staleness, 0, \"Staleness\");\nDEFINE_string(ps_stats_path, \"\", \"Petuum PS statistics output file\");\nDEFINE_int32(ps_snapshot_clock, 0, \"How often to take PS snapshots; 0 disables\");\nDEFINE_int32(ps_resume_clock, 0, \"If nonzero, resume from the PS snapshot with this ID\");\nDEFINE_string(ps_snapshot_dir, \"\", \"Where to save PS snapshots\");\nDEFINE_string(ps_resume_dir, \"\", \"Where to retrieve PS snapshots for resuming\");\n\n// Typedefs\ntypedef std::pair<int,float> int_pair_float_t;\n\n// Data variables\nmatrixloader::AbstractMatrixLoader* data_matrix;\n\n// Returns the number of workers threads across all clients\nint get_total_num_workers() {\n  return FLAGS_num_clients * FLAGS_num_worker_threads;\n}\n// Returns the global thread ID of this worker\nint get_global_worker_id(int local_thread_id) {\n  return (FLAGS_client_id * FLAGS_num_worker_threads) + local_thread_id;\n}\n\n// Performs stochastic gradient descent on the (i,j)-th element of the matrix,\n// which takes value Xij.\nvoid sgd_element(const int i, const int j, const float Xij, float step_size, int global_worker_id,\n                 petuum::Table<float>& L_table,\n                 petuum::Table<float>& R_table,\n                 petuum::Table<float>& loss_table) {\n  // Read L(i,:) and R(:,j) from Petuum PS\n  petuum::RowAccessor Li_acc;\n  petuum::RowAccessor Rj_acc;\n  L_table.Get(i, &Li_acc);\n  R_table.Get(j, &Rj_acc);\n  const petuum::DenseRow<float>& Li = Li_acc.Get<petuum::DenseRow<float> >();\n  const petuum::DenseRow<float>& Rj = Rj_acc.Get<petuum::DenseRow<float> >();\n  \n  // Compute L(i,:) * R(:,j)\n  float LiRj = 0.0;\n  for (int k = 0; k < FLAGS_K; ++k) {\n    LiRj += Li[k] * Rj[k];\n  }\n  // Update the loss function (does not include L2 regularizer term)\n  loss_table.Inc(0,global_worker_id,pow(Xij - LiRj, 2));\n  \n  // Now update L(i,:) and R(:,j) based on the loss function at X(i,j).\n  // The non-regularized loss function at X(i,j) is ( X(i,j) - L(i,:)*R(:,j) )^2.\n  //\n  // The non-regularized gradient w.r.t. L(i,k) is -2*X(i,j)R(k,j) + 2*L(i,:)*R(:,j)*R(k,j).\n  // The non-regularized gradient w.r.t. R(k,j) is -2*X(i,j)L(i,k) + 2*L(i,:)*R(:,j)*L(i,k).\n  petuum::UpdateBatch<float> Li_update;\n  petuum::UpdateBatch<float> Rj_update;\n  for (int k = 0; k < FLAGS_K; ++k) {\n    float gradient = 0.0;\n    // Compute update for L(i,k)\n    gradient = -2 * (Xij - LiRj) * Rj[k] + FLAGS_lambda * 2 * Li[k];\n    Li_update.Update(k, -gradient * step_size);\n    // Compute update for R(k,j)\n    gradient = -2 * (Xij - LiRj) * Li[k] + FLAGS_lambda * 2 * Rj[k];\n    Rj_update.Update(k, -gradient * step_size);\n  }\n  // Commit updates to Petuum PS\n  L_table.BatchInc(i,Li_update);\n  R_table.BatchInc(j,Rj_update);\n}\n\n// Initialize the Matrix Factorization solver\nvoid init_mf(petuum::Table<float>& L_table, petuum::Table<float>& R_table) {\n  // Uniform RNG that produces numbers in [-1,1)\n  std::mt19937 generator(FLAGS_rng_seed);\n  std::uniform_real_distribution<> dist(-1.,1.);\n  // Add a random initialization in [-1,1)/num_workers to each element of L and R\n  const int num_workers = get_total_num_workers();\n  for (int i = 0; i < data_matrix->getN(); ++i) {\n    petuum::UpdateBatch<float> L_updates;\n    for (int k = 0; k < FLAGS_K; ++k) {\n      double init_val = dist(generator) / num_workers;\n      L_updates.Update(k,init_val);\n    }\n    L_table.BatchInc(i,L_updates);\n  }\n  for (int j = 0; j < data_matrix->getM(); ++j) {\n    petuum::UpdateBatch<float> R_updates;\n    for (int k = 0; k < FLAGS_K; ++k) {\n      double init_val = dist(generator) / num_workers;\n      R_updates.Update(k,init_val);\n    }\n    R_table.BatchInc(j,R_updates);\n  }\n}\n\n// Outputs L_table and R_table to disk\nvoid output_to_disk(petuum::Table<float>& L_table, petuum::Table<float>& R_table) {\n  // L_table\n  std::string L_file = FLAGS_output_prefix + \".L\";\n  std::ofstream L_stream(L_file.c_str());\n  for (uint32_t i = 0; i < data_matrix->getN(); ++i) {\n    petuum::RowAccessor Li_acc;\n    L_table.Get(i, &Li_acc);\n    const petuum::DenseRow<float>& Li = Li_acc.Get<petuum::DenseRow<float> >();\n    for (uint32_t k = 0; k < FLAGS_K; ++k) {\n      L_stream << Li[k] << \" \";\n    }\n    L_stream << \"\\n\";\n  }\n  L_stream.close();\n  // R_table\n  std::string R_file = FLAGS_output_prefix + \".R\";\n  std::ofstream R_stream(R_file.c_str());\n  for (uint32_t j = 0; j < data_matrix->getM(); ++j) {\n    petuum::RowAccessor Rj_acc;\n    R_table.Get(j, &Rj_acc);\n    const petuum::DenseRow<float>& Rj = Rj_acc.Get<petuum::DenseRow<float> >();\n    for (uint32_t k = 0; k < FLAGS_K; ++k) {\n      R_stream << Rj[k] << \" \";\n    }\n    R_stream << \"\\n\";\n  }\n  R_stream.close();\n}\n\n// Main Matrix Factorization routine, called by pthread_create\nvoid* solve_mf(void* args) {\n  int local_thread_id = *reinterpret_cast<int*>(args);\n  // Register this thread with Petuum PS\n  petuum::PSTableGroup::RegisterThread();\n  // Get tables\n  petuum::Table<float> L_table = petuum::PSTableGroup::GetTableOrDie<float>(0);\n  petuum::Table<float> R_table = petuum::PSTableGroup::GetTableOrDie<float>(1);\n  petuum::Table<float> loss_table = petuum::PSTableGroup::GetTableOrDie<float>(2);\n  // Initialize MF solver\n  const int total_num_workers = get_total_num_workers();\n  const int global_worker_id = get_global_worker_id(local_thread_id); // global_worker_id lies in the range [0,total_num_workers)\n  STATS_APP_INIT_BEGIN();\n  if (FLAGS_ps_resume_clock == 0) { // Only initialize L, R tables if not resuming\n    init_mf(L_table,R_table);\n  } else if (global_worker_id == 0) {\n    std::cout << \"...Resuming at Iteration \" << FLAGS_ps_resume_clock-FLAGS_staleness\n              << \" (Snapshot \" << FLAGS_ps_resume_clock << \")\" << std::endl;\n  }\n  petuum::PSTableGroup::GlobalBarrier();  // Let stale values finish propagating (performs staleness+1 clock()s)\n  STATS_APP_INIT_END();\n  // Run MF solver\n  for (int iter = 0; iter < FLAGS_num_iterations; ++iter) {\n    // If resuming, skip iterations until we reach the correct iteration\n    if (iter < FLAGS_ps_resume_clock-FLAGS_staleness-1) {\n      petuum::PSTableGroup::Clock();\n      continue;\n    }\n    \n    // Begin iteration\n    boost::posix_time::ptime beginT = boost::posix_time::microsec_clock::local_time();\n    if (global_worker_id == 0) {\n      std::cout << \"Iteration \" << iter+1 << \"/\" << FLAGS_num_iterations << \"... \" << std::flush;\n    }\n    // Clear loss function table\n    petuum::RowAccessor loss_acc;\n    loss_table.Get(0, &loss_acc);\n    const petuum::DenseRow<float>& loss_row = loss_acc.Get<petuum::DenseRow<float> >();\n    loss_table.Inc(0,global_worker_id,-loss_row[global_worker_id]);\n    \n    // Divide matrix elements across workers, and perform SGD\n    bool last_el = false;\n    int64_t row,col;\n    float val;\n    STATS_APP_ACCUM_COMP_BEGIN();\n    float step_size = FLAGS_init_step_size * pow(FLAGS_step_size_offset + iter, -FLAGS_step_size_pow);\n    while (last_el == false) {\n      data_matrix->getNextEl(global_worker_id,row,col,val,last_el);\n      sgd_element(row,col,val,step_size,global_worker_id,L_table,R_table,loss_table);\n    }\n    STATS_APP_ACCUM_COMP_END();\n    \n    // Output loss function (does not include L2 regularizer term)\n    if (global_worker_id == 0) {\n      petuum::RowAccessor loss_acc;\n      loss_table.Get(0, &loss_acc);\n      const petuum::DenseRow<float>& loss_row = loss_acc.Get<petuum::DenseRow<float> >();\n      float loss = 0.0;\n      for (int t = 0; t < total_num_workers; ++t) {\n        loss += loss_row[t];\n      }\n      std::cout << \"loss function = \" << loss << \"... \" << std::flush;\n    }\n    // Advance Parameter Server iteration\n    petuum::PSTableGroup::Clock();\n    boost::posix_time::time_duration elapTime = boost::posix_time::microsec_clock::local_time() - beginT;\n    if (global_worker_id == 0) {\n      std::cout << \"elapsed time = \" << ((float) elapTime.total_milliseconds()) / 1000 << std::endl;\n    }\n  }\n  // Let stale values finish propagating (performs staleness+1 clock()s)\n  petuum::PSTableGroup::GlobalBarrier();\n  // Output results to disk\n  if (global_worker_id == 0) {\n    std::cout << \"Outputting results to prefix \" << FLAGS_output_prefix << \" ... \" << std::flush;\n    output_to_disk(L_table,R_table);\n    std::cout << \"done\" << std::endl;\n  }\n  // Deregister this thread with Petuum PS\n  petuum::PSTableGroup::DeregisterThread();\n  return 0;\n}\n\n// Main function\nint main(int argc, char *argv[]) {\n  google::ParseCommandLineFlags(&argc, &argv, true);\n  google::InitGoogleLogging(argv[0]);\n  boost::posix_time::ptime beginT = boost::posix_time::microsec_clock::local_time();\n  \n  // Configure Petuum PS\n  petuum::TableGroupConfig table_group_config;\n  // Global parameters for the whole PS system\n  table_group_config.num_total_server_threads = FLAGS_num_clients;  // 1 server thread per client\n  table_group_config.num_total_bg_threads = FLAGS_num_clients;  // 1 background thread per client\n  table_group_config.num_total_clients = FLAGS_num_clients;\n  table_group_config.num_tables = 3;  // L_table, R_table, loss_table\n  // Single-node-PS versus multi-machine PS\n#ifdef PETUUM_SINGLE_NODE\n  table_group_config.ooc_path_prefix = FLAGS_output_prefix + \".matrixfact_sn.localooc\";\n  table_group_config.consistency_model = petuum::LocalOOC;\n#else\n  petuum::GetHostInfos(FLAGS_hostfile, &table_group_config.host_map);\n  petuum::GetServerIDsFromHostMap(&table_group_config.server_ids, table_group_config.host_map);\n  table_group_config.consistency_model = petuum::SSPPush;\n#endif\n  // Local parameters for this process\n  table_group_config.num_local_server_threads = 1;\n  table_group_config.num_local_bg_threads = 1;\n  table_group_config.num_local_app_threads = FLAGS_num_worker_threads + 1;  // +1 for main() thread\n  table_group_config.client_id = FLAGS_client_id;\n  // Stats and snapshots\n  table_group_config.stats_path = FLAGS_ps_stats_path;\n  table_group_config.snapshot_clock = FLAGS_ps_snapshot_clock;  // Only for multi-machine PS\n  table_group_config.resume_clock = FLAGS_ps_resume_clock;  // Only for multi-machine PS\n  table_group_config.snapshot_dir = FLAGS_ps_snapshot_dir;  // Only for multi-machine PS\n  table_group_config.resume_dir = FLAGS_ps_resume_dir;  // Only for multi-machine PS\n  // Configure PS row types\n  petuum::PSTableGroup::RegisterRow<petuum::DenseRow<float> >(0);  // Register dense rows as ID 0\n  // Start PS\n  // IMPORTANT: This command starts up the name node service on client 0.\n  //            We therefore do it ASAP, before other lengthy actions like\n  //            loading data.\n  petuum::PSTableGroup::Init(table_group_config, false);  // Initializing thread does not need table access\n  \n  // Load Data\n  STATS_APP_LOAD_DATA_BEGIN();\n  if (FLAGS_offsetsfile.size() == 0) { // Load the full matrix\n    if (FLAGS_client_id == 0) {\n      std::cout << \"Data mode: Loading matrix \" << FLAGS_datafile << \" into memory...\" << std::endl;\n    }\n    data_matrix = new matrixloader::StandardMatrixLoader(FLAGS_datafile,get_total_num_workers());\n  } else { // Disk-based loader\n    if (FLAGS_client_id == 0) {\n      std::cout << \"Data mode: Streaming matrix \" << FLAGS_datafile << \" from disk using offsets \" << FLAGS_offsetsfile << std::endl;\n    }\n    auto dml = new matrixloader::DiskMatrixLoader(FLAGS_datafile,FLAGS_offsetsfile,get_total_num_workers());\n    for (int t = 0; t < FLAGS_num_worker_threads; ++t) {  // Initialize workers\n      dml->initWorker(get_global_worker_id(t));\n    }\n    data_matrix = dml;\n  }\n  STATS_APP_LOAD_DATA_END();\n  \n  // Output statistics\n  if (FLAGS_client_id == 0) {\n    std::cout << \"Matrix dimensions: \" << data_matrix->getN() << \" by \" << data_matrix->getM() << std::endl;\n    std::cout << \"# non-missing entries: \" << data_matrix->getNNZ() << std::endl;\n    std::cout << \"Factorization rank: \" << FLAGS_K << std::endl;\n    std::cout << \"# client machines: \" << FLAGS_num_clients << std::endl;\n    std::cout << \"# worker threads per client: \" << FLAGS_num_worker_threads << std::endl;\n    std::cout << \"SSP staleness: \" << FLAGS_staleness << std::endl;\n    std::cout << \"Step size formula: \" << FLAGS_init_step_size << \" * (\" << FLAGS_step_size_offset << \" + t)^(-\" << FLAGS_step_size_pow << \")\" << std::endl;\n    std::cout << \"Regularization strength lambda: \" << FLAGS_lambda << std::endl;\n    std::cout << \"  (Note: displayed loss function does not include regularization term)\" << std::endl;\n  }\n  \n  // Configure PS tables\n  petuum::ClientTableConfig table_config;\n  table_config.table_info.row_type = 0; // Dense rows\n  table_config.oplog_capacity = 100;\n  // L_table (N by K)\n  table_config.table_info.table_staleness = FLAGS_staleness;\n  table_config.table_info.row_capacity = FLAGS_K;\n#ifdef PETUUM_SINGLE_NODE\n  table_config.process_cache_capacity = FLAGS_ps_row_in_memory_limit;\n#else\n  if (FLAGS_ps_row_cache_size == 0) {\n    table_config.process_cache_capacity = data_matrix->getN();\n  } else {\n    table_config.process_cache_capacity = FLAGS_ps_row_cache_size;\n  }\n#endif\n  petuum::PSTableGroup::CreateTable(0,table_config);\n  // R_table (M by K)\n  table_config.table_info.table_staleness = FLAGS_staleness;\n  table_config.table_info.row_capacity = FLAGS_K;\n#ifdef PETUUM_SINGLE_NODE\n  table_config.process_cache_capacity = FLAGS_ps_row_in_memory_limit;\n#else\n  if (FLAGS_ps_row_cache_size == 0) {\n    table_config.process_cache_capacity = data_matrix->getM();\n  } else {\n    table_config.process_cache_capacity = FLAGS_ps_row_cache_size;\n  }\n#endif\n  petuum::PSTableGroup::CreateTable(1,table_config);\n  // loss_table (1 by total # workers)\n  table_config.table_info.table_staleness = 0;  // No staleness for loss table\n  table_config.table_info.row_capacity = get_total_num_workers();\n  table_config.process_cache_capacity = 1;\n  petuum::PSTableGroup::CreateTable(2,table_config);\n  // Finished creating tables\n  petuum::PSTableGroup::CreateTableDone();\n  \n  // Run Petuum PS-based MF solver\n  pthread_t* threads = new pthread_t[FLAGS_num_worker_threads];\n  int* local_thread_ids = new int[FLAGS_num_worker_threads];\n  for (int t = 0; t < FLAGS_num_worker_threads; ++t) {\n    local_thread_ids[t] = t;\n    pthread_create(threads+t, NULL, solve_mf, local_thread_ids+t);\n  }\n  petuum::PSTableGroup::WaitThreadRegister();\n  for (int t = 0; t < FLAGS_num_worker_threads; ++t) {\n    pthread_join(threads[t], NULL);\n  }\n  delete threads;\n  delete local_thread_ids;\n  delete data_matrix;\n  \n  // Cleanup and output runtime\n  petuum::PSTableGroup::ShutDown();\n  boost::posix_time::time_duration elapTime = boost::posix_time::microsec_clock::local_time() - beginT;\n  if (FLAGS_client_id == 0) {\n    std::cout << \"total runtime = \" << ((float) elapTime.total_milliseconds()) / 1000 << \"s\" << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "321fb409afd5d18136635046c33e692bc315d0cb", "size": 18201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/matrixfact/src/matrixfact.cpp", "max_stars_repo_name": "ForrestGan/public", "max_stars_repo_head_hexsha": "2cada36c4b523cf80f16a4f0d0fdc01166a69df1", "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": "apps/matrixfact/src/matrixfact.cpp", "max_issues_repo_name": "ForrestGan/public", "max_issues_repo_head_hexsha": "2cada36c4b523cf80f16a4f0d0fdc01166a69df1", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/matrixfact/src/matrixfact.cpp", "max_forks_repo_name": "ForrestGan/public", "max_forks_repo_head_hexsha": "2cada36c4b523cf80f16a4f0d0fdc01166a69df1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.276119403, "max_line_length": 248, "alphanum_fraction": 0.706719411, "num_tokens": 4897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478896, "lm_q2_score": 0.030675801378361855, "lm_q1q2_score": 0.010804071911206154}}
{"text": "/*\n  Author(s):      Robert Patterson and Markus Sander\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the DimerInception class declared in the\n    swp_DimerInception.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Prof Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_dimer_inception.h\"\n\n#include \"swp_mechanism.h\"\n#include \"swp_primary.h\"\n\n#include <boost/random/uniform_01.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::Processes;\nusing namespace std;\n\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (protected).\nDimerInception::DimerInception(void)\n: Inception(), m_kfm(0.0), m_ksf1(0.0), m_ksf2(0.0), m_efm(2.2)\n{\n    m_name = \"DimerInception\";\n}\n\n// Initialising constructor.\nDimerInception::DimerInception(const Sweep::Mechanism &mech)\n: Inception(mech), m_kfm(0.0), m_ksf1(0.0), m_ksf2(0.0),\n  m_efm(mech.GetEnhancementFM())\n{\n    m_name = \"DimerInception\";\n}\n\n// Copy constructor.\nDimerInception::DimerInception(const DimerInception &copy)\n: m_efm(copy.m_efm)\n{\n    *this = copy;\n}\n\n// Stream-reading constructor.\nDimerInception::DimerInception(std::istream &in, const Sweep::Mechanism &mech)\n: m_efm(mech.GetEnhancementFM())\n{\n    Deserialize(in, mech);\n}\n\n// Default destructor.\nDimerInception::~DimerInception(void)\n{\n}\n\n// OPERATOR OVERLOADS.\n\n// Assignment operator.\nDimerInception &DimerInception::operator =(const DimerInception &rhs)\n{\n    if (this != &rhs) {\n        Inception::operator =(rhs);\n        m_kfm  = rhs.m_kfm;\n        m_ksf1 = rhs.m_ksf1;\n        m_ksf2 = rhs.m_ksf2;\n    }\n    return *this;\n}\n\n/*!\n * Create a new particle and add it to the ensemble with position uniformly\n * distributed over the grid cell.\n *\n * The iterm parameter is included because it will be needed for many process\n * types and this function is meant to have a general signature.\n *\n * \\param[in]       t               Time\n * \\param[in]       local_geom      Details of geometry around current location\n * \\param[in,out]   sys             System to update\n * \\param[in]       iterm           Process term responsible for this event\n * \\param[in,out]   rng             Random number generator\n *\n * \\return      0 on success, otherwise negative.\n */\nint DimerInception::Perform(const double t, Cell &sys,\n                            const Geometry::LocalGeometry1d &local_geom,\n                            const unsigned int iterm,\n                            rng_type &rng) const {\n\n    // This routine performs the inception on the given chemical system.\n\n    // Check if hybrid particle-number/particle model\n    // If not, add particle to ensemble.\n    if (!m_mech->IsHybrid())\n    {\n    // Create a new particle of the type specified\n    // by the system ensemble.\n    Particle *sp = m_mech->CreateParticle(t);\n\t//Incepting first PAH from inception list.\n\n    // Get the cell vertices\n    fvector vertices = local_geom.cellVertices();\n\n    // Sample a uniformly distributed position, note that this method\n    // works whether the vertices come in increasing or decreasing order,\n    // but 1d is assumed for now.\n    double posn = vertices.front();\n\n    const double width = vertices.back() - posn;\n    boost::uniform_01<rng_type&, double> uniformGenerator(rng);\n    posn += width * uniformGenerator();\n\n    sp->setPositionAndTime(posn, t);\n\n\n    // Initialise the new particle.\n    sp->Primary()->SetComposition(ParticleComp());\n    sp->Primary()->SetValues(ParticleTrackers());\n    sp->UpdateCache();\n\n\tdouble spwt = sp->getStatisticalWeight();\n\n    // Add particle to system's ensemble.\n    sys.Particles().Add(*sp, rng);\n\n    // Update gas-phase chemistry of system.\n    if (!sys.GetIsAdiabaticFlag())\n        adjustGas(sys, spwt);\n    // Update gas-phase chemistry and temperature of system.\n    else\n        adjustParticleTemperature(sys, spwt, 1, ParticleComp()[0], 1);\n    }\n    else\n    {\n        // Adjust particle number properties\n        sys.Particles().UpdateNumberAtIndex(ParticleComp()[0], 1);\n        sys.Particles().UpdateTotalParticleNumber(1);\n        sys.Particles().UpdateTotalsWithIndex(ParticleComp()[0], 1.0);\n\n        // Update gas-phase chemistry of system.\n        if (!sys.GetIsAdiabaticFlag())\n            adjustGas(sys, 1);\n        // Update gas-phase chemistry and temperature of system.\n        else\n            adjustParticleTemperature(sys, 1, 1, ParticleComp()[0], 1);\n    }\n\n    return 0;\n}\n\n// PERFORMING THE PROCESS.\n\n\n// INCEPTION KERNEL.\n\n/*!\n * The inception rate is based on a transition coagulation kernel that\n * is calculated using a molecule diameter and mass.  These values do not\n * have to correspond the the physical properties of the molecule, but they\n * are fed into the transition regime kernel.\n *\n * @param[in]    m1    mass of first molecule\n * @param[in]    m2    mass of second molecule\n * @param[in]    d1    diameter of first molecule\n * @param[in]    d2    diameter of second molecule\n */\nvoid DimerInception::SetInceptingSpecies(double m1, double m2, double d1, double d2)\n{\n    // The free mol part can be handled by the free mol specific method\n    SetInceptingSpeciesFreeMol(m1, m2, d1, d2);\n\n    // Now the slip flow part\n    double invd1=1.0/d1, invd2=1.0/d2;\n    m_ksf1 = CSF * (d1+d2);\n    m_ksf2 = 2.0 * 1.257 * m_ksf1 * ((invd1*invd1) + (invd2*invd2));\n    m_ksf1 = m_ksf1 * (invd1+invd2);\n}\n\n/*!\n * The inception rate is based on a free molecular coagulation kernel only,\n * contrast \\ref SetInceptingSpecies that\n * is calculated using a molecule diameter and mass.  These values do not\n * have to correspond the the physical properties of the molecule, but they\n * are fed into the transition regime kernel.\n *\n * @param[in]    m1    mass of first molecule\n * @param[in]    m2    mass of second molecule\n * @param[in]    d1    diameter of first molecule\n * @param[in]    d2    diameter of second molecule\n */\nvoid DimerInception::SetInceptingSpeciesFreeMol(double m1, double m2, double d1, double d2)\n{\n    // This routine sets the free-mol and slip flow kernel parameters given\n    // the mass and diameter of the incepting species.\n    m_kfm  = m_efm * CFM * sqrt((1.0/m1) + (1.0/m2)) * (d1+d2) * (d1+d2);\n    m_ksf1 = 0.0;\n    m_ksf2 = 0.0;\n}\n\n// TOTAL RATE CALCULATIONS.\n\n// Returns rate of the process for the given system.\ndouble DimerInception::Rate(double t, const Cell &sys, const Geometry::LocalGeometry1d &local_geom) const\n{\n    // Get the current chemical conditions.\n    double T = sys.GasPhase().Temperature();\n    double P = sys.GasPhase().Pressure();\n\t\n\t// Calculate the rate.\n\treturn Rate(sys.GasPhase(), sqrt(T),\n                MeanFreePathAir(T,P),\n                sys.SampleVolume());\n}\n\n\n\n/*!\n * Calculate inception rate using a the transition coagulation kernel\n * with the values provided by the user.  The result is this value\n * multiplied by the square of the number concentration of the gas\n * phase species.\n *\n * Requires all the parameters that would otherwise be calculated by\n * the routine to be passed as arguments.\n *\n * @param[in]    gas      Gas phase mixture\n * @param[in]    sqrtT    square root of temperature\n * @param[in]    MFP      mean free path in gas\n * @param[in]    vol      sample volume\n *\n * @return    Inception rate for a cell of size vol. (\\f$ \\mathrm{s}^{-1}\\f$)\n */\ndouble DimerInception::Rate(const EnvironmentInterface &gas, double sqrtT,\n                     double MFP, double vol) const\n{\n    double rate = A() * vol * chemRatePart(gas);\n\n    const double fm   = sqrtT * m_kfm;\n    if((m_ksf1 > 0) || (m_ksf2 > 0))  {\n        const double Temperature = gas.Temperature();\n\n        // Temperature divided by viscosity\n        double T_viscosity = Temperature / gas.Viscosity();\n\n        // Transition regime\n        double sf   = T_viscosity  * (m_ksf1 + (MFP*m_ksf2));\n        rate *= ((fm*sf) / (fm+sf));\n    }\n    else {\n        // Free mol regime only\n        rate *= fm;\n    }\n\n    return rate;\n}\n\n/*!\n * Calculates the gas-phase chemistry contribution to the rate\n * expression.  This is overloaded as Avogadro's number must be\n * included in the terms for inception processes.\n *\n * @param[in]    gas      Gas phase mixture\n */\ndouble DimerInception::chemRatePart(const EnvironmentInterface &gas) const\n{\n    // Factor of 0.5 adjusts for doubling counting of pairs of molecules in the number\n    // of possible collisions.\n    double rate = 0.5;\n\n    Sprog::StoichMap::const_iterator i;\n    for (i=m_reac.begin(); i!=m_reac.end(); ++i) {\n        //std::cerr << \"Mole frac to use \" << fracs[i->first] << std::endl;\n        double conc = gas.SpeciesConcentration(i->first);\n        for (int j=0; j!=i->second; ++j) {\n            rate *= (NA * conc);\n        }\n    }\n\n    return rate;\n}\n\n\n// RATE TERM CALCULATIONS.\n\n// Returns the number of rate terms for this process (one).\nunsigned int DimerInception::TermCount(void) const {return 1;}\n\n// Calculates the rate terms given an iterator to a double vector. The\n// iterator is advanced to the position after the last term for this\n// process.  Returns the sum of all terms.\ndouble DimerInception::RateTerms(const double t, const Cell &sys,\n                               const Geometry::LocalGeometry1d &local_geom,\n                               fvector::iterator &iterm) const\n{\n    // Get the current chemical conditions.\n    double T = sys.GasPhase().Temperature();\n    double P = sys.GasPhase().Pressure();\n\n    // Calculate the single rate term and advance iterator.\n    \n    if (sys.ParticleModel()->Postprocessing() == ParticleModel::wdotA4) {\n        double Rate = NA * sys.GasPhase().PropertyValue(1007) * sys.SampleVolume();\n\n        if (Rate < 0.0)\n            Rate = 0.0;\n\n        *iterm = Rate; \n\t}else{\n        *iterm = Rate(sys.GasPhase(), sqrt(T),\n                      MeanFreePathAir(T,P),\n                      sys.SampleVolume());\n    }\n\n    return *(iterm++);\n}\n\n\n// READ/WRITE/COPY.\n\n// Creates a copy of the inception.\nDimerInception *const DimerInception::Clone(void) const {return new DimerInception(*this);}\n\n// Returns the process type.  Used to identify different\n// processes and for serialisation.\nProcessType DimerInception::ID(void) const {return Dimer_Inception_ID;}\n\n// Writes the object to a binary stream.\nvoid DimerInception::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Serialize base class.\n        Inception::Serialize(out);\n\n        // Write free-mol parameter.\n        double v = (double)m_kfm;\n        out.write((char*)&v, sizeof(v));\n\n        // Write slip-flow parameters.\n        v = (double)m_ksf1;\n        out.write((char*)&v, sizeof(v));\n        v = (double)m_ksf2;\n        out.write((char*)&v, sizeof(v));\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, DimerInception::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid DimerInception::Deserialize(std::istream &in, const Sweep::Mechanism &mech)\n{\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        double val = 0.0;\n\n        switch (version) {\n            case 0:\n                // Deserialize base class.\n                Inception::Deserialize(in, mech);\n\n                // Read free-mol parameter.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_kfm = (double)val;\n\n                // Read slip-flow parameters.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_ksf1 = (double)val;\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_ksf2 = (double)val;\n\n                break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, DimerInception::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, DimerInception::Deserialize).\");\n    }\n}\n", "meta": {"hexsha": "9dc1b34dea8ffa24205fb125869ad074881a68bf", "size": 13379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_dimer_inception.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_dimer_inception.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_dimer_inception.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 31.4061032864, "max_line_length": 105, "alphanum_fraction": 0.6410045594, "num_tokens": 3396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478896, "lm_q2_score": 0.030675800935278857, "lm_q1q2_score": 0.010804071755151532}}
{"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#ifndef heom_hierarchy_graph_hpp\n#define heom_hierarchy_graph_hpp\n\n#include <unordered_map>\n\n#include <boost/functional/hash.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n\n#include \"heom/common.hpp\"\n\n\nnamespace heom {\n\nusing uid_t = std::int32_t; // unique node id\n\n// represents a tuple in the HEOM sense (kind of an excitation vector) which uniquely describes one ado_tuple/matrix/hierarchy node\nusing tuple = std::vector<int_t>; // excitation vector, value type of each node\n// hash function for tuple\n//auto tuple_hash = [](const tuple& v) { return boost::hash_range(v.begin(), v.end()); }; // TODO: report compiler bug, causes multiple definition linker error with Intel compiler, tested with 16.0.3 and 17.0.1\nstd::size_t tuple_hash(const tuple& v);\n\nclass hierarchy_graph\n{\npublic:\n\t//using tuple_to_uid_map = std::unordered_map<tuple, uid_t, decltype(tuple_hash)>;\n\tusing tuple_to_uid_map = std::unordered_map<tuple, uid_t, std::function<decltype(tuple_hash)>>;\n\tusing node_list = std::vector<tuple>;\n\tusing adj_list = std::vector<uid_t>;\n\tusing edge_list = std::vector<adj_list>;\n\n\tstatic const uid_t invalid_uid;\n\n\thierarchy_graph(std::int64_t baths_number, std::int64_t baths_matsubaras, std::int64_t depth);\n\thierarchy_graph(std::int64_t width, std::int64_t depth);\n\n\tint64_t width() const { return width_; }\n\tint64_t depth() const { return depth_; }\n\tint64_t nodes() const { return nodes_; }\n\tint64_t compute_nodes() const { return compute_nodes_; }\n\tint64_t halo_nodes() const { return nodes_ - compute_nodes_; }\n\tint64_t edges() const { return plus_edge_count_ + minus_edge_count_; }\n\tint64_t plus_edge_count() const { return plus_edge_count_; }\n\tint64_t minus_edge_count() const { return minus_edge_count_; }\n\n\tuid_t first_non_plus_uid() const { return first_non_plus_uid_; }\n\n\tconst node_list& tuples() const { return tuples_; }\n\tconst edge_list& plus_edges() const { return plus_edges_; }\n\tconst edge_list& minus_edges() const { return minus_edges_; }\n\n\tconst std::vector<int_t>& nodes_per_depth() const { return nodes_per_depth_; }\n\n\t// compute depth of a tuple\n\tint_t depth(const tuple& t) const;\n\t// compute depth of an uid\n\tint_t depth(const uid_t& uid) const;\n\n\t/**\n\t * Write graph to file, METIS and Boost.Graph compatible adjacency list\n\t * format, i.e. first row contains two space separated numbers for the\n\t * node and edge count. Every other row i cantains the adjacency list for\n\t * node i (count starting at 1).\n\t *\n\t * @param filename name/path of the output file.\n\t */\n\tvoid write_graph_file(const std::string& filename);\n\nprotected:\n\thierarchy_graph() = default;\n\thierarchy_graph(int64_t width, int64_t depth, int64_t nodes, int64_t compute_nodes, uid_t first_non_plus_uid);\n\n//private:\n\tint64_t width_ = 0; // max. number of outgoing plus or minus edges per node\n\tint64_t depth_ = 0; // number of hierarchy layers within the graph\n\tint64_t nodes_ = 0; // number of nodes\n\tint64_t compute_nodes_ = 0; // nodes to be computed\n\tint64_t plus_edge_count_ = 0; // number of plus edges\n\tint64_t minus_edge_count_ = 0; // number of minu edges\n\n\t// first node that has no outgoing downward (plus) edges\n\tuid_t first_non_plus_uid_ = invalid_uid;\n\n\tnode_list tuples_;\n\tedge_list plus_edges_;\n\tedge_list minus_edges_;\n\n\tstd::vector<int_t> nodes_per_depth_;\n};\n\n} // namespace heom\n\n#endif // heom_hierarchy_graph_hpp\n", "meta": {"hexsha": "34ddf895d248acebe3dd16b799d7663d5829ed57", "size": 3619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dm-heom/include/heom/hierarchy_graph.hpp", "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/include/heom/hierarchy_graph.hpp", "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/include/heom/hierarchy_graph.hpp", "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": 36.19, "max_line_length": 210, "alphanum_fraction": 0.7518651561, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.03514485044314309, "lm_q1q2_score": 0.01080205153523075}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the ParticleImage class declared in the\n    swp_particle_image.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_particle_image.h\"\n#include \"swp_bintree_primary.h\"\n#include \"swp_surfvol_primary.h\"\n#include \"swp_PAH_primary.h\"\n#include \"string_functions.h\"\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <fstream>\n#include <vector>\n#include <stdexcept>\nusing namespace Sweep;\nusing namespace Sweep::Imaging;\nusing namespace std;\nusing namespace Strings;\n\nconst double ParticleImage::m_necking = 1.000;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default contructor.\nParticleImage::ParticleImage(void)\n{\n}\n\n// Initialising constructor.\n/*ParticleImage::ParticleImage(const Particle &sp, const ParticleModel &model)\n{\n    Construct(sp, model);\n}*/\n\n// Destructor.\nParticleImage::~ParticleImage(void)\n{\n}\n\n// PARTICLE IMAGE DATA CONSTRUCTION.\n\n/*!\n * @brief           Construct a particle image\n *\n * @param sp        Particle object\n * @param model     Particle model describing object\n */\nvoid ParticleImage::Construct(const Particle &sp, const ParticleModel &model)\n{\n    // Initialise new RNG here as the calling functions do not have access to\n    // the original one\n    rng_type rng(size_t(100));\n\n    // Clear the current image data structure.\n    m_root.Clear();\n\n    if (model.AggModel() == AggModels::Spherical_ID) {\n        // Spherical particle model, just draw\n        // a single sphere.\n\n        m_root.Insert(sp.SphDiameter() * 0.5e9); // Convert to nm.\n\n    } else if (model.AggModel() == AggModels::SurfVol_ID) {\n        // Surface-volume model, construct a tree\n        // of identical primaries, estimating the primary\n        // count and diameter.\n\n        const AggModels::SurfVolPrimary *svp = NULL;\n        svp = dynamic_cast<const AggModels::SurfVolPrimary*>(sp.Primary());\n\n        m_root.Clear();\n        for (unsigned int i=0; i!=svp->PP_Count(); ++i) {\n            // Convert to radius in nm\n            m_root.Insert(svp->PP_Diameter() * 0.5e9);\n        }\n\n        //! At the moment tracking of the distance between the centres of\n        //! primary particles does not apply to the surface-volume model.\n        calc_FM(m_root, *(&rng), false);\n\n    } else if (model.AggModel() == AggModels::BinTree_ID ||\n            model.AggModel() == AggModels::BinTreeSilica_ID) {\n        // Binary Tree generic model\n\n        const AggModels::BinTreePrimary *p;\n        p = dynamic_cast<const AggModels::BinTreePrimary*>(sp.Primary());\n        ConstructTree(p, *(&rng), model.getTrackPrimaryCoordinates());\n\n    } else if (model.AggModel() == AggModels::PAH_KMC_ID) {\n        // PAHPP (binary tree like) model\n\n        const AggModels::PAHPrimary *p;\n        p = dynamic_cast<const AggModels::PAHPrimary*>(sp.Primary());\n        ConstructTree(p, *(&rng), model.getTrackPrimaryCoordinates());\n    } else {\n        throw std::runtime_error(\"Unknown particle model. (ParticleImage::Construct)\");\n    }\n\n    // Set to TEM-style projection\n    //m_root.Project();\n}\n\n/*!\n *  This function is like a limited assignment operator, except that the\n *  children are not copied and the pointers to the particles may need\n *  adjusting after this method has finished.\n *\n *  @param[in,out] node   Pointer to node of ImgNode tree.\n *  @param[in]     source Pointer to the primary to be copied.\n */\ntemplate <class ParticleClass>\nvoid ParticleImage::CopyParts(ImgNode &node, const ParticleClass *source)\n{\n\t//! Since m_cen_bshp and m_cen_mass are vectors do unit conversion in\n    //! function.\n    node.setBoundSph(source->m_cen_bsph);\n    node.setCOM(source->m_cen_mass);\n\n\t//! Units of nm.\n    node.setRadius(source->m_primarydiam*0.5e9);\n    node.setDistance(source->m_distance_centreToCentre*1.0e9);\n}\n\n/*!\n *  Recursively copy the tree for non-leaf nodes.\n *\n *  @param[in,out] node   Pointer to node of ImgNode tree.\n *  @param[in]     source Pointer to the primary to be copied.\n */\ntemplate <class ParticleClass>\nvoid ParticleImage::CopyTree(ImgNode &node, const ParticleClass *source)\n{\n    //! Create the new left and right children with nothing in them.\n    node.m_leftchild = new ImgNode();\n    node.m_rightchild = new ImgNode();\n\n    //! Copy the properties such as the volume, surface area and list of\n    //! constituent PAH molecules.\n    CopyParts(*node.m_leftchild, source->m_leftchild);\n    CopyParts(*node.m_rightchild, source->m_rightchild);\n\n    // Set the pointers to the parent.\n    node.m_leftchild->m_parent=&node;\n    node.m_rightchild->m_parent=&node;\n\n    //! The left and right particle are set further down in UpdateAllPointers.\n    //! These are the pointers that specify which primary particles touch each\n    //! other in the aggregate structure.\n    node.m_leftparticle=NULL;\n    node.m_rightparticle=NULL;\n\n    //! Recurse to copy the subtrees.\n    if (source->m_leftchild->m_leftchild!=NULL)\n        CopyTree(*node.m_leftchild, source->m_leftchild);\n\n    if (source->m_rightchild->m_leftchild!=NULL)\n        CopyTree(*node.m_rightchild, source->m_rightchild);\n\n    //! Set the leftparticle and rightparticle.\n    UpdateAllPointers(node, source);\n}\n\n//! Generates a projection on the zx plane (set all y to 0)\nvoid ParticleImage::Project()\n{\n    // Call to ImgNode\n    m_root.Project();\n}\n\n/*!\n * @brief       Writes a 3dout format file\n *\n * This made use of some custom-made OpenGL renderer by Markus Sander\n * which has since been lost. (wjm34 27/07/2012)\n *\n * @param file  File output stream\n * @param x     ?\n * @param y     ?\n * @param z     ?\n */\nvoid ParticleImage::Write3dout(std::ofstream &file, double x, double y, double z)\n{\n    if (file.good()) {\n        string line;\n        double val = 0.0;\n\n        // vector of arrays to store primary coordinates.  First\n        // 3 values are the cartesian coordinates, final value\n        // is the primary radius.\n        vector<fvector> coords;\n\n        // Get the primary coordinates from the aggregate tree.\n        m_root.GetPriCoords(coords);\n\t\tfile.write(line.c_str(), line.length());\n        //write the radius of gyration\n        double Rg=RadiusofGyration();\n        line = cstr(0) + \" \" + cstr(0) +\n               \" \" + cstr(0)+\"\\n \";\n        file.write(line.c_str(), line.length());\n        line = cstr(Rg)+\"\\n\";\t\t\t\t\t\t\t//write radius of gyration\n        file.write(line.c_str(), line.length());\n        // Write the primaries to the 3dout file.\n        for (unsigned int i=0; i!=coords.size(); ++i) {\n            val  = coords[i][3] * m_necking;\n            line = cstr(coords[i][0]+x) + \" \" + cstr(coords[i][1]+y) +\n                   \" \" + cstr(coords[i][2]+z)+\"\\n \";\n            file.write(line.c_str(), line.length());\n            line = cstr(val)+\"\\n\";\t\t\t\t\t\t\t//write radius\n            file.write(line.c_str(), line.length());\n        }\n\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, ParticleImage::Write3dout).\");\n    }\n}\n\n/*\nvoid ParticleImage::LengthWidth(double &L, double &W)\n{\n    //align the particle along the z axis\n\tdouble xmax=0;\n\tdouble ymax=0;\n\tdouble xmin=0;\n\tdouble ymin=0;\n    double zmax=0;\n\tdouble zmin=0;\n    double dx=0,dy=0,dz=0;\n    //the radius of outher spheres\n\tdouble yminrad=0;\n\tdouble xminrad=0;\n\tdouble ymaxrad=0;\n\tdouble xmaxrad=0;\n    double zmaxrad=0;\n    double zminrad=0;\n\tvector<fvector> coords;\n    m_root.GetPriCoords(coords);\n    double dist=0, distmax=0;\n\tfor (unsigned int i=0; i!=coords.size(); ++i) {\n        dist=sqrt(coords[i][0]*coords[i][0]+coords[i][1]*coords[i][1]+coords[i][2]*coords[i][2])+coords[i][3];\n\t\tif (dist>distmax) {\n            xmax=coords[i][0];ymax=coords[i][1];zmax=coords[i][2];\n            distmax=dist;\n        }\n\t}\n    //added to debug ms785\n    if (m_root.m_left!=NULL)\n    {\n        double phi=atan2(ymax,xmax);\n        double theta=(PI/2)-atan(zmax/sqrt((xmax*xmax)+(ymax*ymax)));\n\n      //  m_root.Translate(-dx,-dy,-dz);\n        m_root.RotateOrigin(0,-phi-PI/2);\n        ofstream out;\n       // out.open(\"particlebeforeshift.3d\");\n       // this->Write3dout(out,0,0,0);\n       // out.close();\n        m_root.RotateOrigin(-theta,0);\n\n      //  out.open(\"particleaftershift.3d\");\n      //  this->Write3dout(out,0,0,0);\n      //  out.close();\n    }\n    coords.clear();\n    m_root.GetPriCoords(coords);\n\txmax=coords[0][0];\n\txmin=xmax;\n\tymax=coords[0][1];\n\tymin=ymax;\n    zmax=coords[0][2];\n\tzmin=zmax;\n\tfor (unsigned int i=0; i!=coords.size(); ++i) {\n\t\tif (xmax<=coords[i][0]+coords[i][3]) {xmax=coords[i][0]+coords[i][3];xmaxrad=coords[i][3];}\n\t\tif (ymax<=coords[i][1]+coords[i][3]) {ymax=coords[i][1]+coords[i][3];ymaxrad=coords[i][3];}\n        if (zmax<=coords[i][2]+coords[i][3]) {zmax=coords[i][2]+coords[i][3];zmaxrad=coords[i][3];}\n\t\tif (xmin>=coords[i][0]-coords[i][3]) {xmin=coords[i][0]-coords[i][3];xminrad=coords[i][3];}\n\t\tif (ymin>=coords[i][1]-coords[i][3]) {ymin=coords[i][1]-coords[i][3];yminrad=coords[i][3];}\n        if (zmin>=coords[i][2]-coords[i][3]) {zmin=coords[i][2]-coords[i][3];zminrad=coords[i][3];}\n\t}\n    dx=abs(xmax-xmin);\n    dy=abs(ymax-ymin);\n    dz=abs(zmax-zmin);\n\tL=dz;\n\n   // W=max(dy,dx);\n    W=dx;\n\n}*/\n\n//! Calculates the radius of gyration of a particle\ndouble ParticleImage::RadiusofGyration()\n{\n    double sum=0;\n    double mass;\n    double totalmass=0;\n    double r2;\n    double Rg;\n    vector<fvector> coords;\n    m_root.GetPriCoords(coords);\n\tfor (unsigned int i=0; i!=coords.size(); ++i) {\n        //mass is proportional to the cube of the radius\n        mass=coords[i][3]*coords[i][3]*coords[i][3];\n        r2=coords[i][0]*coords[i][0]+coords[i][1]*coords[i][1]+coords[i][2]*coords[i][2];\n        sum+=mass*r2;\n        totalmass+=mass;\n\t}\n    Rg=sqrt(sum/totalmass);\n    return Rg;\n}\n\n/*!\n *  Each node contains two pointers (m_leftparticle and m_rightparticle)\n *  to primary particles that are connected by this node.\n *  This function is used when the entire particle tree is duplicated.\n *  It sets the pointers in the copied node, that the connectivity\n *  of the primary particles in this node is the same as in the original node.\n *\n *  @todo give this method a more accurate name.\n *\n *  @param[in,out] node     Pointer to node of ImgNode tree.\n *  @param[in]     original Pointer to the primary to be copied.\n */\ntemplate <class ParticleClass>\nvoid ParticleImage::UpdateAllPointers(ImgNode &node, const ParticleClass *original)\n{\n    //! The primary has no children => there are no left and right particles.\n    if (original->m_leftchild == NULL) {\n        //! Since this is not a connecting node it does not have left and\n        //!right particles.\n        node.m_leftparticle=NULL;\n        node.m_rightparticle=NULL;\n    } else {\n        //! Find the route to m_leftparticle in the original tree.\n        std::stack<bool> route = recordPath(original->m_leftparticle, original);\n\n        //! Now follow the same route down the new tree to find the new left particle.\n        node.m_leftparticle = descendPath(&node, route);\n\n        //! Find the route to m_rightparticle in the original tree.\n        route = recordPath(original->m_rightparticle, original);\n\n        //! Now follow the same route down the new tree to find the new right particle.\n        node.m_rightparticle = descendPath(&node, route);\n    }\n}\n\n/*!\n *  This is a helper function for UpdateAllPointers.\n *  It climbs up the tree from bottom to top recording a route\n *  suitable for use in call to @see descendPath.\n *\n *  @param[in] bottom Tree node from which to start climbing.\n *  @param[in] top    Tree node at which to stop climbing.\n *\n *  @pre top must be above bottom in a tree.\n *\n *  @return Stack that can be used to descend the same path by moving to the\n *          left child each time the top of the stack is true.\n */\ntemplate <class ParticleClass>\nstd::stack<bool> ParticleImage::recordPath(const ParticleClass* bottom, const ParticleClass* const top) {\n    std::stack<bool> wasLeftChild;\n\n    while(bottom != top) {\n        //! check whether bottom was a left child of its parent.\n        wasLeftChild.push(bottom == bottom->m_parent->m_leftchild);\n\n        //! Climb one level up the tree.\n        bottom = bottom->m_parent;\n    }\n    return wasLeftChild;\n}\n\n/*!\n *  @param[in]     here           Point in tree from which to start descent.\n *  @param[in,out] takeLeftBranch Instructions for which child to move to at each level.\n *\n *  @return The node at the bottom of the path.\n *\n *  @pre  here must be a node of tree in which takeLeftBranch is a valid path.\n *  @post takeLeftBranch.empty() == true.\n */\ntemplate <class ParticleClass>\nParticleClass* ParticleImage::descendPath(ParticleClass *here, std::stack<bool> &takeLeftBranch) {\n    while(!takeLeftBranch.empty()) {\n        //! Move one step down the tree in the instructed direction.\n        if(takeLeftBranch.top())\n            here = here->m_leftchild;\n        else\n            here = here->m_rightchild;\n\n        //! This instuction has now been processed.\n        takeLeftBranch.pop();\n    }\n    return here;\n}\n\n// RENDERING FUNCTIONS.\n\n// Draws the particle image to a POVRAY file.\nvoid ParticleImage::WritePOVRAY(std::ofstream &file)\n{\n    if (file.good()) {\n        string line;\n        double val = 0.0;\n\n        // vector of arrays to store primary coordinates.  First\n        // 3 values are the cartesian coordinates, final value\n        // is the primary radius.\n        vector<fvector> coords;\n\n        // Write ParticleDiameter argument to POV file.\n        val  = m_root.Radius() * 2.0;\n        line = \"#declare ParticleDiameter = \" + cstr(val) + \";\\n\";\n        file.write(line.c_str(), line.length());\n\n        // Write aggregate opening declaration.\n        line = \"#declare MyParticle = blob {\\n\";\n        file.write(line.c_str(), line.length());\n\n        // Write threshold radius based on necking parameter.\n        val  = max(pow(1.0 - (1.0/(m_necking*m_necking)), 2.0), 1.0e-4);\n        line = \"  threshold \" + cstr(val) + \"\\n\";\n        file.write(line.c_str(), line.length());\n\n        // Get the primary coordinates from the aggregate tree.\n        m_root.GetPriCoords(coords);\n\n        // Write the primaries to the POV-RAY file.\n        for (unsigned int i=0; i!=coords.size(); ++i) {\n            val  = coords[i][3] * m_necking;\n            line = \"sphere {<\" + cstr(coords[i][0]) + \", \" + cstr(coords[i][1]) +\n                   \", \" + cstr(coords[i][2]) + \">, \" + cstr(val) + \", 1.0}\\n\";\n            file.write(line.c_str(), line.length());\n        }\n\n        // Write closing brace for MyParticle declaration.\n        line = \"}\\n\";\n        file.write(line.c_str(), line.length());\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, ParticleImage::WritePOVRAY).\");\n    }\n}\n\n\n// AGGREGATE SPHERE-TREE CONSTRUCTORS (FREE-MOLECULAR).\n\n\n/*!\n *  @brief Generate the free-molecular structure of a particle.\n *\n *  Calculates the aggregate structure down from the given\n *  node. Assumes that the tree leaves have been initialised\n *  with the correct radii, and recalculates their positions.\n *\n *  @param[in,out] node                   Pointer to node of ImgNode tree.\n *  @param[in]     rng                    Random number generator.\n *  @param[in]     trackPrimaryCoordinates Flag used to indicate whether to track primary coordinates.\n */\nvoid ParticleImage::calc_FM(ImgNode &node, Sweep::rng_type &rng, const bool trackPrimaryCoordinates)\n{\n    ImgNode *target = node.m_leftchild;\n    ImgNode *bullet = node.m_rightchild;\n\n    if ((target != NULL) && (bullet != NULL)) {\n        //! Pass calculation down binary tree left & right branches.\n        calc_FM(*target, rng, trackPrimaryCoordinates);\n        calc_FM(*bullet, rng, trackPrimaryCoordinates);\n\n        //! The first part of the collision algorithm is to\n        //! randomly orientate both left and right aggregates.\n        //! They are both then placed so that their bounding\n        //! spheres are at the origin.\n\n        //! Rotate left node randomly about CoM.\n        //! Generate a random number on [0,1)-double-interval.\n        boost::uniform_01<rng_type&, double> uniformGenerator(rng);\n        double phi1   = uniformGenerator() * 2.0 * PI;\n        double theta1 = ((2.0*uniformGenerator())-1.0) * PI;\n        target->RotateCOM(theta1, phi1);\n\n        //! Rotate right node randomly about CoM.\n        double phi2   = uniformGenerator() * 2.0 * PI;\n        double theta2 = ((2.0*uniformGenerator())-1.0) * PI;\n        bullet->RotateCOM(theta2, phi2);\n\n        //! Move both spheres so that the bounding spheres\n        //! sit at the origin.\n        target->CentreBoundSph();\n        bullet->CentreBoundSph();\n\n        //! Perform the collision of the left and right nodes.\n        //! This may require several iterations if the chosen\n        //! x-y displacement means that the aggregates cannot\n        //! collide in the z-direction.\n        Coords::Vector D;\n        double sumr=0.0;\n        bool hit = false;\n        while (!hit) {\n            //! Need to reset target and bullet here, in case\n            //! they have been changed by the tree traversal\n            //! code below.\n            target = node.m_leftchild;\n            bullet = node.m_rightchild;\n\n            if (!trackPrimaryCoordinates) {\n                sumr = target->Radius() + bullet->Radius();\n            } else {\n                sumr = node.m_distance_centreToCentre;\n            }\n\n            //! Create a random displacement of the bullet node\n            //! in the x-y plane.  The displacement is never\n            //! greater than the sum of the radii, therefore they\n            //! should always touch.\n            D[0] = ((2.0 * uniformGenerator()) - 1.0) * sumr;\n            D[1] = ((2.0 * uniformGenerator()) - 1.0) * sumr;\n\n            //// Calculate the z-position for the collision of the\n            //// target and bullet.  We do this in case both the\n            //// target and bullet are leaf nodes, and hence the\n            //// binary tree traversal won't happen.\n            // hit = calcCollZ(target->m_cen_mass, target->m_r,\n            //                 bullet->m_cen_mass, bullet->m_r,\n            //                 D[0], D[1], dz1);\n            // if (!hit) continue; // Should never happen.\n            // D[2] = target->m_cen_bsph[2] + dz1;\n\n            if (!trackPrimaryCoordinates) {\n                //! The next code determines the displacement along the z-axis\n                //! required for the target and bullet aggregates to touch.  This\n                //! requires falling down the tree progressively recalculating\n                //! the nearest nodes at each level, until the leaf nodes\n                //! are reached.\n                //! This next code calculates the minimum distance between the\n                //! target's children and bullet's children, or the target or\n                //! bullet if they have no children.  The two children with\n                //! the smallest separation are chosen as the next target\n                //! and bullet.\n                hit = minCollZ(*target, *bullet, D[0], D[1], D[2]);\n            } else {\n                //! By including pointers to a node's left and right particles,\n                //! we can directly calculate the displacement in the z\n                //! direction for these two particles which maintains the\n                //! particle's connectivity thus negating the need to call\n                //! calcCollZ function through minCollZ.\n                hit = calcCollZ(node.m_leftparticle->BoundSphCentre(), node.m_leftparticle->Radius(),\n                                node.m_rightparticle->BoundSphCentre(), node.m_rightparticle->Radius(),\n                                D[0], D[1], D[2], sumr, trackPrimaryCoordinates);\n            }\n        }\n\n        //! We have a new location for the bullet (right node), so move it.\n        node.m_rightchild->Translate(D[0], D[1], D[2]);\n\n        //! Calculate properties of this node.\n        node.CalcBoundSph();\n        node.CalcCOM();\n        node.CentreBoundSph();\n    }\n}\n\n// Calculates the minimum collision distance between\n// a target and a bullet node by moving down the\n// binary tree.  If the nodes collide then returns\n// true, otherwise returns false.\n/*!\n * @brief           Calculates the minimum collision distance\n *\n * Calculates the minimum collision distance between\n * a target and a bullet node by moving down the\n * binary tree.  If the nodes collide then returns\n * true, otherwise returns false.\n *\n * @param target    Target node\n * @param bullet    Bullet node\n * @param dx        ?\n * @param dy        ?\n * @param dz        ?\n * @return          Have the nodes collided?\n */\nbool ParticleImage::minCollZ(const ImgNode &target,\n                             const ImgNode &bullet,\n                             double dx, double dy, double &dz)\n{\n    bool hit=false, hit1=false;\n    double dz2=0.0, dz3=0.0, dz4=0.0;\n\n    if (target.IsLeaf()) {\n        // Target is a leaf\n        if (bullet.IsLeaf()) {\n            // Bullet is a leaf (both leaves).\n           return calcCollZ(target.BoundSphCentre(), target.Radius(),\n                            bullet.BoundSphCentre(), bullet.Radius(),\n                            dx, dy, dz, 0.0, false);\n        } else {\n            // Bullet is not a leaf, call sub-nodes.\n            // Calculate minimum dz for the target and the bullet left subnode.\n            hit1 = calcCollZ(target.BoundSphCentre(), target.Radius(),\n                             bullet.m_leftchild->BoundSphCentre(), bullet.m_leftchild->Radius(),\n                             dx, dy, dz, 0.0, false);\n            if (hit1) hit = minCollZ(target, *bullet.m_leftchild, dx, dy, dz);\n            // Calculate minimum dz for the target and the bullet right subnode.\n            hit1 = calcCollZ(target.BoundSphCentre(), target.Radius(),\n                             bullet.m_rightchild->BoundSphCentre(), bullet.m_rightchild->Radius(),\n                             dx, dy, dz2, 0.0, false);\n            if (hit1) hit = minCollZ(target, *bullet.m_rightchild, dx, dy, dz2) || hit;\n            // Return minimum dz.\n            dz = min(dz, dz2);\n            return hit;\n        }\n    } else {\n        // Target is not a leaf.\n        if (bullet.IsLeaf()) {\n            // Bullet is a leaf, call target sub-nodes..\n            // Calculate minimum dz for the target left subnode and the bullet.\n            hit1 = calcCollZ(target.m_leftchild->BoundSphCentre(), target.m_leftchild->Radius(),\n                             bullet.BoundSphCentre(), bullet.Radius(),\n                             dx, dy, dz, 0.0, false);\n            if (hit1) hit = minCollZ(*target.m_leftchild, bullet, dx, dy, dz);\n            // Calculate minimum dz for the target right subnode and the bullet.\n            hit1 = calcCollZ(target.m_rightchild->BoundSphCentre(), target.m_rightchild->Radius(),\n                             bullet.BoundSphCentre(), bullet.Radius(),\n                             dx, dy, dz2, 0.0, false);\n            if (hit1) hit = minCollZ(*target.m_rightchild, bullet, dx, dy, dz2) || hit;\n            // Return minimum dz.\n            dz = min(dz, dz2);\n            return hit;\n        } else {\n            // Bullet is not a leaf (neither is a leaf), check all left/right\n            // collision combinations.\n            // Target left and bullet left.\n            hit1 = calcCollZ(target.m_leftchild->BoundSphCentre(), target.m_leftchild->Radius(),\n                             bullet.m_leftchild->BoundSphCentre(), bullet.m_leftchild->Radius(),\n                             dx, dy, dz, 0.0, false);\n            if (hit1) hit = minCollZ(*target.m_leftchild, *bullet.m_leftchild, dx, dy, dz);\n            // Target left and bullet right.\n            hit1 = calcCollZ(target.m_leftchild->BoundSphCentre(), target.m_leftchild->Radius(),\n                             bullet.m_rightchild->BoundSphCentre(), bullet.m_rightchild->Radius(),\n                             dx, dy, dz2, 0.0, false);\n            if (hit1) hit = minCollZ(*target.m_leftchild, *bullet.m_rightchild, dx, dy, dz2) || hit;\n            // Target right and bullet left.\n            hit1 = calcCollZ(target.m_rightchild->BoundSphCentre(), target.m_rightchild->Radius(),\n                             bullet.m_leftchild->BoundSphCentre(), bullet.m_leftchild->Radius(),\n                             dx, dy, dz3, 0.0, false);\n            if (hit1) hit = minCollZ(*target.m_rightchild, *bullet.m_leftchild, dx, dy, dz3) || hit;\n            // Target right and bullet right.\n            hit1 = calcCollZ(target.m_rightchild->BoundSphCentre(), target.m_rightchild->Radius(),\n                             bullet.m_rightchild->BoundSphCentre(), bullet.m_rightchild->Radius(),\n                             dx, dy, dz4, 0.0, false);\n            if (hit1) hit = minCollZ(*target.m_rightchild, *bullet.m_rightchild, dx, dy, dz4) || hit;\n            // Returns minimum dz.\n            dz = min(min(dz, dz2), min(dz3, dz4));\n            return hit;\n        }\n    }\n}\n\n/*!\n *  @brief Calculates the z-displacement of a sphere.\n *\n *  Calculates the z-displacement of a bullet sphere for a +ve\n *  collision with a target sphere. Returns true if the\n *  spheres collide, otherwise false.\n *\n *  @param[in]  p1                     Coordinates of sphere 1.\n *  @param[in]  r1                     Radius of sphere 1.\n *  @param[in]  p2                     Coordinates of sphere 2.\n *  @param[in]  r2                     Radius of sphere 2\n *  @param[in]  dx                     Bullet x displacement.\n *  @param[in]  dy                     Bullet y displacement.\n *  @param[out] dz                     Bullet z displacement.\n *  @param[in]  distanceCentreToCentre Distance between the centres of neighbouring primary particles.\n *  @param[in]  trackPrimaryCoordinates Flag used to indicate whether to track primary coordinates.\n *\n *  @return Have the nodes collided?\n */\nbool ParticleImage::calcCollZ(const Coords::Vector &p1, double r1,\n                              const Coords::Vector &p2, double r2,\n                              double dx, double dy, double &dz,\n                              double distanceCentreToCentre, const bool trackPrimaryCoordinates)\n{\n    double sumrsqr;\n\n    if (!trackPrimaryCoordinates) {\n        sumrsqr = r1 + r2;\n    } else {\n        sumrsqr = distanceCentreToCentre;\n    }\n\n    //! Calculate the square of the sum of the radii, or the distance between\n    //! the centres of neighbouring primary particles if tracking primary\n    //! separation.\n    sumrsqr *= sumrsqr;\n\n    //! Calculate dx, dy and dz. Remember to include\n    //! argument contributions.\n    double xdev = p2[0] - p1[0] + dx;\n    double ydev = p2[1] - p1[1] + dy;\n    double zdev = p2[2] - p1[2];\n\n    //! Calculate dx, dy and dz squared.\n    double dxsqr = xdev * xdev;\n    double dysqr = ydev * ydev;\n    double dzsqr = zdev * zdev;\n\n    // Calculate quadratic terms.\n    double b = 2.0 * zdev;\n    double c = dxsqr + dysqr + dzsqr - sumrsqr;\n\n    //! Calculate discriminant.\n    double dis = (b*b) - (4.0*c);\n\n    if (dis >= 0.0) {\n        //! Spheres intersect.\n        dz = - 0.5 * (b + sqrt(dis));\n        return true;\n    } else {\n        //! Spheres do not intersect.\n        dz = 1.0e10; //!< A large number.\n        return false;\n    }\n}", "meta": {"hexsha": "c7e7a9100f08d80e571d001284d3f3848aca68ae", "size": 28583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_particle_image.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_particle_image.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_particle_image.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 37.4123036649, "max_line_length": 110, "alphanum_fraction": 0.607074135, "num_tokens": 7139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111975283019596, "lm_q2_score": 0.032589743591528754, "lm_q1q2_score": 0.010791107842826464}}
{"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/// Computes conductivities versus temperature.\n/// Material information and sweep settings provided via XML input.\n\n#include <iostream>\n#include <functional>\n#include <boost/filesystem.hpp>\n#include <boost/mpi.hpp>\n#include <utilities.hpp>\n#include <vasp_io.hpp>\n#include <qpoint_grid.hpp>\n#include <processes.hpp>\n#include <isotopic_scattering.hpp>\n#include <bulk_hdf5.hpp>\n#include <analytic1d.hpp>\n#include <io_utils.hpp>\n#include <bulk_properties.hpp>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <beyondRTA.hpp>\n\nint main(int argc, char** argv) {\n    // set up MPI environment\n    boost::mpi::environment env;\n    boost::mpi::communicator world;\n\n    if (world.size() > 1) {\n        std::cout\n            << \"*** ERROR: kappa_Tsweep does not run in parallel mode. ***\"\n            << std::endl;\n        world.abort(1);\n    }\n\n    if (argc < 2) {\n        std::cout << \"USAGE: kappa_Tsweep <inputfile.xml>\" << std::endl;\n        return 1;\n    }\n\n    else {\n        // define variables\n        std::string target_directory = \"AUTO\";\n        std::string target_filename = \"AUTO\";\n        std::string h5_repository = \".\";\n        std::string mat_directory;\n        std::string mat_base;\n        int gridDensityA = -1;\n        int gridDensityB = -1;\n        int gridDensityC = -1;\n        bool logsweep = false;\n        double Tmin = -1.0;\n        double Tmax = -1.0;\n        int NT = -1;\n        bool projectConductivity = false;\n        Eigen::Vector3d uvector(0.0, 0.0, 0.0);\n        Eigen::Vector3d u_norm(0.0, 0.0, 0.0);\n        bool fullBTE = false;\n        bool fullBTE_iterative = true;\n        bool outputCapacity = false;\n        bool superlattice = false;\n        std::string superlattice_UID = \"NULL\";\n\n        std::cout << \"*************************************\" << std::endl;\n        std::cout << \"This is ALMA/kappa_Tsweep version \" << ALMA_VERSION_MAJOR\n                  << \".\" << ALMA_VERSION_MINOR << std::endl;\n        std::cout << \"*************************************\" << std::endl;\n\n        // verify that input file exists.\n        if (!boost::filesystem::exists(boost::filesystem::path{argv[1]})) {\n            std::cout << \"ERROR: input file \" << argv[1] << \" does not exist.\"\n                      << std::endl;\n            exit(1);\n        }\n\n        /////////////////////////\n        /// PARSE INPUT FILE  ///\n        /////////////////////////\n\n        std::string xmlfile(argv[1]);\n        std::cout << \"PARSING \" << xmlfile << \" ...\" << std::endl;\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(xmlfile, tree);\n\n        for (const auto& v : tree.get_child(\"Tsweep\")) {\n            if (v.first == \"H5repository\") {\n                h5_repository =\n                    alma::parseXMLfield<std::string>(v, \"root_directory\");\n            }\n\n            if (v.first == \"target\") {\n                target_directory =\n                    alma::parseXMLfield<std::string>(v, \"directory\");\n                target_filename = alma::parseXMLfield<std::string>(v, \"file\");\n            }\n\n            if (v.first == \"compound\") {\n                mat_directory =\n                    alma::parseXMLfield<std::string>(v, \"directory\");\n                mat_base = alma::parseXMLfield<std::string>(v, \"base\");\n\n                gridDensityA = alma::parseXMLfield<int>(v, \"gridA\");\n                gridDensityB = alma::parseXMLfield<int>(v, \"gridB\");\n                gridDensityC = alma::parseXMLfield<int>(v, \"gridC\");\n            }\n\n            if (v.first == \"superlattice\") {\n                superlattice_UID = alma::parseXMLfield<std::string>(v, \"UID\");\n            }\n\n            if (v.first == \"sweep\") {\n                std::string sweepID =\n                    alma::parseXMLfield<std::string>(v, \"type\");\n\n                if (sweepID.compare(\"log\") == 0) {\n                    logsweep = true;\n                }\n\n                Tmin = alma::parseXMLfield<double>(v, \"start\");\n                Tmax = alma::parseXMLfield<double>(v, \"stop\");\n                NT = alma::parseXMLfield<int>(v, \"points\");\n            }\n\n            if (v.first == \"fullBTE\") {\n                fullBTE = true;\n                fullBTE_iterative = alma::parseXMLfield<bool>(v, \"iterative\");\n            }\n\n            if (v.first == \"transportAxis\") {\n                projectConductivity = true;\n                double ux = alma::parseXMLfield<double>(v, \"x\");\n                double uy = alma::parseXMLfield<double>(v, \"y\");\n                double uz = alma::parseXMLfield<double>(v, \"z\");\n\n                uvector << ux, uy, uz;\n            }\n\n            if (v.first == \"outputHeatCapacity\") {\n                outputCapacity = true;\n            }\n        } // end XML parsing\n\n        // Ensure that provided information is within expected bounds\n\n        bool badinput = false;\n\n        if (gridDensityA < 1) {\n            std::cout << \"ERROR: provided gridA is \" << gridDensityA\n                      << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (gridDensityB < 1) {\n            std::cout << \"ERROR: provided gridB is \" << gridDensityB\n                      << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (gridDensityC < 1) {\n            std::cout << \"ERROR: provided gridC is \" << gridDensityC\n                      << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (Tmin <= 0.0) {\n            std::cout << \"ERROR: provided start temperature is \" << Tmin\n                      << std::endl;\n            std::cout << \"Value must be positive.\" << std::endl;\n            badinput = true;\n        }\n\n        if ((Tmax < Tmin) || (Tmax <= 0.0)) {\n            std::cout << \"ERROR: provided end temperature is \" << Tmax\n                      << std::endl;\n            std::cout << \"Value must be positive and >= start temperature.\"\n                      << std::endl;\n            badinput = true;\n        }\n\n        if (NT <= 0) {\n            std::cout << \"ERROR: provided number of temperature values is \"\n                      << NT << std::endl;\n            std::cout << \"Value must be at least 1.\" << std::endl;\n            badinput = true;\n        }\n\n        if (projectConductivity && (uvector.norm() < 1e-12)) {\n            std::cout << \"ERROR: provided transport axis vector has zero norm.\"\n                      << std::endl;\n            badinput = true;\n        }\n\n        if (badinput) {\n            world.abort(1);\n        }\n\n        // Initialise file system and verify that directories actually exist\n        auto launch_path = boost::filesystem::current_path();\n        auto basedir = boost::filesystem::path(h5_repository);\n\n        if (!(boost::filesystem::exists(boost::filesystem::path(basedir)))) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"Repository directory \" << basedir\n                      << \" does not exist.\" << std::endl;\n            world.abort(1);\n        }\n\n        if (!(boost::filesystem::exists(\n                boost::filesystem::path(basedir / mat_directory)))) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"Material directory \" << mat_directory\n                      << \" does not exist within the HDF5 repository.\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n        // Resolve name of HDF5 file\n        std::stringstream h5namebuilder;\n        h5namebuilder << mat_base << \"_\" << gridDensityA << \"_\" << gridDensityB\n                      << \"_\" << gridDensityC << \".h5\";\n        std::string h5filename = h5namebuilder.str();\n\n        // obtain phonon data from HDF5 file\n        auto hdf5_path = basedir / boost::filesystem::path(mat_directory) /\n                         boost::filesystem::path(h5filename);\n\n        if (!(boost::filesystem::exists(hdf5_path))) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"H5 file \" << h5filename\n                      << \" does not exist within the material directory.\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n        std::cout << \"Opening HDF5 file \" << hdf5_path << std::endl;\n\n        auto hdf5_data =\n            alma::load_bulk_hdf5(hdf5_path.string().c_str(), world);\n        auto description = std::get<0>(hdf5_data);\n        auto poscar = std::move(std::get<1>(hdf5_data));\n        auto syms = std::move(std::get<2>(hdf5_data));\n        auto grid = std::move(std::get<3>(hdf5_data));\n        auto processes = std::move(std::get<4>(hdf5_data));\n\n        if (processes->size() == 0) {\n            std::cout << \"ERROR:\" << std::endl;\n            std::cout << \"List of 3-phonon processes is missing in H5 file.\"\n                      << std::endl;\n            world.abort(1);\n        }\n\n        // Check if we are dealing with a superlattice.\n        // If so, load the applicable scattering data.\n\n        auto subgroups =\n            alma::list_scattering_subgroups(hdf5_path.string().c_str(), world);\n\n        int superlattice_count = 0;\n\n        for (std::size_t ngroup = 0; ngroup < subgroups.size(); ngroup++) {\n            if (subgroups.at(ngroup).find(\"superlattice\") !=\n                std::string::npos) {\n                superlattice_count++;\n            }\n        }\n\n        superlattice_count /= 2;\n\n        if (superlattice_count > 0) {\n            superlattice = true;\n        }\n\n        Eigen::ArrayXXd w0_SLdisorder;\n        Eigen::ArrayXXd w0_SLbarriers;\n\n        if (superlattice) {\n            // complain if there are multiple possibilities\n\n            if ((superlattice_count > 1) && (superlattice_UID == \"NULL\")) {\n                std::cout << \"ERROR:\" << std::endl;\n                std::cout << \"H5 file contains scattering information for \"\n                             \"multiple superlattices.\"\n                          << std::endl;\n                std::cout << \"Must provide the superlattice UID via the \"\n                             \"<superlattice> XML tag.\"\n                          << std::endl;\n                world.abort(1);\n            }\n\n            // if the user provided a UID, verify that corresponding data exists\n\n            if (superlattice_UID != \"NULL\") {\n                int UIDcount = 0;\n\n                for (std::size_t ngroup = 0; ngroup < subgroups.size();\n                     ngroup++) {\n                    if (subgroups.at(ngroup).find(superlattice_UID) !=\n                        std::string::npos) {\n                        UIDcount++;\n                    }\n                }\n\n                if (UIDcount != 2) {\n                    std::cout << \"ERROR:\" << std::endl;\n                    std::cout << \"H5 file does not contain any superlattice \"\n                                 \"data with provided UID \"\n                              << superlattice_UID << \".\" << std::endl;\n                    world.abort(1);\n                }\n            }\n\n            // load the scattering rates from the H5 file\n\n            bool UIDmatch = true;\n\n            for (std::size_t ngroup = 0; ngroup < subgroups.size(); ngroup++) {\n                bool contains_SLdisorder =\n                    (subgroups.at(ngroup).find(\"superlattice\") !=\n                     std::string::npos) &&\n                    (subgroups.at(ngroup).find(\"disorder\") !=\n                     std::string::npos);\n\n                bool contains_SLbarriers =\n                    (subgroups.at(ngroup).find(\"superlattice\") !=\n                     std::string::npos) &&\n                    (subgroups.at(ngroup).find(\"barriers\") !=\n                     std::string::npos);\n\n                if (superlattice_count > 1) {\n                    UIDmatch = (subgroups.at(ngroup).find(superlattice_UID) !=\n                                std::string::npos);\n                }\n\n                if (contains_SLdisorder && UIDmatch) {\n                    auto mysubgroup = alma::load_scattering_subgroup(\n                        hdf5_path.string().c_str(),\n                        subgroups.at(ngroup),\n                        world);\n                    w0_SLdisorder = mysubgroup.w0;\n                }\n\n                if (contains_SLbarriers && UIDmatch) {\n                    auto mysubgroup = alma::load_scattering_subgroup(\n                        hdf5_path.string().c_str(),\n                        subgroups.at(ngroup),\n                        world);\n                    w0_SLbarriers = mysubgroup.w0;\n                }\n            }\n        }\n\n        // Build list of temperature values\n        Eigen::VectorXd Tlist;\n\n        if (logsweep) {\n            Tlist = alma::logSpace(Tmin, Tmax, NT);\n        }\n\n        else {\n            Tlist.setLinSpaced(NT, Tmin, Tmax);\n        }\n\n        // Create output writer\n        std::stringstream outputbuffer;\n\n        // Write file header\n\n        if (projectConductivity) {\n            outputbuffer << \"Temp[K],kappaRTA<\" << uvector(0) << \",\"\n                         << uvector(1) << \",\" << uvector(2) << \">[W/m-K]\";\n\n            if (fullBTE) {\n                outputbuffer << \",kappaBTE<\" << uvector(0) << \",\" << uvector(1)\n                             << \",\" << uvector(2) << \">[W/m-K]\";\n            }\n        }\n\n        else {\n            if (!fullBTE) {\n                outputbuffer << \"Temp[K],kappaRTA_xx[W/m-K],kappaRTA_xy[W/\"\n                                \"m-K],kappaRTA_xz[W/m-K],kappaRTA_yy[W/\"\n                                \"m-K],kappaRTA_yz[W/m-K],kappaRTA_zz[W/m-K]\";\n            }\n            else {\n                outputbuffer << \"Temp[K],kappaRTA_xx[W/m-K],kappaBTE_xx[W/\"\n                                \"m-K],kappaRTA_xy[W/m-K],kappaBTE_xy[W/\"\n                                \"m-K],kappaRTA_xz[W/m-K],kappaBTE_xz[W/\"\n                                \"m-K],kappaRTA_yy[W/m-K],kappaBTE_yy[W/\"\n                                \"m-K],kappaRTA_yz[W/m-K],kappaBTE_yz[W/\"\n                                \"m-K],kappaRTA_zz[W/m-K]kappaBTE_zz[W/m-K],\";\n            }\n        }\n\n        if (outputCapacity) {\n            outputbuffer << \",Cbulk[J/m^3-K]\";\n        }\n\n        outputbuffer << std::endl;\n\n        // RUN CALCULATIONS\n\n        std::cout << \"Running Tsweep for \" << mat_base << std::endl;\n\n        auto twoph_processes = alma::find_allowed_twoph(*grid, world);\n\n        // temperature-independent scattering rates\n        Eigen::ArrayXXd w_elastic;\n\n        if (superlattice) {\n            w_elastic = w0_SLbarriers.array() + w0_SLdisorder.array();\n        }\n        else {\n            w_elastic =\n                alma::calc_w0_twoph(*poscar, *grid, twoph_processes, world);\n        }\n\n        if (projectConductivity) {\n            u_norm = uvector.array() / uvector.norm();\n        }\n\n        for (int nT = 0; nT < NT; nT++) {\n            double T = Tlist(nT);\n\n            std::cout << \" Processing \" << T << \" K (temperature \" << nT + 1\n                      << \" of \" << NT << \")\" << std::endl;\n\n            Eigen::ArrayXXd w3(\n                alma::calc_w0_threeph(*grid, *processes, T, world));\n            Eigen::ArrayXXd w(w3 + w_elastic);\n\n            Eigen::Matrix3d kappa_RTA = alma::calc_kappa(*poscar, *grid, w, T);\n            Eigen::Matrix3d kappa_BTE;\n\n            if (fullBTE) {\n                kappa_BTE = alma::beyondRTA::calc_kappa(*poscar,\n                                                        *grid,\n                                                        *syms,\n                                                        *processes,\n                                                        twoph_processes,\n                                                        w,\n                                                        T,\n                                                        fullBTE_iterative,\n                                                        world);\n            }\n\n            if (projectConductivity) { // write conductivity along chosen\n                                       // direction\n                Eigen::MatrixXd kappa_u =\n                    u_norm.transpose() * kappa_RTA.matrix() * u_norm;\n                outputbuffer << T << \",\" << kappa_u(0, 0);\n\n                if (fullBTE) {\n                    Eigen::MatrixXd kappa_u =\n                        u_norm.transpose() * kappa_BTE.matrix() * u_norm;\n                    outputbuffer << \",\" << kappa_u(0, 0);\n                }\n            }\n\n            else { // write tensor components\n                if (!fullBTE) {\n                    outputbuffer << T << \",\" << kappa_RTA(0, 0) << \",\"\n                                 << kappa_RTA(0, 1) << \",\";\n                    outputbuffer << kappa_RTA(0, 2) << \",\" << kappa_RTA(1, 1)\n                                 << \",\";\n                    outputbuffer << kappa_RTA(1, 2) << \",\" << kappa_RTA(2, 2);\n                }\n\n                else {\n                    outputbuffer << T << \",\" << kappa_RTA(0, 0) << \",\"\n                                 << kappa_BTE(0, 0) << \",\";\n                    outputbuffer << kappa_RTA(0, 1) << \",\" << kappa_BTE(0, 1)\n                                 << \",\";\n                    outputbuffer << kappa_RTA(0, 2) << \",\" << kappa_BTE(0, 2)\n                                 << \",\";\n                    outputbuffer << kappa_RTA(1, 1) << \",\" << kappa_BTE(1, 1)\n                                 << \",\";\n                    outputbuffer << kappa_RTA(1, 2) << \",\" << kappa_BTE(1, 2)\n                                 << \",\";\n                    outputbuffer << kappa_RTA(2, 2) << \",\" << kappa_BTE(2, 2);\n                }\n            }\n\n            if (outputCapacity) {\n                outputbuffer << \",\" << 1e27 * alma::calc_cv(*poscar, *grid, T);\n            }\n\n            outputbuffer << std::endl;\n        } // END CALCULATIONS\n\n        // WRITE FILE\n\n        // go to the launch directory\n        boost::filesystem::current_path(launch_path);\n\n        // resolve output directory if AUTO is selected\n        if (target_directory.compare(\"AUTO\") == 0) {\n            target_directory = \"output/kappa_Tsweep\";\n        }\n\n        // create output directory if it doesn't exist yet\n        auto outputfolder = boost::filesystem::path(target_directory);\n\n        if (!(boost::filesystem::exists(outputfolder))) {\n            boost::filesystem::create_directories(outputfolder);\n        }\n\n        boost::filesystem::current_path(launch_path);\n\n        // resolve file name if AUTO selected\n\n        if (target_filename.compare(\"AUTO\") == 0) {\n            std::stringstream filenamebuilder;\n            filenamebuilder << mat_base << \"_\" << gridDensityA << \"_\"\n                            << gridDensityB << \"_\" << gridDensityC;\n\n            if (projectConductivity) {\n                filenamebuilder << \"_\" << uvector(0) << \",\" << uvector(1) << \",\"\n                                << uvector(2);\n            }\n\n            filenamebuilder << \"_\" << Tmin << \"_\" << Tmax;\n\n            filenamebuilder << \".Tsweep\";\n            target_filename = filenamebuilder.str();\n        }\n\n        // save file\n\n        std::cout << std::endl;\n        std::cout << \"Writing to file \" << target_filename << std::endl;\n        std::cout << \"in subdirectory \" << target_directory << std::endl;\n        std::cout << \"under root directory \" << launch_path << std::endl;\n\n        std::ofstream outputwriter;\n        outputwriter.open(\"./\" + target_directory + \"/\" + target_filename);\n        outputwriter << outputbuffer.str();\n        outputwriter.close();\n\n        std::cout << std::endl << \"[DONE.]\" << std::endl;\n\n        return 0;\n    }\n}\n", "meta": {"hexsha": "b468c30a04cbc0df013839d7525c0a9694284a1a", "size": 20431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kappa_Tsweep.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/kappa_Tsweep.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/kappa_Tsweep.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.0971731449, "max_line_length": 80, "alphanum_fraction": 0.4691889775, "num_tokens": 4692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.02595735550240123, "lm_q1q2_score": 0.010769676837882679}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, University of Stuttgart\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 University of Stuttgart nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey, Sohaib Akbar */\n\n#include <ompl/geometric/planners/quotientspace/datastructures/QuotientSpaceGraphSparse.h>\n#include <ompl/geometric/planners/quotientspace/datastructures/PlannerDataVertexAnnotated.h>\n#include <ompl/geometric/PathSimplifier.h>\n#include <ompl/base/objectives/PathLengthOptimizationObjective.h>\n#include <ompl/base/objectives/MaximizeMinClearanceObjective.h>\n#include <ompl/base/goals/GoalSampleableRegion.h>\n#include <ompl/tools/config/SelfConfig.h>\n#include <ompl/util/Exception.h>\n#include <ompl/control/PathControl.h>\n\n#include <boost/property_map/vector_property_map.hpp>\n#include <boost/property_map/transform_value_property_map.hpp>\n#include <boost/foreach.hpp>\n#include \"GoalVisitor.hpp\"\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/incremental_components.hpp>  //same_component\n#include <boost/math/constants/constants.hpp>\n#include <boost/range/adaptor/map.hpp>\n\nusing namespace og;\n#define foreach BOOST_FOREACH\n\nQuotientSpaceGraphSparse::QuotientSpaceGraphSparse(const ob::SpaceInformationPtr &si, QuotientSpace *parent)\n  : BaseT(si, parent), geomPath_(si)\n{\n    setName(\"QuotientSpaceGraphSparse\");\n    Planner::declareParam<double>(\"sparse_delta_fraction\", this, &QuotientSpaceGraphSparse::setSparseDeltaFraction,\n                                  &QuotientSpaceGraphSparse::getSparseDeltaFraction, \"0.0:0.01:1.0\");\n\n    if (!isSetup())\n    {\n        setup();\n    }\n    pathVisibilityChecker_ = new PathVisibilityChecker(Q1);\n\n    psimp_ = std::make_shared<PathSimplifier>(si_);\n    psimp_->freeStates(false);\n}\n\nQuotientSpaceGraphSparse::~QuotientSpaceGraphSparse()\n{\n}\n\nvoid QuotientSpaceGraphSparse::deleteConfiguration(Configuration *q)\n{\n    BaseT::deleteConfiguration(q);\n}\n\nvoid QuotientSpaceGraphSparse::setup()\n{\n    BaseT::setup();\n    if (!nearestSparse_)\n    {\n        nearestSparse_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Configuration *>(this));\n        nearestSparse_->setDistanceFunction(\n            [this](const Configuration *a, const Configuration *b) { return si_->distance(a->state, b->state); });\n    }\n\n    double maxExt = Q1->getMaximumExtent();\n    sparseDelta_ = sparseDeltaFraction_ * maxExt;\n    denseDelta_ = denseDeltaFraction_ * maxExt;\n    pathBias_ = pathBiasFraction_ * maxExt;\n    double d = (double)Q1->getStateDimension();\n    double e = boost::math::constants::e<double>();\n    kPRMStarConstant_ = e + (e / d);\n}\n\nvoid QuotientSpaceGraphSparse::clear()\n{\n    BaseT::clear();\n\n    if (nearestSparse_)\n    {\n        std::vector<Configuration *> configs;\n        nearestSparse_->list(configs);\n        if (configs.size() > 1)\n        {\n            for (auto &config : configs)\n            {\n                deleteConfiguration(config);\n            }\n        }\n        nearestSparse_->clear();\n    }\n    graphSparse_.clear();\n\n    selectedPath = -1;\n    graphNeighborhood.clear();\n    visibleNeighborhood.clear();\n    vrankSparse.clear();\n    vparentSparse.clear();\n    v_start_sparse = -1;\n    v_goal_sparse = -1;\n    Nold_v = 0;\n    Nold_e = 0;\n\n    pathStackHead_.clear();\n    pathStack_.clear();\n}\nvoid QuotientSpaceGraphSparse::clearDynamic()\n{\n    // BaseT::clear();\n\n    if (nearestSparse_)\n    {\n        std::vector<Configuration *> configs;\n        nearestSparse_->list(configs);\n        for (auto &config : configs)\n        {\n            if (config->state != qStart_->state)\n                deleteConfiguration(config);\n        }\n        nearestSparse_->clear();\n    }\n    graphSparse_.clear();\n\n    // selectedPath = -1;\n    graphNeighborhood.clear();\n    visibleNeighborhood.clear();\n    vrankSparse.clear();\n    vparentSparse.clear();\n    Nold_v = 0;\n    Nold_e = 0;\n\n    const Vertex vl = add_vertex(qStart_, graphSparse_);\n    nearestSparse_->add(qStart_);\n    disjointSetsSparse_.make_set(vl);\n    graphSparse_[vl]->index = vl;\n}\n\nconst ompl::geometric::QuotientSpaceGraph::Configuration *\nompl::geometric::QuotientSpaceGraphSparse::nearest(const Configuration *q) const\n{\n    if (!isDynamic())\n        return BaseT::nearest(q);\n    else\n    {\n        return nearestSparse_->nearest(const_cast<Configuration *>(q));\n    }\n}\n\nompl::base::Cost ompl::geometric::QuotientSpaceGraphSparse::costHeuristicSparse(Vertex u, Vertex v) const\n{\n    return opt_->motionCostHeuristic(graphSparse_[u]->state, graphSparse_[v]->state);\n}\n\nompl::base::PathPtr ompl::geometric::QuotientSpaceGraphSparse::getPathSparse(const Vertex &start, const Vertex &goal)\n{\n    std::vector<Vertex> prev(boost::num_vertices(graphSparse_));\n    auto weight = boost::make_transform_value_property_map(std::mem_fn(&EdgeInternalState::getCost),\n                                                           get(boost::edge_bundle, graphSparse_));\n    try\n    {\n        boost::astar_search(graphSparse_, start, [this, goal](const Vertex v) { return costHeuristicSparse(v, goal); },\n                            boost::predecessor_map(&prev[0])\n                                .weight_map(weight)\n                                .distance_compare([this](EdgeInternalState c1, EdgeInternalState c2) {\n                                    return opt_->isCostBetterThan(c1.getCost(), c2.getCost());\n                                })\n                                .distance_combine([this](EdgeInternalState c1, EdgeInternalState c2) {\n                                    return opt_->combineCosts(c1.getCost(), c2.getCost());\n                                })\n                                .distance_inf(opt_->infiniteCost())\n                                .distance_zero(opt_->identityCost()));\n    }\n    catch (AStarFoundGoal &)\n    {\n    }\n\n    auto p(std::make_shared<PathGeometric>(si_));\n    if (prev[goal] == goal)\n    {\n        return nullptr;\n    }\n\n    std::vector<Vertex> vpath;\n    for (Vertex pos = goal; prev[pos] != pos; pos = prev[pos])\n    {\n        graphSparse_[pos]->on_shortest_path = true;\n        vpath.push_back(pos);\n        p->append(graphSparse_[pos]->state);\n    }\n    graphSparse_[start]->on_shortest_path = true;\n    vpath.push_back(start);\n    p->append(graphSparse_[start]->state);\n\n    shortestVertexPath_.clear();\n    shortestVertexPath_.insert(shortestVertexPath_.begin(), vpath.rbegin(), vpath.rend());\n    p->reverse();\n\n    return p;\n}\n\nvoid QuotientSpaceGraphSparse::Init()\n{\n    // BaseT::init(); //sa-> ? gives error maybe pis_.nextStart() can be called once so add base init() code here\n    // QuotientSpaceGraph init()\n    auto *goal = dynamic_cast<base::GoalSampleableRegion *>(pdef_->getGoal().get());\n    if (goal == nullptr)\n    {\n        OMPL_ERROR(\"%s: Unknown type of goal\", getName().c_str());\n        throw ompl::Exception(\"Unknown goal type\");\n    }\n\n    if (const base::State *st = pis_.nextStart())\n    {\n        if (st != nullptr)\n        {\n            // dense QuotientSpaceGraph\n            qStart_ = new Configuration(Q1, st);\n            qStart_->isStart = true;\n            vStart_ = BaseT::addConfiguration(qStart_);\n            // Sparse\n            // v_start_sparse = addConfigurationSparse(qStart_);\n            Configuration *ql = new Configuration(Q1, qStart_->state);\n            const Vertex vl = add_vertex(ql, graphSparse_);\n            nearestSparse_->add(ql);\n            disjointSetsSparse_.make_set(vl);\n            graphSparse_[vl]->index = vl;\n\n            assert(boost::num_vertices(graphSparse_) == 1);\n            v_start_sparse = graphSparse_[0]->index;\n            graphSparse_[v_start_sparse]->isStart = true;\n\n            qStart_->representativeIndex = v_start_sparse;\n        }\n    }\n    if (qStart_ == nullptr)\n    {\n        OMPL_ERROR(\"%s: There are no valid initial states!\", getName().c_str());\n        throw ompl::Exception(\"Invalid initial states.\");\n    }\n\n    if (const base::State *st = pis_.nextGoal())\n    {\n        if (st != nullptr)\n        {\n            // dense QuotientSpaceGraph\n            qGoal_ = new Configuration(Q1, st);\n            qGoal_->isGoal = true;\n            vGoal_ = BaseT::addConfiguration(qGoal_);  // sa-> (added) Q:- why goal state was not added in configuration\n\n            // sparse - not added in QuotientSpaceGraph .: because it was added in grow() function\n            if (!isDynamic())\n            {\n                // v_goal_sparse = addConfigurationSparse(qGoal_);\n                Configuration *ql = new Configuration(Q1, qGoal_->state);\n                const Vertex vl = add_vertex(ql, graphSparse_);\n                nearestSparse_->add(ql);\n                disjointSetsSparse_.make_set(vl);\n                graphSparse_[vl]->index = vl;\n\n                v_goal_sparse = vl;\n                graphSparse_[v_goal_sparse]->isGoal = true;\n\n                assert(boost::num_vertices(graphSparse_) == 2);\n\n                qGoal_->representativeIndex = v_goal_sparse;\n            }\n        }\n    }\n    if (qGoal_ == nullptr)\n    {\n        OMPL_ERROR(\"%s: There are no valid goal states!\", getName().c_str());\n        throw ompl::Exception(\"Invalid goal states.\");\n    }\n}\n\nvoid QuotientSpaceGraphSparse::debugInvalidState(const ob::State *s)\n{\n    const ob::StateSpacePtr space = Q1->getStateSpace();\n    bool bounds = space->satisfiesBounds(s);\n    if (!bounds)\n    {\n        std::vector<ob::StateSpacePtr> Q1_decomposed;\n        if (!space->isCompound())\n        {\n            Q1_decomposed.push_back(space);\n        }\n        else\n        {\n            ob::CompoundStateSpace *Q1_compound = space->as<ob::CompoundStateSpace>();\n            Q1_decomposed = Q1_compound->getSubspaces();\n        }\n\n        for (uint k = 0; k < Q1_decomposed.size(); k++)\n        {\n            ob::StateSpacePtr spacek = Q1_decomposed.at(k);\n            int type = spacek->getType();\n            switch (type)\n            {\n                case ob::STATE_SPACE_REAL_VECTOR:\n                {\n                    auto *RN = spacek->as<ob::RealVectorStateSpace>();\n                    const ob::RealVectorStateSpace::StateType *sk =\n                        s->as<ob::CompoundState>()->as<ob::RealVectorStateSpace::StateType>(k);\n                    std::vector<double> bl = RN->getBounds().low;\n                    std::vector<double> bh = RN->getBounds().high;\n                    for (uint k = 0; k < bl.size(); k++)\n                    {\n                        double qk = sk->values[k];\n                        double qkl = bl.at(k);\n                        double qkh = bh.at(k);\n                        if (qk < qkl || qk > qkh)\n                        {\n                            std::cout << \"OUTOFBOUNDS [\" << k << \"] \" << bl.at(k) << \" <= \" << qk << \" <= \" << bh.at(k)\n                                      << std::endl;\n                        }\n                    }\n                    break;\n                }\n            }\n        }\n    }\n}\n\nvoid QuotientSpaceGraphSparse::uniteComponentsSparse(Vertex m1, Vertex m2)\n{\n    disjointSetsSparse_.union_set(m1, m2);\n}\nbool QuotientSpaceGraphSparse::sameComponentSparse(Vertex m1, Vertex m2)\n{\n    return boost::same_component(m1, m2, disjointSetsSparse_);\n}\n\nQuotientSpaceGraphSparse::Vertex QuotientSpaceGraphSparse::addConfigurationSparse(Configuration *q)\n{\n    Configuration *ql = new Configuration(Q1, q->state);  // for sparse create new Configuration ***\n    const Vertex vl = add_vertex(ql, graphSparse_);\n    nearestSparse_->add(ql);\n    disjointSetsSparse_.make_set(vl);\n    graphSparse_[vl]->index = vl;\n    updateRepresentatives(q);\n    consecutiveFailures_ = 0;  // reset consecutive failures\n    return vl;\n}\n\nvoid QuotientSpaceGraphSparse::findGraphNeighbors(Configuration *q, std::vector<Configuration *> &graphNeighborhood,\n                                                  std::vector<Configuration *> &visibleNeighborhood)\n{\n    graphNeighborhood.clear();\n    visibleNeighborhood.clear();\n\n    nearestSparse_->nearestR(q, sparseDelta_, graphNeighborhood);\n\n    for (Configuration *qn : graphNeighborhood)\n        if (Q1->checkMotion(q->state, qn->state))\n            visibleNeighborhood.push_back(qn);\n}\n\nvoid QuotientSpaceGraphSparse::addEdgeSparse(const Vertex a, const Vertex b)\n{\n    ob::Cost weight = opt_->motionCost(graphSparse_[a]->state, graphSparse_[b]->state);\n    EdgeInternalState properties(weight);\n    boost::add_edge(a, b, properties, graphSparse_);\n    uniteComponentsSparse(a, b);\n}\n\nbool QuotientSpaceGraphSparse::checkAddCoverage(Configuration *q, std::vector<Configuration *> &visibleNeighborhood)\n{\n    /*for (int i = 0; i < visibleNeighborhood.size(); i++)\n    {\n        Configuration *q_neighbor = visibleNeighborhood.at(i);\n        // If path between is free\n        if (Q1->checkMotion(q_neighbor->state, q->state))\n        {\n            return false;  // abort already in covered region\n        }\n    }*/\n    // No free paths means we add for coverage\n    if (visibleNeighborhood.empty())\n    {\n        addConfigurationSparse(q);\n        return true;\n    }\n    return false;\n}\n\nbool QuotientSpaceGraphSparse::checkAddConnectivity(Configuration *q, std::vector<Configuration *> &visibleNeighborhood)\n{\n    // The sample q is able to connect to at least two nodes that are otherwise disconnected:\n    std::vector<Vertex> links;\n    if (visibleNeighborhood.size() > 1)\n    {\n        // For each neighbor\n        for (std::size_t i = 0; i < visibleNeighborhood.size(); ++i)\n        {\n            // For each other neighbor\n            for (std::size_t j = i + 1; j < visibleNeighborhood.size(); ++j)\n            {\n                // If they are in different components\n                if (!sameComponentSparse(visibleNeighborhood[i]->index, visibleNeighborhood[j]->index))  // ???????????????????\n                                                                                                         // check???????\n                    // If the paths between are collision free\n                    if (Q1->checkMotion(q->state, visibleNeighborhood[i]->state) &&\n                        Q1->checkMotion(q->state, visibleNeighborhood[j]->state))\n                    {\n                        links.push_back(visibleNeighborhood[i]->index);\n                        links.push_back(visibleNeighborhood[j]->index);\n                    }\n            }\n        }\n\n        if (!links.empty())\n        {\n            Vertex v = addConfigurationSparse(q);\n\n            for (Vertex link : links)\n            {\n                // If there's no edge\n                if (!boost::edge(v, link, graphSparse_).second)\n                {\n                    // And the components haven't been united by previous links\n                    if (!sameComponentSparse(link, v))  //??????????????????? check??????????????????????????\n                                                        //check???????\n                    {\n                        addEdgeSparse(v, link);\n                    }\n                }\n            }\n            return true;\n        }\n    }\n    return false;\n}\nbool QuotientSpaceGraphSparse::checkAddInterface(Configuration *q, std::vector<Configuration *> &graphNeighborhood,\n                                                 std::vector<Configuration *> &visibleNeighborhood)\n{\n    // Pairs of nodes that share an interface to also be connected with an edge\n    // If we have more than 1 or 0 neighbors\n    if (visibleNeighborhood.size() > 1)\n    {\n        // The sample q reveals the existence of an interface between two nodes that do not share an edge\n        // N = Nearest_Guards( q, \u0002, GS); v1 ← arg minn∈N d( q, n); v2 ← arg minn∈N,n\u0011=v1 d( q, n);\n        // if L( v1, q) , L( q, v2) ∈ Cfree ∧ L( v1, v2) ∈/ ES then if L( v1, v2) ∈ Cfree then ES ← ES ∪ L( v1, v2);\n        // else VS ← VS ∪ {q}; ES ← ES ∪ {L( v1, q) , L( q, v2) };\n        Configuration *qn0 = graphNeighborhood[0];\n        Configuration *qn1 = graphNeighborhood[1];\n        Configuration *qv0 = visibleNeighborhood[0];\n        Configuration *qv1 = visibleNeighborhood[1];\n\n        if (qn0 == qv0 && qn1 == qv1)\n        {\n            // If our two closest neighbors don't share an edge\n            if (!boost::edge(qv0->index, qv1->index, graphSparse_).second)\n            {\n                // If they can be directly connected\n                if (si_->checkMotion(qv0->state, qv1->state))\n                {\n                    addEdgeSparse(qv0->index, qv1->index);\n                    consecutiveFailures_ = 0;  // sohaib -> from sparse -> reset consecutive failures\n                }\n                else\n                {\n                    // Add the new node to the graph, to bridge the interface\n                    // Vertex v = addGuard(si_->cloneState(qNew), INTERFACE);\n                    Vertex v = addConfigurationSparse(q);\n                    addEdgeSparse(v, qv0->index);\n                    addEdgeSparse(v, qv1->index);\n                }\n                return true;\n            }\n        }\n    }\n    return false;\n}\n//''''######################################################################################################################\n\nvoid ompl::geometric::QuotientSpaceGraphSparse::updateRepresentatives(Configuration *q)\n{\n    // Get all of the dense samples which may be affected by adding this node\n    std::vector<Configuration *> dense_points;\n    nearestDatastructure_->nearestR(q, sparseDelta_ + denseDelta_, dense_points);\n\n    // For each of those points\n    for (Configuration *dense_point : dense_points)\n    {\n        // Remove that point from the old representative's list(s)\n        removeFromRepresentatives(dense_point);\n\n        // Update that point's representative\n        std::vector<Configuration *> graphNeighborhood;\n        nearestSparse_->nearestR(dense_point, sparseDelta_, graphNeighborhood);\n\n        for (Configuration *qn : graphNeighborhood)\n            if (si_->checkMotion(dense_point->state, qn->state))\n            {\n                dense_point->representativeIndex = qn->index;\n                break;\n            }\n    }\n\n    std::set<Vertex> interfaceRepresentatives;  // sparse\n    // For each of the points\n    for (Configuration *dense_point : dense_points)\n    {\n        // Get it's representative\n        if (dense_point->representativeIndex < 0)\n            continue;\n        Vertex rep = dense_point->representativeIndex;\n        // Extract the representatives of any interface-sharing neighbors\n        getInterfaceNeighborRepresentatives(dense_point, interfaceRepresentatives);\n\n        // For sanity's sake, make sure we clear ourselves out of what this new rep might think of us\n        removeFromRepresentatives(dense_point);\n\n        // Add this vertex to it's representative's list for the other representatives\n        addToRepresentatives(dense_point->index, rep, interfaceRepresentatives);\n    }\n}\n/////////////////////#############################################################\nvoid ompl::geometric::QuotientSpaceGraphSparse::addToRepresentatives(Vertex q, Vertex rep,\n                                                                     const std::set<Vertex> &interfaceRepresentatives)\n{\n    // If this node supports no interfaces\n    if (interfaceRepresentatives.empty())\n    {\n        // Add it to the pool of non-interface nodes\n        bool new_insert = graphSparse_[rep]->nonInterfaceIndexList.insert(q).second;\n        // we expect this was not previously tracked\n        if (!new_insert)\n            assert(false);\n    }\n    else\n    {\n        // otherwise, for every neighbor representative\n        foreach (Vertex v, interfaceRepresentatives)\n        {\n            assert(rep == dense_point->representativeIndex);  //-->    representativesProperty_[dense_point]);\n            auto it = graphSparse_[rep]->interfaceIndexList.find(v);\n            if (it != graphSparse_[rep]->interfaceIndexList.end())\n            {\n                if (!it->second.insert(q).second)\n                    assert(false);\n            }\n            else\n            {\n                std::set<normalized_index_type> list;\n                list.insert(q);\n                std::pair<normalized_index_type, std::set<normalized_index_type>> newinterface(v, list);\n                if (!graphSparse_[rep]->interfaceIndexList.insert(newinterface).second)\n                    assert(false);\n            }\n        }\n    }\n}\n\nvoid ompl::geometric::QuotientSpaceGraphSparse::getInterfaceNeighborRepresentatives(\n    Configuration *q, std::set<Vertex> &interfaceRepresentatives)\n{\n    interfaceRepresentatives.clear();\n\n    // Get our representative\n    Vertex rep = q->representativeIndex;\n    // For each neighbor we are connected to\n    foreach (Vertex n, boost::adjacent_vertices(q->index, graph_))\n    {\n        // Get his representative\n        Vertex orep = graph_[n]->representativeIndex;  //-->     representativesProperty_[n];\n        // If that representative is not our own\n        if (orep != rep)\n            // If he is within denseDelta_\n            if (si_->distance(q->state, graph_[n]->state) < denseDelta_)\n                // Include his rep in the set\n                interfaceRepresentatives.insert(orep);\n    }\n}\n\nvoid ompl::geometric::QuotientSpaceGraphSparse::removeFromRepresentatives(Configuration *q)\n{\n    if (q->representativeIndex < 0)\n        return;\n    // Remove the node from the non-interface points (if there)\n    graphSparse_[q->representativeIndex]->nonInterfaceIndexList.erase(q->index);\n\n    // From each of the interfaces\n    std::unordered_map<normalized_index_type, std::set<normalized_index_type>> interfaceList =\n        graphSparse_[q->representativeIndex]->interfaceIndexList;\n\n    for (std::unordered_map<normalized_index_type, std::set<normalized_index_type>>::iterator it =\n             interfaceList.begin();\n         it != interfaceList.end(); it++)\n    {\n        // Remove this node from that list\n        it->second.erase(q->index);\n    }\n}\n\n/////////////////////#############################################################\nvoid ompl::geometric::QuotientSpaceGraphSparse::getInterfaceNeighborhood(Configuration *q,\n                                                                         std::vector<Vertex> &interfaceNeighborhood)\n{\n    interfaceNeighborhood.clear();\n\n    // Get our representative\n    Vertex rep = q->representativeIndex;\n\n    // For each neighbor we are connected to\n    foreach (Vertex n, boost::adjacent_vertices(q->index, graph_))\n    {\n        // If neighbor representative is not our own\n        if (graph_[n]->representativeIndex != rep)\n        {\n            // If he is within denseDelta_\n            if (si_->distance(q->state, graph_[n]->state) < denseDelta_)\n            {\n                // Append him to the list\n                interfaceNeighborhood.push_back(n);\n            }\n        }\n    }\n}\n\nvoid ompl::geometric::QuotientSpaceGraphSparse::computeVPP(Vertex v, Vertex vp, std::vector<Vertex> &VPPs)\n{\n    foreach (Vertex cvpp, boost::adjacent_vertices(v, graphSparse_))\n        if (cvpp != vp)\n            if (!boost::edge(cvpp, vp, graphSparse_).second)\n                VPPs.push_back(cvpp);\n}\n\nvoid ompl::geometric::QuotientSpaceGraphSparse::computeX(Vertex v, Vertex vp, Vertex vpp, std::vector<Vertex> &Xs)\n{\n    // x are nodes that share an interface and an edge with v, share an edge with v\" but do not share with v'. I\n    Xs.clear();\n    foreach (Vertex cx, boost::adjacent_vertices(vpp, graphSparse_))\n        if (boost::edge(cx, v, graphSparse_).second && !boost::edge(cx, vp, graphSparse_).second)\n        {\n            auto it = graphSparse_[vpp]->interfaceIndexList.find(cx);\n            if (it != graphSparse_[vpp]->interfaceIndexList.end())\n                if (!it->second.empty())  // if (!interfaceListsProperty_[vpp][cx].empty())\n                    Xs.push_back(cx);\n        }\n    Xs.push_back(vpp);\n}\n\nompl::geometric::QuotientSpaceGraph::Vertex ompl::geometric::QuotientSpaceGraphSparse::getInterfaceNeighbor(Vertex q,\n                                                                                                            Vertex rep)\n{\n    foreach (Vertex vp, boost::adjacent_vertices(q, graph_))\n        if (/*representativesProperty_[vp]*/ graph_[vp]->representativeIndex == rep)\n            if (distance(graph_[q], graph_[vp]) <= denseDelta_)\n                return vp;\n    throw Exception(name_, \"Vertex has no interface neighbor with given representative\");\n}\n\nvoid ompl::geometric::QuotientSpaceGraphSparse::computeDensePath(const Vertex &start, const Vertex &goal,\n                                                                 std::deque<base::State *> &path)\n{\n    path.clear();\n\n    // Vertex s = graph_[start]->index ; Vertex g = graph_[goal]->index;\n    // ompl::base::PathPtr dpath = getPath(s, g);\n\n    // boost::vector_property_map<Vertex> prev(boost::num_vertices(graph_));\n    BaseT::getPathDenseGraphPath(start, goal, graph_, path);\n    /*try\n    {\n        boost::astar_search(graph, start,\n                            [this, goal](const Vertex v)\n                            {\n                                return costHeuristic(v, goal);\n                            },\n                            boost::predecessor_map(&prev[0]).visitor(AStarGoalVisitor<Vertex>(goal)));\n    }\n    catch (AStarFoundGoal &)\n    {\n    }*/\n\n    /*if (prev[goal] == goal)\n        OMPL_WARN(\"%s: No dense path was found?\", getName().c_str());\n    else\n    {\n        for (Vertex pos = goal; prev[pos] != pos; pos = prev[pos])\n            path.push_front(graph_[pos]->state);\n        path.push_front(graph_[start]->state);\n    }*/\n}\nbool ompl::geometric::QuotientSpaceGraphSparse::addPathToSpanner(const std::deque<base::State *> &dense_path, Vertex vp,\n                                                                 Vertex vpp)\n{\n    // First, check to see that the path has length\n    if (dense_path.size() <= 1)\n    {\n        // The path is 0 length, so simply link the representatives\n        addEdgeSparse(vp, vpp);\n        consecutiveFailures_ = 0;  // resetFailures();\n    }\n    else\n    {\n        // We will need to construct a PathGeometric to do this.\n        geomPath_.getStates().resize(dense_path.size());\n        std::copy(dense_path.begin(), dense_path.end(), geomPath_.getStates().begin());\n\n        // Attempt to simplify the path\n        psimp_->reduceVertices(geomPath_, geomPath_.getStateCount() * 2);\n\n        // we are sure there are at least 2 points left on geomPath_\n\n        std::vector<Vertex> added_nodes;\n        added_nodes.reserve(geomPath_.getStateCount());\n        for (std::size_t i = 0; i < geomPath_.getStateCount(); ++i)\n        {\n            // Add each guard\n            Configuration *q_path = new Configuration(Q1, si_->cloneState(geomPath_.getState(i)));\n            Vertex ng = addConfigurationSparse(q_path);\n            added_nodes.push_back(ng);\n        }\n        // Link them up\n        for (std::size_t i = 1; i < added_nodes.size(); ++i)\n        {\n            addEdgeSparse(added_nodes[i - 1], added_nodes[i]);\n        }\n        // link them to their representatives\n        addEdgeSparse(added_nodes[0], vp);\n        addEdgeSparse(added_nodes[added_nodes.size() - 1], vpp);\n    }\n    geomPath_.getStates().clear();\n    return true;\n}\n\n//---------------------------------------------------------------------------------------------------------------------------********\n\nbool ompl::geometric::QuotientSpaceGraphSparse::checkAddPath(Configuration *q)\n{\n    std::vector<Vertex> neigh;\n    getInterfaceNeighborhood(q, neigh);\n\n    if (!neigh.empty())\n    {\n        return false;\n    }\n\n    bool result = false;\n\n    Vertex v = q->representativeIndex;\n\n    std::set<Vertex> n_rep;\n    foreach (Vertex qp, neigh)\n        n_rep.insert(graph_[qp]->representativeIndex);\n\n    std::vector<Vertex> Xs;\n    // for each v' in n_rep\n    for (auto it = n_rep.begin(); it != n_rep.end() && !result; ++it)\n    {\n        Vertex vp = *it;\n        // Identify appropriate v\" candidates => vpps\n        std::vector<Vertex> VPPs;\n\n        computeVPP(v, vp, VPPs);\n\n        foreach (Vertex vpp, VPPs)\n        {\n            double s_max = 0;\n\n            // Find the X nodes to test\n            computeX(v, vp, vpp, Xs);\n\n            // For each x in xs\n            foreach (Vertex x, Xs)\n            {\n                // Compute/Retain MAXimum distance path thorugh S\n                double dist = (si_->distance(graphSparse_[x]->state, graphSparse_[v]->state) +\n                               si_->distance(graphSparse_[v]->state, graphSparse_[vp]->state)) /\n                              2.0;\n                if (dist > s_max)\n                    s_max = dist;\n            }\n\n            std::deque<base::State *> bestDPath;  // DensePath\n            Vertex best_qpp = boost::graph_traits<Graph>::null_vertex();\n            double d_min = std::numeric_limits<double>::infinity();  // Insanely big number\n            // For each vpp in vpps\n            for (std::size_t j = 0; j < VPPs.size() && !result; ++j)\n            {\n                Vertex vpp = VPPs[j];\n                // For each q\", which are stored interface nodes on v for i(vpp,v)\n                auto it = graphSparse_[v]->interfaceIndexList.find(vpp);\n                if (it != graphSparse_[v]->interfaceIndexList.end())\n                {\n                    foreach (Vertex qpp, /*interfaceListsProperty_[v][vpp]*/ it->second)\n                    {\n                        // check that representatives are consistent\n                        assert(/*representativesProperty_[qpp]*/ graph_[qpp]->representativeIndex == v);\n\n                        // If they happen to be the one and same node\n                        if (q->index == qpp)\n                        {\n                            bestDPath.push_front(q->state);\n                            best_qpp = qpp;\n                            d_min = 0;\n                        }\n                        else\n                        {\n                            // Compute/Retain MINimum distance path on D through q, q\"\n                            std::deque<base::State *> dPath;  // DensePath\n                            computeDensePath(q->index, qpp, dPath);\n                            if (!dPath.empty())\n                            {\n                                // compute path length\n                                double length = 0.0;\n                                std::deque<base::State *>::const_iterator jt = dPath.begin();\n                                for (auto it = jt + 1; it != dPath.end(); ++it)\n                                {\n                                    length += si_->distance(*jt, *it);\n                                    jt = it;\n                                }\n\n                                if (length < d_min)\n                                {\n                                    d_min = length;\n                                    bestDPath.swap(dPath);\n                                    best_qpp = qpp;\n                                }\n                            }\n                        }\n                    }\n                    // If the spanner property is violated for these paths\n                    if (s_max > stretchFactor_ * d_min)\n                    {\n                        // Need to augment this path with the appropriate neighbor information\n                        Vertex na = getInterfaceNeighbor(q->index, vp);\n                        Vertex nb = getInterfaceNeighbor(best_qpp, vpp);\n\n                        bestDPath.push_front(graph_[na]->state);\n                        bestDPath.push_back(graph_[nb]->state);\n\n                        // check consistency of representatives\n                        assert(graph_[na]->representativeIndex == vp && graph_[nb]->representativeIndex == vpp);\n\n                        // Add the dense path to the spanner\n                        addPathToSpanner(bestDPath, vpp, vp);\n\n                        // Report success\n                        result = true;\n                    }\n                }\n            }\n        }\n    }\n    return result;\n}\n//**************************************************************************************************************************************************\nbool QuotientSpaceGraphSparse::sampleQuotient(ob::State *q_random_graph)\n{\n    if (!getChild()->isDynamic() && pathStack_.size() > 0)\n    {\n        if (selectedPath >= 0 && selectedPath < (int)pathStack_.size())\n        {\n\n            std::vector<ob::State *> states = pathStackHead_.at(selectedPath);\n            uint N = states.size();\n\n            //############################################################################\n            // Vertex Sampling\n            // int k = rng_.uniformInt(0, N-1);\n            // ob::State *state = states.at(k);\n            // Q1->getStateSpace()->copyState(q_random_graph, state);\n            // Q1_sampler->sampleUniformNear(q_random_graph, q_random_graph, 0.2);\n\n            //############################################################################\n            // Edge Sampling\n            uint k = rng_.uniformInt(0, N - 1);\n            double r = rng_.uniform01();\n            ob::State *s1 = states.at((k < N - 1) ? k : k - 1);\n            ob::State *s2 = states.at((k < N - 1) ? k + 1 : k);\n            Q1->getStateSpace()->interpolate(s1, s2, r, q_random_graph);\n\n            Q1_sampler_->sampleUniformNear(q_random_graph, q_random_graph, pathBias_);\n        }\n        else\n        {\n            OMPL_ERROR(\"Selected path is %d (have you selected a path?)\");\n            throw ompl::Exception(\"Unknown selected path\");\n        }\n    }\n    else\n    {\n        // no solution path, we can just sample randomly\n        const Vertex v = boost::random_vertex(graph_, rng_boost);\n        Q1->getStateSpace()->copyState(q_random_graph, graph_[v]->state);\n    }\n    return true;\n}\n\nunsigned int QuotientSpaceGraphSparse::getNumberOfPaths() const\n{\n    return pathStackHead_.size();\n}\n//############################################################################\n//############################################################################\n\nvoid QuotientSpaceGraphSparse::Rewire(Vertex &v)\n{\n    Configuration *q = graphSparse_[v];\n    std::vector<Configuration *> neighbors;\n    uint Nv = boost::degree(v, graphSparse_);\n    uint K = Nv + 2;\n    nearestSparse_->nearestK(const_cast<Configuration *>(q), K, neighbors);\n\n    for (uint k = Nv + 1; k < neighbors.size(); k++)\n    {\n        Configuration *qn = neighbors.at(k);\n        if (Q1->checkMotion(q->state, qn->state))\n        {\n            addEdge(q->index, qn->index);\n        }\n    }\n}\n\nvoid QuotientSpaceGraphSparse::Rewire()\n{\n    Vertex v = boost::random_vertex(graphSparse_, rng_boost);\n    return Rewire(v);\n}\n\nvoid QuotientSpaceGraphSparse::removeLastPathFromStack()\n{\n    pathStackHead_.erase(pathStackHead_.end() - 1);\n}\nvoid QuotientSpaceGraphSparse::pushPathToStack(std::vector<ob::State *> &path)\n{\n    og::PathGeometric gpath(Q1);\n    for (uint k = 0; k < path.size(); k++)\n    {\n        gpath.append(path.at(k));\n    }\n\n    ob::OptimizationObjectivePtr lengthObj(new ob::PathLengthOptimizationObjective(Q1));\n    ob::OptimizationObjectivePtr clearObj(new ob::MaximizeMinClearanceObjective(Q1));\n    ob::MultiOptimizationObjective *multiObj = new ob::MultiOptimizationObjective(Q1);\n\n    multiObj->addObjective(lengthObj, 1.0);\n    multiObj->addObjective(clearObj, 1.0);\n    ob::OptimizationObjectivePtr pathObj(multiObj);\n\n    if (isDynamic())\n    {\n        // shortcutter.shortcutPath(gpath);\n    }\n    else\n    {\n        og::PathSimplifier shortcutter(Q1, ob::GoalPtr(), pathObj);\n        // make sure that we have enough vertices so that the right path class is\n        // visualized (problems with S1)\n        if (Q1->getStateSpace()->getType() == ob::STATE_SPACE_SO2)\n        {\n            gpath.interpolate();\n        }\n        else\n        {\n            shortcutter.smoothBSpline(gpath);\n            shortcutter.simplifyMax(gpath);\n        }\n    }\n\n    if (!isDynamic() && !isProjectable(gpath.getStates()))\n    {\n        std::cout << \"REJECTED (Not projectable)\" << std::endl;\n        numberOfFailedAddingPathCalls++;\n        return;\n    }\n\n    if (!isDynamic() && !pathVisibilityChecker_->CheckValidity(gpath.getStates()))\n    {\n        std::cout << \"REJECTED (Infeasible)\" << std::endl;\n        numberOfFailedAddingPathCalls++;\n        return;\n    }\n\n    if (pathStack_.size() <= 0)\n    {\n        pathStack_.push_back(gpath);\n    }\n    else\n    {\n        for (uint k = 0; k < pathStack_.size(); k++)\n        {\n            og::PathGeometric &pathk = pathStack_.at(k);\n            if (pathVisibilityChecker_->IsPathVisible(gpath.getStates(), pathk.getStates()))\n            {\n                std::cout << \"REJECTED (Equal to path \" << k << \")\" << std::endl;\n                numberOfFailedAddingPathCalls++;\n                return;\n            }\n        }\n        pathStack_.push_back(gpath);\n    }\n    std::cout << \"Added to stack (\" << pathStack_.size() << \" paths on stack)\" << std::endl;\n}\nvoid QuotientSpaceGraphSparse::PrintPathStack()\n{\n    std::cout << std::string(80, '-') << std::endl;\n    std::cout << \"Path Stack\" << std::endl;\n    std::cout << std::string(80, '-') << std::endl;\n    for (uint k = 0; k < pathStack_.size(); k++)\n    {\n        std::vector<ob::State *> pathk = pathStack_.at(k).getStates();\n        for (uint j = 0; j < pathk.size(); j++)\n        {\n            Q1->printState(pathk.at(j));\n        }\n        std::cout << std::string(80, '-') << std::endl;\n    }\n}\n\nvoid QuotientSpaceGraphSparse::removeEdgeIfReductionLoop(const Edge &e)\n{\n    const Vertex v1 = boost::source(e, graphSparse_);\n    const Vertex v2 = boost::target(e, graphSparse_);\n\n    //############################################################################\n    // (2) Get common neighbors of v1,v2\n    std::vector<Vertex> v1_neighbors;\n    std::vector<Vertex> v2_neighbors;\n    std::vector<Vertex> common_neighbors;\n\n    OEIterator edge_iter, edge_iter_end, next;\n\n    boost::tie(edge_iter, edge_iter_end) = boost::out_edges(v1, graphSparse_);\n    for (next = edge_iter; edge_iter != edge_iter_end; edge_iter = next)\n    {\n        const Vertex v_target = boost::target(*edge_iter, graphSparse_);\n        if (v_target != v2)\n            v1_neighbors.push_back(v_target);\n        ++next;\n    }\n    boost::tie(edge_iter, edge_iter_end) = boost::out_edges(v2, graphSparse_);\n    for (next = edge_iter; edge_iter != edge_iter_end; edge_iter = next)\n    {\n        const Vertex v_target = boost::target(*edge_iter, graphSparse_);\n        if (v_target != v1)\n            v2_neighbors.push_back(v_target);\n        ++next;\n    }\n\n    for (uint k = 0; k < v1_neighbors.size(); k++)\n    {\n        for (uint j = 0; j < v2_neighbors.size(); j++)\n        {\n            const Vertex v1k = v1_neighbors.at(k);\n            const Vertex v2k = v2_neighbors.at(j);\n            if (v1k == v2k)\n            {\n                common_neighbors.push_back(v1k);\n            }\n        }\n    }\n\n    // rm duplicates\n    std::sort(common_neighbors.begin(), common_neighbors.end());\n    auto last = std::unique(common_neighbors.begin(), common_neighbors.end());\n    common_neighbors.erase(last, common_neighbors.end());\n\n    //############################################################################\n    //  (3) Check if face (v1, v2, v3) is feasible\n    for (uint k = 0; k < common_neighbors.size(); k++)\n    {\n        const Vertex v3 = common_neighbors.at(k);\n        std::vector<Vertex> vpath1;\n        vpath1.push_back(v1);\n        vpath1.push_back(v3);\n        vpath1.push_back(v2);\n        std::vector<Vertex> vpath2;\n        vpath2.push_back(v1);\n        vpath2.push_back(v2);\n\n        if (pathVisibilityChecker_->IsPathVisible(vpath1, vpath2, graphSparse_))\n        {\n            // RemoveEdge\n            std::cout << \"Removing Edge \" << v1 << \"<->\" << v2 << std::endl;\n            boost::remove_edge(v1, v2, graphSparse_);\n        }\n    }\n}\nvoid QuotientSpaceGraphSparse::removeReducibleLoops()\n{\n    // Edge e = boost::random_edge(graphSparse_, rng_boost);\n    uint Mend = boost::num_edges(graphSparse_);\n    for (uint k = 0; k < Mend; k++)\n    {\n        Edge e = boost::random_edge(graphSparse_, rng_boost);\n        removeEdgeIfReductionLoop(e);\n    }\n}\n\nvoid QuotientSpaceGraphSparse::freePath(std::vector<ob::State *> path, const ob::SpaceInformationPtr &si) const\n{\n    for (uint k = 0; k < path.size(); k++)\n    {\n        si->freeState(path.at(k));\n    }\n    path.clear();\n}\nstd::vector<ob::State *> QuotientSpaceGraphSparse::getProjectedPath(std::vector<ob::State *> pathQ1,\n                                                                    const ob::SpaceInformationPtr &si) const\n{\n    std::vector<ob::State *> pathQ0;\n    for (uint k = 0; k < pathQ1.size(); k++)\n    {\n        ob::State *qk = pathQ1.at(k);\n        ob::State *qkProjected = Q0->allocState();\n        projectQ0(qk, qkProjected);\n        pathQ0.push_back(qkProjected);\n    }\n    return pathQ0;\n}\n\nbool QuotientSpaceGraphSparse::isProjectable(const std::vector<ob::State *> &pathQ1) const\n{\n    return (getProjectionIndex(pathQ1) >= 0);\n}\n\nint QuotientSpaceGraphSparse::getProjectionIndex(const std::vector<ob::State *> &pathQ1) const\n{\n    if (!hasParent())\n        return 0;\n    std::vector<ob::State *> pathQ0 = getProjectedPath(pathQ1, Q0);\n    // for(uint k = 0; k < pathQ1.size(); k++){\n    //   ob::State *qk = pathQ1.at(k);\n    //   ob::State *qkProjected = Q0->allocState();\n    //   projectQ0(qk, qkProjected);\n    //   pathQ0.push_back(qkProjected);\n    // }\n\n    QuotientSpaceGraphSparse *quotient = static_cast<QuotientSpaceGraphSparse *>(parent_);\n    unsigned int K = quotient->getNumberOfPaths();\n\n    for (uint k = 0; k < K; k++)\n    {\n        std::vector<ob::State *> pathQ0k = quotient->getKthPath(k);\n        bool visible = quotient->getPathVisibilityChecker()->IsPathVisible(pathQ0, pathQ0k);\n        if (visible)\n        {\n            freePath(pathQ0, Q0);\n            return k;\n        }\n    }\n    freePath(pathQ0, Q0);\n    return -1;\n}\n\nvoid QuotientSpaceGraphSparse::getPathIndices(const std::vector<ob::State *> &states, std::vector<int> &idxPath) const\n{\n    if (!hasParent())\n    {\n        return;\n    }\n    else\n    {\n        QuotientSpaceGraphSparse *quotient = static_cast<QuotientSpaceGraphSparse *>(parent_);\n        // TODO: we need to check here to which local minima we project. This is\n        // necessary, since sometimes we find a path which actually projects on a\n        // different quotient-space path (and not the selected one).\n        // APPROACH 1: Assign them all to selected path\n        // QuotientSpaceGraphSparse *quotient = static_cast<QuotientSpaceGraphSparse*>(parent_);\n        // unsigned int K = quotient->getNumberOfPaths();\n        // assert(K>0);\n        // unsigned int Ks = quotient->selectedPath;\n        // assert(Ks>=0);\n        // idxPath.push_back(Ks);\n        // quotient->getPathIndices(states, idxPath);\n        if (isDynamic())\n        {\n            int Ks = quotient->selectedPath;\n            std::cout << \"DYNAMIC Projection Index \" << Ks << \"| \" << getName() << std::endl;\n            idxPath.push_back(Ks);\n        }\n        else\n        {\n            int K = getProjectionIndex(states);\n            std::cout << \"Projection Index \" << K << \"| \" << getName() << std::endl;\n            if (K < 0)\n            {\n                K = 0;\n                OMPL_WARN(\"Projection not found. Possibly unprojectable path.\");\n            }\n            idxPath.push_back(K);\n            // quotient->getPathIndices(states, idxPath);\n        }\n        std::vector<ob::State *> pathQ0 = getProjectedPath(states, Q0);\n        quotient->getPathIndices(pathQ0, idxPath);\n\n        // APPROACH 2: Assign them to their projection\n        // convert CS path to QS path\n        // std::vector<ob::State*> pathcur;\n        // for(uint k = 0; k < states.size(); k++){\n        //  ob::State *qk = states.at(k);\n        //  ob::State *qkProjected = Q0->allocState();\n        //  projectQ0(qk, qkProjected);\n        //  pathcur.push_back(qkProjected);\n        //}\n        ////Check which path can be deformed into QS path\n        // QuotientSpaceGraphSparse *quotient = static_cast<QuotientSpaceGraphSparse*>(parent_);\n        // unsigned int K = quotient->getNumberOfPaths();\n        // assert(K>0);\n\n        // bool success = false;\n        // for(uint k = 0; k < K; k++){\n        //   std::vector<ob::State*> pathk = quotient->getKthPath(k);\n        //   bool visible = quotient->getPathVisibilityChecker()->IsPathVisible(pathcur, pathk);\n        //   if(visible){\n        //     idxPath.push_back(k);\n        //     quotient->getPathIndices(pathcur, idxPath);\n        //     success = true;\n        //     break;\n        //   }\n        // }\n        // if(!success){\n        //  //This path is not deformable into any of the QuotientSpace paths\n        //  //One way to resolve this issue would be to add the new\n        //  OMPL_INFORM(\"Could not find projected path on QuotientSpace. Creating new one.\");\n\n        //  quotient->removeLastPathFromStack();\n        //  quotient->pushPathToStack(pathcur);\n        //  idxPath.push_back(0);\n        //  quotient->getPathIndices(pathcur, idxPath);\n        //}else{\n        //  //free all states\n        //  for(uint k = 0; k < pathcur.size(); k++){\n        //    Q0->freeState(pathcur.at(k));\n        //  }\n        //}\n    }\n    // idxPath.insert(shortestVertexPath_.begin(), vpath.rbegin(), vpath.rend());\n    // idxPath.insert(idxPath.begin(), idxPath.rbegin(), idxPath.rend());\n}\n\nPathVisibilityChecker *QuotientSpaceGraphSparse::getPathVisibilityChecker()\n{\n    return pathVisibilityChecker_;\n}\nconst std::vector<ob::State *> QuotientSpaceGraphSparse::getKthPath(uint k) const\n{\n    return pathStackHead_.at(k);\n}\n\n// A recursive function to print all paths from 'u' to 'd'.\n// visited[] keeps track of vertices in current path.\n// path[] stores actual vertices and path_index is current\n// index in path[]\nvoid QuotientSpaceGraphSparse::printAllPathsUtil(Vertex u, Vertex d, bool visited[], int path[], int &path_index)\n{\n    // terminate if we have enough paths in stack\n    if (pathStack_.size() > Nhead)\n        return;\n    if (numberOfFailedAddingPathCalls > 10)\n        return;\n\n    // Mark the current node and store it in path[]\n    visited[u] = true;\n    path[path_index] = u;\n    path_index++;\n\n    // If current vertex is same as destination, then print\n    // current path[]\n    if (u == d)\n    {\n        std::vector<ob::State *> pp;\n        for (int i = 0; i < path_index; i++)\n        {\n            pp.push_back(graphSparse_[path[i]]->state);\n        }\n        pushPathToStack(pp);\n    }\n    else  // If current vertex is not destination\n    {\n        // Recur for all the vertices adjacent to current vertex\n        OEIterator ei, ei_end;\n        for (boost::tie(ei, ei_end) = boost::out_edges(u, graphSparse_); ei != ei_end; ++ei)\n        {\n            Vertex source = boost::source(*ei, graphSparse_);\n            Vertex target = boost::target(*ei, graphSparse_);\n            Vertex vnext = (source == u ? target : source);\n            if (!visited[vnext])\n            {\n                printAllPathsUtil(vnext, d, visited, path, path_index);\n                if (pathStack_.size() > Nhead)\n                    break;\n            }\n        }\n    }\n\n    // Remove current vertex from path[] and mark it as unvisited\n    path_index--;\n    visited[u] = false;\n}\n// used in QuotientSpaceGraphSparse::enumerateAllPaths()  which used nowhere\nbool QuotientSpaceGraphSparse::hasSparseGraphChanged()\n{\n    unsigned Nv = boost::num_vertices(graphSparse_);\n    unsigned Ne = boost::num_edges(graphSparse_);\n    if ((Nv > Nold_v) || (Ne > Nold_e))\n    {\n        Nold_v = Nv;\n        Nold_e = Ne;\n        return true;\n    }\n    return false;\n}\n// used nowhere\nvoid QuotientSpaceGraphSparse::enumerateAllPaths()\n{\n    if (!hasSolution_)\n        return;\n\n    if (isDynamic())\n    {\n        ob::PathPtr path;\n\n        const Configuration *q_nearest_to_goal = nearest(qGoal_);\n        Configuration *qStartSparse = graphSparse_[v_start_sparse];\n        path = getPathSparse(qStartSparse->index, q_nearest_to_goal->index);\n        if (path == nullptr)\n        {\n            OMPL_WARN(\"No solution found, but hasSolution_ is set.\");\n            return;\n        }\n        og::PathGeometric &gpath = static_cast<og::PathGeometric &>(*path);\n        // pathStack_.push_back(gpath);\n\n        unsigned int kBefore = pathStack_.size();\n        pushPathToStack(gpath.getStates());\n        unsigned int kAfter = pathStack_.size();\n        if (kAfter > kBefore)\n            clearDynamic();\n    }\n    else\n    {\n        // Check if we already enumerated all paths. If yes, then the number of\n        // vertices has not changed.\n        if (!hasSparseGraphChanged())\n        {\n            return;\n        }\n        // TestVisibilityChecker();\n        std::cout << \"Enumerating paths on \" << getName() << std::endl;\n\n        // Remove Edges\n        //(1) REDUCIBLE: Removal of reducible loops [Schmitzberger 02]\n        removeReducibleLoops();\n        //############################################################################\n\n        // PathEnumerator pe(v_start_sparse, v_goal_sparse, graphSparse_);\n        // pe.ComputePaths();\n\n        unsigned numberVertices = boost::num_vertices(graphSparse_);\n        if (numberVertices <= 0)\n            return;\n        bool *visited = new bool[numberVertices];\n        std::cout << \"Sparse Graph has \" << boost::num_vertices(graphSparse_) << \" vertices and \"\n                  << boost::num_edges(graphSparse_) << \" edges.\" << std::endl;\n\n        int *path = new int[numberVertices];\n        int path_index = 0;  // Initialize path[] as empty\n\n        for (unsigned int i = 0; i < numberVertices; i++)\n            visited[i] = false;\n\n        numberOfFailedAddingPathCalls = 0;\n\n        printAllPathsUtil(v_start_sparse, v_goal_sparse, visited, path, path_index);\n        //############################################################################\n    }\n    uint Npathsize = pathStack_.size();\n    uint Npaths = std::min(Nhead, Npathsize);\n    pathStackHead_.clear();\n    for (uint k = 0; k < Npaths; k++)\n    {\n        // og::PathGeometric& pathK = (*(pathStack_.rbegin()+k));\n        og::PathGeometric &pathK = pathStack_.at(k);  //*(pathStack_.rbegin()+k));\n        pathStackHead_.push_back(pathK.getStates());\n    }\n    OMPL_INFORM(\"Found %d path classes.\", pathStackHead_.size());\n    OMPL_INFORM(\"%s\", std::string(80, '-').c_str());\n\n    // TODO: update internally QuotientSpace hierarchy. Create new QuotientSpaces\n    // for each path.\n}\n\nvoid QuotientSpaceGraphSparse::getPlannerDataRoadmap(ob::PlannerData &data, std::vector<int> pathIdx) const\n{\n    foreach (const Vertex v, boost::vertices(graphSparse_))\n    {\n        ob::PlannerDataVertexAnnotated p(graphSparse_[v]->state);\n        p.setLevel(level_);\n        p.setPath(pathIdx);\n        data.addVertex(p);\n    }\n    foreach (const Edge e, boost::edges(graphSparse_))\n    {\n        const Vertex v1 = boost::source(e, graphSparse_);\n        const Vertex v2 = boost::target(e, graphSparse_);\n\n        ob::PlannerDataVertexAnnotated p1(graphSparse_[v1]->state);\n        ob::PlannerDataVertexAnnotated p2(graphSparse_[v2]->state);\n\n        data.addEdge(p1, p2);\n    }\n}\n\nvoid QuotientSpaceGraphSparse::print(std::ostream &out) const\n{\n    BaseT::print(out);\n    out << \"   --[QuotientSpaceGraphSparse has \" << boost::num_vertices(graphSparse_) << \" vertices and \"\n        << boost::num_edges(graphSparse_) << \" edges.]\" << std::endl;\n}\n\nstd::vector<int> QuotientSpaceGraphSparse::GetSelectedPathIndex() const\n{\n    std::vector<int> CurPath;\n    QuotientSpaceGraphSparse *pparent = static_cast<QuotientSpaceGraphSparse *>(parent_);\n    while (pparent != nullptr)\n    {\n        CurPath.push_back(pparent->selectedPath);\n        pparent = static_cast<QuotientSpaceGraphSparse *>(pparent->parent_);\n    }\n    if (selectedPath < 0)\n        CurPath.push_back(0);\n    else\n        CurPath.push_back(selectedPath);\n\n    return CurPath;\n}\n\nbool ompl::geometric::QuotientSpaceGraphSparse::getSolution(base::PathPtr &solution)\n{\n    if (hasSolution_)\n    {\n        solutionPath_ = getPath(v_start_sparse, v_goal_sparse, graphSparse_);\n        startGoalVertexPath_ = shortestVertexPath_;\n        solution = solutionPath_;\n        return true;\n    }\n    else\n    {\n        base::Goal *g = pdef_->getGoal().get();\n        bestCost_ = base::Cost(+base::dInf);\n        bool same_component = sameComponent(v_start_sparse, v_goal_sparse);\n\n        if (same_component &&\n            g->isStartGoalPairValid(graphSparse_[v_goal_sparse]->state, graphSparse_[v_start_sparse]->state))\n        {\n            solutionPath_ = getPath(v_start_sparse, v_goal_sparse, graphSparse_);\n            if (solutionPath_)\n            {\n                solution = solutionPath_;\n                hasSolution_ = true;\n                startGoalVertexPath_ = shortestVertexPath_;\n                return true;\n            }\n        }\n    }\n    return hasSolution_;\n}\n\nvoid QuotientSpaceGraphSparse::getPlannerData(ob::PlannerData &data) const\n{\n    OMPL_DEBUG(\"Sparse Roadmap has %d/%d vertices/edges (Dense has %d/%d).\", boost::num_vertices(graphSparse_),\n               boost::num_edges(graphSparse_), boost::num_vertices(graph_), boost::num_edges(graph_));\n    // QuotientSpaceGraph::getPlannerData(data);\n    // from QSGraph\n    std::vector<int> idxPathI;\n    QuotientSpace *pparent = getParent();\n    while (pparent != nullptr)\n    {\n        idxPathI.push_back(0);\n        pparent = pparent->getParent();\n    }\n    idxPathI.push_back(0);\n\n    unsigned int startComponent = 0;\n    unsigned int goalComponent = 1;\n\n    base::PlannerDataVertexAnnotated pstart(graphSparse_[vStart_]->state, startComponent);\n    pstart.setPath(idxPathI);\n    data.addStartVertex(pstart);\n\n    if (hasSolution_)\n    {\n        goalComponent = 0;\n        base::PlannerDataVertexAnnotated pgoal(graphSparse_[vGoal_]->state, goalComponent);\n        pgoal.setPath(idxPathI);\n        data.addGoalVertex(pgoal);\n    }\n\n    foreach (const Edge e, boost::edges(graphSparse_))\n    {\n        const Vertex v1 = boost::source(e, graphSparse_);\n        const Vertex v2 = boost::target(e, graphSparse_);\n\n        base::PlannerDataVertexAnnotated p1(graphSparse_[v1]->state);\n        base::PlannerDataVertexAnnotated p2(graphSparse_[v2]->state);\n        p1.setPath(idxPathI);\n        p2.setPath(idxPathI);\n\n        unsigned int vi1 = data.addVertex(p1);\n        unsigned int vi2 = data.addVertex(p2);\n        data.addEdge(p1, p2);\n\n        unsigned int v1Component = const_cast<QuotientSpaceGraphSparse *>(this)->disjointSetsSparse_.find_set(v1);\n        unsigned int v2Component = const_cast<QuotientSpaceGraphSparse *>(this)->disjointSetsSparse_.find_set(v2);\n        base::PlannerDataVertexAnnotated &v1a = static_cast<base::PlannerDataVertexAnnotated &>(data.getVertex(vi1));\n        base::PlannerDataVertexAnnotated &v2a = static_cast<base::PlannerDataVertexAnnotated &>(data.getVertex(vi2));\n\n        if (v1Component == startComponent || v2Component == startComponent)\n        {\n            v1a.setComponent(0);\n            v2a.setComponent(0);\n        }\n        else if (v1Component == goalComponent || v2Component == goalComponent)\n        {\n            v1a.setComponent(1);\n            v2a.setComponent(1);\n        }\n        else\n        {\n            v1a.setComponent(2);\n            v2a.setComponent(2);\n        }\n    }\n    // Make sure to add edge-less nodes as well\n    // add dense nodes\n    /*foreach (const Vertex n, boost::vertices(graph_)){\n      base::PlannerDataVertexAnnotated node(graph_[n]->state, 2);\n      node.setPath(idxPathI);\n      data.addVertex(node);\n    }*/\n    // add sparse nodes green color\n    foreach (const Vertex n, boost::vertices(graphSparse_))\n    {\n        base::PlannerDataVertexAnnotated node(graphSparse_[n]->state, 3);\n        node.setPath(idxPathI);\n        data.addVertex(node);\n    }\n    // end\n    /*return;\n\n    if(pathStackHead_.empty()){\n        OMPL_ERROR(\"%s has 0 solutions.\", getName().c_str());\n            throw ompl::Exception(\"Zero solutions\");\n        }\n    if(pathStackHead_.size()>0){\n        OMPL_DEVMSG1(\"%s has %d solutions.\", getName().c_str(), pathStackHead_.size());\n        std::vector<int> idxPathI;\n        for(uint i = 0; i < pathStackHead_.size(); i++){\n            const std::vector<ob::State*> states = pathStackHead_.at(i);\n\n            idxPathI.clear();\n            getPathIndices(states, idxPathI);\n            std::reverse(idxPathI.begin(), idxPathI.end());\n            idxPathI.push_back(i);\n            // idxPathI.insert(idxPathI.begin(), idxPathI.rbegin(), idxPathI.rend());\n\n            //############################################################################\n            //DEBUG\n            std::cout << \"[\";\n            for(uint k = 0; k < idxPathI.size(); k++){\n              std::cout << idxPathI.at(k) << \" \";\n            }\n            std::cout << \"]\" << std::endl;\n            //############################################################################\n\n            ob::PlannerDataVertexAnnotated *p1 = new ob::PlannerDataVertexAnnotated(states.at(0));\n            p1->setLevel(level_);\n            p1->setPath(idxPathI);\n            data.addStartVertex(*p1);\n\n            for(uint k = 0; k < states.size()-1; k++){\n\n              ob::PlannerDataVertexAnnotated *p2 = new\n    ob::PlannerDataVertexAnnotated(states.at(k+1));//Q1->cloneState(graphSparse_[v2]->state)); p2->setLevel(level_);\n              p2->setPath(idxPathI);\n\n              if(k==states.size()-2){\n                data.addGoalVertex(*p2);\n              }else{\n                data.addVertex(*p2);\n              }\n              data.addEdge(*p1,*p2);\n\n              p1 = p2;\n            }\n        }\n        // idxPathI = GetSelectedPathIndex();\n        getPlannerDataRoadmap(data, idxPathI);\n    }else{\n\n      if(boost::num_vertices(graphSparse_) > 0){\n        std::vector<int> CurPath = GetSelectedPathIndex();\n        // for(uint k = 0; k < CurPath.size(); k++) std::cout << CurPath.at(k) << \",\";\n        // std::cout << std::endl;\n\n        getPlannerDataRoadmap(data, CurPath);\n      }\n\n    }*/\n}\n", "meta": {"hexsha": "236fe8cf10947322a04d4c0c4178df924b111ef8", "size": 59952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/geometric/planners/quotientspace/datastructures/src/QuotientSpaceGraphSparse.cpp", "max_stars_repo_name": "sohaib-gujjar/ompl", "max_stars_repo_head_hexsha": "d3f803af845771b30eb03b6698b82d3dd2fd8de2", "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/ompl/geometric/planners/quotientspace/datastructures/src/QuotientSpaceGraphSparse.cpp", "max_issues_repo_name": "sohaib-gujjar/ompl", "max_issues_repo_head_hexsha": "d3f803af845771b30eb03b6698b82d3dd2fd8de2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/geometric/planners/quotientspace/datastructures/src/QuotientSpaceGraphSparse.cpp", "max_forks_repo_name": "sohaib-gujjar/ompl", "max_forks_repo_head_hexsha": "d3f803af845771b30eb03b6698b82d3dd2fd8de2", "max_forks_repo_licenses": ["BSD-3-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.6454767726, "max_line_length": 148, "alphanum_fraction": 0.5659527622, "num_tokens": 14019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.025957354654703464, "lm_q1q2_score": 0.010769676486173852}}
{"text": "#include \"filter.h\"\n#include \"branch_group.h\"\n#include <xpas/phylo_kmer_db.h>\n#include <xpas/version.h>\n#include <boost/filesystem.hpp>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <iostream>\n#include <random>\n\nusing namespace xpas;\nnamespace fs = boost::filesystem;\n\n\n/// A pair storing the information needed to evaluate a phylo k-mer by\n/// the filtering function. \"Value\" is the value calculated by the filter\n/// which is used to compare the informativeness of the k-mer against the others\nstruct filter_value\n{\n    phylo_kmer::key_type key;\n    double filter_score;\n    size_t num_entries;\n\n    bool operator<(const filter_value& rhs) const\n    {\n        return filter_score < rhs.filter_score;\n    }\n\n    bool operator>(const filter_value& rhs) const\n    {\n        return filter_score > rhs.filter_score;\n    }\n};\n\nstd::string xpas::get_fvs_file(const std::string& working_dir, size_t batch_idx)\n{\n    return (fs::path{xpas::get_groups_dir(working_dir)} / fs::path(std::to_string(batch_idx) + \".fvs\")).string();\n}\n\nkmer_filter::kmer_filter(std::string working_dir, size_t num_batches, double mu, phylo_kmer::score_type threshold)\n    : _working_dir{ std::move(working_dir) }, _num_batches{ num_batches }, _mu{ mu }, _threshold{ threshold }\n{}\n\nxpas::phylo_kmer::score_type logscore_to_score(xpas::phylo_kmer::score_type log_score)\n{\n    return std::min(std::pow(10, log_score), 1.0);\n}\n\nclass batched_filter : public kmer_filter\n{\npublic:\n    batched_filter(size_t total_num_groups, std::string working_dir, size_t num_batches, double mu, phylo_kmer::score_type threshold)\n        : kmer_filter{ std::move(working_dir), num_batches, mu, threshold },\n        _total_num_groups{ total_num_groups }\n    {}\n\n    ~batched_filter() noexcept override = default;\n\n    void filter(const std::vector<phylo_kmer::branch_type>& group_ids) override\n    {\n        /// Create Filter Value files for every batch\n        std::vector<std::vector<filter_value>> batch_filter_values;\n\n        size_t total_num_kmers = 0;\n\n        /// num of pairs { branch -> score }\n        size_t total_num_entries = 0;\n\n        for (size_t batch_idx = 0; batch_idx < _num_batches; ++batch_idx)\n        {\n            /// Merge hashmaps of the same batch\n            auto batch_db = merge_batch(_working_dir, group_ids, batch_idx);\n            total_num_kmers += batch_db.size();\n            total_num_entries += get_num_entries(batch_db);\n\n            /// Calculate filter values for the batch\n            auto filter_values = calc_filter_values(batch_db);\n\n            /// FIXME: do the partial sort to the (mu * total_num_kmers)th element\n            std::sort(filter_values.begin(), filter_values.end());\n            batch_filter_values.push_back(std::move(filter_values));\n        }\n\n        /// The vector of indexes of top kmers for every batch,\n        /// needed for the merge\n        std::vector<size_t> batch_idx(_num_batches, 0);\n\n        /// Initialize a min-heap for the merge algorithm\n        std::priority_queue<filter_value, std::vector<filter_value>, std::greater<>> heap;\n        for (const auto& batch_fv : batch_filter_values)\n        {\n            heap.push(batch_fv[0]);\n        }\n\n        size_t max_entries_allowed = _mu * total_num_entries;\n        size_t num_entries = 0;\n        while (num_entries < max_entries_allowed)\n        {\n            /// Mark the top k-mer as good\n            auto best_fv = heap.top();\n            heap.pop();\n            _filtered.insert(best_fv.key);\n            num_entries += best_fv.num_entries;\n\n            /// take the next k-mer value from this batch\n            size_t best_kmer_index = kmer_batch(best_fv.key, _num_batches);\n            const auto& best_kmer_batch = batch_filter_values[best_kmer_index];\n            batch_idx[best_kmer_index]++;\n            if (batch_idx[best_kmer_index] < best_kmer_batch.size())\n            {\n                /// and push it to the heap\n                heap.push(best_kmer_batch[batch_idx[best_kmer_index]]);\n            }\n        }\n    }\n\n    bool is_good(phylo_kmer::key_type key) const noexcept override\n    {\n        return _filtered.find(key) != _filtered.end();\n    }\n\nprotected:\n    size_t get_num_entries(const phylo_kmer_db& db) const\n    {\n        size_t num_entries = 0;\n        for (const auto& [kmer, entries] : db)\n        {\n            num_entries += entries.size();\n        }\n        return num_entries;\n    }\n    virtual std::vector<filter_value> calc_filter_values(const phylo_kmer_db& db) const = 0;\n\n    /// The total number of groups for which k-mers values are calculated\n    size_t _total_num_groups;\n\n    /// The set of k-mers taken by the filter\n    std::unordered_set<phylo_kmer::key_type> _filtered;\n\n};\n\nclass entropy_filter : public batched_filter\n{\npublic:\n    entropy_filter(size_t total_num_groups, std::string working_dir, size_t num_batches, double mu,\n                   phylo_kmer::score_type threshold)\n        : batched_filter{ total_num_groups, std::move(working_dir), num_batches, mu, threshold }\n    {}\n\n    ~entropy_filter() noexcept override = default;\n\n    void filter(const std::vector<phylo_kmer::branch_type>& group_ids) override\n    {\n        std::cout << \"Filtering (minimal conditional entropy)...\" << std::endl;\n        batched_filter::filter(group_ids);\n    }\n\nprivate:\n    static double shannon(double x)\n    {\n        return - x * std::log2(x);\n    }\n\n    std::vector<filter_value> calc_filter_values(const phylo_kmer_db& db) const override\n    {\n        std::vector<filter_value> filter_values;\n\n        for (const auto& [key, entries] : db)\n        {\n            /// calculate the score sum to normalize scores\n            double score_sum = 0;\n#ifdef KEEP_POSITIONS\n            for (const auto& [branch, log_score, position] : entries)\n            {\n                (void)branch;\n                (void)position;\n                score_sum += logscore_to_score(log_score);\n            }\n#else\n            for (const auto&[branch, log_score] : entries)\n            {\n                (void) branch;\n                score_sum += logscore_to_score(log_score);\n            }\n#endif\n\n            /// do not forget the branches that are not stored in the database,\n            /// they suppose to have the threshold score\n            score_sum += static_cast<double>(_total_num_groups - entries.size()) * _threshold;\n\n            /// Entropy\n            const auto weighted_threshold = _threshold / score_sum;\n            const auto target_threshold = shannon(weighted_threshold);\n\n            auto fv = filter_value{key, 0.0, entries.size()};\n            auto HcBw1 = static_cast<double>(_total_num_groups) * target_threshold;\n#ifdef KEEP_POSITIONS\n            for (const auto& [branch, log_score, position] : entries)\n#else\n            for (const auto&[branch, log_score] : entries)\n#endif\n            {\n                /// s_wc / S_w\n                const auto weighted_score = logscore_to_score(log_score) / score_sum;\n                const auto target_value = shannon(weighted_score);\n\n                HcBw1 = HcBw1 - target_threshold + target_value;\n                //std::cout << \"FV: \" << key << \" \" << xpas::decode_kmer(key, 5) << \" \" <<\n                //                                                                      filter_stats[key] << std::endl;\n            }\n            //std::cout << \"\\tEntropy: \" << HcBw1 << std::endl;\n            fv.filter_score = HcBw1;\n            filter_values.push_back(fv);\n        }\n        return filter_values;\n    }\n\n};\n\nclass mif0_filter : public batched_filter\n{\npublic:\n    mif0_filter(size_t total_num_groups, std::string working_dir, size_t num_batches, double mu,\n                phylo_kmer::score_type threshold)\n        : batched_filter{ total_num_groups, std::move(working_dir), num_batches, mu, threshold }\n    {}\n\n    ~mif0_filter() noexcept override = default;\n\n    void filter(const std::vector<phylo_kmer::branch_type>& group_ids) override\n    {\n        std::cout << \"Filtering (maximal mutual information, short version)...\" << std::endl;\n        batched_filter::filter(group_ids);\n    }\n\nprivate:\n    static double shannon(double x)\n    {\n        return - x * std::log2(x);\n    }\n\n    std::vector<filter_value> calc_filter_values(const phylo_kmer_db& db) const override\n    {\n        std::vector<filter_value> filter_values;\n        for (const auto& [key, entries] : db)\n        {\n            /// calculate the score sum to normalize scores7\n            /// i.e. S_w by the notation\n            double score_sum = 0;\n#ifdef KEEP_POSITIONS\n            for (const auto& [branch, log_score, position] : entries)\n            {\n                (void)branch;\n                (void)position;\n                score_sum += logscore_to_score(log_score);\n            }\n#else\n            //std::cout << key << std::endl;\n            for (const auto& [branch, log_score] : entries)\n            {\n                (void)branch;\n                score_sum += logscore_to_score(log_score);\n\n                //std::cout << \"\\t\" << logscore_to_score(log_score) << \",\" << std::endl;\n            }\n#endif\n\n            /// do not forget the branches that are not stored in the database,\n            /// they suppose to have the threshold score\n            score_sum += static_cast<double>(_total_num_groups - entries.size()) * _threshold;\n\n            //std::cout << \"\\tTreshold: \" << _threshold << std::endl;\n            //std::cout << \"\\tS_w: \" << score_sum << std::endl;\n\n            /// s_wc / S_w, if s_wc == threshold\n            const auto weighted_threshold = _threshold / score_sum;\n            const auto target_threshold = shannon(weighted_threshold);\n\n            auto fv = filter_value{key, 0.0, entries.size()};\n            auto HcBw1 = static_cast<double>(_total_num_groups) * target_threshold;\n#ifdef KEEP_POSITIONS\n            for (const auto& [branch, log_score, position] : entries)\n#else\n            for (const auto& [branch, log_score] : entries)\n#endif\n            {\n                /// s_wc / S_w\n                const auto weighted_score = logscore_to_score(log_score) / score_sum;\n                const auto target_value = shannon(weighted_score);\n\n                HcBw1 = HcBw1 - target_threshold + target_value;\n                //std::cout << \"FV: \" << key << \" \" << xpas::decode_kmer(key, 5) << \" \" <<\n                //                                                                      filter_stats[key] << std::endl;\n            }\n\n            //std::cout << \"\\tEntropy: \" << filter_stats[key] << std::endl;\n            const auto Hc = std::log2(_total_num_groups);\n\n            /// MIs: Sw [ H(c) - H(c | B_w = 1) ] -> max\n            ///   or equivalently\n            ///      Sw [ H(c | B_w = 1) - H(c) ] -> min\n            fv.filter_score = score_sum * (HcBw1 - Hc);\n            //std::cout << \"\\t - MIF0: \" << fv.filter_score << std::endl;\n\n            filter_values.push_back(fv);\n        }\n        return filter_values;\n    }\n};\n\n\nclass mif1_filter : public batched_filter\n{\npublic:\n    mif1_filter(size_t total_num_groups, std::string working_dir, size_t num_batches, double mu,\n                phylo_kmer::score_type threshold)\n        : batched_filter{ total_num_groups, std::move(working_dir), num_batches, mu, threshold }\n    {}\n\n    ~mif1_filter() noexcept override = default;\n\n    void filter(const std::vector<phylo_kmer::branch_type>& group_ids) override\n    {\n        std::cout << \"Filtering (maximal mutual information, full version)...\" << std::endl;\n        batched_filter::filter(group_ids);\n    }\n\nprivate:\n    static double shannon(double x)\n    {\n        return - x * std::log2(x);\n    }\n\n    std::vector<filter_value> calc_filter_values(const phylo_kmer_db& db) const override\n    {\n        std::vector<filter_value> filter_values;\n        const auto N = _total_num_groups;\n\n        for (const auto& [key, entries] : db)\n        {\n            //std::cout << key << std::endl;\n\n            /// calculate the score sum to normalize scores\n            double Sw = 0;\n#ifdef KEEP_POSITIONS\n            for (const auto& [branch, log_score, position] : entries)\n            {\n                (void)branch;\n                (void)position;\n                Sw += logscore_to_score(log_score);\n            }\n#else\n            for (const auto& [branch, log_score] : entries)\n            {\n                (void)branch;\n                Sw += logscore_to_score(log_score);\n\n                //std::cout << \"\\t\" << logscore_to_score(log_score) << \",\" << std::endl;\n            }\n#endif\n\n            /// do not forget the branches that are not stored in the database,\n            /// they suppose to have the threshold score\n            Sw += static_cast<double>(N - entries.size()) * _threshold;\n\n            //std::cout << \"\\tSW = \" << Sw << std::endl;\n\n            /// Calculate the Mutual Information\n            /// MI = H(C) - H(C|Bw) =\n            ///    = H(C) - [P(Bw=1)H(C|Bw=1) + P(Bw=0)H(C|Bw=0)] =\n            ///    = A - (B + C)\n            const auto A = std::log2(_total_num_groups);\n\n            /// P(Bw == 1) = s_wc / Sw, if s_wc == threshold\n            const auto PBw1_threshold = _threshold / Sw;\n            /// P(Bw == 0) = (1 - s_wc) / (N - Sw), if s_wc == threshold\n            const auto PBw0_threshold = (1 - _threshold) / (N - Sw);\n\n            /// Calculate B and C: starting with the missing scores\n            double HcBw1 = static_cast<double>(N) * shannon(PBw1_threshold);\n            double HcBw0 = static_cast<double>(N) * shannon(PBw0_threshold);\n            auto fv = filter_value{key, 0.0, entries.size()};\n#ifdef KEEP_POSITIONS\n            for (const auto& [branch, log_score, position] : entries)\n#else\n            for (const auto& [branch, log_score] : entries)\n#endif\n            {\n                const auto swc = logscore_to_score(log_score);\n\n                /// P(c|Bw == 1) = s_wc / Sw\n                const auto PcBw1 = swc / Sw;\n                /// P(c|Bw == 0) = (1 - s_wc) / (N - Sw)\n                const auto PcBw0 = (1 - swc) / (N - Sw);\n\n                HcBw1 = HcBw1 - shannon(PBw1_threshold) + shannon(PcBw1);\n                HcBw0 = HcBw0 - shannon(PBw0_threshold) + shannon(PcBw0);\n            }\n            /// P(Bw=1)\n            const auto PBw1 = Sw / N;\n            const auto B = PBw1 * HcBw1;\n            /// P(Bw=0)\n            const auto PBw0 = (N - Sw) / N;\n            const auto C = PBw0 * HcBw0;\n\n\n            /// A - (B + C) -> max\n            /// which is A - B - C -> max\n            /// which is -A + B + C -> min\n            fv.filter_score = - A + B + C;\n            filter_values.push_back(fv);\n            //std::cout << \"\\tA: \" << A << std::endl;\n            //std::cout << \"\\tB: \" << B << std::endl;\n            //std::cout << \"\\tC: \" << C << std::endl;\n            //std::cout << \"\\tMIF1: \" << fv.filter_score << std::endl;\n        }\n\n        return filter_values;\n    }\n};\n\nclass random_filter : public batched_filter\n{\npublic:\n    random_filter(size_t total_num_groups, std::string working_dir,\n                  size_t num_batches, double mu, phylo_kmer::score_type threshold)\n        : batched_filter{ total_num_groups, std::move(working_dir), num_batches, mu, threshold }\n    {}\n\n    ~random_filter() noexcept override = default;\n\n    void filter(const std::vector<phylo_kmer::branch_type>& group_ids) override\n    {\n        std::cout << \"Filtering (random)...\" << std::endl;\n        batched_filter::filter(group_ids);\n    }\n\nprivate:\n    std::vector<filter_value> calc_filter_values(const phylo_kmer_db& db) const override\n    {\n        std::vector<filter_value> filter_values;\n\n        std::default_random_engine generator(42);\n        std::uniform_real_distribution<double> distribution(0, 1);\n\n        for (const auto& [key, entries] : db)\n        {\n            auto fv = filter_value{ key, distribution(generator), entries.size() };\n            filter_values.push_back(fv);\n        }\n        return filter_values;\n    }\n};\n\nclass no_filter : public kmer_filter\n{\npublic:\n    no_filter(std::string working_dir, size_t num_batches, double mu, phylo_kmer::score_type threshold)\n        : kmer_filter{ std::move(working_dir), num_batches, mu, threshold }\n    {}\n\n    ~no_filter() noexcept override = default;\n\n    void filter(const std::vector<phylo_kmer::branch_type>& group_ids) override\n    {\n        (void)group_ids;\n    }\n\n    [[nodiscard]]\n    bool is_good(phylo_kmer::key_type key) const noexcept override\n    {\n        (void)key;\n        return true;\n    }\n};\n\n\nstd::unique_ptr<kmer_filter> xpas::make_filter(xpas::filter_type filter,\n                                               size_t total_num_nodes,\n                                               std::string working_dir, size_t num_batches,\n                                               double mu, phylo_kmer::score_type threshold)\n{\n    if (filter == filter_type::no_filter || mu == 1.0)\n    {\n        return std::make_unique<no_filter>(std::move(working_dir), num_batches, mu, threshold);\n    }\n    else if (filter == filter_type::entropy)\n    {\n        return std::make_unique<entropy_filter>(total_num_nodes, std::move(working_dir), num_batches, mu, threshold);\n    }\n    else if (filter == filter_type::mif0)\n    {\n        return std::make_unique<mif0_filter>(total_num_nodes, std::move(working_dir), num_batches, mu, threshold);\n    }\n    else if (filter == filter_type::mif1)\n    {\n        return std::make_unique<mif1_filter>(total_num_nodes, std::move(working_dir), num_batches, mu, threshold);\n    }\n    else if (filter == filter_type::random)\n    {\n        return std::make_unique<random_filter>(total_num_nodes, std::move(working_dir), num_batches, mu, threshold);\n    }\n    else\n    {\n        throw std::runtime_error(\"Error: Unsupported filter type.\");\n    }\n}", "meta": {"hexsha": "72e7f714ede208e2e1e5e49d4064be48e0705db1", "size": 17765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/src/filter.cpp", "max_stars_repo_name": "nromashchenko/xpas", "max_stars_repo_head_hexsha": "95ea95e9b937cf9216d6a55219008da1fc1dfc57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/src/filter.cpp", "max_issues_repo_name": "nromashchenko/xpas", "max_issues_repo_head_hexsha": "95ea95e9b937cf9216d6a55219008da1fc1dfc57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T13:04:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T14:48:55.000Z", "max_forks_repo_path": "build/src/filter.cpp", "max_forks_repo_name": "phylo42/xpas", "max_forks_repo_head_hexsha": "a3d4cac00cfc8c1a5c442e1dd6060c26037dc62d", "max_forks_repo_licenses": ["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.9704724409, "max_line_length": 133, "alphanum_fraction": 0.5821559246, "num_tokens": 4356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.025957355314023947, "lm_q1q2_score": 0.010769676384135415}}
{"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 \"random_numbers.h\"\n\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/random/lagged_fibonacci.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/scoped_ptr.hpp>\n#include <boost/thread/mutex.hpp>\n\nstatic boost::uint32_t first_seed_ = 0;\n\n/// Compute the first seed to be used; this function should be called only once\nstatic boost::uint32_t firstSeed(void)\n{\n    boost::scoped_ptr<int> mem(new int());\n    first_seed_ = (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                                    (unsigned long long)(mem.get()));\n    return first_seed_;\n}\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.\nstatic boost::uint32_t nextSeed(void)\n{\n    static boost::mutex                                                                rngMutex;\n    boost::mutex::scoped_lock                                                          slock(rngMutex);\n    static boost::lagged_fibonacci607                                                  sGen(firstSeed());\n    static boost::uniform_int<>                                                        sDist(1, 1000000000);\n    static boost::variate_generator<boost::lagged_fibonacci607&, boost::uniform_int<>> s(sGen, sDist);\n    boost::uint32_t                                                                    v = s();\n    return v;\n}\n\nrandom_numbers::RandomNumberGenerator::RandomNumberGenerator(void)\n    : generator_(nextSeed()), uniDist_(0, 1), normalDist_(0, 1), uni_(generator_, uniDist_),\n      normal_(generator_, normalDist_)\n{\n}\n\nrandom_numbers::RandomNumberGenerator::RandomNumberGenerator(boost::uint32_t seed)\n    : generator_(seed), uniDist_(0, 1), normalDist_(0, 1), uni_(generator_, uniDist_), normal_(generator_, normalDist_)\n{\n    // Because we manually specified a seed, we need to save it ourselves\n    first_seed_ = seed;\n}\n\n// From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III,\n//       pg. 124-132\nvoid random_numbers::RandomNumberGenerator::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\nboost::uint32_t random_numbers::RandomNumberGenerator::getFirstSeed()\n{\n    return first_seed_;\n}", "meta": {"hexsha": "e967d89c1c7ff58b7f150c4a8a5a08e2f34ea8ac", "size": 4663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/random_numbers.cpp", "max_stars_repo_name": "aqiugroup/DBow3", "max_stars_repo_head_hexsha": "289b38bff0daeaa956fb250196d1dd6dbefac8f6", "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": "utils/random_numbers.cpp", "max_issues_repo_name": "aqiugroup/DBow3", "max_issues_repo_head_hexsha": "289b38bff0daeaa956fb250196d1dd6dbefac8f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/random_numbers.cpp", "max_forks_repo_name": "aqiugroup/DBow3", "max_forks_repo_head_hexsha": "289b38bff0daeaa956fb250196d1dd6dbefac8f6", "max_forks_repo_licenses": ["BSD-3-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.4095238095, "max_line_length": 119, "alphanum_fraction": 0.6367145614, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.02716923212646138, "lm_q1q2_score": 0.010760867560040847}}
{"text": "#include \"utils.hh\"\n\n#include \"TensorField.hh\"\n\n#include <vtkSmartPointer.h>\n#include <vtkDoubleArray.h>\n#include <vtkImageData.h>\n#include <vtkPointData.h>\n#include <vtkDataSetTriangleFilter.h>\n#include <vtkUnstructuredGrid.h>\n#include <vtkUnstructuredGridWriter.h>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n\n#include <iostream>\n#include <string>\n#include <memory>\n#include <stdexcept>\n\nusing namespace cpp_utils;\n\nnamespace po = boost::program_options;\n\nusing namespace tl;\n\nusing Mat3dr = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>;\n\nenum class FieldType\n{\n    TEST,\n    TEST2,\n    TESTIMAG,\n    VORTEX_SIMPLE,\n    IDENTITY,\n    CONSTANT,\n    TOPO1\n};\n\n\nstd::unique_ptr<TensorField> makeTensorField(FieldType ftype)\n{\n    switch(ftype)\n    {\n        case FieldType::TEST:\n            return std::unique_ptr<TestField>{new TestField{}};\n        case FieldType::TEST2:\n            return std::unique_ptr<TestField2>{new TestField2{}};\n        case FieldType::TESTIMAG:\n            return std::unique_ptr<TestFieldImag>{new TestFieldImag{}};\n        case FieldType::VORTEX_SIMPLE:\n            return std::unique_ptr<TensorVortexSimple>{new TensorVortexSimple{}};\n        case FieldType::IDENTITY:\n            return std::unique_ptr<Identity>{new Identity{}};\n        case FieldType::CONSTANT:\n            return std::unique_ptr<ConstantNonSymmetric>{\n                    new ConstantNonSymmetric{}};\n        case FieldType::TOPO1:\n            return std::unique_ptr<SingleTopoLine>{\n                    new SingleTopoLine{}};\n        default:\n            return nullptr;\n    }\n}\n\n\nstd::istream& operator>>(std::istream& in, FieldType& ftype)\n{\n    auto token = std::string{};\n    in >> token;\n\n    boost::to_upper(token);\n\n    if(token == \"TEST\")\n    {\n        ftype = FieldType::TEST;\n    }\n    else if(token == \"TEST2\")\n    {\n        ftype = FieldType::TEST2;\n    }\n    else if(token == \"TESTIMAG\")\n    {\n        ftype = FieldType::TESTIMAG;\n    }\n    else if(token == \"VORTEX_SIMPLE\")\n    {\n        ftype = FieldType::VORTEX_SIMPLE;\n    }\n    else if(token == \"IDENTITY\")\n    {\n        ftype = FieldType::IDENTITY;\n    }\n    else if(token == \"CONSTANT\")\n    {\n        ftype = FieldType::CONSTANT;\n    }\n    else if(token == \"TOPO1\")\n    {\n        ftype = FieldType::TOPO1;\n    }\n    else\n    {\n        throw po::validation_error(po::validation_error::invalid_option_value, \"ftype\", token);\n    }\n\n    return in;\n}\n\n\nstd::ostream& operator<<(std::ostream& out, const FieldType& ftype)\n{\n    switch(ftype)\n    {\n        case FieldType::TEST:\n            out << \"test\";\n            break;\n        case FieldType::TEST2:\n            out << \"test2\";\n            break;\n        case FieldType::TESTIMAG:\n            out << \"testimag\";\n            break;\n        case FieldType::VORTEX_SIMPLE:\n            out << \"vortex_simple\";\n            break;\n        case FieldType::IDENTITY:\n            out << \"identity\";\n            break;\n        case FieldType::CONSTANT:\n            out << \"constant\";\n            break;\n        case FieldType::TOPO1:\n            out << \"topo1\";\n            break;\n        default:\n            assert(false);\n    }\n    return out;\n}\n\n\nint main(int argc, char const* argv[])\n{\n    using namespace tl;\n\n    auto ftype = FieldType::TEST;\n    auto minx = 0.;\n    auto maxx = 0.;\n    auto miny = 0.;\n    auto maxy = 0.;\n    auto minz = 0.;\n    auto maxz = 0.;\n    auto np = 0u;\n    auto out_name = std::string{\"Grid.vtk\"};\n\n    try\n    {\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()(\"help,h\", \"produce help message\")\n                (\"num-points,n\",\n                 po::value(&np)->required(),\n                 \"Number of grid points in the largest extent of the box\")\n                (\"min-x\",\n                 po::value(&minx)->required(),\n                 \"Lower bound in x direction\")\n                (\"max-x\",\n                 po::value(&maxx)->required(),\n                 \"Upper bound in x direction\")(\n                \"min-y\",\n                po::value(&miny)->required(),\n                \"Lower bound in y direction\")\n                (\"max-y\",\n                 po::value(&maxy)->required(),\n                 \"Upper bound in y direction\")\n                (\"min-z\",\n                 po::value(&minz)->required(),\n                 \"Lower bound in z direction\")\n                (\"max-z\",\n                 po::value(&maxz)->required(),\n                 \"Upper bound in z direction\")\n                (\"ftype,f\",\n                 po::value(&ftype)->required()->default_value(ftype),\n                 \"Type of tensor field to generate\")\n                (\"output,o\",\n                 po::value<std::string>(&out_name)->required()->default_value(\n                        out_name),\n                 \"Name of the output file\");\n\n        auto vm = po::variables_map{};\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if(vm.empty() || vm.count(\"help\"))\n        {\n            std::cout << \"Generates a VTK file with a tensor field on a regular \"\n                          \"tetrahedralized grid.\\n\\n\";\n            std::cout << desc << \"\\n\";\n            return 0;\n        }\n\n        po::notify(vm);\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << \"error: \" << e.what() << \"\\n\";\n        return 1;\n    }\n    catch(...)\n    {\n        std::cerr << \"Exception of unknown type!\\n\";\n    }\n\n    auto tfield = makeTensorField(ftype);\n\n    auto maxdim = std::max({maxx-minx, maxy-miny, maxz-minz});\n    auto h = maxdim/(np-1);\n\n    auto nx = int(std::ceil((maxx-minx)/h)) + 1;\n    auto ny = int(std::ceil((maxy-miny)/h)) + 1;\n    auto nz = int(std::ceil((maxz-minz)/h)) + 1;\n\n    auto grid = vtkSmartPointer<vtkImageData>::New();\n    grid->SetDimensions(nx, ny, nz);\n    grid->SetOrigin(minx, miny, minz);\n    grid->SetSpacing((maxx - minx) / (nx - 1),\n                     (maxy - miny) / (ny - 1),\n                     (maxz - minz) / (nz - 1));\n\n    auto s_data = vtkSmartPointer<vtkDoubleArray>::New();\n    s_data->SetName(\"S\");\n    s_data->SetNumberOfComponents(9);\n    s_data->SetNumberOfTuples(grid->GetNumberOfPoints());\n    grid->GetPointData()->AddArray(s_data);\n\n    auto sx_data = vtkSmartPointer<vtkDoubleArray>::New();\n    sx_data->SetName(\"Sx\");\n    sx_data->SetNumberOfComponents(9);\n    sx_data->SetNumberOfTuples(grid->GetNumberOfPoints());\n    grid->GetPointData()->AddArray(sx_data);\n\n    auto sy_data = vtkSmartPointer<vtkDoubleArray>::New();\n    sy_data->SetName(\"Sy\");\n    sy_data->SetNumberOfComponents(9);\n    sy_data->SetNumberOfTuples(grid->GetNumberOfPoints());\n    grid->GetPointData()->AddArray(sy_data);\n\n    auto sz_data = vtkSmartPointer<vtkDoubleArray>::New();\n    sz_data->SetName(\"Sz\");\n    sz_data->SetNumberOfComponents(9);\n    sz_data->SetNumberOfTuples(grid->GetNumberOfPoints());\n    grid->GetPointData()->AddArray(sz_data);\n\n    for(auto i: range(grid->GetNumberOfPoints()))\n    {\n        using MapV3d = Eigen::Map<Vec3d>;\n        auto pos = Vec3d{MapV3d{grid->GetPoint(i)}};\n        auto s = Mat3dr{tfield->t(pos)};\n        auto sx = Mat3dr{tfield->tx(pos)};\n        auto sy = Mat3dr{tfield->ty(pos)};\n        auto sz = Mat3dr{tfield->tz(pos)};\n        s_data->SetTuple(i, s.data());\n        sx_data->SetTuple(i, sx.data());\n        sy_data->SetTuple(i, sy.data());\n        sz_data->SetTuple(i, sz.data());\n    }\n\n    auto tri_filt = vtkSmartPointer<vtkDataSetTriangleFilter>::New();\n    tri_filt->SetInputData(grid);\n\n\n    auto writer = vtkSmartPointer<vtkUnstructuredGridWriter>::New();\n    writer->SetInputConnection(0, tri_filt->GetOutputPort());\n    writer->SetFileName(out_name.c_str());\n    writer->SetFileTypeToBinary();\n    writer->Update();\n    writer->Write();\n}\n", "meta": {"hexsha": "af3e8f3d7b12f903ee4d95fab3965b661e421eff", "size": 7737, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/generate_grid_dataset.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/generate_grid_dataset.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/generate_grid_dataset.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": 27.8309352518, "max_line_length": 95, "alphanum_fraction": 0.556417216, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.03461884132918788, "lm_q1q2_score": 0.010755879996288636}}
{"text": "/*ckwg +29\n * Copyright 2014-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 Implementation of kwiver::arrows::core::transform functions to apply\n * similarity transformations\n */\n\n#include \"transform.h\"\n#include <Eigen/Geometry>\n\n\nnamespace kwiver {\nnamespace arrows {\nnamespace core {\n\n\n/// Transform the camera by applying a similarity transformation in place\nvoid\ntransform_inplace(vital::simple_camera_perspective& cam,\n                  const vital::similarity_d& xform)\n{\n  cam.set_center( xform * cam.get_center() );\n  cam.set_rotation( cam.get_rotation() * xform.rotation().inverse() );\n  cam.set_center_covar( transform(cam.get_center_covar(), xform) );\n}\n\n\n/// Transform the camera map by applying a similarity transformation in place\nvoid transform_inplace(vital::simple_camera_perspective_map& cameras,\n                       const vital::similarity_d& xform)\n{\n  auto cam_map = cameras.T_cameras();\n  for (auto& p : cam_map)\n  {\n    transform_inplace(*p.second, xform);\n  }\n}\n\n\n/// Transform the landmark by applying a similarity transformation in place\ntemplate <typename T>\nvoid\ntransform_inplace(vital::landmark_<T>& lm,\n                  const vital::similarity_<T>& xform)\n{\n  lm.set_loc( xform * lm.get_loc() );\n  lm.set_scale( lm.get_scale() * xform.scale() );\n  lm.set_covar( transform(lm.get_covar(), xform) );\n}\n\n\n/// Transform the landmark map by applying a similarity transformation in place\nvoid transform_inplace(vital::landmark_map& landmarks,\n                       const vital::similarity_d& xform)\n{\n  vital::landmark_map::map_landmark_t lm_map = landmarks.landmarks();\n  transform_inplace(lm_map, xform);\n}\n\n\n/// Transform the landmark map by applying a similarity transformation in place\nvoid transform_inplace(vital::landmark_map::map_landmark_t& landmarks,\n                       const vital::similarity_d& xform)\n{\n  for (vital::landmark_map::map_landmark_t::value_type& p : landmarks)\n  {\n    if (vital::landmark_d* vlm = dynamic_cast<vital::landmark_d*>(p.second.get()))\n    {\n      transform_inplace(*vlm, xform);\n    }\n    else if (vital::landmark_f* vlm = dynamic_cast<vital::landmark_f*>(p.second.get()))\n    {\n      transform_inplace(*vlm, vital::similarity_f(xform));\n    }\n  }\n}\n\n\n/// Transform a 3D covariance matrix with a similarity transformation\ntemplate <typename T>\nvital::covariance_<3,T> transform(const vital::covariance_<3,T>& covar,\n                                  const vital::similarity_<T>& xform)\n{\n  // TODO trasform covariance parameters directly\n  // instead of converting to matrix form and back\n  Eigen::Matrix<T,3,3> C(covar.matrix());\n  Eigen::Matrix<T,3,3> sR(xform.rotation().matrix());\n  sR /= xform.scale();\n  C = sR * C * sR.transpose();\n  return vital::covariance_<3,T>(C);\n}\n\n\n/// construct a transformed camera by applying a similarity transformation\nvital::camera_perspective_sptr transform(vital::camera_perspective_sptr cam,\n                                         const vital::similarity_d& xform)\n{\n  cam = std::dynamic_pointer_cast<vital::camera_perspective>(cam->clone());\n  if( vital::simple_camera_perspective* vcam =\n      dynamic_cast<vital::simple_camera_perspective*>(cam.get()) )\n  {\n    transform_inplace(*vcam, xform);\n  }\n  else\n  {\n    vital::simple_camera_perspective* new_cam =\n        new vital::simple_camera_perspective( xform * cam->center(),\n                                  cam->rotation() * xform.rotation().inverse(),\n                                  cam->intrinsics() );\n    new_cam->set_center_covar( transform(cam->center_covar(), xform) );\n    cam = vital::camera_perspective_sptr( new_cam );\n  }\n  return cam;\n}\n\n\n/// construct a transformed map of cameras by applying a similarity transformation\nvital::camera_map_sptr transform(vital::camera_map_sptr cameras,\n                                 const vital::similarity_d& xform)\n{\n  vital::camera_map::map_camera_t cam_map = cameras->cameras();\n  for(vital::camera_map::map_camera_t::value_type& p : cam_map)\n  {\n    auto cam_ptr = std::dynamic_pointer_cast<vital::camera_perspective>(p.second);\n    if (!cam_ptr)\n    {\n      p.second = nullptr;\n      continue;\n    }\n    p.second = transform(cam_ptr, xform);\n  }\n  return vital::camera_map_sptr(new vital::simple_camera_map(cam_map));\n}\n\n\n/// construct a transformed map of cameras by applying a similarity transformation\nvital::camera_perspective_map_sptr\ntransform(vital::camera_perspective_map_sptr cameras,\n          const vital::similarity_d& xform)\n{\n  auto cam_map = cameras->T_cameras();\n  for (auto& p : cam_map)\n  {\n    p.second = transform(p.second, xform);\n  }\n  return std::make_shared<vital::camera_perspective_map>(cam_map);\n}\n\n\n/// construct a transformed landmark by applying a similarity transformation\nvital::landmark_sptr transform(vital::landmark_sptr lm,\n                               const vital::similarity_d& xform)\n{\n  if (!lm)\n  {\n    return vital::landmark_sptr();\n  }\n  lm = lm->clone();\n  if( vital::landmark_d* vlm = dynamic_cast<vital::landmark_d*>(lm.get()) )\n  {\n    transform_inplace(*vlm, xform);\n  }\n  else if( vital::landmark_f* vlm = dynamic_cast<vital::landmark_f*>(lm.get()) )\n  {\n    transform_inplace(*vlm, vital::similarity_f(xform));\n  }\n  else\n  {\n    auto new_lm = std::make_shared<vital::landmark_d>( *lm );\n    new_lm->set_loc( xform * lm->loc() );\n    new_lm->set_scale( lm->scale() * xform.scale() );\n    new_lm->set_covar( transform(lm->covar(), xform) );\n    lm = new_lm;\n  }\n  return lm;\n}\n\n\n/// construct a transformed map of landmarks by applying a similarity transformation\nvital::landmark_map_sptr transform(vital::landmark_map_sptr landmarks,\n                                   const vital::similarity_d& xform)\n{\n  vital::landmark_map::map_landmark_t lm_map = landmarks->landmarks();\n  for(vital::landmark_map::map_landmark_t::value_type& p : lm_map)\n  {\n    p.second = transform(p.second, xform);\n  }\n  return vital::landmark_map_sptr(new vital::simple_landmark_map(lm_map));\n}\n\n\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_TRANSFORM(T) \\\ntemplate KWIVER_ALGO_CORE_EXPORT vital::covariance_<3,T> \\\ntransform(const vital::covariance_<3,T>& covar, \\\n          const vital::similarity_<T>& xform); \\\ntemplate KWIVER_ALGO_CORE_EXPORT void \\\ntransform_inplace(vital::landmark_<T>& cam, \\\n                  const vital::similarity_<T>& xform);\n\nINSTANTIATE_TRANSFORM(double);\nINSTANTIATE_TRANSFORM(float);\n\n#undef INSTANTIATE_TRANSFORM\n/// \\endcond\n\n\n} // end namespace core\n} // end namespace arrows\n} // end namespace kwiver\n", "meta": {"hexsha": "3ae240369f4e2b292ff93c05fea7e4377d6a8cca", "size": 8023, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "arrows/core/transform.cxx", "max_stars_repo_name": "massir-rpi/kwiver", "max_stars_repo_head_hexsha": "51547e12d61bce6b5c72302e56215a3fca0e2712", "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": "arrows/core/transform.cxx", "max_issues_repo_name": "massir-rpi/kwiver", "max_issues_repo_head_hexsha": "51547e12d61bce6b5c72302e56215a3fca0e2712", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/core/transform.cxx", "max_forks_repo_name": "massir-rpi/kwiver", "max_forks_repo_head_hexsha": "51547e12d61bce6b5c72302e56215a3fca0e2712", "max_forks_repo_licenses": ["BSD-3-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.4291666667, "max_line_length": 87, "alphanum_fraction": 0.6976193444, "num_tokens": 1934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943704494217, "lm_q2_score": 0.03461884095568606, "lm_q1q2_score": 0.010755878996415539}}
{"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/utilities/parsers.cpp\n    \\brief\n    \\ingroup utilities\n*/\n\n#include <boost/algorithm/string.hpp>\n#include <map>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ql/currencies/all.hpp>\n#include <ql/errors.hpp>\n#include <ql/indexes/all.hpp>\n#include <ql/time/calendars/all.hpp>\n#include <ql/time/daycounters/all.hpp>\n#include <ql/utilities/dataparsers.hpp>\n#include <ql/version.hpp>\n#include <qle/calendars/chile.hpp>\n#include <qle/calendars/colombia.hpp>\n#include <qle/calendars/france.hpp>\n#include <qle/calendars/malaysia.hpp>\n#include <qle/calendars/netherlands.hpp>\n#include <qle/calendars/peru.hpp>\n#include <qle/calendars/philippines.hpp>\n#include <qle/calendars/thailand.hpp>\n#include <qle/currencies/africa.hpp>\n#include <qle/currencies/america.hpp>\n#include <qle/currencies/asia.hpp>\n#include <qle/currencies/metals.hpp>\n#include <qle/time/yearcounter.hpp>\n\n#include <boost/lexical_cast.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace std;\n\nnamespace ore {\nnamespace data {\n\nDate parseDate(const string& s) {\n    // TODO: review\n\n    if (s == \"\")\n        return Date();\n\n    // guess formats from token number and sizes\n    // check permissible lengths\n    QL_REQUIRE((s.size() >= 3 && s.size() <= 6) || s.size() == 8 || s.size() == 10,\n               \"invalid date format of \" << s << \", date string length 8 or 10 or between 3 and 6 required\");\n\n    vector<string> tokens;\n    boost::split(tokens, s, boost::is_any_of(\"-/.:\"));\n\n    if (tokens.size() == 1) {\n        if (s.size() == 8) {\n            // yyyymmdd\n            int y = parseInteger(s.substr(0, 4));\n            int m = parseInteger(s.substr(4, 2));\n            int d = parseInteger(s.substr(6, 2));\n            return Date(d, Month(m), y);\n        } else if (s.size() >= 3 && s.size() <= 6) {\n            // Excel format\n            // Boundaries will be checked by Date constructor\n            // Boundaries are minDate = 367 i.e. Jan 1st, 1901\n            // and maxDate = 109574 i.e. Dec 31st, 2199\n            BigInteger serial = parseInteger(s);\n            return Date(serial);\n        }\n    } else if (tokens.size() == 3) {\n        if (tokens[0].size() == 4) {\n            // yyyy-mm-dd\n            // yyyy/mm/dd\n            // yyyy.mm.dd\n            int y = parseInteger(tokens[0]);\n            int m = parseInteger(tokens[1]);\n            int d = parseInteger(tokens[2]);\n            return Date(d, Month(m), y);\n        } else if (tokens[0].size() == 2) {\n            // dd-mm-yy\n            // dd/mm/yy\n            // dd.mm.yy\n            // dd-mm-yyyy\n            // dd/mm/yyyy\n            // dd.mm.yyyy\n            int d = parseInteger(tokens[0]);\n            int m = parseInteger(tokens[1]);\n            int y = parseInteger(tokens[2]);\n            if (y < 100) {\n                if (y > 80)\n                    y += 1900;\n                else\n                    y += 2000;\n            }\n            return Date(d, Month(m), y);\n        }\n    }\n\n    QL_FAIL(\"Cannot convert \\\"\" << s << \"\\\" to Date.\");\n}\n\nReal parseReal(const string& s) {\n    try {\n        return std::stod(s);\n    } catch (const std::exception& ex) {\n        QL_FAIL(\"Failed to parseReal(\\\"\" << s << \"\\\") \" << ex.what());\n    }\n}\n\nbool tryParseReal(const string& s, QuantLib::Real& result) {\n    try {\n        result = std::stod(s);\n    } catch (...) {\n        result = Null<Real>();\n        return false;\n    }\n    return true;\n}\n\nInteger parseInteger(const string& s) {\n    try {\n        return boost::lexical_cast<Integer>(s.c_str());\n    } catch (std::exception& ex) {\n        QL_FAIL(\"Failed to parseInteger(\\\"\" << s << \"\\\") \" << ex.what());\n    }\n}\n\nbool parseBool(const string& s) {\n    static map<string, bool> b = {{\"Y\", true},  {\"YES\", true}, {\"TRUE\", true},   {\"true\", true},   {\"1\", true},\n                                  {\"N\", false}, {\"NO\", false}, {\"FALSE\", false}, {\"false\", false}, {\"0\", false}};\n\n    auto it = b.find(s);\n    if (it != b.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Cannot convert \" << s << \" to bool\");\n    }\n}\n\nCalendar parseCalendar(const string& s) {\n    static map<string, Calendar> m = {{\"TGT\", TARGET()},\n                                      {\"TARGET\", TARGET()},\n                                      {\"EUR\", TARGET()},\n                                      {\"FR\", France()},\n                                      {\"FRF\", France()},\n                                      {\"IT\", Italy()},\n                                      {\"ITL\", Italy()},\n                                      {\"NL\", Netherlands()},\n                                      {\"NGL\", Netherlands()},\n                                      {\"ZUB\", Switzerland()},\n                                      {\"CHF\", Switzerland()},\n                                      {\"CHZU\", Switzerland()},\n                                      {\"Switzerland\", Switzerland()},\n                                      {\"US\", UnitedStates()},\n                                      {\"USNY\", UnitedStates()},\n                                      {\"USD\", UnitedStates()},\n                                      {\"NYB\", UnitedStates()},\n                                      {\"US-SET\", UnitedStates(UnitedStates::Settlement)},\n                                      {\"US settlement\", UnitedStates(UnitedStates::Settlement)},\n                                      {\"US-GOV\", UnitedStates(UnitedStates::GovernmentBond)},\n                                      {\"US-FED\", UnitedStates(UnitedStates::FederalReserve)},\n                                      {\"US-NYSE\", UnitedStates(UnitedStates::NYSE)},\n                                      {\"New York stock exchange\", UnitedStates(UnitedStates::NYSE)},\n                                      {\"US with Libor impact\", UnitedStates(UnitedStates::LiborImpact)},\n                                      {\"US-NERC\", UnitedStates(UnitedStates::NERC)},\n                                      {\"GB\", UnitedKingdom()},\n                                      {\"GBP\", UnitedKingdom()},\n                                      {\"UK\", UnitedKingdom()},\n                                      {\"UK settlement\", UnitedKingdom()},\n                                      {\"London stock exchange\", UnitedKingdom(UnitedKingdom::Exchange)},\n                                      {\"LNB\", UnitedKingdom()},\n                                      {\"CA\", Canada()},\n                                      {\"TRB\", Canada()},\n                                      {\"CAD\", Canada()},\n                                      {\"CATO\", Canada()},\n                                      {\"Canada\", Canada()},\n                                      {\"SYB\", Australia()},\n                                      {\"AU\", Australia()},\n                                      {\"AUD\", Australia()},\n                                      {\"Australia\", Australia()},\n                                      {\"TKB\", Japan()},\n                                      {\"JP\", Japan()},\n                                      {\"JPTO\", Japan()},\n                                      {\"JPY\", Japan()},\n                                      {\"Japan\", Japan()},\n                                      {\"ZAR\", SouthAfrica()},\n                                      {\"SA\", SouthAfrica()},\n                                      {\"SS\", Sweden()},\n                                      {\"SEK\", Sweden()},\n                                      {\"SEST\", Sweden()},\n                                      {\"Sweden\", Sweden()},\n                                      {\"ARS\", Argentina()},\n                                      {\"BRL\", Brazil()},\n                                      {\"BWP\", Botswana()},\n                                      {\"CNH\", China()},\n                                      {\"CNY\", China()},\n                                      {\"CZK\", CzechRepublic()},\n                                      {\"DKK\", Denmark()},\n                                      {\"DEN\", Denmark()},\n                                      {\"Denmark\", Denmark()},\n                                      {\"FIN\", Finland()},\n                                      {\"HKD\", HongKong()},\n                                      {\"ISK\", Iceland()},\n                                      {\"ILS\", Israel()},\n                                      {\"INR\", India()},\n                                      {\"IDR\", Indonesia()},\n                                      {\"MXN\", Mexico()},\n                                      {\"NZD\", NewZealand()},\n                                      {\"NOK\", Norway()},\n                                      {\"Norway\", Norway()},\n                                      {\"PLN\", Poland()},\n                                      {\"RON\", Romania()},\n                                      {\"RUB\", Russia()},\n                                      {\"SAR\", SaudiArabia()},\n                                      {\"SGD\", Singapore()},\n                                      {\"KRW\", SouthKorea()},\n                                      {\"TWD\", Taiwan()},\n                                      {\"TRY\", Turkey()},\n                                      {\"TRIS\", Turkey()},\n                                      {\"UAH\", Ukraine()},\n                                      {\"HUF\", Hungary()},\n                                      {\"GBLO\", UnitedKingdom()},\n                                      {\"CLP\", Chile()},\n                                      {\"THB\", QuantExt::Thailand()},\n                                      {\"COP\", Colombia()},\n                                      {\"PEN\", Peru()},\n                                      {\"MYR\", Malaysia()},\n                                      {\"PHP\", Philippines()},\n                                      // city specific calendars\n                                      {\"FRA\", Germany(Germany::Settlement)},\n                                      // fallback to TARGET for these emerging ccys\n                                      {\"KWD\", TARGET()},\n                                      {\"TND\", TARGET()},\n                                      {\"KZT\", TARGET()},\n                                      {\"QAR\", TARGET()},\n                                      {\"MXV\", TARGET()},\n                                      {\"CLF\", TARGET()},\n                                      {\"EGP\", TARGET()},\n                                      {\"BHD\", TARGET()},\n                                      {\"OMR\", TARGET()},\n                                      {\"VND\", TARGET()},\n                                      {\"AED\", TARGET()},\n                                      {\"NGN\", TARGET()},\n                                      {\"MAD\", TARGET()},\n                                      {\"PKR\", TARGET()},\n                                      // ISDA http://www.fpml.org/coding-scheme/business-center-7-15.xml\n                                      {\"EUTA\", TARGET()},\n                                      {\"BEBR\", TARGET()}, // Belgium, Brussels not in QL\n                                      {\"WeekendsOnly\", WeekendsOnly()},\n                                      {\"UNMAPPED\", WeekendsOnly()},\n                                      {\"NullCalendar\", NullCalendar()},\n                                      {\"\", NullCalendar()}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        // Try to split them up\n        vector<string> calendarNames;\n        split(calendarNames, s, boost::is_any_of(\",()\")); // , is delimiter, the brackets may arise if joint calendar\n        // now remove any leading strings indicating a joint calendar\n        calendarNames.erase(std::remove(calendarNames.begin(), calendarNames.end(), \"JoinHolidays\"),\n                            calendarNames.end());\n        calendarNames.erase(std::remove(calendarNames.begin(), calendarNames.end(), \"JoinBusinessDays\"),\n                            calendarNames.end());\n        calendarNames.erase(std::remove(calendarNames.begin(), calendarNames.end(), \"\"), calendarNames.end());\n        QL_REQUIRE(calendarNames.size() > 1 && calendarNames.size() <= 4, \"Cannot convert \" << s << \" to Calendar\");\n        // Populate a vector of calendars.\n        vector<Calendar> calendars;\n        for (Size i = 0; i < calendarNames.size(); i++) {\n            boost::trim(calendarNames[i]);\n            try {\n                calendars.push_back(parseCalendar(calendarNames[i]));\n            } catch (std::exception& e) {\n                QL_FAIL(\"Cannot convert \" << s << \" to Calendar [exception:\" << e.what() << \"]\");\n            } catch (...) {\n                QL_FAIL(\"Cannot convert \" << s << \" to Calendar [unhandled exception]\");\n            }\n        }\n\n        switch (calendarNames.size()) {\n        case 2:\n            return JointCalendar(calendars[0], calendars[1]);\n        case 3:\n            return JointCalendar(calendars[0], calendars[1], calendars[2]);\n        case 4:\n            return JointCalendar(calendars[0], calendars[1], calendars[2], calendars[3]);\n        default:\n            QL_FAIL(\"Cannot convert \" << s << \" to Calendar\");\n        }\n    }\n}\n\nPeriod parsePeriod(const string& s) { return PeriodParser::parse(s); }\n\nBusinessDayConvention parseBusinessDayConvention(const string& s) {\n    static map<string, BusinessDayConvention> m = {{\"F\", Following},\n                                                   {\"Following\", Following},\n                                                   {\"FOLLOWING\", Following},\n                                                   {\"MF\", ModifiedFollowing},\n                                                   {\"ModifiedFollowing\", ModifiedFollowing},\n                                                   {\"Modified Following\", ModifiedFollowing},\n                                                   {\"MODIFIEDF\", ModifiedFollowing},\n                                                   {\"MODFOLLOWING\", ModifiedFollowing},\n                                                   {\"P\", Preceding},\n                                                   {\"Preceding\", Preceding},\n                                                   {\"PRECEDING\", Preceding},\n                                                   {\"MP\", ModifiedPreceding},\n                                                   {\"ModifiedPreceding\", ModifiedPreceding},\n                                                   {\"Modified Preceding\", ModifiedPreceding},\n                                                   {\"MODIFIEDP\", ModifiedPreceding},\n                                                   {\"U\", Unadjusted},\n                                                   {\"Unadjusted\", Unadjusted},\n                                                   {\"INDIFF\", Unadjusted},\n                                                   {\"NEAREST\", Nearest},\n                                                   {\"NONE\", Unadjusted},\n                                                   {\"NotApplicable\", Unadjusted}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Cannot convert \" << s << \" to BusinessDayConvention\");\n    }\n}\n\nDayCounter parseDayCounter(const string& s) {\n    static map<string, DayCounter> m = {{\"A360\", Actual360()},\n                                        {\"Actual/360\", Actual360()},\n                                        {\"ACT/360\", Actual360()},\n                                        {\"A365\", Actual365Fixed()},\n                                        {\"A365F\", Actual365Fixed()},\n                                        {\"Actual/365 (Fixed)\", Actual365Fixed()},\n                                        {\"Actual/365 (fixed)\", Actual365Fixed()},\n                                        {\"ACT/365.FIXED\", Actual365Fixed()},\n                                        {\"ACT/365\", Actual365Fixed()},\n                                        {\"ACT/365L\", Actual365Fixed()},\n                                        {\"T360\", Thirty360(Thirty360::USA)},\n                                        {\"30/360\", Thirty360(Thirty360::USA)},\n                                        {\"30/360 (Bond Basis)\", Thirty360(Thirty360::USA)},\n                                        {\"ACT/nACT\", Thirty360(Thirty360::USA)},\n                                        {\"30E/360 (Eurobond Basis)\", Thirty360(Thirty360::European)},\n                                        {\"30E/360\", Thirty360(Thirty360::European)},\n                                        {\"30E/360.ISDA\", Thirty360(Thirty360::European)},\n                                        {\"30/360 (Italian)\", Thirty360(Thirty360::Italian)},\n                                        {\"ActActISDA\", ActualActual(ActualActual::ISDA)},\n                                        {\"ACT/ACT.ISDA\", ActualActual(ActualActual::ISDA)},\n                                        {\"Actual/Actual (ISDA)\", ActualActual(ActualActual::ISDA)},\n                                        {\"ActualActual (ISDA)\", ActualActual(ActualActual::ISDA)},\n                                        {\"ACT/ACT\", ActualActual(ActualActual::ISDA)},\n                                        {\"ACT29\", ActualActual(ActualActual::AFB)},\n                                        {\"ACT\", ActualActual(ActualActual::ISDA)},\n                                        {\"ActActISMA\", ActualActual(ActualActual::ISMA)},\n                                        {\"Actual/Actual (ISMA)\", ActualActual(ActualActual::ISMA)},\n                                        {\"ActualActual (ISMA)\", ActualActual(ActualActual::ISMA)},\n                                        {\"ActActAFB\", ActualActual(ActualActual::AFB)},\n                                        {\"ACT/ACT.AFB\", ActualActual(ActualActual::AFB)},\n                                        {\"ACT/ACT.ISMA\", ActualActual(ActualActual::ISMA)},\n                                        {\"Actual/Actual (AFB)\", ActualActual(ActualActual::AFB)},\n                                        {\"1/1\", OneDayCounter()},\n                                        {\"BUS/252\", Business252()},\n                                        {\"Business/252\", Business252()},\n                                        {\"Actual/365 (No Leap)\", Actual365Fixed(Actual365Fixed::NoLeap)},\n                                        {\"Act/365 (NL)\", Actual365Fixed(Actual365Fixed::NoLeap)},\n                                        {\"NL/365\", Actual365Fixed(Actual365Fixed::NoLeap)},\n                                        {\"Actual/365 (JGB)\", Actual365Fixed(Actual365Fixed::NoLeap)},\n                                        {\"Simple\", SimpleDayCounter()},\n                                        {\"Year\", YearCounter()}\n    };\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"DayCounter \" << s << \" not recognized\");\n    }\n}\n\nCurrency parseCurrency(const string& s) {\n    static map<string, Currency> m = {\n        {\"ATS\", ATSCurrency()}, {\"AUD\", AUDCurrency()}, {\"BEF\", BEFCurrency()}, {\"BRL\", BRLCurrency()},\n        {\"CAD\", CADCurrency()}, {\"CHF\", CHFCurrency()}, {\"CNH\", CNHCurrency()}, {\"CNY\", CNYCurrency()},\n        {\"CZK\", CZKCurrency()}, {\"DEM\", DEMCurrency()}, {\"DKK\", DKKCurrency()}, {\"EUR\", EURCurrency()},\n        {\"ESP\", ESPCurrency()}, {\"FIM\", FIMCurrency()}, {\"FRF\", FRFCurrency()}, {\"GBP\", GBPCurrency()},\n        {\"GRD\", GRDCurrency()}, {\"HKD\", HKDCurrency()}, {\"HUF\", HUFCurrency()}, {\"IEP\", IEPCurrency()},\n        {\"ITL\", ITLCurrency()}, {\"INR\", INRCurrency()}, {\"ISK\", ISKCurrency()}, {\"JPY\", JPYCurrency()},\n        {\"KRW\", KRWCurrency()}, {\"LUF\", LUFCurrency()}, {\"NLG\", NLGCurrency()}, {\"NOK\", NOKCurrency()},\n        {\"NZD\", NZDCurrency()}, {\"PLN\", PLNCurrency()}, {\"PTE\", PTECurrency()}, {\"RON\", RONCurrency()},\n        {\"SEK\", SEKCurrency()}, {\"SGD\", SGDCurrency()}, {\"THB\", THBCurrency()}, {\"TRY\", TRYCurrency()},\n        {\"TWD\", TWDCurrency()}, {\"USD\", USDCurrency()}, {\"ZAR\", ZARCurrency()}, {\"ARS\", ARSCurrency()},\n        {\"CLP\", CLPCurrency()}, {\"COP\", COPCurrency()}, {\"IDR\", IDRCurrency()}, {\"ILS\", ILSCurrency()},\n        {\"KWD\", KWDCurrency()}, {\"PEN\", PENCurrency()}, {\"PKR\", PKRCurrency()}, {\"MXN\", MXNCurrency()},\n        {\"SAR\", SARCurrency()}, {\"RUB\", RUBCurrency()}, {\"TND\", TNDCurrency()}, {\"MYR\", MYRCurrency()},\n        {\"UAH\", UAHCurrency()}, {\"KZT\", KZTCurrency()}, {\"QAR\", QARCurrency()}, {\"MXV\", MXVCurrency()},\n        {\"CLF\", CLFCurrency()}, {\"EGP\", EGPCurrency()}, {\"BHD\", BHDCurrency()}, {\"OMR\", OMRCurrency()},\n        {\"VND\", VNDCurrency()}, {\"AED\", AEDCurrency()}, {\"PHP\", PHPCurrency()}, {\"NGN\", NGNCurrency()},\n        {\"MAD\", MADCurrency()}, {\"XAU\", XAUCurrency()}, {\"XAG\", XAGCurrency()}, {\"XPD\", XPDCurrency()},\n        {\"XPT\", XPTCurrency()}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Currency \" << s << \" not recognized\");\n    }\n}\n\nDateGeneration::Rule parseDateGenerationRule(const string& s) {\n    static map<string, DateGeneration::Rule> m = {{\"Backward\", DateGeneration::Backward},\n                                                  {\"Forward\", DateGeneration::Forward},\n                                                  {\"Zero\", DateGeneration::Zero},\n                                                  {\"ThirdWednesday\", DateGeneration::ThirdWednesday},\n                                                  {\"Twentieth\", DateGeneration::Twentieth},\n                                                  {\"TwentiethIMM\", DateGeneration::TwentiethIMM},\n                                                  {\"OldCDS\", DateGeneration::OldCDS},\n                                                  {\"CDS2015\", DateGeneration::CDS2015},\n                                                  {\"CDS\", DateGeneration::CDS}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        // fall back for CDS2015\n        if (s == \"CDS2015\") {\n            ALOG(\"Date Generation Rule CDS2015 replaced with CDS because QuantLib Version is < 1.10\");\n            return DateGeneration::CDS;\n        }\n        QL_FAIL(\"Date Generation Rule \" << s << \" not recognized\");\n    }\n}\n\nFrequency parseFrequency(const string& s) {\n    static map<string, Frequency> m = {{\"Z\", Once},\n                                       {\"Once\", Once},\n                                       {\"A\", Annual},\n                                       {\"Annual\", Annual},\n                                       {\"S\", Semiannual},\n                                       {\"Semiannual\", Semiannual},\n                                       {\"Q\", Quarterly},\n                                       {\"Quarterly\", Quarterly},\n                                       {\"B\", Bimonthly},\n                                       {\"Bimonthly\", Bimonthly},\n                                       {\"M\", Monthly},\n                                       {\"Monthly\", Monthly},\n                                       {\"L\", EveryFourthWeek},\n                                       {\"Lunarmonth\", EveryFourthWeek},\n                                       {\"W\", Weekly},\n                                       {\"Weekly\", Weekly},\n                                       {\"D\", Daily},\n                                       {\"Daily\", Daily}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Frequency \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nCompounding parseCompounding(const string& s) {\n    static map<string, Compounding> m = {\n        {\"Simple\", Simple},\n        {\"Compounded\", Compounded},\n        {\"Continuous\", Continuous},\n        {\"SimpleThenCompounded\", SimpleThenCompounded},\n    };\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Compounding \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nPosition::Type parsePositionType(const std::string& s) {\n    static map<string, Position::Type> m = {\n        {\"Long\", Position::Long}, {\"Short\", Position::Short}, {\"L\", Position::Long}, {\"S\", Position::Short},\n    };\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Position type \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nSettlement::Type parseSettlementType(const std::string& s) {\n    static map<string, Settlement::Type> m = {\n        {\"Cash\", Settlement::Cash},\n        {\"Physical\", Settlement::Physical},\n        {\"C\", Settlement::Cash},\n        {\"P\", Settlement::Physical},\n    };\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Settlement type \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nSettlement::Method parseSettlementMethod(const std::string& s) {\n    static map<string, Settlement::Method> m = {\n        {\"PhysicalOTC\", Settlement::PhysicalOTC},\n        {\"PhysicalCleared\", Settlement::PhysicalCleared},\n        {\"CollateralizedCashPrice\", Settlement::CollateralizedCashPrice},\n        {\"ParYieldCurve\", Settlement::ParYieldCurve},\n    };\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Settlement method \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nExercise::Type parseExerciseType(const std::string& s) {\n    static map<string, Exercise::Type> m = {\n        {\"European\", Exercise::European}, {\"Bermudan\", Exercise::Bermudan}, {\"American\", Exercise::American},\n    };\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Exercise type \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nOption::Type parseOptionType(const std::string& s) {\n    static map<string, Option::Type> m = {{\"Put\", Option::Put}, {\"Call\", Option::Call}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Option type \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nvoid parseDateOrPeriod(const string& s, Date& d, Period& p, bool& isDate) {\n    QL_REQUIRE(!s.empty(), \"Cannot parse empty string as date or period\");\n    string c(1, s.back());\n    bool isPeriod = c.find_first_of(\"DdWwMmYy\") != string::npos;\n    if (isPeriod) {\n        p = ore::data::parsePeriod(s);\n        isDate = false;\n    } else {\n        d = ore::data::parseDate(s);\n        QL_REQUIRE(d != Date(), \"Cannot parse \\\"\" << s << \"\\\" as date\");\n        isDate = true;\n    }\n}\n\nQuantLib::LsmBasisSystem::PolynomType parsePolynomType(const std::string& s) {\n    static map<string, LsmBasisSystem::PolynomType> poly = {\n        {\"Monomial\", LsmBasisSystem::PolynomType::Monomial},\n        {\"Laguerre\", LsmBasisSystem::PolynomType::Laguerre},\n        {\"Hermite\", LsmBasisSystem::PolynomType::Hermite},\n        {\"Hyperbolic\", LsmBasisSystem::PolynomType::Hyperbolic},\n        {\"Legendre\", LsmBasisSystem::PolynomType::Legendre},\n        {\"Chebyshev\", LsmBasisSystem::PolynomType::Chebyshev},\n        {\"Chebyshev2nd\", LsmBasisSystem::PolynomType::Chebyshev2nd},\n    };\n\n    auto it = poly.find(s);\n    if (it != poly.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Polynom type \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nSobolBrownianGenerator::Ordering parseSobolBrownianGeneratorOrdering(const std::string& s) {\n    static map<string, SobolBrownianGenerator::Ordering> m = {{\"Factors\", SobolBrownianGenerator::Ordering::Factors},\n                                                              {\"Steps\", SobolBrownianGenerator::Ordering::Steps},\n                                                              {\"Diagonal\", SobolBrownianGenerator::Ordering::Diagonal}};\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"SobolBrownianGenerator ordering \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nSobolRsg::DirectionIntegers parseSobolRsgDirectionIntegers(const std::string& s) {\n    static map<string, SobolRsg::DirectionIntegers> m = {\n        {\"Unit\", SobolRsg::DirectionIntegers::Unit},\n        {\"Jaeckel\", SobolRsg::DirectionIntegers::Jaeckel},\n        {\"SobolLevitan\", SobolRsg::DirectionIntegers::SobolLevitan},\n        {\"SobolLevitanLemieux\", SobolRsg::DirectionIntegers::SobolLevitanLemieux},\n        {\"JoeKuoD5\", SobolRsg::DirectionIntegers::JoeKuoD5},\n        {\"JoeKuoD6\", SobolRsg::DirectionIntegers::JoeKuoD6},\n        {\"JoeKuoD7\", SobolRsg::DirectionIntegers::JoeKuoD7},\n        {\"Kuo\", SobolRsg::DirectionIntegers::Kuo},\n        {\"Kuo2\", SobolRsg::DirectionIntegers::Kuo2},\n        {\"Kuo3\", SobolRsg::DirectionIntegers::Kuo3}};\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"SobolRsg direction integers \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nstd::vector<string> parseListOfValues(string s) {\n    boost::trim(s);\n    std::vector<string> vec;\n    boost::char_separator<char> sep(\",\");\n    boost::tokenizer<boost::char_separator<char>> tokens(s, sep);\n    for (auto r : tokens) {\n        boost::trim(r);\n        vec.push_back(r);\n    }\n    return vec;\n}\n\nAmortizationType parseAmortizationType(const std::string& s) {\n    static map<string, AmortizationType> type = {\n        {\"None\", AmortizationType::None},\n        {\"FixedAmount\", AmortizationType::FixedAmount},\n        {\"RelativeToInitialNotional\", AmortizationType::RelativeToInitialNotional},\n        {\"RelativeToPreviousNotional\", AmortizationType::RelativeToPreviousNotional},\n        {\"Annuity\", AmortizationType::Annuity}};\n\n    auto it = type.find(s);\n    if (it != type.end()) {\n        return it->second;\n    } else {\n        QL_FAIL(\"Amortitazion type \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nSequenceType parseSequenceType(const std::string& s) {\n    static map<string, SequenceType> seq = {{\"MersenneTwister\", SequenceType::MersenneTwister},\n                                            {\"MersenneTwisterAntithetic\", SequenceType::MersenneTwisterAntithetic},\n                                            {\"Sobol\", SequenceType::Sobol},\n                                            {\"SobolBrownianBridge\", SequenceType::SobolBrownianBridge}};\n    auto it = seq.find(s);\n    if (it != seq.end())\n        return it->second;\n    else\n        QL_FAIL(\"sequence type \\\"\" << s << \"\\\" not recognised\");\n}\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "b10ac03a86986a111c0a9aa406fb846760609313", "size": 30871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/utilities/parsers.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": "OREData/ored/utilities/parsers.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": "OREData/ored/utilities/parsers.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": 46.1449925262, "max_line_length": 120, "alphanum_fraction": 0.4413851187, "num_tokens": 6360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020279, "lm_q2_score": 0.04336579891845121, "lm_q1q2_score": 0.010754172860636884}}
{"text": "//   GAMBIT: Global and Modular BSM Inference Tool\n//   *********************************************\n///  \\file\n///\n///  Example of GAMBIT DarkBit standalone\n///  main program.\n///\n///  *********************************************\n///\n///  Authors (add name and date if you modify):\n///\n///  \\author Christoph Weniger\n///  \\date 2016 Feb\n///  \\author Jonathan Cornell\n///  \\date 2016 July\n///  \\author Sebastian Wild\n///  \\date 2016 Aug\n///\n///  *********************************************\n\n#include <iostream>\n#include <fstream>\n\n#include \"gambit/Elements/standalone_module.hpp\"\n#include \"gambit/DarkBit/DarkBit_rollcall.hpp\"\n#include \"gambit/Elements/spectrum_factories.hpp\"\n#include \"gambit/Utils/util_functions.hpp\"\n\n#include <boost/multi_array.hpp>\n\nusing namespace DarkBit::Functown;     // Functors wrapping the module's actual module functions\nusing namespace BackendIniBit::Functown;    // Functors wrapping the backend initialisation functions\n\nQUICK_FUNCTION(DarkBit, TH_ProcessCatalog, OLD_CAPABILITY, TH_ProcessCatalog_WIMP, TH_ProcessCatalog, ())\nQUICK_FUNCTION(DarkBit, DarkMatter_ID, OLD_CAPABILITY, DarkMatter_ID_WIMP, std::string, ())\nQUICK_FUNCTION(DarkBit, DD_couplings, OLD_CAPABILITY, DD_couplings_WIMP, DM_nucleon_couplings, ())\n\n\nvoid dump_array_to_file(const std::string & filename, const\n    boost::multi_array<double, 2> & a, const std::vector<double> & x, const\n    std::vector<double> & y)\n{\n  std::fstream file;\n  file.open(filename, std::ios_base::out);\n  file << \"0.0 \";\n  for (size_t i = 0; i < x.size(); i++)\n    file << x[i] << \" \";\n  file << std::endl;\n  for (size_t j = 0; j < y.size(); j++)\n  {\n    file << y[j] << \" \";\n    for (size_t i = 0; i < x.size(); i++)\n    {\n      file << a[i][j] << \" \";\n    }\n    file << std::endl;\n  }\n  file.close();\n}\n\nvoid dumpSpectrum(std::string filename, double mWIMP, double sv, std::vector<double> brList, double mPhi = -1)\n{\n  DarkMatter_ID_WIMP.reset_and_calculate();\n  TH_ProcessCatalog_WIMP.setOption<std::vector<double>>(\"brList\", brList);\n  TH_ProcessCatalog_WIMP.setOption<double>(\"mWIMP\", mWIMP);\n  TH_ProcessCatalog_WIMP.setOption<double>(\"sv\", sv);\n  if (mPhi != -1)\n    TH_ProcessCatalog_WIMP.setOption<double>(\"mPhi\", mPhi);\n  TH_ProcessCatalog_WIMP.reset_and_calculate();\n  RD_fraction_one.reset_and_calculate();\n  SimYieldTable_DarkSUSY.reset_and_calculate();\n  SimYieldTable_MicrOmegas.reset_and_calculate();\n  GA_missingFinalStates.reset_and_calculate();\n  cascadeMC_FinalStates.reset_and_calculate();\n  cascadeMC_DecayTable.reset_and_calculate();\n  cascadeMC_LoopManager.reset_and_calculate();\n  cascadeMC_gammaSpectra.reset_and_calculate();\n  GA_AnnYield_General.reset_and_calculate();\n  dump_GammaSpectrum.setOption<std::string>(\"filename\", filename);\n  dump_GammaSpectrum.reset_and_calculate();\n}\n\n// ---- Set up basic internal structures for direct & indirect detection ----\n\nnamespace Gambit\n{\n  namespace DarkBit\n  {\n\n    void TH_ProcessCatalog_WIMP(DarkBit::TH_ProcessCatalog& result)\n    {\n      using namespace Pipes::TH_ProcessCatalog_WIMP;\n      using std::vector;\n      using std::string;\n\n      // Initialize empty catalog and main annihilation process\n      TH_ProcessCatalog catalog;\n      TH_Process process_ann(\"WIMP\", \"WIMP\");\n      TH_Process process_dec(\"phi\");\n      TH_Process process_dec1(\"phi1\");\n      TH_Process process_dec2(\"phi2\");\n\n      ///////////////////////////////////////\n      // Import particle masses and couplings\n      ///////////////////////////////////////\n\n#define addParticle(Name, Mass, spinX2)                                        \\\n      catalog.particleProperties.insert(std::pair<string, TH_ParticleProperty> \\\n      (Name , TH_ParticleProperty(Mass, spinX2)));\n\n      /// Option mWIMP<double>: WIMP mass in GeV (required)\n      double mWIMP = runOptions->getValue<double>(\"mWIMP\");\n      /// Option sv<double>: Cross-section in cm3/s (required)\n      double sv = runOptions->getValue<double>(\"sv\");\n      double b = 0;  // defined as sv(v) = sv(v=0) + b*(sv=0)*v**2\n      /// Option brList<std::vector<double>>: List of branching ratios (required)\n      auto brList = runOptions->getValue<std::vector<double>>(\"brList\");\n      /// Option mWIMP<double>: WIMP mass in GeV (required)\n      double mPhi = runOptions->getValueOrDef<double>(59.0, \"mPhi\");\n\n      addParticle(\"gamma\", 0.0,  2)\n      addParticle(\"Z0\", 91.2,  2)\n      addParticle(\"W+\", 80.39, 2)\n      addParticle(\"W-\", 80.39, 2)\n      addParticle(\"e+_3\", 1.8,  1)\n      addParticle(\"e-_3\", 1.8,  1)\n      addParticle(\"e+_1\", 0.00051, 1)\n      addParticle(\"e-_1\", 0.00051, 1)\n      addParticle(\"b\", 4.9,  1)\n      addParticle(\"bbar\", 4.9,  1)\n      addParticle(\"d_3\", 4.9,  1)\n      addParticle(\"dbar_3\", 4.9,  1)\n\n      addParticle(\"WIMP\", mWIMP,  0)\n      addParticle(\"phi\",  mPhi,  0)\n      addParticle(\"phi1\", 100.,  0)\n      addParticle(\"phi2\", 100.,  0)\n#undef addParticle\n\n      TH_Channel dec_channel(daFunk::vec<string>(\"gamma\", \"gamma\"), daFunk::cnst(1.));\n      process_dec.channelList.push_back(dec_channel);\n\n      TH_Channel dec_channel1(daFunk::vec<string>(\"e+_3\", \"e-_3\"), daFunk::cnst(1.));\n      process_dec1.channelList.push_back(dec_channel1);\n\n      TH_Channel dec_channel2(daFunk::vec<string>(\"d_3\", \"dbar_3\"), daFunk::cnst(1.));\n      process_dec2.channelList.push_back(dec_channel2);\n\n      process_ann.resonances_thresholds.threshold_energy.push_back(2*mWIMP);\n      auto p1 = daFunk::vec<string>(\"d_3\", \"gamma\", \"gamma\", \"e-_3\", \"W-\", \"e-_1\", \"phi\");\n      auto p2 = daFunk::vec<string>(\"dbar_3\", \"Z0\", \"gamma\", \"e+_3\", \"W+\", \"e+_1\", \"phi2\");\n      {\n        for ( unsigned int i = 0; i < brList.size()-1; i++ )\n        {\n          double mtot_final =\n            catalog.getParticleProperty(p1[i]).mass +\n            catalog.getParticleProperty(p2[i]).mass;\n          if ( mWIMP*2 > mtot_final && brList[i]!= 0.)\n          {\n            // std::cout << p1[i] << \" \" << p2[i] << \" \" << brList[i] << std::endl;\n            daFunk::Funk kinematicFunction = (daFunk::one(\"v\")+pow(daFunk::var(\"v\"), 2)*b)*sv*brList[i];\n            TH_Channel new_channel(\n                daFunk::vec<string>(p1[i], p2[i]), kinematicFunction\n                );\n            process_ann.channelList.push_back(new_channel);\n          }\n          else\n          {\n            process_ann.resonances_thresholds.threshold_energy.\n              push_back(mtot_final);\n          }\n        }\n      }\n\n      if ( brList[7] > 0. )\n      {\n        auto E = daFunk::var(\"E\");\n        // Note:: The below is an arbitrary form of the differential section for demonstration purposes\n        daFunk::Funk kinematicFunction = daFunk::one(\"v\", \"E1\")/(pow(E-50, 4)+1)*sv*brList[7];\n        // Note: In the three body final states, the gamma yield from AnnYield currently is just the contribution\n        // from the first particle in the list (here the photon):\n        TH_Channel new_channel(daFunk::vec<string>(\"gamma\", \"e+_1\", \"e-_1\"), kinematicFunction);\n        process_ann.channelList.push_back(new_channel);\n      }\n\n      catalog.processList.push_back(process_ann);\n      catalog.processList.push_back(process_dec);\n      catalog.processList.push_back(process_dec1);\n      catalog.processList.push_back(process_dec2);\n\n      catalog.validate();\n\n      result = catalog;\n    } // function TH_ProcessCatalog_WIMP\n\n    // Identifier for DM particle\n    void DarkMatter_ID_WIMP(std::string& result)\n    {\n      result = \"WIMP\";\n    }\n\n    void DD_couplings_WIMP(DM_nucleon_couplings& result)\n    {\n      using namespace Pipes::DD_couplings_WIMP;\n      /// Option gps<double>: gps (default 0)\n      result.gps = runOptions->getValueOrDef<double>(0., \"gps\");\n      /// Option gns<double>: gns (default 0)\n      result.gns = runOptions->getValueOrDef<double>(0., \"gns\");\n      /// Option gpa<double>: gpa (default 0)\n      result.gpa = runOptions->getValueOrDef<double>(0., \"gpa\");\n      /// Option gna<double>: gna (default 0)\n      result.gna = runOptions->getValueOrDef<double>(0., \"gna\");\n      //std::cout << \"DD_coupling says\" << std::endl;\n      //std::cout << result.gps << std::endl;\n    }\n  }\n}\n\nint main(int argc, char* argv[])\n{\n    std::cout << std::endl;\n    std::cout << \"Welcome to the DarkBit Generic WIMP standalone program!\" << std::endl;\n    std::cout << std::endl;\n    std::cout << \"**************************************************************************************\" << std::endl;\n    std::cout << \"This standalone example demonstrates how to calculate a range of observables and \" << std::endl;\n    std::cout << \"likelihoods for a generic WIMP model defined by the WIMP mass and an annihilation (or \" << std::endl;\n    std::cout << \"scattering) cross section. The model also contains three scalar particles which decay:\" << std::endl;\n    std::cout << \"phi -> gamma gamma    phi_1 -> tau+ tau-  phi_2 -> b bbar\" << std::endl;\n    std::cout << std::endl;\n    std::cout << \"Usage: DarkBit_standalone_WIMP mode\" << std::endl;\n    std::cout << std::endl;\n    std::cout << \"Mode Options: \" << std::endl;\n    std::cout << \"  0: Outputs spectrum of gamma rays from WIMP annihilation to b bbar (dPhi_dE0.dat)\" << std::endl;\n    std::cout << \"  1: Outputs spectrum of gamma rays from WIMP annihilation to gamma Z_0 (dPhi_dE1.dat)\" << std::endl;\n    std::cout << \"  2: Outputs spectrum of gamma rays from WIMP annihilation to gamma gamma (dPhi_dE2.dat)\" << std::endl;\n    std::cout << \"  3: Outputs spectrum of gamma rays from WIMP annihilation to tau+ tau- (dPhi_dE3.dat)\" << std::endl;\n    std::cout << \"  4: Outputs spectrum of gamma rays from WIMP annihilation to W+ W- (dPhi_dE4.dat)\" << std::endl;\n    std::cout << \"  5: Outputs spectrum of gamma rays from WIMP annihilation to gamma e+ e- \" << std::endl;\n    std::cout << \"      (dPhi_dE5.dat)\" << std::endl;\n    std::cout << \"  6: Outputs tables of gamma-ray likelihoods and the relic density\" << std::endl;\n    std::cout << \"      in <sigma v> / m_WIMP parameter space.\" << std::endl;\n    std::cout << \"  7: Outputs tables of direct detection likelihoods in sigma / m_WIMP parameter\" << std::endl;\n    std::cout << \"      space.\" << std::endl;\n    std::cout << \"  >=10: Outputs spectrum of gamma rays from WIMP annihilation to phi phi_2. The\" << std::endl;\n    std::cout << \"       mode value is m_phi while m_phi_2=100 GeV (dPhi_dE_FCMC_(mode).dat)\" << std::endl;\n    std::cout << \" N.B. Here dPhi/dE = sigma v / m_chi^2 * dN/dE\" << std::endl;\n    std::cout << \"**************************************************************************************\" << std::endl;\n    std::cout << std::endl;\n\n  try\n  {\n    if (argc==1)\n    {\n      std::cout << \"Please select test mode>=0\" << std::endl;\n      exit(1);\n    }\n    int mode = std::stoi((std::string)argv[1]);\n    std::cout << \"Starting with mode \" << mode << std::endl;\n\n\n    // ---- Initialise logging and exceptions ----\n\n    initialise_standalone_logs(\"runs/DarkBit_standalone_WIMP/logs/\");\n    logger()<<\"Running DarkBit standalone example\"<<LogTags::info<<EOM;\n    model_warning().set_fatal(true);\n\n\n    // ---- Check that required backends are present ----\n\n    if (not Backends::backendInfo().works[\"DarkSUSY5.1.3\"]) backend_error().raise(LOCAL_INFO, \"DarkSUSY 5.1.3 is missing!\");\n    if (not Backends::backendInfo().works[\"gamLike1.0.1\"]) backend_error().raise(LOCAL_INFO, \"gamLike 1.0.1 is missing!\");\n    if (not Backends::backendInfo().works[\"DDCalc2.2.0\"]) backend_error().raise(LOCAL_INFO, \"DDCalc 2.2.0 is missing!\");\n    if (not Backends::backendInfo().works[\"MicrOmegas_MSSM3.6.9.2\"]) backend_error().raise(LOCAL_INFO, \"MicrOmegas 3.6.9.2 for MSSM is missing!\");\n\n    // ---- Initialize models ----\n\n    // Initialize halo model\n    ModelParameters* Halo_primary_parameters = Models::Halo_Einasto::Functown::primary_parameters.getcontentsPtr();\n    Halo_primary_parameters->setValue(\"vrot\", 235.); // Local properties\n    Halo_primary_parameters->setValue(\"v0\", 235.);\n    Halo_primary_parameters->setValue(\"vesc\", 550.);\n    Halo_primary_parameters->setValue(\"rho0\", 0.4);\n    Halo_primary_parameters->setValue(\"r_sun\", 8.5);\n\n    Halo_primary_parameters->setValue(\"rs\", 20.);  // Global properties\n    Halo_primary_parameters->setValue(\"rhos\", 0.08);\n    Halo_primary_parameters->setValue(\"alpha\", 0.17);\n\n\n    // --- Resolve halo dependencies ---\n    ExtractLocalMaxwellianHalo.notifyOfModel(\"Halo_Einasto\");\n    ExtractLocalMaxwellianHalo.resolveDependency(&Models::Halo_Einasto::Functown::primary_parameters);\n    ExtractLocalMaxwellianHalo.reset_and_calculate();\n\n    GalacticHalo_Einasto.notifyOfModel(\"Halo_Einasto\");\n    GalacticHalo_Einasto.resolveDependency(&Models::Halo_Einasto::Functown::primary_parameters);\n    GalacticHalo_Einasto.reset_and_calculate();\n\n    // ---- Initialize backends ----\n\n    // Assume for direct and indirect detection likelihoods that dark matter\n    // density is always the measured one (despite relic density results)\n    RD_fraction_one.reset_and_calculate();\n\n    // Set up DDCalc backend initialization\n    Backends::DDCalc_2_2_0::Functown::DDCalc_CalcRates_simple.setStatus(2);\n    Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment.setStatus(2);\n    Backends::DDCalc_2_2_0::Functown::DDCalc_LogLikelihood.setStatus(2);\n    DDCalc_2_2_0_init.resolveDependency(&ExtractLocalMaxwellianHalo);\n    // Assume for direct and indirect detection likelihoods that dark matter\n    // density is always the measured one (despite relic density results)\n    DDCalc_2_2_0_init.resolveDependency(&RD_fraction_one);\n    DDCalc_2_2_0_init.resolveDependency(&mwimp_generic);\n    DDCalc_2_2_0_init.resolveDependency(&DD_couplings_WIMP);\n\n    // Initialize gamLike backend\n    gamLike_1_0_1_init.reset_and_calculate();\n\n    // Initialize DarkSUSY backend\n    DarkSUSY_5_1_3_init.reset_and_calculate();\n\n    // Initialize MicrOmegas backend\n    // The below allows us to initialise MicrOmegas_MSSM without a particular MSSM model.\n    MicrOmegas_MSSM_3_6_9_2_init.notifyOfModel(\"Halo_Einasto\");\n    MicrOmegas_MSSM_3_6_9_2_init.reset_and_calculate();\n\n    // ---- Gamma-ray yields ----\n\n    // Initialize tabulated gamma-ray yields\n    SimYieldTable_DarkSUSY.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::dshayield);\n    SimYieldTable_MicrOmegas.resolveBackendReq(&Backends::MicrOmegas_MSSM_3_6_9_2::Functown::dNdE);\n    SimYieldTable_DarkSUSY.setOption<bool>(\"allow_yield_extrapolation\", true);\n    SimYieldTable_MicrOmegas.setOption<bool>(\"allow_yield_extrapolation\", true);\n\n    // Select SimYieldTable\n    //auto SimYieldTablePointer = &SimYieldTable_MicrOmegas;\n    auto SimYieldTablePointer = &SimYieldTable_DarkSUSY;\n\n    // Collect missing final states for simulation in cascade MC\n    GA_missingFinalStates.resolveDependency(&TH_ProcessCatalog_WIMP);\n    GA_missingFinalStates.resolveDependency(SimYieldTablePointer);\n    GA_missingFinalStates.resolveDependency(&DarkMatter_ID_WIMP);\n\n    // Infer for which type of final states particles MC should be performed\n    cascadeMC_FinalStates.setOption<std::vector<std::string>>(\"cMC_finalStates\", daFunk::vec((std::string)\"gamma\"));\n\n    // Collect decay information for cascade MC\n    cascadeMC_DecayTable.resolveDependency(&TH_ProcessCatalog_WIMP);\n    cascadeMC_DecayTable.resolveDependency(SimYieldTablePointer);\n\n    // Set up MC loop manager for cascade MC\n    cascadeMC_LoopManager.setOption<int>(\"cMC_maxEvents\", 20000);\n    cascadeMC_Histograms.setOption<double>(\"cMC_endCheckFrequency\", 25);\n    cascadeMC_Histograms.setOption<double>(\"cMC_gammaRelError\", .05);\n    cascadeMC_Histograms.setOption<int>(\"cMC_numSpecSamples\", 25);\n    cascadeMC_Histograms.setOption<int>(\"cMC_NhistBins\", 300);\n    cascadeMC_LoopManager.resolveDependency(&GA_missingFinalStates);\n    std::vector<functor*> nested_functions = initVector<functor*>(\n        &cascadeMC_InitialState, &cascadeMC_GenerateChain, &cascadeMC_Histograms, &cascadeMC_EventCount);\n    cascadeMC_LoopManager.setNestedList(nested_functions);\n\n    // Set up initial state for cascade MC step\n    cascadeMC_InitialState.resolveDependency(&GA_missingFinalStates);\n    cascadeMC_InitialState.resolveLoopManager(&cascadeMC_LoopManager);\n    //cascadeMC_InitialState.reset_and_calculate();\n\n    // Perform MC step for cascade MC\n    cascadeMC_GenerateChain.resolveDependency(&cascadeMC_InitialState);\n    cascadeMC_GenerateChain.resolveDependency(&cascadeMC_DecayTable);\n    cascadeMC_GenerateChain.resolveLoopManager(&cascadeMC_LoopManager);\n    //cascadeMC_GenerateChain.reset_and_calculate();\n\n    // Generate histogram for cascade MC\n    cascadeMC_Histograms.resolveDependency(&cascadeMC_InitialState);\n    cascadeMC_Histograms.resolveDependency(&cascadeMC_GenerateChain);\n    cascadeMC_Histograms.resolveDependency(&TH_ProcessCatalog_WIMP);\n    cascadeMC_Histograms.resolveDependency(SimYieldTablePointer);\n    cascadeMC_Histograms.resolveDependency(&cascadeMC_FinalStates);\n    cascadeMC_Histograms.resolveLoopManager(&cascadeMC_LoopManager);\n    //cascadeMC_Histograms.reset_and_calculate();\n\n    // Check convergence of cascade MC\n    cascadeMC_EventCount.resolveDependency(&cascadeMC_InitialState);\n    cascadeMC_EventCount.resolveLoopManager(&cascadeMC_LoopManager);\n    //cascadeMC_EventCount.reset_and_calculate();\n\n    // Start cascade MC loop\n\n    // Infer gamma-ray spectra for recorded MC results\n    cascadeMC_gammaSpectra.resolveDependency(&GA_missingFinalStates);\n    cascadeMC_gammaSpectra.resolveDependency(&cascadeMC_FinalStates);\n    cascadeMC_gammaSpectra.resolveDependency(&cascadeMC_Histograms);\n    cascadeMC_gammaSpectra.resolveDependency(&cascadeMC_EventCount);\n\n    // Calculate total gamma-ray yield (cascade MC + tabulated results)\n    GA_AnnYield_General.resolveDependency(&TH_ProcessCatalog_WIMP);\n    GA_AnnYield_General.resolveDependency(SimYieldTablePointer);\n    GA_AnnYield_General.resolveDependency(&DarkMatter_ID_WIMP);\n    GA_AnnYield_General.resolveDependency(&cascadeMC_gammaSpectra);\n\n    dump_GammaSpectrum.resolveDependency(&GA_AnnYield_General);\n\n    // Resolve Galactic halo requirements for gamLike\n    set_gamLike_GC_halo.resolveDependency(&GalacticHalo_Einasto);\n    set_gamLike_GC_halo.resolveBackendReq(&Backends::gamLike_1_0_1::Functown::set_halo_profile);\n\n    // Calculate Fermi LAT dwarf likelihood\n    lnL_FermiLATdwarfs_gamLike.resolveDependency(&GA_AnnYield_General);\n    // Assume for direct and indirect detection likelihoods that dark matter\n    // density is always the measured one (despite relic density results)\n    lnL_FermiLATdwarfs_gamLike.resolveDependency(&RD_fraction_one);\n    lnL_FermiLATdwarfs_gamLike.resolveBackendReq(&Backends::gamLike_1_0_1::Functown::lnL);\n\n    lnL_HESSGC_gamLike.resolveDependency(&GA_AnnYield_General);\n    lnL_HESSGC_gamLike.resolveDependency(&RD_fraction_one);\n    lnL_HESSGC_gamLike.resolveBackendReq(&Backends::gamLike_1_0_1::Functown::lnL);\n\n    lnL_CTAGC_gamLike.resolveDependency(&GA_AnnYield_General);\n    lnL_CTAGC_gamLike.resolveDependency(&RD_fraction_one);\n    lnL_CTAGC_gamLike.resolveBackendReq(&Backends::gamLike_1_0_1::Functown::lnL);\n\n    lnL_FermiGC_gamLike.resolveDependency(&GA_AnnYield_General);\n    lnL_FermiGC_gamLike.resolveDependency(&RD_fraction_one);\n    lnL_FermiGC_gamLike.resolveBackendReq(&Backends::gamLike_1_0_1::Functown::lnL);\n\n\n    // -- Calculate relic density --\n    RD_eff_annrate_from_ProcessCatalog.notifyOfModel(\"ScalarSingletDM_Z2\");\n    RD_eff_annrate_from_ProcessCatalog.resolveDependency(&TH_ProcessCatalog_WIMP);\n    RD_eff_annrate_from_ProcessCatalog.resolveDependency(&DarkMatter_ID_WIMP);\n\n    RD_spectrum_from_ProcessCatalog.resolveDependency(&TH_ProcessCatalog_WIMP);\n    RD_spectrum_from_ProcessCatalog.resolveDependency(&DarkMatter_ID_WIMP);\n\n    RD_spectrum_ordered_func.resolveDependency(&RD_spectrum_from_ProcessCatalog);\n\n    RD_oh2_general.resolveDependency(&RD_spectrum_ordered_func);\n    RD_oh2_general.resolveDependency(&RD_eff_annrate_from_ProcessCatalog);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::dsrdthlim);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::dsrdtab);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::dsrdeqn);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::dsrdwintp);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::widths);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rdmgev);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rdpth);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rdpars);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rdswitch);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rdlun);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rdpadd);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rddof);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rderrors);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::rdtime);\n    RD_oh2_general.resolveBackendReq(&Backends::DarkSUSY_5_1_3::Functown::DSparticle_code);\n\n\n    // ---- Calculate direct detection constraints ----\n\n    // Calculate direct detection rates for LZ, PandaX 2017, Xenon 1T and PICO-60\n    LZ_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    LZ_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_CalcRates_simple);\n    PandaX_2017_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    PandaX_2017_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_CalcRates_simple);\n    PICO_60_2017_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    PICO_60_2017_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_CalcRates_simple);\n    XENON1T_2017_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    XENON1T_2017_Calc.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_CalcRates_simple);\n\n    // Calculate direct detection likelihood for LZ, PandaX 2017, Xenon 1T and PICO-60\n    LZ_GetLogLikelihood.resolveDependency(&LZ_Calc);\n    LZ_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    LZ_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_LogLikelihood);\n    PandaX_2017_GetLogLikelihood.resolveDependency(&PandaX_2017_Calc);\n    PandaX_2017_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    PandaX_2017_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_LogLikelihood);\n    XENON1T_2017_GetLogLikelihood.resolveDependency(&XENON1T_2017_Calc);\n    XENON1T_2017_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    XENON1T_2017_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_LogLikelihood);\n    PICO_60_2017_GetLogLikelihood.resolveDependency(&PICO_60_2017_Calc);\n    PICO_60_2017_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    PICO_60_2017_GetLogLikelihood.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_LogLikelihood);\n\n    // Provide bin number in LZ\n    LZ_GetBinSignal.resolveDependency(&LZ_Calc);\n    LZ_GetBinSignal.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Experiment);\n    LZ_GetBinSignal.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_Bins);\n    LZ_GetBinSignal.resolveBackendReq(&Backends::DDCalc_2_2_0::Functown::DDCalc_BinSignal);\n\n    // Set generic WIMP mass object\n    mwimp_generic.resolveDependency(&TH_ProcessCatalog_WIMP);\n    mwimp_generic.resolveDependency(&DarkMatter_ID_WIMP);\n    sigma_SI_p_simple.resolveDependency(&DD_couplings_WIMP);\n    sigma_SI_p_simple.resolveDependency(&mwimp_generic);\n\n    // Generate gamma-ray spectra for various final states\n    if ( (mode >= 0) and (mode < 6) )\n    {\n      std::cout << \"Producing test spectra.\" << std::endl;\n      double mass = 100.;\n      double sv = 3e-26;\n      // The array that is being passed to dumpSpectrum give the branching fraction to various final states.\n      // They are (as defined in TH_ProcessCatalog_WIMP):\n      // 0: b bbar\n      // 1: gamma Z_0\n      // 2: gamma gamma\n      // 3: tau+ tau-\n      // 4: W+ W-\n      // 5: e+ e-\n      // 6: phi phi2\n      // 7: gamma e+ e-\n      if (mode==5) dumpSpectrum(\"dPhi_dE5.dat\", mass, sv*0.1, daFunk::vec<double>(0., 0., 0., 0., 0., 0., 0., 1.));\n      if (mode==0) dumpSpectrum(\"dPhi_dE0.dat\", mass, sv, daFunk::vec<double>(1., 0., 0., 0., 0., 0., 0., 0.));\n      if (mode==1) dumpSpectrum(\"dPhi_dE1.dat\", mass, sv, daFunk::vec<double>(0., 1., 0., 0., 0., 0., 0., 0.));\n      if (mode==2) dumpSpectrum(\"dPhi_dE2.dat\", mass, sv, daFunk::vec<double>(0., 0., 1., 0., 0., 0., 0., 0.));\n      if (mode==3) dumpSpectrum(\"dPhi_dE3.dat\", mass, sv, daFunk::vec<double>(0., 0., 0., 1., 0., 0., 0., 0.));\n      if (mode==4) dumpSpectrum(\"dPhi_dE4.dat\", mass, sv, daFunk::vec<double>(0., 0., 0., 0., 1., 0., 0., 0.));\n    }\n\n    // Generate gamma-ray spectra for various masses\n    if (mode >= 10)\n    {\n      std::cout << \"Producing test spectra.\" << std::endl;\n      double mass = 100.;\n      double sv = 3e-26;\n      std::string filename = \"dPhi_dE_FCMC_\" + std::to_string(mode) + \".dat\";\n      dumpSpectrum(filename, mass, sv, daFunk::vec<double>(0., 0., 0., 0., 0., 0., 1., 0.), mode);\n    }\n\n    // Systematic parameter maps annihilation\n    if (mode==6)\n    {\n      std::cout << \"Producing gamma ray test maps.\" << std::endl;\n      int mBins = 60;\n      int svBins = 60;\n      double oh2, lnL;\n      std::vector<double> sv_list, m_list;\n\n      GalacticHalo_Einasto.reset_and_calculate();\n      set_gamLike_GC_halo.reset_and_calculate();\n\n      boost::multi_array<double, 2>\n        lnL_b_array{boost::extents[mBins][svBins]},\n        lnL_b_array2{boost::extents[mBins][svBins]},\n        lnL_b_array3{boost::extents[mBins][svBins]},\n        lnL_b_array4{boost::extents[mBins][svBins]},\n        lnL_tau_array{boost::extents[mBins][svBins]};\n      boost::multi_array<double, 2> oh2_array{boost::extents[mBins][svBins]};\n\n      sv_list = daFunk::logspace(-28.0, -22.0, svBins);\n\n      std::cout << \"Calculating gamma-ray likelihood tables for annihilation to b bbar.\" << std::endl;\n      m_list = daFunk::logspace(log10(5.), 4., mBins);\n      for (size_t i = 0; i < m_list.size(); i++)\n      {\n        for (size_t j = 0; j < sv_list.size(); j++)\n        {\n          TH_ProcessCatalog_WIMP.setOption<double>(\"mWIMP\", m_list[i]);\n          TH_ProcessCatalog_WIMP.setOption<double>(\"sv\", sv_list[j]);\n          //std::cout << \"Parameters: \" << m_list[i] << \" \" << sv_list[j] << std::endl;\n\n          TH_ProcessCatalog_WIMP.setOption<std::vector<double>>(\"brList\", daFunk::vec<double>(1., 0., 0., 0., 0., 0., 0., 0.));\n          DarkMatter_ID_WIMP.reset_and_calculate();\n          TH_ProcessCatalog_WIMP.reset_and_calculate();\n          RD_fraction_one.reset_and_calculate();\n          SimYieldTable_DarkSUSY.reset_and_calculate();\n          SimYieldTable_MicrOmegas.reset_and_calculate();\n          GA_missingFinalStates.reset_and_calculate();\n          cascadeMC_FinalStates.reset_and_calculate();\n          cascadeMC_DecayTable.reset_and_calculate();\n          cascadeMC_LoopManager.reset_and_calculate();\n          cascadeMC_gammaSpectra.reset_and_calculate();\n          GA_AnnYield_General.reset_and_calculate();\n          lnL_FermiLATdwarfs_gamLike.setOption<std::string>(\"version\", \"pass8\");\n          lnL_FermiLATdwarfs_gamLike.reset_and_calculate();\n          lnL = lnL_FermiLATdwarfs_gamLike(0);\n          //std::cout << \"Fermi dwarf likelihood: \" << lnL << std::endl;\n          lnL_b_array[i][j] = lnL;\n          lnL_HESSGC_gamLike.setOption<std::string>(\"version\", \"integral_fixedJ\");\n          lnL_HESSGC_gamLike.reset_and_calculate();\n          lnL = lnL_HESSGC_gamLike(0);\n          //std::cout << \"HESS GC likelihood: \" << lnL << std::endl;\n          lnL_b_array2[i][j] = lnL;\n          lnL_CTAGC_gamLike.reset_and_calculate();\n          lnL = lnL_CTAGC_gamLike(0);\n          //std::cout << \"CTA GC likelihood: \" << lnL << std::endl;\n          lnL_b_array3[i][j] = lnL;\n          lnL_FermiGC_gamLike.setOption<std::string>(\"version\", \"fixedJ\");\n          lnL_FermiGC_gamLike.reset_and_calculate();\n          lnL = lnL_FermiGC_gamLike(0);\n          lnL_b_array4[i][j] = lnL;\n          //std::cout << \"Fermi GC likelihood: \" << lnL << std::endl;\n        }\n      }\n\n      dump_array_to_file(\"FermiD_b_table.dat\", lnL_b_array, m_list, sv_list);\n      dump_array_to_file(\"HESSGC_b_table.dat\", lnL_b_array2, m_list, sv_list);\n      dump_array_to_file(\"CTAGC_b_table.dat\", lnL_b_array3, m_list, sv_list);\n      dump_array_to_file(\"FermiGC_b_table.dat\", lnL_b_array4, m_list, sv_list);\n\n      std::cout << \"Calculating Fermi-LAT dwarf spheroidal likehood table for annihilation to tau+ tau-.\" << std::endl;\n      m_list = daFunk::logspace(log10(1.9), 4., mBins);\n      for (size_t i = 0; i < m_list.size(); i++)\n      {\n        for (size_t j = 0; j < sv_list.size(); j++)\n        {\n          TH_ProcessCatalog_WIMP.setOption<double>(\"mWIMP\", m_list[i]);\n          TH_ProcessCatalog_WIMP.setOption<double>(\"sv\", sv_list[j]);\n          //std::cout << \"Parameters: \" << m_list[i] << \" \" << sv_list[j] << std::endl;\n\n          TH_ProcessCatalog_WIMP.setOption<std::vector<double>>(\"brList\", daFunk::vec<double>(0., 0., 0., 1., 0., 0., 0., 0.));\n          DarkMatter_ID_WIMP.reset_and_calculate();\n          TH_ProcessCatalog_WIMP.reset_and_calculate();\n          RD_fraction_one.reset_and_calculate();\n          SimYieldTable_DarkSUSY.reset_and_calculate();\n          SimYieldTable_MicrOmegas.reset_and_calculate();\n          GA_missingFinalStates.reset_and_calculate();\n          cascadeMC_FinalStates.reset_and_calculate();\n          cascadeMC_DecayTable.reset_and_calculate();\n          cascadeMC_LoopManager.reset_and_calculate();\n          cascadeMC_gammaSpectra.reset_and_calculate();\n          GA_AnnYield_General.reset_and_calculate();\n          lnL_FermiLATdwarfs_gamLike.reset_and_calculate();\n          lnL = lnL_FermiLATdwarfs_gamLike(0);\n          //std::cout << \"Fermi LAT likelihood: \" << lnL << std::endl;\n          lnL_tau_array[i][j] = lnL;\n        }\n      }\n\n      dump_array_to_file(\"FermiD_tau_table.dat\", lnL_tau_array, m_list, sv_list);\n\n      std::cout << \"Calculating table of Omega h^2 values.\" << std::endl;\n      m_list = daFunk::logspace(-1.0, 4., mBins);\n      for (size_t i = 0; i < m_list.size(); i++)\n      {\n        for (size_t j = 0; j < sv_list.size(); j++)\n        {\n          TH_ProcessCatalog_WIMP.setOption<double>(\"mWIMP\", m_list[i]);\n          TH_ProcessCatalog_WIMP.setOption<double>(\"sv\", sv_list[j]);\n          //std::cout << \"Parameters: \" << m_list[i] << \" \" << sv_list[j] << std::endl;\n\n          TH_ProcessCatalog_WIMP.setOption<std::vector<double>>(\"brList\", daFunk::vec<double>(0., 0., 0., 0., 0., 1., 0., 0.));\n          DarkMatter_ID_WIMP.reset_and_calculate();\n          TH_ProcessCatalog_WIMP.reset_and_calculate();\n          RD_eff_annrate_from_ProcessCatalog.reset_and_calculate();\n          RD_spectrum_from_ProcessCatalog.reset_and_calculate();\n          RD_spectrum_ordered_func.reset_and_calculate();\n          RD_oh2_general.reset_and_calculate();\n          oh2 = RD_oh2_general(0);\n          //std::cout << \"Omega h^2 = \" << oh2 << std::endl;\n          oh2_array[i][j] = oh2;\n        }\n      }\n\n      dump_array_to_file(\"oh2_table.dat\", oh2_array, m_list, sv_list);\n    }\n\n    // Systematic parameter maps scattering\n    if (mode==7)\n    {\n      std::cout << \"Producing direct detection test maps.\" << std::endl;\n      double lnL1, lnL2, lnL3, lnL4;\n      int nbins;\n      double g, reduced_mass;\n      //int mBins = 300;\n      //int sBins = 200;\n      int mBins = 120;\n      int sBins = 80;\n      const double mN = (m_proton + m_neutron) / 2;\n      std::vector<double> m_list = daFunk::logspace(0.0, 4.0, mBins);\n      std::vector<double> s_list;\n      boost::multi_array<double, 2> lnL_array1{boost::extents[mBins][sBins]},\n          lnL_array2{boost::extents[mBins][sBins]}, lnL_array3{boost::extents[mBins][sBins]},\n          lnL_array4{boost::extents[mBins][sBins]};\n      TH_ProcessCatalog_WIMP.setOption<double>(\"sv\", 0.);\n      TH_ProcessCatalog_WIMP.setOption<std::vector<double>>(\"brList\", daFunk::vec<double>(1., 0., 0., 0., 0., 0., 0., 0.));\n\n      s_list = daFunk::logspace(-47., -40., sBins);\n      // Calculate array of sigma_SI and lnL values for LZ, PandaX, XENON1T and PICO-60\n      // assuming gps=gns\n\n      std::cout << \"Calculating tables of SI likelihoods.\" << std::endl;\n      for (size_t i = 0; i < m_list.size(); i++)\n      {\n        for (size_t j = 0; j < s_list.size(); j++)\n        {\n          // Re-initialize DDCalc with LZ/Xenon/PandaX halo parameters\n          Halo_primary_parameters->setValue(\"rho0\", 0.3);\n          Halo_primary_parameters->setValue(\"vrot\", 232.7); // v_Earth = 245 km/s\n          Halo_primary_parameters->setValue(\"v0\", 220.);\n          Halo_primary_parameters->setValue(\"vesc\", 544.);\n          ExtractLocalMaxwellianHalo.reset_and_calculate();\n\n          TH_ProcessCatalog_WIMP.setOption<double>(\"mWIMP\", m_list[i]);\n          //std::cout << \"Parameters: \" << m_list[i] << \" \" << s_list[j] << std::endl;\n          reduced_mass = (m_list[i] * mN) / (mN + m_list[i]);\n          g = sqrt(s_list[j]*pi/gev2cm2) / (reduced_mass);\n          DarkMatter_ID_WIMP.reset_and_calculate();\n          TH_ProcessCatalog_WIMP.reset_and_calculate();\n          // Assume for direct and indirect detection likelihoods that dark matter\n          // density is always the measured one (despite relic density results)\n          RD_fraction_one.reset_and_calculate();\n          DD_couplings_WIMP.setOption<double>(\"gps\", g);\n          DD_couplings_WIMP.setOption<double>(\"gns\", g);\n          DD_couplings_WIMP.setOption<double>(\"gpa\", 0.);\n          DD_couplings_WIMP.setOption<double>(\"gna\", 0.);\n          DD_couplings_WIMP.reset_and_calculate();\n          mwimp_generic.reset_and_calculate();\n\n          DDCalc_2_2_0_init.reset_and_calculate();\n          LZ_Calc.reset_and_calculate();\n          LZ_GetLogLikelihood.reset_and_calculate();\n\n          XENON1T_2017_Calc.reset_and_calculate();\n          XENON1T_2017_GetLogLikelihood.reset_and_calculate();\n          PandaX_2017_Calc.reset_and_calculate();\n          PandaX_2017_GetLogLikelihood.reset_and_calculate();\n\n          lnL1 = LZ_GetLogLikelihood(0);\n          lnL2 = PandaX_2017_GetLogLikelihood(0);\n          lnL3 = XENON1T_2017_GetLogLikelihood(0);\n\n          // Set LocalHalo Model parameters to PICO-60 values\n          Halo_primary_parameters->setValue(\"rho0\", 0.3);\n          Halo_primary_parameters->setValue(\"vrot\", 220.);\n          Halo_primary_parameters->setValue(\"v0\", 220.);\n          Halo_primary_parameters->setValue(\"vesc\", 544.);\n          ExtractLocalMaxwellianHalo.reset_and_calculate();\n\n          DDCalc_2_2_0_init.reset_and_calculate();\n          PICO_60_2017_Calc.reset_and_calculate();\n          PICO_60_2017_GetLogLikelihood.reset_and_calculate();\n          lnL4 = PICO_60_2017_GetLogLikelihood(0);\n\n          //std::cout << \"LZ SI lnL = \" << lnL1 << std::endl;\n          //std::cout << \"PandaX_2017 SI lnL = \" << lnL2 << std::endl;\n          //std::cout << \"XENON1T_2017 SI lnL = \" << lnL3 << std::endl;\n          //std::cout << \"PICO_60_2017 SI lnL = \" << lnL4 << std::endl;\n\n          DDCalc_2_2_0_init.reset_and_calculate();\n          LZ_Calc.reset_and_calculate();\n          std::vector<double> events;\n          LZ_GetBinSignal.reset_and_calculate();\n          events = LZ_GetBinSignal(0);\n          nbins = events.size();\n          std::cout << \"Number of LZ bins: \" << nbins << std::endl;\n          std::cout << \"Predicted signal: \";\n          for (int ibin=0;ibin<=nbins-1;ibin++) {\n            std::cout << events[ibin] << \" \";\n          }\n          std::cout << std::endl;\n\n          lnL_array1[i][j] = lnL1;\n          lnL_array2[i][j] = lnL2;\n          lnL_array3[i][j] = lnL3;\n          lnL_array4[i][j] = lnL4;\n        }\n      }\n\n      dump_array_to_file(\"LZ_SI_table.dat\", lnL_array1, m_list, s_list);\n      dump_array_to_file(\"PandaX_2017_SI_table.dat\", lnL_array2, m_list, s_list);\n      dump_array_to_file(\"XENON1T_2017_SI_table.dat\", lnL_array3, m_list, s_list);\n      dump_array_to_file(\"PICO_60_2017_SI_table.dat\", lnL_array4, m_list, s_list);\n\n      s_list = daFunk::logspace(-42., -35., sBins);\n      // Calculate array of sigma_SI and lnL values for LZ, PandaX, XENON1T and PICO-60\n      // assuming gna=0 (proton-only)\n\n      std::cout << \"Calculating tables of SD likelihoods.\" << std::endl;\n      for (size_t i = 0; i < m_list.size(); i++)\n      {\n        for (size_t j = 0; j < s_list.size(); j++)\n        {\n          // Re-initialize DDCalc with LZ/Xenon/PandaX halo parameters\n          Halo_primary_parameters->setValue(\"rho0\", 0.3);\n          Halo_primary_parameters->setValue(\"vrot\", 232.7); // v_Earth = 245 km/s\n          Halo_primary_parameters->setValue(\"v0\", 220.);\n          Halo_primary_parameters->setValue(\"vesc\", 544.);\n          ExtractLocalMaxwellianHalo.reset_and_calculate();\n\n          TH_ProcessCatalog_WIMP.setOption<double>(\"mWIMP\", m_list[i]);\n          //std::cout << \"Parameters: \" << m_list[i] << \" \" << s_list[j] << std::endl;\n          reduced_mass = (m_list[i] * m_proton) / (m_proton + m_list[i]);\n          g = sqrt(s_list[j]*pi/(3*gev2cm2)) / (reduced_mass);\n          DarkMatter_ID_WIMP.reset_and_calculate();\n          TH_ProcessCatalog_WIMP.reset_and_calculate();\n          RD_fraction_one.reset_and_calculate();\n          DD_couplings_WIMP.setOption<double>(\"gps\", 0.);\n          DD_couplings_WIMP.setOption<double>(\"gns\", 0.);\n          DD_couplings_WIMP.setOption<double>(\"gpa\", g);\n          DD_couplings_WIMP.setOption<double>(\"gna\", 0.);\n          DD_couplings_WIMP.reset_and_calculate();\n          mwimp_generic.reset_and_calculate();\n\n          DDCalc_2_2_0_init.reset_and_calculate();\n          LZ_Calc.reset_and_calculate();\n          LZ_GetLogLikelihood.reset_and_calculate();\n          XENON1T_2017_Calc.reset_and_calculate();\n          XENON1T_2017_GetLogLikelihood.reset_and_calculate();\n          PandaX_2017_Calc.reset_and_calculate();\n          PandaX_2017_GetLogLikelihood.reset_and_calculate();\n          lnL1 = LZ_GetLogLikelihood(0);\n          lnL2 = PandaX_2017_GetLogLikelihood(0);\n          lnL3 = XENON1T_2017_GetLogLikelihood(0);\n\n          // Set LocalHalo Model parameters to PICO-60 values\n          Halo_primary_parameters->setValue(\"rho0\", 0.3);\n          Halo_primary_parameters->setValue(\"vrot\", 220.);\n          Halo_primary_parameters->setValue(\"v0\", 220.);\n          Halo_primary_parameters->setValue(\"vesc\", 544.);\n          ExtractLocalMaxwellianHalo.reset_and_calculate();\n\n          DDCalc_2_2_0_init.reset_and_calculate();\n          PICO_60_2017_Calc.reset_and_calculate();\n          PICO_60_2017_GetLogLikelihood.reset_and_calculate();\n          lnL4 = PICO_60_2017_GetLogLikelihood(0);\n\n          //std::cout << \"LZ SD lnL = \" << lnL1 << std::endl;\n          //std::cout << \"PandaX_2017 SD lnL = \" << lnL2 << std::endl;\n          //std::cout << \"XENON1T_2017 SD lnL = \" << lnL3 << std::endl;\n          //std::cout << \"PICO_60_2017 SD lnL = \" << lnL4 << std::endl;\n\n          lnL_array1[i][j] = lnL1;\n          lnL_array2[i][j] = lnL2;\n          lnL_array3[i][j] = lnL3;\n          lnL_array4[i][j] = lnL4;\n        }\n      }\n\n      dump_array_to_file(\"LZ_SD_table.dat\", lnL_array1, m_list, s_list);\n      dump_array_to_file(\"PandaX_2017_SD_table.dat\", lnL_array2, m_list, s_list);\n      dump_array_to_file(\"XENON1T_2017_SD_table.dat\", lnL_array3, m_list, s_list);\n      dump_array_to_file(\"PICO_60_2017_SD_table.dat\", lnL_array4, m_list, s_list);\n\n      // Reset halo parameters to DarkBit defaults.\n      Halo_primary_parameters->setValue(\"rho0\", 0.4);\n      Halo_primary_parameters->setValue(\"vrot\", 235.);\n      Halo_primary_parameters->setValue(\"v0\", 235.);\n      Halo_primary_parameters->setValue(\"vesc\", 550.);\n      ExtractLocalMaxwellianHalo.reset_and_calculate();\n      GalacticHalo_Einasto.reset_and_calculate();\n\n    }\n  }\n\n  catch (std::exception& e)\n  {\n    std::cout << \"DarkBit_standalone_WIMP has exited with fatal exception: \" << e.what() << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "f56fd6bba8f7a6546a802be4216c97b5367b9f66", "size": 40485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DarkBit/examples/DarkBit_standalone_WIMP.cpp", "max_stars_repo_name": "anderkve/gambit_np", "max_stars_repo_head_hexsha": "3183fff753376523730eda1920711f221224a9b5", "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": "DarkBit/examples/DarkBit_standalone_WIMP.cpp", "max_issues_repo_name": "anderkve/gambit_np", "max_issues_repo_head_hexsha": "3183fff753376523730eda1920711f221224a9b5", "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": "DarkBit/examples/DarkBit_standalone_WIMP.cpp", "max_forks_repo_name": "anderkve/gambit_np", "max_forks_repo_head_hexsha": "3183fff753376523730eda1920711f221224a9b5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T20:46:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T20:46:24.000Z", "avg_line_length": 47.5734430082, "max_line_length": 146, "alphanum_fraction": 0.6745461282, "num_tokens": 11713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748935136304, "lm_q2_score": 0.03021458390183501, "lm_q1q2_score": 0.010749590370234001}}
{"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_MODE_PADDING_HPP\n#define CRYPTO3_MODE_PADDING_HPP\n\n#include <nil/crypto3/utilities/secmem.hpp>\n\n#include <string>\n\n#include <boost/static_assert.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace block {\n            namespace modes {\n                namespace padding {\n                    /*!\n                     * @brief  Block Cipher Mode Padding Method\n                     * @tparam Cipher Block cipher used\n                     *\n                     * This class is pretty limited, it cannot deal well with\n                     * randomized padding methods, or any padding method that\n                     * wants to add more than one block. For instance, it should\n                     * be possible to define cipher text stealing mode as simply\n                     * a padding mode for CBC, which happens to consume the last\n                     * two block (and requires use of the block cipher).\n                     */\n                    template<typename Cipher>\n                    struct basic_padding {\n                        typedef std::size_t size_type;\n\n                        typedef Cipher cipher_type;\n\n                        constexpr static const size_type block_bits = cipher_type::block_bits;\n                        constexpr static const size_type block_words = cipher_type::block_words;\n                        typedef typename cipher_type::block_type block_type;\n                    };\n\n                    /*!\n                     * @tparam Cipher Block cipher used\n                     */\n                    template<typename Cipher>\n                    struct zeros : public basic_padding<Cipher> {\n                        typedef typename basic_padding<Cipher>::size_type size_type;\n\n                        typedef typename basic_padding<Cipher>::cipher_type cipher_type;\n\n                        constexpr static const size_type block_bits = basic_padding<Cipher>::block_bits;\n                        constexpr static const size_type block_words = basic_padding<Cipher>::block_words;\n                        typedef typename basic_padding<Cipher>::block_type block_type;\n\n                        constexpr static const bool always_pad = false;\n\n                        inline static size_type required_output_size(size_type len, size_type block_size) {\n                            if (len) {\n                                const size_type rem = len % block_size;\n                                if (rem) {\n                                    if (std::numeric_limits<size_type>::max() - len < block_size) {\n                                        throw std::overflow_error(\"message length is too long\");\n                                    } else {\n                                        return len - rem + block_size;\n                                    }\n                                }\n                            }\n                            return len;\n                        }\n\n                        inline static block_type pad(const block_type &block, size_type bytes_in_block) {\n                            block_type result = block;\n                            uint8_t *ptr = static_cast<uint8_t *>(&*result.data());\n                            std::memset(ptr + bytes_in_block, 0, block_bits / CHAR_BIT - bytes_in_block);\n\n                            return result;\n                        }\n\n                        inline static block_type unpad(const block_type &block, size_type bytes_in_block) {\n                            ct::poison(block, bytes_in_block);\n                            uint8_t bad_input = 0;\n                            uint8_t seen_one = 0;\n                            size_t pad_pos = bytes_in_block - 1;\n                            size_t i = bytes_in_block;\n\n                            while (i) {\n                                seen_one |= ct::is_equal<uint8_t>(block[i - 1], 0x80);\n                                pad_pos -= ct::select<uint8_t>(~seen_one, 1, 0);\n                                bad_input |= ~ct::is_zero<uint8_t>(block[i - 1]) & ~seen_one;\n                                i--;\n                            }\n                            bad_input |= ~seen_one;\n\n                            ct::conditional_copy_mem(size_t(bad_input), &pad_pos, &bytes_in_block, &pad_pos, 1);\n                            ct::unpoison(block, bytes_in_block);\n                            ct::unpoison(pad_pos);\n                        }\n                    };\n\n                    /*!\n                     * @brief (ISO/IEC 9797-1, padding method 2)\n                     * @tparam Cipher Block cipher used\n                     * 0x80 0x00 0x00 ....\n                     */\n                    template<typename Cipher>\n                    struct one_and_zeros : public basic_padding<Cipher> {\n                        typedef typename basic_padding<Cipher>::size_type size_type;\n\n                        typedef typename basic_padding<Cipher>::cipher_type cipher_type;\n\n                        constexpr static const size_type block_bits = basic_padding<Cipher>::block_bits;\n                        constexpr static const size_type block_words = basic_padding<Cipher>::block_words;\n                        typedef typename basic_padding<Cipher>::block_type block_type;\n\n                        BOOST_STATIC_ASSERT(block_bits > 0);\n\n                        constexpr static const bool always_pad = true;\n\n                        inline static size_type required_output_size(size_type len, size_type block_size) {\n                            if (len) {\n                                const size_type rem = len % block_size;\n                                if (rem) {\n                                    if (std::numeric_limits<size_type>::max() - len < block_size) {\n                                        throw std::overflow_error(\"message length is too long\");\n                                    } else {\n                                        return len - rem + block_size;\n                                    }\n                                }\n                            }\n                            return len + block_size;\n                        }\n\n                        inline static block_type pad(const block_type &block, size_type bytes_in_block) {\n                            block_type result = block;\n                            uint8_t *ptr = static_cast<uint8_t *>(result);\n                            ptr += bytes_in_block;\n                            *ptr++ = 0x80;\n                            ++bytes_in_block;\n                            std::memset(ptr, 0, block_bits / CHAR_BIT - bytes_in_block);\n                            return result;\n                        }\n                    };\n\n                    /*!\n                     * @brief\n                     * @tparam Cipher Block cipher used\n                     */\n                    template<typename Cipher>\n                    struct trailing_bit : public basic_padding<Cipher> {\n                        typedef typename basic_padding<Cipher>::size_type size_type;\n\n                        typedef typename basic_padding<Cipher>::cipher_type cipher_type;\n\n                        constexpr static const size_type block_bits = basic_padding<Cipher>::block_bits;\n                        constexpr static const size_type block_words = basic_padding<Cipher>::block_words;\n                        typedef typename basic_padding<Cipher>::block_type block_type;\n                    };\n\n                    /*!\n                     * @tparam Cipher Block cipher used\n                     * RFC 2315 (10.3.2)\n                     * Some content-encryption algorithms assume the\n                     * input length is a multiple of k octets, where k > 1, and\n                     * let the application define a method for handling inputs\n                     * whose lengths are not a multiple of k octets. For such\n                     * algorithms, the method shall be to pad the input at the\n                     * trailing end with k - (l mod k) octets all having value k -\n                     * (l mod k), where l is the length of the input. In other\n                     * words, the input is padded at the trailing end with one of\n                     * the following strings:\n                     *\n                     *          01 -- if l mod k = k-1\n                     *         02 02 -- if l mod k = k-2\n                     *                     .\n                     *                     .\n                     *                     .\n                     *       k k ... k k -- if l mod k = 0\n                     *\n                     * The padding can be removed unambiguously since all input is\n                     * padded and no padding string is a suffix of another. This\n                     * padding method is well-defined if and only if k < 256;\n                     * methods for larger k are an open issue for further study.\n                     */\n                    template<typename Cipher>\n                    struct pkcs7 : public basic_padding<Cipher> {\n                        typedef typename basic_padding<Cipher>::size_type size_type;\n\n                        typedef typename basic_padding<Cipher>::cipher_type cipher_type;\n\n                        constexpr static const size_type block_bits = basic_padding<Cipher>::block_bits;\n                        constexpr static const size_type block_words = basic_padding<Cipher>::block_words;\n                        typedef typename basic_padding<Cipher>::block_type block_type;\n\n                        BOOST_STATIC_ASSERT(block_bits > 0 && block_bits < 256);\n\n                        inline static void pad(const block_type &block, size_type bytes_in_block) {\n                            const uint8_t pad_value = static_cast<uint8_t>(block_size - last_byte_pos);\n\n                            for (size_t i = 0; i != pad_value; ++i) {\n                                buffer.push_back(pad_value);\n                            }\n                        }\n\n                        inline static void unpad(const block_type &block, size_type bytes_in_block) {\n                            ct::poison(block, bytes_in_block);\n                            size_t bad_input = 0;\n                            const uint8_t last_byte = block[bytes_in_block - 1];\n\n                            bad_input |= ct::expand_mask<size_t>(last_byte > bytes_in_block);\n\n                            size_t pad_pos = bytes_in_block - last_byte;\n                            size_t i = bytes_in_block - 2;\n                            while (i) {\n                                bad_input |=\n                                    (~ct::is_equal(block[i], last_byte)) & ct::expand_mask<uint8_t>(i >= pad_pos);\n                                --i;\n                            }\n\n                            ct::conditional_copy_mem(bad_input, &pad_pos, &bytes_in_block, &pad_pos, 1);\n                            ct::unpoison(block, bytes_in_block);\n                            ct::unpoison(pad_pos);\n                        }\n                    };\n\n                    /*!\n                     * @brief ESP Padding (RFC 4304)\n                     * @tparam Cipher\n                     */\n                    template<typename Cipher>\n                    struct esp : public basic_padding<Cipher> {\n                        typedef typename basic_padding<Cipher>::size_type size_type;\n\n                        typedef typename basic_padding<Cipher>::cipher_type cipher_type;\n\n                        constexpr static const size_type block_bits = basic_padding<Cipher>::block_bits;\n                        constexpr static const size_type block_words = basic_padding<Cipher>::block_words;\n                        typedef typename basic_padding<Cipher>::block_type block_type;\n\n                        inline static void pad(const block_type &block, size_type bytes_in_block) {\n                            uint8_t pad_value = 0x01;\n\n                            for (size_t i = last_byte_pos; i < bytes_in_block; ++i) {\n                                buffer.push_back(pad_value++);\n                            }\n                        }\n\n                        inline static void unpad(const block_type &block, size_type size) {\n                            ct::poison(block, size);\n\n                            const size_t last_byte = block[size - 1];\n                            size_t bad_input = 0;\n                            bad_input |= ct::expand_mask<size_t>(last_byte > size);\n\n                            size_t pad_pos = size - last_byte;\n                            size_t i = size - 1;\n                            while (i) {\n                                bad_input |= ~ct::is_equal<uint8_t>(size_t(block[i - 1]), size_t(block[i]) - 1) &\n                                             ct::expand_mask<uint8_t>(i > pad_pos);\n                                --i;\n                            }\n                            ct::conditional_copy_mem(bad_input, &pad_pos, &size, &pad_pos, 1);\n                            ct::unpoison(block, size);\n                            ct::unpoison(pad_pos);\n                        }\n                    };\n\n                    /*!\n                     * @brief ANSI X9.23 Padding\n                     * @tparam Cipher\n                     */\n                    template<typename Cipher>\n                    struct ansi_x923 : public basic_padding<Cipher> {\n                        typedef typename basic_padding<Cipher>::size_type size_type;\n\n                        typedef typename basic_padding<Cipher>::cipher_type cipher_type;\n\n                        constexpr static const size_type block_bits = basic_padding<Cipher>::block_bits;\n                        constexpr static const size_type block_words = basic_padding<Cipher>::block_words;\n                        typedef typename basic_padding<Cipher>::block_type block_type;\n\n                        BOOST_STATIC_ASSERT(block_bits > 0 && block_bits < 256);\n\n                        inline static void pad(const block_type &block, size_type bytes_in_block) {\n                            const uint8_t pad_value = static_cast<uint8_t>(bytes_in_block - last_byte_pos);\n\n                            for (size_t i = last_byte_pos; i < bytes_in_block - 1; ++i) {\n                                buffer.push_back(0);\n                            }\n                            buffer.push_back(pad_value);\n                        }\n\n                        inline static void unpad(const block_type &block, size_type size) {\n                            ct::poison(block, size);\n                            size_t bad_input = 0;\n                            const size_t last_byte = block[size - 1];\n\n                            bad_input |= ct::expand_mask<size_t>(last_byte > size);\n\n                            size_t pad_pos = size - last_byte;\n                            size_t i = size - 2;\n                            while (i) {\n                                bad_input |= (~ct::is_zero(block[i])) & ct::expand_mask<uint8_t>(i >= pad_pos);\n                                --i;\n                            }\n                            ct::conditional_copy_mem(bad_input, &pad_pos, &size, &pad_pos, 1);\n                            ct::unpoison(block, size);\n                            ct::unpoison(pad_pos);\n                        }\n                    };\n                }    // namespace padding\n            }        // namespace modes\n        }            // namespace block\n    }                // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "2240e6d8d7165c419a9df021f952220cadf1344b", "size": 16933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/modes/padding.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/modes/padding.hpp", "max_issues_repo_name": "NilFoundation/crypto3-modes", "max_issues_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:20:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:26:17.000Z", "max_forks_repo_path": "include/nil/crypto3/modes/padding.hpp", "max_forks_repo_name": "NilFoundation/crypto3-modes", "max_forks_repo_head_hexsha": "f21ae3185dcd37ccef31523e40ec0203c201da36", "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": 50.3958333333, "max_line_length": 114, "alphanum_fraction": 0.4670761235, "num_tokens": 2879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.03732688560390975, "lm_q1q2_score": 0.010741476339399807}}
{"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 *      120717    D. Dirkx          Creation of file.\n *      130120    D. Dirkx          Updated with new Julian day + seconds since Julian day input.\n *      130226    K. Kumar          Updated return-type for getCartesianStateFromEphemeris().\n *\n *    References\n *\n *    Notes\n *\n */\n\n#include <stdexcept>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/exception/all.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n\n#include \"Tudat/External/SpiceInterface/spiceEphemeris.h\"\n\nnamespace tudat\n{\n\nnamespace ephemerides\n{\n\n//! Constructor\nSpiceEphemeris::SpiceEphemeris( const std::string& targetBodyName,\n                                const std::string& observerBodyName,\n                                const bool correctForStellarAbberation,\n                                const bool correctForLightTimeAbberation,\n                                const bool convergeLighTimeAbberation,\n                                const std::string& referenceFrameName )\n    : Ephemeris( observerBodyName, referenceFrameName ),\n      targetBodyName_( targetBodyName )\n{\n    // Check consistency of input.\n    if ( correctForLightTimeAbberation == 0 && convergeLighTimeAbberation == 1 )\n    {\n        boost::throw_exception(\n                    boost::enable_error_info(\n                        std::runtime_error(\n                            \"Warning, requested multiple iterations for light time correction, \"\n                            \"but not light time correction itself.\" ) ) );\n    }\n\n    if ( correctForLightTimeAbberation == 0 && correctForStellarAbberation ==  1 )\n    {\n\n        boost::throw_exception(\n                    boost::enable_error_info(\n                        std::runtime_error\n                        ( \"Warning, requested stellar aberration, but not light-time correction, \"\n                          \"this is not supprted by spice.\" ) ) );\n    }\n\n    // Set aberration corrections variable.\n    abberationCorrections_ = \"\";\n    if ( correctForLightTimeAbberation && !convergeLighTimeAbberation )\n    {\n        abberationCorrections_.append( \"LT\" );\n    }\n\n    else if ( correctForLightTimeAbberation && convergeLighTimeAbberation )\n    {\n        abberationCorrections_.append( \"CN\" );\n    }\n\n    else if ( !correctForLightTimeAbberation && !correctForStellarAbberation )\n    {\n        abberationCorrections_.append( \"NONE\" );\n    }\n\n    if ( correctForLightTimeAbberation && correctForStellarAbberation )\n    {\n        abberationCorrections_.append( \"+S\" );\n    }\n}\n\n//! Get Cartesian state from ephemeris.\nbasic_mathematics::Vector6d SpiceEphemeris::getCartesianStateFromEphemeris(\n        const double secondsSinceEpoch, const double julianDayAtEpoch )\n{\n    using namespace basic_astrodynamics;\n\n    // Retrieve body state at given ephemeris time, using settings passed to constructor of this\n    // object.\n\n    // Calculate ephemeris time at which cartesian state is to be determind.\n    const double ephemerisTime = secondsSinceEpoch + ( JULIAN_DAY_ON_J2000 - julianDayAtEpoch ) *\n            physical_constants::JULIAN_DAY;\n\n    // Retrieve Cartesian state from spice.\n    const basic_mathematics::Vector6d cartesianStateAtEpoch =\n            spice_interface::getBodyCartesianStateAtEpoch(\n                targetBodyName_, referenceFrameOrigin_, referenceFrameOrientation_,\n                abberationCorrections_, ephemerisTime );\n\n    return cartesianStateAtEpoch;\n}\n\n} // namespace ephemerides\n} // namespace tudat\n", "meta": {"hexsha": "a2f68659dd54f3a5e9f70d3de1fff142e6479848", "size": 5211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/External/SpiceInterface/spiceEphemeris.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/External/SpiceInterface/spiceEphemeris.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/External/SpiceInterface/spiceEphemeris.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": 40.3953488372, "max_line_length": 99, "alphanum_fraction": 0.6735751295, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284184892007467, "lm_q2_score": 0.040845716347790245, "lm_q1q2_score": 0.010735963605318108}}
{"text": "/**\n * @file\n * @brief Implementation of generic charge propagation module\n * @remarks Based on code from Paul Schuetze\n * @copyright Copyright (c) 2017-2019 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n */\n\n#include \"GenericPropagationModule.hpp\"\n\n#include <cmath>\n#include <limits>\n#include <map>\n#include <memory>\n#include <random>\n#include <sstream>\n#include <string>\n#include <utility>\n\n#include <Eigen/Core>\n\n#include <Math/Point3D.h>\n#include <Math/Vector3D.h>\n#include <TCanvas.h>\n#include <TFile.h>\n#include <TH2F.h>\n#include <TH3F.h>\n#include <TPaveText.h>\n#include <TPolyLine3D.h>\n#include <TPolyMarker3D.h>\n#include <TStyle.h>\n\n#include \"core/config/Configuration.hpp\"\n#include \"core/messenger/Messenger.hpp\"\n#include \"core/utils/file.h\"\n#include \"core/utils/log.h\"\n#include \"core/utils/unit.h\"\n#include \"tools/ROOT.h\"\n#include \"tools/runge_kutta.h\"\n\n#include \"objects/DepositedCharge.hpp\"\n#include \"objects/PropagatedCharge.hpp\"\n\nusing namespace allpix;\n\n/**\n * Besides binding the message and setting defaults for the configuration, the module copies some configuration variables to\n * local copies to speed up computation.\n */\nGenericPropagationModule::GenericPropagationModule(Configuration& config,\n                                                   Messenger* messenger,\n                                                   std::shared_ptr<Detector> detector)\n    : Module(config, detector), messenger_(messenger), detector_(std::move(detector)) {\n    // Save detector model\n    model_ = detector_->getModel();\n\n    // Require deposits message for single detector\n    messenger_->bindSingle(this, &GenericPropagationModule::deposits_message_, MsgFlags::REQUIRED);\n\n    // Seed the random generator with the module seed\n    random_generator_.seed(getRandomSeed());\n\n    // Set default value for config variables\n    config_.setDefault<double>(\"spatial_precision\", Units::get(0.25, \"nm\"));\n    config_.setDefault<double>(\"timestep_start\", Units::get(0.01, \"ns\"));\n    config_.setDefault<double>(\"timestep_min\", Units::get(0.001, \"ns\"));\n    config_.setDefault<double>(\"timestep_max\", Units::get(0.5, \"ns\"));\n    config_.setDefault<double>(\"integration_time\", Units::get(25, \"ns\"));\n    config_.setDefault<unsigned int>(\"charge_per_step\", 10);\n    config_.setDefault<double>(\"temperature\", 293.15);\n\n    config_.setDefault<bool>(\"output_linegraphs\", false);\n    config_.setDefault<bool>(\"output_animations\", false);\n    config_.setDefault<bool>(\"output_plots\",\n                             config_.get<bool>(\"output_linegraphs\") || config_.get<bool>(\"output_animations\"));\n    config_.setDefault<bool>(\"output_animations_color_markers\", false);\n    config_.setDefault<double>(\"output_plots_step\", config_.get<double>(\"timestep_max\"));\n    config_.setDefault<bool>(\"output_plots_use_pixel_units\", false);\n    config_.setDefault<bool>(\"output_plots_align_pixels\", false);\n    config_.setDefault<double>(\"output_plots_theta\", 0.0f);\n    config_.setDefault<double>(\"output_plots_phi\", 0.0f);\n    config_.setDefault<bool>(\"output_plots_lines_at_implants\", false);\n\n    // Set defaults for charge carrier propagation:\n    config_.setDefault<bool>(\"propagate_electrons\", true);\n    config_.setDefault<bool>(\"propagate_holes\", false);\n    if(!config_.get<bool>(\"propagate_electrons\") && !config_.get<bool>(\"propagate_holes\")) {\n        throw InvalidValueError(\n            config_,\n            \"propagate_electrons\",\n            \"No charge carriers selected for propagation, enable 'propagate_electrons' or 'propagate_holes'.\");\n    }\n\n    config_.setDefault<bool>(\"ignore_magnetic_field\", false);\n\n    // Copy some variables from configuration to avoid lookups:\n    temperature_ = config_.get<double>(\"temperature\");\n    timestep_min_ = config_.get<double>(\"timestep_min\");\n    timestep_max_ = config_.get<double>(\"timestep_max\");\n    timestep_start_ = config_.get<double>(\"timestep_start\");\n    integration_time_ = config_.get<double>(\"integration_time\");\n    target_spatial_precision_ = config_.get<double>(\"spatial_precision\");\n    output_plots_ = config_.get<bool>(\"output_plots\");\n    output_linegraphs_ = config_.get<bool>(\"output_linegraphs\");\n    output_animations_ = config_.get<bool>(\"output_animations\");\n    output_plots_step_ = config_.get<double>(\"output_plots_step\");\n    output_plots_lines_at_implants_ = config_.get<bool>(\"output_plots_lines_at_implants\");\n\n    // Enable parallelization of this module if multithreading is enabled and no per-event output plots are requested:\n    if(!(output_animations_ || output_linegraphs_)) {\n        enable_parallelization();\n    }\n\n    // Parameterization variables from https://doi.org/10.1016/0038-1101(77)90054-5 (section 5.2)\n    electron_Vm_ = Units::get(1.53e9 * std::pow(temperature_, -0.87), \"cm/s\");\n    electron_Ec_ = Units::get(1.01 * std::pow(temperature_, 1.55), \"V/cm\");\n    electron_Beta_ = 2.57e-2 * std::pow(temperature_, 0.66);\n\n    hole_Vm_ = Units::get(1.62e8 * std::pow(temperature_, -0.52), \"cm/s\");\n    hole_Ec_ = Units::get(1.24 * std::pow(temperature_, 1.68), \"V/cm\");\n    hole_Beta_ = 0.46 * std::pow(temperature_, 0.17);\n\n    boltzmann_kT_ = Units::get(8.6173e-5, \"eV/K\") * temperature_;\n\n    // Parameter for charge transport in magnetic field (approximated from graphs:\n    // http://www.ioffe.ru/SVA/NSM/Semicond/Si/electric.html) FIXME\n    electron_Hall_ = 1.15;\n    hole_Hall_ = 0.9;\n}\n\nvoid GenericPropagationModule::create_output_plots(unsigned int event_num) {\n    LOG(TRACE) << \"Writing output plots\";\n\n    // Convert to pixel units if necessary\n    if(config_.get<bool>(\"output_plots_use_pixel_units\")) {\n        for(auto& deposit_points : output_plot_points_) {\n            for(auto& point : deposit_points.second) {\n                point.SetX((point.x() / model_->getPixelSize().x()) + 1);\n                point.SetY((point.y() / model_->getPixelSize().y()) + 1);\n            }\n        }\n    }\n\n    // Calculate the axis limits\n    double minX = FLT_MAX, maxX = FLT_MIN;\n    double minY = FLT_MAX, maxY = FLT_MIN;\n    unsigned long tot_point_cnt = 0;\n    double start_time = std::numeric_limits<double>::max();\n    unsigned int total_charge = 0;\n    unsigned int max_charge = 0;\n    for(auto& deposit_points : output_plot_points_) {\n        for(auto& point : deposit_points.second) {\n            minX = std::min(minX, point.x());\n            maxX = std::max(maxX, point.x());\n\n            minY = std::min(minY, point.y());\n            maxY = std::max(maxY, point.y());\n        }\n        start_time = std::min(start_time, deposit_points.first.getEventTime());\n        total_charge += deposit_points.first.getCharge();\n        max_charge = std::max(max_charge, deposit_points.first.getCharge());\n\n        tot_point_cnt += deposit_points.second.size();\n    }\n\n    // Compute frame axis sizes if equal scaling is requested\n    if(config_.get<bool>(\"output_plots_use_equal_scaling\", true)) {\n        double centerX = (minX + maxX) / 2.0;\n        double centerY = (minY + maxY) / 2.0;\n        if(config_.get<bool>(\"output_plots_use_pixel_units\")) {\n            minX = centerX - model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;\n            maxX = centerX + model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;\n\n            minY = centerY - model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;\n            maxY = centerY + model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;\n        } else {\n            minX = centerX - model_->getSensorSize().z() / 2.0;\n            maxX = centerX + model_->getSensorSize().z() / 2.0;\n\n            minY = centerY - model_->getSensorSize().z() / 2.0;\n            maxY = centerY + model_->getSensorSize().z() / 2.0;\n        }\n    }\n\n    // Align on pixels if requested\n    if(config_.get<bool>(\"output_plots_align_pixels\")) {\n        if(config_.get<bool>(\"output_plots_use_pixel_units\")) {\n            minX = std::floor(minX - 0.5) + 0.5;\n            minY = std::floor(minY + 0.5) - 0.5;\n            maxX = std::ceil(maxX - 0.5) + 0.5;\n            maxY = std::ceil(maxY + 0.5) - 0.5;\n        } else {\n            double div;\n            div = minX / model_->getPixelSize().x();\n            minX = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().x();\n            div = minY / model_->getPixelSize().y();\n            minY = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().y();\n            div = maxX / model_->getPixelSize().x();\n            maxX = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().x();\n            div = maxY / model_->getPixelSize().y();\n            maxY = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().y();\n        }\n    }\n\n    // Use a histogram to create the underlying frame\n    auto* histogram_frame = new TH3F((\"frame_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                     \"\",\n                                     10,\n                                     minX,\n                                     maxX,\n                                     10,\n                                     minY,\n                                     maxY,\n                                     10,\n                                     model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,\n                                     model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0);\n    histogram_frame->SetDirectory(getROOTDirectory());\n\n    // Create the canvas for the line plot and set orientation\n    auto canvas = std::make_unique<TCanvas>((\"line_plot_\" + std::to_string(event_num)).c_str(),\n                                            (\"Propagation of charge for event \" + std::to_string(event_num)).c_str(),\n                                            1280,\n                                            1024);\n    canvas->cd();\n    canvas->SetTheta(config_.get<float>(\"output_plots_theta\") * 180.0f / ROOT::Math::Pi());\n    canvas->SetPhi(config_.get<float>(\"output_plots_phi\") * 180.0f / ROOT::Math::Pi());\n\n    // Draw the frame on the canvas\n    histogram_frame->GetXaxis()->SetTitle(\n        (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n    histogram_frame->GetYaxis()->SetTitle(\n        (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n    histogram_frame->GetZaxis()->SetTitle(\"z (mm)\");\n    histogram_frame->Draw();\n\n    // Loop over all point sets created during propagation\n    // The vector of unique_pointers is required in order not to delete the objects before the canvas is drawn.\n    std::vector<std::unique_ptr<TPolyLine3D>> lines;\n    short current_color = 1;\n    for(auto& deposit_points : output_plot_points_) {\n        auto line = std::make_unique<TPolyLine3D>();\n        for(auto& point : deposit_points.second) {\n            line->SetNextPoint(point.x(), point.y(), point.z());\n        }\n        // Plot all lines with at least three points with different color\n        if(line->GetN() >= 3) {\n            EColor plot_color = (deposit_points.first.getType() == CarrierType::ELECTRON ? EColor::kAzure : EColor::kOrange);\n            current_color = static_cast<short int>(plot_color - 9 + (static_cast<int>(current_color) + 1) % 19);\n            line->SetLineColor(current_color);\n            line->Draw(\"same\");\n        }\n        lines.push_back(std::move(line));\n    }\n\n    // Draw and write canvas to module output file, then clear the stored lines\n    canvas->Draw();\n    getROOTDirectory()->WriteTObject(canvas.get());\n    lines.clear();\n\n    // Create canvas for GIF animition of process\n    canvas = std::make_unique<TCanvas>((\"animation_\" + std::to_string(event_num)).c_str(),\n                                       (\"Propagation of charge for event \" + std::to_string(event_num)).c_str(),\n                                       1280,\n                                       1024);\n    canvas->cd();\n\n    // Change axis labels if close to zero or PI as they behave different here\n    if(std::fabs(config_.get<double>(\"output_plots_theta\") / (ROOT::Math::Pi() / 2.0) -\n                 std::round(config_.get<double>(\"output_plots_theta\") / (ROOT::Math::Pi() / 2.0))) < 1e-6 ||\n       std::fabs(config_.get<double>(\"output_plots_phi\") / (ROOT::Math::Pi() / 2.0) -\n                 std::round(config_.get<double>(\"output_plots_phi\") / (ROOT::Math::Pi() / 2.0))) < 1e-6) {\n        histogram_frame->GetXaxis()->SetLabelOffset(-0.1f);\n        histogram_frame->GetYaxis()->SetLabelOffset(-0.075f);\n    } else {\n        histogram_frame->GetXaxis()->SetTitleOffset(2.0f);\n        histogram_frame->GetYaxis()->SetTitleOffset(2.0f);\n    }\n\n    // Draw frame on canvas\n    histogram_frame->Draw();\n\n    if(output_animations_) {\n        // Create the contour histogram\n        std::vector<std::string> file_name_contour;\n        std::vector<TH2F*> histogram_contour;\n        file_name_contour.push_back(createOutputFile(\"contourX\" + std::to_string(event_num) + \".gif\"));\n        histogram_contour.push_back(new TH2F((\"contourX_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                             \"\",\n                                             100,\n                                             minY,\n                                             maxY,\n                                             100,\n                                             model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,\n                                             model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));\n        histogram_contour.back()->SetDirectory(getROOTDirectory());\n        file_name_contour.push_back(createOutputFile(\"contourY\" + std::to_string(event_num) + \".gif\"));\n        histogram_contour.push_back(new TH2F((\"contourY_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                             \"\",\n                                             100,\n                                             minX,\n                                             maxX,\n                                             100,\n                                             model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,\n                                             model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));\n        histogram_contour.back()->SetDirectory(getROOTDirectory());\n        file_name_contour.push_back(createOutputFile(\"contourZ\" + std::to_string(event_num) + \".gif\"));\n        histogram_contour.push_back(new TH2F((\"contourZ_\" + getUniqueName() + \"_\" + std::to_string(event_num)).c_str(),\n                                             \"\",\n                                             100,\n                                             minX,\n                                             maxX,\n                                             100,\n                                             minY,\n                                             maxY));\n        histogram_contour.back()->SetDirectory(getROOTDirectory());\n\n        // Create file and disable statistics for histogram\n        std::string file_name_anim = createOutputFile(\"animation\" + std::to_string(event_num) + \".gif\");\n        for(size_t i = 0; i < 3; ++i) {\n            histogram_contour[i]->SetStats(false);\n        }\n\n        // Remove temporary created files\n        remove(file_name_anim.c_str());\n        for(size_t i = 0; i < 3; ++i) {\n            remove(file_name_contour[i].c_str());\n        }\n\n        // Create color table\n        TColor* colors[80];\n        for(int i = 20; i < 100; ++i) {\n            auto color_idx = TColor::GetFreeColorIndex();\n            colors[i - 20] = new TColor(color_idx,\n                                        static_cast<float>(i) / 100.0f - 0.2f,\n                                        static_cast<float>(i) / 100.0f - 0.2f,\n                                        static_cast<float>(i) / 100.0f - 0.2f);\n        }\n\n        // Create animation of moving charges\n        auto animation_time = static_cast<unsigned int>(\n            std::round((Units::convert(config_.get<long double>(\"output_plots_step\"), \"ms\") / 10.0) *\n                       config_.get<long double>(\"output_animations_time_scaling\", 1e9)));\n        unsigned long plot_idx = 0;\n        unsigned int point_cnt = 0;\n        LOG_PROGRESS(INFO, getUniqueName() + \"_OUTPUT_PLOTS\") << \"Written 0 of \" << tot_point_cnt << \" points for animation\";\n        while(point_cnt < tot_point_cnt) {\n            std::vector<std::unique_ptr<TPolyMarker3D>> markers;\n            unsigned long min_idx_diff = std::numeric_limits<unsigned long>::max();\n\n            // Reset the canvas\n            canvas->Clear();\n            canvas->SetTheta(config_.get<float>(\"output_plots_theta\") * 180.0f / ROOT::Math::Pi());\n            canvas->SetPhi(config_.get<float>(\"output_plots_phi\") * 180.0f / ROOT::Math::Pi());\n            canvas->Draw();\n\n            // Reset the histogram frame\n            histogram_frame->SetTitle(\"Charge propagation in sensor\");\n            histogram_frame->GetXaxis()->SetTitle(\n                (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n            histogram_frame->GetYaxis()->SetTitle(\n                (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\")).c_str());\n            histogram_frame->GetZaxis()->SetTitle(\"z (mm)\");\n            histogram_frame->Draw();\n\n            auto text = std::make_unique<TPaveText>(-0.75, -0.75, -0.60, -0.65);\n            auto time_ns = Units::convert(plot_idx * config_.get<long double>(\"output_plots_step\"), \"ns\");\n            std::stringstream sstr;\n            sstr << std::fixed << std::setprecision(2) << time_ns << \"ns\";\n            auto time_str = std::string(8 - sstr.str().size(), ' ');\n            time_str += sstr.str();\n            text->AddText(time_str.c_str());\n            text->Draw();\n\n            // Plot all the required points\n            for(auto& deposit_points : output_plot_points_) {\n                auto points = deposit_points.second;\n\n                auto diff = static_cast<unsigned long>(std::round((deposit_points.first.getEventTime() - start_time) /\n                                                                  config_.get<long double>(\"output_plots_step\")));\n                if(static_cast<long>(plot_idx) - static_cast<long>(diff) < 0) {\n                    min_idx_diff = std::min(min_idx_diff, diff - plot_idx);\n                    continue;\n                }\n                auto idx = plot_idx - diff;\n                if(idx >= points.size()) {\n                    continue;\n                }\n                min_idx_diff = 0;\n\n                auto marker = std::make_unique<TPolyMarker3D>();\n                marker->SetMarkerStyle(kFullCircle);\n                marker->SetMarkerSize(static_cast<float>(deposit_points.first.getCharge() *\n                                                         config_.get<double>(\"output_animations_marker_size\", 1)) /\n                                      static_cast<float>(max_charge));\n                auto initial_z_perc = static_cast<int>(\n                    ((points[0].z() + model_->getSensorSize().z() / 2.0) / model_->getSensorSize().z()) * 80);\n                initial_z_perc = std::max(std::min(79, initial_z_perc), 0);\n                if(config_.get<bool>(\"output_animations_color_markers\")) {\n                    marker->SetMarkerColor(static_cast<Color_t>(colors[initial_z_perc]->GetNumber()));\n                }\n                marker->SetNextPoint(points[idx].x(), points[idx].y(), points[idx].z());\n                marker->Draw();\n                markers.push_back(std::move(marker));\n\n                histogram_contour[0]->Fill(points[idx].y(), points[idx].z(), deposit_points.first.getCharge());\n                histogram_contour[1]->Fill(points[idx].x(), points[idx].z(), deposit_points.first.getCharge());\n                histogram_contour[2]->Fill(points[idx].x(), points[idx].y(), deposit_points.first.getCharge());\n                ++point_cnt;\n            }\n\n            // Create a step in the animation\n            if(min_idx_diff != 0) {\n                canvas->Print((file_name_anim + \"+100\").c_str());\n                plot_idx += min_idx_diff;\n            } else {\n                // print animation\n                if(point_cnt < tot_point_cnt - 1) {\n                    canvas->Print((file_name_anim + \"+\" + std::to_string(animation_time)).c_str());\n                } else {\n                    canvas->Print((file_name_anim + \"++100\").c_str());\n                }\n\n                // Draw and print contour histograms\n                for(size_t i = 0; i < 3; ++i) {\n                    canvas->Clear();\n                    canvas->SetTitle((std::string(\"Contour of charge propagation projected on the \") +\n                                      static_cast<char>('X' + i) + \"-axis\")\n                                         .c_str());\n                    switch(i) {\n                    case 0 /* x */:\n                        histogram_contour[i]->GetXaxis()->SetTitle(\n                            (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        histogram_contour[i]->GetYaxis()->SetTitle(\"z (mm)\");\n                        break;\n                    case 1 /* y */:\n                        histogram_contour[i]->GetXaxis()->SetTitle(\n                            (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        histogram_contour[i]->GetYaxis()->SetTitle(\"z (mm)\");\n                        break;\n                    case 2 /* z */:\n                        histogram_contour[i]->GetXaxis()->SetTitle(\n                            (std::string(\"x \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        histogram_contour[i]->GetYaxis()->SetTitle(\n                            (std::string(\"y \") + (config_.get<bool>(\"output_plots_use_pixel_units\") ? \"(pixels)\" : \"(mm)\"))\n                                .c_str());\n                        break;\n                    default:;\n                    }\n                    histogram_contour[i]->SetMinimum(1);\n                    histogram_contour[i]->SetMaximum(total_charge /\n                                                     config_.get<double>(\"output_animations_contour_max_scaling\", 10));\n                    histogram_contour[i]->Draw(\"CONTZ 0\");\n                    if(point_cnt < tot_point_cnt - 1) {\n                        canvas->Print((file_name_contour[i] + \"+\" + std::to_string(animation_time)).c_str());\n                    } else {\n                        canvas->Print((file_name_contour[i] + \"++100\").c_str());\n                    }\n                    histogram_contour[i]->Reset();\n                }\n                ++plot_idx;\n            }\n            markers.clear();\n\n            LOG_PROGRESS(INFO, getUniqueName() + \"_OUTPUT_PLOTS\")\n                << \"Written \" << point_cnt << \" of \" << tot_point_cnt << \" points for animation\";\n        }\n    }\n    output_plot_points_.clear();\n}\n\nvoid GenericPropagationModule::init() {\n\n    auto detector = getDetector();\n\n    // Check for electric field and output warning for slow propagation if not defined\n    if(!detector->hasElectricField()) {\n        LOG(WARNING) << \"This detector does not have an electric field.\";\n    }\n\n    // For linear fields we can in addition check if the correct carriers are propagated\n    if(detector->getElectricFieldType() == FieldType::LINEAR) {\n        auto model = detector_->getModel();\n        auto probe_point = ROOT::Math::XYZPoint(model->getSensorCenter().x(),\n                                                model->getSensorCenter().y(),\n                                                model->getSensorCenter().z() + model->getSensorSize().z() / 2.01);\n\n        // Get the field close to the implants and check its sign:\n        auto efield = detector->getElectricField(probe_point);\n        auto direction = std::signbit(efield.z());\n        // Compare with propagated carrier type:\n        if(direction && !config_.get<bool>(\"propagate_electrons\")) {\n            LOG(WARNING) << \"Electric field indicates electron collection at implants, but electrons are not propagated!\";\n        }\n        if(!direction && !config_.get<bool>(\"propagate_holes\")) {\n            LOG(WARNING) << \"Electric field indicates hole collection at implants, but holes are not propagated!\";\n        }\n    }\n\n    // Check for magnetic field\n    has_magnetic_field_ = detector->hasMagneticField();\n    if(has_magnetic_field_) {\n        if(config_.get<bool>(\"ignore_magnetic_field\")) {\n            has_magnetic_field_ = false;\n            LOG(WARNING) << \"A magnetic field is switched on, but is set to be ignored for this module.\";\n        } else {\n            LOG(DEBUG) << \"This detector sees a magnetic field.\";\n            magnetic_field_ = detector_->getMagneticField();\n        }\n    }\n\n    if(output_plots_) {\n        step_length_histo_ = new TH1D(\"step_length_histo\",\n                                      \"Step length;length [#mum];integration steps\",\n                                      100,\n                                      0,\n                                      static_cast<double>(Units::convert(0.25 * model_->getSensorSize().z(), \"um\")));\n\n        drift_time_histo_ = new TH1D(\"drift_time_histo\",\n                                     \"Drift time;Drift time [ns];charge carriers\",\n                                     static_cast<int>(Units::convert(integration_time_, \"ns\") * 5),\n                                     0,\n                                     static_cast<double>(Units::convert(integration_time_, \"ns\")));\n\n        uncertainty_histo_ =\n            new TH1D(\"uncertainty_histo\",\n                     \"Position uncertainty;uncertainty [nm];integration steps\",\n                     100,\n                     0,\n                     static_cast<double>(4 * Units::convert(config_.get<double>(\"spatial_precision\"), \"nm\")));\n\n        group_size_histo_ = new TH1D(\"group_size_histo\",\n                                     \"Charge carrier group size;group size;number of groups trasnported\",\n                                     config_.get<int>(\"charge_per_step\") - 1,\n                                     1,\n                                     static_cast<double>(config_.get<unsigned int>(\"charge_per_step\")));\n    }\n}\n\nvoid GenericPropagationModule::run(unsigned int event_num) {\n\n    // Create vector of propagated charges to output\n    std::vector<PropagatedCharge> propagated_charges;\n\n    // Loop over all deposits for propagation\n    LOG(TRACE) << \"Propagating charges in sensor\";\n    unsigned int propagated_charges_count = 0;\n    unsigned int step_count = 0;\n    long double total_time = 0;\n    for(auto& deposit : deposits_message_->getData()) {\n\n        if((deposit.getType() == CarrierType::ELECTRON && !config_.get<bool>(\"propagate_electrons\")) ||\n           (deposit.getType() == CarrierType::HOLE && !config_.get<bool>(\"propagate_holes\"))) {\n            LOG(DEBUG) << \"Skipping charge carriers (\" << deposit.getType() << \") on \"\n                       << Units::display(deposit.getLocalPosition(), {\"mm\", \"um\"});\n            continue;\n        }\n\n        // Loop over all charges in the deposit\n        unsigned int charges_remaining = deposit.getCharge();\n\n        LOG(DEBUG) << \"Set of charge carriers (\" << deposit.getType() << \") on \"\n                   << Units::display(deposit.getLocalPosition(), {\"mm\", \"um\"});\n\n        auto charge_per_step = config_.get<unsigned int>(\"charge_per_step\");\n        while(charges_remaining > 0) {\n            // Define number of charges to be propagated and remove charges of this step from the total\n            if(charge_per_step > charges_remaining) {\n                charge_per_step = charges_remaining;\n            }\n            charges_remaining -= charge_per_step;\n\n            // Get position and propagate through sensor\n            auto position = deposit.getLocalPosition();\n\n            // Add point of deposition to the output plots if requested\n            if(output_linegraphs_) {\n                auto global_position = detector_->getGlobalPosition(position);\n                output_plot_points_.emplace_back(\n                    PropagatedCharge(position, global_position, deposit.getType(), charge_per_step, deposit.getEventTime()),\n                    std::vector<ROOT::Math::XYZPoint>());\n            }\n\n            // Propagate a single charge deposit\n            auto prop_pair = propagate(position, deposit.getType());\n            position = prop_pair.first;\n\n            LOG(DEBUG) << \" Propagated \" << charge_per_step << \" to \" << Units::display(position, {\"mm\", \"um\"}) << \" in \"\n                       << Units::display(prop_pair.second, \"ns\") << \" time\";\n\n            // Create a new propagated charge and add it to the list\n            auto global_position = detector_->getGlobalPosition(position);\n            PropagatedCharge propagated_charge(position,\n                                               global_position,\n                                               deposit.getType(),\n                                               charge_per_step,\n                                               deposit.getEventTime() + prop_pair.second,\n                                               &deposit);\n\n            propagated_charges.push_back(std::move(propagated_charge));\n\n            // Update statistical information\n            ++step_count;\n            propagated_charges_count += charge_per_step;\n            total_time += charge_per_step * prop_pair.second;\n            if(output_plots_) {\n                drift_time_histo_->Fill(static_cast<double>(Units::convert(prop_pair.second, \"ns\")), charge_per_step);\n                group_size_histo_->Fill(charge_per_step);\n            }\n        }\n    }\n\n    // Output plots if required\n    if(output_linegraphs_) {\n        create_output_plots(event_num);\n    }\n\n    // Write summary and update statistics\n    long double average_time = total_time / std::max(1u, propagated_charges_count);\n    LOG(INFO) << \"Propagated \" << propagated_charges_count << \" charges in \" << step_count << \" steps in average time of \"\n              << Units::display(average_time, \"ns\");\n    total_propagated_charges_ += propagated_charges_count;\n    total_steps_ += step_count;\n    total_time_ += total_time;\n\n    // Create a new message with propagated charges\n    auto propagated_charge_message = std::make_shared<PropagatedChargeMessage>(std::move(propagated_charges), detector_);\n\n    // Dispatch the message with propagated charges\n    messenger_->dispatchMessage(this, propagated_charge_message);\n}\n\n/**\n * Propagation is simulated using a parameterization for the electron mobility. This is used to calculate the electron\n * velocity at every point with help of the electric field map of the detector. An Runge-Kutta integration is applied in\n * multiple steps, adding a random diffusion to the propagating charge every step.\n */\nstd::pair<ROOT::Math::XYZPoint, double> GenericPropagationModule::propagate(const ROOT::Math::XYZPoint& pos,\n                                                                            const CarrierType& type) {\n    // Create a runge kutta solver using the electric field as step function\n    Eigen::Vector3d position(pos.x(), pos.y(), pos.z());\n\n    // Define a lambda function to compute the carrier mobility\n    // NOTE This function is typically the most frequently executed part of the framework and therefore the bottleneck\n    auto carrier_mobility = [&](double efield_mag) {\n        // Compute carrier mobility from constants and electric field magnitude\n        double numerator, denominator;\n        if(type == CarrierType::ELECTRON) {\n            numerator = electron_Vm_ / electron_Ec_;\n            denominator = std::pow(1. + std::pow(efield_mag / electron_Ec_, electron_Beta_), 1.0 / electron_Beta_);\n        } else {\n            numerator = hole_Vm_ / hole_Ec_;\n            denominator = std::pow(1. + std::pow(efield_mag / hole_Ec_, hole_Beta_), 1.0 / hole_Beta_);\n        }\n        return numerator / denominator;\n    };\n\n    // Define a function to compute the diffusion\n    auto carrier_diffusion = [&](double efield_mag, double timestep) -> Eigen::Vector3d {\n        double diffusion_constant = boltzmann_kT_ * carrier_mobility(efield_mag);\n        double diffusion_std_dev = std::sqrt(2. * diffusion_constant * timestep);\n\n        // Compute the independent diffusion in three\n        std::normal_distribution<double> gauss_distribution(0, diffusion_std_dev);\n        Eigen::Vector3d diffusion;\n        for(int i = 0; i < 3; ++i) {\n            diffusion[i] = gauss_distribution(random_generator_);\n        }\n        return diffusion;\n    };\n\n    // Define lambda functions to compute the charge carrier velocity with or without magnetic field\n    std::function<Eigen::Vector3d(double, Eigen::Vector3d)> carrier_velocity_noB =\n        [&](double, Eigen::Vector3d cur_pos) -> Eigen::Vector3d {\n        auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));\n        Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());\n\n        return static_cast<int>(type) * carrier_mobility(efield.norm()) * efield;\n    };\n\n    std::function<Eigen::Vector3d(double, Eigen::Vector3d)> carrier_velocity_withB =\n        [&](double, Eigen::Vector3d cur_pos) -> Eigen::Vector3d {\n        auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));\n        Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());\n\n        Eigen::Vector3d velocity;\n        Eigen::Vector3d bfield(magnetic_field_.x(), magnetic_field_.y(), magnetic_field_.z());\n\n        auto mob = carrier_mobility(efield.norm());\n        auto exb = efield.cross(bfield);\n\n        Eigen::Vector3d term1;\n        double hallFactor = (type == CarrierType::ELECTRON ? electron_Hall_ : hole_Hall_);\n        term1 = static_cast<int>(type) * mob * hallFactor * exb;\n\n        Eigen::Vector3d term2 = mob * mob * hallFactor * hallFactor * efield.dot(bfield) * bfield;\n\n        auto rnorm = 1 + mob * mob * hallFactor * hallFactor * bfield.dot(bfield);\n        return static_cast<int>(type) * mob * (efield + term1 + term2) / rnorm;\n    };\n\n    // Create the runge kutta solver with an RKF5 tableau, using different velocity calculators depending on the magnetic\n    // field\n    auto runge_kutta = make_runge_kutta(\n        tableau::RK5, (has_magnetic_field_ ? carrier_velocity_withB : carrier_velocity_noB), timestep_start_, position);\n\n    // Continue propagation until the deposit is outside the sensor\n    Eigen::Vector3d last_position = position;\n    double last_time = 0;\n    size_t next_idx = 0;\n    while(detector_->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position)) &&\n          runge_kutta.getTime() < integration_time_) {\n        // Update output plots if necessary (depending on the plot step)\n        if(output_linegraphs_) {\n            auto time_idx = static_cast<size_t>(runge_kutta.getTime() / output_plots_step_);\n            while(next_idx <= time_idx) {\n                output_plot_points_.back().second.push_back(static_cast<ROOT::Math::XYZPoint>(position));\n                next_idx = output_plot_points_.back().second.size();\n            }\n        }\n\n        // Save previous position and time\n        last_position = position;\n        last_time = runge_kutta.getTime();\n\n        // Execute a Runge Kutta step\n        auto step = runge_kutta.step();\n\n        // Get the current result and timestep\n        auto timestep = runge_kutta.getTimeStep();\n        position = runge_kutta.getValue();\n\n        // Get electric field at current position and fall back to empty field if it does not exist\n        auto efield = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(position));\n\n        // Apply diffusion step\n        auto diffusion = carrier_diffusion(std::sqrt(efield.Mag2()), timestep);\n        position += diffusion;\n        runge_kutta.setValue(position);\n\n        // Adapt step size to match target precision\n        double uncertainty = step.error.norm();\n\n        // Update step length histogram\n        if(output_plots_) {\n            step_length_histo_->Fill(static_cast<double>(Units::convert(step.value.norm(), \"um\")));\n            uncertainty_histo_->Fill(static_cast<double>(Units::convert(step.error.norm(), \"nm\")));\n        }\n\n        // Lower timestep when reaching the sensor edge\n        if(std::fabs(model_->getSensorSize().z() / 2.0 - position.z()) < 2 * step.value.z()) {\n            timestep *= 0.75;\n        } else {\n            if(uncertainty > target_spatial_precision_) {\n                timestep *= 0.75;\n            } else if(2 * uncertainty < target_spatial_precision_) {\n                timestep *= 1.5;\n            }\n        }\n        // Limit the timestep to certain minimum and maximum step sizes\n        if(timestep > timestep_max_) {\n            timestep = timestep_max_;\n        } else if(timestep < timestep_min_) {\n            timestep = timestep_min_;\n        }\n        runge_kutta.setTimeStep(timestep);\n    }\n\n    // Find proper final position in the sensor\n    auto time = runge_kutta.getTime();\n    if(!detector_->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position))) {\n        auto check_position = position;\n        check_position.z() = last_position.z();\n        if(position.z() > 0 && detector_->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(check_position))) {\n            // Carrier left sensor on the side of the pixel grid, interpolate end point on surface\n            auto z_cur_border = std::fabs(position.z() - model_->getSensorSize().z() / 2.0);\n            auto z_last_border = std::fabs(model_->getSensorSize().z() / 2.0 - last_position.z());\n            auto z_total = z_cur_border + z_last_border;\n            position = (z_last_border / z_total) * position + (z_cur_border / z_total) * last_position;\n            time = (z_last_border / z_total) * time + (z_cur_border / z_total) * last_time;\n        } else {\n            // Carrier left sensor on any order border, use last position inside instead\n            position = last_position;\n            time = last_time;\n        }\n    }\n\n    // If requested, remove charge drift lines from plots if they did not reach the implant side within the integration time:\n    if(output_linegraphs_ && output_plots_lines_at_implants_) {\n        // If drift time is larger than integration time or the charge carriers have been collected at the backside, remove\n        if(time >= integration_time_ || last_position.z() < -model_->getSensorSize().z() * 0.45) {\n            output_plot_points_.pop_back();\n        }\n    }\n\n    // Return the final position of the propagated charge\n    return std::make_pair(static_cast<ROOT::Math::XYZPoint>(position), time);\n}\n\nvoid GenericPropagationModule::finalize() {\n    if(output_plots_) {\n        step_length_histo_->Write();\n        drift_time_histo_->Write();\n        uncertainty_histo_->Write();\n        group_size_histo_->Write();\n    }\n\n    long double average_time = total_time_ / std::max(1u, total_propagated_charges_);\n    LOG(INFO) << \"Propagated total of \" << total_propagated_charges_ << \" charges in \" << total_steps_\n              << \" steps in average time of \" << Units::display(average_time, \"ns\");\n}\n", "meta": {"hexsha": "c020fbdae1a3215a0f76a73caa30826feb702712", "size": 39961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/GenericPropagation/GenericPropagationModule.cpp", "max_stars_repo_name": "nashadroid/allpix-squared", "max_stars_repo_head_hexsha": "ae3c9b35241b7d301866e1a602443a436bdfb35f", "max_stars_repo_licenses": ["MIT"], "max_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/GenericPropagation/GenericPropagationModule.cpp", "max_issues_repo_name": "nashadroid/allpix-squared", "max_issues_repo_head_hexsha": "ae3c9b35241b7d301866e1a602443a436bdfb35f", "max_issues_repo_licenses": ["MIT"], "max_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/GenericPropagation/GenericPropagationModule.cpp", "max_forks_repo_name": "nashadroid/allpix-squared", "max_forks_repo_head_hexsha": "ae3c9b35241b7d301866e1a602443a436bdfb35f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9718137255, "max_line_length": 125, "alphanum_fraction": 0.5774129777, "num_tokens": 8826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.02405355110167842, "lm_q1q2_score": 0.010716567438381387}}
{"text": "#pragma once\n#include <boost/core/demangle.hpp>\n#include <iomanip>\n\n#include \"basis.hpp\"\n#include \"bilinear_form.hpp\"\nnamespace spacetime {\n\ntemplate <template <typename, typename> class OperatorTime,\n          typename OperatorSpace, typename BasisTimeIn, typename BasisTimeOut>\nBilinearForm<OperatorTime, OperatorSpace, BasisTimeIn, BasisTimeOut>::\n    BilinearForm(DoubleTreeVector<BasisTimeIn, BasisSpace> *vec_in,\n                 DoubleTreeVector<BasisTimeOut, BasisSpace> *vec_out,\n                 bool use_cache, space::OperatorOptions space_opts)\n    : BilinearForm(vec_in, vec_out, GenerateSigma(*vec_in, *vec_out),\n                   GenerateTheta(*vec_in, *vec_out), use_cache, space_opts) {}\n\ntemplate <template <typename, typename> class OperatorTime,\n          typename OperatorSpace, typename BasisTimeIn, typename BasisTimeOut>\nBilinearForm<OperatorTime, OperatorSpace, BasisTimeIn, BasisTimeOut>::\n    BilinearForm(\n        DoubleTreeVector<BasisTimeIn, BasisSpace> *vec_in,\n        DoubleTreeVector<BasisTimeOut, BasisSpace> *vec_out,\n        std::shared_ptr<DoubleTreeVector<BasisTimeIn, BasisSpace>> sigma,\n        std::shared_ptr<DoubleTreeVector<BasisTimeOut, BasisSpace>> theta,\n        bool use_cache, space::OperatorOptions space_opts)\n    : vec_in_(vec_in),\n      vec_out_(vec_out),\n      sigma_(sigma),\n      theta_(theta),\n      use_cache_(use_cache),\n      space_opts_(std::move(space_opts)) {\n  auto time_start = std::chrono::steady_clock::now();\n#ifdef VERBOSE\n  std::cerr << std::left;\n  std::cerr << std::endl\n            << boost::core::demangle(typeid(*this).name()) << std::endl;\n  std::cerr << space_opts << std::endl;\n  std::cerr << \"  vec_in:  #bfs = \" << std::setw(10) << vec_in_->Bfs().size()\n            << \"#container = \" << vec_in_->container().size() << std::endl;\n  std::cerr << \"  vec_out: #bfs = \" << std::setw(10) << vec_out_->Bfs().size()\n            << \"#container = \" << vec_out_->container().size() << std::endl;\n  std::cerr << \"  sigma:   #bfs = \" << std::setw(10) << sigma_->Bfs().size()\n            << \"#container = \" << sigma_->container().size() << std::endl;\n  std::cerr << \"  theta:   #bfs = \" << std::setw(10) << theta_->Bfs().size()\n            << \"#container = \" << theta_->container().size() << std::endl;\n  std::cerr << std::right;\n#endif\n\n  // If use cache, cache the bil forms here.\n  if (use_cache_) {\n    // Calculate R_sigma(Id x A_1)I_Lambda.\n    for (auto psi_in_labda : sigma_->Project_0()->Bfs()) {\n      auto fiber_in = vec_in_->Fiber_1(psi_in_labda->node());\n      auto fiber_out = psi_in_labda->FrozenOtherAxis();\n      if (fiber_out->children().empty()) continue;\n      bil_space_low_.emplace_back(fiber_in, fiber_out, space_opts_);\n    }\n\n    // Calculate R_Lambda(L_0 x Id)I_Sigma.\n    for (auto psi_out_labda : vec_out_->Project_1()->Bfs()) {\n      auto fiber_in = sigma_->Fiber_0(psi_out_labda->node());\n      if (fiber_in->children().empty()) continue;\n      auto fiber_out = psi_out_labda->FrozenOtherAxis();\n      bil_time_low_.emplace_back(fiber_in, fiber_out);\n    }\n\n    // In case we have theta == sigma and vec_out == vec_in, then\n    // we *could* reuse the above derived bilforms.\n\n    // Calculate R_Theta(U_1 x Id)I_Lambda.\n    for (auto psi_in_labda : theta_->Project_1()->Bfs()) {\n      auto fiber_in = vec_in_->Fiber_0(psi_in_labda->node());\n      auto fiber_out = psi_in_labda->FrozenOtherAxis();\n      if (fiber_out->children().empty()) continue;\n      bil_time_upp_.emplace_back(fiber_in, fiber_out);\n    }\n\n    // Calculate R_Lambda(Id x A2)I_Theta.\n    for (auto psi_out_labda : vec_out_->Project_0()->Bfs()) {\n      auto fiber_in = theta_->Fiber_1(psi_out_labda->node());\n      if (fiber_in->children().empty()) continue;\n      auto fiber_out = psi_out_labda->FrozenOtherAxis();\n      bil_space_upp_.emplace_back(fiber_in, fiber_out, space_opts_);\n    }\n  }\n  time_construct_ = std::chrono::duration<double>(\n      std::chrono::steady_clock::now() - time_start);\n}\n\ntemplate <template <typename, typename> class OperatorTime,\n          typename OperatorSpace, typename BasisTimeIn, typename BasisTimeOut>\nEigen::VectorXd BilinearForm<OperatorTime, OperatorSpace, BasisTimeIn,\n                             BasisTimeOut>::Apply(const Eigen::VectorXd &v_in) {\n  if (v_in.squaredNorm() == 0)\n    return Eigen::VectorXd::Zero(vec_out_->container().size());\n\n  // Debug information.\n  auto time_start = std::chrono::steady_clock::now();\n  num_apply_++;\n\n  Eigen::VectorXd v_lower;\n\n  // Store the input in the double tree.\n  vec_in_->FromVectorContainer(v_in);\n\n  // Check whether we have to recalculate the bilinear forms.\n  if (!use_cache_) {\n    // Calculate R_sigma(Id x A_1)I_Lambda.\n    for (auto psi_in_labda : sigma_->Project_0()->Bfs()) {\n      auto fiber_in = vec_in_->Fiber_1(psi_in_labda->node());\n      auto fiber_out = psi_in_labda->FrozenOtherAxis();\n      if (fiber_out->children().empty()) continue;\n      auto bil_form = space::CreateBilinearForm<OperatorSpace>(\n          fiber_in, fiber_out, space_opts_);\n      bil_form.Apply();\n    }\n\n    // Calculate R_Lambda(L_0 x Id)I_Sigma.\n    for (auto psi_out_labda : vec_out_->Project_1()->Bfs()) {\n      auto fiber_in = sigma_->Fiber_0(psi_out_labda->node());\n      if (fiber_in->children().empty()) continue;\n      auto fiber_out = psi_out_labda->FrozenOtherAxis();\n      auto bil_form =\n          Time::CreateBilinearForm<OperatorTime>(fiber_in, fiber_out);\n      bil_form.ApplyLow();\n    }\n\n    // Store the lower output.\n    v_lower = vec_out_->ToVectorContainer();\n\n    // Reset the input, if necessary.\n    if (vec_in_ == sigma_.get() ||\n        static_cast<void *>(vec_in_) == static_cast<void *>(vec_out_))\n      vec_in_->FromVectorContainer(v_in);\n\n    // Calculate R_Theta(U_1 x Id)I_Lambda.\n    for (auto psi_in_labda : theta_->Project_1()->Bfs()) {\n      auto fiber_in = vec_in_->Fiber_0(psi_in_labda->node());\n      auto fiber_out = psi_in_labda->FrozenOtherAxis();\n      if (fiber_out->children().empty()) continue;\n      auto bil_form =\n          Time::CreateBilinearForm<OperatorTime>(fiber_in, fiber_out);\n      bil_form.ApplyUpp();\n    }\n\n    // Calculate R_Lambda(Id x A2)I_Theta.\n    for (auto psi_out_labda : vec_out_->Project_0()->Bfs()) {\n      auto fiber_in = theta_->Fiber_1(psi_out_labda->node());\n      if (fiber_in->children().empty()) continue;\n      auto fiber_out = psi_out_labda->FrozenOtherAxis();\n      auto bil_form = space::CreateBilinearForm<OperatorSpace>(\n          fiber_in, fiber_out, space_opts_);\n      bil_form.Apply();\n    }\n  } else {\n    // Apply the lower part using cached bil forms.\n    for (auto &bil_form : bil_space_low_) bil_form.Apply();\n    for (auto &bil_form : bil_time_low_) bil_form.ApplyLow();\n\n    // Store the lower output.\n    v_lower = vec_out_->ToVectorContainer();\n\n    // Reset the input, if necessary.\n    if (vec_in_ == sigma_.get() ||\n        static_cast<void *>(vec_in_) == static_cast<void *>(vec_out_))\n      vec_in_->FromVectorContainer(v_in);\n\n    // Apply the upper part using cached bil forms.\n    for (auto &bil_form : bil_time_upp_) bil_form.ApplyUpp();\n    for (auto &bil_form : bil_space_upp_) bil_form.Apply();\n  }\n\n  // Return vectorized output.\n  Eigen::VectorXd result = v_lower + vec_out_->ToVectorContainer();\n\n  // Store timing results.\n  time_apply_ += std::chrono::duration<double>(\n      std::chrono::steady_clock::now() - time_start);\n\n  return result;\n}\n\ntemplate <template <typename, typename> class OperatorTime,\n          typename OperatorSpace, typename BasisTimeIn, typename BasisTimeOut>\nEigen::VectorXd\nBilinearForm<OperatorTime, OperatorSpace, BasisTimeIn,\n             BasisTimeOut>::ApplyTranspose(const Eigen::VectorXd &v_in) {\n  if (v_in.squaredNorm() == 0)\n    return Eigen::VectorXd::Zero(vec_in_->container().size());\n\n  // ApplyTranspose only works with if we have cached the bil forms.\n  assert(use_cache_);\n\n  Eigen::VectorXd v_lower;\n\n  // Store the input in the double tree.\n  vec_out_->FromVectorContainer(v_in);\n\n  // NOTE: We are calculating the transpose, by transposing all the time/space\n  // bilinear forms. This means that the order of evaluation changes, and that\n  // ApplyLow becomes  ApplyUpp, and vice versa. Since L is the strict lower\n  // diagonal, this only works in Sigma is larger than described in followup3.\n  // (See also the note in GenerateSigma).\n\n  // Apply the lower part using cached bil forms.\n  for (auto &bil_form : bil_space_upp_) bil_form.Transpose().Apply();\n  for (auto &bil_form : bil_time_upp_) bil_form.Transpose().ApplyLow();\n\n  // Store the lower output.\n  v_lower = vec_in_->ToVectorContainer();\n\n  // Reset the input, if necessary.\n  if (vec_out_ == theta_.get() ||\n      static_cast<void *>(vec_out_) == static_cast<void *>(vec_in_))\n    vec_out_->FromVectorContainer(v_in);\n\n  // Apply the upper part using cached bil forms.\n  for (auto &bil_form : bil_time_low_) bil_form.Transpose().ApplyUpp();\n  for (auto &bil_form : bil_space_low_) bil_form.Transpose().Apply();\n\n  // Return vectorized output.\n  return v_lower + vec_in_->ToVectorContainer();\n}\n\ntemplate <typename OperatorSpace, typename BasisTimeIn, typename BasisTimeOut>\nBlockDiagonalBilinearForm<OperatorSpace, BasisTimeIn, BasisTimeOut>::\n    BlockDiagonalBilinearForm(DblVecIn *vec_in, DblVecOut *vec_out,\n                              bool use_cache, space::OperatorOptions space_opts)\n    : vec_in_(vec_in),\n      vec_out_(vec_out),\n      use_cache_(use_cache),\n      space_opts_(std::move(space_opts)) {\n  auto time_start = std::chrono::steady_clock::now();\n  assert(vec_in->container().size() == vec_out->container().size());\n  // If use cache, cache the bil forms here.\n  if (use_cache_) {\n    for (auto psi_out_labda : vec_out_->Project_0()->Bfs()) {\n      auto fiber_in = vec_in_->Fiber_1(psi_out_labda->node());\n      if (fiber_in->children().empty()) continue;\n      auto fiber_out = psi_out_labda->FrozenOtherAxis();\n      // Set the level of the time wavelet.\n      space_opts_.time_level = std::get<0>(psi_out_labda->nodes())->level();\n      space_bilforms_.emplace_back(fiber_in, fiber_out, space_opts_);\n    }\n  }\n  time_construct_ = std::chrono::duration<double>(\n      std::chrono::steady_clock::now() - time_start);\n}\n\ntemplate <typename OperatorSpace, typename BasisTimeIn, typename BasisTimeOut>\nEigen::VectorXd\nBlockDiagonalBilinearForm<OperatorSpace, BasisTimeIn, BasisTimeOut>::Apply(\n    const Eigen::VectorXd &v_in) {\n  if (v_in.squaredNorm() == 0)\n    return Eigen::VectorXd::Zero(vec_out_->container().size());\n\n  // Debug information.\n  auto time_start = std::chrono::steady_clock::now();\n  num_apply_++;\n\n  // Store the input in the double tree.\n  vec_in_->FromVectorContainer(v_in);\n\n  if (!use_cache_) {\n    for (auto psi_out_labda : vec_out_->Project_0()->Bfs()) {\n      auto fiber_in = vec_in_->Fiber_1(psi_out_labda->node());\n      if (fiber_in->children().empty()) continue;\n      auto fiber_out = psi_out_labda->FrozenOtherAxis();\n      // Set the level of the time wavelet.\n      space_opts_.time_level = std::get<0>(psi_out_labda->nodes())->level();\n      auto bil_form = space::CreateBilinearForm<OperatorSpace>(\n          fiber_in, fiber_out, space_opts_);\n      bil_form.Apply();\n    }\n  } else {\n    // Apply the space bilforms.\n    for (auto &bil_form : space_bilforms_) bil_form.Apply();\n  }\n  // Return vectorized output.\n  Eigen::VectorXd result = vec_out_->ToVectorContainer();\n\n  // Store timing results.\n  time_apply_ += std::chrono::duration<double>(\n      std::chrono::steady_clock::now() - time_start);\n\n  return result;\n}\n}  // namespace spacetime\n", "meta": {"hexsha": "6ac4a37a7fc5930db04434649b4e2ab438456a64", "size": 11584, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "src/spacetime/bilinear_form.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/spacetime/bilinear_form.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/spacetime/bilinear_form.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": 39.9448275862, "max_line_length": 80, "alphanum_fraction": 0.6750690608, "num_tokens": 3046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.025565212438420554, "lm_q1q2_score": 0.010704075434988244}}
{"text": "//=============================================================================================================\n/**\n * @file     fwd_eeg_sphere_model.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\n *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n *           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>\n * @since    0.1.0\n * @date     December, 2016\n *\n * @section  LICENSE\n *\n * Copyright (C) 2016, Lorenz Esch, Matti Hamalainen, Christoph Dinh. 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 the FwdEegSphereModel Class.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"utils/simplex_algorithm.h\"\n\n#include \"fwd_eeg_sphere_model.h\"\n#include \"fwd_eeg_sphere_model_set.h\"\n\n#include <QtAlgorithms>\n\n#include <qmath.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace UTILSLIB;\nusing namespace FWDLIB;\n\n#define MIN_1(a,b) ((a) < (b) ? (a) : (b))\n\n//ToDo Remove after refactoring\n#define X_1 0\n#define Y_1 1\n#define Z_1 2\n/*\n * Dot product and length\n */\n#define VEC_DOT_1(x,y) ((x)[X_1]*(y)[X_1] + (x)[Y_1]*(y)[Y_1] + (x)[Z_1]*(y)[Z_1])\n#define VEC_LEN_1(x) sqrt(VEC_DOT_1(x,x))\n/*\n * Others...\n */\n#define VEC_DIFF_1(from,to,diff) {\\\n    (diff)[X_1] = (to)[X_1] - (from)[X_1];\\\n    (diff)[Y_1] = (to)[Y_1] - (from)[Y_1];\\\n    (diff)[Z_1] = (to)[Z_1] - (from)[Z_1];\\\n    }\n\n#define VEC_COPY_1(to,from) {\\\n    (to)[X_1] = (from)[X_1];\\\n    (to)[Y_1] = (from)[Y_1];\\\n    (to)[Z_1] = (from)[Z_1];\\\n    }\n\n#define CROSS_PRODUCT_1(x,y,xy) {\\\n    (xy)[X_1] =   (x)[Y_1]*(y)[Z_1]-(y)[Y_1]*(x)[Z_1];\\\n    (xy)[Y_1] = -((x)[X_1]*(y)[Z_1]-(y)[X_1]*(x)[Z_1]);\\\n    (xy)[Z_1] =   (x)[X_1]*(y)[Y_1]-(y)[X_1]*(x)[Y_1];\\\n    }\n\n#define MALLOC_1(x,t) (t *)malloc((x)*sizeof(t))\n\n#define REALLOC_1(x,y,t) (t *)((x == NULL) ? malloc((y)*sizeof(t)) : realloc((x),(y)*sizeof(t)))\n\n#define FREE(x) if ((char *)(x) != NULL) free((char *)(x))\n\n#define ALLOC_DCMATRIX_1(x,y) mne_dmatrix_1((x),(y))\n#define FREE_DCMATRIX_1(m) mne_free_dcmatrix_1((m))\n\n#define ALLOC_CMATRIX_1(x,y) mne_cmatrix_1((x),(y))\n\n/*\n * float matrices\n */\n#define FREE_CMATRIX_1(m) mne_free_cmatrix_1((m))\n\n#ifndef TRUE\n#define TRUE 1\n#endif\n\n#ifndef FALSE\n#define FALSE 0\n#endif\n\n#ifndef FAIL\n#define FAIL -1\n#endif\n\n#ifndef OK\n#define OK 0\n#endif\n\nstatic void matrix_error_1(int kind, int nr, int nc)\n\n{\n    if (kind == 1)\n        printf(\"Failed to allocate memory pointers for a %d x %d matrix\\n\",nr,nc);\n    else if (kind == 2)\n        printf(\"Failed to allocate memory for a %d x %d matrix\\n\",nr,nc);\n    else\n        printf(\"Allocation error for a %d x %d matrix\\n\",nr,nc);\n    if (sizeof(void *) == 4) {\n        printf(\"This is probably because you seem to be using a computer with 32-bit architecture.\\n\");\n        printf(\"Please consider moving to a 64-bit platform.\");\n    }\n    printf(\"Cannot continue. Sorry.\\n\");\n    exit(1);\n}\n\nfloat **mne_cmatrix_1(int nr,int nc)\n\n{\n    int i;\n    float **m;\n    float *whole;\n\n    m = MALLOC_1(nr,float *);\n    if (!m) matrix_error_1(1,nr,nc);\n    whole = MALLOC_1(nr*nc,float);\n    if (!whole) matrix_error_1(2,nr,nc);\n\n    for(i=0;i<nr;i++)\n        m[i] = whole + i*nc;\n    return m;\n}\n\ndouble **mne_dmatrix_1(int nr, int nc)\n\n{\n    int i;\n    double **m;\n    double *whole;\n\n    m = MALLOC_1(nr,double *);\n    if (!m) matrix_error_1(1,nr,nc);\n    whole = MALLOC_1(nr*nc,double);\n    if (!whole) matrix_error_1(2,nr,nc);\n\n    for(i=0;i<nr;i++)\n        m[i] = whole + i*nc;\n    return m;\n}\n\nvoid mne_free_cmatrix_1 (float **m)\n{\n    if (m) {\n        free(*m);\n        free(m);\n    }\n}\n\nvoid mne_free_dcmatrix_1 (double **m)\n\n{\n    if (m) {\n        FREE(*m);\n        FREE(m);\n    }\n}\n\n#define MAXTERMS 1000\n#define EPS      1e-10\n#define SIN_EPS  1e-3\n\nstatic int         terms = 0;       /* These statistics may be useful */\nstatic int         eval = 0;\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nFwdEegSphereModel::FwdEegSphereModel()\n: fn(NULL)\n, nterms  (0)\n, lambda  (NULL)\n, mu      (NULL)\n, nfit    (0)\n, scale_pos (0)\n{\n    r0[0] = 0.0;\n    r0[1] = 0.0;\n    r0[2] = 0.0;\n}\n\n//=============================================================================================================\n\nFwdEegSphereModel::FwdEegSphereModel(const FwdEegSphereModel& p_FwdEegSphereModel)\n{\n    int k;\n\n    if (!p_FwdEegSphereModel.name.isEmpty())\n        this->name = p_FwdEegSphereModel.name;\n    if (p_FwdEegSphereModel.nlayer() > 0) {\n        for (k = 0; k < p_FwdEegSphereModel.nlayer(); k++)\n            this->layers.append(p_FwdEegSphereModel.layers[k]);\n    }\n    VEC_COPY_1(this->r0,p_FwdEegSphereModel.r0);\n    if (p_FwdEegSphereModel.nterms > 0) {\n        this->fn = VectorXd(p_FwdEegSphereModel.nterms);\n        this->nterms = p_FwdEegSphereModel.nterms;\n        for (k = 0; k < p_FwdEegSphereModel.nterms; k++)\n            this->fn[k] = p_FwdEegSphereModel.fn[k];\n    }\n    if (p_FwdEegSphereModel.nfit > 0) {\n        this->mu     = VectorXf(p_FwdEegSphereModel.nfit);\n        this->lambda = VectorXf(p_FwdEegSphereModel.nfit);\n        this->nfit   = p_FwdEegSphereModel.nfit;\n        for (k = 0; k < p_FwdEegSphereModel.nfit; k++) {\n            this->mu[k] = p_FwdEegSphereModel.mu[k];\n            this->lambda[k] = p_FwdEegSphereModel.lambda[k];\n        }\n    }\n    this->scale_pos = p_FwdEegSphereModel.scale_pos;\n}\n\n//=============================================================================================================\n\nFwdEegSphereModel* FwdEegSphereModel::fwd_create_eeg_sphere_model(const QString& name,\n                                                     int nlayer,\n                                                     const VectorXf& rads,\n                                                     const VectorXf& sigmas)\n/*\n      * Produce a new sphere model structure\n      */\n{\n    FwdEegSphereModel* new_model = new FwdEegSphereModel();\n\n    new_model->name   = name;\n\n    for (int k = 0; k < nlayer; k++) {\n        FwdEegSphereLayer layer;\n        layer.rad = layer.rel_rad = rads[k];\n        layer.sigma = sigmas[k];\n        new_model->layers.append(layer);\n    }\n    /*\n   * Sort...\n   */\n    qSort (new_model->layers.begin(), new_model->layers.end(), FwdEegSphereLayer::comp_layers);\n\n    /*\n   * Scale the radiuses\n   */\n    float R  = new_model->layers[nlayer-1].rad;\n    float rR = new_model->layers[nlayer-1].rel_rad;\n    for (int k = 0; k < nlayer; k++) {\n        new_model->layers[k].rad     = new_model->layers[k].rad/R;\n        new_model->layers[k].rel_rad = new_model->layers[k].rel_rad/rR;\n    }\n    return new_model;\n}\n\n//=============================================================================================================\n\nFwdEegSphereModel::~FwdEegSphereModel()\n{\n}\n\n//=============================================================================================================\n\nFwdEegSphereModel* FwdEegSphereModel::setup_eeg_sphere_model(const QString& eeg_model_file, QString eeg_model_name, float eeg_sphere_rad)\n{\n    FwdEegSphereModelSet* eeg_models = NULL;\n    FwdEegSphereModel*    eeg_model  = NULL;\n\n    if (eeg_model_name.isEmpty())\n        eeg_model_name = QString(\"Default\");\n\n    eeg_models = FwdEegSphereModelSet::fwd_load_eeg_sphere_models(eeg_model_file,NULL);\n    eeg_models->fwd_list_eeg_sphere_models(stderr);\n\n    if ((eeg_model = eeg_models->fwd_select_eeg_sphere_model(eeg_model_name)) == NULL)\n        goto bad;\n\n    if (!eeg_model->fwd_setup_eeg_sphere_model(eeg_sphere_rad,true,3))\n        goto bad;\n    printf(\"Using EEG sphere model \\\"%s\\\" with scalp radius %7.1f mm\\n\",\n           eeg_model->name.toUtf8().constData(),1000*eeg_sphere_rad);\n    printf(\"\\n\");\n    delete eeg_models;\n    return eeg_model;\n\nbad : {\n        delete eeg_models;\n        delete eeg_model;\n        return NULL;\n    }\n}\n\n//=============================================================================================================\n\nfitUser FwdEegSphereModel::new_fit_user(int nfit, int nterms)\n\n{\n    fitUser u = MALLOC_1(1,fitUserRec);\n    u->y      = MALLOC_1(nterms-1,double);\n    u->resi   = MALLOC_1(nterms-1,double);\n    u->M      = ALLOC_DCMATRIX_1(nterms-1,nfit-1);\n    u->uu     = ALLOC_DCMATRIX_1(nfit-1,nterms-1);\n    u->vv     = ALLOC_DCMATRIX_1(nfit-1,nfit-1);\n    u->sing   = MALLOC_1(nfit,double);\n    u->fn     = MALLOC_1(nterms,double);\n    u->w      = MALLOC_1(nterms,double);\n    u->nfit   = nfit;\n    u->nterms = nterms;\n    return u;\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\ndouble FwdEegSphereModel::fwd_eeg_get_multi_sphere_model_coeff(int n)\n{\n    MatrixXd M,Mn,help,Mm;\n    static MatrixXd mat1;\n    static MatrixXd mat2;\n    static MatrixXd mat3;\n    static VectorXd c1;\n    static VectorXd c2;\n    static VectorXd cr;\n    static VectorXd cr_mult;\n    double div,div_mult;\n    double n1;\n#ifdef TEST\n    double rel1,rel2;\n    double b,c;\n#endif\n    int    k;\n\n    if (this->nlayer() == 0 || this->nlayer() == 1)\n        return 1.0;\n    /*\n   * Now follows the tricky case\n   */\n#ifdef TEST\n    if (this->nlayer() == 2) {\n        rel1 = layers[0].sigma/layers[1].sigma;\n        n1 = n + 1.0;\n        div_mult = 2.0*n + 1;\n        b = pow(this->layers[0].rel_rad,div_mult);\n        return div_mult/((n1 + n*rel1) + b*n1*(rel1-1.0));\n    }\n    else if (this->nlayer() == 3) {\n        rel1 = this->layers[0].sigma/this->layers[1].sigma;\n        rel2 = this->layers[1].sigma/this->layers[2].sigma;\n        n1 = n + 1.0;\n        div_mult = 2.0*n + 1.0;\n        b = pow(this->layers[0].rel_rad,div_mult);\n        c = pow(this->layers[1].rel_rad,div_mult);\n        div_mult = div_mult*div_mult;\n        div = (b*n*n1*(rel1-1.0)*(rel2-1.0) + c*(rel1*n + n1)*(rel2*n + n1))/c +\n                n1*(b*(rel1-1.0)*(rel2*n1 + n) + c*(rel1*n + n1)*(rel2-1.0));\n        return div_mult/div;\n    }\n#endif\n    if (n == 1) {\n        /*\n     * Initialize the arrays\n     */\n        c1.resize(this->nlayer()-1);\n        c2.resize(this->nlayer()-1);\n        cr.resize(this->nlayer()-1);\n        cr_mult.resize(this->nlayer()-1);\n        for (k = 0; k < this->nlayer()-1; k++) {\n            c1[k] = this->layers[k].sigma/this->layers[k+1].sigma;\n            c2[k] = c1[k] - 1.0;\n            cr_mult[k] = this->layers[k].rel_rad;\n            cr[k] = cr_mult[k];\n            cr_mult[k] = cr_mult[k]*cr_mult[k];\n        }\n        if (mat1.cols() == 0)\n            mat1 = MatrixXd(2,2);\n        if (mat2.cols() == 0)\n            mat2 = MatrixXd(2,2);\n        if (mat3.cols() == 0)\n            mat3 = MatrixXd(2,2);\n    }\n    /*\n   * Increment the radius coefficients\n   */\n    for (k = 0; k < this->nlayer()-1; k++)\n        cr[k] = cr[k]*cr_mult[k];\n    /*\n   * Multiply the matrices\n   */\n    M  = mat1;\n    Mn = mat2;\n    Mm = mat3;\n    M(0,0) = M(1,1) = 1.0;\n    M(0,1) = M(1,0) = 0.0;\n    div      = 1.0;\n    div_mult = 2.0*n + 1.0;\n    n1       = n + 1.0;\n\n    for (k = this->nlayer()-2; k >= 0; k--) {\n\n        Mm(0,0) = (n + n1*c1[k]);\n        Mm(0,1) = n1*c2[k]/cr[k];\n        Mm(1,0) = n*c2[k]*cr[k];\n        Mm(1,1) = n1 + n*c1[k];\n\n        Mn(0,0) = Mm(0,0)*M(0,0) + Mm(0,1)*M(1,0);\n        Mn(0,1) = Mm(0,0)*M(0,1) + Mm(0,1)*M(1,1);\n        Mn(1,0) = Mm(1,0)*M(0,0) + Mm(1,1)*M(1,0);\n        Mn(1,1) = Mm(1,0)*M(0,1) + Mm(1,1)*M(1,1);\n        help = M;\n        M = Mn;\n        Mn = help;\n        div = div*div_mult;\n\n    }\n    return n*div/(n*M(1,1) + n1*M(1,0));\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\nvoid FwdEegSphereModel::next_legen(int n, double x, double *p0, double *p01, double *p1, double *p11)        /* Input: P1(n-2) Output: P1(n-1) */\n/*\n          * Compute the next Legendre polynomials of the\n          * first and second kind using the recursion formulas.\n          *\n          * The routine initializes automatically with the known values\n          * when n = 1\n          */\n{\n    double  help0,help1;\n\n    if (n > 1) {\n        help0 = *p0;\n        help1 = *p1;\n        *p0 = ((2*n-1)*x*help0 - (n-1)*(*p01))/n;\n        *p1 = ((2*n-1)*x*help1 - n*(*p11))/(n-1);\n        *p01 = help0;\n        *p11 = help1;\n    }\n    else if (n == 0) {\n        *p0   = 1.0;\n        *p1   = 0.0;\n    }\n    else if (n == 1) {\n        *p01  = 1.0;\n        *p0   = x;\n        *p11  = 0.0;\n        *p1   = sqrt(1.0-x*x);\n    }\n    return;\n}\n\n//=============================================================================================================\n\nvoid FwdEegSphereModel::calc_pot_components(double beta, double cgamma, double *Vrp, double *Vtp, const Eigen::VectorXd& fn, int nterms)\n{\n    double Vt = 0.0;\n    double Vr = 0.0;\n    double p0,p01,p1,p11;\n    double betan,multn;\n    int    n;\n\n    betan = 1.0;\n    p0 = p01 = p1 = p11 = 0.0;\n    for (n = 1; n <= nterms; n++) {\n        if (betan < EPS) {\n            terms = terms + n;\n            eval  = eval + 1;\n            break;\n        }\n        next_legen (n,cgamma,&p0,&p01,&p1,&p11);\n        multn = betan*fn[n-1];\t/* The 2*n + 1 factor is included in fn */\n        Vr = Vr + multn*p0;\n        Vt = Vt + multn*p1/n;\n        betan = beta*betan;\n    }\n     *Vrp = Vr;\n     *Vtp = Vt;\n    return;\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\nint FwdEegSphereModel::fwd_eeg_multi_spherepot(float *rd, float *Q, float **el, int neeg, float *Vval, void *client)\t  /* The model definition */\n/*\n * Compute the electric potentials in a set of electrodes in spherically\n * Symmetric head model.\n *\n * The code is based on the formulas presented in\n *\n * Z. Zhang, A fast method to compute surface potentials\n * generated by dipoles within multilayer anisotropic spheres,\n * Phys. Med. Biol., 40, 335 - 349, 1995.\n *\n * and\n *\n * J.C. Moscher, R.M. Leahy, and P.S. Lewis, Matrix Kernels for\n * Modeling of EEG and MEG Data, Los Alamos Technical Report,\n * LA-UR-96-1993, 1996.\n *\n * This version does not use the acceleration with help of equivalent sources\n * in the homogeneous model\n *\n */\n{\n    FwdEegSphereModel* m = (FwdEegSphereModel*)client;\n    float  my_rd[3],pos[3];\n    int    k,p;\n    float  pos2,rd_len,pos_len;\n    double beta,cos_gamma,Vr,Vt;\n    float  vec1[3],vec2[3],v1,v2;\n    float  cos_beta,Qr,Qt,Q2,c;\n    float  pi4_inv = 0.25/M_PI;\n    float  sigmaM_inv;\n    /*\n       * Precompute the coefficients\n       */\n    if (m->fn.size() == 0 || m->nterms != MAXTERMS) {\n        m->fn.resize(MAXTERMS);\n        m->nterms = MAXTERMS;\n        for (k = 0; k < MAXTERMS; k++)\n            m->fn[k] = (2*k+3)*m->fwd_eeg_get_multi_sphere_model_coeff(k+1);\n    }\n    /*\n       * Move to the sphere coordinates\n       */\n    for (p = 0; p < 3; p++)\n        my_rd[p] = rd[p] - m->r0[p];\n    rd = my_rd;\n    rd_len = VEC_LEN_1(rd);\n    Q2     = VEC_DOT_1(Q,Q);\n    /*\n       * Ignore dipoles outside the innermost sphere\n       */\n    if (rd_len >= m->layers[0].rad) {\n        for (k = 0; k < neeg; k++)\n            Vval[k] = 0.0;\n        return OK;\n    }\n    /*\n       * Special case: rd and Q are parallel\n       */\n    c = VEC_DOT_1(rd,Q)/(rd_len*sqrt(Q2));\n    if ((1.0-c*c) < SIN_EPS)\t{\t/* Almost parallel:\n                         * Q is purely radial */\n        Qr = sqrt(Q2);\n        Qt = 0.0;\n        cos_beta = 0.0;\n        v1 = 0.0;\n        vec1[0] = vec1[1] = vec1[2] = 0.0;\n    }\n    else {\n        CROSS_PRODUCT_1(rd,Q,vec1);\n        v1 = VEC_LEN_1(vec1);\n        cos_beta = 0.0;\n        Qr = Qt = 0.0;\n    }\n    for (k = 0; k < neeg; k++) {\n        for (p = 0; p < 3; p++)\n            pos[p] = el[k][p] - m->r0[p];\n        /*\n         * Should the position be scaled or not?\n         */\n        if (m->scale_pos) {\n            pos_len = m->layers[m->nlayer()-1].rad/VEC_LEN_1(pos);\n#ifdef DEBUG\n            printf(\"%10.4f %10.4f %10.4f %10.4f\\n\",pos_len,1000*pos[0],1000*pos[1],1000*pos[2]);\n#endif\n            for (p = 0; p < 3; p++)\n                pos[p] = pos_len*pos[p];\n        }\n        pos2 = VEC_DOT_1(pos,pos);\n        pos_len = sqrt(pos2);\n        /*\n         * Calculate the two ingredients for the final result\n         */\n        cos_gamma = VEC_DOT_1(pos,rd)/(rd_len*pos_len);\n        beta = rd_len/pos_len;\n        calc_pot_components(beta,cos_gamma,&Vr,&Vt,m->fn,m->nterms);\n        /*\n         * Then compute the combined result\n         */\n        if (v1 > 0.0) {\n            CROSS_PRODUCT_1(rd,pos,vec2);\n            v2 = VEC_LEN_1(vec2);\n\n            if (v2  > 0.0)\n                cos_beta = VEC_DOT_1(vec1,vec2)/(v1*v2);\n            else\n                cos_beta = 0.0;\n\n            Qr = VEC_DOT_1(Q,rd)/rd_len;\n            Qt = sqrt(Q2 - Qr*Qr);\n        }\n        Vval[k] = pi4_inv*(Qr*Vr + Qt*cos_beta*Vt)/pos2;\n    }\n    /*\n       * Scale by the conductivity if we have the layers\n       * defined\n       */\n    if (m->nlayer() > 0) {\n        sigmaM_inv = 1.0/m->layers[m->nlayer()-1].sigma;\n        for (k = 0; k < neeg; k++)\n            Vval[k] = Vval[k]*sigmaM_inv;\n    }\n    return OK;\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\nint FwdEegSphereModel::fwd_eeg_multi_spherepot_coil1(float *rd, float *Q, FwdCoilSet *els, float *Vval, void *client)           /* Client data will be the sphere model definition */\n/*\n * Calculate the EEG in the sphere model using the fwdCoilSet structure\n *\n * This version does not use the acceleration with help of equivalent sources\n * in the homogeneous model\n *\n */\n{\n    float *vval_one = NULL,val;\n    int   nvval = 0;\n    int   k,c;\n    FwdCoil* el;\n\n    for (k = 0; k < els->ncoil; k++, el++) {\n        el = els->coils[k];\n        if (el->coil_class == FWD_COILC_EEG) {\n            if (el->np > nvval) {\n                vval_one = REALLOC_1(vval_one,el->np,float);\n                nvval = el->np;\n            }\n            if (fwd_eeg_multi_spherepot(rd,Q,el->rmag,el->np,vval_one,client) != OK) {\n                FREE(vval_one);\n                return FAIL;\n            }\n            for (c = 0, val = 0.0; c < el->np; c++)\n                val += el->w[c]*vval_one[c];\n            *Vval = val;\n        }\n        Vval++;\n    }\n    FREE(vval_one);\n    return OK;\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\nbool FwdEegSphereModel::fwd_eeg_spherepot_vec( float   *rd, float   **el, int neeg, float **Vval_vec, void *client)\n{\n    FwdEegSphereModel* m = (FwdEegSphereModel*)client;\n    float fact = 0.25f/(float)M_PI;\n    float a_vec[3];\n    float a,a2,a3;\n    float rrd,rd2,rd2_inv,r,r2,ra,rda;\n    float F;\n    float c1,c2,m1,m2;\n    int   k,p,eq;\n    float *this_pos;\n    float orig_rd[3],scaled_rd[3];\n    float pos[3],pos_len;\n    /*\n   * Shift to the sphere model coordinates\n   */\n    for (p = 0; p < 3; p++)\n        orig_rd[p] = rd[p] - m->r0[p];\n    rd = scaled_rd;\n    /*\n   * Initialize the arrays\n   */\n    for (k = 0 ; k < neeg ; k++) {\n        Vval_vec[X_1][k] = 0.0;\n        Vval_vec[Y_1][k] = 0.0;\n        Vval_vec[Z_1][k] = 0.0;\n    }\n    /*\n   * Ignore dipoles outside the innermost sphere\n   */\n    if (VEC_LEN_1(orig_rd) >= m->layers[0].rad)\n        return true;\n    /*\n   * Default to homogeneous model if no model was previously set\n   */\n#ifdef FOO\n    if (nequiv == 0) /* what to do */\n        eeg_set_homog_sphere_model();\n#endif\n    /*\n   * Make a weighted sum over the equivalence parameters\n   */\n    for (eq = 0; eq < m->nfit; eq++) {\n        /*\n     * Scale the dipole position\n     */\n        for (p = 0; p < 3; p++)\n            rd[p] = m->mu[eq]*orig_rd[p];\n\n        rd2     = VEC_DOT_1(rd,rd);\n        rd2_inv = 1.0/rd2;\n\n        /*\n     * Go over all electrodes\n     */\n        for (k = 0; k < neeg ; k++) {\n            this_pos = el[k];\n\n            for (p = 0; p < 3; p++)\n                pos[p] = this_pos[p] - m->r0[p];\n            /*\n       * Scale location onto the surface of the sphere\n       */\n            if (m->scale_pos) {\n                pos_len = m->layers[m->nlayer()-1].rad/VEC_LEN_1(pos);\n                for (p = 0; p < 3; p++)\n                    pos[p] = pos_len*pos[p];\n            }\n            this_pos = pos;\n\n            /* Vector from dipole to the field point */\n\n            VEC_DIFF_1 (rd,this_pos,a_vec);\n\n            /* Compute the dot products needed */\n\n            a2  = VEC_DOT_1(a_vec,a_vec);       a = sqrt(a2);\n            a3  = 2.0/(a2*a);\n            r2  = VEC_DOT_1(this_pos,this_pos); r = sqrt(r2);\n            rrd = VEC_DOT_1(this_pos,rd);\n            ra  = r2 - rrd;\n            rda = rrd - rd2;\n\n            /* The main ingredients */\n\n            F  = a*(r*a + ra);\n            c1 = a3*rda + 1.0/a - 1.0/r;\n            c2 = a3 + (a+r)/(r*F);\n\n            /* Mix them together and scale by lambda/(rd*rd) */\n\n            m1 = (c1 - c2*rrd);\n            m2 = c2*rd2;\n\n            Vval_vec[X_1][k] = Vval_vec[X_1][k] + m->lambda[eq]*rd2_inv*(m1*rd[X_1] + m2*this_pos[X_1]);\n            Vval_vec[Y_1][k] = Vval_vec[Y_1][k] + m->lambda[eq]*rd2_inv*(m1*rd[Y_1] + m2*this_pos[Y_1]);\n            Vval_vec[Z_1][k] = Vval_vec[Z_1][k] + m->lambda[eq]*rd2_inv*(m1*rd[Z_1] + m2*this_pos[Z_1]);\n        }             /* All electrodes done */\n    }               /* All equivalent dipoles done */\n    /*\n   * Finish by scaling by 1/(4*M_PI);\n   */\n    for (k = 0; k  < neeg; k++) {\n        Vval_vec[X_1][k] = fact*Vval_vec[X_1][k];\n        Vval_vec[Y_1][k] = fact*Vval_vec[Y_1][k];\n        Vval_vec[Z_1][k] = fact*Vval_vec[Z_1][k];\n    }\n    return true;\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\nint FwdEegSphereModel::fwd_eeg_spherepot_coil_vec(float *rd, FwdCoilSet* els, float **Vval_vec, void *client)\n{\n    float **vval_one = NULL;\n    float val;\n    int   nvval = 0;\n    int   k,c,p;\n    FwdCoil* el;\n\n    for (k = 0; k < els->ncoil; k++, el++) {\n        el = els->coils[k];\n        if (el->coil_class == FWD_COILC_EEG) {\n            if (el->np > nvval) {\n                FREE_CMATRIX_1(vval_one);\n                vval_one = ALLOC_CMATRIX_1(3,el->np);\n                nvval = el->np;\n            }\n            if (!fwd_eeg_spherepot_vec(rd,el->rmag,el->np,vval_one,client)) {\n                FREE_CMATRIX_1(vval_one);\n                return FAIL;\n            }\n            for (p = 0; p < 3; p++) {\n                for (c = 0, val = 0.0; c < el->np; c++)\n                    val += el->w[c]*vval_one[p][c];\n                Vval_vec[p][k] = val;\n            }\n        }\n    }\n    FREE_CMATRIX_1(vval_one);\n    return OK;\n}\n\n//=============================================================================================================\n\nint FwdEegSphereModel::fwd_eeg_spherepot_grad_coil(float *rd, float Q[], FwdCoilSet *coils, float Vval[], float xgrad[], float ygrad[], float zgrad[], void *client)  /* Client data to be passed to some foward modelling routines */\n/*\n          * Quick and dirty solution: use differences\n          *\n          * This routine uses the acceleration with help of equivalent sources\n          * in the homogeneous sphere.\n          *\n          */\n{\n    float my_rd[3];\n    float step  = 0.0005;\n    float step2 = 2*step;\n    float *grads[3];\n    int   p,q;\n\n    grads[0] = xgrad;\n    grads[1] = ygrad;\n    grads[2] = zgrad;\n\n    for (p = 0; p < 3; p++) {\n        VEC_COPY_1(my_rd,rd);\n        my_rd[p] = my_rd[p] + step;\n        if (fwd_eeg_spherepot_coil(my_rd,Q,coils,grads[p],client) == FAIL)\n            return FAIL;\n        VEC_COPY_1(my_rd,rd);\n        my_rd[p] = my_rd[p] - step;\n        if (fwd_eeg_spherepot_coil(my_rd,Q,coils,Vval,client) == FAIL)\n            return FAIL;\n        for (q = 0; q < coils->ncoil; q++)\n            grads[p][q] = (grads[p][q]-Vval[q])/step2;\n    }\n    if (Vval) {\n        if (fwd_eeg_spherepot_coil(rd,Q,coils,Vval,client) == FAIL)\n            return FAIL;\n    }\n    return OK;\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\nint FwdEegSphereModel::fwd_eeg_spherepot(   float   *rd,       /* Dipole position */\n                                            float   *Q,\t /* Dipole moment */\n                                            float   **el,\t /* Electrode positions */\n                                            int     neeg,\t /* Number of electrodes */\n                                            VectorXf& Vval,\t /* The potential values */\n                                            void    *client)\n/*\n      * This routine calculates the potentials for a specific dipole direction\n      *\n      * This routine uses the acceleration with help of equivalent sources\n      * in the homogeneous sphere.\n      */\n{\n    FwdEegSphereModel* m = (FwdEegSphereModel*)client;\n    float fact = 0.25f/M_PI;\n    float a_vec[3];\n    float a,a2,a3;\n    float rrd,rd2,rd2_inv,r,r2,ra,rda;\n    float F;\n    float c1,c2,m1,m2,f1,f2;\n    int   k,p,eq;\n    float *this_pos;\n    float orig_rd[3],scaled_rd[3];\n    float pos[3],pos_len;\n    /*\n   * Shift to the sphere model coordinates\n   */\n    for (p = 0; p < 3; p++)\n        orig_rd[p] = rd[p] - m->r0[p];\n    rd = scaled_rd;\n    /*\n   * Initialize the arrays\n   */\n    for (k = 0 ; k < neeg ; k++)\n        Vval[k] = 0.0;\n    /*\n   * Ignore dipoles outside the innermost sphere\n   */\n    if (VEC_LEN_1(orig_rd) >= m->layers[0].rad)\n        return true;\n    /*\n   * Default to homogeneous model if no model was previously set\n   */\n#ifdef FOO\n    if (nequiv == 0) /* what to do */\n        eeg_set_homog_sphere_model();\n#endif\n    /*\n   * Make a weighted sum over the equivalence parameters\n   */\n    for (eq = 0; eq < m->nfit; eq++) {\n        /*\n     * Scale the dipole position\n     */\n        for (p = 0; p < 3; p++)\n            rd[p] = m->mu[eq]*orig_rd[p];\n\n        rd2     = VEC_DOT_1(rd,rd);\n        rd2_inv = 1.0/rd2;\n\n        f1 = VEC_DOT_1(rd,Q);\n        /*\n     * Go over all electrodes\n     */\n        for (k = 0; k < neeg ; k++) {\n            this_pos = el[k];\n\n            for (p = 0; p < 3; p++)\n                pos[p] = this_pos[p] - m->r0[p];\n            /*\n       * Scale location onto the surface of the sphere\n       */\n            if (m->scale_pos) {\n                pos_len = m->layers[m->nlayer()-1].rad/VEC_LEN_1(pos);\n                for (p = 0; p < 3; p++)\n                    pos[p] = pos_len*pos[p];\n            }\n            this_pos = pos;\n\n            /* Vector from dipole to the field point */\n\n            VEC_DIFF_1 (rd,this_pos,a_vec);\n\n            /* Compute the dot products needed */\n\n            a2  = VEC_DOT_1(a_vec,a_vec);       a = sqrt(a2);\n            a3  = 2.0/(a2*a);\n            r2  = VEC_DOT_1(this_pos,this_pos); r = sqrt(r2);\n            rrd = VEC_DOT_1(this_pos,rd);\n            ra  = r2 - rrd;\n            rda = rrd - rd2;\n\n            /* The main ingredients */\n\n            F  = a*(r*a + ra);\n            c1 = a3*rda + 1.0/a - 1.0/r;\n            c2 = a3 + (a+r)/(r*F);\n\n            /* Mix them together and scale by lambda/(rd*rd) */\n\n            m1 = (c1 - c2*rrd);\n            m2 = c2*rd2;\n\n            f2 = VEC_DOT_1(this_pos,Q);\n            Vval[k] = Vval[k] + m->lambda[eq]*rd2_inv*(m1*f1 + m2*f2);\n        }             /* All electrodes done */\n    }               /* All equivalent dipoles done */\n    /*\n   * Finish by scaling by 1/(4*M_PI);\n   */\n    for (k = 0; k  < neeg; k++)\n        Vval[k] = fact*Vval[k];\n    return OK;\n}\n\n//=============================================================================================================\n// fwd_multi_spherepot.c\nint FwdEegSphereModel::fwd_eeg_spherepot_coil(  float *rd, float *Q, FwdCoilSet* els, float *Vval, void *client)\n{\n    VectorXf vval_one;\n    float val;\n    int   nvval = 0;\n    int   k,c;\n    FwdCoil* el;\n\n    for (k = 0; k < els->ncoil; k++, el++) {\n        el = els->coils[k];\n        if (el->coil_class == FWD_COILC_EEG) {\n            if (el->np > nvval) {\n                vval_one.resize(el->np);\n                nvval = el->np;\n            }\n            if (fwd_eeg_spherepot(rd,Q,el->rmag,el->np,vval_one,client) != OK) {\n                return FAIL;\n            }\n            for (c = 0, val = 0.0; c < el->np; c++)\n                val += el->w[c]*vval_one[c];\n            *Vval = val;\n        }\n        Vval++;\n    }\n    return OK;\n}\n\n//=============================================================================================================\n// fwd_eeg_sphere_models.c\nbool FwdEegSphereModel::fwd_setup_eeg_sphere_model(float rad, bool fit_berg_scherg, int nfit)\n{\n    int nterms = 200;\n    float  rv;\n\n    /*\n     * Scale the relative radiuses\n     */\n    for (int k = 0; k < this->nlayer(); k++)\n        this->layers[k].rad = rad*this->layers[k].rel_rad;\n\n    if (fit_berg_scherg) {\n        if (this->fwd_eeg_fit_berg_scherg(nterms,nfit,rv)) {\n            printf(\"Equiv. model fitting -> \");\n            printf(\"RV = %g %%\\n\",100*rv);\n            for (int k = 0; k < nfit; k++)\n                printf(\"mu%d = %g\\tlambda%d = %g\\n\", k+1,this->mu[k],k+1,this->layers[this->nlayer()-1].sigma*this->lambda[k]);\n        }\n        else\n            return false;\n    }\n\n    printf(\"Defined EEG sphere model with rad = %7.2f mm\\n\", 1000.0*rad);\n    return true;\n}\n\nEigen::MatrixXd toDoubleEigenMatrix(double **mat, const int m, const int n)\n{\n    Eigen::MatrixXd eigen_mat(m,n);\n\n    for ( int i = 0; i < m; ++i)\n        for ( int j = 0; j < n; ++j)\n            eigen_mat(i,j) = mat[i][j];\n\n    return eigen_mat;\n}\n\nvoid fromDoubleEigenMatrix(const Eigen::MatrixXd& from_mat, double **to_mat, const int m, const int n)\n{\n    for ( int i = 0; i < m; ++i)\n        for ( int j = 0; j < n; ++j)\n            to_mat[i][j] = from_mat(i,j);\n}\n\nvoid fromDoubleEigenMatrix(const Eigen::MatrixXd& from_mat, double **to_mat)\n{\n    fromDoubleEigenMatrix(from_mat, to_mat, from_mat.rows(), from_mat.cols());\n}\n\nvoid fromDoubleEigenVector(const Eigen::VectorXd& from_vec, double *to_vec, const int n)\n{\n    for ( int i = 0; i < n; ++i)\n        to_vec[i] = from_vec[i];\n}\n\nvoid fromDoubleEigenVector(const Eigen::VectorXd& from_vec, double *to_vec)\n{\n    fromDoubleEigenVector(from_vec, to_vec, from_vec.size());\n}\n\n//============================= fwd_fit_berg_scherg.c\nstatic double dot_dvectors (double *v1,\n                            double *v2,\n                            int   nn)\n{\n    double result = 0.0;\n    int   k;\n\n    for (k = 0; k < nn; k++)\n        result = result + v1[k]*v2[k];\n    return (result);\n}\n//============================= fwd_fit_berg_scherg.c\nstatic int c_dsvd(double **mat,\t\t/* The matrix */\n                  int   m,int n,\t/* m rows n columns */\n                  double *sing,\t        /* Singular values (must have size\n                                                           * MIN(m,n)+1 */\n                  double **uu,\t\t/* Left eigenvectors */\n                  double **vv)\t\t/* Right eigenvectors */\n/*\n      * Compute the SVD of mat.\n      * The singular vector calculations depend on whether\n      * or not u and v are given.\n      * The allocations should be done as follows\n      *\n      * mat = ALLOC_DCMATRIX(m,n);\n      * vv  = ALLOC_DCMATRIX(MIN(m,n),n);\n      * uu  = ALLOC_DCMATRIX(MIN(m,n),m);\n      * sing = MALLOC(MIN(m,n),double);\n      *\n      * mat is modified by this operation\n      *\n      * This simply allocates the workspace and calls the\n      * LAPACK Fortran routine\n      */\n{\n    int    udim = MIN_1(m,n);\n\n    Eigen::MatrixXd eigen_mat = toDoubleEigenMatrix(mat, m, n);\n\n    //ToDo Optimize computation depending of whether uu or vv are defined\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd(eigen_mat,Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    fromDoubleEigenVector(svd.singularValues(), sing, svd.singularValues().size());\n\n    if ( uu != NULL )\n        fromDoubleEigenMatrix(svd.matrixU().transpose(), uu, udim, m);\n\n    if ( vv != NULL )\n        fromDoubleEigenMatrix(svd.matrixV().transpose(), vv, n, n);\n\n    return 0;\n    //  return info;\n}\n\n/*\n * Include the simplex and SVD code here.\n * It is not too much of a problem\n */\n\n//============================= fwd_fit_berg_scherg.c\n\n//============================= fwd_fit_berg_scherg.c\nnamespace FWDLIB\n{\n\ntypedef struct {\n    double lambda;\t\t/* Magnitude for the apparent dipole */\n    double mu;\t\t\t/* Distance multiplier for the apparent dipole */\n} *bergSchergPar,bergSchergParRec;\n\n} // Namepsace\n\n//============================= fwd_fit_berg_scherg.c\nstatic int comp_pars(const void *p1,const void *p2)\n/*\n      * Comparison function for sorting layers\n      */\n{\n    bergSchergPar v1 = (bergSchergPar)p1;\n    bergSchergPar v2 = (bergSchergPar)p2;\n\n    if (v1->mu > v2->mu)\n        return -1;\n    else if (v1->mu < v2->mu)\n        return 1;\n    else\n        return 0;\n}\n\n//============================= fwd_fit_berg_scherg.c\nstatic void sort_parameters(VectorXd& mu,VectorXd& lambda,int nfit)\n/*\n      * Sort the parameters so that largest mu comes first\n      */\n{\n    bergSchergPar pars = MALLOC_1(nfit,bergSchergParRec);\n\n    for (int k = 0; k < nfit; k++) {\n        pars[k].mu = mu[k];\n        pars[k].lambda = lambda[k];\n    }\n    \n    qsort (pars, nfit, sizeof(bergSchergParRec), comp_pars);\n\n    for (int k = 0; k < nfit; k++) {\n        mu[k]     = pars[k].mu;\n        lambda[k] = pars[k].lambda;\n    }\n    \n    FREE(pars);\n}\n\n//============================= fwd_fit_berg_scherg.c\nstatic bool report_fit(int    loop,\n                      const VectorXd &fitpar,\n                      double Smin)\n\n/*\n      * Report our progress\n      */\n{\n#ifdef LOG_FIT\n    for (int k = 0; k < fitpar.size(); k++)\n        printf(\"%g \",mu[k]);\n    printf(\"%g\\n\",Smin);\n#endif\n    return true;\n}\n\n//============================= fwd_fit_berg_scherg.c\nstatic MatrixXd get_initial_simplex(const VectorXd &pars,\n                                    double simplex_size)\n\n{\n    int npar = pars.size();\n\n    MatrixXd simplex = MatrixXd::Zero(npar+1,npar);\n\n    simplex.rowwise() += pars.transpose();\n\n    for (int k = 1; k < npar+1; k++)\n        simplex(k,k-1) += simplex_size;\n\n    return simplex;\n}\n\nvoid FwdEegSphereModel::compose_linear_fitting_data(const VectorXd& mu,fitUser u)\n{\n    double mu1n,k1;\n    int k,p;\n    /*\n   * y is the data to be fitted (nterms-1 x 1)\n   * M is the model matrix      (nterms-1 x nfit-1)\n   */\n    for (k = 0; k < u->nterms-1; k++) {\n        k1 = k + 1;\n        mu1n = pow(mu[0],k1);\n        u->y[k] = u->w[k]*(u->fn[k+1] - mu1n*u->fn[0]);\n        for (p = 0; p < u->nfit-1; p++)\n            u->M[k][p] = u->w[k]*(pow(mu[p+1],k1)-mu1n);\n    }\n}\n\n// fwd_fit_berg_scherg.c\ndouble FwdEegSphereModel::compute_linear_parameters(const VectorXd& mu,\n                                        VectorXd& lambda,\n                                        fitUser u)\n/*\n      * Compute the best-fitting linear parameters\n      * Return the corresponding RV\n      */\n{\n    int k,p,q;\n    VectorXd vec(u->nfit-1);\n    double sum;\n\n    compose_linear_fitting_data(mu,u);\n\n    c_dsvd(u->M,u->nterms-1,u->nfit-1,u->sing,u->uu,u->vv);\n    /*\n   * Compute the residuals\n   */\n    for (k = 0; k < u->nterms-1; k++)\n        u->resi[k] = u->y[k];\n\n    for (p = 0; p < u->nfit-1; p++) {\n        vec[p] = dot_dvectors(u->uu[p],u->y,u->nterms-1);\n        for (k = 0; k < u->nterms-1; k++)\n            u->resi[k] = u->resi[k] - u->uu[p][k]*vec[p];\n        vec[p] = vec[p]/u->sing[p];\n    }\n\n    for (p = 0; p < u->nfit-1; p++) {\n        for (q = 0, sum = 0.0; q < u->nfit-1; q++)\n            sum += u->vv[q][p]*vec[q];\n        lambda[p+1] = sum;\n    }\n    for (p = 1, sum = 0.0; p < u->nfit; p++)\n        sum += lambda[p];\n    lambda[0] = u->fn[0] - sum;\n    return dot_dvectors(u->resi,u->resi,u->nterms-1)/dot_dvectors(u->y,u->y,u->nterms-1);\n}\n\n// fwd_fit_berg_scherg.c\ndouble FwdEegSphereModel::one_step (const VectorXd& mu, const void *user_data)\n/*\n      * Evaluate the residual sum of squares fit for one set of\n      * mu values\n      */\n{\n    int k,p;\n    double  dot;\n    fitUser u = (fitUser)user_data;\n\n    for (k = 0; k < u->nfit; k++) {\n        if (std::fabs(mu[k]) > 1.0)\n            return 1.0;\n    }\n    /*\n   * Compose the data for the linear fitting\n   */\n    compose_linear_fitting_data(mu,u);\n    /*\n   * Compute SVD\n   */\n    c_dsvd(u->M,u->nterms-1,u->nfit-1,u->sing,u->uu,NULL);\n    /*\n   * Compute the residuals\n   */\n    for (k = 0; k < u->nterms-1; k++)\n        u->resi[k] = u->y[k];\n    for (p = 0; p < u->nfit-1; p++) {\n        dot = dot_dvectors(u->uu[p],u->y,u->nterms-1);\n        for (k = 0; k < u->nterms-1; k++)\n            u->resi[k] = u->resi[k] - u->uu[p][k]*dot;\n    }\n    /*\n   * Return their sum of squares\n   */\n    return dot_dvectors(u->resi,u->resi,u->nterms-1);\n}\n\n// fwd_fit_berg_scherg.c\nbool FwdEegSphereModel::fwd_eeg_fit_berg_scherg(int   nterms,              /* Number of terms to use in the series expansion\n                                                                                    * when fitting the parameters */\n                            int   nfit,\t               /* Number of equivalent dipoles to fit */\n                            float &rv)\n/*\n      * This routine fits the Berg-Scherg equivalent spherical model\n      * dipole parameters by minimizing the difference between the\n      * actual and approximative series expansions\n      */\n{\n    bool res = false;\n    int   k;\n    double rd,R,f;\n    double simplex_size = 0.01;\n    MatrixXd simplex;\n    VectorXd func_val;\n    double ftol = 1e-9;\n    VectorXd lambda;\n    VectorXd mu;\n    int   neval;\n    int   max_eval = 1000;\n    int   report   = 1;\n    fitUser u = new_fit_user(nfit,nterms);\n\n    if (nfit < 2) {\n        printf(\"fwd_fit_berg_scherg does not work with less than two equivalent sources.\");\n        return false;\n    }\n\n    /*\n   * (1) Calculate the coefficients of the true expansion\n   */\n    for (k = 0; k < nterms; k++)\n        u->fn[k] = this->fwd_eeg_get_multi_sphere_model_coeff(k+1);\n\n    /*\n   * (2) Calculate the weighting\n   */\n    rd = R = this->layers[0].rad;\n    for (k = 1; k < this->nlayer(); k++) {\n        if (this->layers[k].rad > R)\n            R = this->layers[k].rad;\n        if (this->layers[k].rad < rd)\n            rd = this->layers[k].rad;\n    }\n    f = rd/R;\n\n#ifdef ZHANG\n    /*\n   * This is the Zhang weighting\n   */\n    for (k = 1; k < nterms; k++)\n        u->w[k-1] = pow(f,k);\n#else\n    /*\n   * This is the correct weighting\n   */\n    for (k = 1; k < nterms; k++)\n        u->w[k-1] = sqrt((2.0*k+1)*(3.0*k+1.0)/k)*pow(f,(k-1.0));\n#endif\n\n    /*\n   * (3) Prepare for simplex minimization\n   */\n    func_val = VectorXd(nfit+1);\n    lambda   = VectorXd(nfit);\n    mu       = VectorXd(nfit);\n    /*\n   * (4) Rather arbitrary initial guess\n   */\n    for (k = 0; k < nfit; k++) {\n        /*\n    mu[k] = (k+1)*0.1*f;\n     */\n        mu[k] = (rand() / (RAND_MAX + 1.0))*f;//replacement for: mu[k] = drand48()*f;\n    }\n\n    simplex = get_initial_simplex(mu,simplex_size);\n    for (k = 0; k < nfit+1; k++)\n        func_val[k] = one_step(static_cast<VectorXd>(simplex.row(k)),u);\n\n    /*\n   * (5) Do the nonlinear minimization\n   */\n    if (!(res = SimplexAlgorithm::simplex_minimize<double>( simplex,\n                                                            func_val,\n                                                            ftol,\n                                                            one_step,\n                                                            u,\n                                                            max_eval,\n                                                            neval,\n                                                            report,\n                                                            report_fit)))\n        goto out;\n\n    for (k = 0; k < nfit; k++)\n        mu[k] = simplex(0,k);\n\n    /*\n   * (6) Do the final step: calculation of the linear parameters\n   */\n    rv = compute_linear_parameters(mu,lambda,u);\n\n    sort_parameters(mu,lambda,nfit);\n#ifdef LOG_FIT\n    printf(\"RV = %g %%\\n\",100*rv);\n#endif\n    this->mu.resize(nfit);\n    this->lambda.resize(nfit);\n    this->nfit   = nfit;\n    for (k = 0; k < nfit; k++) {\n        this->mu[k] = mu[k];\n        /*\n     * This division takes into account the actual conductivities\n     */\n        this->lambda[k] = lambda[k]/this->layers[this->nlayer()-1].sigma;\n#ifdef LOG_FIT\n        printf(\"lambda%d = %g\\tmu%d = %g\\n\",k+1,lambda[k],k+1,mu[k]);\n#endif\n    }\n\n    /*\n   * This is the cleanup code\n   */\nout : {\n        if (u) {\n            FREE(u->fn);\n            FREE_DCMATRIX_1(u->M);\n            FREE_DCMATRIX_1(u->uu);\n            FREE_DCMATRIX_1(u->vv);\n            FREE(u->y);\n            FREE(u->w);\n            FREE(u->resi);\n            FREE(u->sing);\n        }\n        return res;\n    }\n}\n", "meta": {"hexsha": "cdb6cde612c2f9345b2266a9a80a10a8776fbff8", "size": 42987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fwd/fwd_eeg_sphere_model.cpp", "max_stars_repo_name": "jobehrens/mne-cpp", "max_stars_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 130.0, "max_stars_repo_stars_event_min_datetime": "2015-02-01T23:47:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T01:46:11.000Z", "max_issues_repo_path": "libraries/fwd/fwd_eeg_sphere_model.cpp", "max_issues_repo_name": "jobehrens/mne-cpp", "max_issues_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 519.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T12:44:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T18:12:52.000Z", "max_forks_repo_path": "libraries/fwd/fwd_eeg_sphere_model.cpp", "max_forks_repo_name": "jobehrens/mne-cpp", "max_forks_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 138.0, "max_forks_repo_forks_event_min_datetime": "2015-04-02T12:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T13:21:25.000Z", "avg_line_length": 29.6871546961, "max_line_length": 230, "alphanum_fraction": 0.494917068, "num_tokens": 12881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.024423088456409045, "lm_q1q2_score": 0.010693002047160682}}
{"text": "//\n// Created by Karine Miras on 21/03/2017.\n//\n\n#include <algorithm>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <random>\n#include <string>\n#include <sstream>\n#include <vector>\n\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n\n#include \"Aux.h\"\n#include \"EvolutionIndirect.h\"\n#include \"Genome.h\"\n#include \"LSystem.h\"\n#include \"Measures.h\"\n\n\n/**\n * Initializes the population with new genomes.\n * @param LS - Lsystem structure containing the alphabet.\n **/\nvoid EvolutionIndirect::initPopulation(LSystem LS)\n{\n\n  //creates new genomes according to population size\n  for (int i = 1; i <= this->params[\"pop_size\"]; i++)\n  {\n    // initial genomes receive personal ids, but the ids of the parents are none\n    Genome gen = Genome(std::to_string(this->next_id),\n                        \"N\",\n                        \"N\");\n\n\n    // creates genetic-strings for the production rules of the letters in the grammar (initial random rules)\n    gen.build_grammar(LS,\n                      this->params);\n\n    this->offspring.push_back(gen);  // adds genome to the population\n\n    // increments id that will be used for any next genome created\n    this->next_id++;\n\n  }\n}\n\n\n/**\n*   Performs crossover among individuals in the population.\n**/\n\nvoid EvolutionIndirect::crossover(\n    LSystem LS)\n{\n\n\n  // creates new individuals via crossover (size of offspring is relative to the size of population)\n  for (int i = 0;\n       i < ceil(this->params[\"pop_size\"] * this->params[\"offspring_prop\"]); i++)\n  {\n\n    // selects parents for the crossover, according to INDEX\n    int parent1 = this->tournament();\n    int parent2 = parent1;\n\n    while (parent2 == parent1)\n    { // makes sure that parent2 is different from parent1\n      parent2 = this->tournament();\n    }\n\n    // #TEST: Tests if selected parents are different.\n    this->tests.testParents(parent1,\n                            parent2);\n\n    // creates new offspring genome\n    Genome gen = Genome(std::to_string(this->next_id),\n                        this->population[parent1].getId(),\n                        this->population[parent2].getId());\n\n    this->aux.logs(\" crossover for genome \" + std::to_string(this->next_id)\n                   + \" - p1: \" + this->population[parent1].getId()\n                   + \" p2: \" + this->population[parent2].getId());\n\n    this->next_id++;\n\n    std::map< std::string, GeneticString  > grammar =\n        std::map< std::string, GeneticString  >();\n\n    std::random_device rd;\n    std::default_random_engine generator(rd());\n\n    std::uniform_real_distribution< double > prob(0.0, 1.0);\n\n    // for each letter in the grammar\n    for (const auto &letter : LS.getAlphabet())\n    {\n      if (prob(generator) <= prob(generator))\n      {\n        this->aux.logs(letter.first + \" from parent1\");\n\n        // copies object of rule from the genome parent1\n        GeneticString gsp1 = GeneticString(this->population[parent1]\n                                              .getGrammar()[letter.first]);\n        grammar.emplace(letter.first, gsp1); // gets it from parent1\n      }\n      else\n      {\n        this->aux.logs(letter.first + \" from parent2\");\n\n        // copies object of rule from the genome parent2\n        GeneticString gsp2 = GeneticString(this->population[parent2]\n                                               .getGrammar()[letter.first]);\n        grammar.emplace(letter.first, gsp2); // gets it from parent1\n      }\n    }\n\n    gen.setGrammar(grammar); // sets grammar for the new genome\n\n    this->offspring.push_back(gen); // adds new individual to the offspring\n  }\n\n\n}\n\n\n/**\n * Performs mutation to individuals of the offspring.\n * @param LS - Lsystem structure containing the alphabet.\n * @param offspring - offspring to be mutated\n */\n\nvoid EvolutionIndirect::mutation(\n    LSystem LS)\n{\n\n\n  std::random_device rd;\n  std::default_random_engine generator(rd());\n\n  // distribution for letters of the alphabet, to be possibly included\n  // (does not include position 0, which is core-component, as it should be present only once)\n  std::uniform_int_distribution< int >\n      dist_letter(1,\n                  (int) LS.getAlphabetIndex().size() - 1);\n\n  // distribution for letters of the alphabet, to be the target of the mutation\n  std::uniform_int_distribution< int >\n      dist_letter_target(0,\n                         (int) LS.getAlphabetIndex().size() - 1);\n\n  // distribution for the mounting commands\n  std::uniform_int_distribution< int >\n      dist_mountingcommand(0,\n                           (int) LS.getMountingCommands().size() - 1);\n\n  // distribution for the moving commands\n  std::uniform_int_distribution< int >\n      dist_movingcommand(0,\n                         (int) LS.getMovingCommands().size() - 1);\n\n  // distribution for the brain move commands (does not include brainperturb)\n  std::uniform_int_distribution< int >\n      dist_brainmovecommand(1,\n                            (int) LS.getBrainMoveCommands().size() - 1);\n\n  // distribution for the brain change commands\n  std::uniform_int_distribution< int >\n      dist_brainchangecommand(0,\n                              (int) LS.getBrainChangeCommands().size() - 1);\n\n  // distribution for 0-1 probabilities\n  std::uniform_real_distribution< double > prob(0.0,\n                                                1.0);\n\n\n  // for each genome of the offspring\n  for (int i = 0; i < this->offspring.size(); i++)\n  {\n\n    std::string mutate_letter = LS.getAlphabetIndex()[dist_letter_target(generator)];\n    // distribution for the type of mutation which will be performed\n    std::uniform_int_distribution< int > type_mutation(1,\n                                                       3);\n    int type_of_mutation = type_mutation(generator);\n\n\n    // mutates genome given  probability\n    if (prob(generator) <= this->params[\"mutation_prob\"])\n    {\n\n      // # deletion\n      if (type_of_mutation == 1)\n      {\n\n        //  if there is at least more than one component\n        if (this->offspring[i].getGrammar()[mutate_letter].count() > 1)\n        {\n\n          // distribution for position of deletion in the genetic-string\n          std::uniform_int_distribution< int > pos_d(1,\n                                                     this->offspring[i].getGrammar()[mutate_letter].count());\n          int pos_deletion = pos_d(generator);\n\n          // if it is the production rule of the core-component, prevents core-component from being deleted, preserving the root\n          if (mutate_letter == \"C\" and pos_deletion == 1)\n          {\n            // std::cout<<\"cant delete the the core-component from the beginning of its rule\";\n          }\n          else\n          {\n\n            this->aux.logs(\"mutation: remove in \" + this->offspring[i].getId()\n                           + \" for \" + mutate_letter\n                           + \" at \" + std::to_string(pos_deletion));\n            this->offspring[i].getGrammar()[mutate_letter].remove(pos_deletion); //\n            // removes item from chosen position\n\n          }\n        }\n\n        // # swapping\n      }\n      else if (type_of_mutation == 2)\n      {\n\n\n        // distribution for position of insertion/swap in the genetic-string\n        std::uniform_int_distribution< int > pos_s(1,\n                                                   this->offspring[i].getGrammar()[mutate_letter].count());\n\n        // position of items to be swapped in the genetic-string\n        int pos_swap1 = pos_s(generator);\n        int pos_swap2 = pos_s(generator);\n\n        while (pos_swap2 < pos_swap1)\n        {\n          pos_swap2 = pos_s(generator);\n        }  // makes sure position swap1 is before position swap2\n\n        // never swaps core component\n        if (mutate_letter == \"C\" and pos_swap1 == 1)\n        {\n          pos_swap1 = 0;\n          pos_swap2 = 0;\n        }\n\n        this->offspring[i].getGrammar()[mutate_letter].swap(pos_swap1,\n                                                       pos_swap2); // removes item from chosen position\n        this->aux.logs(\"mutation: swap in \" + this->offspring[i].getId() + \" for \" +\n                       mutate_letter\n                       + \" between \" + std::to_string(pos_swap1) + \" and \" +\n                       std::to_string(pos_swap2));\n\n\n        // # adding\n      }\n      else if (type_of_mutation == 3)\n      {\n\n        // type of item to add\n        std::uniform_int_distribution< int > type_adding(1,\n                                                         5);\n        int type_of_adding = type_adding(generator);\n        int aux =0;\n\n        std::string genetic_string_item = \"\";\n\n        // distribution for position of insertion in the genetic-string\n        std::uniform_int_distribution< int > pos_i(0,\n                                                   this->offspring[i].getGrammar()[mutate_letter].count());\n        int pos_insertion = pos_i(generator);\n\n        // if it is the production rule of the core-component, prevents new items from being inserted at the beginning, preserving the root\n        if (mutate_letter == \"C\" and pos_insertion == 0)  pos_insertion++;\n\n\n        // # adding mounting command\n        if (type_of_adding == 1)\n        {\n          aux = dist_mountingcommand(generator);\n          this->aux.logs(\n              \"mutation: add mounting command \" + LS.getMountingCommands()[aux]\n              + \" in \" + this->offspring[i].getId()\n              + \" for \" + mutate_letter + \" at \"\n              + std::to_string(pos_insertion));\n          genetic_string_item = LS.getMountingCommands()[aux];\n        }\n\n          // # adding letter\n        else if (type_of_adding == 2)\n        {\n          aux = dist_letter(generator);\n          auto letter = LS.buildBrainCommand(LS.getAlphabetIndex()[aux]);\n          this->aux.logs(\"mutation: add letter \" + letter\n                         + \" in \" + this->offspring[i].getId()\n                         + \" for \" + mutate_letter + \" at \"\n                         + std::to_string(pos_insertion));\n          genetic_string_item = letter;\n        }\n\n          // # adding moving command\n        else if (type_of_adding == 3)\n        {\n          aux = dist_movingcommand(generator);\n          this->aux.logs(\"mutation: add moving command \" + LS\n              .getMovingCommands()[aux]\n                         + \" in \" + this->offspring[i].getId()\n                         + \" for \" + mutate_letter\n                         + \" at \" + std::to_string(pos_insertion));\n          genetic_string_item = LS.getMovingCommands()[aux];\n        }\n\n          // # adding brain move command\n        else if (type_of_adding == 4)\n        {\n          aux = dist_brainmovecommand(generator);\n          std::string com = LS.buildBrainCommand(LS.getBrainMoveCommands()[aux]);\n          this->aux.logs(\"mutation: add brain move command \"\n                         + com\n                         + \" in \" + this->offspring[i].getId()\n                         + \" for \" + mutate_letter\n                         + \" at \" + std::to_string(pos_insertion));\n          genetic_string_item = com;\n        }\n\n          // # adding brain change command (topological change)\n        else if (type_of_adding == 5)\n        {\n          aux = dist_brainchangecommand(generator);\n          std::string com = LS.buildBrainCommand(LS.getBrainChangeCommands()[aux]);\n          this->aux.logs(\"mutation: add brain change command \"\n                         + com\n                         + \" in \" + this->offspring[i].getId()\n                         + \" for \" + mutate_letter\n                         + \" at \" + std::to_string(pos_insertion));\n          genetic_string_item = com;\n        }\n\n        //  (possibly) alters genetic-string (production rule) adding items (letters or commands)\n        this->offspring[i].getGrammar()[mutate_letter].add(pos_insertion,\n                                                      genetic_string_item);\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "b4f53ea514624229935c3a0b86cc9a05afdbbda0", "size": 12038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lsystem/src/EvolutionIndirect.cpp", "max_stars_repo_name": "karinemiras/l-system", "max_stars_repo_head_hexsha": "a3b75876a325a224f87a41edb208389f49b00b6e", "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": "lsystem/src/EvolutionIndirect.cpp", "max_issues_repo_name": "karinemiras/l-system", "max_issues_repo_head_hexsha": "a3b75876a325a224f87a41edb208389f49b00b6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lsystem/src/EvolutionIndirect.cpp", "max_forks_repo_name": "karinemiras/l-system", "max_forks_repo_head_hexsha": "a3b75876a325a224f87a41edb208389f49b00b6e", "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.9098591549, "max_line_length": 139, "alphanum_fraction": 0.569446752, "num_tokens": 2638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.031618768637422405, "lm_q1q2_score": 0.010689582370104166}}
{"text": "#include <execinfo.h>\n#include <libgen.h>\n#include <math.h>\n#include <pwd.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <fstream>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/regex.hpp>\n\n//#include \"cons.h\"\n#include \"util.h\"\n\nusing namespace std;\n\n\nnamespace Util {\n\tconst string& HomeDir() {\n\t\tstatic string homedir;\n\t\tif (homedir.size() == 0) {\n\t\t\tstruct passwd *pw = getpwuid(getuid());\n\t\t\thomedir = pw->pw_dir;\n\t\t}\n\t\treturn homedir;\n\t}\n\n\tstring ToYMD_HMS(const boost::posix_time::time_duration& td) {\n\t\t// in: 7027:33:44\n\t\t// out: 1y0m3d-19:33:44\n\t\tstatic const auto sep = boost::is_any_of(\":\");\n\t\tvector<string> t;\n\t\tstring s = boost::posix_time::to_simple_string(td);\n\t\tboost::split(t, s, sep);\n\n\t\tint h = atoi(t[0].c_str());\t// total hours\n\t\tint year = h / (365 * 24);\t// starts with 0\n\t\th -= (year * (365 * 24));\t// remaining hours\n\t\tconst double hours_in_month = 365.0/12*24;\n\t\tint month = int(h / hours_in_month);\t// starts with 0\n\t\th -= int(month * hours_in_month);\n\t\tint day = h / 24;\n\t\th -= (day * 24);\n\t\tint hour = h;\n\n\t\tstring out;\n\n\t\tbool started = false;\n\t\tif (year == 0 && started == false)\n\t\t\t;\n\t\telse {\n\t\t\tout += str(boost::format(\"%dy\") % year);\n\t\t\tstarted = true;\n\t\t}\n\n\t\tif (month == 0 && started == false)\n\t\t\t;\n\t\telse {\n\t\t\tout += str(boost::format(\"%dm\") % month);\n\t\t\tstarted = true;\n\t\t}\n\n\t\tif (day == 0 && started == false)\n\t\t\t;\n\t\telse {\n\t\t\tout += str(boost::format(\"%dd-\") % day);\n\t\t\tstarted = true;\n\t\t}\n\n\t\tout += str(boost::format(\"%02d:%s:%02d\") % hour % t[1] % atoi(t[2].c_str()));\n\t\treturn out;\n\t}\n\n\n\tstring Indent(const string& in, int indent) {\n\t\t//cout << \"[\" << in << \"]\\n\";\n\t\tstatic const auto sep = boost::is_any_of(\"\\n\");\n\n\t\tstring leading_spaces;\n\t\tfor (int i = 0; i < indent; i ++)\n\t\t\tleading_spaces += \" \";\n\n\t\tvector<string> tokens;\n\t\tboost::split(tokens, in, sep);\n\t\tstring out;\n\n\t\tfor (size_t i = 0; i < tokens.size(); i ++) {\n\t\t\tif (i != 0)\n\t\t\t\tout += \"\\n\";\n\t\t\tif (tokens[i].size() != 0)\n\t\t\t\tout += (leading_spaces + tokens[i]);\n\t\t}\n\n\t\treturn out;\n\t}\n\n\tstring Prepend(const string& p, const string& in) {\n\t\tstatic const auto sep = boost::is_any_of(\"\\n\");\n\t\tvector<string> tokens;\n\t\tboost::split(tokens, in, sep);\n\t\tstring out;\n\n\t\tfor (size_t i = 0; i < tokens.size(); i ++) {\n\t\t\tif ((i == tokens.size() - 1) && tokens[i].size() == 0)\n\t\t\t\tcontinue;\n\t\t\tout += (p + tokens[i] + \"\\n\");\n\t\t}\n\t\treturn out;\n\t}\n\n\t//void RunSubprocess(const string& cmd_) {\n\t//\tCons::MT _(cmd_, false);\n\t//\tstring cmd = string(\"( \") + cmd_ + \" ) 2>&1\";\n\t//\tFILE* pipe = popen(cmd.c_str(), \"r\");\n\t//\tif (! pipe)\n\t//\t\tTHROW(boost::format(\"Unable to popen: %1%\") % cmd);\n\n\t//\tchar buffer[4096];\n\t//\twhile (! feof(pipe)) {\n\t//\t\t// Print as soon as a line is available\n\t//\t\tif (fgets(buffer, sizeof(buffer), pipe))\n\t//\t\t\tCons::P(buffer);\n\t//\t}\n\t//\tpclose(pipe);\n\t//}\n\n\tvoid SetEnv(const char* k, const char* v) {\n\t\tif (setenv(k, v, 1) != 0)\n\t\t\tTHROW(boost::format(\"Unable to setenv: %s %s\") % k % v);\n\t}\n\n\tvoid SetEnv(const char* k, const string& v) {\n\t\tif (setenv(k, v.c_str(), 1) != 0)\n\t\t\tTHROW(boost::format(\"Unable to setenv: %s %s\") % k % v);\n\t}\n\n\tvoid ReadStr(std::ifstream& ifs, std::string& str) {\n\t\tsize_t s;\n\t\tifs.read((char*)&s, sizeof(s));\n\t\tstr.resize(s);\n\t\tifs.read((char*)&str[0], s);\n\t}\n\n\tconst string& SrcDir() {\n\t\tstatic string srcdir;\n\t\tif (srcdir.size() == 0) {\n\t\t\tchar file[PATH_MAX];\n\t\t\tstrcpy(file, __FILE__);\n\t\t\tsrcdir = dirname(file);\n\t\t}\n\t\treturn srcdir;\n\t}\n\n\t// http://en.wikipedia.org/wiki/Haversine_formula\n\t// http://blog.julien.cayzac.name/2008/10/arc-and-distance-between-two-points-on.html\n\n\t/** @brief Computes the arc, in radian, between two WGS-84 positions.\n\t *\n\t * The result is equal to <code>Distance(from,to)/EARTH_RADIUS_IN_METERS</code>\n\t *    <code>= 2*asin(sqrt(h(d/EARTH_RADIUS_IN_METERS )))</code>\n\t *\n\t * where:<ul>\n\t *    <li>d is the distance in meters between 'from' and 'to' positions.</li>\n\t *    <li>h is the haversine function: <code>h(x)=sin²(x/2)</code></li>\n\t * </ul>\n\t *\n\t * The haversine formula gives:\n\t *    <code>h(d/R) = h(from.lat-to.lat)+h(from.lon-to.lon)+cos(from.lat)*cos(to.lat)</code>\n\t *\n\t * @sa http://en.wikipedia.org/wiki/Law_of_haversines\n\t */\n\tdouble ArcInRadians(\n\t\t\tdouble lat0, double lon0,\n\t\t\tdouble lat1, double lon1) {\n\t\t/// @brief The usual PI/180 constant\n\t\tstatic const double DEG_TO_RAD = 0.017453292519943295769236907684886;\n\t\t/// @brief Earth's quatratic mean radius for WGS-84\n\t\t//static const double EARTH_RADIUS_IN_METERS = 6372797.560856;\n\n\t\tdouble latitudeArc  = (lat0 - lat1) * DEG_TO_RAD;\n\t\tdouble longitudeArc = (lon0 - lon1) * DEG_TO_RAD;\n\t\tdouble latitudeH = sin(latitudeArc * 0.5);\n\t\tlatitudeH *= latitudeH;\n\t\tdouble lontitudeH = sin(longitudeArc * 0.5);\n\t\tlontitudeH *= lontitudeH;\n\t\tdouble tmp = cos(lat0 * DEG_TO_RAD) * cos(lat1 * DEG_TO_RAD);\n\t\treturn 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH));\n\t}\n\n\tdouble ArcInMeters(\n\t\t\tdouble lat0, double lon0,\n\t\t\tdouble lat1, double lon1) {\n\t\tstatic const double EARTH_RADIUS_IN_METERS = 6372797.560856;\n\t\treturn EARTH_RADIUS_IN_METERS * ArcInRadians(lat0, lon0, lat1, lon1);\n\t}\n\n\t// Latitude/longitude to 3D Cartesian coordinates\n\tvoid Ll_3Dc(const double lat, const double lon, double xyz[]) {\n\t\t// http://stackoverflow.com/questions/1185408/converting-from-longitude-latitude-to-cartesian-coordinates\n\n\t\tdouble lat_r = M_PI * (lat / 180);\n\t\tdouble lon_r = M_PI * (lon / 180);\n\n\t\tstatic const double R = 1.0;\n\t\txyz[0] = R * cos(lat_r) * cos(lon_r);\n\t\txyz[1] = R * cos(lat_r) * sin(lon_r);\n\t\txyz[2] = R * sin(lat_r);\n\t}\n\n\t// http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix\n\tstring exec(const string& cmd) {\n\t\tconst int buf_size = 1024;\n\t\tchar buffer[buf_size];\n\t\tstring result = \"\";\n\t\tshared_ptr<FILE> pipe(popen(cmd.c_str(), \"r\"), pclose);\n\t\tif (!pipe) THROW(\"popen() failed!\");\n\t\twhile (!feof(pipe.get())) {\n\t\t\tif (fgets(buffer, buf_size, pipe.get()) != NULL)\n\t\t\t\tresult += buffer;\n\t\t}\n\t\treturn result;\n\t}\n\n\tstring StackTrace(int skip_innermost_stack) {\n\t\tconst int max_bufs = 32;\n\t\tvoid* buf[max_bufs];\n\t\tint buf_size = backtrace(buf, max_bufs);\n\n\t\tchar** messages = backtrace_symbols(buf, buf_size);\n\t\tstring stack_trace;\n\t\tfor (int i = skip_innermost_stack; i < buf_size; ++ i) {\n\t\t\tif (i > skip_innermost_stack)\n\t\t\t\tstack_trace += \"\\n\";\n\t\t\t//Cons::P(messages[i]);\n\n\t\t\t// Examples:\n\t\t\t//   target/simulator(_ZN10LocationDB7WhereIsERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE+0x65) [0x4b0261]\n\t\t\t//   0                1                                                                                   234        56\n\t\t\t//   There must be a new line or something at the end.\n\t\t\t//\n\t\t\t//   /lib/x86_64-linux-gnu/libc.so.6(+0x354a0) [0x7f17a1f6b4a0]\n\t\t\t//   0                               1        234              56\n\t\t\t//\n\t\t\t//   target/clusterer() [0x46b199]\n\t\t\t//   0                1234        56\n\t\t\t//   target/clusterer(_ZN9Clusterer5PointC2Ev+0xb1) [0x46d7cf]\n\t\t\t//   0                1                            234        56\n\t\t\tstatic const auto sep = boost::is_any_of(\"() \\t[]\\r\\n\");\n\t\t\tvector<string> t;\n\t\t\tstring m1(boost::trim_copy(string(messages[i])));\n\t\t\tboost::split(t, m1, sep, boost::token_compress_off);\n\t\t\tif (t.size() != 6) {\n\t\t\t\tTHROW(boost::format(\"unexpected format: %s\\nt.size()=%d\\nt=[%s]\")\n\t\t\t\t\t\t\t% messages[i] % t.size() % boost::join(t, \"\\n\"));\n\t\t\t}\n\n\t\t\tconst string& binary_file_name = t[0];\n\n\t\t\tstring decorated_function_name;\n\t\t\tif (t[1].size() > 0) {\n\t\t\t\tstatic const auto sep1 = boost::is_any_of(\"+\");\n\t\t\t\tvector<string> t1;\n\t\t\t\tboost::split(t1, t[1], sep1);\n\t\t\t\tif (t1.size() != 2) {\n\t\t\t\t\tTHROW(boost::format(\"unexpected format: %s\\nt1.size()=%d\\nt1=[%s]\")\n\t\t\t\t\t\t\t\t% messages[i] % t1.size() % boost::join(t1, \"\\n\"));\n\t\t\t\t}\n\t\t\t\tdecorated_function_name = t1[0];\n\t\t\t}\n\n\t\t\tstack_trace += messages[i];\n\t\t\tstack_trace += \"\\n\";\n\t\t\t//Cons::P(boost::format(\"DF: %s\") % decorated_function_name);\n\n\t\t\tif (decorated_function_name.size() > 0) {\n\t\t\t\t// c++filt _ZN10LocationDB7WhereIsERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE\n\t\t\t\tstack_trace += Util::Indent(boost::trim_copy(Util::exec(str(boost::format(\"c++filt %s\") % decorated_function_name))), 2);\n\t\t\t\tstack_trace += \"\\n\";\n\t\t\t}\n\n\t\t\tstring addr = t[4];\n\t\t\t//Cons::P(boost::format(\"addr: %s\") % addr);\n\t\t\tif (addr.size() > 0) {\n\t\t\t\tstack_trace += Util::Indent(boost::trim_copy(Util::exec(str(boost::format(\"addr2line -e %s %s\") % binary_file_name % addr))), 2);\n\t\t\t}\n\n\t\t\tstack_trace += \"\\n\";\n\t\t}\n\n\t\treturn stack_trace;\n\t}\n\n\tstring CurDateTime() {\n\t\ttime_t     now = time(0);\n\t\tstruct tm  tm_;\n\t\tchar       buf[80];\n\t\ttm_ = *localtime(&now);\n\t\t//strftime(buf, sizeof(buf), \"%m%d-%H%M%S\", &tm_);\n\t\tstrftime(buf, sizeof(buf), \"%m%d-%H%M\", &tm_);\n\n\t\t// Add seconds and milliseconds.\n\t\tstruct timeval tp;\n\t\tgettimeofday(&tp, NULL);\n\t\t//long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;\n\t\treturn str(boost::format(\"%s%02d.%03d\")\n\t\t\t% buf\n\t\t\t% (tp.tv_sec % 60)\n\t\t\t% (tp.tv_usec / 1000));\n\t}\n\n\tstring BuildHeader(const string& fmt, const string& column_names) {\n\t\t// Float, integer, or string\n\t\tstatic const boost::regex e(\"%(([-+]?[0-9]*\\\\.?[0-9]*f)|([-+]?[0-9]*d)|([-+]?[0-9]*s))\");\n\n\t\tboost::smatch m;\n\t\tstring fmt0 = fmt;\n\t\tvector<size_t> name_end_pos;\n\t\tsize_t nep = 0;\n\t\twhile (boost::regex_search(fmt0, m, e)) {\n\t\t\tif (m.size() == 0)\n\t\t\t\tTHROW(\"Unexpected\");\n\t\t\tif (nep != 0)\n\t\t\t\tnep ++;\n\t\t\tnep += abs(atoi(m[0].str().c_str() + 1));\n\t\t\tname_end_pos.push_back(nep);\n\t\t\tfmt0 = m.suffix();\n\t\t}\n\n\t\t//cout << \"name_end_pos:\\n\";\n\t\t//for (int i: name_end_pos)\n\t\t//\tcout << i << \" \";\n\t\t//cout << \"\\n\";\n\n\t\tvector<string> names;\n\t\tstatic const auto sep = boost::is_any_of(\" \");\n\t\tboost::split(names, column_names, sep, boost::token_compress_on);\n\t\t//string names_flat(\"#\");\n\t\t//for (auto n: names)\n\t\t//\tnames_flat += (\" \" + n);\n\t\t//names_flat += \"\\n\";\n\t\t//names_flat += \"#\\n\";\n\n\t\t// Header lines\n\t\tvector<string> lines;\n\t\tfor (size_t i = 0; i < names.size(); i ++) {\n\t\t\tbool fit = false;\n\t\t\tfor (auto& l: lines) {\n\t\t\t\tif (l.size() + 1 + names[i].size() > name_end_pos[i])\n\t\t\t\t\tcontinue;\n\n\t\t\t\twhile (l.size() + 1 + names[i].size() < name_end_pos[i])\n\t\t\t\t\tl += \" \";\n\t\t\t\tl += (\" \" + names[i]);\n\t\t\t\tfit = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (fit)\n\t\t\t\tcontinue;\n\n\t\t\tstring l(\"#\");\n\t\t\twhile (l.size() + 1 + names[i].size() < name_end_pos[i])\n\t\t\t\tl += \" \";\n\t\t\tl += (\" \" + names[i]);\n\t\t\tlines.push_back(l);\n\t\t}\n\n\t\t// Indices for names starting from 1 for easy gnuplot indexing\n\t\tvector<string> ilines;\n\t\tfor (size_t i = 0; i < names.size(); i ++) {\n\t\t\tstring idxstr = str(boost::format(\"%d\") % (i + 1));\n\t\t\tbool fit = false;\n\t\t\tfor (auto& l: ilines) {\n\t\t\t\tif (l.size() + 1 + idxstr.size() > name_end_pos[i])\n\t\t\t\t\tcontinue;\n\n\t\t\t\twhile (l.size() + 1 + idxstr.size() < name_end_pos[i])\n\t\t\t\t\tl += \" \";\n\t\t\t\tl += (\" \" + idxstr);\n\t\t\t\tfit = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (fit)\n\t\t\t\tcontinue;\n\n\t\t\tstring l(\"#\");\n\t\t\twhile (l.size() + 1 + idxstr.size() < name_end_pos[i])\n\t\t\t\tl += \" \";\n\t\t\tl += (\" \" + idxstr);\n\t\t\tilines.push_back(l);\n\t\t}\n\n\t\t//string header = names_flat;\n\t\tstring header;\n\t\tfor (auto l: lines)\n\t\t\theader += (l + \"\\n\");\n\t\tfor (auto l: ilines)\n\t\t\theader += l;\n\n\t\treturn header;\n\t}\n};\n\n\n_Error::_Error(const std::string& s, const char* file_name_, const int line_no_)\n: runtime_error(s), file_name(file_name_), line_no(line_no_)\n{\n\t_Init();\n}\n\n_Error::_Error(boost::format& f, const char* file_name_, const int line_no_)\n: runtime_error(str(f)), file_name(file_name_), line_no(line_no_)\n{\n\t_Init();\n}\n\nvoid _Error::_Init() {\n\t// Stack trace skips the innermost 3 functions, StackTrace(), _Init(), and\n\t// _Error().\n\t_what = str(boost::format(\"%s\\n%s\")\n\t\t\t% runtime_error::what()\n\t\t\t% Util::Indent(Util::StackTrace(3), 2));\n}\n\nconst char* _Error::what() const noexcept {\n\treturn _what.c_str();\n}\n", "meta": {"hexsha": "28ffd0c4cd4546304777707641502a9bb45590ef", "size": 11745, "ext": "cc", "lang": "C++", "max_stars_repo_path": "util/util.cc", "max_stars_repo_name": "hobinyoon/mutant-rocksdb", "max_stars_repo_head_hexsha": "0cc2ecd83ed1fa8fd9c6a75ed3d7881bf4e504d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/util.cc", "max_issues_repo_name": "hobinyoon/mutant-rocksdb", "max_issues_repo_head_hexsha": "0cc2ecd83ed1fa8fd9c6a75ed3d7881bf4e504d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/util.cc", "max_forks_repo_name": "hobinyoon/mutant-rocksdb", "max_forks_repo_head_hexsha": "0cc2ecd83ed1fa8fd9c6a75ed3d7881bf4e504d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T15:06:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T09:08:46.000Z", "avg_line_length": 27.3139534884, "max_line_length": 133, "alphanum_fraction": 0.5934440187, "num_tokens": 3855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.02800752030174629, "lm_q1q2_score": 0.010677015135133701}}
{"text": "//=============================================================================================================\n/**\n * @file     signalmodel.cpp\n * @author   Ruben Dörfel <doerfelruben@aol.com>\n * @since    0.1.9\n * @date     December, 2021\n *\n * @section  LICENSE\n *\n * Copyright (C) 2021, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n *       following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n *       the following disclaimer in the documentation and/or other materials provided with the distribution.\n *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n *       to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief    signalModel class definition.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"hpimodelparameters.h\"\n#include \"signalmodel.h\"\n#include <utils/mnemath.h>\n#include <iostream>\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <qmath.h>\n\n//=============================================================================================================\n// EIGEN INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Core>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace INVERSELIB;\nusing namespace Eigen;\n\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nMatrixXd SignalModel::fitData(const HpiModelParameters& hpiModelParameters, const MatrixXd& matData)\n{\n\n    if(checkEmpty(hpiModelParameters)) {\n        return MatrixXd();\n    }\n\n    const bool bParametersChanged = m_modelParameters != hpiModelParameters;\n    const bool bDimensionsChanged = m_iCurrentModelCols != matData.cols();\n\n    if(bDimensionsChanged || bParametersChanged) {\n        m_iCurrentModelCols = matData.cols();\n        m_modelParameters = hpiModelParameters;\n        selectModelAndCompute();\n    }\n\n    return m_matInverseSignalModel * matData.transpose();\n}\n\n//=============================================================================================================\n\nbool SignalModel::checkDataDimensions(const int iCols)\n{\n    bool bHasChanged = false;\n    if(iCols != m_iCurrentModelCols) {\n        m_iCurrentModelCols = iCols;\n        bHasChanged = true;\n    }\n    return bHasChanged;\n}\n\n//=============================================================================================================\n\nbool SignalModel::checkModelParameters(const HpiModelParameters& hpiModelParameters)\n{\n    bool bHasChanged = false;\n    if((m_modelParameters.iSampleFreq() != hpiModelParameters.iSampleFreq()) ||\n        (m_modelParameters.iLineFreq() != hpiModelParameters.iLineFreq()) ||\n        (m_modelParameters.iNHpiCoils() != hpiModelParameters.iNHpiCoils()) ||\n        (m_modelParameters.vecHpiFreqs() != hpiModelParameters.vecHpiFreqs()) ||\n        (m_modelParameters.bBasic() != hpiModelParameters.bBasic())) {\n        bHasChanged = true;\n        m_modelParameters = hpiModelParameters;\n    }\n    return bHasChanged;\n}\n\n//=============================================================================================================\n\nbool SignalModel::checkEmpty(const HpiModelParameters& hpiModelParameters)\n{\n    if(hpiModelParameters.vecHpiFreqs().empty()) {\n        std::cout << \"SignalModel::checkEmpty - no Hpi frequencies set\" << std::endl;\n        return true;\n    } else if(hpiModelParameters.iSampleFreq() == 0) {\n        std::cout << \"SignalModel::checkEmpty - no sampling frequencies set\" << std::endl;\n        return true;\n    }\n    return false;\n}\n\n//=============================================================================================================\n\nvoid SignalModel::selectModelAndCompute()\n{\n    if(m_modelParameters.bBasic()) {\n        computeInverseBasicModel();\n    } else {\n        computeInverseAdvancedModel();\n    }\n}\n\n//=============================================================================================================\n\nvoid SignalModel::computeInverseBasicModel()\n{\n    const int iNumCoils = m_modelParameters.iNHpiCoils();\n    MatrixXd matSimsig;\n    const VectorXd vecTime = VectorXd::LinSpaced(m_iCurrentModelCols, 0, m_iCurrentModelCols-1) *1.0/m_modelParameters.iSampleFreq();\n\n    // Generate simulated data Matrix\n    matSimsig.conservativeResize(m_iCurrentModelCols,iNumCoils*2);\n\n    for(int i = 0; i < iNumCoils; ++i) {\n        matSimsig.col(i) = sin(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());\n        matSimsig.col(i+iNumCoils) = cos(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());\n    }\n    m_matInverseSignalModel = UTILSLIB::MNEMath::pinv(matSimsig);\n}\n\n//=============================================================================================================\n\nvoid SignalModel::computeInverseAdvancedModel()\n{\n    const int iNumCoils = m_modelParameters.iNHpiCoils();\n    const int iSampleFreq = m_modelParameters.iSampleFreq();\n    MatrixXd matSimsig;\n    MatrixXd matSimsigInvTemp;\n\n    const VectorXd vecTime = VectorXd::LinSpaced(m_iCurrentModelCols, 0, m_iCurrentModelCols-1) *1.0/iSampleFreq;\n\n    // add linefreq + harmonics + DC part to model\n    matSimsig.conservativeResize(m_iCurrentModelCols,iNumCoils*4+2);\n    for(int i = 0; i < iNumCoils; ++i) {\n        matSimsig.col(i) = sin(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());\n        matSimsig.col(i+iNumCoils) = cos(2*M_PI*m_modelParameters.vecHpiFreqs()[i]*vecTime.array());\n        matSimsig.col(i+2*iNumCoils) = sin(2*M_PI*m_modelParameters.iLineFreq()*(i+1)*vecTime.array());\n        matSimsig.col(i+3*iNumCoils) = cos(2*M_PI*m_modelParameters.iLineFreq()*(i+1)*vecTime.array());\n    }\n    matSimsig.col(iNumCoils*4) = RowVectorXd::LinSpaced(m_iCurrentModelCols, -0.5, 0.5);\n    matSimsig.col(iNumCoils*4+1).fill(1);\n    matSimsigInvTemp = UTILSLIB::MNEMath::pinv(matSimsig);\n    m_matInverseSignalModel = matSimsigInvTemp.block(0,0,iNumCoils*2,m_iCurrentModelCols);\n}\n", "meta": {"hexsha": "99c60127b7ed53d82909ff905b282403234db1e7", "size": 8115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/inverse/hpiFit/signalmodel.cpp", "max_stars_repo_name": "Zeitproblem/mne-cpp", "max_stars_repo_head_hexsha": "38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2", "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/inverse/hpiFit/signalmodel.cpp", "max_issues_repo_name": "Zeitproblem/mne-cpp", "max_issues_repo_head_hexsha": "38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/inverse/hpiFit/signalmodel.cpp", "max_forks_repo_name": "Zeitproblem/mne-cpp", "max_forks_repo_head_hexsha": "38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2", "max_forks_repo_licenses": ["BSD-3-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.8648648649, "max_line_length": 133, "alphanum_fraction": 0.5314849045, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961697, "lm_q2_score": 0.024798162808180795, "lm_q1q2_score": 0.010666864344048291}}
{"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 <vector>\n\n// Third party includes\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n#include <votca/tools/elements.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/aobasis.h\"\n#include \"votca/xtp/aomatrix.h\"\n#include \"votca/xtp/aomatrix3d.h\"\n#include \"votca/xtp/aopotential.h\"\n#include \"votca/xtp/density_integration.h\"\n#include \"votca/xtp/dftengine.h\"\n#include \"votca/xtp/eeinteractor.h\"\n#include \"votca/xtp/logger.h\"\n#include \"votca/xtp/mmregion.h\"\n#include \"votca/xtp/orbitals.h\"\n#include \"votca/xtp/qmmolecule.h\"\n\nusing boost::format;\nusing namespace boost::filesystem;\nusing namespace std;\nusing std::flush;\nusing namespace votca::tools;\n\nnamespace votca {\nnamespace xtp {\n\nvoid DFTEngine::Initialize(Property& options) {\n\n  string key = \"package\";\n  const string key_xtpdft = \"package.xtpdft\";\n  _dftbasis_name = options.get(key + \".basisset\").as<string>();\n\n  if (options.get(key + \".use_auxbasisset\").as<bool>()) {\n    _auxbasis_name = options.get(key + \".auxbasisset\").as<string>();\n  }\n\n  _four_center_method =\n      options.get(key_xtpdft + \".four_center_method\").as<std::string>();\n\n  if (_four_center_method != \"RI\") {\n    _with_screening = options.get(key_xtpdft + \".with_screening\").as<bool>();\n    _screening_eps = options.get(key_xtpdft + \".screening_eps\").as<double>();\n  }\n\n  if (options.get(key + \".use_ecp\").as<bool>()) {\n    _ecp_name = options.get(key + \".ecp\").as<string>();\n    _with_ecp = true;\n  } else {\n    _with_ecp = false;\n  }\n  _with_guess = options.get(key + \".read_guess\").as<bool>();\n  _initial_guess = options.get(key_xtpdft + \".initial_guess\").as<string>();\n\n  _grid_name = options.get(key_xtpdft + \".integration_grid\").as<string>();\n  _xc_functional_name = options.get(key + \".functional\").as<string>();\n\n  if (options.get(key_xtpdft + \".use_external_density\").as<bool>()) {\n    _integrate_ext_density = true;\n    _orbfilename = options.ifExistsReturnElseThrowRuntimeError<string>(\n        key_xtpdft + \".externaldensity.orbfile\");\n    _gridquality = options.ifExistsReturnElseThrowRuntimeError<string>(\n        key_xtpdft + \".externaldensity.gridquality\");\n    _state = options.ifExistsReturnElseThrowRuntimeError<string>(\n        key_xtpdft + \".externaldensity.state\");\n  }\n\n  if (options.get(key_xtpdft + \".use_external_field\").as<bool>()) {\n    _integrate_ext_field = true;\n\n    _extfield = options.ifExistsReturnElseThrowRuntimeError<Eigen::Vector3d>(\n        key_xtpdft + \".externalfield\");\n  }\n\n  _conv_opt.Econverged =\n      options.get(key_xtpdft + \".convergence.energy\").as<double>();\n  _conv_opt.error_converged =\n      options.get(key_xtpdft + \".convergence.error\").as<double>();\n  _max_iter =\n      options.get(key_xtpdft + \".convergence.max_iterations\").as<Index>();\n\n  string method = options.get(key_xtpdft + \".convergence.method\").as<string>();\n  if (method == \"DIIS\") {\n    _conv_opt.usediis = true;\n  } else if (method == \"mixing\") {\n    _conv_opt.usediis = false;\n  }\n  if (!_conv_opt.usediis) {\n    _conv_opt.histlength = 1;\n    _conv_opt.maxout = false;\n  }\n  _conv_opt.mixingparameter =\n      options.get(key_xtpdft + \".convergence.mixing\").as<double>();\n  _conv_opt.levelshift =\n      options.get(key_xtpdft + \".convergence.levelshift\").as<double>();\n  _conv_opt.levelshiftend =\n      options.get(key_xtpdft + \".convergence.levelshift_end\").as<double>();\n  _conv_opt.maxout =\n      options.get(key_xtpdft + \".convergence.DIIS_maxout\").as<bool>();\n  _conv_opt.histlength =\n      options.get(key_xtpdft + \".convergence.DIIS_length\").as<Index>();\n  _conv_opt.diis_start =\n      options.get(key_xtpdft + \".convergence.DIIS_start\").as<double>();\n  _conv_opt.adiis_start =\n      options.get(key_xtpdft + \".convergence.ADIIS_start\").as<double>();\n\n  return;\n}\n\nvoid DFTEngine::PrintMOs(const Eigen::VectorXd& MOEnergies, Log::Level level) {\n  XTP_LOG(level, *_pLog) << \"  Orbital energies: \" << flush;\n  XTP_LOG(level, *_pLog) << \"  index occupation energy(Hartree) \" << flush;\n  for (Index i = 0; i < MOEnergies.size(); i++) {\n    Index occupancy = 0;\n    if (i < _numofelectrons / 2) {\n      occupancy = 2;\n    }\n    XTP_LOG(level, *_pLog) << (boost::format(\" %1$5d      %2$1d   %3$+1.10f\") %\n                               i % occupancy % MOEnergies(i))\n                                  .str()\n                           << flush;\n  }\n  return;\n}\n\nvoid DFTEngine::CalcElDipole(const Orbitals& orb) const {\n  QMState state = QMState(\"n\");\n  Eigen::Vector3d result = orb.CalcElDipole(state);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Electric Dipole is[e*bohr]:\\n\\t\\t dx=\" << result[0]\n      << \"\\n\\t\\t dy=\" << result[1] << \"\\n\\t\\t dz=\" << result[2] << flush;\n  return;\n}\n\nMat_p_Energy DFTEngine::CalcEXXs(const Eigen::MatrixXd& MOCoeff,\n                                 const Eigen::MatrixXd& Dmat) const {\n  if (_four_center_method == \"RI\") {\n    if (_conv_accelerator.getUseMixing() || MOCoeff.rows() == 0) {\n      return _ERIs.CalculateEXX(Dmat);\n    } else {\n      Eigen::MatrixXd occblock =\n          MOCoeff.block(0, 0, MOCoeff.rows(), _numofelectrons / 2);\n      return _ERIs.CalculateEXX(occblock, Dmat);\n    }\n  } else {\n    if (_four_center_method == \"direct\") {\n      throw std::runtime_error(\n          \"direct 4c method only works with LDA and GGA functionals.\");\n    }\n    return _ERIs.CalculateEXX_4c_small_molecule(Dmat);\n  }\n}\n\ntools::EigenSystem DFTEngine::IndependentElectronGuess(\n    const Mat_p_Energy& H0) const {\n  return _conv_accelerator.SolveFockmatrix(H0.matrix());\n}\n\ntools::EigenSystem DFTEngine::ModelPotentialGuess(\n    const Mat_p_Energy& H0, const QMMolecule& mol,\n    const Vxc_Potential<Vxc_Grid>& vxcpotential) const {\n  Eigen::MatrixXd Dmat = AtomicGuess(mol);\n  Mat_p_Energy ERIs = CalculateERIs(Dmat);\n  Mat_p_Energy e_vxc = vxcpotential.IntegrateVXC(Dmat);\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Filled DFT Vxc matrix \" << flush;\n\n  Eigen::MatrixXd H = H0.matrix() + ERIs.matrix() + e_vxc.matrix();\n  if (_ScaHFX > 0) {\n    Mat_p_Energy EXXs = CalcEXXs(Eigen::MatrixXd::Zero(0, 0), Dmat);\n    H -= 0.5 * _ScaHFX * EXXs.matrix();\n  }\n  return _conv_accelerator.SolveFockmatrix(H);\n}\n\nbool DFTEngine::Evaluate(Orbitals& orb) {\n  Prepare(orb.QMAtoms());\n  Mat_p_Energy H0 = SetupH0(orb.QMAtoms());\n  tools::EigenSystem MOs;\n  MOs.eigenvalues() = Eigen::VectorXd::Zero(H0.cols());\n  MOs.eigenvectors() = Eigen::MatrixXd::Zero(H0.rows(), H0.cols());\n  Vxc_Potential<Vxc_Grid> vxcpotential = SetupVxc(orb.QMAtoms());\n  ConfigOrbfile(orb);\n\n  if (_with_guess) {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Reading guess from orbitals object/file\" << flush;\n    MOs = orb.MOs();\n    MOs.eigenvectors() = OrthogonalizeGuess(MOs.eigenvectors());\n  } else {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Setup Initial Guess using: \" << _initial_guess\n        << flush;\n    if (_initial_guess == \"independent\") {\n      MOs = IndependentElectronGuess(H0);\n    } else if (_initial_guess == \"atom\") {\n      MOs = ModelPotentialGuess(H0, orb.QMAtoms(), vxcpotential);\n    } else {\n      throw std::runtime_error(\"Initial guess method not known/implemented\");\n    }\n  }\n\n  Eigen::MatrixXd Dmat = _conv_accelerator.DensityMatrix(MOs);\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Guess Matrix gives N=\" << std::setprecision(9)\n      << Dmat.cwiseProduct(_dftAOoverlap.Matrix()).sum() << \" electrons.\"\n      << flush;\n\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" STARTING SCF cycle\" << flush;\n  XTP_LOG(Log::error, *_pLog)\n      << \" ----------------------------------------------\"\n         \"----------------------------\"\n      << flush;\n\n  for (Index this_iter = 0; this_iter < _max_iter; this_iter++) {\n    XTP_LOG(Log::error, *_pLog) << flush;\n    XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Iteration \" << this_iter + 1\n                                << \" of \" << _max_iter << flush;\n\n    Mat_p_Energy e_vxc = vxcpotential.IntegrateVXC(Dmat);\n    XTP_LOG(Log::info, *_pLog)\n        << TimeStamp() << \" Filled DFT Vxc matrix \" << flush;\n\n    Mat_p_Energy ERIs = CalculateERIs(Dmat);\n    Eigen::MatrixXd H = H0.matrix() + ERIs.matrix() + e_vxc.matrix();\n    double Eone = Dmat.cwiseProduct(H0.matrix()).sum();\n    double Etwo = 0.5 * ERIs.energy() + e_vxc.energy();\n    double exx = 0.0;\n    if (_ScaHFX > 0) {\n      Mat_p_Energy EXXs = CalcEXXs(MOs.eigenvectors(), Dmat);\n      XTP_LOG(Log::info, *_pLog)\n          << TimeStamp() << \" Filled DFT Electron exchange matrix\" << flush;\n      H -= 0.5 * _ScaHFX * EXXs.matrix();\n      exx = -_ScaHFX / 4 * EXXs.energy();\n    }\n    Etwo += exx;\n    double totenergy = Eone + H0.energy() + Etwo;\n    XTP_LOG(Log::info, *_pLog) << TimeStamp() << \" Single particle energy \"\n                               << std::setprecision(12) << Eone << flush;\n    XTP_LOG(Log::info, *_pLog) << TimeStamp() << \" Two particle energy \"\n                               << std::setprecision(12) << Etwo << flush;\n    XTP_LOG(Log::info, *_pLog)\n        << TimeStamp() << std::setprecision(12) << \" Local Exc contribution \"\n        << e_vxc.energy() << flush;\n    if (_ScaHFX > 0) {\n      XTP_LOG(Log::info, *_pLog)\n          << TimeStamp() << std::setprecision(12)\n          << \" Non local Ex contribution \" << exx << flush;\n    }\n    XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Total Energy \"\n                                << std::setprecision(12) << totenergy << flush;\n\n    Dmat = _conv_accelerator.Iterate(Dmat, H, MOs, totenergy);\n\n    PrintMOs(MOs.eigenvalues(), Log::info);\n\n    XTP_LOG(Log::info, *_pLog) << \"\\t\\tGAP \"\n                               << MOs.eigenvalues()(_numofelectrons / 2) -\n                                      MOs.eigenvalues()(_numofelectrons / 2 - 1)\n                               << flush;\n\n    if (_conv_accelerator.isConverged()) {\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" Total Energy has converged to \"\n          << std::setprecision(9) << _conv_accelerator.getDeltaE()\n          << \"[Ha] after \" << this_iter + 1\n          << \" iterations. DIIS error is converged up to \"\n          << _conv_accelerator.getDIIsError() << flush;\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" Final Single Point Energy \"\n          << std::setprecision(12) << totenergy << \" Ha\" << flush;\n      XTP_LOG(Log::error, *_pLog) << TimeStamp() << std::setprecision(12)\n                                  << \" Final Local Exc contribution \"\n                                  << e_vxc.energy() << \" Ha\" << flush;\n      if (_ScaHFX > 0) {\n        XTP_LOG(Log::error, *_pLog)\n            << TimeStamp() << std::setprecision(12)\n            << \" Final Non Local Ex contribution \" << exx << \" Ha\" << flush;\n      }\n\n      Mat_p_Energy EXXs = CalcEXXs(MOs.eigenvectors(), Dmat);\n      exx = -1.0 / 4.0 * EXXs.energy();\n      XTP_LOG(Log::error, *_pLog) << TimeStamp() << std::setprecision(12)\n                                  << \" EXX energy \" << exx << \" Ha\" << flush;\n\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << std::setprecision(12) << \" Final EXX Total energy \"\n          << totenergy - e_vxc.energy() + (1.0 - _ScaHFX) * exx << \" Ha\"\n          << flush;\n\n      PrintMOs(MOs.eigenvalues(), Log::error);\n      orb.setQMEnergy(totenergy);\n      orb.MOs() = MOs;\n      CalcElDipole(orb);\n      break;\n    } else if (this_iter == _max_iter - 1) {\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" DFT calculation has not converged after \"\n          << _max_iter\n          << \" iterations. Use more iterations or another convergence \"\n             \"acceleration scheme.\"\n          << std::flush;\n      return false;\n    }\n  }\n  return true;\n}\n\nMat_p_Energy DFTEngine::SetupH0(const QMMolecule& mol) const {\n\n  AOKinetic dftAOkinetic;\n\n  dftAOkinetic.Fill(_dftbasis);\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Filled DFT Kinetic energy matrix .\" << flush;\n\n  AOMultipole dftAOESP;\n  dftAOESP.FillPotential(_dftbasis, mol);\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Filled DFT nuclear potential matrix.\" << flush;\n\n  Eigen::MatrixXd H0 = dftAOkinetic.Matrix() + dftAOESP.Matrix();\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Constructed independent particle hamiltonian \"\n      << flush;\n  double E0 = NuclearRepulsion(mol);\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Nuclear Repulsion Energy is \"\n                              << std::setprecision(9) << E0 << flush;\n\n  if (_with_ecp) {\n    AOECP dftAOECP;\n    dftAOECP.FillPotential(_dftbasis, _ecp);\n    H0 += dftAOECP.Matrix();\n    XTP_LOG(Log::info, *_pLog)\n        << TimeStamp() << \" Filled DFT ECP matrix\" << flush;\n  }\n\n  if (_addexternalsites) {\n    XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" \" << _externalsites->size()\n                                << \" External sites\" << flush;\n    if (_externalsites->size() < 200) {\n      XTP_LOG(Log::error, *_pLog)\n          << \" Name      Coordinates[a0]     charge[e]         dipole[e*a0]    \"\n             \"              quadrupole[e*a0^2]         \"\n          << flush;\n\n      for (const std::unique_ptr<StaticSite>& site : *_externalsites) {\n        std::string output =\n            (boost::format(\"  %1$s\"\n                           \"   %2$+1.4f %3$+1.4f %4$+1.4f\"\n                           \"   %5$+1.4f\") %\n             site->getElement() % site->getPos()[0] % site->getPos()[1] %\n             site->getPos()[2] % site->getCharge())\n                .str();\n        const Eigen::Vector3d& dipole = site->getDipole();\n        output += (boost::format(\"   %1$+1.4f %2$+1.4f %3$+1.4f\") % dipole[0] %\n                   dipole[1] % dipole[2])\n                      .str();\n        if (site->getRank() > 1) {\n          Eigen::VectorXd quadrupole = site->Q().tail<5>();\n          output += (boost::format(\n                         \"   %1$+1.4f %2$+1.4f %3$+1.4f %4$+1.4f %5$+1.4f\") %\n                     quadrupole[0] % quadrupole[1] % quadrupole[2] %\n                     quadrupole[3] % quadrupole[4])\n                        .str();\n        }\n        XTP_LOG(Log::error, *_pLog) << output << flush;\n      }\n    }\n\n    Mat_p_Energy ext_multipoles =\n        IntegrateExternalMultipoles(mol, *_externalsites);\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Nuclei-external site interaction energy \"\n        << std::setprecision(9) << ext_multipoles.energy() << flush;\n    E0 += ext_multipoles.energy();\n    H0 += ext_multipoles.matrix();\n  }\n\n  if (_integrate_ext_density) {\n    Orbitals extdensity;\n    extdensity.ReadFromCpt(_orbfilename);\n    Mat_p_Energy extdensity_result = IntegrateExternalDensity(mol, extdensity);\n    E0 += extdensity_result.energy();\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Nuclei- external density interaction energy \"\n        << std::setprecision(9) << extdensity_result.energy() << flush;\n    H0 += extdensity_result.matrix();\n  }\n\n  if (_integrate_ext_field) {\n\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Integrating external electric field with F[Hrt]=\"\n        << _extfield.transpose() << flush;\n    H0 += IntegrateExternalField(mol);\n  }\n\n  return Mat_p_Energy(E0, H0);\n}\n\nvoid DFTEngine::SetupInvariantMatrices() {\n\n  _dftAOoverlap.Fill(_dftbasis);\n\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Filled DFT Overlap matrix.\" << flush;\n\n  _conv_opt.numberofelectrons = _numofelectrons;\n  _conv_accelerator.Configure(_conv_opt);\n  _conv_accelerator.setLogger(_pLog);\n  _conv_accelerator.setOverlap(_dftAOoverlap, 1e-8);\n  _conv_accelerator.PrintConfigOptions();\n\n  if (_four_center_method == \"RI\") {\n    // prepare invariant part of electron repulsion integrals\n    _ERIs.Initialize(_dftbasis, _auxbasis);\n    XTP_LOG(Log::info, *_pLog)\n        << TimeStamp() << \" Inverted AUX Coulomb matrix, removed \"\n        << _ERIs.Removedfunctions() << \" functions from aux basis\" << flush;\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp()\n        << \" Setup invariant parts of Electron Repulsion integrals \" << flush;\n  } else {\n\n    if (_four_center_method == \"cache\") {\n\n      XTP_LOG(Log::info, *_pLog)\n          << TimeStamp() << \" Calculating 4c integrals. \" << flush;\n      _ERIs.Initialize_4c_small_molecule(_dftbasis);\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" Calculated 4c integrals. \" << flush;\n    }\n\n    if (_with_screening && _four_center_method == \"direct\") {\n      XTP_LOG(Log::info, *_pLog)\n          << TimeStamp() << \" Calculating 4c diagonals. \" << flush;\n      _ERIs.Initialize_4c_screening(_dftbasis, _screening_eps);\n      XTP_LOG(Log::info, *_pLog)\n          << TimeStamp() << \" Calculated 4c diagonals. \" << flush;\n    }\n  }\n\n  return;\n}\n\nEigen::MatrixXd DFTEngine::RunAtomicDFT_unrestricted(\n    const QMAtom& uniqueAtom) const {\n  bool with_ecp = _with_ecp;\n  if (uniqueAtom.getElement() == \"H\" || uniqueAtom.getElement() == \"He\") {\n    with_ecp = false;\n  }\n\n  QMMolecule atom = QMMolecule(\"individual_atom\", 0);\n  atom.push_back(uniqueAtom);\n\n  BasisSet basisset;\n  basisset.Load(_dftbasis_name);\n  AOBasis dftbasis;\n  dftbasis.Fill(basisset, atom);\n  Vxc_Grid grid;\n  grid.GridSetup(_grid_name, atom, dftbasis);\n  Vxc_Potential<Vxc_Grid> gridIntegration(grid);\n  gridIntegration.setXCfunctional(_xc_functional_name);\n\n  ECPAOBasis ecp;\n  if (with_ecp) {\n    ECPBasisSet ecps;\n    ecps.Load(_ecp_name);\n    ecp.Fill(ecps, atom);\n  }\n\n  Index numofelectrons = uniqueAtom.getNuccharge();\n  Index alpha_e = 0;\n  Index beta_e = 0;\n\n  if ((numofelectrons % 2) != 0) {\n    alpha_e = numofelectrons / 2 + numofelectrons % 2;\n    beta_e = numofelectrons / 2;\n  } else {\n    alpha_e = numofelectrons / 2;\n    beta_e = alpha_e;\n  }\n\n  AOOverlap dftAOoverlap;\n  AOKinetic dftAOkinetic;\n  AOMultipole dftAOESP;\n  AOECP dftAOECP;\n  ERIs ERIs_atom;\n\n  // DFT AOOverlap matrix\n\n  dftAOoverlap.Fill(dftbasis);\n  dftAOkinetic.Fill(dftbasis);\n\n  dftAOESP.FillPotential(dftbasis, atom);\n  ERIs_atom.Initialize_4c_small_molecule(dftbasis);\n\n  ConvergenceAcc Convergence_alpha;\n  ConvergenceAcc Convergence_beta;\n  ConvergenceAcc::options opt_alpha = _conv_opt;\n  opt_alpha.mode = ConvergenceAcc::KSmode::open;\n  opt_alpha.histlength = 20;\n  opt_alpha.levelshift = 0.1;\n  opt_alpha.levelshiftend = 0.0;\n  opt_alpha.usediis = true;\n  opt_alpha.adiis_start = 0.0;\n  opt_alpha.diis_start = 0.0;\n  opt_alpha.numberofelectrons = alpha_e;\n\n  ConvergenceAcc::options opt_beta = opt_alpha;\n  opt_beta.numberofelectrons = beta_e;\n\n  Logger log;\n  Convergence_alpha.Configure(opt_alpha);\n  Convergence_alpha.setLogger(&log);\n  Convergence_alpha.setOverlap(dftAOoverlap, 1e-8);\n  Convergence_beta.Configure(opt_beta);\n  Convergence_beta.setLogger(&log);\n  Convergence_beta.setOverlap(dftAOoverlap, 1e-8);\n  /**** Construct initial density  ****/\n\n  Eigen::MatrixXd H0 = dftAOkinetic.Matrix() + dftAOESP.Matrix();\n  if (with_ecp) {\n    dftAOECP.FillPotential(dftbasis, ecp);\n    H0 += dftAOECP.Matrix();\n  }\n  tools::EigenSystem MOs_alpha = Convergence_alpha.SolveFockmatrix(H0);\n\n  Eigen::MatrixXd dftAOdmat_alpha = Convergence_alpha.DensityMatrix(MOs_alpha);\n  if (uniqueAtom.getElement() == \"H\") {\n    return dftAOdmat_alpha;\n  }\n  tools::EigenSystem MOs_beta = Convergence_beta.SolveFockmatrix(H0);\n  Eigen::MatrixXd dftAOdmat_beta = Convergence_beta.DensityMatrix(MOs_beta);\n\n  Index maxiter = 80;\n  for (Index this_iter = 0; this_iter < maxiter; this_iter++) {\n    Mat_p_Energy ERIs = ERIs_atom.CalculateERIs_4c_small_molecule(\n        dftAOdmat_alpha + dftAOdmat_beta);\n    double E_two_alpha = ERIs.matrix().cwiseProduct(dftAOdmat_alpha).sum();\n    double E_two_beta = ERIs.matrix().cwiseProduct(dftAOdmat_beta).sum();\n    Eigen::MatrixXd H_alpha = H0 + ERIs.matrix();\n    Eigen::MatrixXd H_beta = H0 + ERIs.matrix();\n\n    Mat_p_Energy e_vxc = gridIntegration.IntegrateVXC(dftAOdmat_alpha);\n    Eigen::MatrixXd AOVxc_alpha = e_vxc.matrix();\n    double E_vxc_alpha = e_vxc.energy();\n    H_alpha += AOVxc_alpha;\n    E_two_alpha += E_vxc_alpha;\n\n    e_vxc = gridIntegration.IntegrateVXC(dftAOdmat_beta);\n    Eigen::MatrixXd AOVxc_beta = e_vxc.matrix();\n    double E_vxc_beta = e_vxc.energy();\n    H_beta += AOVxc_beta;\n    E_two_beta += E_vxc_beta;\n\n    if (_ScaHFX > 0) {\n      Mat_p_Energy EXXs =\n          ERIs_atom.CalculateEXX_4c_small_molecule(dftAOdmat_alpha);\n      double E_exx_alpha =\n          -0.5 * _ScaHFX * EXXs.matrix().cwiseProduct(dftAOdmat_alpha).sum();\n      H_alpha -= _ScaHFX * EXXs.matrix();\n      E_two_alpha += E_exx_alpha;\n      ERIs_atom.CalculateEXX_4c_small_molecule(dftAOdmat_beta);\n      double E_exx_beta =\n          -0.5 * _ScaHFX * EXXs.matrix().cwiseProduct(dftAOdmat_beta).sum();\n      H_beta -= _ScaHFX * EXXs.matrix();\n      E_two_beta += E_exx_beta;\n    }\n\n    double E_one_alpha = dftAOdmat_alpha.cwiseProduct(H0).sum();\n    double E_one_beta = dftAOdmat_beta.cwiseProduct(H0).sum();\n    double E_alpha = E_one_alpha + E_two_alpha;\n    double E_beta = E_one_beta + E_two_beta;\n    double totenergy = E_alpha + E_beta;\n    // evolve alpha\n    dftAOdmat_alpha =\n        Convergence_alpha.Iterate(dftAOdmat_alpha, H_alpha, MOs_alpha, E_alpha);\n    // evolve beta\n    dftAOdmat_beta =\n        Convergence_beta.Iterate(dftAOdmat_beta, H_beta, MOs_beta, E_beta);\n\n    XTP_LOG(Log::debug, *_pLog)\n        << TimeStamp() << \" Iter \" << this_iter << \" of \" << maxiter << \" Etot \"\n        << totenergy << \" diise_a \" << Convergence_alpha.getDIIsError()\n        << \" diise_b \" << Convergence_beta.getDIIsError() << \"\\n\\t\\t a_gap \"\n        << MOs_alpha.eigenvalues()(alpha_e) -\n               MOs_alpha.eigenvalues()(alpha_e - 1)\n        << \" b_gap \"\n        << MOs_beta.eigenvalues()(beta_e) - MOs_beta.eigenvalues()(beta_e - 1)\n        << \" Nalpha=\"\n        << dftAOoverlap.Matrix().cwiseProduct(dftAOdmat_alpha).sum()\n        << \" Nbeta=\" << dftAOoverlap.Matrix().cwiseProduct(dftAOdmat_beta).sum()\n        << flush;\n\n    bool converged =\n        Convergence_alpha.isConverged() && Convergence_beta.isConverged();\n    if (converged || this_iter == maxiter - 1) {\n\n      if (converged) {\n        XTP_LOG(Log::info, *_pLog) << TimeStamp() << \" Converged after \"\n                                   << this_iter + 1 << \" iterations\" << flush;\n      } else {\n        XTP_LOG(Log::info, *_pLog)\n            << TimeStamp() << \" Not converged after \" << this_iter + 1\n            << \" iterations. Unconverged density.\\n\\t\\t\\t\"\n            << \" DIIsError_alpha=\" << Convergence_alpha.getDIIsError()\n            << \" DIIsError_beta=\" << Convergence_beta.getDIIsError() << flush;\n      }\n      break;\n    }\n  }\n  Eigen::MatrixXd avgmatrix =\n      SphericalAverageShells(dftAOdmat_alpha + dftAOdmat_beta, dftbasis);\n  XTP_LOG(Log::info, *_pLog)\n      << TimeStamp() << \" Atomic density Matrix for \" << uniqueAtom.getElement()\n      << \" gives N=\" << std::setprecision(9)\n      << avgmatrix.cwiseProduct(dftAOoverlap.Matrix()).sum() << \" electrons.\"\n      << flush;\n  return avgmatrix;\n}\n\nEigen::MatrixXd DFTEngine::AtomicGuess(const QMMolecule& mol) const {\n\n  std::vector<std::string> elements = mol.FindUniqueElements();\n  XTP_LOG(Log::info, *_pLog) << TimeStamp() << \" Scanning molecule of size \"\n                             << mol.size() << \" for unique elements\" << flush;\n  QMMolecule uniqueelements = QMMolecule(\"uniqueelements\", 0);\n  for (auto element : elements) {\n    uniqueelements.push_back(QMAtom(0, element, Eigen::Vector3d::Zero()));\n  }\n\n  XTP_LOG(Log::info, *_pLog) << TimeStamp() << \" \" << uniqueelements.size()\n                             << \" unique elements found\" << flush;\n  std::vector<Eigen::MatrixXd> uniqueatom_guesses;\n  for (QMAtom& unique_atom : uniqueelements) {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Calculating atom density for \"\n        << unique_atom.getElement() << flush;\n    Eigen::MatrixXd dmat_unrestricted = RunAtomicDFT_unrestricted(unique_atom);\n    uniqueatom_guesses.push_back(dmat_unrestricted);\n  }\n\n  Eigen::MatrixXd guess =\n      Eigen::MatrixXd::Zero(_dftbasis.AOBasisSize(), _dftbasis.AOBasisSize());\n  Index start = 0;\n  for (const QMAtom& atom : mol) {\n    Index index = 0;\n    for (; index < uniqueelements.size(); index++) {\n      if (atom.getElement() == uniqueelements[index].getElement()) {\n        break;\n      }\n    }\n    Eigen::MatrixXd& dmat_unrestricted = uniqueatom_guesses[index];\n    guess.block(start, start, dmat_unrestricted.rows(),\n                dmat_unrestricted.cols()) = dmat_unrestricted;\n    start += dmat_unrestricted.rows();\n  }\n\n  return guess;\n}\n\nvoid DFTEngine::ConfigOrbfile(Orbitals& orb) {\n  if (_with_guess) {\n\n    if (orb.hasDFTbasisName()) {\n      if (orb.getDFTbasisName() != _dftbasis_name) {\n        throw runtime_error(\n            (boost::format(\"Basisset Name in guess orb file \"\n                           \"and in dftengine option file differ %1% vs %2%\") %\n             orb.getDFTbasisName() % _dftbasis_name)\n                .str());\n      }\n    } else {\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp()\n          << \" WARNING: \"\n             \"Orbital file has no basisset information,\"\n             \"using it as a guess might work or not for calculation with \"\n          << _dftbasis_name << flush;\n    }\n  }\n  orb.setDFTbasisName(_dftbasis_name);\n  orb.setBasisSetSize(_dftbasis.AOBasisSize());\n  orb.setXCFunctionalName(_xc_functional_name);\n  orb.setScaHFX(_ScaHFX);\n  if (_with_ecp) {\n    orb.setECPName(_ecp_name);\n  }\n  if (_four_center_method == \"RI\") {\n    orb.setAuxbasisName(_auxbasis_name);\n  }\n\n  if (_with_guess) {\n    if (orb.hasECPName() || _with_ecp) {\n      if (orb.getECPName() != _ecp_name) {\n        throw runtime_error(\n            (boost::format(\"ECPs in orb file: %1% and options %2% differ\") %\n             orb.getECPName() % _ecp_name)\n                .str());\n      }\n    }\n    if (orb.getNumberOfAlphaElectrons() != _numofelectrons / 2) {\n      throw runtime_error(\n          (boost::format(\"Number of electron in guess orb file: %1% and in \"\n                         \"dftengine: %2% differ.\") %\n           orb.getNumberOfAlphaElectrons() % (_numofelectrons / 2))\n              .str());\n    }\n    if (orb.getBasisSetSize() != _dftbasis.AOBasisSize()) {\n      throw runtime_error((boost::format(\"Number of levels in guess orb file: \"\n                                         \"%1% and in dftengine: %2% differ.\") %\n                           orb.getBasisSetSize() % _dftbasis.AOBasisSize())\n                              .str());\n    }\n  } else {\n    orb.setNumberOfAlphaElectrons(_numofelectrons / 2);\n    orb.setNumberOfOccupiedLevels(_numofelectrons / 2);\n  }\n  return;\n}\n\nvoid DFTEngine::Prepare(QMMolecule& mol) {\n  XTP_LOG(Log::error, *_pLog) << TimeStamp() << \" Using \"\n                              << OPENMP::getMaxThreads() << \" threads\" << flush;\n\n  if (XTP_HAS_MKL_OVERLOAD()) {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Using MKL overload for Eigen \" << flush;\n  } else {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp()\n        << \" Using native Eigen implementation, no BLAS overload \" << flush;\n  }\n\n  XTP_LOG(Log::error, *_pLog) << \" Molecule Coordinates [A] \" << flush;\n  for (const QMAtom& atom : mol) {\n    const Eigen::Vector3d pos = atom.getPos() * tools::conv::bohr2ang;\n    std::string output = (boost::format(\"  %1$s\"\n                                        \"   %2$+1.4f %3$+1.4f %4$+1.4f\") %\n                          atom.getElement() % pos[0] % pos[1] % pos[2])\n                             .str();\n\n    XTP_LOG(Log::error, *_pLog) << output << flush;\n  }\n  BasisSet dftbasisset;\n  dftbasisset.Load(_dftbasis_name);\n\n  _dftbasis.Fill(dftbasisset, mol);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Loaded DFT Basis Set \" << _dftbasis_name << \" with \"\n      << _dftbasis.AOBasisSize() << \" functions\" << flush;\n\n  if (_four_center_method == \"RI\") {\n    BasisSet auxbasisset;\n    auxbasisset.Load(_auxbasis_name);\n    _auxbasis.Fill(auxbasisset, mol);\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Loaded AUX Basis Set \" << _auxbasis_name << \" with \"\n        << _auxbasis.AOBasisSize() << \" functions\" << flush;\n  }\n  if (_with_ecp) {\n    ECPBasisSet ecpbasisset;\n    ecpbasisset.Load(_ecp_name);\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Loaded ECP library \" << _ecp_name << flush;\n\n    std::vector<std::string> results = _ecp.Fill(ecpbasisset, mol);\n    XTP_LOG(Log::info, *_pLog) << TimeStamp() << \" Filled ECP Basis of size \"\n                               << _ecp.ECPAOBasisSize() << flush;\n    if (results.size() > 0) {\n      std::string message = \"\";\n      for (const std::string& element : results) {\n        message += \" \" + element;\n      }\n      XTP_LOG(Log::error, *_pLog)\n          << TimeStamp() << \" Found no ECPs for elements\" << message << flush;\n    }\n  }\n\n  for (const QMAtom& atom : mol) {\n    _numofelectrons += atom.getNuccharge();\n  }\n\n  // here number of electrons is actually the total number, everywhere else in\n  // votca it is just alpha_electrons\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Total number of electrons: \" << _numofelectrons\n      << flush;\n\n  SetupInvariantMatrices();\n  return;\n}\n\nVxc_Potential<Vxc_Grid> DFTEngine::SetupVxc(const QMMolecule& mol) {\n  _ScaHFX = Vxc_Potential<Vxc_Grid>::getExactExchange(_xc_functional_name);\n  if (_ScaHFX > 0) {\n    XTP_LOG(Log::error, *_pLog)\n        << TimeStamp() << \" Using hybrid functional with alpha=\" << _ScaHFX\n        << flush;\n  }\n  Vxc_Grid grid;\n  grid.GridSetup(_grid_name, mol, _dftbasis);\n  Vxc_Potential<Vxc_Grid> vxc(grid);\n  vxc.setXCfunctional(_xc_functional_name);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Setup numerical integration grid \" << _grid_name\n      << \" for vxc functional \" << _xc_functional_name << flush;\n  XTP_LOG(Log::info, *_pLog)\n      << \"\\t\\t \"\n      << \" with \" << grid.getGridSize() << \" points\"\n      << \" divided into \" << grid.getBoxesSize() << \" boxes\" << flush;\n  return vxc;\n}\n\ndouble DFTEngine::NuclearRepulsion(const QMMolecule& mol) const {\n  double E_nucnuc = 0.0;\n\n  for (Index i = 0; i < mol.size(); i++) {\n    const Eigen::Vector3d& r1 = mol[i].getPos();\n    double charge1 = double(mol[i].getNuccharge());\n    for (Index j = 0; j < i; j++) {\n      const Eigen::Vector3d& r2 = mol[j].getPos();\n      double charge2 = double(mol[j].getNuccharge());\n      E_nucnuc += charge1 * charge2 / (r1 - r2).norm();\n    }\n  }\n  return E_nucnuc;\n}\n\n// average atom densities matrices, for SP and other combined shells average\n// each subshell separately.\nEigen::MatrixXd DFTEngine::SphericalAverageShells(\n    const Eigen::MatrixXd& dmat, const AOBasis& dftbasis) const {\n  Eigen::MatrixXd avdmat = Eigen::MatrixXd::Zero(dmat.rows(), dmat.cols());\n  Index start = 0.0;\n  std::vector<Index> starts;\n  std::vector<Index> ends;\n  for (const AOShell& shell : dftbasis) {\n    Index end = shell.getNumFunc() + start;\n    starts.push_back(start);\n    ends.push_back(end);\n    start = end;\n  }\n  for (Index k = 0; k < Index(starts.size()); k++) {\n    Index s1 = starts[k];\n    Index e1 = ends[k];\n    Index len1 = e1 - s1;\n    for (Index l = 0; l < Index(starts.size()); l++) {\n      Index s2 = starts[l];\n      Index e2 = ends[l];\n      Index len2 = e2 - s2;\n      double diag = 0.0;\n      double offdiag = 0.0;\n      for (Index i = 0; i < len1; ++i) {\n        for (Index j = 0; j < len2; ++j) {\n          if (i == j) {\n            diag += dmat(s1 + i, s2 + j);\n          } else {\n            offdiag += dmat(s1 + i, s2 + j);\n          }\n        }\n      }\n      if (len1 == len2) {\n        diag = diag / double(len1);\n        offdiag = offdiag / double(len1 * (len1 - 1));\n      } else {\n        double avg = (diag + offdiag) / double(len1 * len2);\n        diag = avg;\n        offdiag = avg;\n      }\n      for (Index i = 0; i < len1; ++i) {\n        for (Index j = 0; j < len2; ++j) {\n          if (i == j) {\n            avdmat(s1 + i, s2 + j) = diag;\n          } else {\n            avdmat(s1 + i, s2 + j) = offdiag;\n          }\n        }\n      }\n    }\n  }\n  return avdmat;\n}\n\ndouble DFTEngine::ExternalRepulsion(\n    const QMMolecule& mol,\n    const std::vector<std::unique_ptr<StaticSite> >& multipoles) const {\n\n  if (multipoles.size() == 0) {\n    return 0;\n  }\n\n  double E_ext = 0;\n  eeInteractor interactor;\n  for (const QMAtom& atom : mol) {\n    StaticSite nucleus = StaticSite(atom, double(atom.getNuccharge()));\n    for (const std::unique_ptr<StaticSite>& site : *_externalsites) {\n      if ((site->getPos() - nucleus.getPos()).norm() < 1e-7) {\n        XTP_LOG(Log::error, *_pLog) << TimeStamp()\n                                    << \" External site sits on nucleus, \"\n                                       \"interaction between them is ignored.\"\n                                    << flush;\n        continue;\n      }\n      E_ext += interactor.CalcStaticEnergy_site(*site, nucleus);\n    }\n  }\n  return E_ext;\n}\n\nEigen::MatrixXd DFTEngine::IntegrateExternalField(const QMMolecule& mol) const {\n\n  AODipole dipole;\n  dipole.setCenter(mol.getPos());\n  dipole.Fill(_dftbasis);\n  Eigen::MatrixXd result =\n      Eigen::MatrixXd::Zero(dipole.Dimension(), dipole.Dimension());\n  for (Index i = 0; i < 3; i++) {\n    result -= dipole.Matrix()[i] * _extfield[i];\n  }\n  return result;\n}\n\nMat_p_Energy DFTEngine::IntegrateExternalMultipoles(\n    const QMMolecule& mol,\n    const std::vector<std::unique_ptr<StaticSite> >& multipoles) const {\n\n  Mat_p_Energy result(_dftbasis.AOBasisSize(), _dftbasis.AOBasisSize());\n  AOMultipole dftAOESP;\n\n  dftAOESP.FillPotential(_dftbasis, multipoles);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Filled DFT external multipole potential matrix\"\n      << flush;\n  result.matrix() = dftAOESP.Matrix();\n  result.energy() = ExternalRepulsion(mol, multipoles);\n\n  return result;\n}\n\nMat_p_Energy DFTEngine::IntegrateExternalDensity(\n    const QMMolecule& mol, const Orbitals& extdensity) const {\n  BasisSet basis;\n  basis.Load(extdensity.getDFTbasisName());\n  AOBasis aobasis;\n  aobasis.Fill(basis, extdensity.QMAtoms());\n  Vxc_Grid grid;\n  grid.GridSetup(_gridquality, extdensity.QMAtoms(), aobasis);\n  DensityIntegration<Vxc_Grid> numint(grid);\n  Eigen::MatrixXd dmat = extdensity.DensityMatrixFull(_state);\n\n  numint.IntegrateDensity(dmat);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Calculated external density\" << flush;\n  Eigen::MatrixXd e_contrib = numint.IntegratePotential(_dftbasis);\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Calculated potential from electron density\" << flush;\n  AOMultipole esp;\n  esp.FillPotential(_dftbasis, extdensity.QMAtoms());\n\n  double nuc_energy = 0.0;\n  for (const QMAtom& atom : mol) {\n    nuc_energy +=\n        numint.IntegratePotential(atom.getPos()) * double(atom.getNuccharge());\n    for (const QMAtom& extatom : extdensity.QMAtoms()) {\n      const double dist = (atom.getPos() - extatom.getPos()).norm();\n      nuc_energy +=\n          double(atom.getNuccharge()) * double(extatom.getNuccharge()) / dist;\n    }\n  }\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Calculated potential from nuclei\" << flush;\n  XTP_LOG(Log::error, *_pLog)\n      << TimeStamp() << \" Electrostatic: \" << nuc_energy << flush;\n  return Mat_p_Energy(nuc_energy, e_contrib + esp.Matrix());\n}\n\nMat_p_Energy DFTEngine::CalculateERIs(const Eigen::MatrixXd& DMAT) const {\n  if (_four_center_method == \"RI\") {\n    return _ERIs.CalculateERIs(DMAT);\n  } else if (_four_center_method == \"cache\") {\n    return _ERIs.CalculateERIs_4c_small_molecule(DMAT);\n  } else if (_four_center_method == \"direct\") {\n    return _ERIs.CalculateERIs_4c_direct(_dftbasis, DMAT);\n  } else {\n    throw std::runtime_error(\"ERI method not known.\");\n  }\n}\n\nEigen::MatrixXd DFTEngine::OrthogonalizeGuess(\n    const Eigen::MatrixXd& GuessMOs) const {\n  Eigen::MatrixXd nonortho =\n      GuessMOs.transpose() * _dftAOoverlap.Matrix() * GuessMOs;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(nonortho);\n  Eigen::MatrixXd result = GuessMOs * es.operatorInverseSqrt();\n  return result;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "e85fa59f0c61f7351e69685f1ee0c00445586e2a", "size": 36727, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/dftengine/dftengine.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/dftengine/dftengine.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/dftengine/dftengine.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.7266536965, "max_line_length": 80, "alphanum_fraction": 0.6161679418, "num_tokens": 10673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.024798161096480503, "lm_q1q2_score": 0.010666862883146453}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2013-2020.\n// Modifications copyright (c) 2013-2020 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_DE9IM_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_DE9IM_HPP\n\n#include <tuple>\n\n#include <boost/geometry/algorithms/detail/relate/result.hpp>\n#include <boost/geometry/core/topological_dimension.hpp>\n#include <boost/geometry/core/tag.hpp>\n\n#include <boost/geometry/util/sequence.hpp>\n#include <boost/geometry/util/tuples.hpp>\n\nnamespace boost { namespace geometry\n{\n    \nnamespace de9im\n{\n\n/*!\n\\brief DE-9IM model intersection matrix.\n\\ingroup de9im\n\\details This matrix can be used to express spatial relations as defined in\n         Dimensionally Extended 9-Intersection Model.\n\n\\qbk{[heading See also]}\n\\qbk{* [link geometry.reference.algorithms.relation relation]}\n */\nclass matrix\n    : public detail::relate::matrix<3, 3>\n{\n#ifdef DOXYGEN_INVOKED\npublic:\n    /*!\n    \\brief Initializes all of the matrix elements to F\n     */\n    matrix();\n    /*!\n    \\brief Subscript operator\n    \\param index The index of the element\n    \\return The element\n     */\n    char operator[](std::size_t index) const;\n    /*!\n    \\brief Returns the iterator to the first element\n    \\return const RandomAccessIterator\n     */\n    const_iterator begin() const;\n    /*!\n    \\brief Returns the iterator past the last element\n    \\return const RandomAccessIterator\n     */\n    const_iterator end() const;\n    /*!\n    \\brief Returns the number of elements\n    \\return 9\n     */\n    static std::size_t size();\n    /*!\n    \\brief Returns raw pointer to elements\n    \\return const pointer to array of elements\n     */\n    inline const char * data() const;\n    /*!\n    \\brief Returns std::string containing elements\n    \\return string containing elements\n     */\n    inline std::string str() const;\n#endif\n};\n\n/*!\n\\brief DE-9IM model intersection mask.\n\\ingroup de9im\n\\details This mask can be used to check spatial relations as defined in\n         Dimensionally Extended 9-Intersection Model.\n\n\\qbk{[heading See also]}\n\\qbk{* [link geometry.reference.algorithms.relate relate]}\n */\nclass mask\n    : public detail::relate::mask<3, 3>\n{\n    typedef detail::relate::mask<3, 3> base_type;\n\npublic:\n    /*!\n    \\brief The constructor.\n    \\param code The mask pattern.\n    */\n    inline explicit mask(const char* code)\n        : base_type(code)\n    {}\n    \n    /*!\n    \\brief The constructor.\n    \\param code The mask pattern.\n    */\n    inline explicit mask(std::string const& code)\n        : base_type(code.c_str(), code.size())\n    {}\n};\n\n// static_mask\n\n/*!\n\\brief DE-9IM model intersection mask (static version).\n\\ingroup de9im\n\\details This mask can be used to check spatial relations as defined in\n         Dimensionally Extended 9-Intersection Model.\n\\tparam II Interior/Interior intersection mask element\n\\tparam IB Interior/Boundary intersection mask element\n\\tparam IE Interior/Exterior intersection mask element\n\\tparam BI Boundary/Interior intersection mask element\n\\tparam BB Boundary/Boundary intersection mask element\n\\tparam BE Boundary/Exterior intersection mask element\n\\tparam EI Exterior/Interior intersection mask element\n\\tparam EB Exterior/Boundary intersection mask element\n\\tparam EE Exterior/Exterior intersection mask element\n\n\\qbk{[heading See also]}\n\\qbk{* [link geometry.reference.algorithms.relate relate]}\n */\ntemplate\n<\n    char II = '*', char IB = '*', char IE = '*',\n    char BI = '*', char BB = '*', char BE = '*',\n    char EI = '*', char EB = '*', char EE = '*'\n>\nclass static_mask\n    : public detail::relate::static_mask\n        <\n            std::integer_sequence\n                <\n                    char, II, IB, IE, BI, BB, BE, EI, EB, EE\n                >,\n            3, 3\n        >\n{};\n\n\ninline\nstd::tuple<mask, mask>\noperator||(mask const& m1, mask const& m2)\n{\n    return std::tuple<mask, mask>(m1, m2);\n}\n\ntemplate <typename ...Masks>\ninline\nstd::tuple<Masks..., mask>\noperator||(std::tuple<Masks...> const& t, mask const& m)\n{\n    return geometry::tuples::push_back\n            <\n                std::tuple<Masks...>,\n                mask\n            >::apply(t, m);\n}\n\ntemplate\n<\n    char II1, char IB1, char IE1,\n    char BI1, char BB1, char BE1,\n    char EI1, char EB1, char EE1,\n    char II2, char IB2, char IE2,\n    char BI2, char BB2, char BE2,\n    char EI2, char EB2, char EE2\n>\ninline\nutil::type_sequence\n    <\n        static_mask<II1, IB1, IE1, BI1, BB1, BE1, EI1, EB1, EE1>,\n        static_mask<II2, IB2, IE2, BI2, BB2, BE2, EI2, EB2, EE2>\n    >\noperator||(static_mask<II1, IB1, IE1, BI1, BB1, BE1, EI1, EB1, EE1> const& ,\n           static_mask<II2, IB2, IE2, BI2, BB2, BE2, EI2, EB2, EE2> const& )\n{\n    return util::type_sequence\n            <\n                static_mask<II1, IB1, IE1, BI1, BB1, BE1, EI1, EB1, EE1>,\n                static_mask<II2, IB2, IE2, BI2, BB2, BE2, EI2, EB2, EE2>\n            >();\n}\n\ntemplate\n<\n    typename ...StaticMasks,\n    char II, char IB, char IE,\n    char BI, char BB, char BE,\n    char EI, char EB, char EE\n>\ninline\nutil::type_sequence\n<\n    StaticMasks...,\n    static_mask<II, IB, IE, BI, BB, BE, EI, EB, EE>\n>\noperator||(util::type_sequence<StaticMasks...> const& ,\n           static_mask<II, IB, IE, BI, BB, BE, EI, EB, EE> const& )\n{\n    return util::type_sequence\n            <\n                StaticMasks...,\n                static_mask<II, IB, IE, BI, BB, BE, EI, EB, EE>\n            >();\n}\n\n} // namespace de9im\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace de9im\n{\n\n// PREDEFINED MASKS\n\n// TODO:\n// 1. specialize for simplified masks if available\n// e.g. for TOUCHES use 1 mask for A/A\n// 2. Think about dimensions > 2 e.g. should TOUCHES be true\n// if the interior of the Areal overlaps the boundary of the Volumetric\n// like it's true for Linear/Areal\n\n// EQUALS\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_equals_type\n{\n    typedef geometry::de9im::static_mask<'T', '*', 'F', '*', '*', 'F', 'F', 'F', '*'> type; // wikipedia\n    //typedef geometry::de9im::static_mask<'T', 'F', 'F', 'F', 'T', 'F', 'F', 'F', 'T'> type; // OGC\n};\n\n// DISJOINT\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_disjoint_type\n{\n    typedef geometry::de9im::static_mask<'F', 'F', '*', 'F', 'F', '*', '*', '*', '*'> type;\n};\n\n// TOUCHES - NOT P/P\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    std::size_t Dim1 = geometry::topological_dimension<Geometry1>::value,\n    std::size_t Dim2 = geometry::topological_dimension<Geometry2>::value\n>\nstruct static_mask_touches_impl\n{\n    typedef util::type_sequence\n        <\n            geometry::de9im::static_mask<'F', 'T', '*', '*', '*', '*', '*', '*', '*'>,\n            geometry::de9im::static_mask<'F', '*', '*', 'T', '*', '*', '*', '*', '*'>,\n            geometry::de9im::static_mask<'F', '*', '*', '*', 'T', '*', '*', '*', '*'>\n        > type;\n};\n// According to OGC, doesn't apply to P/P\n// Using the above mask the result would be always false\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_touches_impl<Geometry1, Geometry2, 0, 0>\n{\n    typedef geometry::detail::relate::false_mask type;\n};\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_touches_type\n    : static_mask_touches_impl<Geometry1, Geometry2>\n{};\n\n// WITHIN\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_within_type\n{\n    typedef geometry::de9im::static_mask<'T', '*', 'F', '*', '*', 'F', '*', '*', '*'> type;\n};\n\n// COVERED_BY (non OGC)\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_covered_by_type\n{\n    typedef util::type_sequence\n        <\n            geometry::de9im::static_mask<'T', '*', 'F', '*', '*', 'F', '*', '*', '*'>,\n            geometry::de9im::static_mask<'*', 'T', 'F', '*', '*', 'F', '*', '*', '*'>,\n            geometry::de9im::static_mask<'*', '*', 'F', 'T', '*', 'F', '*', '*', '*'>,\n            geometry::de9im::static_mask<'*', '*', 'F', '*', 'T', 'F', '*', '*', '*'>\n        > type;\n};\n\n// CROSSES\n// dim(G1) < dim(G2) - P/L P/A L/A\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    std::size_t Dim1 = geometry::topological_dimension<Geometry1>::value,\n    std::size_t Dim2 = geometry::topological_dimension<Geometry2>::value,\n    bool D1LessD2 = (Dim1 < Dim2)\n>\nstruct static_mask_crosses_impl\n{\n    typedef geometry::de9im::static_mask<'T', '*', 'T', '*', '*', '*', '*', '*', '*'> type;\n};\n// TODO: I'm not sure if this one below should be available!\n// dim(G1) > dim(G2) - L/P A/P A/L\ntemplate\n<\n    typename Geometry1, typename Geometry2, std::size_t Dim1, std::size_t Dim2\n>\nstruct static_mask_crosses_impl<Geometry1, Geometry2, Dim1, Dim2, false>\n{\n    typedef geometry::de9im::static_mask<'T', '*', '*', '*', '*', '*', 'T', '*', '*'> type;\n};\n// dim(G1) == dim(G2) - P/P A/A\ntemplate\n<\n    typename Geometry1, typename Geometry2, std::size_t Dim\n>\nstruct static_mask_crosses_impl<Geometry1, Geometry2, Dim, Dim, false>\n{\n    typedef geometry::detail::relate::false_mask type;\n};\n// dim(G1) == 1 && dim(G2) == 1 - L/L\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_crosses_impl<Geometry1, Geometry2, 1, 1, false>\n{\n    typedef geometry::de9im::static_mask<'0', '*', '*', '*', '*', '*', '*', '*', '*'> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_crosses_type\n    : static_mask_crosses_impl<Geometry1, Geometry2>\n{};\n\n// OVERLAPS\n\n// dim(G1) != dim(G2) - NOT P/P, L/L, A/A\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    std::size_t Dim1 = geometry::topological_dimension<Geometry1>::value,\n    std::size_t Dim2 = geometry::topological_dimension<Geometry2>::value\n>\nstruct static_mask_overlaps_impl\n{\n    typedef geometry::detail::relate::false_mask type;\n};\n// dim(G1) == D && dim(G2) == D - P/P A/A\ntemplate <typename Geometry1, typename Geometry2, std::size_t Dim>\nstruct static_mask_overlaps_impl<Geometry1, Geometry2, Dim, Dim>\n{\n    typedef geometry::de9im::static_mask<'T', '*', 'T', '*', '*', '*', 'T', '*', '*'> type;\n};\n// dim(G1) == 1 && dim(G2) == 1 - L/L\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_overlaps_impl<Geometry1, Geometry2, 1, 1>\n{\n    typedef geometry::de9im::static_mask<'1', '*', 'T', '*', '*', '*', 'T', '*', '*'> type;\n};\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct static_mask_overlaps_type\n    : static_mask_overlaps_impl<Geometry1, Geometry2>\n{};\n\n}} // namespace detail::de9im\n#endif // DOXYGEN_NO_DETAIL\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_DE9IM_HPP\n", "meta": {"hexsha": "a89d46100ae698b1a4af35d4848cca1f5ca6c2fa", "size": 10985, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/relate/de9im.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/relate/de9im.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/detail/relate/de9im.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 28.4585492228, "max_line_length": 104, "alphanum_fraction": 0.6406918525, "num_tokens": 3020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.034618842449693356, "lm_q1q2_score": 0.010640379200793394}}
{"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 SIMPLEUNIFORMSOURCEPDE_HPP_\n#define SIMPLEUNIFORMSOURCEPDE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractLinearEllipticPde.hpp\"\n\n/**\n *  A simple nutrient PDE which is not directly coupled to the cell population.\n */\ntemplate<unsigned DIM>\nclass SimpleUniformSourcePde : 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    }\n\n    /** Coefficient of consumption of nutrient by cells. */\n    double mCoefficient;\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param coefficient the coefficient of consumption of nutrient by cells (defaults to 0.0)\n     */\n    SimpleUniformSourcePde(double coefficient=0.0);\n\n    /**\n     * @return mCoefficient\n     */\n    double GetCoefficient() const;\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#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(SimpleUniformSourcePde)\n\n#endif /*SIMPLEUNIFORMSOURCEPDE_HPP_*/\n", "meta": {"hexsha": "c85a5c50643288582d10b99bce9c227f66fb3568", "size": 4168, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/population/pdes/SimpleUniformSourcePde.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/SimpleUniformSourcePde.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/SimpleUniformSourcePde.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": 34.1639344262, "max_line_length": 101, "alphanum_fraction": 0.7288867562, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353745, "lm_q2_score": 0.026355352989510358, "lm_q1q2_score": 0.010636146885061891}}
{"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_PERIMETER_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n\n\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/variant_fwd.hpp>\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/algorithms/detail/calculate_null.hpp>\n#include <boost/geometry/algorithms/detail/calculate_sum.hpp>\n// #include <boost/geometry/algorithms/detail/throw_on_empty_input.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/strategies/default_length_result.hpp>\n#include <boost/geometry/strategies/default_strategy.hpp>\n#include <boost/geometry/util/compress_variant.hpp>\n#include <boost/geometry/util/transform_variant.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n// Default perimeter is 0.0, specializations implement calculated values\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct perimeter : detail::calculate_null\n{\n    typedef typename default_length_result<Geometry>::type return_type;\n\n    template <typename Strategy>\n    static inline return_type apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return calculate_null::apply<return_type>(geometry, strategy);\n    }\n};\n\ntemplate <typename Geometry>\nstruct perimeter<Geometry, ring_tag>\n    : detail::length::range_length\n        <\n            Geometry,\n            closure<Geometry>::value\n        >\n{};\n\ntemplate <typename Polygon>\nstruct perimeter<Polygon, polygon_tag> : detail::calculate_polygon_sum\n{\n    typedef typename default_length_result<Polygon>::type return_type;\n    typedef detail::length::range_length\n                <\n                    typename ring_type<Polygon>::type,\n                    closure<Polygon>::value\n                > policy;\n\n    template <typename Strategy>\n    static inline return_type apply(Polygon const& polygon, Strategy const& strategy)\n    {\n        return calculate_polygon_sum::apply<return_type, policy>(polygon, strategy);\n    }\n};\n\n\n// box,n-sphere: to be implemented\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy {\n\nstruct perimeter\n{\n    template <typename Geometry, typename Strategy>\n    static inline typename default_length_result<Geometry>::type\n    apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return dispatch::perimeter<Geometry>::apply(geometry, strategy);\n    }\n\n    template <typename Geometry>\n    static inline typename default_length_result<Geometry>::type\n    apply(Geometry const& geometry, default_strategy)\n    {\n        typedef typename strategy::distance::services::default_strategy\n            <\n                point_tag,\n                typename point_type<Geometry>::type\n            >::type strategy_type;\n\n        return dispatch::perimeter<Geometry>::apply(geometry, strategy_type());\n    }\n};\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry>\nstruct perimeter\n{\n    typedef typename default_length_result<Geometry>::type result_type;\n\n    template <typename Strategy>\n    static inline result_type\n    apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        concept::check<Geometry const>();\n        return resolve_strategy::perimeter::apply(geometry, strategy);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct perimeter<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    typedef typename compress_variant<\n        typename transform_variant<\n            boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>,\n            default_length_result<boost::mpl::placeholders::_>\n        >::type\n    >:: type result_type;\n\n    template <typename Strategy>\n    struct visitor: boost::static_visitor<result_type>\n    {\n        Strategy const& m_strategy;\n\n        visitor(Strategy const& strategy): m_strategy(strategy) {}\n\n        template <typename Geometry>\n        result_type operator()(Geometry const& geometry) const\n        {\n            return perimeter<Geometry>::apply(geometry, m_strategy);\n        }\n    };\n\n    template <typename Strategy>\n    static inline result_type\n    apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry,\n          Strategy const& strategy)\n    {\n        return boost::apply_visitor(visitor<Strategy>(strategy), geometry);\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\brief \\brief_calc{perimeter}\n\\ingroup perimeter\n\\details The function perimeter returns the perimeter of a geometry,\n    using the default distance-calculation-strategy\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry\n\\return \\return_calc{perimeter}\n\n\\qbk{[include reference/algorithms/perimeter.qbk]}\n */\ntemplate<typename Geometry>\ninline typename resolve_variant::perimeter<Geometry>::result_type perimeter(\n        Geometry const& geometry)\n{\n    // detail::throw_on_empty_input(geometry);\n    return resolve_variant::perimeter<Geometry>::apply(geometry, default_strategy());\n}\n\n/*!\n\\brief \\brief_calc{perimeter} \\brief_strategy\n\\ingroup perimeter\n\\details The function perimeter returns the perimeter of a geometry,\n    using specified strategy\n\\tparam Geometry \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{distance}\n\\param geometry \\param_geometry\n\\param strategy strategy to be used for distance calculations.\n\\return \\return_calc{perimeter}\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/perimeter.qbk]}\n */\ntemplate<typename Geometry, typename Strategy>\ninline typename resolve_variant::perimeter<Geometry>::result_type perimeter(\n        Geometry const& geometry, Strategy const& strategy)\n{\n    // detail::throw_on_empty_input(geometry);\n    return resolve_variant::perimeter<Geometry>::apply(geometry, strategy);\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n\n", "meta": {"hexsha": "25870b9de4d2954bdda0d075c271f3024616d75d", "size": 6541, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/algorithms/perimeter.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/algorithms/perimeter.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/algorithms/perimeter.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 30.8537735849, "max_line_length": 87, "alphanum_fraction": 0.7352086837, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.026759284058610288, "lm_q1q2_score": 0.01059850094941571}}
{"text": "#include <mpi.h>\n\n#include <string>\n#include <map>\n#include <time.h>\n#include <vector>\n#include <fstream>\n#include <boost/timer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/cmdline.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/timer.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <arcane/ArcaneVersion.h>\n#include <arcane/Timer.h>\n#include <arcane/ItemPairGroup.h>\n#include <arcane/mesh/ItemFamily.h>\n#include <arcane/utils/PlatformUtils.h>\n#include <arcane/utils/IMemoryInfo.h>\n#include <arcane/utils/OStringStream.h>\n#include <arcane/ITimeLoopMng.h>\n#include <alien/arcane_tools/accessors/ItemVectorAccessor.h>\n#include <alien/core/block/VBlock.h>\n\n#include <alien/arcane_tools/IIndexManager.h>\n#include <alien/arcane_tools/indexManager/BasicIndexManager.h>\n#include <alien/arcane_tools/indexManager/SimpleAbstractFamily.h>\n#include <alien/arcane_tools/distribution/DistributionFabric.h>\n#include <alien/arcane_tools/indexSet/IndexSetFabric.h>\n#include <alien/arcane_tools/data/Space.h>\n\n#include <alien/kernels/simple_csr/algebra/SimpleCSRLinearAlgebra.h>\n\n#include <alien/ref/AlienRefSemantic.h>\n\n#include <alien/ref/mv_expr/MVExpr.h>\n\n#ifdef ALIEN_USE_PETSC\n#include <alien/kernels/petsc/io/AsciiDumper.h>\n#include <alien/kernels/petsc/algebra/PETScLinearAlgebra.h>\n#endif\n#ifdef ALIEN_USE_MTL4\n#include <alien/kernels/mtl/algebra/MTLLinearAlgebra.h>\n#endif\n#ifdef ALIEN_USE_HTSSOLVER\n#include <alien/kernels/hts/HTSBackEnd.h>\n#include <alien/kernels/hts/data_structure/HTSMatrix.h>\n#include <alien/kernels/hts/algebra/HTSLinearAlgebra.h>\n#endif\n#ifdef ALIEN_USE_TRILINOS\n#include <alien/kernels/trilinos/TrilinosBackEnd.h>\n#include <alien/kernels/trilinos/data_structure/TrilinosMatrix.h>\n#include <alien/kernels/trilinos/algebra/TrilinosLinearAlgebra.h>\n#endif\n\n#include <alien/expression/solver/ILinearSolver.h>\n#include <alien/ref/AlienImportExport.h>\n\n#include \"AlienStokesModule.h\"\n\n#include <arcane/ItemPairGroup.h>\n#include <arcane/IMesh.h>\n\n#include <alien/core/impl/MultiVectorImpl.h>\n\nusing namespace Arcane;\nusing namespace Alien;\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\nInteger\nAlienStokesModule::_computeDir(Real3 const& x)\n{\n  Integer dir = -1;\n  Real max_coord = 0.;\n  for (Integer i = 0; i < dim; ++i) {\n    if (std::abs(x[i]) > max_coord) {\n      dir = i;\n      max_coord = std::abs(x[i]);\n    }\n  }\n  assert(dir != -1);\n  return dir;\n}\n\nInteger\nAlienStokesModule::_computeOrientation(Face const& face)\n{\n  Integer dir = m_face_type[face];\n  Integer orientation = 0;\n  if (face.frontCell().null()) {\n    Real3 n = m_face_center[face] - m_cell_center[face.backCell()];\n    if (n[dir] > 0)\n      orientation = 1;\n    else\n      orientation = -1;\n  } else {\n    Real3 n = m_cell_center[face.frontCell()] - m_face_center[face];\n    if (n[dir] > 0)\n      orientation = 1;\n    else\n      orientation = -1;\n  }\n  return orientation;\n}\n\nvoid\nAlienStokesModule::init()\n{\n  Alien::setTraceMng(traceMng());\n  Alien::setVerbosityLevel(Alien::Verbosity::Debug);\n  m_parallel_mng = subDomain()->parallelMng();\n\n  m_homogeneous = options()->homogeneous();\n\n  for (Integer i = 0; i < dim; ++i)\n    m_h[i] = 0.;\n\n  ENUMERATE_CELL (icell, allCells()) {\n    Real3 x;\n    ENUMERATE_NODE (inode, icell->nodes()) {\n      x += m_node_coord[*inode];\n    }\n    x /= icell->nbNode();\n    m_cell_center[icell] = x;\n  }\n\n  ENUMERATE_FACE (iface, allFaces()) {\n    Real3 x;\n    ENUMERATE_NODE (inode, iface->nodes()) {\n      x += m_node_coord[*inode];\n    }\n    x /= iface->nbNode();\n    m_face_center[iface] = x;\n    auto cell = iface->cell(0);\n    Real3 n = m_cell_center[cell] - m_face_center[iface];\n    Integer dir = _computeDir(n);\n    m_face_type[iface] = dir;\n\n    Integer orientation = _computeOrientation(*iface);\n    m_face_orientation[iface] = orientation;\n\n    if (m_h[dir] == 0 && iface->nbCell() == 2) {\n      Real3 d = m_cell_center[iface->frontCell()] - m_cell_center[iface->backCell()];\n      m_h[dir] = d.abs();\n      m_h2[dir] = m_h[dir] * m_h[dir];\n    }\n  }\n\n  info() << \" H  = \" << m_h[0] << \" \" << m_h[1] << \" \" << m_h[2];\n  info() << \" H2 = \" << m_h2[0] << \" \" << m_h2[1] << \" \" << m_h2[2];\n\n  initSourceAndBoundaryTerm();\n\n  Alien::ILinearSolver* solver = options()->linearSolver();\n  solver->init();\n}\n\n/*---------------------------------------------------------------------------*/\nbool\nAlienStokesModule::_isNodeOfFace(Face const& face, Integer node_lid)\n{\n  ENUMERATE_NODE (inode, face.nodes()) {\n    if (inode->localId() == node_lid)\n      return true;\n  }\n  return false;\n}\n\nvoid\nAlienStokesModule::_computeFaceConnectivity(\n    Face const& face, Alien::UniqueArray2<Integer>& connectivity)\n{\n  Integer face_lid = face.localId();\n  Integer face_type = m_face_type[face];\n  connectivity.fill(-1);\n  Integer nb_nodes = face.nbNode();\n  for (Integer i = 0; i < nb_nodes; ++i) {\n    Node node0 = face.node(i);\n    Node node1 = face.node(i == nb_nodes - 1 ? 0 : i + 1);\n    Integer node1_lid = node1.localId();\n    Real3 xN = 0.5 * (m_node_coord[node0] + m_node_coord[node1]) - m_face_center[face];\n    Integer dir = _computeDir(xN);\n    Integer up = xN[dir] > 0 ? 1 : 0;\n    ENUMERATE_FACE (iface2, node0.faces()) {\n      Face const& conn_face = *iface2;\n      if (conn_face.localId() != face_lid && _isNodeOfFace(conn_face, node1_lid)\n          && m_face_type[conn_face] == face_type) {\n        connectivity[dir][up] = conn_face.localId();\n      }\n    }\n    if (connectivity[dir][up] == -1) {\n      connectivity[dir][up] = -1 - i;\n    }\n  }\n}\n\nInteger\nAlienStokesModule::_upStreamFace(Face const& face, Integer cell_id)\n{\n  Integer up = 0;\n  Integer orientation = m_face_orientation[face];\n  if (orientation > 0) {\n    if (!face.backCell().null()) {\n      if (face.backCell().localId() == cell_id)\n        up = 1;\n      else\n        up = -1;\n    } else {\n      if (face.frontCell().localId() == cell_id)\n        up = -1;\n      else\n        up = 1;\n    }\n  } else {\n    if (!face.backCell().null()) {\n      if (face.backCell().localId() == cell_id)\n        up = -1;\n      else\n        up = 1;\n    } else {\n      if (face.frontCell().localId() == cell_id)\n        up = 1;\n      else\n        up = -1;\n    }\n  }\n  assert(up != 0);\n  return up;\n}\n\nAlienStokesModule::eBCType\nAlienStokesModule::getBCType(Real3 const& xF, Integer dir)\n{\n  switch (dir) {\n  case 0:\n    if (xF[0] == 1.)\n      return Neumann;\n    else\n      return Dirichlet;\n  case 1:\n    if (xF[0] == 1.)\n      return Neumann;\n    else\n      return Dirichlet;\n  case 2:\n    if (xF[0] == 1.)\n      return Neumann;\n    else\n      return Dirichlet;\n  }\n  return Dirichlet;\n}\nAlienStokesModule::eBCType\nAlienStokesModule::getBCType(Face const& face)\n{\n  Integer face_type = m_face_type[face];\n  Real3 xF = m_face_center[face];\n  return getBCType(xF, face_type);\n}\nvoid\nAlienStokesModule::initVelocityAndPressure()\n{\n  m_xV.resize(3);\n  ENUMERATE_CELL (icell, allCells()) {\n    Real3 const& xC = m_cell_center[icell];\n    m_xV[icell][0] = ux(xC);\n    m_xV[icell][1] = uy(xC);\n    m_xV[icell][2] = uz(xC);\n    m_xP[icell] = pressure(xC);\n    m_xE[icell] = m_xV[icell][0] * m_xV[icell][0] + m_xV[icell][1] * m_xV[icell][1]\n        + m_xV[icell][2] * m_xV[icell][2];\n  }\n}\nvoid\nAlienStokesModule::initSourceAndBoundaryTerm()\n{\n  ENUMERATE_CELL (icell, allCells()) {\n    m_g[icell] = div(m_cell_center[*icell]);\n  }\n\n  ENUMERATE_FACE (iface, allFaces()) {\n    m_f[iface] = func(m_face_center[*iface], m_face_type[*iface]);\n  }\n\n  ENUMERATE_FACE (iface, allCells().outerFaceGroup()) {\n    m_fD[iface] = funcD(m_face_center[*iface], m_face_type[*iface]);\n    m_fN[iface] = funcN(m_face_center[*iface], m_face_type[*iface]);\n    m_flux[iface] = funcD(m_face_center[*iface], m_face_type[*iface]);\n  }\n}\n\nvoid\nAlienStokesModule::test()\n{\n  Timer pbuild_timer(subDomain(), \"PBuildPhase\", Timer::TimerReal);\n\n  ItemGroup areaP = allCells();\n  ItemGroup areaU = allCells().innerFaceGroup();\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // CREATE GLOBAL Space FROM IndexManger\n  // CREATE MATRIX ASSOCIATED TO Space\n  // CREATE VECTORS ASSOCIATED TO Space\n  //\n\n  Alien::ArcaneTools::BasicIndexManager index_manager(m_parallel_mng);\n  index_manager.setTraceMng(traceMng());\n  auto indexSetU = index_manager.buildScalarIndexSet(\"U\", areaU);\n  auto indexSetP = index_manager.buildScalarIndexSet(\"P\", areaP);\n  index_manager.prepare();\n  info() << \"U Size : \" << indexSetU.getAllIndexes().size();\n  info() << \"P Size : \" << indexSetP.getAllIndexes().size();\n\n  // Accès à l'indexation\n  Alien::UniqueArray<Integer> allPIndex = index_manager.getIndexes(indexSetP);\n  Alien::UniqueArray<Integer> allUIndex = index_manager.getIndexes(indexSetU);\n\n  Alien::ArcaneTools::Space space(&index_manager);\n  m_mdist = Alien::ArcaneTools::createMatrixDistribution(space);\n  m_vdist = Alien::ArcaneTools::createVectorDistribution(space);\n\n  info() << \"Space size = \" << m_vdist.globalSize()\n         << \", local size= \" << m_vdist.localSize();\n\n  Alien::Matrix matrixA(m_mdist); // local matrix for exact measure without side effect\n                                  // (however, you can reuse a matrix with several\n                                  // builder)\n\n  Alien::Vector vectorB(m_vdist);\n  Alien::Vector vectorX(m_vdist);\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // CREATE COMPOSITE Space FROM TWO IndexManger\n  // CREATE MATRICES ASSOCIATED TO Composite Space USPace and PSpace\n  // CREATE VECTORS ASSOCIATED TO USpace and PSpace\n  //\n\n  Alien::ArcaneTools::BasicIndexManager u_index_manager(m_parallel_mng);\n  u_index_manager.setTraceMng(traceMng());\n  auto u_indexSet = u_index_manager.buildScalarIndexSet(\"U\", areaU);\n  u_index_manager.prepare();\n  info() << \"U Size : \" << u_indexSet.getAllIndexes().size();\n\n  Alien::ArcaneTools::BasicIndexManager p_index_manager(m_parallel_mng);\n  p_index_manager.setTraceMng(traceMng());\n  auto p_indexSet = p_index_manager.buildScalarIndexSet(\"P\", areaP);\n  p_index_manager.prepare();\n  info() << \"P Size : \" << p_indexSet.getAllIndexes().size();\n\n  auto u_global_size = u_index_manager.globalSize();\n  auto u_local_size = u_index_manager.localSize();\n  auto p_global_size = p_index_manager.globalSize();\n  auto p_local_size = p_index_manager.localSize();\n\n  m_Adist = MatrixDistribution(\n      u_global_size, u_global_size, u_local_size, parallelMng()->messagePassingMng());\n  m_Bdist = MatrixDistribution(\n      u_global_size, p_global_size, u_local_size, parallelMng()->messagePassingMng());\n  m_tBdist = MatrixDistribution(\n      p_global_size, u_global_size, p_local_size, parallelMng()->messagePassingMng());\n  m_udist =\n      VectorDistribution(u_global_size, u_local_size, parallelMng()->messagePassingMng());\n  m_pdist =\n      VectorDistribution(p_global_size, p_local_size, parallelMng()->messagePassingMng());\n\n  Alien::Matrix A(m_Adist);\n  Alien::Matrix B(m_Bdist);\n  Alien::Matrix tB(m_tBdist);\n\n  Alien::Vector g(m_pdist);\n  Alien::Vector f(m_udist);\n\n  Alien::UniqueArray<Integer> allPIndexB = p_index_manager.getIndexes(p_indexSet);\n  Alien::UniqueArray<Integer> allUIndexA = u_index_manager.getIndexes(u_indexSet);\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // MATRIX BUILDING AND FILLING\n  //\n  {\n    Timer::Sentry ts(&pbuild_timer);\n    Alien::MatrixProfiler profiler(matrixA);\n\n    info() << \"DEFINE BLOCK MATRIX PROFILE\";\n    Alien::MatrixProfiler profilerA(A);\n    Alien::MatrixProfiler profilerB(B);\n    Alien::MatrixProfiler profilertB(tB);\n\n    ///////////////////////////////////////////////////////////////////////////\n    //\n    // DEFINE PROFILE\n    //\n\n    //\n    // UX, UY, UZ equations\n    //\n    info() << \"DEFINE BLOCK U-U PROFILE\";\n\n    UniqueArray2<Integer> connectivity(dim, 2);\n    ENUMERATE_FACE (iface, areaP.innerFaceGroup().own()) {\n      const Face& face = *iface;\n      auto face_lid = iface->localId();\n      auto face_type = m_face_type[face];\n      info() << \"FACE[\" << face_lid << \"]\";\n      const Integer iIndex = allUIndex[face.localId()];\n      assert(iIndex != -1);\n      profiler.addMatrixEntry(iIndex, allUIndex[face.localId()]);\n\n      const Integer iIndexA = allUIndexA[face.localId()];\n      assert(iIndexA != -1);\n\n      profilerA.addMatrixEntry(iIndexA, allUIndexA[face.localId()]);\n\n      ENUMERATE_CELL (icell, iface->cells()) {\n        const Cell& cell = *icell;\n        info() << \"            CELL[\" << cell.localId() << \"]\";\n        assert(allPIndex[cell.localId()] != -1);\n        profiler.addMatrixEntry(iIndex, allPIndex[cell.localId()]);\n\n        profilerB.addMatrixEntry(iIndexA, allPIndexB[cell.localId()]);\n        ENUMERATE_FACE (iface2, cell.faces()) {\n          if (!iface2->isSubDomainBoundary()) {\n            if (iface2->localId() != face_lid && m_face_type[*iface2] == face_type) {\n              profiler.addMatrixEntry(iIndex, allUIndex[iface2->localId()]);\n\n              profilerA.addMatrixEntry(iIndexA, allUIndexA[iface2->localId()]);\n            }\n          }\n        }\n      }\n\n      _computeFaceConnectivity(face, connectivity);\n      for (Integer i = 0; i < dim; ++i) {\n        if (i != face_type) {\n          for (Integer iconn = 0; iconn < 2; ++iconn) {\n            if (connectivity[i][iconn] != -1) {\n              assert(allUIndex[connectivity[i][iconn]] != -1);\n              profiler.addMatrixEntry(iIndex, allUIndex[connectivity[i][iconn]]);\n\n              profilerA.addMatrixEntry(iIndexA, allUIndexA[connectivity[i][iconn]]);\n            }\n          }\n        }\n      }\n    }\n\n    //\n    // P equations\n    //\n    info() << \"DEFINE BLOCK P-U PROFILE\";\n    ENUMERATE_CELL (icell, areaP.own()) {\n      const Cell& cell = *icell;\n      const Integer iIndex = allPIndex[cell.localId()];\n      assert(iIndex != -1);\n      info() << \"CELL[\" << cell.localId() << \"]\";\n      if (m_cell_center[icell].abs() < m_h[0]) {\n        profiler.addMatrixEntry(iIndex, iIndex);\n      }\n\n      const Integer iIndexB = allPIndexB[cell.localId()];\n      assert(iIndexB != -1);\n\n      ENUMERATE_FACE (iface, icell->faces()) {\n        const Face& face = *iface;\n        info() << \"        FACE[\" << face.localId() << \"]\";\n        if (!face.isSubDomainBoundary()) {\n          assert(allUIndex[face.localId()] != -1);\n          profiler.addMatrixEntry(iIndex, allUIndex[face.localId()]);\n\n          assert(allUIndexA[face.localId()] != -1);\n          profilertB.addMatrixEntry(iIndexB, allUIndexA[face.localId()]);\n        }\n      }\n    }\n  }\n\n  {\n    Timer::Sentry ts(&pbuild_timer);\n\n    info() << \"FILL MATRIX VALUE\";\n    Alien::ProfiledMatrixBuilder builder(\n        matrixA, Alien::ProfiledMatrixOptions::eResetValues);\n\n    info() << \"FILL A FILLER\";\n    Alien::ProfiledMatrixBuilder builderA(A, Alien::ProfiledMatrixOptions::eResetValues);\n    info() << \"FILL B FILLER\";\n    Alien::ProfiledMatrixBuilder builderB(B, Alien::ProfiledMatrixOptions::eResetValues);\n    info() << \"FILL tB FILLER\";\n    Alien::ProfiledMatrixBuilder buildertB(\n        tB, Alien::ProfiledMatrixOptions::eResetValues);\n\n    info() << \"INIT VECTORS\";\n    Alien::LocalVectorWriter rhs(vectorB);\n    for (Integer i = 0; i < rhs.size(); ++i)\n      rhs[i] = 0.;\n\n    Alien::LocalVectorWriter rhsU(f);\n    for (Integer i = 0; i < rhsU.size(); ++i)\n      rhsU[i] = 0.;\n\n    Alien::LocalVectorWriter rhsP(g);\n    for (Integer i = 0; i < rhsP.size(); ++i)\n      rhsP[i] = 0.;\n\n    //\n    // UX, UY, UZ equations\n    //\n    info() << \"FILL U-U MATRIX VALUE\";\n    UniqueArray2<Integer> connectivity(dim, 2);\n    ENUMERATE_FACE (iface, areaP.innerFaceGroup().own()) {\n      const Face& face = *iface;\n      if (face.isSubDomainBoundary())\n        continue;\n\n      auto face_lid = iface->localId();\n      auto face_type = m_face_type[face];\n\n      const Integer iIndex = allUIndex[face.localId()];\n      assert(iIndex != -1);\n      rhs[iIndex] += m_f[face];\n\n      const Integer iIndexU = allUIndexA[face.localId()];\n      assert(iIndexU != -1);\n      rhsU[iIndexU] += m_f[face];\n\n      Integer orientation = m_face_orientation[iface];\n\n      Cell front_cell = iface->frontCell();\n      if (!front_cell.null()) {\n        builder(iIndex, allPIndex[front_cell.localId()]) = orientation / m_h[face_type];\n\n        builderB(iIndexU, allPIndexB[front_cell.localId()]) =\n            orientation / m_h[face_type];\n\n        ENUMERATE_FACE (iface2, front_cell.faces()) {\n          if (iface2->localId() != face_lid && m_face_type[*iface2] == face_type) {\n            if (iface2->isSubDomainBoundary()) {\n              Integer bc_type = getBCType(*iface2);\n              switch (bc_type) {\n              case Neumann:\n                rhs[iIndex] += m_fN[*iface2] / m_h[face_type];\n                rhsU[iIndexU] += m_fN[*iface2] / m_h[face_type];\n\n                break;\n              case Dirichlet:\n              default:\n                rhs[iIndex] += m_fD[*iface2] / m_h2[face_type];\n                builder(iIndex, iIndex) += 1. / m_h2[face_type];\n\n                rhsU[iIndexU] += m_fD[*iface2] / m_h2[face_type];\n                builderA(iIndexU, iIndexU) += 1. / m_h2[face_type];\n\n                break;\n              }\n            } else {\n              builder(iIndex, allUIndex[iface2->localId()]) += -1 / m_h2[face_type];\n              builder(iIndex, iIndex) += 1. / m_h2[face_type];\n\n              builderA(iIndexU, allUIndexA[iface2->localId()]) += -1 / m_h2[face_type];\n              builderA(iIndexU, iIndexU) += 1. / m_h2[face_type];\n            }\n          }\n        }\n      }\n      Cell back_cell = iface->backCell();\n      if (!back_cell.null()) {\n        builder(iIndex, allPIndex[back_cell.localId()]) =\n            -1. * orientation / m_h[face_type];\n        builderB(iIndexU, allPIndexB[back_cell.localId()]) =\n            -1. * orientation / m_h[face_type];\n\n        ENUMERATE_FACE (iface2, back_cell.faces()) {\n          if (iface2->localId() != face_lid && m_face_type[*iface2] == face_type) {\n            if (iface2->isSubDomainBoundary()) {\n              Integer bc_type = getBCType(*iface2);\n              switch (bc_type) {\n              case Neumann:\n                rhs[iIndex] += m_fN[*iface2] / m_h[face_type];\n                rhsU[iIndexU] += m_fN[*iface2] / m_h[face_type];\n\n                break;\n              case Dirichlet:\n              default:\n                rhs[iIndex] += m_fD[*iface2] / m_h2[face_type];\n                builder(iIndex, iIndex) += 1. / m_h2[face_type];\n\n                rhsU[iIndex] += m_fD[*iface2] / m_h2[face_type];\n                builderA(iIndexU, iIndexU) += 1. / m_h2[face_type];\n\n                break;\n              }\n            } else {\n              builder(iIndex, allUIndex[iface2->localId()]) += -1 / m_h2[face_type];\n              builder(iIndex, iIndex) += 1. / m_h2[face_type];\n\n              builderA(iIndexU, allUIndexA[iface2->localId()]) += -1 / m_h2[face_type];\n              builder(iIndexU, iIndexU) += 1. / m_h2[face_type];\n            }\n          }\n        }\n      }\n      _computeFaceConnectivity(face, connectivity);\n      for (Integer dir = 0; dir < dim; ++dir) {\n        if (dir != face_type) {\n          for (Integer iconn = 0; iconn < 2; ++iconn) {\n            if (connectivity[dir][iconn] >= 0) {\n              assert(allUIndex[connectivity[dir][iconn]] != -1);\n              builder(iIndex, allUIndex[connectivity[dir][iconn]]) += -1 / m_h2[dir];\n              builder(iIndex, iIndex) += 1. / m_h2[dir];\n\n              builderA(iIndexU, allUIndexA[connectivity[dir][iconn]]) += -1 / m_h2[dir];\n              builderA(iIndexU, iIndexU) += 1. / m_h2[dir];\n            } else {\n              Integer inode0 = -connectivity[dir][iconn] - 1;\n              Node node0 = face.node(inode0);\n              Real3 xN0 = m_node_coord[node0];\n              Integer inode1 = inode0 == face.nbNode() - 1 ? 0 : inode0 + 1;\n              Node node1 = face.node(inode1);\n              Real3 xN1 = m_node_coord[node1];\n              Integer bc_type = getBCType(xN0, dir);\n              switch (bc_type) {\n              case Neumann:\n                rhs[iIndex] += 0.5 * (funcN(xN0, dir) + funcN(xN1, dir)) / m_h[dir];\n                rhsU[iIndexU] += 0.5 * (funcN(xN0, dir) + funcN(xN1, dir)) / m_h[dir];\n                break;\n              case Dirichlet:\n              default:\n                rhs[iIndex] += (funcD(xN0, dir) + funcD(xN1, dir)) / m_h2[dir];\n                builder(iIndex, iIndex) += 1. / m_h2[dir];\n\n                rhsU[iIndexU] += (funcD(xN0, dir) + funcD(xN1, dir)) / m_h2[dir];\n                builderA(iIndexU, iIndexU) += 1. / m_h2[dir];\n                break;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    //\n    // P equations\n    //\n    ENUMERATE_CELL (icell, areaP.own()) {\n      const Cell& cell = *icell;\n      Integer cell_lid = icell->localId();\n      const Integer iIndex = allPIndex[cell.localId()];\n      assert(iIndex != -1);\n\n      const Integer iIndexP = allPIndexB[cell.localId()];\n      assert(iIndexP != -1);\n\n      if (m_cell_center[icell].abs() < m_h[0])\n        builder(iIndex, iIndex) = 1000000;\n\n      rhs[iIndex] += m_g[cell];\n\n      rhsP[iIndexP] += m_g[cell];\n\n      ENUMERATE_FACE (iface, icell->faces()) {\n        const Face& face = *iface;\n        Integer face_lid = face.localId();\n        Integer face_type = m_face_type[face];\n        Integer up = _upStreamFace(face, cell_lid);\n        if (face.isSubDomainBoundary()) {\n          rhs[iIndex] -= up / m_h[face_type];\n          rhsP[iIndexP] -= up / m_h[face_type];\n\n          Integer bc_type = getBCType(*iface);\n          info() << \"     Boundary F\" << bc_type;\n          switch (bc_type) {\n          case Neumann:\n            rhs[iIndex] -= up * m_fN[*iface];\n            rhsP[iIndexP] -= up * m_fN[*iface];\n            ENUMERATE_FACE (iface2, icell->faces()) {\n              Face const& face2 = *iface2;\n              Integer face2_type = m_face_type[face2];\n              Integer face2_lid = face2.localId();\n              if (face2_lid != face_lid && face2_type == face_type) {\n                builder(iIndex, allUIndex[face2.localId()]) += up / m_h[face_type];\n                buildertB(iIndexP, allUIndexA[face2.localId()]) += up / m_h[face_type];\n              }\n            }\n            break;\n          case Dirichlet:\n          default:\n            rhs[iIndex] -= up * m_fD[*iface] / m_h[face_type];\n            rhsP[iIndexP] -= up * m_fD[*iface] / m_h[face_type];\n            break;\n          }\n        } else {\n          builder(iIndex, allUIndex[face.localId()]) += up / m_h[face_type];\n          buildertB(iIndexP, allUIndexA[face.localId()]) += up / m_h[face_type];\n        }\n      }\n    }\n\n    info() << \"BUILDER FINALIZE\";\n\n    builder.finalize();\n\n    builderA.finalize();\n    builderB.finalize();\n    buildertB.finalize();\n  }\n\n  {\n    SystemWriter writer(\"StokesMatrix\", \"ascii\", parallelMng()->messagePassingMng());\n    writer.dump(matrixA);\n  }\n  {\n    SystemWriter writer(\"StokesMatrixA\", \"ascii\", parallelMng()->messagePassingMng());\n    writer.dump(A);\n  }\n  {\n    SystemWriter writer(\"StokesMatrixB\", \"ascii\", parallelMng()->messagePassingMng());\n    writer.dump(B);\n  }\n  {\n    SystemWriter writer(\"StokesMatrixtB\", \"ascii\", parallelMng()->messagePassingMng());\n    writer.dump(tB);\n  }\n  {\n    std::ofstream fout(\"StokesVectorF.txt\");\n    Alien::VectorReader f_view(f);\n    fout << f_view.size() << std::endl;\n    for (int i = 0; i < f_view.size(); ++i) {\n      fout << i << \" \" << f_view[i] << std::endl;\n    }\n  }\n  {\n    std::ofstream fout(\"StokesVectorG.txt\");\n    Alien::VectorReader g_view(g);\n    fout << g_view.size() << std::endl;\n    for (int i = 0; i < g_view.size(); ++i) {\n      fout << i << \" \" << g_view[i] << std::endl;\n    }\n  }\n\n  info() << \"===================================================\";\n  info() << \"STOKES INFO :\";\n  info() << \" PBUILD    :\" << pbuild_timer.totalTime();\n  info() << \"===================================================\";\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // RESOLUTION\n  //\n  bool solve = true;\n  if (solve) {\n    Alien::Vector p(m_pdist);\n    Alien::Vector u(m_udist);\n\n    // Initial guest\n    Alien::LocalVectorWriter u0_view(u);\n    for (Integer i = 0; i < u0_view.size(); ++i)\n      u0_view[i] = 0.;\n\n    Alien::LocalVectorWriter p0_view(p);\n    for (Integer i = 0; i < p0_view.size(); ++i)\n      p0_view[i] = 0.;\n\n    bool succeed = solveUzawaMethod(A, B, tB, f, g, u, p);\n\n    if (succeed) {\n      Alien::VectorReader u_view(u);\n      Alien::VectorReader p_view(p);\n\n      ENUMERATE_FACE (iface, areaU.own()) {\n        const Integer iIndex = allUIndexA[iface->localId()];\n        m_flux[iface] = u_view[iIndex];\n      }\n\n      m_v.resize(dim);\n      ENUMERATE_CELL (icell, areaP.own()) {\n        const Integer iIndex = allPIndexB[icell->localId()];\n        m_p[icell] = p_view[iIndex];\n        Real v[dim] = { 0., 0., 0. };\n        ENUMERATE_FACE (iface, icell->faces()) {\n          v[m_face_type[*iface]] += m_flux[*iface];\n        }\n        m_v[icell][0] = v[0] / 2;\n        m_v[icell][1] = v[1] / 2;\n        m_v[icell][2] = v[2] / 2;\n        m_e[icell] = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) / 4;\n      }\n    }\n  }\n\n  subDomain()->timeLoopMng()->stopComputeLoop(true);\n}\n\n/*---------------------------------------------------------------------------*/\n\nReal\nAlienStokesModule::pressure(Real3 const& x) const\n{\n  return 1 - x[0];\n}\n\nReal\nAlienStokesModule::ux(Real3 const& x) const\n{\n  return 1 + x[0];\n}\n\nReal\nAlienStokesModule::duxdn(Real3 const& x, Integer dir) const\n{\n  switch (dir) {\n  case 0:\n    return 1.;\n  default:\n    return 0.;\n  }\n}\n\nReal\nAlienStokesModule::uy(Real3 const& x) const\n{\n  return x[1] - 0.5;\n}\n\nReal\nAlienStokesModule::duydn(Real3 const& x, Integer dir) const\n{\n  switch (dir) {\n  case 1:\n    return 1.;\n  default:\n    return 0.;\n  }\n}\n\nReal\nAlienStokesModule::uz(Real3 const& x) const\n{\n  return x[2] - 0.5;\n}\n\nReal\nAlienStokesModule::duzdn(Real3 const& x, Integer dir) const\n{\n  switch (dir) {\n  case 2:\n    return 1.;\n  default:\n    return 0.;\n  }\n}\n\nReal\nAlienStokesModule::div(Real3 const& xC) const\n{\n  return 3;\n}\n\nReal\nAlienStokesModule::func(Real3 const& xC, Integer dir) const\n{\n  switch (dir) {\n  case 0:\n    return 1;\n  default:\n    return 0.;\n  }\n}\n\nReal\nAlienStokesModule::funcN(Real3 const& xF, Integer dir) const\n{\n  switch (dir) {\n  case 0:\n    return duxdn(xF, dir);\n  case 1:\n    return duydn(xF, dir);\n  case 2:\n    return duzdn(xF, dir);\n  default:\n    return 0.;\n  }\n}\n\nReal\nAlienStokesModule::funcD(Real3 const& xF, Integer dir) const\n{\n  switch (dir) {\n  case 0:\n    return ux(xF);\n  case 1:\n    return uy(xF);\n  case 2:\n    return uz(xF);\n  default:\n    return 0.;\n  }\n}\n\nbool\nAlienStokesModule::solveUzawaMethod(Alien::Matrix& A, Alien::Matrix& B, Alien::Matrix& tB,\n    Alien::Vector& f, Alien::Vector& g, Alien::Vector& uk, Alien::Vector& pk)\n{\n  Timer psolve_timer(subDomain(), \"PSolvePhase\", Timer::TimerReal);\n\n  m_omega = options()->uzawaFactor();\n  m_uzawa_max_nb_iterations = options()->uzawaMaxNbIterations();\n\n  Alien::ILinearSolver* solver = options()->linearSolver();\n  solver->init();\n\n  Vector ru(m_udist);\n  Vector rp(m_pdist);\n\n  using namespace Alien;\n  using namespace Alien::MVExpr;\n\n  for (int k = 0; k < m_uzawa_max_nb_iterations; ++k) {\n    // Update velocity\n    ru = f - B * pk;\n\n    {\n      Timer::Sentry ts(&psolve_timer);\n      solver->solve(A, ru, uk);\n    }\n    Alien::SolverStatus status = solver->getStatus();\n    if (!status.succeeded)\n      return false;\n\n    rp = g - tB * uk;\n    // Update pressure\n    pk = pk - m_omega * rp;\n  }\n\n  solver->end();\n\n  info() << \"===================================================\";\n  info() << \"STOKES INFO :\";\n  info() << \" PSOLVE    :\" << psolve_timer.totalTime();\n  info() << \"===================================================\";\n\n  return true;\n}\n\n/*---------------------------------------------------------------------------*/\n\nARCANE_REGISTER_MODULE_ALIENSTOKES(AlienStokesModule);\n", "meta": {"hexsha": "1b82de876b6502687ce3160c62ffef2ffbc26804", "size": 28203, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/AlienBench/AlienStokesModule.cc", "max_stars_repo_name": "cedricga91/alien_legacy_plugins", "max_stars_repo_head_hexsha": "459701026d76dbe1e8a6b20454f6b50ec9722f7f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T09:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T14:22:35.000Z", "max_issues_repo_path": "test/AlienBench/AlienStokesModule.cc", "max_issues_repo_name": "cedricga91/alien_legacy_plugins", "max_issues_repo_head_hexsha": "459701026d76dbe1e8a6b20454f6b50ec9722f7f", "max_issues_repo_licenses": ["Apache-2.0"], "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/AlienBench/AlienStokesModule.cc", "max_forks_repo_name": "cedricga91/alien_legacy_plugins", "max_forks_repo_head_hexsha": "459701026d76dbe1e8a6b20454f6b50ec9722f7f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T14:50:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:23:07.000Z", "avg_line_length": 29.5939139559, "max_line_length": 90, "alphanum_fraction": 0.5824557671, "num_tokens": 8085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.029760091794651562, "lm_q1q2_score": 0.010587893489198023}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 14:43:25\n\n#ifndef SSM_SLHA_IO_H\n#define SSM_SLHA_IO_H\n\n#include \"SSM_mass_eigenstates.hpp\"\n#include \"SSM_model_slha.hpp\"\n#include \"SSM_info.hpp\"\n#include \"SSM_observables.hpp\"\n#include \"SSM_physical.hpp\"\n#include \"problems.hpp\"\n#include \"spectrum_generator_problems.hpp\"\n#include \"standard_model_two_scale_model.hpp\"\n#include \"slha_io.hpp\"\n#include \"ckm.hpp\"\n#include \"ew_input.hpp\"\n#include \"lowe.h\"\n\n#include <Eigen/Core>\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp>\n\n#define Pole(p) physical.p\n#define PHYSICAL(p) model.get_physical().p\n#define PHYSICAL_SLHA(p) model.get_physical_slha().p\n#define LOCALPHYSICAL(p) physical.p\n#define MODEL model\n#define MODELPARAMETER(p) model.get_##p()\n#define EXTRAPARAMETER(p) model.get_##p()\n#define OBSERVABLES observables\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define SCALES(p) scales.p\n\nnamespace flexiblesusy {\n\nstruct SSM_input_parameters;\nclass Spectrum_generator_settings;\n\ntemplate <class T>\nclass SSM;\n\nstruct SSM_scales {\n   double HighScale{0.}, SUSYScale{0.}, LowScale{0.};\n   double pole_mass_scale{0.};\n};\n\nclass SSM_slha_io {\npublic:\n   SSM_slha_io();\n\n   void clear();\n\n   void fill(softsusy::QedQcd& qedqcd) const { slha_io.fill(qedqcd); }\n   void fill(SSM_input_parameters&) const;\n   void fill(SSM_mass_eigenstates&) const;\n   template <class Model> void fill(SSM_slha<Model>&) const;\n   void fill(Physical_input&) const;\n   void fill(Spectrum_generator_settings&) const;\n   double get_parameter_output_scale() const;\n   const SLHA_io& get_slha_io() const { return slha_io; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   void set_block(const std::string& str, SLHA_io::Position position = SLHA_io::back) { slha_io.set_block(str, position); }\n   void set_blocks(const std::vector<std::string>& vec, SLHA_io::Position position = SLHA_io::back) { slha_io.set_blocks(vec, position); }\n   template <class Model> void set_extra(const SSM_slha<Model>&, const SSM_scales&, const SSM_observables&);\n   void set_input(const SSM_input_parameters&);\n   void set_modsel(const SLHA_io::Modsel&);\n   void set_physical_input(const Physical_input&);\n   void set_settings(const Spectrum_generator_settings&);\n   void set_sminputs(const softsusy::QedQcd&);\n   template <class... Ts> void set_spectrum(const std::tuple<Ts...>&);\n   template <class Model> void set_spectrum(const SSM_slha<Model>&);\n   template <class T> void set_spectrum(const SSM<T>&);\n   void set_spectrum(const standard_model::Standard_model& m) { slha_io.set_spectrum(m); }\n   void set_spinfo(const Spectrum_generator_problems&);\n   void set_spinfo(const Problems&);\n   void set_spinfo(const std::vector<std::string>&, const std::vector<std::string>&);\n   void set_print_imaginary_parts_of_majorana_mixings(bool);\n   void write_to(const std::string&) const;\n   void write_to_file(const std::string& file_name) const { slha_io.write_to_file(file_name); }\n   void write_to_stream(std::ostream& ostr = std::cout) const { slha_io.write_to_stream(ostr); }\n\n   static void fill_minpar_tuple(SSM_input_parameters&, int, double);\n   static void fill_extpar_tuple(SSM_input_parameters&, int, double);\n   static void fill_imminpar_tuple(SSM_input_parameters&, int, double);\n   static void fill_imextpar_tuple(SSM_input_parameters&, int, double);\n\n   template <class Model>\n   static void fill_slhaea(SLHAea::Coll&, const SSM_slha<Model>&, const softsusy::QedQcd&, const SSM_scales&, const SSM_observables&);\n\n   template <class Model>\n   static SLHAea::Coll fill_slhaea(const SSM_slha<Model>&, const softsusy::QedQcd&, const SSM_scales&, const SSM_observables&);\n\nprivate:\n   SLHA_io slha_io; ///< SLHA io class\n   bool print_imaginary_parts_of_majorana_mixings;\n\n   void set_extpar(const SSM_input_parameters&);\n   void set_imminpar(const SSM_input_parameters&);\n   void set_imextpar(const SSM_input_parameters&);\n   void set_minpar(const SSM_input_parameters&);\n   void set_mass(const SSM_physical&, bool);\n   void set_mixing_matrices(const SSM_physical&, bool);\n   template <class Model> void set_model_parameters(const SSM_slha<Model>&);\n   void set_ckm(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   void set_pmns(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   double read_scale() const;\n   void fill_drbar_parameters(SSM_mass_eigenstates&) const;\n   void fill_physical(SSM_physical&) const;\n};\n\n/**\n * Reads DR-bar parameters, pole masses and mixing matrices from a\n * SLHA output file.\n */\ntemplate <class Model>\nvoid SSM_slha_io::fill(SSM_slha<Model>& model) const\n{\n   fill(static_cast<SSM_mass_eigenstates&>(model));\n   fill_physical(model.get_physical_slha());\n}\n\ntemplate <class Model>\nvoid SSM_slha_io::fill_slhaea(\n   SLHAea::Coll& slhaea, const SSM_slha<Model>& model,\n   const softsusy::QedQcd& qedqcd, const SSM_scales& scales,\n   const SSM_observables& observables)\n{\n   SSM_slha_io slha_io;\n   const SSM_input_parameters& input = model.get_input();\n   const auto& problems = model.get_problems();\n   const bool error = problems.have_problem();\n\n   slha_io.set_spinfo(problems);\n   slha_io.set_sminputs(qedqcd);\n   slha_io.set_input(input);\n   if (!error) {\n      slha_io.set_spectrum(model);\n      slha_io.set_extra(model, scales, observables);\n   }\n\n   slhaea = slha_io.get_slha_io().get_data();\n}\n\ntemplate <class Model>\nSLHAea::Coll SSM_slha_io::fill_slhaea(\n   const SSM_slha<Model>& model, const softsusy::QedQcd& qedqcd,\n   const SSM_scales& scales, const SSM_observables& observables)\n{\n   SLHAea::Coll slhaea;\n   SSM_slha_io::fill_slhaea(slhaea, model, qedqcd, scales, observables);\n\n   return slhaea;\n}\n\n/**\n * Stores the model (DR-bar) parameters in the SLHA object.\n *\n * @param model model class\n */\ntemplate <class Model>\nvoid SSM_slha_io::set_model_parameters(const SSM_slha<Model>& model)\n{\n   {\n      std::ostringstream block;\n      block << \"Block gauge Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(g1) * 0.7745966692414834), \"g1 * 0.7745966692414834\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(g2)), \"g2\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(g3)), \"g3\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"Yu\", ToMatrix(MODELPARAMETER(Yu_slha)), \"Yu\", model.get_scale());\n   slha_io.set_block(\"Yd\", ToMatrix(MODELPARAMETER(Yd_slha)), \"Yd\", model.get_scale());\n   slha_io.set_block(\"Ye\", ToMatrix(MODELPARAMETER(Ye_slha)), \"Ye\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block SM Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(mu2)), \"mu2\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(Lambdax)), \"Lambdax\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block HMIX Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(v)), \"v\")\n            << FORMAT_ELEMENT(51, (MODELPARAMETER(vS)), \"vS\")\n            << FORMAT_ELEMENT(31, (MODELPARAMETER(K1)), \"K1\")\n            << FORMAT_ELEMENT(32, (MODELPARAMETER(K2)), \"K2\")\n            << FORMAT_ELEMENT(35, (MODELPARAMETER(Kappa)), \"Kappa\")\n            << FORMAT_ELEMENT(33, (MODELPARAMETER(LambdaS)), \"LambdaS\")\n            << FORMAT_ELEMENT(34, (MODELPARAMETER(MS)), \"MS\")\n      ;\n      slha_io.set_block(block);\n   }\n\n\n}\n\n/**\n * Writes extra SLHA blocks\n *\n * @param model model class\n * @param scales struct of boundary condition scales\n * @param observables struct of observables\n */\ntemplate <class Model>\nvoid SSM_slha_io::set_extra(\n   const SSM_slha<Model>& model, const SSM_scales& scales,\n   const SSM_observables& observables)\n{\n   const SSM_physical physical(model.get_physical_slha());\n\n   {\n      std::ostringstream block;\n      block << \"Block FlexibleSUSYLowEnergy Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (OBSERVABLES.a_muon), \"Delta(g-2)_muon/2 FlexibleSUSY\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block EFFHIGGSCOUPLINGS\" << '\\n'\n            << FORMAT_RANK_THREE_TENSOR(25, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon(0))), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(35, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon(1))), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(25, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon(0))), \"Abs(effective H-Gluon-Gluon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(35, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon(1))), \"Abs(effective H-Gluon-Gluon coupling)\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices of\n * all given models in the SLHA object.\n *\n * @todo Use generic lambda instead of Set_spectrum in C++14\n *\n * @param models model classes\n */\ntemplate <class... Ts>\nvoid SSM_slha_io::set_spectrum(const std::tuple<Ts...>& models)\n{\n   Set_spectrum<SSM_slha_io> ss(this);\n   boost::fusion::for_each(models, ss);\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in BPMZ convention\n */\ntemplate <class T>\nvoid SSM_slha_io::set_spectrum(const SSM<T>& model)\n{\n   set_spectrum(SSM_slha<SSM<T> >(model));\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in SLHA convention\n */\ntemplate <class Model>\nvoid SSM_slha_io::set_spectrum(const SSM_slha<Model>& model)\n{\n   const SSM_physical physical(model.get_physical_slha());\n   const bool write_sm_masses = model.do_calculate_sm_pole_masses();\n\n   set_model_parameters(model);\n   set_mass(physical, write_sm_masses);\n   set_mixing_matrices(physical, write_sm_masses);\n\n   if (slha_io.get_modsel().quark_flavour_violated)\n      set_ckm(model.get_ckm_matrix(), model.get_scale());\n\n   if (slha_io.get_modsel().lepton_flavour_violated)\n      set_pmns(model.get_pmns_matrix(), model.get_scale());\n}\n\n} // namespace flexiblesusy\n\n#undef Pole\n#undef PHYSICAL\n#undef PHYSICAL_SLHA\n#undef LOCALPHYSICAL\n#undef MODEL\n#undef MODELPARAMETER\n#undef EXTRAPARAMETER\n#undef OBSERVABLES\n#undef LowEnergyConstant\n#undef SCALES\n\n#endif\n", "meta": {"hexsha": "a782aa85cd49767d0e1356205e9d07da3626f80c", "size": 11314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/SSM/SSM_slha_io.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/SSM/SSM_slha_io.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/SSM/SSM_slha_io.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": 35.1366459627, "max_line_length": 144, "alphanum_fraction": 0.7092982146, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.025957359364135853, "lm_q1q2_score": 0.010573299446007524}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Aleksei Moskvin <alalmoskvin@gmail.com>\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 substantfrom_store_configs_and_replicaial 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_MERKLE_HPP\n#define FILECOIN_MERKLE_HPP\n\n#include <nil/filecoin/storage/proofs/core/merkle/storage/utilities.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/optional.hpp>\n#include <nil/filecoin/storage/proofs/core/merkle/storage/vec.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        namespace merkletree {\n            const size_t SMALL_TREE_BUILD = 1024;\n\n            // Number of nodes to process in parallel during the `build` stage.\n            const size_t BUILD_CHUNK_NODES = 1024 * 4;\n            // Number of batched nodes processed and stored together when\n            // populating from the data leaves.\n            const size_t BUILD_DATA_BLOCK_SIZE = 64 * BUILD_CHUNK_NODES;\n\n            // Merkle Tree.\n            //\n            // All leafs and nodes are stored in a linear array (vec).\n            //\n            // A merkle tree is a tree in which every non-leaf node is the hash of its\n            // child nodes. A diagram depicting how it works://\n            // ```text\n            //         root = h1234 = h(h12 + h34)\n            //        /                           \\\n            //  h12 = h(h1 + h2)            h34 = h(h3 + h4)\n            //   /            \\              /            \\\n            // h1 = h(tx1)  h2 = h(tx2)    h3 = h(tx3)  h4 = h(tx4)\n            // ```\n            //\n            // In memory layout:\n            //\n            // ```text\n            //     [h1 h2 h3 h4 h12 h34 root]\n            // ```\n            //\n            // Merkle root is always the last element in the array.\n            //\n            // The number of inputs must always be a power of two.\n            //\n            // This tree structure can consist of at most 3 layers of trees (of\n            // arity U, N and R, from bottom to top).\n            //\n            // This structure ties together multiple Merkle Trees and allows\n            // supported properties of the Merkle Trees across it.  The\n            // significance of this class is that it allows an arbitrary number\n            // of sub-trees to be constructed and proven against.\n            //\n            // To show an example, this structure can be used to create a single\n            // tree composed of 3 sub-trees, each that have branching factors /\n            // arity of 4.  Graphically, this may look like this:\n            //\n            // ```text\n            //                O\n            //       ________/|\\_________\n            //      /         |          \\\n            //     O          O           O\n            //  / / \\ \\    / / \\ \\     / / \\ \\\n            // O O  O  O  O O  O  O   O O  O  O\n            //\n            //\n            // At most, one more layer (top layer) can be constructed to group a\n            // number of the above sub-tree structures (not pictured).\n            //\n            // BaseTreeArity is the arity of the base layer trees [bottom].\n            // SubTreeArity is the arity of the sub-tree layer of trees [middle].\n            // TopTreeArity is the arity of the top layer of trees [top].\n            //\n            // With N and R defaulting to 0, the tree performs as a single base\n            // layer merkle tree without layers (i.e. a conventional merkle\n            // tree).\n            template<typename Hash>\n            struct MerkleTree_basic_policy {\n                typedef std::array<uint8_t, Hash::digest_size> hash_result_type;\n                constexpr static const std::size_t hash_digest_size = Hash::digest_size;\n            };\n\n            template<typename Hash, typename Store, size_t BaseTreeArity = 2>\n            struct MerkleTree {\n                Store data;\n\n                typedef typename MerkleTree_basic_policy<Hash>::hash_result_type element;\n                constexpr static const std::size_t element_size = MerkleTree_basic_policy<Hash>::hash_digest_size;\n\n                size_t leafs;\n                size_t len;\n                // Note: The former 'upstream' merkle_light project uses 'height'\n                // (with regards to the tree property) incorrectly, so we've\n                // renamed it since it's actually a 'row_count'.  For example, a\n                // tree with 2 leaf nodes and a single root node has a height of\n                // 1, but a row_count of 2.\n                //\n                // Internally, this code considers only the row_count.\n                size_t row_count;\n                // Cache with the `root` of the tree built from `data`. This allows to\n                // not access the `Store` (e.g., access to disks in `DiskStore`).\n                element root;\n\n                template<std::size_t Arity = 2>\n                element build_small_tree(size_t leafs, size_t row_count) {\n                    BOOST_ASSERT_MSG(leafs % 2 == 0, \"Leafs must be a power of two\");\n\n                    size_t level = 0;\n                    size_t width = leafs;\n                    size_t level_node_index = 0;\n                    size_t branches = Arity;\n                    size_t shift = (size_t)std::log(branches);\n\n                    size_t read_start;\n                    size_t write_start;\n                    while (width > 1) {\n                        // Same indexing logic as `build`.\n                        if (level == 0) {\n                            read_start = 0;\n                            write_start = data.len();\n                        } else {\n                            read_start = level_node_index;\n                            write_start = level_node_index + width;\n                        }\n\n                        std::array<uint8_t, width * element_size> buf;\n                        std::array<uint8_t, width * element_size / Arity> buf_result;\n                        std::pair<size_t, size_t> r =\n                            std::make_pair(read_start * element_size, (read_start + width) * element_size);\n                        data.read(r, buf.begin());\n                        BOOST_ASSERT_MSG((buf.size() / element_size) % Arity != 0, \"Invalid count data for hashing\");\n                        for (size_t i = 0; i < buf.size() - element_size * Arity; i += element_size * Arity) {\n                            root = crypto3::hash<Hash>(buf.begin() + i, buf.begin() + i + element_size * Arity);\n                            std::copy(root.begin(), root.end(), buf_result.begin() + buf_result.size());\n                        }\n                        data.write(std::make_pair(buf_result.begin(), buf_result.end()), write_start * element_size);\n                        level_node_index += width;\n                        level += 1;\n                        width >>= shift;    // width /= branches;\n                    };\n                    BOOST_ASSERT_MSG(row_count == level + 1, \"Invalid tree row_count\");\n                    // The root isn't part of the previous loop so `row_count` is\n                    // missing one level.\n\n                    return root;\n                };\n\n                template<std::size_t Arity = 2>\n                void process_layer(size_t width, size_t level, size_t read_start, size_t write_start) {\n                    size_t branches = Arity;\n\n                    // Allocate `width` indexes during operation (which is a negligible memory bloat\n                    // compared to the 32-bytes size of the nodes stored in the `Store`s) and hash each\n                    // pair of nodes to write them to the next level in concurrent threads.\n                    // Process `BUILD_CHUNK_NODES` nodes in each thread at a time to reduce contention,\n                    // optimized for big sector sizes (small ones will just have one thread doing all\n                    // the work).\n                    BOOST_ASSERT_MSG(BUILD_CHUNK_NODES % branches == 0, \"Invalid chunk size\");\n                    for (size_t chunk_index = read_start; chunk_index < read_start + width;\n                         chunk_index += BUILD_CHUNK_NODES) {\n                        size_t chunk_size = std::min(BUILD_CHUNK_NODES, read_start + width - chunk_index);\n                        std::array<uint8_t, BUILD_CHUNK_NODES * element_size> buf;\n                        std::array<uint8_t, BUILD_CHUNK_NODES * element_size / Arity> buf_result;\n                        data.read(std::make_pair(chunk_index * element_size, (chunk_index + chunk_size) * element_size),\n                                  buf.begin());\n                        BOOST_ASSERT_MSG((buf.size() / element_size) % Arity != 0, \"Invalid count data for hashing\");\n                        for (size_t i = 0; i < buf.size() - element_size * Arity; i += element_size * Arity) {\n                            root = crypto3::hash<Hash>(buf.begin() + i, buf.begin() + i + element_size * Arity);\n                            std::copy(root.begin(), root.end(), buf_result.begin() + buf_result.size());\n                        }\n                        // We write the hashed nodes to the next level in the\n                        // position that would be \"in the middle\" of the\n                        // previous pair (dividing by branches).\n                        size_t write_delta = (chunk_index - read_start) / branches;\n                        size_t nodes_size = (buf.size() / element_size / branches) * element_size;\n                        // Check that we correctly pre-allocated the space.\n                        data.write(std::make_pair<buf.begin(), buf.end()>, (write_start + write_delta) * element_size);\n                    }\n                };\n\n                // Default merkle-tree build, based on store type.\n                template<std::size_t Arity = 2>\n                element build(size_t leafs, size_t row_count, utilities::StoreConfig config) {\n                    size_t branches = Arity;\n                    BOOST_ASSERT_MSG(data.len() == leafs, \"Inconsistent data\");\n                    BOOST_ASSERT_MSG(leafs % 2 == 0, \"Leafs must be a power of two\");\n\n                    if (leafs <= SMALL_TREE_BUILD) {\n                        return build_small_tree<Arity>(leafs, row_count);\n                    }\n\n                    size_t shift = (size_t)std::log(branches);\n\n                    // Process one `level` at a time of `width` nodes. Each level has half the nodes\n                    // as the previous one; the first level, completely stored in `data`, has `leafs`\n                    // nodes. We guarantee an even number of nodes per `level`, duplicating the last\n                    // node if necessary.\n                    size_t level = 0;\n                    size_t width = leafs;\n                    size_t level_node_index = 0;\n                    while (width > 1) {\n                        // Start reading at the beginning of the current level, and writing the next\n                        // level immediate after.  `level_node_index` keeps track of the current read\n                        // starts, and width is updated accordingly at each level so that we know where\n                        // to start writing.\n                        size_t read_start;\n                        size_t write_start;\n                        if (level == 0) {\n                            read_start = 0;\n                            write_start = data.len();\n                        } else {\n                            read_start = level_node_index;\n                            write_start = level_node_index + width;\n                        }\n                        process_layer<Arity>(width, level, read_start, write_start);\n                        level_node_index += width;\n                        level += 1;\n                        width >>= shift;    // width /= branches;\n                    }\n\n                    BOOST_ASSERT_MSG(row_count == level + 1, \"Invalid tree row_count\");\n                    // The root isn't part of the previous loop so `row_count` is\n                    // missing one level.\n\n                    // Return the root\n                    return root;\n                };\n\n                /// Creates new merkle tree from an already allocated 'Store'\n                /// (used with 'Store::new_from_disk').  The specified 'size' is\n                /// the number of base data leafs in the MT.\n                MerkleTree(Store data, size_t leafs) {\n                    size_t branches = BaseTreeArity;\n                    BOOST_ASSERT_MSG(utilities::next_pow2(leafs) == leafs, \"leafs MUST be a power of 2\");\n                    BOOST_ASSERT_MSG(utilities::next_pow2(branches) == branches, \"branches MUST be a power of 2\");\n\n                    size_t tree_len = utilities::get_merkle_tree_len(leafs, branches);\n                    BOOST_ASSERT_MSG(tree_len == data.len(), \"Inconsistent tree data\");\n\n                    BOOST_ASSERT_MSG(utilities::is_merkle_tree_size_valid(leafs, branches),\n                                     \"MerkleTree size is invalid given the arity\");\n\n                    this->data = data;\n                    this->leafs = leafs;\n                    this->len = tree_len;\n                    this->row_count = utilities::get_merkle_tree_row_count(leafs, branches);\n                    this->root = data.read(data.len() - 1);\n                }\n                // Represent a fully constructed merkle tree from a provided slice.\n                MerkleTree(std::pair<uint8_t *, uint8_t *> data, size_t leafs) {\n                    size_t branches = BaseTreeArity;\n                    size_t tree_len = utilities::get_merkle_tree_len(leafs, branches);\n                    BOOST_ASSERT_MSG(tree_len == (data.first - data.second) / element_size, \"Inconsistent tree data\");\n\n                    BOOST_ASSERT_MSG(utilities::is_merkle_tree_size_valid(leafs, branches),\n                                     \"MerkleTree size is invalid given the arity\");\n\n                    this->data = Store(tree_len, &data);\n                    this->leafs = leafs;\n                    this->len = tree_len;\n                    this->row_count = utilities::get_merkle_tree_row_count(leafs, branches);\n                    this->root = this->data.read((data.first - data.second) - element_size);\n                }\n\n                // Represent a fully constructed merkle tree from a provided slice.\n                MerkleTree(std::pair<uint8_t *, uint8_t *> data, size_t leafs, utilities::StoreConfig config) {\n                    size_t branches = BaseTreeArity;\n                    size_t row_count = utilities::get_merkle_tree_row_count(leafs, branches);\n                    size_t tree_len = utilities::get_merkle_tree_len(leafs, branches);\n                    BOOST_ASSERT_MSG(tree_len == (data.first - data.second) / element_size, \"Inconsistent tree data\");\n\n                    BOOST_ASSERT_MSG(utilities::is_merkle_tree_size_valid(leafs, branches),\n                                     \"MerkleTree size is invalid given the arity\");\n                    this->data = Store(tree_len, branches, &data, config);\n                    this->leafs = leafs;\n                    this->len = tree_len;\n                    this->row_count = row_count;\n                    this->root = this->data.read((data.first - data.second) - element_size);\n                }\n\n                // Truncates the data for later access via LevelCacheStore\n                // interface.\n                bool compact() {\n                    return data.compact();\n                }\n\n                // Returns `true` if the store contains no elements.\n                bool is_empty() {\n                    return data.is_empty();\n                }\n\n                // Returns merkle leaf at index i\n                element read_at(size_t i) {\n                    element t;\n                    data.read(std::make_pair<i * element_size, (i + 1) * element_size), t.begin());\n                    return t;\n                }\n\n                std::vector<element> read_range(size_t start, size_t end) {\n                    BOOST_ASSERT_MSG(start < end, \"start must be less than end\");\n                    std::vector<element> res;\n                    res.resize(end - start);\n                    for (size_t i = start; i < end; ++i) {\n                        data.read(std::make_pair<i * element_size, (i + 1) * element_size), res[i - start].begin())\n                    }\n                    return res;\n                }\n\n                // Reads into a pre-allocated slice (for optimization purposes).\n                void read_into(size_t pos, uint8_t *buf) {\n                    data.read(std::make_pair<pos * element_size, (pos + 1) * element_size), buf);\n                }\n\n                // Build the tree given a slice of all leafs, in bytes form.\n                pub fn from_byte_slice_with_config(uint8_t* leafs : &[u8], utilitites::StoreConfig config) {\n                    BOOST_ASSERT_MSG(\n                        leafs.len() % element_size == 0, \"{} ist not a multiple of {}\", leafs.len(), E::byte_len());\n\n                    size_t leafs_count = leafs.len() / element_size;\n                    size_t branches = BaseTreeArity;\n                    BOOST_ASSERT_MSG(leafs_count > 1, \"not enough leaves\");\n                    BOOST_ASSERT_MSG(utilities::next_pow2(leafs_count) == leafs_count, \"size MUST be a power of 2\");\n                    BOOST_ASSERT_MSG(utilities::next_pow2(branches) == branches, \"branches MUST be a power of 2\");\n\n                    let size = utilities::get_merkle_tree_len(leafs_count, branches());\n                    let row_count = utilities::get_merkle_tree_row_count(leafs_count, branches);\n\n                     let root = S::build::<A, BaseTreeArity>(&mut data, leafs_count, row_count, Some(config)) ? ;\n                    this->data = Store(size, branches, leafs, config.clone());\n                    this->leafs = leafs_count;\n                    this->len = size;\n                    this->row_count = row_count;\n                }\n\n                // Build the tree given a slice of all leafs, in bytes form.\n                pub fn from_byte_slice(leafs : &[u8])->Result<Self> {\n                    BOOST_ASSERT_MSG(leafs.len() % element_size == 0, \"{} is not a multiple of {}\", leafs.len(), element_size);\n\n                    size_t leafs_count = leafs.len() / element_size;\n                    size_t branches = BaseTreeArity;\n                    BOOST_ASSERT_MSG(leafs_count > 1, \"not enough leaves\");\n                    BOOST_ASSERT_MSG(utilities::next_pow2(leafs_count) == leafs_count, \"size MUST be a power of 2\");\n                    BOOST_ASSERT_MSG(utilities::next_pow2(branches) == branches, \"branches MUST be a power of 2\");\n\n                    size_t row_count = utilities::get_merkle_tree_row_count(leafs_count, branches);\n                    this->root = S::build::<A, BaseTreeArity>(&mut data, leafs_count, row_count, None) ? ;\n                    this->data = Store(size, leafs);\n                    this->leafs = leafs_count;\n                    this->len = utilities::get_merkle_tree_len(leafs_count, branches);\n                    this->row_count = row_count;\n                }\n\n                // Attempts to create a new merkle tree using hashable objects yielded by\n                // the provided iterator. This method returns the first error yielded by\n                // the iterator, if the iterator yielded an error.\n                // try_from_iter\n                MerkleTree(std::pair<uint8_t *, uint8_t *> data) {\n                    size_t leafs = (data.second - data.first) / element_size;\n                    size_t branches = BaseTreeArity;\n                    BOOST_ASSERT_MSG(leafs > 1, \"not enough leaves\");\n                    BOOST_ASSERT_MSG(next_pow2(leafs) == leafs, \"size MUST be a power of 2\");\n                    BOOST_ASSERT_MSG(next_pow2(branches) == branches, \"branches MUST be a power of 2\");\n\n                    size_t size = get_merkle_tree_len(leafs, branches);\n                    size_t row_count = get_merkle_tree_row_count(leafs, branches);\n\n                    self->root = self->build<BaseTreeArity>(data, leafs, row_count, None);\n                    self->data = Data::BaseTree(data);\n                    self->leafs = leafs;\n                    self->len = size;\n                    self->row_count = row_count;\n                }\n            };\n\n            template<typename Hash, typename Store, size_t BaseTreeArity = 2, size_t SubTreeArity = 2>\n            struct SubMerkleTree {\n                std::vector<MerkleTree<Hash, Store, BaseTreeArity>> data;\n\n                typedef typename MerkleTree_basic_policy<Hash>::hash_result_type element;\n                constexpr static const std::size_t element_size = MerkleTree_basic_policy<Hash>::hash_digest_size;\n\n                size_t leafs;\n                size_t len;\n                // Note: The former 'upstream' merkle_light project uses 'height'\n                // (with regards to the tree property) incorrectly, so we've\n                // renamed it since it's actually a 'row_count'.  For example, a\n                // tree with 2 leaf nodes and a single root node has a height of\n                // 1, but a row_count of 2.\n                //\n                // Internally, this code considers only the row_count.\n                size_t row_count;\n                // Cache with the `root` of the tree built from `data`. This allows to\n                // not access the `Store` (e.g., access to disks in `DiskStore`).\n                element root;\n\n                // Creates new compound merkle tree from a vector of merkle\n                // trees.  The ordering of the trees is significant, as trees are\n                // leaf indexed / addressable in the same sequence that they are\n                // provided here.\n                SubMerkleTree(std::vector<MerkleTree<Hash, Store, BaseTreeArity>> trees) {\n                    BOOST_ASSERT_MSG(SubTreeArity > 0,\n                                     \"Cannot use from_trees if not constructing a structure with sub-trees\");\n                    BOOST_ASSERT_MSG(trees.len() == SubTreeArity,\n                                     \"Length of trees MUST equal the number of sub tree layer nodes\");\n                    // Total number of leafs in the compound tree is the combined leafs total of all subtrees.\n                    size_t leafs = 0;\n                    // Total length of the compound tree is the combined length of all subtrees plus the root.\n                    size_t len = 0;\n                    // Total row_count of the compound tree is the row_count of any of the sub-trees to top-layer plus\n                    // root.\n                    size_t row_count = trees[0].row_count() + 1;\n                    for (size_t i = 0; i < trees.size(); ++i) {\n                        BOOST_ASSERT_MSG(trees[i].row_count() == trees[0].row_count(),\n                                         \"All passed in trees must have the same row_count\");\n                        BOOST_ASSERT_MSG(trees[i].len() == trees[0].len(),\n                                         \"All passed in trees must have the same length\");\n                        len += trees[i].len;\n                        leafs += trees[i].row_count;\n                    }\n\n                    // Calculate the compound root by hashing the top layer roots together.\n                    let roots : Vec<E> = trees.iter().map(| x | x.root()).collect();\n                    element root = A::default().multi_node(&roots, 1);\n\n                    this->data = Data::SubTree(trees);\n                    this->leafs = leafs;\n                    this->len = len;\n                    this->row_count = row_count;\n                    this->root = root;\n                }\n            };\n\n            template<typename Hash,\n                     typename Store,\n                     size_t BaseTreeArity = 2,\n                     size_t SubTreeArity = 2,\n                     size_t TopTreeArity = 2>\n            struct TopMerkleTree {\n                std::vector<SubMerkleTree<Hash, Store, BaseTreeArity, SubTreeArity>> data;\n\n                typedef typename MerkleTree_basic_policy<Hash>::hash_result_type element;\n                constexpr static const std::size_t element_size = MerkleTree_basic_policy<Hash>::hash_digest_size;\n\n                size_t leafs;\n                size_t len;\n                // Note: The former 'upstream' merkle_light project uses 'height'\n                // (with regards to the tree property) incorrectly, so we've\n                // renamed it since it's actually a 'row_count'.  For example, a\n                // tree with 2 leaf nodes and a single root node has a height of\n                // 1, but a row_count of 2.\n                //\n                // Internally, this code considers only the row_count.\n                size_t row_count;\n                // Cache with the `root` of the tree built from `data`. This allows to\n                // not access the `Store` (e.g., access to disks in `DiskStore`).\n                element root;\n\n                // Creates new top layer merkle tree from a vector of merkle\n                // trees with sub-trees.  The ordering of the trees is\n                // significant, as trees are leaf indexed / addressable in the\n                // same sequence that they are provided here.\n                TopMerkleTree(std::vector<SubMerkleTree<Hash, Store, BaseTreeArity, SubTreeArity>> trees) {\n                    BOOST_ASSERT_MSG(TopTreeArity > 0,\n                                     \"Cannot use from_sub_trees if not constructing a structure with sub-trees\");\n                    for (size_t i = 0; i < trees.size(); ++i) {\n                        BOOST_ASSERT_MSG(trees[i].row_count() == trees[0].row_count(),\n                                         \"All passed in trees must have the same row_count\");\n                        BOOST_ASSERT_MSG(trees[i].len() == trees[0].len(),\n                                         \"All passed in trees must have the same length\");\n                    }\n\n                    size_t top_layer_nodes = TopTreeArity;\n                    BOOST_ASSERT_MSG(trees.len() == top_layer_nodes,\n                                     \"Length of trees MUST equal the number of top layer nodes\");\n\n                    // If we are building a compound tree with no sub-trees,\n                    // all properties revert to the single tree properties.\n                    let(leafs, len, row_count, root) = {\n                        // Total number of leafs in the compound tree is the combined leafs total of all subtrees.\n                        size_t leafs = trees.iter().fold(0, | leafs, mt | leafs + mt.leafs());\n                    // Total length of the compound tree is the combined length of all subtrees plus the root.\n                    size_t len = trees.iter().fold(0, | len, mt | len + mt.len()) + 1;\n                    // Total row_count of the compound tree is the row_count of any of the sub-trees to top-layer plus\n                    // root.\n                    size_t row_count = trees[0].row_count() + 1;\n                    // Calculate the compound root by hashing the top layer roots together.\n                    let roots : Vec<E> = trees.iter().map(| x | x.root()).collect();\n                    element root = A::default().multi_node(&roots, 1);\n\n                    (leafs, len, row_count, root)\n                };\n                this->data = Data::TopTree(trees);\n                this->leafs = leafs;\n                this->len = len;\n                this->row_count = row_count;\n                this->root = root;\n            };\n\n            // Creates new top layer merkle tree from a vector of merkle\n            // trees by first constructing the appropriate sub-trees.  The\n            // ordering of the trees is significant, as trees are leaf\n            // indexed / addressable in the same sequence that they are\n            // provided here.\n            TopMerkleTree(std::vector<MerkleTree<Hash, Store, BaseTreeArity>> trees) {\n                BOOST_ASSERT_MSG(TopTreeArity > 0,\n                                 \"Cannot use from_sub_trees if not constructing a structure with sub-trees\");\n                for (size_t i = 0; i < trees.size(); ++i) {\n                    BOOST_ASSERT_MSG(trees[i].row_count() == trees[0].row_count(),\n                                     \"All passed in trees must have the same row_count\");\n                    BOOST_ASSERT_MSG(trees[i].len() == trees[0].len(), \"All passed in trees must have the same length\");\n                }\n\n                size_t sub_tree_count = TopTreeArity;\n                size_t top_layer_nodes = sub_tree_count * SubTreeArity;\n                BOOST_ASSERT_MSG(trees.len() == top_layer_nodes,\n                                 \"Length of trees MUST equal the number of top layer nodes\");\n\n                // Group the trees appropriately into sub-tree ready vectors.\n                let mut grouped_trees = Vec::with_capacity(sub_tree_count);\n                    for\n                        _ in(0..sub_tree_count).step_by(trees.len() / sub_tree_count) {\n                            grouped_trees.push(trees.split_off(trees.len() / sub_tree_count));\n                        }\n                    grouped_trees.insert(0, trees);\n\n                    let mut sub_trees : Vec<MerkleTree<E, A, S, BaseTreeArity, SubTreeArity>> =\n                                            Vec::with_capacity(sub_tree_count);\n                    for\n                        group in grouped_trees {\n                        sub_trees.push(MerkleTree::from_trees(group)?);\n                        }\n\n                    let(leafs, len, row_count, root) = {\n                        // Total number of leafs in the compound tree is the combined leafs total of all subtrees.\n                            let leafs = sub_trees.iter().fold(0, | leafs, mt | leafs + mt.leafs());\n                        // Total length of the compound tree is the combined length of all subtrees plus the root.\n                        let len = sub_trees.iter().fold(0, | len, mt | len + mt.len()) + 1;\n                        // Total row_count of the compound tree is the row_count of any of the sub-trees to top-layer plus\n                        // root.\n                        let row_count = sub_trees[0].row_count() + 1;\n                        // Calculate the compound root by hashing the top layer roots together.\n                        let roots : Vec<E> = sub_trees.iter().map(| x | x.root()).collect();\n                        let root = A::default().multi_node(&roots, 1);\n\n                        (leafs, len, row_count, root)\n                    }\n                this->data = Data::TopTree(sub_trees);\n                this->leafs = leafs;\n                this->len = len;\n                this->row_count = row_count;\n                this->root = root;\n            };\n        };\n    }    // namespace merkletree\n}    // namespace filecoin\n}    // namespace nil\n\n#endif    // FILECOIN_DISK_HPP\n", "meta": {"hexsha": "9bc4c7ab33651ac25650ee73e8db5ee65c4ad8ca", "size": 32382, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/merkle/merkle.hpp", "max_stars_repo_name": "NilFoundation/crypto3-fil-proofs", "max_stars_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/merkle/merkle.hpp", "max_issues_repo_name": "NilFoundation/crypto3-fil-proofs", "max_issues_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-06T13:07:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T12:38:09.000Z", "max_forks_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/merkle/merkle.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": 55.6391752577, "max_line_length": 127, "alphanum_fraction": 0.5190846767, "num_tokens": 6677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.02479816199737538, "lm_q1q2_score": 0.010571991914971726}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <iostream>\n#include <boost/algorithm/clamp.hpp>\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\nusing namespace tensorflow;\nusing namespace std;\nusing namespace boost::algorithm;\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n/*\n * bottom_data:输入网络，rois的绝对坐标以bottom_data的空间大小为限\n * bottom_rois应该是2维的shape为[N,5],最后一维依次为[batch_index,w_min,h_min,w_max,h_max] 绝对坐标\n * 包含边界(min及max)\n * 输出output:[N,pool_height,pool_width,channels]\n */\n\nREGISTER_OP(\"RoiPooling\")\n    .Attr(\"T: {float, double}\")\n    .Attr(\"pool_height: int\")\n    .Attr(\"pool_width: int\")\n    .Attr(\"spatial_scale: float\")\n    .Input(\"bottom_data: T\")\n    .Input(\"bottom_rois: T\")\n    .Output(\"top_data: T\")\n    .Output(\"argmax: int32\")\n    .SetShapeFn([](shape_inference::InferenceContext* c){\n            auto dims_data     = c->input(0);\n            auto channels      = c->Value(c->Dim(dims_data,3));\n            auto dims_rois     = c->input(1);\n            auto num_rois      = c->Value(c->Dim(dims_rois,0));\n            int  pooled_height = 0;\n            int  pooled_width  = 0;\n\n            c->GetAttr(\"pool_width\",&pooled_width);\n            c->GetAttr(\"pool_height\",&pooled_height);\n\n            auto output_shape = c->MakeShape({num_rois, pooled_height, pooled_width, channels});\n\n            c->set_output(0,output_shape);\n\n            return Status::OK();\n            });\n\n\nREGISTER_OP(\"RoiPoolingGrad\")\n    .Attr(\"T: {float, double}\")\n    .Attr(\"pool_height: int\")\n    .Attr(\"pool_width: int\")\n    .Attr(\"spatial_scale: float\")\n    .Input(\"bottom_data: T\")\n    .Input(\"bottom_rois: T\")\n    .Input(\"argmax: int32\")\n    .Input(\"grad: T\")\n    .Output(\"output: T\");\n\ntemplate <typename Device, typename T>\nclass RoiPoolingOp : public OpKernel {\n public:\n  explicit RoiPoolingOp(OpKernelConstruction* context) : OpKernel(context) {\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"pool_height\", &pool_height_));\n    OP_REQUIRES(context, pool_height_ >= 0,\n                errors::InvalidArgument(\"Need pool_height >= 0, got \",\n                                        pool_height_));\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"pool_width\", &pool_width_));\n    OP_REQUIRES(context, pool_width_ >= 0,\n                errors::InvalidArgument(\"Need pool_width >= 0, got \",\n                                        pool_width_));\n\t/*\n\t * 对bottom_rois指定的区域进行缩放\n\t */\n    OP_REQUIRES_OK(context,\n                   context->GetAttr(\"spatial_scale\", &spatial_scale_));\n  }\n\n  void Compute(OpKernelContext* context) override\n  {\n    const Tensor &bottom_data      = context->input(0);\n    const Tensor &bottom_rois      = context->input(1);\n    auto          bottom_data_flat = bottom_data.flat<T>();\n    auto          bottom_rois_flat = bottom_rois.flat<T>();\n\n    OP_REQUIRES(context, bottom_data.dims() == 4,\n                errors::InvalidArgument(\"data must be 4-dimensional\"));\n\n    OP_REQUIRES(context, bottom_rois.dims() == 2,\n                errors::InvalidArgument(\"rois must be 2-dimensional\"));\n\n    int num_rois = bottom_rois.dim_size(0);\n    int batch_size = bottom_data.dim_size(0);\n    int data_height = bottom_data.dim_size(1);\n    int data_width = bottom_data.dim_size(2);\n    int num_channels = bottom_data.dim_size(3);\n\n    int dims[4];\n\n    dims[0] = num_rois;\n    dims[1] = pool_height_;\n    dims[2] = pool_width_;\n    dims[3] = num_channels;\n\n    TensorShape output_shape;\n    TensorShapeUtils::MakeShape(dims, 4, &output_shape);\n\n    Tensor* output_tensor = NULL;\n\n    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_tensor));\n\n    auto output = output_tensor->template flat<T>();\n\n    Tensor* argmax_tensor = NULL;\n    OP_REQUIRES_OK(context, context->allocate_output(1, output_shape, &argmax_tensor));\n    auto argmax = argmax_tensor->template flat<int>();\n\n    int   pool_height   = pool_height_;\n    int   pool_width    = pool_width_;\n    float spatial_scale = spatial_scale_;\n\n\tif((num_rois<=0) || (batch_size<=0)) {\n\t\twhile(1)\n\t\t\tprintf(\"in box nr :%d,data nr%d\\n\",num_rois,batch_size);\n\t}\n\n    auto shard = [pool_height, pool_width, spatial_scale,\n                  num_rois, batch_size, data_height, data_width, num_channels,\n                  &bottom_data_flat, &bottom_rois_flat, &output, &argmax]\n                  (int64 start, int64 limit) {\n      for (int64 b = start; b < limit; ++b)\n      {\n        // (n, ph, pw, c) is an element in the pooled output\n        int n = b;\n        int c = n % num_channels;\n        n /= num_channels;\n        int pw = n % pool_width;\n        n /= pool_width;\n        int ph = n % pool_height;\n        n /= pool_height;\n\n        const float* bottom_rois = bottom_rois_flat.data() + n * 5;\n\t\t/*\n\t\t * 确定roi区域\n\t\t */\n        int roi_batch_ind = bottom_rois[0];\n        int roi_start_w   = round(bottom_rois[1] *spatial_scale);\n        int roi_start_h   = round(bottom_rois[2] *spatial_scale);\n        int roi_end_w     = round(bottom_rois[3] *spatial_scale);\n        int roi_end_h     = round(bottom_rois[4] *spatial_scale);\n\n        int     roi_width  = std::max(roi_end_w - roi_start_w + 1, 1);\n        int     roi_height = std::max(roi_end_h - roi_start_h + 1, 1);\n        const T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pool_height);\n        const T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pool_width);\n\n        int hstart  =  static_cast<int>(floor(ph * bin_size_h));\n        int wstart  =  static_cast<int>(floor(pw * bin_size_w));\n        int hend    =  static_cast<int>(ceil((ph + 1) * bin_size_h));\n        int wend    =  static_cast<int>(ceil((pw + 1) * bin_size_w));\n\n        hstart  =  clamp(hstart + roi_start_h, 0, data_height);\n        hend    =  clamp(hend + roi_start_h, 0, data_height);\n        wstart  =  clamp(wstart + roi_start_w, 0, data_width);\n        wend    =  clamp(wend + roi_start_w, 0, data_width);\n        bool is_empty = (hend <= hstart) || (wend <= wstart);\n\n        float maxval = is_empty ? 0 : -FLT_MAX;\n        int maxidx = -1;\n        const float* bottom_data = bottom_data_flat.data() + roi_batch_ind * num_channels * data_height * data_width;\n\t\t//printf(\"process:%d, total=%d\\n\",b,output.size());\n\t\t/*\n\t\tif((hend>hstart+1)||(wend>wstart+1))\n\t\t\tprintf(\"hstart=%d,wstart=%d,hend=%d,wend=%d\\n\",hstart,wstart,hend,wend);\n\t\t\t*/\n        for (int h = hstart; h < hend; ++h) {\n          for (int w = wstart; w < wend; ++w) {\n            int bottom_index = (h * data_width + w) * num_channels + c;\n            if (bottom_data[bottom_index] > maxval) {\n              maxval = bottom_data[bottom_index];\n              maxidx = bottom_index;\n            }\n          }\n        }\n        output(b) = maxval;\n        argmax(b) = maxidx;\n      }\n    };\n\n    const DeviceBase::CpuWorkerThreads& worker_threads =\n        *(context->device()->tensorflow_cpu_worker_threads());\n    const int64 shard_cost =\n        num_rois * num_channels * pool_height * pool_width * spatial_scale;\n    Shard(worker_threads.num_threads, worker_threads.workers,\n          output.size(), shard_cost, shard);\n  }\n private:\n  int pool_height_;\n  int pool_width_;\n  float spatial_scale_;\n};\n//梯度\ntemplate <class Device, class T>\nclass RoiPoolingGradOp : public OpKernel {\n\tpublic:\n\t\texplicit RoiPoolingGradOp(OpKernelConstruction* context) : OpKernel(context) {\n\n\t\t\tOP_REQUIRES_OK(context,\n\t\t\t\t\tcontext->GetAttr(\"pool_height\", &pool_height_));\n\t\t\tOP_REQUIRES(context, pool_height_ >= 0,\n\t\t\t\t\terrors::InvalidArgument(\"Need pool_height >= 0, got \",\n\t\t\t\t\t\tpool_height_));\n\t\t\tOP_REQUIRES_OK(context,\n\t\t\t\t\tcontext->GetAttr(\"pool_width\", &pool_width_));\n\t\t\tOP_REQUIRES(context, pool_width_ >= 0,\n\t\t\t\t\terrors::InvalidArgument(\"Need pool_width >= 0, got \",\n\t\t\t\t\t\tpool_width_));\n\t\t\tOP_REQUIRES_OK(context,\n\t\t\t\t\tcontext->GetAttr(\"spatial_scale\", &spatial_scale_));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n\t\t{\n\t\t\tconst Tensor &bottom_data  = context->input(0);\n\t\t\tconst Tensor &bottom_rois  = context->input(1);\n\t\t\tconst Tensor &argmax_data  = context->input(2);\n\t\t\tconst Tensor &out_backprop = context->input(3);\n\n\t\t\tauto bottom_data_flat  = bottom_data.flat<T>();\n\t\t\tauto bottom_rois_flat  = bottom_rois.flat<T>();\n\t\t\tauto argmax_data_flat  = argmax_data.flat<int32>();\n\t\t\tauto out_backprop_flat = out_backprop.flat<T>();\n\n\t\t\tOP_REQUIRES(context, bottom_data.dims() == 4,\n\t\t\t\t\terrors::InvalidArgument(\"data must be 4-dimensional\"));\n\n\t\t\tOP_REQUIRES(context, bottom_rois.dims() == 2,\n\t\t\t\t\terrors::InvalidArgument(\"rois must be 2-dimensional\"));\n\n\t\t\tOP_REQUIRES(context, argmax_data.dims() == 4,\n\t\t\t\t\terrors::InvalidArgument(\"argmax_data must be 4-dimensional\"));\n\n\t\t\tOP_REQUIRES(context, out_backprop.dims() == 4,\n\t\t\t\t\terrors::InvalidArgument(\"out_backprop must be 4-dimensional\"));\n\n\t\t\tint num_rois = bottom_rois.dim_size(0);\n\t\t\tint batch_size = bottom_data.dim_size(0);\n\t\t\tint data_height = bottom_data.dim_size(1);\n\t\t\tint data_width = bottom_data.dim_size(2);\n\t\t\tint num_channels = bottom_data.dim_size(3);\n\n\t\t\tTensorShape output_shape = bottom_data.shape();\n\n\t\t\tTensor* output_tensor = NULL;\n\t\t\tOP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_tensor));\n\n\t\t\tauto  output        = output_tensor->template flat<T>();\n\t\t\tint   pool_height   = pool_height_;\n\t\t\tint   pool_width    = pool_width_;\n\t\t\tfloat spatial_scale = spatial_scale_;\n\n\t\t\tauto shard = [pool_height, pool_width, spatial_scale,\n\t\t\t\t num_rois, batch_size, data_height, data_width, num_channels,\n\t\t\t\t &bottom_data_flat, &bottom_rois_flat, &argmax_data_flat,\n\t\t\t\t &out_backprop_flat, &output](int64 start, int64 limit) {\n\t\t\t\t\t for (int64 b = start; b < limit; ++b)\n\t\t\t\t\t {\n\t\t\t\t\t\t // (n, h, w, c) coords in bottom data\n\t\t\t\t\t\t int n = b;\n\t\t\t\t\t\t int c = n % num_channels;\n\t\t\t\t\t\t n /= num_channels;\n\t\t\t\t\t\t int w = n % data_width;\n\t\t\t\t\t\t n /= data_width;\n\t\t\t\t\t\t int h = n % data_height;\n\t\t\t\t\t\t n /= data_height;\n\n\t\t\t\t\t\t float gradient = 0.0;\n\t\t\t\t\t\t //Accumulate gradient over all ROIs that pooled this element\n\t\t\t\t\t\t for (int roi_n = 0; roi_n < num_rois; ++roi_n)\n\t\t\t\t\t\t {\n\t\t\t\t\t\t\t const float *offset_bottom_rois = bottom_rois_flat.data() + roi_n *5;\n\t\t\t\t\t\t\t int          roi_batch_ind      = offset_bottom_rois[0];\n\t\t\t\t\t\t\t if (n != roi_batch_ind) {\n\t\t\t\t\t\t\t\t continue;\n\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t int roi_start_w = round(offset_bottom_rois[1] *spatial_scale);\n\t\t\t\t\t\t\t int roi_start_h = round(offset_bottom_rois[2] *spatial_scale);\n\t\t\t\t\t\t\t int roi_end_w   = round(offset_bottom_rois[3] *spatial_scale);\n\t\t\t\t\t\t\t int roi_end_h   = round(offset_bottom_rois[4] *spatial_scale);\n\n\n\t\t\t\t\t\t\t const bool in_roi = (w >= roi_start_w && w <= roi_end_w &&\n\t\t\t\t\t\t\t\t\t h >= roi_start_h && h <= roi_end_h);\n\t\t\t\t\t\t\t if (!in_roi) {\n\t\t\t\t\t\t\t\t continue;\n\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t int          offset             = roi_n *pool_height *pool_width *num_channels;\n\t\t\t\t\t\t\t const float *offset_top_diff    = out_backprop_flat.data() + offset;\n\t\t\t\t\t\t\t const int   *offset_argmax_data = argmax_data_flat.data() + offset;\n\n\t\t\t\t\t\t\t int roi_width  = std::max(roi_end_w - roi_start_w + 1, 1);\n\t\t\t\t\t\t\t int roi_height = std::max(roi_end_h - roi_start_h + 1, 1);\n\n\t\t\t\t\t\t\t const T bin_size_h = static_cast<T>(roi_height)\n\t\t\t\t\t\t\t\t / static_cast<T>(pool_height);\n\t\t\t\t\t\t\t const T bin_size_w = static_cast<T>(roi_width)\n\t\t\t\t\t\t\t\t / static_cast<T>(pool_width);\n\n\t\t\t\t\t\t\t int phstart  =  floor(static_cast<int>(h - roi_start_h) / bin_size_h);\n\t\t\t\t\t\t\t int phend    =  ceil(static_cast<int>(h - roi_start_h + 1) / bin_size_h);\n\t\t\t\t\t\t\t int pwstart  =  floor(static_cast<int>(w - roi_start_w) / bin_size_w);\n\t\t\t\t\t\t\t int pwend    =  ceil(static_cast<int>(w - roi_start_w + 1) / bin_size_w);\n\n\t\t\t\t\t\t\t phstart  =  clamp(phstart, 0, pool_height);\n\t\t\t\t\t\t\t phend    =  clamp(phend, 0, pool_height);\n\t\t\t\t\t\t\t pwstart  =  clamp(pwstart, 0, pool_width);\n\t\t\t\t\t\t\t pwend    =  clamp(pwend, 0, pool_width);\n\n\t\t\t\t\t\t\t for (int ph = phstart; ph < phend; ++ph) {\n\t\t\t\t\t\t\t\t for (int pw = pwstart; pw < pwend; ++pw) {\n\t\t\t\t\t\t\t\t\t if (offset_argmax_data[(ph * pool_width + pw) * num_channels + c] == (h * data_width + w) * num_channels + c)\n\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t gradient += offset_top_diff[(ph * pool_width + pw) * num_channels + c];\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\t output(b) = gradient;\n\t\t\t\t\t }\n\t\t\t\t };\n\n\t\t\tconst DeviceBase::CpuWorkerThreads& worker_threads =\n\t\t\t\t*(context->device()->tensorflow_cpu_worker_threads());\n\t\t\tconst int64 shard_cost =\n\t\t\t\tnum_rois * num_channels * pool_height * pool_width * spatial_scale;\n\t\t\tShard(worker_threads.num_threads, worker_threads.workers,\n\t\t\t\t\toutput.size(), shard_cost, shard);\n\t\t}\n\tprivate:\n\t\tint   pool_height_;\n\t\tint   pool_width_;\n\t\tfloat spatial_scale_;\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"RoiPooling\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), RoiPoolingOp<CPUDevice, float>);\nREGISTER_KERNEL_BUILDER(Name(\"RoiPoolingGrad\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), RoiPoolingGradOp<CPUDevice, float>);\n", "meta": {"hexsha": "69175eef600a20fa49f599346401ba9b3a30900b", "size": 13097, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tfop/roipooling.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/roipooling.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/roipooling.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.1019830028, "max_line_length": 130, "alphanum_fraction": 0.633122089, "num_tokens": 3544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.025178842614969447, "lm_q1q2_score": 0.010542303584040963}}
{"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 \"common.h\"\n\n#include <boost/lexical_cast.hpp>\n\n#include <vector>\n\nusing namespace dangdal;\n\nstruct ScaledBand {\n\tScaledBand() :\n\t\toversample(0), lo_w(0), lo_h(0), hi_w(0), hi_h(0),\n\t\tdelta_x(0), delta_y(0), band(NULL), line_buf_idx(0)\n\t{ }\n\n\tint oversample;\n\tsize_t lo_w, lo_h;\n\tsize_t hi_w, hi_h;\n\tint delta_x, delta_y;\n\tstd::vector<std::vector<double> > kernel_x;\n\tstd::vector<std::vector<double> > kernel_y;\n\tGDALRasterBandH band;\n\tstd::vector<std::vector<double> > lines_buf;\n\tint line_buf_idx;\n};\n\nvoid copyGeoCode(GDALDatasetH dst_ds, GDALDatasetH src_ds);\nScaledBand getScaledBand(GDALDatasetH lores_ds, int band_id, GDALDatasetH hires_ds);\nvoid readLineScaled(ScaledBand &sb, int row, double *hires_buf);\ndouble avoidNDV(double in, double ndv, GDALDataType out_dt);\n\nvoid usage(const std::string &cmdname) {\n\tprintf(\"Usage:\\n %s\\n\", cmdname.c_str());\n\tprintf(\n\"      -rgb <src_rgb.tif> [ -rgb <src.tif> ... ]\\n\"\n\"      [ -lum <lum.tif> <weight> ... ] -pan <pan.tif>\\n\"\n\"      [ -ndv <nodataval> ] -o <out-rgb.tif>\\n\"\n\"\\nWhere:\\n\"\n\"    rgb.tif    Source bands that are to be enhanced\\n\"\n\"    lum.tif    Bands used to simulate lo-res pan band\\n\"\n\"    pan.tif    Hi-res panchromatic band\\n\"\n\"\\nExamples, basic usage:\\n\"\n\"    gdal_landsat_pansharp -rgb quickbird_rgb.tif -pan quickbird_pan.tif -o out.tif\\n\"\n\"\\nExamples, using simulated pan band (gives better results):\\n\"\n\"(coefficients from http://www.dpi.inpe.br/~leila/publications/boggione2003spb.pdf)\\n\"\n\"    gdal_landsat_pansharp -rgb lansat321.tif -lum landsat234.tif 0.25 0.23 0.52 \\\\\\n\"\n\"      -pan landsat8.tif -ndv 0 -o out.tif\\n\\n\"\n\"    gdal_landsat_pansharp -rgb landsat3.tif -rgb landsat2.tif -rgb landsat1.tif \\\\\\n\"\n\"      -lum landsat2.tif 0.25 -lum landsat3.tif 0.23 -lum landsat4.tif 0.52 \\\\\\n\"\n\"      -pan landsat8.tif -ndv 0 -o out.tif\\n\\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::vector<GDALDatasetH> rgb_ds;\n\tstd::vector<GDALDatasetH> lum_ds;\n\tstd::vector<double> lum_weights;\n\n\tstd::string pan_fn;\n\tstd::string dst_fn;\n\tstd::string output_format;\n\tdouble ndv = 0;\n\tbool use_ndv = 0;\n\n\tGDALAllRegister();\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 duplicate values\n\t\tif(arg[0] == '-') {\n\t\t\ttry {\n\t\t\t\tif(arg == \"-ndv\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tndv = boost::lexical_cast<double>(arg_list[argp++].c_str());\n\t\t\t\t\tuse_ndv = true;\n\t\t\t\t} \n\t\t\t\telse if(arg == \"-of\" ) { if(argp == arg_list.size()) usage(cmdname); output_format = arg_list[argp++]; }\n\t\t\t\telse if(arg == \"-o\"  ) { if(argp == arg_list.size()) usage(cmdname); dst_fn = arg_list[argp++]; }\n\t\t\t\telse if(arg == \"-pan\") { if(argp == arg_list.size()) usage(cmdname); pan_fn = arg_list[argp++]; }\n\t\t\t\telse if(arg == \"-rgb\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tstd::string fn = arg_list[argp++];\n\t\t\t\t\tGDALDatasetH ds = GDALOpen(fn.c_str(), GA_ReadOnly);\n\t\t\t\t\tif(!ds) fatal_error(\"open failed\");\n\t\t\t\t\trgb_ds.push_back(ds); \n\t\t\t\t}\n\t\t\t\telse if(arg == \"-lum\") {\n\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\tstd::string fn = arg_list[argp++];\n\t\t\t\t\tGDALDatasetH ds = GDALOpen(fn.c_str(), GA_ReadOnly);\n\t\t\t\t\tif(!ds) fatal_error(\"open failed\");\n\t\t\t\t\tlum_ds.push_back(ds); \n\t\t\t\t\tint nb = GDALGetRasterCount(ds);\n\t\t\t\t\twhile(nb) {\n\t\t\t\t\t\tif(argp == arg_list.size()) usage(cmdname);\n\t\t\t\t\t\tdouble w = boost::lexical_cast<double>(arg_list[argp++]);\n\t\t\t\t\t\tlum_weights.push_back(w);\n\t\t\t\t\t\tnb--;\n\t\t\t\t\t}\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}\n\t\t} else {\n\t\t\tusage(cmdname);\n\t\t}\n\t}\n\n\tif(pan_fn.empty() || dst_fn.empty()) usage(cmdname);\n\n\tif(output_format.empty()) output_format = \"GTiff\";\n\n\t//////// open source ////////\n\n\tGDALDatasetH pan_ds = GDALOpen(pan_fn.c_str(), GA_ReadOnly);\n\tif(!pan_ds) fatal_error(\"open failed\");\n\n\tsize_t w = GDALGetRasterXSize(pan_ds);\n\tsize_t h = GDALGetRasterYSize(pan_ds);\n\tif(!w || !h) fatal_error(\"missing width/height\");\n\n\tif(GDALGetRasterCount(pan_ds) != 1) fatal_error(\"Pan input must be only one band\");\n\n\tGDALRasterBandH pan_band = GDALGetRasterBand(pan_ds, 1);\n\n\t// this will be updated via GDALDataTypeUnion as RGB bands are opened\n\tGDALDataType out_dt = GDALGetRasterDataType(pan_band);\n\n\t/////\n\n\tstd::vector<ScaledBand> rgb_bands;\n\tfor(size_t ds_idx=0; ds_idx<rgb_ds.size(); ds_idx++) {\n\t\tint nb = GDALGetRasterCount(rgb_ds[ds_idx]);\n\t\tfor(int i=0; i<nb; i++) {\n\t\t\trgb_bands.push_back(getScaledBand(rgb_ds[ds_idx], i+1, pan_ds));\n\t\t\tout_dt = GDALDataTypeUnion(out_dt, GDALGetRasterDataType(\n\t\t\t\tGDALGetRasterBand(rgb_ds[ds_idx], i+1)));\n\t\t}\n\t}\n\tsize_t rgb_band_count = rgb_bands.size();\n\tif(!rgb_band_count) usage(cmdname);\n\n\tstd::vector<ScaledBand> lum_bands;\n\tif(!lum_ds.empty()) {\n\t\tfor(size_t ds_idx=0; ds_idx<lum_ds.size(); ds_idx++) {\n\t\t\tint nb = GDALGetRasterCount(lum_ds[ds_idx]);\n\t\t\tfor(int i=0; i<nb; i++) {\n\t\t\t\tlum_bands.push_back(getScaledBand(lum_ds[ds_idx], i+1, pan_ds));\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlum_bands = rgb_bands;\n\t\tlum_weights.assign(rgb_band_count, 1);\n\t}\n\tsize_t lum_band_count = lum_bands.size();\n\n\tdouble lum_weight_total = 0;\n\tfor(size_t i=0; i<lum_band_count; i++) {\n\t\tlum_weight_total += lum_weights[i];\n\t}\n\t//printf(\"lum weights:\");\n\tfor(size_t i=0; i<lum_band_count; i++) {\n\t\tlum_weights[i] /= lum_weight_total;\n\t\t//printf(\" %lf\", lum_weights[i]);\n\t}\n\t//printf(\"\\n\");\n\n\t//////// open output ////////\n\n\tprintf(\"Output size is %zd x %zd x %zd\\n\", w, h, rgb_band_count);\n\tprintf(\"Output datatype is %s\\n\", GDALGetDataTypeName(out_dt));\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\tGDALDatasetH dst_ds = GDALCreate(dst_driver, dst_fn.c_str(), w, h, rgb_band_count, out_dt, NULL);\n\tif(!dst_ds) fatal_error(\"could not create output\");\n\tcopyGeoCode(dst_ds, pan_ds);\n\n\tstd::vector<GDALRasterBandH> dst_bands;\n\tfor(size_t i=0; i<rgb_band_count; i++) {\n\t\tdst_bands.push_back(GDALGetRasterBand(dst_ds, i+1));\n\t\tif(use_ndv) {\n\t\t\tGDALSetRasterNoDataValue(dst_bands[i], ndv);\n\t\t}\n\t}\n\n\t//////// process data ////////\n\n\tstd::vector<std::vector<double> > lum_buf(lum_band_count);\n\tfor(size_t band_idx=0; band_idx<lum_band_count; band_idx++) {\n\t\tlum_buf[band_idx].resize(w);\n\t}\n\tstd::vector<double> pan_buf(w);\n\tstd::vector<double> rgb_buf(w);\n\tstd::vector<double> out_buf(w);\n\tstd::vector<double> scale_buf(w);\n\n\tfor(size_t row=0; row<h; row++) {\n\t\tGDALTermProgress((double)row/h, NULL, NULL);\n\n\t\tGDALRasterIO(pan_band, GF_Read, 0, row, w, 1, &pan_buf[0], w, 1, GDT_Float64, 0, 0);\n\t\tfor(size_t band_idx=0; band_idx<lum_band_count; band_idx++) {\n\t\t\treadLineScaled(lum_bands[band_idx], row, &lum_buf[band_idx][0]);\n\t\t}\n\n\t\tfor(size_t col=0; col<w; col++) {\n\t\t\tbool skip = 0;\n\n\t\t\tif(use_ndv) {\n\t\t\t\tif(pan_buf[col] == ndv) skip = 1;\n\t\t\t\tfor(size_t band_idx=0; band_idx<lum_band_count; band_idx++) {\n\t\t\t\t\tif(lum_buf[band_idx][col] == ndv) {\n\t\t\t\t\t\tskip = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(skip) {\n\t\t\t\tscale_buf[col] = 1;\n\t\t\t} else {\n\t\t\t\tdouble lum_out = (double)pan_buf[col];\n\t\t\t\tdouble lum_in = 0;\n\t\t\t\tfor(size_t i=0; i<lum_band_count; i++) {\n\t\t\t\t\tlum_in += lum_buf[i][col] * lum_weights[i];\n\t\t\t\t}\n\n\t\t\t\tscale_buf[col] = lum_in>0 ? lum_out/lum_in : 0;\n\t\t\t} // skip\n\t\t} // col\n\n\t\tfor(size_t band_idx=0; band_idx<rgb_band_count; band_idx++) {\n\t\t\treadLineScaled(rgb_bands[band_idx], row, &rgb_buf[0]);\n\n\t\t\tfor(size_t col=0; col<w; col++) {\n\t\t\t\tif(use_ndv && rgb_buf[col] == ndv) {\n\t\t\t\t\tout_buf[col] = ndv;\n\t\t\t\t} else {\n\t\t\t\t\tdouble dbl_val = rgb_buf[col] * scale_buf[col];\n\n\t\t\t\t\tif(use_ndv) {\n\t\t\t\t\t\tdbl_val = avoidNDV(dbl_val, ndv, out_dt);\n\t\t\t\t\t}\n\n\t\t\t\t\tout_buf[col] = dbl_val;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tGDALRasterIO(dst_bands[band_idx], GF_Write, 0, row, w, 1,\n\t\t\t\t&out_buf[0], w, 1, GDT_Float64, 0, 0);\n\t\t}\n\t} // row\n\n\tfor(size_t i=0; i<rgb_ds.size(); i++) {\n\t\tGDALClose(rgb_ds[i]);\n\t}\n\tfor(size_t i=0; i<lum_ds.size(); i++) {\n\t\tGDALClose(lum_ds[i]);\n\t}\n\tGDALClose(pan_ds);\n\tGDALClose(dst_ds);\n\n\tGDALTermProgress(1, NULL, NULL);\n\n\treturn 0;\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\nScaledBand getScaledBand(GDALDatasetH lores_ds, int band_id, GDALDatasetH hires_ds) {\n\tdouble lores_affine[6];\n\tdouble hires_affine[6];\n\tif(GDALGetGeoTransform(lores_ds, lores_affine) != CE_None) {\n\t\tfatal_error(\"cannot determine affine\");\n\t}\n\tif(GDALGetGeoTransform(hires_ds, hires_affine) != CE_None) {\n\t\tfatal_error(\"cannot determine affine\");\n\t}\n\t// FIXME - we could probably work it out, as long as all the inputs\n\t// are rotated the same way\n\tif(\n\t\tlores_affine[2] || lores_affine[4] ||\n\t\thires_affine[2] || hires_affine[4]\n\t) fatal_error(\"input must not be rotated\");\n\t// again, it could probably be made to work...\n\tif(\n\t\tlores_affine[1] != -lores_affine[5] ||\n\t\thires_affine[1] != -hires_affine[5]\n\t) fatal_error(\"input must have square pixels\");\n\n\tScaledBand sb;\n\n\tdouble band_res = lores_affine[1];\n\tdouble base_res = hires_affine[1];\n\tdouble offset_x =  (hires_affine[0] - lores_affine[0]) / band_res;\n\tdouble offset_y = -(hires_affine[3] - lores_affine[3]) / band_res;\n\tdouble scale = band_res / base_res;\n\tsb.oversample = (int)round(scale);\n\tif(fabs(scale - (double)sb.oversample) > 1e+6) \n\t\tfatal_error(\"scales of input images must differ by an integer factor\");\n\n\tsb.lo_w = GDALGetRasterXSize(lores_ds);\n\tsb.lo_h = GDALGetRasterYSize(lores_ds);\n\tif(!sb.lo_w || !sb.lo_h) fatal_error(\"missing width/height\");\n\n\tsb.hi_w = GDALGetRasterXSize(hires_ds);\n\tsb.hi_h = GDALGetRasterYSize(hires_ds);\n\tif(!sb.hi_w || !sb.hi_h) fatal_error(\"missing width/height\");\n\n\t//printf(\"%d: %f %f %d %dx%d\\n\", band_id, \n\t//\toffset_x, offset_y, sb.oversample, sb.lo_w, sb.lo_h);\n\n\tsb.band = GDALGetRasterBand(lores_ds, band_id);\n\n\tsb.delta_x = (int)floor(offset_x);\n\toffset_x -= (double)sb.delta_x;\n\tsb.delta_y = (int)floor(offset_y);\n\toffset_y -= (double)sb.delta_y;\n\n\t// Cubic convolution resampling.  For more info see:\n\t// http://www.imgfsr.com/ResamplingCVPR.pdf\n\tsb.kernel_x.resize(sb.oversample);\n\tsb.kernel_y.resize(sb.oversample);\n\tfor(int mod=0; mod<sb.oversample; mod++) {\n\t\tsb.kernel_x[mod].resize(4);\n\t\tsb.kernel_y[mod].resize(4);\n\t\tdouble t = offset_x + (double)mod / (double)sb.oversample;\n\t\tsb.kernel_x[mod][0] = -0.5*t*t*t + 1.0*t*t - 0.5*t;\n\t\tsb.kernel_x[mod][1] =  1.5*t*t*t - 2.5*t*t + 1;\n\t\tsb.kernel_x[mod][2] = -1.5*t*t*t + 2.0*t*t + 0.5*t;\n\t\tsb.kernel_x[mod][3] =  0.5*t*t*t - 0.5*t*t;\n\t\tt = offset_y + (double)mod / (double)sb.oversample;\n\t\tsb.kernel_y[mod][0] = -0.5*t*t*t + 1.0*t*t - 0.5*t;\n\t\tsb.kernel_y[mod][1] =  1.5*t*t*t - 2.5*t*t + 1;\n\t\tsb.kernel_y[mod][2] = -1.5*t*t*t + 2.0*t*t + 0.5*t;\n\t\tsb.kernel_y[mod][3] =  0.5*t*t*t - 0.5*t*t;\n\t}\n\n\tsb.lines_buf.resize(4);\n\tfor(int j=0; j<4; j++) {\n\t\tsb.lines_buf[j].resize(sb.hi_w);\n\t}\n\tsb.line_buf_idx = -1000000;\n\n\treturn sb;\n}\n\nvoid readLineScaled1D(ScaledBand &sb, int row, double *hires_buf) {\n\tstd::vector<double> lores_buf(sb.lo_w);\n\n\tif(row < 0 || size_t(row) >= sb.lo_h) {\n\t\tfor(size_t col=0; col<sb.hi_w; col++) {\n\t\t\thires_buf[col] = 0;\n\t\t}\n\t} else {\n\t\tGDALRasterIO(sb.band, GF_Read, 0, row, sb.lo_w, 1, &lores_buf[0], sb.lo_w, 1, GDT_Float64, 0, 0);\n\t\tfor(int mx=0; mx<sb.oversample; mx++) {\n\t\t\tdouble *kernel = &sb.kernel_x[mx][0];\n\t\t\tfor(int x0=0; ; x0++) {\n\t\t\t\tsize_t col = x0 * sb.oversample + mx;\n\t\t\t\tif(col >= sb.hi_w) break;\n\t\t\t\tdouble accum = 0;\n\t\t\t\tfor(int i=0; i<4; i++) {\n\t\t\t\t\tint x = x0 - 1 + i + sb.delta_x;\n\t\t\t\t\tdouble v = (x<0 || size_t(x) >= sb.lo_w) ? 0 : lores_buf[x];\n\t\t\t\t\taccum += v * kernel[i];\n\t\t\t\t}\n\t\t\t\thires_buf[col] = accum;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid readLineScaled(ScaledBand &sb, int row, double *hires_buf) {\n\tint y0 = row / sb.oversample;\n\tint my = row % sb.oversample;\n\tdouble *kernel = &sb.kernel_y[my][0];\n\n\tint top_y = y0 - 1 + sb.delta_y;\n\tif(top_y == sb.line_buf_idx) {\n\t\t// no action\n\t} else if(top_y == sb.line_buf_idx+1) {\n\t\tstd::vector<double> tmp;\n\t\tstd::swap(tmp, sb.lines_buf[0]);\n\t\tfor(int j=0; j<3; j++) {\n\t\t\tstd::swap(sb.lines_buf[j], sb.lines_buf[j+1]);\n\t\t}\n\t\tstd::swap(sb.lines_buf[3], tmp);\n\t\treadLineScaled1D(sb, top_y+3, &sb.lines_buf[3][0]);\n\t\tsb.line_buf_idx = top_y;\n\t} else {\n\t\tfor(int j=0; j<4; j++) {\n\t\t\treadLineScaled1D(sb, top_y+j, &sb.lines_buf[j][0]);\n\t\t}\n\t\tsb.line_buf_idx = top_y;\n\t}\n\n\tfor(size_t col=0; col<sb.hi_w; col++) {\n\t\tdouble accum = 0;\n\t\tfor(int j=0; j<4; j++) {\n\t\t\taccum += sb.lines_buf[j][col] * kernel[j];\n\t\t}\n\t\thires_buf[col] = accum;\n\t}\n}\n\n// Helper for avoidNDV, used when datatype is an integer type.\ntemplate <typename T>\ndouble avoidNDV_int(double in, double ndv) {\n\tint64_t in_int = int64_t(round(in));\n\tint64_t ndv_int = int64_t(round(ndv));\n\tif(in_int != ndv_int) return in_int;\n\n\tint64_t valid_low  = std::numeric_limits<T>::min();\n\tint64_t valid_high = std::numeric_limits<T>::max();\n\n\t// Compute center of valid range.\n\t// NOTE: this addition doesn't overflow.\n\tint64_t mid = (valid_low+valid_high)/2;\n\t// Avoid NDV, by moving toward center of valid range.\n\t// This way, we don't fall off the edge.\n\treturn (ndv < mid) ? in_int+1 : in_int-1;\n}\n\n// If in==ndv, then perturb the value to avoid NDV.\ndouble avoidNDV(double in, double ndv, GDALDataType out_dt) {\n\t// First, clip to valid range.  This is the only way to know whether the pixel will end up\n\t// being NDV after being written.  This is probably not the fastest way to do it though...\n\t{\n\t\t// size of largest possible datatype (GDT_CFloat64), doubled (just in case).\n\t\tchar tmp[32];\n\t\tGDALCopyWords(&in, GDT_Float64, 0, tmp, out_dt, 0, 1);\n\t\tGDALCopyWords(tmp, out_dt, 0, &in, GDT_Float64, 0, 1);\n\t}\n\n\tswitch(out_dt) {\n\t\tcase GDT_Byte:   return avoidNDV_int< uint8_t>(in, ndv);\n\t\tcase GDT_UInt16: return avoidNDV_int<uint16_t>(in, ndv);\n\t\tcase GDT_Int16:  return avoidNDV_int< int16_t>(in, ndv);\n\t\tcase GDT_UInt32: return avoidNDV_int<uint32_t>(in, ndv);\n\t\tcase GDT_Int32:  return avoidNDV_int< int32_t>(in, ndv);\n\t\tdefault:         return (in==ndv) ? in+1 : in;\n\t}\n}\n", "meta": {"hexsha": "2a721a22771861a87789e882f5fb130e2f805c76", "size": 15852, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gdal_landsat_pansharp.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_landsat_pansharp.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_landsat_pansharp.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": 32.6845360825, "max_line_length": 217, "alphanum_fraction": 0.671776432, "num_tokens": 5109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766830082071396, "lm_q2_score": 0.03210070336038288, "lm_q1q2_score": 0.01051838292524644}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"sheaf_of_planes_observation_equation_jacobian.h\"\n\nstruct Plane{\n\tdouble a;\n\tdouble b;\n\tdouble c;\n\tdouble d;\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\nstd::vector<Eigen::Affine3d> sheaf_of_planes;\nstd::pair<Eigen::Vector3d, Eigen::Vector3d> line;\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\nint main(int argc, char *argv[]){\n\tfor(size_t i = 0; i < 10; i++){\n\t\tTaitBryanPose pose;\n\n\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + 5;\n\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + 5;\n\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + 5;\n\n\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 90;\n\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0001;\n\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0001;\n\n\t\tsheaf_of_planes.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\t}\n\n\tline.first = Eigen::Vector3d(0.1,0.1,0.1);\n\tline.second = Eigen::Vector3d(0.1,0.1,1.1);\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(\"sheaf_of_planes\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\tglColor3f(0.0f, 1.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\tglColor3f(0.0f, 0.0f, 1.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();\n\n\tfor(size_t i = 0 ; i < sheaf_of_planes.size(); i++){\n\t\tEigen::Affine3d &m = sheaf_of_planes[i];\n\n\t\tglBegin(GL_LINES);\n\t\t\tglColor3f(m(0,2),m(1,2),m(2,2));\n\t\t\tfor(float step = -1.0f; step <= 1.1f; step += 0.1f)\n\t\t\t{\n\t\t\t\tEigen::Vector3d v1(-1, step, 0);\n\t\t\t\tEigen::Vector3d v2( 1, step, 0);\n\n\t\t\t\tEigen::Vector3d v1t = m * v1;\n\t\t\t\tEigen::Vector3d v2t = m * v2;\n\n\t\t\t\tglVertex3f(v1t.x(), v1t.y(), v1t.z());\n\t\t\t\tglVertex3f(v2t.x(), v2t.y(), v2t.z());\n\n\t\t\t\tv1 = Eigen::Vector3d(step,-1, 0);\n\t\t\t\tv2 = Eigen::Vector3d(step, 1, 0);\n\n\t\t\t\tv1t = m * v1;\n\t\t\t\tv2t = m * v2;\n\n\t\t\t\tglVertex3f(v1t.x(), v1t.y(), v1t.z());\n\t\t\t\tglVertex3f(v2t.x(), v2t.y(), v2t.z());\n\t\t\t}\n\t\tglEnd();\n\t}\n\n\tglLineWidth(5);\n\tEigen::Vector3d line_direction = line.second - line.first;\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINES);\n\t\tglVertex3f(line.first.x() + line_direction.x() * 100.0, line.first.y() + line_direction.y() * 100.0, line.first.z() + line_direction.z() * 100.0);\n\t\tglVertex3f(line.first.x() - line_direction.x() * 100.0, line.first.y() - line_direction.y() * 100.0, line.first.z() - line_direction.z() * 100.0);\n\tglEnd();\n\tglLineWidth(1);\n\n\tglutSwapBuffers();\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 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < sheaf_of_planes.size(); i++){\n\t\t\t\tPlane plane;\n\t\t\t\tplane.a = sheaf_of_planes[i](0,2);\n\t\t\t\tplane.b = sheaf_of_planes[i](1,2);\n\t\t\t\tplane.c = sheaf_of_planes[i](2,2);\n\t\t\t\tplane.d = -plane.a * sheaf_of_planes[i](0,3) - plane.b * sheaf_of_planes[i](1,3) - plane.c * sheaf_of_planes[i](2,3);\n\n\t\t\t\tEigen::Matrix<double, 4, 1> residual;\n\t\t\t\tsheaf_of_planes_observation_equation(residual, line.first.x(), line.first.y(), line.first.z(), line.second.x(), line.second.y(), line.second.z(), plane.a, plane.b, plane.c, plane.d);\n\n\t\t\t\tEigen::Matrix<double, 4, 6> jacobian;\n\t\t\t\tsheaf_of_planes_observation_equation_jacobian(jacobian, line.first.x(), line.first.y(), line.first.z(), line.second.x(), line.second.y(), line.second.z(), plane.a, plane.b, plane.c, plane.d);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tfor(size_t j = 0 ; j < 4; j ++){\n\t\t\t\t\tfor(size_t k = 0 ; k < 6; k ++){\n\t\t\t\t\t\ttripletListA.emplace_back(ir + j, k, -jacobian(j,k));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  1000000);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3,  1);\n\n\t\t\t\ttripletListB.emplace_back(ir    , 0,  residual(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  residual(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  residual(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0,  residual(3,0));\n\t\t\t}\n\n\t\t\tEigen::Matrix<double, 1, 1> residual;\n\t\t\tEigen::Matrix<double, 1, 6> jacobian;\n\t\t\tline_direction_norm_observation_equation(residual, line.first.x(), line.first.y(), line.first.z(), line.second.x(), line.second.y(), line.second.z());\n\t\t\tline_direction_observation_equation_jacobian(jacobian, line.first.x(), line.first.y(), line.first.z(), line.second.x(), line.second.y(), line.second.z());\n\n\t\t\tint ir = tripletListB.size();\n\n\t\t\tfor(size_t k = 0 ; k < 6; k ++){\n\t\t\t\ttripletListA.emplace_back(ir, k, -jacobian(0,k));\n\t\t\t}\n\t\t\ttripletListP.emplace_back(ir    , ir    ,  1000000);\n\t\t\ttripletListB.emplace_back(ir    , 0,  residual(0,0));\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(6, 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(6, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\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\t//std::cout << it.value() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6){\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\tline.first.x() += h_x[0];\n\t\t\t\tline.first.y() += h_x[1];\n\t\t\t\tline.first.z() += h_x[2];\n\t\t\t\tline.second.x() += h_x[3];\n\t\t\t\tline.second.y() += h_x[4];\n\t\t\t\tline.second.z() += h_x[5];\n\n\t\t\t\tstd::cout << \"line: \" << line.first.x() <<  \" \" << line.first.y() << \" \" <<  line.first.z() << \" \" << line.second.x() << \" \" <<  line.second.y() << \" \" << line.second.z() << std::endl;\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'n':{\n\t\t\tTaitBryanPose pose;\n\n\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0;\n\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0;\n\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0;\n\n\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\n\n\t\t\tfor(size_t i = 0; i < sheaf_of_planes.size(); i++){\n\t\t\t\tTaitBryanPose pose_omfika;\n\n\t\t\t\tpose_omfika.px = 0;\n\t\t\t\tpose_omfika.py = 0;\n\t\t\t\tpose_omfika.pz = 0;\n\n\t\t\t\tpose_omfika.om = ((float(rand()%1000000))/1000000.0f - 0.5) * .012;\n\t\t\t\tpose_omfika.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * .012;\n\t\t\t\tpose_omfika.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * .012;\n\n\t\t\t\tsheaf_of_planes[i] =  affine_matrix_from_pose_tait_bryan(pose_omfika) * affine_matrix_from_pose_tait_bryan(pose) * sheaf_of_planes[i] * affine_matrix_from_pose_tait_bryan(pose_omfika).inverse();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: modify planes\" << std::endl;\n\tstd::cout << \"t: optimize\" << std::endl;\n}\n", "meta": {"hexsha": "c9db93f03618480174dcb469d620b9ecf00b20c9", "size": 10451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/sheaf_of_planes.cpp", "max_stars_repo_name": "karolmajek/observation_equations", "max_stars_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/c++Examples/src/sheaf_of_planes.cpp", "max_issues_repo_name": "karolmajek/observation_equations", "max_issues_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/sheaf_of_planes.cpp", "max_forks_repo_name": "karolmajek/observation_equations", "max_forks_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 28.9501385042, "max_line_length": 198, "alphanum_fraction": 0.6311357765, "num_tokens": 3738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.024423087524418494, "lm_q1q2_score": 0.010505526342908592}}
{"text": "/*\n * GenericGraph2D.cpp\n *\n *   Created on: Nov 23, 2010\n *       Author: nikai\n *  Description: generic graph types used in partitioning\n */\n#include <iostream>\n#include <boost/make_shared.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <gtsam/base/DSFVector.h>\n\n#include \"GenericGraph.h\"\n\nusing namespace std;\n\nnamespace gtsam { namespace partition {\n\n  /**\n   * Note: Need to be able to handle a graph with factors that involve variables not in the given {keys}\n   */\n  list<vector<size_t> > findIslands(const GenericGraph2D& graph, const vector<size_t>& keys, WorkSpace& workspace,\n      const int minNrConstraintsPerCamera, const int minNrConstraintsPerLandmark)\n  {\n    typedef pair<int, int> IntPair;\n    typedef list<sharedGenericFactor2D> FactorList;\n    typedef map<IntPair, FactorList::iterator> Connections;\n\n    // create disjoin set forest\n    DSFVector dsf(workspace.dsf, keys);\n\n    FactorList factors(graph.begin(), graph.end());\n    size_t nrFactors = factors.size();\n    FactorList::iterator itEnd;\n    workspace.prepareDictionary(keys);\n    while (nrFactors) {\n      Connections connections;\n      bool succeed = false;\n      itEnd = factors.end();\n      list<FactorList::iterator> toErase;\n      for (FactorList::iterator itFactor=factors.begin(); itFactor!=itEnd; itFactor++) {\n\n        // remove invalid factors\n        GenericNode2D key1 = (*itFactor)->key1, key2 = (*itFactor)->key2;\n        if (workspace.dictionary[key1.index]==-1 || workspace.dictionary[key2.index]==-1) {\n          toErase.push_back(itFactor);  nrFactors--; continue;\n        }\n\n        size_t label1 = dsf.find(key1.index);\n        size_t label2 = dsf.find(key2.index);\n        if (label1 == label2) {  toErase.push_back(itFactor);  nrFactors--; continue; }\n\n        // merge two trees if the connection is strong enough, otherwise cache it\n        // an odometry factor always merges two islands\n        if (key1.type == NODE_POSE_2D && key2.type  == NODE_POSE_2D) {\n          toErase.push_back(itFactor); nrFactors--;\n          dsf.merge(label1, label2);\n          succeed = true;\n          break;\n        }\n\n        // single landmark island only need one measurement\n        if ((dsf.isSingleton(label1)==1 && key1.type == NODE_LANDMARK_2D) ||\n            (dsf.isSingleton(label2)==1 && key2.type == NODE_LANDMARK_2D)) {\n          toErase.push_back(itFactor); nrFactors--;\n          dsf.merge(label1, label2);\n          succeed = true;\n          break;\n        }\n\n        // stack the current factor with the cached constraint\n        IntPair labels = (label1 < label2) ? make_pair(label1, label2) : make_pair(label2, label1);\n        Connections::iterator itCached = connections.find(labels);\n        if (itCached == connections.end()) {\n          connections.insert(make_pair(labels, itFactor));\n          continue;\n        } else {\n          GenericNode2D key21 = (*itCached->second)->key1, key22 = (*itCached->second)->key2;\n          // if observe the same landmark, we can not merge, abandon the current factor\n          if ((key1.index == key21.index && key1.type == NODE_LANDMARK_2D) ||\n              (key1.index == key22.index && key1.type == NODE_LANDMARK_2D) ||\n              (key2.index == key21.index && key2.type == NODE_LANDMARK_2D) ||\n              (key2.index == key22.index && key2.type == NODE_LANDMARK_2D)) {\n            toErase.push_back(itFactor); nrFactors--;\n            continue;\n          } else {\n            toErase.push_back(itFactor); nrFactors--;\n            toErase.push_back(itCached->second); nrFactors--;\n            dsf.merge(label1, label2);\n            connections.erase(itCached);\n            succeed = true;\n            break;\n          }\n        }\n      }\n\n      // erase unused factors\n      for(const FactorList::iterator& it: toErase)\n        factors.erase(it);\n\n      if (!succeed) break;\n    }\n\n    list<vector<size_t> > islands;\n    map<size_t, vector<size_t> > arrays = dsf.arrays();\n    for(const auto& kv : arrays)\n      islands.push_back(kv.second);\n    return islands;\n  }\n\n\n  /* ************************************************************************* */\n  void print(const GenericGraph2D& graph, const std::string name) {\n    cout << name << endl;\n    for(const sharedGenericFactor2D& factor_: graph)\n      cout << factor_->key1.index << \" \" << factor_->key2.index << endl;\n  }\n\n  /* ************************************************************************* */\n  void print(const GenericGraph3D& graph, const std::string name) {\n    cout << name << endl;\n    for(const sharedGenericFactor3D& factor_: graph)\n      cout << factor_->key1.index << \" \" << factor_->key2.index << \" (\" <<\n      factor_->key1.type << \", \" << factor_->key2.type <<\")\" << endl;\n  }\n\n  /* ************************************************************************* */\n  // create disjoin set forest\n  DSFVector createDSF(const GenericGraph3D& graph, const vector<size_t>& keys, const WorkSpace& workspace) {\n    DSFVector dsf(workspace.dsf, keys);\n    typedef list<sharedGenericFactor3D> FactorList;\n\n    FactorList factors(graph.begin(), graph.end());\n    size_t nrFactors = factors.size();\n    FactorList::iterator itEnd;\n    while (nrFactors) {\n\n      bool succeed = false;\n      itEnd = factors.end();\n      list<FactorList::iterator> toErase;\n      for (FactorList::iterator itFactor=factors.begin(); itFactor!=itEnd; itFactor++) {\n\n        // remove invalid factors\n        if (graph.size() == 178765) cout << \"kai21\" <<  endl;\n        GenericNode3D key1 = (*itFactor)->key1, key2 = (*itFactor)->key2;\n        if (graph.size() == 178765) cout << \"kai21: \" << key1.index << \" \" << key2.index << endl;\n        if (workspace.dictionary[key1.index]==-1 || workspace.dictionary[key2.index]==-1) {\n          toErase.push_back(itFactor);  nrFactors--; continue;\n        }\n\n        if (graph.size() == 178765) cout << \"kai22\" << endl;\n        size_t label1 = dsf.find(key1.index);\n        size_t label2 = dsf.find(key2.index);\n        if (label1 == label2) {  toErase.push_back(itFactor);  nrFactors--; continue; }\n\n        if (graph.size() == 178765) cout << \"kai23\" << endl;\n        // merge two trees if the connection is strong enough, otherwise cache it\n        // an odometry factor always merges two islands\n        if ((key1.type == NODE_POSE_3D && key2.type  == NODE_LANDMARK_3D) ||\n            (key1.type == NODE_POSE_3D && key2.type  == NODE_POSE_3D)) {\n          toErase.push_back(itFactor); nrFactors--;\n          dsf.merge(label1, label2);\n          succeed = true;\n          break;\n        }\n\n        if (graph.size() == 178765) cout << \"kai24\" << endl;\n\n\n      }\n\n      // erase unused factors\n      for(const FactorList::iterator& it: toErase)\n      factors.erase(it);\n\n      if (!succeed) break;\n    }\n    return dsf;\n  }\n\n  /* ************************************************************************* */\n  // first check the type of the key (pose or landmark), and then check whether it is singular\n  inline bool isSingular(const set<size_t>& singularCameras, const set<size_t>& singularLandmarks, const GenericNode3D& node) {\n    switch(node.type) {\n    case NODE_POSE_3D:\n      return singularCameras.find(node.index) != singularCameras.end(); break;\n    case NODE_LANDMARK_3D:\n      return singularLandmarks.find(node.index) != singularLandmarks.end(); break;\n    default:\n      throw runtime_error(\"unrecognized key type!\");\n    }\n  }\n\n  /* ************************************************************************* */\n  void findSingularCamerasLandmarks(const GenericGraph3D& graph, const WorkSpace& workspace,\n      const vector<bool>& isCamera, const vector<bool>& isLandmark,\n      set<size_t>& singularCameras, set<size_t>& singularLandmarks,  vector<int>& nrConstraints,\n      bool& foundSingularCamera, bool& foundSingularLandmark,\n      const int minNrConstraintsPerCamera, const int minNrConstraintsPerLandmark) {\n\n    // compute the constraint number per camera\n    std::fill(nrConstraints.begin(),  nrConstraints.end(),    0);\n    for(const sharedGenericFactor3D& factor_: graph) {\n      const int& key1 = factor_->key1.index;\n      const int& key2 = factor_->key2.index;\n      if (workspace.dictionary[key1] != -1 &&  workspace.dictionary[key2] != -1 &&\n          !isSingular(singularCameras, singularLandmarks, factor_->key1) &&\n          !isSingular(singularCameras, singularLandmarks, factor_->key2)) {\n        nrConstraints[key1]++;\n        nrConstraints[key2]++;\n\n        // a single pose constraint is sufficient for stereo, so we add 2 to the counter\n        // for a total of 3, i.e. the same as 3 landmarks fully constraining the camera\n        if(factor_->key1.type == NODE_POSE_3D && factor_->key2.type == NODE_POSE_3D){\n          nrConstraints[key1]+=2;\n          nrConstraints[key2]+=2;\n        }\n      }\n    }\n\n    // find singular cameras and landmarks\n    foundSingularCamera = false;\n    foundSingularLandmark = false;\n    for (size_t i=0; i<nrConstraints.size(); i++) {\n      if (isCamera[i] && nrConstraints[i] < minNrConstraintsPerCamera &&\n          singularCameras.find(i) == singularCameras.end()) {\n        singularCameras.insert(i);\n        foundSingularCamera = true;\n      }\n      if (isLandmark[i] && nrConstraints[i] < minNrConstraintsPerLandmark &&\n          singularLandmarks.find(i) == singularLandmarks.end()) {\n        singularLandmarks.insert(i);\n        foundSingularLandmark = true;\n      }\n    }\n  }\n\n  /* ************************************************************************* */\n  list<vector<size_t> > findIslands(const GenericGraph3D& graph, const vector<size_t>& keys, WorkSpace& workspace,\n      const size_t minNrConstraintsPerCamera, const size_t minNrConstraintsPerLandmark) {\n\n    // create disjoint set forest\n    workspace.prepareDictionary(keys);\n    DSFVector dsf = createDSF(graph, keys, workspace);\n\n    const bool verbose = false;\n    bool foundSingularCamera = true;\n    bool foundSingularLandmark = true;\n\n    list<vector<size_t> > islands;\n    set<size_t> singularCameras, singularLandmarks;\n    vector<bool> isCamera(workspace.dictionary.size(), false);\n    vector<bool> isLandmark(workspace.dictionary.size(), false);\n\n    // check the constraint number of every variable\n    // find the camera and landmark keys\n    for(const sharedGenericFactor3D& factor_: graph) {\n      //assert(factor_->key2.type == NODE_LANDMARK_3D); // only VisualSLAM should come here, not StereoSLAM\n      if (workspace.dictionary[factor_->key1.index] != -1) {\n        if (factor_->key1.type == NODE_POSE_3D)\n          isCamera[factor_->key1.index] = true;\n        else\n          isLandmark[factor_->key1.index] = true;\n      }\n            if (workspace.dictionary[factor_->key2.index] != -1) {\n        if (factor_->key2.type == NODE_POSE_3D)\n          isCamera[factor_->key2.index] = true;\n        else\n          isLandmark[factor_->key2.index] = true;\n            }\n    }\n\n    vector<int> nrConstraints(workspace.dictionary.size(), 0);\n    // iterate until all singular variables have been removed. Removing a singular variable\n    // can cause another to become singular, so this will probably run several times\n    while (foundSingularCamera || foundSingularLandmark) {\n      findSingularCamerasLandmarks(graph, workspace, isCamera, isLandmark,      // input\n          singularCameras, singularLandmarks, nrConstraints,                    // output\n          foundSingularCamera, foundSingularLandmark,                           // output\n          minNrConstraintsPerCamera,  minNrConstraintsPerLandmark);             // input\n    }\n\n    // add singular variables directly as islands\n    if (!singularCameras.empty()) {\n      if (verbose) cout << \"singular cameras:\";\n      for(const size_t i: singularCameras) {\n        islands.push_back(vector<size_t>(1, i)); // <---------------------------\n        if (verbose) cout << i << \" \";\n      }\n      if (verbose) cout << endl;\n    }\n    if (!singularLandmarks.empty()) {\n      if (verbose) cout << \"singular landmarks:\";\n      for(const size_t i: singularLandmarks) {\n        islands.push_back(vector<size_t>(1, i)); // <---------------------------\n        if (verbose) cout << i << \" \";\n      }\n      if (verbose) cout << endl;\n    }\n\n\n    // regenerating islands\n    map<size_t, vector<size_t> > labelIslands = dsf.arrays();\n    size_t label; vector<size_t> island;\n    for(const auto& li: labelIslands) {\n      tie(label, island) = li;\n      vector<size_t> filteredIsland; // remove singular cameras from array\n      filteredIsland.reserve(island.size());\n      for(const size_t key: island) {\n        if ((isCamera[key]   && singularCameras.find(key) == singularCameras.end()) ||        // not singular\n            (isLandmark[key] && singularLandmarks.find(key) == singularLandmarks.end()) ||    // not singular\n            (!isCamera[key] && !isLandmark[key])) {   // the key is not involved in any factor, so the type is undertermined\n          filteredIsland.push_back(key);\n        }\n      }\n      islands.push_back(filteredIsland);\n    }\n\n    // sanity check\n    size_t nrKeys = 0;\n    for(const vector<size_t>& island: islands)\n      nrKeys += island.size();\n    if (nrKeys != keys.size())  {\n      cout << nrKeys << \" vs \" << keys.size() << endl;\n      throw runtime_error(\"findIslands: the number of keys is inconsistent!\");\n    }\n\n\n    if (verbose) cout << \"found \" << islands.size() << \" islands!\" << endl;\n    return islands;\n  }\n\n  /* ************************************************************************* */\n  // return the number of intersection between two **sorted** landmark vectors\n  inline int getNrCommonLandmarks(const vector<size_t>& landmarks1, const vector<size_t>& landmarks2){\n    size_t i1 = 0, i2 = 0;\n    int nrCommonLandmarks = 0;\n    while (i1 < landmarks1.size() && i2 < landmarks2.size()) {\n      if (landmarks1[i1] < landmarks2[i2])\n        i1 ++;\n      else if (landmarks1[i1] > landmarks2[i2])\n        i2 ++;\n      else {\n        i1++; i2++;\n        nrCommonLandmarks ++;\n      }\n    }\n    return nrCommonLandmarks;\n  }\n\n  /* ************************************************************************* */\n  void reduceGenericGraph(const GenericGraph3D& graph, const std::vector<size_t>& cameraKeys,  const std::vector<size_t>& landmarkKeys,\n      const std::vector<int>& dictionary,  GenericGraph3D& reducedGraph) {\n\n    typedef size_t LandmarkKey;\n    // get a mapping from each landmark to its connected cameras\n    vector<vector<LandmarkKey> > cameraToLandmarks(dictionary.size());\n    // for odometry xi-xj where i<j, we always store cameraToCamera[i] = j, otherwise equal to -1 if no odometry\n    vector<int> cameraToCamera(dictionary.size(), -1);\n    size_t key_i, key_j;\n    for(const sharedGenericFactor3D& factor_: graph) {\n      if (factor_->key1.type == NODE_POSE_3D) {\n        if (factor_->key2.type == NODE_LANDMARK_3D) {// projection factor\n          cameraToLandmarks[factor_->key1.index].push_back(factor_->key2.index);\n        }\n        else { // odometry factor\n          if (factor_->key1.index < factor_->key2.index) {\n            key_i = factor_->key1.index;\n            key_j = factor_->key2.index;\n          } else {\n            key_i = factor_->key2.index;\n            key_j = factor_->key1.index;\n          }\n          cameraToCamera[key_i] = key_j;\n        }\n      }\n    }\n\n    // sort the landmark keys for the late getNrCommonLandmarks call\n    for(vector<LandmarkKey> &landmarks: cameraToLandmarks){\n      if (!landmarks.empty())\n        std::sort(landmarks.begin(), landmarks.end());\n    }\n\n    // generate the reduced graph\n    reducedGraph.clear();\n    int factorIndex = 0;\n    int camera1, camera2, nrTotalConstraints;\n    bool hasOdometry;\n    for (size_t i1=0; i1<cameraKeys.size()-1; ++i1) {\n      for (size_t i2=i1+1; i2<cameraKeys.size(); ++i2) {\n        camera1 = cameraKeys[i1];\n        camera2 = cameraKeys[i2];\n        int nrCommonLandmarks = getNrCommonLandmarks(cameraToLandmarks[camera1], cameraToLandmarks[camera2]);\n        hasOdometry =  cameraToCamera[camera1] == camera2;\n        if (nrCommonLandmarks > 0 || hasOdometry) {\n          nrTotalConstraints = 2 * nrCommonLandmarks + (hasOdometry ? 6 : 0);\n          reducedGraph.push_back(boost::make_shared<GenericFactor3D>(camera1, camera2,\n              factorIndex++, NODE_POSE_3D, NODE_POSE_3D, nrTotalConstraints));\n        }\n      }\n    }\n  }\n\n  /* ************************************************************************* */\n  void checkSingularity(const GenericGraph3D& graph, const std::vector<size_t>& frontals,\n      WorkSpace& workspace, const size_t minNrConstraintsPerCamera, const size_t minNrConstraintsPerLandmark) {\n    workspace.prepareDictionary(frontals);\n    vector<size_t> nrConstraints(workspace.dictionary.size(), 0);\n\n    // summarize the constraint number\n    const vector<int>& dictionary = workspace.dictionary;\n    vector<bool> isValidCamera(workspace.dictionary.size(), false);\n    vector<bool> isValidLandmark(workspace.dictionary.size(), false);\n    for(const sharedGenericFactor3D& factor_: graph) {\n      assert(factor_->key1.type == NODE_POSE_3D);\n      //assert(factor_->key2.type == NODE_LANDMARK_3D);\n      const size_t& key1 = factor_->key1.index;\n      const size_t& key2 = factor_->key2.index;\n      if (dictionary[key1] == -1 || dictionary[key2] == -1)\n        continue;\n\n      isValidCamera[key1] = true;\n      if(factor_->key2.type == NODE_LANDMARK_3D)\n        isValidLandmark[key2] = true;\n      else\n        isValidCamera[key2] = true;\n\n      nrConstraints[key1]++;\n      nrConstraints[key2]++;\n\n      // a single pose constraint is sufficient for stereo, so we add 2 to the counter\n      // for a total of 3, i.e. the same as 3 landmarks fully constraining the camera\n      if(factor_->key1.type == NODE_POSE_3D && factor_->key2.type == NODE_POSE_3D){\n        nrConstraints[key1]+=2;\n        nrConstraints[key2]+=2;\n      }\n    }\n\n    // find the minimum constraint for cameras and landmarks\n    size_t minFoundConstraintsPerCamera = 10000;\n    size_t minFoundConstraintsPerLandmark = 10000;\n\n    for (size_t i=0; i<isValidCamera.size(); i++) {\n      if (isValidCamera[i]) {\n        minFoundConstraintsPerCamera   = std::min(nrConstraints[i], minFoundConstraintsPerCamera);\n        if (nrConstraints[i] < minNrConstraintsPerCamera)\n              cout << \"!!!!!!!!!!!!!!!!!!! camera with \" << nrConstraints[i] << \" constraint: \" << i << endl;\n      }\n\n    }\n    for (size_t j=0; j<isValidLandmark.size(); j++) {\n      if (isValidLandmark[j]) {\n        minFoundConstraintsPerLandmark = std::min(nrConstraints[j], minFoundConstraintsPerLandmark);\n        if (nrConstraints[j] < minNrConstraintsPerLandmark)\n          cout << \"!!!!!!!!!!!!!!!!!!! landmark with \" << nrConstraints[j] << \" constraint: \" << j << endl;\n      }\n    }\n\n    // debug info\n    for(const size_t key: frontals) {\n      if (isValidCamera[key] && nrConstraints[key] < minNrConstraintsPerCamera)\n        cout << \"singular camera:\" << key << \" with \" << nrConstraints[key] << \" constraints\" << endl;\n    }\n\n     if (minFoundConstraintsPerCamera < minNrConstraintsPerCamera)\n      throw runtime_error(\"checkSingularity:minConstraintsPerCamera < \" + boost::lexical_cast<string>(minFoundConstraintsPerCamera));\n    if (minFoundConstraintsPerLandmark < minNrConstraintsPerLandmark)\n      throw runtime_error(\"checkSingularity:minConstraintsPerLandmark < \" + boost::lexical_cast<string>(minFoundConstraintsPerLandmark));\n  }\n\n}} // namespace\n", "meta": {"hexsha": "92f0266d0a6b3f4e58793e4e355a5ad38d381c96", "size": 19442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/partition/GenericGraph.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam_unstable/partition/GenericGraph.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam_unstable/partition/GenericGraph.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "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": 41.0168776371, "max_line_length": 137, "alphanum_fraction": 0.6124884271, "num_tokens": 4768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773708, "lm_q2_score": 0.02675928318544315, "lm_q1q2_score": 0.010498652722777205}}
{"text": "//=============================================================================================================\n/**\n * @file     hpifit.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\n *           Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;\n *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n * @since    0.1.0\n * @date     March, 2017\n *\n * @section  LICENSE\n *\n * Copyright (C) 2017, Lorenz Esch, Matti Hamalainen. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n *       following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n *       the following disclaimer in the documentation and/or other materials provided with the distribution.\n *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n *       to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief    HPIFit class defintion.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"hpifit.h\"\n#include \"hpifitdata.h\"\n\n#include <utils/ioutils.h>\n#include <utils/mnemath.h>\n\n#include <iostream>\n#include <fiff/fiff_cov.h>\n#include <fiff/fiff_dig_point_set.h>\n#include <fstream>\n\n#include <fwd/fwd_coil_set.h>\n\n//=============================================================================================================\n// EIGEN INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Dense>\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QFuture>\n#include <QtConcurrent/QtConcurrent>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace INVERSELIB;\nusing namespace FIFFLIB;\nusing namespace FWDLIB;\n\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nHPIFit::HPIFit(FiffInfo::SPtr pFiffInfo,\n               bool bDoFastFit)\n    : m_bDoFastFit(bDoFastFit)\n{\n    // init member variables\n    m_lChannels = QList<FIFFLIB::FiffChInfo>();\n    m_vecInnerind = QVector<int>();\n    m_sensors = SensorSet();\n    m_lBads = pFiffInfo->bads;\n    m_matModel = MatrixXd(0,0);\n    m_vecFreqs = QVector<int>();\n\n    updateChannels(pFiffInfo);\n    updateSensor();\n}\n\n//=============================================================================================================\n\nvoid HPIFit::fitHPI(const MatrixXd& t_mat,\n                    const MatrixXd& t_matProjectors,\n                    FiffCoordTrans& transDevHead,\n                    const QVector<int>& vecFreqs,\n                    QVector<double>& vecError,\n                    VectorXd& vecGoF,\n                    FiffDigPointSet& fittedPointSet,\n                    FiffInfo::SPtr pFiffInfo,\n                    bool bDoDebug,\n                    const QString& sHPIResourceDir,\n                    int iMaxIterations,\n                    float fAbortError)\n{\n    //Check if data was passed\n    if(t_mat.rows() == 0 || t_mat.cols() == 0 ) {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - No data passed. Returning.\";\n        return;\n    }\n    //Check if projector was passed\n    if(t_matProjectors.rows() == 0 || t_matProjectors.cols() == 0 ) {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - No projector passed. Returning.\";\n        return;\n    }\n\n    bool bUpdateModel = false;\n\n    // check if bads have changed and update coils/channellist if so\n    if(!(m_lBads == pFiffInfo->bads) || m_lChannels.isEmpty()) {\n        m_lBads = pFiffInfo->bads;\n        updateChannels(pFiffInfo);\n        updateSensor();\n        bUpdateModel = true;\n    }\n\n    if(m_lChannels.isEmpty()) {\n        qWarning() << \"HPIFit::fitHPI - Channel list is empty. Returning.\";\n        return;\n    }\n\n    // check if we have to update the model\n    if(bUpdateModel || (m_matModel.rows() == 0) || (m_vecFreqs != vecFreqs) || (t_mat.cols() != m_matModel.cols())) {\n        updateModel(pFiffInfo->sfreq, t_mat.cols(), pFiffInfo->linefreq, vecFreqs);\n        m_vecFreqs = vecFreqs;\n        bUpdateModel = false;\n    }\n\n    // Make sure the fitted digitzers are empty\n    fittedPointSet.clear();\n\n    // init coil parameters\n    struct CoilParam coil;\n\n    //Get HPI coils from digitizers and set number of coils\n    int iNumCoils = 0;\n    QList<FiffDigPoint> lHPIPoints;\n\n    for(int i = 0; i < pFiffInfo->dig.size(); ++i) {\n        if(pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) {\n            iNumCoils++;\n            lHPIPoints.append(pFiffInfo->dig[i]);\n        }\n    }\n\n    //Set coil frequencies\n    VectorXd vecCoilfreq(iNumCoils);\n\n    if(vecFreqs.size() >= iNumCoils) {\n        for(int i = 0; i < iNumCoils; ++i) {\n            vecCoilfreq[i] = vecFreqs.at(i);\n            //std::cout<<std::endl << vecCoilfreq[i] << \"Hz\";\n        }\n    } else {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - Not enough coil frequencies specified. Returning.\";\n        return;\n    }\n\n    // Initialize HPI coils location and moment\n    coil.pos = MatrixXd::Zero(iNumCoils,3);\n    coil.mom = MatrixXd::Zero(iNumCoils,3);\n    coil.dpfiterror = VectorXd::Zero(iNumCoils);\n    coil.dpfitnumitr = VectorXd::Zero(iNumCoils);\n\n    // Create digitized HPI coil position matrix\n    MatrixXd matHeadHPI(iNumCoils,3);\n\n    // check the pFiffInfo->dig information. If dig is empty, set the matHeadHPI is 0;\n    if (lHPIPoints.size() > 0) {\n        for (int i = 0; i < lHPIPoints.size(); ++i) {\n            matHeadHPI(i,0) = lHPIPoints.at(i).r[0];\n            matHeadHPI(i,1) = lHPIPoints.at(i).r[1];\n            matHeadHPI(i,2) = lHPIPoints.at(i).r[2];\n        }\n    } else {\n        matHeadHPI.fill(0);\n    }\n\n    //Create new projector based on the excluded channels, first exclude the rows then the columns\n    MatrixXd matProjectorsRows(m_vecInnerind.size(),t_matProjectors.cols());\n    MatrixXd matProjectorsInnerind(m_vecInnerind.size(),m_vecInnerind.size());\n\n    for (int i = 0; i < matProjectorsRows.rows(); ++i) {\n        matProjectorsRows.row(i) = t_matProjectors.row(m_vecInnerind.at(i));\n    }\n\n    for (int i = 0; i < matProjectorsInnerind.cols(); ++i) {\n        matProjectorsInnerind.col(i) = matProjectorsRows.col(m_vecInnerind.at(i));\n    }\n\n    // Get the data from inner layer channels\n    MatrixXd matInnerdata(m_vecInnerind.size(), t_mat.cols());\n\n    for(int j = 0; j < m_vecInnerind.size(); ++j) {\n        matInnerdata.row(j) << t_mat.row(m_vecInnerind[j]);\n    }\n\n    // Calculate topo\n    MatrixXd matTopo;\n    MatrixXd matAmp(m_vecInnerind.size(), iNumCoils);\n    MatrixXd matAmpC(m_vecInnerind.size(), iNumCoils);\n\n    matTopo = m_matModel * matInnerdata.transpose(); // topo: # of good inner channel x 8\n\n    if(m_bDoFastFit) {\n        // Select sine or cosine component depending on the relative size\n        matTopo.transposeInPlace();\n        matAmp = matTopo.leftCols(iNumCoils);\n        matAmpC = matTopo.rightCols(iNumCoils);\n        for(int j = 0; j < iNumCoils; ++j) {\n           float fNS = 0.0;\n           float fNC = 0.0;\n           fNS = matAmp.col(j).array().square().sum();\n           fNC = matAmpC.col(j).array().square().sum();\n           if(fNC > fNS) {\n               matAmp.col(j) = matAmpC.col(j);\n           }\n        }\n    } else {\n        // estimate the sinusoid phase\n        for(int i = 0; i < iNumCoils; ++i) {\n            int from = 2*i;\n            MatrixXd m = matTopo.block(from,0,2,matTopo.cols());\n            JacobiSVD<MatrixXd> svd(m, ComputeThinU | ComputeThinV);\n            matAmp.col(i) = svd.singularValues()(0) * svd.matrixV().col(0);\n        }\n    }\n\n    //Find good seed point/starting point for the coil position in 3D space\n    //Find biggest amplitude per pickup coil (sensor) and store corresponding sensor channel index\n    VectorXi vecChIdcs(iNumCoils);\n\n    for (int j = 0; j < iNumCoils; j++) {\n        int iChIdx = 0;\n        VectorXd::Index indMax;\n        matAmp.col(j).maxCoeff(&indMax);\n        if(indMax < m_vecInnerind.size()) {\n            iChIdx = m_vecInnerind.at(indMax);\n        }\n        vecChIdcs(j) = iChIdx;\n    }\n\n    vecError.resize(iNumCoils);\n    double dError = std::accumulate(vecError.begin(), vecError.end(), .0) / vecError.size();\n    MatrixXd matCoilPos = MatrixXd::Zero(iNumCoils,3);\n\n    // Generate seed point by projection the found channel position 3cm inwards if previous transDevHead is identity or bad fit\n    if(transDevHead.trans == MatrixXd::Identity(4,4).cast<float>() || dError > 0.010) {\n        for (int j = 0; j < vecChIdcs.rows(); ++j) {\n            if(vecChIdcs(j) < pFiffInfo->chs.size()) {\n                Vector3f r0 = pFiffInfo->chs.at(vecChIdcs(j)).chpos.r0;\n                matCoilPos.row(j) = (-1 * pFiffInfo->chs.at(vecChIdcs(j)).chpos.ez * 0.03 + r0).cast<double>();\n            }\n        }\n    } else {\n        matCoilPos = transDevHead.apply_inverse_trans(matHeadHPI.cast<float>()).cast<double>();\n    }\n\n    coil.pos = matCoilPos;\n\n    // Perform actual localization\n    coil = dipfit(coil,\n                  m_sensors,\n                  matAmp,\n                  iNumCoils,\n                  matProjectorsInnerind,\n                  iMaxIterations,\n                  fAbortError);\n\n    Matrix4d matTrans = computeTransformation(matHeadHPI, coil.pos);\n    transDevHead = FiffCoordTrans::make(1,4,matTrans.cast<float>(),true);\n\n    //Calculate Error\n    MatrixXd matTemp = coil.pos;\n    MatrixXd matTestPos = transDevHead.apply_trans(matTemp.cast<float>()).cast<double>();\n    MatrixXd matDiffPos = matTestPos - matHeadHPI;\n\n    for(int i = 0; i < matDiffPos.rows(); ++i) {\n        vecError[i] = matDiffPos.row(i).norm();\n    }\n\n    // store Goodness of Fit\n    vecGoF = coil.dpfiterror;\n    for(int i = 0; i < vecGoF.size(); ++i) {\n        vecGoF(i) = 1 - vecGoF(i);\n    }\n\n    //Generate final fitted points and store in digitizer set\n    for(int i = 0; i < coil.pos.rows(); ++i) {\n        FiffDigPoint digPoint;\n        digPoint.kind = FIFFV_POINT_EEG; //Store as EEG so they have a different color\n        digPoint.ident = i;\n        digPoint.r[0] = coil.pos(i,0);\n        digPoint.r[1] = coil.pos(i,1);\n        digPoint.r[2] = coil.pos(i,2);\n\n        fittedPointSet << digPoint;\n    }\n\n    if(bDoDebug) {\n        // DEBUG HPI fitting and write debug results\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - dpfiterror\" << coil.dpfiterror << std::endl << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - Initial seed point for HPI coils\" << std::endl << matCoilPos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - temp\" << std::endl << matTemp << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - testPos\" << std::endl << matTestPos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - Diff fitted - original\" << std::endl << matDiffPos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - dev/head trans\" << std::endl << matTrans << std::endl;\n\n        QString sTimeStamp = QDateTime::currentDateTime().toString(\"yyMMdd_hhmmss\");\n\n        if(!QDir(sHPIResourceDir).exists()) {\n            QDir().mkdir(sHPIResourceDir);\n        }\n\n        UTILSLIB::IOUtils::write_eigen_matrix(matCoilPos, QString(\"%1/%2_coilPosSeed_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(vecGoF, QString(\"%1/%2_gof_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(coil.pos, QString(\"%1/%2_coilPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(matHeadHPI, QString(\"%1/%2_headHPI_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXd testPosCut = matTestPos.transpose();//block(0,0,3,4);\n        UTILSLIB::IOUtils::write_eigen_matrix(testPosCut, QString(\"%1/%2_testPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXi matIdx(vecChIdcs.rows(),1);\n        matIdx.col(0) = vecChIdcs;\n        UTILSLIB::IOUtils::write_eigen_matrix(matIdx, QString(\"%1/%2_idx_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXd matCoilFreq(vecCoilfreq.rows(),1);\n        matCoilFreq.col(0) = vecCoilfreq;\n        UTILSLIB::IOUtils::write_eigen_matrix(matCoilFreq, QString(\"%1/%2_coilFreq_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(matDiffPos, QString(\"%1/%2_diffPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(matAmp, QString(\"%1/%2_amp_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n    }\n}\n\n//=============================================================================================================\n\nvoid HPIFit::findOrder(const MatrixXd& t_mat,\n                       const MatrixXd& t_matProjectors,\n                       FiffCoordTrans& transDevHead,\n                       QVector<int>& vecFreqs,\n                       QVector<double>& vecError,\n                       VectorXd& vecGoF,\n                       FiffDigPointSet& fittedPointSet,\n                       FiffInfo::SPtr pFiffInfo)\n{\n    // clear points\n    fittedPointSet.clear();\n    transDevHead.clear();\n    vecError.fill(0);\n\n    // casual fit to get fitted coils\n    fitHPI(t_mat, t_matProjectors, transDevHead, vecFreqs, vecError, vecGoF, fittedPointSet, pFiffInfo);\n\n    // extract digitized and fitted coils\n    int iNumCoils = vecFreqs.length();\n    QVector<int> vecToOrder = vecFreqs;\n    VectorXd vecOrder(iNumCoils);\n    Vector4d vecInit(0,1,2,3);\n    MatrixXd matCoil = MatrixXd::Zero(iNumCoils,3);\n    MatrixXd matDig = MatrixXd::Zero(iNumCoils,3);\n    VectorXd vecDist = VectorXd::Zero(iNumCoils);\n    QList<FiffDigPoint> lHPIPoints;\n\n    for(int i = 0; i < iNumCoils; ++i) {\n        matCoil(i,0) = fittedPointSet[i].r[0];\n        matCoil(i,1) = fittedPointSet[i].r[1];\n        matCoil(i,2) = fittedPointSet[i].r[2];\n    }\n\n    for(int i = 0; i < pFiffInfo->dig.size(); ++i) {\n        if(pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) {\n            lHPIPoints.append(pFiffInfo->dig[i]);\n        }\n    }\n\n    for (int i = 0; i < lHPIPoints.size(); ++i) {\n        matDig(i,0) = lHPIPoints.at(i).r[0];\n        matDig(i,1) = lHPIPoints.at(i).r[1];\n        matDig(i,2) = lHPIPoints.at(i).r[2];\n    }\n\n    // Find closest point to each dig and find with that the order\n\n    for(int i = 0; i < iNumCoils; i++) {\n        // distances from of fitted point to all digitized\n        vecDist = (matCoil.rowwise() - matDig.row(i)).rowwise().norm();\n        Eigen::MatrixXf::Index min_index;\n        vecDist.minCoeff(&min_index);\n        vecOrder(i) = vecInit(min_index);\n        vecToOrder[i] = vecFreqs[min_index];\n    }\n\n    // check if still all frequencies are represented and update model\n    if(std::accumulate(vecFreqs.begin(), vecFreqs.end(), .0) ==  std::accumulate(vecToOrder.begin(), vecToOrder.end(), .0)) {\n        vecFreqs = vecToOrder;\n    } else {\n        qWarning() << \"HPIFit::findOrder: frequency ordering was not succesfull.\";\n    }\n}\n\n//=============================================================================================================\n\nCoilParam HPIFit::dipfit(struct CoilParam coil,\n                         const SensorSet& sensors,\n                         const MatrixXd& matData,\n                         int iNumCoils,\n                         const MatrixXd& t_matProjectors,\n                         int iMaxIterations,\n                         float fAbortError)\n{\n    //Do this in conncurrent mode\n    //Generate QList structure which can be handled by the QConcurrent framework\n    QList<HPIFitData> lCoilData;\n\n    for(qint32 i = 0; i < iNumCoils; ++i) {\n        HPIFitData coilData;\n        coilData.m_coilPos = coil.pos.row(i);\n        coilData.m_sensorData = matData.col(i);\n        coilData.m_sensors = sensors;\n        coilData.m_matProjector = t_matProjectors;\n        coilData.m_iMaxIterations = iMaxIterations;\n        coilData.m_fAbortError = fAbortError;\n\n        lCoilData.append(coilData);\n    }\n    //Do the concurrent filtering\n    if(!lCoilData.isEmpty()) {\n//        //Do sequential\n//        for(int l = 0; l < lCoilData.size(); ++l) {\n//            doDipfitConcurrent(lCoilData[l]);\n//        }\n\n        //Do concurrent\n        QFuture<void> future = QtConcurrent::map(lCoilData,\n                                                 &HPIFitData::doDipfitConcurrent);\n        future.waitForFinished();\n\n        //Transform results to final coil information\n        for(qint32 i = 0; i < lCoilData.size(); ++i) {\n            coil.pos.row(i) = lCoilData.at(i).m_coilPos;\n            coil.mom = lCoilData.at(i).m_errorInfo.moment.transpose();\n            coil.dpfiterror(i) = lCoilData.at(i).m_errorInfo.error;\n            coil.dpfitnumitr(i) = lCoilData.at(i).m_errorInfo.numIterations;\n\n            //std::cout<<std::endl<< \"HPIFit::dipfit - Itr steps for coil \" << i << \" =\" <<coil.dpfitnumitr(i);\n        }\n    }\n\n    return coil;\n}\n\n//=============================================================================================================\n\nEigen::Matrix4d HPIFit::computeTransformation(Eigen::MatrixXd matNH, MatrixXd matBT)\n{\n    MatrixXd matXdiff, matYdiff, matZdiff, matC, matQ;\n    Matrix4d matTransFinal = Matrix4d::Identity(4,4);\n    Matrix4d matRot = Matrix4d::Zero(4,4);\n    Matrix4d matTrans = Matrix4d::Identity(4,4);\n    double dMeanX,dMeanY,dMeanZ,dNormf;\n\n    for(int i = 0; i < 15; ++i) {\n        // Calculate mean translation for all points -> centroid of both data sets\n        matXdiff = matNH.col(0) - matBT.col(0);\n        matYdiff = matNH.col(1) - matBT.col(1);\n        matZdiff = matNH.col(2) - matBT.col(2);\n\n        dMeanX = matXdiff.mean();\n        dMeanY = matYdiff.mean();\n        dMeanZ = matZdiff.mean();\n\n        // Apply translation -> bring both data sets to the same center location\n        for (int j = 0; j < matBT.rows(); ++j) {\n            matBT(j,0) = matBT(j,0) + dMeanX;\n            matBT(j,1) = matBT(j,1) + dMeanY;\n            matBT(j,2) = matBT(j,2) + dMeanZ;\n        }\n\n        // Estimate rotation component\n        matC = matBT.transpose() * matNH;\n\n        JacobiSVD< MatrixXd > svd(matC ,Eigen::ComputeThinU | ComputeThinV);\n\n        matQ = svd.matrixU() * svd.matrixV().transpose();\n\n        //Handle special reflection case\n        if(matQ.determinant() < 0) {\n            matQ(0,2) = matQ(0,2) * -1;\n            matQ(1,2) = matQ(1,2) * -1;\n            matQ(2,2) = matQ(2,2) * -1;\n        }\n\n        // Apply rotation on translated points\n        matBT = matBT * matQ;\n\n        // Calculate GOF\n        dNormf = (matNH.transpose()-matBT.transpose()).norm();\n\n        // Store rotation part to transformation matrix\n        matRot(3,3) = 1;\n        for(int j = 0; j < 3; ++j) {\n            for(int k = 0; k < 3; ++k) {\n                matRot(j,k) = matQ(k,j);\n            }\n        }\n\n        // Store translation part to transformation matrix\n        matTrans(0,3) = dMeanX;\n        matTrans(1,3) = dMeanY;\n        matTrans(2,3) = dMeanZ;\n\n        // Safe rotation and translation to final matrix for next iteration step\n        // This step is safe to do since we change one of the input point sets (matBT)\n        // ToDo: Replace this for loop with a least square solution process\n        matTransFinal = matRot * matTrans * matTransFinal;\n    }\n    return matTransFinal;\n}\n\n//=============================================================================================================\n\nvoid HPIFit::createSensorSet(SensorSet& sensors,\n                             QSharedPointer<FWDLIB::FwdCoilSet> coils)\n{\n    int iNchan = coils->ncoil;\n\n    // init sensor struct\n    int iNp = coils->coils[0]->np;\n    sensors.w = RowVectorXd(iNchan*iNp);\n    sensors.r0 = MatrixXd(iNchan,3);\n    sensors.cosmag = MatrixXd(iNchan*iNp,3);\n    sensors.rmag = MatrixXd(iNchan*iNp,3);\n    sensors.ncoils = iNchan;\n    sensors.tra = MatrixXd::Identity(iNchan,iNchan);\n    sensors.np = iNp;\n\n    for(int i = 0; i < iNchan; i++){\n        FwdCoil* coil = (coils->coils[i]);\n        MatrixXd matRmag = MatrixXd::Zero(iNp,3);\n        MatrixXd matCosmag = MatrixXd::Zero(iNp,3);\n        RowVectorXd vecW(iNp);\n\n        sensors.r0(i,0) = coil->r0[0];\n        sensors.r0(i,1) = coil->r0[1];\n        sensors.r0(i,2) = coil->r0[2];\n\n        for (int p = 0; p < iNp; p++){\n            sensors.w(i*iNp+p) = coil->w[p];\n            for (int c = 0; c < 3; c++) {\n                matRmag(p,c)   = coil->rmag[p][c];\n                matCosmag(p,c) = coil->cosmag[p][c];\n            }\n        }\n\n        sensors.cosmag.block(i*iNp,0,iNp,3) = matCosmag;\n        sensors.rmag.block(i*iNp,0,iNp,3) = matRmag;\n    }\n}\n\n//=============================================================================================================\n\nvoid HPIFit::storeHeadPosition(float fTime,\n                               const Eigen::MatrixXf& transDevHead,\n                               Eigen::MatrixXd& matPosition,\n                               const Eigen::VectorXd& vecGoF,\n                               const QVector<double>& vecError)\n\n{\n    // Write quaternions and vecTime in position matrix. Format is the same like MaxFilter's .pos files.\n    Matrix3f matRot = transDevHead.block(0,0,3,3);\n\n    double dError = std::accumulate(vecError.begin(), vecError.end(), .0) / vecError.size();     // HPI estimation Error\n    Eigen::Quaternionf quatHPI(matRot);\n\n//    qDebug() << \"quatHPI.x() \" << \"quatHPI.y() \" << \"quatHPI.y() \" << \"trans x \" << \"trans y \" << \"trans z \";\n//    qDebug() << quatHPI.x() << quatHPI.y() << quatHPI.z() << transDevHead(0,3) << transDevHead(1,3) << transDevHead(2,3);\n\n    matPosition.conservativeResize(matPosition.rows()+1, 10);\n    matPosition(matPosition.rows()-1,0) = fTime;\n    matPosition(matPosition.rows()-1,1) = quatHPI.x();\n    matPosition(matPosition.rows()-1,2) = quatHPI.y();\n    matPosition(matPosition.rows()-1,3) = quatHPI.z();\n    matPosition(matPosition.rows()-1,4) = transDevHead(0,3);\n    matPosition(matPosition.rows()-1,5) = transDevHead(1,3);\n    matPosition(matPosition.rows()-1,6) = transDevHead(2,3);\n    matPosition(matPosition.rows()-1,7) = vecGoF.mean();\n    matPosition(matPosition.rows()-1,8) = dError;\n    matPosition(matPosition.rows()-1,9) = 0;\n}\n\n//=============================================================================================================\n\nvoid HPIFit::updateSensor()\n{\n    // Create MEG-Coils and read data\n    int iAcc = 2;\n    int iNch = m_lChannels.size();\n\n    if(iNch == 0) {\n        return;\n    }\n\n    FiffCoordTransOld* t = NULL;\n\n    if(m_pCoilTemplate.isNull()) {\n        // read coil_def.dat\n        QString qPath = QString(QCoreApplication::applicationDirPath() + \"/resources/general/coilDefinitions/coil_def.dat\");\n        m_pCoilTemplate = QSharedPointer<FWDLIB::FwdCoilSet>(FwdCoilSet::read_coil_defs(qPath));\n    }\n\n    // create sensor set\n    m_pCoilMeg = QSharedPointer<FWDLIB::FwdCoilSet>(m_pCoilTemplate->create_meg_coils(m_lChannels, iNch, iAcc, t));\n    createSensorSet(m_sensors, m_pCoilMeg);\n}\n\n//=============================================================================================================\n\nvoid HPIFit::updateChannels(QSharedPointer<FIFFLIB::FiffInfo> pFiffInfo)\n{\n    // Get the indices of inner layer channels and exclude bad channels and create channellist\n    int iNumCh = pFiffInfo->nchan;\n\n    for (int i = 0; i < iNumCh; ++i) {\n        if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG ||\n           pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 ||\n           pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 ||\n           pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) {\n            // Check if the sensor is bad, if not append to innerind\n            if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) {\n                m_vecInnerind.append(i);\n                m_lChannels.append(pFiffInfo->chs[i]);\n            }\n        }\n    }\n\n    m_lBads = pFiffInfo->bads;\n}\n\n//=============================================================================================================\n\nvoid HPIFit::updateModel(const int iSamF,\n                         const int iSamLoc,\n                         int iLineF,\n                         const QVector<int>& vecFreqs)\n{\n    int iNumCoils = vecFreqs.size();\n    MatrixXd matSimsig;\n    VectorXd vecTime = VectorXd::LinSpaced(iSamLoc, 0, iSamLoc-1) *1.0/iSamF;\n\n    if(m_bDoFastFit){\n        // Generate simulated data Matrix\n        matSimsig.conservativeResize(iSamLoc,iNumCoils*2);\n\n        for(int i = 0; i < iNumCoils; ++i) {\n            matSimsig.col(i) = sin(2*M_PI*vecFreqs[i]*vecTime.array());\n            matSimsig.col(i+iNumCoils) = cos(2*M_PI*vecFreqs[i]*vecTime.array());\n        }\n        m_matModel = UTILSLIB::MNEMath::pinv(matSimsig);\n        return;\n\n    } else {\n        // add linefreq + harmonics + DC part to model\n        matSimsig.conservativeResize(iSamLoc,iNumCoils*4);\n        for(int i = 0; i < iNumCoils; ++i) {\n            matSimsig.col(i) = sin(2*M_PI*vecFreqs[i]*vecTime.array());\n            matSimsig.col(i+iNumCoils) = cos(2*M_PI*vecFreqs[i]*vecTime.array());\n            matSimsig.col(i+2*iNumCoils) = sin(2*M_PI*iLineF*i*vecTime.array());\n            matSimsig.col(i+3*iNumCoils) = cos(2*M_PI*iLineF*i*vecTime.array());\n        }\n        matSimsig.col(14) = RowVectorXd::LinSpaced(iSamLoc, -0.5, 0.5);\n        matSimsig.col(15).fill(1);\n    }\n    m_matModel = UTILSLIB::MNEMath::pinv(matSimsig);\n\n    // reorder for faster computation\n    MatrixXd matTemp = m_matModel;\n    RowVectorXi vecIndex(2*iNumCoils);\n    vecIndex << 0,4,1,5,2,6,3,7;\n    for(int i = 0; i < vecIndex.size(); ++i) {\n        matTemp.row(i) = m_matModel.row(vecIndex(i));\n    }\n    m_matModel = matTemp;\n}\n", "meta": {"hexsha": "cacfc3837dbf8e31b1a51153dd3e517668bdf562", "size": 27728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/inverse/hpiFit/hpifit.cpp", "max_stars_repo_name": "jobehrens/mne-cpp", "max_stars_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 130.0, "max_stars_repo_stars_event_min_datetime": "2015-02-01T23:47:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T01:46:11.000Z", "max_issues_repo_path": "libraries/inverse/hpiFit/hpifit.cpp", "max_issues_repo_name": "jobehrens/mne-cpp", "max_issues_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 519.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T12:44:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T18:12:52.000Z", "max_forks_repo_path": "libraries/inverse/hpiFit/hpifit.cpp", "max_forks_repo_name": "jobehrens/mne-cpp", "max_forks_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 138.0, "max_forks_repo_forks_event_min_datetime": "2015-04-02T12:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T13:21:25.000Z", "avg_line_length": 39.1638418079, "max_line_length": 139, "alphanum_fraction": 0.5547100404, "num_tokens": 7417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.02675928163314608, "lm_q1q2_score": 0.010498652113753872}}
{"text": "/***\n第三章\t 模板进阶知识\n第一节 万能引用（universal reference / forwarding reference：转发引用）\n（1）类型区别基本含义\n\n（2）universal reference / 万能引用 / 未定义引用基本认识\n结论：万能引用是一种类型。就跟int是一种类型是一个道理。再次强调，万能引用是一种类型。\n右值引用（全称：右值引用类型）是用&&符号表示。右值引用是绑定到右值上。\n万能引用离不开两种语境：\na)必须是函数模板\nb)必须是发生了模板类型推断并且函数模板形参长这样：T&&\n如果实参传递了一个整型左值给形参，tmprv的类型最终会被推断为int &类型。\n如果果实参传递了一个整型右值给形参，tmprv的类型最终会被推断为int &&类型。\n结论：T&&是一个万能引用类型。\n\n题目:\nvoid func(int&& param){...}   //右值引用，因为func不是函数模板而是一个普通函数。\n\ntemplate <typename T>\nvoid func(T && tmpvalue){...} //是万能引用\n\ntemplate <typename T>\nvoid func(std::vector<T>&& param) { ... } //右值引用\n\n什么情形才是万能引用？\n(a)一个是函数模板中用作函数参数的类型推断（参数中要涉及到类型推断），T&&\n(b）auto &&tmpvalue = ..... 也是万能引用，这个后续再谈。\n其他情况的&&，都是右值引用。\n\n（3）万能引用资格的剥夺与辨认\n（3.1）剥夺:const会剥夺 一个引用成为万能引用的资格，被打回原型成右值引用\n（3.2）辨认\n***/\n\n#include <iostream>\n#include <vector>\n\n//#include <boost/type_index.hpp>\nusing namespace std;\n//#pragma warning(disable : 4996) \n\n\nnamespace _nmsp1\n{\t\n\tvoid  func(const int& abc) {}\n\t\n\ttemplate <typename T>\n\tvoid  func(const T& abc) {} //T = int ,abc = const int&\n\n\tvoid myfunc(int&& tmprv)    //参数tmprv是个右值引用类型\n\t{\n\t\tcout << tmprv << endl;\n\t\treturn;\n\t}\n\n\t/*\n\ttemplate <typename T>\n\tvoid myfunc(T&& tmprv) //注意，&&是属于tmprv类型的一部分，不是T类型的一部分（&&和T类型没有关系）\n\t{\n\t\ttmprv = 12;        //不管tmprv的类型是左值引用还是右值引用，都可以给tmprv赋值。因为tmprv本身是个左值。\n\t\tcout << tmprv << endl;\n\t\treturn;\n\t}\n\t*/\n\t\n\t\n\ttemplate <typename T>\n\tvoid func(std::vector<T>&& param) \n\t{ \n\n\t} \n}\n\nnamespace _nmsp2\n{\n\t\n\ttemplate <typename T>\n\tvoid myfunc(T&& tmprv) //注意，&&是属于tmprv类型的一部分，不是T类型的一部分（&&和T类型没有关系）\n\t{\n\t\ttmprv = 12;        //不管tmprv的类型是左值引用还是右值引用，都可以给tmprv赋值。因为tmprv本身是个左值。\n\t\tcout << tmprv << endl;\n\t\treturn;\n\t}\n\t\n}\n\nnamespace _nmsp3\n{\n\ttemplate <typename T>\n\tvoid myfunc(const T&& tmprv)  //有const修饰，万能引用资格被剥夺，因为&&，所以只能是个右值引用\n\t{\t\t\n\t\tcout << tmprv << endl;\n\t\treturn;\n\t}\n\n\ttemplate <typename T>\n\tclass mytestc\n\t{\n\tpublic:\n\t\tvoid testfunc(T&& x) {};   //这个不是万能引用，而是右值引用,因为 testfunc成员函数本身没有涉及到类型推断。\n\n\tpublic:\n\t\ttemplate <typename T2>\n\t\tvoid testfunc2(T2&& x) {}; //x类型是万能引用类型\n\n\t};\n}\n\n\n\nint main()\n{ \n\t/*测试_nmsp1*/\n\t_nmsp1::func(10);\n\tint&& rv = 1000;\n\n\t_nmsp1::myfunc(10); //正确，右值做实参。\n\tint i1 = 100;        //i左值\n\t//_nmsp1::myfunc(i1);  //错，右值 引用不能接（绑）左值。\n\n\tstd::vector<int> aa = { 1 };\n\t_nmsp1::func(std::move(aa));\n\n\tint i2 = 100;\n\t//_nmsp1::myfunc(i2);           //不可以，只能传递右值进去，必须是std::move(i);\n\t_nmsp2::myfunc(std::move(i2));  \n\n\t/*测试_nmsp2*/\n\tint k1 = 100;\n\t_nmsp2::myfunc(k1);             //左值被传递，因此tmprv是个左值引用，也就是int&，最终i值变成12；\n\tprintf(\"i2 = %d\\n\", k1);\n\t\n\tint k2 = 200;\n\t_nmsp2::myfunc(std::move(k2));  //右值被传递，因此tmprv是个右值引用，也就是int&&，最终i值变成12；\n\tprintf(\"k2 = %d\\n\", k2);\n\n    //测试_nmsp3\n\t_nmsp3::mytestc<int> mc;\n\tint j1 = 100;\n\tmc.testfunc(std::move(j1));  //左值不能绑定到右值引用上，必须修改为std::move(i);\n\n\t_nmsp3::mytestc<int> myoc;\n\tint j2 = 10;\n\tmyoc.testfunc2(j2); //int &\n\tmyoc.testfunc2(3);  //int &&\n\n\treturn 0;\n}\n", "meta": {"hexsha": "fa6acac31fb9bd17fb29b5adbcbd363170258d84", "size": 2813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/3/301.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/3/301.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/3/301.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 18.8791946309, "max_line_length": 74, "alphanum_fraction": 0.6516174902, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1403362494900832, "lm_q2_score": 0.07477004084625212, "lm_q1q2_score": 0.010492947106583349}}
{"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\n#include <Eigen/Dense>\n#include <algorithm>\n#include <numeric>\n#include <random>\n\n#include \"open3d/geometry/BoundingVolume.h\"\n#include \"open3d/geometry/KDTreeFlann.h\"\n#include \"open3d/geometry/Qhull.h\"\n#include \"open3d/geometry/TriangleMesh.h\"\n#include \"open3d/utility/Console.h\"\n#include \"open3d/utility/Eigen.h\"\n\nnamespace open3d {\nnamespace geometry {\n\nPointCloud &PointCloud::Clear() {\n    points_.clear();\n    normals_.clear();\n    colors_.clear();\n    return *this;\n}\n\nbool PointCloud::IsEmpty() const { return !HasPoints(); }\n\nEigen::Vector3d PointCloud::GetMinBound() const {\n    return ComputeMinBound(points_);\n}\n\nEigen::Vector3d PointCloud::GetMaxBound() const {\n    return ComputeMaxBound(points_);\n}\n\nEigen::Vector3d PointCloud::GetCenter() const { return ComputeCenter(points_); }\n\nAxisAlignedBoundingBox PointCloud::GetAxisAlignedBoundingBox() const {\n    return AxisAlignedBoundingBox::CreateFromPoints(points_);\n}\n\nOrientedBoundingBox PointCloud::GetOrientedBoundingBox() const {\n    return OrientedBoundingBox::CreateFromPoints(points_);\n}\n\nPointCloud &PointCloud::Transform(const Eigen::Matrix4d &transformation) {\n    TransformPoints(transformation, points_);\n    TransformNormals(transformation, normals_);\n    return *this;\n}\n\nPointCloud &PointCloud::Translate(const Eigen::Vector3d &translation,\n                                  bool relative) {\n    TranslatePoints(translation, points_, relative);\n    return *this;\n}\n\nPointCloud &PointCloud::Scale(const double scale,\n                              const Eigen::Vector3d &center) {\n    ScalePoints(scale, points_, center);\n    return *this;\n}\n\nPointCloud &PointCloud::Rotate(const Eigen::Matrix3d &R,\n                               const Eigen::Vector3d &center) {\n    RotatePoints(R, points_, center);\n    RotateNormals(R, normals_);\n    return *this;\n}\n\nPointCloud &PointCloud::operator+=(const PointCloud &cloud) {\n    // We do not use std::vector::insert to combine std::vector because it will\n    // crash if the pointcloud is added to itself.\n    if (cloud.IsEmpty()) return (*this);\n    size_t old_vert_num = points_.size();\n    size_t add_vert_num = cloud.points_.size();\n    size_t new_vert_num = old_vert_num + add_vert_num;\n    if ((!HasPoints() || HasNormals()) && cloud.HasNormals()) {\n        normals_.resize(new_vert_num);\n        for (size_t i = 0; i < add_vert_num; i++)\n            normals_[old_vert_num + i] = cloud.normals_[i];\n    } else {\n        normals_.clear();\n    }\n    if ((!HasPoints() || HasColors()) && cloud.HasColors()) {\n        colors_.resize(new_vert_num);\n        for (size_t i = 0; i < add_vert_num; i++)\n            colors_[old_vert_num + i] = cloud.colors_[i];\n    } else {\n        colors_.clear();\n    }\n    points_.resize(new_vert_num);\n    for (size_t i = 0; i < add_vert_num; i++)\n        points_[old_vert_num + i] = cloud.points_[i];\n    return (*this);\n}\n\nPointCloud PointCloud::operator+(const PointCloud &cloud) const {\n    return (PointCloud(*this) += cloud);\n}\n\nstd::vector<double> PointCloud::ComputePointCloudDistance(\n        const PointCloud &target) {\n    std::vector<double> distances(points_.size());\n    KDTreeFlann kdtree;\n    kdtree.SetGeometry(target);\n#pragma omp parallel for schedule(static)\n    for (int i = 0; i < (int)points_.size(); i++) {\n        std::vector<int> indices(1);\n        std::vector<double> dists(1);\n        if (kdtree.SearchKNN(points_[i], 1, indices, dists) == 0) {\n            utility::LogDebug(\n                    \"[ComputePointCloudToPointCloudDistance] Found a point \"\n                    \"without neighbors.\");\n            distances[i] = 0.0;\n        } else {\n            distances[i] = std::sqrt(dists[0]);\n        }\n    }\n    return distances;\n}\n\nPointCloud &PointCloud::RemoveNonFinitePoints(bool remove_nan,\n                                              bool remove_infinite) {\n    bool has_normal = HasNormals();\n    bool has_color = HasColors();\n    size_t old_point_num = points_.size();\n    size_t k = 0;                                 // new index\n    for (size_t i = 0; i < old_point_num; i++) {  // old index\n        bool is_nan = remove_nan &&\n                      (std::isnan(points_[i](0)) || std::isnan(points_[i](1)) ||\n                       std::isnan(points_[i](2)));\n        bool is_infinite = remove_infinite && (std::isinf(points_[i](0)) ||\n                                               std::isinf(points_[i](1)) ||\n                                               std::isinf(points_[i](2)));\n        if (!is_nan && !is_infinite) {\n            points_[k] = points_[i];\n            if (has_normal) normals_[k] = normals_[i];\n            if (has_color) colors_[k] = colors_[i];\n            k++;\n        }\n    }\n    points_.resize(k);\n    if (has_normal) normals_.resize(k);\n    if (has_color) colors_.resize(k);\n    utility::LogDebug(\n            \"[RemoveNonFinitePoints] {:d} nan points have been removed.\",\n            (int)(old_point_num - k));\n    return *this;\n}\n\nstd::shared_ptr<PointCloud> PointCloud::SelectByIndex(\n        const std::vector<size_t> &indices, bool invert /* = false */) const {\n    auto output = std::make_shared<PointCloud>();\n    bool has_normals = HasNormals();\n    bool has_colors = HasColors();\n\n    std::vector<bool> mask = std::vector<bool>(points_.size(), invert);\n    for (size_t i : indices) {\n        mask[i] = !invert;\n    }\n\n    for (size_t i = 0; i < points_.size(); i++) {\n        if (mask[i]) {\n            output->points_.push_back(points_[i]);\n            if (has_normals) output->normals_.push_back(normals_[i]);\n            if (has_colors) output->colors_.push_back(colors_[i]);\n        }\n    }\n    utility::LogDebug(\n            \"Pointcloud down sampled from {:d} points to {:d} points.\",\n            (int)points_.size(), (int)output->points_.size());\n    return output;\n}\n\n// helper classes for VoxelDownSample and VoxelDownSampleAndTrace\nnamespace {\nclass AccumulatedPoint {\npublic:\n    AccumulatedPoint()\n        : num_of_points_(0),\n          point_(0.0, 0.0, 0.0),\n          normal_(0.0, 0.0, 0.0),\n          color_(0.0, 0.0, 0.0) {}\n\npublic:\n    void AddPoint(const PointCloud &cloud, int index) {\n        point_ += cloud.points_[index];\n        if (cloud.HasNormals()) {\n            if (!std::isnan(cloud.normals_[index](0)) &&\n                !std::isnan(cloud.normals_[index](1)) &&\n                !std::isnan(cloud.normals_[index](2))) {\n                normal_ += cloud.normals_[index];\n            }\n        }\n        if (cloud.HasColors()) {\n            color_ += cloud.colors_[index];\n        }\n        num_of_points_++;\n    }\n\n    Eigen::Vector3d GetAveragePoint() const {\n        return point_ / double(num_of_points_);\n    }\n\n    Eigen::Vector3d GetAverageNormal() const {\n        // Call NormalizeNormals() afterwards if necessary\n        return normal_ / double(num_of_points_);\n    }\n\n    Eigen::Vector3d GetAverageColor() const {\n        return color_ / double(num_of_points_);\n    }\n\npublic:\n    int num_of_points_;\n    Eigen::Vector3d point_;\n    Eigen::Vector3d normal_;\n    Eigen::Vector3d color_;\n};\n\nclass point_cubic_id {\npublic:\n    size_t point_id;\n    int cubic_id;\n};\n\nclass AccumulatedPointForTrace : public AccumulatedPoint {\npublic:\n    void AddPoint(const PointCloud &cloud,\n                  size_t index,\n                  int cubic_index,\n                  bool approximate_class) {\n        point_ += cloud.points_[index];\n        if (cloud.HasNormals()) {\n            if (!std::isnan(cloud.normals_[index](0)) &&\n                !std::isnan(cloud.normals_[index](1)) &&\n                !std::isnan(cloud.normals_[index](2))) {\n                normal_ += cloud.normals_[index];\n            }\n        }\n        if (cloud.HasColors()) {\n            if (approximate_class) {\n                auto got = classes.find(int(cloud.colors_[index][0]));\n                if (got == classes.end())\n                    classes[int(cloud.colors_[index][0])] = 1;\n                else\n                    classes[int(cloud.colors_[index][0])] += 1;\n            } else {\n                color_ += cloud.colors_[index];\n            }\n        }\n        point_cubic_id new_id;\n        new_id.point_id = index;\n        new_id.cubic_id = cubic_index;\n        original_id.push_back(new_id);\n        num_of_points_++;\n    }\n\n    Eigen::Vector3d GetMaxClass() {\n        int max_class = -1;\n        int max_count = -1;\n        for (auto it = classes.begin(); it != classes.end(); it++) {\n            if (it->second > max_count) {\n                max_count = it->second;\n                max_class = it->first;\n            }\n        }\n        return Eigen::Vector3d(max_class, max_class, max_class);\n    }\n\n    std::vector<point_cubic_id> GetOriginalID() { return original_id; }\n\nprivate:\n    // original point cloud id in higher resolution + its cubic id\n    std::vector<point_cubic_id> original_id;\n    std::unordered_map<int, int> classes;\n};\n}  // namespace\n\nstd::shared_ptr<PointCloud> PointCloud::VoxelDownSample(\n        double voxel_size) const {\n    auto output = std::make_shared<PointCloud>();\n    if (voxel_size <= 0.0) {\n        utility::LogError(\"[VoxelDownSample] voxel_size <= 0.\");\n    }\n    Eigen::Vector3d voxel_size3 =\n            Eigen::Vector3d(voxel_size, voxel_size, voxel_size);\n    Eigen::Vector3d voxel_min_bound = GetMinBound() - voxel_size3 * 0.5;\n    Eigen::Vector3d voxel_max_bound = GetMaxBound() + voxel_size3 * 0.5;\n    if (voxel_size * std::numeric_limits<int>::max() <\n        (voxel_max_bound - voxel_min_bound).maxCoeff()) {\n        utility::LogError(\"[VoxelDownSample] voxel_size is too small.\");\n    }\n    std::unordered_map<Eigen::Vector3i, AccumulatedPoint,\n                       utility::hash_eigen<Eigen::Vector3i>>\n            voxelindex_to_accpoint;\n\n    Eigen::Vector3d ref_coord;\n    Eigen::Vector3i voxel_index;\n    for (int i = 0; i < (int)points_.size(); i++) {\n        ref_coord = (points_[i] - voxel_min_bound) / voxel_size;\n        voxel_index << int(floor(ref_coord(0))), int(floor(ref_coord(1))),\n                int(floor(ref_coord(2)));\n        voxelindex_to_accpoint[voxel_index].AddPoint(*this, i);\n    }\n    bool has_normals = HasNormals();\n    bool has_colors = HasColors();\n    for (auto accpoint : voxelindex_to_accpoint) {\n        output->points_.push_back(accpoint.second.GetAveragePoint());\n        if (has_normals) {\n            output->normals_.push_back(accpoint.second.GetAverageNormal());\n        }\n        if (has_colors) {\n            output->colors_.push_back(accpoint.second.GetAverageColor());\n        }\n    }\n    utility::LogDebug(\n            \"Pointcloud down sampled from {:d} points to {:d} points.\",\n            (int)points_.size(), (int)output->points_.size());\n    return output;\n}\n\nstd::tuple<std::shared_ptr<PointCloud>,\n           Eigen::MatrixXi,\n           std::vector<std::vector<int>>>\nPointCloud::VoxelDownSampleAndTrace(double voxel_size,\n                                    const Eigen::Vector3d &min_bound,\n                                    const Eigen::Vector3d &max_bound,\n                                    bool approximate_class) const {\n    auto output = std::make_shared<PointCloud>();\n    Eigen::MatrixXi cubic_id;\n    if (voxel_size <= 0.0) {\n        utility::LogError(\"[VoxelDownSample] voxel_size <= 0.\");\n    }\n    // Note: this is different from VoxelDownSample.\n    // It is for fixing coordinate for multiscale voxel space\n    auto voxel_min_bound = min_bound;\n    auto voxel_max_bound = max_bound;\n    if (voxel_size * std::numeric_limits<int>::max() <\n        (voxel_max_bound - voxel_min_bound).maxCoeff()) {\n        utility::LogError(\"[VoxelDownSample] voxel_size is too small.\");\n    }\n    std::unordered_map<Eigen::Vector3i, AccumulatedPointForTrace,\n                       utility::hash_eigen<Eigen::Vector3i>>\n            voxelindex_to_accpoint;\n    int cid_temp[3] = {1, 2, 4};\n    for (size_t i = 0; i < points_.size(); i++) {\n        auto ref_coord = (points_[i] - voxel_min_bound) / voxel_size;\n        auto voxel_index = Eigen::Vector3i(int(floor(ref_coord(0))),\n                                           int(floor(ref_coord(1))),\n                                           int(floor(ref_coord(2))));\n        int cid = 0;\n        for (int c = 0; c < 3; c++) {\n            if ((ref_coord(c) - voxel_index(c)) >= 0.5) {\n                cid += cid_temp[c];\n            }\n        }\n        voxelindex_to_accpoint[voxel_index].AddPoint(*this, i, cid,\n                                                     approximate_class);\n    }\n    bool has_normals = HasNormals();\n    bool has_colors = HasColors();\n    int cnt = 0;\n    cubic_id.resize(voxelindex_to_accpoint.size(), 8);\n    cubic_id.setConstant(-1);\n    std::vector<std::vector<int>> original_indices(\n            voxelindex_to_accpoint.size());\n    for (auto accpoint : voxelindex_to_accpoint) {\n        output->points_.push_back(accpoint.second.GetAveragePoint());\n        if (has_normals) {\n            output->normals_.push_back(accpoint.second.GetAverageNormal());\n        }\n        if (has_colors) {\n            if (approximate_class) {\n                output->colors_.push_back(accpoint.second.GetMaxClass());\n            } else {\n                output->colors_.push_back(accpoint.second.GetAverageColor());\n            }\n        }\n        auto original_id = accpoint.second.GetOriginalID();\n        for (int i = 0; i < (int)original_id.size(); i++) {\n            size_t pid = original_id[i].point_id;\n            int cid = original_id[i].cubic_id;\n            cubic_id(cnt, cid) = int(pid);\n            original_indices[cnt].push_back(int(pid));\n        }\n        cnt++;\n    }\n    utility::LogDebug(\n            \"Pointcloud down sampled from {:d} points to {:d} points.\",\n            (int)points_.size(), (int)output->points_.size());\n    return std::make_tuple(output, cubic_id, original_indices);\n}\n\nstd::shared_ptr<PointCloud> PointCloud::UniformDownSample(\n        size_t every_k_points) const {\n    if (every_k_points == 0) {\n        utility::LogError(\"[UniformDownSample] Illegal sample rate.\");\n    }\n    std::vector<size_t> indices;\n    for (size_t i = 0; i < points_.size(); i += every_k_points) {\n        indices.push_back(i);\n    }\n    return SelectByIndex(indices);\n}\n\nstd::shared_ptr<PointCloud> PointCloud::RandomDownSample(\n        double sampling_ratio) const {\n    if (sampling_ratio < 0 || sampling_ratio > 1) {\n        utility::LogError(\n                \"[RandomDownSample] Illegal sampling_ratio {}, sampling_ratio \"\n                \"must be between 0 and 1.\");\n    }\n    std::vector<size_t> indices(points_.size());\n    std::iota(std::begin(indices), std::end(indices), (size_t)0);\n    std::random_device rd;\n    std::mt19937 prng(rd());\n    std::shuffle(indices.begin(), indices.end(), prng);\n    indices.resize((int)(sampling_ratio * points_.size()));\n    return SelectByIndex(indices);\n}\n\nstd::shared_ptr<PointCloud> PointCloud::Crop(\n        const AxisAlignedBoundingBox &bbox) const {\n    if (bbox.IsEmpty()) {\n        utility::LogError(\n                \"[CropPointCloud] AxisAlignedBoundingBox either has zeros \"\n                \"size, or has wrong bounds.\");\n    }\n    return SelectByIndex(bbox.GetPointIndicesWithinBoundingBox(points_));\n}\nstd::shared_ptr<PointCloud> PointCloud::Crop(\n        const OrientedBoundingBox &bbox) const {\n    if (bbox.IsEmpty()) {\n        utility::LogError(\n                \"[CropPointCloud] AxisAlignedBoundingBox either has zeros \"\n                \"size, or has wrong bounds.\");\n    }\n    return SelectByIndex(bbox.GetPointIndicesWithinBoundingBox(points_));\n}\n\nstd::shared_ptr<PointCloud> PointCloud::CropConvexHull(\n        const BoundingConvexHull &bhull, bool invert) const {\n    Eigen::Vector3d p1;\n    Eigen::Vector3d p2;\n    Eigen::Vector3d p3;\n    Eigen::Vector3d normal;\n    Eigen::Vector3d center = bhull.GetCenter();\n    Eigen::Vector3i triangle;\n    double ccw;\n    double cosine;\n\n    std::vector<size_t> out_index;\n\n    for (size_t k = 0; k < points_.size(); k++) {\n        const auto &point = points_[k];\n        bool valid = true;\n        for (size_t j = 0; j < bhull.convex_hull_->triangles_.size(); j++) {\n            triangle = bhull.convex_hull_->triangles_[j];\n            p1 = bhull.convex_hull_->vertices_[triangle(0)];\n            p2 = bhull.convex_hull_->vertices_[triangle(1)];\n            p3 = bhull.convex_hull_->vertices_[triangle(2)];\n            normal = bhull.convex_hull_->triangle_normals_[j];\n            ccw = (p1 - center).dot(normal);\n            if (ccw < 0) {\n                normal = -normal;\n            }\n            cosine = (p1 - point).dot(normal);\n            if (cosine < 0) {\n                valid = false;\n                break;\n            }\n        }\n        if (valid) {\n            out_index.push_back(k);\n        }\n    }\n\n    return SelectByIndex(out_index, invert);\n}\n\nstd::tuple<std::shared_ptr<PointCloud>, std::vector<size_t>>\nPointCloud::RemoveRadiusOutliers(size_t nb_points, double search_radius) const {\n    if (nb_points < 1 || search_radius <= 0) {\n        utility::LogError(\n                \"[RemoveRadiusOutliers] Illegal input parameters,\"\n                \"number of points and radius must be positive\");\n    }\n    KDTreeFlann kdtree;\n    kdtree.SetGeometry(*this);\n    std::vector<bool> mask = std::vector<bool>(points_.size());\n#pragma omp parallel for schedule(static)\n    for (int i = 0; i < int(points_.size()); i++) {\n        std::vector<int> tmp_indices;\n        std::vector<double> dist;\n        size_t nb_neighbors = kdtree.SearchRadius(points_[i], search_radius,\n                                                  tmp_indices, dist);\n        mask[i] = (nb_neighbors > nb_points);\n    }\n    std::vector<size_t> indices;\n    for (size_t i = 0; i < mask.size(); i++) {\n        if (mask[i]) {\n            indices.push_back(i);\n        }\n    }\n    return std::make_tuple(SelectByIndex(indices), indices);\n}\n\nstd::tuple<std::shared_ptr<PointCloud>, std::vector<size_t>>\nPointCloud::RemoveStatisticalOutliers(size_t nb_neighbors,\n                                      double std_ratio) const {\n    if (nb_neighbors < 1 || std_ratio <= 0) {\n        utility::LogError(\n                \"[RemoveStatisticalOutliers] Illegal input parameters, number \"\n                \"of neighbors and standard deviation ratio must be positive\");\n    }\n    if (points_.size() == 0) {\n        return std::make_tuple(std::make_shared<PointCloud>(),\n                               std::vector<size_t>());\n    }\n    KDTreeFlann kdtree;\n    kdtree.SetGeometry(*this);\n    std::vector<double> avg_distances = std::vector<double>(points_.size());\n    std::vector<size_t> indices;\n    size_t valid_distances = 0;\n\n#pragma omp parallel for schedule(static)\n    for (int i = 0; i < int(points_.size()); i++) {\n        std::vector<int> tmp_indices;\n        std::vector<double> dist;\n        kdtree.SearchKNN(points_[i], int(nb_neighbors), tmp_indices, dist);\n        double mean = -1.0;\n        if (dist.size() > 0u) {\n            valid_distances++;\n            std::for_each(dist.begin(), dist.end(),\n                          [](double &d) { d = std::sqrt(d); });\n            mean = std::accumulate(dist.begin(), dist.end(), 0.0) / dist.size();\n        }\n        avg_distances[i] = mean;\n    }\n    if (valid_distances == 0) {\n        return std::make_tuple(std::make_shared<PointCloud>(),\n                               std::vector<size_t>());\n    }\n    double cloud_mean = std::accumulate(\n            avg_distances.begin(), avg_distances.end(), 0.0,\n            [](double const &x, double const &y) { return y > 0 ? x + y : x; });\n    cloud_mean /= valid_distances;\n    double sq_sum = std::inner_product(\n            avg_distances.begin(), avg_distances.end(), avg_distances.begin(),\n            0.0, [](double const &x, double const &y) { return x + y; },\n            [cloud_mean](double const &x, double const &y) {\n                return x > 0 ? (x - cloud_mean) * (y - cloud_mean) : 0;\n            });\n    // Bessel's correction\n    double std_dev = std::sqrt(sq_sum / (valid_distances - 1));\n    double distance_threshold = cloud_mean + std_ratio * std_dev;\n    for (size_t i = 0; i < avg_distances.size(); i++) {\n        if (avg_distances[i] > 0 && avg_distances[i] < distance_threshold) {\n            indices.push_back(i);\n        }\n    }\n    return std::make_tuple(SelectByIndex(indices), indices);\n}\n\nstd::tuple<Eigen::Vector3d, Eigen::Matrix3d>\nPointCloud::ComputeMeanAndCovariance() const {\n    if (IsEmpty()) {\n        return std::make_tuple(Eigen::Vector3d::Zero(),\n                               Eigen::Matrix3d::Identity());\n    }\n    std::vector<size_t> all_idx(points_.size());\n    std::iota(all_idx.begin(), all_idx.end(), 0);\n    return utility::ComputeMeanAndCovariance(points_, all_idx);\n}\n\nstd::vector<double> PointCloud::ComputeMahalanobisDistance() const {\n    std::vector<double> mahalanobis(points_.size());\n    Eigen::Vector3d mean;\n    Eigen::Matrix3d covariance;\n    std::tie(mean, covariance) = ComputeMeanAndCovariance();\n    Eigen::Matrix3d cov_inv = covariance.inverse();\n#pragma omp parallel for schedule(static)\n    for (int i = 0; i < (int)points_.size(); i++) {\n        Eigen::Vector3d p = points_[i] - mean;\n        mahalanobis[i] = std::sqrt(p.transpose() * cov_inv * p);\n    }\n    return mahalanobis;\n}\n\nstd::vector<double> PointCloud::ComputeNearestNeighborDistance() const {\n    if (points_.size() < 2) {\n        return std::vector<double>(points_.size(), 0);\n    }\n\n    std::vector<double> nn_dis(points_.size());\n    KDTreeFlann kdtree(*this);\n#pragma omp parallel for schedule(static)\n    for (int i = 0; i < (int)points_.size(); i++) {\n        std::vector<int> indices(2);\n        std::vector<double> dists(2);\n        if (kdtree.SearchKNN(points_[i], 2, indices, dists) <= 1) {\n            utility::LogDebug(\n                    \"[ComputePointCloudNearestNeighborDistance] Found a point \"\n                    \"without neighbors.\");\n            nn_dis[i] = 0.0;\n        } else {\n            nn_dis[i] = std::sqrt(dists[1]);\n        }\n    }\n    return nn_dis;\n}\n\nstd::tuple<std::shared_ptr<TriangleMesh>, std::vector<size_t>>\nPointCloud::ComputeConvexHull() const {\n    return Qhull::ComputeConvexHull(points_);\n}\n\nstd::tuple<std::shared_ptr<TriangleMesh>, std::vector<size_t>>\nPointCloud::HiddenPointRemoval(const Eigen::Vector3d &camera_location,\n                               const double radius) const {\n    if (radius <= 0) {\n        utility::LogError(\n                \"[HiddenPointRemoval] radius must be larger than zero.\");\n    }\n\n    // perform spherical projection\n    std::vector<Eigen::Vector3d> spherical_projection;\n    for (size_t pidx = 0; pidx < points_.size(); ++pidx) {\n        Eigen::Vector3d projected_point = points_[pidx] - camera_location;\n        double norm = projected_point.norm();\n        spherical_projection.push_back(\n                projected_point + 2 * (radius - norm) * projected_point / norm);\n    }\n\n    // add origin\n    size_t origin_pidx = spherical_projection.size();\n    spherical_projection.push_back(Eigen::Vector3d(0, 0, 0));\n\n    // calculate convex hull of spherical projection\n    std::shared_ptr<TriangleMesh> visible_mesh;\n    std::vector<size_t> pt_map;\n    std::tie(visible_mesh, pt_map) =\n            Qhull::ComputeConvexHull(spherical_projection);\n\n    // reassign original points to mesh\n    size_t origin_vidx = pt_map.size();\n    for (size_t vidx = 0; vidx < pt_map.size(); vidx++) {\n        size_t pidx = pt_map[vidx];\n        if (pidx != origin_pidx) {\n            visible_mesh->vertices_[vidx] = points_[pidx];\n        } else {\n            origin_vidx = vidx;\n            visible_mesh->vertices_[vidx] = camera_location;\n        }\n    }\n\n    // erase origin if part of mesh\n    if (origin_vidx < visible_mesh->vertices_.size()) {\n        visible_mesh->vertices_.erase(visible_mesh->vertices_.begin() +\n                                      origin_vidx);\n        pt_map.erase(pt_map.begin() + origin_vidx);\n        for (size_t tidx = visible_mesh->triangles_.size(); tidx-- > 0;) {\n            if (visible_mesh->triangles_[tidx](0) == (int)origin_vidx ||\n                visible_mesh->triangles_[tidx](1) == (int)origin_vidx ||\n                visible_mesh->triangles_[tidx](2) == (int)origin_vidx) {\n                visible_mesh->triangles_.erase(\n                        visible_mesh->triangles_.begin() + tidx);\n            } else {\n                if (visible_mesh->triangles_[tidx](0) > (int)origin_vidx)\n                    visible_mesh->triangles_[tidx](0) -= 1;\n                if (visible_mesh->triangles_[tidx](1) > (int)origin_vidx)\n                    visible_mesh->triangles_[tidx](1) -= 1;\n                if (visible_mesh->triangles_[tidx](2) > (int)origin_vidx)\n                    visible_mesh->triangles_[tidx](2) -= 1;\n            }\n        }\n    }\n    return std::make_tuple(visible_mesh, pt_map);\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "c8d610b3e7327bac4e7084363b29d0b41a2ed7b7", "size": 26411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/geometry/PointCloud.cpp", "max_stars_repo_name": "gliese581gg/Open3D", "max_stars_repo_head_hexsha": "06fb206dda9f3853be3f9b16d03c06d623b193ee", "max_stars_repo_licenses": ["MIT"], "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/PointCloud.cpp", "max_issues_repo_name": "gliese581gg/Open3D", "max_issues_repo_head_hexsha": "06fb206dda9f3853be3f9b16d03c06d623b193ee", "max_issues_repo_licenses": ["MIT"], "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/PointCloud.cpp", "max_forks_repo_name": "gliese581gg/Open3D", "max_forks_repo_head_hexsha": "06fb206dda9f3853be3f9b16d03c06d623b193ee", "max_forks_repo_licenses": ["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.1985915493, "max_line_length": 80, "alphanum_fraction": 0.5908901594, "num_tokens": 6402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478897, "lm_q2_score": 0.029760092332479712, "lm_q1q2_score": 0.010481557553409094}}
{"text": " /**\n  * The MIT License (MIT)\n  *\n  * Copyright (c) 2014 Behrouz Babaki, Tias Guns, Siegfried Nijssen\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 <scip/scip.h> \n#include <scip/scipdefplugins.h>\n#include <cstring>\n#include <cstdlib>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <utility>\n#include <boost/concept_check.hpp>\n#include <sys/types.h>\n#include <dirent.h>\n\n#include \"init.h\"\n#include \"cons_mlcl.h\"\n#include \"pricer_optclust.h\" // for print_cluster()\nusing namespace std;\n\n/** public-like **/\n\nSCIP_RETCODE initialize_solution(const char* fileName, SCIP* scip,\n                                 const vector<vector<double> > & distances,\n                                 vector<SCIP_CONS*> setcover_con, SCIP_CONS* side_con,\n                                 vector<pair<unsigned int, unsigned int> > mlVec, \n\t\t\t\t vector<pair<unsigned int, unsigned int> > clVec,\n\t\t\t\t vector<double>& upper,\n\t\t\t\t vector<double>& lower\n                                ) {\n  vector<vector<bool> > clusters;\n  vector<double> costs;\n\n  extract_clusters(fileName, distances, clusters, costs, upper, lower);\n\n  assert (clusters.size() == costs.size());\n  int size = costs.size();\n\n  for (int counter = 0; counter < size; counter++) {\n    if ( cluster_satisfies_mlcl(clusters[counter], mlVec, clVec) ) {\n      SCIP_CALL( add_cluster_variable(scip, distances, setcover_con, side_con, clusters[counter],  costs[counter]) );\n    }\n    else \n      cout << \"cluster \" << counter << \" does not satisfy the constraints.\" << endl;\n  }\n  \n  return SCIP_OKAY;\n}\n\nSCIP_RETCODE init_sol_dir(const char* dirName, SCIP* scip,\n\t\t\t  const vector<vector<double> > & distances,\n\t\t\t  vector<SCIP_CONS*> setcover_con, SCIP_CONS* side_con,\n\t\t\t  vector<pair<unsigned int, unsigned int> > mlVec, \n\t\t\t  vector<pair<unsigned int, unsigned int> > clVec,\n\t\t\t  vector<double>& upper,\n\t\t\t  vector<double>& lower\n\t\t\t  ){\n  \n  priority_queue<struct initClustering, vector<struct initClustering>, compQ> clusteringQ;\n  DIR * dir = opendir (dirName);\n  struct dirent * entries;\n\n  upper.clear();\n  lower.clear();\n\n  while ((entries = readdir(dir)) != NULL)\n    if (entries->d_type == 8){\n      bool success = false;\n      struct initClustering currClustering;\n      vector<vector<bool> > clusters;\n      vector<double> costs;\n\n      vector<double> upper_bounds;\n      vector<double> lower_bounds;\n\n      char fileName [255];\n      strcpy(fileName, dirName);\n      strcat(fileName, \"/\");\n      strcat(fileName, entries->d_name);\n      success = extract_clusters(fileName, distances, clusters, costs, upper_bounds, lower_bounds);\n\n      if (success){\n\tcurrClustering.totalCost = 0;\n\tcurrClustering.satCount = 0;\n\tfor (int counter = 0, clusteringSize = clusters.size(); counter < clusteringSize; counter++)\n\t  if (cluster_satisfies_mlcl(clusters[counter], mlVec, clVec)){\n\t    currClustering.clusters.push_back(clusters[counter]);\n\t    currClustering.costs.push_back(costs[counter]);\n\t    currClustering.totalCost += costs[counter];\n\t    (currClustering.satCount)++;\n\t  }\n\tcurrClustering.upper_bounds = upper_bounds;\n\tcurrClustering.lower_bounds = lower_bounds;\n\tclusteringQ.push(currClustering);\n      }\n\n    }\n  closedir(dir);\n\n  if (!clusteringQ.empty()){\n    vector<vector<bool> > bestClusters = (clusteringQ.top()).clusters;\n    vector<double> bClusterCosts = (clusteringQ.top()).costs;\n    upper = (clusteringQ.top()).upper_bounds;\n    lower = (clusteringQ.top()).lower_bounds;\n    for (int counter = 0, clusteringSize = bestClusters.size(); counter < clusteringSize; counter++)\n      SCIP_CALL( add_cluster_variable(scip, distances, setcover_con, side_con, bestClusters[counter],  bClusterCosts[counter]) );\n  }\n \n  return SCIP_OKAY;\n\n}\n\n\nSCIP_RETCODE init_MlCl_constraints(const char* consFile, SCIP* scip, vector<pair<unsigned int, unsigned int> >& mlVec, vector<pair<unsigned int, unsigned int> >& clVec){\n\n   extract_constraints(consFile, mlVec, clVec);\n          \n   char con_name[255];\n\n   for (auto itr = mlVec.begin(); itr!= mlVec.end(); itr++){\n    SCIP_CONS* consML;\n    SCIPsnprintf(con_name, 255, \"ML-%i-%i\", itr->first, itr->second);\n    SCIP_CALL( SCIPcreateConsML(scip, &consML, con_name,\n                  itr->first,                       /* the first data point to be linked */\n                  itr->second                       /* the second data point to be linked */\n                  ) );\n    SCIP_CALL( SCIPaddCons(scip, consML) );\n   }\n\n   for (auto itr = clVec.begin(); itr!= clVec.end(); itr++){\n    SCIP_CONS* consCL;\n    SCIPsnprintf(con_name, 255, \"CL-%i-%i\", itr->first, itr->second);\n    SCIP_CALL( SCIPcreateConsCL(scip, &consCL, con_name,\n                  itr->first,                       /* the first data point to be linked */\n                  itr->second                       /* the second data point to be linked */\n                  ) );\n\n    SCIP_CALL( SCIPaddCons(scip, consCL) );\n   }\n   return SCIP_OKAY;\n}\n\n/** private-like **/\n\nbool extract_clusters(const char* fileName, const vector<vector<double> >& distances, vector<vector<bool> >& clusters, vector<double>& costs, vector<double>& upper, vector<double>& lower){ \n\n  clusters.clear();\n  ifstream inputFile (fileName, ios::in);\n\n  if (inputFile.fail()) {\n    cerr << \"Error! Can't open cluster file '\" << fileName << \"', quitting...\\n\";\n    return false;\n  }\n  \n  int number_of_elements = distances.size();\n  \n  int line = -1;\n  string s;\n  while(getline(inputFile,s)) {\n    if (!s.empty()) {\n      line += 1;\n      int clusIndex = atoi(s.c_str());\n      \n      if (clusIndex < 0) {\n          cerr << \"Error reading '\" << fileName << \"', found negative cluster index '\" << clusIndex << \"'\\n\";\n\t  return false;\n      }\n      \n      if (clusIndex > (int)clusters.size()-1) {\n          // a new cluster index\n          // create empty clusters upto the index+1 (to compensate offset 0)\n          clusters.resize(clusIndex+1, vector<bool>(number_of_elements, false));\n      }\n    \n      clusters[clusIndex][line] = true;\n    }\n  }\n  int number_of_clusters = clusters.size();\n\n  #ifndef NDEBUG\n  for (int counter = 0; counter < number_of_clusters; counter++)\n    assert (clusters[counter].size() == (unsigned)number_of_elements);\n  #endif\n\n  /* computing costs of clusters*/\n  costs.clear();\n  for (int counter = 0; counter < number_of_clusters; counter++)\n    costs.push_back(ObjPricerOptClust::getClusterCost(distances, clusters[counter]));\n\n  /* print the sum of all cluster costs (cost of the whole clustering) */\n  double clusteringCost = 0;\n  for (auto itr = costs.begin(), itrEnd = costs.end(); itr != itrEnd; itr++)\n    clusteringCost += *itr;\n  cout << \"\\ncost of the initial clustering: \" << setprecision(15) << clusteringCost << endl;\n\n  /* compute an estimate for first coefficients */\n  getFirstCoefs (distances, clusters, costs, upper, lower);\n\nreturn true;\n\n}\n\nSCIP_RETCODE add_cluster_variable(\n\t\t\t\t  \n   SCIP*                 scip,\n   const vector<vector<double> >& distances,\n   vector<SCIP_CONS*> setcover_con,\n   SCIP_CONS* side_con,\n   const vector<bool>&      cluster,\n   double cluster_cost\n   )\n{\n   char var_name[255];\n   SCIPsnprintf(var_name, 255, \"X_%d\", SCIPgetNVars(scip));\n   SCIPdebugMessage(\"new variable <%s>\\n\", var_name);\n\n   /* create the new variable */\n\n   SCIP_VAR* var;\n   SCIP_CALL( SCIPcreateVar(scip, &var, var_name,\n                            0.0,                     // lower bound\n                            1.0,      // upper bound\n                            cluster_cost,                       // objective\n                            SCIP_VARTYPE_BINARY, // variable type\n                            false, false, 0, 0, 0, 0, 0) );\n\n   /* add new variable to the list of variables to price into LP */\n   SCIP_CALL( SCIPaddVar(scip, var) );\n\n   /* add the coefficients of this variable to setcovering and side constraints */\n   for (unsigned i= 0; i < cluster.size(); ++i)\n      if (cluster[i])\n         SCIP_CALL( SCIPaddCoefLinear(scip, setcover_con[i], var, 1.0) );         \n\n   SCIP_CALL( SCIPaddCoefLinear(scip, side_con, var, 1.0 ) );\n\n   // /* cleanup */\n   // SCIP_CALL( SCIPreleaseVar(scip, &var) );\n\n   return SCIP_OKAY;\n}\n\nvoid extract_constraints(const char* fileName, vector<pair<unsigned int, unsigned int> >& mlVec, vector<pair< unsigned int, unsigned int> >& clVec){\n   mlVec.clear();\n   clVec.clear();\n   ifstream inputFile (fileName, ios::in);\n\n  if (inputFile.fail()) {\n    cerr << \"Error! Can't open constraint file '\" << fileName << \"', quitting...\\n\";\n    exit(-1);\n  }\n\n  string line;\n  while(getline(inputFile, line)){\n     istringstream ss(line);\n     unsigned int first, second;\n     int consType;\n     ss >> first >> second >> consType;\n     if (!ss.fail()){\n        pair<unsigned int, unsigned int> p = \n           make_pair(first, second);\n        if (consType == 1)\n           mlVec.push_back(p);\n        else if (consType == -1)\n           clVec.push_back(p);\n     }\n  }\n}\n\nbool cluster_satisfies_mlcl(std::vector< bool > cluster, vector< std::pair< unsigned int, unsigned int > > mlVec, vector< std::pair< unsigned int, unsigned int > > clVec)\n{\n    // check ML violation\n    for (unsigned i=0; i!=mlVec.size(); i++) {\n        unsigned first = mlVec[i].first;\n        unsigned second = mlVec[i].second;\n        if ( ( cluster[first] == true && cluster[second] == false )\n           ||( cluster[first] == false && cluster[second] == true ) )\n            return false;\n    }\n    // check CL violation\n    for (unsigned i=0; i!=clVec.size(); i++) {\n        if ( cluster[clVec[i].first] == true && cluster[clVec[i].second] == true )\n            return false;\n    }\n    return true;\n}\n\nvoid getFirstCoefs (const vector<vector<double> >& distances, const vector<vector<bool> >& clusters, const vector<double>& costs, vector<double>& upper, vector<double>& lower){\n\n  unsigned int num_instances = distances.size();\n  unsigned int num_clusetrs = clusters.size();\n  vector<int> cluster_sizes (num_clusetrs , -1);\n  vector<int> assignments (num_instances, -1);\n\n  upper.clear();\n  upper.resize(num_instances);\n  lower.clear();\n  lower.resize(num_instances);\n\n  for (size_t i = 0; i < num_clusetrs; i++){\n    unsigned int clusterSize = 0;\n    for (size_t j = 0; j < num_instances; j++)\n      if (clusters[i][j]){\n\tassignments[j] = i;\n\tclusterSize++;\n      }\n\n    cluster_sizes[i] = clusterSize;\n  }\n\n  #ifndef NDEBUG\n  for (auto itr = assignments.begin(), iend = assignments.end(); itr!=iend; itr++)\n    if (*itr >= num_clusetrs || *itr < 0){\n      cout << \"something went wrong when assigning instances to clusters\" << endl;\n      exit (EXIT_FAILURE);\n    }\n\n  for (auto itr = cluster_sizes.begin(), iend = cluster_sizes.end(); itr!=iend; itr++)\n    if (*itr < 0){\n      cout << \"cluster with negative size?\" << endl;\n      exit (EXIT_FAILURE);\n    }\n  #endif\n\n  for (size_t curr_inst = 0; curr_inst < num_instances; curr_inst++){\n    double curr_dist_sum = 0;\n\n    for (size_t other_inst = 0; other_inst < num_instances; other_inst++)\n      if (assignments[curr_inst] == assignments[other_inst])\n\tcurr_dist_sum += distances[curr_inst][other_inst];\n    \n    unsigned int curr_assigned_cluster = assignments[curr_inst];\n    double curr_new_cost = (costs[curr_assigned_cluster] * cluster_sizes[curr_assigned_cluster] -\n\t\t\t    curr_dist_sum ) / (cluster_sizes[curr_assigned_cluster] - 1);\n    lower[curr_inst] = costs[curr_assigned_cluster] - curr_new_cost;\n  }\n\n  for (size_t curr_inst = 0; curr_inst < num_instances; curr_inst++){\n    bool firstRound = true;\n    double min_diff = 0;\n\n    for (size_t curr_clust = 0; curr_clust < num_clusetrs; curr_clust++)\n      if (curr_clust != static_cast <unsigned int> (assignments[curr_inst])){\n\tdouble dist_sum = 0;\n\tfor (size_t other_inst = 0; other_inst < num_instances; other_inst++)\n\t  if (clusters[curr_clust][other_inst])\n\t    dist_sum += distances[curr_inst][other_inst];\n\n\tdouble curr_clust_diff = ((costs[curr_clust] * cluster_sizes[curr_clust] \n\t\t\t\t   + dist_sum) / (cluster_sizes[curr_clust] + 1)) - costs[curr_clust];\n\tif (firstRound){\n\t  min_diff = curr_clust_diff;\n\t  firstRound = false;\n\t}\n\telse if (curr_clust_diff < min_diff)\n\t  min_diff = curr_clust_diff;\n      }\n\n    assert (firstRound == false);\n    upper[curr_inst] = min_diff;\n  }\n\n}\n", "meta": {"hexsha": "de94f2e23208d7bcb42003125f35c36a3a830424", "size": 13381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/init.cpp", "max_stars_repo_name": "Behrouz-Babaki/CCCG", "max_stars_repo_head_hexsha": "275d3cf00edb5ce379a66131169580fe5d0aa3c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-12T03:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-12T03:00:19.000Z", "max_issues_repo_path": "src/init.cpp", "max_issues_repo_name": "Behrouz-Babaki/CCCG", "max_issues_repo_head_hexsha": "275d3cf00edb5ce379a66131169580fe5d0aa3c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/init.cpp", "max_forks_repo_name": "Behrouz-Babaki/CCCG", "max_forks_repo_head_hexsha": "275d3cf00edb5ce379a66131169580fe5d0aa3c1", "max_forks_repo_licenses": ["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.3984575835, "max_line_length": 189, "alphanum_fraction": 0.641431881, "num_tokens": 3330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478897, "lm_q2_score": 0.02976009222491408, "lm_q1q2_score": 0.010481557515524285}}
{"text": "#include <mpi.h>\n\n#include <string>\n#include <map>\n#include <time.h>\n#include <vector>\n#include <fstream>\n#include <boost/timer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/cmdline.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/timer.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <arcane/ArcaneVersion.h>\n#include <arcane/Timer.h>\n#include <arcane/ItemPairGroup.h>\n#include <arcane/mesh/ItemFamily.h>\n#include <arcane/utils/PlatformUtils.h>\n#include <arcane/utils/IMemoryInfo.h>\n#include <arcane/utils/OStringStream.h>\n#include <arcane/ITimeLoopMng.h>\n#include <alien/arcane_tools/accessors/ItemVectorAccessor.h>\n#include <alien/core/block/VBlock.h>\n\n#include <alien/arcane_tools/IIndexManager.h>\n#include <alien/arcane_tools/indexManager/BasicIndexManager.h>\n#include <alien/arcane_tools/indexManager/SimpleAbstractFamily.h>\n#include <alien/arcane_tools/distribution/DistributionFabric.h>\n#include <alien/arcane_tools/indexSet/IndexSetFabric.h>\n#include <alien/arcane_tools/data/Space.h>\n\n#include <alien/kernels/simple_csr/algebra/SimpleCSRLinearAlgebra.h>\n#include <alien/kernels/simple_csr/algebra/SimpleCSRInternalLinearAlgebra.h>\n\n#include <alien/ref/AlienRefSemantic.h>\n\n#include <alien/kernels/redistributor/Redistributor.h>\n#include <alien/ref/data/scalar/RedistributedVector.h>\n#include <alien/ref/data/scalar/RedistributedMatrix.h>\n#include <alien/ref/import_export/MatrixMarketSystemWriter.h>\n\n#include <alien/expression/solver/SolverStater.h>\n\n#ifdef ALIEN_USE_PETSC\n#include <alien/kernels/petsc/io/AsciiDumper.h>\n#include <alien/kernels/petsc/algebra/PETScLinearAlgebra.h>\n#endif\n#ifdef ALIEN_USE_MTL4\n#include <alien/kernels/mtl/algebra/MTLLinearAlgebra.h>\n#endif\n#ifdef ALIEN_USE_HTSSOLVER\n#include <alien/kernels/hts/HTSBackEnd.h>\n#include <alien/kernels/hts/data_structure/HTSMatrix.h>\n#include <alien/kernels/hts/algebra/HTSLinearAlgebra.h>\n#endif\n#ifdef ALIEN_USE_TRILINOS\n#include <alien/kernels/trilinos/TrilinosBackEnd.h>\n#include <alien/kernels/trilinos/data_structure/TrilinosMatrix.h>\n#include <alien/kernels/trilinos/algebra/TrilinosLinearAlgebra.h>\n#endif\n\n#include <alien/expression/solver/ILinearSolver.h>\n#include \"AlienCoreSolverOptionTypes.h\"\n\n#include \"AlienBenchModule.h\"\n\n#include <arcane/ItemPairGroup.h>\n#include <arcane/IMesh.h>\n\n#include <alien/core/impl/MultiVectorImpl.h>\n\n#include <alien/expression/krylov/AlienKrylov.h>\n#include <alien/utils/StdTimer.h>\n\nusing namespace Arcane;\nusing namespace Alien;\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid\nAlienBenchModule::init()\n{\n  Alien::setTraceMng(traceMng());\n  Alien::setVerbosityLevel(Alien::Verbosity::Debug);\n  m_parallel_mng = subDomain()->parallelMng();\n  m_homogeneous = options()->homogeneous();\n  m_diag_coeff = options()->diagonalCoefficient();\n  m_lambdax = options()->lambdax();\n  m_lambday = options()->lambday();\n  m_lambdaz = options()->lambdaz();\n  m_alpha = options()->alpha();\n\n  Alien::ILinearSolver* solver = options()->linearSolver();\n  solver->init();\n}\n\n/*---------------------------------------------------------------------------*/\n\nvoid\nAlienBenchModule::test()\n{\n  Timer pbuild_timer(subDomain(), \"PBuildPhase\", Timer::TimerReal);\n  Timer psolve_timer(subDomain(), \"PSolvePhase\", Timer::TimerReal);\n  Timer rbuild_timer(subDomain(), \"RBuildPhase\", Timer::TimerReal);\n  Timer rsolve_timer(subDomain(), \"RSolvePhase\", Timer::TimerReal);\n\n  ItemGroup areaU = allCells();\n  CellCellGroup cell_cell_connection(areaU.own(), areaU, m_stencil_kind);\n  CellCellGroup all_cell_cell_connection(areaU, areaU, m_stencil_kind);\n\n  Alien::ArcaneTools::BasicIndexManager index_manager(m_parallel_mng);\n  index_manager.setTraceMng(traceMng());\n\n  auto indexSetU = index_manager.buildScalarIndexSet(\"U\", areaU);\n  index_manager.prepare();\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // CREATE Space FROM IndexManger\n  // CREATE MATRIX ASSOCIATED TO Space\n  // CREATE VECTORS ASSOCIATED TO Space\n  //\n\n  // Accès à l'indexation\n  Arccore::UniqueArray<Arccore::Integer> allUIndex = index_manager.getIndexes(indexSetU);\n\n  Alien::ArcaneTools::Space space(&index_manager, \"TestSpace\");\n  m_mdist = Alien::ArcaneTools::createMatrixDistribution(space);\n  m_vdist = Alien::ArcaneTools::createVectorDistribution(space);\n\n  info() << \"GLOBAL SIZE : \" << m_vdist.globalSize();\n\n  Alien::Vector vectorB(m_vdist);\n  Alien::Vector vectorBB(m_vdist);\n  Alien::Vector vectorX(m_vdist);\n\n  Alien::Vector coordX(m_vdist);\n  Alien::Vector coordY(m_vdist);\n  Alien::Vector coordZ(m_vdist);\n\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // VECTOR BUILDING AND FILLING\n  //\n  info() << \"Building & initializing vector b\";\n  info() << \"Space size = \" << m_vdist.globalSize()\n         << \", local size= \" << m_vdist.localSize();\n\n  ENUMERATE_CELL (icell, areaU) {\n    Real3 x;\n    ENUMERATE_NODE (inode, icell->nodes()) {\n      x += m_node_coord[*inode];\n    }\n    x /= icell->nbNode();\n    m_cell_center[icell] = x;\n    m_u[icell] = funcn(x);\n    m_k[icell] = funck(x);\n  }\n  {\n    // Builder du vecteur\n    Alien::VectorWriter writer(vectorX);\n    Alien::VectorWriter x(coordX);\n    Alien::VectorWriter y(coordY);\n    Alien::VectorWriter z(coordZ);\n\n    ENUMERATE_CELL(icell,areaU.own())\n    {\n      const Integer iIndex = allUIndex[icell->localId()];\n      writer[iIndex] = m_u[icell] ;\n      x[iIndex] = m_cell_center[icell].x ;\n      y[iIndex] = m_cell_center[icell].y ;\n      z[iIndex] = m_cell_center[icell].z ;\n    }\n  }\n\n  Alien::Matrix matrixA(m_mdist); // local matrix for exact measure without side effect\n                                  // (however, you can reuse a matrix with several\n                                  // builder)\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // MATRIX BUILDING AND FILLING\n  //\n  {\n    Timer::Sentry ts(&pbuild_timer);\n    Alien::MatrixProfiler profiler(matrixA);\n    ///////////////////////////////////////////////////////////////////////////\n    //\n    // DEFINE PROFILE\n    //\n    ENUMERATE_ITEMPAIR(Cell, Cell, icell, cell_cell_connection)\n    {\n      const Cell& cell = *icell;\n      const Integer iIndex = allUIndex[cell.localId()];\n      profiler.addMatrixEntry(iIndex, allUIndex[cell.localId()]);\n      ENUMERATE_SUB_ITEM(Cell, isubcell, icell)\n      {\n        const Cell& subcell = *isubcell;\n        profiler.addMatrixEntry(iIndex, allUIndex[subcell.localId()]);\n      }\n    }\n  }\n  {\n    Timer::Sentry ts(&pbuild_timer);\n    Alien::ProfiledMatrixBuilder builder(\n        matrixA, Alien::ProfiledMatrixOptions::eResetValues);\n    ENUMERATE_ITEMPAIR(Cell, Cell, icell, cell_cell_connection)\n    {\n      const Cell& cell = *icell;\n      double diag = dii(cell);\n\n      Integer i = allUIndex[cell.localId()];\n      builder(i, i) += diag;\n      ENUMERATE_SUB_ITEM(Cell, isubcell, icell)\n      {\n        const Cell& subcell = *isubcell;\n        double off_diag = fij(cell, subcell);\n        builder(i, i) += off_diag;\n        Integer j = allUIndex[subcell.localId()];\n        builder(i, j) -= off_diag;\n      }\n    }\n    if (options()->sigma() > 0.) {\n      m_sigma = options()->sigma();\n      auto xCmax = Real3{ 0.25, 0.25, 0.25 };\n      auto xCmin = Real3{ 0.75, 0.75, 0.55 };\n      ENUMERATE_ITEMPAIR(Cell, Cell, icell, all_cell_cell_connection)\n      {\n        const Cell& cell = *icell;\n        Real3 xC = m_cell_center[icell];\n        Real3 xDmax = xC - xCmax;\n        Real3 xDmin = xC - xCmin;\n        m_s[cell] = 0;\n        if (xDmax.abs() < options()->epsilon()) {\n          m_s[cell] = 1.;\n          Integer i = allUIndex[cell.localId()];\n          info() << \"MATRIX TRANSFO SIGMAMAX \" << i;\n          if (cell.isOwn())\n            builder(i, i) = m_sigma;\n          ENUMERATE_SUB_ITEM(Cell, isubcell, icell)\n          {\n            const Cell& subcell = *isubcell;\n            if (subcell.isOwn()) {\n              Integer j = allUIndex[subcell.localId()];\n              builder(j, i) = 0.;\n            }\n          }\n        }\n        if (xDmin.abs() < options()->epsilon()) {\n          m_s[cell] = -1.;\n          Integer i = allUIndex[cell.localId()];\n          info() << \"MATRIX TRANSFO SIGMA MIN\" << i;\n\n          if (cell.isOwn())\n            builder(i, i) = 1. / m_sigma;\n          ENUMERATE_SUB_ITEM(Cell, isubcell, icell)\n          {\n            const Cell& subcell = *isubcell;\n            if (subcell.isOwn()) {\n              Integer j = allUIndex[subcell.localId()];\n              builder(j, i) = 0.;\n            }\n          }\n        }\n      }\n    }\n\n    builder.finalize();\n  }\n\n  {\n    Alien::SimpleCSRLinearAlgebra csrAlg;\n    csrAlg.mult(matrixA, vectorX, vectorB);\n    csrAlg.mult(matrixA, vectorX, vectorBB);\n    Real normeb = csrAlg.norm2(vectorB);\n    info() << \"||b||=\" << normeb;\n  }\n#ifdef ALIEN_USE_HTSSOLVER\n/*{\n  info()<<\"HTS\";\n  Alien::HTSLinearAlgebra htsAlg;\n  htsAlg.mult(matrixA,vectorX,vectorB);\n  htsAlg.mult(matrixA,vectorX,vectorBB);\n  Real normeb = htsAlg.norm2(vectorB) ;\n  info()<<\"||b||=\"<<normeb;\n}*/\n#endif\n#ifdef ALIEN_USE_TRILINOS\n  /*{\n    info() << \"Trilinos\";\n    Alien::TrilinosLinearAlgebra tpetraAlg;\n    tpetraAlg.mult(matrixA, vectorX, vectorB);\n    tpetraAlg.mult(matrixA, vectorX, vectorBB);\n    Real normeb = tpetraAlg.norm2(vectorB);\n    info() << \"||b||=\" << normeb;\n    // tpetraAlg.dump(matrixA,\"MatrixA.txt\") ;\n    // tpetraAlg.dump(vectorB,\"vectorB.txt\") ;\n    // tpetraAlg.dump(vectorBB,\"vectorBB.txt\") ;\n    // tpetraAlg.dump(vectorX,\"vectorX.txt\") ;\n  }*/\n#endif\n\n  if (options()->unitRhs()) {\n    Alien::LocalVectorWriter v(vectorBB);\n    for (Integer i = 0; i < v.size(); ++i)\n      v[i] = 1.;\n  }\n\n  if (options()->zeroRhs()) {\n    Alien::LocalVectorWriter v(vectorB);\n    for (Integer i = 0; i < v.size(); ++i)\n      v[i] = 0.;\n  }\n\n  ///////////////////////////////////////////////////////////////////////////\n  //\n  // RESOLUTION\n  //\n  if(options()->alienCoreSolver.size()>0)\n  {\n    {\n      Alien::LocalVectorReader reader(vectorBB);\n      Alien::LocalVectorWriter vb(vectorB);\n      Alien::LocalVectorWriter vx(vectorX);\n      for (Integer i = 0; i < m_vdist.localSize(); ++i) {\n        vx[i] = 0.;\n        vb[i] = reader[i];\n      }\n    }\n    typedef Alien::SimpleCSRInternalLinearAlgebra    AlgebraType ;\n    typedef typename AlgebraType::BackEndType        BackEndType ;\n    typedef Alien::Iteration<AlgebraType>            StopCriteriaType ;\n    typedef Alien::CG<AlgebraType>                   SolverType ;\n\n    AlgebraType alg ;\n    auto const& true_A = matrixA.impl()->get<Alien::BackEnd::tag::simplecsr>() ;\n    auto const& true_b = vectorB.impl()->get<Alien::BackEnd::tag::simplecsr>() ;\n    auto&       true_x = vectorX.impl()->get<Alien::BackEnd::tag::simplecsr>(true) ;\n\n    auto const& opt           = options()->alienCoreSolver[0] ;\n    int output_level  = opt->outputLevel() ;\n    int max_iteration = opt->maxIter() ;\n    double tol        = opt->tol() ;\n\n    auto solver_opt   = opt->solver() ;\n    auto precond_opt  = opt->preconditioner() ;\n\n    auto backend      = opt->backend() ;\n    auto asynch       = opt->asynch() ;\n\n    // clang-format off\n    auto run = [&](auto& alg)\n              {\n                typedef typename\n                    boost::remove_reference<decltype(alg)>::type AlgebraType ;\n                typedef typename AlgebraType::BackEndType        BackEndType ;\n                typedef Alien::Iteration<AlgebraType>            StopCriteriaType ;\n\n                auto const& true_A = matrixA.impl()->get<BackEndType>() ;\n                auto const& true_b = vectorB.impl()->get<BackEndType>() ;\n                auto&       true_x = vectorX.impl()->get<BackEndType>(true) ;\n\n                StopCriteriaType stop_criteria{alg,true_b,tol,max_iteration,output_level>0?traceMng():nullptr} ;\n\n                switch(solver_opt)\n                {\n                  case AlienCoreSolverOptionTypes::CG:\n                  {\n                    typedef Alien::CG<AlgebraType> SolverType ;\n\n                    SolverType solver{alg,traceMng()} ;\n                    solver.setOutputLevel(output_level) ;\n                    switch(precond_opt)\n                    {\n                      case AlienCoreSolverOptionTypes::ChebyshevPoly:\n                      {\n                          info()<<\"CHEBYSHEV PRECONDITIONER\";\n                          double polynom_factor          = opt->polyFactor() ;\n                          int    polynom_order           = opt->polyOrder() ;\n                          int    polynom_factor_max_iter = opt->polyFactorMaxIter() ;\n\n                          typedef Alien::ChebyshevPreconditioner<AlgebraType,true> PrecondType ;\n                          PrecondType      precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ;\n                          precond.setOutputLevel(output_level) ;\n                          precond.init() ;\n\n                          Timer::Sentry ts(&psolve_timer);\n                          if(asynch==0)\n                            solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                          else\n                            solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                      }\n                      break;\n                      case AlienCoreSolverOptionTypes::NeumannPoly:\n                        {\n                          info()<<\"NEUMANN PRECONDITIONER\";\n                          double polynom_factor          = opt->polyFactor() ;\n                          int    polynom_order           = opt->polyOrder() ;\n                          int    polynom_factor_max_iter = opt->polyFactorMaxIter() ;\n\n                          typedef Alien::NeumannPolyPreconditioner<AlgebraType> PrecondType ;\n                          PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ;\n                          precond.init() ;\n\n                          Timer::Sentry ts(&psolve_timer);\n                          if(asynch==0)\n                            solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                          else\n                            solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                        }\n                        case AlienCoreSolverOptionTypes::Diag:\n                        default:\n                        {\n                          info()<<\"DIAG PRECONDITIONER\";\n                          typedef Alien::DiagPreconditioner<AlgebraType> PrecondType ;\n                          PrecondType      precond{alg,true_A} ;\n                          precond.init() ;\n\n                          Timer::Sentry ts(&psolve_timer);\n                          if(asynch==0)\n                            solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                          else\n                            solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                        }\n                        break ;\n                    }\n                }\n                break ;\n                case AlienCoreSolverOptionTypes::BCGS:\n                {\n                  typedef Alien::BiCGStab<AlgebraType> SolverType ;\n                  SolverType solver{alg,traceMng()} ;\n                  solver.setOutputLevel(output_level) ;\n                  switch(precond_opt)\n                  {\n                  case AlienCoreSolverOptionTypes::ChebyshevPoly:\n                   {\n                      info()<<\"CHEBYSHEV PRECONDITIONER\";\n                      double polynom_factor          = opt->polyFactor() ;\n                      int    polynom_order           = opt->polyOrder() ;\n                      int    polynom_factor_max_iter = opt->polyFactorMaxIter() ;\n\n                      typedef Alien::ChebyshevPreconditioner<AlgebraType,true> PrecondType ;\n                      PrecondType      precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ;\n                      precond.setOutputLevel(output_level) ;\n                      precond.init() ;\n\n                      Timer::Sentry ts(&psolve_timer);\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                   break ;\n                  case AlienCoreSolverOptionTypes::NeumannPoly:\n                    {\n                      info()<<\"NEUMANN PRECONDITIONER\";\n                      double polynom_factor          = opt->polyFactor() ;\n                      int    polynom_order           = opt->polyOrder() ;\n                      int    polynom_factor_max_iter = opt->polyFactorMaxIter() ;\n\n                      typedef Alien::NeumannPolyPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ;\n                      precond.init() ;\n\n                      Timer::Sentry ts(&psolve_timer);\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                    break ;\n                  case AlienCoreSolverOptionTypes::ILU0:\n                    {\n                      info()<<\"ILU0 PRECONDITIONER\";\n                      typedef Alien::ILU0Preconditioner<AlgebraType> PrecondType ;\n                      PrecondType precond{alg,true_A,traceMng()} ;\n                      precond.init() ;\n\n                      Timer::Sentry ts(&psolve_timer);\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                    break ;\n                  case AlienCoreSolverOptionTypes::FILU0:\n                    {\n                      info()<<\"FILU0 PRECONDITIONER\";\n                      typedef Alien::FILU0Preconditioner<AlgebraType> PrecondType ;\n                      PrecondType precond{alg,true_A,traceMng()} ;\n                      precond.setParameter(\"nb-factor-iter\",opt->filuFactorNiter()) ;\n                      precond.setParameter(\"nb-solver-iter\",opt->filuSolverNiter()) ;\n                      precond.setParameter(\"tol\",           opt->filuTol()) ;\n                      precond.init() ;\n\n                      Timer::Sentry ts(&psolve_timer);\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                    break ;\n\n                  case AlienCoreSolverOptionTypes::Diag:\n                  default:\n                    {\n                      info()<<\"DIAG PRECONDITIONER\";\n                      typedef Alien::DiagPreconditioner<AlgebraType> PrecondType ;\n                      PrecondType      precond{alg,true_A} ;\n                      precond.init() ;\n\n                      Timer::Sentry ts(&psolve_timer);\n                      if(asynch==0)\n                        solver.solve(precond,stop_criteria,true_A,true_b,true_x) ;\n                      else\n                        solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ;\n                    }\n                    break ;\n                  }\n                }\n                break ;\n                default :\n                  fatal()<<\"unknown solver\";\n                }\n\n                if(stop_criteria.getStatus())\n                {\n                  info()<<\"Solver has converged\";\n                  info()<<\"Nb iterations  : \"<<stop_criteria();\n                  info()<<\"Criteria value : \"<<stop_criteria.getValue();\n                }\n                else\n                {\n                  info()<<\"Solver convergence failed\";\n                }\n              } ;\n    // clang-format on\n\n    switch(backend)\n    {\n      case AlienCoreSolverOptionTypes::SimpleCSR:\n      {\n        Alien::SimpleCSRInternalLinearAlgebra alg;\n        run(alg);\n      }\n      break ;\n      case AlienCoreSolverOptionTypes::SYCL:\n      {\n#ifdef ALIEN_USE_SYCL\n        Alien::SYCLInternalLinearAlgebra alg;\n        alg.setDotAlgo(vm[\"dot-algo\"].as<int>());\n        run(alg);\n#else\n        fatal() << \"SYCL BackEnd not available\";\n#endif\n      }\n      break ;\n      default:\n        fatal() << \"SYCL BackEnd not available\";\n        break ;\n    }\n  }\n  else\n  {\n    Alien::ILinearSolver* solver = options()->linearSolver();\n    solver->init();\n#ifdef ALIEN_USE_TRILINOS\n      if(solver->getBackEndName().contains(\"tpetraserial\"))\n      {\n        auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetraserial>(false) ;\n        mat.setMatrixCoordinate(coordX,coordY,coordZ) ;\n      }\n#ifdef KOKKOS_ENABLE_OPENMP\n      if(solver->getBackEndName().contains(\"tpetraomp\"))\n      {\n        auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetraomp>(false) ;\n        mat.setMatrixCoordinate(coordX,coordY,coordZ) ;\n      }\n#endif\n#ifdef KOKKOS_ENABLE_THREADS\n\n      if(solver->getBackEndName().contains(\"tpetrapth\"))\n      {\n        auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetrapth>(false) ;\n        mat.setMatrixCoordinate(coordX,coordY,coordZ) ;\n      }\n#endif\n#ifdef KOKKOS_ENABLE_CUDA\n      if(solver->getBackEndName().contains(\"tpetracuda\"))\n      {\n        auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetracuda>(true) ;\n        mat->setCoordinate(coordX,coordY,coordZ) ;\n      }\n#endif\n#endif\n    \n\n    if (not solver->hasParallelSupport() and m_parallel_mng->commSize() > 1) {\n      info() << \"Current solver has not a parallel support for solving linear system : \"\n                \"skip it\";\n    } else {\n      Integer nb_resolutions = options()->nbResolutions();\n      for (Integer i = 0; i < nb_resolutions; ++i) {\n        if (i > 0) // i=0, matrix allready filled\n        {\n          Timer::Sentry ts(&pbuild_timer);\n          Alien::ProfiledMatrixBuilder builder(\n              matrixA, Alien::ProfiledMatrixOptions::eResetValues);\n          ENUMERATE_ITEMPAIR(Cell, Cell, icell, cell_cell_connection)\n          {\n            const Cell& cell = *icell;\n            double diag = dii(cell);\n\n            Integer i = allUIndex[cell.localId()];\n            builder(i, i) += diag;\n            ENUMERATE_SUB_ITEM(Cell, isubcell, icell)\n            {\n              const Cell& subcell = *isubcell;\n              double off_diag = fij(cell, subcell);\n              builder(i, i) += off_diag;\n              Integer j = allUIndex[subcell.localId()];\n              builder(i, j) -= off_diag;\n            }\n          }\n          if (options()->sigma() > 0.) {\n            m_sigma = options()->sigma();\n            auto xCmax = Real3{ 0.25, 0.25, 0.25 };\n            auto xCmin = Real3{ 0.75, 0.75, 0.55 };\n            ENUMERATE_ITEMPAIR(Cell, Cell, icell, all_cell_cell_connection)\n            {\n              const Cell& cell = *icell;\n              Real3 xC = m_cell_center[icell];\n              Real3 xDmax = xC - xCmax;\n              Real3 xDmin = xC - xCmin;\n              m_s[cell] = 0;\n              if (xDmax.abs() < options()->epsilon()) {\n                m_s[cell] = 1.;\n                Integer i = allUIndex[cell.localId()];\n                info() << \"MATRIX TRANSFO SIGMAMAX \" << i;\n                if (cell.isOwn())\n                  builder(i, i) = m_sigma;\n                ENUMERATE_SUB_ITEM(Cell, isubcell, icell)\n                {\n                  const Cell& subcell = *isubcell;\n                  if (subcell.isOwn()) {\n                    Integer j = allUIndex[subcell.localId()];\n                    builder(j, i) = 0.;\n                  }\n                }\n              }\n              if (xDmin.abs() < options()->epsilon()) {\n                m_s[cell] = -1.;\n                Integer i = allUIndex[cell.localId()];\n                info() << \"MATRIX TRANSFO SIGMA MIN\" << i;\n\n                if (cell.isOwn())\n                  builder(i, i) = 1. / m_sigma;\n                ENUMERATE_SUB_ITEM(Cell, isubcell, icell)\n                {\n                  const Cell& subcell = *isubcell;\n                  if (subcell.isOwn()) {\n                    Integer j = allUIndex[subcell.localId()];\n                    builder(j, i) = 0.;\n                  }\n                }\n              }\n            }\n          }\n\n          builder.finalize();\n        }\n\n        // Réinitialisation de vectorX\n        // if(i>0)  // i=0, vector allready filled\n        {\n          Alien::LocalVectorReader reader(vectorBB);\n          Alien::LocalVectorWriter vb(vectorB);\n          Alien::LocalVectorWriter vx(vectorX);\n          for (Integer i = 0; i < m_vdist.localSize(); ++i) {\n            vx[i] = 0.;\n            vb[i] = reader[i];\n          }\n        }\n        if(i==0)\n        {\n          Alien::MatrixMarketSystemWriter matrix_exporter(\"AlienBenchMatrixA.mtx\",m_parallel_mng->messagePassingMng()) ;\n          matrix_exporter.dump(matrixA) ;\n          Alien::MatrixMarketSystemWriter vector_exporter(\"AlienBenchVectorB.mtx\",m_parallel_mng->messagePassingMng()) ;\n          vector_exporter.dump(vectorB) ;\n        }\n\n        Timer::Sentry ts(&psolve_timer);\n        solver->solve(matrixA, vectorB, vectorX);\n      }\n      Alien::SolverStatus status = solver->getStatus();\n      if (status.succeeded) {\n        info()<<\"RESOLUTION SUCCEED\";\n        Alien::VectorReader reader(vectorX);\n        ENUMERATE_CELL (icell, areaU.own()) {\n          const Integer iIndex = allUIndex[icell->localId()];\n          m_x[icell] = reader[iIndex];\n        }\n\n        SimpleCSRLinearAlgebra alg;\n        Alien::Vector vectorR(m_vdist);\n        alg.mult(matrixA, vectorX, vectorR);\n        alg.axpy(-1., vectorB, vectorR);\n        Real res = alg.norm2(vectorR);\n        info() << \"RES : \" << res;\n      }\n      else\n        info()<<\"SOLVER FAILED\";\n      solver->getSolverStat().print(Universe().traceMng(), status, \"Linear Solver : \");\n    }\n    solver->end();\n  }\n\n  if (options()->redistribution() && m_parallel_mng->commSize() > 1) {\n    info() << \"Test REDISTRIBUTION\";\n\n    {\n      Alien::LocalVectorWriter v(vectorX);\n      for (Integer i = 0; i < v.size(); ++i)\n        v[i] = 0;\n    }\n    Alien::Vector vectorR(m_vdist);\n\n    bool keep_proc = false;\n    if (m_parallel_mng->commRank() == 0)\n      keep_proc = true;\n\n    rbuild_timer.start();\n    auto small_comm = Arccore::MessagePassing::mpSplit(m_parallel_mng->messagePassingMng(), keep_proc);\n    Alien::Redistributor redist(matrixA.distribution().globalRowSize(),\n                                m_parallel_mng->messagePassingMng(),\n                                small_comm );\n\n    Alien::RedistributedMatrix Aa(matrixA, redist);\n    Alien::RedistributedVector bb(vectorB, redist);\n    Alien::RedistributedVector xx(vectorX, redist);\n    Alien::RedistributedVector rr(vectorR, redist);\n    rbuild_timer.stop();\n    if (keep_proc) {\n      auto solver = options()->linearSolver();\n      // solver->updateParallelMng(Aa.distribution().parallelMng());\n      solver->init();\n      {\n        Timer::Sentry ts(&rsolve_timer);\n        solver->solve(Aa, bb, xx);\n      }\n\n      Alien::SimpleCSRLinearAlgebra alg;\n\n      alg.mult(Aa, xx, rr);\n      alg.axpy(-1., bb, rr);\n      Real res = alg.norm2(rr);\n      info() << \"REDISTRIBUTION RES : \" << res;\n    }\n  }\n  info() << \"===================================================\";\n  info() << \"BENCH INFO :\";\n  info() << \" PBUILD    :\" << pbuild_timer.totalTime();\n  info() << \" PSOLVE    :\" << psolve_timer.totalTime();\n  info() << \" RBUILD    :\" << rbuild_timer.totalTime();\n  info() << \" RSOLVE    :\" << rsolve_timer.totalTime();\n  info() << \"===================================================\";\n\n  subDomain()->timeLoopMng()->stopComputeLoop(true);\n}\n\n/*---------------------------------------------------------------------------*/\n\nReal\nAlienBenchModule::funcn(Real3 p) const\n{\n  return p.x * p.x * p.y;\n}\n\nReal\nAlienBenchModule::funck(Real3 p) const\n{\n#define PI 3.14159265358979323846264\n\n  if (m_homogeneous)\n    return m_off_diag_coeff;\n  else\n    return std::exp(-m_alpha * 0.5 * (1 + std::sin(2 * PI * p.x / m_lambdax))\n        * (1 + std::sin(2 * PI * p.y / m_lambday)));\n}\n\nReal\nAlienBenchModule::dii(const Cell& ci) const\n{\n  return m_diag_coeff;\n}\n\nReal\nAlienBenchModule::fij(const Cell& ci, const Cell& cj) const\n{\n  if (ci == cj)\n    return dii(ci);\n  else {\n    Real3 xi = m_cell_center[ci];\n    Real3 xj = m_cell_center[cj];\n    Real3 xij = xi + xj;\n    xij /= 2.;\n\n    return funck(xij);\n  }\n}\n\n/*---------------------------------------------------------------------------*/\n\nARCANE_REGISTER_MODULE_ALIENBENCH(AlienBenchModule);\n", "meta": {"hexsha": "410e24f61c82dd5c0a721198f9e4db5f13b2691b", "size": 29178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/AlienBench/AlienBenchModule.cc", "max_stars_repo_name": "arcaneframework/alien_legacy_plugins", "max_stars_repo_head_hexsha": "be42667ece5ad58f9ee32b7700793646bfb8551b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T09:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T14:22:35.000Z", "max_issues_repo_path": "test/AlienBench/AlienBenchModule.cc", "max_issues_repo_name": "arcaneframework/alien_legacy_plugins", "max_issues_repo_head_hexsha": "be42667ece5ad58f9ee32b7700793646bfb8551b", "max_issues_repo_licenses": ["Apache-2.0"], "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/AlienBench/AlienBenchModule.cc", "max_forks_repo_name": "arcaneframework/alien_legacy_plugins", "max_forks_repo_head_hexsha": "be42667ece5ad58f9ee32b7700793646bfb8551b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T14:50:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:23:07.000Z", "avg_line_length": 35.5395858709, "max_line_length": 128, "alphanum_fraction": 0.543251765, "num_tokens": 6976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.0259573574803628, "lm_q1q2_score": 0.0104755287172274}}
{"text": "#ifndef MATHIC_VECTOR_HPP_\n#define MATHIC_VECTOR_HPP_\n\n#include <algorithm>\n#include <array>\n#include <assert.h>\n#include <stdexcept>\n\n#include <algorithm>\n#include <array>\n#include <assert.h>\n#include <boost/type_traits/add_const.hpp>\n#include <boost/type_traits/add_lvalue_reference.hpp>\n#include <boost/type_traits/add_reference.hpp>\n#include <boost/type_traits/remove_cv.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <stdexcept>\n\nnamespace mathic {\n  namespace detail {\n    template <size_t Index, typename T>\n    struct data_holder {\n      enum {\n        index = Index\n      };\n      typedef T type;\n      type value;\n      data_holder() : value() {\n      }\n      data_holder(type const &value) : value(value) {\n      }\n      template <typename Y>\n      data_holder(Y const &value) : value(value) {\n      }\n      void\n      swap(data_holder<Index, T> &rhs) {\n        using std::swap;\n        swap(value, rhs.value);\n      }\n      template <size_t idx1, typename Y>\n      data_holder &\n      operator=(const data_holder<idx1, Y> &rhs) {\n        value = rhs.value;\n        return *this;\n      }\n    };\n    template <size_t... Indexes>\n    struct indexes_tuple {\n      enum {\n        size = sizeof...(Indexes)\n      };\n    };\n    template <size_t num, typename tp = indexes_tuple<>>\n    struct index_builder;\n    template <size_t num, size_t... Indexes>\n    struct index_builder<num, indexes_tuple<Indexes...>> : index_builder<\n                                                               num - 1, indexes_tuple<Indexes..., sizeof...(Indexes)>> {\n    };\n    template <size_t... Indexes>\n    struct index_builder<0, indexes_tuple<Indexes...>> {\n      typedef indexes_tuple<Indexes...> type;\n      enum {\n        size = sizeof...(Indexes)\n      };\n    };\n    template <typename IndexTuple, typename T>\n    struct vector_builder;\n    template <size_t... Indexes, typename T>\n    struct vector_builder<indexes_tuple<Indexes...>, T> : data_holder<Indexes, T>... {\n      typedef indexes_tuple<Indexes...> indexes_tuple_type;\n      typedef vector_builder<indexes_tuple_type, T> this_type;\n      typedef T element_type;\n      typedef typename boost::remove_reference<\n          typename boost::remove_cv<element_type>::type>::type value_type;\n      typedef typename boost::add_lvalue_reference<value_type>::type lvalue_reference;\n      typedef typename boost::add_reference<\n          typename boost::add_const<value_type>::type>::type const_reference;\n      typedef value_type *pointer;\n      typedef value_type const *const_pointer;\n      typedef value_type *iterator;\n      typedef value_type const *const_iterator;\n      vector_builder() : data_holder<Indexes, T>()... {\n      }\n      //\t\tvector_builder(vector_builder const& rhs) :\n      //\t\t\tdata_holder< Indexes, T >( rhs.template at< Indexes >() ) ...\n      //\t\t{\n      //\t\t}\n      /**\n\t\t * Construct vector from a vector of larger size\n\t\t * @param rhs\n\t\t * @param\n\t\t */\n      template <size_t... IndexesR, typename U>\n      vector_builder(\n          vector_builder<indexes_tuple<IndexesR...>, U> const &rhs,\n          typename boost::enable_if_c<sizeof...(Indexes) <= sizeof...(IndexesR)>::type * = 0) : data_holder<Indexes, T>(rhs.template at<Indexes>())... {\n      }\n      template <typename... E>\n      vector_builder(E const &... args,\n                     typename boost::enable_if_c<sizeof...(Indexes) == sizeof...(E)>::type * = 0) : data_holder<Indexes, T>(args)... {\n      }\n      template <typename... E>\n      vector_builder(E &&... args,\n                     typename boost::enable_if_c<sizeof...(Indexes) == sizeof...(E)>::type * = 0) : data_holder<Indexes, T>(std::forward<E>(args))... {\n      }\n      vector_builder(std::initializer_list<value_type> const &args) : data_holder<Indexes, T>(*(args.begin() + Indexes))... {\n      }\n      vector_builder(const_pointer p) : data_holder<Indexes, T>(*(p + Indexes))... {\n      }\n      pointer\n      data() {\n        return &this->data_holder<0, T>::value;\n      }\n      const_pointer\n      data() const {\n        return &this->data_holder<0, T>::value;\n      }\n      template <size_t N>\n      lvalue_reference\n      at() {\n        return this->data_holder<N, T>::value;\n      }\n      template <size_t N>\n      const_reference\n      at() const {\n        return this->data_holder<N, T>::value;\n      }\n      iterator\n      begin() {\n        return &this->data_holder<0, T>::value;\n      }\n      const_iterator\n      begin() const {\n        return &this->data_holder<0, T>::value;\n      }\n      iterator\n      end() {\n        return begin() + indexes_tuple_type::size;\n      }\n      const_iterator\n      end() const {\n        return begin() + indexes_tuple_type::size;\n      }\n      lvalue_reference\n      operator[](size_t idx) {\n        assert(idx < indexes_tuple_type::size);\n        return begin()[idx];\n      }\n      const_reference\n      operator[](size_t idx) const {\n        assert(idx < indexes_tuple_type::size);\n        return begin()[idx];\n      }\n    };\n  } // namespace detail\n  template <typename T, size_t Size>\n  struct vector;\n  namespace detail {\n    template <size_t N, typename T>\n    struct dot_product;\n    template <size_t N, typename T, size_t Size>\n    struct dot_product<N, vector<T, Size>> {\n      typename vector<T, Size>::value_type\n      operator()(vector<T, Size> const &lhs, vector<T, Size> const &rhs) {\n        return dot_product<N - 1, vector<T, Size>>()(lhs, rhs) +\n               lhs.template at<N>() * rhs.template at<N>();\n      }\n    };\n    template <typename T, size_t Size>\n    struct dot_product<0, vector<T, Size>> {\n      typename vector<T, Size>::value_type\n      operator()(vector<T, Size> const &lhs, vector<T, Size> const &rhs) {\n        return lhs.template at<0>() * rhs.template at<0>();\n      }\n    };\n    template <size_t N, typename T>\n    struct scalar_multiplication;\n    template <size_t N, typename T, size_t Size>\n    struct scalar_multiplication<N, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &v, U s) {\n        scalar_multiplication<N - 1, vector<T, Size>>()(v, s);\n        v.template at<N>() *= s;\n      }\n    };\n    template <typename T, size_t Size>\n    struct scalar_multiplication<0, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &v, U s) {\n        v.template at<0>() *= s;\n      }\n    };\n    template <size_t N, typename T>\n    struct scalar_division;\n    template <size_t N, typename T, size_t Size>\n    struct scalar_division<N, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &v, U s) {\n        scalar_division<N - 1, vector<T, Size>>()(v, s);\n        v.template at<N>() /= s;\n      }\n    };\n    template <typename T, size_t Size>\n    struct scalar_division<0, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &v, U s) {\n        v.template at<0>() /= s;\n      }\n    };\n    template <size_t N, typename T>\n    struct vector_addition;\n    template <size_t N, typename T, size_t Size>\n    struct vector_addition<N, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &lhs, vector<U, Size> const &rhs) {\n        vector_addition<N - 1, vector<T, Size>>()(lhs, rhs);\n        lhs.template at<N>() += rhs.template at<N>();\n      }\n    };\n    template <typename T, size_t Size>\n    struct vector_addition<0, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &lhs, vector<U, Size> const &rhs) {\n        lhs.template at<0>() += rhs.template at<0>();\n      }\n    };\n    template <size_t N, typename T>\n    struct vector_substraction;\n    template <size_t N, typename T, size_t Size>\n    struct vector_substraction<N, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &lhs, vector<U, Size> const &rhs) {\n        vector_substraction<N - 1, vector<T, Size>>()(lhs, rhs);\n        lhs.template at<N>() -= rhs.template at<N>();\n      }\n    };\n    template <typename T, size_t Size>\n    struct vector_substraction<0, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &lhs, vector<U, Size> const &rhs) {\n        lhs.template at<0>() -= rhs.template at<0>();\n      }\n    };\n    template <size_t N, typename T>\n    struct set_all_elements;\n    template <size_t N, typename T, size_t Size>\n    struct set_all_elements<N, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &v, U s) {\n        set_all_elements<N - 1, vector<T, Size>>()(v, s);\n        v.template at<N>() = s;\n      }\n    };\n    template <typename T, size_t Size>\n    struct set_all_elements<0, vector<T, Size>> {\n      template <typename U>\n      void\n      operator()(vector<T, Size> &v, U s) {\n        v.template at<0>() = s;\n      }\n    };\n  } // namespace detail\n  template <typename T, size_t Size>\n  struct vector : detail::vector_builder<\n                      typename detail::index_builder<Size>::type, T> {\n    typedef detail::vector_builder<\n        typename detail::index_builder<Size>::type, T>\n        super_type;\n    typedef vector<T, Size> this_type;\n    typedef typename super_type::value_type value_type;\n    typedef typename super_type::lvalue_reference lvalue_reference;\n    typedef typename super_type::const_reference const_reference;\n    typedef typename super_type::pointer pointer;\n    typedef typename super_type::const_pointer const_pointer;\n    vector() : super_type() {\n    }\n    template <typename... E>\n    vector(E const &... args) : super_type(args...) {\n    }\n    vector(std::initializer_list<value_type> const &args) : super_type(args) {\n    }\n    vector(const_pointer p) : super_type(p) {\n    }\n    template <typename U, size_t SizeR>\n    vector(vector<U, SizeR> const &rhs) : super_type(rhs) {\n    }\n    this_type\n    operator-() {\n      this_type res(*this);\n      res *= -1;\n      return res;\n    }\n    template <typename U>\n    this_type &\n    operator*=(U val) {\n      detail::scalar_multiplication<Size - 1, this_type>()(*this, val);\n      return *this;\n    }\n    template <typename U>\n    this_type &\n    operator/=(U val) {\n      detail::scalar_division<Size - 1, this_type>()(*this, val);\n      return *this;\n    }\n    template <typename U>\n    this_type &\n    operator+=(vector<U, Size> const &rhs) {\n      detail::vector_addition<Size - 1, this_type>()(*this, rhs);\n      return *this;\n    }\n    template <typename U>\n    this_type &\n    operator-=(vector<U, Size> const &rhs) {\n      detail::vector_substraction<Size - 1, this_type>()(*this, rhs);\n      return *this;\n    }\n    value_type\n    magnitude_square() const {\n      return detail::dot_product<Size - 1, this_type>()(*this, *this);\n    }\n    value_type\n    magnitude() const {\n      return sqrt(magnitude_square());\n    }\n    bool\n    is_zero() const {\n      return magnitude_square() == 0;\n    }\n    bool\n    is_unit() const {\n      return magnitude_square() == 1;\n    }\n    this_type &\n    zero() {\n      detail::set_all_elements<Size - 1, this_type>()(*this, 0);\n      return *this;\n    }\n    this_type &\n    normalize() {\n      value_type m = magnitude();\n      if (m != 0) {\n        if (m != 1)\n          (*this) /= m;\n      } else {\n        throw std::runtime_error(\"Cannot normalize a zero vector\");\n      }\n      return *this;\n    }\n    this_type\n    normalize() const {\n      this_type v(*this);\n      v.normalize();\n      return v;\n    }\n  };\n  template <typename T, typename U, size_t Size>\n  bool\n  operator==(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    return std::equal(lhs.begin(), lhs.end(), rhs.begin());\n  }\n  template <typename T, typename U, size_t Size>\n  bool\n  operator!=(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    return !(lhs == rhs);\n  }\n  template <typename T, typename U, size_t Size>\n  bool\n  operator<(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n  }\n  template <typename T, typename U, size_t Size>\n  bool\n  operator>(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    return rhs < lhs;\n  }\n  template <typename T, typename U, size_t Size>\n  bool\n  operator<=(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    return !(rhs < lhs);\n  }\n  template <typename T, typename U, size_t Size>\n  bool\n  operator>=(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    return !(lhs < rhs);\n  }\n  template <typename T, size_t Size>\n  typename vector<T, Size>::value_type\n  operator*(vector<T, Size> const &lhs, vector<T, Size> const &rhs) {\n    return detail::dot_product<Size - 1, vector<T, Size>>()(lhs, rhs);\n  }\n  template <typename T, size_t Size, typename U>\n  vector<T, Size>\n  operator*(vector<T, Size> const &v, U s) {\n    vector<T, Size> res(v);\n    res *= s;\n    return res;\n  }\n  template <typename T, size_t Size, typename U>\n  vector<T, Size>\n  operator*(U s, vector<T, Size> const &v) {\n    vector<T, Size> res(v);\n    res *= s;\n    return res;\n  }\n  template <typename T, size_t Size, typename U>\n  vector<T, Size>\n  operator/(vector<T, Size> const &v, U s) {\n    vector<T, Size> res(v);\n    res /= s;\n    return res;\n  }\n  template <typename T, typename U, size_t Size>\n  vector<T, Size>\n  operator+(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    vector<T, Size> res(lhs);\n    res += rhs;\n    return res;\n  }\n  template <typename T, typename U, size_t Size>\n  vector<T, Size>\n  operator-(vector<T, Size> const &lhs, vector<U, Size> const &rhs) {\n    vector<T, Size> res(lhs);\n    res -= rhs;\n    return res;\n  }\n  template <typename T, size_t Size>\n  typename vector<T, Size>::value_type\n  magnitude_square(vector<T, Size> const &v) {\n    return v.magnitude_square();\n  }\n  template <typename T, size_t Size>\n  typename vector<T, Size>::value_type\n  magnitude(vector<T, Size> const &v) {\n    return v.magnitude();\n  }\n  template <typename T, typename U, size_t Size>\n  typename vector<T, Size>::value_type\n  distance_square(vector<T, Size> const &a, vector<U, Size> const &b) {\n    return magnitude_square(a - b);\n  }\n  template <typename T, typename U, size_t Size>\n  typename vector<T, Size>::value_type\n  distance(vector<T, Size> const &a, vector<U, Size> const &b) {\n    return magnitude(a - b);\n  }\n  template <typename T, size_t Size>\n  vector<typename vector<T, Size>::value_type, Size>\n  normalize(vector<T, Size> const &v) {\n    return v.normalize();\n  }\n  /**\n * Cross product for 3D vectors\n * @param a\n * @param b\n * @return\n */\n  template <typename T, typename U>\n  vector<typename vector<T, 3>::value_type, 3>\n  cross(vector<T, 3> const &a, vector<U, 3> const &b) {\n    vector<T, 3> res{\n        a.template at<1>() * b.template at<2>() - a.template at<2>() * b.template at<1>(),\n        a.template at<2>() * b.template at<0>() - a.template at<0>() * b.template at<2>(),\n        a.template at<0>() * b.template at<1>() - a.template at<1>() * b.template at<0>()};\n    return res;\n  }\n  /**\n * Cross product for homogenous 3D vectors\n * @param a\n * @param b\n * @return\n */\n  template <typename T, typename U>\n  vector<typename vector<T, 4>::value_type, 4>\n  cross(vector<T, 4> const &a, vector<U, 4> const &b) {\n    vector<T, 4> res{\n        a.template at<1>() * b.template at<2>() - a.template at<2>() * b.template at<1>(),\n        a.template at<2>() * b.template at<0>() - a.template at<0>() * b.template at<2>(),\n        a.template at<0>() * b.template at<1>() - a.template at<1>() * b.template at<0>(),\n        typename vector<T, 4>::value_type(1)};\n    return res;\n  }\n  /**\n * Projection of vector v onto vector n\n * @param n Target vector\n * @param v Source vector\n * @return Vector that is parallel to n\n */\n  template <typename T, size_t Size>\n  vector<typename vector<T, Size>::value_type, Size>\n  projection(vector<T, Size> const &n, vector<T, Size> const &v) {\n    return n * (v * n / n.magnitude_square());\n  }\n  /**\n * Vector that is perpendicular to n, such as vǁ + vⱶ = v\n * @param n\n * @param v\n * @return\n */\n  template <typename T, size_t Size>\n  vector<typename vector<T, Size>::value_type, Size>\n  perpendicular(vector<T, Size> const &n, vector<T, Size> const &v) {\n    return v - projection(n, v);\n  }\n  /**\n * Project vector v onto vector n\n * @param n\n * @param v\n * @return Pair of vectors vǁ, vⱶ. vǁ is parallel to n, vǁ + vⱶ = v\n */\n  template <typename T, size_t Size>\n  std::pair<\n      vector<typename vector<T, Size>::value_type, Size>,\n      vector<typename vector<T, Size>::value_type, Size>>\n  project(vector<T, Size> const &n, vector<T, Size> const &v) {\n    auto p = projection(n, v);\n    return std::make_pair(p, v - p);\n  }\n} // namespace mathic\n#endif", "meta": {"hexsha": "f4058d21bdd2213530cbd9f17b3b2468a9aef7b2", "size": 16786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathic/vector.hpp", "max_stars_repo_name": "Tremium/mathic", "max_stars_repo_head_hexsha": "dc009383194c9b3769afbbb81a27d6cbae0ac540", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-04T00:38:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-04T00:38:26.000Z", "max_issues_repo_path": "include/mathic/vector.hpp", "max_issues_repo_name": "Tremium/mathic", "max_issues_repo_head_hexsha": "dc009383194c9b3769afbbb81a27d6cbae0ac540", "max_issues_repo_licenses": ["MIT"], "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/mathic/vector.hpp", "max_forks_repo_name": "Tremium/mathic", "max_forks_repo_head_hexsha": "dc009383194c9b3769afbbb81a27d6cbae0ac540", "max_forks_repo_licenses": ["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.7315689981, "max_line_length": 152, "alphanum_fraction": 0.6013344454, "num_tokens": 4482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.02368946918846535, "lm_q1q2_score": 0.010462999059069028}}
{"text": "#include <vector>\n#include <string>\n#include \"LatLon.h\"\n#include <math.h>\n#include \"StreetsDatabaseAPI.h\"\n#include <string>\n#include <iostream>\n#include <iterator>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <sstream>\n#include <iomanip>\n#include <boost/algorithm/string.hpp>\n#include <X11/Xlib.h>\n#include \"graphics.h\"\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n#include \"global_functions.h\"\n#include \"m1.h\"\n#include \"m2.h\"\n#include \"m3.h\"\n#include \"m4.h\"\n#include <sstream>\n#include <chrono>\n#define TURN_PENALTY 15\n//pass in start time to make sure thread kicks out before taking too long\n\nstruct thread_argument {\n    std::vector<unsigned> tour;\n    std::vector<unsigned> tour2;\n    bool first_iter;\n    std::vector<DeliveryInfo> deliveries;\n    double turn_penalty;\n    std::vector<unsigned> result;\n    unsigned start_loc;\n};\n\nstd::unordered_map<unsigned, std::vector<unsigned>> pickups_dropoffs;\nstd::unordered_map<unsigned, std::vector<unsigned>> dropoffs_pickups;\nstd::map<unsigned, std::vector<std::pair<unsigned, std::vector<StreetSegmentIndex>>>> fastest_paths_list;\nstd::unordered_set<unsigned> pickups;\nstd::unordered_set<unsigned> dropoffs_list;\n\nbool solution_sort(std::pair<std::vector<unsigned>, double> p1, std::pair<std::vector<unsigned>, double> p2);\ndouble tour_cost_finder(std::vector<unsigned> path, double turn_penalty);\nstd::vector<unsigned> add_depots(std::vector<unsigned> tour, std::vector<unsigned> depots, double turn_penalty);\nbool tour_legality(std::vector<unsigned> tour, const std::vector<DeliveryInfo>& deliveries);\nunsigned find_target(std::vector<unsigned> path, unsigned start);\nstd::vector<unsigned> find_path_between_all_intersections(const unsigned intersect_id_start, std::unordered_set<unsigned> target_list, const double turn_penalty);\nvoid fastest_list_init(const std::vector<DeliveryInfo>& deliveries, const float turn_penalty);\nstatic void* thread1(void* package);\nstatic void* thread2(void* package);\nstatic void* thread3(void* package);\nstatic void* thread4(void* package);\nstatic void* thread5(void* package);\nstatic void* thread6(void* package);\nstatic void* thread7(void* package);\n\n/**\n * \n */\n\nbool solution_sort(std::pair<std::vector<unsigned>, double> p1, std::pair<std::vector<unsigned>, double> p2) {\n    if (p1.second < p2.second) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\nstd::vector<unsigned> traveling_courier(const std::vector<DeliveryInfo>& deliveries,\n        const std::vector<unsigned>& depots,\n        const float turn_penalty) {\n    std::vector<unsigned> empty;\n    //std::cout << deliveries.size() << \"\\n\";\n    auto start_time = std::chrono::high_resolution_clock::now();\n    fastest_list_init(deliveries, turn_penalty);\n    auto time2 = std::chrono::high_resolution_clock::now();\n    \n    //std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(time2 - start_time).count() << \"\\n\";\n\n    //Need to figure out closest depot then from there\n    //search for the closest pick up (remember to update sets for drop off)\n    //Now check if the drop off or next pick up is closer\n    //And go to that, then search for the next closest pick up\n\n    std::vector<unsigned> path; //This stores all the paths you will go to\n    std::vector<unsigned> valid;\n\n    for (unsigned i = 0; i < deliveries.size(); ++i) {\n        pickups_dropoffs[deliveries[i].pickUp].push_back(deliveries[i].dropOff);\n        dropoffs_pickups[deliveries[i].dropOff].push_back(deliveries[i].pickUp);\n        //std::cout << deliveries[i].dropOff << \" \" << deliveries[i].pickUp<<\"\\n\";\n        if (pickups.find(deliveries[i].pickUp) == pickups.end()) {\n            pickups.insert(deliveries[i].pickUp);\n        }\n        dropoffs_list.insert(deliveries[i].dropOff);\n        valid.push_back(deliveries[i].pickUp);\n    }\n    std::vector<unsigned> starting_path;\n    unsigned count = 0;\n    do {\n        std::vector<unsigned> targets(pickups.begin(), pickups.end());\n        starting_path = find_path_between_intersections(depots[count], targets, turn_penalty); //FIX THIS TO SELECT BEST DEPOT\n        count++;\n        if (count > depots.size()) return empty;\n    } while (starting_path.empty());\n\n    path.push_back(depots[count - 1]);\n\n    std::unordered_set<unsigned> valid_pickups = pickups;\n    std::unordered_set<unsigned> valid_dropoffs;\n    int counter = 0;\n    while (!valid.empty()) {\n        //std::cout<< \"\\n\";\n        valid.clear();\n        valid.insert(valid.end(), valid_pickups.begin(), valid_pickups.end());\n        valid.insert(valid.end(), valid_dropoffs.begin(), valid_dropoffs.end());\n\n\n        if (valid.empty()) {\n            break;\n        }\n        /*std::cout << \"VALID: \";\n        for (unsigned i = 0; i < valid.size(); i++) {\n            std::cout << valid[i] << \" \";\n        }\n        std::cout << \"\\n\";\n        std::cout << \"PATH: \";\n        for (unsigned i = 0; i < path.size(); i++) {\n            std::cout << path[i] << \" \";\n        }\n        std::cout << \"\\n\";*/\n\n        std::vector<unsigned> closest_pick_up_from_depot = find_path_between_intersections(path.back(), valid, turn_penalty);\n        counter++;\n        //std::cout << counter << \"\\n\";\n        unsigned next_stop = find_target(closest_pick_up_from_depot, path.back());\n\n        if (valid_pickups.find(next_stop) != valid_pickups.end()) {\n            valid_pickups.erase(next_stop);\n            std::vector<unsigned> add_to_dropoffs = pickups_dropoffs[next_stop];\n            for (unsigned i = 0; i < add_to_dropoffs.size(); i++) {\n                valid_dropoffs.insert(add_to_dropoffs[i]);\n            }\n            valid_pickups.erase(next_stop);\n        }\n        if (valid_dropoffs.find(next_stop) != valid_dropoffs.end()) {\n\n            std::vector<unsigned> remove_pickups = dropoffs_pickups[next_stop];\n            for (unsigned i = 0; i < remove_pickups.size(); i++) {\n                if (valid_pickups.find(remove_pickups[i]) == valid_pickups.end()) {\n                    valid_pickups.erase(remove_pickups[i]);\n                }\n            }\n            valid_dropoffs.erase(next_stop);\n        }\n        path.push_back(next_stop);\n    }\n\n\n    /*std::vector<unsigned> final_path;*/\n    path.erase(path.begin(), path.begin() + 1);\n    /* std::cout << \"greedy path: \";\n     for (unsigned i = 0; i < path.size(); ++i) {\n         // std::vector<unsigned>temp = find_path_between_intersections(path[i], path[i + 1], turn_penalty);\n         //final_path.insert(final_path.end(), temp.begin(), temp.end());\n         std::cout << path[i] << \" \";\n     }\n     std::cout << \"\\n\";*/\n    //return final_path;\n    auto time3 = std::chrono::high_resolution_clock::now();\n    //std::cout << \"IMPROVEMENT TIME! \" << std::chrono::duration_cast<std::chrono::milliseconds>(time3 - start_time).count() << \"\\n\";\n\n    //solution improvement\n    std::vector<unsigned> best_known_path = path;\n    double best_cost = tour_cost_finder(path, turn_penalty);\n    std::vector<unsigned> localSearch_path = path;\n    std::vector<std::pair<std::vector<unsigned>, double> > sol_list;\n    count = 0;\n    int kick = 0;\n    int perturbation = 0;\n    int improvement = 0;\n    while (1 > 0) {\n        auto current_time = std::chrono::high_resolution_clock::now();\n        if (std::chrono::duration_cast<std::chrono::milliseconds>(current_time - start_time).count() > 29000) {\n            //std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(current_time - start_time).count() << \" asdfsdf\\n\";\n            //std::cout << \"PERTURBATIONS: \" << perturbation << \"\\n\";\n            //std::cout << improvement << \" improvements\\n\";\n            break; //from improvement loop\n        }\n\n        //std::cout<<\"thread start\\n\";\n        auto after_time = std::chrono::high_resolution_clock::now();\n\n        pthread_t threads[8];\n        pthread_attr_t attr;\n        void *status;\n\n        pthread_attr_init(&attr);\n        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n        thread_argument* arg1 = new thread_argument;\n        arg1->deliveries.insert(arg1->deliveries.begin(), deliveries.begin(), deliveries.end());\n        arg1->tour = localSearch_path;\n        arg1->turn_penalty = turn_penalty;\n\n        pthread_create(&threads[0], NULL, thread1, static_cast<void*> (arg1));\n\n        thread_argument* arg2 = new thread_argument;\n        arg2->deliveries.insert(arg2->deliveries.begin(), deliveries.begin(), deliveries.end());\n        arg2->tour = localSearch_path;\n        arg2->turn_penalty = turn_penalty;\n\n        pthread_create(&threads[1], NULL, thread7, static_cast<void*> (arg2));\n\n        thread_argument* arg3 = new thread_argument;\n        arg3->deliveries.insert(arg3->deliveries.begin(), deliveries.begin(), deliveries.end());\n        arg3->tour = localSearch_path;\n        arg3->turn_penalty = turn_penalty;\n\n        pthread_create(&threads[2], NULL, thread1, static_cast<void*> (arg3));\n\n        thread_argument* arg4 = new thread_argument;\n        arg4->deliveries.insert(arg4->deliveries.begin(), deliveries.begin(), deliveries.end());\n        arg4->tour = localSearch_path;\n        arg4->turn_penalty = turn_penalty;\n\n        pthread_create(&threads[3], NULL, thread7, static_cast<void*> (arg4));\n\n        thread_argument* arg5 = new thread_argument;\n        arg5->deliveries.insert(arg5->deliveries.begin(), deliveries.begin(), deliveries.end());\n        arg5->tour = localSearch_path;\n        arg5->turn_penalty = turn_penalty;\n\n        pthread_create(&threads[4], NULL, thread1, static_cast<void*> (arg5));\n\n        thread_argument* arg6 = new thread_argument;\n        arg6->deliveries.insert(arg6->deliveries.begin(), deliveries.begin(), deliveries.end());\n        arg6->tour = localSearch_path;\n        arg6->turn_penalty = turn_penalty;\n\n        pthread_create(&threads[5], NULL, thread7, static_cast<void*> (arg6));\n\n\n        thread_argument* arg7 = new thread_argument;\n        arg7->deliveries.insert(arg7->deliveries.begin(), deliveries.begin(), deliveries.end());\n        arg7->tour = localSearch_path;\n        arg7->turn_penalty = turn_penalty;\n\n\n        pthread_create(&threads[6], NULL, thread1, static_cast<void*> (arg7));\n\n\n        pthread_attr_destroy(&attr);\n        sol_list.clear();\n\n\n        pthread_join(threads[0], &status);\n        std::vector<unsigned> sol1 = arg1->result;\n        double new_cost = tour_cost_finder(sol1, turn_penalty);\n        sol_list.push_back(std::make_pair(sol1, new_cost));\n\n        pthread_join(threads[1], &status);\n        std::vector<unsigned> sol2 = arg2->result;\n        double new_cost1 = tour_cost_finder(sol2, turn_penalty);\n        sol_list.push_back(std::make_pair(sol2, new_cost1));\n\n        pthread_join(threads[2], &status);\n        std::vector<unsigned> sol3 = arg3->result;\n        double new_cost2 = tour_cost_finder(sol3, turn_penalty);\n        sol_list.push_back(std::make_pair(sol3, new_cost2));\n\n        pthread_join(threads[3], &status);\n        std::vector<unsigned> sol4 = arg4->result;\n        double new_cost3 = tour_cost_finder(sol4, turn_penalty);\n        sol_list.push_back(std::make_pair(sol4, new_cost3));\n\n        pthread_join(threads[4], &status);\n        std::vector<unsigned> sol5 = arg5->result;\n        double new_cost4 = tour_cost_finder(sol5, turn_penalty);\n        sol_list.push_back(std::make_pair(sol5, new_cost4));\n\n        pthread_join(threads[5], &status);\n        std::vector<unsigned> sol6 = arg6->result;\n        double new_cost5 = tour_cost_finder(sol6, turn_penalty);\n        sol_list.push_back(std::make_pair(sol6, new_cost5));\n\n        pthread_join(threads[6], &status);\n        std::vector<unsigned> sol7 = arg7->result;\n        double new_cost6 = tour_cost_finder(sol7, turn_penalty);\n        sol_list.push_back(std::make_pair(sol7, new_cost6));\n\n\n        delete arg1;\n        delete arg2;\n        delete arg3;\n        delete arg4;\n        delete arg5;\n        delete arg6;\n        delete arg7;\n\n        std::sort(sol_list.begin(), sol_list.end(), solution_sort);\n\n        if (sol_list[0].second == best_cost) {\n            count++;\n            kick++;\n        }\n\n        if (sol_list[0].second < best_cost) {\n            //std::cout << \"NEW PATH FOUND!\\n\";\n            improvement++;\n            best_known_path = sol_list[0].first;\n            best_cost = sol_list[0].second;\n            count = 0;\n            kick = 0;\n        }\n        \n        if (kick >= 1000){\n            break;\n        }\n        \n        \n        auto time2x = std::chrono::high_resolution_clock::now();\n        double time_rem = 30000 - std::chrono::duration_cast<std::chrono::milliseconds>(time2x - start_time).count();\n        double probability = exp((best_cost - sol_list[0].second) / (time_rem));\n        //std::cout << probability << \" BEST COST: \" << best_cost << \" NEW COST: \" << sol_list[0].second << \" TIME REMAINING: \" << time_rem << \"\\n\";\n        std::random_device rd;\n        std::mt19937 re(rd());\n        std::uniform_real_distribution<double> unif(0, 1);\n        double num = unif(re);\n        //std::cout << \"NUM: \" << num << \"\\n\";\n        if (sol_list[0].second < best_cost) {\n            localSearch_path = localSearch_path = sol_list[0].first;\n        } else if (count >= 10) {\n            localSearch_path = sol_list[1].first;\n            count = 0;\n        } else if (num < probability) {\n            localSearch_path = sol_list[0].first;\n            //std::cout << \"\\nEXPLORING!\\n\\n\";\n        } else {\n\n            localSearch_path = localSearch_path;\n        }\n\n\n        /*\n     \n         multi threaded calls to change functions here\n     \n     \n         */\n\n\n        //make sure to check each solution with best known solution\n\n        //keep track how many times the best solution of 8 matches the best solution known to date, its possible we are at the global minimum\n\n        /*std::vector<unsigned> weights = {20, 17}; //, 13, 11, 11, 11, 9, 8};\n        int weight_sum = 0;\n        current_time = std::chrono::high_resolution_clock::now();\n        double time_left = std::chrono::duration_cast<std::chrono::milliseconds>(current_time - start_time).count();\n        for (unsigned i = 0; i < weights.size(); i++) {\n            weights[i] = weights[i] + round((time_left / 1000) * i / 24);\n            weight_sum = weight_sum + weights[i];\n        }\n\n        std::uniform_int_distribution<std::mt19937::result_type> distribution(0, weight_sum - 1);\n        std::mt19937 rng;\n        rng.seed(std::random_device()());\n        unsigned rand = distribution(rng);\n        unsigned index = 0;\n        for (unsigned i = 0; i < weights.size(); i++) {\n            if (rand < weights[i]) {\n                index = i;\n            }\n            rand = rand - weights[i];\n        }*/\n        //std::cout << \"NEW SOLUTION TO EXPLORE! \" << index << \"\\n\";\n        //localSearch_path = sol_list[0].first;\n        perturbation++;\n\n    }\n\n    if (best_known_path.empty()) {\n        return best_known_path;\n    }\n\n    /*for (int i = 0; i < best_known_path.size(); i++) {\n        std::cout << best_known_path[i] << \"\\n\";\n    }*/\n\n\n    std::vector<unsigned> full_tour = add_depots(best_known_path, depots, turn_penalty);\n    std::vector<unsigned> result;\n\n    result = find_path_between_intersections(full_tour[0], full_tour[1], turn_penalty);\n    for (unsigned i = 1; i < full_tour.size() - 2; i++) {\n\n        std::vector<unsigned> temp;\n        std::vector<std::pair<unsigned, std::vector<unsigned>>> next_stops = fastest_paths_list[full_tour[i]];\n        for (unsigned j = 0; j < next_stops.size(); j++) {\n            //std::cout << \"ADJACENT: \" << next_stops[j].first << \"\\n\";\n            if (next_stops[j].first == full_tour[i + 1]) {\n                temp = next_stops[j].second;\n                break;\n            }\n        }\n        result.insert(result.end(), temp.begin(), temp.end());\n    }\n    std::vector<unsigned> temp = find_path_between_intersections(full_tour[full_tour.size() - 2], full_tour.back(), turn_penalty);\n    result.insert(result.end(), temp.begin(), temp.end());\n    //std::cout << getStreetSegmentInfo(result[0]).from << \" \" << getStreetSegmentInfo(result[0]).to <<\" \" <<  getStreetSegmentInfo(result[1]).from << \" \" << getStreetSegmentInfo(result[1]).to;\n\n    /*std::cout << \"best_tour: \";\n    for (unsigned k = 0; k < best_known_path.size(); k++) {\n        std::cout << best_known_path[k] << \" \";\n    }\n    std::cout << \"\\n\\n\";*/\n    valid_dropoffs.clear();\n    pickups.clear();\n    pickups_dropoffs.clear();\n    dropoffs_pickups.clear();\n    fastest_paths_list.clear();\n    return result;\n}\n\nunsigned find_target(std::vector<unsigned> path, unsigned start) {\n    if (path.size() == 1) {\n        StreetSegmentInfo s = getStreetSegmentInfo(path[0]);\n        if (s.from == start) {\n            return s.to;\n        } else {\n            return s.from;\n        }\n    } else {\n        //std::cout << path.size() << \" PATH SIZE IN FIND TARGET FUNC\\n\";\n        StreetSegmentInfo last_seg = getStreetSegmentInfo(path.back());\n        StreetSegmentInfo other_seg = getStreetSegmentInfo(path[path.size() - 2]);\n        //std::cout << last_seg.to << \" \" << last_seg.from << \" \" << other_seg.to << \" \" << other_seg.from << \"\\n\";\n        if (last_seg.from == other_seg.from) {\n            return last_seg.to;\n        } else if (last_seg.from == other_seg.to) {\n            return last_seg.to;\n        } else if (last_seg.to == other_seg.to) {\n            return last_seg.from;\n        } else {\n            return last_seg.from;\n        }\n    }\n}\n\n\n//package is going to be all of the arguments packed into one variable\n// struct package { tour, deliveries}\n//returns new tour\n\nstatic void* thread1(void* package) {\n\n    thread_argument* arg = static_cast<thread_argument*> (package);\n//    auto start_time = std::chrono::high_resolution_clock::now();\n\n\n    int start_index;\n    std::mt19937 rng;\n    rng.seed(std::random_device()());\n    std::uniform_int_distribution<std::mt19937::result_type> dist6(0, arg->tour.size() - 2);\n\n    start_index = dist6(rng);\n    std::vector<unsigned> new_tour = arg->tour;\n    //std::cout << \"SELECTED INTERSECTion: \" << arg->tour[start_index]<<\"\\n\";\n\n    if (pickups.find(arg->tour[start_index]) != pickups.end() && dropoffs_list.find(arg->tour[start_index]) != dropoffs_list.end()) {\n\n    } else if (pickups.find(arg->tour[start_index]) != pickups.end()) {\n\n        if (dropoffs_list.find(arg->tour[start_index + 1]) != dropoffs_list.end()) {\n            //std::cout << start_index + 1 << \"\\n\";\n            std::vector<unsigned> check = dropoffs_pickups[arg->tour[start_index + 1]];\n            //std::cout << check.size() << \"\\n\";\n            for (unsigned i = 0; i < check.size(); i++) {\n                //std::cout<<check[i]<<\"\\n\";\n                if (check[i] == arg->tour[start_index]) {\n                    arg->result = arg->tour;\n                    return (static_cast<void*> (arg->tour.data()));\n                }\n            }\n\n        }\n        std::reverse(new_tour.begin() + start_index, new_tour.begin() + start_index + 2);\n    } else {\n\n        if (pickups.find(arg->tour[start_index + 1]) != pickups.end()) {\n            std::vector<unsigned> check = pickups_dropoffs[arg->tour[start_index + 1]];\n            for (unsigned i = 0; i < check.size(); i++) {\n                if (check[i] == arg->tour[start_index]) {\n                    arg->result = arg->tour;\n                    return (static_cast<void*> (arg->tour.data()));\n                }\n            }\n\n        }\n        std::reverse(new_tour.begin() + start_index, new_tour.begin() + start_index + 2);\n    }\n    arg->result = new_tour;\n    return (static_cast<void*> (new_tour.data()));\n\n\n}\n\nstatic void* thread2(void* package) {\n    thread_argument* arg = static_cast<thread_argument*> (package);\n    std::vector<unsigned> result;\n\n    if (arg->first_iter) { //DO RANDOM SWAP\n\n        arg->result = arg->tour;\n        //std::cout << \"first exit \\n\";\n        return static_cast<void*> (arg->tour.data());\n    } else {\n        //std::cout <<\"THREAD2 BEGUN\\n\";\n        int rand_bound1 = round(0.3 * arg->tour.size());\n        int rand_bound2 = round(0.6 * arg->tour.size());\n        std::mt19937 rng;\n        rng.seed(std::random_device()());\n        std::uniform_int_distribution<std::mt19937::result_type> dist6(rand_bound1, rand_bound2);\n\n        int cpy_index = dist6(rng);\n        result.insert(result.end(), arg->tour.begin(), arg->tour.begin() + cpy_index);\n        std::unordered_set<unsigned> temp(result.begin(), result.end());\n        std::cout << arg->tour2.size() << \"\\n\";\n        for (unsigned i = 0; i < arg->tour2.size(); i++) {\n            if (temp.find(arg->tour2[i]) == temp.end()) {\n                temp.insert(arg->tour2[i]);\n                result.push_back(arg->tour2[i]);\n            }\n        }\n        std::cout << \"NEW TOUR thread2: \";\n        for (unsigned i = 0; i < result.size(); i++) {\n            std::cout << result[i] << \" \";\n        }\n        std::cout << \"\\n\";\n        arg->result = result;\n        return static_cast<void*> (result.data());\n    }\n}\n\n\n//computes path cost from a vector of intersection ids\n\ndouble tour_cost_finder(std::vector<unsigned> path, double turn_penalty) {\n    double cost = 0;\n    //std::cout<<\"COST FINDER PATH SIZE: \" << path.size() << \"\\n\";\n    for (unsigned i = 0; i < path.size() - 1; i++) {\n        //std::cout << path[i] << \" \";\n        std::vector<unsigned> segments_path;\n        std::vector<std::pair<unsigned, std::vector<unsigned>>> next_stops = fastest_paths_list[path[i]];\n        for (unsigned j = 0; j < next_stops.size(); j++) {\n            //std::cout << \"ADJACENT: \" << next_stops[j].first << \"\\n\";\n            if (next_stops[j].first == path[i + 1]) {\n                segments_path = next_stops[j].second;\n                break;\n            }\n        }\n\n\n        cost = cost + compute_path_travel_time(segments_path, turn_penalty);\n    }\n    //std::cout << cost <<\"\\n\";\n    return cost;\n}\n\n//tour legality function (ASSUMES NO DEPOTS AT END)\n\nbool tour_legality(std::vector<unsigned> tour, const std::vector<DeliveryInfo>& deliveries) {\n    std::unordered_set<unsigned> pickups1; //these should be global\n    std::unordered_map<unsigned, unsigned> dropoffs;\n    for (unsigned i = 0; i < deliveries.size(); i++) {\n        pickups1.insert(deliveries[i].pickUp);\n        dropoffs[deliveries[i].dropOff] = deliveries[i].pickUp;\n    }\n    std::unordered_set<unsigned> done_pickups;\n    for (unsigned i = 0; i < tour.size(); i++) {\n        std::unordered_set<unsigned>::iterator it = pickups1.find(tour[i]);\n        if (it == pickups1.end()) {\n            unsigned pickup = dropoffs[tour[i]]; //ASSUMING TOUR HAS INTERSECTIONS THAT ARE PART OF DELIVERIES AND NO OTHER INTERSECTIONS\n            if (done_pickups.find(pickup) == done_pickups.end()) { //if drop is made before pickup\n                return false;\n            }\n        } else {\n            done_pickups.insert(*it);\n        }\n    }\n    return true;\n}\n\n//adds depots to the two ends of the tour\n\nstd::vector<unsigned> add_depots(std::vector<unsigned> tour, std::vector<unsigned> depots, double turn_penalty) {\n    double cost = std::numeric_limits<double>::infinity();\n    unsigned start_depot = 0;\n    std::vector<unsigned> segments_path;\n    for (unsigned i = 0; i < depots.size(); i++) {\n        std::vector<unsigned> temp = find_path_between_intersections(depots[i], tour[0], turn_penalty);\n        if (!temp.empty()) {\n            double new_cost = compute_path_travel_time(temp, turn_penalty);\n            if (new_cost < cost) {\n                start_depot = i;\n                segments_path = temp;\n                cost = new_cost;\n            }\n        }\n    }\n\n    unsigned depot_init = depots[start_depot]; //function call\n    segments_path = find_path_between_intersections(tour.back(), depots, turn_penalty);\n    unsigned depot_final = find_target(segments_path, tour.back()); //function call\n    //std::cout<<depot_final<<\"\\n\";\n    tour.push_back(depot_final);\n    std::vector<unsigned> result;\n    result.push_back(depot_init);\n    result.insert(result.begin() + 1, tour.begin(), tour.end());\n    return result;\n}\n\nstd::vector<unsigned> find_path_between_all_intersections(const unsigned intersect_id_start,\n        std::unordered_set<unsigned> target_list,\n        const double turn_penalty) {\n    std::vector<unsigned> path;\n    typedef double DVal; //short for Dijkstra Value which is the temporary value assigned to vertices when the algorithm is working\n    typedef std::pair<DVal, IntersectionIndex> Node;\n\n\n    std::vector<DVal> dijkstraValue;\n    std::vector<std::pair<StreetSegmentIndex, IntersectionIndex>> parents;\n    std::priority_queue<Node, std::deque<Node>, std::greater < Node>> heap;\n    dijkstraValue.clear();\n    dijkstraValue.resize(getNumberOfIntersections(), std::numeric_limits<double>::infinity());\n    parents.clear();\n    parents.resize(getNumberOfIntersections());\n    //std::cout<<\"TARGETS SIZE \" << target_list.size() << \"\\n\";\n\n    heap.push(std::make_pair(0, intersect_id_start));\n    dijkstraValue[intersect_id_start] = 0;\n    IntersectionIndex currentNode;\n    while (!heap.empty()) {\n\n        currentNode = heap.top().second;\n        heap.pop();\n\n        //std::cout<<\"CURRENT NODE \" << currentNode << \"\\n\";\n\n\n        std::unordered_set<unsigned>::iterator element = target_list.find(currentNode);\n\n        if (element != target_list.end()) {\n\n            std::vector<unsigned> temp;\n            IntersectionIndex index = currentNode;\n            std::deque<Node_Edge_Object> node_list = adjacency_list[index];\n            while (index != intersect_id_start) {\n                temp.push_back(parents[index].first);\n                index = parents[index].second;\n            }\n            std::reverse(temp.begin(), temp.end());\n            fastest_paths_list[intersect_id_start].push_back(std::make_pair(*element, temp));\n            target_list.erase(element);\n\n            //std::cout<<\"ADDED PATH SIZE: \" << temp.size() <<\" FROM \" << intersect_id_start << \" TO \" << *element<<  \"\\n\";\n        }\n        if (target_list.empty()) {\n            break;\n        }\n        //get all adjacent nodes to current node\n        std::deque <Node_Edge_Object> node_list = adjacency_list[currentNode];\n        for (unsigned i = 0; i < node_list.size(); i++) {\n            double cost = dijkstraValue[currentNode] + node_list[i].weight;\n\n            //cost = cost + (find_distance_between_two_points(getIntersectionPosition(currentNode), getIntersectionPosition(intersect_id_end)));\n            //insert stuff about turn penalties here\n            StreetSegmentInfo prevStreetSeg = getStreetSegmentInfo(parents[currentNode].first);\n            StreetSegmentInfo newStreetSeg = getStreetSegmentInfo(node_list[i].SegId);\n            if (prevStreetSeg.streetID != newStreetSeg.streetID && currentNode != intersect_id_start) {\n                cost = cost + turn_penalty;\n            }\n\n\n\n            if (dijkstraValue[node_list[i].id] > cost) {\n                dijkstraValue[node_list[i].id] = cost;\n                heap.push(std::make_pair(dijkstraValue[node_list[i].id], node_list[i].id));\n                parents[node_list[i].id] = std::make_pair(node_list[i].SegId, currentNode);\n            }\n        }\n    }\n    return path;\n}\n\nvoid fastest_list_init(const std::vector<DeliveryInfo>& deliveries, const float turn_penalty) {\n    std::unordered_set<unsigned> unique_intersections;\n    std::vector<unsigned> unique_intersections_vector;\n    //std::cout<<\"CALLED INIT FUNC\\n\";\n    for (unsigned i = 0; i < deliveries.size(); i++) {\n        if (unique_intersections.find(deliveries[i].pickUp) == unique_intersections.end()) {\n            unique_intersections.insert(deliveries[i].pickUp);\n            unique_intersections_vector.push_back(deliveries[i].pickUp);\n        }\n        if (unique_intersections.find(deliveries[i].dropOff) == unique_intersections.end()) {\n            unique_intersections.insert(deliveries[i].dropOff);\n            unique_intersections_vector.push_back(deliveries[i].dropOff);\n        }\n    }\n    //std::cout << \"NUMBER OF CALLS: \" << unique_intersections_vector.size() << \"\\n\";\n#pragma omp parallel for\n    for (unsigned i = 0; i < unique_intersections_vector.size(); i++) {\n        std::unordered_set<unsigned> temp = unique_intersections;\n        temp.erase(unique_intersections_vector[i]);\n        //auto start_time = std::chrono::high_resolution_clock::now();\n        find_path_between_all_intersections(unique_intersections_vector[i], temp, turn_penalty);\n        /*auto time2 = std::chrono::high_resolution_clock::now();\n        std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(time2 - start_time).count() << \" FIND TIME\\n\";*/\n    }\n\n}\n//package is going to be all of the arguments packed into one variable\n// struct package { tour, deliveries}\n//returns new tour\n//implements insertion opt\n\nstatic void* thread3(void* package) {\n    thread_argument* arg = static_cast<thread_argument*> (package);\n    std::unordered_set<unsigned> pickup_list;\n    std::unordered_map<unsigned, std::vector<unsigned>> drop_pickup;\n    std::unordered_map<unsigned, unsigned> done_pickup_loc;\n    auto start_time = std::chrono::high_resolution_clock::now();\n\n    //std::cout << \"PICKUPS: \";\n    for (unsigned i = 0; i < arg->deliveries.size(); i++) {\n        unsigned pick = arg->deliveries[i].pickUp;\n        unsigned drop = arg->deliveries[i].dropOff;\n        pickup_list.insert(pick);\n        //std::cout << pick << \" \";\n        drop_pickup[drop].push_back(pick);\n    }\n    //std::cout<<\"\\n\";\n    std::vector<unsigned> best_tour = (*arg).tour;\n\n    std::vector<unsigned> side_list;\n    std::vector<unsigned> new_list;\n\n    std::mt19937 rng;\n    rng.seed(std::random_device()());\n    std::uniform_int_distribution<std::mt19937::result_type> distribution(0, best_tour.size() - 3);\n    bool legal_pathing = false;\n    //finding legal path\n    unsigned counter1 = 0;\n    while (legal_pathing == false && counter1 < (new_list.size() - 1)) {\n        auto current_time = std::chrono::high_resolution_clock::now();\n        if (std::chrono::duration_cast<std::chrono::milliseconds>(current_time - start_time).count() > 2500) {\n            arg->result = best_tour;\n            return (static_cast<void*> (best_tour.data()));\n        }\n\n        side_list.clear();\n        new_list.clear();\n        new_list = best_tour;\n        counter1++;\n        unsigned rand = distribution(rng);\n\n        int counter = 0;\n        while (counter < 3 && (counter + rand) < new_list.size()) {\n            counter++;\n        }\n        side_list.insert(side_list.begin(), new_list.begin() + rand, new_list.begin() + rand + counter);\n        new_list.erase(new_list.begin() + rand, new_list.begin() + rand + counter);\n        //insert the side list back into new_list then do the legal check\n        std::uniform_int_distribution<std::mt19937::result_type> dist(0, new_list.size() - 1);\n        rand = dist(rng);\n        new_list.insert(new_list.begin() + rand, side_list.begin(), side_list.end());\n\n        std::map<unsigned, unsigned> locations;\n        for (unsigned i = 0; i < new_list.size(); ++i) {\n            locations[new_list[i]] = i;\n        }\n        int numdrop = 0;\n        int numeach = 0;\n        //pickup_dropoffs\n        //drop_pickup\n//        auto current_time1 = std::chrono::high_resolution_clock::now();\n        for (unsigned i = 0; i < side_list.size(); ++i) {\n            //if drop off\n            if (drop_pickup.find(side_list[i]) != drop_pickup.end()) {\n                numdrop++;\n                //if the drop of index is greater than any of its pick ups\n                for (unsigned j = 0; j < drop_pickup[side_list[i]].size(); ++j) {\n                    //finding pick up with largest index\n                    unsigned p = 0;\n                    for (unsigned k = 1; (k) < locations.size(); ++k) {\n                        unsigned previous = locations[drop_pickup[side_list[i]][0]];\n                        if (previous < locations[drop_pickup[side_list[i]][k]]) {\n                            p = k;\n                        }\n                    }\n                    //Comparing to see if dropoff is after the largest indexed pickup\n                    if (locations[side_list[i]] > locations[drop_pickup[side_list[i]][p]]) {\n                        numeach++;\n                        break;\n                    }\n                }\n            }\n        }\n        if (numeach == numdrop) legal_pathing = true;\n        //\n        //check for if the side_list has any dropoffs\n    }\n\n    if (!legal_pathing) return (static_cast<void*> (best_tour.data()));\n    //std::cout << \"counter: \" << counter1 << \" rand: \" << rand << '\\n';\n    /*std::cout << \"new_tour: \";\n    for (unsigned k = 0; k < new_list.size(); k++) {\n        std::cout << new_list[k] << \" \";\n    }\n    std::cout << \"\\n\\n\";*/\n    double new_cost = tour_cost_finder(new_list, (*arg).turn_penalty);\n    best_tour = new_list;\n    /*    std::cout << \"new_tour: \";\n        for (unsigned k = 0; k < best_tour.size(); k++) {\n            std::cout << best_tour[k] << \" \";\n        }\n        std::cout << \"\\n\\n\";\n     */\n    arg->result = best_tour;\n    auto current_time2 = std::chrono::high_resolution_clock::now();\n    //std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(current_time2 - current_time1).count() << '\\n';\n    return (static_cast<void*> (best_tour.data()));\n}\n\nstatic void* thread4(void* package) {\n    thread_argument* arg = static_cast<thread_argument*> (package);\n\n    std::vector<unsigned> best_tour = (*arg).tour;\n    std::vector<unsigned>::iterator it;\n    std::mt19937 rng;\n    rng.seed(std::random_device()());\n    std::uniform_int_distribution<std::mt19937::result_type> distribution(0, best_tour.size() - 1);\n    bool pick = false;\n    while (pick == false) {\n        unsigned rand = distribution(rng);\n        std::vector<unsigned>::iterator hold = best_tour.begin() + rand;\n        unsigned hold_pickup = *(hold);\n        //if node is a pick up\n        if (pickups_dropoffs.find(hold_pickup) != pickups_dropoffs.end()) {\n            //erase it from the list\n            best_tour.erase(hold);\n            //add it to the front\n            best_tour.insert(best_tour.begin(), hold_pickup);\n            //find corresponding drop offs\n            std::vector<unsigned>::iterator hold_drop = std::find(best_tour.begin() + 1, best_tour.end(), pickups_dropoffs[hold_pickup][0]);\n            if (hold_drop != best_tour.end()) {\n                //erase it from current location\n                best_tour.erase(hold_drop);\n                //add it to back\n                best_tour.push_back(*hold_drop);\n                pick = true;\n            }\n        } else pick = false;\n    }\n    double new_cost = tour_cost_finder(best_tour, (*arg).turn_penalty);\n\n    /*    std::cout << \"new_tour: \";\n        for (unsigned k = 0; k < best_tour.size(); k++) {\n            std::cout << best_tour[k] << \" \";\n        }\n        std::cout << \"\\n\\n\";\n     */\n    arg->result = best_tour;\n    //std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count()\n    return (static_cast<void*> (best_tour.data()));\n}\n\nstatic void* thread5(void* package) {\n    //auto start_time = std::chrono::high_resolution_clock::now();\n    //completely random\n    thread_argument* arg = static_cast<thread_argument*> (package);\n    std::vector<unsigned> result;\n    std::vector<unsigned> valid;\n    std::unordered_set<unsigned> temp_pickups = pickups;\n    std::unordered_set<unsigned> temp_dropoffs;\n\n\n    valid.insert(valid.begin(), pickups.begin(), pickups.end());\n    //std::cout<<arg->deliveries.size()<<\"\\n\";\n    while (!valid.empty()) {\n        //std::cout<<\"adsadsa\\n\";\n        std::unordered_set<unsigned> valid_locs;\n        valid_locs.insert(temp_pickups.begin(), temp_pickups.end());\n        valid_locs.insert(temp_dropoffs.begin(), temp_dropoffs.end());\n\n        std::mt19937 rng;\n        rng.seed(std::random_device()());\n        std::uniform_int_distribution<std::mt19937::result_type> dist6(0, valid_locs.size() - 1);\n        unsigned index = dist6(rng);\n        //std::cout<<\"INDEX: \" << index << \" VALID SIZE \" << valid.size()<< \"\\n\";\n        unsigned inters = valid[index];\n        //std::cout << inters << \"\\n\";\n        result.push_back(inters);\n\n        if (temp_pickups.find(inters) != temp_pickups.end()) {\n            std::vector<unsigned> allDropoffs = pickups_dropoffs[inters];\n            //std::cout<<\"ALL DROPS FOR \" << inters <<\": \";\n            for (unsigned i = 0; i < allDropoffs.size(); i++) {\n                temp_dropoffs.insert(allDropoffs[i]);\n                //std::cout<<allDropoffs[i]<<\"\\n\";\n            }\n            //std::cout << temp_pickups.size() << \" BEFORE\\n\";\n            temp_pickups.erase(inters);\n            //std::cout << temp_pickups.size() << \" AFTER\\n\";\n        }\n        if (temp_dropoffs.find(inters) != temp_dropoffs.end()) {\n            temp_dropoffs.erase(inters);\n        }\n\n        valid.clear();\n        valid.insert(valid.end(), temp_pickups.begin(), temp_pickups.end());\n        valid.insert(valid.end(), temp_dropoffs.begin(), temp_dropoffs.end());\n    }\n    /*std::cout<<\"RESULT: \";\n    for (int i=0; i<result.size();i++){\n        std::cout<<result[i]<<\" \";\n    }\n    std::cout<<\"\\n\";*/\n    arg->result = result;\n    //auto time2 = std::chrono::high_resolution_clock::now();\n    //std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(time2 - start_time).count() << \" THREAD TIME\\n\";\n    return static_cast<void*> (result.data());\n}\n\nstatic void* thread6(void* package) {\n    thread_argument* arg = static_cast<thread_argument*> (package);\n    std::unordered_map<unsigned, unsigned> inter_to_index;\n    std::vector<unsigned> result;\n    std::vector<unsigned>::iterator index;\n    double cost = 0;\n    //std::cout << arg->tour.size() << \"\\n\";\n    for (std::vector<unsigned>::iterator i = arg->tour.begin(); i != arg->tour.end() - 1; i++) {\n        //std::cout <<\"daagasgdas\" << \"\\n\";\n        std::vector<unsigned> temp;\n        temp.push_back(*i);\n        temp.push_back(*(i + 1));\n        double new_cost = tour_cost_finder(temp, arg->turn_penalty);\n        if (new_cost > cost) {\n            cost = new_cost;\n            index = i;\n\n        }\n        inter_to_index[*i] = i - arg->tour.begin();\n    }\n    std::cout << \"INDEX: \" << *index << \"\\n\";\n    unsigned inters = *index;\n    //std::cout << \"INTERS: \" << inters << \"\\n\";\n    /*std::cout << \"before       \";\n    for (int i = 0; i < arg->tour.size(); i++) {\n        std::cout << arg->tour[i] << \" \";\n    }\n    std::cout << \"\\n\";*/\n    if (pickups.find(inters) != pickups.end() && dropoffs_list.find(inters) != dropoffs_list.end()) {\n        std::vector<unsigned> last_drops_pickups = dropoffs_pickups[arg->tour.back()];\n        unsigned last_pick = 0;\n        for (unsigned i = 0; i < last_drops_pickups.size(); i++) {\n            if (last_pick < inter_to_index[last_drops_pickups[i]]) {\n                last_pick = inter_to_index[last_drops_pickups[i]];\n            }\n        }\n        result.insert(result.end(), arg->tour.begin(), arg->tour.begin() + last_pick + 1);\n        result.push_back(arg->tour.back());\n        arg->tour.pop_back();\n        result.insert(result.end(), arg->tour.begin() + last_pick + 1, arg->tour.end());\n        std::cout << \"after1       \";\n        for (unsigned i = 0; i < result.size(); i++) {\n            std::cout << result[i] << \" \";\n        }\n        std::cout << \"\\n\";\n    } else if (pickups.find(inters) != pickups.end()) {\n        std::vector<unsigned> all_drops = pickups_dropoffs[inters];\n        unsigned first_drop = arg->tour.size();\n        for (unsigned i = 0; i < all_drops.size(); i++) {\n            if (first_drop > inter_to_index[all_drops[i]]) {\n                first_drop = inter_to_index[all_drops[i]];\n            }\n        }\n        std::vector< std::pair<unsigned, std::vector<StreetSegmentIndex> > >::iterator it;\n        int new_pos = 0;\n        for (it = fastest_paths_list[inters].begin(); it != fastest_paths_list[inters].end(); it++) {\n            if (inter_to_index[(*it).first] < first_drop) {\n                new_pos = inter_to_index[(*it).first] - 1;\n                break;\n            }\n        }\n        if (new_pos != -1) {\n            result.insert(result.end(), arg->tour.begin(), arg->tour.begin() + new_pos);\n            result.push_back(inters);\n            arg->tour.erase(index);\n            result.insert(result.end(), arg->tour.begin() + new_pos, arg->tour.end());\n            std::cout << \"after2       \";\n            for (unsigned i = 0; i < result.size(); i++) {\n                std::cout << result[i] << \" \";\n            }\n            std::cout << \"\\n\";\n        } else if (new_pos == -1) {\n            result.push_back(inters);\n            arg->tour.erase(index);\n            result.insert(result.end(), arg->tour.begin(), arg->tour.end());\n            std::cout << \"after3       \";\n            for (unsigned i = 0; i < result.size(); i++) {\n                std::cout << result[i] << \" \";\n            }\n            std::cout << \"\\n\";\n        }\n    } else {\n        std::vector<unsigned> all_picks = dropoffs_pickups[inters];\n        unsigned latest_pick = 0;\n        for (unsigned i = 0; i < all_picks.size(); i++) {\n            if (latest_pick < inter_to_index[all_picks[i]]) {\n                latest_pick = inter_to_index[all_picks[i]];\n            }\n        }\n        std::vector< std::pair<unsigned, std::vector<StreetSegmentIndex> > >::iterator it;\n        int new_pos = 0;\n        for (it = fastest_paths_list[inters].begin(); it != fastest_paths_list[inters].end(); it++) {\n            if (inter_to_index[(*it).first] > latest_pick) {\n                new_pos = inter_to_index[(*it).first] - 1;\n                break;\n            }\n        }\n        std::cout << \"new pos\" << new_pos << \"\\n\";\n        if ((new_pos) != -1) {\n            result.insert(result.end(), arg->tour.begin(), arg->tour.begin() + new_pos);\n            result.push_back(inters);\n            arg->tour.erase(index);\n            result.insert(result.end(), arg->tour.begin() + new_pos, arg->tour.end());\n            std::cout << \"after4       \";\n            for (unsigned i = 0; i < result.size(); i++) {\n                std::cout << result[i] << \" \";\n            }\n            std::cout << \"\\n\";\n        } else if (new_pos == -1) {\n            result.push_back(inters);\n            arg->tour.erase(index);\n            result.insert(result.end(), arg->tour.begin(), arg->tour.end());\n            std::cout << \"after5       \";\n            for (unsigned i = 0; i < result.size(); i++) {\n                std::cout << result[i] << \" \";\n            }\n            std::cout << \"\\n\";\n        }\n    }\n    std::cout << \"final        \";\n    for (unsigned i = 0; i < result.size(); i++) {\n        std::cout << result[i] << \" \";\n    }\n    std::cout << \"\\n\\n\";\n    arg->result = result;\n    return static_cast<void*> (result.data());\n}\n\n//Reverse 3\nstatic void* thread7(void* package) {\n    thread_argument* args = static_cast<thread_argument*> (package);\n    std::vector<unsigned> best_tour = args->tour;\n\n    int start_index = 0;\n    std::mt19937 rq;\n    rq.seed(std::random_device()());\n    if ((*args).tour.size() >= 4) {\n        std::uniform_int_distribution<std::mt19937::result_type> dist6(0, (*args).tour.size() - 4);\n        start_index = dist6(rq);\n    } else if ((*args).tour.size() <= 3) {\n        std::uniform_int_distribution<std::mt19937::result_type> dist6(0, (*args).tour.size() - 1);\n        start_index = dist6(rq);\n    }\n\n    std::vector<unsigned>::iterator start_pos = best_tour.begin() + start_index;\n    unsigned count = 0;\n    while (start_pos + count != best_tour.end() && count < 3) {\n        count++;\n    }\n    while (count > 0) {\n        //check if the switched first one has pick ups at the two before it before reverse, if so do random generator again\n        std::unordered_map<unsigned, std::vector<unsigned>>::iterator it = dropoffs_pickups.find(*(start_pos + count));\n        if (it != dropoffs_pickups.end()) {\n            //it is a drop off and now need to check for seeing if the one before it is a pick up\n            for (unsigned i = 0; i < dropoffs_pickups[*(start_pos + count)].size(); ++i) {\n                //if the value in the first position is in the list of the others pick ups rip\n                if (*(start_pos + count) == dropoffs_pickups[*(start_pos + count)][i]) {\n                    args->result = best_tour;\n                    return (static_cast<void*> (best_tour.data()));\n                }\n            }\n        }\n        count--;\n    }\n    //check if the middle has pickups at the one before it, pre-reverse\n    std::reverse(start_pos, start_pos + count);\n    args->result = best_tour;\n    return (static_cast<void*> (best_tour.data()));\n}", "meta": {"hexsha": "11150f499224de76bd91dae20d8c1a4e8c8fb9a3", "size": 44924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "work/mapper/libstreetmap/src/m4.cpp", "max_stars_repo_name": "Muhammad-Abdullah-Bajwa/6ixMaps", "max_stars_repo_head_hexsha": "b85e6c368ac7aaa15a0f02c5275c78ece9363438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "work/mapper/libstreetmap/src/m4.cpp", "max_issues_repo_name": "Muhammad-Abdullah-Bajwa/6ixMaps", "max_issues_repo_head_hexsha": "b85e6c368ac7aaa15a0f02c5275c78ece9363438", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "work/mapper/libstreetmap/src/m4.cpp", "max_forks_repo_name": "Muhammad-Abdullah-Bajwa/6ixMaps", "max_forks_repo_head_hexsha": "b85e6c368ac7aaa15a0f02c5275c78ece9363438", "max_forks_repo_licenses": ["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.5085662759, "max_line_length": 193, "alphanum_fraction": 0.5911539489, "num_tokens": 11029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.021948251795610777, "lm_q1q2_score": 0.010460090182209884}}
{"text": "// This file is distributed under the MIT license.\n// See the LICENSE file for details.\n\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <iostream>\n#include <ostream>\n#include <map>\n#include <utility>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/iostreams/device/mapped_file.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/utility/string_ref.hpp>\n#include <boost/filesystem.hpp>\n\n#include <visionaray/math/io.h>\n#include <visionaray/math/vector.h>\n#include <visionaray/texture/texture.h>\n\n#include \"image.h\"\n#include \"model.h\"\n#include \"obj_grammar.h\"\n#include \"obj_loader.h\"\n\nnamespace qi = boost::spirit::qi;\n\nusing boost::string_ref;\n\n\nnamespace visionaray\n{\n\n//-------------------------------------------------------------------------------------------------\n// Map obj indices to unsigned base-0 indices\n//\n\ntemplate <typename Int>\ninline Int remap_index(Int idx, Int size)\n{\n    return idx < 0 ? size + idx : idx - 1;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Store a triangle and assign visionaray-internal ids\n//\n\nstatic bool store_triangle(model& result, vertex_vector const& vertices, int i1, int i2, int i3)\n{\n    model::triangle_type tri;\n\n    tri.v1 = vertices[i1];\n    tri.e1 = vertices[i2] - tri.v1;\n    tri.e2 = vertices[i3] - tri.v1;\n\n    if (length(cross(tri.e1, tri.e2)) == 0.0f)\n    {\n        std::cerr << \"Warning: rejecting degenerate triangle: zero-based indices: (\"\n                  << i1 << ' ' << i2 << ' ' << i3 << \"), v1|e1|e2: \"\n                  << tri.v1 << ' ' << tri.e1 << ' ' << tri.e2 << '\\n';\n        return false;\n    }\n    else\n    {\n        tri.prim_id = static_cast<unsigned>(result.primitives.size());\n        tri.geom_id = result.materials.size() == 0 ? 0 : static_cast<unsigned>(result.materials.size() - 1);\n        result.primitives.push_back(tri);\n    }\n\n    return true;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Store obj faces (i.e. triangle fans) in vertex|tex_coords|normals lists\n//\n\nstatic void store_faces(\n        model&                  result,\n        vertex_vector const&    vertices,\n        tex_coord_vector const& tex_coords,\n        normal_vector const&    normals,\n        face_vector const&      faces\n        )\n{\n\n    auto vertices_size = static_cast<int>(vertices.size());\n    size_t last = 2;\n    auto i1 = remap_index(faces[0].vertex_index, vertices_size);\n\n    while (last != faces.size())\n    {\n        // triangle\n        auto i2 = remap_index(faces[last - 1].vertex_index, vertices_size);\n        auto i3 = remap_index(faces[last].vertex_index, vertices_size);\n\n        if (store_triangle(result, vertices, i1, i2, i3))\n        {\n\n            // texture coordinates\n            if (faces[0].tex_coord_index && faces[last - 1].tex_coord_index && faces[last].tex_coord_index)\n            {\n                auto tex_coords_size = static_cast<int>(tex_coords.size());\n                auto ti1 = remap_index(*faces[0].tex_coord_index, tex_coords_size);\n                auto ti2 = remap_index(*faces[last - 1].tex_coord_index, tex_coords_size);\n                auto ti3 = remap_index(*faces[last].tex_coord_index, tex_coords_size);\n\n                result.tex_coords.push_back( tex_coords[ti1] );\n                result.tex_coords.push_back( tex_coords[ti2] );\n                result.tex_coords.push_back( tex_coords[ti3] );\n            }\n\n            // normals\n            if (faces[0].normal_index && faces[last - 1].normal_index && faces[last].normal_index)\n            {\n                auto normals_size = static_cast<int>(normals.size());\n                auto ni1 = remap_index(*faces[0].normal_index, normals_size);\n                auto ni2 = remap_index(*faces[last - 1].normal_index, normals_size);\n                auto ni3 = remap_index(*faces[last].normal_index, normals_size);\n\n                result.shading_normals.push_back( normals[ni1] );\n                result.shading_normals.push_back( normals[ni2] );\n                result.shading_normals.push_back( normals[ni3] );\n            }\n        }\n\n        ++last;\n    }\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// aabb of a list of triangles\n//\n\ninline aabb bounds(model::triangle_list const& tris)\n{\n    aabb result;\n    result.invalidate();\n\n    for (auto const& tri : tris)\n    {\n        auto v1 = tri.v1;\n        auto v2 = tri.v1 + tri.e1;\n        auto v3 = tri.v1 + tri.e2;\n\n        result = combine(result, v1);\n        result = combine(result, v2);\n        result = combine(result, v3);\n    }\n\n    return result;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Obj material\n//\n\nstruct mtl\n{\n    vec3 ka = vec3(0.2f, 0.2f, 0.2f);\n    vec3 kd = vec3(0.8f, 0.8f, 0.8f);\n    vec3 ke = vec3(0.0f, 0.0f, 0.0f);\n    vec3 ks = vec3(0.1f, 0.1f, 0.1);\n    float tr = 0.0f; // tr=1-d\n    float d = 1.0f;\n    float ns = 32.0f;\n    float ni = 1.0f;\n    std::string map_kd = \"\";\n    int illum = 2;\n};\n\n\n//-------------------------------------------------------------------------------------------------\n// Parse mtllib\n//\n\nstatic void parse_mtl(std::string const& filename, std::map<std::string, mtl>& matlib, obj_grammar const& grammar)\n{\n    boost::iostreams::mapped_file_source file(filename);\n\n    std::map<std::string, mtl>::iterator mtl_it = matlib.end();\n\n    string_ref text(file.data(), file.size());\n    auto it = text.cbegin();\n\n    string_ref mtl_name;\n\n    while (it != text.cend())\n    {\n        if ( qi::phrase_parse(it, text.cend(), grammar.r_newmtl, qi::blank, mtl_name) )\n        {\n            std::string name(mtl_name.begin(), mtl_name.length());\n            boost::trim(name);\n            auto r = matlib.insert({ name, mtl() });\n            if (!r.second)\n            {\n                // Material already exists...\n            }\n\n            mtl_it = r.first;\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_ka, qi::blank, mtl_it->second.ka) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_kd, qi::blank, mtl_it->second.kd) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_ke, qi::blank, mtl_it->second.ke) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_ks, qi::blank, mtl_it->second.ks) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_tr, qi::blank, mtl_it->second.tr) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_d, qi::blank, mtl_it->second.d) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_ns, qi::blank, mtl_it->second.ns) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_ni, qi::blank, mtl_it->second.ni) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_map_kd, qi::blank, mtl_it->second.map_kd) )\n        {\n        }\n        else if ( mtl_it != matlib.end() && qi::phrase_parse(it, text.cend(), grammar.r_illum, qi::blank, mtl_it->second.illum) )\n        {\n        }\n        else if ( qi::phrase_parse(it, text.cend(), grammar.r_unhandled, qi::blank) )\n        {\n        }\n    }\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Add material to container\n//\n\ntemplate <typename Container>\nvoid add_material(Container& cont, mtl m, string_ref name)\n{\n    model::material_type mat;\n    mat.name = std::string(name.data(), name.length());\n    mat.ca = m.ka;\n    mat.cd = m.kd;\n    mat.cs = m.ks;\n    mat.ce = m.ke;\n    mat.ior = vec3(m.ni);\n    mat.transmission = m.tr > 0.0f ? m.tr : 0.0f;\n    mat.transmission = 1.0f - m.d > 0.0f ? 1.0f - m.d : mat.transmission;\n    mat.specular_exp = m.ns;\n    mat.illum = m.illum;\n    cont.emplace_back(mat);\n}\n\n\nstatic void insert_dummy_texture(model& mod)\n{\n    using tex_type = model::texture_type;\n\n    tex_type tex(1, 1);\n    tex.set_address_mode(Wrap);\n    tex.set_filter_mode(Nearest);\n\n    vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f);\n    tex.reset(&dummy_texel);\n\n    mod.texture_map.insert(std::make_pair(\"null\", std::move(tex)));\n\n    // Maybe a \"null\" texture was already present and thus not inserted\n    //  ==> find the one that was already inserted\n    auto it = mod.texture_map.find(\"null\");\n\n    // Insert a ref\n    mod.textures.push_back(tex_type::ref_type(it->second));\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Load a single obj file\n//\n\nvoid load_obj(std::string const& filename, model& mod)\n{\n    std::vector<std::string> filenames(1);\n\n    filenames[0] = filename;\n\n    load_obj(filenames, mod);\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Load obj files\n//\n\nvoid load_obj(std::vector<std::string> const& filenames, model& mod)\n{\n    std::vector<std::string> parsed_matlibs;\n\n    std::map<std::string, mtl> matlib;\n\n    size_t geom_id = 0;\n\n    obj_grammar grammar;\n\n    // containers for parsing\n\n    string_ref comment;\n    string_ref mtl_file;\n    string_ref mtl_name;\n\n    for (auto filename : filenames)\n    {\n        boost::iostreams::mapped_file_source file(filename);\n\n        string_ref text(file.data(), file.size());\n        auto it = text.cbegin();\n\n        vertex_vector    vertices;\n        tex_coord_vector tex_coords;\n        normal_vector    normals;\n        face_vector      faces;\n\n        while (it != text.cend())\n        {\n            faces.clear();\n\n            if ( qi::phrase_parse(it, text.cend(), grammar.r_comment, qi::blank, comment) )\n            {\n            }\n            else if ( qi::phrase_parse(it, text.cend(), grammar.r_mtllib, qi::blank, mtl_file) )\n            {\n                std::string mtl_file_string(mtl_file.begin(), mtl_file.length());\n\n                // Some obj files repeat the same mtllib command over and over again..\n                bool already_parsed = std::find(parsed_matlibs.begin(), parsed_matlibs.end(), mtl_file_string) != parsed_matlibs.end();\n\n                if (!already_parsed)\n                {\n                    boost::filesystem::path p(filename);\n                    std::string mtl_dir = p.parent_path().string();\n\n                    std::string mtl_path = \"\";\n                    if (mtl_dir.empty())\n                    {\n                        mtl_path = std::string(mtl_file.begin(), mtl_file.length());\n                    }\n                    else\n                    {\n                        mtl_path = mtl_dir + \"/\" + std::string(mtl_file.begin(), mtl_file.length());\n                    }\n\n                    if (boost::filesystem::exists(mtl_path))\n                    {\n                        parse_mtl(mtl_path, matlib, grammar);\n                    }\n                    else\n                    {\n                        std::cerr << \"Warning: file does not exist: \" << mtl_path << '\\n';\n                    }\n\n                    parsed_matlibs.push_back(mtl_file_string);\n                }\n                else\n                {\n                    std::cerr << \"Warning: mtllib already parsed: \" << mtl_file << '\\n';\n                }\n            }\n            else if ( qi::phrase_parse(it, text.cend(), grammar.r_usemtl, qi::blank, mtl_name) )\n            {\n                std::string name(mtl_name.begin(), mtl_name.length());\n                boost::trim(name);\n                auto mat_it = matlib.find(name);\n                if (mat_it != matlib.end())\n                {\n                    typedef model::texture_type tex_type;\n\n                    add_material(mod.materials, mat_it->second, name);\n\n                    if (!mat_it->second.map_kd.empty()) // File path specified in mtl file\n                    {\n                        std::string tex_filename;\n\n                        boost::filesystem::path kdp(mat_it->second.map_kd);\n\n                        if (kdp.is_absolute())\n                        {\n                            tex_filename = kdp.string();\n                        }\n\n                        // Maybe boost::filesystem was wrong and a relative path\n                        // camouflaged as an absolute one (e.g. because it was\n                        // erroneously prefixed with a '/' under Unix.\n                        // Happens e.g. in the fairy forest model..\n                        // Let's also check for that..\n\n                        if (!boost::filesystem::exists(tex_filename) || !kdp.is_absolute())\n                        {\n                            // Find texture relative to the path the obj file is located in\n                            boost::filesystem::path p(filename);\n                            tex_filename = p.parent_path().string() + \"/\" + mat_it->second.map_kd;\n                            std::replace(tex_filename.begin(), tex_filename.end(), '\\\\', '/');\n                        }\n\n                        if (!boost::filesystem::exists(tex_filename))\n                        {\n                            boost::trim(tex_filename);\n                        }\n\n                        if (boost::filesystem::exists(tex_filename))\n                        {\n                            // Load the texture if we haven't done so yet\n                            auto tex_it = mod.texture_map.find(mat_it->second.map_kd);\n                            if (tex_it == mod.texture_map.end())\n                            {\n                                image img;\n                                if (img.load(tex_filename))\n                                {\n                                    tex_type tex(img.width(), img.height());\n                                    tex.set_address_mode( Wrap );\n                                    tex.set_filter_mode( Linear );\n\n                                    if (img.format() == PF_RGB32F)\n                                    {\n                                        // Down-convert to 8-bit, add alpha=1.0\n                                        auto data_ptr = reinterpret_cast<vector<3, float> const*>(img.data());\n                                        tex.reset(data_ptr, PF_RGB32F, PF_RGBA8, AlphaIsOne);\n                                    }\n                                    else if (img.format() == PF_RGBA32F)\n                                    {\n                                        // Down-convert to 8-bit\n                                        auto data_ptr = reinterpret_cast<vector<4, float> const*>(img.data());\n                                        tex.reset(data_ptr, PF_RGBA32F, PF_RGBA8);\n                                    }\n                                    else if (img.format() == PF_RGB16UI)\n                                    {\n                                        // Down-convert to 8-bit, add alpha=1.0\n                                        auto data_ptr = reinterpret_cast<vector<3, unorm<16>> const*>(img.data());\n                                        tex.reset(data_ptr, PF_RGB16UI, PF_RGBA8, AlphaIsOne);\n                                    }\n                                    else if (img.format() == PF_RGBA16UI)\n                                    {\n                                        // Down-convert to 8-bit\n                                        auto data_ptr = reinterpret_cast<vector<4, unorm<16>> const*>(img.data());\n                                        tex.reset(data_ptr, PF_RGBA16UI, PF_RGBA8);\n                                    }\n                                    else if (img.format() == PF_R8)\n                                    {\n                                        // Let RGB=R and add alpha=1.0\n                                        auto data_ptr = reinterpret_cast<unorm< 8> const*>(img.data());\n                                        tex.reset(data_ptr, PF_R8, PF_RGBA8, AlphaIsOne);\n                                    }\n                                    else if (img.format() == PF_RGB8)\n                                    {\n                                        // Add alpha=1.0\n                                        auto data_ptr = reinterpret_cast<vector<3, unorm< 8>> const*>(img.data());\n                                        tex.reset(data_ptr, PF_RGB8, PF_RGBA8, AlphaIsOne);\n                                    }\n                                    else if (img.format() == PF_RGBA8)\n                                    {\n                                        // \"Native\" texture format\n                                        auto data_ptr = reinterpret_cast<vector<4, unorm< 8>> const*>(img.data());\n                                        tex.reset(data_ptr);\n                                    }\n                                    else\n                                    {\n                                        std::cerr << \"Warning: unsupported pixel format\\n\";\n                                    }\n\n                                    mod.texture_map.insert(std::make_pair(mat_it->second.map_kd, std::move(tex)));\n                                    // Will be ref()'d below\n                                    tex_it = mod.texture_map.find(mat_it->second.map_kd);\n                                }\n                                else\n                                {\n                                    std::cerr << \"Warning: cannot load texture from file: \" << tex_filename << '\\n';\n                                }\n                            }\n\n                            if (tex_it != mod.texture_map.end())\n                            {\n                                // File was already present in map or was\n                                // just loaded. Push a reference to it!\n                                auto& loaded_tex = tex_it->second;\n                                mod.textures.push_back(tex_type::ref_type(loaded_tex));\n                            }\n                        }\n                        else\n                        {\n                            std::cerr << \"Warning: file does not exist: \" << tex_filename << '\\n';\n                        }\n                    }\n\n                    // if no texture was loaded, insert a dummy\n                    if (mod.textures.size() < mod.materials.size())\n                    {\n                        insert_dummy_texture(mod);\n                    }\n\n                    assert( mod.textures.size() == mod.materials.size() );\n                }\n                else\n                {\n                    std::cerr << \"Warning: material not present in mtllib: \" << name << '\\n';\n                }\n\n                geom_id = mod.materials.size() == 0 ? 0 : mod.materials.size() - 1;\n            }\n            else if ( qi::phrase_parse(it, text.cend(), grammar.r_vertices, qi::blank, vertices) )\n            {\n            }\n            else if ( qi::phrase_parse(it, text.cend(), grammar.r_tex_coords, qi::blank, tex_coords) )\n            {\n            }\n            else if ( qi::phrase_parse(it, text.cend(), grammar.r_normals, qi::blank, normals) )\n            {\n            }\n            else if ( qi::phrase_parse(it, text.cend(), grammar.r_face, qi::blank, faces) )\n            {\n                store_faces(mod, vertices, tex_coords, normals, faces);\n            }\n            else if ( qi::phrase_parse(it, text.cend(), grammar.r_unhandled, qi::blank) )\n            {\n            }\n            else\n            {\n                ++it;\n            }\n        }\n\n        // See that there is a material for each geometry\n        for (size_t i = mod.materials.size(); i <= geom_id; ++i)\n        {\n            mod.materials.emplace_back(model::material_type());\n        }\n\n        // See that there is a (at least dummy) texture for each geometry\n        for (size_t i = mod.textures.size(); i <= geom_id; ++i)\n        {\n            insert_dummy_texture(mod);\n        }\n    }\n\n    // Calculate geometric normals\n    for (auto const& tri : mod.primitives)\n    {\n        vec3 n = normalize(cross(tri.e1, tri.e2));\n        mod.geometric_normals.push_back(n);\n    }\n\n    // See that each triangle has (potentially dummy) texture coordinates\n    for (size_t i = mod.tex_coords.size(); i < mod.primitives.size() * 3; ++i)\n    {\n        mod.tex_coords.emplace_back(0.0f);\n    }\n\n\tmod.bbox.insert(bounds(mod.primitives));\n}\n\n} // visionaray\n", "meta": {"hexsha": "b9ead020b13e068a3dff5b7866afa0117bee6969", "size": 20714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/obj_loader.cpp", "max_stars_repo_name": "sylvainbouxin/visionaray", "max_stars_repo_head_hexsha": "39aba3605ca92b6b086852d3524b762ac259ed43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/obj_loader.cpp", "max_issues_repo_name": "sylvainbouxin/visionaray", "max_issues_repo_head_hexsha": "39aba3605ca92b6b086852d3524b762ac259ed43", "max_issues_repo_licenses": ["MIT"], "max_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/obj_loader.cpp", "max_forks_repo_name": "sylvainbouxin/visionaray", "max_forks_repo_head_hexsha": "39aba3605ca92b6b086852d3524b762ac259ed43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T20:21:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T20:21:23.000Z", "avg_line_length": 36.3403508772, "max_line_length": 135, "alphanum_fraction": 0.4586752921, "num_tokens": 4391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.02405355070814844, "lm_q1q2_score": 0.010438795170057111}}
{"text": "#include \"Scene_renderer.h\"\n// local\n#include \"Consts.h\"\n#include \"Mesh_generator.h\"\n#include \"Matrix_lib.h\"\n// boost\n#include <boost/numeric/ublas/assignment.hpp>\n// std\n#include <stdexcept>\n// glm\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtc/type_ptr.hpp>\n#define GLM_ENABLE_EXPERIMENTAL\n#include <glm/gtx/rotate_vector.hpp>\n#include <glm/gtx/quaternion.hpp>\n// ImGui\n#include \"imgui.h\"\n\n//******************************************************************************\n// Scene_renderer\n//******************************************************************************\n\nScene_renderer::Scene_renderer(std::shared_ptr<Scene_state> state)\n    : Base_renderer()\n    , tesseract_thickness_(1.f)\n    , curve_thickness_(1.f)\n    , sphere_diameter_(1.f)\n    , number_of_animations_(6)\n    , visibility_mask_(0)\n    , track_mouse_(false)\n    , filter_arrow_annotations_(true)\n    , show_labels_(true)\n{\n    set_state(state);\n}\n\n//******************************************************************************\n// set_shaders\n//******************************************************************************\n\nvoid Scene_renderer::set_shaders(std::shared_ptr<Diffuse_shader> diffuse,\n                                 std::shared_ptr<Screen_shader> screen)\n{\n    diffuse_shader_ = diffuse;\n    screen_shader_  = screen;\n}\n\n//******************************************************************************\n// set_text_renderer\n//******************************************************************************\n\nvoid Scene_renderer::set_text_renderer(std::shared_ptr<Text_renderer> tex_ren)\n{\n    text_renderer_ = tex_ren;\n}\n\n//******************************************************************************\n// render\n//******************************************************************************\n\nvoid Scene_renderer::render()\n{\n    // Scene rendering ---------------------------------------------------------\n\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n    glEnable(GL_DEPTH_TEST);\n    \n    if(state_            == nullptr ||\n       state_->tesseract == nullptr ||\n       state_->curves.empty())\n    {\n        return;\n    }\n\n    back_geometry_  = std::make_unique<Diffuse_shader::Mesh_geometry>();\n    front_geometry_ = std::make_unique<Diffuse_shader::Mesh_geometry>();\n    screen_geometry_ = std::make_unique<Screen_shader::Screen_geometry>();\n\n    label_points_.clear();\n\n    glUseProgram(diffuse_shader_->program_id);\n\n    glViewport(static_cast<GLint>(display_scale_x_ * region_.left()),\n               static_cast<GLint>(display_scale_y_ * region_.bottom()),\n               static_cast<GLsizei>(display_scale_x_ * region_.width()),\n               static_cast<GLsizei>(display_scale_y_ * region_.height()));\n\n    std::vector<float> anims =\n        split_animation(state_->unfolding_anim, number_of_animations_);\n    float hide_4D = anims[0],\n          project_curve_4D = anims[1],\n          unfold_4D = anims[2],\n          hide_3D = anims[3],\n          project_curve_3D = anims[4],\n          unfold_3D = anims[5];\n\n    glm::mat4 proj_mat = glm::perspective(\n        state_->fov_y,\n        region_.width() / region_.height(),\n        0.1f,\n        100.f);\n    auto camera_mat = glm::translate(glm::mat4(1.f), state_->camera_3D);\n    glm::vec3 light_pos(0.f, 0.f, 70.f);\n    auto world_mat = glm::toMat4(glm::lerp(state_->rotation_3D,\n                                           glm::quat(),\n                                           static_cast<float>(unfold_3D)));\n    auto norm_mat = glm::transpose(glm::inverse(glm::mat3(world_mat)));\n\n    // Cache the Model-view-projection matrix for arrow drawing\n    auto mvp_mat = proj_mat * camera_mat * world_mat;\n\n    glUniformMatrix4fv(diffuse_shader_->proj_mat_id,\n                       1,\n                       GL_FALSE,\n                       glm::value_ptr(proj_mat));\n    glUniformMatrix4fv(diffuse_shader_->mv_mat_id,\n                       1,\n                       GL_FALSE,\n                       glm::value_ptr(camera_mat * world_mat));\n    glUniformMatrix3fv(diffuse_shader_->normal_mat_id,\n                       1,\n                       GL_FALSE,\n                       glm::value_ptr(norm_mat));\n    glUniform3fv(diffuse_shader_->light_pos_id,\n                 1,\n                 glm::value_ptr(light_pos));\n    glUniform2fv(diffuse_shader_->fog_range_id,\n                 1,\n                 glm::value_ptr(fog_range_));\n\n    //gui_.Renderer->remove_all_meshes();\n    //gui_.distanceWarning->hide();\n    //gui_.Renderer->show_labels(false);\n    //gui_.Renderer->remove_annotation_points();\n\n    auto rot_m = get_rotation_matrix();\n\n    // Project the tesseract from 4D to 3D\n    Scene_wireframe_object projected_t = *state_->tesseract.get();\n    project_to_3D(projected_t.get_vertices(), rot_m);\n\n    // Choosing the high-resolution or the low-resolution curve\n    std::vector<Curve> projected_c;\n\n    // Array of curves used to project into 3D spaces\n    typedef std::vector<Curve> curves_3d_t;\n    std::vector<curves_3d_t> curves_3d;\n\n    for(size_t ci = 0; ci < state_->curves.size(); ++ci)\n    {\n        projected_c.push_back(*state_->curves[ci].get());\n    \n        curves_3d_t curves;\n        for(int i = 0; i < 8; ++i)\n            curves.push_back(*state_->curves[ci].get());\n        curves_3d.push_back(curves);\n\n        // Project curves from 4D to 3D\n        project_to_3D(projected_c[ci].get_vertices(), rot_m);\n    }\n\n    // Animation unfolding the tesseract to the Dali-cross\n    if(state_->unfolding_anim == 0)\n    {\n        // Draw tesseract\n        if(state_->show_tesseract)\n            draw_tesseract(projected_t);\n\n        // Draw 4D curve\n        if(state_->show_curve)\n        {\n            for(size_t ci = 0; ci < projected_c.size(); ++ci)\n            {\n                if(state_->use_unique_curve_colors)\n                {\n                    draw_curve(\n                        projected_c[ci],\n                        1.,\n                        state_->get_curve_color(ci));\n                }\n                else\n                {\n                    draw_curve(\n                        projected_c[ci],\n                        1.,\n                        state_->get_color(Curve_low_speed),\n                        state_->get_color(Curve_high_speed));\n                }\n                draw_annotations(projected_c[ci], mvp_mat);\n            }\n        }\n    }\n    else\n    {\n        std::vector<Cube> plots_3D = state_->tesseract->split();\n\n        for(auto& c: curves_3d)\n            move_curves_to_3D_plots(project_curve_4D, c);\n\n        if(unfold_4D > 0)\n            tesseract_unfolding(unfold_4D, plots_3D, curves_3d);\n\n        // Project 3D plots from 4D to 3D\n        auto rot = get_rotation_matrix(unfold_4D);\n        for(auto& p : plots_3D)\n            project_to_3D(p.get_vertices(), rot);\n\n        auto visibility_coeff = [this](size_t i) {\n            if(visibility_mask_ == 0 || visibility_mask_ & 1 << i)\n                return 1.f;\n            else\n                return 0.1f;\n        };\n\n        if(0 < hide_4D && project_curve_3D == 0)\n        {\n            // Draw 3D plots\n            if(state_->show_tesseract)\n            {\n                for(size_t i = 0; i < plots_3D.size(); ++i)\n                {\n                    auto& c = plots_3D[i];\n                    if(state_->use_simple_dali_cross && i != 1 &&\n                       i != 2 && i != 5 && i != 7)\n                    {\n                        // Sometimes it is dangerous to draw to transparent\n                        // objects with direrent at different animation stages,\n                        // because they both are drawn first. Therefore we make\n                        // this ckecup here to avoid possible drawing issues\n                        if(hide_4D != 1)\n                        {\n                            draw_3D_plot(\n                                c, visibility_coeff(i) * (1.f - hide_4D));\n                        }\n                    }\n                    else\n                    {\n                        draw_3D_plot(c, visibility_coeff(i) * (1.f - hide_3D));\n                    }\n                }\n            }\n\n            for(size_t ci = 0; ci < curves_3d.size(); ++ci)\n            {\n                // Draw curves\n                if(state_->show_curve)\n                {\n                    for(size_t i = 0; i < curves_3d[ci].size(); ++i)\n                    {\n                        if(state_->use_simple_dali_cross && i != 1 &&\n                           i != 2 && i != 5 && i != 7)\n                        {\n                            continue;\n                        }\n\n                        auto c = curves_3d[ci][i];\n                        project_to_3D(c.get_vertices(), rot);\n\n                        if(state_->use_unique_curve_colors)\n                        {\n                            draw_curve(\n                                c,\n                                visibility_coeff(i) * (1.f - hide_3D),\n                                state_->get_curve_color(ci));\n                        }\n                        else\n                        {\n                            draw_curve(\n                                c,\n                                visibility_coeff(i) * (1.f - hide_3D),\n                                state_->get_color(Curve_low_speed),\n                                state_->get_color(Curve_high_speed));\n                        }\n                        if(visibility_coeff(i) == 1. && hide_3D < 0.5)\n                            draw_annotations(c, mvp_mat);\n                    }\n                }\n            }\n        }\n\n        // Create meshes for the cubes representign the Tesseract / Dali-cross\n        if(hide_3D > 0)\n        {\n            // Get the source plots\n            std::vector<Square> plots_2D = Cube::split(plots_3D);\n\n            typedef std::vector<Curve> curvs_2d_t;\n            std::vector<curvs_2d_t> curves_2d;\n\n            for(auto& c3d : curves_3d)\n            {\n                std::vector<Curve> curves;\n                curves.push_back(c3d[5]);\n                curves.push_back(c3d[1]);\n                curves.push_back(c3d[7]);\n                curves.push_back(c3d[1]);\n                curves.push_back(c3d[7]);\n                curves.push_back(c3d[7]);\n\n                move_curves_to_2D_plots(project_curve_3D, curves);\n                curves_2d.push_back(curves);\n            }\n\n            for(auto& c2d : curves_2d)\n            {\n                for(auto& c : c2d)\n                {\n                    project_to_3D(c.get_vertices(), rot);\n                }\n            }\n            plots_unfolding(unfold_3D, plots_2D, curves_2d);\n\n            // Draw 2D plots\n            if(state_->show_tesseract)\n            {\n                for(auto& p : plots_2D)\n                    draw_2D_plot(p);\n            }\n\n            label_points_.push_back(plots_2D[0].get_vertices()[3]);\n            label_points_.push_back(plots_2D[3].get_vertices()[0]);\n            label_points_.push_back(plots_2D[5].get_vertices()[1]);\n\n            // Draw 2D curves\n            if(state_->show_curve)\n            {\n                for(size_t ci = 0; ci < curves_2d.size(); ++ci)\n                {\n                    for(auto& c : curves_2d[ci])\n                    {\n                        if(state_->use_unique_curve_colors)\n                        {\n                            draw_curve(c, 1., state_->get_curve_color(ci));\n                        }\n                        else\n                        {\n                            draw_curve(\n                                c,\n                                1.,\n                                state_->get_color(Curve_low_speed),\n                                state_->get_color(Curve_high_speed));\n                        }\n\n                        draw_annotations(c, mvp_mat);\n                    }\n                }\n            }\n        }\n    }\n\n    if(back_geometry_->data_array.size() > 0)\n    {\n        back_geometry_->init_buffers();\n        diffuse_shader_->draw_geometry(back_geometry_);\n    }\n    if(front_geometry_->data_array.size() > 0)\n    {\n        front_geometry_->init_buffers();\n        diffuse_shader_->draw_geometry(front_geometry_);\n    }\n\n    // On screen rendering -----------------------------------------------------\n\n    glUseProgram(screen_shader_->program_id);\n\n    glViewport(static_cast<GLint>(  display_scale_x_ * region_.left()   ),\n               static_cast<GLint>(  display_scale_y_ * region_.bottom() ),\n               static_cast<GLsizei>(display_scale_x_ * region_.width()  ),\n               static_cast<GLsizei>(display_scale_y_ * region_.height()));\n\n    glm::mat4 proj_ortho = glm::ortho(0.f,\n                                      static_cast<float>(region_.width()),\n                                      0.f,\n                                      static_cast<float>(region_.height()));\n    glUniformMatrix4fv(screen_shader_->proj_mat_id,\n                       1,\n                       GL_FALSE,\n                       glm::value_ptr(proj_ortho));\n\n    if(state_->show_legend)\n        draw_legend(region_);\n\n    if(show_labels_ && unfold_3D > 0.66f)\n        draw_labels_in_2D(mvp_mat);\n\n    screen_geometry_->init_buffers();\n    screen_shader_->draw_geometry(*screen_geometry_.get());\n}\n\n//******************************************************************************\n// process_input\n//******************************************************************************\n\nvoid Scene_renderer::process_input(const Base_renderer::Renderer_io& io)\n{\n    if(io.mouse_down && region_.contains(io.mouse_pos))\n        track_mouse_ = true;\n\n    if(io.mouse_up)\n        track_mouse_ = false;\n\n    if(track_mouse_ && glm::length(io.mouse_move) > 0)\n    {\n        glm::vec3 axis(-io.mouse_move.y, io.mouse_move.x, 0.f);\n        float length = glm::length(axis);\n        state_->rotation_3D =\n            glm::angleAxis(\n                glm::radians(0.25f * length),\n                glm::normalize(axis)) *\n            state_->rotation_3D;\n    }\n\n    if(io.mouse_wheel && region_.contains(io.mouse_pos))\n        state_->camera_3D.z += io.mouse_wheel_y * 0.05f;\n\n    if(io.key_pressed)\n    {\n        switch(io.key)\n        {\n        case Base_renderer::Renderer_io::Key_0:\n            visibility_mask_ = 0;\n            break;\n        case Base_renderer::Renderer_io::Key_1:\n            visibility_mask_ ^= 1 << 0;\n            break;\n        case Base_renderer::Renderer_io::Key_2:\n            visibility_mask_ ^= 1 << 1;\n            break;\n        case Base_renderer::Renderer_io::Key_3:\n            visibility_mask_ ^= 1 << 2;\n            break;\n        case Base_renderer::Renderer_io::Key_4:\n            visibility_mask_ ^= 1 << 3;\n            break;\n        case Base_renderer::Renderer_io::Key_5:\n            visibility_mask_ ^= 1 << 4;\n            break;\n        case Base_renderer::Renderer_io::Key_6:\n            visibility_mask_ ^= 1 << 5;\n            break;\n        case Base_renderer::Renderer_io::Key_7:\n            visibility_mask_ ^= 1 << 6;\n            break;\n        case Base_renderer::Renderer_io::Key_8:\n            visibility_mask_ ^= 1 << 7;\n            break;\n        case Base_renderer::Renderer_io::Key_F1:\n            visibility_mask_ = 1 << 0;\n            break;\n        case Base_renderer::Renderer_io::Key_F2:\n            visibility_mask_ = 1 << 1;\n            break;\n        case Base_renderer::Renderer_io::Key_F3:\n            visibility_mask_ = 1 << 2;\n            break;\n        case Base_renderer::Renderer_io::Key_F4:\n            visibility_mask_ = 1 << 3;\n            break;\n        case Base_renderer::Renderer_io::Key_F5:\n            visibility_mask_ = 1 << 4;\n            break;\n        case Base_renderer::Renderer_io::Key_F6:\n            visibility_mask_ = 1 << 5;\n            break;\n        case Base_renderer::Renderer_io::Key_F7:\n            visibility_mask_ = 1 << 6;\n            break;\n        case Base_renderer::Renderer_io::Key_F8:\n            visibility_mask_ = 1 << 7;\n            break;\n        }\n    }\n}\n\n//******************************************************************************\n// project_to_3D\n//******************************************************************************\n\nvoid Scene_renderer::project_to_3D(\n    Scene_vertex_t& point,\n    const boost::numeric::ublas::matrix<float>& rot_mat)\n{\n    Scene_vertex_t tmp_vert = prod(point, rot_mat);\n    tmp_vert = tmp_vert - state_->camera_4D;\n    tmp_vert = prod(tmp_vert, state_->projection_4D);\n\n    //if(tmp_vert(3) < 0)\n    //    gui_.distanceWarning->show();\n    assert(tmp_vert(3) > 0);\n\n    tmp_vert(0) /= tmp_vert(4);\n    tmp_vert(1) /= tmp_vert(4);\n    tmp_vert(2) /= tmp_vert(4);\n    // Important!\n    // Original coordinates in tmp_vert(3) and tmp_vert(4) are kept!\n    // It is required for the 4D perspective.\n\n    point = tmp_vert;\n}\n\n//******************************************************************************\n// project_to_3D\n//******************************************************************************\n\nvoid Scene_renderer::project_to_3D(\n    std::vector<Scene_vertex_t>& verts,\n    const boost::numeric::ublas::matrix<float>& rot_mat)\n{\n    auto project = [&](Scene_vertex_t& v)\n    {\n        project_to_3D(v, rot_mat);\n    };\n    std::for_each(verts.begin(), verts.end(), project);\n}\n\nnamespace\n{\n//******************************************************************************\n// ColorToGlm\n//******************************************************************************\n\nglm::vec4 ColorToGlm(const Color& c, const float alpha)\n{\n    return glm::vec4(c.r_norm(), c.g_norm(), c.b_norm(), alpha);\n}\n} // namespace\n\n//******************************************************************************\n// draw_tesseract\n//******************************************************************************\n\nvoid Scene_renderer::draw_tesseract(Scene_wireframe_object& t)\n{\n    Mesh t_mesh;\n    for(auto const& e : t.edges())\n    {\n        auto& current = t.get_vertices()[e.vert1];\n        auto& next = t.get_vertices()[e.vert2];\n        const glm::vec4 col = ColorToGlm(e.color, 1.f);\n\n        Mesh_generator::cylinder(\n            5,\n            tesseract_thickness_ / current(3),\n            tesseract_thickness_ / next(3),\n            glm::vec3(current(0), current(1), current(2)),\n            glm::vec3(next(0), next(1), next(2)),\n            col,\n            t_mesh);\n\n    }\n\n    for(unsigned int i = 0; i < t.get_vertices().size(); ++i)\n    {\n        float size_coef = 1.f;\n\n        auto const& v = t.get_vertices()[i];\n        glm::vec3 pos(v(0), v(1), v(2));\n\n        if(i == 0)\n            Mesh_generator::sphere(\n                6,\n                6,\n                size_coef * sphere_diameter_ / v(3),\n                pos,\n                glm::vec4(1.f, 0.f, 0.f, 1.f),\n                t_mesh);\n        else\n            Mesh_generator::sphere(\n                6,\n                6,\n                size_coef * sphere_diameter_ / v(3),\n                pos,\n                glm::vec4(0.59f, 0.59f, 0.59f, 1.f),\n                t_mesh);\n\n    }\n\n    diffuse_shader_->append_to_geometry(*back_geometry_.get(), t_mesh);\n}\n\n//******************************************************************************\n// draw_curve\n//******************************************************************************\n\nvoid Scene_renderer::draw_curve(Curve& c, float opacity, const Color& color)\n{\n    draw_curve(c, opacity, color, color);\n}\n\n//******************************************************************************\n// draw_curve\n//******************************************************************************\n\nvoid Scene_renderer::draw_curve(\n    Curve& c,\n    float opacity,\n    const Color& slow_c,\n    const Color& fast_c)\n{\n    const float marker_size = 8.f; //gui_.markerSize->value();\n\n    auto log_speed = [](float speed) {\n        return std::log2(3 * speed + 1) / 2;\n    };\n\n    auto get_speed_color =\n        [&opacity, &log_speed, &slow_c, &fast_c, this](float normalized_speed) {\n            float speed = log_speed(normalized_speed);\n            return glm::vec4(\n                (1 - speed) * slow_c.r_norm() +\n                    speed * fast_c.r_norm(),\n                (1 - speed) * slow_c.g_norm() +\n                    speed * fast_c.g_norm(),\n                (1 - speed) * slow_c.b_norm() +\n                    speed * fast_c.b_norm(),\n                opacity);\n        };\n\n    // Curve\n    Mesh curve_mesh;\n    std::vector<glm::vec3> point_directions(c.vertices().size());\n    { // first\n        const auto& a = c.get_vertices()[0];\n        const auto& b = c.get_vertices()[1];\n        point_directions.front() = glm::normalize(\n            glm::vec3(b[0], b[1], b[2]) - glm::vec3(a[0], a[1], a[2]));\n    }\n    for(size_t i = 1; i < c.vertices().size() - 1; ++i)\n    {\n        const auto& p1 = c.vertices()[i - 1];\n        const auto& p2 = c.vertices()[i];\n        const auto& p3 = c.vertices()[i + 1];\n        const glm::vec3 dir1 = glm::normalize(\n            glm::vec3(p2[0], p2[1], p2[2]) - glm::vec3(p1[0], p1[1], p1[2]));\n        const glm::vec3 dir2 = glm::normalize(\n            glm::vec3(p3[0], p3[1], p3[2]) - glm::vec3(p2[0], p2[1], p2[2]));\n        point_directions[i] = glm::normalize(dir1 + dir2);\n    }\n    { // last\n        const auto& a = c.vertices()[c.vertices().size() - 2];\n        const auto& b = c.vertices()[c.vertices().size() - 1];\n        point_directions.back() = glm::normalize(\n            glm::vec3(b[0], b[1], b[2]) - glm::vec3(a[0], a[1], a[2]));\n    }\n\n    for(size_t i = 0; i < c.edges().size(); ++i)\n    {\n        const auto& e = c.edges()[i];\n\n        auto& current = c.get_vertices()[e.vert1];\n        auto& next = c.get_vertices()[e.vert2];\n\n        // We are interested only in some interval of the curve\n        if(state_->curve_selection &&\n           !state_->curve_selection->in_range(c.time_stamp()[e.vert1]))\n        {\n            continue;\n        }\n\n        auto& stats = c.get_stats();\n        float speed_coeff = (stats.speed[i] - stats.min_speed) /\n                            (stats.max_speed - stats.min_speed);\n\n        Mesh_generator::cylinder_v2(\n            5,\n            curve_thickness_ / current(3),\n            curve_thickness_ / next(3),\n            glm::vec3(current(0), current(1), current(2)),\n            glm::vec3(next(0), next(1), next(2)),\n            point_directions[i],\n            point_directions[i + 1],\n            get_speed_color(speed_coeff),\n            curve_mesh);\n    }\n    // TODO: fix the line below\n    //gui_.Renderer->add_mesh(curve_mesh, opacity < 1.);\n    if(opacity < 1.f)\n        diffuse_shader_->append_to_geometry(*front_geometry_.get(), curve_mesh);\n    else\n        diffuse_shader_->append_to_geometry(*back_geometry_.get(), curve_mesh);\n\n\n    if(state_->is_timeplayer_active)\n    {\n        auto marker =\n            c.get_point(c.t_min() + state_->timeplayer_pos * c.t_duration());\n\n        Mesh marker_mesh;\n        Mesh_generator::sphere(\n            5,\n            5,\n            marker_size / marker(3),\n            glm::vec3(marker(0), marker(1), marker(2)),\n            glm::vec4(1, 0, 0, 1),\n            marker_mesh);\n\n        diffuse_shader_->append_to_geometry(*back_geometry_.get(), marker_mesh);\n    }\n}\n\n//******************************************************************************\n// set_line_thickness\n//******************************************************************************\n\nvoid Scene_renderer::set_line_thickness(float t_thickness, float c_thickness)\n{\n    tesseract_thickness_ = t_thickness;\n    curve_thickness_ = c_thickness;\n}\n\n//******************************************************************************\n// set_sphere_diameter\n//******************************************************************************\n\nvoid Scene_renderer::set_sphere_diameter(float diameter)\n{\n    sphere_diameter_ = diameter;\n}\n\n//******************************************************************************\n// set_fog\n//******************************************************************************\n\nvoid Scene_renderer::set_fog(float fog_dist, float fog_range)\n{\n    fog_range_.x = fog_dist - 0.5f * fog_range;\n    fog_range_.y = fog_dist + 0.5f * fog_range;\n}\n\n//******************************************************************************\n// split_animation\n//******************************************************************************\n\nstd::vector<float> Scene_renderer::split_animation(float animation,\n                                                   int    sections)\n{\n    float section_length = 1.f / sections;\n\n    std::vector<float> splited_animations(sections);\n\n    int current_section =\n        animation == 1.f ? sections - 1 : (int)std::floor(animation * sections);\n\n    for(int i = 0; i < sections; ++i)\n    {\n        if(i < current_section)\n            splited_animations[i] = 1.f;\n        else if(i == current_section)\n            splited_animations[i] = animation * sections - current_section;\n        else\n            splited_animations[i] = 0.f;\n    }\n\n    return splited_animations;\n}\n\n//******************************************************************************\n// draw_annotations\n//******************************************************************************\n\nvoid Scene_renderer::draw_annotations(Curve& c, const glm::mat4& projection)\n{\n    // Parameters\n    const float min_arrow_dist(0.1f),\n                arrow_spacing(6.f),\n                arrow_size(8.f),\n                sphere_diam(4.f);\n\n    const glm::vec4 arrow_color(0.f, 0.f, 0.f, 1.f),\n                    sphere_color(0.f, 0.f, 0.f, 1.f);\n\n    auto annot_arrows = c.get_arrows(*state_->curve_selection.get());\n    auto annot_dots = c.get_markers(*state_->curve_selection.get());\n\n    // This variable points either to the filtered or original arrows\n    std::vector<Curve_annotations>* annot_ptr;\n\n    // If necessary, filter the annotations\n    std::vector<Curve_annotations> filtered_annotations;\n    if(filter_arrow_annotations_)\n    {\n        annot_ptr = &filtered_annotations;\n\n        for(size_t i = 0; i < annot_arrows.size(); ++i)\n        {\n            auto& current = annot_arrows[i];\n            double dist = std::numeric_limits<double>::max();\n\n            for(size_t j = i + 1; j < annot_arrows.size(); ++j)\n            {\n                auto& next = annot_arrows[j];\n\n                auto v = next.point - current.point;\n                double length =\n                    std::sqrt(v(0) * v(0) + v(1) * v(1) + v(2) * v(2));\n\n                dist = std::min(length, dist);\n            }\n\n            if(dist > min_arrow_dist)\n            {\n                filtered_annotations.push_back(current);\n            }\n        }\n    }\n    else\n    {\n        annot_ptr = &annot_arrows;\n    }\n\n    // Draw annotation points\n\n    for(auto& a : *annot_ptr)\n    {\n        // Copy and project point\n\n        glm::vec4 point(a.point(0), a.point(1), a.point(2), 1.f);\n        point = projection * point;\n        for(char i = 0; i < 3; ++i)\n            point[i] /= point[3];\n\n        glm::vec4 dir(a.dir(0), a.dir(1), a.dir(2), 1.f);\n        dir = projection * dir;\n        for(char i = 0; i < 3; ++i)\n            dir[i] /= dir[3];\n\n        glm::vec4 scale(region_.width() / 2,  region_.height() / 2, 0.f, 0.f);\n        glm::vec4 disp( region_.width() / 2,  region_.height() / 2, 0.f, 0.f);\n        point = point * scale + disp;\n        dir   = dir   * scale + disp;\n\n        dir = dir - point;\n        dir = glm::normalize(dir);\n\n        auto draw_arrow = [&](glm::vec4 pos, glm::vec4 dir, float size)\n        {\n            glm::vec4 left_side =\n                glm::rotateZ(dir, glm::radians(30.f)) * size;\n            glm::vec4 right_side =\n                glm::rotateZ(dir, glm::radians(-30.f)) * size;     \n\n            Screen_shader::Line_strip line;\n            line.emplace_back(Screen_shader::Line_point(glm::vec2(pos.x -  left_side.x, pos.y -  left_side.y), 1.f, arrow_color));\n            line.emplace_back(Screen_shader::Line_point(glm::vec2(pos.x,                pos.y               ), 1.f, arrow_color));\n            line.emplace_back(Screen_shader::Line_point(glm::vec2(pos.x - right_side.x, pos.y - right_side.y), 1.f, arrow_color));\n            screen_shader_->append_to_geometry(*screen_geometry_.get(), line);\n        };\n\n        switch(a.dimensionality)\n        {\n        case 1:\n            draw_arrow(point, dir, arrow_size);\n            break;\n        case 2:\n            draw_arrow(point + dir * 0.5f * arrow_spacing, dir, arrow_size);\n            draw_arrow(point - dir * 0.5f * arrow_spacing, dir, arrow_size);\n            break;\n        case 3:\n            draw_arrow(point, dir, arrow_size);\n            draw_arrow(point - dir * arrow_spacing, dir, arrow_size);\n            draw_arrow(point + dir * arrow_spacing, dir, arrow_size);\n            break;\n        case 4:\n            draw_arrow(point - dir * 1.5f * arrow_spacing, dir, arrow_size);\n            draw_arrow(point - dir * 0.5f * arrow_spacing, dir, arrow_size);\n            draw_arrow(point + dir * 0.5f * arrow_spacing, dir, arrow_size);\n            draw_arrow(point + dir * 1.5f * arrow_spacing, dir, arrow_size);\n            break;\n        }\n    }\n\n    // Draw switch points\n\n    for(auto& a : annot_dots)\n    {\n        Mesh mesh;\n        Mesh_generator::sphere(\n            5,\n            5,\n            sphere_diam / a(3),\n            glm::vec3(a(0), a(1), a(2)),\n            sphere_color,\n            mesh);\n        diffuse_shader_->append_to_geometry(*back_geometry_.get(), mesh);\n    }\n}\n\n//******************************************************************************\n// draw_legend\n//******************************************************************************\n\nvoid Scene_renderer::draw_legend(const Region& region)\n{\n    // Parameters\n\n    const auto rect_size(20.f),\n               spacing(7.5f);\n    const glm::vec4 col(1.f, 0.f, 0.f, 1.f);\n\n    auto draw_axis_legened = [&](\n        char pos,\n        const std::string& text,\n        glm::vec4 color)\n    {\n        // Make background\n\n        const auto x = region.width()  - (pos + 1) * (rect_size + spacing);\n        const auto y = region.height() - rect_size - spacing;\n\n        screen_shader_->append_to_geometry(\n        *screen_geometry_.get(),\n        Screen_shader::Rectangle(\n            x,\n            y,\n            x + rect_size,\n            y + rect_size,\n            color));\n\n        // Output text\n\n\n        const auto symbol_width(6.f);\n        const auto symbol_half_height(8.5f);\n        const auto x_displacement = text.size() * 0.5f * symbol_width;\n\n        text_renderer_->add_text(\n            region_,\n            glm::vec2(\n                x + 0.5f * rect_size - x_displacement,\n                y + 0.5f * rect_size + symbol_half_height),\n            text);\n    };\n\n    auto color_to_vec4 = [](const Color& c)\n    {\n        return glm::vec4(c.r_norm(), c.g_norm(), c.b_norm(), c.a_norm());\n    };\n\n    draw_axis_legened(\n        3,\n        \"x\",\n        color_to_vec4(state_->get_color(X_axis)));\n\n    draw_axis_legened(\n        2,\n        \"y\",\n        color_to_vec4(state_->get_color(Y_axis)));\n\n    draw_axis_legened(\n        1,\n        \"z\",\n        color_to_vec4(state_->get_color(Z_axis)));\n\n    draw_axis_legened(\n        0,\n        \"w\",\n        color_to_vec4(state_->get_color(W_axis)));\n}\n\n//******************************************************************************\n// move_curves_to_3D_plots\n//******************************************************************************\n\nvoid Scene_renderer::move_curves_to_3D_plots(float coeff,\n                                             std::vector<Curve>& curves)\n{\n    // Curve 1\n    for(auto& v : curves[0].get_vertices())\n        v(3) = v(3) + coeff * (state_->tesseract_size[3] / 2 - v(3));\n    // Curve 2\n    for(auto& v : curves[1].get_vertices())\n        v(3) = v(3) + coeff * (-state_->tesseract_size[3] / 2 - v(3));\n    // Curve 3\n    for(auto& v : curves[2].get_vertices())\n        v(2) = v(2) + coeff * (state_->tesseract_size[2] / 2 - v(2));\n    // Curve 4\n    for(auto& v : curves[3].get_vertices())\n        v(2) = v(2) + coeff * (-state_->tesseract_size[2] / 2 - v(2));\n    // Curve 5\n    for(auto& v : curves[4].get_vertices())\n        v(1) = v(1) + coeff * (-state_->tesseract_size[1] / 2 - v(1));\n    // Curve 6\n    for(auto& v : curves[5].get_vertices())\n        v(1) = v(1) + coeff * (state_->tesseract_size[1] / 2 - v(1));\n    // Curve 7\n    for(auto& v : curves[6].get_vertices())\n        v(0) = v(0) + coeff * (-state_->tesseract_size[0] / 2 - v(0));\n    // Curve 8\n    for(auto& v : curves[7].get_vertices())\n        v(0) = v(0) + coeff * (state_->tesseract_size[0] / 2 - v(0));\n}\n\n//******************************************************************************\n// move_curves_to_2D_plots\n//******************************************************************************\n\nvoid Scene_renderer::move_curves_to_2D_plots(\n    float coeff,\n    std::vector<Curve>& curves)\n{\n    // Curve 1\n    for(auto& v : curves[0].get_vertices())\n        v(2) = v(2) + coeff * (-state_->tesseract_size[2] / 2 - v(2));\n    // Curve 2\n    for(auto& v : curves[1].get_vertices())\n        v(2) = v(2) + coeff * (-state_->tesseract_size[2] / 2 - v(2));\n    // Curve 3\n    for(auto& v : curves[2].get_vertices())\n        v(2) = v(2) + coeff * (-state_->tesseract_size[2] / 2 - v(2));\n    // Curve 4\n    for(auto& v : curves[3].get_vertices())\n        v(1) = v(1) + coeff * (-state_->tesseract_size[1] / 2 - v(1));\n    // Curve 5\n    for(auto& v : curves[4].get_vertices())\n        v(1) = v(1) + coeff * (-state_->tesseract_size[1] / 2 - v(1));\n    // Curve 6\n    for(auto& v : curves[5].get_vertices())\n        v(0) = v(0) + coeff *\n        (0.5f * state_->tesseract_size[0] + state_->tesseract_size[3] - v(0));\n}\n\n//******************************************************************************\n// tesseract_unfolding\n//******************************************************************************\n\nvoid Scene_renderer::tesseract_unfolding(\n    float coeff,\n    std::vector<Cube>& plots_3D,\n    std::vector<std::vector<Curve>>& curves_3D)\n{\n    auto transform_3D_plot =\n        [](Scene_wireframe_object& c,\n           boost::numeric::ublas::matrix<float>& rot,\n           Scene_vertex_t disp)\n    {\n        for(auto& v : c.get_vertices())\n        {\n            for(int i = 0; i < 5; ++i)\n                v(i) += disp(i);\n\n            v = prod(v, rot);\n\n            for(int i = 0; i < 5; ++i)\n                v(i) -= disp(i);\n        }\n    };\n\n    // Cube and curve 1 and 5\n    {\n        auto rot = Matrix_lib_f::getYWRotationMatrix(\n            static_cast<float>(-coeff * PI / 2));\n        Scene_vertex_t disp1(5);\n        disp1 <<= 0,\n                  state_->tesseract_size[1] / 2,\n                  0,\n                  state_->tesseract_size[3] / 2,\n                  0;\n\n        transform_3D_plot(plots_3D[0], rot, disp1);\n        transform_3D_plot(plots_3D[4], rot, disp1);\n\n        const auto vert = plots_3D[4].get_vertices()[0];\n        Scene_vertex_t disp2(5);\n        disp2 <<= 0, -vert(1), 0, -vert(3), 0;\n\n        transform_3D_plot(plots_3D[0], rot, disp2);\n\n        for(auto& c: curves_3D)\n        {\n            transform_3D_plot(c[4], rot, disp1);\n\n            transform_3D_plot(c[0], rot, disp1);\n            transform_3D_plot(c[0], rot, disp2);\n        }\n    }\n    // Cube and curve 3\n    {\n        auto rot = Matrix_lib_f::getZWRotationMatrix(\n            static_cast<float>(coeff * PI / 2));\n        Scene_vertex_t disp(5);\n        disp <<= 0,\n                 0,\n                 -state_->tesseract_size[2] / 2,\n                 state_->tesseract_size[3] / 2,\n                 0;\n\n        transform_3D_plot(plots_3D[2], rot, disp);\n        \n        for(auto& c: curves_3D)\n            transform_3D_plot(c[2], rot, disp);\n    }\n    // Cube and curve 4\n    {\n        auto rot = Matrix_lib_f::getZWRotationMatrix(\n            static_cast<float>(-coeff * PI / 2));\n        Scene_vertex_t disp(5);\n        disp <<= 0,\n                 0,\n                 state_->tesseract_size[2] / 2,\n                 state_->tesseract_size[3] / 2,\n                 0;\n\n        transform_3D_plot(plots_3D[3], rot, disp);\n\n        for(auto& c: curves_3D)\n            transform_3D_plot(c[3], rot, disp);\n    }\n    // Cube and curve 6\n    {\n        auto rot = Matrix_lib_f::getYWRotationMatrix(\n            static_cast<float>(coeff * PI / 2));\n        Scene_vertex_t disp(5);\n        disp <<= 0,\n                 -state_->tesseract_size[1] / 2,\n                 0,\n                 state_->tesseract_size[3] / 2,\n                 0;\n\n        transform_3D_plot(plots_3D[5], rot, disp);\n\n        for(auto& c: curves_3D)\n            transform_3D_plot(c[5], rot, disp);\n    }\n    // Cube and curve 7\n    {\n        auto rot = Matrix_lib_f::getXWRotationMatrix(\n            static_cast<float>(coeff * PI / 2));\n        Scene_vertex_t disp(5);\n        disp <<= state_->tesseract_size[0] / 2,\n                 0,\n                 0,\n                 state_->tesseract_size[3] / 2,\n                 0;\n\n        transform_3D_plot(plots_3D[6], rot, disp);\n\n        for(auto& c: curves_3D)\n            transform_3D_plot(c[6], rot, disp);\n    }\n    // Cube and curve 8\n    {\n        auto rot = Matrix_lib_f::getXWRotationMatrix(\n            static_cast<float>(-coeff * PI / 2));\n        Scene_vertex_t disp(5);\n        disp <<= -state_->tesseract_size[0] / 2,\n                  0,\n                  0,\n                  state_->tesseract_size[3] / 2,\n                  0;\n\n        transform_3D_plot(plots_3D[7], rot, disp);\n\n        for(auto& c: curves_3D)\n            transform_3D_plot(c[7], rot, disp);\n    }\n}\n\n//******************************************************************************\n// get_rotation_matrix\n//******************************************************************************\n\nboost::numeric::ublas::matrix<float> Scene_renderer::get_rotation_matrix()\n{\n    auto m = Matrix_lib_f::getXYRotationMatrix(state_->xy_rot);\n    m = prod(m, Matrix_lib_f::getYZRotationMatrix(state_->yz_rot));\n    m = prod(m, Matrix_lib_f::getZXRotationMatrix(state_->zx_rot));\n    m = prod(m, Matrix_lib_f::getXWRotationMatrix(state_->xw_rot));\n    m = prod(m, Matrix_lib_f::getYWRotationMatrix(state_->yw_rot));\n    m = prod(m, Matrix_lib_f::getZWRotationMatrix(state_->zw_rot));\n\n    return m;\n}\n\n//******************************************************************************\n// get_rotation_matrix\n//******************************************************************************\n\nboost::numeric::ublas::matrix<float>\nScene_renderer::get_rotation_matrix(float view_straightening)\n{\n    auto angle_xy = (1 - view_straightening) * state_->xy_rot,\n         angle_yz = (1 - view_straightening) * state_->yz_rot,\n         angle_zx = (1 - view_straightening) * state_->zx_rot,\n         angle_xw = (1 - view_straightening) * state_->xw_rot,\n         angle_yw = (1 - view_straightening) * state_->yw_rot,\n         angle_zw = (1 - view_straightening) * state_->zw_rot;\n\n    auto m = Matrix_lib_f::getXYRotationMatrix(angle_xy);\n    m = prod(m, Matrix_lib_f::getYZRotationMatrix(angle_yz));\n    m = prod(m, Matrix_lib_f::getZXRotationMatrix(angle_zx));\n    m = prod(m, Matrix_lib_f::getXWRotationMatrix(angle_xw));\n    m = prod(m, Matrix_lib_f::getYWRotationMatrix(angle_yw));\n    m = prod(m, Matrix_lib_f::getZWRotationMatrix(angle_zw));\n\n    return m;\n}\n\n//******************************************************************************\n// draw_3D_plot\n//******************************************************************************\n\nvoid Scene_renderer::draw_3D_plot(Cube& cube, float opacity)\n{\n    for(size_t i = 0; i < cube.edges().size(); ++i)\n    {\n        auto const& e = cube.edges()[i];\n\n        Mesh t_mesh;\n\n        auto& current = cube.get_vertices()[e.vert1];\n        auto& next = cube.get_vertices()[e.vert2];\n        const glm::vec4 col = ColorToGlm(e.color, opacity);\n\n        Mesh_generator::cylinder(\n            5,\n            tesseract_thickness_ / current(3),\n            tesseract_thickness_ / next(3),\n            glm::vec3(current(0), current(1), current(2)),\n            glm::vec3(next(0), next(1), next(2)),\n            col,\n            t_mesh);\n\n        opacity < 1.0 ? diffuse_shader_->append_to_geometry(\n                            *front_geometry_.get(), t_mesh)\n                      : diffuse_shader_->append_to_geometry(\n                            *back_geometry_.get(), t_mesh);\n    }\n}\n\n//******************************************************************************\n// draw_2D_plot\n//******************************************************************************\n\nvoid Scene_renderer::draw_2D_plot(Scene_wireframe_object& plot)\n{\n    for(auto const& e : plot.edges())\n    {\n        Mesh t_mesh;\n\n        auto& current = plot.get_vertices()[e.vert1];\n        auto& next = plot.get_vertices()[e.vert2];\n        const glm::vec4 col = ColorToGlm(e.color, 1.f);\n\n        Mesh_generator::cylinder(\n            5,\n            tesseract_thickness_ / current(3),\n            tesseract_thickness_ / next(3),\n            glm::vec3(current(0), current(1), current(2)),\n            glm::vec3(next(0), next(1), next(2)),\n            col,\n            t_mesh);\n\n        diffuse_shader_->append_to_geometry(*back_geometry_.get(), t_mesh);\n    }\n}\n\n//******************************************************************************\n// plots_unfolding\n//******************************************************************************\n\nvoid Scene_renderer::plots_unfolding(\n    float coeff,\n    std::vector<Square>& plots_2D,\n    std::vector<std::vector<Curve>>& curves_2D)\n{\n    auto transform_3D_plot =\n        [](Scene_wireframe_object& c,\n           boost::numeric::ublas::matrix<float>& rot,\n           Scene_vertex_t& disp)\n    {\n        for(auto& v : c.get_vertices())\n        {\n            // We have to create a copy vector of the size of four in order\n            // to multiype to the 4x4 rotation matrix\n            Scene_vertex_t copy_v(4);\n            copy_v <<= v(0), v(1), v(2), v(3);\n\n            for(int i = 0; i < 4; ++i)\n                copy_v(i) += disp(i);\n\n            copy_v = prod(copy_v, rot);\n\n            for(int i = 0; i < 4; ++i)\n                copy_v(i) -= disp(i);\n\n            v <<= copy_v(0), copy_v(1), copy_v(2), copy_v(3), 0;\n        }\n    };\n\n    {\n        auto anchor = plots_2D[1].get_vertices()[0];\n        auto rot_axis =\n            plots_2D[1].get_vertices()[1] - plots_2D[1].get_vertices()[0];\n        auto rot = Matrix_lib_f::getRotationMatrix(\n            static_cast<float>(coeff * PI / 2),\n            rot_axis(0),\n            rot_axis(1),\n            rot_axis(2));\n        Scene_vertex_t disp(5);\n        disp <<= -anchor(0), -anchor(1), -anchor(2), 0, 0;\n\n        transform_3D_plot(plots_2D[3], rot, disp);\n        transform_3D_plot(plots_2D[4], rot, disp);\n        transform_3D_plot(plots_2D[5], rot, disp);\n\n        for(auto& c: curves_2D)\n        {\n            transform_3D_plot(c[3], rot, disp);\n            transform_3D_plot(c[4], rot, disp);\n            transform_3D_plot(c[5], rot, disp);\n        }\n    }\n    {\n        auto anchor = plots_2D[2].get_vertices()[1];\n        auto rot_axis =\n            plots_2D[4].get_vertices()[2] - plots_2D[4].get_vertices()[1];\n        auto rot = Matrix_lib_f::getRotationMatrix(\n            static_cast<float>(coeff * PI / 2),\n            rot_axis(0),\n            rot_axis(1),\n            rot_axis(2));\n        Scene_vertex_t disp(5);\n        disp <<= -anchor(0), -anchor(1), -anchor(2), 0, 0;\n\n        transform_3D_plot(plots_2D[5], rot, disp);\n\n        for(auto& c: curves_2D)\n            transform_3D_plot(c[5], rot, disp);\n    }\n}\n\n//******************************************************************************\n// plots_unfolding\n//******************************************************************************\n\nvoid Scene_renderer::draw_labels_in_2D(const glm::mat4& projection)\n{\n    // Draw labels in 2D\n    if(label_points_.size() != 3)\n        return;\n\n    glm::vec4 upper_left(\n        label_points_[0](0), label_points_[0](1), label_points_[0](2), 1.f);\n    glm::vec4 bottom_left(\n        label_points_[1](0), label_points_[1](1), label_points_[1](2), 1.f);\n    glm::vec4 bottom_right(\n        label_points_[2](0), label_points_[2](1), label_points_[2](2), 1.f);\n\n    upper_left = projection * upper_left;\n    bottom_left = projection * bottom_left;\n    bottom_right = projection * bottom_right;\n\n    for(char i = 0; i < 3; ++i)\n    {\n        upper_left[i]   /= upper_left[3];\n        bottom_left[i]  /= bottom_left[3];\n        bottom_right[i] /= bottom_right[3];\n    }\n\n    glm::vec4 scale(region_.width() / 2, region_.height() / 2, 0.f, 0.f);\n    glm::vec4 disp(region_.width() / 2, region_.height() / 2, 0.f, 0.f);\n    upper_left = upper_left * scale + disp;\n    bottom_left = bottom_left * scale + disp;\n    bottom_right = bottom_right * scale + disp;\n\n    std::vector<glm::vec4> points;\n    auto horiz_dir = bottom_right - bottom_left;\n\n    auto lenght = glm::length(horiz_dir);\n\n    glm::vec4 horiz_disp(-3.f, -0.025f * lenght, 0.f, 0.f);\n    for(int i = 0; i < 3; ++i)\n        points.push_back(\n            bottom_left + horiz_dir * static_cast<float>((2.f * i + 1.f) / 6.f) + horiz_disp);\n\n    auto vert_dir = upper_left - bottom_left;\n    glm::vec4 vert_disp(-0.08f * lenght - 3.f, 6.f, 0.f, 0.f);\n    for(int i = 0; i < 3; ++i)\n        points.push_back(\n            bottom_left + vert_dir * static_cast<float>((2.f * i + 1.f) / 6.f) + vert_disp);\n\n\n    text_renderer_->add_text(\n        region_,\n        glm::vec2(\n            points[0].x,\n            points[0].y),\n        std::string(\"X\"));\n\n    text_renderer_->add_text(\n        region_,\n        glm::vec2(\n            points[1].x,\n            points[1].y),\n        std::string(\"W\"));\n\n    text_renderer_->add_text(\n        region_,\n        glm::vec2(\n            points[2].x,\n            points[2].y),\n        std::string(\"Y\"));\n\n    text_renderer_->add_text(\n        region_,\n        glm::vec2(\n            points[3].x,\n            points[3].y),\n        std::string(\"-Z\"));\n\n    text_renderer_->add_text(\n        region_,\n        glm::vec2(\n            points[4].x,\n            points[4].y),\n        std::string(\"Y\"));\n\n    text_renderer_->add_text(\n        region_,\n        glm::vec2(\n            points[5].x,\n            points[5].y),\n        std::string(\"W\"));\n}\n", "meta": {"hexsha": "79f8e4a0bd02a996bdaab9e967074433f49fae91", "size": 46464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Scene_renderer.cpp", "max_stars_repo_name": "aleksandr-amirkhanov/ManyLands", "max_stars_repo_head_hexsha": "5565d9013b54a501544c79fb260ccbe0a1cfb31c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-28T18:48:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T16:18:42.000Z", "max_issues_repo_path": "src/Scene_renderer.cpp", "max_issues_repo_name": "aleksandr-amirkhanov/ManyLands", "max_issues_repo_head_hexsha": "5565d9013b54a501544c79fb260ccbe0a1cfb31c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Scene_renderer.cpp", "max_forks_repo_name": "aleksandr-amirkhanov/ManyLands", "max_forks_repo_head_hexsha": "5565d9013b54a501544c79fb260ccbe0a1cfb31c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T14:23:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T14:23:06.000Z", "avg_line_length": 32.5606166783, "max_line_length": 130, "alphanum_fraction": 0.4787147039, "num_tokens": 11140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.027585283126145898, "lm_q1q2_score": 0.010414565854035631}}
{"text": "#include \"orbit_integrator.hpp\"\n#include \"profile.hpp\"\n\n#include <boost/python.hpp>\n#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv.h>\n# include <boost/python/return_opaque_pointer.hpp>\n# include <boost/python/def.hpp>\n# include <boost/python/module.hpp>\n# include <boost/python/return_value_policy.hpp>\n\n//struct void\nBOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(gsl_odeiv_step_type);\n\nnamespace gd {\nusing namespace boost::python;\n/*\nstruct gsl_odeiv_step_type_to_pyint\n{\n\tgsl_odeiv_step_type_to_pyint() {\n\t\tboost::python::converter::registry::push_back(\n\t\t\t&convertible,\n\t\t\t&construct,\n\t\t\tboost::python::type_id<gsl_odeiv_step_type_to_pyint>()\n\t\t);\n\t}\n\tstatic PyObject* convert(const gsl_odeiv_step_type* x)\n\t{        \n\t\treturn PyInt_FromLong((long int)x);\n\t}\n\tstatic const gsl_odeiv_step_type* execute(PyObject* x)\n\t{\n\t\treturn (const gsl_odeiv_step_type*)PyInt_AsLong(x);\n\t}\n};\n*/\n\n\n\nvoid py_export_orbit_integrator() {\n\tclass_< OrbitIntegrator, boost::noncopyable >(\"OrbitIntegrator\", no_init);\n\tclass_< OrbitIntegratorSet, boost::noncopyable >(\"OrbitIntegratorSet\", no_init);\n\n\tclass_<OrbitIntegratorEuler, bases<OrbitIntegrator> >(\"OrbitIntegratorEuler\", init<double, double, double, double>())\n\t\t.def(\"integrate\", (&OrbitIntegratorEuler::integrate))\n\t;\n\tclass_<OrbitIntegratorLeapFrog, bases<OrbitIntegrator> >(\"OrbitIntegratorLeapFrog\", init<double, double, double, double>())\n\t\t.def(\"integrate\", (&OrbitIntegratorLeapFrog::integrate))\n\t;\n\tclass_<OrbitIntegratorSetLeapFrog, bases<OrbitIntegratorSet> >(\"OrbitIntegratorSetLeapFrog\", init<ProfileModel*, int>())\n\t\t\t.def(\"integrate\", (&OrbitIntegratorSetLeapFrog::integrate))\n\t\t\t\t\t;\n\tclass_<OrbitIntegratorSetLeapFrog3d, bases<OrbitIntegratorSet> >(\"OrbitIntegratorSetLeapFrog3d\", init<ProfileModel3d*, int>())\n\t\t\t.def(\"integrate\", (&OrbitIntegratorSetLeapFrog3d::integrate))\n\t\t\t\t\t;\n\tclass_<OrbitIntegratorGSL>(\"OrbitIntegratorGSL\", init<ProfileModel*, optional<double, double, const gsl_odeiv_step_type*> >())\n\t\t.def(\"integrate\", (&OrbitIntegratorGSL::integrate))\n\t\t;\n\tclass_<OrbitIntegratorAxiGSL>(\"OrbitIntegratorAxiGSL\", init<ProfileModelAxi*, optional<double, double, const gsl_odeiv_step_type*> >())\n\t\t.def(\"integrate\", (&OrbitIntegratorAxiGSL::integrate))\n\t\t;\n\tclass_<OrbitIntegrator2dGSL>(\"OrbitIntegrator2dGSL\", init<ProfileModel2d*, optional<double, double, const gsl_odeiv_step_type*> >())\n\t\t.def(\"integrate\", (&OrbitIntegrator2dGSL::integrate))\n\t\t;\n\tclass_<OrbitIntegratorGSL3d>(\"OrbitIntegratorGSL3d\", init<ProfileModel*, optional<double, double, const gsl_odeiv_step_type*> >())\n\t\t.def(\"integrate\", (&OrbitIntegratorGSL3d::integrate))\n\t\t;\n\topaque<gsl_odeiv_step_type>();\n\tscope().attr(\"gsl_odeiv_step_rk2\") = (gsl_odeiv_step_type*)&gsl_odeiv_step_rk2;\n\tscope().attr(\"gsl_odeiv_step_rk4\") = (gsl_odeiv_step_type*)&gsl_odeiv_step_rk4;\n\tscope().attr(\"gsl_odeiv_step_rkf45\") = (gsl_odeiv_step_type*)&gsl_odeiv_step_rkf45;\n\tscope().attr(\"gsl_odeiv_step_rkck\") = (gsl_odeiv_step_type*)&gsl_odeiv_step_rkck;\n\tscope().attr(\"gsl_odeiv_step_rk8pd\") = (gsl_odeiv_step_type*)&gsl_odeiv_step_rk8pd;\n\tscope().attr(\"gsl_odeiv_step_rk2imp\") = (gsl_odeiv_step_type*)&gsl_odeiv_step_rk2imp;\n\tscope().attr(\"gsl_odeiv_step_rk4imp\") = (gsl_odeiv_step_type*)&gsl_odeiv_step_rk4imp;\n\t//to_python_converter<const gsl_odeiv_step_type*, gsl_odeiv_step_type_to_pyint> ();\n\t//lvalue_from_pytype<pyfile_to_FILE,&PyFile_Type> ();\n\t//lvalue_from_pytype<gsl_odeiv_step_type_to_pyint, &PyInt_Type> ();\n\t//opaque\n\n\t//handle<> h(gsl_odeiv_step_rkck);\n\t//scope().attr(\"gsl_odeiv_step_rkck\") = h;\n}\n\nint f(double t, const double y[], double f[], void *params) {\n\t//OrbitIntegratorGSL *oi = ( OrbitIntegratorGSL*)params;\n\tProfileModel* profile_model = (ProfileModel*)params;\n\tdouble r = sqrt(y[0]*y[0] + y[1]*y[1]);\n\tdouble dphidr = profile_model->dphidr(r)* 3.2407764868054621e-17;\n\t//double dphidr = G * mass * r / pow((r*r + scale*scale), (3./2)) * 3.2407764868054621e-17; \n\tdouble Fx = -dphidr*y[0]/r;\n\tdouble Fy = -dphidr*y[1]/r;\n\t//printf (\"%.5e %.5e %.5e %.5e\\n\", r, dphidr, Fx, Fy);\n\tf[0] = y[2]*3.2407764868054621e-17;\n\tf[1] = y[3]*3.2407764868054621e-17;\n\tf[2] = Fx;\n\tf[3] = Fy;\n\treturn GSL_SUCCESS;\n}\n\nstruct f_axi_params_type {\n\tProfileModelAxi* profile_model;\n\tdouble Lz;\n};\nint f_axi(double t, const double y[], double f[], void *params) {\n\t//OrbitIntegratorGSL *oi = ( OrbitIntegratorGSL*)params;\n\tProfileModelAxi* profile_model = ((f_axi_params_type*)params)->profile_model;\n\tdouble Lz = ((f_axi_params_type*)params)->Lz;\n\tdouble x = y[0];\n\tdouble z = y[1];\n\tdouble dphidx_eff = profile_model->dphidx_eff(x, z, Lz)* 3.2407764868054621e-17;\n\tdouble dphidz_eff = profile_model->dphidz_eff(x, z, Lz)* 3.2407764868054621e-17;\n//double dphidr = G * mass * r / pow((r*r + scale*scale), (3./2)) * 3.2407764868054621e-17; \n\tdouble Fx = -dphidx_eff;\n\tdouble Fz = -dphidz_eff;\n\t//printf (\"%.5e %.5e %.5e %.5e\\n\", r, dphidr, Fx, Fy);\n\tf[0] = y[2]*3.2407764868054621e-17;\n\tf[1] = y[3]*3.2407764868054621e-17;\n\tf[2] = Fx;\n\tf[3] = Fz;\n\treturn GSL_SUCCESS;\n}\nstruct orbit2d_params_type {\n\tProfileModel2d* profile_model;\n\tdouble angular_velocity;\n};\n\nint f2d(double t, const double y[], double f[], void *params) {\n\t//OrbitIntegratorGSL3d *oi = ( OrbitIntegratorGSL3d*)params;\n\torbit2d_params_type* orbit2d_params = (orbit2d_params_type*)params;\n\t//ProfileModel2d* profile_model = (ProfileModel2d*)params;\n\t//double r = sqrt(y[0]*y[0] + y[1]*y[1] + y[2]*y[2]);\n\tdouble angular_velocity = orbit2d_params->angular_velocity * 3.2407764868054621e-17;\n\tdouble angular_velocity_sq = angular_velocity * angular_velocity;\n\t//printf(\"%f \", angular_velocity);\n\tdouble dphidx = orbit2d_params->profile_model->dphidx(y[0], y[1])* 3.2407764868054621e-17 - angular_velocity_sq*y[0];\n\tdouble dphidy = orbit2d_params->profile_model->dphidy(y[0], y[1])* 3.2407764868054621e-17 - angular_velocity_sq*y[1];\n//double dphidr = G * mass * r / pow((r*r + scale*scale), (3./2)) * 3.2407764868054621e-17; \n\tdouble Fx = -dphidx + 2 * angular_velocity * y[3];\n\tdouble Fy = -dphidy - 2 * angular_velocity * y[2];\n\t//printf (\"%.5e %.5e %.5e %.5e\\n\", r, dphidr, Fx, Fy);\n\tf[0] = y[2]*3.2407764868054621e-17;\n\tf[1] = y[3]*3.2407764868054621e-17;\n\tf[2] = Fx;\n\tf[3] = Fy;\n\treturn GSL_SUCCESS;\n}\n\nint f3d(double t, const double y[], double f[], void *params) {\n\t//OrbitIntegratorGSL3d *oi = ( OrbitIntegratorGSL3d*)params;\n\tProfileModel* profile_model = (ProfileModel*)params;\n\tdouble r = sqrt(y[0]*y[0] + y[1]*y[1] + y[2]*y[2]);\n\tdouble dphidr = profile_model->dphidr(r)* 3.2407764868054621e-17;\n\t//double dphidr = G * mass * r / pow((r*r + scale*scale), (3./2)) * 3.2407764868054621e-17; \n\tdouble Fx = -dphidr*y[0]/r;\n\tdouble Fy = -dphidr*y[1]/r;\n\tdouble Fz = -dphidr*y[2]/r;\n\t//printf (\"%.5e %.5e %.5e %.5e\\n\", r, dphidr, Fx, Fy);\n\tf[0] = y[3]*3.2407764868054621e-17;\n\tf[1] = y[4]*3.2407764868054621e-17;\n\tf[2] = y[5]*3.2407764868054621e-17;\n\tf[3] = Fx;\n\tf[4] = Fy;\n\tf[5] = Fz;\n\treturn GSL_SUCCESS;\n}\n/*\nint  (hEadjust) (void * state, size_t dim, unsigned int ord, const double y[], const double yerr[], const double yp[], double * h) {\n\treturn GSL_ODEIV_HADJ_NIL;\n}\n\nconst gsl_odeiv_control_type Econtrol_type = {\"E control\", NULL, NULL, &hEadjust, NULL};\n\t\t\nstruct Econtrol_state {\n\tProfile* profile;\n\tdouble maxrelE, time;\n};\n\ngsl_odeiv_control* gsl_odeiv_control_E(Profile* profile, double maxrelE, double time) {\n\tgsl_odeiv_control* c = (gsl_odeiv_control*)malloc(sizeof(gsl_odeiv_control));\n\t//gsl_odeiv_control * c = gsl_odeiv_control_alloc (&Econtrol_type);\n\t\n\tEcontrol_state* econtrol_state = (Econtrol_state*)malloc(sizeof(Econtrol_state));\n\tecontrol_state->profile = profile;\n\tecontrol_state->maxrelE = maxrelE;\n\tecontrol_state->time = time;\n\t\n\tc->state = econtrol_state;\n\tc->type = &Econtrol_type;\n\treturn c;\n\t \n\t\t\n}\n*/\nvoid OrbitIntegrator2dGSL::integrate(int N, double angular_velocity, double_vector dt, double_matrix q0, double_matrix v0, double_matrix xout, double_matrix yout , double_matrix vxout, double_matrix vyout) {\n\tdouble* xoutp = xout.data().begin();\n\tdouble* youtp = yout.data().begin();\n\tdouble* vxoutp = vxout.data().begin();\n\tdouble* vyoutp = vyout.data().begin();\n\tint no_particles = dt.size();\n\t\n\t\n\tfor(int i = 0; i < no_particles; i++) {\n\t\t//double t = 0;\n\t\t//double Fx, Fy;\n\t\tdouble  x = q0(i,0);\n\t\tdouble  y = q0(i,1);\n\t\tdouble vx = v0(i,0);\n\t\tdouble vy = v0(i,1);\n\t\t//const gsl_odeiv_step_type * T = gsl_odeiv_step_rkck;\n\t\tdouble t1 = 0.0, t2 = dt(i);\n\t\tdouble stepsize = dt(i);\n\t\tdouble phasespace[4];\n\t\t//printf(\"%p %p\\n\", gsl_odeiv_step_type_, gsl_odeiv_step_rkck);\n\t\tgsl_odeiv_step * s\t\t= gsl_odeiv_step_alloc (gsl_odeiv_step_type_, 4);\n\t\tgsl_odeiv_control * c\t= gsl_odeiv_control_y_new (error_abs, error_rel);\n\t\tgsl_odeiv_evolve * e\t= gsl_odeiv_evolve_alloc (4);\n\t\t\n\t\torbit2d_params_type params = {profile_model, angular_velocity};\n\t\tgsl_odeiv_system sys = {f2d, NULL, 4, &params};\n\t\tphasespace[0] = x;\n\t\tphasespace[1] = y;\n\t\tphasespace[2] = vx;\n\t\tphasespace[3] = vy;\n\t\t\n\t\tfor(int j = 0; j < N; j++) {\n\t\t\t\n\t\t\tint status = GSL_SUCCESS;\n\t\t\twhile(t1 < t2) {\n\t\t\t\tstatus = gsl_odeiv_evolve_apply (e, c, s, &sys, &t1, t2, &stepsize, phasespace);\n\t\t\t\tif (status != GSL_SUCCESS)\n\t\t\t\t\tbreak;\n\t\t\t\t//printf (\"%.5e %.5e %.5e %.5e\\n\", t, phasespace[0], phasespace[1], stepsize);\n\t\t\t}\n\t\t\tt2 += dt(i);\n\t\t\tif (status != GSL_SUCCESS) {\n\t\t\t\tprintf (\"error integrating\\n\");\n\t\t\t}\n\t\t\txoutp[i*N+j] = phasespace[0];\n\t\t\tyoutp[i*N+j] = phasespace[1];\n\t\t\tvxoutp[i*N+j] = phasespace[2];\n\t\t\tvyoutp[i*N+j] = phasespace[3];\n\t\t}\n\t}\n}\n\nvoid OrbitIntegratorGSL3d::integrate(int N, double_vector dt, double_matrix q0, double_matrix v0, double_matrix xout, double_matrix yout, double_matrix zout, double_matrix vxout, double_matrix vyout, double_matrix vzout) {\n\tdouble* xoutp = xout.data().begin();\n\tdouble* youtp = yout.data().begin();\n\tdouble* zoutp = zout.data().begin();\n\tdouble* vxoutp = vxout.data().begin();\n\tdouble* vyoutp = vyout.data().begin();\n\tdouble* vzoutp = vzout.data().begin();\n\tint no_particles = dt.size();\n\n\tfor(int i = 0; i < no_particles; i++) {\n\t\t//double t = 0;\n\t\t//double Fx, Fy;\n\t\tdouble  x = q0(i,0);\n\t\tdouble  y = q0(i,1);\n\t\tdouble  z = q0(i,2);\n\t\tdouble vx = v0(i,0);\n\t\tdouble vy = v0(i,1);\n\t\tdouble vz = v0(i,2);\n\t\t//const gsl_odeiv_step_type * T = gsl_odeiv_step_rkck;\n\t\tdouble t1 = 0.0, t2 = dt(i);\n\t\tdouble stepsize = dt(i);\n\t\tdouble phasespace[6];\n\t\t//printf(\"%p %p\\n\", gsl_odeiv_step_type_, gsl_odeiv_step_rkck);\n\t\tgsl_odeiv_step * s\t\t= gsl_odeiv_step_alloc (gsl_odeiv_step_type_, 6);\n\t\tgsl_odeiv_control * c\t= gsl_odeiv_control_y_new (error_abs, error_rel);\n\t\tgsl_odeiv_evolve * e\t= gsl_odeiv_evolve_alloc (6);\n\t\t\n\t\tgsl_odeiv_system sys = {f3d, NULL, 6, profile_model};\n\t\tphasespace[0] = x;\n\t\tphasespace[1] = y;\n\t\tphasespace[2] = z;\n\t\tphasespace[3] = vx;\n\t\tphasespace[4] = vy;\n\t\tphasespace[5] = vz;\n\n\t\tfor(int j = 0; j < N; j++) {\n\n\t\t\tint status = GSL_SUCCESS;\n\t\t\twhile(t1 < t2) {\n\t\t\t\tstatus = gsl_odeiv_evolve_apply (e, c, s, &sys, &t1, t2, &stepsize, phasespace);\n\t\t\t\tif (status != GSL_SUCCESS)\n\t\t\t\t\tbreak;\n\t\t\t\t//printf (\"%.5e %.5e %.5e %.5e\\n\", t, phasespace[0], phasespace[1], stepsize);\n\t\t\t}\n\t\t\tt2 += dt(i);\n\t\t\tif (status != GSL_SUCCESS) {\n\t\t\t\tprintf (\"error integrating\\n\");\n\t\t\t}\n\t\t\txoutp[i*N+j] = phasespace[0];\n\t\t\tyoutp[i*N+j] = phasespace[1];\n\t\t\tzoutp[i*N+j] = phasespace[2];\n\t\t\tvxoutp[i*N+j] = phasespace[3];\n\t\t\tvyoutp[i*N+j] = phasespace[4];\n\t\t\tvzoutp[i*N+j] = phasespace[5];\n\t\t}\n\t}\n}\n\nvoid OrbitIntegratorGSL::integrate(int N, double_vector dt, double_matrix q0, double_matrix v0, double_matrix xout, double_matrix yout, double_matrix vxout, double_matrix vyout) {\n\tdouble* xoutp = xout.data().begin();\n\tdouble* youtp = yout.data().begin();\n\tdouble* vxoutp = vxout.data().begin();\n\tdouble* vyoutp = vyout.data().begin();\n\tint no_particles = dt.size();\n\n\tfor(int i = 0; i < no_particles; i++) {\n\t\t//double t = 0;\n\t\t//double Fx, Fy;\n\t\tdouble  x = q0(i,0);\n\t\tdouble  y = q0(i,1);\n\t\tdouble vx = v0(i,0);\n\t\tdouble vy = v0(i,1);\n\t\t//const gsl_odeiv_step_type * T = gsl_odeiv_step_rk8pd;\n\t\tdouble t1 = 0.0, t2 = dt(i);\n\t\tdouble stepsize = dt(i);\n\t\tdouble phasespace[4];\n\n\t\tgsl_odeiv_step * s\t\t= gsl_odeiv_step_alloc (gsl_odeiv_step_type_, 4);\n\t\tgsl_odeiv_control * c\t= gsl_odeiv_control_y_new (error_abs, error_rel);\n\t\tgsl_odeiv_evolve * e\t= gsl_odeiv_evolve_alloc (4);\n\t\t\n\t\tgsl_odeiv_system sys = {f, NULL, 4, profile_model};\n\t\tphasespace[0] = x;\n\t\tphasespace[1] = y;\n\t\tphasespace[2] = vx;\n\t\tphasespace[3] = vy;\n\n\t\tfor(int j = 0; j < N; j++) {\n\n\t\t\tint status = GSL_SUCCESS;\n\t\t\twhile(t1 < t2) {\n\t\t\t\tstatus = gsl_odeiv_evolve_apply (e, c, s, &sys, &t1, t2, &stepsize, phasespace);\n\t\t\t\tif (status != GSL_SUCCESS)\n\t\t\t\t\tbreak;\n\t\t\t\t//printf (\"%.5e %.5e %.5e %.5e\\n\", t, phasespace[0], phasespace[1], stepsize);\n\t\t\t}\n\t\t\tt2 += dt(i);\n\t\t\tif (status != GSL_SUCCESS) {\n\t\t\t\tprintf (\"error integrating\\n\");\n\t\t\t}\n\t\t\txoutp[i*N+j] = phasespace[0];\n\t\t\tyoutp[i*N+j] = phasespace[1];\n\t\t\tvxoutp[i*N+j] = phasespace[2];\n\t\t\tvyoutp[i*N+j] = phasespace[3];\n\t\t}\n\t}\n}\n\t\n\nvoid OrbitIntegratorAxiGSL::integrate(int N, double_vector dt, double_vector Lz, double_matrix q0, double_matrix v0, double_matrix xout, double_matrix zout, double_matrix vxout, double_matrix vzout) {\n\tdouble* xoutp = xout.data().begin();\n\tdouble* zoutp = zout.data().begin();\n\tdouble* vxoutp = vxout.data().begin();\n\tdouble* vzoutp = vzout.data().begin();\n\tint no_particles = dt.size();\n\t\n\tfor(int i = 0; i < no_particles; i++) {\n\t\t//double t = 0;\n\t\t//double Fx, Fy;\n\t\tdouble  x = q0(i,0);\n\t\tdouble  z = q0(i,1);\n\t\tdouble vx = v0(i,0);\n\t\tdouble vz = v0(i,1);\n\t\tdouble Lzi = Lz(i);\n//const gsl_odeiv_step_type * T = gsl_odeiv_step_rk8pd;\n\t\tdouble t1 = 0.0, t2 = dt(i);\n\t\tdouble stepsize = dt(i);\n\t\tdouble phasespace[4];\n\t\t\n\t\tgsl_odeiv_step * s\t\t= gsl_odeiv_step_alloc (gsl_odeiv_step_type_, 4);\n\t\tgsl_odeiv_control * c\t= gsl_odeiv_control_y_new (error_abs, error_rel);\n\t\tgsl_odeiv_evolve * e\t= gsl_odeiv_evolve_alloc (4);\n\t\t\n\t\tf_axi_params_type params = {profile_model, Lzi};\n\t\tgsl_odeiv_system sys = {f_axi, NULL, 4, &params};\n\t\tphasespace[0] = x;\n\t\tphasespace[1] = z;\n\t\tphasespace[2] = vx;\n\t\tphasespace[3] = vz;\n\t\t\n\t\tfor(int j = 0; j < N; j++) {\n\t\t\t\n\t\t\tint status = GSL_SUCCESS+1;\n\t\t\tdo {\n\t\t\t\tstatus = gsl_odeiv_evolve_apply (e, c, s, &sys, &t1, t2, &stepsize, phasespace);\n\t\t\t/*if (status != GSL_SUCCESS) {\n\t\t\t\tprintf (\"error integrating\\n\");\n\t\t\t\tbreak;*/\n\t\t\t} while(status != GSL_SUCCESS); \n\t\t\t\t//printf (\"%.5e %.5e %.5e %.5e\\n\", t, phasespace[0], phasespace[1], stepsize);\n\t\t\t//}\n\t\t\tt2 += dt(i);\n\t\t\tif (status != GSL_SUCCESS) {\n\t\t\t\tprintf (\"error integrating\\n\");\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t\txoutp[i*N+j] = phasespace[0];\n\t\t\tzoutp[i*N+j] = phasespace[1];\n\t\t\tvxoutp[i*N+j] = phasespace[2];\n\t\t\tvzoutp[i*N+j] = phasespace[3];\n\t\t}\n\t}\n}\n\n}\n\t\n\t\n", "meta": {"hexsha": "8ac859a476e95ee64e3ce9044e98e3ff9af625d1", "size": 14680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/orbit_integrator.cpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/orbit_integrator.cpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/orbit_integrator.cpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2884615385, "max_line_length": 222, "alphanum_fraction": 0.6819482289, "num_tokens": 5325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.02556521104637466, "lm_q1q2_score": 0.010413564338411563}}
{"text": "#include <SFML/Graphics.hpp>\n#include <vector>\n#include <random>\n#include <boost/asio.hpp>\n#include \"world.pb.h\"\n\nusing boost::asio::ip::tcp;\n\nconst sf::Vector2f cell_offset(0.5f, 0.5f);\nconst sf::Vector2f cell_size (4.f,4.f);\nconst size_t width = 100;\nconst size_t height = 100;\nconst float camera_speed = 300;\nconst float camera_zoom = 1.001f;\nconst float camera_default_zoom = 0.45f;\nconst float camera_max_zoom = 2.f;\nconst float camera_min_zoom = 0.1f;\nconst float fps = 1.f/8.f;\nconst float builder_speed = 1.f/8.f;\nconst sf::Color background_color(50, 50, 50);\nconst sf::Color cell_color(255, 255, 255);\nconst sf::Color grid_color(150, 150, 150);\nconst sf::Color builder_color(255, 0, 0, 100);\nconst sf::Color other_builder_color(0, 255, 0, 100);\nconst char* default_port = \"5000\";\nconst char* default_host = \"localhost\";\n\nusing namespace std;\n\nuniform_int_distribution<size_t> dist(0,1);\nrandom_device rd;\n\nsf::Vector2f Normalize(const sf::Vector2f &vec) {\n    float length = vec.x * vec.x + vec.y * vec.y;\n    if (length < 1e-5) return vec;\n    return vec / sqrt(length);\n}\n\nstd::string buff(1024,' ');\nstd::vector<sf::Vector2i> other_players;\n\nvoid do_read(tcp::socket &socket)\n{\n    socket.async_read_some(boost::asio::buffer(buff),\n        [&](boost::system::error_code ec, std::size_t length)\n        {\n            if (!ec)\n            {\n                other_players.clear();\n                World world;\n                world.ParseFromArray(buff.data(), length);\n                for (auto player : world.players()) {\n                    if (!player.is_player()) other_players.emplace_back(player.x(), player.y());\n                }\n                do_read(socket);\n            }\n            else {\n                exit(0);\n            }\n        });\n}\n\n\nint main()\n{\n    vector<vector<bool>> map(height,vector<bool>(width));\n    vector<vector<bool>> buff_map(height,vector<bool>(width));\n\n    boost::asio::io_context io_context;\n\n    tcp::socket s(io_context);\n    tcp::resolver resolver(io_context);\n    boost::asio::connect(s, resolver.resolve(default_host, default_port));\n\n    do_read(s);\n    \n    //, sf::Style::Fullscreen\n    sf::RenderWindow window(sf::VideoMode::getFullscreenModes()[0], \"Game Of Life\");\n    sf::View view(window.getView());\n    view.setCenter(sf::Vector2f(width * (cell_size.x + cell_offset.x) + cell_offset.x, height * (cell_size.y + cell_offset.y) + cell_offset.y) / 2.f);\n    window.setView(view);\n\n    sf::Clock clock;\n    sf::Clock fps_clock;\n    sf::Clock builder_clock;\n    \n    sf::Vector2i builder_position;\n\n    bool grid_visible = true;\n    bool game_paused = true;\n    bool key_g_is_released = true;\n    bool key_space_is_released = true;\n    bool key_p_is_released = true;\n    bool key_c_is_released = true;\n    bool key_r_is_released = true;\n\n\n    float camera_current_zoom = camera_default_zoom;\n    view.zoom(camera_default_zoom);\n\n    while (window.isOpen())\n    {\n        float dt = clock.restart().asSeconds();\n        \n        io_context.poll();\n\n        sf::Event event;\n        while (window.pollEvent(event))\n        {\n            if (event.type == sf::Event::Closed)\n                window.close();\n        }\n\n        sf::Vector2f direction;\n\n\n        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {\n            window.close();\n        }\n        if (sf::Joystick::isButtonPressed(0, sf::Joystick::Z) || sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {\n            direction += sf::Vector2f(-1.f, 0.f);\n        }\n        if (sf::Joystick::isButtonPressed(0, sf::Joystick::Y) || sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {\n            direction += sf::Vector2f(1.f, 0.f);\n        }\n        if (sf::Joystick::isButtonPressed(0, sf::Joystick::R) || sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {\n            direction += sf::Vector2f(0.f, -1.f);\n        }\n        if (sf::Joystick::isButtonPressed(0,sf::Joystick::X) || sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {\n            direction += sf::Vector2f(0.f, 1.f);\n        }\n\n        sf::Vector2i old_builder_position = builder_position;\n\n        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {\n            if (builder_position.x > 0 && builder_clock.getElapsedTime().asSeconds() > builder_speed) {\n                builder_position += sf::Vector2i(-1, 0); \n            }\n        }\n        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {\n            if (builder_position.x + 1 < width && builder_clock.getElapsedTime().asSeconds() > builder_speed) {\n                builder_position += sf::Vector2i(1, 0);\n            }\n        }\n        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {\n            if (builder_position.y > 0 && builder_clock.getElapsedTime().asSeconds() > builder_speed) {\n                builder_position += sf::Vector2i(0, -1);\n            }\n        }\n        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {\n            if (builder_position.y + 1 < height && builder_clock.getElapsedTime().asSeconds() > builder_speed) {\n                builder_position += sf::Vector2i(0, 1);\n            }\n        }\n\n        if (builder_clock.getElapsedTime().asSeconds() > builder_speed) {\n            builder_clock.restart();\n        }\n\n        if (old_builder_position != builder_position) {\n            Player player;\n            player.set_x(builder_position.x);\n            player.set_y(builder_position.y);\n            player.set_id(0);\n            player.set_is_player(true);\n            boost::asio::write(s, boost::asio::buffer(player.SerializeAsString()));\n        }\n\n        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q) || sf::Joystick::isButtonPressed(0, sf::Joystick::U)) {\n            if (camera_current_zoom > camera_min_zoom) {\n                view.zoom(1 / camera_zoom);\n                camera_current_zoom /= camera_zoom;\n            }\n        }\n        if (sf::Keyboard::isKeyPressed(sf::Keyboard::E) || sf::Joystick::isButtonPressed(0, sf::Joystick::V)) {\n            if (camera_current_zoom < camera_max_zoom) {\n                view.zoom(camera_zoom);\n                camera_current_zoom *= camera_zoom;\n            }\n        }\n        if (key_g_is_released) {\n            if (sf::Keyboard::isKeyPressed(sf::Keyboard::G)) {\n                grid_visible = !grid_visible;\n                key_g_is_released = false;\n            }\n        }\n        if (!sf::Keyboard::isKeyPressed(sf::Keyboard::G)) {\n            key_g_is_released = true;\n        }\n\n        if (key_p_is_released) {\n            if (sf::Keyboard::isKeyPressed(sf::Keyboard::P)) {\n                game_paused = !game_paused;\n                key_p_is_released = false;\n            }\n        }\n        if (!sf::Keyboard::isKeyPressed(sf::Keyboard::P)) {\n            key_p_is_released = true;\n        }\n\n        if (key_space_is_released) {\n            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {\n                map[builder_position.y][builder_position.x] = !map[builder_position.y][builder_position.x];\n                key_space_is_released = false;\n            }\n        }\n        if (!sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {\n            key_space_is_released = true;\n        }\n\n        if (key_c_is_released) {\n            if (sf::Keyboard::isKeyPressed(sf::Keyboard::C)) {\n                map = vector<vector<bool>>(height, vector<bool>(width));\n                key_c_is_released = false;\n            }\n        }\n        if (!sf::Keyboard::isKeyPressed(sf::Keyboard::C)) {\n            key_c_is_released = true;\n        }\n\n        if (key_r_is_released) {\n            if (sf::Keyboard::isKeyPressed(sf::Keyboard::R)) {\n                map = vector<vector<bool>>(height, vector<bool>(width));\n                for (size_t i = 0; i < map.size(); i++) {\n                    for (size_t j = 0; j < map[i].size(); j++) {\n                        map[i][j] = dist(rd);\n                    }\n                }\n                key_r_is_released = false;\n            }\n        }\n        if (!sf::Keyboard::isKeyPressed(sf::Keyboard::R)) {\n            key_r_is_released = true;\n        }\n\n        direction = Normalize(direction);\n        \n\n        view.setCenter(view.getCenter() + direction * dt * camera_speed * camera_current_zoom);\n        window.setView(view);\n\n        window.clear(background_color);\n\n        sf::RectangleShape builder_rect(cell_size);\n        builder_rect.setFillColor(builder_color);\n        sf::RectangleShape other_builder_rect(cell_size);\n        other_builder_rect.setFillColor(other_builder_color);\n        sf::RectangleShape cell_rect(cell_size);\n        cell_rect.setFillColor(cell_color);\n        sf::RectangleShape v_rect(sf::Vector2f(cell_offset.x, height * (cell_size.y + cell_offset.y) + cell_offset.y));\n        v_rect.setFillColor(grid_color);\n        sf::RectangleShape h_rect(sf::Vector2f(width * (cell_size.x + cell_offset.x) + cell_offset.x, cell_offset.y));\n        h_rect.setFillColor(grid_color);\n\n        if (grid_visible) {\n            for (size_t i = 0; i < width + 1; i++) {\n                v_rect.setPosition(i * (cell_size.x + cell_offset.x), 0.f);\n                window.draw(v_rect);\n            }\n\n            for (size_t i = 0; i < height + 1; i++) {\n                h_rect.setPosition(0.f, i * (cell_size.y + cell_offset.y));\n                window.draw(h_rect);\n            }\n        }\n        \n\n        for (size_t i = 0; i < map.size(); i++) {\n            for (size_t j = 0; j < map[i].size(); j++) {\n                if (map[i][j]){\n                    cell_rect.setPosition(j * (cell_size.x + cell_offset.x) + cell_offset.x, i * (cell_size.y + cell_offset.y) + cell_offset.y);\n                    window.draw(cell_rect);\n                }\n            }\n        }\n\n\n        \n        for (auto builder_position : other_players) {\n            other_builder_rect.setPosition(builder_position.x* (cell_size.x + cell_offset.x) + cell_offset.x,\n                builder_position.y* (cell_size.y + cell_offset.y) + cell_offset.y);\n            window.draw(other_builder_rect);\n        }\n        builder_rect.setPosition(builder_position.x* (cell_size.x + cell_offset.x) + cell_offset.x,\n            builder_position.y* (cell_size.y + cell_offset.y) + cell_offset.y);\n        window.draw(builder_rect);\n\n        if (fps_clock.getElapsedTime().asSeconds() < fps) {\n            window.display();\n            continue;\n        }\n        fps_clock.restart();\n\n        if (!game_paused) {\n            for (size_t i = 0; i < map.size(); i++) {\n                for (size_t j = 0; j < map[i].size(); j++) {\n                    size_t count = map[(i + 1) % height][(j - 1 + width) % width]\n                        + map[(i + 1) % height][j] \n                        + map[(i + 1) % height][(j + 1) % width] \n                        + map[i][(j - 1 + width) % width] +\n                        map[i][(j + 1) % width] +\n                        map[(i - 1 + height) % height][(j - 1 + width) % width] +\n                        map[(i - 1 + height) % height][j] +\n                        map[(i - 1 + height) % height][(j + 1) % width];\n                    buff_map[i][j] = map[i][j];\n                    if (map[i][j]) {\n                        if (count < 2 || count > 3) {\n                            buff_map[i][j] = false;\n                        }\n                    }\n                    else {\n                        if (count == 3) {\n                            buff_map[i][j] = true;\n                        }\n                    }\n                }\n            }\n            map.swap(buff_map);\n        }\n        \n\n        \n\n        window.display();\n    }\n\n    return 0;\n}", "meta": {"hexsha": "bdd0bbdaf467a16922c12921ea8485ec6dfd8fb4", "size": 11568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "client.cpp", "max_stars_repo_name": "KHIPSTERcat/game-of-life", "max_stars_repo_head_hexsha": "9ecf1a1088181cfdc10031659dcbb94cc97ea0c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-23T23:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T02:03:08.000Z", "max_issues_repo_path": "client.cpp", "max_issues_repo_name": "KHIPSTERcat/game-of-life", "max_issues_repo_head_hexsha": "9ecf1a1088181cfdc10031659dcbb94cc97ea0c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client.cpp", "max_forks_repo_name": "KHIPSTERcat/game-of-life", "max_forks_repo_head_hexsha": "9ecf1a1088181cfdc10031659dcbb94cc97ea0c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-16T15:42:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-16T15:42:25.000Z", "avg_line_length": 35.2682926829, "max_line_length": 150, "alphanum_fraction": 0.5375172891, "num_tokens": 2784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.02675928502879603, "lm_q1q2_score": 0.010399140543950077}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke and Gerton Lunter\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#if __GNUC__ >= 6\n    #pragma GCC diagnostic ignored \"-Wignored-attributes\"\n#endif\n\n#include \"simd_pair_hmm.hpp\"\n\n#include <vector>\n#include <algorithm>\n#include <emmintrin.h>\n#include <cassert>\n\n#include <boost/container/small_vector.hpp>\n\n//#include <iostream> // DEBUG\n//#include <iterator> // DEBUG\n//\n//struct Seq { __m128i val; };\n//struct Qual { __m128i val; };\n//struct Mask { __m128i val; };\n//\n//std::ostream& operator<<(std::ostream& os, const Seq s)\n//{\n//    const auto val = (std::uint16_t*) &s.val;\n//    std::copy(val, val + 8, std::ostreambuf_iterator<char>(os));\n//    return os;\n//}\n//\n//std::ostream& operator<<(std::ostream& os, const Qual q)\n//{\n//    const auto val = (std::uint16_t*) &q.val;\n//    std::transform(val, val + 8, std::ostream_iterator<unsigned>(os, \" \"),\n//                   [] (const auto x) { return x >> 2; });\n//    return os;\n//}\n//\n//std::ostream& operator<<(std::ostream& os, const Mask m)\n//{\n//    const auto val = (std::uint16_t*) &m.val;\n//    std::copy(val, val + 8, std::ostream_iterator<bool>(os));\n//    return os;\n//}\n\nnamespace octopus { namespace hmm { namespace simd {\n\nconstexpr std::size_t staticBackpointerCapacity {10000};\n\ntemplate <typename T>\nusing SmallVector = boost::container::small_vector<T, staticBackpointerCapacity>;\n\nconstexpr short nScore {2 << 2};\nconstexpr int bandSize {8};\nconstexpr short inf {0x7800};\nconstexpr char gap {'-'};\n\nauto extract_epi16(const __m128i a, const int imm) noexcept\n{\n    switch (imm) {\n        case 0:  return _mm_extract_epi16(a, 0);\n        case 1:  return _mm_extract_epi16(a, 1);\n        case 2:  return _mm_extract_epi16(a, 2);\n        case 3:  return _mm_extract_epi16(a, 3);\n        case 4:  return _mm_extract_epi16(a, 4);\n        case 5:  return _mm_extract_epi16(a, 5);\n        case 6:  return _mm_extract_epi16(a, 6);\n        default: return _mm_extract_epi16(a, 7);\n    }\n}\n\nint align(const char* truth, const char* target, const std::int8_t* qualities,\n          int truth_len, int target_len,\n          short gap_open, short gap_extend, short nuc_prior) noexcept\n{\n    // target is the read; the shorter of the sequences\n    // no checks for overflow are done\n    //\n    // the bottom-left and top-right corners of the DP table are just\n    // included at the extreme ends of the diagonal, which measures\n    // n=8 entries diagonally across.  This fixes the length of the\n    // longer (horizontal) sequence to 15 (2*8-1) more than the shorter\n    //\n    // the << 2's are because the lower two bits are reserved for back tracing\n    \n    assert(truth_len > bandSize && (truth_len == target_len + 2 * bandSize - 1));\n    \n    gap_open <<= 2;\n    gap_extend <<= 2;\n    nuc_prior <<= 2;\n    \n    using SimdInt = __m128i;\n    \n    SimdInt _m1 {_mm_set1_epi16(inf)};\n    auto _i1 = _m1;\n    auto _d1 = _m1;\n    auto _m2 = _m1;\n    auto _i2 = _m1;\n    auto _d2 = _m1;\n    \n    const SimdInt _gap_open {_mm_set1_epi16(gap_open)};\n    const SimdInt _gap_extend {_mm_set1_epi16(gap_extend)};\n    const SimdInt _nuc_prior  {_mm_set1_epi16(nuc_prior)};\n    \n    SimdInt _initmask   {_mm_set_epi16(0,0,0,0,0,0,0,-1)};\n    SimdInt _initmask2  {_mm_set_epi16(0,0,0,0,0,0,0,-0x8000)};\n    \n    // truth is initialized with the n-long prefix, in forward direction\n    // target is initialized as empty; reverse direction\n    SimdInt _truthwin  {_mm_set_epi16(truth[7], truth[6], truth[5], truth[4],\n                                      truth[3], truth[2], truth[1], truth[0])};\n    SimdInt _targetwin  {_m1};\n    SimdInt _qualitieswin {_mm_set1_epi16(64 << 2)};\n    \n    // if N, make nScore; if != N, make inf\n    SimdInt _truthnqual {_mm_add_epi16(_mm_and_si128(_mm_cmpeq_epi16(_truthwin, _mm_set1_epi16('N')),\n                                                     _mm_set1_epi16(nScore - inf)),\n                                       _mm_set1_epi16(inf))};\n    \n    short minscore {inf};\n    \n    for (int s {0}; s <= 2 * (target_len + bandSize); s += 2) {\n        // truth is current; target needs updating\n        _targetwin    = _mm_slli_si128(_targetwin, 2);\n        _qualitieswin = _mm_slli_si128(_qualitieswin, 2);\n        \n        if (s / 2 < target_len) {\n            _targetwin    = _mm_insert_epi16(_targetwin, target[s / 2], 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, qualities[s / 2] << 2, 0);\n        } else {\n            _targetwin    = _mm_insert_epi16(_targetwin, '0', 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, 64 << 2, 0);\n        }\n        \n        // S even\n        \n        _m1 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m1));\n        _m2 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m2));\n        _m1 = _mm_min_epi16(_m1, _mm_min_epi16(_i1, _d1));\n        \n        short score = extract_epi16(_m1, std::max(0, s / 2 - target_len));\n        if (s / 2 >= target_len) {\n            minscore = std::min(score, minscore);\n        }\n        \n        _m1 = _mm_add_epi16(_m1, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _qualitieswin), _truthnqual));\n        _d1 = _mm_min_epi16(_mm_add_epi16(_d2, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m2, _i2),\n                                          _mm_srli_si128(_gap_open, 2))); // allow I->D\n        _d1 = _mm_insert_epi16(_mm_slli_si128(_d1, 2), inf, 0);\n        _i1 = _mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_i2, _gap_extend),\n                                          _mm_add_epi16(_m2, _gap_open)),\n                            _nuc_prior);\n        \n        // S odd\n        // truth needs updating; target is current\n        const auto pos = bandSize + s / 2;\n        const char base {(pos < truth_len) ? truth[pos] : 'N'};\n        \n        _truthwin   = _mm_insert_epi16(_mm_srli_si128(_truthwin, 2), base,\n                                       bandSize - 1);\n        _truthnqual = _mm_insert_epi16(_mm_srli_si128(_truthnqual, 2), base == 'N' ? nScore : inf,\n                                       bandSize - 1);\n        \n        _initmask  = _mm_slli_si128(_initmask, 2);\n        _initmask2 = _mm_slli_si128(_initmask2, 2);\n        _m2 = _mm_min_epi16(_m2, _mm_min_epi16(_i2, _d2));\n        \n        if (s / 2 >= target_len) {\n            minscore = std::min(static_cast<short>(extract_epi16(_m2, s / 2 - target_len)), minscore);\n        }\n        \n        _m2 = _mm_add_epi16(_m2, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _qualitieswin), _truthnqual));\n        _d2 = _mm_min_epi16(_mm_add_epi16(_d1, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m1, _i1), _gap_open)); // allow I->D\n        _i2 = _mm_insert_epi16(_mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_mm_srli_si128(_i1, 2),\n                                                                         _gap_extend),\n                                                           _mm_add_epi16(_mm_srli_si128(_m1, 2),\n                                                                         _gap_open)),\n                                             _nuc_prior), inf, bandSize - 1);\n        \n    }\n    \n    return (minscore + 0x8000) >> 2;\n}\n\nint align(const char* truth, const char* target, const std::int8_t* qualities,\n          const int truth_len, const int target_len,\n          const std::int8_t* gap_open, short gap_extend, short nuc_prior) noexcept\n{\n    // target is the read; the shorter of the sequences\n    // no checks for overflow are done\n    //\n    // the bottom-left and top-right corners of the DP table are just\n    // included at the extreme ends of the diagonal, which measures\n    // n=8 entries diagonally across.  This fixes the length of the\n    // longer (horizontal) sequence to 15 (2*8-1) more than the shorter\n    //\n    // the << 2's are because the lower two bits are reserved for back tracing\n    \n    assert(truth_len > bandSize && (truth_len == target_len + 2 * bandSize - 1));\n    \n    gap_extend <<= 2;\n    nuc_prior <<= 2;\n    \n    using SimdInt = __m128i;\n    \n    SimdInt _m1 {_mm_set1_epi16(inf)};\n    auto _i1 = _m1;\n    auto _d1 = _m1;\n    auto _m2 = _m1;\n    auto _i2 = _m1;\n    auto _d2 = _m1;\n    \n    SimdInt _gap_extend {_mm_set1_epi16(gap_extend)};\n    SimdInt _nuc_prior  {_mm_set1_epi16(nuc_prior)};\n    \n    SimdInt _initmask   {_mm_set_epi16(0,0,0,0,0,0,0,-1)};\n    SimdInt _initmask2  {_mm_set_epi16(0,0,0,0,0,0,0,-0x8000)};\n    \n    // truth is initialized with the n-long prefix, in forward direction\n    // target is initialized as empty; reverse direction\n    SimdInt _truthwin  {_mm_set_epi16(truth[7], truth[6], truth[5], truth[4],\n                                      truth[3], truth[2], truth[1], truth[0])};\n    SimdInt _targetwin  {_m1};\n    SimdInt _qualitieswin {_mm_set1_epi16(64 << 2)};\n    \n    // if N, make nScore; if != N, make inf\n    SimdInt _truthnqual {_mm_add_epi16(_mm_and_si128(_mm_cmpeq_epi16(_truthwin, _mm_set1_epi16('N')),\n                                                     _mm_set1_epi16(nScore - inf)),\n                                       _mm_set1_epi16(inf))};\n    \n    SimdInt _gap_open {_mm_set_epi16(gap_open[7] << 2,gap_open[6] << 2,gap_open[5] << 2,gap_open[4] << 2,\n                                     gap_open[3] << 2,gap_open[2] << 2,gap_open[1] << 2,gap_open[0] << 2)};\n    \n    short minscore {inf};\n    \n    for (int s {0}; s <= 2 * (target_len + bandSize); s += 2) {\n        // truth is current; target needs updating\n        _targetwin    = _mm_slli_si128(_targetwin, 2);\n        _qualitieswin = _mm_slli_si128(_qualitieswin, 2);\n        \n        if (s / 2 < target_len) {\n            _targetwin    = _mm_insert_epi16(_targetwin, target[s / 2], 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, qualities[s / 2] << 2, 0);\n        } else {\n            _targetwin    = _mm_insert_epi16(_targetwin, '0', 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, 64 << 2, 0);\n        }\n        \n        // S even\n        \n        _m1 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m1));\n        _m2 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m2));\n        _m1 = _mm_min_epi16(_m1, _mm_min_epi16(_i1, _d1));\n        \n        if (s / 2 >= target_len) {\n            minscore = std::min(static_cast<short>(extract_epi16(_m1, s / 2 - target_len)), minscore);\n        }\n        \n        _m1 = _mm_add_epi16(_m1, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _qualitieswin), _truthnqual));\n        _d1 = _mm_min_epi16(_mm_add_epi16(_d2, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m2, _i2),\n                                          _mm_srli_si128(_gap_open, 2))); // allow I->D\n        _d1 = _mm_insert_epi16(_mm_slli_si128(_d1, 2), inf, 0);\n        _i1 = _mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_i2, _gap_extend),\n                                          _mm_add_epi16(_m2, _gap_open)),\n                            _nuc_prior);\n        \n        // S odd\n        // truth needs updating; target is current\n        const auto pos = bandSize + s / 2;\n        const char base {(pos < truth_len) ? truth[pos] : 'N'};\n        \n        _truthwin   = _mm_insert_epi16(_mm_srli_si128(_truthwin, 2), base,\n                                       bandSize - 1);\n        _truthnqual = _mm_insert_epi16(_mm_srli_si128(_truthnqual, 2), base == 'N' ? nScore : inf,\n                                       bandSize - 1);\n        _gap_open   = _mm_insert_epi16(_mm_srli_si128(_gap_open, 2),\n                                       gap_open[pos < truth_len ? pos : truth_len - 1] << 2,\n                                       bandSize - 1);\n        \n        _initmask  = _mm_slli_si128(_initmask, 2);\n        _initmask2 = _mm_slli_si128(_initmask2, 2);\n        \n        _m2 = _mm_min_epi16(_m2, _mm_min_epi16(_i2, _d2));\n        \n        if (s / 2 >= target_len) {\n            minscore = std::min(static_cast<short>(extract_epi16(_m2, s / 2 - target_len)), minscore);\n        }\n        \n        _m2 = _mm_add_epi16(_m2, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                 _qualitieswin), _truthnqual));\n        _d2 = _mm_min_epi16(_mm_add_epi16(_d1, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m1, _i1), _gap_open)); // allow I->D\n        _i2 = _mm_insert_epi16(_mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_mm_srli_si128(_i1, 2),\n                                                                         _gap_extend),\n                                                           _mm_add_epi16(_mm_srli_si128(_m1, 2),\n                                                                         _gap_open)),\n                                             _nuc_prior), inf, bandSize - 1);\n        \n    }\n    \n    return (minscore + 0x8000) >> 2;\n}\n\nint align(const char* truth, const char* target, const std::int8_t* qualities,\n          const int truth_len, const int target_len,\n          const std::int8_t* gap_open, const std::int8_t* gap_extend,\n          short nuc_prior) noexcept\n{\n    assert(truth_len > bandSize && (truth_len == target_len + 2 * bandSize - 1));\n    \n    nuc_prior <<= 2;\n    \n    using SimdInt = __m128i;\n    \n    SimdInt _m1 {_mm_set1_epi16(inf)};\n    auto _i1 = _m1;\n    auto _d1 = _m1;\n    auto _m2 = _m1;\n    auto _i2 = _m1;\n    auto _d2 = _m1;\n    \n    SimdInt _nuc_prior  {_mm_set1_epi16(nuc_prior)};\n    \n    SimdInt _initmask   {_mm_set_epi16(0,0,0,0,0,0,0,-1)};\n    SimdInt _initmask2  {_mm_set_epi16(0,0,0,0,0,0,0,-0x8000)};\n    \n    // truth is initialized with the n-long prefix, in forward direction\n    // target is initialized as empty; reverse direction\n    SimdInt _truthwin  {_mm_set_epi16(truth[7], truth[6], truth[5], truth[4],\n                                      truth[3], truth[2], truth[1], truth[0])};\n    SimdInt _targetwin  {_m1};\n    SimdInt _qualitieswin {_mm_set1_epi16(64 << 2)};\n    \n    // if N, make nScore; if != N, make inf\n    SimdInt _truthnqual {_mm_add_epi16(_mm_and_si128(_mm_cmpeq_epi16(_truthwin, _mm_set1_epi16('N')),\n                                                     _mm_set1_epi16(nScore - inf)),\n                                       _mm_set1_epi16(inf))};\n    \n    SimdInt _gap_open {_mm_set_epi16(gap_open[7] << 2,gap_open[6] << 2,gap_open[5] << 2,gap_open[4] << 2,\n                                     gap_open[3] << 2,gap_open[2] << 2,gap_open[1] << 2,gap_open[0] << 2)};\n    SimdInt _gap_extend {_mm_set_epi16(gap_extend[7] << 2,gap_extend[6] << 2,gap_extend[5] << 2,gap_extend[4] << 2,\n                                       gap_extend[3] << 2,gap_extend[2] << 2,gap_extend[1] << 2,gap_extend[0] << 2)};\n    \n    short minscore {inf};\n    \n    for (int s {0}; s <= 2 * (target_len + bandSize); s += 2) {\n        // truth is current; target needs updating\n        _targetwin    = _mm_slli_si128(_targetwin, 2);\n        _qualitieswin = _mm_slli_si128(_qualitieswin, 2);\n        \n        if (s / 2 < target_len) {\n            _targetwin    = _mm_insert_epi16(_targetwin, target[s / 2], 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, qualities[s / 2] << 2, 0);\n        } else {\n            _targetwin    = _mm_insert_epi16(_targetwin, '0', 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, 64 << 2, 0);\n        }\n        \n        // S even\n        _m1 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m1));\n        _m2 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m2));\n        _m1 = _mm_min_epi16(_m1, _mm_min_epi16(_i1, _d1));\n        \n        if (s / 2 >= target_len) {\n            minscore = std::min(static_cast<short>(extract_epi16(_m1, s / 2 - target_len)), minscore);\n        }\n        \n        _m1 = _mm_add_epi16(_m1, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _qualitieswin), _truthnqual));\n        _d1 = _mm_min_epi16(_mm_add_epi16(_d2, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m2, _i2),\n                                          _mm_srli_si128(_gap_open, 2))); // allow I->D\n        _d1 = _mm_insert_epi16(_mm_slli_si128(_d1, 2), inf, 0);\n        _i1 = _mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_i2, _gap_extend),\n                                          _mm_add_epi16(_m2, _gap_open)),\n                            _nuc_prior);\n        \n        // S odd; truth needs updating; target is current\n        const auto pos = bandSize + s / 2;\n        const char base {(pos < truth_len) ? truth[pos] : 'N'};\n        _truthwin   = _mm_insert_epi16(_mm_srli_si128(_truthwin, 2), base, bandSize - 1);\n        _truthnqual = _mm_insert_epi16(_mm_srli_si128(_truthnqual, 2), base == 'N' ? nScore : inf, bandSize - 1);\n        const auto gap_idx = pos < truth_len ? pos : truth_len - 1;\n        _gap_open   = _mm_insert_epi16(_mm_srli_si128(_gap_open, 2), gap_open[gap_idx] << 2, bandSize - 1);\n        _gap_extend = _mm_insert_epi16(_mm_srli_si128(_gap_extend, 2), gap_extend[gap_idx] << 2, bandSize - 1);\n        \n        _initmask  = _mm_slli_si128(_initmask, 2);\n        _initmask2 = _mm_slli_si128(_initmask2, 2);\n        \n        _m2 = _mm_min_epi16(_m2, _mm_min_epi16(_i2, _d2));\n        \n        if (s / 2 >= target_len) {\n            minscore = std::min(static_cast<short>(extract_epi16(_m2, s / 2 - target_len)), minscore);\n        }\n        \n        _m2 = _mm_add_epi16(_m2, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _qualitieswin), _truthnqual));\n        _d2 = _mm_min_epi16(_mm_add_epi16(_d1, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m1, _i1), _gap_open)); // allow I->D\n        _i2 = _mm_insert_epi16(_mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_mm_srli_si128(_i1, 2),\n                                                                         _gap_extend),\n                                                           _mm_add_epi16(_mm_srli_si128(_m1, 2),\n                                                                         _gap_open)),\n                                             _nuc_prior), inf, bandSize - 1);\n        \n    }\n    \n    return (minscore + 0x8000) >> 2;\n}\n\nint align(const char* truth, const char* target, const std::int8_t* qualities,\n          const int truth_len, const int target_len,\n          const char* snv_mask, const std::int8_t* snv_prior,\n          const std::int8_t* gap_open, short gap_extend, short nuc_prior) noexcept\n{\n    assert(truth_len > bandSize && (truth_len == target_len + 2 * bandSize - 1));\n    \n    gap_extend <<= 2;\n    nuc_prior <<= 2;\n    \n    using SimdInt = __m128i;\n    \n    SimdInt _m1 {_mm_set1_epi16(inf)};\n    auto _i1 = _m1;\n    auto _d1 = _m1;\n    auto _m2 = _m1;\n    auto _i2 = _m1;\n    auto _d2 = _m1;\n    \n    SimdInt _gap_extend {_mm_set1_epi16(gap_extend)};\n    SimdInt _nuc_prior  {_mm_set1_epi16(nuc_prior)};\n    SimdInt _initmask   {_mm_set_epi16(0,0,0,0,0,0,0,-1)};\n    SimdInt _initmask2  {_mm_set_epi16(0,0,0,0,0,0,0,-0x8000)};\n    \n    SimdInt _truthwin  {_mm_set_epi16(truth[7], truth[6], truth[5], truth[4],\n                                      truth[3], truth[2], truth[1], truth[0])};\n    SimdInt _targetwin  {_m1};\n    SimdInt _qualitieswin {_mm_set1_epi16(64 << 2)};\n    \n    SimdInt _snvmaskwin  {_mm_set_epi16(snv_mask[7], snv_mask[6], snv_mask[5], snv_mask[4],\n                                        snv_mask[3], snv_mask[2], snv_mask[1], snv_mask[0])};\n    SimdInt _snv_priorwin {_mm_set_epi16(snv_prior[7] << 2, snv_prior[6] << 2, snv_prior[5] << 2, snv_prior[4] << 2,\n                                         snv_prior[3] << 2, snv_prior[2] << 2, snv_prior[1] << 2, snv_prior[0] << 2)};\n    \n    SimdInt _snvmask;\n    \n    // if N, make nScore; if != N, make inf\n    SimdInt _truthnqual {_mm_add_epi16(_mm_and_si128(_mm_cmpeq_epi16(_truthwin, _mm_set1_epi16('N')),\n                                                     _mm_set1_epi16(nScore - inf)),\n                                       _mm_set1_epi16(inf))};\n    \n    SimdInt _gap_open {_mm_set_epi16(gap_open[7] << 2,gap_open[6] << 2,gap_open[5] << 2,gap_open[4] << 2,\n                                     gap_open[3] << 2,gap_open[2] << 2,gap_open[1] << 2,gap_open[0] << 2)};\n    \n    short minscore {inf};\n    \n    for (int s {0}; s <= 2 * (target_len + bandSize); s += 2) {\n        // truth is current; target needs updating\n        _targetwin    = _mm_slli_si128(_targetwin, 2);\n        _qualitieswin = _mm_slli_si128(_qualitieswin, 2);\n        \n        if (s / 2 < target_len) {\n            _targetwin    = _mm_insert_epi16(_targetwin, target[s / 2], 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, qualities[s / 2] << 2, 0);\n        } else {\n            _targetwin    = _mm_insert_epi16(_targetwin, '0', 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, 64 << 2, 0);\n        }\n        \n        // S even\n        \n        _m1 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m1));\n        _m2 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m2));\n        _m1 = _mm_min_epi16(_m1, _mm_min_epi16(_i1, _d1));\n        \n        if (s / 2 >= target_len) {\n            minscore = std::min(static_cast<short>(extract_epi16(_m1, s / 2 - target_len)), minscore);\n        }\n        \n        _snvmask = _mm_cmpeq_epi16(_targetwin, _snvmaskwin);\n        \n        _m1 = _mm_add_epi16(_m1, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                 _mm_min_epi16(_qualitieswin,\n                                                                               _mm_or_si128(_mm_and_si128(_snvmask, _snv_priorwin),\n                                                                                            _mm_andnot_si128(_snvmask, _qualitieswin)))),\n                                               _truthnqual));\n        _d1 = _mm_min_epi16(_mm_add_epi16(_d2, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m2, _i2),\n                                          _mm_srli_si128(_gap_open, 2))); // allow I->D\n        _d1 = _mm_insert_epi16(_mm_slli_si128(_d1, 2), inf, 0);\n        _i1 = _mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_i2, _gap_extend),\n                                          _mm_add_epi16(_m2, _gap_open)),\n                            _nuc_prior);\n        \n        // S odd\n        // truth needs updating; target is current\n        const auto pos = bandSize + s / 2;\n        const char base {pos < truth_len ? truth[pos] : 'N'};\n        \n        _truthwin     = _mm_insert_epi16(_mm_srli_si128(_truthwin, 2),\n                                         base,\n                                         bandSize - 1);\n        _truthnqual   = _mm_insert_epi16(_mm_srli_si128(_truthnqual, 2),\n                                         base == 'N' ? nScore : inf,\n                                         bandSize - 1);\n        _snvmaskwin   = _mm_insert_epi16(_mm_srli_si128(_snvmaskwin, 2),\n                                         pos < truth_len ? snv_mask[pos] : 'N',\n                                         bandSize - 1);\n        _snv_priorwin = _mm_insert_epi16(_mm_srli_si128(_snv_priorwin, 2),\n                                         (pos < truth_len ? snv_prior[pos] : inf) << 2,\n                                         bandSize - 1);\n        _gap_open     = _mm_insert_epi16(_mm_srli_si128(_gap_open, 2),\n                                         gap_open[pos < truth_len ? pos : truth_len - 1] << 2,\n                                         bandSize - 1);\n        \n        _initmask  = _mm_slli_si128(_initmask, 2);\n        _initmask2 = _mm_slli_si128(_initmask2, 2);\n        \n        _m2 = _mm_min_epi16(_m2, _mm_min_epi16(_i2, _d2));\n        \n        if (s / 2 >= target_len) {\n            minscore = std::min(static_cast<short>(extract_epi16(_m2, s / 2 - target_len)), minscore);\n        }\n        \n        _snvmask = _mm_cmpeq_epi16(_targetwin, _snvmaskwin);\n        \n        _m2 = _mm_add_epi16(_m2, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _mm_min_epi16(_qualitieswin,\n                                                                              _mm_or_si128(_mm_and_si128(_snvmask, _snv_priorwin),\n                                                                                           _mm_andnot_si128(_snvmask, _qualitieswin)))),\n                                               _truthnqual));\n        _d2 = _mm_min_epi16(_mm_add_epi16(_d1, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m1, _i1), _gap_open)); // allow I->D\n        _i2 = _mm_insert_epi16(_mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_mm_srli_si128(_i1, 2),\n                                                                         _gap_extend),\n                                                           _mm_add_epi16(_mm_srli_si128(_m1, 2),\n                                                                         _gap_open)),\n                                             _nuc_prior), inf, bandSize - 1);\n    }\n    \n    return (minscore + 0x8000) >> 2;\n}\n\nint align(const char* truth, const char* target, const std::int8_t* qualities,\n          const int truth_len, const int target_len,\n          const std::int8_t* gap_open, short gap_extend, short nuc_prior,\n          int& first_pos, char* aln1, char* aln2) noexcept\n{\n    // target is the read; the shorter of the sequences\n    // no checks for overflow are done\n    \n    // the bottom-left and top-right corners of the DP table are just\n    // included at the extreme ends of the diagonal, which measures\n    // n=8 entries diagonally across.  This fixes the length of the\n    // longer (horizontal) sequence to 15 (2*8-1) more than the shorter\n    \n    assert(truth_len > bandSize && (truth_len == target_len + 2 * bandSize - 1));\n    assert(aln1 != nullptr && aln2 != nullptr);\n    \n    gap_extend <<= 2;\n    nuc_prior <<= 2;\n    \n    constexpr int matchLabel  {0};\n    constexpr int insertLabel {1};\n    constexpr int deleteLabel {3};\n    \n    using SimdInt = __m128i;\n    \n    SimdInt _m1 {_mm_set1_epi16(inf)};\n    auto _i1 = _m1;\n    auto _d1 = _m1;\n    auto _m2 = _m1;\n    auto _i2 = _m1;\n    auto _d2 = _m1;\n    \n    SimdInt _gap_extend {_mm_set1_epi16(gap_extend)};\n    SimdInt _nuc_prior  {_mm_set1_epi16(nuc_prior)};\n    SimdInt _initmask   {_mm_set_epi16(0,0,0,0,0,0,0,-1)};\n    SimdInt _initmask2  {_mm_set_epi16(0,0,0,0,0,0,0,-0x8000)};\n    \n    static const SimdInt _three {_mm_set1_epi16(3)};\n    SmallVector<SimdInt> _backpointers(2 * (truth_len + bandSize));\n    \n    // sequence 1 is initialized with the n-long prefix, in forward direction\n    // sequence 2 is initialized as empty; reverse direction\n    SimdInt _truthwin  {_mm_set_epi16(truth[7], truth[6], truth[5], truth[4],\n                                      truth[3], truth[2], truth[1], truth[0])};\n    SimdInt _targetwin  {_m1};\n    SimdInt _qualitieswin {_mm_set1_epi16(64 << 2)};\n    \n    // if N, make nScore; if != N, make inf\n    SimdInt _truthnqual {_mm_add_epi16(_mm_and_si128(_mm_cmpeq_epi16(_truthwin, _mm_set1_epi16('N')),\n                                                     _mm_set1_epi16(nScore - inf)),\n                                       _mm_set1_epi16(inf))};\n    \n    SimdInt _gap_open {_mm_set_epi16(gap_open[7] << 2,gap_open[6] << 2,gap_open[5] << 2,gap_open[4] << 2,\n                                     gap_open[3] << 2,gap_open[2] << 2,gap_open[1] << 2,gap_open[0] << 2)};\n    \n    short cur_score {0}, minscore {inf}, minscoreidx {-1};\n    \n    // main loop.  Do one extra iteration, with nucs from sequence 2 just moved out\n    // of the targetwin/qual arrays, to simplify getting back pointers\n    int s;\n    for (s = 0; s <= 2 * (target_len + bandSize); s += 2) {\n        // truth is current; target needs updating\n        _targetwin    = _mm_slli_si128(_targetwin, 2);\n        _qualitieswin = _mm_slli_si128(_qualitieswin, 2);\n        \n        if (s / 2 < target_len) {\n            _targetwin    = _mm_insert_epi16(_targetwin, target[s / 2], 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, qualities[s / 2] << 2, 0);\n        } else {\n            _targetwin    = _mm_insert_epi16(_targetwin, '0', 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, 64 << 2, 0);\n        }\n        \n        // S even\n        _m1 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m1));\n        _m2 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m2));\n        _m1 = _mm_min_epi16(_m1, _mm_min_epi16(_i1, _d1));\n        \n        if (s / 2 >= target_len) {\n            cur_score = extract_epi16(_m1, s / 2 - target_len);\n            if (cur_score < minscore) {\n                minscore = cur_score;\n                minscoreidx = s;     // point back to the match state at this entry, so as not to\n            }                        // have to store the state at s-2\n        }\n        \n        _m1 = _mm_add_epi16(_m1, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _qualitieswin), _truthnqual));\n        _d1 = _mm_min_epi16(_mm_add_epi16(_d2, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m2, _i2),\n                                          _mm_srli_si128(_gap_open, 2))); // allow I->D\n        _d1 = _mm_insert_epi16(_mm_slli_si128(_d1, 2), inf, 0);\n        _i1 = _mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_i2, _gap_extend),\n                                          _mm_add_epi16(_m2, _gap_open)), _nuc_prior);\n        \n        _backpointers[s] = _mm_or_si128(_mm_or_si128(_mm_and_si128(_three, _m1),\n                                                     _mm_slli_epi16(_mm_and_si128(_three, _i1), 2 * insertLabel)),\n                                        _mm_slli_epi16(_mm_and_si128(_three, _d1), 2 * deleteLabel));\n        \n        // set state labels\n        _m1 = _mm_andnot_si128(_three, _m1);\n        _i1 = _mm_or_si128(_mm_andnot_si128(_three, _i1), _mm_srli_epi16(_three, 1));\n        _d1 = _mm_or_si128(_mm_andnot_si128(_three, _d1), _three);\n        \n        // S odd\n        \n        // truth needs updating; target is current\n        const char c {(bandSize + s / 2 < truth_len) ? truth[bandSize + (s / 2)] : 'N'};\n        \n        _truthwin   = _mm_insert_epi16(_mm_srli_si128(_truthwin,   2), c, bandSize - 1);\n        _truthnqual = _mm_insert_epi16(_mm_srli_si128(_truthnqual, 2), (c == 'N') ? nScore : inf, bandSize - 1);\n        _gap_open   = _mm_insert_epi16(_mm_srli_si128(_gap_open,  2),\n                                       gap_open[bandSize + s / 2 < truth_len ? bandSize + s / 2 : truth_len - 1] << 2, bandSize - 1);\n        _initmask  = _mm_slli_si128(_initmask, 2);\n        _initmask2 = _mm_slli_si128(_initmask2, 2);\n        _m2 = _mm_min_epi16(_m2, _mm_min_epi16(_i2, _d2));\n        \n        // at this point, extract minimum score.  Referred-to position must\n        // be y==target_len-1, so that current position has y==target_len; i==0 so d=0 and y=s/2\n        if (s / 2 >= target_len) {\n            cur_score = extract_epi16(_m2, s / 2 - target_len);\n            if (cur_score < minscore) {\n                minscore = cur_score;\n                minscoreidx = s + 1;\n            }\n        }\n        \n        _m2 = _mm_add_epi16(_m2, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin), _qualitieswin),\n                                               _truthnqual));\n        _d2 = _mm_min_epi16(_mm_add_epi16(_d1, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m1, _i1),  // allow I->D\n                                          _gap_open));\n        _i2 = _mm_insert_epi16(_mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_mm_srli_si128(_i1, 2), _gap_extend),\n                                                           _mm_add_epi16(_mm_srli_si128(_m1, 2), _gap_open)),\n                                             _nuc_prior),\n                               inf, bandSize - 1);\n        _backpointers[s + 1] = _mm_or_si128(_mm_or_si128(_mm_and_si128(_three, _m2),\n                                                         _mm_slli_epi16(_mm_and_si128(_three, _i2), 2 * insertLabel)),\n                                            _mm_slli_epi16(_mm_and_si128(_three, _d2), 2 * deleteLabel));\n        \n        // set state labels\n        _m2 = _mm_andnot_si128(_three, _m2);\n        _i2 = _mm_or_si128(_mm_andnot_si128(_three, _i2), _mm_srli_epi16(_three, 1));\n        _d2 = _mm_or_si128(_mm_andnot_si128(_three, _d2), _three);\n    }\n    \n    s = minscoreidx;    // point to the dummy match transition\n    \n    auto i      = s / 2 - target_len;\n    auto y      = target_len;\n    auto x      = s - y;\n    auto alnidx = 0;\n    auto state = (reinterpret_cast<short*>(_backpointers.data() + s)[i] >> (2 * matchLabel)) & 3;\n    \n    s -= 2;\n    \n    // this is 2*y (s even) or 2*y+1 (s odd)\n    while (y > 0) {\n        const auto new_state = (reinterpret_cast<short*>(_backpointers.data() + s)[i] >> (2 * state)) & 3;\n        \n        if (state == matchLabel) {\n            s -= 2;\n            aln1[alnidx] = truth[--x];\n            aln2[alnidx] = target[--y];\n        } else if (state == insertLabel) {\n            i += s & 1;\n            s -= 1;\n            aln1[alnidx] = gap;\n            aln2[alnidx] = target[--y];\n        } else {\n            s -= 1;\n            i -= s & 1;\n            aln1[alnidx] = truth[--x];\n            aln2[alnidx] = gap;\n        }\n        state = new_state;\n        alnidx++;\n    }\n    \n    aln1[alnidx] = 0;\n    aln2[alnidx] = 0;\n    \n    first_pos = x;\n    \n    // reverse them\n    for (int j {alnidx - 1}, i = 0; i < j; ++i, j--) {\n        x = aln1[i];\n        y = aln2[i];\n        aln1[i] = aln1[j];\n        aln2[i] = aln2[j];\n        aln1[j] = x;\n        aln2[j] = y;\n    }\n    \n    return (minscore + 0x8000) >> 2;\n}\n\nint align(const char* truth, const char* target, const std::int8_t* qualities,\n          int truth_len, int target_len,\n          const char* snv_mask, const std::int8_t* snv_prior,\n          const std::int8_t* gap_open, short gap_extend, short nuc_prior,\n          char* aln1, char* aln2, int& first_pos) noexcept\n{\n    assert(truth_len > bandSize && (truth_len == target_len + 2 * bandSize - 1));\n    assert(aln1 != nullptr && aln2 != nullptr);\n    \n    gap_extend <<= 2;\n    nuc_prior <<= 2;\n    \n    constexpr int matchLabel  {0};\n    constexpr int insertLabel {1};\n    constexpr int deleteLabel {3};\n    \n    using SimdInt = __m128i;\n    \n    SimdInt _m1 {_mm_set1_epi16(inf)};\n    auto _i1 = _m1;\n    auto _d1 = _m1;\n    auto _m2 = _m1;\n    auto _i2 = _m1;\n    auto _d2 = _m1;\n    \n    SimdInt _gap_extend {_mm_set1_epi16(gap_extend)};\n    SimdInt _nuc_prior  {_mm_set1_epi16(nuc_prior)};\n    SimdInt _initmask   {_mm_set_epi16(0,0,0,0,0,0,0,-1)};\n    SimdInt _initmask2  {_mm_set_epi16(0,0,0,0,0,0,0,-0x8000)};\n    \n    static const SimdInt _three {_mm_set1_epi16(3)};\n    SmallVector<SimdInt> _backpointers(2 * (truth_len + bandSize));\n    \n    SimdInt _truthwin  {_mm_set_epi16(truth[7], truth[6], truth[5], truth[4],\n                                      truth[3], truth[2], truth[1], truth[0])};\n    SimdInt _targetwin  {_m1};\n    SimdInt _qualitieswin {_mm_set1_epi16(64 << 2)};\n    \n    SimdInt _snvmaskwin  {_mm_set_epi16(snv_mask[7], snv_mask[6], snv_mask[5], snv_mask[4],\n                                        snv_mask[3], snv_mask[2], snv_mask[1], snv_mask[0])};\n    SimdInt _snv_priorwin {_mm_set_epi16(snv_prior[7] << 2, snv_prior[6] << 2, snv_prior[5] << 2, snv_prior[4] << 2,\n                                         snv_prior[3] << 2, snv_prior[2] << 2, snv_prior[1] << 2, snv_prior[0] << 2)};\n    \n    SimdInt _snvmask;\n    \n    // if N, make nScore; if != N, make inf\n    SimdInt _truthnqual {_mm_add_epi16(_mm_and_si128(_mm_cmpeq_epi16(_truthwin, _mm_set1_epi16('N')),\n                                                     _mm_set1_epi16(nScore - inf)),\n                                       _mm_set1_epi16(inf))};\n    SimdInt _gap_open {_mm_set_epi16(gap_open[7] << 2,gap_open[6] << 2,gap_open[5] << 2,gap_open[4] << 2,\n                                     gap_open[3] << 2,gap_open[2] << 2,gap_open[1] << 2,gap_open[0] << 2)};\n    \n    short cur_score {0}, minscore {inf}, minscoreidx {-1};\n    \n    int s;\n    for (s = 0; s <= 2 * (target_len + bandSize); s += 2) {\n        // truth is current; target needs updating\n        _targetwin    = _mm_slli_si128(_targetwin, 2);\n        _qualitieswin = _mm_slli_si128(_qualitieswin, 2);\n        \n        if (s / 2 < target_len) {\n            _targetwin    = _mm_insert_epi16(_targetwin, target[s / 2], 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, qualities[s / 2] << 2, 0);\n        } else {\n            _targetwin    = _mm_insert_epi16(_targetwin, '0', 0);\n            _qualitieswin = _mm_insert_epi16(_qualitieswin, 64 << 2, 0);\n        }\n        \n        // S even\n        \n        // initialize to -0x8000\n        _m1 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m1));\n        _m2 = _mm_or_si128(_initmask2, _mm_andnot_si128(_initmask, _m2));\n        _m1 = _mm_min_epi16(_m1, _mm_min_epi16(_i1, _d1));\n        \n        // at this point, extract minimum score.  Referred-to position must\n        // be y==target_len-1, so that current position has y==target_len; i==0 so d=0 and y=s/2\n        \n        if (s / 2 >= target_len) {\n            cur_score = extract_epi16(_m1, s / 2 - target_len);\n            if (cur_score < minscore) {\n                minscore = cur_score;\n                minscoreidx = s;     // point back to the match state at this entry, so as not to\n            }                        // have to store the state at s-2\n        }\n        \n        _snvmask = _mm_cmpeq_epi16(_targetwin, _snvmaskwin);\n        _m1 = _mm_add_epi16(_m1, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _mm_min_epi16(_qualitieswin,\n                                                                              _mm_or_si128(_mm_and_si128(_snvmask, _snv_priorwin),\n                                                                                           _mm_andnot_si128(_snvmask, _qualitieswin)))),\n                                               _truthnqual));\n        _d1 = _mm_min_epi16(_mm_add_epi16(_d2, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m2, _i2),\n                                          _mm_srli_si128(_gap_open, 2))); // allow I->D\n        _d1 = _mm_insert_epi16(_mm_slli_si128(_d1, 2), inf, 0);\n        _i1 = _mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_i2, _gap_extend),\n                                          _mm_add_epi16(_m2, _gap_open)), _nuc_prior);\n        \n        _backpointers[s] = _mm_or_si128(_mm_or_si128(_mm_and_si128(_three, _m1),\n                                                     _mm_slli_epi16(_mm_and_si128(_three, _i1),\n                                                                    2 * insertLabel)),\n                                        _mm_slli_epi16(_mm_and_si128(_three, _d1), 2 * deleteLabel));\n        \n        // set state labels\n        _m1 = _mm_andnot_si128(_three, _m1);\n        _i1 = _mm_or_si128(_mm_andnot_si128(_three, _i1), _mm_srli_epi16(_three, 1));\n        _d1 = _mm_or_si128(_mm_andnot_si128(_three, _d1), _three);\n        \n        // S odd\n        \n        // truth needs updating; target is current\n        const auto pos = bandSize + s / 2;\n        const char base {(pos < truth_len) ? truth[pos] : 'N'};\n        \n        _truthwin   = _mm_insert_epi16(_mm_srli_si128(_truthwin, 2), base, bandSize - 1);\n        _truthnqual = _mm_insert_epi16(_mm_srli_si128(_truthnqual, 2),\n                                       (base == 'N') ? nScore : inf, bandSize - 1);\n        _snvmaskwin   = _mm_insert_epi16(_mm_srli_si128(_snvmaskwin, 2),\n                                         pos < truth_len ? snv_mask[pos] : 'N', bandSize - 1);\n        _snv_priorwin = _mm_insert_epi16(_mm_srli_si128(_snv_priorwin, 2),\n                                         (pos < truth_len) ? snv_prior[pos] << 2 : inf << 2,\n                                         bandSize - 1);\n        _gap_open  = _mm_insert_epi16(_mm_srli_si128(_gap_open,  2),\n                                      gap_open[pos < truth_len ? pos : truth_len - 1] << 2,\n                                      bandSize - 1);\n        \n        _initmask  = _mm_slli_si128(_initmask, 2);\n        _initmask2 = _mm_slli_si128(_initmask2, 2);\n        \n        _m2 = _mm_min_epi16(_m2, _mm_min_epi16(_i2, _d2));\n        \n        // at this point, extract minimum score.  Referred-to position must\n        // be y==target_len-1, so that current position has y==target_len; i==0 so d=0 and y=s/2\n        if (s / 2 >= target_len) {\n            cur_score = extract_epi16(_m2, s / 2 - target_len);\n            if (cur_score < minscore) {\n                minscore = cur_score;\n                minscoreidx = s + 1;\n            }\n        }\n        \n        _snvmask = _mm_cmpeq_epi16(_targetwin, _snvmaskwin);\n        \n        _m2 = _mm_add_epi16(_m2, _mm_min_epi16(_mm_andnot_si128(_mm_cmpeq_epi16(_targetwin, _truthwin),\n                                                                _mm_min_epi16(_qualitieswin,\n                                                                              _mm_or_si128(_mm_and_si128(_snvmask, _snv_priorwin),\n                                                                                           _mm_andnot_si128(_snvmask, _qualitieswin)))),\n                                               _truthnqual));\n        _d2 = _mm_min_epi16(_mm_add_epi16(_d1, _gap_extend),\n                            _mm_add_epi16(_mm_min_epi16(_m1, _i1),  // allow I->D\n                                          _gap_open));\n        _i2 = _mm_insert_epi16(_mm_add_epi16(_mm_min_epi16(_mm_add_epi16(_mm_srli_si128(_i1, 2), _gap_extend),\n                                                           _mm_add_epi16(_mm_srli_si128(_m1, 2), _gap_open)),\n                                             _nuc_prior),\n                               inf, bandSize - 1);\n        _backpointers[s + 1] = _mm_or_si128(_mm_or_si128(_mm_and_si128(_three, _m2),\n                                                         _mm_slli_epi16(_mm_and_si128(_three, _i2), 2 * insertLabel)),\n                                            _mm_slli_epi16(_mm_and_si128(_three, _d2), 2 * deleteLabel));\n        \n        // set state labels\n        _m2 = _mm_andnot_si128(_three, _m2);\n        _i2 = _mm_or_si128(_mm_andnot_si128(_three, _i2), _mm_srli_epi16(_three, 1));\n        _d2 = _mm_or_si128(_mm_andnot_si128(_three, _d2), _three);\n    }\n    \n    s = minscoreidx;    // point to the dummy match transition\n    \n    auto i      = s / 2 - target_len;\n    auto y      = target_len;\n    auto x      = s - y;\n    auto alnidx = 0;\n    auto state  = (reinterpret_cast<short*>(_backpointers.data() + s)[i] >> (2 * matchLabel)) & 3;\n    \n    s -= 2;\n    \n    // this is 2*y (s even) or 2*y+1 (s odd)\n    while (y > 0) {\n        const auto new_state = (reinterpret_cast<short*>(_backpointers.data() + s)[i] >> (2 * state)) & 3;\n        \n        if (state == matchLabel) {\n            s -= 2;\n            aln1[alnidx] = truth[--x];\n            aln2[alnidx] = target[--y];\n        } else if (state == insertLabel) {\n            i += s & 1;\n            s -= 1;\n            aln1[alnidx] = gap;\n            aln2[alnidx] = target[--y];\n        } else {\n            s -= 1;\n            i -= s & 1;\n            aln1[alnidx] = truth[--x];\n            aln2[alnidx] = gap;\n        }\n        state = new_state;\n        alnidx++;\n    }\n    \n    aln1[alnidx] = 0;\n    aln2[alnidx] = 0;\n    first_pos = x;\n    \n    // reverse them\n    for (int j {alnidx - 1}, i = 0; i < j; ++i, j--) {\n        x = aln1[i];\n        y = aln2[i];\n        aln1[i] = aln1[j];\n        aln2[i] = aln2[j];\n        aln1[j] = x;\n        aln2[j] = y;\n    }\n    \n    return (minscore + 0x8000) >> 2;\n}\n\nint calculate_flank_score(const int truth_len, const int lhs_flank_len, const int rhs_flank_len,\n                          const std::int8_t* quals, const std::int8_t* gap_open,\n                          const short gap_extend, const short nuc_prior,\n                          const int first_pos, const char* aln1, const char* aln2,\n                          int& target_mask_size) noexcept\n{\n    static constexpr char match {'M'}, insertion {'I'}, deletion {'D'};\n    \n    auto prev_state = match;\n    int x {first_pos}; // index into haplotype\n    int y {0};         // index into read\n    int i {0};         // index into alignment\n    int result {0};    // alignment score (within flank)\n    target_mask_size = 0;\n    \n    while (aln1[i]) {\n        auto new_state = match;\n        if (aln1[i] == gap) {\n            new_state = insertion;\n        } else if (aln2[i] == gap) { // can't be both '-'\n            new_state = deletion;\n        }\n        switch (new_state) {\n            case match:\n            {\n                if (x < lhs_flank_len || x >= (truth_len - rhs_flank_len)) {\n                    if (aln1[i] != aln2[i]) {\n                        if (aln1[i] != 'N') {\n                            result += quals[y];\n                        } else {\n                            result += nScore >> 2;\n                        }\n                    }\n                    ++target_mask_size;\n                }\n                ++x;\n                ++y;\n                break;\n            }\n            case insertion:\n            {\n                if (x < lhs_flank_len || x >= (truth_len - rhs_flank_len)) {\n                    if (prev_state == insertion) {\n                        result += gap_extend + nuc_prior;\n                    } else {\n                        // gap open score is charged for insertions just after the corresponding base, hence the -1\n                        result += gap_open[x - 1] + nuc_prior;\n                    }\n                    ++target_mask_size;\n                }\n                ++y;\n                break;\n            }\n            case deletion:\n            {\n                if (x < lhs_flank_len || x >= (truth_len - rhs_flank_len)) {\n                    if (prev_state == deletion) {\n                        result += gap_extend;\n                    } else {\n                        result += gap_open[x];\n                    }\n                }\n                ++x;\n                break;\n            }\n        }\n        \n        ++i;\n        prev_state = new_state;\n    }\n    \n    return result;\n}\n\nint calculate_flank_score(const int truth_len, const int lhs_flank_len, const int rhs_flank_len,\n                          const char* target, const std::int8_t* quals,\n                          const char* snv_mask, const std::int8_t* snv_prior,\n                          const std::int8_t* gap_open, const short gap_extend, const short nuc_prior,\n                          const int first_pos, const char* aln1, const char* aln2,\n                          int& target_mask_size) noexcept\n{\n    static constexpr char match {'M'}, insertion {'I'}, deletion {'D'};\n    \n    auto prev_state = match;\n    int x {first_pos}; // index into truth\n    int y {0};         // index into target\n    int i {0};         // index into alignment\n    int result {0};    // alignment score (within flank)\n    const auto rhs_flank_begin = truth_len - rhs_flank_len;\n    target_mask_size = 0;\n    \n    while (aln1[i]) {\n        auto new_state = match;\n        if (aln1[i] == gap) {\n            new_state = insertion;\n        } else if (aln2[i] == gap) { // can't be both '-'\n            new_state = deletion;\n        }\n        switch (new_state) {\n            case match:\n            {\n                if (x < lhs_flank_len || x >= rhs_flank_begin) {\n                    if (aln1[i] != aln2[i]) {\n                        if (aln1[i] != 'N') {\n                            result += (snv_mask[x] == target[y]) ? std::min(quals[y], snv_prior[x]) : quals[y];\n                        } else {\n                            result += nScore >> 2;\n                        }\n                    }\n                    ++target_mask_size;\n                }\n                ++x;\n                ++y;\n                break;\n            }\n            case insertion:\n            {\n                if (x < lhs_flank_len || x >= rhs_flank_begin) {\n                    if (prev_state == insertion) {\n                        result += gap_extend + nuc_prior;\n                    } else {\n                        // gap open score is charged for insertions just after the corresponding base, hence the -1\n                        result += gap_open[x - 1] + nuc_prior;\n                    }\n                    ++target_mask_size;\n                }\n                ++y;\n                break;\n            }\n            case deletion:\n            {\n                if (x < lhs_flank_len || x >= rhs_flank_begin) {\n                    if (prev_state == deletion) {\n                        result += gap_extend;\n                    } else {\n                        result += gap_open[x];\n                    }\n                }\n                ++x;\n                break;\n            }\n        }\n        ++i;\n        prev_state = new_state;\n    }\n    \n    return result;\n}\n\n} // namespace simd\n} // namespace hmm\n} // namespace octopus\n", "meta": {"hexsha": "939879e5077fe3562d6d64367399b5a65c453b72", "size": 49807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/models/pairhmm/simd_pair_hmm.cpp", "max_stars_repo_name": "alimanfoo/octopus", "max_stars_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-21T23:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T23:34:28.000Z", "max_issues_repo_path": "src/core/models/pairhmm/simd_pair_hmm.cpp", "max_issues_repo_name": "alimanfoo/octopus", "max_issues_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/models/pairhmm/simd_pair_hmm.cpp", "max_forks_repo_name": "alimanfoo/octopus", "max_forks_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.669955157, "max_line_length": 137, "alphanum_fraction": 0.5181400205, "num_tokens": 14328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388515, "lm_q2_score": 0.02333077097307662, "lm_q1q2_score": 0.010394547887279146}}
{"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 SLHA_IO_H\n#define SLHA_IO_H\n\n#include <string>\n#include <sstream>\n#include <iosfwd>\n#include <vector>\n#include <Eigen/Core>\n#include <boost/format.hpp>\n#include <boost/function.hpp>\n#include \"slhaea.h\"\n#include \"config.h\"\n#include \"logger.hpp\"\n#include \"error.hpp\"\n#include \"wrappers.hpp\"\n#include \"numerics2.hpp\"\n#include \"pmns.hpp\"\n#include \"standard_model_two_scale_model.hpp\"\n\nnamespace softsusy {\n   class QedQcd;\n} // namespace softsusy\n\nnamespace flexiblesusy {\n\n   class Spectrum_generator_settings;\n   class Physical_input;\n\n   namespace {\n      /// SLHA line formatter for the MASS block entries\n      const boost::format mass_formatter(\" %9d   %16.8E   # %s\\n\");\n      /// SLHA line formatter for the mixing matrix entries (NMIX, UMIX, VMIX, ...)\n      const boost::format mixing_matrix_formatter(\" %2d %2d   %16.8E   # %s\\n\");\n      /// SLHA line formatter for vector entries\n      const boost::format vector_formatter(\" %5d   %16.8E   # %s\\n\");\n      /// SLHA number formatter\n      const boost::format number_formatter(\"         %16.8E   # %s\\n\");\n      /// SLHA line formatter for entries with three indices\n      const boost::format tensor_formatter(\" %8d %8d %8d   %16.8E   # %s\\n\");\n      /// SLHA scale formatter\n      const boost::format scale_formatter(\"%9.8E\");\n      /// SLHA line formatter for the one-element entries (HMIX, GAUGE, MSOFT, ...)\n      const boost::format single_element_formatter(\" %5d   %16.8E   # %s\\n\");\n      /// SLHA line formatter for the SPINFO block entries\n      const boost::format spinfo_formatter(\" %5d   %s\\n\");\n   } // namespace\n\n#define FORMAT_MASS(pdg,mass,name)                                      \\\n   boost::format(mass_formatter) % (pdg) % (mass) % (name)\n#define FORMAT_MIXING_MATRIX(i,k,entry,name)                            \\\n   boost::format(mixing_matrix_formatter) % (i) % (k) % (entry) % (name)\n#define FORMAT_ELEMENT(pdg,value,name)                                  \\\n   boost::format(single_element_formatter) % (pdg) % (value) % (name)\n#define FORMAT_SCALE(n)                                                 \\\n   boost::format(scale_formatter) % (n)\n#define FORMAT_NUMBER(n,str)                                            \\\n   boost::format(number_formatter) % (n) % (str)\n#define FORMAT_SPINFO(n,str)                                            \\\n   boost::format(spinfo_formatter) % (n) % (str)\n#define FORMAT_RANK_THREE_TENSOR(i,j,k,entry,name)                      \\\n   boost::format(tensor_formatter) % (i) % (j) % (k) % (entry) % (name)\n\n/**\n * @class SLHA_io\n * @brief Handles reading and writing of SLHA files\n *\n * Reading: There are two ways to read block entries from SLHA files:\n * a) using the read_block() function with a %SLHA_io::Tuple_processor\n * or b) using the read_entry() function for each entry.  Note, that\n * a) is much faster than b) (more than 1000 times) because b) needs\n * to search for the block each time read_entry() is called.\n *\n * Example how to use a tuple processor (fast!):\n * \\code{.cpp}\nvoid process_tuple(double* array, int key, double value) {\n   array[key] = value;\n}\n\nvoid read_file() {\n   double array[1000];\n\n   SLHA_io reader;\n   reader.read_from_file(\"file.slha\");\n\n   SLHA_io::Tuple_processor processor = [&array] (int key, double value) {\n      return process_tuple(array, key, value);\n   };\n\n   reader.read_block(\"MyBlock\", processor);\n}\n * \\endcode\n *\n * Example how to use a for loop (slow!):\n * \\code{.cpp}\nvoid read_file() {\n   double array[1000];\n\n   SLHA_io reader;\n   reader.read_from_file(\"file.slha\");\n\n   for (int i = 0; i < 1000; i++) {\n      array[i] = reader.read_entry(\"MyBlock\", i);\n   }\n}\n * \\endcode\n */\nclass SLHA_io {\npublic:\n   using Tuple_processor = std::function<void(int, double)>;\n   enum Position { front, back };\n   struct Modsel {\n      bool quark_flavour_violated{false};   ///< MODSEL[6]\n      bool lepton_flavour_violated{false};  ///< MODSEL[6]\n      double parameter_output_scale{0.};    ///< MODSEL[12]\n      void clear() { *this = Modsel(); }\n   };\n\n   struct CKM_wolfenstein {\n      double lambdaW{0.}, aCkm{0.}, rhobar{0.}, etabar{0.};\n      void clear() { *this = CKM_wolfenstein(); }\n   };\n\n   void clear();\n\n   // reading functions\n   bool block_exists(const std::string&) const;\n   void fill(softsusy::QedQcd&) const;\n   void fill(Spectrum_generator_settings&) const;\n   void fill(Physical_input&) const;\n   const Modsel& get_modsel() const { return modsel; }\n   const SLHAea::Coll& get_data() const { return data; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   double read_block(const std::string&, const Tuple_processor&) const;\n   template <class Derived>\n   double read_block(const std::string&, Eigen::MatrixBase<Derived>&) const;\n   double read_block(const std::string&, double&) const;\n   double read_entry(const std::string&, int) const;\n   double read_scale(const std::string&) const;\n\n   // writing functions\n   void set_data(const SLHAea::Coll& data_) { data = data_; }\n   void set_block(const std::ostringstream&, Position position = back);\n   void set_block(const std::string&, Position position = back);\n   void set_blocks(const std::vector<std::string>&, Position position = back);\n   void set_block(const std::string&, double, const std::string&, double scale = 0.);\n   template<class Scalar, int M, int N>\n   void set_block(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, N>&, const std::string&, double scale = 0.);\n   template<class Scalar, int M>\n   void set_block(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, 1>&, const std::string&, double scale = 0.);\n   template<class Scalar, int M, int N>\n   void set_block_imag(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, N>&, const std::string&, double scale = 0.);\n   template<class Scalar, int M>\n   void set_block_imag(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, 1>&, const std::string&, double scale = 0.);\n   template <class Derived>\n   void set_block(const std::string&, const Eigen::MatrixBase<Derived>&, const std::string&, double scale = 0.);\n   template <class Derived>\n   void set_block_imag(const std::string&, const Eigen::MatrixBase<Derived>&, const std::string&, double scale = 0.);\n   void set_modsel(const Modsel&);\n   void set_physical_input(const Physical_input&);\n   void set_settings(const Spectrum_generator_settings&);\n   void set_sminputs(const softsusy::QedQcd&);\n   void write_to_file(const std::string&) const;\n   void write_to_stream(std::ostream& = std::cerr) const;\n\n   // Standard_model class interface\n   void set_mass(const standard_model::Standard_model_physical&);\n   void set_mixing_matrices(const standard_model::Standard_model_physical&);\n   void set_model_parameters(const standard_model::Standard_model&);\n   void set_spectrum(const standard_model::Standard_model&);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>&,\n                                                         Eigen::Matrix<double, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_slha(double&,\n                                                         Eigen::Matrix<double, 1, 1>&);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>&,\n                                                         Eigen::Matrix<std::complex<double>, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_slha(double&,\n                                                         Eigen::Matrix<std::complex<double>, 1, 1>&);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>&,\n                                                       Eigen::Matrix<double, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_hk(double&,\n                                                       Eigen::Matrix<double, 1, 1>&);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>&,\n                                                       Eigen::Matrix<std::complex<double>, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_hk(double&,\n                                                       Eigen::Matrix<std::complex<double>, 1, 1>&);\n\nprivate:\n   SLHAea::Coll data{};        ///< SHLA data\n   Modsel modsel{};            ///< data from block MODSEL\n   template <class Scalar>\n   static Scalar convert_to(const std::string&); ///< convert string\n   static std::string to_lower(const std::string&); ///< string to lower case\n   static void process_sminputs_tuple(softsusy::QedQcd&, int, double);\n   static void process_modsel_tuple(Modsel&, int, double);\n   static void process_vckmin_tuple(CKM_wolfenstein&, int, double);\n   static void process_upmnsin_tuple(PMNS_parameters&, int, double);\n   static void process_flexiblesusy_tuple(Spectrum_generator_settings&, int, double);\n   static void process_flexiblesusyinput_tuple(Physical_input&, int, double);\n   void read_modsel();\n   template <class Derived>\n   double read_matrix(const std::string&, Eigen::MatrixBase<Derived>&) const;\n   template <class Derived>\n   double read_vector(const std::string&, Eigen::MatrixBase<Derived>&) const;\n};\n\ntemplate<class S>\nstruct Set_spectrum {\n   S* slha_io;\n   Set_spectrum(S* slha_io_) : slha_io(slha_io_) {}\n   template<typename T>\n   void operator()(const T& model) const { slha_io->set_spectrum(model); }\n};\n\ntemplate <class Scalar>\nScalar SLHA_io::convert_to(const std::string& str)\n{\n   Scalar value;\n   try {\n      value = SLHAea::to<Scalar>(str);\n   }  catch (const boost::bad_lexical_cast& error) {\n      const std::string msg(R\"(cannot convert string \")\" + str + R\"(\" to )\"\n                            + typeid(Scalar).name());\n      throw ReadError(msg);\n   }\n   return value;\n}\n\n/**\n * Fills a matrix from a SLHA block\n *\n * @param block_name block name\n * @param matrix matrix to be filled\n *\n * @return scale (or 0 if no scale is defined)\n */\ntemplate <class Derived>\ndouble SLHA_io::read_matrix(const std::string& block_name, Eigen::MatrixBase<Derived>& matrix) const\n{\n   if (matrix.cols() <= 1) throw SetupError(\"Matrix has less than 2 columns\");\n\n   auto block = data.find(data.cbegin(), data.cend(), block_name);\n\n   const int cols = matrix.cols(), rows = matrix.rows();\n   double scale = 0.;\n\n   while (block != data.cend()) {\n      for (const auto& line: *block) {\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() >= 3) {\n            const int i = convert_to<int>(line[0]) - 1;\n            const int k = convert_to<int>(line[1]) - 1;\n            if (0 <= i && i < rows && 0 <= k && k < cols) {\n               const double value = convert_to<double>(line[2]);\n               matrix(i,k) = value;\n            }\n         }\n      }\n\n      ++block;\n      block = data.find(block, data.cend(), block_name);\n   }\n\n   return scale;\n}\n\n/**\n * Fills a vector from a SLHA block\n *\n * @param block_name block name\n * @param vector vector to be filled\n *\n * @return scale (or 0 if no scale is defined)\n */\ntemplate <class Derived>\ndouble SLHA_io::read_vector(const std::string& block_name, Eigen::MatrixBase<Derived>& vector) const\n{\n   if (vector.cols() != 1) throw SetupError(\"Vector has more than 1 column\");\n\n   auto block = data.find(data.cbegin(), data.cend(), block_name);\n\n   const int rows = vector.rows();\n   double scale = 0.;\n\n   while (block != data.cend()) {\n      for (const auto& line: *block) {\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 i = convert_to<int>(line[0]) - 1;\n            if (0 <= i && i < rows) {\n               const double value = convert_to<double>(line[1]);\n               vector(i,0) = value;\n            }\n         }\n      }\n\n      ++block;\n      block = data.find(block, data.cend(), block_name);\n   }\n\n   return scale;\n}\n\n/**\n * Fills a matrix or vector from a SLHA block\n *\n * @param block_name block name\n * @param dense matrix or vector to be filled\n *\n * @return scale (or 0 if no scale is defined)\n */\ntemplate <class Derived>\ndouble SLHA_io::read_block(const std::string& block_name, Eigen::MatrixBase<Derived>& dense) const\n{\n   return dense.cols() == 1\n      ? read_vector(block_name, dense)\n      : read_matrix(block_name, dense);\n}\n\ntemplate<class Scalar, int NRows>\nvoid SLHA_io::set_block(const std::string& name,\n                        const Eigen::Matrix<std::complex<Scalar>, NRows, 1>& 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 <= NRows; ++i) {\n      ss << boost::format(vector_formatter) % i % Re(matrix(i-1,0))\n         % (\"Re(\" + symbol + \"(\" + ToString(i) + \"))\");\n   }\n\n   set_block(ss);\n}\n\ntemplate<class Scalar, int NRows, int NCols>\nvoid SLHA_io::set_block(const std::string& name,\n                        const Eigen::Matrix<std::complex<Scalar>, NRows, NCols>& 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 <= NRows; ++i) {\n      for (int k = 1; k <= NCols; ++k) {\n         ss << boost::format(mixing_matrix_formatter) % i % k\n            % Re(matrix(i-1,k-1))\n            % (\"Re(\" + symbol + \"(\" + ToString(i) + \",\"\n               + ToString(k) + \"))\");\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate<class Scalar, int NRows>\nvoid SLHA_io::set_block_imag(const std::string& name,\n                             const Eigen::Matrix<std::complex<Scalar>, NRows, 1>& 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 <= NRows; ++i) {\n      ss << boost::format(vector_formatter) % i % Im(matrix(i-1,0))\n         % (\"Im(\" + symbol + \"(\" + ToString(i) + \"))\");\n   }\n\n   set_block(ss);\n}\n\ntemplate<class Scalar, int NRows, int NCols>\nvoid SLHA_io::set_block_imag(const std::string& name,\n                             const Eigen::Matrix<std::complex<Scalar>, NRows, NCols>& 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 <= NRows; ++i) {\n      for (int k = 1; k <= NCols; ++k) {\n         ss << boost::format(mixing_matrix_formatter) % i % k\n            % Im(matrix(i-1,k-1))\n            % (\"Im(\" + symbol + \"(\" + ToString(i) + \",\"\n               + ToString(k) + \"))\");\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate <class Derived>\nvoid SLHA_io::set_block(const std::string& name,\n                        const Eigen::MatrixBase<Derived>& 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   const int rows = matrix.rows();\n   const int cols = matrix.cols();\n   for (int i = 1; i <= rows; ++i) {\n      if (cols == 1) {\n         ss << boost::format(vector_formatter) % i % matrix(i-1,0)\n            % (symbol + \"(\" + ToString(i) + \")\");\n      } else {\n         for (int k = 1; k <= cols; ++k) {\n            ss << boost::format(mixing_matrix_formatter) % i % k % matrix(i-1,k-1)\n               % (symbol + \"(\" + ToString(i) + \",\" + ToString(k) + \")\");\n         }\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate <class Derived>\nvoid SLHA_io::set_block_imag(const std::string& name,\n                             const Eigen::MatrixBase<Derived>& 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   const int rows = matrix.rows();\n   const int cols = matrix.cols();\n   for (int i = 1; i <= rows; ++i) {\n      if (cols == 1) {\n         ss << boost::format(vector_formatter) % i % Im(matrix(i-1,0))\n            % (\"Im(\" + symbol + \"(\" + ToString(i) + \"))\");\n      } else {\n         for (int k = 1; k <= cols; ++k) {\n            ss << boost::format(mixing_matrix_formatter) % i % k % Im(matrix(i-1,k-1))\n               % (\"Im(\" + symbol + \"(\" + ToString(i) + \",\" + ToString(k) + \"))\");\n         }\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>&,\n                                                        Eigen::Matrix<double, N, N>&)\n{\n}\n\n/**\n * Converts the given vector of masses and the corresponding (complex)\n * mixing matrix to SLHA convention: Matrix rows with non-zero\n * imaginary parts are multiplied by i and the corresponding mass\n * eigenvalue is multiplied by -1.  As a result the mixing matrix will\n * be real and the mass eigenvalues might be positive or negative.  It\n * is assumed that these mixings result from diagonalizing a symmetric\n * fermion mass matrix in the convention of Haber and Kane,\n * Phys. Rept. 117 (1985) 75-263.  This conversion makes sense only if\n * the original symmetric mass matrix is real-valued.\n *\n * @param m vector of masses\n * @param z mixing matrix\n */\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>& m,\n                                                        Eigen::Matrix<std::complex<double>, N, N>& z)\n{\n   for (int i = 0; i < N; i++) {\n      // check if i'th row contains non-zero imaginary parts\n      if (!is_zero(z.row(i).imag().cwiseAbs().maxCoeff())) {\n         z.row(i) *= std::complex<double>(0.0,1.0);\n         m(i) *= -1;\n#ifdef ENABLE_DEBUG\n         if (!is_zero(z.row(i).imag().cwiseAbs().maxCoeff())) {\n            WARNING(\"Row \" << i << \" 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}\n\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>&,\n                                                      Eigen::Matrix<double, N, N>&)\n{\n}\n\n/**\n * Converts the given vector of masses and the corresponding (real)\n * mixing matrix to Haber-Kane convention (Phys. Rept. 117 (1985)\n * 75-263): Masses are positive and mixing matrices can be complex.\n *\n * @param m vector of masses\n * @param z mixing matrix\n */\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>& m,\n                                                      Eigen::Matrix<std::complex<double>, N, N>& z)\n{\n   for (int i = 0; i < N; i++) {\n      if (m(i) < 0.) {\n         z.row(i) *= std::complex<double>(0.0,1.0);\n         m(i) *= -1;\n      }\n   }\n}\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "ecd10305e9e74a7b65c0f6dac4a408508d5d2686", "size": 20348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/slha_io.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/slha_io.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/slha_io.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": 35.4494773519, "max_line_length": 132, "alphanum_fraction": 0.5903282878, "num_tokens": 5194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808785120009, "lm_q2_score": 0.0356785513904138, "lm_q1q2_score": 0.010381776227618178}}
{"text": "/// @file\n/// @copyright The code is licensed under the BSD License\n///            <http://opensource.org/licenses/BSD-2-Clause>,\n///            Copyright (c) 2012-2015 Alexandre Hamez.\n/// @author Alexandre Hamez\n\n#pragma once\n\n#include <initializer_list>\n#include <type_traits> // enable_if, is_same\n#include <unordered_map>\n#include <vector>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/container/flat_set.hpp>\n\n#include \"sdd/internal_manager_fwd.hh\"\n#include \"sdd/dd/check_compatibility.hh\"\n#include \"sdd/dd/context_fwd.hh\"\n#include \"sdd/dd/definition.hh\"\n#include \"sdd/dd/nary.hh\"\n#include \"sdd/dd/operations_fwd.hh\"\n#include \"sdd/dd/square_union.hh\"\n#include \"sdd/mem/linear_alloc.hh\"\n#include \"sdd/util/hash.hh\"\n#include \"sdd/values/empty.hh\"\n#include \"sdd/values/values_traits.hh\"\n\nnamespace sdd { namespace dd {\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief The sum operation in the cache.\ntemplate <typename C>\nstruct LIBSDD_ATTRIBUTE_PACKED sum_op_impl\n{\n  /// @brief The textual representation of the union operator.\n  static constexpr char symbol = '+';\n\n  /// @brief Perform the SDD union algorithm.\n  ///\n  /// It's a so-called 'n-ary' union in the sense that we don't create intermediary SDD.\n  /// Also, a lot of tests permit to break loops as soon as possible.\n  template <typename InputIterator, typename NodeType>\n  static\n  std::enable_if_t< std::is_same<NodeType, hierarchical_node<C>>::value\n                    or not values::values_traits<typename C::Values>::fast_iterable\n                  , SDD<C>>\n  work(InputIterator begin, InputIterator end, context<C>& cxt)\n  {\n    using node_type = NodeType;\n    using valuation_type = typename node_type::valuation_type;\n\n    mem::rewinder _(cxt.arena());\n\n    auto operands_cit = begin;\n    const auto operands_end = end;\n\n    // Get the first operand as a node, we need it to initialize the algorithm.\n    const node_type& head = mem::variant_cast<node_type>(**operands_cit);\n\n    // Type of the list of successors for a valuation, to be merged with the union operation\n    // right before calling the square union.\n    using sum_builder_type = sum_builder<C, SDD<C>>;\n\n    /// @todo Use intrusive hash map to save on memory allocations?\n    // List all the successors for each valuation in the final alpha.\n    std::unordered_map< valuation_type\n                      , sum_builder_type\n                      , std::hash<valuation_type>\n                      , std::equal_to<valuation_type>\n                      , mem::linear_alloc<std::pair<const valuation_type, sum_builder_type>>\n                      >\n      res( head.size(), std::hash<valuation_type>(), std::equal_to<valuation_type>()\n         , mem::linear_alloc<std::pair<const valuation_type, sum_builder_type>>(cxt.arena()));\n\n    using pair_type = std::pair<valuation_type, sum_builder_type>;\n\n    // Needed to temporarily store arcs erased from res and arcs from the alpha visited in\n    // the loop (B).\n    std::vector<pair_type, mem::linear_alloc<pair_type>>\n      save(mem::linear_alloc<pair_type>(cxt.arena()));\n    save.reserve(head.size());\n\n    // Used in test (F).\n    std::vector<pair_type, mem::linear_alloc<pair_type>>\n      remainder(mem::linear_alloc<pair_type>(cxt.arena()));\n    remainder.reserve(head.size());\n\n    // Initialize res with the alpha of the first operand.\n    for (const auto& arc : head)\n    {\n      sum_builder_type succs(cxt);\n      succs.add(arc.successor());\n      res.emplace(arc.valuation(), std::move(succs));\n    }\n\n    // (A).\n    for (++operands_cit; operands_cit != operands_end; ++operands_cit)\n    {\n      // Throw a Top if operands are incompatible (different types or different variables).\n      check_compatibility(*begin, *operands_cit);\n\n      const auto res_end = res.end();\n\n      const node_type& node = mem::variant_cast<node_type>(**operands_cit);\n      const auto alpha_end = node.end();\n\n      // (B). For each arc of the current operand.\n      for (auto alpha_cit = node.begin(); alpha_cit != alpha_end; ++alpha_cit)\n      {\n        // The current valuation may be modified, we need a copy.\n        auto current_val = alpha_cit->valuation();\n        auto current_succ = alpha_cit->successor();\n\n        // Initialize the start of the next search.\n        auto res_cit = res.begin();\n\n        // (C). While the current valuation is not empty, test it against arcs in res.\n        while (not values::empty_values(current_val) and res_cit != res_end)\n        {\n          const valuation_type& res_val = res_cit->first;\n          sum_builder_type& res_succs = res_cit->second;\n\n          // (D).\n          if (current_val == res_val) // Same valuations.\n          {\n            save.emplace_back(res_val, std::move(res_succs));\n            save.back().second.add(std::move(current_succ));\n            res_cit = res.erase(res_cit);\n            // Avoid useless insertion or temporary variables.\n            goto equality;\n          }\n\n          intersection_builder<C, valuation_type> inter_builder(cxt);\n          inter_builder.add(current_val);\n          inter_builder.add(res_val);\n          const valuation_type inter = intersection(cxt, std::move(inter_builder));\n\n          // (E). The current valuation and the current arc from res have a common part.\n          if (not values::empty_values(inter))\n          {\n            save.emplace_back(inter, res_succs);\n            save.back().second.add(current_succ);\n\n            // (F).\n            valuation_type diff = difference(cxt, res_val, inter);\n            if (not values::empty_values(diff))\n            {\n              // (res_val - inter) can't be in intersection, but we need to keep it\n              // for the next arcs of the current alpha. So we put it in a temporary storage.\n              // It will be added back in res when we have finished with the current valuation.\n              remainder.emplace_back(std::move(diff), std::move(res_succs));\n            }\n\n            // We won't need the current arc of res for the current val, we already have the\n            // common part. Now, the current valuation has to be tested against the next arcs\n            // of res.\n            res_cit = res.erase(res_cit);\n\n            // (G). The current valuation is completely included in the current arc of res.\n            if (current_val == inter)\n            {\n              // We can move to the next arc of the current operand.\n              break;\n            }\n\n            // Continue with what remains of val. If val is empty, the loop will stop at the\n            // next iteration.\n            current_val = difference(cxt, current_val, inter);\n          }\n          else // (H). Empty intersection, lookup for next possible common parts.\n          {\n            ++res_cit;\n          }\n        } // While we're not at the end of res and val is not empty.\n\n        // (I). For val or a part of val (it could have been modified during the previous\n        // loop), we didn't find an intersection with any arc of res.\n        if (not values::empty_values(current_val))\n        {\n          sum_builder_type succs(cxt);\n          succs.add(std::move(current_succ));\n          save.emplace_back(std::move(current_val), std::move(succs));\n        }\n\n        // Both arcs had the same valuation.\n        equality:;\n\n        // Reinject all parts that were removed in (F).\n        for (auto& rem : remainder)\n        {\n          res.emplace(std::move(rem.first), std::move(rem.second));\n        }\n        remainder.clear();\n\n      } // For each arc of the current operand.\n\n      // Reinject all parts that were removed from res (all parts that have a non-empty\n      // intersection with the current alpha) and all parts of the current alpha that have an\n      // empty intersection with all the parts of res.\n      res.insert(save.begin(), save.end());\n\n      // We still need save.\n      save.clear();\n    } // End of iteration on operands.\n\n    square_union<C, valuation_type> su(cxt);\n    su.reserve(res.size());\n    for (auto& arc : res)\n    {\n      // construct an operand for the square union: (successors union) --> valuation\n      su.add(sum(cxt, std::move(arc.second)), std::move(arc.first));\n    }\n\n    return SDD<C>(head.variable(), su());\n  }\n\n  /// @brief Linear union of flat SDDs whose valuation are \"fast iterable\".\n  template <typename InputIterator, typename NodeType>\n  static\n  std::enable_if_t< std::is_same<NodeType, flat_node<C>>::value\n                    and values::values_traits<typename C::Values>::fast_iterable\n                  , SDD<C>>\n  work(InputIterator begin, InputIterator end, context<C>& cxt)\n  {\n    const auto& variable = mem::variant_cast<flat_node<C>>(**begin).variable();\n\n    mem::rewinder _(cxt.arena());\n\n    using values_type      = typename C::Values;\n    using values_builder   = typename values::values_traits<values_type>::builder;\n    using value_type       = typename values_type::value_type;\n    using sum_builder_type = sum_builder<C, SDD<C>>;\n    boost::container::flat_map< value_type, sum_builder_type, std::less<value_type>\n                              , mem::linear_alloc<std::pair<value_type, sum_builder_type>>>\n      value_to_succ( std::less<value_type>()\n                   , mem::linear_alloc<std::pair<value_type, sum_builder_type>>(cxt.arena()));\n    value_to_succ.reserve(std::distance(begin, end) * 2);\n\n    for (auto cit = begin; cit != end; ++cit)\n    {\n      check_compatibility(*begin, *cit);\n\n      const auto& node = mem::variant_cast<flat_node<C>>(**cit);\n      for (const auto& arc : node)\n      {\n        const SDD<C> succ = arc.successor();\n        for (const auto& value : arc.valuation())\n        {\n          const auto search = value_to_succ.find(value);\n          if (search == value_to_succ.end())\n          {\n            value_to_succ.emplace_hint(search, value, sum_builder_type(cxt, {succ}));\n          }\n          else\n          {\n            search->second.add(succ);\n          }\n        }\n      }\n    }\n\n    // The following is almost like the square union except that we use a values_builder to\n    // efficiently create the valuation of an arc (rather than using a union).\n    boost::container::flat_map< SDD<C>, values_builder, std::less<SDD<C>>\n                              , mem::linear_alloc<std::pair<SDD<C>, values_builder>>>\n      succ_to_value( std::less<SDD<C>>()\n                   , mem::linear_alloc<std::pair<SDD<C>, values_builder>>(cxt.arena()));\n    succ_to_value.reserve(value_to_succ.size());\n    for (auto& value_succs : value_to_succ)\n    {\n      const SDD<C> succ = sum(cxt, std::move(value_succs.second));\n      const auto search = succ_to_value.find(succ);\n      if (search == succ_to_value.end())\n      {\n        values_builder tmp;\n        tmp.insert(value_succs.first);\n        succ_to_value.emplace_hint(search, std::move(succ), std::move(tmp));\n      }\n      else\n      {\n        search->second.insert(std::move(value_succs.first));\n      }\n    }\n\n    alpha_builder<C, values_type> alpha(cxt);\n    alpha.reserve(succ_to_value.size());\n    for (auto& succ_values : succ_to_value)\n    {\n      alpha.add(values_type(std::move(succ_values.second)), std::move(succ_values.first));\n    }\n\n    return SDD<C>(variable, std::move(alpha));\n  }\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief Add an arc to the operands of the sum operation.\nstruct sum_builder_policy\n{\n  template <typename Container, typename Valuation>\n  void\n  add(Container& set, Valuation&& operand)\n  {\n    if (not values::empty_values(operand))\n    {\n      set.insert(std::forward<Valuation>(operand));\n    }\n  }\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief The sum operation of a set of SDD.\n/// @related sdd::SDD\ntemplate <typename C>\ninline\nSDD<C>\nsum(context<C>& cxt, sum_builder<C, SDD<C>>&& builder)\n{\n  if (builder.empty())\n  {\n    return zero<C>();\n  }\n  else if (builder.size() == 1)\n  {\n    return *builder.begin();\n  }\n  return cxt.sum_cache()({builder});\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @internal\n/// @brief The sum operation of a set of values.\n/// @details A wrapper around the implementation of sum provided by Values.\ntemplate <typename C, typename Values>\ninline\nValues\nsum(context<C>&, sum_builder<C, Values>&& builder)\n{\n  if (builder.empty())\n  {\n    return Values();\n  }\n  else if (builder.size() == 1)\n  {\n    return *builder.begin();\n  }\n  else\n  {\n    auto cit = builder.begin();\n    const auto end = builder.end();\n    Values result = *cit;\n    for (++cit; cit != end; ++cit)\n    {\n      typename C::Values tmp = sum(result, *cit);\n      using std::swap;\n      swap(tmp, result);\n    }\n    return result;\n  }\n}\n\n} // namespace dd\n\n/*------------------------------------------------------------------------------------------------*/\n\n/// @brief Perform the union of two SDD.\n/// @related SDD\ntemplate <typename C>\ninline\nSDD<C>\noperator+(const SDD<C>& lhs, const SDD<C>& rhs)\n{\n  return dd::sum( global<C>().sdd_context\n                , dd::sum_builder<C, SDD<C>>(global<C>().sdd_context, {lhs, rhs}));\n}\n\n/// @brief Perform the union of two SDD.\n/// @related SDD\ntemplate <typename C>\ninline\nSDD<C>&\noperator+=(SDD<C>& lhs, const SDD<C>& rhs)\n{\n  SDD<C> tmp = dd::sum( global<C>().sdd_context\n                      , dd::sum_builder<C, SDD<C>>(global<C>().sdd_context, {lhs, rhs}));\n  using std::swap;\n  swap(tmp, lhs);\n  return lhs;\n}\n\n/// @brief Perform the union of an iterable container of SDD.\n/// @related SDD\ntemplate <typename C, typename InputIterator>\nSDD<C>\ninline\nsum(InputIterator begin, InputIterator end)\n{\n  dd::sum_builder<C, SDD<C>> builder(global<C>().sdd_context);\n  for (; begin != end; ++begin)\n  {\n    builder.add(*begin);\n  }\n  return dd::sum(global<C>().sdd_context, std::move(builder));\n}\n\n/// @brief Perform the union of an initializer list of SDD.\n/// @related SDD\ntemplate <typename C>\nSDD<C>\ninline\nsum(std::initializer_list<SDD<C>> operands)\n{\n  return sum<C>(std::begin(operands), std::end(operands));\n}\n\n/*------------------------------------------------------------------------------------------------*/\n\n} // namespace sdd\n", "meta": {"hexsha": "0badd5a903081e411f1e0c91de1118dc6cff1ef1", "size": 14371, "ext": "hh", "lang": "C++", "max_stars_repo_path": "sdd/dd/sum.hh", "max_stars_repo_name": "tic-toc/libsdd", "max_stars_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-21T19:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T01:20:28.000Z", "max_issues_repo_path": "sdd/dd/sum.hh", "max_issues_repo_name": "tic-toc/libsdd", "max_issues_repo_head_hexsha": "5c3deb43523d062929f169c3d7a301240f0fb811", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-05T23:39:44.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-05T23:40:04.000Z", "max_forks_repo_path": "libsdd/sdd/dd/sum.hh", "max_forks_repo_name": "kyouko-taiga/SwiftSDD", "max_forks_repo_head_hexsha": "9312160e0fac5fef6e605c9e74c543ded9708e54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-05-13T14:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T20:13:39.000Z", "avg_line_length": 33.6557377049, "max_line_length": 100, "alphanum_fraction": 0.5986361422, "num_tokens": 3305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.02368946957618333, "lm_q1q2_score": 0.010371806462004016}}
{"text": "/*\n * Copyright (c) 2011-2019, 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_OPTIMIZER_FUNCTION_HPP_\n#define DART_OPTIMIZER_FUNCTION_HPP_\n\n#include <functional>\n#include <memory>\n#include <string>\n\n#include <Eigen/Dense>\n\nnamespace dart {\nnamespace optimizer {\n\nclass Function\n{\npublic:\n  /// Constructor\n  explicit Function(const std::string& name = \"function\");\n\n  /// Destructor\n  virtual ~Function();\n\n  /// Sets the name of this Function\n  virtual void setName(const std::string& newName);\n\n  /// Returns the name of this Function\n  const std::string& getName() const;\n\n  /// Evaluates and returns the objective function at the point x\n  virtual double eval(const Eigen::VectorXd& x) const = 0;\n\n  /// Evaluates and returns the objective function at the point x\n  virtual void evalGradient(const Eigen::VectorXd& x,\n                            Eigen::Map<Eigen::VectorXd> grad) const;\n\n  /// Evaluates and return the objective function at the point x.\n  ///\n  /// If you have a raw array that the gradient will be passed in, then use\n  /// evalGradient(const Eigen::VectorXd&, Eigen::Map<Eigen::VectorXd>)\n  /// for better performance.\n  void evalGradient(const Eigen::VectorXd& x, Eigen::VectorXd& grad) const;\n\n  /// Evaluates and return the objective function at the point x\n  virtual void evalHessian(\n      const Eigen::VectorXd& x,\n      Eigen::Map<Eigen::VectorXd, Eigen::RowMajor> Hess) const;\n\nprotected:\n  /// Name of this function\n  std::string mName;\n};\n\nusing FunctionPtr = std::shared_ptr<Function>;\nusing UniqueFunctionPtr = std::unique_ptr<Function>;\n\nusing CostFunction = std::function<double(const Eigen::VectorXd&)>;\n\nusing GradientFunction = std::function<void(\n    const Eigen::VectorXd&, Eigen::Map<Eigen::VectorXd>)>;\n\nusing HessianFunction = std::function<void(\n    const Eigen::VectorXd&,\n    Eigen::Map<Eigen::VectorXd, Eigen::RowMajor>)>;\n\n/// ModularFunction uses C++11 std::function to allow you to easily swap\n/// out the cost function, gradient function, and Hessian function during\n/// runtime for an optimizer::Function instance.\nclass ModularFunction : public Function\n{\npublic:\n  /// Constructor\n  explicit ModularFunction(const std::string& name = \"modular_function\");\n\n  /// Destructor\n  ~ModularFunction() override;\n\n  /// eval() will now call whatever CostFunction you set using\n  /// setCostFunction()\n  double eval(const Eigen::VectorXd& x) const override;\n\n  /// evalGradient() will now call whatever GradientFunction you set\n  /// using setGradientFunction()\n  void evalGradient(const Eigen::VectorXd& x,\n                    Eigen::Map<Eigen::VectorXd> grad) const override;\n\n  /// evalHessian() will now call whatever HessianFunction you set using\n  /// setHessianFunction()\n  void evalHessian(\n      const Eigen::VectorXd& x,\n      Eigen::Map<Eigen::VectorXd, Eigen::RowMajor> Hess) const override;\n\n  /// Set the function that gets called by eval()\n  void setCostFunction(CostFunction cost);\n\n  /// Replace the cost function with a constant-zero function. Passing in\n  /// true will cause a warning to be printed out whenever eval() is called.\n  void clearCostFunction(bool printWarning = true);\n\n  /// Set the function that gets called by evalGradient()\n  void setGradientFunction(GradientFunction gradient);\n\n  /// Replace the gradient function with the default evalGradient() of\n  /// the base Function class. A warning will be printed whenever evalGradient()\n  /// gets called.\n  void clearGradientFunction();\n\n  /// Set the function that gets called by evalHessian()\n  void setHessianFunction(HessianFunction hessian);\n\n  /// Replace the Hessian function with the default evalHessian() of the\n  /// base Function class. A warning will be printed whenever evalHessian() gets\n  /// called.\n  void clearHessianFunction();\n\nprotected:\n  /// Storage for the cost function\n  CostFunction mCostFunction;\n\n  /// Storage for the gradient function\n  GradientFunction mGradientFunction;\n\n  /// Storage for the Hessian function\n  HessianFunction mHessianFunction;\n};\n\n/// NullFunction is a constant-zero Function\nclass NullFunction : public Function\n{\npublic:\n  /// Constructor\n  explicit NullFunction(const std::string& name = \"null_function\");\n\n  /// Destructor\n  ~NullFunction() override;\n\n  /// eval() will always return exactly zero\n  double eval(const Eigen::VectorXd&) const override;\n\n  /// evalGradient will always set grad to a zero vector that\n  /// matches the dimensionality of _x\n  void evalGradient(const Eigen::VectorXd& x,\n                    Eigen::Map<Eigen::VectorXd> grad) const override;\n\n  /// evalHessian() will always set Hess to a zero matrix that matches\n  /// the dimensionality of _x\n  void evalHessian(\n      const Eigen::VectorXd& _x,\n      Eigen::Map<Eigen::VectorXd, Eigen::RowMajor> Hess) const override;\n};\n\nclass MultiFunction\n{\npublic:\n  /// Constructor\n  MultiFunction();\n\n  /// Destructor\n  virtual ~MultiFunction();\n\n  /// Operator ()\n  virtual void operator()(const Eigen::VectorXd& x,\n                          Eigen::Map<Eigen::VectorXd>& f,\n                          Eigen::Map<Eigen::MatrixXd>& grad) = 0;\n};\n\n}  // namespace optimizer\n}  // namespace dart\n\n#endif  // DART_OPTIMIZER_FUNCTION_HPP_\n\n", "meta": {"hexsha": "143425de8f67c32ceca0f98ef52c29ed349e7c3a", "size": 6741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/optimizer/Function.hpp", "max_stars_repo_name": "vslavik/dart", "max_stars_repo_head_hexsha": "bab2f04300fc607bd52c396d6735ef0d3448cd5c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-14T09:37:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-14T09:37:25.000Z", "max_issues_repo_path": "dart/optimizer/Function.hpp", "max_issues_repo_name": "vslavik/dart", "max_issues_repo_head_hexsha": "bab2f04300fc607bd52c396d6735ef0d3448cd5c", "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/optimizer/Function.hpp", "max_forks_repo_name": "vslavik/dart", "max_forks_repo_head_hexsha": "bab2f04300fc607bd52c396d6735ef0d3448cd5c", "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.3712871287, "max_line_length": 80, "alphanum_fraction": 0.7178460169, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625615, "lm_q2_score": 0.027169232421851548, "lm_q1q2_score": 0.010357442999370775}}
{"text": "// Copyright (c) 2014, Paul Furgale, Jérôme Maye and Jörn Rehder, Autonomous Systems Lab, ETH Zurich, Switzerland\n// Copyright (c) 2014, Thomas Schneider, Skybotix AG, Switzerland\n// Copyright (c) 2016, Luc Oth\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice, this list of\n// conditions and the following disclaimer.\n//\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//\n// * All advertising materials mentioning features or use of this software must display the\n// following acknowledgement: This product includes software developed by the\n// Autonomous Systems Lab and Skybotix AG.\n//\n// * Neither the name of the Autonomous Systems Lab and Skybotix AG 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 AUTONOMOUS SYSTEMS LAB AND SKYBOTIX AG ''AS IS'' AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// the AUTONOMOUS SYSTEMS LAB OR SKYBOTIX AG BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT\n// 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,\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// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye\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 ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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// Derived from https://github.com/ethz-asl/kalibr/ (2016)\n//\n// Changes wrt. original:\n//  _ remove dependency on Schweizer-Messer toolbox\n//  _ remove dependency on sparse_block_matrix (drop support for sparse\n//    initialization)\n//\n// WARNING: Do NOT use as-is in production code.\n// @todo The code itself was initially designed purely for research and before\n//       actually using it in production code, we should properly verify its\n//       capabilities. One major part is the efficiency which isn't perfect at\n//       all (pure Eigen::Dynamic implementations, a bunch of duplicate\n//       evaluations for readability and some debuggng stuff)\n\n#pragma once\n\n#include <vector>\n#include <Eigen/Core>\n#include <ze/common/logging.hpp>\n#include <ze/common/types.hpp>\n\nnamespace ze_splines {\n\n// Define a generic expression of a matrix where all coefficients\n// are defined by a functor.\n// A BiVector is a vector that holds the values of cumulative basis functions\n// and extends the definition to the outside of its definition:\n// if before the segment where it is defined: 0\n// after the segment: fixed to end_value\nclass BiVector;\n}  // namespace ze_splines\n\nnamespace Eigen {\nnamespace internal {\ntemplate<>\n\nstruct functor_traits<ze_splines::BiVector>\n{\n  enum { Cost = 1, PacketAccess = false, IsRepeatable = true };\n};\n}  // namespace internal\n}  // namespace Eigen\n\nnamespace ze_splines {\n\nclass BiVector {\n  enum { Cost = 1, PacketAccess = false, IsRepeatable = true };\nprivate:\n  const int startIndex_;\n  const ze::real_t endValue_;\n  const ze::VectorX localBi_;\n\npublic:\n  BiVector(int startIndex, const ze::VectorX& localBi, ze::real_t endValue)\n    : startIndex_(startIndex)\n    , endValue_(endValue)\n    , localBi_(localBi)\n  {};\n\n  ze::real_t operator() (int i, int j = 0) const {\n    i -= startIndex_;\n    if(i < 0)\n    {\n      return endValue_;\n    }\n    if(i >= (localBi_.rows()))\n    {\n      return 0;\n    }\n    return  i >= 0 ? localBi_(i): 0;\n  }\n};\n\n} // namespace ze_splines\n\nnamespace ze {\n\n/**\n * @class BSpline\n *\n * A class to facilitate state estimation for vechicles in 3D space using B-Splines\n *\n */\nclass BSpline\n{\npublic:\n\n  /**\n   * Create a spline of the specified order. The resulting B-spline will\n   * be a series of piecewise polynomials of degree splineOrder - 1.\n   *\n   * @param splineOrder The order of the spline.\n   */\n  BSpline(int spline_order);\n\n  /**\n   * A destructor.\n   *\n   */\n  ~BSpline();\n\n  /**\n   *\n   * @return The order of the spline\n   */\n  int spline_order() const;\n\n  /**\n   *\n   * @return The degree of polynomial used by the spline.\n   */\n  int polynomialDegree() const;\n\n  /**\n   *\n   * @return the minimum number of knots required to have at least one valid\n   * time segment.\n   */\n  int minimumKnotsRequired() const;\n\n  /**\n   *\n   * @return the dimension of the bspline (only valid after initialization)\n   */\n  int dimension() const;\n\n  /**\n   * @param numTimeSegments the number of time segments required\n   * @return the number of coefficients required for a specified number of\n   * valid time segments.\n   */\n  int numCoefficientsRequired(int num_time_segments) const;\n\n  /**\n   * @param numTimeSegments the number of time segments required\n   * @return the number of knots required for a specified number of valid\n   * time segments.\n   */\n  int numKnotsRequired(int num_time_segments) const;\n\n  /**\n   *\n   * @param numKnots the number of knots.\n   * @return the number of valid time segments for a given number of knots.\n   */\n  int numValidTimeSegments(int num_knots) const;\n\n  /**\n   *\n   * @return the number of valid time segments for a given for the current\n   * knot sequence.\n   */\n  int numValidTimeSegments() const;\n\n  /**\n   * Return the basis matrix active on the \\f$i^{\\textup{th}}\\f$ time segment.\n   *\n   * @param i The index of the time segment.\n   *\n   * @return The basis matrix active on the time segment.\n   */\n  const MatrixX& basisMatrix(int i) const;\n\n  /**\n   *\n   * @return the time interval that the spline is well-defined on\n   * [t_min(), t_max()]\n   */\n  std::pair<real_t, real_t> timeInterval() const;\n\n  /**\n   * Return the time interval of a single spline segment.\n   *\n   * @param i The index of the time segment\n   *\n   * @return the time interval of the ith spline segment.\n   */\n  std::pair<real_t, real_t> timeInterval(int i) const;\n\n  /**\n   * Set the knots and coefficients of the spline. Each column of the\n   * coefficient matrix\n   * is interpreted as a single, vector-valued spline coefficient.\n   *\n   * @param knots        A non-decreasing knot sequence.\n   * @param coefficients A set of spline coefficients.\n   */\n  void setKnotsAndCoefficients(const std::vector<real_t>& knots,\n                               const MatrixX& coefficients);\n\n  /**\n   * Set the knots and coefficients of the spline. Each column of the\n   * coefficient matrix is interpreted as a single, vector-valued spline\n   * coefficient.\n   *\n   * @param knots        A non-decreasing knot sequence.\n   * @param coefficients A set of spline coefficients.\n   */\n  void setKnotVectorAndCoefficients(const VectorX& knots,\n                                    const MatrixX& coefficients);\n\n  /**\n   * Sets the coefficient matrix from the stacked vector of coefficients.\n   *\n   * @param coefficients The stacked vector of coefficients.\n   */\n  void setCoefficientVector(const VectorX& coefficients);\n\n  /**\n   *\n   * @return The stacked vector of coefficients.\n   */\n  VectorX coefficientVector();\n\n  /**\n   * Sets the matrix of coefficients.\n   *\n   * @param coefficients\n   */\n  void setCoefficientMatrix(const MatrixX& coefficients);\n\n  /**\n   * @return the current knot vector.\n   */\n  const std::vector<real_t> knots() const;\n\n  /**\n   * @return the current knot vector.\n   */\n  VectorX knotVector() const;\n\n  /**\n   * @return the current spline coefficient matrix. Each column of\n   * the coefficient matrix is interpreted as a single, vector-valued\n   * spline coefficient.\n   */\n  const MatrixX& coefficients() const;\n\n  /**\n   *\n   * @return The number of total coefficients the spline currently uses\n   */\n  int numCoefficients() const;\n\n  /**\n   * This is equivalent to spline.coefficients().cols()\n   *\n   * @return The number of vector-valued coefficient columns the spline\n   * currently uses\n   */\n  int numVvCoefficients() const;\n\n  /**\n   *\n   * @return The minimum time that the spline is well-defined on.\n   */\n  real_t t_min() const;\n\n  /**\n   *\n   * @return The maximum time that the spline is well-defined on. Because B-splines\n   *         are defined on half-open intervals, the spline curve is well defined up\n   *         to but not including this time.\n   */\n  real_t t_max() const;\n\n  /**\n   * Evaluate the spline curve at the time t.\n   *\n   * @param t The time to evaluate the spline curve\n   *\n   * @return The value of the spline curve at the time t.\n   */\n  VectorX eval(real_t t) const;\n\n  /**\n   * Evaluate the derivative of the spline curve at time t.\n   *\n   * @param t The time to evaluate the spline derivative.\n   * @param derivativeOrder The order of the derivative. This must be >= 0\n   *\n   * @return The value of the derivative of the spline curve evaluated at t.\n   */\n  VectorX evalD(real_t t, int derivative_order) const;\n\n  /**\n   * Evaluate the derivative of the spline curve at time t and retrieve the Jacobian\n   * of the value with respect to small changes in the paramter vector. The Jacobian\n   * only refers to the local parameter vector. The indices of the local parameters with\n   * respect to the full paramter vector can be retrieved using localCoefficientVectorIndices().\n   *\n   * @param t The time to evaluate the spline derivative.\n   * @param derivativeOrder The order of the derivative. This must be >= 0\n   *\n   * @return The value of the derivative of the spline curve evaluated at t and the Jacobian.\n   */\n  std::pair<VectorX, MatrixX> evalDAndJacobian(real_t t,\n                                               int derivative_order) const;\n\n  /**\n   * Evaluate the derivative of the spline curve at time t and retrieve the Jacobian\n   * of the value with respect to small changes in the paramter vector. The Jacobian\n   * only refers to the local parameter vector.\n   *\n   * @param t The time to evaluate the spline derivative.\n   * @param derivativeOrder The order of the derivative. This must be >= 0\n   * @param a pointer to the Jacobian matrix to fill in\n   * @param a pointer to an int vector that will be filled with the local coefficient indices\n   *\n   * @return The value of the derivative of the spline curve evaluated at t.\n   */\n  VectorX evalDAndJacobian(real_t t,\n                           int derivative_order,\n                           MatrixX * Jacobian,\n                           VectorXi * coefficient_indices) const;\n\n   /**\n   * Get the local basis matrix evaluated at the time \\f$ t \\f$.\n   * For vector-valued spline coefficients of dimension \\f$ D \\f$\n   * and a B-spline of order $S$, this matrix will be \\f$ D \\times SD \\f$\n   *\n   * @param t The time to evaluate the local basis matrix.\n   * @param derivativeOrder The derivative order to return (0 is no derivative)\n   *\n   * @return The local basis matrix evaluated at time \\f$ t \\f$\n   */\n  MatrixX Phi(real_t t, int derivative_order = 0) const;\n\n  /**\n   * Get the local basis matrix evaluated at the time \\f$ t \\f$.\n   * For vector-valued spline coefficients of dimension \\f$ D \\f$\n   * and a B-spline of order $S$, this matrix will be \\f$ D \\times SD \\f$\n   *\n   * @param t The time to evaluate the local basis matrix.\n   * @param derivativeOrder The derivative order to return (0 is no derivative)\n   *\n   * @return The local basis matrix evaluated at time \\f$ t \\f$\n   */\n  MatrixX localBasisMatrix(real_t t, int derivative_order = 0) const;\n\n  /**\n   * Get the local coefficient matrix evaluated at the time \\f$ t \\f$.\n   * For vector-valued spline coefficients of dimension \\f$ D \\f$\n   * and a B-spline of order $S$, this matrix will be \\f$ D \\times S \\f$.\n   * Each column of the resulting matrix corresponds to a single vector-valued\n   * coefficient.\n   *\n   * @param t The time being queried\n   *\n   * @return The local coefficient matrix active at time \\f$ t \\f$\n   */\n  MatrixX localCoefficientMatrix(real_t t) const;\n\n  /**\n   * Return a map to a single coefficient column.\n   * This allows the user to pass around what is essentially a pointer\n   * to a single column in the coefficient matrix.\n   *\n   * @param i The column of the coefficient matrix to return. \\f$ 0 \\le i < \\f$ coefficients().cols()\n   *\n   * @return A map to column i of the coefficient matrix.\n   */\n  Eigen::Map<VectorX> vvCoefficientVector(int i);\n\n  /**\n   * Return a map to a single coefficient column.\n   * This allows the user to pass around what is essentially a pointer\n   * to a single column in the coefficient matrix.\n   *\n   * @param i The column of the coefficient matrix to return. \\f$ 0 \\le i < \\f$ coefficients().cols()\n   *\n   * @return A map to column i of the coefficient matrix.\n   */\n  Eigen::Map<const VectorX> vvCoefficientVector(int i) const;\n\n  /**\n   * Return a map to a single coefficient column.\n   * This allows the user to pass around what is essentially a pointer\n   * to a single column in the coefficient matrix.\n   *\n   * @param i The column of the coefficient matrix to return. \\f$ 0 \\le i < \\f$ coefficients().cols()\n   *\n   * @return A map to column i of the coefficient matrix.\n   */\n  template<int D>\n  Eigen::Map<Eigen::Matrix<real_t, D, 1> > fixedSizeVvCoefficientVector(int i)\n  {\n    CHECK_EQ(D,coefficients_.rows())\n        << \"Size mismatch between requested vector size and actual vector size\";\n    CHECK_LE(0, coefficients_.cols()) << \"Index out of range\";\n    CHECK_LE(i, coefficients_.cols()) << \"Index out of range\";\n\n    return Eigen::Map<Eigen::Matrix<real_t, D, 1> >(&coefficients_(0,i),coefficients_.rows());\n  }\n\n  /**\n   * Return a map to a single coefficient column.\n   * This allows the user to pass around what is essentially a pointer\n   * to a single column in the coefficient matrix.\n   *\n   * @param i The column of the coefficient matrix to return. \\f$ 0 \\le i < \\f$ coefficients().cols()\n   *\n   * @return A map to column i of the coefficient matrix.\n   */\n  template<int D>\n  Eigen::Map<const Eigen::Matrix<real_t, D, 1> > fixedSizeVvCoefficientVector(int i) const\n  {\n    CHECK_EQ(D,coefficients_.rows())\n        << \"Size mismatch between requested vector size and actual vector size\";\n    CHECK_LE(0, coefficients_.cols()) << \"Index out of range\";\n    CHECK_LE(i, coefficients_.cols()) << \"Index out of range\";\n\n    return Eigen::Map< const Eigen::Matrix<real_t, D, 1> >(\n          &coefficients_(0,i), coefficients_.rows());\n  }\n\n  /**\n   * Get the local coefficient vector evaluated at the time \\f$ t \\f$.\n   * For vector-valued spline coefficients of dimension \\f$ D \\f$\n   * and a B-spline of order $S$, this vector will be \\f$ SD \\times 1 \\f$\n   * Evaluating the B-spline at time t, eval(t,O) is equivalent to evaluating\n   * Phi(t,O) * localCoefficientVector(t)\n   *\n   * @param t The time being queried\n   *\n   * @return The local coefficient vector active at time \\f$ t \\f$\n   */\n  VectorX localCoefficientVector(real_t t) const;\n\n  /**\n   * Update the local coefficient vector\n   *\n   * @param t The time used to select the local coefficients.\n   * @param c The local coefficient vector.\n   */\n  void setLocalCoefficientVector(real_t t, const VectorX& c);\n\n  /**\n   * Get the indices of the local coefficients active at time t.\n   *\n   * @param t The time being queried.\n   *\n   * @return The indices of the local coefficients active at time t.\n   */\n  VectorXi localCoefficientVectorIndices(real_t t) const;\n\n  /**\n   * Get the indices of the local vector-valued coefficients active at time t.\n   *\n   * @param t The time being queried.\n   *\n   * @return The indices of the local vector-valued coefficients active at time t.\n   */\n  VectorXi localVvCoefficientVectorIndices(real_t t) const;\n\n  int coefficientVectorLength() const;\n\n  /**\n   * Initialize a spline from two times and two positions. The spline will be initialized to\n   * have one valid time segment \\f$[t_0, t_1)\\f$ such that \\f$\\mathbf b(t_0) = \\mathbf p_0\\f$,\n   * \\f$\\mathbf b(t_1) = \\mathbf p_1\\f$,\n   * \\f$\\dot{\\mathbf b}(t_0) = \\frac{\\mathbf{p_1} - \\mathbf p_0}{t_1 - t_0}\\f$, and\n   * \\f$\\dot{\\mathbf b}(t_1) = \\frac{\\mathbf{p_1} - \\mathbf p_0}{t_1 - t_0}\\f$.\n   *\n   * @param t_0 The start of the time interval.\n   * @param t_1 The end of the time interval\n   * @param p_0 The position at the start of the time interval.\n   * @param p_1 The position at the end of the time interval.\n   */\n  void initSpline(real_t t_0,\n                  real_t t_1,\n                  const VectorX& p_0,\n                  const VectorX& p_1);\n\n  //! Spline initialization version 2.\n  void initSpline2(const VectorX& times,\n                   const MatrixX& interpolation_points,\n                   int num_segments,\n                   real_t lambda);\n\n  //! Spline initialization version 3.\n  void initSpline3(const VectorX& times,\n                   const MatrixX& interpolation_points,\n                   int num_segments,\n                   real_t lambda);\n\n  /**\n   * Add a curve segment that interpolates the point p, ending at time t.\n   *\n   * If the new time corresponds with the first knot past the end of the curve,\n   * the existing curve is perfectly preserved. Otherwise, the existing curve\n   * will interpolate its current position at the current endpoint and the new\n   * position at the new endpoint but will not necessarily match the last segment\n   * exactly.\n   *\n   * @param t The time of the point to interpolate. This must be greater than t_max()\n   * @param p The point to interpolate at time t.\n   */\n  void addCurveSegment(real_t t, const VectorX& p);\n\n  /**\n   * Add a curve segment that interpolates the point p, ending at time t.\n   *\n   * If the new time corresponds with the first knot past the end of the curve,\n   * the existing curve is perfectly preserved. Otherwise, the existing curve\n   * will interpolate its current position at the current endpoint and the new\n   * position at the new endpoint but will not necessarily match the last segment\n   * exactly.\n   *\n   * @param t The time of the point to interpolate. This must be greater than t_max()\n   * @param p The point to interpolate at time t.\n   * @param lambda a smoothness parameter. Higher for more smooth.\n   */\n  void addCurveSegment2(real_t t, const VectorX& p, real_t lambda);\n\n  /**\n   * Removes a curve segment from the left by removing one knot and one coefficient vector.\n   * After calling this function, the curve will have one fewer segment. The new minimum\n   * time will be timeInterval(0).first\n   *\n   */\n  void removeCurveSegment();\n\n  /**\n   * Get the \\f$ \\mathbf V_i \\f$ matrix associated with the integral over the segment.\n   *\n   * @param segmentIndex\n   *\n   * @return the \\f$ \\mathbf V_i \\f$ matrix\n   */\n  MatrixX Vi(int segmentIndex) const;\n\n  VectorX evalIntegral(real_t t1, real_t t2) const;\n  inline VectorX evalI(real_t t1, real_t t2) const\n  {\n    return evalIntegral(t1, t2);\n  }\n\n  MatrixX Mi(int segment_index) const;\n  MatrixX Bij(int segment_index, int column_index) const;\n  MatrixX U(real_t t, int derivative_order) const;\n  VectorX u(real_t t, int derivative_order) const;\n  int segmentIndex(real_t t) const;\n  MatrixX Dii(int segment_index) const;\n  MatrixX Di(int segment_index) const;\n\n  /**\n   * Get the b_i(t) for i in localVvCoefficientVectorIndices\n   * (@see #localVvCoefficientVectorIndices).\n   *\n   * @param t The time being queried.\n   *\n   * @return [b_i(t) for i in localVvCoefficientVectorIndices].\n   *\n   */\n  VectorX getLocalBiVector(real_t t, int derivative_order = 0) const;\n  void getLocalBiInto(real_t t, VectorX& ret, int derivative_order = 0) const;\n\n  /**\n   * Get the cumulative (tilde) b_i(t) for i in localVvCoefficientVectorIndices\n   * (@see #localVvCoefficientVectorIndices).\n   *\n   * @param t The time being queried.\n   *\n   * @return [tilde b_i(t) for i in localVvCoefficientVectorIndices].\n   *\n   */\n  VectorX getLocalCumulativeBiVector(real_t t, int derivative_order = 0) const;\n\n  Eigen::CwiseNullaryOp<ze_splines::BiVector, VectorX>\n  getBiVector(real_t t) const\n  {\n    return Eigen::CwiseNullaryOp<ze_splines::BiVector, VectorX>(\n          numValidTimeSegments(), 1,\n          ze_splines::BiVector(segmentIndex(t), getLocalBiVector(t), 0));\n  }\n  Eigen::CwiseNullaryOp<ze_splines::BiVector, VectorX>\n  getCumulativeBiVector(real_t t) const\n  {\n    return Eigen::CwiseNullaryOp<ze_splines::BiVector, VectorX>(\n          numValidTimeSegments(), 1,\n          ze_splines::BiVector(segmentIndex(t),getLocalCumulativeBiVector(t), 1));\n  }\n\n  MatrixX segmentQuadraticIntegral(const MatrixX& W,\n                                   int segment_index,\n                                   int derivative_order) const;\n  MatrixX segmentQuadraticIntegralDiag(const VectorX& Wdiag,\n                                       int segment_index,\n                                       int derivative_order) const;\n  MatrixX curveQuadraticIntegral(const MatrixX& W,int derivative_order) const;\n  MatrixX curveQuadraticIntegralDiag(const VectorX& Wdiag, int derivative_order) const;\n\n  void initConstantSpline(real_t t_min, real_t t_max,\n                          int num_segments, const VectorX& constant);\n\nprotected:\n  /**\n   * An internal function to find the segment of the knot sequence\n   * that the time t falls in. The function returns the\n   * value \\f$ u = \\frac{t - t_i}{t_{i+1} - t_i} \\f$ and the index \\f$i\\f$\n   *\n   * @param t The time being queried.\n   *\n   * @return A pair with the first value \\f$ u = \\frac{t - t_i}{t_{i+1} - t_i} \\f$\n   * and the second value the index \\f$i\\f$\n   */\n  std::pair<real_t,int> computeUAndTIndex(real_t t) const;\n\n  /**\n   * An internal function to find the segment of the knot sequence\n   * that the time t falls in. The function returns the width of the\n   * knot segment \\f$ \\Delta t_i = t_{i+1} - t_i \\f$ and the index \\f$i\\f$\n   *\n   * @param t The time being queried.\n   *\n   * @return A pair with the first value \\f$ \\Delta t_i = t_{i+1} - t_i \\f$\n   * and the second value the index \\f$i\\f$\n   */\n  std::pair<real_t,int> computeTIndex(real_t t) const;\n\n  /**\n   * Compute the vector \\f$ \\mathbf u(t) \\f$ for a spline of\n   * order \\f$ S \\f$, this is an \\f$ S \\times 1 \\f$ vector.\n   *\n   * At derivative order 0 (no derivative), this vector is\n   * \\f$ \\mathbf u(t) = \\left [ 1 \\; u(t) \\; u(t)^2 \\; \\dots \\; u(t)^{S-1} \\right ]^T \\f$\n   *\n   * For higher derivative order \\f$ M \\f$, the vector returned is\n   * \\f$ \\mathbf u^{(M)}(t) = \\frac{\\partial^{(M)}\\mathbf u(t)}{\\partial t^{(M)}}\n   *\n   * @param uval the value \\f$ u(t) \\f$\n   * @param segmentIndex\n   * @param derivativeOrder\n   *\n   * @return\n   */\n  VectorX computeU(real_t uval, int segment_index, int derivative_order) const;\n\n  int basisMatrixIndexFromStartingKnotIndex(int starting_knot_index) const;\n  int startingKnotIndexFromBasisMatrixIndex(int basis_matrix_index) const;\n  const MatrixX& basisMatrixFromKnotIndex(int knot_index) const;\n\n  /**\n   * Throws an exception if the knot sequence is not non-decreasing.\n   *\n   * @param knots The knot sequence to verify.\n   */\n  void verifyKnotSequence(const std::vector<real_t>& knots);\n\n  /**\n   * Initialize the basis matrices based on the current knot sequence.\n   * There is one basis matrix for each valid time segment defined by the spline.\n   *\n   * Implemented using the recursive basis matrix algorithm from\n   * Qin, Kaihuai, General matrix representations for B-splines,\n   * The Visual Computer (2000) 16:177–186\n   *\n   */\n  void initializeBasisMatrices();\n\n  /**\n   * The recursive function used to implement the recursive basis matrix algorithm from\n   * Qin, Kaihuai, General matrix representations for B-splines,\n   * The Visual Computer (2000) 16:177–186\n   *\n   * @param k The order of the matrix requested.\n   * @param i The time segment of the basis matrix\n   *\n   * @return\n   */\n  MatrixX M(int k, int i);\n\n  /**\n   * A helper function for producing the M matrices. Defined in\n   * Qin, Kaihuai, General matrix representations for B-splines,\n   * The Visual Computer (2000) 16:177–186\n   *\n   */\n  real_t d_0(int k, int i, int j);\n\n  /**\n   * A helper function for producing the M matrices. Defined in\n   * Qin, Kaihuai, General matrix representations for B-splines,\n   * The Visual Computer (2000) 16:177–186\n   *\n   */\n  real_t d_1(int k, int i, int j);\n\n  /// The order of the spline.\n  int spline_order_;\n\n  /// The knot sequence used by the B-spline.\n  std::vector<real_t> knots_;\n\n  /// The coefficient matrix used by the B-Spline. Each column can be seen as a\n  /// single vector-valued spline coefficient.\n  /// This is stored explicityl in column major order to ensure that each column (i.e.\n  /// a single vector-valued spline coefficient) is stored in contiguous memory. This\n  /// allows one to, for example, map a single spline coefficient using the Eigen::Map type.\n  Eigen::Matrix<real_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> coefficients_;\n\n  /// The basis matrices for each time segment the B-spline is defined over.\n  std::vector<MatrixX> basis_matrices_;\n};\n} // namespace ze\n", "meta": {"hexsha": "b63ea341d51fabeece33bfd5d24ab4427ee37bb6", "size": 26944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ze_splines/include/ze/splines/bspline.hpp", "max_stars_repo_name": "rockenbf/ze_oss", "max_stars_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-09-27T07:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T20:44:28.000Z", "max_issues_repo_path": "ze_splines/include/ze/splines/bspline.hpp", "max_issues_repo_name": "rockenbf/ze_oss", "max_issues_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-18T15:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-21T03:10:06.000Z", "max_forks_repo_path": "ze_splines/include/ze/splines/bspline.hpp", "max_forks_repo_name": "rockenbf/ze_oss", "max_forks_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-11-05T07:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T02:26:08.000Z", "avg_line_length": 35.2209150327, "max_line_length": 113, "alphanum_fraction": 0.6826009501, "num_tokens": 6816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.02517884206634889, "lm_q1q2_score": 0.01035129564815617}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n\n/****************************************************************************/\n\n/* Paso: Pattern */\n\n/****************************************************************************/\n\n/* Author: Lutz Gross, l.gross@uq.edu.au */\n\n/****************************************************************************/\n\n#include \"Pattern.h\"\n#include \"PasoException.h\"\n#include \"PasoUtil.h\"\n\n#include <boost/scoped_array.hpp>\n\nusing escript::IndexList;\n\nnamespace paso {\n\nPattern::Pattern(int ntype, dim_t numOut, dim_t numIn, index_t* inPtr,\n                 index_t* idx) :\n    type(ntype),\n    numOutput(numOut),\n    numInput(numIn),\n    len(0),\n    ptr(inPtr),\n    index(idx),\n    main_iptr(NULL),\n    numColors(-1),\n    coloring(NULL),\n    hb_row(NULL),\n    hb_col(NULL)\n{\n    const index_t index_offset = (ntype & MATRIX_FORMAT_OFFSET1 ? 1:0);\n    index_t min_index = index_offset, max_index = index_offset-1;\n\n    if (inPtr!=NULL && idx != NULL) {\n#pragma omp parallel\n      {\n        index_t loc_min_index=index_offset;\n        index_t loc_max_index=index_offset-1;\n        if (ntype & MATRIX_FORMAT_OFFSET1) {\n#pragma omp for schedule(static)\n            for (dim_t i=0; i < numOut; ++i) {\n                if (inPtr[i] < inPtr[i+1]) {\n                    qsort(&(idx[inPtr[i]-1]),(size_t)(inPtr[i+1]-inPtr[i]),sizeof(index_t), util::comparIndex);\n                    loc_min_index = std::min(loc_min_index, idx[inPtr[i]-1]);\n                    loc_max_index = std::max(loc_max_index, idx[inPtr[i+1]-2]);\n                }\n            }\n        } else {\n#pragma omp for schedule(static)\n            for (dim_t i=0; i < numOut; ++i) {\n                if (inPtr[i] < inPtr[i+1]) {\n                    qsort(&(idx[inPtr[i]]),(size_t)(inPtr[i+1]-inPtr[i]),sizeof(index_t), util::comparIndex);\n                    loc_min_index = std::min(loc_min_index, idx[inPtr[i]]);\n                    loc_max_index = std::max(loc_max_index, idx[inPtr[i+1]-1]);\n                }\n            }\n        }\n        #pragma omp critical\n        {\n            min_index=std::min(loc_min_index, min_index);\n            max_index=std::max(loc_max_index, max_index);\n        }\n      } // parallel section\n\n      if (min_index < index_offset || max_index >= numIn+index_offset) {\n          throw PasoException(\"Pattern: Pattern index out of range.\");\n      }\n      len = ptr[numOutput] - index_offset;\n    }\n}\n\n/* deallocates a Pattern */\nPattern::~Pattern()\n{\n    delete[] ptr;\n    delete[] index;\n    delete[] main_iptr;\n    delete[] coloring;\n    delete[] hb_row;\n    delete[] hb_col;\n}\n\n/* creates a pattern from a range of indices */\nPattern_ptr Pattern::fromIndexListArray(dim_t n0, dim_t n,\n                                        const IndexList* index_list_array,\n                                        index_t range_min, index_t range_max,\n                                        index_t index_offset)\n{\n    dim_t* ptr = new index_t[n+1-n0];\n\n    // get the number of connections per row\n#pragma omp parallel for schedule(static)\n    for (dim_t i=n0; i < n; ++i) {\n        ptr[i-n0]=index_list_array[i].count(range_min, range_max);\n    }\n    // accumulate ptr\n    dim_t s=0;\n    for (dim_t i=n0; i < n; ++i) {\n        const dim_t itmp=ptr[i-n0];\n        ptr[i-n0]=s;\n        s+=itmp;\n    }\n    ptr[n-n0]=s;\n\n    // fill index\n    index_t* index = new index_t[ptr[n-n0]];\n#pragma omp parallel for schedule(static)\n    for (dim_t i=n0; i < n; ++i) {\n        index_list_array[i].toArray(&index[ptr[i-n0]], range_min, range_max,\n                                    index_offset);\n    }\n    Pattern_ptr out(new Pattern(MATRIX_FORMAT_DEFAULT, n-n0,\n                                range_max+index_offset, ptr, index));\n\n    return out;\n}\n\nindex_t* Pattern::borrowMainDiagonalPointer()\n{\n    if (main_iptr == NULL) {\n        const dim_t n = numOutput;\n        main_iptr=new index_t[n];\n        bool fail = false;\n        // identify the main diagonals\n#pragma omp parallel for schedule(static)\n        for (index_t i = 0; i < n; ++i) {\n            index_t* idx = &index[ptr[i]];\n            index_t* where_p=reinterpret_cast<index_t*>(bsearch(&i, idx,\n                        (size_t)(ptr[i+1] - ptr[i]),\n                        sizeof(index_t), util::comparIndex));\n            if (where_p == NULL) {\n                fail = true;\n            } else {\n                main_iptr[i] = ptr[i]+(index_t)(where_p-idx);\n            }\n        }\n        if (fail) {\n            delete[] main_iptr;\n            main_iptr = NULL;\n        }\n    }\n    return main_iptr;\n}\n\nindex_t* Pattern::borrowColoringPointer()\n{\n    // is coloring available?\n    if (coloring == NULL) {\n        coloring = new index_t[numInput];\n        index_t out = 0;\n        const dim_t n = numOutput;\n        index_t* mis_marker = new index_t[n];\n        // get coloring\n#pragma omp parallel for schedule(static)\n        for (index_t i = 0; i < n; i++) {\n            coloring[i] = -1;\n            mis_marker[i] = -1;\n        }\n\n        while (util::isAny(n, coloring, -1)) {\n            mis(mis_marker);\n\n#pragma omp parallel for schedule(static)\n            for (index_t i = 0; i < n; ++i) {\n                if (mis_marker[i])\n                    coloring[i] = out;\n                mis_marker[i] = coloring[i];\n            }\n            ++out;\n        }\n        delete[] mis_marker;\n        numColors = out;\n    }\n    return coloring;\n}\n\n// creates a subpattern\nPattern_ptr Pattern::getSubpattern(dim_t newNumRows, dim_t newNumCols,\n                                   const index_t* row_list,\n                                   const index_t* new_col_index) const\n{\n    const index_t index_offset=(type & MATRIX_FORMAT_OFFSET1 ? 1:0);\n\n    index_t* newPtr = new index_t[newNumRows+1];\n#pragma omp parallel\n    {\n#pragma omp for schedule(static)\n        for (dim_t i=0; i < newNumRows+1; ++i) newPtr[i]=0;\n\n        // find the number of column entries in each row\n#pragma omp for schedule(static)\n        for (dim_t i=0; i < newNumRows; ++i) {\n            index_t j=0;\n            const index_t subpattern_row=row_list[i];\n            #pragma ivdep\n            for (index_t k=ptr[subpattern_row]-index_offset;\n                         k < ptr[subpattern_row+1]-index_offset; ++k) {\n                if (new_col_index[index[k]-index_offset] > -1)\n                    j++;\n            }\n            newPtr[i]=j;\n        }\n    } // parallel section\n\n    // accumulate ptr\n    newPtr[newNumRows]=util::cumsum(newNumRows, newPtr);\n    index_t* newIndex = new index_t[newPtr[newNumRows]];\n\n    // find the number of column entries in each row\n#pragma omp parallel for schedule(static)\n    for (dim_t i=0; i < newNumRows; ++i) {\n        index_t j=newPtr[i];\n        const index_t subpattern_row=row_list[i];\n        #pragma ivdep\n        for (index_t k=ptr[subpattern_row]-index_offset; k < ptr[subpattern_row+1]-index_offset; ++k) {\n            const index_t tmp=new_col_index[index[k]-index_offset];\n            if (tmp > -1) {\n                newIndex[j]=tmp;\n                ++j;\n            }\n        }\n    }\n    // create return value\n    Pattern_ptr out(new Pattern(type, newNumRows, newNumCols, newPtr, newIndex));\n    return out;\n}\n\nPattern_ptr Pattern::unrollBlocks(int newType, dim_t output_block_size,\n                                  dim_t input_block_size)\n{\n    Pattern_ptr out;\n    const index_t index_offset_in=(type & MATRIX_FORMAT_OFFSET1 ? 1:0);\n    const index_t index_offset_out=(newType & MATRIX_FORMAT_OFFSET1 ? 1:0);\n\n    if (output_block_size == 1 && input_block_size == 1 &&\n          (type & MATRIX_FORMAT_OFFSET1) == (newType & MATRIX_FORMAT_OFFSET1)) {\n        out = shared_from_this();\n    } else {\n        const dim_t block_size = output_block_size*input_block_size;\n        const dim_t new_len = len * block_size;\n        const dim_t new_numOutput = numOutput * output_block_size;\n        const dim_t new_numInput = numInput * input_block_size;\n\n        index_t* newPtr = new index_t[new_numOutput+1];\n        index_t* newIndex = new index_t[new_len];\n        #pragma omp parallel\n        {\n            #pragma omp for schedule(static)\n            for (dim_t i=0; i < new_numOutput+1; ++i)\n                newPtr[i]=index_offset_out;\n\n            #pragma omp single\n            newPtr[new_numOutput]=new_len+index_offset_out;\n\n            #pragma omp for schedule(static)\n            for (dim_t i=0; i < numOutput; ++i) {\n                for (dim_t k=0; k < output_block_size; ++k) {\n                    newPtr[i*output_block_size+k]=(ptr[i]-index_offset_in)*block_size+\n                                                       (ptr[i+1]-ptr[i])*input_block_size*k+index_offset_out;\n                }\n            }\n\n#pragma omp for schedule(static)\n            for (dim_t i=0; i < new_numOutput; ++i) {\n                #pragma ivdep\n                for (index_t iPtr=newPtr[i]-index_offset_out; iPtr<newPtr[i+1]-index_offset_out; ++iPtr) {\n                    newIndex[iPtr]=index_offset_out;\n                }\n            }\n\n            #pragma omp for schedule(static)\n            for (dim_t i=0; i < numOutput; ++i) {\n                for (index_t iPtr=ptr[i]-index_offset_in; iPtr < ptr[i+1]-index_offset_in; ++iPtr) {\n                    for (dim_t k=0; k < output_block_size; ++k) {\n                        #pragma ivdep\n                        for (dim_t j=0; j < input_block_size; ++j) {\n                            newIndex[newPtr[i*output_block_size+k]-index_offset_out+(iPtr-(ptr[i]-index_offset_in))*input_block_size+j] =\n                                (index[iPtr]-index_offset_in)*input_block_size+j+index_offset_out;\n                        }\n                    }\n                }\n            }\n        } // parallel section\n        out.reset(new Pattern(newType, new_numOutput, new_numInput, newPtr, newIndex));\n    }\n    return out;\n}\n\n// computes the pattern coming from a matrix-matrix multiplication\nPattern_ptr Pattern::multiply(int type, const_Pattern_ptr B) const\n{\n    boost::scoped_array<IndexList> index_list(new IndexList[numOutput]);\n\n#pragma omp parallel for schedule(static)\n    for (dim_t i = 0; i < numOutput; i++) {\n        for (index_t iptrA = ptr[i]; iptrA < ptr[i+1]; ++iptrA) {\n            const dim_t j = index[iptrA];\n            for (index_t iptrB = B->ptr[j]; iptrB < B->ptr[j+1]; ++iptrB) {\n                const dim_t k = B->index[iptrB];\n                index_list[i].insertIndex(k);\n            }\n        }\n    }\n    return Pattern::fromIndexListArray(0, numOutput, index_list.get(), 0,\n                                       B->numInput, 0);\n}\n\n/*\n * Computes the pattern  of C = A binary operation B for CSR matrices A,B\n * Note: we do not check whether A_ij(op)B_ij=0\n */\nPattern_ptr Pattern::binop(int type, const_Pattern_ptr B) const\n{\n    boost::scoped_array<IndexList> index_list(new IndexList[numOutput]);\n    const dim_t nRowsB = B->numOutput;\n\n#pragma omp parallel for schedule(static)\n    for (dim_t i = 0; i < nRowsB; i++) {\n        index_t iptrA = ptr[i];\n        index_t iptrB = B->ptr[i];\n\n        while (iptrA < ptr[i+1] && iptrB < B->ptr[i+1]) {\n            const dim_t j = index[iptrA];\n            const dim_t k = B->index[iptrB];\n            if (j < k) {\n                index_list[i].insertIndex(j);\n                iptrA++;\n            } else if (j > k) {\n                index_list[i].insertIndex(k);\n                iptrB++;\n            } else { // (j == k)\n                index_list[i].insertIndex(j);\n                iptrB++;\n                iptrA++;\n            }\n        }\n        while(iptrA < ptr[i+1]) {\n            const dim_t j = index[iptrA];\n            index_list[i].insertIndex(j);\n            iptrA++;\n        }\n        while(iptrB < B->ptr[i+1]) {\n            const dim_t k = B->index[iptrB];\n            index_list[i].insertIndex(k);\n            iptrB++;\n        }\n    }\n\n    return Pattern::fromIndexListArray(0, numOutput, index_list.get(), 0,\n                                       numInput, 0);\n}\n\n} // namespace paso\n\n", "meta": {"hexsha": "046fba64aaca9a62a71a58c875d3712faff0e4e0", "size": 12557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "paso/src/Pattern.cpp", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paso/src/Pattern.cpp", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paso/src/Pattern.cpp", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3962765957, "max_line_length": 137, "alphanum_fraction": 0.5310981922, "num_tokens": 3094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262785020255, "lm_q2_score": 0.03258974276938117, "lm_q1q2_score": 0.010344840764622958}}
{"text": "// Spear: Statistical Platform for Elucidating moleculAr Reactivity\n// Copyright (C) Purdue University -- BSD license\n\n#include \"spear/FunctionalGroup.hpp\"\n#include \"spear/Molecule_impl.hpp\"\n\n#include <boost/graph/vf2_sub_graph_iso.hpp>\n\nusing namespace Spear;\n\nstatic std::string str_toupper(std::string s) {\n    std::transform(s.begin(), s.end(), s.begin(), \n                   [](unsigned char c){ return std::toupper(c); }\n                  );\n    return s;\n}\n\nFunctionalGroup::FunctionalGroup(const std::string& smiles) {\n    using boost::add_vertex;\n    assert(!smiles.empty());\n\n    std::queue<size_t> paren_backs;\n    std::map <size_t, size_t> rings;\n    size_t current = 0;\n    size_t previous = 0;\n    auto bond_order = Bond::Order::UNKNOWN;\n    bool first_atom = true;\n    bool in_prop_list = false;\n\n    auto add_atom = \n    [this, &first_atom, &bond_order, &previous, &current](Element::Symbol atom) {\n        add_vertex(atom, graph_);\n\n        if (!first_atom) {\n            boost::add_edge(previous, ++current,\n            EdgeProperty(bond_order), graph_);\n        }\n\n        first_atom = false;\n        previous = current;\n        bond_order = Bond::Order::UNKNOWN;\n        properties_.emplace_back(std::list<AtomPropertyCompare>());\n    };\n\n    auto read_number =\n    [&smiles](size_t& start) {\n        if (std::isdigit(smiles[start + 1]) == 0) {\n            return static_cast<size_t>(1);\n        }\n        ++start;\n        size_t number = 0;\n        while (start < smiles.size() && (std::isdigit(smiles[start]) != 0)) {\n            number *= 10;\n            number += static_cast<size_t>(smiles[start] - '0');\n            ++start;\n        }\n        --start;\n        return number;\n    };\n\n    for (size_t i = 0; i < smiles.size(); ++i) {\n        if (in_prop_list) {\n            size_t bonds = 0;\n            size_t i_copy = i;\n            switch (smiles[i]) {\n            case 'D': // Degree\n                bonds = read_number(i);\n\n                // Add a lambda function to compare the bond counts\n                properties_.back().emplace_back(\n                    [bonds](const AtomVertex& a1) {\n                        return a1.degree() == bonds;\n                    }\n                );\n                continue;\n            case 'X': // Total bonds (explicit + implicit Hs)\n                bonds = read_number(i);\n                properties_.back().emplace_back(\n                    [bonds](const AtomVertex& a1) {\n                        return a1.degree() + a1.implicit_hydrogens() == bonds;\n                    }\n                );\n                continue;\n            case 'h': // Implicit hydrogens\n                bonds = read_number(i);\n                if (i != i_copy) {\n                    properties_.back().emplace_back(\n                        [bonds](const AtomVertex& a1) {\n                            return a1.implicit_hydrogens() == bonds;\n                        }\n                    );\n                } else {\n                    properties_.back().emplace_back(\n                        [bonds](const AtomVertex& a1) {\n                            return a1.implicit_hydrogens() >= 1;\n                        }\n                    );\n                }\n                continue;\n            case 'H': // Total hydrogens\n                bonds = read_number(i);\n                properties_.back().emplace_back(\n                    [bonds](const AtomVertex& a1) {\n                        return a1.total_hydrogens() == bonds;\n                    }\n                );\n                continue;\n            case 'R':\n                bonds = read_number(i);\n                if (i != i_copy) {\n                    properties_.back().emplace_back(\n                        [bonds](const AtomVertex& a1) {\n                            auto sssrs = a1.sssrs();\n                            return std::distance(sssrs.first, sssrs.second) ==\n                                   static_cast<std::ptrdiff_t>(bonds);\n                        }\n                    );\n                } else {\n                    properties_.back().emplace_back(\n                        [](const AtomVertex& a1) {\n                            auto sssrs = a1.sssrs();\n                            return std::distance(sssrs.first, sssrs.second) != 0;\n                        }\n                    );\n                }\n                continue;\n            case 'r':\n                bonds = read_number(i);\n                if (i != i_copy) {\n                    properties_.back().emplace_back(\n                        [bonds](const AtomVertex& a1) {\n                            auto sssrs = a1.sssrs();\n                            for (auto ring = sssrs.first; ring != sssrs.second; ++ring) {\n                                if (ring->second.size() == bonds) return true;\n                            }\n                            return false;\n                        }\n                    );\n                } else {\n                    properties_.back().emplace_back(\n                        [](const AtomVertex& a1) {\n                            auto sssrs = a1.sssrs();\n                            return std::distance(sssrs.first, sssrs.second) != 0;\n                        }\n                    );\n                }\n                continue;\n            case 'a':\n                properties_.back().emplace_back(\n                    [](const AtomVertex& a1) {\n                        return a1.is_aromatic();\n                    }\n                );\n                continue;\n            case 'A':\n                properties_.back().emplace_back(\n                    [](const AtomVertex& a1) {\n                        return !a1.is_aromatic();\n                    }\n                );\n                continue;\n            case '#':\n                bonds = read_number(i);\n                add_atom(static_cast<Element::Symbol>(bonds));\n                continue;\n            default:\n                break;\n            }\n        }\n\n        if (smiles[i] == 'a' || smiles[i] == 'A') {\n            bool should_be_aromatic = std::islower(smiles[i]) != 0;\n            if (!in_prop_list) {\n                add_atom(Element::Symbol(0));\n            }\n\n            properties_.back().emplace_back(\n                [should_be_aromatic](const AtomVertex& a1) {\n                    return a1.is_aromatic() == should_be_aromatic;\n                }\n            );\n\n            continue;\n        }\n\n        if (std::islower(smiles[i]) != 0) {\n            auto is_found = Element::SymbolForName.find(\n                str_toupper(smiles.substr(i, 1))\n            );\n            if (is_found != Element::SymbolForName.end()) {\n                add_atom(is_found->second);\n            } else {\n                throw std::invalid_argument(std::string(\"Element not found: \") + smiles[i]);\n            }\n            properties_.back().emplace_back(\n                [](const AtomVertex& a1) {\n                    return a1.is_aromatic();\n                }\n            );\n            continue;\n        }\n\n        // Unlike a smiles string, C does not imply aliphatic!\n        if (std::isupper(smiles[i]) != 0) {\n            size_t element_length =\n                i + 1 < smiles.size() && (std::islower(smiles[i+1]) != 0)? 2 : 1;\n\n            auto element_name = smiles.substr(i, element_length);\n            auto is_found = Element::SymbolForName.find(element_name);\n\n            if (is_found != Element::SymbolForName.end()) {\n                add_atom(is_found->second);\n            } else {\n                throw std::invalid_argument(\"Element not found: \" + element_name);\n            }\n            i += element_length - 1;\n            continue;\n        }\n\n        if (std::isdigit(smiles[i]) != 0) {\n            auto ring_id = static_cast<size_t>(smiles[i] - '0');\n            auto ring_lookup = rings.find(ring_id);\n\n            if (ring_lookup == rings.end()) {\n                rings.insert({ring_id, previous});\n                continue;\n            }\n\n            boost::add_edge(previous, ring_lookup->second,\n                EdgeProperty(bond_order), graph_);\n            rings.erase(ring_lookup);\n            continue;\n        }\n\n        switch (smiles[i]) {\n        case '.': first_atom = false; break;\n        case '*': add_atom(Element::Symbol(0)); break;\n        case '@': break;\n        case '/': break;\n        case '\\\\': break;\n        case '%': break;\n        case '~': bond_order = Bond::Order::UNKNOWN; break;\n        case '-': bond_order = Bond::Order::SINGLE; break; // We don't support charges\n        case '=': bond_order = Bond::Order::DOUBLE; break;\n        case '#': bond_order = Bond::Order::TRIPLE; break;\n        case ':': bond_order = Bond::Order::AROMATIC; break;\n        case '[': in_prop_list = true; break;\n        case ']': in_prop_list = false; break;\n        case '+': break;\n        case '(':\n            paren_backs.push(previous);\n            break;\n        case ')':\n            previous = paren_backs.back();\n            paren_backs.pop();\n            break;\n        default: break;\n        }\n    }\n}\n\n/// This Functor is run when the graph matching algorithm finds a potential\n/// FunctionalGroup. It is responsible for populating the found_groups list\n/// and performing final checks for properties in the functional group.\nstruct FunctionalGroupFinder {\n    FunctionalGroupFinder(const Molecule& mol, const FunctionalGroup& fg,\n        std::list<std::vector<size_t>>& found_groups):\n    mol_(mol), fg_(fg), found_groups_(found_groups) {\n    }\n\n    // Map1 should be the functional group\n    // Map2 should be the molecule\n    // Therefore, fg_to_mol coverts the functional group mapping to the molecule\n    template <typename Map1To2, typename Map2To1>\n    bool operator()(Map1To2 fg_to_mol, Map2To1 /*unused*/) {\n\n        std::vector<size_t> group;\n\n        // Prepare to loop through the functional group\n        group.reserve(boost::num_vertices(fg_.graph()));\n        auto verticies_iter = boost::vertices(fg_.graph());\n\n        // Add the **molecule** index to the group, *not* the functional groups\n        // v is an interator through the functional group\n        for (auto v = verticies_iter.first; v != verticies_iter.second; ++v) {\n\n            const auto& mol_id = boost::get(fg_to_mol, *v); // v is the functional group index\n            const auto& mol_index = boost::get(boost::vertex_index, mol_.graph(), mol_id);\n\n            // Final property check\n            auto fg_index = boost::get(boost::vertex_index_t(), fg_.graph(), *v);\n            const auto& props = fg_.properties(fg_index);\n            for (const auto& prop : props) {\n                if (!prop(mol_[mol_index])) {\n                    // Don't add the group, get out!\n                    return true;\n                }\n            }\n\n            // All tests for this functional group atom -> molecular atom passed\n            group.push_back(mol_index);\n        }\n\n        // All tests for all atoms have passed\n        found_groups_.emplace_back(group);\n        return true;\n    }\n\nprivate:\n    const Molecule& mol_;\n    const FunctionalGroup& fg_;\n    std::list<std::vector<size_t>>& found_groups_;\n};\n\n\n/// This Functor compares the properties of an edge (bond) or vertex(atom).\n/// The template arguments should be automatically deduced when a comparison\n/// structure is initialized using the **compare_topology** function.\ntemplate <typename PropertyFirst, typename PropertySecond, typename IgnoreType>\nstruct CompareTopology {\n  \n    CompareTopology(const PropertyFirst property_map1,\n                    const PropertySecond property_map2,\n                    const IgnoreType ignore) :\n    property1_(property_map1), property2_(property_map2), ignore_(ignore) {}\n\n    template <typename ItemFirst,\n              typename ItemSecond>\n    bool operator()(const ItemFirst item1, const ItemSecond item2) const {\n        if (boost::get(property1_, item1) == ignore_) return true;\n        if (boost::get(property2_, item2) == ignore_) return true;\n        return boost::get(property1_, item1) == boost::get(property2_, item2);\n    }\n  \nprivate:\n    const PropertyFirst property1_;\n    const PropertySecond property2_;\n    const IgnoreType ignore_;\n};\n\n/// This is a convience function for creating CompareTopology Functors.\ntemplate <typename PropertyFirst, typename PropertySecond, typename IgnoreType>\nCompareTopology<PropertyFirst, PropertySecond, IgnoreType>\ncompare_topology(const PropertyFirst property1,\n                 const PropertySecond property2,\n                 const IgnoreType ignore) {\n    return CompareTopology<PropertyFirst, PropertySecond, IgnoreType>\n        (property1, property2, ignore);\n}\n\nstd::list<std::vector<size_t>> Spear::find_functional_groups(const Molecule& mol,\n                                                             const FunctionalGroup& fg) {\n\n    // Initial objects to hold the found functional groups\n    std::list<std::vector<size_t>> found_groups;\n    FunctionalGroupFinder callback(mol, fg, found_groups);\n\n    const auto& fg_graph = fg.graph();\n    const auto& mol_graph = mol.graph();\n\n    // Make comparison functions\n    auto vertex_comp =\n        compare_topology(boost::get(boost::vertex_name, fg_graph),\n                         boost::get(boost::vertex_name, mol_graph),\n                         uint64_t(0));\n\n    auto edge_comp =\n        compare_topology(boost::get(boost::edge_name, fg_graph),\n                         boost::get(boost::edge_name, mol_graph),\n                         uint64_t(0));\n\n    // Find subgraphs\n    boost::vf2_subgraph_iso(fg_graph, mol_graph, callback,\n        boost::vertex_order_by_mult(fg_graph),\n        boost::edges_equivalent(edge_comp).vertices_equivalent(vertex_comp));\n\n    return found_groups;\n}\n", "meta": {"hexsha": "100cb9db8fbaca771a2697a088ebd0b3ac923af5", "size": 13725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FunctionalGroup.cpp", "max_stars_repo_name": "chopralab/spear", "max_stars_repo_head_hexsha": "d45ffc907ab1730789413dd04afb347a26f35154", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T07:57:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T13:58:37.000Z", "max_issues_repo_path": "src/FunctionalGroup.cpp", "max_issues_repo_name": "chopralab/spear", "max_issues_repo_head_hexsha": "d45ffc907ab1730789413dd04afb347a26f35154", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FunctionalGroup.cpp", "max_forks_repo_name": "chopralab/spear", "max_forks_repo_head_hexsha": "d45ffc907ab1730789413dd04afb347a26f35154", "max_forks_repo_licenses": ["BSD-3-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.2137203166, "max_line_length": 94, "alphanum_fraction": 0.5147540984, "num_tokens": 2891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233684437737093, "lm_q2_score": 0.02635535590511949, "lm_q1q2_score": 0.01034017716825709}}
{"text": "/*\n * Copyright 2010-2016 by RomboStudios\n * All rights reserved.\n ******************************************************************************\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 the software's owners 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 * Created:\tAugutst 15, 2011\n */\n\n\n#ifndef CPC_POINTCONTAINER_H_INCLUDED\n#define CPC_POINTCONTAINER_H_INCLUDED\n\n#include <boost/scoped_array.hpp>\n\n\nnamespace cpc\n{\n\n/// ------------------------------------------------------------------------------\n/// Naive octree for storing a point hierarchy\ntemplate< typename DataType, class iPointlist >\nclass iOctreeGI\n{\npublic:\n\t/// Tree node\n\t/// Leaf nodes have npoints > 0, \n\t/// specifying the number of child points contained\n\tstruct Node\n\t{\n\t\tNode()\n\t\t:\tbbox_min(1e30f)\n\t\t,\tbbox_max(-1e30f)\n\n\t\t,\taggP(0.f)\n\t\t,\taggN(0.f)\n\t\t,\taggR(0.f)\n\t\t,\taggCol(0.f)\n\n\t\t,\tnpoints(0)\n\n\t\t,\tdata()\n\t\t{\n\t\t\tchildren[0] = children[1] = children[2] = children[3] = 0;\n\t\t\tchildren[4] = children[5] = children[6] = children[7] = 0;\n\t\t}\n\n\t\t/// Octree node data\n\t\tiVector3\tbbox_min;\t\t\t\t// node bounding box min\n\t\tiVector3\tbbox_max;\t\t\t\t// node bounding box max\n\n\t\tiVector3\taggP;\t\t\t\t\t// aggregated position\n\t\tiVector3\taggN;\t\t\t\t\t// normal\n\t\tiVector3\taggCol;\t\t\t\t\t// node radiance\n\t\tfloat\t\taggR;\t\t\t\t\t// and radius\n\n\t\tint npoints;\t\t\t\t\t\t// Number of child points for the leaf node case\n\n\t\tNode* children[8];\t\t\t\t\t// Child nodes, to be indexed as children[z][y][x]\n\n\t\tboost::scoped_array<float> data;\t// Collection of points in leaf\n\t\t\t\t\t\t\t\t\t\t\t// The building mechanism stores leaf points \n\t\t\t\t\t\t\t\t\t\t\t// directly in the octree node\n\t};\n\n\t/// Construct tree from array of points\n\tiOctreeGI():\t\t\t\tm_root(0),\tm_dataSize(0){}\n\t~iOctreeGI()\t\t\t\t{};\n\n\t\n\t/// Get total node\n\tint getTotalNodes()\t\t\t{ return m_totnodes; };\n\n\t/// Get root node of tree\n\tconst Node* root()\tconst\t{ return m_root; }\n\n\t/// Get number of floats representing each point.\n\tint dataSize()\t\tconst\t{ return m_dataSize; }\n\n\t/// Clear tree\n\tvoid Clear()\t\t\t\t{ deleteTree(m_root); }\n\n\n\t/// Build octree from pointlist //////////////////////////////////////////////////////////////////////\n\tiOctreeGI( iPointlist* pointlist )\n\t:\tm_root(0)\n\t,\tm_dataSize(iPointlist::NODESIZE)\n\t{\n\t\tthis->Clear();\t///\t/////////////////////////////////////// <== !!?\n\t\tsize_t npoints = pointlist->GetTotalNodes();\n\n\n\t\t// We make octree bound cubic rather than fitting the point cloud\n\t\t// tightly.  This improves the distribution of points in the octree\n\t\t// nodes and reduces artifacts when groups of points are aggregated\n\t\t// in the internal nodes.\n\t\t//\n\t\t// If we *don't* do this and we have a rectangular (non-cubic)\n\t\t// bound, we end up with a lot more points in one direction inside\n\t\t// a node than another.  This means the aggregated averaged point -\n\t\t// intended to represent the collection - is in the middle, but\n\t\t// with lots of room on either side:\n\t\t//\n\t\t// +-----------+   ----->    +----/^\\----+\n\t\t// | o o o o o |  aggregate  |   | . |   |\n\t\t// +-----------+             +----\\_/----+\n\t\t//\n\t\t//   <------->                   <--->\n\t\t// even distribution           all in middle :(\n\t\t//\n\t\t// That is, there will be large gaps between neighbouring disks,\n\t\t// which gives large transparent gaps in the microrendered surface.\n\n\t\tiVector3\tbbox_min;\t\t\t\t\t\t\t// node bounding box min\n\t\tiVector3\tbbox_max;\t\t\t\t\t\t\t// node bounding box max\n\n\t\tfor(size_t i = 0; i < npoints; ++i)\n\t\t{\n\t\t\tiVector3 p ( pointlist->template GetNodeVectorAt<DATA_SLOT_POS>(i) );\t\t\t\n\t\t\tp.expand_bbox(bbox_min, bbox_max);\n\t\t}\n\t\tiVector3 d ( bbox_max - bbox_min );\t\t\t\t// diagonal\n\t\tiVector3 c ( (bbox_min + bbox_max) / 2.f );\t\t// center\n\n\t\tfloat maxDim2 = ds_MAX(ds_MAX(d.GetX(), d.GetY()), d.GetZ()) / 2;\n\t\tbbox_min = c - maxDim2;\n\t\tbbox_max = c + maxDim2;\n\n\n\t\t// Get a ref(workspace) to the actual pointlist\n\t\tiPointListSimple workspace;\n\t\tworkspace.SetStorageArray( pointlist->GetStorageArray() );\n\n\t\t// Build octree\n\t\tm_root = makeTree(0, &workspace, npoints, m_dataSize, bbox_min, bbox_max);\n\t}\n\n\n\t/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////\nprivate:\n\n\t/// Members \n\tNode* m_root;\n\tint m_dataSize;\n\tint m_totnodes;\n\n\n\t/// Recursively delete tree, depth first.\n\tstatic void deleteTree(Node* n)\n\t{\n\t\tif(!n) return;\n\n\t\tfor(int i = 0; i < 8; ++i)\n\t\tdeleteTree(n->children[i]);\n\n\t\tdelete n;\n\t}\n\n\n\t/// Build a tree node from the given points\n\ttemplate<class xPointList>\n\tNode* makeTree(\tint\t\t\t\t\tdepth, \n\t\t\t\t\txPointList*\t\t\tpointlist, \n\t\t\t\t\tsize_t\t\t\t\tnpoints, \n\t\t\t\t\tint\t\t\t\t\tdataSize, \n\t\t\t\t\tconst iVector3&\t\tbbox_min,\n\t\t\t\t\tconst iVector3&\t\tbbox_max\n\t\t\t\t\t)\n\t{\n\t\tassert(npoints != 0);\n\t\tm_totnodes++;\n\n\n\t\t// Setup bounding box\n\t\tNode* node = new Node;\n\t\tnode->bbox_min = bbox_min;\n\t\tnode->bbox_max = bbox_max;\n\n\t\tiVector3 c ( (bbox_min + bbox_max) / 2.f);\n\t\tnode->npoints = 0;\n\n\n\t\t// Limit max depth of tree to prevent infinite recursion\n\t\tint maxDepth = 24;\n\t\tsize_t pointsPerLeaf = 8;\n\n\t\tif(npoints <= pointsPerLeaf || depth >= maxDepth)\n\t\t{\n\t\t\t// Small number of child points: make this a leaf node\n\t\t\tnode->npoints = npoints;\n\n\t\t\t// Copy over data into node\n\t\t\tnode->data.reset(new float[npoints*dataSize]);\n\n\t\t\tiVector3 sumP(0.f);\t\tiVector3 sumN(0.f);\n\t\t\tiVector3 sumCol(0.f);\tfloat sumA = 0.f;\n\n\t\t\tfor(size_t j = 0; j < npoints; ++j)\n\t\t\t{\n\t\t\t\tconst float* nodedata = pointlist->GetNodePtr( j );\n\n\t\t\t\t// copy extra data\n\t\t\t\tfor(int i = 0; i < dataSize; ++i)\n\t\t\t\tnode->data[ j*dataSize + i ] = nodedata[i];\n\n\t\t\t\t// compute averages (area weighted)\n\t\t\t\tfloat A = pointlist->template GetNodeScalarAt<DATA_SLOT_AREA>( nodedata );\n\t\t\t\tA *= A;\n\t\t\t\tsumA\t+=\tA;\n\t\t\t\tsumP\t+=\tA * iVector3(pointlist->template GetNodeVectorAt<DATA_SLOT_POS>( nodedata ));\n\t\t\t\tsumN\t+=\tA * iVector3(pointlist->template GetNodeVectorAt<DATA_SLOT_DIR>( nodedata ));\n\t\t\t\tsumCol\t+=\tA * iVector3(pointlist->template GetNodeVectorAt<DATA_SLOT_IRRAD>( nodedata ));\n\t\t\t}\n\n\t\t\tnode->aggP\t\t=\t1.0f/sumA * sumP;\n\t\t\tnode->aggN\t\t=\tsumN.normalize();\n\t\t\tnode->aggR\t\t=\tsqrtf(sumA);\n\t\t\tnode->aggCol\t=\t1.0f/sumA * sumCol;\n\n\t\t\treturn node;\n\t\t}\n\t\t\n\t\t// allocate extra workspace for storing child points (ugh!)\n\t\tstd::vector< const float*> workspace(8*npoints);\n\t\tconst float** w = &workspace[0];\n\t\tconst float** P[8] = {\n\t\t\tw,             w + npoints,   w + 2*npoints, w + 3*npoints,\n\t\t\tw + 4*npoints, w + 5*npoints, w + 6*npoints, w + 7*npoints\n\t\t};\n\n\t\t// Partition points into the eight child nodes\n\t\tsize_t np[8] = {0};\n\t\tfor(size_t i = 0; i < npoints; ++i)\n\t\t{\n\t\t\tconst float* p = pointlist->GetNodePtr( i );\n\n\t\t\tint cellIndex = 4*(p[2] > c.GetZ()) + 2*(p[1] > c.GetY()) + (p[0] > c.GetX());\n\t\t\tP[cellIndex][np[cellIndex]++] = p;\n\t\t}\n\n\t\t// Recursively generate child nodes and finalize node\n\t\tfloat sumA = 0;\n\t\tiVector3 sumP(0.f);\n\t\tiVector3 sumN(0.f);\n\t\tiVector3 sumCol(0.f);\n\n\t\tfor(int i = 0; i < 8; ++i)\n\t\t{\n\t\t\tif(np[i] == 0)\n\t\t\tcontinue;\n\n\t\t\t//Box3f bnd;\n\t\t\tiVector3\tbnd_bbox_min;\t\t\t// node bounding box min\n\t\t\tiVector3\tbnd_bbox_max;\t\t\t// node bounding box max\n\t\t\tbnd_bbox_min.SetX( (i     % 2 == 0) ? bbox_min.GetX() : c.GetX() );\n\t\t\tbnd_bbox_min.SetY( ((i/2) % 2 == 0) ? bbox_min.GetY() : c.GetY() );\n\t\t\tbnd_bbox_min.SetZ( ((i/4) % 2 == 0) ? bbox_min.GetZ() : c.GetZ() );\n\t\t\tbnd_bbox_max.SetX( (i     % 2 == 0) ? c.GetX() : bbox_max.GetX() );\n\t\t\tbnd_bbox_max.SetY( ((i/2) % 2 == 0) ? c.GetY() : bbox_max.GetY() );\n\t\t\tbnd_bbox_max.SetZ( ((i/4) % 2 == 0) ? c.GetZ() : bbox_max.GetZ() );\n\n\t\t\t// Node plist workspace\n\t\t\tiPointListSimple nodeplist;\n\t\t\tnodeplist.SetStorageArray( P[i] );\n\n\t\t\t//* Make child node\n\t\t\tNode* child = makeTree(depth+1, &nodeplist, np[i], dataSize, bnd_bbox_min, bnd_bbox_max);\n\t\t\tnode->children[i] = child;\n\n\t\t\t// Weighted average with weight = disk surface area\n\t\t\tfloat A = child->aggR * child->aggR;\n\t\t\tsumA\t+=\tA;\n\t\t\tsumP\t+=\tA * child->aggP;\n\t\t\tsumN\t+=\tA * child->aggN;\n\t\t\tsumCol\t+=\tA * child->aggCol;\n\t\t}\n\n\t\tnode->aggP\t\t=\t1.0f/sumA * sumP;\n\t\tnode->aggN\t\t=\tsumN.normalize();\n\t\tnode->aggR\t\t=\tsqrtf(sumA);\n\t\tnode->aggCol\t=\t1.0f/sumA * sumCol;\n\n\t\treturn node;\n\t}\t\n\n};\t\t// iOctreeGI\n\n}\t\t// cpc namespace\n#endif\t// CPC_POINTCONTAINER_H_INCLUDED\n", "meta": {"hexsha": "ca1147ef777fbfdec9d32b71cc7b9cbcc7f3892e", "size": 9427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "DataStructures/pointcontainer.hpp", "max_stars_repo_name": "RomboDev/mrPointClouds", "max_stars_repo_head_hexsha": "aa12165b878e0fb615ce8ef80410b7a0e375f8d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-04-18T16:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T20:53:37.000Z", "max_issues_repo_path": "DataStructures/pointcontainer.hpp", "max_issues_repo_name": "RomboDev/mrPointClouds", "max_issues_repo_head_hexsha": "aa12165b878e0fb615ce8ef80410b7a0e375f8d6", "max_issues_repo_licenses": ["MIT"], "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/pointcontainer.hpp", "max_forks_repo_name": "RomboDev/mrPointClouds", "max_forks_repo_head_hexsha": "aa12165b878e0fb615ce8ef80410b7a0e375f8d6", "max_forks_repo_licenses": ["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.1182108626, "max_line_length": 116, "alphanum_fraction": 0.6235281638, "num_tokens": 2816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220179564702847, "lm_q2_score": 0.02931223244728875, "lm_q1q2_score": 0.010323820902358189}}
{"text": "// Copyright (C) 2004-2006 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n\n/**************************************************************************\n * This source file implements the variation on Dijkstra's algorithm      *\n * presented by Crauser et al. in:                                        *\n *                                                                        *\n *   Andreas Crauser, Kurt Mehlhorn, Ulrich Meyer, and Peter              *\n *   Sanders. A Parallelization of Dijkstra's Shortest Path               *\n *   Algorithm. In Lubos Brim, Jozef Gruska, and Jiri Zlatuska,          *\n *   editors, Mathematical Foundations of Computer Science (MFCS),        *\n *   volume 1450 of Lecture Notes in Computer Science, pages              *\n *   722--731, 1998. Springer.                                            *\n *                                                                        *\n * This implementation is, however, restricted to the distributed-memory  *\n * case, where the work is distributed by virtue of the vertices being    *\n * distributed. In a shared-memory (single address space) context, we     *\n * would want to add an explicit balancing step.                          *\n **************************************************************************/\n#ifndef BOOST_GRAPH_CRAUSER_ET_AL_SHORTEST_PATHS_HPP\n#define BOOST_GRAPH_CRAUSER_ET_AL_SHORTEST_PATHS_HPP\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <boost/assert.hpp>\n#include <boost/graph/distributed/detail/dijkstra_shortest_paths.hpp>\n#include <boost/graph/parallel/algorithm.hpp>\n#include <functional>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/property_map/property_map_iterator.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <algorithm>\n#include <boost/property_map/parallel/caching_property_map.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/graph/distributed/detail/remote_update_set.hpp>\n#include <vector>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/parallel/container_traits.hpp>\n\n#ifdef PBGL_ACCOUNTING\n#  include <boost/graph/accounting.hpp>\n#  include <numeric>\n#endif // PBGL_ACCOUNTING\n\n#ifdef MUTABLE_QUEUE\n#    include <boost/pending/mutable_queue.hpp>\n#endif\n\nnamespace boost { namespace graph { namespace distributed {\n\n#ifdef PBGL_ACCOUNTING\nstruct crauser_et_al_shortest_paths_stats_t\n{\n  /* Total wall-clock time used by the algorithm.*/\n  accounting::time_type execution_time;\n\n  /* The number of vertices deleted in each superstep. */\n  std::vector<std::size_t> deleted_vertices;\n\n  template<typename OutputStream>\n  void print(OutputStream& out)\n  {\n    double avg_deletions = std::accumulate(deleted_vertices.begin(),\n                                           deleted_vertices.end(),\n                                           0.0);\n    avg_deletions /= deleted_vertices.size();\n\n    out << \"Problem = \\\"Single-Source Shortest Paths\\\"\\n\"\n        << \"Algorithm = \\\"Crauser et al\\\"\\n\"\n        << \"Function = crauser_et_al_shortest_paths\\n\"\n        << \"Wall clock time = \" << accounting::print_time(execution_time)\n        << \"\\nSupersteps = \" << deleted_vertices.size() << \"\\n\"\n        << \"Avg. deletions per superstep = \" << avg_deletions << \"\\n\";\n  }\n};\n\nstatic crauser_et_al_shortest_paths_stats_t crauser_et_al_shortest_paths_stats;\n#endif\n\nnamespace detail {\n\n  /************************************************************************\n   * Function objects that perform distance comparisons modified by the   *\n   * minimum or maximum edge weights.                                     *\n   ************************************************************************/\n  template<typename Vertex, typename DistanceMap, typename MinInWeightMap,\n           typename Combine, typename Compare>\n  struct min_in_distance_compare\n    : std::binary_function<Vertex, Vertex, bool>\n  {\n    min_in_distance_compare(DistanceMap d, MinInWeightMap m,\n                            Combine combine, Compare compare)\n      : distance_map(d), min_in_weight(m), combine(combine),\n        compare(compare)\n    {\n    }\n\n    bool operator()(const Vertex& x, const Vertex& y) const\n    {\n      return compare(combine(get(distance_map, x), -get(min_in_weight, x)),\n                     combine(get(distance_map, y), -get(min_in_weight, y)));\n    }\n\n  private:\n    DistanceMap distance_map;\n    MinInWeightMap min_in_weight;\n    Combine combine;\n    Compare compare;\n  };\n\n  template<typename Vertex, typename DistanceMap, typename MinOutWeightMap,\n           typename Combine, typename Compare>\n  struct min_out_distance_compare\n    : std::binary_function<Vertex, Vertex, bool>\n  {\n    min_out_distance_compare(DistanceMap d, MinOutWeightMap m,\n                             Combine combine, Compare compare)\n      : distance_map(d), min_out_weight(m), combine(combine),\n        compare(compare)\n    {\n    }\n\n    bool operator()(const Vertex& x, const Vertex& y) const\n    {\n      return compare(combine(get(distance_map, x), get(min_out_weight, x)),\n                     combine(get(distance_map, y), get(min_out_weight, y)));\n    }\n\n  private:\n    DistanceMap distance_map;\n    MinOutWeightMap min_out_weight;\n    Combine combine;\n    Compare compare;\n  };\n  /************************************************************************/\n\n  /************************************************************************\n   * Dijkstra queue that implements Crauser et al.'s criteria. This queue *\n   * actually stores three separate priority queues, to help expose all   *\n   * vertices that can be processed in a single phase.                    *\n   ************************************************************************/\n  template<typename Graph, typename Combine,\n           typename Compare, typename VertexIndexMap, typename DistanceMap,\n           typename PredecessorMap, typename MinOutWeightMap,\n           typename MinInWeightMap>\n  class crauser_et_al_dijkstra_queue\n    : public graph::detail::remote_update_set<\n               crauser_et_al_dijkstra_queue<\n                 Graph, Combine, Compare, VertexIndexMap, DistanceMap,\n                 PredecessorMap, MinOutWeightMap, MinInWeightMap>,\n               typename boost::graph::parallel::process_group_type<Graph>::type,\n               typename dijkstra_msg_value<DistanceMap, PredecessorMap>::type,\n               typename property_map<Graph, vertex_owner_t>::const_type>\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor\n      vertex_descriptor;\n    typedef crauser_et_al_dijkstra_queue self_type;\n    typedef dijkstra_msg_value<DistanceMap, PredecessorMap> msg_value_creator;\n    typedef typename msg_value_creator::type msg_value_type;\n    typedef typename graph_traits<Graph>::vertices_size_type\n      vertices_size_type;\n    typedef typename property_map<Graph, vertex_owner_t>::const_type\n      OwnerPropertyMap;\n    typedef typename boost::graph::parallel::process_group_type<Graph>::type\n      process_group_type;\n    typedef graph::detail::remote_update_set<self_type, process_group_type,\n                                             msg_value_type, OwnerPropertyMap>\n      inherited;\n\n    // Priority queue for tentative distances\n    typedef indirect_cmp<DistanceMap, Compare> dist_queue_compare_type;\n\n    typedef typename property_traits<DistanceMap>::value_type distance_type;\n\n#ifdef MUTABLE_QUEUE\n    typedef mutable_queue<vertex_descriptor, std::vector<vertex_descriptor>,\n                          dist_queue_compare_type, VertexIndexMap> dist_queue_type;\n\n#else\n    typedef relaxed_heap<vertex_descriptor, dist_queue_compare_type,\n                         VertexIndexMap> dist_queue_type;\n#endif // MUTABLE_QUEUE\n\n    // Priority queue for OUT criteria\n    typedef min_out_distance_compare<vertex_descriptor, DistanceMap,\n                                     MinOutWeightMap, Combine, Compare>\n      out_queue_compare_type;\n\n#ifdef MUTABLE_QUEUE\n    typedef mutable_queue<vertex_descriptor, std::vector<vertex_descriptor>,\n                          out_queue_compare_type, VertexIndexMap> out_queue_type;\n\n#else\n    typedef relaxed_heap<vertex_descriptor, out_queue_compare_type,\n                         VertexIndexMap> out_queue_type;\n#endif // MUTABLE_QUEUE\n\n    // Priority queue for IN criteria\n    typedef min_in_distance_compare<vertex_descriptor, DistanceMap,\n                                    MinInWeightMap, Combine, Compare>\n      in_queue_compare_type;\n\n#ifdef MUTABLE_QUEUE\n    typedef mutable_queue<vertex_descriptor, std::vector<vertex_descriptor>,\n                          in_queue_compare_type, VertexIndexMap> in_queue_type;\n\n#else\n    typedef relaxed_heap<vertex_descriptor, in_queue_compare_type,\n                         VertexIndexMap> in_queue_type;\n#endif // MUTABLE_QUEUE\n\n    typedef typename process_group_type::process_id_type process_id_type;\n\n  public:\n    typedef typename dist_queue_type::size_type  size_type;\n    typedef typename dist_queue_type::value_type value_type;\n\n    crauser_et_al_dijkstra_queue(const Graph& g,\n                                 const Combine& combine,\n                                 const Compare& compare,\n                                 const VertexIndexMap& id,\n                                 const DistanceMap& distance_map,\n                                 const PredecessorMap& predecessor_map,\n                                 const MinOutWeightMap& min_out_weight,\n                                 const MinInWeightMap& min_in_weight)\n      : inherited(boost::graph::parallel::process_group(g), get(vertex_owner, g)),\n        dist_queue(num_vertices(g),\n                   dist_queue_compare_type(distance_map, compare),\n                   id),\n        out_queue(num_vertices(g),\n                  out_queue_compare_type(distance_map, min_out_weight,\n                                         combine, compare),\n                  id),\n        in_queue(num_vertices(g),\n                 in_queue_compare_type(distance_map, min_in_weight,\n                                       combine, compare),\n                 id),\n        g(g),\n        distance_map(distance_map),\n        predecessor_map(predecessor_map),\n        min_out_weight(min_out_weight),\n        min_in_weight(min_in_weight),\n        min_distance(0),\n        min_out_distance(0)\n#ifdef PBGL_ACCOUNTING\n        , local_deletions(0)\n#endif\n    { }\n\n    void push(const value_type& x)\n    {\n      msg_value_type msg_value =\n        msg_value_creator::create(get(distance_map, x),\n                                  predecessor_value(get(predecessor_map, x)));\n      inherited::update(x, msg_value);\n    }\n\n    void update(const value_type& x) { push(x); }\n\n    void pop()\n    {\n      // Remove from distance queue\n      dist_queue.remove(top_vertex);\n\n      // Remove from OUT queue\n      out_queue.remove(top_vertex);\n\n      // Remove from IN queue\n      in_queue.remove(top_vertex);\n\n#ifdef PBGL_ACCOUNTING\n      ++local_deletions;\n#endif\n    }\n\n    vertex_descriptor& top() { return top_vertex; }\n    const vertex_descriptor& top() const { return top_vertex; }\n\n    bool empty()\n    {\n      inherited::collect();\n\n      // If there are no suitable messages, wait until we get something\n      while (!has_suitable_vertex()) {\n        if (do_synchronize()) return true;\n      }\n      // Return true only if nobody has any messages; false if we\n      // have suitable messages\n      return false;\n    }\n\n    bool do_synchronize()\n    {\n      using boost::parallel::all_reduce;\n      using boost::parallel::minimum;\n\n      inherited::synchronize();\n\n      // TBD: could use combine here, but then we need to stop using\n      // minimum<distance_type>() as the function object.\n      distance_type local_distances[2];\n      local_distances[0] =\n        dist_queue.empty()? (std::numeric_limits<distance_type>::max)()\n        : get(distance_map, dist_queue.top());\n\n      local_distances[1] =\n        out_queue.empty()? (std::numeric_limits<distance_type>::max)()\n        : (get(distance_map, out_queue.top())\n           + get(min_out_weight, out_queue.top()));\n\n      distance_type distances[2];\n      all_reduce(this->process_group, local_distances, local_distances + 2,\n                 distances, minimum<distance_type>());\n      min_distance = distances[0];\n      min_out_distance = distances[1];\n\n#ifdef PBGL_ACCOUNTING\n      std::size_t deletions = 0;\n      all_reduce(this->process_group, &local_deletions, &local_deletions + 1,\n                 &deletions, std::plus<std::size_t>());\n      if (process_id(this->process_group) == 0) {\n        crauser_et_al_shortest_paths_stats.deleted_vertices.push_back(deletions);\n      }\n      local_deletions = 0;\n      BOOST_ASSERT(deletions > 0);\n#endif\n\n      return min_distance == (std::numeric_limits<distance_type>::max)();\n    }\n\n  private:\n    vertex_descriptor predecessor_value(vertex_descriptor v) const\n    { return v; }\n\n    vertex_descriptor\n    predecessor_value(property_traits<dummy_property_map>::reference) const\n    { return graph_traits<Graph>::null_vertex(); }\n\n    bool has_suitable_vertex() const\n    {\n      if (!dist_queue.empty()) {\n        top_vertex = dist_queue.top();\n        if (get(distance_map, dist_queue.top()) <= min_out_distance)\n          return true;\n      }\n\n      if (!in_queue.empty()) {\n        top_vertex = in_queue.top();\n        return (get(distance_map, top_vertex)\n                - get(min_in_weight, top_vertex)) <= min_distance;\n      }\n      return false;\n    }\n\n  public:\n    void\n    receive_update(process_id_type source, vertex_descriptor vertex,\n                   distance_type distance)\n    {\n      // Update the queue if the received distance is better than\n      // the distance we know locally\n      if (distance < get(distance_map, vertex)\n          || (distance == get(distance_map, vertex)\n              && source == process_id(this->process_group))) {\n        // Update the local distance map\n        put(distance_map, vertex, distance);\n\n        bool is_in_queue = dist_queue.contains(vertex);\n\n        if (!is_in_queue) {\n          dist_queue.push(vertex);\n          out_queue.push(vertex);\n          in_queue.push(vertex);\n        }\n        else {\n          dist_queue.update(vertex);\n          out_queue.update(vertex);\n          in_queue.update(vertex);\n        }\n      }\n    }\n\n    void\n    receive_update(process_id_type source, vertex_descriptor vertex,\n                   std::pair<distance_type, vertex_descriptor> p)\n    {\n      if (p.first <= get(distance_map, vertex)) {\n        put(predecessor_map, vertex, p.second);\n        receive_update(source, vertex, p.first);\n      }\n    }\n\n  private:\n    dist_queue_type           dist_queue;\n    out_queue_type            out_queue;\n    in_queue_type             in_queue;\n    mutable value_type        top_vertex;\n    const Graph&              g;\n    DistanceMap               distance_map;\n    PredecessorMap            predecessor_map;\n    MinOutWeightMap           min_out_weight;\n    MinInWeightMap            min_in_weight;\n    distance_type             min_distance;\n    distance_type             min_out_distance;\n#ifdef PBGL_ACCOUNTING\n    std::size_t               local_deletions;\n#endif\n  };\n  /************************************************************************/\n\n  /************************************************************************\n   * Initialize the property map that contains the minimum incoming edge  *\n   * weight for each vertex. There are separate implementations for       *\n   * directed, bidirectional, and undirected graph.                       *\n   ************************************************************************/\n  template<typename Graph, typename MinInWeightMap, typename WeightMap,\n           typename Inf, typename Compare>\n  void\n  initialize_min_in_weights(const Graph& g, MinInWeightMap min_in_weight,\n                            WeightMap weight, Inf inf, Compare compare,\n                            directed_tag, incidence_graph_tag)\n  {\n    // Send minimum weights off to the owners\n    set_property_map_role(vertex_distance, min_in_weight);\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n        if (get(weight, e) < get(min_in_weight, target(e, g)))\n          put(min_in_weight, target(e, g), get(weight, e));\n      }\n    }\n\n    using boost::graph::parallel::process_group;\n    synchronize(process_group(g));\n\n    // Replace any infinities with zeros\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      if (get(min_in_weight, v) == inf) put(min_in_weight, v, 0);\n    }\n  }\n\n  template<typename Graph, typename MinInWeightMap, typename WeightMap,\n           typename Inf, typename Compare>\n  void\n  initialize_min_in_weights(const Graph& g, MinInWeightMap min_in_weight,\n                            WeightMap weight, Inf inf, Compare compare,\n                            directed_tag, bidirectional_graph_tag)\n  {\n#if 0\n    typename property_map<Graph, vertex_local_t>::const_type\n      local = get(vertex_local, g);\n\n    // This code assumes that the properties of the in-edges are\n    // available locally. This is not necessarily the case, so don't\n    // do this yet.\n    set_property_map_role(vertex_distance, min_in_weight);\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      if (in_edges(v, g).first != in_edges(v, g).second) {\n        std::cerr << \"weights(\" << g.distribution().global(get(local, v))\n                  << \") = \";\n        BGL_FORALL_INEDGES_T(v, e, g, Graph) {\n          std::cerr << get(weight, e) << ' ';\n        }\n        std::cerr << std::endl;\n        put(min_in_weight, v,\n            *std::min_element\n            (make_property_map_iterator(weight, in_edges(v, g).first),\n             make_property_map_iterator(weight, in_edges(v, g).second),\n             compare));\n      } else {\n        put(min_in_weight, v, 0);\n      }\n      std::cerr << \"miw(\" << g.distribution().global(get(local, v)) << \") = \"\n                << get(min_in_weight, v) << std::endl;\n    }\n#else\n    initialize_min_in_weights(g, min_in_weight, weight, inf, compare,\n                              directed_tag(), incidence_graph_tag());\n#endif\n  }\n\n  template<typename Graph, typename MinInWeightMap, typename WeightMap,\n           typename Inf, typename Compare>\n  inline void\n  initialize_min_in_weights(const Graph&, MinInWeightMap, WeightMap, Inf,\n                            Compare, undirected_tag, bidirectional_graph_tag)\n  {\n    // In weights are the same as out weights, so do nothing\n  }\n  /************************************************************************/\n\n\n  /************************************************************************\n   * Initialize the property map that contains the minimum outgoing edge  *\n   * weight for each vertex.                                              *\n   ************************************************************************/\n  template<typename Graph, typename MinOutWeightMap, typename WeightMap,\n           typename Compare>\n  void\n  initialize_min_out_weights(const Graph& g, MinOutWeightMap min_out_weight,\n                             WeightMap weight, Compare compare)\n  {\n    typedef typename property_traits<WeightMap>::value_type weight_type;\n\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      if (out_edges(v, g).first != out_edges(v, g).second) {\n        put(min_out_weight, v,\n            *std::min_element\n            (make_property_map_iterator(weight, out_edges(v, g).first),\n             make_property_map_iterator(weight, out_edges(v, g).second),\n             compare));\n        if (get(min_out_weight, v) < weight_type(0))\n            boost::throw_exception(negative_edge());\n      }\n    }\n  }\n\n  /************************************************************************/\n\n} // end namespace detail\n\ntemplate<typename DistributedGraph, typename DijkstraVisitor,\n         typename PredecessorMap, typename DistanceMap, typename WeightMap,\n         typename IndexMap, typename ColorMap, typename Compare,\n         typename Combine, typename DistInf, typename DistZero>\nvoid\ncrauser_et_al_shortest_paths\n  (const DistributedGraph& g,\n   typename graph_traits<DistributedGraph>::vertex_descriptor s,\n   PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n   IndexMap index_map, ColorMap color_map,\n   Compare compare, Combine combine, DistInf inf, DistZero zero,\n   DijkstraVisitor vis)\n{\n\n#ifdef PBGL_ACCOUNTING\n  crauser_et_al_shortest_paths_stats.deleted_vertices.clear();\n  crauser_et_al_shortest_paths_stats.execution_time = accounting::get_time();\n#endif\n\n  // Property map that stores the lowest edge weight outgoing from\n  // each vertex. If a vertex has no out-edges, the stored weight\n  // is zero.\n  typedef typename property_traits<WeightMap>::value_type weight_type;\n  typedef iterator_property_map<weight_type*, IndexMap> MinOutWeightMap;\n  std::vector<weight_type> min_out_weights_vec(num_vertices(g), inf);\n  MinOutWeightMap min_out_weight(&min_out_weights_vec.front(), index_map);\n  detail::initialize_min_out_weights(g, min_out_weight, weight, compare);\n\n  // Property map that stores the lowest edge weight incoming to\n  // each vertex. For undirected graphs, this will just be a\n  // shallow copy of the version for outgoing edges.\n  typedef typename graph_traits<DistributedGraph>::directed_category\n    directed_category;\n  const bool is_undirected =\n    is_same<directed_category, undirected_tag>::value;\n  typedef MinOutWeightMap MinInWeightMap;\n  std::vector<weight_type>\n    min_in_weights_vec(is_undirected? 1 : num_vertices(g), inf);\n  MinInWeightMap min_in_weight(&min_in_weights_vec.front(), index_map);\n  typedef typename graph_traits<DistributedGraph>::traversal_category\n    category;\n  detail::initialize_min_in_weights(g, min_in_weight, weight, inf, compare,\n                                    directed_category(), category());\n\n  // Initialize local portion of property maps\n  typename graph_traits<DistributedGraph>::vertex_iterator ui, ui_end;\n  for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n    put(distance, *ui, inf);\n    put(predecessor, *ui, *ui);\n  }\n  put(distance, s, zero);\n\n  // Dijkstra Queue\n  typedef detail::crauser_et_al_dijkstra_queue\n            <DistributedGraph, Combine, Compare, IndexMap, DistanceMap,\n             PredecessorMap, MinOutWeightMap, MinInWeightMap>\n    Queue;\n\n  Queue Q(g, combine, compare, index_map, distance, predecessor,\n          min_out_weight, is_undirected? min_out_weight : min_in_weight);\n\n  // Parallel Dijkstra visitor\n  ::boost::detail::dijkstra_bfs_visitor<\n      DijkstraVisitor, Queue, WeightMap,\n      boost::parallel::caching_property_map<PredecessorMap>,\n      boost::parallel::caching_property_map<DistanceMap>, Combine, Compare\n    > bfs_vis(vis, Q, weight,\n              boost::parallel::make_caching_property_map(predecessor),\n              boost::parallel::make_caching_property_map(distance),\n              combine, compare, zero);\n\n  set_property_map_role(vertex_color, color_map);\n  set_property_map_role(vertex_distance, distance);\n\n  breadth_first_search(g, s, Q, bfs_vis, color_map);\n\n#ifdef PBGL_ACCOUNTING\n  crauser_et_al_shortest_paths_stats.execution_time =\n    accounting::get_time() - crauser_et_al_shortest_paths_stats.execution_time;\n#endif\n}\n\ntemplate<typename DistributedGraph, typename PredecessorMap,\n         typename DistanceMap, typename WeightMap>\nvoid\ncrauser_et_al_shortest_paths\n  (const DistributedGraph& g,\n   typename graph_traits<DistributedGraph>::vertex_descriptor s,\n   PredecessorMap predecessor, DistanceMap distance, WeightMap weight)\n{\n  typedef typename property_traits<DistanceMap>::value_type distance_type;\n\n  std::vector<default_color_type> colors(num_vertices(g), white_color);\n\n  crauser_et_al_shortest_paths(g, s, predecessor, distance, weight,\n                               get(vertex_index, g),\n                               make_iterator_property_map(&colors[0],\n                                                          get(vertex_index, g)),\n                               std::less<distance_type>(),\n                               closed_plus<distance_type>(),\n                               (std::numeric_limits<distance_type>::max)(),\n                               distance_type(),\n                               dijkstra_visitor<>());\n}\n\ntemplate<typename DistributedGraph, typename PredecessorMap,\n         typename DistanceMap>\nvoid\ncrauser_et_al_shortest_paths\n  (const DistributedGraph& g,\n   typename graph_traits<DistributedGraph>::vertex_descriptor s,\n   PredecessorMap predecessor, DistanceMap distance)\n{\n  crauser_et_al_shortest_paths(g, s, predecessor, distance,\n                               get(edge_weight, g));\n}\n\n} // end namespace distributed\n\n#ifdef PBGL_ACCOUNTING\nusing distributed::crauser_et_al_shortest_paths_stats;\n#endif\n\nusing distributed::crauser_et_al_shortest_paths;\n\n\n} } // end namespace boost::graph\n\n#endif // BOOST_GRAPH_CRAUSER_ET_AL_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "04b2ace36675a87fe0d201522f8d2e7daf648e5f", "size": 25295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/graph/distributed/crauser_et_al_shortest_paths.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/graph/distributed/crauser_et_al_shortest_paths.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/graph/distributed/crauser_et_al_shortest_paths.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": 38.3839150228, "max_line_length": 101, "alphanum_fraction": 0.6285431904, "num_tokens": 5226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.027585281927004695, "lm_q1q2_score": 0.010313469976848092}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 15:16:03\n\n/**\n * @file MSSM_cxx_diagrams.hpp\n *\n * This file was generated at Thu 10 May 2018 15:16:03 with FlexibleSUSY\n * 2.0.1 and SARAH 4.12.2 .\n */\n\n#ifndef MSSM_CXXDIAGRAMS_H\n#define MSSM_CXXDIAGRAMS_H\n\n#include \"numerics2.hpp\"\n#include \"wrappers.hpp\"\n\n#include <array>\n#include <boost/range/join.hpp>\n#include <boost/mpl/vector_c.hpp>\n#include <boost/fusion/adapted/mpl.hpp>\n#include <boost/fusion/include/vector.hpp>\n#include <boost/fusion/adapted/boost_array.hpp>\n#include <boost/array.hpp>\n\n#include <boost/version.hpp>\n\n#if BOOST_VERSION >= 105800\n#include <boost/fusion/include/move.hpp>\n#else\n#include <boost/fusion/include/copy.hpp>\n#endif\n\n#define INPUTPARAMETER(p) context.model.get_input().p\n#define MODELPARAMETER(p) context.model.get_##p()\n#define DERIVEDPARAMETER(p) context.model.p()\n#define PHASE(p) context.model.get_##p()\n\nnamespace flexiblesusy {\nnamespace cxx_diagrams {\nnamespace impl {\n/** \\brief Helper template for make_array\n */\ntemplate<class ForwardIterator, std::size_t N, class T>\nstruct make_array_it {\n   using decayed_type = typename std::decay<\n                        typename std::iterator_traits<ForwardIterator>::value_type\n                        >::type;\n   static constexpr bool use_cast = !std::is_same<decayed_type, T>::value;\n\n   template<class... Args>\n   static auto iterate(ForwardIterator begin, Args &&...args)\n   -> typename std::enable_if<\n   !use_cast,\n   std::array<T, N + sizeof...(Args)>\n   >::type {\n      ForwardIterator copy(begin);\n      return make_array_it<ForwardIterator, N-1, T>::iterate(++begin,\n            std::forward<Args>(args)..., *copy);\n   }\n\n   template<class... Args>\n   static auto iterate(ForwardIterator begin, Args &&...args)\n   -> typename std::enable_if<\n   use_cast,\n   std::array<T, N + sizeof...(Args)>\n   >::type {\n      ForwardIterator copy(begin);\n      return make_array_it<ForwardIterator, N-1, T>::iterate(++begin,\n            std::forward<Args>(args)..., T(*copy));\n   }\n};\n\n/** \\brief Specialized helper template for make_array */\ntemplate<class ForwardIterator, class T>\nstruct make_array_it<ForwardIterator, 0, T> {\n   template<class... Args>\n   static auto iterate(ForwardIterator /* begin */, Args &&...args)\n   -> std::array<T, sizeof...(Args)> {\n      return std::array<T, sizeof...(Args)>{ std::forward<Args>(args)... };\n   }\n};\n\n/** \\class make_array\n * \\brief Facility for easy construction of \\a std::array\n *        objects.\n * \\tparam N The size of the to be constructed array\n * \\tparam T The type of the objects the array should hold\n *           or void (by default) if the type should be\n *           inferred.\n */\ntemplate<std::size_t N, class T = void>\nstruct make_array {\n   /** \\brief Construct a \\a std::array by copying values\n    *         from a range.\n    * \\tparam ForwardIterator The iterator type (usually inferred)\n    * \\param[in] begin The iterator marking the beginning of\n    *                  the range to be copied.\n    * \\returns A \\a std::array holding the desired objects.\n    * \\warning \\a begin must be incrementable sufficiently\n    *          often (\\a N times) otherwise the behaviour\n    *          is undefined.\n    */\n   template<class ForwardIterator>\n   static auto iterate(ForwardIterator begin)\n   -> std::array<typename std::conditional<\n   std::is_void<T>::value,\n       typename std::iterator_traits<ForwardIterator>::value_type,\n       T\n   >::type, N> {\n      using value_type = typename std::conditional<\n      std::is_void<T>::value,\n      typename std::iterator_traits<ForwardIterator>::value_type,\n      T\n      >::type;\n\n      return make_array_it<ForwardIterator, N, value_type>::iterate(begin);\n   }\n};\n\ntemplate<class Array1, class Array2>\nauto concatenate(const Array1& a1, const Array2& a2)\n-> std::array<\ntypename std::common_type<\ntypename Array1::value_type,\n         typename Array1::value_type\n         >::type,\n         std::tuple_size<Array1>::value + std::tuple_size<Array2>::value>\n         {\n            using value_type = typename std::common_type<\n                               typename Array1::value_type,\n            typename Array1::value_type\n            >::type;\n            constexpr auto size = std::tuple_size<Array1>::value + std::tuple_size<Array2>::value;\n\n            auto range1 = boost::make_iterator_range(boost::begin(a1),\n                          boost::end(a1));\n            auto range2 = boost::make_iterator_range(boost::begin(a2),\n                          boost::end(a2));\n            auto joined = boost::join(range1, range2);\n\n            return make_array<size, value_type>::iterate(boost::begin(joined));\n         }\n\n         /**\n          * @class IndexBounds<N>\n          * @brief A class representing multiple (N) index ranges.\n          *\n          * N is a non-negative integer.\n          * The ranges are specified the c++ way; The range begins are inclusive\n          * and the range ends are exclusive. Misspecified ranges result in\n          * undefined behaviour!\n          * The intended use is to iterate over an IndexBounds<N> using the normal\n          * begin()/end() syntax, which will iterate over every possible combination\n          * of the indices within their respective ranges.\n          * The ranges are const! Once they are initialized they cannot be changed.\n          * Initialization is done like = {{ beg1, beg2, ... }, { end1, end2, ... }}\n          */\n         template<int N> struct IndexBounds;\n\n/**\n * @class IndexIterator<N>\n * @brief The iterator class used by IndexBounds<N>.\n *\n * It only fulfils the input iterator requirements!\n * The value_type is a const std::array<int, N>\n * containing the current indices.\n * Incrementing the iterator results in a new index combination.\n */\ntemplate<int N> struct IndexIterator {\n   using difference_type = typename std::array<int, N>::difference_type;\n   using value_type = int;\n   using pointer = int*;\n   using reference = int&;\n   using iterator_category = std::input_iterator_tag;\n\n   friend class IndexBounds<N>;\nprivate:\n   const IndexBounds<N>& bounds;\n   std::array<int, N> indices;\n\n   IndexIterator(const IndexBounds<N>& b, std::array<int, N>&& i)\n      : bounds(b), indices(std::move(i)) {}\npublic:\n   const std::array<int, N>& operator*() const\n   {\n      return indices;\n   }\n\n   const std::array<int, N>* operator->() const\n   {\n      return &indices;\n   }\n\n   IndexIterator& operator++()\n   {\n      for (int i = 0; i != N; i++) {\n         indices[i]++;\n         if (indices[i] == bounds.indexEnd[i]) {\n            indices[i] = bounds.indexBegin[i];\n            continue;\n         }\n\n         return *this;\n      }\n\n      indices = make_array<N>::iterate(bounds.indexEnd);\n      return *this;\n   }\n\n   IndexIterator operator++(int)\n   {\n      IndexIterator it(*this);\n      this->operator++();\n      return it;\n   }\n\n   template<int M>\n   friend bool operator==(const IndexIterator<M>& it1, const IndexIterator<M>& it2);\n};\n\ntemplate<int N>\nbool operator==(const IndexIterator<N>& it1, const IndexIterator<N>& it2)\n{\n   return it1.indices == it2.indices;\n}\n\ntemplate<int N>\nbool operator!=(const IndexIterator<N>& it1, const IndexIterator<N>& it2)\n{\n   return !(it1 == it2);\n}\n\ntemplate<int N> struct IndexBounds {\n   typedef const std::array<int, N> indices_type;\n\n   int indexBegin[N];\n   int indexEnd[N];\n\n   typedef IndexIterator<N> const_iterator;\n\n   const_iterator begin() const\n   {\n      return const_iterator(*this, make_array<N>::iterate(indexBegin));\n   }\n\n   const_iterator end() const\n   {\n      return const_iterator(*this, make_array<N>::iterate(indexEnd));\n   }\n};\n\ntemplate<> struct IndexBounds<0> {\n   using indices_type = const std::array<int, 0>;\n   using const_iterator = indices_type*;\n\n   const indices_type dummyIndex = {};\n\n   const_iterator begin() const\n   {\n      return &dummyIndex;\n   }\n   const_iterator end() const\n   {\n      return (begin()+1);\n   }\n};\n\n} // namespace impl\n\n// Lorentz conjugate fermions\ntemplate<class Field> struct bar {\n   static constexpr int numberOfGenerations = Field::numberOfGenerations;\n   static constexpr int numberOfFieldIndices = Field::numberOfFieldIndices;\n   using smFlags = typename Field::smFlags;\n\n   static constexpr double electric_charge = - Field::electric_charge;\n\n   using type = bar<Field>;\n   using lorentz_conjugate = Field;\n};\n\n// Lorentz conjugate bosons\ntemplate<class Field> struct conj {\n   static constexpr int numberOfGenerations = Field::numberOfGenerations;\n   static constexpr int numberOfFieldIndices = Field::numberOfFieldIndices;\n   using smFlags = typename Field::smFlags;\n\n   static constexpr double electric_charge = - Field::electric_charge;\n\n   using type = conj<Field>;\n   using lorentz_conjugate = Field;\n};\n\n// Double Lorentz conjugation\ntemplate<class Field> struct bar<bar<Field>> {\n   using type = Field;\n};\ntemplate<class Field> struct conj<conj<Field>> {\n   using type = Field;\n};\n\n// Remove Lorentz conjugation\ntemplate<class Field> struct remove_lorentz_conjugation {\n   using type = Field;\n};\n\ntemplate<class Field> struct remove_lorentz_conjugation<bar<Field>> {\n   using type = Field;\n};\n\ntemplate<class Field> struct remove_lorentz_conjugation<conj<Field>> {\n   using type = Field;\n};\n\n\n// Declare a type that can hold the field indices for any given field\ntemplate<class Field> struct field_indices {\n   using type = std::array<int, Field::numberOfFieldIndices>;\n};\n\ntemplate<class Field>\ntypename std::enable_if<Field::numberOfGenerations != 1, bool>::type\nisSMField(const typename field_indices<Field>::type& indices)\n{\n   boost::array<bool,Field::numberOfGenerations> smFlags;\n\n#if BOOST_VERSION >= 105800\n   boost::fusion::move(typename Field::smFlags(), smFlags);\n#else\n   boost::fusion::copy(typename Field::smFlags(), smFlags);\n#endif\n\n   return smFlags[indices[0]];\n}\n\ntemplate<class Field>\ntypename std::enable_if<Field::numberOfGenerations == 1, bool>::type\nisSMField(const typename field_indices<Field>::type& /* indices */)\n{\n   return boost::mpl::at_c<typename Field::smFlags,0>::type::value;\n}\n\nstruct VG {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = VG;\n};\n\nstruct gG {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = bar<gG>::type;\n};\n\nstruct Glu {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = Glu;\n};\n\nstruct Fv {\n   static constexpr int numberOfGenerations = 3;\n   using smFlags = boost::mpl::vector_c<bool, true, true, true>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = bar<Fv>::type;\n};\n\nstruct VP {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 0;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = VP;\n};\n\nstruct VZ {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 0;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = VZ;\n};\n\nstruct gP {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 0;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = bar<gP>::type;\n};\n\nstruct gZ {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 0;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = bar<gZ>::type;\n};\n\nstruct gWm {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 0;\n   static constexpr double electric_charge = -1;\n   using lorentz_conjugate = bar<gWm>::type;\n};\n\nstruct gWmC {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 0;\n   static constexpr double electric_charge = 1;\n   using lorentz_conjugate = bar<gWmC>::type;\n};\n\nstruct Sd {\n   static constexpr int numberOfGenerations = 6;\n   using smFlags = boost::mpl::vector_c<bool, false, false, false, false, false, false>;\n   static constexpr int numberOfFieldIndices = 2;\n   static constexpr double electric_charge = -0.3333333333333333;\n   using lorentz_conjugate = conj<Sd>::type;\n};\n\nstruct Sv {\n   static constexpr int numberOfGenerations = 3;\n   using smFlags = boost::mpl::vector_c<bool, false, false, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = conj<Sv>::type;\n};\n\nstruct Su {\n   static constexpr int numberOfGenerations = 6;\n   using smFlags = boost::mpl::vector_c<bool, false, false, false, false, false, false>;\n   static constexpr int numberOfFieldIndices = 2;\n   static constexpr double electric_charge = 0.6666666666666666;\n   using lorentz_conjugate = conj<Su>::type;\n};\n\nstruct Se {\n   static constexpr int numberOfGenerations = 6;\n   using smFlags = boost::mpl::vector_c<bool, false, false, false, false, false, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = -1;\n   using lorentz_conjugate = conj<Se>::type;\n};\n\nstruct hh {\n   static constexpr int numberOfGenerations = 2;\n   using smFlags = boost::mpl::vector_c<bool, false, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = hh;\n};\n\nstruct Ah {\n   static constexpr int numberOfGenerations = 2;\n   using smFlags = boost::mpl::vector_c<bool, false, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = Ah;\n};\n\nstruct Hpm {\n   static constexpr int numberOfGenerations = 2;\n   using smFlags = boost::mpl::vector_c<bool, false, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = -1;\n   using lorentz_conjugate = conj<Hpm>::type;\n};\n\nstruct Chi {\n   static constexpr int numberOfGenerations = 4;\n   using smFlags = boost::mpl::vector_c<bool, false, false, false, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = 0;\n   using lorentz_conjugate = Chi;\n};\n\nstruct Cha {\n   static constexpr int numberOfGenerations = 2;\n   using smFlags = boost::mpl::vector_c<bool, false, false>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = -1;\n   using lorentz_conjugate = bar<Cha>::type;\n};\n\nstruct Fe {\n   static constexpr int numberOfGenerations = 3;\n   using smFlags = boost::mpl::vector_c<bool, true, true, true>;\n   static constexpr int numberOfFieldIndices = 1;\n   static constexpr double electric_charge = -1;\n   using lorentz_conjugate = bar<Fe>::type;\n};\n\nstruct Fd {\n   static constexpr int numberOfGenerations = 3;\n   using smFlags = boost::mpl::vector_c<bool, true, true, true>;\n   static constexpr int numberOfFieldIndices = 2;\n   static constexpr double electric_charge = -0.3333333333333333;\n   using lorentz_conjugate = bar<Fd>::type;\n};\n\nstruct Fu {\n   static constexpr int numberOfGenerations = 3;\n   using smFlags = boost::mpl::vector_c<bool, true, true, true>;\n   static constexpr int numberOfFieldIndices = 2;\n   static constexpr double electric_charge = 0.6666666666666666;\n   using lorentz_conjugate = bar<Fu>::type;\n};\n\nstruct VWm {\n   static constexpr int numberOfGenerations = 1;\n   using smFlags = boost::mpl::vector_c<bool, true>;\n   static constexpr int numberOfFieldIndices = 0;\n   static constexpr double electric_charge = -1;\n   using lorentz_conjugate = conj<VWm>::type;\n};\n\n// Named fields\nusing Photon = VP;\nusing Electron = Fe;\n\n// Fields that are their own Lorentz conjugates.\ntemplate<> struct conj<VG> { using type = VG; };\ntemplate<> struct bar<Glu> { using type = Glu; };\ntemplate<> struct conj<VP> { using type = VP; };\ntemplate<> struct conj<VZ> { using type = VZ; };\ntemplate<> struct conj<hh> { using type = hh; };\ntemplate<> struct conj<Ah> { using type = Ah; };\ntemplate<> struct bar<Chi> { using type = Chi; };\n\n\n\n/**\n* @class SingleComponentedVertex\n* @brief A vertex whose value can be represented by a single complex number\n*/\nclass SingleComponentedVertex {\nprivate:\n   std::complex<double> val; ///< The value\npublic:\n   SingleComponentedVertex(std::complex<double> v)\n      : val(v) {}\n\n   /**\n   * @fn value\n   * @brief Returns the value of the vertex.\n   */\n   std::complex<double> value() const\n   {\n      return val;\n   }\n\n   /**\n   * @fn isZero\n   * @brief Tests whether the value is numerically significant\n   */\n   bool isZero() const\n   {\n      return (is_zero(val.real()) && is_zero(val.imag()));\n   }\n};\n\n/**\n* @class LeftAndRightComponentedVertex\n* @brief A vertex whose value can be represented by two complex numbers\n*/\nclass LeftAndRightComponentedVertex {\nprivate:\n   std::pair<std::complex<double>, std::complex<double>> value;  ///< The values\npublic:\n   LeftAndRightComponentedVertex(const std::complex<double>& left,\n                                 const std::complex<double>& right)\n      : value(left, right) {}\n\n   /**\n   * @fn left\n   * @brief Returns the left component of the vertex.\n   */\n   std::complex<double> left() const\n   {\n      return value.first;\n   }\n\n   /**\n   * @fn right\n   * @brief Returns the left component of the vertex.\n   */\n   std::complex<double> right() const\n   {\n      return value.second;\n   }\n\n   /**\n   * @fn isZero\n   * @brief Tests whether the values are numerically significant\n   */\n   bool isZero() const\n   {\n      return (is_zero(value.first.real()) && is_zero(value.first.imag()) &&\n              is_zero(value.second.real()) && is_zero(value.second.imag()));\n   }\n};\n\n/**\n * @class VertexData<F...>\n * @brief VertexData data for a vertex with the fields specified by F....\n */\ntemplate<class ...Fields> struct VertexData;\n\nstruct EvaluationContext;\n\n/**\n * @class Vertex<F...>\n * @brief A template that represents a vertex with open field indices.\n *\n * All elements in F... have to be publicly derived from Field.\n * To obtain a conrete value, use the static member function evaluate()\n * along with the desired field indices.\n */\ntemplate<class ...F> class Vertex {\n   using Data = VertexData<F...>;\n   using bounds_type = typename std::decay<decltype(Data::index_bounds)>::type;\npublic:\n   using vertex_type = typename Data::vertex_type;\n   using indices_type = typename decltype(Data::index_bounds)::indices_type;\n\n   static constexpr bounds_type index_bounds = Data::index_bounds;\n\n   /**\n    * @fn fieldIndices\n    * @brief Returns the subset of indices belonging to\n    *        a field at a given index.\n    * @param indices The complete set of indices for all fields\n    *\n    * The field indexing is in the same order as the template arguments\n    * and starts at 0.\n    */\n   template<int fieldIndex>\n   static\n   std::array<int, Data::fieldIndexStart[fieldIndex+1] - Data::fieldIndexStart[fieldIndex]>\n   fieldIndices(const indices_type& indices)\n   {\n      constexpr auto length = Data::fieldIndexStart[fieldIndex+1] - Data::fieldIndexStart[fieldIndex];\n      constexpr auto offset = Data::fieldIndexStart[fieldIndex];\n      auto begin = indices.begin() + offset;\n      return impl::make_array<length>::iterate(begin);\n   }\n\n   /**\n    * @fn vertex\n    * @brief Calculates the vertex for a given set of field indices.\n    * @param indices The field indices\n    * @param context The evaluation context\n    */\n   static vertex_type evaluate(const indices_type& indices, const EvaluationContext& context);\n};\n\n\n/**\n* @class EvaluationContext\n* @brief Represents an evaluation context.\n*\n* It simply contains a reference to a model object.\n* All computational functions are forwarded to that object,\n* e.g. mass calculation functions.\n*/\nstruct EvaluationContext {\n   MSSM_mass_eigenstates& model; ///< The model object.\n\n   template<class Field>\n   double mass(const typename field_indices<Field>::type& indices) const\n   {\n      using CleanField = typename remove_lorentz_conjugation<Field>::type;\n      return mass_impl<CleanField>(indices);\n   }\n\nprivate:\n   template<class Field>\n   double mass_impl(const typename field_indices<Field>::type& indices) const;\n};\n\n\ntemplate<> struct VertexData<bar<Fe>::type, Ah, Fe>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 2, 3 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<Fe, Ah, bar<Fe>::type>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 2, 3 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<VP, bar<Fe>::type, Fe>\n{\n   static constexpr impl::IndexBounds<2> index_bounds = { { 0, 0 }, { 3, 3 } };\n   static constexpr int fieldIndexStart[4] = { 0, 0, 1, 2 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<bar<Fe>::type, Chi, Se>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 4, 6 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<Fe, Chi, conj<Se>::type>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 4, 6 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<VP, conj<Se>::type, Se>\n{\n   static constexpr impl::IndexBounds<2> index_bounds = { { 0, 0 }, { 6, 6 } };\n   static constexpr int fieldIndexStart[4] = { 0, 0, 1, 2 };\n   using vertex_type = SingleComponentedVertex;\n};\n\ntemplate<> struct VertexData<bar<Fe>::type, Fv, Hpm>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 3, 2 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<Fe, bar<Fv>::type, conj<Hpm>::type>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 3, 2 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<VP, conj<Hpm>::type, Hpm>\n{\n   static constexpr impl::IndexBounds<2> index_bounds = { { 0, 0 }, { 2, 2 } };\n   static constexpr int fieldIndexStart[4] = { 0, 0, 1, 2 };\n   using vertex_type = SingleComponentedVertex;\n};\n\ntemplate<> struct VertexData<bar<Fe>::type, hh, Fe>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 2, 3 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<Fe, hh, bar<Fe>::type>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 2, 3 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<bar<Fe>::type, Sv, Cha>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 3, 2 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<Fe, conj<Sv>::type, bar<Cha>::type>\n{\n   static constexpr impl::IndexBounds<3> index_bounds = { { 0, 0, 0 }, { 3, 3, 2 } };\n   static constexpr int fieldIndexStart[4] = { 0, 1, 2, 3 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\ntemplate<> struct VertexData<VP, bar<Cha>::type, Cha>\n{\n   static constexpr impl::IndexBounds<2> index_bounds = { { 0, 0 }, { 2, 2 } };\n   static constexpr int fieldIndexStart[4] = { 0, 0, 1, 2 };\n   using vertex_type = LeftAndRightComponentedVertex;\n};\n\n\ntemplate<> inline\nVertex<bar<Fe>::type, Ah, Fe>::vertex_type\nVertex<bar<Fe>::type, Ah, Fe>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZEL = MODELPARAMETER(ZEL);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZA = MODELPARAMETER(ZA);\n\n   const std::complex<double> left = std::complex<double>(0.,-0.7071067811865475)*SUM(j2,0,2,Conj(ZEL(gt3,j2))*SUM(j1,0,2,Conj(ZER(gt1,j1))*Ye(j1,j2)))*ZA(gt2,0);\n\n   const std::complex<double> right = std::complex<double>(0.,0.7071067811865475)*SUM(j2,0,2,SUM(j1,0,2,Conj(Ye(j1,j2))*ZER(gt3,j1))*ZEL(gt1,j2))*ZA(gt2,0);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<Fe, Ah, bar<Fe>::type>::vertex_type\nVertex<Fe, Ah, bar<Fe>::type>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZEL = MODELPARAMETER(ZEL);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZA = MODELPARAMETER(ZA);\n\n   const std::complex<double> left = std::complex<double>(0.,-0.7071067811865475)*SUM(j2,0,2,Conj(ZEL(gt1,j2))*SUM(j1,0,2,Conj(ZER(gt3,j1))*Ye(j1,j2)))*ZA(gt2,0);\n\n   const std::complex<double> right = std::complex<double>(0.,0.7071067811865475)*SUM(j2,0,2,SUM(j1,0,2,Conj(Ye(j1,j2))*ZER(gt1,j1))*ZEL(gt3,j2))*ZA(gt2,0);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<VP, bar<Fe>::type, Fe>::vertex_type\nVertex<VP, bar<Fe>::type, Fe>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt2 = indices[0];\n   const int gt3 = indices[1];\n   const auto g1 = MODELPARAMETER(g1);\n   const auto g2 = MODELPARAMETER(g2);\n   const auto ThetaW = DERIVEDPARAMETER(ThetaW);\n\n   const std::complex<double> left = 0.5*KroneckerDelta(gt2,gt3)*(0.7745966692414834*g1*Cos(ThetaW) + g2*Sin(ThetaW));\n\n   const std::complex<double> right = 0.7745966692414834*g1*Cos(ThetaW)*KroneckerDelta(gt2,gt3);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<bar<Fe>::type, Chi, Se>::vertex_type\nVertex<bar<Fe>::type, Chi, Se>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto g1 = MODELPARAMETER(g1);\n   const auto g2 = MODELPARAMETER(g2);\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZN = MODELPARAMETER(ZN);\n   const auto ZE = MODELPARAMETER(ZE);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZEL = MODELPARAMETER(ZEL);\n\n   const std::complex<double> left = -1.0954451150103321*g1*Conj(ZN(gt2,0))*SUM(j1,0,2,Conj(ZE(gt3,3 + j1))*Conj(ZER(gt1,j1))) - Conj(ZN(gt2,2))*SUM(j2,0,2,Conj(ZE(gt3,j2))*SUM(j1,0,2,Conj(ZER(gt1,j1))*Ye(j1,j2)));\n\n   const std::complex<double> right = 0.7071067811865475*SUM(j1,0,2,Conj(ZE(gt3,j1))*ZEL(gt1,j1))*(0.7745966692414834*g1*ZN(gt2,0) + g2*ZN(gt2,1)) - SUM(j2,0,2,SUM(j1,0,2,Conj(Ye(j1,j2))*Conj(ZE(gt3,3 + j1)))*ZEL(gt1,j2))*ZN(gt2,2);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<Fe, Chi, conj<Se>::type>::vertex_type\nVertex<Fe, Chi, conj<Se>::type>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto g1 = MODELPARAMETER(g1);\n   const auto g2 = MODELPARAMETER(g2);\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZN = MODELPARAMETER(ZN);\n   const auto ZEL = MODELPARAMETER(ZEL);\n   const auto ZE = MODELPARAMETER(ZE);\n   const auto ZER = MODELPARAMETER(ZER);\n\n   const std::complex<double> left = 0.5477225575051661*g1*Conj(ZN(gt2,0))*SUM(j1,0,2,Conj(ZEL(gt1,j1))*ZE(gt3,j1)) + 0.7071067811865475*g2*Conj(ZN(gt2,1))*SUM(j1,0,2,Conj(ZEL(gt1,j1))*ZE(gt3,j1)) - Conj(ZN(gt2,2))*SUM(j2,0,2,Conj(ZEL(gt1,j2))*SUM(j1,0,2,Ye(j1,j2)*ZE(gt3,3 + j1)));\n\n   const std::complex<double> right = -1.0954451150103321*g1*SUM(j1,0,2,ZE(gt3,3 + j1)*ZER(gt1,j1))*ZN(gt2,0) - SUM(j2,0,2,SUM(j1,0,2,Conj(Ye(j1,j2))*ZER(gt1,j1))*ZE(gt3,j2))*ZN(gt2,2);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<VP, conj<Se>::type, Se>::vertex_type\nVertex<VP, conj<Se>::type, Se>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt2 = indices[0];\n   const int gt3 = indices[1];\n   const auto g1 = MODELPARAMETER(g1);\n   const auto g2 = MODELPARAMETER(g2);\n   const auto ZE = MODELPARAMETER(ZE);\n   const auto ThetaW = DERIVEDPARAMETER(ThetaW);\n\n   const std::complex<double> result = -0.5*(0.7745966692414834*g1*Cos(ThetaW) + g2*Sin(ThetaW))*SUM(j1,0,2,Conj(ZE(gt3,j1))*ZE(gt2,j1)) - 0.7745966692414834*g1*Cos(ThetaW)*SUM(j1,0,2,Conj(ZE(gt3,3 + j1))*ZE(gt2,3 + j1));\n\n   return vertex_type(result);\n}\n\ntemplate<> inline\nVertex<bar<Fe>::type, Fv, Hpm>::vertex_type\nVertex<bar<Fe>::type, Fv, Hpm>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZP = MODELPARAMETER(ZP);\n\n   const std::complex<double> left = SUM(j1,0,2,Conj(ZER(gt1,j1))*Ye(j1,gt2))*ZP(gt3,0);\n\n   const std::complex<double> right = 0;\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<Fe, bar<Fv>::type, conj<Hpm>::type>::vertex_type\nVertex<Fe, bar<Fv>::type, conj<Hpm>::type>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZP = MODELPARAMETER(ZP);\n\n   const std::complex<double> left = 0;\n\n   const std::complex<double> right = SUM(j1,0,2,Conj(Ye(j1,gt2))*ZER(gt1,j1))*ZP(gt3,0);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<VP, conj<Hpm>::type, Hpm>::vertex_type\nVertex<VP, conj<Hpm>::type, Hpm>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt2 = indices[0];\n   const int gt3 = indices[1];\n   const auto g1 = MODELPARAMETER(g1);\n   const auto g2 = MODELPARAMETER(g2);\n   const auto ThetaW = DERIVEDPARAMETER(ThetaW);\n\n   const std::complex<double> result = -0.5*KroneckerDelta(gt2,gt3)*(0.7745966692414834*g1*Cos(ThetaW) + g2*Sin(ThetaW));\n\n   return vertex_type(result);\n}\n\ntemplate<> inline\nVertex<bar<Fe>::type, hh, Fe>::vertex_type\nVertex<bar<Fe>::type, hh, Fe>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZEL = MODELPARAMETER(ZEL);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZH = MODELPARAMETER(ZH);\n\n   const std::complex<double> left = -0.7071067811865475*SUM(j2,0,2,Conj(ZEL(gt3,j2))*SUM(j1,0,2,Conj(ZER(gt1,j1))*Ye(j1,j2)))*ZH(gt2,0);\n\n   const std::complex<double> right = -0.7071067811865475*SUM(j2,0,2,SUM(j1,0,2,Conj(Ye(j1,j2))*ZER(gt3,j1))*ZEL(gt1,j2))*ZH(gt2,0);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<Fe, hh, bar<Fe>::type>::vertex_type\nVertex<Fe, hh, bar<Fe>::type>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto ZEL = MODELPARAMETER(ZEL);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZH = MODELPARAMETER(ZH);\n\n   const std::complex<double> left = -0.7071067811865475*SUM(j2,0,2,Conj(ZEL(gt1,j2))*SUM(j1,0,2,Conj(ZER(gt3,j1))*Ye(j1,j2)))*ZH(gt2,0);\n\n   const std::complex<double> right = -0.7071067811865475*SUM(j2,0,2,SUM(j1,0,2,Conj(Ye(j1,j2))*ZER(gt1,j1))*ZEL(gt3,j2))*ZH(gt2,0);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<bar<Fe>::type, Sv, Cha>::vertex_type\nVertex<bar<Fe>::type, Sv, Cha>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto g2 = MODELPARAMETER(g2);\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto UM = MODELPARAMETER(UM);\n   const auto ZV = MODELPARAMETER(ZV);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto ZEL = MODELPARAMETER(ZEL);\n   const auto UP = MODELPARAMETER(UP);\n\n   const std::complex<double> left = Conj(UM(gt3,1))*SUM(j2,0,2,Conj(ZV(gt2,j2))*SUM(j1,0,2,Conj(ZER(gt1,j1))*Ye(j1,j2)));\n\n   const std::complex<double> right = -(g2*SUM(j1,0,2,Conj(ZV(gt2,j1))*ZEL(gt1,j1))*UP(gt3,0));\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<Fe, conj<Sv>::type, bar<Cha>::type>::vertex_type\nVertex<Fe, conj<Sv>::type, bar<Cha>::type>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt1 = indices[0];\n   const int gt2 = indices[1];\n   const int gt3 = indices[2];\n   const auto g2 = MODELPARAMETER(g2);\n   const auto Ye = MODELPARAMETER(Ye);\n   const auto UP = MODELPARAMETER(UP);\n   const auto ZEL = MODELPARAMETER(ZEL);\n   const auto ZV = MODELPARAMETER(ZV);\n   const auto ZER = MODELPARAMETER(ZER);\n   const auto UM = MODELPARAMETER(UM);\n\n   const std::complex<double> left = -(g2*Conj(UP(gt3,0))*SUM(j1,0,2,Conj(ZEL(gt1,j1))*ZV(gt2,j1)));\n\n   const std::complex<double> right = SUM(j2,0,2,SUM(j1,0,2,Conj(Ye(j1,j2))*ZER(gt1,j1))*ZV(gt2,j2))*UM(gt3,1);\n\n   return vertex_type(left, right);\n}\n\ntemplate<> inline\nVertex<VP, bar<Cha>::type, Cha>::vertex_type\nVertex<VP, bar<Cha>::type, Cha>::evaluate(const indices_type& indices, const EvaluationContext& context)\n{\n   const int gt2 = indices[0];\n   const int gt3 = indices[1];\n   const auto g2 = MODELPARAMETER(g2);\n   const auto g1 = MODELPARAMETER(g1);\n   const auto UM = MODELPARAMETER(UM);\n   const auto UP = MODELPARAMETER(UP);\n   const auto ThetaW = DERIVEDPARAMETER(ThetaW);\n\n   const std::complex<double> left = g2*Conj(UM(gt3,0))*Sin(ThetaW)*UM(gt2,0) + 0.5*Conj(UM(gt3,1))*(0.7745966692414834*g1*Cos(ThetaW) + g2*Sin(ThetaW))*UM(gt2,1);\n\n   const std::complex<double> right = g2*Conj(UP(gt2,0))*Sin(ThetaW)*UP(gt3,0) + 0.5*Conj(UP(gt2,1))*(0.7745966692414834*g1*Cos(ThetaW) + g2*Sin(ThetaW))*UP(gt3,1);\n\n   return vertex_type(left, right);\n}\n\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<VG>(const std::array<int, 1>& indices) const\n{ return model.get_MVG(); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Glu>(const std::array<int, 1>& indices) const\n{ return model.get_MGlu(); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Fv>(const std::array<int, 1>& indices) const\n{ return model.get_MFv(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<VP>(const std::array<int, 0>& indices) const\n{ return model.get_MVP(); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<VZ>(const std::array<int, 0>& indices) const\n{ return model.get_MVZ(); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Sd>(const std::array<int, 2>& indices) const\n{ return model.get_MSd(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Sv>(const std::array<int, 1>& indices) const\n{ return model.get_MSv(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Su>(const std::array<int, 2>& indices) const\n{ return model.get_MSu(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Se>(const std::array<int, 1>& indices) const\n{ return model.get_MSe(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<hh>(const std::array<int, 1>& indices) const\n{ return model.get_Mhh(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Ah>(const std::array<int, 1>& indices) const\n{ return model.get_MAh(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Hpm>(const std::array<int, 1>& indices) const\n{ return model.get_MHpm(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Chi>(const std::array<int, 1>& indices) const\n{ return model.get_MChi(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Cha>(const std::array<int, 1>& indices) const\n{ return model.get_MCha(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Fe>(const std::array<int, 1>& indices) const\n{ return model.get_MFe(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Fd>(const std::array<int, 2>& indices) const\n{ return model.get_MFd(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<Fu>(const std::array<int, 2>& indices) const\n{ return model.get_MFu(indices[0]); }\n\ntemplate<> inline\ndouble EvaluationContext::mass_impl<VWm>(const std::array<int, 0>& indices) const\n{ return model.get_MVWm(); }\n\nnamespace impl {\n   static LeftAndRightComponentedVertex unit_charge(const EvaluationContext& context)\n   {\n      using vertex_type = LeftAndRightComponentedVertex;\n\n      std::array<int, 1> electron_indices = { 0 };\n      std::array<int, 0> photon_indices = {};\n      std::array<int, 2> indices = concatenate(concatenate(photon_indices, electron_indices), electron_indices);\n\n         const int gt2 = indices[0];\n      const int gt3 = indices[1];\n      const auto g1 = MODELPARAMETER(g1);\n      const auto g2 = MODELPARAMETER(g2);\n      const auto ThetaW = DERIVEDPARAMETER(ThetaW);\n\n      const std::complex<double> left = -0.7745966692414834*g1*Cos(ThetaW)*KroneckerDelta(gt2,gt3);\n\n      const std::complex<double> right = -0.5*KroneckerDelta(gt2,gt3)*(0.7745966692414834*g1*Cos(ThetaW) + g2*Sin(ThetaW));\n\n      return vertex_type(left, right);\n   }\n}\n\nstatic double unit_charge(const EvaluationContext& context)\n{\n   return impl::unit_charge(context).left().real() / Electron::electric_charge;\n}\n\n} // namespace cxx_diagrams\n} // namespace flexiblesusy\n\n#undef INPUTPARAMETER\n#undef MODELPARAMETER\n#undef DERIVEDPARAMETER\n#undef PHASE\n\n#endif\n", "meta": {"hexsha": "d52fbafa132115db80e7ad1e3735bcf50a668784", "size": 39371, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSM/MSSM_cxx_diagrams.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSM/MSSM_cxx_diagrams.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSM/MSSM_cxx_diagrams.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": 33.2244725738, "max_line_length": 282, "alphanum_fraction": 0.6848187752, "num_tokens": 11099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.036220055864974746, "lm_q1q2_score": 0.010307358770553887}}
{"text": "#include <boost/thread.hpp>\n#include <boost/thread.hpp>\n#include \"caffe/layer.hpp\"\n\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid Layer<Dtype>::InitMutex() {\n  forward_mutex_.reset(new boost::mutex());\n}\n\ntemplate <typename Dtype>\nvoid Layer<Dtype>::Lock() {\n  if (IsShared()) {\n    forward_mutex_->lock();\n  }\n}\n\ntemplate <typename Dtype>\nvoid Layer<Dtype>::Unlock() {\n  if (IsShared()) {\n    forward_mutex_->unlock();\n  }\n}\n\n\n/*\n * 聚类的目的是得到各个weight属于的中心以及这个中心的值\n */\ntemplate<typename Dtype>\nvoid Layer<Dtype>::kmeans_cluster(vector<int> &cLabel, vector<Dtype> &cCentro, Dtype *cWeights, int nWeights, \\\n  vector<bool> &mask, int nCluster,  int max_iter){\n\n  Dtype maxWeight = std::numeric_limits<Dtype>::min();\n  Dtype minWeight = std::numeric_limits<Dtype>::max();\n\n  //find min max\n  for(int k = 0; k < nWeights; ++k){\n    if(mask[k]){\n      if(cWeights[k] > maxWeight)\n        maxWeight = cWeights[k];\n      if(cWeights[k] < minWeight)\n        minWeight = cWeights[k];\n    }\n    cLabel[k] = -1; //initialize all label to -1\n  }\n\n  // generate initial centroids linearly\n  for (int k = 0; k < nCluster; k++)\n    cCentro[k] = minWeight + (maxWeight - minWeight) * k / (nCluster - 1);\n\n\n  Dtype *ptrC = new Dtype[nCluster]; // 用来存各个中心的权重的和，和下面的相除得到各个中心新的值\n  int *ptrS = new int[nCluster]; // 用来存各个中心的权重的个数\n  int iter = 0;\n  double mCurDistance = 0.0;\n  double mPreDistance = std::numeric_limits<double>::max();\n  Dtype distance, mindistance; // 临时变量，用于存每个weight到中心的距离和最短距离\n\n  // clustering\n  while (iter < max_iter)\n  {\n    // check convergence\n    if (fabs(mPreDistance - mCurDistance) / mPreDistance < 0.01)  break;\n    mPreDistance = mCurDistance; mCurDistance = 0.0;\n    for (int n = 0; n < nWeights; n++){\n      if (!mask[n])  continue; // 如果mask为0，则跳过这个值\n      mindistance = std::numeric_limits<Dtype>::max();\n      for (int k = 0; k < nCluster; k++){\n        distance = fabs(cWeights[n] - cCentro[k]);\n        if (distance < mindistance){\n          mindistance = distance;\n          cLabel[n] = k;\n        }\n      }\n      mCurDistance = mCurDistance + mindistance;\n    }\n\n    // 更新中心，初始化为0\n    for (int k = 0; k < nCluster; k++){\n      ptrC[k] = 0.f;\n      ptrS[k] = 0;\n    }\n\n    for (int n = 0; n < nWeights; n++){\n      if (mask[n]){\n        ptrC[cLabel[n]] += cWeights[n];\n        ptrS[cLabel[n]] += 1;\n      }\n    }\n\n    for (int k = 0; k < nCluster; k++)\n      cCentro[k] = ptrC[k]/ptrS[k]; // 更新中心值\n\n    iter++;\n  }\n  delete[] ptrC; delete[] ptrS;\n}\n\n\n  INSTANTIATE_CLASS(Layer);\n\n}  // namespace caffe\n", "meta": {"hexsha": "5822fd771fcbad2689685bd52d460814d95c2750", "size": 2524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layer.cpp", "max_stars_repo_name": "hixio-mh/Caffe_APP", "max_stars_repo_head_hexsha": "670829989a82040f1c7aaa01cd41100cfc783a2f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/caffe/layer.cpp", "max_issues_repo_name": "hixio-mh/Caffe_APP", "max_issues_repo_head_hexsha": "670829989a82040f1c7aaa01cd41100cfc783a2f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/layer.cpp", "max_forks_repo_name": "hixio-mh/Caffe_APP", "max_forks_repo_head_hexsha": "670829989a82040f1c7aaa01cd41100cfc783a2f", "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.0380952381, "max_line_length": 111, "alphanum_fraction": 0.6038034865, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.026759282797368875, "lm_q1q2_score": 0.010299972926387286}}
{"text": "/*\n * @Descripttion: \n * @version: 1.0版本\n * @Author: Frank.Wu\n * @Date: 2020-01-09 15:25:57\n * @LastEditors: Frank.Wu\n * @LastEditTime: 2020-11-01 10:36:33\n */\n#ifdef _USE_PCL_\n#include \"LidarFeaturePoints.h\"\n\n#include \"../LidarGeometry/Geometry.h\"\n#include \"../LidarGeometry/GeometryAlgorithm.h\"\n\n#include <boost/thread/thread.hpp>\n#include <pcl/range_image/range_image.h>\n#include <pcl/features/range_image_border_extractor.h>\n#include <pcl/registration/correspondence_rejection_sample_consensus.h>\n\n#include <pcl/console/time.h>\n#include <pcl/point_types.h>\n#include <pcl/common/io.h>\n#include <pcl/keypoints/sift_keypoint.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/features/fpfh.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/keypoints/iss_3d.h>\n#include<ceres/ceres.h>\nusing namespace ceres;\nusing namespace GeometryLas;\n\ntypedef pcl::PointXYZ PointType;\n/**\n * @brief  重构一下取值函数，默认取值为去强度值，没有这个部分则报错：\n           error: ‘const struct pcl::PointXYZ’ has no member named ‘intensity’\n * @note   \n * @retval None\n */\nnamespace pcl\n{\n  template<>\n    struct SIFTKeypointFieldSelector<PointXYZ>\n    {\n      inline float\n      operator () (const PointXYZ &p) const\n      {\n    return p.z;\n      }\n    };\n}\n\n\n\n/**\n * @brief  代码运行过程会有内存泄露的问题，感觉应该是库的问题，但是不知道问题在哪里\n            经过检查是RangeImage这段代码的问题，感觉跟内核有关，估计是虚拟机运行\n            不支持，或者是指令集的问题\n            2019-07-21:经过查看资料发现是PCL库编译的问题，存在Boost库与STD冲突的问题\n            编译的时候添加C++11标准用Release编译就可以解决这个问题\n            2019-12-26:一直提取特征Narf点数量为0，不知道问题出现在哪里,需要进一步研究\n * @note   \n * @param  input_cloud:  输入点云\n * @param  &narfIndex:   特征点点云\n * @param  &narfDesc:    特征点描述\n * @retval \n */\nlong LidarFeaturePoints::LidarFeature_NARF(pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud,pcl::PointCloud<int> &narfIndex,pcl::PointCloud<pcl::Narf36> &narfDesc)\n{\n    pcl::PointCloud<PointType>& point_cloud = *input_cloud;\n    float angular_resolution = 0.5f;           ////angular_resolution为模拟的深度传感器的角度分辨率，即深度图像中一个像素对应的角度大小\n    float support_size = 4.0f;                 //点云大小的设置\n    pcl::RangeImage::CoordinateFrame coordinate_frame = pcl::RangeImage::CAMERA_FRAME;     //设置坐标系\n    bool setUnseenToMaxRange = false;\n    bool rotation_invariant = true;\n    pcl::PointCloud<pcl::PointWithViewpoint> far_ranges;\n    Eigen::Affine3f scene_sensor_pose (Eigen::Affine3f::Identity ());\n    \n    // -----------------------------------------------\n\t// -----Create RangeImage from the PointCloud-----\n\t// -----------------------------------------------\n    float noise_level = 0.0;\n    float min_range = 0.0f;\n    int border_size = 1;\n    boost::shared_ptr<pcl::RangeImage> range_image_ptr (new pcl::RangeImage());\n    pcl::RangeImage& range_image = *range_image_ptr;  \n    range_image.createFromPointCloud (point_cloud, angular_resolution, pcl::deg2rad (360.0f), pcl::deg2rad (180.0f),\n                                   scene_sensor_pose, coordinate_frame, noise_level, min_range, border_size);\n    range_image.integrateFarRanges (far_ranges); \n\n    if (setUnseenToMaxRange)\n        range_image.setUnseenToMaxRange ();\n\n    /*提取特征点*/\n    pcl::RangeImageBorderExtractor range_image_border_extractor;   //用来提取边缘\n    pcl::NarfKeypoint narf_keypoint_detector;      //用来检测关键点\n    narf_keypoint_detector.setRangeImageBorderExtractor (&range_image_border_extractor);   //\n    narf_keypoint_detector.setRangeImage (&range_image);\n    narf_keypoint_detector.getParameters ().support_size = support_size;    //设置NARF的参数\n    narf_keypoint_detector.compute (narfIndex);\n\n    /*提取特征描述*/\n    std::vector<int> keypoint_indices2;\n    keypoint_indices2.resize (narfIndex.points.size ());\n    for (unsigned int i=0; i<narfIndex.size (); ++i) // This step is necessary to get the right vector type\n        keypoint_indices2[i]=narfIndex.points[i];\n    pcl::NarfDescriptor narf_descriptor (&range_image, &keypoint_indices2);\n    narf_descriptor.getParameters ().support_size = support_size;\n    narf_descriptor.getParameters ().rotation_invariant = rotation_invariant;\n    narf_descriptor.compute (narfDesc);\n    printf(\"feature points count:%d\\n\",narfIndex.size());\n    return 0;\n}\n\nlong LidarFeaturePoints::LidarFeature_Sift(pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud,\n                                           pcl::PointCloud<int> &siftPointIdx,\n                                           pcl::PointCloud<pcl::FPFHSignature33>::Ptr siftFPFH)\n{\n    // Parameters for sift computation\n    float min_scale = 2.0f;       //the standard deviation of the smallest scale in the scale space\n    int n_octaves   = 8;           //the number of octaves (i.e. doublings of scale) to compute\n    int n_scales_per_octave = 4;   //the number of scales to compute within each octave\n    float min_contrast = 0.5f;    //the minimum contrast required for detection\n\n    pcl::console::TicToc time;\n    time.tic();\n\n    // Estimate the sift interest points using z values from xyz as the Intensity variants\n    //pcl::PointCloud<pcl::PointXYZ>::Ptr feauture_cloud\n    pcl::SIFTKeypoint<pcl::PointXYZ, pcl::PointWithScale> sift;\n    pcl::PointCloud<pcl::PointWithScale> result;\n    pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ> ());\n\n    sift.setSearchMethod(tree);\n    sift.setScales(min_scale, n_octaves, n_scales_per_octave);\n    sift.setMinimumContrast(min_contrast);\n    sift.setInputCloud(input_cloud);\n    sift.compute(result);\n\n    //pcl::PointIndicesConstPtr keypoints_indices = sift.getKeypointsIndices();\n    //计算点云特征\n    pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>());\n    pcl::NormalEstimation<pcl::PointXYZ,pcl::Normal> est_normal;\n    est_normal.setInputCloud(input_cloud);\n    est_normal.setSearchMethod(tree);\n    est_normal.setKSearch(10);          //近邻10个点\n    est_normal.compute(*normals);       //计算法线\n\n    //创建FPFH估计对象fpfh，并把输入数据集cloud和法线normals传递给它。\n    pcl::FPFHEstimation<pcl::PointXYZ,pcl::Normal,pcl::FPFHSignature33> fpfh;\n    pcl::search::KdTree<pcl::PointXYZ>::Ptr treeFPFH(new pcl::search::KdTree<pcl::PointXYZ> ());\n    fpfh.setInputCloud(input_cloud);\n    fpfh.setInputNormals(normals);\n    fpfh.setSearchMethod(treeFPFH);\n    //fpfh.setIndices(keypoints_indices);\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs(new pcl::PointCloud<pcl::FPFHSignature33>());\n    fpfh.setKSearch(10);        //近邻10个点\n    fpfh.compute(*fpfhs);       //计算特征\n    \n    //判断SIFT点在原始点云中的index\n    const int searchNum=1;\n    std::vector<int> pointIdxNKNSearch(searchNum);\n    std::vector<float> pointNKNSquaredDistance(searchNum);\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n    kdtree.setInputCloud(input_cloud);\n    for(auto resPoint : result.points)\n    {\n        pcl::PointXYZ searchPoint;\n        searchPoint.x=resPoint.x;\n        searchPoint.y=resPoint.y;\n        searchPoint.z=resPoint.z;\n\n        if (kdtree.nearestKSearch(searchPoint, searchNum, pointIdxNKNSearch, pointNKNSquaredDistance) > 0 )\n        {\n            siftPointIdx.push_back(pointIdxNKNSearch[0]);\n            siftFPFH->push_back(fpfhs->points[pointIdxNKNSearch[0]]);\n        }\n    }\n\n    std::cout << \"Computing Points: \"<<input_cloud->size()<<std::endl;\n    std::cout << \"Computing FPFH Features: \"<<siftFPFH->size()<<std::endl;\n    std::cout << \"Computing the SIFT points takes \"<<time.toc()/1000<<\"seconds\"<<std::endl;\n    std::cout << \"No. of SIFT points in the result are \" << siftPointIdx.size () << std::endl;\n\n/*\n    std::cout << \"Computing Points: \"<<input_cloud->size()<<std::endl;\n    std::cout << \"Computing FPFH Features: \"<<fpfhs->size()<<std::endl;\n    std::cout << \"Computing Normals: \"<<normals->size()<<std::endl;\n    std::cout << \"Computing the SIFT points takes \"<<time.toc()/1000<<\"seconds\"<<std::endl;\n    std::cout << \"No. of SIFT points in the result are \" << result.points.size () << std::endl;\n */\n\n    // Copying the pointwithscale to pointxyz so as visualize the cloud\n    //copyPointCloud(result, *feauture_cloud);\n    //std::cout << \"SIFT points in the result are \" << feauture_cloud->points.size () << std::endl;\n\n#ifdef _DEBUG\n    FILE *fs = fopen(\"../data/test/ptSIFT.txt\",\"w+\");\n    if(fs!=nullptr)\n    {\n        for(int i=0;i<siftPointIdx.points.size ();++i)\n            fprintf(fs,\"%lf  %lf  %lf  %lf  %lf  %lf\\n\",input_cloud->points[siftPointIdx[i]].x,\n                                        input_cloud->points[siftPointIdx[i]].y,\n                                        input_cloud->points[siftPointIdx[i]].z,\n                                        255.0f,255.0f,0.0f);\n        fclose(fs);\n    }else\n    {\n        printf(\"create test output failed!\\n\");\n    }\n#endif\n    return 0;\n}\n\n\nlong LidarFeaturePoints::LidarFeature_ISS(pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud,\n                                          pcl::PointCloud<int> &siftPointIdx,\n                                          pcl::PointCloud<pcl::FPFHSignature33>::Ptr siftFPFH)\n{\n    pcl::console::TicToc time;\n    time.tic();\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_src_is(new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::ISSKeypoint3D<pcl::PointXYZ, pcl::PointXYZ> iss_det;\n    pcl::search::KdTree<pcl::PointXYZ>::Ptr tree_1(new pcl::search::KdTree<pcl::PointXYZ>());\n\n    double model_solution = 0.4;//参数小，采取的关键点少，论文中为500左右\n\n    //参数设置\n    iss_det.setSearchMethod(tree_1);\n    iss_det.setSalientRadius(6*model_solution);//\n    iss_det.setNonMaxRadius(4*model_solution);//\n    iss_det.setThreshold21 (0.975);\n    iss_det.setThreshold32 (0.975);\n    iss_det.setMinNeighbors(5);\n    iss_det.setNumberOfThreads(4);\n    iss_det.setInputCloud(input_cloud);\n    iss_det.compute(*cloud_src_is);\n\n    clock_t end = clock();\n       //pcl::PointIndicesConstPtr keypoints_indices = sift.getKeypointsIndices();\n    //计算点云特征\n    pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>());\n    pcl::NormalEstimation<pcl::PointXYZ,pcl::Normal> est_normal;\n    est_normal.setInputCloud(input_cloud);\n    est_normal.setSearchMethod(tree_1);\n    est_normal.setKSearch(10);          //近邻10个点\n    est_normal.compute(*normals);       //计算法线\n\n    //创建FPFH估计对象fpfh，并把输入数据集cloud和法线normals传递给它。\n    pcl::FPFHEstimation<pcl::PointXYZ,pcl::Normal,pcl::FPFHSignature33> fpfh;\n    pcl::search::KdTree<pcl::PointXYZ>::Ptr treeFPFH(new pcl::search::KdTree<pcl::PointXYZ> ());\n    fpfh.setInputCloud(input_cloud);\n    fpfh.setInputNormals(normals);\n    fpfh.setSearchMethod(treeFPFH);\n    //fpfh.setIndices(keypoints_indices);\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs(new pcl::PointCloud<pcl::FPFHSignature33>());\n    fpfh.setKSearch(10);        //近邻10个点\n    fpfh.compute(*fpfhs);       //计算特征\n    \n    //判断SIFT点在原始点云中的index\n    const int searchNum=1;\n    std::vector<int> pointIdxNKNSearch(searchNum);\n    std::vector<float> pointNKNSquaredDistance(searchNum);\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n    kdtree.setInputCloud(input_cloud);\n    \n    for(auto resPoint : cloud_src_is->points)\n    {\n        pcl::PointXYZ searchPoint;\n        searchPoint.x = resPoint.x;\n        searchPoint.y = resPoint.y;\n        searchPoint.z = resPoint.z;\n\n        if (kdtree.nearestKSearch(searchPoint, searchNum, pointIdxNKNSearch, pointNKNSquaredDistance) > 0 )\n        {\n            siftPointIdx.push_back(pointIdxNKNSearch[0]);\n            siftFPFH->push_back(fpfhs->points[pointIdxNKNSearch[0]]);\n        }\n    }\n\n    std::cout << \"Computing Points: \"<<input_cloud->size()<<std::endl;\n    std::cout << \"Computing ISS Features: \"<<siftFPFH->size()<<std::endl;\n    std::cout << \"Computing the ISS points takes \"<<time.toc()/1000<<\"seconds\"<<std::endl;\n    std::cout << \"No. of ISS points in the result are \" << siftPointIdx.size () << std::endl;\n\n#ifdef _DEBUG\n    FILE *fs = fopen(\"../data/test/ptISS.txt\",\"w+\");\n    if(fs!=nullptr)\n    {\n        for(int i=0;i<siftPointIdx.points.size ();++i)\n            fprintf(fs,\"%lf  %lf  %lf  %lf  %lf  %lf\\n\",input_cloud->points[siftPointIdx[i]].x,\n                                        input_cloud->points[siftPointIdx[i]].y,\n                                        input_cloud->points[siftPointIdx[i]].z,\n                                        255.0f,255.0f,0.0f);\n        fclose(fs);\n    }else\n    {\n        printf(\"create test output failed!\\n\");\n    }\n#endif\n    return 0;\n    \n}\n\n// 直接通过kdtree查找比较快\n// inline double disFpfh(pcl::FPFHSignature33 pt1,pcl::FPFHSignature33 pt2)\n// {\n//     double dis = 0;\n//     for(int i=0;i<pt1.descriptorSize();++i)\n//     {\n//         dis+=(pt1.histogram[i]-pt2.histogram[i])*(pt1.histogram[i]-pt2.histogram[i]);\n//     }\n//     return sqrt(dis);\n// }\n\nlong LidarFeatureRegistration::LidarRegistration_SiftFPFHMatch(pcl::PointCloud<pcl::FPFHSignature33>::Ptr siftFPFH1,\n                                pcl::PointCloud<pcl::FPFHSignature33>::Ptr siftFPFH2,\n                                std::vector<MATCHHISTRODIS> &matches)\n{\n    pcl::KdTreeFLANN<pcl::FPFHSignature33> kdtree;\n    kdtree.setInputCloud(siftFPFH1);\n    const int searchNum=1;\n    std::vector<int> pointIdxNKNSearch(searchNum);\n    std::vector<float> pointNKNSquaredDistance(searchNum);\n    \n    //特征匹配\n    int num=0;\n    for(auto fpfhTar:siftFPFH2->points)\n    {\n        if (kdtree.nearestKSearch(fpfhTar, searchNum, pointIdxNKNSearch, pointNKNSquaredDistance) > 0 )\n        {\n            MATCHHISTRODIS matchTmp;\n            matchTmp.relation=-1;\n            matchTmp.idx2 = num;\n            matchTmp.idx1 = pointIdxNKNSearch[0];\n            matches.push_back(matchTmp);\n            num++;\n        }\n    }\n}\n\nlong LidarFeatureRegistration::LidarRegistration_Match(pcl::PointCloud<int> idxList1,\n                                 pcl::PointCloud<int> idxList2,\n                                 pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,\n                                 pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2,\n                                 int matchNum,\n                                 std::vector<MATCHHISTRODIS> &matches)\n{\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree1;\n\tkdtree1.setInputCloud(cloud1);\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree2;\n\tkdtree2.setInputCloud(cloud2);\n\n    for(int i=0;i<idxList1.size();++i)\n    {\n        //find the most match point\n        MATCHHISTRODIS matchTmp;\n        matchTmp.relation=-1;\n        matchTmp.idx1 = idxList1[i];\n        matchTmp.idx2 = idxList2[0];\n        for(int j=0;j<idxList2.size();++j)\n        {\n            pcl::PointXYZ pnt1=cloud1->points[idxList1[i]];\n            pcl::PointXYZ pnt2=cloud2->points[idxList2[j]];\n            double rel=LidarRegistration_CorrelationMatch(pnt1,pnt2,kdtree1,cloud1,kdtree2,cloud2,matchNum);\n            matchTmp.idx2 = matchTmp.relation>rel?matchTmp.idx2:idxList2[j];\n            matchTmp.relation=max(rel,matchTmp.relation);\n        }\n        if(matchTmp.relation<40)\n        {\n            // printf(\"%lf\\n\",matchTmp.relation);\n            matches.push_back(matchTmp);\n        }\n    }\n    printf(\"match point count is : %d\\n\",matches.size());\n    return 0;\n}\n\nlong LidarFeatureRegistration::LidarRegistration_RANSC(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,\n                             pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2,\n                             pcl::PointCloud<int> siftPointIdx1,\n                             pcl::PointCloud<int> siftPointIdx2,\n                             int type,\n                             std::vector<MATCHHISTRODIS> &matches)\n{\n\n    boost::shared_ptr<pcl::Correspondences> correspondence_all(new pcl::Correspondences);\n    boost::shared_ptr<pcl::Correspondences> correspondence_inliner(new pcl::Correspondences);\n    pcl::Correspondences correspondences;\n    \n    for(int i=0;i<matches.size();++i)\n    {\n        //output match point list\n        int id1,id2;\n        if(type==0)\n        {\n\n            if(siftPointIdx1[matches[i].idx1]>cloud1->points.size())\n            {\n                printf(\"%d\\n\",siftPointIdx1[matches[i].idx1]);\n                continue;\n            }\n\n            if(siftPointIdx2[matches[i].idx2]>cloud2->points.size())\n            {\n                printf(\"%d\\n\",siftPointIdx2[matches[i].idx2]);\n                continue;\n            }\n            id1 = siftPointIdx1[matches[i].idx1];\n            id2 = siftPointIdx2[matches[i].idx2];\n        }\n        else if(type==1)\n        {\n            id1 = matches[i].idx1;\n            id2 = matches[i].idx2;\n        }\n\n        pcl::Correspondence Correspondence;\n\t\tCorrespondence.index_match = id2;   //目标点云\n\t\tCorrespondence.index_query = id1;//源点云\n        // printf(\"%d-%d\\n\",id2,id1);\n\t\tcorrespondences.push_back(Correspondence);\n    }\n    *correspondence_all = correspondences;\n\n    printf(\"process ransc\\n\");\n    pcl::registration::CorrespondenceRejectorSampleConsensus<pcl::PointXYZ> ransac;\n\transac.setInputSource(cloud1);\n\transac.setInputTarget(cloud2);\n\transac.setMaximumIterations(400);\n\transac.setInlierThreshold(40);\n\transac.getRemainingCorrespondences(*correspondence_all, *correspondence_inliner);\n\n    matches.clear();\n    for (int i = 0; i < correspondence_inliner->size(); i++)\n\t{\n        MATCHHISTRODIS matchdis;\n        matchdis.idx1 = correspondence_inliner->at(i).index_match;\n        matchdis.idx2 = correspondence_inliner->at(i).index_query;\n        matchdis.relation = -1;\n        matches.push_back(matchdis);\n    }\n    return 0;\n}\n\n\nvoid LidarFeatureRegistration::LidarRegistration_OutputTest(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,\n                                 pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2,\n                                 pcl::PointCloud<int> siftPointIdx1,\n                                 pcl::PointCloud<int> siftPointIdx2,\n                                 int type,\n                                 std::vector<MATCHHISTRODIS> matches)\n{\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree1;\n\tkdtree1.setInputCloud(cloud1);\n    pcl::KdTreeFLANN<pcl::PointXYZ> kdtree2;\n\tkdtree2.setInputCloud(cloud2);\n    const int matchNum=20;\n    for(int i=0;i<matches.size();++i)\n    {\n        //output match point list\n        int id1,id2;\n        if(type==0)\n        {\n            if(siftPointIdx1[matches[i].idx1]>cloud1->points.size())\n            {\n                printf(\"%d\\n\",siftPointIdx1[matches[i].idx1]);\n                continue;\n            }\n            if(siftPointIdx2[matches[i].idx2]>cloud2->points.size())\n            {\n                printf(\"%d\\n\",siftPointIdx2[matches[i].idx2]);\n                continue;\n            }\n            id1 = siftPointIdx1[matches[i].idx1];\n            id2 = siftPointIdx2[matches[i].idx2];\n        }\n        else if(type==1)\n        {\n            id1 = matches[i].idx1;\n            id2 = matches[i].idx2;\n        }\n\n        pcl::PointXYZ pnt1=cloud1->points[id1];\n        pcl::PointXYZ pnt2=cloud2->points[id2];\n\n        std::vector<int> pointIdxNKNSearch1(matchNum);\n        std::vector<int> pointIdxNKNSearch2(matchNum);\n        std::vector<float> pointNKNSquaredDistance(matchNum);\n\n        kdtree1.nearestKSearch(pnt1, matchNum, pointIdxNKNSearch1, pointNKNSquaredDistance);\n        kdtree2.nearestKSearch(pnt2, matchNum, pointIdxNKNSearch2, pointNKNSquaredDistance);\n\n        std::string path=\"../data/\"+to_string(i)+\".txt\";\n        FILE* fs = fopen(path.c_str(),\"w+\");\n        fprintf(fs,\"%lf,%lf,%lf,%lf,%lf,%lf\\n\", pnt1.x,pnt1.y,pnt1.z,0,0,255.0);\n        fprintf(fs,\"%lf,%lf,%lf,%lf,%lf,%lf\\n\", pnt2.x,pnt2.y,pnt2.z,0,0,255.0);\n        // for(int tIdx=0;tIdx<matchNum;++tIdx)\n        // {\n        //     fprintf(fs,\"%lf,%lf,%lf\\n\", cloud1->points[pointIdxNKNSearch1[tIdx]].x,\n        //                     cloud1->points[pointIdxNKNSearch1[tIdx]].y,\n        //                     cloud1->points[pointIdxNKNSearch1[tIdx]].z);\n        //     fprintf(fs,\"%lf,%lf,%lf\\n\", cloud2->points[pointIdxNKNSearch2[tIdx]].x,\n        //                     cloud2->points[pointIdxNKNSearch2[tIdx]].y,\n        //                     cloud2->points[pointIdxNKNSearch1[tIdx]].z);\n        // }\n        fclose(fs);\n    }\n}\n\nvoid LidarFeatureRegistration::LidarRegistration_Check(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,\n                                 pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2,\n                                 pcl::PointCloud<int> siftPointIdx1,\n                                 pcl::PointCloud<int> siftPointIdx2,\n                                 int type,\n                                 std::vector<MATCHHISTRODIS> matches,\n                                 GeometryLas::Point3D pntCenter,\n                                 double *r_t)\n{\n    double totalRMS=0;\n    for(int i=0;i<matches.size();++i)\n    {\n        //output match point list\n        int id1,id2;\n        if(type==0)\n        {\n            if(siftPointIdx1[matches[i].idx1]>cloud1->points.size())\n            {\n                printf(\"%d\\n\",siftPointIdx1[matches[i].idx1]);\n                continue;\n            }\n\n            if(siftPointIdx2[matches[i].idx2]>cloud2->points.size())\n            {\n                printf(\"%d\\n\",siftPointIdx2[matches[i].idx2]);\n                continue;\n            }\n            id1 = siftPointIdx1[matches[i].idx1];\n            id2 = siftPointIdx2[matches[i].idx2];\n        }\n        else if(type==1)\n        {\n            id1 = matches[i].idx1;\n            id2 = matches[i].idx2;\n        }\n\n        pcl::PointXYZ pnt1=cloud1->points[id1];\n        pcl::PointXYZ pnt2=cloud2->points[id2];\n\n        double x1 = pnt1.x-pntCenter.x,y1 = pnt1.y-pntCenter.y,z1=pnt1.z-pntCenter.z;\n        double x2 = pnt2.x,y2 = pnt2.y,z2=pnt2.z;\n        // Debug\n        // printf(\"center x: %lf y: %lf z: %lf\\n\",pntCenter.x,pntCenter.y,pntCenter.z);\n\n        MatrixXd rotMat = MatrixXd::Identity(3,3);\n        rotMat(0,0) = cos(r_t[1])*cos(r_t[2]);\n        rotMat(0,1) = sin(r_t[0])*sin(r_t[1])*cos(r_t[2]) - cos(r_t[0])*sin(r_t[2]);\n        rotMat(0,2) = cos(r_t[0])*sin(r_t[1])*cos(r_t[2]) + sin(r_t[0])*sin(r_t[2]);\n        rotMat(1,0) = cos(r_t[1])*sin(r_t[2]);\n        rotMat(1,1) = sin(r_t[0])*sin(r_t[1])*sin(r_t[2]) + cos(r_t[0])*cos(r_t[2]);\n        rotMat(1,2) = cos(r_t[0])*sin(r_t[1])*sin(r_t[2]) - sin(r_t[0])*cos(r_t[2]);\n        rotMat(2,0) = -sin(r_t[1]);\n        rotMat(2,1) = sin(r_t[0])*cos(r_t[1]);\n        rotMat(2,2) = cos(r_t[0])*cos(r_t[1]);\n\n        MatrixXd ptMat(3,1);\n        ptMat(0,0) = x1;\n        ptMat(1,0) = y1;\n        ptMat(2,0) = z1;\n        MatrixXd transMat=rotMat*ptMat;\n\n        double res1=((transMat(0,0)-r_t[3]-x2+pntCenter.x)*(transMat(0,0)-r_t[3]-x2+pntCenter.x));\n        double res2=((transMat(1,0)-r_t[4]-y2+pntCenter.y)*(transMat(1,0)-r_t[4]-y2+pntCenter.y));\n        double res3=((transMat(2,0)-r_t[5]-z2+pntCenter.z)*(transMat(2,0)-r_t[5]-z2+pntCenter.z));\n        printf(\"RMS of x=%lf,y=%lf,z=%lf,total=%lf\\n\",res1,res2,res3,sqrt(res1+res2+res3)/3);\n        totalRMS+=sqrt(res1+res2+res3)/3;\n    }\n\n    printf(\"total RMS error:%lf\\n\",totalRMS/matches.size());\n}\n\ndouble LidarFeatureRegistration::LidarRegistration_CorrelationMatch(pcl::PointXYZ pnt1,pcl::PointXYZ pnt2,\n                                                                pcl::KdTreeFLANN<pcl::PointXYZ> kdtree1,\n                                                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,\n                                                                pcl::KdTreeFLANN<pcl::PointXYZ> kdtree2,\n                                                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2,\n                                                                int nearPointsNum)\n{\n    std::vector<int> pointIdxNKNSearch1(nearPointsNum);\n    std::vector<int> pointIdxNKNSearch2(nearPointsNum);\n    std::vector<float> pointNKNSquaredDistance(nearPointsNum);\n\n    kdtree1.nearestKSearch(pnt1, nearPointsNum, pointIdxNKNSearch1, pointNKNSquaredDistance);\n    kdtree2.nearestKSearch(pnt2, nearPointsNum, pointIdxNKNSearch2, pointNKNSquaredDistance);\n\n    double *distro1 = new double[nearPointsNum];\n    double *distro2 = new double[nearPointsNum];\n\n    // 获取距离直方图\n    LidarRegistration_DisHistro(pointIdxNKNSearch1[0],pointIdxNKNSearch1,cloud1,distro1);\n    LidarRegistration_DisHistro(pointIdxNKNSearch2[0],pointIdxNKNSearch2,cloud2,distro2);\n\n    //距离直方图叠加角度直方图\n    // LidarRegistration_DisAngleHistro(pointIdxNKNSearch1[0],pointIdxNKNSearch1,cloud1,distro1);\n    // LidarRegistration_DisAngleHistro(pointIdxNKNSearch2[0],pointIdxNKNSearch2,cloud2,distro2);\n    double colRel=LidarRegistration_Correlation(distro1,distro2,nearPointsNum);\n    \n    delete []distro1;distro1=nullptr;\n    delete []distro2;distro1=nullptr;\n    return colRel;\n\n    // std::vector<int> match;\n    // double matchRatio=0;\n    // for(int i=0;i<nearPointsNum;++i)\n    // {\n    //     LidarRegistration_DisHistro(pointIdxNKNSearch1[i],pointIdxNKNSearch1,cloud1,distro1);\n    //     double maxRel = -99999;\n    //     match.push_back(i);\n    //     int maxInd=0;\n    //     for(int j=0;j<nearPointsNum;++j)\n    //     {\n    //         LidarRegistration_DisHistro(pointIdxNKNSearch2[j],pointIdxNKNSearch2,cloud2,distro2);\n    //         double colRel=LidarRegistration_Correlation(distro1,distro2,nearPointsNum);\n    //         maxInd = maxRel>colRel?maxInd:j;\n    //         maxRel=max(maxRel,colRel);\n    //     }\n    //     match.push_back(maxInd);\n    //     matchRatio+=maxRel;\n    // }\n    // // printf(\"%lf\\n\",matchRatio);\n    // delete []distro1;distro1=nullptr;\n    // delete []distro2;distro1=nullptr;\n    // return matchRatio/nearPointsNum;\n} \n\ndouble LidarFeatureRegistration::LidarRegistration_Correlation(double* data1,double *data2,int num)\n{\n    double sumA(0.0), sumB(0.0), aveA(0.0), aveB(0.0);\n \n\t//求和\n\tsumA = std::accumulate(data1,data1+num, 0.0);\n\tsumB = std::accumulate(data2,data2+num, 0.0);\n \n\t//求平均值\n\taveA = sumA / double(num);\n\taveB = sumB / double(num);\n \n\t//计算相关系数\n\tdouble R1(0), R2(0), R3(0);\n\tfor (long i = 0; i < num; i++)\n\t{\n\t\tR1 += (data1[i] - aveA) * (data2[i] - aveB);\n\t\tR2 += pow((data1[i] - aveA), 2);\n\t\tR3 += pow((data2[i] - aveB), 2);\n\t}\n \n    //计算距离\n    double dis=0;\n    for(long i=0;i<num;++i)\n    {\n        dis+=(data1[i]-data2[i])*(data1[i]-data2[i]);\n    }\n    dis=sqrt(dis/num);\n    double ratio=1.0;\n\n\treturn (/*R1 / sqrt(R2*R3)*/1/dis*ratio);\n}\n\n\nlong LidarFeatureRegistration::LidarRegistration_DisHistro(int idxPnt,vector<int> idxPntAllNear,pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,double *disHistro)\n{\n    memset(disHistro,sizeof(double)*idxPntAllNear.size(),0);\n    Point3D pt2(cloud1->points[idxPnt].x,cloud1->points[idxPnt].y,cloud1->points[idxPnt].z);\n    for(int i=0;i<idxPntAllNear.size();++i)\n    {\n        Point3D pt1(cloud1->points[idxPntAllNear[i]].x,cloud1->points[idxPntAllNear[i]].y,cloud1->points[idxPntAllNear[i]].z);\n        disHistro[i] = DistanceComputation::Distance(pt1,pt2);\n    }\n    std::sort(disHistro,disHistro+idxPntAllNear.size());\n    return 0;\n}\n\n\nlong LidarFeatureRegistration::LidarRegistration_DisAngleHistro(int idxPnt,vector<int> idxPntAllNear,pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,double *disHistro)\n{\n    double *histro = new double[idxPntAllNear.size()];\n    memset(histro,sizeof(double)*idxPntAllNear.size(),0);\n    memset(disHistro,sizeof(double)*idxPntAllNear.size(),0);\n    Point3D pt2(cloud1->points[idxPnt].x,cloud1->points[idxPnt].y,cloud1->points[idxPnt].z);\n    for(int i=0;i<idxPntAllNear.size();++i)\n    {\n        Point3D pt1(cloud1->points[idxPntAllNear[i]].x,cloud1->points[idxPntAllNear[i]].y,cloud1->points[idxPntAllNear[i]].z);\n        histro[i] = DistanceComputation::Distance(pt1,pt2);\n    }\n    \n    vector<int> idx(idxPntAllNear.size());\n    for (int i = 0; i < idxPntAllNear.size(); i++)idx[i] = i;\n    sort(histro,histro+idxPntAllNear.size());\n    sort(idx.begin(),idx.end(),[histro](int i1, int i2) {return histro[i1] < histro[i2]; });\n    \n    double vx1=cloud1->points[idx[0]].x-cloud1->points[idxPnt].x;\n    double vy1=cloud1->points[idx[0]].y-cloud1->points[idxPnt].y;\n    double vz1=cloud1->points[idx[0]].z-cloud1->points[idxPnt].z;\n\n    double down1 = vx1*vx1+vy1*vy1+vz1*vz1;\n    disHistro[0] = histro[0];\n    for (int i = 1; i < idxPntAllNear.size(); i++)\n    {\n\n        double vx2=cloud1->points[idx[i]].x-cloud1->points[idxPnt].x;\n        double vy2=cloud1->points[idx[i]].y-cloud1->points[idxPnt].y;\n        double vz2=cloud1->points[idx[i]].z-cloud1->points[idxPnt].y;\n        \n        double up = vx1*vx2+vy1*vy2+vz1*vz2;\n        double down2 = vx2*vx2+vy2*vy2+vz2*vz2;\n        disHistro[i] = histro[i]*up/sqrt(down1)/sqrt(down2);\n        // angleHistro[i-1]=up/sqrt(down1)*sqrt(down2);\n    }\n    delete []histro;histro=nullptr;\n}\n\n#ifdef _USE_CERES_\n/**\n * @name: ceres 自动求导,注意，各个库采用的编译器类型要一致，\n *        PCL采用C++14 则ceres也采用c++14，否则在link的时候会出问题\n * @msg: \n * @return: \n */\nstruct CostFunctorRotTrans{\n    \n\tCostFunctorRotTrans(double x1,double y1,double z1,double x2,double y2,double z2)\n                        :m_x1(x1), m_y1(y1), m_z1(z1), m_x2(x2), m_y2(y2), m_z2(z2)\n    {}\n\n\ttemplate <typename T> \n    bool operator()(const T* r_t, T* residual) const \n    {\n        T a11 = cos(r_t[1])*cos(r_t[2]);\n        T a12 = sin(r_t[0])*sin(r_t[1])*cos(r_t[2]) - cos(r_t[0])*sin(r_t[2]);\n        T a13 = cos(r_t[0])*sin(r_t[1])*cos(r_t[2]) + sin(r_t[0])*sin(r_t[2]);\n        T b11 = cos(r_t[1])*sin(r_t[2]);\n        T b12 = sin(r_t[0])*sin(r_t[1])*sin(r_t[2]) + cos(r_t[0])*cos(r_t[2]);\n        T b13 = cos(r_t[0])*sin(r_t[1])*sin(r_t[2]) - sin(r_t[0])*cos(r_t[2]);\n        T c11 = -sin(r_t[1]);\n        T c12 = sin(r_t[0])*cos(r_t[1]);\n        T c13 = cos(r_t[0])*cos(r_t[1]);\n\n        residual[0]=(a11*m_x1+a12*m_y1+a13*m_z1+r_t[3]-m_x2)*\n                    (a11*m_x1+a12*m_y1+a13*m_z1+r_t[3]-m_x2);\n        residual[1]=(b11*m_x1+b12*m_y1+b13*m_z1+r_t[4]-m_y2)*\n                    (b11*m_x1+b12*m_y1+b13*m_z1+r_t[4]-m_y2);\n        residual[2]=(c11*m_x1+c12*m_y1+c13*m_z1+r_t[5]-m_z2)*\n                    (c11*m_x1+c12*m_y1+c13*m_z1+r_t[5]-m_z2);\n\t\t\n        return true;\n\t}\n \n\t// static ceres::CostFunction* Create(const double observed_depth) {\n\t// \treturn (new ceres::AutoDiffCostFunction<CostFunctorRotTrans, 6, 3>(\n\t// \t\tnew CostFunctorRotTrans(m_obs,m_match)));\n\t// }\n \n    const double m_x1;\n    const double m_y1;\n    const double m_z1;\n    const double m_x2;\n    const double m_y2;\n    const double m_z2;\n};\n\n/**\n * @name: 获取数值中点\n * @param {type} \n * @return: \n */\nstatic Point3D GetMaxMinCenterPoint(pcl::PointCloud<pcl::PointXYZ>::Ptr pts_cloud)\n{\n    Point3D ptMax(-999999999,-999999999,-999999999);\n    Point3D ptMin(999999999,999999999,999999999);\n\n    for (int i = 0; i < pts_cloud->points.size(); ++i) \n    {\n        ptMax.x=max(double(pts_cloud->points[i].x),ptMax.x);\n        ptMax.y=max(double(pts_cloud->points[i].y),ptMax.y);\n        ptMax.z=max(double(pts_cloud->points[i].z),ptMax.z);\n\n        ptMin.x=min(double(pts_cloud->points[i].x),ptMin.x);\n        ptMin.y=min(double(pts_cloud->points[i].y),ptMin.y);\n        ptMin.z=min(double(pts_cloud->points[i].z),ptMin.z);\n    }\n\n    return Point3D((ptMax.x+ptMin.x)/2,(ptMax.y+ptMin.y)/2,(ptMax.z+ptMin.z)/2);\n}\n\n//TODO:\n//功能是做完了，最后也能够收敛，但是计算结果的残差太大，而且在匹配过程中可能存在误匹配的店\n//第一步是需要处理误匹配的店，然后再找到减小残差的办法\nlong LidarFeatureRegistration::LidarRegistration_RotTrans(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1,\n                                                          pcl::PointCloud<int> ptSiftIdx1,\n                                                          pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2,\n                                                          pcl::PointCloud<int> ptSiftIdx2,\n                                                          pcl::PointCloud<int> siftMatchPointIdx,\n                                                          double *r_t)\n{\n    Problem problem;\n    for(int i=0;i<6;++i)\n        r_t[i]=0;\n    Point3D ptCent1 = GetMaxMinCenterPoint(cloud1);\n    Point3D ptCent2 = GetMaxMinCenterPoint(cloud2);\n    \n    double *obs=new double[3*siftMatchPointIdx.points.size()];\n    double *match=new double[3*siftMatchPointIdx.points.size()];\n\n    for (int i = 0; i < siftMatchPointIdx.points.size(); ++i) \n    {\n        const int idx1 = ptSiftIdx2.points[i];\n        const int idx2 = ptSiftIdx1.points[siftMatchPointIdx.points[i]];\n        \n        obs[i*3+0]=cloud1->points[idx1].x-ptCent1.x;\n        obs[i*3+1]=cloud1->points[idx1].y-ptCent1.y;\n        obs[i*3+2]=cloud1->points[idx1].z-ptCent1.z;\n\n        match[i*3+0]=cloud2->points[idx2].x-ptCent1.x;\n        match[i*3+1]=cloud2->points[idx2].y-ptCent1.y;\n        match[i*3+2]=cloud2->points[idx2].z-ptCent1.z;\n    }\n\n    for (int i = 0; i < siftMatchPointIdx.points.size(); ++i) \n    {\n        CostFunction* cost_function =\n            new AutoDiffCostFunction<CostFunctorRotTrans, 3,6>(\n                new CostFunctorRotTrans(obs[i+3+0],obs[i+3+1],obs[i+3+2],match[i*3+0],match[i*3+1],match[i*3+2]));\n        problem.AddResidualBlock(cost_function, nullptr, r_t);\n    }\n    \n    Solver::Options options;\n    options.linear_solver_type=ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout=true;\n    options.max_num_iterations = 500;\n    Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n\n    delete obs;  obs=nullptr;\n    delete match;match=nullptr;\n\n    return 0;\n}\n#endif\n\n#endif", "meta": {"hexsha": "c2bfc0b4059d206dbbe9d74388d9cb3f6e60ff78", "size": 33013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LidarPCLAlgorithm/LidarFeaturePoints.cpp", "max_stars_repo_name": "RemoteSensingFrank/LidarProc", "max_stars_repo_head_hexsha": "f6f6868e82b87171533f6e8cd998fdaef2bbf745", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T00:32:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T04:34:04.000Z", "max_issues_repo_path": "src/LidarPCLAlgorithm/LidarFeaturePoints.cpp", "max_issues_repo_name": "Xiaobin-Jiang/LidarProc", "max_issues_repo_head_hexsha": "3ab44cbf460626c15a00f4bf2b8ffd85e4008d22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-20T09:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T06:37:26.000Z", "max_forks_repo_path": "src/LidarPCLAlgorithm/LidarFeaturePoints.cpp", "max_forks_repo_name": "Xiaobin-Jiang/LidarProc", "max_forks_repo_head_hexsha": "3ab44cbf460626c15a00f4bf2b8ffd85e4008d22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2018-03-12T00:32:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T00:37:26.000Z", "avg_line_length": 38.8845700824, "max_line_length": 162, "alphanum_fraction": 0.610183867, "num_tokens": 9924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.026759281730164647, "lm_q1q2_score": 0.010299972893225972}}
{"text": "﻿/*\n * File: GNGAlgorithm.cpp\n * Author: staszek \"kudkudak\" jastrzebski <grimghil<at>gmail.com>\n *\n * Created on 11 sierpień 2012, 10:02\n */\n\n//TODO: refactor getExample\n#include <cstdlib>\n#include <utility>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/date_time/posix_time/posix_time_types.hpp>\n#include <gng_algorithm.h>\n\nusing namespace boost;\nusing namespace gmum;\nusing namespace std;\n\nnamespace gmum {\n\nGNGNode ** GNGAlgorithm::LargestErrorNodesLazy() {\n\tGNGNode ** largest = new GNGNode*[2];\n\tGNGNode * gng_node;\n\n\tFOREACH(int it, errorHeap.getLazyList())\n\t{\n\t\tgng_node = &m_g[it];\n\t\terrorHeap.insert(gng_node->nr, gng_node->error);\n\t}\n\n\terrorHeap.getLazyList().clear();\n\n\tErrorNode max;\n\t//Extract max until you get correct one (that is not lazy)\n\tdo {\n\t\tmax = errorHeap.extractMax();\n\n\t\tDBG(m_logger, 4, \"GNGAlgorithm::LargestErrorLazy::found max \" + to_string(max.i));\n\n\t\tGNGNode * gng_node = &m_g[max.i];\n\t\tif (gng_node->error_cycle != c) {\n\t\t\tfixErrorNew(gng_node);\n\t\t\terrorHeap.update(gng_node->nr, gng_node->error);\n\t\t} else {\n\t\t\tlargest[0] = gng_node;\n\t\t\tint j = 0;\n\t\t\tdouble error = 0.0;\n\t\t\tDBG(m_logger, 4, \"GNGAlgorithm::LargestErrorLazy::found max \" + to_string(max.i));\n\n\t\t\tBOOST_FOREACH(GNGEdge * edg, *largest[0])\n\t\t\t{\n\t\t\t\t++j;\n\t\t\t\tfixErrorNew(&m_g[(edg)->nr]);\n\n\t\t\t\tif (j == 1) {\n\t\t\t\t\tlargest[1] = &m_g[(edg)->nr];\n\t\t\t\t\terror = largest[1]->error;\n\t\t\t\t\t;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tdouble new_error = m_g[(edg)->nr].error;\n\n\t\t\t\tif (error < new_error) {\n\t\t\t\t\terror = new_error;\n\t\t\t\t\tlargest[1] = &m_g[(edg)->nr];\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t} while (1); DBG(m_logger, 3, \"GNGAlgorithm::LargestErrorLazy::returning\");\n\treturn largest;\n\n}\n\nGNGGraph* GNGGraphAccessHack::pool = 0;\n\nGNGAlgorithm::GNGAlgorithm(GNGGraph * g, GNGDataset* db,\n\t\tdouble * boundingbox_origin, double * boundingbox_axis, double l,\n\t\tint max_nodes, int max_age, double alpha, double betha, double lambda,\n\t\tdouble eps_w, double eps_n, int dim, bool uniformgrid_optimization,\n\t\tbool lazyheap_optimization, unsigned int utility_option,\n\t\tdouble utility_k, boost::shared_ptr<Logger> logger) :\n\t\tm_g(*g), g_db(db), c(0), s(0), m_max_nodes(max_nodes), m_max_age(\n\t\t\t\tmax_age), m_alpha(alpha), m_betha(betha), m_lambda(lambda), m_eps_w(\n\t\t\t\teps_w), m_eps_n(eps_n), m_density_threshold(0.1), m_grow_rate(\n\t\t\t\t1.5), errorHeap(), dim(dim), m_toggle_uniformgrid(\n\t\t\t\tuniformgrid_optimization), m_toggle_lazyheap(\n\t\t\t\tlazyheap_optimization),  m_utility_option(\n\t\t\t\tutility_option), m_mean_error(1000), m_utility_k(utility_k), m_logger(\n\t\t\t\tlogger), m_iteration(0),\n\t\t\t\tm_gng_status(GNG_TERMINATED),\n\t\t\t\tm_gng_status_request(GNG_TERMINATED) {\n\n\tDBG(m_logger, 1, \"GNGAlgorithm:: Constructing object\");\n\tDBG(m_logger, 10,\n\t\t\t\"GNGAlgorithm::Constructed object with utility \"\n\t\t\t\t\t+ to_string(utility_option) + \" \" + to_string(utility_k));\n\n\tif (m_toggle_uniformgrid) {\n\t\tug = new UniformGrid<std::vector<Node>, Node, int>(boundingbox_origin,\n\t\t\t\tboundingbox_axis, l, dim, m_grow_rate, m_density_threshold, 0.4,\n\t\t\t\tm_logger);\n\n\t\tGNGGraphAccessHack::pool = &m_g;\n\n\t\tug->setDistFunction(GNGGraphAccessHack::dist);\n\n\t\t// Restore uniform grid state\n\t\tint maximum_index = m_g.get_maximum_index();\n\t\tREP(i, maximum_index + 1)\n\t\t\tif (m_g.existsNode(i))\n\t\t\t\tug->insert(m_g[i].position, m_g[i].nr);\n\n\t}\n\n\tif (m_toggle_lazyheap) {\n\t\tint maximum_index = m_g.get_maximum_index();\n\t\tREP(i, maximum_index + 1)\n\t\t\tif (m_g.existsNode(i))\n\t\t\t\tsetErrorNew(&m_g[i], m_g[i].error);\n\t}\n\n\tm_betha_powers_size = m_lambda * 10;\n\tm_betha_powers = new double[m_betha_powers_size];\n\n\tREP(i, m_betha_powers_size)\n\t\tm_betha_powers[i] = std::pow(m_betha, (double) (i));\n\n\tm_betha_powers_to_n_length = m_max_nodes * 2;\n\tm_betha_powers_to_n = new double[m_max_nodes * 2];\n\n\tREP(i, m_max_nodes * 2)\n\t\tm_betha_powers_to_n[i] = std::pow(m_betha, m_lambda * (double) (i));\n\tDBG(m_logger, 1, \"GNGAlgorithm:: Constructed object\");\n}\n\nvoid GNGAlgorithm::randomInit() {\n\n\tDBG(m_logger, 3, \"randomInit::Drawing examples\");\n\n\tint ex1 = g_db->drawExample();\n\tint ex2 = g_db->drawExample();\n\n\tDBG(m_logger, 3, \"randomInit::Drawn 2\");\n\tint index = 0;\n\twhile (ex2 == ex1 && index < 100) {\n\t\t++index;\n\t\tex2 = g_db->drawExample();\n\t}\n\tDBG(m_logger, 3, \"randomInit::database_size = \" + to_string(g_db->size()));\n\tDBG(m_logger, 3,\n\t\t\t\"randomInit::drawn \" + to_string(ex1) + \" \" + to_string(ex2));\n\n\tconst double * ex1_ptr = g_db->getPosition(ex1);\n\tconst double * ex1_extra_ptr = g_db->getExtraData(ex1);\n\tconst double * ex2_ptr = g_db->getPosition(ex2);\n\tconst double * ex2_extra_ptr = g_db->getExtraData(ex2);\n\n\tm_g.newNode(ex1_ptr);\n\tm_g.newNode(ex2_ptr);\n\n\tif (ex1_extra_ptr)\n\t\tm_g[0].extra_data = ex1_extra_ptr[0];\n\tif (ex2_extra_ptr)\n\t\tm_g[1].extra_data = ex2_extra_ptr[0];\n\n\tDBG(m_logger, 3,\n\t\t\t\"randomInit::created nodes graph size=\"\n\t\t\t\t\t+ to_string(m_g.get_number_nodes()));\n\n#ifdef GMUM_DEBUG_2\n\tassert(m_g.get_number_nodes()==2);\n#endif\n\n\tif (m_toggle_uniformgrid) {\n\t\tug->insert(m_g[0].position, 0);\n\t\tug->insert(m_g[1].position, 1);\n\t}\n\n\tif (m_toggle_lazyheap) {\n\t\tsetErrorNew(&m_g[0], 0.0);\n\t\tsetErrorNew(&m_g[1], 0.0);\n\t}\n\tif (this->m_utility_option == BasicUtility) {\n\t\tsetUtility(0, 0.001);\n\t\tsetUtility(1, 0.001);\n\t}\n}\n\nvoid GNGAlgorithm::addNewNode() {\n\tusing namespace std;\n\n    if (m_max_nodes <= m_g.get_number_nodes()) {\n\t\tDBG(m_logger, 4,\n\t\t\t\t\"GNGAlgorith::AddNewNode:: achieved maximum number of nodes\");\n\t\treturn;\n\t}\n\n\tLOG(m_logger, 10, \"GNGAlgorith::AddNewNode \"+to_string(m_g.get_number_nodes()));\n\n\tDBG(m_logger, 4, \"GNGAlgorith::AddNewNode::start search\");\n\n\tif (m_toggle_lazyheap)\n\t\tDBG(m_logger, 4,\n\t\t\t\t\"GNGAlgorithm::AddNewNode:: \" + to_string(m_toggle_lazyheap)\n\t\t\t\t\t\t+ \" : )= toggle_lazyheap\");\n\n\tGNGNode ** error_nodes_new;\n\n\tif (m_toggle_lazyheap)\n\t\terror_nodes_new = LargestErrorNodesLazy();\n\telse\n\t\terror_nodes_new = LargestErrorNodes();\n\n\tDBG(m_logger, 4, \"GNGAlgorith::AddNewNode::search completed\");\n\n\tif (!error_nodes_new[0] || !error_nodes_new[1])\n\t\treturn;\n\n\tDBG(m_logger, 4, \"GNGAlgorith::AddNewNode::search completed and successful\");\n\n\t\n\n\tdouble position[this->dim]; //param\n\n\t//TODO: < GNG_DIM?\n\tfor (int i = 0; i < this->dim; ++i) //param\n\t\tposition[i] = (error_nodes_new[0]->position[i]\n\t\t\t\t+ error_nodes_new[1]->position[i]) / 2;\n\n\t//In case pool has been reallocated\n\tint er_nr1 = error_nodes_new[0]->nr, er_nr2 = error_nodes_new[1]->nr;\n\tint new_node_index = m_g.newNode(&position[0]);\n\terror_nodes_new[0] = &m_g[er_nr1];\n\terror_nodes_new[1] = &m_g[er_nr2];\n\n\t//Vote for extra data\n\tm_g[new_node_index].extra_data = (error_nodes_new[0]->extra_data\n\t\t\t+ error_nodes_new[1]->extra_data) / 2.0;\n\n\tif (m_toggle_uniformgrid)\n\t\tug->insert(m_g[new_node_index].position, new_node_index);\n\n\tDBG(m_logger, 4, \"GNGAlgorith::AddNewNode::added \" + to_string(m_g[new_node_index]));\n\n\tm_g.removeUDEdge(error_nodes_new[0]->nr, error_nodes_new[1]->nr);\n\n\tDBG(m_logger, 3, \"GNGAlgorith::AddNewNode::removed edge beetwen \" +\n\t\t\tto_string(error_nodes_new[0]->nr) + \" and\" + to_string(error_nodes_new[1]->nr));\n\tDBG(m_logger, 2,\n\t\t\t\"GNGAlgorithm::AddNewNode::largest error node after removing edge : \"\n\t\t\t\t\t+ to_string(*error_nodes_new[0]));\n\n\tm_g.addUDEdge(error_nodes_new[0]->nr, new_node_index);\n\n\tm_g.addUDEdge(new_node_index, error_nodes_new[1]->nr);\n\n\tDBG(m_logger, 3, \"GNGAlgorith::AddNewNode::add edge beetwen \" +\n\t\t\tto_string(error_nodes_new[0]->nr) + \" and\" + to_string(new_node_index));\n\n\tif (!m_toggle_lazyheap) {\n\t\tdecreaseError(error_nodes_new[0]);\n\t\tdecreaseError(error_nodes_new[1]);\n\t\tsetError(&m_g[new_node_index],\n\t\t\t\t(error_nodes_new[0]->error + error_nodes_new[1]->error) / 2);\n\t} else {\n\t\tdecreaseErrorNew(error_nodes_new[0]);\n\t\tdecreaseErrorNew(error_nodes_new[1]);\n\t\tsetErrorNew(&m_g[new_node_index],\n\t\t\t\t(error_nodes_new[0]->error + error_nodes_new[1]->error) / 2);\n\t}\n\n\tif (this->m_utility_option == BasicUtility)\n\t\tthis->setUtility(new_node_index,\n\t\t\t\t0.5\n\t\t\t\t\t\t* (getUtility(error_nodes_new[0]->nr)\n\t\t\t\t\t\t\t\t+ getUtility(error_nodes_new[1]->nr)));\n\n\tdelete[] error_nodes_new;\n\tDBG(m_logger, 3, \"GNGAlgorith::AddNewNode::delete done\");\n}\n\n\nint GNGAlgorithm::predict(const std::vector<double> & ex) {\n\n\tif (m_g.get_number_nodes() == 0)\n\t\treturn -1; //No node\n\n\tif (ex.size() != g_db->getGNGDim())\n\t\tthrow BasicException(\"Wrong example dimensionality\");\n\n\treturn _getNearestNeurons(&ex[0]).first;\n}\n\nstd::pair<double, int> GNGAlgorithm::adapt(const double * ex,\n\t\tconst double * extra) {\n\tDBG(m_logger, 4, \"GNGAlgorith::Adapt::commence search\");\n\n\tstd::pair<int, int> nearest = _getNearestNeurons(ex);\n\tGNGNode * nearest_0 = &m_g[nearest.first], * nearest_1 = &m_g[nearest.second];\n\n\n\tDBG(m_logger, 4, \"GNGAlgorith::Adapt::found nearest nodes to the drawn example \" + to_string(*nearest_0) + \" \" + to_string(*nearest_1));\n\n\tdouble error = m_g.get_dist(nearest_0->position, ex);\n\n\tif (this->m_utility_option == BasicUtility) {\n\n\t\tDBG(m_logger, 4, \"GNGAlgorithm::Adapt::setting utility\");\n\n\t\tdouble error_2 = m_g.get_dist(nearest_1->position, ex);\n\n\t\tthis->setUtility(nearest_0->nr,\n\t\t\t\tthis->getUtility(nearest_0->nr) + error_2 - error);\n\t}\n\n\tDBG(m_logger, 3, \"GNGAlgorith::Adapt::increasing error\");\n\n\tif (!m_toggle_lazyheap)\n\t\tincreaseError(nearest_0, error);\n\telse\n\t\tincreaseErrorNew(nearest_0, error);\n\n\tDBG(m_logger, 3, \"GNGAlgorith::Adapt::accounted for the error\");\n\n\tif (m_toggle_uniformgrid)\n\t\tug->remove(nearest_0->position);\n\tfor (int i = 0; i < this->dim; ++i)\n\t\tnearest_0->position[i] += m_eps_w * (ex[i] - nearest_0->position[i]);\n\n\t//Adapt to extra dimensionality if present (TODO: refactor)\n\tif (extra)\n\t\tnearest_0->extra_data = (nearest_0->extra_data + extra[0]) / 2.0;\n\n\tif (m_toggle_uniformgrid)\n\t\tug->insert(nearest_0->position, nearest_0->nr);\n\n\tif (nearest_0->edgesCount) {\n\t\tFOREACH(GNGEdge * edg, *nearest_0)\n\t\t{\n\t\t\tif (m_toggle_uniformgrid)\n\t\t\t\tug->remove(m_g[(edg)->nr].position);\n\n\t\t\tfor (int i = 0; i < this->dim; ++i) { //param accounting\n\t\t\t\tm_g[(edg)->nr].position[i] += m_eps_n\n\t\t\t\t\t\t* (ex[i] - m_g[(edg)->nr].position[i]);\n\t\t\t}\n\n\t\t\t//Adapt to extra dimensionality if present (TODO: refactor)\n\t\t\tif (extra) {\n\t\t\t\tm_g[(edg)->nr].extra_data = (0.9 * m_g[(edg)->nr].extra_data\n\t\t\t\t\t\t+ extra[0] * 0.1);\n\t\t\t}\n\n\t\t\tif (m_toggle_uniformgrid)\n\t\t\t\tug->insert(m_g[(edg)->nr].position, (edg)->nr);\n\t\t}\n\t}\n\n\tDBG(m_logger, 4,\n\t\t\t\"GNGAlgorith::Adapt::position of the winner and neighbour mutated\");\n\n\tif (!m_g.isEdge(nearest_0->nr, nearest_1->nr)) {\n\t\tm_g.addUDEdge(nearest_0->nr, nearest_1->nr);\n\t\tDBG(m_logger, 4,\n\t\t\t\t\"GNGAlgorith::Adapt::added edge beetwen \"\n\t\t\t\t\t\t+ to_string(nearest_0->nr) + \" and \"\n\t\t\t\t\t\t+ to_string(nearest_1->nr));\n\t}\n\n\tbool BYPASS = false;\n\n\tDBG(m_logger, 4, \"GNGAlgorith::Adapt::commence scan of edges\");\n\n\t//TODO: assuming here GNGNode not any arbitrary node :/\n\tGNGNode::EdgeIterator edg = nearest_0->begin();\n\twhile (edg != nearest_0->end()) {\n\t\tDBG(m_logger, 2, \"Currently on edge to\" + to_string((edg)->nr));\n\n\t\t(*edg)->age++;\n\t\t(((*edg)->rev))->age++;\n\n\t\tif ((*edg)->nr == nearest_1->nr) {\n\t\t\t(*edg)->age = 0;\n\t\t\t(((*edg)->rev))->age = 0;\n\t\t}\n\n\t\tif ((*edg)->age > m_max_age) {\n\n\t\t\tDBG(m_logger, 3,\n\t\t\t\t\t\"GNGAlgorith::Adapt::Removing aged edge \"\n\t\t\t\t\t\t\t+ to_string(nearest_0->nr) + \" - \"\n\t\t\t\t\t\t\t+ to_string((edg)->nr));\n\n\t\t\tint nr = (*edg)->nr;\n\n\t\t\t//Note that this is O(E), but average number of edges is very small, so it is OK\n\t\t\tedg = m_g.removeUDEdge(nearest_0->nr, nr);\n\n\t\t\tif (m_g[nr].edgesCount == 0 && this->m_utility_option == None) {\n\n\t\t\t\tDBG(m_logger, 8, \"GNGAlgorith:: remove node because no edges\");\n\n#ifdef DEBUG_GMUM_2\n\t\t\t\tFOREACH(GNGEdge* edg2, m_g[nr])\n\t\t\t\t{\n\t\t\t\t\tcerr<<\"WARNING: GNGAlgorithm:: edges count of neighbours of erased node, shouldn't happen! \" + to_string(m_g[(edg2)->nr].edgesCount)<<endl;\n\t\t\t\t}\n#endif\n\n\t\t\t\tif (m_toggle_uniformgrid)\n\t\t\t\t\tug->remove(m_g[nr].position);\n\n\t\t\t\tDBG(m_logger, 8,\n\t\t\t\t\t\t\"GNGAlgorithm::Adapt() Erasing node \"\n\t\t\t\t\t\t\t\t+ to_string<int>(nr));\n\t\t\t\tDBG(m_logger, 8,\n\t\t\t\t\t\t\"GNGAlgorithm::Adapt() First coordinate \"\n\t\t\t\t\t\t\t\t+ to_string<double>(m_g[nr].position[0]));\n\n\t\t\t\tm_g.deleteNode(nr);\n\t\t\t}\n\t\t\tif (m_g[nearest_0->nr].edgesCount == 0\n\t\t\t\t\t&& this->m_utility_option == None) {\n\n\t\t\t\tDBG(m_logger, 49,\n\t\t\t\t\t\t\"WARNING: GNGAlgorithm::Adapt() remove node because no edges, shouldn't happen\"); //Shouldn't happen\n\n\t\t\t\tif (m_toggle_uniformgrid)\n\t\t\t\t\tug->remove(m_g[nearest_0->nr].position);\n\t\t\t\tm_g.deleteNode(nearest_0->nr);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (edg != nearest_0->end())\n\t\t\t\t--edg;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t\tDBG(m_logger, 3, \"GNGAlgorith::Adapt::Removal completed\");\n\t\t}\n\t\t++edg;\n\t}\n\n\t//erase nodes\n\tif (this->m_utility_option == BasicUtility)\n\t\tthis->utilityCriterionCheck();\n\n\treturn std::pair<double, int>(error, nearest.first);\n}\n\ndouble GNGAlgorithm::calculateAccumulatedError() {\n\n\tint maximum_index = m_g.get_maximum_index();\n\tm_accumulated_error = 0.0;\n\n\tif (this->m_toggle_lazyheap) {\n\n\t\tm_g.lock();\n\t\tint maximum_index = m_g.get_maximum_index();\n\t\tm_accumulated_error = 0.0;\n\n\t\tREP(i, maximum_index + 1)\n\t\t\tif (m_g.existsNode(i))\n\t\t\t\tm_accumulated_error += m_g[i].error;\n\n\t\tm_g.unlock();\n\t\treturn m_accumulated_error;\n\t} else {\n\t\tm_g.lock();\n\t\tm_accumulated_error = 0.0;\n\t\tREP(i, maximum_index + 1)\n\t\t\tif (m_g.existsNode(i))\n\t\t\t\tm_accumulated_error += m_g[i].error;\n\n\t\tm_g.unlock();\n\t\treturn m_accumulated_error;\n\t}\n}\n\nvoid GNGAlgorithm::testAgeCorrectness() {\n\tint maximum_index = m_g.get_maximum_index();\n\tREP(i, maximum_index + 1)\n\t\tif (m_g.existsNode(i) && m_g[i].edgesCount)\n\t\t\tBOOST_FOREACH(GNGEdge* edg, m_g[i])\n\t\t\t\tif ((edg)->age > m_max_age) {\n\t\t\t\t\t//cout << \"XXXXXXXXXXXXXXXXX\\n\";\n\t\t\t\t\t//cout << (m_g[i]) << endl;\n\t\t\t\t}\n}\n\nvoid GNGAlgorithm::resizeUniformGrid() {\n\n\tDBG(m_logger, 6, \"GNGAlgorithm::Resize Uniform Grid\");\n\tDBG(m_logger, 6,\n\t\t\t\"GNGAlgorithm::Resize Uniform Grid old_l=\"\n\t\t\t\t\t+ to_string(ug->getCellLength()));\n\tDBG(m_logger, 6,\n\t\t\t\"GNGAlgorithm::Resize Uniform Grid new_l=\"\n\t\t\t\t\t+ to_string(ug->getCellLength() / m_grow_rate));\n\n\tug->new_l(ug->getCellLength() / m_grow_rate);\n\n\tint maximum_index = m_g.get_maximum_index();\n\n\tREP(i, maximum_index + 1)\n\t\tif (m_g.existsNode(i))\n\t\t\tug->insert(m_g[i].position, m_g[i].nr);\n\n}\n\nGNGNode ** GNGAlgorithm::LargestErrorNodes() {\n\tDBG(m_logger, 2, \"LargestErrorNodes::started procedure\");\n\n\tGNGNode ** largest = new GNGNode*[2];\n\n\tlargest[0] = 0;\n\tlargest[1] = 0;\n\tdouble error = -1.0;\n\n\tREP(i, m_g.get_maximum_index() + 1)\n\t\tif (m_g.existsNode(i))\n\t\t\terror = std::max(error, m_g[i].error);\n\n\tDBG(m_logger, 2, \"LargestErrorNodes::found maximum error\");\n\n\tREP(i, m_g.get_maximum_index() + 1)\n\t\tif (m_g.existsNode(i))\n\t\t\tif (m_g[i].error == error)\n\t\t\t\tlargest[0] = &m_g[i];\n\n\tDBG(m_logger, 2, \"LargestErrorNodes::largest picked\");\n\n\tif (largest[0]->edgesCount == 0) { //{largest[0]->error=0; return largest;} //error?\n\t\tm_g.deleteNode(largest[0]->nr);\n\t\treturn largest;\n\t}\n\n\tint j = 0;\n\n\tFOREACH(GNGEdge* edg, *largest[0])\n\t{\n\t\t++j;\n\n\t\tif (j == 1) {\n\t\t\tlargest[1] = &m_g[(edg)->nr];\n\t\t\terror = largest[1]->error;\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble new_error = m_g[(edg)->nr].error;\n\n\t\tif (error < new_error) {\n\t\t\terror = new_error;\n\t\t\tlargest[1] = &m_g[(edg)->nr];\n\t\t}\n\t}\n\n\treturn largest;\n}\n\nvoid GNGAlgorithm::updateClustering() {\n\tgmum::scoped_lock<GNGDataset> db_lock(*g_db);\n\tfor(unsigned int i=0;i<g_db->size();++i){\n\t\tset_clustering(i, _getNearestNeurons(g_db->getPosition(i)).first);\n\t}\n}\n\nvoid GNGAlgorithm::runAlgorithm() { //1 thread needed to do it (the one that computes)\n    m_gng_status = m_gng_status_request = GNG_RUNNING;\n\t//Initialize global counters\n\ts = 0;\n\tc = 0; // cycle variable for lazyheap optimization\n\n\tLOG(m_logger, 7, \"GNGAlgorithm::check size of the db \" + to_string(g_db->size()));\n\n\twhile (g_db->size() < 2) {\n        this->status_change_mutex.lock();\n\t\twhile (m_gng_status_request == GNG_PAUSED) {\n\t\t\tif (m_gng_status_request == GNG_TERMINATED){\n\t\t\t\tm_gng_status = GNG_TERMINATED;\n\t\t\t\tstatus_change_mutex.unlock();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis->status_change_condition.wait(this->status_change_mutex);\n\t\t}\n        this->status_change_mutex.unlock();\n\t}\n\n\tif (m_g.get_number_nodes() == 0) {\n\t\tgmum::scoped_lock<GNGDataset> db_lock(*g_db);\n\t\tgmum::scoped_lock<GNGGraph> graph_lock(m_g);\n\t\trandomInit();\n\t} else if (m_g.get_number_nodes() == 1) {\n\t\tcerr << \"Incorrect passed graph to GNGAlgorithm. Aborting\\n\";\n\t\tthrow BasicException(\"Incorrect passed graph to GNGAlgorithm\");\n\t}\n\n\t//We have to calculate error so we will collect error from adapt\n\t//and when count is > dataset size we will set m_mean_error\n\tdouble accumulated_error = 0.0;\n\tdouble time_elapsed =0., time_elapsed_last_error=0.;\n\tint accumulated_error_count = 0, accumulated_error_count_last = 0;\n\n\tLOG(m_logger, 3, \"GNGAlgorithm::init successful, starting the loop\"); \n    LOG(m_logger, 10, \"GNGAlgorithm::gng_status=\"+to_string(this->m_gng_status));\n    LOG(m_logger, 10, \"GNGAlgorithm::gng_status_request=\"+to_string(this->m_gng_status_request));\n\twhile (true) {\n\t\tthis->status_change_mutex.lock();\n\t\twhile (this->m_gng_status_request == GNG_PAUSED) {\n\t\t\tm_gng_status = m_gng_status_request;\n\t\t\tthis->status_change_condition.wait(this->status_change_mutex);\n\t\t}\n\t\tif (this->m_gng_status_request == GNG_TERMINATED){\n\t        LOG(m_logger, 10, \"GNGAlgorithm::terminate request\"); \n\t\t    this->status_change_mutex.unlock();\n\t\t\tbreak;\n\t\t}\n\t\tthis->status_change_mutex.unlock();\n\t\tm_gng_status = GNG_RUNNING;\n\n\t\tdouble dt =0.;\n\t\tboost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();\n\n\t\tfor (s = 0; s < m_lambda; ++s) { //global counter!!\n\n\t\t\tconst double * position, *vertex_data;\n\t\t\tunsigned int ex = 0;\n\t\t\t{\n\t\t\t\t//Fined grained locks are necessary to prevent deadlocks\n\t\t\t\tgmum::scoped_lock<GNGDataset> db_lock(*g_db);\n\t\t\t\tex = g_db->drawExample();\n\n\n\t\t\t\tposition = g_db->getPosition(ex);\n\t\t\t\tvertex_data = g_db->getExtraData(ex);\n\t\t\t\tDBG(m_logger, 0, \"GNGAlgorithm::draw example\");\n\t\t\t}\n\n\t\t\tgmum::scoped_lock<GNGGraph> graph_lock(m_g);\n\t\t\tstd::pair<double, int> adapt_result = adapt(position, vertex_data);\n\n#ifdef GMUM_DEBUG\n\t\t\tassert(adapt_result.second >= 0);\n#endif\n\n\t\t\tset_clustering(ex, adapt_result.second);\n\t\t\taccumulated_error += adapt_result.first;\n\t\t\taccumulated_error_count += 1;\n\t\t}\n\n#ifdef GMUM_DEBUG_2\n\t\tfor (int i = 0; i <= m_g.get_maximum_index(); ++i) { //another idea for storing list of actual nodes?\n\t\t\tif (m_g.existsNode(i) && m_g[i].edgesCount == 0 && m_utility_option == None) {\n\t\t\t\tcerr<<\"Error at \" + to_string<int>(i))<<endl;\n\t\t\t}\n\t\t}\n#endif\n\n\t\tdt = ((boost::posix_time::microsec_clock::local_time() - start).total_milliseconds()+ 1.)/1000.0 ;\n\t\ttime_elapsed += dt;\n\t\ttime_elapsed_last_error += dt;\n\n\t\t//Calculate mini-batch error\n\t\tif ((time_elapsed_last_error > 0.1 && accumulated_error_count > 5 * m_g.get_number_nodes()) ||\n\t\t\t\taccumulated_error_count > 15 * m_g.get_number_nodes()) {\n\t\t\tgmum::scoped_lock<gmum::fast_mutex> stat_lock(m_statistics_mutex);\n\n\t\t\tm_mean_error.push_back(make_pair<double, double>(time_elapsed,\n\t\t\t\t\taccumulated_error/(double)accumulated_error_count\n\t\t\t\t\t));\n\n\t\t\taccumulated_error_count_last = accumulated_error_count;\n\t\t\ttime_elapsed_last_error = 0.0;\n\t\t\taccumulated_error = 0.0;\n\t\t\taccumulated_error_count = 0;\n\t\t}\n\n\t\t{\n\t\t\tgmum::scoped_lock<GNGGraph> graph_lock(m_g);\n\t\t\taddNewNode();\n\n\t\t\tif (m_toggle_uniformgrid && ug->check_grow()) {\n\t\t\t\tDBG(m_logger, 10, \"GNGAlgorithm:: resizing uniform grid\");\n\t\t\t\tresizeUniformGrid();\n\t\t\t}\n\n\t\t\t++c; //epoch\n\t\t\tif (!m_toggle_lazyheap)\n\t\t\t\tdecreaseAllErrors();\n\t\t\tif (this->m_utility_option == BasicUtility)\n\t\t\t\tdecreaseAllUtility();\n\t\t}\n\t\t++m_iteration;\n\n\t\tDBG(m_logger, 9, \"GNGAlgorithm::iteration \"+to_string(m_iteration));\n\t}\n\tm_gng_status = GNG_TERMINATED\n\tDBG(m_logger, 30, \"GNGAlgorithm::Terminated server\");\n}\n\n\n\n\n\n\n\n\n\n\n/** Start algorithm loop */\nvoid GNGAlgorithm::run(bool synchronized) {\n    //TODO: refactor run to resume?\n    if(m_gng_status == GNG_TERMINATED){\n        return;\n    }\n\n    if(m_gng_status != GNG_RUNNING){\n\t    m_gng_status_request = GNG_RUNNING;\n\t    this->status_change_condition.notify_all();\n    }\n    if(this->g_db->size() > 2 && synchronized){ \n        //Algorithm should start. Run is synchronized. \n        //Terminated is also accepted state\n        while(m_gng_status == GNG_PAUSED){\n            gmum::sleep(10);\n        }\n    }\n}\n\nbool GNGAlgorithm::isRunning(){\n\treturn this->m_gng_status == GNG_RUNNING;\n}\n\n/** Pause algorithm loop */\nvoid GNGAlgorithm::pause(bool synchronized) {\n    if(this->m_gng_status != GNG_PAUSED){\n\t    this->m_gng_status_request = GNG_PAUSED;\n\t    this->status_change_condition.notify_all();\n    }\n    if(this->g_db->size() > 2 && synchronized){\n         //Terminated is also accepted state\n         while(m_gng_status == GNG_RUNNING){\n            gmum::sleep(10);        \n         }\n    }\n}\n\n/** Terminate the algorithm */\nvoid GNGAlgorithm::terminate(bool synchronized) {\n    if(this->m_gng_status != GNG_TERMINATED){\n\t    this->m_gng_status_request = GNG_TERMINATED;\n\t    this->status_change_condition.notify_all();\n    }\n    if(synchronized){\n        while(m_gng_status == GNG_RUNNING){\n            gmum::sleep(10);        \n        }\n    }\n}\n\nvoid GNGAlgorithm::setMaxNodes(int value) {\n\tm_max_nodes = value;\n}\n\nint GNGAlgorithm::getIteration() const{\n\treturn m_iteration;\n}\n\nunsigned GNGAlgorithm::getErrorIndex() const{\n\treturn m_mean_error.size();\n}\n\ndouble GNGAlgorithm::getMeanError() {\n\n\tgmum::scoped_lock<gmum::fast_mutex> alg_lock(m_statistics_mutex);\n\tDBG(m_logger, 3, gmum::to_string(m_mean_error.size()));\n\tif(m_mean_error.size() == 0){\n\t\treturn -1.0;\n\t}else{\n\n\t\treturn m_mean_error[m_mean_error.size()-1].second;\n\t}\n}\n\nvector<pair<double, double> > GNGAlgorithm::getMeanErrorStatistics() {\n\tgmum::scoped_lock<gmum::fast_mutex> alg_lock(m_statistics_mutex);\n\tif(m_mean_error.size() == 0){\n\t\treturn vector<pair<double, double> >(1, make_pair<double,double>(0., std::numeric_limits<double>::max()));\n\t}else{\n\t\treturn vector<pair<double, double> >(m_mean_error.begin(), m_mean_error.end());\n\t}\n}\n\n//Retrieve clustering result.\n//@note pauses algorithm as many\nconst vector<int> & GNGAlgorithm::get_clustering(){\n\tbool was_running = false;\n\tif(isRunning()){\n\t\twas_running = true;\n\t\tpause();\n\t}\n\tvector<int> & result = clustering_result;\n\tif(was_running)\n\t\trun();\n\n\treturn result;\n}\n\n GNGAlgorithm::~GNGAlgorithm() {\n\tdelete[] m_betha_powers_to_n;\n\tdelete[] m_betha_powers;\n}\n\n\n\nstd::pair<int, int> GNGAlgorithm::_getNearestNeurons(const double *ex){\n\tif (m_toggle_uniformgrid) {\n\t\t\tDBG(m_logger, 1, \"GNGAlgorithm::Adapt::Graph size \" + to_string(m_g.get_number_nodes()));\n\t\t\tstd::vector<int> nearest_index = ug->findNearest(ex, 2); //TwoNearestNodes(ex->position);\n\t\t\tDBG(m_logger, 1, \"GNGAlgorithm::Adapt::Found nearest\");\n\n\t\t\t#ifdef GMUM_DEBUG_2\n\t\t\t\t\tif (nearest_index[0] == nearest_index[1]) {\n\t\t\t\t\t\tcerr<<\"Adapt::Found same nearest_indexes!~! \"+to_string(nearest_index[0])<<endl;\n\t\t\t\t\t\tthrow BasicException(\"Found same nearest_indexes\");  //something went wrong (-1==-1 też)\n\t\t\t\t\t}\n\t\t\t#endif\n\n\n\t\t\t#ifdef GMUM_DEBUG_2\n\t\t\t\t\tassert(m_g[nearest_index[1]].position > m_g.get_dist(m_g[nearest_index[0]].position, ex));\n\t\t\t#endif\n\n\t\t\treturn std::pair<int, int>(nearest_index[0], nearest_index[1]);\n\t\t} else {\n\t\t\tDBG(m_logger, 1, \"GNGAlgorithm::just called TwoNearestNodes\");\n\t\t\tint start_index = 0;\n\t\t\twhile (!m_g.existsNode(start_index))\n\t\t\t\t++start_index;\n\n\t\t\tdouble dist0 = m_g.get_dist(ex, m_g[start_index].position);\n\t\t\tint best_0 = start_index, best_1 = -1;\n\t\t\tfor (int i = start_index + 1; i <= m_g.get_maximum_index(); ++i) {\n\t\t\t\tif (m_g.existsNode(i)) {\n\t\t\t\t\tdouble new_dist = m_g.get_dist(ex, m_g[i].position);\n\t\t\t\t\tif (dist0 > new_dist) {\n\t\t\t\t\t\tdist0 = new_dist;\n\t\t\t\t\t\tbest_0 = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tDBG(m_logger, 1, \"finding next\\n\");\n\n\t\t\tstart_index = 0;\n\t\t\twhile (!m_g.existsNode(start_index) || start_index == best_0)\n\t\t\t\t++start_index;\n\t\t\tdouble dist1 = m_g.get_dist(ex, m_g[start_index].position);\n\t\t\tbest_1 = start_index;\n\n\t\t\tfor (int i = start_index + 1; i <= m_g.get_maximum_index(); ++i) { //another idea for storing list of actual nodes?\n\t\t\t\tif (m_g.existsNode(i) && i != best_0) {\n\t\t\t\t\tdouble new_dist = m_g.get_dist(ex, m_g[i].position);\n\t\t\t\t\tif (dist1 > new_dist) {\n\t\t\t\t\t\tdist1 = new_dist;\n\t\t\t\t\t\tbest_1 = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t#ifdef GMUM_DEBUG_2\n\t\t\t\tassert(dist1 > dist0);\n\t\t\t#endif\n\n\t\t\treturn std::pair<int, int>(best_0, best_1);\n\t\t}\n}\n\n\nvoid GNGAlgorithm::resetUniformGrid(double * orig, double *axis, double l) {\n\tug->purge(orig, axis, l);\n\tint maximum_index = m_g.get_maximum_index();\n\n\tREP(i, maximum_index + 1)\n\t{\n\t\tif (m_g.existsNode(i))\n\t\t\tug->insert(m_g[i].position, m_g[i].nr);\n\t}\n}\n\nbool GNGAlgorithm::stoppingCriterion() {\n\treturn m_g.get_number_nodes() > m_max_nodes;\n}\n\nvoid GNGAlgorithm::increaseErrorNew(GNGNode * node, double error) {\n\tfixErrorNew(node);\n\tassert(m_lambda - s <= m_betha_powers_size -1);\n\tnode->error += m_betha_powers[m_lambda - s] * error;\n\terrorHeap.updateLazy(node->nr);\n}\n\nvoid GNGAlgorithm::fixErrorNew(GNGNode * node) {\n\n\tif (node->error_cycle == c)\n\t\treturn;\n\n\twhile(c - node->error_cycle > m_betha_powers_to_n_length - 1){\n\t\tDBG(m_logger, 5, \"Recreating m_betha_powers_to_n\");\n\t\tdelete[] m_betha_powers_to_n;\n\t\tm_betha_powers_to_n_length *= 2;\n\t\tm_betha_powers_to_n = new double[m_betha_powers_to_n_length];\n\t\tREP(i, m_betha_powers_to_n_length)\n\t\tm_betha_powers_to_n[i] = std::pow(m_betha, m_lambda * (double) (i));\n\t}\n\n\tassert(c - node->error_cycle  <= m_betha_powers_to_n_length -1);\n\n\tnode->error = m_betha_powers_to_n[c - node->error_cycle] * node->error;\n\tnode->error_cycle = c;\n\n}\n\n\nvoid GNGAlgorithm::set_clustering(unsigned int ex, unsigned int node_idx){\n\n\tif(ex + 1 > clustering_result.size()){\n\t\tDBG(m_logger, 6, \"Resizing clustering_result to \"+to_string(g_db->size()));\n\t\tclustering_result.resize(g_db->size());\n\t}\n\n\t//Can potentially happen in case of shrinkage of dataset size\n\tif(ex + 1 > clustering_result.size()){\n\t\tcerr<<\"g_db->size mismatch with ex index?\\n\";\n\t\treturn;\n\t}\n\n\n\tclustering_result[ex] = node_idx;\n}\n\ndouble GNGAlgorithm::getMaximumError() const {\n\tdouble max_error = 0;\n\tint maximum_index = m_g.get_maximum_index();\n\tREP(i,maximum_index+1)\n\t\tif (m_g.existsNode(i))\n\t\t\tmax_error = std::max(max_error, m_g[i].error);\n\treturn max_error;\n}\n\nvoid GNGAlgorithm::decreaseAllErrorsNew() {\n\treturn;\n}\n\nvoid GNGAlgorithm::decreaseErrorNew(GNGNode * node) {\n\tfixErrorNew(node);\n\tnode->error = m_alpha * node->error;\n\terrorHeap.updateLazy(node->nr);\n}\n\nvoid GNGAlgorithm::setErrorNew(GNGNode * node, double error) {\n\tnode->error = error;\n\tnode->error_cycle = c;\n\terrorHeap.insertLazy(node->nr);\n}\n\nvoid GNGAlgorithm::increaseError(GNGNode * node, double error) {\n\tnode->error += error;\n}\n\nvoid GNGAlgorithm::decreaseAllErrors() {\n\tint maximum_index = m_g.get_maximum_index();\n\tREP(i,maximum_index+1)\n\t\tif (m_g.existsNode(i))\n\t\t\tm_g[i].error = m_betha * m_g[i].error;\n}\n\nvoid GNGAlgorithm::decreaseError(GNGNode * node) {\n\tnode->error = m_alpha * node->error;\n}\n\nvoid GNGAlgorithm::setError(GNGNode * node, double error) {\n\tnode->error = error;\n}\n\n// Note: this code is not optimal and is inserted only for research purposes\n\ndouble GNGAlgorithm::getUtility(int i) {\n\treturn m_g[i].utility;\n}\n\nvoid GNGAlgorithm::setUtility(int i, double u) {\n\tm_g[i].utility = u;\n}\n\nvoid GNGAlgorithm::utilityCriterionCheck() {\n\n\tif (m_g.get_number_nodes() < 10)\n\t\treturn; //just in case\n\n\tdouble max_error = this->getMaximumError();\n\tint maximum_index = m_g.get_maximum_index();\n\n\tdouble min_utility = 100000000;\n\tint min_utility_index = -1;\n\n\tfor (int i = 0; i <= maximum_index; ++i)\n\t\tif (min_utility > getUtility(i)) {\n\t\t\tmin_utility = getUtility(i);\n\t\t\tmin_utility_index = i;\n\t\t}\n\n\tif (m_g.existsNode(min_utility_index) && max_error / getUtility(min_utility_index) > m_utility_k) {\n\n\t\tDBG(m_logger,2, \"GNGAlgorithm:: removing node with utility \"+gmum::to_string(getUtility(min_utility_index)) + \" max error \"+gmum::to_string(max_error));\n\n\t\tDBG(m_logger,2,gmum::to_string<double>(max_error));\n\n\t\tGNGNode::EdgeIterator edg = m_g[min_utility_index].begin();\n\t\twhile (edg != m_g[min_utility_index].end()) {\n\t\t\tint nr = (*edg)->nr;\n\t\t\tedg = m_g.removeUDEdge(min_utility_index, nr);\n\t\t}\n\n\t\tm_g.deleteNode(min_utility_index);\n\t\tsetUtility(min_utility_index, 0);\n\t}\n\n}\nvoid GNGAlgorithm::decreaseAllUtility() {\n\tint maximum_index = m_g.get_maximum_index();\n\tfor (int i = 0; i <= maximum_index; ++i)\n\t\tif (m_g.existsNode(i))\n\t\t\tsetUtility(i, getUtility(i) * (m_betha));\n}\n\n\n\n\n\n\n\n\n\n\n\n\n}\n", "meta": {"hexsha": "6b71816be1ab7d0ab6d22d83172a5d56268554db", "size": 28327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gng/gng_algorithm.cpp", "max_stars_repo_name": "kudkudak/Growing-Neural-Gas", "max_stars_repo_head_hexsha": "c1c72fe4f33cebe203f094babbe9b2bdddb85a02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T08:54:56.000Z", "max_issues_repo_path": "src/gng/gng_algorithm.cpp", "max_issues_repo_name": "kudkudak/Growing-Neural-Gas", "max_issues_repo_head_hexsha": "c1c72fe4f33cebe203f094babbe9b2bdddb85a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T09:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-25T15:53:44.000Z", "max_forks_repo_path": "src/gng/gng_algorithm.cpp", "max_forks_repo_name": "kudkudak/Growing-Neural-Gas", "max_forks_repo_head_hexsha": "c1c72fe4f33cebe203f094babbe9b2bdddb85a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-03-26T08:45:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T23:02:11.000Z", "avg_line_length": 26.9780952381, "max_line_length": 154, "alphanum_fraction": 0.6810110495, "num_tokens": 8699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.025957358799003922, "lm_q1q2_score": 0.010280883870921274}}
{"text": "// Copyright 2018 Ulf Adams\n//\n// The contents of this file may be used under the terms of the Apache License,\n// Version 2.0.\n//\n//    (See accompanying file LICENSE-Apache or copy at\n//     http://www.apache.org/licenses/LICENSE-2.0)\n//\n// Alternatively, the contents of this file may be used under the terms of\n// the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE-Boost or copy at\n//     https://www.boost.org/LICENSE_1_0.txt)\n//\n// Unless required by applicable law or agreed to in writing, this software\n// is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n// KIND, either express or implied.\n\n// Runtime compiler options:\n// -DRYU_DEBUG Generate verbose debugging output to stdout.\n//\n// -DRYU_ONLY_64_BIT_OPS Avoid using uint128_t or 64-bit intrinsics. Slower,\n//     depending on your compiler.\n//\n// -DRYU_OPTIMIZE_SIZE Use smaller lookup tables. Instead of storing every\n//     required power of 5, only store every 26th entry, and compute\n//     intermediate values with a multiplication. This reduces the lookup table\n//     size by about 10x (only one case, and only double) at the cost of some\n//     performance. Currently requires MSVC intrinsics.\n\n/*\n    This is a derivative work\n*/\n\n#ifndef BOOST_JSON_DETAIL_RYU_IMPL_D2S_IPP\n#define BOOST_JSON_DETAIL_RYU_IMPL_D2S_IPP\n\n#include <boost/json/detail/ryu/ryu.hpp>\n#include <cstdlib>\n#include <cstring>\n\n#ifdef RYU_DEBUG\n#include <stdio.h>\n#endif\n\n// ABSL avoids uint128_t on Win32 even if __SIZEOF_INT128__ is defined.\n// Let's do the same for now.\n#if defined(__SIZEOF_INT128__) && !defined(_MSC_VER) && !defined(RYU_ONLY_64_BIT_OPS)\n#define BOOST_JSON_RYU_HAS_UINT128\n#elif defined(_MSC_VER) && !defined(RYU_ONLY_64_BIT_OPS) && defined(_M_X64)\n#define BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS\n#endif\n\n#include <boost/json/detail/ryu/detail/common.hpp>\n#include <boost/json/detail/ryu/detail/digit_table.hpp>\n#include <boost/json/detail/ryu/detail/d2s.hpp>\n#include <boost/json/detail/ryu/detail/d2s_intrinsics.hpp>\n\nnamespace boost {\nnamespace json {\nnamespace detail {\n\nnamespace ryu {\nnamespace detail {\n\n// We need a 64x128-bit multiplication and a subsequent 128-bit shift.\n// Multiplication:\n//   The 64-bit factor is variable and passed in, the 128-bit factor comes\n//   from a lookup table. We know that the 64-bit factor only has 55\n//   significant bits (i.e., the 9 topmost bits are zeros). The 128-bit\n//   factor only has 124 significant bits (i.e., the 4 topmost bits are\n//   zeros).\n// Shift:\n//   In principle, the multiplication result requires 55 + 124 = 179 bits to\n//   represent. However, we then shift this value to the right by j, which is\n//   at least j >= 115, so the result is guaranteed to fit into 179 - 115 = 64\n//   bits. This means that we only need the topmost 64 significant bits of\n//   the 64x128-bit multiplication.\n//\n// There are several ways to do this:\n// 1. Best case: the compiler exposes a 128-bit type.\n//    We perform two 64x64-bit multiplications, add the higher 64 bits of the\n//    lower result to the higher result, and shift by j - 64 bits.\n//\n//    We explicitly cast from 64-bit to 128-bit, so the compiler can tell\n//    that these are only 64-bit inputs, and can map these to the best\n//    possible sequence of assembly instructions.\n//    x64 machines happen to have matching assembly instructions for\n//    64x64-bit multiplications and 128-bit shifts.\n//\n// 2. Second best case: the compiler exposes intrinsics for the x64 assembly\n//    instructions mentioned in 1.\n//\n// 3. We only have 64x64 bit instructions that return the lower 64 bits of\n//    the result, i.e., we have to use plain C.\n//    Our inputs are less than the full width, so we have three options:\n//    a. Ignore this fact and just implement the intrinsics manually.\n//    b. Split both into 31-bit pieces, which guarantees no internal overflow,\n//       but requires extra work upfront (unless we change the lookup table).\n//    c. Split only the first factor into 31-bit pieces, which also guarantees\n//       no internal overflow, but requires extra work since the intermediate\n//       results are not perfectly aligned.\n#if defined(BOOST_JSON_RYU_HAS_UINT128)\n\n// Best case: use 128-bit type.\ninline\nstd::uint64_t\n    mulShift(\n    const std::uint64_t m,\n    const std::uint64_t* const mul,\n    const std::int32_t j) noexcept\n{\n    const uint128_t b0 = ((uint128_t) m) * mul[0];\n    const uint128_t b2 = ((uint128_t) m) * mul[1];\n    return (std::uint64_t) (((b0 >> 64) + b2) >> (j - 64));\n}\n\ninline\nuint64_t\nmulShiftAll(\n    const std::uint64_t m,\n    const std::uint64_t* const mul,\n    std::int32_t const j,\n    std::uint64_t* const vp,\n    std::uint64_t* const vm,\n    const std::uint32_t mmShift) noexcept\n{\n//  m <<= 2;\n//  uint128_t b0 = ((uint128_t) m) * mul[0]; // 0\n//  uint128_t b2 = ((uint128_t) m) * mul[1]; // 64\n//\n//  uint128_t hi = (b0 >> 64) + b2;\n//  uint128_t lo = b0 & 0xffffffffffffffffull;\n//  uint128_t factor = (((uint128_t) mul[1]) << 64) + mul[0];\n//  uint128_t vpLo = lo + (factor << 1);\n//  *vp = (std::uint64_t) ((hi + (vpLo >> 64)) >> (j - 64));\n//  uint128_t vmLo = lo - (factor << mmShift);\n//  *vm = (std::uint64_t) ((hi + (vmLo >> 64) - (((uint128_t) 1ull) << 64)) >> (j - 64));\n//  return (std::uint64_t) (hi >> (j - 64));\n    *vp = mulShift(4 * m + 2, mul, j);\n    *vm = mulShift(4 * m - 1 - mmShift, mul, j);\n    return mulShift(4 * m, mul, j);\n}\n\n#elif defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)\n\ninline\nstd::uint64_t\nmulShift(\n    const std::uint64_t m,\n    const std::uint64_t* const mul,\n    const std::int32_t j) noexcept\n{\n    // m is maximum 55 bits\n    std::uint64_t high1;                                   // 128\n    std::uint64_t const low1 = umul128(m, mul[1], &high1); // 64\n    std::uint64_t high0;                                   // 64\n    umul128(m, mul[0], &high0);                            // 0\n    std::uint64_t const sum = high0 + low1;\n    if (sum < high0)\n        ++high1; // overflow into high1\n    return shiftright128(sum, high1, j - 64);\n}\n\ninline\nstd::uint64_t\nmulShiftAll(\n    const std::uint64_t m,\n    const std::uint64_t* const mul,\n    const std::int32_t j,\n    std::uint64_t* const vp,\n    std::uint64_t* const vm,\n    const std::uint32_t mmShift) noexcept\n{\n    *vp = mulShift(4 * m + 2, mul, j);\n    *vm = mulShift(4 * m - 1 - mmShift, mul, j);\n    return mulShift(4 * m, mul, j);\n}\n\n#else // !defined(BOOST_JSON_RYU_HAS_UINT128) && !defined(BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS)\n\ninline\nstd::uint64_t\nmulShiftAll(\n    std::uint64_t m,\n    const std::uint64_t* const mul,\n    const std::int32_t j,\n    std::uint64_t* const vp,\n    std::uint64_t* const vm,\n    const std::uint32_t mmShift)\n{\n    m <<= 1;\n    // m is maximum 55 bits\n    std::uint64_t tmp;\n    std::uint64_t const lo = umul128(m, mul[0], &tmp);\n    std::uint64_t hi;\n    std::uint64_t const mid = tmp + umul128(m, mul[1], &hi);\n    hi += mid < tmp; // overflow into hi\n\n    const std::uint64_t lo2 = lo + mul[0];\n    const std::uint64_t mid2 = mid + mul[1] + (lo2 < lo);\n    const std::uint64_t hi2 = hi + (mid2 < mid);\n    *vp = shiftright128(mid2, hi2, (std::uint32_t)(j - 64 - 1));\n\n    if (mmShift == 1)\n    {\n        const std::uint64_t lo3 = lo - mul[0];\n        const std::uint64_t mid3 = mid - mul[1] - (lo3 > lo);\n        const std::uint64_t hi3 = hi - (mid3 > mid);\n        *vm = shiftright128(mid3, hi3, (std::uint32_t)(j - 64 - 1));\n    }\n    else\n    {\n        const std::uint64_t lo3 = lo + lo;\n        const std::uint64_t mid3 = mid + mid + (lo3 < lo);\n        const std::uint64_t hi3 = hi + hi + (mid3 < mid);\n        const std::uint64_t lo4 = lo3 - mul[0];\n        const std::uint64_t mid4 = mid3 - mul[1] - (lo4 > lo3);\n        const std::uint64_t hi4 = hi3 - (mid4 > mid3);\n        *vm = shiftright128(mid4, hi4, (std::uint32_t)(j - 64));\n    }\n\n    return shiftright128(mid, hi, (std::uint32_t)(j - 64 - 1));\n}\n\n#endif // BOOST_JSON_RYU_HAS_64_BIT_INTRINSICS\n\ninline\nstd::uint32_t\ndecimalLength17(\n    const std::uint64_t v)\n{\n    // This is slightly faster than a loop.\n    // The average output length is 16.38 digits, so we check high-to-low.\n    // Function precondition: v is not an 18, 19, or 20-digit number.\n    // (17 digits are sufficient for round-tripping.)\n    BOOST_ASSERT(v < 100000000000000000L);\n    if (v >= 10000000000000000L) { return 17; }\n    if (v >= 1000000000000000L) { return 16; }\n    if (v >= 100000000000000L) { return 15; }\n    if (v >= 10000000000000L) { return 14; }\n    if (v >= 1000000000000L) { return 13; }\n    if (v >= 100000000000L) { return 12; }\n    if (v >= 10000000000L) { return 11; }\n    if (v >= 1000000000L) { return 10; }\n    if (v >= 100000000L) { return 9; }\n    if (v >= 10000000L) { return 8; }\n    if (v >= 1000000L) { return 7; }\n    if (v >= 100000L) { return 6; }\n    if (v >= 10000L) { return 5; }\n    if (v >= 1000L) { return 4; }\n    if (v >= 100L) { return 3; }\n    if (v >= 10L) { return 2; }\n    return 1;\n}\n\n// A floating decimal representing m * 10^e.\nstruct floating_decimal_64\n{\n    std::uint64_t mantissa;\n    // Decimal exponent's range is -324 to 308\n    // inclusive, and can fit in a short if needed.\n    std::int32_t exponent;\n};\n\ninline\nfloating_decimal_64\nd2d(\n    const std::uint64_t ieeeMantissa,\n    const std::uint32_t ieeeExponent)\n{\n    std::int32_t e2;\n    std::uint64_t m2;\n    if (ieeeExponent == 0)\n    {\n        // We subtract 2 so that the bounds computation has 2 additional bits.\n        e2 = 1 - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;\n        m2 = ieeeMantissa;\n    }\n    else\n    {\n        e2 = (std::int32_t)ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2;\n        m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;\n    }\n    const bool even = (m2 & 1) == 0;\n    const bool acceptBounds = even;\n\n#ifdef RYU_DEBUG\n    printf(\"-> %\" PRIu64 \" * 2^%d\\n\", m2, e2 + 2);\n#endif\n\n    // Step 2: Determine the interval of valid decimal representations.\n    const std::uint64_t mv = 4 * m2;\n    // Implicit bool -> int conversion. True is 1, false is 0.\n    const std::uint32_t mmShift = ieeeMantissa != 0 || ieeeExponent <= 1;\n    // We would compute mp and mm like this:\n    // uint64_t mp = 4 * m2 + 2;\n    // uint64_t mm = mv - 1 - mmShift;\n\n    // Step 3: Convert to a decimal power base using 128-bit arithmetic.\n    std::uint64_t vr, vp, vm;\n    std::int32_t e10;\n    bool vmIsTrailingZeros = false;\n    bool vrIsTrailingZeros = false;\n    if (e2 >= 0) {\n        // I tried special-casing q == 0, but there was no effect on performance.\n        // This expression is slightly faster than max(0, log10Pow2(e2) - 1).\n        const std::uint32_t q = log10Pow2(e2) - (e2 > 3);\n        e10 = (std::int32_t)q;\n        const std::int32_t k = DOUBLE_POW5_INV_BITCOUNT + pow5bits((int32_t)q) - 1;\n        const std::int32_t i = -e2 + (std::int32_t)q + k;\n#if defined(BOOST_JSON_RYU_OPTIMIZE_SIZE)\n        uint64_t pow5[2];\n        double_computeInvPow5(q, pow5);\n        vr = mulShiftAll(m2, pow5, i, &vp, &vm, mmShift);\n#else\n        vr = mulShiftAll(m2, DOUBLE_POW5_INV_SPLIT()[q], i, &vp, &vm, mmShift);\n#endif\n#ifdef RYU_DEBUG\n        printf(\"%\" PRIu64 \" * 2^%d / 10^%u\\n\", mv, e2, q);\n        printf(\"V+=%\" PRIu64 \"\\nV =%\" PRIu64 \"\\nV-=%\" PRIu64 \"\\n\", vp, vr, vm);\n#endif\n        if (q <= 21)\n        {\n            // This should use q <= 22, but I think 21 is also safe. Smaller values\n            // may still be safe, but it's more difficult to reason about them.\n            // Only one of mp, mv, and mm can be a multiple of 5, if any.\n            const std::uint32_t mvMod5 = ((std::uint32_t)mv) - 5 * ((std::uint32_t)div5(mv));\n            if (mvMod5 == 0)\n            {\n                vrIsTrailingZeros = multipleOfPowerOf5(mv, q);\n            }\n            else if (acceptBounds)\n            {\n                // Same as min(e2 + (~mm & 1), pow5Factor(mm)) >= q\n                // <=> e2 + (~mm & 1) >= q && pow5Factor(mm) >= q\n                // <=> true && pow5Factor(mm) >= q, since e2 >= q.\n                vmIsTrailingZeros = multipleOfPowerOf5(mv - 1 - mmShift, q);\n            }\n            else\n            {\n                // Same as min(e2 + 1, pow5Factor(mp)) >= q.\n                vp -= multipleOfPowerOf5(mv + 2, q);\n            }\n        }\n    }\n    else\n    {\n        // This expression is slightly faster than max(0, log10Pow5(-e2) - 1).\n        const std::uint32_t q = log10Pow5(-e2) - (-e2 > 1);\n        e10 = (std::int32_t)q + e2;\n        const std::int32_t i = -e2 - (std::int32_t)q;\n        const std::int32_t k = pow5bits(i) - DOUBLE_POW5_BITCOUNT;\n        const std::int32_t j = (std::int32_t)q - k;\n#if defined(BOOST_JSON_RYU_OPTIMIZE_SIZE)\n        std::uint64_t pow5[2];\n        double_computePow5(i, pow5);\n        vr = mulShiftAll(m2, pow5, j, &vp, &vm, mmShift);\n#else\n        vr = mulShiftAll(m2, DOUBLE_POW5_SPLIT()[i], j, &vp, &vm, mmShift);\n#endif\n#ifdef RYU_DEBUG\n        printf(\"%\" PRIu64 \" * 5^%d / 10^%u\\n\", mv, -e2, q);\n        printf(\"%u %d %d %d\\n\", q, i, k, j);\n        printf(\"V+=%\" PRIu64 \"\\nV =%\" PRIu64 \"\\nV-=%\" PRIu64 \"\\n\", vp, vr, vm);\n#endif\n        if (q <= 1)\n        {\n            // {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at least q trailing 0 bits.\n            // mv = 4 * m2, so it always has at least two trailing 0 bits.\n            vrIsTrailingZeros = true;\n            if (acceptBounds)\n            {\n                // mm = mv - 1 - mmShift, so it has 1 trailing 0 bit iff mmShift == 1.\n                vmIsTrailingZeros = mmShift == 1;\n            }\n            else\n            {\n                // mp = mv + 2, so it always has at least one trailing 0 bit.\n                --vp;\n            }\n        }\n        else if (q < 63)\n        {\n            // TODO(ulfjack): Use a tighter bound here.\n            // We want to know if the full product has at least q trailing zeros.\n            // We need to compute min(p2(mv), p5(mv) - e2) >= q\n            // <=> p2(mv) >= q && p5(mv) - e2 >= q\n            // <=> p2(mv) >= q (because -e2 >= q)\n            vrIsTrailingZeros = multipleOfPowerOf2(mv, q);\n#ifdef RYU_DEBUG\n            printf(\"vr is trailing zeros=%s\\n\", vrIsTrailingZeros ? \"true\" : \"false\");\n#endif\n        }\n    }\n#ifdef RYU_DEBUG\n    printf(\"e10=%d\\n\", e10);\n    printf(\"V+=%\" PRIu64 \"\\nV =%\" PRIu64 \"\\nV-=%\" PRIu64 \"\\n\", vp, vr, vm);\n    printf(\"vm is trailing zeros=%s\\n\", vmIsTrailingZeros ? \"true\" : \"false\");\n    printf(\"vr is trailing zeros=%s\\n\", vrIsTrailingZeros ? \"true\" : \"false\");\n#endif\n\n    // Step 4: Find the shortest decimal representation in the interval of valid representations.\n    std::int32_t removed = 0;\n    std::uint8_t lastRemovedDigit = 0;\n    std::uint64_t output;\n    // On average, we remove ~2 digits.\n    if (vmIsTrailingZeros || vrIsTrailingZeros)\n    {\n        // General case, which happens rarely (~0.7%).\n        for (;;)\n        {\n            const std::uint64_t vpDiv10 = div10(vp);\n            const std::uint64_t vmDiv10 = div10(vm);\n            if (vpDiv10 <= vmDiv10)\n                break;\n            const std::uint32_t vmMod10 = ((std::uint32_t)vm) - 10 * ((std::uint32_t)vmDiv10);\n            const std::uint64_t vrDiv10 = div10(vr);\n            const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);\n            vmIsTrailingZeros &= vmMod10 == 0;\n            vrIsTrailingZeros &= lastRemovedDigit == 0;\n            lastRemovedDigit = (uint8_t)vrMod10;\n            vr = vrDiv10;\n            vp = vpDiv10;\n            vm = vmDiv10;\n            ++removed;\n        }\n#ifdef RYU_DEBUG\n        printf(\"V+=%\" PRIu64 \"\\nV =%\" PRIu64 \"\\nV-=%\" PRIu64 \"\\n\", vp, vr, vm);\n        printf(\"d-10=%s\\n\", vmIsTrailingZeros ? \"true\" : \"false\");\n#endif\n        if (vmIsTrailingZeros)\n        {\n            for (;;)\n            {\n                const std::uint64_t vmDiv10 = div10(vm);\n                const std::uint32_t vmMod10 = ((std::uint32_t)vm) - 10 * ((std::uint32_t)vmDiv10);\n                if (vmMod10 != 0)\n                    break;\n                const std::uint64_t vpDiv10 = div10(vp);\n                const std::uint64_t vrDiv10 = div10(vr);\n                const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);\n                vrIsTrailingZeros &= lastRemovedDigit == 0;\n                lastRemovedDigit = (uint8_t)vrMod10;\n                vr = vrDiv10;\n                vp = vpDiv10;\n                vm = vmDiv10;\n                ++removed;\n            }\n        }\n#ifdef RYU_DEBUG\n        printf(\"%\" PRIu64 \" %d\\n\", vr, lastRemovedDigit);\n        printf(\"vr is trailing zeros=%s\\n\", vrIsTrailingZeros ? \"true\" : \"false\");\n#endif\n        if (vrIsTrailingZeros && lastRemovedDigit == 5 && vr % 2 == 0)\n        {\n            // Round even if the exact number is .....50..0.\n            lastRemovedDigit = 4;\n        }\n        // We need to take vr + 1 if vr is outside bounds or we need to round up.\n        output = vr + ((vr == vm && (!acceptBounds || !vmIsTrailingZeros)) || lastRemovedDigit >= 5);\n    }\n    else\n    {\n        // Specialized for the common case (~99.3%). Percentages below are relative to this.\n        bool roundUp = false;\n        const std::uint64_t vpDiv100 = div100(vp);\n        const std::uint64_t vmDiv100 = div100(vm);\n        if (vpDiv100 > vmDiv100)\n        {\n            // Optimization: remove two digits at a time (~86.2%).\n            const std::uint64_t vrDiv100 = div100(vr);\n            const std::uint32_t vrMod100 = ((std::uint32_t)vr) - 100 * ((std::uint32_t)vrDiv100);\n            roundUp = vrMod100 >= 50;\n            vr = vrDiv100;\n            vp = vpDiv100;\n            vm = vmDiv100;\n            removed += 2;\n        }\n        // Loop iterations below (approximately), without optimization above:\n        // 0: 0.03%, 1: 13.8%, 2: 70.6%, 3: 14.0%, 4: 1.40%, 5: 0.14%, 6+: 0.02%\n        // Loop iterations below (approximately), with optimization above:\n        // 0: 70.6%, 1: 27.8%, 2: 1.40%, 3: 0.14%, 4+: 0.02%\n        for (;;)\n        {\n            const std::uint64_t vpDiv10 = div10(vp);\n            const std::uint64_t vmDiv10 = div10(vm);\n            if (vpDiv10 <= vmDiv10)\n                break;\n            const std::uint64_t vrDiv10 = div10(vr);\n            const std::uint32_t vrMod10 = ((std::uint32_t)vr) - 10 * ((std::uint32_t)vrDiv10);\n            roundUp = vrMod10 >= 5;\n            vr = vrDiv10;\n            vp = vpDiv10;\n            vm = vmDiv10;\n            ++removed;\n        }\n#ifdef RYU_DEBUG\n        printf(\"%\" PRIu64 \" roundUp=%s\\n\", vr, roundUp ? \"true\" : \"false\");\n        printf(\"vr is trailing zeros=%s\\n\", vrIsTrailingZeros ? \"true\" : \"false\");\n#endif\n        // We need to take vr + 1 if vr is outside bounds or we need to round up.\n        output = vr + (vr == vm || roundUp);\n    }\n    const std::int32_t exp = e10 + removed;\n\n#ifdef RYU_DEBUG\n    printf(\"V+=%\" PRIu64 \"\\nV =%\" PRIu64 \"\\nV-=%\" PRIu64 \"\\n\", vp, vr, vm);\n    printf(\"O=%\" PRIu64 \"\\n\", output);\n    printf(\"EXP=%d\\n\", exp);\n#endif\n\n    floating_decimal_64 fd;\n    fd.exponent = exp;\n    fd.mantissa = output;\n    return fd;\n}\n\ninline\nint\nto_chars(\n    const floating_decimal_64 v,\n    const bool sign,\n    char* const result)\n{\n    // Step 5: Print the decimal representation.\n    int index = 0;\n    if (sign)\n        result[index++] = '-';\n\n    std::uint64_t output = v.mantissa;\n    std::uint32_t const olength = decimalLength17(output);\n\n#ifdef RYU_DEBUG\n    printf(\"DIGITS=%\" PRIu64 \"\\n\", v.mantissa);\n    printf(\"OLEN=%u\\n\", olength);\n    printf(\"EXP=%u\\n\", v.exponent + olength);\n#endif\n\n    // Print the decimal digits.\n    // The following code is equivalent to:\n    // for (uint32_t i = 0; i < olength - 1; ++i) {\n    //   const uint32_t c = output % 10; output /= 10;\n    //   result[index + olength - i] = (char) ('0' + c);\n    // }\n    // result[index] = '0' + output % 10;\n\n    std::uint32_t i = 0;\n    // We prefer 32-bit operations, even on 64-bit platforms.\n    // We have at most 17 digits, and uint32_t can store 9 digits.\n    // If output doesn't fit into uint32_t, we cut off 8 digits,\n    // so the rest will fit into uint32_t.\n    if ((output >> 32) != 0)\n    {\n        // Expensive 64-bit division.\n        std::uint64_t const q = div1e8(output);\n        std::uint32_t output2 = ((std::uint32_t)output) - 100000000 * ((std::uint32_t)q);\n        output = q;\n\n        const std::uint32_t c = output2 % 10000;\n        output2 /= 10000;\n        const std::uint32_t d = output2 % 10000;\n        const std::uint32_t c0 = (c % 100) << 1;\n        const std::uint32_t c1 = (c / 100) << 1;\n        const std::uint32_t d0 = (d % 100) << 1;\n        const std::uint32_t d1 = (d / 100) << 1;\n        std::memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c0, 2);\n        std::memcpy(result + index + olength - i - 3, DIGIT_TABLE() + c1, 2);\n        std::memcpy(result + index + olength - i - 5, DIGIT_TABLE() + d0, 2);\n        std::memcpy(result + index + olength - i - 7, DIGIT_TABLE() + d1, 2);\n        i += 8;\n    }\n    uint32_t output2 = (std::uint32_t)output;\n    while (output2 >= 10000)\n    {\n#ifdef __clang__ // https://bugs.llvm.org/show_bug.cgi?id=38217\n        const uint32_t c = output2 - 10000 * (output2 / 10000);\n#else\n        const uint32_t c = output2 % 10000;\n#endif\n        output2 /= 10000;\n        const uint32_t c0 = (c % 100) << 1;\n        const uint32_t c1 = (c / 100) << 1;\n        memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c0, 2);\n        memcpy(result + index + olength - i - 3, DIGIT_TABLE() + c1, 2);\n        i += 4;\n    }\n    if (output2 >= 100) {\n        const uint32_t c = (output2 % 100) << 1;\n        output2 /= 100;\n        memcpy(result + index + olength - i - 1, DIGIT_TABLE() + c, 2);\n        i += 2;\n    }\n    if (output2 >= 10) {\n        const uint32_t c = output2 << 1;\n        // We can't use memcpy here: the decimal dot goes between these two digits.\n        result[index + olength - i] = DIGIT_TABLE()[c + 1];\n        result[index] = DIGIT_TABLE()[c];\n    }\n    else {\n        result[index] = (char)('0' + output2);\n    }\n\n    // Print decimal point if needed.\n    if (olength > 1) {\n        result[index + 1] = '.';\n        index += olength + 1;\n    }\n    else {\n        ++index;\n    }\n\n    // Print the exponent.\n    result[index++] = 'E';\n    int32_t exp = v.exponent + (int32_t)olength - 1;\n    if (exp < 0) {\n        result[index++] = '-';\n        exp = -exp;\n    }\n\n    if (exp >= 100) {\n        const int32_t c = exp % 10;\n        memcpy(result + index, DIGIT_TABLE() + 2 * (exp / 10), 2);\n        result[index + 2] = (char)('0' + c);\n        index += 3;\n    }\n    else if (exp >= 10) {\n        memcpy(result + index, DIGIT_TABLE() + 2 * exp, 2);\n        index += 2;\n    }\n    else {\n        result[index++] = (char)('0' + exp);\n    }\n\n    return index;\n}\n\nstatic inline bool d2d_small_int(const uint64_t ieeeMantissa, const uint32_t ieeeExponent,\n  floating_decimal_64* const v) {\n  const uint64_t m2 = (1ull << DOUBLE_MANTISSA_BITS) | ieeeMantissa;\n  const int32_t e2 = (int32_t) ieeeExponent - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS;\n\n  if (e2 > 0) {\n    // f = m2 * 2^e2 >= 2^53 is an integer.\n    // Ignore this case for now.\n    return false;\n  }\n\n  if (e2 < -52) {\n    // f < 1.\n    return false;\n  }\n\n  // Since 2^52 <= m2 < 2^53 and 0 <= -e2 <= 52: 1 <= f = m2 / 2^-e2 < 2^53.\n  // Test if the lower -e2 bits of the significand are 0, i.e. whether the fraction is 0.\n  const uint64_t mask = (1ull << -e2) - 1;\n  const uint64_t fraction = m2 & mask;\n  if (fraction != 0) {\n    return false;\n  }\n\n  // f is an integer in the range [1, 2^53).\n  // Note: mantissa might contain trailing (decimal) 0's.\n  // Note: since 2^53 < 10^16, there is no need to adjust decimalLength17().\n  v->mantissa = m2 >> -e2;\n  v->exponent = 0;\n  return true;\n}\n\n} // detail\n\nint\nd2s_buffered_n(\n    double f,\n    char* result) noexcept\n{\n    using namespace detail;\n    // Step 1: Decode the floating-point number, and unify normalized and subnormal cases.\n    std::uint64_t const bits = double_to_bits(f);\n\n#ifdef RYU_DEBUG\n    printf(\"IN=\");\n    for (std::int32_t bit = 63; bit >= 0; --bit) {\n        printf(\"%d\", (int)((bits >> bit) & 1));\n    }\n    printf(\"\\n\");\n#endif\n\n    // Decode bits into sign, mantissa, and exponent.\n    const bool ieeeSign = ((bits >> (DOUBLE_MANTISSA_BITS + DOUBLE_EXPONENT_BITS)) & 1) != 0;\n    const std::uint64_t ieeeMantissa = bits & ((1ull << DOUBLE_MANTISSA_BITS) - 1);\n    const std::uint32_t ieeeExponent = (std::uint32_t)((bits >> DOUBLE_MANTISSA_BITS) & ((1u << DOUBLE_EXPONENT_BITS) - 1));\n    // Case distinction; exit early for the easy cases.\n    if (ieeeExponent == ((1u << DOUBLE_EXPONENT_BITS) - 1u) || (ieeeExponent == 0 && ieeeMantissa == 0)) {\n        return copy_special_str(result, ieeeSign, ieeeExponent != 0, ieeeMantissa != 0);\n    }\n\n    floating_decimal_64 v;\n    const bool isSmallInt = d2d_small_int(ieeeMantissa, ieeeExponent, &v);\n    if (isSmallInt) {\n        // For small integers in the range [1, 2^53), v.mantissa might contain trailing (decimal) zeros.\n        // For scientific notation we need to move these zeros into the exponent.\n        // (This is not needed for fixed-point notation, so it might be beneficial to trim\n        // trailing zeros in to_chars only if needed - once fixed-point notation output is implemented.)\n        for (;;) {\n            std::uint64_t const q = div10(v.mantissa);\n            std::uint32_t const r = ((std::uint32_t) v.mantissa) - 10 * ((std::uint32_t) q);\n            if (r != 0)\n                break;\n            v.mantissa = q;\n            ++v.exponent;\n        }\n    }\n    else {\n        v = d2d(ieeeMantissa, ieeeExponent);\n    }\n\n    return to_chars(v, ieeeSign, result);\n}\n\nvoid\nd2s_buffered(\n    double f,\n    char* result) noexcept\n{\n    const int index = d2s_buffered_n(f, result);\n\n    // Terminate the string.\n    result[index] = '\\0';\n}\n\nchar*\nd2s(double f) noexcept\n{\n    static thread_local char result[25];\n    d2s_buffered(f, result);\n    return result;\n}\n\n} // ryu\n\n} // detail\n} // json\n} // boost\n\n#endif\n", "meta": {"hexsha": "4089fa012b09c2ee5a7427d08ebf6830c9b6247a", "size": 26052, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "include/boost/json/detail/ryu/impl/d2s.ipp", "max_stars_repo_name": "rtobar/json", "max_stars_repo_head_hexsha": "400136a292fda23452c5d914cda7fef70939a2b5", "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/json/detail/ryu/impl/d2s.ipp", "max_issues_repo_name": "rtobar/json", "max_issues_repo_head_hexsha": "400136a292fda23452c5d914cda7fef70939a2b5", "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/json/detail/ryu/impl/d2s.ipp", "max_forks_repo_name": "rtobar/json", "max_forks_repo_head_hexsha": "400136a292fda23452c5d914cda7fef70939a2b5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T20:17:06.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-20T20:17:06.000Z", "avg_line_length": 34.9222520107, "max_line_length": 124, "alphanum_fraction": 0.5816827883, "num_tokens": 8243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.031618770348393645, "lm_q1q2_score": 0.010251925032132814}}
{"text": "// Copyright (c) 2012 Hasso-Plattner-Institut fuer Softwaresystemtechnik GmbH. All rights reserved.\n#include \"base.h\"\n#include \"layout_utils.h\"\n#include \"matrix.h\"\n\n#include <algorithm>\n#include <float.h>\n#include <functional>\n#include <limits.h>\n#include <math.h>\n#include <map>\n#include <sstream>\n#include <unordered_map>\n#include <list>\n\n\n#include <boost/unordered_set.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/combination.hpp>\n#include <boost/assign.hpp>\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n\n\n#include <metis.h>\n\nusing namespace boost::assign;\n\n\n\nnamespace std {\n\ntemplate <>\nstruct hash<hyrise::layouter::subset_t> {\n public:\n  size_t operator()(const std::vector<unsigned>& ref) const {\n    size_t test = 0;\n    std::hash<unsigned int> h;\n    for (auto t : ref)\n      test ^= (h(t) << 1);\n    return test;\n  }\n};\n\n}  // namespace std\n\nnamespace hyrise {\nnamespace layouter {\n\nQuery::Query(LayouterConfiguration::access_type_t type, std::vector<unsigned> qA, double parameter, int weight)\n    : type(type), queryAttributes(qA), parameter(parameter), weight(weight) {\n  std::sort(queryAttributes.begin(), queryAttributes.end());\n}\n\nunsigned Query::getContainerWidth() {\n  unsigned width = 0;\n  BOOST_FOREACH(unsigned a, _container) { width += _schema.attributes[a]; }\n  return width;\n}\n\nvoid Query::getAttUnion() {\n\n  // Prepare\n  _attributeRefSet.clear();\n  _attributeRefSet.insert(queryAttributes.begin(), queryAttributes.end());\n  _attUnion.clear();\n\n\n  // Search\n  BOOST_FOREACH(unsigned l, _container)\n  if (_attributeRefSet.count(l) > 0)\n    _attUnion.push_back(l);\n\n  std::sort(_attUnion.begin(), _attUnion.end());\n\n  if (_costModel.compare(COL_COST) == 0) {\n    _attUnion.push_back(0);\n  }\n}\n\ndouble Query::containerCost(std::vector<unsigned> container, Schema s, std::string costModel) {\n  _container = container;\n  _schema = s;\n  _costModel = costModel;\n\n  _containerWidth = getContainerWidth();\n\n  // Check if there are any attributes, that match agains the given containers\n  getAttUnion();\n\n  double cost = 0;\n\n  if (_attUnion.size() == 0) {\n    return 0;\n  }\n\n  if (_costModel.compare(HYRISE_COST) == 0) {\n    cost = hyriseCost();\n  } else {\n    cost = INT_MIN;\n  }\n\n  return weight * cost;\n}\n\ndouble Query::hyriseCost() {\n  double misses = 0;\n\n  if (type == LayouterConfiguration::access_type_fullprojection) {\n    misses = hyriseProjection();\n  } else if (type == LayouterConfiguration::access_type_outoforder) {\n    misses = hyriseOOO();\n  } else {\n    misses = DBL_MIN;\n  }\n\n  return misses;\n}\n\ndouble Query::hyriseProjection() {\n  if (_containerWidth <= CACHE_LINE_SIZE) {\n    return ceil(_containerWidth * _schema.nbTuples / (CACHE_LINE_SIZE * 1.0));\n  }\n\n  if (_attUnion.size() == 1) {\n\n    unsigned po = 0;\n\n    for (unsigned i = 0; i < _container.size(); ++i) {\n      if (_container[i] == _attUnion[0]) {\n        break;\n      }\n\n      po += _schema.attributes[_container[i]];\n    }\n\n    unsigned pw = _schema.attributes[_attUnion[0]];\n    return hyrisePartialProjection(po, pw);\n  } else {\n    return hyriseEquivalentProjection(false);\n  }\n}\n\ndouble Query::hyrisePartialProjection(unsigned po, unsigned pw) {\n  if (_containerWidth - pw < CACHE_LINE_SIZE) {\n    return ceil(_containerWidth * _schema.nbTuples / (CACHE_LINE_SIZE * 1.0));\n  }\n\n  double misses = 0.0;\n  int nbPossibleOffsets = LCM(CACHE_LINE_SIZE, _containerWidth) / _containerWidth;\n\n  // the cases creating an additional miss are all the cases for which the offset\n  // is greater than the transition point\n  for (int r = 0; r < nbPossibleOffsets; r++) {\n    int lineoffset = ((r * _containerWidth) + po) % CACHE_LINE_SIZE;\n    misses += ceil((double)(lineoffset + pw) / CACHE_LINE_SIZE);\n  }\n\n  double averageMisses = (double)misses / nbPossibleOffsets;\n  misses = ((double)_schema.nbTuples * averageMisses);\n  return misses;\n}\n\ndouble Query::hyriseEquivalentProjection(bool isSelective) {\n\n  // compute the offset for each attribute\n  int offset = 0;\n  std::vector<int> attsOffset(_container.size());\n\n  for (unsigned i = 0; i < _container.size(); i++) {\n    attsOffset[i] = offset;\n    offset += _schema.attributes[_container[i]];\n  }\n\n  int containerWidth = offset;\n\n  // start with the first attribute and try to make equivalent projection\n  std::vector<int> eqProjectionOffset;\n  std::vector<int> eqProjectionEnd;\n\n  int currentProjection = -1;\n\n  for (unsigned i = 0; i < _container.size(); ++i) {\n    // i is the position of the att in the container\n    // att is the attribute number corresponding to i\n    int att = _container[i];\n\n    // if the attribute is projected, add it to projection\n    if (std::find(queryAttributes.begin(), queryAttributes.end(), att) == queryAttributes.end())\n        // att is not projected\n    {\n      continue;\n    } else {\n      if (currentProjection == -1) {\n        // first projection, add it\n        currentProjection = 0;\n        eqProjectionOffset.push_back(attsOffset[i]);\n        eqProjectionEnd.push_back(attsOffset[i] + _schema.attributes[att]);\n        continue;\n      }\n\n      // new projected attribute; check if the gap is big\n      int gap = attsOffset[i] - eqProjectionEnd[currentProjection];\n\n      if (gap < CACHE_LINE_SIZE) {\n        // same projection\n        eqProjectionEnd[currentProjection] = attsOffset[i] + _schema.attributes[att];\n      } else {\n        // new projection\n        currentProjection++;\n        eqProjectionOffset.push_back(attsOffset[i]);\n        eqProjectionEnd.push_back(attsOffset[i] + _schema.attributes[att]);\n      }\n    }\n  }\n\n  // compute the gap between the first and last projection\n  if (currentProjection > 0) {\n    int interRowGap = eqProjectionOffset[0] + containerWidth - eqProjectionEnd[currentProjection];\n\n    if (interRowGap < CACHE_LINE_SIZE) {\n      // merge last with first projection\n      eqProjectionOffset[0] = eqProjectionOffset[currentProjection];\n      eqProjectionEnd[0] = eqProjectionEnd[0] + containerWidth;\n\n      eqProjectionOffset.pop_back();\n      eqProjectionEnd.pop_back();\n    }\n  }\n\n  double misses = 0;\n\n  for (unsigned i = 0; i < eqProjectionOffset.size(); i++) {\n    int po = eqProjectionOffset[i];\n    int pw = eqProjectionEnd[i] - po;\n\n    if (!isSelective) {\n      misses += hyrisePartialProjection(po, pw);\n    } else {\n      misses += hyriseSingleOOO(po, pw);\n    }\n  }\n\n  return misses;\n}\n\ndouble Query::hyriseOOO() {\n\n  if (_attUnion.size() == 1) {\n    int po = 0;\n\n    for (unsigned i = 0; i < _container.size(); i++) {\n      if (_container[i] == _attUnion[0]) {\n        break;\n      }\n\n      po += _schema.attributes[_container[i]];\n    }\n\n    int pw = _schema.attributes[_attUnion[0]];\n    return hyriseSingleOOO(po, pw);\n  } else {\n    return hyriseEquivalentProjection(true);\n  }\n}\n\ndouble Query::hyriseSingleOOO(int po, int pw) {\n  double misses = 0;\n\n  // int cacheLineTransitionPoint = CACHE_LINE_SIZE - (pw % CACHE_LINE_SIZE) + 1;\n  int nbPossibleOffsets = LCM(CACHE_LINE_SIZE, _containerWidth) / _containerWidth;\n\n  for (int r = 0; r < nbPossibleOffsets; r++) {\n    int lineoffset = ((r * _containerWidth) + po) % CACHE_LINE_SIZE;\n    misses += ceil((double)(lineoffset + pw) / CACHE_LINE_SIZE);\n  }\n\n  double averageMisses = (double)misses / nbPossibleOffsets;\n  misses = ((double)_schema.nbTuples * averageMisses);\n\n  // try to divide in the traditional two cases\n  if (_containerWidth - pw < CACHE_LINE_SIZE) {\n    // compute the average number of rows in a cache line\n    double nbRowsInLine = ((double)(CACHE_LINE_SIZE)) / _containerWidth;\n\n    // compute the average number of lines that are touched for each projection\n    double rowsToSubstract = 1 + (nbRowsInLine - 1) * parameter;\n\n    misses = (averageMisses * ((double)_schema.nbTuples * parameter / rowsToSubstract));\n  } else {\n    // \"simple\" case, rows are independent w.r.t. misses\n    misses = (int)(averageMisses * ((double)_schema.nbTuples * parameter));\n  }\n\n  return misses;\n}\n\nLayout::Layout(internal_layout_t l) : _layout(l) {}\n\nLayout::Layout() : _layout() {}\n\nbool Layout::operator==(const Layout& l) const {\n  if (_layout.size() == 0) {\n    return false;\n  }\n\n  for (unsigned i = 0; i < l._layout.size(); ++i) {\n    std::vector<unsigned> left = _layout[i];\n    std::vector<unsigned> right = l._layout[i];\n\n    if (left.size() != right.size()) {\n      return false;\n    }\n\n    for (unsigned j = 0; j < left.size(); ++j) {\n      if (left[j] != right[j]) {\n        return false;\n      }\n    }\n  }\n\n  return true;\n}\n\nvoid Layout::add(std::vector<unsigned> subset) {\n  _layout.push_back(subset);\n\n  // Set based caching of layouts\n  std::set<unsigned> tmp(subset.begin(), subset.end());\n  _cached_layout.push_back(tmp);\n}\n\nvoid Layout::removeLast() { _layout.pop_back(); }\n\nResult::Result(Layout& l, std::vector<double> c) {\n  layout = Layout(l);\n  cost = c;\n  totalCost = 0;\n\n  for (unsigned i = 0; i < cost.size(); ++i) {\n    totalCost += cost[i];\n  }\n}\n\nbool Result::operator==(const Result& r) const { return totalCost == r.totalCost; }\n\nbool Result::layoutEquals(const Result& r) const { return layout == r.layout; }\n\nvoid Result::print() const {\n  BOOST_FOREACH(subset_t s, layout.raw()) {\n    std::cout << \"|\";\n    BOOST_FOREACH(unsigned t, s) { std::cout << \" \" << t << \" \"; }\n    std::cout << \"|\";\n  }\n\n  std::cout << \" Cost: \" << totalCost << \" [\";\n  BOOST_FOREACH(double d, cost) { std::cout << \" \" << d; }\n  std::cout << \" ]\" << std::endl;\n}\n\nstd::string Result::output() const {\n  std::vector<std::string> names, types, groups;\n  std::stringstream output;\n  int counter = 0;\n  BOOST_FOREACH(subset_t s, layout.raw()) {\n    BOOST_FOREACH(unsigned t, s) {\n      // Add the name for each group\n      names.push_back(_names[t]);\n      types.push_back(\"INTEGER\");\n      groups.push_back(str(boost::format(\"%1%_R\") % counter));\n    }\n    counter++;\n  }\n  // Finalizing the output\n  output << boost::algorithm::join(names, \" | \") << std::endl;\n  output << boost::algorithm::join(types, \" | \") << std::endl;\n  output << boost::algorithm::join(groups, \" | \") << std::endl;\n  return output.str();\n}\n\n\nSchema::Schema(std::vector<unsigned> a, int nbA, std::vector<std::string> an)\n    : attnames(an), nbAttributes(a.size()), nbTuples(nbA), attributes(a) {}\n\nvoid Schema::add(const Query* q) { queries.push_back(new Query(*q)); }\n\nvoid Schema::removeLastQuery() { queries.pop_back(); }\n\ndouble Schema::costForSubset(subset_t t, std::string costModel) const {\n  size_t num_queries = queries.size();\n  double total = 0.0;\n\n  for (size_t q = 0; q < num_queries; ++q)\n    total += queries[q]->containerCost(t, *this, costModel);\n\n  return total;\n}\n\nSchema Schema::baseCopy() const {\n  Schema result(*this);\n  result.queries.clear();\n  return result;\n}\n\nBaseLayouter::BaseLayouter() : nbLayouts(0) {}\n\nvoid BaseLayouter::layout(Schema s, std::string cM) {\n  schema = s;\n  costModel = cM;\n\n  generateSubSets();\n\n\n  iterateThroughLayouts();\n  std::sort(results.begin(), results.end());\n}\n\n\nLayout::internal_layout_t BaseLayouter::eliminateInvalidSubsets(subset_t reference, Layout::internal_layout_t input) {\n  Layout::internal_layout_t result;\n  bool found;\n  std::set<unsigned> initial(reference.begin(), reference.end());\n\n  BOOST_FOREACH(subset_t right, input) {\n    found = false;\n    BOOST_FOREACH(unsigned i, right) {\n      if (initial.count(i) > 0) {\n        found = true;\n        break;\n      }\n    }\n    if (!found)\n      result += right;\n  }\n\n  return result;\n}\n\nvoid BaseLayouter::iterateLayoutSubsets(subset_t input, Layout::internal_layout_t subsets) {\n  subset_t front = input;\n  Layout::internal_layout_t rest = subsets;\n\n  // Eliminate all invalid combinations from rest\n  Layout::internal_layout_t eliminated = eliminateInvalidSubsets(front, rest);\n\n  std::vector<uint32_t> elimSizes;\n  for (subset_t t : eliminated)\n    elimSizes.push_back(t.size());\n\n  unsigned upperBound = eliminated.size() < schema.nbAttributes ? eliminated.size() : schema.nbAttributes;\n\n  // always check lower bound\n  // the lower bound defines how many partitions we need to actually make a valid layout\n  unsigned lowerBound = checkLowerBound(input, subsets);\n\n  // std::cout << \"---- E / U / L ----\" << std::endl;\n  print(input);\n  print(eliminated);\n  return;\n  // std::cout << eliminated.size() << std::endl;\n  // std::cout << schema.nbAttributes << std::endl;\n  // std::cout << upperBound << std::endl;\n  // std::cout << lowerBound << std::endl;\n  // std::cout << \"--------------------\" << std::endl;\n\n  for (unsigned i = lowerBound - 1; i <= upperBound; ++i) {\n\n    // Prepare intial setting, since we cannot swap vectors\n    subset_t combi;\n    for (unsigned j = 0; j < eliminated.size(); ++j)\n      combi += j;\n\n    // std::cout << \"Combinations \" << eliminated.size() << \" over \" << i << std::endl;\n    size_t combinations = 0;\n    size_t noAttr = 0;\n    do {\n      size_t nb = 0;\n      nb += input.size();\n\n      // Check\n      for (unsigned j = 0; j < i; ++j) {\n        nb += elimSizes[combi[j]];\n        if (nb > schema.nbAttributes) {\n          ++noAttr;\n          goto contLoop;\n        }\n      }\n\n      // Add front to layout and all other combinations here and check if they are valid\n      {\n        Layout l;\n        l.add(input);\n\n        for (unsigned j = 0; j < i; ++j) {\n          if (l.canAdd(eliminated[combi[j]])) {\n            l.add(eliminated[combi[j]]);\n          } else {\n            goto contLoop;\n          }\n        }\n\n        // std::cout << \"New layout?\" << std::endl;\n        if (nb == schema.nbAttributes) {\n          Result r(l, getCost(l));\n          nbLayouts++;\n          results.push_back(r);\n        }\n      }\n    contLoop:\n      ++combinations;\n    } while (boost::next_combination(combi.begin(), combi.begin() + i, combi.end()));\n\n    // std::cout << combinations << \" / \" << noAttr << std::endl;\n\n    // if all combinations had more attributes than we can add to the table we can break the loop\n    // here since there will be no case where adding a partition will have std::less attributes\n    if (combinations == noAttr) {\n      break;\n    }\n  }\n}\n\nsize_t BaseLayouter::checkLowerBound(subset_t input, Layout::internal_layout_t subsets) {\n  // sort subsets by size descending\n  Layout::internal_layout_t sorted(subsets);\n  sort(sorted.begin(), sorted.end(), sort_subset_by_size);\n\n  unsigned counted = input.size();\n  unsigned lowerBound = 1;\n  for (size_t i = 0; i < sorted.size(); ++i) {\n    counted += sorted[i].size();\n    if (counted <= schema.nbAttributes)\n      ++lowerBound;\n    else\n      break;\n  }\n\n  if (counted < schema.nbAttributes)\n    return std::numeric_limits<unsigned>::max();\n\n  return lowerBound;\n}\n\nstd::vector<std::vector<subset_t> > BaseLayouter::iterateThroughLayoutSubsetsFast(size_t n,\n                                                                                  std::vector<subset_t> list,\n                                                                                  size_t current_size,\n                                                                                  size_t dest_size,\n                                                                                  size_t max_attr,\n                                                                                  size_t curr_attr) {\n  //    std::cout << \"Recurse with \" << n << \" \" << current_size << \" \" << dest_size << \" \" << max_attr << \" \" <<\n  // curr_attr << std::endl;\n  typedef std::vector<std::vector<subset_t> > iterate_result_t;\n  // Recursion abortion defined here\n  if (n == 1 or list.size() == 1) {\n    iterate_result_t res;\n    for (auto x : list) {\n      if (x.size() + curr_attr == max_attr) {\n        std::vector<subset_t> tmp = {x};\n        res.push_back(tmp);\n      }\n    }\n    return res;\n  }\n\n  // No we handle the main part of the recursion\n  size_t index = 0;\n  iterate_result_t result;\n  while (index < list.size()) {\n\n    // FXIME\n    // if (list.size() - 1 < n - 1 or list.size() == index+1 or list.size() - index < dest_size - current_size)\n    //    return result;\n\n    // Check if it makes sense to proceed with recursion Potential\n    // improvement. Make sure, we only extract those subsets that are\n    // relevant.\n\n    // There is a second case when we can abort: If we know, that\n    // we have n-1 elements left and the minimal length is\n    // e.g. two that means we generate at lest (n-1)*two\n    // attributes, if this number is too large we will abort\n\n    subset_t left_list = list[index];\n    std::vector<subset_t> rest_list(list.begin() + index + 1, list.end());\n\n    /* We define another abort criterion here, if a single element\n    from our current pivot element is found inside another element\n    from the drill down list we can safeley remove these elements\n    from the list\n    */\n    std::vector<subset_t> new_rest;\n    for (auto x : rest_list) {\n      for (auto f : left_list)\n        for (auto r : x)\n          if (f == r)\n            goto bbb;\n\n      new_rest.push_back(x);\n\n    bbb:\n      continue;\n    }\n\n    rest_list = new_rest;\n    // rest_list.erase(std::remove_if(rest_list.begin(), rest_list.end(), [&left_list](subset_t& e){\n    //             for( const auto& f : left_list)\n    //                 if (std::find(e.begin(), e.end(), f) != left_list.end())\n    //                     return true;\n\n    //             return false;\n    //         }), rest_list.end());\n\n    iterate_result_t all;\n\n    if (rest_list.size() > 0 && curr_attr + rest_list[0].size() <= max_attr &&\n        (rest_list[0].size() * (n - 1) + curr_attr <= max_attr or list.size() < n)) {\n      all = iterateThroughLayoutSubsetsFast(\n          n - 1, rest_list, current_size + 1, dest_size, max_attr, curr_attr + list[index].size());\n    }\n\n    for (auto part : all) {\n      /*\n        Now we need a fast way to identify that we will not have\n        a single elemnt doubled.\n       */\n      std::vector<subset_t> tmp{list[index]};\n      tmp.insert(tmp.end(), part.begin(), part.end());\n      result.push_back(tmp);\n    }\n    ++index;\n  }\n  return result;\n}\n\nvoid BaseLayouter::iterateThroughLayouts() {\n  std::sort(subsets.begin(), subsets.end(), subset_t_lt);\n\n  if (subsets.size() == 1) {\n    Layout l;\n    l.add(subsets[0]);\n    Result r(l, getCost(l));\n    nbLayouts++;\n    results.push_back(r);\n    return;\n  }\n\n  //  if (subsets.size() > schema.nbAttributes)\n  if (true) {\n\n    // We have an issue here since we do not check what the minimum\n    // size of attribute groups is we need to have. If we have the\n    // case that only using 100 groups in our 100 attribute group\n    // large table we can succeed, we will check all other\n    // possibilities before, thus we need to increase the start point\n    // to a reasonable amount\n\n    // Since we know the subsets are orered in size, we can deduce the\n    // minium amount by the size of the biggest element\n    auto start_min = schema.nbAttributes / subsets.back().size();\n\n    for (size_t i = start_min; i <= schema.nbAttributes; ++i) {\n      auto intermediate_results = iterateThroughLayoutSubsetsFast(i, subsets, 0, i, schema.nbAttributes, 0);\n\n      for (auto x : intermediate_results) {\n        Layout l;\n        for (auto t : x)\n          l.add(t);\n        Result r(l, getCost(l));\n        nbLayouts++;\n        results.push_back(r);\n      }\n    }\n  } else {\n\n    // list<subset_t> down(subsets.begin(), subsets.end());\n\n    // Layout l;\n    //    iterateThroughLayoutSubsets2(l, down);\n\n    for (size_t s = 0; s < subsets.size(); ++s) {\n      iterateLayoutSubsets(subsets[s], Layout::internal_layout_t(subsets.begin() + 1 + s, subsets.end()));\n    }\n  }\n}\n\nvoid BaseLayouter::generateLayouts(Layout layout, size_t iter) {\n  // only continue if we are save\n  if (iter >= subsets.size()) {\n    if (layout.size() == schema.nbAttributes) {\n      Result r(layout, getCost(layout));\n      if (!(r.layout == results.back().layout)) {\n        nbLayouts++;\n        results.push_back(r);\n      }\n    }\n\n    return;\n  }\n\n  // get current subset\n  subset_t currentSubset = subsets[iter];\n  Layout original = layout;\n\n  if (tryToAddSubset(layout, currentSubset)) {\n    // Add to the layout and check\n    layout.add(currentSubset);\n    if (layout.size() == schema.nbAttributes) {\n      Result r(layout, getCost(layout));\n      nbLayouts++;\n      results.push_back(r);\n    }\n\n    size_t newIter = iter + 1;\n    generateLayouts(layout, newIter);\n  }\n\n  if (subsets[iter + 1].size() + original.size() <= schema.nbAttributes)\n    generateLayouts(original, iter + 1);\n}\n\nbool BaseLayouter::tryToAddSubset(const Layout& l, const subset_t& subset) const {\n  if (l.size() + subset.size() > schema.nbAttributes)\n    return false;\n\n\n  if (!l.canAdd(subset))\n    return false;\n\n  return true;\n}\n\n\n\nvoid BaseLayouter::generateSubSets() {\n  for (unsigned i = 1; i <= schema.nbAttributes; i++) {\n    generateSubSetsK(i, schema.nbAttributes);\n  }\n}\n\nstd::vector<subset_t> BaseLayouter::externalGenerateSubSetsK(unsigned k, unsigned nbAtts) {\n  subset_t s(nbAtts);\n  for (size_t i = 0; i < nbAtts; ++i)\n    s[i] = i;\n\n  std::vector<subset_t> result;\n\n  do {\n    result.push_back(subset_t(s.begin(), s.begin() + k));\n  } while (boost::next_partial_permutation(s.begin(), s.begin() + k, s.end()));\n\n  return result;\n}\n\nvoid BaseLayouter::generateSubSetsK(unsigned k, unsigned nbAtts) { subsets += externalGenerateSubSetsK(k, nbAtts); }\n\n\nvoid BaseLayouter::generateSet(std::vector<subset_t>& ctx,\n                               std::vector<unsigned> s,\n                               unsigned position,\n                               unsigned nextInt,\n                               unsigned k,\n                               unsigned N) {\n  if (position == k) {\n    // create the subset\n    subset_t newSubSet(k);\n\n    for (unsigned i = 0; i < k; i++) {\n      newSubSet[i] = s[i];\n    }\n\n    ctx.push_back(newSubSet);\n    return;\n  }\n\n  for (unsigned i = nextInt; i < N; i++) {\n    s[position] = i;\n    generateSet(ctx, s, position + 1, i + 1, k, N);\n  }\n}\n\nstd::vector<double> BaseLayouter::getCost(Layout l) {\n  size_t num_queries = schema.queries.size();\n  std::vector<double> totalCost(num_queries, 0.0);\n\n  BOOST_FOREACH(subset_t container, l.raw()) {\n    for (size_t q = 0; q < num_queries; ++q) {\n      totalCost[q] += schema.queries[q]->containerCost(container, schema, costModel);\n    }\n  }\n  return totalCost;\n}\n\nstd::vector<Result> BaseLayouter::getNBestResults(size_t n) {\n  size_t ms = n < results.size() ? n : results.size();\n  std::vector<Result> rs = std::vector<Result>(ms);\n  for (size_t i = 0; i < ms; ++i) {\n    rs[i] = results[i];\n    rs[i].setNames(schema.getAttributeNames());\n  }\n  return rs;\n}\n\nResult BaseLayouter::getBestResult(std::string newCostModel) {\n  Result r = results.front();\n  r.setNames(schema.getAttributeNames());\n  return r;\n}\n\nstd::vector<std::string> BaseLayouter::getAttributeNames() const { return schema.getAttributeNames(); }\n\ndouble BaseLayouter::getRowCost() const {\n  // build layout\n  subset_t tmp;\n  for (size_t i = 0; i < schema.nbAttributes; ++i)\n    tmp.push_back(i);\n\n  return schema.costForSubset(tmp, costModel);\n}\n\ndouble BaseLayouter::getColumnCost() const {\n  double result = 0.0;\n  for (size_t i = 0; i < schema.nbAttributes; ++i) {\n    subset_t tmp;\n    tmp.push_back(i);\n    result += schema.costForSubset(tmp, costModel);\n  }\n\n  return result;\n}\n\n\nvoid FastCandidateLayouter::layout(Schema s, std::string costModel) {\n  results.clear();\n  subsets.clear();\n  _mapping.clear();\n\n  _candidateList = std::vector<std::set<unsigned> >();\n\n  schema = s;\n  costModel = costModel;\n\n  // This is the part where the relevant subsets\n  // are created\n  generateCandidateList();\n\n\n  // Create subset mapping for primary partitions\n  for (unsigned i = 0; i < _candidateList.size(); ++i) {\n    _mapping.push_back(subset_t(_candidateList[i].begin(), _candidateList[i].end()));\n  }\n\n  // Now Create the required partitions table\n  subset_t partitions(_candidateList.size() - 1, 0);\n  for (unsigned i = 1; i < _candidateList.size(); ++i)\n    partitions[i - 1] = i;\n\n  subset_t initial(1, 0);\n  generateResults(initial, partitions);\n\n  // remap result, based on partitions\n  std::vector<subset_t> mappedResult;\n  BOOST_FOREACH(subset_t s, result) {\n    subset_t newSubset;\n    BOOST_FOREACH(unsigned i, s) {\n      BOOST_FOREACH(unsigned j, _mapping[i])\n      newSubset += j;\n    }\n    mappedResult += newSubset;\n  }\n\n  result = mappedResult;\n\n  // Prepare result\n  std::vector<double> costs;\n  BOOST_FOREACH(subset_t s, result) { costs.push_back(schema.costForSubset(s, HYRISE_COST)); }\n  Layout l(result);\n  Result r(l, costs);\n  results.push_back(r);\n}\n\ndouble FastCandidateLayouter::costFor(subset_t first) {\n  double result = 0;\n  subset_t tmp;\n  BOOST_FOREACH(unsigned i, first)\n  BOOST_FOREACH(unsigned j, _mapping[i])\n  tmp.push_back(j);\n\n  result = schema.costForSubset(tmp, HYRISE_COST);\n  return result;\n}\n\ndouble FastCandidateLayouter::costFor(subset_t first, subset_t second) { return costFor(first) + costFor(second); }\n\nvoid FastCandidateLayouter::generateResults(subset_t initial, subset_t other) {\n  Layout::internal_layout_t intermediate;\n  subset_t next;\n  double min = std::numeric_limits<double>::max();\n\n  if (other.size() == 0 && initial.size() == 1) {\n    result += initial;\n    return;\n  }\n\n  do {\n\n    subset_t combined(initial);\n\n    combined += other.front();\n\n    // Now we compare the cost for all possibilities, both, merged\n\n    double singleCost = costFor(initial, subset_t(1, other.front()));\n    double mergedCost = costFor(combined);\n\n    print(combined);\n    std::cout << \"--\" << std::endl;\n    print(initial);\n    print(subset_t(1, other.front()));\n    std::cout << costFor(initial) << \" \" << costFor(subset_t(1, other.front())) << std::endl;\n    std::cout << \"SC \" << singleCost << \" MC \" << mergedCost << std::endl;\n\n    if (singleCost < min) {\n      intermediate.clear();\n      intermediate += initial, subset_t(1, other.front());\n\n      next = subset_t(other.begin() + 1, other.end());\n      min = singleCost;\n    }\n\n    if (mergedCost < min) {\n      intermediate.clear();\n      intermediate += combined;\n\n      next = subset_t(other.begin() + 1, other.end());\n      min = mergedCost;\n    }\n\n  } while (boost::next_partial_permutation(other.begin(), other.begin() + 1, other.end()));\n\n  std::cout << \"Finished calculation, checking for result \" << intermediate.size() << std::endl;\n\n  // The single cost are better, proceed separate\n  if (intermediate.size() > 1) {\n    result += intermediate.front();\n    if (other.begin() + 1 != other.end()) {\n      print(intermediate.back());\n      print(next);\n      generateResults(intermediate.back(), next);\n    } else\n      result += intermediate.back();\n  } else {\n    if (other.begin() + 1 != other.end())\n      generateResults(intermediate.front(), next);\n    else\n      result += intermediate.front();\n  }\n}\n\n\nCandidateLayouter::CandidateLayouter() : BaseLayouter(), _candidateList() {}\n\nvoid CandidateLayouter::layout(Schema s, std::string cM) {\n  results.clear();\n  subsets.clear();\n  _candidateList = std::vector<std::set<unsigned> >();\n\n  schema = s;\n  costModel = cM;\n\n  // This is the part where the relevant subsets\n  // are created\n  generateCandidateList();\n  combineCandidates();\n\n  // Finish the job and search for the perfect match\n  std::sort(subsets.begin(), subsets.end(), subset_t_lt);\n\n  // Initialize bit vector with all valid subsets, initially all\n  // subsets are valid\n  std::vector<bool> validSubsets(subsets.size(), true);\n  std::vector<bool> uncheckedSubsets(subsets.size(), true);\n\n  // Cache cost map\n  std::unordered_map<subset_t, double> cache;\n\n\n  // Reduce the number of subsets to examine for building the final\n  // layout. The main idea in this sub-step is to identify all those\n  // merged sub-groups that yield equal cost\n  size_t index = 0;\n  while (index < subsets.size()) {\n    // if the subsets are smaller than a single attribute, ignore\n    if (subsets[index].size() > 1) {\n      size_t currentSize = subsets[index].size();\n\n      // Find end of group\n      size_t stop = index + 1;\n      while (stop < subsets.size())\n        if (subsets[stop++].size() > currentSize)\n          break;\n\n      // Now for each element inside this block, find possible partners\n      for (size_t i = index; i < stop; ++i) {\n        if (!uncheckedSubsets[i])\n          continue;\n\n\n        double current;\n\n        if (cache.count(subsets[i]) == 0)\n          cache[subsets[i]] = schema.costForSubset(subsets[i], HYRISE_COST);\n\n        current = cache[subsets[i]];\n\n        // Now compare with all other subsets\n        for (size_t j = i + 1; j < stop; ++j) {\n          if (uncheckedSubsets[j] && subset_t_content_equal(subsets[i], subsets[j])) {\n            uncheckedSubsets[j] = false;\n            double test;\n            if (cache.count(subsets[j]) == 0)\n              cache[subsets[j]] = schema.costForSubset(subsets[j], HYRISE_COST);\n\n            test = cache[subsets[j]];\n\n\n            if (current == test)\n              validSubsets[j] = 0;\n          }\n        }\n      }\n    }\n    ++index;\n  }\n\n  std::vector<subset_t> newList;\n  for (size_t i = 0; i < validSubsets.size(); ++i) {\n    if (validSubsets[i])\n      newList.push_back(subsets[i]);\n  }\n\n  subsets = newList;\n  iterateThroughLayouts();\n  std::sort(results.begin(), results.end());\n}\n\nvoid CandidateLayouter::generateCandidateList() {\n  BOOST_FOREACH(Query * q, schema.queries) {\n    std::set<unsigned> newQuery;\n    BOOST_FOREACH(unsigned i, q->queryAttributes) { newQuery.insert(i); }\n\n    if (_candidateList.size() == 0) {\n      _candidateList.push_back(newQuery);\n    } else {\n      std::vector<std::set<unsigned> > newSets;\n      BOOST_FOREACH(std::set<unsigned> & oldSet, _candidateList) {\n        std::set<unsigned> intersect;\n        BOOST_FOREACH(unsigned i, newQuery) {\n          if (oldSet.count(i) > 0) {\n            // the new set and the existing set intersect\n            // add the attribute to the intersection\n            intersect.insert(i);\n          }\n        }\n\n        BOOST_FOREACH(unsigned i, intersect) {\n          newQuery.erase(i);\n          oldSet.erase(i);\n        }\n\n        // keep track of which sets to add\n        newSets.push_back(intersect);\n      }\n\n      // add new sets, i.e. add query and intersect\n      _candidateList.push_back(newQuery);\n      BOOST_FOREACH(std::set<unsigned> newSet, newSets) { _candidateList.push_back(newSet); }\n\n      // Delete empty sets\n      std::vector<unsigned> toDelete;\n\n      for (size_t i = 0; i < _candidateList.size(); ++i) {\n        if (_candidateList[i].size() == 0) {\n          toDelete.push_back(i);\n        }\n      }\n\n      for (size_t i = toDelete.size(); i > 0; --i) {\n        _candidateList.erase(_candidateList.begin() + toDelete[i - 1]);\n      }\n    }\n  }\n\n  // add a set for those attributes that are never queried\n  std::set<unsigned> neverQueried;\n\n  for (unsigned i = 0; i < schema.nbAttributes; ++i) {\n    bool queried = false;\n    BOOST_FOREACH(std::set<unsigned> set, _candidateList) {\n      if (set.count(i) > 0) {\n        queried = true;\n        break;\n      }\n    }\n\n    if (!queried) {\n      neverQueried.insert(i);\n    }\n  }\n\n  if (neverQueried.size() > 0) {\n    _candidateList.push_back(neverQueried);\n  }\n}\n\n\nstd::string strval(subset_t m) {\n  std::stringstream strs;\n  BOOST_FOREACH(unsigned i, m) { strs << i << \" \"; }\n\n  return strs.str();\n}\n\n\nsubset_t merge_subsets(subset_t base, std::vector<subset_t>& mapping) {\n  subset_t result;\n  BOOST_FOREACH(unsigned i, base) {\n    BOOST_FOREACH(unsigned j, mapping[i]) { result.push_back(j); }\n  }\n\n  return result;\n}\n\ntypedef std::unordered_map<std::string, double> cache_t;\n\n// Intermediate Result Structure to capture cost and mappings\nstruct _intermediate {\n  std::vector<subset_t> single;\n  double single_cost;\n  subset_t merged;\n  double merge_cost;\n\n  static _intermediate create(subset_t base,\n                              std::vector<subset_t>& mapping,\n                              Schema& schema,\n                              std::string& costModel,\n                              cache_t& cache) {\n    _intermediate res;\n    res.single_cost = 0.0;\n    res.merge_cost = 0.0;\n\n    std::string tmp_val;\n\n    BOOST_FOREACH(unsigned i, base) {\n      res.single.push_back(mapping[i]);\n      tmp_val = strval(mapping[i]);\n      if (cache.count(tmp_val) == 0) {\n        cache[tmp_val] = schema.costForSubset(mapping[i], costModel);\n      }\n\n      res.single_cost += cache[tmp_val];\n      // res.single_cost += schema.costForSubset(mapping[i], costModel);\n\n      BOOST_FOREACH(unsigned j, mapping[i]) { res.merged.push_back(j); }\n    }\n\n    res.merge_cost = schema.costForSubset(res.merged, costModel);\n    return res;\n  }\n};\n\n\nstd::vector<subset_t> CandidateLayouter::externalCombineCandidates(std::vector<std::set<unsigned> > candidateList) {\n\n  std::vector<subset_t> mapping;\n  for (unsigned i = 0; i < candidateList.size(); ++i) {\n    mapping.push_back(subset_t(candidateList[i].begin(), candidateList[i].end()));\n  }\n\n\n  // Cache to avoid frequent recalculations\n\n  cache_t _cache;\n\n  // The first step is to build a list of permutations of the input\n  // candidate list, so that if the input is [1][2,3] -> the output\n  // will be [1], [2,3], [1,2,3]\n  std::vector<subset_t> result;\n\n  subset_t tmp(candidateList.size(), 0);\n  subset_t initial;\n\n  // Prepare the current permutation step\n  for (unsigned j = 0; j < candidateList.size(); ++j)\n    tmp[j] = j;\n\n  result = candidateMergePath(initial, tmp, mapping, _cache);\n\n  return result;\n}\n\nstd::vector<subset_t> CandidateLayouter::candidateMergePath(subset_t initial,\n                                                            subset_t rest,\n                                                            std::vector<subset_t>& mapping,\n                                                            std::unordered_map<std::string, double>& _cache) {\n  std::vector<subset_t> result;\n  do {\n\n    subset_t combined(initial);\n    combined.push_back(rest.front());\n\n    _intermediate c = _intermediate::create(combined, mapping, schema, costModel, _cache);\n    if (c.single.size() == 1 || c.merge_cost < c.single_cost) {\n      // Append the intermediate merged list to the\n      result.push_back(c.merged);\n\n      if (rest.begin() + 1 != rest.end()) {\n        subset_t down(rest.begin() + 1, rest.end());\n        std::vector<subset_t> tmp = candidateMergePath(combined, down, mapping, _cache);\n        BOOST_FOREACH(subset_t t, tmp)\n        result.push_back(t);\n      }\n    }\n  } while (boost::next_partial_permutation(rest.begin(), rest.begin() + 1, rest.end()));\n\n  return result;\n}\n\n\nvoid CandidateLayouter::combineCandidates() { subsets = externalCombineCandidates(_candidateList); }\n\n/////////////////////////////////////////////////////////////////////////\n\nint layouter::DivideAndConquerLayouter::numCuts = 4;\n\nDivideAndConquerLayouter::DivideAndConquerLayouter() : CandidateLayouter() {}\n\n\nMatrix<int> DivideAndConquerLayouter::createAffinityMatrix() {\n\n  // Build the initial empty matrix\n  Matrix<int> d(subsets.size());\n\n  // Now make the big check\n  for (size_t i = 0; i < subsets.size() - 1; ++i) {\n    subset_t subsetToCheck = subsets[i];\n\n    for (size_t j = i + 1; j < subsets.size(); ++j) {\n      subset_t otherSubset = subsets[j];\n\n      // Now check both subsets if they appear in the queries together\n      BOOST_FOREACH(Query * q, schema.queries) {\n\n        subset_t::iterator l = std::find_first_of(\n            q->queryAttributes.begin(), q->queryAttributes.end(), subsetToCheck.begin(), subsetToCheck.end());\n\n        subset_t::iterator r = std::find_first_of(\n            q->queryAttributes.begin(), q->queryAttributes.end(), otherSubset.begin(), otherSubset.end());\n\n        if (l != q->queryAttributes.end() && r != q->queryAttributes.end()) {\n          // Found a hit\n          int tmp = d.get(i, j) + 1;\n          d.set(j, i, tmp);\n          d.set(i, j, tmp);\n        }\n      }\n    }\n  }\n\n  return d;\n}\n\nstd::vector<std::vector<set_subset_t> > DivideAndConquerLayouter::partitionGraph(Matrix<int> m) {\n  adj_t t = m.buildAdjacency();\n\n  int numvertices = m.numVertices();\n\n  int options[METIS_NOPTIONS];\n  METIS_SetDefaultOptions(options);\n  options[METIS_OPTION_PTYPE] = METIS_PTYPE_KWAY;\n  options[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_CUT;\n  options[METIS_OPTION_NUMBERING] = 0;\n  // options[METIS_OPTION_DBGLVL] = METIS_DBG_INFO | METIS_DBG_MEMORY | METIS_DBG_COARSEN;\n  options[METIS_OPTION_DBGLVL] = 0;\n\n  int ncon = 1;\n\n  // K defines the size of the parition, while k is the number of cuts the\n  // partitioner will have to do, so we can calculate k by\n  // dividing P/K\n  int nparts = numvertices > numCuts ? numvertices / numCuts : 1;  // - 1 < numCuts ? numvertices - 1 : numCuts;\n  if (nparts == 1)\n    nparts = 2;\n\n  int edgecut = 0;\n\n  int* part = (int*)malloc(1 * numvertices * sizeof(numvertices));\n  int res = METIS_PartGraphKway(&numvertices,  // Number of Vertices\n                                &ncon,  // Number of balancing constraints\n                                t.xadj,\n                                t.adjncy,\n                                nullptr,  // vertices weight\n                                nullptr,  // vertices size\n                                t.adjwgt,  // edege weight\n                                &nparts,  // number of parts to partition\n                                nullptr,  // targeted partition weight\n                                nullptr,  // ubvec, load imbalance bla bla\n                                options,\n                                &edgecut,\n                                part);  // result parts\n\n\n  if (res == METIS_OK) {\n    // std::cout << nparts << std::endl;\n\n    // Based on the partitions of the graph, we can now\n    // merge the subsets to new subsets\n    std::vector<std::vector<set_subset_t> > candidatePartitions(nparts);  // Create at least nparts buckets\n    for (int i = 0; i < numvertices; ++i) {\n      int current = part[i];\n      set_subset_t oldsubset = set_subset_t(subsets[i].begin(), subsets[i].end());\n\n      // Copy the subsets over\n      candidatePartitions[current].push_back(oldsubset);\n    }\n\n    // the result may contain empty partitions\n    return candidatePartitions;\n\n  } else {\n    throw std::runtime_error(\"Graph Partitioning Seriously Failed\");\n  }\n}\n\nvoid DivideAndConquerLayouter::layout(Schema s, std::string cm) {\n  results.clear();\n  subsets.clear();\n\n  if (s.queries.size() == 1) {\n    CandidateLayouter::layout(s, cm);\n    return;\n  }\n\n  _candidateList = std::vector<std::set<unsigned> >();\n\n  schema = s;\n  costModel = cm;\n\n  // This is the part where the relevant subsets\n  // are created\n  generateCandidateList();\n  subsets.clear();\n\n  BOOST_FOREACH(std::set<unsigned> l, _candidateList) { subsets.push_back(subset_t(l.begin(), l.end())); }\n\n\n  Matrix<int> m = createAffinityMatrix();\n\n  // The result of the partitioning operation is a list of parition\n  // lists that are layouted independently\n  std::vector<std::vector<set_subset_t> > partitions = partitionGraph(m);\n\n  // The partitions variable holds a list of subset lists, which are\n  // layouted individually.\n  subsets.clear();\n\n  size_t nbAtt = schema.nbAttributes;\n  std::vector<subset_t> global;\n  BOOST_FOREACH(std::vector<set_subset_t> tmp, partitions) {\n\n    // Ignore empty sets\n    if (tmp.size() == 0)\n      continue;\n\n    std::vector<subset_t> permutations = externalCombineCandidates(tmp);\n    std::set<unsigned> current;\n    for (subset_t t : permutations)\n      for (unsigned u : t)\n        current.insert(u);\n\n    schema.nbAttributes = current.size();\n    subsets = permutations;\n\n    results.clear();\n    iterateThroughLayouts();\n    std::sort(results.begin(), results.end());\n\n    Result r = results[0];\n    Layout l = r.layout;\n\n    for (subset_t t : l.raw())\n      global += t;\n  }\n\n  schema.nbAttributes = nbAtt;\n  subsets = global;\n  // Finish the job and search for the perfect match\n  iterateThroughLayouts();\n  std::sort(results.begin(), results.end());\n}\n}\n}  // namespace hyrise::layouter\n", "meta": {"hexsha": "6b8e00d3998771b0b35f7c7aafe51a875d201cc8", "size": 40012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/layouter/base.cpp", "max_stars_repo_name": "jmarten/hyrise", "max_stars_repo_head_hexsha": "795d8c1c55ed6cbd313d88cee40610006fa85669", "max_stars_repo_licenses": ["MIT"], "max_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/layouter/base.cpp", "max_issues_repo_name": "jmarten/hyrise", "max_issues_repo_head_hexsha": "795d8c1c55ed6cbd313d88cee40610006fa85669", "max_issues_repo_licenses": ["MIT"], "max_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/layouter/base.cpp", "max_forks_repo_name": "jmarten/hyrise", "max_forks_repo_head_hexsha": "795d8c1c55ed6cbd313d88cee40610006fa85669", "max_forks_repo_licenses": ["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.5392296719, "max_line_length": 118, "alphanum_fraction": 0.6200139958, "num_tokens": 10231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.02128735035760237, "lm_q1q2_score": 0.01022811795896343}}
{"text": "// /**\n//  * @file   \n//  * @brief  Fock JK matrix operator implementation\n//  */\n\n// #include <algorithm>\n\n// #include \"hf/work_queue.hpp\"\n// #include \"hf/hf.hpp\"\n// #include \"hf/thread.hpp\"\n// #include \"runtime.hpp\"\n\n// #include \"util/numeric.hpp\"\n// #include \"matrix/meta.hpp\"\n\n// #include \"hf/cuda.hpp\"\n\n// #include <boost/array.hpp>\n// #include <boost/typeof/typeof.hpp>\n// #include <boost/utility.hpp>\n// #include <boost/math/special_functions/pow.hpp>\n// #include <boost/date_time/posix_time/posix_time.hpp>\n// #include <boost/lambda/lambda.hpp>\n\n// using boost::math::pow;\n// namespace lambda = boost::lambda;\n\n// #define TYPEOF BOOST_TYPEOF\n// #define AUTO BOOST_AUTO\n\n// #ifdef HAVE_GA\n// #include \"distributed.hpp\"\n// #endif\n\n\n// using namespace hf;\n\n// // see hf.h\n// void hf::fock(const Basis &basis, \n// \t      const matrix::meta_matrix<BlockMatrix> &D,\n// \t      matrix::meta_matrix<BlockMatrix> &F,\n// \t      const matrix::meta_matrix<Matrix> *Kmax,\n// \t      const matrix::meta_matrix<Matrix> *Dmax,\n// \t      double cutoff) {\n\n//     timer t;\n\n//     Screen<matrix::meta_matrix<Matrix> > screen(*Kmax, *Dmax, cutoff);\n\n//     typedef rysq::block_matrix_adapter<double> matrix_adapter;\n//     rysq::initialize();\n\n//     work_queue queue(basis.blocks().size());\n\n    \n\n//     lockable<TYPEOF(F)> lockable_fock(F);\n\n//     size_t num_threads = runtime::num_threads(fock_thread_group::max_threads());\n//     fock_thread_group host(basis.blocks().begin(), basis.centers(), screen,\n// \t\t\t   D, lockable_fock, queue, num_threads);\n\n// #if HF_CUDA\n//     {\n// \tstd::vector<int> devices = runtime::cuda_devices(cuda::all_devices());\n// \tcuda::fock_thread_group cuda(basis.blocks().begin(), basis.centers(), screen,\n// \t\t\t\t     D, lockable_fock, queue, devices);\n// \tcuda.join_all();\n//     }\n// #endif\n\n//     host.join_all();\n\n//     if (!queue.backlog().empty()) {\n//     \tfock_thread host(basis.blocks().begin(), basis.centers(), screen,\n//     \t\t\t D, lockable_fock, queue);\n//     \thost.join();\n//     }\n\n//     matrix::symmeterize(F); // symmetrize fock matrix\n\n//     // surface.render(K);\n//     //matrix::plot::surface(F);\n\n//     return;\n// }\n\n", "meta": {"hexsha": "ca8e58169eb3b19f86b7c5357ee0d2e663d364e8", "size": 2163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/src/hf/fock.cpp", "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamess/libqc/src/hf/fock.cpp", "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamess/libqc/src/hf/fock.cpp", "max_forks_repo_name": "andremirt/v_cond", "max_forks_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5795454545, "max_line_length": 83, "alphanum_fraction": 0.6245954693, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.024423087657560003, "lm_q1q2_score": 0.010225870964833678}}
{"text": "#include <algorithm>\n#include <vector>\n\n#include <armadillo>\nusing namespace arma;\n\n// json parser\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\nnamespace pt = boost::property_tree;\n\n#include \"../GreensTensor/GreensTensorFactory.h\"\n#include \"Friction.h\"\n\nFriction::Friction(const std::string &input_file) {\n  // Create a root\n  pt::ptree root;\n\n  // Load the json file in this ptree\n  pt::read_json(input_file, root);\n  this->relerr_omega = root.get<double>(\"Friction.relerr_omega\");\n\n  // read greens tensor\n  this->powerspectrum = std::make_shared<PowerSpectrum>(input_file);\n  this->polarizability = powerspectrum->get_polarizability();\n  this->greens_tensor = powerspectrum->get_greens_tensor();\n}\n\nFriction::Friction(std::shared_ptr<GreensTensor> greens_tensor,\n                   std::shared_ptr<Polarizability> polarizability,\n                   std::shared_ptr<PowerSpectrum> powerspectrum,\n                   double relerr_omega)\n    : greens_tensor(greens_tensor), polarizability(polarizability),\n      powerspectrum(powerspectrum), relerr_omega(relerr_omega) {}\n\ndouble Friction::calculate(Spectrum_Options spectrum) const {\n  double result;\n  double omega_a = this->polarizability->get_omega_a();\n  // Collect all specifically relevant point within the integration\n  std::vector<double> lim = {0., 0.99 * omega_a, 1.001 * omega_a,\n                             this->greens_tensor->omega_ch()};\n  // Sort the points and erase duplicates\n  std::sort(lim.begin(), lim.end());\n  auto last = std::unique(lim.begin(), lim.end());\n  lim.erase(last, lim.end());\n\n  // Start integration\n  result = 0.;\n  auto F = [=](double x) -> double { return friction_integrand(x, spectrum); };\n\n  for (int i = 0; i < (int)lim.size() - 1; i++) {\n    result += cquad(F, lim[i], lim[i + 1], relerr_omega,\n                    std::abs(result) * relerr_omega);\n  }\n  // Perform last integration from the last significant point to infinity\n  result += qagiu(F, lim[lim.size() - 1], relerr_omega,\n                  std::abs(result) * relerr_omega);\n  return result;\n}\n\ndouble Friction::friction_integrand(double omega,\n                                    Spectrum_Options spectrum) const {\n  // Compute the full spectrum of the power spectrum\n  if (spectrum == FULL) {\n\n    // Initialize all tensors\n    cx_mat::fixed<3, 3> green_kv(fill::zeros);\n    cx_mat::fixed<3, 3> green_temp_kv(fill::zeros);\n    cx_mat::fixed<3, 3> alpha_I(fill::zeros);\n    cx_mat::fixed<3, 3> powerspec(fill::zeros);\n\n    // computation of the Green's tensor in the first term of eq. (4.3)\n    greens_tensor->integrate_k(omega, green_kv, IM, KV);\n\n    // computation of the Green's tensor in the second term of eq. (4.3)\n    greens_tensor->integrate_k(omega, green_temp_kv, IM, KV_TEMP);\n\n    // computation of the imaginary part of the polarizability appearing in the\n    // second term of eq. (4.3)\n    polarizability->calculate_tensor(omega, alpha_I, IM);\n\n    // computation of the powerspectrum apperaing in the first term of eq. (4.3)\n    powerspectrum->calculate(omega, powerspec, FULL);\n\n    return real(2. * trace(-powerspec * green_kv +\n                           1. / M_PI * alpha_I * green_temp_kv));\n  }\n  // Compute onyl the non-LTE contribution of the power-spectrum\n  else if (spectrum == NON_LTE_ONLY) {\n    // Initialize all tensors\n    cx_mat::fixed<3, 3> J(fill::zeros);\n    cx_mat::fixed<3, 3> green_kv(fill::zeros);\n    cx_mat::fixed<3, 3> alpha_fancy_I(fill::zeros);\n    cx_mat::fixed<3, 3> green_fancy_I_kv_non_LTE(fill::zeros);\n\n    // Compute the Green's tensor in the first term of eq. (4.5)\n    greens_tensor->integrate_k(omega, green_kv, IM, KV);\n\n    // Compute the Green's tensor in the second term of eq. (4.5)\n    // the \\Sigma distribution is already included here\n    greens_tensor->integrate_k(omega, green_fancy_I_kv_non_LTE, IM, KV_NON_LTE);\n\n    // Compute the power spectrum for the first term of eq. (4.5)\n    powerspectrum->calculate(omega, J, NON_LTE_ONLY);\n\n    // Compute the polarizability for the second term of eq. (4.5)\n    polarizability->calculate_tensor(omega, alpha_fancy_I, IM);\n\n    // Put everything together\n    return real(\n        trace(2. *\n              (-J * green_kv + alpha_fancy_I * green_fancy_I_kv_non_LTE)));\n  }\n  // Ensure that a valid integration argument has been passed\n  else {\n    std::cerr << \"No valid option for the calculation of quantum friction have \"\n                 \"been passed\"\n              << std::endl;\n    exit(0);\n  }\n}\n\nvoid Friction::print_info(std::ostream &stream) const {\n  stream << \"# Friction\\n#\\n\"\n  << \"# relerr_omega = \" << relerr_omega << \"\\n\";\n greens_tensor->print_info(stream);\n polarizability->print_info(stream);\n powerspectrum->print_info(stream);\n}\n", "meta": {"hexsha": "7c868afc4a4398410a9ab44fbb238b6630aae9b8", "size": 4761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Friction/Friction.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "src/Friction/Friction.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "src/Friction/Friction.cpp", "max_forks_repo_name": "myoelmy/quaca", "max_forks_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6230769231, "max_line_length": 80, "alphanum_fraction": 0.6698172653, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.02843603273609212, "lm_q1q2_score": 0.010218890595950419}}
{"text": "// Copyright 2019 ETH Zürich, Thomas Schöps\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice,\n//    this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors\n//    may be used to endorse or promote products derived from this software\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\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 \"camera_calibration/calibration.h\"\n\n#include <thread>\n\n#include <boost/filesystem.hpp>\n#include <libvis/logging.h>\n#include <libvis/eigen.h>\n#include <libvis/image.h>\n#include <libvis/image_display.h>\n#include <libvis/lm_optimizer.h>\n#include <libvis/util.h>\n#include <QApplication>\n#include <QDir>\n#include <QFileInfo>\n\n#include \"camera_calibration/bundle_adjustment/ba_state.h\"\n#include \"camera_calibration/bundle_adjustment/cuda_joint_optimization.h\"\n#include \"camera_calibration/calibration_report.h\"\n#include \"camera_calibration/calibration_initialization/dense_initialization.h\"\n#include \"camera_calibration/dataset.h\"\n#include \"camera_calibration/fitting_report.h\"\n#include \"camera_calibration/hash_vec2i.h\"\n#include \"camera_calibration/io/calibration_io.h\"\n#include \"camera_calibration/models/all_models.h\"\n#include \"camera_calibration/local_parametrizations/quaternion_parametrization.h\"\n#include \"camera_calibration/ui/calibration_window.h\"\n#include \"camera_calibration/util.h\"\n\nnamespace vis {\n\n// TODO: Make the number of spline parameters configurable?\nconstexpr int kNumSplineParametersForRadialModel = 250;\n\nvoid DeleteOutlierFeatures(\n    int camera_index,\n    Dataset* dataset,\n    BAState* state,\n    float outlier_removal_factor,\n    CalibrationWindow* calibration_window,\n    bool step_by_step,\n    const char* outlier_visualization_path) {\n  // Get statistics of reprojection errors\n  vector<double> reprojection_errors;\n  \n  for (int imageset_index = 0; imageset_index < dataset->ImagesetCount(); ++ imageset_index) {\n    if (!state->image_used.at(imageset_index)) {\n      continue;\n    }\n    \n    const SE3d& this_image_tr_global = state->image_tr_global(camera_index, imageset_index);\n    Mat3d image_r_global = this_image_tr_global.rotationMatrix();\n    const Vec3d& image_t_global = this_image_tr_global.translation();\n    \n    shared_ptr<const Imageset> imageset = dataset->GetImageset(imageset_index);\n    const vector<PointFeature>& features = imageset->FeaturesOfCamera(camera_index);\n    \n    for (const PointFeature& feature : features) {\n      Vec3d local_point = image_r_global * state->points[feature.index] + image_t_global;\n      Vec2d pixel;\n      if (state->intrinsics[camera_index]->Project(local_point, &pixel)) {\n        Vec2d reprojection_error = pixel - feature.xy.cast<double>();\n        double reprojection_error_magnitude = reprojection_error.norm();\n        reprojection_errors.push_back(reprojection_error_magnitude);\n      }\n    }\n  }\n  \n  if (reprojection_errors.size() < 8) {  // arbitrary threshold\n    // Too few reprojection errors to reliably detect outliers.\n    return;\n  }\n  \n  std::sort(reprojection_errors.begin(), reprojection_errors.end());\n  \n  // Determine outlier threshold\n  double first_quartile_error = reprojection_errors[0.25f * reprojection_errors.size() + 0.5f];\n  double third_quartile_error = reprojection_errors[0.75f * reprojection_errors.size() + 0.5f];\n  // 1.5 is what matplotlib uses by default for outliers in box plots\n  double outlier_threshold = third_quartile_error + outlier_removal_factor * (third_quartile_error - first_quartile_error);\n  \n  Image<Vec3u8> outlier_visualization(state->intrinsics[camera_index]->width(), state->intrinsics[camera_index]->height());\n  outlier_visualization.SetTo(Vec3u8::Zero());\n  \n  // Remove outliers\n  usize num_removed_outliers = 0;\n  for (int imageset_index = 0; imageset_index < dataset->ImagesetCount(); ++ imageset_index) {\n    if (!state->image_used.at(imageset_index)) {\n      continue;\n    }\n    \n    const SE3d& this_image_tr_global = state->image_tr_global(camera_index, imageset_index);\n    Mat3d image_r_global = this_image_tr_global.rotationMatrix();\n    const Vec3d& image_t_global = this_image_tr_global.translation();\n    \n    shared_ptr<Imageset> imageset = dataset->GetImageset(imageset_index);\n    vector<PointFeature>& features = imageset->FeaturesOfCamera(camera_index);\n    \n    usize num_features = features.size();\n    erase_if(features, [&](const PointFeature& feature){\n      Vec3d local_point = image_r_global * state->points[feature.index] + image_t_global;\n      Vec2d pixel;\n      if (!state->intrinsics[camera_index]->Project(local_point, &pixel)) {\n        LOG(1) << \"Removing outlier which does not project into the image.\";\n        outlier_visualization(feature.xy.x(), feature.xy.y()) = Vec3u8(127, 127, 127);\n        return true;\n      }\n      Vec2d reprojection_error = pixel - feature.xy.cast<double>();\n      double reprojection_error_magnitude = reprojection_error.norm();\n      if (reprojection_error_magnitude > outlier_threshold) {\n        LOG(1) << \"Removing outlier with reprojection error higher than threshold (\" << reprojection_error_magnitude << \" > \" << outlier_threshold << \")\";\n        \n        if (reprojection_error_magnitude > 10) {\n          outlier_visualization(feature.xy.x(), feature.xy.y()) = Vec3u8(255, 0, 0);\n        } else if (reprojection_error_magnitude > 5) {\n          outlier_visualization(feature.xy.x(), feature.xy.y()) = Vec3u8(255, 127, 0);\n        } else if (reprojection_error_magnitude > 1) {\n          outlier_visualization(feature.xy.x(), feature.xy.y()) = Vec3u8(255, 255, 0);\n        } else {\n          outlier_visualization(feature.xy.x(), feature.xy.y()) = Vec3u8(255, 255, 255);\n        }\n      }\n      return reprojection_error_magnitude > outlier_threshold;\n    });\n    num_removed_outliers += num_features - features.size();\n    \n    if (features.size() < 3) {\n      state->image_used.at(imageset_index) = false;\n    }\n  }\n  \n  LOG(INFO) << \"Outlier detection removed \" << num_removed_outliers << \" outlier features.\";\n  \n  if (calibration_window) {\n    calibration_window->UpdateRemovedOutliers(camera_index, outlier_visualization);\n    if (step_by_step) {\n      GetKeyInput();\n    }\n  }\n  \n  if (outlier_visualization_path) {\n    ostringstream path;\n    path << outlier_visualization_path << \"_camera\" << camera_index << \"_removed_outliers.png\";\n    \n    // Create containing folder\n    QFileInfo(path.str().c_str()).dir().mkpath(\".\");\n    \n    if (!outlier_visualization.Write(path.str())) {\n      LOG(ERROR) << \"Cannot write file: \" << path.str();\n    }\n  }\n  \n  // TODO: It might theoretically happen that some points in the points vector\n  //       are not referenced anymore at all after removing outliers. Those\n  //       should ideally be removed here, otherwise they might have a\n  //       detrimental effect on the optimization.\n}\n\n\nvoid RunBundleAdjustment(\n    bool use_cuda,\n    SchurMode schur_mode,\n    int max_iteration_count,\n    double cost_reduction_threshold,\n    Dataset* dataset,\n    BAState* state,\n    double regularization_weight,\n    bool localize_only,\n    CalibrationWindow* calibration_window,\n    bool step_by_step,\n    const char* state_output_path) {\n   // NOTE: So far I didn't see any improvement from using multiple deltas.\n   //       But it does have an effect, since making it too large (1e-1) resulted in problems.\n  vector<double> numerical_diff_delta_range = {/*1e-3,*/ 1e-4/*, 1e-5*/};\n  \n  double lambda = -1;\n  \n  for (usize numerical_diff_delta_index = 0; numerical_diff_delta_index < numerical_diff_delta_range.size(); ++ numerical_diff_delta_index) {\n    double numerical_diff_delta = numerical_diff_delta_range[numerical_diff_delta_index];\n    \n    double last_cost = numeric_limits<double>::infinity();\n    for (int iteration = 0; iteration < max_iteration_count; ++ iteration) {\n      double cost;\n      \n      if (use_cuda) {\n        if (localize_only) {\n          LOG(ERROR) << \"localize_only is not supported for CUDA-based optimization currently\";\n        }\n        OptimizationReport report = CudaOptimizeJointly(\n            *dataset,\n            state,\n            /*max_iteration_count*/ 1,\n            /*int max_inner_iterations*/ 50,  // TODO: tune\n            lambda,\n            numerical_diff_delta,\n            regularization_weight,\n            &lambda);\n        cost = report.final_cost;\n      } else {\n        cost = OptimizeJointly(\n            *dataset,\n            state,\n            /*max_iteration_count*/ 1,\n            lambda,\n            numerical_diff_delta,\n            regularization_weight,\n            localize_only,\n            /*eliminate_points*/ false,\n            schur_mode,\n            &lambda);\n      }\n      \n      LOG(INFO) << \"[\" << (iteration + 1) << \"] Cost: \" << cost;\n      \n      // Save the optimization state\n      if (state_output_path) {\n        SaveBAState(state_output_path, *state);\n      }\n      \n      // Beautify all camera orientations\n      if (!localize_only) {\n        for (int camera_index = 0; camera_index < state->num_cameras(); ++ camera_index) {\n          Mat3d rotation = state->intrinsics[camera_index]->ChooseNiceCameraOrientation();\n          SE3d rotation_transform(rotation, Vec3d::Zero());\n          state->camera_tr_rig[camera_index] = rotation_transform * state->camera_tr_rig[camera_index];\n        }\n      }\n      \n      // Visualize current state\n      if (calibration_window) {\n        for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n          calibration_window->SetCurrentCameraIndex(camera_index);\n          \n          // Visualize model intrinsics\n          Image<Vec3u8> visualization;\n          VisualizeModelDirections(*state->intrinsics[camera_index], &visualization);\n          calibration_window->UpdateObservationDirections(camera_index, visualization);\n          \n          // Visualize reprojection errors\n          Image<u8> reprojection_histogram_image;\n          CreateReprojectionErrorHistogram(\n              camera_index,\n              *dataset,\n              *state,\n              &reprojection_histogram_image);\n          calibration_window->UpdateErrorHistogram(camera_index, reprojection_histogram_image);\n          \n          // Visualize reprojection errors with their magnitudes\n          CreateReprojectionErrorMagnitudeVisualization(\n              *dataset, camera_index, *state, 5.0f, &visualization);\n          calibration_window->UpdateReprojectionErrors(camera_index, visualization, dataset, state);\n          \n          // Visualize reprojection error directions\n          CreateReprojectionErrorDirectionVisualization(\n              *dataset, camera_index, *state, &visualization);\n          calibration_window->UpdateErrorDirections(camera_index, visualization);\n        }\n        \n        if (step_by_step) {\n          LOG(INFO) << \"> Press Return to continue\";\n          GetKeyInput();\n        }\n      }\n      \n      // Stop if the q key was pressed\n      if (PollKeyInput() == 'q') {\n        break;\n      }\n      \n      // Stopping criterion\n      if (cost >= last_cost - cost_reduction_threshold) {\n        break;\n      }\n      last_cost = cost;\n    }\n  }\n}\n\n\nvoid ScaleToMetric(\n    Dataset* dataset,\n    BAState* state) {\n  // Average a scaling correction factor by comparing the distance of neighboring corners\n  // in the ideal pattern and all optimized patterns. Comparing neighboring corners (as\n  // opposed to comparing other corner pairs) makes sense since we expect non-rigid\n  // deformations to the calibration pattern (e.g., if it is printed on paper).\n  double scaling_log_sum = 0;\n  int scaling_count = 0;\n  \n  for (usize k = 0; k < dataset->KnownGeometriesCount(); ++ k) {\n    const KnownGeometry& geometry = dataset->GetKnownGeometry(k);\n    \n    // Build a map from corner positions to indices in state->points\n    unordered_map<Vec2i, int> corner_position_to_index;\n    for (const pair<int, Vec2i>& item : geometry.feature_id_to_position) {\n      int feature_id = item.first;\n      const Vec2i& position = item.second;\n      \n      auto it = state->feature_id_to_points_index.find(feature_id);\n      if (it != state->feature_id_to_points_index.end()) {\n        corner_position_to_index[position] = it->second;\n      }\n    }\n    if (corner_position_to_index.empty()) {\n      continue;\n    }\n    \n    // Loop over all corners\n    for (const pair<int, Vec2i>& item : geometry.feature_id_to_position) {\n      const Vec2i& position = item.second;\n      auto it = corner_position_to_index.find(position);\n      if (it == corner_position_to_index.end()) {\n        continue;\n      }\n      int index = it->second;\n      \n      // Loop over neighbors of this corner (looking in one direction is sufficient)\n      constexpr int kNeighbors[2][2] = {{1, 0}, {0, 1}};\n      \n      for (int n = 0; n < 2; ++ n) {\n        // Is the neighbor within the pattern?\n        Vec2i neighbor_position = position + Vec2i(kNeighbors[n][0], kNeighbors[n][1]);\n        \n        auto cit = corner_position_to_index.find(neighbor_position);\n        if (cit == corner_position_to_index.end()) {\n          continue;\n        }\n        int neighbor_index = cit->second;\n        \n        double ideal_distance = geometry.cell_length_in_meters;\n        double actual_distance =\n            (state->points[index] -\n            state->points[neighbor_index]).norm();\n        \n        scaling_log_sum += std::log(ideal_distance / actual_distance);\n        ++ scaling_count;\n      }\n    }\n  }\n  \n  double scaling_factor = std::exp(scaling_log_sum / scaling_count);\n  state->ScaleState(scaling_factor);\n}\n\n\nbool ResampleModel(\n    shared_ptr<CameraModel>& model_to_optimize,\n    SE3d* camera_tr_rig,\n    int calibration_min_x,\n    int calibration_min_y,\n    int calibration_max_x,\n    int calibration_max_y,\n    CameraModel::Type model_type,\n    int target_resolution_x,\n    int target_resolution_y) {\n  LOG(INFO) << \"Resampling model ...\";\n  \n  // Special case for resampling NoncentralGeneric --> NoncentralGeneric\n  if (model_to_optimize->type() == CameraModel::Type::NoncentralGeneric &&\n      model_type == CameraModel::Type::NoncentralGeneric) {\n    NoncentralGenericModel* ngb_model = dynamic_cast<NoncentralGenericModel*>(model_to_optimize.get());\n    Image<Vec3d> new_point_grid(target_resolution_x, target_resolution_y);\n    Image<Vec3d> new_direction_grid(target_resolution_x, target_resolution_y);\n    for (u32 y = 0; y < new_point_grid.height(); ++ y) {\n      for (u32 x = 0; x < new_point_grid.width(); ++ x) {\n        // Convert the grid point (in the new grid) to pixel-corner convention coordinates\n        Vec2d pixel = CentralGenericModel::GridPointToPixelCornerConv(\n            x, y,\n            calibration_min_x, calibration_min_y,\n            calibration_max_x, calibration_max_y,\n            new_direction_grid.width(), new_direction_grid.height());\n        \n        Vec2d old_grid_point = ngb_model->PixelCornerConvToGridPoint(pixel.x(), pixel.y());\n        old_grid_point = old_grid_point.cwiseMax(Vec2d(0, 0)).cwiseMin(Vec2d(ngb_model->point_grid().width() - 1.001, ngb_model->point_grid().height() - 1.001));\n        \n        // The result of InterpolateBilinear() will not fit perfectly, but\n        // should be fine as an initial state for optimization\n        new_point_grid(x, y) = ngb_model->point_grid().InterpolateBilinear<Vec3d>(Vec2d(\n            old_grid_point.x(),\n            old_grid_point.y()));\n        new_direction_grid(x, y) = ngb_model->direction_grid().InterpolateBilinear<Vec3d>(Vec2d(\n            old_grid_point.x(),\n            old_grid_point.y()));\n      }\n    }\n    NoncentralGenericModel* new_ngb_model = new NoncentralGenericModel(\n        target_resolution_x, target_resolution_y,\n        calibration_min_x, calibration_min_y,\n        calibration_max_x, calibration_max_y,\n        model_to_optimize->width(), model_to_optimize->height());\n    new_ngb_model->SetPointGrid(new_point_grid);\n    new_ngb_model->SetDirectionGrid(new_direction_grid);\n    model_to_optimize.reset(new_ngb_model);\n    return true;\n  }\n  \n  if (model_to_optimize->type() == CameraModel::Type::NoncentralGeneric) {\n    LOG(ERROR) << \"Camera model resampling with NoncentralGeneric as a source model type is not implemented for anything else than NoncentralGeneric as target type.\";\n    return false;\n  }\n  \n  // Create dense direction model from old camera\n  Image<Vec3d> dense_model(model_to_optimize->width(), model_to_optimize->height());\n  for (u32 y = 0; y < dense_model.height(); ++ y) {\n    for (u32 x = 0; x < dense_model.width(); ++ x) {\n      if (!model_to_optimize->Unproject(x + 0.5, y + 0.5, &dense_model(x, y))) {\n        dense_model(x, y) = Vec3d::Constant(numeric_limits<double>::quiet_NaN());\n      }\n    }\n  }\n  \n  // Fit new camera to the dense model\n  const int calibration_area_width = calibration_max_x - calibration_min_x + 1;\n  const int calibration_area_height = calibration_max_y - calibration_min_y + 1;\n  \n  // TODO: Try to avoid the need for a special case for each camera model here,\n  //       probably use AllocateCameraModel().\n  if (model_type == CameraModel::Type::CentralGeneric ||\n      model_type == CameraModel::Type::NoncentralGeneric) {\n    CentralGenericModel* new_cgbsp_model = new CentralGenericModel(\n        target_resolution_x, target_resolution_y,\n        calibration_min_x, calibration_min_y,\n        calibration_max_x, calibration_max_y,\n        model_to_optimize->width(), model_to_optimize->height());\n    constexpr int kMaxXSamplesForFitting = 300;\n    constexpr int kMaxYSamplesForFitting = 300;\n    int subsample_step = std::max<int>(1, std::min(std::round(calibration_area_width / kMaxXSamplesForFitting),\n                                                   std::round(calibration_area_height / kMaxYSamplesForFitting)));\n    bool success = new_cgbsp_model->FitToDenseModel(dense_model, subsample_step, 3);\n    if (success) {\n      if (model_type == CameraModel::Type::NoncentralGeneric) {\n        NoncentralGenericModel* new_ngbsp_model = new NoncentralGenericModel(\n            target_resolution_x, target_resolution_y,\n            calibration_min_x, calibration_min_y,\n            calibration_max_x, calibration_max_y,\n            model_to_optimize->width(), model_to_optimize->height());\n        new_ngbsp_model->InitializeFromCentralGenericModel(*new_cgbsp_model);\n        delete new_cgbsp_model;\n        model_to_optimize.reset(new_ngbsp_model);\n      } else {\n        model_to_optimize.reset(new_cgbsp_model);\n      }\n    }\n    return success;\n  } else if (model_type == CameraModel::Type::CentralRadial) {\n    CentralRadialModel* new_cr_model = new CentralRadialModel(\n        model_to_optimize->width(), model_to_optimize->height(), kNumSplineParametersForRadialModel);\n    constexpr int kMaxXSamplesForFitting = 300;\n    constexpr int kMaxYSamplesForFitting = 300;\n    int subsample_step = std::max<int>(1, std::min(std::round(calibration_area_width / kMaxXSamplesForFitting),\n                                                   std::round(calibration_area_height / kMaxYSamplesForFitting)));\n    bool success = new_cr_model->FitToDenseModel(dense_model, subsample_step, 15);\n    if (success) {\n      model_to_optimize.reset(new_cr_model);\n    }\n    return success;\n  } else if (model_type == CameraModel::Type::CentralThinPrismFisheye) {\n    CentralThinPrismFisheyeModel* new_ctpf_model = new CentralThinPrismFisheyeModel(\n        model_to_optimize->width(), model_to_optimize->height(), true);\n    constexpr int kMaxXSamplesForFitting = 300;\n    constexpr int kMaxYSamplesForFitting = 300;\n    int subsample_step = std::max<int>(1, std::min(std::round(calibration_area_width / kMaxXSamplesForFitting),\n                                                   std::round(calibration_area_height / kMaxYSamplesForFitting)));\n    Mat3d parametric_r_dense = Mat3d::Identity();\n    bool success = new_ctpf_model->FitToDenseModel(dense_model, &parametric_r_dense, subsample_step, 3);\n    if (success) {\n      model_to_optimize.reset(new_ctpf_model);\n      \n      SE3d parametric_tr_dense;\n      parametric_tr_dense.setRotationMatrix(parametric_r_dense);\n      *camera_tr_rig = parametric_tr_dense * (*camera_tr_rig);\n    }\n    return success;\n  } else if (model_type == CameraModel::Type::CentralOpenCV) {\n    CentralOpenCVModel* new_cocv_model = new CentralOpenCVModel(\n        model_to_optimize->width(), model_to_optimize->height());\n    constexpr int kMaxXSamplesForFitting = 300;\n    constexpr int kMaxYSamplesForFitting = 300;\n    int subsample_step = std::max<int>(1, std::min(std::round(calibration_area_width / kMaxXSamplesForFitting),\n                                                   std::round(calibration_area_height / kMaxYSamplesForFitting)));\n    Mat3d parametric_r_dense = Mat3d::Identity();\n    bool success = new_cocv_model->FitToDenseModel(dense_model, &parametric_r_dense, subsample_step, 3);\n    if (success) {\n      model_to_optimize.reset(new_cocv_model);\n      \n      SE3d parametric_tr_dense;\n      parametric_tr_dense.setRotationMatrix(parametric_r_dense);\n      *camera_tr_rig = parametric_tr_dense * (*camera_tr_rig);\n    }\n    return success;\n  } else {\n    LOG(ERROR) << \"Resampling to this target model type is not implemented yet.\";\n    return false;\n  }\n}\n\n\n/// Computes the parameter grid resolution for the model's calibrated image area,\n/// depending on the desired approximate number of pixels per cell, and the\n/// number of cells on each side that should be outside the image area. For\n/// example, for B-Spline interpolation, there should be one more cell on each\n/// side to provide a sufficient context size for interpolation (unless using\n/// clamped access to the parameters).\nvoid ComputeGridResolution(\n    int calibration_area_width,\n    int calibration_area_height,\n    int exterior_cells_per_side,\n    int approx_pixels_per_cell,\n    int* resolution_x,\n    int* resolution_y) {\n  *resolution_x = calibration_area_width / approx_pixels_per_cell + 0.5f + 2 * exterior_cells_per_side;\n  *resolution_y = calibration_area_height / approx_pixels_per_cell + 0.5f + 2 * exterior_cells_per_side;\n}\n\nvoid ComputeGridResolution(\n    const CameraModel& model,\n    int approx_pixels_per_cell,\n    int* resolution_x,\n    int* resolution_y) {\n  int calibration_area_width = model.calibration_max_x() - model.calibration_min_x() + 1;\n  int calibration_area_height = model.calibration_max_y() - model.calibration_min_y() + 1;\n  int exterior_cells_per_side = 0;\n  CameraModel::Type type = model.type();\n  IDENTIFY_CAMERA_MODEL_TYPE(type, exterior_cells_per_side = _type::exterior_cells_per_side();)\n  ComputeGridResolution(\n      calibration_area_width,\n      calibration_area_height,\n      exterior_cells_per_side,\n      approx_pixels_per_cell,\n      resolution_x,\n      resolution_y);\n}\n\n\nvoid ResampleModelsIfNecessary(\n    Dataset* dataset,\n    BAState* state,\n    CameraModel::Type model_type,\n    int approx_pixels_per_cell) {\n  for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n    shared_ptr<CameraModel>& model = state->intrinsics[camera_index];\n    \n    int loaded_grid_resolution_x, loaded_grid_resolution_y;\n    bool have_grid = model->GetGridResolution(&loaded_grid_resolution_x, &loaded_grid_resolution_y);\n    if (have_grid) {\n      LOG(INFO) << \"Grid resolution loaded from file: \" << loaded_grid_resolution_x << \" x \" << loaded_grid_resolution_y;\n    }\n    \n    int desired_grid_resolution_x, desired_grid_resolution_y;\n    ComputeGridResolution(\n        *model,\n        approx_pixels_per_cell,\n        &desired_grid_resolution_x,\n        &desired_grid_resolution_y);\n    LOG(INFO) << \"Choosing grid resolution: \" << desired_grid_resolution_x << \" x \" << desired_grid_resolution_y;\n    \n    // Re-sample in case the loaded grid resolution differs from the desired one,\n    // or the loaded model type differs from the desired one.\n    if ((have_grid && (desired_grid_resolution_x != loaded_grid_resolution_x ||\n                       desired_grid_resolution_y != loaded_grid_resolution_y)) ||\n        model->type() != model_type) {\n      ResampleModel(\n          model,\n          &state->camera_tr_rig[camera_index],\n          model->calibration_min_x(), model->calibration_min_y(),\n          model->calibration_max_x(), model->calibration_max_y(),\n          model_type,\n          desired_grid_resolution_x, desired_grid_resolution_y);\n    }\n  }\n}\n\n\n/// Given the grid resolution on the full-sized level 0, computes the grid\n/// resolution for a smaller pyramid level.\n// TODO: What is a good upsampling factor?\nvoid CalcGridResolutionForLevel(int pyramid_level, int full_resolution_x, int full_resolution_y, int* x, int* y) {\n  *x = static_cast<int>(full_resolution_x * pow(1.333, -pyramid_level) + 0.5f);\n  *y = static_cast<int>(full_resolution_y * pow(1.333, -pyramid_level) + 0.5f);\n};\n\n\nvoid ComputeIntegerBoundingRectForFeatures(\n    Dataset* dataset,\n    int camera_index,\n    const vector<bool>& image_used,\n    int& calibration_min_x,\n    int& calibration_min_y,\n    int& calibration_max_x,\n    int& calibration_max_y) {\n  calibration_min_x = numeric_limits<int>::max();\n  calibration_min_y = numeric_limits<int>::max();\n  calibration_max_x = 0;\n  calibration_max_y = 0;\n  \n  for (int i = 0; i < dataset->ImagesetCount(); ++ i) {\n    if (!image_used[i]) {\n      continue;\n    }\n    \n    vector<PointFeature>& matches = dataset->GetImageset(i)->FeaturesOfCamera(camera_index);\n    for (PointFeature& feature : matches) {\n      calibration_min_x = std::min(calibration_min_x, static_cast<int>(feature.xy.x()));\n      calibration_min_y = std::min(calibration_min_y, static_cast<int>(feature.xy.y()));\n      calibration_max_x = std::max(calibration_max_x, static_cast<int>(feature.xy.x()));\n      calibration_max_y = std::max(calibration_max_y, static_cast<int>(feature.xy.y()));\n    }\n  }\n}\n\n\ntemplate <typename ModelT>\nCameraModel* AllocateCameraModel(\n    Dataset* dataset,\n    int camera_index,\n    const vector<bool>& image_used,\n    int approx_pixels_per_cell,\n    int num_pyramid_levels) {\n  // Determine bounding rectangle of feature matches. The calibration will be\n  // constrained to this rectangle to avoid mostly-unconstrained variables.\n  int calibration_min_x, calibration_min_y;\n  int calibration_max_x, calibration_max_y;\n  ComputeIntegerBoundingRectForFeatures(\n      dataset, camera_index, image_used,\n      calibration_min_x, calibration_min_y,\n      calibration_max_x, calibration_max_y);\n  \n  LOG(INFO) << \"Area that will be calibrated for camera \" << camera_index\n            << \": (\" << calibration_min_x << \", \" << calibration_min_y\n            << \") to (\" << calibration_max_x << \", \" << calibration_max_y << \")\";\n  \n  int calibration_area_width = calibration_max_x - calibration_min_x + 1;\n  int calibration_area_height = calibration_max_y - calibration_min_y + 1;\n  \n  // Fit the final model to the initialization.\n  int camera_width = dataset->GetImageSize(camera_index).x();\n  int camera_height = dataset->GetImageSize(camera_index).y();\n  \n  int grid_resolution_x, grid_resolution_y;\n  ComputeGridResolution(\n      calibration_area_width,\n      calibration_area_height,\n      ModelT::exterior_cells_per_side(),\n      approx_pixels_per_cell,\n      &grid_resolution_x,\n      &grid_resolution_y);\n  LOG(INFO) << \"Choosing grid resolution (for highest pyramid level): \" << grid_resolution_x << \" x \" << grid_resolution_y;\n  \n  \n  int first_resolution_x;\n  int first_resolution_y;\n  CalcGridResolutionForLevel(num_pyramid_levels - 1, grid_resolution_x, grid_resolution_y, &first_resolution_x, &first_resolution_y);\n  \n  return new ModelT(\n      first_resolution_x, first_resolution_y,\n      calibration_min_x, calibration_min_y,\n      calibration_max_x, calibration_max_y,\n      camera_width, camera_height);\n}\n\ntemplate <>\nCameraModel* AllocateCameraModel<CentralRadialModel>(\n    Dataset* dataset,\n    int camera_index,\n    const vector<bool>& /*image_used*/,\n    int /*approx_pixels_per_cell*/,\n    int /*num_pyramid_levels*/) {\n  return new CentralRadialModel(\n      dataset->GetImageSize(camera_index).x(),\n      dataset->GetImageSize(camera_index).y(),\n      kNumSplineParametersForRadialModel);\n}\n\ntemplate <>\nCameraModel* AllocateCameraModel<CentralThinPrismFisheyeModel>(\n    Dataset* dataset,\n    int camera_index,\n    const vector<bool>& /*image_used*/,\n    int /*approx_pixels_per_cell*/,\n    int /*num_pyramid_levels*/) {\n  // TODO: Make use_equidistant_projection configurable?\n  return new CentralThinPrismFisheyeModel(\n      dataset->GetImageSize(camera_index).x(),\n      dataset->GetImageSize(camera_index).y(),\n      /*use_equidistant_projection*/ true);\n}\n\ntemplate <>\nCameraModel* AllocateCameraModel<CentralOpenCVModel>(\n    Dataset* dataset,\n    int camera_index,\n    const vector<bool>& /*image_used*/,\n    int /*approx_pixels_per_cell*/,\n    int /*num_pyramid_levels*/) {\n  return new CentralOpenCVModel(\n      dataset->GetImageSize(camera_index).x(),\n      dataset->GetImageSize(camera_index).y());\n}\n\n\ntemplate <typename ModelT>\nbool FitCameraModelToDenseInitialization(\n    int camera_index,\n    const Image<Vec3d>& dense_model,\n    ModelT* model,\n    CalibrationWindow* calibration_window,\n    bool step_by_step) {\n  constexpr int kMaxXSamplesForFitting = 300;\n  constexpr int kMaxYSamplesForFitting = 300;\n  int calibration_area_width = model->calibration_max_x() - model->calibration_min_x() + 1;\n  int calibration_area_height = model->calibration_max_y() - model->calibration_min_y() + 1;\n  int subsample_step = std::max<int>(1, std::min(std::round(calibration_area_width / kMaxXSamplesForFitting),\n                                                 std::round(calibration_area_height / kMaxYSamplesForFitting)));\n  LOG(INFO) << \"FitToDenseModel() ...\";\n  if (!model->FitToDenseModel(dense_model, subsample_step, 3)) {\n    LOG(INFO) << \"Calibration failed: Fitting the model to the dense calibration initialization failed.\";\n    return false;\n  }\n  \n  if (calibration_window) {\n    Image<Vec3u8> visualization;\n    VisualizeModelDirections(*model, &visualization);\n    calibration_window->SetCurrentCameraIndex(camera_index);\n    calibration_window->UpdateObservationDirections(camera_index, visualization);\n    \n    if (step_by_step) {\n      LOG(INFO) << \"> Press Return to continue\";\n      GetKeyInput();\n    }\n  }\n  \n  return true;\n}\n\ntemplate <>\nbool FitCameraModelToDenseInitialization<NoncentralGenericModel>(\n    int /*camera_index*/,\n    const Image<Vec3d>& /*dense_model*/,\n    NoncentralGenericModel* /*model*/,\n    CalibrationWindow* /*calibration_window*/,\n    bool /*step_by_step*/) {\n  LOG(FATAL) << \"FitCameraModelToDenseInitialization is not supported for camera model type NoncentralGenericModel.\";\n  return false;\n}\n\n\nbool InitializeBAStateFromDenseInitialization(\n    Dataset* dataset,\n    const DenseInitialization& dense,\n    CameraModel::Type model_type,\n    int approx_pixels_per_cell,\n    int num_pyramid_levels,\n    bool initialize_intrinsics,\n    CalibrationWindow* calibration_window,\n    bool step_by_step,\n    BAState* state) {\n  // Initialize state->image_used by using all imagesets that are used by at least\n  // one camera in the dense initialization.\n  state->image_used.clear();\n  state->image_used.resize(dense.image_used[0].size(), false);\n  for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n    for (int imageset_index = 0; imageset_index < dense.image_used[camera_index].size(); ++ imageset_index) {\n      state->image_used[imageset_index] =\n          state->image_used[imageset_index] ||\n          dense.image_used[camera_index][imageset_index];\n    }\n  }\n  \n  // Initialize state->intrinsics by fitting to the dense observation directions.\n  if (initialize_intrinsics) {\n    state->intrinsics.resize(dataset->num_cameras());\n    for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n      CameraModel::Type final_type = model_type;\n      if (model_type == CameraModel::Type::NoncentralGeneric) {\n        final_type = model_type;\n        model_type = CameraModel::Type::CentralGeneric;\n      }\n      \n      IDENTIFY_CAMERA_MODEL_TYPE(model_type,\n        state->intrinsics[camera_index].reset(AllocateCameraModel<_model_type>(\n            dataset,\n            camera_index,\n            dense.image_used[camera_index],\n            approx_pixels_per_cell,\n            num_pyramid_levels));\n      );\n      \n      CameraModel& model = *state->intrinsics[camera_index];\n      IDENTIFY_CAMERA_MODEL(model,\n        if (!FitCameraModelToDenseInitialization<_model_type>(\n            camera_index,\n            dense.observation_directions[camera_index],\n            &_model,\n            calibration_window,\n            step_by_step)) {\n          return false;\n        }\n      );\n      \n      if (final_type != model_type) {\n        if (final_type == CameraModel::Type::NoncentralGeneric &&\n            model_type == CameraModel::Type::CentralGeneric) {\n          LOG(INFO) << \"NoncentralGenericModel::InitializeFromCentralGenericModel() ...\";\n          NoncentralGenericModel* noncentral_model = new NoncentralGenericModel();\n          noncentral_model->InitializeFromCentralGenericModel(*dynamic_cast<CentralGenericModel*>(state->intrinsics[camera_index].get()));\n          state->intrinsics[camera_index].reset(noncentral_model);\n          model_type = final_type;\n        } else {\n          LOG(FATAL) << \"This combination of initial and final model is not supported.\";\n        }\n      }\n    }\n  }\n  \n  // Initialize state->points to the known geometry.\n  state->points.clear();\n  state->feature_id_to_points_index.clear();\n  for (usize k = 0; k < dense.known_geometry_localized.size(); ++ k) {\n    if (!dense.known_geometry_localized[k]) {\n      continue;\n    }\n    \n    const auto& known_geometry = dataset->GetKnownGeometry(k);\n    const auto& feature_id_to_position = known_geometry.feature_id_to_position;\n    for (auto it = feature_id_to_position.cbegin(); it != feature_id_to_position.cend(); ++ it) {\n      Vec3f pattern_point = Vec3f(known_geometry.cell_length_in_meters * it->second.x(), known_geometry.cell_length_in_meters * it->second.y(), 0);\n      Vec3f global_point = dense.global_r_known_geometry[k] * pattern_point + dense.global_t_known_geometry[k];\n      state->points.emplace_back(global_point.cast<double>());\n      \n      state->feature_id_to_points_index[it->first] = state->points.size() - 1;\n    }\n  }\n  \n  // Initialize state->camera_tr_rig by averaging the poses in the dense\n  // initialization (which are determined individually, without rig constraints).\n  // TODO: Would the use of a RANSAC process help here?\n  constexpr int kRigCameraIndex = 0;\n  \n  vector<vector<SE3d>> camera_tr_rig(dataset->num_cameras());\n  for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n    for (int imageset_index = 0; imageset_index < dense.num_imagesets(); ++ imageset_index) {\n      if (dense.image_used[camera_index][imageset_index] && dense.image_used[kRigCameraIndex][imageset_index]) {\n        camera_tr_rig[camera_index].push_back(\n            dense.image_tr_global[camera_index][imageset_index] *\n            dense.image_tr_global[kRigCameraIndex][imageset_index].inverse());\n      }\n    }\n  }\n  \n  state->camera_tr_rig.resize(dataset->num_cameras());\n  for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n    vector<SE3d>& this_camera_tr_rig = camera_tr_rig[camera_index];\n    state->camera_tr_rig[camera_index] = AverageSE3(this_camera_tr_rig.size(), this_camera_tr_rig.data());\n  }\n  \n  // Initialize state->rig_tr_global by using the previously estimated\n  // camera_tr_rig transformations to let each image in an imageset vote for\n  // where the rig pose should be, and average the result.\n  // TODO: Would the use of a RANSAC process help here?\n  vector<SE3d> rig_tr_camera(state->camera_tr_rig.size());\n  for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n    rig_tr_camera[camera_index] = state->camera_tr_rig[camera_index].inverse();\n  }\n  \n  vector<SE3d> rig_tr_global;\n  state->rig_tr_global.resize(dense.num_imagesets());\n  for (int imageset_index = 0; imageset_index < dense.num_imagesets(); ++ imageset_index) {\n    rig_tr_global.clear();\n    \n    for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n      if (dense.image_used[camera_index][imageset_index]) {\n        rig_tr_global.push_back(\n            rig_tr_camera[camera_index] *\n            dense.image_tr_global[camera_index][imageset_index]\n        );\n      }\n    }\n    \n    state->rig_tr_global[imageset_index] = AverageSE3(rig_tr_global.size(), rig_tr_global.data());\n  }\n  \n  return true;\n}\n\n\nbool Calibrate(\n    Dataset* dataset,\n    const char* dense_initialization_path,\n    const char* state_initialization_base_path,\n    const char* outlier_visualization_path,\n    bool use_cuda,\n    SchurMode schur_mode,\n    int num_pyramid_levels,\n    CameraModel::Type model_type,\n    int approx_pixels_per_cell,\n    double regularization_weight,\n    float outlier_removal_factor,\n    bool localize_only,\n    CalibrationWindow* calibration_window,\n    BAState* state,\n    const char* dataset_output_path,\n    const char* state_output_path) {\n  constexpr bool step_by_step = false;\n  \n  if (dataset->ImagesetCount() < 3) {\n    LOG(INFO) << \"Calibration failed: too few input images given (\" << dataset->ImagesetCount()\n              << \"), calibration requires at least 3. (In practice, many more should be used.)\";\n    return false;\n  }\n  LOG(INFO) << \"Calibrate() starting ...\";\n  \n  \n  // --- Load or estimate the dense initialization (if needed) ---\n  DenseInitialization dense;\n  \n  if (!state_initialization_base_path) {  // skip if loading a state later\n    if (dense_initialization_path && boost::filesystem::exists(dense_initialization_path)) {\n      LOG(INFO) << \"Loading dense initialization from: \" << dense_initialization_path;\n      if (!LoadDenseInitialization(dense_initialization_path, &dense)) {\n        return false;\n      }\n    } else {\n      for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n        LOG(INFO) << \"Estimating the dense initialization for camera \" << camera_index << \" ...\";\n        if (calibration_window) {\n          calibration_window->SetCurrentCameraIndex(camera_index);\n        }\n        if (!dense.InitializeCamera(dataset, camera_index, /*localize_only*/ false, calibration_window, step_by_step)) {\n          return false;\n        }\n      }\n      \n      // Save the initialization such that the calibration process can be re-started\n      // from here.\n      if (dense_initialization_path) {\n        LOG(INFO) << \"Saving dense initialization to \" << dense_initialization_path;\n        if (!SaveDenseInitialization(dense_initialization_path, dense)) {\n          LOG(ERROR) << \"Could not save file: \" << dense_initialization_path;\n        }\n      }\n    }\n  }\n  \n  \n  // --- Load or estimate the initial optimization state ---\n  if (state_initialization_base_path) {\n    // Passing nullptr as dataset here since we are going to call ComputeFeatureIdToPointsIndex() later anyway.\n    if (!LoadBAState(state_initialization_base_path, state, nullptr)) {\n      return false;\n    }\n    if (localize_only) {\n      // The model type does not need to be given as input for localize_only,\n      // so get it from the loaded state.\n      model_type = state->intrinsics[0]->type();\n    }\n    \n    if (calibration_window) {\n      Image<Vec3u8> visualization;\n      for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n        VisualizeModelDirections(*state->intrinsics[camera_index], &visualization);\n        calibration_window->UpdateObservationDirections(camera_index, visualization);\n      }\n    }\n    \n    // Do the loaded models need to be resampled?\n    if (!localize_only) {\n      ResampleModelsIfNecessary(dataset, state, model_type, approx_pixels_per_cell);\n    }\n    \n    if (localize_only) {\n      // Convert the intrinsics to a dense model.\n      dense.observation_directions.resize(dataset->num_cameras());\n      for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n        if (!CreateObservationDirectionsImage(state->intrinsics[camera_index].get(), &dense.observation_directions[camera_index])) {\n          LOG(FATAL) << \"This camera model is not supported for localization.\";\n        }\n        if (calibration_window) {\n          calibration_window->SetCurrentCameraIndex(camera_index);\n        }\n        if (!dense.InitializeCamera(dataset, camera_index, /*localize_only*/ true, calibration_window, step_by_step)) {\n          return false;\n        }\n      }\n      \n      vector<shared_ptr<CameraModel>> original_intrinsics = state->intrinsics;\n      InitializeBAStateFromDenseInitialization(\n          dataset, dense, model_type, approx_pixels_per_cell, num_pyramid_levels, /*initialize_intrinsics*/ false,\n          calibration_window, step_by_step, state);\n      state->intrinsics = original_intrinsics;\n    }\n  } else {\n    InitializeBAStateFromDenseInitialization(\n        dataset, dense, model_type, approx_pixels_per_cell, num_pyramid_levels, /*initialize_intrinsics*/ true,\n        calibration_window, step_by_step, state);\n  }\n  \n  \n  // --- Use bundle adjustment (BA) to refine the state ---\n  \n  // Preparation for bundle adjustment: For each feature, store the index of the\n  // observed point in the points vector for fast lookup.\n  state->ComputeFeatureIdToPointsIndex(dataset);\n  \n  // Compute and store the grid resolutions on the final pyramid level.\n  vector<pair<int, int>> full_grid_resolutions(state->num_cameras());\n  for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n    int dummy, dummy2;\n    if (state->intrinsics[camera_index]->GetGridResolution(&dummy, &dummy2)) {\n      ComputeGridResolution(\n          *state->intrinsics[camera_index],\n          approx_pixels_per_cell,\n          &full_grid_resolutions[camera_index].first,\n          &full_grid_resolutions[camera_index].second);\n    }\n  }\n  \n  // Loop over bundle adjustment iterations for pyramid levels which are not full size\n  for (int pyramid_level = num_pyramid_levels - 1; pyramid_level > 0 && !localize_only; -- pyramid_level) {\n    LOG(INFO) << \"Bundle adjustment with pyramid level: \" << pyramid_level;\n    \n    // Print current grid resolutions and ensure that the camera models are\n    // actually set to these resolutions.\n    for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n      if (full_grid_resolutions[camera_index].first >= 0) {\n        int resolution_x, resolution_y;\n        CalcGridResolutionForLevel(pyramid_level, full_grid_resolutions[camera_index].first, full_grid_resolutions[camera_index].second, &resolution_x, &resolution_y);\n        int actual_resolution_x, actual_resolution_y;\n        CHECK(state->intrinsics[camera_index]->GetGridResolution(&actual_resolution_x, &actual_resolution_y)) << \"Camera model without GetGridResolution() used with pyramid scheme; set --num_pyramid_levels to 1\";\n        CHECK_EQ(resolution_x, actual_resolution_x);\n        CHECK_EQ(resolution_y, actual_resolution_y);\n        LOG(INFO) << \"Grid resolution on pyramid level \" << pyramid_level << \" for camera \" << camera_index << \": \" << resolution_x << \" x \" << resolution_y;\n      }\n    }\n    \n    // Loosen the cost reduction threshold after a few iterations. Reasoning: We\n    // want to make sure to do a few iterations, and want to continue doing them\n    // as long as they make reasonable progress, but don't need to solve the\n    // problem to an extreme precision as long as we are not on the final\n    // pyramid level yet.\n    RunBundleAdjustment(\n        use_cuda, schur_mode, /*max_iteration_count*/ 10, /*cost_reduction_threshold*/ 0.0001, dataset, state, regularization_weight,\n        localize_only, calibration_window, step_by_step, state_output_path);\n    RunBundleAdjustment(\n        use_cuda, schur_mode, /*max_iteration_count*/ 50, /*cost_reduction_threshold*/ 1, dataset, state, regularization_weight,\n        localize_only, calibration_window, step_by_step, state_output_path);\n    \n    // Upsample the camera models to the next level\n    for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n      CameraModel& model = *state->intrinsics[camera_index];\n      if (full_grid_resolutions[camera_index].first >= 0) {\n        int target_resolution_x, target_resolution_y;\n        CalcGridResolutionForLevel(pyramid_level - 1, full_grid_resolutions[camera_index].first, full_grid_resolutions[camera_index].second, &target_resolution_x, &target_resolution_y);\n        ResampleModel(\n            state->intrinsics[camera_index],\n            &state->camera_tr_rig[camera_index],\n            model.calibration_min_x(), model.calibration_min_y(),\n            model.calibration_max_x(), model.calibration_max_y(),\n            model_type,\n            target_resolution_x, target_resolution_y);\n      }\n    }\n  }\n  \n  // Print final grid resolutions\n  if (!localize_only) {\n    for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n      if (full_grid_resolutions[camera_index].first >= 0) {\n        LOG(INFO) << \"Bundle adjustment with final grid resolution for camera \" << camera_index << \": \"\n                  << full_grid_resolutions[camera_index].first << \" x \" << full_grid_resolutions[camera_index].second << \" ...\";\n      }\n    }\n  }\n  \n  // Run some BA iterations and delete outliers?\n  if (outlier_removal_factor > 0) {\n    // Do a few initial BA iterations before doing outlier rejection.\n    RunBundleAdjustment(\n        use_cuda, schur_mode, /*max_iteration_count*/ (num_pyramid_levels == 1) ? 100 : 10, /*cost_reduction_threshold*/ 0.0001, dataset, state, regularization_weight,\n        localize_only, calibration_window, step_by_step, state_output_path);\n    \n    for (int camera_index = 0; camera_index < dataset->num_cameras(); ++ camera_index) {\n      DeleteOutlierFeatures(camera_index, dataset, state, outlier_removal_factor, calibration_window, step_by_step, outlier_visualization_path);\n    }\n    \n    if (dataset_output_path) {\n      SaveDataset(dataset_output_path, *dataset);\n    }\n  }\n  \n  // Run main BA iterations.\n  RunBundleAdjustment(\n      use_cuda, schur_mode, /*max_iteration_count*/ 100, /*cost_reduction_threshold*/ 0.0001, dataset, state, regularization_weight,\n      localize_only, calibration_window, step_by_step, state_output_path);\n  \n  // If we used CUDA, which has a PCG-based BA implementation that is less accurate\n  // than the CPU implementation, finish up with some CPU iterations.\n  if (use_cuda) {\n    RunBundleAdjustment(\n        /*use_cuda*/ false, schur_mode, /*max_iteration_count*/ 10, /*cost_reduction_threshold*/ 0.0001, dataset, state, regularization_weight,\n        localize_only, calibration_window, step_by_step, state_output_path);\n  }\n  \n  // Scale the result as good as possible.\n  // If we only localize, we skip this. Otherwise, we would very likely *modify*\n  // non-central cameras here, unless we get a perfect 1 as scaling factor.\n  if (!localize_only) {\n    ScaleToMetric(dataset, state);\n  }\n  \n  return true;\n}\n\n\nvoid ExtractFeatures(\n    const vector<string>& image_directories,\n    FeatureDetectorTaggedPattern& detector,\n    Dataset* dataset,\n    CalibrationWindow* calibration_window) {\n  // Find all images in the first folder and ensure that they are also in the other folders.\n  // We assume that all folders have images with the same names in them since they should correspond.\n  vector<string> filenames;\n  unordered_set<string> filename_set;\n  boost::filesystem::directory_iterator it(image_directories[0]), end;\n  while (it != end) {\n    filenames.push_back(it->path().filename().string());\n    filename_set.insert(it->path().filename().string());\n    ++ it;\n  }\n  sort(filenames.begin(), filenames.end());\n  \n  for (int camera_index = 1; camera_index < image_directories.size(); ++ camera_index) {\n    int num_files = 0;\n    boost::filesystem::directory_iterator it(image_directories[camera_index]);\n    while (it != end) {\n      if (filename_set.count(it->path().filename().string()) == 0) {\n        LOG(ERROR) << \"The file \" << it->path().filename().string() << \" is in the image folder with index \" << camera_index << \", but not in the first image folder. The same number of files with matching filenames must be in each folder.\";\n        return;\n      }\n      ++ num_files;\n      ++ it;\n    }\n    if (num_files != filenames.size()) {\n      LOG(ERROR) << \"The number of files in the first image folder and in the image folder with index \" << camera_index << \" differs. The same number of files with matching filenames must be in each folder.\";\n      return;\n    }\n  }\n  \n  LOG(INFO) << \"Found \" << filenames.size() << \" images to extract features from.\";\n  \n  for (int camera_index = 0; camera_index < image_directories.size(); ++ camera_index) {\n    bool image_size_set = false;\n    for (int imageset_index = 0; imageset_index < filenames.size(); ++ imageset_index) {\n      const string& filename = filenames[imageset_index];\n      \n      string path = (boost::filesystem::path(image_directories[camera_index]) / filename).string();\n      Image<Vec3u8> image(path);\n      if (image.empty()) {\n        LOG(ERROR) << \"Cannot read image: \" << path << \". Aborting.\";\n        return;\n      }\n      \n      if (!image_size_set) {\n        dataset->SetImageSize(camera_index, image.size());\n      } else {\n        if (image.size() != dataset->GetImageSize(camera_index).cast<u32>()) {\n          LOG(ERROR) << \"The size of image \" << path << \" (\" << image.width() << \" x \" << image.height()\n                    << \") does not match that of the previous images (\" << dataset->GetImageSize(camera_index).x() << \" x \" << dataset->GetImageSize(camera_index).y() << \"). Aborting.\";\n          return;\n        }\n      }\n      \n      shared_ptr<Imageset> imageset;\n      if (camera_index == 0) {\n        imageset = dataset->NewImageset();\n      } else {\n        imageset = dataset->GetImageset(imageset_index);\n      }\n      imageset->SetFilename(filename);\n      vector<PointFeature>& features = imageset->FeaturesOfCamera(camera_index);\n      Image<Vec3u8> detection_visualization;\n      detector.DetectFeatures(image, &features, calibration_window ? &detection_visualization : nullptr);\n      \n      LOG(INFO) << path << \": \" << features.size() << \" features\";\n      \n      if (calibration_window) {\n        calibration_window->UpdateFeatureDetection(camera_index, detection_visualization);\n      }\n    }\n  }\n  \n  // Delete empty imagesets.\n  for (int imageset_index = static_cast<int>(filenames.size()) - 1; imageset_index >= 0; -- imageset_index) {\n    bool is_empty = true;\n    for (int camera_index = 0; camera_index < image_directories.size(); ++ camera_index) {\n      if (!dataset->GetImageset(imageset_index)->FeaturesOfCamera(camera_index).empty()) {\n        is_empty = false;\n        break;\n      }\n    }\n    \n    if (is_empty) {\n      dataset->DeleteImageset(imageset_index);\n    }\n  }\n}\n\n\nvoid CalibrateBatch(\n    const vector<string>& image_directories,\n    const vector<string>& dataset_files,\n    const string& dense_initialization_base_path,\n    const string& state_directory,\n    const string& dataset_output_path,\n    const string& state_output_directory,\n    const string& pruned_dataset_output_path,\n    const string& report_base_path,\n    FeatureDetectorTaggedPattern* detector,\n    int num_pyramid_levels,\n    CameraModel::Type model_type,\n    int cell_length_in_pixels,\n    double regularization_weight,\n    float outlier_removal_factor,\n    bool localize_only,\n    SchurMode schur_mode,\n    CalibrationWindow* calibration_window) {\n  Dataset dataset(image_directories.size());\n  \n  // Either create the dataset by extracting features from images, or by loading\n  // it from a file.\n  if (!image_directories.empty()) {\n    if (calibration_window) {\n      calibration_window->SetDataset(&dataset);\n    }\n    dataset.ExtractKnownGeometries(*detector);\n    ExtractFeatures(image_directories, *detector, &dataset, calibration_window);\n    \n    if (!dataset_output_path.empty()) {\n      SaveDataset(dataset_output_path.c_str(), dataset);\n    }\n  } else if (!dataset_files.empty()) {\n    LOG(INFO) << \"Dataset 0: \" << dataset_files[0];\n    if (!LoadDataset(dataset_files[0].c_str(), &dataset)) {\n      return;\n    }\n    for (int i = 1; i < dataset_files.size(); ++ i) {\n      Dataset additional_dataset(0);\n      LOG(INFO) << \"Dataset \" << i << \": \" << dataset_files[i];\n      if (!LoadDataset(dataset_files[i].c_str(), &additional_dataset)) {\n        return;\n      }\n      if (!dataset.Merge(additional_dataset)) {\n        return;\n      }\n    }\n    if (calibration_window) {\n      calibration_window->SetDataset(&dataset);\n    }\n  } else {\n    LOG(FATAL) << \"Either image_directories or dataset_files must be non-empty.\";\n  }\n  \n  // If no calibration output was requested, do not perform calibration.\n  if (state_output_directory.empty() &&\n      report_base_path.empty()) {\n    return;\n  }\n  \n  constexpr bool use_cuda = false;  // TODO: make configurable once the CUDA version works well\n  \n  BAState calibration;\n  if (!Calibrate(&dataset,\n                 dense_initialization_base_path.empty() ? nullptr : dense_initialization_base_path.c_str(),\n                 state_directory.empty() ? nullptr : state_directory.c_str(),\n                 report_base_path.empty() ? nullptr : report_base_path.c_str(),\n                 use_cuda,\n                 schur_mode,\n                 num_pyramid_levels,\n                 model_type,\n                 cell_length_in_pixels,\n                 regularization_weight,\n                 outlier_removal_factor,\n                 localize_only,\n                 calibration_window,\n                 &calibration,\n                 pruned_dataset_output_path.empty() ? nullptr : pruned_dataset_output_path.c_str(),\n                 state_output_directory.empty() ? nullptr : state_output_directory.c_str())) {\n    LOG(ERROR) << \"Calibration failed.\";\n    return;\n  }\n  \n  // Save the resulting calibration.\n  if (!state_output_directory.empty()) {\n    SaveBAState(state_output_directory.c_str(), calibration);\n  }\n  if (!pruned_dataset_output_path.empty()) {\n    SaveDataset(pruned_dataset_output_path.c_str(), dataset);\n  }\n  \n  // Create the calibration error report.\n  if (!report_base_path.empty()) {\n    CreateCalibrationReport(dataset, calibration, report_base_path);\n  }\n  \n  // // Fit parametric models to see how well they fit.\n  // CreateFittingVisualization(\n  //     calibration,\n  //     report_base_path,\n  //     /*max_visualization_extent*/ -1,\n  //     /*max_visualization_extent_pixels*/ -1);\n}\n\n\nint BatchCalibrationWithGUI(\n    int argc,\n    char** argv,\n    const vector<string>& image_directories,\n    const vector<string>& dataset_files,\n    const string& dense_initialization_base_path,\n    const string& state_directory,\n    const string& dataset_output_path,\n    const string& state_output_directory,\n    const string& pruned_dataset_output_path,\n    const string& report_base_path,\n    FeatureDetectorTaggedPattern* detector,\n    int num_pyramid_levels,\n    CameraModel::Type model_type,\n    int cell_length_in_pixels,\n    double regularization_weight,\n    float outlier_removal_factor,\n    bool localize_only,\n    SchurMode schur_mode,\n    bool show_visualizations) {\n  QApplication qapp(argc, argv);\n  qapp.setQuitOnLastWindowClosed(false);\n  \n  // Create the main window.\n  CalibrationWindow calibration_window(nullptr, Qt::WindowFlags());\n  if (show_visualizations) {\n    calibration_window.show();\n    calibration_window.raise();\n  }\n  \n  // Start the actual application in its own thread\n  thread calibrate_thread([&]{\n    CalibrateBatch(\n        image_directories,\n        dataset_files,\n        dense_initialization_base_path,\n        state_directory,\n        dataset_output_path,\n        state_output_directory,\n        pruned_dataset_output_path,\n        report_base_path,\n        detector,\n        num_pyramid_levels,\n        model_type,\n        cell_length_in_pixels,\n        regularization_weight,\n        outlier_removal_factor,\n        localize_only,\n        schur_mode,\n        show_visualizations ? &calibration_window : nullptr);\n    \n    RunInQtThreadBlocking([&]() {\n      if (calibration_window.isVisible()) {\n        qapp.setQuitOnLastWindowClosed(true);\n      } else {\n        qapp.quit();\n      }\n    });\n  });\n  \n  // Run the Qt event loop\n  qapp.exec();\n  \n  calibrate_thread.join();\n  return EXIT_SUCCESS;\n}\n\n}\n", "meta": {"hexsha": "6084304ddc99dfd78cd24eea7847d5751ed62994", "size": 57893, "ext": "cc", "lang": "C++", "max_stars_repo_path": "applications/camera_calibration/src/camera_calibration/calibration.cc", "max_stars_repo_name": "xiesc/camera_calibration", "max_stars_repo_head_hexsha": "8bd0071a1175894101f6dd204345297010756c09", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-03T13:25:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-03T13:25:49.000Z", "max_issues_repo_path": "applications/camera_calibration/src/camera_calibration/calibration.cc", "max_issues_repo_name": "xiesc/camera_calibration", "max_issues_repo_head_hexsha": "8bd0071a1175894101f6dd204345297010756c09", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/camera_calibration/src/camera_calibration/calibration.cc", "max_forks_repo_name": "xiesc/camera_calibration", "max_forks_repo_head_hexsha": "8bd0071a1175894101f6dd204345297010756c09", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T07:41:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T07:41:04.000Z", "avg_line_length": 41.1171875, "max_line_length": 240, "alphanum_fraction": 0.6894615929, "num_tokens": 13375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.021615334929176125, "lm_q1q2_score": 0.010217211662638047}}
{"text": "\n#include \"MirrorPlasma.hpp\"\n#include <cmath>\n#include <iostream>\n#include <boost/math/tools/roots.hpp>\n#include <functional>\n#include \"TransitionFunction.hpp\"\n#include \"BatchRunner.hpp\"\n\nMirrorPlasma::VacuumMirrorConfiguration::VacuumMirrorConfiguration(const std::map<std::string, double>& parameterMap, std::string FuelName, \n\tbool rThrust, tribool AHeating, tribool rDiagnostics, bool ambiPolPhi, bool collisions, bool includeCXLosses, std::string asciiOut, std::string netCdfOut)\n\t: AmbipolarPhi(ambiPolPhi), IncludeCXLosses(includeCXLosses), Collisional(collisions), OutputFile(asciiOut), NetcdfOutputFile(netCdfOut)\n{\n\tif( parameterMap.find(\"CentralCellField\") != parameterMap.end())\n\t\tCentralCellFieldStrength = parameterMap.at(\"CentralCellField\");\n\n\tif( parameterMap.find(\"MirrorRatio\") != parameterMap.end())\n\t\tMirrorRatio = parameterMap.at(\"MirrorRatio\");\n\telse if( parameterMap.find(\"ThroatField\") != parameterMap.end())\n\t\tMirrorRatio = parameterMap.at(\"ThroatField\")/CentralCellFieldStrength;\n\n\tif( parameterMap.find(\"PlasmaRadiusMin\") != parameterMap.end())\n\t\tAxialGapDistance = parameterMap.at(\"PlasmaRadiusMin\");\n\telse if( parameterMap.find(\"AxialGapDistance\") != parameterMap.end())\n\t\tAxialGapDistance = parameterMap.at(\"AxialGapDistance\");\n\n\tif( parameterMap.find(\"PlasmaColumnWidth\") != parameterMap.end())\n\t\tPlasmaColumnWidth = parameterMap.at(\"PlasmaColumnWidth\");\n\telse if(parameterMap.find(\"PlasmaRadiusMax\") != parameterMap.end())\n\t\tPlasmaColumnWidth = parameterMap.at(\"PlasmaRadiusMax\") - AxialGapDistance;\n\n\tif( parameterMap.find(\"Voltage\") != parameterMap.end())\n\t\tImposedVoltage = parameterMap.at(\"Voltage\");\n\n\tif( parameterMap.find(\"WallRadius\") != parameterMap.end())\n\t\tWallRadius = parameterMap.at(\"WallRadius\");\n\n\tif( parameterMap.find(\"PlasmaLength\") != parameterMap.end())\n\t\tPlasmaLength = parameterMap.at(\"PlasmaLength\");\n\n\tif( parameterMap.find(\"AuxiliaryHeating\") != parameterMap.end())\n\t\tAuxiliaryHeating = parameterMap.at(\"AuxiliaryHeating\");\n\n\tif( parameterMap.find(\"ParallelFudgeFactor\") != parameterMap.end())\n\t\tParallelFudgeFactor = parameterMap.at(\"ParallelFudgeFactor\");\n\n\tif( parameterMap.find(\"PerpFudgeFactor\") != parameterMap.end())\n\t\tPerpFudgeFactor = parameterMap.at(\"PerpFudgeFactor\");\n\n\tif( parameterMap.find(\"InitialTemp\") != parameterMap.end())\n\t\tInitialTemp = parameterMap.at(\"InitialTemp\");\n\n\tif( parameterMap.find(\"InitialMach\") != parameterMap.end())\n\t\tInitialMach = parameterMap.at(\"InitialMach\");\n\n\tif( parameterMap.find(\"SundialsAbsTol\") != parameterMap.end())\n\t\tSundialsAbsTol = parameterMap.at(\"SundialsAbsTol\");\n\n\tif( parameterMap.find(\"SundialsRelTol\") != parameterMap.end())\n\t\tSundialsRelTol = parameterMap.at(\"SundialsRelTol\");\n\n\tif( parameterMap.find(\"RateThreshold\") != parameterMap.end())\n\t\tRateThreshold = parameterMap.at(\"RateThreshold\");\n\n\tif ( FuelName == \"Hydrogen\" ) {\n\t\tIonSpecies.Mass   = 1.0;\n\t\tIonSpecies.Charge = 1.0;\n\t\tIonSpecies.Name   = \"Hydrogen\";\n\t\tAlphaHeating = false;\n\t\tReportNuclearDiagnostics = false;\n\t} else if ( FuelName == \"Deuterium\" ) {\n\t\tIonSpecies.Mass   = 2.0;\n\t\tIonSpecies.Charge = 1.0;\n\t\tIonSpecies.Name   = \"Deuterium\";\n\t\tAlphaHeating = false;\n\t\tReportNuclearDiagnostics = true;\n\t} else if ( FuelName == \"DT Fuel\" ) {\n\t\tIonSpecies.Mass   = 2.5;\n\t\tIonSpecies.Charge = 1.0;\n\t\tIonSpecies.Name   = \"Deuterium/Tritium Fuel\";\n\t\tAlphaHeating = true;\n\t\tReportNuclearDiagnostics = true;\n\t} else {\n\t\tstd::string ErrorMessage = \"[error] Fuel is not a recognized plasma species\";\n\t\tthrow std::invalid_argument( ErrorMessage );\n\t}\n\n\t// If specified in the config file these values override the defaults from the fuel\n\tif(AHeating == tribool::tru) AlphaHeating = true;\n\telse if(AHeating == tribool::fal) AlphaHeating = false;\n\n\tif(rDiagnostics == tribool::tru) ReportNuclearDiagnostics = true;\n\telse if(rDiagnostics == tribool::fal) ReportNuclearDiagnostics = false;\n}\n\n/* Replaced by Batch Runner \nMirrorPlasma::MirrorPlasma( toml::value const& plasmaConfig )\n\t: pVacuumConfig( std::make_shared<VacuumMirrorConfiguration>( plasmaConfig ) )\n{\n\tconst auto mirrorConfig = toml::find<toml::value>( plasmaConfig, \"configuration\" );\n\n\tdouble TiTe = toml::find_or<double>( mirrorConfig, \"IonToElectronTemperatureRatio\", 0.0 );\n\tif ( TiTe < 0.0 )\n\t{\n\t\tthrow std::invalid_argument( \"[error] Ion to Electron temperature ratio must be a positive number\" );\n\t}\n\n\t// Default to pure plasma\n\tZeff = toml::find_or<double>( mirrorConfig, \"Zeff\", 1.0 );\n\tif ( Zeff <= 0.0 ) {\n\t\tthrow std::invalid_argument( \"[error] Effective charge (Z_eff) must be positive!\" );\n\t}\n\n\ttry {\n\t\tElectronDensity = toml::find<double>( mirrorConfig, \"ElectronDensity\" );\n\t} catch ( std::out_of_range &e ) {\n\t\tthrow std::invalid_argument( \"[error] You must specify the electron density (ElectronDensity) in the [configuration] block\" );\n\t}\n\n\tif ( ElectronDensity <= 0.0 ) {\n\t\tthrow std::invalid_argument( \"[error] Electron density must be positive!\" );\n\t}\n\n\tIonDensity = ElectronDensity / pVacuumConfig->IonSpecies.Charge;\n\n\t// If the temperature is -1.0, that indicates we are in a Temperature Solve run\n\t// and the temperature will be solved for.\n\tif ( mirrorConfig.count( \"ElectronTemperature\" ) == 1 ) {\n\t\tElectronTemperature = toml::find<double>( mirrorConfig, \"ElectronTemperature\" );\n\t\tIonTemperature = ElectronTemperature * TiTe;\n\t} else if ( mirrorConfig.count( \"ElectronTemperature\" ) == 0 ) {\n\t\tElectronTemperature = -1.0;\n\t\tIonTemperature = -1.0;\n\t} else {\n\t\tthrow std::invalid_argument( \"[error] Electron Temperature specified more than once!\" );\n\t}\n\n\tif ( mirrorConfig.count( \"NeutralDensity\" ) == 1 ) {\n\t\tNeutralSource = 0;\n\t\tNeutralDensity = mirrorConfig.at( \"NeutralDensity\" ).as_floating();\n\t\tFixedNeutralDensity = true;\n\t} else {\n\t\tNeutralSource = 0;\n\t\tNeutralDensity = 0;\n\t\tFixedNeutralDensity = false;\n\t}\n\n\tif ( mirrorConfig.count( \"VoltageTrace\" ) == 1 ) {\n\t\tReadVoltageFile( mirrorConfig.at( \"VoltageTrace\" ).as_string() );\n\t\tisTimeDependent = true;\n\t\tSetTime( 0 );\n\t} else {\n\t\tisTimeDependent = false;\n\t\ttime = -1;\n\t}\n}\n*/\n\nMirrorPlasma::MirrorPlasma(std::shared_ptr< VacuumMirrorConfiguration > pVacuumConfig, std::map<std::string,double> parameterMap, std::string vTrace)\n\t: pVacuumConfig(pVacuumConfig)\n{\n\tif( parameterMap.find(\"Zeff\") != parameterMap.end())\n\t\tZeff = parameterMap.at(\"Zeff\");\n\telse Zeff = 1.0;\n\n\tif( parameterMap.find(\"ElectronDensity\") != parameterMap.end())\n\t\tElectronDensity = parameterMap.at(\"ElectronDensity\");\n\n\tIonDensity = ElectronDensity / pVacuumConfig->IonSpecies.Charge; \n\n\tdouble TiTe = 0.0;\n\tif( parameterMap.find(\"IonToElectronTemperatureRatio\") != parameterMap.end())\n\t\tTiTe = parameterMap.at(\"IonToElectronTemperatureRatio\");\n\n\n\tif( parameterMap.find(\"ElectronTemperature\") != parameterMap.end())\n\t{\n\t\tElectronTemperature = parameterMap.at(\"ElectronTemperature\");\n\t\tIonTemperature = ElectronTemperature < 0.0 ? -1.0 : ElectronTemperature * TiTe;\n\t}\n\t// Note if(...) only false if theres a bug. Batch runner will populate the value as -1.0 if its not found in the config file\n\telse\n\t{\n\t\tElectronTemperature = -1.0;\n\t\tIonTemperature = -1.0;\n\t}\n\n\t// Note: current excecution has NeutralSource always initially set to 0. If this changes work will have to be done in BatchRunner\n\tif( parameterMap.find(\"NeutralDensity\") != parameterMap.end())\n\t{\n\t\tNeutralDensity = parameterMap.at(\"NeutralDensity\");\n\t\tNeutralSource = 0.0;\n\t\tif ( NeutralDensity == 0.0 )\n\t\t\tFixedNeutralDensity = false;\n\t\telse\n\t\t\tFixedNeutralDensity = true;\n\t}\n\telse\n\t{\n\t\tNeutralDensity = 0.0;\n\t\tNeutralSource = 0.0;\n\t\tFixedNeutralDensity = false;\n\t}\n\n\tif(!vTrace.empty())\n\t{\n\t\tReadVoltageFile( vTrace );\n\t\tisTimeDependent = true;\n\t\tSetTime( 0 );\n\t}\n\telse\n\t{\n\t\tisTimeDependent = false;\n\t\ttime = -1;\n\t}\n}\n\n// From NRL Formulary p34\ndouble MirrorPlasma::LogLambdaElectron() const\n{\n\t// Convert to NRL Formulary Units\n\tdouble neNRL = ElectronDensity * 1e14; // We use 10^20 / m^3 = 10^14 / cm^3\n\tdouble TeNRL = ElectronTemperature * 1000; // We normalize to 1 keV they use 1 ev\n\t// For sensible values of the coulomb logarithm, the lambda_ee value in the NRL formulary\n\t// can be simplified to be the same as the middle lambda_ei value.\n\treturn 24.0 - 0.5*::log( neNRL ) + ::log( TeNRL );\n}\n\n// tau_ee\ndouble MirrorPlasma::ElectronCollisionTime() const\n{\n\tdouble PiThreeHalves = ::pow( M_PI, 1.5 ); // pi^(3/2)\n\tdouble TeThreeHalves = ::pow( ElectronTemperature * ReferenceTemperature, 1.5 );\n\tdouble ZIon = pVacuumConfig->IonSpecies.Charge;\n\treturn 12 * ::sqrt( ElectronMass ) * PiThreeHalves * TeThreeHalves * VacuumPermittivity * VacuumPermittivity / ( ::sqrt(2) * IonDensity * ReferenceDensity * ::pow( ZIon, 2 ) * ::pow( ElectronCharge, 4 ) * LogLambdaElectron() );\n}\n\n// NRL Formulary p34\ndouble MirrorPlasma::LogLambdaIon() const\n{\n\tdouble TiNRL = IonTemperature * 1000;\n\tdouble niNRL = IonDensity * 1e14;\n\tdouble ZIon = pVacuumConfig->IonSpecies.Charge;\n\treturn 23.0 - 0.5 * ::log( niNRL ) - 1.5 * ::log( ZIon * ZIon / TiNRL );\n}\n\ndouble MirrorPlasma::IonCollisionTime() const\n{\n\tdouble PiThreeHalves = ::pow( M_PI, 1.5 ); // pi^(3/2)\n\tdouble TiThreeHalves = ::pow( IonTemperature * ReferenceTemperature, 1.5 );\n\tdouble ZIon = pVacuumConfig->IonSpecies.Charge;\n\treturn 12 * ::sqrt( pVacuumConfig->IonSpecies.Mass * ProtonMass ) * PiThreeHalves * TiThreeHalves * VacuumPermittivity * VacuumPermittivity / ( ::sqrt(2) * IonDensity * ReferenceDensity * ::pow( ZIon * ElectronCharge, 4 ) * LogLambdaIon() );\n}\n\n// Leading order contribution to Phi_0 in O(M^2)\n// in units of T_e/e\ndouble MirrorPlasma::CentrifugalPotential() const\n{\n\tdouble tau = IonTemperature / ElectronTemperature;\n\treturn -( 0.5/tau ) * ( 1.0 - 1.0 / pVacuumConfig->MirrorRatio ) * MachNumber * MachNumber / ( pVacuumConfig->IonSpecies.Charge / tau + 1 );\n}\n\n// Chi_e Defined in units of T_e\ndouble MirrorPlasma::ParallelElectronPastukhovLossRate( double Chi_e ) const\n{\n\t// For consistency, the integral in Pastukhov's paper is 1.0, as the\n\t// entire theory is an expansion in M^2 >> 1\n\tdouble R = pVacuumConfig->MirrorRatio;\n\tdouble tau_ee = ElectronCollisionTime();\n\tdouble Sigma = 1.0 + Zeff; // Include collisions with ions and impurities as well as self-collisions\n\tdouble LossRate = ( M_2_SQRTPI / tau_ee ) * Sigma * ElectronDensity * ReferenceDensity * ( 1.0 / ::log( R * Sigma ) ) * ( ::exp( - Chi_e ) / Chi_e );\n\n\t// To prevent false solutions, apply strong losses if the Mach number drops\n\tif ( Chi_e < 1.0 ) {\n\t\tdouble BaseLossRate = ElectronDensity * ReferenceDensity * ( SoundSpeed() / pVacuumConfig->PlasmaLength );\n\t\tdouble smoothing = Transition( Chi_e, .5, 1.0 );\n\t\treturn smoothing*BaseLossRate + ( 1-smoothing )*LossRate;\n\t}\n\n\treturn LossRate*pVacuumConfig->ParallelFudgeFactor;\n}\n\ndouble MirrorPlasma::ParallelElectronParticleLoss() const\n{\n\tif ( pVacuumConfig->Collisional ) {\n\t\t// Particle loss from the mirror throat\n\t\t// given by the density at the throat and the sounds transit time\n\t\tdouble MirrorThroatDensity = IonDensity * ReferenceDensity * ::exp( CentrifugalPotential() );\n#ifdef DEBUG\n\t\tstd::cout << \"Electron parallel particle loss is \" << SoundSpeed() * MirrorThroatDensity << \"\\t\";\n\t\tstd::cout << \"Collisionless parallel losse would have been \" << ParallelElectronPastukhovLossRate( -AmbipolarPhi() );\n#endif\n\t\treturn SoundSpeed() * MirrorThroatDensity;\n\t}\n\tdouble Chi_e = -AmbipolarPhi(); // Ignore small electron mass correction\n\treturn ParallelElectronPastukhovLossRate( Chi_e );\n}\n\ndouble MirrorPlasma::ParallelElectronHeatLoss() const\n{\n\tif ( pVacuumConfig->Collisional )\n\t{\n\t\tdouble kappa_parallel = 3.16 * ElectronDensity * ElectronTemperature * ReferenceDensity * ReferenceTemperature * ElectronCollisionTime() / ( ElectronMass  );\n\t\tdouble L_parallel = pVacuumConfig->PlasmaLength;\n#ifdef DEBUG\n\t\tstd::cout << \"Electron parallel heat flux is \" << kappa_parallel * ElectronTemperature * ReferenceTemperature / ( L_parallel * L_parallel ) << std::endl;\n\t\tstd::cout << \"Collisionless parallel heat flux would have been \"\n\t\t          << ParallelElectronPastukhovLossRate( -AmbipolarPhi() ) * ( ElectronTemperature * ReferenceTemperature ) * (  1.0 - AmbipolarPhi() );\n#endif\n\t\treturn kappa_parallel * ElectronTemperature * ReferenceTemperature / ( L_parallel * L_parallel );\n\t}\n\n\t// Energy loss per particle is ~ e Phi + T_e\n\t// AmbipolarPhi = e Phi / T_e so loss is T_e * ( AmbipolarPhi + 1)\n\tdouble Chi_e = -AmbipolarPhi(); // Ignore small electron mass correction\n\t// Particle energy is roughly T_e + Chi_e (thermal + potential)\n\treturn ParallelElectronPastukhovLossRate( Chi_e ) * ( ElectronTemperature * ReferenceTemperature ) * ( Chi_e + 1.0 );\n}\n\n// Chi_i Defined in units of T_i\ndouble MirrorPlasma::ParallelIonPastukhovLossRate( double Chi_i ) const\n{\n\t// For consistency, the integral in Pastukhov's paper is 1.0, as the\n\t// entire theory is an expansion in M^2 >> 1\n\tdouble R = pVacuumConfig->MirrorRatio;\n\tdouble tau_ii = IonCollisionTime();\n\tdouble Sigma = 1.0;\n\tdouble LossRate = ( M_2_SQRTPI / tau_ii ) * Sigma * IonDensity * ReferenceDensity * ( 1.0 / ::log( R * Sigma ) ) * ( ::exp( - Chi_i ) / Chi_i );\n\n\t// To prevent false solutions, apply strong losses if the Mach number drops\n\tif ( Chi_i < 1.0 ) {\n\t\tdouble BaseLossRate = IonDensity * ReferenceDensity * ( SoundSpeed() / pVacuumConfig->PlasmaLength );\n\t\tdouble smoothing = Transition( Chi_i, .5, 1.0 );\n\t\treturn smoothing*BaseLossRate + ( 1-smoothing )*LossRate;\n\t}\n\n\treturn LossRate*pVacuumConfig->ParallelFudgeFactor;\n}\n\ndouble MirrorPlasma::Chi_i( double Phi ) const\n{\n\treturn pVacuumConfig->IonSpecies.Charge * Phi * ( ElectronTemperature/IonTemperature ) + 0.5 * MachNumber * MachNumber * ( 1.0 - 1.0/pVacuumConfig->MirrorRatio ) * ( ElectronTemperature / IonTemperature );\n}\n\ndouble MirrorPlasma::Chi_i() const\n{\n\treturn Chi_i( AmbipolarPhi() );\n}\n\ndouble MirrorPlasma::ParallelIonParticleLoss() const\n{\n\tif ( pVacuumConfig->Collisional ) {\n\t\t// Particle loss at the sound speed from the mirror throat\n\t\tdouble MirrorThroatDensity = IonDensity * ReferenceDensity * ::exp( CentrifugalPotential() );\n\t\treturn SoundSpeed() * MirrorThroatDensity;\n\t}\n\n\t// Electrostatic energy + centrifugal potential energy\n\treturn ParallelIonPastukhovLossRate( Chi_i() );\n}\n\ndouble MirrorPlasma::ParallelIonHeatLoss() const\n{\n\tif ( pVacuumConfig->Collisional ) {\n\t\t// Collisional parallel heat transport\n\t\tdouble IonMass = pVacuumConfig->IonSpecies.Mass * ProtonMass;\n\t\tdouble kappa_parallel = 3.9 * IonDensity * IonTemperature * ReferenceDensity * ReferenceTemperature * IonCollisionTime() / ( IonMass );\n\t\tdouble L_parallel = pVacuumConfig->PlasmaLength;\n\t\treturn kappa_parallel * IonTemperature * ReferenceTemperature / ( L_parallel * L_parallel );\n\t}\n\n\t// Energy loss per particle is ~ Chi_i + T_i\n\treturn ParallelIonPastukhovLossRate( Chi_i() ) * ( IonTemperature * ReferenceTemperature ) * ( ::fabs( Chi_i() )  + 1.0 );\n}\n/*\ndouble MirrorPlasma::ParallelCurrent( double Phi ) const\n{\n\tdouble Chi_i = pVacuumConfig->IonSpecies.Charge * Phi * ( ElectronTemperature/IonTemperature ) +\n\t\t0.5 * MachNumber * MachNumber * ( 1.0 - 1.0/pVacuumConfig->MirrorRatio ) * ( ElectronTemperature / IonTemperature );\n\tdouble Chi_e = -Phi; // Ignore small electron mass correction\n\n\t// If Alphas are included, they correspond to a (small) charge flow\n\tif ( pVacuumConfig->AlphaHeating )\n\t{\n\t\tdouble AlphaLossRate =  AlphaProductionRate() * PromptAlphaLossFraction();\n\t\treturn 2.0*AlphaLossRate + ParallelIonPastukhovLossRate( Chi_i )*pVacuumConfig->IonSpecies.Charge - ParallelElectronPastukhovLossRate( Chi_e );\n\t}\n\telse\n\t{\n\t\treturn ParallelIonPastukhovLossRate( Chi_i )*pVacuumConfig->IonSpecies.Charge - ParallelElectronPastukhovLossRate( Chi_e );\n\t}\n}\n*/\n\n// Sets Phi to the ambipolar Phi required such that ion loss = electron loss\ndouble MirrorPlasma::AmbipolarPhi() const\n{\n\tdouble AmbipolarPhi = CentrifugalPotential();\n\n\tif ( pVacuumConfig->Collisional )\n\t\treturn AmbipolarPhi;\n\n\tif ( pVacuumConfig->AmbipolarPhi ) {\n\t\t// Add correction.\n\t\tdouble Sigma = 1.0 + Zeff;\n\t\tdouble R = pVacuumConfig->MirrorRatio;\n\t\tdouble Correction = ::log( (  ElectronCollisionTime() / IonCollisionTime() ) * ( ::log( R*Sigma ) / ( Sigma * ::log( R ) ) ) );\n\n\t\t// This gives us a first-order guess for the Ambipolar potential. Now we solve j_|| = 0 to get the better answer.\n\t\t//\n\t\tauto ParallelCurrent = [ & ]( double Phi ) {\n\t\t\tdouble Chi_e = -Phi; // Ignore small electron mass correction\n\n\t\t\t// If Alphas are included, they correspond to a (small) charge flow\n\t\t\tif ( pVacuumConfig->AlphaHeating )\n\t\t\t{\n\t\t\t\tdouble AlphaLossRate =  AlphaProductionRate() * PromptAlphaLossFraction();\n\t\t\t\treturn 2.0*AlphaLossRate + ParallelIonPastukhovLossRate( Chi_i( Phi ) )*pVacuumConfig->IonSpecies.Charge - ParallelElectronPastukhovLossRate( Chi_e );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn ParallelIonPastukhovLossRate( Chi_i( Phi ) )*pVacuumConfig->IonSpecies.Charge - ParallelElectronPastukhovLossRate( Chi_e );\n\t\t\t}\n\t\t};\n\n\t\tboost::uintmax_t iters = 1000;\n\t\tboost::math::tools::eps_tolerance<double> tol( 11 ); // only bother getting part in 1024 accuracy\n\t\tauto [ Phi_l, Phi_u ] = boost::math::tools::bracket_and_solve_root( ParallelCurrent, AmbipolarPhi, 1.2, false, tol, iters );\n\t\tAmbipolarPhi = ( Phi_l + Phi_u )/2.0;\n\n\t\tif ( ::fabs( Phi_u - Phi_l )/2.0 > ::fabs( 0.01*AmbipolarPhi ) )\n\t\t{\n\t\t\tstd::cerr << \"Unable to find root of j_|| = 0, using approximation\" << std::endl;\n\t\t\treturn CentrifugalPotential() + Correction/2.0;\n\t\t}\n\t}\n\n\treturn AmbipolarPhi;\n}\n\ndouble MirrorPlasma::ParallelKineticEnergyLoss() const\n{\n\tdouble IonLossRate = ParallelIonParticleLoss();\n\tdouble EndExpansionRatio = 1.0; // If particles are hitting the wall at a radius larger than they are confined at, this increases momentum loss per particle\n\t// M^2 = u^2 / c_s^2 = m_i u^2 / T_e\n\tdouble KineticEnergyPerIon = 0.5 * ElectronTemperature * ReferenceTemperature * ( EndExpansionRatio * EndExpansionRatio ) *  MachNumber * MachNumber;\n\t// Convert to W/m^3 for consistency across loss rates\n\treturn IonLossRate * KineticEnergyPerIon;\n}\n\ndouble MirrorPlasma::ClassicalIonHeatLoss() const\n{\n\tdouble omega_ci = IonCyclotronFrequency();\n\tdouble IonMass = pVacuumConfig->IonSpecies.Mass * ProtonMass;\n\tdouble kappa_perp = 2.0 * IonDensity * IonTemperature * ReferenceTemperature * ReferenceDensity / ( IonMass * omega_ci * omega_ci * IonCollisionTime() );\n\tdouble L_T = ( pVacuumConfig->PlasmaColumnWidth / 2.0 );\n\t// Power density in W/m^3\n\treturn kappa_perp * IonTemperature * ReferenceTemperature /( L_T * L_T );\n}\n\ndouble MirrorPlasma::ClassicalElectronHeatLoss() const\n{\n\tdouble omega_ce = ElectronCyclotronFrequency();\n\tdouble kappa_perp = 4.66 * ElectronDensity * ElectronTemperature * ReferenceTemperature * ReferenceDensity / ( ElectronMass * omega_ce * omega_ce * ElectronCollisionTime() );\n\tdouble L_T = ( pVacuumConfig->PlasmaColumnWidth / 2.0 );\n\t// Power density in W/m^3\n\treturn kappa_perp * ElectronTemperature * ReferenceTemperature /( L_T * L_T );\n}\n\ndouble MirrorPlasma::ClassicalHeatLosses() const\n{\n\treturn ClassicalIonHeatLoss() + ClassicalElectronHeatLoss();\n}\n\ndouble MirrorPlasma::RadiationLosses() const\n{\n\treturn BremsstrahlungLosses() + CyclotronLosses();\n}\n\n// Formula from the NRL formulary page 58 and the definition of Z_eff:\n// n_e Z_eff = Sum_i n_i Z_i^2 (sum over all species that aren't electrons)\ndouble MirrorPlasma::BremsstrahlungLosses() const\n{\n\t// NRL formulary with reference values factored out\n\t// Return units are W/m^3\n\treturn 169 * ::sqrt( 1000 * ElectronTemperature ) * Zeff * ElectronDensity * ElectronDensity;\n}\n\n// Formula (34) on page 58 of the NRL formulary is the vacuum emission\n// we use the modified loss rate given in Tamor (1988) including a transparency factor\ndouble MirrorPlasma::CyclotronLosses() const\n{\n\t// NRL formulary with reference values factored out\n\t// Return units are W/m^3\n\tdouble B_central = pVacuumConfig->CentralCellFieldStrength; // in Tesla\n\tdouble P_vacuum = 6.21 * 1000 * ElectronDensity * ElectronTemperature * B_central * B_central;\n\n\t// Characteristic absorption length\n\t// lambda_0 = (Electron Inertial Lenght) / ( Plasma Frequency / Cyclotron Frequency )  ; Eq (4) of Tamor\n\t//\t\t\t\t= (5.31 * 10^-4 / (n_e20)^1/2) / ( 3.21 * (n_e20)^1/2 / B ) ; From NRL Formulary, converted to our units (Tesla for B & 10^20 /m^3 for n_e)\n\tdouble LambdaZero = ( 5.31e-4 / 3.21 ) * ( B_central / ElectronDensity );\n\tdouble WallReflectivity = 0.95;\n\tdouble OpticalThickness = ( pVacuumConfig->PlasmaColumnWidth / ( 1.0 - WallReflectivity ) ) / LambdaZero;\n\t// This is the Phi introduced by Trubnikov and later approximated by Tamor \n\tdouble TransparencyFactor = ::pow( ElectronTemperature, 1.5 ) / ( 200.0 * ::sqrt( OpticalThickness ) );\n\t// Moderate the vacuum emission by the transparency factor\n\treturn P_vacuum * TransparencyFactor;\n}\n\ndouble MirrorPlasma::Beta() const\n{\n\t// From Plasma Formulary, so convert to /cm^3 , eV, and Gauss\n\tdouble ne_Formulary = ElectronDensity * ReferenceDensity * 1e-6;\n\tdouble Te_Formulary = ElectronTemperature * 1e3;\n\tdouble ni_Formulary = IonDensity * ReferenceDensity * 1e-6;\n\tdouble Ti_Formulary = IonTemperature * 1e3;\n\tdouble MagField_Formulary = pVacuumConfig->CentralCellFieldStrength * 1e4;\n\treturn 4.03e-11 * ( ne_Formulary * Te_Formulary + ni_Formulary * Ti_Formulary ) / ( MagField_Formulary * MagField_Formulary );\n}\n\ndouble MirrorPlasma::DebyeLength() const\n{\n\t// l_debye^2 = epsilon_0 * (k_B T_e) / n_e * e^2\n\tdouble LambdaDebyeSquared = VacuumPermittivity * ( ElectronTemperature * ReferenceTemperature ) / ( ElectronDensity * ReferenceDensity * ElectronCharge * ElectronCharge );\n\treturn ::sqrt( LambdaDebyeSquared );\n}\n\n\ndouble MirrorPlasma::NuStar() const\n{\n\treturn pVacuumConfig->PlasmaLength / ( IonCollisionTime() * SoundSpeed() );\n}\n\n\ndouble MirrorPlasma::KineticEnergy() const\n{\n\tdouble IonMass = ProtonMass * pVacuumConfig->IonSpecies.Mass;\n\tdouble u = MachNumber * SoundSpeed();\n\treturn .5 * IonMass * IonDensity * ReferenceDensity * u * u * pVacuumConfig->PlasmaVolume();\n}\n\ndouble MirrorPlasma::ThermalEnergy() const\n{\n\treturn 1.5 * ( ElectronDensity * ElectronTemperature + IonDensity * IonTemperature ) * ReferenceDensity * ReferenceTemperature * pVacuumConfig->PlasmaVolume();\n}\n\n// Braginskii eta_1\ndouble MirrorPlasma::ClassicalViscosity() const\n{\n\tdouble omega_ci = IonCyclotronFrequency();\n\treturn pVacuumConfig->PerpFudgeFactor * ( 3.0 / 10.0 ) * ( IonDensity * ReferenceDensity * IonTemperature * ReferenceTemperature ) / ( omega_ci * omega_ci * IonCollisionTime() );\n}\n\n\n// Viscous heating = eta * u^2 / L_u^2\ndouble MirrorPlasma::ViscousHeating() const\n{\n\tdouble L_u = ( pVacuumConfig->PlasmaColumnWidth / 2.0 );\n\tdouble Velocity = MachNumber * SoundSpeed();\n\tdouble VelocityShear = Velocity / L_u;\n\n\treturn ClassicalViscosity() * VelocityShear * VelocityShear;\n}\n\ndouble MirrorPlasma::ViscousTorque() const\n{\n\tdouble L_u = ( pVacuumConfig->PlasmaColumnWidth / 2.0 );\n\tdouble Velocity = MachNumber * SoundSpeed();\n\n\treturn ClassicalViscosity() * ( Velocity * pVacuumConfig->PlasmaCentralRadius() / ( L_u * L_u ) );\n}\n\ndouble MirrorPlasma::ClassicalElectronParticleLosses() const\n{\n\tdouble omega_ce = ElectronCyclotronFrequency();\n\tdouble L_n = ( pVacuumConfig->PlasmaColumnWidth / 2.0 );\n\tdouble D = ElectronTemperature * ReferenceTemperature / ( ElectronMass * omega_ce * omega_ce * ElectronCollisionTime() );\n\treturn ( D / ( L_n * L_n ) ) * ElectronDensity * ReferenceDensity;\n}\n\ndouble MirrorPlasma::ClassicalIonParticleLosses() const\n{\n\t// just the pure plasma Ambipolar result\n\treturn ClassicalElectronParticleLosses();\n}\n\ndouble MirrorPlasma::AlfvenMachNumber() const\n{\n\t// v_A^2 = B^2 / mu_0 * n_i * m_i\n\t// c_s^2 = T_e / m_i\n\tdouble MassDensity = IonDensity * ReferenceDensity * pVacuumConfig->IonSpecies.Mass * ProtonMass;\n\tdouble AlfvenSpeed = pVacuumConfig->CentralCellFieldStrength / ::sqrt( PermeabilityOfFreeSpace * MassDensity );\n\n\treturn MachNumber * ( SoundSpeed() / AlfvenSpeed );\n}\n\ndouble MirrorPlasma::CollisionalTemperatureEquilibrationTime() const\n{\n\treturn ElectronCollisionTime()/( (3./pVacuumConfig->IonSpecies.Mass)*(ElectronMass/ProtonMass) );\n}\n\ndouble MirrorPlasma::IonToElectronHeatTransfer() const\n{\n\tdouble EnergyDensity = ( ElectronDensity * ReferenceDensity ) * ( IonTemperature - ElectronTemperature ) * ReferenceTemperature;\n\t// return EnergyDensity / ( 1e-6 ); // Start by ensuring equal temperatures ( force tau to be 1 µs )\n\treturn EnergyDensity / CollisionalTemperatureEquilibrationTime();\n}\n\ndouble MirrorPlasma::CXHeatLosses() const\n{\n\tdouble EnergyPerIon = IonTemperature * ReferenceTemperature;\n\treturn CXLossRate() * EnergyPerIon;\n}\n\ndouble MirrorPlasma::IonHeatLosses() const\n{\n\treturn ClassicalIonHeatLoss() + ParallelIonHeatLoss() + CXHeatLosses();\n}\n\ndouble MirrorPlasma::ElectronHeatLosses() const\n{\n\treturn ParallelElectronHeatLoss() + RadiationLosses();\n}\n\ndouble MirrorPlasma::IonHeating() const\n{\n\tdouble Heating = ViscousHeating();\n\n\treturn Heating - IonToElectronHeatTransfer();\n}\n\ndouble MirrorPlasma::ElectronHeating() const\n{\n\tdouble Heating = pVacuumConfig->AuxiliaryHeating * 1e6 / pVacuumConfig->PlasmaVolume(); // Auxiliary Heating stored as MW, heating is in W/m^3\n\tif ( pVacuumConfig->AlphaHeating ) {\n\t\t// 1e6 as we are using W/m^3 and the formulary was in MW/m^3\n\t\tHeating += AlphaHeating() * 1e6;\n\t}\n\t// std::cout << \"e-Heating comprises \" << Heating << \" of aux and \" << IonToElectronHeatTransfer() << \" transfer\" << std::endl;\n\treturn Heating + IonToElectronHeatTransfer();\n}\n\n\nvoid MirrorPlasma::SetMachFromVoltage()\n{\n\t// u = E x B / B^2\n\t// M = u/c_s ~ (V/aB)/cs\n\tMachNumber = pVacuumConfig->ImposedVoltage / ( pVacuumConfig->PlasmaColumnWidth * pVacuumConfig->CentralCellFieldStrength * SoundSpeed() );\n}\n\ndouble MirrorPlasma::AngularMomentumPerParticle() const\n{\n\treturn pVacuumConfig->IonSpecies.Mass * ProtonMass * SoundSpeed() * MachNumber * pVacuumConfig->PlasmaCentralRadius();\n}\n\ndouble MirrorPlasma::ParallelAngularMomentumLossRate() const\n{\n\tdouble IonLoss = ParallelIonParticleLoss();\n\treturn IonLoss * AngularMomentumPerParticle(); \n}\n\ndouble MirrorPlasma::CXMomentumLosses() const\n{\n\tdouble IonLoss = CXLossRate();\n\treturn IonLoss * AngularMomentumPerParticle();\n}\n\n// Momentum Equation is\n//\t\tI d omega / dt = <Viscous Torque> + <Parallel Angular Momentum Loss> + R J_R B_z\n//\n// Div(J) = 0 => R J_R = constant\n//\n// Current I_radial = 2 * pi * R * J_R * L_plasma\n//\ndouble MirrorPlasma::RadialCurrent() const\n{\n\tdouble Torque = -ViscousTorque();\n\tdouble ParallelLosses = -ParallelAngularMomentumLossRate();\n\tdouble CXLosses = -CXMomentumLosses();\n\t// Inertial term = m_i n_i R^2 d omega / dt ~= m_i n_i R^2 d  / dt ( E/ ( R*B) )\n\t//\t\t\t\t\t~= m_i n_i (R/B) * d/dt ( V / a )\n\tdouble Inertia;\n\tif ( isTimeDependent )\n\t\tInertia = pVacuumConfig->IonSpecies.Mass * ProtonMass * IonDensity * ( pVacuumConfig->PlasmaCentralRadius() / pVacuumConfig->CentralCellFieldStrength )\n\t\t            * VoltageFunction->prime( time );\n\telse\n\t\tInertia = 0.0;\n\n\t// R J_R = (<Torque> + <ParallelLosses> + <Inertia>)/B_z\n\t// I_R = 2*Pi*R*L*J_R\n\tdouble I_radial = 2.0 * M_PI * pVacuumConfig->PlasmaLength * ( Torque + ParallelLosses + Inertia + CXLosses ) / pVacuumConfig->CentralCellFieldStrength;\n\treturn I_radial;\n}\n\n// Thrust from ions leaving\n// assume parallel kinetic energy contains Chi_i\ndouble MirrorPlasma::ParallelIonThrust() const\n{\n\tdouble ParallelKineticEnergy = ( Chi_i() + 1.0 ) * IonTemperature * ReferenceTemperature;\n\tdouble ParallelMomentum = ::sqrt( 2.0  *  ParallelKineticEnergy * pVacuumConfig->IonSpecies.Mass * ProtonMass );\n\t// Only half the particle loss, as the Thrust diagnostics need each end separately.\n\treturn ParallelMomentum * ( ParallelIonParticleLoss() / 2.0 ) * pVacuumConfig->PlasmaVolume();\n}\n\n\nvoid MirrorPlasma::UpdateVoltage()\n{\n\tif ( !isTimeDependent )\n\t\treturn;\n\telse\n\t\tpVacuumConfig->ImposedVoltage = ( *VoltageFunction )( time );\n}\n\nvoid MirrorPlasma::SetTime( double new_time )\n{\n\ttime = new_time;\n\tUpdateVoltage();\n}\n", "meta": {"hexsha": "e179becbe553e774400892a3cbbd01940bfc51d4", "size": 27855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MirrorPlasma.cpp", "max_stars_repo_name": "MylesKelly/MCTrans", "max_stars_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "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": "MirrorPlasma.cpp", "max_issues_repo_name": "MylesKelly/MCTrans", "max_issues_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MirrorPlasma.cpp", "max_forks_repo_name": "MylesKelly/MCTrans", "max_forks_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_forks_repo_licenses": ["BSD-3-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.7413073713, "max_line_length": 242, "alphanum_fraction": 0.7309998205, "num_tokens": 7836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.021615334259521845, "lm_q1q2_score": 0.010217211346103535}}
{"text": "/*\n\nCopyright (c) 2005-2015, 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 ABSTRACTODEBASEDCELLCYCLEMODEL_HPP_\n#define ABSTRACTODEBASEDCELLCYCLEMODEL_HPP_\n\n#include <vector>\n\n#include \"ChasteSerialization.hpp\"\n#include \"ClassIsAbstract.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractCellCycleModel.hpp\"\n#include \"CellCycleModelOdeHandler.hpp\"\n#include \"SimulationTime.hpp\"\n\n/**\n * This class contains all the functionality shared by 'ODE-based' cell-cycle models,\n * where the duration of one or more cell cycle phases are evaluated 'on the fly'\n * as the cell ages, according to a system of ordinary differential equations (ODEs)\n * governing (for example) the concentrations of key intracellular proteins. To\n * determine when cell division should occur, one or more stopping conditions for\n * this ODE system may be specified.\n *\n * This class of cell-cycle models is distinct from 'simple' cell-cycle models, where\n * the duration of each cell cycle phase is determined when the cell-cycle model is\n * created.\n */\nclass AbstractOdeBasedCellCycleModel : public AbstractCellCycleModel, public CellCycleModelOdeHandler\n{\nprivate:\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the cell-cycle model and 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<AbstractCellCycleModel>(*this);\n        archive & boost::serialization::base_object<CellCycleModelOdeHandler>(*this);\n        archive & mDivideTime;\n        archive & mFinishedRunningOdes;\n        archive & mG2PhaseStartTime;\n    }\n\nprotected:\n\n    /** The time at which the cell should divide - Set this to DBL_MAX in constructor. */\n    double mDivideTime;\n\n    /** Whether the cell-cycle model is currently in a delay (not solving ODEs). */\n    bool mFinishedRunningOdes;\n\n    /** The start time for the G2 phase. */\n    double mG2PhaseStartTime;\n\npublic:\n\n    /**\n     * Creates an AbstractOdeBasedCellCycleModel, calls SetBirthTime on the\n     * AbstractCellCycleModel to make sure that can be set 'back in time' for\n     * cells which did not divide at the current time.\n     *\n     * @param lastTime  The birth time of the cell / last time model was evaluated (defaults to the current SimulationTime)\n     * @param pOdeSolver An optional pointer to a cell-cycle model ODE solver object (allows the use of different ODE solvers)\n     */\n    AbstractOdeBasedCellCycleModel(double lastTime = SimulationTime::Instance()->GetTime(),\n                                   boost::shared_ptr<AbstractCellCycleModelOdeSolver> pOdeSolver = boost::shared_ptr<AbstractCellCycleModelOdeSolver>());\n\n    /**\n     * Destructor.\n     */\n    virtual ~AbstractOdeBasedCellCycleModel();\n\n    /**\n     * Default UpdateCellCyclePhase() method for an ODE-based cell-cycle model.\n     * This method calls SolveOdeToTime() for G1 phase and adds time for the other phases.\n     *\n     * Can be overridden if they should do something more subtle.\n     */\n    virtual void UpdateCellCyclePhase();\n\n    /**\n     * Get the time at which the ODE stopping event occurred.\n     * Only called in those subclasses for which stopping events\n     * are defined.\n     *\n     * @return the time at which the ODE system reached its stopping event\n     */\n    double GetOdeStopTime();\n\n    /**\n     * This overrides the AbstractCellCycleModel::SetBirthTime(double birthTime)\n     * because an ODE based cell-cycle model has more to reset...\n     *\n     * @param birthTime the simulation time when the cell was born\n     */\n    void SetBirthTime(double birthTime);\n\n    /**\n     * @return the protein concentrations at the current time (useful for tests)\n     *\n     * NB: Will copy the vector - you can't use this to modify the concentrations.\n     */\n    std::vector<double> GetProteinConcentrations() const;\n\n    /**\n     * Sets the protein concentrations and time when the model was last evaluated - should only be called by tests\n     *\n     * @param lastTime the SimulationTime at which the protein concentrations apply\n     * @param proteinConcentrations a standard vector of doubles of protein concentrations\n     *\n     */\n    void SetProteinConcentrationsForTestsOnly(double lastTime, std::vector<double> proteinConcentrations);\n\n    /**\n     * For a naturally cycling model this does not need to be overridden in the\n     * subclasses. But most models should override this function and then\n     * call AbstractOdeBasedCellCycleModel::ResetForDivision() from inside their version.\n     */\n    virtual void ResetForDivision();\n\n    /**\n     * Set mFinishedRunningOdes. Used in CreateCellCycleModel().\n     *\n     * @param finishedRunningOdes the new value of mFinishedRunningOdes\n     */\n    void SetFinishedRunningOdes(bool finishedRunningOdes);\n\n    /**\n     * Set mDivideTime.\n     *\n     * @param divideTime the new value of mDivideTime\n     */\n    void SetDivideTime(double divideTime);\n\n    /**\n     * Set mG2PhaseStartTime. Used in CreateCellCycleModel().\n     *\n     * @param g2PhaseStartTime the new value of mG2PhaseStartTime\n     */\n    void SetG2PhaseStartTime(double g2PhaseStartTime);\n\n    /**\n     * Outputs cell cycle model parameters to file.\n     *\n     * @param rParamsFile the file stream to which the parameters are output\n     */\n    virtual void OutputCellCycleModelParameters(out_stream& rParamsFile);\n};\n\nCLASS_IS_ABSTRACT(AbstractOdeBasedCellCycleModel)\n\n#endif /*ABSTRACTODEBASEDCELLCYCLEMODEL_HPP_*/\n", "meta": {"hexsha": "86b053571a9877df91223368c41b723449e6166a", "size": 7318, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/population/cell/cycle/AbstractOdeBasedCellCycleModel.hpp", "max_stars_repo_name": "ktunya/ChasteMod", "max_stars_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "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/cell/cycle/AbstractOdeBasedCellCycleModel.hpp", "max_issues_repo_name": "ktunya/ChasteMod", "max_issues_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_issues_repo_licenses": ["Apache-2.0"], "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/cell/cycle/AbstractOdeBasedCellCycleModel.hpp", "max_forks_repo_name": "ktunya/ChasteMod", "max_forks_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "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.1145833333, "max_line_length": 153, "alphanum_fraction": 0.7327138562, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.023330766516555388, "lm_q1q2_score": 0.010214758175574224}}
{"text": "#include <string>\n#include <vector>\n#include <memory>\n#include <map>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n\n#include <boost/filesystem.hpp>\n#include <yaml-cpp/yaml.h>\n\n#include \"cantera/base/stringUtils.h\"\n#include \"cantera/base/ct_defs.h\"\n#include \"cantera/IdealGasMix.h\"\n#include \"cantera/InterfaceLatInt.h\"\n#include \"cantera/Interface.h\"\n#include \"cantera/thermo/SurfLatIntPhase.h\"\n#include \"cantera/thermo/SurfPhase.h\"\n#include \"cantera/thermo/LateralInteraction.h\"\n#include \"cantera/thermo/StoichSubstance.h\"\n#include \"cantera/thermo/ThermoPhase.h\"\n#include \"cantera/zeroD/Reactor.h\"\n#include \"cantera/zeroD/Wall.h\"\n#include \"IdealGasTRampReactor.h\"\n#include \"cantera/zeroD/ReactorNet.h\"\n#include \"cantera/zeroD/Reservoir.h\"\n#include \"cantera/zeroD/ReactorSurface.h\"\n#include \"cantera/zeroD/flowControllers.h\"\n\n#include \"util.h\"\n#include \"run_reactor.h\"\n#include \"omkmexceptions.h\"\n#include \"io.h\"\n#include \"ReactorNetHybrid.h\"\n\n\nnamespace OpenMKM \n{\n\nusing namespace std;\nusing namespace Cantera;\nnamespace fs = boost::filesystem;\n\n//TODO: Add nSurfaces() function to Reactor/ReactorBase to eliminate the need\n// to pass surfaces argument\n/*\nvoid print_rctr_state(double z, Reactor* rctr, vector<SurfPhase*> surfaces, \n                      ofstream& gas_mole_out, ofstream& gas_mass_out, \n                      ofstream& gas_msdot_out, ofstream& surf_cov_out,\n                      ofstream& state_var_out)\n*/\n\n\nvoid run_0d_reactor(ReactorParser& rctr_parser,\n                    shared_ptr<IdealGasMix> gas, \n                    vector<shared_ptr<InterfaceInteractions>> surfaces,\n                    ofstream& gen_info_out) \n{\n    //Define the reactor based on the input file\n    auto rctr = make_shared<IdealGasTRampReactor>();\n    rctr->insert(*gas);\n    gen_info_out << \"Reactor density \" << rctr->density() << endl;\n\n    // Read the reactor dimensions\n    double rctr_vol = rctr_parser.getVolume();\n    auto rctr_type = rctr_parser.getReactorType();\n    size_t rctr_nos = 1;\n    if (rctr_type == PFR_0D) { // Modify rctr_nos only for PFR_0D\n        rctr_nos = rctr_parser.getNodes();\n        if (rctr_nos == 1) { // Raise warning to increase cstr number\n            cout << \"Number of nodes in 0d PFR simulation is 1. \\n \" \n                 << \"Suggestion: Input 'nodes' parameter if not given already or \" \n                 << \"increase its value to greater than 1.\";\n        }\n        rctr_vol /= rctr_nos;\n    }\n\n    rctr->setInitialVolume(rctr_vol);\n    vector<shared_ptr<ReactorSurface>> cat_surfs;\n    vector<SurfPhase*> surf_phases;\n\n    double cat_abyv = rctr_parser.getCatalystAbyV();\n    cout << \"Catalyst loading (Area/Volume): \" << cat_abyv << endl;\n\n    if (cat_abyv == 0.0 && surfaces.size() > 0) {\n        cout << \"WARNING!!!\\nCatalyst loading is zero.\\n\"\n             << \"Ignoring the surface phases given in the YAML file\\n\"\n             << \"--------------\\n\";\n    }\n\n    if (cat_abyv != 0.0) {\n        auto cat_area = cat_abyv * rctr_vol;\n        size_t surf_spec_no = 0;\n        for (const auto surf : surfaces) {\n            surf_spec_no += surf->nSpecies();\n            auto cat_surf = make_shared<ReactorSurface>(); \n            cat_surf->setKinetics(surf.get());\n            surf_phases.push_back(dynamic_cast<SurfPhase*> (surf.get()));\n            vector<double> coverages(surf->nSpecies());\n            surf->getCoverages(coverages.data());\n            cat_surf->setCoverages(coverages.data());\n            cat_surf->setArea(cat_area);\n            cat_surfs.push_back(cat_surf);\n            rctr->addSurface(cat_surf.get());\n        }\n    }\n    cout << \"# of surface phases considered: \" << cat_surfs.size() << endl;\n\n    // Only CSTR and PFR_0D require valves, controllers and \n    // reservoirs to facilitate mass transfer. Attach them to reactor\n\n    // The following are nominally defined in the case of BATCH reactor also \n    // to prevent crashing the program\n    auto in_rsrv = make_shared<Reservoir>();\n    auto exhst = make_shared<Reservoir>();\n    auto inlet_mfc = make_shared<MassFlowController>();\n    auto outlet = make_shared<PressureController>();\n    \n    // Set the output type\n    OutputFormat data_format = rctr_parser.printFormat();\n    setOutputFormat(data_format);\n\n    if (rctr_type != BATCH) {\n        bool fr_defined = rctr_parser.FlowRateDefined();\n        bool mfr_defined = rctr_parser.MassFlowRateDefined();\n        bool rt_defined = rctr_parser.ResidenceTimeDefined();\n        int no_var_defined = fr_defined + mfr_defined + rt_defined;\n        if (no_var_defined > 1) {\n            cout << \"WARNING: Define only one of 'flow_rate', 'mass_flow_rate', \"\n                 << \"'residence_time'. Only one of the variables is used \" \n                 << \"in the order shown above\" << endl;\n        } else if (!no_var_defined) {\n            cout << \"WARNING: Define one of 'flow_rate', 'mass_flow_rate', \"\n                 << \"'residence_time' within inlet_gas. Using 0 for flow \"\n                 << \"rate, which is equivalent to simulating batch reactor.\" << endl;\n        }\n        double mfr{0};\n        if (fr_defined) {\n            auto flow_rate = rctr_parser.getFlowRate();\n            mfr = rctr->mass() * flow_rate / rctr_vol;\n        }\n        else if (mfr_defined) {\n            mfr = rctr_parser.getMassFlowRate();\n        } else if (rt_defined) {\n            auto rt = rctr_parser.getResidenceTime();\n            mfr = rctr->mass()/rt;\n        }\n\n        inlet_mfc->setMassFlowRate(mfr);\n        outlet->setMaster(inlet_mfc.get());\n        outlet->setPressureCoeff(0.00001);\n        in_rsrv->insert(*gas);\n        exhst->insert(*gas);\n        inlet_mfc->install(*in_rsrv, *rctr);\n        outlet->install(*rctr, *exhst);\n    }\n\n    rctr->setChemistry();\n\n    // Read the reactor mode and set corresponding parameters\n    string mode = rctr_parser.getMode();\n    cout << \"Reactor temperature mode: \" << mode << endl;\n    gen_info_out << \"Reactor Temperature mode: \"  << mode << endl;\n\n    // heat_rsrv and wall are nominally defined.\n    // They are used if heat transfer is required.\n    auto heat_rsrv = make_shared<Reservoir>(); \n    auto wall = make_shared<Wall>();\n    if (mode == \"isothermal\" || mode == \"tpd\")  \n        rctr->setEnergy(0);\n    else {\n        rctr->setEnergy(1);\n        if (mode == \"heat\"){\n            double htc = rctr_parser.getWallHeatTransferCoeff();  // htc\n            double wall_abyv = rctr_parser.getWallSpecificArea(); // wall_abyv\n            double ext_temp = rctr_parser.getExternalTemp();      // Text\n            auto press = gas->pressure();\n            gas->setState_TP(ext_temp, press);\n            heat_rsrv->insert(*gas);\n            wall->setHeatTransferCoeff(htc);\n            wall->setArea(wall_abyv * rctr->volume());\n            wall->install(*heat_rsrv, *rctr);\n        }\n    }\n\n    /* Sensitivity Analysis */\n    bool sens_on = rctr_parser.isSensitivityAnalysisEnabled();\n    vector<string> rxnids;\n\n    if (sens_on) {\n        rxnids = rctr_parser.getSensitivityReactions();\n        for (auto& id : rxnids){\n            // Identify which kinetics the reaction belong to\n            // First gas phase kinetics\n            bool rxnConsumed = false;\n            for (size_t i = 0; i < gas->nReactions(); i++){\n                if (gas->reaction(i)->id == id){\n                    rctr->addSensitivityReaction(i);\n                    rxnConsumed = true;\n                    break;\n                }\n            }\n            size_t kin_ind = 0;\n            while(!rxnConsumed && kin_ind < surfaces.size()) {\n                for (size_t i = 0; i < surfaces[kin_ind]->nReactions(); i++){\n                    if (surfaces[kin_ind]->reaction(i)->id == id){\n\t\t\tcat_surfs[kin_ind]->addSensitivityReaction(i);\n\t\t\trxnConsumed = true;\n                        break;\n                    }\n                }\n                kin_ind++;\n            }\n            if(!rxnConsumed) {\n                throw CanteraError(\"Sensitivity reaction id {} not found in any mechanism\", id);\n            }\n        }\n\n    }\n    // Read simulation parameters\n    double end_time = 0;\n    if (mode == \"tpd\"){\n        auto beg_temp = rctr_parser.T();\n        auto end_temp = rctr_parser.getTPDEndTemp();\n        auto temp_ramp = rctr_parser.getTPDTempRamp();\n        rctr->setBeta(temp_ramp);\n        end_time = (end_temp - beg_temp)/temp_ramp;\n        cout << \"TPD simulation\" << endl;\n        cout << \"Temperature ramp \" << temp_ramp << endl;\n        cout << \"End temperature  \" << end_temp << endl;\n    } else {\n        end_time = rctr_parser.getEndTime();\n    }\n\n    vector<double> times;\n    bool transient_log = rctr_parser.logTransient();\n    if (transient_log && rctr_nos == 1){ // Only for singler CSTR or a batch reactor\n        auto step_size = rctr_parser.getInitStep();\n        cout << \"Simulation Step size \" << step_size << endl;\n\n        string stepping = rctr_parser.steppingType();\n        if (stepping == \"logarithmic\"){\n            times = get_log10_intervals(end_time, step_size);\n        }\n        else if (stepping == \"regular\"){\n            times = get_reg_intervals(0, end_time, step_size);\n        } \n    } else{\n        times.push_back(end_time);\n    }\n    cout << \"Size of time vector \" << times.size() << endl;\n    \n    // Setup simulation \n    ReactorNet rnet; \n    //ReactorNetHybrid rnet; \n    rnet.addReactor(*rctr);\n\n    // Pass any user defined numerical options to the solver\n    if (rctr_parser.tolerancesDefined()){\n        auto abs_tol = rctr_parser.get_atol();\n        auto rel_tol = rctr_parser.get_rtol();\n        rnet.setTolerances(rel_tol, abs_tol);\n    }\n    /* For these options, changes have to be made in Cantera\n    if (rctr_parser.solverInitStepSizeDefined()){\n        rnet.setInitialStepSize(rctr_parser.getSolverInitStepSize());\n    }\n    if (rctr_parser.solverMaxStepsDefined()){\n        rnet.setMaxNumSteps(rctr_parser.getSolverMaxSteps());\n    }*/\n\n    auto gas_print_specie_header = [&gas, data_format](string ind_var, ostream& out) -> void\n    {\n        if (data_format == OutputFormat::CSV) {\n            out << ind_var;\n            for (const auto & sp_name : gas->speciesNames()) {\n                out << \",\" << sp_name;\n            }\n        } else {\n            out << setw(16) << left << ind_var;\n            for (const auto & sp_name : gas->speciesNames()) {\n                out << setw(16) << left << sp_name;\n            }\n        }\n        out << endl;\n    };\n\n    // Steady state condition makes sense For CSTR and PFR_0D \n    vector<double> T_params = rctr_parser.Ts();\n    vector<double> P_params = rctr_parser.Ps();\n    vector<double> fr_params = rctr_parser.FRs();\n    if (!fr_params.size()){\n        if (rctr_type != BATCH) {\n            auto mfr = inlet_mfc->massFlowRate();\n            fr_params.push_back(mfr/gas->density());\n        }\n        else {\n            fr_params.push_back(0.0);\n        }\n    }\n\n    fs::path curr_dir = \".\";\n    for (const auto& T : T_params){\n        for (const auto& P : P_params){\n            for (const auto& fr : fr_params){\n                // Set the gas state TPX and sync the appropriate reactors\n                auto X = rctr_parser.getGasPhaseComposition();\n                gas->setState_TPX(T, P, X);\n                if (rctr_type != BATCH){\n                    in_rsrv->syncState();\n                    exhst->syncState();\n                    inlet_mfc->setMassFlowRate(fr * gas->density());\n                }\n                rctr->syncState();\n                rnet.setInitialTime(0);\n                rnet.reinitialize();\n\n                string new_dir = \"T-\"  + to_string(T) + \",P-\" + to_string(P) \n                                       + \",fr-\" + to_string(fr);\n                fs::path out_dir = curr_dir;\n                if (T_params.size() > 1 || P_params.size() > 1 || fr_params.size() > 1){\n                    out_dir /= new_dir;\n                    create_directory(out_dir);\n                }\n                \n                string file_ext;\n                if (data_format == OutputFormat::CSV) {\n                    file_ext = \"csv\";\n                } else {\n                    file_ext = \"dat\";\n                }\n\n                ofstream gas_ss_mole_out ((out_dir / (\"gas_mole_ss.\" + file_ext)).string(), ios::out);\n                ofstream gas_ss_mass_out ((out_dir / (\"gas_mass_ss.\" + file_ext)).string(), ios::out);\n                ofstream gas_ss_msdot_out ((out_dir / (\"gas_msdot_ss.\" + file_ext)).string(), ios::out);\n                ofstream surf_ss_out ((out_dir / (\"surf_cov_ss.\" + file_ext)).string(), ios::out);\n                ofstream state_var_ss_out ((out_dir / (\"rctr_state_ss.\" + file_ext)).string(), ios::out);\n                ofstream rates_out ((out_dir / \"rates_ss.out\").string(), ios::out);\n\n                if (data_format == OutputFormat::DAT) {\n                    gas_ss_mole_out << \"#Gas Mole fractions at Steady State\\n\";\n                    gas_ss_mass_out << \"#Gas Mass fractions at Steady State\\n\";\n                    gas_ss_msdot_out << \"#Surface Production Rates of  Gas Species at Steady State\\n\";\n                    surf_ss_out << \"#Surace Coverages at Steady State\\n\"; \n                    state_var_ss_out << \"#Steady State Reactor State\\n\";\n                }\n                \n                // Reaction path analysis (RPA) data, consisting of rates of progress.\n                // By default these values are written for simulation end time (PFR or CSTR)\n                // and for PFR exit. If enabled, RPA data is also written for all z-points\n                // of PFR\n                auto rpa_flag = rctr_parser.RPA();\n\n                auto state_var_print_hdr = [data_format](ostream& out, const string ind0) -> void\n                {\n                    if (data_format == OutputFormat::CSV) {\n                        out << ind0 << \",\"//\"z(m)\"\n                            << \"Temperature(K)\" << \",\" \n                            << \"Pressure(Pa)\" << \",\" \n                            << \"Density(kg/m3)\" << \",\" \n                            << \"U(J/kg)\" \n                            << endl;\n                    } else {\n                        out << setw(16) << left << ind0 //\"z(m)\"\n                            << setw(16) << left << \"Temperature(K)\" \n                            << setw(16) << left << \"Pressure(Pa)\" \n                            << setw(16) << left << \"Density(kg/m3)\" \n                            << setw(16) << left << \"U(J/kg)\" \n                            << endl;\n                    }\n                };\n\n                auto surf_print_hdr = [&](ostream& out, const string ind0) -> void\n                {\n                    if (data_format == OutputFormat::CSV) {\n                        out << ind0;\n                        for (const auto surf : surfaces) {\n                            for (const auto & sp_name : surf->speciesNames()) {\n                                out << \",\" << sp_name;\n                            }\n                        }\n                    } else {\n                        out << setw(16) << left << ind0;\n                        for (const auto surf : surfaces) {\n                            for (const auto & sp_name : surf->speciesNames()) {\n                                out << setw(16) << left << sp_name;\n                            }\n                        }\n                    }\n                    out << endl;\n                };\n\n                if (rctr_type == PFR_0D) {\n                    gas_print_specie_header(\"z(m)\", gas_ss_mole_out);\n                    gas_print_specie_header(\"z(m)\", gas_ss_mass_out);\n                    gas_print_specie_header(\"z(m)\", gas_ss_msdot_out);\n                    surf_print_hdr(surf_ss_out, \"z(m)\");\n                    state_var_print_hdr(state_var_ss_out, \"z(m)\");\n                } else {\n                    gas_print_specie_header(\"t(s)\", gas_ss_mole_out);\n                    gas_print_specie_header(\"t(s)\", gas_ss_mass_out);\n                    gas_print_specie_header(\"t(s)\", gas_ss_msdot_out);\n                    surf_print_hdr(surf_ss_out, \"t(s)\");\n                    state_var_print_hdr(state_var_ss_out, \"t(s)\");\n                }\n                    /*\n                    surf_ss_out \n                        << setw(16) << left << \"z(m)\";\n                    for (const auto surf : surfaces) {\n                        for (const auto & sp_name : surf->speciesNames()) {\n                            surf_ss_out << setw(16) << left << sp_name;\n                        }\n                    }\n                    surf_ss_out << endl;\n                    */\n                    \n                    // Print the inlet state\n                    //rnet.reinitialize();\n                if (rctr_type != BATCH) {\n                    print_0d_rctr_state(0, rctr.get(), surf_phases, gas_ss_mole_out, \n                                        gas_ss_mass_out, gas_ss_msdot_out, surf_ss_out, \n                                        state_var_ss_out);\n                }\n\n                // Transient state makes sense For BATCH and CSTR \n                ofstream gas_tr_mole_out ((out_dir / (\"gas_mole_tr.\" + file_ext)).string(), ios::out);\n                ofstream gas_tr_mass_out ((out_dir / (\"gas_mass_tr.\" + file_ext)).string(), ios::out);\n                ofstream gas_tr_msdot_out ((out_dir / (\"gas_msdot_tr.\" + file_ext)).string(), ios::out);\n                ofstream surf_tr_out ((out_dir / (\"surf_cov_tr.\" + file_ext)).string(), ios::out);\n                ofstream state_var_tr_out ((out_dir / (\"rctr_state_tr.\" + file_ext)).string(), ios::out);\n                if (rctr_type != PFR_0D && times.size() > 1) {\n                    if (data_format == OutputFormat::DAT) {\n                        gas_tr_mole_out << \"Transient Gas Mole fractions\"  << endl;\n                        gas_tr_mass_out << \"Transient Gas Mass fractions\"  << endl;\n                        gas_tr_msdot_out << \"Transient Surface Production Rates of  Gas Species\"  << endl;\n                        surf_tr_out << \"Transient Surface Coverages\"  << endl;\n                    }\n                    gas_print_specie_header(\"t(s)\", gas_tr_mole_out);\n                    gas_print_specie_header(\"t(s)\", gas_tr_mass_out);\n                    gas_print_specie_header(\"t(s)\", gas_tr_msdot_out);\n                    surf_print_hdr(surf_tr_out, \"t(s)\");\n                    state_var_print_hdr(state_var_tr_out, \"t(s)\");\n                }\n\n                vector<double> gas_X(gas->nSpecies()); // Temporary work array\n                for (size_t i = 0; i < rctr_nos; i++) {\n                    if (rctr_nos > 1) {\n                        gen_info_out << \"CSTR #: \" << i << endl;\n                    }\n                    // The next 9 lines redefine the TPX of gas for each reactor\n                    double temp = rctr->contents().temperature();\n                    double pressure = rctr->contents().pressure();\n                    rctr->contents().getMoleFractions(gas_X.data());\n                    gas->setState_TPX(temp, pressure, gas_X.data());\n                    if (rctr_type != BATCH){\n                        in_rsrv->syncState();\n                    }\n                    rnet.setInitialTime(0);\n                    rnet.reinitialize();\n                    rnet.setMaxTimeStep(1e-1);\n\n                    /*\n                    if (times.size() == 1) { \n                        cout << \"Solving with steady state solver\" << endl;\n                        rnet.setIntegratorEndTime(times[0]);\n                        rnet.solve();\n                    }\n                    else*/ {\n                        for (const auto & tm : times) {\n                            rnet.advance(tm);\n                            if (transient_log) {\n                                print_0d_rctr_state(tm, rctr.get(), surf_phases, \n                                                    gas_tr_mole_out, gas_tr_mass_out, \n                                                    gas_tr_msdot_out, surf_tr_out, \n                                                    state_var_tr_out);\n\n                            }\n                        }\n                    }\n                    rctr->restoreState();\n\n                    double ind_val;\n                    if (rctr_type == PFR_0D) {\n                        ind_val = (i+0.5)*rctr_vol;\n                    }\n                    else {\n                        ind_val = times.back();\n                    }\n                        \n                    print_0d_rctr_state(ind_val, rctr.get(), surf_phases, \n                                        gas_ss_mole_out, gas_ss_mass_out, \n                                        gas_ss_msdot_out, surf_ss_out, state_var_ss_out);\n\n                    if (rpa_flag) {\n                        string rpa_file_name = \"rates_z-\";\n                        rpa_file_name += to_string((i+0.5)*rctr_vol);\n                        rpa_file_name += \".out\";\n                        ofstream rates_out((out_dir / rpa_file_name).string(), \n                                           ios::out); // Masks the name\n                        print_rxn_rates_hdr(rates_out);\n\n                        rates_out.precision(6);\n\n                        print_rxn_rates(gas.get(), rates_out);\n                        for (auto surf : surfaces) {\n                            print_rxn_rates(surf.get(), rates_out);\n                        }\n                    }\n                }\n                // Print final rpa data\n                print_rxn_rates_hdr(rates_out);\n                rates_out.precision(6);\n                print_rxn_rates(gas.get(), rates_out);\n                for (auto surf : surfaces) {\n                    print_rxn_rates(surf.get(), rates_out);\n                }\n\n            }\n        }\n    }\n}\n}\n", "meta": {"hexsha": "cc3be9b892cb6070ba40034d5d361e5186cc8365", "size": 21752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/zerodReactor.cpp", "max_stars_repo_name": "wittregr/openmkm", "max_stars_repo_head_hexsha": "58efabaffb4235641c079b86fe05afe356b3620d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zerodReactor.cpp", "max_issues_repo_name": "wittregr/openmkm", "max_issues_repo_head_hexsha": "58efabaffb4235641c079b86fe05afe356b3620d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zerodReactor.cpp", "max_forks_repo_name": "wittregr/openmkm", "max_forks_repo_head_hexsha": "58efabaffb4235641c079b86fe05afe356b3620d", "max_forks_repo_licenses": ["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.5908221797, "max_line_length": 106, "alphanum_fraction": 0.5087808018, "num_tokens": 4932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.027585282126861555, "lm_q1q2_score": 0.010212771905277336}}
{"text": "/*\n *            Copyright 2009-2021 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 <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n#include <votca/tools/elements.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/IncrementalFockBuilder.h\"\n#include \"votca/xtp/aomatrix.h\"\n#include \"votca/xtp/aopotential.h\"\n#include \"votca/xtp/density_integration.h\"\n#include \"votca/xtp/dftengine.h\"\n#include \"votca/xtp/eeinteractor.h\"\n#include \"votca/xtp/logger.h\"\n#include \"votca/xtp/mmregion.h\"\n#include \"votca/xtp/orbitals.h\"\n\nnamespace votca {\nnamespace xtp {\n\nvoid DFTEngine::Initialize(tools::Property& options) {\n\n  const std::string key_xtpdft = \"xtpdft\";\n  dftbasis_name_ = options.get(\".basisset\").as<std::string>();\n\n  if (options.exists(\".auxbasisset\")) {\n    auxbasis_name_ = options.get(\".auxbasisset\").as<std::string>();\n  }\n\n  if (!auxbasis_name_.empty()) {\n    screening_eps_ = options.get(key_xtpdft + \".screening_eps\").as<double>();\n    fock_matrix_reset_ =\n        options.get(key_xtpdft + \".fock_matrix_reset\").as<Index>();\n  }\n  if (options.exists(\".ecp\")) {\n    ecp_name_ = options.get(\".ecp\").as<std::string>();\n  }\n\n  initial_guess_ = options.get(\".initial_guess\").as<std::string>();\n\n  grid_name_ = options.get(key_xtpdft + \".integration_grid\").as<std::string>();\n  xc_functional_name_ = options.get(\".functional\").as<std::string>();\n\n  if (options.exists(key_xtpdft + \".externaldensity\")) {\n    integrate_ext_density_ = true;\n    orbfilename_ =\n        options.get(key_xtpdft + \".externaldensity.orbfile\").as<std::string>();\n    gridquality_ = options.get(key_xtpdft + \".externaldensity.gridquality\")\n                       .as<std::string>();\n    state_ =\n        options.get(key_xtpdft + \".externaldensity.state\").as<std::string>();\n  }\n\n  if (options.exists(\".externalfield\")) {\n    integrate_ext_field_ = true;\n    extfield_ = options.get(\".externalfield\").as<Eigen::Vector3d>();\n  }\n\n  conv_opt_.Econverged =\n      options.get(key_xtpdft + \".convergence.energy\").as<double>();\n  conv_opt_.error_converged =\n      options.get(key_xtpdft + \".convergence.error\").as<double>();\n  max_iter_ =\n      options.get(key_xtpdft + \".convergence.max_iterations\").as<Index>();\n\n  std::string method =\n      options.get(key_xtpdft + \".convergence.method\").as<std::string>();\n  if (method == \"DIIS\") {\n    conv_opt_.usediis = true;\n  } else if (method == \"mixing\") {\n    conv_opt_.usediis = false;\n  }\n  if (!conv_opt_.usediis) {\n    conv_opt_.histlength = 1;\n    conv_opt_.maxout = false;\n  }\n  conv_opt_.mixingparameter =\n      options.get(key_xtpdft + \".convergence.mixing\").as<double>();\n  conv_opt_.levelshift =\n      options.get(key_xtpdft + \".convergence.levelshift\").as<double>();\n  conv_opt_.levelshiftend =\n      options.get(key_xtpdft + \".convergence.levelshift_end\").as<double>();\n  conv_opt_.maxout =\n      options.get(key_xtpdft + \".convergence.DIIS_maxout\").as<bool>();\n  conv_opt_.histlength =\n      options.get(key_xtpdft + \".convergence.DIIS_length\").as<Index>();\n  conv_opt_.diis_start =\n      options.get(key_xtpdft + \".convergence.DIIS_start\").as<double>();\n  conv_opt_.adiis_start =\n      options.get(key_xtpdft + \".convergence.ADIIS_start\").as<double>();\n}\n\nvoid DFTEngine::PrintMOs(const Eigen::VectorXd& MOEnergies, Log::Level level) {\n  XTP_LOG(level, *pLog_) << \"  Orbital energies: \" << std::flush;\n  XTP_LOG(level, *pLog_) << \"  index occupation energy(Hartree) \" << std::flush;\n  for (Index i = 0; i < MOEnergies.size(); i++) {\n    Index occupancy = 0;\n    if (i < numofelectrons_ / 2) {\n      occupancy = 2;\n    }\n    XTP_LOG(level, *pLog_) << (boost::format(\" %1$5d      %2$1d   %3$+1.10f\") %\n                               i % occupancy % MOEnergies(i))\n                                  .str()\n                           << std::flush;\n  }\n  return;\n}\n\nvoid DFTEngine::CalcElDipole(const Orbitals& orb) const {\n  QMState state = QMState(\"n\");\n  Eigen::Vector3d result = orb.CalcElDipole(state);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Electric Dipole is[e*bohr]:\\n\\t\\t dx=\" << result[0]\n      << \"\\n\\t\\t dy=\" << result[1] << \"\\n\\t\\t dz=\" << result[2] << std::flush;\n  return;\n}\n\nstd::array<Eigen::MatrixXd, 2> DFTEngine::CalcERIs_EXX(\n    const Eigen::MatrixXd& MOCoeff, const Eigen::MatrixXd& Dmat,\n    double error) const {\n  if (!auxbasis_name_.empty()) {\n    if (conv_accelerator_.getUseMixing() || MOCoeff.rows() == 0) {\n      return ERIs_.CalculateERIs_EXX_3c(Eigen::MatrixXd::Zero(0, 0), Dmat);\n    } else {\n      Eigen::MatrixXd occblock = MOCoeff.leftCols(numofelectrons_ / 2);\n      return ERIs_.CalculateERIs_EXX_3c(occblock, Dmat);\n    }\n  } else {\n    return ERIs_.CalculateERIs_EXX_4c(Dmat, error);\n  }\n}\n\nEigen::MatrixXd DFTEngine::CalcERIs(const Eigen::MatrixXd& Dmat,\n                                    double error) const {\n  if (!auxbasis_name_.empty()) {\n    return ERIs_.CalculateERIs_3c(Dmat);\n  } else {\n    return ERIs_.CalculateERIs_4c(Dmat, error);\n  }\n}\n\ntools::EigenSystem DFTEngine::IndependentElectronGuess(\n    const Mat_p_Energy& H0) const {\n  return conv_accelerator_.SolveFockmatrix(H0.matrix());\n}\n\ntools::EigenSystem DFTEngine::ModelPotentialGuess(\n    const Mat_p_Energy& H0, const QMMolecule& mol,\n    const Vxc_Potential<Vxc_Grid>& vxcpotential) const {\n  Eigen::MatrixXd Dmat = AtomicGuess(mol);\n  Mat_p_Energy e_vxc = vxcpotential.IntegrateVXC(Dmat);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Filled DFT Vxc matrix \" << std::flush;\n\n  Eigen::MatrixXd H = H0.matrix() + e_vxc.matrix();\n\n  if (ScaHFX_ > 0) {\n    std::array<Eigen::MatrixXd, 2> both =\n        CalcERIs_EXX(Eigen::MatrixXd::Zero(0, 0), Dmat, 1e-12);\n    H += both[0];\n    H += ScaHFX_ * both[1];\n  } else {\n    H += CalcERIs(Dmat, 1e-12);\n  }\n  return conv_accelerator_.SolveFockmatrix(H);\n}\n\nbool DFTEngine::Evaluate(Orbitals& orb) {\n  Prepare(orb);\n  Mat_p_Energy H0 = SetupH0(orb.QMAtoms());\n  tools::EigenSystem MOs;\n  MOs.eigenvalues() = Eigen::VectorXd::Zero(H0.cols());\n  MOs.eigenvectors() = Eigen::MatrixXd::Zero(H0.rows(), H0.cols());\n  Vxc_Potential<Vxc_Grid> vxcpotential = SetupVxc(orb.QMAtoms());\n  ConfigOrbfile(orb);\n\n  if (initial_guess_ == \"orbfile\") {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Reading guess from orbitals object/file\"\n        << std::flush;\n    MOs = orb.MOs();\n    MOs.eigenvectors() = OrthogonalizeGuess(MOs.eigenvectors());\n  } else {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Setup Initial Guess using: \" << initial_guess_\n        << std::flush;\n    if (initial_guess_ == \"independent\") {\n      MOs = IndependentElectronGuess(H0);\n    } else if (initial_guess_ == \"atom\") {\n      MOs = ModelPotentialGuess(H0, orb.QMAtoms(), vxcpotential);\n    } else {\n      throw std::runtime_error(\"Initial guess method not known/implemented\");\n    }\n  }\n\n  Eigen::MatrixXd Dmat = conv_accelerator_.DensityMatrix(MOs);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Guess Matrix gives N=\" << std::setprecision(9)\n      << Dmat.cwiseProduct(dftAOoverlap_.Matrix()).sum() << \" electrons.\"\n      << std::flush;\n\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" STARTING SCF cycle\" << std::flush;\n  XTP_LOG(Log::error, *pLog_)\n      << \" ----------------------------------------------\"\n         \"----------------------------\"\n      << std::flush;\n\n  Eigen::MatrixXd J = Eigen::MatrixXd::Zero(Dmat.rows(), Dmat.cols());\n  Eigen::MatrixXd K;\n  if (ScaHFX_ > 0) {\n    K = Eigen::MatrixXd::Zero(Dmat.rows(), Dmat.cols());\n  }\n\n  double start_incremental_F_threshold = 1e-4;\n  if (!auxbasis_name_.empty()) {\n    start_incremental_F_threshold = 0.0;  // Disable if RI is used\n  }\n  IncrementalFockBuilder incremental_fock(*pLog_, start_incremental_F_threshold,\n                                          fock_matrix_reset_);\n  incremental_fock.Configure(Dmat);\n\n  for (Index this_iter = 0; this_iter < max_iter_; this_iter++) {\n    XTP_LOG(Log::error, *pLog_) << std::flush;\n    XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Iteration \" << this_iter + 1\n                                << \" of \" << max_iter_ << std::flush;\n\n    Mat_p_Energy e_vxc = vxcpotential.IntegrateVXC(Dmat);\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << \" Filled DFT Vxc matrix \" << std::flush;\n\n    Eigen::MatrixXd H = H0.matrix() + e_vxc.matrix();\n    double Eone = Dmat.cwiseProduct(H0.matrix()).sum();\n    double Etwo = e_vxc.energy();\n    double exx = 0.0;\n\n    incremental_fock.Start(this_iter, conv_accelerator_.getDIIsError());\n    incremental_fock.resetMatrices(J, K, Dmat);\n    incremental_fock.UpdateCriteria(conv_accelerator_.getDIIsError(),\n                                    this_iter);\n\n    double integral_error =\n        std::min(conv_accelerator_.getDIIsError() * 1e-5, 1e-5);\n    if (ScaHFX_ > 0) {\n      std::array<Eigen::MatrixXd, 2> both = CalcERIs_EXX(\n          MOs.eigenvectors(), incremental_fock.getDmat_diff(), integral_error);\n      J += both[0];\n      H += J;\n      Etwo += 0.5 * Dmat.cwiseProduct(J).sum();\n      K += both[1];\n      H += 0.5 * ScaHFX_ * K;\n      exx = 0.25 * ScaHFX_ * Dmat.cwiseProduct(K).sum();\n      XTP_LOG(Log::info, *pLog_)\n          << TimeStamp() << \" Filled F+K matrix \" << std::flush;\n    } else {\n      J += CalcERIs(incremental_fock.getDmat_diff(), integral_error);\n      XTP_LOG(Log::info, *pLog_)\n          << TimeStamp() << \" Filled F matrix \" << std::flush;\n      H += J;\n      Etwo += 0.5 * Dmat.cwiseProduct(J).sum();\n    }\n\n    Etwo += exx;\n    double totenergy = Eone + H0.energy() + Etwo;\n    XTP_LOG(Log::info, *pLog_) << TimeStamp() << \" Single particle energy \"\n                               << std::setprecision(12) << Eone << std::flush;\n    XTP_LOG(Log::info, *pLog_) << TimeStamp() << \" Two particle energy \"\n                               << std::setprecision(12) << Etwo << std::flush;\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << std::setprecision(12) << \" Local Exc contribution \"\n        << e_vxc.energy() << std::flush;\n    if (ScaHFX_ > 0) {\n      XTP_LOG(Log::info, *pLog_)\n          << TimeStamp() << std::setprecision(12)\n          << \" Non local Ex contribution \" << exx << std::flush;\n    }\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Total Energy \" << std::setprecision(12) << totenergy\n        << std::flush;\n\n    Dmat = conv_accelerator_.Iterate(Dmat, H, MOs, totenergy);\n    incremental_fock.UpdateDmats(Dmat, conv_accelerator_.getDIIsError(),\n                                 this_iter);\n\n    PrintMOs(MOs.eigenvalues(), Log::info);\n\n    XTP_LOG(Log::info, *pLog_) << \"\\t\\tGAP \"\n                               << MOs.eigenvalues()(numofelectrons_ / 2) -\n                                      MOs.eigenvalues()(numofelectrons_ / 2 - 1)\n                               << std::flush;\n\n    if (conv_accelerator_.isConverged()) {\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" Total Energy has converged to \"\n          << std::setprecision(9) << conv_accelerator_.getDeltaE()\n          << \"[Ha] after \" << this_iter + 1\n          << \" iterations. DIIS error is converged up to \"\n          << conv_accelerator_.getDIIsError() << std::flush;\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" Final Single Point Energy \"\n          << std::setprecision(12) << totenergy << \" Ha\" << std::flush;\n      XTP_LOG(Log::error, *pLog_) << TimeStamp() << std::setprecision(12)\n                                  << \" Final Local Exc contribution \"\n                                  << e_vxc.energy() << \" Ha\" << std::flush;\n      if (ScaHFX_ > 0) {\n        XTP_LOG(Log::error, *pLog_) << TimeStamp() << std::setprecision(12)\n                                    << \" Final Non Local Ex contribution \"\n                                    << exx << \" Ha\" << std::flush;\n      }\n\n      PrintMOs(MOs.eigenvalues(), Log::error);\n      orb.setQMEnergy(totenergy);\n      orb.MOs() = MOs;\n      CalcElDipole(orb);\n      break;\n    } else if (this_iter == max_iter_ - 1) {\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" DFT calculation has not converged after \"\n          << max_iter_\n          << \" iterations. Use more iterations or another convergence \"\n             \"acceleration scheme.\"\n          << std::flush;\n      return false;\n    }\n  }\n  return true;\n}\n\nMat_p_Energy DFTEngine::SetupH0(const QMMolecule& mol) const {\n\n  AOKinetic dftAOkinetic;\n\n  dftAOkinetic.Fill(dftbasis_);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Filled DFT Kinetic energy matrix .\" << std::flush;\n\n  AOMultipole dftAOESP;\n  dftAOESP.FillPotential(dftbasis_, mol);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Filled DFT nuclear potential matrix.\" << std::flush;\n\n  Eigen::MatrixXd H0 = dftAOkinetic.Matrix() + dftAOESP.Matrix();\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Constructed independent particle hamiltonian \"\n      << std::flush;\n  double E0 = NuclearRepulsion(mol);\n  XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" Nuclear Repulsion Energy is \"\n                              << std::setprecision(9) << E0 << std::flush;\n\n  if (!ecp_name_.empty()) {\n    AOECP dftAOECP;\n    dftAOECP.FillPotential(dftbasis_, ecp_);\n    H0 += dftAOECP.Matrix();\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << \" Filled DFT ECP matrix\" << std::flush;\n  }\n\n  if (externalsites_ != nullptr) {\n    XTP_LOG(Log::error, *pLog_) << TimeStamp() << \" \" << externalsites_->size()\n                                << \" External sites\" << std::flush;\n    bool has_quadrupoles = std::any_of(\n        externalsites_->begin(), externalsites_->end(),\n        [](const std::unique_ptr<StaticSite>& s) { return s->getRank() == 2; });\n    std::string header =\n        \" Name      Coordinates[a0]     charge[e]         dipole[e*a0]    \";\n    if (has_quadrupoles) {\n      header += \"              quadrupole[e*a0^2]\";\n    }\n    XTP_LOG(Log::error, *pLog_) << header << std::flush;\n    Index limit = 50;\n    Index counter = 0;\n    for (const std::unique_ptr<StaticSite>& site : *externalsites_) {\n      if (counter == limit) {\n        break;\n      }\n      std::string output =\n          (boost::format(\"  %1$s\"\n                         \"   %2$+1.4f %3$+1.4f %4$+1.4f\"\n                         \"   %5$+1.4f\") %\n           site->getElement() % site->getPos()[0] % site->getPos()[1] %\n           site->getPos()[2] % site->getCharge())\n              .str();\n      const Eigen::Vector3d& dipole = site->getDipole();\n      output += (boost::format(\"   %1$+1.4f %2$+1.4f %3$+1.4f\") % dipole[0] %\n                 dipole[1] % dipole[2])\n                    .str();\n      if (site->getRank() > 1) {\n        Eigen::VectorXd quadrupole = site->Q().tail<5>();\n        output +=\n            (boost::format(\"   %1$+1.4f %2$+1.4f %3$+1.4f %4$+1.4f %5$+1.4f\") %\n             quadrupole[0] % quadrupole[1] % quadrupole[2] % quadrupole[3] %\n             quadrupole[4])\n                .str();\n      }\n      XTP_LOG(Log::error, *pLog_) << output << std::flush;\n      counter++;\n    }\n    if (counter == limit) {\n      XTP_LOG(Log::error, *pLog_)\n          << \"              ... (\" << externalsites_->size() - limit\n          << \" sites not displayed)\\n\"\n          << std::flush;\n    }\n\n    Mat_p_Energy ext_multipoles =\n        IntegrateExternalMultipoles(mol, *externalsites_);\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Nuclei-external site interaction energy \"\n        << std::setprecision(9) << ext_multipoles.energy() << std::flush;\n    E0 += ext_multipoles.energy();\n    H0 += ext_multipoles.matrix();\n  }\n\n  if (integrate_ext_density_) {\n    Orbitals extdensity;\n    extdensity.ReadFromCpt(orbfilename_);\n    Mat_p_Energy extdensity_result = IntegrateExternalDensity(mol, extdensity);\n    E0 += extdensity_result.energy();\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Nuclei-external density interaction energy \"\n        << std::setprecision(9) << extdensity_result.energy() << std::flush;\n    H0 += extdensity_result.matrix();\n  }\n\n  if (integrate_ext_field_) {\n\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Integrating external electric field with F[Hrt]=\"\n        << extfield_.transpose() << std::flush;\n    H0 += IntegrateExternalField(mol);\n  }\n\n  return Mat_p_Energy(E0, H0);\n}\n\nvoid DFTEngine::SetupInvariantMatrices() {\n\n  dftAOoverlap_.Fill(dftbasis_);\n\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Filled DFT Overlap matrix.\" << std::flush;\n\n  conv_opt_.numberofelectrons = numofelectrons_;\n  conv_accelerator_.Configure(conv_opt_);\n  conv_accelerator_.setLogger(pLog_);\n  conv_accelerator_.setOverlap(dftAOoverlap_, 1e-8);\n  conv_accelerator_.PrintConfigOptions();\n\n  if (!auxbasis_name_.empty()) {\n    // prepare invariant part of electron repulsion integrals\n    ERIs_.Initialize(dftbasis_, auxbasis_);\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << \" Inverted AUX Coulomb matrix, removed \"\n        << ERIs_.Removedfunctions() << \" functions from aux basis\"\n        << std::flush;\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp()\n        << \" Setup invariant parts of Electron Repulsion integrals \"\n        << std::flush;\n  } else {\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << \" Calculating 4c diagonals. \" << std::flush;\n    ERIs_.Initialize_4c(dftbasis_);\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << \" Calculated 4c diagonals. \" << std::flush;\n  }\n\n  return;\n}\n\nEigen::MatrixXd DFTEngine::RunAtomicDFT_unrestricted(\n    const QMAtom& uniqueAtom) const {\n  bool with_ecp = !ecp_name_.empty();\n  if (uniqueAtom.getElement() == \"H\" || uniqueAtom.getElement() == \"He\") {\n    with_ecp = false;\n  }\n\n  QMMolecule atom = QMMolecule(\"individual_atom\", 0);\n  atom.push_back(uniqueAtom);\n\n  BasisSet basisset;\n  basisset.Load(dftbasis_name_);\n  AOBasis dftbasis;\n  dftbasis.Fill(basisset, atom);\n  Vxc_Grid grid;\n  grid.GridSetup(grid_name_, atom, dftbasis);\n  Vxc_Potential<Vxc_Grid> gridIntegration(grid);\n  gridIntegration.setXCfunctional(xc_functional_name_);\n\n  ECPAOBasis ecp;\n  if (with_ecp) {\n    ECPBasisSet ecps;\n    ecps.Load(ecp_name_);\n    ecp.Fill(ecps, atom);\n  }\n\n  Index numofelectrons = uniqueAtom.getNuccharge();\n  Index alpha_e = 0;\n  Index beta_e = 0;\n\n  if ((numofelectrons % 2) != 0) {\n    alpha_e = numofelectrons / 2 + numofelectrons % 2;\n    beta_e = numofelectrons / 2;\n  } else {\n    alpha_e = numofelectrons / 2;\n    beta_e = alpha_e;\n  }\n\n  AOOverlap dftAOoverlap;\n  AOKinetic dftAOkinetic;\n  AOMultipole dftAOESP;\n  AOECP dftAOECP;\n  ERIs ERIs_atom;\n\n  // DFT AOOverlap matrix\n\n  dftAOoverlap.Fill(dftbasis);\n  dftAOkinetic.Fill(dftbasis);\n\n  dftAOESP.FillPotential(dftbasis, atom);\n  ERIs_atom.Initialize_4c(dftbasis);\n\n  ConvergenceAcc Convergence_alpha;\n  ConvergenceAcc Convergence_beta;\n  ConvergenceAcc::options opt_alpha = conv_opt_;\n  opt_alpha.mode = ConvergenceAcc::KSmode::open;\n  opt_alpha.histlength = 20;\n  opt_alpha.levelshift = 0.1;\n  opt_alpha.levelshiftend = 0.0;\n  opt_alpha.usediis = true;\n  opt_alpha.adiis_start = 0.0;\n  opt_alpha.diis_start = 0.0;\n  opt_alpha.numberofelectrons = alpha_e;\n\n  ConvergenceAcc::options opt_beta = opt_alpha;\n  opt_beta.numberofelectrons = beta_e;\n\n  Logger log;\n  Convergence_alpha.Configure(opt_alpha);\n  Convergence_alpha.setLogger(&log);\n  Convergence_alpha.setOverlap(dftAOoverlap, 1e-8);\n  Convergence_beta.Configure(opt_beta);\n  Convergence_beta.setLogger(&log);\n  Convergence_beta.setOverlap(dftAOoverlap, 1e-8);\n  /**** Construct initial density  ****/\n\n  Eigen::MatrixXd H0 = dftAOkinetic.Matrix() + dftAOESP.Matrix();\n  if (with_ecp) {\n    dftAOECP.FillPotential(dftbasis, ecp);\n    H0 += dftAOECP.Matrix();\n  }\n  tools::EigenSystem MOs_alpha = Convergence_alpha.SolveFockmatrix(H0);\n\n  Eigen::MatrixXd dftAOdmat_alpha = Convergence_alpha.DensityMatrix(MOs_alpha);\n  if (uniqueAtom.getElement() == \"H\") {\n    return dftAOdmat_alpha;\n  }\n  tools::EigenSystem MOs_beta = Convergence_beta.SolveFockmatrix(H0);\n  Eigen::MatrixXd dftAOdmat_beta = Convergence_beta.DensityMatrix(MOs_beta);\n\n  Index maxiter = 80;\n  for (Index this_iter = 0; this_iter < maxiter; this_iter++) {\n\n    Eigen::MatrixXd H_alpha = H0;\n    Eigen::MatrixXd H_beta = H_alpha;\n\n    double E_two_alpha = 0.0;\n    double E_two_beta = 0.0;\n\n    double integral_error = std::min(1e-5 * 0.5 *\n                                         (Convergence_alpha.getDIIsError() +\n                                          Convergence_beta.getDIIsError()),\n                                     1e-5);\n    if (ScaHFX_ > 0) {\n      std::array<Eigen::MatrixXd, 2> both_alpha =\n          ERIs_atom.CalculateERIs_EXX_4c(dftAOdmat_alpha, integral_error);\n\n      std::array<Eigen::MatrixXd, 2> both_beta =\n          ERIs_atom.CalculateERIs_EXX_4c(dftAOdmat_beta, integral_error);\n      Eigen::MatrixXd Hartree = both_alpha[0] + both_beta[0];\n      E_two_alpha += Hartree.cwiseProduct(dftAOdmat_alpha).sum();\n      E_two_beta += Hartree.cwiseProduct(dftAOdmat_beta).sum();\n      E_two_alpha += 0.5 * both_alpha[1].cwiseProduct(dftAOdmat_alpha).sum();\n      E_two_beta += 0.5 * both_beta[1].cwiseProduct(dftAOdmat_beta).sum();\n      H_alpha += Hartree + ScaHFX_ * both_alpha[1];\n      H_beta += Hartree + ScaHFX_ * both_beta[1];\n\n    } else {\n      Eigen::MatrixXd Hartree = ERIs_atom.CalculateERIs_4c(\n          dftAOdmat_alpha + dftAOdmat_beta, integral_error);\n      E_two_alpha += Hartree.cwiseProduct(dftAOdmat_alpha).sum();\n      E_two_beta += Hartree.cwiseProduct(dftAOdmat_beta).sum();\n      H_alpha += Hartree;\n      H_beta += Hartree;\n    }\n\n    Mat_p_Energy e_vxc_alpha = gridIntegration.IntegrateVXC(dftAOdmat_alpha);\n    H_alpha += e_vxc_alpha.matrix();\n    E_two_alpha += e_vxc_alpha.energy();\n\n    Mat_p_Energy e_vxc_beta = gridIntegration.IntegrateVXC(dftAOdmat_beta);\n    H_beta += e_vxc_beta.matrix();\n    E_two_beta += e_vxc_beta.energy();\n\n    double E_one_alpha = dftAOdmat_alpha.cwiseProduct(H0).sum();\n    double E_one_beta = dftAOdmat_beta.cwiseProduct(H0).sum();\n    double E_alpha = E_one_alpha + E_two_alpha;\n    double E_beta = E_one_beta + E_two_beta;\n    double totenergy = E_alpha + E_beta;\n    // evolve alpha\n    dftAOdmat_alpha =\n        Convergence_alpha.Iterate(dftAOdmat_alpha, H_alpha, MOs_alpha, E_alpha);\n    // evolve beta\n    dftAOdmat_beta =\n        Convergence_beta.Iterate(dftAOdmat_beta, H_beta, MOs_beta, E_beta);\n\n    XTP_LOG(Log::debug, *pLog_)\n        << TimeStamp() << \" Iter \" << this_iter << \" of \" << maxiter << \" Etot \"\n        << totenergy << \" diise_a \" << Convergence_alpha.getDIIsError()\n        << \" diise_b \" << Convergence_beta.getDIIsError() << \"\\n\\t\\t a_gap \"\n        << MOs_alpha.eigenvalues()(alpha_e) -\n               MOs_alpha.eigenvalues()(alpha_e - 1)\n        << \" b_gap \"\n        << MOs_beta.eigenvalues()(beta_e) - MOs_beta.eigenvalues()(beta_e - 1)\n        << \" Nalpha=\"\n        << dftAOoverlap.Matrix().cwiseProduct(dftAOdmat_alpha).sum()\n        << \" Nbeta=\" << dftAOoverlap.Matrix().cwiseProduct(dftAOdmat_beta).sum()\n        << std::flush;\n\n    bool converged =\n        Convergence_alpha.isConverged() && Convergence_beta.isConverged();\n    if (converged || this_iter == maxiter - 1) {\n\n      if (converged) {\n        XTP_LOG(Log::info, *pLog_)\n            << TimeStamp() << \" Converged after \" << this_iter + 1\n            << \" iterations\" << std::flush;\n      } else {\n        XTP_LOG(Log::info, *pLog_)\n            << TimeStamp() << \" Not converged after \" << this_iter + 1\n            << \" iterations. Unconverged density.\\n\\t\\t\\t\"\n            << \" DIIsError_alpha=\" << Convergence_alpha.getDIIsError()\n            << \" DIIsError_beta=\" << Convergence_beta.getDIIsError()\n            << std::flush;\n      }\n      break;\n    }\n  }\n  Eigen::MatrixXd avgmatrix =\n      SphericalAverageShells(dftAOdmat_alpha + dftAOdmat_beta, dftbasis);\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Atomic density Matrix for \" << uniqueAtom.getElement()\n      << \" gives N=\" << std::setprecision(9)\n      << avgmatrix.cwiseProduct(dftAOoverlap.Matrix()).sum() << \" electrons.\"\n      << std::flush;\n  return avgmatrix;\n}\n\nEigen::MatrixXd DFTEngine::AtomicGuess(const QMMolecule& mol) const {\n\n  std::vector<std::string> elements = mol.FindUniqueElements();\n  XTP_LOG(Log::info, *pLog_)\n      << TimeStamp() << \" Scanning molecule of size \" << mol.size()\n      << \" for unique elements\" << std::flush;\n  QMMolecule uniqueelements = QMMolecule(\"uniqueelements\", 0);\n  for (auto element : elements) {\n    uniqueelements.push_back(QMAtom(0, element, Eigen::Vector3d::Zero()));\n  }\n\n  XTP_LOG(Log::info, *pLog_) << TimeStamp() << \" \" << uniqueelements.size()\n                             << \" unique elements found\" << std::flush;\n  std::vector<Eigen::MatrixXd> uniqueatom_guesses;\n  for (QMAtom& unique_atom : uniqueelements) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Calculating atom density for \"\n        << unique_atom.getElement() << std::flush;\n    Eigen::MatrixXd dmat_unrestricted = RunAtomicDFT_unrestricted(unique_atom);\n    uniqueatom_guesses.push_back(dmat_unrestricted);\n  }\n\n  Eigen::MatrixXd guess =\n      Eigen::MatrixXd::Zero(dftbasis_.AOBasisSize(), dftbasis_.AOBasisSize());\n  Index start = 0;\n  for (const QMAtom& atom : mol) {\n    Index index = 0;\n    for (; index < uniqueelements.size(); index++) {\n      if (atom.getElement() == uniqueelements[index].getElement()) {\n        break;\n      }\n    }\n    Eigen::MatrixXd& dmat_unrestricted = uniqueatom_guesses[index];\n    guess.block(start, start, dmat_unrestricted.rows(),\n                dmat_unrestricted.cols()) = dmat_unrestricted;\n    start += dmat_unrestricted.rows();\n  }\n\n  return guess;\n}\n\nvoid DFTEngine::ConfigOrbfile(Orbitals& orb) {\n  if (initial_guess_ == \"orbfile\") {\n\n    if (orb.hasDFTbasisName()) {\n      if (orb.getDFTbasisName() != dftbasis_name_) {\n        throw std::runtime_error(\n            (boost::format(\"Basisset Name in guess orb file \"\n                           \"and in dftengine option file differ %1% vs %2%\") %\n             orb.getDFTbasisName() % dftbasis_name_)\n                .str());\n      }\n    } else {\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp()\n          << \" WARNING: \"\n             \"Orbital file has no basisset information,\"\n             \"using it as a guess might work or not for calculation with \"\n          << dftbasis_name_ << std::flush;\n    }\n  }\n  orb.setXCFunctionalName(xc_functional_name_);\n  orb.setXCGrid(grid_name_);\n  orb.setScaHFX(ScaHFX_);\n  if (!ecp_name_.empty()) {\n    orb.setECPName(ecp_name_);\n  }\n  if (!auxbasis_name_.empty()) {\n    orb.SetupAuxBasis(auxbasis_name_);\n  }\n\n  if (initial_guess_ == \"orbfile\") {\n    if (orb.hasECPName() || !ecp_name_.empty()) {\n      if (orb.getECPName() != ecp_name_) {\n        throw std::runtime_error(\n            (boost::format(\"ECPs in orb file: %1% and options %2% differ\") %\n             orb.getECPName() % ecp_name_)\n                .str());\n      }\n    }\n    if (orb.getNumberOfAlphaElectrons() != numofelectrons_ / 2) {\n      throw std::runtime_error(\n          (boost::format(\"Number of electron in guess orb file: %1% and in \"\n                         \"dftengine: %2% differ.\") %\n           orb.getNumberOfAlphaElectrons() % (numofelectrons_ / 2))\n              .str());\n    }\n    if (orb.getBasisSetSize() != dftbasis_.AOBasisSize()) {\n      throw std::runtime_error(\n          (boost::format(\"Number of levels in guess orb file: \"\n                         \"%1% and in dftengine: %2% differ.\") %\n           orb.getBasisSetSize() % dftbasis_.AOBasisSize())\n              .str());\n    }\n  } else {\n    orb.setNumberOfAlphaElectrons(numofelectrons_ / 2);\n    orb.setNumberOfOccupiedLevels(numofelectrons_ / 2);\n  }\n  return;\n}\n\nvoid DFTEngine::Prepare(Orbitals& orb) {\n  QMMolecule& mol = orb.QMAtoms();\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Using \" << OPENMP::getMaxThreads() << \" threads\"\n      << std::flush;\n\n  if (XTP_HAS_MKL_OVERLOAD()) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Using MKL overload for Eigen \" << std::flush;\n  } else {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp()\n        << \" Using native Eigen implementation, no BLAS overload \"\n        << std::flush;\n  }\n\n  XTP_LOG(Log::error, *pLog_) << \" Molecule Coordinates [A] \" << std::flush;\n  for (const QMAtom& atom : mol) {\n    const Eigen::Vector3d pos = atom.getPos() * tools::conv::bohr2ang;\n    std::string output = (boost::format(\"  %1$s\"\n                                        \"   %2$+1.4f %3$+1.4f %4$+1.4f\") %\n                          atom.getElement() % pos[0] % pos[1] % pos[2])\n                             .str();\n\n    XTP_LOG(Log::error, *pLog_) << output << std::flush;\n  }\n\n  orb.SetupDftBasis(dftbasis_name_);\n  dftbasis_ = orb.getDftBasis();\n\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Loaded DFT Basis Set \" << dftbasis_name_ << \" with \"\n      << dftbasis_.AOBasisSize() << \" functions\" << std::flush;\n\n  if (!auxbasis_name_.empty()) {\n    BasisSet auxbasisset;\n    auxbasisset.Load(auxbasis_name_);\n    auxbasis_.Fill(auxbasisset, mol);\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Loaded AUX Basis Set \" << auxbasis_name_ << \" with \"\n        << auxbasis_.AOBasisSize() << \" functions\" << std::flush;\n  }\n  if (!ecp_name_.empty()) {\n    ECPBasisSet ecpbasisset;\n    ecpbasisset.Load(ecp_name_);\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Loaded ECP library \" << ecp_name_ << std::flush;\n\n    std::vector<std::string> results = ecp_.Fill(ecpbasisset, mol);\n    XTP_LOG(Log::info, *pLog_)\n        << TimeStamp() << \" Filled ECP Basis\" << std::flush;\n    if (results.size() > 0) {\n      std::string message = \"\";\n      for (const std::string& element : results) {\n        message += \" \" + element;\n      }\n      XTP_LOG(Log::error, *pLog_)\n          << TimeStamp() << \" Found no ECPs for elements\" << message\n          << std::flush;\n    }\n  }\n\n  for (const QMAtom& atom : mol) {\n    numofelectrons_ += atom.getNuccharge();\n  }\n\n  // here number of electrons is actually the total number, everywhere else in\n  // votca it is just alpha_electrons\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Total number of electrons: \" << numofelectrons_\n      << std::flush;\n\n  SetupInvariantMatrices();\n  return;\n}\n\nVxc_Potential<Vxc_Grid> DFTEngine::SetupVxc(const QMMolecule& mol) {\n  ScaHFX_ = Vxc_Potential<Vxc_Grid>::getExactExchange(xc_functional_name_);\n  if (ScaHFX_ > 0) {\n    XTP_LOG(Log::error, *pLog_)\n        << TimeStamp() << \" Using hybrid functional with alpha=\" << ScaHFX_\n        << std::flush;\n  }\n  Vxc_Grid grid;\n  grid.GridSetup(grid_name_, mol, dftbasis_);\n  Vxc_Potential<Vxc_Grid> vxc(grid);\n  vxc.setXCfunctional(xc_functional_name_);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Setup numerical integration grid \" << grid_name_\n      << \" for vxc functional \" << xc_functional_name_ << std::flush;\n  XTP_LOG(Log::info, *pLog_)\n      << \"\\t\\t \"\n      << \" with \" << grid.getGridSize() << \" points\"\n      << \" divided into \" << grid.getBoxesSize() << \" boxes\" << std::flush;\n  return vxc;\n}\n\ndouble DFTEngine::NuclearRepulsion(const QMMolecule& mol) const {\n  double E_nucnuc = 0.0;\n\n  for (Index i = 0; i < mol.size(); i++) {\n    const Eigen::Vector3d& r1 = mol[i].getPos();\n    double charge1 = double(mol[i].getNuccharge());\n    for (Index j = 0; j < i; j++) {\n      const Eigen::Vector3d& r2 = mol[j].getPos();\n      double charge2 = double(mol[j].getNuccharge());\n      E_nucnuc += charge1 * charge2 / (r1 - r2).norm();\n    }\n  }\n  return E_nucnuc;\n}\n\n// spherically average the density matrix belonging to two shells\nEigen::MatrixXd DFTEngine::SphericalAverageShells(\n    const Eigen::MatrixXd& dmat, const AOBasis& dftbasis) const {\n  Eigen::MatrixXd avdmat = Eigen::MatrixXd::Zero(dmat.rows(), dmat.cols());\n  for (const AOShell& shellrow : dftbasis) {\n    Index size_row = shellrow.getNumFunc();\n    Index start_row = shellrow.getStartIndex();\n    for (const AOShell& shellcol : dftbasis) {\n      Index size_col = shellcol.getNumFunc();\n      Index start_col = shellcol.getStartIndex();\n      Eigen::MatrixXd shelldmat =\n          dmat.block(start_row, start_col, size_row, size_col);\n      if (shellrow.getL() == shellcol.getL()) {\n        double diagavg = shelldmat.diagonal().sum() / double(shelldmat.rows());\n        Index offdiagelements =\n            shelldmat.rows() * shelldmat.cols() - shelldmat.cols();\n        double offdiagavg = (shelldmat.sum() - shelldmat.diagonal().sum()) /\n                            double(offdiagelements);\n        avdmat.block(start_row, start_col, size_row, size_col).array() =\n            offdiagavg;\n        avdmat.block(start_row, start_col, size_row, size_col)\n            .diagonal()\n            .array() = diagavg;\n      } else {\n        double avg = shelldmat.sum() / double(shelldmat.size());\n        avdmat.block(start_row, start_col, size_row, size_col).array() = avg;\n      }\n    }\n  }\n  return avdmat;\n}\n\ndouble DFTEngine::ExternalRepulsion(\n    const QMMolecule& mol,\n    const std::vector<std::unique_ptr<StaticSite> >& multipoles) const {\n\n  if (multipoles.size() == 0) {\n    return 0;\n  }\n\n  double E_ext = 0;\n  eeInteractor interactor;\n  for (const QMAtom& atom : mol) {\n    StaticSite nucleus = StaticSite(atom, double(atom.getNuccharge()));\n    for (const std::unique_ptr<StaticSite>& site : *externalsites_) {\n      if ((site->getPos() - nucleus.getPos()).norm() < 1e-7) {\n        XTP_LOG(Log::error, *pLog_) << TimeStamp()\n                                    << \" External site sits on nucleus, \"\n                                       \"interaction between them is ignored.\"\n                                    << std::flush;\n        continue;\n      }\n      E_ext += interactor.CalcStaticEnergy_site(*site, nucleus);\n    }\n  }\n  return E_ext;\n}\n\nEigen::MatrixXd DFTEngine::IntegrateExternalField(const QMMolecule& mol) const {\n\n  AODipole dipole;\n  dipole.setCenter(mol.getPos());\n  dipole.Fill(dftbasis_);\n  Eigen::MatrixXd result =\n      Eigen::MatrixXd::Zero(dipole.Dimension(), dipole.Dimension());\n  for (Index i = 0; i < 3; i++) {\n    result -= dipole.Matrix()[i] * extfield_[i];\n  }\n  return result;\n}\n\nMat_p_Energy DFTEngine::IntegrateExternalMultipoles(\n    const QMMolecule& mol,\n    const std::vector<std::unique_ptr<StaticSite> >& multipoles) const {\n\n  Mat_p_Energy result(dftbasis_.AOBasisSize(), dftbasis_.AOBasisSize());\n  AOMultipole dftAOESP;\n\n  dftAOESP.FillPotential(dftbasis_, multipoles);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Filled DFT external multipole potential matrix\"\n      << std::flush;\n  result.matrix() = dftAOESP.Matrix();\n  result.energy() = ExternalRepulsion(mol, multipoles);\n\n  return result;\n}\n\nMat_p_Energy DFTEngine::IntegrateExternalDensity(\n    const QMMolecule& mol, const Orbitals& extdensity) const {\n  BasisSet basis;\n  basis.Load(extdensity.getDFTbasisName());\n  AOBasis aobasis;\n  aobasis.Fill(basis, extdensity.QMAtoms());\n  Vxc_Grid grid;\n  grid.GridSetup(gridquality_, extdensity.QMAtoms(), aobasis);\n  DensityIntegration<Vxc_Grid> numint(grid);\n  Eigen::MatrixXd dmat = extdensity.DensityMatrixFull(state_);\n\n  numint.IntegrateDensity(dmat);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Calculated external density\" << std::flush;\n  Eigen::MatrixXd e_contrib = numint.IntegratePotential(dftbasis_);\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Calculated potential from electron density\"\n      << std::flush;\n  AOMultipole esp;\n  esp.FillPotential(dftbasis_, extdensity.QMAtoms());\n\n  double nuc_energy = 0.0;\n  for (const QMAtom& atom : mol) {\n    nuc_energy +=\n        numint.IntegratePotential(atom.getPos()) * double(atom.getNuccharge());\n    for (const QMAtom& extatom : extdensity.QMAtoms()) {\n      const double dist = (atom.getPos() - extatom.getPos()).norm();\n      nuc_energy +=\n          double(atom.getNuccharge()) * double(extatom.getNuccharge()) / dist;\n    }\n  }\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Calculated potential from nuclei\" << std::flush;\n  XTP_LOG(Log::error, *pLog_)\n      << TimeStamp() << \" Electrostatic: \" << nuc_energy << std::flush;\n  return Mat_p_Energy(nuc_energy, e_contrib + esp.Matrix());\n}\n\nEigen::MatrixXd DFTEngine::OrthogonalizeGuess(\n    const Eigen::MatrixXd& GuessMOs) const {\n  Eigen::MatrixXd nonortho =\n      GuessMOs.transpose() * dftAOoverlap_.Matrix() * GuessMOs;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(nonortho);\n  Eigen::MatrixXd result = GuessMOs * es.operatorInverseSqrt();\n  return result;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "ff05853787753e740152019ae12caffb0503f218", "size": 37190, "ext": "cc", "lang": "C++", "max_stars_repo_path": "xtp/src/libxtp/dftengine/dftengine.cc", "max_stars_repo_name": "ipelupessy/votca", "max_stars_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xtp/src/libxtp/dftengine/dftengine.cc", "max_issues_repo_name": "ipelupessy/votca", "max_issues_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xtp/src/libxtp/dftengine/dftengine.cc", "max_forks_repo_name": "ipelupessy/votca", "max_forks_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0717749758, "max_line_length": 80, "alphanum_fraction": 0.617800484, "num_tokens": 10702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.031143833569754333, "lm_q1q2_score": 0.01020484702684451}}
{"text": "/*\n * BSD 2-Clause License\n *\n * Copyright (c) 2020, Christoph Neuhauser\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 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <boost/algorithm/string/predicate.hpp>\n#include <regex>\n\n#include <Utils/Convert.hpp>\n#include <Utils/File/Logfile.hpp>\n#include <Math/Math.hpp>\n#include <Math/Geometry/MatrixUtil.hpp>\n\n#include \"Tokens.hpp\"\n#include \"TransformString.hpp\"\n\nglm::mat4 parseTransformString(std::string transformString) {\n    glm::mat4 matrix = sgl::matrixIdentity();\n\n    // Iterate over all of the concatenated transformations (pattern: \"type(content)\").\n    // First match: Transform type. Second match: Transform information in the brackets.\n    std::regex transformRegex(\"\\\\s*(\\\\S+)\\\\s*\\\\(\\\\s*(.+)\\\\s*\\\\)(.*)\");\n    std::smatch what;\n    while (std::regex_search(transformString, what, transformRegex)) {\n        std::string transformType = what[1];\n        std::string transformContent = what[2];\n        transformString = what[3]; // Continue with next part of string\n\n        // Now split the transform content in the brackets (multiple float values separated by space or commas).\n        std::vector<std::string> transformData = getTokenList(transformContent, NUMBER_AND_DEGREES_REGEX_STRING);\n\n        if (transformType == \"translate\") {\n            float x = sgl::fromString<float>(transformData.at(0));\n            float y = sgl::fromString<float>(transformData.at(1));\n            float z = sgl::fromString<float>(transformData.at(1));\n            matrix = matrix * sgl::matrixTranslation(glm::vec3(x, y, z));\n        } else if (transformType == \"scale\") {\n            float scaleX = sgl::fromString<float>(transformData.at(0));\n            if (transformData.size() == 1) {\n                matrix = matrix * sgl::matrixScaling(glm::vec3(scaleX, scaleX, scaleX));\n            } else {\n                float scaleY = sgl::fromString<float>(transformData.at(1));\n                float scaleZ = sgl::fromString<float>(transformData.at(2));\n                matrix = matrix * sgl::matrixScaling(glm::vec3(scaleX, scaleY, scaleZ));\n            }\n        } else if (transformType == \"rotate\") {\n            float rotationAngleRadians = 0.0f;\n            // Degree or radians?\n            if (boost::ends_with(transformData.at(0), \"°\")) {\n                std::string numberString =\n                        transformData.at(0).substr(0, transformData.at(0).find_last_of(\"°\") - 1);\n                rotationAngleRadians = sgl::fromString<float>(numberString) / 180.0f * sgl::PI;\n            } else {\n                rotationAngleRadians = sgl::fromString<float>(transformData.at(0));\n            }\n            float axisX = sgl::fromString<float>(transformData.at(1));\n            float axisY = sgl::fromString<float>(transformData.at(2));\n            float axisZ = sgl::fromString<float>(transformData.at(3));\n            matrix = matrix * glm::rotate(rotationAngleRadians, glm::vec3(axisX, axisY, axisZ));\n        } else if (transformType == \"matrix\") {\n            float m[16];\n            for (size_t i = 0; i < transformData.size(); i++) {\n                m[i] = sgl::fromString<float>(transformData.at(i));\n            }\n\n            if (transformData.size() == 9) {\n                matrix = matrix * glm::mat4(\n                        m[0], m[3], m[6], 0.0f,\n                        m[1], m[4], m[7], 0.0f,\n                        m[2], m[5], m[8], 0.0f,\n                        0.0f, 0.0f, 0.0f, 1.0f\n                );\n            } else if (transformData.size() == 12) {\n                matrix = matrix * glm::mat4(\n                        m[0], m[4], m[8], 0.0f,\n                        m[1], m[5], m[9], 0.0f,\n                        m[2], m[6], m[10], 0.0f,\n                        m[3], m[7], m[11], 1.0f\n                );\n            } else if (transformData.size() == 16) {\n                matrix = matrix * glm::mat4(\n                        m[0], m[4], m[8], m[12],\n                        m[1], m[5], m[9], m[13],\n                        m[2], m[6], m[10], m[14],\n                        m[3], m[7], m[11], m[15]\n                );\n            } else {\n                sgl::Logfile::get()->writeError(\n                        \"ERROR in parseTransformString: Invalid number of elements in matrix.\");\n            }\n        } else if (transformType == \"matrixc\") {\n            float m[16];\n            for (size_t i = 0; i < transformData.size(); i++) {\n                m[i] = sgl::fromString<float>(transformData.at(i));\n            }\n\n            if (transformData.size() == 9) {\n                matrix = matrix * glm::mat4(\n                        m[0], m[1], m[2], 0.0f,\n                        m[3], m[4], m[5], 0.0f,\n                        m[6], m[7], m[8], 0.0f,\n                        0.0f, 0.0f, 0.0f, 1.0f\n                );\n            } else if (transformData.size() == 12) {\n                matrix = matrix * glm::mat4(\n                        m[0], m[1], m[2], 0.0f,\n                        m[3], m[4], m[5], 0.0f,\n                        m[6], m[7], m[8], 0.0f,\n                        m[9], m[10], m[11], 1.0f\n                );\n            } else if (transformData.size() == 16) {\n                matrix = matrix * glm::mat4(\n                        m[0], m[1], m[2], m[3],\n                        m[4], m[5], m[6], m[7],\n                        m[8], m[9], m[10], m[11],\n                        m[12], m[13], m[14], m[15]\n                );\n            } else {\n                sgl::Logfile::get()->writeError(\n                        \"ERROR in parseTransformString: Invalid number of elements in matrix.\");\n            }\n        }\n    }\n\n    return matrix;\n}\n", "meta": {"hexsha": "13d9d5a1699aaa0c95888f95844c3fd8212d537d", "size": 6889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Regex/TransformString.cpp", "max_stars_repo_name": "chrismile/sgl", "max_stars_repo_head_hexsha": "03748cadbd1661285081c47775213091b665cb86", "max_stars_repo_licenses": ["MIT", "Unlicense", "Apache-2.0", "BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-20T19:13:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T01:45:10.000Z", "max_issues_repo_path": "src/Utils/Regex/TransformString.cpp", "max_issues_repo_name": "chrismile/sgl", "max_issues_repo_head_hexsha": "03748cadbd1661285081c47775213091b665cb86", "max_issues_repo_licenses": ["MIT", "Unlicense", "Apache-2.0", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-20T20:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:32:46.000Z", "max_forks_repo_path": "src/Utils/Regex/TransformString.cpp", "max_forks_repo_name": "chrismile/sgl", "max_forks_repo_head_hexsha": "03748cadbd1661285081c47775213091b665cb86", "max_forks_repo_licenses": ["MIT", "Unlicense", "Apache-2.0", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T13:02:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T06:39:46.000Z", "avg_line_length": 45.9266666667, "max_line_length": 113, "alphanum_fraction": 0.5334591378, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.02194825587403225, "lm_q1q2_score": 0.010203778970185703}}
{"text": "// Copyright 2014 Nicolas Mellado\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// Authors: Nicolas Mellado\n//\n// An implementation of the Super 4-points Congruent Sets (Super 4PCS)\n// algorithm presented in:\n//\n// Super 4PCS: Fast Global Pointcloud Registration via Smart Indexing\n// Nicolas Mellado, Dror Aiger, Niloy J. Mitra\n// Symposium on Geometry Processing 2014.\n//\n// Data acquisition in large-scale scenes regularly involves accumulating\n// information across multiple scans. A common approach is to locally align scan\n// pairs using Iterative Closest Point (ICP) algorithm (or its variants), but\n// requires static scenes and small motion between scan pairs. This prevents\n// accumulating data across multiple scan sessions and/or different acquisition\n// modalities (e.g., stereo, depth scans). Alternatively, one can use a global\n// registration algorithm allowing scans to be in arbitrary initial poses. The\n// state-of-the-art global registration algorithm, 4PCS, however has a quadratic\n// time complexity in the number of data points. This vastly limits its\n// applicability to acquisition of large environments. We present Super 4PCS for\n// global pointcloud registration that is optimal, i.e., runs in linear time (in\n// the number of data points) and is also output sensitive in the complexity of\n// the alignment problem based on the (unknown) overlap across scan pairs.\n// Technically, we map the algorithm as an 'instance problem' and solve it\n// efficiently using a smart indexing data organization. The algorithm is\n// simple, memory-efficient, and fast. We demonstrate that Super 4PCS results in\n// significant speedup over alternative approaches and allows unstructured\n// efficient acquisition of scenes at scales previously not possible. Complete\n// source code and datasets are available for research use at\n// http://geometry.cs.ucl.ac.uk/projects/2014/super4PCS/.\n\n\n#ifndef _SUPER4PCS_ACCELERATORS_INDEXED_NORMAL_SET_HPP_\n#define _SUPER4PCS_ACCELERATORS_INDEXED_NORMAL_SET_HPP_\n\n#include <math.h>\n#include <set>\n#include <Eigen/Geometry>\n\nnamespace GlobalRegistration{\n\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::~IndexedNormalSet(){\n  for(unsigned int i = 0; i != _grid.size(); i++)\n    delete(_grid[i]);\n}\n\n/*!\n \\return Cell id corresponding to p in the euclidean grid\n \\warning p must be normalized between 0 and 1\n */\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nint\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::indexPos(\n  const Point& p) const\n{\n  // Unroll the loop over the different dimensions at compile time\n  return Utils::UnrollIndexLoop<VALIDATE_INDICES>( coordinatesPos(p),  dim-1,  _egSize );\n}\n\n/*!\n \\return Cell id corresponding to p in the euclidean grid\n \\warning p must be normalized between 0 and 1\n */\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nint\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::indexNormal(\n  const Point& n) const\n{\n  // Unroll the loop over the different dimension at compile time\n  return Utils::UnrollIndexLoop<VALIDATE_INDICES>( coordinatesNormal(n), dim-1, _ngSize);\n}\n\n\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nint\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::indexCoordinatesPos(\n  const Point& pCoord) const\n{\n  // Unroll the loop over the different dimensions at compile time\n  return Utils::UnrollIndexLoop<VALIDATE_INDICES>( pCoord,  dim-1,  _egSize );\n}\n\n\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nint\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::indexCoordinatesNormal(\n  const Point& nCoord) const\n{\n  // Unroll the loop over the different dimension at compile time\n  return Utils::UnrollIndexLoop<VALIDATE_INDICES>( nCoord,  dim-1, _ngSize);\n}\n\n\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nbool\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::addElement(\n  const Point& p,\n  const Point& n,\n  unsigned int id)\n{\n  const int pId = indexPos(p);\n  if (pId == -1) return false;\n\n  const int nId = indexNormal(n);\n  if (nId == -1) return false;\n\n  if (_grid[pId] == NULL) _grid[pId] = new AngularGrid;\n  (_grid[pId])->at(nId).push_back(id);\n\n  return true;\n}\n\n\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nvoid\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::getNeighbors(\n  const Point& p,\n  std::vector<unsigned int>&nei)\n{\n  AngularGrid* grid = angularGrid(p);\n  if ( grid == NULL ) return;\n\n  for(typename AngularGrid::const_iterator it = grid->cbegin();\n      it != grid->cend(); it++){\n    const std::vector<unsigned int>& lnei = *it;\n    nei.insert( nei.end(), lnei.begin(), lnei.end() );\n  }\n}\n\n\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nvoid\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::getNeighbors(\n  const Point& p,\n  const Point& n,\n  std::vector<unsigned int>&nei)\n{\n  AngularGrid* grid = angularGrid(p);\n  if ( grid == NULL ) return;\n\n  const std::vector<unsigned int>& lnei = grid->at(indexNormal(n));\n  nei.insert( nei.end(), lnei.begin(), lnei.end() );\n}\n\n\ntemplate <class Point, int dim, int _ngSize, typename Scalar>\nvoid\nIndexedNormalSet<Point, dim, _ngSize, Scalar>::getNeighbors(\n  const Point& p,\n  const Point& n,\n  Scalar cosAlpha,\n  std::vector<unsigned int>&nei,\n  bool tryReverse)\n{\n  AngularGrid* grid = angularGrid(p);\n  if ( grid == NULL ) return;\n\n  const Scalar alpha          = std::acos(cosAlpha);\n  const Scalar perimeter      = Scalar(2) * M_PI * std::atan(alpha);\n  const unsigned int nbSample = 2*std::ceil(perimeter*Scalar(_ngSize) /Scalar(2.));\n  const Scalar angleStep      = Scalar(2) * M_PI / Scalar(nbSample);\n\n  const Scalar sinAlpha       = std::sin(alpha);\n\n  Eigen::Quaternion<Scalar> q;\n  q.setFromTwoVectors(Point(0.,0.,1.), n);\n\n  std::set<unsigned int> colored;\n\n  // Do the rendering independently of the content\n  for(unsigned int a = 0; a != nbSample; a++){\n    Scalar theta    = Scalar(a) * angleStep;\n    const Point dir = ( q * Point(sinAlpha*std::cos(theta),\n                              sinAlpha*std::sin(theta),\n                              cosAlpha ) ).normalized();\n    int id = indexNormal( dir );\n    if(grid->at(id).size() != 0){\n      colored.insert(id);\n    }\n\n    if (tryReverse){\n      id = indexNormal( -dir );\n      if(grid->at(id).size() != 0){\n        colored.insert(id);\n      }\n    }\n  }\n\n  for( std::set<unsigned int>::const_iterator it = colored.cbegin();\n       it != colored.cend(); it++){\n    const std::vector<unsigned int>& lnei = grid->at(*it);\n    nei.insert( nei.end(), lnei.begin(), lnei.end() );\n  }\n}\n\n} // namespace Super4CS\n\n\n#endif // _INDEXED_NORMAL_SET_HPP_\n\n", "meta": {"hexsha": "82a6f35254bacddf306004a35abd8559f1543236", "size": 7242, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/super4pcs/accelerators/normalset.hpp", "max_stars_repo_name": "xinkang/Super4PCS", "max_stars_repo_head_hexsha": "ee31c7e912c5c1acbd8d811c42306dea37164d4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 378.0, "max_stars_repo_stars_event_min_datetime": "2015-01-25T11:23:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T15:57:31.000Z", "max_issues_repo_path": "src/super4pcs/accelerators/normalset.hpp", "max_issues_repo_name": "RioWong/Super4PCS", "max_issues_repo_head_hexsha": "7971c7fab0ffcbe9a2a4a517c0211edc37ba7af8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2015-09-18T06:23:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-02T19:54:26.000Z", "max_forks_repo_path": "src/super4pcs/accelerators/normalset.hpp", "max_forks_repo_name": "RioWong/Super4PCS", "max_forks_repo_head_hexsha": "7971c7fab0ffcbe9a2a4a517c0211edc37ba7af8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 159.0, "max_forks_repo_forks_event_min_datetime": "2015-01-16T19:02:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:16:03.000Z", "avg_line_length": 33.3732718894, "max_line_length": 89, "alphanum_fraction": 0.7033968517, "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.024798162087464867, "lm_q1q2_score": 0.010194793971137876}}
{"text": "#include \"simulate.hpp\"\n\n#include <iostream>\n#include <sstream>\n#include <boost/program_options.hpp>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <boost/math/distributions.hpp>\n#include <ctime>\n#include <string>\n#include <cstdlib>\n#include <sys/time.h>\n#include <omp.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"helpers.hpp\"\n#include \"policy.hpp\"\n#include \"stats.hpp\"\n\nusing namespace std;\nusing namespace boost::math;\nusing namespace boost::random;\n\nstatic const int MAX_ARMS = 10;\nstatic const string WEIGHTS_FILE = \"/home/gutin/research/mab/cpp/rewards.config\";\n\nvoid simulate(int arms, \n              unsigned long num_trials,\n              unsigned long horizon,\n              bool gaussian,\n              double a_param,\n              double b_param,\n              const string& tablefile,\n              const string& curvefile,\n              bool p_stdout)\n{\n  timeval tv;\n  gettimeofday(&tv,NULL);\n\n  boost::mt19937 seed(tv.tv_sec);\n  boost::uniform_real<> dist(0.0,1.0);\n  boost::normal_distribution<> normdist(0.0,1.0);\n  boost::uniform_int<> idist(1,1000000);\n  RandomSampleHelper bh(tv.tv_sec);\n  RandUnif urandom(seed,dist);\n  RandNorm nrandom(seed,normdist);\n   \n  RandIntUnif urandomint(seed,idist);\n\n  #ifdef _OPENMP\n  int max_threads = omp_get_max_threads();\n  RandUnif* rngs[max_threads];\n  RandNorm* nrngs[max_threads];\n  for(int i = 0; i < max_threads; ++i)\n  {\n    long randomint = urandomint();\n    boost::mt19937 subseed(randomint);\n    rngs[i] = new RandUnif(subseed, dist);\n    nrngs[i] = new RandNorm(subseed, normdist);\n  }\n  #endif\n\n  Table3D indices99;\n  if (!gaussian && horizon == 999)\n  {\n    for (unsigned int t = 1; t <= horizon+200; ++t)\n    {\n      Table indices;\n      stringstream ss;\n      ss << t;\n      string number = ss.str();\n      loadFromCSV(\"/dev/shm/gixs/hor_\" + number + \".csv\", indices, horizon, horizon);\n      indices99.push_back(indices);\n    }\n  }\n\n  #ifdef SIMMULT\n  const int minalpha = 50;\n  const int maxalpha = 150;\n  const int alphainc = 50;\n  vector<Stats> regretmult;\n  vector<Stats> g_regretmult;\n  int maxsteps = 1;\n  for (double j = minalpha; j <= maxalpha; j += alphainc)\n  {\n    for (int ksteps = 1; ksteps <= maxsteps; ksteps += 2)\n    {\n      ostringstream os;\n      os << \"OGI(\" << ksteps << \")-\" << j;\n      string name = os.str();\n      regretmult.push_back(Stats(horizon, num_trials, name));\n    }\n    ostringstream os;\n    os << \"OGI-\" << \"-\" << j;\n    string name = os.str();\n    //g_regretmult.push_back(Stats(horizon, num_trials, name));\n  }\n  #endif\n  #ifdef SIMSHD\n  Stats regretshd(horizon, num_trials, \"OGI-1\");\n  #endif\n  #ifdef SIMSHD2\n  Stats regretshd2(horizon, num_trials, \"OGI-2\");\n  #endif\n  #ifdef SIMSHD3\n  Stats regretshd3(horizon, num_trials, \"OGI-3\");\n  #endif\n  #ifdef SIMSHD5\n  Stats regretshd5(horizon, num_trials, \"OGI-5\");\n  #endif\n  #ifdef SIMNEW\n  Stats regretgit1(horizon, num_trials, \"OGI-Gaussian\");\n  #endif\n  #ifdef SIMGIT\n  Stats regretgit(horizon, num_trials, \"OGI\");\n  #endif\n  #ifdef SIMTOM\n  Stats regrettom(horizon, num_trials, \"TS\");\n  #endif\n  #ifdef SIMNAIVE\n  vector<double> regretnaive(horizon, 0);\n  #endif\n  #ifdef SIMIDS\n  Stats regretids(horizon, num_trials, \"IDS\");\n  #endif\n  #ifdef SIMIDS2\n  Stats regretids2(horizon, num_trials, \"IDS2\");\n  #endif\n  #ifdef SIMBUCB\n  Stats regretbucb(horizon, num_trials, \"Bayes UCB\");\n  #endif\n  #ifdef SIMUCB1\n  Stats regretucb1(horizon, num_trials, \"UCB1\");\n  #endif\n  #ifdef SHOWTIMING\n  clock_t timing = clock();\n  #endif\n\n  vector<double> default_mus(arms, 0);\n  loadLineFromCSV(WEIGHTS_FILE, default_mus, arms);\n  #pragma omp parallel\n  {\n    #ifdef _OPENMP\n    int threadid = omp_get_thread_num();\n    #endif\n    \n    vector<double> mus(arms, 0);\n    for(int i = 0; i < arms; ++i)\n      mus[i] = default_mus[i];\n    #pragma omp for\n    for(unsigned int trial = 0; trial < num_trials; ++trial)\n    {\n      double mustar = -1;\n      int astar = -1;\n      Table rewards(arms, vector<double>(horizon, 0));\n      vector<double> uniforms(horizon, 0);\n      for (int a = 0; a < arms; ++a)\n      { \n        #ifdef RANDARMS\n        #ifdef _OPENMP\n\t      double mu = gaussian ? (*nrngs[threadid])() : (*rngs[threadid])();\n        #endif\n        #ifndef _OPENMP\n        double mu = gaussian ? nrandom() : urandom();\n        #endif\n        #else\n        double mu = default_mus[a];\n        #endif\n\n        if (mu > mustar)\n        {\n          mustar = mu;\n          astar = a;\n        }\n        \n        for (unsigned long t = 0; t < horizon; ++t)\n        {\n          #ifdef _OPENMP\n          rewards[a][t] = gaussian ? (mu + (*nrngs[threadid])()) : ((*rngs[threadid])() < mu ? 1 : 0);\n          #endif\n          #ifndef _OPENMP\n          rewards[a][t] = gaussian ? (mu + nrandom()) : (urandom() < mu ? 1 : 0);\n          #endif\n        }\n      }\n      for (unsigned long t = 0; t < horizon; ++t)\n      {\n        #ifdef OPENMP\n        uniforms[t] = (*rngs[threadif])();\n        #else\n        uniforms[t] = urandom();\n        #endif\n      }\n      #ifdef SIMMULT\n      PolicyCollection<InterestingPolicy> pcl;\n      PolicyCollection<GittinsPolicy> gcl;\n      for (double j = minalpha; j <= maxalpha; j += alphainc)\n      {\n        for (int ksteps = 1; ksteps <= maxsteps; ksteps += 2)\n          pcl.pcs.push_back( shared_ptr<InterestingPolicy>( new InterestingPolicy(horizon, arms, 1, j, gaussian, ksteps) ) );\n        //gcl.pcs.push_back( shared_ptr<GittinsPolicy>( new GittinsPolicy(indices99, horizon, arms, j, gaussian)));\n      }\n      #endif\n      #ifdef SIMNAIVE\n      NaivePolicy naip(horizon, arms);\n      #endif\n      #ifdef SIMTOM\n      ThompsonPolicy tomp(bh, horizon, arms, gaussian);\n      #endif\n      #ifdef SIMIDS\n      #ifdef _OPENMP\n      IDSPolicy ids(horizon, uniforms, arms, gaussian, 10000);\n      #endif\n      #ifndef _OPENMP\n      IDSPolicy ids(horizon, uniforms, arms, gaussian, 10000);\n      #endif\n      #endif\n      #ifdef SIMIDS2\n      IDSPolicy ids2(horizon, uniforms, arms, gaussian, 2000);\n      #endif\n      #ifdef SIMSHD\n        #ifdef _OPENMP\n      InterestingPolicy nitp(horizon, arms, a_param, b_param, gaussian);\n        #else\n      InterestingPolicy nitp(horizon, arms, a_param, b_param, gaussian);\n        #endif\n      #endif\n      #ifdef SIMSHD2\n        #ifdef _OPENMP\n      InterestingPolicy nitp2(horizon, arms, a_param, b_param, gaussian, 2);\n        #else\n      InterestingPolicy nitp2(horizon, arms, a_param, b_param, gaussian, 2);\n        #endif\n      #endif\n      #ifdef SIMSHD3\n      InterestingPolicy nitp3(horizon, arms, a_param, b_param, gaussian, 3);\n      #endif\n      #ifdef SIMSHD5\n      InterestingPolicy nitp5(horizon, arms, a_param, b_param, gaussian, 5);\n      #endif\n      #ifdef SIMNEW\n      GittinsPolicy gitp99(indices99, horizon, arms, b_param, gaussian); \n      #endif\n      #ifdef SIMGIT\n      GittinsPolicy gitp(indices99, horizon, arms, b_param, gaussian); \n      #endif\n      #ifdef SIMBUCB\n      BayesUCBPolicy bucb(horizon, arms, gaussian);\n      #endif\n      #ifdef SIMUCB1\n      UCB1Policy ucb1(horizon, arms); \n      #endif\n      for(unsigned long t = 1; t <= horizon; ++t)\n      {\n        #ifdef SIMMULT\n        pcl.simulate(rewards, t, mustar, regretmult);\n        gcl.simulate(rewards, t, mustar, g_regretmult);\n        #endif\n        #ifdef SIMNAIVE\n        naip.simulate(rewards, t, mustar, regretnaive);\n        #endif\n        #ifdef SIMTOM\n        tomp.simulate(rewards, t, mustar, regrettom);\n        #endif\n        #ifdef SIMIDS\n        ids.simulate(rewards, t, mustar, regretids);\n        #endif\n        #ifdef SIMIDS2\n        ids2.simulate(rewards, t, mustar, regretids2);\n        #endif\n        #ifdef SIMSHD\n        nitp.simulate(rewards, t, mustar, regretshd);\n        #endif\n        #ifdef SIMSHD2\n        nitp2.simulate(rewards, t, mustar, regretshd2);\n        #endif\n        #ifdef SIMSHD3\n        nitp3.simulate(rewards, t, mustar, regretshd3);\n        #endif\n        #ifdef SIMSHD5\n        nitp5.simulate(rewards, t, mustar, regretshd5);\n        #endif\n        #ifdef SIMNEW\n        gitp99.simulate(rewards, t, mustar, regretgit1);\n        #endif\n        #ifdef SIMGIT\n        if (!gaussian && horizon == 1000)\n          gitp.simulate(rewards, t, mustar, regretgit);\n        #endif\n        #ifdef SIMBUCB\n        bucb.simulate(rewards, t, mustar, regretbucb);\n        #endif\n        #ifdef SIMUCB1\n        ucb1.simulate(rewards, t, mustar, regretucb1);\n        #endif\n      }\n    }\n  }\n  #ifdef SHOWTIMING\n  timing = clock() - timing;\n  cout << \"took \" << ((float)timing)/CLOCKS_PER_SEC << \" seconds of cpu time\" << endl;\n  #endif\n\n  vector<Stats*> algo_stats;\n  #ifndef PRINT_POLICY \n  #ifdef SIMMULT\n  for (unsigned int i = 0; i < regretmult.size(); ++i)\n    algo_stats.push_back(&regretmult[i]);\n  for (unsigned int i = 0; i < g_regretmult.size(); ++i)\n    algo_stats.push_back(&g_regretmult[i]);\n  #endif\n  #ifdef SIMNAIVE\n  printRegret(regretnaive, (double)num_trials);\n  #endif\n  #ifdef SIMNEW\n  algo_stats.push_back(&regretgit1);\n  #endif\n  #ifdef SIMGIT\n  if (!gaussian && horizon == 1000)\n    algo_stats.push_back(&regretgit);\n  #endif\n  #ifdef SIMSHD\n  algo_stats.push_back(&regretshd);\n  #endif\n  #ifdef SIMSHD2\n  algo_stats.push_back(&regretshd2);\n  #endif\n  #ifdef SIMSHD3\n  algo_stats.push_back(&regretshd3);\n  #endif\n  #ifdef SIMSHD5\n  algo_stats.push_back(&regretshd5);\n  #endif\n  #ifdef SIMIDS\n  algo_stats.push_back(&regretids);\n  #endif\n  #ifdef SIMIDS2\n  algo_stats.push_back(&regretids2);\n  #endif\n  #ifdef SIMTOM\n  algo_stats.push_back(&regrettom);\n  #endif\n  #ifdef SIMBUCB\n  algo_stats.push_back(&regretbucb);\n  #endif\n  #ifdef SIMUCB1\n  algo_stats.push_back(&regretucb1);\n  #endif\n  #endif\n  int num_algos = algo_stats.size();\n  for (int i = 0; i < num_algos; ++i)\n  {\n    Stats* stats = algo_stats[i];\n    for (int t = 0; t < stats->clen-1; ++t)\n    {\n      cout << stats->total_regret[t] << \", \";\n    }\n    cout << stats->total_regret[stats->clen-1] << endl;\n  }\n  #ifdef _OPENMP\n  for(int i = 0; i < max_threads; ++i)\n  {\n    delete rngs[i];\n    delete nrngs[i];\n  }\n  #endif\n}\n", "meta": {"hexsha": "edcaf7cc988cfad40d7017aa1bc73f921d4f7723", "size": 10080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/simulate.cpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/simulate.cpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/simulate.cpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 27.2432432432, "max_line_length": 125, "alphanum_fraction": 0.6113095238, "num_tokens": 3128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.024798161637017424, "lm_q1q2_score": 0.010194793785954035}}
{"text": "#include \"Common/Defines.h\"\n#include \"Crypto/Commit.h\"\n#include \"Common/BitVector.h\"\n//#include \"Common/Timer.h\"\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nnamespace bOPRF {\n\n\tTimer gTimer;\n\tconst block ZeroBlock = _mm_set_epi64x(0, 0);\n\tconst block OneBlock = _mm_set_epi64x(0, 1);\n\tconst block AllOneBlock = _mm_set_epi64x(u64(-1), u64(-1));\n\tconst block CCBlock = ([]() {block cc; memset(&cc, 0xcc, sizeof(block)); return cc; })();\n\n\tstd::ostream& operator<<(std::ostream& out, const block& blk)\n\t{\n\t\tout << std::hex;\n\t\tu64* data = (u64*)&blk;\n\n\t\tout << std::setw(16) << std::setfill('0') << data[0]\n\t\t\t<< std::setw(16) << std::setfill('0') << data[1];\n\n\t\tout << std::dec << std::setw(0);\n\n\t\treturn out;\n\t}\n\n\tstd::ostream& operator<<(std::ostream& out, const blockBop& blk)\n\t{\n\t\tout << std::hex;\n\t\tu64* data = (u64*)&blk;\n\n\t\tout << std::setw(16) << std::setfill('0') << data[0] << \"...\"\n\t\t\t//<< std::setw(16) << std::setfill('0') << data[1]\n\t\t\t//<< std::setw(16) << std::setfill('0') << data[2]\n\t\t\t//<< std::setw(16) << std::setfill('0') << data[3]\n\t\t\t//<< std::setw(16) << std::setfill('0') << data[4]\n\t\t\t//<< std::setw(16) << std::setfill('0') << data[5]\n\t\t\t<< std::setw(16) << std::setfill('0') << data[6];\n\n\t\tout << std::dec << std::setw(0);\n\n\t\treturn out;\n\t}\n\n\n\tstd::ostream* gOut = &std::cout;\n\n\n\n\tstd::ostream& operator<<(std::ostream& out, const Commit& comm)\n\t{\n\t\tout << std::hex;\n\n\t\tu32* data = (u32*)comm.data();\n\n\t\tout << std::setw(8) << std::setfill('0') << data[0]\n\t\t\t<< std::setw(8) << std::setfill('0') << data[1]\n\t\t\t<< std::setw(8) << std::setfill('0') << data[2]\n\t\t\t<< std::setw(8) << std::setfill('0') << data[3]\n\t\t\t<< std::setw(8) << std::setfill('0') << data[4];\n\n\t\tout << std::dec << std::setw(0);\n\n\t\treturn out;\n\t}\n\tblock PRF(const block& b, u64 i)\n\t{\n\t\t//TODO(\"REMOVE THIS!!\");\n\t\t//return b;\n\n\n\n\n\n\t\tblock ret, tweak = _mm_set1_epi64x(i), enc;\n\n\t\tret = b ^ tweak;\n\n\t\tmAesFixedKey.ecbEncBlock(ret, enc);\n\n\t\tret = ret ^ enc; // H( a0 ) \n\n\t\treturn ret;\n\t}\n\n\tvoid split(const std::string &s, char delim, std::vector<std::string> &elems) {\n\t\tstd::stringstream ss(s);\n\t\tstd::string item;\n\t\twhile (std::getline(ss, item, delim)) {\n\t\t\telems.push_back(item);\n\t\t}\n\t}\n\n\tstd::vector<std::string> split(const std::string &s, char delim) {\n\t\tstd::vector<std::string> elems;\n\t\tsplit(s, delim, elems);\n\t\treturn elems;\n\t}\n\n\tconst int tab64[64] = {\n\t\t63,  0, 58,  1, 59, 47, 53,  2,\n\t\t60, 39, 48, 27, 54, 33, 42,  3,\n\t\t61, 51, 37, 40, 49, 18, 28, 20,\n\t\t55, 30, 34, 11, 43, 14, 22,  4,\n\t\t62, 57, 46, 52, 38, 26, 32, 41,\n\t\t50, 36, 17, 19, 29, 10, 13, 21,\n\t\t56, 45, 25, 31, 35, 16,  9, 12,\n\t\t44, 24, 15,  8, 23,  7,  6,  5 };\n\n\n\tu64 log2floor(u64 value)\n\t{\n\t\tvalue |= value >> 1;\n\t\tvalue |= value >> 2;\n\t\tvalue |= value >> 4;\n\t\tvalue |= value >> 8;\n\t\tvalue |= value >> 16;\n\t\tvalue |= value >> 32;\n\t\treturn tab64[((uint64_t)((value - (value >> 1)) * 0x07EDD5E59A4E28C2)) >> 58];\n\t}\n\n\tu64 log2ceil(u64 value)\n\t{\n\t\treturn u64(std::ceil(std::log2(value)));\n\t}\n\n\tu64 get_stash_size(u64 neles) {\n\t\tif (neles >= (1 << 24))\n\t\t\treturn 2;\n\t\tif (neles >= (1 << 20))\n\t\t\treturn 3;\n\t\tif (neles >= (1 << 16))\n\t\t\treturn 4;\n\t\tif (neles >= (1 << 12))\n\t\t\treturn 6;\n\t\tif (neles >= (1 << 8))\n\t\t\treturn 12;\n\n\t\treturn 12; //other\n\n\t\tthrow std::runtime_error(\"get_stash_size: rt error at \" LOCATION);\n\n\t}\n\n\t//template<unsigned int N = 16>\n\tdouble getBinOverflowProb(u64 numBins, u64 numBalls, u64 binSize, double epsilon = 0.0001)\n\t{\n\t\tif (numBalls <= binSize)\n\t\t\treturn std::numeric_limits<double>::max();\n\n\t\tif (numBalls > unsigned(-1))\n\t\t{\n\t\t\tauto msg = (\"boost::math::binomial_coefficient(...) only supports \" + std::to_string(sizeof(unsigned) * 8) + \" bit inputs which was exceeded.\" LOCATION);\n\t\t\tstd::cout << msg << std::endl;\n\t\t\tthrow std::runtime_error(msg);\n\t\t}\n\n\t\t//try \n\t\t//{\n\n\t\t\t//std::cout << numBalls << \" \" << numBins << \" \" << binSize << std::endl;\n\t\ttypedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<16>> T;\n\t\tT sum = 0.0;\n\t\tT sec = 0.0;// minSec + 1;\n\t\tT diff = 1;\n\t\tu64 i = binSize + 1;\n\n\n\t\twhile (diff > T(epsilon) && numBalls >= i /*&& sec > minSec*/)\n\t\t{\n\t\t\tsum += numBins * boost::math::binomial_coefficient<T>(numBalls, i)\n\t\t\t\t* boost::multiprecision::pow(T(1.0) / numBins, i) * boost::multiprecision::pow(1 - T(1.0) / numBins, numBalls - i);\n\n\t\t\t//std::cout << \"sum[\" << i << \"] \" << sum << std::endl;\n\n\t\t\tT sec2 = boost::multiprecision::log2(sum);\n\t\t\tdiff = boost::multiprecision::abs(sec - sec2);\n\t\t\t//std::cout << diff << std::endl;\n\t\t\tsec = sec2;\n\n\t\t\ti++;\n\t\t}\n\n\t\treturn std::max<double>(0, (double)-sec);\n\t\t//}\n\t\t//catch (std::exception& e)\n\t\t//{\n\t\t//\tif (N == 16)\n\t\t//\t{\n\t\t//\t\tstd::cout << \"percision failure at \" << LOCATION << \"\\n tring again with high percision (performance penalty)\" << std::endl;\n\t\t//\t\t// try again with higher percition\n\t\t//\t\treturn getBinOverflowProb<128>(numBins, numBalls, binSize);\n\t\t//\t}\n\t\t//\t\t\n\t\t//\tstd::cout << \"retry percision failure at \" << LOCATION << \"\\n\" << e.what() << std::endl;\n\t\t//\tthrow;\n\t\t//}\n\t}\n\n\tu64 get_bin_size(u64 numBins, u64 numBalls, u64 statSecParam)\n\t{\n\n\t\tauto B = std::max<u64>(1, numBalls / numBins);\n\n\t\tdouble currentProb = 0;\n\t\tu64 step = 1;\n\n\t\tbool doubling = true;\n\n\t\twhile (currentProb < statSecParam || step > 1)\n\t\t{\n\t\t\tif (!step)\n\t\t\t\tthrow std::runtime_error(LOCATION);\n\n\n\t\t\tif (statSecParam > currentProb)\n\t\t\t{\n\t\t\t\tif (doubling) step = std::max<u64>(1, step * 2);\n\t\t\t\telse          step = std::max<u64>(1, step / 2);\n\n\t\t\t\tB += step;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdoubling = false;\n\t\t\t\tstep = std::max<u64>(1, step / 2);\n\t\t\t\tB -= step;\n\t\t\t}\n\t\t\tcurrentProb = getBinOverflowProb(numBins, numBalls, B);\n\t\t}\n\n\n\n\t\treturn B;\n\t\t//if (simpleSize <= cuckooSize)\n\t\t//{\n\n\t\t//\tif (simpleSize >= (1 << 24))\n\t\t//\t\treturn 28;\n\t\t//\tif (simpleSize >= (1 << 20))\n\t\t//\t\treturn 27;\n\t\t//\tif (simpleSize >= (1 << 16))\n\t\t//\t\treturn 26;\n\t\t//\tif (simpleSize >= (1 << 12))\n\t\t//\t\treturn 25;\n\t\t//\tif (simpleSize >= (1 << 8))\n\t\t//\t\treturn 24;\n\n\t\t//\t//return 30;  //other\n\t\t//}\n\t\t//else \n\t\t//{\n\t\t//\treturn simpleSize / cuckooSize + 16 + 4 * std::sqrt(simpleSize * std::log2(cuckooSize) / cuckooSize);\n\t\t//}\n\n\t\t//throw std::runtime_error(\"get_bin_size: rt error at \" LOCATION);\n\t}\n\n\tu64 get_codeword_size(u64 neles) {\n\t\tif (neles >= (1 << 24))\n\t\t\treturn 448 / 8; // in byte\n\t\tif (neles >= (1 << 20))\n\t\t\treturn 448 / 8;\n\t\tif (neles >= (1 << 16))\n\t\t\treturn 440 / 8;\n\t\tif (neles >= (1 << 12))\n\t\t\treturn 432 / 8;\n\t\tif (neles >= (1 << 8))\n\t\t\treturn 424 / 8;\n\n\t\treturn 424 / 8;\n\n\t\t//throw std::runtime_error(\"get_codeword_size: rt error at \" LOCATION);\n\t}\n\tu64 get_mask_size(u64 neles, u64 othersize, u64 statSecParam) {\n\n\n\t\treturn (statSecParam + log2(neles * othersize) + 7 ) / 8;\n\n\t\t//if (neles >= (1 << 24))\n\t\t//\treturn 88 / 8;  // in byte\n\t\t//if (neles >= (1 << 20))\n\t\t//\treturn 80 / 8;\n\t\t//if (neles >= (1 << 16))\n\t\t//\treturn 72 / 8;\n\t\t//if (neles >= (1 << 12))\n\t\t//\treturn 64 / 8;\n\t\t//if (neles >= (1 << 8))\n\t\t//\treturn 56 / 8;\n\n\t\t//return 56 / 8;\n\t\t////return (40 + 2 * log(neles)) / 8;\n\n\t//\tthrow std::runtime_error(\"get_codeword_size: rt error at \" LOCATION);\n\t}\n}\n\n\n", "meta": {"hexsha": "53993d109bd5ab577f174af6808b85b0cea462b6", "size": 7101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bOPRFlib/Common/Defines.cpp", "max_stars_repo_name": "keiyou/BaRK-OPRF", "max_stars_repo_head_hexsha": "4c633c463ec5ab9814c238a7d50b5053fad2f73b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-11-19T16:39:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T14:42:02.000Z", "max_issues_repo_path": "bOPRFlib/Common/Defines.cpp", "max_issues_repo_name": "keiyou/BaRK-OPRF", "max_issues_repo_head_hexsha": "4c633c463ec5ab9814c238a7d50b5053fad2f73b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-19T22:15:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:51:38.000Z", "max_forks_repo_path": "bOPRFlib/Common/Defines.cpp", "max_forks_repo_name": "keiyou/BaRK-OPRF", "max_forks_repo_head_hexsha": "4c633c463ec5ab9814c238a7d50b5053fad2f73b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-06-14T03:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:01:05.000Z", "avg_line_length": 23.5913621262, "max_line_length": 156, "alphanum_fraction": 0.5620335164, "num_tokens": 2681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.023689469877741762, "lm_q1q2_score": 0.010189962311203917}}
{"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 <math.h>\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 <boost/math/special_functions/round.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include \"../logger.h\"\n#include \"GdaFlexValue.h\"\n\nGdaFlexValue::GdaFlexValue()\n\t: V(1), obs(1), tms(1), is_string_lit(false),\n\t  weights_uuid(boost::uuids::nil_uuid())\n{\n\tV = 0.0;\n}\n\nGdaFlexValue::GdaFlexValue(size_t obs_, size_t tms_)\n\t: V(obs_*tms_), obs(obs_), tms(tms_), is_string_lit(false),\n\t  weights_uuid(boost::uuids::nil_uuid())\n{\n\tV = 0.0;\n}\n\nGdaFlexValue::GdaFlexValue(const std::valarray<double>& V_,\n\t\t\t\t\t\t   size_t obs_, size_t tms_)\n\t: V(V_), obs(obs_), tms(tms_), is_string_lit(false),\n\t  weights_uuid(boost::uuids::nil_uuid())\n{\n}\n\nGdaFlexValue::GdaFlexValue(const std::vector<long>& counts)\n\t: V(counts.size()), obs(counts.size()), tms(1), is_string_lit(false),\n\t  weights_uuid(boost::uuids::nil_uuid())\n{\n\tfor (size_t i=0, sz=counts.size(); i<sz; ++i) {\n\t\tV[i] = (double) counts[i];\n\t}\n}\n\nGdaFlexValue::GdaFlexValue(const double& value)\n\t: V(value, 1), obs(1), tms(1), is_string_lit(false),\n\t  weights_uuid(boost::uuids::nil_uuid())\n{\n}\n\nGdaFlexValue::GdaFlexValue(const GdaFlexValue& v)\n\t: V(v.V), obs(v.obs), tms(v.tms),\n\t  is_string_lit(v.is_string_lit), string_lit(v.string_lit),\n\t  weights_uuid(v.weights_uuid)\n{\n}\n\nGdaFlexValue::GdaFlexValue(boost::uuids::uuid u)\n\t: V(0), obs(0), tms(1), is_string_lit(false), weights_uuid(u)\n{\n}\n\nGdaFlexValue::GdaFlexValue(const wxString& str_lit)\n\t: V(0), obs(0), tms(1), is_string_lit(true), string_lit(str_lit)\n{\n\tLOG(string_lit);\n}\n\nGdaFlexValue& GdaFlexValue::operator=(const GdaFlexValue& v)\n{\n\tif (v.V.size() != V.size()) V.resize(v.V.size());\n\tV = v.V;\n\tobs = v.obs;\n\ttms = v.tms;\n\tis_string_lit = v.is_string_lit;\n\tstring_lit = v.string_lit;\n\tweights_uuid = v.weights_uuid;\n\treturn *this;\n}\n\nbool GdaFlexValue::IsStringLit() const\n{\n\treturn is_string_lit;\n}\n\nbool GdaFlexValue::IsData() const\n{\n\treturn weights_uuid.is_nil()\n\t\t&& !is_string_lit;\n}\n\nbool GdaFlexValue::IsWeights() const\n{\n\treturn !weights_uuid.is_nil() && !is_string_lit;\n}\n\nwxString GdaFlexValue::ToStr() const\n{\n\twxString s;\n\tif (IsStringLit()) {\n\t\ts << \"string literal type\\n\";\n\t\ts << \"string_lit: \" << string_lit;\n\t\treturn s;\n\t}\n\tif (IsWeights()) {\n\t\ts << \"weights type\\n\";\n\t\ts << \"weights_uuid: \" << wxString(boost::uuids::to_string(weights_uuid));\n\t\treturn s;\n\t}\n\ts << \"data type\\n\";\n\tif (V.size() == 0) return s;\n\tif (V.size() == 1) {\n\t\ts << V[0];\n\t} else {\n\t\tfor (size_t r=0; r<obs; ++r) {\n\t\t\ts << \"[\";\n\t\t\tfor (size_t t=0; t<tms-1; ++t) {\n\t\t\t\ts << V[r*tms+t] << \", \";\n\t\t\t}\n\t\t\ts << V[r*tms+tms-1] << \"]\";\n\t\t\tif (r<obs-1) s << \"\\n\";\n\t\t} \n\t}\n\treturn s;\n}\nGdaFlexValue& GdaFlexValue::operator+=(const GdaFlexValue& v)\n{\n\texception_if_not_data(*this);\n\texception_if_not_data(v);\n\tgrow_if_smaller(v);\n\t// obs >= v.obs && tms >= v.tms\n\tif (obs == v.obs && tms == v.tms) {\n\t\tV += v.V;\n\t} else if (v.V.size() == 1) {\n\t\tV += v.V[0];\n\t} else if (tms > 1 && v.tms == 1) {\n\t\tfor (size_t t=0; t<tms; ++t) {\n\t\t\tV[std::slice(t,obs,tms)] += v.V;\n\t\t}\n\t} else if (obs > 1 && v.obs == 1) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[std::slice(i*tms,tms,1)] += v.V;\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::operator-=(const GdaFlexValue& v)\n{\n\texception_if_not_data(*this);\n\texception_if_not_data(v);\n\tgrow_if_smaller(v);\n\tif (obs == v.obs && tms == v.tms) {\n\t\tV -= v.V;\n\t} else if (v.V.size() == 1) {\n\t\tV -= v.V[0];\n\t} else if (tms > 1 && v.tms == 1) {\n\t\tfor (size_t t=0; t<tms; ++t) {\n\t\t\tV[std::slice(t,obs,tms)] -= v.V;\n\t\t}\n\t} else if (obs > 1 && v.obs == 1) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[std::slice(i*tms,tms,1)] -= v.V;\n\t\t}\n\t}\n\treturn *this;\n}\n\n\nGdaFlexValue& GdaFlexValue::operator*=(const GdaFlexValue& v)\n{\n\texception_if_not_data(*this);\n\texception_if_not_data(v);\n\tgrow_if_smaller(v);\n\tif (obs == v.obs && tms == v.tms) {\n\t\tV *= v.V;\n\t} else if (v.V.size() == 1) {\n\t\tV *= v.V[0];\n\t} else if (tms > 1 && v.tms == 1) {\n\t\tfor (size_t t=0; t<tms; ++t) {\n\t\t\tV[std::slice(t,obs,tms)] *= v.V;\n\t\t}\n\t} else if (obs > 1 && v.obs == 1) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[std::slice(i*tms,tms,1)] *= v.V;\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::operator/=(const GdaFlexValue& v)\n{\n\texception_if_not_data(*this);\n\texception_if_not_data(v);\n\tgrow_if_smaller(v);\n\tif (obs == v.obs && tms == v.tms) {\n\t\tV /= v.V;\n\t} else if (v.V.size() == 1) {\n\t\tV /= v.V[0];\n\t} else if (tms > 1 && v.tms == 1) {\n\t\tfor (size_t t=0; t<tms; ++t) {\n\t\t\tV[std::slice(t,obs,tms)] /= v.V;\n\t\t}\n\t} else if (obs > 1 && v.obs == 1) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[std::slice(i*tms,tms,1)] /= v.V;\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::operator^=(const GdaFlexValue& v)\n{\n\texception_if_not_data(*this);\n\texception_if_not_data(v);\n\tgrow_if_smaller(v);\n\tif (obs == v.obs && tms == v.tms) {\n\t\tV = pow(V, v.V);\n\t} else if (v.V.size() == 1) {\n\t\tV = pow(V, v.V[0]);\n\t} else if (tms > 1 && v.tms == 1) {\n\t\tfor (size_t t=0; t<tms; ++t) {\n\t\t\tV[std::slice(t,obs,tms)] =\n\t\t\t\tpow(std::valarray<double>(V[std::slice(t,obs,tms)]), v.V);\n\t\t}\n\t} else if (obs > 1 && v.obs == 1) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[std::slice(i*tms,tms,1)] =\n\t\t\t\tpow(std::valarray<double>(V[std::slice(i*tms,tms,1)]), v.V);\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::NegateSelf()\n{\n\texception_if_not_data(*this);\n\tV = -V;\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::ApplyUniSelf(double (*f)(double))\n{\n\tLOG_MSG(\"In GdaFlexValue::ApplyUniSelf\");\n\texception_if_not_data(*this);\n\tfor (int i=0, sz=V.size(); i<sz; ++i) V[i] = f(V[i]);\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::ApplyBinarySelf(double (*f)(double, double),\n\t\t\t\t\t\t\t\t\t\t\tconst GdaFlexValue& v)\n{\n\tLOG_MSG(\"In GdaFlexValue::ApplyBinarySelf\");\n\texception_if_not_data(*this);\n\texception_if_not_data(v);\n\tgrow_if_smaller(v);\n\tGdaFlexValue cpy_v(v);\n\tcpy_v.grow_if_smaller(*this);\n\tfor (int i=0, sz=V.size(); i<sz; ++i) V[i] = f(V[i], cpy_v.V[i]);\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Sum()\n{\n\texception_if_not_data(*this);\n\tif (obs == 1) return *this;\n\tstd::valarray<double> x(0.0, tms);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tx[t] += V[i*tms+t];\n\t\t}\n\t}\n\tV = x;\n\tobs = 1;\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Mean()\n{\n\texception_if_not_data(*this);\n\tstd::valarray<double> x(0.0, tms);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tx[t] += V[i*tms+t];\n\t\t}\n\t\tx[t] /= obs;\n\t}\n\tV = x;\n\tobs = 1;\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::StdDev()\n{\n\texception_if_not_data(*this);\n\tstd::valarray<double> mean(0.0, tms);\n\tstd::valarray<double> sum_sq(0.0, tms);\n\tstd::valarray<double> sd(0.0, tms);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tmean[t] += V[i*tms+t];\n\t\t}\n\t\tmean[t] /= obs;\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[i*tms+t] -= mean[t];\n\t\t\tsum_sq[t] += V[i*tms+t] * V[i*tms+t];\n\t\t}\n\t\tsd[t] = sqrt(sum_sq[t] / (((double) obs)-1.0));\n\t}\n\tV = sd;\n\tobs = 1;\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::DevFromMean()\n{\n\texception_if_not_data(*this);\n\tstd::valarray<double> mean(0.0, tms);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tmean[t] += V[i*tms+t];\n\t\t}\n\t\tmean[t] /= obs;\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[i*tms+t] -= mean[t];\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Standardize()\n{\n\texception_if_not_data(*this);\n\tstd::valarray<double> mean(0.0, tms);\n\tstd::valarray<double> sum_sq(0.0, tms);\n\tstd::valarray<double> sd(0.0, tms);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tmean[t] += V[i*tms+t];\n\t\t}\n\t\tmean[t] /= obs;\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[i*tms+t] -= mean[t];\n\t\t\tsum_sq[t] += V[i*tms+t] * V[i*tms+t];\n\t\t}\n\t\tsd[t] = sqrt(sum_sq[t] / (((double) obs)-1.0));\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[i*tms+t] /= sd[t];\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Shuffle()\n{\n\texception_if_not_data(*this);\n    // 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, obs-1);\n\t// X(rng) -> returns a uniform random number from 0 to obs-1;\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\t// swap each item in data with a random position in data.\n\t\t\t// This will produce a random permutation\n\t\t\tsize_t r = (size_t) X(rng);\n\t\t\tdouble tmp = V[r*tms+t];\n\t\t\tV[r*tms+t] = V[i*tms+t];\n\t\t\tV[i*tms+t] = tmp;\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::UniformDist()\n{\n\texception_if_not_data(*this);\n\tstatic boost::mt19937 rng(std::time(0));\n\tstatic boost::uniform_01<boost::mt19937> X(rng);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[i*tms+t] = X();\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::GaussianDist(double mean, double sd)\n{\n\texception_if_not_data(*this);\n\tstatic boost::mt19937 rng(std::time(0));\n\tboost::normal_distribution<> norm_dist(mean, sd);\n\tboost::variate_generator<boost::mt19937&,\n\t\t\t\t\t\t\t boost::normal_distribution<> >\n\t\tX(rng, norm_dist);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[i*tms+t] = X();\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Enumerate(double from, double step)\n{\n\texception_if_not_data(*this);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tdouble x=from;\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tV[i*tms+t] = x;\n\t\t\tx+=step;\n\t\t}\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Round()\n{\n\texception_if_not_data(*this);\n\tfor (size_t i=0, sz=V.size(); i<sz; ++i) {\n\t\tV[i] = boost::math::round(V[i]);\n\t}\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Max()\n{\n\texception_if_not_data(*this);\n\tif (obs == 1) return *this;\n\tdouble pos_inf = std::numeric_limits<double>::infinity();\n\tdouble nan = std::numeric_limits<double>::quiet_NaN();\n\tstd::valarray<double> x(nan, tms);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tbool any_defined = false;\n\t\tdouble m = -pos_inf;\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tdouble v = V[i*tms+t];\n\t\t\tif (v != v) continue;\n\t\t\tany_defined = true;\n\t\t\tif (v > m) m = v;\n\t\t}\n\t\tif (any_defined) x[t] = m;\n\t}\n\tV = x;\n\tobs = 1;\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Min()\n{\n\texception_if_not_data(*this);\n\tif (obs == 1) return *this;\n\tdouble pos_inf = std::numeric_limits<double>::infinity();\n\tdouble nan = std::numeric_limits<double>::quiet_NaN();\n\tstd::valarray<double> x(nan, tms);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tbool any_defined = false;\n\t\tdouble m = pos_inf;\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tdouble v = V[i*tms+t];\n\t\t\tif (v != v) continue;\n\t\t\tany_defined = true;\n\t\t\tif (v < m) m = v;\n\t\t}\n\t\tif (any_defined) x[t] = m;\n\t}\n\tV = x;\n\tobs = 1;\n\treturn *this;\n}\n\nGdaFlexValue& GdaFlexValue::Rotate(int step)\n{\n\texception_if_not_data(*this);\n\tfor (size_t t=0; t<tms; ++t) {\n\t\tstd::vector<double> tmp(obs);\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\ttmp[i] = V[i*tms+t];\n\t\t}\n\t\tfor (size_t i=0; i<obs; ++i) {\n\t\t\tint r = (((int) i)+step+obs) % ((int) obs);\n\t\t\tV[i*tms+t] = tmp[r];\n\t\t}\n\t}\n\treturn *this;\n}\n\ndouble GdaFlexValue::GetDouble() const\n{\n\t//exception_if_not_data(*this);\n\treturn V.size() > 0 ? V[0] : std::numeric_limits<double>::quiet_NaN();\n}\n\nvoid GdaFlexValue::SetSize(size_t obs_, size_t tms_)\n{\n\tif (obs == obs_ && tms == tms_) return;\n\tobs = obs_;\n\ttms = tms_;\n\tV.resize(obs_*tms_);\n}\n\n/**\n  Increase the obs and tms dimensions to be compatible\n  with the target value.\n\n  Examples:\n\n  A = [1]  B = [1]\n               [2]\n               [3]\n\n  C = [1 2 3 4]  D = [1 2 3 4]\n                     [5 6 7 8]\n                     [9 10 11 12]\n\n  A can grow to B, C or D\n  B can grow to D\n  C can grow to D\n  B and C can not grow to each other's size,\n  but rather they must grow to D's dimentions.\n\n  eg B + C\n  B -> [1 1 1 1]  C -> [1 2 3 4]\n       [2 2 2 2]       [1 2 3 4]\n       [3 3 3 3]       [1 2 3 4]\n\n  B + C -> [2 3 4 5]\n           [3 4 5 6]\n           [4 5 6 7]\n\n  B + mean(D)  in this case mean(D) collapses to the same\n  dimensions as C\n\n  So, increase dimensions does the following:\n  increase this->obs if this->obs < v.obs\n  increase this->tms if this->tms < v.tms\n\n  Should be able to do this in a two step process. For\n  example, to make A compatible with D\n  [1] -> [1] -> [1 1 1 1]\n         [1]    [1 1 1 1]\n         [1]    [1 1 1 1]\n\n  Enumerate will always become a single columm\n  enumerate(from, step)\n\n  \n\n */\nvoid GdaFlexValue::grow_if_smaller(const GdaFlexValue& v)\n{\n\tif (obs == v.obs && tms == v.tms) return;\n\tif (obs > 1 && v.obs > 1 && obs != v.obs) {\n\t\tthrow GdaFVException(\"number of obs mismatch\");\n\t}\n\tif (tms > 1 && v.tms > 1 && tms != v.tms) {\n\t\tthrow GdaFVException(\"number of tms mismatch\");\n\t}\n\n\t// in special case where V.size() == 1, can resize\n    // much faster.\n\tif (V.size() == 1) {\n\t\tdouble t = V[0];\n\t\tV.resize(v.V.size());\n\t\tobs = v.obs;\n\t\ttms = v.tms;\n\t\tV = t;\n\t\treturn;\n\t}\n\n\t// if *this has fewer obs, then increase obs dim\n\tif (obs < v.obs) {\n\t\tstd::valarray<double> orig(V);\n\t\tV.resize(v.obs*tms);\n\t\tfor (size_t i=0; i<v.obs; ++i) {\n\t\t\tV[std::slice(i*tms,tms,1)] = orig;\n\t\t}\n\t\tobs = v.obs;\n\t}\n\n\t// if *this has fewer tms, then increase tms dim\n\tif (tms < v.tms) {\n\t\tstd::valarray<double> orig(V);\n\t\tV.resize(obs*v.tms);\n\t\tfor (size_t t=0; t<v.tms; ++t) {\n\t\t\tV[std::slice(t,obs,v.tms)] = orig;\n\t\t}\n\t\ttms = v.tms;\n\t}\n}\n\nvoid GdaFlexValue::exception_if_not_data(const GdaFlexValue& x)\n{\n\tif (!x.IsData()) {\n\t\tthrow GdaFVException(\"value expected data expression\");\n\t}\n}\n\nvoid GdaFlexValue::exception_if_not_weights(const GdaFlexValue& x)\n{\n\tif (!x.IsWeights()) {\n\t\tthrow GdaFVException(\"value expected weights expression\");\n\t}\n}\n\n", "meta": {"hexsha": "52052c4e4a66eb0ac386ab8e584a613c735f5028", "size": 14454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VarCalc/GdaFlexValue.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": "VarCalc/GdaFlexValue.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": "VarCalc/GdaFlexValue.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": 23.1634615385, "max_line_length": 75, "alphanum_fraction": 0.6054379411, "num_tokens": 5251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.03210070648551677, "lm_q1q2_score": 0.010189607796983424}}
{"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 \"Odometry.h\"\n\n#include <Eigen/Dense>\n#include <Core/Geometry/Image.h>\n#include <Core/Geometry/RGBDImage.h>\n#include <Core/Odometry/RGBDOdometryJacobian.h>\n#include <Core/Utility/Eigen.h>\n#include <Core/Utility/Timer.h>\n\nnamespace open3d {\n\nnamespace {\n\nstd::tuple<std::shared_ptr<Image>, std::shared_ptr<Image>>\n        InitializeCorrespondenceMap(int width, int height)\n{\n    // initialization: filling with any (u,v) to (-1,-1)\n    auto correspondence_map = std::make_shared<Image>();\n    auto depth_buffer = std::make_shared<Image>();\n    correspondence_map->PrepareImage(width, height, 2, 4);\n    depth_buffer->PrepareImage(width, height, 1, 4);\n    for (int v = 0; v < correspondence_map->height_; v++) {\n        for (int u = 0; u < correspondence_map->width_; u++) {\n            *PointerAt<int>(*correspondence_map, u, v, 0) = -1;\n            *PointerAt<int>(*correspondence_map, u, v, 1) = -1;\n            *PointerAt<float>(*depth_buffer, u, v, 0) = -1.0f;\n        }\n    }\n    return std::make_tuple(correspondence_map, depth_buffer);\n}\n\ninline void AddElementToCorrespondenceMap(\n        Image &correspondence_map, Image &depth_buffer,\n        int u_s, int v_s, int u_t, int v_t, float transformed_d_t) {\n    int exist_u_t, exist_v_t;\n    double exist_d_t;\n    exist_u_t = *PointerAt<int>(correspondence_map, u_s, v_s, 0);\n    exist_v_t = *PointerAt<int>(correspondence_map, u_s, v_s, 1);\n    if (exist_u_t != -1 && exist_v_t != -1) {\n        exist_d_t = *PointerAt<float>(depth_buffer, u_s, v_s);\n        if (transformed_d_t < exist_d_t) { // update nearer point as correspondence\n            *PointerAt<int>(correspondence_map, u_s, v_s, 0) = u_t;\n            *PointerAt<int>(correspondence_map, u_s, v_s, 1) = v_t;\n            *PointerAt<float>(depth_buffer, u_s, v_s) = transformed_d_t;\n        }\n    } else { // register correspondence\n        *PointerAt<int>(correspondence_map, u_s, v_s, 0) = u_t;\n        *PointerAt<int>(correspondence_map, u_s, v_s, 1) = v_t;\n        *PointerAt<float>(depth_buffer, u_s, v_s) = transformed_d_t;\n    }\n}\n\nvoid MergeCorrespondenceMaps(\n        Image &correspondence_map, Image &depth_buffer,\n        Image &correspondence_map_part, Image &depth_buffer_part)\n{\n    for (int v_s = 0; v_s < correspondence_map.height_; v_s++) {\n        for (int u_s = 0; u_s < correspondence_map.width_; u_s++) {\n            int u_t = *PointerAt<int>(correspondence_map_part, u_s, v_s, 0);\n            int v_t = *PointerAt<int>(correspondence_map_part, u_s, v_s, 1);\n            if (u_t != -1 && v_t != -1) {\n                float transformed_d_t = *PointerAt<float>(\n                        depth_buffer_part, u_s, v_s);\n                AddElementToCorrespondenceMap(correspondence_map,\n                        depth_buffer, u_s, v_s, u_t, v_t, transformed_d_t);\n            }\n        }\n    }\n}\n\nint CountCorrespondence(const Image &correspondence_map)\n{\n    int correspondence_count = 0;\n    for (int v_s = 0; v_s < correspondence_map.height_; v_s++) {\n        for (int u_s = 0; u_s < correspondence_map.width_; u_s++) {\n            int u_t = *PointerAt<int>(correspondence_map, u_s, v_s, 0);\n            int v_t = *PointerAt<int>(correspondence_map, u_s, v_s, 1);\n            if (u_t != -1 && v_t != -1) {\n                correspondence_count++;\n            }\n        }\n    }\n    return correspondence_count;\n}\n\nstd::shared_ptr<CorrespondenceSetPixelWise> ComputeCorrespondence(\n        const Eigen::Matrix3d intrinsic_matrix,\n        const Eigen::Matrix4d &extrinsic,\n        const Image &depth_s, const Image &depth_t,\n        const OdometryOption &option)\n{\n    const Eigen::Matrix3d K = intrinsic_matrix;\n    const Eigen::Matrix3d K_inv = K.inverse();\n    const Eigen::Matrix3d R = extrinsic.block<3, 3>(0, 0);\n    const Eigen::Matrix3d KRK_inv = K * R * K_inv;\n    Eigen::Vector3d Kt = K * extrinsic.block<3, 1>(0, 3);\n\n    std::shared_ptr<Image> correspondence_map;\n    std::shared_ptr<Image> depth_buffer;\n    std::tie(correspondence_map, depth_buffer) =\n            InitializeCorrespondenceMap(depth_t.width_, depth_t.height_);\n\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n#endif\n    std::shared_ptr<Image> correspondence_map_private;\n    std::shared_ptr<Image> depth_buffer_private;\n    std::tie(correspondence_map_private, depth_buffer_private) =\n            InitializeCorrespondenceMap(depth_t.width_, depth_t.height_);\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n    for (int v_s = 0; v_s < depth_s.height_; v_s++) {\n        for (int u_s = 0; u_s < depth_s.width_; u_s++) {\n            double d_s = *PointerAt<float>(depth_s, u_s, v_s);\n            if (!std::isnan(d_s)) {\n                Eigen::Vector3d uv_in_s =\n                    d_s * KRK_inv * Eigen::Vector3d(u_s, v_s, 1.0) + Kt;\n                double transformed_d_s = uv_in_s(2);\n                int u_t = (int)(uv_in_s(0) / transformed_d_s + 0.5);\n                int v_t = (int)(uv_in_s(1) / transformed_d_s + 0.5);\n                if (u_t >= 0 && u_t < depth_t.width_ &&\n                        v_t >= 0 && v_t < depth_t.height_) {\n                    double d_t = *PointerAt<float>(depth_t, u_t, v_t);\n                    if (!std::isnan(d_t) && std::abs(transformed_d_s - d_t)\n                            <= option.max_depth_diff_) {\n                        AddElementToCorrespondenceMap(\n                                *correspondence_map_private,\n                                *depth_buffer_private,\n                                u_s, v_s, u_t, v_t, (float)d_s);\n                    }\n                }\n            }\n        }\n    }\n#ifdef _OPENMP\n#pragma omp critical\n{\n#endif\n    MergeCorrespondenceMaps(\n            *correspondence_map, *depth_buffer,\n            *correspondence_map_private, *depth_buffer_private);\n#ifdef _OPENMP\n}    //    omp critical\n}    //    omp parallel\n#endif\n\n    auto correspondence = std::make_shared<CorrespondenceSetPixelWise>();\n    int correspondence_count = CountCorrespondence(*correspondence_map);\n    correspondence->resize(correspondence_count);\n    int cnt = 0;\n    for (int v_s = 0; v_s < correspondence_map->height_; v_s++) {\n        for (int u_s = 0; u_s < correspondence_map->width_; u_s++) {\n            int u_t = *PointerAt<int>(*correspondence_map, u_s, v_s, 0);\n            int v_t = *PointerAt<int>(*correspondence_map, u_s, v_s, 1);\n            if (u_t != -1 && v_t != -1) {\n                Eigen::Vector4i pixel_correspondence(u_s, v_s, u_t, v_t);\n                (*correspondence)[cnt] = pixel_correspondence;\n                cnt++;\n            }\n        }\n    }\n    return correspondence;\n}\n\nstd::shared_ptr<Image> ConvertDepthImageToXYZImage(\n        const Image &depth, const Eigen::Matrix3d &intrinsic_matrix)\n{\n    auto image_xyz = std::make_shared<Image>();\n    if (depth.num_of_channels_ != 1 || depth.bytes_per_channel_ != 4) {\n        PrintDebug(\"[ConvertDepthImageToXYZImage] Unsupported image format.\\n\");\n        return image_xyz;\n    }\n    const double inv_fx = 1.0 / intrinsic_matrix(0, 0);\n    const double inv_fy = 1.0 / intrinsic_matrix(1, 1);\n    const double ox = intrinsic_matrix(0, 2);\n    const double oy = intrinsic_matrix(1, 2);\n    image_xyz->PrepareImage(depth.width_, depth.height_, 3, 4);\n\n    for (int y = 0; y < image_xyz->height_; y++) {\n        for (int x = 0; x < image_xyz->width_; x++) {\n            float *px = PointerAt<float>(*image_xyz, x, y, 0);\n            float *py = PointerAt<float>(*image_xyz, x, y, 1);\n            float *pz = PointerAt<float>(*image_xyz, x, y, 2);\n            float z = *PointerAt<float>(depth, x, y);\n            *px = (float)((x - ox) * z * inv_fx);\n            *py = (float)((y - oy) * z * inv_fy);\n            *pz = z;\n        }\n    }\n    return image_xyz;\n}\n\nstd::vector<Eigen::Matrix3d>\n        CreateCameraMatrixPyramid(\n        const PinholeCameraIntrinsic &pinhole_camera_intrinsic, int levels)\n{\n    std::vector<Eigen::Matrix3d> pyramid_camera_matrix;\n    pyramid_camera_matrix.reserve(levels);\n    for (int i = 0; i < levels; i++) {\n        Eigen::Matrix3d level_camera_matrix;\n        if (i == 0)\n            level_camera_matrix = pinhole_camera_intrinsic.intrinsic_matrix_;\n        else\n            level_camera_matrix = 0.5 * pyramid_camera_matrix[i - 1];\n        level_camera_matrix(2, 2) = 1.;\n        pyramid_camera_matrix.push_back(level_camera_matrix);\n    }\n    return pyramid_camera_matrix;\n}\n\nEigen::Matrix6d CreateInformationMatrix(\n        const Eigen::Matrix4d &extrinsic,\n        const PinholeCameraIntrinsic &pinhole_camera_intrinsic,\n        const Image &depth_s, const Image &depth_t,\n        const OdometryOption &option)\n{\n    auto correspondence = ComputeCorrespondence(\n            pinhole_camera_intrinsic.intrinsic_matrix_,\n            extrinsic, depth_s, depth_t, option);\n\n    auto xyz_t = ConvertDepthImageToXYZImage(\n            depth_t, pinhole_camera_intrinsic.intrinsic_matrix_);\n\n    // write q^*\n    // see http://redwood-data.org/indoor/registration.html\n    // note: I comes first and q_skew is scaled by factor 2.\n    Eigen::Matrix6d GTG = Eigen::Matrix6d::Identity();\n#ifdef _OPENMP\n#pragma omp parallel\n    {\n#endif\n        Eigen::Matrix6d GTG_private = Eigen::Matrix6d::Identity();\n        Eigen::Vector6d G_r_private = Eigen::Vector6d::Zero();\n#ifdef _OPENMP\n#pragma omp for nowait\n#endif\n        for (auto row = 0; row < correspondence->size(); row++) {\n            int u_t = (*correspondence)[row](2);\n            int v_t = (*correspondence)[row](3);\n            double x = *PointerAt<float>(*xyz_t, u_t, v_t, 0);\n            double y = *PointerAt<float>(*xyz_t, u_t, v_t, 1);\n            double z = *PointerAt<float>(*xyz_t, u_t, v_t, 2);\n            G_r_private.setZero();\n            G_r_private(1) = z;\n            G_r_private(2) = -y;\n            G_r_private(3) = 1.0;\n            GTG_private.noalias() += G_r_private * G_r_private.transpose();\n            G_r_private.setZero();\n            G_r_private(0) = -z;\n            G_r_private(2) = x;\n            G_r_private(4) = 1.0;\n            GTG_private.noalias() += G_r_private * G_r_private.transpose();\n            G_r_private.setZero();\n            G_r_private(0) = y;\n            G_r_private(1) = -x;\n            G_r_private(5) = 1.0;\n            GTG_private.noalias() += G_r_private * G_r_private.transpose();\n        }\n#ifdef _OPENMP\n#pragma omp critical\n#endif\n        {\n            GTG += GTG_private;\n        }\n#ifdef _OPENMP\n    }\n#endif\n    return std::move(GTG);\n}\n\nvoid NormalizeIntensity(Image &image_s, Image &image_t,\n        CorrespondenceSetPixelWise &correspondence)\n{\n    if (image_s.width_ != image_t.width_ ||\n        image_s.height_ != image_t.height_) {\n        PrintError(\"[NormalizeIntensity] Size of two input images should be same\\n\");\n        return;\n    }\n    double mean_s = 0.0, mean_t = 0.0;\n    for (int row = 0; row < correspondence.size(); row++) {\n        int u_s = correspondence[row](0);\n        int v_s = correspondence[row](1);\n        int u_t = correspondence[row](2);\n        int v_t = correspondence[row](3);\n        mean_s += *PointerAt<float>(image_s, u_s, v_s);\n        mean_t += *PointerAt<float>(image_t, u_t, v_t);\n    }\n    mean_s /= (double)correspondence.size();\n    mean_t /= (double)correspondence.size();\n    LinearTransformImage(image_s, 0.5 / mean_s, 0.0);\n    LinearTransformImage(image_t, 0.5 / mean_t, 0.0);\n}\n\ninline std::shared_ptr<RGBDImage> PackRGBDImage(\n    const Image &color, const Image &depth) {\n    return std::make_shared<RGBDImage>(RGBDImage(color, depth));\n}\n\nstd::shared_ptr<Image> PreprocessDepth(\n        const Image &depth_orig, const OdometryOption &option)\n{\n    std::shared_ptr<Image> depth_processed = std::make_shared<Image>();\n    *depth_processed = depth_orig;\n    for (int y = 0; y < depth_processed->height_; y++) {\n        for (int x = 0; x < depth_processed->width_; x++) {\n            float *p = PointerAt<float>(*depth_processed, x, y);\n            if ((*p < option.min_depth_ || *p > option.max_depth_ || *p <= 0))\n                *p = std::numeric_limits<float>::quiet_NaN();\n        }\n    }\n    return depth_processed;\n}\n\ninline bool CheckImagePair(const Image &image_s, const Image &image_t)\n{\n    return (image_s.width_ == image_t.width_ &&\n            image_s.height_ == image_t.height_);\n}\n\ninline bool CheckRGBDImagePair(const RGBDImage &source, const RGBDImage &target)\n{\n    return (CheckImagePair(source.color_, target.color_) &&\n            CheckImagePair(source.depth_, target.depth_) &&\n            CheckImagePair(source.color_, source.depth_) &&\n            CheckImagePair(target.color_, target.depth_) &&\n            CheckImagePair(source.color_, target.color_) &&\n            source.color_.num_of_channels_ == 1 &&\n            source.depth_.num_of_channels_ == 1 &&\n            target.color_.num_of_channels_ == 1 &&\n            target.depth_.num_of_channels_ == 1 &&\n            source.color_.bytes_per_channel_ == 4 &&\n            target.color_.bytes_per_channel_ == 4 &&\n            source.depth_.bytes_per_channel_ == 4 &&\n            target.depth_.bytes_per_channel_ == 4);\n}\n\nstd::tuple<std::shared_ptr<RGBDImage>, std::shared_ptr<RGBDImage>>\n        InitializeRGBDOdometry(\n        const RGBDImage &source, const RGBDImage &target,\n        const PinholeCameraIntrinsic &pinhole_camera_intrinsic,\n        const Eigen::Matrix4d &odo_init,\n        const OdometryOption &option)\n{\n    auto source_gray = FilterImage(source.color_,\n            Image::FilterType::Gaussian3);\n    auto target_gray = FilterImage(target.color_,\n            Image::FilterType::Gaussian3);\n    auto source_depth_preprocessed = PreprocessDepth(source.depth_, option);\n    auto target_depth_preprocessed = PreprocessDepth(target.depth_, option);\n    auto source_depth = FilterImage(*source_depth_preprocessed,\n            Image::FilterType::Gaussian3);\n    auto target_depth = FilterImage(*target_depth_preprocessed,\n            Image::FilterType::Gaussian3);\n\n    auto correspondence = ComputeCorrespondence(\n            pinhole_camera_intrinsic.intrinsic_matrix_, odo_init,\n            *source_depth, *target_depth, option);\n    int corresps_count_required = (int)(source_gray->height_ *\n            source_gray->width_ * option.minimum_correspondence_ratio_ + 0.5);\n    if (correspondence->size() < corresps_count_required) {\n        PrintWarning(\"[InitializeRGBDPair] Bad initial pose\\n\");\n    }\n    NormalizeIntensity(*source_gray, *target_gray, *correspondence);\n\n    auto source_out = PackRGBDImage(*source_gray, *source_depth);\n    auto target_out = PackRGBDImage(*target_gray, *target_depth);\n    return std::make_tuple(source_out, target_out);\n}\n\nstd::tuple<bool, Eigen::Matrix4d> DoSingleIteration(\n    int iter, int level,\n    const RGBDImage &source, const RGBDImage &target,\n    const Image &source_xyz,\n    const RGBDImage &target_dx, const RGBDImage &target_dy,\n    const Eigen::Matrix3d intrinsic,\n    const Eigen::Matrix4d &extrinsic_initial,\n    const RGBDOdometryJacobian &jacobian_method,\n    const OdometryOption &option)\n{\n    auto correspondence = ComputeCorrespondence(\n            intrinsic, extrinsic_initial, source.depth_, target.depth_, option);\n    int corresps_count_required = (int)(source.color_.height_ *\n            source.color_.width_ * option.minimum_correspondence_ratio_ + 0.5);\n    int corresps_count = (int)correspondence->size();\n    if (corresps_count < corresps_count_required) {\n        PrintWarning(\"[ComputeOdometry] Too fewer correspondences (%d found / %d required)\\n\",\n                corresps_count, corresps_count_required);\n        return std::make_tuple(false, Eigen::Matrix4d::Identity());\n    }\n\n    auto f_lambda = [&]\n            (int i, std::vector<Eigen::Vector6d> &J_r, std::vector<double> &r) {\n        jacobian_method.ComputeJacobianAndResidual(i, J_r, r,\n                source, target, source_xyz, target_dx, target_dy,\n                intrinsic, extrinsic_initial, *correspondence);\n    };\n    PrintDebug(\"Iter : %d, Level : %d, \", iter, level);\n    Eigen::Matrix6d JTJ;\n    Eigen::Vector6d JTr;\n    std::tie(JTJ, JTr) = ComputeJTJandJTr<Eigen::Matrix6d, Eigen::Vector6d>(\n            f_lambda, corresps_count);\n\n    bool is_success;\n    Eigen::Matrix4d extrinsic;\n    std::tie(is_success, extrinsic) =\n            SolveJacobianSystemAndObtainExtrinsicMatrix(JTJ, JTr);\n    if (!is_success) {\n        PrintWarning(\"[ComputeOdometry] no solution!\\n\");\n        return std::make_tuple(false, Eigen::Matrix4d::Identity());\n    } else {\n        return std::make_tuple(true, extrinsic);\n    }\n}\n\nstd::tuple<bool, Eigen::Matrix4d> ComputeMultiscale(\n        const RGBDImage &source, const RGBDImage &target,\n        const PinholeCameraIntrinsic &pinhole_camera_intrinsic,\n        const Eigen::Matrix4d &extrinsic_initial,\n        const RGBDOdometryJacobian &jacobian_method,\n        const OdometryOption &option)\n{\n    std::vector<int> iter_counts = option.iteration_number_per_pyramid_level_;\n    int num_levels = (int)iter_counts.size();\n\n    auto source_pyramid = CreateRGBDImagePyramid(source, num_levels);\n    auto target_pyramid = CreateRGBDImagePyramid(target, num_levels);\n    auto target_pyramid_dx = FilterRGBDImagePyramid\n            (target_pyramid, Image::FilterType::Sobel3Dx);\n    auto target_pyramid_dy = FilterRGBDImagePyramid\n            (target_pyramid, Image::FilterType::Sobel3Dy);\n\n    Eigen::Matrix4d result_odo = extrinsic_initial.isZero() ?\n            Eigen::Matrix4d::Identity() : extrinsic_initial;\n\n    std::vector<Eigen::Matrix3d> pyramid_camera_matrix =\n            CreateCameraMatrixPyramid(pinhole_camera_intrinsic,\n            (int)iter_counts.size());\n\n    for (int level = num_levels - 1; level >= 0; level--) {\n        const Eigen::Matrix3d level_camera_matrix = pyramid_camera_matrix[level];\n\n        auto source_xyz_level = ConvertDepthImageToXYZImage(\n                source_pyramid[level]->depth_, level_camera_matrix);\n        auto source_level = PackRGBDImage(source_pyramid[level]->color_,\n                source_pyramid[level]->depth_);\n        auto target_level = PackRGBDImage(target_pyramid[level]->color_,\n                target_pyramid[level]->depth_);\n        auto target_dx_level = PackRGBDImage(target_pyramid_dx[level]->color_,\n                target_pyramid_dx[level]->depth_);\n        auto target_dy_level = PackRGBDImage(target_pyramid_dy[level]->color_,\n                target_pyramid_dy[level]->depth_);\n\n        for (int iter = 0; iter < iter_counts[num_levels - level - 1]; iter++) {\n            Eigen::Matrix4d curr_odo;\n            bool is_success;\n            std::tie(is_success, curr_odo) = DoSingleIteration(\n                iter, level,\n                *source_level, *target_level, *source_xyz_level,\n                *target_dx_level, *target_dy_level, level_camera_matrix,\n                result_odo, jacobian_method, option);\n            result_odo = curr_odo * result_odo;\n\n            if (!is_success) {\n                PrintWarning(\"[ComputeOdometry] no solution!\\n\");\n                return std::make_tuple(false, Eigen::Matrix4d::Identity());\n            }\n        }\n    }\n    return std::make_tuple(true, result_odo);\n}\n\n}    // unnamed namespace\n\nstd::tuple<bool, Eigen::Matrix4d, Eigen::Matrix6d>\n        ComputeRGBDOdometry(const RGBDImage &source, const RGBDImage &target,\n        const PinholeCameraIntrinsic &pinhole_camera_intrinsic\n        /*= PinholeCameraIntrinsic()*/,\n        const Eigen::Matrix4d &odo_init /*= Eigen::Matrix4d::Identity()*/,\n        const RGBDOdometryJacobian &jacobian_method\n        /*=RGBDOdometryJacobianFromHybridTerm*/,\n        const OdometryOption &option /*= OdometryOption()*/)\n{\n    if (!CheckRGBDImagePair(source, target)) {\n        PrintError(\"[RGBDOdometry] Two RGBD pairs should be same in size.\\n\");\n        return std::make_tuple(false,\n                Eigen::Matrix4d::Identity(), Eigen::Matrix6d::Zero());\n    }\n\n    std::shared_ptr<RGBDImage> source_processed, target_processed;\n    std::tie(source_processed, target_processed) =\n            InitializeRGBDOdometry(source, target, pinhole_camera_intrinsic,\n            odo_init, option);\n\n    Eigen::Matrix4d extrinsic;\n    bool is_success;\n    std::tie(is_success, extrinsic) = ComputeMultiscale(\n            *source_processed, *target_processed,\n            pinhole_camera_intrinsic, odo_init, jacobian_method, option);\n\n    if (is_success) {\n        Eigen::Matrix4d trans_output = extrinsic;\n        Eigen::MatrixXd info_output = CreateInformationMatrix(extrinsic,\n                pinhole_camera_intrinsic, source_processed->depth_,\n                target_processed->depth_, option);\n        return std::make_tuple(true, trans_output, info_output);\n    }\n    else {\n        return std::make_tuple(false,\n                Eigen::Matrix4d::Identity(), Eigen::Matrix6d::Identity());\n    }\n}\n\n}    // namespace open3d\n", "meta": {"hexsha": "0e880b78b67f9da93da88ddd06d5d84f568598fe", "size": 22253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/Odometry/Odometry.cpp", "max_stars_repo_name": "csjunxu/Open3D", "max_stars_repo_head_hexsha": "ef042a6c50e54c4bb56ccb4657a745c9b38c1b7f", "max_stars_repo_licenses": ["MIT"], "max_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/Odometry/Odometry.cpp", "max_issues_repo_name": "csjunxu/Open3D", "max_issues_repo_head_hexsha": "ef042a6c50e54c4bb56ccb4657a745c9b38c1b7f", "max_issues_repo_licenses": ["MIT"], "max_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/Odometry/Odometry.cpp", "max_forks_repo_name": "csjunxu/Open3D", "max_forks_repo_head_hexsha": "ef042a6c50e54c4bb56ccb4657a745c9b38c1b7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-31T07:02:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-31T07:02:30.000Z", "avg_line_length": 41.057195572, "max_line_length": 94, "alphanum_fraction": 0.6323192379, "num_tokens": 5644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.025957356538476316, "lm_q1q2_score": 0.010184026983823263}}
{"text": "//==============================================================================\n//\n//   (c) Copyright, 2010 University Corporation for Atmospheric Research (UCAR).\n//       All rights reserved.\n//       Do not copy or distribute without authorization.\n//\n//       File: $RCSfile: ruc2wrfgrid.cc,v $\n//       Version: $Revision: 1.2 $  Dated: $Date: 2010-05-05 19:29:17 $\n//\n//==============================================================================\n\n/**\n * @file ruc2wrfgrid.cc\n *\n * Convert RUC 130 conus lat-longs to WRF grid coordinates\n *\n * @date 3/25/10\n */\n\n// Include files \n#include <stdio.h>\n#include <string>\n#include <vector>\n#include <projects.h>\n#include <boost/format.hpp>\n#include \"Proj4Wrap.hh\"\n\nusing boost::format;\nusing std::string;\nusing std::vector;\n\n// Functions\n\nint main(int argc, char **argv)\n{\n  // Uses latitude where lambert conformal projection is true and\n  // median aligned with cartesian y-axis\n  double ruclov = -95;\n  double rucla1 = 16.281;\n  double ruclo1 = -126.138;\n  double ruclatin1 = 25.0;\n  double ruclatin2 = 25.0;\n  double rucdx = 13545.087;\n  double rucdy = 13545.087;\n  int rucnx = 451;\n  int rucny = 337;\n\n  string rucParamString = str(format(\"+proj=lcc +R=6371200 +lon_0=%1% +lat_0=%2% +lat_1=%3% +lat_2=%4%\") % ruclov % ruclatin1 % ruclatin1 % ruclatin2);\n\n\n\n\n  p4w::Proj4Wrap rucLambertProj(rucParamString, p4w::Proj4Wrap::LON_LAT_TYPE, ruclo1, rucla1, rucdx, rucdy);\n  printf(\"ruc false easting, false northing: %g %g\\n\", rucLambertProj.getFalseEasting(), rucLambertProj.getFalseNorthing());\n  double xc;\n  double yc;\n  double lon;\n  double lat;\n  \n  rucLambertProj.ll2xy(ruclo1, rucla1, &xc, &yc);\n  printf(\"xc, yc: %g %g\\n\", xc, yc);\n  rucLambertProj.ll2xy(-57.383, 55.481, &xc, &yc);\n  printf(\"xc, yc: %g %g\\n\", xc, yc);\n  rucLambertProj.xy2ll(0, 0, &lon, &lat);\n  printf(\"lon, lat: %g %g\\n\", lon, lat);\n\n\n  p4w::Proj4Wrap rucLambertProj1(rucParamString, p4w::Proj4Wrap::EASTING_NORTHING_TYPE, 3.33214e+06, 588890, rucdx, rucdy);\n  printf(\"EASTINGNORTHING\\n\");\n  printf(\"ruc lon lat: %g %g\\n\", rucLambertProj1.getOriginLon(), rucLambertProj1.getOriginLat());\n  \n  rucLambertProj1.ll2xy(ruclo1, rucla1, &xc, &yc);\n  printf(\"xc, yc: %g %g\\n\", xc, yc);\n  rucLambertProj1.ll2xy(-57.383, 55.481, &xc, &yc);\n  printf(\"xc, yc: %g %g\\n\", xc, yc);\n  rucLambertProj1.xy2ll(0, 0, &lon, &lat);\n  printf(\"lon, lat: %g %g\\n\", lon, lat);\n\n  p4w::Proj4Wrap rucLambertProj2(rucParamString, p4w::Proj4Wrap::EASTING_NORTHING_TYPE, 0, 0, rucdx, rucdy);\n  printf(\"EASTINGNORTHING\\n\");\n  printf(\"ruc lon lat: %g %g\\n\", rucLambertProj2.getOriginLon(), rucLambertProj2.getOriginLat());\n  \n  rucLambertProj2.ll2xy(ruclo1, rucla1, &xc, &yc);\n  printf(\"xc, yc: %g %g\\n\", xc, yc);\n  rucLambertProj2.ll2xy(-57.383, 55.481, &xc, &yc);\n  printf(\"xc, yc: %g %g\\n\", xc, yc);\n  rucLambertProj2.xy2ll(0, 0, &lon, &lat);\n  printf(\"lon, lat: %g %g\\n\", lon, lat);\n\n  double wrflov = -95;\n  double wrfla1 = 1.066;\n  double wrflo1 = -128.499;\n  double wrflatin1 = 45.0;\n  double wrflatin2 = 45.0;\n  double wrfdx = 13545.087;\n  double wrfdy = 13545.087;\n\n  printf(\"\\n\");\n  string wrfParamString = str(format(\"+proj=lcc +R=6370000 +lon_0=%1% +lat_1=%2% +lat_2=%3%\") % wrflov % wrflatin1 % wrflatin2);\n\n  p4w::Proj4Wrap wrfLambertProj(wrfParamString, p4w::Proj4Wrap::LON_LAT_TYPE, wrflo1, wrfla1, wrfdx, wrfdy);\n\n  printf(\"netcdf rucwrf_coord {\\n\");\n  printf(\"dimensions:\\n\");\n  printf(\"\\ty = %d;\\n\", rucny);\n  printf(\"\\tx = %d;\\n\", rucnx);\n  printf(\"variables:\\n\");\n  printf(\"float x(y, x);\\n\");\n  printf(\"x:long_name = \\\"x coordinate\\\";\\n\");\n  printf(\"float y(y, x);\\n\");\n  printf(\"y:long_name = \\\"y coordinate\\\";\\n\");\n  printf(\"data:\\n\");\n  printf(\"x = \\n\");\n\n  vector<float> xvec;\n  vector<float> yvec;\n  for (int i=0; i<337; i++)\n    for (int j=0; j<451; j++)\n      {\n\tdouble xc = j;\n\tdouble yc = i;\n\tdouble lat;\n\tdouble lon;\n\tdouble lat1;\n\tdouble lon1;\n\n\trucLambertProj.xy2ll(xc, yc, &lon, &lat);\n\twrfLambertProj.ll2xy(lon, lat, &xc, &yc);\n\twrfLambertProj.xy2ll(xc, yc, &lon1, &lat1);\n\n\tif (fabs(lat-lat1) > 0.000001 || fabs(lon-lon1) > 0.000001)\n\t  printf(\"ERROR: lat diff, lon diff: %g %g\\n\", fabs(lat-lat1), fabs(lon-lon1));\n\txvec.push_back(xc);\n\tyvec.push_back(yc);\n      }\n\n  int totalCt = rucnx * rucny;\n  for (int i=0; i<totalCt-1; i++)\n    {\n      printf(\"%.7lf,\\n\", xvec[i]);\n    }\n  printf(\"%.7lf;\\n\", xvec[totalCt-1]);\n\n  printf(\"y = \\n\");\n\n  for (int i=0; i<totalCt-1; i++)\n    {\n      printf(\"%.7lf,\\n\", yvec[i]);\n    }\n  printf(\"%.7lf;\\n\", yvec[totalCt-1]);\n\n  printf(\"}\\n\");\n}\n\n\n", "meta": {"hexsha": "bfb40e66e896728e018f5220412687144a8f20f0", "size": 4520, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/Proj4Wrap/src/Proj4Wrap/ruc2wrfgrid.cc", "max_stars_repo_name": "OSADP/Pikalert-Vehicle-Data-Translator-", "max_stars_repo_head_hexsha": "295da604408f6f13af0301b55476a81311459386", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-03T15:59:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-21T11:11:57.000Z", "max_issues_repo_path": "libs/Proj4Wrap/src/Proj4Wrap/ruc2wrfgrid.cc", "max_issues_repo_name": "OSADP/Pikalert-Vehicle-Data-Translator-", "max_issues_repo_head_hexsha": "295da604408f6f13af0301b55476a81311459386", "max_issues_repo_licenses": ["Apache-2.0"], "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/Proj4Wrap/src/Proj4Wrap/ruc2wrfgrid.cc", "max_forks_repo_name": "OSADP/Pikalert-Vehicle-Data-Translator-", "max_forks_repo_head_hexsha": "295da604408f6f13af0301b55476a81311459386", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-02T06:47:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-02T18:32:23.000Z", "avg_line_length": 28.9743589744, "max_line_length": 151, "alphanum_fraction": 0.6126106195, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.020332351524664102, "lm_q1q2_score": 0.010166175762332051}}
{"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 \"mps_voxels/OccupancyData.h\"\n#include \"mps_voxels/moveit_pose_type.h\"\n#include \"mps_voxels/Scene.h\"\n\n#include \"mps_voxels/LocalOctreeServer.h\" // for setBBox()\n#include \"mps_voxels/shape_utils.h\"\n#include \"mps_voxels/project_point.hpp\"\n\n#include <image_geometry/pinhole_camera_model.h>\n\n#include <Eigen/StdVector>\n\n// From https://tavianator.com/cgit/dimension.git/tree/libdimension/bvh/bvh.c#n196\n// NB: Will miss if ray is coplanar with a box face\nbool\nfast_ray_box_intersection(const Eigen::Vector3f& rayOrigin,\n                          const Eigen::Vector3f& rayVectorInv,\n                          const Eigen::Vector3f& bboxMin,\n                          const Eigen::Vector3f& bboxMax)\n{\n// This is actually correct, even though it appears not to handle edge cases\n// (ray.n.{x,y,z} == 0).  It works because the infinities that result from\n// dividing by zero will still behave correctly in the comparisons.  Rays\n// which are parallel to an axis and outside the box will have tmin == inf\n// or tmax == -inf, while rays inside the box will have tmin and tmax\n// unchanged.\n\n\tdouble tx1 = (bboxMin.x() - rayOrigin.x())*rayVectorInv.x();\n\tdouble tx2 = (bboxMax.x() - rayOrigin.x())*rayVectorInv.x();\n\n\tdouble tmin = std::min(tx1, tx2);\n\tdouble tmax = std::max(tx1, tx2);\n\n\tdouble ty1 = (bboxMin.y() - rayOrigin.y())*rayVectorInv.y();\n\tdouble ty2 = (bboxMax.y() - rayOrigin.y())*rayVectorInv.y();\n\n\ttmin = std::max(tmin, std::min(ty1, ty2));\n\ttmax = std::min(tmax, std::max(ty1, ty2));\n\n\tdouble tz1 = (bboxMin.z() - rayOrigin.z())*rayVectorInv.z();\n\tdouble tz2 = (bboxMax.z() - rayOrigin.z())*rayVectorInv.z();\n\n\ttmin = std::max(tmin, std::min(tz1, tz2));\n\ttmax = std::min(tmax, std::max(tz1, tz2));\n\n\treturn tmax >= std::max(0.0, tmin);\n}\n\nnamespace mps\n{\n\nOccupancyData::OccupancyData(std::shared_ptr<VoxelRegion> region)\n\t: voxelRegion(std::move(region)),\n\t  vertexState(voxelRegion->num_vertices(), VoxelRegion::FREE_SPACE),\n\t  edgeState(voxelRegion->num_edges(), false)\n{\n\n}\n\nOccupancyData::OccupancyData(std::shared_ptr<VoxelRegion> _region,\n                             VoxelRegion::VertexLabels _state)\n\t: voxelRegion(std::move(_region)),\n\t  vertexState(std::move(_state)),\n\t  edgeState(voxelRegion->num_edges(), false),\n\t  uniqueObjectLabels(getUniqueObjectLabels(vertexState))\n{\n\t// There's currently ~1.5M edges. Reserve this for a sparser state representation\n\t// Build the edge representation\n//\tfor (VoxelRegion::edges_size_type e = 0; e < voxelRegion->num_edges(); ++e)\n//\t{\n//\t\tconst VoxelRegion::edge_descriptor edge = voxelRegion->edge_at(e);\n//\t\tauto i = voxelRegion->index_of(source(edge, voxelRegion));\n//\t\tauto j = voxelRegion->index_of(target(edge, voxelRegion));\n//\n//\t\tedgeState[e] = (vertexState[i] == vertexState[j]);\n//\t}\n\n\t// Allocate the object representation\n\tfor (const auto& id : uniqueObjectLabels)\n\t{\n\t\tauto subtree = std::make_shared<octomap::OcTree>(voxelRegion->resolution);\n\t\tsubtree->setProbMiss(0.05);\n\t\tsubtree->setProbHit(0.95);\n\t\tsetBBox(voxelRegion->regionMin, voxelRegion->regionMax, subtree.get());\n\t\tauto res = objects.emplace(id, std::make_shared<Object>(id, subtree));\n\t\tres.first->second->minExtent = Eigen::Vector3d::Constant(std::numeric_limits<double>::max());\n\t\tres.first->second->maxExtent = Eigen::Vector3d::Constant(std::numeric_limits<double>::lowest());\n\t}\n\n\t// Populate the object representation\n\tfor (mps::VoxelRegion::vertices_size_type v = 0; v < voxelRegion->num_vertices(); ++v)\n\t{\n\t\tconst auto label = vertexState[v];\n\t\tif (label == VoxelRegion::FREE_SPACE) { continue; }\n\t\tconst auto descriptor = voxelRegion->vertex_at(v);\n\t\tconst auto coordinate = voxelRegion->coordinate_of(descriptor);\n\n\t\tObjectIndex objID(label);\n\t\tauto& obj = objects.at(objID);\n\t\tobj->occupancy->setNodeValue(coordinate.x(), coordinate.y(), coordinate.z(),\n\t\t                             std::numeric_limits<float>::max(), true);\n\t\tobj->minExtent = obj->minExtent.cwiseMin(coordinate);\n\t\tobj->maxExtent = obj->maxExtent.cwiseMax(coordinate);\n\t}\n\n\t// Prune and approximate shape data\n\tfor (auto& pair : objects)\n\t{\n\t\tpair.second->occupancy->updateInnerOccupancy();\n\t\tpair.second->approximation = approximateShape(pair.second->occupancy.get());\n\t\tassert(pair.second->approximation);\n\t}\n\n//\tsegInfo = std::make_shared<SegmentationInfo>();\n//\t*segInfo = *scene->segInfo; // Shallow copy; deep copy objectness later\n//\n//\tconst auto& os = scene->segInfo->objectness_segmentation;\n//\tsegInfo->objectness_segmentation = boost::make_shared<cv_bridge::CvImage>(\n//\t\tos->header, os->encoding,\n//\t\tcv::Mat(os->image.size(),\n//\t\t        os->image.type()));\n//\n//\tconst int segStep = 1;\n//\tsegInfo->objectness_segmentation->image = rayCastOccupancy(*this, scene->cameraModel, scene->worldTcamera, scene->roi, segStep);\n\n//\tif (scene->scenario->shouldVisualize(\"particle_segmentation\"))\n//\t{\n////\t\tIMSHOW()\n//\t}\n}\n\nObjectIndex OccupancyData::coordToObject(const Eigen::Vector3d& pt) const\n{\n\tif (!voxelRegion->isInRegion(pt)) { return ObjectIndex(VoxelRegion::FREE_SPACE); }\n\treturn ObjectIndex(vertexState.at(voxelRegion->index_of(voxelRegion->coordToVertexDesc(pt))));\n}\n\ncv::Rect2d occupancyToROI(const OccupancyData& state, const image_geometry::PinholeCameraModel& cameraModel, const moveit::Pose& worldTcamera)\n{\n\tEigen::AlignedBox2d aabb;\n\tEigen::AlignedBox2d imageAABB(Eigen::Vector2d{0, 0},\n\t                              Eigen::Vector2d{cameraModel.cameraInfo().width, cameraModel.cameraInfo().height});\n\tmoveit::Pose cameraTworld = worldTcamera.inverse(Eigen::Isometry);\n\tfor (const auto& obj : state.objects)\n\t{\n\t\t// Get all corners of box\n\t\tfor (const auto& corner : getCorners(obj.second->minExtent, obj.second->maxExtent, 3))\n\t\t{\n\t\t\tEigen::Vector3d p = cameraTworld * corner;\n\t\t\tcv::Point3d worldPt_camera(p.x(), p.y(), p.z());\n\t\t\tcv::Point2d imgPt = cameraModel.project3dToPixel(worldPt_camera);\n\t\t\tEigen::Vector2d pt{imgPt.x, imgPt.y};\n\n\t\t\taabb.extend(pt);\n\t\t}\n\t}\n\n\taabb = aabb.intersection(imageAABB);\n\n\treturn {aabb.min().x(), aabb.min().y(), aabb.max().x()-aabb.min().x(), aabb.max().y()-aabb.min().y()};\n}\n\ncv::Rect2d workspaceToROI(const VoxelRegion& region, const image_geometry::PinholeCameraModel& cameraModel, const moveit::Pose& worldTcamera)\n{\n\tEigen::AlignedBox2d aabb;\n\tEigen::AlignedBox2d imageAABB(Eigen::Vector2d{0, 0},\n\t                              Eigen::Vector2d{cameraModel.cameraInfo().width, cameraModel.cameraInfo().height});\n\tmoveit::Pose cameraTworld = worldTcamera.inverse(Eigen::Isometry);\n\n\t// Get all corners of box\n\tfor (const auto& corner : getCorners(region.regionMin, region.regionMax, 3))\n\t{\n\t\tEigen::Vector3d p = cameraTworld * corner;\n\t\tcv::Point3d worldPt_camera(p.x(), p.y(), p.z());\n\t\tcv::Point2d imgPt = cameraModel.project3dToPixel(worldPt_camera);\n\t\tEigen::Vector2d pt{imgPt.x, imgPt.y};\n\n\t\taabb.extend(pt);\n\t}\n\n\taabb = aabb.intersection(imageAABB);\n\n\treturn {aabb.min().x(), aabb.min().y(), aabb.max().x()-aabb.min().x(), aabb.max().y()-aabb.min().y()};\n}\n\n\ncv::Mat rayCastOccupancy(const OccupancyData& state, const image_geometry::PinholeCameraModel& cameraModel, const moveit::Pose& worldTcamera, const cv::Rect& roi, const int& step)\n{\n//\tauto roi = cameraModel.rectifiedRoi();\n\n\tusing LabelT = uint16_t;\n\tusing DepthT = float;\n\tcv::Mat labels = cv::Mat::zeros(cameraModel.cameraInfo().height, cameraModel.cameraInfo().width, CV_16U);\n\tcv::Mat depthBuf(cameraModel.cameraInfo().height, cameraModel.cameraInfo().width, CV_32F, std::numeric_limits<DepthT>::max());\n\n//\tstd::map<ObjectIndex, std::shared_ptr<octomap::OcTree>> labelToOcTreeLookup = particle.state->voxelRegion->vertexLabelToOctrees(particle.state->vertexState, particle.state->uniqueObjectLabels);\n//\tstd::cerr << \"labelToOcTreeLookup contains \" << labelToOcTreeLookup.size() << \" elements.\" << std::endl;\n\n\tconst Eigen::Vector3f r0_world = worldTcamera.translation().cast<float>();\n\tconst octomap::point3d cameraPose(r0_world.x(), r0_world.y(), r0_world.z());\n\n//\troi.y = 0; roi.height = cameraModel.cameraInfo().height;\n//\troi.x = 0; roi.width = cameraModel.cameraInfo().width;\n\n\t// TODO: TOO SLOW!!!\n#pragma omp parallel for\n\tfor (int v = roi.y; v < roi.y+roi.height; /*++v*/v+=step)\n\t{\n\t\tfor (int u = roi.x; u < roi.x + roi.width; /*++u*/u+=step)\n\t\t{\n\t\t\tconst Eigen::Vector3f rn_world = (worldTcamera.linear() * toPoint3D<Eigen::Vector3d>(u, v, 0.5, cameraModel).normalized()).cast<float>();\n\t\t\tconst octomap::point3d rayPoint(rn_world.x(), rn_world.y(), rn_world.z());\n\n\t\t\tconst Eigen::Vector3f rnInv_world = rn_world.cast<float>().cwiseInverse();\n\n\t\t\tfor (const auto& pair : state.objects)\n\t\t\t{\n\t\t\t\t// Check AABB intersection\n\t\t\t\tconst auto& obj = pair.second; // particle.state->objects.at(pair.first);\n\t\t\t\tbool mightHit = fast_ray_box_intersection(r0_world, rnInv_world, obj->minExtent.cast<float>(), obj->maxExtent.cast<float>());\n\t\t\t\tif (!mightHit) { continue; }\n\n\t\t\t\toctomap::point3d intsectPoint;\n\t\t\t\tif (obj->occupancy->castRay(cameraPose, rayPoint, intsectPoint, true, 2.0))\n\t\t\t\t{\n//\t\t\t\t\tstd::cerr << \"Intersection with octree \" << pair.first << std::endl;\n\t\t\t\t\tdouble dist = (intsectPoint - cameraPose).norm();\n\t\t\t\t\tauto& zBuf = depthBuf.at<DepthT>(v, u);\n\t\t\t\t\tif (dist < zBuf)\n\t\t\t\t\t{\n\t\t\t\t\t\tzBuf = dist;\n\t\t\t\t\t\tlabels.at<LabelT>(v, u) = pair.first.id; //// voxel label == 0: free sapce; seg label == 0: free space;\n//\t\t\t\t\t\tstd::cerr << \"label value: \" << labels.at<LabelT>(v, u) << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn labels;\n}\n\n}\n", "meta": {"hexsha": "8dd422f406bd11bd2fdedb4ecba65136e3ba8c09", "size": 11000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mps_voxels/src/mps_voxels/OccupancyData.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/mps_voxels/OccupancyData.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/mps_voxels/OccupancyData.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": 40.4411764706, "max_line_length": 196, "alphanum_fraction": 0.7017272727, "num_tokens": 3012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.024053553200505073, "lm_q1q2_score": 0.010162737361147324}}
{"text": "/*\nBoost Software License - Version 1.0 - August 17th, 2003\n\nPermission is hereby granted, free of charge, to any person or organization\nobtaining a copy of the software and accompanying documentation covered by\nthis license (the \"Software\") to use, reproduce, display, distribute,\nexecute, and transmit the Software, and to prepare derivative works of the\nSoftware, and to permit third-parties to whom the Software is furnished to\ndo so, all subject to the following:\n\nThe copyright notices in the Software and this entire statement, including\nthe above license grant, this restriction and the following disclaimer,\nmust be included in all copies of the Software, in whole or in part, and\nall derivative works of the Software, unless such copies or derivative\nworks are solely in the form of machine-executable object code generated by\na source language processor.\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, TITLE AND NON-INFRINGEMENT. IN NO EVENT\nSHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\nFOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n\t\t\t\t\tLicense Agreement\n\t\t\t\t\tFor Open Source Computer Vision Library\n\t\t\t\t\t(3-clause BSD License)\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   * Redistribution's of source code must retain the above copyright notice,\n     this list of conditions and the following disclaimer.\n\n   * Redistribution's 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   * The name of the copyright holders may not be used to endorse or promote products\n     derived from this software without specific prior written permission.\n\n This software is provided by the copyright holders and contributors \"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 disclaimed.\n In no event shall the Intel Corporation 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 services;\n loss of use, data, or profits; or business interruption) however caused\n and on any theory of liability, whether in contract, strict liability,\n 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     Author: Trent Weiss\n */\n\n#include \"voronoi_art/voronoi_processing/voronoi_processing.h\"\n#include \"voronoi_art/image_processing/image_processing.h\"\n#include <math.h>\n#include <boost/bind.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n#include <iostream>\n#include <boost/timer/timer.hpp>\n#include <Eigen/Dense>\nnamespace voronoi_art {\nstruct point_slope {\n\tEigen::Vector2d x;\n\tdouble y;\n};\ntypedef struct point_slope point_slope_t;\nvoronoi_processing::voronoi_processing(const Mat& input_image,\n\t\tconst std::vector<point_type>& site_points, bool extract_delaunay) {\n\tvd_.reset(new VD);\n\tinput_image_ = input_image.clone();\n\tinput_image_pixels_ = image_processing::image_to_point_vector(input_image_);\n\tsite_points_ = std::vector<point_type>(site_points);\n\t{\n\t\tboost::timer::auto_cpu_timer voronoi_timer(\"Voronoi Diagram took: %t sec CPU, %w sec real\\n\");\n\t\tconstruct_voronoi(site_points_.begin(), site_points_.end(), vd_.get());\n\t}\n\tif (extract_delaunay) {\n\t\tdelaunay_triangulation_.reset(new delaunay_triangulation);\n\t\tboost::timer::auto_cpu_timer voronoi_timer(\"Extracting Delaunay Triangulation took: %t sec CPU, %w sec real\\n\");\n\t\textract_delaunay_triangulation();\n\t}\n}\nvoronoi_processing::~voronoi_processing() {\n\t// TODO Auto-generated destructor stub\n}\n//Eigen::Vector2d po\nvoid voronoi_processing::add_delaunay_half_segments(\n\t\tVD::const_cell_iterator& it) {\n\tpoint_type site_point = point_type(site_points_[it->source_index()]);\n\tvoronoi_processing::delaunay_vertex u = boost::add_vertex<\n\t\t\tvoronoi_processing::delaunay_triangulation>(\n\t\t\t*delaunay_triangulation_);\n\t(*delaunay_triangulation_)[u] = site_point;\n\tconst voronoi_edge<VD::coordinate_type>* edge = it->incident_edge();\n\tdo {\n\t\tedge = edge->next();\n\t\tconst voronoi_vertex<VD::coordinate_type>* v0 = edge->vertex0();\n\t\tconst voronoi_vertex<VD::coordinate_type>* v1 = edge->vertex1();\n\t\tif (v0 and v1) {\n\t\t\tpoint_type p0(v0->x(), (v0->y()));\n\t\t\tpoint_type p1(v1->x(), (v1->y()));\n\t\t\tpoint_type intersection;\n\t\t\tif (p1.x() == p0.x()) {\n\t\t\t\t//edge is a vertical line segment.\n\t\t\t     intersection = point_type(p1.x(), site_point.y());\n\t\t\t} else if (p1.y() == p0.y()) {\n\t\t\t\t//edge is a horizontal line segment.\n\t\t\t     intersection = point_type(site_point.x(), p1.y());\n\t\t\t} else {\n\t\t\t\t/*\n\t\t\t\t * intersection is the solution to a system of linear equations\n\t\t\t\t * y-y_p = m * (x - x_p)\n\t\t\t\t * y-y_p = m*x - m*x_p\n\t\t\t\t * -m*x + y = y_p - m*x_p\n\t\t\t\t *\n\t\t\t\t */\n\t\t\t\tEigen::Vector2d X, Y;\n\t\t\t\tEigen::Matrix2d A = Eigen::Matrix2d::Zero();\n\t\t\t\tdouble m_edge = (p1.y() - p0.y()) / (p1.x() - p0.x());\n\t\t\t\tdouble m_line = -1.0 / m_edge;\n\t\t\t\tA(0, 0) = -m_edge;\n\t\t\t\tA(0, 1) = 1.0;\n\t\t\t\tY[0] = p0.y() - m_edge * p0.x();\n\n\t\t\t\tA(1, 0) = -m_line;\n\t\t\t\tA(1, 1) = 1.0;\n\t\t\t\tY[1] = site_point.y() - m_line * site_point.x();\n\t\t\t\tX = A.inverse() * Y;\n\t\t\t\tintersection = point_type(X.x(), X.y());\n\t\t\t}\n\t\t\tvoronoi_processing::delaunay_vertex v = boost::add_vertex<\n\t\t\t\t\tvoronoi_processing::delaunay_triangulation>(\n\t\t\t\t\t*delaunay_triangulation_);\n\t\t\t(*delaunay_triangulation_)[v] = intersection;\n\n\t\t\tdelaunay_edge e;\n\t\t\tbool b;\n\t\t\tboost::tie(e, b) = boost::add_edge<\n\t\t\t\t\tvoronoi_processing::delaunay_triangulation>(u, v,\n\t\t\t\t\t*delaunay_triangulation_);\n\t\t\t(*delaunay_triangulation_)[e] = input_image_.at<Vec3b>(\n\t\t\t\t\tcv_float_point(site_point.x(), site_point.y()));\n\t\t}\n\t} while (edge != it->incident_edge());\n}\nvoid voronoi_processing::extract_delaunay_triangulation() {\n\n\tfor (VD::const_cell_iterator it = vd_->cells().begin();\n\t\t\tit != vd_->cells().end(); ++it) {\n\n\t\tif ((not it->is_degenerate())) {\n\t\t\tadd_delaunay_half_segments(it);\n\t\t}\n\t}\n}\npoint_type voronoi_processing::cv_point_to_voronoi(const cv_float_point& pt) {\n\treturn point_type(pt.x, pt.y);\n}\n\ncv_float_point voronoi_processing::voronoi_vertex_to_cv_point(\n\t\tconst VD::vertex_type* vertex) {\n\tfloat x = (float) vertex->x();\n\tfloat y = (float) vertex->y();\n\treturn cv_float_point(x, y);\n}\n\nstd::shared_ptr<const voronoi_art::VD> voronoi_processing::get_voronoi_diagram() const {\n\treturn vd_;\n}\n\nconst std::vector<point_type>& voronoi_processing::get_site_points() const {\n\treturn site_points_;\n}\ninline double euclidean_distance(const point_type& a, const point_type& b) {\n\treturn std::sqrt(std::pow(a.x() - b.x(), 2) + std::pow(a.y() - b.y(), 2));\n}\nbool sort_functor(const point_type& a, const point_type& b,\n\t\tconst point_type& reference_point) {\n\treturn euclidean_distance(a, reference_point)\n\t\t\t< euclidean_distance(b, reference_point);\n}\nvector<cv_int_point> voronoi_processing::voronoi_cell_to_cv_int_polygon(\n\t\tconst VD::cell_type cell) {\n\n\tvector<cv_int_point> rtn;\n\tconst voronoi_edge<VD::coordinate_type>* edge = cell.incident_edge();\n\tdo {\n\t\tedge = edge->next();\n\t\tconst voronoi_vertex<VD::coordinate_type>* v0 = edge->vertex0();\n\t\tif (!v0) {\n\t\t\tcontinue;\n\t\t}\n\t\tcv_float_point pt = voronoi_vertex_to_cv_point(edge->vertex0());\n\t\trtn.push_back(cv_int_point(std::round(pt.x), std::round(pt.y)));\n\t} while (edge != cell.incident_edge());\n\treturn rtn;\n}\nvector<cv_float_point> voronoi_processing::voronoi_cell_to_cv_float_polygon(\n\t\tconst VD::cell_type cell) {\n\n\tvector<cv_float_point> rtn;\n\tconst voronoi_edge<double>* edge = cell.incident_edge();\n\tdo {\n\t\tedge = edge->next();\n\t\tconst voronoi_vertex<double>* v0 = edge->vertex0();\n\t\tif (!v0) {\n\t\t\tcontinue;\n\t\t}\n\t\trtn.push_back(voronoi_vertex_to_cv_point(edge->vertex0()));\n\t} while (edge != cell.incident_edge());\n\treturn rtn;\n}\nScalar average_color(const vector<Scalar>& colors) {\n\tunsigned long r = 0, g = 0, b = 0;\n\tfor (const Scalar& color : colors) {\n\t\tr += color[0];\n\t\tg += color[1];\n\t\tb += color[2];\n\t}\n\tfloat size = (float) colors.size();\n\tr = std::round((float) r / size);\n\tg = std::round((float) g / size);\n\tb = std::round((float) b / size);\n\treturn Scalar(r, g, b, 1.0);\n}\nvector<cv_int_point> extractIntPoints(const vector<Pixel>& pixels) {\n\tvector<cv_int_point> rtn(pixels.size());\n\tfor (unsigned int i = 0; i < rtn.size(); ++i) {\n\t\trtn[i] = pixels[i].get_int_point();\n\t}\n\treturn rtn;\n}\n\nvoid voronoi_processing::draw_cell(voronoi_art::VD::const_cell_iterator& cell,\n\t\tvector<Pixel>& pixels_copy, Mat& image) const {\n\tvector<cv_int_point> cv_poly_int = voronoi_cell_to_cv_int_polygon(*cell);\n\tpoint_type pt = site_points_[cell->source_index()];\n\tMat mask(image.size(),CV_8U, Scalar::all(0.0));\n\tcv::fillConvexPoly(mask, &cv_poly_int[0], cv_poly_int.size(), Scalar(255.0,0.0,0.0,1.0));\n\tScalar color = cv::mean(input_image_,mask);\n\n\tcv::fillConvexPoly(image, &cv_poly_int[0], cv_poly_int.size(), color);\n\n}\nvoid voronoi_processing::draw_cells(Mat& image) const {\n\n\tvector<Pixel> pixels_copy(input_image_pixels_);\n\tfor (VD::const_cell_iterator it = vd_->cells().begin();\n\t\t\tit != vd_->cells().end(); ++it) {\n\n\t\tif (it->contains_point() and (not it->is_degenerate())) {\n\n\t\t\tdraw_cell(it, pixels_copy, image);\n\t\t}\n\t}\n}\n\nvoid voronoi_processing::draw_edge(const voronoi_art::VD::edge_type& edge,\n\t\tMat& image) const {\n\n\tconst VD::vertex_type* v0 = edge.vertex0();\n\tScalar color;\n\tif (v0 and edge.next()->vertex0()) {\n\t\tint r = std::round(site_points_[edge.cell()->source_index()].y());\n\t\tint c = std::round(site_points_[edge.cell()->source_index()].x());\n\t\tcolor = input_image_.at<Vec3b>(r, c);\n\n\t\tline(image, voronoi_vertex_to_cv_point(v0),\n\t\t\t\tvoronoi_vertex_to_cv_point(edge.next()->vertex0()), color);\n\t}\n\n}\nvoid voronoi_processing::draw_edges(Mat& image) const {\n\tfor (VD::const_edge_iterator it = vd_->edges().begin();\n\t\t\tit != vd_->edges().end(); ++it) {\n\n\t\tif (it->is_primary() and (not it->is_infinite())) {\n\t\t\tdraw_edge(*it, image);\n\t\t}\n\t}\n}\n\nvoid voronoi_processing::draw_delaunay_edges(Mat& image) const {\n\n\tstd::pair<boost::graph_traits<delaunay_triangulation>::edge_iterator,\n\t\t\tboost::graph_traits<delaunay_triangulation>::edge_iterator> range =\n\t\t\tboost::edges(*delaunay_triangulation_);\n\tboost::graph_traits<delaunay_triangulation>::edge_iterator it = range.first;\n\tboost::graph_traits<delaunay_triangulation>::edge_iterator end =\n\t\t\trange.second;\n\twhile (it != end) {\n\t\tpoint_type a = (*delaunay_triangulation_)[it->m_source];\n\t\tpoint_type b = (*delaunay_triangulation_)[it->m_target];\n\n\t\tcv_float_point acv(a.x(), a.y());\n\t\tcv_float_point bcv(b.x(), b.y());\n\t\tScalar* color = (Scalar*) (it->m_eproperty);\n\t\tline(image, acv, bcv, *color);\n\t\tit++;\n\t}\n}\nvoronoi_processing::delaunay_triangulation_ptr voronoi_processing::get_delaunay_triangulation() const {\n\treturn delaunay_triangulation_ptr(delaunay_triangulation_);\n}\n\nvoid voronoi_processing::draw_delaunay_cells(Mat& image) const {\n}\n} /* namespace voronoi_art */\n\n", "meta": {"hexsha": "374c13deeed9b2760817969ea74f1ac70ddb1cef", "size": 11488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src/voronoi_processing/voronoi_processing.cpp", "max_stars_repo_name": "Electric-Turtle/voronoi-art", "max_stars_repo_head_hexsha": "fd75a807a03f564bc36e50f64b31065b0f14684e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-13T00:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T00:39:32.000Z", "max_issues_repo_path": "src/src/voronoi_processing/voronoi_processing.cpp", "max_issues_repo_name": "Electric-Turtle/voronoi-art", "max_issues_repo_head_hexsha": "fd75a807a03f564bc36e50f64b31065b0f14684e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/voronoi_processing/voronoi_processing.cpp", "max_forks_repo_name": "Electric-Turtle/voronoi-art", "max_forks_repo_head_hexsha": "fd75a807a03f564bc36e50f64b31065b0f14684e", "max_forks_repo_licenses": ["BSD-3-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.5859872611, "max_line_length": 114, "alphanum_fraction": 0.7228412256, "num_tokens": 3142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.024053550883050646, "lm_q1q2_score": 0.010162736731827809}}
{"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.hh\"\n#include \"graph_filtering.hh\"\n#include \"graph_properties.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_python_interface.hh\"\n#include \"numpy_bind.hh\"\n#include \"hash_map_wrap.hh\"\n#include \"coroutine.hh\"\n#include \"graph_python_interface.hh\"\n\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python.hpp>\n\n#if (BOOST_VERSION >= 106000)\n# include <boost/math/special_functions/relative_difference.hpp>\n#endif\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\nstruct stop_search {};\n\ntemplate <class DistMap, class PredMap>\nclass bfs_max_visitor:\n    public boost::bfs_visitor<null_visitor>\n{\npublic:\n    bfs_max_visitor(DistMap dist_map, PredMap pred, size_t max_dist,\n                    size_t source, size_t target, std::vector<size_t>& reached)\n        : _dist_map(dist_map), _pred(pred), _max_dist(max_dist),\n          _source(source), _target(target), _dist(0), _reached(reached) {}\n\n    ~bfs_max_visitor()\n    {\n        typedef typename property_traits<DistMap>::value_type dist_t;\n        constexpr dist_t inf = std::is_floating_point<dist_t>::value ?\n            numeric_limits<dist_t>::infinity() :\n            numeric_limits<dist_t>::max();\n        for (auto v : _unreached)\n            _dist_map[v] = inf;\n    }\n\n    template <class Graph>\n    void tree_edge(typename graph_traits<Graph>::edge_descriptor e,\n                   Graph& g)\n    {\n        _pred[target(e,g)] = source(e,g);\n    }\n\n    template <class Graph>\n    void examine_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                        Graph&)\n    {\n        if ( _dist_map[v] > _max_dist)\n            throw stop_search();\n    }\n\n    template <class Graph>\n    void discover_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                         Graph&)\n    {\n        auto p = _pred[v];\n        if (size_t(p) == v)\n            return;\n        _dist_map[v] = _dist_map[p] + 1;\n        _reached.push_back(v);\n        if (_dist_map[v] > _max_dist)\n            _unreached.push_back(v);\n        if (v == _target)\n            throw stop_search();\n    }\n\nprivate:\n    DistMap _dist_map;\n    PredMap _pred;\n    typename property_traits<DistMap>::value_type _max_dist;\n    size_t _source;\n    size_t _target;\n    size_t _dist;\n    std::vector<size_t> _unreached;\n    std::vector<size_t>& _reached;\n};\n\ntemplate <class DistMap, class PredMap>\nclass bfs_max_multiple_targets_visitor:\n    public boost::bfs_visitor<null_visitor>\n{\npublic:\n    bfs_max_multiple_targets_visitor(DistMap dist_map, PredMap pred,\n                                     size_t max_dist, size_t source,\n                                     gt_hash_set<std::size_t> target,\n                                     std::vector<size_t>& reached)\n        : _dist_map(dist_map), _pred(pred), _max_dist(max_dist),\n          _source(source), _target(target), _dist(0), _reached(reached) {}\n\n    ~bfs_max_multiple_targets_visitor()\n    {\n        typedef typename property_traits<DistMap>::value_type dist_t;\n        constexpr dist_t inf = std::is_floating_point<dist_t>::value ?\n            numeric_limits<dist_t>::infinity() :\n            numeric_limits<dist_t>::max();\n        for (auto v : _unreached)\n            _dist_map[v] = inf;\n    }\n\n    template <class Graph>\n    void tree_edge(typename graph_traits<Graph>::edge_descriptor e,\n                   Graph& g)\n    {\n        _pred[target(e,g)] = source(e,g);\n    }\n\n    template <class Graph>\n    void examine_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                        Graph&)\n    {\n        if ( _dist_map[v] > _max_dist)\n            throw stop_search();\n    }\n\n    template <class Graph>\n    void discover_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                         Graph&)\n    {\n        auto p = _pred[v];\n        if (size_t(p) == v)\n            return;\n        _dist_map[v] = _dist_map[p] + 1;\n\n        if (_dist_map[v] > _max_dist)\n            _unreached.push_back(v);\n\n        auto iter = _target.find(v);\n        if (iter != _target.end())\n        {\n            _target.erase(iter);\n            if (_target.empty())\n                throw stop_search();\n        };\n    }\n\nprivate:\n    DistMap _dist_map;\n    PredMap _pred;\n    typename property_traits<DistMap>::value_type _max_dist;\n    size_t _source;\n    gt_hash_set<std::size_t> _target;\n    size_t _dist;\n    std::vector<size_t> _unreached;\n    std::vector<size_t>& _reached;\n};\n\n\ntemplate <class DistMap>\nclass djk_max_visitor:\n    public boost::dijkstra_visitor<null_visitor>\n{\npublic:\n    djk_max_visitor(DistMap dist_map,\n                    typename property_traits<DistMap>::value_type max_dist,\n                    typename property_traits<DistMap>::value_type inf,\n                    size_t target, std::vector<size_t>& reached)\n        : _dist_map(dist_map), _max_dist(max_dist), _inf(inf),\n          _target(target), _reached(reached) {}\n\n    ~djk_max_visitor()\n    {\n        for (auto v : _unreached)\n            _dist_map[v] = _inf;\n    }\n\n    template <class Graph>\n    void examine_vertex(typename graph_traits<Graph>::vertex_descriptor u,\n                        Graph&)\n    {\n        if (_dist_map[u] > _max_dist)\n            throw stop_search();\n\n        if (u == _target)\n            throw stop_search();\n    }\n\n    template <class Graph>\n    void discover_vertex(typename graph_traits<Graph>::vertex_descriptor u,\n                         Graph&)\n    {\n        if (_dist_map[u] > _max_dist)\n            _unreached.push_back(u);\n        _reached.push_back(u);\n    }\n\nprivate:\n    DistMap _dist_map;\n    typename property_traits<DistMap>::value_type _max_dist;\n    typename property_traits<DistMap>::value_type _inf;\n    size_t _target;\n    std::vector<size_t> _unreached;\n    std::vector<size_t>& _reached;\n};\n\n\ntemplate <class DistMap>\nclass djk_max_multiple_targets_visitor:\n    public boost::dijkstra_visitor<null_visitor>\n{\npublic:\n    djk_max_multiple_targets_visitor(DistMap dist_map,\n                                     typename property_traits<DistMap>::value_type max_dist, \n                                     typename property_traits<DistMap>::value_type inf, \n                                     gt_hash_set<std::size_t> target,\n                                     std::vector<size_t>& reached)\n        : _dist_map(dist_map), _max_dist(max_dist), _inf(inf),\n          _target(target), _reached(reached) {}\n\n    ~djk_max_multiple_targets_visitor()\n    {\n        for (auto v : _unreached)\n            _dist_map[v] = _inf;\n    }\n\n    template <class Graph>\n    void examine_vertex(typename graph_traits<Graph>::vertex_descriptor u,\n                        Graph&)\n    {\n        if (_dist_map[u] > _max_dist)\n            throw stop_search();\n\n        auto iter = _target.find(u);\n        if (iter != _target.end())\n        {\n            _target.erase(iter);\n            if (_target.empty())\n                throw stop_search();\n        };\n    }\n\n    template <class Graph>\n    void discover_vertex(typename graph_traits<Graph>::vertex_descriptor u,\n                         Graph&)\n    {\n        if (_dist_map[u] > _max_dist)\n            _unreached.push_back(u);\n        _reached.push_back(u);\n    }\n\nprivate:\n    DistMap _dist_map;\n    typename property_traits<DistMap>::value_type _max_dist;\n    typename property_traits<DistMap>::value_type _inf;\n    gt_hash_set<std::size_t> _target;\n    std::vector<size_t> _unreached;\n    std::vector<size_t>& _reached;\n};\n\nstruct do_bfs_search\n{\n    template <class Graph, class VertexIndexMap, class DistMap, class PredMap>\n    void operator()(const Graph& g, size_t source,\n                    boost::python::object otarget_list,\n                    VertexIndexMap vertex_index, DistMap dist_map,\n                    PredMap pred_map, long double max_dist,\n                    std::vector<size_t>& reached) const\n    {\n        typedef typename property_traits<DistMap>::value_type dist_t;\n\n        auto target_list = get_array<int64_t, 1>(otarget_list);\n        gt_hash_set<std::size_t> tgt(target_list.begin(),\n                                     target_list.end());\n\n        dist_t inf = std::is_floating_point<dist_t>::value ?\n            numeric_limits<dist_t>::infinity() :\n            numeric_limits<dist_t>::max();\n\n        dist_t max_d = (max_dist > 0) ? max_dist : inf;\n\n        dist_map[source] = 0;\n\n        unchecked_vector_property_map<boost::default_color_type, VertexIndexMap>\n        color_map(vertex_index, num_vertices(g));\n        try\n        {\n            if (tgt.size() <= 1)\n            {\n                size_t target = tgt.empty() ?\n                    graph_traits<GraphInterface::multigraph_t>::null_vertex() :\n                    *tgt.begin();\n                breadth_first_visit(g, vertex(source, g),\n                                    visitor(bfs_max_visitor<DistMap, PredMap>\n                                            (dist_map, pred_map, max_d,\n                                             source, target, reached)).\n                                    vertex_index_map(vertex_index).\n                                    color_map(color_map));\n            }\n            else\n            {\n                breadth_first_visit(g, vertex(source, g),\n                                    visitor(bfs_max_multiple_targets_visitor<DistMap, PredMap>\n                                            (dist_map, pred_map, max_d,\n                                             source, tgt, reached)).\n                                    vertex_index_map(vertex_index).\n                                    color_map(color_map));\n            }\n\n        }\n        catch (stop_search&) {}\n    }\n};\n\nstruct do_djk_search\n{\n    template <class Graph, class VertexIndexMap, class DistMap, class PredMap,\n              class WeightMap>\n    void operator()(const Graph& g, size_t source,\n                    boost::python::object otarget_list,\n                    VertexIndexMap vertex_index, DistMap dist_map,\n                    PredMap pred_map, WeightMap weight, long double max_dist,\n                    std::vector<size_t>& reached) const\n    {\n        auto target_list = get_array<int64_t, 1>(otarget_list);\n\n        typedef typename property_traits<DistMap>::value_type dist_t;\n\n        constexpr dist_t inf = (std::is_floating_point<dist_t>::value) ?\n            numeric_limits<dist_t>::infinity() :\n            numeric_limits<dist_t>::max();\n\n        dist_t max_d = (max_dist > 0) ? max_dist : inf;\n\n        gt_hash_set<std::size_t> tgt(target_list.begin(),\n                                     target_list.end());\n\n        dist_map[source] = 0;\n\n        try\n        {\n            if (tgt.size() <= 1)\n            {\n                size_t target = tgt.empty() ?\n                    graph_traits<GraphInterface::multigraph_t>::null_vertex() :\n                    *tgt.begin();\n                dijkstra_shortest_paths_no_color_map_no_init\n                    (g, vertex(source, g), pred_map, dist_map, weight,\n                     vertex_index, std::less<dist_t>(),\n                     boost::closed_plus<dist_t>(), inf, dist_t(),\n                     djk_max_visitor<DistMap>(dist_map, max_d, inf, target,\n                                              reached));\n            }\n            else\n            {\n                dijkstra_shortest_paths_no_color_map_no_init\n                    (g, vertex(source, g), pred_map, dist_map, weight,\n                     vertex_index, std::less<dist_t>(),\n                     boost::closed_plus<dist_t>(), inf, dist_t(),\n                     djk_max_multiple_targets_visitor<DistMap>(dist_map, max_d,\n                                                               inf, tgt,\n                                                               reached));\n            }\n\n        }\n        catch (stop_search&) {}\n\n    }\n};\n\nstruct do_bf_search\n{\n    template <class Graph, class DistMap, class PredMap, class WeightMap>\n    void operator()(const Graph& g, size_t source, DistMap dist_map,\n                    PredMap pred_map, WeightMap weight) const\n    {\n        bool ret = bellman_ford_shortest_paths(g, root_vertex(source).\n                                               predecessor_map(pred_map).\n                                               distance_map(dist_map).\n                                               weight_map(weight));\n        if (!ret)\n            throw ValueException(\"Graph contains negative loops\");\n\n        // consistency with dijkstra\n        typedef typename property_traits<DistMap>::value_type dist_t;\n        if (std::is_floating_point<dist_t>::value)\n        {\n            for (auto v : vertices_range(g))\n            {\n                if (dist_map[v] == numeric_limits<dist_t>::max())\n                    dist_map[v] = numeric_limits<dist_t>::infinity();\n            }\n        }\n    }\n};\n\nvoid get_dists(GraphInterface& gi, size_t source, boost::python::object tgt,\n               boost::any dist_map, boost::any weight, boost::any pred_map,\n               long double max_dist, bool bf, std::vector<size_t>& reached)\n{\n    typedef property_map_type\n        ::apply<int64_t, GraphInterface::vertex_index_map_t>::type pred_map_t;\n\n    pred_map_t pmap = any_cast<pred_map_t>(pred_map);\n\n    if (weight.empty())\n    {\n        run_action<>()\n            (gi, std::bind(do_bfs_search(), std::placeholders::_1, source, tgt, gi.get_vertex_index(),\n                           std::placeholders::_2, pmap.get_unchecked(num_vertices(gi.get_graph())),\n                           max_dist, std::ref(reached)),\n             writable_vertex_scalar_properties())\n            (dist_map);\n    }\n    else\n    {\n        if (bf)\n        {\n            run_action<>()\n                (gi, std::bind(do_bf_search(), std::placeholders::_1, source,\n                               std::placeholders::_2, pmap.get_unchecked(num_vertices(gi.get_graph())),\n                               std::placeholders::_3),\n                 writable_vertex_scalar_properties(),\n                 edge_scalar_properties())\n                (dist_map, weight);\n        }\n        else\n        {\n            run_action<>()\n                (gi, std::bind(do_djk_search(), std::placeholders::_1, source, tgt, gi.get_vertex_index(),\n                               std::placeholders::_2, pmap.get_unchecked(num_vertices(gi.get_graph())),\n                               std::placeholders::_3, max_dist, std::ref(reached)),\n                 writable_vertex_scalar_properties(),\n                 edge_scalar_properties())\n                (dist_map, weight);\n        }\n    }\n}\n\ntemplate <class Graph, class Dist, class Pred, class Weight, class Preds>\nvoid get_all_preds(Graph g, Dist dist, Pred pred, Weight weight, Preds preds,\n                   long double epsilon)\n{\n    parallel_vertex_loop\n        (g,\n         [&](auto v)\n         {\n            if (size_t(pred[v]) == v)\n                return;\n            auto d = dist[v];\n            typedef decltype(d) dist_t;\n            for (auto e : in_or_out_edges_range(v, g))\n            {\n                auto u = source(e, g);\n                if (!std::is_floating_point<dist_t>::value)\n                {\n                    if (dist_t(dist[u] + get(weight, e)) == d)\n                        preds[v].push_back(u);\n                }\n                else\n                {\n#if (BOOST_VERSION >= 106000)\n                    if (boost::math::relative_difference(dist_t(dist[u] + get(weight, e)), d) < epsilon)\n                        preds[v].push_back(u);\n#else\n                    if (abs(dist_t(dist[u] + get(weight, e)) - d) < epsilon)\n                        preds[v].push_back(u);\n#endif\n                }\n            }\n         });\n};\n\nvoid do_get_all_preds(GraphInterface& gi, boost::any adist, boost::any apred,\n                      boost::any aweight, boost::any apreds,\n                      long double epsilon)\n{\n    typedef property_map_type\n        ::apply<int64_t, GraphInterface::vertex_index_map_t>::type pred_map_t;\n    typedef property_map_type\n        ::apply<vector<int64_t>, GraphInterface::vertex_index_map_t>::type preds_map_t;\n\n    pred_map_t pred = any_cast<pred_map_t>(apred);\n    preds_map_t preds = any_cast<preds_map_t>(apreds);\n\n    typedef UnityPropertyMap<int,GraphInterface::edge_t> weight_map_t;\n    typedef boost::mpl::push_back<edge_scalar_properties, weight_map_t>::type\n        weight_props_t;\n\n    if (aweight.empty())\n        aweight = weight_map_t();\n\n    run_action<>()\n        (gi, [&](auto& g, auto dist, auto weight)\n             {get_all_preds(g, dist, pred.get_unchecked(num_vertices(g)),\n                            weight, preds.get_unchecked(num_vertices(g)),\n                            epsilon);},\n         vertex_scalar_properties(), weight_props_t())(adist, aweight);\n}\n\n\ntemplate <class Pred, class Yield>\nvoid get_all_shortest_paths(size_t s, size_t t, Pred pred, Yield& yield)\n{\n    vector<size_t> path;\n    vector<pair<size_t, size_t>> stack = {{t, 0}};\n    while (!stack.empty())\n    {\n        size_t v, i;\n        std::tie(v, i) = stack.back();\n        if (v == s)\n        {\n            path.clear();\n            for (auto iter = stack.rbegin(); iter != stack.rend(); ++iter)\n                path.push_back(iter->first);\n            yield(wrap_vector_owned<size_t>(path));\n        }\n        if (pred[v].size() > i)\n        {\n            stack.emplace_back(pred[v][i], 0);\n        }\n        else\n        {\n            stack.pop_back();\n            if (!stack.empty())\n                ++stack.back().second;\n        }\n    }\n};\n\npython::object do_get_all_shortest_paths(GraphInterface& gi, size_t s, size_t t,\n                                         boost::any apred)\n{\n#ifdef HAVE_BOOST_COROUTINE\n    auto dispatch = [&](auto& yield)\n        {\n            run_action<>()\n                (gi, [&](auto&, auto pred)\n                     {get_all_shortest_paths(s, t, pred, yield);},\n                 vertex_scalar_vector_properties())(apred);\n        };\n    return python::object(CoroGenerator(dispatch));\n#else\n    throw GraphException(\"This functionality is not available because boost::coroutine was not found at compile-time\");\n#endif // HAVE_BOOST_COROUTINE\n}\n\n\ntemplate <class Graph, class Yield, class VMap>\nvoid get_all_paths(size_t s, size_t t, size_t cutoff, VMap visited,\n                   Yield& yield, Graph& g)\n{\n    typedef typename graph_traits<Graph>::out_edge_iterator eiter_t;\n    typedef std::pair<eiter_t, eiter_t> item_t;\n\n    visited[s] = true;\n    vector<size_t> vs = {s};\n    vector<item_t> stack = {out_edges(s, g)};\n    while (!stack.empty())\n    {\n        auto& pos = stack.back();\n        if (pos.first == pos.second || stack.size() > cutoff)\n        {\n            visited[vs.back()] = false;\n            vs.pop_back();\n            stack.pop_back();\n            if (!stack.empty())\n                ++stack.back().first;\n            continue;\n        }\n\n        auto v = target(*pos.first, g);\n\n        if (v == t)\n        {\n            vector<size_t> path = {s};\n            for (auto& ei : stack)\n                path.push_back(target(*ei.first, g));\n\n            yield(wrap_vector_owned<size_t>(path));\n\n            ++pos.first;\n        }\n        else\n        {\n            if (!visited[v])\n            {\n                visited[v] = true;\n                vs.push_back(v);\n                stack.push_back(out_edges(v, g));\n            }\n            else\n            {\n                ++pos.first;\n            }\n        }\n    }\n};\n\npython::object do_get_all_paths(GraphInterface& gi, size_t s, size_t t,\n                                size_t cutoff, boost::any avisited)\n{\n#ifdef HAVE_BOOST_COROUTINE\n    typedef vprop_map_t<uint8_t>::type vprop_t;\n    vprop_t visited = boost::any_cast<vprop_t>(avisited);\n    auto dispatch = [&](auto& yield)\n        {\n            run_action<>()\n            (gi, [&](auto& g) {get_all_paths(s, t, cutoff,\n                                             visited.get_unchecked(), yield,\n                                             g);})();\n        };\n    return python::object(CoroGenerator(dispatch));\n#else\n    throw GraphException(\"This functionality is not available because boost::coroutine was not found at compile-time\");\n#endif // HAVE_BOOST_COROUTINE\n}\n\nvoid export_dists()\n{\n    python::def(\"get_dists\", &get_dists);\n    python::def(\"get_all_preds\", &do_get_all_preds);\n    python::def(\"get_all_shortest_paths\", &do_get_all_shortest_paths);\n    python::def(\"get_all_paths\", &do_get_all_paths);\n};\n", "meta": {"hexsha": "ac900f4671fe643de3e8d9d96dc1f157bcab86b9", "size": 21411, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/topology/graph_distance.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_distance.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_distance.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": 33.4024960998, "max_line_length": 119, "alphanum_fraction": 0.5581243286, "num_tokens": 4709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.020964240359363787, "lm_q1q2_score": 0.010154660512071588}}
{"text": "//\tCopyright (c) 2016, Philipp Gergen, Andre Gaschler\n//\tAll rights reserved.\n//\n//\tRedistribution and use in source and binary forms, with or without\n// modification,\n//\tare permitted provided that the following conditions are met:\n//\n//\t* Redistributions of source code must retain the above copyright notice,\n// this\n//\t  list of conditions and the following disclaimer.\n//\n//\t* Redistributions in binary form must reproduce the above copyright\n// notice, this\n//\t  list of conditions and the following disclaimer in the documentation\n// and/or\n//\t  other materials provided with the distribution.\n//\n//\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n// IS\" AND\n//\tANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED\n//\tWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n//\tDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR\n//\tANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES\n//\t(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES;\n//\tLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n// AND ON\n//\tANY 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\n// THIS\n//\tSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"boundingmesh/SegmenterDownsampling.h\"\n#include \"boundingmesh/Segmenter.h\"\n\n#include <math.h>\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n\n#include <Eigen/SVD>\n\n#ifdef CGAL_AVAILABLE\n#include \"CGAL/convex_hull_2.h\"\n#include \"CGAL/Exact_predicates_inexact_constructions_kernel.h\"\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\n#endif\n\n#define MAX(a, b) (((a) > (b)) ? (a) : (b))\n#define MIN(a, b) (((a) < (b)) ? (a) : (b))\n#define MAX_Real (1.79769e+308)\n\nnamespace boundingmesh {\n\n// Returns the unit vector in the direction of the current split\nVector3 Split::directionVector() {\n  if (dimension == 0) {\n    return Vector3(1, 0, 0);\n  } else if (dimension == 1) {\n    return Vector3(0, 1, 0);\n  } else {\n    return Vector3(0, 0, 1);\n  }\n}\n\nvoid VoxelSubset::mergeSplit(AppliedSplit split) {\n  // Filter redundant splits:\n  // Each dimension can have at most 2 splits     ....|->....<-|...\n  // AppliedSplit::mergeSplits determines which plane to keep/discard\n  bool add = true;\n  for (std::vector<AppliedSplit>::iterator it = splits_.begin();\n       it != splits_.end();) {\n    int result = AppliedSplit::mergeSplitsMerge(*it, split);\n    switch (result) {\n      case 0:\n        ++it;\n        break;\n      case 1:\n        add = false;\n        ++it;\n        break;\n      case 2:\n        it = splits_.erase(it);\n        break;\n    }\n  }\n\n  if (add) splits_.push_back(split);\n}\n\nint AppliedSplit::mergeSplitsMerge(const AppliedSplit& a,\n                                   const AppliedSplit& b) {\n  /*\n   Determines the merge action for 2 splits\n   0 -> keep both\n   1 -> keep only a\n   2 -> keep only b\n   */\n  if (a.split.dimension != b.split.dimension || a.direction != b.direction)\n    return 0;\n  else if (a.direction && b.direction) {\n    // both splits are above, take higher\n    if (a.split.index > b.split.index)\n      return 2;\n    else\n      return 1;\n  } else {\n    // both splits are below, take lower\n    if (a.split.index > b.split.index)\n      return 1;\n    else\n      return 2;\n  }\n}\n\n// Merges two voxel subsets together by adding the voxels form both sets to one\n// set and recalculating the convex hull\nVoxelSubset VoxelSubset::merge(VoxelSubset other) {\n  VoxelSubset ret(*this, true);\n  for (int i = 0; i < indices_.size(); ++i) {\n    ret.addVoxel(indices_[i]);\n  }\n\n  for (int i = 0; i < other.indices_.size(); i++) {\n    ret.addVoxel(other.indices_[i]);\n  }\n\n  for (int i = 0; i < 3; i++) {\n    bool hasDirection = false;\n    bool hasNotDirection = false;\n    for (int j = 0; j < ret.splits_.size(); j++) {\n      if (ret.splits_[j].split.dimension == i) {\n        if (ret.splits_[j].direction) {\n          hasDirection = true;\n        } else {\n          hasNotDirection = true;\n        }\n      }\n    }\n    if (!hasDirection) {\n      Split split(i, -10);\n      ret.splits_.push_back(AppliedSplit(split, true));\n    }\n    if (!hasNotDirection) {\n      Split split(i, voxels_->resolution(i) + 10);\n      ret.splits_.push_back(AppliedSplit(split, false));\n    }\n  }\n\n  for (int i = 0; i < other.splits_.size(); i++) {\n    // splits_.push_back(other.splits_[i]);\n    ret.mergeSplit(other.splits_[i]);\n  }\n\n  ret.calculateConvexHullVoxel();\n  return ret;\n}\n\n// Partitions the given voxel subset into two parts according the the provided\n// split\n// This also calculates the convex hulls for both new parts\nstd::vector<VoxelSubset> VoxelSubset::partitionVoxel(Split split) {\n  return partitionVoxel(split, true);\n}\n\nstd::vector<VoxelSubset> VoxelSubset::partitionVoxel(Split split,\n                                                     bool calculateHulls) {\n  // Partition voxels of a set according to a plane\n  std::vector<VoxelSubset> subsets;\n\n  subsets.push_back(VoxelSubset(*this, true));\n  subsets.push_back(VoxelSubset(*this, true));\n\n  AppliedSplit above(split, true);\n  AppliedSplit below(split, false);\n\n  subsets[0].addSplit(above);\n  subsets[1].addSplit(below);\n\n  for (int i = 0; i < indices_.size(); ++i) {\n    const Voxel& voxel = voxels_->voxel(indices_[i]);\n    if (split.test(voxel)) {\n      subsets[0].addVoxel(indices_[i]);\n    } else {\n      subsets[1].addVoxel(indices_[i]);\n    }\n  }\n  // std::cout<<\"split \"<<split.dimension<<\" \"<<split.index<<\" Values:\n  // \"<<subsets[0].evaluate()<<\" \"<<subsets[1].evaluate()<<std::endl;\n  if (calculateHulls) {\n    subsets[0].calculateConvexHullVoxel();\n    subsets[1].calculateConvexHullVoxel();\n  }\n  return subsets;\n}\n// Returns a subset of all voxels from the current voxel subset which\n// only contains all voxels from the surface of the original mesh\nVoxelSubset VoxelSubset::getSurfaceSubset() const {\n  VoxelSubset ret = VoxelSubset(*this, true);\n  for (int i = 0; i < indices_.size(); ++i) {\n    if (voxels_->voxel(indices_[i]).type() == SURFACE) {\n      ret.addVoxel(indices_[i]);\n    }\n  }\n  return ret;\n}\n\nint VoxelSubset::voxelCount() const { return indices_.size(); }\n\n// Returns the number of voxels which are located at the surface\n// of the original mesh in the current voxel subset\nint VoxelSubset::surfaceVoxelCount() const {\n  int ret = 0;\n  for (int i = 0; i < indices_.size(); i++) {\n    if (voxels_->voxel(indices_[i]).type() == SURFACE) {\n      ret++;\n    }\n  }\n  return ret;\n}\n\n// Function calculating the area of the convex hull using\n// http://alienryderflex.com/polygon_area/\nReal convexHull2DArea(std::vector<Point_2> points) {\n  Real area = 0.0;\n  int j = points.size() - 1;\n  for (int i = 0; i < points.size(); i++) {\n    area += (points[j].x() + points[i].x()) * (points[j].y() - points[i].y());\n    j = i;\n  }\n\n  return area;\n}\n\n// Calculates the area of the 2D convex hull of a voxel set not looking\n// at the specified direction (first return value)\n// Additionally the area of the inner pixels is calculated\nvoid write2DHullWRL(std::vector<Point_2> points, std::vector<Point_2> hull,\n                    std::string filename) {\n  std::ofstream file(filename.c_str());\n  file << \"#VRML V2.0 utf8\" << std::endl << std::endl;\n  file << \"#Created by boundingmesh\" << std::endl << std::endl;\n\n  file << \"Transform {\" << std::endl;\n  file << \"\\t translation 0 0 0\" << std::endl;\n  // file << \"\\t scale \" << subset.volume() << \" \" << voxels_->voxelSize()\n  //\t\t<< \" \" << voxels_->voxelSize() << std::endl;\n  file << \"\\t children [ \" << std::endl;\n  file << \"\\t\\tShape {\" << std::endl;\n  file << \"\\t\\t\\tgeometry PointSet { \" << std::endl;\n  file << \"\\t\\t\\t\\tcoord Coordinate { \" << std::endl;\n\n  file << \"\\t\\t\\t\\t\\tpoint [\" << std::endl;\n  for (unsigned int i = 0; i < points.size(); ++i) {\n    file << \"\\t\\t\\t\\t\\t\\t\" << points[i].x() << \" \" << points[i].y() << \" 0,\"\n         << std::endl;\n  }\n  file << \"\\t\\t\\t\\t\\t]\" << std::endl;\n  file << \"\\t\\t\\t\\t}\" << std::endl;\n  file << \"\\t\\t\\t\\tcolor Color {\" << std::endl;\n  file << \"\\t\\t\\t\\t\\tcolor [\" << std::endl;\n  for (unsigned int i = 0; i < points.size(); ++i) {\n    file << \"\\t\\t\\t\\t\\t\\t0 0 1,\" << std::endl;\n  }\n  file << \"\\t\\t\\t\\t\\t]\" << std::endl;\n  file << \"\\t\\t\\t\\t}\" << std::endl;\n  file << \"\\t\\t\\t}\" << std::endl;\n  file << \"\\t\\t}\" << std::endl;\n\n  file << \"\\t\\tShape {\" << std::endl;\n  file << \"\\t\\t\\tgeometry IndexedLineSet { \" << std::endl;\n  file << \"\\t\\t\\t\\tcoord Coordinate { \" << std::endl;\n\n  file << \"\\t\\t\\t\\t\\tpoint [\" << std::endl;\n  for (unsigned int i = 0; i < hull.size(); ++i) {\n    file << \"\\t\\t\\t\\t\\t\\t\" << hull[i].x() << \" \" << hull[i].y() << \" 0,\"\n         << std::endl;\n  }\n  file << \"\\t\\t\\t\\t\\t]\" << std::endl;\n  file << \"\\t\\t\\t\\t}\" << std::endl;\n  file << \"\\t\\t\\t\\tcolor Color {\" << std::endl;\n  file << \"\\t\\t\\t\\t\\tcolor [\" << std::endl;\n  for (unsigned int i = 0; i < hull.size(); ++i) {\n    file << \"\\t\\t\\t\\t\\t\\t1 0 0,\" << std::endl;\n  }\n  file << \"\\t\\t\\t\\t\\t]\" << std::endl;\n  file << \"\\t\\t\\t\\t}\" << std::endl;\n  file << \"\\t\\t\\t\\t\\tcoordIndex [\" << std::endl;\n  for (unsigned int i = 0; i < hull.size() - 1; ++i) {\n    file << \"\\t\\t\\t\\t\\t\\t\" << i << \", \" << (i + 1) << \", -1,\" << std::endl;\n  }\n  file << \"\\t\\t\\t\\t\\t\\t\" << (hull.size() - 1) << \", 0, -1\" << std::endl;\n  file << \"\\t\\t\\t\\t\\t]\" << std::endl;\n  file << \"\\t\\t\\t\\t\\tcolorIndex [\" << std::endl;\n  for (unsigned int i = 0; i < hull.size(); ++i) {\n    file << \"\\t\\t\\t\\t\\t\\t\" << i << \", \" << std::endl;\n  }\n  file << \"\\t\\t\\t\\t\\t]\" << std::endl;\n  file << \"\\t\\t\\t}\" << std::endl;\n  file << \"\\t\\t}\" << std::endl;\n\n  file << \"\\t]\" << std::endl;\n  file << \"}\";\n}\n\nstd::pair<Real, Real> VoxelSubset::calculate2DConvexHullVolume(int direction) {\n  // Determine directions of the convex hull\n  int dir1 = (direction + 1) % 3;\n  int dir2 = (direction + 2) % 3;\n\n  ComputeBB();\n  int len1 = bounding_box_max_[dir1] - bounding_box_min_[dir1] + 1;\n  int len2 = bounding_box_max_[dir2] - bounding_box_min_[dir2] + 1;\n\n  // Create and initialize new 2D array to store point positions\n  int** points = new int*[len1];\n  for (int i = 0; i < len1; i++) {\n    points[i] = new int[len2];\n    for (int j = 0; j < len2; j++) {\n      points[i][j] = 0;\n    }\n  }\n\n  // Fill the point position array\n  for (int i = 0; i < indices_.size(); i++) {\n    const Voxel& voxel = voxels_->voxel(indices_[i]);\n    int x = voxel.coordinate(dir1) - bounding_box_min_[dir1];\n    int y = voxel.coordinate(dir2) - bounding_box_min_[dir2];\n    points[x][y] = 1;\n  }\n\n  // Calculate the real positions from the point array\n  std::vector<Point_2> pointCoordinates;\n  Vector3 origin = voxels_->origin();\n  for (int i = 0; i < len1; i++) {\n    for (int j = 0; j < len2; j++) {\n      if (points[i][j] == 1) {\n        double d1 = i * voxels_->voxelSize() + origin(dir1);\n        double d2 = j * voxels_->voxelSize() + origin(dir1);\n\n        pointCoordinates.push_back(Point_2(d1, d2));\n      }\n    }\n  }\n  // Delete unneeded points to prevent memory leaks\n  for (int i = 0; i < len1; i++) {\n    delete[] points[i];\n  }\n  delete[] points;\n\n  // Calculate the convex hull and the area of it\n  std::vector<Point_2> pointsHull;\n  CGAL::convex_hull_2(pointCoordinates.begin(), pointCoordinates.end(),\n                      std::back_inserter(pointsHull));\n  // write2DHullWRL(pointCoordinates, pointsHull, \"hull2d_\" +\n  // std::to_string(splits_.size()) + \"_\" + std::to_string(len1) + \"_\" +\n  // std::to_string(len2) + \".wrl\");\n  return std::make_pair(\n      fabs(convexHull2DArea(pointsHull)),\n      pointCoordinates.size() * voxels_->voxelSize() * voxels_->voxelSize());\n}\n\n// Calculates the convex hull from voxel subset\n// This uses one point for each of the 8 corner points of a voxel and\n// then simply calls the convex hull algorithm\nvoid VoxelSubset::calculateConvexHullVoxel() {\n  std::vector<Vector3> points;\n  bool useCenter = false;\n\n  // Generate additional points within the volume\n  // Required at intersection of 3 planes, within the volume\n  for (int i = 0; i < splits_.size(); ++i)\n    for (int j = i + 1; j < splits_.size(); ++j)\n      for (int k = j + 1; k < splits_.size(); ++k) {\n        if (splits_[i].split.dimension != splits_[j].split.dimension &&\n            splits_[i].split.dimension != splits_[k].split.dimension &&\n            splits_[j].split.dimension != splits_[k].split.dimension) {\n          Vector3 voxel_pos;\n          voxel_pos(splits_[i].split.dimension) = splits_[i].split.index;\n          voxel_pos(splits_[j].split.dimension) = splits_[j].split.index;\n          voxel_pos(splits_[k].split.dimension) = splits_[k].split.index;\n\n          if (voxel_pos(0) < 0 || voxel_pos(0) > voxels_->resolution(0) ||\n              voxel_pos(1) < 0 || voxel_pos(1) > voxels_->resolution(1) ||\n              voxel_pos(2) < 0 || voxel_pos(2) > voxels_->resolution(2)) {\n            continue;\n          }\n\n          bool neighbour_filled =\n              voxels_->voxelAt(voxel_pos(0), voxel_pos(1), voxel_pos(2)) >= 0;\n          if (voxel_pos(2) + 1 < voxels_->resolution(2))\n            neighbour_filled = neighbour_filled ||\n                               voxels_->voxelAt(voxel_pos(0), voxel_pos(1),\n                                                voxel_pos(2) + 1) >= 0;\n          if (voxel_pos(1) + 1 < voxels_->resolution(1))\n            neighbour_filled = neighbour_filled ||\n                               voxels_->voxelAt(voxel_pos(0), voxel_pos(1) + 1,\n                                                voxel_pos(2)) >= 0;\n\n          if (voxel_pos(1) + 1 < voxels_->resolution(1) &&\n              voxel_pos(2) + 1 < voxels_->resolution(2))\n            neighbour_filled = neighbour_filled ||\n                               voxels_->voxelAt(voxel_pos(0), voxel_pos(1) + 1,\n                                                voxel_pos(2) + 1) >= 0;\n          if (voxel_pos(0) + 1 < voxels_->resolution(0))\n            neighbour_filled = neighbour_filled ||\n                               voxels_->voxelAt(voxel_pos(0) + 1, voxel_pos(1),\n                                                voxel_pos(2)) >= 0;\n          if (voxel_pos(0) + 1 < voxels_->resolution(0) &&\n              voxel_pos(2) + 1 < voxels_->resolution(2))\n            neighbour_filled = neighbour_filled ||\n                               voxels_->voxelAt(voxel_pos(0) + 1, voxel_pos(1),\n                                                voxel_pos(2) + 1) >= 0;\n          if (voxel_pos(0) + 1 < voxels_->resolution(0) &&\n              voxel_pos(1) + 1 < voxels_->resolution(1))\n            neighbour_filled =\n                neighbour_filled ||\n                voxels_->voxelAt(voxel_pos(0) + 1, voxel_pos(1) + 1,\n                                 voxel_pos(2)) >= 0;\n          if (voxel_pos(0) + 1 < voxels_->resolution(0) &&\n              voxel_pos(1) + 1 < voxels_->resolution(1) &&\n              voxel_pos(2) + 1 < voxels_->resolution(2))\n            neighbour_filled =\n                neighbour_filled ||\n                voxels_->voxelAt(voxel_pos(0) + 1, voxel_pos(1) + 1,\n                                 voxel_pos(2) + 1) >= 0;\n          // Consider interior if at least one neighbouring voxel is filled\n          if (!neighbour_filled) {\n            continue;\n          }\n          Vector3 offset;\n          offset(splits_[i].split.dimension) =\n              (splits_[i].split.index + 0.5) * voxels_->voxelSize();\n          offset(splits_[j].split.dimension) =\n              (splits_[j].split.index + 0.5) * voxels_->voxelSize();\n          offset(splits_[k].split.dimension) =\n              (splits_[k].split.index + 0.5) * voxels_->voxelSize();\n          Vector3 new_point = voxels_->origin() + offset;\n          points.push_back(new_point);\n        }\n      }\n\n  Vector3 origin = voxels_->origin();\n\n  if (useCenter) {\n    for (int i = 0; i < indices_.size(); i++) {\n      const Voxel& voxel = voxels_->voxel(indices_[i]);\n      if (voxels_->voxel(indices_[i]).type() == SURFACE) {\n        double xp = voxel.x() * voxels_->voxelSize() + origin(0);\n        double yp = voxel.y() * voxels_->voxelSize() + origin(1);\n        double zp = voxel.z() * voxels_->voxelSize() + origin(2);\n        points.push_back(Vector3(xp, yp, zp));\n      }\n    }\n  } else {\n    for (int i = 0; i < indices_.size(); i++) {\n      const Voxel& voxel = voxels_->voxel(indices_[i]);\n      if (voxels_->voxel(indices_[i]).type() == SURFACE) {\n        double xp = (voxel.x() + 0.5) * voxels_->voxelSize() + origin(0);\n        double yp = (voxel.y() + 0.5) * voxels_->voxelSize() + origin(1);\n        double zp = (voxel.z() + 0.5) * voxels_->voxelSize() + origin(2);\n        double xm = (voxel.x() - 0.5) * voxels_->voxelSize() + origin(0);\n        double ym = (voxel.y() - 0.5) * voxels_->voxelSize() + origin(1);\n        double zm = (voxel.z() - 0.5) * voxels_->voxelSize() + origin(2);\n        points.push_back(Vector3(xp, yp, zp));\n        points.push_back(Vector3(xp, yp, zm));\n        points.push_back(Vector3(xp, ym, zp));\n        points.push_back(Vector3(xp, ym, zm));\n        points.push_back(Vector3(xm, yp, zp));\n        points.push_back(Vector3(xm, yp, zm));\n        points.push_back(Vector3(xm, ym, zp));\n        points.push_back(Vector3(xm, ym, zm));\n      }\n    }\n  }\n  // std::cout << \"Calculating convex hull with number of points: \"\n  //\t\t<< points.size() << std::endl;\n  if (points.size() > 3)\n    convex_hull_ = Convex(points);\n  else\n    convex_hull_ = Convex();\n\n  // convex_hull_.volume = convex_hull_.ComputeVolume();\n}\n\n// Simply method for debugging purposes which outputs a given voxel subset\n// to a file in WRL file format\nvoid VoxelSubset::writeWRL(std::string filename, bool debugTriangles) {\n  std::ofstream file(filename.c_str());\n  file << \"#VRML V2.0 utf8\" << std::endl << std::endl;\n  file << \"#Created by boundingmesh\" << std::endl << std::endl;\n  file << \"Transform {\" << std::endl;\n  file << \"\\t translation \" << voxels_->origin()(0) << \" \"\n       << voxels_->origin()(1) << \" \" << voxels_->origin()(2) << std::endl;\n  file << \"\\t scale \" << voxels_->voxelSize() << \" \" << voxels_->voxelSize()\n       << \" \" << voxels_->voxelSize() << std::endl;\n  file << \"\\t children [ \" << std::endl;\n  for (unsigned int i = 0; i < indices_.size(); ++i) {\n    const Voxel& voxel = voxels_->voxel(indices_[i]);\n    file << \"\\t\\tTransform {\" << std::endl;\n    file << \"\\t\\t\\t translation \" << voxel.x() << \" \" << voxel.y() << \" \"\n         << voxel.z() << std::endl;\n    file << \"\\t\\t\\t children [ \" << std::endl;\n\n    file << \"\\t\\t\\t\\tShape {\" << std::endl;\n    file << \"\\t\\t\\t\\t\\tappearance Appearance {\" << std::endl;\n    file << \"\\t\\t\\t\\t\\t\\tmaterial Material {\" << std::endl;\n    file << \"\\t\\t\\t\\t\\t\\t\\ttransparency 0.5\" << std::endl;\n    if (debugTriangles) {\n      if (voxel.nTriangles() == 0)\n        file << \"\\t\\t\\t\\t\\t\\t\\tdiffuseColor 1 0 0\" << std::endl;\n      else if (voxel.nTriangles() == 1)\n        file << \"\\t\\t\\t\\t\\t\\t\\tdiffuseColor 0 1 0\" << std::endl;\n      else if (voxel.nTriangles() == 2)\n        file << \"\\t\\t\\t\\t\\t\\t\\tdiffuseColor 0 0 1\" << std::endl;\n      else if (voxel.nTriangles() == 3)\n        file << \"\\t\\t\\t\\t\\t\\t\\tdiffuseColor 1 1 1\" << std::endl;\n      else\n        file << \"\\t\\t\\t\\t\\t\\t\\tdiffuseColor 0 0 0\" << std::endl;\n\n    } else {\n      if (voxel.type() == SURFACE)\n        file << \"\\t\\t\\t\\t\\t\\t\\tdiffuseColor 1 0 0\" << std::endl;\n      else if (voxel.type() == INNER)\n        file << \"\\t\\t\\t\\t\\t\\t\\tdiffuseColor 0 0 1\" << std::endl;\n    }\n    file << \"\\t\\t\\t\\t\\t\\t}\" << std::endl;\n    file << \"\\t\\t\\t\\t\\t}\" << std::endl;\n    file << \"\\t\\t\\t\\t\\tgeometry Box {\" << std::endl;\n    file << \"\\t\\t\\t\\t\\t\\tsize 1 1 1\" << std::endl;\n    file << \"\\t\\t\\t\\t\\t}\" << std::endl;\n    file << \"\\t\\t\\t\\t}\" << std::endl;\n    file << \"\\t\\t\\t ]\" << std::endl;\n    file << \"\\t\\t}\";\n  }\n  file << \"\\t ]\" << std::endl;\n  file << \"}\";\n}\n\nSegmenterDownsampling::SegmenterDownsampling() {}\n\nvoid SegmenterDownsampling::setMaximumConcavity(Real maximum_concavity) {\n  maximum_concavity_ = maximum_concavity;\n}\n\nvoid SegmenterDownsampling::setMaxPasses(int passes) { passes_ = passes; }\n\nvoid SegmenterDownsampling::setMesh(std::shared_ptr<Mesh> mesh,\n                                    int min_voxel_count) {\n  int count = 1;\n  double length = 100;\n  VoxelSet set;\n  while (count < min_voxel_count * 0.9 || count > min_voxel_count * 1.1) {\n    set = VoxelSet(mesh, length, true);\n    count = set.nVoxels();\n    // std::cout << \"count: \" << count << \" length: \" << length << std::endl;\n    if (count < min_voxel_count * 0.9 || count > min_voxel_count * 1.1) {\n      double a = pow((double)(min_voxel_count) / count, 1.0 / 3.0);\n      length = length / a;\n      // std::cout << \"a: \" << a << \" length: \" << length << std::endl;\n    }\n  }\n\n  voxels_ = std::make_shared<VoxelSet>(mesh, length, true);\n}\n\nstd::shared_ptr<VoxelSet> SegmenterDownsampling::getVoxels() { return voxels_; }\n\n// Computes and stores the bounding box\nvoid VoxelSubset::ComputeBB() {\n  const size_t nVoxels = indices_.size();\n  if (nVoxels == 0) return;\n  bounding_box_min_[0] = voxels_->voxel(indices_[0]).x();\n  bounding_box_max_[0] = voxels_->voxel(indices_[0]).x();\n  bounding_box_min_[1] = voxels_->voxel(indices_[0]).y();\n  bounding_box_max_[1] = voxels_->voxel(indices_[0]).y();\n  bounding_box_min_[2] = voxels_->voxel(indices_[0]).z();\n  bounding_box_max_[2] = voxels_->voxel(indices_[0]).z();\n  Vector3 bary = Vector3::Zero();\n  for (size_t p = 0; p < nVoxels; ++p) {\n    const Voxel& voxel = voxels_->voxel(indices_[p]);\n    bary[0] += voxel.x();\n    bary[1] += voxel.y();\n    bary[2] += voxel.z();\n\n    if (bounding_box_min_[0] > voxel.x()) {\n      bounding_box_min_[0] = voxel.x();\n    }\n    if (bounding_box_max_[0] < voxel.x()) {\n      bounding_box_max_[0] = voxel.x();\n    }\n    if (bounding_box_min_[1] > voxel.y()) {\n      bounding_box_min_[1] = voxel.y();\n    }\n    if (bounding_box_max_[1] < voxel.y()) {\n      bounding_box_max_[1] = voxel.y();\n    }\n    if (bounding_box_min_[2] > voxel.z()) {\n      bounding_box_min_[2] = voxel.z();\n    }\n    if (bounding_box_max_[2] < voxel.z()) {\n      bounding_box_max_[2] = voxel.z();\n    }\n  }\n\n  bary /= (double)nVoxels;\n  for (int h = 0; h < 3; ++h) {\n    barycenter_[h] = (short)(bary[h] + 0.5);\n  }\n}\n\nvoid VoxelSubset::ComputePrincipalAxes() {\n  const size_t nVoxels = indices_.size();\n  if (nVoxels == 0) return;\n  barycenterPCA_[0] = barycenterPCA_[1] = barycenterPCA_[2] = 0.0;\n  for (size_t v = 0; v < nVoxels; ++v) {\n    const Voxel& voxel = voxels_->voxel(indices_[v]);\n    barycenterPCA_[0] += voxel.x();\n    barycenterPCA_[1] += voxel.y();\n    barycenterPCA_[2] += voxel.z();\n  }\n  barycenterPCA_ /= (double)nVoxels;\n\n  double covMat[3][3] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};\n  double x, y, z;\n  for (size_t v = 0; v < nVoxels; ++v) {\n    const Voxel& voxel = voxels_->voxel(indices_[v]);\n    x = voxel.x() - barycenter_[0];\n    y = voxel.y() - barycenter_[1];\n    z = voxel.z() - barycenter_[2];\n    covMat[0][0] += x * x;\n    covMat[1][1] += y * y;\n    covMat[2][2] += z * z;\n    covMat[0][1] += x * y;\n    covMat[0][2] += x * z;\n    covMat[1][2] += y * z;\n  }\n  covMat[0][0] /= nVoxels;\n  covMat[1][1] /= nVoxels;\n  covMat[2][2] /= nVoxels;\n  covMat[0][1] /= nVoxels;\n  covMat[0][2] /= nVoxels;\n  covMat[1][2] /= nVoxels;\n  covMat[1][0] = covMat[0][1];\n  covMat[2][0] = covMat[0][2];\n  covMat[2][1] = covMat[1][2];\n  Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> covMatEigen(\n      &covMat[0][0]);\n  Eigen::JacobiSVD<Eigen::Matrix<double, 3, 3>> svd(covMatEigen);\n  // covMatEigen = Q*D*QT\n  D_.setZero();\n  D_.diagonal().head(svd.nonzeroSingularValues()) = svd.singularValues();\n}\n\nReal VoxelSubset::GetEigenValue(int axis) const {\n  // std::cout << \"Eigenvalue: \" << d_[axis][axis] << \" \" << D_(axis, axis);\n  return D_(axis, axis);\n}\n\nVector3 VoxelSubset::GetBoundingBoxMin() const { return bounding_box_min_; }\nVector3 VoxelSubset::GetBoundingBoxMax() const { return bounding_box_max_; }\n\nReal VoxelSubset::GetBoundingBoxSize() const {\n  Real a = bounding_box_max_[0] - bounding_box_min_[0];\n  Real b = bounding_box_max_[1] - bounding_box_min_[1];\n  Real c = bounding_box_max_[2] - bounding_box_min_[2];\n  return sqrt(a * a + b * b + c * c);\n}\n\nReal SegmenterDownsampling::computePreferredCuttingDirection(VoxelSubset& tset,\n                                                             Vector3& dir) {\n#if 0\n    //FIXME: how should eigenvalues indicate a direction? For that, we would need eigenvectors\n\tReal ex = tset.GetEigenValue(0);\n\tReal ey = tset.GetEigenValue(1);\n\tReal ez = tset.GetEigenValue(2);\n\tReal vx = (ey - ez) * (ey - ez);\n\tReal vy = (ex - ez) * (ex - ez);\n\tReal vz = (ex - ey) * (ex - ey);\n\tif (vx < vy && vx < vz) {\n\t\tReal e = ey * ey + ez * ez;\n\t\tdir[0] = 1.0;\n\t\tdir[1] = 0.0;\n\t\tdir[2] = 0.0;\n\t\treturn (e == 0.0) ? 0.0 : 1.0 - vx / e;\n\t} else if (vy < vx && vy < vz) {\n\t\tReal e = ex * ex + ez * ez;\n\t\tdir[0] = 0.0;\n\t\tdir[1] = 1.0;\n\t\tdir[2] = 0.0;\n\t\treturn (e == 0.0) ? 0.0 : 1.0 - vy / e;\n\t} else {\n\t\tReal e = ex * ex + ey * ey;\n\t\tdir[0] = 0.0;\n\t\tdir[1] = 0.0;\n\t\tdir[2] = 1.0;\n\t\treturn (e == 0.0) ? 0.0 : 1.0 - vz / e;\n\t}\n#else\n  dir[0] = 1.0;\n  dir[1] = 0.0;\n  dir[2] = 0.0;\n  return 0;\n#endif\n}\n\ninline Real computeLocalConcavity(const Real volume,\n                                  const Real volumeConvexHull) {\n  return fabs(volumeConvexHull - volume) / volumeConvexHull;\n}\ninline Real computeConcavity(Real volume, Real volumeConvexHull, Real volume0) {\n  return fabs(volumeConvexHull - volume) / volume0;\n}\n\nReal SegmenterDownsampling::rateSplit(VoxelSubset& inputSet, Split split,\n                                      const Vector3& preferredCuttingDirection,\n                                      const Real w, const Real alpha,\n                                      const Real beta, const Real delta) {\n  VoxelSubset onSurfacePSet = inputSet.getSurfaceSubset();\n\n  VoxelSubset left(0);\n  VoxelSubset right(0);\n  // compute convex-hulls\n\n  std::vector<VoxelSubset> surfaceParts = onSurfacePSet.partitionVoxel(split);\n  left = surfaceParts[0];\n  right = surfaceParts[1];\n  if (superDebug_) {\n    surfaceParts[0].writeWRL(\"a0_voxel.wrl\");\n    surfaceParts[1].writeWRL(\"a1_voxel.wrl\");\n    left.getConvexHull()->writeWrl(\"b0_voxel.wrl\");\n    right.getConvexHull()->writeWrl(\"b1_voxel.wrl\");\n  }\n\n  Real volumeLeftCH = left.convexVolume();\n  Real volumeRightCH = right.convexVolume();\n\n  // compute clipped volumes\n  std::vector<VoxelSubset> parts = inputSet.partitionVoxel(split, false);\n  Real volumeLeft = parts[0].volume();\n  Real volumeRight = parts[1].volume();\n  Real concavityLeft =\n      computeConcavity(volumeLeft, volumeLeftCH, initial_volume_);\n  Real concavityRight =\n      computeConcavity(volumeRight, volumeRightCH, initial_volume_);\n  Real localConcaviotyLeft = computeLocalConcavity(volumeLeft, volumeLeftCH);\n  Real localConcavityRight = computeLocalConcavity(volumeRight, volumeRightCH);\n  Real concavity = (concavityLeft + concavityRight);\n  Real localConcavity = delta * (localConcaviotyLeft + localConcavityRight);\n\n  // compute cost\n  Real balance =\n      alpha * pow(pow(volumeLeft - volumeRight, 2.0), 0.5) / initial_volume_;\n  Real symmetry =\n      beta * w * preferredCuttingDirection.dot(split.directionVector());\n  Real total = concavity + balance + symmetry + localConcavity;\n  if (debug_) {\n    std::cout << split.dimension << \" \" << split.index << \" \" << volumeLeft\n              << \" \" << volumeRight << \" \" << total << \" \" << concavity << \" \"\n              << balance << \" \" << symmetry << \" \" << localConcavity\n              << std::endl;\n  }\n\n  return total;\n}\n\nReal SegmenterDownsampling::rateSplit3(VoxelSubset& inputSet, Split split,\n                                       const Vector3& preferredCuttingDirection,\n                                       const Real w, const Real alpha,\n                                       const Real beta, const Real delta) {\n  int direction1 = (split.dimension + 1) % 3;\n  int direction2 = (split.dimension + 2) % 3;\n\n  VoxelSubset onSurfacePSet = inputSet.getSurfaceSubset();\n  std::vector<VoxelSubset> parts = onSurfacePSet.partitionVoxel(split, false);\n  std::pair<Real, Real> part00 =\n      parts[0].calculate2DConvexHullVolume(direction1);\n  std::pair<Real, Real> part01 =\n      parts[1].calculate2DConvexHullVolume(direction1);\n  std::pair<Real, Real> part10 =\n      parts[0].calculate2DConvexHullVolume(direction2);\n  std::pair<Real, Real> part11 =\n      parts[1].calculate2DConvexHullVolume(direction2);\n\n  Real volumeLeftCH0 = part00.first;\n  Real volumeRightCH0 = part01.first;\n  Real volumeLeft0 = part00.second;\n  Real volumeRight0 = part01.second;\n  Real volumeLeftCH1 = part10.first;\n  Real volumeRightCH1 = part11.first;\n  Real volumeLeft1 = part10.second;\n  Real volumeRight1 = part11.second;\n\n  Real area0 = initial_area_[direction1];\n  Real concavityLeft0 = computeConcavity(volumeLeft0, volumeLeftCH0, area0);\n  Real concavityRight0 = computeConcavity(volumeRight0, volumeRightCH0, area0);\n  Real localConcavityLeft0 = computeLocalConcavity(volumeLeft0, volumeLeftCH0);\n  Real localConcavityRight0 =\n      computeLocalConcavity(volumeRight0, volumeRightCH0);\n\n  Real area1 = initial_area_[direction2];\n  Real concavityLeft1 = computeConcavity(volumeLeft1, volumeLeftCH1, area1);\n  Real concavityRight1 = computeConcavity(volumeRight1, volumeRightCH1, area1);\n  Real localConcavityLeft1 = computeLocalConcavity(volumeLeft1, volumeLeftCH1);\n  Real localConcavityRight1 =\n      computeLocalConcavity(volumeRight1, volumeRightCH1);\n\n  Real concavity =\n      MAX(concavityLeft0 + concavityRight0, concavityLeft1 + concavityRight1);\n  // Real concavity = MAX(concavityLeft0 + concavityRight0, concavityLeft1 +\n  // concavityRight1);\n  Real localConcavity = delta * MAX(localConcavityLeft0 + localConcavityRight0,\n                                    localConcavityLeft1 + localConcavityRight1);\n\n  // compute cost\n  Real balance = alpha *\n                 pow(pow(parts[0].volume() - parts[1].volume(), 2.0), 0.5) /\n                 initial_volume_;\n  Real symmetry =\n      beta * w * preferredCuttingDirection.dot(split.directionVector());\n  Real total = concavity + balance + symmetry + localConcavity;\n  if (debug_) {\n    std::cout << split.dimension << \" \" << split.index << \" \" << total << \" \"\n              << concavity << \" \" << balance << \" \" << symmetry << \" \"\n              << localConcavity << std::endl;\n    std::cout << \"\\t\" << volumeLeft0 << \"\\t\" << volumeLeftCH0 << \"\\t\\t\"\n              << volumeRight0 << \"\\t\" << volumeRightCH0 << std::endl;\n    std::cout << \"\\t\" << volumeLeft1 << \"\\t\" << volumeLeftCH1 << \"\\t\\t\"\n              << volumeRight1 << \"\\t\" << volumeRightCH1 << std::endl;\n  }\n\n  return total;\n}\n\nvoid SegmenterDownsampling::computeBestClippingPlane(\n    const VoxelSubset& inputPSet2, const Real volume,\n    const std::vector<Split>& splits, const Vector3& preferredCuttingDirection,\n    const Real w, const Real alpha, const Real beta, const Real delta,\n    const int convexhullDownsampling, Split& bestSplit) {\n  VoxelSubset inputPSet = inputPSet2;\n\n  int iBest = -1;\n  Real minTotal = MAX_Real;\n\n  for (int x = 0; x < splits.size(); ++x) {\n    Split split = splits[x];\n\n    Real total = 0;\n    if (heuristic_ == 1) {\n      total = rateSplit(inputPSet, split, preferredCuttingDirection, w, alpha,\n                        beta, delta);\n    } else if (heuristic_ == 2) {\n      std::cout << \"Heuristic2 not compiled.\" << std::endl;\n      throw std::invalid_argument(\"Heuristic2 not compiled\");\n    } else if (heuristic_ == 3) {\n      total = rateSplit3(inputPSet, split, preferredCuttingDirection, w, alpha,\n                         beta, delta);\n    } else {\n      std::cout << \"Unknown heuristc: \" << heuristic_ << std::endl;\n    }\n\n    if (total < minTotal || (total == minTotal && x < iBest)) {\n      bestSplit = split;\n      minTotal = total;\n      iBest = x;\n    }\n  }\n}\n\nvoid SegmenterDownsampling::printDebugSlices(VoxelSubset whole_mesh) {\n  for (int i = 0; i < voxels_->resolution(0); i++) {\n    std::vector<VoxelSubset> parts = whole_mesh.partitionVoxel(Split(0, i));\n    parts[0].writeWRL(\"part\" + std::to_string(static_cast<long long>(i)) +\n                      \"_voxel.wrl\");\n  }\n}\n\nvoid SegmenterDownsampling::compute() {\n  std::vector<VoxelSubset> parts;\n  std::vector<VoxelSubset> inputParts;\n  std::vector<VoxelSubset> temp;\n\n  VoxelSubset whole_mesh(voxels_);\n  for (int i = 0; i < voxels_->nVoxels(); ++i) {\n    whole_mesh.addVoxel(i);\n  }\n  whole_mesh.calculateConvexHullVoxel();\n  inputParts.push_back(whole_mesh);\n  // printDebugSlices(whole_mesh);\n\n  for (int pass = 0; pass < passes_ && inputParts.size() > 0; pass++) {\n    std::cout << \"Pass \" << pass << \" Number of parts: \" << inputParts.size()\n              << std::endl;\n    if (debug_) {\n      std::vector<std::shared_ptr<Mesh>> meshes;\n      for (unsigned int i = 0; i < inputParts.size(); ++i) {\n        meshes.push_back(inputParts[i].getConvexHull());\n      }\n      for (unsigned int i = 0; i < parts.size(); ++i) {\n        meshes.push_back(parts[i].getConvexHull());\n      }\n      boundingmesh::Mesh::writeMultimeshWrl(\n          meshes,\n          \"step\" + std::to_string(static_cast<long long>(pass)) + \".wrl\", true);\n    }\n    for (int partIndex = 0; partIndex < inputParts.size(); partIndex++) {\n      VoxelSubset currentPart = inputParts[partIndex];\n      Real volume = currentPart.volume();\n      currentPart.ComputeBB();\n      currentPart.ComputePrincipalAxes();\n      if (pass == 1 && partIndex == 0) {\n        // superDebug_ = true;\n      }\n      if (debug_) {\n        currentPart.getConvexHull()->writeWrl(\n            \"step\" + std::to_string(static_cast<long long>(pass)) + \"_\" +\n            std::to_string(static_cast<long long>(partIndex)) + \".wrl\");\n        inputParts[partIndex].writeWRL(\n            \"step\" + std::to_string(static_cast<long long>(pass)) + \"_\" +\n                std::to_string(static_cast<long long>(partIndex)) +\n                \"_voxel.wrl\",\n            true);\n      }\n      Real volumeConvexHull = fabs(currentPart.convexVolume());\n\n      if (pass == 0) {\n        initial_volume_ = volumeConvexHull;\n        initial_size_ = currentPart.GetBoundingBoxSize();\n        initial_surface_voxels_ = currentPart.getSurfaceSubset().voxelCount();\n        for (int i = 0; i < 3; i++) {\n          initial_area_[i] = currentPart.calculate2DConvexHullVolume(i).first;\n        }\n      }\n\n      Real concavity =\n          computeConcavity(volume, volumeConvexHull, initial_volume_);\n      Real error =\n          (1.01 * currentPart.surfaceVoxelCount() * voxels_->voxelSize() *\n           voxels_->voxelSize() * voxels_->voxelSize()) /\n          initial_volume_;\n      Real localConcavity =\n          (volumeConvexHull > 0.0)\n              ? computeLocalConcavity(volume, volumeConvexHull)\n              : 0.0;\n      if (debug_) {\n        std::cout << \"volume: \" << volume\n                  << \" convexVolume: \" << volumeConvexHull\n                  << \" concavity: \" << concavity << \" error: \" << error\n                  << \" localConcavity: \" << localConcavity << std::endl;\n      }\n\n      if (concavity > maximum_concavity_ && concavity > error) {\n        Vector3 preferredCuttingDirection;\n        Real w = computePreferredCuttingDirection(currentPart,\n                                                  preferredCuttingDirection);\n\n        std::vector<Split> possibleSplits =\n            generateSplits(currentPart, plane_downsampling_);\n\n        Split bestSplit;\n\n        computeBestClippingPlane(\n            currentPart, volume, possibleSplits, preferredCuttingDirection, w,\n            concavity * alpha_, concavity * beta_, concavity * delta_,\n            convexhull_downsampling_, bestSplit);\n\n        if (plane_downsampling_ > 1) {\n          possibleSplits =\n              refineSplits(currentPart, bestSplit, plane_downsampling_);\n\n          computeBestClippingPlane(currentPart, volume, possibleSplits,\n                                   preferredCuttingDirection, w,\n                                   concavity * alpha_, concavity * beta_,\n                                   concavity * delta_, 1, bestSplit);\n        }\n\n        std::vector<VoxelSubset> parts = currentPart.partitionVoxel(bestSplit);\n        temp.insert(temp.end(), parts.begin(), parts.end());\n      } else {\n        parts.push_back(currentPart);\n      }\n    }\n    inputParts = temp;\n    temp.clear();\n  }\n  parts.insert(parts.end(), inputParts.begin(), inputParts.end());\n\n  std::vector<std::shared_ptr<Mesh>> meshes;\n  std::vector<std::shared_ptr<Mesh>> meshes2;\n  for (unsigned int i = 0; i < parts.size(); ++i) {\n    if (debug_) {\n      meshes2.push_back(parts[i].getConvexHull());\n    }\n  }\n  if (debug_) {\n    boundingmesh::Mesh::writeMultimeshWrl(\n        meshes2, \"stepfinal_beforemerge_voxelhull.wrl\", true);\n  }\n  std::cout << \"Merging convex hulls...\" << std::endl;\n  // parts = mergeConvexHulls(parts);\n  for (long long i = 0; i < parts.size(); ++i) {\n    if (debug_) {\n      meshes.push_back(parts[i].getConvexHull());\n    }\n    parts[i].calculateConvexHull();\n    if (debug_) {\n      parts[i].getConvexHull()->writeWrl(\n          \"stepfinal_part\" + std::to_string(static_cast<long long>(i)) +\n          \".wrl\");\n    }\n  }\n  if (debug_) {\n    boundingmesh::Mesh::writeMultimeshWrl(\n        meshes, \"stepfinal_aftermerge_voxelhull.wrl\", true);\n  }\n  subsets_ = parts;\n  for (unsigned int i = 0; i < subsets_.size(); ++i) {\n    segmentation_.push_back(subsets_[i].getConvexHull());\n  }\n}\n\n// Determines whether the bounding boxes of two voxel subsets are adjacent\n// to each other or not\nbool SegmenterDownsampling::arePartsAdjacent(VoxelSubset& p1, VoxelSubset& p2) {\n  double maxDelta = 1;\n  Vector3 p1min = p1.GetBoundingBoxMin();\n  Vector3 p1max = p1.GetBoundingBoxMax();\n  Vector3 p2min = p2.GetBoundingBoxMin();\n  Vector3 p2max = p2.GetBoundingBoxMax();\n\n  for (int i = 0; i < 3; i++) {\n    if (p1max[i] + maxDelta < p2min[i] || p1min[i] - maxDelta > p2max[i]) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n// Merges adjacent convex hulls so that the error does not increase above the\n// specified threshhold and\n// the total number of parts decreases at the same time\nstd::vector<VoxelSubset> SegmenterDownsampling::mergeConvexHulls(\n    std::vector<VoxelSubset> parts) {\n  long long iteration = 0;\n  if (parts.size() > 1) {\n    bool iterate = true;\n\n    for (int i = 0; i < parts.size(); i++) {\n      parts[i].ComputeBB();\n    }\n\n    while (iterate) {\n      if (parts.empty()) {\n        continue;\n      }\n      size_t bestp1 = 0;\n      size_t bestp2 = 0;\n      double bestCost = MAX_Real;  // initial_volume_;\n      for (size_t p1 = 0; p1 < parts.size() - 1; ++p1) {\n        double volume1 = parts[p1].convexVolume();\n        for (size_t p2 = p1 + 1; p2 < parts.size() - 1; ++p2) {\n          double volume2 = parts[p2].convexVolume();\n\n          if (!arePartsAdjacent(parts[p1], parts[p2])) {\n            continue;\n          }\n\n          VoxelSubset merged = parts[p1].merge(parts[p2]);\n\n          double combinedVolumeCH = merged.convexVolume();\n          double combinedVolume = volume1 + volume2;\n          double cost = computeConcavity(combinedVolume, combinedVolumeCH,\n                                         initial_volume_);\n\n          if (cost < bestCost) {\n            bestCost = cost;\n            bestp1 = p1;\n            bestp2 = p2;\n          }\n        }\n      }\n      if (debug_) {\n        std::cout << \" best cost: \" << bestCost << \" gamma: \" << gamma_\n                  << std::endl;\n      }\n      if (bestCost < gamma_) {\n        if (debug_) {\n          parts[bestp1].getConvexHull()->writeWrl(\n              \"mergedpart1_\" + std::to_string(iteration) + \".wrl\");\n          parts[bestp2].getConvexHull()->writeWrl(\n              \"mergedpart2_\" + std::to_string(iteration) + \".wrl\");\n        }\n        VoxelSubset merged = parts[bestp1].merge(parts[bestp2]);\n        parts.erase(parts.begin() + bestp1);\n        parts.erase(parts.begin() + bestp2 - 1);\n        parts.push_back(merged);\n        std::cout << \"merged \" << bestp1 << \" with \" << bestp2\n                  << \"part1 volume: \" << parts[bestp1].convexVolume()\n                  << \" part2 volume: \" << parts[bestp2].convexVolume()\n                  << \" combined volume: \" << merged.convexVolume() << std::endl;\n        iterate = true;\n        if (debug_) {\n          merged.getConvexHull()->writeWrl(\"mergedpart\" +\n                                           std::to_string(iteration) + \".wrl\");\n          std::vector<std::shared_ptr<Mesh>> meshes;\n          for (unsigned int i = 0; i < parts.size(); ++i) {\n            if (debug_) {\n              meshes.push_back(parts[i].getConvexHull());\n            }\n          }\n          boundingmesh::Mesh::writeMultimeshWrl(\n              meshes, \"merge\" + std::to_string(iteration) + \".wrl\", true);\n        }\n      } else {\n        iterate = false;\n      }\n      iteration++;\n    }\n  }\n\n  return parts;\n}\n\nstd::vector<std::shared_ptr<Mesh>> SegmenterDownsampling::getSegmentation() {\n  return segmentation_;\n}\n\n// Generates a lit of all possible splits considering only every nth split\n// where n is the downsampling rate\nstd::vector<Split> SegmenterDownsampling::generateSplits(\n    const VoxelSubset& subset, const int downsampling) {\n  std::vector<Split> possible_splits;\n  Vector3 min = subset.GetBoundingBoxMin();\n  Vector3 max = subset.GetBoundingBoxMax();\n  for (int dimension = 0; dimension < 3; ++dimension)\n    for (int index = min(dimension) + 1; index < max(dimension);\n         index += downsampling) {\n      possible_splits.push_back(Split(dimension, index));\n    }\n\n  return possible_splits;\n}\n\n// Generates all splits around the split that has previously been declared as\n// best split with downsampling\nstd::vector<Split> SegmenterDownsampling::refineSplits(\n    const VoxelSubset& subset, const Split& bestSplit, const int downsampling) {\n  std::vector<Split> possible_splits;\n  int dimension = bestSplit.dimension;\n  int start = MAX(subset.GetBoundingBoxMin()(dimension),\n                  bestSplit.index - downsampling);\n  int end = MIN(subset.GetBoundingBoxMax()(dimension) - 1,\n                bestSplit.index + downsampling);\n  for (int index = start; index <= end; index += 1) {\n    possible_splits.push_back(Split(dimension, index));\n  }\n\n  return possible_splits;\n}\n}\n", "meta": {"hexsha": "5bf0dadf0bb51f3c7df637bae0e042b8f74953e6", "size": 42427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boundingmesh/SegmenterDownsampling.cpp", "max_stars_repo_name": "antoninklopp/bounding-mesh", "max_stars_repo_head_hexsha": "c1a4d1e628c295f6b6cd457e4084b2cb05f8d178", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 313.0, "max_stars_repo_stars_event_min_datetime": "2015-12-01T10:38:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:21:25.000Z", "max_issues_repo_path": "src/boundingmesh/SegmenterDownsampling.cpp", "max_issues_repo_name": "RodrigoCodeBernardo/bounding-mesh", "max_issues_repo_head_hexsha": "b34022531d176a7fb9b511cc4ada446909a986eb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2016-02-06T12:53:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T10:26:40.000Z", "max_forks_repo_path": "src/boundingmesh/SegmenterDownsampling.cpp", "max_forks_repo_name": "RodrigoCodeBernardo/bounding-mesh", "max_forks_repo_head_hexsha": "b34022531d176a7fb9b511cc4ada446909a986eb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-02-04T22:57:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T10:12:51.000Z", "avg_line_length": 36.3556126821, "max_line_length": 94, "alphanum_fraction": 0.5938906828, "num_tokens": 12390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.021948254074728567, "lm_q1q2_score": 0.010118513405059778}}
{"text": "/**\n\nCopyright (c) 2016, Hanselmann Fabian, Heller Florian, Heizmann Heinrich, Kübler Marcel, Mehlhaus Jonas, Meißner Pascal, Qattan Mohamad, Reckling Reno, Stroh Daniel\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\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. 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\n3. Neither the name of the copyright holder 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 \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#pragma once\n\n#include <Eigen/Geometry>\n#include <cmath>\n#include \"common_type/Pose.hpp\"\n#include \"common_type/Quaternion.hpp\"\n#include \"common_type/VoteSpecifier.hpp\"\n#include \"common_type/Point.hpp\"\n\nnamespace ISM {\n  class GeometryHelper {\n  public:\n\n    //Methods are all inlined since heavily used in performance relevant code.\n\n    /**Voting related methods**/\n\n    /**\n     * Calculates an absolute pose at refPoint based on a relative orientation refToSourceQuat towards source.\n     *\n     * @param source Absolute position in refPoint has been calculated be combining source and the relative position of refPoint towards source.\n     * @param refPoint Absolute position for which we want to calculate the corresponding orientation.\n     * @param refToSourceQuat Relative orientation of searched absolute pose relative to source.\n     * @return 6D pose being looked for.\n     */\n    static PosePtr getReferencePose(const PosePtr& source, const PointPtr& refPoint, const QuaternionPtr& objectToRefPoseQuat) {\n      PosePtr result = PosePtr(new Pose());\n      getReferencePose(source, refPoint, objectToRefPoseQuat, result);\n      return result;\n    }\n\n    //Faster variant that avoids allocation of local Pose in every call of this method.\n    static void getReferencePose(const PosePtr& source, const PointPtr& refPoint, const QuaternionPtr& objectToRefPoseQuat, PosePtr& result) {\n      result->point = refPoint;\n      result->quat = eigenQuatToQuat(source->quat->eigen * objectToRefPoseQuat->eigen);\n    }\n\n    /**\n     * Calculate an absolute position by combining refPose and a relative position vector composed of refToObjectQuat and radius.\n     *\n     * @param refPose Absolute position that is combined with relative pose.\n     * @param refToObjectQuat Orientation of Eigen::Vector3d connecting refPose and position being searched for.\n     * @param radius Length of Eigen::Vector3d connecting refPose and position being searched for.\n     * @return 3D position being looked for.\n     */\n    static PointPtr getSourcePoint(const PosePtr& refPose, const QuaternionPtr& refToObjectQuat, double radius) {\n      PointPtr result = PointPtr(new Point());\n      getSourcePoint(refPose, refToObjectQuat, radius, result);\n      return result;\n    }\n\n    //Faster variant that avoids allocation of local Pose in every call of this method.\n    static void getSourcePoint(const PosePtr& refPose, const QuaternionPtr& refToObjectQuat, double radius, PointPtr& result) {\n      Eigen::Vector3d relativeObjectVector = refToObjectQuat->eigen._transformVector(Eigen::Vector3d::UnitX());\n      Eigen::Vector3d absoluteObjectVector = refPose->quat->eigen._transformVector(relativeObjectVector);\n      result->eigen = refPose->point->eigen + (absoluteObjectVector * radius);\n    }\n\n    static PosePtr getSourcePose(const PosePtr& reference, const PointPtr& sourcePoint, const QuaternionPtr& refToObjectPoseQuat) {\n      PosePtr result = PosePtr(new Pose());\n      getSourcePose(reference, sourcePoint, refToObjectPoseQuat, result);\n      return result;\n    }\n\n    //Faster variant that avoids allocation of local Pose in every call of this method.\n    static void getSourcePose(const PosePtr& reference, const PointPtr& sourcePoint, const QuaternionPtr& refToObjectPoseQuat, PosePtr& result) {\n      result->point = sourcePoint;\n      result->quat->eigen = reference->quat->eigen * refToObjectPoseQuat->eigen;\n    }\n\n    static PointPtr applyQuatAndRadiusToPose(const PosePtr& pose, const QuaternionPtr& quat, double radius) {\n      //apply transformation to viewport vector, then scale, than transform to object coordinates and add\n      Eigen::Quaternion<double> rotation = pose->quat->eigen * quat->eigen;\n      Eigen::Vector3d objectPoint = pose->point->eigen;\n\n      Eigen::Vector3d resultVec = objectPoint + rotation._transformVector(Eigen::Vector3d::UnitX()) * radius;\n\n      return vectorToPoint(resultVec);\n    }\n\n    static Quaternion selfQuat;\n    static double constexpr epsylon = 1e-4;\n    static bool isSelfVote(const VoteSpecifierPtr& vote)\n    {\n      if ( !(vote->radius > -epsylon && vote->radius < epsylon) ||\n\t   !quatEqual(selfQuat, *(vote->objectToRefPoseQuat)))\n        {\n\t  return false;\n        }\n      return true;\n    }\n\n    /**Pose related methods**/\n\n    static VoteSpecifierPtr createVoteSpecifier(const PosePtr& sourcePose, const PosePtr& refPose) {\n      if ((refPose->point->eigen - sourcePose->point->eigen).norm() == 0) {\n\t//avoid special case\n\tsourcePose->point->eigen.x() = (sourcePose->point->eigen.x() + 0.0000001);\n      };\n      Eigen::Vector3d objToRefVector = refPose->point->eigen - sourcePose->point->eigen;\n      Eigen::Vector3d refToObjVector = objToRefVector * -1.0;\n      Eigen::Quaternion<double> p = sourcePose->quat->eigen;\n      Eigen::Quaternion<double> r = refPose->quat->eigen;\n\n      //rotate everything relative to object pose\n      Eigen::Vector3d relativeRefPoint = p.inverse()._transformVector(objToRefVector);\n\n      Eigen::Quaternion<double> otr = vectorRotationToEigenQuat(Eigen::Vector3d::UnitX(), relativeRefPoint);\n      Eigen::Quaternion<double> otrp = (p.inverse()) * r;\n\n      //rotate everything relative to ref pose\n      Eigen::Vector3d relativeObjPoint = r.inverse()._transformVector(refToObjVector);\n      Eigen::Quaternion<double> rto = vectorRotationToEigenQuat(Eigen::Vector3d::UnitX(), relativeObjPoint);\n      Eigen::Quaternion<double> rtop = (r.inverse()) * p;\n\n      return VoteSpecifierPtr(\n\t\t\t      new VoteSpecifier(\n\t\t\t\t\t\teigenQuatToQuat(otr),\n\t\t\t\t\t\teigenQuatToQuat(otrp),\n\t\t\t\t\t\teigenQuatToQuat(rto),\n\t\t\t\t\t\teigenQuatToQuat(rtop),\n\t\t\t\t\t\tobjToRefVector.norm()\n\t\t\t\t\t\t)\n\t\t\t      );\n    }\n\n    static PosePtr getPoseFromVote(const PosePtr& source, const VoteSpecifierPtr& vote)\n    {\n      PointPtr referencePoint = applyQuatAndRadiusToPose(source, vote->objectToRefQuat, vote->radius);\n      return getReferencePose(source, referencePoint, vote->objectToRefPoseQuat);\n    }\n\n    static bool poseEqual(const PosePtr& p1, const PosePtr& p2) {\n      bool overall = (quatEqual(p1->quat, p2->quat) && pointEqual (p1->point, p2->point));\n      return overall;\n    }\n\n    static Eigen::Vector3d getDirectionVector(const PosePtr& first, const PosePtr& second) {\n\n      Eigen::Vector3d firstToSecond = second->point->eigen - first->point->eigen;\n      Eigen::Quaternion<double> firstRotation = first->quat->eigen;\n      return firstRotation.inverse()._transformVector(firstToSecond);\n\n    }\n\n    static bool sharedNeighborhoodEvaluation(const PosePtr& p1, const PosePtr& p2, double distanceNeighbourThreshold, double angleNeighbourThreshold)\n    {\n      double distance_angle = getAngleBetweenQuats(p1->quat, p2->quat);\n      double distance_position = getDistanceBetweenPoints(p1->point, p2->point);\n\n      return distanceNeighbourThreshold > distance_position\n\t&& angleNeighbourThreshold > fabs(distance_angle);\n    }\n\n    /**Point related methods**/\n\n    static Eigen::Vector3d pointToVector(const PointPtr& p) {\n      return p->eigen;\n    }\n\n    static PointPtr vectorToPoint(const Eigen::Vector3d& v) {\n      return PointPtr(new Point(v[0], v[1], v[2]));\n    }\n\n    static double getDistanceBetweenPoints(const PointPtr& p1, const PointPtr& p2) {\n      return (p1->eigen - p2->eigen).norm();\n\n    }\n\n    static double getSquaredDistanceBetweenPoints(const PointPtr &p1, const PointPtr &p2)\n    {\n      return (p1->eigen - p2->eigen).squaredNorm();\n    }\n\n    static bool pointEqual(const PointPtr& p1, const PointPtr& p2)\n    {\n      bool xAbs = fabs(p1->eigen.x() - p2->eigen.x()) < 0.00001;\n      bool yAbs = fabs(p1->eigen.y() - p2->eigen.y()) < 0.00001;\n      bool zAbs = fabs(p1->eigen.z() - p2->eigen.z()) < 0.00001;\n      return (xAbs && yAbs && zAbs);\n    }\n\n    /**Quaternion related methods**/\n\n    static Eigen::Quaternion<double> quatToEigenQuat(const QuaternionPtr& q) {\n      return q->eigen;\n    }\n\n    static QuaternionPtr eigenQuatToQuat(const Eigen::Quaternion<double>& q) {\n      return QuaternionPtr(new Quaternion(q.w(), q.x(), q.y(), q.z()));\n    }\n\n    static QuaternionPtr normalize(const QuaternionPtr& quat) {\n      return eigenQuatToQuat(quat->eigen.normalized());\n    }\n\n    static double getAngleBetweenQuats(const QuaternionPtr& q1, const QuaternionPtr& q2) {\n      return rad2deg( q1->eigen.angularDistance(q2->eigen) );\n    }\n\n    static Eigen::Vector3d getAxisFromQuat(const QuaternionPtr& quat, const Eigen::Vector3d& viewport = Eigen::Vector3d::UnitX()) {\n      Eigen::Quaternion<double> rotation = quat->eigen;\n      return rotation._transformVector(viewport);\n    }\n\n    static double getAngleBetweenAxes(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) {\n\n      double cosOfAngle = v1.dot(v2) / (v1.norm() * v2.norm());\n      if(cosOfAngle < -1.0) cosOfAngle = -1.0;\n      if(cosOfAngle > 1.0) cosOfAngle = 1.0;\n\n      return rad2deg(acos(cosOfAngle));\n\n    }\n\n    static bool quatEqual(const QuaternionPtr& q1, const QuaternionPtr& q2)\n    {\n      return quatEqual(*q1, *q2);\n    }\n\n    static bool quatEqual(const Quaternion& q1, const Quaternion& q2) {\n      bool qxAbs = fabs(q1.eigen.x() - q2.eigen.x()) < 0.00001;\n      bool qyAbs = fabs(q1.eigen.y() - q2.eigen.y()) < 0.00001;\n      bool qzAbs = fabs(q1.eigen.z() - q2.eigen.z()) < 0.00001;\n      bool qwAbs = fabs(q1.eigen.w() - q2.eigen.w()) < 0.00001;\n      return (qxAbs && qyAbs && qzAbs && qwAbs);\n    }\n\n    static Eigen::Quaternion<double> vectorRotationToEigenQuat(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) {\n      Eigen::Quaternion<double> q;\n      q.setFromTwoVectors(v1, v2);\n      return q;\n    }\n\n    static QuaternionPtr getQuatFromRPY(const QuaternionPtr& q, const double alpha, const double beta, const double gamma){\n      Eigen::Quaternion<double> eq = q->eigen;\n      Eigen::AngleAxisd rollAngle(deg2rad(alpha), Eigen::Vector3d::UnitX());\n      Eigen::AngleAxisd pitchAngle(deg2rad(beta), Eigen::Vector3d::UnitY());\n      Eigen::AngleAxisd yawAngle(deg2rad(gamma), Eigen::Vector3d::UnitZ());\n\n      Eigen::Quaterniond rot = yawAngle * pitchAngle * rollAngle;\n\n\n      return eigenQuatToQuat(eq * rot);\n\n    }\n\n    static QuaternionPtr getAveragePose(const std::vector<QuaternionPtr>& poseQuats) {\n      Eigen::Vector3d combined(0, 0, 0);\n\n      for (const QuaternionPtr& quat : poseQuats) {\n\tcombined += quat->eigen._transformVector(Eigen::Vector3d::UnitX());\n      }\n\n      Eigen::Quaternion<double> ret;\n      ret.setFromTwoVectors(Eigen::Vector3d::UnitX(), combined);\n      return eigenQuatToQuat(ret.normalized());\n    }\n\n    static bool getNextCombination(const std::vector<unsigned int>::iterator first, std::vector<unsigned int>::iterator k, const std::vector<unsigned int>::iterator last)\n    {\n      if ((first == last) || (first == k) || (last == k))\n\treturn false;\n\n      std::vector<unsigned int>::iterator it1 = first;\n      std::vector<unsigned int>::iterator it2 = last;\n      it1++;\n      if (last == it1)\n\treturn false;\n      it1 = last;\n      it1--;\n      it1 = k;\n      it2--;\n      while (first != it1)\n        {\n\t  if (*--it1 < *it2)\n            {\n\t      std::vector<unsigned int>::iterator j = k;\n\t      while (!(*it1 < *j)) ++j;\n\t      std::iter_swap(it1,j);\n\t      it1++;\n\t      j++;\n\t      it2 = k;\n\t      std::rotate(it1,j,last);\n\t      while (last != j)\n                {\n\t\t  j++;\n\t\t  it2++;\n                }\n\t      std::rotate(k,it2,last);\n\t      return true;\n            }\n        }\n      std::rotate(first,k,last);\n      return false;\n    }\n\n    /**Various geometry related helpers**/\n\n    static double rad2deg(double rad) {\n      return rad * (180.0 / M_PI);\n    }\n\n    static double deg2rad(double deg) {\n      return deg * (M_PI / 180.0);\n    }\n\n    static inline bool checkIfDoubleNaN(double& c)\n    {\n      /*\n       * distance != distance for portable way check for nan\n       * but be aware:\n       * http://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c\n       */\n      bool isNan = c != c;\n      if (isNan)\n        {\n\t  std::cerr << \" NaN \";\n        }\n      return isNan;\n    }\n\n  };\n\n}\n", "meta": {"hexsha": "02106bb9962ab8741a1e4ae560771587538104ba", "size": 13688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libism/ISM/utility/GeometryHelper.hpp", "max_stars_repo_name": "Tobi2001/asr_lib_ism", "max_stars_repo_head_hexsha": "935619b185621e1b882fa1ef06b6eff47d2fb3cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T13:37:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-29T13:37:36.000Z", "max_issues_repo_path": "libism/ISM/utility/GeometryHelper.hpp", "max_issues_repo_name": "Tobi2001/asr_lib_ism", "max_issues_repo_head_hexsha": "935619b185621e1b882fa1ef06b6eff47d2fb3cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libism/ISM/utility/GeometryHelper.hpp", "max_forks_repo_name": "Tobi2001/asr_lib_ism", "max_forks_repo_head_hexsha": "935619b185621e1b882fa1ef06b6eff47d2fb3cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-03T13:51:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-13T08:24:01.000Z", "avg_line_length": 39.9067055394, "max_line_length": 755, "alphanum_fraction": 0.6868790181, "num_tokens": 3465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.02194825287519286, "lm_q1q2_score": 0.01011851285205369}}
{"text": "/**\nMIT License\n\nThis file is part of the Granite project which is based on Basalt.\nhttps://github.com/DLR-RM/granite\n\nCopyright (c) Martin Wudenka, Deutsches Zentrum für Luft- und Raumfahrt\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/**\nOriginal license of Basalt:\nBSD 3-Clause License\n\nThis file is part of the Basalt project.\nhttps://gitlab.com/VladyslavUsenko/granite-headers.git\n\nCopyright (c) 2019, Vladyslav Usenko and Nikolaus Demmel.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n@file\n@brief Implementation of stereographic parametrization for unit vectors\n*/\n\n#pragma once\n\n#include <Eigen/Dense>\n\nnamespace granite {\n\n/// @brief Stereographic projection for minimal representation of unit vectors\n///\n/// \\image html stereographic.png\n/// The projection is defined on the entire\n/// sphere, except at one point: the projection point. Where it is defined, the\n/// mapping is smooth and bijective. The illustrations shows 3 examples of unit\n/// vectors parametrized with a point in the 2D plane. See\n/// \\ref project and \\ref unproject functions for more details.\ntemplate <typename Scalar = double>\nclass StereographicParam {\n public:\n  using Vec2 = Eigen::Matrix<Scalar, 2, 1>;\n  using Vec4 = Eigen::Matrix<Scalar, 4, 1>;\n\n  using Mat24 = Eigen::Matrix<Scalar, 2, 4>;\n  using Mat42 = Eigen::Matrix<Scalar, 4, 2>;\n\n  /// @brief Project the point and optionally compute Jacobian\n  ///\n  /// Projection function is defined as follows:\n  /// \\f{align}{\n  ///    \\pi(\\mathbf{x}) &=\n  ///    \\begin{bmatrix}\n  ///   {\\frac{x}{d + z}}\n  ///    \\\\ {\\frac{y}{d + z}}\n  ///    \\\\ \\end{bmatrix},\n  ///    \\\\ d &= \\sqrt{x^2 + y^2 + z^2}.\n  /// \\f}\n  /// @param[in] p3d point to project [x,y,z]\n  /// @param[out] d_r_d_p if not nullptr computed Jacobian of projection\n  /// with respect to p3d\n  /// @return 2D projection of the point which parametrizes the corresponding\n  /// direction vector\n  static inline Vec2 project(const Vec4& p3d, Mat24* d_r_d_p = nullptr) {\n    const Scalar sqrt = p3d.template head<3>().norm();\n    const Scalar norm = p3d[2] + sqrt;\n    const Scalar norm_inv = Scalar(1) / norm;\n\n    const Vec2 res(p3d[0] * norm_inv, p3d[1] * norm_inv);\n\n    if (d_r_d_p) {\n      Scalar norm_inv2 = norm_inv * norm_inv;\n      Scalar tmp = -norm_inv2 / sqrt;\n\n      (*d_r_d_p).setZero();\n\n      (*d_r_d_p)(0, 0) = norm_inv + p3d[0] * p3d[0] * tmp;\n      (*d_r_d_p)(1, 0) = p3d[0] * p3d[1] * tmp;\n\n      (*d_r_d_p)(1, 1) = norm_inv + p3d[1] * p3d[1] * tmp;\n      (*d_r_d_p)(0, 1) = p3d[0] * p3d[1] * tmp;\n\n      (*d_r_d_p)(0, 2) = p3d[0] * norm * tmp;\n      (*d_r_d_p)(1, 2) = p3d[1] * norm * tmp;\n\n      (*d_r_d_p)(0, 3) = Scalar(0);\n      (*d_r_d_p)(1, 3) = Scalar(0);\n    }\n\n    return res;\n  }\n\n  /// @brief Unproject the point and optionally compute Jacobian\n  ///\n  /// The unprojection function is computed as follows: \\f{align}{\n  ///    \\pi^{-1}(\\mathbf{u}) &=\n  ///    \\frac{2}{1 + x^2 + y^2}\n  ///    \\begin{bmatrix}\n  ///    u \\\\ v \\\\ 1\n  ///    \\\\ \\end{bmatrix}-\\begin{bmatrix}\n  ///    0 \\\\ 0 \\\\ 1\n  ///    \\\\ \\end{bmatrix}.\n  /// \\f}\n  ///\n  /// @param[in] proj point to unproject [u,v]\n  /// @param[out] d_r_d_p if not nullptr computed Jacobian of unprojection\n  /// with respect to proj\n  /// @return unprojected 3D unit vector\n  static inline Vec4 unproject(const Vec2& proj, Mat42* d_r_d_p = nullptr) {\n    const Scalar x2 = proj[0] * proj[0];\n    const Scalar y2 = proj[1] * proj[1];\n    const Scalar r2 = x2 + y2;\n\n    const Scalar norm_inv = Scalar(2) / (Scalar(1) + r2);\n\n    const Vec4 res(proj[0] * norm_inv, proj[1] * norm_inv, norm_inv - Scalar(1),\n                   Scalar(0));\n\n    if (d_r_d_p) {\n      const Scalar norm_inv2 = norm_inv * norm_inv;\n      const Scalar xy = proj[0] * proj[1];\n\n      (*d_r_d_p)(0, 0) = (norm_inv - x2 * norm_inv2);\n      (*d_r_d_p)(0, 1) = -xy * norm_inv2;\n\n      (*d_r_d_p)(1, 0) = -xy * norm_inv2;\n      (*d_r_d_p)(1, 1) = (norm_inv - y2 * norm_inv2);\n\n      (*d_r_d_p)(2, 0) = -proj[0] * norm_inv2;\n      (*d_r_d_p)(2, 1) = -proj[1] * norm_inv2;\n\n      (*d_r_d_p)(3, 0) = Scalar(0);\n      (*d_r_d_p)(3, 1) = Scalar(0);\n    }\n\n    return res;\n  }\n};\n\n}  // namespace granite\n", "meta": {"hexsha": "44b9149db85da520a141b925b2e50bd8e4f3cc98", "size": 6547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "thirdparty/granite-headers/include/granite/camera/stereographic_param.hpp", "max_stars_repo_name": "wstuerzl/granite", "max_stars_repo_head_hexsha": "8bbb6497d1b3100c25099d56672416dfa01346b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T09:18:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T12:20:37.000Z", "max_issues_repo_path": "thirdparty/granite-headers/include/granite/camera/stereographic_param.hpp", "max_issues_repo_name": "wstuerzl/granite", "max_issues_repo_head_hexsha": "8bbb6497d1b3100c25099d56672416dfa01346b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-19T08:58:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T11:42:15.000Z", "max_forks_repo_path": "thirdparty/granite-headers/include/granite/camera/stereographic_param.hpp", "max_forks_repo_name": "wstuerzl/granite", "max_forks_repo_head_hexsha": "8bbb6497d1b3100c25099d56672416dfa01346b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T07:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T16:56:10.000Z", "avg_line_length": 38.2865497076, "max_line_length": 460, "alphanum_fraction": 0.6833664274, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577487985229844, "lm_q2_score": 0.02843603458865538, "lm_q1q2_score": 0.010116826789254671}}
{"text": "/**\n* This file is part of Intrinsic3D.\n*\n* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n* Copyright (c) 2019, Technical University of Munich. 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*    * 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 <nv/keyframe_selection.h>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <fstream>\n#include <iomanip>\n\n#include <Eigen/Geometry>\n#include <opencv2/imgproc.hpp>\n\nnamespace nv\n{\n\n    KeyframeSelection::KeyframeSelection(int window_size) :\n        window_size_(window_size)\n\t{\n\t}\n\n\n\tKeyframeSelection::~KeyframeSelection()\n\t{\n\t}\n\n\n\tvoid KeyframeSelection::reset()\n\t{\n\t\tframe_scores_.clear();\n\t\tis_keyframe_.clear();\n\t}\n\n\n\tvoid KeyframeSelection::add(const cv::Mat &color)\n\t{\n        // compute frame score (measure for image blur)\n        double score = estimateBlur(color);\n\n\t\tframe_scores_.push_back(score);\n\t}\n\n\n\tvoid KeyframeSelection::selectKeyframes()\n\t{\n\t\tint n = (int)frame_scores_.size();\n\n        // select best frame within a fixed size window\n        is_keyframe_.resize(n, false);\n\n        int num_windows = n / window_size_;\n        if (n % window_size_ > 0)\n            ++num_windows;\n\n        for (int j = 0; j < num_windows; ++j)\n        {\n            // determine window start and end indices\n            int id_win_beg = j * window_size_;\n            int id_win_end = std::min(id_win_beg + window_size_, n);\n            // find frame with best score within window\n            double score_max = 0.0;\n            int id_max = id_win_beg;\n            for (int id = id_win_beg; id < id_win_end; ++id)\n            {\n                if (frame_scores_[id] > score_max)\n                {\n                    score_max = frame_scores_[id];\n                    id_max = id;\n                }\n            }\n            // assign isKeyframe to frame ids\n            for (int id = id_win_beg; id < id_win_end; ++id)\n            {\n                is_keyframe_[id] = (id == id_max);\n            }\n        }\n\t}\n\n\n\tbool KeyframeSelection::isKeyframe(int id) const\n\t{\n\t\tif (!frameExists(id))\n\t\t\treturn false;\n\t\treturn is_keyframe_[id];\n\t}\n\n\n    size_t KeyframeSelection::countKeyframes() const\n    {\n        size_t cnt = 0;\n        for (auto is_kf : is_keyframe_)\n        {\n            if (is_kf)\n                ++cnt;\n        }\n        return cnt;\n    }\n\n\n    void KeyframeSelection::drawScore(int id, cv::Mat &image) const\n\t{\n\t\tif (!frameExists(id))\n\t\t\treturn;\n\n        std::string text = \"score: \" + std::to_string(frame_scores_[id]);\n        cv::putText(image, text, cv::Point(10, 50), cv::FONT_HERSHEY_COMPLEX, 0.9, cv::Scalar(0, 255, 0), 2);\n\t}\n\n\n\tbool KeyframeSelection::load(const std::string &filename)\n    {\n\t\treset();\n\t\t\n\t\t// open input file\n\t\tstd::ifstream file(filename.c_str());\n\t\tif (!file.is_open())\n\t\t\treturn false;\n\n        // load window size\n\t\tstd::string line;\n\t\tif (std::getline(file, line))\n\t\t{\n\t\t\tif (line.empty())\n\t\t\t\treturn false;\n            std::istringstream iss(line);\n            int window_size;\n            if (!(iss >> window_size))\n                return false;\n            window_size_ = window_size;\n\t\t}\n\n\t\t// load frames scores and isKeyframe from file\n\t\twhile (std::getline(file, line))\n\t\t{\n\t\t\tif (line.empty())\n\t\t\t\tcontinue;\n\t\t\tstd::istringstream iss(line);\n\t\t\tdouble score;\n            bool is_kf;\n            if (!(iss >> score >> is_kf))\n\t\t\t\tbreak;\n\t\t\tframe_scores_.push_back(score);\n            is_keyframe_.push_back(is_kf);\n\t\t}\n\n\t\t// close file\n\t\tfile.close();\n\n\t\treturn true;\n\t}\n\n\n\tbool KeyframeSelection::save(const std::string &filename) const\n\t{\n\t\tif (frame_scores_.empty() || is_keyframe_.empty() || frame_scores_.size() != is_keyframe_.size())\n\t\t\treturn false;\n\n\t\t// open output file\n\t\tstd::ofstream file(filename.c_str());\n\t\tif (!file.is_open())\n\t\t\treturn false;\n\n        // write window size into output file\n        file << window_size_ << std::endl;\n\n\t\t// write frame scores and isKeyframe into output file\n\t\tfile << std::fixed << std::setprecision(6);\n        for (size_t i = 0; i < is_keyframe_.size(); ++i)\n\t\t{\n\t\t\tdouble score = frame_scores_[i];\n\t\t\tbool isKf = is_keyframe_[i];\n            file << score << \" \" << static_cast<int>(isKf) << std::endl;\n\t\t}\n\t\t// close file\n\t\tfile.close();\n\n\t\treturn true;\n\t}\n\n\n\tbool KeyframeSelection::frameExists(int id) const\n\t{\n        if (id < 0 || id >= frame_scores_.size() || id >= is_keyframe_.size())\n\t\t\treturn false;\n\t\telse\n\t\t\treturn true;\n\t}\n\n\n\tdouble KeyframeSelection::estimateBlur(const cv::Mat &color) const\n\t{\n\t\tif (color.empty())\n\t\t\treturn 0.0;\n\t\tcv::Mat gray;\n\t\tif (color.channels() == 1)\n\t\t\tgray = color;\n\t\telse if (color.channels() == 3)\n\t\t\tcv::cvtColor(color, gray, cv::COLOR_BGR2GRAY);\n\t\telse\n\t\t\treturn 0.0;\n\n\t\t// convert grayscale image to float\n        cv::Mat gray_f;\n        gray.convertTo(gray_f, CV_32FC1, 1.0 / 255.0);\n\n        // estimate blur using no-reference perceptual blur metric (Crete2007)\n        return estimateBlurCrete(gray_f);\n\t}\n\n\n\tdouble KeyframeSelection::estimateBlurCrete(const cv::Mat &gray) const\n\t{\n\t\t// no-reference perceptual blur metric (Crete2007)\n\n\t\tint w = gray.cols;\n\t\tint h = gray.rows;\n\n\t\t// create blur kernels for strong low-pass filter\n\t\tcv::Mat hv = cv::Mat::ones(9, 1, CV_32F)  * (1.0 / 9.0);\n\t\tcv::Mat hh;\n\t\tcv::transpose(hv, hh);\n\n\t\t// blur image using a strong low-pass filter\n        cv::Mat b_ver, b_hor;\n        cv::filter2D(gray, b_ver, CV_32FC1, hv);\n        cv::filter2D(gray, b_hor, CV_32FC1, hh);\n\n\t\t// compute absolute difference images (vertical)\n        cv::Mat d_f_ver = cv::Mat::zeros(h, w, CV_32FC1);\n        cv::Mat d_b_ver = cv::Mat::zeros(h, w, CV_32FC1);\n\t\tfor (int y = 1; y < h; ++y)\n\t\t{\n\t\t\tfor (int x = 0; x < w; ++x)\n\t\t\t{\n                d_f_ver.at<float>(y, x) = std::abs(gray.at<float>(y, x) - gray.at<float>(y - 1, x));\n                d_b_ver.at<float>(y, x) = std::abs(b_ver.at<float>(y, x) - b_ver.at<float>(y - 1, x));\n\t\t\t}\n\t\t}\n\n\t\t// compute absolute difference images (horizontal)\n        cv::Mat d_f_hor = cv::Mat::zeros(h, w, CV_32FC1);\n        cv::Mat d_b_hor = cv::Mat::zeros(h, w, CV_32FC1);\n\t\tfor (int y = 0; y < h; ++y)\n\t\t{\n\t\t\tfor (int x = 1; x < w; ++x)\n\t\t\t{\n                d_f_hor.at<float>(y, x) = std::abs(gray.at<float>(y, x) - gray.at<float>(y, x - 1));\n                d_b_hor.at<float>(y, x) = std::abs(b_hor.at<float>(y, x) - b_hor.at<float>(y, x - 1));\n\t\t\t}\n\t\t}\n\n\t\t// compute vertical and horizontal variation\n        cv::Mat v_ver = cv::Mat::zeros(h, w, CV_32FC1);\n        cv::Mat v_hor = cv::Mat::zeros(h, w, CV_32FC1);\n\t\tfor (int y = 0; y < h; ++y)\n\t\t{\n\t\t\tfor (int x = 0; x < w; ++x)\n\t\t\t{\n                v_ver.at<float>(y, x) = std::max(0.0f, d_f_ver.at<float>(y, x) - d_b_ver.at<float>(y, x));\n                v_hor.at<float>(y, x) = std::max(0.0f, d_f_hor.at<float>(y, x) - d_b_hor.at<float>(y, x));\n\t\t\t}\n\t\t}\n\n\t\t// compute sum of coefficients\n        double s_f_ver = cv::sum(d_f_ver).val[0];\n        double s_v_ver = cv::sum(v_ver).val[0];\n        double s_f_hor = cv::sum(d_f_hor).val[0];\n        double s_v_hor = cv::sum(v_hor).val[0];\n\n\t\t// normalize results\n        double b_f_ver = (s_f_ver - s_v_ver) / s_f_ver;\n        double b_f_hor = (s_f_hor - s_v_hor) / s_f_hor;\n\n\t\t// compute final score: select more annyoing blur\n        double blur_score = std::max(b_f_ver, b_f_hor);\n\n\t\t// invert score for 1.0=best and 0.0=worst\n        blur_score = 1.0 - blur_score;\n\n        return blur_score;\n\t}\n\n} // namespace nv\n", "meta": {"hexsha": "ef16cbc8497c021fb7b404867ca98897e116803d", "size": 8828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libintrinsic3d/src/keyframe_selection.cpp", "max_stars_repo_name": "dazinovic/intrinsic3d", "max_stars_repo_head_hexsha": "4e5ea3b3d81b4174f33765e1d3dd0b24c2716c06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 370.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T23:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T12:40:03.000Z", "max_issues_repo_path": "libintrinsic3d/src/keyframe_selection.cpp", "max_issues_repo_name": "wangxihao/intrinsic3d", "max_issues_repo_head_hexsha": "a0ae31df213b37828a8c48ce6567b7a211e3df3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2019-02-13T10:15:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T10:22:47.000Z", "max_forks_repo_path": "libintrinsic3d/src/keyframe_selection.cpp", "max_forks_repo_name": "wangxihao/intrinsic3d", "max_forks_repo_head_hexsha": "a0ae31df213b37828a8c48ce6567b7a211e3df3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2019-02-28T06:19:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:06:35.000Z", "avg_line_length": 28.2044728435, "max_line_length": 109, "alphanum_fraction": 0.6123697327, "num_tokens": 2468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512973571032984, "lm_q2_score": 0.036769462777089715, "lm_q1q2_score": 0.010116372576071503}}
{"text": "#include \"CppSimulation.hpp\"\n\n#include <boost/numeric/odeint.hpp>\n#include <functional>\n#include <algorithm>\n#include <vector>\n#include <exception>\n\nnamespace pysim{\n\nstruct EarlyBreakException : public std::exception {\n    virtual const char* what() const throw() {\n        return \"A comparison resulted in an early break of the simulation\";\n    }\n}earlybreak;\n\nSimulation::Simulation(void)\n    :currentTime(0) {\n}\n\n\nSimulation::~Simulation(void) {\n}\n\nvoid Simulation::doGenericStep(const std::vector< double > &state,\n                               std::vector< double > &der,\n                               double time) {\n    // Copy the state variables to the actual systems\n    auto si = states.cbegin();\n    for (auto i = state.cbegin(); i != state.cend(); ++i) {\n        **si++ = *i;\n    }\n\n    // Copy state outputs from all systems to their respective inputs\n    // Since they are states, and constant input to this function this\n    // is done before the timestep calulations.\n    for ( auto syst = systems.begin(); syst != systems.end(); ++syst ) {\n\t\t(*syst)->preStep();\n        (*syst)->copystateoutputs();\n\t\t(*syst)->copyoutputs();\n    }\n\n    // Do the time step for all systems, and copy the variable\n    // outputs after the time step.\n    for ( auto syst = systems.begin(); syst != systems.end(); ++syst ) {\n        (*syst)->doStep(time);\n        (*syst)->copyoutputs();\n    }\n\n    // Copy the systems derivate variables to the\n    // solvers (the input to this function).\n    auto di = der.begin();\n    for ( auto i = ders.cbegin(); i != ders.cend(); ++i ) {\n        *(di++) = **i;\n    }\n}\n\nvoid Simulation::observer(const std::vector<double> &state, double time) {\n    currentTime = time;\n\n    // Copy the state variables to the actual systems\n    auto si = states.cbegin();\n    for (auto i = state.cbegin(); i != state.cend(); ++i) {\n        **si++ = *i;\n    }\n\n    for ( auto syst = systems.cbegin(); syst != systems.end(); ++syst ) {\n        (*syst)->postStep();\n        (*syst)->doStoreStep(time);\n    }\n    for (   auto syst = discreteSystems.cbegin();\n            syst != discreteSystems.end();\n            ++syst) {\n        (*syst)->postStep();\n        (*syst)->doStoreStep(time);\n    }\n\n    bool compare_break = false;\n    for (auto syst = systems.cbegin(); syst != systems.end(); ++syst) {\n        if ((*syst)->do_comparison()) {\n            compare_break = true;\n        }\n    }\n    if (compare_break) {\n        throw earlybreak;\n    }\n}\n\n\nvoid Simulation::prepare_first_sim() {\n    // Copy system states to this objects list\n    for ( auto syst = systems.cbegin(); syst != systems.end(); ++syst ) {\n        (*syst)->preSim();\n\n        std::vector<double*> sp = (*syst)->getStatePointers();\n        std::copy(sp.cbegin(), sp.cend(), std::back_inserter(states));\n\n        std::vector<double*> dp = (*syst)->getDerPointers();\n        std::copy(dp.cbegin(), dp.cend(), std::back_inserter(ders));\n\n        if (ders.size() != states.size()) {\n            throw std::runtime_error(\"Unequal states and ders\");\n        }\n\n    }\n    for (   auto syst = discreteSystems.cbegin();\n            syst != discreteSystems.end();\n            ++syst) {\n        (*syst)->preSim();\n    }\n}\n\nbool myfn(SimulatableSystemInterface* i, SimulatableSystemInterface* j) {\n    return i->getNextUpdateTime() < j->getNextUpdateTime();\n}\n\nvoid Simulation::simulate(double duration,\n                          double dt,\n                          char* solvername,\n                          double abs_err,\n                          double rel_err,\n                          bool dense_output) {\n    if (currentTime == 0.0) {\n        prepare_first_sim();\n    }\n    double endtime = currentTime + duration;\n\n    if (discreteSystems.size() > 0) {\n        auto si = std::min_element(discreteSystems.begin(),\n                                   discreteSystems.end(),\n                                   myfn);\n        double inter_endtime = (*si)->getNextUpdateTime();\n        while (inter_endtime < endtime) {\n            if (inter_endtime > 0) {\n                setup_odeint(inter_endtime, dt, solvername,\n                             abs_err, rel_err, dense_output);\n            }\n            do {\n                (*si)->doStep(currentTime);\n                std::vector<double*> states = (*si)->getStatePointers();\n                std::vector<double*> ders = (*si)->getDerPointers();\n\n                //Copy states to der\n                auto state_iter = states.begin();\n                auto der_iter = ders.begin();\n                while (state_iter != states.end()) {\n                    **state_iter++ = **der_iter++;\n                }\n\n                (*si)->copystateoutputs();\n                (*si)->copyoutputs();\n                si = std::min_element(discreteSystems.begin(),\n                                      discreteSystems.end(),\n                                      myfn);\n            } while ((*si)->getNextUpdateTime() == inter_endtime);\n\n            si = std::min_element(discreteSystems.begin(),\n                                  discreteSystems.end(),\n                                  myfn);\n            inter_endtime = (*si)->getNextUpdateTime();\n        }\n    }\n    setup_odeint(endtime, dt, solvername, abs_err, rel_err, dense_output);\n}\n\nvoid Simulation::setup_odeint(double endtime,\n                              double dt,\n                              char* solvername,\n                              double abs_err,\n                              double rel_err,\n                              bool dense_output) {\n    using namespace boost::numeric::odeint;\n    using std::vector;\n\n    namespace pl = std::placeholders;\n    auto ff = std::bind(&Simulation::doGenericStep,\n                        this,\n                        pl::_1, pl::_2, pl::_3);\n    auto sf = std::bind(&Simulation::observer, this, pl::_1, pl::_2);\n\n    vector< double > state;\n    for ( auto i = states.cbegin(); i != states.cend(); ++i ) {\n        state.push_back(**i);\n    }\n    try {\n        if (strcmp(solvername, \"rk4\") == 0) {\n            runge_kutta4<vector< double > > stepper;\n            integrate_const(stepper, ff, state, currentTime, endtime, dt, sf);\n        } else if (strcmp(solvername, \"ck54\") == 0) {\n            typedef runge_kutta_cash_karp54<vector<double> > error_stepper_type;\n            auto cs = make_controlled <error_stepper_type>(abs_err, rel_err);\n            integrate_adaptive(cs, ff, state, currentTime, endtime, dt, sf);\n        } else if (strcmp(solvername, \"dp5\") == 0) {\n            typedef runge_kutta_dopri5<vector<double> > error_stepper_type;\n            if (dense_output) {\n                auto cs = make_dense_output(abs_err, rel_err, error_stepper_type());\n                integrate_const(cs, ff, state, currentTime, endtime, dt, sf);\n            } else {\n                auto cs = make_controlled <error_stepper_type>(abs_err, rel_err);\n                integrate_adaptive(cs, ff, state, currentTime, endtime, dt, sf);\n            }\n        } else {\n            char errmsg[50];\n            snprintf(errmsg, sizeof(errmsg), \"Unknown solver: %s\", solvername);\n            throw std::invalid_argument(errmsg);\n        }\n    } catch (EarlyBreakException &eb) {\n        printf(\"%s\\n\",eb.what());\n    }\n}\n\n\nvoid Simulation::addSystem(SimulatableSystemInterface* system) {\n    if (system->getDiscrete()) {\n        discreteSystems.push_back(system);\n    } else {\n        systems.push_back(system);\n    }\n}\n\n}\n", "meta": {"hexsha": "013dd4ca91790159351e4a8e613d8ef829799e11", "size": 7442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pysim/cppsource/CppSimulation.cpp", "max_stars_repo_name": "freol35241/pysim", "max_stars_repo_head_hexsha": "36faf67d00ff644a593f20994c0f15053d600886", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-01-15T07:43:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T20:21:38.000Z", "max_issues_repo_path": "pysim/cppsource/CppSimulation.cpp", "max_issues_repo_name": "freol35241/pysim", "max_issues_repo_head_hexsha": "36faf67d00ff644a593f20994c0f15053d600886", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2016-05-06T23:21:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T22:40:25.000Z", "max_forks_repo_path": "pysim/cppsource/CppSimulation.cpp", "max_forks_repo_name": "freol35241/pysim", "max_forks_repo_head_hexsha": "36faf67d00ff644a593f20994c0f15053d600886", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T14:55:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-11T06:29:35.000Z", "avg_line_length": 33.5225225225, "max_line_length": 84, "alphanum_fraction": 0.5354743349, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.029312228631440916, "lm_q1q2_score": 0.010115804604232524}}
{"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_DETAIL_RANGE_GENERATOR_INCLUDE\n#define MTL_DETAIL_RANGE_GENERATOR_INCLUDE\n\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/glas_tag.hpp>\n#include <boost/numeric/mtl/utility/complexity.hpp>\n#include <boost/numeric/mtl/detail/base_cursor.hpp>\n#include <boost/mpl/less.hpp>\n\nnamespace mtl { namespace traits { namespace detail {\n\n    /// Range generator that traverses all elements of some densely stored collection \n    /** - Or contiguous parts of such collection\n        - Works for matrices and vectors when derived from contiguous_memory_block\n    **/\n    template <typename Collection, typename Cursor, typename Complexity>\n    struct dense_element_range_generator\n    {\n\ttypedef Complexity          complexity;\n\ttypedef Cursor              type;\n\tstatic int const            level = 1;\n\n\ttype begin(Collection const& collection)\n\t{\n\t    return collection.elements();\n\t}\n\ttype end(Collection const& collection)\n\t{\n\t    return collection.elements() + collection.used_memory();\n\t}\n    };\n\n    /// Range generator that traverses all elements of some collection stored in strides\n    template <typename Collection, typename Ref, typename Traversor>\n    struct strided_element_range_generator\n    {\n\ttypedef complexity_classes::linear  complexity;\n\ttypedef Traversor                   type;\n\tstatic int const                    level = 1;\n\n\ttype begin(Ref& c)\n\t{\n\t    return type(c.address_data(), c.stride());\n\t}\n\ttype end(Ref& c)\n\t{\n\t\tusing mtl::size;\n\t    return type(c.address_data() + size(c) + c.stride(), c.stride());\n\t}\n    };\n\n\n    // Like above over all elements but in terms of offsets\n    // Also with reference to collection in cursor\n    template <typename Matrix, typename Cursor, typename Complexity>\n    struct all_offsets_range_generator\n    {\n\ttypedef Complexity          complexity;\n\ttypedef Cursor              type;\n\tstatic int const            level = 1;\n\n\ttype begin(Matrix const& matrix) const\n\t{\n\t    return type(matrix, 0);\n\t}\n\ttype end(Matrix const& matrix) const\n\t{\n\t    return type(matrix, matrix.nnz());\n\t}\n    };\n    \n\n    // Cursor to some submatrix (e.g. row, column, block matrix, block row)\n    // This cursor is intended to be used by range generators to iterate \n    // over subsets of the submatrix this cursor refers to.\n    // For instance if this cursor refers to a row then a range \n    // can iterate over the elements in this row.\n    // If this cursor refers to a block then a range can iterate over the rows in this block.\n    // The level of a generated cursor must be of course at least one level less\n    // The tag serves to dispatching between row and column cursors\n    template <typename Matrix, typename Tag, int Level>\n    struct sub_matrix_cursor\n      : mtl::detail::base_cursor<std::size_t>\n    {\n\ttypedef sub_matrix_cursor                        self;\n\ttypedef mtl::detail::base_cursor<std::size_t>    base;\n\ttypedef Matrix                                   ref_type;\n\tstatic int const                                 level = Level;\n\n\tsub_matrix_cursor(std::size_t i, Matrix const& c)\n\t    : base(i), ref(c) \n\t{}\t\n\n\tself operator+(std::size_t offset) const\n\t{\n\t    return self(key + offset, ref);\n\t}\n\n\t// otherwise base_cursor returns an int and ranged for doesn't work\n\t// for getting the key of base_cursor use this->value()\n\tself operator*() const { return *this; }\n\t\n\tMatrix const& ref;\n    };\n\n    // Key for canonically referring to its elements with row and column index\n    template <typename Matrix>\n    struct matrix_element_key\n    {\n\ttypedef typename Collection<Matrix>::size_type           size_type;\n\ttypedef matrix_element_key                               self;\n\n\tmatrix_element_key(Matrix const& ref, std::size_t r, std::size_t c) : ref(ref)\n\t{\n\t    indices[0]= size_type(r); indices[1]= size_type(c);\n\t}\n\n\tbool operator==(const self& cc) const { return &ref == &cc.ref && indices[0] == cc.indices[0] && indices[1] == cc.indices[1]; }\n\tbool operator!=(const self& cc) const { return !(*this == cc); }\n\n\tsize_type indices[2];\n\tMatrix const& ref;\n    };\n\n    // Cursor for canonically referring to its elements with row and column index\n    // Increments row for pos==0 and column for pos==1\n    // Referring operator returns matrix_element_key\n    template <typename Matrix, int pos>\n    struct matrix_element_cursor\n    {\n\ttypedef typename Collection<Matrix>::size_type           size_type;\n\ttypedef matrix_element_cursor                            self;\n\ttypedef matrix_element_key<Matrix>                       key_type;\n\tstatic int const            level = 2;\n\t\n\tmatrix_element_cursor(Matrix const& ref, size_type r, size_type c) : ref(ref)\n\t{\n\t    indices[0]= r; indices[1]= c;\n\t}\n\t\n\tkey_type operator*() const { return key_type(ref, indices[0], indices[1]); }\n\n\tself& operator++() { ++indices[pos]; return *this; }\n\tself operator++(int) { self tmp(*this); ++indices[pos]; return tmp; }\n\ttemplate <typename T> self& operator+=(T n) { indices[pos] += size_type(n); return *this; }\n\ttemplate <typename T> self& operator+(T n) const { self tmp = *this; tmp += n; return tmp; }\n\n\tself& operator--() { indices[pos]--; return *this; }\n\tself operator--(int) { self tmp(*this); indices[pos]--; return tmp; }\n\ttemplate <typename T> self& operator-=(T n) { indices[pos] -= size_type(n); return *this; }\n\ttemplate <typename T> self& operator-(T n) const { self tmp = *this; tmp -= n; return tmp; }\n\n\tbool operator==(const self& cc) const { return &ref == &cc.ref && indices[0] == cc.indices[0] && indices[1] == cc.indices[1]; }\n\tbool operator!=(const self& cc) const { return !(*this == cc); }\n\n\tsize_type indices[2];\n\tMatrix const& ref;\n    };\n\n\n    template <typename Matrix, typename Complexity, int Level>\n    struct all_rows_range_generator\n    {\n\ttypedef Complexity                                       complexity;\n\tstatic int const                                         level = Level;\n\ttypedef Matrix                                           ref_type;\n\ttypedef sub_matrix_cursor<Matrix, glas::tag::row, Level> type;\n\ttypedef typename Collection<Matrix>::size_type           size_type;\n\n\ttype begin(Matrix const& c) const\n\t{\n\t    return type(0, c); // return type(c.begin_row(), c); get rid of obsolete stuff\n\t}\n\ttype end(Matrix const& c) const\n\t{\n\t\tusing mtl::num_rows; using mtl::mat::num_rows;\n\t    return type(int(num_rows(c)), c); //return type(c.end_row(), c);\n\t}\n\ttype lower_bound(Matrix const& c, size_type position) const\n\t{\n\t\tusing mtl::num_rows;\n\t    return type(std::min(num_rows(c), position), c);\n\t}\n    };\n\n    template <typename Cursor>\n    struct all_cols_in_row_range_generator\n    {\n\ttypedef complexity_classes::linear                       complexity;\n\tstatic int const                                         level = 1;\n\ttypedef typename Cursor::ref_type                        ref_type;\n\ttypedef typename Collection<ref_type>::size_type         size_type;\n\n\n\ttypedef matrix_element_cursor<ref_type, 1>               type;\n\n\ttype begin(Cursor const& c) const { return type(c.ref, c.value(), size_type(0)); }\n\ttype end(Cursor const& c) const { using mtl::num_cols; return type(c.ref, c.value(), num_cols(c.ref)); }\n\ttype lower_bound(Cursor const& c, size_type position) const\n\t{\n\t\tusing mtl::num_cols;\n\t    return type(c.ref, c.value, std::min(num_cols(c.ref), position));\n\t}\n    };\n\n\n    template <typename Matrix, typename Complexity, int Level>\n    struct all_cols_range_generator\n    {\n\ttypedef Complexity          complexity;\n\tstatic int const            level = Level;\n\ttypedef sub_matrix_cursor<Matrix, glas::tag::col, Level> type;\n\ttypedef typename Collection<Matrix>::size_type           size_type;\n\n\ttype begin(Matrix const& c) const\n\t{\n\t    return type(0, c); // return type(c.begin_col(), c);\n\t}\n\ttype end(Matrix const& c) const\n\t{\n\t\tusing mtl::num_cols;\n\t    return type(num_cols(c), c); // return type(c.end_col(), c);\n\t}\n\ttype lower_bound(Matrix const& c, size_type position) const\n\t{\n\t\tusing mtl::num_cols;\n\t    return type(std::min(num_cols(c), position), c);\n\t}\n    };\n\n    template <typename Cursor>\n    struct all_rows_in_col_range_generator\n    {\n\ttypedef complexity_classes::linear                       complexity;\n\tstatic int const            level = 1;\n\ttypedef typename Cursor::ref_type                        ref_type;\n\ttypedef typename Collection<ref_type>::size_type         size_type;\n\n\n\ttypedef matrix_element_cursor<ref_type, 0> type;\n\n\ttype begin(Cursor const& c) const { return type(c.ref, 0, c.value()); }\n\ttype end(Cursor const& c) const { using mtl::num_rows; return type(c.ref, num_rows(c.ref), c.value()); }\n\ttype lower_bound(Cursor const& c, size_type position) const\n\t{\n\t\tusing mtl::num_rows;\n\t    return type(c.ref, std::min(num_rows(c.ref), position), c.value());\n\t}\n    };\n\n\n    // Use RangeGenerator for Collection by applying to .ref\n    template <typename Coll, typename RangeGenerator>\n    struct referred_range_generator\n    {\n\ttypedef typename RangeGenerator::complexity complexity;\n\tstatic int const                            level = RangeGenerator::level;\n\ttypedef typename RangeGenerator::type       type;\n\ttypedef typename Collection<Coll>::size_type  size_type;\n\t\n\ttype begin(const Coll& c)\n\t{\n\t    return RangeGenerator().begin(c.ref);\n\t}\n\n\ttype end(const Coll& c)\n\t{\n\t    return RangeGenerator().end(c.ref);\n\t}\n\ttype lower_bound(const Coll& c, size_type position)\n\t{\n\t    return RangeGenerator().lower_bound(c.ref, position);\n\t}\n    };\n\n} // namespace detail\n\n    namespace range {\n\n\ttemplate <typename Range1, typename Range2>\n\tstruct min\n\t    : public boost::mpl::if_< \n\t            boost::mpl::less<\n\t                   typename Range1::complexity, \n\t                   typename Range2::complexity>\n\t          , Range1\n\t          , Range2\n\t      >\n\t{};\n    }\n\n}} // namespace mtl::traits\n\n#endif // MTL_DETAIL_RANGE_GENERATOR_INCLUDE\n", "meta": {"hexsha": "cb20616ab0192689844e8d5d1e2ddc6b17300d78", "size": 10330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/detail/range_generator.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/detail/range_generator.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/detail/range_generator.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": 33.538961039, "max_line_length": 128, "alphanum_fraction": 0.6511132623, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.04535258265106529, "lm_q1q2_score": 0.010100026452478534}}
{"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_MOTIFS_HH\n#define GRAPH_MOTIFS_HH\n\n#include <boost/graph/isomorphism.hpp>\n#include <boost/functional/hash.hpp>\n#include <algorithm>\n#include <vector>\n\n#include \"random.hh\"\n#include \"hash_map_wrap.hh\"\n\nnamespace graph_tool\n{\nnamespace mpl = boost::mpl;\n\ntemplate <class Value>\nvoid insert_sorted(std::vector<Value>& v, const Value& val)\n{\n    auto iter = lower_bound(v.begin(), v.end(), val);\n    if (iter != v.end() && *iter == val)\n        return; // no repetitions\n    v.insert(iter, val);\n}\n\ntemplate <class Value>\nbool has_val(std::vector<Value>& v, const Value& val)\n{\n    auto iter = lower_bound(v.begin(), v.end(), val);\n    if (iter == v.end())\n        return false;\n    return *iter == val;\n}\n\n// gets all the subgraphs starting from vertex v and store it in subgraphs.\ntemplate <class Graph, class Sampler>\nvoid get_subgraphs(Graph& g, typename boost::graph_traits<Graph>::vertex_descriptor v,\n                   size_t n,\n                   std::vector<std::vector<typename boost::graph_traits<Graph>::vertex_descriptor> >& subgraphs,\n                   Sampler sampler)\n{\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t;\n\n    // extension and subgraph stack\n    std::vector<std::vector<vertex_t>> ext_stack(1);\n    std::vector<std::vector<vertex_t>> sub_stack(1);\n    std::vector<std::vector<vertex_t>> sub_neighbors_stack(1);\n\n    sub_stack[0].push_back(v);\n    for (auto e : out_edges_range(v, g))\n    {\n        typename boost::graph_traits<Graph>::vertex_descriptor u = target(e, g);\n        if (u > v && !has_val(ext_stack[0], u))\n        {\n            insert_sorted(ext_stack[0], u);\n            insert_sorted(sub_neighbors_stack[0],u);\n        }\n    }\n\n    while (!sub_stack.empty())\n    {\n        std::vector<vertex_t>& ext = ext_stack.back();\n        std::vector<vertex_t>& sub = sub_stack.back();\n        std::vector<vertex_t>& sub_neighbors = sub_neighbors_stack.back();\n\n        if (sub.size() == n)\n        {\n            // found a subgraph of the desired size; put it in the list and go\n            // back a level\n            subgraphs.push_back(sub);\n            sub_stack.pop_back();\n            ext_stack.pop_back();\n            sub_neighbors_stack.pop_back();\n            continue;\n        }\n\n        if (ext.empty())\n        {\n            // no where else to go\n            ext_stack.pop_back();\n            sub_stack.pop_back();\n            sub_neighbors_stack.pop_back();\n            continue;\n        }\n        else\n        {\n            // extend subgraph\n            std::vector<vertex_t> new_ext, new_sub = sub,\n                new_sub_neighbors = sub_neighbors;\n\n            // remove w from ext\n            vertex_t w = ext.back();\n            ext.pop_back();\n\n            // insert w in subgraph\n            insert_sorted(new_sub, w);\n\n            // update new_ext\n            new_ext = ext;\n            for (auto e : out_edges_range(w, g))\n            {\n                vertex_t u = target(e, g);\n                if (u > v)\n                {\n                    if (!has_val(sub_neighbors, u))\n                        insert_sorted(new_ext, u);\n                    insert_sorted(new_sub_neighbors, u);\n                }\n            }\n\n            sampler(new_ext, ext_stack.size());\n\n            ext_stack.push_back(new_ext);\n            sub_stack.push_back(new_sub);\n            sub_neighbors_stack.push_back(new_sub_neighbors);\n        }\n    }\n}\n\n// sampling selectors\n\nstruct sample_all\n{\n    template <class val_type>\n    void operator()(std::vector<val_type>&, size_t) {}\n};\n\nstruct sample_some\n{\n    sample_some(std::vector<double>& p, rng_t& rng): _p(&p), _rng(&rng) {}\n    sample_some() {}\n\n    template <class val_type>\n    void operator()(std::vector<val_type>& extend, size_t d)\n    {\n        typedef std::uniform_real_distribution<double> rdist_t;\n        auto random = std::bind(rdist_t(), std::ref(*_rng));\n\n        double pd = (*_p)[d+1];\n        size_t nc = extend.size();\n        double u = nc*pd - floor(nc*pd);\n        size_t n;\n        double r;\n        #pragma omp critical (random)\n        {\n            r = random();\n        }\n        if (r < u)\n            n = size_t(ceil(nc*pd));\n        else\n            n = size_t(floor(nc*pd));\n\n        if (n == extend.size())\n            return;\n        if (n == 0)\n        {\n            extend.clear();\n            return;\n        }\n\n        typedef std::uniform_int_distribution<size_t> idist_t;\n        for (size_t i = 0; i < n; ++i)\n        {\n            auto random_v = std::bind(idist_t(0, extend.size()-i-1),\n                                      std::ref(*_rng));\n            size_t j;\n            #pragma omp critical (random)\n            {\n                j = i + random_v();\n            }\n            std::swap(extend[i], extend[j]);\n        }\n        extend.resize(n);\n    }\n\n    std::vector<double>* _p;\n    rng_t* _rng;\n};\n\n\n// build the actual induced subgraph from the vertex list\ntemplate <class Graph, class GraphSG>\nvoid make_subgraph\n    (std::vector<typename boost::graph_traits<Graph>::vertex_descriptor>& vlist,\n     Graph& g, GraphSG& sub)\n{\n    for (size_t i = 0; i < vlist.size(); ++i)\n        add_vertex(sub);\n    for (size_t i = 0; i < vlist.size(); ++i)\n    {\n        typename boost::graph_traits<Graph>::vertex_descriptor ov = vlist[i], ot;\n        typename boost::graph_traits<GraphSG>::vertex_descriptor nv = vertex(i,sub);\n        for (auto e : out_edges_range(ov, g))\n        {\n            ot = target(e, g);\n            auto viter = lower_bound(vlist.begin(), vlist.end(), ot);\n            size_t ot_index = viter - vlist.begin();\n            if (viter != vlist.end() && vlist[ot_index] == ot &&\n                (graph_tool::is_directed(g) || ot < ov))\n                add_edge(nv, vertex(ot_index, sub), sub);\n        }\n    }\n}\n\n// compare two graphs for labeled exactness (not isomorphism)\ntemplate <class Graph>\nbool graph_cmp(Graph& g1, Graph& g2)\n{\n    if (num_vertices(g1) != num_vertices(g2) || num_edges(g1) != num_edges(g2))\n        return false;\n\n    typename boost::graph_traits<Graph>::vertex_iterator v1, v1_end;\n    typename boost::graph_traits<Graph>::vertex_iterator v2, v2_end;\n    std::tie(v2, v2_end) = vertices(g2);\n    for (std::tie(v1, v1_end) = vertices(g1); v1 != v1_end; ++v1)\n    {\n        if (out_degree(*v1, g1) != out_degree(*v2, g2))\n            return false;\n        if (in_degreeS()(*v1, g1) != in_degreeS()(*v2, g2))\n            return false;\n\n        std::vector<typename boost::graph_traits<Graph>::vertex_descriptor> out1, out2;\n        typename boost::graph_traits<Graph>::out_edge_iterator e, e_end;\n        for (std::tie(e, e_end) = out_edges(*v1, g1); e != e_end; ++e)\n            out1.push_back(target(*e, g1));\n        for (std::tie(e, e_end) = out_edges(*v2, g2); e != e_end; ++e)\n            out2.push_back(target(*e, g2));\n        std::sort(out1.begin(), out1.end());\n        std::sort(out2.begin(), out2.end());\n        if (out1 != out2)\n            return false;\n    }\n    return true;\n}\n\n// short hand for subgraph types\ntypedef boost::adj_list<size_t> d_graph_t;\n\n// we need this wrap to use the undirected_adaptor only on directed graphs\nstruct wrap_undirected\n{\n    template <class Graph>\n    struct apply\n    {\n        typedef typename mpl::if_<typename is_directed_::apply<Graph>::type,\n                                  boost::undirected_adaptor<Graph>,\n                                  Graph&>::type type;\n    };\n};\n\nstruct wrap_directed\n{\n    template <class Graph, class Sub>\n    struct apply\n    {\n        typedef typename mpl::if_<typename is_directed_::apply<Graph>::type,\n                                  Sub&,\n                                  boost::undirected_adaptor<Sub>>::type type;\n    };\n};\n\n\n// get the signature of the graph: sorted degree sequence\ntemplate <class Graph>\nvoid get_sig(Graph& g, std::vector<size_t>& sig)\n{\n    sig.clear();\n    size_t N = num_vertices(g);\n    if (N > 0)\n        sig.resize(graph_tool::is_directed(g) ? 2 * N : N);\n    for (size_t i = 0; i < N; ++i)\n    {\n        auto v = vertex(i, g);\n        sig[i] = out_degree(v, g);\n        if(graph_tool::is_directed(g))\n            sig[i + N] = in_degreeS()(v, g);\n    }\n    sort(sig.begin(), sig.end());\n}\n\n// gets (or samples) all the subgraphs in graph g\nstruct get_all_motifs\n{\n    get_all_motifs(bool collect_vmaps, double p, bool comp_iso, bool fill_list,\n                   rng_t& rng)\n        : collect_vmaps(collect_vmaps), p(p),\n          comp_iso(comp_iso), fill_list(fill_list), rng(rng) {}\n    bool collect_vmaps;\n    double p;\n    bool comp_iso;\n    bool fill_list;\n    rng_t& rng;\n\n    template <class Graph, class Sampler, class VMap>\n    void operator()(Graph& g, size_t k, std::vector<d_graph_t>& subgraph_list,\n                    std::vector<size_t>& hist, std::vector<std::vector<VMap> >& vmaps,\n                    Sampler sampler) const\n    {\n        // this hashes subgraphs according to their signature\n        gt_hash_map<std::vector<size_t>,\n                    std::vector<std::pair<size_t, d_graph_t> >,\n                    std::hash<std::vector<size_t>>> sub_list;\n        std::vector<size_t> sig; // current signature\n\n        for (size_t i = 0; i < subgraph_list.size(); ++i)\n        {\n            auto& sub = subgraph_list[i];\n            typename wrap_directed::apply<Graph,d_graph_t>::type\n                usub(sub);\n            get_sig(usub, sig);\n            sub_list[sig].emplace_back(i, sub);\n        }\n\n        // the subgraph count\n        hist.resize(subgraph_list.size());\n\n        typedef std::uniform_real_distribution<double> rdist_t;\n        auto random = std::bind(rdist_t(), std::ref(rng));\n\n        // the set of vertices V to be sampled (filled only if p < 1)\n        std::vector<size_t> V;\n        if (p < 1)\n        {\n            for (auto v : vertices_range(g))\n                V.push_back(v);\n\n            size_t n;\n            if (random() < p)\n                n = size_t(ceil(V.size()*p));\n            else\n                n = size_t(floor(V.size()*p));\n\n            typedef std::uniform_int_distribution<size_t> idist_t;\n            for (size_t i = 0; i < n; ++i)\n            {\n                auto random_v = std::bind(idist_t(0, V.size()-i-1),\n                                          std::ref(rng));\n                size_t j = i + random_v();\n                std::swap(V[i], V[j]);\n            }\n            V.resize(n);\n        }\n\n        size_t N = (p < 1) ? V.size() : num_vertices(g);\n        #pragma omp parallel for if (num_vertices(g) > OPENMP_MIN_THRESH) \\\n            private(sig)\n        for (size_t i = 0; i < N; ++i)\n        {\n            std::vector<std::vector<typename boost::graph_traits<Graph>::vertex_descriptor> >\n                subgraphs;\n            typename boost::graph_traits<Graph>::vertex_descriptor v =\n                (p < 1) ? V[i] : vertex(i, g);\n            if (!is_valid_vertex(v, g))\n                continue;\n\n            typename wrap_undirected::apply<Graph>::type ug(g);\n            get_subgraphs(ug, v, k, subgraphs, sampler);\n\n            for (size_t j = 0; j < subgraphs.size(); ++j)\n            {\n                d_graph_t sub;\n                typename wrap_directed::apply<Graph,d_graph_t>::type\n                    usub(sub);\n                make_subgraph(subgraphs[j], g, usub);\n                get_sig(usub, sig);\n\n                #pragma omp critical (gather)\n                {\n                    bool skip = false;\n                    auto iter = sub_list.find(sig);\n                    if(iter == sub_list.end())\n                    {\n                        if (!fill_list)\n                            skip = true; // avoid inserting an element in sub_list\n                        sub_list[sig].clear();\n                    }\n\n                    if (!skip)\n                    {\n                        bool found = false;\n                        size_t pos;\n                        auto sl = sub_list.find(sig);\n                        if (sl != sub_list.end())\n                        {\n                            for (auto& mpos : sl->second)\n                            {\n                                d_graph_t& motif = mpos.second;\n                                typename wrap_directed::apply<Graph,d_graph_t>::type\n                                    umotif(motif);\n                                if (comp_iso)\n                                {\n                                    if (isomorphism(umotif, usub,\n                                                    vertex_index1_map(get(boost::vertex_index, umotif)).\n                                                    vertex_index2_map(get(boost::vertex_index, usub))))\n                                        found = true;\n                                }\n                                else\n                                {\n                                    if (graph_cmp(umotif, usub))\n                                        found = true;\n                                }\n                                if (found)\n                                {\n                                    pos = mpos.first;\n                                    hist[pos]++;\n                                    break;\n                                }\n                            }\n                        }\n\n                        if (found == false && fill_list)\n                        {\n                            subgraph_list.push_back(sub);\n                            sub_list[sig].emplace_back(subgraph_list.size() - 1,\n                                                       sub);\n                            hist.push_back(1);\n                            pos = hist.size() - 1;\n                            found = true;\n                        }\n\n                        if (found && collect_vmaps)\n                        {\n                            if (pos >= vmaps.size())\n                                vmaps.resize(pos + 1);\n                            vmaps[pos].push_back(VMap(get(boost::vertex_index,sub)));\n                            for (size_t vi = 0; vi < num_vertices(sub); ++vi)\n                                vmaps[pos].back()[vertex(vi, sub)] = subgraphs[j][vi];\n                        }\n                    }\n                }\n            }\n        }\n    }\n};\n\n} //graph-tool namespace\n\n#endif // GRAPH_MOTIFS_HH\n", "meta": {"hexsha": "409ca9dddadc5ce1bc5ced9a5f2a23dcad4e54c1", "size": 15130, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/clustering/graph_motifs.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/clustering/graph_motifs.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/clustering/graph_motifs.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": 33.2527472527, "max_line_length": 112, "alphanum_fraction": 0.5001321877, "num_tokens": 3431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.025957356915230906, "lm_q1q2_score": 0.010087497190497001}}
{"text": "#include \"MeshCuboidPredictor.h\"\n\n#include \"ICP.h\"\n#include \"MeshCuboidParameters.h\"\n#include \"Utilities.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <ANN/ANN.h>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n\nMeshCuboidPredictor::MeshCuboidPredictor(unsigned int _num_labels)\n\t: num_labels_(_num_labels)\n{\n\n}\n\nvoid MeshCuboidPredictor::get_missing_label_indices(\n\tconst std::list<LabelIndex> &_given_label_indices,\n\tstd::list<LabelIndex> &_missing_label_indices) const\n{\n\t_missing_label_indices.clear();\n}\n\nReal MeshCuboidPredictor::get_single_potential(\n\tconst MeshCuboid *_cuboid,\n\tconst MeshCuboidAttributes *_attributes,\n\tconst MeshCuboidTransformation *_transformation,\n\tconst LabelIndex _label_index)const\n{\n\tassert(_cuboid);\n\tassert(_attributes);\n\tassert(_transformation);\n\n\tReal potential = 0.0;\n\tunsigned int num_sample_points = 0;\n\n\t// FIXME:\n\t// This should be done in pre-processing.\n\t//unsigned int num_confidence_tol_sample_point = 0;\n\t//for (std::vector<MeshSamplePoint *>::const_iterator sample_it = _cuboid->get_sample_points().begin();\n\t//\tsample_it != _cuboid->get_sample_points().end(); ++sample_it)\n\t//{\n\t//\tassert(_label_index < (*sample_it)->label_index_confidence_.size());\n\t//\tif ((*sample_it)->label_index_confidence_[_label_index] >= FLAGS_param_min_sample_point_confidence)\n\t//\t\t++num_confidence_tol_sample_point;\n\t//}\n\n\t//if (num_confidence_tol_sample_point <\n\t//\tFLAGS_param_min_num_confidence_tol_sample_points * _cuboid->get_sample_points().size())\n\t//{\n\t//\tpotential = FLAGS_param_max_potential;\n\t//}\n\t\n\tfor (std::vector<MeshSamplePoint *>::const_iterator sample_it = _cuboid->get_sample_points().begin();\n\t\tsample_it != _cuboid->get_sample_points().end(); ++sample_it)\n\t{\n\t\tif (_label_index >= (*sample_it)->label_index_confidence_.size())\n\t\t{\n\t\t\t// Dummy label.\n\t\t\treturn -std::log(FLAGS_param_null_cuboid_probability);\n\t\t}\n\n\t\tassert((*sample_it)->label_index_confidence_[_label_index] >= 0.0);\n\t\tassert((*sample_it)->label_index_confidence_[_label_index] <= 1.0);\n\t\tif ((*sample_it)->label_index_confidence_[_label_index] < 10E-12)\n\t\t{\n\t\t\tpotential += 12;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpotential -= std::log((*sample_it)->label_index_confidence_[_label_index]);\n\t\t}\n\t\t++num_sample_points;\n\t}\n\n\tif (num_sample_points == 0)\n\t{\n\t\treturn -std::log(FLAGS_param_null_cuboid_probability);\n\t}\n\telse\n\t{\n\t\tpotential /= num_sample_points;\n\t}\n\n\treturn potential;\n}\n\nReal MeshCuboidPredictor::get_pair_potential(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidAttributes *_attributes_1, const MeshCuboidAttributes *_attributes_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2)const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_attributes_1); assert(_attributes_2);\n\tassert(_transformation_1); assert(_transformation_2);\n\n\t// Not implemented.\n\tReal potential = 0.0;\n\treturn potential;\n}\n\nvoid MeshCuboidPredictor::get_single_quadratic_form(\n\tMeshCuboid *_cuboid, const unsigned int _cuboid_index,\n\tEigen::MatrixXd &_quadratic_term, Eigen::VectorXd &_linear_term, double& _constant_term) const\n{\n\tassert(_cuboid);\n\n\t_quadratic_term.setZero();\n\t_linear_term.setZero();\n\t_constant_term = 0;\n\n\tunsigned int num_sample_points = _cuboid->num_sample_points();\n\tunsigned int num_cuboid_surface_points = _cuboid->num_cuboid_surface_points();\n\tconst unsigned int mat_size = _quadratic_term.cols();\n\tconst unsigned int num_corners = MeshCuboid::k_num_corners;\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\n\t// X: sample points, Y: cuboid surface points.\n\tunsigned int num_X_points = num_sample_points;\n\tunsigned int num_Y_points = num_cuboid_surface_points;\n\n\tif (num_X_points == 0 || num_Y_points == 0)\n\t\treturn;\n\n\tdouble sum_visibility = 0.0;\n\tfor (int cuboid_surface_point_index = 0;\n\t\tcuboid_surface_point_index < num_cuboid_surface_points;\n\t\t++cuboid_surface_point_index)\n\t{\n\t\tsum_visibility += _cuboid->get_cuboid_surface_point(cuboid_surface_point_index)->visibility_;\n\t}\n\n\tif (sum_visibility == 0)\n\t\treturn;\n\n\tEigen::MatrixXd all_X_points(3, num_X_points + num_Y_points);\n\tEigen::MatrixXd all_Y_points(3, num_X_points + num_Y_points);\n\tEigen::MatrixXd all_Y_coeffs(num_corners, num_X_points + num_Y_points);\n\tEigen::VectorXd all_weights(num_X_points + num_Y_points);\n\n\tunsigned int pair_index = 0;\n\n\n\t// Sample point -> Cuboid surface point.\n\tfor (int sample_point_index = 0; sample_point_index < num_sample_points; ++sample_point_index)\n\t{\n\t\tint cuboid_surface_point_index =\n\t\t\t_cuboid->get_sample_to_cuboid_surface_correspondences(sample_point_index);\n\t\tassert(cuboid_surface_point_index >= 0);\n\n\t\t//\n\t\tEigen::Vector3d X_point;\n\t\tEigen::Vector3d Y_point;\n\t\tEigen::VectorXd Y_coeff(MeshCuboid::k_num_corners);\n\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tX_point(i) = _cuboid->get_sample_point(sample_point_index)->point_[i];\n\t\t\tY_point(i) = _cuboid->get_cuboid_surface_point(cuboid_surface_point_index)->point_[i];\n\t\t}\n\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t\tY_coeff(corner_index) = _cuboid->get_cuboid_surface_point(\n\t\t\tcuboid_surface_point_index)->corner_weights_[corner_index];\n\n\t\tall_X_points.col(pair_index) = X_point;\n\t\tall_Y_coeffs.col(pair_index) = Y_coeff;\n\t\tall_Y_points.col(pair_index) = Y_point;\n\t\tall_weights(pair_index) = 1.0 / num_sample_points;\n\n\t\t++pair_index;\n\t\t//\n\t}\n\n\t// Cuboid surface point -> Sample point.\n\tfor (int cuboid_surface_point_index = 0;\n\t\tcuboid_surface_point_index < num_cuboid_surface_points;\n\t\t++cuboid_surface_point_index)\n\t{\n\t\tint sample_point_index =\n\t\t\t_cuboid->get_cuboid_surface_to_sample_correspondence(cuboid_surface_point_index);\n\t\tassert(sample_point_index >= 0);\n\n\t\t//\n\t\tEigen::Vector3d X_point;\n\t\tEigen::Vector3d Y_point;\n\t\tEigen::VectorXd Y_coeff(MeshCuboid::k_num_corners);\n\n\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tX_point(i) = _cuboid->get_sample_point(sample_point_index)->point_[i];\n\t\t\tY_point(i) = _cuboid->get_cuboid_surface_point(cuboid_surface_point_index)->point_[i];\n\t\t}\n\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t\tY_coeff(corner_index) = _cuboid->get_cuboid_surface_point(\n\t\t\tcuboid_surface_point_index)->corner_weights_[corner_index];\n\n\t\tdouble visibility = _cuboid->get_cuboid_surface_point(cuboid_surface_point_index)->visibility_;\n\n\t\tall_X_points.col(pair_index) = X_point;\n\t\tall_Y_coeffs.col(pair_index) = Y_coeff;\n\t\tall_Y_points.col(pair_index) = Y_point;\n\t\tall_weights(pair_index) = visibility / sum_visibility;\n\n\t\t++pair_index;\n\t\t//\n\t}\n\t\n\tassert(pair_index == num_X_points + num_Y_points);\n\n\tassert(_quadratic_term.rows() == mat_size);\n\tassert(_linear_term.rows() == mat_size);\n\tassert(_cuboid_index * MeshCuboidAttributes::k_num_attributes <= mat_size);\n\n\n\tMeshCuboidAttributes attribute;\n\tattribute.compute_attributes(_cuboid);\n\tEigen::VectorXd x = attribute.get_attributes();\n\n\tfor (unsigned int point_index = 0; point_index < num_X_points + num_Y_points; ++point_index)\n\t{\n\t\tEigen::Vector3d X_point = all_X_points.col(point_index);\n\t\tEigen::VectorXd Y_coeff = all_Y_coeffs.col(point_index);\n\t\tEigen::VectorXd Y_point = all_Y_points.col(point_index);\n\t\tassert(Y_coeff.size() == MeshCuboid::k_num_corners);\n\t\tdouble weight = all_weights(point_index);\n\n\t\tEigen::MatrixXd A0(3, num_attributes);\n\t\tA0.setZero();\n\n\t\tfor (unsigned int corner_index = 0; corner_index < MeshCuboid::k_num_corners; ++corner_index)\n\t\t{\n\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t\tA0.col(MeshCuboidAttributes::k_corner_index + 3 * corner_index + i)(i) =\n\t\t\t\tY_coeff(corner_index);\n\t\t}\n\n#ifdef DEBUG_TEST\n\t\tReal error = std::abs(((A0 * x) - Y_point).norm());\n\t\tCHECK_NUMERICAL_ERROR(__FUNCTION__, error);\n#endif\n\n\t\tEigen::Vector3d b = -X_point;\n\n\t\tEigen::MatrixXd A = Eigen::MatrixXd::Zero(3, mat_size);\n\t\tunsigned int start_index = (_cuboid_index * MeshCuboidAttributes::k_num_attributes);\n\t\tA.block<3, MeshCuboidAttributes::k_num_attributes>(0, start_index) = A0;\n\n\t\t_quadratic_term = _quadratic_term + weight * (A.transpose() * A);\n\t\t_linear_term = _linear_term + weight * (A.transpose() * b);\n\t\t_constant_term = _constant_term + weight * (b.transpose() * b)(0);\n\t}\n}\n\nReal MeshCuboidPredictor::get_pair_quadratic_form(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst unsigned int _cuboid_index_1, const unsigned int _cuboid_index_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2,\n\tEigen::MatrixXd &_quadratic_term, Eigen::VectorXd &_linear_term, double& _constant_term)const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\t//assert(_label_index_1 != _label_index_2);\n\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\tconst unsigned int mat_size = _quadratic_term.cols();\n\n\tassert(_quadratic_term.rows() == mat_size);\n\tassert(_linear_term.rows() == mat_size);\n\tassert(_cuboid_index_1 * num_attributes <= mat_size);\n\tassert(_cuboid_index_2 * num_attributes <= mat_size);\n\n\t_quadratic_term.setZero();\n\t_linear_term.setZero();\n\t_constant_term = 0;\n\n\treturn 0;\n}\n\nReal MeshCuboidPredictor::get_pair_conditional_quadratic_form(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst unsigned int _cuboid_index_1, const unsigned int _cuboid_index_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2,\n\tEigen::MatrixXd &_quadratic_term, Eigen::VectorXd &_linear_term, double& _constant_term)const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\t//assert(_label_index_1 != _label_index_2);\n\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\tconst unsigned int mat_size = _quadratic_term.cols();\n\n\tassert(_quadratic_term.rows() == mat_size);\n\tassert(_linear_term.rows() == mat_size);\n\tassert(_cuboid_index_1 * num_attributes <= mat_size);\n\tassert(_cuboid_index_2 * num_attributes <= mat_size);\n\n\t_quadratic_term.setZero();\n\t_linear_term.setZero();\n\t_constant_term = 0;\n\n\treturn 0;\n}\n\nMeshCuboidJointNormalRelationPredictor::MeshCuboidJointNormalRelationPredictor(\n\tconst std::vector< std::vector<MeshCuboidJointNormalRelations *> > &_relations)\n\t: MeshCuboidPredictor(_relations.size())\n\t, relations_(_relations)\n{\n\tfor (unsigned int label_index = 0; label_index < num_labels_; ++label_index)\n\t\tassert(relations_[label_index].size() == num_labels_);\n}\n\nvoid MeshCuboidJointNormalRelationPredictor::get_missing_label_indices(\n\tconst std::list<LabelIndex> &_given_label_indices,\n\tstd::list<LabelIndex> &_missing_label_indices)const\n{\n\t_missing_label_indices.clear();\n\tunsigned int num_labels = relations_.size();\n\n\tbool *is_missing_label = new bool[num_labels];\n\tmemset(is_missing_label, true, num_labels * sizeof(bool));\n\n\tfor (std::list<LabelIndex>::const_iterator it = _given_label_indices.begin();\n\t\tit != _given_label_indices.end(); ++it)\n\t{\n\t\tLabelIndex label_index = (*it);\n\t\tassert(label_index < num_labels);\n\t\tis_missing_label[label_index] = false;\n\t}\n\n\tfor (LabelIndex label_index_1 = 0; label_index_1 < num_labels; ++label_index_1)\n\t{\n\t\tif (is_missing_label[label_index_1])\n\t\t{\n\t\t\tbool is_label_confliced = false;\n\n\t\t\tfor (LabelIndex label_index_2 = 0; label_index_2 < num_labels; ++label_index_2)\n\t\t\t{\n\t\t\t\tif (!is_missing_label[label_index_2] && !relations_[label_index_1][label_index_2])\n\t\t\t\t{\n\t\t\t\t\tis_label_confliced = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!is_label_confliced)\n\t\t\t{\n\t\t\t\t_missing_label_indices.push_back(label_index_1);\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete[] is_missing_label;\n}\n\nReal MeshCuboidJointNormalRelationPredictor::get_pair_potential(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidAttributes *_attributes_1, const MeshCuboidAttributes *_attributes_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2) const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_attributes_1); assert(_attributes_2);\n\tassert(_transformation_1); assert(_transformation_2);\n\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tReal potential = FLAGS_param_max_potential;\n\n\t//const MeshCuboidJointNormalRelations *relation_12 = relations_[_label_index_1][_label_index_2];\n\t//const MeshCuboidJointNormalRelations *relation_21 = relations_[_label_index_2][_label_index_1];\n\n\t//if (relation_12 && relation_21)\n\t//{\n\t//\tReal potential_12 = relation_12->compute_error(_cuboid_1, _cuboid_2, _transformation_1, _transformation_2);\n\t//\tReal potential_21 = relation_21->compute_error(_cuboid_2, _cuboid_1, _transformation_2, _transformation_1);\n\t//\tpotential = potential_12 + potential_21;\n\t//}\n\n\tconst MeshCuboidJointNormalRelations *relation_12 = relations_[_label_index_1][_label_index_2];\n\tif (relation_12)\n\t{\n\t\tReal potential_12 = relation_12->compute_error(_cuboid_1, _cuboid_2, _transformation_1, _transformation_2);\n\t\tpotential = potential_12;\n\n\t\t// Using bilateral relations.\n\t\t// (A, B) and (B, A) pairs are the same.\n#ifdef DEBUG_TEST\n\t\tconst MeshCuboidJointNormalRelations *relation_21 = relations_[_label_index_2][_label_index_1];\n\t\tif (relation_21)\n\t\t{\n\t\t\tReal potential_21 = relation_12->compute_error(_cuboid_1, _cuboid_2, _transformation_1, _transformation_2);\n\t\t\tCHECK_NUMERICAL_ERROR(__FUNCTION__, potential_12, potential_21);\n\t\t}\n\t}\n#endif\n\n\treturn potential;\n}\n\nReal MeshCuboidJointNormalRelationPredictor::get_pair_quadratic_form(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst unsigned int _cuboid_index_1, const unsigned int _cuboid_index_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2,\n\tEigen::MatrixXd &_quadratic_term, Eigen::VectorXd &_linear_term, Real& _constant_term) const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\tconst unsigned int mat_size = _quadratic_term.cols();\n\n\tassert(_quadratic_term.rows() == mat_size);\n\tassert(_linear_term.rows() == mat_size);\n\tassert(_cuboid_index_1 * num_attributes <= mat_size);\n\tassert(_cuboid_index_2 * num_attributes <= mat_size);\n\n\t_quadratic_term.setZero();\n\t_linear_term.setZero();\n\t_constant_term = 0;\n\n\tconst MeshCuboidJointNormalRelations *relation_12 = relations_[_label_index_1][_label_index_2];\n\tif (!relation_12) return 0.0;\n\n\n\tMeshCuboidFeatures features_1, features_2;\n\tEigen::MatrixXd attributes_to_features_map_1, attributes_to_features_map_2;\n\n\tfeatures_1.compute_features(_cuboid_1, &attributes_to_features_map_1);\n\tfeatures_2.compute_features(_cuboid_2, &attributes_to_features_map_2);\n\n\tassert(attributes_to_features_map_1.rows() == num_features);\n\tassert(attributes_to_features_map_2.rows() == num_features);\n\n\tassert(attributes_to_features_map_1.cols() == num_attributes);\n\tassert(attributes_to_features_map_2.cols() == num_attributes);\n\n\tMeshCuboidTransformation transformation_1;\n\ttransformation_1.compute_transformation(_cuboid_1);\n\tEigen::MatrixXd rotation_1;\n\tEigen::MatrixXd translation_1;\n\ttransformation_1.get_linear_map_transformation(rotation_1, translation_1);\n\n\tMeshCuboidTransformation transformation_2;\n\ttransformation_2.compute_transformation(_cuboid_2);\n\tEigen::MatrixXd rotation_2;\n\tEigen::MatrixXd translation_2;\n\ttransformation_2.get_linear_map_transformation(rotation_2, translation_2);\n\n\n\t// (Ax + b)'C(Ax + b) = x'(A'CA)x + 2*(b'CA)x.\n\tunsigned int start_index_1 = (_cuboid_index_1 * num_attributes);\n\tunsigned int start_index_2 = (_cuboid_index_2 * num_attributes);\n\n\tEigen::MatrixXd A1_orig = Eigen::MatrixXd::Zero(2 * num_features, mat_size);\n\tEigen::MatrixXd A2_orig = Eigen::MatrixXd::Zero(2 * num_features, mat_size);\n\n\n\t// The rotation is fixed, and attribute-to-feature map is a function of 'cuboid_1' attributes.\n\tA1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t= A1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t+ rotation_1 * attributes_to_features_map_1;\n\n\t// The translation is a function of 'cuboid_1' attributes.\n\tA1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t= A1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t+ translation_1;\n\n\t// The rotation is fixed, and attribute-to-feature map is a function of 'cuboid_2' attributes.\n\tA1_orig.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t= A1_orig.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t+ rotation_1 * attributes_to_features_map_2;\n\n\t// The translation is a function of 'cuboid_1' attributes.\n\tA1_orig.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t= A1_orig.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t+ translation_1;\n\t\n\n\t// The rotation is fixed, and attribute-to-feature map is a function of 'cuboid_2' attributes.\n\tA2_orig.block<num_features, num_attributes>(0, start_index_2)\n\t\t= A2_orig.block<num_features, num_attributes>(0, start_index_2)\n\t\t+ rotation_2 * attributes_to_features_map_2;\n\n\t// The translation is a function of 'cuboid_2' attributes.\n\tA2_orig.block<num_features, num_attributes>(0, start_index_2)\n\t\t= A2_orig.block<num_features, num_attributes>(0, start_index_2)\n\t\t+ translation_2;\n\n\t// The rotation is fixed, and attribute-to-feature map is a function of 'cuboid_1' attributes.\n\tA2_orig.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t= A2_orig.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t+ rotation_2 * attributes_to_features_map_1;\n\n\t// The translation is a function of 'cuboid_2' attributes.\n\tA2_orig.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t= A2_orig.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t+ translation_2;\n\n\n\t// NOTE:\n\t// Since the center point is always the origin in the local coordinates,\n\t// it is not used as the feature values.\n\tconst unsigned int num_rows = MeshCuboidJointNormalRelations::k_mat_size;\n\tEigen::MatrixXd A(num_rows, mat_size);\n\tA.topRows(2 * num_features - MeshCuboidFeatures::k_corner_index)\n\t\t= A1_orig.bottomRows(2 * num_features - MeshCuboidFeatures::k_corner_index);\n\tA.bottomRows(2 * num_features - MeshCuboidFeatures::k_corner_index)\n\t\t= A2_orig.bottomRows(2 * num_features - MeshCuboidFeatures::k_corner_index);\n\n\tEigen::VectorXd b = -relation_12->get_mean();\n\tassert(b.rows() == MeshCuboidJointNormalRelations::k_mat_size);\n\n\tEigen::MatrixXd C = relation_12->get_inv_cov();\n\tassert(C.rows() == MeshCuboidJointNormalRelations::k_mat_size);\n\tassert(C.cols() == MeshCuboidJointNormalRelations::k_mat_size);\n\n\n\t_quadratic_term = A.transpose() * C * A;\n\t_linear_term = (b.transpose() * C * A).transpose();\n\t_constant_term = (b.transpose() * C * b);\n\n\t\n\tMeshCuboidAttributes attributes_1, attributes_2;\n\tattributes_1.compute_attributes(_cuboid_1);\n\tattributes_2.compute_attributes(_cuboid_2);\n\n\tEigen::VectorXd x1 = attributes_1.get_attributes();\n\tEigen::VectorXd x2 = attributes_2.get_attributes();\n\tEigen::VectorXd x = Eigen::VectorXd::Zero(mat_size);\n\tx.block<num_attributes, 1>(start_index_1, 0) = x1;\n\tx.block<num_attributes, 1>(start_index_2, 0) = x2;\n\n\tReal potential = 0;\n\tpotential += (x.transpose() * _quadratic_term * x);\n\tpotential += (2 * _linear_term.transpose() * x);\n\tpotential += _constant_term;\n\n\n#ifdef DEBUG_TEST\n\tReal same_potential = relation_12->compute_error(_cuboid_1, _cuboid_2, &transformation_1, &transformation_2);\n\tCHECK_NUMERICAL_ERROR(__FUNCTION__, potential, same_potential);\n#endif\n\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\t//std::stringstream filename_sstr;\n\t//filename_sstr << std::string(\"quadratic_mat_\")\n\t//\t<< _cuboid_index_1 << std::string(\"_\")\n\t//\t<< _cuboid_index_2 << std::string(\".csv\");\n\n\t//std::ofstream csv_file(filename_sstr.str());\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\t//csv_file << _quadratic_term.format(csv_format) << std::endl;\n\t//csv_file.close();\n\n\treturn potential;\n}\n\nReal MeshCuboidJointNormalRelationPredictor::get_pair_conditional_quadratic_form(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst unsigned int _cuboid_index_1, const unsigned int _cuboid_index_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2,\n\tEigen::MatrixXd &_quadratic_term, Eigen::VectorXd &_linear_term, Real& _constant_term) const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\tconst unsigned int mat_size = _quadratic_term.cols();\n\n\tassert(_quadratic_term.rows() == mat_size);\n\tassert(_linear_term.rows() == mat_size);\n\tassert(_cuboid_index_1 * num_attributes <= mat_size);\n\tassert(_cuboid_index_2 * num_attributes <= mat_size);\n\n\t_quadratic_term.setZero();\n\t_linear_term.setZero();\n\t_constant_term = 0;\n\n\tconst MeshCuboidJointNormalRelations *relation_12 = relations_[_label_index_1][_label_index_2];\n\tif (!relation_12) return 0.0;\n\n\n\tMeshCuboidFeatures features_1, features_2;\n\tEigen::MatrixXd attributes_to_features_map_1, attributes_to_features_map_2;\n\n\tfeatures_1.compute_features(_cuboid_1, &attributes_to_features_map_1);\n\tfeatures_2.compute_features(_cuboid_2, &attributes_to_features_map_2);\n\n\tassert(attributes_to_features_map_1.rows() == num_features);\n\tassert(attributes_to_features_map_2.rows() == num_features);\n\n\tassert(attributes_to_features_map_1.cols() == num_attributes);\n\tassert(attributes_to_features_map_2.cols() == num_attributes);\n\n\tMeshCuboidTransformation transformation_1;\n\ttransformation_1.compute_transformation(_cuboid_1);\n\tEigen::MatrixXd rotation_1;\n\tEigen::MatrixXd translation_1;\n\ttransformation_1.get_linear_map_transformation(rotation_1, translation_1);\n\n\n\t// (Ax + b)'C(Ax + b) = x'(A'CA)x + 2*(b'CA)x.\n\tunsigned int start_index_1 = (_cuboid_index_1 * num_attributes);\n\tunsigned int start_index_2 = (_cuboid_index_2 * num_attributes);\n\n\tEigen::MatrixXd A1_orig = Eigen::MatrixXd::Zero(2 * num_features, mat_size);\n\n\n\t// The rotation is fixed, and attribute-to-feature map is a function of 'cuboid_1' attributes.\n\tA1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t= A1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t+ rotation_1 * attributes_to_features_map_1;\n\n\t// The translation is a function of 'cuboid_1' attributes.\n\tA1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t= A1_orig.block<num_features, num_attributes>(0, start_index_1)\n\t\t+ translation_1;\n\n\t// The rotation is fixed, and attribute-to-feature map is a function of 'cuboid_2' attributes.\n\tA1_orig.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t= A1_orig.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t+ rotation_1 * attributes_to_features_map_2;\n\n\t// The translation is a function of 'cuboid_1' attributes.\n\tA1_orig.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t= A1_orig.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t+ translation_1;\n\n\t// NOTE:\n\t// 'A2_orig' is not computed since here it is assumed that\n\t// the local coordinates of 'cuboid_2' is unknown.\n\t// See function 'MeshCuboidJointNormalRelationPredictor::get_pair_quadratic_form()'\n\n\n\t// NOTE:\n\t// Since the center point is always the origin in the local coordinates,\n\t// it is not used as the feature values.\n\tconst unsigned int num_rows =\n\t\t2 * MeshCuboidFeatures::k_num_features - MeshCuboidFeatures::k_corner_index;\n\tEigen::MatrixXd A = A1_orig.bottomRows(num_rows);\n\n\t// NOTE:\n\t// Since the local coordinates of 'cuboid_2' is unknown,\n\t// Features for only 1 -> 1 and 1 -> 2 are used.\n\tEigen::VectorXd b = -relation_12->get_mean().segment(0, num_rows);\n\n\t// NOTE:\n\t// Since the local coordinates of 'cuboid_2' is unknown,\n\t// Features for only 1 -> 1 and 1 -> 2 are used.\n\tEigen::MatrixXd C = relation_12->get_inv_cov().block(0, 0, num_rows, num_rows);\n\n\t_quadratic_term = A.transpose() * C * A;\n\t_linear_term = (b.transpose() * C * A).transpose();\n\t_constant_term = (b.transpose() * C * b);\n\n\n\tMeshCuboidAttributes attributes_1, attributes_2;\n\tattributes_1.compute_attributes(_cuboid_1);\n\tattributes_2.compute_attributes(_cuboid_2);\n\n\tEigen::VectorXd x1 = attributes_1.get_attributes();\n\tEigen::VectorXd x2 = attributes_2.get_attributes();\n\tEigen::VectorXd x = Eigen::VectorXd::Zero(mat_size);\n\tx.block<num_attributes, 1>(start_index_1, 0) = x1;\n\tx.block<num_attributes, 1>(start_index_2, 0) = x2;\n\n\tReal potential = 0;\n\tpotential += (x.transpose() * _quadratic_term * x);\n\tpotential += (2 * _linear_term.transpose() * x);\n\tpotential += _constant_term;\n\n\n#ifdef DEBUG_TEST\n\tReal same_potential = relation_12->compute_conditional_error(_cuboid_1, _cuboid_2, &transformation_1);\n\tCHECK_NUMERICAL_ERROR(__FUNCTION__, potential, same_potential);\n#endif\n\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\t//std::stringstream filename_sstr;\n\t//filename_sstr << std::string(\"conditional_quadratic_mat_\")\n\t//\t<< _cuboid_index_1 << std::string(\"_\")\n\t//\t<< _cuboid_index_2 << std::string(\".csv\");\n\n\t//std::ofstream csv_file(filename_sstr.str());\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\t//csv_file << _quadratic_term.format(csv_format) << std::endl;\n\t//csv_file.close();\n\n\treturn potential;\n}\n\nMeshCuboidCondNormalRelationPredictor::MeshCuboidCondNormalRelationPredictor(\n\tconst std::vector< std::vector<MeshCuboidCondNormalRelations *> > &_relations)\n\t: MeshCuboidPredictor(_relations.size())\n\t, relations_(_relations)\n{\n\tfor (unsigned int label_index = 0; label_index < num_labels_; ++label_index)\n\t\tassert(relations_[label_index].size() == num_labels_);\n}\n\nvoid MeshCuboidCondNormalRelationPredictor::get_missing_label_indices(\n\tconst std::list<LabelIndex> &_given_label_indices,\n\tstd::list<LabelIndex> &_missing_label_indices)const\n{\n\t_missing_label_indices.clear();\n\tunsigned int num_labels = relations_.size();\n\n\tbool *is_missing_label = new bool[num_labels];\n\tmemset(is_missing_label, true, num_labels * sizeof(bool));\n\n\tfor (std::list<LabelIndex>::const_iterator it = _given_label_indices.begin();\n\t\tit != _given_label_indices.end(); ++it)\n\t{\n\t\tLabelIndex label_index = (*it);\n\t\tassert(label_index < num_labels);\n\t\tis_missing_label[label_index] = false;\n\t}\n\n\tfor (LabelIndex label_index_1 = 0; label_index_1 < num_labels; ++label_index_1)\n\t{\n\t\tif (is_missing_label[label_index_1])\n\t\t{\n\t\t\tbool is_label_confliced = false;\n\n\t\t\tfor (LabelIndex label_index_2 = 0; label_index_2 < num_labels; ++label_index_2)\n\t\t\t{\n\t\t\t\tif (!is_missing_label[label_index_2] && !relations_[label_index_1][label_index_2])\n\t\t\t\t{\n\t\t\t\t\tis_label_confliced = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!is_label_confliced)\n\t\t\t{\n\t\t\t\t_missing_label_indices.push_back(label_index_1);\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete[] is_missing_label;\n}\n\nReal MeshCuboidCondNormalRelationPredictor::get_pair_potential(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidAttributes *_attributes_1, const MeshCuboidAttributes *_attributes_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2) const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_attributes_1); assert(_attributes_2);\n\tassert(_transformation_1); assert(_transformation_2);\n\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tReal potential = FLAGS_param_max_potential;\n\n\tconst MeshCuboidCondNormalRelations *relation_12 = relations_[_label_index_1][_label_index_2];\n\tconst MeshCuboidCondNormalRelations *relation_21 = relations_[_label_index_2][_label_index_1];\n\n\tif (relation_12 && relation_21)\n\t{\n\t\tReal potential_12 = relation_12->compute_error(_cuboid_1, _cuboid_2, _transformation_1, _transformation_2);\n\t\tReal potential_21 = relation_21->compute_error(_cuboid_2, _cuboid_1, _transformation_2, _transformation_1);\n\t\tpotential = potential_12 + potential_21;\n\t}\n\n\treturn potential;\n}\n\nReal MeshCuboidCondNormalRelationPredictor::get_pair_quadratic_form(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst unsigned int _cuboid_index_1, const unsigned int _cuboid_index_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2,\n\tEigen::MatrixXd &_quadratic_term, Eigen::VectorXd &_linear_term, Real& _constant_term) const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\tconst unsigned int num_global_coord_points = MeshCuboidFeatures::k_num_local_points;\n\tconst unsigned int num_non_global_coord_features = num_features - 3 * num_global_coord_points;\n\tconst unsigned int mat_size = _quadratic_term.cols();\n\n\tassert(_quadratic_term.rows() == mat_size);\n\tassert(_linear_term.rows() == mat_size);\n\tassert(_cuboid_index_1 * num_attributes <= mat_size);\n\tassert(_cuboid_index_2 * num_attributes <= mat_size);\n\n\t_quadratic_term.setZero();\n\t_linear_term.setZero();\n\t_constant_term = 0;\n\n\n\tMeshCuboidFeatures features_1, features_2;\n\tEigen::MatrixXd attributes_to_features_map_1, attributes_to_features_map_2;\n\n\tfeatures_1.compute_features(_cuboid_1, &attributes_to_features_map_1);\n\tfeatures_2.compute_features(_cuboid_2, &attributes_to_features_map_2);\n\n\tassert(attributes_to_features_map_1.rows() == num_features);\n\tassert(attributes_to_features_map_2.rows() == num_features);\n\n\tassert(attributes_to_features_map_1.cols() == num_attributes);\n\tassert(attributes_to_features_map_2.cols() == num_attributes);\n\n\tMeshCuboidTransformation transformation_1;\n\ttransformation_1.compute_transformation(_cuboid_1);\n\tEigen::MatrixXd rotation_1;\n\tEigen::MatrixXd translation_1;\n\ttransformation_1.get_linear_map_transformation(rotation_1, translation_1);\n\n\tMeshCuboidTransformation transformation_2;\n\ttransformation_2.compute_transformation(_cuboid_2);\n\n\n\tconst MeshCuboidCondNormalRelations *relation_12 = relations_[_label_index_1][_label_index_2];\n\tif (!relation_12) return 0.0;\n\n\n\t// (Ax + b)'C(Ax + b) = x'(A'CA)x + 2*(b'CA)x.\n\tEigen::MatrixXd A = Eigen::MatrixXd::Zero(num_features, mat_size);\n\tEigen::VectorXd b = Eigen::VectorXd::Zero(num_features);\n\tEigen::MatrixXd C = Eigen::MatrixXd::Zero(num_features, num_features);\n\n\tunsigned int start_index_1 = (_cuboid_index_1 * num_attributes);\n\tunsigned int start_index_2 = (_cuboid_index_2 * num_attributes);\n\n\tEigen::MatrixXd mean_A = Eigen::MatrixXd::Zero(num_features, num_features);\n\tmean_A.rightCols(num_non_global_coord_features) = relation_12->get_mean_A();\n\n\tA.block<num_features, num_attributes>(0, start_index_1)\n\t\t= A.block<num_features, num_attributes>(0, start_index_1)\n\t\t- mean_A * attributes_to_features_map_1;\n\n\tA.block<num_features, num_attributes>(0, start_index_2)\n\t\t= A.block<num_features, num_attributes>(0, start_index_2)\n\t\t+ rotation_1 * attributes_to_features_map_2;\n\n\tA.block<num_features, num_attributes>(0, start_index_1)\n\t\t= A.block<num_features, num_attributes>(0, start_index_1)\n\t\t+ translation_1;\n\n\tb = -relation_12->get_mean_b();\n\n\tC = relation_12->get_inv_cov();\n\n\t_quadratic_term = A.transpose() * C * A;\n\t_linear_term = (b.transpose() * C * A).transpose();\n\t_constant_term = (b.transpose() * C * b);\n\n\n\tMeshCuboidAttributes attributes_1, attributes_2;\n\tattributes_1.compute_attributes(_cuboid_1);\n\tattributes_2.compute_attributes(_cuboid_2);\n\n\tEigen::VectorXd x1 = attributes_1.get_attributes();\n\tEigen::VectorXd x2 = attributes_2.get_attributes();\n\tEigen::VectorXd x = Eigen::VectorXd::Zero(mat_size);\n\tx.block<num_attributes, 1>(start_index_1, 0) = x1;\n\tx.block<num_attributes, 1>(start_index_2, 0) = x2;\n\n\tReal potential = 0;\n\tpotential += (x.transpose() * _quadratic_term * x);\n\tpotential += (2 * _linear_term.transpose() * x);\n\tpotential += _constant_term;\n\n\n#ifdef DEBUG_TEST\n\tReal same_potential = relation_12->compute_error(_cuboid_1, _cuboid_2, &transformation_1, &transformation_2);\n\tCHECK_NUMERICAL_ERROR(__FUNCTION__, potential, same_potential);\n#endif\n\t\n\t//std::stringstream filename_sstr;\n\t//filename_sstr << std::string(\"quadratic_mat_\")\n\t//\t<< _cuboid_index_1 << std::string(\"_\")\n\t//\t<< _cuboid_index_2 << std::string(\".csv\");\n\t//std::ofstream csv_file(filename_sstr.str());\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\t//csv_file << quadratic_form.format(csv_format) << std::endl;\n\t//csv_file.close();\n\t\n\treturn potential;\n}\n\n/*\nMeshCuboidPCARelationPredictor::MeshCuboidPCARelationPredictor(\n\tconst std::vector< std::vector<MeshCuboidPCARelations> > &_relations)\n\t: MeshCuboidPredictor(_relations.size())\n\t, relations_(_relations)\n{\n\tfor (unsigned int label_index = 0; label_index < num_labels_; ++label_index)\n\t\tassert(relations_[label_index].size() == num_labels_);\n}\n\nReal MeshCuboidPCARelationPredictor::get_pair_potential(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidAttributes *_attributes_1, const MeshCuboidAttributes *_attributes_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2) const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_attributes_1); assert(_attributes_2);\n\tassert(_transformation_1); assert(_transformation_2);\n\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tReal potential = 0.0;\n\n\tMeshCuboidFeatures features_1, features_2;\n\tfeatures_1.compute_features(_cuboid_1);\n\tfeatures_2.compute_features(_cuboid_2);\n\n\tEigen::VectorXd features_vec_1 = features_1.get_features();\n\tEigen::VectorXd features_vec_2 = features_2.get_features();\n\tEigen::VectorXd transformed_features_vec_1 = _transformation_2->get_transformed_features(_cuboid_1);\n\tEigen::VectorXd transformed_features_vec_2 = _transformation_1->get_transformed_features(_cuboid_2);\n\n\tif (_label_index_1 < _label_index_2)\n\t{\n\t\tconst MeshCuboidPCARelations &relation = relations_[_label_index_1][_label_index_2];\n\t\tpotential += relation.compute_error(transformed_features_vec_1, transformed_features_vec_2);\n\t}\n\telse\n\t{\n\t\tconst MeshCuboidPCARelations &relation = relations_[_label_index_2][_label_index_1];\n\t\tpotential += relation.compute_error(transformed_features_vec_1, transformed_features_vec_2);\n\t}\n\n\treturn potential;\n}\n\nReal MeshCuboidPCARelationPredictor::get_pair_quadratic_form(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst unsigned int _cuboid_index_1, const unsigned int _cuboid_index_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2,\n\tEigen::MatrixXd &_quadratic_term, Eigen::VectorXd &_linear_term, Real& _constant_term) const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tconst unsigned int num_attributes = MeshCuboidAttributes::k_num_attributes;\n\tconst unsigned int num_features = MeshCuboidFeatures::k_num_features;\n\tconst unsigned int num_global_coord_points = MeshCuboidFeatures::k_num_local_points;\n\tconst unsigned int mat_size = _quadratic_term.cols();\n\n\tassert(_quadratic_term.rows() == mat_size);\n\tassert(_linear_term.rows() == mat_size);\n\tassert(_cuboid_index_1 * num_attributes <= mat_size);\n\tassert(_cuboid_index_2 * num_attributes <= mat_size);\n\n\t_quadratic_term.setZero();\n\t_linear_term.setZero();\n\t_constant_term = 0;\n\n\n\tMeshCuboidFeatures features_1, features_2;\n\tEigen::MatrixXd attributes_to_features_map_1, attributes_to_features_map_2;\n\n\tfeatures_1.compute_features(_cuboid_1, &attributes_to_features_map_1);\n\tfeatures_2.compute_features(_cuboid_2, &attributes_to_features_map_2);\n\n\tassert(attributes_to_features_map_1.rows() == num_features);\n\tassert(attributes_to_features_map_2.rows() == num_features);\n\n\tassert(attributes_to_features_map_1.cols() == num_attributes);\n\tassert(attributes_to_features_map_2.cols() == num_attributes);\n\n\tMeshCuboidTransformation transformation_1;\n\ttransformation_1.compute_transformation(_cuboid_1);\n\tEigen::MatrixXd rotation_1;\n\tEigen::MatrixXd translation_1;\n\ttransformation_1.get_feature_transformation(rotation_1, translation_1);\n\n\tMeshCuboidTransformation transformation_2;\n\ttransformation_2.compute_transformation(_cuboid_2);\n\tEigen::MatrixXd rotation_2;\n\tEigen::MatrixXd translation_2;\n\ttransformation_2.get_feature_transformation(rotation_2, translation_2);\n\n\tMeshCuboidAttributes attributes_1, attributes_2;\n\tattributes_1.compute_attributes(_cuboid_1);\n\tattributes_2.compute_attributes(_cuboid_2);\n\n\t// (Ax + b)'C(Ax + b) = x'(A'CA)x + 2*(b'CA)x.\n\tEigen::MatrixXd A = Eigen::MatrixXd::Zero(2 * num_features, mat_size);\n\tEigen::VectorXd b = Eigen::VectorXd::Zero(2 * num_features);\n\tEigen::MatrixXd C = Eigen::MatrixXd::Zero(2 * num_features, 2 * num_features);\n\n\tunsigned int start_index_1 = (_cuboid_index_1 * num_attributes);\n\tunsigned int start_index_2 = (_cuboid_index_2 * num_attributes);\n\n\tEigen::VectorXd x1 = attributes_1.get_attributes();\n\tEigen::VectorXd x2 = attributes_2.get_attributes();\n\tEigen::VectorXd x0 = Eigen::VectorXd::Zero(mat_size);\n\tx0.block<num_attributes, 1>(start_index_1, 0) = x1;\n\tx0.block<num_attributes, 1>(start_index_2, 0) = x2;\n\n\tA.block<num_features, num_attributes>(0, start_index_1)\n\t\t= A.block<num_features, num_attributes>(0, start_index_1)\n\t\t+ rotation_2 * attributes_to_features_map_1;\n\n\tA.block<num_features, num_attributes>(0, start_index_2)\n\t\t= A.block<num_features, num_attributes>(0, start_index_2)\n\t\t+ translation_2;\n\n\tA.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t= A.block<num_features, num_attributes>(num_features, start_index_2)\n\t\t+ rotation_1 * attributes_to_features_map_2;\n\n\tA.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t= A.block<num_features, num_attributes>(num_features, start_index_1)\n\t\t+ translation_1;\n\n\n\tEigen::MatrixXd P;\n\tif (_label_index_1 < _label_index_2)\n\t{\n\t\tconst MeshCuboidPCARelations &relation = relations_[_label_index_1][_label_index_2];\n\t\tb = b - relation.get_mean();\n\t\tP = relation.get_pca_bases();\n\t}\n\telse\n\t{\n\t\tconst MeshCuboidPCARelations &relation = relations_[_label_index_2][_label_index_1];\n\t\tb = b - relation.get_mean();\n\t\tP = relation.get_pca_bases();\n\t}\n\n\tEigen::MatrixXd I = Eigen::MatrixXd::Identity(2 * num_features, 2 * num_features);\n\n\t_quadratic_term = _quadratic_term + A.transpose() * (I - P).transpose() * (I - P) * A;\n\t_linear_term = _linear_term + ((b.transpose() * (I - P).transpose() * (I - P) * A).transpose());\n\t_constant_term = _constant_term + (b.transpose() * (I - P).transpose() * (I - P) * b);\n\n\t_quadratic_term = _quadratic_term + A.transpose() * P * A;\n\t_linear_term = _linear_term - (A.transpose() * P * A * x0);\n\t_constant_term = _constant_term + (x0.transpose() * A.transpose() * P * A * x0);\n\n\n\tReal potential = 0;\n\tpotential += (x0.transpose() * _quadratic_term * x0);\n\tpotential += (2 * _linear_term.transpose() * x0);\n\tpotential += _constant_term;\n\n\n\t// DEBUG.\n\tEigen::VectorXd transformed_features_vec_1 = transformation_2.get_transformed_features(_cuboid_1);\n\tEigen::VectorXd transformed_features_vec_2 = transformation_1.get_transformed_features(_cuboid_2);\n\tReal same_potential = 0.0;\n\tif (_label_index_1 < _label_index_2)\n\t{\n\t\tconst MeshCuboidPCARelations &relation = relations_[_label_index_1][_label_index_2];\n\t\tsame_potential = relation.compute_error(transformed_features_vec_1, transformed_features_vec_2);\n\t}\n\telse\n\t{\n\t\tconst MeshCuboidPCARelations &relation = relations_[_label_index_2][_label_index_1];\n\t\tsame_potential = relation.compute_error(transformed_features_vec_1, transformed_features_vec_2);\n\t}\n\n\tCHECK_ERROR(__FUNCTION__, potential, same_potential);\n\t\n\t// DEBUG.\n\t//std::stringstream filename_sstr;\n\t//filename_sstr << std::string(\"quadratic_mat_\")\n\t//\t<< _cuboid_index_1 << std::string(\"_\")\n\t//\t<< _cuboid_index_2 << std::string(\".csv\");\n\t//std::ofstream csv_file(filename_sstr.str());\n\t//Eigen::IOFormat csv_format(Eigen::StreamPrecision, 0, \",\");\n\t//csv_file << quadratic_form.format(csv_format) << std::endl;\n\t//csv_file.close();\n\n\treturn potential;\n}\n\nMeshCuboidCCARelationPredictor::MeshCuboidCCARelationPredictor(\n\tconst std::vector< std::vector< std::vector<MeshCuboidCCARelations> > >& _relations)\n\t: MeshCuboidPredictor(_relations.size())\n\t, relations_(_relations)\n{\n\tfor (unsigned int label_index_1 = 0; label_index_1 < num_labels_; ++label_index_1)\n\t{\n\t\tassert(_relations[label_index_1].size() == num_labels_);\n\t\tfor (unsigned int label_index_2 = 0; label_index_2 < num_labels_; ++label_index_2)\n\t\t\tassert(_relations[label_index_1][label_index_2].size() == num_labels_);\n\t}\n}\n\nReal MeshCuboidCCARelationPredictor::get_pair_potential(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidAttributes *_attributes_1, const MeshCuboidAttributes *_attributes_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2)const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_attributes_1); assert(_attributes_2);\n\tassert(_transformation_1); assert(_transformation_2);\n\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\t// NOTE:\n\t// Now considering only different label pairs.\n\t//assert(_label_index_1 != _label_index_2);\n\n\tReal potential = 0.0;\n\n\t// Compute potential.\n\t//MeshCuboidCCARelations *relation_12;\n\t//// NOTE:\n\t//// Use increasing order of label indices for cuboid pairs.\n\t//if (label_index_1 <= label_index_2)\n\t//relation_12 = &(_relations[label_index_1][label_index_2]);\n\t//else\n\t//relation_12 = &(_relations[label_index_2][label_index_1]);\n\t//assert(relation_12);\n\t//potential = relation_12->compute_error(&attributes_1, &attributes_2);\n\t\n\n\t// NOTE:\n\tconst std::vector<MeshCuboidCCARelations> *relation_12;\n\t// Use increasing order of label indices for cuboid pairs.\n\tif (_label_index_1 <= _label_index_2)\n\t\trelation_12 = &(relations_[_label_index_1][_label_index_2]);\n\telse\n\t\trelation_12 = &(relations_[_label_index_2][_label_index_1]);\n\n\tEigen::VectorXd transformed_features_11 = _transformation_1->get_transformed_features(_cuboid_1);\n\tEigen::VectorXd transformed_features_21 = _transformation_1->get_transformed_features(_cuboid_2);\n\tpotential += (*relation_12)[_label_index_1].compute_error(\n\t\ttransformed_features_11, transformed_features_21);\n\n\tEigen::VectorXd transformed_features_12 = _transformation_2->get_transformed_features(_cuboid_1);\n\tEigen::VectorXd transformed_features_22 = _transformation_2->get_transformed_features(_cuboid_2);\n\tpotential += (*relation_12)[_label_index_2].compute_error(\n\t\ttransformed_features_12, transformed_features_22);\n\n\treturn potential;\n}\n\nMeshCuboidManualRelationPredictor::MeshCuboidManualRelationPredictor(\n\tconst std::vector<MeshCuboidStats> &_single_stats,\n\tconst std::vector< std::vector<MeshCuboidStats> > &_pair_stats)\n\t: MeshCuboidPredictor(_single_stats.size())\n\t, single_stats_(_single_stats)\n\t, pair_stats_(_pair_stats)\n{\n\tassert(_pair_stats.size() == num_labels_);\n\tfor (unsigned int label_index = 0; label_index < num_labels_; ++label_index)\n\t\tassert(_pair_stats[label_index].size() == num_labels_);\n}\n\nReal MeshCuboidManualRelationPredictor::get_single_potential(\n\tconst MeshCuboid *_cuboid,\n\tconst MeshCuboidAttributes *_attributes,\n\tconst MeshCuboidTransformation *_transformation,\n\tconst LabelIndex _label_index)const\n{\n\tassert(_cuboid);\n\tassert(_attributes);\n\tassert(_transformation);\n\n\tassert(_label_index < num_labels_);\n\n\tReal potential = 0.0;\n\n\t// Compute potential.\n\t//\n\tMeshSingleCuboidManualFeatures single_features(\"single_potential\");\n\tsingle_features.compute_values(_cuboid);\n\tpotential -= single_features.compute_log_probability(single_stats_[_label_index]);\n\n\t// NOTE:\n\t// Pairwise attribute relations are also defined for a single part attributes.\n\tMeshPairCuboidManualFeatures pair_features(\"pair_potential\");\n\tpair_features.compute_values(_cuboid, _cuboid);\n\tpotential -= pair_features.compute_log_probability(pair_stats_[_label_index][_label_index]);\n\t//\n\n\treturn potential;\n}\n\nReal MeshCuboidManualRelationPredictor::get_pair_potential(\n\tconst MeshCuboid *_cuboid_1, const MeshCuboid *_cuboid_2,\n\tconst MeshCuboidAttributes *_attributes_1, const MeshCuboidAttributes *_attributes_2,\n\tconst MeshCuboidTransformation *_transformation_1, const MeshCuboidTransformation *_transformation_2,\n\tconst LabelIndex _label_index_1, const LabelIndex _label_index_2)const\n{\n\tassert(_cuboid_1); assert(_cuboid_2);\n\tassert(_attributes_1); assert(_attributes_2);\n\tassert(_transformation_1); assert(_transformation_2);\n\n\tassert(_label_index_1 < num_labels_);\n\tassert(_label_index_2 < num_labels_);\n\n\tReal potential = 0.0;\n\n\t// Compute potential.\n\t//\n\tMeshPairCuboidManualFeatures pair_features(\"pair_potential\");\n\tpair_features.compute_values(_cuboid_1, _cuboid_2);\n\n\t// NOTE:\n\t// Check symmetry:\n\t// pair_features.compute_values(label_2, cuboid_2, label_1, cuboid_1);\n\n\t// NOTE:\n\t// Use increasing order of label indices for cuboid pairs.\n\tif (_label_index_1 <= _label_index_2)\n\t{\n\t\tpotential -= pair_features.compute_log_probability(\n\t\t\tpair_stats_[_label_index_1][_label_index_2]);\n\t}\n\telse\n\t{\n\t\tpotential -= pair_features.compute_log_probability(\n\t\t\tpair_stats_[_label_index_2][_label_index_1]);\n\t}\n\n\treturn potential;\n}\n*/\n", "meta": {"hexsha": "968ba2438fbbece0545db4451177920e05936b75", "size": 46355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MeshCuboidPredictor.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/MeshCuboidPredictor.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/MeshCuboidPredictor.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": 36.385400314, "max_line_length": 111, "alphanum_fraction": 0.7781684824, "num_tokens": 12882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.02262919760245302, "lm_q1q2_score": 0.010081976219338883}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// Copyright (c) 2019, Brian Lee, Vinitha Ranganeni\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#ifndef INCLUDE_STATESPACE_SE2_HPP_\n#define INCLUDE_STATESPACE_SE2_HPP_\n\n#include <Eigen/Dense>\n#include <vector>\n#include <unordered_map>\n#include <memory>\n#include <utility>\n#include <boost/functional/hash.hpp>\n#include \"StateSpace.hpp\"\n\nnamespace libcozmo {\nnamespace statespace {\n\n// This class implements a discretized two-dimensional Special Euclidean\n// group SE(2), i.e. the space of planar rigid body transformations.\nclass SE2 : public virtual StateSpace {\n public:\n    class State : public StateSpace::State {\n     public:\n        /// Constructs identity state\n        State() : x(0), y(0), theta(0) {}\n\n        ~State() = default;\n\n        /// Constructs state with given parameters\n        explicit State(const int& x, const int& y, const int& theta);\n\n        /// Documentation Inherited\n        /// Vector in format [x, y, theta]\n        void from_vector(const Eigen::VectorXd& state);\n\n        /// Documentation Inherited\n        bool operator== (const StateSpace::State& state) const override;\n\n        /// Custom state hash\n        friend std::size_t hash_value(const State& state) {\n            std::size_t seed = 0;\n            boost::hash_combine(seed, boost::hash_value(state.x));\n            boost::hash_combine(seed, boost::hash_value(state.y));\n            boost::hash_combine(seed, boost::hash_value(state.theta));\n            return seed;\n        }\n\n        int X() const;\n        int Y() const;\n        int Theta() const;\n\n        /// Documentation Inherited\n        Eigen::VectorXd vector() const override;\n\n     private:\n        int x;\n        int y;\n        int theta;\n\n        friend class SE2;\n    };\n\n    /// Constructs a discretized SE2 state space\n    ///\n    /// \\param resolution_m Resolution of the environment (mm)\n    /// \\param num_theta_vals Number of discretized theta values; Must be a\n    /// power of 2\n    SE2(\n        const double& resolution_m,\n        const int& num_theta_vals) : \\\n        m_resolution(resolution_m),\n        m_num_theta_vals(num_theta_vals),\n        m_statespace(std::make_shared<aikido::statespace::SE2>()),\n        m_distance_metric(aikido::distance::SE2(m_statespace)) {}\n\n    ~SE2();\n\n    /// Documentation inherited\n    int get_or_create_state(const StateSpace::State& _state) override;\n\n    /// Documentation inherited\n    int get_or_create_state(\n        const aikido::statespace::StateSpace::State& _state) override;\n\n    /// Documentation inherited\n    /// Input vector in format [x, y, theta]\n    int get_or_create_state(const Eigen::VectorXd& _state) override;\n\n    /// Documentation inherited\n    void discrete_state_to_continuous(\n        const StateSpace::State& _state,\n        aikido::statespace::StateSpace::State*\n            _continuous_state) const override;\n\n    /// Documentation inherited\n    void continuous_state_to_discrete(\n        const aikido::statespace::StateSpace::State& _state,\n        StateSpace::State* _discrete_state) const override;\n\n    /// Documentation inherited\n    bool get_state_id(\n        const StateSpace::State& _state, int* _state_id) const override;\n\n    /// Documentation inherited\n    StateSpace::State* get_state(const int& _state_id) const override;\n\n    /// Documentation inherited\n    /// State is valid if theta is in [0, num_theta_vals]\n    bool is_valid_state(const StateSpace::State& _state) const override;\n\n    /// Documentation inherited\n    int size() const override;\n\n    /// Documentation inherited\n    double get_distance(\n        const StateSpace::State& _state_1,\n        const StateSpace::State& _state_2) const override;\n\n    /// Documentation inherited\n    double get_distance(\n        const aikido::statespace::StateSpace::State& _state_1,\n        const aikido::statespace::StateSpace::State& _state_2) const override;\n\n    /// Documentation inherited\n    void copy_state(\n        const StateSpace::State& _source,\n        StateSpace::State* _destination) const override;\n\n    /// Documentation inherited\n    double get_resolution() const override;\n\n private:\n    /// Creates a new state and adds it to the statespace\n    ///\n    /// \\return pointer to the state\n    StateSpace::State* create_state() override;\n\n    /// Gets normalized angle (radians) in [0, 2pi]\n    ///\n    /// \\param theta_rad Angle (radians)\n    /// \\return normalized angle\n    double normalize_angle_rad(const double& theta_rad) const;\n\n    /// Converts discrete angle to continuous (radians)\n    ///\n    /// \\param theta Discrete angle in [0, num_theta_vals]\n    /// \\return Continuous angle in [0, 2pi]\n    double discrete_angle_to_continuous(const int& theta) const;\n\n    /// Converts discrete angle to continuous (radians)\n    ///\n    /// \\param theta Continuous angle (radians)\n    /// \\return Discrete angle in [0, num_theta_vals]\n    int continuous_angle_to_discrete(const double& theta) const;\n\n    /// Converts discrete position to continuous (x_mm, y_mm)\n    ///\n    /// \\param position Discrete coordinates\n    /// \\return Continous coordinates in meters\n    Eigen::Vector2d discrete_position_to_continuous(\n        const Eigen::Vector2i& position) const;\n\n    /// Converts continuous position (x_mm, y_mm) to discrete\n    ///\n    /// \\param position Continuous coordinates in millimeters\n    /// \\return Discrete coordinates\n    Eigen::Vector2i continuous_position_to_discrete(\n        const Eigen::Vector2d& position) const;\n\n    /// Maps discrete state (libcozmo::statespace::SE2::State) to state ID\n    std::unordered_map<State, int, boost::hash<State>> m_state_to_id_map;\n\n    /// Vector of discrete states (libcozmo::statespace::SE2::State)\n    /// Index of state is the state ID\n    std::vector<State*> m_state_map;\n\n    /// Number of discretized theta values\n    const int m_num_theta_vals;\n\n    /// Resolution of environment (mm)\n    const double m_resolution;\n\n    std::shared_ptr<aikido::statespace::SE2> m_statespace;\n    aikido::distance::SE2 m_distance_metric;\n};\n\n}  // namespace statespace\n}  // namespace libcozmo\n\n#endif  // INCLUDE_STATESPACE_SE2_HPP_\n\n", "meta": {"hexsha": "20afc25d8c7c45290ace4985c7b834cbc4f74a2e", "size": 7778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/statespace/SE2.hpp", "max_stars_repo_name": "JHLee0513/libcozmo", "max_stars_repo_head_hexsha": "f3a90a39ec1b1c4ead691328fd43459d67a3a44a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-01-11T15:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T21:49:05.000Z", "max_issues_repo_path": "include/statespace/SE2.hpp", "max_issues_repo_name": "JHLee0513/libcozmo", "max_issues_repo_head_hexsha": "f3a90a39ec1b1c4ead691328fd43459d67a3a44a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-07-19T01:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-10T07:28:30.000Z", "max_forks_repo_path": "include/statespace/SE2.hpp", "max_forks_repo_name": "JHLee0513/libcozmo", "max_forks_repo_head_hexsha": "f3a90a39ec1b1c4ead691328fd43459d67a3a44a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T20:04:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T10:12:35.000Z", "avg_line_length": 35.6788990826, "max_line_length": 80, "alphanum_fraction": 0.6757521214, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.025178841883475373, "lm_q1q2_score": 0.010066794445489795}}
{"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#include \"dart/optimizer/nlopt/NloptSolver.hpp\"\n\n#include <memory>\n\n#include <Eigen/Dense>\n\n#include \"dart/common/Console.hpp\"\n#include \"dart/common/StlHelpers.hpp\"\n#include \"dart/optimizer/Function.hpp\"\n#include \"dart/optimizer/Problem.hpp\"\n\nnamespace dart {\nnamespace optimizer {\n\n//==============================================================================\nNloptSolver::NloptSolver(\n    const Solver::Properties& properties, nlopt::algorithm alg)\n  : NloptSolver(properties, convertAlgorithm(alg))\n{\n  // Do nothing\n}\n\n//==============================================================================\nNloptSolver::NloptSolver(\n    const Solver::Properties& properties, NloptSolver::Algorithm alg)\n  : Solver(properties), mOpt(nullptr), mAlg(convertAlgorithm(alg)), mMinF(0.0)\n{\n  // Do nothing\n}\n\n//==============================================================================\nNloptSolver::NloptSolver(std::shared_ptr<Problem> problem, nlopt::algorithm alg)\n  : NloptSolver(std::move(problem), convertAlgorithm(alg))\n{\n  // Do nothing\n}\n\n//==============================================================================\nNloptSolver::NloptSolver(\n    std::shared_ptr<Problem> problem, NloptSolver::Algorithm alg)\n  : Solver(std::move(problem)),\n    mOpt(nullptr),\n    mAlg(convertAlgorithm(alg)),\n    mMinF(0.0)\n{\n  // Do nothing\n}\n\n//==============================================================================\nNloptSolver::~NloptSolver()\n{\n  // Do nothing\n}\n\n//==============================================================================\nstatic std::vector<double> convertToStd(const Eigen::VectorXd& v)\n{\n  return std::vector<double>(v.data(), v.data() + v.size());\n}\n\n//==============================================================================\nstatic Eigen::VectorXd convertToEigen(const std::vector<double>& v)\n{\n  Eigen::VectorXd result(v.size());\n  for (std::size_t i = 0; i < v.size(); ++i)\n    result[static_cast<Eigen::Index>(i)] = v[i];\n\n  return result;\n}\n\n//==============================================================================\nbool NloptSolver::solve()\n{\n  // Allocate a new nlopt::opt structure if needed\n  std::size_t dimension = mProperties.mProblem->getDimension();\n  if (nullptr == mOpt || mOpt->get_dimension() != dimension\n      || mOpt->get_algorithm() != mAlg)\n  {\n    mOpt = std::make_unique<nlopt::opt>(mAlg, dimension);\n  }\n  else\n  {\n    mOpt->remove_equality_constraints();\n    mOpt->remove_inequality_constraints();\n  }\n\n  const std::shared_ptr<Problem>& problem = mProperties.mProblem;\n\n  mOpt->set_maxeval(static_cast<int>(mProperties.mNumMaxIterations));\n  mOpt->set_xtol_rel(mProperties.mTolerance);\n  mOpt->set_lower_bounds(convertToStd(problem->getLowerBounds()));\n  mOpt->set_upper_bounds(convertToStd(problem->getUpperBounds()));\n\n  // Set up the nlopt::opt\n  mOpt->set_min_objective(\n      NloptSolver::_nlopt_func, problem->getObjective().get());\n\n  for (std::size_t i = 0; i < problem->getNumEqConstraints(); ++i)\n  {\n    FunctionPtr fn = problem->getEqConstraint(i);\n    try\n    {\n      mOpt->add_equality_constraint(\n          NloptSolver::_nlopt_func, fn.get(), mProperties.mTolerance);\n    }\n    catch (const std::invalid_argument& e)\n    {\n      dterr << \"[NloptSolver::solve] Encountered exception [\" << e.what()\n            << \"] while adding an equality constraint to an Nlopt solver. \"\n            << \"Check whether your algorithm [\" << nlopt::algorithm_name(mAlg)\n            << \"] (\" << mAlg << \") supports equality constraints!\\n\";\n      assert(false);\n    }\n    catch (const std::exception& e)\n    {\n      dterr << \"[NloptSolver::solve] Encountered exception [\" << e.what()\n            << \"] while adding an equality constraint to the Nlopt solver. \"\n            << \"This might be a bug in DART; please report this!\\n\";\n      assert(false);\n    }\n  }\n\n  for (std::size_t i = 0; i < problem->getNumIneqConstraints(); ++i)\n  {\n    FunctionPtr fn = problem->getIneqConstraint(i);\n    try\n    {\n      mOpt->add_inequality_constraint(\n          NloptSolver::_nlopt_func, fn.get(), mProperties.mTolerance);\n    }\n    catch (const std::invalid_argument& e)\n    {\n      dterr << \"[NloptSolver::solve] Encountered exception [\" << e.what()\n            << \"] while adding an inequality constraint to an Nlopt solver. \"\n            << \"Check whether your algorithm [\" << nlopt::algorithm_name(mAlg)\n            << \"] (\" << mAlg << \") supports inequality constraints!\\n\";\n      assert(false);\n    }\n    catch (const std::exception& e)\n    {\n      dterr << \"[NloptSolver::solve] Encountered exception [\" << e.what()\n            << \"] while adding an inequality constraint to the Nlopt solver. \"\n            << \"This might be a bug in DART; please report this!\\n\";\n      assert(false);\n    }\n  }\n\n  // Optimize\n  mX = convertToStd(problem->getInitialGuess());\n  nlopt::result result = mOpt->optimize(mX, mMinF);\n\n  // If the result is not in this range, then it failed\n  if (!(nlopt::SUCCESS <= result && result <= nlopt::XTOL_REACHED))\n    return false;\n\n  // Store optimal and optimum values\n  problem->setOptimumValue(mMinF);\n  problem->setOptimalSolution(convertToEigen(mX));\n\n  return true;\n}\n\n//==============================================================================\nEigen::VectorXd NloptSolver::getLastConfiguration() const\n{\n  return convertToEigen(mX);\n}\n\n//==============================================================================\nstd::string NloptSolver::getType() const\n{\n  return \"NloptSolver\";\n}\n\n//==============================================================================\nstd::shared_ptr<Solver> NloptSolver::clone() const\n{\n  return std::make_shared<NloptSolver>(getSolverProperties(), getAlgorithm2());\n}\n\n//==============================================================================\nvoid NloptSolver::copy(const NloptSolver& other)\n{\n  setProperties(other.getSolverProperties());\n  setAlgorithm(other.getAlgorithm2());\n}\n\n//==============================================================================\nNloptSolver& NloptSolver::operator=(const NloptSolver& other)\n{\n  copy(other);\n  return *this;\n}\n\n//==============================================================================\nvoid NloptSolver::setAlgorithm(nlopt::algorithm alg)\n{\n  setAlgorithm(convertAlgorithm(alg));\n}\n\n//==============================================================================\nvoid NloptSolver::setAlgorithm(NloptSolver::Algorithm alg)\n{\n  mAlg = convertAlgorithm(alg);\n}\n\n//==============================================================================\nnlopt::algorithm NloptSolver::getAlgorithm() const\n{\n  return convertAlgorithm(getAlgorithm2());\n}\n\n//==============================================================================\nNloptSolver::Algorithm NloptSolver::getAlgorithm2() const\n{\n  return convertAlgorithm(mAlg);\n}\n\n//==============================================================================\n#define NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(alg_name)                          \\\n  case alg_name:                                                               \\\n    return nlopt::algorithm::alg_name;\n\n//==============================================================================\n#define NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(alg_name)                          \\\n  case nlopt::algorithm::alg_name:                                             \\\n    return alg_name;\n\n//==============================================================================\nnlopt::algorithm NloptSolver::convertAlgorithm(NloptSolver::Algorithm algorithm)\n{\n  switch (algorithm)\n  {\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_DIRECT)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_DIRECT_L)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_DIRECT_L_RAND)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_DIRECT_NOSCAL)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_DIRECT_L_NOSCAL)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_DIRECT_L_RAND_NOSCAL)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_ORIG_DIRECT)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_ORIG_DIRECT_L)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GD_STOGO)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GD_STOGO_RAND)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_LBFGS_NOCEDAL)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_LBFGS)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_PRAXIS)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_VAR1)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_VAR2)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_TNEWTON)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_TNEWTON_RESTART)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_TNEWTON_PRECOND)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_TNEWTON_PRECOND_RESTART)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_CRS2_LM)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_MLSL)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GD_MLSL)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_MLSL_LDS)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GD_MLSL_LDS)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_MMA)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_COBYLA)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_NEWUOA)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_NEWUOA_BOUND)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_NELDERMEAD)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_SBPLX)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_AUGLAG)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_AUGLAG)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_AUGLAG_EQ)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_AUGLAG_EQ)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LN_BOBYQA)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_ISRES)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(AUGLAG)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(AUGLAG_EQ)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(G_MLSL)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(G_MLSL_LDS)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_SLSQP)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(LD_CCSAQ)\n    NLOPTSOLVER_ALGORITHM_DART_TO_NLOPT(GN_ESCH)\n    default:\n      dtwarn << \"[NloptSolver] Attempt to convert unsupported algorithm '\"\n             << algorithm << \"'. Use nlopt::algorithm::LN_COBYLA instead. \\n\";\n      return nlopt::algorithm::LN_COBYLA;\n  }\n}\n\n//==============================================================================\nNloptSolver::Algorithm NloptSolver::convertAlgorithm(nlopt::algorithm algorithm)\n{\n  switch (algorithm)\n  {\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_DIRECT)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_DIRECT_L)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_DIRECT_L_RAND)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_DIRECT_NOSCAL)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_DIRECT_L_NOSCAL)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_DIRECT_L_RAND_NOSCAL)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_ORIG_DIRECT)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_ORIG_DIRECT_L)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GD_STOGO)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GD_STOGO_RAND)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_LBFGS_NOCEDAL)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_LBFGS)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_PRAXIS)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_VAR1)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_VAR2)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_TNEWTON)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_TNEWTON_RESTART)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_TNEWTON_PRECOND)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_TNEWTON_PRECOND_RESTART)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_CRS2_LM)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_MLSL)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GD_MLSL)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_MLSL_LDS)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GD_MLSL_LDS)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_MMA)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_COBYLA)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_NEWUOA)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_NEWUOA_BOUND)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_NELDERMEAD)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_SBPLX)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_AUGLAG)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_AUGLAG)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_AUGLAG_EQ)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_AUGLAG_EQ)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LN_BOBYQA)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_ISRES)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(AUGLAG)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(AUGLAG_EQ)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(G_MLSL)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(G_MLSL_LDS)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_SLSQP)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(LD_CCSAQ)\n    NLOPTSOLVER_ALGORITHM_NLOPT_TO_DART(GN_ESCH)\n    default:\n      dtwarn << \"[NloptSolver] Attempt to convert unsupported algorithm '\"\n             << algorithm\n             << \"'. Use NloptSolver::Algorithm::LN_COBYLA instead. \\n\";\n      return LN_COBYLA;\n  }\n}\n\n//==============================================================================\ndouble NloptSolver::_nlopt_func(\n    unsigned n, const double* x, double* gradient, void* func_data)\n{\n  Function* fn = static_cast<Function*>(func_data);\n\n  Eigen::Map<const Eigen::VectorXd> mapX(x, n);\n\n  if (gradient)\n  {\n    Eigen::Map<Eigen::VectorXd> grad(gradient, n);\n    fn->evalGradient(mapX, grad);\n  }\n\n  return fn->eval(mapX);\n}\n\n//==============================================================================\nvoid NloptSolver::_nlopt_mfunc(\n    unsigned m,\n    double* result,\n    unsigned n,\n    const double* x,\n    double* gradient,\n    void* func_data)\n{\n  Eigen::Map<const Eigen::VectorXd> mapX(x, n);\n  Eigen::Map<Eigen::VectorXd> f(result, m);\n  Eigen::Map<Eigen::MatrixXd> grad(gradient, 0, 0);\n  if (gradient)\n    new (&grad) Eigen::Map<Eigen::MatrixXd, Eigen::RowMajor>(gradient, m, n);\n\n  return (*static_cast<MultiFunction*>(func_data))(mapX, f, grad);\n}\n\n} // namespace optimizer\n} // namespace dart\n", "meta": {"hexsha": "a69749d6d989694510d3c1f086008a2c94482f57", "size": 15374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dart/optimizer/nlopt/NloptSolver.cpp", "max_stars_repo_name": "dartsim/dart", "max_stars_repo_head_hexsha": "f974937b438e92d558f8f2f01cc31b50d3386dd3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 729.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T22:01:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:26:23.000Z", "max_issues_repo_path": "dart/optimizer/nlopt/NloptSolver.cpp", "max_issues_repo_name": "dartsim/dart", "max_issues_repo_head_hexsha": "f974937b438e92d558f8f2f01cc31b50d3386dd3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1071.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:48:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T17:10:36.000Z", "max_forks_repo_path": "dart/optimizer/nlopt/NloptSolver.cpp", "max_forks_repo_name": "dartsim/dart", "max_forks_repo_head_hexsha": "f974937b438e92d558f8f2f01cc31b50d3386dd3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 295.0, "max_forks_repo_forks_event_min_datetime": "2015-01-09T01:50:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T03:20:20.000Z", "avg_line_length": 37.5892420538, "max_line_length": 80, "alphanum_fraction": 0.6505788994, "num_tokens": 4039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.021287351366577112, "lm_q1q2_score": 0.01006217925199439}}
{"text": "// Copyright (c) 2016 The dave Simulator Authors.\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, 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 TidalOscillation.hh\n/// \\brief Interpolation of NOAA data for Tidal Oscillation feature\n\n#ifndef __TIDAL_OSCILLATION_HH__\n#define __TIDAL_OSCILLATION_HH__\n\n#include <gazebo/gazebo.hh>\n#include <cstdlib>\n#include <ctime>\n#include <random>\n#include <utility>\n#include <string>\n#include <vector>\n\n// #include <boost/math/interpolators/barycentric_rational.hpp>\n\nnamespace gazebo\n{\n  /// \\brief Interpolation of NOAA data for Tidal Oscillation feature\n  class TidalOscillation\n  {\n    /// \\brief Class constructor\n    public: TidalOscillation();\n\n    /// \\brief Resets the process parameters\n    public: void Reset();\n\n    /// \\brief Prepare the data for interpolation\n    public: void Initiate(bool _harmonicConstituents);\n\n    /// \\brief Translate datetime string to datenum\n    public: double TranslateDate(std::array<int, 5> _datetime);\n\n    /// \\brief Input Datenum data\n    public: std::vector<std::array<int, 5>> dateGMT;\n\n    /// \\brief Input Tidal data\n    public: std::vector<double> speedcmsec;\n\n    /// \\brief Input Datenum data\n    public: std::vector<double> datenum;\n\n    /// \\brief Bool for method type\n    public: bool harmonicConstituent;\n\n    /// \\brief Tidal current harmonic constituents\n    public: double M2_amp;\n    public: double M2_phase;\n    public: double M2_speed;\n    public: double S2_amp;\n    public: double S2_phase;\n    public: double S2_speed;\n    public: double N2_amp;\n    public: double N2_phase;\n    public: double N2_speed;\n\n    /// \\brief Input Tidal direction\n    public: double ebbDirection;\n    public: double floodDirection;\n\n    /// \\brief Input world start time\n    public: std::array<int, 5> worldStartTime;\n    public: double worldStartTime_num;\n\n    /// \\brief Update function for a new time stamp\n    /// \\param _time Current time stamp\n    public: std::pair<double, double>\n      Update(double _time, double _currentDepthRatio);\n\n    /// \\brief save current state (Flood: true, Ebb: false)\n    public: bool currentType;\n  };\n}\n\n#endif  // __TIDAL_OSCILLATION_HH__\n", "meta": {"hexsha": "2f68dc4113acf38f8ac05be6ae6218df0d2c8fe7", "size": 2655, "ext": "hh", "lang": "C++", "max_stars_repo_path": "transient_current_dave_plugin/dave_world_plugins/include/dave_world_plugins/TidalOscillation.hh", "max_stars_repo_name": "wangcongrobot/dave", "max_stars_repo_head_hexsha": "8c2b27462c9628672d71978280a7ad6dbf44eec6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-15T17:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-15T17:10:21.000Z", "max_issues_repo_path": "transient_current_dave_plugin/dave_world_plugins/include/dave_world_plugins/TidalOscillation.hh", "max_issues_repo_name": "wangcongrobot/dave", "max_issues_repo_head_hexsha": "8c2b27462c9628672d71978280a7ad6dbf44eec6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transient_current_dave_plugin/dave_world_plugins/include/dave_world_plugins/TidalOscillation.hh", "max_forks_repo_name": "wangcongrobot/dave", "max_forks_repo_head_hexsha": "8c2b27462c9628672d71978280a7ad6dbf44eec6", "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.1758241758, "max_line_length": 75, "alphanum_fraction": 0.7114877589, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.02976009426866113, "lm_q1q2_score": 0.010061207084782024}}
{"text": "/*\n * MaxWalkSat.cpp\n *\n *  Created on: Mar 19, 2012\n *      Author: selman.joe@gmail.com\n */\n\n#include \"MaxWalkSat.h\"\n#include \"../logic/syntax/ELSentence.h\"\n#include \"../logic/Domain.h\"\n#include \"../logic/Moves.h\"\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/unordered_map.hpp>\n#include <limits>\n\nconst unsigned int MWSSolver::defNumIterations = 1000;\nconst double MWSSolver::defProbOfRandomMove = 0.2;\n\nModel MWSSolver::run(boost::mt19937& rng) {\n    if (domain_ == NULL) {\n        std::logic_error e(\"unable to run MWSSolver with Domain set to null ptr\");\n        throw e;\n    }\n    return run(rng, domain_->defaultModel());\n}\n\nnamespace {\n// we will calculate the resulting model and score for all\n// moves, and choose the highest scoring one to move to.  This struct\n// makes it a lot more convenient to do.\nstruct MWSState {\n    Move move;\n    Model model;\n    double score;\n    // the three below here are copies of the versions above\n    std::vector<bool> localFormNeedUpdates;\n    std::vector<double> localScores;\n    std::vector<bool> localFormFullySat;\n};\n}\n\nModel MWSSolver::run(boost::mt19937& rng, const Model& initialModel) {\n    // validate domain\n    if (domain_ == NULL) {\n        std::logic_error e(\"unable to run MWSSolver with Domain set to null ptr\");\n        throw e;\n    }\n    // copy the domain's sentences into our own\n    std::vector<ELSentence> formulas;\n    std::copy(domain_->formulas_begin(), domain_->formulas_end(), std::back_inserter(formulas));\n\n    if (formulas.size() == 0) {\n        LOG(LOG_WARN) << \"no formulas given - returning initial model\";\n        return initialModel;\n    }\n\n    // now note which sentences have valid moves\n    std::vector<bool> formWithMoves(formulas.size(), false);\n    for (std::vector<ELSentence>::size_type i = 0;\n            i < formulas.size();\n            i++) {\n        // infinite weight domains are invalid\n        if (formulas[i].hasInfWeight()) {\n            std::logic_error e(\"unable to deal with infinitely weighted sentences.\");\n            throw e;\n        }\n        if (!canFindMovesFor(*formulas[i].sentence(), *domain_)) {\n            LOG(LOG_WARN) << \"currently cannot generate moves for sentence: \\\"\" << formulas[i].sentence()->toString() << \"\\\".  ignoring it for generating moves\";\n            formWithMoves[i] = false;\n        } else {\n            formWithMoves[i] = true;\n        }\n    }\n\n    // now record which sentences contain each atom - this is used to cache\n    // the results of previous satisfied sentences.\n    boost::unordered_map<Atom, std::vector<std::vector<ELSentence>::size_type > > atomToSentence;\n    for (std::vector<ELSentence>::size_type i = 0;\n            i != formulas.size();\n            i++) {\n        AtomCollector collector;\n        formulas[i].sentence()->visit(collector);\n        for (AtomCollector::atom_set::const_iterator atomit = collector.atoms.begin();\n                atomit != collector.atoms.end();\n                atomit++) {\n            atomToSentence[*atomit].push_back(i);\n        }\n    }\n\n    // setup stores for the score as well as whether each sentence is fully satisfied\n    std::vector<double> formScores(formulas.size(), 0.0);\n    std::vector<bool> formFullySat(formulas.size(), false);\n    // also setup a vector we will use to mark which scores need updating\n    std::vector<bool> formNeedUpdates(formulas.size(), true);\n\n    updateScores(formulas, initialModel, formNeedUpdates, formScores, formFullySat);\n\n    double currentScore = std::accumulate(formScores.begin(), formScores.end(), 0.0);\n    double bestScore = currentScore;\n    Model currentModel = initialModel;\n    Model bestModel = initialModel;\n\n    unsigned int showPeriodMod = (numIterations_ < 20 ? 1 : numIterations_/20); // TODO: make this configurable\n    for (unsigned int iteration=1; iteration <= numIterations_; iteration++) {\n        if (iteration % showPeriodMod == 0) {\n            std::cout << \".\";\n            std::cout.flush();\n        }\n        LOG(LOG_DEBUG) << \"currentModel: \" << currentModel;\n        LOG(LOG_DEBUG) << \"current score: \" << currentScore;\n\n        // first, check to see if all our formulas are fully satisfied - if\n        // that's the case, there's no real improvement left\n\n        // At the same time build a list of formulas we can find moves for\n        // that are not fully satisfied\n        bool noImprovementLeft = true;\n        std::vector<std::size_t> formCandidates;\n        for (std::vector<bool>::size_type i = 0;\n                i < formulas.size();\n                i++) {\n            if (!formFullySat[i]) {\n                noImprovementLeft = false;\n                if (formWithMoves[i]) {\n                    formCandidates.push_back(i);\n                }\n            }\n        }\n        if (noImprovementLeft) {\n            LOG(LOG_DEBUG) << \"exiting early, no more sentences to satisfy!\";\n            return currentModel;\n        }\n        // if formCandidates is empty, then we aren't fully satisfied but we\n        // can't generate moves for any valid sentences right now.  log a\n        // warning and generate a random move\n        Move nextMove;\n//        std::cout << \"candidates = \";\n//        for (std::vector<std::size_t>::const_iterator it = formCandidates.begin();\n//                it != formCandidates.end();\n//                it++) {\n//            std::cout << formulas[*it].toString() << \", \";\n//        }\n//        std::cin.get();\n\n        if (formCandidates.empty()) {\n            LOG(LOG_WARN) << \"cannot generate any moves for the current model (not all formulas are currently handled) - generating a random move\";\n            // pick a random atom\n            boost::uniform_int<std::size_t> atomPick(0, domain_->atoms_size()-1);\n            std::size_t atomInd = atomPick(rng);\n            Domain::atom_const_iterator atomIt = domain_->atoms_begin();\n            while (atomInd > 0) {\n                atomIt++;\n                atomInd--;\n            }\n\n            Atom atom = *atomIt;\n            // now pick a spanning interval\n\n            Interval maxInterval = domain_->maxInterval();\n            boost::uniform_int<unsigned int> momentPick(maxInterval.start(), maxInterval.finish());\n            unsigned int start = momentPick(rng);\n            unsigned int finish = momentPick(rng);\n            if (start > finish) std::swap(start, finish);\n\n            SpanInterval si;\n            if (domain_->isLiquid(atom.name())) {\n                si = SpanInterval(start, finish);\n            } else {\n                si = SpanInterval(start, start, finish, finish);\n            }\n            // make a random flip to add/subtract\n            Move::change ch(atom, si);\n            boost::bernoulli_distribution<> flip(0.5);\n            if (flip(rng)) {\n                nextMove.toAdd.push_back(ch);\n            } else {\n                nextMove.toDel.push_back(ch);\n            }\n        } else {\n            // choose a formula to improve at random\n            boost::uniform_int<std::size_t> formulaPick(0, formCandidates.size()-1);\n            std::size_t formChoseInd = formulaPick(rng);\n            ELSentence formula = formulas[formCandidates[formChoseInd]];\n            LOG(LOG_DEBUG) << \"choosing formula: \" << formula << \" to improve.\";\n\n\n            // find the moves for it\n            std::vector<Move> moves = findMovesFor(*domain_, currentModel, formula, rng);\n            if (moves.size() == 0) {\n\n                LOG(LOG_WARN) << \"WARNING: unable to find moves for sentence \" << formula.sentence()->toString()\n                        << \" even though its violated!  continuing (with a null iteration)...\";\n                continue; // TODO: this shouldn't happen, right?\n            }\n            if (FileLog::globalLogLevel() <= LOG_DEBUG) {\n                std::ostringstream vecStream;\n                for (std::vector<Move>::const_iterator it = moves.begin(); it != moves.end(); it++) {\n                    if (it != moves.begin()) vecStream << \", \";\n                    vecStream << \"(\" << it->toString() << \")\";\n                }\n                LOG(LOG_DEBUG) << \"moves to consider: \" << vecStream.str();\n            }\n\n            boost::bernoulli_distribution<> randMovePick(probOfRandomMove_);\n            if (randMovePick(rng)) {\n                // take a random move\n                boost::uniform_int<std::size_t> movesPick(0, moves.size()-1);\n                Move aMove = moves[movesPick(rng)];\n                LOG(LOG_DEBUG) << \"taking random move: \" << aMove.toString();\n\n                currentModel = updateWithMove(aMove, currentModel, atomToSentence, formNeedUpdates);\n                // update scores\n                updateScores(formulas, currentModel, formNeedUpdates, formScores, formFullySat);\n                currentScore = std::accumulate(formScores.begin(), formScores.end(), 0.0);\n            } else {\n                // instead of choosing a random move, choose the move that leads to the\n                // highest scoring move.\n\n                // we will calculate the resulting model and score for all\n                // moves, and choose the highest scoring one to move to\n                MWSState bestMWSState;\n\n                bestMWSState.score = std::numeric_limits<double>::min();    // the lowest value possible\n                // also have a vector of best models in case of ties\n                std::vector<MWSState> ties;\n\n                //std::vector<std::pair<Model, double> > nearbyModels;\n                for (std::vector<Move>::const_iterator it = moves.begin(); it != moves.end(); it++) {\n                    Move m = *it;\n                    std::vector<bool> localFormNeedUpdates(formNeedUpdates);\n                    Model nearbyModel = updateWithMove(m, currentModel, atomToSentence, localFormNeedUpdates);\n\n                    std::vector<double> localScores(formScores);\n                    std::vector<bool> localFormFullySat(formFullySat);\n                    updateScores(formulas, nearbyModel, localFormNeedUpdates, localScores, localFormFullySat);\n                    double nearbyScore = std::accumulate(localScores.begin(), localScores.end(), 0.0);\n\n                    if (nearbyScore > bestMWSState.score) {\n                        // save it\n                        bestMWSState.move = m;\n                        bestMWSState.model = nearbyModel;\n                        bestMWSState.score = nearbyScore;\n                        bestMWSState.localFormNeedUpdates = localFormNeedUpdates;\n                        bestMWSState.localScores = localScores;\n                        bestMWSState.localFormFullySat = localFormFullySat;\n\n                        ties.clear();\n                        ties.push_back(bestMWSState);\n                    } else if (nearbyScore == bestMWSState.score) {\n                        // found a tie\n                        MWSState tieState;\n                        tieState.move = m;\n                        tieState.model = nearbyModel;\n                        tieState.score = nearbyScore;\n                        tieState.localFormNeedUpdates = localFormNeedUpdates;\n                        tieState.localScores = localScores;\n                        tieState.localFormFullySat = localFormFullySat;\n\n                        ties.push_back(tieState);\n                    }\n                }\n                assert(bestMWSState.score > std::numeric_limits<double>::min());\n                if (ties.size() > 1) {\n                    // pick a choice randomly\n                    boost::uniform_int<std::size_t> tieChoice(0, ties.size()-1);\n                    bestMWSState = ties[tieChoice(rng)];\n                }\n                LOG(LOG_DEBUG) << \"taking move \" << bestMWSState.move.toString();\n                currentModel = bestMWSState.model;\n                currentScore = bestMWSState.score;\n                formNeedUpdates = bestMWSState.localFormNeedUpdates;\n                formScores = bestMWSState.localScores;\n                formFullySat = bestMWSState.localFormFullySat;\n            }\n        }\n        // check to see if its the best score foudn so far\n        if (currentScore > bestScore) {\n            LOG(LOG_DEBUG) << \"remembering this model as the best one seen so far.\";\n            bestScore = currentScore;\n            bestModel = currentModel;\n        }\n\n    }\n    LOG(LOG_INFO) << \"returning the best model found with a score of \" << bestScore;\n    return bestModel;\n\n//    for (int iteration=1; iteration <= numIterations; iteration++) {\n//        if (iteration % showPeriodMod == 0) {\n//            std::cout << \".\";\n//            std::cout.flush();\n//        }\n//        LOG(LOG_DEBUG) << \"currentModel: \" << currentModel;\n//        LOG(LOG_DEBUG) << \"current score: \" << currentScore;\n//\n//        datalog << currentScore;\n//\n//        // make a list of the current unsatisfied formulas we can calc moves for\n//        std::vector<int> notFullySatisfied = validForms;\n//        std::vector<ELSentence> curFormulas = formulas;\n//\n//        for (std::vector<int>::iterator it = notFullySatisfied.begin(); it != notFullySatisfied.end(); ) {\n//            int i = *it;\n//\n//            ELSentence wsent = curFormulas.at(i);\n//            //const WSentence *wsentence = *it;\n//            if (wsent.fullySatisfied(currentModel, d)) {\n//                it = notFullySatisfied.erase(it);\n//            } else {\n//                it++;\n//            }\n//        }\n//\n//        if (notFullySatisfied.size()==0) {\n//            // can't really improve on this\n//            LOG(LOG_INFO) << \"no more sentences to satisfy!  exiting early after \"<< iteration-1 << \" iterations\";\n//            return currentModel;\n//        }\n//\n//        // pick one at random\n//        boost::uniform_int<std::size_t> curFormUniformPick(0, notFullySatisfied.size()-1);\n//        ELSentence toImprove = curFormulas.at(notFullySatisfied.at(curFormUniformPick(rng)));\n//        LOG(LOG_DEBUG) << \"choosing formula: \" << toImprove << \" to improve.\";\n//        // find the set of moves that improve it\n//        std::vector<Move> moves = findMovesFor(d, currentModel, toImprove, rng);\n//        if (moves.size() == 0) {\n//            LOG(LOG_WARN) << \"WARNING: unable to find moves for sentence \" << toImprove.sentence()->toString()\n//                    << \" but couldn't find any (even though its violated)!  continuing...\";\n//            continue; // TODO: this shouldn't happen, right?\n//        }\n//        if (FileLog::globalLogLevel() <= LOG_DEBUG) {\n//            std::ostringstream vecStream;\n//            for (std::vector<Move>::const_iterator it = moves.begin(); it != moves.end(); it++) {\n//                if (it != moves.begin()) vecStream << \", \";\n//                vecStream << \"(\" << it->toString() << \")\";\n//            }\n//            LOG(LOG_DEBUG) << \"moves to consider: \" << vecStream.str();\n//        }\n//        boost::bernoulli_distribution<> randMovePick(probOfRandomMove);\n//        if (randMovePick(rng)) {\n//            // take a random move\n//            boost::uniform_int<std::size_t> movesPick(0, moves.size()-1);\n//            Move aMove = moves[movesPick(rng)];\n//            LOG(LOG_DEBUG) << \"taking random move: \" << aMove.toString();\n//            currentModel = executeMove(d, aMove, currentModel);\n//            score_pair scorePair = computeScoresForMove(d, currentModel, aMove, currentScore, formScores, occurs);\n//            currentScore = scorePair.totalScore;\n//            formScores = scorePair.formScores;\n//        } else {\n//            // find the models resulting from each move, and choose the highest scoring model as our next model\n//            double bestLocalScore = 0.0;\n//            std::vector<Model> bestLocalModels;\n//            std::vector<Move> bestLocalMoves;\n//            std::vector<score_pair> bestLocalScorePairs;\n//\n//            //bestLocalModels.push_back(currentModel);\n//            for (std::vector<Move>::const_iterator it=moves.begin(); it != moves.end(); it++) {\n//                Model nextModel = executeMove(d, *it, currentModel);\n//                score_pair scorePair = computeScoresForMove(d, nextModel, *it, currentScore, formScores, occurs);\n//                double nextScore = scorePair.totalScore;\n//                if (nextScore > bestLocalScore) {\n//                    bestLocalModels.clear();\n//                    bestLocalMoves.clear();\n//                    bestLocalScorePairs.clear();\n//\n//                    bestLocalScore = nextScore;\n//                    bestLocalModels.push_back(nextModel);\n//                    bestLocalMoves.push_back(*it);\n//                    bestLocalScorePairs.push_back(scorePair);\n//                } else if (nextScore == bestLocalScore) {\n//                    bestLocalModels.push_back(nextModel);\n//                    bestLocalMoves.push_back(*it);\n//                    bestLocalScorePairs.push_back(scorePair);\n//                }\n//            }\n//            boost::uniform_int<std::size_t> modelPick(0, bestLocalModels.size()-1);\n//            int idx = modelPick(rng);  // choose one at random\n//            currentModel = bestLocalModels[idx];\n//            score_pair scorePair = bestLocalScorePairs[idx];\n//            currentScore = scorePair.totalScore;\n//            formScores = scorePair.formScores;\n//            LOG(LOG_DEBUG) << \"choosing best local move: \" << bestLocalMoves[idx].toString();\n//        }\n//        // evaluate and see if our model is better than any found so far\n//        if (currentScore > bestScore) {\n//            LOG(LOG_DEBUG) << \"remembering this model as best scoring so far\";\n//            bestModel = currentModel;\n//            bestScore = currentScore;\n//        }\n//    }\n//\n//    return bestModel;\n\n\n    std::runtime_error e(\"MWSSolver::run() not implemented.\");\n    throw e;\n}\n\nModel MWSSolver::updateWithMove(const Move& m,\n        const Model& currentModel,\n        const boost::unordered_map<Atom, std::vector<std::vector<ELSentence>::size_type > >& atomMap,\n        std::vector<bool>& formsNeedUpdate) {\n    // scan over all atoms in the move - if its being modified, mark the formula as needing update\n    boost::unordered_set<Atom> moveAtoms;\n    for (std::vector<Move::change>::const_iterator it = m.toAdd.begin();\n            it != m.toAdd.end();\n            it++) {\n        moveAtoms.insert(it->get<0>());\n    }\n    for (std::vector<Move::change>::const_iterator it = m.toDel.begin();\n            it != m.toDel.end();\n            it++) {\n        moveAtoms.insert(it->get<0>());\n    }\n\n    for (boost::unordered_set<Atom>::const_iterator it = moveAtoms.begin();\n            it != moveAtoms.end();\n            it++) {\n        Atom a = *it;\n        if (atomMap.count(a)) {\n            // TODO: loop over all sentences\n            std::vector<std::vector<ELSentence>::size_type > formsWithAtom = atomMap.at(a);\n            for (std::vector<std::vector<ELSentence>::size_type >::const_iterator atomIt = formsWithAtom.begin();\n                    atomIt != formsWithAtom.end();\n                    atomIt++) {\n            formsNeedUpdate[*atomIt] = true;\n            }\n        }\n    }\n\n    // now execute the move\n    return executeMove(*domain_, m, currentModel);\n}\n\n/*\nModel maxWalkSat(Domain& d,\n        int numIterations,\n        double probOfRandomMove,\n        boost::mt19937& rng,\n        const Model* initialModel,\n        std::ostream* dataout) {\n    row_out datalog(dataout);\n\n    Model currentModel(d.maxInterval());\n    if (initialModel==0) currentModel = d.defaultModel();\n    else currentModel = *initialModel;\n\n    // filter out sentences we can't currently generate moves for\n    std::vector<int> validForms;\n    //std::vector<int> validNorm;\n    std::vector<ELSentence> formulas(d.formulas_begin(), d.formulas_end());\n    //std::vector<ELSentence> formulas = formSet.formulas();\n    for (std::vector<ELSentence>::size_type i = 0; i < formulas.size(); i++) {\n        ELSentence form = formulas[i];\n        if (form.hasInfWeight()) {\n            throw std::invalid_argument(\"maxWalkSat(): can't solve a problem with infinite weights - rewrite first\");\n        }\n        if (canFindMovesFor(*(form.sentence()), d)) {\n            validForms.push_back(i);\n        } else {\n            // TODO: use a logging warning instead of stderr\n            //std::cerr << \"WARNING: currently cannot generate moves for sentence: \\\"\" << d.formulas().at(i).sentence()->toString() << \"\\\".\" << std::endl;\n            LOG(LOG_WARN) << \"currently cannot generate moves for sentence: \\\"\" <<form.sentence()->toString() << \"\\\".\";\n        }\n    }\n    if (validForms.size() ==0) {\n        // TODO: log an error\n        std::cerr << \"ERROR: no valid sentences to generate moves for!\" << std::endl;\n        return currentModel;\n    }\n\n    AtomOccurences occurs = findAtomOccurences(formulas);\n    std::vector<double> formScores;\n    double currentScore = 0.0;\n    for (unsigned int i = 0; i < formulas.size(); i++) {\n        ELSentence formula = formulas[i];\n        double localScore = d.score(formula, currentModel);\n        formScores.push_back(localScore);\n        currentScore += localScore;\n    }\n\n    // initialize best score to the current score\n    double bestScore = currentScore;\n    Model bestModel = currentModel;\n\n\n    unsigned int showPeriodMod = (numIterations < 20 ? 1 : numIterations/20);\n\n    for (int iteration=1; iteration <= numIterations; iteration++) {\n        if (iteration % showPeriodMod == 0) {\n            std::cout << \".\";\n            std::cout.flush();\n        }\n        LOG(LOG_DEBUG) << \"currentModel: \" << currentModel;\n        LOG(LOG_DEBUG) << \"current score: \" << currentScore;\n\n        datalog << currentScore;\n\n        // make a list of the current unsatisfied formulas we can calc moves for\n        std::vector<int> notFullySatisfied = validForms;\n        std::vector<ELSentence> curFormulas = formulas;\n\n        for (std::vector<int>::iterator it = notFullySatisfied.begin(); it != notFullySatisfied.end(); ) {\n            int i = *it;\n\n            ELSentence wsent = curFormulas.at(i);\n            //const WSentence *wsentence = *it;\n            if (wsent.fullySatisfied(currentModel, d)) {\n                it = notFullySatisfied.erase(it);\n            } else {\n                it++;\n            }\n        }\n\n        if (notFullySatisfied.size()==0) {\n            // can't really improve on this\n            LOG(LOG_INFO) << \"no more sentences to satisfy!  exiting early after \"<< iteration-1 << \" iterations\";\n            return currentModel;\n        }\n\n        // pick one at random\n        boost::uniform_int<std::size_t> curFormUniformPick(0, notFullySatisfied.size()-1);\n        ELSentence toImprove = curFormulas.at(notFullySatisfied.at(curFormUniformPick(rng)));\n        LOG(LOG_DEBUG) << \"choosing formula: \" << toImprove << \" to improve.\";\n        // find the set of moves that improve it\n        std::vector<Move> moves = findMovesFor(d, currentModel, toImprove, rng);\n        if (moves.size() == 0) {\n            LOG(LOG_WARN) << \"WARNING: unable to find moves for sentence \" << toImprove.sentence()->toString()\n                    << \" but couldn't find any (even though its violated)!  continuing...\";\n            continue; // TODO: this shouldn't happen, right?\n        }\n        if (FileLog::globalLogLevel() <= LOG_DEBUG) {\n            std::ostringstream vecStream;\n            for (std::vector<Move>::const_iterator it = moves.begin(); it != moves.end(); it++) {\n                if (it != moves.begin()) vecStream << \", \";\n                vecStream << \"(\" << it->toString() << \")\";\n            }\n            LOG(LOG_DEBUG) << \"moves to consider: \" << vecStream.str();\n        }\n        boost::bernoulli_distribution<> randMovePick(probOfRandomMove);\n        if (randMovePick(rng)) {\n            // take a random move\n            boost::uniform_int<std::size_t> movesPick(0, moves.size()-1);\n            Move aMove = moves[movesPick(rng)];\n            LOG(LOG_DEBUG) << \"taking random move: \" << aMove.toString();\n            currentModel = executeMove(d, aMove, currentModel);\n            score_pair scorePair = computeScoresForMove(d, currentModel, aMove, currentScore, formScores, occurs);\n            currentScore = scorePair.totalScore;\n            formScores = scorePair.formScores;\n        } else {\n            // find the models resulting from each move, and choose the highest scoring model as our next model\n            double bestLocalScore = 0.0;\n            std::vector<Model> bestLocalModels;\n            std::vector<Move> bestLocalMoves;\n            std::vector<score_pair> bestLocalScorePairs;\n\n            //bestLocalModels.push_back(currentModel);\n            for (std::vector<Move>::const_iterator it=moves.begin(); it != moves.end(); it++) {\n                Model nextModel = executeMove(d, *it, currentModel);\n                score_pair scorePair = computeScoresForMove(d, nextModel, *it, currentScore, formScores, occurs);\n                double nextScore = scorePair.totalScore;\n                if (nextScore > bestLocalScore) {\n                    bestLocalModels.clear();\n                    bestLocalMoves.clear();\n                    bestLocalScorePairs.clear();\n\n                    bestLocalScore = nextScore;\n                    bestLocalModels.push_back(nextModel);\n                    bestLocalMoves.push_back(*it);\n                    bestLocalScorePairs.push_back(scorePair);\n                } else if (nextScore == bestLocalScore) {\n                    bestLocalModels.push_back(nextModel);\n                    bestLocalMoves.push_back(*it);\n                    bestLocalScorePairs.push_back(scorePair);\n                }\n            }\n            boost::uniform_int<std::size_t> modelPick(0, bestLocalModels.size()-1);\n            int idx = modelPick(rng);  // choose one at random\n            currentModel = bestLocalModels[idx];\n            score_pair scorePair = bestLocalScorePairs[idx];\n            currentScore = scorePair.totalScore;\n            formScores = scorePair.formScores;\n            LOG(LOG_DEBUG) << \"choosing best local move: \" << bestLocalMoves[idx].toString();\n        }\n        // evaluate and see if our model is better than any found so far\n        if (currentScore > bestScore) {\n            LOG(LOG_DEBUG) << \"remembering this model as best scoring so far\";\n            bestModel = currentModel;\n            bestScore = currentScore;\n        }\n    }\n\n    return bestModel;\n}\n\n\nnamespace {\n    AtomOccurences findAtomOccurences(const std::vector<ELSentence>& sentences) {\n        // set up a mapping from atom to formula index.  this represents formulas where the atom occurs\n        AtomCollector collector;\n        AtomOccurences occurs;\n        for (std::vector<ELSentence>::size_type i = 0; i < sentences.size(); i++) {\n            ELSentence formula = sentences.at(i);\n\n            collector.atoms.clear();\n            formula.sentence()->visit(collector);\n            // add this index to all occurrences of our atom\n            BOOST_FOREACH(Atom a, collector.atoms) {\n                FormSet set = occurs[a];\n                if (set.count(i) == 0) {\n                    set.insert(i);\n                    occurs[a] = set;\n                }\n            }\n        }\n\n        return occurs;\n    }\n\n    score_pair computeScoresForMove(const Domain& d,\n            const Model& m,\n            const Move& move,\n            double currentScore,\n            const std::vector<double>& curFormScores,\n            const AtomOccurences& occurs) {\n        // first, find the formulas we need to recompute\n        std::set<int> formsToRescore;\n        std::vector<Move::change> allchanges(move.toAdd);\n        std::copy(move.toDel.begin(), move.toDel.end(), std::back_inserter(allchanges));\n\n        BOOST_FOREACH(Move::change change, allchanges) {\n            Atom a = change.get<0>();\n            if (occurs.count(a) > 0) {\n                AtomOccurences::const_iterator it = occurs.find(a);\n                FormSet changedForms = it->second;\n                std::copy(changedForms.begin(), changedForms.end(), std::inserter(formsToRescore, formsToRescore.end()));\n            }\n        }\n\n        score_pair pair;\n        pair.formScores = curFormScores;\n        pair.totalScore = currentScore;\n\n        // start recomputing, adjusting the total score as necessary\n        std::vector<ELSentence> formulas(d.formulas_begin(), d.formulas_end());\n        for (std::set<int>::const_iterator it = formsToRescore.begin(); it != formsToRescore.end(); it++) {\n            int formNum = *it;\n            ELSentence sentence = formulas[formNum];\n\n            double score = d.score(sentence, m);\n            if (score != curFormScores.at(formNum)) {   // TODO: require some sort of epsilon check?\n                double difference = score - curFormScores.at(formNum);\n                pair.formScores[formNum] = score;\n                pair.totalScore += difference;\n            }\n        }\n\n        return pair;\n    }\n}\n*/\n\nvoid MWSSolver::updateScores(const std::vector<ELSentence>& formulas,\n        const Model& model,\n        std::vector<bool>& whichToUpdate,\n        std::vector<double>& scores,\n        std::vector<bool>& fullySatisfied) {\n//    std::cout << \"in MWSSolver::updateScores()\" << std::endl;\n//\n//    std::cout << \"fullySatisfied: \";\n//    std::copy(fullySatisfied.begin(), fullySatisfied.end(), std::ostream_iterator<bool>(std::cout, \", \"));\n//    std::cout << std::endl;\n\n    // first, calculate all the SISets for our sentences\n    for (std::size_t i = 0;\n            i < whichToUpdate.size();\n            i++) {\n\n        if (!whichToUpdate[i]) {\n//            std::cout << \"  asked not to update this formula\" << std::endl;\n            continue;    // skip elements that don't need updating\n        }\n        ELSentence formula = formulas[i];\n\n        // find the quantification for the current sentence\n        SISet quantification(domain_->maxSpanInterval(), false, domain_->maxInterval());\n        if (formula.isQuantified()) {\n            quantification = formula.quantification();\n        }\n\n        SISet formSat = formula.dSatisfied(model, *domain_);\n        // next, overwrite the score for the model\n        scores[i] = ((double)formSat.size()) * formula.weight();\n        // finally, mark if its completely satisfied\n        SISet leftover = quantification;\n        leftover.subtract(formSat);\n        if (leftover.empty()) {\n            fullySatisfied[i] = true;\n        } else {\n            fullySatisfied[i] = false;\n        }\n        // done updating!  make a note\n        whichToUpdate[i] = false;\n    }\n//    std::cout << \"leaving MWSSolver::updateScores()\";\n//    std::cout << \"fullySatisfied: \";\n//    std::copy(fullySatisfied.begin(), fullySatisfied.end(), std::ostream_iterator<bool>(std::cout, \", \"));\n//    std::cout << std::endl;\n\n}\n", "meta": {"hexsha": "50502f7cf69c39f435724a218bfc50b2332c0504", "size": 30819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inference/MaxWalkSat.cpp", "max_stars_repo_name": "JunLi-Galios/repel", "max_stars_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inference/MaxWalkSat.cpp", "max_issues_repo_name": "JunLi-Galios/repel", "max_issues_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inference/MaxWalkSat.cpp", "max_forks_repo_name": "JunLi-Galios/repel", "max_forks_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_forks_repo_licenses": ["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.3459915612, "max_line_length": 161, "alphanum_fraction": 0.5705571239, "num_tokens": 6899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.02716923055104719, "lm_q1q2_score": 0.010058739424861289}}
{"text": "/*\nCopyright or © or Copr. CNRS\n\nThis software is a computer program whose purpose is to estimate\nphylogenies and evolutionary parameters from a dataset according to\nthe maximum likelihood principle.\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\nliability. \n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading,  using,  modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean  that it is complicated to manipulate,  and  that  also\ntherefore means  that it is reserved for developers  and  experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or \ndata to be ensured and,  more generally, to use and operate it in the \nsame conditions as regards security. \n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n*/\n\n/**\n\n@file\n@author Wandrille Duchemin\n@created 06-Nov-2015\n@modified 16-Jun-2016\n\n\n**/\n\n#include <stdlib.h>\n#include <time.h>\n#include <boost/foreach.hpp>\n\n#include \"MyCladesAndTripartitions.h\"\n\n\n//Private functions\n\n\n/*\nTakes:\n - CladeForest * CF : pointer to a cladeForest instance\n - int idU : current idU\n - double probaFixed = 1.0 : probability not to choose the split (hypothetically) described in the CladeForest\n\nReturns:\n\t(pair <int,int>):  a split of that clade chosen according to the CladeForest or randomly drawn (according to its split ratio)\n*//*\npair <int,int> getNextOrRandomClade(CladeForest * CF , int idU , double probaFixed)\n{\n\n\tpair <int,int> chosenSplit;\n\n\tdouble r = ((double) rand()/ RAND_MAX); //random results\n\tdouble ratio;//to store the various ratios\n\n\n\tint nbSplit = getSplitCount(idU);\n\tint counter;\n\n\tbool foundRandom = false;\n\tbool preferFixed = true;\n\n\tdouble rFixed = ((double) rand()/ RAND_MAX); //random results\n\tif( rFixed > probaFixed ) // we will chose at random\n\t{\n\t\tpreferFixed = false;\n\t}\n\n\tfor(counter=0;counter<nbSplit;counter++)//for each split\n\t{\n\t\tif(preferFixed) // we chose the clade from the cladeForest if possible\n\t\t{\n\t\t\tpair <int,int> tempresult= getCladeSplit(idU,counter); // check if the clade exists in the CladeForest\n\t\n\t\t\tif( ( CF->hasClade(tempresult.first) ) || ( CF->hasClade(tempresult.second) ) ) // found\n\t\t\t{\n\t\t\t\tchosenSplit = tempresult;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(!foundRandom)\n\t\t{\n\t\t\tratio = getSplitRatio(idU,counter);\n\t\t\tif( r <= ratio)\n\t\t\t{\n\t\t\t\tchosenSplit = getCladeSplit(idU,counter);//the chosen clade is found and returned\n\t\t\t\tfoundRandom = true;\n\t\t\t}\n\t\t\tr = r - ratio;//not the chosen clade, we update r\n\t\t}\n\n\t\tif((foundRandom) && (!preferFixed))\n\t\t\tbreak; // we found the random choice and won't take the fixed choice -> no need to continue\n\t}\n\n\treturn chosenSplit;\n}\n*/\n\n/**\nTakes:\n\t- int idU : id of a clade\n\nReturns:\n\tpair<int,int> a split of that clade drawn randomly (according to its split ratio)\n**/\npair<int,int> MyCladesAndTripartitions::getRandomClade(int idU)\n{\n\n\tdouble r = ((double) rand()/ RAND_MAX); //random results\n\tdouble ratio;//to store the various ratios\n\n\n\tint nbSplit = getSplitCount(idU);\n\tint counter;\n\tfor(counter=0;counter<nbSplit;counter++)//for each split\n\t{\n\t\tratio = getSplitRatio(idU,counter);\n\t\tif( r <= ratio)\n\t\t\treturn getCladeSplit(idU,counter);//the chosen clade is found and returned\n\t\tr = r - ratio;//not the chosen clade, we update r\n\t}\n\treturn getCladeSplit(idU,nbSplit - 1);//return the last split\n\n}\n\n/**\nTakes:\n\t- int idU : id of a clade\n\nReturns:\n\tpair<int,int> a split of that clade that has the maximum split ratio\n**/\npair<int,int> MyCladesAndTripartitions::getMaxClade(int idU)\n{\n\n\t//First, we find the list of all split of clade idU with the maximum ratio\n\tdouble maxRatio = 0;\n\tvector<int> maxIndex;//vector to keep the indexes of the split with the max ratio\n\n\tdouble ratio;\n\n\tint nbSplit = getSplitCount(idU);\n\n\t//cout << idU << \":\" << nbSplit << endl;\n\tint counter;\n\tfor(counter=0;counter<nbSplit;counter++)//for each split\n\t{\n\t\tratio = getSplitRatio(idU,counter);\n\t\tif(ratio > maxRatio)\n\t\t{\n\t\t\tmaxRatio = ratio;\n\t\t\tmaxIndex.clear();\n\t\t\tmaxIndex.push_back(counter);\n\t\t}\n\t\telse if(ratio == maxRatio)\n\t\t{\n\t\t\tmaxIndex.push_back(counter);\n\t\t}\n\t}\n\n\n\t\n\tif(maxIndex.size() == 1)//There is only one split with the maximum ratio: return it\n\t{\n\t\treturn getCladeSplit(idU,maxIndex[0]);\n\t}\n\n\t//There is more than one split: return a random one\n\tint r = rand() % maxIndex.size();\n\treturn getCladeSplit(idU,maxIndex[r]);\n\n}\n\n\n/**\nTakes:\n\t- int &pOrd : current depth-first post-order number\n\t- int idU : current clade in the recursion\n\nReturns:\n\tMyGeneNode * \n**/\nMyGeneNode *MyCladesAndTripartitions::getRandomTreeAux(int &pOrd,int idU )\n{\n    MyGeneNode *node = new MyGeneNode();\n    pair<int,int> cladeSplit = getRandomClade( idU );\n    if( cladeSplit.first != -1 ) {\n        node->addSon( getRandomTreeAux( pOrd, cladeSplit.first ) );\n        node->addSon( getRandomTreeAux( pOrd, cladeSplit.second ) );\n        node->setBranchProperty(bpp::TreeTools::BOOTSTRAP, bpp::Number<double>(pOrd));\n    } else \n        node->setName( mClades.getLeafName( idU ) );\n\n    if( mBranchLengths[idU] != -1 )\n        node->setDistanceToFather( (mBranchLengths[idU] + 1)/getCladeOccurrences(idU) );\n\n    pOrd++;\n\n    return node;\n}\n\n\n/**\nTakes:\n\t- int &pOrd : current depth-first post-order number\n\t- int idU : current clade in the recursion\n\nReturns:\n\tMyGeneNode * \n**/\nMyGeneNode * MyCladesAndTripartitions::getMaxTreeAux(int &pOrd,int idU ) \n{\n    MyGeneNode *node = new MyGeneNode();\n    pair<int,int> cladeSplit = getMaxClade( idU);\n    //cout << idU << \"->\" << cladeSplit.first << \",\" << cladeSplit.second << endl;\n    if( cladeSplit.first != -1 ) {\n        node->addSon( getMaxTreeAux( pOrd, cladeSplit.first ) );\n        node->addSon( getMaxTreeAux( pOrd, cladeSplit.second ) );\n        node->setBranchProperty(bpp::TreeTools::BOOTSTRAP, bpp::Number<double>(pOrd));\n    } else \n        node->setName( mClades.getLeafName( idU ) );\n\n    if( mBranchLengths[idU] != -1 )\n        node->setDistanceToFather( (mBranchLengths[idU] + 1)/getCladeOccurrences(idU) );\n\n    pOrd++;\n\n    return node;\n\n}\n\n/**\nRECURSIVE\n\nTakes:\n\t- MyGeneNode * node: a tree to compute the likelihood from\n\t- double default_proba: proba to give to a split that is absent from the MyCladesAndTripartitions counts\n\t\nReturns:\n\tpair<double,vector<string>>:\n\t\tdouble: likelihood of the node (and underlying subtree) according to the CCPs distribution.\n\t\tvector<string>: list of all the leaves in the subtree rooted at node\n**/\npair<double,vector<string> > MyCladesAndTripartitions::getTreeLikelihoodAux(MyGeneNode *node, double default_proba)\n{\n\n\tstd::pair<double, vector<string> > toreturn;\n\n\ttoreturn.first = 1;//set base proba to 1.\n\n\tif (node->isLeaf())\n\t{\n\t\ttoreturn.second.push_back(node->getName());\n\t\treturn toreturn;\n\t}\n\t\n\tint nbson,i, cladeId;\n\n\tnbson = node->getNumberOfSons();\n\n\tif(nbson ==1)//only one son -> this is a intermediary node of some sort \n\t\treturn getTreeLikelihoodAux(node->getSon(0),default_proba);// return the value for its only son\n\telse if(nbson > 2)//more than 2 sons: error\n\t\tthrow bpp::Exception(\"MyCladesAndTripartitions::getTreeLikelihoodAux: does not work when the tree is polytomic!\");\n\n\t//We are now in the caser where there is more than one son\n\n\tstd::pair<double, vector<string> > tempresult;//to put the result from each son\n\n\tstd::pair<int,int> split;//split\n\n\t//first son\n\ttempresult = getTreeLikelihoodAux(node->getSon(0),default_proba);//getting the result for this son\n\n\ttoreturn.first *= tempresult.first;//updating proba\n\n\tBOOST_FOREACH( string leafName, tempresult.second)\n\t\ttoreturn.second.push_back(leafName);//updating leaf list\n\n\tsplit.first = mClades.getCladeIntFromLeafList(tempresult.second);\n\n\ttempresult.second.clear();//clearing \n\n\t//second son\n\ttempresult = getTreeLikelihoodAux(node->getSon(1),default_proba);//getting the result for this son\n\n\ttoreturn.first *= tempresult.first;//updating proba\n\tBOOST_FOREACH(string leafName, tempresult.second)\n\t\ttoreturn.second.push_back(leafName);//updating leaf list\n\n\tsplit.second = mClades.getCladeIntFromLeafList(tempresult.second);\n\n\ttempresult.second.clear();//clearing \n\n\t//now getting current cladeId\n\tcladeId = mClades.getCladeIntFromLeafList(toreturn.second);\n\t\n\tif(cladeId == -1 )\n\t\ttoreturn.first *=default_proba;\n\telse if(split.first != -1 || split.second != -1)//if the son clades are known\n\n\t\tfor(i=0 ; i < getSplitCount(cladeId) ; i++)\n\t\t{\n\t\t\tpair <int,int> testsplit = getCladeSplit(cladeId,i);\n\t\t\tif(split.first == testsplit.first || split.second == testsplit.first)//found the correct split\n\t\t\t{\n\n\t\t\t\tif(cladeId != 0 || mRooted)// special condition for the root clade: should not use split ratio if the distribution is unrooted\n\t\t\t\t\ttoreturn.first *= getSplitRatio(cladeId,i);\n\t\t\t\telse if(cladeId == 0)\n\t\t\t\t\ttoreturn.first *= ((double) getCladeOccurrences(split.first))/ ((double) mGeneTreeCount); //  if we are the \"root\" clade but the distribution is unrooted, we should multiply by the number of time we saw the child clade (clade probability)\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(i == getSplitCount(cladeId))//the split was not found\n\t\t\ttoreturn.first *=default_proba;\n\n\treturn toreturn;\n}\n\n\ndouble MyCladesAndTripartitions::getMaxLikelihoodAux(int idU)\n{\n\n\tif( mClades.isLeaf(idU) ) // stopping condition\n\t\treturn 1;\n\n\t\n\tdouble maxRatio = 0;\n\tdouble ratio;\n\n\tint nbSplit = getSplitCount(idU);\n\n\t//cout << idU << \":\" << nbSplit << endl;\n\tint counter;\n\tfor(counter=0;counter<nbSplit;counter++)//for each split\n\t{\n\t\tpair<int,int> cladeSplit = getCladeSplit(idU,counter);\n\n\t\tratio = 1;\n\t\tif(idU != 0 || mRooted)// special condition for the root clade: should not use split ratio if the distribution is unrooted\n\t\t\tratio *= getSplitRatio(idU,counter);\n\t\telse if(idU == 0)\n\t\t\tratio *= ((double) getCladeOccurrences(cladeSplit.first))/ ((double) mGeneTreeCount); //  if we are the \"root\" clade but the distribution is unrooted, we should multiply by the number of time we saw the child clade (clade probability)\n\n\n\t\tratio *= getMaxLikelihoodAux(cladeSplit.first) * getMaxLikelihoodAux(cladeSplit.second);\n\n\t\tif(ratio > maxRatio)\n\t\t{\n\t\t\tmaxRatio = ratio;\n\t\t}\n\t}\n\n\treturn maxRatio;\n\n}\n\n\n// Public functions\n\n\n\n/**\n * Constructor - Compute all clades and tripartitions for the given \n * gene trees. \n */\nMyCladesAndTripartitions::MyCladesAndTripartitions( char charSep, vector<MyGeneTree*> &geneTrees, bool verbose, bool &overflow, string &errStr, bool polytomy ) : CladesAndTripartitions( charSep, geneTrees,verbose,overflow, errStr,polytomy,NULL)\n{srand (time(NULL));//init the random seed\n}\n\n\n/**\n * Constructor - Ale reader\n * \n */\nMyCladesAndTripartitions::MyCladesAndTripartitions( char charSep, string aleFileName, string &errStr, bool verbose ) : CladesAndTripartitions( charSep, aleFileName, errStr, verbose )\n{srand (time(NULL));//init the random seed\n}\n\n\n/**\nReturns a tree where bipartitions have been drawn at random according to their split ratios\n**/\nMyGeneTree * MyCladesAndTripartitions::getRandomTree()\n{\n \tif( mClades.getLeafCount() < 3 )\n \t\treturn getMaxTree(); \n\n    int pOrd = 0;\n    MyGeneNode *node = getRandomTreeAux( pOrd, mClades.getRootClade() );\n    return new MyGeneTree( *node );\n}\n\n/**\nReturns a tree where bipartition have the maximum split ratios for the encountered clades\n**/\nMyGeneTree * MyCladesAndTripartitions::getMaxTree()\n{\n\tint pOrd = 0;\n\tMyGeneNode *node;\n\n\t//special procedures when there is only 1 or 2 leaves in the tree.\n\tif(mClades.getLeafCount() == 1)\n\t{\n\t\t//cout << \" clade count \" << mClades.getCladeCount() << endl;\n\t\t//printMe();\n\t    node = new MyGeneNode();\n\t    node->setName( mClades.getLeafName( 1 ) );\n\t}\n\telse if(mClades.getLeafCount() == 2)\n\t{\n\t    node = new MyGeneNode();\n    \n\t\tvector<int> Scl = mClades.getSortedClades();\n\t\tfor(unsigned i = 0; i < Scl.size(); i++)\n\t\t{\n\t\t\tif(mClades.isLeaf(Scl[i]))\n\t\t\t{\n\t\t\t\tMyGeneNode *sonNode = new MyGeneNode();\n\t\t\t\tsonNode->setName( mClades.getLeafName( Scl[i] ) );\n\t\t\t\tnode->addSon( sonNode);\n\t\t\t\tnode->setBranchProperty(bpp::TreeTools::BOOTSTRAP, bpp::Number<double>(pOrd));\n\t\t\t}\t\t\n\t\t}\n    }\n    else\n    {\n\t\tnode = getMaxTreeAux( pOrd, mClades.getRootClade() );\n    }\n\t\n\n    return new MyGeneTree( *node );\n}\n\n/**\nRECURSIVE\n\nTakes:\n\t- MyGeneNode * node: a tree to compute the likelihood from\n\t- double default_proba: proba to give to a split that is absent from the MyCladesAndTripartitions counts\n\nReturns:\n\tdouble: likelihood of the node (and underlying subtree) according to the CCPs distribution.\n\nNB: requires the tree to be binary\n**/\ndouble MyCladesAndTripartitions::getTreeLikelihood(MyGeneNode *node, double default_proba)\n{\n\tpair<double,vector<string> > result;\n\tresult = getTreeLikelihoodAux(node,default_proba);//recursive function\n\treturn result.first;\n}\n\n/*\nTakes:\n - node (MyGeneNode *): node of a tree\n\nReturns:\n (bool): true if the leafs of the subtree rooted at node all corresponds to existing clades in the MyCladesAndTripartitions instance\n */\nbool MyCladesAndTripartitions::isCompatible(MyGeneNode * node)\n{\n\tif(node->isLeaf())\n\t{\n\t\tvector <string> leafNames;\n\t\tleafNames.push_back(node->getName());\n\n\t\ttry\n\t\t{\n\t\t\tmClades.getCladeIntFromLeafList(leafNames); // will throw an error if the leaf clade does not exists\n\t\t}\n\t\tcatch(exception & e) // not very elegant.\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tbool result= true;\n\n\t//recursion\n\tint nbson = node->getNumberOfSons();\n\n\tfor(int i = 0; i < nbson; i++)\n\t{\n\t\tif(!isCompatible(node->getSon(i)))\n\t\t{\n\t\t\tresult = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn result;\n}\n\ndouble MyCladesAndTripartitions::getMaxLikelihood()\n{\n\treturn getMaxLikelihoodAux(mClades.getRootClade());\n}\n\n\n\nint MyCladesAndTripartitions::RestrictToClade(vector <int> cladesToForce)\n{\n\t//1. from clade to force to clade to delete\n\t// the clades to delete are the clades incompatible with the ones we want to force\n\tvector< vector<int> > noncompatibleLists = mClades.PUBLICgetNoncompatible();\t\n\tmap <int,bool> cladeToDeleteMAP; // we first put the clades to delete in a map to avoid doubles\n\t//cout << \"restricting to clades\" ;\n\tfor(unsigned i = 0 ; i < cladesToForce.size(); i++)\n\t{\n\t\tint idU = cladesToForce[i];\n\t\t//cout << \" \" << idU ;\n\t\tfor(unsigned j = 0 ; j < noncompatibleLists[idU].size(); j++)\n\t\t{\n\t\t\tcladeToDeleteMAP[ noncompatibleLists[idU][j] ] = true;\n\t\t}\n\t}\n\n\tfor(unsigned i = 0 ; i < cladesToForce.size(); i++)// remove the clades to restrict from the clade to delete list to if they appear in the map\n\t{\n\t\tint idU = cladesToForce[i];\n\t\tcladeToDeleteMAP[ idU ] = false;\n\t}\n\n\t//cout << endl;\n\tvector <int> cladeToDelete;\n\tfor (map<int,bool>::iterator it=cladeToDeleteMAP.begin(); it!=cladeToDeleteMAP.end(); ++it) \n\t{\n\t\tif(it->second) // that way we don't remove a clade to restrict\n\t  \t\tcladeToDelete.push_back( it->first );\n  \t}\n\t//cout << \"MyCladesAndTripartitions::RestrictToClade. Deleting \"<< cladeToDelete.size() << \" clades\"<<endl;\n\t//for(unsigned i = 0 ; i < cladeToDelete.size(); i++)\n\t//\tcout << cladeToDelete[i] << \" \";\n\t//cout << endl;\n  \t//2. delete the clades to delete\n\treturn deleteClades(cladeToDelete);\n}\n\n\nint MyCladesAndTripartitions::RestrictToClade(vector <vector <string> > cladesToForce)\n{\n\tvector <int> cladesToForceIDU;\n\n\tfor( unsigned i = 0 ; i < cladesToForce.size() ; i++)\n\t{\n\t\tint idU = mClades.getCladeIntFromLeafList( cladesToForce[i] );\n\t\tif(idU >= 0 )\n\t\t\tcladesToForceIDU.push_back( idU );\n\t\n\t\t//cout << idU <<\" <- \";\n\t\t//for(unsigned j = 0 ; j < cladesToForce[i].size() ; j++)\n\t\t//\tcout << cladesToForce[i][j] << \" \";\t\n\t\t//cout << endl;\n\t}\n\treturn RestrictToClade(cladesToForceIDU);\n}\n\n\n\n\n\n\n\n/*\nworks if source is amalgamted trees\n*/\nMyCladesAndTripartitions::MyCladesAndTripartitions(MyCladesAndTripartitions * source)\n{\n\n    mRooted = false;   ///< amalgamated tree is not rooted\n\n    mGeneTreeCount = source->getmGeneTreeCount();\n\n    mNewickGeneTree = source->getmNewickGeneTree(); ///< save newick string for ALE output\n\n\tmClades = source->mClades;\n\n\n\tvector <int> sortedClades = mClades.getSortedClades();\n\n\tfor(unsigned i = 0 ; i < sortedClades.size(); i++)\n\t{\n\t\tint cladeNum = i;// as this is how things are organized in the cladesandtripartition instance, we keep this structure\n\n\t\tint splitCount = source->getSplitCount( cladeNum );\n\n\t\tmCladeSplits.push_back( vector< pair<int,int> > () );        ///< All splits for each clade (by clade id)\n\t\tmSplitsRatio.push_back( vector <double> ()  );        ///< Occurence of each split as a vector, divided by clade occurrences.\n\t\tfor(unsigned splitNum = 0 ; splitNum < splitCount; splitNum++)\n\t\t{\n\t\t\tmCladeSplits[cladeNum].push_back( source->getCladeSplit( cladeNum, splitNum ) ) ;\n\t\t\tmSplitsRatio[cladeNum].push_back( source->getSplitRatio( cladeNum, splitNum ) ) ;\n\t\t}\n\n\t    mCladeOccurrences.push_back( source->getCladeOccurrences( cladeNum ) );///< Occurence of each clade, indexed by clade number.\n\n\t\tmBranchLengths.push_back( source->getmBranchLengths( cladeNum ) ); ///< branch length for each clade\n\n\t}\n\n}", "meta": {"hexsha": "9eaa844764ff9068d854a8e6e7b83a01f3bed63f", "size": 17635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/DeCoSTAR_01042020/source/MyCladesAndTripartitions.cpp", "max_stars_repo_name": "danydoerr/spp_dcj", "max_stars_repo_head_hexsha": "1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T16:03:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T14:52:43.000Z", "max_issues_repo_path": "tools/DeCoSTAR_01042020/source/MyCladesAndTripartitions.cpp", "max_issues_repo_name": "danydoerr/spp_dcj", "max_issues_repo_head_hexsha": "1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a", "max_issues_repo_licenses": ["MIT"], "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/DeCoSTAR_01042020/source/MyCladesAndTripartitions.cpp", "max_forks_repo_name": "danydoerr/spp_dcj", "max_forks_repo_head_hexsha": "1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a", "max_forks_repo_licenses": ["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.4435483871, "max_line_length": 244, "alphanum_fraction": 0.7073433513, "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.02716922956641336, "lm_q1q2_score": 0.010058739060324829}}
{"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_SOLVER_HPP_\n#define DART_OPTIMIZATION_SOLVER_HPP_\n\n#include <iostream>\n#include <memory>\n\n#include <Eigen/Dense>\n\nnamespace dart {\nnamespace optimization {\n\nclass Problem;\n\n/// Abstract class that provides a common interface for different Solvers. The\n/// different Solver implementations each use a different nonlinear problem\n/// solving library, which could lead to differences in performance for various\n/// problem types. This base class allows the different Solver implementations\n/// to be swapped out with each other quickly and easily to help with testing,\n/// benchmarking, and experimentation.\nclass Solver\n{\npublic:\n  /// The Solver::Properties class contains Solver parameters that are common\n  /// to all Solver types. Most (but not necessarily all) Solvers will make use\n  /// of these parameters, and these parameters can be directly copied or\n  /// transferred between all Solver types.\n  struct Properties\n  {\n    /// Nonlinear optimization Problem to be solved\n    std::shared_ptr<Problem> mProblem;\n\n    /// The relative tolerance on the optimization parameters. For example, the\n    /// distance between the last parameters and the current parameters to be\n    /// considered converged.\n    double mTolerance;\n\n    /// The maximum number of iterations that the solver should use. Use 0 for\n    /// infinite iterations.\n    std::size_t mNumMaxIterations;\n\n    /// How many iterations between printing the Solver's progress to the\n    /// terminal. Use 0 for no printing.\n    std::size_t mIterationsPerPrint;\n\n    /// Stream for printing the Solver's progress. Default is std::cout.\n    std::ostream* mOutStream;\n\n    /// Set to true if the final result should be printed to the terminal.\n    bool mPrintFinalResult;\n\n    /// Publish the results of the optimization to a file. Leave this string\n    /// empty to avoid publishing anything.\n    std::string mResultFile;\n\n    Properties(\n        std::shared_ptr<Problem> _problem = nullptr,\n        double _tolerance = 1e-9,\n        std::size_t _numMaxIterations = 500,\n        std::size_t _iterationsPerPrint = 0,\n        std::ostream* _ostream = &std::cout,\n        bool _printFinalResult = false,\n        const std::string& _resultFile = \"\");\n  };\n\n  /// Default Constructor\n  explicit Solver(const Properties& _properties = Properties());\n\n  /// Alternative Constructor\n  explicit Solver(std::shared_ptr<Problem> _problem);\n\n  /// \\brief Destructor\n  virtual ~Solver() = default;\n\n  /// Solve optimization problem\n  virtual bool solve() = 0;\n\n  /// Get the type (implementation) of this Solver\n  virtual std::string getType() const = 0;\n\n  /// Create an identical clone of this Solver\n  virtual std::shared_ptr<Solver> clone() const = 0;\n\n  /// Set the generic Properties of this Solver\n  void setProperties(const Properties& _properties);\n\n  /// Get the generic Properties of this Solver\n  const Properties& getSolverProperties() const;\n\n  /// Copy the generic Properties of another Solver\n  void copy(const Solver& _otherSolver);\n\n  /// Copy the generic Properties of another Solver\n  Solver& operator=(const Solver& _otherSolver);\n\n  /// Set the nonlinear optimization problem\n  virtual void setProblem(std::shared_ptr<Problem> _newProblem);\n\n  /// Get nonlinear optimization problem\n  std::shared_ptr<Problem> getProblem() const;\n\n  /// Set the maximum step size allowed for the Problem to be considered\n  /// converged\n  virtual void setTolerance(double _newTolerance);\n\n  /// Get the maximum step size allowed for the Problem to be considered\n  /// converged\n  double getTolerance() const;\n\n  /// Set the maximum number of iterations that the Solver should use\n  virtual void setNumMaxIterations(std::size_t _newMax);\n\n  /// Get the maximum number of iterations that the Solver should use\n  std::size_t getNumMaxIterations() const;\n\n  /// Set the number of iterations that should pass between printing progress to\n  /// the terminal. Use 0 for no printing.\n  virtual void setIterationsPerPrint(std::size_t _newRatio);\n\n  /// Get the number of iterations that should pass between printing progress to\n  /// the terminal. A value of 0 means there will be no printing.\n  std::size_t getIterationsPerPrint() const;\n\n  /// Set the output stream that prints the Solver's progress.\n  virtual void setOutStream(std::ostream* _os);\n\n  /// Get the output stream that prints the Solver's progress.\n  std::ostream* getOutStream() const;\n\n  /// Set to true if the final result should be printed to the terminal\n  virtual void setPrintFinalResult(bool _print);\n\n  /// Returns true if the final result should be printed to the terminal\n  bool getPrintFinalResult() const;\n\n  /// Set the name of the file that results should be printed to. Use an empty\n  /// string to indicate that results should not be printed to a file.\n  virtual void setResultFileName(const std::string& _resultFile);\n\n  /// Get the name of the file that results should be printed to. An empty\n  /// string indicates that results should not be printed to a file.\n  const std::string& getResultFileName() const;\n\nprotected:\n  Properties mProperties;\n};\n\n} // namespace optimization\n} // namespace dart\n\n#endif // DART_OPTIMIZATION_SOLVER_HPP_\n", "meta": {"hexsha": "1d8b1ac0f7e75c83dbf984c53f9d8f1ab62a8b90", "size": 6817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/optimization/Solver.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/Solver.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/Solver.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": 37.2513661202, "max_line_length": 80, "alphanum_fraction": 0.7352207716, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28140560742914383, "lm_q2_score": 0.03567854895516831, "lm_q1q2_score": 0.010040143740919584}}
{"text": "#ifndef ATM_SUBSTRINGS_FROM_LONGEST_HPP\n#define ATM_SUBSTRINGS_FROM_LONGEST_HPP\n\n#include <cmath>\n#include <map>\n#include <vector>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/range/algorithm/find.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/iterator.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/size.hpp>\n#include <boost/range/sub_range.hpp>\n#include <boost/range/value_type.hpp>\n#include <boost/utility.hpp>\n#include \"sast/sast.hpp\"\n\n\nnamespace atm {\n\ntemplate <class RandomAccessRange, class Index>\nstruct substrings_from_longest {\n    using range_type = RandomAccessRange;\n    using char_type = typename boost::range_value<RandomAccessRange>::type;\n    using index_type = Index;\n\nprotected:\n    using sast_type = sast::sast<RandomAccessRange, index_type>;\n\npublic:\n    struct substr {\n        using iterator       = typename boost::range_iterator<RandomAccessRange>::type;\n        using const_iterator = typename boost::range_const_iterator<RandomAccessRange>::type;\n\n        index_type pos()           const { return parent_->pos(i_, j_); }\n        boost::sub_range<const std::vector<index_type>> allpos() const { return parent_->allpos(i_, j_); }\n        index_type length()        const { return j_ - i_; }\n        index_type frequency()     const { return parent_->frequency(i_, j_); }\n        double     spurity()       const { return parent_->strict_purity(i_, j_); }\n        double     lpurity()       const { return parent_->loose_purity(i_, j_); }\n        double     luniversality() const { return parent_->left_universality(i_, j_); }\n        double     runiversality() const { return parent_->right_universality(i_, j_); }\n\n        iterator begin() { return boost::begin(parent_->input_) + i_; }\n        iterator end()   { return boost::begin(parent_->input_) + j_; }\n        const_iterator begin() const { return boost::const_begin(parent_->input_) + i_; }\n        const_iterator end()   const { return boost::const_begin(parent_->input_) + j_; }\n\n        substr(const substrings_from_longest* parent, int i, int j)\n            : parent_(parent), i_(i), j_(j)\n        {}\n\n    private:\n        const substrings_from_longest* parent_;\n        int i_;\n        int j_;\n    };\n\nprivate:\n    template <class> struct substring_iterator;\n\npublic:\n    using iterator       = substring_iterator<substr>;\n    using const_iterator = substring_iterator<const substr>;\n\n    substrings_from_longest(const sast_type& sast)\n        : sast_(sast),\n          input_(sast_.input()),\n          finder_(sast::make_positional_finder(sast_))\n    {}\n\n    iterator begin() { return iterator(this, 0, boost::size(input_)); }\n    iterator end()   { return iterator(this, 0, 0); }\n    const_iterator begin() const { return const_iterator(this, 0, boost::size(input_)); }\n    const_iterator end()   const { return const_iterator(this, 0, 0); }\n\nprivate:\n    template <class Value>\n    struct substring_iterator\n        : public boost::iterator_facade<\n            substring_iterator<Value>,\n            Value,\n            boost::random_access_traversal_tag,\n            Value,\n            int>\n    {\n        substring_iterator()\n            : parent_(0), i_(-1), j_(-1)\n        {}\n\n        substring_iterator(const substrings_from_longest* parent, int i, int j)\n            : parent_(parent), i_(i), j_(j)\n        {}\n\n        template <class OtherValue>\n        substring_iterator(const substring_iterator<OtherValue>& other)\n            : parent_(other.parent_), i_(other.i_), j_(other.j_)\n        {}\n\n    private:\n        friend class boost::iterator_core_access;\n        template <class> friend struct substring_iterator;\n\n        void increment() {\n            if (static_cast<std::size_t>(j_) == boost::size(parent_->input_)) {\n                const auto width = (j_ - i_) - 1;\n                i_ = 0;\n                j_ = 0 + width;\n            }\n            else {\n                ++i_;\n                ++j_;\n            }\n        }\n\n        void decrement() {\n            if (i_ == 0) {\n                const auto width = (j_ - i_) + 1;\n                i_ = boost::size(parent_->input_) - width;\n                j_ = boost::size(parent_->input_);\n            }\n            else {\n                --i_;\n                --j_;\n            }\n        }\n\n        void advance(int n) {\n            if (n >= 0) {\n                auto width = j_ - i_;\n                while (static_cast<std::size_t>(n) > boost::size(parent_->input_) - j_) {\n                    n -= (boost::size(parent_->input_) - j_) + 1;\n                    --width;\n                    i_ = 0;\n                    j_ = 0 + width;\n                }\n                i_ += n;\n                j_ += n;\n            }\n            else {\n                n = -n;\n                auto width = j_ - i_;\n                while (n > i_ - 0) {\n                    n -= (i_ - 0) + 1;\n                    ++width;\n                    i_ = boost::size(parent_->input_) - width;\n                    j_ = boost::size(parent_->input_);\n                }\n                i_ -= n;\n                j_ -= n;\n            }\n        }\n\n        int distance_to(const substring_iterator<Value>& other) const {\n            int d = 0;\n            auto width = j_ - i_;\n            auto owidth = other.j_ - other.i_;\n            if (owidth < width || (owidth == width && other.i_ > this->i_)) {\n                int j = this->j_;\n                while (owidth < width) {\n                    d += (boost::size(parent_->input_) - j) + 1;\n                    --width;\n                    j = 0 + width;\n                }\n                d += other.j_ - j;\n            }\n            else {\n                int j = other.j_;\n                while (owidth > width) {\n                    d += (boost::size(parent_->input_) - j) + 1;\n                    --owidth;\n                    j = 0 + owidth;\n                }\n                d += this->j_ - j;\n                d = -d;\n            }\n            return d;\n        }\n\n        template <class OtherValue>\n        bool equal(const substring_iterator<OtherValue>& other) const {\n            return this->parent_ == other.parent_\n                && this->i_ == other.i_\n                && this->j_ == other.j_;\n        }\n\n        Value dereference() const {\n            return substr(parent_, i_, j_);\n        }\n\n        const substrings_from_longest* parent_;\n        int i_;\n        int j_;\n    };\n\nprotected:\n    index_type pos(const int i, const int j) const {\n        const auto len_substr = j - i;\n        // substrに対応する内部ノードを見つける。\n        typename sast_type::const_iterator n = finder_.find(i, j);\n        if (n->length() >= len_substr) {\n            // substrは2回以上出現しており、対応する内部ノードが存在する。\n            return n->pos();\n        }\n        else {\n            // substrは1回しか出現しておらず、対応する内部ノードが存在しない。\n            return i;\n        }\n    }\n\n    boost::sub_range<const std::vector<index_type>> allpos(const int i, const int j) const {\n        const auto len_substr = j - i;\n        // substrに対応する内部ノードを見つける。\n        typename sast_type::const_iterator n = finder_.find(i, j);\n        if (n->length() >= len_substr) {\n            // substrは2回以上出現しており、対応する内部ノードが存在する。\n            return n->allpos();\n        }\n        else {\n            // substrは1回しか出現しておらず、対応する内部ノードが存在しない。\n            auto found = boost::find(n->allpos(), i);\n            return boost::make_iterator_range(found, boost::next(found));\n        }\n    }\n\n    index_type frequency(const int i, const int j) const {\n        const auto len_substr = j - i;\n        // substrに対応する内部ノードを見つける。\n        typename sast_type::const_iterator n = finder_.find(i, j);\n        if (n->length() >= len_substr) {\n            // substrは2回以上出現しており、対応する内部ノードが存在する。\n            return n->frequency();\n        }\n        else {\n            // substrは1回しか出現しておらず、対応する内部ノードが存在しない。\n            return 1;\n        }\n    }\n\n    double strict_purity(const int i, const int j) const {\n        const auto len_substr = j - i;\n        // substrに対応する内部ノードを見つける。\n        typename sast_type::const_iterator n = finder_.find(i, j);\n        if (n->length() >= len_substr) {\n            // substrは2回以上出現しており、対応する内部ノードが存在する。\n            const auto kk = n->length() - len_substr;  // ノードkではkk文字削ったことに相当する。\n\n            return strict_purity_(n, kk);\n        }\n        else {\n            // substrは1回しか出現しておらず、対応する内部ノードが存在しない。\n            // substrと同じ出現回数のsub-substrを数える。\n            uint64_t count = 0;\n            {\n                // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n                count += len_substr - n->length();\n            }\n            for (int l = 1; l < len_substr; ++l) {\n                // substrの先頭をl文字削ったsub-substrを考える。\n                const auto len_subsubstr = len_substr - l;\n\n                // sub-substrに対応するノードを見つける。\n                // d[node_to_parent_node[m]] < len_subsubstr <= d[m] を満たす m を\n                // 見つける。\n                typename sast_type::const_iterator m = finder_.find(i + l, j);\n                if (m->length() < len_subsubstr) {\n                    count += len_subsubstr - m->length();\n                }\n            }\n\n            // strict purity of substr\n            const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n            const double spurity = static_cast<double>(count) / num_subsubstrs;\n\n            return spurity;\n        }\n    }\n\n    double strict_purity_(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n        const auto freq_substr = n->frequency();\n        const auto len_substr  = n->length() - ii;\n\n        // substrと同じ出現回数のsub-substrを数える。\n        uint64_t count = 0;\n        {\n            // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n            // ノードiに対応する部分文字列をsubstr[i]とすると、substr[i]の末尾\n            // を削って得られる部分文字列の内で、substr[i]と同じ頻度をもつもの\n            // はsuffix tree上ではノードiにまとめられている\n            // （分岐が無い <=> 頻度が同じ）。\n\n            // ノードiの親ノードjを見つける。\n            const auto m = n.parent();\n\n            // substrの末尾を0文字以上削って得られるsub-substrの内で、出現\n            // 回数がsubstrと同じものの数はd[i] - d[j]である。\n            count += n->length() - m->length() - ii;\n        }\n        for (int j = 1; j < len_substr; ++j) {\n            // substrの先頭をj文字削ったsub-substrを考える。\n            const auto len_subsubstr = len_substr - j;\n\n            // sub-substrに対応するノードを見つける。\n            // {内部,葉}ノードに対応する部分文字列から先頭の1文字を削って得られ\n            // る文字列には、必ず対応する{内部,葉}ノードが存在する。\n            // ii ＞ 0 の場合、d[k] == len_subsubstr を満たす「ノード」が必ずし\n            // も存在するとは限らない。よって、\n            // d[node_to_parent_node[k]] < len_subsubstr <= d[k] を満たす k を\n            // 見つける。\n            auto m = n;\n            for (int l = 0; l < j; ++l) {\n                m = m.suffix();\n            }\n            while (m.parent()->length() >= len_subsubstr) {\n                m = m.parent();\n            }\n            const auto kk = m->length() - len_subsubstr;  // ノードiでii文字削ると、ノードkではkk文字削ったことに相当する。\n\n            // sub-substrの出現回数をチェックする。\n            const auto freq_subsubstr = m->frequency();\n            if (freq_subsubstr == freq_substr) {\n                // ノードkの親ノードmを見つける。\n                const auto mp = m.parent();\n\n                // sub-substrの末尾を0文字以上削って得られる\n                // sub-sub-substrの内で、出現回数がsub-substrと同じもの\n                // の数はd[k] - d[m]である。\n                count += m->length() - mp->length() - kk;\n            }\n        }\n\n        // strict purity of substr\n        const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n        const double spurity = static_cast<double>(count) / num_subsubstrs;\n\n        return spurity;\n    }\n\n    double loose_purity(const int i, const int j) const {\n        const auto len_substr = j - i;\n        // substrに対応する内部ノードを見つける。\n        typename sast_type::const_iterator n = finder_.find(i, j);\n        if (n->length() >= len_substr) {\n            // substrは2回以上出現しており、対応する内部ノードが存在する。\n            const auto kk = n->length() - len_substr;  // ノードkではkk文字削ったことに相当する。\n\n            return loose_purity_(n, kk);\n        }\n        else {\n            // substrは1回しか出現しておらず、対応する内部ノードが存在しない。\n            // substrと同じ出現回数のsub-substrを数える。\n            double support = 0;\n            {\n                // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n                support += len_substr - n->length();\n                for (auto m = n, p = n.parent(); m->length() > 0; m = p, p = p.parent()) {\n                    const auto num_subsubstrs_of_same_frequency = m->length() - p->length();\n                    const auto freq_subsubstr = m->frequency();\n                    const double sup = 1.0 / freq_subsubstr;\n                    support += num_subsubstrs_of_same_frequency * sup;\n                }\n            }\n            for (int l = 1; l < len_substr; ++l) {\n                // substrの先頭をl文字削ったsub-substrを考える。\n                const auto len_subsubstr = len_substr - l;\n\n                // sub-substrに対応するノードを見つける。\n                // d[node_to_parent_node[m]] < len_subsubstr <= d[m] を満たす m を\n                // 見つける。\n                typename sast_type::const_iterator m = finder_.find(i + l, j);\n                if (m->length() >= len_subsubstr) {\n                    const auto mm = m->length() - len_subsubstr;  // ノードmではmm文字削ったことに相当する。\n\n                    // sub-substrの末尾を0文字以上削って得られるsub-substrについて考える。\n                    for (auto o = m, p = m.parent(); o->length() > 0; o = p, p = p.parent()) {\n                        const auto num_subsubstrs_of_same_frequency = o->length() - p->length() - (o == m ? mm : 0);\n                        const auto freq_subsubstr = o->frequency();\n                        const double sup = 1.0 / freq_subsubstr;\n                        support += num_subsubstrs_of_same_frequency * sup;\n                    }\n                }\n                else {\n                    support += len_subsubstr - m->length();\n                    for (auto o = m, p = m.parent(); o->length() > 0; o = p, p = p.parent()) {\n                        const auto num_subsubstrs_of_same_frequency = o->length() - p->length();\n                        const auto freq_subsubstr = o->frequency();\n                        const double sup = 1.0 / freq_subsubstr;\n                        support += num_subsubstrs_of_same_frequency * sup;\n                    }\n                }\n            }\n\n            // loose purity of substr\n            const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n            const double lpurity = support / num_subsubstrs;\n\n            return lpurity;\n        }\n    }\n\n    double loose_purity_(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n        const auto freq_substr = n->frequency();\n        const auto len_substr  = n->length() - ii;\n\n        double support = 0;\n        {\n            // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n            for (auto m = n, p = n.parent(); m->length() > 0; m = p, p = p.parent()) {\n                const auto num_subsubstrs_of_same_frequency = m->length() - p->length() - (m == n ? ii : 0);\n                const auto freq_subsubstr = m->frequency();\n                const double sup = static_cast<double>(freq_substr) / freq_subsubstr;\n                support += num_subsubstrs_of_same_frequency * sup;\n            }\n        }\n        for (int j = 1; j < len_substr; ++j) {\n            // substrの先頭をj文字削ったsub-substrを考える。\n            const auto len_subsubstr = len_substr - j;\n\n            // sub-substrに対応するノードを見つける。\n            // ii ＞ 0 の場合、d[k] == len_subsubstr を満たす「ノード」が必ずし\n            // も存在するとは限らない。よって、\n            // d[node_to_parent_node[k]] < len_subsubstr <= d[k] を満たす k を\n            // 見つける。\n            auto m = n;\n            for (int l = 0; l < j; ++l) {\n                m = m.suffix();\n            }\n            while (m.parent()->length() >= len_subsubstr) {\n                m = m.parent();\n            }\n            const auto kk = m->length() - len_subsubstr;  // ノードiでii文字削ると、ノードkではkk文字削ったことに相当する。\n\n            // sub-substrの末尾を0文字以上削って得られるsub-substrについて考える。\n            for (auto o = m, p = m.parent(); o->length() > 0; o = p, p = p.parent()) {\n                const auto num_subsubstrs_of_same_frequency = o->length() - p->length() - (o == m ? kk : 0);\n                const auto freq_subsubstr = o->frequency();\n                const double sup = static_cast<double>(freq_substr) / freq_subsubstr;\n                support += num_subsubstrs_of_same_frequency * sup;\n            }\n        }\n\n        // loose purity of substr\n        const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n        const double lpurity = support / num_subsubstrs;\n\n        return lpurity;\n    }\n\n    std::map<char_type, int> left_extensions(const int i, const int j) const {\n        std::map<char_type, int> char_dist;\n        for (const auto pos : allpos(i, j)) {\n            const auto& c = boost::const_begin(input_)[pos - 1];\n            char_dist[c] += 1;\n        }\n\n        return char_dist;\n    }\n\n    std::map<char_type, int> right_extensions(const int i, const int j) const {\n        const auto len_substr = j - i;\n\n        std::map<char_type, int> char_dist;\n        for (const auto pos : allpos(i, j)) {\n            const auto& c = boost::const_begin(input_)[pos + len_substr];\n            char_dist[c] += 1;\n        }\n\n        return char_dist;\n    }\n\n    double left_universality(const int i, const int j) const {\n        const auto freq_substr = frequency(i, j);\n\n        std::map<char_type, int> char_dist = left_extensions(i, j);\n\n        double e = 0;\n        for (const auto& kv : char_dist) {\n            const double p = static_cast<double>(kv.second) / freq_substr;\n            e += -p * std::log(p);\n        }\n        const double u = 1 - std::exp(-e);\n\n        return u;\n    }\n\n    double right_universality(const int i, const int j) const {\n        const auto freq_substr = frequency(i, j);\n\n        std::map<char_type, int> char_dist = right_extensions(i, j);\n\n        double e = 0;\n        for (const auto& kv : char_dist) {\n            const double p = static_cast<double>(kv.second) / freq_substr;\n            e += -p * std::log(p);\n        }\n        const double u = 1 - std::exp(-e);\n\n        return u;\n    }\n\n    const sast_type& sast_;\n    const RandomAccessRange& input_;\n    sast::positional_finder<RandomAccessRange, index_type> finder_;\n};\n\n}  // namespace atm\n\n\n#endif  /* ATM_SUBSTRINGS_FROM_LONGEST_HPP */\n", "meta": {"hexsha": "e45c006881be0bef6f4954337264fac94ac6acef", "size": 18696, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/atm/substrings_from_longest.hpp", "max_stars_repo_name": "yuttie/atm", "max_stars_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/atm/substrings_from_longest.hpp", "max_issues_repo_name": "yuttie/atm", "max_issues_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/atm/substrings_from_longest.hpp", "max_forks_repo_name": "yuttie/atm", "max_forks_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.373540856, "max_line_length": 116, "alphanum_fraction": 0.5271715875, "num_tokens": 5382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.023330767620074855, "lm_q1q2_score": 0.010035667832247635}}
{"text": "// Work started 08/14/2012\n// New code cleaned on June 10, 2013. \n// For past cpmd codes refer to versions before June 5, 2013\n// NB joined fun 05/01/2017.\n// This is main.\n// This is (Car Parrinello) molecular dynamics for electrostatics on membranes\n\n// VJ Lessons Learned, other notes (pre-May 2017):\n/*\nLessons:\n\n1. Do not use exit(1) to exit the program. This leads to memory leaks.\n\nOther Notes:\nAug 22 2012 - NOTE THREADSIZE different in different regions of code.\nfor precal it is 8, for fmd forces, energies it is 4.\nTesting parameters: echo 3 4 100 35 0.0001 300 0.8 0 1 1\n*/\n\n//  NB Changes (May 2017 - Present):\n/* Changes :\n\n2017.05.12:  NB has edited main.cpp to incorporate a single (1) type of fractionally ionizable group with parameter (alpha). This includes ability to echo (input) this new parameter (alpha) below and to call function \"new assign_random_q_values\" (found in Interface.cpp) using this parameter. [Preliminary studies reporting multiple groups have assumed the groups to have the same alpha values, i.e. one group is basic the other acidic and you are at pH = Mean[pKa1, pKa2].]\n\n2017.06.05:  NB has added working area constraint functions (SHAKE_for_area & RATTLE_for_area).  Area is conserved to within a fraction of a percent with default masses = 1.0, etc.  \n\n                2017.09.20:  SHAKE_for_area & RATTLE_for_area found to be in error, math mistake.  Only coincide\n\n2017.06.13:  NB has added a pre-MD line below to dump the initial state in the movie file as well; it calls this timestep \"-1\" in the movie file due to the way the function \"interface_movie\" is defined.\n\n2017.06.26:  NB is working to make the optimization dynamics a real-time study.  Because the temperature uniformly started at (.5T), an excess factor of 2 in the denominator of the standard deviation of the initial velocity distribution \"p_sigma\" was removed (within \"functions.cpp\").  The temperature now begins sufficiently close to the intended temperature (within 10% @ t = 1 step).  Energy conservation is improved after this correction. [Adding a factor of 2 in the denominator of all DOF's supplied to the thermostat also had this effect, but it seems correcting \"p_sigma\" - not thermostat DOF's - is the correct solution.  Some sources imply DOF's should be 3N - 1 due to constraint, however energy conservation seems to work marginally better without subtracting the constraint DOF, so subtraction may be wrong.]\n\n2017.06.28:  NB has finished adapting the code to a real-time study (sans barostat).  The parameters that optimally conserve energy for discretizations up to (3,8) are {C = 5,  T = 1.0, Q = 0.01, M = 1.0, dt = .00001, DOF = 3N}.\n\n2017.07.04:  NB has added a for statement allowing \"assign_random_q_values\" to create 5 divisions.\n\n2017.07.08:  NB made a few trivial changes such as 1) making \"total_time\" now specify the number of steps to run itself rather than a function of (dt) because it would have an error if the ratio became to large and 2) eliminating the unused variable M introduced to specify vertex mass (we must keep as 1.0).  Additionally, a character flag (\"annealFlag\") has been added (that must be echoed after all numerical parameters) that signifies if annealing should occur ('y' or 'n').\n\n2017.07.09:  NB is refining functionality to continue a simulation from a pre-existing off-file (\"Optimized.off\", must have this name). This involved adding a second character flag (that also must be echoed, after the numerical parameters and annealing flag) signifying if said off-file is to be loaded. If you use Nicholas' automated-PBS script generator, it will automatically denote the values of these flags in the cluster job name (and warn you if you are submitting a RT job that anneals).\n\n2017.08.08:  NB has randomized the charge distribution assignment scheme (rather than using permutations as it introduces significant stripes and polar deficits in charge density & potential, though it produces similar shapes for the case tested.)  Also, I am changing the function for generation of axially distributed patches of charge (spherical caps).\n\n2017.09.07:  NB has verified all mathematical components of the volume and area constraints.  All are correct, a factor of (1/2) is missing in the face area gradient within the \"compute_neg_VGrads\" function; however, adding it here causes major issues, meaning it is probably within those functions already (must check).  It is only used in bending energy calculations and (if area constrained) the \"SHAKE/RATTLE_for_area\" functions.  Adding (1/2) factors in the appropriate place within the \"SHAKE/RATTLE_for_area\" seems to be fine.\n\n*/\n\n#include \"utility.h\"\n#include \"interface.h\"\n#include \"vertex.h\"\n#include \"edge.h\"\n#include \"face.h\"\n#include \"particle.h\"\n#include \"control.h\"\n#include \"functions.h\"\n#include \"thermostat.h\"\n#include <boost/filesystem/operations.hpp>\n#include <boost/program_options.hpp>\n\nusing namespace boost::program_options;\n\n// Declaring function to initiate and propagate the MD:\nvoid md_interface(INTERFACE &, vector<PARTICLE> &, vector<THERMOSTAT> &, vector<THERMOSTAT> &, CONTROL &, char, char, char, const double scalefactor, double box_halflength);\n\n//MPI boundary parameters\nunsigned int lowerBoundMesh;\nunsigned int upperBoundMesh;\nunsigned int sizFVecMesh;\n//unsigned int extraElementsMesh;\nint lowerBoundIons;\nint upperBoundIons;\nint sizFVecIons;\nunsigned int extraElementsIons;\nmpi::environment env;\nmpi::communicator world;\n\nint main(int argc, const char *argv[]) {\n    // (2017.09.14 NB added.)  Delete existing outfiles directory if it exists, then recreate it empty.\n    if (world.rank() == 0) {\n        if (boost::filesystem::remove_all(\"outfiles\") == 0) perror(\"Error deleting outfiles directory\");\n        else cout << \"Pre-existing outfiles directory successfully, replaced with an empty directory.\" << endl;\n        boost::filesystem::create_directory(\"outfiles\");\n    }\n    // Declare variables to make the system:\n    double ein = epsilon_water;        // permittivity of inside medium\n    double eout = epsilon_water;        // permittivity of outside medium\n    double T, Q_mesh, Q_ion;                        // Temperature of the system, mass of thermostate (0 if inactive), timestep.\n    unsigned int chain_length;    // length of nose-hoover thermostat chain, 1 minimum, 1 means no thermostat\n\n    INTERFACE boundary;                    // interface (modelled as soft LJ wall)\n    unsigned int disc1, disc2;\n    double lambda_a, lambda_v;          // lambdas measuring strength of area & volume constraints  (unused)\n\n    double unit_radius_sphere, youngsModulus, q_strength, alpha, conc_out, z_out; // radius (in nm), net charge (if all charged), fractional q-occupancy, salt conc (MOLAR), salt valency\n    int numPatches;\n    double fracChargedPatch;\n    char randomFlag, offFlag, geomConstraint, bucklingFlag, constraintForm, counterionFlag, functionFlag;  // functionFlag indicates different pattern initializations, -y for yingyang pattern, -c for cube formation.\n    string externalPattern;\n\n    // Counterion Initializations:\n    double packing_fraction, box_halflength;\n    int counterion_valency;\n    double counterion_diameter = 0.6; // Counterion diameter in nanometers.\n    vector<PARTICLE> counterions;\n\n    // Control of the dynamics:\n    CONTROL mdremote;\n\n    // Specify variables via command line (-X x):\n    options_description desc(\"Usage:\\nrandom_mesh <options>\");\n    desc.add_options()\n            (\"help,h\", \"print usage message\")\n                 // Physical Parameters:\n            (\"unitRadius,R\", value<double>(&unit_radius_sphere)->default_value(10),\n             \"Radius of the initial sphere & simulation unit of length (in nanometers).\")\n            (\"netCharge,q\", value<double>(&q_strength)->default_value(600),\n             \"Net NP charge, if fully occupied (elementary charges).\")\n            (\"saltConc,c\", value<double>(&conc_out)->default_value(0.005),\n             \"Salt concentration (Molar).\")\n            (\"tensSigma,t\", value<double>(&boundary.sigma_a)->default_value(1),\n             \"Surface tension constant (dynes/cm).\")\n            (\"volTensSigma,v\", value<double>(&boundary.sigma_v)->default_value(1),\n             \"Volume tension constant (atm/nm^3).\")\n            (\"bending,b\", value<double>(&boundary.bkappa)->default_value(40),\n             \"The bending modulus of the particle (kB*T).\")\n            (\"Stretching,s\", value<double>(&boundary.sconstant)->default_value(40),\n             \"Reduced stretching modulus of the particle (kB*T/R0^2).\")\n            (\"GeomConstraint,G\", value<char>(&geomConstraint)->default_value('N'),\n             \"Specification of rigid geometric constraints, 'V' for volume.\")\n            (\"functionFlag,H\", value<char>(&functionFlag)->default_value('n'),\n             \"specification of function, 'y' for yinyang function.\")\n            (\"bucklingFlag,B\", value<char>(&bucklingFlag)->default_value('n'),\n             \"Specification of stretching form, if spontaneous buckling should occur.\")\n                 // Physical Parameters for patterned (Janus, Striped, Polyhedral) particles:\n            (\"numPatches,N\", value<int>(&numPatches)->default_value(1),\n             \"The number of distinct charge patches (of tunable size if N = 2).\")\n            (\"fracChargePatch,p\", value<double>(&fracChargedPatch)->default_value(0.5),\n             \"Surface area fraction of the patch (if N = 2, otherwise irrelevant).\")\n            (\"externalPattern,E\", value<string>(&externalPattern)->default_value(\"None\"),\n             \"Filename of pattern to be imported (without the '.dat' extension).\")\n                // Physical Parameters for counterion condensation:\n            (\"counterionFlag,I\", value<char>(&counterionFlag)->default_value('n'),\n             \"Flag specifying if explicit counterions should be present, 'y' for yes.\")\n            (\"packingFraction,P\", value<double>(&packing_fraction)->default_value(0.01),\n             \"NP packing fraction determining total box size.\")\n            (\"counterionValency,Z\", value<int>(&counterion_valency)->default_value(1),\n             \"Valency of the counterions.\")\n                // Virtual Parameters:\n            (\"totalTime,S\", value<int>(&mdremote.steps)->default_value(250000),\n             \"Duration of the simulation (total timesteps).\")\n            (\"timestep,d\", value<double>(&mdremote.timestep)->default_value(0.001),\n             \"Time step used in the simulation.\")\n            (\"initTemp,T\", value<double>(&T)->default_value(0.001),\n             \"Target initial temperature (prior to annealing).\")\n            (\"disc2,D\", value<unsigned int>(&disc2)->default_value(8),\n             \"Discretization parameter 2\")\n            (\"chain_length,C\", value<unsigned int>(&chain_length)->default_value(5),\n             \"Number of thermostat particles in the Nose-Hoover chain (plus 1).\")\n            (\"meshThermostatMass,Q\", value<double>(&Q_mesh)->default_value(.01),\n             \"Mass of the mesh thermostat (higher means less strongly coupled).\")\n            (\"ionsThermostatMass,Y\", value<double>(&Q_ion)->default_value(.01),\n             \"Mass of the ions thermostat (higher means less strongly coupled).\")\n                 // Annealing Parameters:\n            (\"annealFlag,a\", value<char>(&mdremote.anneal)->default_value('y'),\n             \"If annealing occurs or not ('y' for yes).\")\n            (\"anneal_freq,f\", value<int>(&mdremote.annealfreq)->default_value(50000),\n             \"Interval number of steps between which annealing commences.\")\n            (\"anneal_dura,u\", value<int>(&mdremote.annealDuration)->default_value(5000),\n             \"Number of steps over which to reduce (T = fT*T) & (Q_mesh = fQ*Q_mesh), same as before if 1\")\n            (\"anneal_Tfac,e\", value<double>(&mdremote.TAnnealFac)->default_value(1.25),\n             \"Fold reduction to temperature at initial annealing call.  Was 10 before (and constant throughout)\")\n                 // Runtime & Output Parameters:\n            (\"randomFlag,F\", value<char>(&randomFlag)->default_value('y'),\n             \"If predefined shape used or not ('y' for yes).\")\n            (\"offFlag,o\", value<char>(&offFlag)->default_value('n'),\n             \"If predefined shape used or not ('y' for yes).\")\n            (\"moviestart,m\", value<int>(&mdremote.moviestart)->default_value(1),\n             \"The starting point of the movie\")\n            (\"offfreq,O\", value<int>(&mdremote.offfreq)->default_value(2500),\n             \"The frequency of making off files\")\n            (\"moviefreq,M\", value<int>(&mdremote.moviefreq)->default_value(1000),\n             \"The frequency of shooting the movie\")\n            (\"povfreq,V\", value<int>(&mdremote.povfreq)->default_value(100000),\n             \"The frequency of making povray files\")\n            (\"writedata,W\", value<int>(&mdremote.writedata)->default_value(500),\n             \"frequency of dumping thermo time series (after 1K steps)\");\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n\n    // Compute the box radius (where NP radius is unit length so it is not found here):\n    //if(counterionFlag != 'y') packing_fraction = 1.0;\n    //box_halflength = pow(1 / packing_fraction,1.0/3.0);\n    box_halflength = 1.0;\n    // Reducing the counterion diameter:\n    counterion_diameter = (counterion_diameter / unit_radius_sphere);\n\n    // Compute the 2D Young's Modulus (in kB*T/nm^2) from the reduced stretching constant specified as input:\n    youngsModulus = boundary.sconstant / (unit_radius_sphere * unit_radius_sphere);  // For information purposes only.\n\n    // The dimensionless form of the tension factors are a function of radius:\n    double dynePerCm_Scalefactor = pow(10,-14)*(pow(unit_radius_sphere, 2)/unitenergy);\n    boundary.sigma_a = (dynePerCm_Scalefactor * boundary.sigma_a);    // Coefficient is 1 (dyne/cm) in (kB T_room/(R0 nm^2)).\n    //double dynePerUmFifth_Scalefactor = pow(10,-4)*pow(10,-18)*(pow(unit_radius_sphere, 6)/unitenergy);\n    //boundary.sigma_v = (dynePerUmFifth_Scalefactor * boundary.sigma_v);\n    double atmPerNmThird_Scalefactor = (1.01325 * pow(10,5)) * pow(10,-27) * (pow(unit_radius_sphere, 6) / (unitenergy * pow(10, -7)));\n    boundary.sigma_v = atmPerNmThird_Scalefactor * boundary.sigma_v;\n\n    // The scale factor for electrostatic interactions is a function of radius:\n    const double scalefactor = epsilon_water * lB_water / unit_radius_sphere;\n\n    disc1 = 3;                                          //  Discretization parameters (h, k).\n    alpha = 1.0;                                        //  Fractional charge occupancy.\n    if (chain_length == 1) Q_mesh = 0;                  //  Reduced mass of the thermostat particle(s)\n    if (chain_length == 1) Q_ion = 0;                   //  Reduced mass of the thermostat particle(s)\n\n    mdremote.QAnnealFac =\n            1.00 + (mdremote.TAnnealFac / 10.0);        // Maintain previous scaling, same as before (fQ = 2) if fT = 10.\n\n    // Flags for rigid geometric constraint and form:\n    constraintForm = 'L';                               // Enforce a linear constraint (not quadratic).\n\n    // ### Simulation setup: ###\n    // Unused quantities for antiquated constraints & energy functionals:\n    lambda_v = 0;                        // hardwiring volume constraint. Unused.\n    lambda_a = 0;                        // hardwiring area constraint. Unused.\n    boundary.lambda_l = 0;            // forgot what was this?!  NB:  I think it's an edge line tension force. Unused.\n\n    // Electrostatics setup (membrane, implicit salt ions):\n    z_out = 1;                        // Valency of implicit (salt) ions.\n    boundary.ein = ein;               // Permittivity inside the membrane.\n    boundary.eout = eout;             // Permittivity outside the membrane.  (Both equal by default.)\n    boundary.set_up(unit_radius_sphere);\n    // Assigning the Debye length outside (in reduced units):\n    if (conc_out == 0)\n        boundary.inv_kappa_out = 100000000;  // Effectively infinite, no screening.\n    else\n        boundary.inv_kappa_out =\n                (0.257 / sqrt(z_out * boundary.lB_out * unit_radius_sphere * conc_out)) / unit_radius_sphere;\n\n    // Generate the membrane, assign charge to vertices:\n    boundary.discretize(disc1, disc2);            // discretize the interface\n    if (disc1 != 0 || disc2 != 0) {\n        if (externalPattern == \"None\") \n\t\t\t  boundary.assign_random_q_values(q_strength, alpha, numPatches, fracChargedPatch, randomFlag, functionFlag);\n        else \n\t\t\t  boundary.assign_external_q_values(q_strength, externalPattern);\n\t }\n\n    //  Assess total actual charge on the membrane for record & to place the correct number of counterions:\n    double q_actual = 0;\n    for (unsigned int i = 0; i < boundary.V.size(); i++) {\n        q_actual += boundary.V[i].q;\n    }\n\n    // Populate the box with counterions, if requested:\n    if(counterionFlag == 'y') {\n        boundary.put_counterions(q_actual, unit_radius_sphere, counterion_diameter, box_halflength, counterions, counterion_valency);\n        cout << \"Counterions have been placed inside the box.\" << endl;\n    }\n\n    boundary.dressup(lambda_a, lambda_v);            // Compute initial normals, areas, and volumes.\n\n    boundary.ref_area = boundary.total_area; // NB changed from (4 * pi), discrete membrane differs.\n    boundary.ref_volume = boundary.total_volume;\n    //boundary.ref_Area_Vertices = boundary.total_Area_Vertices;    // (2017.09.19 NB added.)  Initial area by vertices.\n\n    // LJ parameters (mesh-mesh almost never invoked, present for security reasons):\n    double lj_length_mesh_mesh_coeff = 0.1;\n    boundary.lj_length_mesh_mesh = lj_length_mesh_mesh_coeff * boundary.avg_edge_length;\n    double meshPointRadius = 0.5 * boundary.avg_edge_length;\n    boundary.lj_length_mesh_ions = ((2.0 * meshPointRadius + counterion_diameter) / 2.0);\n    boundary.elj = 1.0;\n\n    // Thermostat for MD of the interface:\n    vector<THERMOSTAT> mesh_bath, ions_bath;        // thermostat for real system (interface + ions)\n    if (chain_length == 1) {\n        mesh_bath.push_back(THERMOSTAT(0, T, 3 * boundary.V.size(), 0.0, 0, 0));\n        ions_bath.push_back(THERMOSTAT(0, T, 3 * counterions.size(), 0.0, 0, 0));\n    }\n    else {\n        mesh_bath.push_back(THERMOSTAT(Q_mesh, T, 3 * boundary.V.size(), 0, 0, 0));\n        ions_bath.push_back(THERMOSTAT(Q_ion, T, 3 * counterions.size(), 0, 0, 0));\n        while (mesh_bath.size() != chain_length - 1)\n            mesh_bath.push_back(THERMOSTAT(Q_mesh, T, 1, 0, 0, 0));\n        while (ions_bath.size() != chain_length - 1)\n            ions_bath.push_back(THERMOSTAT(Q_ion, T, 1, 0, 0, 0));\n        mesh_bath.push_back(THERMOSTAT(0, T, 3 * boundary.V.size(), 0.0, 0, 0));    // dummy bath (has 0 mass)\n        ions_bath.push_back(THERMOSTAT(0, T, 3 * counterions.size(), 0.0, 0, 0));\n    }\n\n    // Assign masses to vertices\n    for (unsigned int i = 0; i < boundary.V.size(); i++)\n        boundary.V[i].m = 1.0;      // NB:  Energy conservation fails invariably if not = 1.0 .\n\n    // NB added following lines to load off-file (stops if the file is not found; specify correctly):\n    if (offFlag == 'y') boundary.load_configuration(\"380000.off\");\n\n    int numOfNodes = world.size();\n    if (world.rank() == 0) {\n#pragma omp parallel default(shared)\n        {\n            if (omp_get_thread_num() == 0) {\n                printf(\"Number of MPI processes used %d\\n\", numOfNodes);\n                printf(\"Number of OpenMP threads per MPI process %d\\n\", omp_get_num_threads());\n            }\n        }\n    }\n\n    if (world.rank() == 0) {\n        // Define an output stream to provide the same things as the (*.out) file on the HPC cluster (minus run outputs):\n        // Useful in automated analysis when console output is not saved by default on local PC.\n        ofstream list_out(\"outfiles/simulation.out\", ios::app);\n\n        // ### Output to the console (or HPC *.out file) & backup \"simulation.out\" file) the simulation parameters: ###\n\n        cout << \"\\n===================\\nMembrane\\n===================\\n\";\n        cout << \"Unit radius of the sphere (in nm): \" << unit_radius_sphere << endl;\n        cout << \"Number of vertices: \" << boundary.V.size() << endl;\n        cout << \"Number of edges: \" << boundary.E.size() << endl;\n        cout << \"Number of faces: \" << boundary.F.size() << endl;\n        cout << \"Lambda_v: \" << lambda_v << endl;\n        cout << \"Lambda_a: \" << lambda_a << endl;\n        cout << \"Lambda_l: \" << boundary.lambda_l << endl;\n        cout << \"Total intial volume: \" << boundary.total_volume << \"  Sphere volume: \" << (4. / 3.) * pi\n             << \"  Ref volume: \" << boundary.ref_volume << endl;\n        cout << \"Total intial face area: \" << boundary.total_area << \"  Sphere area: \" << 4 * pi << \"  Ref area: \"\n             << boundary.ref_area << endl;\n        cout << \"Mesh point radius: \" << meshPointRadius << endl;\n        cout << \"Bending rigidity: \" << boundary.bkappa << endl;\n        cout << \"Young's Modulus (2D): \" << youngsModulus << endl;\n        cout << \"Stretching constant: \" << boundary.sconstant << endl;\n        cout << \"Surface Tension constant: \" << (boundary.sigma_a / dynePerCm_Scalefactor) << endl;\n        cout << \"Volume Tension constant: \" << (boundary.sigma_v / atmPerNmThird_Scalefactor)<< endl;\n        cout << \"Unstretched edge length: \" << boundary.avg_edge_length\n             << endl; // NB uncommented & replaced the output value.\n        cout << \"LJ strength: \" << boundary.elj << endl;\n        cout << \"LJ mesh-mesh distance cutoff: \" << boundary.lj_length_mesh_mesh << endl;\n        cout << \"LJ mesh-ion distance cutoff: \" << boundary.lj_length_mesh_ions << endl;\n        cout << \"Rigid geometric constraint: \" << geomConstraint << endl;\n\n        cout << \"\\n===================\\nElectrostatics\\n===================\\n\";\n        cout << \"Total charge on membrane (if homogeneously charged): \" << q_strength << endl;\n        cout << \"Final actual charge on membrane: \" << q_actual << endl;\n        cout << \"Number of simulated counterions: \" << counterions.size() << endl;\n        cout << \"Fractional charge occupancy (alpha): \" << alpha << endl;\n        cout << \"The number of patches is: \" << numPatches << endl;\n        cout << \"The size of each patch is: \" << fracChargedPatch << endl;\n        cout << \"The name of the external file used to specify charge patterning is: \" << externalPattern << endl;\n        cout << \"Salt concentration: \" << conc_out << endl;\n        cout << \"Debye length: \" << boundary.inv_kappa_out << endl;\n        cout << \"Bjerrum length: \" << boundary.lB_out << endl;\n\n        cout << \"\\n===================\\nThermodynamics\\n===================\\n\";\n        cout << \"Initial Temperature (T): \" << T << endl;\n        cout << \"Thermostat mass (Q_mesh): \" << mesh_bath[0].Q << endl;\n        cout << \"Number of thermostats (C): \" << mesh_bath.size() << endl;\n        cout << \"Timestep (dt): \" << mdremote.timestep << \"  &  Total steps: \" << mdremote.steps << \".\" << endl;\n        cout << \"Annealing: \" << mdremote.anneal << endl;\n        cout << \"Anneal frequency: \" << mdremote.annealfreq << endl;\n        cout << \"Anneal duration: \" << mdremote.annealDuration << endl;\n        cout << \"Temperature annealing decrement: \" << mdremote.TAnnealFac << endl;\n        cout << \"Thermostat mass decrement: \" << mdremote.QAnnealFac << endl;\n        cout << \"Randomness during run: \" << randomFlag << endl;\n        cout << \"Off-file loaded: \" << offFlag << endl;\n\n        // Same thing in a file even if you're not on an HPC that can store the console output automatically on request:\n        list_out << \"===================\\nMembrane\\n===================\\n\";\n        list_out << \"Unit radius of the sphere (in nm): \" << unit_radius_sphere\n                 << endl; //NB added in observing size change.\n        list_out << \"Number of vertices: \" << boundary.V.size() << endl;\n        list_out << \"Number of edges: \" << boundary.E.size() << endl;\n        list_out << \"Number of faces: \" << boundary.F.size() << endl;\n        list_out << \"Lambda_v: \" << lambda_v << endl;\n        list_out << \"Lambda_a: \" << lambda_a << endl;\n        list_out << \"Lambda_l: \" << boundary.lambda_l << endl;\n        list_out << \"Total intial volume: \" << boundary.total_volume << \"  Sphere volume: \" << (4. / 3.) * pi\n                 << \"  Ref volume: \" << boundary.ref_volume << endl;\n        list_out << \"Total intial face area: \" << boundary.total_area << \"  Sphere area: \" << 4 * pi << \"  Ref area: \"\n                 << boundary.ref_area << endl;\n        list_out << \"Mesh point radius: \" << meshPointRadius << endl;\n        list_out << \"Bending rigidity: \" << boundary.bkappa << endl;\n        list_out << \"Young's Modulus (2D): \" << youngsModulus << endl;\n        list_out << \"Stretching constant: \" << boundary.sconstant << endl;\n        list_out << \"Surface Tension constant: \" << (boundary.sigma_a / dynePerCm_Scalefactor) << endl;\n        list_out << \"Volume Tension constant: \" << (boundary.sigma_v / atmPerNmThird_Scalefactor) << endl;\n        list_out << \"LJ strength: \" << boundary.elj << endl;\n        list_out << \"LJ distance cutoff: \" << boundary.lj_length_mesh_mesh << endl;\n        list_out << \"Rigid geometric constraint: \" << geomConstraint << endl;\n\n        list_out << \"\\n===================\\nElectrostatics\\n===================\\n\";\n        list_out << \"Total charge on membrane: \" << q_strength << endl;\n        list_out << \"Final actual charge on membrane: \" << q_actual << endl;\n        list_out << \"Number of simulated counterions: \" << counterions.size() << endl;\n        list_out << \"Fractional charge occupancy (alpha): \" << alpha << endl;\n        list_out << \"The number of patches is: \" << numPatches << endl;\n        list_out << \"The size of each patch is: \" << fracChargedPatch << endl;\n        list_out << \"The name of the external file used to specify charge patterning is: \" << externalPattern << endl;\n        list_out << \"Salt concentration: \" << conc_out << endl;\n        list_out << \"Debye length: \" << boundary.inv_kappa_out << endl;\n        list_out << \"Bjerrum length: \" << boundary.lB_out << endl;\n\n        list_out << \"\\n===================\\nThermodynamics\\n===================\\n\";\n        list_out << \"Initial Temperature (T): \" << T << endl;\n        list_out << \"Thermostat mass (Q_mesh): \" << mesh_bath[0].Q << endl;\n        list_out << \"Number of thermostats (C): \" << mesh_bath.size() << endl;\n        list_out << \"Timestep (dt): \" << mdremote.timestep << \"  &  Total steps: \" << mdremote.steps << \".\" << endl;\n        list_out << \"Annealing: \" << mdremote.anneal << endl;\n        list_out << \"Anneal frequency: \" << mdremote.annealfreq << endl;\n        list_out << \"Anneal duration: \" << mdremote.annealDuration << endl;\n        list_out << \"Temperature annealing decrement: \" << mdremote.TAnnealFac << endl;\n        list_out << \"Thermostat mass decrement: \" << mdremote.QAnnealFac << endl;\n        list_out << \"Randomness during run: \" << randomFlag << endl;\n        list_out << \"Off-file loaded: \" << offFlag << endl;\n\n        // (NB added) Print the initial state in the movie file, prior to MD:\n        interface_movie(0, boundary.V, counterions, box_halflength);  // NB added.  Note, calls this \"time step -1\" in movie file.\n\n    }\n    // Initiate MD of the boundary/membrane:\n    boundary.dressup(lambda_a, lambda_v);\n    boundary.output_configuration();    // NB added.  More information on the initial state.\n    /*boundary.compute_local_energies(scalefactor);  // Returns 'nan' at the moment as energies... should fix.\n    boundary.compute_local_energies_by_component();\n    if (world.rank() == 0) {\n        rename(\"outfiles/local_electrostatic_E.off\", \"outfiles/local_electrostatic_E_initial.off\");\n        rename(\"outfiles/local_elastic_E.off\", \"outfiles/local_elastic_E_initial.off\");\n        rename(\"outfiles/local_stretching_E.off\", \"outfiles/local_stretching_E_initial.off\");\n        rename(\"outfiles/local_bending_E.off\", \"outfiles/local_bending_E_initial.off\");\n    }*/\n    //MPI Boundary calculation for ions\n    /*\n    unsigned int rangeMesh = boundary.V.size() / world.size() + 1.5;\n    lowerBoundMesh = world.rank() * rangeMesh;\n    upperBoundMesh = (world.rank() + 1) * rangeMesh - 1;\n    extraElementsMesh = world.size() * rangeMesh - boundary.V.size();\n    sizFVecMesh = upperBoundMesh - lowerBoundMesh + 1;\n    if (world.rank() == world.size() - 1) {\n        upperBoundMesh = boundary.V.size() - 1;\n        sizFVecMesh = upperBoundMesh - lowerBoundMesh + 1 + extraElementsMesh;\n    }\n    if (world.size() == 1) {\n        lowerBoundMesh = 0;\n        upperBoundMesh = boundary.V.size() - 1;\n    }\n*/\n    // MPI Boundary calculations for the mesh:\n    unsigned int rangeMesh = (boundary.V.size() + world.size() - 1) / (1.0 * world.size());\n    lowerBoundMesh = world.rank() * rangeMesh;\n    upperBoundMesh = (world.rank() + 1) * rangeMesh - 1;\n    //extraElementsMesh = world.size() * rangeMesh - boundary.V.size();\n    sizFVecMesh = rangeMesh;\n    if (world.rank() == world.size() - 1) {\n        upperBoundMesh = boundary.V.size() - 1;\n    }\n\n    // MPI Boundary calculations for the ions:\n    int rangeIons = (counterions.size() + world.size() - 1) / (1.0 * world.size());\n    lowerBoundIons = world.rank() * rangeIons;\n    upperBoundIons = (world.rank() + 1) * rangeIons - 1;\n    extraElementsIons = world.size() * rangeIons - counterions.size();\n    sizFVecIons = rangeIons;\n    if (world.rank() == world.size() - 1) {\n        upperBoundIons = counterions.size() - 1; // With zero counterions, this is negative, preventing loop evaluation.\n    }\n\n    md_interface(boundary, counterions, mesh_bath, ions_bath, mdremote, geomConstraint, bucklingFlag, constraintForm, scalefactor, box_halflength);\n    boundary.compute_local_energies(scalefactor);\n    boundary.compute_local_energies_by_component();\n\n\n    //newly added by FS on 2021/2/5\n    //condensation input file generation\n\n    double box_halflength_new = pow(((4.0 / 3.0) * 3.1415926 * unit_radius_sphere * unit_radius_sphere * unit_radius_sphere) / packing_fraction, 1.0 / 3.0) / (2.0 * unit_radius_sphere);\n    double qLJ = charge_e / pow(4.0 * pi * epsilon_0 * KB_raw * room_temperature * unit_radius_sphere * pow(10.0, -9), 1.0 / 2.0);\n    cout << \"box radius: \" << box_halflength_new << endl;\n    cout << \"qLJ: \" << qLJ << endl;\n    \n    boundary.assign_dual_initial();\n    boundary.reassign_charges();\n    cout << \"Finish assigning duals and recomputing all the charges\" << endl;\n    boundary.put_counterions(q_actual, unit_radius_sphere, counterion_diameter, box_halflength_new, counterions, counterion_valency);\n    cout << \"Finish putting ions\" << endl;\n    create_input_coordinate(boundary.V, boundary.Dual, counterions, box_halflength_new, qLJ, 0.6/unit_radius_sphere);\n    cout << \"Finish generating condensation input file \" << endl;\n\n    return 0;\n}\n// End of main\n\n", "meta": {"hexsha": "f365f9584b9135bfe9f9becd8eed11f0c237f32b", "size": 30964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "supunkamburugamuve/np-shape-lab", "max_stars_repo_head_hexsha": "913b3f7f9fecb2c651ac790eacf0d11e78338721", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "supunkamburugamuve/np-shape-lab", "max_issues_repo_head_hexsha": "913b3f7f9fecb2c651ac790eacf0d11e78338721", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-08-02T16:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-24T17:09:03.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "supunkamburugamuve/np-shape-lab", "max_forks_repo_head_hexsha": "913b3f7f9fecb2c651ac790eacf0d11e78338721", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T16:44:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-19T22:27:51.000Z", "avg_line_length": 62.9349593496, "max_line_length": 821, "alphanum_fraction": 0.649205529, "num_tokens": 7783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.022286182982299584, "lm_q1q2_score": 0.01001524681126724}}
{"text": "//\n// Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.\n// Copyright (c) 2015-2017, University of Bremen\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// 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#ifndef __MAPS_LINESEGMENT_HPP__\n#define __MAPS_LINESEGMENT_HPP__\n\n/** Boost serialization **/\n#include <boost/serialization/access.hpp>\n#include <boost/serialization/nvp.hpp>\n\n/** Eigen **/\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n/** Base types **/\n#include <base/Float.hpp>\n\n/** Std **/\n#include <math.h>\n#include <utility>\n\nnamespace maps { namespace geometric\n{\n    /**@brief LineSegment class IEEE 1873 standard\n     * adapted to lines in D-space.\n     * T type (e.g. float or double)\n     * D int specification for the dimensional space\n     * **/\n    template <typename T, int D>\n    class LineSegment: public Eigen::ParametrizedLine<T, D>\n    {\n    public:\n        typedef typename Eigen::ParametrizedLine<T, D>::VectorType VectorType;\n\n    private:\n        /**  Origin (psi_a) and End (psi_b) point of the line \n         * m_origin form the parent class is the psi_a **/\n        VectorType _psi_b;\n\n    public:\n        inline LineSegment() {}\n\n        LineSegment(const LineSegment<T, D>& other)\n            : Eigen::ParametrizedLine<T, D>(other.origin(), other.direction()),\n            _psi_b(other.psi_b())\n        {}\n\n        LineSegment(const VectorType &psi_a, const VectorType &psi_b)\n            : Eigen::ParametrizedLine<T, D>(psi_a, (psi_b-psi_a).normalized()),\n            _psi_b(psi_b)\n        {}\n\n        inline const VectorType& psi_a() const\n        {\n            return const_cast<LineSegment<T, D>& >(*this).origin();\n        }\n\n        inline VectorType& psi_a()\n        {\n            return static_cast<VectorType&>(Eigen::ParametrizedLine<T, D>::origin());\n        }\n\n\n        inline const VectorType& psi_b() const\n        {\n            return const_cast<VectorType& >(_psi_b);\n        }\n\n        void psi_b(const VectorType &other_psi_b)\n        {\n            this->_psi_b = other_psi_b;\n            this->direction() =  (this->_psi_b - this->origin()).normalized();\n            return;\n        }\n\n        inline const VectorType& direction() const\n        {\n            return const_cast<LineSegment<T, D>& >(*this).direction();\n        }\n\n        inline VectorType& direction()\n        {\n            return static_cast<VectorType&>(Eigen::ParametrizedLine<T, D>::direction());\n        }\n\n\n        /** Perpendicular distance from the origin of the local coordinate\n         * system of the map to the line segment. Unit is meter. **/\n        inline T rho() const\n        {\n            /** The distance of zero to its projection onto the line **/\n            T dist = this->distance(VectorType::Zero());\n\n            /** In case the projected distance is zero the line is passing by\n             * the origin of the local coordinate system**/\n            if (dist == 0.00)\n            {\n                dist += this->origin().norm();\n            }\n\n            return dist;\n        }\n\n        /** Angle in radians [0, 2*pi] for the orientation of a vector\n         * representing the perpendicular distance to the line segment, measured\n         * counterclockwise from horizontal x-axis of the local coordinate\n         * system of the map.**/\n        T alpha() const\n        {\n\n            /** The slope is given when the dimension D equal to 2**/\n            if (D == 2)\n            {\n                /** Normally Alpha is the angle given by the slope m = tan(alpha) **/\n                T alpha = atan2(this->direction()[1], this->direction()[0]);\n\n                /** Convert alpha between [0, 2pi] **/\n                alpha = (alpha >= 0 ? alpha : (2.0*M_PI + alpha));\n\n                /** IEEE Std 1873-2015 request alpha as the perpendicular to it\n                 * It means the angle of the rho_axis wrt to the x-axis of the\n                 * local coordinate frame **/\n                alpha += M_PI/2.0;\n\n                /** Convert between [0, 2*pi] **/\n                return (alpha > 2.0*M_PI ? alpha - (2.0*M_PI): alpha);\n            }\n            return base::NaN<T>();\n        }\n\n    protected:\n        /** Grants access to boost serialization */\n        friend class boost::serialization::access;\n\n        /** Serializes the members of this class*/\n        template <typename Archive>\n        void serialize(Archive &ar, const unsigned int version)\n        {\n            ar & BOOST_SERIALIZATION_NVP(this->m_origin);\n            ar & BOOST_SERIALIZATION_NVP(this->m_direction);\n            ar & BOOST_SERIALIZATION_NVP(this->_psi_b);\n        }\n\n    };\n\n    typedef LineSegment<double, 2> LineSegment2d;\n    typedef LineSegment<double, 3> LineSegment3d;\n    typedef LineSegment<float, 2> LineSegment2f;\n    typedef LineSegment<float, 3> LineSegment3f;\n}}\n#endif /* __MAPS_LINESEGMENT_HPP__ */\n", "meta": {"hexsha": "e68e0f2382c9c2dd3c82ad5d4407b9fd337037e5", "size": 6118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometric/LineSegment.hpp", "max_stars_repo_name": "JanWehrmann/slam-maps", "max_stars_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T05:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T02:34:18.000Z", "max_issues_repo_path": "src/geometric/LineSegment.hpp", "max_issues_repo_name": "JanWehrmann/slam-maps", "max_issues_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T18:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T15:20:31.000Z", "max_forks_repo_path": "src/geometric/LineSegment.hpp", "max_forks_repo_name": "JanWehrmann/slam-maps", "max_forks_repo_head_hexsha": "c03117e9d66ec312723ad700baabc0af04f36d70", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-03-10T10:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T05:50:10.000Z", "avg_line_length": 34.96, "max_line_length": 88, "alphanum_fraction": 0.6185027787, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.028436031192289504, "lm_q1q2_score": 0.010015220860293739}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <cstring>\n#include <cmath>\n#include <fstream>\n#include <string>\n#include <regex>\n#include <iterator>\n#include <python3.7m/Python.h>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/implicit.hpp>\n#include <boost/python/extract.hpp>\n#include <arpa/inet.h>\n#include <netinet/in.h>\n\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\ninline void destroyManagerCObject(PyObject *obj)\n{\n    double *b = reinterpret_cast<double *>(PyCapsule_GetPointer(obj, NULL));\n    if (b)\n    {\n        delete[] b;\n    }\n}\n\nstruct AdvParser\n{\n    bool checkBase = true;\n    bool checkNodes = true;\n    bool shapeCreated = true;\n    int xnodes, ynodes, znodes;\n    double xbase, ybase, zbase;\n    AdvParser()\n    {\n        xnodes = 0;\n        ynodes = 0;\n        znodes = 0;\n\n        xbase = 0.0;\n        ybase = 0.0;\n        zbase = 0.0;\n    };\n\n    void setXnodes(int val) { this->xnodes = val; }\n    void setYnodes(int val) { this->ynodes = val; }\n    void setZnodes(int val) { this->znodes = val; }\n    void setXbase(int val) { this->xbase = val; }\n    void setYbase(int val) { this->ybase = val; }\n    void setZbase(int val) { this->zbase = val; }\n    int getXnodes() { return xnodes; }\n    int getYnodes() { return ynodes; }\n    int getZnodes() { return znodes; }\n    double getXbase() { return xbase; }\n    double getYbase() { return ybase; }\n    double getZbase() { return zbase; }\n\n    np::ndarray getOmfToList(std::string path)\n    {\n        // is a text file\n        std::ifstream miffile;\n        miffile.open(path, std::ios::out);\n        int buffer_size = getMifHeader(miffile);\n\n        int num_vectors = xnodes * ynodes * znodes;\n        double *fut_ndarray = (double *)(malloc(sizeof(double) * num_vectors * 3));\n        int i = 0;\n        if (miffile.is_open())\n        {\n            std::string line;\n            while (std::getline(miffile, line))\n            {\n                std::istringstream iss(line);\n                if (line[0] == '#')\n                    continue;\n                else\n                {\n                    double x, y, z;\n                    if (!(iss >> x >> y >> z))\n                        break;\n                    fut_ndarray[i + 0] = x;\n                    fut_ndarray[i + 1] = y;\n                    fut_ndarray[i + 2] = z;\n                    i += 3;\n                }\n            }\n        }\n        miffile.close();\n        boost::python::numpy::dtype dt1 = boost::python::numpy::dtype::get_builtin<double>();\n        boost::python::tuple shape = boost::python::make_tuple(num_vectors, 3);\n        boost::python::tuple stride = boost::python::make_tuple(3 * sizeof(double), sizeof(double));\n        boost::python::numpy::ndarray vectorData = boost::python::numpy::from_data(fut_ndarray,\n                                                                                   dt1,\n                                                                                   shape,\n                                                                                   stride,\n                                                                                   boost::python::object());\n        // last entry is object owner\n        return vectorData;\n    }\n\n    int getMifHeader(std::ifstream &miffile)\n    {\n        std::string line;\n        int buffer_size = 0;\n\n        std::string node_reg(\"# xnodes:\");\n        std::string base_reg(\"# xbase:\");\n\n        // we have to change strategy here\n        std::string data_text(\"# Begin: Data Text\");\n        if (miffile.is_open())\n        {\n            while (std::getline(miffile, line))\n            {\n                if (line.at(0) == '#')\n                {\n                    if (line == \"# Begin: Data Binary 8\")\n                    {\n                        buffer_size = 8;\n                        break;\n                    }\n                    else if (line == \"# Begin: Data Binary 4\")\n                    {\n                        buffer_size = 4;\n                        break;\n                    }\n                    else if (data_text.compare(line.substr(0, data_text.length())) == 0)\n                    {\n                        buffer_size = 1;\n                        break;\n                    }\n\n                    if (checkNodes && line.substr(0, node_reg.length()) == node_reg)\n                    {\n\n                        if (node_reg.at(2) == 'x')\n                        {\n                            xnodes = std::stoi(line.substr(node_reg.length(), line.length()));\n                            node_reg.at(2) = 'y';\n                        }\n                        else if (node_reg.at(2) == 'y')\n                        {\n                            ynodes = std::stoi(line.substr(node_reg.length(), line.length()));\n                            node_reg.at(2) = 'z';\n                        }\n                        else\n                        {\n                            znodes = std::stoi(line.substr(node_reg.length(), line.length()));\n                            checkNodes = false;\n                        }\n                    }\n                    if (checkBase && line.substr(0, base_reg.length()) == base_reg)\n                    {\n\n                        if (base_reg.at(2) == 'x')\n                        {\n                            xbase = std::stod(line.substr(base_reg.length(), line.length()));\n                            base_reg.at(2) = 'y';\n                        }\n                        else if (base_reg.at(2) == 'y')\n                        {\n                            ybase = std::stod(line.substr(base_reg.length(), line.length()));\n                            base_reg.at(2) = 'z';\n                        }\n                        else\n                        {\n                            zbase = std::stod(line.substr(base_reg.length(), line.length()));\n                            checkBase = false;\n                        }\n                    }\n                }\n                else\n                    break;\n            }\n            if (buffer_size <= 0)\n            {\n                throw std::runtime_error(\"Invalid buffer size\");\n            }\n            char IEEE_BUF[buffer_size + 1];\n\n            miffile.read(IEEE_BUF, buffer_size);\n            if (buffer_size == 4)\n            {\n                float IEEE_val;\n                float IEEE_VALIDATION = 1234567.0;\n\n                std::memcpy(&IEEE_val, IEEE_BUF, sizeof(float));\n                if (IEEE_val != IEEE_VALIDATION)\n                {\n                    printf(\"%f\\n\", IEEE_val);\n                    throw std::runtime_error(\"IEEE value not consistent\");\n                }\n            }\n            else if (buffer_size == 8)\n            {\n                double IEEE_val;\n                double IEEE_VALIDATION = 123456789012345.0;\n                std::memcpy(&IEEE_val, IEEE_BUF, sizeof(double));\n\n                if (IEEE_val != IEEE_VALIDATION)\n                {\n                    printf(\"%f\\n\", IEEE_val);\n                    throw std::runtime_error(\"IEEE value not consistent\");\n                }\n            }\n            else if (buffer_size == 1)\n            {\n                // this is a text file\n                // actaully I don't know what I should do here\n            }\n            else\n            {\n                throw std::runtime_error(\"Unspecified or invalid buffer size for binary input data\");\n            }\n\n            return buffer_size;\n        }\n        else\n        {\n            throw std::runtime_error(\"Invalid mif file\");\n        }\n        return 0;\n    }\n\n    void matrix_vector_mul(double mat[3][3], double vec[3])\n    {\n        // only 3 x 1, inplace\n        double c[3] = {vec[0], vec[1], vec[2]};\n        vec[0] = mat[0][0] * c[0] + mat[0][1] * c[1] + mat[0][2] * c[2];\n        vec[1] = mat[1][0] * c[0] + mat[1][1] * c[1] + mat[1][2] * c[2];\n        vec[2] = mat[2][0] * c[0] + mat[2][1] * c[1] + mat[2][2] * c[2];\n    }\n\n    void matrix_vector_cpy(double mat[3][3], double c[3], double vec[3])\n    {\n        // only 3 x 1, not inplace\n        vec[0] = mat[0][0] * c[0] + mat[0][1] * c[1] + mat[0][2] * c[2];\n        vec[1] = mat[1][0] * c[0] + mat[1][1] * c[1] + mat[1][2] * c[2];\n        vec[2] = mat[2][0] * c[0] + mat[2][1] * c[1] + mat[2][2] * c[2];\n    }\n\n    void a_cross_b(double a[3], double b[3], double c[3])\n    {\n        c[0] = a[1] * b[2] - a[2] * b[1];\n        c[1] = a[2] * b[0] - a[0] * b[2];\n        c[2] = a[0] * b[1] - a[1] * b[0];\n    }\n\n    void generateVBO(double *vbo,\n                     int *offset,\n                     int *normal_offset,\n                     double position[3],\n                     double vector[3], // from omf\n                     double color[3],  // from omf\n                     double t_rotation[3][3],\n                     double height,\n                     double radius,\n                     int resolution)\n    {\n        double height_operator[3] = {0, 0, height * 1.5};\n        double mag = sqrt(pow(vector[0], 2) +\n                          pow(vector[1], 2) +\n                          pow(vector[2], 2));\n        double phi = acos(vector[2] / mag);         // z rot\n        double theta = atan2(vector[1], vector[0]); // y rot\n        double ct = cos(theta);\n        double st = sin(theta);\n        double cp = cos(phi);\n        double sp = sin(phi);\n        double rotation_matrix[3][3] = {\n            {ct, -st * cp, st * sp},\n            {st, cp * ct, -sp * ct},\n            {0, sp, cp}};\n        double origin_base[3], cpy[3];\n        double cyllinder_co_rot[3] = {radius, radius, 0};\n        double cone_co_rot[3] = {2 * radius, 2 * radius, 0};\n        std::memcpy(origin_base, position, sizeof(double) * 3);\n        double n[3], u[3], v[3];\n        int prev_off = 36;\n        for (int i = 0; i < (resolution - 1); i++)\n        {\n            // colors first\n            std::memcpy(vbo + *offset, color, sizeof(double) * 3);\n            std::memcpy(vbo + *offset + 9, color, sizeof(double) * 3);\n            std::memcpy(vbo + *offset + 18, color, sizeof(double) * 3);\n            std::memcpy(vbo + *offset + 27, color, sizeof(double) * 3);\n            // bottom triangle - cyllinder\n            matrix_vector_cpy(rotation_matrix, cyllinder_co_rot, cpy);\n            vbo[*offset + 3] = origin_base[0] + cpy[0];\n            vbo[*offset + 4] = origin_base[1] + cpy[1];\n            vbo[*offset + 5] = origin_base[2] + cpy[2];\n\n            // bottom triangle - cone\n            cone_co_rot[2] += height;\n            matrix_vector_cpy(rotation_matrix, cone_co_rot, cpy);\n            vbo[*offset + 6] = origin_base[0] + cpy[0];\n            vbo[*offset + 7] = origin_base[1] + cpy[1];\n            vbo[*offset + 8] = origin_base[2] + cpy[2];\n\n            // top triangle - cyllinder\n            cyllinder_co_rot[2] += height;\n            matrix_vector_cpy(rotation_matrix, cyllinder_co_rot, cpy);\n            vbo[*offset + 21] = origin_base[0] + cpy[0];\n            vbo[*offset + 22] = origin_base[1] + cpy[1];\n            vbo[*offset + 23] = origin_base[2] + cpy[2];\n\n            // top triangle - cone\n            matrix_vector_mul(rotation_matrix, height_operator);\n            vbo[*offset + 24] = origin_base[0] + height_operator[0];\n            vbo[*offset + 25] = origin_base[1] + height_operator[1];\n            vbo[*offset + 26] = origin_base[2] + height_operator[2];\n            height_operator[0] = 0;\n            height_operator[1] = 0;\n            height_operator[2] = 1.5 * height;\n            cyllinder_co_rot[2] -= height;\n            cone_co_rot[2] -= height;\n\n            matrix_vector_mul(t_rotation, cyllinder_co_rot);\n            matrix_vector_mul(t_rotation, cone_co_rot);\n\n            if (i > 0)\n            {\n                // firstly compute the later indices for vertex\n                // because we will use them to compute the normals\n\n                u[0] = vbo[*offset + 3] - vbo[*offset - prev_off + 3];\n                u[1] = vbo[*offset + 4] - vbo[*offset - prev_off + 4];\n                u[2] = vbo[*offset + 5] - vbo[*offset - prev_off + 5];\n\n                v[0] = vbo[*offset - prev_off + 21] - vbo[*offset - prev_off + 3];\n                v[1] = vbo[*offset - prev_off + 22] - vbo[*offset - prev_off + 4];\n                v[2] = vbo[*offset - prev_off + 23] - vbo[*offset - prev_off + 5];\n\n                // cross product\n                a_cross_b(u, v, n);\n                vbo[*normal_offset + 0] = n[0];\n                vbo[*normal_offset + 1] = n[1];\n                vbo[*normal_offset + 2] = n[2];\n\n                vbo[*normal_offset + 18] = n[0];\n                vbo[*normal_offset + 19] = n[1];\n                vbo[*normal_offset + 20] = n[2];\n                // normals to the cone triangle\n                u[0] = vbo[*offset + 6] - vbo[*offset - prev_off + 6];\n                u[1] = vbo[*offset + 7] - vbo[*offset - prev_off + 7];\n                u[2] = vbo[*offset + 8] - vbo[*offset - prev_off + 8];\n\n                v[0] = vbo[*offset - prev_off + 24] - vbo[*offset - prev_off + 6];\n                v[1] = vbo[*offset - prev_off + 25] - vbo[*offset - prev_off + 7];\n                v[2] = vbo[*offset - prev_off + 26] - vbo[*offset - prev_off + 8];\n\n                // cross product\n                a_cross_b(u, v, n);\n                vbo[*normal_offset + 3] = n[0];\n                vbo[*normal_offset + 4] = n[1];\n                vbo[*normal_offset + 5] = n[2];\n\n                vbo[*normal_offset + 21] = n[0];\n                vbo[*normal_offset + 22] = n[1];\n                vbo[*normal_offset + 23] = n[2];\n                *normal_offset += 18;\n                *normal_offset += 18;\n            }\n            *offset += prev_off;\n        }\n        // colors first\n        std::memcpy(vbo + *offset, color, sizeof(double) * 3);\n        std::memcpy(vbo + *offset + 9, color, sizeof(double) * 3);\n        std::memcpy(vbo + *offset + 18, color, sizeof(double) * 3);\n        std::memcpy(vbo + *offset + 27, color, sizeof(double) * 3);\n        // reset rotational vectors to their defaults\n        cyllinder_co_rot[0] = radius;\n        cyllinder_co_rot[1] = radius;\n        cyllinder_co_rot[2] = 0;\n        matrix_vector_mul(rotation_matrix, cyllinder_co_rot);\n        vbo[*offset + 3] = origin_base[0] + cyllinder_co_rot[0];\n        vbo[*offset + 4] = origin_base[1] + cyllinder_co_rot[1];\n        vbo[*offset + 5] = origin_base[2] + cyllinder_co_rot[2];\n\n        cone_co_rot[0] = 2 * radius;\n        cone_co_rot[1] = 2 * radius;\n        cone_co_rot[2] = height;\n        matrix_vector_mul(rotation_matrix, cone_co_rot);\n        vbo[*offset + 6] = origin_base[0] + cone_co_rot[0];\n        vbo[*offset + 7] = origin_base[1] + cone_co_rot[1];\n        vbo[*offset + 8] = origin_base[2] + cone_co_rot[2];\n\n        cyllinder_co_rot[0] = radius;\n        cyllinder_co_rot[1] = radius;\n        cyllinder_co_rot[2] += height;\n        matrix_vector_mul(rotation_matrix, cyllinder_co_rot);\n        vbo[*offset + 21] = origin_base[0] + cyllinder_co_rot[0];\n        vbo[*offset + 22] = origin_base[1] + cyllinder_co_rot[1];\n        vbo[*offset + 23] = origin_base[2] + cyllinder_co_rot[2];\n\n        height_operator[0] = 0;\n        height_operator[1] = 0;\n        height_operator[2] = 1.5 * height;\n        matrix_vector_mul(rotation_matrix, height_operator);\n        vbo[*offset + 24] = origin_base[0] + height_operator[0];\n        vbo[*offset + 25] = origin_base[1] + height_operator[1];\n        vbo[*offset + 26] = origin_base[2] + height_operator[2];\n\n        // normals to the cyllinder triangle\n        u[0] = vbo[*offset + 3] - vbo[*offset - prev_off + 3];\n        u[1] = vbo[*offset + 4] - vbo[*offset - prev_off + 4];\n        u[2] = vbo[*offset + 5] - vbo[*offset - prev_off + 5];\n\n        v[0] = vbo[*offset - prev_off + 21] - vbo[*offset - prev_off + 3];\n        v[1] = vbo[*offset - prev_off + 22] - vbo[*offset - prev_off + 4];\n        v[2] = vbo[*offset - prev_off + 23] - vbo[*offset - prev_off + 5];\n\n        // cross product\n        a_cross_b(u, v, n);\n        vbo[*normal_offset + 0] = n[0];\n        vbo[*normal_offset + 1] = n[1];\n        vbo[*normal_offset + 2] = n[2];\n\n        vbo[*normal_offset + 18] = n[0];\n        vbo[*normal_offset + 19] = n[1];\n        vbo[*normal_offset + 20] = n[2];\n\n        // normals to the cone triangle\n        u[0] = vbo[*offset + 6] - vbo[*offset - prev_off + 6];\n        u[1] = vbo[*offset + 7] - vbo[*offset - prev_off + 7];\n        u[2] = vbo[*offset + 8] - vbo[*offset - prev_off + 8];\n\n        v[0] = vbo[*offset - prev_off + 24] - vbo[*offset - prev_off + 6];\n        v[1] = vbo[*offset - prev_off + 25] - vbo[*offset - prev_off + 7];\n        v[2] = vbo[*offset - prev_off + 26] - vbo[*offset - prev_off + 8];\n\n        // cross product\n        a_cross_b(u, v, n);\n        vbo[*normal_offset + 3] = n[0];\n        vbo[*normal_offset + 4] = n[1];\n        vbo[*normal_offset + 5] = n[2];\n\n        vbo[*normal_offset + 21] = n[0];\n        vbo[*normal_offset + 22] = n[1];\n        vbo[*normal_offset + 23] = n[2];\n        *normal_offset += 18;\n        *normal_offset += 18;\n\n        // LAST NORMALS MUST CATCH UP and are the same as previous\n        vbo[*normal_offset + 0] = n[0];\n        vbo[*normal_offset + 1] = n[1];\n        vbo[*normal_offset + 2] = n[2];\n        vbo[*normal_offset + 3] = n[0];\n        vbo[*normal_offset + 4] = n[1];\n        vbo[*normal_offset + 5] = n[2];\n        *normal_offset += 18;\n        vbo[*normal_offset + 0] = n[0];\n        vbo[*normal_offset + 1] = n[1];\n        vbo[*normal_offset + 2] = n[2];\n        vbo[*normal_offset + 3] = n[0];\n        vbo[*normal_offset + 4] = n[1];\n        vbo[*normal_offset + 5] = n[2];\n        *normal_offset += 18;\n        *offset += prev_off;\n    }\n\n    void generateCubes2(double *sh, double position[3], double dimensions[3], int current_pos)\n    {\n        double arr[144] = {\n            //TOP FACE\n            position[0] + dimensions[0], position[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1] + dimensions[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0] + dimensions[0], position[1] + dimensions[1], position[2] + dimensions[2],\n            0, 0, 0,\n            //BOTTOM FACE\n            position[0] + dimensions[0], position[1], position[2],\n            0, 0, 0,\n            position[0], position[1], position[2],\n            0, 0, 0,\n            position[0], position[1] + dimensions[1], position[2],\n            0, 0, 0,\n            position[0] + dimensions[0], position[1] + dimensions[1], position[2],\n            0, 0, 0,\n            //FRONT FACE\n            position[0] + dimensions[0], position[1] + dimensions[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1] + dimensions[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1] + dimensions[1], position[2],\n            0, 0, 0,\n            position[0] + dimensions[0], position[1] + dimensions[1], position[2],\n            0, 0, 0,\n            //BACK FACE\n            position[0] + dimensions[0], position[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1], position[2],\n            0, 0, 0,\n            position[0] + dimensions[0], position[1], position[2],\n            0, 0, 0,\n            //RIGHT FACE\n            position[0] + dimensions[0], position[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0] + dimensions[0], position[1] + dimensions[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0] + dimensions[0], position[1] + dimensions[1], position[2],\n            0, 0, 0,\n            position[0] + dimensions[0], position[1], position[2],\n            0, 0, 0,\n            //LEFT FACE\n            position[0], position[1] + dimensions[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1], position[2] + dimensions[2],\n            0, 0, 0,\n            position[0], position[1], position[2],\n            0, 0, 0,\n            position[0], position[1] + dimensions[1], position[2],\n            0, 0, 0};\n\n        // normals here\n        double ux, uy, uz;\n        double vx, vy, vz;\n        int offset = 0;\n        for (int i = 0; i < 6; i++)\n        {\n            ux = arr[offset + 0] - arr[offset + 6]; // first vertex\n            uy = arr[offset + 1] - arr[offset + 7];\n            uz = arr[offset + 2] - arr[offset + 8];\n\n            vx = arr[offset + 0] - arr[offset + 12]; // second vertex\n            vy = arr[offset + 1] - arr[offset + 13];\n            vz = arr[offset + 2] - arr[offset + 14];\n\n            // cross product\n            for (int j = 0; j < 4; j++)\n            {\n                arr[offset + 3 + j * 6 + 0] = uy * vz - vy * uz;\n                arr[offset + 3 + j * 6 + 1] = ux * uz - vx - vz;\n                arr[offset + 3 + j * 6 + 2] = ux * vy - uy * vx;\n            }\n            offset += 24;\n        }\n        std::memcpy(sh + current_pos, arr, sizeof(double) * 144);\n    }\n\n    np::ndarray generateIndices(int N, int index_required)\n    {\n        int start_index = 0;\n        int *indices = (int *)malloc(sizeof(int) * (3 * (index_required - 2) * N));\n        for (int n = 0; n < N; n++)\n        {\n            start_index = n * index_required + 3;\n            for (int i = 0; i < (index_required - 2); i++)\n            {\n                indices[n * (index_required - 2) * 3 + i * 3 + 0] = start_index + i - 3;\n                indices[n * (index_required - 2) * 3 + i * 3 + 1] = start_index + i - 2;\n                indices[n * (index_required - 2) * 3 + i * 3 + 2] = start_index + i - 1;\n            }\n        }\n        np::dtype dt = np::dtype::get_builtin<int>();\n        p::tuple shape = p::make_tuple(3 * (index_required - 2) * N);\n        p::tuple stride = p::make_tuple(sizeof(int));\n        p::handle<> h(::PyCapsule_New((void *)indices,\n                                      NULL,\n                                      (PyCapsule_Destructor)&destroyManagerCObject));\n        return np::from_data(indices,\n                             dt,\n                             shape,\n                             stride,\n                             p::object(h));\n    }\n    np::ndarray getCubeOutline(int xn, int yn, int zn,\n                               double xb, double yb, double zb,\n                               int sampling,\n                               int start_layer, int stop_layer)\n    {\n        /*\n        Cube MIF OUTLINE \n        2 VBOs because the geometry is constant\n        1) Geometry + Normal VBO \n        2) Color VBO  \n        */\n        int per_vertex = 144;\n        // per_vertex = 72;\n        double *sh = (double *)(malloc(sizeof(double) * xn * yn * zn * per_vertex));\n        double dimensions[3] = {xb * sampling, yb * sampling, zb};\n        int current_pos = 0;\n        for (int z = start_layer; z < stop_layer; z += 1)\n        {\n            for (int y = 0; y < ynodes; y += sampling)\n            {\n                for (int x = 0; x < xnodes; x += sampling)\n                {\n                    double position[3] = {xb * (x % xn) - xn * xb / 2,\n                                          yb * (y % yn) - yn * yb / 2,\n                                          zb * (z % zn) - zn * zb / 2};\n                    generateCubes2(sh, position, dimensions, current_pos);\n                    current_pos += per_vertex;\n                }\n            }\n        }\n\n        np::dtype dt = np::dtype::get_builtin<double>();\n        p::tuple shape = p::make_tuple(xn * yn * zn * per_vertex);\n        p::tuple stride = p::make_tuple(sizeof(double));\n        p::handle<> h(::PyCapsule_New((void *)sh,\n                                      NULL,\n                                      (PyCapsule_Destructor)&destroyManagerCObject));\n        return np::from_data(sh,\n                             dt,\n                             shape,\n                             stride,\n                             p::object(h));\n    }\n    void getHeader(std::string filepath)\n    {\n        std::ifstream miffile;\n        miffile.open(filepath, std::ios::out | std::ios_base::binary);\n        getMifHeader(miffile);\n        miffile.close();\n    }\n\n    np::ndarray getShapeAsNdarray(double xb, double yb, double zb)\n    {\n        double *sh = (double *)(malloc(sizeof(double) * xnodes * ynodes * znodes * 3));\n        int current_pos = 0;\n        for (int z = 0; z < znodes; z++)\n        {\n            for (int y = 0; y < ynodes; y++)\n            {\n                for (int x = 0; x < xnodes; x++)\n                {\n                    sh[current_pos + 0] = xb * (x % xnodes) - xnodes * xb / 2;\n                    sh[current_pos + 1] = yb * (y % ynodes) - ynodes * yb / 2;\n                    sh[current_pos + 2] = zb * (z % znodes) - znodes * zb / 2;\n                    current_pos += 3;\n                }\n            }\n        }\n        np::dtype dt = np::dtype::get_builtin<double>();\n        p::tuple shape = p::make_tuple(current_pos);\n        p::tuple stride = p::make_tuple(sizeof(double));\n        p::handle<> h(::PyCapsule_New((void *)sh,\n                                      NULL,\n                                      (PyCapsule_Destructor)&destroyManagerCObject));\n        return np::from_data(sh,\n                             dt,\n                             shape,\n                             stride,\n                             p::object(h));\n    }\n\n    np::ndarray getMifAsNdarrayWithColor(std::string path,\n                                         p::list color_vector_l,\n                                         p::list positive_color_l,\n                                         p::list negative_color_l,\n                                         int sampling,\n                                         int start_layer,\n                                         int stop_layer,\n                                         int binary)\n    {\n        double color_vector[3] = {\n            p ::extract<double>(color_vector_l[0]),\n            p ::extract<double>(color_vector_l[1]),\n            p ::extract<double>(color_vector_l[2])};\n        double positive_color[3] = {\n            p ::extract<double>(positive_color_l[0]),\n            p ::extract<double>(positive_color_l[1]),\n            p ::extract<double>(positive_color_l[2])};\n\n        double negative_color[3] = {\n            p ::extract<double>(negative_color_l[0]),\n            p ::extract<double>(negative_color_l[1]),\n            p ::extract<double>(negative_color_l[2])};\n\n        std::ifstream miffile;\n        std::ios::openmode openmod;\n        if (binary)\n        {\n            openmod = std::ios::out | std::ios_base::binary;\n        }\n        else\n        {\n            openmod = std::ios::out;\n        }\n        miffile.open(path, openmod);\n        int buffer_size = getMifHeader(miffile);\n        if (buffer_size == 0)\n        {\n            miffile.close();\n            throw std::runtime_error(\"Invalid mif/ovf file\");\n        }\n\n        int lines = znodes * xnodes * ynodes;\n\n        double *vals;\n        vals = (double *)malloc(sizeof(double) * lines * 3);\n\n        if (buffer_size == 4)\n        {\n            char buffer[buffer_size * lines * 3];\n            miffile.read(buffer, buffer_size * lines * 3);\n            float fvals[lines * 3];\n            std::memcpy(fvals, buffer, lines * 3 * sizeof(float));\n            for (int i = 0; i < lines * 3; i++)\n            {\n                vals[i] = fvals[i];\n            }\n        }\n        else if (buffer_size == 8)\n        {\n            char buffer[buffer_size * lines * 3];\n            miffile.read(buffer, buffer_size * lines * 3);\n            vals = (double *)(buffer);\n        }\n        else if (buffer_size == 1)\n        {\n            int i = 0;\n            if (miffile.is_open())\n            {\n                std::string line;\n                while (std::getline(miffile, line))\n                {\n                    std::istringstream iss(line);\n                    if (line[0] == '#')\n                        continue;\n                    else\n                    {\n                        double x, y, z;\n                        if (!(iss >> x >> y >> z))\n                            break;\n                        vals[i + 0] = x;\n                        vals[i + 1] = y;\n                        vals[i + 2] = z;\n                        i += 3;\n                    }\n                }\n            }\n        }\n        miffile.close();\n\n        int inflate = 24; // 24 vetrtivesd in a cube\n\n        double *fut_ndarray = (double *)(malloc(sizeof(double) * znodes * xnodes * ynodes * 3 * inflate));\n        double mag, dot;\n        double *array_to_cpy = (double *)(malloc(sizeof(double) * 3));\n        int offset = 0;\n        int index = 0;\n\n        for (int z = start_layer; z < stop_layer; z += 1)\n        {\n            for (int y = 0; y < ynodes; y += sampling)\n            {\n                for (int x = 0; x < xnodes; x += sampling)\n                {\n                    index = 3 * (x + xnodes * y + xnodes * ynodes * z);\n                    mag = sqrt(pow(vals[index + 0], 2) +\n                               pow(vals[index + 1], 2) +\n                               pow(vals[index + 2], 2));\n                    if (mag != 0.0)\n                    {\n                        dot = (vals[index + 0] / mag) * color_vector[0] +\n                              (vals[index + 1] / mag) * color_vector[1] +\n                              (vals[index + 2] / mag) * color_vector[2];\n\n                        if (dot > 0)\n                        {\n                            array_to_cpy[0] = positive_color[0] * dot + (1.0 - dot);\n                            array_to_cpy[1] = positive_color[1] * dot + (1.0 - dot);\n                            array_to_cpy[2] = positive_color[2] * dot + (1.0 - dot);\n                        }\n                        else\n                        {\n                            dot *= -1;\n\n                            array_to_cpy[0] = negative_color[0] * dot + (1.0 - dot);\n                            array_to_cpy[1] = negative_color[1] * dot + (1.0 - dot);\n                            array_to_cpy[2] = negative_color[2] * dot + (1.0 - dot);\n                        }\n                    }\n                    else\n                    {\n                        array_to_cpy[0] = 0.0;\n                        array_to_cpy[1] = 0.0;\n                        array_to_cpy[2] = 0.0;\n                    }\n\n                    for (int inf = 0; inf < inflate; inf++)\n                    {\n                        std::memcpy(fut_ndarray + offset, array_to_cpy, sizeof(double) * 3);\n                        offset += 3;\n                    }\n                }\n            }\n        }\n\n        np::dtype dt = np::dtype::get_builtin<double>();\n        p::tuple shape = p::make_tuple(offset);\n        p::tuple stride = p::make_tuple(sizeof(double));\n        p::handle<> h(::PyCapsule_New((void *)fut_ndarray,\n                                      NULL,\n                                      (PyCapsule_Destructor)&destroyManagerCObject));\n        return np::from_data(fut_ndarray,\n                             dt,\n                             shape,\n                             stride,\n                             p::object(h));\n    }\n\n    np::ndarray getMifVBO(std::string path,\n                          int resolution,\n                          p::list color_vector_l,\n                          p::list positive_color_l,\n                          p::list negative_color_l,\n                          int sampling,\n                          double height,\n                          double radius,\n                          int start_layer,\n                          int stop_layer,\n                          int xscaler,\n                          int yscaler,\n                          int zscaler,\n                          int binary)\n    {\n        if (start_layer < 0 || start_layer > stop_layer)\n        {\n            throw std::invalid_argument(\"Start layer cannot be smaller than stop layer\");\n        }\n        if (stop_layer > znodes)\n        {\n            throw std::invalid_argument(\"Stop layer too large\");\n        }\n        double color_vector[3] = {\n            p ::extract<double>(color_vector_l[0]),\n            p ::extract<double>(color_vector_l[1]),\n            p ::extract<double>(color_vector_l[2])};\n        double positive_color[3] = {\n            p ::extract<double>(positive_color_l[0]),\n            p ::extract<double>(positive_color_l[1]),\n            p ::extract<double>(positive_color_l[2])};\n\n        double negative_color[3] = {\n            p ::extract<double>(negative_color_l[0]),\n            p ::extract<double>(negative_color_l[1]),\n            p ::extract<double>(negative_color_l[2])};\n\n        std::ifstream miffile;\n        std::ios::openmode openmod;\n        if (binary)\n        {\n            openmod = std::ios::out | std::ios_base::binary;\n        }\n        else\n        {\n            openmod = std::ios::out;\n        }\n        miffile.open(path, openmod);\n        int buffer_size = getMifHeader(miffile);\n        if (buffer_size == 0)\n        {\n            miffile.close();\n            throw std::runtime_error(\"Invalid mif/ovf file\");\n        }\n\n        int lines = znodes * xnodes * ynodes;\n        double *vals;\n        vals = (double *)malloc(sizeof(double) * lines * 3);\n        if (buffer_size == 4)\n        {\n            char buffer[buffer_size * lines * 3];\n            miffile.read(buffer, buffer_size * lines * 3);\n            float fvals[lines * 3];\n            std::memcpy(fvals, buffer, lines * 3 * sizeof(float));\n            for (int i = 0; i < lines * 3; i++)\n            {\n                vals[i] = fvals[i];\n            }\n        }\n        else if (buffer_size == 8)\n        {\n            char buffer[buffer_size * lines * 3];\n            miffile.read(buffer, buffer_size * lines * 3);\n            // research why this casting with memcpy causes SIGSEV\n            // std::memcpy(vals, buffer, lines * 3 * sizeof(double));\n            vals = (double *)(buffer);\n        }\n        else if (buffer_size == 1)\n        {\n            int i = 0;\n            if (miffile.is_open())\n            {\n                std::string line;\n                while (std::getline(miffile, line))\n                {\n                    std::istringstream iss(line);\n                    if (line[0] == '#')\n                        continue;\n                    else\n                    {\n                        double x, y, z;\n                        if (!(iss >> x >> y >> z))\n                            break;\n                        vals[i + 0] = x;\n                        vals[i + 1] = y;\n                        vals[i + 2] = z;\n                        i += 3;\n                    }\n                }\n            }\n        }\n        miffile.close();\n\n        int size = xnodes * ynodes * znodes * resolution * 10 * 3;\n        double *fut_ndarray = (double *)(malloc(sizeof(double) * size));\n        // double fut_ndarray[size];\n        if (fut_ndarray == NULL)\n        {\n            throw std::runtime_error(\"Failed to allocate memory for a large array\");\n        }\n        double pos[3], vec[3], col[3];\n        double mag, dot;\n        int offset = 0;\n        int index = 0;\n        int normal_offset = 12;\n\n        double theta = 2 * M_PI / resolution;\n        double c = cos(theta);\n        double s = sin(theta);\n        double t_rotation[3][3] = {\n            {c, -s, 0},\n            {s, c, 0},\n            {0, 0, 1}};\n\n        double xb = xscaler * 1e9 * xbase / sampling;\n        double yb = yscaler * 1e9 * ybase / sampling;\n        double zb = zscaler * 1e9 * zbase / sampling;\n\n        double xoffset = xnodes * xb / 2;\n        double yoffset = ynodes * yb / 2;\n        double zoffset = znodes * zb / 2;\n        for (int z = start_layer; z < stop_layer; z += 1)\n        {\n            for (int y = 0; y < ynodes; y += sampling)\n            {\n                for (int x = 0; x < xnodes; x += sampling)\n                {\n                    index = 3 * (x + xnodes * y + xnodes * ynodes * z);\n                    mag = sqrt(pow(vals[index + 0], 2) +\n                               pow(vals[index + 1], 2) +\n                               pow(vals[index + 2], 2));\n                    if (mag == 0.0)\n                        continue;\n\n                    pos[0] = xb * (x % xnodes) - xoffset;\n                    pos[1] = yb * (y % ynodes) - yoffset;\n                    pos[2] = zb * (z % znodes) - zoffset;\n                    vec[0] = vals[index + 0] / mag;\n                    vec[1] = vals[index + 1] / mag;\n                    vec[2] = vals[index + 2] / mag;\n                    dot = vec[0] * color_vector[0] +\n                          vec[1] * color_vector[1] +\n                          vec[2] * color_vector[2];\n\n                    if (dot > 0)\n                    {\n                        col[0] = positive_color[0] * dot + (1.0 - dot);\n                        col[1] = positive_color[1] * dot + (1.0 - dot);\n                        col[2] = positive_color[2] * dot + (1.0 - dot);\n                    }\n                    else\n                    {\n                        dot *= -1;\n                        col[0] = negative_color[0] * dot + (1.0 - dot);\n                        col[1] = negative_color[1] * dot + (1.0 - dot);\n                        col[2] = negative_color[2] * dot + (1.0 - dot);\n                    }\n                    generateVBO(\n                        fut_ndarray,\n                        &offset,\n                        &normal_offset,\n                        pos,\n                        vec,\n                        col,\n                        t_rotation,\n                        height,\n                        radius,\n                        resolution);\n                }\n            }\n        }\n        np::dtype dt = np::dtype::get_builtin<double>();\n        p::tuple shape = p::make_tuple(offset);\n        p::tuple stride = p::make_tuple(sizeof(double));\n        p::handle<> h(::PyCapsule_New((void *)fut_ndarray,\n                                      NULL,\n                                      (PyCapsule_Destructor)&destroyManagerCObject));\n        return np::from_data(fut_ndarray,\n                             dt,\n                             shape,\n                             stride,\n                             p::object(h));\n    }\n\n    np::ndarray getMifAsNdarray(std::string path)\n    {\n\n        std::ifstream miffile;\n        miffile.open(path, std::ios::out | std::ios_base::binary);\n        int buffer_size = getMifHeader(miffile);\n        if (buffer_size == 0)\n        {\n            miffile.close();\n            throw std::runtime_error(\"Invalid mif file\");\n        }\n\n        int lines = znodes * xnodes * ynodes;\n        char buffer[buffer_size * lines * 3];\n        miffile.read(buffer, buffer_size * lines * 3);\n        double *vals = (double *)buffer;\n        double *fut_ndarray = (double *)(malloc(sizeof(double) * lines * 3));\n        double mag;\n        for (int i = 0; i < lines * 3; i += 3)\n        {\n            mag = sqrt(pow(vals[i + 0], 2) + pow(vals[i + 1], 2) + pow(vals[i + 2], 2));\n            if (mag == 0.0)\n                mag = 1.0;\n            fut_ndarray[i + 0] = vals[i + 0] / mag;\n            fut_ndarray[i + 1] = vals[i + 1] / mag;\n            fut_ndarray[i + 2] = vals[i + 2] / mag;\n        }\n        miffile.close();\n        // use explicit namespace here to make sure it does not mix the functions\n        np::dtype dt1 = np::dtype::get_builtin<double>();\n        p::tuple shape = p::make_tuple(lines, 3);\n        p::tuple stride = p::make_tuple(3 * sizeof(double), sizeof(double));\n        p::handle<> h(::PyCapsule_New((void *)fut_ndarray,\n                                      NULL,\n                                      (PyCapsule_Destructor)&destroyManagerCObject));\n        np::ndarray vectorData = np::from_data(fut_ndarray,\n                                               dt1,\n                                               shape,\n                                               stride,\n                                               p::object(h));\n        // last entry is object owner\n        return vectorData;\n    }\n};\n\nBOOST_PYTHON_MODULE(AdvParser)\n{\n    // avoids the SIGSEV on dtype in numpy initialization\n    boost::python::numpy::initialize();\n\n    using namespace boost::python;\n\n    class_<AdvParser>(\"AdvParser\")\n        .def(init<>())\n        .def(init<AdvParser>())\n\n        .def(\"getMifAsNdarrayWithColor\", &AdvParser::getMifAsNdarrayWithColor)\n        .def(\"getMifVBO\", &AdvParser::getMifVBO)\n        .def(\"getCubeOutline\", &AdvParser::getCubeOutline)\n        .def(\"getOmfToList\", &AdvParser::getOmfToList)\n        .def(\"getMifAsNdarray\", &AdvParser::getMifAsNdarray)\n\n        .def(\"getHeader\", &AdvParser::getHeader)\n        .def(\"getShapeAsNdarray\", &AdvParser::getShapeAsNdarray)\n        .def(\"generateIndices\", &AdvParser::generateIndices)\n\n        .add_property(\"xnodes\", &AdvParser::getXnodes, &AdvParser::setXnodes)\n        .add_property(\"ynodes\", &AdvParser::getYnodes, &AdvParser::setYnodes)\n        .add_property(\"znodes\", &AdvParser::getZnodes, &AdvParser::setZnodes)\n\n        .add_property(\"xbase\", &AdvParser::getXbase, &AdvParser::setXbase)\n        .add_property(\"ybase\", &AdvParser::getYbase, &AdvParser::setYbase)\n        .add_property(\"zbase\", &AdvParser::getZbase, &AdvParser::setZbase);\n}\n", "meta": {"hexsha": "87cb481c19f3da1ec578cd80a858a49e3c66941a", "size": 41727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CParseAdvanced/AdvParser.cpp", "max_stars_repo_name": "LemurPwned/VISM", "max_stars_repo_head_hexsha": "4d1e6b68d2bf1f9f3a09ce42c531ed2ce1d16400", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T11:52:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T13:26:45.000Z", "max_issues_repo_path": "CParseAdvanced/AdvParser.cpp", "max_issues_repo_name": "LemurPwned/VISM", "max_issues_repo_head_hexsha": "4d1e6b68d2bf1f9f3a09ce42c531ed2ce1d16400", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2018-08-17T18:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-18T10:43:08.000Z", "max_forks_repo_path": "CParseAdvanced/AdvParser.cpp", "max_forks_repo_name": "LemurPwned/VISM", "max_forks_repo_head_hexsha": "4d1e6b68d2bf1f9f3a09ce42c531ed2ce1d16400", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-16T02:48:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-30T13:26:48.000Z", "avg_line_length": 38.4935424354, "max_line_length": 108, "alphanum_fraction": 0.4401227023, "num_tokens": 10742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.02479815992531721, "lm_q1q2_score": 0.010007715379486916}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp\n//! \\author Alex Robinson\n//! \\brief  The decoupled complete Doppler broadened photon energy dist. def.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_DECOUPLED_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n#define MONTE_CARLO_DECOUPLED_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n\n// Std Lib Includes\n#include <algorithm>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_DiscreteDistribution.hpp\"\n#include \"Utility_ExplicitTemplateInstantiationMacros.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\n/*! \\details The Compton profile grids must be in me*c units (not atomic\n * units). The Compton profiles must be in inverse me*c units (not inverse\n * atomic units). Only half profiles should be provided (grid ranges from 0.0\n * to 1.0).\n */\ntemplate<typename ComptonProfilePolicy>\nDecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution(\n   const std::vector<double>& endf_subshell_occupancies,\n   const std::vector<Data::SubshellType>& endf_subshell_order,\n   const std::vector<double>& old_subshell_binding_energies,\n   const std::vector<double>& old_subshell_occupancies,\n   const std::shared_ptr<const ComptonProfileSubshellConverter>&\n   subshell_converter,\n   const CompleteDopplerBroadenedPhotonEnergyDistribution::ComptonProfileArray&\n   compton_profile_array )\n  : StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>(\n                                                     endf_subshell_occupancies,\n                                                     endf_subshell_order,\n                                                     subshell_converter,\n                                                     compton_profile_array ),\n  d_old_subshell_occupancy_distribution(),\n  d_old_subshell_binding_energy( old_subshell_binding_energies ),\n  d_old_subshell_occupancies( old_subshell_occupancies ),\n  d_min_binding_energy_index( 0 )\n{\n  // Make sure the old shell data is valid\n  testPrecondition( old_subshell_binding_energies.size() > 0 );\n  testPrecondition( old_subshell_occupancies.size() ==\n\t\t    old_subshell_binding_energies.size() );\n  // Make sure the comptron profile array is valid\n  testPrecondition( compton_profile_array.size() ==\n\t\t    old_subshell_binding_energies.size() );\n\n  // Create the old subshell interaction distribution\n  std::vector<double> dummy_indep_vals( old_subshell_occupancies.size() );\n\n  d_old_subshell_occupancy_distribution.reset(\n\t       new Utility::DiscreteDistribution( dummy_indep_vals,\n\t\t\t\t\t          old_subshell_occupancies ) );\n\n  // Calculate the min binding energy index\n  std::vector<double>::iterator min_binding_energy_it =\n    std::min_element( d_old_subshell_binding_energy.begin(),\n                      d_old_subshell_binding_energy.end() );\n\n  d_min_binding_energy_index =\n    std::distance( d_old_subshell_binding_energy.begin(),\n                   min_binding_energy_it );\n}\n\n// Return the binding energy of a subshell\ntemplate<typename ComptonProfilePolicy>\ndouble DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getSubshellBindingEnergy(\n                                            const Data::SubshellType subshell ) const\n{\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  unsigned old_subshell_index = this->getOldSubshellIndex( subshell );\n\n  return d_old_subshell_binding_energy[old_subshell_index];\n}\n\n// Return the occupancy of a subshell (default is the ENDF occupancy)\ntemplate<typename ComptonProfilePolicy>\ndouble DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getSubshellOccupancy(\n                                            const Data::SubshellType subshell ) const\n{\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  unsigned old_subshell_index = this->getOldSubshellIndex( subshell );\n\n  return d_old_subshell_occupancies[old_subshell_index];\n}\n\n// Evaluate the distribution with electron momentum projection\n/*! \\details Because the old subshell binding energies and subshell occupancy\n * data are used the procedure for evaluating the total cross section must be\n * changed. The electron momentum projection must be in me*c units \n * (a momentum value of me*c kg*m/s is 1.0 in me*c units). The distribution\n * will have units of barns since the unitless momentum is being used.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateWithElectronMomentumProjection(\n                                   const double incoming_energy,\n                                   const double electron_momentum_projection,\n                                   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the electron momentum projection is valid\n  testPrecondition( electron_momentum_projection >= -1.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // The total double differential cross section\n  double cross_section = 0.0;\n\n  // Evaluate each subshell\n  for( unsigned i = 0; i < d_old_subshell_binding_energy.size(); ++i )\n  {\n    // Get the subshell binding energy\n    const double subshell_binding_energy = d_old_subshell_binding_energy[i];\n\n    // Calculate the max electron momentum projection\n    ComptonProfile::MomentumQuantity max_electron_momentum_projection =\n      calculateMaxElectronMomentumProjection( incoming_energy,\n                                              subshell_binding_energy,\n                                              scattering_angle_cosine )*\n    ComptonProfile::MomentumUnit();\n\n    // Get the subshell occupancy\n    const double subshell_occupancy = d_old_subshell_occupancies[i];\n\n    // Get the subshell Compton profile\n    const ComptonProfile& compton_profile = this->getComptonProfile( i );\n\n    cross_section += subshell_occupancy*\n      ComptonProfilePolicy::evaluateWithPossibleLimit(\n                   compton_profile,\n                   electron_momentum_projection*ComptonProfile::MomentumUnit(),\n                   max_electron_momentum_projection ).value();\n  }\n\n  cross_section *= this->evaluateMultiplier( incoming_energy,\n                                             scattering_angle_cosine )*\n    this->evaluateRelativisticTerm( incoming_energy,\n                                    scattering_angle_cosine );\n\n  // Make sure the cross section is valid\n  testPostcondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the exact distribution\n/*! \\details Because the old subshell binding energies and subshell occupancy\n * data are used the procedure for evaluating the total cross section must be\n * changed. The distribution has units of barns/MeV.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateExact(\n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double outgoing_energy,\n\t\t\t\t   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the outgoing energy is valid\n  testPrecondition( outgoing_energy <= incoming_energy );\n  testPrecondition( outgoing_energy >= 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // Calculate the electron momentum projection\n  const ComptonProfile::MomentumQuantity electron_momentum_projection = \n    ComptonProfile::MomentumUnit()*\n    calculateElectronMomentumProjection( incoming_energy,\n                                         outgoing_energy,\n                                         scattering_angle_cosine );\n\n  // The total double differential cross section\n  double cross_section = 0.0;\n\n  // Evaluate each subshell\n  for( unsigned i = 0; i < d_old_subshell_binding_energy.size(); ++i )\n  {\n    // Get the subshell binding energy\n    const double subshell_binding_energy = d_old_subshell_binding_energy[i];\n\n    // Get the subshell occupancy\n    const double subshell_occupancy = d_old_subshell_occupancies[i];\n\n    // Get the subshell Compton profile\n    const ComptonProfile& compton_profile = this->getComptonProfile( i );\n\n    if( outgoing_energy <= incoming_energy - subshell_binding_energy )\n    {\n      cross_section += subshell_occupancy*\n        ComptonProfilePolicy::evaluate( compton_profile,\n                                        electron_momentum_projection ).value();\n    }\n  }\n\n  cross_section *= this->evaluateMultiplierExact( incoming_energy,\n                                                  outgoing_energy,\n                                                  scattering_angle_cosine )*\n    this->evaluateRelativisticTermExact( incoming_energy,\n                                         outgoing_energy,\n                                         scattering_angle_cosine );\n\n  // Make sure the cross section is valid\n  testPostcondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the integrated cross section\ntemplate<typename ComptonProfilePolicy>\ndouble DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateIntegratedCrossSection(\n                                         const double incoming_energy,\n                                         const double scattering_angle_cosine,\n                                         const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  boost::function<double (double x)> double_diff_cs_wrapper = \n    boost::bind<double>( &DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution::evaluateWithElectronMomentumProjection,\n                         boost::cref( *this ),\n                         incoming_energy,\n                         _1,\n                         scattering_angle_cosine );\n\n  // Get the min subshell binding energy\n  const double subshell_binding_energy =\n      d_old_subshell_binding_energy[d_min_binding_energy_index];\n\n  // Get the subshell Compton profile\n  const ComptonProfile& compton_profile =\n    this->getComptonProfile( d_min_binding_energy_index );\n\n  // Calculate the max electron momentum projection\n  double pz_max =\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            subshell_binding_energy,\n                                            scattering_angle_cosine );\n\n  // Don't go above the table max (profile will evaluate to zero beyond it)\n  pz_max = ComptonProfilePolicy::getUpperLimitOfIntegration(\n                               compton_profile,\n                               pz_max*ComptonProfile::MomentumUnit() ).value();\n\n  // Calculate the min electron momentum projection\n  double pz_min = ComptonProfilePolicy::getLowerLimitOfIntegration(\n                               pz_max*ComptonProfile::MomentumUnit() ).value();\n\n  // Calculate the absolute error and the integrated cross section\n  double abs_error, diff_cs;\n\n  Utility::GaussKronrodIntegrator<double> quadrature_set( precision );\n\n  if( pz_min < pz_max )\n  {\n    quadrature_set.integrateAdaptively<15>( double_diff_cs_wrapper,\n                                            pz_min,\n                                            pz_max,\n                                            diff_cs,\n                                            abs_error );\n  }\n  else\n  {\n    abs_error = 0.0;\n    diff_cs = 0.0;\n  }\n\n  // Make sure that the differential cross section is valid\n  testPostcondition( diff_cs >= 0.0 );\n\n  return diff_cs;                         \n}\n\n  // Evaluate the exact integrated cross section\ntemplate<typename ComptonProfilePolicy>\ndouble DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateIntegratedCrossSectionExact( \n                                         const double incoming_energy,\n                                         const double scattering_angle_cosine,\n                                         const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  boost::function<double (double x)> double_diff_cs_wrapper = \n    boost::bind<double>( &DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution::evaluateExact,\n                         boost::cref( *this ),\n                         incoming_energy,\n                         _1,\n                         scattering_angle_cosine );\n    \n\n  // Get the min subshell binding energy\n  const double subshell_binding_energy =\n    d_old_subshell_binding_energy[d_min_binding_energy_index];\n\n  // Calculate the max energy\n  double energy_max = incoming_energy - subshell_binding_energy;\n\n  // Calculate the max electron momentum projection\n  double pz_max =\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            subshell_binding_energy,\n                                            scattering_angle_cosine );\n\n  // Get the subshell Compton profile\n  const ComptonProfile& compton_profile =\n    this->getComptonProfile( d_min_binding_energy_index );\n\n  // Calculate the max table energy\n  const double pz_table_max =\n    ComptonProfilePolicy::getUpperBoundOfMomentum( compton_profile ).value();\n\n  if( pz_max > pz_table_max )\n  {\n    bool energetically_possible;\n    \n    energy_max = calculateDopplerBroadenedEnergy( pz_table_max,\n                                                  incoming_energy,\n                                                  scattering_angle_cosine,\n                                                  energetically_possible );\n  }\n\n  // Calculate the absolute error and the integrated cross section\n  double abs_error, diff_cs;\n\n  Utility::GaussKronrodIntegrator<double> quadrature_set( precision );\n\n  quadrature_set.integrateAdaptively<15>( double_diff_cs_wrapper,\n                                          0.0,\n                                          energy_max,\n                                          diff_cs,\n                                          abs_error );\n\n  // Make sure that the differential cross section is valid\n  testPostcondition( diff_cs >= 0.0 );\n\n  return diff_cs;\n}\n\n// Sample an interaction subshell\n/*! \\details The old subshell index used to select the Compton profile and\n * and the binding energy is not the same as the subshell (each are sampled\n * separately - i.e. they are decoupled).\n */\ntemplate<typename ComptonProfilePolicy>\nvoid DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleInteractionSubshell(\n                                           size_t& old_subshell_index,\n                                           double& subshell_binding_energy,\n                                           Data::SubshellType& subshell ) const\n{\n  old_subshell_index = this->sampleOldInteractionSubshell();\n\n  subshell_binding_energy = d_old_subshell_binding_energy[old_subshell_index];\n\n  subshell = this->sampleENDFInteractionSubshell();\n}\n\n// Sample the old subshell that is interacted with\ntemplate<typename ComptonProfilePolicy>\nsize_t DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleOldInteractionSubshell() const\n{\n  size_t old_subshell_of_interaction;\n\n  d_old_subshell_occupancy_distribution->sampleAndRecordBinIndex(\n                                                 old_subshell_of_interaction );\n\n  return old_subshell_of_interaction;\n}\n\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<FullComptonProfilePolicy> );\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<HalfComptonProfilePolicy> );\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution<DoubledHalfComptonProfilePolicy> );\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_DECOUPLED_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "0a2a58fd172cacb7b28ef5c8253a8450dcb93a5d", "size": 17435, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution_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_DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution_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_DecoupledStandardCompleteDopplerBroadenedPhotonEnergyDistribution_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": 42.8378378378, "max_line_length": 155, "alphanum_fraction": 0.6782907944, "num_tokens": 3482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.025957356444287673, "lm_q1q2_score": 0.00999130173410462}}
{"text": "/**\n ** Isaac Genome Alignment Software\n ** Copyright (c) 2010-2017 Illumina, Inc.\n ** All rights reserved.\n **\n ** This software is provided under the terms and conditions of the\n ** GNU GENERAL PUBLIC LICENSE Version 3\n **\n ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3\n ** along with this program. If not, see\n ** <https://github.com/illumina/licenses/>.\n **\n ** \\file BandedSmithWaterman.cpp\n **\n ** \\brief See BandedSmithWaterman.hh\n **\n ** \\author Come Raczy\n **/\n\n#include <iostream>\n#include <cassert>\n#include <cstdlib>\n#include <algorithm>\n#include <boost/format.hpp>\n#include <cstdint>\n\n#include \"alignment/BandedSmithWaterman.hh\"\n\nnamespace isaac\n{\nnamespace alignment\n{\n\ntemplate <unsigned widestGapSize>\nBandedSmithWaterman<widestGapSize>::BandedSmithWaterman(const int matchScore, const int mismatchScore,\n                                         const int gapOpenScore, const int gapExtendScore,\n                                         const int maxReadLength)\n    : mismatchesMin_(gapOpenScore / -mismatchScore)\n    , matchScore_(matchScore)\n    , mismatchScore_(mismatchScore)\n    , gapOpenScore_(gapOpenScore)\n    , gapExtendScore_(gapExtendScore)\n    , maxReadLength_(maxReadLength)\n    , initialValue_(static_cast<int>(std::numeric_limits<short>::min()) + gapOpenScore_)\n    , T_(new char[maxReadLength_ * 3 * WIDEST_GAP_SIZE * sizeof(int16_t)])\n{\n    // check that there won't be any overflows in the matrices\n    const int maxScore = std::max(std::max(std::max(abs(matchScore_), abs(mismatchScore_)), abs(gapOpenScore_)), abs(gapExtendScore_));\n    if ((maxReadLength_ * maxScore) >= abs(static_cast<int>(initialValue_)))\n    {\n        const std::string message = (boost::format(\"BandedSmithWaterman: unsupported read length (%i) for these scores (%i): use smaller scores or shorter reads\") % maxReadLength_ % maxScore).str();\n        BOOST_THROW_EXCEPTION(isaac::common::InvalidParameterException(message));\n    }\n}\n\ntemplate <unsigned widestGapSize>\nBandedSmithWaterman<widestGapSize>::~BandedSmithWaterman()\n{\n    free(T_);\n}\n\ntemplate <unsigned widestGapSize>\nvoid BandedSmithWaterman<widestGapSize>::cp(int16_t source[WIDEST_GAP_SIZE], int16_t destination[WIDEST_GAP_SIZE]) const\n{\n    // AV\n    for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n    destination[i] = source[i];\n    }\n}\n\ntemplate <unsigned widestGapSize>\nunsigned BandedSmithWaterman<widestGapSize>::align(\n    const std::vector<char> &query,\n    const reference::Contig::const_iterator databaseBegin,\n    const reference::Contig::const_iterator databaseEnd,\n    Cigar &cigar) const\n{\n    return align(query.begin(), query.end(), databaseBegin, databaseEnd, cigar);\n}\n\ntemplate <unsigned widestGapSize>\nunsigned BandedSmithWaterman<widestGapSize>::trimTailIndels(Cigar& cigar, const size_t beginOffset) const\n{\n    unsigned ret = 0;\n    uint64_t extend = 0;\n    for (Cigar::Component component = Cigar::decode(cigar.back());\n        cigar.size() != beginOffset; component = Cigar::decode(cigar.back()))\n    {\n        if (Cigar::DELETE == component.second)\n        {\n            //CASAVA does not like CIGAR beginning with a deletion in the data\n            cigar.pop_back();\n            ISAAC_ASSERT_MSG(\n                Cigar::DELETE != Cigar::decode(cigar.back()).second,\n                \"two Cigar::DELETE cannot be next to each other\");\n            ret += component.first;\n        }\n        else if (Cigar::INSERT == component.second)\n        {\n            // tail and head insertions are biasing best alignment choice. remove them and extend the adjacent align operation\n            extend += component.first;\n            ret -= component.first;\n            cigar.pop_back();\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    if (extend)\n    {\n        if(cigar.size() == beginOffset)\n        {\n            // this was a really bad s-w alignment. Something like this: 15D7I7D15I15D15I15D15I15D15I15D\n            cigar.addOperation(extend, Cigar::ALIGN);\n        }\n        else\n        {\n            const Cigar::Component component = Cigar::decode(cigar.back());\n            ISAAC_ASSERT_MSG(Cigar::ALIGN == component.second, \"Unexpected operation at the end of cigar \" <<\n                             Cigar::toString(cigar.begin() + beginOffset, cigar.end()) << \" : \"  << component.second);\n            cigar.updateOperation(cigar.size() - 1, component.first + extend, Cigar::ALIGN);\n        }\n    }\n    return ret;\n}\n\ntemplate <unsigned widestGapSize>\nvoid BandedSmithWaterman<widestGapSize>::removeAdjacentIndels(Cigar& cigar, const size_t beginOffset) const\n{\n//    ISAAC_THREAD_CERR << \"BandedSmithWaterman::removeAdjacentIndels \" << Cigar::toString(cigar.begin() + beginOffset, cigar.end()) << std::endl;\n    const Cigar::iterator begin = cigar.begin() + beginOffset;\n    for (Cigar::iterator it = begin + 1; cigar.end() != it;)\n    {\n        const Cigar::iterator last = it - 1;\n        const Cigar::Component lastcomponent = Cigar::decode(*last);\n        const Cigar::Component component = Cigar::decode(*it);\n        if (Cigar::ALIGN == lastcomponent.second)\n        {\n            if (Cigar::ALIGN == component.second)\n            {\n                cigar.updateOperation(std::distance(cigar.begin(), last), lastcomponent.first + component.first, Cigar::ALIGN);\n                it = cigar.erase(it);\n            }\n            else\n            {\n                ++it;\n            }\n        }\n        else if (Cigar::DELETE == lastcomponent.second)\n        {\n            if (Cigar::DELETE == component.second)\n            {\n                cigar.updateOperation(std::distance(cigar.begin(), last), lastcomponent.first + component.first, Cigar::DELETE);\n                it = cigar.erase(it);\n            }\n            else if (Cigar::INSERT == component.second)\n            {\n                if (component.first < lastcomponent.first)\n                {\n                    cigar.updateOperation(std::distance(cigar.begin(), last), lastcomponent.first - component.first, Cigar::DELETE);\n                    cigar.updateOperation(std::distance(cigar.begin(), it), component.first, Cigar::ALIGN);\n                }\n                else if (lastcomponent.first < component.first)\n                {\n                    cigar.updateOperation(std::distance(cigar.begin(), last), component.first - lastcomponent.first, Cigar::INSERT);\n                    cigar.updateOperation(std::distance(cigar.begin(), it), lastcomponent.first, Cigar::ALIGN);\n                    if (begin != it - 1)\n                    {\n                        --it;\n                    }\n                }\n                else\n                {\n                    cigar.updateOperation(std::distance(cigar.begin(), last), component.first, Cigar::ALIGN);\n                    it = cigar.erase(it);\n                    if (begin != it - 1)\n                    {\n                        --it;\n                    }\n                }\n            }\n            else\n            {\n                ++it;\n            }\n        }\n        else if (Cigar::INSERT == lastcomponent.second)\n        {\n            if (Cigar::INSERT == component.second)\n            {\n                cigar.updateOperation(std::distance(cigar.begin(), last), lastcomponent.first + component.first, Cigar::INSERT);\n                it = cigar.erase(it);\n            }\n            else if (Cigar::DELETE == component.second)\n            {\n                if (component.first < lastcomponent.first)\n                {\n                    cigar.updateOperation(std::distance(cigar.begin(), last), lastcomponent.first - component.first, Cigar::INSERT);\n                    cigar.updateOperation(std::distance(cigar.begin(), it), component.first, Cigar::ALIGN);\n                }\n                else if (lastcomponent.first < component.first)\n                {\n                    cigar.updateOperation(std::distance(cigar.begin(), last), component.first - lastcomponent.first, Cigar::DELETE);\n                    cigar.updateOperation(std::distance(cigar.begin(), it), lastcomponent.first, Cigar::ALIGN);\n                    if (begin != it - 1)\n                    {\n                        --it;\n                    }\n                }\n                else\n                {\n                    cigar.updateOperation(std::distance(cigar.begin(), last), component.first, Cigar::ALIGN);\n                    it = cigar.erase(it);\n                    if (begin != it - 1)\n                    {\n                        --it;\n                    }\n                }\n            }\n            else\n            {\n                ++it;\n            }\n        }\n        else\n        {\n            ++it;\n        }\n    }\n    //ISAAC_THREAD_CERR << \"BandedSmithWaterman::removeAdjacentIndels done \" << Cigar::toString(cigar.begin() + beginOffset, cigar.end()) << std::endl;\n}\n\n\ntemplate <unsigned widestGapSize>\nunsigned BandedSmithWaterman<widestGapSize>::align(\n    const std::vector<char>::const_iterator queryBegin,\n    const std::vector<char>::const_iterator queryEnd,\n    const reference::Contig::const_iterator databaseBegin,\n    const reference::Contig::const_iterator databaseEnd,\n    Cigar &cigar) const\n{\n    assert(databaseEnd > databaseBegin);\n    const size_t querySize = std::distance(queryBegin, queryEnd);\n    ISAAC_ASSERT_MSG(querySize + WIDEST_GAP_SIZE - 1 == (uint64_t)(databaseEnd - databaseBegin), \"q:\" << std::string(queryBegin, queryEnd) << \" db:\" << std::string(databaseBegin, databaseEnd));\n    assert(querySize <= size_t(maxReadLength_));\n    const size_t originalCigarSize = cigar.size();\n    int16_t *t = (int16_t*)T_;\n\n    int16_t GapOpenScore[WIDEST_GAP_SIZE], GapExtendScore[WIDEST_GAP_SIZE];\n    for(unsigned i = 0; i < WIDEST_GAP_SIZE; i++) {\n        GapOpenScore[i] = gapOpenScore_;\n        GapExtendScore[i] = gapExtendScore_;\n    }\n    // Initialize E, F and G\n    int16_t D[WIDEST_GAP_SIZE], E[WIDEST_GAP_SIZE], F[WIDEST_GAP_SIZE], G[WIDEST_GAP_SIZE];\n    for(unsigned i = 0; i < WIDEST_GAP_SIZE; i++) {\n        E[i] = initialValue_;\n        F[i] = 0;\n        G[i] = initialValue_;\n    }\n    G[0] = 0;\n\n    for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n        D[i] = *(databaseBegin + (WIDEST_GAP_SIZE - i - 2));\n    }\n\n    // iterate over all bases in the query\n    int16_t F1[WIDEST_GAP_SIZE + 1];\n    int16_t cmpgtEgMask1[WIDEST_GAP_SIZE + 1], maxEg1[WIDEST_GAP_SIZE + 1];\n    F1[0] = initialValue_ + gapExtendScore_;\n    maxEg1[0] = initialValue_ + gapOpenScore_;\n    cmpgtEgMask1[0] = 0;\n    std::vector<char>::const_iterator queryCurrent = queryBegin;\n    for (unsigned queryOffset = 0; queryEnd != queryCurrent; ++queryOffset, ++queryCurrent)\n    {\n        int16_t TE[WIDEST_GAP_SIZE], TF[WIDEST_GAP_SIZE], TG[WIDEST_GAP_SIZE];\n        int16_t D1[WIDEST_GAP_SIZE + 1];\n        int16_t Q[WIDEST_GAP_SIZE];\n        int16_t GA[WIDEST_GAP_SIZE];\n\n        // get F[i-1, j] - extend\n        int16_t cmpgtGfMask[WIDEST_GAP_SIZE];\n\n        int16_t *cmpgtEgMaskOff = cmpgtEgMask1 + 1;\n        int16_t *maxEgOff = maxEg1 + 1;\n        // AV\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            cmpgtEgMaskOff[i] = E[i] > G[i] ? 1 : 0;\n        }\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            maxEgOff[i] = G[i] > E[i] ? G[i] : E[i];\n        }\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            cmpgtGfMask[i] = F[i] > maxEgOff[i] ? 2 : 0;\n        }\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            GA[i] = maxEgOff[i] > F[i] ? maxEgOff[i] : F[i];\n        }\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            TG[i] =\n                   cmpgtEgMaskOff[i] >\n                cmpgtGfMask[i] ? cmpgtEgMaskOff[i] : cmpgtGfMask[i];\n        }\n\n        cp(F, F1 + 1);\n        int16_t GF1[WIDEST_GAP_SIZE], maxEgSubGapOpen1[WIDEST_GAP_SIZE],\n            cmpgtGfMask1[WIDEST_GAP_SIZE];\n        // AV\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            GF1[i] = F1[i] - GapExtendScore[i];\n            maxEgSubGapOpen1[i] = maxEg1[i] - GapOpenScore[i];\n            cmpgtGfMask1[i] = GF1[i] > maxEgSubGapOpen1[i] ? 2 : 0;\n            TF[i] =\n                cmpgtEgMask1[i] >\n                cmpgtGfMask1[i] ? cmpgtEgMask1[i] : cmpgtGfMask1[i];\n            F[i] =\n                maxEgSubGapOpen1[i] > GF1[i] ? maxEgSubGapOpen1[i] : GF1[i];\n        }\n\n        // add the match/mismatch score\n        // load the query base in all 8 values of the register\n        for(unsigned i = 0; i < WIDEST_GAP_SIZE; i++) { \n            Q[i] = *queryCurrent;\n        }\n\n        // shift the database by 1 byte to the left and add the new base\n\n        cp(D, D1+1);\n        D1[0] = *(databaseBegin + queryOffset + (WIDEST_GAP_SIZE - 1));\n        cp(D1, D);\n\n        // compare query and database. 0xff if different (that also the sign bits)\n        int16_t B[WIDEST_GAP_SIZE], Match[WIDEST_GAP_SIZE],\n        Mismatch[WIDEST_GAP_SIZE], W[WIDEST_GAP_SIZE];\n\n        // lea\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            B[i] = (Q[i] == D[i]) ? 0 : 0xFFFF;\n            Match[i] = (~B[i]) & matchScore_;\n            Mismatch[i] = B[i] & mismatchScore_;\n            W[i] = Match[i] + Mismatch[i];\n            G[i] = GA[i] + (W[i] | (B[i] & 0xFF00));\n        }\n\n        // E[i,j] = max(G[i, j-1] - open, E[i, j-1] - extend, F[i, j-1] - open)\n         int16_t cmpgtFgMask2[WIDEST_GAP_SIZE + 1], maxFg2[WIDEST_GAP_SIZE + 1];\n           int16_t *cmpgtFgMaskOff2 = cmpgtFgMask2 + 1;\n           int16_t *maxFgOff2 = maxFg2 + 1;\n           // AV\n           for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n               cmpgtFgMask2[i] = F[i] > G[i] ? 2 : 0;\n               maxFg2[i] = F[i] > G[i] ? F[i] : G[i];\n               maxFg2[i] -= GapOpenScore[i];\n           }\n\n           E[WIDEST_GAP_SIZE - 1] = initialValue_;\n        maxFg2[WIDEST_GAP_SIZE] = initialValue_;\n\n        short e = initialValue_;\n        short fg = initialValue_;\n        for (size_t i = WIDEST_GAP_SIZE; i > 0; i--) {\n            short max = fg;\n            if (e > fg) {\n                max = e;\n            }\n           E[i - 1] = max;\n           fg = maxFg2[i - 1];\n    \n           e = max - gapExtendScore_;\n        }\n\n        // lea\n        int16_t cmpgtFgSueFgMask2[WIDEST_GAP_SIZE];\n        cmpgtFgMask2[WIDEST_GAP_SIZE] = initialValue_;\n        for (size_t i = 0; i < WIDEST_GAP_SIZE; i++) {\n            cmpgtFgSueFgMask2[i] = E[i] > maxFgOff2[i] ? 5 : 0;\n            E[i] = E[i] > maxFgOff2[i] ? E[i] : maxFgOff2[i];\n            TE[i] =\n                (cmpgtFgSueFgMask2[i] >\n                 cmpgtFgMaskOff2[i] ? cmpgtFgSueFgMask2[i] :\n                 cmpgtFgMaskOff2[i]) & 3;\n        }\n\n        TF[0] = 0;\n\n        cp(TG, t);\n        cp(TE, t + WIDEST_GAP_SIZE);\n        cp(TF, t + WIDEST_GAP_SIZE * 2);\n        t += WIDEST_GAP_SIZE * 3;\n    }\n    // find the max of E, F and G at the end\n    short max = G[WIDEST_GAP_SIZE - 1] - 1;\n\n    int ii = querySize - 1;\n    int jj = ii;\n    unsigned maxType = 0;\n\n\n    int16_t *TT[] = {G, E, F};\n    for (unsigned j = WIDEST_GAP_SIZE; j > 0; j--)\n    {\n        for (unsigned type = 0; 3 > type; ++type)\n        {\n            const short value = TT[type][j - 1];\n            if (value > max)\n            {\n                max = value;\n                jj = j - 1;\n                maxType = type;\n            }\n        }\n    }\n\n    const int jjIncrement[] = {0, 1, -1};\n    const int iiIncrement[] = {-1, 0, -1};\n    const Cigar::OpCode opCodes[] = {Cigar::ALIGN, Cigar::DELETE, Cigar::INSERT};\n    unsigned opLength = 0;\n    if (jj > 0)\n    {\n        cigar.addOperation(jj, Cigar::DELETE);\n    }\n    while(ii >= 0 && jj >= 0 && jj <= int(WIDEST_GAP_SIZE - 1))\n    {\n        ++opLength;\n        const unsigned nextMaxType = T_[(ii * 3 + maxType)\n            * WIDEST_GAP_SIZE * sizeof(int16_t) + (jj * 2)];\n        if (nextMaxType != maxType)\n        {\n            cigar.addOperation(opLength, opCodes[maxType]);\n            opLength = 0;\n        }\n        ii += iiIncrement[maxType];\n        jj += jjIncrement[maxType];\n        maxType = nextMaxType;\n    }\n    assert(-1 == ii);\n    if (1 != maxType && opLength)\n    {\n        cigar.addOperation(opLength, opCodes[maxType]);\n        opLength = 0;\n    }\n    if (int(WIDEST_GAP_SIZE - 1) > jj)\n    {\n        cigar.addOperation(opLength + (WIDEST_GAP_SIZE - 1) - jj, Cigar::DELETE);\n        opLength = 0;\n    }\n    assert(0 == opLength);\n    unsigned ret = trimTailIndels(cigar, originalCigarSize);\n    std::reverse(cigar.begin() + originalCigarSize, cigar.end());\n    trimTailIndels(cigar, originalCigarSize);\n    removeAdjacentIndels(cigar, originalCigarSize);\n    return ret;\n}\n\ntemplate class BandedSmithWaterman<16>;\ntemplate class BandedSmithWaterman<32>;\ntemplate class BandedSmithWaterman<64>;\n\n} // namespace alignment\n} // namespace isaac\n\n", "meta": {"hexsha": "14db1916ea1bed41c3748cfb7a548992919fcd4a", "size": 16813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/c++/lib/alignment/BandedSmithWaterman.cpp", "max_stars_repo_name": "Illumina/Isaac4", "max_stars_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T22:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:33:22.000Z", "max_issues_repo_path": "src/c++/lib/alignment/BandedSmithWaterman.cpp", "max_issues_repo_name": "Illumina/Isaac4", "max_issues_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-26T11:36:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T18:48:43.000Z", "max_forks_repo_path": "src/c++/lib/alignment/BandedSmithWaterman.cpp", "max_forks_repo_name": "Illumina/Isaac4", "max_forks_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T14:44:06.000Z", "avg_line_length": 36.2349137931, "max_line_length": 198, "alphanum_fraction": 0.5577231904, "num_tokens": 4498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.025957356114627416, "lm_q1q2_score": 0.009991301607214382}}
{"text": "/*\n * SimData.cpp\n *\n *  Created on: Feb 15, 2011\n *      Author: ignacio.martin@imdea.org\n *\n * Copyright 2014 IMDEA Materials Institute, Getafe, Madrid, Spain\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 \"SimData.h\"\n#include \"MCClient.h\"\n#include \"kernel/Mesh.h\"\n#include \"kernel/Domain.h\"\n#include \"kernel/RateManager.h\"\n#include \"kernel/Constants.h\"\n#include \"lkmc/LatticeParam.h\"\n#include \"lkmc/LatticeAtom.h\"\n#include \"lkmc/LatticeAtomDiamond.h\"\n#include \"lkmc/Lattice.h\"\n#include \"okmc/Particle.h\"\n#include \"okmc/Defect.h\"\n#include \"okmc/EDType.h\"\n#include \"okmc/Interface.h\"\n#include \"okmc/MobileParticle.h\"\n#include \"okmc/Cluster.h\"\n#include \"io/ParameterManager.h\"\n#include \"kernel/StateManager.h\"\n#include \"io/Diagnostic.h\"\n#include \"io/Polynomial.h\"\n#include \"io/FileParameters.h\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iomanip>\n\nusing std::vector;\nusing std::pair;\nusing std::map;\nusing std::string;\nusing std::setw;\nusing Kernel::Coordinates;\nusing Kernel::Mesh;\n\nusing namespace boost::numeric;\n\nnamespace Domains {\n\nSimData::SimData(IO::FileParameters *pFP) : _lastTime(0), _dim(1)\n{\n\t_odelta[0] = pFP->getFloat(\"MC/Mesh/delta.x\");\n\t_odelta[1] = pFP->getFloat(\"MC/Mesh/delta.y\");\n\t_odelta[2] = pFP->getFloat(\"MC/Mesh/delta.z\");\n}\n\nvoid SimData::getLKMCInterface(vector<ParticleData>&c, bool bDefective) const\n{\n\tconst bool interface = true;\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tLKMC::LatticeSite *first = it->getFirstLS();\n\t\twhile(first)\n\t\t{\n\t\t\tLKMC::LatticeAtom *pLA = dynamic_cast<LKMC::LatticeAtom *>(first);\n\t\t\tif(pLA)\n\t\t\t{\n\t\t\t\tstd::string name = Domains::global()->PM()->getElementName(pLA->getPType());\n\t\t\t\tif(interface)\n\t\t\t\t{\n\t\t\t\t\t// a/c interface = crystalline atoms having an amorphous NN\n\t\t\t\t\tif(pLA->isDefective())\n\t\t\t\t\t\tc.push_back(ParticleData(it->getMaterial(), pLA->getCoordinates(), pLA->getPType(), pLA->getEType(), name));\n\t\t\t\t\telse\n\t\t\t\t\t\tfor(unsigned j=0; j < pLA->first(); ++j)\n\t\t\t\t\t\t\tif(pLA->getNeighbor(j) && pLA->getPerformed() && pLA->getNeighbor(j)->getPerformed() != pLA->getPerformed())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tc.push_back(ParticleData(it->getMaterial(), pLA->getCoordinates(), pLA->getPType(), pLA->getEType(), name));\n\t\t\t\t\t\t\t\tbreak ;\n\t\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tc.push_back(ParticleData(it->getMaterial(), pLA->getCoordinates(), pLA->getPType(), pLA->getEType(), name));\n\t\t\t}\n\t\t\tfirst = first->getNext();\n\t\t}\n\t}\n}\n\nvoid SimData::getACInterfaceMean(Kernel::Coordinates &min, Kernel::Coordinates &max, Kernel::Coordinates &meanO) const\n{\n\tstd::set<LKMC::LatticeAtom *> ac;\n\tLKMC::LatticeAtom *pLA;\n\tKernel::CoordinatesT<double> mean;\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it != Domains::global()->endMEI(); ++it)\n\t{\n\t\tpLA = static_cast<LKMC::LatticeAtom * >(it->getFirstLS());\n\n\t\twhile (pLA) {\n\t\t\tfor(unsigned j=0; j < pLA->first(); ++j)\n\t\t\t\tif(pLA->getNeighbor(j) /*&& amorph.find(pLA->getNeighbor(j)) == amorph.end()*/\n\t\t\t\t\t\t&& !pLA->getNeighbor(j)->getPerformed() && /*!pLA->getNeighbor(j)->getDefective() &&*/ pLA->getPerformed()) {\n\t\t\t\t\tdouble x = pLA->getCoordinates()._x;\n\t\t\t\t\tdouble y = pLA->getCoordinates()._y;\n\t\t\t\t\tdouble z = pLA->getCoordinates()._z;\n\n\t\t\t\t\tif (x >= min._x && x <= max._x && y >= min._y && y <= max._y && z >= min._z && z <= max._z) {\n\t\t\t\t\t\tac.insert(pLA);\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tpLA = static_cast<LKMC::LatticeAtom * >(pLA->getNext());\n\t\t}\n\t}\n\n\tmean._x = 0.;\n\tmean._y = 0.;\n\tmean._z = 0.;\n\n\tfor (std::set<LKMC::LatticeAtom *>::iterator it = ac.begin(); it != ac.end(); ++it) {\n\t\tmean._x += static_cast<double>((*it)->getCoordinates()._x);\n\t\tmean._y += static_cast<double>((*it)->getCoordinates()._y);\n\t\tmean._z += static_cast<double>((*it)->getCoordinates()._z);\n\t}\n\tmeanO._x = ac.size() ? mean._x / ac.size() : 0.;\n\tmeanO._y = ac.size() ? mean._y / ac.size() : 0.;\n\tmeanO._z = ac.size() ? mean._z / ac.size() : 0.;\n}\n\nfloat SimData::getACInterfaceCoverage(Kernel::Coordinates &min, Kernel::Coordinates &max) const\n{\n\tstd::set<LKMC::LatticeAtom *> ac;\n\tLKMC::LatticeAtom *pLA;\n\tKernel::CoordinatesT<double> mean;\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it != Domains::global()->endMEI(); ++it)\n\t{\n\t\tpLA = static_cast<LKMC::LatticeAtom * >(it->getFirstLS());\n\n\t\twhile (pLA) {\n\t\t\tfor(unsigned j=0; j < pLA->first(); ++j)\n\t\t\t\tif(pLA->getNeighbor(j) && pLA->getNeighbor(j)->getPerformed() && !pLA->getPerformed()) {\n\t\t\t\t\tdouble x = pLA->getCoordinates()._x;\n\t\t\t\t\tdouble y = pLA->getCoordinates()._y;\n\t\t\t\t\tdouble z = pLA->getCoordinates()._z;\n\n\t\t\t\t\tif (x >= min._x && x <= max._x && y >= min._y && y <= max._y && z >= min._z && z <= max._z) {\n\t\t\t\t\t\tac.insert(pLA);\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tpLA = static_cast<LKMC::LatticeAtom * >(pLA->getNext());\n\t\t}\n\t}\n\n\tunsigned precursor = 0;\n\n\tfor (std::set<LKMC::LatticeAtom *>::iterator it = ac.begin(); it != ac.end(); ++it)\n\t\tif((*it)->getState() == LKMC::LatticeAtom::LS_PRECURSOR)\n\t\t\tprecursor++;\n\treturn float(precursor)/float(ac.size());\n}\n\nvoid SimData::getACInterfaceMinMax(Kernel::Coordinates &min, Kernel::Coordinates &max, Kernel::Coordinates &acm, Kernel::Coordinates &acM) const\n{\n\tstd::set<LKMC::LatticeAtom *> ac;\n\tLKMC::LatticeAtom *pLA;\n\tacm = max;\n\tacM = min;\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it != Domains::global()->endMEI(); ++it)\n\t{\n\t\tpLA = static_cast<LKMC::LatticeAtom * >(it->getFirstLS());\n\n\t\twhile (pLA)\n\t\t{\n\t\t\tfor(unsigned j=0; j < pLA->first(); ++j)\n\t\t\t\tif(pLA->getNeighbor(j) /*&& amorph.find(pLA->getNeighbor(j)) == amorph.end()*/\n\t\t\t\t\t\t&& !pLA->getNeighbor(j)->getPerformed() && /*!pLA->getNeighbor(j)->getDefective() &&*/ pLA->getPerformed())\n\t\t\t\t{\n\t\t\t\t\tdouble x = pLA->getCoordinates()._x;\n\t\t\t\t\tdouble y = pLA->getCoordinates()._y;\n\t\t\t\t\tdouble z = pLA->getCoordinates()._z;\n\n\t\t\t\t\tif (x >= min._x && x <= max._x && y >= min._y && y <= max._y && z >= min._z && z <= max._z)\n\t\t\t\t\t{\n\t\t\t\t\t\tif( x <= acm._x) acm._x = x;\n\t\t\t\t\t\tif( y <= acm._y) acm._y = y;\n\t\t\t\t\t\tif( z <= acm._z) acm._z = z;\n\t\t\t\t\t\tif( x >= acM._x) acM._x = x;\n\t\t\t\t\t\tif( y >= acM._y) acM._y = y;\n\t\t\t\t\t\tif( z >= acM._z) acM._z = z;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tpLA = static_cast<LKMC::LatticeAtom * >(pLA->getNext());\n\t\t}\n\t}\n}\n\nvoid SimData::getACInterfaceStdev(Kernel::Coordinates &min, Kernel::Coordinates &max, Kernel::Coordinates &stdevO) const\n{\n\tstd::set<LKMC::LatticeAtom *> ac;\n\tLKMC::LatticeAtom *pLA;\n\tKernel::CoordinatesT<double> mean, stdev; //to increase precision a little.\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it != Domains::global()->endMEI(); ++it)\n\t{\n\t\tpLA = static_cast<LKMC::LatticeAtom * >(it->getFirstLS());\n\n\t\twhile (pLA) {\n\t\t/*\tstd::set<const LKMC::LatticeAtom *> amorph;\n\t\t\tfor(unsigned i=0; i<pLA->first(); ++i) {\n\t\t\t\tif (pLA->getNeighbor(i) && !pLA->getNeighbor(i)->getPerformed()) {\n\t\t\t\t\t// amorphous\n\t\t\t\t\tunsigned def = 0;\n\t\t\t\t\tfor(unsigned j=0; j<pLA->getNeighbor(i)->first(); ++j) {\n\t\t\t\t\t\tif (pLA->getNeighbor(i)->getNeighbor(j) && pLA->getNeighbor(i)->getNeighbor(j)->getDefective())\n\t\t\t\t\t\t\t++def;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (def >= 1) {\n\t\t\t\t\t\tamorph.insert(pLA->getNeighbor(i));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}*/\n\t\t\tfor(unsigned j=0; j < pLA->first(); ++j) {\n\t\t\t\tif(pLA->getNeighbor(j) /*&& amorph.find(pLA->getNeighbor(j)) == amorph.end() */&& !pLA->getNeighbor(j)->getPerformed()/* && !pLA->getNeighbor(j)->getDefective()*/ && pLA->getPerformed()) {\n\t\t\t\t\tdouble x = pLA->getCoordinates()._x;\n\t\t\t\t\tdouble y = pLA->getCoordinates()._y;\n\t\t\t\t\tdouble z = pLA->getCoordinates()._z;\n\n\t\t\t\t\tif (x >= min._x && x <= max._x && y >= min._y && y <= max._y && z >= min._z && z <= max._z) {\n\t\t\t\t\t\tac.insert(pLA);\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tpLA = static_cast<LKMC::LatticeAtom * >(pLA->getNext());\n\t\t}\n\t}\n\n\tmean._x = 0.;\n\tmean._y = 0.;\n\tmean._z = 0.;\n\n\tfor (std::set<LKMC::LatticeAtom *>::iterator it = ac.begin(); it != ac.end(); ++it) {\n\t\tmean._x += static_cast<double>((*it)->getCoordinates()._x) / static_cast<double>(ac.size());\n\t\tmean._y += static_cast<double>((*it)->getCoordinates()._y) / static_cast<double>(ac.size());\n\t\tmean._z += static_cast<double>((*it)->getCoordinates()._z) / static_cast<double>(ac.size());\n\t}\n\n\tstdev._x = 0.;\n\tstdev._y = 0.;\n\tstdev._z = 0.;\n\tfor (std::set<LKMC::LatticeAtom *>::iterator it = ac.begin(); it != ac.end(); ++it) {\n\t\tstdev._x += pow(static_cast<double>((*it)->getCoordinates()._x) - mean._x, 2);\n\t\tstdev._y += pow(static_cast<double>((*it)->getCoordinates()._y) - mean._y, 2);\n\t\tstdev._z += pow(static_cast<double>((*it)->getCoordinates()._z) - mean._z, 2);\n\t}\n\n\tstdevO._x = ac.size() ? sqrt(stdev._x/ac.size()) : 0.;\n\tstdevO._y = ac.size() ? sqrt(stdev._y/ac.size()) : 0.;\n\tstdevO._z = ac.size() ? sqrt(stdev._z/ac.size()) : 0.;\n}\n\nvoid SimData::getOKMCParticles(std::vector<Domains::ParticleData> &data, const vector<string> &defects) const\n{\n\tconst unsigned nParticles = Domains::global()->PM()->getNParticles();\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tOKMC::Particle *pPart = it->getFirstPart();\n\t\twhile(pPart)\n\t\t{\n\t\t\tKernel::Event::E_TYPE     et = pPart->getDefect()->getEType();\n\t\t\tKernel::P_TYPE              pt = pPart->getPType();\n\t\t\tconst Kernel::Coordinates co = pPart->getCoordinates();\n\t\t\tKernel::M_TYPE            mt = it->getMaterial();\n\t\t\tstring name;\n\t\t\tunsigned defectType = 0;\n\t\t\tswitch(et)\n\t\t\t{\n\t\t\tcase Kernel::Event::CLUSTER:\n\t\t\t{\n\t\t\t\tOKMC::Cluster *mc = static_cast<OKMC::Cluster *>(pPart->getDefect());\n\t\t\t\tname = mc->getDomain()->_pClPar->getParams(it->getMaterial(), mc->getEDType())->_name;\n\t\t\t\tdefectType = 2+mc->getEDType();\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase Kernel::Event::INTERFACE:\n\t\t\t\tdefectType = 1;\n\t\t\t\tname = Kernel::Event::getEName(et);\n\t\t\tbreak;\n\n\t\t\tcase Kernel::Event::MOBILEPARTICLE:\n\t\t\tdefault:\n\t\t\t\tdefectType = 0;\n\t\t\t\tname = Kernel::Event::getEName(et);\n\t\t\tbreak;\n\t\t\t}\n\t\t\tif(defects.empty() || std::find(defects.begin(), defects.end(), name) != defects.end())\n\t\t\t\tdata.push_back(Domains::ParticleData(mt, co, pt+defectType*nParticles, et, name, pPart->getDefect()->getIndex(0)));\n\t\t\tpPart = pPart->getNext();\n\t\t}\n\n\t\tunsigned howMany = it->getBAtoms();\n\t\tKernel::Domain *pDomain = it->getDomain();\n\t\tKernel::M_TYPE mt = it->getMaterial();\n\t\tKernel::P_TYPE alloyPt = Domains::global()->PM()->getMaterial(mt)._alloy;\n\t\twhile(howMany--)\n\t\t{\n\t\t\tKernel::Coordinates co;\n\t\t\tpDomain->_pMesh->getRandomPosition(it->getIndex(), co,\n\t\t\t\tpDomain->_rng_dom.rand(), pDomain->_rng_dom.rand(), pDomain->_rng_dom.rand());\n\t\t\tif(defects.empty() || std::find(defects.begin(), defects.end(), \"Alloy\") != defects.end())\n\t\t\t\tdata.push_back(Domains::ParticleData(mt, co, alloyPt, Kernel::Event::MOBILEPARTICLE, \"Alloy\", 0));\n\t\t}\n\t}\n\n}\n\n//include alloy particles\nvoid SimData::collectDefects(map<string, unsigned> maps[Kernel::MAX_MATERIALS]) const\n{\n\tDomains::DefectIterator itEnd = Domains::global()->endDI();\n\tfor(Domains::DefectIterator it = Domains::global()->beginDI(); it!= Domains::global()->endDI(); ++it)\n\t{\n\t\tKernel::ID theMap = it->getID();\n\t\tassert(theMap._mt < Domains::global()->PM()->getNMaterials());\n\t\tstring name = Domains::global()->PM()->getIDName(theMap);\n\t\tKernel::M_TYPE mt = it->getElement()->getMaterial();\n\t\tstd::stringstream ss;\n\t\tswitch(it->getEType())\n\t\t{\n\t\tcase Kernel::Event::CLUSTER:\n\t\t\tss << it->getDomain()->_pClPar->getParams(mt, static_cast<const OKMC::Cluster *>(*it)->getEDType())->_name;\n\t\t\tbreak;\n\t\tcase Kernel::Event::INTERFACE:\n\t\t\tcontinue; //to be treated differently\n\t\tdefault:\n\t\t\tss << Kernel::Event::getEName(it->getEType());\n\t\t\tbreak;\n\t\t}\n\t\tss << \"/\" << name;\n\t\tif(maps[mt].find(ss.str()) == maps[mt].end())\n\t\t\tmaps[mt][ss.str()] = 1;\n\t\telse\n\t\t\tmaps[mt][ss.str()]++;\n\t}\n\t//interfaces only\n\tfor(Domains::DefectIterator it = Domains::global()->beginDI(); it!= Domains::global()->endDI(); ++it)\n\t{\n\t\tconst OKMC::Interface *pInt = dynamic_cast<const OKMC::Interface *> (*it);\n\t\tif(pInt)\n\t\t{\n\t\t\tKernel::ID theMap = pInt->getID();\n\t\t\tstring name0 = Domains::global()->PM()->getMaterialName(pInt->getElement(0)->getMaterial());\n\t\t\tstring name1 = Domains::global()->PM()->getMaterialName(pInt->getElement(1)->getMaterial());\n\t\t\tstd::stringstream ss;\n\t\t\tKernel::M_TYPE mt;\n\t\t\tif(name0 < name1)\n\t\t\t{\n\t\t\t\tmt = pInt->getElement(0)->getMaterial();\n\t\t\t\tss << name0 << \"_\" << name1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmt = pInt->getElement(1)->getMaterial();\n\t\t\t\tss << name1 << \"_\" << name0;\n\t\t\t}\n\t\t\tfor(map<Kernel::P_TYPE, unsigned>::iterator it2 = theMap._pt.begin(); it2 != theMap._pt.end(); ++it2)\n\t\t\t{\n\t\t\t\tstd::stringstream sss;\n\t\t\t\tsss << ss.str() << \"/\" << Domains::global()->PM()->getParticleName(theMap._mt, it2->first);\n\t\t\t\tif(maps[mt].find(sss.str()) == maps[mt].end())\n\t\t\t\t\tmaps[mt][sss.str()] = it2->second;\n\t\t\t\telse\n\t\t\t\t\tmaps[mt][sss.str()] += it2->second;\n\t\t\t}\n\t\t}\n\t}\n\t//alloy particles\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tunsigned howMany = it->getBAtoms();\n\t\tif(howMany)\n\t\t{\n\t\t\tKernel::M_TYPE mt = it->getMaterial();\n\t\t\tKernel::P_TYPE pt = Domains::global()->PM()->getMaterial(mt)._alloy;\n\t\t\tstd::stringstream ss;\n\t\t\tss << Kernel::Event::getEName(Kernel::Event::MOBILEPARTICLE) << \"/\" << Domains::global()->PM()->getParticleName(mt, pt);\n\t\t\tif(maps[mt].find(ss.str()) == maps[mt].end())\n\t\t\t\tmaps[mt][ss.str()] = it->getBAtoms();\n\t\t\telse\n\t\t\t\tmaps[mt][ss.str()] += it->getBAtoms();\n\t\t}\n\t}\n}\n\n/*\n * orig_mt: Silicon, Iron, etc...\n * pt: I_TYPE, Carbon, etc...\n * defe: <100>, Cluster, etc...\n * theMap: B2I3, I35, etc...\n * defects. false:particle, true:defects\n */\n//include alloy particles\nunsigned SimData::count(Kernel::M_TYPE orig_mt, const string &partName, const std::string &defe,\n\t\tconst string &sID, unsigned minSize, bool defects, const std::string &st) const\n{\n\tunsigned counter=0;\n\tKernel::P_TYPE names[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\tnames[mt] = Domains::global()->PM()->getParticleNumber(mt, partName);\n\tKernel::ID IDs[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\tIDs[mt] = Domains::global()->PM()->getID(mt, sID);\n\tfor(Domains::DefectIterator it = Domains::global()->beginDI(); it!= Domains::global()->endDI(); ++it)\n\t{\n\t\tKernel::M_TYPE mt = it->getElement()->getMaterial();\n\t\tKernel::P_TYPE partType = names[mt];\n\t\tvector<const OKMC::Particle *> parts = it->getParticles();\n\t\tif(parts.size() < minSize)\n\t\t\tcontinue;\n\t\tfor(vector<const OKMC::Particle *>::iterator itPart = parts.begin(); itPart!=parts.end(); ++itPart)\n\t\t{\n\t\t\tconst OKMC::Particle *pPart = *itPart;\n\t\t\tKernel::P_TYPE pt = pPart->getPType();\n\t\t\tKernel::Event::E_TYPE ev = pPart->getDefect()->getEType();\n\t\t\tKernel::M_TYPE mt = pPart->getElement()->getMaterial();\n\t\t\tOKMC::Cluster *pMC = dynamic_cast<OKMC::Cluster *>(pPart->getDefect());\n\t\t\tOKMC::Interface *pIF = dynamic_cast<OKMC::Interface *>(pPart->getDefect());\n\t\t\tOKMC::MobileParticle *pMP = dynamic_cast<OKMC::MobileParticle *>(pPart->getDefect());\n\t\t\tif(Domains::global()->PM()->getMaterial(mt)._binary == false && (pMC || pIF))\n\t\t\t\tpt = Domains::global()->PM()->getParticleForCluster(mt, pt, Kernel::POS_0);\n\t\t\tbool isMt = orig_mt == mt;\n\t\t\tbool isPart = pt == partType;\n\t\t\tbool isGenericDefect  = Kernel::Event::getEName(ev) == defe;\n\t\t\tbool isExtendedDefect = pMC && it->getDomain()->_pClPar->getParams(mt, pMC->getEDType())->_name == defe;\n\t\t\tbool isID = IDs[mt] == pPart->getDefect()->getID();\n\t\t\tbool isGenericState = st.empty();\n\t\t\tbool isState = (pMP && st == Domains::global()->PM()->getStateName(mt, pMP->getPType(), pMP->getState()));\n\n\t\t\tif( (orig_mt == Kernel::MAX_MATERIALS || isMt)   &&\n\t\t\t\t\t(partName.empty() || isPart) &&\n\t\t\t\t\t(defe.empty()     || isGenericDefect || isExtendedDefect) &&\n\t\t\t\t\t(sID.empty()      || isID) &&\n\t\t\t\t\t(isState          || isGenericState))\n\t\t\t{\n\t\t\t\tcounter++;\n\t\t\t\tif(defects)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t//alloy particles\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tKernel::M_TYPE mt = it->getMaterial();\n\t\tKernel::P_TYPE partType = names[mt];\n\t\tunsigned howMany = it->getBAtoms();\n\t\tif(howMany)\n\t\t{\n\t\t\tKernel::M_TYPE mt = it->getMaterial();\n\t\t\tKernel::P_TYPE pt = Domains::global()->PM()->getMaterial(mt)._alloy;\n\t\t\tif(Domains::global()->PM()->getMaterial(mt)._binary == false)\n\t\t\t\tpt = Domains::global()->PM()->getParticle(mt, pt, Kernel::POS_0);\n\t\t\tKernel::Event::E_TYPE ev = Kernel::Event::MOBILEPARTICLE;\n\t\t\tbool isMt = orig_mt == mt;\n\t\t\tbool isPart = pt == partType;\n\t\t\tbool isGenericDefect  = Kernel::Event::getEName(ev) == defe;\n\n\t\t\tif( (orig_mt == Kernel::MAX_MATERIALS || isMt)   &&\n\t\t\t\t\t(partName.empty() || isPart) &&\n\t\t\t\t\t(defe.empty()     || isGenericDefect))\n\t\t\t{\n\t\t\t\tcounter+= it->getBAtoms();\n\t\t\t\tif(defects)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn counter;\n}\n\n//count number of positions in the simulation\nunsigned SimData::countPos(Kernel::M_TYPE orig_mt, const std::string &spos,\n\t\tconst std::string &defe, const std::string &sID) const\n{\n\tunsigned counter=0;\n\tKernel::P_POS positions[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\tpositions[mt] = Domains::global()->PM()->getPositionNumber(mt, spos);\n\tKernel::ID IDs[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\t\tIDs[mt] = Domains::global()->PM()->getID(mt, sID);\n\n\tfor(Domains::DefectIterator it = Domains::global()->beginDI(); it!= Domains::global()->endDI(); ++it)\n\t{\n\t\tKernel::M_TYPE mt = it->getElement()->getMaterial();\n\t\tKernel::ID theID = it->getID();\n\t\tbool isMt = orig_mt == mt;\n\t\tKernel::Event::E_TYPE ev = (*it)->getEType();\n\t\tbool isGenericDefect  = Kernel::Event::getEName(ev) == defe;\n\t\tconst OKMC::Cluster *pMC = dynamic_cast<const OKMC::Cluster *>(*it);\n\t\tbool isExtendedDefect = pMC && it->getDomain()->_pClPar->getParams(mt, pMC->getEDType())->_name == defe;\n\t\tbool isID = IDs[mt] == (*it)->getID();\n\t\tconst OKMC::MobileParticle *pMP = dynamic_cast<const OKMC::MobileParticle *>(*it);\n\t\t\n\t\tif(pMP)\n\t\t{\n\t\t\tif( (orig_mt == Kernel::MAX_MATERIALS || isMt) &&\n\t\t        \t Domains::global()->PM()->getPPos(pMP->getPType()) == positions[mt] &&\n\t\t        \t (defe.empty()     || isGenericDefect || isExtendedDefect) &&\n\t\t        \t (sID.empty()      || isID)\n\t\t        \t )\n\t\t        \t \tcounter++;\n\t\t}\n\t\telse\n\t\t\tfor(map<Kernel::P_POS, unsigned>::iterator posIt=theID._pos.begin(); posIt!=theID._pos.end(); ++posIt)\n\t\t\t\tif( (orig_mt == Kernel::MAX_MATERIALS || isMt) &&\n\t\t        \t posIt->first == positions[mt] &&\n\t\t        \t (defe.empty()     || isGenericDefect || isExtendedDefect) &&\n\t\t        \t (sID.empty()      || isID)\n\t\t        \t )\n\t\t        \t \tcounter += posIt->second;\n\t}\n\treturn counter;\n}\n\n//computes the average radius of the specified defects\ndouble SimData::radius(Kernel::M_TYPE orig_mt, const string &defect, const string &sID, double minRad) const\n{\n\tunsigned count = 0;\n\tdouble radius = 0;\n\n\tKernel::ID IDs[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\tIDs[mt] = Domains::global()->PM()->getID(mt, sID);\n\n\tfor(Domains::DefectIterator it = Domains::global()->beginDI(); it!= Domains::global()->endDI(); ++it)\n\t{\n\t\tKernel::M_TYPE mt = it->getElement()->getMaterial();\n\t\tconst OKMC::Cluster *pMC = dynamic_cast<const OKMC::Cluster *>(*it);\n\t\tbool isMt = orig_mt == mt;\n\t\tbool isDefect = pMC && it->getDomain()->_pClPar->getParams(mt, pMC->getEDType())->_name == defect;\n\t\tbool isID = IDs[mt] == it->getID();\n\t\tif( (orig_mt == Kernel::MAX_MATERIALS || isMt)   && pMC &&\n\t\t\t(defect.empty()   || isDefect) &&\n\t\t\t(sID.empty()      || isID))\n\t\t{\n\t\t\tdouble rad = pMC->getRadius();\n\t\t\tif(rad >= minRad)\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\tradius += rad;\n\t\t\t}\n\t\t}\n\t}\n\treturn (count ? radius / count : 0);\n}\n\n//static\n//given a defect list, it fills it into a vector with the defect types.\nvoid SimData::createDefectList(Kernel::M_TYPE mt, const string &def, vector<unsigned> &defects)\n{\n\tvector<string> texts;\n\tIO::ParameterManager::getTokens(def, ',', texts);\n\tIO::ParameterManager * pPM = Domains::global()->PM();\n\tfor(vector<string>::iterator it=texts.begin(); it!=texts.end(); ++it)\n\t{\n\t\tint defect = pPM->getEDType(mt, *it);\n\t\tif(defect == -1)\n\t\t\tERRORMSG(\"defect name '\" << *it << \"'not recognized in material\" << pPM->getMaterialName(mt));\n\t\tdefects.push_back(defect);\n\t}\n}\n\n//returns histograms\n//for mean values, a tcl script can be used\nstring SimData::getHistogram(Kernel::M_TYPE orig_mt, const string &orig_defect) const\n{\n\tmap<string, unsigned> histogram;\n\n\tvector<unsigned> defects;\n\tcreateDefectList(orig_mt, orig_defect, defects);\n\tfor(Domains::DefectIterator it = Domains::global()->beginDI(); it!= Domains::global()->endDI(); ++it)\n\t{\n\t\tKernel::M_TYPE mt = it->getElement()->getMaterial();\n\t\tconst OKMC::Cluster *pMC = dynamic_cast<const OKMC::Cluster *>(*it);\n\n\t\tif( pMC && orig_mt == mt && std::find(defects.begin(), defects.end(), pMC->getEDType()) != defects.end())\n\t\t{\n\t\t\tKernel::ID id = pMC->getID();\n\t\t\tstring name = pMC->name();\n\t\t\tif(histogram.find(name) == histogram.end())\n\t\t\t\thistogram[name] = 1;\n\t\t\telse\n\t\t\t\thistogram[name]++;\n\t\t}\n\t}\n\n\tstd::stringstream ss;\n\tfor(map<string, unsigned>::const_iterator it=histogram.begin(); it!=histogram.end(); ++it)\n\t\tss << it->first << \" \" << it->second << std::endl;\n\treturn ss.str();\n}\n\n// Returns the dose implanted in the material as #FP / #atoms\n// Count only the V's\ndouble SimData::getDose(Kernel::M_TYPE mt) \n{\n    IO::ParameterManager * pPM = Domains::global()->PM();\n    map<string, unsigned> theMap = Domains::global()->client()->getCreatedDefects(mt);\n    unsigned nFP(0); \n    unsigned nAtm(0);\n    for(map<string, unsigned>::const_iterator it = theMap.begin(); it != theMap.end(); ++it)   \n    {\n        if(pPM->getDefectType(it->first, mt) == Kernel::Event::MOBILEPARTICLE && \n               it->first == \"V\")                    \n                nFP += it->second;\n        else\n        {\n            Kernel::ID theID = pPM->getID(mt, it->first);\n            for(map<Kernel::P_TYPE, unsigned>::const_iterator pIt = theID._pt.begin();\n                    pIt != theID._pt.end(); ++pIt)            \n                if(pPM->getParticleName(mt, pIt->first) == \"V\")\n                    nFP += it->second * pIt->second;        \n        }\n    }\n    for(Domains::MeshElementIterator it = Domains::global()->beginMEI(); it != Domains::global()->endMEI(); ++it)\n        nAtm += it->getMaterial() == mt ? it->getAtoms() : 0;\n    return double(nFP) / double(nAtm);\n}\n\n//obtains macroscopic diffusivity\ndouble SimData::getDiffusivity(const string &mate, const string &name, bool bMacro) const\n{\n\tKernel::M_TYPE mt = Domains::global()->PM()->getMaterialNumber(mate);\n\tif(mt == Kernel::MAX_MATERIALS)\n\t\tERRORMSG(\"Material \" << mate << \" not recognized.\");\n\tKernel::P_TYPE pt = Domains::global()->PM()->getParticleNumber(mt, name);\n\tif(pt == Kernel::UNDEFINED_TYPE)\n\t\tERRORMSG(\"Particle name not recognized\");\n\tif(pt < 2)\n\t\tERRORMSG(\"I and V particles not allowed\");\n\tif(Domains::global()->PM()->getMaterial(mt)._binary == false && bMacro)\n\t\tpt = Domains::global()->PM()->getFamily(pt);\n\tif(bMacro && pt >= Domains::global()->PM()->getNFamilies())\n\t\tERRORMSG(\"Species needs to be simple when specifying macroscopic\");\n\n\n\tdouble r2 = 0;\n\tunsigned howMany = 0;\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tif(mt != it->getMaterial())\n\t\t\tcontinue;\n\t\tOKMC::Particle *part = it->getFirstPart();\n\t\twhile(part)\n\t\t{\n\t\t\tif( (bMacro && Domains::global()->PM()->getFamily(part->getPType()) == pt) ||\n\t\t\t\t\tpt == part->getPType())\n\t\t\t{\n\t\t\t\tKernel::Coordinates r=part->getCoordinates() - part->getOrig();\n\t\t\t\tr2 += r*r;\n\t\t\t\thowMany++;\n\t\t\t}\n\t\t\tpart = part->getNext();\n\t\t}\n\t}\n\tdouble time = Domains::global()->data()->getDeltaTime();\n\tif(time && howMany)\n\t\treturn 1./6.*r2*1e-14/howMany/time;\n\telse\n\t{\n\t\tWARNINGMSG(\"No time passed or no particles found for diffusion calculation, returning 0\");\n\t\treturn 0;\n\t}\n}\n\nIO::OutDataVectorC<double> SimData::getJumps(const string &name) const\n{\n\tstd::vector<std::string> tokens;\n\tIO::ParameterManager *PM=Domains::global()->PM();\n\tPM->getTokens(name,'_',tokens);\n\tKernel::P_TYPE names[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\tnames[mt] = Domains::global()->PM()->getParticleNumber(mt, name);\n\tIO::OutDataVectorC<double> odv3;\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tKernel::M_TYPE mt = (*it)->getMaterial();\n\t\tKernel::P_TYPE pt = names[mt];\n\t\tunsigned state = PM->getStateNumber(mt, pt, tokens[1] );\n\t\tCoordinates m,M;\n\t\tit->getCorners(m, M);\n\t\todv3.push(3, m, M, double(it->getHops(pt, state)) );\n\t}\n\treturn collapse(odv3);\n}\n\n//takes a 3D information field and \"collapses\" it into 2D or 1D\n//Assumes that the total mesh is a uniform tensor mesh even if there are several domains\nIO::OutDataVectorC<double> SimData::collapse(const IO::OutDataVectorC<double> &odv_temp) const\n{\n\tIO::OutDataVectorC<double> odv_c;\n\tIO::OutDataVectorC<double> odv;\n\n\t//filter for min, max\n\tfor(IO::OutDataVectorC<double>::const_iterator it = odv_temp.begin(); it!=odv_temp.end(); ++it)\n\t\tif(it->_cm.isIntoEqual(_min, _max) && it->_cM.isIntoEqual(_min, _max))\n\t\t\todv.push_back(*it);\n\n\tif(_dim == 3)\n\t\treturn odv;\n\n\tfloat eps = 1e-2;\n\tif(_dim == 2) //collapse z\n\t{\n\t\t//stores all x and all y\n\t\tvector<float> linesX = Domains::global()->getDomain(0)->_pMesh->getLines(0);\n\t\tvector<float> linesY = Domains::global()->getDomain(0)->_pMesh->getLines(1);\n\n\t\tfor(vector<float>::iterator itx = linesX.begin(); itx != linesX.end()-1; ++itx)\n\t\t\tfor(vector<float>::iterator ity = linesY.begin(); ity != linesY.end()-1; ++ity)\n\t\t\t{\n\t\t\t\tdouble howMany = 0;\n\t\t\t\tdouble accumulated = 0;\n\t\t\t\tfor(IO::OutDataVectorC<double>::const_iterator it=odv.begin(); it!=odv.end(); ++it)\n\t\t\t\t\tif( it->_cm._x < *itx + eps  && it->_cm._x > *itx - eps &&\n\t\t\t\t\t\tit->_cm._y < *ity + eps  && it->_cm._y > *ity - eps)\n\t\t\t\t\t{\n\t\t\t\t\t\thowMany++;\n\t\t\t\t\t\taccumulated += it->_data;\n\t\t\t\t\t}\n\t\t\t\todv_c.push(2, Coordinates(*itx, *ity, 0), Coordinates(*(itx+1), *(ity+1), 0), howMany? accumulated/howMany:0);\n\t\t\t}\n\t}\n\tif(_dim == 1)\n\t{\n\t\tvector<float> linesX = Domains::global()->getDomain(0)->_pMesh->getLines(0);\n\t\tfor(vector<float>::iterator itx = linesX.begin(); itx != linesX.end()-1; ++itx)\n\t\t{\n\t\t\tdouble howMany = 0;\n\t\t\tdouble accumulated = 0;\n\t\t\tfor(IO::OutDataVectorC<double>::const_iterator it=odv.begin(); it!=odv.end(); ++it)\n\t\t\t{\n\t\t\t\tif( it->_cm._x < *itx + eps  && it->_cm._x > *itx - eps)\n\t\t\t\t{\n\t\t\t\t\thowMany++;\n\t\t\t\t\taccumulated += it->_data;\n\t\t\t\t}\n\t\t\t}\n\t\t\todv_c.push(1, Coordinates(*itx, 0, 0), Coordinates(*(itx+1), 0, 0),  howMany? accumulated/howMany:0);\n\t\t}\n\t}\n\t//dim == 0.\n\tif(_dim == 0)\n\t{\n\t\tdouble howMany = 0;\n\t\tdouble accumulated = 0;\n\t\tfor(IO::OutDataVectorC<double>::const_iterator it=odv.begin(); it!=odv.end(); ++it)\n\t\t{\n\t\t\thowMany++;\n\t\t\taccumulated += it->_data;\n\t\t}\n\t\todv_c.push(0, Coordinates(), Coordinates(), howMany? accumulated/howMany:0);\n\t}\n\treturn odv_c;\n}\n\n//takes a 3D particle field and \"collapses\" it into 3,2,1 or 0D creating concentrations.\nIO::OutDataVectorC<double> SimData::collapse(const IO::OutDataVectorP<double> &odv_temp) const\n{\n\tIO::OutDataVectorC<double> odv_out;\n\tIO::OutDataVectorP<double> odv;\n\n\tunsigned n[3];\n\tn[0] = round((_max._x - _min._x) / _odelta[0]);\n\tn[1] = round((_max._y - _min._y) / _odelta[1]);\n\tn[2] = round((_max._z - _min._z) / _odelta[2]);\n\tfloat delta[3] = {  (_max._x - _min._x)/n[0], (_max._y - _min._y)/n[1], (_max._z - _min._z)/n[2] };\n\tdouble factor = 0;\n\n\tfor(IO::OutDataVectorP<double>::const_iterator it = odv_temp.begin(); it!=odv_temp.end(); ++it)\n\t\t\tif(it->_coords.isIntoEqual(_min, _max))\n\t\t\t\todv.push_back(*it);\n\n\tif(_dim == 3)\n\t{\n\t\tfactor = 1e21/(delta[0]*delta[1]*delta[2]);\n\t\tfor(unsigned nx=0; nx < n[0]; ++nx)\n\t\t\tfor(unsigned ny=0; ny < n[1]; ++ny)\n\t\t\t\tfor(unsigned nz=0; nz < n[2]; ++nz)\n\t\t\t\t\todv_out.push(_dim,\n\t\t\t\t\t\t\tCoordinates(_min._x + nx    *delta[0], _min._y + ny    *delta[1], _min._z + nz    *delta[2]),\n\t\t\t\t\t\t\tCoordinates(_min._x + (nx+1)*delta[0], _min._y + (ny+1)*delta[1], _min._z + (nz+1)*delta[2]), 0.);\n\t}\n\tif(_dim == 2)\n\t{\n\t\tfactor = 1e21/(delta[0]*delta[1]*(_max._z - _min._z));\n\t\tfor(unsigned nx=0; nx < n[0]; ++nx)\n\t\t\tfor(unsigned ny=0; ny < n[1]; ++ny)\n\t\t\t\todv_out.push(_dim, Coordinates(_min._x + nx    *delta[0], _min._y + ny    *delta[1], 0),\n\t\t\t\t\t\t           Coordinates(_min._x + (nx+1)*delta[0], _min._y + (ny+1)*delta[1], 0), 0.);\n\t}\n\tif(_dim == 1)\n\t{\n\t\tfactor = 1e21/(delta[0]*(_max._y - _min._y)*(_max._z - _min._z));\n\t\tfor(unsigned nx=0; nx < n[0]; ++nx)\n\t\t\todv_out.push(_dim, Coordinates(_min._x + nx    *delta[0], 0, 0),\n\t\t\t\t\t\t\t   Coordinates(_min._x + (nx+1)*delta[0], 0, 0), 0.);\n\t}\n\tif(_dim == 0)\n\t{\n\t\tfactor = 1e21/((_max._x - _min._x)*(_max._y - _min._y)*(_max._z - _min._z));\n\t\todv_out.push(_dim, Coordinates(), Coordinates(), 0.);\n\t}\n\tfor(IO::OutDataVectorP<double>::const_iterator it=odv.begin(); it!=odv.end(); ++it)\n\t\todv_out[toODVC(delta, n, it->_coords)]._data += it->_data * factor;\n\n\treturn odv_out;\n}\n\nunsigned SimData::toODVC(float delta[3], unsigned n[3], const Coordinates &c) const\n{\n\tunsigned ix = (c._x - _min._x) / delta[0];\n\tunsigned iy = (c._y - _min._y) / delta[1];\n\tunsigned iz = (c._z - _min._z) / delta[2];\n\tswitch(_dim)\n\t{\n\tcase 3:\n\t\treturn ix*n[2]*n[1] + iy*n[2] + iz;\n\tcase 2:\n\t\treturn ix*n[1] + iy;\n\tcase 1:\n\t\treturn ix;\n\tcase 0:\n\t\treturn 0;\n\tdefault:\n\t\tERRORMSG(\"Incorrect dimension!\");\n\t\treturn 0;\n\t}\n}\n\nIO::OutDataVectorC<double> SimData::getProfileMobile(const string &name, const string &st, const string &mate) const\n{\n\n\tIO::ParameterManager *PM=Domains::global()->PM();\n\tdouble time = Domains::global()->data()->getDeltaTime();\n\tIO::OutDataVectorC<double> odv;\n\tbool bAll = st.empty();\n\tKernel::M_TYPE mt = Domains::global()->PM()->getMaterialNumber(mate);\n\tbool bParticleDefined = false;\n\tKernel::P_TYPE names[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\tnames[mt] = Domains::global()->PM()->getParticleNumber(mt, name);\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tif (mate.empty()) mt = it->getMaterial();\n\t\tif(mt != it->getMaterial())\n\t\t\tcontinue;\n\t\tKernel::P_TYPE pt = names[it->getMaterial()];\n\t\tif(pt == Kernel::UNDEFINED_TYPE || Domains::global()->PM()->isGasLike(mt)) //in gas or similar..\n\t\t\tcontinue;\n\t\tunsigned state = bAll? 0: PM->getStateNumber(mt, pt, st);\n\t\tif(state == Kernel::UNDEFINED_STATE)\n\t\t\tcontinue;\n\t\tbParticleDefined = true;\n\t\tCoordinates coordm ,coordM;\n\t\tit->getCorners(coordm, coordM);\n\t\tunsigned endDoWhile = (bAll? PM->getStates(mt, pt): state);\n\t\tdouble temp  = 0;\n\t\tdo\n\t\t{\n\t\t\tdouble freq = Domains::global()->PM()->getMigrationRate(*it, pt, state);\n\t\t\tunsigned jumps = it->getHops(pt, state);\n\t\t\ttemp += jumps? double(jumps)/(time*freq*it->getVolume()*1e-21) : 0.;\n\t\t\tstate++;\n\t\t} while(state < endDoWhile);\n\t\todv.push(3, coordm, coordM, temp);\n\t}\n\tif(bParticleDefined == false)\n\t\tERRORMSG(\"Particle \" << name << \" does not seem to be defined in this materials...\");\n\treturn collapse(odv);\n}\n\nIO::OutDataVectorC<double> SimData::getParticleProfile(const string &name, const string &def,\n\t\tconst string &st, const string &mate) const\n{\n\tIO::OutDataVectorP<double> odvp;\n\tIO::OutDataVectorC<double> odvc;\n\n\tKernel::M_TYPE mt = Domains::global()->PM()->getMaterialNumber(mate);\n\tKernel::P_TYPE names[Kernel::MAX_MATERIALS];\n\tfor(unsigned mt=0; mt < Domains::global()->PM()->getNMaterials(); ++mt)\n\t\tnames[mt] = Domains::global()->PM()->getParticleNumber(mt, name);\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tif (!mate.size()) mt = it->getMaterial();\n\t\tif(mt != it->getMaterial())\n\t\t\tcontinue;\n\t\tKernel::P_TYPE pt = names[it->getMaterial()];\n\t\tif(pt == Kernel::UNDEFINED_TYPE)\n\t\t\tcontinue;\n\t\tif (!Domains::global()->PM()->isImpurity(mt,pt) && Domains::global()->PM()->isAmorphous((*it)->getMaterial())) //No counting Is nor Vs for amorhpus MEs\n\t\t\tcontinue;\n\t\tKernel::P_TYPE alloy_pt = Domains::global()->PM()->getMaterial((it->getMaterial()))._alloy;\n\t\tif(Domains::global()->PM()->getMaterial(mt)._binary == false)\n\t\t\talloy_pt = Domains::global()->PM()->getParticle(mt, alloy_pt, Kernel::POS_0);\n\t\tif(alloy_pt == pt)\n\t\t{\n\t\t\tCoordinates m, M;\n\t\t\tit->getCorners(m, M);\n\t\t\todvc.push(3, m, M, float(it->getBAtoms()) / float(it->getVolume()) * 1e21);\n//\t\t\todvc.push(3, m, M, it->getAlloyFraction() * Domains::global()->PM()->getMaterial(it->getMaterial())._densityAlloyCm3);\n\t\t}\n\t\telse if(name.empty())\n\t\t{\n\t\t\tCoordinates m, M;\n\t\t\tit->getCorners(m, M);\n\t\t\todvc.push(3, m, M, float(it->getAAtoms()) / float(it->getVolume()) * 1e21);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOKMC::Particle *pPart = it->getFirstPart();\n\t\t\tunsigned stN = Domains::global()->PM()->getStateNumber(it->getMaterial(), pt, st);\n\n\t\t\twhile(pPart)\n\t\t\t{\n\t\t\t\tKernel::Event::E_TYPE ev = pPart->getDefect()->getEType();\n\t\t\t    OKMC::Cluster *pMC = dynamic_cast<OKMC::Cluster *>(pPart->getDefect());\n\t\t\t    OKMC::Interface *pIF = dynamic_cast<OKMC::Interface *>(pPart->getDefect());\n\t\t\t    Kernel::P_TYPE thisPt = pPart->getPType();\n\t\t\t    if(Domains::global()->PM()->getMaterial(mt)._binary == false && (pMC || pIF))\n\t\t\t\t\tthisPt = Domains::global()->PM()->getParticleForCluster(mt, thisPt, Kernel::POS_0);\n\t\t\t    bool isPart = thisPt == pt;\n\t\t\t    bool isGenericDefect  = Kernel::Event::getEName(ev) == def;\n\t\t\t    bool isExtendedDefect = pMC && it->getDomain()->_pClPar->getParams(mt, pMC->getEDType())->_name == def;\n\t\t\t    bool isSt = pPart->getDefect()->getState() == stN;\n\t\t\t    if(isPart &&\n\t\t\t      (def.empty() || isGenericDefect || isExtendedDefect) &&\n\t\t\t      (st.empty()  || isSt))\n\t\t\t    \todvp.push(3, pPart->getCoordinates(), 1.);\n\t\t\t\t\t\tpPart = pPart->getNext();\n\t\t\t}\n\t\t}\n\t}\n\treturn odvc.size()? collapse(odvc) : collapse(odvp);\n}\n\nIO::OutDataVectorC<double> SimData::getAtomProfile(const string &name, const string &mate) const\n{\n\tIO::OutDataVectorC<double> odv;\n\n\tKernel::M_TYPE mt = Domains::global()->PM()->getMaterialNumber(mate);\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tif (!mate.size()) mt = it->getMaterial();\n\t\tif(mt != it->getMaterial())\n\t\t\tcontinue;\n\t\tCoordinates m, M;\n\t\tit->getCorners(m, M);\n\t\tif(name == \"A.atoms\")\n\t\t\todv.push(3, m, M, it->getAAtoms());\n\t\telse\n\t\t\todv.push(3, m, M, it->getBAtoms());\n\t}\n\treturn collapse(odv);\n}\n\nIO::OutDataVectorC<double> SimData::getBalance(const string &name, const string &mate) const\n{\n\tIO::OutDataVectorC<double> odv;\n\n\tKernel::M_TYPE mt = Domains::global()->PM()->getMaterialNumber(mate);\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tif (!mate.size()) mt = it->getMaterial();\n\t\tif(mt != it->getMaterial())\n\t\t\tcontinue;\n\t\tCoordinates m, M;\n\t\tit->getCorners(m, M);\n\t\tif(name == \"A.atoms\")\n\t\t\todv.push(3, m, M, it->_ABalance);\n\t\telse\n\t\t\todv.push(3, m, M, it->_BBalance);\n\t}\n\treturn collapse(odv);\n}\n\nIO::OutDataVectorC<double> SimData::getLKMCProfile(const string &name) const {\n\tIO::OutDataVectorP<double> odv;\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tLKMC::LatticeAtom *pLA = static_cast<LKMC::LatticeAtom *>(it->getFirstLS());\n\n\t\twhile (pLA) {\n\t\t\t/*if (name == \"lkmc.defects\" && pLA->getDefective()) {\n\t\t\t\todv.push(3, pLA->getCoordinates(), 1.);\n\t\t\t}*/\n\t\t\tif (name == \"lkmc.ac\" && !pLA->getPerformed()) {\n\t\t\t\tfor (unsigned i = 0; i < pLA->first(); ++i) {\n\t\t\t\t\tif (pLA->getNeighbor(i) && pLA->getNeighbor(i)->getPerformed()) {\n\t\t\t\t\t\todv.push(3, pLA->getCoordinates(), 1.);\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tpLA = static_cast<LKMC::LatticeAtom *>(pLA->getNext());\n\t\t}\n\t}\n\treturn collapse(odv);\n}\n\nIO::OutDataVectorC<double> SimData::getStrain(const string &name) const\n{\n\tIO::OutDataVectorC<double> odv;\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tCoordinates m, M;\n\t\tit->getCorners(m, M);\n\t\tif(name == \"xx\")\n\t\t\todv.push(3, m, M, it->strain_xx());\n\t\telse if(name == \"yy\")\n\t\t\todv.push(3, m, M, it->strain_yy());\n\t\telse if(name == \"zz\")\n\t\t\todv.push(3, m, M, it->strain_zz());\n\t\telse if(name == \"xy\")\n\t\t\todv.push(3, m, M, it->strain_xy());\n\t\telse if(name == \"xz\")\n\t\t\todv.push(3, m, M, it->strain_xz());\n\t\telse if(name == \"yz\")\n\t\t\todv.push(3, m, M, it->strain_yz());\n\t}\n\treturn collapse(odv);\n}\n\nIO::OutDataVectorC<double> SimData::getStress(const string &name) const\n{\n\tIO::OutDataVectorC<double> odv;\n\tfor(Domains::MeshElementIterator it = Domains::global()->beginMEI(); it != Domains::global()->endMEI(); ++it)\n\t{\n\t\tCoordinates m, M;\n\t\tit->getCorners(m, M);\n\t\tif(name == \"xx\")\n\t\t\todv.push(3, m, M, it->stress_xx());\n\t\telse if(name == \"yy\")\n\t\t\todv.push(3, m, M, it->stress_yy());\n\t\telse if(name == \"zz\")\n\t\t\todv.push(3, m, M, it->stress_zz());\n\t\telse if(name == \"xy\")\n\t\t\todv.push(3, m, M,  it->stress_xy());\n\t\telse if(name == \"xz\")\n\t\t\todv.push(3, m, M, it->stress_xz());\n\t\telse if(name == \"yz\")\n\t\t\todv.push(3, m, M,  it->stress_yz());\n\t}\n\treturn collapse(odv);\n}\n\nIO::OutDataVectorC<double> SimData::getElectrostatic(const string &name) const\n{\n\tIO::OutDataVectorC<double> odv;\n\tfor(Domains::MeshElementIterator it = Domains::global()->beginMEI(); it != Domains::global()->endMEI(); ++it)\n\t{\n\t\tCoordinates m, M;\n\t\tit->getCorners(m, M);\n\t\tif(name == \"potential\") {\n\t\t\todv.push(3, m, M, it->electrostaticPotential());\n\t\t}\n\t\telse if (name == \"electron.density\") {\n\t\t\tKernel::MeshElement *pME = const_cast<Kernel::MeshElement *>(*it);\n\t\t\tstd::set<Electrostatics::MeshNode *> s;\n\n\t\t\tKernel::Mesh *pMesh = it->getDomain()->_pMesh;\n\t\t\tpMesh->getNodesFromElement(pME, s);\n\n\t\t\tif (s.empty()) {\n\t\t\t\tERRORMSG(\"SimData::getElectrostatic: cannot find nodes of element \" << it->getIndex());\n\t\t\t}\n\n\t\t\tdouble dat  = 0;\n\t\t\tfor (std::set<Electrostatics::MeshNode *>::const_iterator i = s.begin(); i != s.end(); ++i) {\n\t\t\t\tdat  += (*i)->getElectronDensity();\n\t\t\t}\n\t\t\todv.push(3, m, M, dat / static_cast<double>(s.size()));\n\t\t}\n\t\telse if (name == \"hole.density\") {\n\t\t\tKernel::MeshElement *pME = const_cast<Kernel::MeshElement *>(*it);\n\t\t\tstd::set<Electrostatics::MeshNode *> s;\n\n\t\t\tKernel::Mesh *pMesh = it->getDomain()->_pMesh;\n\t\t\tpMesh->getNodesFromElement(pME, s);\n\n\t\t\tif (s.empty()) {\n\t\t\t\tERRORMSG(\"SimData::getElectrostatic: cannot find nodes of element \" << it->getIndex());\n\t\t\t}\n\n\t\t\tdouble dat  = 0;\n\t\t\tfor (std::set<Electrostatics::MeshNode *>::const_iterator i = s.begin(); i != s.end(); ++i) {\n\t\t\t\tdat  += (*i)->getHoleDensity();\n\t\t\t}\n\t\t\todv.push(3, m, M, dat / static_cast<double>(s.size()));\n\t\t}\n\t\telse if (name == \"bandgap\") {\n\t\t\todv.push(3, m, M, it->bandGap());\n\t\t}\n\t\telse if (name == \"conduction.bandedge\") {\n\t\t\t// 0.5 * _Eg(i) - _psi(i)\n\t\t\todv.push(3, m, M, 0.5 * it->bandGap() - it->electrostaticPotential());\n\t\t}\n\t\telse if (name == \"valence.bandedge\") {\n\t\t\t// - 0.5 * _Eg(i) - _psi(i)\n\t\t\todv.push(3, m, M, - 0.5 * it->bandGap() - it->electrostaticPotential());\n\t\t}\n\t}\n\treturn collapse(odv);\n}\n\nstd::vector<float> SimData::getMixEnthalpy(const std::string &name) const\n{\n\tstd::vector<float> ov(1001);\n\tIO::FileParameters * pPar =  Domains::global()->getFileParameters();\n\tIO::Polynomial out = pPar->getPolynomial(name + \"/Models/mixing.enthalpy\");\n\tfor(unsigned i = 0; i < ov.size(); i++)\n\t{\n\t\tfloat x = float(i) / 1000.;\n\t\tov[i] = out.getValue(x);\n\t}\n\treturn ov;\n}\n\nstring SimData::getCoordination(double r, const Kernel::Coordinates &c, int typ) const\n{\n\tKernel::Coordinates m(-r-.5, -r-.5, -r-.5), M(r+.5,r+.5,r+.5), rel(0,0,0);\n\tm += c ;\n\tM += c;\n\tstd::vector<LKMC::Lattice::LatticeInformation> neis; //type, coordinates\n\tif(!Domains::global()->client()->isInCell(c))\n\t\tERRORMSG(\"extract: Coordinate \" << c << \" is not in this cell\");\n\tKernel::Domain *pDomain = Domains::global()->getDomain(c);\n\tKernel::MeshElement *pEle = pDomain->_pMesh->getElement(pDomain->_pMesh->getIndexFromCoordinates(c));\n\tKernel::M_TYPE mt = pEle->getMaterial();\n\tif(mt == Kernel::MAX_MATERIALS)\n\t\tERRORMSG(\"Material \" << Domains::global()->PM()->getMaterialName(pEle->getMaterial()) << \" does not define a material to be transformed into\");\n\tif(!pDomain->_pLat[mt])\n\t\tERRORMSG(\"Material \" << Domains::global()->PM()->getMaterialName(mt) << \" does not have a defined lattice!\");\n\tpDomain->_pLat[mt]->fill(m, M, neis, false);\n\tLOWMSG(\"Found \" << neis.size() << \" atoms\\n\");\n\tstd::multimap<double, int> myMap;  //dist, atom_type\n\tdouble minDist = 1e57;\n\tint atomType = 0;\n\tfor(std::vector<LKMC::Lattice::LatticeInformation>::iterator it=neis.begin(); it<neis.end(); ++it)\n\t{\n\t\tdouble dist = std::sqrt(\n\t\t\t\t(it->_coords._x - c._x)*(it->_coords._x - c._x) +\n\t\t\t\t(it->_coords._y - c._y)*(it->_coords._y - c._y) +\n\t\t\t\t(it->_coords._z - c._z)*(it->_coords._z - c._z));\n\t\tif(typ == -1 || typ == int(it->_type))\n\t\t\tif(dist < minDist)\n\t\t\t{\n\t\t\t\tminDist = dist;\n\t\t\t\tatomType = it->_type;\n\t\t\t\trel = it->_coords;\n\t\t\t}\n\t}\n\tLOWMSG(\"Taking origin at atom \" << rel << \" of type \" << atomType);\n\tLOWMSG(\"Dist   Typ H0  H1  H2\");\n\tfor(std::vector<LKMC::Lattice::LatticeInformation>::iterator it=neis.begin(); it<neis.end(); ++it)\n\t{\n\t\tdouble dist = std::sqrt(\n\t\t\t\t(it->_coords._x - rel._x)*(it->_coords._x - rel._x) +\n\t\t\t\t(it->_coords._y - rel._y)*(it->_coords._y - rel._y) +\n\t\t\t\t(it->_coords._z - rel._z)*(it->_coords._z - rel._z));\n\t\tif(dist > r)\n\t\t\tcontinue;\n\t\tmyMap.insert(std::pair<double, int>(dist, it->_type));  //dist atom_type\n\t}\n\tint howMany[3] = { 0, 0, 0 };\n\tstd::stringstream ss;\n\tfor(std::multimap<double, int>::iterator it=myMap.begin(); it!=myMap.end(); ++it)\n\t{\n\t\thowMany[it->second]++;\n\t\tss << std::right << setw(6) << std::setprecision(3) << it->first << \" \" << it->second << \" \" << setw(3) <<\n\t\t\t\thowMany[0] << \" \" << setw(3) << howMany[1] << \" \" << setw(3) << howMany[2] << std::endl;\n\t}\n\treturn ss.str();\n}\n\nunsigned SimData::countDisplaced(const std::string &mate, const bool bAmorph, const float threshold) const\n{\n\tIO::ParameterManager *PM = Domains::global()->PM();\n\tunsigned counter = 0, meCounter = 0;\n\tKernel::M_TYPE mt = PM->getMaterialNumber(mate);\n\tstring name = mate + \"/Models/atomic.density\";\n\tdouble amorph = Domains::global()->getFileParameters()->getFloat(name);\n\tfloat thrs = threshold > 0 ? threshold : 1.e24;\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tif(PM->getMaterial(it->getMaterial())._basicMaterial == mt)\n\t\t{\n\t\t\tif(PM->isAmorphous(it->getMaterial()) )\n\t\t\t\tmeCounter += unsigned(amorph/1.e21*it->getVolume());\n\t\t\telse\n\t\t\t{\n\t\t\t\tOKMC::Particle *pPart = it->getFirstPart();\n\t\t\t\twhile(pPart) {\n\n\t\t\t\t\tKernel::P_TYPE pt = pPart->getPType();\n\t\t\t\t\tif( PM->getFamily(pt) == PM->getMaterial(mt)._pt[0] || PM->getFamily(pt) == PM->getMaterial(mt)._pt[1] )\n\t\t\t\t\t\tmeCounter++;\n\t\t\t\t\tpPart = pPart->getNext();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!bAmorph && double(meCounter)/it->getVolume()*1.e21 >= thrs)\n\t\t\tcounter += unsigned(amorph/1.e21*it->getVolume());\n\t\telse\n\t\t\tcounter += meCounter;\n\t\tmeCounter = 0;\n\t}\n\treturn counter;\n}\n\nIO::OutDataVectorC<double> SimData::amorphousFraction() const\n{\n\tIO::ParameterManager *PM = Domains::global()->PM();\n\tIO::OutDataVectorC<double> odvc;\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\tCoordinates m, M;\n\t\tit->getCorners(m, M);\n\t\tif( PM->isAmorphous(it->getMaterial()) )\n\t\t\todvc.push(3,m,M,1.);\n\t\telse\n\t\t\todvc.push(3,m,M,0.);\n\t}\n\n\treturn collapse(odvc);\n}\n\nIO::OutDataVectorC<double> SimData::getDamageProfile() const\n{\n\tIO::OutDataVectorC<double> odvc;\n\tIO::ParameterManager *PM = Domains::global()->PM();\n\n\tfor(Domains::MeshElementIterator it=Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t{\n\t\t\tCoordinates m, M;\n\t\t\tit->getCorners(m, M);\n\t\t\tif(Domains::global()->PM()->isAmorphous((*it)->getMaterial()))\n\t\t\t\todvc.push(3,m,M,PM->getMaterial(PM->getMaterial(it->getMaterial())._basicMaterial)._amorphThreshold);\n\t\t\telse\n\t\t\t{\n\t\t\t\tOKMC::Particle *pPart = it->getFirstPart();\n\t\t\t\tunsigned nParts = 0;\n\t\t\t\twhile(pPart) {\n\t\t\t\t\tKernel::P_TYPE pt = pPart->getPType();\n\t\t\t\t\tif( !Domains::global()->PM()->isImpurity(it->getMaterial(),pt) )\n\t\t\t\t\t\tnParts++;\n\t\t\t\t\tpPart = pPart->getNext();\n\t\t\t\t}\n\t\t\t\todvc.push(3,m,M,double(nParts)/it->getVolume()*1.e21);\n\t\t\t}\n\t}\n\n\treturn collapse(odvc);\n}\n\ndouble SimData::getDeltaTime() const\n{\n\treturn Domains::global()->getTime() - _lastTime;\n}\n\nvoid SimData::reset()\n{\n\t_lastTime = Domains::global()->getTime();\n\t// now reset the hops\n\tfor(Domains::MeshElementIterator it = Domains::global()->beginMEI(); it!=Domains::global()->endMEI(); ++it)\n\t\tit.modify()->resetHops();\n\tfor(Domains::ParticleIterator it = Domains::global()->beginPI(); it!=Domains::global()->endPI(); ++it)\n\t\tit.modify()->setOrig(it->getCoordinates());\n}\n\n//returns an y,z map with the free interface position.\nstring SimData::getFuzz() const\n{\n\tstd::stringstream ss;\n\tstd::map<std::pair<float, float>, float> interface;\n\n\tKernel::Coordinates cell, Cell;\n\tfor(Domains::MeshElementIterator mi = Domains::global()->beginMEI(); mi != Domains::global()->endMEI(); ++mi)\n\t{\n\t\tmi->getCorners(cell, Cell);\n\t\tstd::pair<float, float> yz(cell._y, cell._z);\n\t\tif( (interface.find(yz) == interface.end() || interface[yz] > cell._x) && mi->getInterfaces().size())\n\t\t\tinterface[yz] = cell._x;\n\t}\n\n\tfor(std::map<std::pair<float, float>, float>::iterator it=interface.begin(); it!=interface.end(); ++it)\n\t\tss << it->first.first << \" \" << it->first.second << \" \" << it->second << std::endl;\n\treturn ss.str();\n}\n\n}\n\n", "meta": {"hexsha": "cb2486d3be9d4f6a8c009e070ced33c8edc58480", "size": 46182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/domains/SimData.cpp", "max_stars_repo_name": "imartinbragado/MMonCa", "max_stars_repo_head_hexsha": "126744a90253d7d7884c6dc7ec100db00a106a66", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T16:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T09:13:49.000Z", "max_issues_repo_path": "src/domains/SimData.cpp", "max_issues_repo_name": "Warmshawn/MMonCa", "max_issues_repo_head_hexsha": "df279c2103484e89898ff4e81b45fb9ad43bcb9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/domains/SimData.cpp", "max_forks_repo_name": "Warmshawn/MMonCa", "max_forks_repo_head_hexsha": "df279c2103484e89898ff4e81b45fb9ad43bcb9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T03:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T10:38:14.000Z", "avg_line_length": 34.8018085908, "max_line_length": 192, "alphanum_fraction": 0.628058551, "num_tokens": 14835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.02595735503145802, "lm_q1q2_score": 0.009991301556591345}}
{"text": "// Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.\n\n// Boost Software License - Version 1.0 - August 17th, 2003\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//  Authors: Thejaka Kanewala\n//           Andrew Lumsdaine\n\n//======== Maximal Independent Set Algortihms================//\n// This implements two algorithms: 1. FIX \n// MIS algorithm 2. FIX-PQ algorithm with thread level \n// ordering (use MIS_PRIORITY preprocessor macro)\n//===========================================================//\n\n\n#ifndef BOOST_GRAPH_MIS\n#define BOOST_GRAPH_MIS\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <am++/counter_coalesced_message_type.hpp>\n#include <am++/detail/thread_support.hpp>\n\n#include <boost/parallel/append_buffer.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/parallel/algorithm.hpp> // for all_reduce\n#include <boost/graph/parallel/iteration_macros.hpp> // for all_reduce\n#include <boost/graph/parallel/thread_support.hpp> // for compare_and_swap\n#include <algorithm> // for std::min, std::max\n#include <boost/format.hpp>\n#include <iostream>\n#include <atomic>\n#include \"boost/tuple/tuple.hpp\"\n#include \"thread_pq_def.hpp\"\n#include <boost/graph/distributed/owner_defs.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\n//for profiling\n#ifdef CRAYPAT\n#include <pat_api.h>\n#endif\n\n#define MIS_UNFIX 0\n#define MIS_FIX1 1\n#define MIS_FIX0 2\n\ntypedef int state_t;\n\nnamespace boost { namespace graph { namespace distributed {\n\ntemplate<typename Graph, typename MISMap,\n\t typename IdDistribution,\n\t typename PriorityQueueGenerator = thread_priority_queue_gen,\n         typename MessageGenerator = \n           amplusplus::simple_generator<amplusplus::counter_coalesced_message_type_gen> >\nclass maximal_independent_set {\n\n  typedef maximal_independent_set<Graph, MISMap, IdDistribution,\n\t\t\t\t  PriorityQueueGenerator, MessageGenerator> \n    self_type;\n\n  typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap;\n\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef typename graph_traits<Graph>::degree_size_type Degree;\n\n  typedef append_buffer<Vertex, 10u> InitialBuffer;\n\n  typedef unsigned long distance_t;\n\n  // < Target, < < Source, Source State >, distance from min neighbor> >\n  typedef std::pair<Vertex, std::pair<Vertex, std::pair<state_t, distance_t> > > work_item_t;\n\n  static Vertex targetv(work_item_t wi) {\n    return wi.first;\n  }\n\n  static Vertex sourcev(work_item_t wi) {\n    return wi.second.first;\n  }\n\n  static state_t statev(work_item_t wi) {\n    return wi.second.second.first;\n  }\n\n  static distance_t distancev(work_item_t wi) {\n    return wi.second.second.second;\n  }\n\n\n  typedef typename std::map<Vertex, int > NeighborCountMap;\n\n  struct default_comparer {\n    bool operator()(const work_item_t& wi1, const work_item_t& wi2) {\n      state_t s1 = statev(wi1);\n      state_t s2 = statev(wi2);\n      \n      if (s1 > s2)\n\treturn true;\n#ifdef MIS_DISTANCE_ORDERING\n      else if (s1 == s2) { // MIS_FIX1 vertices should be processed first\n\tdistance_t d1 = distancev(wi1);\n\tdistance_t d2 = distancev(wi2);\n\n\tif (d1 > d2) { \n\t  return true;\n\t} else if (d1 == d2) {\n\t  Vertex v1 = targetv(wi1);\n\t  Vertex v2 = targetv(wi2);\n\t\n\t  if (v1 > v2)\n\t    return true;\n\t  else\n\t    return false;\n\t\n\t} else\n\t  return false;\n      } else\n\treturn false;\n#else // distance ordering not defined\n      else\n\treturn false;\n#endif\n\n    }\n\n    /*#ifdef 0\n    bool operatorinverse()(const work_item_t& wi1, const work_item_t& wi2) const {\n      state_t s1 = statev(wi1);\n      state_t s2 = statev(wi2);\n      \n      if (s1 < s2)\n\treturn true;\n      else if (s1 == s2) {\n\tif (s1 == 0) {\n\t  distance_t d1 = distancev(wi1);\n\t  distance_t d2 = distancev(wi2);\n\n\t  if (d1 < d2) { // MIS_FIX1 vertices should be processed first\n\t    return true;\n\t  } else if (d1 == d2) {\n\t    Vertex v1 = targetv(wi1);\n\t    Vertex v2 = targetv(wi2);\n\t\n\t    if (v1 < v2)\n\t      return true;\n\t    else\n\t      return false;\n\t\n\t  } else\n\t    return false;\n\t} else {\n\t  Vertex v1 = targetv(wi1);\n\t  Vertex v2 = targetv(wi2);\n\t\n\t  if (v1 < v2)\n\t    return true;\n\t  else\n\t    return false;\n\t}\n      } else\n\treturn false;\n\n    }\n    #endif*/\n  };\n\n\n  typedef typename PriorityQueueGenerator::template queue<work_item_t, \n\t\t\t\t\t\t\t  default_comparer>::type PriorityQueue_t;\n  struct processing_function;\n\n  struct minimum_pair_first\n  {\n    template<typename T>\n    const T& operator()(const T& x, const T& y) const { return x.first < y.first ? x : y; }\n\n    template<typename F>\n    struct result {\n      typedef typename boost::function_traits<F>::arg1_type type;\n    };\n  };\n\n\n  typedef typename MessageGenerator::template call_result<work_item_t, \n\t\t\t\t\t\t\t  processing_function, \n\t\t\t\t\t\t\t  owner_from_pair<OwnerMap, work_item_t>, \n\t\t\t\t\t\t\t  amplusplus::idempotent_combination_t<minimum_pair_first > >::type RelaxMessage;\n  \npublic:\n  maximal_independent_set(Graph& g,\n\t\t\t  MISMap& mismap, \n\t\t\t  amplusplus::transport &t,\n\t\t\t  const IdDistribution& idd,\n\t\t\t  int freq,\n\t\t\t  int offset,\n\t\t\t  MessageGenerator message_gen = \n\t\t\t  MessageGenerator(amplusplus::counter_coalesced_message_type_gen(1 << 12)))\n    : dummy_first_member_for_init_order((amplusplus::register_mpi_datatype<work_item_t>(), 0)),\n      g(g), transport(t), \n      id_distribution(idd),\n      mis(mismap),\n      owner(get(vertex_owner, g)), \n      core_offset(offset),\n    relax_msg(message_gen, transport, owner_from_pair<OwnerMap, work_item_t>(owner),\n\t      amplusplus::idempotent_combination(minimum_pair_first())),\n      flushFrequency(freq), pq(t.get_nthreads()), counter(0)\n  {\n    initialize();\n  }\n\n  void operator() (int tid) { \n\n    run(tid); \n\n  }\n\n  void run(int tid = 0);\n  time_type get_start_time() {\n    return start_time;\n  }\n\n\n  void add_to_pq(const work_item_t& data, int tid) {\n    pq.push(data, tid);\n  }\n\n#ifdef MIS_STATS\n  void print_stats() {\n    unsigned long skipped = 0;\n    unsigned long called = 0;\n\n    std::vector<unsigned long>::iterator ite = skipped_handlers.begin();\n    for (; ite != skipped_handlers.end(); ++ite) {\n      skipped += (*ite);\n    }\n\n    ite = called_handlers.begin();\n    for (; ite != called_handlers.end(); ++ite) {\n      called += (*ite);\n    }\n    \n    std::cout << \"Skiped : \" << skipped << \", Called : \" << called\n\t      << std::endl;\n  }\n#endif\n\n#ifdef MIS_PRIORITY\n  void print_pq_sizes() {\n#ifdef MIS_STATS\n    int i = 0;\n    std::vector<size_t>::iterator ite = pq_sizes.begin();\n    for(; ite != pq_sizes.end(); ++ite) {\n      std::cout << \"thread : \" << i << \", pq size : \" << (*ite)\n\t\t<< std::endl;\n      ++i;\n    }\n#endif\n  }\n#endif\n\n\nprivate:\n  void initialize();\n  void process(const work_item_t& data, int tid);\n  void handle_queue(const int tid, amplusplus::transport::end_epoch_request& request);\n  void handle_fix0_wi(const work_item_t& data, int tid, int& flushcnt);\n\n  template<typename SizeType>\n  inline SizeType logical_id(SizeType k) {\n    return id_distribution(k);\n  }\n\n  work_item_t construct_wi(Vertex d,\n\t\t\t   Vertex s,\n\t\t\t   state_t state,\n\t\t\t   distance_t distance) {\n    // typedef std::pair<Vertex, std::pair<Vertex, std::pair<state_t, distance_t> > > work_item_t;\n    work_item_t wi(d, std::make_pair(s, std::make_pair(state, distance)));\n    return wi;\n  }\n\n  const int dummy_first_member_for_init_order;\n  const Graph& g;\n  amplusplus::transport& transport;\n  const IdDistribution& id_distribution;\n  MISMap& mis;\n  OwnerMap owner;\n  shared_ptr<amplusplus::detail::barrier> t_bar;\n  RelaxMessage relax_msg;\n  time_type start_time;\n  int flushFrequency;\n  PriorityQueue_t pq;\n  std::atomic_ullong counter;\n  NeighborCountMap lower_neighbors;\n  NeighborCountMap lower_fixed_neighbors;\n  shared_ptr<InitialBuffer> buffer;\n  int core_offset;\n#ifdef MIS_STATS\n  std::vector<unsigned long> skipped_handlers;\n  std::vector<unsigned long> called_handlers;\n#endif\n#ifdef MIS_PRIORITY\n#ifdef MIS_STATS\n  std::vector<size_t> pq_sizes;\n#endif\n#endif\n\n};\n\n#define MIS_PARMS                                   \\\n      typename Graph, typename MISMap, typename IdDistribution, typename PriorityQueueGenerator, typename MessageGenerator\n\n#define MIS_TYPE                                    \\\n      maximal_independent_set<Graph, MISMap, IdDistribution, PriorityQueueGenerator, MessageGenerator>\n\n\ntemplate<MIS_PARMS>\nvoid\nMIS_TYPE::initialize() {\n\n#ifdef MIS_PRIORITY\n  std::cout << \"Running with MIS priority .....\" << std::endl;\n#ifdef MIS_STATS\n  pq_sizes.resize(transport.get_nthreads(), 0);\n#endif\n#else\n  std::cout << \"Running with *out* MIS priority .....\" << std::endl;\n#endif\n\n  relax_msg.set_handler(processing_function(*this));\n\n#ifdef MIS_STATS\n  skipped_handlers.resize(transport.get_nthreads(), 0);\n  called_handlers.resize(transport.get_nthreads(), 0);\n#endif\n\n  //\n  shared_ptr<InitialBuffer> p(new InitialBuffer);\n  buffer.swap(p);\n\n  BGL_FORALL_VERTICES_T(u, g, Graph) {\n    mis[u] = MIS_UNFIX;\n    // lower_neighbors are not initialized\n    std::set<Vertex> locadjacencies;\n    int count = 0;\n    BGL_FORALL_OUTEDGES_T(u, e, g, Graph) {\n      Vertex v = target(e, g);\n      if (logical_id(v) < logical_id(u)) {\n\tif (locadjacencies.insert(v).second) { //to avoid parallel edges\n\t  ++count;\n\t}\n      }\n    }\n\n    if (count == 0) {\n      buffer->push_back(u);\n    }\n\n    lower_neighbors.insert(std::make_pair(u, count));\n    lower_fixed_neighbors.insert(std::make_pair(u, 0));\n  }\n\n  \n\n}\n\n\ntemplate<MIS_PARMS>\nvoid\nMIS_TYPE::handle_fix0_wi(const work_item_t& data, int tid, int& flushcnt) {\n  Vertex dest_vertex = targetv(data);\n  Vertex source_vertex = sourcev(data);\n  state_t source_state = statev(data);\n  distance_t dist = distancev(data);\n\n#ifdef MIS_PRIORITY\n  if (mis[dest_vertex] != MIS_UNFIX) {\n#ifdef PRINT_DEBUG\n    assert(mis[dest_vertex] == MIS_FIX1 ||\n\t   mis[dest_vertex] == MIS_FIX0);\n\n    if (mis[dest_vertex] == MIS_FIX1) {\n      if (logical_id(source_vertex) < logical_id(dest_vertex)) {\n\tstd::cout << \"To dest_vertex : \" << dest_vertex << \" to be fixed we must have checked all its lower neighbors (\" \n\t\t  << source_vertex << \")\" <<\n\t  \"lfn=\" << lower_fixed_neighbors[dest_vertex] << \" ln=\" << lower_neighbors[dest_vertex] << \n\t  std::endl;\n\tassert(false);\n      }\n    }\n#endif\n\n#ifdef MIS_STATS\n    ++skipped_handlers[tid];\n#endif\n    return;\n  }\n#endif\n\n  // case 3:\n  // Source vertex is not in mis and fixed =>\n  // If source vertex is less than destination vertex, then add\n  // 1 to lower_fixed_neighbors\n  // Also check, all neighbors less than current vertex are in\n  // lower_fixed_neighbors, if so promote dest_vertex to be in MIS and fix (MIS_FIX1).\n  // Inform neigbors about state changes.\n  assert(source_state == MIS_FIX0);\n\n#ifdef MIS_STATS\n  ++called_handlers[tid];\n#endif\n\n  if (logical_id(source_vertex) < logical_id(dest_vertex)) {\n\n#ifdef PRINT_DEBUG\n    assert(lower_neighbors[dest_vertex] > 0);\n    if (lower_fixed_neighbors[dest_vertex] >= lower_neighbors[dest_vertex]) {\n      std::cout << \"lfn=\" << lower_fixed_neighbors[dest_vertex] << \" ln=\" << lower_neighbors[dest_vertex]\n\t\t<< std::endl;\n    }\n#endif\n\n    // if all lower neigbors are fixed dest vertex must also be fixed\n    assert(lower_fixed_neighbors[dest_vertex] < lower_neighbors[dest_vertex]);\n\n    if (__atomic_add_fetch(&lower_fixed_neighbors[dest_vertex], 1, __ATOMIC_SEQ_CST) == lower_neighbors[dest_vertex]) {\n      // all the lower neigbors are fixed\n      assert(lower_fixed_neighbors[dest_vertex] == lower_neighbors[dest_vertex]);\n      mis[dest_vertex] = MIS_FIX1;\n      // vertex is fixed. We do not need to maintain lower_fixed_neighbors\n      // for this vertex any more.\n      // source not in mis -- just inform every neighbor the current state\n      std::set<Vertex> adjacencies;\n      BGL_FORALL_OUTEDGES_T(dest_vertex, e, g, Graph) {\n\tVertex u = target(e, g);\n\tif (logical_id(u) > logical_id(dest_vertex)) { // we know that all lower neighbors are fixed, therefore we only need to send messages to higher neighbors\n\t  if (adjacencies.insert(u).second) {\n#ifdef MIS_PRIORITY\n\t    //\t    if (fix0vertices[tid].insert(u).second) {\n\t      ++flushcnt;\n#endif\n\t      work_item_t wi = construct_wi(u, dest_vertex, mis[dest_vertex],\n\t\t\t\t\t    (dist + 1));\n#ifndef MIS_PRIORITY\n\t      //\t      transport.increase_activity_count(1);\n#endif\n\t      relax_msg.send(wi);\n#ifdef MIS_PRIORITY\n\t      // }\n#endif\n\t  }\n\t}\n      }\n    }\n  }\n}\n\n\ntemplate<MIS_PARMS>\nvoid\nMIS_TYPE::process(const work_item_t& data, int tid) {\n  //   typedef std::pair<Vertex, std::pair<Vertex, state_t > > work_item_t;\n\n  /*#ifdef CRAYPAT\n  if (PAT_region_begin ( 2, \"misprocess\" ) == PAT_API_FAIL) {\n    std::cout << \"PAT begin failed ! \" << std::endl;\n    assert(false);\n  }\n  #endif*/\n  \n\n  Vertex dest_vertex = targetv(data);\n  Vertex source_vertex = sourcev(data);\n  state_t source_state = statev(data);\n  distance_t dist = distancev(data);\n\n\n#ifdef PRINT_DEBUG\n  std::cout << \"dv : \" << dest_vertex << \" sv : \" << source_vertex << \" s_state : \" << source_state\n\t    << \" d_state :\" << mis[dest_vertex] << \" distance : \" << dist \n\t    << std::endl;\n#endif\n\n  // case 1:\n  // is destination vertex fixed ? then just ignore\n  if (mis[dest_vertex] != MIS_UNFIX) {\n    assert(mis[dest_vertex] == MIS_FIX1 ||\n\t   mis[dest_vertex] == MIS_FIX0);\n#ifndef MIS_PRIORITY\n    //    transport.decrease_activity_count(1);\n#endif\n\n    /*#ifdef CRAYPAT\n    if (PAT_region_end(2) == PAT_API_FAIL) {\n     std::cout << \"PAT end failed ! \" << std::endl;\n     assert(false);\n    }\n    #endif*/\n\n#ifdef MIS_STATS\n    ++skipped_handlers[tid];\n#endif\n    return;\n  }\n\n  // case 2:\n  // Source vertex is in mis and fixed =>\n  // Destination vertex state must be transferred to MIS_FIX0.\n  if (source_state == MIS_FIX1) {\n#ifdef MIS_STATS\n    ++called_handlers[tid];\n#endif\n    //mis[dest_vertex] = MIS_FIX0; \n    // source in mis, therefore dest must be out of mis\n    int expected = MIS_UNFIX;\n    if (__atomic_compare_exchange_n(&mis[dest_vertex], &expected, MIS_FIX0, false /*no weak*/, \n\t\t\t\t    __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) {\n\n      assert(mis[dest_vertex] == MIS_FIX0);\n      // inform all neighbors\n      std::set<Vertex> adjacencies;\n      BGL_FORALL_OUTEDGES_T(dest_vertex, e, g, Graph) {\n\tVertex u = target(e, g);\n\tif (logical_id(u) > logical_id(dest_vertex)) {\n\t  if (adjacencies.insert(u).second) {\n\t    work_item_t wi = construct_wi(u, dest_vertex, mis[dest_vertex],\n\t\t\t\t\t  (dist + 1));\n\t      \n#ifdef MIS_PRIORITY\n\t    relax_msg.send(wi);\n#else\n\t    //\t    transport.increase_activity_count(1);\n\t    relax_msg.send(wi);\n#endif\n\t  }\n\t}\n      }\n      \n    }\n  } else {\n#ifdef MIS_PRIORITY\n\n    if (pq.empty(tid)) {\n      transport.increase_activity_count(1);\n    }\n    pq.put(data, tid);\n\n#else\n    int ignore = 0;\n    handle_fix0_wi(data, tid, ignore);\n#endif\n  } // end of else\n\n#ifndef MIS_PRIORITY\n  // done processing the work item\n  //  transport.decrease_activity_count(1);\n#endif\n\n  /*#ifdef CRAYPAT\n  if (PAT_region_end(2) == PAT_API_FAIL) {\n    std::cout << \"PAT end failed ! \" << std::endl;\n    assert(false);\n  }\n  #endif*/\n\n\n}\n\ntemplate<MIS_PARMS>\nvoid\nMIS_TYPE::run(int tid) {\n  AMPLUSPLUS_WITH_THREAD_ID(tid) {\n\n#ifdef CRAYPAT\n      if (PAT_region_begin ( 1, \"misrun\" ) == PAT_API_FAIL) {\n\tstd::cout << \"PAT begin failed ! \" << std::endl;\n\tassert(false);\n      }\n#endif\n\n    int nthreads = transport.get_nthreads();\n    if (0 == tid) {\n      // Set the number of threads to the barrier\n      t_bar.reset(new amplusplus::detail::barrier(nthreads));\n    }\n\n    { amplusplus::scoped_epoch epoch(transport); }\n\n    // Now above if branch needs to be executed to every thread\n    // Therefore wait till every thread comes to this point\n    t_bar->wait();\n\n    // if two processes are running on the same node, core_offset\n    // is important to achieve thread affinity\n    if (pin(tid+core_offset) != 0) {\n      std::cerr << \"[ERROR] Unable to pin current thread to \"\n\t\t<< \"core : \" << tid << std::endl;\n      assert(false);\n    }\n\n    // wait till all threads are pinned\n    t_bar->wait();\n    { amplusplus::scoped_epoch epoch(transport); }\n\n    validate_thread_core_relation();\n\n    // should come before begin epoch\n    start_time = get_time();\n    // Start the algorithm\n    transport.begin_epoch();\n\n    typename InitialBuffer::size_type buff_size;\n    buff_size = buffer->size();\n    for (typename InitialBuffer::size_type i = tid ; \n\t i < buff_size ; i+= nthreads) {\n      Vertex u = (*buffer)[i];\n      mis[u] = MIS_FIX1;\n      std::set<Vertex> adjacencies;\n      BGL_FORALL_OUTEDGES_T(u, e, g, Graph) {\n\tVertex v = target(e, g);\n\tif (u != v) { // ignore self loops\n\t  if (adjacencies.insert(v).second) {\n\t    work_item_t wi = construct_wi(v, u, mis[u], 0);\n\t    relax_msg.send(wi);\n\t  }\n\t}\n      }\n\n    }\n#ifdef PRINT_DEBUG\n    // for information, can remove\n    if (tid == 0)\n      std::cout << \"Number of minimum_neighbor_vertices : \" << counter << std::endl;\n#endif\n\n    amplusplus::transport::end_epoch_request request = transport.i_end_epoch();\n    // if we have work process queues. queue is populated in the relax_msg\n    handle_queue(tid, request);\n\n#ifdef CRAYPAT\n    if (PAT_region_end(1) == PAT_API_FAIL) {\n      std::cout << \"PAT end failed ! \" << std::endl;\n      assert(false);\n    }\n#endif\n\n\n\n  }\n}\n\ntemplate<MIS_PARMS>\nvoid \nMIS_TYPE::handle_queue(const int tid, amplusplus::transport::end_epoch_request& request) {\n  int doFlushCounter = 0;\n  while(true) {\n#ifdef MIS_PRIORITY\n#ifdef MIS_STATS\n    if (pq.size(tid) > pq_sizes[tid]) {\n      pq_sizes[tid] = pq.size(tid);\n    }\n#endif\n\n    work_item_t wi;\n    while(pq.pop(wi, tid)) {\n      // to make sure pq is ordering properly TODO remove once verified\n#ifdef PRINT_DEBUG\n      std::cout << \"target vertex : \" << targetv(wi) << \" source : \" << sourcev(wi) << std::endl;\n#endif\n\n      bool e = pq.empty(tid);\n      handle_fix0_wi(wi, tid, doFlushCounter);\n\n      if (e)\n\ttransport.decrease_activity_count(1);\n\n      if(doFlushCounter == flushFrequency) {\n\tdoFlushCounter = 0;\n\tif (request.test()) {\n\t  assert(pq.empty(tid));\n\t  break;\n\t}\n      }\n    }\n\n    if (request.test())\n      break;\n#else\n    if (request.test())\n      break;\n#endif\n  }\n}\n\ntemplate<MIS_PARMS>\nstruct MIS_TYPE::\nprocessing_function {\n  \n  processing_function() : self(NULL) {}\n  processing_function(maximal_independent_set& self) : self(&self) {}\n  \n  void operator() (const work_item_t& data) const {\n    int tid = amplusplus::detail::get_thread_id();\n#ifdef PRINT_DEBUG\n    std::cout << \"Handler called in tid : \" << tid << std::endl;\n#endif\n    self->process(data, tid);\n  }\n\nprotected:\n  maximal_independent_set* self;\n};\n\n}}}\n#endif\n", "meta": {"hexsha": "ed7baf46ead79312057475f53aaba528737efacc", "size": 20134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/distributed/mis.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": "boost/graph/distributed/mis.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": "boost/graph/distributed/mis.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": 27.0982503365, "max_line_length": 154, "alphanum_fraction": 0.6715506109, "num_tokens": 5216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297119360208, "lm_q2_score": 0.03622005300402791, "lm_q1q2_score": 0.009965212749305605}}
{"text": "/*\nCopyright (c) 2020 Salah Eddine Bouterfif\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 <fstream>\n#include <sstream>\n#include <ciso646>\n#include <iomanip>\n\n#include \"Randomizer.h\"\n#include \"thirdparty/cxxopts/cxxopts.hpp\"\n\n#ifndef __has_include\nstatic_assert(false, \"__has_include not supported\");\n#else\n#if __has_include(<filesystem>)\n#include <filesystem>\nnamespace fs = std::filesystem;\n#elif __has_include(<experimental/filesystem>)\n#include <experimental/filesystem>\nnamespace fs = std::experimental::filesystem;\n#elif __has_include(<boost/filesystem.hpp>)\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\n#endif\n#endif\n\n// minmax\n#ifndef MIN\n#define MIN(a, b) (((a) > (b)) ? (b) : (a))\n#endif\n#ifndef MAX\n#define MAX(a, b) (((a) > (b)) ? (a) : (b))\n#endif\n\nstd::pair<std::string, std::string> generateInstance(int i, int nb_jobs, int nb_machines, int &k, int &nb_perturbations, double &fixed_percentage, long &seed, int &lower_bound, float &workload)\n{\n\n  // calculate the task index in ptime_arr\n  auto calTaskIdx = [&](int row_idx, int col_idx)\n  {\n    return row_idx * nb_machines + col_idx;\n  };\n\n  std::vector<int> ptime_arr(nb_jobs * nb_machines);\n  Randomizer random(seed);\n  seed = random.seed();\n  workload = 0.0;\n  lower_bound = 0;\n  bool is_random_hard = false;\n\n  if (k == 0 or nb_perturbations == 0 or fixed_percentage == 0)\n    is_random_hard = true;\n\n  if (is_random_hard)\n  {\n    // use these random parameters if parameters are 0\n    k = static_cast<int>(random(nb_jobs * nb_machines, nb_jobs * nb_machines * 100));\n    nb_perturbations = static_cast<int>(random(nb_jobs * nb_jobs, nb_jobs * nb_jobs * nb_machines));\n    fixed_percentage = (double)random(RAND_MAX) / (RAND_MAX);\n  }\n\n  // square problems\n  if (nb_jobs == nb_machines /*or nb_jobs < nb_machines*/)\n  {\n    for (int i = 0; i < nb_jobs; ++i)\n    {\n      // sum of each row = k\n      for (int j = 0; j < nb_machines; ++j)\n      {\n        ptime_arr[calTaskIdx(i, j)] = int(floor(k / nb_machines));\n      }\n      ptime_arr[calTaskIdx(i, i)] += k % (nb_machines);\n    }\n  }\n  // for rectangle problems, make sur that sum of all row is equal to k\n  // devide the rec into a square and add k mod m to a square sub matrix\n  // at a time ensuring all sum of row elem is equal to k\n  else\n  {\n    int inc = 0;\n    int min = MIN(nb_jobs, nb_machines);\n    // populate ptime_arr and apply the mod on the main diagonal\n    for (int i = 0; i < nb_jobs; ++i)\n    {\n      if (inc == min)\n        inc = 0;\n      // sum of each row = k\n      for (int j = 0; j < nb_machines; ++j)\n      {\n        ptime_arr[calTaskIdx(i, j)] = int(floor(k / nb_machines));\n        if (i >= min and j == inc)\n          ptime_arr[calTaskIdx(i, j)] += k % (nb_machines);\n      }\n      if (i < min)\n        ptime_arr[calTaskIdx(i, i)] += k % (nb_machines);\n      inc++;\n    }\n  }\n\n  std::stringstream ss_instance;\n  std::stringstream ss_name;\n  ss_name.str(\"\");\n  ss_instance.str(\"\");\n  // perturbations to to ptime_arr\n  for (int i = 0; i < nb_perturbations; ++i)\n  {\n    // task 1\n    int idx1 = 0;\n    int idx2 = 0;\n    // task 2\n    int idx3 = 0;\n    int idx4 = 0;\n\n    // select 2 different taks randomely\n    while (idx1 == idx3 or idx2 == idx4)\n    {\n      idx1 = static_cast<int>(random(0, nb_jobs - 1));\n      idx2 = static_cast<int>(random(0, nb_machines - 1));\n      idx3 = static_cast<int>(random(0, nb_jobs - 1));\n      idx4 = static_cast<int>(random(0, nb_machines - 1));\n    }\n    // the maximum removable work is the minimum of the two durations\n    // minus 1 to avoid creating tasks of length 0\n    const int removable = MIN(ptime_arr[calTaskIdx(idx1, idx2)], ptime_arr[calTaskIdx(idx3, idx4)]) - 1;\n    // fixed part that must be removed\n    const int must_remove = static_cast<int>(trunc(removable * fixed_percentage));\n    // random duration to be remove\n    const int removed = must_remove + static_cast<int>(random(0, removable - must_remove));\n    // substract from the removed frmo the first two tasks\n    ptime_arr[calTaskIdx(idx1, idx2)] -= removed;\n    ptime_arr[calTaskIdx(idx3, idx4)] -= removed;\n\n    // add the amount removed from the two first tasks,\n    // to keep all line sums equal to K\n    ptime_arr[calTaskIdx(idx1, idx4)] += removed;\n    ptime_arr[calTaskIdx(idx3, idx2)] += removed;\n  }\n\n  // calculate the workload of the instance\n  // classical lower bound\n  std::vector<int> machine(nb_machines);\n  float pttot = 0;\n  for (int i = 0; i < nb_jobs; i++)\n  {\n    int job = 0;\n    for (int j = 0; j < nb_machines; j++)\n    {\n      // add processing time on scheduled machine\n      machine[j] += ptime_arr[calTaskIdx(i, j)];\n      job += ptime_arr[calTaskIdx(i, j)];\n      pttot += ptime_arr[calTaskIdx(i, j)];\n    }\n    lower_bound = MAX(lower_bound, job);\n  }\n  for (int j = 0; j < nb_machines; j++)\n  {\n    lower_bound = MAX(lower_bound, machine[j]);\n  }\n  workload = float((pttot / (nb_machines * lower_bound)));\n\n  // create an instance name\n  int num = i + 1;\n  ss_name << \"hossp_\"\n          << std::setfill('0') << std::setw(2) << nb_jobs\n          << \"_\"\n          << std::setfill('0') << std::setw(2) << nb_machines;\n\n  ss_instance << \"// k = \" << k\n              << \", pert = \" << nb_perturbations\n              << \", fix = \" << fixed_percentage\n              << \", seed = \" << random.seed()\n              << \", lb = \" << lower_bound\n              << \", workload = \" << workload\n              << \"\\n\";\n\n  ss_instance << nb_jobs << \" \" << nb_machines << \"\\n\";\n  for (int i = 0; i < nb_jobs; ++i)\n  {\n    for (int j = 0; j < nb_machines; ++j)\n    {\n      ss_instance << ptime_arr[calTaskIdx(i, j)] << \" \";\n    }\n    ss_instance << \"\\n\";\n  }\n  ss_instance << \"\\n\";\n\n  return std::make_pair(ss_name.str(), ss_instance.str());\n}\n\nint main(int argc, char **argv)\n{\n  try\n  {\n    cxxopts::Options option(\"hossp\", \"hossp: Generate hard random instances of the open shop problem\");\n    option.add_options()(\"h,help\", \"This help message and exit\")\n                        (\"n,jobs\", \"number of jobs\", cxxopts::value<int>()->default_value(\"0\"))\n                        (\"m,machines\", \"number of machines\", cxxopts::value<int>()->default_value(\"0\"))\n                        (\"k\", \"the k value, =rand(n*m,n*m*100) if 0\", cxxopts::value<int>()->default_value(\"0\"))\n                        (\"f,fix\", \"fixed percentage, =rand(0,1) if 0\", cxxopts::value<double>()->default_value(\"0\"))\n                        (\"p,pert\", \"number of perturbations, =rand(n*m,n*m^2) if 0\", cxxopts::value<int>()->default_value(\"0\"))\n                        (\"g,generate\", \"number of instances to generate\", cxxopts::value<int>()->default_value(\"1\"))\n                        (\"o,out\", \"Enable stdout\", cxxopts::value<bool>()->default_value(\"false\"))\n                        (\"d,dir\", \"Output directory\", cxxopts::value<std::string>()->default_value(\"\"))\n                        (\"s,seed\", \"random seed.\", cxxopts::value<long>()->default_value(\"0\"))\n                        ;\n\n    if (argc == 1)\n    {\n      std::cout << option.help();\n      exit(1);\n    }\n    auto option_parse = option.parse(argc, argv);\n    if (option_parse.count(\"help\"))\n    {\n      std::cout << option.help();\n      exit(1);\n    }\n    if (option_parse[\"jobs\"].as<int>() <= 0)\n    {\n      std::cerr << \"Error: option jobs must be > 0\" << std::endl;\n      exit(1);\n    }\n    if (option_parse[\"machines\"].as<int>() <= 0)\n    {\n      std::cerr << \"Error: option machines must be > 0\" << std::endl;\n      exit(1);\n    }\n    if (option_parse[\"pert\"].as<int>() < 0)\n    {\n      std::cerr << \"Error: option pert must be >= 0\" << std::endl;\n      exit(1);\n    }\n    if (option_parse[\"fix\"].as<double>() < 0 or option_parse[\"fix\"].as<double>() > 1)\n    {\n      std::cerr << \"Error: option fix must be >= 0.0 and <= 1.0\" << std::endl;\n      exit(1);\n    }\n    if (option_parse[\"k\"].as<int>() < 0)\n    {\n      std::cerr << \"Error: option k must be >= 0\" << std::endl;\n      exit(1);\n    }\n    if (option_parse[\"g\"].as<int>() <= 0)\n    {\n      std::cerr << \"Error: option generate must be > 0\" << std::endl;\n      exit(1);\n    }\n\n    if (option_parse[\"seed\"].as<long>() < 0)\n    {\n      std::cerr << \"Error: option seed must be >= 0\" << std::endl;\n      exit(1);\n    }\n\n    if (option_parse[\"g\"].as<int>() > 1 and option_parse[\"seed\"].as<long>() > 0)\n    {\n      std::cerr << \"Error: cannot define a random seed to generate multiple instances.\" << std::endl;\n      exit(1);\n    }\n\n    bool is_stdout = option_parse[\"out\"].as<bool>();\n    std::string out_dir = option_parse[\"dir\"].as<std::string>();\n\n    int nb_jobs = option_parse[\"jobs\"].as<int>();\n    int nb_machines = option_parse[\"machines\"].as<int>();\n\n    int k = option_parse[\"k\"].as<int>();\n    int nb_perturbations = option_parse[\"pert\"].as<int>();\n    double fixed_percentage = option_parse[\"fix\"].as<double>();\n\n    int nb_instances = option_parse[\"g\"].as<int>();\n    long seed = option_parse[\"seed\"].as<long>();\n\n    // print instance statistics\n    std::string logdir = \"./log/\";\n    fs::create_directories(logdir);\n    std::ofstream out_stats;\n    std::string stats_filename = logdir + \"stats.txt\";\n    out_stats.open(stats_filename, std::ofstream::out | std::ofstream::app);\n    for (int i = 0; i < nb_instances; ++i)\n    {\n      float workload = 0.0;\n      int lower_bound = 0;\n\n      const std::pair<std::string, std::string> instance = generateInstance(i, nb_jobs, nb_machines, k, nb_perturbations, fixed_percentage, seed, lower_bound, workload);\n\n      if (is_stdout)\n        std::cout << instance.second;\n      if (not(is_stdout and out_dir.empty()))\n      {\n        // renumber instances according to existing instances\n        std::stringstream instance_filename_ss;\n        int num = i + 1;\n        instance_filename_ss << out_dir << instance.first << \"_\" << std::setfill('0') << std::setw(2) << num << \".txt\";\n\n        while (fs::exists(instance_filename_ss.str()))\n        {\n          num++;\n          instance_filename_ss.clear();\n          instance_filename_ss.str(std::string());\n          instance_filename_ss << out_dir << instance.first << \"_\" << std::setfill('0') << std::setw(2) << num << \".txt\";\n        }\n\n        // print stats on created instance\n        if (out_stats.is_open())\n        {\n          out_stats << instance.first << \"_\" << std::setfill('0') << std::setw(2) << num\n                    << \",\"\n                    << k\n                    << \",\"\n                    << nb_perturbations\n                    << \",\"\n                    << fixed_percentage\n                    << \",\"\n                    << seed\n                    << \",\"\n                    << lower_bound\n                    << \",\"\n                    << workload\n                    << \"\\n\";\n        }\n        else\n        {\n          std::cerr << \"Error: cannot open file \" << stats_filename << std::endl;\n        }\n\n        // print the instance to a text file\n        std::ofstream instance_file;\n        instance_file.open(instance_filename_ss.str(), std::ofstream::out);\n        if (instance_file.is_open())\n        {\n          instance_file << instance.second;\n          instance_file.close();\n        }\n      }\n      // reset seed \n      seed = 0;\n      nb_perturbations = 0;\n      fixed_percentage = 0;\n    }\n\n    out_stats.close();\n  }\n  catch (const std::exception &e)\n  {\n    std::cerr << e.what() << std::endl;\n    exit(1);\n  }\n  return 0;\n}\n", "meta": {"hexsha": "9cd49fab3e3ab52f47922573f33bc19a8cc98a45", "size": 12348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "eddinho/hossp", "max_stars_repo_head_hexsha": "2283cf8335a20921cb35238b87e40241f71c3e6e", "max_stars_repo_licenses": ["MIT"], "max_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": "eddinho/hossp", "max_issues_repo_head_hexsha": "2283cf8335a20921cb35238b87e40241f71c3e6e", "max_issues_repo_licenses": ["MIT"], "max_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": "eddinho/hossp", "max_forks_repo_head_hexsha": "2283cf8335a20921cb35238b87e40241f71c3e6e", "max_forks_repo_licenses": ["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.4634146341, "max_line_length": 193, "alphanum_fraction": 0.5831713638, "num_tokens": 3350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.021615335126133266, "lm_q1q2_score": 0.009965032503741993}}
{"text": "/*\n * Copyright 2015 Fadri Furrer, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Michael Burri, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Mina Kamel, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Janosch Nikolic, ASL, ETH Zurich, Switzerland\n * Copyright 2015 Markus Achtelik, ASL, ETH Zurich, Switzerland\n * Copyright 2016 Geoffrey Hunter <gbmhunter@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 * 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 COMMON_H\n#define COMMON_H\n\n#include <Eigen/Dense>\n#include <gazebo/gazebo.hh>\n\nnamespace gazebo\n{\n\n//===============================================================================================//\n//========================================= DEBUGGING ===========================================//\n//===============================================================================================//\n\n/// \\addtogroup Debug Print Switches\n/// @{\n\n// The following boolean constants enable/disable debug printing when certain plugin methods are called.\n// Suitable for debugging purposes. Left on permanently can swamp std::out and can crash Gazebo.\n\n  static const bool kPrintOnPluginLoad = false;\n  static const bool kPrintOnUpdates = false;\n  static const bool kPrintOnMsgCallback = false;\n\n/// @}\n\n// Default values\n  static const std::string kDefaultNamespace = \"\";\n  static constexpr double kDefaultRotorVelocitySlowdownSim = 10.0;\n\n//===============================================================================================//\n//================================== TOPICS FOR ROS INTERFACE ===================================//\n//===============================================================================================//\n\n// These should perhaps be defined in an .sdf/.xacro file instead?\n  static const std::string kConnectGazeboToRosSubtopic = \"connect_gazebo_to_ros_subtopic\";\n  static const std::string kConnectRosToGazeboSubtopic = \"connect_ros_to_gazebo_subtopic\";\n\n/// \\brief    Special-case topic for ROS interface plugin to listen to (if present)\n///           and broadcast transforms to the ROS system.\n  static const std::string kBroadcastTransformSubtopic = \"broadcast_transform\";\n\n\n/// \\brief      Obtains a parameter from sdf.\n/// \\param[in]  sdf           Pointer to the sdf object.\n/// \\param[in]  name          Name of the parameter.\n/// \\param[out] param         Param Variable to write the parameter to.\n/// \\param[in]  default_value Default value, if the parameter not available.\n/// \\param[in]  verbose       If true, gzerror if the parameter is not available.\n  template<class T>\n  bool getSdfParam(\n    sdf::ElementPtr sdf, const std::string & name, T & param, const T & default_value, const bool & verbose =\n    false)\n  {\n    if (sdf->HasElement(name)) {\n      param = sdf->GetElement(name)->Get<T>();\n      return true;\n    } else {\n      param = default_value;\n      if (verbose) {\n        gzerr << \"[rotors_gazebo_plugins] Please specify a value for parameter \\\"\" << name <<\n          \"\\\".\\n\";\n      }\n    }\n    return false;\n  }\n\n}\n\n/// \\brief    This class can be used to apply a first order filter on a signal.\n///           It allows different acceleration and deceleration time constants.\n/// \\details\n///           Short reveiw of discrete time implementation of first order system:\n///           Laplace:\n///             X(s)/U(s) = 1/(tau*s + 1)\n///           continous time system:\n///             dx(t) = (-1/tau)*x(t) + (1/tau)*u(t)\n///           discretized system (ZoH):\n///             x(k+1) = exp(samplingTime*(-1/tau))*x(k) + (1 - exp(samplingTime*(-1/tau))) * u(k)\ntemplate<typename T>\nclass FirstOrderFilter\n{\n\npublic:\n  FirstOrderFilter(double timeConstantUp, double timeConstantDown, T initialState)\n  : timeConstantUp_(timeConstantUp),\n    timeConstantDown_(timeConstantDown),\n    previousState_(initialState) {}\n\n  /// \\brief    This method will apply a first order filter on the inputState.\n  T updateFilter(T inputState, double samplingTime)\n  {\n\n    T outputState;\n    if (inputState > previousState_) {\n      // Calcuate the outputState if accelerating.\n      double alphaUp = exp(-samplingTime / timeConstantUp_);\n      // x(k+1) = Ad*x(k) + Bd*u(k)\n      outputState = alphaUp * previousState_ + (1 - alphaUp) * inputState;\n\n    } else {\n      // Calculate the outputState if decelerating.\n      double alphaDown = exp(-samplingTime / timeConstantDown_);\n      outputState = alphaDown * previousState_ + (1 - alphaDown) * inputState;\n    }\n    previousState_ = outputState;\n    return outputState;\n\n  }\n\n  ~FirstOrderFilter() {}\n\nprotected:\n  double timeConstantUp_;\n  double timeConstantDown_;\n  T previousState_;\n};\n\n/// \\brief    Computes a quaternion from the 3-element small angle approximation theta.\ntemplate<class Derived>\nEigen::Quaternion<typename Derived::Scalar> QuaternionFromSmallAngle(\n  const Eigen::MatrixBase<Derived> & theta)\n{\n  typedef typename Derived::Scalar Scalar;\n  EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived);\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);\n  const Scalar q_squared = theta.squaredNorm() / 4.0;\n\n  if (q_squared < 1) {\n    return Eigen::Quaternion<Scalar>(\n      sqrt(\n        1 - q_squared), theta[0] * 0.5, theta[1] * 0.5, theta[2] * 0.5);\n  } else {\n    const Scalar w = 1.0 / sqrt(1 + q_squared);\n    const Scalar f = w * 0.5;\n    return Eigen::Quaternion<Scalar>(w, theta[0] * f, theta[1] * f, theta[2] * f);\n  }\n}\n\ntemplate<class In, class Out>\nvoid copyPosition(const In & in, Out * out)\n{\n  out->x = in.x;\n  out->y = in.y;\n  out->z = in.z;\n}\n\n#endif /* ROTORS_GAZEBO_PLUGINS_COMMON_H_ */\n", "meta": {"hexsha": "d3fb4a259c8bef42c65173928e0b50d7a6be4dcc", "size": 6054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "botanbot_gazebo/include/botanbot_gazebo/gazebo_to_octomap_common.hpp", "max_stars_repo_name": "nikostsagk/botanbot_sim", "max_stars_repo_head_hexsha": "7b0c7a0336f04a04ac9c4c963f374a15064077b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T14:51:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:02:03.000Z", "max_issues_repo_path": "botanbot_gazebo/include/botanbot_gazebo/gazebo_to_octomap_common.hpp", "max_issues_repo_name": "nikostsagk/botanbot_sim", "max_issues_repo_head_hexsha": "7b0c7a0336f04a04ac9c4c963f374a15064077b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-11-08T23:45:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T15:41:46.000Z", "max_forks_repo_path": "botanbot_gazebo/include/botanbot_gazebo/gazebo_to_octomap_common.hpp", "max_forks_repo_name": "nikostsagk/botanbot_sim", "max_forks_repo_head_hexsha": "7b0c7a0336f04a04ac9c4c963f374a15064077b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T02:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T19:25:13.000Z", "avg_line_length": 36.0357142857, "max_line_length": 109, "alphanum_fraction": 0.6219028741, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940439256578, "lm_q2_score": 0.04813676940972089, "lm_q1q2_score": 0.009959210884694055}}
{"text": "/**\n @file tile.hpp\n @author pat <pat@fourthbox.com>\n */\n\n#ifndef LIBPMG_UTILS_HPP_\n#define LIBPMG_UTILS_HPP_\n\n#include <queue>\n#include <unordered_map>\n\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n\n#include \"map.hpp\"\n\nnamespace libpmg {\n\n/**\n Simple implementation of a priority queue.\n */\ntemplate<typename T, typename priority_t>\nstruct PriorityQueue {\n    typedef std::pair<priority_t, T> PQElement;\n    std::priority_queue<PQElement, std::vector<PQElement>,\n    std::greater<PQElement>> elements;\n    \n    inline bool empty() const { return elements.empty(); }\n    \n    inline void push(T item, priority_t priority) {\n        elements.emplace(priority, item);\n    }\n    \n    inline T pop() {\n        T best_item = elements.top().second;\n        elements.pop();\n        return best_item;\n    }\n    \n    inline std::size_t size() {\n        if (elements.size() < std::numeric_limits<std::size_t>::max())\n            return elements.size();\n        \n        return std::numeric_limits<std::size_t>::max();\n    }\n};\n\n/**\n A struct containing utility functions\n */\nstruct Utils {\n    \n    /**\n     Prints debug log informations.\n     @param message The message to be printed\n     */\n    static inline void LogDebug(std::string const &message) {\n        \n        printf(\"%s\\n\", message.c_str());\n    }\n    \n    /**\n     Prints debug log informations.\n     @param context A string indicating the context for better describing the message\n     @param message The message to be printed\n     */\n    static inline void LogDebug(std::string const &context, std::string const &message) {\n        \n        printf(\"%s:: %s\\n\", context.c_str(), message.c_str());\n    }\n    \n    /**\n     Prints debug log informations with a warning sign.\n     @param context A string indicating the context for better describing the message\n     @param message The message to be printed\n     */\n    static inline void LogWarning(std::string const &context, std::string const &message) {\n        \n        printf(\"[WARNING] %s:: %s\\n\", context.c_str(), message.c_str());\n    }\n\n    /**\n     Prints debug log informations with an error sign.\n     @param context A string indicating the context for better describing the message\n     @param message The message to be printed\n     */\n    static inline void LogError(std::string const &context, std::string const &message) {\n        \n        printf(\"[ERROR] %s:: %s\\n\", context.c_str(), message.c_str());\n    }\n    \n    /**\n     A function that uses the BFS algorithm to find the shortest path between 2 Location on a Map.\n     @param start_coor A pair of coordinats representing the start location\n     @param end_coor A pair of coordinats representing the end location\n     @param map A pointer to the Map where the search is happening\n     @param diagonals Whether diagonal paths should be used (compatible with FOUR_DIRECTIONAL, creating a \"stair\" effect)\n     @param dir Whether locations can be connected diagonally\n     @param reset_path_flags Whether path flags should be reset before running the algorithm\n     @return A pointer to an unordered map of locations. The key is the location \"connected\" to the value on the generated path\n     */\n    static std::unique_ptr<std::unordered_map<Location*, Location*>>\n    BreadthFirstSearch(std::pair<std::size_t, std::size_t> start_coor,\n                       std::pair<std::size_t, std::size_t> end_coor,\n                       Map *map,\n                       bool diagonals,\n                       MoveDirections const &dir,\n                       bool reset_path_flags = true);\n    \n    /**\n     A function that uses the Dijkstra algorithm to find the shortest path between 2 Location on a Map.\n     @param start_coor A pair of coordinats representing the start location\n     @param end_coor A pair of coordinats representing the end location\n     @param map A pointer to the Map where the search is happening\n     @param dir Whether locations can be connected diagonally\n     @param reset_path_flags Whether path flags should be reset before running the algorithm\n     @return A pointer to an unordered map of locations. The key is the location \"connected\" to the value on the generated path\n     */\n    static std::unique_ptr<std::unordered_map<Location*, Location*>>\n    Dijkstra(std::pair<std::size_t, std::size_t> start_coor,\n             std::pair<std::size_t, std::size_t> end_coor,\n             Map *map,\n             MoveDirections const &dir,\n             bool reset_path_flags = true);\n    \n    /**\n     A function that uses the Astar algorithm to find the shortest path between 2 Location on a Map.\n     @param start_coor A pair of coordinats representing the start location\n     @param end_coor A pair of coordinats representing the end location\n     @param map A pointer to the Map where the search is happening\n     @param dir Whether locations can be connected diagonally\n     @param reset_path_flags Whether path flags should be reset before running the algorithm\n     @return A pointer to an unordered map of locations. The key is the location \"connected\" to the value on the generated path\n     */\n    static std::unique_ptr<std::unordered_map<Location*, Location*>>\n    Astar(std::pair<std::size_t, std::size_t> start_coor,\n          std::pair<std::size_t, std::size_t> end_coor,\n          Map *map,\n          MoveDirections const &dir,\n          bool reset_path_flags = true);\n    \n    /**\n     Generates a random unique id.\n     @return A string with a UUID\n     */\n    static std::string GenerateUUID() { return boost::uuids::to_string(boost::uuids::random_generator()()); }\n};\n\n}\n\n#endif /* LIBPMG_UTILS_HPP_ */\n", "meta": {"hexsha": "86a7cb546ea8fcdf8c2a93d2ba699a4c790da763", "size": 5672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils.hpp", "max_stars_repo_name": "fourthbox/libpmg", "max_stars_repo_head_hexsha": "bac18c89cc8baeadf1b7b920d2b31931b89bfe25", "max_stars_repo_licenses": ["MIT"], "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/utils.hpp", "max_issues_repo_name": "fourthbox/libpmg", "max_issues_repo_head_hexsha": "bac18c89cc8baeadf1b7b920d2b31931b89bfe25", "max_issues_repo_licenses": ["MIT"], "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/utils.hpp", "max_forks_repo_name": "fourthbox/libpmg", "max_forks_repo_head_hexsha": "bac18c89cc8baeadf1b7b920d2b31931b89bfe25", "max_forks_repo_licenses": ["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.0718954248, "max_line_length": 127, "alphanum_fraction": 0.6659026798, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.023330768256720726, "lm_q1q2_score": 0.009946410618668152}}
{"text": "/*\n * vi:ts=4:tw=78:shiftwidth=4:expandtab\n * vim600:fdm=marker\n *\n * gistrainer.cpp  -  a trainer for conditional ME model with GIS algorithm\n *\n * An implementation of Generalized Iterative Scaling.  The reference paper\n * for this implementation was Adwait Ratnaparkhi's tech report at the\n * University of Pennsylvania's Institute for Research in Cognitive Science,\n * and is available at ftp://ftp.cis.upenn.edu/pub/ircs/tr/97-08.ps.Z\n *\n * This C++ implementation is originally based on java maxent implementation,\n * with the help of developers from java maxent.\n * see http://maxent.sf.net\n * \n * Current implementation implements the \"Correction Free\" GIS algorithm with\n * Gaussian prior smoothing described in [Curran and Clark, 2003]:\n * \"Investigating GIS and Smoothing for Maximum Entropy Taggers\".\n *\n * Without the computation of correction parameter, the new GIS algorithm is\n * much faster, making the already simple algorithm simpler.\n *\n * Copyright (C) 2002 by Zhang Le <ejoy@users.sourceforge.net>\n * Begin       : 31-Dec-2002\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#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <cassert>\n#include <cfloat>\n#include <cmath>\n#include <cstdlib>\n#include <limits>\n#include <tr1/unordered_map>\n#include <boost/timer.hpp>\n#include <idmlib/maxent/gistrainer.hpp>\n#include <idmlib/maxent/display.hpp>\n#include <idmlib/maxent/finite.h>\n\nnamespace maxent{\n\nvoid GISTrainer::init_trainer() {\n    assert(m_params->size() > 0);\n    assert(m_es->size() > 0);\n\n    // (bool) is needed for BCC5.5\n    if ((bool)m_heldout_es && m_heldout_es->size() > 0) {\n        cerr << \"calculating heldout accuracy is not supported in GIS trainer yet.\" << endl;\n    }\n\n    m_modifiers.reset(new vector<vector<double> >\n            (m_params->size(), vector<double>(0)) );\n    m_observed_expects.reset(new vector<vector<double> >\n            (m_params->size(), vector<double>(0)) );\n\n    // init all thetas to 0.0\n    for (size_t i = 0; i < m_params->size(); ++i) {\n        std::vector<pair<size_t, size_t> >& param = (*m_params)[i];\n        (*m_modifiers)[i].resize(param.size());\n        (*m_observed_expects)[i].resize(param.size());\n        for (size_t j = 0; j < param.size(); ++j) {\n            m_theta[param[j].second] = 0.0;\n            assert((*m_modifiers)[i][j] == 0.0);\n        }\n    }\n\n    // determine the correction constant\n    // C = max sum_{x,y} f_i(x, y)\n    // m_correct_constant = (*m_es)[0].context_size();\n    m_correct_constant = -999;\n    for (size_t i = 0; i < m_es->size(); ++i) {\n        // size_t len = (*m_es)[i].context_size();\n        double t = 0.0;\n        Event& e = (*m_es)[i];\n        // assume no duplicated features\n        for (size_t j = 0; j < e.context_size(); ++j) {\n            assert (e.m_context[j].second >= 0.0);\n            t += e.m_context[j].second;\n        }\n\n        if (t > m_correct_constant)\n            m_correct_constant = t;\n    }\n\n    m_N = 0;\n    for (vector<Event>::iterator it = m_es->begin();\n            it != m_es->end(); ++it) {\n        // XXX: is the calculation of active features correct?\n        m_N += it->m_count;\n    }\n\n    // calculate observed feature expectations\n    // a hash map to hold the value of feature <pred,outcome> pair occured in event list\n    // which is the sum of active feature f_i(a,b) in the training set\n    typedef std::tr1::unordered_map <pair<size_t, size_t>, float, featid_hasher> FeatSumMap;\n    FeatSumMap feat_sum;\n    for (vector<Event>::const_iterator it = m_es->begin();\n            it != m_es->end(); ++it) {\n        size_t len = it->context_size();\n        for (size_t i = 0; i < len; ++i) {\n        // check for feature values, current implementation only supports\n        // binary features\n//            if (it->m_context[i].second != 1.0)\n//                throw runtime_error(\"Current GIS implementation only supports binary features, use L-BFGS instead\");\n            feat_sum[make_pair(it->m_context[i].first,it->m_outcome)] +=\n                (it->m_count * it->m_context[i].second);\n        }\n    }\n\n    // Get the observed expectations of the features. Strictly speaking,\n    // we should divide the counts by the number of tokens, but because of\n    // the way the model's expectations are approximated in the\n    // implementation, this is cancelled out when we compute the next\n    // iteration of a parameter, making the extra divisions wasteful.\n    // Because we need no division of N in Ep<f_i> and Eq<f_i>\n    // when calculating delta of update paramater:\n    // lambda(n+1) = lambda(n) + (1/C)*[log(Ep<f_i>) - log(Eq<f_i>)]\n\n    FeatSumMap::iterator it;\n    for (size_t pid = 0; pid < m_params->size(); ++pid) {\n        vector<pair<size_t, size_t> >& param = (*m_params)[pid];\n        vector<double>& observ = (*m_observed_expects)[pid];\n        for (size_t j = 0; j < param.size(); ++j) {\n            it = feat_sum.find(make_pair(pid,param[j].first));\n            assert(it != feat_sum.end());\n            if (it == feat_sum.end())\n                throw runtime_error(\"broken training data: some <pid, oid> in params not found in training data\");\n\n            observ[j] = it->second; // Ep<f_i> = sum C(f_i)*f_i\n        }\n    }\n\n    if (!m_sigma2) {\n        // We are not using a prior, so we can save log(E_ref) instead \n        // to avoid unnecessary log(*) operation during gis parameter updates\n\n        const double LOG_ZERO = log(numeric_limits<double>::min());\n        for (size_t pid = 0; pid < m_params->size(); ++pid) {\n            vector<pair<size_t, size_t> >& param = (*m_params)[pid];\n            vector<double>& observ = (*m_observed_expects)[pid];\n            for (size_t j = 0; j < param.size(); ++j) {\n                observ[j] = (observ[j] == 0.0) ? LOG_ZERO : log(observ[j]);\n            }\n        }\n    }\n}\n\nvoid GISTrainer::train(size_t iter, double tol) {\n    if (!m_params || !m_es)\n        throw runtime_error(\"Can not train on an empty model\");\n\n    init_trainer();\n\n    // now enter iterations\n    const double LOG_ZERO = log(numeric_limits<double>::min());\n    double old_loglikelihood = 99999;\n    double new_loglikelihood = 0.0;\n    double acc;\n    size_t correct;\n    size_t best_oid;\n    vector<double> q(m_n_outcomes); // q(y|x)\n    boost::timer t;\n    size_t niter = 0;\n\n    display(\"\");\n    display(\"Starting GIS iterations...\");\n    display(\"Number of Predicates: %d\", m_params->size());\n    display(\"Number of Outcomes:   %d\", m_n_outcomes);\n    display(\"Number of Parameters: %d\", m_n_theta);\n    display(\"Tolerance:            %E\", tol);\n    display(\"Gaussian Penalty:     %s\", (m_sigma2?\"on\":\"off\"));\n#if defined(NDEBUG)\n    display(\"Optimized version\");\n#endif\n    display(\"iters   loglikelihood    training accuracy   heldout accuracy\");\n    display(\"=============================================================\");\n\n    for (; niter < iter;) {\n        new_loglikelihood = 0.0;\n        correct = 0;\n\n        // computer modifiers for all features from training data\n        for (vector<Event>::iterator it = m_es->begin();\n                it != m_es->end(); ++it) {\n            best_oid = eval(it->m_context, it->context_size(), q);\n            if (best_oid == it->m_outcome)\n                correct += it->m_count;\n            // TODO:optimize the code\n            // calculate Eq<f_i> = \\sum q(y|x) * Count(f_i) * f_i(x, y) \n            // (need not being divided by N)\n            for (size_t i = 0; i < it->context_size(); ++i) {\n                size_t pid = it->m_context[i].first;\n                double fval = it->m_context[i].second;\n                vector<pair<size_t, size_t> >& param = (*m_params)[pid];\n                for (size_t j = 0; j < param.size(); ++j) {\n                    size_t oid = param[j].first;\n                    (*m_modifiers)[pid][j] += q[oid] * it->m_count * fval;\n                    // binary case: (*m_modifiers)[pid][j] += q[oid] * it->m_count;\n                }\n            }\n            assert(finite(q[it->m_outcome]));\n            double t = log(q[it->m_outcome]);\n            new_loglikelihood += (finite(t) ? t : LOG_ZERO) * it->m_count;\n            assert(finite(new_loglikelihood));\n        }\n        acc = correct/double(m_N);\n\n        // compute the new parameter values\n        if (m_sigma2) { // applying Gaussian penality\n            for (size_t pid = 0; pid < m_params->size(); ++pid) {\n                vector<pair<size_t, size_t> >& param = (*m_params)[pid];\n                for (size_t i = 0; i < param.size(); ++i) {\n                    size_t fid = param[i].second;\n                    m_theta[fid] += newton((*m_modifiers)[pid][i],\n                            (*m_observed_expects)[pid][i], fid);\n                    (*m_modifiers)[pid][i] = 0.0; // clear modifiers for next iteration\n                }\n            }\n        } else {\n            for (size_t pid = 0; pid < m_params->size(); ++pid) {\n                vector<pair<size_t, size_t> >& param = (*m_params)[pid];\n                for (size_t i = 0; i < param.size(); ++i) {\n                    if ((*m_modifiers)[pid][i] != 0.0) { \n                        m_theta[param[i].second] += \n                            ((*m_observed_expects)[pid][i] -\n                             log((*m_modifiers)[pid][i])) / m_correct_constant;\n                        (*m_modifiers)[pid][i] = 0.0; // clear modifiers for next iteration\n                    } else {\n                        // E_q == 0 means feature value is 0, which means\n                        // update for this parameter will always be zero,\n                        // hence can be ignored.\n                    }\n                }\n            }\n        }\n\n        ++niter;\n        display(\"%3d\\t%E\\t  %.3f%%\\t     %s\",\n                niter , (new_loglikelihood/m_N) , (acc*100) ,  \"N/A\");\n        if (fabs((old_loglikelihood - new_loglikelihood)/old_loglikelihood) < tol) {\n            display(\"Training terminats succesfully in %.2f seconds\", t.elapsed());\n            break;\n        }\n        old_loglikelihood = new_loglikelihood;\n    }\n    if (niter >= iter)\n        display(\"Maximum numbers of %d iterations reached in %.2f seconds\", iter , t.elapsed());\n\n    // kill a bunch of these big objects now that we don't need them\n    m_modifiers.reset();\n    m_observed_expects.reset();\n}\n\n// Calculate the ith GIS parameter updates with Gaussian prior\n// using Newton-Raphson method\n// the update rule is the solution of the following equation:\n//                                   lambda_i + delta_i\n// E_ref = E_q * exp (C * delta_i) + ------------------ * N\n//                                       sigma_i^2\n// note: E_ref and E_q were not divided by N\ndouble GISTrainer::newton(double f_q, double f_ref, size_t i, double tol) {\n    size_t maxiter = 50;\n    double x0 = 0.0;\n    double x = 0.0;\n\n    for (size_t iter = 1; iter <= maxiter; ++iter) {\n        double t = f_q * exp(m_correct_constant * x0);\n        double fval = t + m_N * (m_theta[i] + x0) / m_sigma2[i] - f_ref;\n        double fpval = t * m_correct_constant + m_N / m_sigma2[i];\n        if (fpval == 0) {\n            cerr <<\n                \"Warning: zero-derivative encountered in newton() method.\" \n                << endl;\n            return x0;\n        }\n        x = x0 - fval/fpval;\n        if (abs(x-x0) < tol)\n            return x;\n        x0 = x;\n    }\n    throw runtime_error(\"Failed to converge after 50 iterations in newton() method\");\n}\n\n} // namespace maxent\n\n", "meta": {"hexsha": "29db51b3f4496c20723be6b87e6a4eaa6f0d9abc", "size": 12155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/maxent/gistrainer.cpp", "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/maxent/gistrainer.cpp", "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/maxent/gistrainer.cpp", "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": 40.1155115512, "max_line_length": 118, "alphanum_fraction": 0.5731797614, "num_tokens": 3139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.03067580436917223, "lm_q1q2_score": 0.00994618126808085}}
{"text": "/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n\n/*!\n* \\file solver_library.cpp\n* \\ingroup Objects\n* \\brief SolverLibrary class source file.\n* \\author Josh Lurz\n*/\n#include \"util/base/include/definitions.h\"\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include \"util/base/include/definitions.h\"\n#include <vector>\n#include <map>\n#include <cmath>\n#include <string>\n#include <algorithm>\n#include \"solution/util/include/solver_library.h\"\n#include \"marketplace/include/marketplace.h\"\n#include \"containers/include/world.h\"\n#include \"util/base/include/configuration.h\"\n#include \"util/base/include/util.h\"\n#include \"solution/util/include/solution_info.h\"\n#include \"solution/util/include/solution_info_set.h\"\n#include \"solution/util/include/calc_counter.h\"\n#include \"util/logger/include/ilogger.h\"\n#include \"solution/util/include/ublas-helpers.hpp\"\n#include \"containers/include/iactivity.h\"\n\n#include \"solution/util/include/edfun.hpp\"\n#include \"solution/util/include/functor-subs.hpp\"\n\nusing namespace std;\n\n#define NO_REGIONAL_DERIVATIVES 0\n\n/*! \\brief Calculate and return a relative excess demand.\n* \\author Josh Lurz\n* \\details This function determines the excess demand relative to the demand. This helps to determine which market is truely\n* the worst. This function returns 0 if the ED value is below the excessDemandFloor as the market is considered solved.\n* Otherwise, relative excess demand is determined to be the absolute value of excess demand divided by demand multiplied by 100.\n* \\param excessDemand The excess demand.\n* \\param demand The market demand.\n* \\param excessDemandFloor Value of ED below which the market should be considered solved.\n* \\return The relative excess demand, excess demand as a percentage of demand.\n*/\ndouble SolverLibrary::getRelativeED( const double excessDemand, const double demand, const double excessDemandFloor ) {\n\n    // Initialize return value\n    double retValue = 0;\n    double tempDemand = fabs( demand );\n\n    // If demand is 0, set tempDemand to small number to avoid\n    // divide by 0.\n    if( tempDemand < util::getSmallNumber() ) {\n        tempDemand = util::getSmallNumber();\n    }\n\n    // Check if the ED is below a minimal value.\n    if( fabs( excessDemand ) < excessDemandFloor ) {\n        retValue = 0;\n    }\n    // Find the ratio of excess demand to demand.\n    else {\n        retValue = fabs( excessDemand ) / tempDemand;\n    }\n\n    return retValue;\n}\n\n/*! \\brief Determine whether a market is within the solution tolerance.\n* \\author Josh Lurz\n* \\details This function determines if a market is solved to within the solution tolerance. It does this by checking if the\n* relative excess demand is less than the solution tolerance.\n* \\param excessDemand The excess demand.\n* \\param demand The market demand.\n* \\param solutionTolerance The relative excess demand below which a market is considered solved.\n* \\param excessDemandFloor Absolute value of ED below which the market should be considered solved.\n*/\nbool SolverLibrary::isWithinTolerance( const double excessDemand, const double demand, const double solutionTolerance, const double excessDemandSolutionFloor ) {\n    return ( getRelativeED( excessDemand, demand, excessDemandSolutionFloor ) < solutionTolerance );\n}\n\n/*! \\brief Function to calculate partial derivatives for Newton-Raphson method, NR_Ron()\n*\n* This function calculates matrices of partial derivatives of supplies and demands for all markets which are currently being solved.\n* The function uses the fact that changing a price while holding all other prices constant can only change markets that are affected.\n* It must however set the Marketplace mIsDerivativeCalc flag to ensure only changes are noted so the non-affected markets do not need\n* to null supplies and demands nor recalculate what they were.\n* \\param marketplace The marketplace to perform derivative calculations on.\n* \\param world The world object which is used for calls to World::calc\n* \\param aSolutionSet The vector of SolutionInfo objects which store the current prices, supplies and demands.\n* \\param Delta to use when changing prices.\n* \\param per The current model period.\n*/\nvoid SolverLibrary::derivatives( Marketplace* marketplace, World* world, SolutionInfoSet& aSolutionSet,\n                                 const double aDeltaPrice, const int per ) {\n\n    // TODO: could fix but why?\n    /*ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n    solverLog.setLevel( ILogger::NOTICE );\n    solverLog << \"Starting derivative calculation\" << endl;\n\n    // Initial call to world.calc to ensure we have set our baseline to take\n    // partials from.\n    marketplace->nullSuppliesAndDemands( per );\n    world->calc( per );\n\n#if( !NO_REGIONAL_DERIVATIVES )\n    // Set the flag to only take supply/demand differences\n    marketplace->mIsDerivativeCalc = true;\n#endif\n    // Retain the original values.\n    aSolutionSet.storeValues();\n\n    // Calculate derivatives for each market.\n    for ( unsigned int j = 0; j < aSolutionSet.getNumSolvable(); j++ ) {\n        double currDeltaPrice = aSolutionSet.getSolvable( j ).getDeltaPrice( aDeltaPrice );\n        aSolutionSet.getSolvable( j ).increaseX( currDeltaPrice, currDeltaPrice );\n\n#if( NO_REGIONAL_DERIVATIVES )\n        marketplace->nullSuppliesAndDemands( per );\n        world->calc( per );\n#else\n\n        // Determine which calculations are affected.\n        const vector<IActivity*>& affectedItems = aSolutionSet.getSolvable( j ).getDependencies();\n\n        /*! \\invariant There is at least one item to calculate. * /\n        assert( !affectedItems.empty() );\n\n        world->calc( per, affectedItems );\n        \n        // Set the stale flag to indicate that demand calculations may need to\n        // recalculate it's corresponding price calculation.  Setting this flag\n        // allows this to be lazy.\n        for( size_t partialIndex = 0 ; partialIndex < affectedItems.size(); ++partialIndex ) {\n            affectedItems[ partialIndex ]->setStale();\n        }\n#endif\n\n        aSolutionSet.getSolvable( j ).calcDemandElas( aSolutionSet );\n        aSolutionSet.getSolvable( j ).calcSupplyElas( aSolutionSet );\n        aSolutionSet.restoreValues();\n    }\n#if( !NO_REGIONAL_DERIVATIVES )\n    // Reset the derivative flag.\n    marketplace->mIsDerivativeCalc = false;\n#endif\n*/\n}\n\n/* \\brief Calculate the JFDM, JFSM, and JF matrices from the derivatives stored in the SolutionInfo. */\nvoid SolverLibrary::updateMatrices( SolutionInfoSet& aSolutionSet, Matrix& JFSM, Matrix& JFDM, Matrix& JF ){\n    for( unsigned int j = 0; j < aSolutionSet.getNumSolvable(); ++j ){\n        for( unsigned int i = 0; i < aSolutionSet.getNumSolvable(); ++i ){\n            JFDM( i , j ) = aSolutionSet.getSolvable( j ).getDemandElasWithRespectTo( i );\n            JFSM( i , j ) = aSolutionSet.getSolvable( j ).getSupplyElasWithRespectTo( i );\n            JF( i , j ) = JFSM( i , j ) - JFDM( i , j );\n            assert( util::isValidNumber( JF( i , j) ) );\n        }\n    }\n\n}\n\n/*! \\brief Calculate and set new market prices based on Log NR  mechanism\n * \\param aSolutionSet An object containing the set of SolutionInfo objects representing all markets.\n * \\param JFLUFactorized LU factored JF matrix\n * \\param aPermMatrix Permutation matrix used to factorize JF\n * \\param aDefaultMaxPriceJump The default factor used to limit the price changes from this algorithm.\n * \\return Whether prices were set successfully.\n */\nbool SolverLibrary::calculateNewPricesLogNR( SolutionInfoSet& aSolutionSet, Matrix& JFLUFactorized,\n                                             PermutationMatrix& aPermMatrix, const double aDefaultMaxPriceJump )\n{\n    using namespace boost::numeric::ublas;\n    boost::numeric::ublas::vector<double> KDS( aSolutionSet.getNumSolvable() ); // k values demand - supply\n    \n    // initialize KDS as logs of original demand - supply or -F(Xn)\n    for ( unsigned int i = 0; i < aSolutionSet.getNumSolvable(); i++ ) {\n        KDS[ i ] = log( max( aSolutionSet.getSolvable( i ).getDemand(), util::getSmallNumber() ) )\n            - log( max( aSolutionSet.getSolvable( i ).getSupply(), util::getSmallNumber() ) );\n    }\n    \n    // Store the solution set prices so that they can be restored if NR fails to\n    // generate valid prices.\n    std::vector<double> storedPrices = storePrices( aSolutionSet );\n    boost::numeric::ublas::vector<double> price(aSolutionSet.getNumSolvable());\n    std::copy(storedPrices.begin(),storedPrices.begin()+price.size(),price.begin());\n\n    ILogger &solverLog = ILogger::getLogger(\"solver_log\");\n    solverLog.setLevel(ILogger::DEBUG);\n    solverLog << \"x: \" << price << \"\\nfx: \" << KDS << \"\\n\";\n    \n    \n    // to solve JF(Xn) * ( Xn+1 - Xn ) = -F(Xn) we use lu substitution which\n    // is favorable to calculating the inverse of JF.  lu_substitue will leave\n    // us with ( Xn+1 - Xn ) stored in KDS\n    lu_substitute( JFLUFactorized, aPermMatrix, KDS );\n    solverLog << \"dx: \" << KDS << \"\\n\";\n    \n    // To calculate the new price Xn+1 we do Xn+1 = Xn + KDS\n    // then take the e^Xn+1 to get the prices back in normal terms\n    for ( unsigned int i = 0; i < aSolutionSet.getNumSolvable(); i++ ) {\n        // we must take the log of the current prices before adding it to KDS\n        // to put them in the same domain\n        double newPrice = exp( log( aSolutionSet.getSolvable( i ).getPrice() ) + KDS[ i ] );\n        if( util::isValidNumber( newPrice ) ) {\n            // determine a max price change to allow\n            SolutionInfo& currSolutionInfo = aSolutionSet.getSolvable( i );\n            double maxNRStep = currSolutionInfo.getMaxNRPriceJump( aDefaultMaxPriceJump );\n            \n            // limit the price change to avoid diverging from the solution\n            // when a derivative was taken at a discontinous point\n            if ( newPrice > currSolutionInfo.getPrice() * maxNRStep ){\n                ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n                solverLog.setLevel( ILogger::DEBUG );\n                solverLog << currSolutionInfo.getName() << \" hit max price change, \" << currSolutionInfo.getPrice() << ','\n                    << newPrice << ',' << currSolutionInfo.getPrice() * maxNRStep << ','\n                    << newPrice / currSolutionInfo.getPrice()  << endl;\n                newPrice = currSolutionInfo.getPrice() * maxNRStep;\n            }\n            else if ( newPrice < currSolutionInfo.getPrice() / maxNRStep ){\n                ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n                solverLog.setLevel( ILogger::DEBUG );\n                solverLog << currSolutionInfo.getName() << \" hit max price change, \" << currSolutionInfo.getPrice() << ','\n                    << newPrice << ',' << currSolutionInfo.getPrice() / maxNRStep << ','\n                    << currSolutionInfo.getPrice() / newPrice << endl;\n                newPrice = currSolutionInfo.getPrice() / maxNRStep;\n            }\n            \n            currSolutionInfo.setPrice( newPrice );\n        }\n        else {\n            ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n            solverLog.setLevel( ILogger::ERROR );\n            solverLog << \"Correcting invalid price generated by Newton-Raphson in market \"\n                << aSolutionSet.getSolvable( i ).getName() << \".  Price was \"\n                << newPrice << endl;\n            // Restore prices and return failure.\n            restorePrices( aSolutionSet, storedPrices );\n            return false;\n        }\n    }\n    return true;\n}\n\n/*! \\brief Calculate the LU factorization of a matrix using partial pivoting.\n * \\author Pralit Patel\n * \\details This function changes an input matrix to an LU factorizated version and also\n *          produces a permutation matrix. This can be used in conjunction with lu_substitue\n *          to solve a set of equations of the form Ax=b and is less computationaly intensive\n *          than finding the inverse of A and multiplying that by b.\n *          This function also checks if the matrix is singular in which case garbage may\n *          be returned since no inverse exists.  The return value should always be\n *          checked after a call to this method.\n * \\param aInputMatrix Matrix that will be LU factorized.\n * \\param aPermMatrix A permutation matrix that will hold the permutations used for LU decomposition.\n * \\return Whether the factorization was succesful.  It may not be successful if the input matrix is\n *          is singular in which case the contents of the matrix and permutation matrix will be garbage.\n */\nbool SolverLibrary::luFactorizeMatrix( Matrix& aInputMatrix, PermutationMatrix& aPermMatrix ) {\n    using namespace boost::numeric::ublas;\n    \n    // need to reset the permutation matrix\n    PermutationMatrix tempPerm( aInputMatrix.size1() );\n    aPermMatrix.assign( tempPerm );\n    \n    // do the LU-factorization, the return value is the singular row + 1\n    // and so if the return value is 0 there were no singularities\n    return lu_factorize( aInputMatrix, aPermMatrix ) != 0;\n}\n\n/*! \\brief Bracket a set of markets.\n* \\details Function finds bracket interval for each market and puts this\n*          information into solution set vector\n* \\author Sonny Kim, Josh Lurz, Steve Smith, Kate Calvin\n* \\param aMarketplace Marketplace reference.\n* \\param aWorld World reference.\n* \\param aDefaultBracketInterval The default bracket interval by which trial values are moved\n*                                which may be overriden by a SolutionInfo.  The bracket interval\n*                                is used as the multiplier to expand trial brackets.\n* \\param aMaxIterations The maximum iterations allowed to find a brackets.\n* \\param aSolutionSet Vector of market solution information\n* \\param aCalcCounter The calculation counter.\n* \\param aPeriod Model period\n* \\return Whether bracketing of all markets completed successfully.\n*/\nbool SolverLibrary::bracket( Marketplace* aMarketplace, World* aWorld, const double aDefaultBracketInterval,\n                             const unsigned int aMaxIterations, SolutionInfoSet& aSolutionSet, CalcCounter* aCalcCounter,\n                             const ISolutionInfoFilter* aSolutionInfoFilter, const int aPeriod )\n{\n    bool code = false;\n    static const double LOWER_BOUND = util::getVerySmallNumber();\n\n    // Make sure the markets are up to date before starting.\n    aMarketplace->nullSuppliesAndDemands( aPeriod );\n#if GCAM_PARALLEL_ENABLED\n    aWorld->calc( aPeriod, aWorld->getGlobalFlowGraph() );\n#else\n    aWorld->calc( aPeriod );\n#endif\n    aSolutionSet.updateSolvable( aSolutionInfoFilter );\n    // Return with code true if all markets are bracketed.\n    if( aSolutionSet.isAllBracketed() ){\n        return code = true;\n    }\n    aSolutionSet.resetBrackets();\n\n    ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n    solverLog.setLevel( ILogger::NOTICE );\n    solverLog << \"Entering bracketing\" << endl;\n    \n    if( aSolutionSet.getNumSolvable() == 0 ) {\n        solverLog << \"Exiting bracketing early due to empty solvable set.\" << endl;\n        return true;\n    }\n    \n    // Set up the EDFun wrapper which we will use to do the model evaluations.\n    // This way we can re-use the same concepts to backtrack on a bracket step\n    // similar to how we do it in the linesearch algorithm used in NR.\n    using UBVECTOR = boost::numeric::ublas::vector<double>;\n    LogEDFun edFun(aSolutionSet, aWorld, aMarketplace, aPeriod, false);\n    FdotF<double, double> F(edFun);\n    UBVECTOR x(aSolutionSet.getNumSolvable());\n    UBVECTOR prev_x(aSolutionSet.getNumSolvable());\n    UBVECTOR dx(aSolutionSet.getNumSolvable());\n    for(int i = 0; i < aSolutionSet.getNumSolvable(); ++i) {\n        x[i] = aSolutionSet.getSolvable(i).getPrice();\n    }\n    edFun.scaleInitInputs(x);\n    double currFX = F(x);\n    double prevFX;\n    \n    solverLog.setLevel( ILogger::DEBUG );\n    solverLog << aSolutionSet << endl;\n    solverLog << endl << \"Initial FX: \" << currFX << endl;\n\n    ILogger& singleLog = ILogger::getLogger( \"single_market_log\" );\n\n    // Loop is done at least once.\n    unsigned int iterationCount = 1;\n    do {\n        prev_x = x;\n        prevFX = currFX;\n        aSolutionSet.printMarketInfo( \"Bracket All\", aCalcCounter->getPeriodCount(), singleLog );\n\n        // Iterate through each market.\n        for ( unsigned int i = 0; i < aSolutionSet.getNumSolvable(); i++ ) {\n            // Fetch the current \n            SolutionInfo& currSol = aSolutionSet.getSolvable( i );\n            double currBracketInterval = currSol.getBracketInterval( aDefaultBracketInterval );\n            \n            // Check for special case where a resource with no supply can become \"solved\" during\n            // the bracketing procedure.\n            if( fabs( currSol.getSupply() ) < util::getSmallNumber() &&\n                fabs( currSol.getDemand() ) < util::getSmallNumber() )\n            {\n                currSol.setBracketed();\n            }\n            if ( !currSol.isBracketed() ) {\n                // If a market is not bracketed, then EDL and EDR have the same sign\n                // Check if ED has the same sign as EDL and EDR.\n                if ( util::sign( currSol.getED() ) == util::sign( currSol.getEDLeft() ) ) {\n                    // If Supply > Demand at point X, then we want to decrease x to increase demand\n                    // If ED is negative, then so are EDL and EDR\n                    // So, X, XL, and XR are all greater than the solution price\n                    if ( currSol.getED() < 0 ) {\n                        currSol.moveRightBracketToX();\n                        currSol.decreaseX( currBracketInterval, LOWER_BOUND );\n                    } // END: if statement testing if ED < 0\n                    // If Supply <= Demand. Price needs to increase so demand decreases\n                    // If ED is positive, then so are EDL and EDR\n                    // So, X, XL, and XR are all less than the solution price\n                    else {\n                        currSol.moveLeftBracketToX();\n                        currSol.increaseX( currBracketInterval, LOWER_BOUND );\n                    } // END: if statement testing if ED > 0\n                } // END: if statement testing if ED and EDL have the same sign\n                // If market is unbracketed, EDL and EDR have the same sign\n                // ED has the opposite sign of EDL and EDR\n                else {\n                    // If ED < 0, then EDL > 0 and EDR > 0\n                    // To bracket we just need to move XR to X\n                    if ( currSol.getED() < 0 ) {\n                        currSol.moveRightBracketToX();\n                    } // END: if statement testing if ED < 0\n                    // If ED > 0, then EDL < 0 and EDR < 0\n                    // To bracket, we just need to move XL to X\n                    else {\n                        currSol.moveLeftBracketToX();\n                    } // END: if statement testing if ED > 0\n                } // END: if statement testing if ED and EDL have opposite signs\n\n                // Check if current marketed is now bracketed\n                // If so, set bracketed to true\n                if( currSol.isCurrentlyBracketed() ){\n                    currSol.setBracketed();\n                }\n\n            } // END: if statement testing if bracketed\n            // If bracketed, but left and right prices are equal\n            else if ( currSol.getBracketSize() == 0 ){\n                // If XL and XR are equal, market is not bracketed\n                // If ED, EDL and EDR all have same sign, set bracketed to false\n                if ( util::sign( currSol.getED() ) == util::sign( currSol.getEDLeft() ) ) {\n                    currSol.resetBrackets();\n                }\n                // if ED < EDL, then X > XL\n                // if we move XR to X, then market will be bracketed\n                else if ( currSol.getED() < currSol.getEDLeft() ) {\n                    currSol.moveRightBracketToX();\n\n                    // Check if market is currently bracketed\n                    // If so, set bracketed to true\n                    if( currSol.isCurrentlyBracketed() ){\n                        currSol.setBracketed();\n                    }\n                }\n                // if ED > EDL, then X < XL\n                // if we move XL to X, then market will be bracketed\n                else {\n                    currSol.moveLeftBracketToX();\n\n                    // Check if market is currently bracketed\n                    // If so, set bracketed to true\n                    if( currSol.isCurrentlyBracketed() ){\n                        currSol.setBracketed();\n                    }\n                }\n            } // END: if statement testing if currSol is bracketed with XL == XR\n            x[i] = currSol.getPrice();\n        } // end for loop\n\n        // Rescale prices to be normalized then run an iteration\n        edFun.scaleInitInputs(x);\n        currFX = F(x);\n        solverLog << \"Current FX: \" << currFX << endl;\n        \n        // Check if this bracket step has increased the \"error\" F dot F by more than the\n        // allowable threshold and walk back the step by half until it no longer does.\n        const double FX_INCREASE_THRESHOLD = 10.0;\n        double stepMult = 1.0;\n        dx = x - prev_x;\n        while(currFX > (prevFX * FX_INCREASE_THRESHOLD)) {\n            stepMult /= 2.0;\n            x = prev_x + dx * stepMult;\n            currFX = F(x);\n            solverLog << \"Walked back: \" << stepMult << \", Current FX: \" << currFX << endl;\n        }\n        solverLog.setLevel( ILogger::NOTICE );\n        solverLog << \"Completed an iteration of bracket: \" << iterationCount << endl;\n        solverLog << aSolutionSet << endl;\n    } while ( ++iterationCount <= aMaxIterations && !aSolutionSet.isAllBracketed() );\n\n    code = ( aSolutionSet.isAllBracketed() ? true : false );\n\n    solverLog.setLevel( ILogger::DEBUG );\n    solverLog << \"Solution Info Set before leaving bracket: \" << endl;\n    solverLog << aSolutionSet << endl;\n\n    aSolutionSet.printMarketInfo( \"End Bracketing Attempt\", 0, singleLog );\n\n    return code;\n}\n\n/*\n * \\brief Function finds bracket interval for a single market.\n * \\author Josh Lurz\n * \\param aMarketplace Marketplace reference.\n * \\param aWorld World reference.\n * \\param aDefaultBracketInterval The default bracket interval by which trial values are moved\n *                                which may be overriden by a SolutionInfo.  The bracket interval\n *                                is used as the multiplier to expand trial brackets.\n * \\param aMaxIterations The maximum iterations allowed to find a brackets.\n * \\param aSolSet The solution info set.\n * \\param aSol The solution info to bracket.\n * \\param aCalcCounter The calculation counter.\n * \\param period Model period\n * \\return Whether the market was successfully bracketed.\n */\nbool SolverLibrary::bracketOne( Marketplace* aMarketplace, World* aWorld, const double aDefaultBracketInterval,\n                                const unsigned int aMaxIterations, SolutionInfoSet& aSolSet, SolutionInfo* aSol,\n                                CalcCounter* aCalcCounter, const ISolutionInfoFilter* aSolutionInfoFilter, const int aPeriod )\n{\n    static const double LOWER_BOUND = util::getSmallNumber();\n\n    aSolSet.updateSolvable( aSolutionInfoFilter );\n    double bracketInterval = aSol->getBracketInterval( aDefaultBracketInterval );\n\n    // Logging\n    ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n    solverLog.setLevel( ILogger::NOTICE );\n    solverLog << \"Entering single market bracketing for market \" << aSol->getName() << \".\" << endl;\n    solverLog.setLevel( ILogger::DEBUG );\n    solverLog << \"Solution info set prior to bracket one.\" << endl;\n    solverLog << aSolSet << endl;\n\n    ILogger& singleLog = ILogger::getLogger( \"single_market_log\" );\n\n    aSol->resetBrackets();\n    unsigned int numIterations = 0;\n\n    // Loop is done at least once.\n    do {\n        aSolSet.printMarketInfo( \"Bracket One on \" + aSol->getName(),\n                                 aCalcCounter->getPeriodCount(),\n                                 singleLog );\n\n        // If ED at X and L are the same sign.\n        if ( util::sign( aSol->getED() ) == util::sign( aSol->getEDLeft() ) ) {\n            // If Supply > Demand at point X.\n            if ( aSol->getED() < 0 ) {\n                aSol->moveRightBracketToX();\n                if( !aSol->isCurrentlyBracketed() ){\n                    aSol->decreaseX( bracketInterval, LOWER_BOUND );\n                }\n                else {\n                    aSol->setBracketed();\n                }\n            }\n            else { // If Supply <= Demand. Price needs to increase.\n                aSol->moveLeftBracketToX();\n                if( !aSol->isCurrentlyBracketed() ){\n                    aSol->increaseX( bracketInterval, LOWER_BOUND );\n                }\n                else {\n                    aSol->setBracketed();\n                }\n            }\n        }\n        else {  // ED at X and R are the same sign.\n            if ( aSol->getED() < 0 ) { // If Supply > Demand at X.\n                aSol->moveRightBracketToX();\n                if( !aSol->isCurrentlyBracketed() ){\n                    aSol->decreaseX( bracketInterval, LOWER_BOUND );\n                }\n                else {\n                    aSol->setBracketed();\n                }\n            }\n            else { // If Supply <= Demand at X. Prices need to increase.\n                aSol->moveLeftBracketToX();\n                if( !aSol->isCurrentlyBracketed() ){\n                    aSol->increaseX( bracketInterval, LOWER_BOUND );\n                }\n                else {\n                    aSol->setBracketed();\n                }\n            }\n        }\n        // Check if the market is actually solved.\n        if( aSol->isSolved() ){\n            aSol->setBracketed();\n            aSol->moveLeftBracketToX();\n            aSol->moveRightBracketToX();\n        }\n\n        aMarketplace->nullSuppliesAndDemands( aPeriod );\n        aWorld->calc( aPeriod );\n        aSolSet.updateSolvable( aSolutionInfoFilter );\n        solverLog.setLevel( ILogger::NOTICE );\n        solverLog << \"Completed an iteration of bracketOne.\" << endl;\n        solverLog << *aSol << endl;\n    } while ( ++numIterations < aMaxIterations && !aSol->isBracketed() );\n\n    solverLog.setLevel( ILogger::NOTICE );\n    solverLog << \"Exiting single market bracketing.\" << endl;\n    solverLog.setLevel( ILogger::DEBUG );\n    solverLog << \"Solution info set after bracket one.\" << endl;\n    solverLog << aSolSet << endl;\n\n    return aSol->isBracketed();\n}\n\n/*! \\brief Store the current prices in the solver set in a vector.\n* \\param aSolutionSet Solution set.\n* \\return Vector of prices currently in the solver set.\n*/\nvector<double> SolverLibrary::storePrices( const SolutionInfoSet& aSolutionSet ){\n    vector<double> storedPrices;\n    for( unsigned int i = 0; i < aSolutionSet.getNumTotal(); ++i ){\n        storedPrices.push_back( aSolutionSet.getAny( i ).getPrice() );\n    }\n    return storedPrices;\n}\n\n/*! \\brief Restore prices in the solver set to the values of a given vector.\n* \\param aSolutionSet Solution set.\n* \\param aPrices Prices to set into the solver set.\n*/\nvoid SolverLibrary::restorePrices( SolutionInfoSet& aSolutionSet, const vector<double>& aPrices ){\n    /*! \\pre One price per market. */\n    assert( aSolutionSet.getNumTotal() == aPrices.size() );\n    for( unsigned int i = 0; i < aSolutionSet.getNumTotal(); ++i ){\n        aSolutionSet.getAny( i ).setPrice( aPrices[ i ] );\n    }\n}\n", "meta": {"hexsha": "1398bcd5e637c2d05743ebf7b36f117c2b7c68ba", "size": 29363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/solution/util/source/solver_library.cpp", "max_stars_repo_name": "ypwong22/gcam-core", "max_stars_repo_head_hexsha": "f8138153e52b5e875b1775406d2de70868587149", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cvs/objects/solution/util/source/solver_library.cpp", "max_issues_repo_name": "ypwong22/gcam-core", "max_issues_repo_head_hexsha": "f8138153e52b5e875b1775406d2de70868587149", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvs/objects/solution/util/source/solver_library.cpp", "max_forks_repo_name": "ypwong22/gcam-core", "max_forks_repo_head_hexsha": "f8138153e52b5e875b1775406d2de70868587149", "max_forks_repo_licenses": ["ECL-2.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.2409448819, "max_line_length": 161, "alphanum_fraction": 0.6388652386, "num_tokens": 6741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.020023440887407883, "lm_q1q2_score": 0.009933505469018762}}
{"text": "// $Id$\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n//  Contribution from Roger Sayle\n#include <vector>\n#include \"Pubchem.h\"\n#include <DataStructs/ExplicitBitVect.h>\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/SmilesParse/SmilesParse.h>\n#include <GraphMol/Substruct/SubstructMatch.h>\n#include <GraphMol/MolOps.h>\n\n#include <RDGeneral/BoostStartInclude.h>\n#include <boost/flyweight.hpp>\n#include <boost/flyweight/no_tracking.hpp>\n#include <RDGeneral/BoostEndInclude.h>\n\nnamespace {\nstruct Patterns {\n  std::unique_ptr<RDKit::ROMol> bit_8 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]1~*~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_11 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*1~*~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_13 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#8]~[#7](~[#6])~[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_14 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16]-[#16]\"));\n  std::unique_ptr<RDKit::ROMol> bit_15 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#8]~[#6](~[#8])~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_16 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]1~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_17 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]#[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_19 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*1~*~*~*~*~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_20 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#14]\"));\n  std::unique_ptr<RDKit::ROMol> bit_21 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#6]=[#6](~[!#6!#1])~[!#6!#1]\"));\n  std::unique_ptr<RDKit::ROMol> bit_22 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*1~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_23 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#7]~[#6](~[#8])~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_24 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]-[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_25 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#7]~[#6](~[#7])~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_26 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]=@[#6](@*)@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_28 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1]~[CH2]~[!#6!#1]\"));\n  std::unique_ptr<RDKit::ROMol> bit_30 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#6]~[!#6!#1](~[#6])(~[#6])~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_31 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[F,Cl,Br,I]\"));\n  std::unique_ptr<RDKit::ROMol> bit_32 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]~[#16]~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_33 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~[#16]\"));\n  std::unique_ptr<RDKit::ROMol> bit_34 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[CH2]=*\"));\n  std::unique_ptr<RDKit::ROMol> bit_36 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16R]\"));\n  std::unique_ptr<RDKit::ROMol> bit_37 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#7]~[#6](~[#8])~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_38 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#7]~[#6](~[#6])~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_39 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#8]~[#16](~[#8])~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_40 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16]-[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_41 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]#[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_43 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1!H0]~*~[!#6!#1!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_44 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\n          \"[!#1;!#6;!#7;!#8;!#9;!#14;!#15;!#16;!#17;!#35;!#53]\"));\n  std::unique_ptr<RDKit::ROMol> bit_45 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]=[#6]~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_47 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16]~*~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_48 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#8]~[!#6!#1](~[#8])~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_49 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!+0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_50 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#6]=[#6](~[#6])~[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_51 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]~[#16]~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_52 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_53 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1!H0]~*~*~*~[!#6!#1!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_54 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1!H0]~*~*~[!#6!#1!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_55 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]~[#16]~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_56 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#8]~[#7](~[#8])~[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_57 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8R]\"));\n  std::unique_ptr<RDKit::ROMol> bit_58 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1]~[#16]~[!#6!#1]\"));\n  std::unique_ptr<RDKit::ROMol> bit_59 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16]!:*:*\"));\n  std::unique_ptr<RDKit::ROMol> bit_60 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16]=[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_61 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*~[#16](~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_62 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*@*!@*@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_63 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]=[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_64 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*@*!@[#16]\"));\n  std::unique_ptr<RDKit::ROMol> bit_65 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"c:n\"));\n  std::unique_ptr<RDKit::ROMol> bit_66 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#6]~[#6](~[#6])(~[#6])~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_67 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[#16]\"));\n  std::unique_ptr<RDKit::ROMol> bit_68 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1!H0]~[!#6!#1!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_69 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[!#6!#1!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_70 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1]~[#7]~[!#6!#1]\"));\n  std::unique_ptr<RDKit::ROMol> bit_71 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_72 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]~*~*~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_73 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16]=*\"));\n  std::unique_ptr<RDKit::ROMol> bit_74 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[CH3]~*~[CH3]\"));\n  std::unique_ptr<RDKit::ROMol> bit_75 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*!@[#7]@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_76 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]=[#6](~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_77 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_78 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]=[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_79 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*~*~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_80 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*~*~*~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_81 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#16]~*(~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_82 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*~[CH2]~[!#6!#1!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_83 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]1~*~*~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_84 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[NH2]\"));\n  std::unique_ptr<RDKit::ROMol> bit_85 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#6]~[#7](~[#6])~[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_86 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[C;H2,H3][!#6!#1][C;H2,H3]\"));\n  std::unique_ptr<RDKit::ROMol> bit_87 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[F,Cl,Br,I]!@*@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_89 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]~*~*~*~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_90 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[$([!#6!#1!H0]~*~*~[CH2]~*),$([!#6!#1!H0R]1@[R]@[R]@[\"\n                         \"CH2R]1),$([!#6!#1!H0]~[R]1@[R]@[CH2R]1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_91 = std::unique_ptr<\n      RDKit::ROMol>(RDKit::SmartsToMol(\n      \"[$([!#6!#1!H0]~*~*~*~[CH2]~*),$([!#6!#1!H0R]1@[R]@[R]@[R]@[CH2R]1),$([!#\"\n      \"6!#1!H0]~[R]1@[R]@[R]@[CH2R]1),$([!#6!#1!H0]~*~[R]1@[R]@[CH2R]1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_92 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#8]~[#6](~[#7])~[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_93 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[CH3]\"));\n  std::unique_ptr<RDKit::ROMol> bit_94 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_95 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*~*~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_96 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*1~*~*~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_97 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*~*~*~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_98 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1]1~*~*~*~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_99 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]=[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_100 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*~[CH2]~[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_101 = std::unique_ptr<\n      RDKit::ROMol>(RDKit::SmartsToMol(\n      \"[$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[\"\n      \"R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[\"\n      \"R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]\"\n      \"@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@\"\n      \"1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_102 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_104 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1!H0]~*~[CH2]~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_105 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*@*(@*)@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_106 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[!#6!#1]~*(~[!#6!#1])~[!#6!#1]\"));\n  std::unique_ptr<RDKit::ROMol> bit_107 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[F,Cl,Br,I]~*(~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_108 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[CH3]~*~*~*~[CH2]~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_109 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*~[CH2]~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_110 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~[#6]~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_111 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*~[CH2]~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_112 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*~*(~*)(~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_113 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]!:*:*\"));\n  std::unique_ptr<RDKit::ROMol> bit_114 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[CH3]~[CH2]~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_115 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[CH3]~*~[CH2]~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_116 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[$([CH3]~*~*~[CH2]~*),$([CH3]~*1~*~[CH2]1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_117 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_118 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[$(*~[CH2]~[CH2]~*),$(*1~[CH2]~[CH2]1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_119 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]=*\"));\n  std::unique_ptr<RDKit::ROMol> bit_120 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6R]\"));\n  std::unique_ptr<RDKit::ROMol> bit_121 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7R]\"));\n  std::unique_ptr<RDKit::ROMol> bit_122 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*~[#7](~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_123 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]~[#6]~[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_124 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[!#6!#1]\"));\n  std::unique_ptr<RDKit::ROMol> bit_126 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*!@[#8]!@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_127 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*@*!@[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_128 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\n          \"[$(*~[CH2]~*~*~*~[CH2]~*),$([R]1@[CH2R]@[R]@[R]@[R]@[CH2R]1),$(*~[\"\n          \"CH2]~[R]1@[R]@[R]@[CH2R]1),$(*~[CH2]~*~[R]1@[R]@[CH2R]1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_129 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[$(*~[CH2]~*~*~[CH2]~*),$([R]1@[CH2]@[R]@[R]@[CH2R]1)\"\n                         \",$(*~[CH2]~[R]1@[R]@[CH2R]1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_131 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_132 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]~*~[CH2]~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_133 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*@*!@[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_135 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]!:*:*\"));\n  std::unique_ptr<RDKit::ROMol> bit_136 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]=*\"));\n  std::unique_ptr<RDKit::ROMol> bit_137 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!C!cR]\"));\n  std::unique_ptr<RDKit::ROMol> bit_138 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[!#6!#1]~[CH2]~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_139 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[O!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_140 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_141 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[CH3]\"));\n  std::unique_ptr<RDKit::ROMol> bit_142 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_144 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*!:*:*!:*\"));\n  std::unique_ptr<RDKit::ROMol> bit_145 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*1~*~*~*~*~*~1\"));\n  std::unique_ptr<RDKit::ROMol> bit_147 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[$(*~[CH2]~[CH2]~*),$([R]1@[CH2R]@[CH2R]1)]\"));\n  std::unique_ptr<RDKit::ROMol> bit_148 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*~[!#6!#1](~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_149 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[C;H3,H4]\"));\n  std::unique_ptr<RDKit::ROMol> bit_150 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*!@*@*!@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_151 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7!H0]\"));\n  std::unique_ptr<RDKit::ROMol> bit_152 = std::unique_ptr<RDKit::ROMol>(\n      RDKit::SmartsToMol(\"[#8]~[#6](~[#6])~[#6]\"));\n  std::unique_ptr<RDKit::ROMol> bit_154 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]=[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_155 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"*!@[CH2]!@*\"));\n  std::unique_ptr<RDKit::ROMol> bit_156 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#7]~*(~*)~*\"));\n  std::unique_ptr<RDKit::ROMol> bit_157 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]-[#8]\"));\n  std::unique_ptr<RDKit::ROMol> bit_158 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[#6]-[#7]\"));\n  std::unique_ptr<RDKit::ROMol> bit_162 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"a\"));\n  std::unique_ptr<RDKit::ROMol> bit_165 =\n      std::unique_ptr<RDKit::ROMol>(RDKit::SmartsToMol(\"[R]\"));\n};\n\nboost::flyweight<std::unique_ptr<Patterns>, boost::flyweights::no_tracking>\n    gpats;\nvoid GenerateFP(const RDKit::ROMol &mol, ExplicitBitVect &fp) {\n  if (!gpats.get()) {\n    gpats = std::unique_ptr<Patterns>(new Patterns());\n  }\n  const Patterns &pats = *(gpats.get());\n  PRECONDITION(fp.size() == 167, \"bad fingerprint\");\n  fp.clearBits();\n\n  if (!mol.getNumAtoms()) {\n    return;\n  }\n\n  std::vector<RDKit::MatchVectType> matches;\n  RDKit::RWMol::ConstAtomIterator atom;\n  RDKit::MatchVectType match;\n  unsigned int count;\n\n  for (atom = mol.beginAtoms(); atom != mol.endAtoms(); ++atom) {\n    switch ((*atom)->getAtomicNum()) {\n      case 3:\n      case 11:\n      case 19:\n      case 37:\n      case 55:\n      case 87:\n        fp.setBit(35);\n        break;\n      case 4:\n      case 12:\n      case 20:\n      case 38:\n      case 56:\n      case 88:\n        fp.setBit(10);\n        break;\n      case 5:\n      case 13:\n      case 31:\n      case 49:\n      case 81:\n        fp.setBit(18);\n        break;\n      case 9:\n        fp.setBit(42);\n        fp.setBit(134);\n        break;\n      case 15:\n        fp.setBit(29);\n        break;\n      case 16:\n        fp.setBit(88);\n        break;\n      case 17:\n        fp.setBit(103);\n        fp.setBit(134);\n        break;\n      case 21:\n      case 22:\n      case 39:\n      case 40:\n      case 72:\n        fp.setBit(5);\n        break;\n      case 23:\n      case 24:\n      case 25:\n      case 41:\n      case 42:\n      case 43:\n      case 73:\n      case 74:\n      case 75:\n        fp.setBit(7);\n        break;\n      case 26:\n      case 27:\n      case 28:\n      case 44:\n      case 45:\n      case 46:\n      case 76:\n      case 77:\n      case 78:\n        fp.setBit(9);\n        break;\n      case 29:\n      case 30:\n      case 47:\n      case 48:\n      case 79:\n      case 80:\n        fp.setBit(12);\n        break;\n      case 32:\n      case 33:\n      case 34:\n      case 50:\n      case 51:\n      case 52:\n      case 82:\n      case 83:\n      case 84:\n        fp.setBit(3);\n        break;\n      case 35:\n        fp.setBit(46);\n        fp.setBit(134);\n        break;\n      case 53:\n        fp.setBit(27);\n        fp.setBit(134);\n        break;\n      case 57:\n      case 58:\n      case 59:\n      case 60:\n      case 61:\n      case 62:\n      case 63:\n      case 64:\n      case 65:\n      case 66:\n      case 67:\n      case 68:\n      case 69:\n      case 70:\n      case 71:\n        fp.setBit(6);\n        break;\n      case 89:\n      case 90:\n      case 91:\n      case 92:\n      case 93:\n      case 94:\n      case 95:\n      case 96:\n      case 97:\n      case 98:\n      case 99:\n      case 100:\n      case 101:\n      case 102:\n      case 103:\n        fp.setBit(4);\n        break;\n      case 104:\n        fp.setBit(2);\n        break;\n    }\n  }\n\n  if (RDKit::SubstructMatch(mol, *pats.bit_8, match, true)) {\n    fp.setBit(8);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_11, match, true)) {\n    fp.setBit(11);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_13, match, true)) {\n    fp.setBit(13);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_14, match, true)) {\n    fp.setBit(14);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_15, match, true)) {\n    fp.setBit(15);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_16, match, true)) {\n    fp.setBit(16);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_17, match, true)) {\n    fp.setBit(17);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_19, match, true)) {\n    fp.setBit(19);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_20, match, true)) {\n    fp.setBit(20);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_21, match, true)) {\n    fp.setBit(21);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_22, match, true)) {\n    fp.setBit(22);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_23, match, true)) {\n    fp.setBit(23);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_24, match, true)) {\n    fp.setBit(24);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_25, match, true)) {\n    fp.setBit(25);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_26, match, true)) {\n    fp.setBit(26);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_28, match, true)) {\n    fp.setBit(28);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_30, match, true)) {\n    fp.setBit(30);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_31, match, true)) {\n    fp.setBit(31);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_32, match, true)) {\n    fp.setBit(32);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_33, match, true)) {\n    fp.setBit(33);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_34, match, true)) {\n    fp.setBit(34);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_36, match, true)) {\n    fp.setBit(36);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_37, match, true)) {\n    fp.setBit(37);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_38, match, true)) {\n    fp.setBit(38);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_39, match, true)) {\n    fp.setBit(39);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_40, match, true)) {\n    fp.setBit(40);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_41, match, true)) {\n    fp.setBit(41);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_43, match, true)) {\n    fp.setBit(43);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_44, match, true)) {\n    fp.setBit(44);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_45, match, true)) {\n    fp.setBit(45);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_47, match, true)) {\n    fp.setBit(47);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_48, match, true)) {\n    fp.setBit(48);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_49, match, true)) {\n    fp.setBit(49);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_50, match, true)) {\n    fp.setBit(50);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_51, match, true)) {\n    fp.setBit(51);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_52, match, true)) {\n    fp.setBit(52);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_53, match, true)) {\n    fp.setBit(53);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_54, match, true)) {\n    fp.setBit(54);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_55, match, true)) {\n    fp.setBit(55);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_56, match, true)) {\n    fp.setBit(56);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_57, match, true)) {\n    fp.setBit(57);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_58, match, true)) {\n    fp.setBit(58);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_59, match, true)) {\n    fp.setBit(59);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_60, match, true)) {\n    fp.setBit(60);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_61, match, true)) {\n    fp.setBit(61);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_62, match, true)) {\n    fp.setBit(62);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_63, match, true)) {\n    fp.setBit(63);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_64, match, true)) {\n    fp.setBit(64);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_65, match, true)) {\n    fp.setBit(65);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_66, match, true)) {\n    fp.setBit(66);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_67, match, true)) {\n    fp.setBit(67);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_68, match, true)) {\n    fp.setBit(68);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_69, match, true)) {\n    fp.setBit(69);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_70, match, true)) {\n    fp.setBit(70);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_71, match, true)) {\n    fp.setBit(71);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_72, match, true)) {\n    fp.setBit(72);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_73, match, true)) {\n    fp.setBit(73);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_74, match, true)) {\n    fp.setBit(74);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_75, match, true)) {\n    fp.setBit(75);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_76, match, true)) {\n    fp.setBit(76);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_77, match, true)) {\n    fp.setBit(77);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_78, match, true)) {\n    fp.setBit(78);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_79, match, true)) {\n    fp.setBit(79);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_80, match, true)) {\n    fp.setBit(80);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_81, match, true)) {\n    fp.setBit(81);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_82, match, true)) {\n    fp.setBit(82);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_83, match, true)) {\n    fp.setBit(83);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_84, match, true)) {\n    fp.setBit(84);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_85, match, true)) {\n    fp.setBit(85);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_86, match, true)) {\n    fp.setBit(86);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_87, match, true)) {\n    fp.setBit(87);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_89, match, true)) {\n    fp.setBit(89);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_90, match, true)) {\n    fp.setBit(90);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_91, match, true)) {\n    fp.setBit(91);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_92, match, true)) {\n    fp.setBit(92);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_93, match, true)) {\n    fp.setBit(93);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_94, match, true)) {\n    fp.setBit(94);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_95, match, true)) {\n    fp.setBit(95);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_96, match, true)) {\n    fp.setBit(96);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_97, match, true)) {\n    fp.setBit(97);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_98, match, true)) {\n    fp.setBit(98);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_99, match, true)) {\n    fp.setBit(99);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_100, match, true)) {\n    fp.setBit(100);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_101, match, true)) {\n    fp.setBit(101);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_102, match, true)) {\n    fp.setBit(102);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_104, match, true)) {\n    fp.setBit(104);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_105, match, true)) {\n    fp.setBit(105);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_106, match, true)) {\n    fp.setBit(106);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_107, match, true)) {\n    fp.setBit(107);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_108, match, true)) {\n    fp.setBit(108);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_109, match, true)) {\n    fp.setBit(109);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_110, match, true)) {\n    fp.setBit(110);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_111, match, true)) {\n    fp.setBit(111);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_112, match, true)) {\n    fp.setBit(112);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_113, match, true)) {\n    fp.setBit(113);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_114, match, true)) {\n    fp.setBit(114);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_115, match, true)) {\n    fp.setBit(115);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_116, match, true)) {\n    fp.setBit(116);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_117, match, true)) {\n    fp.setBit(117);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_118, matches, true, true) > 1) {\n    fp.setBit(118);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_119, match, true)) {\n    fp.setBit(119);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_120, matches, true, true) > 1) {\n    fp.setBit(120);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_121, match, true)) {\n    fp.setBit(121);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_122, match, true)) {\n    fp.setBit(122);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_123, match, true)) {\n    fp.setBit(123);\n  }\n  count = RDKit::SubstructMatch(mol, *pats.bit_124, matches, true, true);\n  if (count > 0) {\n    fp.setBit(124);\n  }\n  if (count > 1) {\n    fp.setBit(130);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_126, match, true)) {\n    fp.setBit(126);\n  }\n  count = RDKit::SubstructMatch(mol, *pats.bit_127, matches, true, true);\n  if (count > 1) {\n    fp.setBit(127);\n  }\n  if (count > 0) {\n    fp.setBit(143);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_128, match, true)) {\n    fp.setBit(128);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_129, match, true)) {\n    fp.setBit(129);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_131, matches, true, true) > 1) {\n    fp.setBit(131);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_132, match, true)) {\n    fp.setBit(132);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_133, match, true)) {\n    fp.setBit(133);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_135, match, true)) {\n    fp.setBit(135);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_136, matches, true, true) > 1) {\n    fp.setBit(136);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_137, match, true)) {\n    fp.setBit(137);\n  }\n  count = RDKit::SubstructMatch(mol, *pats.bit_138, matches, true, true);\n  if (count > 1) {\n    fp.setBit(138);\n  }\n  if (count > 0) {\n    fp.setBit(153);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_139, match, true)) {\n    fp.setBit(139);\n  }\n  count = RDKit::SubstructMatch(mol, *pats.bit_140, matches, true, true);\n  if (count > 3) {\n    fp.setBit(140);\n  }\n  if (count > 2) {\n    fp.setBit(146);\n  }\n  if (count > 1) {\n    fp.setBit(159);\n  }\n  if (count > 0) {\n    fp.setBit(164);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_141, matches, true, true) > 2) {\n    fp.setBit(141);\n  }\n  count = RDKit::SubstructMatch(mol, *pats.bit_142, matches, true, true);\n  if (count > 1) {\n    fp.setBit(142);\n  }\n  if (count > 0) {\n    fp.setBit(161);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_144, match, true)) {\n    fp.setBit(144);\n  }\n  count = RDKit::SubstructMatch(mol, *pats.bit_145, matches, true, true);\n  if (count > 1) {\n    fp.setBit(145);\n  }\n  if (count > 0) {\n    fp.setBit(163);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_147, match, true)) {\n    fp.setBit(147);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_148, match, true)) {\n    fp.setBit(148);\n  }\n  count = RDKit::SubstructMatch(mol, *pats.bit_149, matches, true, true);\n  if (count > 1) {\n    fp.setBit(149);\n  }\n  if (count > 0) {\n    fp.setBit(160);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_150, match, true)) {\n    fp.setBit(150);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_151, match, true)) {\n    fp.setBit(151);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_152, match, true)) {\n    fp.setBit(152);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_154, match, true)) {\n    fp.setBit(154);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_155, match, true)) {\n    fp.setBit(155);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_156, match, true)) {\n    fp.setBit(156);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_157, match, true)) {\n    fp.setBit(157);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_158, match, true)) {\n    fp.setBit(158);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_162, match, true)) {\n    fp.setBit(162);\n  }\n  if (RDKit::SubstructMatch(mol, *pats.bit_165, match, true)) {\n    fp.setBit(165);\n  }\n\n  /* BIT 125 */\n  RDKit::RingInfo *info = mol.getRingInfo();\n  unsigned int ringcount = info->numRings();\n  unsigned int nArom = 0;\n  for (unsigned int i = 0; i < ringcount; i++) {\n    bool isArom = true;\n    const std::vector<int> *ring = &info->bondRings()[i];\n    std::vector<int>::const_iterator iter;\n    for (iter = ring->begin(); iter != ring->end(); ++iter) {\n      if (!mol.getBondWithIdx(*iter)->getIsAromatic()) {\n        isArom = false;\n        break;\n      }\n    }\n    if (isArom) {\n      if (nArom) {\n        fp.setBit(125);\n        break;\n      } else {\n        nArom++;\n      }\n    }\n  }\n\n  /* BIT 166 */\n  std::vector<int> mapping;\n  if (RDKit::MolOps::getMolFrags(mol, mapping) > 1) {\n    fp.setBit(166);\n  }\n}\n}  // namespace\n\nnamespace RDKit {\nnamespace MACCSFingerprints {\nExplicitBitVect *getFingerprintAsBitVect(const ROMol &mol) {\n  auto *fp = new ExplicitBitVect(167);\n  GenerateFP(mol, *fp);\n  return fp;\n}\n}  // namespace MACCSFingerprints\n}  // namespace RDKit\n", "meta": {"hexsha": "1725937729b7b87b75dea7e57be2b964eccb6b9c", "size": 33703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Fingerprints/MACCS.cpp", "max_stars_repo_name": "wojiaozhangyang/rdkit-fp", "max_stars_repo_head_hexsha": "6fdd705f1043c78d762e8a4ee0382635fe71881a", "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/Fingerprints/MACCS.cpp", "max_issues_repo_name": "wojiaozhangyang/rdkit-fp", "max_issues_repo_head_hexsha": "6fdd705f1043c78d762e8a4ee0382635fe71881a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/GraphMol/Fingerprints/MACCS.cpp", "max_forks_repo_name": "wojiaozhangyang/rdkit-fp", "max_forks_repo_head_hexsha": "6fdd705f1043c78d762e8a4ee0382635fe71881a", "max_forks_repo_licenses": ["BSD-3-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.5142255005, "max_line_length": 80, "alphanum_fraction": 0.5939530606, "num_tokens": 13382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.023689469791582207, "lm_q1q2_score": 0.009918707786010374}}
{"text": "/*\nWork in progress: patch by Marco (AUG,19th 2012)\n> oni fixed\n> pcl added: mostly to include rgb treatment while grabbing from PCD files obtained by pcl_openni_grab_frame -noend \n> sync issue fixed\n> volume_size issue fixed\n> world.pcd write exception on windows fixed on new trunk version\n\n+ minor changes\n*/\n\n/*\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2011, 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 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*  Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)\n*/\n\n#define _CRT_SECURE_NO_DEPRECATE\n\n#include <iostream>\n\n#include <pcl/console/parse.h>\n\n#include <boost/filesystem.hpp>\n\n#include <pcl/gpu/kinfu_large_scale/kinfu.h>\n#include <pcl/gpu/kinfu_large_scale/raycaster.h>\n#include <pcl/gpu/kinfu_large_scale/marching_cubes.h>\n#include <pcl/gpu/containers/initialization.h>\n\n#include <pcl/common/time.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/visualization/image_viewer.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/ply_io.h>\n#include <pcl/io/vtk_io.h>\n#include <pcl/io/openni_grabber.h>\n#include <pcl/io/oni_grabber.h>\n#include <pcl/io/pcd_grabber.h>\n\n#include \"openni_capture.h\"\n#include \"color_handler.h\"\n#include \"evaluation.h\"\n\n#include <pcl/common/angles.h>\n\n#ifdef HAVE_OPENCV  \n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#endif\ntypedef pcl::ScopeTime ScopeTimeT;\n\n#include <pcl/gpu/kinfu_large_scale/screenshot_manager.h>\n\nusing namespace std;\nusing namespace pcl;\nusing namespace Eigen;\n\nusing namespace pcl::gpu::kinfuLS;\n\nusing pcl::gpu::DeviceArray;\nusing pcl::gpu::DeviceArray2D;\nusing pcl::gpu::PtrStepSz;\n\nnamespace pc = pcl::console;\n\nnamespace pcl\n{\n  namespace gpu\n  {\n    namespace kinfuLS\n    {\n      void paint3DView (const KinfuTracker::View& rgb24, KinfuTracker::View& view, float colors_weight = 0.5f);\n      void mergePointNormal (const DeviceArray<PointXYZ>& cloud, const DeviceArray<Normal>& normals, DeviceArray<PointNormal>& output);\n    }\n  }\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvector<string> getPcdFilesInDir(const string& directory)\n{\n  namespace fs = boost::filesystem;\n  fs::path dir(directory);\n\n  std::cout << \"path: \" << directory << std::endl;\n  if (directory.empty() || !fs::exists(dir) || !fs::is_directory(dir))\n          PCL_THROW_EXCEPTION (pcl::IOException, \"No valid PCD directory given!\\n\");\n\n  vector<string> result;\n  fs::directory_iterator pos(dir);\n  fs::directory_iterator end;           \n\n  for(; pos != end ; ++pos)\n    if (fs::is_regular_file(pos->status()) )\n      if (fs::extension(*pos) == \".pcd\")\n      {\n#if BOOST_FILESYSTEM_VERSION == 3\n        result.push_back (pos->path ().string ());\n#else\n        result.push_back (pos->path ());\n#endif\n        cout << \"added: \" << result.back() << endl;\n      }\n\n  return result;  \n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstruct SampledScopeTime : public StopWatch\n{          \n  enum { EACH = 33 };\n  SampledScopeTime(int& time_ms) : time_ms_(time_ms) {}\n  ~SampledScopeTime()\n  {\n    static int i_ = 0;\n    static boost::posix_time::ptime starttime_ = boost::posix_time::microsec_clock::local_time();\n    time_ms_ += getTime ();\n    if (i_ % EACH == 0 && i_)\n    {\n      boost::posix_time::ptime endtime_ = boost::posix_time::microsec_clock::local_time();\n      cout << \"Average frame time = \" << time_ms_ / EACH << \"ms ( \" << 1000.f * EACH / time_ms_ << \"fps )\"\n           << \"( real: \" << 1000.f * EACH / (endtime_-starttime_).total_milliseconds() << \"fps )\"  << endl;\n      time_ms_ = 0;\n      starttime_ = endtime_;\n    }\n    ++i_;\n  }\nprivate:    \n  int& time_ms_;    \n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\nsetViewerPose (visualization::PCLVisualizer& viewer, const Eigen::Affine3f& viewer_pose)\n{\n  Eigen::Vector3f pos_vector = viewer_pose * Eigen::Vector3f (0, 0, 0);\n  Eigen::Vector3f look_at_vector = viewer_pose.rotation () * Eigen::Vector3f (0, 0, 1) + pos_vector;\n  Eigen::Vector3f up_vector = viewer_pose.rotation () * Eigen::Vector3f (0, -1, 0);\n  viewer.setCameraPosition (pos_vector[0], pos_vector[1], pos_vector[2],\n                            look_at_vector[0], look_at_vector[1], look_at_vector[2],\n                            up_vector[0], up_vector[1], up_vector[2]);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nEigen::Affine3f \ngetViewerPose (visualization::PCLVisualizer& viewer)\n{\n  Eigen::Affine3f pose = viewer.getViewerPose();\n  Eigen::Matrix3f rotation = pose.linear();\n\n  Matrix3f axis_reorder;  \n  axis_reorder << 0,  0,  1,\n          -1,  0,  0,\n          0, -1,  0;\n\n  rotation = rotation * axis_reorder;\n  pose.linear() = rotation;\n  return pose;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ntemplate<typename CloudT> void\nwriteCloudFile (int format, const CloudT& cloud);\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nvoid\nwritePolygonMeshFile (int format, const pcl::PolygonMesh& mesh);\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ntemplate<typename MergedT, typename PointT>\ntypename PointCloud<MergedT>::Ptr merge(const PointCloud<PointT>& points, const PointCloud<RGB>& colors)\n{    \n  typename PointCloud<MergedT>::Ptr merged_ptr(new PointCloud<MergedT>());\n\n  pcl::copyPointCloud (points, *merged_ptr);      \n  for (size_t i = 0; i < colors.size (); ++i)\n    merged_ptr->points[i].rgba = colors.points[i].rgba;\n\n  return merged_ptr;\n}\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nboost::shared_ptr<pcl::PolygonMesh> convertToMesh(const DeviceArray<PointXYZ>& triangles)\n{ \n  if (triangles.empty())\n          return boost::shared_ptr<pcl::PolygonMesh>();\n\n  pcl::PointCloud<pcl::PointXYZ> cloud;\n  cloud.width  = (int)triangles.size();\n  cloud.height = 1;\n  triangles.download(cloud.points);\n\n  boost::shared_ptr<pcl::PolygonMesh> mesh_ptr( new pcl::PolygonMesh() ); \n  pcl::toPCLPointCloud2(cloud, mesh_ptr->cloud);\n\n  mesh_ptr->polygons.resize (triangles.size() / 3);\n  for (size_t i = 0; i < mesh_ptr->polygons.size (); ++i)\n  {\n    pcl::Vertices v;\n    v.vertices.push_back(i*3+0);\n    v.vertices.push_back(i*3+2);\n    v.vertices.push_back(i*3+1);              \n    mesh_ptr->polygons[i] = v;\n  }    \n  return mesh_ptr;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstruct CurrentFrameCloudView\n{\n  CurrentFrameCloudView() : cloud_device_ (480, 640), cloud_viewer_ (\"Frame Cloud Viewer\")\n  {\n    cloud_ptr_ = PointCloud<PointXYZ>::Ptr (new PointCloud<PointXYZ>);\n\n    cloud_viewer_.setBackgroundColor (0, 0, 0.15);\n    cloud_viewer_.setPointCloudRenderingProperties (visualization::PCL_VISUALIZER_POINT_SIZE, 1);\n    cloud_viewer_.addCoordinateSystem (1.0, \"global\");\n    cloud_viewer_.initCameraParameters ();\n    cloud_viewer_.setPosition (0, 500);\n    cloud_viewer_.setSize (640, 480);\n    cloud_viewer_.setCameraClipDistances (0.01, 10.01);\n  }\n\n  void\n  show (const KinfuTracker& kinfu)\n  {\n    kinfu.getLastFrameCloud (cloud_device_);\n\n    int c;\n    cloud_device_.download (cloud_ptr_->points, c);\n    cloud_ptr_->width = cloud_device_.cols ();\n    cloud_ptr_->height = cloud_device_.rows ();\n    cloud_ptr_->is_dense = false;\n\n    cloud_viewer_.removeAllPointClouds ();\n    cloud_viewer_.addPointCloud<PointXYZ>(cloud_ptr_);\n    cloud_viewer_.spinOnce ();\n  }\n\n  void\n  setViewerPose (const Eigen::Affine3f& viewer_pose) {\n    ::setViewerPose (cloud_viewer_, viewer_pose);\n  }\n\n  PointCloud<PointXYZ>::Ptr cloud_ptr_;\n  DeviceArray2D<PointXYZ> cloud_device_;\n  visualization::PCLVisualizer cloud_viewer_;\n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstruct ImageView\n{\n  ImageView() : paint_image_ (false), accumulate_views_ (false)\n  {\n    viewerScene_.setWindowTitle (\"View3D from ray tracing\");\n    viewerScene_.setPosition (0, 0);\n    viewerDepth_.setWindowTitle (\"Kinect Depth stream\");\n    viewerDepth_.setPosition (640, 0);\n    //viewerColor_.setWindowTitle (\"Kinect RGB stream\");\n  }\n\n  void\n  showScene (KinfuTracker& kinfu, const PtrStepSz<const pcl::gpu::kinfuLS::PixelRGB>& rgb24, bool registration, Eigen::Affine3f* pose_ptr = 0)\n  {\n    if (pose_ptr)\n    {\n      raycaster_ptr_->run ( kinfu.volume (), *pose_ptr, kinfu.getCyclicalBufferStructure () ); //says in cmake it does not know it\n      raycaster_ptr_->generateSceneView(view_device_);\n    }\n    else\n    {\n      kinfu.getImage (view_device_);\n    }\n\n    if (paint_image_ && registration && !pose_ptr)\n    {\n      colors_device_.upload (rgb24.data, rgb24.step, rgb24.rows, rgb24.cols);\n      paint3DView (colors_device_, view_device_);\n    }\n\n    int cols;\n    view_device_.download (view_host_, cols);\n    viewerScene_.showRGBImage (reinterpret_cast<unsigned char*> (&view_host_[0]), view_device_.cols (), view_device_.rows ());    \n\n          //viewerColor_.showRGBImage ((unsigned char*)&rgb24.data, rgb24.cols, rgb24.rows);\n#ifdef HAVE_OPENCV\n    if (accumulate_views_)\n    {\n      views_.push_back (cv::Mat ());\n      cv::cvtColor (cv::Mat (480, 640, CV_8UC3, (void*)&view_host_[0]), views_.back (), CV_RGB2GRAY);\n      //cv::copy(cv::Mat(480, 640, CV_8UC3, (void*)&view_host_[0]), views_.back());\n    }\n#endif\n  }\n\n  void\n  showDepth (const PtrStepSz<const unsigned short>& depth) \n  { \n    viewerDepth_.showShortImage (depth.data, depth.cols, depth.rows, 0, 5000, true); \n  }\n\n  void\n  showGeneratedDepth (KinfuTracker& kinfu, const Eigen::Affine3f& pose)\n  {            \n    raycaster_ptr_->run(kinfu.volume(), pose, kinfu.getCyclicalBufferStructure ());\n    raycaster_ptr_->generateDepthImage(generated_depth_);    \n\n    int c;\n    vector<unsigned short> data;\n    generated_depth_.download(data, c);\n\n    viewerDepth_.showShortImage (&data[0], generated_depth_.cols(), generated_depth_.rows(), 0, 5000, true);\n  }\n\n  void\n  toggleImagePaint()\n  {\n    paint_image_ = !paint_image_;\n    cout << \"Paint image: \" << (paint_image_ ? \"On   (requires registration mode)\" : \"Off\") << endl;\n  }\n\n  bool paint_image_;\n  bool accumulate_views_;\n\n  visualization::ImageViewer viewerScene_; //view the raycasted model\n  visualization::ImageViewer viewerDepth_; //view the current depth map\n  //visualization::ImageViewer viewerColor_;\n\n  KinfuTracker::View view_device_;\n  KinfuTracker::View colors_device_;\n  vector<pcl::gpu::kinfuLS::PixelRGB> view_host_;\n\n  RayCaster::Ptr raycaster_ptr_;\n\n  KinfuTracker::DepthMap generated_depth_;\n\n#ifdef HAVE_OPENCV\n  vector<cv::Mat> views_;\n#endif\n};\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// View the volume as 3D points\nstruct SceneCloudView\n{\n  enum { GPU_Connected6 = 0, CPU_Connected6 = 1, CPU_Connected26 = 2 };\n\n  SceneCloudView() : extraction_mode_ (GPU_Connected6), compute_normals_ (false), valid_combined_ (false), cube_added_(false), cloud_viewer_ (\"Scene Cloud Viewer\")\n  {\n    cloud_ptr_ = PointCloud<PointXYZ>::Ptr (new PointCloud<PointXYZ>);\n    normals_ptr_ = PointCloud<Normal>::Ptr (new PointCloud<Normal>);\n    combined_ptr_ = PointCloud<PointNormal>::Ptr (new PointCloud<PointNormal>);\n    point_colors_ptr_ = PointCloud<RGB>::Ptr (new PointCloud<RGB>);\n\n    cloud_viewer_.setBackgroundColor (0, 0, 0);\n    cloud_viewer_.addCoordinateSystem (1.0, \"global\");\n    cloud_viewer_.initCameraParameters ();\n    cloud_viewer_.setPosition (0, 500);\n    cloud_viewer_.setSize (640, 480);\n    cloud_viewer_.setCameraClipDistances (0.01, 10.01);\n\n    cloud_viewer_.addText (\"H: print help\", 2, 15, 20, 34, 135, 246);         \n    cloud_viewer_.addText (\"ICP State: \", 450, 55, 20, 0.0, 1.0, 0.0, \"icp\");\n    cloud_viewer_.addText (\"Press 'S' to save the current world\", 450, 35, 10, 0.0, 1.0, 0.0, \"icp_save\");\n    cloud_viewer_.addText (\"Press 'R' to reset the system\", 450, 15, 10, 0.0, 1.0, 0.0, \"icp_reset\");\n  }\n  \n  inline void \n  drawCamera (Eigen::Affine3f& pose, const string& name, double r, double g, double b)\n  {\n    double focal = 575;\n    double height = 480;\n    double width = 640;\n    \n    // create a 5-point visual for each camera\n    pcl::PointXYZ p1, p2, p3, p4, p5;\n    p1.x=0; p1.y=0; p1.z=0;\n    double angleX = RAD2DEG (2.0 * atan (width / (2.0*focal)));\n    double angleY = RAD2DEG (2.0 * atan (height / (2.0*focal)));\n    double dist = 0.75;\n    double minX, minY, maxX, maxY;\n    maxX = dist*tan (atan (width / (2.0*focal)));\n    minX = -maxX;\n    maxY = dist*tan (atan (height / (2.0*focal)));\n    minY = -maxY;\n    p2.x=minX; p2.y=minY; p2.z=dist;\n    p3.x=maxX; p3.y=minY; p3.z=dist;\n    p4.x=maxX; p4.y=maxY; p4.z=dist;\n    p5.x=minX; p5.y=maxY; p5.z=dist;\n    p1=pcl::transformPoint (p1, pose);\n    p2=pcl::transformPoint (p2, pose);\n    p3=pcl::transformPoint (p3, pose);\n    p4=pcl::transformPoint (p4, pose);\n    p5=pcl::transformPoint (p5, pose);\n    std::stringstream ss;\n    ss.str (\"\");\n    ss << name << \"_line1\";\n    cloud_viewer_.addLine (p1, p2, r, g, b, ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line2\";\n    cloud_viewer_.addLine (p1, p3, r, g, b, ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line3\";\n    cloud_viewer_.addLine (p1, p4, r, g, b, ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line4\";\n    cloud_viewer_.addLine (p1, p5, r, g, b, ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line5\";\n    cloud_viewer_.addLine (p2, p5, r, g, b, ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line6\";\n    cloud_viewer_.addLine (p5, p4, r, g, b, ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line7\";\n    cloud_viewer_.addLine (p4, p3, r, g, b, ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line8\";\n    cloud_viewer_.addLine (p3, p2, r, g, b, ss.str ());    \n  }\n  \n  inline void \n  removeCamera (const string& name)\n  {\n    cloud_viewer_.removeShape (name);\n    std::stringstream ss;\n    ss.str (\"\");\n    ss << name << \"_line1\";\n    cloud_viewer_.removeShape (ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line2\";\n    cloud_viewer_.removeShape (ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line3\";\n    cloud_viewer_.removeShape (ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line4\";\n    cloud_viewer_.removeShape (ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line5\";\n    cloud_viewer_.removeShape (ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line6\";\n    cloud_viewer_.removeShape (ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line7\";\n    cloud_viewer_.removeShape (ss.str ());\n    ss.str (\"\");\n    ss << name << \"_line8\";\n    cloud_viewer_.removeShape (ss.str ());\n  }\n\n  void\n  displayICPState (KinfuTracker& kinfu, bool was_lost_)\n  {\n    string name = \"last_good_track\";\n    string name_estimate = \"last_good_estimate\";\n    if (was_lost_ && !kinfu.icpIsLost ()) //execute only when ICP just recovered (i.e. was_lost_ == true && icpIsLost == false)\n    {\n      removeCamera(name);\n      removeCamera(name_estimate);\n      clearClouds(false);\n      cloud_viewer_.updateText (\"ICP State: OK\", 450, 55, 20, 0.0, 1.0, 0.0, \"icp\");\n      cloud_viewer_.updateText (\"Press 'S' to save the current world\", 450, 35, 10, 0.0, 1.0, 0.0, \"icp_save\");\n      cloud_viewer_.updateText (\"Press 'R' to reset the system\", 450, 15, 10, 0.0, 1.0, 0.0, \"icp_reset\");\n    }\n    else if (!was_lost_ && kinfu.icpIsLost()) //execute only when we just lost ourselves (i.e. was_lost_ = false && icpIsLost == true)\n    { \n      // draw position of the last good track\n      Eigen::Affine3f last_pose = kinfu.getCameraPose();\n      drawCamera(last_pose, name, 0.0, 1.0, 0.0);\n      \n     \n      \n      cloud_viewer_.updateText (\"ICP State: LOST\", 450, 55, 20, 1.0, 0.0, 0.0, \"icp\");\n      cloud_viewer_.updateText (\"Press 'S' to save the current world\", 450, 35, 10, 1.0, 0.0, 0.0, \"icp_save\");\n      cloud_viewer_.updateText (\"Press 'R' to reset the system\", 450, 15, 10, 1.0, 0.0, 0.0, \"icp_reset\");\n    }\n    \n    \n    if( kinfu.icpIsLost() )\n    {\n      removeCamera(name_estimate);\n       // draw current camera estimate\n      Eigen::Affine3f last_pose_estimate = kinfu.getLastEstimatedPose();\n      drawCamera(last_pose_estimate, name_estimate, 1.0, 0.0, 0.0);      \n    }\n      \n      \n      \n//       cout << \"current estimated pose: \" << kinfu.getLastEstimatedPose().translation() << std::endl << kinfu.getLastEstimatedPose().linear() << std::endl;\n//     \n  }\n  \n  void\n  show (KinfuTracker& kinfu, bool integrate_colors)\n  {\n    viewer_pose_ = kinfu.getCameraPose();\n\n    ScopeTimeT time (\"PointCloud Extraction\");\n    cout << \"\\nGetting cloud... \" << flush;\n\n    valid_combined_ = false;\n\n    if (extraction_mode_ != GPU_Connected6)     // So use CPU\n    {\n      kinfu.volume().fetchCloudHost (*cloud_ptr_, extraction_mode_ == CPU_Connected26);\n    }\n    else\n    {\n      DeviceArray<PointXYZ> extracted = kinfu.volume().fetchCloud (cloud_buffer_device_);             \n\n      if (compute_normals_)\n      {\n        kinfu.volume().fetchNormals (extracted, normals_device_);\n        pcl::gpu::kinfuLS::mergePointNormal (extracted, normals_device_, combined_device_);\n        combined_device_.download (combined_ptr_->points);\n        combined_ptr_->width = (int)combined_ptr_->points.size ();\n        combined_ptr_->height = 1;\n\n        valid_combined_ = true;\n      }\n      else\n      {\n        extracted.download (cloud_ptr_->points);\n        cloud_ptr_->width = (int)cloud_ptr_->points.size ();\n        cloud_ptr_->height = 1;\n      }\n\n      if (integrate_colors)\n      {\n        kinfu.colorVolume().fetchColors(extracted, point_colors_device_);\n        point_colors_device_.download(point_colors_ptr_->points);\n        point_colors_ptr_->width = (int)point_colors_ptr_->points.size ();\n        point_colors_ptr_->height = 1;\n      }\n      else\n        point_colors_ptr_->points.clear();\n    }\n    size_t points_size = valid_combined_ ? combined_ptr_->points.size () : cloud_ptr_->points.size ();\n    cout << \"Done.  Cloud size: \" << points_size / 1000 << \"K\" << endl;\n\n    cloud_viewer_.removeAllPointClouds ();    \n    if (valid_combined_)\n    {\n      visualization::PointCloudColorHandlerRGBHack<PointNormal> rgb(combined_ptr_, point_colors_ptr_);\n      cloud_viewer_.addPointCloud<PointNormal> (combined_ptr_, rgb, \"Cloud\");\n      cloud_viewer_.addPointCloudNormals<PointNormal>(combined_ptr_, 50);\n    }\n    else\n    {\n      visualization::PointCloudColorHandlerRGBHack<PointXYZ> rgb(cloud_ptr_, point_colors_ptr_);\n      cloud_viewer_.addPointCloud<PointXYZ> (cloud_ptr_, rgb);\n    }    \n  }\n\n  void\n  toggleCube(const Eigen::Vector3f& size)\n  {\n    if (cube_added_)\n      cloud_viewer_.removeShape(\"cube\");\n    else\n      cloud_viewer_.addCube(size*0.5, Eigen::Quaternionf::Identity(), size(0), size(1), size(2));\n\n    cube_added_ = !cube_added_;\n  }\n\n  void\n  toggleExtractionMode ()\n  {\n    extraction_mode_ = (extraction_mode_ + 1) % 3;\n    switch (extraction_mode_)\n    {\n      case 0: cout << \"Cloud extraction mode: GPU, Connected-6\" << endl; break;\n      case 1: cout << \"Cloud extraction mode: CPU, Connected-6    (requires a lot of memory)\" << endl; break;\n      case 2: cout << \"Cloud extraction mode: CPU, Connected-26   (requires a lot of memory)\" << endl; break;\n    }         \n  }\n\n  void\n  toggleNormals ()\n  {\n    compute_normals_ = !compute_normals_;\n    cout << \"Compute normals: \" << (compute_normals_ ? \"On\" : \"Off\") << endl;\n  }\n\n  void\n  clearClouds (bool print_message = false)\n  {\n    cloud_viewer_.removeAllPointClouds ();\n    cloud_ptr_->points.clear ();\n    normals_ptr_->points.clear ();    \n    if (print_message)\n      cout << \"Clouds/Meshes were cleared\" << endl;\n  }\n\n  void\n  showMesh(KinfuTracker& kinfu, bool /*integrate_colors*/)\n  {\n    ScopeTimeT time (\"Mesh Extraction\");\n    cout << \"\\nGetting mesh... \" << flush;\n\n    if (!marching_cubes_)\n      marching_cubes_ = MarchingCubes::Ptr( new MarchingCubes() );\n\n    DeviceArray<PointXYZ> triangles_device = marching_cubes_->run(kinfu.volume(), triangles_buffer_device_);    \n    mesh_ptr_ = convertToMesh(triangles_device);\n\n    cloud_viewer_.removeAllPointClouds ();\n    if (mesh_ptr_)\n      cloud_viewer_.addPolygonMesh(*mesh_ptr_);\t\n\n    cout << \"Done.  Triangles number: \" << triangles_device.size() / MarchingCubes::POINTS_PER_TRIANGLE / 1000 << \"K\" << endl;\n  }\n\n  int extraction_mode_;\n  bool compute_normals_;\n  bool valid_combined_;\n  bool cube_added_;\n\n  Eigen::Affine3f viewer_pose_;\n\n  visualization::PCLVisualizer cloud_viewer_;\n\n  PointCloud<PointXYZ>::Ptr cloud_ptr_;\n  PointCloud<Normal>::Ptr normals_ptr_;\n\n  DeviceArray<PointXYZ> cloud_buffer_device_;\n  DeviceArray<Normal> normals_device_;\n\n  PointCloud<PointNormal>::Ptr combined_ptr_;\n  DeviceArray<PointNormal> combined_device_;  \n\n  DeviceArray<RGB> point_colors_device_; \n  PointCloud<RGB>::Ptr point_colors_ptr_;\n\n  MarchingCubes::Ptr marching_cubes_;\n  DeviceArray<PointXYZ> triangles_buffer_device_;\n\n  boost::shared_ptr<pcl::PolygonMesh> mesh_ptr_;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstruct KinFuLSApp\n{\n  enum { PCD_BIN = 1, PCD_ASCII = 2, PLY = 3, MESH_PLY = 7, MESH_VTK = 8 };\n\n  KinFuLSApp(pcl::Grabber& source, float vsz, float shiftDistance, int snapshotRate) : exit_ (false), scan_ (false), scan_mesh_(false), scan_volume_ (false), independent_camera_ (false),\n          registration_ (false), integrate_colors_ (false), pcd_source_ (false), focal_length_(-1.f), capture_ (source), was_lost_(false), time_ms_ (0)\n  {    \n    //Init Kinfu Tracker\n    Eigen::Vector3f volume_size = Vector3f::Constant (vsz/*meters*/);    \n\n    PCL_WARN (\"--- CURRENT SETTINGS ---\\n\");\n    PCL_INFO (\"Volume size is set to %.2f meters\\n\", vsz);\n    PCL_INFO (\"Volume will shift when the camera target point is farther than %.2f meters from the volume center\\n\", shiftDistance);\n    PCL_INFO (\"The target point is located at [0, 0, %.2f] in camera coordinates\\n\", 0.6*vsz);\n    PCL_WARN (\"------------------------\\n\");\n\n    // warning message if shifting distance is abnormally big compared to volume size\n    if(shiftDistance > 2.5 * vsz)\n      PCL_WARN (\"WARNING Shifting distance (%.2f) is very large compared to the volume size (%.2f).\\nYou can modify it using --shifting_distance.\\n\", shiftDistance, vsz);\n\n    kinfu_ = new pcl::gpu::kinfuLS::KinfuTracker(volume_size, shiftDistance);\n\n    Eigen::Matrix3f R = Eigen::Matrix3f::Identity ();   // * AngleAxisf( pcl::deg2rad(-30.f), Vector3f::UnitX());\n    Eigen::Vector3f t = volume_size * 0.5f - Vector3f (0, 0, volume_size (2) / 2 * 1.2f);\n\n    Eigen::Affine3f pose = Eigen::Translation3f (t) * Eigen::AngleAxisf (R);\n\n    kinfu_->setInitialCameraPose (pose);\n    kinfu_->volume().setTsdfTruncDist (0.030f/*meters*/);\n    kinfu_->setIcpCorespFilteringParams (0.1f/*meters*/, sin ( pcl::deg2rad(20.f) ));\n    //kinfu_->setDepthTruncationForICP(3.f/*meters*/);\n    kinfu_->setCameraMovementThreshold(0.001f);\n\n    //Init KinFuLSApp            \n    tsdf_cloud_ptr_ = pcl::PointCloud<pcl::PointXYZI>::Ptr (new pcl::PointCloud<pcl::PointXYZI>);\n    image_view_.raycaster_ptr_ = RayCaster::Ptr( new RayCaster(kinfu_->rows (), kinfu_->cols ()) );\n\n    scene_cloud_view_.cloud_viewer_.registerKeyboardCallback (keyboard_callback, (void*)this);\n    image_view_.viewerScene_.registerKeyboardCallback (keyboard_callback, (void*)this);\n    image_view_.viewerDepth_.registerKeyboardCallback (keyboard_callback, (void*)this);\n\n    scene_cloud_view_.toggleCube(volume_size);\n    frame_counter_ = 0;\n    enable_texture_extraction_ = false;\n\n    //~ float fx, fy, cx, cy;\n    //~ boost::shared_ptr<openni_wrapper::OpenNIDevice> d = ((pcl::OpenNIGrabber)source).getDevice ();\n    //~ kinfu_->getDepthIntrinsics (fx, fy, cx, cy);\n\n    float height = 480.0f;\n    float width = 640.0f;\n    screenshot_manager_.setCameraIntrinsics (pcl::device::kinfuLS::FOCAL_LENGTH, height, width);\n    snapshot_rate_ = snapshotRate;\n    \n    Eigen::Matrix3f Rid = Eigen::Matrix3f::Identity ();   // * AngleAxisf( pcl::deg2rad(-30.f), Vector3f::UnitX());\n    Eigen::Vector3f T = Vector3f (0, 0, -volume_size(0)*1.5f);\n    delta_lost_pose_ = Eigen::Translation3f (T) * Eigen::AngleAxisf (Rid); \n    \n  }\n\n  ~KinFuLSApp()\n  {\n    if (evaluation_ptr_)\n      evaluation_ptr_->saveAllPoses(*kinfu_);\n  }\n\n  void\n  initCurrentFrameView ()\n  {\n    current_frame_cloud_view_ = boost::shared_ptr<CurrentFrameCloudView>(new CurrentFrameCloudView ());\n    current_frame_cloud_view_->cloud_viewer_.registerKeyboardCallback (keyboard_callback, (void*)this);\n    current_frame_cloud_view_->setViewerPose (kinfu_->getCameraPose ());\n  }\n\n  void\n  initRegistration ()\n  {        \n    registration_ = capture_.providesCallback<pcl::ONIGrabber::sig_cb_openni_image_depth_image> ();\n    cout << \"Registration mode: \" << (registration_ ? \"On\" : \"Off (not supported by source)\") << endl;\n  }\n\n  void \n  toggleColorIntegration()\n  {\n    if(registration_)\n    {\n      const int max_color_integration_weight = 2;\n      kinfu_->initColorIntegration(max_color_integration_weight);\n      integrate_colors_ = true;      \n    }    \n    cout << \"Color integration: \" << (integrate_colors_ ? \"On\" : \"Off ( requires registration mode )\") << endl;\n  }\n\n  void\n  toggleIndependentCamera()\n  {\n    independent_camera_ = !independent_camera_;\n    cout << \"Camera mode: \" << (independent_camera_ ?  \"Independent\" : \"Bound to Kinect pose\") << endl;\n  }\n\n  void\n  toggleEvaluationMode(const string& eval_folder, const string& match_file = string())\n  {\n    evaluation_ptr_ = Evaluation::Ptr( new Evaluation(eval_folder) );\n    if (!match_file.empty())\n      evaluation_ptr_->setMatchFile(match_file);\n\n    kinfu_->setDepthIntrinsics (evaluation_ptr_->fx, evaluation_ptr_->fy, evaluation_ptr_->cx, evaluation_ptr_->cy);\n    image_view_.raycaster_ptr_ = RayCaster::Ptr( new RayCaster(kinfu_->rows (), kinfu_->cols (), evaluation_ptr_->fx, evaluation_ptr_->fy, evaluation_ptr_->cx, evaluation_ptr_->cy) );\n  }\n\n  void execute(const PtrStepSz<const unsigned short>& depth, const PtrStepSz<const pcl::gpu::kinfuLS::PixelRGB>& rgb24, bool has_data)\n  {        \n    bool has_image = false;\n    frame_counter_++;\n\n    was_lost_ = kinfu_->icpIsLost();\n    \n    if (has_data)\n    {\n      depth_device_.upload (depth.data, depth.step, depth.rows, depth.cols);\n      if (integrate_colors_)\n        image_view_.colors_device_.upload (rgb24.data, rgb24.step, rgb24.rows, rgb24.cols);\n\n      {\n        SampledScopeTime fps(time_ms_);\n\n        //run kinfu algorithm\n        if (integrate_colors_)\n          has_image = (*kinfu_) (depth_device_, image_view_.colors_device_);\n        else\n          has_image = (*kinfu_) (depth_device_);\n      }\n\n      image_view_.showDepth (depth_);\n      //image_view_.showGeneratedDepth(kinfu_, kinfu_->getCameraPose());\n            \n    }\n\n    if (scan_ || (!was_lost_ && kinfu_->icpIsLost ()) ) //if scan mode is OR and ICP just lost itself => show current volume as point cloud\n    {\n      scan_ = false;\n      //scene_cloud_view_.show (*kinfu_, integrate_colors_); // this triggers out of memory errors, so I comment it out for now (Raph)\n\n      if (scan_volume_)\n      {                \n        cout << \"Downloading TSDF volume from device ... \" << flush;\n        // kinfu_->volume().downloadTsdfAndWeighs (tsdf_volume_.volumeWriteable (), tsdf_volume_.weightsWriteable ());\n        kinfu_->volume ().downloadTsdfAndWeightsLocal ();\n        // tsdf_volume_.setHeader (Eigen::Vector3i (pcl::device::kinfuLS::VOLUME_X, pcl::device::kinfuLS::VOLUME_Y, pcl::device::kinfuLS::VOLUME_Z), kinfu_->volume().getSize ());\n        kinfu_->volume ().setHeader (Eigen::Vector3i (pcl::device::kinfuLS::VOLUME_X, pcl::device::kinfuLS::VOLUME_Y, pcl::device::kinfuLS::VOLUME_Z), kinfu_->volume().getSize ());\n        // cout << \"done [\" << tsdf_volume_.size () << \" voxels]\" << endl << endl;\n        cout << \"done [\" << kinfu_->volume ().size () << \" voxels]\" << endl << endl;\n\n        cout << \"Converting volume to TSDF cloud ... \" << flush;\n        // tsdf_volume_.convertToTsdfCloud (tsdf_cloud_ptr_);\n        kinfu_->volume ().convertToTsdfCloud (tsdf_cloud_ptr_);\n        // cout << \"done [\" << tsdf_cloud_ptr_->size () << \" points]\" << endl << endl;        \n        cout << \"done [\" << kinfu_->volume ().size () << \" points]\" << endl << endl;\n      }\n      else\n        cout << \"[!] tsdf volume download is disabled\" << endl << endl;\n    }\n    \n\n    if (scan_mesh_)\n    {\n      scan_mesh_ = false;\n      scene_cloud_view_.showMesh(*kinfu_, integrate_colors_);\n    }\n\n    if (has_image)\n    {\n      Eigen::Affine3f viewer_pose = getViewerPose(scene_cloud_view_.cloud_viewer_);\n      image_view_.showScene (*kinfu_, rgb24, registration_, independent_camera_ ? &viewer_pose : 0);\n    }    \n\n    if (current_frame_cloud_view_)\n      current_frame_cloud_view_->show (*kinfu_);\n\n    // if ICP is lost, we show the world from a farther view point\n    if(kinfu_->icpIsLost())\n    {\n      setViewerPose (scene_cloud_view_.cloud_viewer_, kinfu_->getCameraPose () * delta_lost_pose_);\n    }\n    else\n    if (!independent_camera_)\n      setViewerPose (scene_cloud_view_.cloud_viewer_, kinfu_->getCameraPose ());\n\n    if (enable_texture_extraction_ && !kinfu_->icpIsLost ()) {\n      if ( (frame_counter_  % snapshot_rate_) == 0 )   // Should be defined as a parameter. Done.\n      {\n        screenshot_manager_.saveImage (kinfu_->getCameraPose (), rgb24);\n      }\n    }\n    \n    // display ICP state\n    scene_cloud_view_.displayICPState (*kinfu_, was_lost_);\n    \n  }\n\n  void source_cb1(const boost::shared_ptr<openni_wrapper::DepthImage>& depth_wrapper)  \n  {        \n    {\n      boost::mutex::scoped_try_lock lock(data_ready_mutex_);\n      if (exit_ || !lock)\n        return;\n\n      depth_.cols = depth_wrapper->getWidth();\n      depth_.rows = depth_wrapper->getHeight();\n      depth_.step = depth_.cols * depth_.elemSize();\n\n      source_depth_data_.resize(depth_.cols * depth_.rows);\n      depth_wrapper->fillDepthImageRaw(depth_.cols, depth_.rows, &source_depth_data_[0]);\n      depth_.data = &source_depth_data_[0];     \n    }\n    data_ready_cond_.notify_one();\n  }\n\n  void source_cb2(const boost::shared_ptr<openni_wrapper::Image>& image_wrapper, const boost::shared_ptr<openni_wrapper::DepthImage>& depth_wrapper, float)\n  {\n    {\n      boost::mutex::scoped_try_lock lock(data_ready_mutex_);\n\n      if (exit_ || !lock)\n      {\n        return;\n      }\n\n      depth_.cols = depth_wrapper->getWidth();\n      depth_.rows = depth_wrapper->getHeight();\n      depth_.step = depth_.cols * depth_.elemSize();\n\n      source_depth_data_.resize(depth_.cols * depth_.rows);\n      depth_wrapper->fillDepthImageRaw(depth_.cols, depth_.rows, &source_depth_data_[0]);\n      depth_.data = &source_depth_data_[0];      \n\n      rgb24_.cols = image_wrapper->getWidth();\n      rgb24_.rows = image_wrapper->getHeight();\n      rgb24_.step = rgb24_.cols * rgb24_.elemSize(); \n\n      source_image_data_.resize(rgb24_.cols * rgb24_.rows);\n      image_wrapper->fillRGB(rgb24_.cols, rgb24_.rows, (unsigned char*)&source_image_data_[0]);\n      rgb24_.data = &source_image_data_[0];    \n\n    }\n    data_ready_cond_.notify_one();\n  }\n\n  void source_cb3(const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr & DC3)\n  {\n    {                             \n      //std::cout << \"Giving colors1\\n\";\n      boost::mutex::scoped_try_lock lock(data_ready_mutex_);\n      //std::cout << lock << std::endl; //causes compile errors \n      if (exit_ || !lock)\n        return;\n      //std::cout << \"Giving colors2\\n\";\n      int width  = DC3->width;\n      int height = DC3->height;\n      depth_.cols = width;\n      depth_.rows = height;\n      depth_.step = depth_.cols * depth_.elemSize();\n      source_depth_data_.resize(depth_.cols * depth_.rows);   \n\n      rgb24_.cols = width;\n      rgb24_.rows = height;\n      rgb24_.step = rgb24_.cols * rgb24_.elemSize(); \n      source_image_data_.resize(rgb24_.cols * rgb24_.rows);\n\n      unsigned char *rgb    = (unsigned char *)  &source_image_data_[0];\n      unsigned short *depth = (unsigned short *) &source_depth_data_[0];  \n\n      //std::cout << \"Giving colors3\\n\";\n      for (int i=0; i<width*height; i++) {\n        PointXYZRGBA pt = DC3->at(i);\n        rgb[3*i +0] = pt.r;\n        rgb[3*i +1] = pt.g;\n        rgb[3*i +2] = pt.b;\n        depth[i]    = pt.z/0.001;\n      }\n      //std::cout << \"Giving colors4\\n\";\n      rgb24_.data = &source_image_data_[0];   \n      depth_.data = &source_depth_data_[0];      \n    }\t\n    data_ready_cond_.notify_one();\n  }\n\n  void\n  startMainLoop (bool triggered_capture)\n  {   \n    using namespace openni_wrapper;\n    typedef boost::shared_ptr<DepthImage> DepthImagePtr;\n    typedef boost::shared_ptr<Image>      ImagePtr;\n\n    boost::function<void (const ImagePtr&, const DepthImagePtr&, float constant)> func1 = boost::bind (&KinFuLSApp::source_cb2, this, _1, _2, _3);\n    boost::function<void (const DepthImagePtr&)> func2 = boost::bind (&KinFuLSApp::source_cb1, this, _1);\n    boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&) > func3 = boost::bind (&KinFuLSApp::source_cb3, this, _1);\n\n    bool need_colors = integrate_colors_ || registration_ || enable_texture_extraction_;\n\n    if ( pcd_source_ && !capture_.providesCallback<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)>() ) {\n      std::cout << \"grabber doesn't provide pcl::PointCloud<pcl::PointXYZRGBA> callback !\\n\";\n    }\n\n    boost::signals2::connection c = pcd_source_? capture_.registerCallback (func3) : need_colors ? capture_.registerCallback (func1) : capture_.registerCallback (func2);\n\n    {\n      boost::unique_lock<boost::mutex> lock(data_ready_mutex_);\n\n      if (!triggered_capture) \n        capture_.start ();\n\n      while (!exit_ && !scene_cloud_view_.cloud_viewer_.wasStopped () && !image_view_.viewerScene_.wasStopped () && !this->kinfu_->isFinished ())\n      { \n        if (triggered_capture)\n          capture_.start(); // Triggers new frame\n\n        bool has_data = data_ready_cond_.timed_wait (lock, boost::posix_time::millisec(100));\n\n        try { this->execute (depth_, rgb24_, has_data); }\n        catch (const std::bad_alloc& /*e*/) { cout << \"Bad alloc\" << endl; break; }\n        catch (const std::exception& /*e*/) { cout << \"Exception\" << endl; break; }\n\n        scene_cloud_view_.cloud_viewer_.spinOnce (3);\n        //~ cout << \"In main loop\" << endl;                  \n      } \n      exit_ = true;\n      boost::this_thread::sleep (boost::posix_time::millisec (100));\n\n      if (!triggered_capture)     \n        capture_.stop (); // Stop stream\n    }\n    c.disconnect();       \n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  void\n  writeCloud (int format) const\n  {      \n    const SceneCloudView& view = scene_cloud_view_;\n\n    if (!view.cloud_ptr_->points.empty ())\n    {\n      if(view.point_colors_ptr_->points.empty()) // no colors\n      {\n        if (view.valid_combined_)\n          writeCloudFile (format, view.combined_ptr_);\n        else\n          writeCloudFile (format, view.cloud_ptr_);\n      }\n      else\n      {        \n        if (view.valid_combined_)\n          writeCloudFile (format, merge<PointXYZRGBNormal>(*view.combined_ptr_, *view.point_colors_ptr_));\n        else\n          writeCloudFile (format, merge<PointXYZRGB>(*view.cloud_ptr_, *view.point_colors_ptr_));\n      }\n    }\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  void\n  writeMesh(int format) const\n  {\n    if (scene_cloud_view_.mesh_ptr_) \n      writePolygonMeshFile(format, *scene_cloud_view_.mesh_ptr_);\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  void\n  printHelp ()\n  {\n    cout << endl;\n    cout << \"KinFu app hotkeys\" << endl;\n    cout << \"=================\" << endl;\n    cout << \"    H    : print this help\" << endl;\n    cout << \"   Esc   : exit\" << endl;\n    cout << \"    T    : take cloud\" << endl;\n    cout << \"    A    : take mesh\" << endl;\n    cout << \"    M    : toggle cloud exctraction mode\" << endl;\n    cout << \"    N    : toggle normals exctraction\" << endl;\n    cout << \"    I    : toggle independent camera mode\" << endl;\n    cout << \"    B    : toggle volume bounds\" << endl;\n    cout << \"    *    : toggle scene view painting ( requires registration mode )\" << endl;\n    cout << \"    C    : clear clouds\" << endl;    \n    cout << \"   1,2,3 : save cloud to PCD(binary), PCD(ASCII), PLY(ASCII)\" << endl;\n    cout << \"    7,8  : save mesh to PLY, VTK\" << endl;\n    cout << \"   X, V  : TSDF volume utility\" << endl;\n    cout << \"   L, l  : On the next shift, KinFu will extract the whole current cube, extract the world and stop\" << endl;\n    cout << \"   S, s  : On the next shift, KinFu will extract the world and stop\" << endl;\n    cout << endl;\n  }  \n\n  bool exit_;\n  bool scan_;\n  bool scan_mesh_;\n  bool scan_volume_;\n\n  bool independent_camera_;\n  int frame_counter_;\n  bool enable_texture_extraction_;\n  pcl::kinfuLS::ScreenshotManager screenshot_manager_;\n  int snapshot_rate_;\n\n  bool registration_;\n  bool integrate_colors_;\n  bool pcd_source_;\n  float focal_length_;\n\n  pcl::Grabber& capture_;\n  KinfuTracker *kinfu_;\n\n  SceneCloudView scene_cloud_view_;\n  ImageView image_view_;\n  boost::shared_ptr<CurrentFrameCloudView> current_frame_cloud_view_;\n\n  KinfuTracker::DepthMap depth_device_;\n\n  pcl::PointCloud<pcl::PointXYZI>::Ptr tsdf_cloud_ptr_;\n\n  Evaluation::Ptr evaluation_ptr_;\n\n  boost::mutex data_ready_mutex_;\n  boost::condition_variable data_ready_cond_;\n\n  std::vector<pcl::gpu::kinfuLS::PixelRGB> source_image_data_;\n  std::vector<unsigned short> source_depth_data_;\n  PtrStepSz<const unsigned short> depth_;\n  PtrStepSz<const pcl::gpu::kinfuLS::PixelRGB> rgb24_;  \n  \n  Eigen::Affine3f delta_lost_pose_;\n  \n  bool was_lost_;\n\n  int time_ms_;\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  static void\n  keyboard_callback (const visualization::KeyboardEvent &e, void *cookie)\n  {\n    KinFuLSApp* app = reinterpret_cast<KinFuLSApp*> (cookie);\n\n    int key = e.getKeyCode ();\n\n    if (e.keyUp ())    \n      switch (key)\n      {\n      case 27: app->exit_ = true; break;\n      case (int)'t': case (int)'T': app->scan_ = true; break;\n      case (int)'a': case (int)'A': app->scan_mesh_ = true; break;\n      case (int)'h': case (int)'H': app->printHelp (); break;\n      case (int)'m': case (int)'M': app->scene_cloud_view_.toggleExtractionMode (); break;\n      case (int)'n': case (int)'N': app->scene_cloud_view_.toggleNormals (); break;      \n      case (int)'c': case (int)'C': app->scene_cloud_view_.clearClouds (true); break;\n      case (int)'i': case (int)'I': app->toggleIndependentCamera (); break;\n      case (int)'b': case (int)'B': app->scene_cloud_view_.toggleCube(app->kinfu_->volume().getSize()); break;\n      case (int)'l': case (int)'L': app->kinfu_->performLastScan (); break;\n      case (int)'s': case (int)'S': app->kinfu_->extractAndSaveWorld (); break;\n      case (int)'r': case (int)'R': app->kinfu_->reset(); app->scene_cloud_view_.clearClouds(); break;\n      case (int)'7': case (int)'8': app->writeMesh (key - (int)'0'); break;  \n      case (int)'1': case (int)'2': case (int)'3': app->writeCloud (key - (int)'0'); break;      \n      case '*': app->image_view_.toggleImagePaint (); break;\n      \n      case (int)'p': case (int)'P': app->kinfu_->setDisableICP(); break;\n\n      case (int)'x': case (int)'X':\n        app->scan_volume_ = !app->scan_volume_;\n        cout << endl << \"Volume scan: \" << (app->scan_volume_ ? \"enabled\" : \"disabled\") << endl << endl;\n        break;\n      case (int)'v': case (int)'V':\n        cout << \"Saving TSDF volume to tsdf_volume.dat ... \" << flush;\n        // app->tsdf_volume_.save (\"tsdf_volume.dat\", true);\n        app->kinfu_->volume ().save (\"tsdf_volume.dat\", true);\n        // cout << \"done [\" << app->tsdf_volume_.size () << \" voxels]\" << endl;\n        cout << \"done [\" << app->kinfu_->volume ().size () << \" voxels]\" << endl;\n        cout << \"Saving TSDF volume cloud to tsdf_cloud.pcd ... \" << flush;\n        pcl::io::savePCDFile<pcl::PointXYZI> (\"tsdf_cloud.pcd\", *app->tsdf_cloud_ptr_, true);\n        cout << \"done [\" << app->tsdf_cloud_ptr_->size () << \" points]\" << endl;\n        break;\n      default:\n        break;\n      }    \n  }\n\n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate<typename CloudPtr> void\nwriteCloudFile (int format, const CloudPtr& cloud_prt)\n{\n  if (format == KinFuLSApp::PCD_BIN)\n  {\n    cout << \"Saving point cloud to 'cloud_bin.pcd' (binary)... \" << flush;\n    pcl::io::savePCDFile (\"cloud_bin.pcd\", *cloud_prt, true);\n  }\n  else if (format == KinFuLSApp::PCD_ASCII)\n  {\n    cout << \"Saving point cloud to 'cloud.pcd' (ASCII)... \" << flush;\n    pcl::io::savePCDFile (\"cloud.pcd\", *cloud_prt, false);\n  }\n  else   /* if (format == KinFuLSApp::PLY) */\n  {\n    cout << \"Saving point cloud to 'cloud.ply' (ASCII)... \" << flush;\n    pcl::io::savePLYFileASCII (\"cloud.ply\", *cloud_prt);\n\n  }\n  cout << \"Done\" << endl;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid\nwritePolygonMeshFile (int format, const pcl::PolygonMesh& mesh)\n{\n  if (format == KinFuLSApp::MESH_PLY)\n  {\n    cout << \"Saving mesh to to 'mesh.ply'... \" << flush;\n    pcl::io::savePLYFile(\"mesh.ply\", mesh);\t\t\n  }\n  else /* if (format == KinFuLSApp::MESH_VTK) */\n  {\n    cout << \"Saving mesh to to 'mesh.vtk'... \" << flush;\n    pcl::io::saveVTKFile(\"mesh.vtk\", mesh);    \n  }  \n  cout << \"Done\" << endl;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nint\nprint_cli_help ()\n{\n  cout << \"\\nKinFu parameters:\" << endl;\n  cout << \"    --help, -h                          : print this message\" << endl;  \n  cout << \"    --registration, -r                  : try to enable registration (source needs to support this)\" << endl;\n  cout << \"    --current-cloud, -cc                : show current frame cloud\" << endl;\n  cout << \"    --save-views, -sv                   : accumulate scene view and save in the end ( Requires OpenCV. Will cause 'bad_alloc' after some time )\" << endl;  \n  cout << \"    --registration, -r                  : enable registration mode\" << endl; \n  cout << \"    --integrate-colors, -ic             : enable color integration mode (allows to get cloud with colors)\" << endl;\n  cout << \"    --extract-textures, -et             : extract RGB PNG images to KinFuSnapshots folder.\" << endl;\n  cout << \"    --volume_size <in_meters>, -vs      : define integration volume size\" << endl;\n  cout << \"    --shifting_distance <in_meters>, -sd : define shifting threshold (distance target-point / cube center)\" << endl;\n  cout << \"    --snapshot_rate <X_frames>, -sr     : Extract RGB textures every <X_frames>. Default: 45  \" << endl;\n  cout << endl << \"\";\n  cout << \"Valid depth data sources:\" << endl; \n  cout << \"    -dev <device> (default), -oni <oni_file>, -pcd <pcd_file or directory>\" << endl;\n  cout << endl << \"\";\n  cout << \" For RGBD benchmark (Requires OpenCV):\" << endl; \n  cout << \"    -eval <eval_folder> [-match_file <associations_file_in_the_folder>]\" << endl << endl;\n\n  return 0;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nint\nmain (int argc, char* argv[])\n{  \n  if (pc::find_switch (argc, argv, \"--help\") || pc::find_switch (argc, argv, \"-h\"))\n    return print_cli_help ();\n\n  int device = 0;\n  pc::parse_argument (argc, argv, \"-gpu\", device);\n  pcl::gpu::setDevice (device);\n  pcl::gpu::printShortCudaDeviceInfo (device);\n\n  //  if (checkIfPreFermiGPU(device))\n  //    return cout << endl << \"Kinfu is supported only for Fermi and Kepler arhitectures. It is not even compiled for pre-Fermi by default. Exiting...\" << endl, 1;\n\n  boost::shared_ptr<pcl::Grabber> capture;\n  bool triggered_capture = false;\n  bool pcd_input = false;\n\n  std::string eval_folder, match_file, openni_device, oni_file, pcd_dir;\n  try\n  {    \n    if (pc::parse_argument (argc, argv, \"-dev\", openni_device) > 0)\n    {\n      capture.reset (new pcl::OpenNIGrabber (openni_device));\n    }\n    else if (pc::parse_argument (argc, argv, \"-oni\", oni_file) > 0)\n    {\n      triggered_capture = true;\n      bool repeat = false; // Only run ONI file once\n      capture.reset (new pcl::ONIGrabber (oni_file, repeat, !triggered_capture));\n    }\n    else if (pc::parse_argument (argc, argv, \"-pcd\", pcd_dir) > 0)\n    {\n      float fps_pcd = 15.0f;\n      pc::parse_argument (argc, argv, \"-pcd_fps\", fps_pcd);\n\n      vector<string> pcd_files = getPcdFilesInDir(pcd_dir);    \n      // Sort the read files by name\n      sort (pcd_files.begin (), pcd_files.end ());\n      capture.reset (new pcl::PCDGrabber<pcl::PointXYZRGBA> (pcd_files, fps_pcd, false));\n      triggered_capture = true;\n      pcd_input = true;\n    }\n    else if (pc::parse_argument (argc, argv, \"-eval\", eval_folder) > 0)\n    {\n      //init data source latter\n      pc::parse_argument (argc, argv, \"-match_file\", match_file);\n    }\n    else\n    {\n      capture.reset( new pcl::OpenNIGrabber() );\n\n      //capture.reset( new pcl::ONIGrabber(\"d:/onis/20111013-224932.oni\", true, true) );\n      //capture.reset( new pcl::ONIGrabber(\"d:/onis/reg20111229-180846.oni, true, true) );    \n      //capture.reset( new pcl::ONIGrabber(\"/media/Main/onis/20111013-224932.oni\", true, true) );\n      //capture.reset( new pcl::ONIGrabber(\"d:/onis/20111013-224551.oni\", true, true) );\n      //capture.reset( new pcl::ONIGrabber(\"d:/onis/20111013-224719.oni\", true, true) );    \n    }\n  }\n  catch (const pcl::PCLException& /*e*/) { return cout << \"Can't open depth source\" << endl, -1; }\n\n  float volume_size = pcl::device::kinfuLS::VOLUME_SIZE;\n  pc::parse_argument (argc, argv, \"--volume_size\", volume_size);\n  pc::parse_argument (argc, argv, \"-vs\", volume_size);\n\n  float shift_distance = pcl::device::kinfuLS::DISTANCE_THRESHOLD;\n  pc::parse_argument (argc, argv, \"--shifting_distance\", shift_distance);\n  pc::parse_argument (argc, argv, \"-sd\", shift_distance);\n\n  int snapshot_rate = pcl::device::kinfuLS::SNAPSHOT_RATE; // defined in device.h\n  pc::parse_argument (argc, argv, \"--snapshot_rate\", snapshot_rate);\n  pc::parse_argument (argc, argv, \"-sr\", snapshot_rate);\n\n  KinFuLSApp app (*capture, volume_size, shift_distance, snapshot_rate);\n\n  if (pc::parse_argument (argc, argv, \"-eval\", eval_folder) > 0)\n    app.toggleEvaluationMode(eval_folder, match_file);\n\n  if (pc::find_switch (argc, argv, \"--current-cloud\") || pc::find_switch (argc, argv, \"-cc\"))\n    app.initCurrentFrameView ();\n\n  if (pc::find_switch (argc, argv, \"--save-views\") || pc::find_switch (argc, argv, \"-sv\"))\n    app.image_view_.accumulate_views_ = true;  //will cause bad alloc after some time  \n\n  if (pc::find_switch (argc, argv, \"--registration\") || pc::find_switch (argc, argv, \"-r\"))  {\n    if (pcd_input) {\n      app.pcd_source_   = true;\n      app.registration_ = true; // since pcd provides registered rgbd\n    } else {\n      app.initRegistration();\n    }\n  }\n\n  if (pc::find_switch (argc, argv, \"--integrate-colors\") || pc::find_switch (argc, argv, \"-ic\"))      \n    app.toggleColorIntegration();\n\n  if (pc::find_switch (argc, argv, \"--extract-textures\") || pc::find_switch (argc, argv, \"-et\"))      \n    app.enable_texture_extraction_ = true;\n\n  // executing\n  if (triggered_capture) \n    std::cout << \"Capture mode: triggered\\n\";\n  else\t\t\t\t     \n    std::cout << \"Capture mode: stream\\n\";\n\n  // set verbosity level\n  pcl::console::setVerbosityLevel(pcl::console::L_VERBOSE);\n  try { app.startMainLoop (triggered_capture); }  \n  catch (const pcl::PCLException& /*e*/) { cout << \"PCLException\" << endl; }\n  catch (const std::bad_alloc& /*e*/) { cout << \"Bad alloc\" << endl; }\n  catch (const std::exception& /*e*/) { cout << \"Exception\" << endl; }\n\n  //~ #ifdef HAVE_OPENCV\n  //~ for (size_t t = 0; t < app.image_view_.views_.size (); ++t)\n  //~ {\n  //~ if (t == 0)\n  //~ {\n  //~ cout << \"Saving depth map of first view.\" << endl;\n  //~ cv::imwrite (\"./depthmap_1stview.png\", app.image_view_.views_[0]);\n  //~ cout << \"Saving sequence of (\" << app.image_view_.views_.size () << \") views.\" << endl;\n  //~ }\n  //~ char buf[4096];\n  //~ sprintf (buf, \"./%06d.png\", (int)t);\n  //~ cv::imwrite (buf, app.image_view_.views_[t]);\n  //~ printf (\"writing: %s\\n\", buf);\n  //~ }\n  //~ #endif\n  std::cout << \"pcl_kinfu_largeScale exiting...\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "d440dab848d3a8434e414f651e3b4af97638ab0f", "size": 50687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dockerfiles/gaas_tutorial_2/GAAS/software/SLAM/ygz_slam_ros/Thirdparty/PCL/gpu/kinfu_large_scale/tools/kinfuLS_app.cpp", "max_stars_repo_name": "hddxds/scripts_from_gi", "max_stars_repo_head_hexsha": "afb8977c001b860335f9062464e600d9115ea56e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-10T14:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-29T03:41:58.000Z", "max_issues_repo_path": "software/SLAM/ygz_slam_ros/Thirdparty/PCL/gpu/kinfu_large_scale/tools/kinfuLS_app.cpp", "max_issues_repo_name": "glider54321/GAAS", "max_issues_repo_head_hexsha": "5c3b8c684e72fdf7f62c5731a260021e741069e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "software/SLAM/ygz_slam_ros/Thirdparty/PCL/gpu/kinfu_large_scale/tools/kinfuLS_app.cpp", "max_forks_repo_name": "glider54321/GAAS", "max_forks_repo_head_hexsha": "5c3b8c684e72fdf7f62c5731a260021e741069e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-20T06:54:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T06:54:41.000Z", "avg_line_length": 36.7563451777, "max_line_length": 186, "alphanum_fraction": 0.6180677491, "num_tokens": 13637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.02843603036892814, "lm_q1q2_score": 0.009914083656335143}}
{"text": "/**\n * @file visitor.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 ARLIB_VISITOR_HPP\n#define ARLIB_VISITOR_HPP\n\n#include <boost/graph/graph_concepts.hpp>\n\n#include <limits>\n#include <unordered_set>\n\n/**\n * An Alternative-Routing library for Boost.Graph\n */\nnamespace arlib {\n//===----------------------------------------------------------------------===//\n//                    Bidirectional Dijkstra visitor\n//===----------------------------------------------------------------------===//\n/**\n * CRTP interface class for bidirectional_dijkstra() visitor.\n *\n * A BiDijkstraVisitor is passed to bidirectional_dijkstra() in order to\n * customize the algorithm behavior with respect to\n *  - terminating_condition(): when a vertex is found both from source and\n * target searches, bidirectional_dijkstra() asks the visitor whether to end the\n *    search or keep going.\n *  - expand_vertex(): given a vertex v, its distance from one root and the\n *    distance-lower-bound from the other and the current minimum st-distance,\n *    the visitor should return whether to expand the search in the direction of\n *    v or not.\n *\n * @tparam Derived The derived class implementing BiDijkstraVisitor interface\n */\ntemplate <typename Derived> class BiDijkstraVisitor {\npublic:\n  /**\n   * Whether or not bidirectional_dijkstra() should stop. It is invoked when a\n   * vertex v is found both from source search and target search.\n   *\n   * @tparam Length The weight value type.\n   * @param min_distance The minimum distance to any node in current direction\n   *        fringe.\n   * @param other_min_distance The minimum distance to any node in the other\n   *        direction fringe.\n   * @param st_distance Current minimum source-target distance.\n   * @return true if bidirectional_dijkstra() should stop.\n   * @return false otherwise.\n   */\n  template <typename Length>\n  bool terminating_condition(Length min_distance, Length other_min_distance,\n                             Length st_distance) {\n    return static_cast<Derived *>(this)->terminating_condition(\n        min_distance, other_min_distance, st_distance);\n  }\n  /**\n   * Whether or not to bidirectional_dijkstra() should expand the search through\n   * the input Vertex v.\n   *\n   * @tparam Vertex The vertex_descriptor.\n   * @tparam Length The weight value type.\n   * @param v The candidate Vertex to expand.\n   * @param v_distance The Vertex distance according to current-direction\n   *        search.\n   * @param lower_bound_v The Vertex distance-heuristic according to\n   *        opposite-direction search.\n   * @param st_distance Current minimum source-target distance.\n   * @return true if bidirectional_dijkstra() should expand vertex @p v\n   * @return false otherwise.\n   */\n  template <typename Vertex, typename Length>\n  bool expand_vertex(Vertex v, Length v_distance, Length lower_bound_v,\n                     Length st_distance) {\n    return static_cast<Derived *>(this)->expand_vertex(\n        v, v_distance, lower_bound_v, st_distance);\n  }\n};\n\n/**\n * BiDijkstraVisitor implementing vanilla Bidirectional Dijkstra behavior as\n * described in Nicholson's paper (1966):\n * https://academic.oup.com/comjnl/article/9/3/275/406281\n */\nclass IdentityBiDijkstraVisitor\n    : public BiDijkstraVisitor<IdentityBiDijkstraVisitor> {\npublic:\n  /**\n   * Vanilla Bidirectional Dijkstra stopping condition.\n   *\n   * @tparam Length The weight value type.\n   * @param min_distance The minimum distance to any node in current direction\n   *        fringe.\n   * @param other_min_distance The minimum distance to any node in the other\n   *        direction fringe.\n   * @param st_distance Current minimum source-target distance.\n   * @return true if @p min_distance + @p other_min_distance > @p st_distance.\n   * @return false otherwise.\n   */\n  template <typename Length>\n  bool terminating_condition(Length min_distance, Length other_min_distance,\n                             Length st_distance) {\n    return (min_distance + other_min_distance) > st_distance;\n  }\n  /**\n   * Always-expand policy.\n   *\n   * @tparam Vertex The vertex_descriptor\n   * @tparam Length The weight value type.\n   * @return true always.\n   */\n  template <typename Vertex, typename Length>\n  bool expand_vertex(Vertex, Length, Length, Length) {\n    return true;\n  }\n};\n\n/**\n * BiDijkstraVisitor implementing Uninformed Bidirectional Pruner as described\n * in\n *\n * A. Paraskevopoulos, C. Zaroliagis, Improved alternative route\n * planning,198in: OASIcs-OpenAccess Series in Informatics, Vol. 33, Schloss\n * Dagstuhl-199Leibniz-Zentrum fuer Informatik, 2013\n * http://drops.dagstuhl.de/opus/volltexte/2013/4248/\n *\n * The purpose of this visitor is to explore the whole graph an keep track of\n * all those vertices that should be pruned.\n * Let v be a Vertex, let tau be the pruning factor, v_distance be the distance\n * of v from the root of current search, other_min_distance be\n * distance-heuristic of v from the opposite search-root and st_distance be the\n * current minimum distance between source and target nodes. Then v should be\n * pruned if:\n * v_distance + lower_bound_v > tau * st_distance\n *\n * @see uninformed_bidirectional_pruner()\n *\n * @tparam Vertex The vertex_descriptor\n */\ntemplate <typename Vertex>\nclass UninformedBiPrunerVisitor\n    : public BiDijkstraVisitor<UninformedBiPrunerVisitor<Vertex>> {\npublic:\n  /**\n   * A set of Vertex of the graph\n   */\n  using VertexSet = std::unordered_set<Vertex, boost::hash<Vertex>>;\n  /**\n   * The VertexSet const-iterator type\n   */\n  using const_iterator = typename VertexSet::const_iterator;\n  /**\n   * Construct a new UninformedBiPrunerVisitor object with a pruning factor of\n   * @p tau.\n   *\n   * @param tau The pruning factor.\n   */\n  explicit UninformedBiPrunerVisitor(double tau)\n      : tau{tau}, is_pruning_phase{false} {}\n  /**\n   * Always keep searching.\n   *\n   * @tparam Length The weight value type.\n   * @param min_distance The minimum distance to any node in current direction\n   *        fringe.\n   * @param other_min_distance The minimum distance to any node in the other\n   *        direction fringe.\n   * @param st_distance Current minimum source-target distance.\n   * @return false always.\n   */\n  template <typename Length>\n  bool terminating_condition(Length min_distance, Length other_min_distance,\n                             Length st_distance) {\n    if (min_distance + other_min_distance > st_distance) {\n      is_pruning_phase = true;\n    }\n    return false;\n  }\n  /**\n   * If the shortest-path from source to target hasn't been found yet, then\n   * always expand. Otherwise, expand only if\n   * @p v_distance + @p lower_bound_v <= tau * @p st_distance\n   *\n   * @tparam Length The weight value type.\n   * @param v The candidate Vertex to expand.\n   * @param v_distance The Vertex distance according to current-direction\n   *        search.\n   * @param lower_bound_v The Vertex distance-heuristic according to\n   *        opposite-direction search.\n   * @param st_distance Current minimum source-target distance.\n   * @return true If the shortest-path from source to target hasn't been found\n   * yet or if @p v_distance + @p lower_bound_v <= tau * @p st_distance\n   * @return false otherwise.\n   */\n  template <typename Length>\n  bool expand_vertex(Vertex v, Length v_distance, Length lower_bound_v,\n                     Length st_distance) {\n    if (is_pruning_phase) {\n      if (v_distance + lower_bound_v <= tau * st_distance) {\n        return true;\n      } else {\n        pruned_vertices.insert(v);\n        return false;\n      }\n    } else\n      return true;\n  }\n  /**\n   * @return a pair of const-iterators to begin and end of the pruned VertexSet.\n   */\n  std::pair<const_iterator, const_iterator> get_pruned_vertices() const {\n    return {pruned_vertices.cbegin(), pruned_vertices.cend()};\n  }\n  /**\n   * @param v The vertex to test\n   * @return true if @p v should be pruned.\n   * @return false otherwise.\n   */\n  bool is_pruned(const Vertex &v) const {\n    return (pruned_vertices.find(v) != std::end(pruned_vertices));\n  }\n\nprivate:\n  double tau;\n  bool is_pruning_phase;\n  std::unordered_set<Vertex, boost::hash<Vertex>> pruned_vertices;\n};\n} // namespace arlib\n#endif", "meta": {"hexsha": "323f8ec119e08745b68cc01bd96197ceaf1462bc", "size": 9411, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arlib/routing_kernels/visitor.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/routing_kernels/visitor.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/routing_kernels/visitor.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": 37.0511811024, "max_line_length": 80, "alphanum_fraction": 0.6983317395, "num_tokens": 2149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807713748839185, "lm_q2_score": 0.029312233295254998, "lm_q1q2_score": 0.009909795925851742}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2013, Ioan A. Sucan\n *  Copyright (c) 2008-2013, 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 <moveit/robot_model/floating_joint_model.h>\n#include <geometric_shapes/check_isometry.h>\n#include <boost/math/constants/constants.hpp>\n#include <ros/console.h>\n#include <limits>\n#include <cmath>\n\nnamespace moveit\n{\nnamespace core\n{\nnamespace\n{\nconstexpr size_t STATE_SPACE_DIMENSION = 7;\n\n}  // namespace\n\nFloatingJointModel::FloatingJointModel(const std::string& name) : JointModel(name), angular_distance_weight_(1.0)\n{\n  type_ = FLOATING;\n  local_variable_names_.push_back(\"trans_x\");\n  local_variable_names_.push_back(\"trans_y\");\n  local_variable_names_.push_back(\"trans_z\");\n  local_variable_names_.push_back(\"rot_x\");\n  local_variable_names_.push_back(\"rot_y\");\n  local_variable_names_.push_back(\"rot_z\");\n  local_variable_names_.push_back(\"rot_w\");\n  for (size_t i = 0; i < STATE_SPACE_DIMENSION; ++i)\n  {\n    variable_names_.push_back(name_ + \"/\" + local_variable_names_[i]);\n    variable_index_map_[variable_names_.back()] = i;\n  }\n\n  variable_bounds_.resize(7);\n\n  variable_bounds_[0].position_bounded_ = true;\n  variable_bounds_[1].position_bounded_ = true;\n  variable_bounds_[2].position_bounded_ = true;\n  variable_bounds_[3].position_bounded_ = true;\n  variable_bounds_[4].position_bounded_ = true;\n  variable_bounds_[5].position_bounded_ = true;\n  variable_bounds_[6].position_bounded_ = true;\n\n  variable_bounds_[0].min_position_ = -std::numeric_limits<double>::infinity();\n  variable_bounds_[0].max_position_ = std::numeric_limits<double>::infinity();\n  variable_bounds_[1].min_position_ = -std::numeric_limits<double>::infinity();\n  variable_bounds_[1].max_position_ = std::numeric_limits<double>::infinity();\n  variable_bounds_[2].min_position_ = -std::numeric_limits<double>::infinity();\n  variable_bounds_[2].max_position_ = std::numeric_limits<double>::infinity();\n  variable_bounds_[3].min_position_ = -1.0;\n  variable_bounds_[3].max_position_ = 1.0;\n  variable_bounds_[4].min_position_ = -1.0;\n  variable_bounds_[4].max_position_ = 1.0;\n  variable_bounds_[5].min_position_ = -1.0;\n  variable_bounds_[5].max_position_ = 1.0;\n  variable_bounds_[6].min_position_ = -1.0;\n  variable_bounds_[6].max_position_ = 1.0;\n\n  computeVariableBoundsMsg();\n}\n\ndouble FloatingJointModel::getMaximumExtent(const Bounds& other_bounds) const\n{\n  double dx = other_bounds[0].max_position_ - other_bounds[0].min_position_;\n  double dy = other_bounds[1].max_position_ - other_bounds[1].min_position_;\n  double dz = other_bounds[2].max_position_ - other_bounds[2].min_position_;\n  return sqrt(dx * dx + dy * dy + dz * dz) + boost::math::constants::pi<double>() * 0.5 * angular_distance_weight_;\n}\n\ndouble FloatingJointModel::distance(const double* values1, const double* values2) const\n{\n  return distanceTranslation(values1, values2) + angular_distance_weight_ * distanceRotation(values1, values2);\n}\n\ndouble FloatingJointModel::distanceTranslation(const double* values1, const double* values2) const\n{\n  double dx = values1[0] - values2[0];\n  double dy = values1[1] - values2[1];\n  double dz = values1[2] - values2[2];\n  return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\ndouble FloatingJointModel::distanceRotation(const double* values1, const double* values2) const\n{\n  double dq =\n      fabs(values1[3] * values2[3] + values1[4] * values2[4] + values1[5] * values2[5] + values1[6] * values2[6]);\n  if (dq + std::numeric_limits<double>::epsilon() >= 1.0)\n    return 0.0;\n  else\n    return acos(dq);\n}\n\nvoid FloatingJointModel::interpolate(const double* from, const double* to, const double t, double* state) const\n{\n  // interpolate position\n  state[0] = from[0] + (to[0] - from[0]) * t;\n  state[1] = from[1] + (to[1] - from[1]) * t;\n  state[2] = from[2] + (to[2] - from[2]) * t;\n\n  double dq = fabs(from[3] * to[3] + from[4] * to[4] + from[5] * to[5] + from[6] * to[6]);\n  double theta = (dq + std::numeric_limits<double>::epsilon() >= 1.0) ? 0.0 : acos(dq);\n  if (theta > std::numeric_limits<double>::epsilon())\n  {\n    double d = 1.0 / sin(theta);\n    double s0 = sin((1.0 - t) * theta);\n    double s1 = sin(t * theta);\n    if (dq < 0)  // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp\n      s1 = -s1;\n    state[3] = (from[3] * s0 + to[3] * s1) * d;\n    state[4] = (from[4] * s0 + to[4] * s1) * d;\n    state[5] = (from[5] * s0 + to[5] * s1) * d;\n    state[6] = (from[6] * s0 + to[6] * s1) * d;\n  }\n  else\n  {\n    state[3] = from[3];\n    state[4] = from[4];\n    state[5] = from[5];\n    state[6] = from[6];\n  }\n}\n\nbool FloatingJointModel::satisfiesPositionBounds(const double* values, const Bounds& bounds, double margin) const\n{\n  if (values[0] < bounds[0].min_position_ - margin || values[0] > bounds[0].max_position_ + margin)\n    return false;\n  if (values[1] < bounds[1].min_position_ - margin || values[1] > bounds[1].max_position_ + margin)\n    return false;\n  if (values[2] < bounds[2].min_position_ - margin || values[2] > bounds[2].max_position_ + margin)\n    return false;\n  double norm_sqr = values[3] * values[3] + values[4] * values[4] + values[5] * values[5] + values[6] * values[6];\n  return fabs(norm_sqr - 1.0) <= std::numeric_limits<float>::epsilon() * 10.0;\n}\n\nbool FloatingJointModel::normalizeRotation(double* values) const\n{\n  // normalize the quaternion if we need to\n  double norm_sqr = values[3] * values[3] + values[4] * values[4] + values[5] * values[5] + values[6] * values[6];\n  if (fabs(norm_sqr - 1.0) > std::numeric_limits<double>::epsilon() * 100.0)\n  {\n    double norm = sqrt(norm_sqr);\n    if (norm < std::numeric_limits<double>::epsilon() * 100.0)\n    {\n      ROS_WARN_NAMED(\"robot_model\", \"Quaternion is zero in RobotState representation. Setting to identity\");\n      values[3] = 0.0;\n      values[4] = 0.0;\n      values[5] = 0.0;\n      values[6] = 1.0;\n    }\n    else\n    {\n      values[3] /= norm;\n      values[4] /= norm;\n      values[5] /= norm;\n      values[6] /= norm;\n    }\n    return true;\n  }\n  else\n    return false;\n}\n\nunsigned int FloatingJointModel::getStateSpaceDimension() const\n{\n  return STATE_SPACE_DIMENSION;\n}\n\nbool FloatingJointModel::enforcePositionBounds(double* values, const Bounds& bounds) const\n{\n  bool result = normalizeRotation(values);\n  for (unsigned int i = 0; i < 3; ++i)\n  {\n    if (values[i] < bounds[i].min_position_)\n    {\n      values[i] = bounds[i].min_position_;\n      result = true;\n    }\n    else if (values[i] > bounds[i].max_position_)\n    {\n      values[i] = bounds[i].max_position_;\n      result = true;\n    }\n  }\n  return result;\n}\n\nvoid FloatingJointModel::computeTransform(const double* joint_values, Eigen::Isometry3d& transf) const\n{\n  transf = Eigen::Isometry3d(\n      Eigen::Translation3d(joint_values[0], joint_values[1], joint_values[2]) *\n      Eigen::Quaterniond(joint_values[6], joint_values[3], joint_values[4], joint_values[5]).normalized());\n}\n\nvoid FloatingJointModel::computeVariablePositions(const Eigen::Isometry3d& transf, double* joint_values) const\n{\n  joint_values[0] = transf.translation().x();\n  joint_values[1] = transf.translation().y();\n  joint_values[2] = transf.translation().z();\n  ASSERT_ISOMETRY(transf)  // unsanitized input, could contain non-isometry\n  Eigen::Quaterniond q(transf.linear());\n  joint_values[3] = q.x();\n  joint_values[4] = q.y();\n  joint_values[5] = q.z();\n  joint_values[6] = q.w();\n}\n\nvoid FloatingJointModel::getVariableDefaultPositions(double* values, const Bounds& bounds) const\n{\n  for (unsigned int i = 0; i < 3; ++i)\n  {\n    // if zero is a valid value\n    if (bounds[i].min_position_ <= 0.0 && bounds[i].max_position_ >= 0.0)\n      values[i] = 0.0;\n    else\n      values[i] = (bounds[i].min_position_ + bounds[i].max_position_) / 2.0;\n  }\n\n  values[3] = 0.0;\n  values[4] = 0.0;\n  values[5] = 0.0;\n  values[6] = 1.0;\n}\n\nvoid FloatingJointModel::getVariableRandomPositions(random_numbers::RandomNumberGenerator& rng, double* values,\n                                                    const Bounds& bounds) const\n{\n  if (bounds[0].max_position_ >= std::numeric_limits<double>::infinity() ||\n      bounds[0].min_position_ <= -std::numeric_limits<double>::infinity())\n    values[0] = 0.0;\n  else\n    values[0] = rng.uniformReal(bounds[0].min_position_, bounds[0].max_position_);\n  if (bounds[1].max_position_ >= std::numeric_limits<double>::infinity() ||\n      bounds[1].min_position_ <= -std::numeric_limits<double>::infinity())\n    values[1] = 0.0;\n  else\n    values[1] = rng.uniformReal(bounds[1].min_position_, bounds[1].max_position_);\n  if (bounds[2].max_position_ >= std::numeric_limits<double>::infinity() ||\n      bounds[2].min_position_ <= -std::numeric_limits<double>::infinity())\n    values[2] = 0.0;\n  else\n    values[2] = rng.uniformReal(bounds[2].min_position_, bounds[2].max_position_);\n\n  double q[4];\n  rng.quaternion(q);\n  values[3] = q[0];\n  values[4] = q[1];\n  values[5] = q[2];\n  values[6] = q[3];\n}\n\nvoid FloatingJointModel::getVariableRandomPositionsNearBy(random_numbers::RandomNumberGenerator& rng, double* values,\n                                                          const Bounds& bounds, const double* seed,\n                                                          const double distance) const\n{\n  if (bounds[0].max_position_ >= std::numeric_limits<double>::infinity() ||\n      bounds[0].min_position_ <= -std::numeric_limits<double>::infinity())\n    values[0] = 0.0;\n  else\n    values[0] = rng.uniformReal(std::max(bounds[0].min_position_, seed[0] - distance),\n                                std::min(bounds[0].max_position_, seed[0] + distance));\n  if (bounds[1].max_position_ >= std::numeric_limits<double>::infinity() ||\n      bounds[1].min_position_ <= -std::numeric_limits<double>::infinity())\n    values[1] = 0.0;\n  else\n    values[1] = rng.uniformReal(std::max(bounds[1].min_position_, seed[1] - distance),\n                                std::min(bounds[1].max_position_, seed[1] + distance));\n  if (bounds[2].max_position_ >= std::numeric_limits<double>::infinity() ||\n      bounds[2].min_position_ <= -std::numeric_limits<double>::infinity())\n    values[2] = 0.0;\n  else\n    values[2] = rng.uniformReal(std::max(bounds[2].min_position_, seed[2] - distance),\n                                std::min(bounds[2].max_position_, seed[2] + distance));\n\n  double da = angular_distance_weight_ * distance;\n  if (da >= .25 * boost::math::constants::pi<double>())\n  {\n    double q[4];\n    rng.quaternion(q);\n    values[3] = q[0];\n    values[4] = q[1];\n    values[5] = q[2];\n    values[6] = q[3];\n  }\n  else\n  {\n    // taken from OMPL\n    // sample angle & axis\n    double ax = rng.gaussian01();\n    double ay = rng.gaussian01();\n    double az = rng.gaussian01();\n    double angle = 2.0 * pow(rng.uniform01(), 1.0 / 3.0) * da;\n    // convert to quaternion\n    double q[4];\n    double norm = sqrt(ax * ax + ay * ay + az * az);\n    if (norm < 1e-6)\n    {\n      q[0] = q[1] = q[2] = 0.0;\n      q[3] = 1.0;\n    }\n    else\n    {\n      double s = sin(angle / 2.0);\n      q[0] = s * ax / norm;\n      q[1] = s * ay / norm;\n      q[2] = s * az / norm;\n      q[3] = cos(angle / 2.0);\n    }\n    // multiply quaternions: near * q\n    values[3] = seed[6] * q[0] + seed[3] * q[3] + seed[4] * q[2] - seed[5] * q[1];\n    values[4] = seed[6] * q[1] + seed[4] * q[3] + seed[5] * q[0] - seed[3] * q[2];\n    values[5] = seed[6] * q[2] + seed[5] * q[3] + seed[3] * q[1] - seed[4] * q[0];\n    values[6] = seed[6] * q[3] - seed[3] * q[0] - seed[4] * q[1] - seed[5] * q[2];\n  }\n}\n\n}  // end of namespace core\n}  // end of namespace moveit\n", "meta": {"hexsha": "d74a37aec2e13e80b1666cbe2cda95db8f52b643", "size": 13295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moveit_core/robot_model/src/floating_joint_model.cpp", "max_stars_repo_name": "lizixroy/moveit", "max_stars_repo_head_hexsha": "4db626d9c3b5d6296b012188a4a0bfe4bddf6bce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1116.0, "max_stars_repo_stars_event_min_datetime": "2016-07-29T06:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:14.000Z", "max_issues_repo_path": "moveit_core/robot_model/src/floating_joint_model.cpp", "max_issues_repo_name": "lizixroy/moveit", "max_issues_repo_head_hexsha": "4db626d9c3b5d6296b012188a4a0bfe4bddf6bce", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2784.0, "max_issues_repo_issues_event_min_datetime": "2016-07-29T15:19:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T01:35:59.000Z", "max_forks_repo_path": "moveit_core/robot_model/src/floating_joint_model.cpp", "max_forks_repo_name": "lizixroy/moveit", "max_forks_repo_head_hexsha": "4db626d9c3b5d6296b012188a4a0bfe4bddf6bce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 956.0, "max_forks_repo_forks_event_min_datetime": "2016-07-30T17:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:48:31.000Z", "avg_line_length": 37.4507042254, "max_line_length": 117, "alphanum_fraction": 0.6476871004, "num_tokens": 3874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.03021458379267781, "lm_q1q2_score": 0.009900361331351819}}
{"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#ifndef BOOST_GRAPH_NEIGHBOR_BREADTH_FIRST_SEARCH_HPP\n#define BOOST_GRAPH_NEIGHBOR_BREADTH_FIRST_SEARCH_HPP\n\n/*\n  Neighbor Breadth First Search\n  Like BFS, but traverses in-edges as well as out-edges.\n  (for directed graphs only. use normal BFS for undirected graphs)\n*/\n#include <boost/config.hpp>\n#include <vector>\n#include <boost/pending/queue.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/named_function_params.hpp>\n\nnamespace boost {\n\n  template <class Visitor, class Graph>\n  struct NeighborBFSVisitorConcept {\n    void constraints() {\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_out_edge(e, g);\n      vis.examine_in_edge(e, g);\n      vis.tree_out_edge(e, g);\n      vis.tree_in_edge(e, g);\n      vis.non_tree_out_edge(e, g);\n      vis.non_tree_in_edge(e, g);\n      vis.gray_target(e, g);\n      vis.black_target(e, g);\n      vis.gray_source(e, g);\n      vis.black_source(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  template <class Visitors = null_visitor>\n  class neighbor_bfs_visitor {\n  public:\n    neighbor_bfs_visitor(Visitors vis = Visitors()) : m_vis(vis) { }\n\n    template <class Vertex, class Graph>\n    void initialize_vertex(Vertex u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_initialize_vertex());      \n    }\n    template <class Vertex, class Graph>\n    void discover_vertex(Vertex u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_discover_vertex());      \n    }\n    template <class Vertex, class Graph>\n    void examine_vertex(Vertex u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_examine_vertex());\n    }\n    template <class Edge, class Graph>\n    void examine_out_edge(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_examine_edge());\n    }\n    template <class Edge, class Graph>\n    void tree_out_edge(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_tree_edge());      \n    }\n    template <class Edge, class Graph>\n    void non_tree_out_edge(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_non_tree_edge());\n    }\n    template <class Edge, class Graph>\n    void gray_target(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_gray_target());\n    }\n    template <class Edge, class Graph>\n    void black_target(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_black_target());\n    }\n    template <class Edge, class Graph>\n    void examine_in_edge(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_examine_edge());\n    }\n    template <class Edge, class Graph>\n    void tree_in_edge(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_tree_edge());      \n    }\n    template <class Edge, class Graph>\n    void non_tree_in_edge(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_non_tree_edge());\n    }\n    template <class Edge, class Graph>\n    void gray_source(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_gray_target());\n    }\n    template <class Edge, class Graph>\n    void black_source(Edge e, Graph& g) {\n      invoke_visitors(m_vis, e, g, on_black_target());\n    }\n    template <class Vertex, class Graph>\n    void finish_vertex(Vertex u, Graph& g) {\n      invoke_visitors(m_vis, u, g, on_finish_vertex());      \n    }\n  protected:\n    Visitors m_vis;\n  };\n\n  template <class Visitors>\n  neighbor_bfs_visitor<Visitors>\n  make_neighbor_bfs_visitor(Visitors vis) {\n    return neighbor_bfs_visitor<Visitors>(vis);\n  }\n\n  namespace detail {\n\n    template <class BidirectionalGraph, class Buffer, class BFSVisitor, \n              class ColorMap>\n    void neighbor_bfs_impl\n      (const BidirectionalGraph& g, \n       typename graph_traits<BidirectionalGraph>::vertex_descriptor s, \n       Buffer& Q, BFSVisitor vis, ColorMap color)\n\n    {\n      function_requires< BidirectionalGraphConcept<BidirectionalGraph> >();\n      typedef graph_traits<BidirectionalGraph> GTraits;\n      typedef typename GTraits::vertex_descriptor Vertex;\n      typedef typename GTraits::edge_descriptor Edge;\n      function_requires< \n        NeighborBFSVisitorConcept<BFSVisitor, BidirectionalGraph> >();\n      function_requires< ReadWritePropertyMapConcept<ColorMap, Vertex> >();\n      typedef typename property_traits<ColorMap>::value_type ColorValue;\n      typedef color_traits<ColorValue> Color;\n      \n      put(color, s, Color::gray());\n      vis.discover_vertex(s, g);\n      Q.push(s);\n      while (! Q.empty()) {\n        Vertex u = Q.top();\n        Q.pop(); // pop before push to avoid problem if Q is priority_queue.\n        vis.examine_vertex(u, g);\n\n        typename GTraits::out_edge_iterator ei, ei_end;\n        for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {\n          Edge e = *ei;\n          vis.examine_out_edge(e, g);\n          Vertex v = target(e, g);\n          ColorValue v_color = get(color, v);\n          if (v_color == Color::white()) {\n            vis.tree_out_edge(e, g);\n            put(color, v, Color::gray());\n            vis.discover_vertex(v, g);\n            Q.push(v);\n          } else {\n            vis.non_tree_out_edge(e, g);\n            if (v_color == Color::gray())\n              vis.gray_target(e, g);\n            else\n              vis.black_target(e, g);\n          }\n        } // for out-edges\n\n        typename GTraits::in_edge_iterator in_ei, in_ei_end;\n        for (tie(in_ei, in_ei_end) = in_edges(u, g); \n             in_ei != in_ei_end; ++in_ei) {\n          Edge e = *in_ei;\n          vis.examine_in_edge(e, g);\n          Vertex v = source(e, g);\n          ColorValue v_color = get(color, v);\n          if (v_color == Color::white()) {\n            vis.tree_in_edge(e, g);\n            put(color, v, Color::gray());\n            vis.discover_vertex(v, g);\n            Q.push(v);\n          } else {\n            vis.non_tree_in_edge(e, g);\n            if (v_color == Color::gray())\n              vis.gray_source(e, g);\n            else\n              vis.black_source(e, g);\n          }\n        } // for in-edges\n\n        put(color, u, Color::black());\n        vis.finish_vertex(u, g);\n      } // while\n    }\n\n    \n    template <class VertexListGraph, class ColorMap, class BFSVisitor,\n      class P, class T, class R>\n    void neighbor_bfs_helper\n      (VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s,\n       ColorMap color, \n       BFSVisitor vis,\n       const bgl_named_params<P, T, R>& params)\n    {\n      typedef graph_traits<VertexListGraph> Traits;\n      // Buffer default\n      typedef typename Traits::vertex_descriptor Vertex;\n      typedef boost::queue<Vertex> queue_t;\n      queue_t Q;\n      detail::wrap_ref<queue_t> Qref(Q);\n      // Initialization\n      typedef typename property_traits<ColorMap>::value_type ColorValue;\n      typedef color_traits<ColorValue> Color;\n      typename boost::graph_traits<VertexListGraph>::vertex_iterator i, i_end;\n      for (tie(i, i_end) = vertices(g); i != i_end; ++i) {\n        put(color, *i, Color::white());\n        vis.initialize_vertex(*i, g);\n      }\n      neighbor_bfs_impl\n        (g, s, \n         choose_param(get_param(params, buffer_param_t()), Qref).ref,\n         vis, color);\n    }\n\n    //-------------------------------------------------------------------------\n    // Choose between default color and color parameters. Using\n    // function dispatching so that we don't require vertex index if\n    // the color default is not being used.\n\n    template <class ColorMap>\n    struct neighbor_bfs_dispatch {\n      template <class VertexListGraph, class P, class T, class R>\n      static void apply\n      (VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s,\n       const bgl_named_params<P, T, R>& params,\n       ColorMap color)\n      {\n        neighbor_bfs_helper\n          (g, s, color,\n           choose_param(get_param(params, graph_visitor),\n                        make_neighbor_bfs_visitor(null_visitor())),\n           params);\n      }\n    };\n\n    template <>\n    struct neighbor_bfs_dispatch<detail::error_property_not_found> {\n      template <class VertexListGraph, class P, class T, class R>\n      static void apply\n      (VertexListGraph& g,\n       typename graph_traits<VertexListGraph>::vertex_descriptor s,\n       const bgl_named_params<P, T, R>& params,\n       detail::error_property_not_found)\n      {\n        std::vector<default_color_type> color_vec(num_vertices(g));\n        null_visitor null_vis;\n        \n        neighbor_bfs_helper\n          (g, s, \n           make_iterator_property_map\n           (color_vec.begin(), \n            choose_const_pmap(get_param(params, vertex_index), \n                              g, vertex_index), color_vec[0]),\n           choose_param(get_param(params, graph_visitor),\n                        make_neighbor_bfs_visitor(null_vis)),\n           params);\n      }\n    };\n\n  } // namespace detail\n\n\n  // Named Parameter Variant\n  template <class VertexListGraph, class P, class T, class R>\n  void neighbor_breadth_first_search\n    (const VertexListGraph& g,\n     typename graph_traits<VertexListGraph>::vertex_descriptor s,\n     const bgl_named_params<P, T, R>& params)\n  {\n    // The graph is passed by *const* reference so that graph adaptors\n    // (temporaries) can be passed into this function. However, the\n    // graph is not really const since we may write to property maps\n    // of the graph.\n    VertexListGraph& ng = const_cast<VertexListGraph&>(g);\n    typedef typename property_value< bgl_named_params<P,T,R>, \n      vertex_color_t>::type C;\n    detail::neighbor_bfs_dispatch<C>::apply(ng, s, params, \n                                            get_param(params, vertex_color));\n  }\n\n\n  // This version does not initialize colors, user has to.\n\n  template <class IncidenceGraph, class P, class T, class R>\n  void neighbor_breadth_first_visit\n    (IncidenceGraph& g,\n     typename graph_traits<IncidenceGraph>::vertex_descriptor s,\n     const bgl_named_params<P, T, R>& params)\n  {\n    typedef graph_traits<IncidenceGraph> Traits;\n    // Buffer default\n    typedef boost::queue<typename Traits::vertex_descriptor> queue_t;\n    queue_t Q;\n    detail::wrap_ref<queue_t> Qref(Q);\n\n    detail::neighbor_bfs_impl\n      (g, s,\n       choose_param(get_param(params, buffer_param_t()), Qref).ref,\n       choose_param(get_param(params, graph_visitor),\n                    make_neighbor_bfs_visitor(null_visitor())),\n       choose_pmap(get_param(params, vertex_color), g, vertex_color)\n       );\n  }\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_NEIGHBOR_BREADTH_FIRST_SEARCH_HPP\n\n", "meta": {"hexsha": "73cb79db6a5dca06d0ada49097b1d18feac06053", "size": 12060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/graph/neighbor_bfs.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/neighbor_bfs.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/graph/neighbor_bfs.hpp", "max_forks_repo_name": "Imperator-Knoedel/Sunset", "max_forks_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 35.4705882353, "max_line_length": 79, "alphanum_fraction": 0.6357379768, "num_tokens": 2869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815651265736978, "lm_q2_score": 0.0433658004638956, "lm_q1q2_score": 0.009894189802437768}}
{"text": "/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n\n/*! \n* \\file lognrbt.cpp\n* \\ingroup objects\n* \\brief LogNRbt (Log Newton-Raphson with backtracking) class source file.\n* \\author Robert Link\n*/\n\n#include \"util/base/include/definitions.h\"\n#include <string>\n#include <algorithm>\n#include <math.h>\n#include <xercesc/dom/DOMNode.hpp>\n#include <xercesc/dom/DOMNodeList.hpp>\n\n#include \"solution/solvers/include/solver_component.h\"\n#include \"solution/solvers/include/lognrbt.hpp\"\n#include \"solution/util/include/calc_counter.h\"\n#include \"marketplace/include/marketplace.h\"\n#include \"containers/include/world.h\"\n#include \"solution/util/include/solution_info_set.h\"\n#include \"solution/util/include/solution_info.h\"\n#include \"solution/util/include/solver_library.h\"\n#include \"util/base/include/util.h\"\n#include \"util/logger/include/ilogger.h\"\n#include \"util/base/include/xml_helper.h\"\n#include \"solution/util/include/solution_info_filter_factory.h\"\n#include \"solution/util/include/solvable_nr_solution_info_filter.h\"\n\n#include \"solution/util/include/functor-subs.hpp\"\n#include \"solution/util/include/linesearch.hpp\"\n#include \"solution/util/include/fdjac.hpp\" \n#include \"solution/util/include/edfun.hpp\"\n#include \"solution/util/include/ublas-helpers.hpp\"\n#include \"solution/util/include/jacobian-precondition.hpp\" \n#include \"util/base/include/fltcmp.hpp\"\n\n#if USE_LAPACK\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/bindings/lapack/gesvd.hpp>\n#include \"solution/util/include/svd_invert_solve.hpp\"\n#else\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#endif\n\n#include \"util/base/include/timer.h\"\n\nusing namespace std;\nusing namespace xercesc;\n\nstd::string LogNRbt::SOLVER_NAME = \"log-newton-raphson-backtracking-solver-component\";\n\n#if USE_LAPACK\n#define UBMATRIX boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major>\n#else\n#define UBMATRIX boost::numeric::ublas::matrix<double>\n#endif\n#define UBVECTOR boost::numeric::ublas::vector<double>\n\nnamespace {\n  // helper functions for the std::transform algorithm\n  double SI2lgprice (const SolutionInfo &si) {return log(si.getPrice());}\n  double SI2price (const SolutionInfo &si) {return si.getPrice();}\n}\n\nbool LogNRbt::XMLParse( const DOMNode* aNode ) {\n\n\n    // assume we were passed a valid node.\n    assert( aNode );\n    \n    // get the children of the node.\n    DOMNodeList* nodeList = aNode->getChildNodes();\n    \n    // loop through the children\n    for ( unsigned int i = 0; i < nodeList->getLength(); ++i ){\n        DOMNode* curr = nodeList->item( i );\n        string nodeName = XMLHelper<string>::safeTranscode( curr->getNodeName() );\n        \n        if( nodeName == \"#text\" ) {\n            continue;\n        }\n        else if( nodeName == \"max-iterations\" ) {\n            mMaxIter = XMLHelper<unsigned int>::getValue( curr );\n        }\n        else if( nodeName == \"ftol\" ) {\n            mFTOL = XMLHelper<double>::getValue(curr);\n        }\n        else if( nodeName == \"solution-info-filter\" ) {\n            mSolutionInfoFilter.reset(\n                SolutionInfoFilterFactory::createSolutionInfoFilterFromString( XMLHelper<string>::getValue( curr ) ) );\n        }\n        else if(nodeName == \"linear-price\") {\n          mLogPricep = false;\n        }\n        else if(nodeName == \"log-price\") {\n          mLogPricep = true;    // not strictly necessary, as this is the default.\n        } \n        else if( SolutionInfoFilterFactory::hasSolutionInfoFilter( nodeName ) ) {\n            mSolutionInfoFilter.reset( SolutionInfoFilterFactory::createAndParseSolutionInfoFilter( nodeName, curr ) );\n        }\n        else {\n            ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n            mainLog.setLevel( ILogger::WARNING );\n            mainLog << \"Unrecognized text string: \" << nodeName << \" found while parsing \"\n                << getXMLName() << \".\" << endl;\n        }\n    }\n    return true;\n}\n\n/*! \\brief Newton-Raphson solver in log-log space with backtracking\n  \n * \\details Attempts to solve the selected markets using a\n *          Newton-Raphson solution with backtracking (see Numerical\n *          Recipes sectn. 9.7).  The solution is performed in\n *          log-log space (log(D/S) as a function of log(price)), as\n *          this extends the domain and range to all reals.  Most of\n *          the heavy lifting is done by the function nrsolve(), wile\n *          this function mostly sets up the structures necessary to\n *          call nrsolve. \n * \\author Robert Link\n * \\param solnset An initial set of SolutionInfo objects representing all markets which can be filtered.\n * \\param period Model period.\n * \\return A status code to indicate if the algorithm was successful or not.\n */\n\nSolverComponent::ReturnCode LogNRbt::solve( SolutionInfoSet& solnset, int period ) {\n    ReturnCode code = SolverComponent::ORIGINAL_STATE;\n\n    // If all markets are solved, then return with success code.\n    if( solnset.isAllSolved() ){\n        return code = SolverComponent::SUCCESS;\n    }\n\n    startMethod();\n    \n    // Update the solution vector for the correct markets to solve.\n    // Need to update solvable status before starting solution (Ignore return code)\n    solnset.updateSolvable( mSolutionInfoFilter.get() );\n\n    ILogger& solverLog = ILogger::getLogger( \"solver_log\" );\n    solverLog.setLevel( ILogger::NOTICE );\n    solverLog << \"Beginning Newton-Raphson solution for period \" << period\n              << \"Solving \" << solnset.getNumSolvable() << \"markets.\\n\";\n    ILogger& worstMarketLog = ILogger::getLogger( \"worst_market_log\" );\n    worstMarketLog.setLevel( ILogger::DEBUG );\n    ILogger& singleLog = ILogger::getLogger( \"single_market_log\" );\n    singleLog.setLevel( ILogger::DEBUG );\n    \n    size_t nsolv = solnset.getNumSolvable(); \n    if( nsolv == 0 ){\n        solverLog << \"No markets were assigned to this solver.  Exiting.\" << endl;\n        return SUCCESS;\n    }\n    \n    solverLog << \"Initial market state:\\nmkt\\tprice\\tsupply\\tdemand\\n\";\n    std::vector<SolutionInfo> solvables = solnset.getSolvableSet();\n    for(size_t i=0; i<solvables.size(); ++i) {\n      solverLog << i << \"\\t\" << solvables[i].getPrice()\n                << \"\\t\" << solvables[i].getSupply()\n                << \"\\t\" << solvables[i].getDemand()\n                << \"\\t\\t\" << solvables[i].getName() << \"\\n\";\n    } \n\n    Timer& solverTimer = TimerRegistry::getInstance().getTimer( TimerRegistry::SOLVER );\n    solverTimer.start();\n    \n    UBVECTOR x(nsolv), fx(nsolv);\n    int neval = 0;\n\n    // set our initial x from the solutionInfoSet\n    std::vector<SolutionInfo> smkts(solnset.getSolvableSet());\n    if(mLogPricep)\n      std::transform(smkts.begin(), smkts.end(), x.begin(), SI2lgprice);\n    else\n      std::transform(smkts.begin(), smkts.end(), x.begin(), SI2price);\n\n    // This is the closure that will evaluate the ED function\n    LogEDFun F(solnset, world, marketplace, period, mLogPricep); \n\n    // scale the initial guess for use in F\n    F.scaleInitInputs(x);\n    \n    // Call F(x), store the result in fx\n    F(x,fx);\n\n    solverLog << \"Initial guess:\\n\" << x << \"\\nInitial F(x):\\n\" << fx << \"\\n\";\n\n    // Precondition the x values to avoid singular columns in the Jacobian\n    solverLog.setLevel(ILogger::DEBUG);\n    UBMATRIX J(F.narg(),F.nrtn());\n    fdjac(F, x, fx, J, true);\n    int pcfail = jacobian_precondition(x,fx,J,F,&solverLog, mLogPricep);\n\n    if(pcfail) {\n      solverLog.setLevel(ILogger::ERROR);\n      solverLog << \"Unable to find nonsingular initial guess for one or more markets.  nrsolve() will probably fail.\\n\";\n      solverLog.setLevel(ILogger::DEBUG);\n    }\n    else {\n      solverLog << \"Revised guess:\\n\" << x << \"\\nInitial F(x):\\n\" << fx << \"\\n\";\n    }\n    \n    // call the solver\n    int nrstatus = nrsolve(F, x, fx, J, neval);\n\n\n    solverTimer.stop();\n\n    solverLog.setLevel(ILogger::NOTICE);\n    solverLog << \"Newton-Raphson solver:  neval= \" << neval << \"\\nResult:  \";\n    if(nrstatus == 0) {\n        solverLog << \"NR solution success.\\n\";\n        code = SUCCESS;\n    }\n    else if(nrstatus == -1) {\n        code = FAILURE_ITER_MAX_REACHED;\n        solverLog << \"NR solution failed: Iteration max reached.\\n\";\n    }\n    else if(nrstatus == -3) {\n        code = FAILURE_ZERO_GRADIENT;\n        solverLog << \"NR solution failed:  Encountered zero gradient in F*F.\\n\";\n    }\n    else if(nrstatus > 0) {\n        code = FAILURE_SINGULAR_MATRIX;\n        solverLog << \"NR solution failed:  Encountered singular matrix (# singular components = \" << nrstatus << \").\\n\";\n    }\n    else {\n        code = FAILURE_UNKNOWN;\n        solverLog << \"NR solution failed for unknown reason.\\n\";\n    }\n    if(!solnset.isAllSolved()) {\n        solverLog << \"The following markets were not solved:\\n\";\n        solnset.printUnsolved(solverLog);\n    }\n\n    solverLog << endl;\n    return code;\n}\n\n\nint LogNRbt::nrsolve(VecFVec<double,double> &F, UBVECTOR &x, UBVECTOR &fx, UBMATRIX &J,\n                     int &neval)\n{\n#if !USE_LAPACK\n  using boost::numeric::ublas::permutation_matrix;\n  using boost::numeric::ublas::lu_factorize;\n  using boost::numeric::ublas::lu_substitute;\n#endif\n  using boost::numeric::ublas::axpy_prod;\n  using boost::numeric::ublas::inner_prod;\n  int nrow = J.size1(), ncol = J.size2();\n  // svd decomposition elements (note nrow == ncol)\n#if USE_LAPACK\n  UBMATRIX Usv(nrow,ncol),VTsv(ncol,ncol);\n  UBVECTOR Ssv(ncol);\n  int singcount = 0;\n  const int scmax = nrow/2;\n#else\n  permutation_matrix<int> p(F.narg()); // permutation vector for pivoting in L-U decomposition\n#endif\n  UBMATRIX Jtmp(nrow, ncol);\n  \n\n  ILogger &solverLog = ILogger::getLogger(\"solver_log\");\n\n  // Note that we no longer need to do a jacobian calculation here\n  // because we do one in the preconditioner\n  F(x,fx);\n\n  solverLog.setLevel(ILogger::DEBUG);\n  \n  neval += 1 + x.size();        // initial function evaluation + jacobian calculations\n\n  const double FTINY = mFTOL*mFTOL;\n  UBVECTOR dx(F.narg());\n  UBVECTOR xnew(F.narg());\n  UBVECTOR gx(F.narg());\n  assert(F.nrtn() == F.narg());\n  assert(x.size() == F.narg());\n  assert(fx.size() == F.nrtn());\n\n  // We create a functor that computes f(x) = F(x)*F(x).  It also\n  // stores the value of F that it produces as an intermediate.\n  FdotF<double,double> fnorm(F);\n  double f0 = inner_prod(fx,fx); // already have a value of F on input, so no need to call fnorm yet\n  if(f0 < FTINY)\n    // Guard against F=0 since it can cause a NaN in our solver.  This\n    // is a more stringent test than our regular convergence test\n    return 0;\n  \n  for(int iter=0; iter<mMaxIter; ++iter) {\n    solverLog << \"NR iter= \" << iter << \"\\tneval= \" << neval << \"\\n\";\n    axpy_prod(fx,J,gx);         // compute the gradient of F*F (= fx^T * J == J^T * fx)\n    // axpy_prod clears gx on entry, so we don't have to do it.\n    // NB: the order of fx and J in that last call is significant!\n    \n    // Check for zero gradient.  This indicates a local minimum in f,\n    // from which we are unlikely to escape.  We will need to try\n    // again with a different initial guess.  (This should be very\n    // uncommon)\n    if(inner_prod(gx,gx) / (f0+FTINY) < mFTOL) {\n      return -3;\n    }\n\n    Jtmp = J;                   // save the Jacobian, since gesvd destroys it.\n\n#if USE_LAPACK\n    int ierr =\n      boost::numeric::bindings::lapack::gesvd('O','A','A', // control parameters\n                                              J,           // input matrix\n                                              Ssv,Usv,VTsv); // output matrices\n    if(ierr != 0) {\n      // svd failed.  It's not even clear under what circumstances\n      // this can happen\n      solverLog.setLevel(ILogger::SEVERE);\n      solverLog << \"****************SVD failed.  This shouldn't happen.  It can't mean anything good.\\n\";\n      return ierr;\n    } \n    \n    // At this point, U, S, and VT contain the SVD of the original Jacobian\n    solverLog.setLevel(ILogger::DEBUG);\n    dx = -1.0*fx; \n    int nsing = svdInvertSolve(Usv,Ssv,VTsv,dx, solverLog);\n    \n    solverLog.setLevel(ILogger::DEBUG);\n    solverLog << \"\\n****************Iteration \" << iter << \"\\nf0= \" << f0\n              << \"\\tnsing= \" << nsing\n              << \"\\nx: \" << x << \"\\nF(x): \" << fx << \"\\ndx: \" << dx << \"\\n\";\n\n\n    if(nsing > 0) {\n      singcount += nsing;\n      if(singcount < scmax) {\n        // Try to reset the x value using the preconditioner\n        solverLog << \"Resetting singular matrix, singcount = \" << singcount << \"\\n\";\n        J = Jtmp;\n        int fail = jacobian_precondition(x, fx, J, F, &solverLog, mLogPricep);\n        if(fail)\n          return nsing;\n\n        // re-evaluate f0 and gx at the new guess\n        double f0 = inner_prod(fx,fx);\n        axpy_prod(fx,J,gx);         // compute the gradient of F*F (= fx^T * J == J^T * fx)\n        \n        // re-solve for dx using the new Jacobian\n        ierr = boost::numeric::bindings::lapack::gesvd('O','A','A', // control parameters\n                                                       J,           // input matrix\n                                                       Ssv,Usv,VTsv); // output matrices\n        if(ierr)\n          return nsing;\n        dx = -1.0*fx;\n        svdInvertSolve(Usv, Ssv, VTsv, dx, solverLog);\n      }\n      else {\n        return nsing;\n      }\n    }\n    else\n      singcount = 0;\n#else  /* No USE_LAPACK.  Use L-U decomposition to do the solution. */\n    int itrial = 0;\n    /* If the L-U decomposition fails the first time around, we will\n       invoke the jacobian preconditioner and try again.  If it fails\n       a second time, we bail out */\n    do {\n      for(size_t i=0; i<p.size(); ++i) p[i] = i;\n      int sing = lu_factorize(J,p);\n      if(sing>0) {\n        int fail=1;\n        if(itrial == 0)\n          fail = jacobian_precondition(x, fx, J, F, &solverLog, mLogPricep);\n        \n        if(fail) {\n          solverLog.setLevel(ILogger::WARNING);\n          solverLog << \"Singular Jacobian:\\n\" << Jtmp << \"\\n\";\n          return sing;\n        }\n      }\n      else {\n        // L-U decomp was successful.  Continue with the next phase of the algorithm.\n        break;\n      }\n    } while(++itrial < 2);\n    \n    // J now holds the L-U decomposition of the Jacobian.  Attempt backsubstitution\n    dx = -1.0*fx;\n    try {\n      lu_substitute(J,p,dx);    // solve dx = J^-1 F\n    }\n    catch (const boost::numeric::ublas::internal_logic &err) {\n      // This error seems to be thrown when the Jacobian is\n      // ill-conditioned.  We let it go because often the solver will\n      // muddle through to a solution.  If not, then it will\n      // eventually stop with a genuinely singular matrix.\n    }\n#endif /* USE_LAPACK */\n    \n    // dx now holds the newton step.  Execute the line search along\n    // that direction.\n    double fnew;\n    int lserr = linesearch(fnorm,x,f0,gx,dx, xnew,fnew, neval);\n\n    if(lserr != 0) {\n      // line search failed.  This means that the descent direction\n      // for F only extends a very short way (roughly TOL * x0).\n      // The most likely way for this to happen is if we're close to a\n      // discontinuity in (probably several components of) the\n      // Jacobian.  Using smoother supply and/or demand functions\n      // might help here.\n      \n      // It's also possible we failed because we're really close to\n      // the solution (sometimes dx gets really tiny near the\n      // solution).  Make a relaxed convergence test and return if we\n      // have a \"close enough\" solution.\n      double msf = f0/fx.size();\n      if(msf < mFTOL)\n        // basically, we're letting ourselves converge to the sqrt of\n        // our intended tolerance.\n        return 0;\n      \n      // We're not close enough to the solution, and we don't have a\n      // good descent direction.  There are no good options at this point\n      // so kick out and hope that the preconditioner can set us straight.\n      solverLog << \"linesearch failure\\n\";\n        return -4;\n    }\n\n    UBVECTOR xstep = xnew-x;    // step in x eventually taken\n    solverLog << \"################Return from linesearch\\nfold= \" << f0 << \"\\tfnew= \" << fnew\n              << \"\\n\";\n    f0 = fnew;\n    x  = xnew;\n    fnorm.lastF(fx);            // get the last value of big-F\n    solverLog << \"\\nxnew: \" << xnew << \"\\nfxnew: \" << fx << \"\\n\";\n    \n  \n    // test for convergence\n    double maxval = 0.0;\n    for(size_t i=0; i<fx.size(); ++i) {\n      double val = fabs(fx[i]);\n      maxval = val>maxval ? val : maxval;\n    }\n\n    solverLog << \"Convergence test maxval: \" << maxval << \"\\n\";\n    if(maxval <= mFTOL) {\n      solverLog << \"Solution successful.\\n\";\n      return 0;                 // SUCCESS \n    }\n    \n    fdjac(F,x,fx,J);            // calculate finite difference Jacobian for the next iteration\n    neval += x.size();          // N evaluations from calculating the Jacobian\n  }\n\n  // if we get here, then we didn't converge in the number of\n  // iterations allowed us.  Return an error code\n  solverLog << \"\\n****************Maximum solver iterations exceeded.\\nlastx: \" << x\n            << \"\\nlastF: \" << fx << \"\\n\";\n  return -1;\n}\n", "meta": {"hexsha": "e5c261773d4efad0398d567d810c4013e994ec18", "size": 18776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/solution/solvers/source/lognrbt.cpp", "max_stars_repo_name": "cmcormack/gcam-core", "max_stars_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-28T04:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T04:10:11.000Z", "max_issues_repo_path": "cvs/objects/solution/solvers/source/lognrbt.cpp", "max_issues_repo_name": "cmcormack/gcam-core", "max_issues_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-30T21:13:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-14T13:21:13.000Z", "max_forks_repo_path": "cvs/objects/solution/solvers/source/lognrbt.cpp", "max_forks_repo_name": "cmcormack/gcam-core", "max_forks_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-26T05:56:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T10:29:30.000Z", "avg_line_length": 37.7786720322, "max_line_length": 120, "alphanum_fraction": 0.6324030677, "num_tokens": 4885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473631961696, "lm_q2_score": 0.022977370913592483, "lm_q1q2_score": 0.009883655511662169}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <map>\n#include <memory>\n#include <optional>\n#include <tuple>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Elliptic/BoundaryConditions/BoundaryCondition.hpp\"\n#include \"Elliptic/BoundaryConditions/BoundaryConditionType.hpp\"\n#include \"Elliptic/DiscontinuousGalerkin/SubdomainOperator/SubdomainOperator.hpp\"\n#include \"Elliptic/Systems/Poisson/BoundaryConditions/Robin.hpp\"\n#include \"Elliptic/Systems/Poisson/FirstOrderSystem.hpp\"\n#include \"Elliptic/Systems/Poisson/Tags.hpp\"\n#include \"NumericalAlgorithms/Convergence/HasConverged.hpp\"\n#include \"NumericalAlgorithms/LinearSolver/ExplicitInverse.hpp\"\n#include \"NumericalAlgorithms/LinearSolver/Gmres.hpp\"\n#include \"NumericalAlgorithms/LinearSolver/LinearSolver.hpp\"\n#include \"Options/Auto.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"ParallelAlgorithms/LinearSolver/Schwarz/ElementCenteredSubdomainData.hpp\"\n#include \"ParallelAlgorithms/LinearSolver/Schwarz/Tags.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// Linear solvers that approximately invert the\n/// `elliptic::dg::subdomain_operator::SubdomainOperator` to make the Schwarz\n/// subdomain solver converge faster.\n/// \\see LinearSolver::Schwarz::Schwarz\nnamespace elliptic::subdomain_preconditioners {\n\n/// \\cond\ntemplate <size_t Dim, typename OptionsGroup, typename Solver,\n          typename LinearSolverRegistrars>\nstruct MinusLaplacian;\n/// \\endcond\n\nnamespace Registrars {\ntemplate <size_t Dim, typename OptionsGroup,\n          typename Solver = LinearSolver::Serial::LinearSolver<tmpl::list<\n              ::LinearSolver::Serial::Registrars::Gmres<\n                  ::LinearSolver::Schwarz::ElementCenteredSubdomainData<\n                      Dim, tmpl::list<Poisson::Tags::Field>>>,\n              ::LinearSolver::Serial::Registrars::ExplicitInverse>>>\nstruct MinusLaplacian {\n  template <typename LinearSolverRegistrars>\n  using f = subdomain_preconditioners::MinusLaplacian<Dim, OptionsGroup, Solver,\n                                                      LinearSolverRegistrars>;\n};\n}  // namespace Registrars\n\n/*!\n * \\brief Approximate the subdomain operator with a flat-space Laplacian\n * for every tensor component separately.\n *\n * This linear solver applies the `Solver` to every tensor component in\n * turn, approximating the subdomain operator with a flat-space Laplacian.\n * This can be a lot cheaper than solving the\n * full subdomain operator and can provide effective preconditioning for an\n * iterative subdomain solver. The approximation is better the closer the\n * original PDEs are to a set of decoupled flat-space Poisson equations.\n *\n * \\par Boundary conditions\n * At external boundaries we impose homogeneous Dirichlet or Neumann boundary\n * conditions on the Poisson sub-problems. For tensor components and element\n * faces where the original boundary conditions are of Dirichlet-type we choose\n * homogeneous Dirichlet boundary conditions, and for those where the original\n * boundary conditions are of Neumann-type we choose homogeneous Neumann\n * boundary conditions. This means we may end up with more than one distinct\n * Poisson operator on subdomains with external boundaries, one per unique\n * combination of element face and boundary-condition type among the tensor\n * components.\n *\n * \\tparam Dim Spatial dimension\n * \\tparam OptionsGroup The options group identifying the\n * `LinearSolver::Schwarz::Schwarz` solver that defines the subdomain geometry.\n * \\tparam Solver Any class that provides a `solve` and a `reset` function,\n * but typically a `LinearSolver::Serial::LinearSolver`. The solver will be\n * factory-created from input-file options.\n */\ntemplate <size_t Dim, typename OptionsGroup,\n          typename Solver = LinearSolver::Serial::LinearSolver<tmpl::list<\n              ::LinearSolver::Serial::Registrars::Gmres<\n                  ::LinearSolver::Schwarz::ElementCenteredSubdomainData<\n                      Dim, tmpl::list<Poisson::Tags::Field>>>,\n              ::LinearSolver::Serial::Registrars::ExplicitInverse>>,\n          typename LinearSolverRegistrars =\n              tmpl::list<Registrars::MinusLaplacian<Dim, OptionsGroup, Solver>>>\nclass MinusLaplacian\n    : public LinearSolver::Serial::LinearSolver<LinearSolverRegistrars> {\n private:\n  using Base = LinearSolver::Serial::LinearSolver<LinearSolverRegistrars>;\n  using StoredSolverType = tmpl::conditional_t<std::is_abstract_v<Solver>,\n                                               std::unique_ptr<Solver>, Solver>;\n  // Identifies an external block boundary, for boundary conditions\n  using BoundaryId = std::pair<size_t, Direction<Dim>>;\n\n public:\n  static constexpr size_t volume_dim = Dim;\n  using options_group = OptionsGroup;\n  using poisson_system =\n      Poisson::FirstOrderSystem<Dim, Poisson::Geometry::FlatCartesian>;\n  using BoundaryConditionsBase =\n      typename poisson_system::boundary_conditions_base;\n  using SubdomainOperator = elliptic::dg::subdomain_operator::SubdomainOperator<\n      poisson_system, OptionsGroup, tmpl::list<>,\n      tmpl::list<Poisson::BoundaryConditions::Robin<Dim>>>;\n  using SubdomainData = ::LinearSolver::Schwarz::ElementCenteredSubdomainData<\n      Dim, tmpl::list<Poisson::Tags::Field>>;\n  // Associates Dirichlet or Neumann conditions to every external block\n  // boundary. For every configuration of this type we'll need a separate\n  // solver, which may cache the Poisson operator matrix that imposes the\n  // corresponding boundary conditions. This type is used as key in other maps,\n  // so it must be hashable. `std::unordered_map` isn't supported by\n  // `boost::hash`, but `std::map` is.\n  using BoundaryConditionsSignature =\n      std::map<BoundaryId, elliptic::BoundaryConditionType>;\n  using solver_type = Solver;\n\n  struct SolverOptionTag {\n    static std::string name() { return \"Solver\"; }\n    using type = StoredSolverType;\n    static constexpr Options::String help =\n        \"The linear solver used to invert the Laplace operator. The solver is \"\n        \"shared between tensor components with the same type of boundary \"\n        \"conditions (Dirichlet-type or Neumann-type).\";\n  };\n\n  struct BoundaryConditions {\n    using type = Options::Auto<elliptic::BoundaryConditionType>;\n    static constexpr Options::String help =\n        \"The boundary conditions imposed by the Laplace operator. Specify \"\n        \"'Auto' to choose between homogeneous Dirichlet or Neumann boundary \"\n        \"conditions automatically, based on the configuration of the the full \"\n        \"operator.\";\n  };\n\n  using options = tmpl::list<SolverOptionTag, BoundaryConditions>;\n  static constexpr Options::String help =\n      \"Approximate the linear operator with a Laplace operator \"\n      \"for every tensor component separately.\";\n\n  MinusLaplacian() = default;\n  MinusLaplacian(MinusLaplacian&& /*rhs*/) = default;\n  MinusLaplacian& operator=(MinusLaplacian&& /*rhs*/) = default;\n  ~MinusLaplacian() = default;\n  MinusLaplacian(const MinusLaplacian& rhs)\n      : Base(rhs),\n        solver_(rhs.clone_solver()),\n        boundary_condition_type_(rhs.boundary_condition_type_) {}\n  MinusLaplacian& operator=(const MinusLaplacian& rhs) {\n    Base::operator=(rhs);\n    solver_ = rhs.clone_solver();\n    boundary_condition_type_ = rhs.boundary_condition_type_;\n    return *this;\n  }\n\n  /// \\cond\n  explicit MinusLaplacian(CkMigrateMessage* m) : Base(m) {}\n  using PUP::able::register_constructor;\n  WRAPPED_PUPable_decl_template(MinusLaplacian);  // NOLINT\n  /// \\endcond\n\n  MinusLaplacian(\n      StoredSolverType solver,\n      std::optional<elliptic::BoundaryConditionType> boundary_condition_type)\n      : solver_(std::move(solver)),\n        boundary_condition_type_(boundary_condition_type) {}\n\n  const Solver& solver() const {\n    if constexpr (std::is_abstract_v<Solver>) {\n      return *solver_;\n    } else {\n      return solver_;\n    }\n  }\n\n  /// The cached solvers for each unique boundary-condition signature. These are\n  /// only exposed to allow verifying their consistency.\n  const auto& cached_solvers() const { return solvers_; }\n\n  /// Solve the equation \\f$Ax=b\\f$ by approximating \\f$A\\f$ with a Laplace\n  /// operator for every tensor component in \\f$x\\f$.\n  template <typename LinearOperator, typename VarsType, typename SourceType,\n            typename... OperatorArgs>\n  Convergence::HasConverged solve(\n      gsl::not_null<VarsType*> solution, LinearOperator&& linear_operator,\n      const SourceType& source,\n      const std::tuple<OperatorArgs...>& operator_args) const;\n\n  void reset() override {\n    mutable_solver().reset();\n    // These buffers depend on the operator being solved, so they are reset when\n    // the operator changes. The other buffers only hold workspace memory so\n    // they don't need to be reset.\n    bc_signatures_ = std::nullopt;\n    solvers_.clear();\n    boundary_conditions_.clear();\n  }\n\n  // NOLINTNEXTLINE(google-runtime-references)\n  void pup(PUP::er& p) override {\n    Base::pup(p);\n    // Serialize object state\n    p | solver_;\n    p | boundary_condition_type_;\n    // Serialize caches that are possibly expensive to re-create\n    p | bc_signatures_;\n    p | solvers_;\n    // Other properties are memory buffers that don't need to be serialized.\n  }\n\n  std::unique_ptr<Base> get_clone() const override {\n    return std::make_unique<MinusLaplacian>(*this);\n  }\n\n private:\n  // For each tensor component, get the set of boundary conditions that should\n  // be imposed by the Laplacian operator on that component, based on the domain\n  // configuration. These are cached for successive solves of the same operator.\n  // An empty list means the subdomain has no external boundaries.\n  template <typename DbTagsList>\n  const std::vector<BoundaryConditionsSignature>&\n  get_cached_boundary_conditions_signatures(\n      const db::DataBox<DbTagsList>& box) const {\n    if (bc_signatures_.has_value()) {\n      // Use cached value\n      return *bc_signatures_;\n    }\n    bc_signatures_ = std::vector<BoundaryConditionsSignature>{};\n    const auto& blocks = db::get<domain::Tags::Domain<Dim>>(box).blocks();\n    const auto collect_bc_signatures = [&bc_signatures = *bc_signatures_,\n                                        &override_boundary_condition_type =\n                                            boundary_condition_type_,\n                                        &blocks](\n                                           const BoundaryId& boundary_id) {\n      if (not bc_signatures.empty() and\n          bc_signatures[0].find(boundary_id) != bc_signatures[0].end()) {\n        // We have already handled this block boundary in an earlier\n        // iteration of the loop. This can happend when the domain is\n        // h-refined, or when multiple elements in a subdomain face the\n        // block boundary.\n        return;\n      }\n      // Get the type of boundary condition (Dirichlet or Neumann) for\n      // each tensor component from the domain configuration\n      const auto& [block_id, direction] = boundary_id;\n      const auto original_boundary_condition = dynamic_cast<\n          const elliptic::BoundaryConditions::BoundaryCondition<Dim>*>(\n          blocks.at(block_id)\n              .external_boundary_conditions()\n              .at(direction)\n              .get());\n      ASSERT(original_boundary_condition != nullptr,\n             \"The boundary condition in block \"\n                 << block_id << \", direction \" << direction\n                 << \" is not of the expected type \"\n                    \"'elliptic::BoundaryConditions::BoundaryCondition<\"\n                 << Dim << \">'.\");\n      const std::vector<elliptic::BoundaryConditionType> bc_types =\n          original_boundary_condition->boundary_condition_types();\n      const size_t num_components = bc_types.size();\n      if (bc_signatures.empty()) {\n        bc_signatures.resize(num_components);\n      } else {\n        ASSERT(bc_signatures.size() == num_components,\n               \"Unexpected number of boundary-condition types. The \"\n               \"boundary condition in block \"\n                   << block_id << \", direction \" << direction << \" returned \"\n                   << num_components << \" items, but another returned \"\n                   << bc_signatures.size()\n                   << \" (one for each tensor component).\");\n      }\n      for (size_t component = 0; component < num_components; ++component) {\n        bc_signatures[component].emplace(\n            boundary_id,\n            override_boundary_condition_type.value_or(bc_types.at(component)));\n      }\n    };\n    // Collect boundary-condition signatures from all elements in the subdomain\n    const auto& element = db::get<domain::Tags::Element<Dim>>(box);\n    for (const auto& direction : element.external_boundaries()) {\n      collect_bc_signatures({element.id().block_id(), direction});\n    }\n    const auto& overlap_elements =\n        db::get<LinearSolver::Schwarz::Tags::Overlaps<\n            domain::Tags::Element<Dim>, Dim, OptionsGroup>>(box);\n    for (const auto& [overlap_id, overlap_element] : overlap_elements) {\n      (void)overlap_id;\n      for (const auto& direction : overlap_element.external_boundaries()) {\n        collect_bc_signatures({overlap_element.id().block_id(), direction});\n      }\n    }\n    return *bc_signatures_;\n  }\n\n  // For a tensor component with the given boundary-condition configuration, get\n  // the solver and the set of boundary conditions that will be passed to the\n  // Poisson subdomain operator. The solver is cached for successive solves of\n  // the same operator. Caching is very important for performance, since the\n  // solver may build up an explicit matrix representation that is expensive to\n  // re-create.\n  std::pair<const Solver&,\n            const std::unordered_map<BoundaryId, const BoundaryConditionsBase&,\n                                     boost::hash<BoundaryId>>&>\n  get_cached_solver_and_boundary_conditions(\n      const std::vector<BoundaryConditionsSignature>& bc_signatures,\n      const size_t component) const {\n    if (bc_signatures.empty()) {\n      // The subdomain has no external boundaries. We use the original solver.\n      return {solver(), boundary_conditions_[{}]};\n    }\n    // Get the cached solver corresponding to this component's\n    // boundary-condition configuration\n    const auto& bc_signature = bc_signatures.at(component);\n    if (solvers_.find(bc_signature) == solvers_.end()) {\n      solvers_.emplace(bc_signature, clone_solver());\n    }\n    const Solver& cached_solver = [this, &bc_signature]() -> const Solver& {\n      if constexpr (std::is_abstract_v<Solver>) {\n        return *solvers_.at(bc_signature);\n      } else {\n        return solvers_.at(bc_signature);\n      }\n    }();\n    // Get the cached set of boundary conditions for this component\n    if (boundary_conditions_.find(bc_signature) == boundary_conditions_.end()) {\n      auto& bc = boundary_conditions_[bc_signature];\n      for (const auto& [boundary_id, bc_type] : bc_signature) {\n        bc.emplace(boundary_id,\n                   bc_type == elliptic::BoundaryConditionType::Dirichlet\n                       ? dirichlet_bc\n                       : neumann_bc);\n      }\n    }\n    return {cached_solver, boundary_conditions_[bc_signature]};\n  }\n\n  Solver& mutable_solver() {\n    if constexpr (std::is_abstract_v<Solver>) {\n      return *solver_;\n    } else {\n      return solver_;\n    }\n  }\n\n  StoredSolverType clone_solver() const {\n    if constexpr (std::is_abstract_v<Solver>) {\n      return solver_->get_clone();\n    } else {\n      return solver_;\n    }\n  }\n\n  // The option-constructed solver for the separate Poisson problems. It is\n  // cloned for each unique boundary-condition configuration of the tensor\n  // components.\n  StoredSolverType solver_{};\n  std::optional<elliptic::BoundaryConditionType> boundary_condition_type_;\n\n  // These are caches to keep track of the unique boundary-condition\n  // configurations. Each configuration has its own solver, because the solver\n  // may cache the operator to speed up repeated solves.\n  // - The boundary-condition configuration for each tensor component, or an\n  //   empty list if the subdomain has no external boundaries, or `std::nullopt`\n  //   to signal a clean cache.\n  mutable std::optional<std::vector<BoundaryConditionsSignature>>\n      bc_signatures_{};\n  // - A clone of the `solver_` for each unique boundary-condition configuration\n  mutable std::unordered_map<BoundaryConditionsSignature, StoredSolverType,\n                             boost::hash<BoundaryConditionsSignature>>\n      solvers_{};\n  mutable std::unordered_map<\n      BoundaryConditionsSignature,\n      std::unordered_map<BoundaryId, const BoundaryConditionsBase&,\n                         boost::hash<BoundaryId>>,\n      boost::hash<BoundaryConditionsSignature>>\n      boundary_conditions_{};\n\n  // These are memory buffers that are kept around for repeated solves. Possible\n  // optimization: Free this memory at appropriate times, e.g. when the element\n  // has completed a full subdomain solve and goes to the background. In some\n  // cases the `subdomain_operator_` is never even used again in subsequent\n  // subdomain solves because it is cached as a matrix (see\n  // LinearSolver::Serial::ExplicitInverse), so we don't need the memory anymore\n  // at all.\n  mutable SubdomainOperator subdomain_operator_{};\n  mutable SubdomainData source_{};\n  mutable SubdomainData initial_guess_in_solution_out_{};\n\n  // These boundary condition instances can be re-used for all tensor components\n  // Note that the _linearized_ boundary conditions are applied by the subdomain\n  // operator, so the constant (third argument) is irrelevant.\n  const Poisson::BoundaryConditions::Robin<Dim> dirichlet_bc{1., 0., 0.};\n  const Poisson::BoundaryConditions::Robin<Dim> neumann_bc{0., 1., 0.};\n};\n\nnamespace detail {\ntemplate <size_t Dim, typename LhsTagsList, typename RhsTagsList>\nvoid assign_component(\n    const gsl::not_null<::LinearSolver::Schwarz::ElementCenteredSubdomainData<\n        Dim, LhsTagsList>*>\n        lhs,\n    const ::LinearSolver::Schwarz::ElementCenteredSubdomainData<\n        Dim, RhsTagsList>& rhs,\n    const size_t lhs_component, const size_t rhs_component) {\n  // Possible optimization: Once we have non-owning Variables we can use a view\n  // into the rhs here instead of copying.\n  const size_t num_points_element = rhs.element_data.number_of_grid_points();\n  for (size_t i = 0; i < num_points_element; ++i) {\n    lhs->element_data.data()[lhs_component * num_points_element + i] =\n        rhs.element_data.data()[rhs_component * num_points_element + i];\n  }\n  for (const auto& [overlap_id, rhs_data] : rhs.overlap_data) {\n    const size_t num_points_overlap = rhs_data.number_of_grid_points();\n    // The random-access operation is relatively slow because it computes a\n    // hash, so it's important for performance to avoid repeating it in every\n    // iteration of the loop below.\n    auto& lhs_vars = lhs->overlap_data[overlap_id];\n    for (size_t i = 0; i < num_points_overlap; ++i) {\n      lhs_vars.data()[lhs_component * num_points_overlap + i] =\n          rhs_data.data()[rhs_component * num_points_overlap + i];\n    }\n  }\n}\n}  // namespace detail\n\ntemplate <size_t Dim, typename OptionsGroup, typename Solver,\n          typename LinearSolverRegistrars>\ntemplate <typename LinearOperator, typename VarsType, typename SourceType,\n          typename... OperatorArgs>\nConvergence::HasConverged\nMinusLaplacian<Dim, OptionsGroup, Solver, LinearSolverRegistrars>::solve(\n    const gsl::not_null<VarsType*> initial_guess_in_solution_out,\n    LinearOperator&& /*linear_operator*/, const SourceType& source,\n    const std::tuple<OperatorArgs...>& operator_args) const {\n  const auto& box = get<0>(operator_args);\n  // Solve each component of the source variables in turn, assuming the operator\n  // is a Laplacian. For each component we select either homogeneous Dirichlet\n  // or Neumann boundary conditions, based on the type of boundary conditions\n  // imposed by the full operator.\n  static constexpr size_t num_components =\n      VarsType::ElementData::number_of_independent_components;\n  source_.destructive_resize(source);\n  initial_guess_in_solution_out_.destructive_resize(source);\n  const std::vector<BoundaryConditionsSignature>& bc_signatures =\n      get_cached_boundary_conditions_signatures(box);\n  ASSERT(bc_signatures.empty() or bc_signatures.size() == num_components,\n         \"Expected \" << num_components\n                     << \" boundary-condition signatures (one per tensor \"\n                        \"component), but got \"\n                     << bc_signatures.size() << \".\");\n  for (size_t component = 0; component < num_components; ++component) {\n    detail::assign_component(make_not_null(&source_), source, 0, component);\n    detail::assign_component(make_not_null(&initial_guess_in_solution_out_),\n                             *initial_guess_in_solution_out, 0, component);\n    const auto& [solver, boundary_conditions] =\n        get_cached_solver_and_boundary_conditions(bc_signatures, component);\n    solver.solve(make_not_null(&initial_guess_in_solution_out_),\n                 subdomain_operator_, source_,\n                 std::forward_as_tuple(box, boundary_conditions));\n    detail::assign_component(initial_guess_in_solution_out,\n                             initial_guess_in_solution_out_, component, 0);\n  }\n  return {0, 0};\n}\n\n/// \\cond\ntemplate <size_t Dim, typename OptionsGroup, typename Solver,\n          typename LinearSolverRegistrars>\n// NOLINTNEXTLINE\nPUP::able::PUP_ID MinusLaplacian<Dim, OptionsGroup, Solver,\n                                 LinearSolverRegistrars>::my_PUP_ID = 0;\n/// \\endcond\n\n}  // namespace elliptic::subdomain_preconditioners\n", "meta": {"hexsha": "910755cf6f16a28a8708b94c000adee09cc84fce", "size": 22100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Elliptic/SubdomainPreconditioners/MinusLaplacian.hpp", "max_stars_repo_name": "Shabibti/spectre", "max_stars_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Elliptic/SubdomainPreconditioners/MinusLaplacian.hpp", "max_issues_repo_name": "Shabibti/spectre", "max_issues_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Elliptic/SubdomainPreconditioners/MinusLaplacian.hpp", "max_forks_repo_name": "Shabibti/spectre", "max_forks_repo_head_hexsha": "0fa0353e209ef2bc53100f7101bd05f12e812f5e", "max_forks_repo_licenses": ["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.1020408163, "max_line_length": 83, "alphanum_fraction": 0.7024886878, "num_tokens": 4934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.021615334929176125, "lm_q1q2_score": 0.009881163562376755}}
{"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 \"PyImathLine.h\"\n#include \"PyImathDecorators.h\"\n#include \"PyImathExport.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include \"PyImath.h\"\n#include \"PyImathVec.h\"\n#include \"PyImathMathExc.h\"\n#include <ImathLineAlgo.h>\n#include <ImathMatrix.h>\n#include <Iex.h>\n\n\nnamespace PyImath{\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\n\ntemplate <class T> struct LineName {static const char *value;};\ntemplate <> const char *LineName<float>::value = \"Line3f\";\ntemplate <> const char *LineName<double>::value = \"Line3d\";\n\ntemplate <class T>\nstatic Line3<T> * \nLine3_construct_default()\n{\n    Vec3<T> point1(T (0), T(0), T(0));\n    Vec3<T> point2(T (1), T(0), T(0));\n    \n    return new Line3<T>(point1, point2);\n}\n\ntemplate <class T>\nstatic Line3<T> * \nLine3_tuple_construct(const tuple &t0, const tuple &t1)\n{\n    Vec3<T> v0, v1;\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3)\n    {\n        v0.x = extract<T>(t0[0]);\n        v0.y = extract<T>(t0[1]);\n        v0.z = extract<T>(t0[2]);\n\n        v1.x = extract<T>(t1[0]);\n        v1.y = extract<T>(t1[1]);\n        v1.z = extract<T>(t1[2]);\n        \n        return new Line3<T>(v0, v1);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");    \n}\n\ntemplate <class T, class S>\nstatic Line3<T> *\nLine3_line_construct(const Line3<S> &line)\n{\n    Line3<T> *l = new Line3<T>;\n    l->pos = line.pos;\n    l->dir = line.dir;\n    \n    return l;\n}\n\ntemplate <class T>\nstatic void\nset1(Line3<T> &line, const Vec3<T> &p0, const Vec3<T> &p1)\n{\n    MATH_EXC_ON;\n    line.set (p0, p1);\n}\n\ntemplate <class T>\nstatic void\nsetTuple(Line3<T> &line, const tuple &t0, const tuple &t1)\n{\n    MATH_EXC_ON;\n    Vec3<T> v0, v1;\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3)\n    {\n        v0.x = extract<T>(t0[0]);\n        v0.y = extract<T>(t0[1]);\n        v0.z = extract<T>(t0[2]);\n\n        v1.x = extract<T>(t1[0]);\n        v1.y = extract<T>(t1[1]);\n        v1.z = extract<T>(t1[2]);\n        \n        line.set(v0, v1);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");    \n}\n\ntemplate <class T>\nstatic Vec3<T>\npointAt(Line3<T> &line, T t)\n{\n    MATH_EXC_ON;\n    return line.operator()(t);\n}\n\ntemplate <class T>\nstatic T\ndistanceTo1(Line3<T> &line, Vec3<T> &p)\n{\n    MATH_EXC_ON;\n    return line.distanceTo(p);\n}\n\ntemplate <class T>\nstatic T\ndistanceTo2(Line3<T> &line, Line3<T> &other)\n{\n    MATH_EXC_ON;\n    return line.distanceTo(other);\n}\n\ntemplate <class T>\nstatic T\ndistanceToTuple(Line3<T> line, const tuple &t)\n{\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        return line.distanceTo(v);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");      \n}\n\ntemplate <class T>\nstatic Vec3<T>\nclosestPointTo1(Line3<T> line, const Vec3<T> &p)\n{\n    MATH_EXC_ON;\n    return line.closestPointTo(p);\n}\n\ntemplate <class T>\nstatic Vec3<T>\nclosestPointTo2(Line3<T> line, const Line3<T> &other)\n{\n    MATH_EXC_ON;\n    return line.closestPointTo(other);\n}\n                     \ntemplate <class T>\nstatic Vec3<T>\nclosestPointToTuple(Line3<T> line, 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        return line.closestPointTo(v);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");      \n}\n\ntemplate <class T>\nstatic Vec3<T>\ngetPosition(Line3<T> &line)\n{\n    return line.pos;\n}\n\ntemplate <class T>\nstatic void\nsetPosition(Line3<T> &line, const Vec3<T> &pos)\n{\n    line.pos = pos;\n}\n\ntemplate <class T>\nstatic void\nsetPositionTuple(Line3<T> &line, const tuple &t)\n{\n    Vec3<T> pos;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        pos.x = extract<T>(t[0]);\n        pos.y = extract<T>(t[1]);\n        pos.z = extract<T>(t[2]);\n        \n        line.pos = pos;\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");    \n}\n\ntemplate <class T>\nstatic Vec3<T>\ngetDirection(Line3<T> &line)\n{\n    return line.dir;\n}\n\ntemplate <class T>\nstatic void\nsetDirection(Line3<T> &line, const Vec3<T> &dir)\n{\n    MATH_EXC_ON;\n    line.dir = dir.normalized();\n}\n\ntemplate <class T>\nstatic void\nsetDirectionTuple(Line3<T> &line, const tuple &t)\n{\n    MATH_EXC_ON;\n    Vec3<T> dir;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        dir.x = extract<T>(t[0]);\n        dir.y = extract<T>(t[1]);\n        dir.z = extract<T>(t[2]);\n        \n        line.dir = dir.normalized();\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");    \n}\n\ntemplate <class T>\nstatic void\nclosestPoints1(Line3<T> &line1, const Line3<T> &line2, Vec3<T> &p0, Vec3<T> &p1)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::closestPoints(line1, line2, p0, p1);\n}\n\ntemplate <class T>\nstatic tuple\nclosestPoints2(Line3<T> &line1, const Line3<T> &line2)\n{\n    MATH_EXC_ON;\n    Vec3<T> p0, p1;\n    IMATH_NAMESPACE::closestPoints(line1, line2, p0, p1);\n    tuple p0Tuple = make_tuple(p0.x,p0.y,p0.z);\n    tuple p1Tuple = make_tuple(p1.x,p1.y,p1.z);\n\n#if !defined(_MSC_VER) || (_MSC_VER <= 1200)\n    tuple t = make_tuple(p0Tuple, p1Tuple);\n    return t;\n#else\n    list v3;\n    v3.append(p0Tuple);\n    v3.append(p1Tuple);\n    return tuple(v3);\n#endif\n}\n\ntemplate <class T>\nstatic Vec3<T>\nclosestVertex(Line3<T> &line, const Vec3<T> &v0, const Vec3<T> &v1, const Vec3<T> &v2)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::closestVertex(v0, v1, v2, line);\n}\n\ntemplate <class T>\nstatic Vec3<T>\nclosestVertexTuple(Line3<T> &line, const tuple &t0, const tuple &t1, const tuple &t2)\n{\n    MATH_EXC_ON;\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3 && t2.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> v0, v1, v2;\n        v0.x = extract<T>(t0[0]);\n        v0.y = extract<T>(t0[1]);\n        v0.z = extract<T>(t0[2]);\n        \n        v1.x = extract<T>(t1[0]);\n        v1.y = extract<T>(t1[1]);\n        v1.z = extract<T>(t1[2]);\n\n        v2.x = extract<T>(t2[0]);\n        v2.y = extract<T>(t2[1]);\n        v2.z = extract<T>(t2[2]);\n        \n        return IMATH_NAMESPACE::closestVertex(v0, v1, v2, line);\n    }        \n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");      \n}\n\ntemplate <class T>\nstatic bool\nintersect1(Line3<T> &line, const Vec3<T> &v0, const Vec3<T> &v1, const Vec3<T> &v2, \n          Vec3<T> &pt, Vec3<T> &barycentric, bool &front)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::intersect(line, v0, v1, v2, pt, barycentric, front);\n}\n\ntemplate <class T>\nstatic object\nintersect2(Line3<T> &line, const Vec3<T> &v0, const Vec3<T> &v1, const Vec3<T> &v2)\n{    \n    MATH_EXC_ON;\n    Vec3<T> pt, bar;\n    bool front;\n    \n    if(IMATH_NAMESPACE::intersect(line, v0, v1, v2, pt, bar, front))\n    {\n        return make_tuple (pt, bar, front);\n    }\n    else\n    {\n        return object();\n    }\n}\n\ntemplate <class T>\nstatic tuple\nintersectTuple(Line3<T> &line, const tuple &t0, const tuple &t1, const tuple &t2)\n{    \n\n    if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3 && t2.attr(\"__len__\")() == 3)\n    {   \n        Vec3<T> v0, v1, v2, pt, bar;\n        bool front;\n        v0.x = extract<T>(t0[0]);\n        v0.y = extract<T>(t0[1]);\n        v0.z = extract<T>(t0[2]);\n        \n        v1.x = extract<T>(t1[0]);\n        v1.y = extract<T>(t1[1]);\n        v1.z = extract<T>(t1[2]);\n\n        v2.x = extract<T>(t2[0]);\n        v2.y = extract<T>(t2[1]);\n        v2.z = extract<T>(t2[2]);\n        \n        if(IMATH_NAMESPACE::intersect(line, v0, v1, v2, pt, bar, front))\n        {\n            tuple t = make_tuple(pt, bar, front);\n            return t;\n        }\n        else\n        {\n            tuple t;\n            return t;\n        }\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");\n}\n\ntemplate <class T>\nstatic Vec3<T>\nrotatePoint(Line3<T> &line, const Vec3<T> &p, const T &r)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::rotatePoint(p, line, r);\n}\n\ntemplate <class T>\nstatic Vec3<T>\nrotatePointTuple(Line3<T> &line, const tuple &t, const T &r)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> p;\n        p.x = extract<T>(t[0]);\n        p.y = extract<T>(t[1]);\n        p.z = extract<T>(t[2]);\n        \n        return IMATH_NAMESPACE::rotatePoint(p, line, r);\n    }        \n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"Line3 expects tuple of length 3\");      \n}\n\ntemplate <class T>\nstatic std::string Line3_repr(const Line3<T> &v)\n{\n    Vec3<T> v1 = v.pos;\n    Vec3<T> v2 = v.pos + v.dir;\n\n    PyObject *v1Obj = V3<T>::wrap (v1);\n    PyObject *v1ReprObj = PyObject_Repr (v1Obj);\n#if PY_MAJOR_VERSION > 2\n    std::string v1ReprStr = PyUnicode_AsUTF8 (v1ReprObj);\n#else\n    std::string v1ReprStr = PyString_AsString (v1ReprObj);\n#endif\n    Py_DECREF (v1ReprObj);\n    Py_DECREF (v1Obj);\n\n    PyObject *v2Obj = V3<T>::wrap (v2);\n    PyObject *v2ReprObj = PyObject_Repr (v2Obj);\n#if PY_MAJOR_VERSION > 2\n    std::string v2ReprStr = PyUnicode_AsUTF8 (v2ReprObj);\n#else\n    std::string v2ReprStr = PyString_AsString (v2ReprObj);\n#endif\n    Py_DECREF (v2ReprObj);\n    Py_DECREF (v2Obj);\n\n    std::stringstream stream;\n    stream << LineName<T>::value << \"(\" << v1ReprStr << \", \" << v2ReprStr << \")\";\n    return stream.str();\n}\n\ntemplate <class T>\nstatic bool\nequal(const Line3<T> &l1, const Line3<T> &l2)\n{\n    if(l1.pos == l2.pos && l1.dir == l2.dir)\n        return true;\n    else\n        return false;\n}\n\ntemplate <class T>\nstatic bool\nnotequal(const Line3<T> &l1, const Line3<T> &l2)\n{\n    if(l1.pos != l2.pos || l1.dir != l2.dir)\n        return true;\n    else\n        return false;\n}\n\ntemplate <class T>\nclass_<Line3<T> >\nregister_Line()\n{\n    const char *name = LineName<T>::value;\n    \n    class_<Line3<T> > line_class(name);\n    line_class\n        .def(\"__init__\", make_constructor(Line3_construct_default<T>), \"initialize point to (0,0,0) and direction to (1,0,0)\")\n        .def(\"__init__\", make_constructor(Line3_tuple_construct<T>))\n        .def(\"__init__\", make_constructor(Line3_line_construct<T,float>))\n        .def(\"__init__\", make_constructor(Line3_line_construct<T,double>))\n        .def(init<const Vec3<float> &, const Vec3<float> &>(\"Line3(point1, point2) construction\"))\n        .def(init<const Vec3<double> &, const Vec3<double> &>(\"Line3(point1, point2) construction\"))\n        .def(self * Matrix44<T>())\n        .def(\"__eq__\", &equal<T>)\n        .def(\"__ne__\", &notequal<T>)\n        \n        .def_readwrite(\"pos\", &Line3<T>::pos)\n        .def_readwrite(\"dir\", &Line3<T>::dir)\n\n        .def(\"pos\", &getPosition<T>, \n        \"l.pos() -- returns the start point of line l\")\n        \n        .def(\"dir\", &getDirection<T>, \n        \"l.dir() -- returns the direction of line l\\n\")\n        \n        .def(\"setPos\", &setPosition<T>, \n        \"l.setPos(p) -- sets the start point of line l to p\")\n        .def(\"setPos\", &setPositionTuple<T>)\n        \n        .def(\"setDir\", &setDirection<T>, \n        \"l.setDir(d) -- sets the direction of line l\\n\"\n\t\t\"to d.normalized().\\n\")\n        .def(\"setDir\", &setDirectionTuple<T>)\n                                            \n        .def(\"set\", &set1<T>, \n        \"l.set(p1, p2) -- sets the start point\\n\"\n\t\t\"and direction of line l by calling\\n\"\n        \"   l.setPos (p1)\\n\"\n        \"   l.setDir (p2 - p1)\\n\")\n        \n        .def(\"set\", &setTuple<T>)\n        \n        .def(\"pointAt\", &pointAt<T>,\n        \"l.pointAt(t) -- returns l.pos() + t * l.dir()\")\n        \n        .def(\"distanceTo\", &distanceTo1<T>, \n        \"l.distanceTo(p) -- returns the distance from\\n\"\n\t\t\"   line l to point p\\n\")\n                                        \n        .def(\"distanceTo\", &distanceTo2<T>, \n        \"l1.distanceTo(l2) -- returns the distance from\\n\"\n        \"   line l1 to line l2\\n\")\n        \n        .def(\"distanceTo\", &distanceToTuple<T>)\n                                \n        .def(\"closestPointTo\", &closestPointTo1<T>, \n        \"l.closestPointTo(p) -- returns the point on\\n\"\n\t\t\"   line l that is closest to point p\\n\"\n        \"\\n\")\n        \n        .def(\"closestPointTo\", &closestPointToTuple<T>)\n        .def(\"closestPointTo\", &closestPointTo2<T>, \n        \"l1.closestPointTo(l2) -- returns the point on\\n\"\n\t\t\"   line l1 that is closest to line l2\\n\")\n        \n        .def(\"closestPoints\", &closestPoints1<T>, \n        \"l1.closestPoints(l2,p0,p1)\")    \n                                            \n        .def(\"closestPoints\", &closestPoints2<T>, \n        \"l1.closestPoints(l2) -- returns a tuple with\\n\"\n\t\t\"two points:\\n\"\n        \"   (l1.closestPoint(l2), l2.closestPoint(l1)\\n\")\n                                             \n        .def(\"closestTriangleVertex\", &closestVertex<T>, \n        \"l.closestTriangleVertex(v0, v1, v2) -- returns\\n\"\n\t\t\"a copy of v0, v1, or v2, depending on which is\\n\"\n        \"closest to line l.\\n\")\n        \n        .def(\"closestTriangleVertex\", &closestVertexTuple<T>)\n        .def(\"intersectWithTriangle\", &intersect2<T>)                                             \n        .def(\"intersectWithTriangle\", &intersect1<T>, \n            \"l.intersectWithTriangle(v0, v1, v2) -- computes the\\n\"\n\t\t\t\"intersection of line l and triangle (v0, v1, v2).\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"If the line and the triangle do not intersect,\\n\"\n\t\t\t\"None is returned.\\n\"\n\t\t\t\"\"\n\t\t\t\"If the line and the triangle intersect, a tuple\\n\"\n\t\t\t\"(p, b, f) is returned:\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"   p  intersection point in 3D space\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"   b  intersection point in barycentric coordinates\\n\"\n\t\t\t\"\\n\"\n\t\t\t\"   f  1 if the line hits the triangle from the\\n\"\n\t\t\t\"      front (((v2-v1) % (v1-v2)) ^ l.dir() < 0),\\n\"\n\t\t\t\"      0 if the line hits the trianble from the\\n\"\n\t\t\t\"      back\\n\"\n\t\t\t\"\\n\")\n        .def(\"intersectWithTriangle\", &intersectTuple<T>)\n            \n        .def(\"rotatePoint\", &rotatePoint<T>, \n            \"l.rotatePoint(p,r) -- rotates point p around\\n\"\n\t\t\t\"line by angle r (in radians), and returns the\\n\"\n\t\t\t\"result (p is not modified)\\n\")\n        \n        .def(\"rotatePoint\", &rotatePointTuple<T>)\n        .def(\"__repr__\",&Line3_repr<T>)\n        ;\n\n    decoratecopy(line_class);\n\n    return line_class;\n}\n\ntemplate PYIMATH_EXPORT class_<Line3<float> > register_Line<float>();\ntemplate PYIMATH_EXPORT class_<Line3<double> > register_Line<double>();\n\n} // namespace PyImath\n", "meta": {"hexsha": "d52a750acf763667b09d7c0719dc42b001beb088", "size": 16357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathLine.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/PyImathLine.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/PyImathLine.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": 27.4907563025, "max_line_length": 126, "alphanum_fraction": 0.5833588066, "num_tokens": 4873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.02887090736407739, "lm_q1q2_score": 0.009861796311450012}}
{"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\n// This file contains modified code from the following open source projects\n// published under the licenses listed below:\n//\n// Software License Agreement (BSD License)\n//\n//  Point Cloud Library (PCL) - www.pointclouds.org\n//  Copyright (c) 2010-2011, Willow Garage, Inc.\n//  Copyright (c) 2012-, Open Perception, Inc.\n//\n//  All rights reserved.\n//\n//  Redistribution and use in source and binary forms, with or without\n//  modification, are permitted provided that the following conditions\n//  are met:\n//\n//   * Redistributions of source code must retain the above copyright\n//     notice, this list of conditions and the following disclaimer.\n//   * Redistributions in binary form must reproduce the above\n//     copyright notice, this list of conditions and the following\n//     disclaimer in the documentation and/or other materials provided\n//     with the distribution.\n//   * Neither the name of the copyright holder(s) 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#ifndef NDT__NDT_OPTIMIZATION_PROBLEM_HPP_\n#define NDT__NDT_OPTIMIZATION_PROBLEM_HPP_\n\n#include <ndt/ndt_map.hpp>\n#include <ndt/ndt_scan.hpp>\n#include <ndt/ndt_config.hpp>\n#include <optimization/optimization_problem.hpp>\n#include <optimization/utils.hpp>\n#include <ndt/utils.hpp>\n#include <experimental/optional>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <tuple>\n#include \"common/types.hpp\"\n\nusing autoware::common::types::bool8_t;\nusing autoware::common::types::float64_t;\n\nnamespace autoware\n{\nnamespace localization\n{\nnamespace ndt\n{\n\ntemplate<typename ScalarT>\nbool8_t is_valid_probability(ScalarT p)\n{\n  bool8_t ret = true;\n  if (std::isnan(p) || p > ScalarT{1.0} || p < ScalarT{0.0}) {\n    ret = false;\n  }\n  return ret;\n}\n\n/// P2D ndt objective. This class implements the P2D ndt score function, its analytical\n/// jacobian and hessian values.\n/// \\tparam MapT Type of map to be used.\ntemplate<typename MapT>\nclass P2DNDTObjective : public common::optimization::CachedExpression<P2DNDTObjective<MapT>,\n    EigenPose<Real>, 1U, 6U, common::optimization::EigenComparator>\n{\npublic:\n  // getting aliases from the base class.\n  using ExpressionT = common::optimization::CachedExpression<P2DNDTObjective<MapT>,\n      EigenPose<Real>, 1U, 6U, common::optimization::EigenComparator>;\n  using DomainValue = typename ExpressionT::DomainValue;\n  using Value = typename ExpressionT::Value;\n  using Jacobian = typename ExpressionT::Jacobian;\n  using Hessian = typename ExpressionT::Hessian;\n  using Map = MapT;\n  using Scan = P2DNDTScan;\n  using Point = typename Map::Point;\n  using Comparator = common::optimization::EigenComparator;\n  using ComputeMode = common::optimization::ComputeMode;\n  using PointGrad = Eigen::Matrix<float64_t, 3, 6>;\n  using PointHessian = Eigen::Matrix<float64_t, 18, 6>;\n\n  /// Constructor.\n  ///\n  /// It should be noted here that ndt optimization problem does not take ownership of neither the\n  /// scan nor the map but uses the references. Hence an optimization problem must not outlive the\n  /// scan or the map.\n  ///\n  /// @param      scan    Scan to align with the map.\n  /// @param      map     NDT map to be aligned.\n  /// @param      config  Optimization config for this objective.\n  ///\n  P2DNDTObjective(\n    const P2DNDTScan & scan, const Map & map, const P2DNDTOptimizationConfig config)\n  : m_scan_ref(scan), m_map_ref(map)\n  {\n    init(config.outlier_ratio());\n  }\n\n  void evaluate_(const DomainValue & x, const ComputeMode & mode)\n  {\n    // Convert pose vector to transform matrix for easy point transformation\n    Eigen::Transform<float64_t, 3, Eigen::Affine, Eigen::ColMajor> transform;\n    transform.setIdentity();\n    transform_adapters::pose_to_transform(x, transform);\n\n    Value score{0.0};\n\n    Jacobian jacobian;\n    std::experimental::optional<GradientAngleParameters> grad_params;\n\n    Hessian hessian;\n    std::experimental::optional<HessianAngleParameters> hessian_params;\n\n    {\n      // Angle parameters to be used by all elements (eq. 6.12) [Magnusson 2009]\n      const AngleParameters angle_params{x};\n      // Only construct jacobian/hessian variables if they are needed.\n      if (mode.jacobian() || mode.hessian()) {\n        jacobian.setZero();\n        grad_params.emplace(angle_params);\n      }\n      if (mode.hessian()) {\n        hessian.setZero();\n        hessian_params.emplace(angle_params);\n      }\n    }\n\n    for (const auto & pt : m_scan_ref) {\n      PointGrad point_gradient;\n      PointHessian point_hessian;\n\n      if (mode.jacobian() || mode.hessian()) {\n        point_gradient.setZero();\n        point_gradient.block<3, 3>(0, 0).setIdentity();\n        compute_point_gradients(grad_params.value(), pt, point_gradient);\n\n        if (mode.hessian()) {\n          point_hessian.setZero();\n          compute_point_hessians(hessian_params.value(), pt, point_hessian);\n        }\n      }\n\n      const Point pt_trans = transform * pt;\n      const auto & cells = m_map_ref.cell(pt_trans);\n\n      for (const auto & cell : cells) {\n        const Point pt_trans_norm = pt_trans - cell.centroid();\n        // Cell iteration used for compatibility with maps with multi-cell lookup\n        if (cell.usable()) {\n          const auto & inv_cov = cell.inverse_covariance();\n          // e^(-d_2/2 * (x_k - mu_k)^T Sigma_k^-1 (x_k - mu_k)) Equation 6.9 [Magnusson 2009]\n          Real e_x_cov_x = std::exp(\n            -m_gauss_d2 * pt_trans_norm.dot(\n              inv_cov * pt_trans_norm) / 2.0);\n\n          if (mode.score()) {\n            score += -m_gauss_d1 * e_x_cov_x;\n          }\n\n          if (mode.jacobian() || mode.hessian()) {\n            const auto d2_e_x_cov_x = m_gauss_d2 * e_x_cov_x;\n\n            // Error checking for invalid values.\n            // TODO(yunus.caliskan): Can be removed after covariance is checked\n            //  for definiteness #216\n            if (!is_valid_probability(d2_e_x_cov_x)) {\n              continue;\n            }\n\n            // Reusable portion of Equation 6.12 and 6.13 [Magnusson 2009]\n            const auto d1_d2_e_x_cov_x = m_gauss_d1 * d2_e_x_cov_x;\n\n            for (auto i = 0U; i < jacobian.rows(); ++i) {\n              const Point cov_dxd_pi = inv_cov * point_gradient.col(i);\n              if (mode.jacobian()) {\n                jacobian(i) += pt_trans_norm.dot(cov_dxd_pi) * d1_d2_e_x_cov_x;\n              }\n              if (mode.hessian()) {\n                for (auto j = 0U; j < hessian.cols(); ++j) {\n                  hessian(i, j) += d1_d2_e_x_cov_x * (-m_gauss_d2 * pt_trans_norm.dot(cov_dxd_pi) *\n                    pt_trans_norm.dot(inv_cov * point_gradient.col(j)) +\n                    pt_trans_norm.dot(inv_cov * point_hessian.block<3, 1>(3 * i, j)) +\n                    point_gradient.col(j).dot(cov_dxd_pi));\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n    if (mode.score()) {\n      this->set_score(score);\n    }\n    if (mode.jacobian()) {\n      this->set_jacobian(jacobian);\n    }\n    if (mode.hessian()) {\n      this->set_hessian(hessian);\n    }\n  }\n\nprivate:\n  /// Struct encapculating the intermediate parameters used in (eq. 6.17) [Magnusson 2009]\n  struct AngleParameters\n  {\npublic:\n    static constexpr auto approx_thresh{10e-5};\n    AngleParameters() = delete;\n    explicit AngleParameters(const DomainValue & pose)\n    {\n      if (std::fabs(pose(3)) < approx_thresh) {\n        cx = 1.0;\n        sx = 0.0;\n      } else {\n        cx = std::cos(pose(3));\n        sx = std::sin(pose(3));\n      }\n\n      if (std::fabs(pose(4)) < approx_thresh) {\n        cy = 1.0;\n        sy = 0.0;\n      } else {\n        cy = std::cos(pose(4));\n        sy = std::sin(pose(4));\n      }\n\n      if (std::fabs(pose(5)) < approx_thresh) {\n        cz = 1.0;\n        sz = 0.0;\n      } else {\n        cz = std::cos(pose(5));\n        sz = std::sin(pose(5));\n      }\n    }\n\n    Real cx{0.0};\n    Real cy{0.0};\n    Real cz{0.0};\n    Real sx{1.0};\n    Real sy{1.0};\n    Real sz{1.0};\n  };\n\n  /// Struct encapculating the intermediate parameters used in (eq. 6.19) [Magnusson 2009]\n  struct GradientAngleParameters\n  {\npublic:\n    GradientAngleParameters() = delete;\n    explicit GradientAngleParameters(const AngleParameters & params)\n    {\n      j_ang_a(0) = -params.sx * params.sz + params.cx * params.sy * params.cz;\n      j_ang_a(1) = -params.sx * params.cz - params.cx * params.sy * params.sz;\n      j_ang_a(2) = -params.cx * params.cy;\n\n      j_ang_b(0) = params.cx * params.sz + params.sx * params.sy * params.cz;\n      j_ang_b(1) = params.cx * params.cz - params.sx * params.sy * params.sz;\n      j_ang_b(2) = -params.sx * params.cy;\n\n      j_ang_c(0) = -params.sy * params.cz;\n      j_ang_c(1) = params.sy * params.sz;\n      j_ang_c(2) = params.cy;\n\n      j_ang_d(0) = params.sx * params.cy * params.cz;\n      j_ang_d(1) = -params.sx * params.cy * params.sz;\n      j_ang_d(2) = params.sx * params.sy;\n\n      j_ang_e(0) = -params.cx * params.cy * params.cz;\n      j_ang_e(1) = params.cx * params.cy * params.sz;\n      j_ang_e(2) = -params.cx * params.sy;\n\n      j_ang_f(0) = -params.cy * params.sz;\n      j_ang_f(1) = -params.cy * params.cz;\n      j_ang_f(2) = 0.0;\n\n      j_ang_g(0) = params.cx * params.cz - params.sx * params.sy * params.sz;\n      j_ang_g(1) = -params.cx * params.sz - params.sx * params.sy * params.cz;\n      j_ang_g(2) = 0.0;\n\n      j_ang_h(0) = params.sx * params.cz + params.cx * params.sy * params.sz;\n      j_ang_h(1) = params.cx * params.sy * params.cz - params.sx * params.sz;\n      j_ang_h(2) = 0.0;\n    }\n\n    Point j_ang_a, j_ang_b, j_ang_c, j_ang_d, j_ang_e, j_ang_f, j_ang_g, j_ang_h;\n  };\n\n  /// Struct encapculating the intermediate parameters used in (eq. 6.21) [Magnusson 2009]\n  struct HessianAngleParameters\n  {\npublic:\n    HessianAngleParameters() = delete;\n    explicit HessianAngleParameters(const AngleParameters & params)\n    {\n      h_ang_a2(0) = -params.cx * params.sz - params.sx * params.sy * params.cz;\n      h_ang_a2(1) = -params.cx * params.cz + params.sx * params.sy * params.sz;\n      h_ang_a2(2) = params.sx * params.cy;\n\n      h_ang_a3(0) = -params.sx * params.sz + params.cx * params.sy * params.cz;\n      h_ang_a3(1) = -params.cx * params.sy * params.sz - params.sx * params.cz;\n      h_ang_a3(2) = -params.cx * params.cy;\n\n      h_ang_b2(0) = params.cx * params.cy * params.cz;\n      h_ang_b2(1) = -params.cx * params.cy * params.sz;\n      h_ang_b2(2) = params.cx * params.sy;\n\n      h_ang_b3(0) = params.sx * params.cy * params.cz;\n      h_ang_b3(1) = -params.sx * params.cy * params.sz;\n      h_ang_b3(2) = params.sx * params.sy;\n\n      h_ang_c2(0) = -params.sx * params.cz - params.cx * params.sy * params.sz;\n      h_ang_c2(1) = params.sx * params.sz - params.cx * params.sy * params.cz;\n      h_ang_c2(2) = 0.0;\n\n      h_ang_c3(0) = params.cx * params.cz - params.sx * params.sy * params.sz;\n      h_ang_c3(1) = -params.sx * params.sy * params.cz - params.cx * params.sz;\n      h_ang_c3(2) = 0.0;\n\n      h_ang_d1(0) = -params.cy * params.cz;\n      h_ang_d1(1) = params.cy * params.sz;\n      h_ang_d1(2) = params.sy;\n\n      h_ang_d2(0) = -params.sx * params.sy * params.cz;\n      h_ang_d2(1) = params.sx * params.sy * params.sz;\n      h_ang_d2(2) = params.sx * params.cy;\n\n      h_ang_d3(0) = params.cx * params.sy * params.cz;\n      h_ang_d3(1) = -params.cx * params.sy * params.sz;\n      h_ang_d3(2) = -params.cx * params.cy;\n\n      h_ang_e1(0) = params.sy * params.sz;\n      h_ang_e1(1) = params.sy * params.cz;\n      h_ang_e1(2) = 0.0;\n\n      h_ang_e2(0) = -params.sx * params.cy * params.sz;\n      h_ang_e2(1) = -params.sx * params.cy * params.cz;\n      h_ang_e2(2) = 0.0;\n\n      h_ang_e3(0) = params.cx * params.cy * params.sz;\n      h_ang_e3(1) = params.cx * params.cy * params.cz;\n      h_ang_e3(2) = 0.0;\n\n      h_ang_f1(0) = -params.cy * params.cz;\n      h_ang_f1(1) = params.cy * params.sz;\n      h_ang_f1(2) = 0.0;\n\n      h_ang_f2(0) = -params.cx * params.sz - params.sx * params.sy * params.cz;\n      h_ang_f2(1) = -params.cx * params.cz + params.sx * params.sy * params.sz;\n      h_ang_f2(2) = 0.0;\n\n      h_ang_f3(0) = -params.sx * params.sz + params.cx * params.sy * params.cz;\n      h_ang_f3(1) = -params.cx * params.sy * params.sz - params.sx * params.cz;\n      h_ang_f3(2) = 0.0;\n    }\n\n    Point h_ang_a2, h_ang_a3,\n      h_ang_b2, h_ang_b3,\n      h_ang_c2, h_ang_c3,\n      h_ang_d1, h_ang_d2, h_ang_d3,\n      h_ang_e1, h_ang_e2, h_ang_e3,\n      h_ang_f1, h_ang_f2, h_ang_f3;\n  };\n\n  void compute_point_gradients(\n    const GradientAngleParameters & params,\n    const Point & x,\n    PointGrad & point_gradient)\n  {\n    point_gradient(1, 3) = x.dot(params.j_ang_a);\n    point_gradient(2, 3) = x.dot(params.j_ang_b);\n    point_gradient(0, 4) = x.dot(params.j_ang_c);\n    point_gradient(1, 4) = x.dot(params.j_ang_d);\n    point_gradient(2, 4) = x.dot(params.j_ang_e);\n    point_gradient(0, 5) = x.dot(params.j_ang_f);\n    point_gradient(1, 5) = x.dot(params.j_ang_g);\n    point_gradient(2, 5) = x.dot(params.j_ang_h);\n  }\n\n  void compute_point_hessians(\n    const HessianAngleParameters & params,\n    const Point & x,\n    PointHessian & point_hessian)\n  {\n    const Point a{0.0, x.dot(params.h_ang_a2), x.dot(params.h_ang_a3)};\n    const Point b{0.0, x.dot(params.h_ang_b2), x.dot(params.h_ang_b3)};\n    const Point c{0.0, x.dot(params.h_ang_c2), x.dot(params.h_ang_c3)};\n    const Point d{x.dot(params.h_ang_d1), x.dot(params.h_ang_d2),\n      x.dot(params.h_ang_d3)};\n    const Point e{x.dot(params.h_ang_e1), x.dot(params.h_ang_e2),\n      x.dot(params.h_ang_e3)};\n    const Point f{x.dot(params.h_ang_f1), x.dot(params.h_ang_f2),\n      x.dot(params.h_ang_f3)};\n\n    point_hessian.block<3, 1>(9, 3) = a;\n    point_hessian.block<3, 1>(12, 3) = b;\n    point_hessian.block<3, 1>(15, 3) = c;\n    point_hessian.block<3, 1>(9, 4) = b;\n    point_hessian.block<3, 1>(12, 4) = d;\n    point_hessian.block<3, 1>(15, 4) = e;\n    point_hessian.block<3, 1>(9, 5) = c;\n    point_hessian.block<3, 1>(12, 5) = e;\n    point_hessian.block<3, 1>(15, 5) = f;\n  }\n\n  /// Initializes the guassian fitting parameters (eq. 6.8) [Magnusson 2009]\n  /// \\param outlier_ratio Outlier ratio to be used in the gaussian distribution variation\n  /// used in (eq. 6.7) [Magnusson 2009]\n  void init(Real outlier_ratio)\n  {\n    if (!is_valid_probability(outlier_ratio)) {\n      throw std::domain_error(\"Outlier ratio must be between 0 and 1\");\n    }\n    const auto c_size = m_map_ref.cell_size();\n    // The gaussian fitting parameters below are taken from the PCL implementation.\n    // 10.0 seems to be a magic number. For details on the gaussian\n    // approximation of the mixture probability in see [Biber et al, 2004] and [Magnusson 2009].\n    const auto gauss_c1 = 10.0 * (1.0 - outlier_ratio);\n    const auto gauss_c2 = outlier_ratio / static_cast<Real>(c_size.x * c_size.y * c_size.z);\n    const auto gauss_d3 = -std::log(gauss_c2);\n    m_gauss_d1 = -std::log(gauss_c1 + gauss_c2) - gauss_d3;\n    m_gauss_d2 = -2 *\n      std::log((-std::log(gauss_c1 * std::exp(-0.5) + gauss_c2) - gauss_d3) / m_gauss_d1);\n  }\n\n  // references as class members to be initialized at constructor.\n  const Scan & m_scan_ref;\n  const Map & m_map_ref;\n  // States:\n  Real m_gauss_d1{0.0};\n  Real m_gauss_d2{0.0};\n};\n\ntemplate<typename MapT>\nusing P2DNDTOptimizationProblem =\n  common::optimization::UnconstrainedOptimizationProblem<P2DNDTObjective<MapT>, EigenPose<Real>,\n    6U>;\n}  // namespace ndt\n}  // namespace localization\n}  // namespace autoware\n\n#endif  // NDT__NDT_OPTIMIZATION_PROBLEM_HPP_\n", "meta": {"hexsha": "12facb08a14eade8cad87e084a43822f39974e1b", "size": 17062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/localization/ndt/include/ndt/ndt_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/localization/ndt/include/ndt/ndt_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/localization/ndt/include/ndt/ndt_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": 36.0718816068, "max_line_length": 99, "alphanum_fraction": 0.6438870004, "num_tokens": 4954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.0244230876131795, "lm_q1q2_score": 0.009856348626554249}}
{"text": "#include \"StereoSlic.h\"\n#include <cmath>\n#include <float.h>\n#include <exception>\n#include <Eigen/Dense>\n\n// Default parameter\nconst int STEREOSLIC_DEFAULT_ITERATION_TOTAL = 10;\nconst double STEREOSLIC_DEFAULT_COLOR_WEIGHT = 3000.0;\nconst double STEREOSLIC_DEFAULT_DISPARITY_WEIGHT = 30.0;\nconst double STEREOSLIC_DEFAULT_NO_DISPARITY_PENALTY = 3.0;\n\n// Pixel offsets of 4- and 8-neighbors\nconst int fourNeighborTotal = 4;\nconst int fourNeighborOffsetX[4] = {-1, 0, 1, 0};\nconst int fourNeighborOffsetY[4] = { 0,-1, 0, 1};\nconst int eightNeighborTotal = 8;\nconst int eightNeighborOffsetX[8] = {-1,-1, 0, 1, 1, 1, 0,-1};\nconst int eightNeighborOffsetY[8] = { 0,-1,-1,-1, 0, 1, 1, 1};\n\n// Prototype declaration\nint computeRequiredSamplingTotal(const int drawTotal, const int inlierTotal, const int pointTotal,\n                                 const int currentSamplingTotal, const double confidenceLevel);\n\n\nStereoSlic::StereoSlic() : iterationTotal_(STEREOSLIC_DEFAULT_ITERATION_TOTAL),\n                           colorWeight_(STEREOSLIC_DEFAULT_COLOR_WEIGHT),\n                           disparityWeight_(STEREOSLIC_DEFAULT_DISPARITY_WEIGHT),\n                           noDisparityPenalty_(STEREOSLIC_DEFAULT_NO_DISPARITY_PENALTY) {}\n\nvoid StereoSlic::setIterationTotal(const int iterationTotal) {\n    if (iterationTotal < 1) {\n        throw std::runtime_error(\"StereoSlic: the number of iterations is less than 1\");\n    }\n    \n    iterationTotal_ = iterationTotal;\n}\n\nvoid StereoSlic::setEnergyParameter(const double colorWeight, const double disparityWeight, const double noDisparityPenalty) {\n    if (colorWeight <= 0 || disparityWeight < 0 || noDisparityPenalty < 0) {\n        throw std::runtime_error(\"StereoSlic: energy parameter is less than zero\");\n    }\n    \n    colorWeight_ = colorWeight;\n    disparityWeight_ = disparityWeight;\n    noDisparityPenalty_ = noDisparityPenalty;\n}\n\nvoid StereoSlic::segment(const int superpixelTotal,\n                         const png::image<png::rgb_pixel>& leftImage,\n                         png::image<png::gray_pixel_16>& segmentImage)\n{\n    energyType_ = 0;   // Color(left)\n    setColorImage(leftImage);\n    performSegmentation(superpixelTotal);\n    makeSegmentImage(segmentImage);\n}\n\nvoid StereoSlic::segment(const int superpixelTotal,\n                         const png::image<png::rgb_pixel>& leftImage,\n                         const png::image<png::gray_pixel_16>& leftDisparityImage,\n                         png::image<png::gray_pixel_16>& segmentImage,\n                         png::image<png::gray_pixel_16>& disparityImage)\n{\n    energyType_ = 1;   // Color(left) + Disparity(left)\n    setColorImage(leftImage);\n    setDisparityImage(leftDisparityImage);\n    performSegmentation(superpixelTotal);\n    makeSegmentImage(segmentImage);\n    makeDisparityImage(disparityImage);\n}\n\nvoid StereoSlic::segment(const int superpixelTotal,\n                         const png::image<png::rgb_pixel>& leftImage,\n                         const png::image<png::gray_pixel_16>& leftDisparityImage,\n                         const png::image<png::gray_pixel_16>& rightDisparityImage,\n                         png::image<png::gray_pixel_16>& segmentImage,\n                         png::image<png::gray_pixel_16>& disparityImage)\n{\n    energyType_ = 2;   // Color(left) + Disparity(left/right)\n    setColorImage(leftImage);\n    setDisparityImage(leftDisparityImage, rightDisparityImage);\n    performSegmentation(superpixelTotal);\n    makeSegmentImage(segmentImage);\n    makeDisparityImage(disparityImage);\n}\n\nvoid StereoSlic::segment(const int superpixelTotal,\n                         const png::image<png::rgb_pixel>& leftImage,\n                         const png::image<png::gray_pixel_16>& leftDisparityImage,\n                         const png::image<png::gray_pixel_16>& rightDisparityImage,\n                         const png::image<png::rgb_pixel>& rightImage,\n                         png::image<png::gray_pixel_16>& segmentImage,\n                         png::image<png::gray_pixel_16>& disparityImage)\n{\n    energyType_ = 3;   // Color(left/right) + Disparity(left/right)\n    setColorImage(leftImage, rightImage);\n    setDisparityImage(leftDisparityImage, rightDisparityImage);\n    performSegmentation(superpixelTotal);\n    makeSegmentImage(segmentImage);\n    makeDisparityImage(disparityImage);\n}\n\n\nvoid StereoSlic::setColorImage(const png::image<png::rgb_pixel>& leftImage) {\n    width_ = static_cast<int>(leftImage.get_width());\n    height_ = static_cast<int>(leftImage.get_height());\n    \n    convertRGBToLab(leftImage, leftLabImage_);\n    calcLeftLabEdges();\n}\n\nvoid StereoSlic::setColorImage(const png::image<png::rgb_pixel>& leftImage,\n                               const png::image<png::rgb_pixel>& rightImage)\n{\n    width_ = static_cast<int>(leftImage.get_width());\n    height_ = static_cast<int>(leftImage.get_height());\n    \n    convertRGBToLab(leftImage, leftLabImage_);\n    calcLeftLabEdges();\n    convertRGBToLab(rightImage, rightLabImage_);\n}\n\nvoid StereoSlic::setDisparityImage(const png::image<png::gray_pixel_16>& leftDisparityImage) {\n    leftDisparityImage_.resize(width_*height_);\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            unsigned short pixelValue = leftDisparityImage[y][x];\n            if (pixelValue == 0) leftDisparityImage_[width_*y + x] = -1.0;\n            else leftDisparityImage_[width_*y + x] = static_cast<float>(pixelValue)/256.0f;\n        }\n    }\n}\n\nvoid StereoSlic::setDisparityImage(const png::image<png::gray_pixel_16>& leftDisparityImage,\n                                   const png::image<png::gray_pixel_16>& rightDisparityImage)\n{\n    leftDisparityImage_.resize(width_*height_);\n    rightDisparityImage_.resize(width_*height_);\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            unsigned short leftPixelValue = leftDisparityImage[y][x];\n            if (leftPixelValue == 0) leftDisparityImage_[width_*y + x] = -1.0;\n            else leftDisparityImage_[width_*y + x] = static_cast<float>(leftPixelValue)/256.0f;\n\n            unsigned short rightPixelValue = rightDisparityImage[y][x];\n            if (rightPixelValue == 0) rightDisparityImage_[width_*y + x] = -1.0;\n            else rightDisparityImage_[width_*y + x] = static_cast<float>(rightPixelValue)/256.0f;\n        }\n    }\n}\n\nvoid StereoSlic::performSegmentation(const int superpixelTotal) {\n    initializeSeeds(superpixelTotal);\n    \n    for (int iterationCount = 0; iterationCount < iterationTotal_; ++iterationCount) {\n        assignLabel();\n        updateSeeds();\n    }\n    enforceLabelConnectivity();\n}\n\nvoid StereoSlic::makeSegmentImage(png::image<png::gray_pixel_16>& segmentImage) const {\n    segmentImage.resize(width_, height_);\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            segmentImage[y][x] = labels_[width_*y + x];\n        }\n    }\n}\n\nvoid StereoSlic::makeDisparityImage(png::image<png::gray_pixel_16>& disparityImage) {\n    estimateDisparityPlaneParameter();\n\n    disparityImage.resize(width_, height_);\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            int seedIndex = labels_[width_*y + x];\n            double estimatedDisparity = seeds_[seedIndex].disparityPlane[0]*x + seeds_[seedIndex].disparityPlane[1]*y + seeds_[seedIndex].disparityPlane[2];\n            if (estimatedDisparity > 0 && estimatedDisparity < 256.0) disparityImage[y][x] = static_cast<unsigned short>(estimatedDisparity*256.0 + 0.5);\n            else if (estimatedDisparity >= 256.0) disparityImage[y][x] = 65535;\n            else disparityImage[y][x] = 0;\n        }\n    }\n}\n\nvoid StereoSlic::convertRGBToLab(const png::image<png::rgb_pixel>& rgbImage,\n                                 std::vector<float>& labImage)\n{\n    const int RGB2LABCONVERTER_XYZ_TABLE_SIZE = 1024;\n    // CIE standard parameters\n    const double epsilon = 0.008856;\n    const double kappa = 903.3;\n    // Reference white\n    const double referenceWhite[3] = {0.950456, 1.0, 1.088754};\n    /// Maximum values\n    const double maxXYZValues[3] = {0.95047, 1.0, 1.08883};\n\n    std::vector<float> sRGBGammaCorrections(256);\n    for (int pixelValue = 0; pixelValue < 256; ++pixelValue) {\n        double normalizedValue = pixelValue/255.0;\n        double transformedValue = (normalizedValue <= 0.04045) ? normalizedValue/12.92 : pow((normalizedValue+0.055)/1.055, 2.4);\n        \n        sRGBGammaCorrections[pixelValue] = transformedValue;\n    }\n    \n    int tableSize = RGB2LABCONVERTER_XYZ_TABLE_SIZE;\n    std::vector<double> xyzTableIndexCoefficients(3);\n    xyzTableIndexCoefficients[0] = (tableSize-1)/maxXYZValues[0];\n    xyzTableIndexCoefficients[1] = (tableSize-1)/maxXYZValues[1];\n    xyzTableIndexCoefficients[2] = (tableSize-1)/maxXYZValues[2];\n    \n    std::vector< std::vector<float> > fXYZConversions(3);\n    for (int xyzIndex = 0; xyzIndex < 3; ++xyzIndex) {\n        fXYZConversions[xyzIndex].resize(tableSize);\n        double stepValue = maxXYZValues[xyzIndex]/tableSize;\n        for (int tableIndex = 0; tableIndex < tableSize; ++tableIndex) {\n            double originalValue = stepValue*tableIndex;\n            double normalizedValue = originalValue/referenceWhite[xyzIndex];\n            double transformedValue = (normalizedValue > epsilon) ? pow(normalizedValue, 1.0/3.0) : (kappa*normalizedValue + 16.0)/116.0;\n            \n            fXYZConversions[xyzIndex][tableIndex] = transformedValue;\n        }\n    }\n    \n    labImage.resize(width_*height_*3);\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            png::rgb_pixel rgbColor = rgbImage[y][x];\n            \n            float correctedR = sRGBGammaCorrections[rgbColor.red];\n            float correctedG = sRGBGammaCorrections[rgbColor.green];\n            float correctedB = sRGBGammaCorrections[rgbColor.blue];\n            \n            float xyzColor[3];\n            xyzColor[0] = correctedR*0.4124564f + correctedG*0.3575761f + correctedB*0.1804375f;\n            xyzColor[1] = correctedR*0.2126729f + correctedG*0.7151522f + correctedB*0.0721750f;\n            xyzColor[2] = correctedR*0.0193339f + correctedG*0.1191920f + correctedB*0.9503041f;\n            \n            int tableIndexX = static_cast<int>(xyzColor[0]*xyzTableIndexCoefficients[0] + 0.5);\n            int tableIndexY = static_cast<int>(xyzColor[1]*xyzTableIndexCoefficients[1] + 0.5);\n            int tableIndexZ = static_cast<int>(xyzColor[2]*xyzTableIndexCoefficients[2] + 0.5);\n            \n            float fX = fXYZConversions[0][tableIndexX];\n            float fY = fXYZConversions[1][tableIndexY];\n            float fZ = fXYZConversions[2][tableIndexZ];\n            \n            labImage[width_*3*y + 3*x] = 116.0*fY - 16.0;\n            labImage[width_*3*y + 3*x + 1] = 500.0*(fX - fY);\n            labImage[width_*3*y + 3*x + 2] = 200.0*(fY - fZ);\n        }\n    }\n}\n\nvoid StereoSlic::calcLeftLabEdges() {\n    leftLabEdges_.resize(width_*height_, 0);\n    for (int y = 1; y < height_-1; ++y) {\n        for (int x = 1; x < width_-1; ++x) {\n            double dxL = leftLabImage_[width_*3*y + 3*(x-1)] - leftLabImage_[width_*3*y + 3*(x+1)];\n            double dxA = leftLabImage_[width_*3*y + 3*(x-1) + 1] - leftLabImage_[width_*3*y + 3*(x+1) + 1];\n            double dxB = leftLabImage_[width_*3*y + 3*(x-1) + 2] - leftLabImage_[width_*3*y + 3*(x+1) + 2];\n            double dx = dxL*dxL + dxA*dxA + dxB*dxB;\n            \n            double dyL = leftLabImage_[width_*3*(y-1) + 3*x] - leftLabImage_[width_*3*(y+1) + 3*x];\n            double dyA = leftLabImage_[width_*3*(y-1) + 3*x + 1] - leftLabImage_[width_*3*(y+1) + 3*x + 1];\n            double dyB = leftLabImage_[width_*3*(y-1) + 3*x + 2] - leftLabImage_[width_*3*(y+1) + 3*x + 2];\n            double dy = dyL*dyL + dyA*dyA + dyB*dyB;\n            \n            leftLabEdges_[width_*y + x] = dx + dy;\n        }\n    }\n}\n\nvoid StereoSlic::initializeSeeds(const int superpixelTotal) {\n    int imageSize = width_*height_;\n    gridSize_ = sqrt(static_cast<double>(imageSize)/superpixelTotal);\n    stepSize_ = static_cast<int>(gridSize_ + 2.0);\n    int offsetX = static_cast<int>(gridSize_/2.0);\n    int offsetY = static_cast<int>(gridSize_/2.0);\n    \n    seeds_.clear();\n    for (int indexY = 0; indexY < height_; ++indexY) {\n        int y = static_cast<int>(gridSize_*indexY + offsetY + 0.5);\n        if (y >= height_) break;\n        for (int indexX = 0; indexX < width_; ++indexX) {\n            int x = static_cast<int>(gridSize_*indexX + offsetX + 0.5);\n            if (x >= width_) break;\n            \n            LabXYD newSeed;\n            newSeed.color[0] = leftLabImage_[width_*3*y + 3*x];\n            newSeed.color[1] = leftLabImage_[width_*3*y + 3*x + 1];\n            newSeed.color[2] = leftLabImage_[width_*3*y + 3*x + 2];\n            newSeed.position[0] = x;\n            newSeed.position[1] = y;\n            seeds_.push_back(newSeed);\n        }\n    }\n    \n    int seedTotal = static_cast<int>(seeds_.size());\n    for (int seedIndex = 0; seedIndex < seedTotal; ++seedIndex) {\n        int originalX = seeds_[seedIndex].position[0];\n        int originalY = seeds_[seedIndex].position[1];\n        int originalPixelIndex = width_*originalY + originalX;\n        \n        int perturbedPixelIndex = originalPixelIndex;\n        for (int neighborIndex = 0; neighborIndex < eightNeighborTotal; ++neighborIndex) {\n            int neighborX = originalX + eightNeighborOffsetX[neighborIndex];\n            int neighborY = originalY + eightNeighborOffsetY[neighborIndex];\n            if (neighborX < 0 || neighborX >= width_ || neighborY < 0 || neighborY >= height_) continue;\n            int neighborPixelIndex = width_*neighborY + neighborX;\n            \n            if (leftLabEdges_[neighborPixelIndex] < leftLabEdges_[perturbedPixelIndex]) {\n                perturbedPixelIndex = neighborPixelIndex;\n            }\n        }\n        \n        if (perturbedPixelIndex != originalPixelIndex) {\n            int perturbedX = perturbedPixelIndex%width_;\n            int perturbedY = perturbedPixelIndex/width_;\n            \n            seeds_[seedIndex].color[0] = leftLabImage_[width_*3*perturbedY + 3*perturbedX];\n            seeds_[seedIndex].color[1] = leftLabImage_[width_*3*perturbedY + 3*perturbedX + 1];\n            seeds_[seedIndex].color[2] = leftLabImage_[width_*3*perturbedY + 3*perturbedX + 2];\n            seeds_[seedIndex].position[0] = perturbedX;\n            seeds_[seedIndex].position[1] = perturbedY;\n        }\n    }\n}\n\nvoid StereoSlic::assignLabel() {\n    int seedTotal = static_cast<int>(seeds_.size());\n    \n    double positionWeight = colorWeight_/(stepSize_*stepSize_);\n    \n    labels_.resize(width_*height_, -1);\n    std::vector<double> distancesToSeeds(width_*height_, DBL_MAX);\n    for (int seedIndex = 0; seedIndex < seedTotal; ++seedIndex) {\n        int minX = (seeds_[seedIndex].position[0] > stepSize_) ? seeds_[seedIndex].position[0] - stepSize_ : 0;\n        int maxX = (seeds_[seedIndex].position[0] < width_ - stepSize_) ? seeds_[seedIndex].position[0] + stepSize_ : width_;\n        int minY = (seeds_[seedIndex].position[1] > stepSize_) ? seeds_[seedIndex].position[1] - stepSize_ : 0;\n        int maxY = (seeds_[seedIndex].position[1] < height_ - stepSize_) ? seeds_[seedIndex].position[1] + stepSize_ : height_;\n        \n        double seedL = seeds_[seedIndex].color[0];\n        double seedA = seeds_[seedIndex].color[1];\n        double seedB = seeds_[seedIndex].color[2];\n        double seedX = seeds_[seedIndex].position[0];\n        double seedY = seeds_[seedIndex].position[1];\n        double seedAlpha = seeds_[seedIndex].disparityPlane[0];\n        double seedBeta = seeds_[seedIndex].disparityPlane[1];\n        double seedGamma = seeds_[seedIndex].disparityPlane[2];\n        \n        for (int y = minY; y < maxY; ++y) {\n            for (int x = minX; x < maxX; ++x) {\n                float leftPixelL = leftLabImage_[width_*3*y + 3*x];\n                float leftPixelA = leftLabImage_[width_*3*y + 3*x + 1];\n                float leftPixelB = leftLabImage_[width_*3*y + 3*x + 2];\n                double distanceLeftLab = (leftPixelL - seedL)*(leftPixelL - seedL)\n                    + (leftPixelA - seedA)*(leftPixelA - seedA)\n                    + (leftPixelB - seedB)*(leftPixelB - seedB);\n                double distanceXY = (x - seedX)*(x - seedX) + (y - seedY)*(y - seedY);\n                \n                // Default distances\n                double distanceRightLab = distanceLeftLab;\n                double distanceLeftD = noDisparityPenalty_;\n                double distanceRightD = noDisparityPenalty_;\n                \n                if (energyType_ > 0) {\n                    double estimatedDisparity = seedAlpha*x + seedBeta*y + seedGamma;\n                    if (estimatedDisparity > 0) {\n                        if (leftDisparityImage_[width_*y + x] > 0) {\n                            // distance of left disparities\n                            double leftDisparityDifference = leftDisparityImage_[width_*y + x] - estimatedDisparity;\n                            distanceLeftD = leftDisparityDifference*leftDisparityDifference;\n                        }\n                        \n                        if (energyType_ > 1) {\n                            int rightX = static_cast<int>(x - estimatedDisparity + 0.5);\n                            if (rightX >= 0 && rightDisparityImage_[width_*y + rightX] > 0) {\n                                double rightDisparityDifference = estimatedDisparity - rightDisparityImage_[width_*y + rightX];\n                                if (rightDisparityDifference < -1) {\n                                    // Occluded\n                                    rightDisparityDifference = 0;\n                                    distanceRightLab = distanceLeftLab;\n                                } else {\n                                    // Non-occluded\n                                    distanceRightD = rightDisparityDifference*rightDisparityDifference;\n                                    if (energyType_ > 2) {\n                                        float rightPixelL = rightLabImage_[width_*3*y + 3*rightX];\n                                        float rightPixelA = rightLabImage_[width_*3*y + 3*rightX + 1];\n                                        float rightPixelB = rightLabImage_[width_*3*y + 3*rightX + 2];\n                                        distanceRightLab = (rightPixelL - seedL)*(rightPixelL - seedL)\n                                            + (rightPixelA - seedA)*(rightPixelA - seedA)\n                                            + (rightPixelB - seedB)*(rightPixelB - seedB);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n                \n                double distanceLab = distanceLeftLab;\n                if (energyType_ == 3) distanceLab += distanceRightLab;\n                double distanceD = 0;\n                if (energyType_ > 0) distanceD = distanceLeftD;\n                if (energyType_ > 1) distanceD += distanceRightD;\n                \n                double distanceLabXYD = distanceLab + positionWeight*distanceXY + disparityWeight_*distanceD;\n                if (distanceLabXYD < distancesToSeeds[width_*y + x]) {\n                    distancesToSeeds[width_*y + x] = distanceLabXYD;\n                    labels_[width_*y + x] = seedIndex;\n                }\n            }\n        }\n    }\n}\n\nvoid StereoSlic::updateSeeds() {\n    updateSeedsColorAndPosition();\n    if (energyType_ > 0) {\n        estimateDisparityPlaneParameter();\n    }\n}\n\nvoid StereoSlic::updateSeedsColorAndPosition() {\n    int seedTotal = static_cast<int>(seeds_.size());\n    \n    std::vector<int> segmentSizes(seedTotal, 0);\n    std::vector<LabXYD> segmentSigmas(seedTotal);\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            int pixelSeedIndex = labels_[width_*y + x];\n            if (pixelSeedIndex >= 0) {\n                segmentSigmas[pixelSeedIndex].color[0] += leftLabImage_[width_*3*y + 3*x];\n                segmentSigmas[pixelSeedIndex].color[1] += leftLabImage_[width_*3*y + 3*x + 1];\n                segmentSigmas[pixelSeedIndex].color[2] += leftLabImage_[width_*3*y + 3*x + 2];\n                segmentSigmas[pixelSeedIndex].position[0] += x;\n                segmentSigmas[pixelSeedIndex].position[1] += y;\n                ++segmentSizes[pixelSeedIndex];\n            }\n        }\n    }\n    \n    for (int seedIndex = 0; seedIndex < seedTotal; ++seedIndex) {\n        double segmentSizeInverse = 1.0;\n        if (segmentSizes[seedIndex] > 0) segmentSizeInverse = 1.0/segmentSizes[seedIndex];\n        \n        seeds_[seedIndex].color[0] = segmentSigmas[seedIndex].color[0]*segmentSizeInverse;\n        seeds_[seedIndex].color[1] = segmentSigmas[seedIndex].color[1]*segmentSizeInverse;\n        seeds_[seedIndex].color[2] = segmentSigmas[seedIndex].color[2]*segmentSizeInverse;\n        seeds_[seedIndex].position[0] = segmentSigmas[seedIndex].position[0]*segmentSizeInverse;\n        seeds_[seedIndex].position[1] = segmentSigmas[seedIndex].position[1]*segmentSizeInverse;\n    }\n}\n\nvoid StereoSlic::estimateDisparityPlaneParameter() {\n    std::vector< std::vector<DisparityPixel> > segmentDisparityPixels = makeDisparityPixelList();\n    int seedTotal = static_cast<int>(segmentDisparityPixels.size());\n    \n    for (int seedIndex = 0; seedIndex < seedTotal; ++seedIndex) {\n        std::vector<double> planeParameter = estimateDisparityPlaneParameter(segmentDisparityPixels[seedIndex]);\n        \n        seeds_[seedIndex].disparityPlane[0] = planeParameter[0];\n        seeds_[seedIndex].disparityPlane[1] = planeParameter[1];\n        seeds_[seedIndex].disparityPlane[2] = planeParameter[2];\n    }\n}\n\nstd::vector< std::vector<StereoSlic::DisparityPixel> > StereoSlic::makeDisparityPixelList() const {\n    int seedTotal = static_cast<int>(seeds_.size());\n    \n    std::vector< std::vector<DisparityPixel> > segmentDisparityPixels(seedTotal);\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            if (leftDisparityImage_[width_*y + x] > 0) {\n                int pixelSeedIndex = labels_[width_*y + x];\n                if (pixelSeedIndex >= 0) {\n                    DisparityPixel newDisparityPixel;\n                    newDisparityPixel.x = x;\n                    newDisparityPixel.y = y;\n                    newDisparityPixel.d = leftDisparityImage_[width_*y + x];\n                    segmentDisparityPixels[pixelSeedIndex].push_back(newDisparityPixel);\n                }\n            }\n        }\n    }\n    \n    return segmentDisparityPixels;\n}\n\nstd::vector<double> StereoSlic::estimateDisparityPlaneParameter(const std::vector<DisparityPixel>& disparityPixels) const {\n    std::vector<double> planeParameter(3);\n    \n    int pixelTotal = static_cast<int>(disparityPixels.size());\n    if (pixelTotal < 3) {\n        planeParameter[0] = 0;\n        planeParameter[1] = 0;\n        planeParameter[2] = -1;\n    } else {\n        bool isSameX = true;\n        bool isSameY = true;\n        for (int pixelIndex = 1; pixelIndex < pixelTotal; ++pixelIndex) {\n            if (disparityPixels[pixelIndex].x != disparityPixels[0].x) isSameX = false;\n            if (disparityPixels[pixelIndex].y != disparityPixels[0].y) isSameY = false;\n            if (!isSameX && !isSameY) break;\n        }\n        if (isSameX || isSameY) {\n            double disparitySum = 0.0;\n            for (int pixelIndex = 0; pixelIndex < pixelTotal; ++pixelIndex) disparitySum += disparityPixels[pixelIndex].d;\n            \n            planeParameter[0] = 0;\n            planeParameter[1] = 0;\n            planeParameter[2] = -1;\n        } else {\n            planeParameter = estimateDisparityPlaneParameterRANSAC(disparityPixels);\n        }\n    }\n    \n    return planeParameter;\n}\n\nstd::vector<double> StereoSlic::estimateDisparityPlaneParameterRANSAC(const std::vector<DisparityPixel>& disparityPixels) const {\n    const double inlierThreshold = 2.0;\n    const double confidenceLevel = 0.99;\n    \n    int pixelTotal = static_cast<int>(disparityPixels.size());\n    \n    int samplingTotal = pixelTotal*2;\n    \n    int bestInlierTotal = 0;\n    std::vector<bool> bestInlierFlags(pixelTotal);\n    int samplingCount = 0;\n    while (samplingCount < samplingTotal) {\n        // Randomly select 3 pixels\n        int drawIndices[3];\n        drawIndices[0] = rand()%pixelTotal;\n        drawIndices[1] = rand()%pixelTotal;\n        while(drawIndices[1] == drawIndices[0]) drawIndices[1] = rand()%pixelTotal;\n        drawIndices[2] = rand()%pixelTotal;\n        while(drawIndices[2] == drawIndices[1] || drawIndices[2] == drawIndices[0]\n              || (disparityPixels[drawIndices[0]].x == disparityPixels[drawIndices[1]].x && disparityPixels[drawIndices[0]].x == disparityPixels[drawIndices[2]].x)\n              || (disparityPixels[drawIndices[0]].y == disparityPixels[drawIndices[1]].y && disparityPixels[drawIndices[0]].y == disparityPixels[drawIndices[2]].y))\n        {\n            drawIndices[2] = rand()%pixelTotal;\n        }\n        \n        // Compute plane parameters\n        Eigen::Matrix3d matPosition;\n        Eigen::Vector3d vecDisparity;\n        for (int i = 0; i < 3; ++i) {\n            matPosition(i, 0) = disparityPixels[drawIndices[i]].x;\n            matPosition(i, 1) = disparityPixels[drawIndices[i]].y;\n            matPosition(i, 2) = 1.0;\n            vecDisparity(i) = disparityPixels[drawIndices[i]].d;\n        }\n        Eigen::Vector3d planeParameter = matPosition.colPivHouseholderQr().solve(vecDisparity);\n        \n        // Count the number of inliers\n        int inlierTotal = 0;\n        std::vector<bool> inlierFlags(pixelTotal);\n        for (int pixelIndex = 0; pixelIndex < pixelTotal; ++pixelIndex) {\n            double estimatedDisparity = planeParameter(0)*disparityPixels[pixelIndex].x + planeParameter(1)*disparityPixels[pixelIndex].y + planeParameter(2);\n            if (fabs(estimatedDisparity - disparityPixels[pixelIndex].d) <= inlierThreshold) {\n                ++inlierTotal;\n                inlierFlags[pixelIndex] = true;\n            } else {\n                inlierFlags[pixelIndex] = false;\n            }\n        }\n        \n        // Update best inliers\n        if (inlierTotal > bestInlierTotal) {\n            bestInlierTotal = inlierTotal;\n            bestInlierFlags = inlierFlags;\n            \n            samplingTotal = computeRequiredSamplingTotal(3, bestInlierTotal, pixelTotal, samplingTotal, confidenceLevel);\n        }\n        \n        // Increment\n        ++samplingCount;\n    }\n    \n    // Least-square estimation\n    Eigen::MatrixXd matPosition(bestInlierTotal, 3);\n    Eigen::VectorXd vecDisparity(bestInlierTotal);\n    int inlierIndex = 0;\n    for (int pixelIndex = 0; pixelIndex < pixelTotal; ++pixelIndex) {\n        if (bestInlierFlags[pixelIndex]) {\n            matPosition(inlierIndex, 0) = disparityPixels[pixelIndex].x;\n            matPosition(inlierIndex, 1) = disparityPixels[pixelIndex].y;\n            matPosition(inlierIndex, 2) = 1.0;\n            vecDisparity(inlierIndex) = disparityPixels[pixelIndex].d;\n            ++inlierIndex;\n        }\n    }\n    Eigen::Vector3d vecPlaneParameter = matPosition.colPivHouseholderQr().solve(vecDisparity);\n    std::vector<double> planeParameter(3);\n    planeParameter[0] = vecPlaneParameter(0);\n    planeParameter[1] = vecPlaneParameter(1);\n    planeParameter[2] = vecPlaneParameter(2);\n    \n    return planeParameter;\n}\n\nvoid StereoSlic::enforceLabelConnectivity() {\n    int imageSize = width_*height_;\n    int seedTotal = static_cast<int>(seeds_.size());\n    \n    const int minimumSegmentSizeThreshold = imageSize/seedTotal/4;\n    \n    std::vector<int> newLabels(width_*height_, -1);\n    int newLabelIndex = 0;\n    for (int y = 0; y < height_; ++y) {\n        for (int x = 0; x < width_; ++x) {\n            if (newLabels[width_*y + x] >= 0) continue;\n            \n            newLabels[width_*y + x] = newLabelIndex;\n            \n            int adjacentLabel = 0;\n            for (int neighborIndex = 0; neighborIndex < fourNeighborTotal; ++neighborIndex) {\n                int neighborX = x + fourNeighborOffsetX[neighborIndex];\n                int neighborY = y + fourNeighborOffsetY[neighborIndex];\n                if (neighborX < 0 || neighborX >= width_ || neighborY < 0 || neighborY >= height_) continue;\n                \n                if (newLabels[width_*neighborY + neighborX] >= 0) adjacentLabel = newLabels[width_*neighborY + neighborX];\n            }\n            \n            std::vector<int> connectedXs(1);\n            std::vector<int> connectedYs(1);\n            connectedXs[0] = x;\n            connectedYs[0] = y;\n            labelConnectedPixels(x, y, newLabelIndex, newLabels, connectedXs, connectedYs);\n            \n            int segmentPixelTotal = static_cast<int>(connectedXs.size());\n            if (segmentPixelTotal <= minimumSegmentSizeThreshold) {\n                for (int i = 0; i < segmentPixelTotal; ++i) {\n                    newLabels[width_*connectedYs[i] + connectedXs[i]] = adjacentLabel;\n                }\n                --newLabelIndex;\n            }\n            \n            ++newLabelIndex;\n        }\n    }\n    \n    labels_ = newLabels;\n    seeds_.resize(newLabelIndex);\n}\n\nvoid StereoSlic::labelConnectedPixels(const int x, const int y, const int newLabelIndex,\n                                      std::vector<int>& newLabels, std::vector<int>& connectedXs, std::vector<int>& connectedYs) const\n{\n    int originalLabelIndex = labels_[width_*y + x];\n    for (int neighborIndex = 0; neighborIndex < fourNeighborTotal; ++neighborIndex) {\n        int neighborX = x + fourNeighborOffsetX[neighborIndex];\n        int neighborY = y + fourNeighborOffsetY[neighborIndex];\n        if (neighborX < 0 || neighborX >= width_ || neighborY < 0 || neighborY >= height_) continue;\n        \n        if (newLabels[width_*neighborY + neighborX] < 0 && labels_[width_*neighborY + neighborX] == originalLabelIndex) {\n            connectedXs.push_back(neighborX);\n            connectedYs.push_back(neighborY);\n            newLabels[width_*neighborY + neighborX] = newLabelIndex;\n            labelConnectedPixels(neighborX, neighborY, newLabelIndex, newLabels, connectedXs, connectedYs);\n        }\n    }\n}\n\n\nint computeRequiredSamplingTotal(const int drawTotal, const int inlierTotal, const int pointTotal, const int currentSamplingTotal, const double confidenceLevel) {\n    double ep = 1 - static_cast<double>(inlierTotal)/static_cast<double>(pointTotal);\n    if (ep == 1.0) {\n        ep = 0.5;\n    }\n    \n    int newSamplingTotal = static_cast<int>(log(1 - confidenceLevel)/log(1 - pow(1 - ep, drawTotal)) + 0.5);\n    if (newSamplingTotal < currentSamplingTotal) {\n        return newSamplingTotal;\n    } else {\n        return currentSamplingTotal;\n    }\n}\n\n\npng::image<png::rgb_pixel> drawSegmentBoundary(const png::image<png::rgb_pixel>& originalImage,\n                                               const png::image<png::gray_pixel_16>& segmentImage,\n                                               const png::rgb_pixel boundaryColor)\n{\n    // Pixel offsets of 8-neighbors\n    const int eightNeighborTotal = 8;\n    const int eightNeighborOffsetX[8] = {-1,-1, 0, 1, 1, 1, 0,-1};\n    const int eightNeighborOffsetY[8] = { 0,-1,-1,-1, 0, 1, 1, 1};\n    \n    // Check image size\n    int width = static_cast<int>(originalImage.get_width());\n    int height = static_cast<int>(originalImage.get_height());\n    if (segmentImage.get_width() != width || segmentImage.get_height() != height) {\n        throw std::runtime_error(\"drawSegmentBoundary: image sizes are different\");\n    }\n    \n    // Copy input image\n    png::image<png::rgb_pixel> boundaryImage(originalImage);\n    \n    // Draw boundary\n    std::vector<bool> boundaryFlags(width*height, false);\n    for (int y = 0; y < height; ++y) {\n        for (int x = 0; x < width; ++x) {\n            int pixelLabelIndex = segmentImage[y][x];\n            \n            bool drawBoundary = false;\n            for (int neighborIndex = 0; neighborIndex < eightNeighborTotal; ++neighborIndex) {\n                int neighborX = x + eightNeighborOffsetX[neighborIndex];\n                int neighborY = y + eightNeighborOffsetY[neighborIndex];\n                if (neighborX < 0 || neighborX >= width || neighborY < 0 || neighborY >= height) continue;\n                \n                int neighborPixelIndex = width*neighborY + neighborX;\n                if (boundaryFlags[neighborPixelIndex]) continue;\n                if (segmentImage[neighborY][neighborX] != pixelLabelIndex) {\n                    drawBoundary = true;\n                    break;\n                }\n            }\n            \n            if (drawBoundary) {\n                boundaryImage[y][x] = boundaryColor;\n            }\n        }\n    }\n    \n    return boundaryImage;\n}\n", "meta": {"hexsha": "6571665aa58e18e562880d9e0225fa100d706bd0", "size": 32993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "preprocess_data/code/superpixel/StereoSlic.cpp", "max_stars_repo_name": "ganlumomo/semantic_3d_mapping", "max_stars_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2018-03-15T13:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:37:55.000Z", "max_issues_repo_path": "preprocess_data/code/superpixel/StereoSlic.cpp", "max_issues_repo_name": "ganlumomo/semantic_3d_mapping", "max_issues_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-04-28T09:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T23:46:00.000Z", "max_forks_repo_path": "preprocess_data/code/superpixel/StereoSlic.cpp", "max_forks_repo_name": "ganlumomo/semantic_3d_mapping", "max_forks_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T06:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:27:42.000Z", "avg_line_length": 45.195890411, "max_line_length": 164, "alphanum_fraction": 0.6038553633, "num_tokens": 8566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.02228618586391452, "lm_q1q2_score": 0.009843206695315616}}
{"text": "#ifndef STAN_MATH_TORSTEN_EVENT_HISTORY_HPP\n#define STAN_MATH_TORSTEN_EVENT_HISTORY_HPP\n\n#include <iomanip>\n#include <stan/math/prim/fun/value_of.hpp>\n#include <stan/math/rev/fun/value_of.hpp>\n#include <stan/math/prim/meta/return_type.hpp>\n#include <stan/math/prim/err/check_greater_or_equal.hpp>\n#include <stan/math/torsten/PKModel/functions.hpp>\n#include <stan/math/torsten/pk_nsys.hpp>\n#include <Eigen/Dense>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <vector>\n#include <utility>\n#include <functional>\n\nnamespace torsten {\n  /** \n   * Implementation of Non event parameters structure for\n   * bioavailability, lag time, real ODEdata, integer ODE data. Since\n   * we allow elision of any of these we need template discern the\n   * combination. The default is that the param pack has both\n   * bioavailability and lag time\n   *\n   * @tparam Ts types of non-event parameters. Each in the parameter\n   * pack is a 2d array.\n   */\n  template<typename... Ts>\n  struct NonEventParameters_Impl {\n    /// total # of params plus one for theta\n    static constexpr int npar = sizeof...(Ts) + 1;\n    using biovar_t = std::tuple_element_t<0, std::tuple<Ts...> >;\n    using lag_t = std::tuple_element_t<1, std::tuple<Ts...> >;\n\n    static const auto& bioavailability(int i, int j,\n                                       const std::tuple<const std::vector<std::vector<Ts> >&...> array_2d_params) {\n      return std::get<0>(array_2d_params).at(i).at(j);\n    }\n    static const auto& lag_time(int i, int j,\n                                const std::tuple<const std::vector<std::vector<Ts> >&...> array_2d_params) {\n      return std::get<1>(array_2d_params).at(i).at(j);\n    }\n  };\n\n  /**\n   * Specialization: there's bioavailabity but no lag time.\n   */\n  template<typename T>\n  struct NonEventParameters_Impl<T> {\n    static constexpr int npar = 2;\n    using biovar_t = T;\n    using lag_t = double;\n\n    static const auto& bioavailability(int i, int j,\n                                       const std::tuple<const std::vector<std::vector<T> >&> array_2d_params) {\n      return std::get<0>(array_2d_params).at(i).at(j);\n    }\n    static double lag_time(int i, int j,\n                                const std::tuple<const std::vector<std::vector<T> >&> array_2d_params) {\n      return 0.0;\n    }\n  };\n\n  /**\n   * Specialization: there's neither bioavailabity but nor lag time.\n   */\n  template<>\n  struct NonEventParameters_Impl<> {\n    static constexpr int npar = 1;\n    using biovar_t = double;\n    using lag_t = double;\n\n    static double bioavailability(int i, int j,\n                                  const std::tuple<> array_2d_params) {\n      return 1.0;\n    }\n    static double lag_time(int i, int j,\n                                const std::tuple<> array_2d_params) {\n      return 0.0;\n    }\n  };\n\n  /**\n   * Parameters & controls that are not part of event sequence,\n   * including\n   * <code>theta</code>,\n   * <code>bioavailability</code>,\n   * <code>tlag</code>(lag time),\n   * <code>x_r</code>(real data for ODE functor),\n   * <code>x_i</code>(integer data for ODE functor)\n   *\n   * except <code>theta</code>, the above parameters are optional and\n   * are handled by parameter packs. Here two packas are used for\n   * different purposes: \n   * 1. bioavailability and lag time are related to PMX events and\n   *    grouped into a <code>tuple</code>. One can specify none,\n   *    bioavailability only, or bioavailability + tlag.\n   * 2. ODE's real and int data are grouped into a pack. One can specify none,\n   *    real data only, or real + int data.\n   *\n   * @tparam T0 type for time\n   * @tparam T4 type for system parameter, usually refered as <code>pMatrix</code> or <code>theta</code>.\n   * @tparam theta_container type of container,  <code>std::vector</code> or \n   *                         <code>Eigen::Matrix</code>(for linear * system)\n   * @tparam params_tuple_type tuple with a parameter pack for PMX events: bioavailability and lag time.\n   * @tparam Ts pack of types for ODE data: real & integer.\n   * \n   */\n  template<typename T0,\n           typename T4,\n           template<typename...> class theta_container,\n           typename params_tuple_type,\n           typename... Ts>\n  struct NonEventParameters;\n  \n  /** \n   * Parameters & controls that are not part of event sequence,\n   * specialization when types for both bioavailability and lag time\n   * are provided in <code>tuple_pars_t</code>.\n   **/\n  template<typename T0,\n           typename T4,\n           template<typename...> class theta_container,\n           typename... tuple_pars_t,\n           typename... Ts>\n  struct NonEventParameters<T0, T4, theta_container,\n                            std::tuple<tuple_pars_t...>, Ts...> {\n    static constexpr int npar = NonEventParameters_Impl<tuple_pars_t..., Ts...>::npar;\n    /// time & index for an event entry's parameters\n    using par_t = std::pair<double, std::array<int, npar> >;\n    using biovar_t = typename NonEventParameters_Impl<tuple_pars_t...>::biovar_t;\n    using lag_t = typename NonEventParameters_Impl<tuple_pars_t...>::lag_t;\n    using T5 = biovar_t;\n    using T6 = lag_t;\n\n    /// mapping between time and corresponding parameter index\n    std::vector<par_t> pars;\n    const std::vector<T0>& time_;\n    const std::vector<theta_container<T4>>& theta_;\n    /// put parameter pack for bioavailability and lag time into tuple for later retrieval\n    const std::tuple<const std::vector<std::vector<tuple_pars_t> >&...> event_ctrl;\n    /// put parameter pack for ODE's real & integer data into tuple for later retrieval\n    const std::tuple<const std::vector<std::vector<Ts> >&...> ode_data;\n\n    template <typename rec_t>\n    NonEventParameters(int id, const rec_t& rec,\n                       const std::vector<theta_container<T4>>& theta,\n                       const std::vector<std::vector<tuple_pars_t> >&... event_ctrl0,\n                       const std::vector<std::vector<Ts> >&... ode_data0) :\n      pars(rec.len_[id]),\n      time_(rec.time_),\n      theta_(theta),\n      event_ctrl{std::forward_as_tuple(event_ctrl0...)},\n      ode_data{std::forward_as_tuple(ode_data0...)} {\n      int ibegin = rec.begin_[id];\n      for (int i = 0; i < rec.len_[id]; ++i) {\n        int theta_i = rec.len_param(id, theta) > 1 ? rec.begin_param(id, theta) + i : rec.begin_param(id, theta);\n        pars[i] = std::make_pair<double, std::array<int, npar> >(double(stan::math::value_of(time_[ibegin + i])),\n          {theta_i,index_param(id,i,rec,event_ctrl0)..., index_param(id,i,rec,ode_data0)...});\n      }\n      sort();\n    }\n\n    /** \n     * For unit test.\n     * \n     * @param id  subject id\n     * @param rec nonmen event record\n     * @param ibegin_theta beginning index in popultion array for subject id\n     * @param isize_theta length in popultion array for subject id\n     * @param ibegin_biovar beginning index in popultion array for subject id\n     * @param isize_biovar length in popultion array for subject id\n     * @param ibegin_tlag beginning index in popultion array for subject id\n     * @param isize_tlag length in popultion array for subject id\n     * @param theta model param\n     * @param array_2d_params0 additional params\n     * \n     */\n    // template <typename rec_t, std::enable_if_t<sizeof...(Ts) == 2>* = nullptr>\n    template <typename rec_t>\n    NonEventParameters(int id, const rec_t& rec,\n                       int ibegin_theta, int isize_theta,\n                       int ibegin_biovar, int isize_biovar,\n                       int ibegin_tlag, int isize_tlag,\n                       const std::vector<theta_container<T4>>& theta,\n                       const std::vector<std::vector<tuple_pars_t> >&... event_ctrl0,\n                       const std::vector<std::vector<Ts> >&... ode_data0) :\n      pars(rec.len_[id]),\n      time_(rec.time_),\n      theta_(theta),\n      event_ctrl{std::forward_as_tuple(event_ctrl0...)},\n      ode_data{std::forward_as_tuple(ode_data0...)} {\n      int ibegin = rec.begin_[id];\n      for (int i = 0; i < rec.len_[id]; ++i) {\n        int j = isize_theta   > 1 ? ibegin_theta  + i : ibegin_theta;\n        int k = isize_biovar  > 1 ? ibegin_biovar + i : ibegin_biovar;\n        int l = isize_tlag    > 1 ? ibegin_tlag   + i : ibegin_tlag;\n        pars[i] = std::make_pair<double, std::array<int, npar> >(double(stan::math::value_of(time_[ibegin + i])), {j, k, l });\n      }\n      sort();\n    }\n\n    inline void set_par_time(int i, double t) {\n      std::get<0>(pars[i]) = t;\n    }\n\n    inline void set_par_array(int i, const std::array<int, npar>& a) {\n      std::get<1>(pars[i]) = a;\n    }\n\n    inline double get_par_time(int i) const {\n      return std::get<0>(pars[i]);\n    }\n\n    inline const std::array<int, npar>& get_par_array(int i) const {\n      return std::get<1>(pars[i]);\n    }\n\n    inline const theta_container<T4>& theta(int i) const {\n      return theta_[std::get<0>(pars[i].second)];\n    }\n\n    template<size_t Is>\n    inline auto& get_model_array_1d_param(int i) const {\n      using Tuple = std::tuple<const std::vector<std::vector<Ts> >&...>;\n      constexpr size_t Is_param = Is + NonEventParameters_Impl<tuple_pars_t...>::npar;\n      return std::get<Is>(ode_data)[std::get<Is_param>(pars[i].second)];\n    }\n\n    inline const T5 bioavailability(int iEvent, int iParameter) const {\n      return NonEventParameters_Impl<tuple_pars_t...>::bioavailability(get_par_array(iEvent)[1], iParameter,\n                                                                       event_ctrl);\n    }\n\n    inline const T6 lag_time(int iEvent, int iParameter) const {\n      return NonEventParameters_Impl<tuple_pars_t...>::lag_time(get_par_array(iEvent)[2], iParameter,\n                                                                event_ctrl);\n    }\n\n    inline int size() { return pars.size(); }\n\n    void sort() {\n      std::sort(pars.begin(), pars.end(),\n                [](const par_t& a, const par_t& b)\n                { return a.first < b.first; });\n    }\n\n    bool is_ordered() {\n      // check that elements are in chronological order.\n      int i = pars.size() - 1;\n      bool ordered = true;\n\n      while (i > 0 && ordered) {\n        ordered = (pars[i].first >= pars[i-1].first);\n        i--;\n      }\n      return ordered;\n    }\n  };\n\n  /** \n   * find <code>i</code>'th param index for subject <code>id</code>\n   * \n   * @param id subject index\n   * @param i param index for this subject\n   * @param rec populatoin event record\n   * @param param param for entire population\n   * \n   * @return <code>i</code>'th param index for subject <code>id</code>\n   */\n  template<typename rec_t, typename T>\n  inline int index_param(int id, int i, const rec_t& rec,\n                         const std::vector<std::vector<T> >& param) {\n    return rec.len_param(id, param) > 1 ? rec.begin_param(id, param) + i : rec.begin_param(id, param);\n  }\n\n  /**\n   * The EventHistory class defines objects that contain a vector of Events,\n   * along with a series of functions that operate on them.\n   */\n  template<typename T0, typename T1, typename T2, typename T3, typename T_lag>\n  struct EventHistory {\n    // using T_scalar = typename stan::return_type_t<T0, T1, T2, T3, T4, T5, T6>;\n    using T_time = typename stan::return_type_t<T0, T1, T2, T3, T_lag>;\n    // using T_rate = typename stan::return_type_t<T2, T5>;\n    // using T_amt = typename stan::return_type_t<T1, T5>;\n    /// <time, <theta index, F index, lag index> >\n    using Param = std::pair<double, std::array<int, 3> >;\n    using rate_t = std::pair<double, std::vector<T2> >;\n\n    const std::vector<T0>& time_;\n    const std::vector<T1>& amt_;\n    const std::vector<T2>& rate_;\n    const std::vector<T3>& ii_;\n    const std::vector<int>& evid_;\n    const std::vector<int>& cmt_;\n    const std::vector<int>& addl_;\n    const std::vector<int>& ss_;\n\n    // internally generated events\n    // these events are not from user input but required for event\n    // specification. Such examples include those from tlag or\n    // infusion dosing.\n    const size_t num_event_times;\n    std::vector<T_time> gen_time;\n    std::vector<T1> gen_amt;\n    std::vector<T2> gen_rate;\n    std::vector<T3> gen_ii;\n    std::vector<int> gen_cmt;\n    std::vector<int> gen_addl;\n    std::vector<int> gen_ss;\n\n    // 0: original(0)/generated(1)\n    // 1: index in original/generated arrays\n    // 2: evid\n    // 3: is new?(0/1)\n    using IDVec = std::array<int, 4>;\n    std::vector<IDVec> idx;\n\n    // rate at distinct time\n    std::vector<rate_t> rates;\n    std::vector<int> rate_index;\n\n    inline bool keep(const IDVec& id)  const { return id[0] == 0; }\n    inline bool isnew(const IDVec& id) const { return id[3] == 1; }\n    inline int evid (const IDVec& id) const { return id[2] ; }\n\n    inline bool keep(int i)  const { return keep(idx[i]); }\n    inline bool isnew(int i) const { return isnew(idx[i]); }\n    inline int evid (int i) const { return evid(idx[i]); }\n\n    /*\n     * for a population with data in ragged array form, we\n     * form the events history using the population data and\n     * the location of the individual in the ragged arrays.\n     * In this constructor we assume @c p_ii.size() > 1 and\n     * @c p_ss.size() > 1.\n     *\n     * @param ncmt nb. of compartments\n     * @param ibegin beginning index of the subject in data array\n     * @param isize # of indices for current subject in data array\n     * @param p_time event time\n     * @param p_amt dosing amount\n     * @param p_rate dosing rate\n     * @param p_ii dosing interval\n     * @param p_evid event id\n     * @param p_cmt event compartment\n     * @param p_addl additional events\n     * @param p_ss steady states flag\n     */\n    EventHistory(int ncmt, int ibegin, int isize,\n                 const std::vector<T0>& p_time, const std::vector<T1>& p_amt,\n                 const std::vector<T2>& p_rate, const std::vector<T3>& p_ii,\n                 const std::vector<int>& p_evid, const std::vector<int>& p_cmt,\n                 const std::vector<int>& p_addl, const std::vector<int>& p_ss) :\n      time_(p_time),\n      amt_(p_amt),\n      rate_(p_rate),\n      ii_(p_ii),\n      evid_(p_evid),\n      cmt_(p_cmt),\n      addl_(p_addl),\n      ss_(p_ss),\n      num_event_times(isize),\n      idx(isize, {0, 0, 0, 0})\n    {\n      const int iend = ibegin + isize;\n      using stan::math::check_greater_or_equal;\n      static const char* caller = \"EventHistory::EventHistory\";\n      check_greater_or_equal(caller, \"isize\", isize , 1);\n      check_greater_or_equal(caller, \"time size\", p_time.size() , size_t(iend));\n      check_greater_or_equal(caller, \"amt size\", p_amt.size()   , size_t(iend));\n      check_greater_or_equal(caller, \"rate size\", p_rate.size() , size_t(iend));\n      check_greater_or_equal(caller, \"ii size\", p_ii.size()     , size_t(iend));\n      check_greater_or_equal(caller, \"evid size\", p_evid.size() , size_t(iend));\n      check_greater_or_equal(caller, \"cmt size\", p_cmt.size()   , size_t(iend));\n      check_greater_or_equal(caller, \"addl size\", p_addl.size() , size_t(iend));\n      check_greater_or_equal(caller, \"ss size\", p_ss.size()     , size_t(iend));\n      for (size_t i = 0; i < isize; ++i) {\n        idx[i][1] = ibegin + i;\n        idx[i][2] = evid_[ibegin + i];\n      }\n      insert_addl_dose();\n      sort_state_time();\n    }\n\n    /**\n     * EventHistory constructor for an invidual, based on population\n     * version.\n     *\n     * @param ncmt nb. of compartments\n     * @param p_time event time\n     * @param p_amt dosing amount\n     * @param p_rate dosing rate\n     * @param p_ii dosing interval\n     * @param p_evid event id\n     * @param p_cmt event compartment\n     * @param p_addl additional events\n     * @param p_ss steady states flag\n     * @param theta parameter vector\n     * @param biovar bioavailability\n     * @param tlag lag time\n     */\n    EventHistory(int ncmt,\n                 const std::vector<T0>& p_time, const std::vector<T1>& p_amt,\n                 const std::vector<T2>& p_rate, const std::vector<T3>& p_ii,\n                 const std::vector<int>& p_evid, const std::vector<int>& p_cmt,\n                 const std::vector<int>& p_addl, const std::vector<int>& p_ss)\n    : EventHistory(ncmt,\n                   0, p_time.size(), p_time, p_amt, p_rate, p_ii, p_evid, p_cmt, p_addl, p_ss)\n    {}\n\n    bool is_reset(int i) const {\n      return evid(i) == 3 || evid(i) == 4;\n    }\n\n    bool is_reset_event(const IDVec& id) {\n      return evid(id) == 3 || evid(id) == 4;\n    }\n\n    bool is_dosing(int i) const {\n      return evid(i) == 1 || evid(i) == 4;\n    }\n\n    /*\n     * if an event is steady-state dosing event.\n     */\n    bool is_ss_dosing(int i) const {\n      return (is_dosing(i) && (ss(i) == 1 || ss(i) == 2)) || ss(i) == 3;\n    }\n\n    static bool is_dosing(const std::vector<int>& event_id, int i) {\n      return event_id[i] == 1 || event_id[i] == 4;\n    }\n\n    bool is_bolus_dosing(int i) const {\n      const double eps = 1.0E-12;\n      return is_dosing(i) && rate(i) < eps;\n    }\n\n    /*\n     * use current event #i as template to @c push_back\n     * another event.\n     */\n    void insert_event(int i) {\n      idx.push_back({1, int(gen_time.size()), idx[i][2], 1});\n      gen_time. push_back(time (i));\n      gen_amt.  push_back(amt  (i));\n      gen_rate. push_back(rate (i));\n      gen_ii.   push_back(ii   (i));\n      gen_cmt.  push_back(cmt  (i));\n      gen_addl. push_back(addl (i));\n      gen_ss.   push_back(ss   (i));\n    }\n\n    /**\n     * Add events to EventHistory object, corresponding to additional dosing,\n     * administered at specified inter-dose interval. This information is stored\n     * in the addl and ii members of the EventHistory object.\n     *\n     * Events is sorted at the end of the procedure.\n     */\n    void insert_addl_dose() {\n      for (int i = 0; i < size(); i++) {\n        if (is_dosing(i) && ((addl(i) > 0) && (ii(i) > 0))) {\n          for (int j = 1; j <= addl(i); j++) {\n            insert_event(i);\n            gen_time.back() += j * ii(i);\n            gen_ii.back() = 0;\n            gen_addl.back() = 0;\n            gen_ss.back() = 0;\n          }\n        }\n      }\n    }\n\n    /*\n     * sort PMX events and nonevents times\n     */\n    void sort_state_time() { std::stable_sort(idx.begin(), idx.end(),\n                                              [this](const IDVec &a, const IDVec &b) {\n                                                using stan::math::value_of;\n                                                double ta = keep(a) ? value_of(time_[a[1]]) : value_of(gen_time[a[1]]);\n                                                double tb = keep(b) ? value_of(time_[b[1]]) : value_of(gen_time[b[1]]);\n                                                return ta < tb;\n                                              });\n    }\n\n    /** \n     * Generate end-of-infusion event to indicate the range of the infusion.\n     * The new event has a special EVID = 9 and it introduces no action.\n     * \n     * @param nCmt nb of compartments for the model\n     */\n    void generate_rates(int nCmt) {\n      using std::vector;\n      using stan::math::value_of;\n\n      const int n = size();\n      for (size_t i = 0; i < n; ++i) {\n        if ((is_dosing(i)) && (rate(i) > 0 && amt(i) > 0)) {\n          insert_event(i);\n          idx.back()[2] = 9;    // set evid to a special type \"9\"\n          gen_time. back() += amt(i)/rate(i);\n          gen_amt.  back() = 0;\n          gen_rate. back() = 0;\n          gen_ii.   back() = 0;\n          gen_addl. back() = 0;\n          gen_ss.   back() = 0;\n        }\n      }\n      sort_state_time();\n\n      rate_t newRate{0.0, std::vector<T2>(nCmt, 0.0)};\n      // unique_times is sorted\n      std::vector<int> ut(unique_times());\n      for (auto i : ut) {\n        newRate.first = value_of(time(i));\n        rates.push_back(newRate);\n      }\n      // check sorted?\n      std::sort(rates.begin(), rates.end(), [](rate_t const &a, rate_t const &b) {\n          return a.first < b.first;\n        });\n\n      for (size_t i = 0; i < size(); ++i) {\n        if ((is_dosing(i)) && (rate(i) > 0 && amt(i) > 0)) {\n          double t0 = value_of(time(i));\n          double t1 = t0 + value_of(amt(i)/rate(i));\n          for (auto&& r : rates) {\n            if (r.first > t0 && r.first <= t1) {\n              r.second[cmt(i) - 1] += rate(i);\n            }\n          }\n        }\n      }\n\n      /*\n       * rate index points to the rates for each state time,\n       * since there is one rates vector per time, not per event.\n       */\n      rate_index.resize(idx.size());\n      int iRate = 0;\n      for (size_t i = 0; i < idx.size(); ++i) {\n        if (rates[iRate].first != time(i)) iRate++;\n        rate_index[i] = iRate;\n      }\n    }\n\n    // Access functions\n    inline T_time time (const IDVec& id) const { return keep(id) ? time_[id[1]] : gen_time[id[1]] ; }\n    inline const T1& amt (const IDVec& id) const { return keep(id) ? amt_[id[1]] : gen_amt[id[1]] ; }\n    inline const T2& rate (const IDVec& id) const { return keep(id) ? rate_[id[1]] : gen_rate[id[1]] ; }\n    inline const T3& ii (const IDVec& id) const { return keep(id) ? ii_[id[1]] : gen_ii[id[1]] ; }\n    inline int cmt (const IDVec& id) const { return keep(id) ? cmt_[id[1]] : gen_cmt[id[1]] ; }\n    inline int addl (const IDVec& id) const { return keep(id) ? addl_[id[1]] : gen_addl[id[1]] ; }\n    inline int ss (const IDVec& id) const { return keep(id) ? ss_[id[1]] : gen_ss[id[1]] ; }\n\n    inline T_time time (int i) const { return time(idx[i]); }\n    inline const T1& amt (int i) const { return amt (idx[i]); }\n    inline const T2& rate (int i) const { return rate(idx[i]); }\n    inline const T3& ii (int i) const { return ii  (idx[i]); }\n    inline int cmt (int i) const { return cmt (idx[i]); }\n    inline int addl (int i) const { return addl(idx[i]); }\n    inline int ss (int i) const { return ss  (idx[i]); }\n\n    inline size_t size() const { return idx.size(); }\n\n    std::vector<int> unique_times() {\n      std::vector<int> t(idx.size());\n      std::iota(t.begin(), t.end(), 0);\n      auto last = std::unique(t.begin(), t.end(),\n                              [this](const int& i, const int& j) {return time(i) == time(j);});\n      t.erase(last, t.end());\n      return t;\n    }\n\n    /*\n     * Overloading the << Operator\n     */\n    friend std::ostream& operator<<(std::ostream& os, const EventHistory& ev) {\n      const int w = 6;\n      os << \"\\n\";\n      os << std::setw(w) << \"time\" <<\n        std::setw(w) << \"amt\" <<\n        std::setw(w) << \"rate\" <<\n        std::setw(w) << \"ii\" <<\n        std::setw(w) << \"evid\" <<\n        std::setw(w) << \"cmt\" <<\n        std::setw(w) << \"addl\" <<\n        std::setw(w) << \"ss\" <<\n        std::setw(w) << \"keep\" <<\n        std::setw(w) << \"isnew\" << \"\\n\";\n      for (size_t i = 0; i < ev.size(); ++i) {\n        os <<\n          std::setw(w)   << ev.time(i) << \" \" <<\n          std::setw(w-1) << ev.amt(i) << \" \" <<\n          std::setw(w-1) << ev.rate(i) << \" \" <<\n          std::setw(w-1) << ev.ii(i) << \" \" <<\n          std::setw(w-1) << ev.evid(i) << \" \" <<\n          std::setw(w-1) << ev.cmt(i) << \" \" <<\n          std::setw(w-1) << ev.addl(i) << \" \" <<\n          std::setw(w-1) << ev.ss(i) << \" \" <<\n          std::setw(w-1) << ev.keep(i) << \" \" <<\n          std::setw(w-1) << ev.isnew(i) << \"\\n\";\n      }\n      return os;\n    }\n  };\n\n}    // torsten namespace\n#endif\n", "meta": {"hexsha": "b9413b1433b76f1c6e25aa9c3c1af0af5486a591", "size": 23333, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ev_history.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ev_history.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "ev_history.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.9398373984, "max_line_length": 126, "alphanum_fraction": 0.5769939571, "num_tokens": 6473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208213138121609, "lm_q2_score": 0.030675801932215606, "lm_q1q2_score": 0.009841451078135034}}
{"text": "/* fflame_generator.hpp -- part of the fractal flames implementation\n *\n * Copyright (C) 2015 Alrik Firl\n *\n * This software may be modified and distributed under the terms\n * of the MIT license.  See the LICENSE file for details.\n */\n\n#ifndef FF_FFLAME_GENERATOR_HPP\n#define FF_FFLAME_GENERATOR_HPP\n\n#include \"fractal_flame.hpp\"\n#include \"ifs.hpp\"\n#include \"ifs_types.hpp\"\n#include \"render_flame.hpp\"\n#include \"util/EventQueue.hpp\"\n#include \"util/ff_utils.hpp\"\n\n#include <opencv2/opencv.hpp>\n//#include <boost/lockfree/queue.hpp>\n#include <boost/lockfree/spsc_queue.hpp>\n\n#include <atomic>\n#include <condition_variable>\n#include <limits>\n#include <memory>\n#include <mutex>\n#include <random>\n#include <string>\n#include <thread>\n\nnamespace FFlames {\n\ntemplate <template <class> class frame_t, typename data_t, typename pixel_t>\nclass fflame_generator {\npublic:\n  // NOTE: can (try to) get a reproducable sequence by not initializing\n  // flame_gen(flame_rd())?\n  fflame_generator(const int imheight, const int imwidth,\n                   const int num_variants,\n                   const int num_workers = std::thread::hardware_concurrency())\n      : num_workers(num_workers), render_imheight(imheight),\n        render_imwidth(imwidth), num_working_variants(num_variants),\n        fflame_histoqueue(100, 30), flame_prebarrier(num_workers),\n        flame_postbarrier(num_workers), fflame_th(nullptr),\n        fflame_histdata(nullptr), flame_gen(flame_rd()),\n        total_variant_rng(\n            0, affine_fcns::variant_list<data_t>::variant_names.size() - 1) {\n    // NOTE: this has to be shared between all the worker threads\n    fflame_histdata = std::unique_ptr<fflame_data<data_t, pixel_t>>(\n        new fflame_data<data_t, pixel_t>());\n\n    initialize_variants();\n    fflame_state.store(false);\n  }\n\n  fflame_generator(const int imheight, const int imwidth,\n                   std::vector<std::string> &&manual_variants,\n                   const int num_workers = std::thread::hardware_concurrency())\n      : num_workers(num_workers), render_imheight(imheight),\n        render_imwidth(imwidth), num_working_variants(manual_variants.size()),\n        fflame_histoqueue(100, 30), flame_prebarrier(num_workers),\n        flame_postbarrier(num_workers), fflame_th(nullptr),\n        fflame_histdata(nullptr), flame_gen(flame_rd()),\n        total_variant_rng(\n            0, affine_fcns::variant_list<data_t>::variant_names.size() - 1) {\n    // NOTE: this has to be shared between all the worker threads\n    fflame_histdata = std::unique_ptr<fflame_data<data_t, pixel_t>>(\n        new fflame_data<data_t, pixel_t>());\n\n    initialize_variants(std::move(manual_variants));\n    fflame_state.store(false);\n  }\n\n  ~fflame_generator() {\n    if (fflame_state.load()) {\n      stop_generation();\n    }\n  }\n\n#if 1\n  template <typename T> using ts_queue_t = EventQueue<T>;\n#else\n  template <typename T>\n  using ts_queue_t =\n      boost::lockfree::spsc_queue<T, boost::lockfree::capacity<1024>>;\n#endif\n\n  void start_generation() {\n    // if already started, don't try to start again\n    if (fflame_state.load()) {\n      return;\n    }\n\n    fflame_state.store(true);\n    fflame_th = std::unique_ptr<std::thread>(\n        new std::thread(&fflame_generator::start_fflame_generation, this));\n  }\n\n  void stop_generation() {\n    if (fflame_state.load()) {\n      fflame_state.store(false);\n      for (size_t th_idx = 0; th_idx < fflame_workers.size(); ++th_idx) {\n        fflame_workers.at(th_idx)->finish_flame();\n      }\n      fflame_th->join();\n    }\n  }\n\n  void register_framequeue(ts_queue_t<frame_t<pixel_t>> *queue) {\n    fflame_imagequeue = queue;\n  }\n\nprivate:\n  void initialize_variants(std::vector<std::string> &&manual_variants);\n  void initialize_variants();\n  void start_fflame_generation();\n  void generate_fflame(fflame_util::fast_rand &rand_gen);\n  void render_fflame();\n\n  // number of threads used for the generation (not counting rendering)\n  int num_workers;\n  int render_imheight;\n  int render_imwidth;\n\n  // the number of variants to have active\n  uint8_t num_working_variants;\n  std::thread::id worker_overlord_id;\n\n  // pause generation if above the max, resume if paused and below the min\n  static constexpr size_t max_image_thresh = 25;\n  static constexpr size_t min_image_thresh = 5;\n\n  // controls the starting and stopping of the worker threads\n  std::mutex gen_mtx;\n  std::condition_variable gen_cv;\n\n  // for passing results asynchronously between the generate & render steps\n  // EventQueue<cv::Mat_<histogram_info<pixel_t>>> fflame_histoqueue;\n\n  ts_queue_t<std::vector<histogram_info<pixel_t>>> fflame_histoqueue;\n  // for holding the final images. provided by the caller\n  ts_queue_t<frame_t<pixel_t>> *fflame_imagequeue;\n\n  fflame_util::barrier flame_prebarrier;\n  fflame_util::barrier flame_postbarrier;\n\n  // the rendering/controller flame thread\n  std::unique_ptr<std::thread> fflame_th;\n  // the fractal flame generation threads\n  std::vector<std::unique_ptr<flame_thread>> fflame_workers;\n\n  // flag for starting/stopping the whole fflame pipeline\n  std::atomic<bool> fflame_state;\n\n  // holds the list of the current variation functions to use\n  std::unique_ptr<affine_fcns::invoker<data_t>> flamer;\n  std::unique_ptr<fflame_data<data_t, pixel_t>> fflame_histdata;\n\n  // the various RNGs needed for the generation\n  std::random_device flame_rd;\n  std::mt19937 flame_gen;\n  // std::uniform_int_distribution<uint8_t> working_variant_rng;\n  std::uniform_int_distribution<> total_variant_rng;\n};\n\ntemplate <template <class> class frame_t, typename data_t, typename pixel_t>\nvoid fflame_generator<frame_t, data_t, pixel_t>::initialize_variants(\n    std::vector<std::string> &&manual_variants) {\n  flamer = std::unique_ptr<affine_fcns::invoker<data_t>>(\n      new affine_fcns::invoker<data_t>(std::move(manual_variants)));\n  flamer->randomize_parameters(-2, 2);\n}\n\ntemplate <template <class> class frame_t, typename data_t, typename pixel_t>\nvoid fflame_generator<frame_t, data_t, pixel_t>::initialize_variants() {\n  flamer = std::unique_ptr<affine_fcns::invoker<data_t>>(\n      new affine_fcns::invoker<data_t>(num_working_variants));\n  // NOTE: we always want to have the linear variant (variant #0)\n  int variant_idx = 0;\n  auto linear_variant_id =\n      affine_fcns::variant_list<data_t>::variant_names[variant_idx];\n  flamer->set_variant(variant_idx, linear_variant_id);\n  for (int i = variant_idx + 1; i < num_working_variants; ++i) {\n    std::string selected_variant;\n    // keep re-rolling the variant until we get a valid one\n    do {\n      variant_idx = total_variant_rng(flame_gen);\n      selected_variant =\n          affine_fcns::variant_list<data_t>::variant_names[variant_idx];\n    } while (!flamer->check_variant_valid(selected_variant));\n\n    // can assume by here that the selected variant is a valid one\n    flamer->set_variant(i, selected_variant);\n  }\n  flamer->randomize_parameters(-2, 2);\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ntemplate <template <class> class frame_t, typename data_t, typename pixel_t>\nvoid fflame_generator<frame_t, data_t, pixel_t>::start_fflame_generation() {\n  fflame_state.store(true);\n\n  std::uniform_int_distribution<uint64_t> flame_dist(\n      0, std::numeric_limits<uint64_t>::max());\n\n  // spawn the worker threads\n  for (int th_idx = 0; th_idx < num_workers; ++th_idx) {\n    // seeds the flame thread's fast random number generator\n    fflame_workers.emplace_back(\n        new flame_thread(flame_dist(flame_gen), flame_dist(flame_gen)));\n    // this step is the one that actually spawns the thread\n    bool flame_run;\n    std::thread::id tid;\n    std::tie(flame_run, tid) = fflame_workers.at(th_idx)->do_flame(\n        &fflame_generator::generate_fflame, this);\n\n    // this would be sort of a big deal. should probably throw something here\n    if (!flame_run) {\n      std::cout << \"NOTE: flame task failed\" << std::endl;\n    }\n\n    if (th_idx == 0) {\n      worker_overlord_id = tid;\n    }\n  }\n\n  // prepare the image and push the image to the shared queue\n  render_fflame();\n}\n\ntemplate <typename pixel_t>\nhistogram_info<pixel_t>\nprint_mat(const cv::Mat_<histogram_info<pixel_t>> &hdata, int row, int col) {\n  return hdata(row, col);\n}\n\n// makes the fractal flame histogram using the chaos game. Is invoked by N\n// threads\ntemplate <template <class> class frame_t, typename data_t, typename pixel_t>\nvoid fflame_generator<frame_t, data_t, pixel_t>::generate_fflame(\n    fflame_util::fast_rand &rand_gen) {\n  while (fflame_state.load()) {\n    auto start_iter_time = std::chrono::high_resolution_clock::now();\n\n    // 0. check if the generation should pause (i.e. too many frames in queue)\n    // --> leave this for after you get it working\n    // 1. start the next flame generation\n    run_fflame<data_t, pixel_t>(flamer.get(),\n                                fflame_constants::num_samples / num_workers,\n                                fflame_histdata.get(), rand_gen);\n\n    auto end_iter_time = std::chrono::high_resolution_clock::now();\n    double time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(\n                              end_iter_time - start_iter_time)\n                              .count();\n    std::cout << \"thread \" << std::this_thread::get_id()\n              << \" generation took -- \" << time_elapsed << \" ms\" << std::endl;\n\n    // 2. wait for all the threads to finish the previous round\n    flame_prebarrier.wait();\n\n    // merge the N thread results using the overlord thread\n    if (std::this_thread::get_id() == worker_overlord_id) {\n      static std::vector<std::string> mutated_variant_ids(num_working_variants,\n                                                          \"default\");\n\n      // somewhat unfortunate, but need to dynamically allocate to avoid scoping\n      // problems\n      auto hist_info = std::unique_ptr<std::vector<histogram_info<pixel_t>>>(\n          new std::vector<histogram_info<pixel_t>>(fflame_constants::imheight *\n                                                   fflame_constants::imwidth));\n      fflame_histdata->get_and_reset(*hist_info);\n\n      // 3.5 pass the finished histogram to the shared-buffer for rendering\n      fflame_histoqueue.push(std::move(hist_info));\n\n      // 4. mutate the variants\n      std::string selected_variant;\n      // keep re-rolling the variant until we get a valid one\n      do {\n        selected_variant =\n            affine_fcns::variant_list<data_t>::variant_names[total_variant_rng(\n                flame_gen)];\n      } while (!flamer->check_variant_valid(selected_variant));\n\n      // replace a random variant (that's not the linear variant)\n      int mod_idx =\n          (num_working_variants > 1)\n              ? total_variant_rng(flame_gen) % (num_working_variants - 1) + 1\n              : 0;\n      // can assume by here that the selected variant is a valid one\n      flamer->set_variant(mod_idx, selected_variant);\n      flamer->randomize_parameters(-2, 2);\n\n      flamer->print_variant_list();\n\n      // there should be no threads waiting at the pre-barrier at this point;\n      // the other (non-overlord) threads should be waiting at the post-barrier\n      flame_prebarrier.reset(num_workers);\n    }\n  }\n}\n\n// generates an image based on the fflame histogram\ntemplate <template <class> class frame_t, typename data_t, typename pixel_t>\nvoid fflame_generator<frame_t, data_t, pixel_t>::render_fflame() {\n  bool got_histdata = false;\n  // int raw_counter = 0;\n\n  fflame_renderer<data_t> flame_image_renderer(render_imheight, render_imwidth);\n\n  double total_render_time = 0;\n  while (fflame_state.load()) {\n    // 1. get the histogram\n    auto hist_info = fflame_histoqueue.pop(got_histdata);\n    if (got_histdata && hist_info) {\n      auto start_render_time = std::chrono::high_resolution_clock::now();\n\n      std::unique_ptr<frame_t<pixel_t>> image =\n          std::unique_ptr<frame_t<pixel_t>>(\n              new frame_t<pixel_t>(render_imheight, render_imwidth));\n      std::fill(image->data, image->data + image->rows * image->cols, 0);\n\n      // 2. call the rendering routine, get resultant image\n      flame_image_renderer.template render<frame_t, pixel_t>(\n          image.get(), std::move(hist_info));\n\n      /*\n                  //filter out the flames that are too sparse\n                  int num_nonzero = 0;\n                  const double image_threshold = 0.1 * imwidth * imheight;\n                  const double px_threshold = 1.0;\n                  for (int r = 0; r < imheight; ++r)\n                  {\n                      for (int c = 0; c < imwidth; ++c)\n                      {\n                          size_t px_sum = cv::sum(outfile_image.at<pixel_t>(r,\n         c))[0]; if(px_sum > px_threshold) { num_nonzero++;\n                          }\n                      }\n                  }\n                  if(num_nonzero < image_threshold)\n                  {\n                      std::cout << \"NOTE: flame too dark\" << std::endl;\n                      continue;\n                  }\n                  //mostly for debugging -- save the images to disk\n                  const std::string raw_impath = \"FFLAME_baseimage_\" +\n         std::to_string(raw_counter++) + \".png\"; cv::imwrite(raw_impath, image);\n      */\n\n      fflame_imagequeue->push(std::move(image));\n\n      auto end_render_time = std::chrono::high_resolution_clock::now();\n      total_render_time +=\n          std::chrono::duration_cast<std::chrono::milliseconds>(\n              end_render_time - start_render_time)\n              .count();\n    }\n  }\n\n  std::cout << \"rendering took -- \" << total_render_time << \" ms\" << std::endl;\n}\n\n} // namespace FFlames\n#endif\n", "meta": {"hexsha": "81e4341d1d626d57dfa9aafb42017ab92aeb94f7", "size": 13715, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fflames/fflame_generator.hpp", "max_stars_repo_name": "alrikai/fflames", "max_stars_repo_head_hexsha": "cf07d993f18c93fb528892b2396eb6d1c03d7de5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T18:37:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-12T18:37:27.000Z", "max_issues_repo_path": "fflames/fflame_generator.hpp", "max_issues_repo_name": "alrikai/fflames", "max_issues_repo_head_hexsha": "cf07d993f18c93fb528892b2396eb6d1c03d7de5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fflames/fflame_generator.hpp", "max_forks_repo_name": "alrikai/fflames", "max_forks_repo_head_hexsha": "cf07d993f18c93fb528892b2396eb6d1c03d7de5", "max_forks_repo_licenses": ["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.1680216802, "max_line_length": 116, "alphanum_fraction": 0.6654028436, "num_tokens": 3368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.025565212902435873, "lm_q1q2_score": 0.009840360922464918}}
{"text": "/*\n *  libtraj_gen.cpp\n *  Trajectory Generator Library\n *\n *  Created by Matthew O'Kelly on 7/17/15.\n *  Copyright (c) 2015 Matthew O'Kelly. All rights reserved.\n *  mokelly@seas.upenn.edu\n *  \n*/\n\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 Autoware nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n\n\n/*\n * This file contains the vehicle model for use in predicting the ego vehicle's motion\n * It also contains a heuristic for initial trajetories and \n * a gradient descent method for refining them...\n *\n * First some constants are defined, these will be specific to your vehicle\n * Nine functions are included: speedControlLogic(),\n * responsetoControlInputs(), and most\n * importantly, the vehicle's motionModel() etc...\n *\n * motionModel() calls responseToControlInputs()\n * responseToControlInputs calls speedControlLogic()\n *\n * For a standalone build use the following command: g++ trajectorygenerator.cpp -o trajectorygenerator -O2 -larmadillo\n * Dependancies: Armadillo, http://arma.sourceforge.net/\n *\n*/\n\n#include <iostream>\n#include <vector>\n#include <armadillo>\n#include <cmath>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"libtraj_gen.h\"\n// #include \"trajectorygenerator.h\"\n\n\n\nusing namespace std;\n\n\n\n//-----------------------------FUNCTIONS------------------------------------//\n\n// ------------INITIALIZE PARAMETERS----------//\n// Heuristic to compute initial paramters given\n// INPUT: Initial state, and a goal state\n// OUTPUT: Estimated control parameters\n// Use #define USE_HEURISTIC_INIT if using Nagy 2001 method\n// This is necessary for cubic splines\n// Use #define FIRST_ORDER if working with first order splines\n\nunion Spline initParams(union State veh, union State goal)\n{\n\n    // Local variables for init and goal:\n    double sx_f = goal.sx;\n    double sy_f = goal.sy;\n    double theta_f = goal.theta;\n    double kappa_0 = veh.kappa;\n    double kappa_f = goal.kappa;\n    \n    // Initialize output\n    union Spline curvature;\n\n    // Convenience\n    double d_theta = abs(theta_f);\n    \n    // Heuristic for initial guess from Nagy and Kelly, 2001\n    // 'Trajectory Generation for Car-like Robots using\n    //  Cubic Curvature Polynomials'\n    #ifdef USE_HEURISTIC_INIT\n        // Order of computation matters, need to compute d before s and so on...\n        \n        // Commented out, because unused for cubic splines\n        //double c = 0.0;\n        \n        // Note we must cast to double to avoid ambiguity\n        double d = sqrt((double)pow(sx_f,2) +(double) pow(sy_f,2));  \n        \n        double s = d * ((pow(d_theta,2))/5.0 + 1.0) + (2.0/5.0)*d_theta;\n        \n        // Commented out because unused for cubic splines\n        //double a = (6* (theta_f/(pow(s,2)))) - (2*kappa_0/s) + (4*kappa_f/s);\n\n        double b = (3/(pow(s,2))) * (kappa_0 + kappa_f) + (6*theta_f/(pow(s,3)));\n\n        double si=0.00;\n        curvature.kappa_0 = veh.kappa;\n        curvature.kappa_1=(1.00/49.00)*(8.00*b*si - 8.00*b*curvature.s - 26.00*curvature.kappa_0 - curvature.kappa_3);\n        curvature.kappa_2=0.25*(curvature.kappa_3 -2.00*curvature.kappa_0 +5.00*curvature.kappa_1);\n        curvature.kappa_3 = goal.kappa;\n        curvature.s = s;\n\n    #endif\n\n    // Alternative heuristic initial guess for first order spline\n    // From Thomas Howard's dissertation page 38\n    #ifdef FIRST_ORDER\n        double d = sqrt((double)pow(sx_f,2) +(double) pow(sy_f,2));\n        double s = d * ((pow(d_theta,2))/5 + 1) + (2/5)  *d_theta;\n        union Spline curvature;\n        double si=0.00;\n        curvature.kappa_0 = veh.kappa;\n        curvature.kappa_1 = 0.00;\n        curvature.kappa_2 = 0.00;\n        curvature.kappa_3 = goal.kappa;\n        curvature.s = s;\n    #endif\n\n    curvature.success=TRUE;\n\n    // Return the initialized curvature union\n    return curvature;\n    \n}\n\n\n// ------------SPEED CONTROL----------//\n// Function for computing safe (feasible) speed and curvature\n// INPUT: Next vehicle state\n// OUTPUT: Updated next vehicle state\n\nunion State speedControlLogic(union State veh_next)\n{\n\n    // Calculate speed (look up from next state vector)\n    double vcmd = abs(veh_next.v);\n    double kappa_next = veh_next.kappa;\n    \n    // Compute safe speed\n    double compare_v=(kappa_next-ascl)/bscl;\n    double vcmd_max = max((double)vscl, compare_v);\n    \n    // Compute safe curvature\n    double compare_kappa = ascl + (bscl * vcmd);\n    double kmax_scl = min((double) kmax, compare_kappa);\n    \n    // Check if max curvature for speed is exceeded\n    if(kappa_next >= kmax_scl)\n    {\n        // Check for safe speed\n        vcmd = sf * vcmd_max;\n    }\n    \n    // Update velocity command, this is not quite equivalent to Ferguson, Howard, & Liukhachev\n    veh_next.v = vcmd;\n    \n    // Return vehicle state\n    return veh_next;    \n}\n\n// ------------RESPONSE TO CONTROL----------//\n// Function for computing the vehicles response to control inputs\n// Mainly deals with delays associated with controls\n// Also considers upper and lower safety bounds\n// INPUT: Current vehicle state, next vehicle state, sampling time\n// OUTPUT: Next vehicle state\n\nunion State responseToControlInputs(union State veh, union State veh_next, double dt)\n{\n\n    // Local variables:\n    double kappa = veh.kappa;\n    double kappa_next = veh_next.kappa;\n    double v = veh.v;\n    double v_next = veh_next.v;\n    \n    // Compute curvature rate command\n    double kdot = (kappa_next - kappa)/dt;\n    \n    // Check against upper bound on curvature rate\n    kdot = min(kdot, (double) dkmax);\n    \n    // Check against lower bound on curvature rate\n    kdot = max(kdot, (double) dkmin);\n    \n    // Call the speedControlLogic function\n    veh_next = speedControlLogic(veh_next);\n    \n    // Compute curvature at the next vehicle state\n    kappa_next = kappa + kdot*dt;\n    \n    // Check upper bound on curvature\n    kappa_next = min(kappa_next, (double) kmax);\n    \n    // Check lower bound on curvature\n    kappa_next = max(kappa_next, (double) kmin);\n    \n    // Compute acceleration command\n    double vdot = (v_next -v)/dt;\n    \n    // Check for upper bound on acceleration\n    vdot = min(vdot, (double) dvmax);\n    \n    // Check for lower bound on acceleration\n    vdot = max(vdot, (double) dvmin);\n    \n    // Compute velocity at next state\n    veh_next.v = v + vdot*dt;\n    \n    // Return next vehicle state\n    return veh_next;  \n}\n\n// ------------COMPUTE CURVATURE----------//\n// Computes the curvature at the next state\n// Still messy but will clean shortly...\n\ndouble getCurvatureCommand(union Spline curvature, double dt, double v, double t)\n{\n    // Local variables for curvature constants\n    double kappa_0 = curvature.kappa_0;\n    double kappa_1 = curvature.kappa_1;\n    double kappa_2 = curvature.kappa_2;\n    double kappa_3 = curvature.kappa_3;\n    double s = curvature.s;\n\n    // Init next command\n    double k_next_cmd =0.0;\n    \n    // Assume position at t=0, si=0\n    double si = 0.0;\n\n    // Estimate distance traveled on spiral\n    double st = v*t;\n\n    // These equations can be found in McNaughton, page 76\n    // They make the knot points equally spaced.\n    // They apply to stable cubic paths\n    #ifdef CUBIC_STABLE\n        double a =0;\n        double b =0;\n        double c= 0;\n        double d = 0;\n        a = kappa_0;\n        b = (-0.50)*(-2*kappa_3 + 11*kappa_0 - 18*kappa_1 + 9*kappa_2)/(s-si);\n        c = (4.50)*(-kappa_3 + 2*kappa_0 - 5*kappa_1 +4*kappa_2)/(pow((s-si), 2));\n        d = (-4.50)*(-kappa_3 + kappa_0 - 3*kappa_1 + 3*kappa_2)/(pow((s-si), 3));\n        k_next_cmd = a + b*st + c*pow(st,2) + d*pow(st,3);\n    #endif\n\n    // These equations can be found in McNaughton, page 77\n    // They make the knot points equally spaced.\n    // They apply to stable quintic paths\n    #ifdef QUINTIC_STABLE\n        double a = kappa_0;\n        double b = kappa_1;\n        double c = kappa_2/2.0;\n        double d = -(575*kappa_0 -648*kappa_3 +81*kappa_4 -8*kappa_5 +170*kappa_1*st +22*kappa_2*pow(st,2)/ (8*pow(st,3));\n        double e = 9*(37*kappa_0 -45*kappa_3 +9*kappa_4 -kappa_5 +10*kappa_1*st +kappa_2*pow(st,2))/(2*pow(st,4));\n        double f = -9*(85*kappa_0 -108*kappa_3 +27*kappa_4 -4*kappa_5 +22*kappa_1*st +2*kappa_2*pow(st,2))/(8*pow(st,5));\n        k_next_cmd = a + b*st + c*pow(st,2) + d*pow(st,3) + e*pow(st,4) +f*pow(st,5); \n    #endif\n\n    // Compute next command from Howard page 39\n    #ifdef FIRST_ORDER\n        k_next_cmd = kappa_0 + ((kappa_1 - kappa_0)/s) * (st);\n    #endif\n\n    // Return value\n    return k_next_cmd;\n    \n}\n\n// ------------COMPUTE VELOCITY----------//\n// Updates the vehicles velocity based on velocity profile\n// Currently assumes constant\n/// Will update to include ramp...\n\ndouble getVelocityCommand(double v_goal, double v)\n{\n    #ifdef DEBUG\n    cout << \"Function: getVelocityCommand()\"<< endl;\n    #endif\n    // Some function based on parameterization of velocity profile\n    // Set to constant for now\n    double v_next_cmd=v_goal;\n    return v_next_cmd;\n}\n\n// ------------MOTION MODEL----------//\n// Computes update to vehicle state\n// INPUT: Current vehicle state, parameterized control inputs, sampling time\n// OUTPUT: Next vehicle state\n\nunion State motionModel(union State veh, union State goal, union Spline curvature, double dt, double horizon, int flag)\n{\n    // Initialized the elapsed time to 0.0 s\n    double t =0.0;\n    // Setup local data structures for holding \n    // the previous and next vehicle states\n    union State veh_next;\n    union State veh_temp;\n    // Set veh_temp to the current state\n    veh_temp=veh;\n    // Compute the stop time for the simulation\n    horizon = curvature.s/goal.v;\n\n    while(t < horizon)\n    {\n        // Read state vector\n        double sx = veh_temp.sx;\n        double sy = veh_temp.sy;\n        double v = veh_temp.v;\n        double theta = veh_temp.theta;\n        double kappa = veh_temp.kappa;\n        double v_goal= goal.v;\n\n        // Compute change in 2D x-position (this is x_dot)\n        double sx_next = sx + (v * cos(theta) * dt);\n\n        veh_next.sx = sx_next;\n\n\n        // Compute change in 2D y-position (this is y_dot)\n        double sy_next = sy + (v * sin(theta) * dt);\n\n        veh_next.sy = sy_next;\n\n        // Compute change in 2D orientation (this is theta_dot)\n        double theta_next = theta + (v * kappa * dt);\n\n        veh_next.theta = theta_next;\n\n        // Get curvature command\n        double kappa_next = getCurvatureCommand(curvature, dt , veh.v,t);\n\n        veh_next.kappa = kappa_next;\n\n        // Get velocity command\n        double v_next = getVelocityCommand(v_goal, v);\n\n        veh_next.v = v_next;\n\n        // Get acceleration command, not used yet...\n        //double a_next_cmd = 0;\n\n\n        // Update the next vehicle state\n        veh_next = responseToControlInputs(veh, veh_next, dt);\n\n        // Increment the timestep\n        t=t+dt;\n\n        // Update veh_temp\n        veh_temp=veh_next;\n\n        // Write to log file if we are testing\n        if(flag==1)\n        {\n            fmm_sx <<veh_temp.sx<<\", \";\n            fmm_sy <<veh_temp.sy<<\", \";\n            fmm_v <<veh_temp.v<<\", \";\n            fmm_theta << veh_temp.theta<<\", \";\n            fmm_kappa<<veh_temp.kappa<<\", \";\n        }\n\n    }\n        // Print information to console\n        #ifdef DEBUG\n        cout << \"Next state sx: \" << veh_next.sx << endl;\n        cout << \"Next state sy: \" << veh_next.sy << endl;\n        cout << \"Next state theta: \" << veh_next.theta << endl;\n        cout << \"Next state v: \" << veh_next.v << endl;\n        cout << \"Next state kappa: \" << veh_next.kappa<< endl;\n        #endif\n\n\n    // Return the state at the end of the trajectory\n    return veh_next;\n}\n\n\n// ------------CHECK CONVERGENCE----------//\n// Checks to see if we have reached target solution\n// INPUT: Next vehicle state predicted by the forward motion model and goal state\n// OUTPUT: Boolean\n// TO DO: if theta is constrained, please check that this is an appropriate metric.\n// IE consider 359 degrees vs. 1 degree\n// Can use fmod (modulus) over pi or 2*pi\n\nbool checkConvergence(union State veh_next, union State goal)\n{\n    #ifdef DEBUG\n    cout << \"Function: checkConvergence()\"<< endl;\n    #endif\n\n    double sx_error = abs(veh_next.sx - goal.sx);\n    double sy_error = abs(veh_next.sy - goal.sy);\n    double theta_error = abs(veh_next.theta - goal.theta);\n\n    // Commented out to suppress compiler warning about unused var\n    // double v_error = abs(veh_next.v - goal.v);\n    // double kappa_error = abs(veh_next.kappa - goal.kappa);\n\n    #ifdef DEBUG_OUTPUT\n    cout << \"Error sx: \" << sx_error << endl;\n    cout << \"Error sy: \" << sy_error << endl;\n    cout << \"Error theta: \" << theta_error << endl;\n    // Commented out to suppress compiler warning about unused var\n    // cout << \"Error v: \" << v_error << endl;\n    // cout << \"Error kappa: \" << kappa_error << endl;\n    #endif\n\n    // Depending on the order of the spline the full range of checks is:\n    // if(sx_error<general_e && sy_error<general_e && theta_error<general_e \n    // && theta_error<general_e && v_error<general_e && kappa_error<general_e)\n    if(sx_error<general_e && sy_error<general_e && theta_error<general_e) \n    {\n        #ifdef DEBUG\n        cout << \"Converged\"<< endl;\n        #endif\n        return TRUE;\n    }\n\n    else\n    {\n        #ifdef DEBUG\n        cout << \"Not Converged\"<< endl;\n        #endif\n        return FALSE;\n    }\n    \n}\n\n// ------------ESTIMATE JACOBIAN----------//\n// Forward difference method via predictive motion model\n// INPUT: Initial State, Target State, Parameterized Action,\n//        Predictive Motion Model, Action Parameters\n// OUTPUT: Jacobian Estimate\n\nunion State pDerivEstimate(union State veh, union State veh_next, union State goal, union Spline curvature, int p_id, double h, double dt, double horizon, int stateIndex)\n{\n    #ifdef DEBUG\n    cout << \"Function: pDerivEstimate()\"<< endl;\n    #endif\n\n    // Index for iterating through parameters\n    int i = 0;\n\n    // Compute difference between desired sx and actual\n    // May need to update with intial state if not 0,0,0,0,0\n    union State delta_state;\n\n    // Compute the difference between the end state of the current spline and the goal\n    for (i=0; i<stateIndex; i++)\n    {\n        delta_state.state_value[i] = (goal.state_value[i] - veh_next.state_value[i]);\n    }\n\n    // Create parameter perturbation vector\n    union Spline perturb_curve = curvature;\n    \n    // Perturb parameter\n    perturb_curve.spline_value[p_id] = curvature.spline_value[p_id] +h;\n    \n    // Check forward motion model with perturbed parameter\n    union State perturb_next = motionModel(veh, goal, perturb_curve, dt, horizon, 0);\n\n    // Now create a new structure to hold the difference between goal and perturbed forward motion model\n    union State delta_perturb_state;\n\n    // Compute difference between goal sx and actual\n    for (i=0; i<stateIndex; i++)\n    {\n         delta_perturb_state.state_value[i] = goal.state_value[i] - perturb_next.state_value[i];\n    }\n\n    // Structure to hold the difference between the perturbed error and unperturbed erro\n    union State partial_state_vector;\n\n    // Estimate partial derivative\n    for (i=0; i<stateIndex; i++)\n    {\n        double num = (delta_perturb_state.state_value[i] - delta_state.state_value[i]);\n        partial_state_vector.state_value[i] = num/h;\n    }\n\n    return partial_state_vector;\n    \n}\n\n// ------------UPDATE PARAMETERS----------//\n// Inverts the Jacobian and computes the parameter update\n\nunion Spline generateCorrection(union State veh, union State veh_next, union State goal, union Spline curvature, double dt, double horizon)\n{\n    // Compute jacobian with forward gradient\n    int i;\n    int stateIndex=3;\n    int j;\n\n    // Matrix J will contain the Jacobian\n    arma::mat J(stateIndex,stateIndex);\n\n    // Initialize it to zero\n    J.fill(0.0);\n\n    // Parameter perturbation vector\n    arma::vec h(stateIndex);\n\n    // How much to perturb each parameter\n    // Note h(0) is larger than others because it perturbs length ~20m\n    // Rather than kappa < ~.19 rad/m\n    h(0)= (double) h_global*10;\n    h(1)= (double) h_global;\n    h(2)= (double) h_global;\n\n    // For each parameter compute the vector associated with a small perturbation of its value\n    for (i=0; i<stateIndex; i++)\n    {\n        union State temp;\n        temp= pDerivEstimate(veh, veh_next, goal, curvature, i, h(i), dt, horizon, stateIndex);\n\n        // For each element of the state vector place the value in the Jacobian matrix (column-wise)\n        for (j=0; j<stateIndex; j++)\n        {\n            J(j,i) = temp.state_value[j]; \n        }\n    }\n    \n    // Put parameters in a vector\n    arma::vec dX(stateIndex);\n    dX.fill(0.0);\n    \n    for(i=0; i<stateIndex; i++)\n    {\n        dX(i) = goal.state_value[i]-veh_next.state_value[i];\n    }\n    \n    // Solve for delta P\n    // Note that we use a try catch routine as it is possible for J to be singular\n    arma::vec dP(stateIndex);\n    try\n    {\n        J=J.i();\n    }\n    catch(const std::exception& e)\n    {\n        curvature.success=FALSE;\n        return curvature;\n        cout<< \"goal.sx: \"<< goal.sx<<endl;\n        cout<< \"goal.sy: \"<< goal.sx<<endl;\n        cout<< \"goal.theta: \"<< goal.sx<<endl;\n    }\n\n    dP=J*dX;\n\n    // Update curvature parameters  \n    for(i=0; i<stateIndex; i++)\n    {\n        curvature.spline_value[i]=curvature.spline_value[i]-dP(i);\n    }\n\n    // Return new spline\n    return curvature;\n}\n\n// ------------NEXT STATE----------//\n// Computes update to vehicle state \n// for the purpose of control\n// Not called in local planner\n// INPUT: Current vehicle state, parameterized control inputs, sampling time\n// OUTPUT: Next vehicle state\n\nunion State nextState(union State veh, union Spline curvature, double vdes, double dt, double elapsedTime)\n{\n    union State veh_next;\n    union State veh_temp;\n    double total_time = elapsedTime + dt;\n    //cout<<\"total_time: \"<< total_time<<endl;\n    double t = 0.00;\n\n    veh_temp=veh;\n    \n    // Read state vector\n    double sx = veh_temp.sx;\n    double sy = veh_temp.sy;\n    double v = veh_temp.v;\n    double theta = veh_temp.theta;\n    double kappa = veh_temp.kappa;\n    double v_goal= vdes;\n\n    //cout<<\"Total sim time: \" << total_time << endl;\n\n    while(t <= total_time)\n    {\n      \n        // Compute change in 2D x-position (this is x_dot)\n        double sx_next = sx + (v * cos(theta) * dt);\n\n        veh_next.sx = sx_next;\n\n\n        // Compute change in 2D y-position (this is y_dot)\n        double sy_next = sy + (v * sin(theta) * dt);\n\n        veh_next.sy = sy_next;\n\n        // Compute change in 2D orientation (this is theta_dot)\n        double theta_next = theta + (v * kappa * dt);\n\n        veh_next.theta = theta_next;\n\n        // Get curvature command\n        double kappa_next = getCurvatureCommand(curvature, dt , veh.v,t);\n\n        veh_next.kappa = kappa_next;\n\n        // Get velocity command\n        double v_next = getVelocityCommand(v_goal, v);\n\n        veh_next.v = v_next;\n\n        // Get acceleration command\n        //double a_next_cmd = 0;\n\n\n        // Update the next vehicle state\n        veh_next = responseToControlInputs(veh, veh_next, dt);\n\n        // Increment the timestep\n        t=t+step_size;\n\n\n        // Update veh_temp\n        veh_temp=veh_next;\n    }\n    cout<<\"Exited the while loop t = \"<<t<<endl;\n    \n    return veh_next;\n}\n\n// plotTraj is used by rViz to compute points for line strip, \n// it is a lighter weight version of nextState\nunion State genLineStrip(union State veh, union Spline curvature, double vdes, double t)\n{\n    union State veh_next;\n    union State veh_temp;\n    double dt = plot_step_size;\n\n    veh_temp=veh;\n\n    // Read state vector\n    double sx = veh_temp.sx;\n    double sy = veh_temp.sy;\n    double v = veh_temp.v;\n    double theta = veh_temp.theta;\n    double kappa = veh_temp.kappa;\n    double v_goal= vdes;\n\n    // Compute change in 2D x-position (this is x_dot)\n    double sx_next = sx + (v * cos(theta) * dt);\n\n    veh_next.sx = sx_next;\n\n\n    // Compute change in 2D y-position (this is y_dot)\n    double sy_next = sy + (v * sin(theta) * dt);\n\n    veh_next.sy = sy_next;\n\n    // Compute change in 2D orientation (this is theta_dot)\n    double theta_next = theta + (v * kappa * dt);\n\n    veh_next.theta = theta_next;\n\n    // Get curvature command\n    double kappa_next = getCurvatureCommand(curvature, dt , veh.v, t);\n\n    veh_next.kappa = kappa_next;\n\n    // Get velocity command\n    double v_next = getVelocityCommand(v_goal, v);\n\n    veh_next.v = v_next;\n\n    // Get acceleration command\n    // double a_next_cmd = 0;\n\n\n    // Update the next vehicle state\n    veh_next = responseToControlInputs(veh, veh_next, dt);\n\n    // Update veh_temp\n    veh_temp=veh_next;\n\n\n    return veh_next;\n}\n\n//------------------MAIN FUNCTION AND HELPER FOR STANDALONE OPERATION------------------------//\n\n#ifdef STANDALONE\n\nunion Spline trajectoryGenerator(double sx, double sy, double theta, double v, double kappa)\n{\n\n#ifdef DEBUG\n    cout << \"Function: main()\"<< endl;\n#endif\n\n// Set velocity\n    double v_0=0.10;\n\n// Initialize convergence criteria to false\n    bool convergence = FALSE;\n\n\n// Set goal vector\n    union State goal;\n    goal.sx = sx;\n    goal.sy = sy;\n    goal.theta = theta;\n    goal.v = v;\n    goal.kappa = kappa;\n\n\n// Initialize and set current state vector\n    union State veh;\n    veh.sx = 0.0;\n    veh.sy = 0.0;\n    veh.theta = 0.0;\n    veh.v = v;\n    veh.kappa = 0.0;\n\n\n// Initialize next state\n    union State veh_next;\n    veh_next.sx = 0.0;\n    veh_next.sy = 0.0;\n    veh_next.theta = 0.0;\n    veh_next.v = 0.00;\n    veh_next.kappa = 0.0;\n\n\n// Initialize parameters as a function of init and goal vectors\n    union Spline curvature;\n    curvature = initParams(veh, goal);\n\n // Initialize iteration counter\n    int iteration = 0;\n\n// Set timestep\n    double dt = step_size;\n\n// While loop for computing trajectory parameters\n    while(convergence == FALSE && iteration<10)\n    {\n\n    // Set time horizon\n        double horizon = curvature.s/v_0;\n\n    // Run motion model\n        veh_next = motionModel(veh, goal, curvature, dt, horizon, 0);\n\n    // Determine convergence criteria\n        convergence = checkConvergence(veh_next, goal);\n\n    // If the motion model doesn't get us to the goal compute new parameters\n        if(convergence==FALSE)\n        {\n        // Update parameters\n            curvature = generateCorrection(veh, veh_next, goal, curvature, dt, horizon);\n            iteration++;\n            if(curvature.success==FALSE)\n            {\n                break;\n            }\n\n        #ifdef ONE_ITER\n            convergence = TRUE;\n        #endif\n        }    \n    }\n\n    if(convergence==FALSE)\n    {\n        cout << \"Not Converged\"<< endl;\n    }\n\n    else\n    {\n        cout << \"Converged in \"<<iteration<<\" iterations\"<< endl;\n\n    #ifdef LOG_OUTPUT\n    // Set time horizon\n        double horizon = curvature.s/v_0;\n    // Run motion model and log data for plotting\n        veh_next = motionModel(veh, goal, curvature, 0.1, horizon, 1);\n        fmm_sx<<\"0.0 \\n\";\n        fmm_sy<<\"0.0 \\n\";\n    #endif\n    }\n\n    return curvature;\n}\n\nint main(void)\n{\n// Open files for logging\n    fmm_sx.open(\"fmm_sx.dat\");\n    fmm_sy.open(\"fmm_sy.dat\");\n    fmm_v.open(\"fmm_v.dat\");\n    fmm_theta.open(\"fmm_theta.dat\");\n    fmm_kappa.open(\"fmm_kappa.dat\");\n\n    int i;\n    int j;\n    int k=0;\n    double sx = 1;\n    double sy = 1;\n    union Spline curvature;\n    \n    #ifdef GEN_PLOT_FILES\n    for(i=5; i<20; i++)\n    {\n        sx=i;\n        for(j=-50; j<50; j++)\n        {\n            if(abs(j)<i+10)\n            {\n                cout<<\"Trajectory Number: \"<<k<<endl;\n                sy=j;\n                double k_goal;\n                if(j<0)\n                {\n                    k_goal=0.15;\n                }\n                else\n                {\n                    k_goal=-0.15;\n                }\n                curvature = trajectoryGenerator(sx, sy, 0.0, 0.1, 0.0);\n                k++;\n            }   \n        }\n    }\n    #endif\n\ntrajectoryGenerator(33.7553, 2.04623, 0.0726169, 11.1111, 0.0);\n\n//Close files \n    fmm_sx.close();\n    fmm_sy.close();\n    fmm_v.close();\n    fmm_theta.close();\n    fmm_kappa.close();\n    \n    return 1;\n}\n\n#endif\n\n", "meta": {"hexsha": "b9548dfeeed5b51fb8d2a77af20e2efd540b3ce3", "size": 25733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core_planning/lattice_planner/lib/libtraj_gen.cpp", "max_stars_repo_name": "alanjclark/autoware.ai", "max_stars_repo_head_hexsha": "ba97edbbffb6f22e78912bf96400a59ef6a13daf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T10:25:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T19:55:16.000Z", "max_issues_repo_path": "ros/src/computing/planning/motion/packages/lattice_planner/lib/libtraj_gen.cpp", "max_issues_repo_name": "anhnv3991/autoware", "max_issues_repo_head_hexsha": "d5b2ed9dc309193c8a2a7c77a2b6c88104c28328", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2019-06-24T16:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T13:41:58.000Z", "max_forks_repo_path": "ros/src/computing/planning/motion/packages/lattice_planner/lib/libtraj_gen.cpp", "max_forks_repo_name": "anhnv3991/autoware", "max_forks_repo_head_hexsha": "d5b2ed9dc309193c8a2a7c77a2b6c88104c28328", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 101.0, "max_forks_repo_forks_event_min_datetime": "2020-05-29T07:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:49:55.000Z", "avg_line_length": 28.9134831461, "max_line_length": 170, "alphanum_fraction": 0.6255391909, "num_tokens": 6697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.023689468628428276, "lm_q1q2_score": 0.009828733191473657}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <map>\nstd::vector<std::pair<int, int> > conv0, conv1, conv2, conv3, conv4;\nstd::vector<std::pair<int, int> > pool01, pool12, pool23, pool34;\nstd::vector<std::pair<std::pair<int, int>, double> > deconv01, deconv12, deconv23, deconv34;\nstd::vector<float> positions;\n\nvoid InitializeFullIndicesCPP(const char* filename) {\n\tFILE* fp = fopen(filename, \"rb\");\n    int num = 4;\n    fread(&num, sizeof(int), 1, fp);\n    fread(&num, sizeof(int), 1, fp);\n    printf(\"%d\\n\", num);\n    conv0.resize(num);\n    fread(conv0.data(), sizeof(std::pair<int, int>), conv0.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    printf(\"%d\\n\", num);\n    conv1.resize(num);\n    fread(conv1.data(), sizeof(std::pair<int, int>), conv1.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    printf(\"%d\\n\", num);\n    conv2.resize(num);\n    fread(conv2.data(), sizeof(std::pair<int, int>), conv2.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    printf(\"%d\\n\", num);\n    conv3.resize(num);\n    fread(conv3.data(), sizeof(std::pair<int, int>), conv3.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    printf(\"%d\\n\", num);\n    conv4.resize(num);\n    fread(conv4.data(), sizeof(std::pair<int, int>), conv4.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    pool01.resize(num);\n    fread(pool01.data(), sizeof(std::pair<int, int>), pool01.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    pool12.resize(num);\n    fread(pool12.data(), sizeof(std::pair<int, int>), pool12.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    pool23.resize(num);\n    fread(pool23.data(), sizeof(std::pair<int, int>), pool23.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    pool34.resize(num);\n    fread(pool34.data(), sizeof(std::pair<int, int>), pool34.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    deconv01.resize(num);\n    fread(deconv01.data(), sizeof(std::pair<std::pair<int, int>, double>), deconv01.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    deconv12.resize(num);\n    fread(deconv12.data(), sizeof(std::pair<std::pair<int, int>, double>), deconv12.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    deconv23.resize(num);\n    fread(deconv23.data(), sizeof(std::pair<std::pair<int, int>, double>), deconv23.size(), fp);\n    fread(&num, sizeof(int), 1, fp);\n    deconv34.resize(num);\n    fread(deconv34.data(), sizeof(std::pair<std::pair<int, int>, double>), deconv34.size(), fp);\n    fclose(fp);\n\n    for (int i = 0; i < 4; ++i) {\n    \tauto& conv = (i == 0) ? deconv01 : ((i == 1) ? deconv12 : (i == 2 ? deconv23 : deconv34));\n    \tfor (int j = 0; j < (int)conv.size(); j += 4) {\n    \t\tint min_id = -1;\n    \t\tfor (int k = 0; k < 4; ++k) {\n    \t\t\tif (conv[j + k].first.first != -1 && (min_id == -1 || conv[j + k].second < conv[min_id].second)) {\n    \t\t\t\tmin_id = j + k;\n    \t\t\t}\n    \t\t}\n    \t\tif (min_id != -1) {\n    \t\t\tfor (int k = 0; k < 4; ++k) {\n    \t\t\t\tif (conv[j + k].first.first == -1) {\n    \t\t\t\t\tconv[j + k] = conv[min_id];\n    \t\t\t\t}\n    \t\t\t}\n    \t\t}\n    \t}\n    }\n}\n\nint GetNumConvIndicesCPP(int level) {\n\tauto& conv = (level == 0) ? conv0 : ((level == 1) ? conv1 : ((level == 2) ? conv2 : (level == 3 ? conv3 : conv4)));\n\treturn (int)conv.size();\n}\n\nint GetNumPoolIndicesCPP(int level) {\n\tlevel += 1;\n\tauto& conv = ((level == 1) ? conv1 : ((level == 2) ? conv2 : ((level == 3) ? conv3 : conv4)));\n\treturn (int)conv.size() / 9;\n}\n\nint GetNumDeconvIndicesCPP(int level) {\n\tauto& conv = (level == 0) ? deconv01 : ((level == 1) ? deconv12 : (level == 2 ? deconv23 : deconv34));\n\treturn (int)conv.size();\n}\n\nvoid GetConvIndicesCPP(void* indatav, int level, int rosy) {\n\tint* indices = (int*)indatav;\n\tauto& conv = (level == 0) ? conv0 : ((level == 1) ? conv1 : ((level == 2) ? conv2 : (level == 3 ? conv3 : conv4)));\n\tif (rosy == 1) {\n\t\tfor (int i = 0; i < (int)conv.size(); ++i) {\n\t\t\tindices[i] = conv[i].first;\n\t\t}\n\t} else {\n\t\tfor (int i = 0; i < (int)conv.size(); ++i) {\n\t\t\tfor (int dir = 0; dir < 4; ++dir) {\n\t\t\t\tindices[i * 4 + dir] = conv[i].first * 4 + (dir + conv[i].second) % 4;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid GetPoolIndicesCPP(void* indatav, int level, int rosy) {\n\tint num_pool = GetNumPoolIndicesCPP(level);\n\tint* indices = (int*)indatav;\n\tauto& pool = (level == 0) ? pool01 : ((level == 1) ? pool12 : (level == 2 ? pool23 : pool34));\n\tif (rosy == 1) {\n\t\tfor (int i = 0; i < (int)pool.size(); ++i) {\n\t\t\tint index = pool[i].first;\n\t\t\tindices[i] = index;\n\t\t}\n\t} else {\n\t\tfor (int i = 0; i < (int)pool.size(); ++i) {\n\t\t\tint offset = i * 4;\n\t\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\t\tint index = pool[i].first * 4 + (j + pool[i].second) % 4;\n\t\t\t\tindices[i * 4 + j] = index;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid GetPoolIndicesReverseCPP(void* indatav, int level, int rosy, int stride) {\n\tint num_pool = GetNumPoolIndicesCPP(level);\n\tstd::vector<int> count(num_pool, 0);\n\tint* indices = (int*)indatav;\n\n\tauto& pool = (level == 0) ? pool01 : ((level == 1) ? pool12 : pool23);\n\tif (rosy == 1) {\n\t\tfor (int i = 0; i < (int)pool.size(); ++i) {\n\t\t\tint index = pool[i].first;\n\t\t\tint& offset = count[pool[i].first];\n\t\t\tif (offset < stride) {\n\t\t\t\tindices[index * stride + offset] = i;\n\t\t\t\toffset += 1;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < num_pool; ++i) {\n\t\t\tint offset = count[i];\n\t\t\tint t = (offset == 0) ? (int)pool.size() : indices[i * stride + offset - 1];\n\t\t\tfor (int j = offset; j < stride; ++j) {\n\t\t\t\tindices[i * stride + j] = t;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int i = 0; i < (int)pool.size(); ++i) {\n\t\t\tint& offset = count[pool[i].first];\n\t\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\t\tint index = pool[i].first * 4 + (j + pool[i].second) % 4;\n\t\t\t\tif (offset < stride) {\n\t\t\t\t\tindices[index * stride + offset] = i * 4 + j;\n\t\t\t\t}\n\t\t\t}\n\t\t\toffset += 1;\n\t\t}\n\t\tfor (int i = 0; i < num_pool * 4; ++i) {\n\t\t\tint offset = count[i / 4];\n\t\t\tint t = (offset == 0) ? (int)pool.size() * 4 : indices[i * stride + offset - 1];\n\t\t\tfor (int j = offset; j < stride; ++j) {\n\t\t\t\tindices[i * stride + j] = t;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid GetDeconvIndicesCPP(void* indatav, int level, int rosy) {\n\tint* indices = (int*)indatav;\n\n\tauto& conv = (level == 0) ? deconv01 : ((level == 1) ? deconv12 : (level == 2 ? deconv23 : deconv34));\n\tint num_pool = GetNumPoolIndicesCPP(level);\n\tif (rosy == 1) {\n\t\tfor (int i = 0; i < (int)conv.size(); ++i) {\n\t\t\tint index = conv[i].first.first;\n\t\t\tindices[i] = index;\n\t\t}\n\t} else {\n\t\tfor (int i = 0; i < (int)conv.size(); ++i) {\n\t\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\t\tint index = conv[i].first.first * 4 + (j + conv[i].first.second) % 4;\n\t\t\t\tindices[i] = index;\n\t\t\t}\n\t\t}\n\t}\n}\n\nextern \"C\" {\n\nvoid InitializeTangentSpace(void* vertices, void* faces, void* nf, int num_v, int num_f, void* tangent_space) {\n\tauto V = Eigen::Map<Eigen::MatrixXf>((float*)vertices, 3, num_v);\n\tauto F = Eigen::Map<Eigen::MatrixXi>((int*)faces, 3, num_f);\n\tauto FN = Eigen::Map<Eigen::MatrixXf>((float*)nf, 3, num_f);\n\tfor (int i = 0; i < num_f; ++i) {\n\t\tEigen::Matrix3d p, q;\n\t\tEigen::Vector3f v1 = V.col(F(1, i)) - V.col(F(0, i));\n\t\tEigen::Vector3f v2 = V.col(F(2, i)) - V.col(F(0, i));\n\t\tEigen::Vector3f v3 = FN.col(i);\n\t\tp.col(0) = Eigen::Vector3d(v1[0], v1[1], v1[2]);\n\t\tp.col(1) = Eigen::Vector3d(v2[0], v2[1], v2[2]);\n\t\tp.col(2) = Eigen::Vector3d(v3[0], v3[1], v3[2]);\n\t\tq = p.inverse();\n\t\tdouble* triangle_space_f = ((double*)tangent_space) + 6 * i;\n\t\tfor (int j = 0; j < 2; ++j) {\n\t\t\tfor (int k = 0; k < 3; ++k) {\n\t\t\t\ttriangle_space_f[k * 2 + j] = q(j, k);\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nvoid ReadBaryCentry(void* bary_coords, void* bary_indices, const char* filename) {\n\tFILE* fp = fopen(filename, \"rb\");\n\tint num_C, num_I;\n\tfread(&num_C, sizeof(int), 1, fp);\n\tfread(&num_I, sizeof(int), 1, fp);\n\tfread(bary_coords, sizeof(float), 3 * num_C, fp);\n\tfread(bary_indices, sizeof(int), num_I, fp);\n\tfclose(fp);\n}\n\nvoid ComputeFacesInfo(void* fv, void* fn, void* v, void* f, int num_v, int num_f) {\n\tauto V = Eigen::Map<Eigen::MatrixXf>((float*)v, 3, num_v);\n\tauto F = Eigen::Map<Eigen::MatrixXi>((int*)f, 3, num_f);\n#pragma omp parallel for\n\tfor (int i = 0; i < num_f; ++i) {\n\t\tfloat* fv_f = ((float*)fv) + 3 * i;\n\t\tfloat* fn_f = ((float*)fn) + 3 * i;\n\t\tEigen::Vector3f FV = (V.col(F(0, i)) + V.col(F(1, i)) + V.col(F(2, i))) / 3.0f;\n\t\tEigen::Vector3f FN = (Eigen::Vector3f(V.col(F(1, i)) - V.col(F(0, i))).cross(Eigen::Vector3f(V.col(F(2, i)) - V.col(F(0, i))))).normalized();\n\t\tfv_f[0] = FV[0];\n\t\tfv_f[1] = FV[1];\n\t\tfv_f[2] = FV[2];\n\t\tfn_f[0] = FN[0];\n\t\tfn_f[1] = FN[1];\n\t\tfn_f[2] = FN[2];\n\t}\n}\n\nvoid InitializeE2E(void* vertices, void* faces, int num_v, int num_f, void* pE2E) {\n\tint* iE2E = (int*)pE2E;\n\tauto V = Eigen::Map<Eigen::MatrixXf>((float*)vertices, 3, num_v);\n\tauto F = Eigen::Map<Eigen::MatrixXi>((int*)faces, 3, num_f);\n\t//E2E = Eigen::VectorXi(num_f * 3);\n\tstd::map<std::pair<int, int>, int > dedgeid;\n\tfor (int i = 0; i < num_f; ++i) {\n\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\tiE2E[i * 3 + j] = -1;\n\t\t\tint x = F(j, i);\n\t\t\tint y = F((j + 1) % 3, i);\n\t\t\tauto key = std::make_pair(x, y);\n\t\t\tauto reverse_key = std::make_pair(y, x);\n\t\t\tif (dedgeid.count(reverse_key)) {\n\t\t\t\tint deid = dedgeid[reverse_key];\n\t\t\t\tiE2E[i * 3 + j] = deid;\n\t\t\t\tiE2E[deid] = i * 3 + j;\n\t\t\t\tdedgeid.erase(reverse_key);\n\t\t\t} else {\n\t\t\t\tdedgeid[key] = i * 3 + j;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid IndexPool(const void * indatav, int inlen, void * outdatav, int outlen, int invalid_idx) {\n\tint* input = (int*)indatav;\n\tint* output = (int*)outdatav;\n\tfor (int i = 0; i < inlen; ++i) {\n\t\tint next_index = input[i] * 4;\n\t\twhile (output[next_index] != -1)\n\t\t\tnext_index += 1;\n\t\toutput[next_index] = i;\n\t}\n\n\tfor (int i = 0; i < outlen; i += 4) {\n\t\tif (output[i] == -1)\n\t\t\toutput[i] = invalid_idx;\n\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\tif (output[i + j + 1] == -1)\n\t\t\t\toutput[i + j + 1] = output[i + j];\n\t\t}\n\t}\n}\n\nvoid IndexLabel(const void* indatav, int inlen, void* outdatav, int outlen, int invalid_idx) {\n\tint* input = (int*)indatav;\n\tint* output = (int*)outdatav;\n\tint top = 0;\n\tfor (int i = 0; i < inlen; ++i) {\n\t\tif (input[i] != invalid_idx) {\n\t\t\toutput[top++] = i;\n\t\t}\n\t}\n}\n\nvoid ReadDialateIndices(void* indatav, const char* filename, int size) {\n\tint t;\n\tFILE* fp = fopen(filename, \"rb\");\n\tfread(&t, sizeof(int), 1, fp);\n\tfread(indatav, sizeof(int), size, fp);\n\tfclose(fp);\n}\n\nvoid ReadArray(void* indatav, const char* filename, int size, int stride) {\n\tFILE* fp = fopen(filename, \"rb\");\n\tfread(indatav, stride, size, fp);\n\tfclose(fp);\n}\n\nint ReadOBJVertices(const char* filename) {\n\tpositions.clear();\n\tpositions.reserve(65536);\n\tstd::ifstream is(filename);\n\tchar c;\n\twhile (is >> c) {\n\t\tif (c != 'v')\n\t\t\tbreak;\n\t\tfloat x, y, z;\n\t\tis >> x >> y >> z;\n\t\tpositions.push_back(x);\n\t\tpositions.push_back(y);\n\t\tpositions.push_back(z);\n\t}\n\treturn positions.size() / 3;\n}\n\nvoid CopyOBJVertices(void* pvertices) {\n\tmemcpy(pvertices, positions.data(), sizeof(float) * positions.size());\n}\n\nvoid InitializeFullIndices(const char* filename) {\n\tInitializeFullIndicesCPP(filename);\n}\n\nint GetLevels() {\n\treturn 4;\n}\n\nint GetNumConvIndices(int level) {\n\treturn GetNumConvIndicesCPP(level);\n}\n\nint GetNumPoolIndices(int level) {\n\treturn GetNumPoolIndicesCPP(level);\n}\n\nint GetNumDeconvIndices(int level) {\n\treturn GetNumDeconvIndicesCPP(level);\n}\n\nvoid GetConvIndices(void* indatav, int level, int rosy) {\n\tGetConvIndicesCPP(indatav, level, rosy);\n}\n\nvoid GetPoolIndices(void* indatav, int level, int rosy) {\n\tGetPoolIndicesCPP(indatav, level, rosy);\n}\n\nvoid GetDeconvIndices(void* indatav, int level, int rosy) {\n\tGetDeconvIndicesCPP(indatav, level, rosy);\n}\n\n\n}\n", "meta": {"hexsha": "f2f77327a724cd54910ba2d40c9f5158b7405f52", "size": 11440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/fastio.cpp", "max_stars_repo_name": "hjwdzh/TextureNet", "max_stars_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2019-03-30T03:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T05:16:51.000Z", "max_issues_repo_path": "data/fastio.cpp", "max_issues_repo_name": "jtpils/TextureNet", "max_issues_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-29T11:21:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T04:09:41.000Z", "max_forks_repo_path": "data/fastio.cpp", "max_forks_repo_name": "jtpils/TextureNet", "max_forks_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-04-12T01:20:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T16:10:33.000Z", "avg_line_length": 30.5066666667, "max_line_length": 143, "alphanum_fraction": 0.5783216783, "num_tokens": 4094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.02096423936537577, "lm_q1q2_score": 0.009827838908837074}}
{"text": "/**\n * Copyright (c) 2018, University Osnabrück\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 University Osnabrück 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 University Osnabrück 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 * GraphSLAM.cpp\n *\n *  @date July 22, 2019\n *  @author Malte Hillmann\n */\n#include \"lvr2/registration/GraphSLAM.hpp\"\n\n#include <Eigen/SparseCholesky>\n\n#include <math.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace lvr2\n{\n\n/**\n * @brief Lists all numbers of scans near to the scan \n * @param scans reference to a vector containing the SlamScanPtr\n * @param scan number of the current scan\n * @param options SlamOptions struct with all params\n * @param output Returns vector of the scan-numbers which ar defined as \"close\" \n * */\nbool findCloseScans(const vector<SLAMScanPtr>& scans, size_t scan, const SLAMOptions& options, vector<size_t>& output)\n{\n    if (scan < options.loopSize)\n    {\n        return false;\n    }\n\n    const SLAMScanPtr& cur = scans[scan];\n\n    // closeLoopPairs not specified => use closeLoopDistance\n    if (options.closeLoopPairs < 0)\n    {\n        double maxDist = std::pow(options.closeLoopDistance, 2);\n        Vector3d pos = cur->getPosition();\n        for (size_t other = 0; other < scan - options.loopSize; other++)\n        {\n            if ((scans[other]->getPosition() - pos).squaredNorm() < maxDist)\n            {\n                output.push_back(other);\n            }\n        }\n    }\n    else\n    {\n        // convert current Scan to KDTree for Pair search\n        auto tree = KDTree::create(cur, options.maxLeafSize);\n\n        size_t maxLen = 0;\n        for (size_t other = 0; other < scan - options.loopSize; other++)\n        {\n            maxLen = max(maxLen, scans[other]->numPoints());\n        }\n        KDTree::Neighbor* neighbors = new KDTree::Neighbor[maxLen];\n\n        for (size_t other = 0; other < scan - options.loopSize; other++)\n        {\n            size_t count = KDTree::nearestNeighbors(tree, scans[other], neighbors, options.slamMaxDistance);\n            if (count >= options.closeLoopPairs)\n            {\n                output.push_back(other);\n            }\n        }\n\n        delete[] neighbors;\n    }\n\n    return !output.empty();\n}\n\n\n/**\n * Conversion from Pose to Matrix representation in GraphSLAMs internally consistent Coordinate System\n * \n * @brief Conversion from Pose to Matrix representation\n * */\nvoid EulerToMatrix4(const Vector3d& pos, const Vector3d& theta, Matrix4d& mat);\n\n/**\n * Conversion from Matrix to Pose representation in GraphSLAMs internally consistent Coordinate System\n * \n * @brief Conversion from Matrix to Pose representation\n * */\nvoid Matrix4ToEuler(const Matrix4d mat, Vector3d& rPosTheta, Vector3d& rPos);\n\nGraphSLAM::GraphSLAM(const SLAMOptions* options)\n    : m_options(options)\n{\n}\n\nvoid GraphSLAM::doGraphSLAM(const vector<SLAMScanPtr>& scans, size_t last, const std::vector<bool>& new_scans) const\n{\n    // ignore first scan, keep last scan => n = last - 1 + 1\n    size_t n = last;\n\n    Graph graph;\n    graph.reserve(n * n / 2);\n\n    GraphMatrix A(6 * n, 6 * n);\n    GraphVector B(6 * n);\n    GraphVector X(6 * n);\n\n    for (size_t iteration = 0;\n            iteration < m_options->slamIterations;\n            iteration++)\n    {\n        cout << \"GraphSLAM Iteration \" << iteration << \" of \" << m_options->slamIterations << endl;\n\n        createGraph(scans, last, graph);\n\n        // Construct the linear equation system A * X = B..\n        fillEquation(scans, graph, A, B);\n\n        graph.clear();\n\n        X = SimplicialCholesky<GraphMatrix>().compute(A).solve(B);\n\n        double sum_position_diff = 0.0;\n\n        // Start with second Scan\n        #pragma omp parallel for reduction(+:sum_position_diff) schedule(static)\n        for (size_t i = 1; i <= last; i++)\n        {\n            if (new_scans.empty() || new_scans.at(i))\n            {\n                const SLAMScanPtr& scan = scans[i];\n\n                // Now update the Poses\n                Matrix6d Ha = Matrix6d::Identity();\n\n                Matrix4d initialPose = scan->pose();\n                Vector3d pos, theta;\n                Matrix4ToEuler(initialPose, theta, pos);\n                if (m_options->verbose)\n                {\n                    cout << \"Start of \" << i << \": \" << pos.transpose() << \", \" << theta.transpose() << endl;\n                }\n\n                double ctx, stx, cty, sty;\n\n#ifndef __APPLE__\n                sincos(theta.x(), &stx, &ctx);\n                sincos(theta.y(), &sty, &cty);\n#else\n                __sincos(theta.x(), &stx, &ctx);\n                __sincos(theta.y(), &sty, &cty);\n#endif\n\n                // Fill Ha\n                Ha(0, 4) = -pos.z() * ctx + pos.y() * stx;\n                Ha(0, 5) = pos.y() * cty * ctx + pos.z() * stx * cty;\n\n                Ha(1, 3) = pos.z();\n                Ha(1, 4) = -pos.x() * stx;\n                Ha(1, 5) = -pos.x() * ctx * cty + pos.z() * sty;\n\n\n                Ha(2, 3) = -pos.y();\n                Ha(2, 4) = pos.x() * ctx;\n                Ha(2, 5) = -pos.x() * cty * stx - pos.y() * sty;\n\n                Ha(3, 5) = sty;\n\n                Ha(4, 4) = stx;\n                Ha(4, 5) = ctx * cty;\n\n                Ha(5, 4) = ctx;\n                Ha(5, 5) = -stx * cty;\n\n                // Correct pose estimate\n                Vector6d result = Ha.inverse() * X.block<6, 1>((i - 1) * 6, 0);\n\n                // Update the Pose\n                pos -= result.block<3, 1>(0, 0);\n                theta -= result.block<3, 1>(3, 0);\n                Matrix4d transform;\n                EulerToMatrix4(pos, theta, transform);\n\n                if (m_options->verbose)\n                {\n                    cout << \"End: pos: \" << pos.transpose() << \",\" << endl << \"theta: \" << theta.transpose() << endl;\n                }\n\n                transform = transform * initialPose.inverse();\n\n                scan->transform(transform, m_options->createFrames, FrameUse::GRAPHSLAM);\n\n                sum_position_diff += result.block<3, 1>(0, 0).norm();\n            }\n        }\n\n        if (m_options->createFrames)\n        {\n            // add Frames to unused Scans\n            scans[0]->addFrame(FrameUse::GRAPHSLAM);\n            for (size_t i = last + 1; i < scans.size(); i++)\n            {\n                scans[i]->addFrame(FrameUse::INVALID);\n            }\n        }\n\n        cout << \"Sum of Position differences = \" << sum_position_diff << endl;\n\n        double avg = sum_position_diff / n;\n        if (avg < m_options->slamEpsilon)\n        {\n            break;\n        }\n    }\n}\n\nvoid GraphSLAM::createGraph(const vector<SLAMScanPtr>& scans, size_t last, Graph& graph) const\n{\n    graph.clear();\n\n    for (size_t i = 1; i <= last; i++)\n    {\n        graph.push_back(make_pair(i - 1, i));\n    }\n\n    vector<size_t> others;\n    for (size_t i = m_options->loopSize; i <= last; i++)\n    {\n        findCloseScans(scans, i, *m_options, others);\n\n        for (size_t other : others)\n        {\n            graph.push_back(make_pair(other, i));\n        }\n\n        others.clear();\n    }\n}\n\nvoid GraphSLAM::fillEquation(const vector<SLAMScanPtr>& scans, const Graph& graph, GraphMatrix& mat, GraphVector& vec) const\n{\n    // Cache all KDTrees\n    map<size_t, KDTreePtr> trees;\n    for (size_t i = 0; i < graph.size(); i++)\n    {\n        size_t a = graph[i].first;\n        if (trees.find(a) == trees.end())\n        {\n            auto tree = KDTree::create(scans[a], m_options->maxLeafSize);\n            trees.insert(make_pair(a, tree));\n        }\n    }\n\n    vector<pair<Matrix6d, Vector6d>> coeff(graph.size());\n\n    #pragma omp parallel for schedule(dynamic)\n    for (size_t i = 0; i < graph.size(); i++)\n    {\n        int a, b;\n        std::tie(a, b) = graph[i];\n\n        KDTreePtr tree  = trees[a];\n        SLAMScanPtr scan = scans[b];\n\n        Matrix6d coeffMat;\n        Vector6d coeffVec;\n        eulerCovariance(tree, scan, coeffMat, coeffVec);\n\n        coeff[i] = make_pair(coeffMat, coeffVec);\n    }\n\n    trees.clear();\n\n    map<pair<int, int>, Matrix6d> result;\n\n    mat.setZero();\n    vec.setZero();\n\n    for (size_t i = 0; i < graph.size(); i++)\n    {\n        int a, b;\n        std::tie(a, b) = graph[i];\n\n        Matrix6d coeffMat;\n        Vector6d coeffVec;\n        std::tie(coeffMat, coeffVec) = coeff[i];\n\n        // first scan is not part of Matrix => ignore any a or b of 0\n\n        int offsetA = (a - 1) * 6;\n        int offsetB = (b - 1) * 6;\n\n        if (offsetA >= 0)\n        {\n            vec.block<6, 1>(offsetA, 0) += coeffVec;\n            auto key = make_pair(offsetA, offsetA);\n            auto found = result.find(key);\n            if (found == result.end())\n            {\n                result.insert(make_pair(key, coeffMat));\n            }\n            else\n            {\n                found->second += coeffMat;\n            }\n        }\n        if (offsetB >= 0)\n        {\n            vec.block<6, 1>(offsetB, 0) -= coeffVec;\n            auto key = make_pair(offsetB, offsetB);\n            auto found = result.find(key);\n            if (found == result.end())\n            {\n                result.insert(make_pair(key, coeffMat));\n            }\n            else\n            {\n                found->second += coeffMat;\n            }\n        }\n        if (offsetA >= 0 && offsetB >= 0)\n        {\n            auto key = make_pair(offsetA, offsetB);\n            auto found = result.find(key);\n            if (found == result.end())\n            {\n                result.insert(make_pair(key, -coeffMat));\n            }\n            else\n            {\n                found->second -= coeffMat;\n            }\n\n            key = make_pair(offsetB, offsetA);\n            found = result.find(key);\n            if (found == result.end())\n            {\n                result.insert(make_pair(key, -coeffMat));\n            }\n            else\n            {\n                found->second -= coeffMat;\n            }\n        }\n    }\n\n    vector<Triplet<double>> triplets;\n    triplets.reserve(result.size() * 6 * 6);\n\n    int x, y;\n    for (auto& e : result)\n    {\n        tie(x, y) = e.first;\n        Matrix6d& m = e.second;\n        for (int dx = 0; dx < 6; dx++)\n        {\n            for (int dy = 0; dy < 6; dy++)\n            {\n                triplets.push_back(Triplet<double>(x + dx, y + dy, m(dx, dy)));\n            }\n        }\n    }\n    mat.setFromTriplets(triplets.begin(), triplets.end());\n}\n\nvoid GraphSLAM::eulerCovariance(KDTreePtr tree, SLAMScanPtr scan, Matrix6d& outMat, Vector6d& outVec) const\n{\n    size_t n = scan->numPoints();\n\n    KDTree::Neighbor* results = new KDTree::Neighbor[n];\n\n    size_t pairs = KDTree::nearestNeighbors(tree, scan, results, m_options->slamMaxDistance);\n\n    Vector6d mz = Vector6d::Zero();\n    Vector3d sum = Vector3d::Zero();\n    double xy, yz, xz, ypz, xpz, xpy;\n    xy = yz = xz = ypz = xpz = xpy = 0.0;\n\n    for (size_t i = 0; i < n; i++)\n    {\n        if (results[i] == nullptr)\n        {\n            continue;\n        }\n\n        Vector3d p = scan->point(i).cast<double>();\n        Vector3d r = results[i]->cast<double>();\n\n        Vector3d mid = (p + r) / 2.0;\n        Vector3d d = r - p;\n\n        double x = mid.x(), y = mid.y(), z = mid.z();\n\n        sum += mid;\n\n        xpy += x * x + y * y;\n        xpz += x * x + z * z;\n        ypz += y * y + z * z;\n\n        xy += x * y;\n        xz += x * z;\n        yz += y * z;\n\n        mz.block<3, 1>(0, 0) += d;\n\n        mz(3) += -z * d.y() + y * d.z();\n        mz(4) += -y * d.x() + x * d.y();\n        mz(5) += z * d.x() - x * d.z();\n    }\n\n    Matrix6d mm = Matrix6d::Zero();\n    mm(0, 0) = mm(1, 1) = mm(2, 2) = pairs;\n    mm(3, 3) = ypz;\n    mm(4, 4) = xpy;\n    mm(5, 5) = xpz;\n\n    mm(0, 4) = mm(4, 0) = -sum.y();\n    mm(0, 5) = mm(5, 0) = sum.z();\n    mm(1, 3) = mm(3, 1) = -sum.z();\n    mm(1, 4) = mm(4, 1) = sum.x();\n    mm(2, 3) = mm(3, 2) = sum.y();\n    mm(2, 5) = mm(5, 2) = -sum.x();\n\n    mm(3, 4) = mm(4, 3) = -xz;\n    mm(3, 5) = mm(5, 3) = -xy;\n    mm(4, 5) = mm(5, 4) = -yz;\n\n    Vector6d d = mm.inverse() * mz;\n\n    double ss = 0.0;\n\n    for (size_t i = 0; i < n; i++)\n    {\n        if (results[i] == nullptr)\n        {\n            continue;\n        }\n\n        Vector3d p = scan->point(i).cast<double>();\n        Vector3d r = results[i]->cast<double>();\n\n        Vector3d mid = (p + r) / 2.0;\n        Vector3d delta = r - p;\n\n        ss += pow(delta.x() + (d(0) - mid.y() * d(4) + mid.z() * d(5)), 2.0)\n              + pow(delta.y() + (d(1) - mid.z() * d(3) + mid.x() * d(4)), 2.0)\n              + pow(delta.z() + (d(2) + mid.y() * d(3) - mid.x() * d(5)), 2.0);\n    }\n\n    delete[] results;\n\n    ss = ss / (2.0 * pairs - 3.0);\n\n    ss = 1.0 / ss;\n\n    outMat = mm * ss;\n    outVec = mz * ss;\n}\n\nvoid EulerToMatrix4(const Vector3d& pos,\n                    const Vector3d& theta,\n                    Matrix4d& mat)\n{\n    double sx = sin(theta[0]);\n    double cx = cos(theta[0]);\n    double sy = sin(theta[1]);\n    double cy = cos(theta[1]);\n    double sz = sin(theta[2]);\n    double cz = cos(theta[2]);\n\n    mat << cy* cz,\n        sx* sy* cz + cx* sz,\n        -cx* sy* cz + sx* sz,\n        0.0,\n        -cy* sz,\n        -sx* sy* sz + cx* cz,\n        cx* sy* sz + sx* cz,\n        0.0,\n        sy,\n        -sx* cy,\n        cx* cy,\n\n        0.0,\n\n        pos[0],\n        pos[1],\n        pos[2],\n        1;\n\n    mat.transposeInPlace();\n}\n\nvoid Matrix4ToEuler(const Matrix4d inputMat,\n                    Vector3d& rPosTheta,\n                    Vector3d& rPos)\n{\n    Matrix4d mat = inputMat.transpose();\n\n    double _trX, _trY;\n\n    // Calculate Y-axis angle\n    rPosTheta[1] = asin(max(-1.0, min(1.0, mat(2, 0)))); // asin returns nan for any number outside [-1, 1]\n    if (mat(0, 0) <= 0.0)\n    {\n        rPosTheta[1] = M_PI - rPosTheta[1];\n    }\n\n    double C = cos(rPosTheta[1]);\n    if (fabs( C ) > 0.005)                    // Gimbal lock?\n    {\n        _trX      =  mat(2, 2) / C;             // No, so get X-axis angle\n        _trY      =  -mat(2, 1) / C;\n        rPosTheta[0]  = atan2( _trY, _trX );\n        _trX      =  mat(0, 0) / C;              // Get Z-axis angle\n        _trY      = -mat(1, 0) / C;\n        rPosTheta[2]  = atan2( _trY, _trX );\n    }\n    else                                        // Gimbal lock has occurred\n    {\n        rPosTheta[0] = 0.0;                       // Set X-axis angle to zero\n        _trX      =  mat(1, 1);  //1                // And calculate Z-axis angle\n        _trY      =  mat(0, 1);  //2\n        rPosTheta[2]  = atan2( _trY, _trX );\n    }\n\n    rPos = inputMat.block<3, 1>(0, 3);\n}\n\n} /* namespace lvr2 */\n", "meta": {"hexsha": "00f58cb4383cfe40e4e2c7b24f4f7688f237e468", "size": 15921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liblvr2/registration/GraphSLAM.cpp", "max_stars_repo_name": "uos/lvr", "max_stars_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-06-19T15:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:08:24.000Z", "max_issues_repo_path": "src/liblvr2/registration/GraphSLAM.cpp", "max_issues_repo_name": "uos/lvr", "max_issues_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:31:25.000Z", "max_forks_repo_path": "src/liblvr2/registration/GraphSLAM.cpp", "max_forks_repo_name": "uos/lvr", "max_forks_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-04-16T11:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T07:47:44.000Z", "avg_line_length": 28.6348920863, "max_line_length": 124, "alphanum_fraction": 0.5122165693, "num_tokens": 4479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.02758528522464313, "lm_q1q2_score": 0.00981415191334053}}
{"text": "#include \"stdafx.h\"\r\n#include <iostream>\r\n#include <boost/format.hpp>\r\n\r\n#include \"api.h\"\r\n#include \"api_helpers.hpp\"\r\n#include \"hpgl_core.h\"\r\n#include \"sugarbox_grid.h\"\r\n#include \"ok_params.h\"\r\n#include \"sk_params.h\"\r\n#include \"sgs_params.h\"\r\n#include \"ik_params.h\"\r\n#include \"median_ik.h\"\r\n#include \"property_writer.h\"\r\n#include \"progress_reporter.h\"\r\n#include \"hpgl_exception.h\"\r\n#include \"output.h\"\r\n\r\nstatic void init_cov_param(hpgl::covariance_param_t * cp, hpgl_cov_params_t * params)\r\n{\r\n\tfor (int i = 0; i < 3; ++i)\r\n\t{\r\n\t\tcp->m_ranges[i] = params->m_ranges[i];\r\n\t\tcp->m_angles[i] = params->m_angles[i];\r\n\t}\r\n\tcp->m_sill = params->m_sill;\r\n\tcp->m_nugget = params->m_nugget;\r\n\tcp->m_covariance_type = (hpgl::covariance_type_t) params->m_covariance_type;\t\r\n}\r\n\r\nstatic void \r\nhandle_exception(const std::exception & ex)\r\n{\r\n\thpgl::set_last_exception_message(ex.what());\r\n}\r\n\r\nextern \"C\" {\r\n\r\nHPGL_API char * hpgl_get_last_exception_message()\r\n{\r\n\treturn (char *) hpgl::get_last_exception_message().c_str();\r\n}\r\n\r\nHPGL_API void hpgl_set_thread_num(int n_threads)\r\n{\r\n\thpgl::set_thread_num(n_threads);\r\n}\r\n\r\nHPGL_API int hpgl_get_thread_num()\r\n{\r\n\treturn hpgl::get_thread_num();\r\n}\r\n\r\nHPGL_API void hpgl_read_inc_file_float(\r\n\t\tchar * filename,\r\n\t\tfloat undefined_value,\r\n\t\tint size,\r\n\t\tfloat * data,\r\n\t\tunsigned char * mask)\r\n{\r\n\thpgl::read_inc_file_float(\r\n\t\t\tfilename,\r\n\t\t\tundefined_value,\r\n\t\t\tsize,\r\n\t\t\tdata,\r\n\t\t\tmask);\r\n}\r\n\r\nHPGL_API void hpgl_read_inc_file_byte(\r\n\t\tchar * filename,\r\n\t\tint undefined_value,\r\n\t\tint size,\r\n\t\tunsigned char * data,\r\n\t\tunsigned char * mask,\r\n\t\tunsigned char * values,\r\n\t\tint values_count)\r\n{\r\n\thpgl::read_inc_file_byte(\r\n\t\t\tfilename,\r\n\t\t\tundefined_value,\r\n\t\t\tsize,\r\n\t\t\tdata,\r\n\t\t\tmask);\r\n\r\n\tfor (int i = 0; i < size; ++i)\r\n\t{\r\n\t\tif (mask[i] != 0)\r\n\t\t{\r\n\t\t\tfor (int j = 0; j < values_count; ++j)\r\n\t\t\t{\r\n\t\t\t\tif (data[i] == values[j])\r\n\t\t\t\t{\r\n\t\t\t\t\tdata[i] = j;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nHPGL_API void hpgl_write_inc_file_float(\r\n\t\tchar * filename,\r\n\t\thpgl_cont_masked_array_t * arr,\r\n\t\tfloat undefined_value,\r\n\t\tchar * name)\r\n{\r\n\tusing namespace hpgl;\r\n\tproperty_writer_t writer;\r\n\twriter.init(filename, name);\r\n\tcont_property_array_t prop(\r\n\t\t\tarr->m_data, \r\n\t\t\tarr->m_mask,\r\n\t\t\tget_shape_volume(&(arr->m_shape)));\r\n\twriter.write_double(prop, undefined_value);\r\n}\r\n\r\nvoid init_remap_table(unsigned char * values, int values_count, int indicator_count, std::vector<unsigned char> & remap_table)\r\n{\r\n\tusing namespace boost;\r\n\tif (values_count == indicator_count)\r\n\t{\r\n\t\tremap_table.assign(values, values+values_count);\r\n\t}\r\n\telse if (values_count > indicator_count)\r\n\t{\r\n\t\tLOGWARNING(format(\"Given %1% values for %2% indicators. Ignoring extra values.\\n\") % values_count % indicator_count);\r\n\t\tremap_table.assign(values, values + indicator_count);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif (values_count > 0)\r\n\t\t\tLOGWARNING(format(\"Warning: Given %1% values for %2% indicators. Ignoring values. Using [0, 1, 2 ..]\\n\") % values_count % indicator_count);\r\n\t\tfor (int i = 0; i < indicator_count; ++i)\r\n\t\t\tremap_table.push_back(i);\r\n\t}\r\n}\r\n\r\nHPGL_API void hpgl_write_inc_file_byte(\r\n\t\tchar * filename,\r\n\t\thpgl_ind_masked_array_t * arr,\r\n\t\tint undefined_value,\t\t\r\n\t\tchar * name,\r\n\t\tunsigned char * values,\r\n\t\tint values_count)\r\n{\r\n\tusing namespace hpgl;\r\n\tstd::vector<unsigned char> remap_table;\r\n\tinit_remap_table(values, values_count, arr->m_indicator_count, remap_table);\r\n\r\n\tproperty_writer_t writer;\r\n\twriter.init(filename, name);\r\n\tindicator_property_array_t prop(\r\n\t\t\tarr->m_data, \r\n\t\t\tarr->m_mask, \r\n\t\t\tget_shape_volume(&(arr->m_shape)),\r\n\t\t\tarr->m_indicator_count);\r\n\twriter.write_byte(prop, undefined_value, remap_table);\r\n}\r\n\r\nHPGL_API void\r\nhpgl_write_gslib_cont_property(\r\n\t\thpgl_cont_masked_array_t * data,\r\n\t\tconst char * filename,\r\n\t\tconst char * name,\r\n\t\tdouble undefined_value)\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&data->m_shape);\r\n\tsp_double_property_array_t prop(new cont_property_array_t(data->m_data, data->m_mask, size));\r\n\thpgl::property_writer_t writer;\r\n\twriter.init(filename, name);\r\n\twriter.write_gslib_double(prop, undefined_value);\r\n}\r\n\r\nHPGL_API void\r\nhpgl_write_gslib_byte_property(\r\n\t\thpgl_ind_masked_array_t * data,\r\n\t\tconst char * filename,\r\n\t\tconst char * name,\r\n\t\tdouble undefined_value,\r\n\t\tunsigned char * values,\r\n\t\tint values_count)\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&data->m_shape);\r\n\tsp_byte_property_array_t prop( new indicator_property_array_t(data->m_data, data->m_mask, size, data->m_indicator_count));\r\n\tstd::vector<unsigned char> remap_table;\r\n\tinit_remap_table(values, values_count, data->m_indicator_count, remap_table);\r\n\r\n\tproperty_writer_t writer;\r\n\twriter.init(filename, name);\r\n\twriter.write_gslib_byte(prop, (unsigned char)undefined_value, remap_table);\r\n}\r\n\r\nHPGL_API void hpgl_ordinary_kriging(\r\n    hpgl_cont_masked_array_t * input_data,\r\n    hpgl_ok_params_t * params,\r\n    hpgl_cont_masked_array_t * output_data)\r\n{\r\n\tusing namespace hpgl;\r\n\tint in_size = get_shape_volume(&input_data->m_shape);\r\n\tint out_size = get_shape_volume(&output_data->m_shape);\r\n\t\t\r\n\tcont_property_array_t in_prop(input_data->m_data, input_data->m_mask, in_size);\r\n\tcont_property_array_t out_prop(output_data->m_data, output_data->m_mask, out_size);\r\n\t\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &input_data->m_shape);\r\n\r\n\tok_params_t ok_p;\r\n\tok_p.m_covariance_type = (covariance_type_t) params->m_covariance_type;\r\n\tok_p.set_ranges(\r\n\t\t\tparams->m_ranges[0],\r\n\t\t\tparams->m_ranges[1],\r\n\t\t\tparams->m_ranges[2]);\r\n\tok_p.set_angles(\r\n\t\t\tparams->m_angles[0],\r\n\t\t\tparams->m_angles[1],\r\n\t\t\tparams->m_angles[2]);\r\n\tok_p.m_sill = params->m_sill;\r\n\tok_p.m_nugget = params->m_nugget;\r\n\t\r\n\tok_p.set_radiuses(\r\n\t\t\tparams->m_radiuses[0],\r\n\t\t\tparams->m_radiuses[1],\r\n\t\t\tparams->m_radiuses[2]);\r\n\r\n\tok_p.m_max_neighbours = params->m_max_neighbours;\r\n\r\n\thpgl::ordinary_kriging(in_prop, grid, ok_p, out_prop, true);\r\n}\r\n\r\nstatic void init_sk_params(hpgl_sk_params_t * params, hpgl::sk_params_t & sk_p)\r\n{\r\n\tusing namespace hpgl;\r\n\tsk_p.m_covariance_type = (covariance_type_t) params->m_covariance_type;\r\n\tsk_p.set_ranges(\r\n\t\t\tparams->m_ranges[0],\r\n\t\t\tparams->m_ranges[1],\r\n\t\t\tparams->m_ranges[2]);\r\n\tsk_p.set_angles(\r\n\t\t\tparams->m_angles[0],\r\n\t\t\tparams->m_angles[1],\r\n\t\t\tparams->m_angles[2]);\r\n\tsk_p.m_sill = params->m_sill;\r\n\tsk_p.m_nugget = params->m_nugget;\r\n\t\r\n\tsk_p.set_radiuses(\r\n\t\t\tparams->m_radiuses[0],\r\n\t\t\tparams->m_radiuses[1],\r\n\t\t\tparams->m_radiuses[2]);\r\n\r\n\tsk_p.m_max_neighbours = params->m_max_neighbours;\r\n\r\n\tif (!params->m_automatic_mean)\r\n\t{\r\n\t\tsk_p.set_mean(params->m_mean);\r\n\t}\r\n}\r\n\r\nHPGL_API void hpgl_simple_kriging(   \r\n    float * input_data,\r\n    unsigned char * input_mask,\r\n    hpgl_shape_t * input_data_shape,\r\n    hpgl_sk_params_t * params,\r\n    float * output_data,\r\n    unsigned char * output_mask,\r\n    hpgl_shape_t * output_data_shape)\r\n{\r\n\tusing namespace hpgl;\r\n\tint in_size = input_data_shape->m_data[0] * input_data_shape->m_data[1] * input_data_shape->m_data[2];\r\n\tint out_size = output_data_shape->m_data[0] * output_data_shape->m_data[1] * output_data_shape->m_data[2];\r\n\t\t\r\n\tcont_property_array_t in_prop(input_data, input_mask, in_size);\r\n\tcont_property_array_t out_prop(output_data, output_mask, out_size);\r\n\t\r\n\tsugarbox_grid_t grid;\r\n\tgrid.init(\r\n\t\t\tinput_data_shape->m_data[0],\r\n\t\t\tinput_data_shape->m_data[1],\r\n\t\t\tinput_data_shape->m_data[2]\r\n\t\t\t  );\r\n\r\n\tsk_params_t sk_p;\r\n\tinit_sk_params(params, sk_p);\r\n\r\n\thpgl::simple_kriging(in_prop, grid, sk_p, out_prop);\r\n\t}\r\n\r\n}\r\n\r\nHPGL_API int\r\nhpgl_simple_kriging_weights(\r\n\t\tfloat * center_coords,\r\n\t\tfloat * neighbours_x,\r\n\t\tfloat * neighbours_y,\r\n\t\tfloat * neighbours_z,\r\n\t\tint neighbours_count,\r\n\t\thpgl_cov_params_t * params,\r\n\t\tfloat * weights)\r\n{\r\n\tusing namespace hpgl;\r\n\treal_location_t center(center_coords[0], center_coords[1], center_coords[2]);\r\n\t\r\n\tstd::vector<real_location_t> neighbour_coords(neighbours_count);\r\n\tfor (int i = 0; i < neighbours_count; ++i)\r\n\t{\r\n\t\tneighbour_coords[i][0] = neighbours_x[i];\r\n\t\tneighbour_coords[i][1] = neighbours_y[i];\r\n\t\tneighbour_coords[i][2] = neighbours_z[i];\r\n\t}\r\n\r\n\tstd::vector<kriging_weight_t> weights2;\r\n\tdouble variance;\r\n\r\n\tsk_params_t sk_p;\r\n\r\n\tsk_p.m_covariance_type = (covariance_type_t) params->m_covariance_type;\r\n\tsk_p.set_ranges(\r\n\t\t\tparams->m_ranges[0],\r\n\t\t\tparams->m_ranges[1],\r\n\t\t\tparams->m_ranges[2]);\r\n\tsk_p.set_angles(\r\n\t\t\tparams->m_angles[0],\r\n\t\t\tparams->m_angles[1],\r\n\t\t\tparams->m_angles[2]);\r\n\tsk_p.m_sill = params->m_sill;\r\n\tsk_p.m_nugget = params->m_nugget;\r\n\r\n\tsimple_kriging_weights(\r\n\t\t\t&sk_p,\r\n\t\t\tcenter,\r\n\t\t\tneighbour_coords,\r\n\t\t\tweights2,\r\n\t\t\tvariance);\r\n\r\n\tfor (int i = 0; i < neighbours_count; ++i)\r\n\t{\r\n\t\tweights[i] = weights2.at(i);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nHPGL_API void hpgl_lvm_kriging(\r\n    float * input_data,\r\n    unsigned char * input_mask,\r\n    hpgl_shape_t * input_data_shape,\r\n    float * mean_data,\r\n    hpgl_shape_t * mean_data_shape,\r\n    hpgl_ok_params_t * params,\r\n    float * output_data,\r\n    unsigned char * output_mask,\r\n    hpgl_shape_t * output_data_shape)\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(input_data_shape);\r\n\tcont_property_array_t input_prop(input_data, input_mask, size);\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, input_data_shape);\r\n\r\n\tok_params_t ok_p;\r\n\tok_p.m_covariance_type = (covariance_type_t) params->m_covariance_type;\r\n\tok_p.set_ranges(\r\n\t\t\tparams->m_ranges[0],\r\n\t\t\tparams->m_ranges[1],\r\n\t\t\tparams->m_ranges[2]);\r\n\tok_p.set_angles(\r\n\t\t\tparams->m_angles[0],\r\n\t\t\tparams->m_angles[1],\r\n\t\t\tparams->m_angles[2]);\r\n\tok_p.m_sill = params->m_sill;\r\n\tok_p.m_nugget = params->m_nugget;\r\n\t\r\n\tok_p.set_radiuses(\r\n\t\t\tparams->m_radiuses[0],\r\n\t\t\tparams->m_radiuses[1],\r\n\t\t\tparams->m_radiuses[2]);\r\n\r\n\tok_p.m_max_neighbours = params->m_max_neighbours;\r\n\r\n\tcont_property_array_t out_prop(output_data, output_mask, size);\r\n\tlvm_kriging(input_prop, mean_data, grid, ok_p, out_prop);\r\n}\r\n\r\nHPGL_API void\r\nhpgl_indicator_kriging(\r\n\t\thpgl_ind_masked_array_t * in_data,\r\n\t\thpgl_ind_masked_array_t * out_data,\r\n\t\thpgl_ik_params_t * params,\r\n\t\tint indicator_count)\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&in_data->m_shape);\r\n\tint size2 = get_shape_volume(&out_data->m_shape);\r\n\tassert (size == size2);\r\n\tindicator_property_array_t in_prop(in_data->m_data, in_data->m_mask, size, in_data->m_indicator_count);\r\n\tindicator_property_array_t out_prop(out_data->m_data, out_data->m_mask, size2, out_data->m_indicator_count);\r\n\r\n\tik_params_t ikp;\r\n\tinit_sis_params(params, indicator_count, &ikp);\r\n\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &(in_data->m_shape));\r\n\r\n\tindicator_kriging(in_prop, grid, ikp, out_prop);\r\n}\r\n\r\nHPGL_API void \r\nhpgl_sgs_simulation(\r\n\t\thpgl_cont_masked_array_t * data,\r\n\t\thpgl_sgs_params_t * params,\t\t\r\n\t\thpgl_non_parametric_cdf_t * cdf,\r\n\t\tdouble * mean,\r\n\t\thpgl_ubyte_array_t * simulation_mask)\r\n\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&(data->m_shape));\r\n\tcont_property_array_t prop(data->m_data, data->m_mask, size);\r\n\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &(data->m_shape));\r\n\r\n\tsgs_params_t sgs_p;\r\n\tinit_sgs_params(params, &sgs_p);\r\n\t\r\n\tif (mean != 0)\r\n\t\tsgs_p.set_mean(*mean);\r\n\t\r\n\tsgs_p.m_lvm = 0;\r\n\tsgs_p.m_mean_kind = mean != 0 ? e_mean_stationary : e_mean_stationary_auto;\r\n\t\r\n\thpgl::sequential_gaussian_simulation(\r\n\t\t\tgrid,\r\n\t\t\tsgs_p,\r\n\t\t\tprop,\r\n\t\t\tcdf,\r\n\t\t\tsimulation_mask != 0 ? simulation_mask->m_data : 0);\t\r\n}\r\n\r\n\r\nHPGL_API void hpgl_sgs_lvm_simulation(\r\n\t\thpgl_cont_masked_array_t * data,\r\n\t\thpgl_sgs_params_t * params,\r\n\t\thpgl_non_parametric_cdf_t * cdf,\r\n\t\thpgl_float_array_t * means,\r\n\t\thpgl_ubyte_array_t * simulation_mask)\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&(data->m_shape));\r\n\tcont_property_array_t prop(data->m_data, data->m_mask, size);\r\n\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &(data->m_shape));\r\n\r\n\tsgs_params_t sgs_p;\r\n\tinit_sgs_params(params, &sgs_p);\r\n\r\n\tsgs_p.m_lvm = means->m_data;\r\n\tsgs_p.m_mean_kind = e_mean_varying;\r\n\t\r\n\thpgl::sequential_gaussian_simulation_lvm(\r\n\t\t\tgrid,\r\n\t\t\tsgs_p,\r\n\t\t\tmeans->m_data,\r\n\t\t\tprop,\r\n\t\t\tcdf,\r\n\t\t\tsimulation_mask != 0 ? simulation_mask->m_data : 0);\r\n}\r\n\r\nHPGL_API void hpgl_median_ik(\r\n\t\thpgl_ind_masked_array_t * in_data,\r\n\t\thpgl_median_ik_params_t * params,\r\n\t\thpgl_ind_masked_array_t * out_data)\r\n{\r\n\tusing namespace hpgl;\r\n\r\n\tint size = get_shape_volume(&(in_data->m_shape));\r\n\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &(in_data->m_shape));\r\n\r\n\tmedian_ik_params mik_p;\r\n\tmik_p.m_covariance_type = (covariance_type_t) params->m_covariance_type;\r\n\tmik_p.set_ranges(\r\n\t\t\tparams->m_ranges[0],\r\n\t\t\tparams->m_ranges[1],\r\n\t\t\tparams->m_ranges[2]);\r\n\tmik_p.set_angles(\r\n\t\t\tparams->m_angles[0],\r\n\t\t\tparams->m_angles[1],\r\n\t\t\tparams->m_angles[2]);\r\n\tmik_p.m_sill = params->m_sill;\r\n\tmik_p.m_nugget = params->m_nugget;\r\n\t\r\n\tmik_p.set_radiuses(\r\n\t\t\tparams->m_radiuses[0],\r\n\t\t\tparams->m_radiuses[1],\r\n\t\t\tparams->m_radiuses[2]);\r\n\r\n\tmik_p.m_max_neighbours = params->m_max_neighbours;\r\n\tmik_p.m_marginal_probs[0] = params->m_marginal_probs[0];\r\n\tmik_p.m_marginal_probs[1] = params->m_marginal_probs[1];\r\n\r\n\tindicator_property_array_t in_prop(\r\n\t\t\tin_data->m_data, \r\n\t\t\tin_data->m_mask,\r\n\t\t\tsize,\r\n\t\t\t2);\r\n\tindicator_property_array_t out_prop(\r\n\t\t\tout_data->m_data,\r\n\t\t\tout_data->m_mask,\r\n\t\t\tsize,\r\n\t\t\t2);\r\n\tmedian_ik_for_two_indicators(mik_p, grid, in_prop, out_prop);\r\n\t\t\r\n}\r\n\r\nHPGL_API void\r\nhpgl_sis_simulation(\r\n\t\thpgl_ind_masked_array_t * data,\r\n\t\thpgl_ik_params_t * params,\r\n\t\tint indicator_count,\r\n\t\tint seed,\r\n\t\thpgl_ubyte_array_t * simulation_mask)\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&data->m_shape);\r\n\tindicator_property_array_t prop(data->m_data, data->m_mask, size, indicator_count);\r\n\t\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &data->m_shape);\r\n\r\n\tik_params_t ikp;\r\n\tinit_sis_params(params, indicator_count, &ikp);\r\n\r\n\tprogress_reporter_t rep(size);\r\n\r\n\tsequential_indicator_simulation(\r\n\t\t\tprop,\r\n\t\t\tgrid,\r\n\t\t\tikp,\r\n\t\t\tseed,\r\n\t\t\trep,\r\n\t\t\tfalse,\r\n\t\t\tsimulation_mask !=0 ? simulation_mask->m_data : 0);\r\n}\r\n\r\nHPGL_API void\r\nhpgl_sis_simulation_lvm(\r\n\t\thpgl_ind_masked_array_t * data,\r\n\t\thpgl_ik_params_t * params,\r\n\t\thpgl_float_array_t * mean_data,\r\n\t\tint indicator_count,\r\n\t\tint seed,\r\n\t\thpgl_ubyte_array_t * simulation_mask,\r\n\t\tint use_correlograms)\r\n{\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&data->m_shape);\r\n\tindicator_property_array_t prop(data->m_data, data->m_mask, size, indicator_count);\r\n\t\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &data->m_shape);\r\n\r\n\tik_params_t ikp;\r\n\tinit_sis_params(params, indicator_count, &ikp);\r\n\r\n\tprogress_reporter_t rep(size);\r\n\t\r\n\tstd::vector<const mean_t *> means;\r\n\tfor (int i = 0; i < indicator_count; ++i)\r\n\t{\r\n\t\tmeans.push_back(mean_data[i].m_data);\r\n\t}\r\n\t\r\n\tsequential_indicator_simulation_lvm(\r\n\t\t\tprop,\r\n\t\t\tgrid,\r\n\t\t\tikp,\r\n\t\t\tseed,\r\n\t\t\t&means[0],\r\n\t\t\trep,\r\n\t\t\tuse_correlograms != 0,\r\n\t\t\tsimulation_mask != 0 ? simulation_mask->m_data : 0);\r\n\t\t\r\n}\r\n\r\nHPGL_API void\r\nhpgl_simple_cokriging_mark1(\r\n\t\thpgl_cont_masked_array_t * input_data,\r\n\t\thpgl_cont_masked_array_t * secondary_data,\r\n\t\thpgl_cokriging_m1_params_t * params,\r\n\t\thpgl_cont_masked_array_t * output_data)\r\n{\r\n\tusing namespace boost;\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&input_data->m_shape);\r\n\tint size2 = get_shape_volume(&secondary_data->m_shape);\r\n\tint size3 = get_shape_volume(&output_data->m_shape);\r\n\r\n\tif (size != size2)\r\n\t{\r\n\t\tthrow hpgl_exception(\r\n\t\t\t\t\"hpgl_simple_cokriging_mark1\", \r\n\t\t\t\tformat(\"Size of secondary data (%1%) is different from size of primary data (%2%)\") % size2 % size);\r\n\t}\r\n\r\n\tif (size != size3)\r\n\t{\r\n\t\tthrow hpgl_exception(\r\n\t\t\t\t\"hpgl_simple_cokriging_mark1\",\r\n\t\t\t\tformat(\"Size of output data (%1%) is different from size of primary data (%2%)\") % size3 % size);\r\n\t}\r\n\r\n\tcont_property_array_t primary_prop(\r\n\t\t\tinput_data->m_data, input_data->m_mask, size);\r\n\tcont_property_array_t secondary_prop(\r\n\t\t\tsecondary_data->m_data, secondary_data->m_mask, size2);\r\n\tcont_property_array_t output_prop(\r\n\t\t\toutput_data->m_data, output_data->m_mask, size3);\r\n\r\n\tneighbourhood_param_t np;\r\n\tnp.m_max_neighbours = params->m_max_neighbours;\r\n\r\n\tcovariance_param_t cp;\r\n\tcp.m_nugget = params->m_nugget;\r\n\tcp.m_sill = params->m_sill;\r\n\tcp.m_covariance_type = (covariance_type_t) params->m_covariance_type;\r\n\r\n\tfor (int i = 0; i < 3; ++i)\r\n\t{\r\n\t\tnp.m_radiuses[i] = params->m_radiuses[i];\r\n\t\tcp.m_ranges[i] = params->m_ranges[i];\r\n\t\tcp.m_angles[i] = params->m_angles[i];\r\n\t}\r\n\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &input_data->m_shape);\r\n\r\n\tsimple_cokriging_markI(\r\n\t\t\tgrid, \r\n\t\t\tprimary_prop,\r\n\t\t\tsecondary_prop,\r\n\t\t\tparams->m_primary_mean,\r\n\t\t\tparams->m_secondary_mean,\r\n\t\t\tparams->m_secondary_variance,\r\n\t\t\tparams->m_correlation_coef,\r\n\t\t\tnp,\r\n\t\t\tcp,\r\n\t\t\toutput_prop);\r\n\t\t\t\t\t\t   \r\n\t\r\n}\r\n\r\nHPGL_API void\r\nhpgl_simple_cokriging_mark2(\r\n\t\thpgl_cont_masked_array_t * primary_data,\r\n\t\thpgl_cont_masked_array_t * secondary_data,\r\n\t\thpgl_cokriging_m2_params_t * params,\t\t\r\n\t\thpgl_cont_masked_array_t * output_data)\r\n{\r\n\tusing namespace boost;\r\n\tusing namespace hpgl;\r\n\tint size = get_shape_volume(&primary_data->m_shape);\r\n\tint size2 = get_shape_volume(&secondary_data->m_shape);\r\n\tint size3 = get_shape_volume(&output_data->m_shape);\r\n\r\n\tif (size != size2)\r\n\t{\r\n\t\tthrow hpgl_exception(\r\n\t\t\t\t\"hpgl_simple_cokriging_mark1\", \r\n\t\t\t\tformat(\"Size of secondary data (%1%) is different from size of primary data (%2%)\") % size2 % size);\r\n\t}\r\n\r\n\tif (size != size3)\r\n\t{\r\n\t\tthrow hpgl_exception(\r\n\t\t\t\t\"hpgl_simple_cokriging_mark1\",\r\n\t\t\t\tformat(\"Size of output data (%1%) is different from size of primary data (%2%)\") % size3 % size);\r\n\t}\r\n\r\n\tcont_property_array_t primary_prop(\r\n\t\t\tprimary_data->m_data, primary_data->m_mask, size);\r\n\tcont_property_array_t secondary_prop(\r\n\t\t\tsecondary_data->m_data, secondary_data->m_mask, size2);\r\n\tcont_property_array_t out_prop(\r\n\t\t\toutput_data->m_data, output_data->m_mask, size3);\r\n\r\n\tsugarbox_grid_t grid;\r\n\tinit_grid(grid, &primary_data->m_shape);\r\n\r\n\tcovariance_param_t primary_cp, secondary_cp;\r\n\r\n\tinit_cov_param(&primary_cp, &params->m_primary_cov_params);\r\n\tinit_cov_param(&secondary_cp, &params->m_secondary_cov_params);\r\n\r\n\tneighbourhood_param_t np;\r\n\tnp.m_max_neighbours = params->m_max_neighbours;\r\n\tfor (int i = 0; i < 3; ++i)\r\n\t{\r\n\t\tnp.m_radiuses[i] = params->m_radiuses[i];\r\n\t}\t\r\n\r\n\tsimple_cokriging_markII(\r\n\t\t\tgrid, primary_prop, \r\n\t\t\tsecondary_prop,\r\n\t\t\tparams->m_primary_mean,\r\n\t\t\tparams->m_secondary_mean,\r\n\t\t\tparams->m_correlation_coef,\r\n\t\t\tnp,\r\n\t\t\tprimary_cp,\r\n\t\t\tsecondary_cp,\r\n\t\t\tout_prop);\r\n}\r\n", "meta": {"hexsha": "f9c5ae8d5e3b25e1323ae2eac099f6dd4566851f", "size": 18476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geo_bsd/hpgl/api.cpp", "max_stars_repo_name": "hpgl/hpgl", "max_stars_repo_head_hexsha": "72d8c4113c242295de740513093f5779c94ba84a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-21T12:24:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:10:45.000Z", "max_issues_repo_path": "src/geo_bsd/hpgl/api.cpp", "max_issues_repo_name": "hpgl/hpgl", "max_issues_repo_head_hexsha": "72d8c4113c242295de740513093f5779c94ba84a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-22T13:14:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T12:16:32.000Z", "max_forks_repo_path": "src/geo_bsd/hpgl/api.cpp", "max_forks_repo_name": "hpgl/hpgl", "max_forks_repo_head_hexsha": "72d8c4113c242295de740513093f5779c94ba84a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-02-15T18:04:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-16T08:54:32.000Z", "avg_line_length": 25.8044692737, "max_line_length": 143, "alphanum_fraction": 0.705780472, "num_tokens": 5269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.026759280080849095, "lm_q1q2_score": 0.009809677429009294}}
{"text": "#include \"simulationexecutor.h\"\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include \"scriptloader.h\"\n#include \"simulation.h\"\n\n#include \"nonlinearhamiltonian.h\"\n\nusing namespace boost;\nusing namespace property_tree;\n\nSimulationExecutor::SimulationExecutor(const std::string& filename) {\n    ptree tree;\n    json_parser::read_json(filename, tree);\n\n    for (auto it = tree.begin(); it != tree.end(); ++it) {\n        if (it->first == \"Simulation\") {\n            const ptree& child = it->second;\n            SimulationParameter params(child.get<double>(\"dx\"),\n                                       child.get<double>(\"dt\"),\n                                       child.get<double>(\"mass\"),\n                                       child.get<int>(\"iterations\"),\n                                       child.get<int>(\"atoms\"));\n            simulations.push_back(std::pair<SimulationParameter, std::string>(params, child.get<std::string>(\"script\")));\n        }\n    }\n\n    run();\n}\n\nSimulationExecutor::SimulationExecutor(const SimulationParameter& params, const std::string& scriptFile) {\n    simulations.push_back(std::pair<SimulationParameter, std::string>(params, scriptFile));\n\n    run();\n}\n\nvoid SimulationExecutor::run() {\n    for (std::pair<SimulationParameter, std::string> simul : simulations) {\n        Simulation sim(simul.first, nullptr);\n        ScriptExecutor(sim, simul.second);\n    }\n}\n", "meta": {"hexsha": "5e8629c511ca03e7f0c79486c30cdc26fcc2fe4d", "size": 1440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulationexecutor.cpp", "max_stars_repo_name": "TheTimmy/CrankNicolson", "max_stars_repo_head_hexsha": "44e2e5e3fa07af17444f1e341e9021c47ab87601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulationexecutor.cpp", "max_issues_repo_name": "TheTimmy/CrankNicolson", "max_issues_repo_head_hexsha": "44e2e5e3fa07af17444f1e341e9021c47ab87601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulationexecutor.cpp", "max_forks_repo_name": "TheTimmy/CrankNicolson", "max_forks_repo_head_hexsha": "44e2e5e3fa07af17444f1e341e9021c47ab87601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T06:09:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-16T06:09:34.000Z", "avg_line_length": 32.0, "max_line_length": 121, "alphanum_fraction": 0.6111111111, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.033589506738452235, "lm_q1q2_score": 0.00977390376648628}}
{"text": "#include <boost/program_options.hpp>\r\n//#include <experimental/filesystem>\r\n#include <boost/filesystem.hpp>\r\n#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n#include <regex>\r\n#include <cstdlib>\r\n#include <cmath>\r\n#include <armadillo>\r\n\r\n#include \"atomsciflow/parser/cif.h\"\r\n#include \"atomsciflow/parser/xyz.h\"\r\n#include \"atomsciflow/base/crystal.h\"\r\n#include \"atomsciflow/utils.h\"\r\n\r\n#include \"atomsciflow/cube_handle/cube_handle.h\"\r\n// needs: libboost-dev, libboost-program-options-dev\r\n\r\nnamespace po = boost::program_options;\r\n\r\n\r\n//namespace filesys = std::experimental::filesystem;  // --std=c++17 -lstdc++fs\r\nnamespace filesys = boost::filesystem;     // --std=c++11 -lboost_filesystem -lboost_system\r\n\r\n\r\n\r\n// used to allow negative number parsed to boost cmd option\r\nstd::vector<po::option> ignore_numbers(std::vector<std::string>& args)\r\n{\r\n    // this function can help to alow negative number args but it probhibits positional args\r\n    // however we do not need positional args. so it is ok.\r\n    std::vector<po::option> result;\r\n    int pos = 0;\r\n    while(!args.empty()) {\r\n        const auto& arg = args[0];\r\n        double num;\r\n        if(boost::conversion::try_lexical_convert(arg, num)) {\r\n            result.push_back(po::option());\r\n            po::option& opt = result.back();\r\n\r\n            opt.position_key = pos++;\r\n            opt.value.push_back(arg);\r\n            opt.original_tokens.push_back(arg);\r\n\r\n            args.erase(args.begin());\r\n        } else {\r\n            break;\r\n        }\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\n\r\n\r\nint main(int argc, char const* argv[]) {\r\n    //\r\n\r\n    po::options_description global(\"Global options\");\r\n    global.add_options()\r\n        (\"command\", po::value<std::string>(), \"command to execute\")\r\n        (\"subargs\", po::value<std::vector<std::string> >(), \"Arguments for command\")\r\n        (\"help, h\", \"print out help information\");\r\n        \r\n    po::positional_options_description pos;\r\n    pos.add(\"command\", 1).add(\"subargs\", -1);\r\n    \r\n    po::variables_map vm;\r\n    \r\n    po::parsed_options parsed = po::command_line_parser(argc, argv).\r\n        options(global).\r\n        positional(pos).\r\n        allow_unregistered().\r\n        run();\r\n        \r\n    po::store(parsed, vm);\r\n    \r\n    std::cout << \"**********************************************************************\" << std::endl;\r\n    std::cout << \"*                       skit-cube.x utils runnig                     *\" << std::endl;\r\n    std::cout << \"**********************************************************************\" << std::endl;\r\n    \r\n    if (0 == vm.count(\"command\")) { // or by vm.empty()\r\n        std::cout << \"You didn't specify any subcommand!\\n\";\r\n        std::exit(1);\r\n    }\r\n    std::string cmd = vm[\"command\"].as<std::string>();\r\n\r\n\r\n    if (cmd == \"along\") {\r\n        //\r\n        std::cout << \"----------------------------------------------------------------------\" << std::endl;    \r\n        std::cout << \"sub commands -> along                                                 \" << std::endl;\r\n        std::cout << \"Run info:\" << std::endl;\r\n\r\n        // along command has the following options:\r\n        po::options_description opt_along(\"along options\");\r\n        opt_along.add_options()\r\n            (\"input, i\", po::value<std::string>(), \"input cube file\")\r\n            (\"output, o\", po::value<std::string>(), \"output structure file\")\r\n            (\"abscissa\", po::value<std::vector<std::string> >()->multitoken(), \"choose the direction to do the dimension reduction\");\r\n        //opts.add_options()\r\n        //    (\"input, i\", po::value<std::string>(&input), \"input structure file\")\r\n        //    (\"output, o\", po::value<std::string>(&output), \"output structure file\");\r\n        // collect all the unrecognized options from the first pass. this will include the \r\n        // (positional) command name so we need to erase that\r\n        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);\r\n        opts.erase(opts.begin());\r\n        //parse again...\r\n        po::store(po::command_line_parser(opts).options(opt_along).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);\r\n        std::cout << \"parse arguments again\" << \"\\n\";\r\n\r\n        if (vm.count(\"help\")) {\r\n            std::cout << opt_along << std::endl;\r\n            std::exit(1);\r\n        }\r\n        po::notify(vm);\r\n\r\n\r\n\r\n        std::cout << \"Preparing to deal with input and output\\n\";\r\n\r\n        if (vm.count(\"input\") && vm.count(\"output\")) {\r\n\r\n        \r\n            std::string input_file = vm[\"input\"].as<std::string>();\r\n            std::string output_file = vm[\"output\"].as<std::string>();\r\n\r\n            filesys::path in_path(input_file);\r\n            filesys::path out_path(output_file);\r\n\r\n            std::vector<std::string> abscissa = vm[\"abscissa\"].as<std::vector<std::string>>();\r\n        \r\n            std::cout << \"input: \" << input_file << std::endl;\r\n            std::cout << \"output: \" << output_file << std::endl;\r\n        \r\n    \r\n        \r\n            // read structure file\r\n            std::cout << \"in_path(extension)->\" << in_path.extension().string() << std::endl;\r\n\r\n            \r\n            atomsciflow::CubeElectronDensity cube;\r\n            cube.read_cube(input_file);\r\n        \r\n            double bohr_to_angstrom = 0.529177249;\r\n            // data dimension reduction\r\n            // the unit of value is actually not physical now!\r\n            // cell_volume are in unit of Angstrom^3\r\n            arma::mat latcell(3, 3);\r\n            latcell.row(0) = arma::conv_to<arma::rowvec>::from(cube.crystal.cell[0]);\r\n            latcell.row(1) = arma::conv_to<arma::rowvec>::from(cube.crystal.cell[1]);\r\n            latcell.row(2) = arma::conv_to<arma::rowvec>::from(cube.crystal.cell[2]);\r\n            \r\n            std::cout << \"latcell:\\n\";\r\n            std::cout << latcell << std::endl;      \r\n\r\n            // std::cout << \"test value:\\n\";\r\n            // std::cout << arma::dot(arma::cross(latcell.row(0), latcell.row(1)), latcell.row(2)) << std::endl;\r\n\r\n            double cell_volume = arma::dot(arma::cross(latcell.row(0), latcell.row(1)), latcell.row(2));\r\n\r\n            double cell_volume_per_unit = cell_volume / (cube.ngridx * cube.ngridy * cube.ngridz);\r\n\r\n            //std::cout << \"cell volume per unit: \" << cell_volume_per_unit << std::endl;\r\n\r\n            int ngridx = cube.ngridx;\r\n            int ngridy = cube.ngridy;\r\n            int ngridz = cube.ngridz;\r\n            // value in cube file are \\rho(r)_of_electrons in unit of e/Bohr^3\r\n            // namely number of electrons each Borh^3\r\n            // so we have to convert it to e/Angstrom^3, through divide it by borh_to_angstrom**3\r\n        \r\n            double total_electrons = arma::accu(cube.data)  * cell_volume_per_unit / pow(bohr_to_angstrom, 3);\r\n\r\n            std::cout << \"======================================================\\n\";\r\n            std::cout << \"           Information collected\\n\";\r\n            std::cout << \"------------------------------------------------------\\n\";\r\n            std::cout << \"cell volume: \" << cell_volume << \" (A^3)\\n\";\r\n            std::cout << \"total electrons: \" << total_electrons << \"\\n\";\r\n            \r\n            // cube.data is in unit of e/Bohr^3\r\n            // we will build data_red_? to be in unit of e/Anstrom, namely number of electrons per Angstrom\r\n            // to do this we have to time the volume density with bohr_to_angstrom^-3\r\n            std::vector<double> data_red_a;\r\n            std::vector<double> data_red_b;\r\n            std::vector<double> data_red_c;\r\n            //arma::vec data_red_a;\r\n            //arma::vec data_red_b;\r\n            //arma::vec data_red_c;\r\n\r\n            double a = arma::norm(latcell.row(0), 2);\r\n            double b = arma::norm(latcell.row(1), 2);\r\n            double c = arma::norm(latcell.row(2), 2);\r\n            \r\n            if (std::find(abscissa.begin(), abscissa.end(), \"c\") != abscissa.end()) {\r\n                double len_ci = c / ngridz;\r\n                auto size = arma::size(cube.data);\r\n                double tmp;\r\n                double rho_line;\r\n                for (int ci = 0; ci < size[2]; ci++) {\r\n                    tmp  = 0;\r\n                    for (int bi = 0; bi < size[1]; bi++) {\r\n                        for (int ai = 0; ai < size[0]; ai++) {\r\n                            tmp += cube.data.at(ai, bi, ci);\r\n                        }\r\n                    }\r\n                    rho_line = tmp * cell_volume_per_unit / pow(bohr_to_angstrom, 3) / len_ci;\r\n                    data_red_c.push_back(rho_line);\r\n                }\r\n            }\r\n\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"b\") != abscissa.end())  {\r\n                double len_bi = b / ngridy;\r\n                auto size = arma::size(cube.data);\r\n                double tmp;\r\n                double rho_line;\r\n                for (int bi  = 0; bi < size[1]; bi++) {\r\n                    tmp = 0;\r\n                    for (int ai = 0; ai < size[0]; ai++) {\r\n                        for (int ci = 0; ci < size[2]; ci++) {\r\n                            tmp += cube.data.at(ai, bi, ci);\r\n                        }\r\n                    }\r\n                    rho_line = tmp * cell_volume_per_unit / pow(bohr_to_angstrom, 3) / len_bi;\r\n                    data_red_b.push_back(rho_line);\r\n                }\r\n            }\r\n\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"a\") != abscissa.end())  {\r\n                double len_ai = a / ngridx;\r\n                auto size = arma::size(cube.data);\r\n                double tmp;\r\n                double rho_line;\r\n                for (int ai = 0; ai < size[0]; ai++) {\r\n                    tmp = 0;\r\n                    for (int ci = 0; ci < size[2]; ci++) {\r\n                        for (int bi = 0; bi < size[1]; bi++) {\r\n                            tmp += cube.data.at(ai, bi, ci);\r\n                        }\r\n                    }\r\n                    rho_line = tmp * cell_volume_per_unit / pow(bohr_to_angstrom, 3) / len_ai;\r\n                    data_red_a.push_back(rho_line);\r\n                }\r\n            }\r\n\r\n            std::cout << \"Preparing to output the data\\n\";\r\n            // output the data and make the plot\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"c\") != abscissa.end()) {\r\n                std::ofstream fout;\r\n                fout.open(output_file+\".1d.c.data\");\r\n                fout << \"#c(angstrom) rho(e) (number of electron per Angstrom)\\n\";\r\n                arma::vec c_coord = arma::linspace(0, c, data_red_c.size());\r\n                for (int i = 0; i < data_red_c.size(); i++) {\r\n                    fout << c_coord.at(i) << \" \" << data_red_c.at(i) << \"\\n\";\r\n                }\r\n                fout.close();\r\n            }\r\n           \r\n            if (std::find(abscissa.begin(), abscissa.end(), \"b\") != abscissa.end()) {\r\n                std::ofstream fout;\r\n                fout.open(output_file+\".1d.b.data\");\r\n                fout << \"#b(angstrom) rho(e) (number of electron per Angstrom)\\n\";\r\n                arma::vec b_coord = arma::linspace(0, b, data_red_b.size());\r\n                for (int i = 0; i < data_red_b.size(); i++) {\r\n                    fout << b_coord.at(i) << \" \" << data_red_b.at(i) << \"\\n\";\r\n                }\r\n                fout.close();\r\n            }\r\n\r\n            if (std::find(abscissa.begin(), abscissa.end(), \"a\") != abscissa.end())  {\r\n                std::ofstream fout;\r\n                fout.open(output_file+\".1d.a.data\");\r\n                fout << \"#a(angstrom) rho(e) (number of electron per Angstrom)\\n\";\r\n                arma::vec a_coord = arma::linspace(0, a, data_red_a.size());\r\n                for (int i = 0; i < data_red_a.size(); i++) {\r\n                    fout << a_coord.at(i) << \" \" << data_red_a.at(i) << \"\\n\";\r\n                }\r\n                fout.close();\r\n            }       \r\n\r\n            //std::ofstream fxx;\r\n            //fxx.open(\"xxx.data\");\r\n            //fxx << cube.data << std::endl;\r\n            //fxx.close();\r\n\r\n        }\r\n        \r\n        \r\n        std::cout << \"----------------------------------------------------------------------\" << std::endl;\r\n        std::cout << \"sub command: along finished!!!                                      \" << std::endl;\r\n        std::cout << \"----------------------------------------------------------------------\" << std::endl;\r\n        \r\n    } else if (cmd == \"diff\") {\r\n        //\r\n        std::cout << \"----------------------------------------------------------------------\" << std::endl;    \r\n        std::cout << \"sub commands -> diff                                                 \" << std::endl;\r\n        std::cout << \"Run info:\" << std::endl;\r\n\r\n        // along command has the following options:\r\n        po::options_description opt_diff(\"diff options\");\r\n        opt_diff.add_options()\r\n            (\"input, i\", po::value<std::vector<std::string> >()->multitoken(), \"input three cube file: TOTAL PART1 PART2\")\r\n            (\"output, o\", po::value<std::string>(), \"output structure file\")\r\n            (\"abscissa\", po::value<std::vector<std::string> >()->multitoken(), \"choose the direction to do the dimension reduction\");\r\n        //opts.add_options()\r\n        //    (\"input, i\", po::value<std::string>(&input), \"input structure file\")\r\n        //    (\"output, o\", po::value<std::string>(&output), \"output structure file\");\r\n        // collect all the unrecognized options from the first pass. this will include the \r\n        // (positional) command name so we need to erase that\r\n        std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);\r\n        opts.erase(opts.begin());\r\n        //parse again...\r\n        po::store(po::command_line_parser(opts).options(opt_diff).style(po::command_line_style::unix_style | po::command_line_style::allow_long_disguise).extra_style_parser(&ignore_numbers).run(), vm);\r\n        std::cout << \"parse arguments again\" << \"\\n\";\r\n\r\n        if (vm.count(\"help\")) {\r\n            std::cout << opt_diff << std::endl;\r\n            std::exit(1);\r\n        }\r\n        po::notify(vm);\r\n\r\n\r\n\r\n        std::cout << \"Preparing to deal with input and output\\n\";\r\n\r\n        if (vm.count(\"input\") && vm.count(\"output\")) {\r\n\r\n        \r\n            // std::string input_file = vm[\"input\"].as<std::string>();\r\n            std::vector<std::string> input_files = vm[\"input\"].as<std::vector<std::string>>();\r\n            std::string output_file = vm[\"output\"].as<std::string>();\r\n\r\n            // filesys::path in_path(input_file);\r\n            filesys::path out_path(output_file);\r\n\r\n            std::vector<std::string> abscissa = vm[\"abscissa\"].as<std::vector<std::string>>();\r\n        \r\n            std::cout << \"input: \\n\" \r\n                << input_files[0] << \"\\n\" \r\n                << input_files[1] << \"\\n\" \r\n                << input_files[2] << \"\\n\" << std::endl;\r\n\r\n            std::cout << \"output: \" << output_file << std::endl;\r\n        \r\n\r\n            atomsciflow::cube_diff_1d(input_files, output_file, abscissa);\r\n\r\n        }\r\n        \r\n        \r\n        std::cout << \"----------------------------------------------------------------------\" << std::endl;\r\n        std::cout << \"sub command: diff finished!!!                                      \" << std::endl;\r\n        std::cout << \"----------------------------------------------------------------------\" << std::endl;\r\n        \r\n    } else {\r\n        std::cout << \"The specified subcommand is not defined!\\n\";\r\n    } \r\n    \r\n    //\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "827ccdcf6abdc89257bff812e7f1b5e7dcb73a20", "size": 15700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/atomsciflow/cmd/asflow_cube.cpp", "max_stars_repo_name": "DeqiTang/pymatflow", "max_stars_repo_head_hexsha": "bd8776feb40ecef0e6704ee898d9f42ded3b0186", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-06T16:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T07:53:34.000Z", "max_issues_repo_path": "cpp/atomsciflow/cmd/asflow_cube.cpp", "max_issues_repo_name": "DeqiTang/pymatflow", "max_issues_repo_head_hexsha": "bd8776feb40ecef0e6704ee898d9f42ded3b0186", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-02T02:23:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T13:29:37.000Z", "max_forks_repo_path": "cpp/atomsciflow/cmd/asflow_cube.cpp", "max_forks_repo_name": "DeqiTang/pymatflow", "max_forks_repo_head_hexsha": "bd8776feb40ecef0e6704ee898d9f42ded3b0186", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-10T16:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-10T16:28:14.000Z", "avg_line_length": 43.2506887052, "max_line_length": 203, "alphanum_fraction": 0.4741401274, "num_tokens": 3587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.028007522634267163, "lm_q1q2_score": 0.009764686898294624}}
{"text": "/*\r\n * This binary enables the training and testing of aromaticity models using\r\n * the NSPDK kernel within the SGD framework.\r\n *\r\n *      Author: mmann\r\n */\r\n\r\n\r\n\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <iomanip>\r\n#include <vector>\r\n#include <string>\r\n#include <exception>\r\n#include <iterator>\r\n#include <cctype>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <map>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n\r\n#include \"biu/OptionParser.hh\"\r\n#include \"biu/Timer.hh\"\r\n\r\n#include <sgm/Graph_boost.hh>\r\n\r\n#include <ggl/Graph.hh>\r\n#include <ggl/chem/Molecule.hh>\r\n#include <ggl/chem/AP_NSPDK.hh>\r\n#include <ggl/chem/SMILESparser.hh>\r\n#include <ggl/chem/SMILESwriter.hh>\r\n#include <ggl/Graph_GML_writer.hh>\r\n\r\n#include <sgd/svmsgd.h>\r\n\r\n#include \"version.hh\"\r\n\r\n\tusing namespace ggl;\r\n\tusing namespace ggl::chem;\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n#ifndef ARGEXCEPTION_\r\n#define ARGEXCEPTION_\r\n\r\n\t  /*! Exception class for exeptions thrown during argument and input parsing.\r\n\t   */\r\n\tclass ArgException : public std::exception {\r\n\tpublic:\r\n\t\t  //! the error message\r\n\t\tstd::string errorMsg;\r\n\t\tArgException( std::string errorMsg_ ) : errorMsg(errorMsg_) {}\r\n\t\tvirtual ~ArgException() throw (){}\r\n\t\tvirtual const char* what() const throw() {\r\n\t\t\treturn errorMsg.c_str();\r\n\t\t}\r\n\t};\r\n\r\n#endif\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nbool\r\nSVector_less(const sgd::SVector& v, const sgd::SVector & vCompare);\r\n\r\n/**\r\n * Dummy pointer class that represents an index within a vector and enables\r\n * vector element comparison/sorting without vector alteration.\r\n */\r\nclass FeatureInfo {\r\n\r\n\tsize_t posInVector;\r\n\tsgd::xvec_t * features;\r\n\r\npublic:\r\n\r\n\tFeatureInfo()\r\n\t: posInVector(0), features(NULL)\r\n\t{}\r\n\r\n\tFeatureInfo( size_t posInVector\r\n\t\t\t\t, sgd::xvec_t * features )\r\n\t: posInVector(posInVector)\r\n\t\t, features(features)\r\n\t{}\r\n\r\n\tsize_t getPosition() const {\r\n\t\treturn posInVector;\r\n\t}\r\n\r\n\tbool\r\n\toperator < ( const FeatureInfo & toComp ) const {\r\n\t\tassert( toComp.features == this->features );\r\n\t\treturn SVector_less( this->features->at(posInVector), toComp.features->at(toComp.posInVector) );\r\n\t}\r\n};\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n/**\r\n * IN CLUSTERING MODE : Collects information for each ring cluster.\r\n */\r\nclass ClusterInfo {\r\npublic:\r\n\t  //! position of the representative within the feature vector\r\n\tsize_t posInVector;\r\n\t  //! number of features for this cluster\r\n\tsize_t clusterSize;\r\n\t  //! number of molecules with this feature\r\n\tsize_t molNumber;\r\n\r\n\tClusterInfo()\r\n\t  : posInVector(0), clusterSize(0), molNumber(0)\r\n\t{}\r\n\r\n\tClusterInfo( const size_t posInVector, const size_t clusterSize, const size_t molNumber)\r\n\t  : posInVector(posInVector), clusterSize(clusterSize), molNumber(molNumber)\r\n\t{}\r\n\r\n};\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nannotateRing( Molecule & mol, const sgm::RingReporter::RingList & ring, bool addAnnotation );\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\ninitAllowedArguments( biu::OptionMap & allowedArgs, std::string &infoText );\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid getFeatures( AP_NSPDK & ap\r\n\t\t\t\t, const Molecule & mol\r\n\t\t\t\t, sgd::xvec_t& trainFeatures\r\n\t\t\t\t, sgd::yvec_t& trainTarget\r\n\t\t\t\t, std::vector< sgm::RingReporter::RingList > * trainRing = NULL\r\n\t\t\t\t);\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid getFeatures(\tAP_NSPDK & ap\r\n\t\t\t\t\t, const std::string & molSMILES\r\n\t\t\t\t\t, sgd::xvec_t& trainFeatures\r\n\t\t\t\t\t, sgd::yvec_t& trainTarget );\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\ntypedef std::vector< std::string > SMILES_container;\r\ntypedef std::back_insert_iterator< SMILES_container > SMILES_inserter;\r\n\r\nvoid parseSMILES(\tstd::istream & in\r\n\t\t\t\t\t, SMILES_inserter & toFill\r\n\t\t\t\t\t, const size_t linesRead ) throw(std::exception);\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nreadModel( std::istream & in, AP_NSPDK_Model & model );\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nprintModel( std::ostream & out, const AP_NSPDK_Model & model );\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nprintWeightedGML( std::ostream & out, AP_NSPDK & apNSPDK, const Molecule & mol, const bool multilineGML );\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nenum Mode { MODE_TRAIN, MODE_TEST, MODE_APPLY, MODE_CLUST, MODE_XVAL, MODE_UNDEF };\r\n\r\nint main( int argc, char** argv ) {\r\n\r\n\t//////////////////////////////////////////////////////////////\r\n\t// variables\r\n\t//////////////////////////////////////////////////////////////\r\n\r\n\tstd::istream* inSMILES = NULL;\r\n\tstd::ifstream* inSMILESFile = NULL;\r\n\tsize_t inSMILESLine = 0;\r\n\r\n\tstd::istream* inModel = NULL;\r\n\tstd::ifstream* inModelFile = NULL;\r\n\r\n\tstd::ostream* out = &std::cout;\r\n\tstd::ofstream* outFile = NULL;\r\n\r\n\tstd::ostream* log = &std::cout;\r\n\tstd::ofstream* logFile = NULL;\r\n\r\n\tstd::ostream* prediction = NULL;\r\n\tstd::ofstream* predictionFile = NULL;\r\n\r\n\tSMILES_container SMILES;\r\n\tMode mode = MODE_UNDEF;\r\n\r\n\tdouble lambda = 0.0;\r\n\tsize_t epochs = 0;\r\n\r\n\tstd::string modelID = \"\";\r\n\tsize_t maxRingSize = 0;\r\n\tsize_t nspdkMaxRingDistance = 0;\r\n\tsize_t nspdkMaxDistance = 0;\r\n\tsize_t nspdkMaxRadius = 0;\r\n\tsize_t nspdkFeatureBitSize = 0;\r\n\tsize_t randomClusterLists = 0;\r\n\r\n\t//////////////////////////////////////////////////////////////\r\n\t// parameter parsing and checking\r\n\t//////////////////////////////////////////////////////////////\r\n\r\n\tbiu::OptionMap allowedArgs;\t//< map of allowed arguments\r\n\tstd::string infoText;\t\t//< info string of the program\r\n\tinitAllowedArguments(allowedArgs,infoText);\t// init\r\n\r\n\t\t// parse programm arguments\r\n\tbiu::COptionParser opts = biu::COptionParser(\tallowedArgs, argc,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\targv, infoText);\r\n\t\t// check arguments parseable and all mandatory arguments given\r\n\t\t// + help output if needed\r\n\tif (opts.argExist(\"help\")) {\r\n\t\topts.coutUsage();\r\n\t\treturn 0;\r\n\t}\r\n\tif (opts.argExist(\"version\")) {\r\n\t\tgiveVersion();\r\n\t\treturn 0;\r\n\t}\r\n\tif (!opts.noErrors()) {\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tint exitValue = 0;\r\n\r\n\ttry {\r\n\r\n\t\t  // set SMILES input stream\r\n\t\tif (boost::iequals(opts.getStrVal(\"smiles\"),\"STDIN\")) {\r\n\t\t\t  // read from STDIN\r\n\t\t\tinSMILES = &std::cin;\r\n\t\t} else {\r\n\t\t\t  // read from file\r\n\t\t\tinSMILESFile = new std::ifstream( opts.getStrVal(\"smiles\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t, std::ifstream::in );\r\n\t\t\tif (!inSMILESFile->is_open()) {\r\n\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\toss\t<<\"cannot open SMILES input file '\" <<opts.getStrVal(\"smiles\") <<\"'\";\r\n\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t}\r\n\t\t\tinSMILES = inSMILESFile;\r\n\t\t}\r\n\t\t  // set output stream\r\n\t\tif (opts.getStrVal(\"out\").size() == 0) {\r\n\t\t\tthrow ArgException(\"no output file given\");\r\n\t\t} else if ( !boost::iequals(opts.getStrVal(\"out\"),\"STDOUT\")) {\r\n\t\t\toutFile = new std::ofstream(\topts.getStrVal(\"out\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t\t, std::ofstream::out );\r\n\t\t\tif (!outFile->is_open()) {\r\n\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\toss\t<<\"cannot open output file '\" <<opts.getStrVal(\"out\") <<\"'\";\r\n\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t}\r\n\t\t\tout = outFile;\r\n\t\t}\r\n\t\t  // set logfile stream\r\n\t\tif (opts.getStrVal(\"log\").size() == 0) {\r\n\t\t\tthrow ArgException(\"no logfile file given\");\r\n\t\t} else if ( boost::iequals(opts.getStrVal(\"log\"),\"STDOUT\")) {\r\n\t\t\tlog = &std::cout;\r\n\t\t} else if ( boost::iequals(opts.getStrVal(\"log\"),\"STDERR\")) {\r\n\t\t\tlog = &std::cerr;\r\n\t\t} else {\r\n\t\t\tlogFile = new std::ofstream(\topts.getStrVal(\"log\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t\t, std::ofstream::out );\r\n\t\t\tif (!logFile->is_open()) {\r\n\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\toss\t<<\"cannot open logfile file '\" <<opts.getStrVal(\"log\") <<\"'\";\r\n\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t}\r\n\t\t\tlog = logFile;\r\n\t\t}\r\n\t\t  // set prediction stream if needed\r\n\t\tif (opts.argExist(\"prediction\") && opts.getStrVal(\"prediction\").size() >= 0) {\r\n\t\t\tif ( boost::iequals(opts.getStrVal(\"prediction\"),\"STDOUT\")) {\r\n\t\t\t\tprediction = &std::cout;\r\n\t\t\t} else if ( boost::iequals(opts.getStrVal(\"prediction\"),\"STDERR\")) {\r\n\t\t\t\tprediction = &std::cerr;\r\n\t\t\t} else {\r\n\t\t\t\tpredictionFile = new std::ofstream(\topts.getStrVal(\"prediction\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t\t\t, std::ofstream::out );\r\n\t\t\t\tif (!predictionFile->is_open()) {\r\n\t\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\t\toss\t<<\"cannot open prediction file '\" <<opts.getStrVal(\"prediction\") <<\"'\";\r\n\t\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t\t}\r\n\t\t\t\tprediction = predictionFile;\r\n\t\t\t}\r\n\t\t}\r\n\t\t  // set mode\r\n\t\tif (boost::iequals(opts.getStrVal(\"mode\"), \"train\")) {\r\n\t\t\tmode = MODE_TRAIN;\r\n\t\t} else if (boost::iequals(opts.getStrVal(\"mode\"), \"test\")) {\r\n\t\t\tmode = MODE_TEST;\r\n\t\t} else if (boost::iequals(opts.getStrVal(\"mode\"), \"apply\")) {\r\n\t\t\tmode = MODE_APPLY;\r\n\t\t} else if (boost::iequals(opts.getStrVal(\"mode\"), \"cluster\")) {\r\n\t\t\tmode = MODE_CLUST;\r\n\t\t} else if (boost::iequals(opts.getStrVal(\"mode\"), \"xval\")) {\r\n\t\t\tmode = MODE_XVAL;\r\n\t\t} else {\r\n\t\t\tstd::ostringstream oss;\r\n\t\t\toss\t<<\"mode '\" <<opts.getStrVal(\"mode\") <<\"' is unknown\";\r\n\t\t\tthrow ArgException(oss.str());\r\n\t\t}\r\n\r\n\t\t  // set SGD lambda\r\n\t\tlambda = opts.getDoubleVal(\"lambda\");\r\n\t\t  // set number of epochs\r\n\t\tif (opts.getIntVal(\"epochs\") <= 0) {\r\n\t\t\tthrow ArgException(\"number of epochs has to be >= 1\");\r\n\t\t} else {\r\n\t\t\tepochs = (size_t)opts.getIntVal(\"epochs\");\r\n\t\t}\r\n\r\n\t\t  // set model ID\r\n\t\tmodelID = opts.getStrVal(\"modelID\");\r\n\t\t  // set max ring size\r\n\t\tif (opts.getIntVal(\"maxRingSize\") <= 2) {\r\n\t\t\tthrow ArgException(\"maximal ring size has to be >= 3\");\r\n\t\t} else {\r\n\t\t\tmaxRingSize = (size_t)opts.getIntVal(\"maxRingSize\");\r\n\t\t}\r\n\t\t  // set the NSPDK maximal distance\r\n\t\tif (opts.getIntVal(\"nspdkMaxDistance\") < 0) {\r\n\t\t\tthrow ArgException(\"NSPDK maximal distance has to be >= 0\");\r\n\t\t} else {\r\n\t\t\tnspdkMaxDistance = (size_t)opts.getIntVal(\"nspdkMaxDistance\");\r\n\t\t}\r\n\t\t  // set the NSPDK maximal radius\r\n\t\tif (opts.getIntVal(\"nspdkMaxRadius\") < 0) {\r\n\t\t\tthrow ArgException(\"NSPDK maximal radius has to be >= 0\");\r\n\t\t} else {\r\n\t\t\tnspdkMaxRadius = (size_t)opts.getIntVal(\"nspdkMaxRadius\");\r\n\t\t}\r\n\t\t  // set the NSPDK maximal radius\r\n\t\tif (opts.argExist(\"nspdkMaxRingDistance\")) {\r\n\t\t\tif (!opts.argExist(\"ringCentered\")) {\r\n\t\t\t\tthrow ArgException(\"Giving 'nspdkMaxRingDistance' without 'ringCentered' makes no sense..\");\r\n\t\t\t}\r\n\t\t\tif (opts.getIntVal(\"nspdkMaxRingDistance\") < 0) {\r\n\t\t\t\tthrow ArgException(\"The maximal distance from the ring for feature generation has to be >= 0\");\r\n\t\t\t} else {\r\n\t\t\t\tnspdkMaxRingDistance = (size_t)opts.getIntVal(\"nspdkMaxRingDistance\");\r\n\t\t\t}\r\n\t\t}\r\n\t\t  // set the NSPDK feature bit size\r\n\t\tif (opts.getIntVal(\"nspdkFeatureBitSize\") < 8) {\r\n\t\t\tthrow ArgException(\"NSPDK maximal radius has to be >= 8\");\r\n\t\t} else {\r\n\t\t\tnspdkFeatureBitSize = (size_t)opts.getIntVal(\"nspdkFeatureBitSize\");\r\n\t\t}\r\n\r\n\r\n\t\t  // set number of random cluster lists\r\n\t\tif (opts.getIntVal(\"outClustLists\") < 0) {\r\n\t\t\tthrow ArgException(\"The number of random cluster sampling lists has to be at least 1.\");\r\n\t\t} else {\r\n\t\t\trandomClusterLists = (size_t)opts.getIntVal(\"outClustLists\");\r\n\t\t}\r\n\r\n\t\t/////////////////////////////////////////////////////////////\r\n\t\t// parse all SMILES\r\n\t\t/////////////////////////////////////////////////////////////\r\n\r\n\t\t  // parse SMILES\r\n\t\t{\r\n\t\t\tSMILES_inserter inserter(SMILES);\r\n\t\t\tinSMILESLine = 0;\r\n\t\t\tparseSMILES( *inSMILES, inserter, inSMILESLine );\r\n\t\t}\r\n\r\n\t\tswitch (mode) {\r\n\r\n\t\tcase MODE_TRAIN : {\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\t\t\t// training mode\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\r\n\t\t\t  // setup new model to be filled\r\n\t\t\tAP_NSPDK_Model newModel;\r\n\r\n\t\t\tnewModel.ringCentered = opts.argExist(\"ringCentered\");\r\n\t\t\tnewModel.modelID = modelID;\r\n\t\t\tnewModel.maxRingSize = maxRingSize;\r\n\t\t\tnewModel.nspdk_maxRingDistance = nspdkMaxRingDistance;\r\n\t\t\tnewModel.nspdk_maxDistance = nspdkMaxDistance;\r\n\t\t\tnewModel.nspdk_maxRadius = nspdkMaxRadius;\r\n\t\t\tnewModel.nspdk_featureBitSize = nspdkFeatureBitSize;\r\n\r\n\t\t\tnewModel.ringEdgeLabel = \"*~\";\r\n\t\t\tnewModel.ringNodeLabelPrefix = \"*\";\r\n\t\t\tnewModel.ringViewLabelPrefix = \"?\";\r\n\r\n\t\t\t  // create AP_NSPDK instance using the model\r\n\t\t\tAP_NSPDK apNSPDK( & newModel );\r\n\t\t\t  // create features\r\n\t\t\tsgd::xvec_t trainFeatures;\r\n\t\t\tsgd::yvec_t trainTarget;\r\n\t\t\tbiu::Timer timer;\r\n\t\t\ttimer.start();\r\n\t\t\tfor (size_t i=0; i<SMILES.size(); ++i ) {\r\n\t\t\t\tgetFeatures( apNSPDK, SMILES.at(i), trainFeatures, trainTarget );\r\n\t\t\t}\r\n\t\t\t*log <<\" time generating    = \" <<(size_t)timer.stop() <<\" ms\" <<std::endl;\r\n\r\n\t\t\t  // create SGD instance\r\n\t\t\tsgd::SvmSgd trainer( lambda );\r\n\t\t\t  // run training\r\n\t\t\ttimer.start();\r\n\t\t\ttrainer.train( trainFeatures, trainTarget, 0, trainFeatures.size(), epochs );\r\n\t\t\t*log <<\" time training      = \" <<(size_t)timer.stop() <<\" ms\" <<std::endl;\r\n\r\n\t\t\t  // store resulting model\r\n\t\t\tnewModel.bias = trainer.getModel().bias;\r\n\t\t\tnewModel.wscale = trainer.getModel().wscale;\r\n\t\t\tnewModel.w = trainer.getModel().w;\r\n\r\n\t\t\t  // output model\r\n\t\t\tprintModel( *out, newModel );\r\n\r\n\t\t\t  // print statistics\r\n\t\t\tsize_t countArom = 0;\r\n\t\t\tfor (sgd::yvec_t::const_iterator it = trainTarget.begin();\r\n\t\t\t\t\tit != trainTarget.end(); ++it )\r\n\t\t\t{\r\n\t\t\t\tif (*it > 0)\r\n\t\t\t\t\tcountArom++;\r\n\t\t\t}\r\n\t\t\t*log\r\n\t\t\t\t<<\" molecules          = \" <<SMILES.size()\r\n\t\t\t\t<<\"\\n overall rings      = \" <<trainTarget.size()\r\n\t\t\t\t<<\"\\n aromatic rings     = \" <<countArom\r\n\t\t\t\t<<\" = \" <<(double(countArom)/double(trainTarget.size())*100.0) <<\" %\"\r\n\t\t\t\t<<\"\\n non-aromatic rings = \" <<(trainTarget.size()-countArom)\r\n\t\t\t\t<<\" = \" <<(double(trainTarget.size()-countArom)/double(trainTarget.size())*100.0) <<\" %\"\r\n\t\t\t\t<<\"\\n\" <<std::endl;\r\n\r\n\t\t}; break;\r\n\t\tcase MODE_XVAL : {\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\t\t\t// cross validation mode\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\r\n\t\t\t  // set number of chunks to randomly split the data into\r\n\t\t\tif (opts.getIntVal(\"xval\") < 2) {\r\n\t\t\t\tthrow ArgException(\"number of epochs has to be >= 2\");\r\n\t\t\t}\r\n\t\t\tconst size_t xval = (size_t)opts.getIntVal(\"xval\");\r\n\r\n\t\t\t  // setup new model to be filled\r\n\t\t\tAP_NSPDK_Model newModel;\r\n\r\n\t\t\tnewModel.ringCentered = opts.argExist(\"ringCentered\");\r\n\t\t\tnewModel.modelID = modelID;\r\n\t\t\tnewModel.maxRingSize = maxRingSize;\r\n\t\t\tnewModel.nspdk_maxRingDistance = nspdkMaxRingDistance;\r\n\t\t\tnewModel.nspdk_maxDistance = nspdkMaxDistance;\r\n\t\t\tnewModel.nspdk_maxRadius = nspdkMaxRadius;\r\n\t\t\tnewModel.nspdk_featureBitSize = nspdkFeatureBitSize;\r\n\r\n\t\t\tnewModel.ringEdgeLabel = \"*~\";\r\n\t\t\tnewModel.ringNodeLabelPrefix = \"*\";\r\n\t\t\tnewModel.ringViewLabelPrefix = \"?\";\r\n\r\n\t\t\t  // create AP_NSPDK instance using the model\r\n\t\t\tAP_NSPDK apNSPDK( & newModel );\r\n\t\t\t  // create features\r\n\t\t\tsgd::xvec_t trainFeatures;\r\n\t\t\tsgd::yvec_t trainTarget;\r\n\t\t\tbiu::Timer timer;\r\n\t\t\ttimer.start();\r\n\t\t\tfor (size_t i=0; i<SMILES.size(); ++i ) {\r\n//\t\t\t\tstd::cerr <<\" generating for \" <<SMILES.at(i) <<\"\\n\";\r\n\t\t\t\tgetFeatures( apNSPDK, SMILES.at(i), trainFeatures, trainTarget );\r\n\t\t\t}\r\n\t\t\t*log <<\" time generating    = \" <<(size_t)timer.stop() <<\" ms\" <<std::endl;\r\n\t\t\t*log <<\" ring number        = \" <<trainFeatures.size() <<std::endl;\r\n\r\n\t\t\t  // create randomized chunks\r\n\t\t\tstd::vector<size_t> randomTrainIds(trainFeatures.size(),0);\r\n\t\t\tfor (size_t i=0; i<randomTrainIds.size(); ++i) {\r\n\t\t\t\trandomTrainIds[i] = i;\r\n\t\t\t}\r\n\t\t\t // initialize random seed:\r\n\t\t\tstd::srand( unsigned (std::time(NULL)) );\r\n\t\t\t // shuffle indices\r\n\t\t\tstd::random_shuffle(randomTrainIds.begin(),randomTrainIds.end());\r\n\t\t\t // get chunk size rounded to ceiling\r\n\t\t\tconst size_t chunkSize = (size_t)std::ceil((double)randomTrainIds.size() / (double)xval);\r\n\r\n\t\t\t // generate test annotation for each feature vector via cross-validation\r\n\t\t\tsgd::yvec_t testValue(trainTarget.size(),-17.0);\r\n\t\t\t  // create SGD instance\r\n\t\t\tsgd::SvmSgd trainer( lambda );\r\n\t\t\tfor (size_t chunk = 0; chunk < xval; ++chunk) {\r\n\r\n\t\t\t\t  // GENERATE TRAIN AND TEST DATA\r\n\r\n\t\t\t\tsize_t chunkStart = chunk*chunkSize;\r\n\t\t\t\tsgd::xvec_t curTestFeatures( chunkSize - ( chunk+1 == xval ? (chunkStart+chunkSize) - trainFeatures.size() : 0) );\r\n\t\t\t\t  // collect train chunks\r\n\t\t\t\tsgd::xvec_t curTrainFeatures( trainFeatures.size() - curTestFeatures.size() );\r\n\t\t\t\tsgd::yvec_t curTrainTargets( trainFeatures.size() - curTestFeatures.size() );\r\n\t\t\t\t  // collect leading chunks\r\n\t\t\t\tsize_t curPos = 0;\r\n\t\t\t\tfor (size_t c=0; c<chunk; ++c) {\r\n\t\t\t\t\tchunkStart = c*chunkSize;\r\n\t\t\t\t\tfor (size_t i=0; i<chunkSize; ++i) {\r\n\t\t\t\t\t\tcurTrainFeatures[curPos] = trainFeatures.at(randomTrainIds.at(chunkStart+i));\r\n\t\t\t\t\t\tcurTrainTargets[curPos]  = trainTarget.at(randomTrainIds.at(chunkStart+i));\r\n\t\t\t\t\t\t++curPos;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t  // collect trailing chunks\r\n\t\t\t\tfor (size_t c=chunk+1; c<xval; ++c) {\r\n\t\t\t\t\tchunkStart = c*chunkSize;\r\n\t\t\t\t\tfor (size_t i=0; i<chunkSize && (chunkStart+i) < trainFeatures.size(); ++i) {\r\n\t\t\t\t\t\tcurTrainFeatures[curPos] = trainFeatures.at(randomTrainIds.at(chunkStart+i));\r\n\t\t\t\t\t\tcurTrainTargets[curPos]  = trainTarget.at(randomTrainIds.at(chunkStart+i));\r\n\t\t\t\t\t\t++curPos;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t  // GENERATE MODEL\r\n\r\n\t\t\t\t  // run training\r\n\t\t\t\ttimer.start();\r\n\t\t\t\ttrainer.train( curTrainFeatures, curTrainTargets, 0, curTrainFeatures.size(), epochs );\r\n\t\t\t\t*log <<chunk <<\" time training      = \" <<(size_t)timer.stop() <<\" ms\" <<std::endl;\r\n\r\n\t\t\t\t  // store resulting model\r\n\t\t\t\tnewModel.bias = trainer.getModel().bias;\r\n\t\t\t\tnewModel.wscale = trainer.getModel().wscale;\r\n\t\t\t\tnewModel.w = trainer.getModel().w;\r\n\r\n\t\t\t\t  // RUN AND STORE PREDICTION ON TEST\r\n\t\t\t\tchunkStart = chunk*chunkSize;\r\n\t\t\t\t  // collect test chunk\r\n\t\t\t\tdouble timeTesting = 0;\r\n\t\t\t\tfor (size_t i=0; i<chunkSize && (chunkStart+i) < trainFeatures.size(); ++i) {\r\n\t\t\t\t\t  // test instance\r\n\t\t\t\t\ttimer.start();\r\n\t\t\t\t\ttestValue[randomTrainIds.at(chunkStart+i)] = newModel.predictValue( trainFeatures.at(randomTrainIds.at(chunkStart+i)) );\r\n\t\t\t\t\ttimeTesting += timer.stop();\r\n\t\t\t\t}\r\n\t\t\t\t*log <<chunk <<\" time testing       = \" <<(size_t)timer.stop() <<\" ms\" <<std::endl;\r\n\r\n\t\t\t}\r\n\r\n\t\t\t // GATHER STATISTICS\r\n\r\n\t\t\tsize_t truePositive  = 0; // correctly aromatic\r\n\t\t\tsize_t trueNegative  = 0; // correctly non-aromatic\r\n\t\t\tsize_t falsePositive = 0; // incorrectly aromatic (is non-aromatic)\r\n\t\t\tsize_t falseNegative = 0; // incorrectly non-aromatic (is aromatic)\r\n\r\n\t\t\t  // compare each target and test value\r\n\t\t\t  // and print target-test value pairs to out\r\n\t\t\t*out <<\"targetVal\\tpredVal\\n\";\r\n\t\t\tfor (size_t i=0; i<testValue.size(); ++i) {\r\n\t\t\t\t*out <<trainTarget.at(i) <<\"\\t\" <<testValue.at(i) <<\"\\n\";\r\n\t\t\t\t  // correct prediction\r\n\t\t\t\tif (trainTarget.at(i)*testValue.at(i) > 0) {\r\n\t\t\t\t\tif (trainTarget.at(i) > 0) {\r\n\t\t\t\t\t\t++truePositive;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t++trueNegative;\r\n\t\t\t\t\t}\r\n\t\t\t\t} // incorrect prediction\r\n\t\t\t\telse {\r\n\t\t\t\t\tif (trainTarget.at(i) > 0) {\r\n\t\t\t\t\t\t++falseNegative;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t++falsePositive;\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  // print statistics\r\n\t\t\tsize_t countArom = (truePositive+falseNegative);\r\n\t\t\t*log\r\n\t\t\t\t<<\" molecules          = \" <<SMILES.size()\r\n\t\t\t\t<<\"\\n overall rings      = \" <<trainTarget.size()\r\n\t\t\t\t<<\"\\n aromatic rings     = \" <<countArom\r\n\t\t\t\t<<\" = \" <<(double(countArom)/double(trainTarget.size())*100.0) <<\" %\"\r\n\t\t\t\t<<\"\\n non-aromatic rings = \" <<(trainTarget.size()-countArom)\r\n\t\t\t\t<<\" = \" <<(double(trainTarget.size()-countArom)/double(trainTarget.size())*100.0) <<\" %\"\r\n\t\t\t\t<<\"\\n\" <<std::endl\r\n\t\t\t\t<<\"\\n TP (arom)            = \" <<truePositive\r\n\t\t\t\t<<\"\\n TN (non-arom)        = \" <<trueNegative\r\n\t\t\t\t<<\"\\n FN (arom)            = \" <<falseNegative\r\n\t\t\t\t<<\"\\n FP (non-arom)        = \" <<falsePositive\r\n\t\t\t\t<<\"\\n\" <<std::endl\r\n\t\t\t\t;\r\n\r\n\r\n\t\t}; break;\r\n\t\tcase MODE_CLUST : {\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\t\t\t// clustering mode\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\r\n\r\n\t\t\t // generate Molecule representation of all SMILES\r\n\t\t\tstd::vector< Molecule > molecules(SMILES.size());\r\n\t\t\tfor (size_t i=0; i<SMILES.size(); ++i) {\r\n\r\n\t\t\t\t  // get molecule graph\r\n\t\t\t\tstd::pair< Molecule, int > parse = SMILESparser::parseSMILES( SMILES.at(i) );\r\n\t\t\t\tif (parse.second >= 0) {\r\n\t\t\t\t\tthrow ArgException(\"SMILES '\"+SMILES.at(i)+\"' cannot be parsed.\");\r\n\t\t\t\t}\r\n\t\t\t\t  // copy to container\r\n\t\t\t\tMoleculeUtil::copy( parse.first, molecules[i] );\r\n\t\t\t\t  // fill protons\r\n\t\t\t\tMoleculeUtil::fillProtons( molecules[i] );\r\n\r\n\t\t\t}\r\n\r\n\r\n\t\t\t  // setup new model to be filled\r\n\t\t\tAP_NSPDK_Model newModel;\r\n\r\n\t\t\tnewModel.ringCentered = opts.argExist(\"ringCentered\");\r\n\t\t\tnewModel.modelID = modelID;\r\n\t\t\tnewModel.maxRingSize = maxRingSize;\r\n\t\t\tnewModel.nspdk_maxRingDistance = nspdkMaxRingDistance;\r\n\t\t\tnewModel.nspdk_maxDistance = nspdkMaxDistance;\r\n\t\t\tnewModel.nspdk_maxRadius = nspdkMaxRadius;\r\n\t\t\tnewModel.nspdk_featureBitSize = nspdkFeatureBitSize;\r\n\r\n\t\t\tnewModel.ringEdgeLabel = \"*~\";\r\n\t\t\tnewModel.ringNodeLabelPrefix = \"*\";\r\n\t\t\tnewModel.ringViewLabelPrefix = \"?\";\r\n\r\n\t\t\t  // create AP_NSPDK instance using the model\r\n\t\t\tAP_NSPDK apNSPDK( & newModel );\r\n\t\t\t  // create features\r\n\t\t\tsgd::xvec_t trainFeatures;\r\n\t\t\tsgd::yvec_t trainTarget;\r\n\t\t\t  // the ring information for each feature vector\r\n\t\t\tstd::vector< sgm::RingReporter::RingList > trainRing;\r\n\t\t\ttypedef std::vector< size_t > SizetVec;\r\n\t\t\tSizetVec trainSMILES;\r\n\t\t\tbiu::Timer timer;\r\n\t\t\ttimer.start();\r\n\t\t\tfor (size_t i=0; i<molecules.size(); ++i ) {\r\n\t\t\t\tgetFeatures( apNSPDK, molecules.at(i), trainFeatures, trainTarget, &trainRing );\r\n\t\t\t\t// store SMILES/molecule ID for each added feature\r\n\t\t\t\ttrainSMILES.resize(trainFeatures.size(),i);\r\n\t\t\t}\r\n\t\t\t*log <<\" time generating    = \" <<(size_t)timer.stop() <<\" ms\" <<std::endl;\r\n\t\t\ttimer.start();\r\n\r\n\t\t\tstd::vector< FeatureInfo > featureInfo( trainFeatures.size() );\r\n\t\t\tfor (size_t i=0; i<featureInfo.size(); ++i) {\r\n\t\t\t\tfeatureInfo[i] = FeatureInfo(i, &trainFeatures);\r\n\t\t\t}\r\n\r\n\t\t\t  // sort all features but preserve ID information for the features\r\n\t\t\tstd::sort( featureInfo.begin(), featureInfo.end());\r\n\r\n\t\t\t*log <<\" time sorting       = \" <<(size_t)timer.stop() <<\" ms\" <<std::endl;\r\n\r\n\t\t\t  // gather histogram data for cluster size\r\n\t\t\t  // and output at most two random samples per cluster\r\n\t\t\ttypedef std::map<size_t,size_t> HIST;\r\n\t\t\tHIST clusterSizeHistogram;\r\n\t\t\tHIST clusterMolHistogram;\r\n\t\t\tsize_t cStart = 0, cNext=0, cID = 0;\r\n\r\n\r\n//\t\t\tstd::cerr <<\"\\n#############  ITERATE  ########## \";\r\n\r\n\t\t\tstd::vector< std::vector<ClusterInfo> > selectedRings(randomClusterLists);\r\n\t\t\t/* initialize random seed: */\r\n\t\t\tstd::srand ( unsigned (std::time(NULL)) );\r\n\t\t\tstd::set<size_t> molIDs;\r\n\t\t\twhile( cNext<featureInfo.size() ) {\r\n\t\t\t\tmolIDs.clear();\r\n\t\t\t\t  // insert index of first cluster molecule\r\n\t\t\t\tmolIDs.insert(trainSMILES.at(featureInfo.at(cNext).getPosition()));\r\n\t\t\t\t  // find end of current cluster\r\n\t\t\t\t++cNext;\r\n\t\t\t\twhile(cNext<featureInfo.size()\r\n\t\t\t\t\t\t&& ! (featureInfo.at(cStart) < featureInfo.at(cNext)))\r\n\t\t\t\t{\r\n\t\t\t\t\t  // insert index of next cluster molecule\r\n\t\t\t\t\tmolIDs.insert(trainSMILES.at(featureInfo.at(cNext).getPosition()));\r\n\t\t\t\t\t++cNext;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// update size histogram information\r\n\t\t\t\tsize_t clusterSize = cNext-cStart;\r\n\t\t\t\tif (clusterSizeHistogram.find(clusterSize) == clusterSizeHistogram.end()) {\r\n\t\t\t\t\tclusterSizeHistogram[clusterSize] = 0;\r\n\t\t\t\t}\r\n\t\t\t\tclusterSizeHistogram[clusterSize]++;\r\n\r\n\t\t\t\t  // update molecule number histogram information\r\n\t\t\t\tsize_t molNumber = molIDs.size();\r\n\t\t\t\tif (clusterMolHistogram.find(molNumber) == clusterMolHistogram.end()) {\r\n\t\t\t\t\tclusterMolHistogram[molNumber] = 0;\r\n\t\t\t\t}\r\n\t\t\t\tclusterMolHistogram[molNumber]++;\r\n\r\n\t\t\t\t  // pick random element of this cluster\r\n\t\t\t\tfor (size_t i=0; i<randomClusterLists; ++i) {\r\n\t\t\t\t\tif (clusterSize == 1) {\r\n\t\t\t\t\t\tselectedRings[i].push_back( ClusterInfo(featureInfo.at(cStart).getPosition(), clusterSize, molNumber) );\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t  // pick element at random\r\n\t\t\t\t\t\tsize_t pos1 = rand() % clusterSize;\r\n\t\t\t\t\t\t  // first element\r\n\t\t\t\t\t\tselectedRings[i].push_back( ClusterInfo(featureInfo.at(cStart+pos1).getPosition(), clusterSize, molNumber) );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t  // go to next cluster\r\n\t\t\t\tcStart = cNext;\r\n\t\t\t\t++cID;\r\n\t\t\t}\r\n\r\n\r\n\t\t\t  // output histogram data to log\r\n\t\t\t*log <<\"\\n\";\r\n\t\t\t*log <<\" cluster size histogram :\\n\\tclusterSize\\t#cluster\\n\";\r\n\t\t\tfor (HIST::const_iterator c=clusterSizeHistogram.begin();c!=clusterSizeHistogram.end(); ++c) {\r\n\t\t\t\t*log <<\"\\t\" <<c->first <<\"\\t\" <<c->second <<\"\\n\";\r\n\t\t\t}\r\n\t\t\t*log <<std::endl;\r\n\t\t\t*log <<\" molecules per cluster histogram :\\n\\tmolPerCluster\\t#cluster\\n\";\r\n\t\t\tfor (HIST::const_iterator c=clusterMolHistogram.begin();c!=clusterMolHistogram.end(); ++c) {\r\n\t\t\t\t*log <<\"\\t\" <<c->first <<\"\\t\" <<c->second <<\"\\n\";\r\n\t\t\t}\r\n\t\t\t*log <<std::endl;\r\n\r\n\t\t\t  // output selected SMILES to out stream\r\n\t\t\tfor (size_t i=0; i<randomClusterLists; ++i) {\r\n\t\t\t\t*out <<\"# cluster sample list \" <<(i+1) <<\"\\n\";\r\n\t\t\t\tfor (std::vector<ClusterInfo>::const_iterator it=selectedRings.at(i).begin(); it!=selectedRings.at(i).end(); ++it) {\r\n\r\n\t\t\t\t\t  // get molecule/SMILES index of representative\r\n\t\t\t\t\tconst size_t molID = trainSMILES.at(it->posInVector);\r\n\r\n\t\t\t\t\t  // get ring annotation within the representative\r\n\t\t\t\t\tannotateRing(molecules[molID], trainRing.at(it->posInVector), true);\r\n\t\t\t\t\t  // get ring annotated SMILES for output\r\n\t\t\t\t\tconst std::string ringSMILES = SMILESwriter::getSMILES(molecules[molID]);\r\n\t\t\t\t\t  // undo ring annotation\r\n\t\t\t\t\tannotateRing(molecules[molID], trainRing.at(it->posInVector), false);\r\n\r\n\t\t\t\t\t  // output original SMILES\r\n\t\t\t\t\t*out <<SMILES.at(molID)\r\n\t\t\t\t\t  // output ring annotated SMILES\r\n\t\t\t\t\t\t<<\" \"\r\n\t\t\t\t\t\t<<ringSMILES\r\n\t\t\t\t\t  // output cluster size\r\n\t\t\t\t\t\t<<\" \"\r\n\t\t\t\t\t\t<<it->clusterSize\r\n\t\t\t\t\t  // output molecule number\r\n\t\t\t\t\t\t<<\" \"\r\n\t\t\t\t\t\t<<it->molNumber\r\n\t\t\t\t\t  // line break\r\n\t\t\t\t\t\t<<\"\\n\";\r\n\t\t\t\t}\r\n\t\t\t\t*out <<std::endl;\r\n\t\t\t}\r\n\r\n\r\n\t\t}; break;\r\n\t\tcase MODE_TEST :\r\n\t\t{\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\t\t\t// test mode\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\r\n\t\t\t  // check input stream\r\n\t\t\tif (boost::iequals(opts.getStrVal(\"smiles\"),opts.getStrVal(\"model\"))) {\r\n\t\t\t\tthrow ArgException(\"cannot read both SMILES and model from same stream\");\r\n\t\t\t}\r\n\r\n\t\t\t  // read model\r\n\t\t\tAP_NSPDK_Model model;\r\n\t\t\tmodel.modelID = modelID;\r\n\r\n\t\t\t  // check if default model to be used\r\n\t\t\tif (opts.getStrVal(\"model\").size() == 1\r\n\t\t\t\t&& std::string(\"OoMmCc\").find(opts.getStrVal(\"model\").at(0)) != std::string::npos )\r\n\t\t\t{\r\n\t\t\t\t// load default model\r\n\t\t\t\tswitch ( opts.getStrVal(\"model\").at(0) ) {\r\n\t\t\t\tcase 'O' :\r\n\t\t\t\tcase 'o' :\r\n\t\t\t\t\tmodel = *(AP_NSPDK_Model::getInstance(\"OpenBabel:2013\"));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 'M' :\r\n\t\t\t\tcase 'm' :\r\n\t\t\t\t\tmodel = *(AP_NSPDK_Model::getInstance(\"Marvin:general:2013\"));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault :\r\n\t\t\t\t\tthrow ArgException(\"unhandled default model character '\"+opts.getStrVal(\"model\")+\"'\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\t  // get model from stream\r\n\r\n\t\t\t\t  // set model input stream\r\n\t\t\t\tif (boost::iequals(opts.getStrVal(\"model\"),\"STDIN\")) {\r\n\t\t\t\t\t  // read from STDIN\r\n\t\t\t\t\tinModel = &std::cin;\r\n\t\t\t\t} else {\r\n\t\t\t\t\t  // check if any model input given\r\n\t\t\t\t\tif (opts.getStrVal(\"model\").size() == 0) {\r\n\t\t\t\t\t\tthrow ArgException(\"test mode but no model input specified\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\t  // read from file\r\n\t\t\t\t\tinModelFile = new std::ifstream( opts.getStrVal(\"model\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t\t\t, std::ifstream::in );\r\n\t\t\t\t\tif (!inModelFile->is_open()) {\r\n\t\t\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\t\t\toss\t<<\"cannot open model input file '\" <<opts.getStrVal(\"model\") <<\"'\";\r\n\t\t\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t\t\t}\r\n\t\t\t\t\tinModel = inModelFile;\r\n\t\t\t\t}\r\n\t\t\t\t  // read model from stream\r\n\t\t\t\treadModel( *inModel, model );\r\n\t\t\t}\r\n\t\t\tif (opts.argExist(\"ringCentered\") && !model.ringCentered) {\r\n\t\t\t\tthrow ArgException(\"Parameter 'ringCentered' is not applicable for the used model\");\r\n\t\t\t}\r\n\r\n\t\t\t  // create AP_NSPDK instance for feature generation using the model\r\n\t\t\tAP_NSPDK apNSPDK( & model );\r\n\r\n\t\t\t  // timing setup\r\n\t\t\tbiu::Timer timer;\r\n\t\t\tdouble timeGenerating = 0.0;\r\n\t\t\tdouble timeTesting = 0.0;\r\n\r\n\t\t\t  // result counting\r\n\t\t\tenum Result { OVERALL, CORRECT\r\n\t\t\t\t\t\t, OVERALL_AROM, CORRECT_AROM\r\n\t\t\t\t\t\t, OVERALL_NON, CORRECT_NON\r\n\t\t\t\t\t\t, OVERALL_MOL, CORRECT_MOL\r\n\t\t\t\t\t\t, RES_NUM };\r\n\t\t\tstd::vector< size_t > count( RES_NUM, 0 );\r\n\r\n\t\t\t  // test each ring of each molecule\r\n\t\t\tfor (size_t i=0; i<SMILES.size(); ++i ) {\r\n\r\n\t\t\t\tcount[OVERALL_MOL]++;\r\n\t\t\t\t  // create features of all rings within current molecule\r\n\t\t\t\tsgd::xvec_t testFeatures;\r\n\t\t\t\tsgd::yvec_t testTarget;\r\n\t\t\t\ttimer.start();\r\n\t\t\t\tgetFeatures( apNSPDK, SMILES.at(i), testFeatures, testTarget );\r\n\t\t\t\ttimeGenerating += timer.stop();\r\n\r\n\t\t\t\t  // test each ring independently\r\n\t\t\t\tbool allRingsCorrect = true;\r\n\t\t\t\tfor (size_t t=0; t<testFeatures.size(); ++t) {\r\n\t\t\t\t\t  // test instance\r\n\t\t\t\t\ttimer.start();\r\n\t\t\t\t\tconst double predictionValue = model.predictValue( testFeatures.at(t) );\r\n\t\t\t\t\ttimeTesting += timer.stop();\r\n\t\t\t\t\t  // count instance\r\n\t\t\t\t\tcount[OVERALL]++;\r\n\t\t\t\t\t  // report target and prediction if needed\r\n\t\t\t\t\tif (prediction != NULL) {\r\n\t\t\t\t\t\t*prediction <<testTarget.at(t) <<\" \" <<predictionValue <<\"\\n\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconst bool isAromatic = predictionValue >= 0;\r\n\t\t\t\t\tif (testTarget.at(t) > 0) {\r\n\t\t\t\t\t\tcount[OVERALL_AROM]++;\r\n\t\t\t\t\t\tif (isAromatic) {\r\n\t\t\t\t\t\t\tcount[CORRECT]++;\r\n\t\t\t\t\t\t\tcount[CORRECT_AROM]++;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tallRingsCorrect = false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tcount[OVERALL_NON]++;\r\n\t\t\t\t\t\tif (!isAromatic) {\r\n\t\t\t\t\t\t\tcount[CORRECT]++;\r\n\t\t\t\t\t\t\tcount[CORRECT_NON]++;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tallRingsCorrect = false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t  // count overall molecule prediction\r\n\t\t\t\tif (allRingsCorrect) {\r\n\t\t\t\t\tcount[CORRECT_MOL]++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t  // print statistics\r\n\t\t\t*out\r\n\t\t\t\t<<\" time generating test   = \" <<(size_t)timeGenerating <<\" ms\"\r\n\t\t\t\t<<\"\\n time testing           = \" <<(size_t)timeTesting <<\" ms\"\r\n\t\t\t\t<<\"\\n overall rings correct  = \" << count[CORRECT] << \" / \" <<count[OVERALL]\r\n\t\t\t\t<<\" = \" <<(double(count[CORRECT])/double(count[OVERALL])*100.0)\r\n\t\t\t\t<<\" %\"\r\n\t\t\t\t<<\"\\n aromatic rings correct = \" << count[CORRECT_AROM] << \" / \" <<count[OVERALL_AROM]\r\n\t\t\t\t<<\" = \" <<(double(count[CORRECT_AROM])/double(count[OVERALL_AROM])*100.0)\r\n\t\t\t\t<<\" %\"\r\n\t\t\t\t<<\"\\n non-aromatic r correct = \" << count[CORRECT_NON] << \" / \" <<count[OVERALL_NON]\r\n\t\t\t\t<<\" = \" <<(double(count[CORRECT_NON])/double(count[OVERALL_NON])*100.0)\r\n\t\t\t\t<<\" %\"\r\n\t\t\t\t<<\"\\n whole molecule correct = \" << count[CORRECT_MOL] << \" / \" <<count[OVERALL_MOL]\r\n\t\t\t\t<<\" = \" <<(double(count[CORRECT_MOL])/double(count[OVERALL_MOL])*100.0)\r\n\t\t\t\t<<\" %\"\r\n\t\t\t\t<<\"\\n\" <<std::endl;\r\n\r\n\r\n\t\t}; break;\r\n\t\tcase MODE_APPLY :\r\n\t\t{\r\n\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\t\t\t// application mode\r\n\t\t\t/////////////////////////////////////////////////////////////\r\n\r\n\t\t\t  // check input stream\r\n\t\t\tif (boost::iequals(opts.getStrVal(\"smiles\"),opts.getStrVal(\"model\"))) {\r\n\t\t\t\tthrow ArgException(\"cannot read both SMILES and model from same stream\");\r\n\t\t\t}\r\n\r\n\t\t\t  // read model\r\n\t\t\tAP_NSPDK_Model model;\r\n\t\t\tmodel.modelID = modelID;\r\n\r\n\t\t\t  // check if default model to be used\r\n\t\t\tif (opts.getStrVal(\"model\").size() == 1\r\n\t\t\t\t&& std::string(\"OoMmCc\").find(opts.getStrVal(\"model\").at(0)) != std::string::npos )\r\n\t\t\t{\r\n\t\t\t\t// load default model\r\n\t\t\t\tswitch ( opts.getStrVal(\"model\").at(0) ) {\r\n\t\t\t\tcase 'O' :\r\n\t\t\t\tcase 'o' :\r\n\t\t\t\t\tmodel = *(AP_NSPDK_Model::getInstance(\"OpenBabel:2013\"));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 'M' :\r\n\t\t\t\tcase 'm' :\r\n\t\t\t\t\tmodel = *(AP_NSPDK_Model::getInstance(\"Marvin:general:2013\"));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault :\r\n\t\t\t\t\tthrow ArgException(\"unhandled default model character '\"+opts.getStrVal(\"model\")+\"'\");\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\t  // get model from stream\r\n\r\n\t\t\t\t  // set model input stream\r\n\t\t\t\tif (boost::iequals(opts.getStrVal(\"model\"),\"STDIN\")) {\r\n\t\t\t\t\t  // read from STDIN\r\n\t\t\t\t\tinModel = &std::cin;\r\n\t\t\t\t} else {\r\n\t\t\t\t\t  // check if any model input given\r\n\t\t\t\t\tif (opts.getStrVal(\"model\").size() == 0) {\r\n\t\t\t\t\t\tthrow ArgException(\"test mode but no model input specified\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\t  // read from file\r\n\t\t\t\t\tinModelFile = new std::ifstream( opts.getStrVal(\"model\").c_str()\r\n\t\t\t\t\t\t\t\t\t\t\t\t, std::ifstream::in );\r\n\t\t\t\t\tif (!inModelFile->is_open()) {\r\n\t\t\t\t\t\tstd::ostringstream oss;\r\n\t\t\t\t\t\toss\t<<\"cannot open model input file '\" <<opts.getStrVal(\"model\") <<\"'\";\r\n\t\t\t\t\t\tthrow ArgException(oss.str());\r\n\t\t\t\t\t}\r\n\t\t\t\t\tinModel = inModelFile;\r\n\t\t\t\t}\r\n\t\t\t\t  // read model from stream\r\n\t\t\t\treadModel( *inModel, model );\r\n\t\t\t}\r\n\r\n\t\t\tif (opts.argExist(\"ringCentered\") && !model.ringCentered) {\r\n\t\t\t\tthrow ArgException(\"Parameter 'ringCentered' is not applicable for the used model\");\r\n\t\t\t}\r\n\r\n\t\t\t  // create AP_NSPDK instance for feature generation using the model\r\n\t\t\tAP_NSPDK apNSPDK( & model );\r\n\r\n\t\t\t  // whether or not weighted GML output or SMILES is to be generated\r\n\t\t\tbool outputWeightGML = opts.argExist(\"outNodeWeight\");\r\n\t\t\tbool multilineGML = false;\r\n\r\n\t\t\t  // run aromaticity perception for each molecule\r\n\t\t\tfor (size_t i=0; i<SMILES.size(); ++i ) {\r\n\r\n\t\t\t\t  // get molecule graph\r\n\t\t\t\tstd::pair< Molecule, int > parse = SMILESparser::parseSMILES( SMILES.at(i) );\r\n\r\n\t\t\t\t  // proton handling\r\n\t\t\t\tMolecule mol;\r\n\t\t\t\tMoleculeUtil::copy( parse.first, mol );\r\n\t\t\t\tMoleculeUtil::fillProtons( mol );\r\n\r\n\t\t\t\t  // apply aromaticity perception\r\n\t\t\t\tapNSPDK.correctAromaticity( mol, false );\r\n\r\n\t\t\t\tif (outputWeightGML) {\r\n\t\t\t\t\t  // write weighted GML output\r\n\t\t\t\t\tprintWeightedGML( *out, apNSPDK, mol, multilineGML );\r\n\t\t\t\t} else {\r\n\t\t\t\t\t  // write SMILES output\r\n\t\t\t\t\t*out <<ggl::chem::SMILESwriter::getSMILES( mol );\r\n\t\t\t\t}\r\n\t\t\t\t  // line break after each molecule\r\n\t\t\t\t*out <<std::endl;\r\n\t\t\t}\r\n\r\n\t\t}; break;\r\n\t\tcase MODE_UNDEF : {\r\n\t\t\tthrow ArgException(\"no mode selected\"); // should never occur\r\n\t\t}; break;\r\n\t\tdefault:\r\n\t\t\tthrow ArgException(\"unknown mode selected\"); // should never occur\r\n\t\t}\r\n\r\n\t} catch (std::exception& ex) {\r\n\t\tstd::cerr <<\"\\n\\n ERROR : \" <<ex.what() <<\"\\n\"<<std::endl;\r\n\t\texitValue = -1;\r\n\t}\r\n\r\n\r\n\t//////////////////////////////////////////////////////////////\r\n\t// final stream handling\r\n\t//////////////////////////////////////////////////////////////\r\n\r\n\tinSMILES = &std::cin;\r\n\tinModel = &std::cin;\r\n\tout = &std::cout;\r\n\tlog = &std::cerr;\r\n\tprediction = NULL;\r\n\tif (inSMILESFile != NULL)\t{ inSMILESFile->close(); delete inSMILESFile; }\r\n\tif (inModelFile != NULL)\t{ inModelFile->close(); delete inModelFile; }\r\n\tif (outFile != NULL)\t\t{ outFile->close(); delete outFile; }\r\n\tif (logFile != NULL)\t\t{ logFile->close(); delete logFile; }\r\n\tif (predictionFile != NULL)\t{ predictionFile->close(); delete predictionFile; }\r\n\r\n\treturn exitValue;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n/*!\r\n * Initialises allowed parameters and their default values and prepares an\r\n * information string for the tool.\r\n */\r\nvoid\r\ninitAllowedArguments(biu::OptionMap & allowedArgs, std::string &infoText )\r\n{\r\n\tinfoText = \"\\n\"\r\n\t\t\"Reads a list of SMILES and trains/tests/applies an aromaticity\"\r\n\t\t\" model using NSPDK and the SGD framework.\\n\"\r\n\t\t\"\\n\"\r\n\t\t;\r\n\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"mode\", false, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"Running mode : 'train' : train a model using the given parameters;\"\r\n\t\t\t\t\t\t\t\" 'xval' : does an 'xval'-cross validation using the given model training parameters and prints target-prediction value pairs to 'out';\"\r\n\t\t\t\t\t\t\t\" 'cluster' : clusters the training data based on feature identity for a model using the given parameters;\"\r\n\t\t\t\t\t\t\t\" 'test' : tests the prediction of ring wise and for whole molecules (model needed);\"\r\n\t\t\t\t\t\t\t\" 'apply' : applies the given model to each molecule and prints the corrected SMILES (model needed)\"\r\n\t\t\t\t\t\t\t));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"smiles\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"SMILES input file name or 'STDIN' when to read from standard input\",\r\n\t\t\t\t\t\t\t\"STDIN\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"out\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"Output file name or 'STDOUT' when to write to standard output\",\r\n\t\t\t\t\t\t\t\"STDOUT\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"log\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"Log file name or 'STDERR'/'STDOUT' when to write to standard error / output\",\r\n\t\t\t\t\t\t\t\"STDERR\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"prediction\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"Prediction file name or 'STDERR'/'STDOUT' when to write to standard error / output\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"model\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"models input file name, or 'STDIN' when to read from standard input, or a single letter code for one of the default models : (O)penBabel or (M)arvin general mode.\",\r\n\t\t\t\t\t\t\t\"STDIN\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"modelID\", true, biu::COption::STRING,\r\n\t\t\t\t\t\t\t\"the models ID to set\",\r\n\t\t\t\t\t\t\t\"NSPDK-SGD-aromaticity-model\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"maxRingSize\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"the maximal ring size to be considered for aromatic ring training/testing\",\r\n\t\t\t\t\t\t\t\"13\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"ringCentered\", true, biu::COption::BOOL,\r\n\t\t\t\t\t\t\t\"NSPDK: if given, the NSPDK features have to touch the ring of interest in at least one node\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"nspdkMaxRingDistance\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"NSPDK: IF(ringCentered) : the distance from ring nodes to be considered for feature generation\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"nspdkMaxDistance\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"NSPDK: the maximal distance between nodes to be considered for feature generation\",\r\n\t\t\t\t\t\t\t\"4\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"nspdkMaxRadius\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"NSPDK: the maximal radius around nodes to be considered for feature generation\",\r\n\t\t\t\t\t\t\t\"2\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"nspdkFeatureBitSize\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"NSPDK: the number of bits used to encode the NSPDK features\",\r\n\t\t\t\t\t\t\t\"22\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"lambda\", true, biu::COption::DOUBLE,\r\n\t\t\t\t\t\t\t\"[mode=train] the lambda factor used by the SGD framework\",\r\n\t\t\t\t\t\t\t\"1e-4\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"epochs\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"[mode=train] the number of training epochs performed by the SGD framework\",\r\n\t\t\t\t\t\t\t\"5\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"outClustLists\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"[mode=cluster] number of random cluster sample lists to be reported\",\r\n\t\t\t\t\t\t\t\"1\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"xval\", true, biu::COption::INT,\r\n\t\t\t\t\t\t\t\"[mode=xval] sets the X for X-cross validation, ie. the number of groups to randomly split the input into\",\r\n\t\t\t\t\t\t\t\"10\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"outNodeWeight\", true, biu::COption::BOOL,\r\n\t\t\t\t\t\t\t\"[mode=apply] output is given in GML format where for each ring the normalized feature weights for view point nodes are provided\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"help\", true, biu::COption::BOOL,\r\n\t\t\t\t\t\t\t\"Displays help on all parameters\"));\r\n\tallowedArgs.push_back(biu::COption(\r\n\t\t\t\t\t\t\t\"version\", true, biu::COption::BOOL,\r\n\t\t\t\t\t\t\t\"Version information\"));\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid getFeatures( AP_NSPDK & ap\r\n\t\t\t\t, const std::string & molSMILES\r\n\t\t\t\t, sgd::xvec_t& trainFeatures\r\n\t\t\t\t, sgd::yvec_t& trainTarget )\r\n{\r\n\r\n\t  // get molecule graph\r\n\tstd::pair< Molecule, int > parse = SMILESparser::parseSMILES( molSMILES );\r\n\r\n\t  // fill protons\r\n\tMolecule mol;\r\n\tMoleculeUtil::copy( parse.first, mol );\r\n\tMoleculeUtil::fillProtons( mol );\r\n\r\n\t  // call final function\r\n\tgetFeatures(ap, mol, trainFeatures, trainTarget, NULL);\r\n\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid getFeatures( AP_NSPDK & ap\r\n\t\t\t\t, const Molecule & mol\r\n\t\t\t\t, sgd::xvec_t& trainFeatures\r\n\t\t\t\t, sgd::yvec_t& trainTarget\r\n\t\t\t\t, std::vector< sgm::RingReporter::RingList > * trainRing\r\n\t\t\t\t)\r\n{\r\n\r\n\t  // get features\r\n\tstd::vector< std::pair< sgm::RingReporter::RingList, nspdk::SVector> > features = ap.getFeatures( mol );\r\n\r\n\t  // create a dummy graph to get access to the ring labels\r\n\tggl::chem::Molecule_Graph molGraph(mol);\r\n\r\n\t  // feed all rings to the feature vector\r\n\tfor (size_t i=0; i<features.size(); ++i ) {\r\n\r\n\t\t  // check if aromatic ring via bond labels\r\n\t\tsgm::RingReporter::RingList::const_iterator cur = features.at(i).first.begin();\r\n\t\tsgm::RingReporter::RingList::const_iterator last = features.at(i).first.begin();\r\n\t\tbool isAromatic = true;\r\n\t\tfor (++cur; isAromatic && cur!=features.at(i).first.end();++cur,++last) {\r\n\t\t\tassert( molGraph.getEdgesBegin(*last,*cur) != molGraph.getEdgesEnd(*last,*cur) /*no edge present*/);\r\n\t\t\tisAromatic = MoleculeUtil::getBondData(molGraph.getEdgesBegin(*last,*cur)->getEdgeLabel())->isAromatic != 0;\r\n\t\t}\r\n\r\n\t\t  // store features\r\n\t\ttrainFeatures.push_back( features.at(i).second );\r\n\t\t  // store training target\r\n\t\ttrainTarget.push_back( isAromatic ? +1 : -1 );\r\n\t\t  // store ring information\r\n\t\tif (trainRing != NULL) {\r\n\t\t\ttrainRing->push_back( features.at(i).first );\r\n\t\t}\r\n\r\n\r\n\t}\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n/*!\r\n * Parses SMILES strings from stream. Each line should contain only ONE SMILES\r\n * string. Leading and tailing whitespaces are ignored.\r\n *\r\n * @param in the stream to read from\r\n * @param toFill the STL inserter to add the found SMILES to\r\n *\r\n */\r\nvoid\r\nparseSMILES(\tstd::istream & in\r\n\t\t\t\t, SMILES_inserter & toFill\r\n\t\t\t\t, const size_t linesRead ) throw(std::exception)\r\n{\r\n\tstd::string line;\r\n\tsize_t lineNumber = linesRead;\r\n\tconst std::string WHITESPACES = std::string(\" \\t\\n\");\r\n\t  // parse whole input stream\r\n\twhile (in.good()) {\r\n\t\t  // read next line\r\n\t\tstd::getline( in, line );\r\n\t\tlineNumber++;\r\n\r\n\t\t  // check if line is not empty\r\n\t\tif (line.size() > 0) {\r\n\t\t\tsize_t start = line.find_first_not_of(WHITESPACES);\r\n\t\t\t  // check if line is not only filled with blanks\r\n\t\t\tif (start != std::string::npos ) {\r\n\t\t\t\tsize_t end = line.find_last_not_of(WHITESPACES);\r\n\t\t\t\t  // add SMILES string to inserter\r\n\t\t\t\t*toFill = line.substr( start, end - start + 1 );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nreadModel( std::istream & in, AP_NSPDK_Model & model )\r\n{\r\n\tin\r\n\t\t>> model.ringCentered\r\n\t\t>> model.nspdk_maxRingDistance\r\n\t\t>> model.nspdk_maxDistance\r\n\t\t>> model.nspdk_maxRadius\r\n\t\t>> model.nspdk_featureBitSize\r\n\t\t>> model.maxRingSize\r\n\t\t>> model.bias\r\n\t\t>> model.wscale\r\n\t\t>> model.w\r\n\t;\r\n\r\n\tmodel.ringEdgeLabel = \"*~\";\r\n\tmodel.ringNodeLabelPrefix = \"*\";\r\n\tmodel.ringViewLabelPrefix = \"?\";\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nprintModel( std::ostream & out, const AP_NSPDK_Model & model )\r\n{\r\n\tout\r\n\t\t<< model.ringCentered <<\" \"\r\n\t\t<< model.nspdk_maxRingDistance <<\" \"\r\n\t\t<< model.nspdk_maxDistance <<\" \"\r\n\t\t<< model.nspdk_maxRadius <<\" \"\r\n\t\t<< model.nspdk_featureBitSize <<\" \"\r\n\t\t<< model.maxRingSize <<\" \"\r\n\t\t<< model.bias <<\" \"\r\n\t\t<< model.wscale <<\" \"\r\n\t\t<< model.w <<\"\\n\"\r\n\t;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nannotateRing( Molecule & mol, const sgm::RingReporter::RingList & ring, bool addAnnotation )\r\n{\r\n\r\n\tconst std::string ringClass = \":1\";\r\n\r\n\t  // label access\r\n\tboost::property_map< ggl::chem::Molecule, ggl::chem::PropNodeLabel >::type\r\n\t\tnodeLabel = boost::get( ggl::chem::PropNodeLabel(), mol );\r\n\r\n\t  // update ring vertices\r\n\tsgm::RingReporter::RingList::const_iterator cur = ring.begin();\r\n\tfor (++cur; cur!=ring.end();++cur) {\r\n\r\n\t\t  // get vertex\r\n\t\tMolecule::vertex_descriptor node = boost::vertex( *cur, mol );\r\n\r\n\t\t  // get current atom label\r\n\t\tstd::string atomLabel = nodeLabel[node];\r\n\r\n\t\t  // alter the atom label accordingly\r\n\t\tif (addAnnotation) {\r\n\t\t\t  // ensure the ring class is not present\r\n\t\t\tassert( atomLabel.find(ringClass) == std::string::npos );\r\n\t\t\tatomLabel += ringClass;\r\n\t\t} else {\r\n\t\t\t  // ensure the ring class is present\r\n\t\t\tassert( atomLabel.find(ringClass) != std::string::npos );\r\n\t\t\tatomLabel = atomLabel.substr(0,atomLabel.find(ringClass));\r\n\r\n\t\t}\r\n\r\n\t\t  // set altered label\r\n\t\tnodeLabel[ node ] = atomLabel;\r\n\t}\r\n\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nvoid\r\nprintWeightedGML( std::ostream & out, AP_NSPDK & apNSPDK, const Molecule & mol, const bool multilineGML )\r\n{\r\n\r\n\tstd::string linesep = (multilineGML ? \"\\n\" : \"\");\r\n\tstd::string indent = (multilineGML ? \"  \" : \"\");\r\n\r\n\t  // get weights for each ring\r\n\tstd::vector< std::pair< AP_NSPDK::RingDescriptor, AP_NSPDK::RingWeightVec> >\r\n\t\tweightsPerRing = apNSPDK.getNodeWeights( mol );\r\n\r\n\t  // generate additional GML information for each ring\r\n\tstd::stringstream ringGmlEncoding;\r\n\t  // change bond and node labels\r\n\t  // for each predicted ring\r\n\tfor (size_t i=0; i<weightsPerRing.size(); ++i)\r\n\t{\r\n\t\tconst AP_NSPDK::RingDescriptor & ring = weightsPerRing.at(i).first;\r\n\t\tconst AP_NSPDK::RingWeightVec & ringWeights = weightsPerRing.at(i).second;\r\n\r\n\t\t  // general ring informationring\r\n\t\tringGmlEncoding <<\"ring [\" <<linesep\r\n\t\t\t\t\t\t<<indent <<\"label \\\"\"\r\n\t\t\t\t\t\t<<(ring.predState == AP_NSPDK::RingDescriptor::Aromatic ? \"aromatic\" : \"non-aromatic\" )\r\n\t\t\t\t\t\t<<\":\"\r\n\t\t\t\t\t\t<<ring.predCertainty\r\n\t\t\t\t\t\t<<\"\\\"\"<<linesep\r\n\t\t  // ring nodes\r\n\t\t\t\t\t\t<<\" ringNodes [ \"\r\n\t\t\t\t\t\t;\r\n\t\t  // start from second node, since first and last node are the same\r\n\t\tsgm::RingReporter::RingList::const_iterator ringNode = ring.ring.begin();\r\n\t\tfor (ringNode++;ringNode != ring.ring.end(); ++ringNode )\r\n\t\t{\r\n\t\t\tringGmlEncoding <<\"id \" <<*ringNode <<\" \";\r\n\t\t}\r\n\t\tringGmlEncoding\t<<\"]\" <<linesep;\r\n\r\n\t\t  // print node weights\r\n\t\tfor (AP_NSPDK::RingWeightVec::const_iterator weight = ringWeights.begin();\r\n\t\t\t\tweight != ringWeights.end(); ++weight )\r\n\t\t{\r\n\t\t\tringGmlEncoding <<indent <<\"nodeWeight [ id \" <<weight->first <<\" label \\\"\" <<weight->second <<\"\\\" ]\" <<linesep;\r\n\t\t}\r\n\r\n\t\t  // print GML end\r\n\t\tringGmlEncoding <<\"]\" <<linesep;\r\n\r\n\t}\r\n\r\n\t  // write final molecule to stream in GML format\r\n\tstd::string additionalGML = ringGmlEncoding.str();\r\n\tGraph_GML_writer::write( out, mol, multilineGML, &additionalGML );\r\n\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\nbool\r\nSVector_less(const sgd::SVector& v, const sgd::SVector & vCompare)\r\n{\r\n\t\t  // get iterators over sparse entries\r\n\t\tconst sgd::SVector::Pair *p1 = v, *p2 = vCompare;\r\n\r\n\t\t// skip all equal elements\r\n\t\tfor( ; p1->i >= 0 && p2->i >= 0 && p1->i == p2->i && p1->v == p2->v; p1++,p2++)\r\n\t\t{ /* just go to next entries */}\r\n\r\n\t\t  // check first non-equal element\r\n\t\tif (p1->i < p2->i ) {\r\n\t\t\t  // if (p1->i < 0) one additional larger entry in vCompare,\r\n\t\t\t  // else one entry in v existing that is 0 in vCompare\r\n\t\t\treturn (p1->i < 0 && p2->v > 0) || (p1->i > 0 && p1->v < 0);\r\n\t\t} else if (p1->i > p2->i) {\r\n\t\t\t  // if (p2->i < 0) one additional larger entry in v,\r\n\t\t\t  // else one entry in vCompare existing that is 0 in v\r\n\t\t\treturn (p2->i < 0 && p1->v < 0) || (p2->i > 0 && p2->v > 0);\r\n\t\t} else {\r\n\t\t\t// p1->i == p2->i\r\n\t\t\tif (p1->i < 0) {\r\n\t\t\t\t  // all the same\r\n\t\t\t\treturn false;\r\n\t\t\t} else {\r\n\t\t\t\t  // check if v is smaller\r\n\t\t\t\treturn p1->v < p2->v;\r\n\t\t\t}\r\n\t\t}\r\n\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n", "meta": {"hexsha": "31b53e0d453ed7228c1c63b8346f5b48ecef9ae9", "size": 48027, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/aromModelNSPDK.cc", "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/bin/aromModelNSPDK.cc", "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/bin/aromModelNSPDK.cc", "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": 33.2596952909, "max_line_length": 173, "alphanum_fraction": 0.5802361172, "num_tokens": 12778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.022286183996952688, "lm_q1q2_score": 0.009757414732494066}}
{"text": "// Copyright (c) 2014 The Dacrs developers\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"base58.h\"\n\n#include \"hash.h\"\n#include \"uint256.h\"\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n#include <vector>\n#include <string>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/static_visitor.hpp>\n\n/* All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" */\nstatic const char* g_pstaBase58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nbool DecodeBase58(const char *psz, vector<unsigned char>& vch) {\n\t// Skip leading spaces.\n\twhile (*psz && isspace(*psz)) {\n\t\tpsz++;\n\t}\n\n\t// Skip and count leading '1's.\n\tint nZeroes = 0;\n\twhile (*psz == '1') {\n\t\tnZeroes++;\n\t\tpsz++;\n\t}\n\n\t// Allocate enough space in big-endian base256 representation.\n\t// log(58) / log(256), rounded up.\n\tvector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1);\n\t// Process the characters.\n\twhile (*psz && !isspace(*psz)) {\n\t\t// Decode base58 character\n\t\tconst char *ch = strchr(g_pstaBase58, *psz);\n\t\tif (ch == NULL) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Apply \"b256 = b256 * 58 + ch\".\n\t\tint carry = ch - g_pstaBase58;\n\t\tfor (vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {\n\t\t\tcarry += 58 * (*it);\n\t\t\t*it = carry % 256;\n\t\t\tcarry /= 256;\n\t\t}\n\t\tassert(carry == 0);\n\t\tpsz++;\n\t}\n\n\t// Skip trailing spaces.\n\twhile (isspace(*psz)) {\n\t\tpsz++;\n\t}\n\n\tif (*psz != 0) {\n\t\treturn false;\n\t}\n\n\t// Skip leading zeroes in b256.\n\tvector<unsigned char>::iterator iter = b256.begin();\n\twhile (iter != b256.end() && *iter == 0) {\n\t\titer++;\n\t}\n\n\t// Copy result into output vector.\n\tvch.reserve(nZeroes + (b256.end() - iter));\n\tvch.assign(nZeroes, 0x00);\n\twhile (iter != b256.end()) {\n\t\tvch.push_back(*(iter++));\n\t}\n\n\treturn true;\n}\n\nstring EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) {\n\t// Skip & count leading zeroes.\n\tint nZeroes = 0;\n\twhile (pbegin != pend && *pbegin == 0) {\n\t\tpbegin++;\n\t\tnZeroes++;\n\t}\n\t// Allocate enough space in big-endian base58 representation.\n\tvector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.\n\t// Process the bytes.\n\twhile (pbegin != pend) {\n\t\tint carry = *pbegin;\n\t\t// Apply \"b58 = b58 * 256 + ch\".\n\t\tfor (vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {\n\t\t\tcarry += 256 * (*it);\n\t\t\t*it = carry % 58;\n\t\t\tcarry /= 58;\n\t\t}\n\t\tassert(carry == 0);\n\t\tpbegin++;\n\t}\n\n\t// Skip leading zeroes in base58 result.\n\tvector<unsigned char>::iterator iter = b58.begin();\n\twhile (iter != b58.end() && *iter == 0) {\n\t\titer++;\n\t}\n\n\t// Translate the result into a string.\n\tstring str;\n\tstr.reserve(nZeroes + (b58.end() - iter));\n\tstr.assign(nZeroes, '1');\n\twhile (iter != b58.end()) {\n\t\tstr += g_pstaBase58[*(iter++)];\n\t}\n\n\treturn str;\n}\n\nstring EncodeBase58(const vector<unsigned char>& vch) {\n\treturn EncodeBase58(&vch[0], &vch[0] + vch.size());\n}\n\nbool DecodeBase58(const string& str, vector<unsigned char>& vchRet) {\n\treturn DecodeBase58(str.c_str(), vchRet);\n}\n\nstring EncodeBase58Check(const vector<unsigned char>& vchIn) {\n\t// add 4-byte hash check to the end\n\tvector<unsigned char> vch(vchIn);\n\tuint256 hash = Hash(vch.begin(), vch.end());\n\tvch.insert(vch.end(), (unsigned char*) &hash, (unsigned char*) &hash + 4);\n\treturn EncodeBase58(vch);\n}\n\nbool DecodeBase58Check(const char* psz, vector<unsigned char>& vchRet) {\n\tif (!DecodeBase58(psz, vchRet)) {\n\t\treturn false;\n\t}\n\n\tif (vchRet.size() < 4) {\n\t\tvchRet.clear();\n\t\treturn false;\n\t}\n\n\t// re-calculate the checksum, insure it matches the included 4-byte checksum\n\tuint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);\n\tif (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {\n\t\tvchRet.clear();\n\t\treturn false;\n\t}\n\tvchRet.resize(vchRet.size() - 4);\n\n\treturn true;\n}\n\nbool DecodeBase58Check(const string& str, vector<unsigned char>& vchRet) {\n\treturn DecodeBase58Check(str.c_str(), vchRet);\n}\n\nCBase58Data::CBase58Data() {\n\tm_vchVersion.clear();\n\tm_vchData.clear();\n}\n\nvoid CBase58Data::SetData(const vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize) {\n\tm_vchVersion = vchVersionIn;\n\tm_vchData.resize(nSize);\n\tif (!m_vchData.empty()) {\n\t\tmemcpy(&m_vchData[0], pdata, nSize);\n\t}\n}\n\nvoid CBase58Data::SetData(const vector<unsigned char> &vchVersionIn, const unsigned char *pbegin,\n\t\tconst unsigned char *pend) {\n\tSetData(vchVersionIn, (void*) pbegin, pend - pbegin);\n}\n\nbool CBase58Data::SetString(const char* psz, unsigned int unVersionBytes) {\n\tvector<unsigned char> vchTemp;\n\tDecodeBase58Check(psz, vchTemp);\n\tif (vchTemp.size() < unVersionBytes) {\n\t\tm_vchData.clear();\n\t\tm_vchVersion.clear();\n\t\treturn false;\n\t}\n\n\tm_vchVersion.assign(vchTemp.begin(), vchTemp.begin() + unVersionBytes);\n\tm_vchData.resize(vchTemp.size() - unVersionBytes);\n\tif (!m_vchData.empty()) {\n\t\tmemcpy(&m_vchData[0], &vchTemp[unVersionBytes], m_vchData.size());\n\t}\n\n\tOPENSSL_cleanse(&vchTemp[0], m_vchData.size());\n\treturn true;\n}\n\nbool CBase58Data::SetString(const string& str) {\n\treturn SetString(str.c_str());\n}\n\nstring CBase58Data::ToString() const {\n\tvector<unsigned char> vch = m_vchVersion;\n\tvch.insert(vch.end(), m_vchData.begin(), m_vchData.end());\n\treturn EncodeBase58Check(vch);\n}\n\nint CBase58Data::CompareTo(const CBase58Data& cBase58) const {\n\tif (m_vchVersion < cBase58.m_vchVersion) {\n\t\treturn -1;\n\t}\n\n\tif (m_vchVersion > cBase58.m_vchVersion) {\n\t\treturn 1;\n\t}\n\n\tif (m_vchData < cBase58.m_vchData) {\n\t\treturn -1;\n\t}\n\n\tif (m_vchData > cBase58.m_vchData) {\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nnamespace {\nclass CDacrsAddressVisitor: public boost::static_visitor<bool> {\n public:\n\tCDacrsAddressVisitor(CDacrsAddress *addrIn) :\n\t\tm_cDacrsAddr(addrIn) {\n\t}\n\n\tbool operator()(const CKeyID &id) const {\n\t\treturn m_cDacrsAddr->Set(id);\n\t}\n\n\tbool operator()(const CNoDestination &no) const {\n\t\treturn false;\n\t}\n\n private:\n\tCDacrsAddress *m_cDacrsAddr;\n};\n};\n\nbool CDacrsAddress::Set(const CKeyID &cId) {\n\tSetData(SysCfg().Base58Prefix(CBaseParams::EM_PUBKEY_ADDRESS), &cId, 20);\n\treturn true;\n}\n\nbool CDacrsAddress::Set(const CTxDestination &cDest) {\n\treturn boost::apply_visitor(CDacrsAddressVisitor(this), cDest);\n}\n\nbool CDacrsAddress::IsValid() const {\n\tbool bValid = false;\n\t{\n\t\tbool bCorrectSize = m_vchData.size() == 20;\n\t\tbool bKnownVersion = m_vchVersion == SysCfg().Base58Prefix(CBaseParams::EM_PUBKEY_ADDRESS);\n\t\tbValid = bCorrectSize && bKnownVersion;\n\t}\n\n\tif (!bValid) {\n\t\tvector<unsigned char> vid;\n\t\tvid.push_back(CBaseParams::EM_ACC_ADDRESS);\n\t\tif (m_vchData.size() == 26 && m_vchVersion == vid) {\n\t\t\tbValid = true;\n\t\t}\n\t}\n\n\treturn bValid;\n}\n\nCTxDestination CDacrsAddress::Get() const {\n\tif (!IsValid()) {\n\t\treturn CNoDestination();\n\t}\n\n\tif (m_vchData.size() == 20) {\n\t\tuint160 cId;\n\t\tmemcpy(&cId, &m_vchData[0], 20);\n\n\t\tif (m_vchVersion == SysCfg().Base58Prefix(CBaseParams::EM_PUBKEY_ADDRESS)) {\n\t\t\treturn CKeyID(cId);\n\t\t} else {\n\t\t\treturn CNoDestination();\n\t\t}\n\t} else {\n\t\treturn CNoDestination();\n\t}\n}\n\nbool CDacrsAddress::GetKeyID(CKeyID &keyID) const {\n\tuint160 cId;\n\n\tif (m_vchVersion == SysCfg().Base58Prefix(CBaseParams::EM_PUBKEY_ADDRESS) && m_vchData.size() == 20) {\n\t\tmemcpy(&cId, &m_vchData[0], 20);\n\t\tkeyID = CKeyID(cId);\n\t\treturn true;\n\t}\n\n\tvector<unsigned char> vuchId;\n\tvuchId.push_back(CBaseParams::EM_ACC_ADDRESS);\n\tif (m_vchData.size() == 26 && m_vchVersion == vuchId) {\n\t\tmemcpy(keyID.begin(), &m_vchData[0], 20);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n//bool CDacrsAddress::GetRegID(CRegID &Regid) const {\n//\n////\tvector<unsigned char> vid;\n////\tvid.push_back(CBaseParams::ACC_ADDRESS);\n//\tif (vchData.size() == 26 && vchVersion == vector<unsigned char>(CBaseParams::ACC_ADDRESS)) {\n//\t\tRegid.SetRegID(vector<unsigned char>(vchData.end()-6,vchData.end()));\n//\t\treturn true;\n//\t}\n//\treturn false;\n//}\n\nbool CDacrsAddress::IsScript() const {\n\treturn IsValid() && m_vchVersion == SysCfg().Base58Prefix(CBaseParams::EM_SCRIPT_ADDRESS);\n}\n\nvoid CDacrsSecret::SetKey(const CKey& vchSecret) {\n\tassert(vchSecret.IsValid());\n\tSetData(SysCfg().Base58Prefix(CBaseParams::EM_SECRET_KEY), vchSecret.begin(), vchSecret.size());\n\tif (vchSecret.IsCompressed()) {\n\t\tm_vchData.push_back(1);\n\t}\n}\n\nCKey CDacrsSecret::GetKey() {\n\tCKey cRet;\n\tcRet.Set(&m_vchData[0], &m_vchData[32], m_vchData.size() > 32 && m_vchData[32] == 1);\n\treturn cRet;\n}\n\nbool CDacrsSecret::IsValid() const {\n\tbool bExpectedFormat = m_vchData.size() == 32 || (m_vchData.size() == 33 && m_vchData[32] == 1);\n\tbool bCorrectVersion = m_vchVersion == SysCfg().Base58Prefix(CBaseParams::EM_SECRET_KEY);\n\treturn bExpectedFormat && bCorrectVersion;\n}\n\nbool CDacrsSecret::SetString(const char* pszSecret) {\n\treturn CBase58Data::SetString(pszSecret) && IsValid();\n}\n\nbool CDacrsSecret::SetString(const string& strSecret) {\n\treturn SetString(strSecret.c_str());\n}\n", "meta": {"hexsha": "245a429799e5fcdf5cc3b39ac34f7b797ea085e3", "size": 8841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/base58.cpp", "max_stars_repo_name": "SoyPay/dacrs", "max_stars_repo_head_hexsha": "ddeb4741beb83756ccc85fd611c66d8be8cb3bad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T09:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T13:49:21.000Z", "max_issues_repo_path": "src/base58.cpp", "max_issues_repo_name": "SoyPay/dacrs", "max_issues_repo_head_hexsha": "ddeb4741beb83756ccc85fd611c66d8be8cb3bad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-03-11T08:51:51.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-25T01:39:43.000Z", "max_forks_repo_path": "src/base58.cpp", "max_forks_repo_name": "SoyPay/dacrs", "max_forks_repo_head_hexsha": "ddeb4741beb83756ccc85fd611c66d8be8cb3bad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T04:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T09:47:27.000Z", "avg_line_length": 24.8342696629, "max_line_length": 103, "alphanum_fraction": 0.6803529013, "num_tokens": 2732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821862, "lm_q2_score": 0.03461883908817703, "lm_q1q2_score": 0.009741935859362578}}
{"text": "/*\r\n(c) 2012 Fengtao Fan\r\n*/\r\n#include \"psbmReebGraph.h\"\r\n#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n#include <cmath>\r\n#include <string>\r\n#include \"SimpleMesh.h\"\r\n#include \"FilesOutputForOptimalCycles.h\"\r\n\r\n\r\n#include <time.h>\r\n#include <sstream>\r\n#include <boost/progress.hpp>\r\n#include <boost/program_options.hpp>\r\n\r\n//\r\nbool CheckBoundaries(_SimpleMesh &inMesh, std::vector<std::vector<std::pair<int, int> > > &boundries) {\r\n    bool ret = false;\r\n    std::vector<bool> edge_flag(inMesh.vecEdge.size(), false);\r\n    for (unsigned int i = 0; i < inMesh.vecEdge.size(); i++) {\r\n        if (!edge_flag[i] && inMesh.vecEdge[i].AdjTriNum == 1) {// this is a boundary edge\r\n            ret = true;\r\n            std::vector<std::pair<int, int> > bdrEdges;\r\n            //\r\n            int terminate_vertex = inMesh.vecEdge[i].v0;\r\n            int current_vertex = inMesh.vecEdge[i].v1;\r\n            int current_edge = i;\r\n            int loop_counter = 0;\r\n            while (current_vertex != terminate_vertex) {\r\n                bdrEdges.push_back(std::pair<int, int>(current_edge, inMesh.vecEdge[current_edge].AdjTri[0]));\r\n                edge_flag[current_edge] = true;\r\n                //\r\n                unsigned int evid = 0;\r\n                for (; evid < inMesh.vecVertex[current_vertex].adjEdges.size(); evid++) {\r\n                    int rot_edge_id = inMesh.vecVertex[current_vertex].adjEdges[evid];\r\n                    if (rot_edge_id != current_edge && inMesh.vecEdge[rot_edge_id].AdjTriNum == 1)\r\n                        break;\r\n                }\r\n                if (evid < inMesh.vecVertex[current_vertex].adjEdges.size()) {\r\n                    current_edge = inMesh.vecVertex[current_vertex].adjEdges[evid];\r\n                    current_vertex = inMesh.vecEdge[current_edge].v0 + inMesh.vecEdge[current_edge].v1 - current_vertex;\r\n                } else {\r\n                    std::cout << \"READING MESH MODEL ERROR : \" << std::endl;\r\n                    std::cout << \"--- CAN NOT FIND ADJACENT BOUDNARY EDGE !\" << std::endl;\r\n                    std::cout << \"--- PLEASE CHECK THE MESH MODEL\" << std::endl;\r\n                    exit(0);\r\n                }\r\n                loop_counter++;\r\n                if (loop_counter > inMesh.vecEdge.size()) {\r\n                    std::cout << \"READING MESH MODEL ERROR : \" << std::endl;\r\n                    std::cout << \"--- PLEASE CHECK THE MESH MODEL\" << std::endl;\r\n                    exit(0);\r\n                }\r\n            }\r\n            edge_flag[current_edge] = true;\r\n            bdrEdges.push_back(std::pair<int, int>(current_edge, inMesh.vecEdge[current_edge].AdjTri[0]));\r\n            //\r\n            boundries.push_back(bdrEdges);\r\n        }\r\n        edge_flag[i] = true;\r\n    }\r\n    return ret;\r\n}\r\n\r\nvoid FindEdgeOrientation(_SimpleMesh &inMesh, const int fid, std::vector<int> &OrientTriangles,\r\n                         std::pair<int, int> &EdgeOrientation) {\r\n    int start_index = 3 * fid;\r\n    std::vector<int> TriOrientation(OrientTriangles.begin() + start_index, OrientTriangles.begin() + start_index + 3);\r\n    TriOrientation.push_back(TriOrientation.front());\r\n    //\r\n    for (unsigned int i = 0; i < 3; i++) {\r\n        if ((EdgeOrientation.first == TriOrientation[i] && EdgeOrientation.second == TriOrientation[i + 1]) ||\r\n            (EdgeOrientation.second == TriOrientation[i] && EdgeOrientation.first == TriOrientation[i + 1])) {\r\n            EdgeOrientation.first = TriOrientation[i + 1];\r\n            EdgeOrientation.second = TriOrientation[i];\r\n        }\r\n    }\r\n    return;\r\n}\r\n\r\nvoid CloseHoles(_SimpleMesh &inMesh, std::vector<std::vector<std::pair<int, int> > > &meshBoundaries,\r\n                std::vector<Vector3> &inMeshNormal,\r\n                std::vector<int> &OrientTriangles, std::set<int> &extraVertices) {\r\n    for (unsigned int b = 0; b < meshBoundaries.size(); b++) {\r\n        Vector3 centroid(0.0, 0.0, 0.0);\r\n        int curEdge = 0;\r\n        int nextEdge = 0;\r\n        int curVertex = 0;\r\n        for (unsigned int i = 0; i < meshBoundaries[b].size(); i++) {// the edges on the boundary is ordered\r\n            curEdge = meshBoundaries[b][i].first;\r\n            nextEdge = meshBoundaries[b][0].first;\r\n            if (i < meshBoundaries[b].size() - 1)\r\n                nextEdge = meshBoundaries[b][i + 1].first;\r\n            // shared vertex\r\n            curVertex = inMesh.vecEdge[curEdge].v0;\r\n            if (curVertex != inMesh.vecEdge[nextEdge].v0 &&\r\n                curVertex != inMesh.vecEdge[nextEdge].v1)\r\n                curVertex = inMesh.vecEdge[curEdge].v1;\r\n            //\r\n            centroid = centroid + Vector3(inMesh.vecVertex[curVertex].x,\r\n                                          inMesh.vecVertex[curVertex].y,\r\n                                          inMesh.vecVertex[curVertex].z);\r\n            //\r\n        }\r\n        centroid = centroid / meshBoundaries[b].size();\r\n        //\r\n        // add vertex\r\n        int centroid_index = inMesh.vecVertex.size();\r\n        extraVertices.insert(centroid_index);\r\n        _SimpleMeshVertex tmpVer;\r\n        tmpVer.x = centroid[0];\r\n        tmpVer.y = centroid[1];\r\n        tmpVer.z = centroid[2];\r\n        //\r\n        inMesh.vecVertex.push_back(tmpVer);\r\n        //\r\n        // add edges and triangles\r\n        std::map<int, int> edge_mapping;\r\n        for (unsigned int i = 0; i < meshBoundaries[b].size(); i++) {\r\n            // Find orientation of this edge\r\n            curEdge = meshBoundaries[b][i].first;\r\n            std::pair<int, int> EdgeOrientation(inMesh.vecEdge[curEdge].v0, inMesh.vecEdge[curEdge].v1);\r\n            FindEdgeOrientation(inMesh, meshBoundaries[b][i].second, OrientTriangles, EdgeOrientation);\r\n            //\r\n            OrientTriangles.push_back(EdgeOrientation.first);\r\n            OrientTriangles.push_back(EdgeOrientation.second);\r\n            OrientTriangles.push_back(centroid_index);\r\n            //\r\n            _SimpleMeshTriangle tmpTri;\r\n            _SimpleMeshEdge tmpEdge;\r\n            //\r\n            tmpTri.v0 = EdgeOrientation.first;\r\n            tmpTri.v1 = EdgeOrientation.second;\r\n            tmpTri.v2 = centroid_index;\r\n            //\r\n            //\r\n            Vector3 leftVec, rightVec;\r\n            leftVec[0] = inMesh.vecVertex[tmpTri.v2].x - inMesh.vecVertex[tmpTri.v1].x;\r\n            leftVec[1] = inMesh.vecVertex[tmpTri.v2].y - inMesh.vecVertex[tmpTri.v1].y;\r\n            leftVec[2] = inMesh.vecVertex[tmpTri.v2].z - inMesh.vecVertex[tmpTri.v1].z;\r\n\r\n            rightVec[0] = inMesh.vecVertex[tmpTri.v0].x - inMesh.vecVertex[tmpTri.v1].x;\r\n            rightVec[1] = inMesh.vecVertex[tmpTri.v0].y - inMesh.vecVertex[tmpTri.v1].y;\r\n            rightVec[2] = inMesh.vecVertex[tmpTri.v0].z - inMesh.vecVertex[tmpTri.v1].z;\r\n            leftVec = leftVec ^ rightVec;\r\n            unitize(leftVec);\r\n            //leftVec = leftVec / norm(leftVec);\r\n            inMeshNormal.push_back(leftVec);\r\n            //\r\n            tmpTri.sortVertices();\r\n            // [v0 v1] existing edge\r\n            inMesh.vecEdge[curEdge].AdjTriNum++;\r\n            inMesh.vecEdge[curEdge].AdjTri[1] = inMesh.vecTriangle.size();\r\n            //\r\n            tmpTri.e01 = curEdge;\r\n            //\r\n            std::map<int, int>::iterator mIter;\r\n            mIter = edge_mapping.find(tmpTri.v1);\r\n            if (mIter == edge_mapping.end()) {// new edge\r\n                tmpEdge.v0 = tmpTri.v1;\r\n                tmpEdge.v1 = tmpTri.v2;\r\n                tmpEdge.AdjTri[0] = inMesh.vecTriangle.size();\r\n                tmpEdge.AdjTriNum = 1;\r\n                //\r\n                inMesh.vecEdge.push_back(tmpEdge);\r\n                tmpTri.e12 = inMesh.vecEdge.size() - 1;\r\n                edge_mapping[tmpTri.v1] = tmpTri.e12;\r\n                //\r\n                inMesh.vecVertex[tmpEdge.v0].adjEdges.push_back(tmpTri.e12);\r\n                inMesh.vecVertex[tmpEdge.v1].adjEdges.push_back(tmpTri.e12);\r\n            } else {// existed edge\r\n                inMesh.vecEdge[mIter->second].AdjTriNum++;\r\n                inMesh.vecEdge[mIter->second].AdjTri[1] = inMesh.vecTriangle.size();\r\n                //\r\n                tmpTri.e12 = mIter->second;\r\n            }\r\n            mIter = edge_mapping.find(tmpTri.v0);\r\n            if (mIter == edge_mapping.end()) {\r\n                // new edge\r\n                tmpEdge.v0 = tmpTri.v0;\r\n                tmpEdge.v1 = tmpTri.v2;\r\n                tmpEdge.AdjTri[0] = inMesh.vecTriangle.size();\r\n                tmpEdge.AdjTriNum = 1;\r\n                //\r\n                inMesh.vecEdge.push_back(tmpEdge);\r\n                tmpTri.e02 = inMesh.vecEdge.size() - 1;\r\n                edge_mapping[tmpTri.v0] = tmpTri.e02;\r\n                //\r\n                inMesh.vecVertex[tmpEdge.v0].adjEdges.push_back(tmpTri.e02);\r\n                inMesh.vecVertex[tmpEdge.v1].adjEdges.push_back(tmpTri.e02);\r\n            } else {// existed already\r\n                inMesh.vecEdge[mIter->second].AdjTriNum++;\r\n                inMesh.vecEdge[mIter->second].AdjTri[1] = inMesh.vecTriangle.size();\r\n                //\r\n                tmpTri.e02 = mIter->second;\r\n            }\r\n            //\r\n            inMesh.vecTriangle.push_back(tmpTri);\r\n        }\r\n    }\r\n    return;\r\n}\r\n\r\nint LoadData(_SimpleMesh &mesh, std::vector<Vector3> &meshNormal,\r\n             const char *mesh_file_name, double &BoundingBoxRadius, std::vector<int> &tris,\r\n             std::set<int> &extraVertices, int &orgTriangleSize,\r\n             const float fEnlargeFactor) {\r\n    int genus = 0;\r\n    _SimpleMeshVertex minBd;\r\n    _SimpleMeshVertex maxBd;\r\n    mesh.LoadMeshInOFFformat(minBd, maxBd, meshNormal, mesh_file_name, tris,\r\n                             fEnlargeFactor);//\"E:\\\\RProgramming\\\\Models\\\\torus.off\");// \"D:\\\\MeshModels\\\\OFF-models\\\\HighGenusCubeHC1.off\");//\r\n    mesh.SetMeshNormalPtr(&meshNormal);\r\n    // triangles in TRIS are in the same order as triangles in mesh.vecTriangle;\r\n    //\r\n    orgTriangleSize = mesh.vecTriangle.size();\r\n    //\r\n    std::vector<std::vector<std::pair<int, int> > > meshBoundaries;\r\n    if (CheckBoundaries(mesh, meshBoundaries)) {// it is a mesh with bondary\r\n        int EulerCharacteristic = mesh.vecVertex.size() + mesh.vecTriangle.size() - mesh.vecEdge.size();\r\n        genus = 1 - (EulerCharacteristic + meshBoundaries.size()) / 2;\r\n        if (genus) {\r\n            CloseHoles(mesh, meshBoundaries, meshNormal, tris, extraVertices);\r\n        }\r\n    } else {// it is a closed mesh\r\n        int EulerCharacteristic = mesh.vecVertex.size() + mesh.vecTriangle.size() - mesh.vecEdge.size();\r\n        genus = 1 - EulerCharacteristic / 2;\r\n    }\r\n    if (!genus) {\r\n        std::cout << \"NOTHING IS COMPUTED : \" << std::endl;\r\n        std::cout << \" ---- MESH HAS GENUS 0!\" << std::endl;\r\n        exit(1);\r\n    }\r\n    std::cout << \"Mesh has genus : \" << genus << std::endl;\r\n    //\r\n\r\n// compute the bounding box\r\n\r\n    return genus;\r\n}\r\n\r\nvoid RandomUniqueDirection(_SimpleMesh &mesh, Vector3 &uniDirection) {\r\n    //\r\n    std::vector<Vector3> vecEdgeDirections(2 * mesh.vecEdge.size());\r\n    // all vectors are pointed to positive Z direction\r\n    for (unsigned int i = 0; i < mesh.vecEdge.size(); i++) {\r\n        vecEdgeDirections[i][0] = mesh.vecVertex[mesh.vecEdge[i].v0].x - mesh.vecVertex[mesh.vecEdge[i].v1].x;\r\n        vecEdgeDirections[i][1] = mesh.vecVertex[mesh.vecEdge[i].v0].y - mesh.vecVertex[mesh.vecEdge[i].v1].y;\r\n        vecEdgeDirections[i][2] = mesh.vecVertex[mesh.vecEdge[i].v0].z - mesh.vecVertex[mesh.vecEdge[i].v1].z;\r\n        //\r\n        if (vecEdgeDirections[i][2] < 0) {\r\n            for (int j = 0; j < 3; j++)\r\n                vecEdgeDirections[i][j] = -vecEdgeDirections[i][j];\r\n        }\r\n        //\r\n        unitize(vecEdgeDirections[i]);\r\n    }\r\n    int mesh_edge_size = mesh.vecEdge.size();\r\n    int opp_v_0;\r\n    int opp_v_1;\r\n    for (unsigned int i = 0; i < mesh.vecEdge.size(); i++) {\r\n        if (mesh.vecEdge[i].AdjTriNum == 2) {\r\n            opp_v_0 = mesh.vecEdge[i].AdjTri[0];\r\n            if (mesh.vecTriangle[opp_v_0].v0 != mesh.vecEdge[i].v0 &&\r\n                mesh.vecTriangle[opp_v_0].v0 != mesh.vecEdge[i].v1) {\r\n                opp_v_0 = mesh.vecTriangle[opp_v_0].v0;\r\n            } else {\r\n                if (mesh.vecTriangle[opp_v_0].v1 != mesh.vecEdge[i].v0 &&\r\n                    mesh.vecTriangle[opp_v_0].v1 != mesh.vecEdge[i].v1) {\r\n                    opp_v_0 = mesh.vecTriangle[opp_v_0].v1;\r\n                } else {\r\n                    opp_v_0 = mesh.vecTriangle[opp_v_0].v2;\r\n                }\r\n            }\r\n            //\r\n            opp_v_1 = mesh.vecEdge[i].AdjTri[1];\r\n            if (mesh.vecTriangle[opp_v_1].v0 != mesh.vecEdge[i].v0 &&\r\n                mesh.vecTriangle[opp_v_1].v0 != mesh.vecEdge[i].v1) {\r\n                opp_v_1 = mesh.vecTriangle[opp_v_1].v0;\r\n            } else {\r\n                if (mesh.vecTriangle[opp_v_1].v1 != mesh.vecEdge[i].v0 &&\r\n                    mesh.vecTriangle[opp_v_1].v1 != mesh.vecEdge[i].v1) {\r\n                    opp_v_1 = mesh.vecTriangle[opp_v_1].v1;\r\n                } else {\r\n                    opp_v_1 = mesh.vecTriangle[opp_v_1].v2;\r\n                }\r\n            }\r\n            //\r\n            vecEdgeDirections[i + mesh_edge_size][0] = mesh.vecVertex[opp_v_0].x - mesh.vecVertex[opp_v_1].x;\r\n            vecEdgeDirections[i + mesh_edge_size][1] = mesh.vecVertex[opp_v_0].y - mesh.vecVertex[opp_v_1].y;\r\n            vecEdgeDirections[i + mesh_edge_size][2] = mesh.vecVertex[opp_v_0].z - mesh.vecVertex[opp_v_1].z;\r\n            //\r\n            if (vecEdgeDirections[i + mesh_edge_size][2] < 0) {\r\n                for (int j = 0; j < 3; j++)\r\n                    vecEdgeDirections[i + mesh_edge_size][j] = -vecEdgeDirections[i + mesh_edge_size][j];\r\n            }\r\n            //\r\n            unitize(vecEdgeDirections[i + mesh_edge_size]);\r\n        }\r\n    }\r\n    //\r\n    srand(time(NULL));\r\n    //\r\n    int runTimesCounter = 0;\r\n    int halfRandMax = RAND_MAX >> 2;\r\n    bool bFindDirection = false;\r\n    double minAangleValue = 1.0;\r\n    double error_precision = 1e-7;\r\n    double max_running_counter = 2000;\r\n    while (!bFindDirection) {\r\n        runTimesCounter++;\r\n        for (int i = 0; i < 3; i++) {\r\n            uniDirection[i] = rand() - halfRandMax;\r\n        }\r\n        if (uniDirection[2] < 0) {\r\n            for (int i = 0; i < 3; i++)\r\n                uniDirection[i] = -uniDirection[i];\r\n        }\r\n        //\r\n        unitize(uniDirection);\r\n        //\r\n        bFindDirection = true;\r\n        minAangleValue = 1.0;\r\n        for (unsigned int i = 0; i < vecEdgeDirections.size(); i++) {\r\n            double angleValue = uniDirection * vecEdgeDirections[i];\r\n            if (angleValue < error_precision && angleValue > -error_precision) {\r\n                bFindDirection = false;\r\n                break;\r\n            }\r\n            if (std::abs(minAangleValue) > std::abs(angleValue))\r\n                minAangleValue = angleValue;\r\n        }\r\n        if (runTimesCounter > max_running_counter)\r\n            break;\r\n    }\r\n    //\r\n    //std::cout << \"run times : \" << runTimesCounter << std::endl;\r\n    //std::cout << \"min angle : \" << minAangleValue << std::endl;\r\n    //\r\n    return;\r\n}\r\n\r\n//\r\nvoid CycleLocalOptimization(_SimpleMesh &locMesh, psbmReebGraph &reebgraph, std::vector<int> &OrientTriangles,\r\n                            std::vector<std::set<int> > &v_basis,\r\n                            std::vector<std::set<int> > &h_basis, const float fEnlargeFactor);\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, const float fEnlargeFactor);\r\n\r\n////\r\nchar *strLicense = \"THIS SOFTWARE IS PROVIDED \\\"AS-IS\\\". THERE IS NO WARRANTY OF ANY KIND. \"\r\n                   \"NEITHER THE AUTHORS NOR THE OHIO STATE UNIVERSITY WILL BE LIABLE FOR \"\r\n                   \"ANY DAMAGES OF ANY KIND, EVEN IF ADVISED OF SUCH POSSIBILITY. \\n\"\r\n                   \"\\n\"\r\n                   \"This software was developed (and is copyrighted by) the Jyamiti group at \"\r\n                   \"The Ohio State University. Please do not redistribute this software. \"\r\n                   \"This program is for academic research use only. This software uses the \"\r\n                   \"CGAL library (www.cgal.org), Boost library (www.boost.org) and Ann library \"\r\n                   \"(www.cs.umd.edu/~mount/ANN/) which are covered under their own licenses.\\n\"\r\n                   \"\\n\"\r\n                   \"The CGAL library's license \"\r\n                   \"(which applies to the CGAL library ONLY and NOT to this program itself) is \"\r\n                   \"as follows:\\n\"\r\n                   \"\\n\"\r\n                   \"LICENSE\\n\"\r\n                   \"---------------------------------------------------------------------------\\n\"\r\n                   \"\\n\"\r\n                   \"The CGAL software consists of several parts, each of which is licensed under \"\r\n                   \"an open source license. It is also possible to obtain commercial licenses \"\r\n                   \"from GeometryFactory (www.geometryfactory.com) for all or parts of CGAL. \\n\"\r\n                   \"\\n\"\r\n                   \"The source code of the CGAL library can be found in the directories \"\r\n                   \"\\\"src/CGAL\\\", \\\"src/CGALQt\\\" and \\\"include/CGAL\\\". It is specified in each file of \"\r\n                   \"the CGAL library which license applies to it. This is either the GNU Lesser \"\r\n                   \"General Public License (as published by the Free Software Foundation; \"\r\n                   \"version 2.1 of the License) or the Q Public License (version 1.0). The texts \"\r\n                   \"of both licenses can be found in the files LICENSE.LGPL and LICENSE.QPL. \\n\"\r\n                   \"\\n\"\r\n                   \"Distributed along with CGAL (for the users' convenience), but not part of \"\r\n                   \"CGAL, are the following third-party libraries, available under their own \"\r\n                   \"licenses: \\n\"\r\n                   \"\\n\"\r\n                   \"- CORE, in the directories \\\"include/CORE\\\" and \\\"src/Core\\\", is licensed under\"\r\n                   \" the QPL (see LICENSE.QPL). \\n\"\r\n                   \"- OpenNL, in the directory \\\"include/OpenNL\\\", is licensed under the LGPL\"\r\n                   \" (see include/OpenNL/LICENSE.OPENNL). \\n\"\r\n                   \"- ImageIO, in the directory \\\"examples/Surface_mesher/ImageIO\\\", is licensed\"\r\n                   \" under the LGPL (see LICENSE.LGPL). \\n\"\r\n                   \"\\n\"\r\n                   \"All other files that do not have an explicit copyright notice (e.g., all \"\r\n                   \"examples and some demos) are licensed under a very permissive license. The \"\r\n                   \"exact license text can be found in the file LICENSE.FREE_USE. Note that some \"\r\n                   \"subdirectories have their own copy of LICENSE.FREE_USE. These copies have \"\r\n                   \"the same license text and differ only in the copyright holder.\\n\"\r\n                   \"---------------------------------------------------------------------------\\n\"\r\n                   \"\\n\"\r\n                   \"The Boost library's license \"\r\n                   \"(which applies to the Boost library ONLY and NOT to this program itself) is \"\r\n                   \"as follows:\\n\"\r\n                   \"\\n\"\r\n                   \"LICENSE\\n\"\r\n                   \"---------------------------------------------------------------------------\\n\"\r\n                   \"Boost Software License - Version 1.0 - August 17th, 2003\\n\"\r\n                   \"\\n\"\r\n                   \"Permission is hereby granted, free of charge, to any person or organization \"\r\n                   \"obtaining a copy of the software and accompanying documentation covered by \"\r\n                   \"this license (the \\\"Software\\\") to use, reproduce, display, distribute, \"\r\n                   \"execute, and transmit the Software, and to prepare derivative works of the \"\r\n                   \"Software, and to permit third-parties to whom the Software is furnished to \"\r\n                   \"do so, all subject to the following: \\n\"\r\n                   \"\\n\"\r\n                   \"The copyright notices in the Software and this entire statement, including \"\r\n                   \"the above license grant, this restriction and the following disclaimer, \"\r\n                   \"must be included in all copies of the Software, in whole or in part, and \"\r\n                   \"all derivative works of the Software, unless such copies or derivative \"\r\n                   \"works are solely in the form of machine-executable object code generated by \"\r\n                   \"a source language processor. \\n\"\r\n                   \"\\n\"\r\n                   \"THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \"\r\n                   \"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \"\r\n                   \"FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT \"\r\n                   \"SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE \"\r\n                   \"FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, \"\r\n                   \"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \"\r\n                   \"DEALINGS IN THE SOFTWARE. \\n\"\r\n                   \"---------------------------------------------------------------------------\\n\"\r\n                   \"\\n\"\r\n                   \"ANN library's license \"\r\n                   \"(which applies to the ANN library ONLY and NOT to this program itself) is \"\r\n                   \"as follows: \\n\"\r\n                   \"\\n\"\r\n                   \"LICENSE\\n\"\r\n                   \"---------------------------------------------------------------------------\\n\"\r\n                   \"The ANN Library (all versions) is provided under the terms and \"\r\n                   \"conditions of the GNU Lesser General Public Library, which is stated \"\r\n                   \"below.  It can also be found at: \\n\"\r\n                   \"\\n\"\r\n                   \"   http:\\//www.gnu.org/copyleft/lesser.html \\n\"\r\n                   \"---------------------------------------------------------------------------\\n\";\r\n\r\n//char * strLicense = \"THIS SOFTWARE IS PROVIDED \\\"AS-IS\\\". http:\\//www.gnu.org/copyleft/lesser.html THERE IS NO WARRANTY OF ANY KIND. \\n\";\r\nbool ParseCommand(int argc, char **argv, std::string &InputFile, std::string &OutputFile) {\r\n    try {\r\n        /* Define the program options description\r\n        */\r\n        namespace po = boost::program_options;\r\n        po::options_description desc(\"ReebHanTun Usage\");\r\n        desc.add_options()\r\n                (\",h\", \"Help information\")\r\n                (\",l\", \"License information\")\r\n                (\",I\", po::value<std::string>(&InputFile)->required(), \"Input file name\")\r\n                (\",O\", po::value<std::string>(&OutputFile)->required(), \"Output file name prefix\");\r\n\r\n        // Parser map\r\n        po::variables_map vm;\r\n        try {\r\n            po::store(po::parse_command_line(argc, argv, desc), vm);\r\n\r\n            //\r\n            if (vm.count(\"-h\")) {\r\n                std::cout << desc << std::endl;\r\n            }\r\n            //\r\n            if (vm.count(\"-l\")) {\r\n                std::cout << strLicense << std::endl;\r\n            }\r\n            //\r\n            po::notify(vm);\r\n        }\r\n        catch (boost::program_options::required_option &e) {\r\n            std::cerr << \"ERROR: \" << e.what() << std::endl;\r\n            return false;\r\n        }\r\n        catch (boost::program_options::error &e) {\r\n            std::cerr << \"ERROR: \" << e.what() << std::endl;\r\n            return false;\r\n        }\r\n        //if (vm.count(\"-I\"))\r\n        //{\r\n        //\tstd::cout << vm[\"-I\"].as<std::string>() << std::endl;\r\n        //}\r\n        //if (vm.count(\"-O\"))\r\n        //{\r\n        //\tstd::cout << vm[\"-O\"].as<std::string>() << std::endl;\r\n        //}\r\n    }\r\n    catch (std::exception &e) {\r\n        std::cerr << \"Unhandled Exception reached the top of main: \"\r\n                  << e.what() << \", application will now exit\" << std::endl;\r\n        return false;\r\n\r\n    }\r\n    return true;\r\n}\r\n\r\nint main(int argc, char **argv) {\r\n    std::string InputFileName;\r\n    std::string OutputFileName;\r\n    Vector3 distinctDirection;\r\n    //\r\n    _SimpleMesh mesh;\r\n    const float fEnlargeFactor = 10000.f;\r\n    std::vector<std::set<int> > v_basis_loops;\r\n    std::vector<std::set<int> > h_basis_loops;\r\n    //\r\n    psbmReebGraph reebGraph;\r\n    std::vector<Vector3> meshNormal;\r\n    //\r\n    if (ParseCommand(argc, argv, InputFileName, OutputFileName)) {\r\n        //\r\n        std::vector<int> OrientTriangles;\r\n        std::set<int> extraVertices;\r\n        int nOrgTriangleSize = 0;\r\n        double BoundingBoxRadius;\r\n        LoadData(mesh, meshNormal, InputFileName.c_str(), BoundingBoxRadius, OrientTriangles, extraVertices,\r\n                 nOrgTriangleSize, fEnlargeFactor);\r\n        //////\r\n\r\n        RandomUniqueDirection(mesh, distinctDirection);\r\n        //\r\n        //std::cout << distinctDirection[0] << \" \" <<\r\n        //\t\t\t distinctDirection[1] << \" \" <<\r\n        //\t\t\t distinctDirection[2] << std::endl;\r\n\r\n        //\r\n\r\n        reebGraph.ReserveSpaceForEdges(mesh.vecEdge.size());\r\n        //\r\n        double *scalarField = new double[mesh.vecVertex.size()];\r\n        int perDir = 0;\r\n        int rayDir = 0;\r\n        for (unsigned int i = 0; i < mesh.vecVertex.size(); i++) {\r\n            scalarField[i] = mesh.vecVertex[i].x * distinctDirection[0] +\r\n                             mesh.vecVertex[i].y * distinctDirection[1] +\r\n                             mesh.vecVertex[i].z * distinctDirection[2];\r\n        }\r\n        reebGraph.SetHeightDirection(distinctDirection);\r\n        reebGraph.AssignData(&mesh, scalarField);\r\n        reebGraph.scalarDir = 1;// x=0, y=1, z=2\r\n        //\r\n        //minimumDiffBetweenVertices(scalarField);\r\n        //\r\n        std::cout << std::endl;\r\n        {\r\n            boost::progress_timer t;\r\n            //\r\n            reebGraph.ComputeReebGraph();\r\n            //\r\n        }\r\n        {\r\n        \treebGraph.WriteReebGraphOBJ(\"casting.obj\", mesh.vecVertex);\r\n        \tstd::cout << \"Vertices in RG : \" << reebGraph.pVecReebNode->size() << std::endl;\r\n        \tstd::cout << \"Edges in RG : \" << reebGraph.pListReebArc->size() << std::endl;\r\n        \tstd::cout << \"Genus is : \" << reebGraph.pListReebArc->size() - reebGraph.pVecReebNode->size() + 1  << std::endl;\r\n        }\r\n        {\r\n            boost::progress_timer t;\r\n            ////\r\n            std::cout << \"Time for mapping and linking :\" << std::endl;\r\n            //reebGraph.ComputeCycleAndPairing();\r\n            reebGraph.ComputingCycle_max_tree();\r\n\r\n//            reebGraph.WriteSimplifiedReebGraphOBJ(\"casting-sim.obj\", mesh.vecVertex);\r\n\r\n            //std::cout << \"mapping\" << std::endl;\r\n            //// computing the cycle on surface\r\n            reebGraph.compute_path_on_mesh_for_each_simplified_arc();//pathArcOnMesh, offsetPathArcOnMesh);\r\n\r\n            //std::cout << \"embed\" << std::endl;\r\n            reebGraph.EmbedCycleAsEdgePathOnMesh();\r\n            //std::cout << \"linking\" << std::endl;\r\n            reebGraph.LinkNumberMatrixComputing();\r\n\r\n        }\r\n        //\r\n\r\n        //\r\n        if (extraVertices.empty())\r\n            CycleLocalOptimization(mesh, reebGraph, OrientTriangles, v_basis_loops, h_basis_loops,\r\n                                   1.f / fEnlargeFactor);\r\n        else\r\n            CycleLocalOptimization_bdry(mesh, reebGraph, OrientTriangles, v_basis_loops, h_basis_loops, extraVertices,\r\n                                        1.f / fEnlargeFactor);\r\n        //\r\n        std::cout << \"Handle and tunnel loops written in files :  \\n\";\r\n        FilesOutputForOptimalCycles files_out_op;\r\n        files_out_op.InitMeshPtr(&mesh);\r\n        files_out_op.WriteCyclesInformation(OutputFileName.c_str(), v_basis_loops, h_basis_loops);\r\n        int orgVertexSize = mesh.vecVertex.size();\r\n        if (!extraVertices.empty())\r\n            orgVertexSize = *extraVertices.begin();\r\n        files_out_op.WriteGeomviewListFormat(OutputFileName.c_str(), v_basis_loops, h_basis_loops, OrientTriangles,\r\n                                             orgVertexSize, nOrgTriangleSize, 1.f / fEnlargeFactor);\r\n\r\n        ///////////////////////////////////////////////////\r\n    }\r\n    return 1;\r\n}\r\n\r\n", "meta": {"hexsha": "f190d1fcd8d9645749a1756effc64aece39d8f83", "size": 28657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ComputeReebGraph.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/ComputeReebGraph.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/ComputeReebGraph.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": 47.2887788779, "max_line_length": 144, "alphanum_fraction": 0.5251073036, "num_tokens": 6573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158251284363395, "lm_q2_score": 0.028436032530251773, "lm_q1q2_score": 0.00971325144698672}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP\r\n\r\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\r\n// This file is automatically generated. DO NOT EDIT.\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 4.9.1\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#include <boost/geometry/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\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct ocea {};\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 ocea\r\n    {\r\n            template <typename T>\r\n            struct par_ocea\r\n            {\r\n                T    rok;\r\n                T    rtk;\r\n                T    sinphi;\r\n                T    cosphi;\r\n                T    singam;\r\n                T    cosgam;\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_ocea_spheroid : public base_t_fi<base_ocea_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>\r\n            {\r\n\r\n                typedef CalculationType geographic_type;\r\n                typedef CalculationType cartesian_type;\r\n\r\n                par_ocea<CalculationType> m_proj_parm;\r\n\r\n                inline base_ocea_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_ocea_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    static const CalculationType ONEPI = detail::ONEPI<CalculationType>();\r\n\r\n                    CalculationType t;\r\n\r\n                    xy_y = sin(lp_lon);\r\n                /*\r\n                    xy_x = atan2((tan(lp_lat) * this->m_proj_parm.cosphi + this->m_proj_parm.sinphi * xy_y) , cos(lp_lon));\r\n                */\r\n                    t = cos(lp_lon);\r\n                    xy_x = atan((tan(lp_lat) * this->m_proj_parm.cosphi + this->m_proj_parm.sinphi * xy_y) / t);\r\n                    if (t < 0.)\r\n                        xy_x += ONEPI;\r\n                    xy_x *= this->m_proj_parm.rtk;\r\n                    xy_y = this->m_proj_parm.rok * (this->m_proj_parm.sinphi * sin(lp_lat) - this->m_proj_parm.cosphi * cos(lp_lat) * xy_y);\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    CalculationType t, s;\r\n\r\n                    xy_y /= this->m_proj_parm.rok;\r\n                    xy_x /= this->m_proj_parm.rtk;\r\n                    t = sqrt(1. - xy_y * xy_y);\r\n                    lp_lat = asin(xy_y * this->m_proj_parm.sinphi + t * this->m_proj_parm.cosphi * (s = sin(xy_x)));\r\n                    lp_lon = atan2(t * this->m_proj_parm.sinphi * s - xy_y * this->m_proj_parm.cosphi,\r\n                        t * cos(xy_x));\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"ocea_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Oblique Cylindrical Equal Area\r\n            template <typename Parameters, typename T>\r\n            inline void setup_ocea(Parameters& par, par_ocea<T>& proj_parm)\r\n            {\r\n                static const T HALFPI = detail::HALFPI<T>();\r\n\r\n                T phi_0=0.0, phi_1, phi_2, lam_1, lam_2, lonz, alpha;\r\n\r\n                proj_parm.rok = 1. / par.k0;\r\n                proj_parm.rtk = par.k0;\r\n                if ( pj_param(par.params, \"talpha\").i) {\r\n                    alpha    = pj_param(par.params, \"ralpha\").f;\r\n                    lonz = pj_param(par.params, \"rlonc\").f;\r\n                    proj_parm.singam = atan(-cos(alpha)/(-sin(phi_0) * sin(alpha))) + lonz;\r\n                    proj_parm.sinphi = asin(cos(phi_0) * sin(alpha));\r\n                } else {\r\n                    phi_1 = pj_param(par.params, \"rlat_1\").f;\r\n                    phi_2 = pj_param(par.params, \"rlat_2\").f;\r\n                    lam_1 = pj_param(par.params, \"rlon_1\").f;\r\n                    lam_2 = pj_param(par.params, \"rlon_2\").f;\r\n                    proj_parm.singam = atan2(cos(phi_1) * sin(phi_2) * cos(lam_1) -\r\n                        sin(phi_1) * cos(phi_2) * cos(lam_2),\r\n                        sin(phi_1) * cos(phi_2) * sin(lam_2) -\r\n                        cos(phi_1) * sin(phi_2) * sin(lam_1) );\r\n                    if (lam_1 == -HALFPI)\r\n                        proj_parm.singam = -proj_parm.singam;\r\n                    proj_parm.sinphi = atan(-cos(proj_parm.singam - lam_1) / tan(phi_1));\r\n                }\r\n                par.lam0 = proj_parm.singam + HALFPI;\r\n                proj_parm.cosphi = cos(proj_parm.sinphi);\r\n                proj_parm.sinphi = sin(proj_parm.sinphi);\r\n                proj_parm.cosgam = cos(proj_parm.singam);\r\n                proj_parm.singam = sin(proj_parm.singam);\r\n                par.es = 0.;\r\n            }\r\n\r\n    }} // namespace detail::ocea\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Oblique Cylindrical 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         - Cylindrical\r\n         - Spheroid\r\n        \\par Projection parameters\r\n         - lonc: Longitude (only used if alpha (or gamma) is specified) (degrees)\r\n         - alpha: Alpha (degrees)\r\n         - lat_1: Latitude of first standard parallel (degrees)\r\n         - lat_2: Latitude of second standard parallel (degrees)\r\n         - lon_1 (degrees)\r\n         - lon_2 (degrees)\r\n        \\par Example\r\n        \\image html ex_ocea.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct ocea_spheroid : public detail::ocea::base_ocea_spheroid<CalculationType, Parameters>\r\n    {\r\n        inline ocea_spheroid(const Parameters& par) : detail::ocea::base_ocea_spheroid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::ocea::setup_ocea(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::ocea, ocea_spheroid, ocea_spheroid)\r\n\r\n        // Factory entry(s)\r\n        template <typename CalculationType, typename Parameters>\r\n        class ocea_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                    return new base_v_fi<ocea_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void ocea_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"ocea\", new ocea_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_OCEA_HPP\r\n\r\n", "meta": {"hexsha": "ca0cf9b6f9c38051c47974c4cd9ab326ef6c3f94", "size": 9752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/ocea.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/ocea.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/ocea.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0344827586, "max_line_length": 141, "alphanum_fraction": 0.5872641509, "num_tokens": 2222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208213138121609, "lm_q2_score": 0.03021458477509262, "lm_q1q2_score": 0.00969348278383413}}
{"text": "/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http://www.bh107.org>.\n\nBohrium is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/foreach.hpp>\n#include <fstream>\n#include <numeric>\n#include <queue>\n#include <cassert>\n\n#include <bohrium/jitk/graph.hpp>\n#include <bohrium/jitk/block.hpp>\n#include <bohrium/jitk/iterator.hpp>\n\nusing namespace std;\n\nnamespace bohrium {\nnamespace jitk {\nnamespace graph {\n\n/* Determines whether there exist a path from 'a' to 'b'\n *\n * Complexity: O(E + V)\n *\n * @a               The first vertex\n * @b               The second vertex\n * @dag             The DAG\n * @only_long_path  Only accept path of length greater than one\n * @return          True if there is a path\n */\nbool path_exist(Vertex a, Vertex b, const DAG &dag, bool only_long_path) {\n    using namespace boost;\n\n    struct path_visitor:default_bfs_visitor {\n        const Vertex dst;\n        path_visitor(Vertex b):dst(b){};\n\n        void examine_edge(Edge e, const DAG &g) const {\n            if(target(e,g) == dst)\n                throw runtime_error(\"\");\n        }\n    };\n    struct long_visitor:default_bfs_visitor {\n        const Vertex src, dst;\n        long_visitor(Vertex a, Vertex b):src(a),dst(b){};\n\n        void examine_edge(Edge e, const DAG &g) const\n        {\n            if(source(e,g) != src and target(e,g) == dst)\n                throw runtime_error(\"\");\n        }\n    };\n    try {\n        if(only_long_path)\n            breadth_first_search(dag, a, visitor(long_visitor(a,b)));\n        else\n            breadth_first_search(dag, a, visitor(path_visitor(b)));\n    }\n    catch (const runtime_error &e) {\n        return true;\n    }\n    return false;\n}\n\n// Create a DAG based on the 'block_list'\nDAG from_block_list(const vector<Block> &block_list) {\n    DAG graph;\n    map<const bh_base*, set<Vertex> > base2vertices;\n    for (const Block &block: block_list) {\n        assert(block.validation());\n        Vertex vertex = boost::add_vertex(block, graph);\n\n        // Find all vertices that must connect to 'vertex'\n        // using and updating 'base2vertices'\n        set<Vertex> connecting_vertices;\n        for (const bh_base *base: block.getAllBases()) {\n            set<Vertex> &vs = base2vertices[base];\n            connecting_vertices.insert(vs.begin(), vs.end());\n            vs.insert(vertex);\n        }\n        // Let's add edges to 'vertex'\n        BOOST_REVERSE_FOREACH (Vertex v, connecting_vertices) {\n            if (vertex != v and block.dependOn(graph[v])) {\n                boost::add_edge(v, vertex, graph);\n            }\n        }\n        // Then we do the same for dependency because of freed arrays\n        set<Vertex> connecting_vertices_freed;\n        if (not block.isInstr()) {\n            for (const bh_base *base: block.getLoop().getAllFrees()) {\n                set<Vertex> &vs = base2vertices[base];\n                connecting_vertices_freed.insert(vs.begin(), vs.end());\n                vs.insert(vertex);\n            }\n        }\n        BOOST_REVERSE_FOREACH (Vertex v, connecting_vertices_freed) {\n            if (vertex != v) {\n                boost::add_edge(v, vertex, graph);\n            }\n        }\n    }\n    return graph;\n}\n\nvector<Block> fill_block_list(const DAG &dag) {\n    vector<Block> ret;\n    vector<Vertex> topological_order;\n    boost::topological_sort(dag, back_inserter(topological_order));\n    BOOST_REVERSE_FOREACH(const Vertex &v, topological_order) {\n        ret.push_back(dag[v]);\n    }\n    return ret;\n}\n\nuint64_t weight(const Block &b1, const Block &b2) {\n    if (b1.isInstr() or b2.isInstr()) {\n        return 0; // Instruction blocks cannot be fused\n    }\n    const set<bh_base *> news = b1.getLoop().getAllNews();\n    const set<bh_base *> frees = b2.getLoop().getAllFrees();\n    vector<bh_base *> new_temps;\n    set_intersection(news.begin(), news.end(), frees.begin(), frees.end(), back_inserter(new_temps));\n\n    uint64_t totalsize = 0;\n    for (const bh_base *base: new_temps) {\n        totalsize += base->nbytes();\n    }\n    return totalsize;\n}\n\nuint64_t block_cost(const Block &block) {\n    std::vector<bh_base*> non_temps;\n    const set<bh_base *> temps = block.isInstr()?set<bh_base *>():block.getLoop().getAllTemps();\n    for (const InstrPtr &instr: bohrium::jitk::iterator::allInstr(block)) {\n        // Find non-temporary arrays\n        for(const bh_view &v: instr->getViews()) {\n            if (temps.find(v.base) == temps.end()) {\n                if (std::find(non_temps.begin(), non_temps.end(), v.base) == non_temps.end()) {\n                    non_temps.push_back(v.base);\n                }\n            }\n        }\n    }\n    uint64_t totalsize = 0;\n    for (const bh_base *base: non_temps) {\n        totalsize += base->nbytes();\n    }\n    return totalsize;\n}\n\nbool validate(DAG &dag) {\n    return true;\n}\n\nvoid merge_vertices(DAG &dag, Vertex a, Vertex b, const bool remove_b) {\n    // Let's merge the two blocks and save it in vertex 'a'\n    assert(not dag[a].isInstr());\n    assert(not dag[b].isInstr());\n    dag[a] = reshape_and_merge(dag[a].getLoop(), dag[b].getLoop());\n    assert(dag[a].validation());\n\n    // Add new children\n    BOOST_FOREACH(Vertex child, boost::adjacent_vertices(b, dag)) {\n        assert(child != a);\n        boost::add_edge(a, child, dag);\n    }\n    // Add new parents\n    BOOST_FOREACH(Vertex parent, boost::inv_adjacent_vertices(b, dag)) {\n        if (parent != a) {\n            boost::add_edge(parent, a, dag);\n        }\n    }\n    // Finally, cleanup of 'b'\n    boost::clear_vertex(b, dag);\n    if (remove_b) {\n        boost::remove_vertex(b, dag);\n    }\n    assert(validate(dag));\n}\n\nvoid transitive_reduction(DAG &dag) {\n    vector<Edge> removals;\n    BOOST_FOREACH(Edge e, boost::edges(dag)) {\n        if(path_exist(source(e,dag), target(e,dag), dag, true))\n            removals.push_back(e);\n    }\n    for (Edge &e: removals) {\n        remove_edge(e, dag);\n    }\n    assert(validate(dag));\n}\n\nvoid merge_system_pendants(DAG &dag) {\n    // Find edges to merge over\n    vector<Edge> merges;\n    BOOST_FOREACH(Edge e, boost::edges(dag)) {\n        Vertex src = boost::source(e, dag);\n        Vertex dst = boost::target(e, dag);\n        if (boost::in_degree(dst, dag) == 1 and boost::out_degree(dst, dag) == 0) { // Leaf\n            if (dag[dst].isSystemOnly()) {\n                merges.push_back(e);\n            }\n        } else if (boost::in_degree(src, dag) == 0 and boost::out_degree(src, dag) == 1) { //Root\n            if (dag[src].isSystemOnly()) {\n                merges.push_back(e);\n            }\n        }\n    }\n    // Do merge\n    for (Edge &e: merges) {\n        Vertex src = boost::source(e, dag);\n        Vertex dst = boost::target(e, dag);\n        merge_vertices(dag, src, dst, false);\n    }\n    // Remove the vertex leftover from the merge\n    // NB: because of Vertex invalidation, we have to traverse in reverse\n    BOOST_REVERSE_FOREACH(Edge &e, merges) {\n        boost::remove_vertex(boost::target(e, dag), dag);\n    }\n    assert(validate(dag));\n}\n\nvoid pprint(const DAG &dag, const char *filename, bool avoid_rank0_sweep, int id) {\n\n    //We define a graph and a kernel writer for graphviz\n    struct graph_writer {\n        const DAG &graph;\n        graph_writer(const DAG &g) : graph(g) {};\n        void operator()(std::ostream& out) const {\n            uint64_t totalcost = 0;\n            BOOST_FOREACH(Vertex v, boost::vertices(graph)) {\n                totalcost += block_cost(graph[v]);\n            }\n            out << \"labelloc=\\\"t\\\";\" << endl;\n            out << \"label=\\\"Total cost: \" << (double) totalcost;\n\n            // Find \"work below par-threshold\"\n            uint64_t threading_below_threshold=0, totalwork=0;\n            BOOST_FOREACH(Vertex v, boost::vertices(graph)) {\n                uint64_t total_threading = 0;\n                if (not graph[v].isInstr()) {\n                    total_threading = parallel_ranks(graph[v].getLoop()).second;\n                }\n                for (const InstrPtr &instr: bohrium::jitk::iterator::allInstr(graph[v])) {\n                    if (bh_opcode_is_system(instr->opcode))\n                        continue;\n                    if (total_threading < 1000) {\n                        threading_below_threshold += instr->operand[0].shape.prod();\n                    }\n                    totalwork += instr->operand[0].shape.prod();\n                }\n            }\n            out << \", Work below par-threshold(1000): \" << threading_below_threshold / (double)totalwork * 100 << \"%\";\n            out << \"\\\";\";\n            out << \"graph [bgcolor=white, fontname=\\\"Courier New\\\"]\" << endl;\n            out << \"node [shape=box color=black, fontname=\\\"Courier New\\\"]\" << endl;\n        }\n    };\n    struct kernel_writer {\n        const DAG &graph;\n        kernel_writer(const DAG &g) : graph(g) {};\n        void operator()(std::ostream& out, const Vertex& v) const {\n            out << \"[label=\\\"Kernel \" << v;\n            out << \", Cost: \" << (double) block_cost(graph[v]);\n            out << \"], Instructions: \\\\l\" << graph[v].pprint(\"\\\\l\");\n            out << \"\\\"]\";\n        }\n    };\n    struct edge_writer {\n        const DAG &graph;\n        const bool avoid_sweep;\n        edge_writer(const DAG &g, bool avoid_sweep) : graph(g), avoid_sweep(avoid_sweep) {};\n        void operator()(std::ostream& out, const Edge& e) const {\n            Vertex src = source(e, graph);\n            Vertex dst = target(e, graph);\n            out << \"[label=\\\" \";\n            out << (double) weight(graph[src], graph[dst]) << \" bytes\\\"\";\n            if (not mergeable(graph[src], graph[dst], avoid_sweep)) {\n                out << \" color=red\";\n            }\n            out << \"]\";\n        }\n    };\n\n    static int dag_count=0;\n    if (id == -1) {\n        id = dag_count;\n    }\n    stringstream ss;\n    ss << filename << \"-\" << id++ << \".dot\";\n    ofstream file;\n    cout << ss.str() << endl;\n    file.open(ss.str());\n    boost::write_graphviz(file, dag, kernel_writer(dag), edge_writer(dag, avoid_rank0_sweep), graph_writer(dag));\n    file.close();\n}\n\nvoid greedy(DAG &dag, bool avoid_rank0_sweep) {\n    while(1) {\n        // First we find all fusible edges\n        vector<Edge> fusibles;\n        {\n            auto edges = boost::edges(dag);\n            for (auto it = edges.first; it != edges.second;) {\n                Edge e = *it; ++it; // NB: we iterate here because boost::remove_edge() invalidates 'it'\n                Vertex v1 = source(e, dag);\n                Vertex v2 = target(e, dag);\n                // Remove transitive edges\n                if(path_exist(v1, v2, dag, true)) {\n                    boost::remove_edge(e, dag);\n                } else {\n                    const Block &b1 = dag[v1];\n                    const Block &b2 = dag[v2];\n                    if (mergeable(b1, b2, avoid_rank0_sweep)) {\n                        fusibles.push_back(e);\n                    }\n                }\n            }\n        }\n        // Any more vertices to fuse?\n        if (fusibles.size() == 0) {\n            break;\n        }\n\n        // Let's find the greatest weight edge.\n        Edge greatest = fusibles.front();\n        uint64_t greatest_weight = weight(dag[source(greatest, dag)], dag[target(greatest, dag)]);\n        for (Edge e: fusibles) {\n            const uint64_t w = weight(dag[source(e, dag)], dag[target(e, dag)]);\n            if (w > greatest_weight) {\n                greatest = e;\n                greatest_weight = w;\n            }\n        }\n        Vertex v1 = source(greatest, dag);\n        Vertex v2 = target(greatest, dag);\n//        cout << \"merge: \" << v1 << \", \" << v2 << endl;\n\n        assert(not path_exist(v1, v2, dag, true)); // Transitive edges should have been removed by now\n\n        merge_vertices(dag, v1, v2, true);\n    }\n    assert(validate(dag));\n}\n\n} // graph\n} // jitk\n} // bohrium\n", "meta": {"hexsha": "ff88bd7ad8748808c7f80b474702455c87743f2f", "size": 12615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/jitk/graph.cpp", "max_stars_repo_name": "bh107/bohrium", "max_stars_repo_head_hexsha": "5b83e7117285fefc7779ed0e9acb0f8e74c7e068", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 236.0, "max_stars_repo_stars_event_min_datetime": "2015-03-31T15:39:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T01:43:14.000Z", "max_issues_repo_path": "core/jitk/graph.cpp", "max_issues_repo_name": "bh107/bohrium", "max_issues_repo_head_hexsha": "5b83e7117285fefc7779ed0e9acb0f8e74c7e068", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 324.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T10:35:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T07:34:10.000Z", "max_forks_repo_path": "core/jitk/graph.cpp", "max_forks_repo_name": "bh107/bohrium", "max_forks_repo_head_hexsha": "5b83e7117285fefc7779ed0e9acb0f8e74c7e068", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-05-26T12:38:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T15:16:37.000Z", "avg_line_length": 34.0945945946, "max_line_length": 118, "alphanum_fraction": 0.5680539041, "num_tokens": 3061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.03021458564835026, "lm_q1q2_score": 0.009693482671580234}}
{"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/// @file\n/// General MC for 2d materials beyond RTA\n/// The function definitions are also located in this file\n\n#include <iostream>\n#include <fstream>\n#include <structures.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/mpi.hpp>\n#include <Eigen/Dense>\n#include <collision_operator.hpp>\n#include <sstream>\n#include <sampling.hpp>\n#include <constants.hpp>\n#include <deviational_particle.hpp>\n#include <sampling.hpp>\n#include <exceptions.hpp>\n#include <functional>\n#include <unordered_map>\n#include <map>\n\n#include <boost/functional/hash.hpp>\n#include <boost/format.hpp>\n#include <geometry_2d.hpp>\n#include <bulk_properties.hpp>\n\n#include <io_utils.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n\n#define TBB_PREVIEW_GLOBAL_CONTROL true\n#include <tbb/concurrent_vector.h>\n#include <tbb/parallel_for.h>\n#include <tbb/global_control.h>\n#include <tbb/parallel_sort.h>\n#include <tbb/enumerable_thread_specific.h>\n#include <mutex>\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\ndouble gamma_pdf(double k, double theta, double x) {\n    return boost::math::gamma_p_derivative(k, x / theta) / theta;\n}\n\n\n/// Key for DMM identification:\n\nusing DMM_key = std::tuple<std::string, std::string, Eigen::Vector3d>;\n\n\n/// Some Specialization of std needed for DMM_key\nnamespace std {\n/// Trivial implementation of std::hash for DMM_key\ntemplate <> struct hash<DMM_key> {\n    std::size_t operator()(const DMM_key& key) const {\n        hash<std::string> backend_str;\n        hash<double> backend_double;\n\n        std::size_t nruter = 0;\n\n        boost::hash_combine(nruter, backend_str(std::get<0>(key)));\n        boost::hash_combine(nruter, backend_str(std::get<1>(key)));\n\n        auto vec3d = std::get<2>(key);\n        boost::hash_combine(nruter, backend_double(vec3d(0)));\n        boost::hash_combine(nruter, backend_double(vec3d(1)));\n        boost::hash_combine(nruter, backend_double(vec3d(2)));\n\n        return nruter;\n    }\n};\n/// Implementation of std::equal_to for DMM\ntemplate <> struct equal_to<DMM_key> {\n    bool operator()(const DMM_key& A, const DMM_key& B) const {\n        bool mat_1 = (std::get<0>(A) == std::get<0>(B));\n        bool mat_2 = (std::get<1>(A) == std::get<1>(B));\n        /// Vectors compariso\n        auto va = std::get<2>(A);\n        auto vb = std::get<2>(B);\n        bool veq = alma::almost_equal((va - vb).norm(), 0.);\n\n        return (mat_1 and mat_2 and veq);\n    }\n};\n}; // namespace std\n\n/// Some alias\nusing gridData =\n    std::unordered_map<std::string, std::unique_ptr<alma::Gamma_grid>>;\nusing cellData =\n    std::unordered_map<std::string, std::unique_ptr<alma::Crystal_structure>>;\n\nusing DMM = std::unordered_map<DMM_key, alma::Diffuse_mismatch_distribution>;\n\n\n/// Specialization of STD\nnamespace std {\n/// Trivial implementation of std::hash for arrays,\n/// required to create an unordered_set of arrays.\ntemplate <typename T> struct hash<std::array<T, 2>> {\n    std::size_t operator()(const array<T, 2>& key) const {\n        hash<T> backend;\n        std::size_t nruter = 0;\n\n        for (auto& e : key)\n            boost::hash_combine(nruter, backend(e));\n        return nruter;\n    }\n};\n\n} // namespace std\n\n/// Helper function that determines in which bin of a grid a particle is\n/// situated. The result is clipped to [0, grid.size() - 2], even if the\n/// particle happens to be out of the grid.\n///\n/// @param[in] grid - sorted grid of values defining the bins\n/// @param[in] target - value (time or position) from the trajectory\n/// @return the index of the bin where the particle is\ninline Eigen::Index get_bin_index(const Eigen::Ref<const Eigen::VectorXd>& grid,\n                                  double target) {\n    auto first = grid.data();\n    auto last = grid.data() + grid.size();\n    auto nruter = static_cast<decltype(grid.size())>(\n                      std::lower_bound(first, last, target) - first) -\n                  1;\n    return std::clamp(nruter, static_cast<Eigen::Index>(0), grid.size() - 2);\n}\n\nstruct spectral_decomposition {\n    /// Size of spectral decomposition\n    std::size_t nomega = 0;\n    std::unordered_map<std::size_t, Eigen::ArrayXXd> gz_omega;\n    std::unordered_map<std::size_t, Eigen::ArrayXXd> gzjx_omega;\n    std::unordered_map<std::size_t, Eigen::ArrayXXd> gzjy_omega;\n    std::unordered_map<std::size_t, Eigen::ArrayXXd> fd_qmesh;\n    /// Spectral grid per material\n    std::unordered_map<std::size_t, Eigen::ArrayXd> omegagrid;\n    /// Broadening widths (with outliers removed) for all materials in the grid.\n    std::unordered_map<std::size_t, Eigen::ArrayXXd> broadening_sigmas;\n    /// Information about qpoints in 1st BZ\n    std::unordered_map<std::size_t, Eigen::ArrayXXd> qpoints1stBZ;\n\n\n    void clean() {\n        for (auto& [loc, g] : this->gz_omega)\n            g.setZero();\n        for (auto& [loc, g] : this->gzjx_omega)\n            g.setZero();\n        for (auto& [loc, g] : this->gzjy_omega)\n            g.setZero();\n        for (auto& [loc, g] : this->fd_qmesh)\n            g.setZero();\n    }\n};\n\n\n/// Parameters of input file\nstruct input_parameters {\n    /// Geometry\n    std::vector<alma::geometry_2d> system;\n\n    /// Time\n    double dt, maxtime;\n    /// Material data\n    cellData system_cell;\n    gridData system_grid;\n    // VARIABLES USED WHILE RUNNING SIMULATION\n    // Volumetric heat capacity for each material\n    std::map<std::string, double> material_cv;\n    // RTA scattering rates for all modes of all materials\n    std::map<std::string, Eigen::ArrayXXd> material_w0;\n    /// Sampler for new phonons generation\n    std::map<std::string, alma::BE_derivative_distribution> material_sampler;\n    /// Reference temperature\n    double T0 = -1;\n    /// Temperature gradient applied to system [K/nm]\n    Eigen::Vector3d gradient = Eigen::Vector3d::Zero();\n\n\n    /// Number of deviational energy particles\n    std::size_t Nparticles;\n    /// Vector of thickness\n    std::vector<double> thicknesses;\n\n    /// Stacking stuff\n    alma::layer_coupling couplings;\n\n    /// This is for gradient simulations\n    double eps_energy = -42.0;\n    double eps_flux = -42.0;\n\n    /// Spectral decomposition\n    spectral_decomposition sd;\n\n    /// Only ballistic\n    bool ballistic = false;\n};\n\n/// Compute the deviational power per unit area at an isothermal\n/// surface.\n///\n/// @param[in] poscar - a description of the unit cell\n/// @param[in] grid - phonon spectrum on a regular grid\n/// @param[in] Twall - the temperature of the wall in K\n/// @param[in] Tref - the simulation temperature in K\n/// @param[in] normal - a normal vector pointing out\n/// of the wall [inside material]\n/// @return  the deviational power per unit area in units of\n/// J / ps / nm ** 2\ninline double calc_dotEeff_wall(\n    const alma::Crystal_structure& poscar,\n    const alma::Gamma_grid& grid,\n    double Twall,\n    double Tref,\n    const Eigen::Ref<const Eigen::Vector3d>& normal) {\n    if (normal.norm() == 0.) {\n        throw alma::value_error(\"invalid normal vector\");\n    }\n    Eigen::Vector3d u(normal.array() / normal.norm());\n    double nruter = 0.;\n    double nqpoints = grid.nqpoints;\n    double nmodes = grid.get_spectrum_at_q(0).omega.size();\n\n    for (std::size_t iq = 0; iq < nqpoints; ++iq) {\n        auto& spectrum = grid.get_spectrum_at_q(iq);\n\n        for (std::size_t im = 0; im < nmodes; ++im) {\n            double vn = u.dot(spectrum.vg.col(im).matrix());\n\n            if (vn >= 0.) {\n                nruter +=\n                    alma::bose_einstein_kernel(spectrum.omega(im), Tref) * vn;\n            }\n        }\n    }\n    nruter *= std::abs((Twall - Tref) / nqpoints);\n    return alma::constants::kB * nruter;\n}\n\n\nnamespace generators {\n\n/// It contains all generators\n///@param[in] sys   - system boxes\n///@param[in] grids - grid data for all materials\n///@param[in] cells - cell data for all materials\n///@param[in] rng   - random number generator\n///@param[in] thickness - thickness of all boxes\n///@param[in,out] einfo - contains absolute flux and energy introduced to system\n///per ps\nalma::D_particle Init_generator(std::vector<alma::geometry_2d>& sys,\n                                gridData& grids,\n                                cellData& cells,\n                                pcg64& rng,\n                                std::vector<double>& thickness,\n                                Eigen::Vector3d& gradient,\n                                Eigen::Vector2d& einfo) {\n    /// Generators\n    static std::unordered_map<\n        std::array<std::size_t, 2>,\n        std::pair<alma::Isothermal_wall_distribution, alma::geom2d_border>>\n        isogens;\n    static std::unordered_map<std::size_t, alma::Nabla_T_distribution>\n        grad_generators;\n\n    static std::map<double, std::array<std::size_t, 2>> weight_gen;\n    static std::map<double, std::size_t> wgrad_gen, winit_gen;\n\n    static alma::particle_sign gsign = alma::get_particle_sign(-1);\n\n    /// Energy per generator\n    static std::array<double, 2> ExGen = {0., 0.};\n\n    einfo.setZero();\n\n\n    if (isogens.size() == 0 and grad_generators.size() == 0) {\n        /// Iterate through system to build up isothermal generators\n        for (auto& s : sys) {\n            /// If not reservoir ignore\n            if (!s.reservoir)\n                continue;\n            /// Retrive material and box id\n            auto smat = s.material;\n            auto sid = s.get_id();\n\n            /// Iterate through contacts:\n            /// This is done each timestep\n            /// only in case we need to recalculate\n            /// the generator\n            for (auto& [c, b] : s.get_contacts()) {\n                if (sys[c].reservoir or sys[c].periodic)\n                    continue;\n\n                if (alma::almost_equal(b[0].get_length(), 0.))\n                    continue;\n\n                if (sys[c].material != smat) {\n                    throw alma::input_error(\"Injection from material A to B \"\n                                            \"is not allowed\\n\");\n                }\n\n                /// Ignore if Temperatures are equal\n                if (alma::almost_equal(s.Teq, sys[c].Teq))\n                    continue;\n                std::array<std::size_t, 2> ids = {sid, c};\n                Eigen::Vector3d nw;\n                nw << b[0].np(0), b[0].np(1), 0;\n\n                alma::Isothermal_wall_distribution igen(\n                    *(grids.at(smat)), s.Teq, sys[c].Teq, nw, rng);\n\n                // double ed   = calc_dotEeff_wall(\n                //            *(cells.at(smat)),\n                //            *(grids.at(smat)),\n                //            s.Teq,\n                //            sys[c].Teq,\n                //            nw);\n                double vuc = cells.at(s.material)->V * thickness[s.get_id()] /\n                             cells.at(s.material)->lattvec(2, 2);\n\n                double ed = igen.get_flux(vuc);\n\n                einfo(0) += ed / vuc;\n\n                isogens[ids] = std::make_pair(igen, b[0]);\n            } // contacts loop\n        }\n\n        // Iterate through system to build up initial condition generators\n        for (auto& s : sys) {\n            /// If reservoir or periodic ignore\n            if (s.reservoir or s.periodic)\n                continue;\n\n            /// If no gradient applied to system\n            if (alma::almost_equal(gradient.norm(), 0.))\n                continue;\n\n            auto mat = s.material;\n\n\n            alma::Nabla_T_distribution myGradGen(\n                *(grids[mat]), gradient, s.Teq, rng);\n\n            grad_generators[s.get_id()] = myGradGen;\n        }\n\n    /// We now iterate through isothermal generators to get the weights\n    /// to know which source the particle will be generated from\n    {\n        std::vector<double> ws, weight_vec;\n        for (auto& [ids, G] : isogens) {\n            auto idr = ids[0];\n            auto mat = sys[idr].material;\n            auto b = G.second;\n            auto Lb = b.get_length();\n            double vuc = cells.at(mat)->V * thickness[idr] /\n                         cells.at(mat)->lattvec(2, 2);\n\n            Eigen::Vector3d nw;\n            nw << b.np(0), b.np(1), 0;\n            double jd = G.first.get_flux(vuc);\n\n            double e_inserted = std::abs(jd) * Lb * thickness[idr];\n            /// This gives the energy inserted per ps in system (not care about\n            /// sign) per unit\n            einfo(1) += e_inserted;\n            ExGen[0] += e_inserted;\n\n            ws.push_back(e_inserted);\n        }\n\n        double wnorm = std::accumulate(ws.begin(), ws.end(), 0.);\n        double cum = 0.;\n        for (auto w : ws) {\n            cum += w / wnorm;\n            weight_vec.push_back(cum);\n        }\n\n        std::size_t ii = 0;\n        for (auto& [ids, G] : isogens) {\n            weight_gen[weight_vec[ii]] = ids;\n            ii++;\n        }\n    }\n\n    {\n        std::vector<double> ws, weight_vec;\n        for (auto& [id, G] : grad_generators) {\n            auto& s = sys[id];\n\n            auto Vucell = cells.at(s.material)->V * thickness[s.get_id()] /\n                          cells.at(s.material)->lattvec(2, 2);\n\n            auto Vbox = s.get_area() * thickness[s.get_id()];\n\n            auto eintro = G.get_energy(Vbox / Vucell);\n\n            ExGen[1] += eintro;\n\n            ws.push_back(eintro);\n        }\n\n        double wnorm = std::accumulate(ws.begin(), ws.end(), 0.);\n        double cum = 0.;\n        for (auto w : ws) {\n            cum += w / wnorm;\n            weight_vec.push_back(cum);\n        }\n\n        std::size_t ii = 0;\n        for (auto& [id, G] : grad_generators) {\n            wgrad_gen[weight_vec[ii]] = id;\n            ii++;\n        }\n    }\n\n        /// Building array to generate\n        double total_exgen = std::accumulate(ExGen.begin(), ExGen.end(), 0.);\n\n        einfo(1) = total_exgen;\n\n        ExGen[0] = ExGen[0] / total_exgen;\n        ExGen[1] = ExGen[1] / total_exgen + ExGen[0];\n        std::cout << \"#Distribution by generators => \" << ExGen[0] << '\\t'\n                  << ExGen[1] << std::endl;\n    }\n\n    double selectGenR = std::uniform_real_distribution(0., 1.)(rng);\n\n    auto genID =\n        std::distance(ExGen.begin(),\n                      std::lower_bound(ExGen.begin(), ExGen.end(), selectGenR));\n\n    switch (genID) {\n        case 0: {\n            /// Selecting the generator\n            double whereGenR = std::uniform_real_distribution(0., 1.)(rng);\n            std::array<std::size_t, 2> ids =\n                weight_gen.lower_bound(whereGenR)->second;\n            auto& G = isogens[ids];\n            auto idr = ids[0];\n            auto idi = ids[1];\n            auto mat = sys[idr].material;\n            auto b = G.second;\n            auto& gen = G.first;\n\n            Eigen::Vector2d ppos = b.get_random_point(rng);\n\n            // Sanity check\n            // if that fails is due to\n            // numerical errors:\n            if (!sys[idi].inside(ppos)) {\n                decltype(ppos) pos0 = ppos;\n                decltype(ppos) d = sys[idi].get_center() - ppos;\n                ppos += 1.0e-6 * d / d.norm();\n                if (!sys[idi].inside(ppos)) {\n                    std::cout << \"Error report\" << std::endl;\n                    std::cout << \"reservoir id: \" << idr << std::endl;\n                    std::cout << \"orig pos:\\n\" << pos0 << std::endl;\n                    std::cout << \"correction\\n\" << d << std::endl;\n                    std::cout << \"corpos:\\n\" << ppos << std::endl;\n                    std::cout << \"id inj box: \" << idi << std::endl;\n                    std::cout << \"center inj box\\n\"\n                              << sys[idi].get_center() << std::endl;\n                    throw alma::geometry_error(\"Generated particle \"\n                                               \"out of insertion box\\n\");\n                }\n            }\n\n            auto pinfo = gen.sample_with_sign();\n            alma::D_particle newp(ppos,\n                                  std::get<1>(pinfo),\n                                  std::get<0>(pinfo),\n                                  std::get<2>(pinfo),\n                                  0.,\n                                  idi);\n\n            return newp;\n        }\n        case 1: {\n            double whereGenR = std::uniform_real_distribution(0., 1.)(rng);\n            auto id = wgrad_gen.lower_bound(whereGenR)->second;\n            auto& G = grad_generators[id];\n\n            Eigen::Vector2d ppos = sys[id].get_random_point(rng);\n\n            auto pinfo = G.sample_with_sign();\n            while (std::get<2>(pinfo) != gsign) {\n                pinfo = G.sample_with_sign();\n            }\n            gsign = alma::get_particle_sign(\n                -1 * static_cast<int>(std::get<2>(pinfo)));\n            alma::D_particle newp(ppos,\n                                  std::get<1>(pinfo),\n                                  std::get<0>(pinfo),\n                                  std::get<2>(pinfo),\n                                  0.,\n                                  id);\n\n            return newp;\n        }\n\n        default: {\n            throw alma::value_error(\"Error selecting generator\");\n        }\n    }\n\n    throw alma::value_error(\"Error selecting generator\");\n    return alma::D_particle();\n}\n\n\n/// This class is to make the diffusive\n/// scattering which is approximated by the Lambert\n/// cosine law with the energy conservation as\n/// constraint.\n/// The probability of going for i to f is the defined as:\n///$P_{i \\rightarrow f} = \\frac{v_f \\cdot\n///\\hat{e}_{\\perp}\\delta(\\omega_f-\\omega_i)}{\\sum_j v_j \\cdot\n///\\hat{e}_{\\perp}\\delta(\\omega_j-\\omega_i)}$ This energy \"conservation\" is\n/// treated in the same way that for three phonon processes, see section 2.4 of\n/// https://doi.org/10.1016/j.cpc.2014.02.015 for reference. Code is partially\n/// adapted from isotopic scattering algorithms.\nclass diffusive_bouncing {\npublic:\n    /// Table with energy conservation from state to state\n    // for each material\n    std::map<std::string, std::vector<std::unordered_map<std::size_t, double>>>\n        lambert;\n\n    /// It creates a table in the full BZ for diffusive bouncing\n    //@param[in] gridData - map containing qgrid data for each material\n    diffusive_bouncing(gridData& d) {\n        for (auto& [m, info] : d) {\n            auto nq = info->nqpoints;\n            auto nb = static_cast<std::size_t>(\n                info->get_spectrum_at_q(0).omega.size());\n            // Precompute the broadening of all modes.\n            Eigen::ArrayXXd sigmas(nb, nq);\n\n            lambert[m] =\n                std::vector<std::unordered_map<std::size_t, double>>(nq * nb);\n\n            for (std::size_t iq = 0; iq < nq; ++iq)\n                for (std::size_t im = 0; im < nb; ++im) {\n                    auto spectrum = info->get_spectrum_at_q(iq);\n                    sigmas(im, iq) = info->base_sigma(spectrum.vg.col(im));\n                }\n            // And refine them by removing outliers.\n            auto percent = alma::calc_percentiles_log(sigmas);\n            double lbound =\n                std::exp(percent[0] - 1.5 * (percent[1] - percent[0]));\n            sigmas = (sigmas < lbound).select(lbound, sigmas);\n\n            for (std::size_t ic = 0; ic < info->get_nequivalences(); ++ic) {\n                /// Gamma phonons cannot couple\n                if (ic == 0)\n                    continue;\n                auto iq1 = info->get_representative(ic);\n                auto spectrum1 = info->get_spectrum_at_q(iq1);\n                /// Gamma phonons cannot couple (we start from 1)\n                for (std::size_t iq2 = 1; iq2 < info->nqpoints; ++iq2) {\n                    auto spectrum2 = info->get_spectrum_at_q(iq2);\n\n                    for (decltype(nb) im1 = 0; im1 < nb; ++im1) {\n                        for (decltype(nb) im2 = 0; im2 < nb; ++im2) {\n                            if (alma::almost_equal(0., spectrum1.omega(im1)) or\n                                alma::almost_equal(0., spectrum2.omega(im2)))\n                                continue;\n                            // Note that, since momentum is not conserved,\n                            // the frequencies are uncorrelated random\n                            // variables. The total standard deviation is\n                            // the quadratic sum of both standard\n                            // deviations.\n                            auto sigma =\n                                std::hypot(sigmas(im1, iq1), sigmas(im2, iq2));\n                            // sigma      = 0.1;\n                            // The only criterion for accepting a process as\n                            // allowed is conservation of energy after\n                            // taking into account the discretization of\n                            // reciprocal space with the usual adaptive\n                            // broadening method.\n                            auto delta = std::fabs(spectrum1.omega(im1) -\n                                                   spectrum2.omega(im2));\n\n                            if (delta <= alma::constants::nsigma * sigma) {\n                                auto distr = boost::math::normal(0., sigma);\n                                /// Recovering full BZ using symmetry operations\n                                for (auto qp :\n                                     info->equivalent_qpairs({iq1, iq2})) {\n                                    auto mode1 = nb * qp[0] + im1;\n                                    auto mode2 = nb * qp[1] + im2;\n                                    this->lambert[m][mode1][mode2] =\n                                        boost::math::pdf(distr, delta);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        // Ended for\n    }\n\n    /// It returns the new state after diffusive bouncing\n    ///@param[in] npout - the vector of the wall pointing outside\n    ///@param[in] mat   - material name\n    ///@param[in] imode - phonon mode id\n    ///@param[in] grid  - map with qgrid data for all materials\n    ///@param[in] rng   - random number generator\n    ///@returns   pair containing mode band and qpoint id\n    std::pair<std::size_t, std::size_t> bounce(Eigen::Vector3d npout,\n                                               std::string mat,\n                                               std::size_t imode,\n                                               gridData& grid,\n                                               pcg64& rng) {\n        auto& tm = this->lambert[mat][imode];\n        auto nb = grid[mat]->get_spectrum_at_q(0).omega.size();\n        /// Iterate over the energy conserving states\n        /// and building histogram for random\n        /// selection of final state\n        std::map<std::size_t, double> states;\n        std::map<double, std::size_t> states2;\n        double cum = 0.;\n        // for (int imf = 3; imf < grid[mat]->nqpoints*nb; imf++){\n        for (auto& [imf, econ] : tm) {\n            auto ib = imf % nb;\n            auto iq = imf / nb;\n            Eigen::Vector3d v = grid[mat]->get_spectrum_at_q(iq).vg.col(ib);\n\n            for (const auto axis : {0, 1, 2}) {\n                if (alma::almost_equal(v(axis), 0.))\n                    v(axis) = 0.;\n            }\n\n            double vn = -(npout.dot(v));\n            if (vn < 0. or alma::almost_equal(vn, 0.))\n                continue;\n            cum += vn * econ;\n            states[imf] = vn * econ;\n        }\n\n        double cum2 = 0;\n\n        for (auto& [imf, tran] : states) {\n            cum2 += tran / cum;\n            states2[cum2] = imf;\n        }\n\n        double s = std::uniform_real_distribution(0., 1.)(rng);\n\n        std::size_t IMF = states2.lower_bound(s)->second;\n\n        return std::make_pair(IMF % nb, IMF / nb);\n    }\n};\n\n\n}; // namespace generators\n\n/// Helper function for processing trajectories\n///@param[in] ibox - r bin id\n///@param[in] tstart - initial time of the trajectory\n///@param[in] tstop  - end time for the trajectory\n///@param[in] sign   - particle sign\n///@param[in] timegrid - grid of times for register\n///@param[in] vg       - particle velocity\n///@param[in,out] gz - matrix where to save the contribution of trajectory\n//                     to bins\n///@param[in,out] gz_jx - matrix where to save the contribution to jx\n///@param[in,out] gz_jy - matrix where to save the contribution to jy\n///@param[in] omega - particle frequency\n///@param[in] ib - particle branch\n///@param[in] iq - particle qpoint id\n///@param[in,out] sd - class containing data of spectral decompositions\nvoid process_segment(std::size_t ibox,\n                     double tstart,\n                     double tstop,\n                     alma::particle_sign& sign,\n                     Eigen::VectorXd& timegrid,\n                     Eigen::Vector2d& vg,\n                     Eigen::ArrayXXd& gz,\n                     Eigen::ArrayXXd& gz_jx,\n                     Eigen::ArrayXXd& gz_jy,\n                     double omega,\n                     std::size_t iq,\n                     std::size_t ib,\n                     spectral_decomposition& sd) {\n    // Compute bounds for the subgrid in (t, r) space covered by the\n    // segment.\n    auto startbin_t = get_bin_index(timegrid, tstart);\n    auto stopbin_t = get_bin_index(timegrid, tstop);\n    double delta_t = tstop - tstart;\n\n    bool spectral = !sd.gz_omega.empty() and sd.gz_omega.count(ibox) != 0;\n\n\n    Eigen::ArrayXd gamma_weights(0);\n    /// Spectral decomposition stuff\n    if (spectral) {\n        gamma_weights.resize(sd.omegagrid[ibox].size());\n        double k = omega * omega / sd.broadening_sigmas[ibox](ib, iq);\n        double theta = sd.broadening_sigmas[ibox](ib, iq) / omega;\n\n        for (Eigen::Index i = 0; i < sd.omegagrid[ibox].size(); ++i) {\n            gamma_weights(i) = gamma_pdf(k, theta, sd.omegagrid[ibox](i));\n        }\n    }\n\n\n    // Compute the time spent in each cell of the (t, z) subgrid.\n    Eigen::ArrayXd lo_time{stopbin_t - startbin_t + 1};\n    Eigen::ArrayXd hi_time{stopbin_t - startbin_t + 1};\n    for (auto i = startbin_t; i <= stopbin_t; ++i) {\n        lo_time(i - startbin_t) = timegrid(i) - tstart;\n        hi_time(i - startbin_t) = timegrid(i + 1) - tstart;\n    }\n\n    /// Shared among threads\n    static std::mutex protector;\n\n    // We are only putting contributions from one single space bin\n    // as function is called always when we change from box\n\n    for (auto i_time = startbin_t; i_time <= stopbin_t; ++i_time) {\n        double lo = std::max(lo_time(i_time - startbin_t), 0.);\n        double hi = std::min(hi_time(i_time - startbin_t), delta_t);\n        double contr = static_cast<double>(sign) * std::max(hi - lo, 0.);\n        gz(ibox, i_time) += contr;\n        gz_jx(ibox, i_time) += vg(0) * contr;\n        gz_jy(ibox, i_time) += vg(1) * contr;\n\n        if (spectral) {\n            protector.lock();\n            sd.gz_omega[ibox].row(i_time) += contr * gamma_weights;\n            sd.gzjx_omega[ibox].row(i_time) += vg(0) * contr * gamma_weights;\n            sd.gzjy_omega[ibox].row(i_time) += vg(1) * contr * gamma_weights;\n            /// Storing distribution in q-mesh\n            sd.fd_qmesh[ibox](i_time, iq) += contr / omega;\n            protector.unlock();\n            // std::cout << \"sp->done\" << std::endl;\n        }\n    }\n\n    return;\n}\n\n/// Helper function for processing trajectories\n///@param[in] ibox - r bin id\n///@param[in] tstart - initial time of the trajectory\n///@param[in] tstop  - end time for the trajectory\n///@param[in] sign   - particle sign\n///@param[in] timegrid - grid of times for register\n///@param[in] vg       - particle velocity\n///@param[in,out] gz - matrix where to save the contribution of trajectory\n//                     to bins\n///@param[in,out] gz_jx - matrix where to save the contribution to jx\n///@param[in,out] gz_jy - matrix where to save the contribution to jy\n///@param[in,out] phi   -\n///@param[in]     evalphi - bool to eval phi\nvoid process_segment(std::size_t ibox,\n                     alma::particle_sign& sign,\n                     double dt,\n                     Eigen::Vector2d& vg,\n                     Eigen::ArrayXd& gz,\n                     Eigen::ArrayXd& gz_jx,\n                     Eigen::ArrayXd& gz_jy,\n                     Eigen::ArrayXd& phi,\n                     double omega,\n                     std::size_t iq,\n                     std::size_t ib,\n                     spectral_decomposition& sd,\n                     bool evalphi = false) {\n    // Compute bounds for the subgrid in (t, r) space covered by the\n    // segment.\n    double contr = static_cast<double>(sign);\n    gz(ibox) += contr * dt;\n    gz_jx(ibox) += vg(0) * contr * dt;\n    gz_jy(ibox) += vg(1) * contr * dt;\n\n\n    bool spectral = !sd.gz_omega.empty() and sd.gz_omega.count(ibox) != 0;\n\n    /// Shared among threads\n    static std::mutex protector;\n\n    /// Spectral decomposition stuff\n    if (spectral) {\n        Eigen::ArrayXd gamma_weights{sd.omegagrid[ibox].size()};\n        double k = omega * omega / sd.broadening_sigmas[ibox](ib, iq);\n        double theta = sd.broadening_sigmas[ibox](ib, iq) / omega;\n        for (Eigen::Index i = 0; i < sd.omegagrid[ibox].size(); ++i) {\n            gamma_weights(i) = gamma_pdf(k, theta, sd.omegagrid[ibox](i));\n        }\n\n        protector.lock();\n        sd.gz_omega[ibox].row(0) += gamma_weights * contr * dt;\n        sd.gzjx_omega[ibox].row(0) += vg(0) * gamma_weights * contr * dt;\n        sd.gzjy_omega[ibox].row(0) += vg(1) * gamma_weights * contr * dt;\n\n        sd.fd_qmesh[ibox](0, iq) += contr / omega;\n\n        protector.unlock();\n    }\n\n    if (evalphi) {\n        phi(ibox) += contr;\n    }\n\n    return;\n}\n\n\n/// Get v:\n/// We need to clean v values of small values\n///@param[in] grid - qpoint grid\n///@param[in] ib   - band index\n///@param[in] iq   - qpoint index\n///@return    phonon group velocity\ninline Eigen::Vector2d get_v(const alma::Gamma_grid& grid,\n                             std::size_t ib,\n                             std::size_t iq) {\n    Eigen::Vector3d v3 = grid.get_spectrum_at_q(iq).vg.col(ib);\n    // return (v3.block(0,0,2,1)).eval();\n    Eigen::Vector2d v2;\n    v2 << v3(0), v3(1);\n    for (auto i = 0; i < 2; i++) {\n        if (alma::almost_equal(v2(i), 0.))\n            v2(i) = 0.;\n    }\n\n    return v2;\n}\n\n\n/// Function controling the change of material it allows for DMM and LDMM\n///@param[in]     inew      - possible box id to check transmission to \n///@param[in]     cboxes    - contact boxes\n///@param[in,out] particle  - deviational particle to evolve\n///@param[in]     sys       - geometry and box info\n///@param[in]     dt        - time to evolve\n///@param[in]     rnd       - random generator\n///@param[in]     grids     - qgrid data per material\n///@param[in]     DMM_gen   - DMM generators for interface scattering\n///@param[in]     thickness - correct materials thickness\n///@param[in]     cells     - cells data\n///@param[in]     coupling  - information for LDMM model for interface\ntemplate<class Random,class Mutex>\nvoid change_material_diffuse(std::size_t inew,\n    std::set<std::size_t>& cboxes,\n    alma::D_particle& particle,\n    std::vector<alma::geometry_2d>& sys,\n    double& dt,\n    Random& rnd,\n    Mutex& pmutex,\n    gridData& grids,\n    DMM& DMM_gen,\n    std::vector<double>& thickness,\n    cellData& cells,\n    alma::layer_coupling& couplings) {\n\n    /// Getting index info\n    std::size_t iold = particle.boxid;\n\n    auto matA = sys[iold].material;\n    auto matB = sys[inew].material;\n\n    /// Getting vector info\n    Eigen::Vector3d nw;\n    nw.setZero();\n    // Get incident vector\n    for (auto& [c, b] : sys[iold].get_contacts()) {\n        if (c == inew) {\n            Eigen::Vector3d nw_;\n            nw_ << b[0].np(0), b[0].np(1), 0.;\n            nw += nw_;\n        }\n    }\n\n    DMM_key DMM_ID = {matA, matB, nw};\n\n    /// If the model for that interface does not exist create it\n    if (DMM_gen.count(DMM_ID) == 0) {\n        bool layer_coupling = couplings.stack_injection;\n\n        if (matA == matB) {\n            throw alma::geometry_error(\"DMM in same material\");\n        }\n\n        /// In the case of layered stacks if\n        /// coupling information is provided\n        /// we use LDMM to take into account\n        /// the coupling of vibrations \n        /// between different layers. Otherwise\n        /// we use traditional DMM\n        if (layer_coupling) {\n            DMM_gen[DMM_ID] =\n                alma::Diffuse_mismatch_distribution(*grids[matA],\n                                                    *cells[matA],\n                                                    *grids[matB],\n                                                    *cells[matB],\n                                                    nw,\n                                                    0.1,\n                                                    rnd,\n                                                    sys[iold].Teq,\n                                                    thickness[iold],\n                                                    thickness[inew],\n                                                    couplings,\n                                                    matA,\n                                                    matB);\n        }\n        else {\n            DMM_gen[DMM_ID] =\n                alma::Diffuse_mismatch_distribution(*grids[matA],\n                                                    *cells[matA],\n                                                    *grids[matB],\n                                                    *cells[matB],\n                                                    nw,\n                                                    0.1,\n                                                    rnd,\n                                                    sys[iold].Teq,\n                                                    thickness[iold],\n                                                    thickness[inew]);\n        }\n    }\n\n    /// Setting incidence (we are always incident from A)\n    char incidence = 'A';\n    /// Scatter at interface\n    auto out_incidence = DMM_gen[DMM_ID].reemit(incidence, particle);\n\n    /// If there is transmission accross interface\n    if (incidence != out_incidence) {\n        particle.boxid = inew;\n        if (cboxes.find(particle.boxid) == cboxes.end()) {\n            throw alma::geometry_error(\"Teleport is not allowed\");\n        }\n    }\n    dt = 0.;\n    return;\n}\n\n\n\n\n/// Particle evolution:\n///@param[in,out] particle - deviational particle to evolve\n///@param[in] v        - particle velocity\n///@param[in] sys      - geometry and box info\n///@param[in] dt       - time to evolve\n///@param[in] rnd     - random generator\n///@param[in] pmutex  - mutex\n///@param[in] db      - diffusive boundary scattering table\n///@param[in] grids   - qgrid data per material\n///@param[in] timegrid - time mesh\n///@param[in,out] gz   - matrix to save particles contributions to bins\n///@param[in,out] gz_jx - matrix where to save the contribution to jx\n///@param[in,out] gz_jy - matrix where to save the contribution to jy\n///@param[in]     DMM_gen - DMM generators for interface scattering\n///@param[in]     thickness - correct materials thickness\n///@param[in]     cells     - cells data\n///@param[in]     material_sampler - postscacttering distribution for sampling\n///after scattering\n///@param[in]     sd - information about spectral decompostions\n///@param[in]     coupling - information for LDMM model for interface\n///@param[in]     ballistic - to turn on/off intrinsic scattering\ntemplate <class Random, class Mutex>\nvoid evolparticle(\n    alma::D_particle& particle,\n    Eigen::Vector2d& v,\n    std::vector<alma::geometry_2d>& sys,\n    double& dt,\n    Random& rnd,\n    Mutex& pmutex,\n    generators::diffusive_bouncing& db,\n    gridData& grids,\n    Eigen::VectorXd& timegrid,\n    Eigen::ArrayXXd& gz,\n    Eigen::ArrayXXd& gz_jx,\n    Eigen::ArrayXXd& gz_jy,\n    DMM& DMM_gen,\n    std::vector<double>& thickness,\n    cellData& cells,\n    std::map<std::string, alma::BE_derivative_distribution>& material_sampler,\n    spectral_decomposition& sd,\n    alma::layer_coupling& couplings,\n    bool ballistic) {\n    Eigen::Vector2d opos(particle.pos);\n\n    auto pq = particle.q;\n    auto pb = particle.alpha;\n    double mu =\n        grids[sys[particle.boxid].material]->get_spectrum_at_q(pq).omega(pb);\n\n    // std::cout << \"# \" << particle.t << '\\t' <<\n    // particle.boxid <<'\\t'<< particle.pos.transpose()\n    //<< '\\t' << v.transpose() << '\\t' << dt << std::endl;\n\n    /// Make some v check\n    for (auto iv : {0, 1}) {\n        if (alma::almost_equal(v(iv), 0.) and v(iv) != 0.) {\n            throw alma::geometry_error(\n                \"Error, please set all that\"\n                \" evaluates almost_equal to 0 as 0. Otherwise,\"\n                \" geometric algorithms will fail\\n\"\n                \"Specifically the rnew check as it contains \"\n                \"v in spatial search of boxes to go\\n\");\n        }\n    }\n\n    /// Apply PBC\n    if (sys[particle.boxid].periodic) {\n        pmutex.lock();\n        auto PBCsol = sys[particle.boxid].translate(opos, v, sys, rnd);\n        pmutex.unlock();\n\n        particle.boxid = PBCsol.first;\n        particle.pos = PBCsol.second;\n        return;\n    }\n\n\n    /// Check if in reservoir\n    if (sys[particle.boxid].reservoir) {\n        /// Terminated particle\n        particle.q = 0;\n        particle.alpha = 0;\n        dt = 0.;\n        return;\n    }\n\n    Eigen::Vector2d rnew = particle.pos + dt * v;\n    // particle.pos(0) = 25;\n\n    /// Check if inside the same box:\n\n    if (sys[particle.boxid].inside(rnew)) {\n        if (sys[particle.boxid].periodic) {\n            std::cout << \"Periodic boxes do not exist\\n\";\n            std::cout << \"r0\\n\" << opos << std::endl;\n            std::cout << \"rf\\n\" << rnew << std::endl;\n            std::cout << \"dt \" << dt << std::endl;\n            std::cout << particle.pos << std::endl;\n            std::cout << \"v\\n\" << v << std::endl;\n            throw alma::geometry_error(\"Peridic error\\n\");\n        }\n\n        particle.pos = rnew;\n\n\n        /// Make here the contribution to the segment\n        process_segment(particle.boxid,\n                        particle.t,\n                        particle.t + dt,\n                        particle.sign,\n                        timegrid,\n                        v,\n                        gz,\n                        gz_jx,\n                        gz_jy,\n                        mu,\n                        pq,\n                        pb,\n                        sd);\n        particle.t += dt;\n\n        if (!ballistic) {\n            /// Scattering here (serial because of rng protection):\n            auto mat = sys[particle.boxid].material;\n            pmutex.lock();\n            auto mode = material_sampler.at(mat).sample();\n            pmutex.unlock();\n            particle.q = mode[1];\n            particle.alpha = mode[0];\n        }\n        dt = 0.;\n        return;\n    }\n\n    /// Check the place it left\n    Eigen::Vector2d rp;\n    rp << particle.pos(0), particle.pos(1);\n\n    /// Here we calculate where the particle is\n    /// going out\n    std::tuple<double, Eigen::Vector2d, std::vector<int>> MRU_sol;\n\n    try {\n        MRU_sol = sys[particle.boxid].get_inter_side(rp, v, dt);\n    }\n    catch (const alma::geometry_error& geomerror) {\n        Eigen::Vector2d d = sys[particle.boxid].get_center() - opos;\n        particle.pos += 1.0e-6 * d / d.norm();\n        // evolparticle(particle, v, sys, dt, rnd,\n        // pmutex,db,grids,timegrid,gz,gz_jx,gz_jy,DMM_gen,thickness,cells,material_sampler,sd,couplings);\n        return;\n    }\n\n    if (std::get<0>(MRU_sol) < 0) {\n        throw alma::geometry_error(\"Error in kinematics\\n\");\n        exit(EXIT_FAILURE);\n    }\n    /// Calculating leftime\n    double left_time = dt - std::get<0>(MRU_sol);\n    double tf = std::get<0>(MRU_sol);\n    if (alma::almost_equal(left_time, 0.)) {\n        left_time = 0.;\n    }\n\n    dt = left_time;\n    rnew = std::get<1>(MRU_sol);\n\n    decltype(rnew) reps = rnew + 1.0e-6 * v / v.norm();\n\n    /// Get contact boxes\n    std::set<std::size_t> cboxes;\n    for (auto& [ibc, border] : sys[particle.boxid].get_contacts()) {\n        cboxes.insert(ibc);\n    }\n\n    /// Check possible boxes to assign:\n    std::vector<std::size_t> pboxes;\n\n\n    for (auto test : cboxes) {\n        if (test == particle.boxid) {\n            continue;\n        }\n\n        auto border_contact = sys[particle.boxid].get_contacts()[test];\n        /// If going along border we do not change\n        bool parallel = alma::almost_equal((border_contact[0].np).dot(v), 0.);\n\n        bool oriented = ((border_contact[0].np).dot(v) > 0.);\n\n        if ((sys[test].inside(rnew) or sys[test].inside(reps)) and !parallel and\n            oriented) {\n            pboxes.push_back(test);\n        }\n    }\n\n    /// If going inside the void\n    if (pboxes.size() == 0) {\n\n        /// Make here the contribution to the segment\n        process_segment(particle.boxid,\n                        particle.t,\n                        particle.t + tf,\n                        particle.sign,\n                        timegrid,\n                        v,\n                        gz,\n                        gz_jx,\n                        gz_jy,\n                        mu,\n                        pq,\n                        pb,\n                        sd);\n        particle.t += tf;\n\n\n        /// Correcting three corner problem\n        auto corner_problem = in_corner3(rnew, sys);\n        if (corner_problem.first) {\n            auto csol = correct_corner_problem(\n                rnew, v, sys, corner_problem.second, rnd);\n\n            particle.boxid = csol.first;\n            Eigen::Vector2d correction =\n                sys[particle.boxid].get_center() - rnew;\n            Eigen::Vector2d corrected_pos =\n                rnew + 1.0e-6 * correction / correction.norm();\n\n            MRU_sol =\n                sys[particle.boxid].get_inter_side(corrected_pos, v, 1.0e+18);\n\n            rnew = std::get<1>(MRU_sol);\n        }\n\n        /// Diffusive scattering\n        std::size_t iborder;\n        auto iborders = std::get<2>(MRU_sol);\n        if (iborders.size() > 1) {\n            /// We first check the borders\n            /// that touch void\n            std::vector<std::size_t> voidborders;\n\n            for (auto& tvb : iborders) {\n                auto& mb = sys[particle.boxid].get_border(tvb);\n\n                Eigen::Vector2d rc = rnew + 1.0e-4 * mb.np;\n\n                bool isvoid = true;\n                for (auto& cb : cboxes) {\n                    if (sys[cb].inside(rc)) {\n                        isvoid = false;\n                        break;\n                    }\n                }\n\n                if (isvoid) {\n                    voidborders.push_back(tvb);\n                }\n            }\n\n            if (voidborders.empty()) {\n                throw alma::geometry_error(\"Error in void borders\\n\");\n            }\n\n            // In the case two borders pointing at void\n            iborder = voidborders[std::uniform_int_distribution(\n                0, static_cast<int>(voidborders.size()))(rnd)];\n        }\n        else {\n            iborder = iborders[0];\n        }\n\n        auto u = sys[particle.boxid].get_border(iborder).np;\n\n        Eigen::Vector3d unp3;\n        unp3 << u(0), u(1), 0.;\n\n        std::size_t Nb =\n            static_cast<std::size_t>(grids[sys[particle.boxid].material]\n                                         ->get_spectrum_at_q(0)\n                                         .omega.size());\n        auto newmode = db.bounce(unp3,\n                                 sys[particle.boxid].material,\n                                 particle.q * Nb + particle.alpha,\n                                 grids,\n                                 rnd);\n\n        particle.pos = rnew;\n        particle.q = newmode.second;\n        particle.alpha = newmode.first;\n        dt = 0.;\n        return;\n    }\n    else if (pboxes.size() == 1) {\n        /// Change material\n        if (sys[particle.boxid].material != sys[pboxes[0]].material) {\n            /// Save contribution here\n            process_segment(particle.boxid,\n                            particle.t,\n                            particle.t + tf,\n                            particle.sign,\n                            timegrid,\n                            v,\n                            gz,\n                            gz_jx,\n                            gz_jy,\n                            mu,\n                            pq,\n                            pb,\n                            sd);\n\n            particle.pos = rnew;\n            particle.t += tf;\n            change_material_diffuse(pboxes[0],cboxes,particle,sys,dt,rnd,pmutex,grids,\n                                    DMM_gen,thickness,cells,couplings);\n            return;\n        }\n        else { /// Same material\n            particle.pos = rnew;\n\n\n            /// Make here the contribution to the segment\n            process_segment(particle.boxid,\n                            particle.t,\n                            particle.t + tf,\n                            particle.sign,\n                            timegrid,\n                            v,\n                            gz,\n                            gz_jx,\n                            gz_jy,\n                            mu,\n                            pq,\n                            pb,\n                            sd);\n            particle.t += tf;\n            particle.boxid = pboxes[0];\n            if (cboxes.find(particle.boxid) == cboxes.end()) {\n                throw alma::geometry_error(\"Teleport is not allowed\");\n            }\n        }\n\n        // std::cout << \"#boxchange\" << std::endl;\n        // evolparticle(particle, v, sys, left_time, rnd,\n        // pmutex,db,grids,timegrid,gz,gz_jx,gz_jy,DMM_gen,thickness,cells,material_sampler,sd,couplings);\n        return;\n    }\n    else {\n        // Make here the contribution to the segment\n        process_segment(particle.boxid,\n                        particle.t,\n                        particle.t + tf,\n                        particle.sign,\n                        timegrid,\n                        v,\n                        gz,\n                        gz_jx,\n                        gz_jy,\n                        mu,\n                        pq,\n                        pb,\n                        sd);\n\n        particle.t += tf;\n        particle.pos = rnew;\n\n\n        std::vector<std::size_t> pbox2;\n\n        Eigen::Vector2d rcheck = rnew + 1.0e-6 * v;\n\n        for (auto& PB : pboxes) {\n            if (sys[PB].inside(rcheck)) {\n                pbox2.push_back(PB);\n            }\n        }\n\n        std::size_t newid;\n        if (pbox2.empty()) {\n            newid = *(alma::choose(pboxes.begin(), pboxes.end(), rnd));\n\n            Eigen::Vector2d d = sys[newid].get_center() - rnew;\n            if (!sys[newid].periodic)\n                particle.pos += 1.0e-6 * d / d.norm();\n\n            if (sys[particle.boxid].material != sys[newid].material) {\n                change_material_diffuse(newid,cboxes,particle,sys,dt,rnd,pmutex,grids,\n                                        DMM_gen,thickness,cells,couplings);\n                return;\n            }\n\n            particle.boxid = newid;\n        }\n        else {\n            newid = *(alma::choose(pbox2.begin(), pbox2.end(), rnd));\n\n            if (sys[particle.boxid].material != sys[newid].material) {\n                change_material_diffuse(newid,cboxes,particle,sys,dt,rnd,pmutex,grids,\n                                        DMM_gen,thickness,cells,couplings);\n                return;\n            }\n\n            particle.boxid = newid;\n        }\n\n\n        if (cboxes.find(particle.boxid) == cboxes.end()) {\n            throw alma::geometry_error(\"Teleport is not allowed\");\n        }\n\n        return;\n    }\n\n\n    throw alma::geometry_error(\"This point should not be reached\");\n\n    return;\n}\n\n\n/// Particle evolution:\n///@param[in,out] particle - deviational particle to evolve\n///@param[in] v        - particle velocity\n///@param[in] sys      - geometry and box info\n///@param[in] dt       - time to evolve\n///@param[in] rnd     - random generator\n///@param[in] pmutex  - mutex\n///@param[in] db      - diffusive boundary scattering table\n///@param[in] grids   - qgrid data per material\n///@param[in] timegrid - time mesh\n///@param[in,out] gz   - matrix to save particles contributions to bins\n///@param[in,out] gz_jx - matrix where to save the contribution to jx\n///@param[in,out] gz_jy - matrix where to save the contribution to jy\n///@param[in,out] phi   - energy loss\n///@param[in]     DMM_gen - DMM generators for interface scattering\n///@param[in]     thickness - correct materials thickness\n///@param[in]     cells     - cells data\ntemplate <class Random, class Mutex>\nvoid evolparticle(\n    alma::D_particle& particle,\n    Eigen::Vector2d& v,\n    std::vector<alma::geometry_2d>& sys,\n    double& dt,\n    Random& rnd,\n    Mutex& pmutex,\n    generators::diffusive_bouncing& db,\n    gridData& grids,\n    Eigen::VectorXd& timegrid,\n    Eigen::ArrayXd& gz,\n    Eigen::ArrayXd& gz_jx,\n    Eigen::ArrayXd& gz_jy,\n    Eigen::ArrayXd& phi,\n    DMM& DMM_gen,\n    std::vector<double>& thickness,\n    cellData& cells,\n    std::map<std::string, alma::BE_derivative_distribution>& material_sampler,\n    std::vector<alma::D_particle>& particles,\n    spectral_decomposition& sd,\n    alma::layer_coupling& couplings) {\n    Eigen::Vector2d opos(particle.pos);\n\n    /// Make some v check\n    for (auto iv : {0, 1}) {\n        if (alma::almost_equal(v(iv), 0.) and v(iv) != 0.) {\n            throw alma::geometry_error(\n                \"Error, please set all that\"\n                \" evaluates almost_equal to 0 as 0. Otherwise,\"\n                \" geometric algorithms will fail\\n\"\n                \"Specifically the rnew check as it contains \"\n                \"v in spatial search of boxes to go\\n\");\n        }\n    }\n\n\n    auto pq = particle.q;\n    auto pb = particle.alpha;\n    double mu =\n        grids[sys[particle.boxid].material]->get_spectrum_at_q(pq).omega(pb);\n\n\n    /// Apply PBC\n    if (sys[particle.boxid].periodic) {\n        pmutex.lock();\n        auto PBCsol = sys[particle.boxid].translate(opos, v, sys, rnd);\n        pmutex.unlock();\n\n        particle.boxid = PBCsol.first;\n        particle.pos = PBCsol.second;\n        return;\n    }\n\n    /// Check if in reservoir\n    if (sys[particle.boxid].reservoir) {\n        /// Terminated particle\n        particle.q = 0;\n        particle.alpha = 0;\n        dt = 0.;\n        return;\n    }\n\n    Eigen::Vector2d rnew = particle.pos + dt * v;\n\n    /// Check if inside the same box:\n\n    if (sys[particle.boxid].inside(rnew)) {\n        if (sys[particle.boxid].periodic) {\n            std::cout << \"Periodic boxes do not exist\\n\";\n            std::cout << \"r0\\n\" << opos << std::endl;\n            std::cout << \"rf\\n\" << rnew << std::endl;\n            std::cout << \"dt \" << dt << std::endl;\n            std::cout << particle.pos << std::endl;\n            std::cout << \"v\\n\" << v << std::endl;\n            throw alma::geometry_error(\"Peridic error\\n\");\n        }\n\n        particle.pos = rnew;\n        particle.t += dt;\n        dt = 0.;\n\n        /// Make here the contribution to the segment\n        process_segment(particle.boxid,\n                        particle.sign,\n                        dt,\n                        v,\n                        gz,\n                        gz_jx,\n                        gz_jy,\n                        phi,\n                        mu,\n                        pq,\n                        pb,\n                        sd,\n                        true);\n\n\n        /// Scattering here (serial because of rng protection):\n        auto mat = sys[particle.boxid].material;\n\n        return;\n    }\n\n    /// Check the place it left\n    Eigen::Vector2d rp;\n    rp << particle.pos(0), particle.pos(1);\n\n    /// Here we calculate where the particle is\n    /// going out\n    std::tuple<double, Eigen::Vector2d, std::vector<int>> MRU_sol;\n\n    try {\n        MRU_sol = sys[particle.boxid].get_inter_side(rp, v, dt);\n    }\n    catch (const alma::geometry_error& geomerror) {\n        Eigen::Vector2d d = sys[particle.boxid].get_center() - opos;\n        particle.pos += 1.0e-6 * d / d.norm();\n        // evolparticle(particle, v, sys, dt, rnd,\n        // pmutex,db,grids,timegrid,gz,gz_jx,gz_jy,phi,DMM_gen,thickness,cells,material_sampler,particles,sd,couplings);\n        return;\n    }\n\n    if (std::get<0>(MRU_sol) < 0) {\n        throw alma::geometry_error(\"Error in kinematics\\n\");\n        exit(EXIT_FAILURE);\n    }\n    /// Calculating leftime\n    double left_time = dt - std::get<0>(MRU_sol);\n    double tf = std::get<0>(MRU_sol);\n    if (alma::almost_equal(left_time, 0.)) {\n        left_time = 0.;\n    }\n    rnew = std::get<1>(MRU_sol);\n    dt = left_time;\n\n    decltype(rnew) reps = rnew + 1.0e-6 * v / v.norm();\n\n\n    /// Get contact boxes\n    std::set<std::size_t> cboxes;\n    for (auto& [ibc, border] : sys[particle.boxid].get_contacts()) {\n        cboxes.insert(ibc);\n    }\n\n    /// Check possible boxes to assign:\n    std::vector<std::size_t> pboxes;\n\n    for (auto test : cboxes) {\n        if (test == particle.boxid) {\n            continue;\n        }\n\n        auto border_contact = sys[particle.boxid].get_contacts()[test];\n        /// If going along border we do not change\n        bool parallel = alma::almost_equal((border_contact[0].np).dot(v), 0.);\n\n        bool oriented = ((border_contact[0].np).dot(v) > 0.);\n\n        if ((sys[test].inside(rnew) or sys[test].inside(reps)) and !parallel and\n            oriented) {\n            pboxes.push_back(test);\n        }\n    }\n\n    /// If going inside the void\n    if (pboxes.size() == 0) {\n        \n        /// Make here the contribution to the segment\n        process_segment(particle.boxid,\n                        particle.sign,\n                        tf,\n                        v,\n                        gz,\n                        gz_jx,\n                        gz_jy,\n                        phi,\n                        mu,\n                        pq,\n                        pb,\n                        sd);\n        particle.t += tf;\n\n\n        /// Correcting three corner problem\n        auto corner_problem = in_corner3(rnew, sys);\n        if (corner_problem.first) {\n            auto csol = correct_corner_problem(\n                rnew, v, sys, corner_problem.second, rnd);\n            particle.boxid = csol.first;\n            Eigen::Vector2d correction =\n                sys[particle.boxid].get_center() - rnew;\n            Eigen::Vector2d corrected_pos =\n                rnew + 1.0e-6 * correction / correction.norm();\n\n            MRU_sol =\n                sys[particle.boxid].get_inter_side(corrected_pos, v, 1.0e+18);\n\n            rnew = std::get<1>(MRU_sol);\n        }\n\n\n        /// Diffusive scattering\n        std::size_t iborder;\n        auto iborders = std::get<2>(MRU_sol);\n        if (iborders.size() > 1) {\n            /// We first check the borders\n            /// that touch void\n            std::vector<std::size_t> voidborders;\n\n            for (auto& tvb : iborders) {\n                auto& mb = sys[particle.boxid].get_border(tvb);\n\n                Eigen::Vector2d rc = rnew + 1.0e-4 * mb.np;\n\n                bool isvoid = true;\n                for (auto& cb : cboxes) {\n                    if (sys[cb].inside(rc)) {\n                        isvoid = false;\n                        break;\n                    }\n                }\n\n                if (isvoid) {\n                    voidborders.push_back(tvb);\n                }\n            }\n\n            if (voidborders.empty()) {\n                throw alma::geometry_error(\"Error in void borders\\n\");\n            }\n\n            // In the case two borders pointing at void\n            iborder = voidborders[std::uniform_int_distribution(\n                0, static_cast<int>(voidborders.size()))(rnd)];\n        }\n        else {\n            iborder = iborders[0];\n        }\n\n        auto u = sys[particle.boxid].get_border(iborder).np;\n\n        Eigen::Vector3d unp3;\n        unp3 << u(0), u(1), 0.;\n\n        std::size_t Nb =\n            static_cast<std::size_t>(grids[sys[particle.boxid].material]\n                                         ->get_spectrum_at_q(0)\n                                         .omega.size());\n        auto newmode = db.bounce(unp3,\n                                 sys[particle.boxid].material,\n                                 particle.q * Nb + particle.alpha,\n                                 grids,\n                                 rnd);\n\n        particle.pos = rnew;\n        particle.q = newmode.second;\n        particle.alpha = newmode.first;\n        \n        dt = 0.;\n        pmutex.lock();\n        particles.push_back(particle);\n        pmutex.unlock();\n        return;\n    }\n    else if (pboxes.size() == 1) {\n        /// Change material\n        if (sys[particle.boxid].material != sys[pboxes[0]].material) {\n            /// Save contribution here\n            process_segment(particle.boxid,\n                            particle.sign,\n                            tf,\n                            v,\n                            gz,\n                            gz_jx,\n                            gz_jy,\n                            phi,\n                            mu,\n                            pq,\n                            pb,\n                            sd);\n            particle.t += tf;\n            particle.pos = rnew;\n            change_material_diffuse(pboxes[0],cboxes,particle,sys,dt,rnd,pmutex,grids,\n                                    DMM_gen,thickness,cells,couplings);\n            pmutex.lock();\n            particles.push_back(particle);\n            pmutex.unlock();\n            return;\n        }\n        else { /// Same material\n            particle.pos = rnew;\n            particle.t += tf;\n\n            /// Make here the contribution to the segment\n            process_segment(particle.boxid,\n                            particle.sign,\n                            tf,\n                            v,\n                            gz,\n                            gz_jx,\n                            gz_jy,\n                            phi,\n                            mu,\n                            pq,\n                            pb,\n                            sd);\n            particle.boxid = pboxes[0];\n            if (cboxes.find(particle.boxid) == cboxes.end()) {\n                throw alma::geometry_error(\"Teleport is not allowed\");\n            }\n        }\n\n        // std::cout << \"#boxchange\" << std::endl;\n        // evolparticle(particle, v, sys, left_time, rnd,\n        // pmutex,db,grids,timegrid,gz,gz_jx,gz_jy,phi,DMM_gen,thickness,cells,material_sampler,particles,sd,couplings);\n        return;\n    }\n    else {\n        // Make here the contribution to the segment\n        process_segment(particle.boxid,\n                        particle.sign,\n                        tf,\n                        v,\n                        gz,\n                        gz_jx,\n                        gz_jy,\n                        phi,\n                        mu,\n                        pq,\n                        pb,\n                        sd);\n\n        particle.t += tf;\n        particle.pos = rnew;\n\n\n        std::vector<std::size_t> pbox2;\n\n        Eigen::Vector2d rcheck = rnew + 1.0e-6 * v;\n\n        for (auto& PB : pboxes) {\n            if (sys[PB].inside(rcheck)) {\n                pbox2.push_back(PB);\n            }\n        }\n\n        std::size_t newid;\n        if (pbox2.empty()) {\n            newid = *(alma::choose(pboxes.begin(), pboxes.end(), rnd));\n\n            Eigen::Vector2d d = sys[newid].get_center() - rnew;\n            if (!sys[newid].periodic)\n                particle.pos += 1.0e-6 * d / d.norm();\n\n            if (sys[particle.boxid].material != sys[newid].material) {\n                change_material_diffuse(newid,cboxes,particle,sys,dt,rnd,pmutex,grids,\n                                        DMM_gen,thickness,cells,couplings);\n                pmutex.lock();\n                particles.push_back(particle);\n                pmutex.unlock();\n                return;\n            }\n\n            particle.boxid = newid;\n        }\n        else {\n            newid = *(alma::choose(pbox2.begin(), pbox2.end(), rnd));\n\n            if (sys[particle.boxid].material != sys[newid].material) {\n                change_material_diffuse(newid,cboxes,particle,sys,dt,rnd,pmutex,grids,DMM_gen,\n                                        thickness,cells,couplings);\n                pmutex.lock();\n                particles.push_back(particle);\n                pmutex.unlock();\n                return;\n            }\n\n            particle.boxid = newid;\n        }\n\n\n        if (cboxes.find(particle.boxid) == cboxes.end()) {\n            throw alma::geometry_error(\"Teleport is not allowed\");\n        }\n        \n        return;\n    }\n\n\n    throw alma::geometry_error(\"This point should not be reached\");\n\n    return;\n}\n\n\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 process_input(std::string& filename,\n                               boost::mpi::communicator& world) {\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(\"RTA_MC2d\")) {\n        /// Reading geometry\n        if (v.first == \"geometry\") {\n            std::string gfname = alma::parseXMLfield<std::string>(v, \"file\");\n            inpars.system = alma::read_geometry_XML(gfname);\n        }\n        if (v.first == \"time\") {\n            inpars.dt = alma::parseXMLfield<double>(v, \"dt\");\n            inpars.maxtime = alma::parseXMLfield<double>(v, \"maxtime\");\n        }\n        if (v.first == \"gradient\") {\n            inpars.gradient(0) = alma::parseXMLfield<double>(v, \"x\");\n            inpars.gradient(1) = alma::parseXMLfield<double>(v, \"y\");\n        }\n\n        if (v.first == \"ballistic\") {\n            inpars.ballistic = true;\n        }\n\n        if (v.first == \"convergence\") {\n            inpars.eps_energy = alma::parseXMLfield<double>(v, \"energy\");\n            inpars.eps_flux = alma::parseXMLfield<double>(v, \"flux\");\n        }\n\n        if (v.first == \"layer\") {\n            std::string material =\n                alma::parseXMLfield<std::string>(v, \"material\");\n\n            std::string layerid =\n                alma::parseXMLfield<std::string>(v, \"layer_name\");\n\n            std::string list_atoms =\n                alma::parseXMLfield<std::string>(v, \"atoms\");\n\n            std::vector<int> atoms_ids;\n            std::istringstream buf(list_atoms);\n            std::istream_iterator<std::string> beg(buf), end;\n            std::vector<std::string> tokens(beg, end); // done!\n            for (auto& s : tokens) {\n                atoms_ids.push_back(boost::lexical_cast<int>(s));\n            }\n\n            inpars.couplings.stack_injection = true;\n\n            inpars.couplings.layers[material][layerid] = atoms_ids;\n\n            std::cout << \"#Layer info: \\n\"\n                      << \"#   -material: \" << material << std::endl\n                      << \"#   -name: \" << layerid << std::endl\n                      << \"#   -atoms: \";\n            for (auto at_id : atoms_ids)\n                std::cout << at_id << '\\t';\n            std::cout << std::endl;\n        }\n\n        if (v.first == \"layers_connection\") {\n            std::string matA = alma::parseXMLfield<std::string>(v, \"layer_A\");\n            std::string matB = alma::parseXMLfield<std::string>(v, \"layer_B\");\n\n            std::cout << \"#Layer connection: \" << matA << \"->\" << matB\n                      << std::endl;\n            std::cout << \"#Layer connection: \" << matB << \"->\" << matA\n                      << std::endl;\n            inpars.couplings.connection[matA] = matB;\n            inpars.couplings.connection[matB] = matA;\n        }\n\n\n        if (v.first == \"material\") {\n            std::string name = alma::parseXMLfield<std::string>(v, \"name\");\n            std::string hdf5file =\n                alma::parseXMLfield<std::string>(v, \"database\");\n            double zsize = alma::parseXMLfield<double>(v, \"thickness\");\n            zmap[name] = zsize;\n            inpars.T0 = alma::parseXMLfield<double>(v, \"T0\");\n            auto data = alma::load_bulk_hdf5(hdf5file.c_str(), world);\n            inpars.system_cell[name] = std::move(std::get<1>(data));\n            inpars.system_grid[name] = std::move(std::get<3>(data));\n\n            auto processes = std::move(std::get<4>(data));\n\n            Eigen::ArrayXXd w3(alma::calc_w0_threeph(\n                *inpars.system_grid[name], *processes, inpars.T0, world));\n            auto twoph_processes =\n                alma::find_allowed_twoph(*inpars.system_grid[name], world);\n            Eigen::ArrayXXd w2(alma::calc_w0_twoph(*inpars.system_cell[name],\n                                                   *inpars.system_grid[name],\n                                                   twoph_processes,\n                                                   world));\n            Eigen::ArrayXXd w0(w3 + w2);\n\n            pcg_extras::seed_seq_from<std::random_device> seed_source;\n            pcg64 rng(seed_source);\n            /// Init the internal material properties for RTA loop\n\n            /// The cv is in J/(K*nm**3)\n            inpars.material_cv[name] = alma::calc_cv(*inpars.system_cell[name],\n                                                     *inpars.system_grid[name],\n                                                     inpars.T0);\n            /// The w are in 1/ps\n            inpars.material_w0[name] = w0;\n            inpars.material_sampler[name] =\n                alma::BE_derivative_distribution(*inpars.system_grid[name],\n                                                 inpars.material_w0[name],\n                                                 inpars.T0,\n                                                 rng);\n        }\n\n        if (v.first == \"particles\") {\n            inpars.Nparticles = alma::parseXMLfield<std::size_t>(v, \"N\");\n        }\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.sd.nomega =\n                        alma::parseXMLfield<std::size_t>(*it, \"ticks\");\n                }\n                if (it->first == \"location\") {\n                    std::size_t loc =\n                        alma::parseXMLfield<std::size_t>(*it, \"bin\");\n                    inpars.sd.gz_omega[loc] = Eigen::ArrayXXd(0, 0);\n                    inpars.sd.gzjx_omega[loc] = Eigen::ArrayXXd(0, 0);\n                    inpars.sd.gzjy_omega[loc] = Eigen::ArrayXXd(0, 0);\n                    inpars.sd.fd_qmesh[loc] = Eigen::ArrayXXd(0, 0);\n                }\n            }\n        }\n    }\n\n    for (auto& s : inpars.system) {\n        if (s.reservoir or s.periodic)\n            continue;\n        if (s.Teq != inpars.T0) {\n            throw alma::input_error(\"Tref in xml is different from provided T0\"\n                                    \" which is incorrect\\n\");\n        }\n        if (s.Treal != s.Teq) {\n            throw alma::input_error(\n                \"Initial temperature out of reference is not allowed\\n\"\n                \"use bRTA simulator with RTA option for those kind of \"\n                \"simulations\\n\");\n        }\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(zmap[mat]);\n    }\n\n\n    bool nograd = alma::almost_equal(inpars.gradient.norm(), 0.);\n\n    auto ntime = 2;\n\n    if (nograd)\n        ntime = std::floor(inpars.maxtime / inpars.dt + 1.0e-6) + 1;\n\n\n    /// Fill information for spectral decomposition\n    if (!inpars.sd.gz_omega.empty()) {\n        /// Init storing arrays\n        for (auto& [loc, gzo] : inpars.sd.gzjx_omega) {\n            gzo.resize(ntime - 1, inpars.sd.nomega);\n            gzo.setZero();\n        }\n\n        for (auto& [loc, gzo] : inpars.sd.fd_qmesh) {\n            auto mat = inpars.system[loc].material;\n            auto nq = inpars.system_grid[mat]->nqpoints;\n            gzo.resize(ntime - 1, nq);\n            gzo.setZero();\n        }\n\n\n        for (auto& [loc, gzo] : inpars.sd.gzjy_omega) {\n            gzo.resize(ntime - 1, inpars.sd.nomega);\n            gzo.setZero();\n        }\n\n        for (auto& [loc, gzo] : inpars.sd.gz_omega) {\n            gzo.resize(ntime - 1, inpars.sd.nomega);\n            gzo.setZero();\n\n            auto mat = inpars.system[loc].material;\n\n            /// If material is not registered\n            if (inpars.sd.omegagrid.count(loc) == 0) {\n                double maxomega = 0;\n\n\n                auto nq = inpars.system_grid[mat]->nqpoints;\n                auto nb = static_cast<int>(\n                    inpars.system_grid[mat]->get_spectrum_at_q(0).omega.size());\n\n                Eigen::ArrayXXd sigmas(nb, nq);\n                Eigen::ArrayXXd qpoints1stBZ(nq, 2);\n\n                /// Get maxomega\n                for (decltype(nq) iq = 0; iq < nq; iq++) {\n                    auto& sp = 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(iq, 0) = q1BZ.row(0).mean();\n                    qpoints1stBZ(iq, 1) = q1BZ.row(1).mean();\n\n                    for (int ib = 0; ib < nb; ib++) {\n                        if (sp.omega(ib) > maxomega)\n                            maxomega = sp.omega(ib);\n\n                        sigmas(ib, iq) =\n                            inpars.system_grid[mat]->base_sigma(sp.vg.col(ib));\n                    }\n                }\n\n                auto percent = alma::calc_percentiles_log(sigmas);\n                sigmas = sigmas.max(\n                    std::exp(percent[0] - 1.5 * (percent[1] - percent[0])));\n\n                double delta_omega =\n                    maxomega / static_cast<double>(inpars.sd.nomega);\n                inpars.sd.omegagrid[loc] =\n                    Eigen::ArrayXd::LinSpaced(inpars.sd.nomega, 0., maxomega);\n                inpars.sd.omegagrid[loc].array() += .5 * delta_omega;\n\n                inpars.sd.qpoints1stBZ[loc] = qpoints1stBZ;\n\n                inpars.sd.broadening_sigmas[loc] = sigmas;\n            }\n        }\n    }\n\n    return inpars;\n}\n\n\n/// Main loop of MC\n\n\nint main(int argc, char** argv) {\n    boost::mpi::environment env;\n    boost::mpi::communicator world;\n\n    auto tA = std::chrono::high_resolution_clock::now();\n\n    if (world.size() > 1) {\n        std::cout << \"Cannot run in MPI\" << std::endl;\n        std::cout << \"Multithreading is allowed via TBB\" << std::endl;\n        world.abort(1);\n    }\n\n    auto my_id = world.rank();\n\n    if (my_id == 0) {\n        std::cout << \"********************************************\"\n                  << std::endl;\n        std::cout << \"This is ALMA/RTA_MC2d version \" << ALMA_VERSION_MAJOR\n                  << \".\" << ALMA_VERSION_MINOR << std::endl;\n        std::cout << \"********************************************\"\n                  << std::endl;\n    }\n\n    // Check that the right number of arguments have been provided.\n    if (argc != 3 and argc != 4) {\n        if (my_id == 0) {\n            std::cerr << boost::format(\n                             \"Usage: %1% <inputfile.xml> nthreads nruns\") %\n                             argv[0]\n                      << std::endl;\n        }\n        return 1;\n    }\n\n\n    std::cout << \"#Init variables:\\n\";\n\n    std::size_t nthreadsTBB = std::atoi(argv[2]);\n    std::size_t nruns = 1;\n    if (argc == 4)\n        nruns = std::atoi(argv[3]);\n\n    tbb::global_control control(tbb::global_control::max_allowed_parallelism,\n                                nthreadsTBB);\n\n    /// Process the file:\n    std::string inputfile = argv[1];\n\n    input_parameters inpars = std::move(process_input(inputfile, world));\n\n    /// Geometry\n    std::vector<alma::geometry_2d> system;\n    std::swap(inpars.system, system);\n\n    std::vector<double> thicknesses;\n    std::swap(thicknesses, inpars.thicknesses);\n\n    /// Time\n    double dt = inpars.dt;\n    double maxtime = inpars.maxtime;\n    std::size_t ntime = std::floor(maxtime / dt + 1.0e-6) + 1;\n    maxtime = (ntime - 1) * dt;\n\n    Eigen::VectorXd timegrid = Eigen::VectorXd::LinSpaced(ntime, 0.0, maxtime);\n\n    /// Material data\n    cellData system_cell = std::move(inpars.system_cell);\n    gridData system_grid = std::move(inpars.system_grid);\n\n    /// The random generator\n    pcg_extras::seed_seq_from<std::random_device> seed_source;\n    pcg64 rng(seed_source);\n    /// Make the thread safe version\n    tbb::enumerable_thread_specific<pcg64> rng_tbb(rng);\n\n    if (inpars.couplings.stack_injection) {\n        std::cout << \"\\n#Layered system corrections ON\\n\" << std::endl;\n    }\n\n    auto Nparticles = inpars.Nparticles;\n\n    auto tB = std::chrono::high_resolution_clock::now();\n    std::cout << \"#Init variables -> Done (\"\n              << (static_cast<std::chrono::duration<double>>(tB - tA)).count()\n              << \" s )\" << std::endl\n              << std::endl;\n\n    /// Building the generators and getting energy info\n    std::cout << \"#Building generators and tables:\\n\";\n    std::cout << \"# Isothermal generators \\n\" << std::endl;\n    Eigen::Vector2d einfo;\n    generators::Init_generator(system,\n                               system_grid,\n                               system_cell,\n                               rng,\n                               thicknesses,\n                               inpars.gradient,\n                               einfo);\n    auto tC = std::chrono::high_resolution_clock::now();\n    std::cout << \"# Isothermal generators -> Done (\"\n              << (static_cast<std::chrono::duration<double>>(tC - tB)).count()\n              << \" s )\\n\"\n              << std::endl;\n\n    std::cout << \"# Diffusive table \\n\" << std::endl;\n    generators::diffusive_bouncing db(system_grid);\n    auto tD = std::chrono::high_resolution_clock::now();\n    std::cout << \"# Diffusive table -> Done (\"\n              << (static_cast<std::chrono::duration<double>>(tD - tC)).count()\n              << \" s )\\n\"\n              << std::endl;\n\n\n    std::cout << \"#Energy and particles information:\\n\";\n    std::cout << \"#|E| =\" << einfo(1) << \" J/ps\" << std::endl;\n    std::cout << \"#Nparticles = \" << Nparticles << std::endl;\n    double Eeff = einfo(1) / Nparticles;\n    std::cout << \"#Eeff = \" << Eeff << \" J/ps\" << std::endl;\n\n    std::mutex sphinx;\n    std::cout << \"#Generating particles:\" << std::endl;\n\n    /// Map for the DMM (it is private for each thread)\n    tbb::enumerable_thread_specific<DMM> DMM_gen_tbb;\n\n    std::size_t irun = 0;\n\n    while (irun < nruns) {\n        std::cout << \"#Run: \" << irun << std::endl;\n\n        unsigned int previous_percentage = 0;\n        std::size_t icounter = 0;\n\n        std::vector<alma::D_particle> particles;\n        particles.reserve(Nparticles);\n        for (decltype(Nparticles) i = 0; i < Nparticles; i++) {\n            Eigen::Vector2d einfo_;\n            auto particle = generators::Init_generator(system,\n                                                       system_grid,\n                                                       system_cell,\n                                                       rng,\n                                                       thicknesses,\n                                                       inpars.gradient,\n                                                       einfo_);\n            //           std::cout << particle.q << '\\t'<< particle.alpha <<\n            //              '\\t' << particle.boxid << std::endl;\n            particles.push_back(particle);\n        }\n        std::cout << \"#Starting MC loop\" << std::endl;\n        /// We evolve the particles\n\n        if (alma::almost_equal(inpars.gradient.norm(), 0)) {\n            /// Print info about intrinsic scattering\n            std::cout << \"#Intrinsic scattering: \" << std::boolalpha\n                      << !(inpars.ballistic) << std::endl;\n            /// To store data\n            Eigen::ArrayXXd gz(system.size(), ntime - 1);\n            gz.setZero();\n            Eigen::ArrayXXd gz_jx(gz);\n            Eigen::ArrayXXd gz_jy(gz);\n\n\n            tbb::enumerable_thread_specific<Eigen::ArrayXXd> gz_tbb(gz);\n            tbb::enumerable_thread_specific<Eigen::ArrayXXd> gz_jx_tbb(gz_jx);\n            tbb::enumerable_thread_specific<Eigen::ArrayXXd> gz_jy_tbb(gz_jy);\n\n\n            tbb::parallel_for(\n                static_cast<std::size_t>(0),\n                static_cast<std::size_t>(Nparticles),\n                static_cast<std::size_t>(1),\n                [&](std::size_t i) {\n                    double time = 0.;\n                    alma::D_particle& particle = particles[i];\n                    sphinx.lock();\n                    unsigned int current_percentage = static_cast<unsigned int>(\n                        100. * (icounter + 1) / Nparticles);\n\n                    if (current_percentage > previous_percentage) {\n                        unsigned int nchars = static_cast<unsigned int>(\n                            72. * (icounter + 1) / Nparticles);\n                        std::cout << \"[\";\n\n                        for (auto i = 0u; i < nchars; ++i) {\n                            std::cout << \"-\";\n                        }\n                        std::cout << \">\";\n\n                        for (auto i = nchars; i < 72; ++i) {\n                            std::cout << \" \";\n                        }\n                        std::cout << \"] \" << current_percentage << \"%\\r\";\n                        std::cout.flush();\n                        previous_percentage = current_percentage;\n                    }\n\n                    icounter++;\n                    sphinx.unlock();\n\n                    /// Particle evoulution and info collection [Multithreading:\n                    /// TBB]\n                    while (time < maxtime) {\n                        // std::cout << i << '\\t' << time << '\\t'\n                        //<< particle.t  <<'\\t' <<\n                        // particle.pos.transpose(); //<< std::endl;\n                        auto mat = system[particle.boxid].material;\n                        auto v = get_v(\n                            *system_grid[mat], particle.alpha, particle.q);\n                        double dt_;\n                        try {\n                            dt_ =\n                                alma::random_dt(inpars.material_w0[mat](\n                                                    particle.alpha, particle.q),\n                                                rng_tbb.local());\n                        }\n                        catch (const alma::value_error& error_) {\n                            std::cout << particle.boxid << '\\t'\n                                      << particle.alpha << '\\t' << particle.q\n                                      << '\\t' << particle.t << '\\t' << time\n                                      << std::endl;\n                            throw alma::value_error(\"invalid scattering rate\");\n                        }\n                        // std::cout << '\\t' << dt_ << std::endl;\n                        if (time + dt_ > maxtime) {\n                            dt_ = maxtime - time + 1.0e-8;\n                        }\n\n                        while (!alma::almost_equal(dt_, 0.)) {\n                            /// We move the particle\n                            evolparticle(particle,\n                                         v,\n                                         system,\n                                         dt_,\n                                         rng_tbb.local(),\n                                         sphinx,\n                                         db,\n                                         system_grid,\n                                         timegrid,\n                                         gz_tbb.local(),\n                                         gz_jx_tbb.local(),\n                                         gz_jy_tbb.local(),\n                                         DMM_gen_tbb.local(),\n                                         thicknesses,\n                                         system_cell,\n                                         inpars.material_sampler,\n                                         inpars.sd,\n                                         inpars.couplings,\n                                         inpars.ballistic);\n                        }\n                        /// Check if arrived to reservoir\n                        /// In that case terminate with that particle\n                        if (particle.q == 0 and particle.alpha == 0)\n                            break;\n\n                        time = particle.t;\n                    }\n                });\n\n            auto tE = std::chrono::high_resolution_clock::now();\n            std::cout\n                << \"\\n#MC loop -> Done ( \"\n                << (static_cast<std::chrono::duration<double>>(tE - tD)).count()\n                << \" s ) \" << std::endl;\n\n            std::cout << \"#Collecting and processing information\\n\";\n            for (auto& g : gz_tbb)\n                gz += g;\n\n            for (auto& g : gz_jx_tbb)\n                gz_jx += g;\n\n            for (auto& g : gz_jy_tbb)\n                gz_jy += g;\n\n            /// The gz is now processed to get the time evolution of the system\n            for (auto ir = 0; ir < gz.rows(); ir++) {\n                /// To obtain the energy density [J/nm**3]\n                /// we divide by the volume of each box\n                double vbox = system[ir].get_area() * thicknesses[ir];\n                gz.row(ir) /= vbox;\n                gz_jx.row(ir) /= vbox;\n                gz_jy.row(ir) /= vbox;\n            }\n            gz *= Eeff;\n            /// We want flux in [J/(m**2 * s)] it is in [J/(nm**2 * ps)]\n            gz_jx *= Eeff * 1e12 * 1e9 * 1e9;\n            gz_jy *= Eeff * 1e12 * 1e9 * 1e9;\n\n\n            /// Spectral decomposition treatment\n            if (!inpars.sd.gz_omega.empty()) {\n                for (auto& [loc, g] : inpars.sd.gz_omega) {\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    g *= Eeff / vbox;\n                }\n\n                for (auto& [loc, g] : inpars.sd.gzjx_omega) {\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    g *= Eeff * 1e12 * 1e9 * 1e9 / vbox;\n                }\n\n                for (auto& [loc, g] : inpars.sd.gzjy_omega) {\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    g *= Eeff * 1e12 * 1e9 * 1e9 / vbox;\n                }\n\n                for (auto& [loc, g] : inpars.sd.fd_qmesh) {\n                    auto mat = system[loc].material;\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    double vcorr =\n                        thicknesses[loc] / system_cell[mat]->lattvec(2, 2);\n                    int NQs = system_grid[mat]->nqpoints;\n\n                    g *= Eeff * vcorr * NQs /\n                         (vbox * 1.0e+12 * alma::constants::hbar);\n                }\n            }\n\n            // Integrate gz in time to get the time response.\n            for (auto ic = 1; ic < gz.cols(); ic++) {\n                gz.col(ic) += gz.col(ic - 1);\n                gz_jx.col(ic) += gz_jx.col(ic - 1);\n                gz_jy.col(ic) += gz_jy.col(ic - 1);\n            }\n\n            /// Spectral decomposition\n            if (!inpars.sd.gz_omega.empty()) {\n                for (auto& [loc, g] : inpars.sd.gz_omega) {\n                    for (int ir = 1; ir < g.rows(); ir++)\n                        g.row(ir) += g.row(ir - 1);\n                }\n\n                for (auto& [loc, g] : inpars.sd.fd_qmesh) {\n                    for (int ir = 1; ir < g.rows(); ir++)\n                        g.row(ir) += g.row(ir - 1);\n                }\n\n                for (auto& [loc, g] : inpars.sd.gz_omega) {\n                    auto mat = system[loc].material;\n                    double vcorr =\n                        thicknesses[loc] / system_cell[mat]->lattvec(2, 2);\n                    g = g / (inpars.material_cv[system[loc].material] / vcorr);\n                }\n\n\n                for (auto& [loc, g] : inpars.sd.gzjx_omega) {\n                    for (int ir = 1; ir < g.rows(); ir++)\n                        g.row(ir) += g.row(ir - 1);\n                }\n\n                for (auto& [loc, g] : inpars.sd.gzjy_omega) {\n                    for (int ir = 1; ir < g.rows(); ir++)\n                        g.row(ir) += g.row(ir - 1);\n                }\n            }\n\n\n            // Translate gz into a \"macroscopic\" temperature.\n            Eigen::ArrayXXd T(gz);\n            for (auto ir = 0; ir < gz.rows(); ir++) {\n                /// We divide by Cv to get deviational temperature\n                /// more accurate as deviation gets larger will be a cubic\n                /// interpolator\n\n                /// We need to correct the volume for the Cv\n                auto mat = system[ir].material;\n                double vcorr =\n                    thicknesses[ir] / system_cell[mat]->lattvec(2, 2);\n\n\n                T.row(ir) =\n                    T.row(ir) /\n                        (inpars.material_cv[system[ir].material] / vcorr) +\n                    inpars.T0;\n            }\n\n            // Write out temperature profile\n            std::cout << \"# Writing temperature\" << std::endl;\n            std::string filename{\n                (boost::format(\"temperature_%|g|K_run_%|i|.csv\") % inpars.T0 %\n                 irun)\n                    .str()};\n            Eigen::MatrixXd output{ntime - 1, system.size() + 1};\n            for (std::size_t i = 0; i < ntime - 1; i++)\n                output(i, 0) = (i + 0.5) * dt;\n            output.bottomRightCorner(ntime - 1, system.size()) = T.transpose();\n            alma::write_to_csv(filename, output, ',');\n\n\n            /// Write fluxes\n            std::cout << \"# Writing Jx\" << std::endl;\n            std::string filename_jx{\n                (boost::format(\"jx_%|g|K_run_%|i|.csv\") % inpars.T0 % irun)\n                    .str()};\n            Eigen::MatrixXd output_jx{ntime - 1, system.size() + 1};\n            for (std::size_t i = 0; i < ntime - 1; i++)\n                output_jx(i, 0) = (i + 0.5) * dt;\n            output_jx.bottomRightCorner(ntime - 1, system.size()) =\n                gz_jx.transpose();\n            alma::write_to_csv(filename_jx, output_jx, ',');\n\n            std::cout << \"# Writing Jy\" << std::endl;\n            std::string filename_jy{\n                (boost::format(\"jy_%|g|K_run_%|i|.csv\") % inpars.T0 % irun)\n                    .str()};\n            Eigen::MatrixXd output_jy{ntime - 1, system.size() + 1};\n            for (std::size_t i = 0; i < ntime - 1; i++)\n                output_jy(i, 0) = (i + 0.5) * dt;\n            output_jy.bottomRightCorner(ntime - 1, system.size()) =\n                gz_jy.transpose();\n            alma::write_to_csv(filename_jy, output_jy, ',');\n\n            if (!inpars.sd.gz_omega.empty()) {\n                std::cout << \"# Writing spectral decompositions\" << std::endl;\n                for (auto& [loc, g] : inpars.sd.gz_omega) {\n                    std::string filename_{\n                        (boost::format(\"deltaT_omega_%|i|_%|g|K_run_%|i|.csv\") %\n                         loc % inpars.T0 % irun)\n                            .str()};\n                    Eigen::MatrixXd output{ntime, inpars.sd.nomega + 1};\n                    output(0, 0) = -1.0;\n                    for (std::size_t i = 1; i < ntime; i++)\n                        output(i, 0) = (i + 0.5) * dt;\n                    output.block(0, 1, 1, inpars.sd.nomega) =\n                        inpars.sd.omegagrid[loc].transpose();\n                    output.bottomRightCorner(ntime - 1, inpars.sd.nomega) = g;\n                    alma::write_to_csv(filename_, output, ',');\n                }\n\n                for (auto& [loc, g] : inpars.sd.fd_qmesh) {\n                    std::string filename_{\n                        (boost::format(\"fd_q_%|i|_%|g|K_run_%|i|.csv\") % loc %\n                         inpars.T0 % irun)\n                            .str()};\n                    std::string header_msg = \"\";\n                    int nq = g.cols();\n                    header_msg += \"# \";\n                    for (int iq = 0; iq < nq; iq++)\n                        header_msg +=\n                            std::to_string(inpars.sd.qpoints1stBZ[loc](iq, 0)) +\n                            \",\";\n                    header_msg.pop_back();\n                    header_msg += \"\\n# \";\n                    for (int iq = 0; iq < nq; iq++)\n                        header_msg +=\n                            std::to_string(inpars.sd.qpoints1stBZ[loc](iq, 1)) +\n                            \",\";\n                    header_msg.pop_back();\n                    header_msg += \"\\n# \";\n                    alma::write_to_csv(filename_, g, ',', false, header_msg);\n                }\n\n                for (auto& [loc, g] : inpars.sd.gzjx_omega) {\n                    std::string filename_{\n                        (boost::format(\"jx_omega_%|i|_%|g|K_run_%|i|.csv\") %\n                         loc % inpars.T0 % irun)\n                            .str()};\n                    Eigen::MatrixXd output{ntime, inpars.sd.nomega + 1};\n                    output(0, 0) = -1.0;\n                    for (std::size_t i = 1; i < ntime; i++)\n                        output(i, 0) = (i + 0.5) * dt;\n                    output.block(0, 1, 1, inpars.sd.nomega) =\n                        inpars.sd.omegagrid[loc].transpose();\n                    output.bottomRightCorner(ntime - 1, inpars.sd.nomega) = g;\n                    alma::write_to_csv(filename_, output, ',');\n                }\n                for (auto& [loc, g] : inpars.sd.gzjy_omega) {\n                    std::string filename_{\n                        (boost::format(\"jy_omega_%|i|_%|g|K_run_%|i|.csv\") %\n                         loc % inpars.T0 % irun)\n                            .str()};\n                    Eigen::MatrixXd output{ntime, inpars.sd.nomega + 1};\n                    output(0, 0) = -1.0;\n                    for (std::size_t i = 1; i < ntime; i++)\n                        output(i, 0) = (i + 0.5) * dt;\n                    output.block(0, 1, 1, inpars.sd.nomega) =\n                        inpars.sd.omegagrid[loc].transpose();\n                    output.bottomRightCorner(ntime - 1, inpars.sd.nomega) = g;\n                    alma::write_to_csv(filename_, output, ',');\n                }\n                inpars.sd.clean();\n            }\n        }\n        else {\n            /// This is the case of periodic structures the algorithm is\n            /// different\n            std::cout << \"PERIODIC CASE: [only steady state is simulated]\\n\";\n            if (inpars.eps_energy > 0.)\n                std::cout << \"#energy convergence \" << inpars.eps_energy\n                          << std::endl;\n            if (inpars.eps_flux > 0.)\n                std::cout << \"#flux convergence \" << inpars.eps_flux\n                          << std::endl;\n\n            /// To store data\n            Eigen::ArrayXd gz(system.size());\n            gz.setZero();\n            Eigen::ArrayXd gz_jx(gz);\n            Eigen::ArrayXd gz_jy(gz);\n            Eigen::ArrayXd phi(gz);\n\n            bool converged = false;\n            std::size_t counter = 1;\n\n            while (particles.size() != 0 and !converged) {\n                Eigen::ArrayXd null(system.size());\n                null.setZero();\n                tbb::enumerable_thread_specific<Eigen::ArrayXd> phi_tbb(null);\n                tbb::enumerable_thread_specific<Eigen::ArrayXd> gz_tbb(null);\n                tbb::enumerable_thread_specific<Eigen::ArrayXd> gz_jx_tbb(null);\n                tbb::enumerable_thread_specific<Eigen::ArrayXd> gz_jy_tbb(null);\n\n                std::vector<alma::D_particle> newparticles;\n\n                tbb::parallel_for(\n                    static_cast<std::size_t>(0),\n                    static_cast<std::size_t>(particles.size()),\n                    static_cast<std::size_t>(1),\n                    [&](std::size_t i) {\n                        auto& particle = particles[i];\n                        auto mat = system[particle.boxid].material;\n                        auto v = get_v(\n                            *system_grid[mat], particle.alpha, particle.q);\n                        double dt_;\n                        try {\n                            dt_ =\n                                alma::random_dt(inpars.material_w0[mat](\n                                                    particle.alpha, particle.q),\n                                                rng_tbb.local());\n                        }\n                        catch (const alma::value_error& error_) {\n                            std::cout << particle.boxid << '\\t'\n                                      << particle.alpha << '\\t' << particle.q\n                                      << '\\t' << particle.t << std::endl;\n                            throw alma::value_error(\"invalid scattering rate\");\n                        }\n\n                        while (!alma::almost_equal(dt_, 0.)) {\n                            /// We move the particle\n                            evolparticle(particle,\n                                         v,\n                                         system,\n                                         dt_,\n                                         rng_tbb.local(),\n                                         sphinx,\n                                         db,\n                                         system_grid,\n                                         timegrid,\n                                         gz_tbb.local(),\n                                         gz_jx_tbb.local(),\n                                         gz_jy_tbb.local(),\n                                         phi_tbb.local(),\n                                         DMM_gen_tbb.local(),\n                                         thicknesses,\n                                         system_cell,\n                                         inpars.material_sampler,\n                                         newparticles,\n                                         inpars.sd,\n                                         inpars.couplings);\n                        }\n                    });\n\n                Eigen::ArrayXd oldgz(gz);\n                Eigen::ArrayXd oldgzjx(gz_jx);\n                Eigen::ArrayXd oldgzjy(gz_jy);\n\n                for (auto& e : gz_tbb)\n                    gz += e;\n\n                for (auto& e : gz_jx_tbb)\n                    gz_jx += e;\n\n\n                for (auto& e : gz_jy_tbb)\n                    gz_jy += e;\n\n                /// Reset phi\n                phi.setZero();\n                for (auto& e : phi_tbb)\n                    phi += e;\n\n                /// Adding new particles\n                for (auto is = 0; is < phi.rows(); is++) {\n                    if (!alma::almost_equal(phi(is), 0)) {\n                        auto sign = alma::get_particle_sign(phi(is));\n                        for (int ig = 0; ig < (int)std::abs(phi(is)); ig++) {\n                            Eigen::Vector2d ppos =\n                                system[is].get_random_point(rng);\n\n                            auto mode =\n                                inpars.material_sampler.at(system[is].material)\n                                    .sample();\n\n                            alma::D_particle newp(\n                                ppos, mode[1], mode[0], sign, 0., is);\n\n                            newparticles.push_back(newp);\n                        }\n                    }\n                }\n\n                /// Calculating the new diff\n                const static double eps_gz = inpars.eps_energy;\n                const static double eps_flux = inpars.eps_flux;\n                double rgz = (oldgz - gz).matrix().norm() / gz.matrix().norm();\n                double rjx =\n                    (oldgzjx - gz_jx).matrix().norm() / gz_jx.matrix().norm();\n                double rjy =\n                    (oldgzjy - gz_jy).matrix().norm() / gz_jy.matrix().norm();\n\n                particles.clear();\n                particles.assign(newparticles.begin(), newparticles.end());\n                std::swap(newparticles, particles);\n\n\n                /// For convergence we will only take\n                if (alma::almost_equal(inpars.gradient(0), 0.)) {\n                    converged = rgz < eps_gz and rjy < eps_flux;\n                    std::cout << counter << '\\t' << particles.size() << '\\t'\n                              << rgz << '\\t' << rjy << std::endl;\n                }\n                else if (alma::almost_equal(inpars.gradient(1), 0.)) {\n                    converged = rgz < eps_gz and rjx < eps_flux;\n                    std::cout << counter << '\\t' << particles.size() << '\\t'\n                              << rgz << '\\t' << rjx << std::endl;\n                }\n                else {\n                    converged =\n                        rgz < eps_gz and rjx < eps_flux and rjy < eps_flux;\n                    std::cout << counter << '\\t' << particles.size() << '\\t'\n                              << rgz << '\\t' << rjx << '\\t' << rjy << std::endl;\n                }\n\n                counter++;\n            }\n\n\n            /// The gz is now processed to get the time evolution of the system\n            for (auto ir = 0; ir < gz.rows(); ir++) {\n                /// To obtain the energy density [J/nm**3]\n                /// we divide by the volume of each box\n                double vbox = system[ir].get_area() * thicknesses[ir];\n                gz.row(ir) /= vbox;\n                gz_jx.row(ir) /= vbox;\n                gz_jy.row(ir) /= vbox;\n            }\n            gz *= Eeff;\n            /// We want flux in [J/(m**2 * s)] it is in [J/(nm**2 * ps)]\n            gz_jx *= Eeff * 1e12 * 1e9 * 1e9;\n            gz_jy *= Eeff * 1e12 * 1e9 * 1e9;\n\n            // Translate gz into a \"macroscopic\" temperature.\n            Eigen::ArrayXXd T(gz);\n            for (auto ir = 0; ir < gz.rows(); ir++) {\n                /// We divide by Cv to get deviational temperature\n                /// more accurate as deviation gets larger will be a cubic\n                /// interpolator\n\n                /// We need to correct the volume for the Cv\n                auto mat = system[ir].material;\n                double vcorr =\n                    thicknesses[ir] / system_cell[mat]->lattvec(2, 2);\n\n                gz(ir) =\n                    gz(ir) / (inpars.material_cv[system[ir].material] / vcorr) +\n                    inpars.T0;\n            }\n\n            /// Spectral decomposition\n            if (!inpars.sd.gz_omega.empty()) {\n                for (auto& [loc, g] : inpars.sd.gz_omega) {\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    g *= Eeff / vbox;\n\n                    auto mat = system[loc].material;\n                    double vcorr =\n                        thicknesses[loc] / system_cell[mat]->lattvec(2, 2);\n                    g = g / (inpars.material_cv[system[loc].material] / vcorr);\n                }\n\n\n                for (auto& [loc, g] : inpars.sd.gzjx_omega) {\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    g *= Eeff * 1e12 * 1e9 * 1e9 / vbox;\n                }\n\n                for (auto& [loc, g] : inpars.sd.gzjy_omega) {\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    g *= Eeff * 1e12 * 1e9 * 1e9 / vbox;\n                }\n\n                for (auto& [loc, g] : inpars.sd.fd_qmesh) {\n                    auto mat = system[loc].material;\n                    double vbox = system[loc].get_area() * thicknesses[loc];\n                    double vcorr =\n                        thicknesses[loc] / system_cell[mat]->lattvec(2, 2);\n                    int NQs = system_grid[mat]->nqpoints;\n\n                    g *= Eeff * vcorr * NQs /\n                         (vbox * 1.0e+12 * alma::constants::hbar);\n                }\n            }\n\n\n            // Write out temperature profile\n            std::cout << \"# Writing steady state\" << std::endl;\n            std::string filename{\n                (boost::format(\"steady_%|g|K_run_%|i|.csv\") % inpars.T0 % irun)\n                    .str()};\n            Eigen::MatrixXd output{3, system.size()};\n            output.row(0) = gz;\n            output.row(1) = gz_jx;\n            output.row(2) = gz_jy;\n            alma::write_to_csv(filename, output, ',');\n\n\n            if (!inpars.sd.gz_omega.empty()) {\n                std::cout << \"# Writing spectral decompositions\" << std::endl;\n                for (auto& [loc, g] : inpars.sd.gz_omega) {\n                    std::string filename_{\n                        (boost::format(\n                             \"steady_deltaT_omega_%|i|_%|g|K_run_%|i|.csv\") %\n                         loc % inpars.T0 % irun)\n                            .str()};\n                    Eigen::MatrixXd output{2, inpars.sd.nomega};\n                    output.block(0, 0, 1, inpars.sd.nomega) =\n                        inpars.sd.omegagrid[loc].transpose();\n                    output.bottomRightCorner(1, inpars.sd.nomega) = g.row(0);\n                    alma::write_to_csv(filename_, output, ',');\n                }\n\n\n                for (auto& [loc, g] : inpars.sd.fd_qmesh) {\n                    std::string filename_{\n                        (boost::format(\"steady_fd_q_%|i|_%|g|K_run_%|i|.csv\") %\n                         loc % inpars.T0 % irun)\n                            .str()};\n                    std::string header_msg = \"\";\n                    int nq = g.cols();\n                    header_msg += \"# \";\n                    for (int iq = 0; iq < nq; iq++)\n                        header_msg +=\n                            std::to_string(inpars.sd.qpoints1stBZ[loc](iq, 0)) +\n                            \",\";\n                    header_msg.pop_back();\n                    header_msg += \"\\n# \";\n                    for (int iq = 0; iq < nq; iq++)\n                        header_msg +=\n                            std::to_string(inpars.sd.qpoints1stBZ[loc](iq, 1)) +\n                            \",\";\n                    header_msg.pop_back();\n                    header_msg += \"\\n# \";\n                    alma::write_to_csv(filename_, g, ',', false, header_msg);\n                }\n\n                for (auto& [loc, g] : inpars.sd.gzjx_omega) {\n                    std::string filename_{\n                        (boost::format(\n                             \"steady_jx_omega_%|i|_%|g|K_run_%|i|.csv\") %\n                         loc % inpars.T0 % irun)\n                            .str()};\n                    Eigen::MatrixXd output{2, inpars.sd.nomega};\n                    output.block(0, 0, 1, inpars.sd.nomega) =\n                        inpars.sd.omegagrid[loc].transpose();\n                    output.bottomRightCorner(1, inpars.sd.nomega) = g.row(0);\n                    alma::write_to_csv(filename_, output, ',');\n                }\n                for (auto& [loc, g] : inpars.sd.gzjy_omega) {\n                    std::string filename_{\n                        (boost::format(\n                             \"steady_jy_omega_%|i|_%|g|K_run_%|i|.csv\") %\n                         loc % inpars.T0 % irun)\n                            .str()};\n                    Eigen::MatrixXd output{2, inpars.sd.nomega};\n                    output.block(0, 0, 1, inpars.sd.nomega) =\n                        inpars.sd.omegagrid[loc].transpose();\n                    output.bottomRightCorner(1, inpars.sd.nomega) = g.row(0);\n                    alma::write_to_csv(filename_, output, ',');\n                }\n                inpars.sd.clean();\n            }\n        }\n        irun++;\n    }\n    auto t_final = std::chrono::high_resolution_clock::now();\n    std::cout\n        << \"# MC -> Done (\"\n        << (static_cast<std::chrono::duration<double>>(t_final - tD)).count()\n        << \" s )\\n\"\n        << std::endl;\n    std::cout << \"END\" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0c40bd1f03716ce98116f53a0f553da08c97ba31", "size": 105355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RTA_MC2D.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/RTA_MC2D.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/RTA_MC2D.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.9019264448, "max_line_length": 120, "alphanum_fraction": 0.4746618575, "num_tokens": 24657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.023330769105581906, "lm_q1q2_score": 0.009679909173456845}}
{"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 \"InlineCalculator.h\"\n\n// std library\n#include <cmath>\n\n// Qt library\n#include <QMap>\n#include <QString>\n#include <QStringList>\n#include <QVariant>\n#include <QVector>\n\n// boost library\n#include <boost/foreach.hpp>\n\n// naif library\n#include <SpiceUsr.h>\n#include <SpiceZfc.h>\n#include <SpiceZmc.h>\n\n// other ISIS\n#include \"IException.h\"\n#include \"InlineInfixToPostfix.h\"\n#include \"IString.h\"\n#include \"NaifStatus.h\"\n\nusing namespace std;\n\nnamespace Isis {\n\n  /**\n   * Constructs an InlineCalculator object by initializing the operator lookup\n   * list.\n   */  \n  InlineCalculator::InlineCalculator() : Calculator() {\n    initialize();\n  }\n \n\n  /**\n   * Constructs an InlineCalculator object by initializing the operator lookup\n   * list and compiles the given equation to prepare for evaluation.\n   *  \n   * @param equation A string representing an equation in infix format.\n   */  \n  InlineCalculator::InlineCalculator(const QString &equation) : Calculator() {\n    initialize();\n    compile(equation);\n  }\n \n\n  /**\n   * Destroys the InlineCalculator object.\n   */  \n  InlineCalculator::~InlineCalculator() {\n    destruct();\n  }\n \n \n  /**\n   * Accesses the number of functions, operators, variables, and scalars to be\n   * executed.\n   *  \n   * @return int The number of functions, operators, variables, and scalars\n   *         stored in the Calculator.\n   */  \n  int InlineCalculator::size() const {\n    return (m_functions.size());\n  }\n \n \n  /**\n   * Accesses the string representation of the current equation, in postfix\n   * format. This equation is most commonly entered using infix, but it is\n   * reformatted to postfix when set.\n   *  \n   * @return QString A string representing the equation, in postfix.\n   */  \n  QString InlineCalculator::equation() const {\n    return (m_equation);\n  }\n \n \n  /**\n   * @brief Compiles the given equation for evaluation.\n   *  \n   * This method first converts the given infix equation into a postfix\n   * equation for evaluation and saves the postfix formatted string. It then\n   * ensures that the equation is ready for evaluation by parsing and\n   * verifying that all tokens are recognized.\n   *  \n   * @param equation A string representing an equation to be compiled, in\n   *                 infix format.\n   *\n   * @return bool Indicates whether the compilation was successful.\n   * @throw IException::User \"Error parsing inline equation. Equation\n   *        element invalid - token not recognized.\"\n   *  \n   */\n  bool InlineCalculator::compile(const QString &equation) {\n    //  Transform equation to postfix order\n \n    QString tokenOps = toPostfix(equation);\n    tokenOps = tokenOps.simplified();\n\n    int nerrors = 0;\n    QString error =  \"Errors parsing inline equation[\" + equation + \"].\";\n    IException errList(IException::User, error, _FILEINFO_);\n \n    Clear();  // Clear the stack\n    m_equation = equation;\n    m_functions.clear();  // Clear function list\n \n    QStringList tokenList = tokenOps.split(\" \");\n    while ( !tokenList.isEmpty() ) {\n      QString token = tokenList.takeFirst();\n      if ( !token.isEmpty() ) {\n         \n        // See if the function already exists.  Note that scalars and variables\n        // that are already present can safely be reused.  New occuring ones are\n        // created fresh!\n        FxTypePtr fx = find(token);\n        if ( 0 != fx ) {\n          m_functions.push_back(fx);\n        }\n        // New scalars and variables will create new unique function objects if\n        // they do not already exist (they would be found above then)\n        else if ( isScalar(token)  ) {\n          fx = addFunction(new ParameterFx(token, &InlineCalculator::scalar, this));\n          m_functions.push_back(fx);\n        }\n        else if ( isVariable(token)  ) {\n          // Will also get line, sample, band, etc...\n          fx = addFunction(new ParameterFx(token, &InlineCalculator::variable, this));\n          m_functions.push_back(fx);\n        }\n        else {\n            //  Parameter not recognized during compile.  All unknown tokens are\n            //  assumed to be variables until run time when they are searched for\n            //  in the current state of the resource pool.\n          try {\n            if ( !orphanTokenHandler(token) ) {\n              error = \"Equation element (\" + token + \") invalid - token not recognized.\";\n              errList.append(IException(IException::User, error, _FILEINFO_));\n              nerrors++;\n            }\n          }\n          // Catch all failures from orphaned tokens\n          catch (IException &e) {\n            errList.append(e);\n            nerrors++;\n          }\n        }\n      }\n    }\n \n    //  Might want to make this optional here\n    if (nerrors > 0) {  \n      throw errList;\n    }\n    return (nerrors == 0);\n  }\n \n\n  /**\n   * @brief Evaluate with a variable pool\n   *  \n   * This method accepts a varible resource pool, stores it off for evaluation\n   * and then executes the operands to provide the result of the equation.  It\n   * stores the variable pool for subsequent runs that should yield identical\n   * results when operator() is invoked.\n   *\n   * @param variablePool Keyword resource for variables substituted at run time\n   *                     of the equation\n   *\n   * @return QVector \\< double \\> Result of the stored equation given the\n   *         resource.\n   * @throw IException::Programmer \"Calculation with variable pool failed.\"\n   *  \n   */\n  QVector<double> InlineCalculator::evaluate(CalculatorVariablePool *variablePool) {\n    QVector<double> value;\n    try {\n      pushVariables(variablePool);\n      value = evaluate();\n      popVariables();\n    }\n    catch (IException &ie) {\n      popVariables();\n      throw IException(ie, IException::Programmer,\n                       \"Calculation with variable pool failed.\",\n                       _FILEINFO_);\n    }\n    return (value);\n  }\n \n\n  /**\n   * @brief Evaluate compiled equation with existing variable pool\n   *  \n   * This executes the operands to provide the result of the equation.  The\n   * currently stored variable pool, refernenced via variables(), is used to\n   * provide the variables utilized in the equation.\n   *  \n   * This is reentrant and as long as the variable pool is unchanged between\n   * succesive calls, they all should return the same result.\n   *\n   * @return QVector \\< double \\> Result of the stored equation.\n   * @throw IException::Unknown \"Too many operands in the equation.\"\n   *  \n   */\n  QVector<double> InlineCalculator::evaluate() {\n \n    BOOST_FOREACH (FxTypePtr function,  m_functions) {\n      function->execute();\n    }\n \n    if (StackSize() != 1) {\n      QString msg = \"Too many operands in the equation [\" + m_equation + \"].\";\n      throw IException(IException::Unknown, msg, _FILEINFO_);\n    }\n \n    return (Pop(true));\n  }\n \n \n  /**\n   * Converts the given string from infix to postfix format.\n   *  \n   * @param equation A string representing an infix equation.\n   *  \n   * @return QString A string representing the given equation converted to\n   *         postfix format.\n   */  \n  QString InlineCalculator::toPostfix(const QString &equation) const {\n    InlineInfixToPostfix parser;\n    return (parser.convert(equation));\n  }\n \n \n  /**\n   * Determines whether the given string contains a scalar value (i.e. can be\n   * converted to a double precision value).\n   *  \n   * @param scalar A string to be checked.\n   *  \n   * @return bool Indicates whether the given string is a scalar value.\n   */  \n  bool InlineCalculator::isScalar(const QString &scalar) {\n    if (scalar.isEmpty())  return (false);\n    try {\n      toDouble(scalar);\n      return (true);\n    }\n    catch (IException &e) {\n      return (false);\n    }\n  }\n \n\n  /**\n   * Determines whether the given string is a variable. If the string is empty\n   * or scalar, this method returns false. Otherwise, it is assumed to be a\n   * variable and this method returns true.\n   *  \n   * @param str A string to be checked.\n   * @return bool Indicates whether the given string is a variable.\n   */  \n  bool InlineCalculator::isVariable(const QString &str) {\n    if (str.isEmpty()) {\n      return (false);\n    }\n    if (!isScalar(str)) {\n      return (true);\n    }\n    return (false);\n  }\n \n\n  /**\n   * @brief Pushes the given value onto the stack as a scalar.\n   *\n   * This method adds the given variant value to the stack as a scalar.\n   *\n   * @param scalar QVariant containing the scalar. Usually a QString.\n   *  \n   */  \n  void InlineCalculator::scalar(const QVariant &scalar) {\n    Push(toDouble(scalar.toString()));\n  }\n \n\n  /**\n   * @brief Pushes the given value onto the stack as a variable.\n   *\n   * This method adds the given variant value to the stack as a variable.\n   *\n   * @param variable QVariant containing the name of the variable. Usually\n   *                 a QString.\n   *  \n   * @throw IException::User \"Could not find variable in variable pool.\"\n   */  \n  void InlineCalculator::variable(const QVariant &variable) {\n    CalculatorVariablePool *variablePool = variables();\n    QString key = variable.toString();\n    if (variablePool->exists(key)) {\n      QVector<double> values = variablePool->value(key);\n      Push(values);\n      return;\n    }\n \n    // Error!\n    QString error = \"Could not find variable [\" + key + \"] in variable pool.\";\n    throw IException(IException::User, error, _FILEINFO_);\n  }\n \n\n  /**\n   * Determines the remainder of the quotient a/b whose sign is the same as that\n   * of a. In other words, this method finds the value r = a - bq such that q is\n   * the integer found by truncating a/b.\n   *  \n   * @param a The dividend (numerator).\n   * @param b The divisor (denominator).\n   *  \n   * @return double The remainder of the quotient that has the same sign\n   *         as the dividend.\n   */  \n  double floatModulusOperator(double a, double b) {\n    return (fmod(a, b));\n  }\n \n\n  /**\n   * Pops the top two vectors off the current stack and performs the\n   * floatModulusOperator() on the corresponding components of these vectors.\n   * The result is then pushed back onto the stack.\n   */  \n  void InlineCalculator::floatModulus() {\n    QVector<double> y = Pop();\n    QVector<double> x = Pop();\n    QVector<double> result;\n    PerformOperation(result, x.begin(), x.end(), y.begin(), y.end(),\n                     floatModulusOperator);\n    Push(result);\n    return;\n  }\n \n\n  /**\n   * Pops the top vector off the current stack and converts from degrees to\n   * radians. The result is then pushed back onto the stack.\n   */  \n  void InlineCalculator::radians() {\n    QVector<double> degree = Pop();\n    QVector<double> result;\n    BOOST_FOREACH(double d, degree) {\n      result.push_back(d * rpd_c());\n    }\n    Push(result);\n    return;\n  }\n \n\n  /**\n   * Pops the top vector off the current stack and converts from radians to\n   * degrees. The result is then pushed back onto the stack.\n   */  \n  void InlineCalculator::degrees() {\n    QVector<double> radians = Pop();\n    QVector<double> result;\n    BOOST_FOREACH(double r, radians) {\n      result.push_back(r * dpr_c());\n    }\n    Push(result);\n    return;\n  }\n\n\n  /**\n   * Pops the top two vectors off the current stack and performs a logical or\n   * on each pair.\n   * \n   * @throws IException::Unknown \"Failed performing logical or operation, \"\n   *                             \"input vectors are of differnet lengths.\"\n   */\n  void InlineCalculator::logicalOr() {\n    QVector<double> inputA = Pop();\n    QVector<double> inputB = Pop();\n    QVector<double> results;\n    if ( inputA.size() != inputB.size() ) {\n      QString msg = \"Failed performing logical or operation, \"\n                    \"input vectors are of differnet lengths.\";\n      throw IException(IException::Unknown, msg, _FILEINFO_);\n    }\n    for (int i = 0; i < inputA.size(); i++) {\n      results.push_back( inputA[i] || inputB[i] );\n    }\n    Push(results);\n    return;\n  }\n\n\n  /**\n   * Pops the top two vectors off the current stack and performs a logical and\n   * on each pair.\n   * \n   * @throws IException::Unknown \"Failed performing logical and operation, \"\n   *                             \"input vectors are of differnet lengths.\"\n   */\n  void InlineCalculator::logicalAnd() {\n    QVector<double> inputA = Pop();\n    QVector<double> inputB = Pop();\n    QVector<double> results;\n    if ( inputA.size() != inputB.size() ) {\n      QString msg = \"Failed performing logical and operation, \"\n                    \"input vectors are of differnet lengths.\";\n      throw IException(IException::Unknown, msg, _FILEINFO_);\n    }\n    for (int i = 0; i < inputA.size(); i++) {\n      results.push_back( inputA[i] && inputB[i] );\n    }\n    Push(results);\n    return;\n  }\n \n\n  /**\n   * Pushes the PI constant onto the current stack.\n   */  \n  void InlineCalculator::pi() {\n    Push(pi_c());\n    return;\n  }\n \n\n  /**\n   * Pushes the Euler constant (e) onto the current stack.\n   */  \n  void InlineCalculator::eConstant() {\n    Push(E);\n    return;\n  }\n \n\n  /**\n   * Determines whether the given function name exists in the current function\n   * pool.\n   *  \n   * @param fxname A string containing the name of the function we are looking\n   *               for in the pool.\n   *  \n   * @return bool Indicates whether the pool contains the given function.\n   */  \n  bool InlineCalculator::fxExists(const QString &fxname) const {\n    return (m_fxPool.contains(fxname));\n  }\n \n\n  /**\n   * Adds a function to the function pool. Once in the pool, functions cannot\n   * be overwritten. This method will throw an exception if we attempt to add\n   * a function with the same name as one already in the pool.\n   *  \n   * @param function The function type pointer to be added to the pool\n   *  \n   * @return InlineCalculator::FxTypePtr The function type pointer that has been\n   *         added to the pool.\n   * @throw IException::Programmer \"Function operator exists!  Cannot replace\n   *                                existing functions in the pool\"\n   */  \n  InlineCalculator::FxTypePtr InlineCalculator::addFunction(InlineCalculator::FxTypePtr function) {\n    FxTypePtr func = find(function->name());\n    if (!func) {\n      m_fxPool.insert(function->name(), function);\n    }\n    else {\n      QString msg = \"Function operator [\" + function->name() +\n                    \"] exists!  Cannot replace existing functions in the pool :-(\";\n      throw IException(IException::Programmer, msg, _FILEINFO_);\n    }\n    return (function);\n  }\n \n\n  /**\n   * @brief Default token handler if it is undefined during parsing/compilation\n   *  \n   * This method provides the default handling of an undefined token found while\n   * compiling an equation.  Users may code their own handler that, for example,\n   * could provide additional further functionality.\n   *  \n   * If the virtualized reimplementation is unable to process it, it can throw an\n   * exception which will be caught, recorded and compiling will continue until\n   * all tokens are processed.  If the optional implementation cannot handle it,\n   * return false from your version and an exception will be thrown for you.\n   *\n   * @param token Character representation of the token.  This could be an\n   *              undefined constant, function or soemthing else that occurs in\n   *              the equation that is not resolved when this is called.\n   *\n   * @return bool True if it is handled, false if it cannot (which is an error\n   *              and an exception will be invoked).\n   *\n   */\n  bool InlineCalculator::orphanTokenHandler(const QString &token) {\n    return (false);\n  }\n \n \n  /**\n   * Push the given variable pool onto the current variable pool list.\n   *  \n   * @param variablePool A pointer to the CalculatorVariablePool object to be\n   *                     pushed onto the current list.\n   */  \n  void InlineCalculator::pushVariables(CalculatorVariablePool *variablePool) {\n    m_variablePoolList.push_back(variablePool);\n    return;\n  }\n \n\n  /**\n   * Accesses the last variable pool in the current pool list. If the list is\n   * empty, an error will be thrown.\n   *  \n   * @return CalculatorVariablePool The last variable pool in the current list.\n   * @throw IException::Programmer \"Request for nonexistent variable pool.\",\n   */  \n  CalculatorVariablePool *InlineCalculator::variables() {\n    if ( !m_variablePoolList.isEmpty() ) {\n      return (m_variablePoolList.back());\n    }\n    throw IException(IException::Programmer,\n                     \"Request for nonexistent variable pool.\",\n                     _FILEINFO_);\n  }\n \n\n  /**\n   * Removes the last variable pool in the current variable pool list.\n   */  \n  void InlineCalculator::popVariables() {\n    Clear();\n    if ( !m_variablePoolList.isEmpty() ) {\n      m_variablePoolList.pop_back();\n    }\n    return;\n  }\n \n \n  /**\n   * Gets a pointer to the function from the current pool that corresponds\n   * to the given function name. This method returns null if no function\n   * with the given name is found.\n   *\n   * @param fxname A string containing the name of the function to be\n   *               found.\n   * @return InlineCalculator::FxTypePtr A pointer to the corresponding\n   *         function type, if found.\n   */  \n  InlineCalculator::FxTypePtr InlineCalculator::find(const QString &fxname) {\n    FxPoolType::iterator fx = m_fxPool.find(fxname);\n    if ( m_fxPool.end() == fx ) return NULL;\n    return (*fx);\n  }\n \n \n  /**\n   * Adds the recognized functions to the function pool.\n   */  \n  void InlineCalculator::initialize() {\n    //  Set up calculator function lookup list\n    addFunction(new VoidFx(\"^\", &Calculator::Exponent, this));\n    addFunction(new VoidFx(\"/\", &Calculator::Divide, this));\n    addFunction(new VoidFx(\"*\", &Calculator::Multiply, this));\n    addFunction(new VoidFx(\"<<\", &Calculator::LeftShift, this));\n    addFunction(new VoidFx(\">>\", &Calculator::RightShift, this));\n    addFunction(new VoidFx(\"+\", &Calculator::Add, this));\n    addFunction(new VoidFx(\"-\", &Calculator::Subtract, this));\n    addFunction(new VoidFx(\">\", &Calculator::GreaterThan, this));\n    addFunction(new VoidFx(\"<\", &Calculator::LessThan, this));\n    addFunction(new VoidFx(\">=\", &Calculator::GreaterThanOrEqual, this));\n    addFunction(new VoidFx(\"<=\", &Calculator::LessThanOrEqual, this));\n    addFunction(new VoidFx(\"==\", &Calculator::Equal, this));\n    addFunction(new VoidFx(\"!=\", &Calculator::NotEqual, this));\n \n    //  These are not part of the Calculator class because InfixToPostfix didn't\n    //  add/recognize them in the tokenizer.  See InlineInfixToPostfix class which\n    //  is part of this calculator.\n    addFunction(new VoidFx(\"&\", &Calculator::And, this));\n    addFunction(new VoidFx(\"and\", &Calculator::And, this));\n    addFunction(new VoidFx(\"|\", &Calculator::Or, this));\n    addFunction(new VoidFx(\"or\", &Calculator::Or, this));\n    addFunction(new InlineVoidFx(\"%\", &InlineCalculator::floatModulus, this));  \n    addFunction(new VoidFx(\"mod\", &Calculator::Modulus, this));\n    addFunction(new InlineVoidFx(\"fmod\", &InlineCalculator::floatModulus, this));\n     \n    addFunction(new VoidFx(\"--\", &Calculator::Negative, this));\n    addFunction(new VoidFx(\"neg\", &Calculator::Negative, this));  \n \n    addFunction(new VoidFx(\"min\", &Calculator::MinimumPixel, this));\n    addFunction(new VoidFx(\"max\", &Calculator::MaximumPixel, this));\n    addFunction(new VoidFx(\"abs\", &Calculator::AbsoluteValue, this));\n    addFunction(new VoidFx(\"sqrt\", &Calculator::SquareRoot, this));\n    addFunction(new VoidFx(\"log\", &Calculator::Log, this));\n    addFunction(new VoidFx(\"ln\", &Calculator::Log, this));\n    addFunction(new VoidFx(\"log10\", &Calculator::Log10, this));\n    addFunction(new InlineVoidFx(\"pi\", &InlineCalculator::pi, this));\n \n    addFunction(new VoidFx(\"sin\", &Calculator::Sine, this));\n    addFunction(new VoidFx(\"cos\", &Calculator::Cosine, this));\n    addFunction(new VoidFx(\"tan\", &Calculator::Tangent, this));\n    addFunction(new VoidFx(\"sec\", &Calculator::Secant, this));\n    addFunction(new VoidFx(\"csc\", &Calculator::Cosecant, this));\n    addFunction(new VoidFx(\"cot\", &Calculator::Cotangent, this));\n    addFunction(new VoidFx(\"asin\", &Calculator::Arcsine, this));\n    addFunction(new VoidFx(\"acos\", &Calculator::Arccosine, this));\n    addFunction(new VoidFx(\"atan\", &Calculator::Arctangent, this));\n    addFunction(new VoidFx(\"atan2\", &Calculator::Arctangent2, this));\n \n    addFunction(new InlineVoidFx(\"degs\", &InlineCalculator::degrees, this));\n    addFunction(new InlineVoidFx(\"rads\", &InlineCalculator::radians, this));\n    addFunction(new InlineVoidFx(\"e\", &InlineCalculator::eConstant, this));\n    addFunction(new InlineVoidFx(\"||\", &InlineCalculator::logicalOr, this));\n    addFunction(new InlineVoidFx(\"&&\", &InlineCalculator::logicalAnd, this));\n \n    // Add new functions available for inlining\n  //  m_variablePoolList = defaultVariables();\n \n    return;\n  }\n \n\n  /**\n   * Discard of all the function pool and class resources.\n   *\n   */\n  void InlineCalculator::destruct() {\n    BOOST_FOREACH (FxTypePtr function,  m_fxPool) {\n      delete function;\n    }\n \n    m_fxPool.clear();\n    m_functions.clear();\n    return;\n  }\n\n\n  /**\n   * Constructs a CalculatorVariablePool object.\n   */\n  CalculatorVariablePool::CalculatorVariablePool() {\n  }\n\n\n  /**\n   * Destroys the CalculatorVariablePool object.\n   */\n  CalculatorVariablePool::~CalculatorVariablePool() {\n  }\n \n\n  /**\n   * Returns true so the real error can be reported.\n   *  \n   * @param variable A string containing the variable we are looking for.\n   * @return bool True\n   */\n  bool CalculatorVariablePool::exists(const QString &variable) const {\n    return (true);\n  }\n \n\n  /**\n   * Return vector of doubles for Calculator functions.\n   *  \n   * @param variable A string containing the variable.\n   * @param index The location in the pool.\n   *  \n   * @return QVector \\< double \\> A vector of calculator functions.\n   * @throw IException::Programmer \"No implementation in Calculator variable pool to provide\n   *                                value for variable.\"\n   */\n  QVector<double> CalculatorVariablePool::value(const QString &variable,\n                                                const int &index) const {\n    QString mess = \"No implementation in Calculator variable pool to provide \"\n                   \" value for variable [\" + variable + \"].\";\n    throw IException(IException::Programmer, mess, _FILEINFO_);\n  }\n \n\n  /**\n   * Add a parameter to the variable pool.  Some implementations can take\n   * advantage of this if desired but it is not standard.\n   *  \n   * @param key A string containing the name of the parameter to be\n   *            added.\n   * @param values A vector of double precision values to be added to the\n   *               variable pool.\n   *  \n   * @throw IException::Programmer \"No implementation in Calculator variable pool to add\n   *                                value for variable.\"\n   */\n  void CalculatorVariablePool::add(const QString &key, QVector<double> &values) {\n    QString mess = \"No implementation in Calculator variable pool to add \"\n                   \" value for variable [\" + key + \"].\";\n    throw IException(IException::Programmer, mess, _FILEINFO_);\n  }\n\n\n  /**\n   * Constructs a function binder given a name.\n   *  \n   * @param name A string containing a name for this function.\n   */\n  FxBinder::FxBinder(const QString &name) : m_name(name) {\n  }\n\n\n  /**\n   * Destroys the FxBinder object.\n   */\n  FxBinder::~FxBinder() {\n  }\n \n\n  /**\n   * The name assigned to this function binder.\n   *  \n   * @return QString A string containing the name of this function.\n   */\n  QString FxBinder::name() const {\n    return (m_name);\n  }\n \n\n  /**\n   * Executes the function. This method is a wrapper for the virtual dispatch\n   * method.\n   */\n  void FxBinder::execute() {\n    dispatch();\n  }\n \n\n  /**\n   * Executes the function. This method is a wrapper for the virtual dispatch\n   * method.\n   */\n  void FxBinder::operator()() {  \n    dispatch();\n  }\n \n\n  /**\n   * Accesses the arguments for this function. For scalars and variables, the\n   * argument is also the function name.\n   *  \n   * @return QVariant The parameters of this function, as a QVariant.\n   */\n  QVariant FxBinder::args()  {\n    return (QVariant(m_name));\n  }\n \n\n  /**\n   * Constructs an InlineVoid function from the given name, InlineCalculator\n   * operator, and InlineCalculator.\n   *  \n   * @param name A string containing a name for this function.\n   * @param function An InlineCalculator operator that takes no arguments.\n   * @param calculator The InlineCalculator used to evaluate this function.\n   */\n  InlineVoidFx::InlineVoidFx(const QString &name, calcOp function,\n                InlineCalculator *calculator) : FxBinder(name),\n                                                m_func(function),\n                                                m_calc(calculator)  {\n  }\n \n\n  /**\n   * Destroys the InlineVoidFx object.\n   */\n  InlineVoidFx::~InlineVoidFx() {\n  }\n \n\n  /**\n   * Calls the function corresponding to this object using its\n   * stored InlineCalculator and InlineCalculator operator.\n   */\n  void InlineVoidFx::dispatch() {  \n    CALL_MEMBER_FN(*m_calc, m_func)();  \n  }\n   \n   \n  /**\n   * Constructs a Parameter function from the given name (containing the\n   * appropriate parameters), InlineCalculator operator, and\n   * InlineCalculator.\n   *  \n   * @param name A string containing a name for this function. Note: The\n   *             name given should include the parameters to be passed\n   *             into this function.\n   * @param function An InlineCalculator operator that takes parameters.\n   * @param calculator The InlineCalculator used to evaluate this function.\n   */\n  ParameterFx::ParameterFx(const QString &name, calcOp function,\n              InlineCalculator *calculator) : FxBinder(name),\n                                              m_func(function),\n                                              m_calc(calculator){\n  }\n \n\n  /**\n   * Destroys the ParameterFx object.\n   */\n  ParameterFx::~ParameterFx() {\n  }\n \n\n  /**\n   * Calls the function corresponding to this object using its\n   * stored InlineCalculator, InlineCalculator operator, and\n   * arguments.\n   */\n  void ParameterFx::dispatch() {  \n    CALL_MEMBER_FN(*m_calc, m_func)(args());  \n  }\n \n \n  /**\n   * Constructs a Void function from the given name, Calculator operator, and\n   * Calculator.\n   *  \n   * @param name A string containing a name for this function.\n   * @param function A Calculator operator that takes no arguments.\n   * @param calculator The Calculator used to evaluate this function.\n   */\n  VoidFx::VoidFx(const QString &name, calcOp function,\n         InlineCalculator *calculator) : FxBinder(name),\n                                         m_func(function),\n                                         m_calc(calculator)  {\n  }\n \n \n  /**\n   * Destroys the VoidFx object.\n   */\n  VoidFx::~VoidFx() {\n  }\n \n \n  /**\n   * Calls the function corresponding to this object using its stored Calculator\n   * and Calculator operator.\n   */\n  void VoidFx::dispatch() {  \n    CALL_MEMBER_FN(*m_calc, m_func)();  \n  }\n} // namespace Isis\n", "meta": {"hexsha": "8661a689d2b856ac86555ffde3f12b5470c4072a", "size": 27434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isis/src/base/objs/InlineCalculator/InlineCalculator.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/InlineCalculator/InlineCalculator.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/InlineCalculator/InlineCalculator.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.5696202532, "max_line_length": 99, "alphanum_fraction": 0.6412845374, "num_tokens": 6387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776780354463427, "lm_q2_score": 0.03358950335247998, "lm_q1q2_score": 0.009665977601898294}}
{"text": "/// \\file   fund.cpp\n///\n/// \\brief\n///\n/// \\authors    maarten\n/// \\date       2020-01-20\n/// \\copyright  Copyright 2017-2020 The Institute for New Economic Thinking, Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing, 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///             You may obtain instructions to fulfill the attribution requirements in CITATION.cff\n///\n#include \"fund.hpp\"\n\n#include <esl/economics/markets/walras/price_setter.hpp>\n\n#include <esl/economics/markets/walras/quote_message.hpp>\nusing esl::economics::markets::walras::quote_message;\n\nusing esl::law::owner;\nusing namespace esl::economics;\nusing namespace esl::economics::accounting;\nusing namespace esl::economics::finance;\n\n\n\nfund::fund(const identity<fund> &i, const jurisdiction &j)\n: agent(i)\n, law::owner<cash>(i)\n, owner<stock>(i)\n, identifiable_as<fund>()\n, company(i,j)\n, lookup_(primary_jurisdiction.tender)\n, reset_amount(1.00, currencies::USD)\n{\n    output_net_asset_value  = create_output<price>(\"net_asset_value\");\n    output_signal           = create_output<double>(\"signal\");\n    output_cash             = create_output<price>(\"cash\");\n    output_stocks           = create_output<price>(\"stocks\");\n    output_loans            = create_output<price>(\"loans\");\n    output_lending          = create_output<price>(\"lending\");\n    output_pnl              = create_output<price>(\"pnl\");\n\n    auto invest_ = [this](auto msg, simulation::time_interval ti, std::seed_seq &seed) {\n        return invest(msg, ti, seed);\n    };\n\n    ESL_REGISTER_CALLBACK(quote_message, -100, invest_, \"make investment decisions\");\n\n    auto process_dividends_ = [this](std::shared_ptr<dividend_announcement_message> m,\n            simulation::time_interval step,\n            std::seed_seq &) {\n\n        for(const auto &[share_, sharedetails_] : m->policy.dividend_per_share){\n            std::tuple<identity<company>, share_class> key_ =\n                    {esl::reinterpret_identity_cast<company>(m->sender), share_};\n\n            auto iterator_ = stocks.find(key_);\n            if (stocks.end() == iterator_){\n                LOG(warning) << \"fund.cpp(\" << __LINE__ << \") fund receives info about stock it is not tracking\" << std::endl;\n            }else{\n                identity<property> stock_ = iterator_->second;\n                market_data.shares_outstanding[stock_] = std::get<0>(sharedetails_);\n\n                uint64_t stocks_ = 0;\n                for(const auto& s: owner<stock>::inventory){\n                    if(s.first->identifier == stock_){\n                        stocks_ += s.second.amount;\n                    }\n                }\n\n                auto dps_ = std::get<1>(sharedetails_);\n                auto usd_ = std::make_shared<cash>(currencies::USD);\n                auto [i, b] = owner<cash>::inventory.emplace(usd_, quantity(0));\n\n                /// TODO: this needs to be moved someplace else\n                auto dividend_received_ = uint64_t((stocks_ * dps_.value * (1.+risk_free_rate)) /  std::get<0>(sharedetails_));\n                i->second.amount += dividend_received_;\n\n                for(auto [p, q]: owner<securities_lending_contract>::properties.items){\n                    if(p->security == stock_){\n                        auto pay_on_short_ = uint64_t((q.amount * dps_.value * (1.+risk_free_rate)) / std::get<0>(sharedetails_));\n\n                        if(i->second.amount < pay_on_short_){\n                            LOG(trace) << \"pay \" << pay_on_short_ << \" to fund short position \" << std::endl;\n                            throw std::invalid_argument(\"out of cash \" + identifier.representation());\n                        }\n                        i->second.amount -= pay_on_short_;\n                    }\n                }\n\n                if(market_data.dividend_per_share.end() == market_data.dividend_per_share.find(stock_)){\n                    market_data.dividend_per_share.insert(std::make_pair(stock_,std::get<1>(sharedetails_)));\n                }else{\n                    market_data.dividend_per_share[stock_].value = std::get<1>(sharedetails_).value;\n                }\n            }\n        }\n        return step.upper;\n    };\n\n    ESL_REGISTER_CALLBACK(quote_message, 16, [&](std::shared_ptr<quote_message> m, simulation::time_interval ti, std::seed_seq &s){\n\n        for(auto [property_, quote_]: m->proposed) {\n            auto price_ = std::get<price>(quote_.type);\n            lookup_.mark_to_market.erase(property_->identifier);\n            auto i = lookup_.mark_to_market.emplace(property_->identifier, price_);\n        }\n\n        return ti.upper;\n        }, \"update prices\");\n\n    ESL_REGISTER_CALLBACK(dividend_announcement_message, 0, process_dividends_, \"process dividend announcement and store dividends\")\n}\n\ntemplate<typename T>\nprice valuate(const esl::law::property_map<quantity> &inventory, const standard &s)\n{\n    price value_ = price::approximate(0.00, s.reporting_currency);\n    for(const auto &[p,q]: inventory){\n        auto cast_ = std::dynamic_pointer_cast<T>(p);\n        if(cast_){\n            value_ += s.value(*cast_, q);\n        }\n    }\n    return value_;\n}\n\n\n///\n/// If we are re-setting wealth in an experiment then\n/// `target_net_asset_value` is set to the value that we reset wealth to.\n/// `target_date` determines the last date on which we reset, for example\n/// in experiments where we always reset it is set to 200 years\n///\nvoid fund::reset_wealth(price &net_asset_value_, simulation::time_interval ti)\n{\n    // if the target NAV rule does not apply, exit\n    // if we are no longer resetting, exit\n    if(!target_net_asset_value.has_value() || double(target_net_asset_value.value()) <= 0. || ti.lower > target_date){\n        if(! output_net_asset_value->values.empty() ){\n            auto pnl = net_asset_value_ - std::get<1>( output_net_asset_value->values.back() );\n            output_pnl->put(ti.lower, pnl);\n        }\n        return;\n    }\n\n    // bailout as a fraction of assets and liabilities\n    double bailout_ratio = double(target_net_asset_value.value()) / double(net_asset_value_);\n\n    //std::cout << this->describe() << \" bailout_ratio \" << std::setprecision(5) << bailout_ratio << \" (\" << target_net_asset_value.value() << \" / \" << net_asset_value_ << \")\" <<std::endl;\n    // bailout monetary amount\n    auto bailout_ = price::approximate((double(target_net_asset_value.value()) - double(net_asset_value_)), currencies::USD);\n    auto remainder_ = bailout_.value;\n\n    output_pnl->put(ti.lower, -bailout_);\n\n\n\n    for(auto &[p, q]: inventory) {\n        auto cast_ = std::dynamic_pointer_cast<loan>(p);\n        if(cast_) {\n            if(remainder_ > 0) {\n                auto dec = std::min<std::uint64_t>(inventory[p].amount, remainder_ / 100);\n                inventory[p].amount -= dec;  // std::uint64_t(inventory[p].amount * bailout_ratio);\n                remainder_ -= dec;\n            } else if(remainder_ < 0) {\n                inventory[p].amount += (-remainder_/ 100);  // std::uint64_t(inventory[p].amount * bailout_ratio);\n                remainder_ = 0;\n            }\n        }\n    }\n\n    if(remainder_){\n\n        for(auto &[p, q]: inventory) {\n            auto cast_ = std::dynamic_pointer_cast<cash>(p);\n            if(cast_){\n                if(remainder_ < 0){\n                    auto dec = std::min<std::uint64_t>(inventory[p].amount, -remainder_);\n                    inventory[p].amount -= dec;//std::uint64_t(inventory[p].amount * bailout_ratio);\n                    remainder_ += dec;\n                }else if(remainder_ > 0){\n                    inventory[p].amount += remainder_;//std::uint64_t(inventory[p].amount * bailout_ratio);\n                    remainder_ = 0;\n                }\n            }\n        }\n\n\n\n    }\n\n\n\n    if(remainder_){\n        for(auto &[p, q]: inventory) {\n            auto cast_ = std::dynamic_pointer_cast<stock>(p);\n            if(cast_){\n                auto i = lookup_.mark_to_market.find(p->identifier);\n                if(lookup_.mark_to_market.end() == i){\n                    continue;\n                }\n                auto change_ = remainder_ / std::get<price>(i->second.type).value;\n                if(change_ < 0){\n                    auto dec = std::min<std::uint64_t>(inventory[p].amount, -change_);\n                    inventory[p].amount -= dec;//std::uint64_t(inventory[p].amount * bailout_ratio);\n                    remainder_ += change_ * std::get<price>(i->second.type).value;\n                }else if(change_ > 0){\n                    inventory[p].amount += change_;//std::uint64_t(inventory[p].amount * bailout_ratio);\n                    remainder_ = 0;\n                }\n            }\n\n\n        }\n    }\n}\n\n\nvoid fund::apply_reinvestment(price &net_asset_value_, simulation::time_interval ti)\n{\n    ///\n    /// \\brief  This section relates to the reinvestment rate experiments,\n    ///         where we introduce (unseen) retail investors that\n    ///         invest based on the performance of the fund\n    ///\n    if(previous_net_asset_value.has_value() && reinvestment_rate != 1.){\n        double returns_ =  double(net_asset_value_) / previous_net_asset_value.value() - 1;\n        double compound_returns_f_ = std::pow(1 + returns_, reinvestment_rate - 1) - 1;\n\n        //std::cout <<\"returns: \" << returns_ << \" compounded \" << compound_returns_f_ << std::endl;\n\n        // OLD rule matching papers\n        //int64_t change_ = static_cast<int64_t>(round(  (reinvestment_rate -1.) * (double(net_asset_value_) - previous_net_asset_value.value()) ));\n        // new rule\n\n        double change_ = compound_returns_f_ * double(net_asset_value_);\n\n        for(auto &[p, q]: inventory){\n            auto cast_ = std::dynamic_pointer_cast<cash>(p);\n            if(cast_){\n                net_asset_value_ += price::approximate(change_, net_asset_value_.valuation);\n                auto qchange_ = std::max<int64_t>(-((int64_t)inventory[p].amount), int64_t(change_ * 100) );\n                inventory[p].amount += qchange_;\n            }\n        }\n    }\n\n}\n\n\nprice fund::net_asset_value(esl::simulation::time_interval ti)\n{\n    for(auto p: shareholder::prices){\n        lookup_.mark_to_market.emplace(p.first->identifier, p.second);\n    }\n\n    for(auto p: bond_prices){\n        lookup_.mark_to_market.emplace(p.first->identifier, p.second);\n    }\n\n    for(auto p: owner<stock>::properties.items){\n        if(lookup_.mark_to_market.end() == lookup_.mark_to_market.find(p.first->identifier)){\n            lookup_.mark_to_market.emplace(p.first->identifier, price::approximate(100.00, currencies::USD));\n        }\n    }\n\n    auto cash1_ = valuate<cash>(inventory, lookup_);\n    auto stocks_ = valuate<stock>(inventory, lookup_);\n    output_stocks->put(ti.lower, stocks_);\n\n    auto loans_value_ = valuate<loan>(inventory, lookup_);\n    auto loans_ = price::approximate(double(loans_value_) * (1.+risk_free_rate), loans_value_.valuation);\n    output_loans->put(ti.lower, loans_);\n\n    auto lending_ = valuate<securities_lending_contract>(inventory, lookup_);\n    output_lending->put(ti.lower, lending_);\n    auto cash_ = price::approximate(double(cash1_) * (1.+risk_free_rate), cash1_.valuation);\n    auto net_asset_value_ = cash_ + stocks_ + lending_ + loans_;\n\n    output_cash->put(ti.lower, cash_);\n    net_asset_value_ = cash_ + stocks_ + lending_ + loans_;\n\n    if(ti.lower > target_date) {\n        apply_reinvestment(net_asset_value_, ti);\n    }\n\n    reset_wealth(net_asset_value_, ti);\n    previous_net_asset_value = double(net_asset_value_);\n\n    output_net_asset_value->put(ti.lower, net_asset_value_);\n    return net_asset_value_;\n}\n\ntime_point fund::act(time_interval interval, std::seed_seq &s)\n{\n    (void)s;\n    return interval.upper;\n}\n\n#include <boost/serialization/export.hpp>\nBOOST_CLASS_EXPORT(esl::data::output<esl::economics::price>);", "meta": {"hexsha": "2416d73a53f62a7f9dcb70edcf4e509617d0ec95", "size": 12439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fund.cpp", "max_stars_repo_name": "maartenscholl/C-Multi_Asset_Artificial_Stock_Market", "max_stars_repo_head_hexsha": "6c2637b53b0b79cee1d13baf928c949f28625954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T19:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T19:07:57.000Z", "max_issues_repo_path": "fund.cpp", "max_issues_repo_name": "maartenscholl/C-Multi_Asset_Artificial_Stock_Market", "max_issues_repo_head_hexsha": "6c2637b53b0b79cee1d13baf928c949f28625954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fund.cpp", "max_forks_repo_name": "maartenscholl/C-Multi_Asset_Artificial_Stock_Market", "max_forks_repo_head_hexsha": "6c2637b53b0b79cee1d13baf928c949f28625954", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7412140575, "max_line_length": 188, "alphanum_fraction": 0.6066404052, "num_tokens": 2881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.02800752344557882, "lm_q1q2_score": 0.009665543967545443}}
{"text": "/**\nBSD 3-Clause License\n\nThis file is part of the RootBA project.\nhttps://github.com/NikolausDemmel/rootba\n\nCopyright (c) 2021, Nikolaus Demmel.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n#pragma once\n\n#include <fstream>\n\n#include <Eigen/Dense>\n\n#include \"rootba/bal/bal_bundle_adjustment_helper.hpp\"\n#include \"rootba/bal/bal_problem.hpp\"\n#include \"rootba/bal/bal_residual_options.hpp\"\n#include \"rootba/cg/block_sparse_matrix.hpp\"\n#include \"rootba/util/assert.hpp\"\n#include \"rootba/util/format.hpp\"\n\nnamespace rootba {\n\ntemplate <typename Scalar, int POSE_SIZE>\nclass LandmarkBlockSC {\n public:\n  struct Options {\n    // use Householder instead of Givens for marginalization\n    bool use_householder = true;\n\n    // use_valid_projections_only: if true, set invalid projection's\n    // residual and jacobian to 0; invalid means z <= 0\n    bool use_valid_projections_only = true;\n\n    // huber norm with given threshold, else squared norm\n    BalResidualOptions residual_options;\n\n    // ceres uses 1.0 / (1.0 + sqrt(SquaredColumnNorm))\n    // we use 1.0 / (eps + sqrt(SquaredColumnNorm))\n    Scalar jacobi_scaling_eps = 1.0;\n  };\n\n  enum State { UNINITIALIZED = 0, ALLOCATED, NUMERICAL_FAILURE, LINEARIZED };\n\n  inline bool is_numerical_failure() const {\n    return state_ == NUMERICAL_FAILURE;\n  }\n\n  using Vec2 = Eigen::Matrix<Scalar, 2, 1>;\n  using Vec3 = Eigen::Matrix<Scalar, 3, 1>;\n  using Vec4 = Eigen::Matrix<Scalar, 4, 1>;\n\n  using VecX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n  using Mat3 = Eigen::Matrix<Scalar, 3, 3>;\n  using Mat36 = Eigen::Matrix<Scalar, 3, 6>;\n\n  using MatX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n  using RowMatX =\n      Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n  using Landmark = typename BalProblem<Scalar>::Landmark;\n  using Camera = typename BalProblem<Scalar>::Camera;\n  using Landmarks = typename BalProblem<Scalar>::Landmarks;\n  using Cameras = typename BalProblem<Scalar>::Cameras;\n\n  inline void allocate_landmark(Landmark& lm, const Options& options) {\n    options_ = options;\n\n    pose_idx_.clear();\n    pose_idx_.reserve(lm.obs.size());\n    for (const auto& [cam_idx, obs] : lm.obs) {\n      pose_idx_.push_back(cam_idx);\n    }\n\n    num_rows_ = pose_idx_.size() * 2;\n\n    lm_idx_ = POSE_SIZE;\n    res_idx_ = lm_idx_ + 3;\n    num_cols_ = res_idx_ + 1;\n\n    storage_.resize(num_rows_, num_cols_);\n\n    state_ = ALLOCATED;\n\n    lm_ptr_ = &lm;\n  }\n\n  // may set state to NumericalFailure --> linearization at this state is\n  // unusable. Numeric check is only performed for residuals that were\n  // considered to be used (valid), which depends on use_valid_projections_only\n  // setting.\n  inline void linearize_landmark(const Cameras& cameras) {\n    ROOTBA_ASSERT(state_ == ALLOCATED || state_ == NUMERICAL_FAILURE ||\n                  state_ == LINEARIZED);\n\n    storage_.setZero(num_rows_, num_cols_);\n\n    bool numerically_valid = true;\n\n    for (size_t i = 0; i < pose_idx_.size(); i++) {\n      size_t cam_idx = pose_idx_[i];\n      size_t obs_idx = i * 2;\n      size_t pose_idx = 0;\n\n      const auto& obs = lm_ptr_->obs.at(cam_idx);\n      const auto& cam = cameras.at(cam_idx);\n\n      typename BalBundleAdjustmentHelper<Scalar>::MatRP Jp;\n      typename BalBundleAdjustmentHelper<Scalar>::MatRI Ji;\n      typename BalBundleAdjustmentHelper<Scalar>::MatRL Jl;\n\n      Vec2 res;\n      const bool valid = BalBundleAdjustmentHelper<Scalar>::linearize_point(\n          obs.pos, lm_ptr_->p_w, cam.T_c_w, cam.intrinsics, true, res, &Jp, &Ji,\n          &Jl);\n\n      if (!options_.use_valid_projections_only || valid) {\n        numerically_valid = numerically_valid && Jl.array().isFinite().all() &&\n                            Jp.array().isFinite().all() &&\n                            Ji.array().isFinite().all() &&\n                            res.array().isFinite().all();\n\n        const Scalar res_squared = res.squaredNorm();\n        const auto [weighted_error, weight] =\n            BalBundleAdjustmentHelper<Scalar>::compute_error_weight(\n                options_.residual_options, res_squared);\n        const Scalar sqrt_weight = std::sqrt(weight);\n\n        storage_.template block<2, 6>(obs_idx, pose_idx) = sqrt_weight * Jp;\n        storage_.template block<2, 3>(obs_idx, pose_idx + 6) = sqrt_weight * Ji;\n        storage_.template block<2, 3>(obs_idx, lm_idx_) = sqrt_weight * Jl;\n        storage_.template block<2, 1>(obs_idx, res_idx_) = sqrt_weight * res;\n      }\n    }\n\n    if (numerically_valid) {\n      state_ = LINEARIZED;\n    } else {\n      state_ = NUMERICAL_FAILURE;\n    }\n  }\n\n  inline void add_Jp_diag2(VecX& res) const {\n    ROOTBA_ASSERT(state_ == LINEARIZED);\n\n    for (size_t i = 0; i < pose_idx_.size(); i++) {\n      size_t cam_idx = pose_idx_[i];\n      res.template segment<POSE_SIZE>(POSE_SIZE * cam_idx) +=\n          storage_.template block<2, POSE_SIZE>(2 * i, 0)\n              .colwise()\n              .squaredNorm();\n    }\n  }\n\n  inline void scale_Jl_cols() {\n    ROOTBA_ASSERT(state_ == LINEARIZED);\n\n    // ceres uses 1.0 / (1.0 + sqrt(SquaredColumnNorm))\n    // we use 1.0 / (eps + sqrt(SquaredColumnNorm))\n    Jl_col_scale =\n        (options_.jacobi_scaling_eps +\n         storage_.block(0, lm_idx_, num_rows_, 3).colwise().norm().array())\n            .inverse();\n\n    storage_.block(0, lm_idx_, num_rows_, 3) *= Jl_col_scale.asDiagonal();\n  }\n\n  inline void scale_Jp_cols(const VecX& jacobian_scaling) {\n    ROOTBA_ASSERT(state_ == LINEARIZED);\n\n    for (size_t i = 0; i < pose_idx_.size(); i++) {\n      size_t cam_idx = pose_idx_[i];\n\n      storage_.template block<2, POSE_SIZE>(2 * i, 0) *=\n          jacobian_scaling.template segment<POSE_SIZE>(POSE_SIZE * cam_idx)\n              .asDiagonal();\n    }\n  }\n\n  inline State get_state() const { return state_; }\n\n  inline void set_landmark_damping(Scalar lambda) { lambda_ = lambda; }\n\n  // Fill the reduced H, b linear system.\n  inline void add_Hb(BlockSparseMatrix<Scalar>& accu, VecX& b) const {\n    ROOTBA_ASSERT(state_ == LINEARIZED);\n\n    // Compute landmark-landmark block plus inverse\n    Mat3 H_ll;\n    Mat3 H_ll_inv;\n    Vec3 H_ll_inv_bl;\n    {\n      auto Jl = storage_.block(0, lm_idx_, num_rows_, 3);\n      H_ll = Jl.transpose() * Jl;\n      H_ll.diagonal().array() += lambda_;\n      H_ll_inv = H_ll.inverse();\n\n      H_ll_inv_bl = H_ll_inv * Jl.transpose() * storage_.col(res_idx_);\n    }\n\n    // Add pose-pose blocks and\n    for (size_t i = 0; i < pose_idx_.size(); i++) {\n      size_t cam_idx_i = pose_idx_[i];\n\n      auto Jp_i = storage_.template block<2, POSE_SIZE>(2 * i, 0);\n      auto Jl_i = storage_.template block<2, 3>(2 * i, lm_idx_);\n      auto r_i = storage_.template block<2, 1>(2 * i, res_idx_);\n\n      MatX H_pp = Jp_i.transpose() * Jp_i;\n      accu.add(cam_idx_i, cam_idx_i, std::move(H_pp));\n\n      // Schur complement blocks\n      for (size_t j = 0; j < pose_idx_.size(); j++) {\n        size_t cam_idx_j = pose_idx_[j];\n        auto Jp_j = storage_.template block<2, POSE_SIZE>(2 * j, 0);\n        auto Jl_j = storage_.template block<2, 3>(2 * j, lm_idx_);\n\n        MatX H_pl_H_ll_inv_H_lp =\n            -Jp_i.transpose() * Jl_i * H_ll_inv * Jl_j.transpose() * Jp_j;\n\n        accu.add(cam_idx_i, cam_idx_j, std::move(H_pl_H_ll_inv_H_lp));\n      }\n\n      // add blocks to b\n      b.template segment<POSE_SIZE>(cam_idx_i * POSE_SIZE) +=\n          Jp_i.transpose() * (r_i - Jl_i * H_ll_inv_bl);\n    }\n  }\n\n  void back_substitute(const VecX& pose_inc, Scalar& l_diff) {\n    ROOTBA_ASSERT(state_ == LINEARIZED);\n\n    Mat3 H_ll = Mat3::Zero();\n    Vec3 tmp = Vec3::Zero();\n    VecX J_inc;\n    J_inc.setZero(num_rows_);\n\n    // Add pose-pose blocks and\n    for (size_t i = 0; i < pose_idx_.size(); i++) {\n      size_t cam_idx_i = pose_idx_[i];\n\n      auto Jp_i = storage_.template block<2, POSE_SIZE>(2 * i, 0);\n      auto Jl_i = storage_.template block<2, 3>(2 * i, lm_idx_);\n      auto r_i = storage_.template block<2, 1>(2 * i, res_idx_);\n\n      H_ll += Jl_i.transpose() * Jl_i;\n\n      auto p_inc = pose_inc.template segment<POSE_SIZE>(cam_idx_i * POSE_SIZE);\n\n      tmp += Jl_i.transpose() * (r_i + Jp_i * p_inc);\n      J_inc.template segment<2>(2 * i) += Jp_i * p_inc;\n    }\n\n    // TODO: store additionally \"Hllinv\" (inverted with lambda), so we don't\n    // need lambda in the interface\n    H_ll.diagonal().array() += lambda_;\n    Vec3 inc = -H_ll.inverse() * tmp;\n\n    // Add landmark jacobian cost change\n    J_inc += storage_.block(0, lm_idx_, num_rows_, 3) * inc;\n\n    l_diff -= J_inc.transpose() * (0.5 * J_inc + storage_.col(res_idx_));\n\n    // Note: scale only after computing model cost change\n    inc.array() *= Jl_col_scale.array();\n    lm_ptr_->p_w += inc;\n  }\n\n  void print_storage(const std::string& filename) const {\n    std::ofstream f(filename);\n\n    Eigen::IOFormat clean_fmt(4, 0, \" \", \"\\n\", \"\", \"\");\n\n    f << \"Storage (state: \" << state_\n      << \" Jl_col_scale: \" << Jl_col_scale.transpose() << \"):\\n\"\n      << storage_.format(clean_fmt) << std::endl;\n\n    f.close();\n  }\n\n protected:\n  // Dense storage for pose Jacobians, padding, landmark Jacobians and\n  // residuals [J_p (all jacobians in one column) | J_l | res]\n  Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      storage_;\n\n  Vec3 Jl_col_scale;\n  Scalar lambda_ = 0;\n\n  std::vector<size_t> pose_idx_;\n  size_t lm_idx_ = 0;\n  size_t res_idx_ = 0;\n\n  size_t num_cols_ = 0;\n  size_t num_rows_ = 0;\n\n  Options options_;\n\n  State state_ = UNINITIALIZED;\n\n  Landmark* lm_ptr_ = nullptr;\n};\n\n}  // namespace rootba\n", "meta": {"hexsha": "06f8d3378b3409edb1dde720099454c4e654bfcd", "size": 10939, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rootba/sc/landmark_block.hpp", "max_stars_repo_name": "zeta1999/rootba", "max_stars_repo_head_hexsha": "d1a680a88980d7ac57cf2ff7459d00ac1cab6c9a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2021-06-20T17:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:15:38.000Z", "max_issues_repo_path": "src/rootba/sc/landmark_block.hpp", "max_issues_repo_name": "zeta1999/rootba", "max_issues_repo_head_hexsha": "d1a680a88980d7ac57cf2ff7459d00ac1cab6c9a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-07-10T11:51:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T00:05:39.000Z", "max_forks_repo_path": "src/rootba/sc/landmark_block.hpp", "max_forks_repo_name": "NikolausDemmel/rootba", "max_forks_repo_head_hexsha": "0762f36a0afa7196709bd0fa147ae75ee7c7632c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T03:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:41:54.000Z", "avg_line_length": 32.8498498498, "max_line_length": 80, "alphanum_fraction": 0.6645031539, "num_tokens": 2988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.028007521924369488, "lm_q1q2_score": 0.009665543819860331}}
{"text": "/*\n\nCopyright (c) 2010--2011, Stephane Magnenat, ASL, ETHZ, Switzerland\nYou can contact the author at <stephane at magnenat dot net>\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * 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 <organization> 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL ETH-ASL BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n#include \"stdafx.h\"\n#include \"nabo_private.h\"\n#include \"index_heap.h\"\n#include <iostream>\n#include <stdexcept>\n#include <limits>\n#include <queue>\n#include <algorithm>\n#include <utility>\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/limits.hpp>\n#include <boost/format.hpp>\n#ifdef HAVE_OPENMP\n#include <omp.h>\n#endif\n\n/*!\t\\file kdtree_cpu.cpp\n\t\\brief kd-tree search, cpu implementation\n\t\\ingroup private\n*/\n\nnamespace Nabo\n{\n\t//! \\ingroup private\n\t//@{\n\t\n\tusing namespace std;\n\t\n\t//! Return the number of bit required to store a value\n\t/** \\param v value to store\n\t * \\return number of bits required\n\t */\n\ttemplate<typename T>\n\tT getStorageBitCount(T v)\n\t{\n\t\tfor (T i = 0; i < 64; ++i)\n\t\t{\n\t\t\tif (v == 0)\n\t\t\t\treturn i;\n\t\t\tv >>= 1;\n\t\t}\n\t\treturn 64;\n\t}\n\t\n\t//! Return the index of the maximum value of a vector of positive values\n\t/** \\param v vector of positive values\n\t * \\return index of maximum value, 0 if the vector is empty\n\t */\n\ttemplate<typename T, typename CloudType>\n\tsize_t argMax(const typename NearestNeighbourSearch<T, CloudType>::Vector& v)\n\t{\n\t\tT maxVal(0);\n\t\tsize_t maxIdx(0);\n\t\tfor (int i = 0; i < v.size(); ++i)\n\t\t{\n\t\t\tif (v[i] > maxVal)\n\t\t\t{\n\t\t\t\tmaxVal = v[i];\n\t\t\t\tmaxIdx = i;\n\t\t\t}\n\t\t}\n\t\treturn maxIdx;\n\t}\n\t\n\t// OPT\n\ttemplate<typename T, typename Heap, typename CloudType>\n\tpair<T,T> KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, Heap, CloudType>::getBounds(const BuildPointsIt first, const BuildPointsIt last, const unsigned dim)\n\t{\n\t\tT minVal(boost::numeric::bounds<T>::highest());\n\t\tT maxVal(boost::numeric::bounds<T>::lowest());\n\t\t\n\t\tfor (BuildPointsCstIt it(first); it != last; ++it)\n\t\t{\n\t\t\tconst T val(cloud.coeff(dim, *it));\n\t\t\tminVal = min(val, minVal);\n\t\t\tmaxVal = max(val, maxVal);\n\t\t}\n\t\t\n\t\treturn make_pair(minVal, maxVal);\n\t}\n\t\n\ttemplate<typename T, typename Heap, typename CloudType>\n\tunsigned KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, Heap, CloudType>::buildNodes(const BuildPointsIt first, const BuildPointsIt last, const Vector minValues, const Vector maxValues)\n\t{\n\t\tconst int count(last - first);\n\t\tassert(count >= 1);\n\t\tconst unsigned pos(nodes.size());\n\t\t\n\t\t//cerr << count << endl;\n\t\tif (count <= int(bucketSize))\n\t\t{\n\t\t\tconst uint32_t initBucketsSize(buckets.size());\n\t\t\t//cerr << \"creating bucket with \" << count << \" values\" << endl;\n\t\t\tfor (int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tconst Index index(*(first+i));\n\t\t\t\tassert(index < cloud.cols());\n\t\t\t\tbuckets.push_back(BucketEntry(&cloud.coeff(0, index), index));\n\t\t\t\t//cerr << \"  \" << &cloud.coeff(0, index) << \", \" << index << endl;\n\t\t\t}\n\t\t\t//cerr << \"at address \" << bucketStart << endl;\n\t\t\tnodes.push_back(Node(createDimChildBucketSize(dim, count),initBucketsSize));\n\t\t\treturn pos;\n\t\t}\n\t\t\n\t\t// find the largest dimension of the box\n\t\tconst unsigned cutDim = argMax<T, CloudType>(maxValues - minValues);\n\t\tconst T idealCutVal((maxValues(cutDim) + minValues(cutDim))/2);\n\t\t\n\t\t// get bounds from actual points\n\t\tconst pair<T,T> minMaxVals(getBounds(first, last, cutDim));\n\t\t\n\t\t// correct cut following bounds\n\t\tT cutVal;\n\t\tif (idealCutVal < minMaxVals.first)\n\t\t\tcutVal = minMaxVals.first;\n\t\telse if (idealCutVal > minMaxVals.second)\n\t\t\tcutVal = minMaxVals.second;\n\t\telse\n\t\t\tcutVal = idealCutVal;\n\t\t\n\t\tint l(0);\n\t\tint r(count-1);\n\t\t// partition points around cutVal\n\t\twhile (1)\n\t\t{\n\t\t\twhile (l < count && cloud.coeff(cutDim, *(first+l)) < cutVal)\n\t\t\t\t++l;\n\t\t\twhile (r >= 0 && cloud.coeff(cutDim, *(first+r)) >= cutVal)\n\t\t\t\t--r;\n\t\t\tif (l > r)\n\t\t\t\tbreak;\n\t\t\tswap(*(first+l), *(first+r));\n\t\t\t++l; --r;\n\t\t}\n\t\tconst int br1 = l;\t// now: points[0..br1-1] < cutVal <= points[br1..count-1]\n\t\tr = count-1;\n\t\t// partition points[br1..count-1] around cutVal\n\t\twhile (1)\n\t\t{\n\t\t\twhile (l < count && cloud.coeff(cutDim, *(first+l)) <= cutVal)\n\t\t\t\t++l;\n\t\t\twhile (r >= br1 && cloud.coeff(cutDim, *(first+r)) > cutVal)\n\t\t\t\t--r;\n\t\t\tif (l > r)\n\t\t\t\tbreak;\n\t\t\tswap(*(first+l), *(first+r));\n\t\t\t++l; --r;\n\t\t}\n\t\tconst int br2 = l; // now: points[br1..br2-1] == cutVal < points[br2..count-1]\n\t\t\n\t\t// find best split index\n\t\tint leftCount;\n\t\tif (idealCutVal < minMaxVals.first)\n\t\t\tleftCount = 1;\n\t\telse if (idealCutVal > minMaxVals.second)\n\t\t\tleftCount = count-1;\n\t\telse if (br1 > count / 2)\n\t\t\tleftCount = br1;\n\t\telse if (br2 < count / 2)\n\t\t\tleftCount = br2;\n\t\telse\n\t\t\tleftCount = count / 2;\n\t\tassert(leftCount > 0);\n\t\t/*if (leftCount >= count)\n\t\t{\n\t\t\tcerr << \"Error found in kdtree:\" << endl;\n\t\t\tcerr << \"cloud size: \" << cloud.cols() << endl;\n\t\t\tcerr << \"count:\" << count << endl;\n\t\t\tcerr << \"leftCount: \" << leftCount << endl;\n\t\t\tcerr << \"br1: \" << br1 << endl;\n\t\t\tcerr << \"br2: \" << br2 << endl;\n\t\t\tcerr << \"idealCutVal: \" << idealCutVal << endl;\n\t\t\tcerr << \"cutVal: \" << cutVal << endl;\n\t\t\tcerr << \"minMaxVals.first: \" << minMaxVals.first << endl;\n\t\t\tcerr << \"minMaxVals.second: \" << minMaxVals.second << endl;\n\t\t}*/\n\t\tassert(leftCount < count);\n\t\t\n\t\t// update bounds for left\n\t\tVector leftMaxValues(maxValues);\n\t\tleftMaxValues[cutDim] = cutVal;\n\t\t// update bounds for right\n\t\tVector rightMinValues(minValues);\n\t\trightMinValues[cutDim] = cutVal;\n\t\t\n\t\t// add this\n\t\tnodes.push_back(Node(0, cutVal));\n\t\t\n\t\t// recurse\n\t\tconst unsigned _UNUSED leftChild = buildNodes(first, first + leftCount, minValues, leftMaxValues);\n\t\tassert(leftChild == pos + 1);\n\t\tconst unsigned rightChild = buildNodes(first + leftCount, last, rightMinValues, maxValues);\n\t\t\n\t\t// write right child index and return\n\t\tnodes[pos].dimChildBucketSize = createDimChildBucketSize(cutDim, rightChild);\n\t\treturn pos;\n\t}\n\n\ttemplate<typename T, typename Heap, typename CloudType>\n\tKDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, Heap, CloudType>::KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt(const CloudType& cloud, const Index dim, const unsigned creationOptionFlags, const Parameters& additionalParameters):\n\t\tNearestNeighbourSearch<T, CloudType>::NearestNeighbourSearch(cloud, dim, creationOptionFlags),\n\t\tbucketSize(additionalParameters.get<unsigned>(\"bucketSize\", 8)),\n\t\tdimBitCount(getStorageBitCount<uint32_t>(this->dim)),\n\t\tdimMask((1<<dimBitCount)-1)\n\t{\n\t\tif (bucketSize < 2)\n\t\t\tthrow runtime_error((boost::format(\"Requested bucket size %1%, but must be larger than 2\") % bucketSize).str());\n\t\tif (cloud.cols() <= bucketSize)\n\t\t{\n\t\t\t// make a single-bucket tree\n\t\t\tfor (int i = 0; i < cloud.cols(); ++i)\n\t\t\t\tbuckets.push_back(BucketEntry(&cloud.coeff(0, i), i));\n\t\t\tnodes.push_back(Node(createDimChildBucketSize(this->dim, cloud.cols()),uint32_t(0)));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tconst uint64_t maxNodeCount((0x1ULL << (32-dimBitCount)) - 1);\n\t\tconst uint64_t estimatedNodeCount(cloud.cols() / (bucketSize / 2));\n\t\tif (estimatedNodeCount > maxNodeCount)\n\t\t{\n\t\t\tthrow runtime_error((boost::format(\"Cloud has a risk to have more nodes (%1%) than the kd-tree allows (%2%). The kd-tree has %3% bits for dimensions and %4% bits for node indices\") % estimatedNodeCount % maxNodeCount % dimBitCount % (32-dimBitCount)).str());\n\t\t}\n\t\t\n\t\t// build point vector and compute bounds\n\t\tBuildPoints buildPoints;\n\t\tbuildPoints.reserve(cloud.cols());\n\t\tfor (int i = 0; i < cloud.cols(); ++i)\n\t\t{\n\t\t\tconst Vector& v(cloud.block(0,i,this->dim,1));\n\t\t\tbuildPoints.push_back(i);\n#ifdef EIGEN3_API\n\t\t\tconst_cast<Vector&>(minBound) = minBound.array().min(v.array());\n\t\t\tconst_cast<Vector&>(maxBound) = maxBound.array().max(v.array());\n#else // EIGEN3_API\n\t\t\tconst_cast<Vector&>(minBound) = minBound.cwise().min(v);\n\t\t\tconst_cast<Vector&>(maxBound) = maxBound.cwise().max(v);\n#endif // EIGEN3_API\n\t\t}\n\t\t\n\t\t// create nodes\n\t\tbuildNodes(buildPoints.begin(), buildPoints.end(), minBound, maxBound);\n\t\tbuildPoints.clear();\n\t}\n\t\n\ttemplate<typename T, typename Heap, typename CloudType>\n\tunsigned long KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, Heap, CloudType>::knn(const Matrix& query, IndexMatrix& indices, Matrix& dists2, const Index k, const T epsilon, const unsigned optionFlags, const T maxRadius) const\n\t{\n\t\tcheckSizesKnn(query, indices, dists2, k, optionFlags);\n\t\t\n\t\tconst bool allowSelfMatch(optionFlags & NearestNeighbourSearch<T>::ALLOW_SELF_MATCH);\n\t\tconst bool sortResults(optionFlags & NearestNeighbourSearch<T>::SORT_RESULTS);\n\t\tconst bool collectStatistics(creationOptionFlags & NearestNeighbourSearch<T>::TOUCH_STATISTICS);\n\t\tconst T maxRadius2(maxRadius * maxRadius);\n\t\tconst T maxError2((1+epsilon)*(1+epsilon));\n\t\tconst int colCount(query.cols());\n\t\t\n\t\tassert(nodes.size() > 0);\n\n\t\tIndexMatrix result(k, query.cols());\n\t\tunsigned long leafTouchedCount(0);\n\n#pragma omp parallel \n\t\t{\t\t\n\n\t\tHeap heap(k);\n\t\tstd::vector<T> off(dim, 0);\n\n#pragma omp for reduction(+:leafTouchedCount) schedule(guided,32)\n\t\tfor (int i = 0; i < colCount; ++i)\n\t\t{\n\t\t\tleafTouchedCount += onePointKnn(query, indices, dists2, i, heap, off, maxError2, maxRadius2, allowSelfMatch, collectStatistics, sortResults);\n\t\t}\n\t\t}\n\t\treturn leafTouchedCount;\n\t}\n\t\n\ttemplate<typename T, typename Heap, typename CloudType>\n\tunsigned long KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, Heap, CloudType>::knn(const Matrix& query, IndexMatrix& indices, Matrix& dists2, const Vector& maxRadii, const Index k, const T epsilon, const unsigned optionFlags) const\n\t{\n\t\tcheckSizesKnn(query, indices, dists2, k, optionFlags, &maxRadii);\n\t\t\n\t\tconst bool allowSelfMatch(optionFlags & NearestNeighbourSearch<T>::ALLOW_SELF_MATCH);\n\t\tconst bool sortResults(optionFlags & NearestNeighbourSearch<T>::SORT_RESULTS);\n\t\tconst bool collectStatistics(creationOptionFlags & NearestNeighbourSearch<T>::TOUCH_STATISTICS);\n\t\tconst T maxError2((1+epsilon)*(1+epsilon));\n\t\tconst int colCount(query.cols());\n\t\t\n\t\tassert(nodes.size() > 0);\n\t\tIndexMatrix result(k, query.cols());\n\t\tunsigned long leafTouchedCount(0);\n\n#pragma omp parallel \n\t\t{\t\t\n\n\t\tHeap heap(k);\n\t\tstd::vector<T> off(dim, 0);\n\t\t\n#pragma omp for reduction(+:leafTouchedCount) schedule(guided,32)\n\t\tfor (int i = 0; i < colCount; ++i)\n\t\t{\n\t\t\tconst T maxRadius(maxRadii[i]);\n\t\t\tconst T maxRadius2(maxRadius * maxRadius);\n\t\t\tleafTouchedCount += onePointKnn(query, indices, dists2, i, heap, off, maxError2, maxRadius2, allowSelfMatch, collectStatistics, sortResults);\n\t\t}\n\t\t}\n\t\treturn leafTouchedCount;\n\t}\n\t\n\ttemplate<typename T, typename Heap, typename CloudType>\n\tunsigned long KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, Heap, CloudType>::onePointKnn(const Matrix& query, IndexMatrix& indices, Matrix& dists2, int i, Heap& heap, std::vector<T>& off, const T maxError2, const T maxRadius2, const bool allowSelfMatch, const bool collectStatistics, const bool sortResults) const\n\t{\n\t\tfill(off.begin(), off.end(), 0);\n\t\theap.reset();\n\t\tunsigned long leafTouchedCount(0);\n\t\t\n\t\tif (allowSelfMatch)\n\t\t{\n\t\t\tif (collectStatistics)\n\t\t\t\tleafTouchedCount += recurseKnn<true, true>(&query.coeff(0, i), 0, 0, heap, off, maxError2, maxRadius2);\n\t\t\telse\n\t\t\t\trecurseKnn<true, false>(&query.coeff(0, i), 0, 0, heap, off, maxError2, maxRadius2);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (collectStatistics)\n\t\t\t\tleafTouchedCount += recurseKnn<false, true>(&query.coeff(0, i), 0, 0, heap, off, maxError2, maxRadius2);\n\t\t\telse\n\t\t\t\trecurseKnn<false, false>(&query.coeff(0, i), 0, 0, heap, off, maxError2, maxRadius2);\n\t\t}\n\t\t\n\t\tif (sortResults)\n\t\t\theap.sort();\n\t\t\n\t\theap.getData(indices.col(i), dists2.col(i));\n\t\treturn leafTouchedCount;\n\t}\n\t\n\ttemplate<typename T, typename Heap, typename CloudType> template<bool allowSelfMatch, bool collectStatistics>\n\tunsigned long KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, Heap, CloudType>::recurseKnn(const T* query, const unsigned n, T rd, Heap& heap, std::vector<T>& off, const T maxError2, const T maxRadius2) const\n\t{\n\t\tconst Node& node(nodes[n]);\n\t\tconst uint32_t cd(getDim(node.dimChildBucketSize));\n\t\t\n\t\tif (cd == uint32_t(dim))\n\t\t{\n\t\t\t//cerr << \"entering bucket \" << node.bucket << endl;\n\t\t\tconst BucketEntry* bucket(&buckets[node.bucketIndex]);\n\t\t\tconst uint32_t bucketSize(getChildBucketSize(node.dimChildBucketSize));\n\t\t\tfor (uint32_t i = 0; i < bucketSize; ++i)\n\t\t\t{\n\t\t\t\t//cerr << \"  \" << bucket-> pt << endl;\n\t\t\t\t//const T dist(dist2<T>(query, cloud.col(index)));\n\t\t\t\t//const T dist((query - cloud.col(index)).squaredNorm());\n\t\t\t\tT dist(0);\n\t\t\t\tconst T* qPtr(query);\n\t\t\t\tconst T* dPtr(bucket->pt);\n\t\t\t\tfor (int i = 0; i < this->dim; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst T diff(*qPtr - *dPtr);\n\t\t\t\t\tdist += diff*diff;\n\t\t\t\t\tqPtr++; dPtr++;\n\t\t\t\t}\n\t\t\t\tif ((dist <= maxRadius2) &&\n\t\t\t\t\t(dist < heap.headValue()) &&\n\t\t\t\t\t(allowSelfMatch || (dist > numeric_limits<T>::epsilon()))\n\t\t\t\t)\n\t\t\t\t\theap.replaceHead(bucket->index, dist);\n\t\t\t\t++bucket;\n\t\t\t}\n\t\t\treturn (unsigned long)(bucketSize);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst unsigned rightChild(getChildBucketSize(node.dimChildBucketSize));\n\t\t\tunsigned long leafVisitedCount(0);\n\t\t\tT& offcd(off[cd]);\n\t\t\t//const T old_off(off.coeff(cd));\n\t\t\tconst T old_off(offcd);\n\t\t\tconst T new_off(query[cd] - node.cutVal);\n\t\t\tif (new_off > 0)\n\t\t\t{\n\t\t\t\tif (collectStatistics)\n\t\t\t\t\tleafVisitedCount += recurseKnn<allowSelfMatch, true>(query, rightChild, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\telse\n\t\t\t\t\trecurseKnn<allowSelfMatch, false>(query, rightChild, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\trd += - old_off*old_off + new_off*new_off;\n\t\t\t\tif ((rd <= maxRadius2) &&\n\t\t\t\t\t(rd * maxError2 < heap.headValue()))\n\t\t\t\t{\n\t\t\t\t\toffcd = new_off;\n\t\t\t\t\tif (collectStatistics)\n\t\t\t\t\t\tleafVisitedCount += recurseKnn<allowSelfMatch, true>(query, n + 1, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\t\telse\n\t\t\t\t\t\trecurseKnn<allowSelfMatch, false>(query, n + 1, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\t\toffcd = old_off;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (collectStatistics)\n\t\t\t\t\tleafVisitedCount += recurseKnn<allowSelfMatch, true>(query, n+1, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\telse\n\t\t\t\t\trecurseKnn<allowSelfMatch, false>(query, n+1, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\trd += - old_off*old_off + new_off*new_off;\n\t\t\t\tif ((rd <= maxRadius2) &&\n\t\t\t\t\t(rd * maxError2 < heap.headValue()))\n\t\t\t\t{\n\t\t\t\t\toffcd = new_off;\n\t\t\t\t\tif (collectStatistics)\n\t\t\t\t\t\tleafVisitedCount += recurseKnn<allowSelfMatch, true>(query, rightChild, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\t\telse\n\t\t\t\t\t\trecurseKnn<allowSelfMatch, false>(query, rightChild, rd, heap, off, maxError2, maxRadius2);\n\t\t\t\t\toffcd = old_off;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn leafVisitedCount;\n\t\t}\n\t}\n\t\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<float,IndexHeapSTL<int,float> >;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<float,IndexHeapBruteForceVector<int,float> >;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<double,IndexHeapSTL<int,double> >;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<double,IndexHeapBruteForceVector<int,double> >;\n\t\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<float,IndexHeapSTL<int,float>,Eigen::Matrix3Xf>;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<float,IndexHeapBruteForceVector<int,float>,Eigen::Matrix3Xf>;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<double,IndexHeapSTL<int,double>,Eigen::Matrix3Xd>;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<double,IndexHeapBruteForceVector<int,double>,Eigen::Matrix3Xd>;\n\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<float,IndexHeapSTL<int,float>,Eigen::Map<const Eigen::Matrix3Xf, Eigen::Aligned> >;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<float,IndexHeapBruteForceVector<int,float>,Eigen::Map<const Eigen::Matrix3Xf, Eigen::Aligned> >;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<double,IndexHeapSTL<int,double>,Eigen::Map<const Eigen::Matrix3Xd, Eigen::Aligned> >;\n\ttemplate struct KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<double,IndexHeapBruteForceVector<int,double>,Eigen::Map<const Eigen::Matrix3Xd, Eigen::Aligned> >;\n\n\t//@}\n}\n", "meta": {"hexsha": "4f76528c68fa2da34fa295ea1cc3e48e3ddf5530", "size": 17283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Automatching/nabo/kdtree_cpu.cpp", "max_stars_repo_name": "foreee/CPCA", "max_stars_repo_head_hexsha": "d2abcb4d05bc2a67e08a0c6833cf3d2292ab1559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T02:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T04:01:37.000Z", "max_issues_repo_path": "Automatching/nabo/kdtree_cpu.cpp", "max_issues_repo_name": "foreee/CPCA", "max_issues_repo_head_hexsha": "d2abcb4d05bc2a67e08a0c6833cf3d2292ab1559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Automatching/nabo/kdtree_cpu.cpp", "max_forks_repo_name": "foreee/CPCA", "max_forks_repo_head_hexsha": "d2abcb4d05bc2a67e08a0c6833cf3d2292ab1559", "max_forks_repo_licenses": ["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.9294871795, "max_line_length": 321, "alphanum_fraction": 0.7036972748, "num_tokens": 4968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052844289766, "lm_q2_score": 0.028007517462155913, "lm_q1q2_score": 0.009665542279926845}}
{"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#define BOOST_PYTHON_MAX_ARITY 17\n\n#include \"PyImathMatrix.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathDecorators.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include <boost/python/tuple.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/raw_function.hpp>\n#include \"PyImath.h\"\n#include \"PyImathVec.h\"\n#include \"PyImathMathExc.h\"\n#include <ImathVec.h>\n#include <ImathMatrixAlgo.h>\n#include <Iex.h>\n#include \"PyImathTask.h\"\n\nnamespace PyImath {\ntemplate<> const char PYIMATH_EXPORT *PyImath::M44fArray::name() { return \"M44fArray\"; }\ntemplate<> const char PYIMATH_EXPORT *PyImath::M44dArray::name() { return \"M44dArray\"; }\n\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\nusing namespace PyImath;\n\ntemplate <class T, int len>\nstruct MatrixRow {\n    explicit MatrixRow(T *data) : _data(data) {}\n    T & operator [] (int i) { return _data[i]; }\n    T *_data;\n\n    static const char *name;\n    static void register_class()\n    {\n        typedef PyImath::StaticFixedArray<MatrixRow,T,len> MatrixRow_helper;\n        class_<MatrixRow> matrixRow_class(name,no_init);\n        matrixRow_class\n            .def(\"__len__\", MatrixRow_helper::len)\n            .def(\"__getitem__\", MatrixRow_helper::getitem,return_value_policy<copy_non_const_reference>())\n            .def(\"__setitem__\", MatrixRow_helper::setitem)\n            ;\n    }\n};\n\ntemplate <> const char *MatrixRow<float,4>::name = \"M44fRow\";\ntemplate <> const char *MatrixRow<double,4>::name = \"M44dRow\";\n\n\ntemplate <class Container, class Data, int len>\nstruct IndexAccessMatrixRow {\n    typedef MatrixRow<Data,len> result_type;\n    static MatrixRow<Data,len> apply(Container &c, int i) { return MatrixRow<Data,len>(c[i]); }\n};\n\ntemplate <class T> struct Matrix44Name { static const char *value; };\ntemplate<> const char *Matrix44Name<float>::value  = \"M44f\";\ntemplate<> const char *Matrix44Name<double>::value = \"M44d\";\n\ntemplate <class T>\nstatic std::string Matrix44_str(const Matrix44<T> &v)\n{\n    std::stringstream stream;\n    stream << Matrix44Name<T>::value << \"(\";\n    for (int row = 0; row < 4; row++)\n    {\n        stream << \"(\";\n\tfor (int col = 0; col < 4; col++)\n\t{\n\t    stream << v[row][col];\n            stream << (col != 3 ? \", \" : \"\");\n\t}\n        stream << \")\" << (row != 3 ? \", \" : \"\");\n    }\n    stream << \")\";\n    return stream.str();\n}\n\n// Non-specialized repr is same as str\ntemplate <class T>\nstatic std::string Matrix44_repr(const Matrix44<T> &v)\n{\n    return Matrix44_str(v);\n}\n\n// Specialization for float to full precision\ntemplate <>\nstd::string Matrix44_repr(const Matrix44<float> &v)\n{\n    return (boost::format(\"%s((%.9g, %.9g, %.9g, %.9g), (%.9g, %.9g, %.9g, %.9g), (%.9g, %.9g, %.9g, %.9g), (%.9g, %.9g, %.9g, %.9g))\")\n                        % Matrix44Name<float>::value\n                        % v[0][0] % v[0][1] % v[0][2] % v[0][3]\n                        % v[1][0] % v[1][1] % v[1][2] % v[1][3]\n                        % v[2][0] % v[2][1] % v[2][2] % v[2][3]\n                        % v[3][0] % v[3][1] % v[3][2] % v[3][3]).str();\n}\n\n// Specialization for double to full precision\ntemplate <>\nstd::string Matrix44_repr(const Matrix44<double> &v)\n{\n    return (boost::format(\"%s((%.17g, %.17g, %.17g, %.17g), (%.17g, %.17g, %.17g, %.17g), (%.17g, %.17g, %.17g, %.17g), (%.17g, %.17g, %.17g, %.17g))\")\n                        % Matrix44Name<double>::value\n                        % v[0][0] % v[0][1] % v[0][2] % v[0][3]\n                        % v[1][0] % v[1][1] % v[1][2] % v[1][3]\n                        % v[2][0] % v[2][1] % v[2][2] % v[2][3]\n                        % v[3][0] % v[3][1] % v[3][2] % v[3][3]).str();\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\ninvert44 (Matrix44<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.invert(singExc);\n}\n\ntemplate <class T>\nstatic Matrix44<T>\ninverse44 (Matrix44<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.inverse(singExc);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\ngjInvert44 (Matrix44<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.gjInvert(singExc);\n}\n\ntemplate <class T>\nstatic Matrix44<T>\ngjInverse44 (Matrix44<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.gjInverse(singExc);\n}\n\ntemplate <class T, class U>\nstatic const Matrix44<T> &\niadd44(Matrix44<T> &m, const Matrix44<U> &m2)\n{\n    MATH_EXC_ON;\n    Matrix44<T> m3;\n    m3.setValue (m2);\n    return m += m3;\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\niadd44T(Matrix44<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    return mat += a;\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nadd44(Matrix44<T> &m, const Matrix44<T> &m2)\n{\n    MATH_EXC_ON;\n    return m + m2;\n}\n\ntemplate <class T, class U>\nstatic const Matrix44<T> &\nisub44(Matrix44<T> &m, const Matrix44<U> &m2)\n{\n    MATH_EXC_ON;\n    Matrix44<T> m3;\n    m3.setValue (m2);\n    return m -= m3;\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nisub44T(Matrix44<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    return mat -= a;\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nsub44(Matrix44<T> &m, const Matrix44<T> &m2)\n{\n    MATH_EXC_ON;\n    return m - m2;\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nnegate44 (Matrix44<T> &m)\n{\n    MATH_EXC_ON;\n    return m.negate();\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nneg44 (Matrix44<T> &m)\n{\n    MATH_EXC_ON;\n    return -m;\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nimul44T(Matrix44<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m *= t;\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nmul44T(Matrix44<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m * t;\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nrmul44T(Matrix44<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return t * m;\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nidiv44T(Matrix44<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m /= t;\n}\n\ntemplate <class T>\nstatic Matrix44<T>\ndiv44T(Matrix44<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m / t;\n}\n\ntemplate <class T>\nstatic void \nextractAndRemoveScalingAndShear44(Matrix44<T> &mat, Vec3<T> &dstScl, Vec3<T> &dstShr, int exc = 1)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::extractAndRemoveScalingAndShear(mat, dstScl, dstShr, exc);\n}\n\ntemplate <class T>\nstatic void\nextractEulerXYZ(Matrix44<T> &mat, IMATH_NAMESPACE::Vec3<T> &dst)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::extractEulerXYZ(mat, dst);\n}\n\ntemplate <class T>\nstatic void\nextractEulerZYX(Matrix44<T> &mat, IMATH_NAMESPACE::Vec3<T> &dst)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::extractEulerZYX(mat, dst);\n}\n\ntemplate <class T>\nstatic int\nextractSHRT44(Matrix44<T> &mat, Vec3<T> &s, Vec3<T> &h, Vec3<T> &r, Vec3<T> &t, int exc = 1)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::extractSHRT(mat, s, h, r, t, exc);\n}\n\ntemplate <class T>\nstatic void\nextractScaling44(Matrix44<T> &mat, Vec3<T> &dst, int exc = 1)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::extractScaling(mat, dst, exc);\n}\n\ntemplate <class T>\nstatic void\nextractScalingAndShear44(Matrix44<T> &mat, Vec3<T> &dstScl, Vec3<T> &dstShr, int exc = 1)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::extractScalingAndShear(mat, dstScl, dstShr, exc);\n}\n\ntemplate <class TV,class TM>\nstatic void\nmultDirMatrix44(Matrix44<TM> &mat, const Vec3<TV> &src, Vec3<TV> &dst)\n{\n    MATH_EXC_ON;\n    mat.multDirMatrix(src, dst);    \n}\n\ntemplate <class TV,class TM>\nstatic Vec3<TV>\nmultDirMatrix44_return_value(Matrix44<TM> &mat, const Vec3<TV> &src)\n{\n    MATH_EXC_ON;\n    Vec3<TV> dst;\n    mat.multDirMatrix(src, dst);    \n    return dst;\n}\n\ntemplate <class T1, class T2>\nstruct op_multDirMatrix {\n\n    static inline void apply(const Matrix44<T2>& m, const Vec3<T1>& src, Vec3<T1>& dst)\n    {\n        m.multDirMatrix(src,dst);\n    }\n};\n\ntemplate <class T1, class T2>\nstruct op_multVecMatrix {\n\n    static inline void apply(const Matrix44<T2>& m, const Vec3<T1>& src, Vec3<T1>& dst)\n    {\n        m.multVecMatrix(src,dst);\n    }\n};\n\ntemplate <class T1,class T2, class Op>\nstruct MatrixVecTask : public Task\n{\n    const Matrix44<T2> &mat;\n    const FixedArray<Vec3<T1> >& src;\n    FixedArray<Vec3<T1> >& dst;\n\n    MatrixVecTask(const Matrix44<T2> &m, const FixedArray<Vec3<T1> >& s, FixedArray<Vec3<T1> >& d)\n        : mat(m), src(s), dst(d) {}\n\n    void execute(size_t start, size_t end)\n    {\n        for(size_t p = start; p < end; ++p) \n            Op::apply(mat,src[p],dst[p]);\n    }\n};\n\ntemplate <class TV,class TM>\nstatic FixedArray<Vec3<TV> >\nmultDirMatrix44_array(Matrix44<TM> &mat, const FixedArray<Vec3<TV> >&src)\n{\n    MATH_EXC_ON;\n    size_t len = src.len();\n    FixedArray<Vec3<TV> > dst(len);\n\n    MatrixVecTask<TV,TM,op_multDirMatrix<TV,TM> > task(mat,src,dst);\n    dispatchTask(task,len);\n\n    return dst;\n}\n\ntemplate <class TV,class TM>\nstatic void\nmultVecMatrix44(Matrix44<TM> &mat, const Vec3<TV> &src, Vec3<TV> &dst)\n{\n    MATH_EXC_ON;\n    mat.multVecMatrix(src, dst);    \n}\n\ntemplate <class TV,class TM>\nstatic Vec3<TV>\nmultVecMatrix44_return_value(Matrix44<TM> &mat, const Vec3<TV> &src)\n{\n    MATH_EXC_ON;\n    Vec3<TV> dst;\n    mat.multVecMatrix(src, dst);    \n    return dst;\n}\n\n\ntemplate <class TV,class TM>\nstatic FixedArray<Vec3<TV> >\nmultVecMatrix44_array(Matrix44<TM> &mat, const FixedArray<Vec3<TV> >&src)\n{\n    MATH_EXC_ON;\n    size_t len = src.len();\n    FixedArray<Vec3<TV> > dst(len);\n\n    MatrixVecTask<TV,TM,op_multVecMatrix<TV,TM> > task(mat,src,dst);\n    dispatchTask(task,len);\n\n    return dst;\n}\n\ntemplate <class T>\nstatic int\nremoveScaling44(Matrix44<T> &mat, int exc = 1)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::removeScaling(mat, exc);\n}\n\ntemplate <class T>\nstatic int\nremoveScalingAndShear44(Matrix44<T> &mat, int exc = 1)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::removeScalingAndShear(mat, exc);\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nsansScaling44(const Matrix44<T> &mat, bool exc = true)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::sansScaling(mat, exc);\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nsansScalingAndShear44(const Matrix44<T> &mat, bool exc = true)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::sansScalingAndShear(mat, exc);\n}\n\n\ntemplate <class T>\nstatic const Matrix44<T> &\nscaleSc44(Matrix44<T> &mat, const T &s)\n{\n    MATH_EXC_ON;\n    Vec3<T> sVec(s, s, s);\n    return mat.scale(sVec);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nscaleV44(Matrix44<T> &mat, const Vec3<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.scale(s);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nscale44Tuple(Matrix44<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        s.z = extract<T>(t[2]);\n        \n        return mat.scale(s);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.scale needs tuple of length 3\");\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nrotateV44(Matrix44<T> &mat, const Vec3<T> &r)\n{\n    MATH_EXC_ON;\n    return mat.rotate(r);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nrotationMatrix44(Matrix44<T> &mat, const object &fromObj, const object &toObj)\n{\n    MATH_EXC_ON;\n    Vec3<T> from, to;\n    if (PyImath::V3<T>::convert (fromObj.ptr(), &from) &&\n        PyImath::V3<T>::convert (toObj.ptr(), &to))\n    {\n        Matrix44<T> rot = IMATH_NAMESPACE::rotationMatrix(from, to);\n        return mat.setValue(rot);\n    }\n    else\n    {\n        THROW(IEX_NAMESPACE::ArgExc, \"m.rotationMatrix expected V3 arguments\");\n    }   \n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nrotationMatrixWithUp44(Matrix44<T> &mat, const object &fromObj, const object &toObj,\n                       const object &upObj)\n{\n    MATH_EXC_ON;\n    Vec3<T> from, to, up;\n    if (PyImath::V3<T>::convert (fromObj.ptr(), &from) &&\n        PyImath::V3<T>::convert (toObj.ptr(), &to) &\n        PyImath::V3<T>::convert (upObj.ptr(), &up))\n    {\n        Matrix44<T> rot = IMATH_NAMESPACE::rotationMatrixWithUpDir(from, to, up);\n        return mat.setValue(rot);\n    }\n    else\n    {\n        THROW(IEX_NAMESPACE::ArgExc, \"m.rotationMatrix expected V3 arguments\");\n    }   \n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetScaleSc44(Matrix44<T> &mat, const T &s)\n{\n    MATH_EXC_ON;\n    Vec3<T> sVec(s, s, s);\n    return mat.setScale(sVec);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetScaleV44(Matrix44<T> &mat, const Vec3<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.setScale(s);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetScale44Tuple(Matrix44<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        s.z = extract<T>(t[2]);\n        \n        return mat.setScale(s);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.translate needs tuple of length 3\");\n}\n\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetShearV44(Matrix44<T> &mat, const Vec3<T> &sVec)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::Shear6<T> shear(sVec[0], sVec[1], sVec[2], T (0), T (0), T (0));\n    return mat.setShear(shear);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetShearS44(Matrix44<T> &mat, const Shear6<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.setShear(s);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetShear44Tuple(Matrix44<T> &mat, const tuple &t)\n{    \n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        s.z = extract<T>(t[2]);\n        Shear6<T> shear(s);\n        \n        return mat.setShear(shear);\n    }\n    else if(t.attr(\"__len__\")() == 6)\n    {\n        Shear6<T> shear;\n        for(int i = 0; i < 6; ++i)\n        {\n            shear[i] = extract<T>(t[i]);\n        }\n        \n        return mat.setShear(shear);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.setShear needs tuple of length 3 or 6\");\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetTranslation44(Matrix44<T> &mat, const Vec3<T> t)\n{\n    MATH_EXC_ON;\n    return mat.setTranslation(t);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetTranslation44Tuple(Matrix44<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> trans;\n        trans.x = extract<T>(t[0]);\n        trans.y = extract<T>(t[1]);\n        trans.z = extract<T>(t[2]);\n        \n        return mat.setTranslation(trans);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.translate needs tuple of length 3\");\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nsetTranslation44Obj(Matrix44<T> &mat, const object &o)\n{\n    MATH_EXC_ON;\n    Vec3<T> v;\n    if (PyImath::V3<T>::convert (o.ptr(), &v))\n    {\n        return mat.setTranslation(v);\n    }\n    else\n    {\n        THROW(IEX_NAMESPACE::ArgExc, \"m.setTranslation expected V3 argument\");\n        return mat;\n    }   \n}\n\ntemplate <class T>\nstatic void\nsetValue44(Matrix44<T> &mat, const Matrix44<T> &value)\n{\n    MATH_EXC_ON;\n    mat.setValue(value);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nshearV44(Matrix44<T> &mat, const Vec3<T> &s)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::Shear6<T> shear(s[0], s[1], s[2], T (0), T (0), T (0));\n    return mat.shear(shear);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nshearS44(Matrix44<T> &mat, const Shear6<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.shear(s);\n}\n\ntemplate <class T>\nstatic const Matrix44<T> &\nshear44Tuple(Matrix44<T> &mat, const tuple &t)\n{    \n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        s.z = extract<T>(t[2]);\n        Shear6<T> shear(s);\n\n        return mat.shear(shear);\n    }\n    else if(t.attr(\"__len__\")() == 6)\n    {\n        Shear6<T> shear;\n        for(int i = 0; i < 6; ++i)\n        {\n            shear[i] = extract<T>(t[i]);\n        }\n        \n        return mat.shear(shear);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.shear needs tuple of length 3 or 6\");\n}\n\n\ntemplate <class T>\nstatic const Matrix44<T> &\ntranslate44(Matrix44<T> &mat, const object &t)\n{\n    MATH_EXC_ON;\n    Vec3<T> v;\n    if (PyImath::V3<T>::convert (t.ptr(), &v))\n    {\n        return mat.translate(v);\n    }\n    else\n    {\n        THROW(IEX_NAMESPACE::ArgExc, \"m.translate expected V3 argument\");\n        return mat;\n    }   \n}\ntemplate <class T>\nstatic const Matrix44<T> &\ntranslate44Tuple(Matrix44<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 3)\n    {\n        Vec3<T> trans;\n        trans.x = extract<T>(t[0]);\n        trans.y = extract<T>(t[1]);\n        trans.z = extract<T>(t[2]);\n        \n        return mat.translate(trans);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.translate needs tuple of length 3\");\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nsubtractTL44(Matrix44<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix44<T> m(mat.x);\n    for(int i = 0; i < 4; ++i)\n        for(int j = 0; j < 4; ++j)\n            m.x[i][j] -= a;\n    \n    return m;\n}\n\ntemplate <class T>\nstatic Matrix44<T>\nsubtractTR44(Matrix44<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix44<T> m(mat.x);\n    for(int i = 0; i < 4; ++i)\n        for(int j = 0; j < 4; ++j)\n            m.x[i][j] = a - m.x[i][j];\n    \n    return m;\n}\n\n\ntemplate <class T>\nstatic Matrix44<T>\nadd44T(Matrix44<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix44<T> m(mat.x);\n    for(int i = 0; i < 4; ++i)\n        for(int j = 0; j < 4; ++j)\n            m.x[i][j] += a;\n    \n    return m;\n}\n\ntemplate <class S, class T>\nstatic Matrix44<T>\nmul44(Matrix44<T> &mat1, Matrix44<S> &mat2)\n{\n    MATH_EXC_ON;\n    Matrix44<T> mat2T;\n    mat2T.setValue (mat2);\n    return mat1 * mat2T;\n}\n\ntemplate <class S, class T>\nstatic Matrix44<T>\nrmul44(Matrix44<T> &mat2, Matrix44<S> &mat1)\n{\n    MATH_EXC_ON;\n    Matrix44<T> mat1T;\n    mat1T.setValue (mat1);\n    return mat1T * mat2;\n}\n\ntemplate <class S, class T>\nstatic const Matrix44<T> &\nimul44(Matrix44<T> &mat1, Matrix44<S> &mat2)\n{\n    MATH_EXC_ON;\n    Matrix44<T> mat2T;\n    mat2T.setValue (mat2);\n    return mat1 *= mat2T;\n}\n\ntemplate <class T>\nstatic bool\nlessThan44(Matrix44<T> &mat1, const Matrix44<T> &mat2)\n{\n    for(int i = 0; i < 4; ++i){\n        for(int j = 0; j < 4; ++j){\n            if(mat1[i][j] > mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return (mat1 != mat2);\n}\n\ntemplate <class T>\nstatic bool\nlessThanEqual44(Matrix44<T> &mat1, const Matrix44<T> &mat2)\n{\n    for(int i = 0; i < 4; ++i){\n        for(int j = 0; j < 4; ++j){\n            if(mat1[i][j] > mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\ntemplate <class T>\nstatic bool\ngreaterThan44(Matrix44<T> &mat1, const Matrix44<T> &mat2)\n{\n    for(int i = 0; i < 4; ++i){\n        for(int j = 0; j < 4; ++j){\n            if(mat1[i][j] < mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return (mat1 != mat2);\n}\n\ntemplate <class T>\nstatic bool\ngreaterThanEqual44(Matrix44<T> &mat1, const Matrix44<T> &mat2)\n{\n    for(int i = 0; i < 4; ++i){\n        for(int j = 0; j < 4; ++j){\n            if(mat1[i][j] < mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\ntemplate <class T>\nstatic tuple\nsingularValueDecomposition44(const Matrix44<T>& m, bool forcePositiveDeterminant = false)\n{\n    IMATH_NAMESPACE::Matrix44<T> U, V;\n    IMATH_NAMESPACE::Vec4<T> S;\n    IMATH_NAMESPACE::jacobiSVD (m, U, S, V, IMATH_NAMESPACE::limits<T>::epsilon(), forcePositiveDeterminant);\n    return make_tuple (U, S, V);\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(invert44_overloads, invert44, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(inverse44_overloads, inverse44, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(gjInvert44_overloads, gjInvert44, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(gjInverse44_overloads, gjInverse44, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractAndRemoveScalingAndShear44_overloads, extractAndRemoveScalingAndShear44, 3, 4)\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractSHRT44_overloads, extractSHRT44, 5, 6)\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractScaling44_overloads, extractScaling44, 2, 3)\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractScalingAndShear44_overloads, extractScalingAndShear44, 3, 4)\nBOOST_PYTHON_FUNCTION_OVERLOADS(removeScaling44_overloads, removeScaling44, 1, 2)\nBOOST_PYTHON_FUNCTION_OVERLOADS(removeScalingAndShear44_overloads, removeScalingAndShear44, 1, 2)\nBOOST_PYTHON_FUNCTION_OVERLOADS(sansScaling44_overloads, sansScaling44, 1, 2)\nBOOST_PYTHON_FUNCTION_OVERLOADS(sansScalingAndShear44_overloads, sansScalingAndShear44, 1, 2)\n\ntemplate <class T>\nstatic Matrix44<T> * Matrix4_tuple_constructor(const tuple &t0, const tuple &t1, const tuple &t2, const tuple &t3)\n{\n  if(t0.attr(\"__len__\")() == 4 && t1.attr(\"__len__\")() == 4 && t2.attr(\"__len__\")() == 4 && t3.attr(\"__len__\")() == 4)\n  {\n      return new Matrix44<T>(extract<T>(t0[0]),  extract<T>(t0[1]),  extract<T>(t0[2]),  extract<T>(t0[3]),\n                             extract<T>(t1[0]),  extract<T>(t1[1]),  extract<T>(t1[2]),  extract<T>(t1[3]),\n                             extract<T>(t2[0]),  extract<T>(t2[1]),  extract<T>(t2[2]),  extract<T>(t2[3]),\n                             extract<T>(t3[0]),  extract<T>(t3[1]),  extract<T>(t3[2]),  extract<T>(t3[3]));\n  }\n  else\n      THROW(IEX_NAMESPACE::LogicExc, \"Matrix44 takes 4 tuples of length 4\");\n}\n\ntemplate <class T, class S>\nstatic Matrix44<T> *Matrix4_matrix_constructor(const Matrix44<S> &mat)\n{\n    Matrix44<T> *m = new Matrix44<T>;\n    \n    for(int i = 0; i < 4; ++i)\n        for(int j = 0; j < 4; ++j)\n            m->x[i][j] = T (mat.x[i][j]);\n    \n    return m;\n}\n\n\ntemplate <class T>\nclass_<Matrix44<T> >\nregister_Matrix44()\n{\n    typedef PyImath::StaticFixedArray<Matrix44<T>,T,4,IndexAccessMatrixRow<Matrix44<T>,T,4> > Matrix44_helper;\n\n    MatrixRow<T,4>::register_class();\n\n    class_<Matrix44<T> > matrix44_class(Matrix44Name<T>::value, Matrix44Name<T>::value,init<Matrix44<T> >(\"copy construction\"));\n    matrix44_class\n        .def(init<>(\"initialize to identity\"))\n        .def(init<T>(\"initialize all entries to a single value\"))\n        .def(\"__init__\", make_constructor(Matrix4_tuple_constructor<T>),\"tuple constructor1\")\n        .def(\"__init__\", make_constructor(Matrix4_matrix_constructor<T,float>))\n        .def(\"__init__\", make_constructor(Matrix4_matrix_constructor<T,double>))\n        \n        .def(init<T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T>(\"make from components\"))\n\t//.def_readwrite(\"x00\", &Matrix44<T>::x[0][0])\n\t//.def_readwrite(\"x01\", &Matrix44<T>::x[0][1])\n\t//.def_readwrite(\"x02\", &Matrix44<T>::x[0][2])\n\t//.def_readwrite(\"x03\", &Matrix44<T>::x[0][3])\n\t//.def_readwrite(\"x10\", &Matrix44<T>::x[1][0])\n\t//.def_readwrite(\"x11\", &Matrix44<T>::x[1][1])\n\t//.def_readwrite(\"x12\", &Matrix44<T>::x[1][2])\n\t//.def_readwrite(\"x13\", &Matrix44<T>::x[1][3])\n\t//.def_readwrite(\"x20\", &Matrix44<T>::x[2][0])\n\t//.def_readwrite(\"x21\", &Matrix44<T>::x[2][1])\n\t//.def_readwrite(\"x22\", &Matrix44<T>::x[2][2])\n\t//.def_readwrite(\"x23\", &Matrix44<T>::x[2][3])\n\t//.def_readwrite(\"x30\", &Matrix44<T>::x[3][0])\n\t//.def_readwrite(\"x31\", &Matrix44<T>::x[3][1])\n\t//.def_readwrite(\"x32\", &Matrix44<T>::x[3][2])\n\t//.def_readwrite(\"x33\", &Matrix44<T>::x[3][3])\n        .def(\"baseTypeEpsilon\", &Matrix44<T>::baseTypeEpsilon,\"baseTypeEpsilon() epsilon value of the base type of the vector\")\n        .staticmethod(\"baseTypeEpsilon\")\n        .def(\"baseTypeMax\", &Matrix44<T>::baseTypeMax,\"baseTypeMax() max value of the base type of the vector\")\n        .staticmethod(\"baseTypeMax\")\n        .def(\"baseTypeMin\", &Matrix44<T>::baseTypeMin,\"baseTypeMin() min value of the base type of the vector\")\n        .staticmethod(\"baseTypeMin\")\n        .def(\"baseTypeSmallest\", &Matrix44<T>::baseTypeSmallest,\"baseTypeSmallest() smallest value of the base type of the vector\")\n        .staticmethod(\"baseTypeSmallest\")\n        .def(\"equalWithAbsError\", &Matrix44<T>::equalWithAbsError,\n             \"m1.equalWithAbsError(m2,e) true if the elements \"\n             \"of v1 and v2 are the same with an absolute error of no more than e, \"\n             \"i.e., abs(m1[i] - m2[i]) <= e\")\n         \n        .def(\"equalWithRelError\", &Matrix44<T>::equalWithRelError,\n             \"m1.equalWithAbsError(m2,e) true if the elements \"\n             \"of m1 and m2 are the same with an absolute error of no more than e, \"\n             \"i.e., abs(m1[i] - m2[i]) <= e * abs(m1[i])\")\n         \n        // need a different version for matrix data access\n        .def(\"__len__\", Matrix44_helper::len)\n        .def(\"__getitem__\", Matrix44_helper::getitem)\n\t//.def(\"__setitem__\", Matrix44_helper::setitem)\n        .def(\"makeIdentity\",&Matrix44<T>::makeIdentity,\"makeIdentity() make this matrix the identity matrix\")\n        .def(\"transpose\",&Matrix44<T>::transpose,return_internal_reference<>(),\"transpose() transpose this matrix\")\n        .def(\"transposed\",&Matrix44<T>::transposed,\"transposed() return a transposed copy of this matrix\")\n        .def(\"minorOf\",&Matrix44<T>::minorOf,\"minorOf() return matrix minor of the (row,col) element of this matrix\")\n        .def(\"fastMinor\",&Matrix44<T>::fastMinor,\"fastMinor() return matrix minor using the specified rows and columns of this matrix\")\n        .def(\"determinant\",&Matrix44<T>::determinant,\"determinant() return the determinant of this matrix\")\n        .def(\"invert\",&invert44<T>,invert44_overloads(\"invert() invert this matrix\")[return_internal_reference<>()])\n        .def(\"inverse\",&inverse44<T>,inverse44_overloads(\"inverse() return a inverted copy of this matrix\"))\n        .def(\"gjInvert\",&gjInvert44<T>,gjInvert44_overloads(\"gjInvert() invert this matrix\")[return_internal_reference<>()])\n        .def(\"gjInverse\",&gjInverse44<T>,gjInverse44_overloads(\"gjInverse() return a inverted copy of this matrix\"))\n        .def(self == self)\n        .def(self != self)\n        .def(\"__iadd__\", &iadd44<T, float>,return_internal_reference<>())\n        .def(\"__iadd__\", &iadd44<T, double>,return_internal_reference<>())\n        .def(\"__iadd__\", &iadd44T<T>,return_internal_reference<>())\n        .def(\"__add__\", &add44<T>)\n        .def(\"__isub__\", &isub44<T, float>,return_internal_reference<>())\n        .def(\"__isub__\", &isub44<T, double>,return_internal_reference<>())\n        .def(\"__isub__\", &isub44T<T>,return_internal_reference<>())\n        .def(\"__sub__\", &sub44<T>)\n        .def(\"negate\",&negate44<T>,return_internal_reference<>(),\"negate() negate all entries in this matrix\")\n        .def(\"__neg__\", &neg44<T>)\n        .def(\"__imul__\", &imul44T<T>,return_internal_reference<>())\n        .def(\"__mul__\", &mul44T<T>)\n        .def(\"__rmul__\", &rmul44T<T>)\n        .def(\"__idiv__\", &idiv44T<T>,return_internal_reference<>())\n        .def(\"__itruediv__\", &idiv44T<T>,return_internal_reference<>())\n        .def(\"__div__\", &div44T<T>)\n        .def(\"__truediv__\", &div44T<T>)\n        .def(\"__add__\", &add44T<T>)\n        .def(\"__radd__\", &add44T<T>)\n        .def(\"__sub__\", &subtractTL44<T>)\n        .def(\"__rsub__\", &subtractTR44<T>)\n        .def(\"__mul__\", &mul44<float, T>)\n        .def(\"__mul__\", &mul44<double, T>)\n        .def(\"__rmul__\", &rmul44<float, T>)\n        .def(\"__rmul__\", &rmul44<double, T>)\n        .def(\"__imul__\", &imul44<float, T>,return_internal_reference<>())\n        .def(\"__imul__\", &imul44<double, T>,return_internal_reference<>())\n        .def(\"__lt__\", &lessThan44<T>)\n        .def(\"__gt__\", &greaterThan44<T>)\n        .def(\"__le__\", &lessThanEqual44<T>)\n        .def(\"__ge__\", &greaterThanEqual44<T>)\n\t//.def(self_ns::str(self))\n\t    .def(\"__repr__\",&Matrix44_repr<T>)\n    \n        .def(\"extractAndRemoveScalingAndShear\", &extractAndRemoveScalingAndShear44<T>, \n             extractAndRemoveScalingAndShear44_overloads(\t\t\t\t\n             \"M.extractAndRemoveScalingAndShear(scl, shr, \"\n             \"[exc]) -- extracts the scaling component of \"\n             \"M into scl and the shearing component of M \"\n             \"into shr.  Also removes the scaling and \"\n             \"shearing components from M.  \"\n             \"Returns 1 unless the scaling component is \"\n             \"nearly 0, in which case 0 is returned. \"\n             \"If optional arg. exc == 1, then if the \"\n             \"scaling component is nearly 0, then MathExc \"\n             \"is thrown.\"))\n             \n        .def(\"extractEulerXYZ\", &extractEulerXYZ<T>, \"extract Euler\")          \n        .def(\"extractEulerZYX\", &extractEulerZYX<T>, \"extract Euler\")\n          \n        .def(\"extractSHRT\", &extractSHRT44<T>, extractSHRT44_overloads(\n             \"M.extractSHRT(Vs, Vh, Vr, Vt, [exc]) -- \"\n\t         \"extracts the scaling component of M into Vs, \"\n\t\t\t \"the shearing component of M in Vh (as XY, \"\n\t         \"XZ, YZ shear factors), the rotation of M \"\n\t         \"into Vr (as Euler angles in the order XYZ), \"\n\t         \"and the translaation of M into Vt. \"\n\t\t\t \"If optional arg. exc == 1, then if the \"\n             \"scaling component is nearly 0, then MathExc \"\n             \"is thrown. \"))\n                \n        .def(\"extractScaling\", &extractScaling44<T>, extractScaling44_overloads(\"extract scaling\"))\n        .def(\"extractScalingAndShear\", &extractScalingAndShear44<T>, extractScalingAndShear44_overloads(\"extract scaling\"))\n        .def(\"singularValueDecomposition\", &singularValueDecomposition44<T>, \n             \"Decomposes the matrix using the singular value decomposition (SVD) into three\\n\"\n             \"matrices U, S, and V which have the following properties: \\n\"\n             \"  1. U and V are both orthonormal matrices, \\n\"\n             \"  2. S is the diagonal matrix of singular values, \\n\"\n             \"  3. U * S * V.transposed() gives back the original matrix.\\n\"\n             \"The result is returned as a tuple [U, S, V].  Note that since S is diagonal we\\n\"\n             \"don't need to return the entire matrix, so we return it as a three-vector.  \\n\"\n             \"\\n\"\n             \"The 'forcePositiveDeterminant' argument can be used to force the U and V^T to\\n\"\n             \"have positive determinant (that is, to be proper rotation matrices); if\\n\"\n             \"forcePositiveDeterminant is False, then the singular values are guaranteed to\\n\"\n             \"be nonnegative but the U and V matrices might contain negative scale along one\\n\"\n             \"of the axes; if forcePositiveDeterminant is True, then U and V cannot contain\\n\"\n             \"negative scale but S[3] might be negative.  \\n\"\n             \"\\n\"\n             \"Our SVD implementation uses two-sided Jacobi rotations to iteratively\\n\"\n             \"diagonalize the matrix, which should be quite robust and significantly faster\\n\"\n             \"than the more general SVD solver in LAPACK.  \\n\",\n             args(\"matrix\", \"forcePositiveDeterminant\"))\n        .def(\"symmetricEigensolve\", &PyImath::jacobiEigensolve<IMATH_NAMESPACE::Matrix44<T> >, \n             \"Decomposes the matrix A using a symmetric eigensolver into matrices Q and S \\n\"\n             \"which have the following properties: \\n\"\n             \"  1. Q is the orthonormal matrix of eigenvectors, \\n\"\n             \"  2. S is the diagonal matrix of eigenvalues, \\n\"\n             \"  3. Q.transposed() * S * Q gives back the original matrix.\\n\"\n             \"\\n\"\n             \"IMPORTANT: It is vital that the passed-in matrix be symmetric, or the result \\n\"\n             \"won't make any sense.  This function will return an error if passed an \\n\"\n             \"unsymmetric matrix.\\n\"\n             \"\\n\"\n             \"The result is returned as a tuple [Q, S].  Note that since S is diagonal \\n\"\n             \"we don't need to return the entire matrix, so we return it as a three-vector. \\n\"\n             \"\\n\"\n             \"Our eigensolver implementation uses one-sided Jacobi rotations to iteratively \\n\"\n             \"diagonalize the matrix, which should be quite robust and significantly faster \\n\"\n             \"than the more general symmetric eigenvalue solver in LAPACK.  \\n\")\n        .def(\"multDirMatrix\", &multDirMatrix44<double,T>, \"mult matrix\")\n        .def(\"multDirMatrix\", &multDirMatrix44_return_value<double,T>, \"mult matrix\")\n        .def(\"multDirMatrix\", &multDirMatrix44_array<double,T>, \"mult matrix\")\n        .def(\"multDirMatrix\", &multDirMatrix44<float,T>, \"mult matrix\")\n        .def(\"multDirMatrix\", &multDirMatrix44_return_value<float,T>, \"mult matrix\")\n        .def(\"multDirMatrix\", &multDirMatrix44_array<float,T>, \"mult matrix\")\n        .def(\"multVecMatrix\", &multVecMatrix44<double,T>, \"mult matrix\")\n        .def(\"multVecMatrix\", &multVecMatrix44_return_value<double,T>, \"mult matrix\")\n        .def(\"multVecMatrix\", &multVecMatrix44_array<double,T>, \"mult matrix\")\n        .def(\"multVecMatrix\", &multVecMatrix44<float,T>, \"mult matrix\")\n        .def(\"multVecMatrix\", &multVecMatrix44_return_value<float,T>, \"mult matrix\")\n        .def(\"multVecMatrix\", &multVecMatrix44_array<float,T>, \"mult matrix\")\n        .def(\"removeScaling\", &removeScaling44<T>, removeScaling44_overloads(\"remove scaling\"))\n        .def(\"removeScalingAndShear\", &removeScalingAndShear44<T>, removeScalingAndShear44_overloads(\"remove scaling\"))\n        .def(\"sansScaling\", &sansScaling44<T>, sansScaling44_overloads(\"sans scaling\"))\n        .def(\"sansScalingAndShear\", &sansScalingAndShear44<T>, sansScalingAndShear44_overloads(\"sans scaling and shear\"))\n        .def(\"scale\", &scaleSc44<T>, return_internal_reference<>(), \"scale matrix\")\n        .def(\"scale\", &scaleV44<T>, return_internal_reference<>(), \"scale matrix\")\n        .def(\"scale\", &scale44Tuple<T>, return_internal_reference<>(), \"scale matrix\")\n        .def(\"rotate\", &rotateV44<T>, return_internal_reference<>(), \"rotate matrix\")\n        .def(\"rotationMatrix\", &rotationMatrix44<T>, return_internal_reference<>(), \"rotationMatrix()\")\n        .def(\"rotationMatrixWithUpDir\", &rotationMatrixWithUp44<T>, return_internal_reference<>(), \"roationMatrixWithUp()\")\n        .def(\"setScale\", &setScaleSc44<T>, return_internal_reference<>(),\"setScale()\")\n        .def(\"setScale\", &setScaleV44<T>, return_internal_reference<>(),\"setScale()\")\n        .def(\"setScale\", &setScale44Tuple<T>, return_internal_reference<>(),\"setScale()\")\n\n        .def(\"setShear\", &setShearV44<T>, return_internal_reference<>(),\"setShear()\")\n        .def(\"setShear\", &setShearS44<T>, return_internal_reference<>(),\"setShear()\")\n        .def(\"setShear\", &setShear44Tuple<T>, return_internal_reference<>(),\"setShear()\")\n        .def(\"setTranslation\", &setTranslation44<T>, return_internal_reference<>(),\"setTranslation()\")\n        .def(\"setTranslation\", &setTranslation44Tuple<T>, return_internal_reference<>(),\"setTranslation()\")\n        .def(\"setTranslation\", &setTranslation44Obj<T>, return_internal_reference<>(),\"setTranslation()\")\n        .def(\"setValue\", &setValue44<T>, \"setValue()\")\n        .def(\"shear\", &shearV44<T>, return_internal_reference<>(),\"shear()\")\n        .def(\"shear\", &shearS44<T>, return_internal_reference<>(),\"shear()\")\n        .def(\"shear\", &shear44Tuple<T>, return_internal_reference<>(),\"shear()\")\n        .def(\"translate\", &translate44<T>, return_internal_reference<>(),\"translate()\")\n        .def(\"translate\", &translate44Tuple<T>, return_internal_reference<>(),\"translate()\")\n        .def(\"translation\", &Matrix44<T>::translation, \"translation()\")\n\n        ;\n\n    decoratecopy(matrix44_class);\n\n    return matrix44_class;\n/*\n    const Matrix44 &\toperator = (const Matrix44 &v);\n    const Matrix44 &\toperator = (T a);\n    T *\t\t\tgetValue ();\n    const T *\t\tgetValue () const;\n    template <class S> void getValue (Matrix44<S> &v) const;\n    template <class S> Matrix44 & setValue (const Matrix44<S> &v);\n    template <class S> Matrix44 & setTheMatrix (const Matrix44<S> &v);\n    template <class S> void multVecMatrix(const Vec2<S> &src, Vec2<S> &dst) const;\n    template <class S> void multDirMatrix(const Vec2<S> &src, Vec2<S> &dst) const;\n    template <class S> const Matrix44 &\tsetRotation (S r);\n    template <class S> const Matrix44 &\trotate (S r);\n    const Matrix44 &\tsetScale (T s);\n    template <class S> const Matrix44 &\tsetScale (const Vec2<S> &s);\n    template <class S> const Matrix44 &\tscale (const Vec2<S> &s);\n    template <class S> const Matrix44 &\tsetTranslation (const Vec2<S> &t);\n    Vec2<T>\t\ttranslation () const;\n    template <class S> const Matrix44 &\ttranslate (const Vec2<S> &t);\n    template <class S> const Matrix44 &\tsetShear (const S &h);\n    template <class S> const Matrix44 &\tsetShear (const Vec2<S> &h);\n    template <class S> const Matrix44 &\tshear (const S &xy);\n    template <class S> const Matrix44 &\tshear (const Vec2<S> &h);\n*/\n}\n\n\ntemplate <class T>\nstatic void\nsetM44ArrayItem(FixedArray<IMATH_NAMESPACE::Matrix44<T> > &ma,\n                Py_ssize_t index,\n                const IMATH_NAMESPACE::Matrix44<T> &m)\n{\n    ma[ma.canonical_index(index)] = m;\n}\n\ntemplate <class T>\nclass_<FixedArray<IMATH_NAMESPACE::Matrix44<T> > >\nregister_M44Array()\n{\n    class_<FixedArray<IMATH_NAMESPACE::Matrix44<T> > > matrixArray_class = FixedArray<IMATH_NAMESPACE::Matrix44<T> >::register_(\"Fixed length array of IMATH_NAMESPACE::Matrix44\");\n    matrixArray_class\n         .def(\"__setitem__\", &setM44ArrayItem<T>)\n        ;\n    return matrixArray_class;\n}\n\n\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Matrix44<float> > register_Matrix44<float>();\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Matrix44<double> > register_Matrix44<double>();\n\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Matrix44<float> > > register_M44Array<float>();\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Matrix44<double> > > register_M44Array<double>();\n\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Matrix44<float> FixedArrayDefaultValue<IMATH_NAMESPACE::Matrix44<float> >::value() { return IMATH_NAMESPACE::Matrix44<float>(); }\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Matrix44<double> FixedArrayDefaultValue<IMATH_NAMESPACE::Matrix44<double> >::value() { return IMATH_NAMESPACE::Matrix44<double>(); }\n}\n", "meta": {"hexsha": "edb66b1f9b548bd3d12a8a21f2056985dfd46d7e", "size": 39582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathMatrix44.cpp", "max_stars_repo_name": "tangent-devops/openexr", "max_stars_repo_head_hexsha": "2f7847e3faf7146f2be8c1c0c3053c50b7ee9d97", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-27T03:39:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-16T16:03:02.000Z", "max_issues_repo_path": "PyIlmBase/PyImath/PyImathMatrix44.cpp", "max_issues_repo_name": "tangent-devops/openexr", "max_issues_repo_head_hexsha": "2f7847e3faf7146f2be8c1c0c3053c50b7ee9d97", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/PyImathMatrix44.cpp", "max_forks_repo_name": "tangent-devops/openexr", "max_forks_repo_head_hexsha": "2f7847e3faf7146f2be8c1c0c3053c50b7ee9d97", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-16T04:34:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-26T00:51:41.000Z", "avg_line_length": 32.7123966942, "max_line_length": 179, "alphanum_fraction": 0.6298822697, "num_tokens": 11615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.025565216336149464, "lm_q1q2_score": 0.009651908515419161}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (c) 2021, Andrew Kennings\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\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\n////////////////////////////////////////////////////////////////////////////////\n// Includes.\n////////////////////////////////////////////////////////////////////////////////\n#include \"detailed_hpwl.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <algorithm>\n#include <boost/tokenizer.hpp>\n#include <cmath>\n#include <iostream>\n#include <stack>\n#include <utility>\n#include \"detailed_manager.h\"\n#include \"detailed_orient.h\"\n#include \"rectangle.h\"\n\nnamespace dpo {\n\n////////////////////////////////////////////////////////////////////////////////\n// Defines.\n////////////////////////////////////////////////////////////////////////////////\n\n////////////////////////////////////////////////////////////////////////////////\n// Classes.\n////////////////////////////////////////////////////////////////////////////////\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nDetailedHPWL::DetailedHPWL(Architecture* arch, Network* network,\n                           RoutingParams* rt)\n    : DetailedObjective(),\n      m_arch(arch),\n      m_network(network),\n      m_rt(rt),\n      m_orientPtr(0),\n      m_skipNetsLargerThanThis(100) {\n  m_traversal = 0;\n  m_edgeMask.resize(m_network->getNumEdges());\n  std::fill(m_edgeMask.begin(), m_edgeMask.end(), m_traversal);\n\n  m_name = \"hpwl\";\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nDetailedHPWL::~DetailedHPWL() {}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nvoid DetailedHPWL::init() {\n  m_traversal = 0;\n  m_edgeMask.resize(m_network->getNumEdges());\n  std::fill(m_edgeMask.begin(), m_edgeMask.end(), m_traversal);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nvoid DetailedHPWL::init(DetailedMgr* mgrPtr, DetailedOrient* orientPtr) {\n  m_orientPtr = orientPtr;\n  m_mgrPtr = mgrPtr;\n  init();\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\ndouble DetailedHPWL::curr() {\n  double x, y;\n  double hpwl = 0.;\n  Rectangle box;\n  for (int i = 0; i < m_network->getNumEdges(); i++) {\n    Edge* edi = m_network->getEdge(i);\n\n    int npins = edi->getNumPins();\n    if (npins <= 1 || npins >= m_skipNetsLargerThanThis) {\n      continue;\n    }\n\n    box.reset();\n    for (int pj = 0; pj < edi->getPins().size(); pj++) {\n      Pin* pinj = edi->getPins()[pj];\n\n      Node* ndj = pinj->getNode();\n\n      x = ndj->getLeft() + 0.5*ndj->getWidth() + pinj->getOffsetX();\n      y = ndj->getBottom() + 0.5*ndj->getHeight() + pinj->getOffsetY();\n\n      box.addPt(x,y);\n    }\n\n    hpwl += (box.getWidth()+box.getHeight());\n  }\n  return hpwl;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\ndouble DetailedHPWL::delta(int n, std::vector<Node*>& nodes,\n                           std::vector<int>& curLeft, std::vector<int>& curBottom,\n                           std::vector<unsigned>& curOri,\n                           std::vector<int>& newLeft, std::vector<int>& newBottom,\n                           std::vector<unsigned>& newOri) {\n  // Given a list of nodes with their old positions and new positions, compute\n  // the change in WL. Note that we need to know the orientation information and\n  // might need to adjust pin information...\n\n  double x, y;\n  double old_wl = 0.;\n  double new_wl = 0.;\n  Rectangle old_box, new_box;\n\n  // Put cells into their \"old positions and orientations\".\n  for (int i = 0; i < n; i++) {\n    nodes[i]->setLeft(curLeft[i]);\n    nodes[i]->setBottom(curBottom[i]);\n    if (m_orientPtr != 0) {\n      m_orientPtr->orientAdjust(nodes[i], curOri[i]);\n    }\n  }\n\n  ++m_traversal;\n  for (int i = 0; i < n; i++) {\n    Node* ndi = nodes[i];\n    for (int pi = 0; pi < ndi->getPins().size(); pi++) {\n      Pin* pini = ndi->getPins()[pi];\n\n      Edge* edi = pini->getEdge();\n\n      int npins = edi->getNumPins();\n      if (npins <= 1 || npins >= m_skipNetsLargerThanThis) {\n        continue;\n      }\n      if (m_edgeMask[edi->getId()] == m_traversal) {\n        continue;\n      }\n      m_edgeMask[edi->getId()] = m_traversal;\n\n      old_box.reset();\n      for (int pj = 0; pj < edi->getNumPins(); pj++) {\n        Pin* pinj = edi->getPins()[pj];\n\n        Node* curr = pinj->getNode();\n\n        x = curr->getLeft() + 0.5*curr->getWidth() + pinj->getOffsetX();\n        y = curr->getBottom() + 0.5*curr->getHeight() + pinj->getOffsetY();\n\n        old_box.addPt(x,y);\n      }\n\n      old_wl += (old_box.getWidth()+old_box.getHeight());\n    }\n  }\n\n  // Put cells into their \"new positions and orientations\".\n  for (int i = 0; i < n; i++) {\n    nodes[i]->setLeft(newLeft[i]);\n    nodes[i]->setBottom(newBottom[i]);\n    if (m_orientPtr != 0) {\n      m_orientPtr->orientAdjust(nodes[i], newOri[i]);\n    }\n  }\n\n  ++m_traversal;\n  for (int i = 0; i < n; i++) {\n    Node* ndi = nodes[i];\n    for (int pi = 0; pi < ndi->getNumPins(); pi++) {\n      Pin* pini = ndi->getPins()[pi];\n\n      Edge* edi = pini->getEdge();\n\n      int npins = edi->getNumPins();\n      if (npins <= 1 || npins >= m_skipNetsLargerThanThis) {\n        continue;\n      }\n      if (m_edgeMask[edi->getId()] == m_traversal) {\n        continue;\n      }\n      m_edgeMask[edi->getId()] = m_traversal;\n\n      new_box.reset();\n      for (int pj = 0; pj < edi->getNumPins(); pj++) {\n        Pin* pinj = edi->getPins()[pj];\n\n        Node* curr = pinj->getNode();\n\n        x = curr->getLeft() + 0.5*curr->getWidth() + pinj->getOffsetX();\n        y = curr->getBottom() + 0.5*curr->getHeight() + pinj->getOffsetY();\n\n        new_box.addPt(x,y);\n      }\n\n      new_wl += (new_box.getWidth()+new_box.getHeight());\n    }\n  }\n\n  // Put cells into their \"old positions and orientations\" before returning\n  // (leave things as they were provided to us...).\n  for (int i = 0; i < n; i++) {\n    nodes[i]->setLeft(curLeft[i]);\n    nodes[i]->setBottom(curBottom[i]);\n    if (m_orientPtr != 0) {\n      m_orientPtr->orientAdjust(nodes[i], curOri[i]);\n    }\n  }\n\n  // +ve means improvement.\n  return old_wl - new_wl;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\ndouble DetailedHPWL::delta(Node* ndi, double new_x, double new_y) {\n  // Compute change in wire length for moving node to new position.\n\n  double old_wl = 0.;\n  double new_wl = 0.;\n  double x, y;\n  Rectangle old_box, new_box;\n\n  ++m_traversal;\n  for (int pi = 0; pi < ndi->getNumPins(); pi++) {\n    Pin* pini = ndi->getPins()[pi];\n\n    Edge* edi = pini->getEdge();\n\n    int npins = edi->getNumPins();\n    if (npins <= 1 || npins >= m_skipNetsLargerThanThis) {\n      continue;\n    }\n    if (m_edgeMask[edi->getId()] == m_traversal) {\n      continue;\n    }\n    m_edgeMask[edi->getId()] = m_traversal;\n\n    old_box.reset();\n    new_box.reset();\n    for (int pj = 0; pj < edi->getNumPins(); pj++) {\n      Pin* pinj = edi->getPins()[pj];\n\n      Node* ndj = pinj->getNode();\n\n      x = ndj->getLeft() + 0.5*ndj->getWidth() + pinj->getOffsetX();\n      y = ndj->getBottom() + 0.5*ndj->getHeight() + pinj->getOffsetY();\n\n      old_box.addPt(x,y);\n\n      if (ndj == ndi) {\n        x = new_x + pinj->getOffsetX();\n        y = new_y + pinj->getOffsetY();\n      }\n\n      new_box.addPt(x,y);\n    }\n    old_wl += (old_box.getWidth()+old_box.getHeight());\n    new_wl += (new_box.getWidth()+new_box.getHeight());\n  }\n  return old_wl - new_wl;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nvoid DetailedHPWL::getCandidates(std::vector<Node*>& candidates) {\n  candidates.erase(candidates.begin(), candidates.end());\n  candidates = m_mgrPtr->m_singleHeightCells;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\ndouble DetailedHPWL::delta(Node* ndi, Node* ndj) {\n  // Compute change in wire length for swapping the two nodes.\n\n  double old_wl = 0.;\n  double new_wl = 0.;\n  double x, y;\n  Rectangle old_box, new_box;\n  Node* nodes[2];\n  nodes[0] = ndi;\n  nodes[1] = ndj;\n\n  ++m_traversal;\n  for (int c = 0; c <= 1; c++) {\n    Node* ndi = nodes[c];\n    for (int pi = 0; pi < ndi->getNumPins(); pi++) {\n      Pin* pini = ndi->getPins()[pi];\n\n      Edge* edi = pini->getEdge();\n\n      //int npins = edi->getNumPins();\n      int npins = edi->getNumPins();\n      if (npins <= 1 || npins >= m_skipNetsLargerThanThis) {\n        continue;\n      }\n      if (m_edgeMask[edi->getId()] == m_traversal) {\n        continue;\n      }\n      m_edgeMask[edi->getId()] = m_traversal;\n\n      old_box.reset();\n      new_box.reset();\n      for (int pj = 0; pj < edi->getNumPins(); pj++) {\n        Pin* pinj = edi->getPins()[pj];\n\n        Node* ndj = pinj->getNode();\n\n        x = ndj->getLeft() + 0.5*ndj->getWidth() + pinj->getOffsetX();\n        y = ndj->getBottom() + 0.5*ndj->getHeight() + pinj->getOffsetY();\n\n        old_box.addPt(x,y);\n\n        if (ndj == nodes[0]) {\n          ndj = nodes[1];\n        } else if (ndj == nodes[1]) {\n          ndj = nodes[0];\n        }\n\n        x = ndj->getLeft() + 0.5*ndj->getWidth() + pinj->getOffsetX();\n        y = ndj->getBottom() + 0.5*ndj->getHeight() + pinj->getOffsetY();\n\n        new_box.addPt(x,y);\n      }\n\n      old_wl += (old_box.getWidth()+old_box.getHeight());\n      new_wl += (new_box.getWidth()+new_box.getHeight());\n    }\n  }\n  return old_wl - new_wl;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\ndouble DetailedHPWL::delta(Node* ndi, double target_xi, double target_yi,\n                           Node* ndj, double target_xj, double target_yj) {\n  // Compute change in wire length for swapping the two nodes.\n\n  double old_wl = 0.;\n  double new_wl = 0.;\n  double x, y;\n  Rectangle old_box, new_box;\n  Node* nodes[2];\n  nodes[0] = ndi;\n  nodes[1] = ndj;\n\n  ++m_traversal;\n  for (int c = 0; c <= 1; c++) {\n    Node* ndi = nodes[c];\n    for (int pi = 0; pi < ndi->getNumPins(); pi++) {\n      Pin* pini = ndi->getPins()[pi];\n\n      Edge* edi = pini->getEdge();\n\n      int npins = edi->getNumPins();\n      if (npins <= 1 || npins >= m_skipNetsLargerThanThis) {\n        continue;\n      }\n      if (m_edgeMask[edi->getId()] == m_traversal) {\n        continue;\n      }\n      m_edgeMask[edi->getId()] = m_traversal;\n\n      old_box.reset();\n      new_box.reset();\n      for (int pj = 0; pj < edi->getPins().size(); pj++) {\n        Pin* pinj = edi->getPins()[pj];\n\n        Node* curr = pinj->getNode();\n\n        x = curr->getLeft() + 0.5*curr->getWidth() + pinj->getOffsetX();\n        y = curr->getBottom() + 0.5*curr->getHeight() + pinj->getOffsetY();\n\n        old_box.addPt(x,y);\n\n        if (curr == nodes[0]) {\n          x = target_xi + pinj->getOffsetX();\n          y = target_yi + pinj->getOffsetY();\n        } else if (curr == nodes[1]) {\n          x = target_xj + pinj->getOffsetX();\n          y = target_yj + pinj->getOffsetY();\n        }\n\n        new_box.addPt(x,y);\n      }\n\n      old_wl += (old_box.getWidth()+old_box.getHeight());\n      new_wl += (new_box.getWidth()+new_box.getHeight());\n    }\n  }\n  return old_wl - new_wl;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n}  // namespace dpo\n", "meta": {"hexsha": "591ad2bde69fa993c476d61664d92cdbd4a7c242", "size": 13781, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/dpo/src/detailed_hpwl.cxx", "max_stars_repo_name": "akennings/OpenROAD", "max_stars_repo_head_hexsha": "6f2a893b88ee7a28921a1c9a7e02500fc488a05f", "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/dpo/src/detailed_hpwl.cxx", "max_issues_repo_name": "akennings/OpenROAD", "max_issues_repo_head_hexsha": "6f2a893b88ee7a28921a1c9a7e02500fc488a05f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-08T22:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T22:08:46.000Z", "max_forks_repo_path": "src/dpo/src/detailed_hpwl.cxx", "max_forks_repo_name": "akennings/OpenROAD", "max_forks_repo_head_hexsha": "6f2a893b88ee7a28921a1c9a7e02500fc488a05f", "max_forks_repo_licenses": ["BSD-3-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.2740046838, "max_line_length": 82, "alphanum_fraction": 0.4855961106, "num_tokens": 3323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754068280545827, "lm_q2_score": 0.025565214155277263, "lm_q1q2_score": 0.009651908408251145}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// This file is a part of the PadallelFDTD Finite-Difference Time-Domain\n// simulation library. It is released under the MIT License. You should have \n// received a copy of the MIT License along with ParallelFDTD.  If not, see\n// http://www.opensource.org/licenses/mit-license.php\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// For details, see the LICENSE file\n//\n// (C) 2013-2014 Jukka Saarelma\n// Aalto University School of Science\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include \"App.h\"\n\nusing namespace boost::python;\n\nvoid FDTD::App::initializeGeometryPy(boost::python::list indices,\n                                     boost::python::list vertices) {\n  int v_len = (int)boost::python::len(vertices);\n  int i_len = (int)boost::python::len(indices);\n  std::vector<float> std_vertices(v_len, 0.f);\n  std::vector<unsigned int> std_indices(i_len, 0);\n\n  for(int i = 0; i < v_len; i++)\n    std_vertices.at(i) = boost::python::extract<float>(vertices[i]);\n\n  for(int i = 0; i < i_len; i++)\n    std_indices.at(i) = boost::python::extract<unsigned int>(indices[i]);\n\n  this->m_geometry.initialize(std_indices, std_vertices);\n}\n\nvoid FDTD::App::setLayerIndicesPy(boost::python::list indices,\n                                  std::string name) {\n  int i_len = (int)boost::python::len(indices);\n  std::vector<int> std_indices(i_len, 0.f);\n  for(int i = 0; i < i_len; i++)\n    std_indices.at(i) = boost::python::extract<int>(indices[i]);\n\n  this->m_geometry.setLayerIndices(std_indices, name);\n}\n\nvoid FDTD::App::addSurfaceMaterials(boost::python::list material_coefficients,\n                                    unsigned int number_of_surfaces,\n                                    unsigned int number_of_coefficients) {\n  int m_len = (int)boost::python::len(material_coefficients);\n  std::vector<float> std_mat(m_len, 0.f);\n  for(int i = 0; i < m_len; i++)\n    std_mat.at(i) = boost::python::extract<float>(material_coefficients[i]);\n\n  this->m_materials.addMaterials(&std_mat[0], \n                                 number_of_surfaces, \n                                 number_of_coefficients);\n}\n\nvoid FDTD::App::addSourceDataFloat(boost::python::list src_data,\n                                   int num_steps,\n                                   int num_sources) {\n  std::vector<float> std_src_data(num_steps*num_sources, 0.0);\n  for(int j = 0; j < num_sources; j++) {\n    for(int i = 0; i < num_steps; i++) {\n      int idx =j*num_steps+i;\n      std_src_data.at(idx) = boost::python::extract<float>(src_data[idx]);\n    }\n  }\n  this->m_parameters.addInputData(std_src_data);\n}\n\nvoid FDTD::App::addSourceDataDouble(boost::python::list src_data,\n                              int num_steps,\n                              int num_sources) {\n  std::vector<double> std_src_data(num_steps*num_sources, 0.0);\n  for(int j = 0; j < num_sources; j++) {\n    for(int i = 0; i < num_steps; i++) {\n      int idx =j*num_steps+i;\n      std_src_data.at(idx) = boost::python::extract<double>(src_data[idx]);\n    }\n  }\n  this->m_parameters.addInputDataDouble(std_src_data);\n}\n\n\nBOOST_PYTHON_MODULE(libPyFDTD) {\n\n  class_< std::vector<float> >(\"std_vec_float\")\n    .def(vector_indexing_suite< std::vector<float> >() )\n    ;\n\n  class_< std::vector<double> >(\"std_vec_double\")\n    .def(vector_indexing_suite< std::vector<double> >() )\n    ;\n\n  class_<FDTD::App>(\"App\") \n    .def(\"initializeDevices\", &FDTD::App::initializeDevices)  \n    .def(\"initializeGeometryFromFile\", &FDTD::App::initializeGeometryFromFile)\n    .def(\"initializeGeometryPy\", &FDTD::App::initializeGeometryPy)\n    .def(\"setLayerIndices\", &FDTD::App::setLayerIndicesPy)\n    .def(\"addSource\", &FDTD::App::addSource)\n    .def(\"addSourceDataFloat\", &FDTD::App::addSourceDataFloat)\n    .def(\"addSourceDataDouble\", &FDTD::App::addSourceDataDouble)\n    .def(\"addReceiver\", &FDTD::App::addReceiver)\n    .def(\"addSurfaceMaterials\", &FDTD::App::addSurfaceMaterials)\n    .def(\"setSpatialFs\", &FDTD::App::setSpatialFs)\n    .def(\"setNumSteps\", &FDTD::App::setNumSteps )\n    .def(\"setUpdateType\", &FDTD::App::setUpdateType)\n    .def(\"setUniform\", &FDTD::App::setUniformMaterial)\n    .def(\"runVisualization\", &FDTD::App::runVisualization)\n    .def(\"runSimulation\", &FDTD::App::runSimulation)\n    .def(\"runCapture\", &FDTD::App::runCapture)\n    .def(\"setUniformMaterial\", &FDTD::App::setUniformMaterial)\n    .def(\"getResponse\", &FDTD::App::getResponse)\n    .def(\"getResponseDouble\", &FDTD::App::getResponseDouble)\n    .def(\"forcePartitionTo\", &FDTD::App::setForcePartitionTo)\n    .def(\"addSliceToCapture\", &FDTD::App::addSliceToCapture)\n    .def(\"setDouble\", &FDTD::App::setDouble)\n    .def(\"setCapturedB\", &FDTD::App::setCapturedB)\n    .def(\"close\", &FDTD::App::close)\n    .def(\"getMvox\", &FDTD::App::getMvoxPerSec)\n    .def(\"getNumElems\", &FDTD::App::getNumElements)\n    ;\n}\n", "meta": {"hexsha": "daf6732d01701ba09cfe2ad8389408893f3afa78", "size": 5488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AppPy.cpp", "max_stars_repo_name": "juuli/ParallelFDTD", "max_stars_repo_head_hexsha": "ba8fbf14b832c7f4936c952f909c5c47c8056877", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T09:54:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T16:58:12.000Z", "max_issues_repo_path": "src/AppPy.cpp", "max_issues_repo_name": "juuli/ParallelFDTD", "max_issues_repo_head_hexsha": "ba8fbf14b832c7f4936c952f909c5c47c8056877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-31T17:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-29T15:52:47.000Z", "max_forks_repo_path": "src/AppPy.cpp", "max_forks_repo_name": "juuli/ParallelFDTD", "max_forks_repo_head_hexsha": "ba8fbf14b832c7f4936c952f909c5c47c8056877", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T12:33:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T11:14:50.000Z", "avg_line_length": 40.6518518519, "max_line_length": 80, "alphanum_fraction": 0.6386661808, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.04208773031866069, "lm_q1q2_score": 0.009602589333397952}}
{"text": "/**\n * Copyright (c) 2018, University Osnabrück\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 University Osnabrück 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 University Osnabrück 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 \"lvr2/reconstruction/PanoramaNormals.hpp\"\n\n#include \"lvr2/geometry/BaseVector.hpp\"\n#include \"lvr2/geometry/Normal.hpp\"\n#include \"lvr2/io/Progress.hpp\"\n#include \"lvr2/io/Timestamp.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n\nusing std::cout;\nusing std::endl;\n\nnamespace lvr2\n{\n\nusing Vec = BaseVector<float>;\n\nPanoramaNormals::PanoramaNormals(ModelToImage* mti)\n    : m_mti(mti)\n{\n    m_buffer = mti->pointBuffer();\n}\n\nPointBufferPtr PanoramaNormals::computeNormals(int width, int height, bool interpolate)\n{\n    // Create new point buffer and tmp storages\n    PointBufferPtr out_buffer(new PointBuffer);\n    vector<float> pts;\n    vector<float> normals;\n\n    // Get input buffer's points\n    PointBufferPtr in_buffer = m_mti->pointBuffer();\n    size_t w_color;\n    size_t n_inPoints = in_buffer->numPoints();\n    floatArr in_points = in_buffer->getPointArray();\n    ucharArr in_colors = in_buffer->getColorArray(w_color);\n\n    // Reserve memory for output buffers (we need a deep copy)\n    floatArr p_arr(new float[n_inPoints * 3]);\n    floatArr n_arr(new float[n_inPoints * 3]);\n    ucharArr c_arr;\n    if(in_buffer->hasColors())\n    {\n        c_arr = ucharArr(new unsigned char[n_inPoints * 3]);\n    }\n\n    // Get panorama\n    ModelToImage::DepthListMatrix mat;\n    m_mti->computeDepthListMatrix(mat);\n\n    // If the desired neighborhood is larger than 2 x 2 pixels\n    // compute offsets for i und j dimension of the image.\n    int di = 2;\n    if(width > 2)\n    {\n        di = width / 2;\n    }\n\n\n    int dj = 2;\n    if(height > 2)\n    {\n        dj = height / 2;\n    }\n\n    // Compute normals\n    // Create progress output\n    string comment = timestamp.getElapsedTime() + \"Computing normals \";\n    ProgressBar progress(mat.pixels.size(), comment);\n\n\n\n    for(size_t i = 0; i < mat.pixels.size(); i++)\n    {\n        #pragma omp parallel for\n        for(size_t j = 0; j < mat.pixels[i].size(); j++)\n        {\n            // Check if image entry is empty\n            if(mat.pixels[i][j].size() == 0)\n            {\n                continue;\n            }\n\n            // Collect 'neighboring' points\n            vector<ModelToImage::PanoramaPoint> nb;\n\n            // The points at the current position are part of the neighborhood\n            std::copy(mat.pixels[i][j].begin(), mat.pixels[i][j].end(), std::back_inserter(nb));\n\n            for(int off_i = -di; off_i <= di; off_i++)\n            {\n                for(int off_j = -dj; off_j <= dj; off_j++)\n                {\n                    int p_i = i + off_i;\n                    int p_j = j + off_j;\n\n\n                    if(p_i >= 0 && p_i < mat.pixels.size() &&\n                       p_j >= 0 && p_j < mat.pixels[i].size())\n                    {\n                        // We only save the first point as representative\n                        // because using all points from list will likely\n                        // result in undesirable configurations for local\n                        // normal estimation\n                        if(mat.pixels[p_i][p_j].size() > 0)\n                        {\n                            nb.push_back(mat.pixels[p_i][p_j][0]);\n                        }\n                    }\n                }\n            }\n\n            // Compute normal if more than three neighbors where found\n            if(nb.size() > 3)\n            {\n\n\n                // Compute mean\n                Vec mean;\n                for(int i = 0; i < nb.size(); i++)\n                {\n                    // Determine position of geometry in point array\n                    size_t index = nb[i].index * 3;\n\n                    // Get point coordinates\n                    Vec neighbor(in_points[index],\n                                           in_points[index + 1],\n                                           in_points[index + 2]);\n\n                    // Add to mean\n                    mean.x += neighbor.x;\n                    mean.y += neighbor.y;\n                    mean.z += neighbor.z;\n                }\n                mean.x /= nb.size();\n                mean.y /= nb.size();\n                mean.z /= nb.size();\n\n                // Calculate covariance\n                double covariance[9] = {0};\n\n                for(int i = 0; i < nb.size(); i++)\n                {\n                    size_t index = nb[i].index * 3;\n\n                    Vec pt(in_points[index    ] - mean.x,\n                                     in_points[index + 1] - mean.y,\n                                     in_points[index + 3] - mean.z);\n\n                    covariance[4] += pt.y * pt.y;\n                    covariance[7] += pt.y * pt.z;\n                    covariance[8] += pt.z * pt.z;\n\n                    pt.x *= pt.x;\n                    pt.y *= pt.x;\n                    pt.z *= pt.x;\n\n                    covariance[0] += pt.x;\n                    covariance[1] += pt.y;\n                    covariance[6] += pt.z;\n\n                }\n\n                covariance[3] = covariance[1];\n                covariance[2] = covariance[6];\n                covariance[5] = covariance[7];\n\n                for(int i = 0; i < 9; i++)\n                {\n                    covariance[i] /= nb.size();\n                }\n\n                // Compute eigenvalues and eigenvectors using GSL\n                gsl_matrix_view m = gsl_matrix_view_array(covariance, 3, 3);\n                gsl_matrix* evec = gsl_matrix_alloc(3, 3);\n                gsl_vector* eval = gsl_vector_alloc(3);\n\n\n                gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3);\n                gsl_eigen_symmv (&m.matrix, eval, evec, w);\n\n                gsl_eigen_symmv_free (w);\n                gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC);\n\n                gsl_vector_view evec_0 = gsl_matrix_column(evec, 0);\n                float nx = gsl_vector_get(&evec_0.vector, 0);\n                float ny = gsl_vector_get(&evec_0.vector, 1);\n                float nz = gsl_vector_get(&evec_0.vector, 2);\n\n                // Flip normals towards reference point\n                Normal<float> nn(nx, ny, nz);\n                Vec center(0, 0, 0);\n\n                size_t index = mat.pixels[i][j][0].index * 3;\n                Vec p1 = center - Vec(in_points[index], in_points[index + 1], in_points[index + 2]);\n\n                if(Normal<float>(p1) * nn < 0)\n                {\n                    nx *= -1;\n                    ny *= -1;\n                    nz *= -1;\n                }\n\n                for(size_t k = 0; k < mat.pixels[i][j].size(); k++)\n                {\n                    // Assign the same normal to all points\n                    // behind this pixel to preserve the complete\n                    // point cloud\n                    size_t index = mat.pixels[i][j][k].index * 3;\n                    size_t color_index = mat.pixels[i][j][k].index * w_color;\n\n                    // Copy point and normal to target buffer\n                    p_arr[index    ] = in_points[index];\n                    p_arr[index + 1] = in_points[index + 1];\n                    p_arr[index + 2] = in_points[index + 2];\n\n                    if(in_buffer->hasColors())\n                    {\n                        c_arr[index    ] = in_colors[color_index];\n                        c_arr[index + 1] = in_colors[color_index + 1];\n                        c_arr[index + 2] = in_colors[color_index + 2];\n                    }\n\n                    if(!interpolate)\n                    {\n                        n_arr[index    ] = nx;\n                        n_arr[index + 1] = ny;\n                        n_arr[index + 2] = nz;\n                    }\n                }\n            }\n        }\n        ++progress;\n    }\n    cout << endl;\n\n//    if(interpolate)\n//    {\n//        cout << timestamp << \" Interpolating normals\" << endl;\n//        for(size_t i = 0; i < mat.pixels.size(); i++)\n//        {\n//            for(size_t j = 0; j < mat.pixels[i].size(); j++)\n//            {\n//                float x = 0.0f;\n//                float y = 0.0f;\n//                float z = 0.0f;\n//                int np = 0;\n//                for(int off_i = -di; off_i <= di; off_i++)\n//                {\n//                    for(int off_j = -dj; off_j <= dj; off_j++)\n//                    {\n//                        int p_i = i + off_i;\n//                        int p_j = j + off_j;\n\n\n//                        if(p_i >= 0 && p_i < mat.pixels.size() &&\n//                           p_j >= 0 && p_j < mat.pixels[i].size())\n//                        {\n//                            for(size_t k = 0; k < mat.pixels[p_i][p_j].size(); k++)\n//                            {\n//                                size_t index = mat.pixels[p_i][p_j][k].index;\n//                                x += in_points[index];\n//                                y += in_points[index + 1];\n//                                z += in_points[index + 2];\n//                                np++;\n//                            }\n//                        }\n//                    }\n//                }\n//                if(np > 3) // Same condition as above\n//                {\n//                    x /= np;\n//                    y /= np;\n//                    z /= np;\n//                    normals.push_back(x);\n//                    normals.push_back(y);\n//                    normals.push_back(z);\n//                }\n\n//            }\n//        }\n\n//        cout << normals.size() << \" \" << pts.size() << endl;\n//    }\n\n    cout << timestamp << \"Finished normal estimation\" << endl;\n\n    if(in_buffer->hasColors())\n    {\n        out_buffer->setColorArray(c_arr, n_inPoints);\n    }\n    out_buffer->setPointArray(p_arr, n_inPoints);\n    out_buffer->setNormalArray(n_arr, n_inPoints);\n\n    return out_buffer;\n}\n\n} // namespace lvr2\n", "meta": {"hexsha": "f71710bee947c739deb9a9ff5ae8110163700538", "size": 11422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/liblvr2/reconstruction/PanoramaNormals.cpp", "max_stars_repo_name": "uos/lvr", "max_stars_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-06-19T15:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:08:24.000Z", "max_issues_repo_path": "src/liblvr2/reconstruction/PanoramaNormals.cpp", "max_issues_repo_name": "uos/lvr", "max_issues_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:31:25.000Z", "max_forks_repo_path": "src/liblvr2/reconstruction/PanoramaNormals.cpp", "max_forks_repo_name": "uos/lvr", "max_forks_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-04-16T11:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T07:47:44.000Z", "avg_line_length": 34.3003003003, "max_line_length": 100, "alphanum_fraction": 0.4801260725, "num_tokens": 2536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.025178843437900302, "lm_q1q2_score": 0.00959866777422786}}
{"text": "// [[Rcpp::depends(BH)]]\n// [[Rcpp::depends(RcppEigen)]]\n\n#include \"distribution.h\"\n#include <boost/math/distributions/logistic.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/cauchy.hpp>\n#include <boost/math/distributions/extreme_value.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\nusing namespace boost::math;\nusing namespace std;\nusing namespace Rcpp ;\n\ndistribution::distribution(void) {\n  // Rcout << \"Distribution is being created\" << endl;\n}\n\nLogicalVector is_character(DataFrame A) {\n  LogicalVector res(A.cols());\n  for (int column = 0 ; column < A.cols() ; column++){\n    // bool a89 = (TYPEOF(A[column]) == STRSXP);\n    // bool a90 = ( TYPEOF(A[column]) == STRSXP || TYPEOF(A[column]) ==  INTSXP );\n    bool a90 = Rf_isFactor(A[column]) || (TYPEOF(A[column]) == STRSXP);\n    res[column] = a90;\n  }\n  return res;\n}\n\ntemplate <int RTYPE>\nIntegerVector fast_factor_template( const Vector<RTYPE>& x ) {\n  Vector<RTYPE> levs = sort_unique(x);\n  IntegerVector out = match(x, levs);\n  out.attr(\"levels\") = as<CharacterVector>(levs);\n  out.attr(\"class\") = \"integer\";\n  return out;\n}\n\nIntegerVector fast_factor( SEXP x ) {\n  switch( TYPEOF(x) ) {\n  case INTSXP: return fast_factor_template<INTSXP>(x);\n  case REALSXP: return fast_factor_template<REALSXP>(x);\n  case STRSXP: return fast_factor_template<STRSXP>(x);\n  }\n  return R_NilValue;\n}\n\nEigen::VectorXd sort_vector_getindex(Eigen::VectorXd x1) {\n  NumericVector V(x1.data(), x1.data() + x1.size());\n  int x=0;\n  std::iota(V.begin(),V.end(),x++);\n  sort( V.begin(),V.end(), [&](int i,int j){return x1[i]<x1[j];} );\n  Eigen::Map<Eigen::VectorXd> XS(Rcpp::as<Eigen::Map<Eigen::VectorXd> >(V));\n  return XS;\n}\n\nEigen::MatrixXd sorted_rows(Eigen::MatrixXd A)\n{\n  Eigen::VectorXd vec1 = sort_vector_getindex(A.col(0));\n  Eigen::MatrixXd B = A.row(vec1(0));\n  for (int i = 1; i < A.rows(); ++i) {\n    B.conservativeResize(B.rows()+1, B.cols());\n    B.row(B.rows()-1) = A.row(vec1(i));\n  }\n  return B;\n}\n\nNumericMatrix to_dummy(SEXP A)\n{\n  IntegerVector cha_to_fact = fast_factor(A);\n  CharacterVector levs1 = cha_to_fact.attr(\"levels\");\n  int var_lev = levs1.length();\n  NumericMatrix B_Ma(cha_to_fact.length(), var_lev);\n  for (int i_1 = 0; i_1 < cha_to_fact.length(); ++i_1){\n    int col_ind = cha_to_fact[i_1] - 1;\n    B_Ma(i_1, col_ind) = 1;\n  }\n  if (var_lev != 2){\n    B_Ma = B_Ma( _ , Range(0,var_lev-2) );\n  } else {\n    B_Ma = B_Ma( _ , Range(1,var_lev-1) );\n  }\n  return B_Ma;\n}\n\nDataFrame sort_by_user(DataFrame A, SEXP order2)\n{\n  IntegerVector y_1 = (A[0]);\n  StringVector y_n(A.rows());\n  IntegerVector order = (fast_factor(order2));\n\n  CharacterVector levs1 = order.attr(\"levels\");\n  CharacterVector levs2 = y_1.attr(\"levels\");\n  if (is_true(all(levs1 == levs2))) {\n    for (int element_order = 0 ; element_order <= order.length(); element_order++){\n      LogicalVector v0 = (y_1 == order[element_order]);\n      y_n[v0] = element_order;\n    }\n    DataFrame B = A;\n    CharacterVector y_2 = as<CharacterVector>(y_n);\n    B[0] = y_2;\n    return B;\n  }stop(\"The response categories do not match the proposed order of entry\");\n}\n\nstd::string distribution::concatenate(std::string x, std::string level)\n{\n  return (x + \" \" +level);\n}\n\n\nList distribution::select_data(DataFrame x1, std::string response,\n                               StringVector explanatory_complete,\n                               StringVector explanatory_proportional,\n                               SEXP order) {\n\n  int P_c = explanatory_complete.size();\n  if(explanatory_complete[0] == \"NA\"){P_c = 0; }\n  // Rcout << P_c << std::endl;\n  int P_p = explanatory_proportional.size();\n  if(explanatory_proportional[0] == \"NA\"){P_p = 0; }\n  // Rcout << P_p << std::endl;\n  const int N = x1.nrows() ; // Number of observations\n\n  // ADD INTERCEPT\n  Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(x1.rows());\n  x1[\"intercept\"] = Ones1;\n\n  // Zero initialization\n  NumericVector a1(1);\n  a1[0] = x1.findName(response);\n  int n_com_cat = 0;\n  for (int element = 0 ; element < explanatory_complete.size() ; element++ ){\n    if(explanatory_complete[0] != \"NA\"){\n      String element_1 = explanatory_complete[element];\n      a1.push_back(x1.findName(element_1));\n    }else {}\n  }\n\n  // SOLO CONTEO\n  DataFrame x21 = x1[a1];\n  LogicalVector n_com_cat1 = is_character(x21);\n  n_com_cat = sum(n_com_cat1)-1;\n\n  // CONTINUA PARA ANADIR PROPORTIONAL\n  for (int element_p = 0 ; element_p < explanatory_proportional.size() ; element_p++ ){\n    if(explanatory_proportional[0] != \"NA\"){\n      String element_2 = explanatory_proportional[element_p];\n      a1.push_back(x1.findName(element_2));\n    }else {}\n  }\n\n  // SE CREA LA MATRIZ COMPLETA DONDE Y ES LA PRIMERA COLUMNA\n  DataFrame x23 = x1[a1];\n  // Just assign factor vector to categorical order proposed\n  DataFrame x2 = sort_by_user(x23, order); // solo reemplaza por nuevo orden\n\n  LogicalVector character_var = is_character(x2);\n  NumericMatrix X_com_cat_int( x2.nrows() , 1 ) ;\n\n  // Solo para conteo de categoricas completas\n  if(explanatory_complete[0] != \"NA\"){\n    for (int column_char = 1 ; column_char < P_c+1; column_char++){\n      if (character_var(column_char)){\n        NumericMatrix a2 = to_dummy(x2[column_char]);\n        X_com_cat_int = cbind(X_com_cat_int, a2);\n      }else{\n        NumericVector a3 = x2[column_char];\n        X_com_cat_int = cbind(X_com_cat_int, a3);\n      }\n    }\n  }\n  int col_com = X_com_cat_int.cols() - 1;\n  // Rcout << col_com << std::endl;\n\n  NumericMatrix result_m( x2.nrows() , 1 ) ;\n  for (int column_char1 = 0 ; column_char1 < x2.cols(); column_char1++){\n    if(character_var[column_char1] == TRUE){\n      NumericMatrix a8 = to_dummy(x2[column_char1]);\n      result_m = cbind(result_m, a8);\n    }\n    else{\n      NumericVector a9 = x2[column_char1];\n      result_m = cbind(result_m, a9);\n    }\n  }\n\n  IntegerVector a4 = fast_factor(x2[0]);\n  CharacterVector levs1 = a4.attr(\"levels\");\n  int K = levs1.length();\n  int Q = K-1;\n  NumericVector a5 = as<NumericVector>(a4);\n  result_m = result_m(_, Range(1,result_m.cols()-1));\n  result_m = cbind(a5,result_m);\n  Eigen::Map<Eigen::MatrixXd> P = as<Eigen::Map<Eigen::MatrixXd> >(result_m);\n  P = sorted_rows(P);\n  Eigen::MatrixXd P1 = P.rightCols(P.cols()-1);\n  Eigen::MatrixXd Y_ext = P1.leftCols(K-1);\n  Eigen::MatrixXd Com_ext = P1.block(0 , K-1 , P1.rows() , col_com );\n  Eigen::MatrixXd Pro_ext = P1.rightCols(P1.cols() - Com_ext.cols() - Y_ext.cols()) ;\n\n  Eigen::MatrixXd X_EXT(2, 2);\n  Eigen::MatrixXd X_M_Complete_Ext;\n  if(P_c > 0){\n    X_M_Complete_Ext = Eigen::kroneckerProduct(Com_ext,Eigen::MatrixXd::Identity(Q,Q)).eval();\n  }\n  Eigen::MatrixXd X_M_Poportional_Ext(N*Q, Pro_ext.cols()) ;\n  if(P_p > 0){\n    for (int x = -1; x < N-1; ++x) {\n      for (int j = (x+1)*Q ; j < (x+2)*Q; ++j){\n        X_M_Poportional_Ext.row(j) = (Pro_ext).row(x+1);\n      }\n    }\n  }\n  X_EXT.conservativeResize( N*Q , X_M_Complete_Ext.cols()+X_M_Poportional_Ext.cols() );\n  X_EXT << X_M_Complete_Ext, X_M_Poportional_Ext;\n\n  return List::create(_[\"Y_ext\"] = Y_ext,\n                      _[\"X_EXT\"] = X_EXT,\n                      _[\"levs1\"] = levs1);\n}\n\nList distribution::select_data_nested(DataFrame x1, std::string response, std::string actual_response,\n                                      std::string individuals,\n                                      StringVector explanatory_complete,\n                                      StringVector depend_y,\n                                      SEXP order) {\n\n  const int N = x1.nrows() ;\n\n  // ADD INTERCEPT\n  Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(N);\n  x1[\"intercept\"] = Ones1;\n\n  NumericVector a1(1);\n  a1[0] = x1.findName(response);\n  a1.push_back(x1.findName(individuals));\n  a1.push_back(x1.findName(actual_response));\n\n  for (int element = 0 ; element < explanatory_complete.size() ; element++ ){\n    if(explanatory_complete[0] != \"NA\"){\n      String element_1 = explanatory_complete[element];\n      a1.push_back(x1.findName(element_1));\n    }else {}\n  }\n  for (int element = 0 ; element < depend_y.size() ; element++ ){\n    if(depend_y[0] != \"NA\"){\n      String element_1 = depend_y[element];\n      a1.push_back(x1.findName(element_1));\n    }else {}\n  }\n\n  DataFrame x2 = sort_by_user(x1[a1], order); // solo reemplaza por nuevo orden\n  // SOLO PARA CONTEO DE NIVELES RESPUESTA\n  IntegerVector a4 = fast_factor(x2[0]);\n  CharacterVector levs1 = a4.attr(\"levels\");\n  int K = levs1.length();\n  int Q = K-1;\n  NumericVector ref_cat(N) ;\n\n  for (int i = 0 ; i < N; i++){\n    if(a4[i] == K){\n      ref_cat[i] = 1;\n    }else {}\n  }\n\n  CharacterVector response_to_reemplace = x2[0];\n  x2[0] = x2[1];\n  x2[1] = response_to_reemplace; //ahora tienen los nombres opuestos\n\n  LogicalVector choice_ind  = x2[2];\n\n  NumericVector ind_response(N/K);\n  int iter = 0;\n  for (int i = 0; i < choice_ind.length(); i++) {\n    if (choice_ind[i]) {\n      ind_response[iter] = a4[i];\n      iter++;\n    } else {\n    }\n  }\n\n  NumericMatrix Y_ext = to_dummy(ind_response);\n\n  NumericVector a88(1);\n  if(explanatory_complete[0] != \"NA\"){\n    String element_1 = explanatory_complete[0];\n    a88[0] = x2.findName(element_1);\n    for (int element_p = 1 ; element_p < explanatory_complete.size() ; element_p++ ){\n      String element_2 = explanatory_complete[element_p];\n      a88.push_back(x2.findName(element_2));\n    }\n  }else {}\n  NumericMatrix complete_var = internal::convert_using_rfunction(x2[a88], \"as.matrix\");\n\n  NumericVector a89(1);\n  if(depend_y[0] != \"NA\"){\n    String element_1 = depend_y[0];\n    a89[0] = x2.findName(element_1);\n    for (int element_p = 1 ; element_p < depend_y.size() ; element_p++ ){\n      String element_2 = depend_y[element_p];\n      a89.push_back(x2.findName(element_2));\n    }\n  }else {}\n\n  NumericMatrix to_change44 = internal::convert_using_rfunction(x2[a89], \"as.matrix\");\n  to_change44 = cbind(to_change44, ref_cat);\n\n  NumericVector to_change_sub(N);\n  NumericMatrix vec;\n  NumericVector vec1, vec_ref , ref5;\n\n  // AHORA COMENZAMOS EL BUQLE POR INDIVIDUOS\n  for(int vector = 0 ; vector < depend_y.length(); vector++){\n    if(depend_y[0] != \"NA\"){\n      for(int indi = 1 ; indi <= (N/K) ; indi++)\n      {\n        vec = to_change44( Range(K*(indi-1),(indi*K)-1) , _);\n        vec1 = vec( _ , vector);\n        vec_ref = vec( _ , depend_y.size());\n        ref5 = vec1[vec_ref == 1];\n        for (int y = 1; y <= K; ++y)\n        {\n          to_change_sub[K*(indi-1)+y-1] = vec1[y-1] - ref5[0];\n        }\n      }\n      to_change44 = cbind(to_change44, to_change_sub);\n    }else {}\n  }\n  to_change44 = to_change44(_, Range(to_change44.cols()-depend_y.length(), to_change44.cols() - 1));\n  to_change44 = cbind(complete_var, to_change44);\n\n  // ELIMINO LA FILA DE REFERENCIA\n  NumericMatrix x52(Dimension(N- N/K, to_change44.ncol()));\n  NumericMatrix x_to_ext(Dimension(N/K, to_change44.ncol()-depend_y.length()));\n  int iter2 = 0;\n  int def = 0;\n  for (int i = 0; i < to_change44.nrow(); i++) {\n    if (ref_cat[i] != 1) {\n      x52.row(iter2) = to_change44.row(i);\n      iter2++;\n    } else {\n      x_to_ext.row(def) = to_change44.row(i);\n      def++;\n    }\n  }\n  Eigen::Map<Eigen::MatrixXd> P = as<Eigen::Map<Eigen::MatrixXd> >(x_to_ext);\n  Eigen::Map<Eigen::MatrixXd> ext_dep_y = as<Eigen::Map<Eigen::MatrixXd> >(x52);\n\n  Eigen::MatrixXd X_M_Complete_Ext = Eigen::kroneckerProduct(P, Eigen::MatrixXd::Identity(Q,Q)).eval();\n\n\n\n\n  // Eigen::MatrixXd X1 = X_M_Complete_Ext.block(0,0,X_M_Complete_Ext.rows(),Q+1) ;\n  //\n  // Eigen::MatrixXd X2 = X_M_Complete_Ext.block(0,(2*Q),X_M_Complete_Ext.rows(),(1)) ;\n\n\n\n  Eigen::MatrixXd X1 = X_M_Complete_Ext.block(0,0,X_M_Complete_Ext.rows(),Q) ;\n  Eigen::MatrixXd X2(X_M_Complete_Ext.rows(),1);\n  // Eigen::MatrixXd X_mod = X1;\n  //\n  //\n  if(explanatory_complete.size() >= 2){\n\n    for (int element_p1 = 0 ; element_p1 < explanatory_complete.size() - 1; element_p1++ ){\n\n      X2 = X_M_Complete_Ext.block(0,((element_p1+1)*Q),X_M_Complete_Ext.rows(),1) ;\n\n\n      X1.conservativeResize(X1.rows(), X1.cols() + 1);\n\n      X1.col(X1.cols()-1) = X2;\n\n      // X_mod << X_mod, X2;\n    }\n\n  }else{}\n\n  Eigen::MatrixXd X_M_dep_y(X_M_Complete_Ext.rows(),X_M_Complete_Ext.cols()+ depend_y.length());\n\n  X_M_dep_y << X_M_Complete_Ext, ext_dep_y.rightCols(depend_y.length());\n\n  Eigen::MatrixXd X_M_dep_y_alt(X1.rows(),X1.cols()+ depend_y.length());\n\n  X_M_dep_y_alt << X1, ext_dep_y.rightCols(depend_y.length());\n\n  return List::create( _[\"X1\"] = X1,\n                       _[\"X_M_dep_y\"] = X_M_dep_y,\n                       _[\"X_M_dep_y_alt\"] = X_M_dep_y_alt,\n                       _[\"X_M_Complete_Ext\"] = X_M_Complete_Ext,\n                       _[\"Y_ext\"] = Y_ext,\n                       _[\"levs1\"] = levs1\n  );\n}\n\nEigen::VectorXd Logistic::in_open_corner(const Eigen::VectorXd& p) const\n{\n  Eigen::VectorXd pi = p;\n  int J = pi.size() + 1;\n  for(int j=0; j<J-1; ++j)\n  { pi[j] = std::max(_epsilon_0, std::min(pi[j], 1-_epsilon_1)); }\n  double sum = pi.sum();\n  if(sum > 1-_epsilon_1)\n  {\n    for(int j=0; j<J-1; ++j)\n    { pi[j] *= (1.-_epsilon_1)/sum;  }\n  }\n  return pi;\n}\n\nLogistic::Logistic(void) {\n  // Rcout << \"Logistic is being created\" << endl;\n}\ndouble Logistic::cdf_logit(const double& value) const\n{\n  boost::math::logistic dist(0., 1.);\n  return boost::math::cdf(dist, value);\n}\ndouble Logistic::pdf_logit(const double& value) const\n{\n  boost::math::logistic dist(0., 1.);\n  return boost::math::pdf(dist, value);\n}\nEigen::VectorXd Logistic::InverseLinkCumulativeFunction(Eigen::VectorXd vector){\n  boost::math::logistic dist(0., 1.);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = boost::math::cdf(dist, vector(i));\n  return vector;\n}\nEigen::VectorXd Logistic::InverseLinkDensityFunction(Eigen::VectorXd vector){\n  boost::math::logistic dist(0., 1.);\n  for (int i = 0; i<=vector.size()-1; i++)\n    vector(i) = boost::math::pdf(dist, vector(i));\n  return vector;\n}\nEigen::VectorXd Logistic::InverseLinkQuantileFunction(Eigen::VectorXd vector ){\n  boost::math::logistic dist(0., 1.);\n  for (int i = 0; i<=vector.size()-1; i++)\n    vector(i) = quantile(dist, vector(i));\n  return vector;\n}\n\n\nNormal::Normal(void) {\n  // Rcout << \"normal is being created\" << endl;\n}\ndouble Normal::cdf_normal(const double& value) const\n{\n  boost::math::normal norm;\n  return boost::math::cdf(norm, value);\n}\ndouble Normal::pdf_normal(const double& value) const\n{\n  boost::math::normal norm;\n  return boost::math::pdf(norm, value);\n}\n\nEigen::VectorXd Normal::InverseLinkCumulativeFunction(Eigen::VectorXd vector ){\n  boost::math::normal norm;\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = cdf(norm, vector(i));\n  return vector;\n}\nEigen::VectorXd Normal::InverseLinkDensityFunction(Eigen::VectorXd vector ){\n  boost::math::normal norm;\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = pdf(norm, vector(i));\n  return vector;\n}\nEigen::VectorXd Normal::InverseLinkQuantileFunction(Eigen::VectorXd vector ){\n  boost::math::normal norm;\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = quantile(norm, vector(i));\n  return vector;\n}\n\nCauchit::Cauchit(void) {\n  // Rcout << \"Cauchit is being created\" << endl;\n}\n\ndouble Cauchit::cdf_cauchit(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  return cdf(extreme_value, value);\n}\ndouble Cauchit::pdf_cauchit(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  return pdf(extreme_value, value);\n}\n\nEigen::VectorXd Cauchit::InverseLinkCumulativeFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = cdf(extreme_value, vector(i));\n  return vector;\n}\nEigen::VectorXd Cauchit::InverseLinkDensityFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = pdf(extreme_value, vector(i));\n  return vector;\n}\nEigen::VectorXd Cauchit::InverseLinkQuantileFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = quantile(extreme_value, vector(i));\n  return vector;\n}\n\nStudent::Student(void) {\n  // Rcout << \"Student is being created\" << endl;\n}\ndouble Student::cdf_student(const double& value, double df_student) const\n{\n  // double _degrees = 1.35;\n  boost::math::students_t_distribution<> student(df_student);\n  return cdf(student, value);\n}\ndouble Student::pdf_student(const double& value, double df_student) const\n{\n  // double _degrees = 1.35;\n  boost::math::students_t_distribution<> student(df_student);\n  return pdf(student, value);\n}\nEigen::VectorXd Student::InverseLinkCumulativeFunction(Eigen::VectorXd vector ){\n  double _degrees = 2.0;\n  boost::math::students_t_distribution<> student(_degrees);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = cdf(student, vector(i));\n  return vector;\n}\nEigen::VectorXd Student::InverseLinkDensityFunction(Eigen::VectorXd vector ){\n  double _degrees = 2.0;\n  boost::math::students_t_distribution<> student(_degrees);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = pdf(student, vector(i));\n  return vector;\n}\n\nGumbel::Gumbel(void) {\n  // Rcout << \"Gumbel is being created\" << endl;\n}\ndouble Gumbel::cdf_gumbel(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  return cdf(extreme_value, value);\n}\ndouble Gumbel::pdf_gumbel(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  return pdf(extreme_value, value);\n}\nEigen::VectorXd Gumbel::InverseLinkCumulativeFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = cdf(extreme_value, vector(i));\n  return vector;\n}\nEigen::VectorXd Gumbel::InverseLinkDensityFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = pdf(extreme_value, vector(i));\n  return vector;\n}\n\nGompertz::Gompertz(void) {\n  // Rcout << \"Gompertz is being created\" << endl;\n}\n\ndouble Gompertz::pdf_gompertz(const double& value) const\n{ double _mu = 0.0;\n  double _sigma = 1.0;\n\n  return (exp((value - _mu)/ _sigma) *  exp( - exp ((value - _mu)/ _sigma) ) ) / _sigma ; }\n\ndouble Gompertz::cdf_gompertz(const double& value) const\n{ double _mu = 0.0;\n  double _sigma = 1.0;\n  return  1 - exp( - exp((value - _mu) / _sigma) ); }\n\nEigen::VectorXd Gompertz::InverseLinkCumulativeFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = 1-cdf(extreme_value, -vector(i));\n  return vector;\n}\nEigen::VectorXd Gompertz::InverseLinkDensityFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = pdf(extreme_value, -vector(i));\n  return vector;\n}\n\nEigen::VectorXd Gompertz::InverseLinkQuantileFunction(Eigen::VectorXd vector ){\n  double _mu = 0.0;\n  double _sigma = 1.0;\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = _mu + _sigma * log( -log(1-vector(i)) );\n  return vector;\n}\n\n\n\nRCPP_MODULE(exportmod){\n  using namespace Rcpp ;\n  class_<distribution>(\"distribution\")\n    .constructor()\n  ;\n}\n\n// RCPP_MODULE(exportmoddev){\n//   using namespace Rcpp ;\n//   class_<distribution>(\"distribution\")\n//     .constructor()\n//   ;\n//   class_<Logistic>(\"Logistic\")\n//     .derives<distribution>(\"distribution\")\n//     .constructor()\n//     .method( \"InverseLinkCumulativeFunction\", &Logistic::InverseLinkCumulativeFunction )\n//   ;\n// }\n\n", "meta": {"hexsha": "f891cf8498ba5a8f8be7395ee40b109a56767267", "size": 20419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distribution.cpp", "max_stars_repo_name": "ylleonv/pack_27", "max_stars_repo_head_hexsha": "5977bbfbededc415b36a92c4e388c0dafb3d2813", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distribution.cpp", "max_issues_repo_name": "ylleonv/pack_27", "max_issues_repo_head_hexsha": "5977bbfbededc415b36a92c4e388c0dafb3d2813", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distribution.cpp", "max_forks_repo_name": "ylleonv/pack_27", "max_forks_repo_head_hexsha": "5977bbfbededc415b36a92c4e388c0dafb3d2813", "max_forks_repo_licenses": ["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.4622496148, "max_line_length": 103, "alphanum_fraction": 0.651354131, "num_tokens": 6142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.03021458401099221, "lm_q1q2_score": 0.009590902568894357}}
{"text": "/*\r\n * Software License Agreement (BSD License)\r\n *\r\n *  Point Cloud Library (PCL) - www.pointclouds.org\r\n *  Copyright (c) 2010-2012, Willow Garage, Inc.\r\n *\r\n *  All rights reserved.\r\n *\r\n *  Redistribution and use in source and binary forms, with or without\r\n *  modification, are permitted provided that the following conditions\r\n *  are met:\r\n *\r\n *   * Redistributions of source code must retain the above copyright\r\n *     notice, this list of conditions and the following disclaimer.\r\n *   * Redistributions in binary form must reproduce the above\r\n *     copyright notice, this list of conditions and the following\r\n *     disclaimer in the documentation and/or other materials provided\r\n *     with the distribution.\r\n *   * Neither the name of Willow Garage, Inc. nor the names of its\r\n *     contributors may be used to endorse or promote products derived\r\n *     from this software without specific prior written permission.\r\n *\r\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\r\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\r\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\r\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\r\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n *  POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#ifndef FAAT_PCL_RECOGNITION_GRAPH_GEOMETRIC_CONSISTENCY_IMPL_H_\r\n#define FAAT_PCL_RECOGNITION_GRAPH_GEOMETRIC_CONSISTENCY_IMPL_H_\r\n\r\n#include \"v4r/common/graph_geometric_consistency.h\"\r\n#include <pcl/registration/correspondence_types.h>\r\n#include <pcl/registration/correspondence_rejection_sample_consensus.h>\r\n#include <pcl/common/io.h>\r\n#include <pcl/common/time.h>\r\n#include <boost/unordered_map.hpp>\r\n#include <boost/graph/connected_components.hpp>\r\n#include <boost/graph/copy.hpp>\r\n#include <boost/graph/biconnected_components.hpp>\r\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\r\n#include <exception>\r\n\r\nstruct V4R_EXPORTS ExtendedClique\r\n{\r\n    std::vector<size_t> * correspondences_;\r\n    float avg_descriptor_distance_;\r\n    float avg_pair_3D_distance_;\r\n    float normalized_clique_size_;\r\n    float avg_pair_3D_distance_unnormalized_;\r\n    float far_away_correspondences_weight_;\r\n};\r\n\r\nbool less_clique_vectors (const std::vector<size_t> * a, const std::vector<size_t> * b);\r\nbool best_clique_vectors (const std::pair<float, std::vector<size_t> *> a, const std::pair<float, std::vector<size_t> *> b);\r\nbool best_extended_cliques (const ExtendedClique & a, const ExtendedClique & b);\r\nbool gcGraphCorrespSorter (pcl::Correspondence i, pcl::Correspondence j);\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nbool\r\ngcGraphCorrespSorter (pcl::Correspondence i, pcl::Correspondence j)\r\n{\r\n    return (i.distance < j.distance);\r\n}\r\n\r\nstruct V4R_EXPORTS ViewD\r\n{\r\n    size_t idx_;\r\n    size_t degree_;\r\n\r\n    bool\r\n    operator< (const ViewD & j) const\r\n    {\r\n        if (degree_ == j.degree_)\r\n            return (idx_ < j.idx_);\r\n\r\n        return degree_ > j.degree_;\r\n    }\r\n};\r\n\r\nstruct V4R_EXPORTS vertexDegreeSorter\r\n{\r\n    bool\r\n    operator() (const ViewD & i, const ViewD & j) const\r\n    {\r\n        return i < j;\r\n    }\r\n};\r\n\r\ntemplate<typename Graph>\r\nclass V4R_EXPORTS save_cliques\r\n{\r\n\r\npublic:\r\n    /*save_cliques (std::size_t& max, std::size_t& maximum_clique, std::size_t& n_cliques, std::vector<std::vector<void *> *> & cliquess) :\r\n     min_size (max), maximum (maximum_clique), n_cliques (n_cliques), cliques (cliquess)\r\n     {\r\n     }*/\r\n\r\n    save_cliques (std::size_t& max, std::size_t& maximum_clique, std::size_t& n_cliques, std::vector<std::vector<size_t> *> & cliquess) :\r\n        min_size (max), maximum (maximum_clique), n_cliques (n_cliques), cliques (cliquess)\r\n    {\r\n    }\r\n\r\n    template<typename Clique, typename Graph2>\r\n    inline void\r\n    clique (const Clique& c, Graph2& g)\r\n    {\r\n\r\n        if (c.size () >= min_size)\r\n        {\r\n            BOOST_USING_STD_MAX();\r\n            maximum = std::max BOOST_PREVENT_MACRO_SUBSTITUTION (maximum, c.size());\r\n\r\n            //save clique...\r\n            typename Clique::const_iterator i, end = c.end ();\r\n            //std::vector<void *> * cc = new std::vector<void *> (c.size ());\r\n            std::vector<size_t> * cc = new std::vector<size_t> (c.size ());\r\n            cliques.push_back (cc);\r\n            size_t p;\r\n            for (i = c.begin (); i != end; ++i, ++p)\r\n            {\r\n                //cc->at (p) = static_cast<void *> (*i);\r\n                cc->at (p) = (*i);\r\n            }\r\n\r\n            n_cliques++;\r\n        }\r\n        else\r\n        {\r\n            return;\r\n        }\r\n\r\n        // Simply assert that each vertex in the clique is connected\r\n        // to all others in the clique.\r\n        /*typename Clique::const_iterator i, j, end = c.end();\r\n         for(i = c.begin(); i != end; ++i) {\r\n         for(j = c.begin(); j != end; ++j) {\r\n         if(i != j) {\r\n         BOOST_ASSERT(edge(*i, *j, g).second);\r\n         }\r\n         }\r\n         }*/\r\n    }\r\n\r\n    std::size_t& min_size;\r\n    std::size_t& maximum;\r\n    std::size_t& n_cliques;\r\n    //std::vector<std::vector<void *> *> & cliques;\r\n    std::vector<std::vector<size_t> *> & cliques;\r\n};\r\n\r\nclass FAATPCL_CliquesException: public std::exception\r\n{\r\n    virtual const char* what() const throw()\r\n    {\r\n        return \"My exception happened\";\r\n    }\r\n} myex;\r\n\r\ntemplate<typename Graph>\r\nclass V4R_EXPORTS Tomita\r\n{\r\n    typedef std::set<typename boost::graph_traits<Graph>::vertex_descriptor> SetType;\r\n    typedef std::vector<typename boost::graph_traits<Graph>::vertex_descriptor> VectorType;\r\n    std::vector<VectorType *> cliques_found_;\r\n    size_t min_clique_size_;\r\n    typedef boost::unordered_map<typename boost::graph_traits<Graph>::vertex_descriptor, size_t> MapType;\r\n    MapType used_ntimes_in_cliques_;\r\n    std::vector<SetType> nnbrs;\r\n    float max_time_allowed_;\r\n    pcl::StopWatch time_elapsed_;\r\n    bool max_time_reached_;\r\n\r\n    void\r\n    addClique (VectorType & clique)\r\n    {\r\n        if (clique.size () >= min_clique_size_)\r\n        {\r\n            VectorType * vt = new VectorType (clique);\r\n            cliques_found_.push_back (vt);\r\n            for (size_t i = 0; i < clique.size (); i++)\r\n            {\r\n                used_ntimes_in_cliques_[clique[i]]++;\r\n            }\r\n\r\n        }\r\n    }\r\n\r\n    void\r\n    printSet (SetType & s)\r\n    {\r\n        typename SetType::iterator vertexIt, vertexEnd;\r\n        SetType tmp;\r\n\r\n        vertexIt = s.begin ();\r\n        vertexEnd = s.end ();\r\n\r\n        for (; vertexIt != vertexEnd; ++vertexIt)\r\n        {\r\n            std::cout << *vertexIt + 1 << \" \";\r\n        }\r\n\r\n        std::cout << std::endl;\r\n    }\r\n    //_extend(nnbrs,cand,done,clique_so_far,cliques);\r\n    void\r\n    extend (SetType & cand, SetType & done, VectorType & clique_so_far)\r\n    {\r\n        SetType small_cand, pivot_nbrs;\r\n        int maxconn = -1;\r\n        size_t num_cand = cand.size ();\r\n\r\n        //iterate over done and compute maximum intersection between candidates and the adjacents of done (nnbrs)\r\n        typename SetType::iterator vertexIt, vertexEnd;\r\n        SetType tmp;\r\n\r\n        vertexIt = done.begin ();\r\n        vertexEnd = done.end ();\r\n\r\n        for (; vertexIt != vertexEnd; ++vertexIt)\r\n        {\r\n            std::set_intersection (cand.begin (), cand.end (), nnbrs[*vertexIt].begin (), nnbrs[*vertexIt].end (), std::inserter (tmp, tmp.begin ()));\r\n\r\n            if (static_cast<int> (tmp.size ()) > maxconn)\r\n            {\r\n                maxconn = static_cast<int> (tmp.size ());\r\n                pivot_nbrs = tmp;\r\n                if (maxconn == (int)num_cand)\r\n                {\r\n                    //All possible cliques already found\r\n                    return;\r\n                }\r\n            }\r\n\r\n            tmp.clear ();\r\n        }\r\n\r\n        //same for candidates\r\n        vertexIt = cand.begin ();\r\n        vertexEnd = cand.end ();\r\n\r\n        for (; vertexIt != vertexEnd; ++vertexIt)\r\n        {\r\n            std::set_intersection (cand.begin (), cand.end (), nnbrs[*vertexIt].begin (), nnbrs[*vertexIt].end (), std::inserter (tmp, tmp.begin ()));\r\n\r\n            if (static_cast<int> (tmp.size ()) > maxconn)\r\n            {\r\n                maxconn = static_cast<int> (tmp.size ());\r\n                pivot_nbrs = tmp;\r\n            }\r\n            tmp.clear ();\r\n        }\r\n\r\n        std::set_difference (cand.begin (), cand.end (), pivot_nbrs.begin (), pivot_nbrs.end (), std::inserter (small_cand, small_cand.begin ()));\r\n        vertexIt = small_cand.begin ();\r\n        vertexEnd = small_cand.end ();\r\n\r\n        for (; vertexIt != vertexEnd; ++vertexIt)\r\n        {\r\n            cand.erase (*vertexIt);\r\n            clique_so_far.push_back (*vertexIt);\r\n            SetType new_cand, new_done;\r\n            std::set_intersection (cand.begin (), cand.end (), nnbrs[*vertexIt].begin (), nnbrs[*vertexIt].end (),\r\n                    std::inserter (new_cand, new_cand.begin ()));\r\n\r\n            std::set_intersection (done.begin (), done.end (), nnbrs[*vertexIt].begin (), nnbrs[*vertexIt].end (),\r\n                    std::inserter (new_done, new_done.begin ()));\r\n\r\n            if (new_done.size () == 0 && new_cand.size () == 0)\r\n                addClique (clique_so_far);\r\n            else if (new_done.size () == 0 && (new_cand.size () == 1))\r\n            {\r\n                if ((clique_so_far.size () + 1) >= min_clique_size_)\r\n                {\r\n                    VectorType tt = clique_so_far;\r\n                    tt.push_back (*(new_cand.begin ()));\r\n                    addClique (tt);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                float t_elapsed = static_cast<float>(time_elapsed_.getTime());\r\n                if(t_elapsed > max_time_allowed_)\r\n                {\r\n                    max_time_reached_ = true;\r\n                    return;\r\n                }\r\n\r\n                extend (new_cand, new_done, clique_so_far);\r\n            }\r\n\r\n            clique_so_far.erase (clique_so_far.begin () + (clique_so_far.size () - 1));\r\n            done.insert (*vertexIt);\r\n        }\r\n    }\r\n\r\npublic:\r\n\r\n    Tomita (size_t mins = 3)\r\n    {\r\n        min_clique_size_ = mins;\r\n        max_time_allowed_ = std::numeric_limits<float>::infinity();\r\n        max_time_reached_ = false;\r\n    }\r\n\r\n    bool\r\n    getMaxTimeReached()\r\n    {\r\n        return max_time_reached_;\r\n    }\r\n\r\n    void\r\n    setMaxTimeAllowed(float t)\r\n    {\r\n        max_time_allowed_ = t;\r\n    }\r\n\r\n    void\r\n    find_cliques (Graph & G, size_t num_v)\r\n    {\r\n        SetType cand, done;\r\n        VectorType clique_so_far;\r\n        nnbrs.clear ();\r\n        used_ntimes_in_cliques_.clear ();\r\n        cliques_found_.clear ();\r\n        time_elapsed_.reset();\r\n        max_time_reached_ = false;\r\n\r\n        typename boost::graph_traits<Graph>::vertex_iterator vertexIt, vertexEnd;\r\n        boost::tie (vertexIt, vertexEnd) = vertices (G);\r\n        nnbrs.resize (num_v);\r\n\r\n        size_t i = 0;\r\n        for (; vertexIt != vertexEnd; ++vertexIt, ++i)\r\n        {\r\n            typename boost::graph_traits<Graph>::adjacency_iterator vi, vi_end;\r\n            size_t k = 0;\r\n            for (boost::tie (vi, vi_end) = boost::adjacent_vertices (*vertexIt, G); vi != vi_end; ++vi, ++k)\r\n            {\r\n                nnbrs[i].insert (*vi);\r\n                cand.insert (*vi);\r\n            }\r\n\r\n            used_ntimes_in_cliques_[*vertexIt] = 0;\r\n        }\r\n\r\n        extend (cand, done, clique_so_far);\r\n    }\r\n\r\n    size_t\r\n    getNumCliquesFound ()\r\n    {\r\n        return cliques_found_.size ();\r\n    }\r\n\r\n    void\r\n    getCliques (std::vector<VectorType *> & cliques)\r\n    {\r\n        cliques = cliques_found_;\r\n    }\r\n};\r\n\r\n\r\nbool\r\nless_clique_vectors (const std::vector<size_t> * a, const std::vector<size_t> * b)\r\n{\r\n    return a->size () < b->size ();\r\n}\r\n\r\nbool\r\nbest_clique_vectors (const std::pair<float, std::vector<size_t> *> a,\r\n                     const std::pair<float, std::vector<size_t> *> b)\r\n{\r\n    if(a.second->size() == b.second->size())\r\n    {\r\n        return a.first > b.first;\r\n    }\r\n\r\n    return a.second->size () > b.second->size ();\r\n}\r\n\r\nbool\r\nbest_extended_cliques (const ExtendedClique & a,\r\n                       const ExtendedClique & b)\r\n{\r\n    /*float a_value = static_cast<float>(a.correspondences_->size()) * 0.5f + a.avg_descriptor_distance_ * 0.25f + a.avg_pair_3D_distance_ * 0.25f;\r\n    float b_value = static_cast<float>(b.correspondences_->size()) * 0.5f + b.avg_descriptor_distance_ * 0.25f + b.avg_pair_3D_distance_ * 0.25f;*/\r\n\r\n    /*float a_value = a.avg_pair_3D_distance_ * 0.5f + a.avg_descriptor_distance_ * 0.5f;\r\n    float b_value = b.avg_pair_3D_distance_ * 0.5f + b.avg_descriptor_distance_ * 0.5f;*/\r\n\r\n    /*float a_value = a.avg_pair_3D_distance_ * 0.5f;\r\n    float b_value = b.avg_pair_3D_distance_ * 0.5f;*/\r\n\r\n    /*float a_value = static_cast<float>(a.normalized_clique_size_) * 0.5f + a.avg_pair_3D_distance_ * 0.5f;\r\n    float b_value = static_cast<float>(b.normalized_clique_size_) * 0.5f + b.avg_pair_3D_distance_ * 0.5f;*/\r\n\r\n    /*float a_value = static_cast<float>(a.normalized_clique_size_) * 0.25f + a.avg_descriptor_distance_ * 0.25f + a.avg_pair_3D_distance_ * 0.25f + a.far_away_correspondences_weight_ * 0.25f;\r\n    float b_value = static_cast<float>(b.normalized_clique_size_) * 0.25f + b.avg_descriptor_distance_ * 0.25f + b.avg_pair_3D_distance_ * 0.25f + b.far_away_correspondences_weight_ * 0.25f;*/\r\n\r\n    float a_value = static_cast<float>(a.normalized_clique_size_) * 0.25f + a.avg_descriptor_distance_ * 0.25f; //+ a.far_away_correspondences_weight_ * 0.1f;\r\n    float b_value = static_cast<float>(b.normalized_clique_size_) * 0.25f + b.avg_descriptor_distance_ * 0.25f; //+ b.far_away_correspondences_weight_ * 0.1f;\r\n\r\n    return a_value > b_value;\r\n}\r\n\r\ntemplate<typename PointModelT, typename PointSceneT>\r\nvoid\r\nv4r::GraphGeometricConsistencyGrouping<PointModelT, PointSceneT>::cleanGraph2(GraphGGCG & g, size_t gc_thres)\r\n{\r\n    typename boost::graph_traits<GraphGGCG>::vertex_iterator vertexIt, vertexEnd;\r\n    std::vector<typename boost::graph_traits<GraphGGCG>::vertex_descriptor> to_be_removed;\r\n\r\n    do\r\n    {\r\n        to_be_removed.clear();\r\n        boost::tie (vertexIt, vertexEnd) = vertices (g);\r\n        for (; vertexIt != vertexEnd; ++vertexIt)\r\n        {\r\n            size_t deg = boost::out_degree (*vertexIt, g);\r\n\r\n            if ((deg > 0) && (deg < (gc_thres - 1)))\r\n                to_be_removed.push_back (*vertexIt);\r\n        }\r\n\r\n        for (size_t i = 0; i < to_be_removed.size (); i++)\r\n            clear_vertex (to_be_removed[i], g);\r\n\r\n    } while(to_be_removed.size() > 0);\r\n}\r\n\r\ntemplate<typename PointModelT, typename PointSceneT>\r\nvoid\r\nv4r::GraphGeometricConsistencyGrouping<PointModelT, PointSceneT>::cleanGraph(GraphGGCG & g, size_t gc_thres)\r\n{\r\n    cleanGraph2(g, gc_thres);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\ntemplate<typename PointModelT, typename PointSceneT>\r\nvoid\r\nv4r::GraphGeometricConsistencyGrouping<PointModelT, PointSceneT>::clusterCorrespondences (std::vector<pcl::Correspondences> &model_instances)\r\n{\r\n  try\r\n  {\r\n    model_instances.clear ();\r\n    found_transformations_.clear ();\r\n\r\n    //for the old gc...\r\n    std::sort (model_scene_corrs_.begin (), model_scene_corrs_.end (), gcGraphCorrespSorter);\r\n\r\n    if (model_scene_corrs_.empty())\r\n        throw std::runtime_error(\"[pcl::GeometricConsistencyGrouping::clusterCorrespondences()] Error! Correspondences not set, please set them before calling again this function.\\n\");\r\n\r\n    //temp copy of scene cloud with the type cast to ModelT in order to use Ransac\r\n    PointCloudPtr temp_scene_cloud_ptr (new PointCloud ());\r\n    pcl::copyPointCloud<PointSceneT, PointModelT> (*scene_, *temp_scene_cloud_ptr);\r\n\r\n    GraphGGCG correspondence_graph (model_scene_corrs_.size ());\r\n    float min_dist_for_cluster = param_.gc_size_ * param_.dist_for_cluster_factor_;\r\n\r\n    for (size_t k = 0; k < model_scene_corrs_.size (); ++k)\r\n    {\r\n        int scene_index_k = model_scene_corrs_[k].index_match;\r\n        int model_index_k = model_scene_corrs_[k].index_query;\r\n        const Eigen::Vector3f& scene_point_k = scene_->at (scene_index_k).getVector3fMap ();\r\n        const Eigen::Vector3f& model_point_k = input_->at (model_index_k).getVector3fMap ();\r\n        const Eigen::Vector3f& scene_normal_k = scene_normals_->at (scene_index_k).getNormalVector3fMap ();\r\n        const Eigen::Vector3f& model_normal_k = input_normals_->at (model_index_k).getNormalVector3fMap ();\r\n\r\n        for (size_t j = (k + 1); j < model_scene_corrs_.size (); ++j)\r\n        {\r\n            int scene_index_j = model_scene_corrs_[j].index_match;\r\n            int model_index_j = model_scene_corrs_[j].index_query;\r\n\r\n            //same scene or model point constraint\r\n            if(scene_index_j == scene_index_k || model_index_j == model_index_k)\r\n                continue;\r\n\r\n            const Eigen::Vector3f& scene_point_j = scene_->at (scene_index_j).getVector3fMap ();\r\n            const Eigen::Vector3f& model_point_j = input_->at (model_index_j).getVector3fMap ();\r\n\r\n            const Eigen::Vector3f& scene_normal_j = scene_normals_->at (scene_index_j).getNormalVector3fMap ();\r\n            const Eigen::Vector3f& model_normal_j = input_normals_->at (model_index_j).getNormalVector3fMap ();\r\n\r\n            Eigen::Vector3f dist_trg = model_point_k - model_point_j;\r\n            Eigen::Vector3f dist_ref = scene_point_k - scene_point_j;\r\n\r\n            //minimum distance constraint\r\n            if ((dist_trg.norm () < min_dist_for_cluster) || (dist_ref.norm () < min_dist_for_cluster))\r\n                continue;\r\n\r\n            double distance = fabs (dist_trg.norm () - dist_ref.norm());\r\n            double dot_distance = 0;\r\n            if (pcl_isnan(scene_normal_k.dot (scene_normal_j)) || pcl_isnan(model_normal_k.dot (model_normal_j)))\r\n                dot_distance = 0.f;\r\n            else\r\n            {\r\n                float dot_model = model_normal_k.dot (model_normal_j);\r\n                dot_distance = std::abs (scene_normal_k.dot (scene_normal_j) - dot_model);\r\n            }\r\n\r\n            //Model normals should be consistently oriented! otherwise reject!\r\n            float dot_distance_model = model_normal_k.dot (model_normal_j);\r\n            if(dot_distance_model < -0.1f)\r\n                continue;\r\n\r\n            //gc constraint and dot_product constraint!\r\n            if ((distance < param_.gc_size_) && (dot_distance <= param_.thres_dot_distance_))\r\n                boost::add_edge (k, j, correspondence_graph);\r\n        }\r\n    }\r\n\r\n\r\n    typename boost::property_map < GraphGGCG, edge_component_t>::type components = get(edge_component, correspondence_graph);\r\n    size_t n_cc = biconnected_components(correspondence_graph, components);\r\n\r\n    if(n_cc < 1)\r\n        return;\r\n\r\n    std::vector<size_t> model_instances_kept_indices;\r\n\r\n    std::vector< std::set<size_t> > unique_vertices_per_cc (n_cc);\r\n    std::vector<size_t> cc_sizes (n_cc, 0);\r\n\r\n    typename boost::graph_traits<GraphGGCG>::edge_iterator edgeIt, edgeEnd;\r\n    boost::tie (edgeIt, edgeEnd) = edges (correspondence_graph);\r\n    for (; edgeIt != edgeEnd; ++edgeIt)\r\n    {\r\n        int c = components[*edgeIt];\r\n        unique_vertices_per_cc[c].insert(boost::source(*edgeIt, correspondence_graph));\r\n        unique_vertices_per_cc[c].insert(boost::target(*edgeIt, correspondence_graph));\r\n    }\r\n\r\n    for(size_t i=0; i < unique_vertices_per_cc.size(); i++)\r\n        cc_sizes[i] = unique_vertices_per_cc[i].size();\r\n\r\n    pcl::registration::CorrespondenceRejectorSampleConsensus<PointModelT> corr_rejector;\r\n    corr_rejector.setMaximumIterations (10000);\r\n    corr_rejector.setInlierThreshold (param_.ransac_threshold_);\r\n    corr_rejector.setInputSource (input_);\r\n    corr_rejector.setInputTarget (temp_scene_cloud_ptr);\r\n    corr_rejector.setSaveInliers(true);\r\n\r\n    //Go through the connected components and decide whether to use CliqueGC or usualGC or ignore (cc_sizes[i] < gc_threshold_)\r\n    //Decision based on the number of vertices in the connected component and graph arbocity...\r\n\r\n    //std::cout << \"Number of connected components over threshold...\" << over_gc << std::endl;\r\n    //    std::cout << \"Number of connected components...\" << n_cc << std::endl;\r\n    size_t analyzed_ccs = 0;\r\n    std::vector<bool> cliques_computation_possible_;\r\n    cliques_computation_possible_.resize(n_cc, param_.use_graph_);\r\n    for (size_t c = 0; c < n_cc; c++)\r\n    {\r\n        //ignore if not enough vertices...\r\n        size_t num_v_in_cc = cc_sizes[c];\r\n        if (num_v_in_cc < param_.gc_threshold_)\r\n            continue;\r\n\r\n        analyzed_ccs++;\r\n\r\n        GraphGGCG connected_graph(correspondence_graph);\r\n\r\n        //iterate over edges and remove those not belonging to this biconnected component\r\n        boost::tie (edgeIt, edgeEnd) = edges (connected_graph);\r\n        for (; edgeIt != edgeEnd; ++edgeIt)\r\n        {\r\n            if (components[*edgeIt] != c)\r\n                boost::remove_edge(*edgeIt, connected_graph);\r\n        }\r\n\r\n        //std::cout << \"Num edges connnected component:\" << boost::num_edges(connected_graph) << std::endl;\r\n        //visualizeGraph(connected_graph, \"connected component\");\r\n\r\n        float arboricity = num_edges (connected_graph) / static_cast<float>(num_v_in_cc - 1);\r\n        //std::cout << \"arboricity:\" << arboricity << \" num_v:\" << num_v_in_cc << \" edges:\" << num_edges (connected_graph) << std::endl;\r\n        //std::vector<std::pair<int, int> > edges_used;\r\n        std::set<size_t> correspondences_used;\r\n\r\n        std::vector< std::vector<size_t> > correspondence_to_instance;\r\n        if(param_.prune_by_CC_)\r\n            correspondence_to_instance.resize(model_scene_corrs_.size());\r\n\r\n        if (cliques_computation_possible_[c] && arboricity < 25 /*&& (num_v_in_cc < 400) && (num_edges (connected_graph) < 8000) && arboricity < 10*/)\r\n        {\r\n            //std::cout << \"Using cliques\" << std::endl;\r\n            //std::cout << \"N edges: \" << num_edges (connected_graph) << \" vertices:\" << num_v_in_cc << \" arboricity:\" << arboricity <<  std::endl;\r\n\r\n            std::vector<std::vector<size_t> *> cliques;\r\n            {\r\n                //pcl::ScopeTime t (\"tomita cliques...\");\r\n                Tomita<GraphGGCG> tom (param_.gc_threshold_);\r\n                tom.setMaxTimeAllowed(param_.max_time_allowed_cliques_comptutation_);\r\n                tom.find_cliques (connected_graph, model_scene_corrs_.size ());\r\n                if(tom.getMaxTimeReached())\r\n                {\r\n                    std::cout << \"Max time ( \" << std::setprecision(2) << param_.max_time_allowed_cliques_comptutation_ << \" ms) reached during clique computation\" << std::endl;\r\n                    cliques_computation_possible_[c] = false;\r\n                    c--;\r\n                    analyzed_ccs--;\r\n\r\n                    //free memory for cliques\r\n                    tom.getCliques (cliques);\r\n                    for (size_t p = 0; p < cliques.size (); p++)\r\n                        delete cliques[p];\r\n\r\n                    continue;\r\n                }\r\n                //std::cout << \"Number of cliques found by tomita...\" << tom.getNumCliquesFound () << std::endl;\r\n                tom.getCliques (cliques);\r\n            }\r\n\r\n            std::vector< ExtendedClique > extended_cliques;\r\n            std::vector<std::pair<float, std::vector<size_t> * > > cliques_with_average_weight;\r\n            for(size_t k = 0; k < cliques.size(); k++)\r\n            {\r\n                float avg_dist = 0.f;\r\n                float max_dist_ = 0.03f; //3 centimeters\r\n                float far_away_average_weight_ = 0.f;\r\n\r\n                for(size_t jj=0; jj < cliques[k]->size(); jj++)\r\n                    avg_dist += model_scene_corrs_[ cliques[k]->at(jj) ].distance;\r\n\r\n                avg_dist /= static_cast<float>(cliques[k]->size());\r\n                cliques_with_average_weight.push_back(std::make_pair(avg_dist, cliques[k]));\r\n\r\n                float avg_3D_dist = 0.f;\r\n\r\n                for(size_t jj=0; jj < cliques[k]->size(); jj++)\r\n                {\r\n\r\n                    int scene_index_j = model_scene_corrs_[ cliques[k]->at(jj) ].index_match;\r\n                    int model_index_j = model_scene_corrs_[ cliques[k]->at(jj) ].index_query;\r\n                    const Eigen::Vector3f& scene_point_j = scene_->at (scene_index_j).getVector3fMap ();\r\n                    const Eigen::Vector3f& model_point_j = input_->at (model_index_j).getVector3fMap ();\r\n\r\n                    for(size_t kk=(jj+1); kk < cliques[k]->size(); kk++)\r\n                    {\r\n                        //for each pair, average 3D distance\r\n\r\n                        int scene_index_k = model_scene_corrs_[ cliques[k]->at(kk) ].index_match;\r\n                        int model_index_k = model_scene_corrs_[ cliques[k]->at(kk) ].index_query;\r\n\r\n                        const Eigen::Vector3f& scene_point_k = scene_->at (scene_index_k).getVector3fMap ();\r\n                        const Eigen::Vector3f& model_point_k = input_->at (model_index_k).getVector3fMap ();\r\n\r\n                        Eigen::Vector3f dist_trg = model_point_k - model_point_j;\r\n                        Eigen::Vector3f dist_ref = scene_point_k - scene_point_j;\r\n\r\n                        float distance_ref_norm = dist_ref.norm();\r\n                        float distance = fabs (dist_trg.norm () - dist_ref.norm());\r\n                        avg_3D_dist += distance;\r\n\r\n                        far_away_average_weight_ += std::min((distance_ref_norm / max_dist_), 1.f);\r\n                    }\r\n                }\r\n\r\n                avg_3D_dist /= (static_cast<float>(cliques[k]->size()) * static_cast<float>(cliques[k]->size() - 1)) / 2.f;\r\n                far_away_average_weight_ /= (static_cast<float>(cliques[k]->size()) * static_cast<float>(cliques[k]->size() - 1)) / 2.f;\r\n\r\n                ExtendedClique ec;\r\n                ec.correspondences_ = cliques[k];\r\n                ec.avg_pair_3D_distance_ = avg_3D_dist;\r\n                ec.avg_descriptor_distance_ = avg_dist;\r\n                ec.avg_pair_3D_distance_unnormalized_ = avg_3D_dist;\r\n                ec.far_away_correspondences_weight_ = far_away_average_weight_;\r\n                extended_cliques.push_back(ec);\r\n            }\r\n\r\n            float max_avg_3D_dist = 0;\r\n            float max_avg_descriptor_dist = 0;\r\n            size_t max_clique_size = 0;\r\n\r\n            for(size_t k = 0; k < cliques.size(); k++)\r\n            {\r\n                if(extended_cliques[k].avg_pair_3D_distance_ > max_avg_3D_dist)\r\n                    max_avg_3D_dist = extended_cliques[k].avg_pair_3D_distance_;\r\n\r\n                if(extended_cliques[k].correspondences_->size() > max_clique_size)\r\n                    max_clique_size = extended_cliques[k].correspondences_->size();\r\n\r\n                if(extended_cliques[k].avg_descriptor_distance_ > max_avg_descriptor_dist)\r\n                    max_avg_descriptor_dist = extended_cliques[k].avg_descriptor_distance_;\r\n            }\r\n\r\n            for(size_t k = 0; k < cliques.size(); k++)\r\n            {\r\n                extended_cliques[k].avg_pair_3D_distance_ = 1.f - (extended_cliques[k].avg_pair_3D_distance_ / max_avg_3D_dist);\r\n                extended_cliques[k].avg_descriptor_distance_ = 1.f - (extended_cliques[k].avg_descriptor_distance_ / max_avg_descriptor_dist);\r\n                extended_cliques[k].normalized_clique_size_ = static_cast<float>(extended_cliques[k].correspondences_->size()) / static_cast<float>(max_clique_size);\r\n            }\r\n\r\n            //process cliques to remove similar ones...\r\n            //sort (cliques.begin (), cliques.end (), less_clique_vectors); //cliques are sorted in increasing order (smaller cliques first)\r\n\r\n            /*sort (cliques_with_average_weight.begin (), cliques_with_average_weight.end (), best_clique_vectors);\r\n        for(size_t k = 0; k < cliques.size(); k++)\r\n        {\r\n            cliques[k] = cliques_with_average_weight[k].second;\r\n        }*/\r\n\r\n            sort (extended_cliques.begin (), extended_cliques.end (), best_extended_cliques);\r\n\r\n            std::vector<std::vector<size_t> *>::iterator it;\r\n            std::vector<size_t> taken_corresps (model_scene_corrs_.size (), 0);\r\n            int max_taken = param_.max_taken_correspondence_;\r\n\r\n            if(!param_.cliques_big_to_small_)\r\n                std::reverse (cliques.begin (), cliques.end ());\r\n\r\n            for (it = cliques.begin (); it != cliques.end (); it++)\r\n            {\r\n                //std::cout << \"clique size:\" << (*it)->size () << std::endl;\r\n                //create a new clique based on how many time the correspondences in *it clique were used\r\n                std::vector<size_t> * new_clique = new std::vector<size_t>;\r\n                new_clique->reserve ((*it)->size ());\r\n                size_t used = 0;\r\n                for (size_t i = 0; i < (*it)->size (); i++)\r\n                {\r\n                    if (taken_corresps[(**it)[i]] < max_taken)\r\n                    {\r\n                        new_clique->push_back ((**it)[i]); //(**it)\r\n                        used++;\r\n                    }\r\n                }\r\n\r\n                if (used >= param_.gc_threshold_)\r\n                {\r\n                    new_clique->resize (used);\r\n\r\n                    //do ransac with these correspondences...\r\n                    pcl::Correspondences temp_corrs, filtered_corrs;\r\n                    temp_corrs.reserve (used);\r\n                    for (size_t j = 0; j < new_clique->size (); j++)\r\n                    {\r\n                        assert(new_clique->at (j) < model_scene_corrs_.size());\r\n                        temp_corrs.push_back (model_scene_corrs_[ new_clique->at (j) ]);\r\n                    }\r\n\r\n                    corr_rejector.getRemainingCorrespondences (temp_corrs, filtered_corrs);\r\n\r\n                    std::vector<int> inlier_indices;\r\n                    corr_rejector.getInliersIndices (inlier_indices);\r\n\r\n                    //check if corr_rejector.getBestTransformation () was not found already\r\n                    bool found = poseExists (corr_rejector.getBestTransformation ());\r\n\r\n                    if ((filtered_corrs.size () >= param_.gc_threshold_) && !found && (inlier_indices.size() != 0))\r\n                    {\r\n                        Eigen::Matrix4f trans = corr_rejector.getBestTransformation ();\r\n\r\n                        //check if the normals are ok after applying the transformation\r\n                        bool all_wrong = param_.check_normals_orientation_;\r\n\r\n                        if( param_.check_normals_orientation_ )\r\n                        {\r\n                            for(size_t j=0; j < filtered_corrs.size(); j++)\r\n                            {\r\n                                //transform normal\r\n                                const Eigen::Vector3f& model_normal = input_normals_->at (filtered_corrs[j].index_query).getNormalVector3fMap ();\r\n                                const Eigen::Vector3f& scene_normal = scene_normals_->at (filtered_corrs[j].index_match).getNormalVector3fMap ();\r\n                                if(!pcl_isfinite(model_normal[0]) || !pcl_isfinite(scene_normal[0]) ||\r\n                                        !pcl_isfinite(model_normal[1]) || !pcl_isfinite(scene_normal[1]) ||\r\n                                        !pcl_isfinite(model_normal[2]) || !pcl_isfinite(scene_normal[2]))\r\n                                {\r\n                                    continue;\r\n                                }\r\n\r\n                                Eigen::Vector3f nt;\r\n                                nt[0] = static_cast<float> (trans (0, 0) * model_normal[0] + trans (0, 1) * model_normal[1] + trans (0, 2) * model_normal[2]);\r\n                                nt[1] = static_cast<float> (trans (1, 0) * model_normal[0] + trans (1, 1) * model_normal[1] + trans (1, 2) * model_normal[2]);\r\n                                nt[2] = static_cast<float> (trans (2, 0) * model_normal[0] + trans (2, 1) * model_normal[1] + trans (2, 2) * model_normal[2]);\r\n                                if(nt.dot(scene_normal) >= (1.f - param_.thres_dot_distance_))\r\n                                    all_wrong = false;\r\n\r\n                            }\r\n                        }\r\n\r\n                        if(!all_wrong)\r\n                        {\r\n                            //PCL_INFO(\"Normals are consistent %d!!\\n\", static_cast<int>(all_nans));\r\n                            found_transformations_.push_back (trans);\r\n                            model_instances.push_back (filtered_corrs);\r\n\r\n                            //mark all inliers\r\n                            for (size_t j = 0; j < inlier_indices.size (); j++)\r\n                            {\r\n                                /*std::cout << \"1\" << inlier_indices[j] << std::endl;\r\n                                std::cout << \"2\" << new_clique->size() << std::endl;\r\n                                std::cout << \"3\" << new_clique->at (inlier_indices[j]) << std::endl;\r\n                                std::cout << \"4\" << taken_corresps.size() << std::endl;*/\r\n\r\n                                taken_corresps[new_clique->at (inlier_indices[j])]++;\r\n\r\n                                if( param_.prune_by_CC_ )\r\n                                    correspondence_to_instance[new_clique->at (inlier_indices[j])].push_back(model_instances.size() - 1);\r\n                            }\r\n\r\n                            if( param_.prune_by_CC_ )\r\n                            {\r\n                                for (size_t j = 0; j < inlier_indices.size (); j++)\r\n                                    correspondences_used.insert(new_clique->at (inlier_indices[j]));\r\n                            }\r\n                        }\r\n                        delete new_clique;\r\n                    }\r\n                    else\r\n                        delete new_clique;\r\n                }\r\n                else\r\n                    delete new_clique;\r\n            }\r\n\r\n            for (size_t p = 0; p < cliques.size (); p++)\r\n                delete cliques[p];\r\n        }\r\n        else\r\n        {\r\n            //use iterative gc for simple cases with lots of correspondences...\r\n            std::cout << \"Correspondence grouping is too hard to solve it using cliques...\" << std::endl;\r\n//            std::cout << \"N edges: \" << num_edges (connected_graph) << \" vertices:\" << num_v_in_cc << \" arboricity:\" << arboricity <<  std::endl;\r\n\r\n            std::vector<size_t> consensus_set;\r\n            consensus_set.resize(model_scene_corrs_.size ());\r\n            std::vector<bool> taken_corresps (model_scene_corrs_.size (), false);\r\n\r\n            GraphGGCG connected_graph(correspondence_graph);\r\n            //iterate over edges and remove those not belonging to this biconnected component\r\n            boost::tie (edgeIt, edgeEnd) = edges (connected_graph);\r\n            for (; edgeIt != edgeEnd; ++edgeIt)\r\n            {\r\n                if (components[*edgeIt] != c)\r\n                {\r\n                    boost::remove_edge(*edgeIt, connected_graph);\r\n                }\r\n            }\r\n\r\n            typename boost::graph_traits<GraphGGCG>::vertex_iterator vertexIt, vertexEnd;\r\n            boost::tie (vertexIt, vertexEnd) = vertices (connected_graph);\r\n            for (; vertexIt != vertexEnd; ++vertexIt)\r\n            {\r\n                if ( boost::out_degree(*vertexIt, connected_graph) < (param_.gc_threshold_ - 1))\r\n                    taken_corresps[*vertexIt] = true;\r\n            }\r\n\r\n            for (size_t i = 0; i < model_scene_corrs_.size (); ++i)\r\n            {\r\n                if (taken_corresps[i])\r\n                    continue;\r\n\r\n                int consensus_size = 0;\r\n                consensus_set[consensus_size++] = i;\r\n\r\n                for (size_t j = 0; j < model_scene_corrs_.size (); ++j)\r\n                {\r\n                    if (j != i && !taken_corresps[j])\r\n                    {\r\n                        //Let's check if j fits into the current consensus set\r\n                        bool is_a_good_candidate = true;\r\n\r\n                        for (int k = 0; k < consensus_size; ++k)\r\n                        {\r\n                            //check if edge (j, consensus_set[k] exists in the graph, if it does not, is_a_good_candidate = false!...\r\n                            if (!(boost::edge (j, consensus_set[k], connected_graph).second))\r\n                            {\r\n                                is_a_good_candidate = false;\r\n                                break;\r\n                            }\r\n                        }\r\n\r\n                        if (is_a_good_candidate)\r\n                            consensus_set[consensus_size++] = j;\r\n                    }\r\n                }\r\n\r\n                if (consensus_size >= param_.gc_threshold_)\r\n                {\r\n                    pcl::Correspondences temp_corrs, filtered_corrs;\r\n                    temp_corrs.reserve (consensus_size);\r\n\r\n                    for (size_t j = 0; j < consensus_size; j++)\r\n                        temp_corrs.push_back (model_scene_corrs_[ consensus_set[j] ]);\r\n\r\n                    if ( param_.ransac_threshold_ > 0)\r\n                    {\r\n                        //pcl::ScopeTime tt(\"ransac filtering\");\r\n                        //ransac filtering\r\n                        corr_rejector.getRemainingCorrespondences (temp_corrs, filtered_corrs);\r\n                        //check if corr_rejector.getBestTransformation () was not found already\r\n                        bool found = poseExists (corr_rejector.getBestTransformation ());\r\n\r\n                        std::vector<int> inlier_indices;\r\n                        corr_rejector.getInliersIndices (inlier_indices);\r\n\r\n                        //save transformations for recognize\r\n                        if ((filtered_corrs.size () >= param_.gc_threshold_) && !found && (inlier_indices.size() != 0))\r\n                        {\r\n                            Eigen::Matrix4f trans = corr_rejector.getBestTransformation ();\r\n\r\n                            //check if the normals are ok after applying the transformation\r\n                            bool all_wrong = param_.check_normals_orientation_;\r\n\r\n                            if( param_.check_normals_orientation_ )\r\n                            {\r\n                                for(size_t j=0; j < filtered_corrs.size(); j++)\r\n                                {\r\n                                    //transform normal\r\n                                    const Eigen::Vector3f& model_normal = input_normals_->at (filtered_corrs[j].index_query).getNormalVector3fMap ();\r\n                                    const Eigen::Vector3f& scene_normal = scene_normals_->at (filtered_corrs[j].index_match).getNormalVector3fMap ();\r\n                                    if(!pcl_isfinite(model_normal[0]) || !pcl_isfinite(scene_normal[0]) ||\r\n                                            !pcl_isfinite(model_normal[1]) || !pcl_isfinite(scene_normal[1]) ||\r\n                                            !pcl_isfinite(model_normal[2]) || !pcl_isfinite(scene_normal[2]))\r\n                                    {\r\n                                        continue;\r\n                                    }\r\n\r\n                                    Eigen::Vector3f nt;\r\n                                    nt[0] = static_cast<float> (trans (0, 0) * model_normal[0] + trans (0, 1) * model_normal[1] + trans (0, 2) * model_normal[2]);\r\n                                    nt[1] = static_cast<float> (trans (1, 0) * model_normal[0] + trans (1, 1) * model_normal[1] + trans (1, 2) * model_normal[2]);\r\n                                    nt[2] = static_cast<float> (trans (2, 0) * model_normal[0] + trans (2, 1) * model_normal[1] + trans (2, 2) * model_normal[2]);\r\n                                    if(nt.dot(scene_normal) >= (1.f - param_.thres_dot_distance_))\r\n                                        all_wrong = false;\r\n\r\n                                }\r\n                            }\r\n\r\n                            if(all_wrong)\r\n                            {\r\n                                //PCL_ERROR(\"Normals are not consistent %d %d!!\\n\", static_cast<int>(all_wrong), static_cast<int>(all_nans));\r\n                                for (size_t j = 0; j < consensus_size; j++)\r\n                                    taken_corresps[consensus_set[j]] = false;\r\n                            }\r\n                            else\r\n                            {\r\n                                //PCL_INFO(\"Normals are consistent, pushing filtered_corrs %d!!\\n\", static_cast<int>(filtered_corrs.size()));\r\n                                found_transformations_.push_back (trans);\r\n                                model_instances.push_back (filtered_corrs);\r\n\r\n                                //mark all inliers\r\n                                for (size_t j = 0; j < inlier_indices.size (); j++)\r\n                                {\r\n                                    taken_corresps[consensus_set[inlier_indices[j]]] = true;\r\n\r\n                                    if(param_.prune_by_CC_)\r\n                                        correspondence_to_instance[consensus_set[inlier_indices[j]]].push_back(model_instances.size() - 1);\r\n                                }\r\n\r\n                                if(param_.prune_by_CC_)\r\n                                {\r\n                                    for (size_t j = 0; j < inlier_indices.size (); j++)\r\n                                        correspondences_used.insert(consensus_set[inlier_indices[j]]);\r\n                                }\r\n                            }\r\n                        }\r\n                        else\r\n                        {\r\n                            //Free the correspondences so they can be used in another set...\r\n                            //PCL_ERROR(\"Freeing %d correspondences from invalid set...\\n\", consensus_set.size ());\r\n                            for (size_t j = 0; j < consensus_size; j++)\r\n                                taken_corresps[consensus_set[j]] = false;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        if( param_.prune_by_CC_ )\r\n        {\r\n            //pcl::ScopeTime t(\"final post-processing...\");\r\n            GraphGGCG connected_graph_used_edges(connected_graph);\r\n            typename boost::graph_traits<GraphGGCG>::vertex_iterator vertexIt, vertexEnd;\r\n            std::vector<typename boost::graph_traits<GraphGGCG>::vertex_descriptor> to_be_removed;\r\n            boost::tie (vertexIt, vertexEnd) = vertices (connected_graph_used_edges);\r\n            for (; vertexIt != vertexEnd; ++vertexIt)\r\n            {\r\n                std::set<size_t>::const_iterator it;\r\n                it = correspondences_used.find(*vertexIt);\r\n                if (it == correspondences_used.end())\r\n                    to_be_removed.push_back (*vertexIt);\r\n            }\r\n\r\n            for (size_t i = 0; i < to_be_removed.size (); i++)\r\n                clear_vertex (to_be_removed[i], connected_graph_used_edges);\r\n\r\n            boost::vector_property_map<size_t> components (boost::num_vertices (connected_graph_used_edges));\r\n            size_t n_cc = boost::connected_components (connected_graph_used_edges, &components[0]);\r\n\r\n            std::vector<size_t> cc_sizes  (n_cc, 0);\r\n            for (size_t i = 0; i < model_scene_corrs_.size (); i++)\r\n                cc_sizes[components[i]]++;\r\n\r\n            size_t ncc_overthres = 0;\r\n            for (size_t i = 0; i < n_cc; i++)\r\n            {\r\n                if(cc_sizes[i] >= param_.gc_threshold_)\r\n                    ncc_overthres++;\r\n            }\r\n\r\n            //std::cout << \"Number of connected components over threshold: \" << ncc_overthres << std::endl;\r\n\r\n            //somehow now i need to do a Nonmax supression of the model_instances that are in the same CC\r\n            //gather instances that were generated with correspondences found in a specific CC\r\n            //correspondence_to_instance maps correspondences (vertices) to instance, we can use that i guess\r\n\r\n            for (size_t internal_c = 0; internal_c < n_cc; internal_c++)\r\n            {\r\n                //ignore if not enough vertices...\r\n                size_t num_v_in_cc_tmp = cc_sizes[internal_c];\r\n                if (num_v_in_cc_tmp < param_.gc_threshold_)\r\n                    continue;\r\n\r\n                std::set<size_t> instances_for_this_cc;\r\n                {\r\n                    boost::tie (vertexIt, vertexEnd) = vertices (connected_graph_used_edges);\r\n\r\n                    for (; vertexIt != vertexEnd; ++vertexIt)\r\n                    {\r\n                        if (components[*vertexIt] == internal_c)\r\n                        {\r\n                            for(size_t k=0; k < correspondence_to_instance[*vertexIt].size(); k++)\r\n                            {\r\n                                instances_for_this_cc.insert(correspondence_to_instance[*vertexIt][k]);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                //std::cout << \"instances in this cc:\" << instances_for_this_cc.size() << std::endl;\r\n                std::set<size_t>::const_iterator it;\r\n                size_t max_size = 0;\r\n                for(it = instances_for_this_cc.begin(); it != instances_for_this_cc.end(); it++)\r\n                {\r\n                    //std::cout << *it << \" \" << model_instances[*it].size() << std::endl;\r\n                    if(max_size <= model_instances[*it].size())\r\n                    {\r\n                        max_size = model_instances[*it].size();\r\n                        //max_idx = *it;\r\n                    }\r\n                }\r\n\r\n                //std::cout << std::endl;\r\n\r\n                float thres = 0.5f;\r\n                for(it = instances_for_this_cc.begin(); it != instances_for_this_cc.end(); it++)\r\n                {\r\n                    if( model_instances[*it].size() > (max_size * thres))\r\n                        model_instances_kept_indices.push_back(*it);\r\n                }\r\n            }\r\n\r\n            /*if(visualize_graph_ && correspondences_used.size() > 0)\r\n            visualizeGraph(connected_graph_used_edges, \"used edges\");*/\r\n        }\r\n    }\r\n\r\n    if(param_.prune_by_CC_)\r\n    {\r\n        for(size_t i=0; i < model_instances_kept_indices.size(); i++)\r\n        {\r\n            model_instances[i] = model_instances[model_instances_kept_indices[i]];\r\n            found_transformations_[i] = found_transformations_[model_instances_kept_indices[i]];\r\n        }\r\n\r\n        model_instances.resize(model_instances_kept_indices.size());\r\n        found_transformations_.resize(model_instances_kept_indices.size());\r\n    }\r\n\r\n    //visualizeCorrespondences(*model_scene_corrs_);\r\n\r\n  }\r\n  // HACK: Michael Zillich: added this try/catch, as somewhere above somtimes a range\r\n  // check exception is thrown. This will have to be handled properly eventually\r\n  catch(std::exception e)\r\n  {\r\n      std::cerr << \"v4r::GraphGeometricConsistencyGroupingi: caught exception: \"\r\n        << e.what() << \"\\n\";\r\n  }\r\n  // HACK END\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\ntemplate<typename PointModelT, typename PointSceneT>\r\nbool\r\nv4r::GraphGeometricConsistencyGrouping<PointModelT, PointSceneT>::recognize (\r\n        std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<\r\n        Eigen::Matrix4f> > &transformations)\r\n{\r\n    std::vector<pcl::Correspondences> model_instances;\r\n    return (this->recognize (transformations, model_instances));\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\ntemplate<typename PointModelT, typename PointSceneT>\r\nbool\r\nv4r::GraphGeometricConsistencyGrouping<PointModelT, PointSceneT>::recognize (\r\n        std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<\r\n        Eigen::Matrix4f> > &transformations,\r\n        std::vector<pcl::Correspondences> &clustered_corrs)\r\n{\r\n    transformations.clear ();\r\n    if (!this->initCompute ())\r\n    {\r\n        PCL_ERROR(\"[v4r::GraphGeometricConsistencyGrouping::recognize()] Error! Model cloud or Scene cloud not set, please set them before calling again this function.\\n\");\r\n        return (false);\r\n    }\r\n\r\n    clusterCorrespondences (clustered_corrs);\r\n\r\n    transformations = found_transformations_;\r\n\r\n    this->deinitCompute ();\r\n    return (true);\r\n}\r\n\r\n#endif // FAAT_PCL_RECOGNITION_SI_GEOMETRIC_CONSISTENCY_IMPL_H_\r\n", "meta": {"hexsha": "15ee994c14f29c9955f5913f8ad827bac68d4f03", "size": 49351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/common/include/v4r/common/impl/graph_geometric_consistency.hpp", "max_stars_repo_name": "byiii/clone_v4r_j", "max_stars_repo_head_hexsha": "628359c7ba19389004618defd6a8d8ab5af35967", "max_stars_repo_licenses": ["MIT"], "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/common/include/v4r/common/impl/graph_geometric_consistency.hpp", "max_issues_repo_name": "byiii/clone_v4r_j", "max_issues_repo_head_hexsha": "628359c7ba19389004618defd6a8d8ab5af35967", "max_issues_repo_licenses": ["MIT"], "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/common/include/v4r/common/impl/graph_geometric_consistency.hpp", "max_forks_repo_name": "byiii/clone_v4r_j", "max_forks_repo_head_hexsha": "628359c7ba19389004618defd6a8d8ab5af35967", "max_forks_repo_licenses": ["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.7508865248, "max_line_length": 193, "alphanum_fraction": 0.5423395676, "num_tokens": 10983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580041760869, "lm_q2_score": 0.03114382884868088, "lm_q1q2_score": 0.009572305077332194}}
{"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_DETAIL_MAYBE_FWD_HPP\n#define BOOST_HANA_DETAIL_MAYBE_FWD_HPP\n\n#include <boost/hana/bool.hpp>\n#include <boost/hana/logical/logical.hpp>\n\n#include <boost/hana/comparable/comparable.hpp>\n#include <boost/hana/core/datatype.hpp>\n#include <boost/hana/monad/monad.hpp>\n\n\nnamespace boost { namespace hana {\n    //! @ingroup group-datatypes\n    //! Represents an optional value.\n    //!\n    //! A `Maybe` either contains a value (represented as `just(x)`), or it\n    //! is empty (represented as `nothing`).\n    //!\n    //! ## Instance of\n    //! `Comparable`, `Functor`, `Applicative`, `Monad`, `Foldable`\n    //! and `Searchable`\n    struct Maybe { };\n\n    namespace maybe_detail {\n        template <bool is_valid, typename T,\n            typename = operators<Comparable, Monad>>\n        struct maybe {\n            using hana_datatype = Maybe;\n\n            template <typename Default, typename F>\n            constexpr auto maybe_impl(Default d, F) const\n            { return d; }\n        };\n\n        template <typename T>\n        struct maybe<true, T> {\n            using hana_datatype = Maybe;\n            T val;\n\n            template <typename Default, typename F>\n            constexpr auto maybe_impl(Default, F f) const\n            { return f(val); }\n        };\n\n        template <typename T>\n        using just = maybe<true, T>;\n        using nothing = maybe<false, void>;\n    }\n\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    //! Create an optional value containing `x`.\n    //! @relates Maybe\n    //!\n    //! ### Example\n    //! @snippet example/maybe/just.cpp main\n    constexpr auto just = [](auto x) {\n        return unspecified;\n    };\n\n    //! An empty optional value.\n    //! @relates Maybe\n    //!\n    //! ### Example\n    //! @snippet example/maybe/nothing.cpp main\n    constexpr unspecified nothing{};\n#else\n    BOOST_HANA_CONSTEXPR_LAMBDA auto just = [](auto x) {\n        return maybe_detail::just<decltype(x)>{x};\n    };\n\n    constexpr maybe_detail::nothing nothing{};\n#endif\n\n    //! Create a `Maybe` with the result of a function, but only if a\n    //! predicate is satisfied.\n    //! @relates Maybe\n    //!\n    //! Specifically, returns `just(f(x))` if `predicate(x)` is a true-valued\n    //! `Logical`, and `nothing` otherwise.\n    //!\n    //!\n    //! @param predicate\n    //! A function called as `predicate(x)` and returning a true-valued\n    //! `Logical` if `just(f(x))` should be the resulting value, and a\n    //! false-valued one if `nothing` should be the resulting value.\n    //! In the current version of the library, the result of `predicate`\n    //! has to be a [compile-time](@ref Logical_terminology) `Logical`.\n    //!\n    //! @param f\n    //! A function called as `f(x)` if the `predicate` returns a true-valued\n    //! `Logical`, and not called at all otherwise. If the `predicate` returns\n    //! a false-valued `Logical`, the `f(x)` expression is not even required\n    //! to be well-formed.\n    //!\n    //! @param x\n    //! The value to either transform and put in a `just`, or discard.\n    //!\n    //!\n    //! ### Example\n    //! @snippet example/maybe/only_when.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto only_when = [](auto predicate, auto f, auto x) {\n        return eval_if(predicate(x),\n            [=](auto _) { return just(_(f)(x)); },\n            [](auto _) { return nothing; }\n        );\n    };\n\n    //! Apply a function to the contents of a `Maybe`, with a fallback\n    //! result.\n    //! @relates Maybe\n    //!\n    //! Specifically, `maybe` takes a default value, a function and an\n    //! optional value. If the optional value is `nothing`, the default\n    //! value is returned. Otherwise, the function is applied to the\n    //! content of the `just`.\n    //!\n    //!\n    //! @param default_\n    //! A default value returned if `m` is `nothing`.\n    //!\n    //! @param f\n    //! A function called as `f(x)` if and only if `m` is an optional value\n    //! of the form `just(x)`. In that case, the result returend by `maybe`\n    //! is the result of `f`.\n    //!\n    //! @param m\n    //! An optional value.\n    //!\n    //!\n    //! ### Example\n    //! @snippet example/maybe/maybe.cpp main\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\n    constexpr auto maybe = [](auto default_, auto f, auto m) {\n        unspecified;\n    };\n#else\n    BOOST_HANA_CONSTEXPR_LAMBDA auto maybe = [](auto default_, auto f, auto m) {\n        return m.maybe_impl(default_, f);\n    };\n#endif\n\n    //! Return whether a `Maybe` contains a value.\n    //! @relates Maybe\n    //!\n    //! Specifically, returns a [compile-time](@ref Logical_terminology)\n    //! true-valued `Logical` if `m` is of the form `just(x)` for some `x`,\n    //! and a false-valued one otherwise.\n    //!\n    //! ### Example\n    //! @snippet example/maybe/is_just.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto is_just = [](auto m) {\n        return maybe(false_, [](auto) { return true_; }, m);\n    };\n\n    //! Return whether a `Maybe` is empty.\n    //! @relates Maybe\n    //!\n    //! Specifically, returns a [compile-time](@ref Logical_terminology)\n    //! true-valued `Logical` if `m` is of the form `nothing`, and a\n    //! false-valued one otherwise.\n    //!\n    //! ### Example\n    //! @snippet example/maybe/is_nothing.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto is_nothing = [](auto m) {\n        return maybe(true_, [](auto) { return false_; }, m);\n    };\n\n    //! Return the contents of a `Maybe`, with a fallback result.\n    //! @relates Maybe\n    //!\n    //! Specifically, returns `x` if `m` of the form `just(x)`, and `default_`\n    //! if `m` is of the form `nothing`.\n    //!\n    //!\n    //! @param default_\n    //! The default value to return if `m` is `nothing`.\n    //!\n    //! @param m\n    //! The optional value to try to retrieve the value from.\n    //!\n    //!\n    //! ### Example\n    //! @snippet example/maybe/from_maybe.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto from_maybe = [](auto default_, auto m) {\n        return maybe(default_, [](auto x) { return x; }, m);\n    };\n\n    //! Extract the content of a `Maybe` or fail at compile-time.\n    //! @relates Maybe\n    //!\n    //! Specifically, returns `x` if the optional value is of the form\n    //! `just(x)`, and triggers a static assertion otherwise.\n    //!\n    //! ### Example\n    //! @snippet example/maybe/from_just.cpp main\n    BOOST_HANA_CONSTEXPR_LAMBDA auto from_just = [](auto m) {\n        auto err = [](auto ...dum) {\n            constexpr bool always_false = sizeof...(dum) != 0;\n            static_assert(always_false,\n            \"trying to extract the value inside a boost::hana::nothing \"\n            \"with boost::hana::from_just\");\n        };\n        return maybe(err, [](auto x) { return [=] { return x; }; }, m)();\n    };\n}} // end namespace boost::hana\n\n#endif // !BOOST_HANA_DETAIL_MAYBE_FWD_HPP\n", "meta": {"hexsha": "de6e04f441b2d48a8d9e98b00274bfa4f1525313", "size": 7020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/hana/detail/maybe_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/detail/maybe_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/detail/maybe_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": 32.3502304147, "max_line_length": 85, "alphanum_fraction": 0.5981481481, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850021044189, "lm_q2_score": 0.03904829426387262, "lm_q1q2_score": 0.00957015128183519}}
{"text": "#include \"MeshCuboidSymmetryGroup.h\"\n#include \"MeshCuboidParameters.h\"\n#include \"Utilities.h\"\n\n#include <bitset>\n#include <Eigen/Eigenvalues> \n\n\nMeshCuboidSymmetryGroupInfo::MeshCuboidSymmetryGroupInfo()\n\t: symmetry_type_(ReflectionSymmetryType)\n\t, aligned_global_axis_index_(0)\n{\n\n}\n\nMeshCuboidSymmetryGroupInfo::MeshCuboidSymmetryGroupInfo(MeshCuboidSymmetryGroupType _symmetry_type,\n\tunsigned int _aligned_global_axis_index)\n\t: symmetry_type_(_symmetry_type)\n\t, aligned_global_axis_index_(_aligned_global_axis_index)\n{\n\n}\n\nMeshCuboidSymmetryGroupInfo::MeshCuboidSymmetryGroupInfo(const MeshCuboidSymmetryGroupInfo& _other)\n{\n\tsymmetry_type_ = _other.symmetry_type_;\n\taligned_global_axis_index_ = _other.aligned_global_axis_index_;\n\tsingle_label_indices_ = _other.single_label_indices_;\n\tpair_label_indices_ = _other.pair_label_indices_;\n}\n\nMeshCuboidSymmetryGroup::MeshCuboidSymmetryGroup()\n\t: num_symmetry_orders_(2)\n{\n\n}\n\nMeshCuboidSymmetryGroup::MeshCuboidSymmetryGroup(const MeshCuboidSymmetryGroupInfo &_info)\n\t: info_(_info)\n\t, num_symmetry_orders_(2)\n{\n\n}\n\nMeshCuboidSymmetryGroup::MeshCuboidSymmetryGroup(const MeshCuboidSymmetryGroup &_other)\n\t:info_(_other.info_)\n\t, num_symmetry_orders_(_other.num_symmetry_orders_)\n{\n\n}\n\nMeshCuboidSymmetryGroup::~MeshCuboidSymmetryGroup()\n{\n\n}\n\nunsigned int MeshCuboidSymmetryGroup::num_symmetry_orders() const\n{\n\tassert(num_symmetry_orders_ >= 2);\n\treturn num_symmetry_orders_;\n}\n\nReal MeshCuboidSymmetryGroup::get_rotation_angle() const\n{\n\treturn M_PI / 180.0 * (360.0 / num_symmetry_orders_);\n}\n\nunsigned int MeshCuboidSymmetryGroup::get_aligned_global_axis_index() const\n{\n\tassert(info_.aligned_global_axis_index_ < 3);\n\treturn info_.aligned_global_axis_index_;\n}\n\nvoid MeshCuboidSymmetryGroup::get_single_cuboid_indices(const std::vector<MeshCuboid *>& _cuboids,\n\tstd::vector<unsigned int> &_single_cuboid_indices) const\n{\n\tconst unsigned int num_cuboids = _cuboids.size();\n\t_single_cuboid_indices.clear();\n\n\tunsigned int num_single_labels = info_.single_label_indices_.size();\n\t_single_cuboid_indices.reserve(num_single_labels);\n\n\tfor (unsigned int i = 0; i < num_single_labels; ++i)\n\t{\n\t\tLabel label_index = info_.single_label_indices_[i];\n\t\tint cuboid_index = 0;\n\t\tfor (; cuboid_index < num_cuboids; ++cuboid_index)\n\t\t{\n\t\t\tif (_cuboids[cuboid_index]->get_label_index() == label_index) break;\n\t\t}\n\n\t\tif (cuboid_index < num_cuboids)\n\t\t\t_single_cuboid_indices.push_back(cuboid_index);\n\t}\n}\n\nvoid MeshCuboidSymmetryGroup::get_pair_cuboid_indices(const std::vector<MeshCuboid *>& _cuboids,\n\tstd::vector< std::pair<unsigned int, unsigned int> > &_pair_cuboid_indices) const\n{\n\tconst unsigned int num_cuboids = _cuboids.size();\n\t_pair_cuboid_indices.clear();\n\n\tunsigned int num_pair_labels = info_.pair_label_indices_.size();\n\t_pair_cuboid_indices.reserve(num_pair_labels);\n\n\tfor (unsigned int i = 0; i < num_pair_labels; ++i)\n\t{\n\t\tLabel label_index_1 = info_.pair_label_indices_[i].first;\n\t\tLabel label_index_2 = info_.pair_label_indices_[i].second;\n\n\t\tunsigned int cuboid_index_1 = 0;\n\t\tfor (; cuboid_index_1 < num_cuboids; ++cuboid_index_1)\n\t\t\tif (_cuboids[cuboid_index_1]->get_label_index() == label_index_1) break;\n\n\t\tunsigned int cuboid_index_2 = 0;\n\t\tfor (; cuboid_index_2 < num_cuboids; ++cuboid_index_2)\n\t\t\tif (_cuboids[cuboid_index_2]->get_label_index() == label_index_2) break;\n\n\t\tif (cuboid_index_1 < num_cuboids && cuboid_index_2 < num_cuboids)\n\t\t\t_pair_cuboid_indices.push_back(std::make_pair(cuboid_index_1, cuboid_index_2));\n\t}\n}\n\nvoid MeshCuboidSymmetryGroup::get_symmetric_sample_point_pairs(\n\tconst std::vector<MeshCuboid *> &_cuboids,\n\tconst std::vector<ANNpointArray> &_cuboid_ann_points,\n\tconst std::vector<ANNkd_tree *> &_cuboid_ann_kd_tree,\n\tconst Real _squared_neighbor_distance,\n\tstd::list<WeightedPointPair> &_sample_point_pairs) const\n{\n\tconst unsigned int num_cuboids = _cuboids.size();\n\tassert(_cuboid_ann_points.size() == num_cuboids);\n\tassert(_cuboid_ann_kd_tree.size() == num_cuboids);\n\n\t_sample_point_pairs.clear();\n\n\n\tstd::vector<unsigned int> single_cuboid_indices;\n\tget_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\tconst unsigned int cuboid_index = (*it);\n\n\t\tget_symmetric_sample_point_pairs(\n\t\t\t_cuboids[cuboid_index],\n\t\t\t_cuboid_ann_points[cuboid_index],\n\t\t\t_cuboid_ann_kd_tree[cuboid_index],\n\t\t\t_squared_neighbor_distance, _sample_point_pairs);\n\t}\n\n\t// NOTE:\n\t// Get inter-cuboid symmetric points only for reflection symmetry.\n\tif (get_symmetry_type() == ReflectionSymmetryType)\n\t{\n\t\tstd::vector< std::pair<unsigned int, unsigned int> > pair_cuboid_indices;\n\t\tget_pair_cuboid_indices(_cuboids, pair_cuboid_indices);\n\n\t\tfor (std::vector< std::pair<unsigned int, unsigned int> >::const_iterator it = pair_cuboid_indices.begin();\n\t\t\tit != pair_cuboid_indices.end(); ++it)\n\t\t{\n\t\t\tconst unsigned int cuboid_index_1 = (*it).first;\n\t\t\tconst unsigned int cuboid_index_2 = (*it).second;\n\n\t\t\t// 1 -> 2.\n\t\t\tget_symmetric_sample_point_pairs(\n\t\t\t\t_cuboids[cuboid_index_1],\n\t\t\t\t_cuboid_ann_points[cuboid_index_2],\n\t\t\t\t_cuboid_ann_kd_tree[cuboid_index_2],\n\t\t\t\t_squared_neighbor_distance, _sample_point_pairs);\n\n\t\t\t// 2 -> 1.\n\t\t\tget_symmetric_sample_point_pairs(\n\t\t\t\t_cuboids[cuboid_index_2],\n\t\t\t\t_cuboid_ann_points[cuboid_index_1],\n\t\t\t\t_cuboid_ann_kd_tree[cuboid_index_1],\n\t\t\t\t_squared_neighbor_distance, _sample_point_pairs);\n\t\t}\n\t}\n}\n\nvoid MeshCuboidSymmetryGroup::get_symmetric_sample_point_pairs(\n\tconst MeshCuboid *_cuboid_1,\n\tconst ANNpointArray &_cuboid_ann_points_2,\n\tANNkd_tree *_cuboid_ann_kd_tree_2,\n\tconst Real _squared_neighbor_distance,\n\tstd::list<WeightedPointPair> &_sample_point_pairs) const\n{\n\tif (!_cuboid_1) return;\n\tstd::vector<MyMesh::Point> cuboid_1_sample_points;\n\t_cuboid_1->get_sample_points(cuboid_1_sample_points);\n\n\tget_symmetric_sample_point_pairs(\n\t\tcuboid_1_sample_points,\n\t\t_cuboid_ann_points_2,\n\t\t_cuboid_ann_kd_tree_2,\n\t\t_squared_neighbor_distance,\n\t\t_sample_point_pairs);\n}\n\nvoid MeshCuboidSymmetryGroup::get_symmetric_sample_point_pairs(\n\tconst std::vector<MyMesh::Point> &_cuboid_1_sample_points,\n\tconst ANNpointArray &_cuboid_ann_points_2,\n\tANNkd_tree *_cuboid_ann_kd_tree_2,\n\tconst Real _squared_neighbor_distance,\n\tstd::list<WeightedPointPair> &_sample_point_pairs) const\n{\n\tif (_cuboid_1_sample_points.size() == 0 || !_cuboid_ann_points_2 || !_cuboid_ann_kd_tree_2)\n\t\treturn;\n\n\tconst int num_points_1 = _cuboid_1_sample_points.size();\n\tconst int num_points_2 = _cuboid_ann_kd_tree_2->nPoints();\n\n\t//\n\tANNpoint q = annAllocPt(3);\n\tANNidxArray nn_idx = new ANNidx[1];\n\tANNdistArray dd = new ANNdist[1];\n\t//\n\n\tfor (int point_index_1 = 0; point_index_1 < num_points_1; ++point_index_1)\n\t{\n\t\tMyMesh::Point point_1 = _cuboid_1_sample_points[point_index_1];\n\n\t\tfor (int symmetry_order = 1; symmetry_order < num_symmetry_orders_; ++symmetry_order)\n\t\t{\n\t\t\tMyMesh::Point symmetric_point_1 = get_symmetric_point(point_1, symmetry_order);\n\n\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t\tq[i] = symmetric_point_1[i];\n\n\t\t\tint num_searched_neighbors = _cuboid_ann_kd_tree_2->annkFRSearch(\n\t\t\t\tq, _squared_neighbor_distance, 1, nn_idx, dd);\n\t\t\tif (num_searched_neighbors > 0)\n\t\t\t{\n\t\t\t\tint point_index_2 = (int)nn_idx[0];\n\t\t\t\tassert(point_index_2 < num_points_2);\n\n\t\t\t\tMyMesh::Point point_2;\n\t\t\t\tfor (unsigned int i = 0; i < 3; ++i)\n\t\t\t\t\tpoint_2[i] = _cuboid_ann_points_2[point_index_2][i];\n\n\t\t\t\t//\n\t\t\t\t// Debug.\n\t\t\t\tReal test_distance = (symmetric_point_1 - point_2).norm();\n\t\t\t\tCHECK_NUMERICAL_ERROR(__FUNCTION__, test_distance, std::sqrt(dd[0]));\n\t\t\t\tdouble distance = (std::sqrt(_squared_neighbor_distance) - std::sqrt(dd[0]));\n\t\t\t\tassert(distance >= 0);\n\t\t\t\t//\n\n\t\t\t\tReal weight = distance * distance;\n\t\t\t\tReal angle = symmetry_order * get_rotation_angle();\n\t\t\t\tWeightedPointPair point_pair(point_1, point_2, weight, angle);\n\t\t\t\t_sample_point_pairs.push_back(point_pair);\n\t\t\t}\n\t\t}\n\t}\n\n\t//\n\tannDeallocPt(q);\n\tdelete[] nn_idx;\n\tdelete[] dd;\n\t//\n}\n\nMeshCuboidReflectionSymmetryGroup* MeshCuboidReflectionSymmetryGroup::constructor(\n\tconst MeshCuboidSymmetryGroupInfo &_info,\n\tconst std::vector<MeshCuboid *>& _cuboids)\n{\n\tMeshCuboidReflectionSymmetryGroup *group = new MeshCuboidReflectionSymmetryGroup(_info);\n\tbool ret = group->compute_symmetry_axis(_cuboids);\n\tif (!ret)\n\t{\n\t\tdelete group;\n\t\tgroup = NULL;\n\t}\n\treturn group;\n}\n\nMeshCuboidReflectionSymmetryGroup::MeshCuboidReflectionSymmetryGroup(\n\tconst MyMesh::Normal _n, const double _t)\n\t: MeshCuboidSymmetryGroup()\n\t, n_(_n)\n\t, t_(_t)\n{\n\n}\n\nMeshCuboidReflectionSymmetryGroup::MeshCuboidReflectionSymmetryGroup(\n\tconst MeshCuboidSymmetryGroupInfo &_info)\n\t: MeshCuboidSymmetryGroup(_info)\n\t, n_(MyMesh::Normal(1, 0, 0))\n\t, t_(0)\n{\n\tassert(_info.symmetry_type_ == ReflectionSymmetryType);\n}\n\nMeshCuboidReflectionSymmetryGroup::MeshCuboidReflectionSymmetryGroup(\n\tconst MeshCuboidReflectionSymmetryGroup &_other)\n\t: MeshCuboidSymmetryGroup(_other)\n\t, n_(_other.n_)\n\t, t_(_other.t_)\n{\n\tn_.normalize();\n\tassert(info_.symmetry_type_ == ReflectionSymmetryType);\n}\n\nMeshCuboidReflectionSymmetryGroup::~MeshCuboidReflectionSymmetryGroup()\n{\n\n}\n\nunsigned int MeshCuboidReflectionSymmetryGroup::num_axis_parameters()\n{\n\treturn (3 + 1);\n}\n\nMeshCuboidSymmetryGroupType MeshCuboidReflectionSymmetryGroup::get_symmetry_type() const\n{\n\tassert(info_.symmetry_type_ == ReflectionSymmetryType);\n\treturn info_.symmetry_type_;\n}\n\nunsigned int MeshCuboidReflectionSymmetryGroup::num_symmetry_orders() const\n{\n\t// NOTE:\n\t// Reflection symmetry is order of 2.\n\tassert(num_symmetry_orders_ == 2);\n\treturn num_symmetry_orders_;\n}\n\nvoid MeshCuboidReflectionSymmetryGroup::set_num_symmetry_order(unsigned int _symmetry_order)\n{\n\t// NOTE:\n\t// Reflection symmetry is order of 2.\n\tassert(false);\n}\n\nvoid MeshCuboidReflectionSymmetryGroup::get_reflection_plane(MyMesh::Normal &_n, double &_t) const\n{\n\t_n = n_;\n\t_t = t_;\n}\n\nvoid MeshCuboidReflectionSymmetryGroup::set_reflection_plane(const MyMesh::Normal &_n, const double &_t)\n{\n\tn_ = _n;\n\tt_ = _t;\n\tn_.normalize();\n}\n\nbool MeshCuboidReflectionSymmetryGroup::compute_symmetry_axis(const std::vector<MeshCuboid *>& _cuboids)\n{\n\tstd::vector< std::pair<unsigned int, unsigned int> > pair_cuboid_indices;\n\tget_pair_cuboid_indices(_cuboids, pair_cuboid_indices);\n\n\tif (pair_cuboid_indices.empty())\n\t{\n\t\tstd::vector<unsigned int> single_cuboid_indices;\n\t\tget_single_cuboid_indices(_cuboids, single_cuboid_indices);\n\t\tif (single_cuboid_indices.empty())\n\t\t\treturn false;\n\n\t\tconst unsigned int num_cuboids = _cuboids.size();\n\n\t\tstd::list<MyMesh::Normal> aligned_normals;\n\t\tstd::list<MyMesh::Point> aligned_centers;\n\n\t\tfor (std::vector<unsigned int>::const_iterator it = single_cuboid_indices.begin();\n\t\t\tit != single_cuboid_indices.end(); ++it)\n\t\t{\n\t\t\tint cuboid_index = (*it);\n\t\t\tassert(cuboid_index < num_cuboids);\n\t\t\tconst MeshCuboid *cuboid = _cuboids[cuboid_index];\n\n\t\t\taligned_normals.push_back(cuboid->get_bbox_axis(get_aligned_global_axis_index()));\n\t\t\taligned_centers.push_back(cuboid->get_bbox_center());\n\t\t}\n\n\t\tassert(!aligned_normals.empty());\n\t\tassert(!aligned_centers.empty());\n\n\t\tEigen::Matrix3d A = Eigen::Matrix3d::Zero();\n\n\t\tfor (std::list<MyMesh::Normal>::const_iterator it = aligned_normals.begin();\n\t\t\tit != aligned_normals.end(); ++it)\n\t\t{\n\t\t\tEigen::Vector3d n_vec;\n\t\t\tfor (int i = 0; i < 3; ++i) n_vec[i] = (*it)[i];\n\t\t\tA += (n_vec * n_vec.transpose());\n\t\t}\n\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(A);\n\t\tEigen::Vector3d n = es.eigenvectors().col(3 - 1);\n\t\tfor (unsigned int i = 0; i < 3; ++i) n_[i] = n[i];\n\t\tn_.normalize();\n\n\t\tt_ = 0;\n\t\tfor (std::list<MyMesh::Point>::const_iterator it = aligned_centers.begin();\n\t\t\tit != aligned_centers.end(); ++it)\n\t\t\tt_ += dot(n_, (*it));\n\t\tt_ /= aligned_centers.size();\n\t}\n\telse\n\t{\n\t\tconst unsigned int num_cuboids = _cuboids.size();\n\n\t\tstd::list< std::pair < MyMesh::Point, MyMesh::Point > > point_pairs;\n\t\tfor (std::vector < std::pair <unsigned int, unsigned int> >::const_iterator it = pair_cuboid_indices.begin();\n\t\t\tit != pair_cuboid_indices.end(); ++it)\n\t\t{\n\t\t\tint cuboid_index_1 = (*it).first;\n\t\t\tint cuboid_index_2 = (*it).second;\n\t\t\tassert(cuboid_index_1 < num_cuboids);\n\t\t\tassert(cuboid_index_2 < num_cuboids);\n\n\t\t\tconst MeshCuboid *cuboid_1 = _cuboids[cuboid_index_1];\n\t\t\tconst MeshCuboid *cuboid_2 = _cuboids[cuboid_index_2];\n\n\t\t\tadd_symmety_cuboid_corner_points(cuboid_1, cuboid_2, _cuboids,\n\t\t\t\tinfo_.aligned_global_axis_index_, point_pairs);\n\t\t}\n\n\t\tassert(!point_pairs.empty());\n\t\tcompute_reflection_plane(point_pairs, n_, t_);\n\t}\n\n\treturn true;\n}\n\nvoid MeshCuboidReflectionSymmetryGroup::add_symmety_cuboid_corner_points(\n\tconst MeshCuboid *cuboid_1, const MeshCuboid *cuboid_2,\n\tconst std::vector<MeshCuboid *>& _cuboids,\n\tconst unsigned int _reflection_axis_index,\n\tstd::list< std::pair < MyMesh::Point, MyMesh::Point > > &_point_pairs)\n{\n\tassert(cuboid_1);\n\tassert(cuboid_2);\n\n\tconst unsigned int dimension = 3;\n\tassert(_reflection_axis_index < dimension);\n\n\t// NOTE:\n\t// Implemented only for 3 dimension.\n\tassert(dimension == 3);\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\tMyMesh::Point corner_point_1 = cuboid_1->get_bbox_corner(corner_index_1);\n\t\tMyMesh::Point corner_point_2 = cuboid_2->get_bbox_corner(corner_index_2);\n\t\t\n\t\t_point_pairs.push_back(std::make_pair(corner_point_1, corner_point_2));\n\t}\n}\n\nvoid MeshCuboidReflectionSymmetryGroup::compute_reflection_plane(\n\tconst std::list< std::pair < MyMesh::Point, MyMesh::Point > > &_point_pairs,\n\tMyMesh::Normal &_n, double &_t)\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\t// => max n^Tdd^Tn.\n\n\t// Eq (2):\n\t// min {n^T(x + y) - 2t}^2.\n\t// If n is estimated, t = 0.5*n^T(x + y).\n\n\tassert(!_point_pairs.empty());\n\n\tEigen::Matrix3d A = Eigen::Matrix3d::Zero();\n\tEigen::Vector3d b = Eigen::Vector3d::Zero();\n\n\tfor (std::list< std::pair < MyMesh::Point, MyMesh::Point > >::const_iterator it = _point_pairs.begin();\n\t\tit != _point_pairs.end(); ++it)\n\t{\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).first[i] + (*it).second[i];\n\t\t\tdiff_p[i] = (*it).first[i] - (*it).second[i];\n\t\t}\n\n\t\tA += (diff_p * diff_p.transpose());\n\t\tb += (0.5 * sum_p);\n\t}\n\n\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(A);\n\tEigen::Vector3d n = es.eigenvectors().col(3 - 1);\n\tfor (unsigned int i = 0; i < 3; ++i) _n[i] = n[i];\n\n\t_n.normalize();\n\t_t = (n.transpose() * b);\n\t_t /= _point_pairs.size();\n}\n\nvoid MeshCuboidReflectionSymmetryGroup::get_reflection_plane_corners(\n\tconst MyMesh::Point &_point, const Real _size,\n\tstd::array<MyMesh::Point, 4>& _corners) const\n{\n\t// Find the closest point on the plane to the given '_point'.\n\t// p_proj = (p - a) - (n'(p-a))n + a  ('a' is a point on the plane, n'a = t)\n\t// p_proj = p - (n'p)n + tn\n\n\tMyMesh::Point center = _point - dot(n_, _point) * n_ + t_ * n_;\n\n\t// Find random two axes of plane.\n\tMyMesh::Normal axes[2];\n\n\taxes[0] = MyMesh::Normal(0.0);\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t{\n\t\tMyMesh::Normal temp(0.0);\n\t\ttemp[i] = 1.0;\n\t\taxes[0] = cross(n_, temp);\n\t\tif (axes[0].norm() > 0.1)\n\t\t{\n\t\t\taxes[0].normalize();\n\t\t\tbreak;\n\t\t}\n\t}\n\tCHECK_NUMERICAL_ERROR(__FUNCTION__, axes[0].norm(), 1.0);\n\taxes[1] = cross(n_, axes[0]);\n\taxes[1].normalized();\n\n\t_corners[0] = center - 0.5 * _size * axes[0] - 0.5 * _size * axes[1];\n\t_corners[1] = center + 0.5 * _size * axes[0] - 0.5 * _size * axes[1];\n\t_corners[2] = center + 0.5 * _size * axes[0] + 0.5 * _size * axes[1];\n\t_corners[3] = center - 0.5 * _size * axes[0] + 0.5 * _size * axes[1];\n}\n\nMyMesh::Point MeshCuboidReflectionSymmetryGroup::get_symmetric_point(\n\tconst MyMesh::Point& _point, unsigned int _symmetry_order) const\n{\n\t// NOTE:\n\t// Symmetry order of 1 means reflection.\n\tassert(_symmetry_order == 1);\n\treturn get_symmetric_point(_point);\n}\n\nMyMesh::Normal MeshCuboidReflectionSymmetryGroup::get_symmetric_normal(\n\tconst MyMesh::Normal& _normal, unsigned int _symmetry_order) const\n{\n\t// NOTE:\n\t// Symmetry order of 1 means reflection.\n\tassert(_symmetry_order == 1);\n\treturn get_symmetric_normal(_normal);\n}\n\nMyMesh::Point MeshCuboidReflectionSymmetryGroup::get_symmetric_point(const MyMesh::Point& _point) const\n{\n\t// Assume that 'n_' is normalized.\n\tMyMesh::Normal plane_to_point = n_ * (dot(n_, _point) - t_);\n\tMyMesh::Point symmetric_point = _point - (plane_to_point * 2);\n\tCHECK_NUMERICAL_ERROR(__FUNCTION__, t_ - dot(n_, 0.5 * (_point + symmetric_point)));\n\treturn symmetric_point;\n}\n\nMyMesh::Normal MeshCuboidReflectionSymmetryGroup::get_symmetric_normal(const MyMesh::Normal& _normal) const\n{\n\t// Assume that 'n_' and 'normal_' are normalized.\n\tMyMesh::Normal n_direction_component = n_ * (dot(n_, _normal));\n\tMyMesh::Normal symmetric_normal = _normal - (n_direction_component * 2);\n\tCHECK_NUMERICAL_ERROR(__FUNCTION__, dot(n_, 0.5 * (_normal + symmetric_normal)));\n\treturn symmetric_normal;\n}\n\nMeshCuboidRotationSymmetryGroup* MeshCuboidRotationSymmetryGroup::constructor(\n\tconst MeshCuboidSymmetryGroupInfo &_info,\n\tconst std::vector<MeshCuboid *>& _cuboids)\n{\n\tMeshCuboidRotationSymmetryGroup *group = new MeshCuboidRotationSymmetryGroup(_info);\n\tbool ret = (group->compute_symmetry_axis(_cuboids) && group->compute_rotation_angle(_cuboids));\n\tif (!ret)\n\t{\n\t\tdelete group;\n\t\tgroup = NULL;\n\t}\n\treturn group;\n}\n\nMeshCuboidRotationSymmetryGroup::MeshCuboidRotationSymmetryGroup(\n\tconst MeshCuboidSymmetryGroupInfo &_info)\n\t: MeshCuboidSymmetryGroup(_info)\n\t, n_(MyMesh::Normal(1, 0, 0))\n\t, t_(MyMesh::Point(0, 0, 0))\n{\n\tassert(_info.symmetry_type_ == RotationSymmetryType);\n}\n\nMeshCuboidRotationSymmetryGroup::MeshCuboidRotationSymmetryGroup(\n\tconst MeshCuboidRotationSymmetryGroup &_other)\n\t: MeshCuboidSymmetryGroup(_other)\n\t, n_(_other.n_)\n\t, t_(_other.t_)\n{\n\tn_.normalize();\n\tassert(info_.symmetry_type_ == RotationSymmetryType);\n}\n\nMeshCuboidRotationSymmetryGroup::~MeshCuboidRotationSymmetryGroup()\n{\n\n}\n\nunsigned int MeshCuboidRotationSymmetryGroup::num_axis_parameters()\n{\n\treturn (3 + 3);\n}\n\nMeshCuboidSymmetryGroupType MeshCuboidRotationSymmetryGroup::get_symmetry_type() const\n{\n\tassert(info_.symmetry_type_ == RotationSymmetryType);\n\treturn info_.symmetry_type_;\n}\n\nbool MeshCuboidRotationSymmetryGroup::compute_symmetry_axis(const std::vector<MeshCuboid *>& _cuboids)\n{\n\tstd::vector<unsigned int> single_cuboid_indices;\n\tget_single_cuboid_indices(_cuboids, single_cuboid_indices);\n\tif (single_cuboid_indices.empty())\n\t\treturn false;\n\n\tconst unsigned int num_cuboids = _cuboids.size();\n\n\tstd::list<MyMesh::Normal> aligned_normals;\n\tstd::list<MyMesh::Point> aligned_centers;\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\tint cuboid_index = (*it);\n\t\tassert(cuboid_index < num_cuboids);\n\t\tconst MeshCuboid *cuboid = _cuboids[cuboid_index];\n\n\t\taligned_normals.push_back(cuboid->get_bbox_axis(get_aligned_global_axis_index()));\n\t\taligned_centers.push_back(cuboid->get_bbox_center());\n\t}\n\n\tassert(!aligned_normals.empty());\n\tassert(!aligned_centers.empty());\n\n\tEigen::Matrix3d A = Eigen::Matrix3d::Zero();\n\n\tfor (std::list<MyMesh::Normal>::const_iterator it = aligned_normals.begin();\n\t\tit != aligned_normals.end(); ++it)\n\t{\n\t\tEigen::Vector3d n_vec;\n\t\tfor (int i = 0; i < 3; ++i) n_vec[i] = (*it)[i];\n\t\tA += (n_vec * n_vec.transpose());\n\t}\n\n\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(A);\n\tEigen::Vector3d n = es.eigenvectors().col(3 - 1);\n\tfor (unsigned int i = 0; i < 3; ++i) n_[i] = n[i];\n\tn_.normalize();\n\n\tt_ = MyMesh::Point(0.0);\n\tfor (std::list<MyMesh::Point>::const_iterator it = aligned_centers.begin();\n\t\tit != aligned_centers.end(); ++it)\n\t\tt_ += (*it);\n\tt_ /= aligned_centers.size();\n\n\treturn true;\n}\n\nMyMesh::Point MeshCuboidRotationSymmetryGroup::get_symmetric_point(\n\tconst MyMesh::Point& _point, unsigned int _symmetry_order) const\n{\n\tassert(_symmetry_order > 0);\n\tassert(_symmetry_order < num_symmetry_orders_);\n\n\tEigen::Vector3d axis_vec, point_vec;\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t{\n\t\taxis_vec[i] = n_[i];\n\t\tpoint_vec[i] = _point[i] - t_[i];\n\t}\n\n\tdouble angle = get_rotation_angle() * _symmetry_order;\n\n\tEigen::AngleAxisd axis_rotation(angle, axis_vec);\n\tEigen::Vector3d rot_point_vec = axis_rotation.toRotationMatrix() * point_vec;\n\n\tMyMesh::Point rot_point;\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t\trot_point[i] = rot_point_vec[i] + t_[i];\n\n\treturn rot_point;\n}\n\nMyMesh::Normal MeshCuboidRotationSymmetryGroup::get_symmetric_normal(\n\tconst MyMesh::Normal& _normal, unsigned int _symmetry_order) const\n{\n\tassert(_symmetry_order > 0);\n\tassert(_symmetry_order < num_symmetry_orders_);\n\n\tEigen::Vector3d axis_vec, normal_vec;\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t{\n\t\taxis_vec[i] = n_[i];\n\t\tnormal_vec[i] = _normal[i];\n\t}\n\n\tdouble angle = get_rotation_angle() * (_symmetry_order + 1);\n\n\tEigen::AngleAxisd axis_rotation(angle, axis_vec);\n\tEigen::Vector3d rot_normal_vec = axis_rotation.toRotationMatrix() * normal_vec;\n\n\tMyMesh::Point ret;\n\tfor (unsigned int i = 0; i < 3; ++i)\n\t{\n\t\tret[i] = rot_normal_vec[i];\n\t}\n\n\treturn ret;\n}\n\nvoid MeshCuboidRotationSymmetryGroup::get_rotation_axis(MyMesh::Normal &_n, MyMesh::Point &_t) const\n{\n\t_n = n_;\n\t_t = t_;\n}\n\nvoid MeshCuboidRotationSymmetryGroup::set_rotation_axis(const MyMesh::Normal &_n, const MyMesh::Point &_t)\n{\n\tn_ = _n;\n\tt_ = _t;\n\tn_.normalize();\n}\n\nvoid MeshCuboidRotationSymmetryGroup::get_rotation_axis_corners(\n\tconst MyMesh::Point &_point, const Real _size, std::array<MyMesh::Point, 2>& _corners) const\n{\n\t// Find the closest point on the axis to the given '_point'.\n\t// min || n*x + t - p ||.\n\t// x = -(n^T (t - p)).\n\n\tdouble x = -dot(n_, t_ - _point);\n\tMyMesh::Point center = n_ * x + t_;\n\n\t_corners[0] = center - n_ * 0.5 * _size;\n\t_corners[1] = center + n_ * 0.5 * _size;\n}\n\nvoid MeshCuboidRotationSymmetryGroup::add_symmety_cuboid_corner_points(\n\tconst MeshCuboid *cuboid_1, const MeshCuboid *cuboid_2,\n\tconst std::vector<MeshCuboid *>& _cuboids,\n\tconst unsigned int _reflection_axis_index,\n\tstd::list< std::pair < MyMesh::Point, MyMesh::Point > > &_point_pairs)\n{\n\n}\n\nvoid MeshCuboidRotationSymmetryGroup::compute_rotation_plane(\n\tconst std::list< std::pair < MyMesh::Point, MyMesh::Point > > &_point_pairs,\n\tMyMesh::Normal &_n, double &_t)\n{\n\n}\n\nbool MeshCuboidRotationSymmetryGroup::compute_rotation_angle(\n\tconst std::vector<MeshCuboid *> &_cuboids)\n{\n\tconst Real squared_neighbor_distance = FLAGS_param_sparse_neighbor_distance\n\t\t* FLAGS_param_sparse_neighbor_distance;\n\tconst unsigned int num_cuboids = _cuboids.size();\n\n\t//\n\tstd::vector<ANNpointArray> cuboid_ann_points(num_cuboids);\n\tstd::vector<ANNkd_tree *> cuboid_ann_kd_tree(num_cuboids);\n\n\tfor (unsigned int cuboid_index = 0; cuboid_index < num_cuboids; ++cuboid_index)\n\t{\n\t\tcuboid_ann_kd_tree[cuboid_index] = NULL;\n\t\tcuboid_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\tcuboid_ann_kd_tree[cuboid_index] = ICP::create_kd_tree(cuboid_sample_points,\n\t\t\tcuboid_ann_points[cuboid_index]);\n\t\tassert(cuboid_ann_points[cuboid_index]);\n\t\tassert(cuboid_ann_kd_tree[cuboid_index]);\n\n\t\tassert(cuboid_ann_points.size() == num_cuboids);\n\t\tassert(cuboid_ann_kd_tree.size() == num_cuboids);\n\t}\n\t//\n\n\tstd::vector<unsigned int> single_cuboid_indices;\n\tget_single_cuboid_indices(_cuboids, single_cuboid_indices);\n\tif (single_cuboid_indices.empty())\n\t\treturn false;\n\n\t// FIXME.\n\tconst unsigned int min_num_symmetry_orders = 3;\n\tconst unsigned int max_num_symmetry_orders = 6;\n\tconst unsigned int default_num_symmetry_orders = 5;\n\n\tReal max_num_point_pairs = 0.0;\n\tunsigned int best_num_symmetry_orders = default_num_symmetry_orders;\n\n\tfor (unsigned int num_symmetry_orders = min_num_symmetry_orders; num_symmetry_orders <= max_num_symmetry_orders;\n\t\t++num_symmetry_orders)\n\t{\n\t\tassert(num_symmetry_orders > 2);\n\n\t\t// Temporary set symmetry order.\n\t\tnum_symmetry_orders_ = num_symmetry_orders;\n\t\tstd::list<WeightedPointPair> sample_point_pairs;\n\t\tget_symmetric_sample_point_pairs(_cuboids, cuboid_ann_points, cuboid_ann_kd_tree,\n\t\t\tsquared_neighbor_distance, sample_point_pairs);\n\n\t\tReal num_point_pairs = sample_point_pairs.size();\n\n\t\t// Divide by the number of rotations.\n\t\tnum_point_pairs /= (num_symmetry_orders - 1);\n\n\t\tstd::cout << \"[\" << num_symmetry_orders << \"]: \" << num_point_pairs << std::endl;\n\n\t\tif (num_point_pairs > max_num_point_pairs)\n\t\t{\n\t\t\tmax_num_point_pairs = num_point_pairs;\n\t\t\tbest_num_symmetry_orders = num_symmetry_orders;\n\t\t}\n\t}\n\n\t//\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\tcuboid_ann_points.clear();\n\tcuboid_ann_kd_tree.clear();\n\t//\n\n\tnum_symmetry_orders_ = best_num_symmetry_orders;\n\tstd::cout << \"num_symmetry_orders = \" << num_symmetry_orders_ << std::endl;\n\n\treturn true;\n}\n", "meta": {"hexsha": "0eb54ae9f74fb5e95cab2db2171b54eb08b6f2fa", "size": 25524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MeshCuboidSymmetryGroup.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/MeshCuboidSymmetryGroup.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/MeshCuboidSymmetryGroup.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": 29.6790697674, "max_line_length": 113, "alphanum_fraction": 0.7423993105, "num_tokens": 7752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.022629202216443645, "lm_q1q2_score": 0.009560942818594941}}
{"text": "// Copyright (C) 2004-2006 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_PARALLEL_DIJKSTRA_HPP\n#define BOOST_GRAPH_PARALLEL_DIJKSTRA_HPP\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/overloading.hpp>\n#include <boost/graph/distributed/concepts.hpp>\n#include <boost/graph/parallel/properties.hpp>\n#include <boost/graph/distributed/crauser_et_al_shortest_paths.hpp>\n#include <boost/graph/distributed/eager_dijkstra_shortest_paths.hpp>\n\nnamespace boost {\n\n  namespace graph { namespace detail {\n\n\n    template<typename Lookahead>\n    struct parallel_dijkstra_impl2\n    {\n      template<typename DistributedGraph, typename DijkstraVisitor,\n               typename PredecessorMap, typename DistanceMap,\n               typename WeightMap, typename IndexMap, typename ColorMap,\n               typename Compare, typename Combine, typename DistInf,\n               typename DistZero>\n      static void\n      run(const DistributedGraph& g,\n          typename graph_traits<DistributedGraph>::vertex_descriptor s,\n          PredecessorMap predecessor, DistanceMap distance,\n          typename property_traits<DistanceMap>::value_type lookahead,\n          WeightMap weight, IndexMap index_map, ColorMap color_map,\n          Compare compare, Combine combine, DistInf inf, DistZero zero,\n          DijkstraVisitor vis)\n      {\n        eager_dijkstra_shortest_paths(g, s, predecessor, distance, lookahead,\n                                      weight, index_map, color_map, compare,\n                                      combine, inf, zero, vis);\n      }\n    };\n\n    template<>\n    struct parallel_dijkstra_impl2< ::boost::param_not_found >\n    {\n      template<typename DistributedGraph, typename DijkstraVisitor,\n               typename PredecessorMap, typename DistanceMap,\n               typename WeightMap, typename IndexMap, typename ColorMap,\n               typename Compare, typename Combine, typename DistInf,\n               typename DistZero>\n      static void\n      run(const DistributedGraph& g,\n          typename graph_traits<DistributedGraph>::vertex_descriptor s,\n          PredecessorMap predecessor, DistanceMap distance,\n          ::boost::param_not_found,\n          WeightMap weight, IndexMap index_map, ColorMap color_map,\n          Compare compare, Combine combine, DistInf inf, DistZero zero,\n          DijkstraVisitor vis)\n      {\n        crauser_et_al_shortest_paths(g, s, predecessor, distance, weight,\n                                     index_map, color_map, compare, combine,\n                                     inf, zero, vis);\n      }\n    };\n\n    template<typename ColorMap>\n    struct parallel_dijkstra_impl\n    {\n      template<typename DistributedGraph, typename DijkstraVisitor,\n               typename PredecessorMap, typename DistanceMap,\n               typename Lookahead, typename WeightMap, typename IndexMap,\n               typename Compare, typename Combine,\n               typename DistInf, typename DistZero>\n      static void\n      run(const DistributedGraph& g,\n          typename graph_traits<DistributedGraph>::vertex_descriptor s,\n          PredecessorMap predecessor, DistanceMap distance,\n          Lookahead lookahead,\n          WeightMap weight, IndexMap index_map, ColorMap color_map,\n          Compare compare, Combine combine, DistInf inf, DistZero zero,\n          DijkstraVisitor vis)\n      {\n        graph::detail::parallel_dijkstra_impl2<Lookahead>\n          ::run(g, s, predecessor, distance, lookahead, weight, index_map,\n                color_map, compare, combine, inf, zero, vis);\n      }\n    };\n\n    template<>\n    struct parallel_dijkstra_impl< ::boost::param_not_found >\n    {\n    private:\n      template<typename DistributedGraph, typename DijkstraVisitor,\n               typename PredecessorMap, typename DistanceMap,\n               typename Lookahead, typename WeightMap, typename IndexMap,\n               typename ColorMap, typename Compare, typename Combine,\n               typename DistInf, typename DistZero>\n      static void\n      run_impl(const DistributedGraph& g,\n               typename graph_traits<DistributedGraph>::vertex_descriptor s,\n               PredecessorMap predecessor, DistanceMap distance,\n               Lookahead lookahead, WeightMap weight, IndexMap index_map,\n               ColorMap color_map, Compare compare, Combine combine,\n               DistInf inf, DistZero zero, DijkstraVisitor vis)\n      {\n        BGL_FORALL_VERTICES_T(u, g, DistributedGraph)\n          BGL_FORALL_OUTEDGES_T(u, e, g, DistributedGraph)\n            local_put(color_map, target(e, g), white_color);\n\n        graph::detail::parallel_dijkstra_impl2<Lookahead>\n          ::run(g, s, predecessor, distance, lookahead, weight, index_map,\n                color_map, compare, combine, inf, zero, vis);\n      }\n\n    public:\n      template<typename DistributedGraph, typename DijkstraVisitor,\n               typename PredecessorMap, typename DistanceMap,\n               typename Lookahead, typename WeightMap, typename IndexMap,\n               typename Compare, typename Combine,\n               typename DistInf, typename DistZero>\n      static void\n      run(const DistributedGraph& g,\n          typename graph_traits<DistributedGraph>::vertex_descriptor s,\n          PredecessorMap predecessor, DistanceMap distance,\n          Lookahead lookahead, WeightMap weight, IndexMap index_map,\n          ::boost::param_not_found,\n          Compare compare, Combine combine, DistInf inf, DistZero zero,\n          DijkstraVisitor vis)\n      {\n        typedef typename graph_traits<DistributedGraph>::vertices_size_type\n          vertices_size_type;\n\n        vertices_size_type n = num_vertices(g);\n        std::vector<default_color_type> colors(n, white_color);\n\n        run_impl(g, s, predecessor, distance, lookahead, weight, index_map,\n                 make_iterator_property_map(colors.begin(), index_map),\n                 compare, combine, inf, zero, vis);\n      }\n    };\n  } } // end namespace graph::detail\n\n\n  /** Dijkstra's single-source shortest paths algorithm for distributed\n   * graphs.\n   *\n   * Also implements the heuristics of:\n   *\n   *   Andreas Crauser, Kurt Mehlhorn, Ulrich Meyer, and Peter\n   *   Sanders. A Parallelization of Dijkstra's Shortest Path\n   *   Algorithm. In Lubos Brim, Jozef Gruska, and Jiri Zlatuska,\n   *   editors, Mathematical Foundations of Computer Science (MFCS),\n   *   volume 1450 of Lecture Notes in Computer Science, pages\n   *   722--731, 1998. Springer.\n   */\n  template<typename DistributedGraph, typename DijkstraVisitor,\n           typename PredecessorMap, typename DistanceMap,\n           typename WeightMap, typename IndexMap, typename Compare,\n           typename Combine, typename DistInf, typename DistZero,\n           typename T, typename Tag, typename Base>\n  inline\n  void\n  dijkstra_shortest_paths\n    (const DistributedGraph& g,\n     typename graph_traits<DistributedGraph>::vertex_descriptor s,\n     PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\n     IndexMap index_map,\n     Compare compare, Combine combine, DistInf inf, DistZero zero,\n     DijkstraVisitor vis,\n     const bgl_named_params<T, Tag, Base>& params\n     BOOST_GRAPH_ENABLE_IF_MODELS_PARM(DistributedGraph,distributed_graph_tag))\n  {\n    typedef typename graph_traits<DistributedGraph>::vertices_size_type\n      vertices_size_type;\n\n    // Build a distributed property map for vertex colors, if we need it\n    bool use_default_color_map\n      = is_default_param(get_param(params, vertex_color));\n    vertices_size_type n = use_default_color_map? num_vertices(g) : 1;\n    std::vector<default_color_type> color(n, white_color);\n    typedef iterator_property_map<std::vector<default_color_type>::iterator,\n                                  IndexMap> DefColorMap;\n    DefColorMap color_map(color.begin(), index_map);\n\n    typedef typename get_param_type< vertex_color_t, bgl_named_params<T, Tag, Base> >::type color_map_type;\n\n    graph::detail::parallel_dijkstra_impl<color_map_type>\n      ::run(g, s, predecessor, distance,\n            get_param(params, lookahead_t()),\n            weight, index_map,\n            get_param(params, vertex_color),\n            compare, combine, inf, zero, vis);\n  }\n} // end namespace boost\n\n#endif // BOOST_GRAPH_PARALLEL_DIJKSTRA_HPP\n", "meta": {"hexsha": "137da693fc7a9dcb6ce472683a2f5538742c6563", "size": 8684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/graph/distributed/dijkstra_shortest_paths.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/graph/distributed/dijkstra_shortest_paths.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/graph/distributed/dijkstra_shortest_paths.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": 42.3609756098, "max_line_length": 107, "alphanum_fraction": 0.680561953, "num_tokens": 1806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.023689469576183324, "lm_q1q2_score": 0.00956028470352018}}
{"text": "/*\n *            Copyright 2009-2012 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#include \"gaussian.h\"\n#include \"votca/ctp/segment.h\"\n\n#include <boost/algorithm/string.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n\n#include <stdio.h>\n#include <iomanip>\n#include <sys/stat.h>\n#include <vector>\n\nusing namespace std;\n\nnamespace votca { namespace ctp {\n    namespace ub = boost::numeric::ublas;\n    \nvoid Gaussian::Initialize( Property *options ) {\n\n    // GAUSSIAN file names\n    std::string fileName = \"system\";\n\n    _xyz_file_name = fileName + \".xyz\";\n    _input_file_name = fileName + \".com\";\n    _log_file_name = fileName + \".log\"; \n    _shell_file_name = fileName + \".sh\";\n    _orb_file_name = \"fort.7\" ;               \n    _input_vxc_file_name = fileName + \"-2.com\";\n    \n    \n    string key = \"package\";\n    string _name = options->get(key+\".name\").as<string> ();\n    \n    if ( _name != \"gaussian\" ) {\n        cerr << \"Tried to use \" << _name << \" package. \";\n        throw std::runtime_error( \"Wrong options file\");\n    }\n    \n    _executable =       options->get(key + \".executable\").as<string> ();\n    _charge =           options->get(key + \".charge\").as<int> ();\n    _spin =             options->get(key + \".spin\").as<int> ();\n    _options =          options->get(key + \".options\").as<string> ();\n    _memory =           options->get(key + \".memory\").as<string> ();\n    _threads =          options->get(key + \".threads\").as<int> ();\n    _chk_file_name  =   options->get(key + \".checkpoint\").as<string> ();\n    _scratch_dir =      options->get(key + \".scratch\").as<string> ();\n    _cleanup =          options->get(key + \".cleanup\").as<string> ();\n    \n    // check if the guess keyword is present, if yes, append the guess later\n    std::string::size_type iop_pos = _options.find(\"cards\");\n    if (iop_pos != std::string::npos) {\n        _write_guess = true;\n    } else\n    {\n        _write_guess = false;\n    }\n\n    // check if the pop keyword is present, if yes, get the charges and save them\n    iop_pos = _options.find(\"pop\");\n    if (iop_pos != std::string::npos) {\n        _get_charges = true;\n    } else\n    {\n        _get_charges = false;\n    }\n\n    // check if the charge keyword is present, if yes, get the self energy and save it\n    iop_pos = _options.find(\"charge\");\n    if (iop_pos != std::string::npos) {\n        _get_self_energy = true;\n        _write_charges = true;\n    } else\n    {\n        _get_self_energy = false;\n        _write_charges = false;\n    }\n\n    // check if the basis set is available (\"/gen\")\n    /* iop_pos = _options.find(\"gen\");\n    if (iop_pos != std::string::npos) {\n        _write_basis_set = true;\n        _basisset_name =  options->get(key + \".basisset\").as<string> ();\n    } else\n    {\n        _write_basis_set = false;\n    } */\n\n    // check if pseudopotentials are required (\"pseudo\")\n    /* iop_pos = _options.find(\"pseudo\");\n    if (iop_pos != std::string::npos) {\n        _write_pseudopotentials = true;\n    } else\n    {\n        _write_pseudopotentials = false;\n    }  */  \n    \n}    \n\n/**\n * Prepares the com file from a vector of segments\n * Appends a guess constructed from monomer orbitals if supplied\n */\nbool Gaussian::WriteInputFile( vector<Segment* > segments, Orbitals* orbitals_guess )\n{\n    vector< Atom* > _atoms;\n    vector< Atom* > ::iterator ait;\n    vector< Segment* >::iterator sit;\n    //[-Wunused-variable]\n    //int qmatoms = 0;\n\n    std::ofstream _com_file;\n    \n    string _com_file_name_full = _run_dir + \"/\" + _input_file_name;\n    \n    _com_file.open ( _com_file_name_full.c_str() );\n    // header \n    if ( _chk_file_name.size() ) _com_file << \"%chk=\" << _chk_file_name << endl;\n    if ( _memory.size() ) _com_file << \"%mem=\" << _memory << endl ;\n    if ( _threads > 0 ) _com_file << \"%nprocshared=\"  << _threads << endl;\n    if ( _options.size() ) _com_file <<  _options << endl ;\n\n    _com_file << endl;\n    _com_file << \"TITLE \";\n\n    for (sit = segments.begin() ; sit != segments.end(); ++sit) {\n        _com_file << (*sit)->getName() << \" \";\n    }\n    _com_file << endl << endl;\n    _com_file << setw(2) << _charge << setw(2) << _spin << endl;\n\n    for (sit = segments.begin() ; sit != segments.end(); ++sit) {\n        \n        _atoms = (*sit)-> Atoms();\n\n        for (ait = _atoms.begin(); ait < _atoms.end(); ++ait) {\n\n            if ((*ait)->HasQMPart() == false) { continue; }\n\n            vec     pos = (*ait)->getQMPos();\n            string  name = (*ait)->getElement();\n\n            //fprintf(out, \"%2s %4.7f %4.7f %4.7f \\n\"\n            _com_file << setw(3) << name.c_str() \n                      << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getX()*10\n                      << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getY()*10\n                      << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getZ()*10 \n                      << endl;\n        }\n    } \n    \n    if ( _write_guess ) {\n        if ( orbitals_guess == NULL ) {\n            throw std::runtime_error( \"A guess for dimer orbitals has not been prepared.\");\n        } else {\n            vector<int> _sort_index;\n            \n            orbitals_guess->SortEnergies( &_sort_index );\n            \n            _com_file << endl << \"(5D15.8)\" << endl;\n            \n            int level = 1;\n            int ncolumns = 5;\n            \n            for ( vector< int > ::iterator soi = _sort_index.begin(); soi != _sort_index.end(); ++ soi ) {\n                \n                double _energy = (orbitals_guess->_mo_energies)[*soi] ;\n                \n                _com_file  << setw(5) << level  << \" Alpha MO OE=\" << FortranFormat( _energy ) << endl;\n                \n                ub::matrix_row< ub::matrix<double> > mr (orbitals_guess->_mo_coefficients, *soi);\n                \n                int column = 1;\n                for (unsigned j = 0; j < mr.size(); ++j) {\n                        _com_file <<  FortranFormat( mr[j] );\n                        if (column == ncolumns) { _com_file << std::endl; column = 0; }\n                        column++;\n                }\n                \n                level++;\n                if ( column != 1 ) _com_file << endl;\n            } \n        }\n    }\n    \n\n\n    \n    if ( _write_charges ) {\n        vector< QMAtom* > *qmatoms = orbitals_guess->getAtoms();\n        vector< QMAtom* >::iterator it;\n        \n        // This is needed for the QM/MM scheme, since only orbitals have \n        // updated positions of the QM region, hence vector<Segments*> is \n        // NULL in the QMMachine and the QM region is also printed here\n        for (it = qmatoms->begin(); it < qmatoms->end(); it++ ) {\n            if ( !(*it)->from_environment ) {\n                _com_file << setw(3) << (*it)->type.c_str() \n                      << setw(12) << setiosflags(ios::fixed) << setprecision(5) << (*it)->x\n                      << setw(12) << setiosflags(ios::fixed) << setprecision(5) << (*it)->y\n                      << setw(12) << setiosflags(ios::fixed) << setprecision(5) << (*it)->z\n                      << endl;\n                \n                \n            //_com_file << (*it)->type << \" \" <<  (*it)->x << \" \" << (*it)->y << \" \" << (*it)->z << endl;\n            }\n        }\n        \n        _com_file << endl;\n        \n        for (it = qmatoms->begin(); it < qmatoms->end(); it++ ) {\n            if ( (*it)->from_environment ) {\n                boost::format fmt(\"%1$+1.7f %2$+1.7f %3$+1.7f %4$+1.7f\");\n                fmt % (*it)->x % (*it)->y % (*it)->z % (*it)->charge;\n                if ((*it)->charge != 0.0 ) _com_file << fmt << endl;\n            }\n        }\n        \n        _com_file << endl;\n    }\n    \n    _com_file << endl;\n    _com_file.close();\n            // and now generate a shell script to run both jobs\n        WriteShellScript();\n    return true;\n}\n\nbool Gaussian::WriteShellScript() {\n    std::ofstream _shell_file;\n    \n    string _shell_file_name_full = _run_dir + \"/\" + _shell_file_name;\n            \n    _shell_file.open ( _shell_file_name_full.c_str() );\n\n    _shell_file << \"#!/bin/tcsh\" << endl ;\n    _shell_file << \"mkdir -p \" << _scratch_dir << endl;\n    _shell_file << \"setenv GAUSS_SCRDIR \" << _scratch_dir << endl;\n    _shell_file << _executable << \" \" << _input_file_name << endl; \n/*    if ( _write_pseudopotentials ) {\n        _shell_file << \"rm fort.22\" << endl;\n        _shell_file << \"setenv DoPrtXC YES\" << endl;\n        _shell_file << _executable << \" \" << _input_vxc_file_name << \" >& /dev/null \" << endl; \n        _shell_file << \"setenv DoPrtXC NO\" << endl;    \n        _shell_file << \"rm $GAUSS_SCRDIR\" << endl;\n    } */\n    _shell_file.close();\n    \n    return true;\n}\n\n/**\n * Runs the Gaussian job. \n */\nbool Gaussian::Run()\n{\n\n    CTP_LOG(logDEBUG,*_pLog) << \"GAUSSIAN: running [\" << _executable << \" \" << _input_file_name << \"]\" << flush;\n    \n    if (system(NULL)) {\n        // if scratch is provided, run the shell script; \n        // otherwise run gaussian directly and rely on global variables \n        string _command;\n        if ( _scratch_dir.size() != 0 || _write_pseudopotentials ) {\n            _command  = \"cd \" + _run_dir + \"; tcsh \" + _shell_file_name;\n//            _command  = \"cd \" + _run_dir + \"; mkdir -p \" + _scratch_dir +\"; \" + _executable + \" \" + _input_file_name;\n        }\n        else {\n            _command  = \"cd \" + _run_dir + \"; mkdir -p $GAUSS_SCRDIR; \" + _executable + \" \" + _input_file_name;\n        }\n\n        int i = system ( _command.c_str() );\n        CTP_LOG(logDEBUG,*_pLog) << \"GAUSSIAN: finished running with the status \" << i << flush;\n        \n        if ( CheckLogFile() ) {\n            CTP_LOG(logDEBUG,*_pLog) << \"GAUSSIAN: finished job\" << flush;\n            return true;\n        } else {\n            CTP_LOG(logDEBUG,*_pLog) << \"GAUSSIAN: job failed\" << flush;\n        }\n    }\n    else {\n        CTP_LOG(logERROR,*_pLog) << _input_file_name << \" failed to start\" << flush; \n        return false;\n    }\n    \n    return true;\n\n}\n\n/**\n * Cleans up after the Gaussian job\n */\nvoid Gaussian::CleanUp() {\n    \n    // cleaning up the generated files\n    if ( _cleanup.size() != 0 ) {\n        \n        CTP_LOG(logDEBUG,*_pLog) << \"Removing \" << _cleanup << \" files\" << flush;        \n        Tokenizer tok_cleanup(_cleanup, \",\");\n        vector <string> _cleanup_info;\n        tok_cleanup.ToVector(_cleanup_info);\n        \n        vector<string> ::iterator it;\n               \n        for (it = _cleanup_info.begin(); it != _cleanup_info.end(); ++it) {\n            \n            if ( *it == \"com\" ) {\n                string file_name = _run_dir + \"/\" + _input_file_name;\n                remove ( file_name.c_str() );\n            }\n            \n            if ( *it == \"sh\" ) {\n                string file_name = _run_dir + \"/\" + _shell_file_name;\n                remove ( file_name.c_str() );\n            }\n            \n            if ( *it == \"log\" ) {\n                string file_name = _run_dir + \"/\" + _log_file_name;\n                remove ( file_name.c_str() );\n            }\n\n           if ( *it == \"chk\" ) {\n                string file_name = _run_dir + \"/\" + _chk_file_name;\n                remove ( file_name.c_str() );\n            }\n            \n            if ( *it == \"fort.7\" ) {\n                string file_name = _run_dir + \"/\" + *it;\n                remove ( file_name.c_str() );\n            }            \n        }\n    }\n    \n}\n\n\n\n/**\n * Reads in the MO coefficients from a GAUSSIAN fort.7 file\n */\nbool Gaussian::ParseOrbitalsFile( Orbitals* _orbitals )\n{\n    std::map <int, std::vector<double> > _coefficients;\n    std::map <int, double> _energies;\n    \n    std::string _line;\n    unsigned _levels = 0;\n    unsigned _level = 0;\n    unsigned _basis_size = 0;\n\n    string _orb_file_name_full = _orb_file_name ;\n    if ( _run_dir != \"\" )  _orb_file_name_full  = _run_dir + \"/\" + _orb_file_name;\n    std::ifstream _input_file( _orb_file_name_full.c_str() );\n    \n    if (_input_file.fail()) {\n        CTP_LOG( logERROR, *_pLog ) << \"File \" << _orb_file_name << \" with molecular orbitals is not found \" << flush;\n        return false;\n    } else {\n        CTP_LOG(logDEBUG, *_pLog) << \"Reading MOs from \" << _orb_file_name << flush;\n    }\n\n    // number of coefficients per line is  in the first line of the file (5D15.8)\n    getline(_input_file, _line);\n    std::vector<string> strs;\n    boost::algorithm::split(strs, _line, boost::is_any_of(\"(D)\"));\n    //clog << strs.at(1) << endl;\n    \n    //[-Wunused-variable]\n    //int nrecords_in_line = boost::lexical_cast<int>(strs.at(1));\n    //string format = strs.at(2);\n\n    //clog << endl << \"Orbital file \" << filename << \" has \" \n    //        << nrecords_in_line << \" records per line, in D\"\n    //        << format << \" format.\" << endl;\n\n    while (_input_file) {\n\n        getline(_input_file, _line);\n        // if a line has an equality sign, must be energy\n        std::string::size_type energy_pos = _line.find(\"=\");\n\n        if (energy_pos != std::string::npos) {\n\n            vector<string> results;\n            boost::trim( _line );\n            \n            boost::algorithm::split(results, _line, boost::is_any_of(\"\\t =\"),\n                    boost::algorithm::token_compress_on); \n            //cout << results[1] << \":\" << results[2] << \":\" << results[3] << \":\" << results[4] << endl;\n            \n            _level = boost::lexical_cast<int>(results.front());\n            boost::replace_first(results.back(), \"D\", \"e\");\n            _energies[ _level ] = boost::lexical_cast<double>( results.back() );            \n            _levels++;\n\n        } else {\n            \n            while (_line.size() > 1) {\n                string _coefficient;\n                _coefficient.assign( _line, 0, 15 );\n                boost::trim( _coefficient );\n                boost::replace_first( _coefficient, \"D\", \"e\" );\n                double coefficient = boost::lexical_cast<double>( _coefficient );\n                _coefficients[ _level ].push_back( coefficient );\n                _line.erase(0, 15);\n            }\n        }\n    }\n\n    // some sanity checks\n    CTP_LOG( logDEBUG, *_pLog ) << \"Energy levels: \" << _levels << flush;\n\n    std::map< int, vector<double> >::iterator iter = _coefficients.begin();\n    _basis_size = iter->second.size();\n\n    for (iter = _coefficients.begin()++; iter != _coefficients.end(); iter++) {\n        if (iter->second.size() != _basis_size) {\n            CTP_LOG( logERROR, *_pLog ) << \"Error reading \" << _orb_file_name << \". Basis set size change from level to level.\" << flush;\n            return false;\n        }\n    }\n    \n    CTP_LOG( logDEBUG, *_pLog ) << \"Basis set size: \" << _basis_size << flush;\n\n    // copying information to the orbitals object\n    _orbitals->setBasisSetSize( _basis_size ); // = _basis_size;\n    // _orbitals->_has_basis_set_size = true;\n    // _orbitals->_has_mo_coefficients = true;\n    // _orbitals->_has_mo_energies = true;\n    \n    // copying energies to the orbitals object  \n    ub::vector<double> &mo_energies = _orbitals->MOEnergies();   \n    mo_energies.resize( _levels );\n    for(size_t i=0; i < mo_energies.size(); i++) mo_energies[i] = _energies[ i+1 ];\n   \n    // copying mo coefficients to the orbitals object\n    ub::matrix<double> &mo_coefficients = _orbitals->MOCoefficients(); \n    mo_coefficients.resize( _levels, _basis_size );     \n    for(size_t i = 0; i < mo_coefficients.size1(); i++) \n    for(size_t j = 0; j < mo_coefficients.size2(); j++) \n          _orbitals->_mo_coefficients(i,j) = _coefficients[i+1][j];\n\n    \n   //cout << _mo_energies << endl;   \n   //cout << _mo_coefficients << endl; \n        \n   CTP_LOG(logDEBUG, *_pLog) << \"GAUSSIAN: done reading MOs\" << flush;\n\n   return true;\n}\n\nbool Gaussian::CheckLogFile() {\n    \n    // check if the log file exists\n    boost::filesystem::path arg_path;\n    char ch;\n    \n    std::string _full_name = ( arg_path / _run_dir / _log_file_name ).c_str();\n    ifstream _input_file( _full_name.c_str() );\n    \n    if (_input_file.fail()) {\n        CTP_LOG(logERROR,*_pLog) << \"GAUSSIAN: \" << _full_name << \" is not found\" << flush;\n        return false;\n    };\n\n    _input_file.seekg(0,ios_base::end);   // go to the EOF\n    \n    // get empty lines and end of lines out of the way\n    do {\n        _input_file.seekg(-2, ios_base::cur);\n        _input_file.get(ch);   \n        //cout << \"\\nChar: \" << ch << endl;\n    } while ( ch == '\\n' || ch == ' ' || ch == '\\t' || (int)_input_file.tellg() == -1 );\n \n    // get the beginning of the line or the file\n    do {\n       _input_file.seekg(-2,ios_base::cur);\n       _input_file.get(ch);   \n       //cout << \"\\nNext Char: \" << ch << \" TELL G \" <<  (int)_input_file.tellg() << endl;\n    } while ( ch != '\\n' && (int)_input_file.tellg() != -1 );\n            \n    string _line;            \n    getline(_input_file,_line);                      // Read the current line\n    //cout << \"\\nResult: \" << _line << '\\n';     // Display it\n    _input_file.close();\n        \n    std::string::size_type self_energy_pos = _line.find(\"Normal termination of Gaussian\");\n    if (self_energy_pos == std::string::npos) {\n            CTP_LOG(logERROR,*_pLog) << \"GAUSSIAN: \" << _full_name  <<  \" is incomplete\" << flush;\n            return false;      \n    } else {\n            //CTP_LOG(logDEBUG,*_pLog) << \"Gaussian CTP_LOG is complete\" << flush;\n            return true;\n    }\n}\n\n/**\n * Parses the Gaussian Log file and stores data in the Orbitals object \n */\nbool Gaussian::ParseLogFile( Orbitals* _orbitals ) {\n\n    static const double _conv_Hrt_eV = 27.21138386;\n\n    string _line;\n    vector<string> results;\n    bool _has_occupied_levels = false;\n    bool _has_unoccupied_levels = false;\n    bool _has_number_of_electrons = false;\n    bool _has_basis_set_size = false;\n    bool _has_overlap_matrix = false;\n    //[-Wunused-but-set-variable]\n    //bool _has_vxc_matrix = false;\n    bool _has_charges = false;\n    //[-Wunused-but-set-variable]\n    //bool _has_coordinates = false;\n    //[-Wunused-but-set-variable]\n    //bool _has_qm_energy = false;\n    bool _has_self_energy = false;\n    \n    //bool _read_vxc = false;\n    \n    int _occupied_levels = 0;\n    int _unoccupied_levels = 0;\n    int _number_of_electrons = 0;\n    int _basis_set_size = 0;\n    //int _cart_basis_set_size;\n    \n    CTP_LOG(logDEBUG,*_pLog) << \"GAUSSIAN: parsing \" << _log_file_name << flush;\n    \n    string _log_file_name_full =  _log_file_name;\n    if ( _run_dir != \"\" ) _log_file_name_full =  _run_dir + \"/\" + _log_file_name;\n\n    // check if CTP_LOG file is complete\n    if ( !CheckLogFile() ) return false;\n    \n    // save qmpackage name\n    //_orbitals->_has_qm_package = true;\n    _orbitals->setQMpakckage(\"gaussian\"); \n    \n    \n    // Start parsing the file line by line\n    ifstream _input_file(_log_file_name_full.c_str());\n    while (_input_file) {\n\n        getline(_input_file, _line);\n        boost::trim(_line);\n\n        /*\n         * Check is pseudo keyword is present in CTP_LOG file -> read vxc\n         */\n      /*  std::string::size_type pseudo_pos = _line.find(\"pseudo=read\");\n         if (pseudo_pos != std::string::npos) {\n             _read_vxc = true;\n         }*/\n        \n        /* Check for ScaHFX = factor of HF exchange included in functional */\n        /*std::string::size_type HFX_pos = _line.find(\"ScaHFX=\");\n         if (HFX_pos != std::string::npos) {\n             boost::algorithm::split(results, _line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n             double _ScaHFX = boost::lexical_cast<double>(results.back()) ;\n             _orbitals->setScaHFX( _ScaHFX );\n             CTP_LOG(logDEBUG,*_pLog) << \"DFT with \" << _ScaHFX << \" of HF exchange!\" << flush ;\n         } */\n        \n        \n        \n        /*\n         * number of occupied and virtual orbitals\n         * N alpha electrons      M beta electrons\n         */\n        std::string::size_type electrons_pos = _line.find(\"alpha electrons\");\n        if (electrons_pos != std::string::npos) {\n            boost::algorithm::split(results, _line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n            _has_number_of_electrons = true;\n            _number_of_electrons =  boost::lexical_cast<int>(results.front()) ;\n            _orbitals->setNumberOfElectrons( _number_of_electrons );\n            // _orbitals->_has_number_of_electrons = true;\n            CTP_LOG(logDEBUG,*_pLog) << \"Alpha electrons: \" << _number_of_electrons << flush ;\n        }\n\n        /*\n         * basis set size\n         * N basis functions,  M primitive gaussians,   K cartesian basis functions\n         */\n        std::string::size_type basis_pos = _line.find(\"basis functions,\");\n        if (basis_pos != std::string::npos) {\n            boost::algorithm::split(results, _line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n            _has_basis_set_size = true;\n            _basis_set_size = boost::lexical_cast<int>(results.front());\n            _orbitals->setBasisSetSize( _basis_set_size );\n            // _orbitals->_has_basis_set_size = true;\n            // _cart_basis_set_size = boost::lexical_cast<int>(results[6] );\n            CTP_LOG(logDEBUG,*_pLog) << \"Basis functions: \" << _basis_set_size << flush;\n            /*if ( _read_vxc ) {\n                CTP_LOG(logDEBUG,*_pLog) << \"Cartesian functions: \" << _cart_basis_set_size << flush;\n            }*/\n        }\n\n        /*\n         * energies of occupied/unoccupied levels\n         * Alpha  occ.(virt.) eigenvalues -- e1 e2 e3 e4 e5\n         */\n        std::string::size_type eigenvalues_pos = _line.find(\"Alpha\");\n        if (eigenvalues_pos != std::string::npos) {\n            \n            std::list<std::string> stringList;\n            //int _unoccupied_levels = 0;\n            //int _occupied_levels = 0;\n\n            while (eigenvalues_pos != std::string::npos && !_has_occupied_levels && !_has_unoccupied_levels) {\n                //cout << _line << endl;\n\n                boost::iter_split(stringList, _line, boost::first_finder(\"--\"));\n\n                vector<string> energies;\n                boost::trim(stringList.back());\n\n                boost::algorithm::split(energies, stringList.back(), boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n\n                if (stringList.front().find(\"virt.\") != std::string::npos) {\n                    _unoccupied_levels += energies.size();\n                    energies.clear();\n                }\n\n                if (stringList.front().find(\"occ.\") != std::string::npos) {\n                    _occupied_levels += energies.size();\n                    energies.clear();\n                }\n\n                getline(_input_file, _line);\n                eigenvalues_pos = _line.find(\"Alpha\");\n                boost::trim(_line);\n\n                //boost::iter_split(stringList, _line, boost::first_finder(\"--\"));\n\n                if (eigenvalues_pos == std::string::npos) {\n                    _has_occupied_levels = true;\n                    _has_unoccupied_levels = true;\n                    _orbitals->setNumberOfLevels( _occupied_levels , _unoccupied_levels );\n                    // _orbitals->_occupied_levels = _occupied_levels;\n                    // _orbitals->_unoccupied_levels = _unoccupied_levels;\n                    // _orbitals->_has_occupied_levels = true;\n                    // _orbitals->_has_unoccupied_levels = true;\n                    CTP_LOG(logDEBUG,*_pLog) << \"Occupied levels: \" << _occupied_levels << flush;\n                    CTP_LOG(logDEBUG,*_pLog) << \"Unoccupied levels: \" << _unoccupied_levels << flush;\n                    \n                    if ( _occupied_levels != _number_of_electrons ) { std::runtime_error(\"Gaussian Log file has energy fields merged\"); }\n                    \n                }\n            } // end of the while loop              \n        } // end of the eigenvalue parsing\n        \n \n         /*\n         * overlap matrix\n         * stored after the *** Overlap *** line\n         */\n        std::string::size_type overlap_pos = _line.find(\"*** Overlap ***\");\n        if (overlap_pos != std::string::npos ) {\n            \n            // prepare the container\n            ub::symmetric_matrix<double> &overlap = _orbitals->AOOverlap();\n                    \n            // _orbitals->_has_overlap = true;\n            overlap.resize( _basis_set_size );\n            \n            _has_overlap_matrix = true;\n            //cout << \"Found the overlap matrix!\" << endl;   \n            vector<int> _j_indeces;\n            \n            int _n_blocks = 1 + (( _basis_set_size - 1 ) / 5);\n            //cout << _n_blocks;\n            \n            getline(_input_file, _line); boost::trim( _line );\n\n            for (int _block = 0; _block < _n_blocks; _block++ ) {\n                \n                // first line gives the j index in the matrix\n                //cout << _line << endl;\n                \n                boost::tokenizer<> tok( _line );\n                std::transform( tok.begin(), tok.end(), std::back_inserter( _j_indeces ), &boost::lexical_cast<int,std::string> );\n                //std::copy( _j_indeces.begin(), _j_indeces.end(), std::ostream_iterator<int>(std::cout,\"\\n\") );\n            \n                // read the block of max _basis_size lines + the following header\n                for (int i = 0; i <= _basis_set_size; i++ ) {\n                    getline (_input_file, _line); \n                    //cout << _line << endl;\n                    if ( std::string::npos == _line.find(\"D\") ) break;\n                    \n                    // split the line on the i index and the rest\n                    \n                    vector<string> _row;\n                    boost::trim( _line );\n                    boost::algorithm::split( _row , _line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on); \n                   \n                            \n                    int _i_index = boost::lexical_cast<int>(  _row.front()  ); \n                    _row.erase( _row.begin() );\n                    \n                    //cout << _i_index << \":\" << _line << endl ;\n                    \n                    std::vector<int>::iterator _j_iter = _j_indeces.begin();\n                    \n                    for (std::vector<string>::iterator iter = _row.begin()++; iter != _row.end(); iter++) {\n                        string  _coefficient = *iter;\n                       \n                        boost::replace_first( _coefficient, \"D\", \"e\" );\n                        //cout << boost::lexical_cast<double>( _coefficient ) << endl;\n                        \n                        int _j_index = *_j_iter;                                \n                        //_overlap( _i_index-1 , _j_index-1 ) = boost::lexical_cast<double>( _coefficient );\n                        overlap( _i_index-1 , _j_index-1 ) = boost::lexical_cast<double>( _coefficient );\n                        _j_iter++;\n                        \n                    }\n \n                    \n                }\n                \n                // clear the index for the next block\n                _j_indeces.clear();        \n            } // end of the blocks\n            CTP_LOG(logDEBUG,*_pLog) << \"Read the overlap matrix\" << flush;\n        } // end of the if \"Overlap\" found   \n\n        \n        /*\n         *  Partial charges from the input file\n         */\n        std::string::size_type charge_pos = _line.find(\"Charges from ESP fit, RMS\");\n        \n        if (charge_pos != std::string::npos && _get_charges ) {        \n                CTP_LOG(logDEBUG,*_pLog) << \"Getting charges\" << flush;\n                _has_charges = true;\n                getline(_input_file, _line);\n                getline(_input_file, _line);\n                \n                bool _has_atoms = _orbitals->hasQMAtoms();\n                \n                vector<string> _row;\n                getline(_input_file, _line);\n                boost::trim( _line );\n                //cout << _line << endl;\n                boost::algorithm::split( _row , _line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on); \n                int nfields =  _row.size();\n                //cout << _row.size() << endl;\n                \n                while ( nfields == 3 ) {\n                    int atom_id = boost::lexical_cast< int >( _row.at(0) );\n                    \n                    //[-Wunused-variable]\n                    //int atom_number = boost::lexical_cast< int >( _row.at(0) );\n                    \n                    string atom_type = _row.at(1);\n                    double atom_charge = boost::lexical_cast< double >( _row.at(2) );\n                    //if ( tools::globals::verbose ) cout << \"... ... \" << atom_id << \" \" << atom_type << \" \" << atom_charge << endl;\n                    getline(_input_file, _line);\n                    boost::trim( _line );\n                    boost::algorithm::split( _row , _line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);  \n                    nfields =  _row.size();\n                    \n                     if ( _has_atoms == false ) {\n                         _orbitals->AddAtom( atom_type, 0, 0, 0, atom_charge );\n                     } else {\n                         QMAtom* pAtom = _orbitals->_atoms.at( atom_id - 1 );\n                         pAtom->type = atom_type;\n                         pAtom->charge = atom_charge;\n                     }\n                    \n                }\n                //_orbitals->_has_atoms = true;\n        }\n        \n\n         /*\n         * Coordinates of the final configuration\n         * stored in the archive at the end of the file\n         */\n        int cpn = 0; // marker appearence marker\n        std::string::size_type coordinates_pos = _line.find(\"\\\\\");\n        \n        if (coordinates_pos != std::string::npos && cpn == 0) {\n            ++cpn; // updates but ignores\n            CTP_LOG(logDEBUG,*_pLog) << \"Getting the coordinates\" << flush;\n            //_has_coordinates = true;\n            boost::trim(_line);\n            string archive = _line;\n            while ( _line.size() != 0 ) {\n                getline(_input_file, _line);\n                boost::trim(_line);\n                archive += _line;\n            }\n                            \n            bool _has_atoms = _orbitals->hasQMAtoms();\n            std::list<std::string> stringList;\n            vector<string> results;\n            boost::iter_split( stringList, archive, boost::first_finder(\"\\\\\\\\\") );\n            \n            list<string>::iterator coord_block = stringList.begin();\n            advance(coord_block, 3);\n            \n            vector<string> atom_block;\n            boost::algorithm::split(atom_block, *coord_block, boost::is_any_of(\"\\\\\"), boost::algorithm::token_compress_on);\n            \n            vector<string>::iterator atom_block_it;\n            int aindex = 0;\n            \n            for(atom_block_it =  ++atom_block.begin(); atom_block_it != atom_block.end(); ++atom_block_it) {\n                vector<string> atom;\n                \n                boost::algorithm::split(atom, *atom_block_it, boost::is_any_of(\",\"), boost::algorithm::token_compress_on);\n                string _atom_type = atom.front() ; \n                \n                vector<string>::iterator it_atom;\n                it_atom = atom.end();\n                double _z =  boost::lexical_cast<double>( *(--it_atom) );\n                double _y =  boost::lexical_cast<double>( *(--it_atom) );\n                double _x =  boost::lexical_cast<double>( *(--it_atom) );\n                \n                if ( _has_atoms == false ) {\n                        _orbitals->AddAtom( _atom_type, _x, _y, _z );\n                } else {\n                         QMAtom* pAtom = _orbitals->_atoms.at( aindex );\n                         pAtom->type = _atom_type;\n                         pAtom->x = _x;\n                         pAtom->y = _y;\n                         pAtom->z = _z;\n                         aindex++;\n                }\n                \n            }\n            \n            // get the QM energy out\n            advance(coord_block, 1);\n            vector<string> block;\n            vector<string> energy;\n            boost::algorithm::split(block, *coord_block, boost::is_any_of(\"\\\\\"), boost::algorithm::token_compress_on);\n            //boost::algorithm::split(energy, block[1], boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n            //_orbitals->setQMEnergy( _conv_Hrt_eV * boost::lexical_cast<double> ( energy[1] ) );\n            map<string,string> properties;\n            vector<string>::iterator block_it;\n            for (block_it = block.begin(); block_it != block.end(); ++block_it) {\n                vector<string> property;\n                boost::algorithm::split(property, *block_it, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n                properties[property[0]] = property[1];                \n            }\n            CTP_LOG(logDEBUG, *_pLog) << \"QM energy \" << _orbitals->getQMEnergy() <<  flush;\n            //_has_qm_energy = true;\n            //_orbitals->_has_atoms = true;\n            //_orbitals->_has_qm_energy = true;\n            if (properties.count(\"HF\") > 0) {\n                double energy_hartree = boost::lexical_cast<double>(properties[\"HF\"]);\n                //_orbitals->setQMEnergy(_has_qm_energy = true;\n                _orbitals-> setQMEnergy( _conv_Hrt_eV * energy_hartree );\n                CTP_LOG(logDEBUG, *_pLog) << \"QM energy \" << _orbitals->_qm_energy <<  flush;\n            }\n            else {\n                cout << endl;\n                throw std::runtime_error(\"ERROR No energy in archive\");\n            }\n            \n//            boost::algorithm::split(energy, block[1], boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n//            cout << endl << energy[1] << endl;\n//            _orbitals->_qm_energy = _conv_Hrt_eV * boost::lexical_cast<double> ( energy[1] );\n//            \n//            CTP_LOG(logDEBUG, *_pLog) << \"QM energy \" << _orbitals->_qm_energy <<  flush;\n//            _has_qm_energy = true;\n\n        }\n\n         /*\n         * Self-energy of external charges\n         */\n         std::string::size_type self_energy_pos = _line.find(\"Self energy of the charges\");\n        \n        if (self_energy_pos != std::string::npos) {\n            //CTP_LOG(logDEBUG,*_pLog) << \"Getting the self energy\\n\" << flush;\n            vector<string> block;\n            vector<string> energy;\n            boost::algorithm::split(block, _line, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n            boost::algorithm::split(energy, block[1], boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n            \n            // _orbitals->_has_self_energy = true;\n            _orbitals->setSelfEnergy( _conv_Hrt_eV * boost::lexical_cast<double> ( energy[1] ) );\n            \n            CTP_LOG(logDEBUG, *_pLog) << \"Self energy = \" << _orbitals->getSelfEnergy() <<  flush;\n\n        }\n        \n        // check if all information has been accumulated and quit \n        if ( _has_number_of_electrons && \n             _has_basis_set_size && \n             _has_occupied_levels && \n             _has_unoccupied_levels &&\n             _has_overlap_matrix &&\n             _has_charges && \n             _has_self_energy\n           ) break;\n        \n    } // end of reading the file line-by-line\n\n    CTP_LOG(logDEBUG,*_pLog) << \"Done parsing\" << flush;\n    _input_file.close();\n    \n    /* Now, again the somewhat ugly construction:\n     * if we request writing of pseudopotential data to the input file, this\n     * implies a GW-BSE run. For this, we have to \n     * - parse atomic orbitals Vxc matrix */\n  /* if ( _read_vxc ) {\n        CTP_LOG(logDEBUG,*_pLog) << \"Parsing fort.24 for Vxc\"  << flush;\n        string _log_file_name_full;\n        if ( _run_dir == \"\" ){\n            _log_file_name_full =  \"fort.24\";\n        }else{\n                _log_file_name_full =  _run_dir + \"/fort.24\";\n        }\n        \n        \n       // prepare the container\n       // _orbitals->_has_vxc = true;\n       ub::symmetric_matrix<double>& _vxc = _orbitals->AOVxc(); \n       _vxc.resize( _cart_basis_set_size  );\n            \n\n       //_has_vxc_matrix = true;\n       //cout << \"Found the overlap matrix!\" << endl;   \n       vector<int> _j_indeces;\n        \n        \n        // Start parsing the file line by line\n        ifstream _input_file(_log_file_name_full.c_str());\n        while (_input_file) {\n           getline (_input_file, _line); \n           if( _input_file.eof() ) break;\n                    \n           vector<string> _row;\n           boost::trim( _line );\n           boost::algorithm::split( _row , _line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on); \n                \n           int _i_index = boost::lexical_cast<int>(  _row[0]  ); \n           int _j_index = boost::lexical_cast<int>(  _row[1]  );\n           //cout << \"Vxc element [\" << _i_index << \":\" << _j_index << \"] \" << boost::lexical_cast<double>( _row[2] ) << endl;\n           _vxc( _i_index-1 , _j_index-1 ) = boost::lexical_cast<double>( _row[2] );\n        }\n        \n        CTP_LOG(logDEBUG,*_pLog) << \"Done parsing\" << flush;\n        _input_file.close();\n   }*/\n    \n    \n    \n\n    return true;\n}\n\n\nstring Gaussian::FortranFormat( const double &number ) {\n    stringstream _ssnumber;\n    if ( number >= 0) _ssnumber << \" \";\n    _ssnumber <<  setiosflags(ios::fixed) << setprecision(8) << std::scientific << number;\n    std::string _snumber = _ssnumber.str(); \n    boost::replace_first(_snumber, \"e\", \"D\");\n    return _snumber;\n}\n\n        \n\n\n\n}}\n", "meta": {"hexsha": "1e7e49b223b354d16d29d4dd9c195cb7d22f52f7", "size": 38352, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libctp/qmpackages/gaussian.cc", "max_stars_repo_name": "mbarbry/ctp", "max_stars_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "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/libctp/qmpackages/gaussian.cc", "max_issues_repo_name": "mbarbry/ctp", "max_issues_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libctp/qmpackages/gaussian.cc", "max_forks_repo_name": "mbarbry/ctp", "max_forks_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56", "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.583501006, "max_line_length": 137, "alphanum_fraction": 0.5243533584, "num_tokens": 9488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.03514484715873382, "lm_q1q2_score": 0.0095602612716226}}
{"text": "// Copyright 2004, 2005 The Trustees of Indiana University.\r\n\r\n// Use, modification and distribution is subject to the Boost Software\r\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Nick Edmonds\r\n//           Andrew Lumsdaine\r\n#ifndef BOOST_GRAPH_SSCA_GENERATOR_HPP\r\n#define BOOST_GRAPH_SSCA_GENERATOR_HPP\r\n\r\n#include <iterator>\r\n#include <utility>\r\n#include <vector>\r\n#include <queue>\r\n#include <boost/config.hpp>\r\n#include <boost/random/uniform_int.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/type_traits/is_base_and_derived.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\nenum Direction\r\n{\r\n    FORWARD = 1,\r\n    BACKWARD = 2,\r\n    BOTH = FORWARD | BACKWARD\r\n};\r\n\r\nnamespace boost\r\n{\r\n\r\n// This generator generates graphs according to the method specified\r\n// in SSCA 1.1.  Current versions of SSCA use R-MAT graphs\r\n\r\ntemplate < typename RandomGenerator, typename Graph > class ssca_iterator\r\n{\r\n    typedef typename graph_traits< Graph >::directed_category directed_category;\r\n    typedef\r\n        typename graph_traits< Graph >::vertices_size_type vertices_size_type;\r\n\r\npublic:\r\n    typedef std::input_iterator_tag iterator_category;\r\n    typedef std::pair< vertices_size_type, vertices_size_type > value_type;\r\n    typedef const value_type& reference;\r\n    typedef const value_type* pointer;\r\n    typedef void difference_type;\r\n\r\n    // No argument constructor, set to terminating condition\r\n    ssca_iterator() : gen(), verticesRemaining(0) {}\r\n\r\n    // Initialize for edge generation\r\n    ssca_iterator(RandomGenerator& gen, vertices_size_type totVertices,\r\n        vertices_size_type maxCliqueSize, double probUnidirectional,\r\n        int maxParallelEdges, double probIntercliqueEdges)\r\n    : gen(&gen)\r\n    , totVertices(totVertices)\r\n    , maxCliqueSize(maxCliqueSize)\r\n    , probUnidirectional(probUnidirectional)\r\n    , maxParallelEdges(maxParallelEdges)\r\n    , probIntercliqueEdges(probIntercliqueEdges)\r\n    , currentClique(0)\r\n    , verticesRemaining(totVertices)\r\n    {\r\n        cliqueNum = std::vector< int >(totVertices, -1);\r\n        current = std::make_pair(0, 0);\r\n    }\r\n\r\n    reference operator*() const { return current; }\r\n    pointer operator->() const { return &current; }\r\n\r\n    ssca_iterator& operator++()\r\n    {\r\n        BOOST_USING_STD_MIN();\r\n        while (values.empty() && verticesRemaining > 0)\r\n        { // If there are no values left, generate a new clique\r\n            uniform_int< vertices_size_type > clique_size(1, maxCliqueSize);\r\n            uniform_int< vertices_size_type > rand_vertex(0, totVertices - 1);\r\n            uniform_int< int > num_parallel_edges(1, maxParallelEdges);\r\n            uniform_int< short > direction(0, 1);\r\n            uniform_01< RandomGenerator > prob(*gen);\r\n            std::vector< vertices_size_type > cliqueVertices;\r\n\r\n            cliqueVertices.clear();\r\n            vertices_size_type size = min BOOST_PREVENT_MACRO_SUBSTITUTION(\r\n                clique_size(*gen), verticesRemaining);\r\n            while (cliqueVertices.size() < size)\r\n            {\r\n                vertices_size_type v = rand_vertex(*gen);\r\n                if (cliqueNum[v] == -1)\r\n                {\r\n                    cliqueNum[v] = currentClique;\r\n                    cliqueVertices.push_back(v);\r\n                    verticesRemaining--;\r\n                }\r\n            } // Nick: This is inefficient when only a few vertices remain...\r\n              //       I should probably just select the remaining vertices\r\n              //       in order when only a certain fraction remain.\r\n\r\n            typename std::vector< vertices_size_type >::iterator first, second;\r\n            for (first = cliqueVertices.begin(); first != cliqueVertices.end();\r\n                 ++first)\r\n                for (second = first + 1; second != cliqueVertices.end();\r\n                     ++second)\r\n                {\r\n                    Direction d;\r\n                    int edges;\r\n\r\n                    d = prob() < probUnidirectional\r\n                        ? (direction(*gen) == 0 ? FORWARD : BACKWARD)\r\n                        : BOTH;\r\n\r\n                    if (d & FORWARD)\r\n                    {\r\n                        edges = num_parallel_edges(*gen);\r\n                        for (int i = 0; i < edges; ++i)\r\n                            values.push(std::make_pair(*first, *second));\r\n                    }\r\n\r\n                    if (d & BACKWARD)\r\n                    {\r\n                        edges = num_parallel_edges(*gen);\r\n                        for (int i = 0; i < edges; ++i)\r\n                            values.push(std::make_pair(*second, *first));\r\n                    }\r\n                }\r\n\r\n            if (verticesRemaining == 0)\r\n            {\r\n                // Generate interclique edges\r\n                for (vertices_size_type i = 0; i < totVertices; ++i)\r\n                {\r\n                    double p = probIntercliqueEdges;\r\n                    for (vertices_size_type d = 2; d < totVertices / 2;\r\n                         d *= 2, p /= 2)\r\n                    {\r\n                        vertices_size_type j = (i + d) % totVertices;\r\n                        if (cliqueNum[j] != cliqueNum[i] && prob() < p)\r\n                        {\r\n                            int edges = num_parallel_edges(*gen);\r\n                            for (int i = 0; i < edges; ++i)\r\n                                values.push(std::make_pair(i, j));\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            currentClique++;\r\n        }\r\n\r\n        if (!values.empty())\r\n        { // If we're not done return a value\r\n            current = values.front();\r\n            values.pop();\r\n        }\r\n\r\n        return *this;\r\n    }\r\n\r\n    ssca_iterator operator++(int)\r\n    {\r\n        ssca_iterator temp(*this);\r\n        ++(*this);\r\n        return temp;\r\n    }\r\n\r\n    bool operator==(const ssca_iterator& other) const\r\n    {\r\n        return verticesRemaining == other.verticesRemaining && values.empty()\r\n            && other.values.empty();\r\n    }\r\n\r\n    bool operator!=(const ssca_iterator& other) const\r\n    {\r\n        return !(*this == other);\r\n    }\r\n\r\nprivate:\r\n    // Parameters\r\n    RandomGenerator* gen;\r\n    vertices_size_type totVertices;\r\n    vertices_size_type maxCliqueSize;\r\n    double probUnidirectional;\r\n    int maxParallelEdges;\r\n    double probIntercliqueEdges;\r\n\r\n    // Internal data structures\r\n    std::vector< int > cliqueNum;\r\n    std::queue< value_type > values;\r\n    int currentClique;\r\n    vertices_size_type verticesRemaining;\r\n    value_type current;\r\n};\r\n\r\n} // end namespace boost\r\n\r\n#endif // BOOST_GRAPH_SSCA_GENERATOR_HPP\r\n", "meta": {"hexsha": "be01be5b854ed9afaa060c8fc2765c44f5e923f6", "size": 6760, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/ssca_graph_generator.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/ssca_graph_generator.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/ssca_graph_generator.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.3147208122, "max_line_length": 81, "alphanum_fraction": 0.5526627219, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37387582277169656, "lm_q2_score": 0.025565215872134086, "lm_q1q2_score": 0.009558216118530168}}
{"text": "#include \"mtp.h\"\n#include \"util.h\"\n#include \"arith_uint256.h\"\n\nextern \"C\" {\n#include \"blake2/blake2.h\"\n#include \"blake2/blake2-impl.h\"\n#include \"blake2/blamka-round-ref.h\"\n#include \"core.h\"\n#include \"ref.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n}\n\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include \"merkle-tree.hpp\"\n#include \"primitives/block.h\"\n#include \"streams.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\nusing boost::numeric_cast;\nusing boost::numeric::bad_numeric_cast;\nusing boost::numeric::positive_overflow;\nusing boost::numeric::negative_overflow;\n\nextern int validate_inputs(const argon2_context *context);\nextern void clear_internal_memory(void *v, size_t n);\n\nnamespace mtp\n{\n\nnamespace {\n\nconst int8_t L = MTP_L;\nconst unsigned T_COST = 1;\nconst unsigned M_COST = 1024 * 1024 * 4;\nconst unsigned LANES = 4;\n\nvoid StoreBlock(void *output, const block *src)\n{\n    for (unsigned i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {\n        store64(static_cast<uint8_t*>(output)\n                + (i * sizeof(src->v[i])), src->v[i]);\n    }\n}\n\nint Argon2CtxMtp(argon2_context *context, argon2_type type,\n        argon2_instance_t *instance)\n{\n    int result = validate_inputs(context);\n    if (result != ARGON2_OK) {\n        return result;\n    }\n    if ((type != Argon2_d) && (type != Argon2_i) && (type != Argon2_id)) {\n        return ARGON2_INCORRECT_TYPE;\n    }\n    result = initialize(instance, context);\n    if (result != ARGON2_OK) {\n        return result;\n    }\n    result = fill_memory_blocks_mtp(instance, context);\n    if (result != ARGON2_OK) {\n        return result;\n    }\n    return ARGON2_OK;\n}\n\nuint32_t IndexBeta(const argon2_instance_t *instance,\n        const argon2_position_t *position, uint32_t pseudo_rand,\n        int same_lane)\n{\n    /*\n     * Pass 0:\n     *      This lane : all already finished segments plus already constructed\n     * blocks in this segment\n     *      Other lanes : all already finished segments\n     * Pass 1+:\n     *      This lane : (SYNC_POINTS - 1) last segments plus already constructed\n     * blocks in this segment\n     *      Other lanes : (SYNC_POINTS - 1) last segments\n     */\n    uint32_t reference_area_size;\n    if (position->pass == 0) {\n        /* First pass */\n        if (position->slice == 0) {\n            /* First slice */\n            reference_area_size = position->index - 1; // all but the previous\n        } else {\n            if (same_lane) {\n                /* The same lane => add current segment */\n                reference_area_size =\n                    (position->slice * instance->segment_length)\n                    + position->index - 1;\n            } else {\n                reference_area_size =\n                    (position->slice * instance->segment_length)\n                    + ((position->index == 0) ? -1 : 0);\n            }\n        }\n    } else {\n        /* Second pass */\n        if (same_lane) {\n            reference_area_size = instance->lane_length\n                - instance->segment_length + position->index - 1;\n        } else {\n            reference_area_size = instance->lane_length\n                - instance->segment_length + ((position->index == 0) ? -1 : 0);\n        }\n    }\n\n    /* 1.2.4. Mapping pseudo_rand to 0..<reference_area_size-1> and produce\n     * relative position */\n    uint64_t relative_position = pseudo_rand;\n    relative_position = (relative_position * relative_position) >> 32;\n    relative_position = reference_area_size - 1\n        - ((reference_area_size * relative_position) >> 32);\n\n    /* 1.2.5 Computing starting position */\n    uint32_t start_position = 0;\n    if (position->pass != 0) {\n        start_position = (position->slice == (ARGON2_SYNC_POINTS - 1))\n            ? 0\n            : (position->slice + 1) * instance->segment_length;\n    }\n\n    /* 1.2.6. Computing absolute position */\n    uint64_t absolute_position = (static_cast<uint64_t>(start_position)\n            + relative_position) % static_cast<uint64_t>(instance->lane_length);\n    return static_cast<uint32_t>(absolute_position);\n}\n\nvoid GetBlockIndex(uint32_t ij, argon2_instance_t *instance,\n        uint32_t *out_ij_prev, uint32_t *out_computed_ref_block)\n{\n    uint32_t ij_prev = 0;\n    if ((ij % instance->lane_length) == 0) {\n        ij_prev = ij + instance->lane_length - 1;\n    } else {\n        ij_prev = ij - 1;\n    }\n    if ((ij % instance->lane_length) == 1) {\n        ij_prev = ij - 1;\n    }\n\n    uint64_t prev_block_opening = instance->memory[ij_prev].v[0];\n    uint32_t ref_lane = static_cast<uint32_t>((prev_block_opening >> 32)\n            % static_cast<uint64_t>(instance->lanes));\n    uint32_t pseudo_rand = static_cast<uint32_t>(prev_block_opening & 0xFFFFFFFF);\n    uint32_t lane = ij / instance->lane_length;\n    uint32_t slice = (ij - (lane * instance->lane_length))\n        / instance->segment_length;\n    uint32_t pos_index = ij - (lane * instance->lane_length)\n        - (slice * instance->segment_length);\n    if (slice == 0) {\n        ref_lane = lane;\n    }\n\n    argon2_position_t position { 0, lane , (uint8_t)slice, pos_index };\n    uint32_t ref_index = IndexBeta(instance, &position, pseudo_rand,\n            ref_lane == position.lane);\n    uint32_t computed_ref_block = (instance->lane_length * ref_lane) + ref_index;\n    *out_ij_prev = ij_prev;\n    *out_computed_ref_block = computed_ref_block;\n}\n\n/** Compute a BLAKE2B hash on a block\n *\n * \\param input  [in]  Block to compute the hash on\n * \\param digest [out] Computed hash\n */\nvoid compute_blake2b(const block& input,\n        uint8_t digest[MERKLE_TREE_ELEMENT_SIZE_B])\n{\n    block tmp_block;\n    copy_block(&tmp_block, &input);\n    uint8_t tmp_block_bytes[ARGON2_BLOCK_SIZE];\n    StoreBlock(&tmp_block_bytes, &tmp_block);\n\n    blake2b_state state;\n    blake2b_init(&state, MERKLE_TREE_ELEMENT_SIZE_B);\n    blake2b_4r_update(&state, tmp_block_bytes, ARGON2_BLOCK_SIZE);\n\n    blake2b_4r_final(&state, digest, MERKLE_TREE_ELEMENT_SIZE_B);\n    clear_internal_memory(tmp_block.v, ARGON2_BLOCK_SIZE);\n    clear_internal_memory(tmp_block_bytes, ARGON2_BLOCK_SIZE);\n}\n\nstruct TargetHelper\n{\n    bool m_negative;\n    bool m_overflow;\n    arith_uint256 m_target;\n\n    TargetHelper(uint32_t target)\n    {\n       m_target.SetCompact(target, &m_negative, &m_overflow);\n    }\n};\n\n} // unnamed namespace\n\nnamespace impl\n{\n\nbool mtp_verify(const char* input, const uint32_t target,\n        const uint8_t hash_root_mtp[16], uint32_t nonce,\n        const uint64_t block_mtp[MTP_L*2][128],\n        const std::deque<std::vector<uint8_t>> proof_mtp[MTP_L*3],\n        uint256 pow_limit,\n        uint256 *mtpHashValue)\n{\n    MerkleTree::Elements proof_blocks[L * 3];\n    MerkleTree::Buffer root;\n    block blocks[L * 2];\n    root.insert(root.begin(), &hash_root_mtp[0], &hash_root_mtp[16]);\n    for (int i = 0; i < (L * 3); ++i) {\n        proof_blocks[i] = proof_mtp[i];\n    }\n    for(int i = 0; i < (L * 2); ++i) {\n        std::memcpy(blocks[i].v, block_mtp[i],\n                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);\n    }\n\n#define TEST_OUTLEN 32\n#define TEST_PWDLEN 80\n#define TEST_SALTLEN 80\n#define TEST_SECRETLEN 0\n#define TEST_ADLEN 0\n\n    unsigned char out[TEST_OUTLEN];\n    unsigned char pwd[TEST_PWDLEN];\n    std::memcpy(pwd, input, TEST_PWDLEN);\n    unsigned char salt[TEST_SALTLEN];\n    std::memcpy(salt, input, TEST_SALTLEN);\n\n    argon2_context context_verify;\n    context_verify.out = out;\n    context_verify.outlen = TEST_OUTLEN;\n    context_verify.version = ARGON2_VERSION_NUMBER;\n    context_verify.pwd = pwd;\n    context_verify.pwdlen = TEST_PWDLEN;\n    context_verify.salt = salt;\n    context_verify.saltlen = TEST_SALTLEN;\n    context_verify.secret = NULL;\n    context_verify.secretlen = TEST_SECRETLEN;\n    context_verify.ad = NULL;\n    context_verify.adlen = TEST_ADLEN;\n    context_verify.t_cost = T_COST;\n    context_verify.m_cost = M_COST;\n    context_verify.lanes = LANES;\n    context_verify.threads = LANES;\n    context_verify.allocate_cbk = NULL;\n    context_verify.free_cbk = NULL;\n    context_verify.flags = ARGON2_DEFAULT_FLAGS;\n\n#undef TEST_OUTLEN\n#undef TEST_PWDLEN\n#undef TEST_SALTLEN\n#undef TEST_SECRETLEN\n#undef TEST_ADLEN\n\n    uint32_t memory_blocks = context_verify.m_cost;\n    if (memory_blocks < (2 * ARGON2_SYNC_POINTS * context_verify.lanes)) {\n        memory_blocks = 2 * ARGON2_SYNC_POINTS * context_verify.lanes;\n    }\n    uint32_t segment_length = memory_blocks / (context_verify.lanes * ARGON2_SYNC_POINTS);\n    memory_blocks = segment_length * (context_verify.lanes * ARGON2_SYNC_POINTS);\n\n    argon2_instance_t instance;\n    instance.version = context_verify.version;\n    instance.memory = NULL;\n    instance.passes = context_verify.t_cost;\n    instance.memory_blocks = context_verify.m_cost;\n    instance.segment_length = segment_length;\n    instance.lane_length = segment_length * ARGON2_SYNC_POINTS;\n    instance.lanes = context_verify.lanes;\n    instance.threads = context_verify.threads;\n    instance.type = Argon2_d;\n    if (instance.threads > instance.lanes) {\n        instance.threads = instance.lanes;\n    }\n\n    // step 7\n    uint256 y[L + 1];\n    std::memset(&y[0], 0, sizeof(y));\n\n    blake2b_state state_y0;\n    blake2b_init(&state_y0, 32); // 256 bit\n    blake2b_update(&state_y0, input, 80);\n    blake2b_update(&state_y0, hash_root_mtp, MERKLE_TREE_ELEMENT_SIZE_B);\n    blake2b_update(&state_y0, &nonce, sizeof(unsigned int));\n    blake2b_final(&state_y0, &y[0], sizeof(uint256));\n\n    // get hash_zero\n    uint8_t h0[ARGON2_PREHASH_SEED_LENGTH];\n    initial_hash(h0, &context_verify, instance.type);\n    \n    // step 8\n    for (uint32_t j = 1; j <= L; ++j) {\n        // compute ij\n        std::string s = \"0x\" + y[j - 1].GetHex();\n        boost::multiprecision::uint256_t t(s);\n        uint32_t ij = numeric_cast<uint32_t>(t % M_COST);\n\n        // retrieve x[ij-1] and x[phi(i)] from proof\n        block prev_block, ref_block, t_prev_block, t_ref_block;\n        std::memcpy(t_prev_block.v, block_mtp[(j * 2) - 2],\n                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);\n        std::memcpy(t_ref_block.v, block_mtp[j*2 - 1],\n                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);\n        copy_block(&prev_block , &t_prev_block);\n        copy_block(&ref_block , &t_ref_block);\n        clear_internal_memory(t_prev_block.v, ARGON2_BLOCK_SIZE);\n        clear_internal_memory(t_ref_block.v, ARGON2_BLOCK_SIZE);\n\n        //prev_index\n        //compute\n        uint32_t memory_blocks_2 = M_COST;\n        if (memory_blocks_2 < (2 * ARGON2_SYNC_POINTS * LANES)) {\n            memory_blocks_2 = 2 * ARGON2_SYNC_POINTS * LANES;\n        }\n\n        uint32_t segment_length_2 = memory_blocks_2 / (LANES * ARGON2_SYNC_POINTS);\n        uint32_t lane_length = segment_length_2 * ARGON2_SYNC_POINTS;\n        uint32_t ij_prev = 0;\n        if ((ij % lane_length) == 0) {\n            ij_prev = ij + lane_length - 1;\n        } else {\n            ij_prev = ij - 1;\n        }\n        if ((ij % lane_length) == 1) {\n            ij_prev = ij - 1;\n        }\n\n        //hash[prev_index]\n        uint8_t digest_prev[MERKLE_TREE_ELEMENT_SIZE_B];\n        compute_blake2b(prev_block, digest_prev);\n        MerkleTree::Buffer hash_prev(digest_prev,\n                digest_prev + sizeof(digest_prev));\n        if (!MerkleTree::checkProofOrdered(proof_blocks[(j * 3) - 2],\n                    root, hash_prev, ij_prev + 1)) {\n            LogPrintf(\"error : checkProofOrdered in x[ij_prev]\\n\");\n            return false;\n        }\n\n        //compute ref_index\n        uint64_t prev_block_opening = prev_block.v[0];\n        uint32_t ref_lane = static_cast<uint32_t>((prev_block_opening >> 32) % LANES);\n        uint32_t pseudo_rand = static_cast<uint32_t>(prev_block_opening & 0xFFFFFFFF);\n        uint32_t lane = ij / lane_length;\n        uint32_t slice = (ij - (lane * lane_length)) / segment_length_2;\n        uint32_t pos_index = ij - (lane * lane_length)\n            - (slice * segment_length_2);\n        if (slice == 0) {\n            ref_lane = lane;\n        }\n\n        argon2_instance_t instance;\n        instance.segment_length = segment_length_2;\n        instance.lane_length = lane_length;\n\n        argon2_position_t position { 0, lane , (uint8_t)slice, pos_index };\n        uint32_t ref_index = IndexBeta(&instance, &position, pseudo_rand,\n                ref_lane == position.lane);\n\n        uint32_t computed_ref_block = (lane_length * ref_lane) + ref_index;\n\n        uint8_t digest_ref[MERKLE_TREE_ELEMENT_SIZE_B];\n        compute_blake2b(ref_block, digest_ref);\n        MerkleTree::Buffer hash_ref(digest_ref, digest_ref + sizeof(digest_ref));\n        if (!MerkleTree::checkProofOrdered(proof_blocks[(j * 3) - 1],\n                    root, hash_ref, computed_ref_block + 1)) {\n            LogPrintf(\"error : checkProofOrdered in x[ij_ref]\\n\");\n            return false;\n        }\n\n        // compute x[ij]\n        block block_ij;\n        fill_block_mtp(&blocks[(j * 2) - 2], &blocks[(j * 2) - 1],\n                &block_ij, 0, computed_ref_block, h0);\n\n        // verify opening\n        // hash x[ij]\n        uint8_t digest_ij[MERKLE_TREE_ELEMENT_SIZE_B];\n        compute_blake2b(block_ij, digest_ij);\n        MerkleTree::Buffer hash_ij(digest_ij, digest_ij + sizeof(digest_ij));\n\n        if (!MerkleTree::checkProofOrdered(proof_blocks[(j * 3) - 3], root,\n                    hash_ij, ij + 1)) {\n            LogPrintf(\"error : checkProofOrdered in x[ij]\\n\");\n            return false;\n        }\n\n        // compute y(j)\n        block blockhash;\n        copy_block(&blockhash, &block_ij);\n        uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];\n        StoreBlock(&blockhash_bytes, &blockhash);\n        blake2b_state ctx_yj;\n        blake2b_init(&ctx_yj, 32);\n        blake2b_update(&ctx_yj, &y[j - 1], 32);\n        blake2b_update(&ctx_yj, blockhash_bytes, ARGON2_BLOCK_SIZE);\n        blake2b_final(&ctx_yj, &y[j], 32);\n        clear_internal_memory(block_ij.v, ARGON2_BLOCK_SIZE);\n        clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE);\n        clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);\n    }    \n\n    // step 9\n    bool negative;\n    bool overflow;\n    arith_uint256 bn_target;\n    bn_target.SetCompact(target, &negative, &overflow); // diff = 1\n\n    for (int i = 0; i < (L * 2); ++i) {\n        clear_internal_memory(blocks[i].v, ARGON2_BLOCK_SIZE);\n    }\n\n    if (mtpHashValue)\n        *mtpHashValue = y[L];\n\n    if (negative || (bn_target == 0) || overflow\n            || (bn_target > UintToArith256(pow_limit))\n            || (UintToArith256(y[L]) > bn_target)) {\n        return false;\n    }\n    return true;\n}\n\nnamespace {\n\nbool mtp_hash1(const char* input, uint32_t target, uint8_t hash_root_mtp[16],\n        unsigned int& nonce, uint64_t block_mtp[MTP_L*2][128],\n        std::deque<std::vector<uint8_t>> proof_mtp[MTP_L*3], uint256 pow_limit,\n        uint256& output)\n{\n#define TEST_OUTLEN 32\n#define TEST_PWDLEN 80\n#define TEST_SALTLEN 80\n#define TEST_SECRETLEN 0\n#define TEST_ADLEN 0\n\n    unsigned char out[TEST_OUTLEN];\n    unsigned char pwd[TEST_PWDLEN];\n    std::memcpy(pwd, input, TEST_PWDLEN);\n    unsigned char salt[TEST_SALTLEN];\n    std::memcpy(salt, input, TEST_SALTLEN);\n\n    argon2_context context;\n    context.out = out;\n    context.outlen = TEST_OUTLEN;\n    context.version = ARGON2_VERSION_NUMBER;\n    context.pwd = pwd;\n    context.pwdlen = TEST_PWDLEN;\n    context.salt = salt;\n    context.saltlen = TEST_SALTLEN;\n    context.secret = NULL;\n    context.secretlen = TEST_SECRETLEN;\n    context.ad = NULL;\n    context.adlen = TEST_ADLEN;\n    context.t_cost = T_COST;\n    context.m_cost = M_COST;\n    context.lanes = LANES;\n    context.threads = LANES;\n    context.allocate_cbk = NULL;\n    context.free_cbk = NULL;\n    context.flags = ARGON2_DEFAULT_FLAGS;\n\n#undef TEST_OUTLEN\n#undef TEST_PWDLEN\n#undef TEST_SALTLEN\n#undef TEST_SECRETLEN\n#undef TEST_ADLEN\n\n    uint32_t memory_blocks = context.m_cost;\n    if (memory_blocks < (2 * ARGON2_SYNC_POINTS * context.lanes)) {\n        memory_blocks = 2 * ARGON2_SYNC_POINTS * context.lanes;\n    }\n    uint32_t segment_length = memory_blocks / (context.lanes * ARGON2_SYNC_POINTS);\n    memory_blocks = segment_length * (context.lanes * ARGON2_SYNC_POINTS);\n\n    argon2_instance_t instance;\n    instance.version = context.version;\n    instance.memory = NULL;\n    instance.passes = context.t_cost;\n    instance.memory_blocks = context.m_cost;\n    instance.segment_length = segment_length;\n    instance.lane_length = segment_length * ARGON2_SYNC_POINTS;\n    instance.lanes = context.lanes;\n    instance.threads = context.threads;\n    instance.type = Argon2_d;\n    if (instance.threads > instance.lanes) {\n        instance.threads = instance.lanes;\n    }\n\n    // step 1\n    Argon2CtxMtp(&context, Argon2_d, &instance);\n\n    // step 2\n    MerkleTree::Elements elements;\n    for (long int i = 0; i < instance.memory_blocks; ++i) {\n        uint8_t digest[MERKLE_TREE_ELEMENT_SIZE_B];\n        compute_blake2b(instance.memory[i], digest);\n        elements.emplace_back(digest, digest + sizeof(digest));\n    }\n\n    MerkleTree ordered_tree(elements, true);\n    MerkleTree::Buffer root = ordered_tree.getRoot();\n    std::copy(root.begin(), root.end(), hash_root_mtp);\n\n    // step 3\n    unsigned int n_nonce_internal = 0;\n    TargetHelper const bn_target(target);\n\n    // step 4\n    uint256 y[L + 1];\n    block blocks[L * 2];\n    MerkleTree::Elements proof_blocks[L * 3];\n    while (true) {\n        if (n_nonce_internal == UINT_MAX) {\n            // go to create a new merkle tree\n            return false;\n        }\n\n        std::memset(&y[0], 0, sizeof(y));\n        std::memset(&blocks[0], 0, sizeof(sizeof(block) * L * 2));\n\n        blake2b_state state;\n        blake2b_init(&state, 32); // 256 bit\n        blake2b_update(&state, input, 80);\n        blake2b_update(&state, hash_root_mtp, MERKLE_TREE_ELEMENT_SIZE_B);\n        blake2b_update(&state, &n_nonce_internal, sizeof(unsigned int));\n        blake2b_final(&state, &y[0], sizeof(uint256));\n\n        // step 5\n        bool init_blocks = false;\n        for (uint32_t j = 1; j <= L; ++j) {\n            std::string s = \"0x\" + y[j - 1].GetHex();\n            boost::multiprecision::uint256_t t(s);\n            uint32_t ij = numeric_cast<uint32_t>(t % M_COST);\n            uint32_t except_index = numeric_cast<uint32_t>(M_COST / LANES);\n            if (((ij % except_index) == 0) || ((ij % except_index) == 1)) {\n                init_blocks = true;\n                break;\n            }\n\n            block blockhash;\n            copy_block(&blockhash, &instance.memory[ij]);\n            uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];\n            StoreBlock(&blockhash_bytes, &blockhash);\n            blake2b_state ctx_yj;\n            blake2b_init(&ctx_yj, 32);\n            blake2b_update(&ctx_yj, &y[j - 1], 32);\n            blake2b_update(&ctx_yj, blockhash_bytes, ARGON2_BLOCK_SIZE);\n            blake2b_final(&ctx_yj, &y[j], 32);\n            clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE);\n            clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);\n\n            //storing blocks\n            uint32_t prev_index;\n            uint32_t ref_index;\n            GetBlockIndex(ij, &instance, &prev_index, &ref_index);\n            //previous block\n            copy_block(&blocks[(j * 2) - 2], &instance.memory[prev_index]);\n            //ref block\n            copy_block(&blocks[(j * 2) - 1], &instance.memory[ref_index]);\n\n            //storing proof\n            //TODO : make it as function please\n            //current proof\n            uint8_t digest_curr[MERKLE_TREE_ELEMENT_SIZE_B];\n            compute_blake2b(instance.memory[ij], digest_curr);\n            MerkleTree::Buffer hash_curr(digest_curr,\n                    digest_curr + sizeof(digest_curr));\n            MerkleTree::Elements proof_curr = ordered_tree.getProofOrdered(\n                    hash_curr, ij + 1);\n            proof_blocks[(j * 3) - 3] = proof_curr;\n\n            //prev proof\n            uint8_t digest_prev[MERKLE_TREE_ELEMENT_SIZE_B];\n            compute_blake2b(instance.memory[prev_index], digest_prev);\n            MerkleTree::Buffer hash_prev(digest_prev,\n                    digest_prev + sizeof(digest_prev));\n            MerkleTree::Elements proof_prev = ordered_tree.getProofOrdered(\n                    hash_prev, prev_index + 1);\n            proof_blocks[(j * 3) - 2] = proof_prev;\n\n            //ref proof\n            uint8_t digest_ref[MERKLE_TREE_ELEMENT_SIZE_B];\n            compute_blake2b(instance.memory[ref_index], digest_ref);\n            MerkleTree::Buffer hash_ref(digest_ref,\n                    digest_ref + sizeof(digest_ref));\n            MerkleTree::Elements proof_ref = ordered_tree.getProofOrdered(\n                    hash_ref, ref_index + 1);\n            proof_blocks[(j * 3) - 1] = proof_ref;\n        }\n\n        if (init_blocks) {\n            n_nonce_internal++;\n            continue;\n        }\n\n        // step 6\n        if (bn_target.m_negative || (bn_target.m_target == 0) || bn_target.m_overflow\n                || (bn_target.m_target > UintToArith256(pow_limit))\n                || (UintToArith256(y[L]) > bn_target.m_target)) {\n            n_nonce_internal++;\n            continue;\n        }\n\n        break;\n    }\n\n    // step 7\n    std::copy(root.begin(), root.end(), hash_root_mtp);\n\n    nonce = n_nonce_internal;\n    for (int i = 0; i < L * 2; ++i) {\n        std::memcpy(block_mtp[i], &blocks[i],\n                sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);\n    }\n    for (int i = 0; i < L * 3; ++i) {\n        proof_mtp[i] = proof_blocks[i];\n    }\n    std::memcpy(&output, &y[L], sizeof(uint256));\n\n    uint8_t h0[ARGON2_PREHASH_SEED_LENGTH];\n    std::memcpy(h0, instance.hash_zero,\n            sizeof(uint8_t) * ARGON2_PREHASH_SEED_LENGTH);\n\n    // get hash_zero\n    uint8_t h0_computed[ARGON2_PREHASH_SEED_LENGTH];\n    initial_hash(h0_computed, &context, instance.type);\n    \n    free_memory(&context, (uint8_t *)instance.memory, instance.memory_blocks, sizeof(block));\n    return true;\n}\n\n} // unnamed namespace\n\nvoid mtp_hash(const char* input, uint32_t target, uint8_t hash_root_mtp[16],\n        unsigned int& nonce, uint64_t block_mtp[MTP_L*2][128],\n        std::deque<std::vector<uint8_t>> proof_mtp[MTP_L*3], uint256 pow_limit,\n        uint256& output)\n{\n    bool done = false;\n    while (!done) {\n        done = mtp_hash1(input, target, hash_root_mtp, nonce, block_mtp,\n                proof_mtp, pow_limit, output);\n    }\n}\n\n}\n\nnamespace \n{\nvoid serializeMtpHeader(CDataStream & stream, CBlockHeader const & header)\n{\n    static_assert(\n                80 == sizeof(header.nVersion) + sizeof(header.hashPrevBlock)+ sizeof(header.hashMerkleRoot) \n                    + sizeof(header.nTime) + sizeof(header.nBits) + sizeof(header.nVersionMTP)\n                , \"The header data size for MTP hashing should be 80 bytes long.\"\n            );\n\n    stream << header.nVersion;\n    stream << header.hashPrevBlock;\n    stream << header.hashMerkleRoot;\n    stream << header.nTime;\n    stream << header.nBits;\n    stream << header.nVersionMTP;\n}\n}\n\nuint256 hash(CBlockHeader & blockHeader, uint256 const & powLimit)\n{\n    if(!blockHeader.mtpHashData)\n        blockHeader.mtpHashData = std::make_shared<CMTPHashData>();\n\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    serializeMtpHeader(ss, blockHeader);\n    \n    uint256 result;\n    impl::mtp_hash(reinterpret_cast<char*>(&ss[0]), blockHeader.nBits, blockHeader.mtpHashData->hashRootMTP\n            , blockHeader.nNonce, blockHeader.mtpHashData->nBlockMTP, blockHeader.mtpHashData->nProofMTP, powLimit, result);\n    \n    return result;\n}\n\n\nbool verify(uint32_t nonce, CBlockHeader const & blockHeader, uint256 const & powLimit, uint256 *mtpHashValue)\n{\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    serializeMtpHeader(ss, blockHeader);\n\n    return impl::mtp_verify(reinterpret_cast<char*>(&ss[0]), blockHeader.nBits, blockHeader.mtpHashData->hashRootMTP\n            , nonce, blockHeader.mtpHashData->nBlockMTP, blockHeader.mtpHashData->nProofMTP, powLimit, mtpHashValue);\n}\n\n}", "meta": {"hexsha": "81bca8c4a078d090c46027e3ab74529c68980988", "size": 24103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypto/MerkleTreeProof/mtp.cpp", "max_stars_repo_name": "myphore/zcoin", "max_stars_repo_head_hexsha": "bf90be86c68f834de12ea719151278d9620df884", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T01:45:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-08T01:45:19.000Z", "max_issues_repo_path": "src/crypto/MerkleTreeProof/mtp.cpp", "max_issues_repo_name": "myphore/zcoin", "max_issues_repo_head_hexsha": "bf90be86c68f834de12ea719151278d9620df884", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crypto/MerkleTreeProof/mtp.cpp", "max_forks_repo_name": "myphore/zcoin", "max_forks_repo_head_hexsha": "bf90be86c68f834de12ea719151278d9620df884", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-21T09:23:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T09:23:20.000Z", "avg_line_length": 34.2859174964, "max_line_length": 124, "alphanum_fraction": 0.638094843, "num_tokens": 6422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462564, "lm_q2_score": 0.021615331777862058, "lm_q1q2_score": 0.00954690855476643}}
{"text": "/*\n * Copyright 2020 Yamana Laboratory, Waseda University\n * Supported by JST CREST Grant Number JPMJCR1503, Japan.\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 <sys/syscall.h> // for thread id\n#include <sys/types.h>   // for thread id\n#include <unistd.h>\n#include <algorithm> // for sort\n#include <chrono>\n#include <fstream>\n#include <random>\n#include <map>\n#include <iomanip> // put_time\n#include <boost/algorithm/string.hpp>\n\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ.h>\n#include <NTL/lzz_pXFactoring.h>\n\n#include <stdsc/stdsc_log.hpp>\n\n#include <sses_share/sses_utility.hpp>\n#include <sses_share/sses_fhekey_container.hpp>\n#include <sses_share/sses_fhectxt_buffer.hpp>\n\n#include <sses_server/sses_server_calcthread.hpp>\n#include <sses_server/sses_server_query.hpp>\n#include <sses_server/sses_server_result.hpp>\n#include <sses_server/sses_server_db.hpp>\n\n//#define ENABLE_LOCAL_DEBUG\n#ifdef ENABLE_LOCAL_DEBUG\n#include <sses_share/sses_fhe_debug.hpp>\n#endif\n\n\n#define __MULTITHREADING_IN_USE__\n\n\nnamespace sses_server\n{\n\n#define LOGINFO(fmt, ...) \\\n    STDSC_LOG_INFO(\"[CalThr:%d, Query:%d] \" fmt, th_id, query_id, ##__VA_ARGS__)\n\n    \nstatic std::vector<int> mergeOR(const std::map<int, std::vector<int>>& index,\n                                const std::vector<int>& id)\n{\n    int len = id.size();\n\n    if (len == 0)\n    {\n        std::vector<int> ret;\n        return ret;\n    }\n\n    if (len == 1)\n    {\n        if (index.find(id[0]) == index.end())\n        {\n            std::vector<int> ret;\n            return ret;\n        }\n        return index.at(id[0]);\n    }\n\n    const std::vector<int> id_l = std::vector<int>(id.begin(), id.begin() + len / 2);\n    const std::vector<int> id_r = std::vector<int>(id.begin() + len / 2, id.end());\n\n    const std::vector<int> res_l = mergeOR(index, id_l);\n    const std::vector<int> res_r = mergeOR(index, id_r);\n\n    int len_l = res_l.size(), p_l = 0;\n    int len_r = res_r.size(), p_r = 0;\n\n    std::vector<int> ret;\n    while (p_l != len_l && p_r != len_r)\n    {\n        if (res_l[p_l] < res_r[p_r]) {\n            ret.push_back(res_l[p_l++]);\n        } else {\n            if (res_l[p_l] == res_r[p_r]) {\n                ++p_l;\n            }\n            ret.push_back(res_r[p_r++]);\n        }\n    }\n    while (p_l != len_l) {\n        ret.push_back(res_l[p_l++]);\n    }\n    while (p_r != len_r) {\n        ret.push_back(res_r[p_r++]);\n    }\n\n    return ret;\n}\n\nstatic std::vector<int> merge(const std::vector<int>& medID,\n                              const std::vector<int>& sideID,\n                              std::map<int, std::vector<int>>& medIndex,\n                              std::map<int, std::vector<int>>& sideIndex)\n{\n    // First use OR to merge between medIndex[medID] -> res1\n    const std::vector<int> medres = mergeOR(medIndex, medID);\n\n    // Then use OR to merge between sideIndex[sideID] -> res2\n    const std::vector<int> sideres = mergeOR(sideIndex, sideID);\n\n    // Then use AND to merge res1 and res2 -> ret\n\n    std::vector<int> ret;\n\n    int lenmed = medres.size(), pmed = 0;\n    int lenside = sideres.size(), pside = 0;\n\n    while (pmed != lenmed && pside != lenside)\n    {\n        if (medres[pmed] < sideres[pside]) {\n            ++pmed;\n        } else if (medres[pmed] > sideres[pside]) {\n            ++pside;\n        } else {\n            ret.push_back(medres[pmed++]);\n            ++pside;\n        }\n    }\n\n    return ret;\n}\n    \nstruct CalcThread::Impl\n{\n    Impl(QueryQueue& in_queue, ResultQueue& out_queue, const uint32_t num_threads)\n        : in_queue_(in_queue), out_queue_(out_queue)\n    {\n        param_.num_threads = num_threads;\n    }\n\n    void exec(CalcThreadParam& args, std::shared_ptr<stdsc::ThreadException> te)\n    {\n        auto th_id = syscall(SYS_gettid);\n        STDSC_LOG_INFO(\"[CalThr:%d] Launched CalThread.\", th_id);\n\n        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n        std::mt19937 generator(seed);\n\n        auto num_threads = args.num_threads;\n        \n        while (!args.force_finish)\n        {\n            STDSC_LOG_INFO(\"[CalThr:%d] Waiting for a query to be inserted into Queue.\", th_id);\n\n            int32_t query_id;\n            Query query;\n            while (!in_queue_.pop(query_id, query))\n            {\n                usleep(args.retry_interval_msec * 1000);\n            }\n\n            LOGINFO(\"Pop a query from Queue. [age: %lu, gender: %s, meds: %s, sides: %s]\",\n                    query.param_.age,\n                    query.param_.gender,\n                    query.param_.meds,\n                    query.param_.sides);\n\n            LOGINFO(\"Start processing for query %d.\", query_id);\n\n            const auto key_id = query.key_id_;\n            const auto& comp_param = query.param_;\n            const auto& key_container = *query.key_container_p_;\n            const auto& db = *query.db_p_;\n\n            auto dbbasicfilepath = db.dbbasic_filepath(key_id);\n            DBBasicFile dbbasic(dbbasicfilepath);\n            LOGINFO(\"Load DBBasic. [status:%d, totalRecords:%lu, totalMedicines:%lu, totalSymptoms:%lu]\",\n                    dbbasic.dbstatus,\n                    dbbasic.totalRecordsNum,\n                    dbbasic.totalMedicinesNum,\n                    dbbasic.totalSymptomsNum);\n            \n            auto context = key_container.get_context(key_id);\n            NTL::ZZX G = context.alMod.getFactorsOverZZ()[0];\n            EncryptedArray ea(context, G);\n            long nslots = ea.size();\n            \n            FHEPubKey pubkey(context);\n            key_container.get(key_id, sses_share::KeyKind_t::kKindPubKey, pubkey);\n\n            std::map<int, std::vector<int>> medIndex;\n            std::map<int, std::vector<int>> sideIndex;\n\n            std::ifstream findexmed(db.medinv_filepath(key_id), std::ios::binary);\n            std::string line;\n            std::vector<std::string> medInfo;\n            int numMed;\n            findexmed >> numMed;\n            for (int i = 0; i < numMed; ++i)\n            {\n                findexmed >> line;\n                boost::algorithm::split(medInfo, line, boost::is_any_of(\":\"));\n                int medId = std::stoi(medInfo[0]);\n                int numindex = std::stoi(medInfo[1]);\n                std::vector<int> tempindex;\n                while (numindex > 0)\n                {\n                    int temprec;\n                    findexmed >> temprec;\n                    tempindex.push_back(temprec);\n                    numindex--;\n                }\n                medIndex.insert(make_pair(medId, tempindex));\n            }\n            findexmed.close();\n\n            std::ifstream findexside(db.sideinv_filepath(key_id), std::ios::binary);\n            std::vector<std::string> sideInfo;\n            int numSide;\n            findexside >> numSide;\n            for (int i = 0; i < numSide; ++i)\n            {\n                findexside >> line;\n                boost::algorithm::split(sideInfo, line, boost::is_any_of(\":\"));\n                int sideId = std::stoi(sideInfo[0]);\n                int numindex = std::stoi(sideInfo[1]);\n                std::vector<int> tempindex;\n                while (numindex > 0)\n                {\n                    int temprec;\n                    findexside >> temprec;\n                    tempindex.push_back(temprec);\n                    numindex--;\n                }\n                sideIndex.insert(make_pair(sideId, tempindex));\n            }\n            findexside.close();\n\n            const std::vector<long> allzero_long(nslots, 0);\n            Ctxt allzero(pubkey);\n            ea.encrypt(allzero, pubkey, allzero_long);\n\n            NTL::SetNumThreads(num_threads);\n\n            std::vector<Ctxt> ctxts;\n            query.encmask_.deserialize(pubkey, ctxts);\n            Ctxt& query_mask = ctxts[0];\n\n            std::vector<int> MedID, SideID;\n            comp_param.get_med_ids(MedID);\n            comp_param.get_side_ids(SideID);\n\n            std::vector<int> filteredres = merge(MedID, SideID, medIndex, sideIndex);\n\n            int numRes = filteredres.size(), numchunks = 0;\n\n            LOGINFO(\"Completed filtering.\");\n            \n            std::vector<std::vector<int>> chunks;\n            std::vector<Ctxt> chunk_res;\n            for (int i = 0; i < numRes; i += 100, ++numchunks)\n            {\n                int end = std::min(i + 100, numRes);\n                std::vector<int> chunk(filteredres.begin() + i,\n                                  filteredres.begin() + end);\n                chunks.push_back(chunk);\n                chunk_res.push_back(allzero);\n            }\n\n            LOGINFO(\"Completed chunk splitting.\");\n\n#ifndef __MULTITHREADING_IN_USE__\n            long first = 0, last = numchunks;\n#else\n            NTL_EXEC_RANGE(numchunks, first, last);\n#endif            \n\n            for (long i = first; i < last; ++i)\n            {\n\n                for (size_t j = 0; j < chunks[i].size(); ++j)\n                {\n                    std::vector<long> posindicator_long = allzero_long;\n                    posindicator_long[j] = 1;\n                    NTL::ZZX posindicator;\n                    ea.encode(posindicator, posindicator_long);\n\n                    std::string filename =\n                        db.encdata_dirpath(key_id) + \"/\" + std::to_string(chunks[i][j]) + \".bin\";\n                    std::ifstream fdb(filename.c_str(), std::ios::binary);\n                    Ctxt encmask(pubkey);\n                    //assert(fdb >> encmask);\n                    fdb >> encmask;\n                    fdb.close();\n                    \n                    encmask.multByConstant(posindicator);\n                    chunk_res[i].addCtxt(encmask, false);\n                }\n\n                chunk_res[i].addCtxt(query_mask, true);\n\n                std::vector<Ctxt> rangemul;\n                for (int diff = -5; diff <= 5; ++diff)\n                {\n                    Ctxt diffed(pubkey);\n                    diffed = chunk_res[i];\n                    diffed.addConstant(NTL::to_ZZX(diff));\n                    rangemul.push_back(diffed);\n                }\n\n                while (rangemul.size() > 1)\n                {\n                    std::vector<Ctxt> rangemul_derived;\n                    for (size_t j = 0; j < rangemul.size(); j += 2)\n                    {\n                        if (j + 1 < rangemul.size()) {\n                            rangemul[j].multiplyBy(rangemul[j + 1]);\n                        }\n                        rangemul_derived.push_back(rangemul[j]);\n                    }\n                    rangemul = rangemul_derived;\n                }\n\n                chunk_res[i] = rangemul[0];\n\n                std::vector<long> randlist_long;\n                for (int i = 0; i < nslots; ++i) {\n                    randlist_long.push_back(generator() % 256 + 1);\n                }\n                NTL::ZZX randlist;\n                ea.encode(randlist, randlist_long);\n                chunk_res[i].multByConstant(randlist);\n                \n            }\n            \n#ifdef __MULTITHREADING_IN_USE__            \n            NTL_EXEC_RANGE_END;\n#endif\n\n            LOGINFO(\"Complete calculation.\");\n\n            sses_share::FHECtxtBuffer chunk_res_ctxtbuff;\n            chunk_res_ctxtbuff.serialize(pubkey, chunk_res);\n            \n            Result result(key_id, query_id, true, chunk_res_ctxtbuff, chunks);\n            out_queue_.push(query_id, result);\n            \n            LOGINFO(\"Push results of each chunk to Queue.\");\n            \n            LOGINFO(\"Finish processing for query %d.\", query_id);\n        }\n    }\n\n    QueryQueue& in_queue_;\n    ResultQueue& out_queue_;\n    CalcThreadParam param_;\n    std::shared_ptr<stdsc::ThreadException> te_;\n};\n\nCalcThread::CalcThread(QueryQueue& in_queue,\n                       ResultQueue& out_queue,\n                       const uint32_t num_threads)\n    : pimpl_(new Impl(in_queue, out_queue, num_threads))\n{\n}\n\nvoid CalcThread::start()\n{\n    pimpl_->param_.force_finish = false;\n    super::start(pimpl_->param_, pimpl_->te_);\n}\n\nvoid CalcThread::stop()\n{\n    STDSC_LOG_INFO(\"Stop calculation thread.\");\n    pimpl_->param_.force_finish = true;\n}\n\nvoid CalcThread::exec(CalcThreadParam& args,\n                      std::shared_ptr<stdsc::ThreadException> te) const\n{\n    pimpl_->exec(args, te);\n}\n\n} /* namespace sses_server */\n", "meta": {"hexsha": "7aac6dd99b4b450c00ff0516ae2e54d4661b43b0", "size": 12846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sses/sses_server/sses_server_calcthread.cpp", "max_stars_repo_name": "yamanalab/SecureSideEffectSearch", "max_stars_repo_head_hexsha": "e223ad0f8cc5b5097af5a6da841f128e4783bd26", "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": "sses/sses_server/sses_server_calcthread.cpp", "max_issues_repo_name": "yamanalab/SecureSideEffectSearch", "max_issues_repo_head_hexsha": "e223ad0f8cc5b5097af5a6da841f128e4783bd26", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-11-02T11:56:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T10:06:39.000Z", "max_forks_repo_path": "sses/sses_server/sses_server_calcthread.cpp", "max_forks_repo_name": "yamanalab/SecureSideEffectSearch", "max_forks_repo_head_hexsha": "e223ad0f8cc5b5097af5a6da841f128e4783bd26", "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.2763819095, "max_line_length": 105, "alphanum_fraction": 0.5346411334, "num_tokens": 3030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.021948252395378596, "lm_q1q2_score": 0.009525134724432078}}
{"text": "/********************************************************************************\nCopyright (c) 2015, TRACLabs, Inc.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n       this list of conditions and the following disclaimer in the documentation\n       and/or other materials provided with the distribution.\n\n    3. Neither the name of the copyright holder nor the names of its contributors\n       may be used to endorse or promote products derived from this software\n       without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n********************************************************************************/\n\n\n#include <trac_ik/trac_ik.hpp>\n#include <boost/date_time.hpp>\n#include <boost/make_shared.hpp>\n#include <Eigen/Geometry>\n#include <ros/ros.h>\n#include <limits>\n#include <kdl_parser/kdl_parser.hpp>\n#include <urdf/model.h>\n\nnamespace TRAC_IK {\n\n  TRAC_IK::TRAC_IK(const std::string& base_link, const std::string& tip_link, const std::string& URDF_param, double _maxtime, double _eps, SolveType _type ) :\n    initialized(false),\n    eps(_eps),\n    maxtime(_maxtime),\n    solvetype(_type),\n    work(io_service)\n  {\n\n    ros::NodeHandle node_handle(\"~\");\n\n    urdf::Model robot_model;\n    std::string xml_string;\n\n    std::string urdf_xml,full_urdf_xml;\n    node_handle.param(\"urdf_xml\",urdf_xml,URDF_param);\n    node_handle.searchParam(urdf_xml,full_urdf_xml);\n    \n    ROS_DEBUG_NAMED(\"trac_ik\",\"Reading xml file from parameter server\");\n    if (!node_handle.getParam(full_urdf_xml, xml_string))\n      {\n        ROS_FATAL_NAMED(\"trac_ik\",\"Could not load the xml from parameter server: %s\", urdf_xml.c_str());\n        return;\n      }\n    \n    node_handle.param(full_urdf_xml,xml_string,std::string());\n    robot_model.initString(xml_string);\n    \n    ROS_DEBUG_STREAM_NAMED(\"trac_ik\",\"Reading joints and links from URDF\");\n\n    KDL::Tree tree;\n    \n    if (!kdl_parser::treeFromUrdfModel(robot_model, tree))\n      ROS_FATAL(\"Failed to extract kdl tree from xml robot description\");\n\n    if(!tree.getChain(base_link, tip_link, chain))\n      ROS_FATAL(\"Couldn't find chain %s to %s\",base_link.c_str(),tip_link.c_str());\n\n    std::vector<KDL::Segment> chain_segs = chain.segments;\n\n    boost::shared_ptr<const urdf::Joint> joint;\n\n    std::vector<double> l_bounds, u_bounds;\n\n    lb.resize(chain.getNrOfJoints());\n    ub.resize(chain.getNrOfJoints());\n\n    uint joint_num=0;\n    for(unsigned int i = 0; i < chain_segs.size(); ++i) {\n      joint = robot_model.getJoint(chain_segs[i].getJoint().getName());\n      if (joint->type != urdf::Joint::UNKNOWN && joint->type != urdf::Joint::FIXED) {\n        joint_num++;\n        float lower, upper;\n        int hasLimits;\n        if ( joint->type != urdf::Joint::CONTINUOUS ) {\n          if(joint->safety) {\n            lower = std::max(joint->limits->lower, joint->safety->soft_lower_limit);\n            upper = std::min(joint->limits->upper, joint->safety->soft_upper_limit);\n          } else {\n            lower = joint->limits->lower;\n            upper = joint->limits->upper;\n          }\n          hasLimits = 1;\n        }\n        else {\n          hasLimits = 0;\n        }\n        if(hasLimits) {\n          lb(joint_num-1)=lower;\n          ub(joint_num-1)=upper;\n        }\n        else {\n          lb(joint_num-1)=std::numeric_limits<float>::lowest();\n          ub(joint_num-1)=std::numeric_limits<float>::max();\n        }\n        ROS_INFO_STREAM(\"IK Using joint \"<<joint->name<<\" \"<<lb(joint_num-1)<<\" \"<<ub(joint_num-1));\n      }\n    }\n    \n    initialize();\n  }\n\n\n  TRAC_IK::TRAC_IK(const KDL::Chain& _chain, const KDL::JntArray& _q_min, const KDL::JntArray& _q_max, double _maxtime, double _eps, SolveType _type):\n    initialized(false),\n    chain(_chain),\n    lb(_q_min),\n    ub(_q_max),\n    eps(_eps),\n    maxtime(_maxtime),\n    solvetype(_type),\n    work(io_service)\n  {\n\n    initialize();\n  }\n\n  void TRAC_IK::initialize() {\n\n    assert(chain.getNrOfJoints()==lb.data.size());\n    assert(chain.getNrOfJoints()==ub.data.size());\n\n    jacsolver.reset(new KDL::ChainJntToJacSolver(chain));\n    nl_solver.reset(new NLOPT_IK::NLOPT_IK(chain,lb,ub,maxtime,eps,NLOPT_IK::SumSq));\n    iksolver.reset(new KDL::ChainIkSolverPos_TL(chain,lb,ub,maxtime,eps,true,true));\n\n    for (uint i=0; i<chain.segments.size(); i++) {\n      std::string type = chain.segments[i].getJoint().getTypeName();\n      if (type.find(\"Rot\")!=std::string::npos) {\n        if (ub(types.size())>=std::numeric_limits<float>::max() && \n            lb(types.size())<=std::numeric_limits<float>::lowest())\n          types.push_back(KDL::BasicJointType::Continuous);\n        else\n          types.push_back(KDL::BasicJointType::RotJoint);\n      }\n      else if (type.find(\"Trans\")!=std::string::npos)\n        types.push_back(KDL::BasicJointType::TransJoint);\n    }\n    \n    assert(types.size()==lb.data.size());\n\n\n    threads.create_thread(boost::bind(&boost::asio::io_service::run,\n                                      &io_service));\n    threads.create_thread(boost::bind(&boost::asio::io_service::run,\n                                      &io_service));\n\n    initialized = true;\n  }\n\n  bool TRAC_IK::unique_solution(const KDL::JntArray& sol) {\n\n    for (uint i=0; i< solutions.size(); i++)\n      if (myEqual(sol,solutions[i]))\n        return false;\n    return true;\n\n  }\n\n  inline void normalizeAngle(double& val, const double& min, const double& max)\n  {\n      if (val > max) {\n        //Find actual angle offset\n        double diffangle = fmod(val-max,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = max + diffangle - 2*M_PI;\n      }\n\n      if (val < min) {\n        //Find actual angle offset\n        double diffangle = fmod(min-val,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = min - diffangle + 2*M_PI;\n      }\n  }\n\n  inline void normalizeAngle(double& val, const double& target)\n  {\n      if (val > target+M_PI) {\n        //Find actual angle offset\n        double diffangle = fmod(val-target,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = target + diffangle - 2*M_PI;\n      }\n\n      if (val < target-M_PI) {\n        //Find actual angle offset\n        double diffangle = fmod(target-val,2*M_PI);\n        // Add that to upper bound and go back a full rotation\n        val = target - diffangle + 2*M_PI;\n      }\n  }\n\n\n  bool TRAC_IK::runKDL(const KDL::JntArray &q_init, const KDL::Frame &p_in)\n  {\n    KDL::JntArray q_out;\n\n    double fulltime = maxtime;\n    KDL::JntArray seed = q_init;\n\n    boost::posix_time::time_duration timediff;\n    double time_left;\n\n    while (true) {\n      timediff=boost::posix_time::microsec_clock::local_time()-start_time;\n      time_left = fulltime - timediff.total_nanoseconds()/1000000000.0;\n\n      if (time_left <= 0)\n        break;\n\n      iksolver->setMaxtime(time_left);\n\n      int kdlRC = iksolver->CartToJnt(seed,p_in,q_out,bounds);\n      if (kdlRC >=0) {\n        switch (solvetype) {\n        case Manip1:\n        case Manip2:\n          normalize_limits(q_init, q_out);\n          break;\n        default:\n          normalize_seed(q_init, q_out);\n          break;\n        }\n        mtx_.lock();\n        if (unique_solution(q_out)) {\n          solutions.push_back(q_out);\n          uint curr_size=solutions.size();\n          errors.resize(curr_size);\n          mtx_.unlock();\n          double err, penalty;\n          switch (solvetype) {\n          case Manip1:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue1(q_out);\n            break;\n          case Manip2:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue2(q_out);\n            break;\n          default:\n            err = TRAC_IK::JointErr(q_init,q_out);\n            break;\n          }\n          mtx_.lock();\n          errors[curr_size-1] = std::make_pair(err,curr_size-1);\n        }\n        mtx_.unlock();\n      }\n      \n      if (!solutions.empty() && solvetype == Speed)\n        break;\n      \n      for (unsigned int j=0; j<seed.data.size(); j++)\n        if (types[j]==KDL::BasicJointType::Continuous)\n          seed(j)=fRand(q_init(j)-2*M_PI, q_init(j)+2*M_PI);\n        else\n          seed(j)=fRand(lb(j), ub(j));\n    }\n    nl_solver->abort();\n\n    iksolver->setMaxtime(fulltime);\n\n    return true;\n  }\n\n  bool TRAC_IK::runNLOPT(const KDL::JntArray &q_init, const KDL::Frame &p_in)\n  {\n    KDL::JntArray q_out;\n\n    double fulltime = maxtime;\n    KDL::JntArray seed = q_init;\n\n    boost::posix_time::time_duration timediff;\n    double time_left;\n\n    while (true) {\n      timediff=boost::posix_time::microsec_clock::local_time()-start_time;\n      time_left = fulltime - timediff.total_nanoseconds()/1000000000.0;\n\n      if (time_left <= 0)\n        break;\n\n      nl_solver->setMaxtime(time_left);\n\n      int nloptRC = nl_solver->CartToJnt(seed,p_in,q_out,bounds);\n      if (nloptRC >=0) {\n        switch (solvetype) {\n        case Manip1:\n        case Manip2:\n          normalize_limits(q_init, q_out);\n          break;\n        default:\n          normalize_seed(q_init, q_out);\n          break;\n        }\n        mtx_.lock();\n        if (unique_solution(q_out)) {\n          solutions.push_back(q_out);\n          uint curr_size=solutions.size();\n          errors.resize(curr_size);\n          mtx_.unlock();\n          double err, penalty;\n          switch (solvetype) {\n          case Manip1:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue1(q_out);\n            break;\n          case Manip2:\n            penalty = manipPenalty(q_out);\n            err = penalty*TRAC_IK::ManipValue2(q_out);\n            break;\n          default:\n            err = TRAC_IK::JointErr(q_init,q_out);\n            break;\n          }\n          mtx_.lock();\n          errors[curr_size-1] = std::make_pair(err,curr_size-1);\n        }\n        mtx_.unlock();\n      }\n      \n      if (!solutions.empty() && solvetype == Speed)\n        break;\n      \n      for (unsigned int j=0; j<seed.data.size(); j++)\n        if (types[j]==KDL::BasicJointType::Continuous)\n          seed(j)=fRand(q_init(j)-2*M_PI, q_init(j)+2*M_PI);\n        else\n          seed(j)=fRand(lb(j), ub(j));\n    }\n\n    iksolver->abort();\n\n    nl_solver->setMaxtime(fulltime);\n\n    return true;\n  }\n\n  void TRAC_IK::normalize_seed(const KDL::JntArray& seed, KDL::JntArray& solution) {\n    // Make sure rotational joint values are within 1 revolution of seed; then\n    // ensure joint limits are met.\n\n    bool improved = false;\n\n    for (uint i=0; i<lb.data.size(); i++) {\n\n      if (types[i]==KDL::BasicJointType::TransJoint)\n        continue;\n\n      double target = seed(i);\n      double val = solution(i);\n\n      normalizeAngle( val, target );\n\n      if (types[i]==KDL::BasicJointType::Continuous) {\n        solution(i) = val;\n        continue;\n      }\n\n      normalizeAngle( val, lb(i), ub(i) );\n\n      solution(i) = val;\n    }\n  }\n\n  void TRAC_IK::normalize_limits(const KDL::JntArray& seed, KDL::JntArray& solution) {\n    // Make sure rotational joint values are within 1 revolution of middle of\n    // limits; then ensure joint limits are met.\n\n    bool improved = false;\n\n    for (uint i=0; i<lb.data.size(); i++) {\n\n      if (types[i] == KDL::BasicJointType::TransJoint)\n        continue;\n\n      double target = seed(i);\n\n      if (types[i] == KDL::BasicJointType::RotJoint && types[i]!=KDL::BasicJointType::Continuous)\n        target = (ub(i)+lb(i))/2.0;\n\n      double val = solution(i);\n\n      normalizeAngle( val, target );\n\n      if (types[i]==KDL::BasicJointType::Continuous) {\n        solution(i) = val;\n        continue;\n      }\n\n      normalizeAngle( val, lb(i), ub(i) );\n\n      solution(i) = val;\n    }\n\n  }\n\n\n  double TRAC_IK::manipPenalty(const KDL::JntArray& arr) {\n    double penalty = 1.0;\n    for (uint i=0; i< arr.data.size(); i++) {\n      if (types[i] == KDL::BasicJointType::Continuous)\n        continue;\n      double range = ub(i)-lb(i);\n      penalty *= ((arr(i)-lb(i))*(ub(i)-arr(i))/(range*range));\n    }\n    return std::max(0.0,1.0 - exp(-1*penalty));\n  }\n\n\n  double TRAC_IK::ManipValue1(const KDL::JntArray& arr) {\n    KDL::Jacobian jac(arr.data.size());\n\n    jacsolver->JntToJac(arr,jac);\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svdsolver(jac.data);\n    Eigen::MatrixXd singular_values = svdsolver.singularValues();\n\n    double error = 1.0;\n    for(unsigned int i=0; i < singular_values.rows(); ++i)\n      error *= singular_values(i,0);\n    return error;\n  }\n\n  double TRAC_IK::ManipValue2(const KDL::JntArray& arr) {\n    KDL::Jacobian jac(arr.data.size());\n\n    jacsolver->JntToJac(arr,jac);\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svdsolver(jac.data);\n    Eigen::MatrixXd singular_values = svdsolver.singularValues();\n\n    return singular_values.minCoeff()/singular_values.maxCoeff();\n  }\n\n\n  int TRAC_IK::CartToJnt(const KDL::JntArray &q_init, const KDL::Frame &p_in, KDL::JntArray &q_out, const KDL::Twist& _bounds) {\n\n    if (!initialized) {\n      ROS_ERROR(\"TRAC-IK was not properly initialized with a valid chain or limits.  IK cannot proceed\");\n      return -1;\n    }\n\n\n    start_time = boost::posix_time::microsec_clock::local_time();\n\n    nl_solver->reset();\n    iksolver->reset();\n\n    solutions.clear();\n    errors.clear();\n\n\n    bounds=_bounds;\n\n    std::vector<boost::shared_future<bool> > pending_data;\n\n    typedef boost::packaged_task<bool> task_t;\n    boost::shared_ptr<task_t> task1 = boost::make_shared<task_t>(boost::bind(&TRAC_IK::runKDL, this, boost::cref(q_init), boost::cref(p_in)));\n\n    boost::shared_ptr<task_t> task2 = boost::make_shared<task_t>(boost::bind(&TRAC_IK::runNLOPT, this, boost::cref(q_init), boost::cref(p_in)));\n\n    boost::shared_future<bool> fut1(task1->get_future());\n    boost::shared_future<bool> fut2(task2->get_future());\n\n    /*\n    // this was for pre-c++11\n    pending_data.push_back(boost::move(fut1));\n    pending_data.push_back(boost::move(fut2));\n    */\n    pending_data.push_back(fut1);\n    pending_data.push_back(fut2);\n\n    io_service.post(boost::bind(&task_t::operator(), task1));\n    io_service.post(boost::bind(&task_t::operator(), task2));\n\n    boost::wait_for_all(pending_data.begin(), pending_data.end());\n\n    if (solutions.empty()) {\n      q_out=q_init;\n      return -3;\n    }\n\n    switch (solvetype) {\n    case Manip1:\n    case Manip2:\n      std::sort(errors.rbegin(),errors.rend()); // rbegin/rend to sort by max\n      break;\n    default:\n      std::sort(errors.begin(),errors.end());\n      break;\n    }\n\n    q_out = solutions[errors[0].second];\n\n    return solutions.size();\n  }\n\n\n  TRAC_IK::~TRAC_IK(){\n    // Force all threads to return from io_service::run().\n    io_service.stop();\n\n    // Suppress all exceptions.\n    try\n      {\n        threads.join_all();\n      }\n    catch ( ... ) {}\n\n  }\n\n}\n", "meta": {"hexsha": "c0d8c94c57753e44055ce7274116a42e15084cba", "size": 15871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/trac_ik/trac_ik_lib/src/trac_ik.cpp", "max_stars_repo_name": "kirmani/hlpr_cadence", "max_stars_repo_head_hexsha": "b8756f2ef01ea2c19e1f9481190dac8e541c7244", "max_stars_repo_licenses": ["MIT"], "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/trac_ik/trac_ik_lib/src/trac_ik.cpp", "max_issues_repo_name": "kirmani/hlpr_cadence", "max_issues_repo_head_hexsha": "b8756f2ef01ea2c19e1f9481190dac8e541c7244", "max_issues_repo_licenses": ["MIT"], "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/trac_ik/trac_ik_lib/src/trac_ik.cpp", "max_forks_repo_name": "kirmani/hlpr_cadence", "max_forks_repo_head_hexsha": "b8756f2ef01ea2c19e1f9481190dac8e541c7244", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-29T21:17:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T21:17:20.000Z", "avg_line_length": 29.6100746269, "max_line_length": 158, "alphanum_fraction": 0.6112406276, "num_tokens": 4121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.021948251355781056, "lm_q1q2_score": 0.009525134273266015}}
{"text": "#ifndef FSTRESULTTRACKERFEATURESTATS_H\n#define FSTRESULTTRACKERFEATURESTATS_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    result_tracker_feature_stats.hpp\n   \\brief   Computes feature occurence statistics in a series of evaluated subsets\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 <list>\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"result_tracker_dupless.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 Collects evaluated subsets to eventually provide Dependency-Aware Feature Ranking coefficients.\n\n\tDependency-Aware Feature ranking (DAF) is a new type of ranking method especially\n\tsuitable for very-high-dimensional feature selection. Unlike standard individual\n\tfeature ranking, the DAF ranking reflects \"average feature quality in context\"\n\tand as such is capable of providing significantly better results than BIF\n\t(provided the data actually do contain mutually dependent features). The method\n\thas been described in combination with Monte Carlo based feature selection\n\tpermitting Wrapper Criteria even in very-high-dimensional setting.\n\tFor usage see \\ref example35 and \\ref example36. For more detailed\n\tinformation see UTIA Technical Report No. 2295.\n*/ \ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET>\nclass Result_Tracker_Feature_Stats : public Result_Tracker_Dupless<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET> {\npublic:\n\ttypedef Result_Tracker_Dupless<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET> parent;\n\ttypedef typename parent::ResultRec ResultRec;\n\ttypedef ResultRec* PResultRec;\n\ttypedef boost::shared_ptr<SUBSET> PSubset;\n\tResult_Tracker_Feature_Stats(const IDXTYPE capacity_limit=0):Result_Tracker_Dupless<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET>(capacity_limit), _n(0) {_itersize[0]=0; _itersize[1]=0; _itersize[2]=0; notify(\"Result_Tracker_Feature_Stats constructor.\");}\n\tResult_Tracker_Feature_Stats(const Result_Tracker_Feature_Stats& rtfs):Result_Tracker_Dupless<RETURNTYPE,IDXTYPE,DIMTYPE,SUBSET>(rtfs), _n(0) {_itersize[0]=0; _itersize[1]=0; _itersize[2]=0; notify(\"Result_Tracker_Feature_Stats copy-constructor.\");}\n\tvirtual ~Result_Tracker_Feature_Stats() {notify(\"Result_Tracker_Feature_Stats destructor.\");}\n\t\n\tbool compute_stats(std::ostream& os=std::cout);\n\tbool print_stats(std::ostream& os=std::cout); \n\n\tbool getFirstDAF(RETURNTYPE &value, DIMTYPE &feature, const unsigned int DAFidx=0) const;\n\tbool getNextDAF(RETURNTYPE &value, DIMTYPE &feature, const unsigned int DAFidx=0) const;\n\n\tResult_Tracker_Feature_Stats* clone() const {throw fst_error(\"Result_Tracker_Feature_Stats::clone() not supported, use Result_Tracker_Feature_Stats::stateless_clone() instead.\");}\n\tResult_Tracker_Feature_Stats* sharing_clone() const {throw fst_error(\"Result_Tracker_Feature_Stats::sharing_clone() not supported, use Result_Tracker_Feature_Stats::stateless_clone() instead.\");}\n\tResult_Tracker_Feature_Stats* stateless_clone() const;\n\n\tvirtual std::ostream& print(std::ostream& os) const {os << \"Result_Tracker_Feature_Stats(limit=\" << parent::_capacity_limit << \") size \" << parent::results.size(); return os;}\n\nprotected:\n\tDIMTYPE _n;\n\t//! Structure to gather feature occurence statistics over probe subset evaluations\n\ttypedef struct {\n\t\tRETURNTYPE freq_is, freq_isnot; // no of subsets containing/not-containing this feature\n\t\tRETURNTYPE mean_is, mean_isnot; // primary criterion mean value over subsets containing/not-containing this feature\n\t\tRETURNTYPE stdev_is, stdev_isnot; // primary criterion stddev over subsets containing/not-containing this feature\n\t\t// DAF0 indicator=  mean_is-mean_isnot\n\t\t// DAF1 indicator= (mean_is-mean_isnot)/((freq_is/freq)*stdev_is+(freq_isnot/freq)*stdev_isnot)\n\t\t// for DAF3 see UTIA Tech Report No. 2295\n\t\tRETURNTYPE daf[3]; \n\t\tbool daf_valid[3]; \n\t} FeatureStat;\n\tvector<FeatureStat> _stats; // for each feature over all subset sizes + then for each feature and each subset size\n\n\t//! Structure to gather probe subset cardinality statistics\n\ttypedef struct {\n\t\tRETURNTYPE freq; // no of subsets\n\t\tRETURNTYPE mean;\n\t\tRETURNTYPE stdev;\n\t\tbool valid;\n\t} SubSizeStat;\n\tvector<SubSizeStat> _dstat; // for each feature over all subset sizes\n\t\n\ttypedef vector<DIMTYPE> ORDERTYPE;\n\tORDERTYPE _order[3];  // to keep feature ordering according to DAF0, DAF1 and DAF2\n\tmutable DIMTYPE _itersize[3]; // iterator over feature ordering according to DAF0, DAF1 and DAF2\n};\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET>\nResult_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET>* Result_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET>::stateless_clone() const\n{\n\tResult_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET> *clone=new Result_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET>(*this);\n\tclone->set_cloned();\n\treturn clone;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET>\nbool Result_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET>::compute_stats(std::ostream& os)\n{\n\tif(parent::results.empty()) return false;\n\t\n\ttypename parent::CONSTRESULTSITER iter=parent::results.begin();\n\t// get n from first recorded sub (assumes all others have the same n)\n\t_n=iter->sub->get_n();\n\t_stats.resize(_n);\n\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\t_stats[f].freq_is=_stats[f].freq_isnot=_stats[f].mean_is=_stats[f].mean_isnot=_stats[f].stdev_is=_stats[f].stdev_isnot=0;\n\t\t_stats[f].daf_valid[0]=false;\n\t\t_stats[f].daf_valid[1]=false;\n\t\t_stats[f].daf_valid[2]=false;\n\t}\n\t_dstat.resize(_n+1);\n\tfor(DIMTYPE ss=1;ss<=_n;ss++) {\n\t\t_dstat[ss].mean=_dstat[ss].stdev=_dstat[ss].freq=0;\n\t\t_dstat[ss].valid=false;\n\t}\n\n\tif(parent::output_normal()) {std::ostringstream sos; sos << std::endl << \"compute_stats() 1/4..\" << std::endl << std::flush; syncout::print(os,sos);}\n\t// gather initial stats\n\tfor(iter=parent::results.begin();iter!=parent::results.end();iter++)\n\t{\n\t\tassert(iter->sub->get_n()==_n);\n\t\tDIMTYPE d=iter->sub->get_d();\n\t\tassert(d>0 && d<=_n);\n\t\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\t\tif(iter->sub->selected_raw(f)) {\n\t\t\t\t_stats[f].freq_is++;\n\t\t\t\t_stats[f].mean_is+=iter->value;\n\t\t\t} else {\n\t\t\t\t_stats[f].freq_isnot++;\n\t\t\t\t_stats[f].mean_isnot+=iter->value;\n\t\t\t}\n\t\t}\n\t\t_dstat[d].mean+=iter->value;\n\t\t_dstat[d].freq++;\n\t}\n\t\n\t// calculate mean values\n\tfor(DIMTYPE f=0;f<_n;f++)\n\t{\n\t\tif(_stats[f].freq_is>0) _stats[f].mean_is/=_stats[f].freq_is;\n\t\tif(_stats[f].freq_isnot>0) _stats[f].mean_isnot/=_stats[f].freq_isnot;\n\t}\n\tfor(DIMTYPE ss=1;ss<=_n;ss++) if(_dstat[ss].freq>0) {\n\t\t_dstat[ss].mean/=_dstat[ss].freq;\n\t}\n\tif(parent::output_normal()) {std::ostringstream sos; sos << \"compute_stats() 2/4..\" << std::endl << std::flush; syncout::print(os,sos);}\n\t\t\n\t// gather more stats\n\tfor(iter=parent::results.begin();iter!=parent::results.end();iter++)\n\t{\n\t\tassert(iter->sub->get_n()==_n);\n\t\tDIMTYPE d=iter->sub->get_d();\n\t\tassert(d>0 && d<=_n);\n\t\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\t\tif(iter->sub->selected_raw(f)) {\n\t\t\t\t_stats[f].stdev_is+=(_stats[f].mean_is-iter->value)*(_stats[f].mean_is-iter->value);\n\t\t\t} else {\n\t\t\t\t_stats[f].stdev_isnot+=(_stats[f].mean_isnot-iter->value)*(_stats[f].mean_isnot-iter->value);\n\t\t\t}\n\t\t}\n\t\t_dstat[d].stdev+=(_dstat[d].mean-iter->value)*(_dstat[d].mean-iter->value);\n\t}\n\t\n\t// calculate stddev values\n\tfor(DIMTYPE f=0;f<_n;f++)\n\t{\n\t\tif(_stats[f].freq_is>0) _stats[f].stdev_is=sqrt(_stats[f].stdev_is/_stats[f].freq_is);\n\t\tif(_stats[f].freq_is>0) _stats[f].stdev_isnot=sqrt(_stats[f].stdev_isnot/_stats[f].freq_isnot);\n\t}\n\tfor(DIMTYPE ss=1;ss<=_n;ss++) if(_dstat[ss].freq>0) {\n\t\t_dstat[ss].stdev=sqrt(_dstat[ss].stdev/_dstat[ss].freq);\n\t\t_dstat[ss].valid=true;\n\t}\n\t\n\t\n\tif(parent::output_normal()) {std::ostringstream sos; sos << \"compute_stats() 3/4..\" << std::endl << std::flush; syncout::print(os,sos);}\n\t// calculate DAF ranks\n\tfor(DIMTYPE f=0;f<_n;f++)\n\t{\n\t\tif(_stats[f].freq_is>0 && _stats[f].freq_isnot>0 && (_stats[f].stdev_is>0 || _stats[f].stdev_isnot>0) ) \n\t\t{\n\t\t\tRETURNTYPE freq=_stats[f].freq_is+_stats[f].freq_isnot;\n\t\t\t//DAF1\n\t\t\t_stats[f].daf[1]=(_stats[f].mean_is-_stats[f].mean_isnot)/( (_stats[f].freq_is/freq)*_stats[f].stdev_is + (_stats[f].freq_isnot/freq)*_stats[f].stdev_isnot );\n\t\t\t_stats[f].daf_valid[1]=true;\n\t\t\t//DAF0\n\t\t\t_stats[f].daf[0]=_stats[f].mean_is-_stats[f].mean_isnot;\n\t\t\t_stats[f].daf_valid[0]=true;\n\t\t} \n\t\telse _stats[f].daf_valid[1]=_stats[f].daf_valid[0]=false;\n\t}\n\t//DAF2\n\tvector<RETURNTYPE> mi1,mi2; mi1.resize(_n+1); mi2.resize(_n+1);\n\tvector<IDXTYPE> cnt1,cnt2; cnt1.resize(_n+1); cnt2.resize(_n+1);\n\tfor(DIMTYPE f=0;f<_n;f++) {mi1[f]=mi2[f]=0; cnt1[f]=cnt2[f]=0;}\n\tfor(iter=parent::results.begin();iter!=parent::results.end();iter++)\n\t{\n\t\tassert(iter->sub->get_n()==_n);\n\t\tDIMTYPE d=iter->sub->get_d();\n\t\tassert(d>0 && d<=_n);\n\t\t\n\t\tif(_dstat[d].stdev>0) {\n\t\t\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\t\t\tif(iter->sub->selected_raw(f)) {mi1[f]+=iter->value/_dstat[d].stdev; cnt1[f]++;}\n\t\t\t\telse {mi2[f]+=iter->value/_dstat[d].stdev; cnt2[f]++;}\n\t\t\t}\n\t\t}\n\t}\t\n\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\tif(cnt1[f]==0 || cnt2[f]==0) _stats[f].daf[2]=0; else\n\t\t{\n\t\t\tmi1[f]/=cnt1[f];\n\t\t\tmi2[f]/=cnt2[f];\n\t\t\t_stats[f].daf[2]=mi1[f]-mi2[f];\n\t\t}\n\t\t_stats[f].daf_valid[2]=true;\n\t}\n\n\tif(parent::output_normal()) {std::ostringstream sos; sos << \"compute_stats() 4/4..\" << std::endl << std::endl << std::flush; syncout::print(os,sos);}\n\t\n\t// order features according to DAF0, DAF1 and DAF2\n\tfor(unsigned int DAFidx=0; DAFidx<3; DAFidx++)\n\t{\n\t\t_order[DAFidx].clear();\n\t\tfor(DIMTYPE f=0;f<_n;f++)\n\t\t{\n\t\t\tif(_stats[f].daf_valid[DAFidx]) {\n\t\t\t\ttypename ORDERTYPE::iterator iter=_order[DAFidx].begin();\n\t\t\t\twhile(iter!=_order[DAFidx].end() && _stats[f].daf[DAFidx]<_stats[*iter].daf[DAFidx]) iter++;\n\t\t\t\t_order[DAFidx].insert(iter,f);\n\t\t\t}\n\t\t}\n\t\tif(_order[DAFidx].size()<_n && parent::output_normal()) {std::ostringstream sos; sos << \"WARNING: DAF\"<<DAFidx<<\" rank could not be computed for all features due to insufficient number of evaluated probes subsets.\" << std::endl << std::flush; syncout::print(os,sos);}\n\t}\n\tif(parent::output_normal()) {\n\t\tRETURNTYPE minfreq=_stats[0].freq_is; if(_stats[0].freq_isnot<_stats[0].freq_is) minfreq=_stats[0].freq_isnot;\n\t\tfor(DIMTYPE f=1;f<_n;f++) {\n\t\t\tif(_stats[f].freq_isnot<minfreq) minfreq=_stats[f].freq_isnot;\n\t\t\tif(_stats[f].freq_is<minfreq) minfreq=_stats[f].freq_is;\n\t\t}\n\t\t{\n\t\t\tstd::ostringstream sos; \n\t\t\tsos << \"Lowest feature evaluation frequency over all probes is \"<<minfreq<<\".\" << std::endl;\n\t\t\tif(minfreq<100) sos << \"WARNING: To ensure reliable DAF estimates the minimum feature evaluation frequency should be at least in the order of hundreds. More probes may be needed.\" << std::endl;\n\t\t\tsos << std::endl << std::flush;\n\t\t\tsyncout::print(os,sos);\n\t\t}\n\t}\n\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET>\nbool Result_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET>::print_stats(std::ostream& os)\n{\n\tstd::ostringstream sos;\n\tif(_n<1) {sos << \"Result_Tracker_Feature_Stats:: Nothing to print out.\" << std::endl; return false;}\n\t{\n\t\tsos << \"Probe subset stats for each (valid) cardinality:\"<< std::endl;\n\t\tfor(DIMTYPE ss=1;ss<=_n;ss++) \n\t\t\tif(_dstat[ss].valid) sos << \" d: \"<< ss << \"  mean=\" << _dstat[ss].mean << \", stddev=\" << _dstat[ss].stdev << \", freq=\" << _dstat[ss].freq << std::endl;\n\t\tsos << std::endl << \"Feature stats over all probe subsets:\"<< std::endl;\n\t\tfor(DIMTYPE f=0;f<_n;f++) {\n\t\t\tsos << \" F:\"<<f<< \" daf0 = \"; if(_stats[f].daf_valid[0]) sos << _stats[f].daf[0]; else sos << \"n/a\"; \n\t\t\tsos << \", daf1 = \"; if(_stats[f].daf_valid[1]) sos << _stats[f].daf[1]; else sos << \"n/a\";\n\t\t\tsos << \", daf2 = \"; if(_stats[f].daf_valid[2]) sos << _stats[f].daf[2]; else sos << \"n/a\";\n\t\t\tsos<<\",  freq \"<<_stats[f].freq_is<<\"|\"<<_stats[f].freq_isnot<<\",  mean \";\n\t\t\tif(_stats[f].freq_is>0) sos<<_stats[f].mean_is; else sos<< \"n/a\";\n\t\t\tsos <<\"|\";\n\t\t\tif(_stats[f].freq_isnot>0) sos<<_stats[f].mean_isnot; else sos<< \"n/a\";\n\t\t\tsos<<\", stdev \";\n\t\t\tif(_stats[f].freq_is>0) sos<<_stats[f].stdev_is; else sos<<\"n/a\";\n\t\t\tsos<<\"|\";\n\t\t\tif(_stats[f].freq_isnot>0) sos<<_stats[f].stdev_isnot; else sos << \"n/a\";\n\t\t\tsos<<std::endl;\n\t\t}\n\t\tsos<<std::endl;\n\t}\n\tsyncout::print(os,sos);\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET>\nbool Result_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET>::getFirstDAF(RETURNTYPE &value, DIMTYPE &feature, const unsigned int DAFidx) const\n{\n\tassert(0<=DAFidx && DAFidx<3);\n\t_itersize[DAFidx]=0;\n\tif(!_order[DAFidx].empty())\t{\n\t\tfeature=_order[DAFidx][0];\n\t\tassert(feature>=0 && feature<_n);\n\t\tvalue=_stats[feature].daf[DAFidx];\n\t\t_itersize[DAFidx]=1;\n\t\treturn true;\n\t} else return false;\n}\n\ntemplate<class RETURNTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET>\nbool Result_Tracker_Feature_Stats<RETURNTYPE, IDXTYPE, DIMTYPE, SUBSET>::getNextDAF(RETURNTYPE &value, DIMTYPE &feature, const unsigned int DAFidx) const\n{\n\tassert(0<=DAFidx && DAFidx<3);\n\tif(0<_itersize[DAFidx] && _itersize[DAFidx]<_order[DAFidx].size()) {\n\t\tfeature=_order[DAFidx][_itersize[DAFidx]];\n\t\tassert(feature>=0 && feature<_n);\n\t\tvalue=_stats[feature].daf[DAFidx];\n\t\t++_itersize[DAFidx];\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\n} // namespace\n#endif // FSTRESULTTRACKERFEATURESTATS_H ///:~\n", "meta": {"hexsha": "aef08edff58f3183745555182219b2632fabf414", "size": 17636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_search/result_tracker_feature_stats.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_search/result_tracker_feature_stats.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_search/result_tracker_feature_stats.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": 46.4105263158, "max_line_length": 269, "alphanum_fraction": 0.69613291, "num_tokens": 5215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.025957355408212587, "lm_q1q2_score": 0.009515700074717243}}
{"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/main/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_MULTIOBJECTIVEPROBLEM_HPP_\n#define DART_OPTIMIZATION_MULTIOBJECTIVEPROBLEM_HPP_\n\n#include <cstddef>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/optimization/Function.hpp\"\n\nnamespace dart {\nnamespace optimization {\n\nclass MultiObjectiveProblem\n{\npublic:\n  /// Constructor\n  explicit MultiObjectiveProblem(std::size_t dim, std::size_t integerDim = 0u);\n\n  /// Destructor\n  virtual ~MultiObjectiveProblem() = default;\n\n  /// \\{ \\name Solution\n\n  /// Sets the dimension of the solution.\n  ///\n  /// The element type of the solution can be either \\c double or \\c int. In the\n  /// case that the solution partially contains integers, we assume the integer\n  /// part takes place the tail of the solution, and the size of the integer\n  /// part is \\p integerDim. For example, a solution vector can be\n  /// <tt>[floating1, floating2, ..., int1, int2]</tt>.\n  ///\n  /// Note that the \\p dim represents the whole dimension of the solution so\n  /// that the dimension of floating-point part is to be (\\p dim -\n  /// \\p integerDim).\n  ///\n  /// By default, we assume the solution is homogeneously floating-point type (\n  /// i.e., \\p integerDim is zero).\n  ///\n  /// \\param[in] dim Total dimension of the solution.\n  /// \\param[in] integerDim The dimension of integer part in the solution.\n  virtual void setSolutionDimension(\n      std::size_t dim, std::size_t integerDim = 0u);\n\n  /// Returns dimension of the solution\n  virtual std::size_t getSolutionDimension() const;\n\n  /// Returns dimension of the floating-point part of the solution\n  std::size_t getDoubleDimension() const;\n\n  /// Sets dimension of the integers in the decision vector\n  virtual void setIntegerDimension(std::size_t dim);\n\n  /// Returns dimension of the integers in the decision vector\n  virtual std::size_t getIntegerDimension() const;\n\n  /// Sets lower bounds for optimization parameters\n  void setLowerBounds(const Eigen::VectorXd& lb);\n\n  /// Returns lower bounds for optimization parameters\n  const Eigen::VectorXd& getLowerBounds() const;\n\n  /// Sets upper bounds for optimization parameters\n  void setUpperBounds(const Eigen::VectorXd& ub);\n\n  /// Returns upper bounds for optimization parameters\n  const Eigen::VectorXd& getUpperBounds() const;\n\n  /// \\}\n\n  /// \\{ \\name Objectives\n\n  /// Returns the total dimension of objective functions.\n  virtual std::size_t getObjectiveDimension() const = 0;\n\n  /// \\}\n\n  /// \\{ \\name Equality Constraints\n\n  /// Returns the total dimension of equality constraints.\n  virtual std::size_t getEqConstraintDimension() const;\n\n  /// \\}\n\n  /// \\{ \\name Inequality Constraints\n\n  /// Returns the total dimension of inequality constraints.\n  virtual std::size_t getIneqConstraintDimension() const;\n\n  /// \\}\n\n  /// \\{ \\name Evaluations\n\n  /// Evaluates objectives\n  virtual Eigen::VectorXd evaluateObjectives(\n      const Eigen::VectorXd& x) const = 0;\n\n  /// Evaluates equality constraints\n  virtual Eigen::VectorXd evaluateEqConstraints(const Eigen::VectorXd& x) const;\n\n  /// Evaluates inequality constraints\n  virtual Eigen::VectorXd evaluateIneqConstraints(\n      const Eigen::VectorXd& x) const;\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\n  /// Prints information of this class to a stream.\n  virtual std::ostream& print(std::ostream& os) const;\n\nprotected:\n  /// Dimension of the decision vector (or optimization parameters)\n  std::size_t mDimension;\n\n  /// Dimension of integer in the decision vector. The integers are placed in\n  /// the tail of the decision vector.\n  std::size_t mIntegerDimension;\n\n  /// Lower bounds for optimization parameters\n  Eigen::VectorXd mLowerBounds;\n\n  /// Upper bounds for optimization parameters\n  Eigen::VectorXd mUpperBounds;\n};\n\n} // namespace optimization\n} // namespace dart\n\n#endif // DART_OPTIMIZATION_MULTIOBJECTIVEPROBLEM_HPP_\n", "meta": {"hexsha": "40f408337754ba18cb642d35cd14fd443398a7f2", "size": 5650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/optimization/MultiObjectiveProblem.hpp", "max_stars_repo_name": "lakshmipathyarjun6/dart", "max_stars_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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/optimization/MultiObjectiveProblem.hpp", "max_issues_repo_name": "lakshmipathyarjun6/dart", "max_issues_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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/MultiObjectiveProblem.hpp", "max_forks_repo_name": "lakshmipathyarjun6/dart", "max_forks_repo_head_hexsha": "0cb60d4c9ff99129b8a0dffb1747f68944b677f4", "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.630952381, "max_line_length": 80, "alphanum_fraction": 0.7288495575, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.025178839597556527, "lm_q1q2_score": 0.009506035588534838}}
{"text": "/*\n * Copyright (c) 2013-2016, Graphics Lab, Georgia Tech Research Corporation\n * Copyright (c) 2013-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#ifndef DART_DYNAMICS_POINTMASS_HPP_\n#define DART_DYNAMICS_POINTMASS_HPP_\n\n#include <vector>\n#include <Eigen/Dense>\n#include \"dart/math/Helpers.hpp\"\n#include \"dart/dynamics/Entity.hpp\"\n\nnamespace dart {\nnamespace dynamics {\n\nclass EllipsoidShape;\nclass SoftBodyNode;\n\nclass PointMassNotifier;\n\n///\nclass PointMass : public common::Subject\n{\npublic:\n  friend class SoftBodyNode;\n\n  /// State for each PointMass\n  struct State\n  {\n    /// Position\n    Eigen::Vector3d mPositions;\n\n    /// Generalized velocity\n    Eigen::Vector3d mVelocities;\n\n    /// Generalized acceleration\n    Eigen::Vector3d mAccelerations;\n\n    /// Generalized force\n    Eigen::Vector3d mForces;\n\n    /// Default constructor\n    State(const Eigen::Vector3d& positions = Eigen::Vector3d::Zero(),\n          const Eigen::Vector3d& velocities = Eigen::Vector3d::Zero(),\n          const Eigen::Vector3d& accelerations = Eigen::Vector3d::Zero(),\n          const Eigen::Vector3d& forces = Eigen::Vector3d::Zero());\n\n    bool operator==(const State& other) const;\n\n    virtual ~State() = default;\n  };\n\n  /// Properties for each PointMass\n  struct Properties\n  {\n    /// Resting position viewed in the parent SoftBodyNode frame\n    Eigen::Vector3d mX0;\n\n    /// Mass.\n    double mMass;\n\n    /// Indices of connected Point Masses\n    std::vector<std::size_t> mConnectedPointMassIndices;\n\n    /// Lower limit of position\n    Eigen::Vector3d mPositionLowerLimits; // Currently unused\n\n    /// Upper limit of position\n    Eigen::Vector3d mPositionUpperLimits; // Currently unused\n\n    /// Min value allowed.\n    Eigen::Vector3d mVelocityLowerLimits; // Currently unused\n\n    /// Max value allowed.\n    Eigen::Vector3d mVelocityUpperLimits; // Currently unused\n\n    /// Min value allowed.\n    Eigen::Vector3d mAccelerationLowerLimits; // Currently unused\n\n    /// upper limit of generalized acceleration\n    Eigen::Vector3d mAccelerationUpperLimits; // Currently unused\n\n    /// Min value allowed.\n    Eigen::Vector3d mForceLowerLimits; // Currently unused\n\n    /// Max value allowed.\n    Eigen::Vector3d mForceUpperLimits; // Currently unused\n\n    Properties(const Eigen::Vector3d& _X0 = Eigen::Vector3d::Zero(),\n               double _mass = 0.0005,\n               const std::vector<std::size_t>& _connections = std::vector<std::size_t>(),\n               const Eigen::Vector3d& _positionLowerLimits =\n                                      Eigen::Vector3d::Constant(-math::constantsd::inf()),\n               const Eigen::Vector3d& _positionUpperLimits =\n                                      Eigen::Vector3d::Constant( math::constantsd::inf()),\n               const Eigen::Vector3d& _velocityLowerLimits =\n                                      Eigen::Vector3d::Constant(-math::constantsd::inf()),\n               const Eigen::Vector3d& _velocityUpperLimits =\n                                      Eigen::Vector3d::Constant( math::constantsd::inf()),\n               const Eigen::Vector3d& _accelerationLowerLimits =\n                                      Eigen::Vector3d::Constant(-math::constantsd::inf()),\n               const Eigen::Vector3d& _accelerationUpperLimits =\n                                      Eigen::Vector3d::Constant( math::constantsd::inf()),\n               const Eigen::Vector3d& _forceLowerLimits =\n                                      Eigen::Vector3d::Constant(-math::constantsd::inf()),\n               const Eigen::Vector3d& _forceUpperLimits =\n                                      Eigen::Vector3d::Constant( math::constantsd::inf()));\n\n    void setRestingPosition(const Eigen::Vector3d& _x);\n\n    void setMass(double _mass);\n\n    bool operator==(const Properties& other) const;\n\n    bool operator!=(const Properties& other) const;\n\n    virtual ~Properties() = default;\n  };\n\n  //--------------------------------------------------------------------------\n  // Constructor and Desctructor\n  //--------------------------------------------------------------------------\n\n  /// Default destructor\n  virtual ~PointMass();\n\n  /// State of this PointMass\n  State& getState();\n\n  /// State of this PointMass\n  const State& getState() const;\n\n  ///\n  std::size_t getIndexInSoftBodyNode() const;\n\n  ///\n  void setMass(double _mass);\n\n  ///\n  double getMass() const;\n\n  ///\n  double getPsi() const;\n\n  ///\n  double getImplicitPsi() const;\n\n  ///\n  double getPi() const;\n\n  ///\n  double getImplicitPi() const;\n\n  ///\n  void addConnectedPointMass(PointMass* _pointMass);\n\n  ///\n  std::size_t getNumConnectedPointMasses() const;\n\n  ///\n  PointMass* getConnectedPointMass(std::size_t _idx);\n\n  ///\n  const PointMass* getConnectedPointMass(std::size_t _idx) const;\n\n\n  /// Set whether this point mass is colliding with other objects. Note that\n  /// this status is set by the constraint solver during dynamics simulation but\n  /// not by collision detector.\n  /// \\param[in] True if this point mass is colliding.\n  void setColliding(bool _isColliding);\n\n  /// Return whether this point mass is set to be colliding with other objects.\n  /// \\return True if this point mass is colliding.\n  bool isColliding();\n\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  std::size_t getNumDofs() const;\n\n//  // Documentation inherited\n//  void setIndexInSkeleton(std::size_t _index, std::size_t _indexInSkeleton);\n\n//  // Documentation inherited\n//  std::size_t getIndexInSkeleton(std::size_t _index) const;\n\n  //----------------------------------------------------------------------------\n  // Position\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  void setPosition(std::size_t _index, double _position);\n\n  // Documentation inherited\n  double getPosition(std::size_t _index) const;\n\n  // Documentation inherited\n  void setPositions(const Eigen::Vector3d& _positions);\n\n  // Documentation inherited\n  const Eigen::Vector3d& getPositions() const;\n\n  // Documentation inherited\n  void resetPositions();\n\n  //----------------------------------------------------------------------------\n  // Velocity\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  void setVelocity(std::size_t _index, double _velocity);\n\n  // Documentation inherited\n  double getVelocity(std::size_t _index) const;\n\n  // Documentation inherited\n  void setVelocities(const Eigen::Vector3d& _velocities);\n\n  // Documentation inherited\n  const Eigen::Vector3d& getVelocities() const;\n\n  // Documentation inherited\n  void resetVelocities();\n\n  //----------------------------------------------------------------------------\n  // Acceleration\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  void setAcceleration(std::size_t _index, double _acceleration);\n\n  // Documentation inherited\n  double getAcceleration(std::size_t _index) const;\n\n  // Documentation inherited\n  void setAccelerations(const Eigen::Vector3d& _accelerations);\n\n  // Documentation inherited\n  const Eigen::Vector3d& getAccelerations() const;\n\n  /// Get the Eta term of this PointMass\n  const Eigen::Vector3d& getPartialAccelerations() const;\n\n  // Documentation inherited\n  void resetAccelerations();\n\n  //----------------------------------------------------------------------------\n  // Force\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  void setForce(std::size_t _index, double _force);\n\n  // Documentation inherited\n  double getForce(std::size_t _index);\n\n  // Documentation inherited\n  void setForces(const Eigen::Vector3d& _forces);\n\n  // Documentation inherited\n  const Eigen::Vector3d& getForces() const;\n\n  // Documentation inherited\n  void resetForces();\n\n  //----------------------------------------------------------------------------\n  // Velocity change\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  void setVelocityChange(std::size_t _index, double _velocityChange);\n\n  // Documentation inherited\n  double getVelocityChange(std::size_t _index);\n\n  // Documentation inherited\n  void resetVelocityChanges();\n\n  //----------------------------------------------------------------------------\n  // Constraint impulse\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  void setConstraintImpulse(std::size_t _index, double _impulse);\n\n  // Documentation inherited\n  double getConstraintImpulse(std::size_t _index);\n\n  // Documentation inherited\n  void resetConstraintImpulses();\n\n  //----------------------------------------------------------------------------\n  // Integration\n  //----------------------------------------------------------------------------\n\n  // Documentation inherited\n  void integratePositions(double _dt);\n\n  // Documentation inherited\n  void integrateVelocities(double _dt);\n\n  //----------------------------------------------------------------------------\n\n  /// Add linear Cartesian force to this node.\n  /// \\param[in] _force External force.\n  /// \\param[in] _isForceLocal True if _force's reference frame is of the parent\n  ///                          soft body node. False if _force's reference frame\n  ///                          is of the world.\n  void addExtForce(const Eigen::Vector3d& _force, bool _isForceLocal = false);\n\n  ///\n  void clearExtForce();\n\n  //----------------------------------------------------------------------------\n  // Constraints\n  //   - Following functions are managed by constraint solver.\n  //----------------------------------------------------------------------------\n  /// Set constraint impulse\n  void setConstraintImpulse(const Eigen::Vector3d& _constImp,\n                            bool _isLocal = false);\n\n  /// Add constraint impulse\n  void addConstraintImpulse(const Eigen::Vector3d& _constImp,\n                            bool _isLocal = false);\n\n  /// Clear constraint impulse\n  void clearConstraintImpulse();\n\n  /// Get constraint impulse\n  Eigen::Vector3d getConstraintImpulses() const;\n\n  //----------------------------------------------------------------------------\n  ///\n  void setRestingPosition(const Eigen::Vector3d& _p);\n\n  ///\n  const Eigen::Vector3d& getRestingPosition() const;\n\n  ///\n  const Eigen::Vector3d& getLocalPosition() const;\n\n  ///\n  const Eigen::Vector3d& getWorldPosition() const;\n\n  /// \\todo Temporary function.\n  Eigen::Matrix<double, 3, Eigen::Dynamic> getBodyJacobian();\n  Eigen::Matrix<double, 3, Eigen::Dynamic> getWorldJacobian();\n\n  /// Return velocity change due to impulse\n  const Eigen::Vector3d& getBodyVelocityChange() const;\n\n  ///\n  SoftBodyNode* getParentSoftBodyNode();\n\n  ///\n  const SoftBodyNode* getParentSoftBodyNode() const;\n\n  /// The number of the generalized coordinates by which this node is\n  ///        affected.\n//  int getNumDependentGenCoords() const;\n\n  /// Return a generalized coordinate index from the array index\n  ///        (< getNumDependentDofs).\n//  int getDependentGenCoord(int _arrayIndex) const;\n\n  /// Get the generalized velocity at the position of this point mass\n  ///        where the velocity is expressed in the parent soft body node frame.\n  const Eigen::Vector3d& getBodyVelocity() const;\n\n  /// Get the generalized velocity at the position of this point mass\n  ///        where the velocity is expressed in the world frame.\n  Eigen::Vector3d getWorldVelocity() const;\n\n  /// Get the generalized acceleration at the position of this point mass\n  ///        where the acceleration is expressed in the parent soft body node\n  ///        frame.\n  const Eigen::Vector3d& getBodyAcceleration() const;\n\n  /// Get the generalized acceleration at the position of this point mass\n  ///        where the acceleration is expressed in the world frame.\n  Eigen::Vector3d getWorldAcceleration() const;\n\nprotected:\n  /// Constructor used by SoftBodyNode\n  explicit PointMass(SoftBodyNode* _softBodyNode);\n\n  ///\n  void init();\n\n  //----------------------------------------------------------------------------\n  /// \\{ \\name Recursive dynamics routines\n  //----------------------------------------------------------------------------\n\n  /// \\brief Update transformation.\n  void updateTransform() const;\n\n  /// \\brief Update body velocity.\n  void updateVelocity() const;\n\n  /// \\brief Update partial body acceleration due to parent joint's velocity.\n  void updatePartialAcceleration() const;\n\n  /// \\brief Update articulated body inertia. Forward dynamics routine.\n  /// \\param[in] _timeStep Rquired for implicit joint stiffness and damping.\n  void updateArtInertiaFD(double _timeStep) const;\n\n  /// \\brief Update bias force associated with the articulated body inertia.\n  /// Forward dynamics routine.\n  /// \\param[in] _gravity Vector of gravitational acceleration\n  /// \\param[in] _timeStep Rquired for implicit joint stiffness and damping.\n  void updateBiasForceFD(double _dt, const Eigen::Vector3d& _gravity);\n\n  /// \\brief Update bias impulse associated with the articulated body inertia.\n  /// Impulse-based forward dynamics routine.\n  void updateBiasImpulseFD();\n\n  /// \\brief Update body acceleration with the partial body acceleration.\n  void updateAccelerationID() const;\n\n  /// \\brief Update body acceleration. Forward dynamics routine.\n  void updateAccelerationFD();\n\n  /// \\brief Update body velocity change. Impluse-based forward dynamics\n  /// routine.\n  void updateVelocityChangeFD();\n\n  /// \\brief Update body force. Inverse dynamics routine.\n  void updateTransmittedForceID(const Eigen::Vector3d& _gravity,\n                                bool _withExternalForces = false);\n\n  /// \\brief Update body force. Forward dynamics routine.\n  void updateTransmittedForce();\n\n  /// \\brief Update body force. Impulse-based forward dynamics routine.\n  void updateTransmittedImpulse();\n\n  /// \\brief Update the joint force. Inverse dynamics routine.\n  void updateJointForceID(double _timeStep,\n                          double _withDampingForces,\n                          double _withSpringForces);\n\n  /// \\brief Update constrained terms due to the constraint impulses. Foward\n  /// dynamics routine.\n  void updateConstrainedTermsFD(double _timeStep);\n\n  /// \\}\n\n  //----------------------------------------------------------------------------\n  /// \\{ \\name Equations of motion related routines\n  //----------------------------------------------------------------------------\n\n  ///\n  void updateMassMatrix();\n\n  ///\n  void aggregateMassMatrix(Eigen::MatrixXd& _MCol, int _col);\n\n  ///\n  void aggregateAugMassMatrix(Eigen::MatrixXd& _MCol, int _col,\n                              double _timeStep);\n\n  ///\n  void updateInvMassMatrix();\n\n  ///\n  void updateInvAugMassMatrix();\n\n  ///\n  void aggregateInvMassMatrix(Eigen::MatrixXd& _MInvCol, int _col);\n\n  ///\n  void aggregateInvAugMassMatrix(Eigen::MatrixXd& _MInvCol, int _col,\n                                 double _timeStep);\n\n  ///\n  void aggregateGravityForceVector(Eigen::VectorXd& _g,\n                                   const Eigen::Vector3d& _gravity);\n\n  ///\n  void updateCombinedVector();\n\n  ///\n  void aggregateCombinedVector(Eigen::VectorXd& _Cg,\n                               const Eigen::Vector3d& _gravity);\n\n  /// Aggregate the external forces mFext in the generalized\n  ///        coordinates recursively.\n  void aggregateExternalForces(Eigen::VectorXd& _Fext);\n\n  /// \\}\n\n  //-------------------- Cache Data for Mass Matrix ----------------------------\n  ///\n  Eigen::Vector3d mM_dV;\n\n  ///\n  Eigen::Vector3d mM_F;\n\n  //----------------- Cache Data for Mass Inverse Matrix -----------------------\n  ///\n  Eigen::Vector3d mBiasForceForInvMeta;\n\n  //---------------- Cache Data for Gravity Force Vector -----------------------\n  ///\n  Eigen::Vector3d mG_F;\n\n  //------------------- Cache Data for Combined Vector -------------------------\n  ///\n  Eigen::Vector3d mCg_dV;\n\n  ///\n  Eigen::Vector3d mCg_F;\n\nprotected:\n  // TODO(JS): Need?\n  ///\n//  Eigen::Matrix<std::size_t, 3, 1> mIndexInSkeleton;\n\n  /// SoftBodyNode that this PointMass belongs to\n  SoftBodyNode* mParentSoftBodyNode;\n\n  /// Index of this PointMass within the SoftBodyNode\n  std::size_t mIndex;\n\n  //----------------------------------------------------------------------------\n  // Configuration\n  //----------------------------------------------------------------------------\n\n  /// Derivatives w.r.t. an arbitrary scalr variable\n  Eigen::Vector3d mPositionDeriv;\n\n  //----------------------------------------------------------------------------\n  // Velocity\n  //----------------------------------------------------------------------------\n\n  /// Derivatives w.r.t. an arbitrary scalr variable\n  Eigen::Vector3d mVelocitiesDeriv;\n\n  //----------------------------------------------------------------------------\n  // Acceleration\n  //----------------------------------------------------------------------------\n\n  /// Derivatives w.r.t. an arbitrary scalr variable\n  Eigen::Vector3d mAccelerationsDeriv;\n\n  //----------------------------------------------------------------------------\n  // Force\n  //----------------------------------------------------------------------------\n\n\n  /// Derivatives w.r.t. an arbitrary scalr variable\n  Eigen::Vector3d mForcesDeriv;\n\n  //----------------------------------------------------------------------------\n  // Impulse\n  //----------------------------------------------------------------------------\n\n  /// Change of generalized velocity\n  Eigen::Vector3d mVelocityChanges;\n\n//  /// Generalized impulse\n//  Eigen::Vector3d mImpulse;\n\n  /// Generalized constraint impulse\n  Eigen::Vector3d mConstraintImpulses;\n\n  //----------------------------------------------------------------------------\n\n  /// Current position viewed in world frame.\n  mutable Eigen::Vector3d mW;\n\n  /// Current position viewed in parent soft body node frame.\n  mutable Eigen::Vector3d mX;\n\n  /// Current velocity viewed in parent soft body node frame.\n  mutable Eigen::Vector3d mV;\n\n  /// Partial Acceleration of this PointMass\n  mutable Eigen::Vector3d mEta;\n\n  ///\n  Eigen::Vector3d mAlpha;\n\n  ///\n  Eigen::Vector3d mBeta;\n\n  /// Current acceleration viewed in parent body node frame.\n  mutable Eigen::Vector3d mA;\n\n  ///\n  Eigen::Vector3d mF;\n\n  ///\n  mutable double mPsi;\n\n  ///\n  mutable double mImplicitPsi;\n\n  ///\n  mutable double mPi;\n\n  ///\n  mutable double mImplicitPi;\n\n  /// Bias force\n  Eigen::Vector3d mB;\n\n  /// External force.\n  Eigen::Vector3d mFext;\n\n  /// A increasingly sorted list of dependent dof indices.\n  std::vector<std::size_t> mDependentGenCoordIndices;\n\n  /// Whether the node is currently in collision with another node.\n  bool mIsColliding;\n\n  //------------------------- Impulse-based Dyanmics ---------------------------\n  /// Velocity change due to constraint impulse\n  Eigen::Vector3d mDelV;\n\n  /// Impulsive bias force due to external impulsive force exerted on\n  ///        bodies of the parent skeleton.\n  Eigen::Vector3d mImpB;\n\n  /// Cache data for mImpB\n  Eigen::Vector3d mImpAlpha;\n\n  /// Cache data for mImpB\n  Eigen::Vector3d mImpBeta;\n\n  /// Generalized impulsive body force w.r.t. body frame.\n  Eigen::Vector3d mImpF;\n\n  PointMassNotifier* mNotifier;\n\npublic:\n  // To get byte-aligned Eigen vectors\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n//struct PointMassPair\n//{\n//  PointMass* pm1;\n//  PointMass* pm2;\n//};\n\nclass PointMassNotifier : public Entity\n{\npublic:\n\n  PointMassNotifier(SoftBodyNode* _parentSoftBody, const std::string& _name);\n\n  bool needsPartialAccelerationUpdate() const;\n\n  void clearTransformNotice();\n  void clearVelocityNotice();\n  void clearPartialAccelerationNotice();\n  void clearAccelerationNotice();\n\n  void notifyTransformUpdate() override;\n  void notifyVelocityUpdate() override;\n  void notifyAccelerationUpdate() override;\n\n  // Documentation inherited\n  const std::string& setName(const std::string& _name) override;\n\n  // Documentation inherited\n  const std::string& getName() const override;\n\nprotected:\n\n  std::string mName;\n\n  bool mNeedPartialAccelerationUpdate;\n\n  SoftBodyNode* mParentSoftBodyNode;\n\n};\n\n}  // namespace dynamics\n}  // namespace dart\n\n#endif  // DART_DYNAMICS_POINTMASS_HPP_\n", "meta": {"hexsha": "d546b7eafe5fd65ddc63c991a0bf13f56ebb8ca1", "size": 21890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/dynamics/PointMass.hpp", "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/dynamics/PointMass.hpp", "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/dynamics/PointMass.hpp", "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": 30.7443820225, "max_line_length": 91, "alphanum_fraction": 0.5944266788, "num_tokens": 4548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.02228618529570873, "lm_q1q2_score": 0.009501081682195982}}
{"text": "/*\n * Mercury7.hpp\n *\n *  Copyright (C) 2012 Marc Kirchner\n *\n * This file is part of the Mass Spectrometry Toolkit (MSTK).\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#ifndef __MSTK_INCLUDE_MSTK_IPACA_MERCURY7_HPP__\n#define __MSTK_INCLUDE_MSTK_IPACA_MERCURY7_HPP__\n#include <MSTK/config.hpp>\n#include <MSTK/ipaca/Mercury7Impl.hpp>\n#include <MSTK/ipaca/Spectrum.hpp>\n#include <MSTK/ipaca/Stoichiometry.hpp>\n#include <MSTK/common/Types.hpp>\n#include <MSTK/ipaca/Traits.hpp>\n#include <boost/shared_ptr.hpp>\n\nnamespace mstk {\n    \nnamespace ipaca {\n\n/** Calculates a theoretical isotope distribution from an\n *  elemental composition (stoichiometry).\n *\n *  The client is required to provide type information for the\n *  stoichiometry and the resulting spectra as well as two conversion\n *  function in \\c ipaca::Traits<U,V> that specifiy how the user-\n *  defined stoichiometry and spectrum types are converted into\n *  the internale representation used by ipaca (i.e. \\c ipaca::Spectrum\n *  and \\c ipaca::Stoichiometry).\n *  See \\c test/Mercury7-test.cpp for a simple example.\n */\ntemplate<typename StoichiometryType, typename SpectrumType>\nclass Mercury7\n{\npublic:\n    /** The type of particle that carries the charge.\n     */\n    enum Particle\n    {\n        ELECTRON, PROTON\n    };\n\n    /** Constructor.\n     */\n    Mercury7();\n\n    /** Functor method to calculate the theoretical isotope\n     *         distribution of a compound.\n     * @param stoichiometry The stoichiometry for which the isotope\n     *                      distribution should be calculated.\n     * @param limit The abundance limit below which peaks are pruned\n     *              during the processing\n     *\n     * The procedure is based on Perttu Haimi's and Alan Rockwood's\n     * sparse/binary convolution algorithm.\n     */\n    SpectrumType\n    operator()(const StoichiometryType& stoichiometry, const int charge,\n        const Particle particle, const Double limit = 1e-26) const;\n\n    /** calculate the monoisotopic mass of a given stoichiometry\n     *  @param stoichiometry The stoichiometry to calculate the mass for.\n     *  @param charge The charge at which the monoisotopic mass is desired\n     *                (zero for theoretical but unobservable mass).\n     */\n    Double\n    getMonoisotopicMass(const StoichiometryType& stoichiometry) const;\n\n    /** calculate the average mass of a given stoichiometry\n     *  @param stoichiometry The stoichiometry to calculate the mass for.\n     *  @param charge The charge at which the average mass is desired\n     *                (zero for theoretical but unobservable mass).\n     */\n    Double getAverageMass(const StoichiometryType& stoichiometry) const;\nprivate:\n    boost::shared_ptr<detail::Mercury7Impl> pImpl_;\n};\n\n//\n// template implementation\n//\n\ntemplate<typename StoichiometryType, typename SpectrumType>\nMercury7<StoichiometryType, SpectrumType>::Mercury7() :\n    pImpl_(new detail::Mercury7Impl)\n{\n}\n\ntemplate<typename StoichiometryType, typename SpectrumType>\nSpectrumType Mercury7<StoichiometryType, SpectrumType>::operator()(\n    const StoichiometryType& stoichiometry, const int charge,\n    const Particle particle, const Double limit) const\n{\n    // convert the user type to our internal type\n    detail::Stoichiometry s;\n    typename Traits<StoichiometryType, SpectrumType>::stoichiometry_converter\n            stoi_conv;\n    stoi_conv(stoichiometry, s);\n    // adjust the stoichiometry for charge and particle type\n\n\n    // Adjust the number of hydrogens.\n    if (charge != 0 && particle == PROTON) {\n        detail::adjustStoichiometryForProtonation<StoichiometryType, SpectrumType>(s, charge);\n    }\n    detail::Spectrum result = pImpl_->operator()(s, limit);\n    // Do the charge adjustment. This is the same for all types of charges\n    // because we adjusted the number of hydrogens earlier.\n    if (charge != 0) {\n        Int absCharge = (abs)(charge);\n        Double e = Traits<StoichiometryType, SpectrumType>::getElectronMass();\n        typedef detail::Spectrum::iterator IT;\n        for (IT i = result.begin(); i != result.end(); ++i) {\n            i->mz = (i->mz - (charge * e)) / absCharge;\n        }\n    }\n    SpectrumType spectrum;\n    typename Traits<StoichiometryType, SpectrumType>::spectrum_converter\n            spec_conv;\n    spec_conv(result, spectrum);\n    return spectrum;\n}\n\ntemplate<typename StoichiometryType, typename SpectrumType>\nDouble Mercury7<StoichiometryType, SpectrumType>::getMonoisotopicMass(\n    const StoichiometryType& stoichiometry) const\n{\n    detail::Stoichiometry s;\n    typename Traits<StoichiometryType, SpectrumType>::stoichiometry_converter\n            stoi_conv;\n    stoi_conv(stoichiometry, s);\n    return pImpl_->getMonoisotopicMass(s);\n}\n\ntemplate<typename StoichiometryType, typename SpectrumType>\nDouble Mercury7<StoichiometryType, SpectrumType>::getAverageMass(\n    const StoichiometryType& stoichiometry) const\n{\n    detail::Stoichiometry s;\n    typename Traits<StoichiometryType, SpectrumType>::stoichiometry_converter\n            stoi_conv;\n    stoi_conv(stoichiometry, s);\n    return pImpl_->getAverageMass(s);\n}\n\n} // namespace ipaca\n\n} // namespace mstk\n\n#endif\n", "meta": {"hexsha": "a907a9ee1796375c7980f816468f7e3d1326234a", "size": 6211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MSTK/ipaca/Mercury7.hpp", "max_stars_repo_name": "kirchnerlab/MSTK", "max_stars_repo_head_hexsha": "99b6d9bffff3ad209a04295a2b23a3e61e76a29c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T19:45:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T19:45:39.000Z", "max_issues_repo_path": "include/MSTK/ipaca/Mercury7.hpp", "max_issues_repo_name": "kirchnerlab/MSTK", "max_issues_repo_head_hexsha": "99b6d9bffff3ad209a04295a2b23a3e61e76a29c", "max_issues_repo_licenses": ["MIT"], "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/MSTK/ipaca/Mercury7.hpp", "max_forks_repo_name": "kirchnerlab/MSTK", "max_forks_repo_head_hexsha": "99b6d9bffff3ad209a04295a2b23a3e61e76a29c", "max_forks_repo_licenses": ["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.5352941176, "max_line_length": 94, "alphanum_fraction": 0.719690871, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.03410042963877804, "lm_q1q2_score": 0.009488676215160738}}
{"text": "// This file is part of the dune-xt-grid project:\n//   https://github.com/dune-community/dune-xt-grid\n// Copyright 2009-2018 dune-xt-grid 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 (2017 - 2018)\n//   René Fritze     (2018)\n//   Tobias Leibner  (2017 - 2018)\n\n#ifndef DUNE_XT_GRID_DD_GLUED_HH\n#define DUNE_XT_GRID_DD_GLUED_HH\n\n#include <array>\n#include <algorithm>\n#include <memory>\n#include <map>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/grid/common/rangegenerators.hh>\n\n#if HAVE_DUNE_GRID_GLUE\n#  include <dune/grid-glue/extractors/codim1extractor.hh>\n#  include <dune/grid-glue/gridglue.hh>\n#  include <dune/grid-glue/merging/contactmerge.hh>\n#endif // HAVE_DUNE_GRID_GLUE\n\n#include <dune/xt/common/exceptions.hh>\n#include <dune/xt/common/float_cmp.hh>\n#include <dune/xt/common/ranges.hh>\n#include <dune/xt/common/timedlogging.hh>\n#include <dune/xt/grid/intersection.hh>\n#include <dune/xt/grid/layers.hh>\n#include <dune/xt/grid/gridprovider/provider.hh>\n#include <dune/xt/grid/gridprovider/cube.hh>\n#include <dune/xt/grid/search.hh>\n#include <dune/xt/grid/type_traits.hh>\n\nnamespace Dune {\nnamespace XT {\nnamespace Grid {\nnamespace DD {\nnamespace Exceptions {\n\n\nclass intersection_orientation_is_broken : public Dune::InvalidStateException\n{};\n\n\n} // namespace Exceptions\n\n\n#if HAVE_DUNE_GRID_GLUE\n\n\ntemplate <typename P0, typename P1>\nsize_t check_for_broken_coupling_intersections(\n    const GridGlue::GridGlue<P0, P1>& glue,\n    const typename P0::ctype& tolerance = 10 * XT::Common::FloatCmp::DefaultEpsilon<typename P0::ctype>::value())\n{\n  const auto inside_grid_view = glue.template gridView<0>();\n  size_t failures = 0;\n  // walk the coupling\n  const auto coupling_intersection_it_end = glue.template iend<0>();\n  for (auto coupling_intersection_it = glue.template ibegin<0>();\n       coupling_intersection_it != coupling_intersection_it_end;\n       ++coupling_intersection_it) {\n    const auto& coupling_intersection = *coupling_intersection_it;\n    const auto coupling_intersection_normal = coupling_intersection.centerUnitOuterNormal();\n    const auto local_entity = coupling_intersection.inside();\n    typename std::remove_const<decltype(coupling_intersection_normal)>::type local_intersection_normal(0.);\n    // find the intersection of the local inside entity that corresponds to the coupling intersection\n    size_t found = 0;\n    for (auto&& local_intersection : intersections(inside_grid_view, local_entity)) {\n      // the coupling intersection may be smaller than the local intersection, so check if all of the corners of the\n      // coupling intersection lie within this local intersection\n      int corners_inside = 0;\n      for (auto ii : XT::Common::value_range(coupling_intersection.geometry().corners()))\n        if (XT::Grid::contains(local_intersection, coupling_intersection.geometry().corner(ii)))\n          ++corners_inside;\n      if (corners_inside == coupling_intersection.geometry().corners()) {\n        // this is the one\n        ++found;\n        local_intersection_normal = local_intersection.centerUnitOuterNormal();\n      }\n    }\n    if (found != 1)\n      DUNE_THROW(InvalidStateException,\n                 \"This should not happen!\\n\"\n                     << \"There were \" << found << \" local intersections which contain the coupling intersection, \"\n                     << \"and there must not be more than one!\");\n    // now the expected normal is local_intersection_normal\n    // and we would like coupling_intersection_normal to point in the same direction\n    // since they have unit length, they should be identical\n    if ((local_intersection_normal - coupling_intersection_normal).infinity_norm() > tolerance)\n      ++failures;\n  }\n  return failures;\n} // ... check_for_broken_coupling_intersections(...)\n\n\n// forward\ntemplate <class MacroGridType, class LocalGridType, Layers layer = Layers::level>\nclass GluedVTKWriter;\n\n\ntemplate <class MacroGridImp, class LocalGridImp, Layers layer = Layers::level>\nclass Glued\n{\n  template <class G, bool anything = true>\n  struct allowed_macro_grid\n  {\n    static const bool value = true;\n  };\n\n  template <class G, bool anything = true>\n  struct allowed_local_grid\n  {\n    static const bool value = true;\n  };\n\n#  if HAVE_DUNE_ALUGRID\n  template <class Comm, bool anything>\n  struct allowed_local_grid<ALUGrid<3, 3, simplex, conforming, Comm>, anything>\n  {\n    static const bool value = false;\n  };\n\n  template <class Comm, bool anything>\n  struct allowed_local_grid<ALUGrid<3, 3, cube, conforming, Comm>, anything>\n  {\n    static const bool value = false;\n  };\n#  endif // HAVE_DUNE_ALUGRID\n\n#  if HAVE_MPI && (HAVE_DUNE_UGGRID || HAVE_UG)\n  // UGGrid does not support multiple parallel instances in parallel and we have no means yet to create multiple\n  // sequential grids once MPI was found.\n  template <bool anything>\n  struct allowed_local_grid<UGGrid<2>, anything>\n  {\n    static const bool value = false;\n  };\n\n  template <bool anything>\n  struct allowed_local_grid<UGGrid<3>, anything>\n  {\n    static const bool value = false;\n  };\n#  endif\n\n  static_assert(allowed_macro_grid<MacroGridImp>::value,\n                \"This macro grid is known to fail, enable on your onw risk by disabling this check!\");\n  static_assert(allowed_local_grid<LocalGridImp>::value,\n                \"This local grid is known to fail, enable on your onw risk by disabling this check!\");\n\npublic:\n  typedef MacroGridImp MacroGridType;\n  typedef XT::Grid::GridProvider<MacroGridType> MacroGridProviderType;\n  typedef typename MacroGridProviderType::LeafGridViewType MacroGridViewType;\n  typedef typename MacroGridType::template Codim<0>::Entity MacroEntityType;\n\n  typedef LocalGridImp LocalGridType;\n  typedef XT::Grid::GridProvider<LocalGridType> LocalGridProviderType;\n  typedef typename LocalGridType::LevelGridView MicroGridViewType;\n  using MicroEntityType = XT::Grid::extract_entity_t<MicroGridViewType>;\n\n  typedef typename MacroGridType::ctype ctype;\n  static const size_t dimDomain = MacroGridType::dimension;\n  static const size_t dimWorld = MacroGridType::dimensionworld;\n\npublic:\n  typedef typename Layer<LocalGridType, layer, Backends::view>::type LocalViewType;\n\nprivate:\n  typedef GridGlue::Codim1Extractor<LocalViewType> LocalExtractorType;\n\npublic:\n  typedef GridGlue::GridGlue<LocalExtractorType, LocalExtractorType> GlueType;\n\nprivate:\n  template <class GridView, class MacroIntersectionType>\n  class CouplingFaceDescriptor\n  {\n    using LocalEntityType = XT::Grid::extract_entity_t<GridView>;\n    typedef typename GridView::ctype ctype;\n\n  public:\n    CouplingFaceDescriptor(const MacroIntersectionType& macro_intersection)\n      : macro_intersection_(macro_intersection)\n    {}\n\n    bool operator()(const LocalEntityType& element, unsigned int face) const\n    {\n      const auto local_intersection_ptr = element.template subEntity<1>(face);\n#  if DUNE_VERSION_GTE(DUNE_GRID, 2, 4)\n      const auto& local_intersection = local_intersection_ptr;\n#  else\n      const auto& local_intersection = *local_intersection_ptr;\n#  endif\n      const auto& local_intersection_geometry = local_intersection.geometry();\n      // Check if all corners of the local intersection lie within the macro intersection.\n      for (auto ii : XT::Common::value_range(local_intersection_geometry.corners()))\n        if (!XT::Grid::contains(macro_intersection_, local_intersection_geometry.corner(ii)))\n          return false;\n      return true;\n    } // ... contains(...)\n\n  private:\n    const MacroIntersectionType& macro_intersection_;\n  }; // CouplingFaceDescriptor\n\n  template <class GV, class MI>\n  static CouplingFaceDescriptor<GV, MI> create_descriptor(const GV& /*gv*/, const MI& mi)\n  {\n    return CouplingFaceDescriptor<GV, MI>(mi);\n  }\n\npublic:\n  Glued(MacroGridProviderType& macro_grid_provider,\n        const size_t num_local_refinements = 0,\n        const bool prepare_glues = false,\n        const bool allow_for_broken_orientation_of_coupling_intersections = false,\n        const ctype& allowed_overlap = 10 * XT::Common::FloatCmp::DefaultEpsilon<ctype>::value())\n    : macro_grid_(macro_grid_provider)\n    , allowed_overlap_(allowed_overlap)\n    , macro_leaf_view_(macro_grid_.leaf_view())\n    , macro_leaf_view_size_(macro_leaf_view_.indexSet().size(0))\n    , local_grids_(macro_leaf_view_.indexSet().size(0), nullptr)\n    , glues_(macro_leaf_view_.indexSet().size(0))\n  {\n    setup_local_grids();\n    if (num_local_refinements > 0)\n      for (auto& local_grid_provider : local_grids_) {\n        assert(local_grid_provider);\n        local_grid_provider->grid().globalRefine(boost::numeric_cast<int>(num_local_refinements));\n      }\n    if (prepare_glues)\n      setup_glues(allow_for_broken_orientation_of_coupling_intersections);\n  } // Glued(...)\n\n  const MacroGridViewType& macro_grid_view() const\n  {\n    assert_macro_grid_state();\n    return macro_leaf_view_;\n  }\n\n  size_t num_subdomains() const\n  {\n    assert_macro_grid_state();\n    return macro_leaf_view_size_;\n  }\n\n  size_t subdomain(const MacroEntityType& macro_entity) const\n  {\n    assert_macro_grid_state();\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return macro_leaf_view_.indexSet().index(macro_entity);\n  }\n\n  bool boundary(const MacroEntityType& macro_entity) const\n  {\n    assert_macro_grid_state();\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return macro_entity.hasBoundaryIntersections();\n  }\n\n  MicroGridViewType global_grid_view()\n  {\n    auto logger = XT::Common::TimedLogger().get(\"grid-multiscale.glued.global_grid_view\");\n    logger.warn() << \"Requiring inefficient access to global micro grid!\" << std::endl;\n    assert_macro_grid_state();\n    prepare_global_grid();\n    return global_grid_->level_view(global_grid_->grid().maxLevel());\n  }\n\n  const std::vector<std::vector<size_t>>& local_to_global_indices()\n  {\n    auto logger = XT::Common::TimedLogger().get(\"grid-multiscale.glued.local_to_global_indices\");\n    logger.warn() << \"Requiring inefficient access to global micro grid!\" << std::endl;\n    assert_macro_grid_state();\n    prepare_global_grid();\n    return *local_to_global_indices_;\n  }\n\n  MicroEntityType local_to_global_entity(const size_t subd, const MicroEntityType& local_entity)\n  {\n    return local_to_global_entity(\n        subd, extract_local_view<layer>()(*local_grids_[subd], max_local_level(subd)).indexSet().index(local_entity));\n  }\n\n  MicroEntityType local_to_global_entity(const size_t subd, const size_t local_entity_index)\n  {\n    auto logger = XT::Common::TimedLogger().get(\"grid-multiscale.glued.local_to_global_entity\");\n    logger.warn() << \"Requiring inefficient access to global micro grid!\" << std::endl;\n    assert_macro_grid_state();\n    prepare_global_grid();\n    const size_t global_index_of_local_entity = local_to_global_indices_->operator[](subd)[local_entity_index];\n    const auto global_micro_grid_view = global_grid_view();\n    const auto entity_it_end = global_micro_grid_view.template end<0>();\n    for (auto entity_it = global_micro_grid_view.template begin<0>(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      if (global_micro_grid_view.indexSet().index(entity) == global_index_of_local_entity)\n        return entity;\n    }\n    DUNE_THROW(XT::Common::Exceptions::wrong_input_given,\n               \"subdomain: \" << subd << \"\\n\"\n                             << \"local_entity_index: \" << local_entity_index << \"\\n\"\n                             << \"global_index_of_local_entity: \" << global_index_of_local_entity);\n    return *global_micro_grid_view.template begin<0>();\n  } // ... local_to_global_entity(...)\n\n  MicroEntityType global_to_local_entity(const MicroEntityType& micro_entity)\n  {\n    assert_macro_grid_state();\n    prepare_global_grid();\n    return global_to_local_entity(global_grid_view().indexSet().index(micro_entity));\n  }\n\n  MicroEntityType global_to_local_entity(const size_t micro_entity_index)\n  {\n    auto logger = XT::Common::TimedLogger().get(\"grid-multiscale.glued.global_to_local_entity\");\n    logger.warn() << \"Requiring inefficient access to global micro grid!\" << std::endl;\n    assert_macro_grid_state();\n    prepare_global_grid();\n    auto subdomain_and_local_entity_index = global_to_local_indices_->operator[](micro_entity_index);\n    const auto subd = subdomain_and_local_entity_index.first;\n    const auto local_index_of_global_entity = subdomain_and_local_entity_index.second;\n    const auto local_grid_view = extract_local_view<layer>()(*local_grids_[subd], max_local_level(subd));\n    const auto entity_it_end = local_grid_view.template end<0>();\n    for (auto entity_it = local_grid_view.template begin<0>(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      if (local_grid_view.indexSet().index(entity) == local_index_of_global_entity)\n        return entity;\n    }\n    DUNE_THROW(XT::Common::Exceptions::wrong_input_given,\n               \"micro_entity_index: \" << micro_entity_index\n                                      << \"\\n\"\n                                         \"subdomain: \"\n                                      << subd << \"\\n\"\n                                      << \"local_index_of_global_entity: \" << local_index_of_global_entity);\n    return *local_grid_view.template begin<0>();\n  } // ... global_to_local_entity(...)\n\n  const std::vector<std::pair<size_t, size_t>>& global_to_local_indices()\n  {\n    auto logger = XT::Common::TimedLogger().get(\"grid-multiscale.glued.global_to_local_indices\");\n    logger.warn() << \"Requiring inefficient access to global micro grid!\" << std::endl;\n    assert_macro_grid_state();\n    prepare_global_grid();\n    assert(global_to_local_indices_);\n    return *global_to_local_indices_;\n  }\n\n  const LocalGridProviderType& local_grid(const MacroEntityType& macro_entity) const\n  {\n    assert_macro_grid_state();\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return local_grid(macro_leaf_view_.indexSet().index(macro_entity));\n  }\n\n  LocalGridProviderType& local_grid(const MacroEntityType& macro_entity)\n  {\n    assert_macro_grid_state();\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    return local_grid(macro_leaf_view_.indexSet().index(macro_entity));\n  }\n\n  LocalGridProviderType& local_grid(const size_t macro_entity_index)\n  {\n    assert_macro_grid_state();\n    assert(macro_entity_index < macro_leaf_view_size_);\n    return *(local_grids_.at(macro_entity_index));\n  }\n\n  const LocalGridProviderType& local_grid(const size_t macro_entity_index) const\n  {\n    assert_macro_grid_state();\n    assert(macro_entity_index < macro_leaf_view_size_);\n    return *(local_grids_.at(macro_entity_index));\n  }\n\n  /**\n   * \\brief Returns (and creates, if it does not exist) the coupling glue between the local grid view of level\n   *        local_level_macro_entity on macro_entity and the local grid view of level local_level_macro_neighbor on\n   * macro_neighbor.\n   * \\note  Access is not implemented efficiently. This could be improved by using std::map::find instead of\n   *        std::map::operator[].\n   */\n  const GlueType& coupling(const MacroEntityType& macro_entity,\n                           const int local_level_macro_entity,\n                           const MacroEntityType& macro_neighbor,\n                           const int local_level_macro_neighbor,\n                           const bool allow_for_broken_orientation_of_coupling_intersections = false)\n  {\n    assert_macro_grid_state();\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    assert(macro_index_set.contains(macro_entity));\n    assert(macro_index_set.contains(macro_neighbor));\n    if (local_level_macro_entity > max_local_level(macro_entity))\n      DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong,\n                 \"max_local_level(macro_entity): \" << max_local_level(macro_entity) << \"\\n\"\n                                                   << \"   local_level_macro_entity:      \" << local_level_macro_entity);\n    if (local_level_macro_neighbor > max_local_level(macro_neighbor))\n      DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong,\n                 \"max_local_level(macro_neighbor): \" << max_local_level(macro_neighbor) << \"\\n\"\n                                                     << \"   local_level_macro_neighbor:      \"\n                                                     << local_level_macro_neighbor);\n    int local_entity_grid_level = local_level_macro_entity;\n    int local_neighbor_grid_level = local_level_macro_neighbor;\n    // in case of local level views, the local_level_macro... have to be non-negative\n    if (layer == Layers::level) {\n      if (local_level_macro_entity < 0)\n        DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong,\n                   \"local_level_macro_entity has to be non-negative (is \" << local_level_macro_entity << \")!\");\n      if (local_level_macro_neighbor < 0)\n        DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong,\n                   \"local_level_macro_neighbor has to be non-negative (is \" << local_level_macro_neighbor << \")!\");\n    } else if (layer == Layers::leaf) {\n      // in case of local leaf views, it has to be -1\n      if (local_level_macro_entity != -1)\n        DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong,\n                   \"local_level_macro_entity has to be -1 (is \" << local_level_macro_entity << \")!\");\n      if (local_level_macro_neighbor != -1)\n        DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong,\n                   \"local_level_macro_neighbor has to be -1 (is \" << local_level_macro_neighbor << \")!\");\n      // since the local leaf views may have been adapted, we use their respective sizes as keys for the glue map\n      local_entity_grid_level *= local_grid(macro_entity).leaf_view().indexSet().size(0);\n      local_neighbor_grid_level *= local_grid(macro_neighbor).leaf_view().indexSet().size(0);\n    }\n    const auto entity_index = macro_index_set.index(macro_entity);\n    const auto neighbor_index = macro_index_set.index(macro_neighbor);\n    auto& glues_for_this_entity_neighbor = glues_[entity_index][neighbor_index];\n    if (glues_for_this_entity_neighbor[local_entity_grid_level][local_neighbor_grid_level] == nullptr) {\n      if (layer == Layers::leaf) {\n        // if the glue for the current leaf sizes does not exist, but for other leaf sizes, then those are not valid any\n        // more and we can get rid of them\n        if (glues_for_this_entity_neighbor.size() > 0)\n          glues_for_this_entity_neighbor.clear();\n      }\n      // find the corresponding macro intersection ...\n      const auto macro_intersection_it_end = macro_leaf_view_.iend(macro_entity);\n      for (auto macro_intersection_it = macro_leaf_view_.ibegin(macro_entity);\n           macro_intersection_it != macro_intersection_it_end;\n           ++macro_intersection_it) {\n        const auto& macro_intersection = *macro_intersection_it;\n        if (macro_intersection.neighbor() && !macro_intersection.boundary()) {\n          const auto real_neighbor_ptr = macro_intersection.outside();\n#  if DUNE_VERSION_GTE(DUNE_GRID, 2, 4)\n          const auto& real_neighbor = real_neighbor_ptr;\n#  else\n          const auto& real_neighbor = *real_neighbor_ptr;\n#  endif\n          if (macro_index_set.index(real_neighbor) == neighbor_index)\n            glues_for_this_entity_neighbor[local_entity_grid_level][local_neighbor_grid_level] =\n                create_glue(macro_entity,\n                            macro_neighbor,\n                            macro_intersection,\n                            (layer == Layers::level) ? local_entity_grid_level : -1,\n                            (layer == Layers::level) ? local_neighbor_grid_level : -1);\n        }\n      } // ... find the corresponding macro intersection\n    }\n\n    const auto& glue = *(glues_for_this_entity_neighbor[local_entity_grid_level][local_neighbor_grid_level]);\n    if (!allow_for_broken_orientation_of_coupling_intersections) {\n      const size_t brocken_intersections = check_for_broken_coupling_intersections(glue);\n      if (brocken_intersections > 0)\n        DUNE_THROW(Exceptions::intersection_orientation_is_broken,\n                   \"The coupling glue between the grid views of\\n\"\n                       << \"     level \" << local_entity_grid_level << \" on macro entity   \"\n                       << macro_leaf_view_.indexSet().index(macro_entity) << \" and\\n\"\n                       << \"     level \" << local_neighbor_grid_level << \" on macro neighbor \"\n                       << macro_leaf_view_.indexSet().index(macro_neighbor) << \"\\n\"\n                       << \"   contains\\n\"\n                       << \"     \" << brocken_intersections << \"/\" << glue.size()\n                       << \" intersections with wrong orientation!\");\n    }\n    return glue;\n  } // ... coupling(...)\n\n  const GlueType& coupling(const MacroEntityType& macro_entity,\n                           const MacroEntityType& macro_neighbor,\n                           const bool allow_for_broken_orientation_of_coupling_intersections = false)\n  {\n    return coupling(macro_entity,\n                    max_local_level(macro_entity),\n                    macro_neighbor,\n                    max_local_level(macro_neighbor),\n                    allow_for_broken_orientation_of_coupling_intersections);\n  }\n\n  int max_local_level(const MacroEntityType& macro_entity) const\n  {\n    assert_macro_grid_state();\n    if (layer == Layers::leaf)\n      return -1;\n    else\n      return local_grid(macro_entity).grid().maxLevel();\n  }\n\n  int max_local_level(const size_t macro_entity_index) const\n  {\n    assert_macro_grid_state();\n    if (layer == Layers::leaf)\n      return -1;\n    else\n      return local_grid(macro_entity_index).grid().maxLevel();\n  }\n\n  const std::vector<std::pair<MicroEntityType, std::vector<int>>>&\n  local_boundary_entities(const MacroEntityType& macro_entity, const int local_level)\n  {\n    assert_macro_grid_state();\n    assert(macro_leaf_view_.indexSet().contains(macro_entity));\n    const size_t macro_entity_index = macro_leaf_view_.indexSet().index(macro_entity);\n    if (local_level > max_local_level(macro_entity))\n      DUNE_THROW(XT::Common::Exceptions::you_are_using_this_wrong,\n                 \"macro_entity_index: \" << macro_entity_index << \"\\n\"\n                                        << \"local_level: \" << local_level << \"\\n\"\n                                        << \"max_local_level(macro_entity): \" << max_local_level(macro_entity));\n    auto& local_level_to_boundary_entity_ptrs_with_local_intersections =\n        macro_entity_to_local_level_to_boundary_entity_ptrs_with_local_intersections_[macro_entity_index];\n    auto& boundary_entity_ptrs_with_local_intersections =\n        local_level_to_boundary_entity_ptrs_with_local_intersections[local_level];\n    //    logger.debug() << \"macro_entity: \" << macro_entity_index << std::endl;\n    if (boundary(macro_entity) && boundary_entity_ptrs_with_local_intersections.empty()) {\n      // create the container, therefore\n      const auto local_leaf_view = local_grids_[macro_entity_index]->leaf_view();\n      // * walk the local grid (manually, to have access to the entity pointer)\n      const auto local_entity_it_end = local_leaf_view.template end<0>();\n      for (auto local_entity_it = local_leaf_view.template begin<0>(); local_entity_it != local_entity_it_end;\n           ++local_entity_it) {\n        const auto& local_entity = *local_entity_it;\n        //        logger.debug() << \"local_entity: \" << local_leaf_view.indexSet().index(local_entity) << \" \";\n        if (local_entity.hasBoundaryIntersections()) {\n          //          logger.debug() << \"(boundary entity)\" << std::endl;\n          std::vector<int> local_boundary_intersections;\n          // This entity has intersections on the local grid boundary, those could either be the domain boundary (which\n          // we are looking for) or a boundary to another local grid (which we are not looking for). To find out\n          // * walk the intersections\n          for (auto&& local_intersection : intersections(local_leaf_view, local_entity)) {\n            if (local_intersection.boundary() && !local_intersection.neighbor()) {\n              //              logger.debug() << \"local_intersection: \" << local_intersection.indexInInside() << \":\" <<\n              //              std::endl;\n              const auto local_intersection_geometry = local_intersection.geometry();\n              const size_t num_corners = boost::numeric_cast<size_t>(local_intersection_geometry.corners());\n              // ** Check if all corners of the intersection lie on the domain boundary (aka the boundary intersection\n              // of\n              //    the macro entity this local grid belongs to. Therefore\n              //    *** walk the intersections of the macro entity\n              for (auto&& macro_intersection : intersections(macro_leaf_view_, macro_entity)) {\n                if (macro_intersection.boundary() && !macro_intersection.neighbor()) {\n                  // This macro intersection lies on the domain boundary, check if the local intersection is contained.\n                  size_t corners_lie_on_boundary = 0;\n                  for (size_t ii = 0; ii < num_corners; ++ii) {\n                    if (XT::Grid::contains(macro_intersection,\n                                           local_intersection_geometry.corner(boost::numeric_cast<int>(ii))))\n                      ++corners_lie_on_boundary;\n                  }\n                  if (corners_lie_on_boundary == num_corners) {\n                    // add the information to the container\n                    local_boundary_intersections.push_back(local_intersection.indexInInside());\n                  } // add the information to the container\n                }\n              } //    *** walk the intersections of the macro entity\n            }\n          } // * walk the intersections\n          if (!local_boundary_intersections.empty()) {\n            // add this local entity and its local intersections to the container\n            boundary_entity_ptrs_with_local_intersections.emplace_back(local_entity, local_boundary_intersections);\n          }\n        } /*else\n          logger.debug() << \"(inner entity)\" << std::endl;*/\n      } // * walk the local grid\n    } // create the container\n    return boundary_entity_ptrs_with_local_intersections;\n  } // ... local_boundary_entities(...)\n\n  template <class... Args>\n  void visualize(const std::string& filename = \"grid.multiscale.glued\", Args&&... args)\n  {\n    assert_macro_grid_state();\n    auto logger = XT::Common::TimedLogger().get(\"grid-multiscale.glued.visualize\");\n    macro_grid_.visualize(filename + \".macro\", std::forward<Args>(args)...);\n    GluedVTKWriter<MacroGridType, LocalGridType, layer> vtk_writer(*this);\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    std::vector<std::vector<double>> subdomain_visualization(macro_index_set.size(0));\n    std::vector<std::vector<double>> boundary_visualization(macro_index_set.size(0));\n    std::vector<std::vector<double>> inside_outside_coupling_visualization(macro_index_set.size(0));\n    std::vector<std::vector<double>> outside_inside_coupling_visualization(macro_index_set.size(0));\n    // walk the macro grid\n    for (auto&& macro_entity : elements(macro_leaf_view_)) {\n      const size_t macro_entity_index = macro_index_set.index(macro_entity);\n      logger.debug() << \"macro_entity: \" << macro_entity_index << \" \";\n      const auto local_level = max_local_level(macro_entity);\n      const auto local_grid_view = extract_local_view<layer>()(*local_grids_[macro_entity_index], local_level);\n      subdomain_visualization[macro_entity_index] =\n          std::vector<double>(local_grid_view.indexSet().size(0), macro_entity_index);\n      boundary_visualization[macro_entity_index] = std::vector<double>(local_grid_view.indexSet().size(0), -1);\n      if (inside_outside_coupling_visualization[macro_entity_index].empty())\n        inside_outside_coupling_visualization[macro_entity_index] =\n            std::vector<double>(local_grid_view.indexSet().size(0), -1);\n      if (outside_inside_coupling_visualization[macro_entity_index].empty())\n        outside_inside_coupling_visualization[macro_entity_index] =\n            std::vector<double>(local_grid_view.indexSet().size(0), -1);\n      // local boundary entities\n      if (boundary(macro_entity)) {\n        logger.debug() << \"(boundary entity)\" << std::endl;\n        const auto& boundary_entities_with_local_intersections = local_boundary_entities(macro_entity, local_level);\n        logger.debug() << \"  \" << boundary_entities_with_local_intersections.size() << \"/\"\n                       << local_grid_view.indexSet().size(0) << \" boundary entities\" << std::endl;\n        for (const auto& element : boundary_entities_with_local_intersections) {\n          const auto& local_entity = element.first;\n          const auto& local_intersections = element.second;\n          if (!local_intersections.empty()) {\n            const size_t local_entity_index = local_grid_view.indexSet().index(local_entity);\n            boundary_visualization[macro_entity_index][local_entity_index] = macro_entity_index;\n          }\n        }\n      } else\n        logger.debug() << \"(inner entity)\" << std::endl;\n      for (auto&& macro_intersection : intersections(macro_leaf_view_, macro_entity)) {\n        if (!macro_intersection.boundary() && macro_intersection.neighbor()) {\n          const auto macro_neighbor_ptr = macro_intersection.outside();\n#  if DUNE_VERSION_GTE(DUNE_GRID, 2, 4)\n          const auto& macro_neighbor = macro_neighbor_ptr;\n#  else\n          const auto& macro_neighbor = *macro_neighbor_ptr;\n#  endif\n          const size_t macro_neighbor_index = macro_leaf_view_.indexSet().index(macro_neighbor);\n          const auto local_neighbor_level = max_local_level(macro_neighbor);\n          const auto local_neighbor_grid_view =\n              extract_local_view<layer>()(*local_grids_[macro_neighbor_index], local_neighbor_level);\n          if (inside_outside_coupling_visualization[macro_neighbor_index].empty())\n            inside_outside_coupling_visualization[macro_neighbor_index] =\n                std::vector<double>(local_neighbor_grid_view.indexSet().size(0), -1);\n          if (outside_inside_coupling_visualization[macro_neighbor_index].empty())\n            outside_inside_coupling_visualization[macro_neighbor_index] =\n                std::vector<double>(local_neighbor_grid_view.indexSet().size(0), -1);\n          // walk the coupling, where this is the inside\n          size_t num_coupling_intersections = 0;\n          const auto& in_out_coupling_glue = coupling(macro_entity,\n                                                      local_level,\n                                                      macro_neighbor,\n                                                      local_neighbor_level,\n                                                      /*allow_for_broken_orientation_of_coupling_intersections=*/true);\n          const auto in_out_coupling_intersection_it_end = in_out_coupling_glue.template iend<0>();\n          for (auto in_out_coupling_intersection_it = in_out_coupling_glue.template ibegin<0>();\n               in_out_coupling_intersection_it != in_out_coupling_intersection_it_end;\n               ++in_out_coupling_intersection_it) {\n            ++num_coupling_intersections;\n            const auto& coupling_intersection = *in_out_coupling_intersection_it;\n            const auto local_entity = coupling_intersection.inside();\n            const size_t local_entity_index = local_grid_view.indexSet().index(local_entity);\n            inside_outside_coupling_visualization[macro_entity_index][local_entity_index] = macro_entity_index;\n            const auto local_neighbor = coupling_intersection.outside();\n            const size_t local_neighbor_index = local_neighbor_grid_view.indexSet().index(local_neighbor);\n            inside_outside_coupling_visualization[macro_neighbor_index][local_neighbor_index] = macro_neighbor_index;\n          }\n          // walk the coupling, where this is the outside\n          size_t out_in_num_coupling_intersections = 0;\n          const auto& out_in_coupling_glue = coupling(macro_neighbor,\n                                                      local_neighbor_level,\n                                                      macro_entity,\n                                                      local_level,\n                                                      /*allow_for_broken_orientation_of_coupling_intersections=*/true);\n          const auto out_in_coupling_intersection_it_end = out_in_coupling_glue.template iend<0>();\n          for (auto out_in_coupling_intersection_it = out_in_coupling_glue.template ibegin<0>();\n               out_in_coupling_intersection_it != out_in_coupling_intersection_it_end;\n               ++out_in_coupling_intersection_it) {\n            ++out_in_num_coupling_intersections;\n            const auto& coupling_intersection = *out_in_coupling_intersection_it;\n            const auto local_entity = coupling_intersection.inside();\n            const size_t local_entity_index = local_grid_view.indexSet().index(local_entity);\n            outside_inside_coupling_visualization[macro_neighbor_index][local_entity_index] = macro_neighbor_index;\n            const auto local_neighbor = coupling_intersection.outside();\n            const size_t local_neighbor_index = local_neighbor_grid_view.indexSet().index(local_neighbor);\n            outside_inside_coupling_visualization[macro_entity_index][local_neighbor_index] = macro_entity_index;\n          }\n          if (num_coupling_intersections != out_in_num_coupling_intersections)\n            DUNE_THROW(XT::Common::Exceptions::internal_error,\n                       \"The coupling glue is broken!\\n\"\n                           << \"macro entity (local level):   \" << macro_entity_index << \" (\" << local_level << \")\\n\"\n                           << \"macro neighbor (local level): \" << macro_neighbor_index << \" (\" << local_neighbor_level\n                           << \")\");\n          logger.debug() << \"  \" << num_coupling_intersections << \" coupling intersections with neighbor \"\n                         << macro_neighbor_index << std::endl;\n        }\n      }\n    } // walk the macro grid\n    vtk_writer.addCellData(subdomain_visualization, \"subdomains\");\n    vtk_writer.addCellData(boundary_visualization, \"local boundary entities\");\n    vtk_writer.addCellData(inside_outside_coupling_visualization, \"local coupling entities (inside/outside)\");\n    vtk_writer.addCellData(outside_inside_coupling_visualization, \"local coupling entities (outside/inside)\");\n    vtk_writer.write(filename, VTK::appendedraw);\n  } // ... visualize(...)\n\nprivate:\n  template <class MacroEntityType>\n  static std::shared_ptr<LocalGridProviderType> create_grid_of_simplex(const MacroEntityType& macro_entity)\n  {\n    try {\n      GridFactory<LocalGridType> subdomain_factory;\n      const auto num_vertices = macro_entity.subEntities(dimDomain);\n      std::vector<unsigned int> vertex_ids(num_vertices, 0);\n      for (auto&& local_vertex_id : XT::Common::value_range(num_vertices)) {\n        const auto vertex = macro_entity.template subEntity<dimDomain>(local_vertex_id).geometry().center();\n        subdomain_factory.insertVertex(vertex);\n        vertex_ids[local_vertex_id] = local_vertex_id;\n      }\n      subdomain_factory.insertElement(macro_entity.geometry().type(), vertex_ids);\n      return std::make_shared<XT::Grid::GridProvider<LocalGridType>>(subdomain_factory.createGrid());\n    } catch (GridError& ee) {\n      DUNE_THROW(GridError,\n                 \"It was not possible to create a grid for this simplex with the given GridType!\\n\\n\"\n                     << \"GridType: \" << XT::Common::Typename<LocalGridType>::value() << \"\\n\\n\"\n                     << \"This was the original error: \" << ee.what());\n    }\n  } // ... create_grid_of_simplex(...)\n\n  template <class MacroEntityType>\n  static std::shared_ptr<LocalGridProviderType> create_grid_of_cube(const MacroEntityType& macro_entity)\n  {\n    const auto num_vertices = macro_entity.subEntities(dimDomain);\n    FieldVector<ctype, dimDomain> lower_left(std::numeric_limits<ctype>::max());\n    FieldVector<ctype, dimDomain> upper_right(std::numeric_limits<ctype>::min());\n    for (auto&& local_vertex_id : XT::Common::value_range(num_vertices)) {\n      const auto vertex = macro_entity.template subEntity<dimDomain>(local_vertex_id).geometry().center();\n      for (size_t dd = 0; dd < dimDomain; ++dd) {\n        lower_left[dd] = std::min(lower_left[dd], vertex[dd]);\n        upper_right[dd] = std::max(upper_right[dd], vertex[dd]);\n      }\n    }\n    std::array<unsigned int, dimDomain> num_elements;\n    std::fill(num_elements.begin(), num_elements.end(), 1);\n    return std::make_shared<XT::Grid::GridProvider<LocalGridType>>(\n        XT::Grid::make_cube_grid<LocalGridType>(lower_left, upper_right, num_elements));\n  } // ... create_grid_of_cube(...)\n\n  void setup_local_grids()\n  {\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    for (auto&& macro_entity : elements(macro_leaf_view_)) {\n      auto macro_entity_index = macro_index_set.index(macro_entity);\n      if (macro_entity.type().isSimplex())\n        local_grids_[macro_entity_index] = create_grid_of_simplex(macro_entity);\n      else if (macro_entity.type().isCube())\n        local_grids_[macro_entity_index] = create_grid_of_cube(macro_entity);\n      else\n        DUNE_THROW(GridError, \"Unknown entity.type() encountered: \" << macro_entity.type());\n    }\n  } // ... setup_local_grids()\n\n  template <Layers l, bool anything = true>\n  struct extract_local_view\n  {\n    template <class G>\n    auto operator()(G& g, int /*lv*/) -> decltype(g.leaf_view())\n    {\n      return g.leaf_view();\n    }\n  };\n\n  template <bool anything>\n  struct extract_local_view<Layers::level, anything>\n  {\n    template <class G>\n    auto operator()(G& g, int lv) -> decltype(g.level_view(lv))\n    {\n      return g.level_view(lv);\n    }\n  };\n\n  template <class MacroIntersectionType>\n  std::shared_ptr<GlueType> create_glue(const MacroEntityType& macro_entity,\n                                        const MacroEntityType& macro_neighbor,\n                                        const MacroIntersectionType& macro_intersection,\n                                        const int local_entity_level,\n                                        const int local_neighbor_level) const\n  {\n    assert(local_entity_level >= -1);\n    assert(local_neighbor_level >= -1);\n    assert(local_entity_level <= max_local_level(macro_entity));\n    assert(local_neighbor_level <= max_local_level(macro_neighbor));\n    const auto& local_entity_grid = local_grid(macro_entity);\n    const auto& local_neighbor_grid = local_grid(macro_neighbor);\n    auto local_entity_view = extract_local_view<layer>()(local_entity_grid, local_entity_level);\n    auto local_neighbor_view = extract_local_view<layer>()(local_neighbor_grid, local_neighbor_level);\n    // create descriptors, these can be discarded after creating the extractors\n    auto entity_descriptor = create_descriptor(local_entity_view, macro_intersection);\n    auto neighbor_descriptor = create_descriptor(local_neighbor_view, macro_intersection);\n    // create extractors and merger as shared_ptr, so glue will handle memory\n    auto entity_extractor = std::make_shared<LocalExtractorType>(local_entity_view, entity_descriptor);\n    auto neighbor_extractor = std::make_shared<LocalExtractorType>(local_neighbor_view, neighbor_descriptor);\n    auto contact_merger = std::make_shared<GridGlue::ContactMerge<dimWorld, ctype>>(allowed_overlap_);\n    // create glue\n    auto glue = std::make_shared<GlueType>(entity_extractor, neighbor_extractor, contact_merger);\n    glue->build();\n    if (glue->size() == 0)\n      DUNE_THROW(GridError,\n                 \"Something went wrong, the coupling glue is empty!\\n\"\n                     << \"   macro_entity \" << macro_leaf_view_.indexSet().index(macro_entity) << \"\\n\"\n                     << \"   local_entity_level \" << local_entity_level << \"\\n\"\n                     << \"   macro_neighbor \" << macro_leaf_view_.indexSet().index(macro_neighbor) << \"\\n\"\n                     << \"   local_neighbor_level \" << local_neighbor_level << \"\\n\");\n    return glue;\n  } // ... create_glue(...)\n\n  void setup_glues(const bool allow_for_broken_orientation_of_coupling_intersections = false)\n  {\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    for (auto&& macro_entity : elements(macro_leaf_view_)) {\n      const auto macro_entity_index = macro_index_set.index(macro_entity);\n      auto& entity_glues = glues_[macro_entity_index];\n      // walk the neighbors ...\n      const auto macro_intersection_it_end = macro_leaf_view_.iend(macro_entity);\n      for (auto macro_intersection_it = macro_leaf_view_.ibegin(macro_entity);\n           macro_intersection_it != macro_intersection_it_end;\n           ++macro_intersection_it) {\n        const auto& macro_intersection = *macro_intersection_it;\n        if (macro_intersection.neighbor() && !macro_intersection.boundary()) {\n          const auto macro_neighbor_ptr = macro_intersection.outside();\n#  if DUNE_VERSION_GTE(DUNE_GRID, 2, 4)\n          const auto& macro_neighbor = macro_neighbor_ptr;\n#  else\n          const auto& macro_neighbor = *macro_neighbor_ptr;\n#  endif\n          const auto macro_neighbor_index = macro_index_set.index(macro_neighbor);\n          for (auto local_entity_level :\n               XT::Common::value_range(local_grids_[macro_entity_index]->grid().maxLevel() + 1))\n            for (auto local_neighbor_level :\n                 XT::Common::value_range(local_grids_[macro_neighbor_index]->grid().maxLevel() + 1)) {\n              auto glue = create_glue(\n                  macro_entity, macro_neighbor, macro_intersection, local_entity_level, local_neighbor_level);\n              if (!allow_for_broken_orientation_of_coupling_intersections) {\n                const size_t brocken_intersections = check_for_broken_coupling_intersections(*glue);\n                if (brocken_intersections > 0)\n                  DUNE_THROW(Exceptions::intersection_orientation_is_broken,\n                             \"The coupling glue between the grid views of\\n\"\n                                 << \"  level \" << local_entity_level << \" on macro entity   \"\n                                 << macro_leaf_view_.indexSet().index(macro_entity) << \" and\\n\"\n                                 << \"  level \" << local_neighbor_level << \" on macro neighbor \"\n                                 << macro_leaf_view_.indexSet().index(macro_neighbor) << \"\\n\"\n                                 << \"contains\\n\"\n                                 << \"  \" << brocken_intersections << \"/\" << glue->size() << \" intersections with wrong\"\n                                 << \"orientation!\");\n              }\n              entity_glues[macro_neighbor_index][local_entity_level][local_neighbor_level] = glue;\n            }\n        }\n      } // ... walk the neighbors\n    }\n  } // ... setup_glues(...)\n\n  void prepare_global_grid()\n  {\n    if (global_grid_)\n      return;\n    const auto& macro_index_set = macro_leaf_view_.indexSet();\n    std::vector<FieldVector<ctype, dimDomain>> vertices;\n    std::vector<std::vector<std::vector<unsigned int>>> entity_to_vertex_ids(local_grids_.size());\n    std::vector<std::vector<GeometryType>> geometry_types(local_grids_.size());\n    // walk the grid for the first time\n    for (auto&& macro_entity : elements(macro_leaf_view_)) {\n      const auto local_leaf_view = local_grid(macro_entity).leaf_view();\n      const auto& local_index_set = local_leaf_view.indexSet();\n      const size_t macro_index = macro_index_set.index(macro_entity);\n      entity_to_vertex_ids[macro_index] = std::vector<std::vector<unsigned int>>(local_index_set.size(0));\n      geometry_types[macro_index] = std::vector<GeometryType>(local_index_set.size(0));\n      for (auto&& micro_entity : elements(local_leaf_view)) {\n        const size_t micro_index = local_index_set.index(micro_entity);\n        const auto num_vertices = micro_entity.\n#  if DUNE_VERSION_GTE(DUNE_GRID, 2, 4)\n\n                                  subEntities(dimDomain);\n#  else\n                                  template count<dimDomain>();\n#  endif\n        entity_to_vertex_ids[macro_index][micro_index] = std::vector<unsigned int>(num_vertices);\n        geometry_types[macro_index][micro_index] = micro_entity.geometry().type();\n        for (unsigned int local_vertex_id = 0; local_vertex_id < num_vertices; ++local_vertex_id) {\n          const unsigned int global_vertex_id = find_insert_vertex(vertices,\n                                                                   micro_entity\n                                                                       .template subEntity<dimDomain>(local_vertex_id)\n#  if DUNE_VERSION_GTE(DUNE_GRID, 2, 4)\n                                                                       .\n#  else\n                                                                       ->\n#  endif\n                                                                   geometry()\n                                                                       .center());\n          entity_to_vertex_ids[macro_index][micro_index][local_vertex_id] = global_vertex_id;\n        }\n      } // walk the local grid\n    } // walk the macro grid\n    GridFactory<LocalGridType> global_factory;\n    for (const auto& vertex : vertices)\n      global_factory.insertVertex(vertex);\n    size_t II = 0;\n    size_t JJ = 0;\n    try {\n      for (size_t ii = 0; ii < local_grids_.size(); ++ii, II = ii)\n        for (size_t jj = 0; jj < entity_to_vertex_ids[ii].size(); ++jj, JJ = jj)\n          global_factory.insertElement(geometry_types[ii][jj], entity_to_vertex_ids[ii][jj]);\n    } catch (GridError& ee) {\n      DUNE_THROW(GridError,\n                 \"It was not possible to insert an element into the grid factory!\\n\\n\"\n                     << \"GridType: \" << XT::Common::Typename<LocalGridType>::value() << \"\\n\"\n                     << \"GeometryType: \" << geometry_types[II][JJ] << \"\\n\"\n                     << \"\\n\"\n                     << \"This was the original error: \" << ee.what());\n    } // try\n    global_grid_ = std::make_unique<XT::Grid::GridProvider<LocalGridType>>(global_factory.createGrid());\n\n    // build maps of indices, relating the local to the global grid\n    const auto global_view = global_grid_->leaf_view();\n    local_to_global_indices_ = std::make_unique<std::vector<std::vector<size_t>>>(macro_leaf_view_.indexSet().size(0));\n    auto& local_to_global_inds = *local_to_global_indices_;\n    global_to_local_indices_ = std::make_unique<std::vector<std::pair<size_t, size_t>>>(global_view.indexSet().size(0));\n    auto& global_to_local_inds = *global_to_local_indices_;\n    // therefore\n    // * create a search on the global view: if all is fine, we only need to walk that one once\n    std::vector<FieldVector<ctype, dimDomain>> local_entity_center{FieldVector<ctype, dimDomain>(0.0)};\n    auto global_search = XT::Grid::make_entity_in_level_search(global_view);\n    // * walk the macro grid\n    for (auto&& macro_entity : elements(macro_leaf_view_)) {\n      const size_t subd = macro_leaf_view_.indexSet().index(macro_entity);\n      const auto local_leaf_view = local_grid(macro_entity).leaf_view();\n      const auto& local_index_set = local_leaf_view.indexSet();\n      local_to_global_inds[subd] = std::vector<size_t>(local_index_set.size(0));\n      // * walk the local grid\n      for (auto&& local_entity : elements(local_leaf_view)) {\n        const size_t local_entity_index = local_index_set.index(local_entity);\n        local_entity_center[0] = local_entity.geometry().center();\n        const auto global_entity_ptr_unique_ptrs = global_search(local_entity_center);\n        // the search has to be successfull, since the global grid has been constructed to exactly contain each local\n        // entity\n        assert(global_entity_ptr_unique_ptrs.size() == 1);\n        const auto& global_entity_ptr_unique_ptr = global_entity_ptr_unique_ptrs.at(0);\n        assert(global_entity_ptr_unique_ptr);\n        const auto& global_entity_ptr = *global_entity_ptr_unique_ptr;\n        const auto& global_entity = *global_entity_ptr;\n        const size_t global_entity_index = global_view.indexSet().index(global_entity);\n        // store information\n        local_to_global_inds[subd][local_entity_index] = global_entity_index;\n        global_to_local_inds[global_entity_index] = {subd, local_entity_index};\n      } // * walk the local grid\n    } // * walk the macro grid\n  } // ... prepare_global_grid(...)\n\n  size_t find_insert_vertex(std::vector<FieldVector<ctype, dimDomain>>& vertices,\n                            FieldVector<ctype, dimDomain>&& vertex) const\n  {\n    // check if vertex is already contained\n    for (size_t ii = 0; ii < vertices.size(); ++ii)\n      if (XT::Common::FloatCmp::eq(vertex, vertices[ii]))\n        return ii;\n    // if not, add it\n    vertices.emplace_back(std::move(vertex));\n    return vertices.size() - 1;\n  } // ... find_insert_vertex(...)\n\n  void assert_macro_grid_state() const\n  {\n    if (macro_leaf_view_.indexSet().size(0) != macro_leaf_view_size_)\n      DUNE_THROW(InvalidStateException,\n                 \"The size of the macro leaf grid view has changed (from \"\n                     << macro_leaf_view_size_ << \" to \" << macro_leaf_view_.indexSet().size(0)\n                     << \"), which invalidates this object!\\n\"\n                     << \"Do not adapt the macro grid after instantiating this object!\");\n  } // void assert_macro_grid_state()\n\n  MacroGridProviderType& macro_grid_;\n  const ctype allowed_overlap_;\n  MacroGridViewType macro_leaf_view_;\n  const size_t macro_leaf_view_size_;\n  std::vector<std::shared_ptr<LocalGridProviderType>> local_grids_;\n  std::vector<std::map<size_t, std::map<int, std::map<int, std::shared_ptr<GlueType>>>>> glues_;\n  std::map<size_t, std::map<int, std::vector<std::pair<MicroEntityType, std::vector<int>>>>>\n      macro_entity_to_local_level_to_boundary_entity_ptrs_with_local_intersections_;\n  std::unique_ptr<LocalGridProviderType> global_grid_;\n  std::unique_ptr<std::vector<std::vector<size_t>>> local_to_global_indices_;\n  std::unique_ptr<std::vector<std::pair<size_t, size_t>>> global_to_local_indices_;\n}; // class Glued\n\n\ntemplate <class MacroGridType, class LocalGridType, Layers layer>\nclass GluedVTKWriter\n{\n  typedef typename Layer<LocalGridType, layer, Backends::view>::type LocalGridViewType;\n\n  // we only need this class to access a protected pwrite method of VTKWriter\n  class LocalVTKWriter : public VTKWriter<LocalGridViewType>\n  {\n    typedef VTKWriter<LocalGridViewType> BaseType;\n\n  public:\n    LocalVTKWriter(const LocalGridViewType& local_grid_view, const size_t subdomain, const size_t num_subdomains)\n      : BaseType(local_grid_view)\n      , commRank_(boost::numeric_cast<int>(subdomain))\n      , commSize_(boost::numeric_cast<int>(num_subdomains))\n    {}\n\n    void write_locally(const std::string& name, VTK::OutputType ot)\n    {\n      BaseType::pwrite(name, \"\", \"\", ot, commRank_, commSize_);\n    }\n\n  private:\n    const int commRank_;\n    const int commSize_;\n  }; // class LocalVTKWriter\n\npublic:\n  typedef Glued<MacroGridType, LocalGridType, layer> GluedGridType;\n\n  GluedVTKWriter(const GluedGridType& glued_grid, const int local_level = -1)\n    : glued_grid_(glued_grid)\n    , local_levels_(glued_grid_.num_subdomains(), -1)\n  {\n    // set each local level to its respective max\n    if (local_level < 0)\n      for (auto&& macro_entity : elements(glued_grid_.macro_grid_view()))\n        local_levels_[glued_grid_.subdomain(macro_entity)] = glued_grid_.max_local_level(macro_entity);\n    prepare_local_vtk_writers();\n  } // GluedVTKWriter(...)\n\n  GluedVTKWriter(const GluedGridType& glued_grid, const std::vector<int>& local_levels)\n    : glued_grid_(glued_grid)\n    , local_levels_(local_levels)\n  {\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      if (local_levels_[ss] < 0)\n        local_levels_[ss] = glued_grid_.max_local_level(ss);\n    prepare_local_vtk_writers();\n  }\n\n  template <class V>\n  void addCellData(const size_t subdomain, const std::vector<V>& vector, const std::string& name, const int ncomps = 1)\n  {\n    DUNE_THROW_IF(subdomain > glued_grid_.num_subdomains(),\n                  Common::Exceptions::index_out_of_range,\n                  \"subdomain = \" << subdomain\n                                 << \"\\n   glued_grid_.num_subdomains() = \" << glued_grid_.num_subdomains());\n    local_vtk_writers_[subdomain]->addCellData(vector, name, ncomps);\n  } // ... addCellData(...)\n\n  template <class V>\n  void addCellData(const std::vector<std::vector<V>>& vectors, const std::string& name, const int ncomps = 1)\n  {\n    DUNE_THROW_IF(vectors.size() != glued_grid_.num_subdomains(),\n                  Common::Exceptions::shapes_do_not_match,\n                  \"vectors.size() =  \" << vectors.size()\n                                       << \"\\n   glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addCellData(vectors[ss], name, ncomps);\n  } // ... addCellData(...)\n\n  template <class VTKFunctionType>\n  void addCellData(const size_t subdomain, const std::shared_ptr<VTKFunctionType>& function, const std::string& name)\n  {\n    DUNE_THROW_IF(subdomain > glued_grid_.num_subdomains(),\n                  Common::Exceptions::index_out_of_range,\n                  \"subdomain = \" << subdomain\n                                 << \"\\n   glued_grid_.num_subdomains() = \" << glued_grid_.num_subdomains());\n    local_vtk_writers_[subdomain]->addCellData(function, name);\n  } // ... addCellData(...)\n\n  template <class VTKFunctionType>\n  void addCellData(const std::vector<std::shared_ptr<VTKFunctionType>>& functions, const std::string& name)\n  {\n    DUNE_THROW_IF(functions.size() != glued_grid_.num_subdomains(),\n                  Common::Exceptions::shapes_do_not_match,\n                  \"functions.size() =  \" << functions.size()\n                                         << \"\\n   glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addCellData(functions[ss], name);\n  } // ... addCellData(...)\n\n  template <class V>\n  void\n  addVertexData(const size_t subdomain, const std::vector<V>& vector, const std::string& name, const int ncomps = 1)\n  {\n    DUNE_THROW_IF(subdomain > glued_grid_.num_subdomains(),\n                  Common::Exceptions::index_out_of_range,\n                  \"subdomain = \" << subdomain\n                                 << \"\\n   glued_grid_.num_subdomains() = \" << glued_grid_.num_subdomains());\n    local_vtk_writers_[subdomain]->addVertexData(vector, name, ncomps);\n  } // ... addVertexData(...)\n\n  template <class V>\n  void addVertexData(const std::vector<std::vector<V>>& vectors, const std::string& name, const int ncomps = 1)\n  {\n    DUNE_THROW_IF(vectors.size() != glued_grid_.num_subdomains(),\n                  Common::Exceptions::shapes_do_not_match,\n                  \"vectors.size() =  \" << vectors.size()\n                                       << \"\\n   glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addVertexData(vectors[ss], name, ncomps);\n  } // ... addVertexData(...)\n\n  template <class VTKFunctionType>\n  void addVertexData(const size_t subdomain, const std::shared_ptr<VTKFunctionType>& function)\n  {\n    DUNE_THROW_IF(subdomain > glued_grid_.num_subdomains(),\n                  Common::Exceptions::index_out_of_range,\n                  \"subdomain = \" << subdomain\n                                 << \"\\n   glued_grid_.num_subdomains() = \" << glued_grid_.num_subdomains());\n    local_vtk_writers_[subdomain]->addVertexData(function);\n  } // ... addVertexData(...)\n\n  template <class VTKFunctionType>\n  void addVertexData(const std::vector<std::shared_ptr<VTKFunctionType>>& functions)\n  {\n    DUNE_THROW_IF(functions.size() != glued_grid_.num_subdomains(),\n                  Common::Exceptions::shapes_do_not_match,\n                  \"functions.size() =  \" << functions.size()\n                                         << \"\\n   glued_grid_.num_subdomains(): \" << glued_grid_.num_subdomains());\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->addVertexData(functions[ss]);\n  } // ... addVertexData(...)\n\n  void clear()\n  {\n    for (auto& local_vtk_writer : local_vtk_writers_)\n      local_vtk_writer->clear();\n  }\n\n  void write(const std::string& name, VTK::OutputType type = VTK::ascii)\n  {\n    for (size_t ss = 0; ss < glued_grid_.num_subdomains(); ++ss)\n      local_vtk_writers_[ss]->write_locally(name, type);\n  }\n\nprivate:\n  template <Layers l, bool anything = true>\n  struct extract_local_view\n  {\n    template <class G>\n    auto operator()(G& g, int /*lv*/) -> decltype(g.leaf_view())\n    {\n      return g.leaf_view();\n    }\n  };\n\n  template <bool anything>\n  struct extract_local_view<Layers::level, anything>\n  {\n    template <class G>\n    auto operator()(G& g, int lv) -> decltype(g.level_view(lv))\n    {\n      return g.level_view(lv);\n    }\n  };\n\n  void prepare_local_vtk_writers()\n  {\n    for (auto&& macro_entity : elements(glued_grid_.macro_grid_view())) {\n      const size_t subdomain = glued_grid_.subdomain(macro_entity);\n      local_vtk_writers_.emplace_back(new LocalVTKWriter(\n          extract_local_view<layer>()(glued_grid_.local_grid(macro_entity), local_levels_[subdomain]),\n          subdomain,\n          glued_grid_.num_subdomains()));\n    }\n  } // ... prepare_local_vtk_writers(...)\n\n  const GluedGridType& glued_grid_;\n  std::vector<int> local_levels_;\n  std::vector<std::unique_ptr<LocalVTKWriter>> local_vtk_writers_;\n}; // class GluedVTKWriter\n\n\n#else // HAVE_DUNE_GRID_GLUE\n\n\ntemplate <class MacroGridImp, class LocalGridImp, Layers layer = Layers::level>\nclass GluedVTKWriter\n{\n  static_assert(AlwaysFalse<MacroGridImp>::value, \"You are missing dune-grid-glue!\");\n};\n\n\ntemplate <class MacroGridImp, class LocalGridImp, Layers layer = Layers::level>\nclass Glued\n{\n  static_assert(AlwaysFalse<MacroGridImp>::value, \"You are missing dune-grid-glue!\");\n};\n\n\n#endif // HAVE_DUNE_GRID_GLUE\n\n\n} // namespace DD\n} // namespace Grid\n} // namespace XT\n} // namespace Dune\n\n#endif // DUNE_XT_GRID_DD_GLUED_HH\n", "meta": {"hexsha": "5fec2db3b0aafb5252cb36f444c68e762fbb6d72", "size": 58927, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/xt/grid/dd/glued.hh", "max_stars_repo_name": "dune-community/dune-xt-grid", "max_stars_repo_head_hexsha": "3453f6619fabc016beaf32409627fec8712f3ef9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-04-04T08:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T04:10:38.000Z", "max_issues_repo_path": "dune/xt/grid/dd/glued.hh", "max_issues_repo_name": "dune-community/dune-xt-grid", "max_issues_repo_head_hexsha": "3453f6619fabc016beaf32409627fec8712f3ef9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2016-01-24T22:11:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T08:30:31.000Z", "max_forks_repo_path": "dune/xt/grid/dd/glued.hh", "max_forks_repo_name": "dune-community/dune-xt-grid", "max_forks_repo_head_hexsha": "3453f6619fabc016beaf32409627fec8712f3ef9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T10:12:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:10:41.000Z", "avg_line_length": 49.0241264559, "max_line_length": 120, "alphanum_fraction": 0.6729343086, "num_tokens": 13121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271168, "lm_q2_score": 0.03963883612289992, "lm_q1q2_score": 0.009487529554648023}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#ifndef __MAKE_MAXIMAL_PLANAR_HPP__\n#define __MAKE_MAXIMAL_PLANAR_HPP__\n\n#include <boost/config.hpp>\n#include <boost/tuple/tuple.hpp>   //for tie\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n\n#include <boost/graph/planar_face_traversal.hpp>\n#include <boost/graph/planar_detail/add_edge_visitors.hpp>\n\n\nnamespace boost\n{\n\n\n  template <typename Graph, typename VertexIndexMap, typename AddEdgeVisitor>\n  struct triangulation_visitor : public planar_face_traversal_visitor\n  {\n\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_t;\n    typedef typename graph_traits<Graph>::edge_iterator edge_iterator_t;\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\n    typedef typename graph_traits<Graph>::adjacency_iterator \n      adjacency_iterator_t;\n    typedef typename std::vector<vertex_t> vertex_vector_t;\n    typedef typename std::vector<v_size_t> v_size_vector_t;\n    typedef typename std::vector<degree_size_t> degree_size_vector_t;\n    typedef iterator_property_map\n      < typename v_size_vector_t::iterator, VertexIndexMap > \n      vertex_to_v_size_map_t;\n    typedef iterator_property_map\n      < typename degree_size_vector_t::iterator, VertexIndexMap > \n      vertex_to_degree_size_map_t;\n    typedef typename vertex_vector_t::iterator face_iterator;\n\n\n    triangulation_visitor(Graph& arg_g, \n                          VertexIndexMap arg_vm, \n                          AddEdgeVisitor arg_add_edge_visitor\n                          ) : \n      g(arg_g),\n      vm(arg_vm),\n      add_edge_visitor(arg_add_edge_visitor),\n      timestamp(0),\n      marked_vector(num_vertices(g), timestamp),\n      degree_vector(num_vertices(g), 0),\n      marked(marked_vector.begin(), vm),\n      degree(degree_vector.begin(), vm)\n    {\n      vertex_iterator_t vi, vi_end;\n      for(tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi)\n        put(degree, *vi, out_degree(*vi, g));\n    }\n\n    template <typename Vertex>\n    void next_vertex(Vertex v)\n    {\n      // Self-loops will appear as consecutive vertices in the list of\n      // vertices on a face. We want to skip these.\n      if (!vertices_on_face.empty() && \n          (vertices_on_face.back() == v || vertices_on_face.front() == v)\n          )\n        return;\n\n      vertices_on_face.push_back(v);\n    }\n\n    void end_face()\n    {\n      ++timestamp;\n\n      if (vertices_on_face.size() <= 3)\n        {\n          // At most three vertices on this face - don't need to triangulate\n          vertices_on_face.clear();\n          return;\n        }\n      \n      // Find vertex on face of minimum degree\n      degree_size_t min_degree = num_vertices(g);\n      typename vertex_vector_t::iterator min_degree_vertex_itr;\n      face_iterator fi_end = vertices_on_face.end();\n      for(face_iterator fi = vertices_on_face.begin(); fi != fi_end; ++fi)\n        {\n          degree_size_t deg = get(degree,*fi);\n          if (deg < min_degree)\n            {\n              min_degree_vertex_itr = fi;\n              min_degree = deg;\n            }\n        }\n\n      // To simplify some of the manipulations, we'll re-arrange \n      // vertices_on_face so that it still contains the same \n      // (counter-clockwise) order of the vertices on this face, but now the \n      // min_degree_vertex is the first element in vertices_on_face.\n      vertex_vector_t temp_vector;\n      std::copy(min_degree_vertex_itr, vertices_on_face.end(), \n                std::back_inserter(temp_vector));\n      std::copy(vertices_on_face.begin(), min_degree_vertex_itr, \n                std::back_inserter(temp_vector));\n      vertices_on_face.swap(temp_vector);\n\n      // Mark all of the min degree vertex's neighbors\n      adjacency_iterator_t ai, ai_end;\n      for(tie(ai,ai_end) = adjacent_vertices(vertices_on_face.front(),g); \n          ai != ai_end; ++ai\n          )\n        {\n          put(marked, *ai, timestamp);\n        }\n\n      typename vertex_vector_t::iterator marked_neighbor \n        = vertices_on_face.end();\n     \n      // The iterator manipulations on the next two lines are safe because \n      // vertices_on_face.size() > 3 (from the first test in this function)\n      fi_end = prior(vertices_on_face.end());\n      for(face_iterator fi = boost::next(boost::next(vertices_on_face.begin())); \n          fi != fi_end; ++fi\n          )\n        {\n          if (get(marked, *fi) == timestamp)\n            {\n              marked_neighbor = fi;\n              break;\n            }\n        }\n\n      if (marked_neighbor == vertices_on_face.end())\n        {\n          add_edge_range(\n                         vertices_on_face[0],\n                         boost::next(boost::next(vertices_on_face.begin())),\n                         prior(vertices_on_face.end())\n                         );\n        }\n      else\n        {\n          add_edge_range(\n                         vertices_on_face[1],\n                         boost::next(marked_neighbor),\n                         vertices_on_face.end()\n                         );\n\n          add_edge_range(\n                         *boost::next(marked_neighbor),\n                         boost::next(boost::next(vertices_on_face.begin())),\n                         marked_neighbor\n                         );\n        }\n\n      //reset for the next face\n      vertices_on_face.clear();\n      \n    }\n\n  private:\n\n    \n    void add_edge_range(vertex_t anchor, \n                        face_iterator fi, \n                        face_iterator fi_end\n                        )\n    {\n      for (; fi != fi_end; ++fi)\n        {\n          vertex_t v(*fi);\n          add_edge_visitor.visit_vertex_pair(anchor, v, g);\n          put(degree, anchor, get(degree, anchor) + 1);\n          put(degree, v, get(degree, v) + 1);\n        }\n    }\n\n\n    Graph& g;\n    VertexIndexMap vm;\n    AddEdgeVisitor add_edge_visitor;\n    v_size_t timestamp;\n    vertex_vector_t vertices_on_face;\n    v_size_vector_t marked_vector;\n    degree_size_vector_t degree_vector;\n    vertex_to_v_size_map_t marked;\n    vertex_to_degree_size_map_t degree;\n    \n  };\n\n\n\n\n  template <typename Graph,\n            typename PlanarEmbedding,\n            typename VertexIndexMap,\n            typename EdgeIndexMap,\n            typename AddEdgeVisitor\n            >\n  void make_maximal_planar(Graph& g, \n                           PlanarEmbedding embedding,\n                           VertexIndexMap vm, \n                           EdgeIndexMap em,\n                           AddEdgeVisitor& vis)\n  {\n    triangulation_visitor<Graph,VertexIndexMap,AddEdgeVisitor> \n      visitor(g, vm, vis);\n    planar_face_traversal(g, embedding, visitor, em);\n  }\n\n\n\n\n  template <typename Graph,\n            typename PlanarEmbedding,\n            typename VertexIndexMap,\n            typename EdgeIndexMap\n            >\n  void make_maximal_planar(Graph& g,\n                           PlanarEmbedding embedding,\n                           VertexIndexMap vm,\n                           EdgeIndexMap em\n                           )\n  {\n    default_add_edge_visitor vis;\n    make_maximal_planar(g, embedding, vm, em, vis);\n  }\n\n\n\n\n  template <typename Graph,\n            typename PlanarEmbedding,\n            typename VertexIndexMap\n            >\n  void make_maximal_planar(Graph& g,\n                           PlanarEmbedding embedding,\n                           VertexIndexMap vm\n                           )\n  {\n    make_maximal_planar(g, embedding, vm, get(edge_index,g));\n  }\n\n\n\n\n  template <typename Graph,\n            typename PlanarEmbedding\n            >\n  void make_maximal_planar(Graph& g,\n                           PlanarEmbedding embedding\n                           )\n  {\n    make_maximal_planar(g, embedding, get(vertex_index,g));\n  }\n\n\n  \n\n} // namespace boost\n\n\n\n#endif //__MAKE_MAXIMAL_PLANAR_HPP__\n", "meta": {"hexsha": "70a1e08abae78544f1974e003e9808bcc6b94449", "size": 8406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/boost/graph/make_maximal_planar.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/make_maximal_planar.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/make_maximal_planar.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": 30.4565217391, "max_line_length": 81, "alphanum_fraction": 0.5879133952, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.01912403814849181, "lm_q1q2_score": 0.009487317320033255}}
{"text": "// Copyright Louis Dionne 2013\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\n// at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GRAPH_HAWICK_CIRCUITS_HPP\n#define BOOST_GRAPH_HAWICK_CIRCUITS_HPP\n\n#include <algorithm>\n#include <boost/assert.hpp>\n#include <boost/foreach.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/move/utility.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/iterator.hpp>\n#include <boost/tuple/tuple.hpp> // for boost::tie\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/utility/result_of.hpp>\n#include <set>\n#include <utility> // for std::pair\n#include <vector>\n\nnamespace boost\n{\nnamespace hawick_circuits_detail\n{\n    //! @internal Functor returning all the vertices adjacent to a vertex.\n    struct get_all_adjacent_vertices\n    {\n        template < typename Sig > struct result;\n\n        template < typename This, typename Vertex, typename Graph >\n        struct result< This(Vertex, Graph) >\n        {\n        private:\n            typedef typename remove_reference< Graph >::type RawGraph;\n            typedef graph_traits< RawGraph > Traits;\n            typedef typename Traits::adjacency_iterator AdjacencyIterator;\n\n        public:\n            typedef std::pair< AdjacencyIterator, AdjacencyIterator > type;\n        };\n\n        template < typename Vertex, typename Graph >\n        typename result< get_all_adjacent_vertices(\n            BOOST_FWD_REF(Vertex), BOOST_FWD_REF(Graph)) >::type\n        operator()(BOOST_FWD_REF(Vertex) v, BOOST_FWD_REF(Graph) g) const\n        {\n            return adjacent_vertices(\n                boost::forward< Vertex >(v), boost::forward< Graph >(g));\n        }\n    };\n\n    //! @internal Functor returning a set of the vertices adjacent to a vertex.\n    struct get_unique_adjacent_vertices\n    {\n        template < typename Sig > struct result;\n\n        template < typename This, typename Vertex, typename Graph >\n        struct result< This(Vertex, Graph) >\n        {\n            typedef std::set< typename remove_reference< Vertex >::type > type;\n        };\n\n        template < typename Vertex, typename Graph >\n        typename result< get_unique_adjacent_vertices(\n            Vertex, Graph const&) >::type\n        operator()(Vertex v, Graph const& g) const\n        {\n            typedef typename result< get_unique_adjacent_vertices(\n                Vertex, Graph const&) >::type Set;\n            return Set(\n                adjacent_vertices(v, g).first, adjacent_vertices(v, g).second);\n        }\n    };\n\n    //! @internal\n    //! Return whether a container contains a given value.\n    //! This is not meant as a general purpose membership testing function; it\n    //! would have to be more clever about possible optimizations.\n    template < typename Container, typename Value >\n    bool contains(Container const& c, Value const& v)\n    {\n        return std::find(boost::begin(c), boost::end(c), v) != boost::end(c);\n    }\n\n    /*!\n     * @internal\n     * Algorithm finding all the cycles starting from a given vertex.\n     *\n     * The search is only done in the subgraph induced by the starting vertex\n     * and the vertices with an index higher than the starting vertex.\n     */\n    template < typename Graph, typename Visitor, typename VertexIndexMap,\n        typename Stack, typename ClosedMatrix, typename GetAdjacentVertices >\n    struct hawick_circuits_from\n    {\n    private:\n        typedef graph_traits< Graph > Traits;\n        typedef typename Traits::vertex_descriptor Vertex;\n        typedef typename Traits::edge_descriptor Edge;\n        typedef typename Traits::vertices_size_type VerticesSize;\n        typedef\n            typename property_traits< VertexIndexMap >::value_type VertexIndex;\n\n        typedef typename result_of< GetAdjacentVertices(\n            Vertex, Graph const&) >::type AdjacentVertices;\n        typedef typename range_iterator< AdjacentVertices const >::type\n            AdjacencyIterator;\n\n        // The one_bit_color_map starts all white, i.e. not blocked.\n        // Since we make that assumption (I looked at the implementation, but\n        // I can't find anything that documents this behavior), we're gonna\n        // assert it in the constructor.\n        typedef one_bit_color_map< VertexIndexMap > BlockedMap;\n        typedef typename property_traits< BlockedMap >::value_type BlockedColor;\n\n        static BlockedColor blocked_false_color()\n        {\n            return color_traits< BlockedColor >::white();\n        }\n\n        static BlockedColor blocked_true_color()\n        {\n            return color_traits< BlockedColor >::black();\n        }\n\n        // This is used by the constructor to secure the assumption\n        // documented above.\n        bool blocked_map_starts_all_unblocked() const\n        {\n            BOOST_FOREACH (Vertex v, vertices(graph_))\n                if (is_blocked(v))\n                    return false;\n            return true;\n        }\n\n        // This is only used in the constructor to make sure the optimization of\n        // sharing data structures between iterations does not break the code.\n        bool all_closed_rows_are_empty() const\n        {\n            BOOST_FOREACH (typename ClosedMatrix::reference row, closed_)\n                if (!row.empty())\n                    return false;\n            return true;\n        }\n\n    public:\n        hawick_circuits_from(Graph const& graph, Visitor& visitor,\n            VertexIndexMap const& vim, Stack& stack, ClosedMatrix& closed,\n            VerticesSize n_vertices)\n        : graph_(graph)\n        , visitor_(visitor)\n        , vim_(vim)\n        , stack_(stack)\n        , closed_(closed)\n        , blocked_(n_vertices, vim_)\n        {\n            BOOST_ASSERT(blocked_map_starts_all_unblocked());\n\n            // Since sharing the data structures between iterations is\n            // just an optimization, it must always be equivalent to\n            // constructing new ones in this constructor.\n            BOOST_ASSERT(stack_.empty());\n            BOOST_ASSERT(closed_.size() == n_vertices);\n            BOOST_ASSERT(all_closed_rows_are_empty());\n        }\n\n    private:\n        //! @internal Return the index of a given vertex.\n        VertexIndex index_of(Vertex v) const { return get(vim_, v); }\n\n        //! @internal Return whether a vertex `v` is closed to a vertex `u`.\n        bool is_closed_to(Vertex u, Vertex v) const\n        {\n            typedef typename ClosedMatrix::const_reference VertexList;\n            VertexList closed_to_u = closed_[index_of(u)];\n            return contains(closed_to_u, v);\n        }\n\n        //! @internal Close a vertex `v` to a vertex `u`.\n        void close_to(Vertex u, Vertex v)\n        {\n            BOOST_ASSERT(!is_closed_to(u, v));\n            closed_[index_of(u)].push_back(v);\n        }\n\n        //! @internal Return whether a given vertex is blocked.\n        bool is_blocked(Vertex v) const\n        {\n            return get(blocked_, v) == blocked_true_color();\n        }\n\n        //! @internal Block a given vertex.\n        void block(Vertex v) { put(blocked_, v, blocked_true_color()); }\n\n        //! @internal Unblock a given vertex.\n        void unblock(Vertex u)\n        {\n            typedef typename ClosedMatrix::reference VertexList;\n\n            put(blocked_, u, blocked_false_color());\n            VertexList closed_to_u = closed_[index_of(u)];\n\n            while (!closed_to_u.empty())\n            {\n                Vertex const w = closed_to_u.back();\n                closed_to_u.pop_back();\n                if (is_blocked(w))\n                    unblock(w);\n            }\n            BOOST_ASSERT(closed_to_u.empty());\n        }\n\n        //! @internal Main procedure as described in the paper.\n        bool circuit(Vertex start, Vertex v)\n        {\n            bool found_circuit = false;\n            stack_.push_back(v);\n            block(v);\n\n            // Cache some values that are used more than once in the function.\n            VertexIndex const index_of_start = index_of(start);\n            AdjacentVertices const adj_vertices\n                = GetAdjacentVertices()(v, graph_);\n            AdjacencyIterator const w_end = boost::end(adj_vertices);\n\n            for (AdjacencyIterator w_it = boost::begin(adj_vertices);\n                 w_it != w_end; ++w_it)\n            {\n                Vertex const w = *w_it;\n                // Since we're only looking in the subgraph induced by `start`\n                // and the vertices with an index higher than `start`, we skip\n                // any vertex that does not satisfy that.\n                if (index_of(w) < index_of_start)\n                    continue;\n\n                // If the last vertex is equal to `start`, we have a circuit.\n                else if (w == start)\n                {\n                    // const_cast to ensure the visitor does not modify the\n                    // stack\n                    visitor_.cycle(const_cast< Stack const& >(stack_), graph_);\n                    found_circuit = true;\n                }\n\n                // If `w` is not blocked, we continue searching further down the\n                // same path for a cycle with `w` in it.\n                else if (!is_blocked(w) && circuit(start, w))\n                    found_circuit = true;\n            }\n\n            if (found_circuit)\n                unblock(v);\n            else\n                for (AdjacencyIterator w_it = boost::begin(adj_vertices);\n                     w_it != w_end; ++w_it)\n                {\n                    Vertex const w = *w_it;\n                    // Like above, we skip vertices that are not in the subgraph\n                    // we're considering.\n                    if (index_of(w) < index_of_start)\n                        continue;\n\n                    // If `v` is not closed to `w`, we make it so.\n                    if (!is_closed_to(w, v))\n                        close_to(w, v);\n                }\n\n            BOOST_ASSERT(v == stack_.back());\n            stack_.pop_back();\n            return found_circuit;\n        }\n\n    public:\n        void operator()(Vertex start) { circuit(start, start); }\n\n    private:\n        Graph const& graph_;\n        Visitor& visitor_;\n        VertexIndexMap const& vim_;\n        Stack& stack_;\n        ClosedMatrix& closed_;\n        BlockedMap blocked_;\n    };\n\n    template < typename GetAdjacentVertices, typename Graph, typename Visitor,\n        typename VertexIndexMap >\n    void call_hawick_circuits(Graph const& graph,\n        Visitor /* by value */ visitor, VertexIndexMap const& vertex_index_map)\n    {\n        typedef graph_traits< Graph > Traits;\n        typedef typename Traits::vertex_descriptor Vertex;\n        typedef typename Traits::vertices_size_type VerticesSize;\n        typedef typename Traits::vertex_iterator VertexIterator;\n\n        typedef std::vector< Vertex > Stack;\n        typedef std::vector< std::vector< Vertex > > ClosedMatrix;\n\n        typedef hawick_circuits_from< Graph, Visitor, VertexIndexMap, Stack,\n            ClosedMatrix, GetAdjacentVertices >\n            SubAlgorithm;\n\n        VerticesSize const n_vertices = num_vertices(graph);\n        Stack stack;\n        stack.reserve(n_vertices);\n        ClosedMatrix closed(n_vertices);\n\n        VertexIterator start, last;\n        for (boost::tie(start, last) = vertices(graph); start != last; ++start)\n        {\n            // Note1: The sub algorithm may NOT be reused once it has been\n            // called.\n\n            // Note2: We reuse the Stack and the ClosedMatrix (after clearing\n            // them) in each iteration to avoid redundant destruction and\n            // construction. It would be strictly equivalent to have these as\n            // member variables of the sub algorithm.\n            SubAlgorithm sub_algo(\n                graph, visitor, vertex_index_map, stack, closed, n_vertices);\n            sub_algo(*start);\n            stack.clear();\n            typename ClosedMatrix::iterator row, last_row = closed.end();\n            for (row = closed.begin(); row != last_row; ++row)\n                row->clear();\n        }\n    }\n\n    template < typename GetAdjacentVertices, typename Graph, typename Visitor >\n    void call_hawick_circuits(\n        Graph const& graph, BOOST_FWD_REF(Visitor) visitor)\n    {\n        call_hawick_circuits< GetAdjacentVertices >(graph,\n            boost::forward< Visitor >(visitor), get(vertex_index, graph));\n    }\n} // end namespace hawick_circuits_detail\n\n//! Enumerate all the elementary circuits in a directed multigraph.\ntemplate < typename Graph, typename Visitor, typename VertexIndexMap >\nvoid hawick_circuits(BOOST_FWD_REF(Graph) graph, BOOST_FWD_REF(Visitor) visitor,\n    BOOST_FWD_REF(VertexIndexMap) vertex_index_map)\n{\n    hawick_circuits_detail::call_hawick_circuits<\n        hawick_circuits_detail::get_all_adjacent_vertices >(\n        boost::forward< Graph >(graph), boost::forward< Visitor >(visitor),\n        boost::forward< VertexIndexMap >(vertex_index_map));\n}\n\ntemplate < typename Graph, typename Visitor >\nvoid hawick_circuits(BOOST_FWD_REF(Graph) graph, BOOST_FWD_REF(Visitor) visitor)\n{\n    hawick_circuits_detail::call_hawick_circuits<\n        hawick_circuits_detail::get_all_adjacent_vertices >(\n        boost::forward< Graph >(graph), boost::forward< Visitor >(visitor));\n}\n\n/*!\n * Same as `boost::hawick_circuits`, but duplicate circuits caused by parallel\n * edges will not be considered. Each circuit will be considered only once.\n */\ntemplate < typename Graph, typename Visitor, typename VertexIndexMap >\nvoid hawick_unique_circuits(BOOST_FWD_REF(Graph) graph,\n    BOOST_FWD_REF(Visitor) visitor,\n    BOOST_FWD_REF(VertexIndexMap) vertex_index_map)\n{\n    hawick_circuits_detail::call_hawick_circuits<\n        hawick_circuits_detail::get_unique_adjacent_vertices >(\n        boost::forward< Graph >(graph), boost::forward< Visitor >(visitor),\n        boost::forward< VertexIndexMap >(vertex_index_map));\n}\n\ntemplate < typename Graph, typename Visitor >\nvoid hawick_unique_circuits(\n    BOOST_FWD_REF(Graph) graph, BOOST_FWD_REF(Visitor) visitor)\n{\n    hawick_circuits_detail::call_hawick_circuits<\n        hawick_circuits_detail::get_unique_adjacent_vertices >(\n        boost::forward< Graph >(graph), boost::forward< Visitor >(visitor));\n}\n} // end namespace boost\n\n#endif // !BOOST_GRAPH_HAWICK_CIRCUITS_HPP\n", "meta": {"hexsha": "ba4065492b5f6199d4962457f590bd092ec42229", "size": 14593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/hawick_circuits.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/hawick_circuits.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/hawick_circuits.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": 37.6108247423, "max_line_length": 80, "alphanum_fraction": 0.622353183, "num_tokens": 3051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.02128735299645948, "lm_q1q2_score": 0.009484144482735848}}
{"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @file math.hpp\n * @author Vaclav Blazek <vaclav.blazek@citationtech.net>\n *\n * 3D mesh operations\n */\n\n#include <unordered_set>\n#include <unordered_map>\n\n#include \"meshop.hpp\"\n#include \"parse-obj.hpp\"\n#include \"parse-ply.hpp\"\n#include \"triclip.hpp\"\n\n#include \"utility/expect.hpp\"\n#include \"utility/small_list.hpp\"\n\n#include <set>\n#include <boost/algorithm/string.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/lexical_cast.hpp>\n\nnamespace geometry {\n\nnamespace ublas = boost::numeric::ublas;\nnamespace ba = boost::algorithm;\n\nObj asObj(const Mesh &mesh)\n{\n    Obj obj;\n    for ( math::Point3 vertex : mesh.vertices ) {\n\n        geometry::Obj::Vector3d overtex;\n        overtex.x = vertex[0]; overtex.y = vertex[1]; overtex.z = vertex[2];\n\n        obj.addVertex( overtex );\n\n        //LOG( info1 ) << \"[\" << overtex.x << \", \" << overtex.y << \", \"\n        //    << overtex.z << \"]\";\n    }\n\n    for ( math::Point2 texture : mesh.tCoords ) {\n\n        geometry::Obj::Vector3d otexture;\n        otexture.x = texture[0]; otexture.y = texture[1]; otexture.z = 0.0;\n\n        obj.addTexture( otexture );\n    }\n\n    for ( geometry::Face face : mesh.faces ) {\n\n        geometry::Obj::Facet facet;\n\n        facet.v[0] = int(face.a);\n        facet.v[1] = int(face.b);\n        facet.v[2] = int(face.c);\n\n        facet.t[0] = int(face.ta);\n        facet.t[1] = int(face.tb);\n        facet.t[2] = int(face.tc);\n\n        obj.addFacet( facet );\n    }\n\n    return obj;\n}\n\nMesh::pointer asMesh(const Obj &obj){\n    auto newMesh(std::make_shared<geometry::Mesh>());\n    for( const auto&v : obj.vertices ){\n        newMesh->vertices.push_back(v);\n    }\n\n    for( const auto&t : obj.texcoords ){\n        newMesh->tCoords.emplace_back( t(0), t(1) );\n    }\n\n    for( const auto&f : obj.facets ){\n        newMesh->addFace(f.v[0], f.v[1], f.v[2], f.t[0], f.t[1], f.t[2]);\n    }\n\n    return newMesh;\n}\n\nstd::string ObjMaterial::name(std::size_t index) const\n{\n    if (index < names.size()) { return names[index]; }\n    return boost::lexical_cast<std::string>(index);\n}\n\nnamespace {\n\nvoid addMtl(std::ostream &out, const ObjMaterial &mtl, unsigned int imageId)\n{\n    if (mtl.libs.empty()) { return; }\n    out << \"usemtl \" << mtl.name(imageId) << '\\n';\n}\n\n} // namespace\n\nvoid saveAsObj(const Mesh &mesh, std::ostream &out\n               , const ObjMaterial &mtl\n               , const boost::filesystem::path &filepath\n               , const ObjStreamSetup &streamSetup)\n{\n    // keep current numeric precision for future use\n    const auto oldPrecision(out.precision());\n\n    for (const auto &lib : mtl.libs) {\n        out << \"mtllib \" << lib << '\\n';\n    }\n\n    if (!streamSetup.vertex(out)) {\n        out.setf(std::ios::scientific, std::ios::floatfield);\n    }\n\n    for (const auto &vertex : mesh.vertices) {\n        out << \"v \" << vertex(0) << ' ' << vertex(1) << ' '  << vertex(2)\n            << '\\n';\n    }\n\n    if (!streamSetup.tx(out)) {\n        out.setf(std::ios::scientific, std::ios::floatfield);\n        // reset precision to recorded one\n        out.precision(oldPrecision);\n    }\n\n    for (const auto &tCoord : mesh.tCoords) {\n        out << \"vt \" << tCoord(0) << ' ' << tCoord(1) << '\\n';\n    }\n\n    const bool textured(!mesh.tCoords.empty());\n\n    unsigned int currentImageId(static_cast<unsigned int>(-1));\n\n    for (const auto &face : mesh.faces) {\n        if (face.degenerate()) {\n            continue;\n        }\n\n        if (textured && (face.imageId != currentImageId)) {\n            addMtl(out, mtl, face.imageId);\n            currentImageId = face.imageId;\n        }\n\n        if (textured) {\n            out << \"f \" << face.a + 1 << '/' << face.ta + 1 << \"/ \"\n                << face.b + 1 << '/' << face.tb + 1 << \"/ \"\n                << face.c + 1 << '/' << face.tc + 1 << \"/\\n\";\n        } else {\n            out << \"f \" << face.a + 1 << ' '\n                << face.b + 1 << ' '\n                << face.c + 1 << \"\\n\";\n        }\n    }\n\n    if (!out) {\n        LOGTHROW(err3, std::runtime_error)\n            << \"Unable to save mesh to <\" << filepath << \">.\";\n    }\n}\n\nvoid saveAsObj(const Mesh &mesh, std::ostream &out\n               , const ObjMaterial &mtl\n               , const boost::filesystem::path &filepath\n               , bool setFormat)\n{\n    struct DontSetFormat : ObjStreamSetup {\n        virtual bool vertex(std::ostream&) const { return true; }\n        virtual bool tx(std::ostream&) const { return true; }\n    };\n\n    const ObjStreamSetup &streamSetup(setFormat\n                                      ? ObjStreamSetup()\n                                      : DontSetFormat());\n\n    saveAsObj(mesh, out, mtl, filepath, streamSetup);\n}\n\nvoid saveAsObj(const Mesh &mesh, const boost::filesystem::path &filepath\n               , const ObjMaterial &mtl, const ObjStreamSetup &streamSetup)\n{\n    LOG(info2) << \"Saving mesh to file <\" << filepath << \">.\";\n\n    std::ofstream f;\n    f.exceptions(std::ios::badbit | std::ios::failbit);\n    try {\n        f.open(filepath.string(), std::ios_base::out | std::ios_base::trunc);\n    } catch (const std::exception&) {\n        LOGTHROW(err3, std::runtime_error)\n            << \"Unable to save mesh to <\" << filepath << \">.\";\n    }\n\n    saveAsObj(mesh, f, mtl, filepath, streamSetup);\n}\n\nvoid saveAsPly( const Mesh &mesh, const boost::filesystem::path &filepath){\n    LOG(info2) << \"Saving mesh to file <\" << filepath << \">.\";\n\n    std::ofstream out;\n    out.exceptions(std::ios::badbit | std::ios::failbit);\n    out.open(filepath.string(), std::ios_base::out | std::ios_base::trunc);\n    out.setf(std::ios::scientific, std::ios::floatfield);\n\n    unsigned validFaces(0);\n    for (const auto &face : mesh.faces) {\n        if (!face.degenerate() && mesh.good(face))\n            validFaces++;\n    }\n\n    out << \"ply\\n\"\n        << \"format ascii 1.0\\n\"\n        << \"comment generated by window-mesh\\n\"\n        << \"element vertex \" << mesh.vertices.size() << '\\n'\n        << \"property float x\\n\"\n        << \"property float y\\n\"\n        << \"property float z\\n\"\n        << \"element face \" << validFaces << '\\n'\n        << \"property list uchar int vertex_indices\\n\"\n        << \"end_header\\n\";\n\n    for (const auto &vertex : mesh.vertices)\n    {\n        out << vertex(0) << ' ' << vertex(1) << ' '  << vertex(2) << '\\n';\n    }\n\n    for (const auto &face : mesh.faces)\n    {\n        if (face.degenerate()) {\n            continue;\n        }\n        if (!mesh.good(face)) {\n            LOG(warn2) << \"Invalid vertex index in face.\";\n            continue;\n        }\n        out << \"3 \" << face.a << ' ' << face.b << ' ' << face.c << '\\n';\n    }\n\n    out.close();\n\n    if (!out) {\n        LOGTHROW(err3, std::runtime_error)\n            << \"Unable to save mesh to <\" << filepath << \">.\";\n    }\n}\n\nMesh loadPly(const boost::filesystem::path& filepath)\n{\n    class SimplePlyParser : public PlyParserBase\n    {\n    public:\n        Mesh mesh;\n\n        void loadHeader(const std::vector<PlyElement>& elements,\n                        const std::vector<std::string>& /* comments */) override\n        {\n            for (const auto& el : elements)\n            {\n                if (el.name == \"vertex\")\n                {\n                    mesh.vertices.reserve(el.count);\n\n                    // check vertex properties\n                    if (el.props.size() != 3)\n                    {\n                        LOGTHROW(err4, std::runtime_error)\n                            << \"No additional vertex properties supported in \"\n                               \"simple parser\";\n                    }\n                    utility::expect(el.props[0].name == \"x\");\n                    utility::expect(el.props[1].name == \"y\");\n                    utility::expect(el.props[2].name == \"z\");\n                }\n                else if (el.name == \"face\")\n                {\n                    mesh.faces.reserve(el.count);\n\n                    // check face properties\n                    if (el.props.size() != 1)\n                    {\n                        LOGTHROW(err4, std::runtime_error)\n                            << \"No additional face properties supported in \"\n                               \"simple parser\";\n                    }\n                    if (!ba::starts_with(el.props[0].type, \"list\"))\n                    {\n                        LOGTHROW(err4, std::runtime_error)\n                            << \"Expected face property type to be a list, but \"\n                               \"got: \"\n                            << el.props[0].type;\n                    }\n                    // does not check the name which should generally be\n                    // \"vertex_index\" but might vary\n                }\n                else\n                {\n                    LOGTHROW(err4, std::runtime_error)\n                        << \"Unexpected element in header - not supported by \"\n                           \"simple parser: \"\n                        << el.name;\n                }\n            }\n        }\n\n        void addVertex(std::istream& f) override\n        {\n            double x, y, z;\n            f >> x >> y >> z;\n            mesh.vertices.emplace_back(x, y, z);\n        }\n\n        void addFace(std::istream& f) override\n        {\n            int n, a, b, c;\n            f >> n >> a >> b >> c;\n            if (n != 3)\n            {\n                LOGTHROW(err4, std::runtime_error)\n                    << \"Simple parser only supports loading triangular meshes, \"\n                       \"but got face with \" << n << \" vertices.\";\n            }\n            mesh.faces.emplace_back(a, b, c);\n        }\n    } simpleParser;\n\n    parsePly(simpleParser, filepath);\n\n    LOG(info1) << \"Loaded mesh with \" << simpleParser.mesh.vertices.size()\n               << \" vertices and \" << simpleParser.mesh.faces.size()\n               << \" faces\";\n\n    return simpleParser.mesh;\n}\n\nconst unsigned int imageIdLimit(1<<16);\n\nvoid loadObj( ObjParserBase &parser\n            , const boost::filesystem::path &filename)\n{\n    std::ifstream file;\n    file.exceptions(std::ios::badbit | std::ios::failbit);\n    file.open(filename.string());\n\n    if (!parser.parse(file)) {\n        LOGTHROW(err2, std::runtime_error)\n            << \"LoadObj failed to parse file \" << filename << \".\";\n    }\n}\n\nMesh loadObj(const boost::filesystem::path &filename, ObjMaterial *mtl)\n{\n    struct Obj2MeshParser : public ObjParserBase {\n        Obj2MeshParser() : imageId(), namedCount() {}\n\n        void addVertex( const Vector3d &v ) {\n            mesh.vertices.push_back(v);\n        }\n\n        void addTexture( const Vector3d &t ) {\n            mesh.tCoords.emplace_back(t.x, t.y);\n        }\n\n        void addFacet( const Facet &f ) {\n            mesh.addFace( f.v[0], f.v[1], f.v[2]\n                        , f.t[0], f.t[1], f.t[2] );\n            mesh.faces.back().imageId = imageId;\n        }\n\n        void addNormal( const Vector3d& ) { }\n\n        void materialLibrary(const std::string &lib) { seenLibs.insert(lib); }\n        void useMaterial(const std::string &name) {\n            auto fmtlMap(mtlMap.find(name));\n            if (fmtlMap == mtlMap.end()) {\n                unsigned int id(0);\n                try {\n                    // is id a (non negative) number?\n                    auto number(boost::lexical_cast<unsigned int>(name));\n                    id = number;\n                } catch (const boost::bad_lexical_cast&) {\n                    // not a number\n                    id = imageIdLimit + namedCount++;\n                }\n\n                fmtlMap = mtlMap.insert(MtlMap::value_type(name, id)).first;\n            }\n\n            imageId = fmtlMap->second;\n        }\n\n        Mesh mesh;\n        unsigned int imageId;\n        std::set<std::string> seenLibs;\n        typedef std::map<std::string, int> MtlMap;\n        MtlMap mtlMap;\n        int namedCount;\n    } parser_;\n\n    loadObj(parser_, filename);\n\n    std::vector<std::string> materials;\n\n    // regenerate IDs if there was any non-numeric material\n    if (parser_.namedCount) {\n        typedef std::map<unsigned int, unsigned int> Mapping;\n        Mapping mapping;\n        for (const auto &item : parser_.mtlMap) {\n            mapping[item.second] = materials.size();\n            materials.push_back(item.first);\n        }\n\n        for (auto &face : parser_.mesh.faces) {\n            face.imageId = mapping[face.imageId];\n        }\n    }\n\n    if (mtl) {\n        mtl->libs.assign(parser_.seenLibs.begin(), parser_.seenLibs.end());\n        mtl->names = std::move(materials);\n    }\n\n    return parser_.mesh;\n}\n\nnamespace {\n\nvoid clipImpl(const Mesh &omesh, Mesh &mesh\n              , const std::vector<ClipPlane> &planes)\n{\n    ClipTriangle::list clipped;\n    for (const auto &face : omesh.faces) {\n        clipped.emplace_back(\n              omesh.vertices[face.a]\n            , omesh.vertices[face.b]\n            , omesh.vertices[face.c]);\n    }\n\n    std::vector<double> tinfos;\n    for (const auto &plane : planes) {\n        clipped = clipTriangles(clipped, plane, tinfos);\n    }\n\n    typedef math::Points3::size_type Index;\n    std::map<math::Point3, Index> pMap;\n    Index next = 0;\n\n    for (const auto &triangle : clipped)\n    {\n        Index indices[3];\n        for (int i = 0; i < 3; i++)\n        {\n            auto pair = pMap.insert(std::make_pair(triangle.pos[i], next));\n            if (pair.second) {\n                next++;\n            }\n            indices[i] = pair.first->second;\n\n            if (indices[i] >= mesh.vertices.size()) {\n                mesh.vertices.push_back(triangle.pos[i]);\n            }\n        }\n        // do not add degenerated faces\n        if ((indices[0] != indices[1]) &&\n            (indices[1] != indices[2]) &&\n            (indices[0] != indices[2]))\n        {\n            mesh.addFace(indices[0], indices[1], indices[2]);\n        }\n    }\n}\n\nstd::vector<ClipPlane> planes(const math::Extents2 &extents)\n{\n    std::vector<ClipPlane> planes;\n    planes.emplace_back(+1.,  0., 0., extents.ll[0]);\n    planes.emplace_back(-1.,  0., 0., -extents.ur[0]);\n    planes.emplace_back(0.,  +1., 0., extents.ll[1]);\n    planes.emplace_back(0.,  -1., 0., -extents.ur[1]);\n    return planes;\n}\n\nstd::vector<ClipPlane> planes(const math::Extents3 &extents)\n{\n    std::vector<ClipPlane> planes;\n    planes.emplace_back(+1.,  0., 0., extents.ll[0]);\n    planes.emplace_back(-1.,  0., 0., -extents.ur[0]);\n    planes.emplace_back(0.,  +1., 0., extents.ll[1]);\n    planes.emplace_back(0.,  -1., 0., -extents.ur[1]);\n    planes.emplace_back(0.,  0., +1., extents.ll[2]);\n    planes.emplace_back(0.,  0., -1., -extents.ur[2]);\n    return planes;\n}\n\n} // namespace\n\nMesh clip(const Mesh &omesh, const math::Extents2 &extents)\n{\n    Mesh out;\n    clipImpl(omesh, out, planes(extents));\n    return out;\n}\n\nMesh clip(const Mesh &omesh, const math::Extents3 &extents)\n{\n    Mesh out;\n    clipImpl(omesh, out, planes(extents));\n    return out;\n}\n\nMesh::pointer removeNonManifoldEdges(Mesh omesh)\n{\n    auto ofaces = omesh.faces;\n    auto pmesh(std::make_shared<geometry::Mesh>(std::move(omesh)));\n    auto& mesh(*pmesh);\n    mesh.faces.clear();\n    mesh.faces.shrink_to_fit();\n\n    typedef Face::index_type index_type;\n\n    struct EdgeKey\n    {\n        index_type v1, v2; // vertex indices\n\n        EdgeKey(index_type v1, index_type v2)\n        {\n            this->v1 = std::min(v1, v2);\n            this->v2 = std::max(v1, v2);\n        }\n\n        bool operator< (const EdgeKey& other) const\n        {\n            return (v1 == other.v1) ? (v2 < other.v2) : (v1 < other.v1);\n        }\n    };\n\n    struct Edge {\n        utility::small_list<index_type, 2> facesIndices;\n    };\n\n    //count faces for each edge\n    std::map<EdgeKey,Edge> edgeMap;\n    for(index_type fi=0; fi<ofaces.size(); fi++){\n        const auto & face(ofaces[fi]);\n        EdgeKey edgeKeys[3] = { EdgeKey(face.a,face.b)\n                           , EdgeKey(face.b,face.c)\n                           , EdgeKey(face.c,face.a) };\n        for(const auto & key : edgeKeys){\n            auto it = edgeMap.find(key);\n            if(it==edgeMap.end()){\n                //if edge is not present insert it with current face\n                Edge edge;\n                edge.facesIndices.insert(fi);\n                edgeMap.insert(std::make_pair(key,edge));\n            }\n            else{\n                //if edge is present add current face to it\n                it->second.facesIndices.insert(fi);\n            }\n        }\n    }\n\n    //collect faces incident with non-manifold edge\n    std::set<index_type> facesToOmit;\n    for(auto it = edgeMap.begin(); it!=edgeMap.end(); it++){\n        if(it->second.facesIndices.size()>2){\n            it->second.facesIndices.for_each([&](index_type fi) {\n                facesToOmit.insert(fi);\n            });\n        }\n    }\n\n    for(index_type fi=0; fi<ofaces.size(); fi++){\n        const auto & face(ofaces[fi]);\n        if(facesToOmit.find(fi)==facesToOmit.end()){\n            mesh.addFace( face.a, face.b, face.c\n                        , face.ta, face.tb, face.tc );\n        }\n    }\n\n    return pmesh;\n}\n\nMesh::pointer removeIsolatedVertices( const Mesh& imesh ){\n    auto pmesh(std::make_shared<geometry::Mesh>());\n    auto & mesh(*pmesh);\n\n    std::map<math::Points3::size_type, math::Points3::size_type> vertexMap;\n    std::map<math::Points2::size_type, math::Points2::size_type> tCoordsMap;\n\n    for( const auto& face: imesh.faces ){\n        math::Points3::size_type vindices[3] { face.a , face.b, face.c };\n        math::Points2::size_type tindices[3] { face.ta , face.tb, face.tc };\n\n        for(unsigned int i=0; i<3; ++i){\n            auto vit = vertexMap.find(vindices[i]);\n            auto tit = tCoordsMap.find(tindices[i]);\n\n            if(vit == vertexMap.end()){\n                mesh.vertices.push_back(imesh.vertices[vindices[i]]);\n                vit = vertexMap.insert(std::make_pair(vindices[i],mesh.vertices.size()-1)).first;\n            }\n            if(imesh.tCoords.size() > 0 && tit == tCoordsMap.end()){\n                mesh.tCoords.push_back(imesh.vertices[tindices[i]]);\n                tit = tCoordsMap.insert(std::make_pair(tindices[i],mesh.tCoords.size()-1)).first;\n            }\n\n            vindices[i] = vit->second;\n            tindices[i] = tit->second;\n        }\n\n        if(imesh.tCoords.size() > 0){\n            mesh.addFace( vindices[0], vindices[1], vindices[2]\n                        , tindices[0], tindices[1], tindices[2] );\n        }\n        else{\n            mesh.addFace( vindices[0], vindices[1], vindices[2] );\n        }\n    }\n\n    return pmesh;\n}\n\n\nMesh::pointer refine( const Mesh & omesh, unsigned int maxFacesCount)\n{\n    auto pmesh(std::make_shared<geometry::Mesh>(omesh));\n    auto & mesh(*pmesh);\n\n    struct EdgeKey\n    {\n        std::size_t v1, v2; // vertex indices\n\n        EdgeKey(std::size_t v1, std::size_t v2)\n        {\n            this->v1 = std::min(v1, v2);\n            this->v2 = std::max(v1, v2);\n        }\n\n        bool operator< (const EdgeKey& other) const\n        {\n            return (v1 == other.v1) ? (v2 < other.v2) : (v1 < other.v1);\n        }\n    };\n\n    struct Edge {\n        typedef enum {\n            AB,\n            BC,\n            CA\n        } EdgeType;\n\n        std::size_t v1, v2;\n        int f1, f2;\n        EdgeType et1, et2;\n\n        float length;\n\n        Edge(std::size_t pv1, std::size_t pv2, float plength)\n            :v1(std::min(pv1,pv2)),v2(std::max(pv1,pv2)), length(plength){\n            f1 = -1;\n            f2 = -1;\n        }\n\n        void addFace(std::size_t pv1, std::size_t pv2, int fid, EdgeType type)\n        {\n            if(pv1<pv2){\n                f1=fid;\n                et1 = type;\n            }\n            else{\n                f2=fid;\n                et2 = type;\n            }\n        }\n\n        bool operator< (const Edge& other) const\n        {\n            return length < other.length;\n        }\n    };\n\n    struct EdgeMap {\n        std::map<EdgeKey, std::shared_ptr<Edge>> map;\n        std::vector<std::shared_ptr<Edge>> heap;\n\n        bool compareEdgePtr(const std::shared_ptr<Edge> &a, const std::shared_ptr<Edge> &b){\n            return a->length<b->length;\n        }\n\n        void addFaceEdge(std::size_t pv1, std::size_t pv2, int fid\n                         , Edge::EdgeType type, float length)\n        {\n            EdgeKey key(pv1, pv2);\n            auto it(map.find(key));\n            if(it!=map.end()){\n                it->second->addFace(pv1, pv2, fid, type );\n            }\n            else{\n                heap.push_back(std::make_shared<Edge>(pv1, pv2, length));\n                heap.back()->addFace(pv1, pv2, fid, type );\n                map.insert(std::make_pair(key,heap.back()));\n                std::push_heap(heap.begin(),heap.end(), [this]( const std::shared_ptr<Edge> &a\n                                                              , const std::shared_ptr<Edge> &b){\n                    return this->compareEdgePtr(a,b);\n                });\n            }\n        }\n\n        Edge pop_top_edge(){\n            auto edge = *heap[0];\n            std::pop_heap(heap.begin(), heap.end(), [this]( const std::shared_ptr<Edge> &a\n                                                          , const std::shared_ptr<Edge> &b){\n                return this->compareEdgePtr(a,b);\n            });\n            heap.pop_back();\n            map.erase(EdgeKey(edge.v1, edge.v2));\n            return edge;\n        }\n\n        Edge top_edge(){\n            return *heap[0];\n        }\n\n        void addFaceEdges(const Mesh & mesh, int fid){\n            const auto& f = mesh.faces[fid];\n            auto e1Length =  float(ublas::norm_2(mesh.vertices[f.a]-mesh.vertices[f.b]));\n            addFaceEdge(f.a, f.b, fid, Edge::EdgeType::AB, e1Length);\n\n            auto e2Length =  float(ublas::norm_2(mesh.vertices[f.b]-mesh.vertices[f.c]));\n            addFaceEdge(f.b, f.c, fid, Edge::EdgeType::BC, e2Length);\n\n            auto e3Length =  float(ublas::norm_2(mesh.vertices[f.c]-mesh.vertices[f.a]));\n            addFaceEdge(f.c, f.a, fid, Edge::EdgeType::CA, e3Length);\n        }\n\n        std::size_t size(){\n            return heap.size();\n        }\n\n    };\n\n    EdgeMap edgeMap;\n\n    auto splitEdge = [&mesh,&edgeMap]( int fid, Edge::EdgeType type\n                       , std::size_t vid) mutable -> void{\n        auto & face = mesh.faces[fid];\n        switch(type){\n            case Edge::EdgeType::AB:\n                {\n                    if(mesh.tCoords.size()>0){\n                        math::Point2 tcMiddle = ( mesh.tCoords[face.ta]\n                                                + mesh.tCoords[face.tb]) * 0.5;\n                        mesh.tCoords.push_back(tcMiddle);\n                    }\n                    mesh.addFace( mesh.faces[fid].b, mesh.faces[fid].c\n                                , vid\n                                , mesh.faces[fid].tb, mesh.faces[fid].tc\n                                , mesh.tCoords.size()-1);\n\n                    mesh.faces[fid].b = vid;\n                    mesh.faces[fid].tb = mesh.tCoords.size()-1;\n\n                    edgeMap.addFaceEdges(mesh, fid);\n                    edgeMap.addFaceEdges(mesh, int(mesh.faces.size()-1));\n                }\n                break;\n            case Edge::EdgeType::BC:\n                {\n                    if(mesh.tCoords.size()>0){\n                        math::Point2 tcMiddle = (mesh.tCoords[face.tb]\n                                                + mesh.tCoords[face.tc]) * 0.5;\n                        mesh.tCoords.push_back(tcMiddle);\n                    }\n                    mesh.addFace( mesh.faces[fid].c,mesh.faces[fid].a, vid\n                                , mesh.faces[fid].tc,mesh.faces[fid].ta\n                                , mesh.tCoords.size()-1);\n\n                    mesh.faces[fid].c = vid;\n                    mesh.faces[fid].tc = mesh.tCoords.size()-1;\n\n                    edgeMap.addFaceEdges(mesh, fid);\n                    edgeMap.addFaceEdges(mesh, int(mesh.faces.size()-1));\n                }\n                break;\n            case Edge::EdgeType::CA:\n                {\n                    if(mesh.tCoords.size()>0){\n                        math::Point2 tcMiddle = (mesh.tCoords[face.tc]\n                                                + mesh.tCoords[face.ta]) * 0.5;\n                        mesh.tCoords.push_back(tcMiddle);\n                    }\n\n                    mesh.addFace( mesh.faces[fid].a,mesh.faces[fid].b, vid\n                                , mesh.faces[fid].ta,mesh.faces[fid].tb\n                                , mesh.tCoords.size()-1);\n\n                    mesh.faces[fid].a = vid;\n                    mesh.faces[fid].ta = mesh.tCoords.size()-1;\n\n                    edgeMap.addFaceEdges(mesh, fid);\n                    edgeMap.addFaceEdges(mesh, int(mesh.faces.size()-1));\n                }\n                break;\n        }\n    };\n\n    for (std::size_t i=0; i<mesh.faces.size(); ++i ) {\n        //add all 3 edges\n        edgeMap.addFaceEdges(mesh, int(i));\n    }\n\n    //sort edges by length\n    while( mesh.faces.size() < maxFacesCount && edgeMap.size()>0 ){\n        //split edge\n        auto edge = edgeMap.pop_top_edge();\n\n        //find middle\n        math::Point3 middle = (mesh.vertices[edge.v1]\n                            + mesh.vertices[edge.v2]) * 0.5;\n        mesh.vertices.push_back(middle);\n\n        //split first face\n        if(edge.f1>=0){\n            splitEdge(edge.f1, edge.et1, mesh.vertices.size()-1);\n        }\n\n        //split second face\n        if(edge.f2>=0){\n            splitEdge(edge.f2, edge.et2, mesh.vertices.size()-1);\n        }\n    }\n\n    return pmesh;\n}\n\nMeshInfo measurePly(std::istream &is, const boost::filesystem::path &path)\n{\n    // read header\n    std::string line;\n    int nvert = -1, ntris = -1;\n    do {\n        if (getline(is, line).eof()) break;\n        std::sscanf(line.c_str(), \"element vertex %d\", &nvert);\n        std::sscanf(line.c_str(), \"element face %d\", &ntris);\n    } while (line != \"end_header\");\n\n    if (nvert < 0 || ntris < 0) {\n        LOGTHROW(err2, std::runtime_error)\n            << \"Unknown PLY format in file \" << path << \".\";\n    }\n\n    return MeshInfo(nvert, ntris);\n}\n\nvoid loadPly(ObjParserBase &parser, std::istream &is\n             , const boost::filesystem::path &path)\n{\n    const auto mi(measurePly(is, path));\n\n    // load points\n    ObjParserBase::Vector3d v;\n    for (std::size_t i = 0; i < mi.vertexCount; i++) {\n        is >> v.x >> v.y >> v.z;\n        parser.addVertex(v);\n    }\n\n    // load triangles\n    ObjParserBase::Facet f;\n    int n;\n    for (std::size_t i = 0; i < mi.faceCount; i++) {\n        is >> n >> f.v[0] >> f.v[1] >> f.v[2];\n        utility::expect(n == 3\n                        , \"Only triangles are supported in PLY files (&s).\"\n                        , path);\n        parser.addFacet(f);\n    }\n}\n\nMeshInfo measurePly(const boost::filesystem::path &path)\n{\n    std::ifstream f(path.string());\n    if (!f.good()) {\n        LOGTHROW(err2, std::runtime_error)\n            << \"Can't open PLY file \" << path << \".\";\n    }\n\n    f.exceptions(std::ios::badbit | std::ios::failbit);\n    const auto mi(measurePly(f, path));\n    f.close();\n\n    return mi;\n}\n\nbool objHasVertexOrFace(const boost::filesystem::path &path)\n{\n    bool hasVorF(false);\n\n    std::ifstream f(path.string());\n    if (!f.good()) {\n        LOGTHROW(err2, std::runtime_error)\n            << \"Can't open OBJ file \" << path << \".\";\n    }\n\n    f.exceptions(std::ios::badbit);\n\n    std::string line;\n    do {\n        getline(f, line);\n        if (f.eof()) break;\n        if (f.fail()) {\n            LOGTHROW(err2, std::runtime_error)\n                << \"Failbit when reading <\" << path << \">\";\n        }\n\n        if (line.empty()) continue;\n        if (line[0] == 'v' || line[0] == 'f') {\n            hasVorF = true;\n            break;\n        }\n    } while (true);\n    f.close();\n\n    return hasVorF;\n}\n\nvoid loadPly(ObjParserBase &parser, const boost::filesystem::path &path)\n{\n    std::ifstream f(path.string());\n    if (!f.good()) {\n        LOGTHROW(err2, std::runtime_error)\n            << \"Can't open PLY file \" << path << \".\";\n    }\n\n    f.exceptions(std::ios::badbit | std::ios::failbit);\n\n    loadPly(parser, f, path);\n\n    f.close();\n}\n\nvoid append(Mesh &mesh, const Mesh &added)\n{\n    // remember vertex indexing shift and append vertices\n    const auto vShift(mesh.vertices.size());\n    mesh.vertices.insert(mesh.vertices.end(), added.vertices.begin()\n                         , added.vertices.end());\n\n    // remember texturing coord indexing shift and append texturing coordinates\n    const auto tcShift(mesh.tCoords.size());\n    mesh.tCoords.insert(mesh.tCoords.end(), added.tCoords.begin()\n                        , added.tCoords.end());\n\n    // append faces with shifts applied\n    for (const auto &f : added.faces) {\n        mesh.addFace(f.a + vShift, f.b + vShift, f.c + vShift\n                     , f.ta + tcShift, f.tb + tcShift, f.tc + tcShift\n                     , f.imageId);\n    }\n}\n\nMesh::list splitById(const Mesh &mesh)\n{\n    typedef unsigned int ImageId;\n\n    struct MeshBuilder {\n        typedef std::unordered_map<ImageId, MeshBuilder> map;\n\n        typedef Face::index_type Index;\n\n        typedef std::unordered_map<Index, Index> VMap;\n\n        VMap vertices;\n        Mesh mesh;\n\n        Index vertex(const Mesh &m, Index v) {\n            auto fvertices(vertices.find(v));\n            if (fvertices == vertices.end()) {\n                auto nv(mesh.vertices.size());\n                mesh.vertices.push_back(m.vertices[v]);\n                fvertices = vertices.insert(VMap::value_type(v, nv)).first;\n            }\n            return fvertices->second;\n        }\n\n        void add(const Mesh &m, const Face &face) {\n            mesh.faces.emplace_back(vertex(m, face.a)\n                                    , vertex(m, face.b)\n                                    , vertex(m, face.c)\n                                    , 0, 0, 0, face.imageId);\n        }\n    };\n\n    MeshBuilder::map builders;\n    std::unordered_set<ImageId> unique;\n    for (const auto &face : mesh.faces) {\n        auto fbuilders(builders.find(face.imageId));\n        if (fbuilders == builders.end()) {\n            fbuilders\n                = builders.insert(MeshBuilder::map::value_type\n                                  (face.imageId, MeshBuilder())).first;\n        }\n        fbuilders->second.add(mesh, face);\n    }\n\n    Mesh::list out;\n    out.reserve(builders.size());\n    for (auto &builder : builders) {\n        out.push_back(std::move(builder.second.mesh));\n    }\n    return out;\n}\n\n} // namespace geometry\n", "meta": {"hexsha": "e525ba3d064ce644b84d190fa39d5fb672754fde", "size": 31909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry/meshop.cpp", "max_stars_repo_name": "Melown/libgeometry", "max_stars_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T19:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T06:52:15.000Z", "max_issues_repo_path": "geometry/meshop.cpp", "max_issues_repo_name": "Melown/libgeometry", "max_issues_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "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": "geometry/meshop.cpp", "max_forks_repo_name": "Melown/libgeometry", "max_forks_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6817307692, "max_line_length": 97, "alphanum_fraction": 0.5148077345, "num_tokens": 7845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.032589741359985346, "lm_q1q2_score": 0.00948299117064831}}
{"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 <iostream>\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 <RansacLib/hybrid_ransac.h>\n#include <RansacLib/ransac.h>\n#include \"hybrid_line_estimator.h\"\n\n// Generates a random transformation.\nvoid GenerateRandomTransform(Eigen::Matrix2d* R, Eigen::Vector2d* t) {\n  std::random_device rand_dev;\n  std::mt19937 rng(rand_dev());\n  std::uniform_real_distribution<double> distr(-0.5, 0.5);\n\n  const double kAngle = distr(rng) * M_PI;\n  *R << std::cos(kAngle), -std::sin(kAngle), std::sin(kAngle), std::cos(kAngle);\n  *t = Eigen::Vector2d(distr(rng) * 10.0, distr(rng) * 10.0);\n}\n\n// Assumes that inlier threshold << 0.5.\nvoid GenerateRandomInstance(const int num_inliers, const int num_outliers,\n                            double inlier_threshold, const Eigen::Matrix2d& R,\n                            const Eigen::Vector2d& t,\n                            Eigen::Matrix4Xd* points_with_normals) {\n  const int kNumPoints = num_inliers + num_outliers;\n  points_with_normals->resize(4, kNumPoints);\n\n  std::vector<int> indices(kNumPoints);\n  std::iota(indices.begin(), indices.end(), 0);\n\n  std::random_device rand_dev;\n  std::mt19937 rng(rand_dev());\n\n  std::shuffle(indices.begin(), indices.end(), rng);\n\n  // Generates num_inliers points along the x-axis in the interval [0, 1] with\n  // a y-value in the range (-inlier_threshold, inlier_threshold) choosen\n  // at random. All normals of the inliers are set to [0, 1]\n  std::uniform_real_distribution<double> distr(-inlier_threshold,\n                                               inlier_threshold);\n\n  const double kXStep = 1.0 / static_cast<double>(num_inliers);\n  double x = 0.0;\n  for (int i = 0; i < num_inliers; ++i, x += kXStep) {\n    const int kIndex = indices[i];\n    points_with_normals->col(kIndex)[0] = x;\n    while (true) {\n      points_with_normals->col(kIndex)[1] = distr(rng);\n      if (points_with_normals->col(kIndex)[1] > -inlier_threshold) {\n        break;\n      }\n    }\n    points_with_normals->col(kIndex)[2] = 0.0;\n    points_with_normals->col(kIndex)[3] = 1.0;\n  }\n\n  // Randomly generates outliers in the range [0, 1] x [-0.5, 0.5].\n  std::uniform_real_distribution<double> distr_x(0.0, 1.0);\n  std::uniform_real_distribution<double> distr_y(-0.5, 0.5);\n  for (int i = num_inliers; i < kNumPoints; ++i) {\n    double x = distr_x(rng);\n    double y = distr_y(rng);\n    while (std::fabs(y) < 5.0 * inlier_threshold) {\n      y = distr_y(rng);\n    }\n\n    const int kIndex = indices[i];\n    points_with_normals->col(kIndex)[0] = x;\n    points_with_normals->col(kIndex)[1] = y;\n\n    points_with_normals->col(kIndex)[2] = 0.0;\n    points_with_normals->col(kIndex)[3] = 0.0;\n    while (points_with_normals->col(kIndex).tail<2>().norm() < 0.5) {\n      points_with_normals->col(kIndex)[2] = distr_y(rng);\n      points_with_normals->col(kIndex)[3] = distr_y(rng);\n      points_with_normals->col(kIndex).tail<2>().normalize();\n    }\n  }\n\n  // Rotates and translates the points.\n  for (int i = 0; i < kNumPoints; ++i) {\n    Eigen::Vector2d p = R * points_with_normals->col(i).head<2>() + t;\n    points_with_normals->col(i).head<2>() = p;\n    Eigen::Vector2d n = R * points_with_normals->col(i).tail<2>();\n    points_with_normals->col(i).tail<2>() = n;\n  }\n}\n\nint main(int argc, char** argv) {\n  ransac_lib::HybridLORansacOptions options;\n  options.min_num_iterations_ = 100u;\n  options.max_num_iterations_ = 10000u;\n  options.max_num_iterations_per_solver_ = 1000u;\n  options.squared_inlier_thresholds_ = {0.01 * 0.01, 0.01 * 0.01};\n  options.data_type_weights_ = {2.0, 0.5};\n\n  std::random_device rand_dev;\n  options.random_seed_ = rand_dev();\n\n  // Generates random instances for outlier ratios 10%, 20%, 30%, ..., 90%,\n  // and then applies HybridRANSAC on it.\n  const int kNumDataPoints = 100;\n  const int kNumDataPointsWithNormals = 100;\n  std::vector<double> outlier_ratios = {0.1, 0.2, 0.3, 0.4, 0.5,\n                                        0.6, 0.7, 0.8, 0.9};\n  for (const double outlier_ratio : outlier_ratios) {\n    std::cout << \" Inlier ratio: \" << 1.0 - outlier_ratio << std::endl;\n    int num_outliers_points =\n        static_cast<int>(static_cast<double>(kNumDataPoints) * outlier_ratio);\n    int num_inliers_points = kNumDataPoints - num_outliers_points;\n\n    Eigen::Matrix2d R;\n    Eigen::Vector2d t;\n    GenerateRandomTransform(&R, &t);\n\n    Eigen::Matrix4Xd data;\n    GenerateRandomInstance(num_inliers_points, num_outliers_points, 0.5 * 0.01,\n                           R, t, &data);\n    Eigen::Matrix2Xd points(2, data.cols());\n    points.row(0) = data.row(0);\n    points.row(1) = data.row(1);\n\n    int num_outliers_points_with_normals = static_cast<int>(\n        static_cast<double>(kNumDataPointsWithNormals) * outlier_ratio);\n    int num_inliers_points_with_normals =\n        kNumDataPointsWithNormals - num_outliers_points_with_normals;\n\n    GenerateRandomInstance(num_inliers_points_with_normals,\n                           num_outliers_points_with_normals, 0.5 * 0.01, R, t,\n                           &data);\n    Eigen::Matrix4Xd points_with_normals = data;\n    std::cout << \"   ... instance generated\" << std::endl;\n\n    std::vector<double> prior_probabilities = {0.2, 0.8};\n    ransac_lib::HybridLineEstimator solver(points, points_with_normals,\n                                           prior_probabilities);\n    ransac_lib::HybridLocallyOptimizedMSAC<Eigen::Vector3d,\n                                           std::vector<Eigen::Vector3d>,\n                                           ransac_lib::HybridLineEstimator>\n        lomsac;\n    ransac_lib::HybridRansacStatistics ransac_stats;\n\n    std::cout << \"   ... running LOMSAC\" << std::endl;\n    Eigen::Vector3d best_model;\n    int num_ransac_inliers =\n        lomsac.EstimateModel(options, solver, &best_model, &ransac_stats);\n    std::cout << \"   ... LOMSAC found \" << num_ransac_inliers << \" inliers in \"\n              << ransac_stats.num_iterations_per_solver[0]\n              << \" iterations of solver 0 and \"\n              << ransac_stats.num_iterations_per_solver[1]\n              << \" iterations of solver 1 with inlier ratios of \"\n              << ransac_stats.inlier_ratios[0] << \" and \"\n              << ransac_stats.inlier_ratios[1] << std::endl;\n  }\n}\n", "meta": {"hexsha": "7fe8a03cb3537c8bcbcc556d3f044a094d30bba9", "size": 8055, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/hybrid_line_estimation.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_estimation.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_estimation.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": 41.0969387755, "max_line_length": 80, "alphanum_fraction": 0.6643078833, "num_tokens": 2156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.022629198096809116, "lm_q1q2_score": 0.009474775304331563}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (c) 2021, Andrew Kennings\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\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// Description:\n// An implementation of maximum independent set matching to reduce either\n// wirelength of displacement.\n//\n// The idea is to color the nodes (for wirelength).  Then, one can solve\n// a matching problem to optimize for wirelength.  Nodes with the same\n// color do not share nets so they can be repositioned without worsening\n// wirelength.  Note that for displacement optimization, colors are not\n// needed.\n//\n// There are likely many improvements which can be made to this code\n// regarding the selection of nodes, etc.\n\n#include \"detailed_mis.h\"\n#include <lemon/cost_scaling.h>\n#include <lemon/cycle_canceling.h>\n#include <lemon/list_graph.h>\n#include <lemon/preflow.h>\n#include <lemon/network_simplex.h>\n#include <lemon/smart_graph.h>\n#include <boost/format.hpp>\n#include <boost/tokenizer.hpp>\n#include <deque>\n#include <set>\n#include <vector>\n#include \"architecture.h\"\n#include \"color.h\"\n#include \"detailed_manager.h\"\n#include \"detailed_segment.h\"\n#include \"network.h\"\n#include \"router.h\"\n#include \"utl/Logger.h\"\n\nusing utl::DPO;\n\nnamespace dpo {\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nclass DetailedMis::Bucket {\n public:\n  virtual ~Bucket() {}\n\n  void clear() { m_nodes.clear(); }\n\n  std::deque<Node*> m_nodes;\n  double m_xmin = 0.0;\n  double m_xmax = 0.0;\n  double m_ymin = 0.0;\n  double m_ymax = 0.0;\n  int m_i = 0;\n  int m_j = 0;\n  int m_travId = 0;\n};\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nDetailedMis::DetailedMis(Architecture* arch, Network* network,\n                         RoutingParams* rt)\n    : m_mgrPtr(0),\n      m_arch(arch),\n      m_network(network),\n      m_rt(rt),\n      m_dimW(0),\n      m_dimH(0),\n      m_stepX(0.0),\n      m_stepY(0.0),\n      m_skipEdgesLargerThanThis(100),\n      m_maxProblemSize(25),\n      m_traversal(0),\n      m_useSameSize(true),\n      m_useSameColor(true),\n      m_maxTimesUsed(2),\n      m_obj(DetailedMis::Hpwl) {}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\nDetailedMis::~DetailedMis() { clearGrid(); }\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::run(DetailedMgr* mgrPtr, std::string command) {\n  // A temporary interface to allow for a string which we will decode to create\n  // the arguments.\n  std::string scriptString = command;\n  boost::char_separator<char> separators(\" \\r\\t\\n;\");\n  boost::tokenizer<boost::char_separator<char> > tokens(scriptString,\n                                                        separators);\n  std::vector<std::string> args;\n  for (boost::tokenizer<boost::char_separator<char> >::iterator it =\n           tokens.begin();\n       it != tokens.end(); it++) {\n    args.push_back(*it);\n  }\n  run(mgrPtr, args);\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::run(DetailedMgr* mgrPtr, std::vector<std::string>& args) {\n  // Given the arguments, figure out which routine to run to do the reordering.\n\n  m_mgrPtr = mgrPtr;\n\n  // Defaults.\n  m_obj = DetailedMis::Hpwl;\n\n  int passes = 1;\n  double tol = 0.01;\n  for (size_t i = 1; i < args.size(); i++) {\n    if (args[i] == \"-p\" && i + 1 < args.size()) {\n      passes = std::atoi(args[++i].c_str());\n    } else if (args[i] == \"-t\" && i + 1 < args.size()) {\n      tol = std::atof(args[++i].c_str());\n    } else if (args[i] == \"-d\") {\n      m_obj = DetailedMis::Disp;\n    }\n  }\n  tol = std::max(tol, 0.01);\n  passes = std::max(passes, 1);\n\n  double last_hpwl, curr_hpwl, init_hpwl, hpwl_x, hpwl_y;\n  double last_disp, curr_disp, init_disp, tot_disp, max_disp, avg_disp;\n  double curr_obj, curr_imp;\n  std::string obj =\n      (m_obj == DetailedMis::Hpwl) ? \"wirelength\" : \"displacement\";\n  m_mgrPtr->getLogger()->info(DPO, 300, \"Set matching objective is {:s}.\",\n                              obj.c_str());\n\n  // If using displacement objective, then it isn't required to use colors.\n  if (m_obj == DetailedMis::Disp) {\n    m_useSameColor = false;\n  }\n\n  m_mgrPtr->resortSegments();\n  curr_hpwl = Utility::hpwl(m_network, hpwl_x, hpwl_y);\n  init_hpwl = curr_hpwl;\n\n  curr_disp = Utility::disp_l1(m_network, tot_disp, max_disp, avg_disp);\n  init_disp = curr_disp;\n\n  // Do some things that only need to be done once regardless\n  // of the number of passes.\n  collectMovableCells(); // Movable cells.\n  colorCells(); // Color the cells.\n  buildGrid(); // Grid for searching for neigbours.\n\n  for (int p = 1; p <= passes; p++) {\n    curr_obj = (m_obj == DetailedMis::Hpwl) ? curr_hpwl : curr_disp;\n\n    m_mgrPtr->getLogger()->info(\n        DPO, 301, \"Pass {:3d} of matching; objective is {:.6e}.\", p, curr_obj);\n\n    // Run the algo here...\n    place();\n\n    last_hpwl = curr_hpwl;\n    curr_hpwl = Utility::hpwl(m_network, hpwl_x, hpwl_y);\n    if (m_obj == DetailedMis::Hpwl &&\n        std::fabs(curr_hpwl - last_hpwl) / last_hpwl <= tol) {\n      break;\n    }\n    last_disp = curr_disp;\n    curr_disp = Utility::disp_l1(m_network, tot_disp, max_disp, avg_disp);\n    if (m_obj == DetailedMis::Disp &&\n        std::fabs(curr_disp - last_disp) / last_disp <= tol) {\n      break;\n    }\n  }\n  m_mgrPtr->resortSegments();\n\n  double hpwl_imp = (((init_hpwl - curr_hpwl) / init_hpwl) * 100.);\n  double disp_imp = (((init_disp - curr_disp) / init_disp) * 100.);\n  curr_imp = (m_obj == DetailedMis::Hpwl) ? hpwl_imp : disp_imp;\n  curr_obj = (m_obj == DetailedMis::Hpwl) ? curr_hpwl : curr_disp;\n  m_mgrPtr->getLogger()->info(\n      DPO, 302,\n      \"End of matching; objective is {:.6e}, improvement is {:.2f} percent.\",\n      curr_obj, curr_imp);\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::place() {\n  // Populate the grid.  Used for searching.\n  populateGrid();\n\n  m_timesUsed.resize(m_network->getNumNodes() );\n  std::fill(m_timesUsed.begin(), m_timesUsed.end(), 0);\n\n  // Select candidates and solve matching problem.  Note that we need to do\n  // something to make this more efficient, otherwise we will solve way too\n  // many problems for larger circuits.  I think one effective idea is to\n  // keep track of how many problems a candidate cell has been involved in;\n  // if it has been involved is >= a certain number of problems, it has \"had\n  // some chance\" to be moved, so skip it.\n  Utility::random_shuffle(m_candidates.begin(), m_candidates.end(),\n                          m_mgrPtr->m_rng);\n  for (size_t i = 0; i < m_candidates.size(); i++) {\n    // Pick a candidate as a seed.\n    Node* ndi = m_candidates[i];\n\n    // Skip seed if it has been used already.\n    if (m_timesUsed[ndi->getId()] >= m_maxTimesUsed) {\n      continue;\n    }\n\n    // Get other cells within the vicinity.\n    if (!gatherNeighbours(ndi)) {\n      continue;\n    }\n\n    // Solve the flow.\n    solveMatch();\n\n    // Increment times each node has been used.\n    for (size_t j = 0; j < m_neighbours.size(); j++) {\n      Node* ndj = m_neighbours[j];\n      ++m_timesUsed[ndj->getId()];\n    }\n\n    // Update grid?  Or, do we need to even bother?\n    ;\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::collectMovableCells() {\n  m_candidates.erase(m_candidates.begin(), m_candidates.end());\n  m_candidates.insert(m_candidates.end(), m_mgrPtr->m_singleHeightCells.begin(),\n                      m_mgrPtr->m_singleHeightCells.end());\n  for (size_t i = 2; i < m_mgrPtr->m_multiHeightCells.size(); i++) {\n    m_candidates.insert(m_candidates.end(),\n                        m_mgrPtr->m_multiHeightCells[i].begin(),\n                        m_mgrPtr->m_multiHeightCells[i].end());\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::colorCells() {\n\n  m_colors.resize(m_network->getNumNodes() );\n  std::fill(m_colors.begin(), m_colors.end(), -1);\n\n  m_movable.resize(m_network->getNumNodes() );\n  std::fill(m_movable.begin(), m_movable.end(), false);\n  for (size_t i = 0; i < m_candidates.size(); i++) {\n    Node* ndi = m_candidates[i];\n    m_movable[ndi->getId()] = true;\n  }\n\n  Graph gr(m_network->getNumNodes() );\n  for (int e = 0; e < m_network->getNumEdges(); e++) {\n    Edge* edi = m_network->getEdge(e);\n\n    int numPins = edi->getPins().size();\n    if (numPins <= 1 || numPins > m_skipEdgesLargerThanThis) {\n      continue;\n    }\n\n    for (int pi = 0; pi < edi->getPins().size(); pi++) {\n      Pin* pini = edi->getPins()[pi];\n      Node* ndi = pini->getNode();\n      if (!m_movable[ndi->getId()]) {\n        continue;\n      }\n\n      for (int pj = pi + 1; pj < edi->getPins().size(); pj++) {\n        Pin* pinj = edi->getPins()[pj];\n        Node* ndj = pinj->getNode();\n        if (!m_movable[ndj->getId()]) {\n          continue;\n        }\n        if (ndj == ndi) {\n          continue;\n        }\n\n        gr.addEdge(ndi->getId(), ndj->getId());\n      }\n    }\n  }\n\n  // The actual coloring.\n  gr.removeDuplicates();\n  gr.greedyColoring();\n\n  std::vector<int> hist;\n  for (size_t i = 0; i < m_network->getNumNodes() ; i++) {\n    Node* ndi = m_network->getNode(i);\n\n    int color = gr.getColor(i);\n    if (color < 0 || color >= gr.getNColors()) {\n      m_mgrPtr->internalError( \"Unable to color cells during matching\" );\n    }\n    if (m_movable[ndi->getId()]) {\n      m_colors[ndi->getId()] = color;\n\n      if (color >= hist.size()) {\n        hist.resize(color + 1, 0);\n      }\n      ++hist[color];\n    }\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::buildGrid() {\n  // Builds a coarse grid over the placement region for locating cells.\n  m_traversal = 0;\n\n  double xmin = m_arch->getMinX();\n  double xmax = m_arch->getMaxX();\n  double ymin = m_arch->getMinY();\n  double ymax = m_arch->getMaxY();\n\n  // Design each grid bin to hold a few hundred cells.  Do this based on the\n  // average width and height of the cells.\n  double avgH = 0.;\n  double avgW = 0.;\n  double avgA = 0.;\n  for (size_t i = 0; i < m_candidates.size(); i++) {\n    Node* ndi = m_candidates[i];\n    avgH += ndi->getHeight();\n    avgW += ndi->getWidth();\n    avgA += ndi->getHeight() * ndi->getWidth();\n  }\n  avgH /= (double)m_candidates.size();\n  avgW /= (double)m_candidates.size();\n  avgA /= (double)m_candidates.size();\n\n  m_stepX = avgW * std::sqrt(m_maxProblemSize);\n  m_stepY = avgH * std::sqrt(m_maxProblemSize);\n\n  m_dimW = (int)std::ceil((xmax - xmin) / m_stepX);\n  m_dimH = (int)std::ceil((ymax - ymin) / m_stepY);\n\n  clearGrid();\n  m_grid.resize(m_dimW);\n  for (size_t i = 0; i < m_grid.size(); i++) {\n    m_grid[i].resize(m_dimH);\n    for (size_t j = 0; j < m_grid[i].size(); j++) {\n      m_grid[i][j] = new Bucket;\n      m_grid[i][j]->m_xmin = xmin + (i)*m_stepX;\n      m_grid[i][j]->m_xmax = xmin + (i + 1) * m_stepX;\n      m_grid[i][j]->m_ymin = ymin + (j)*m_stepY;\n      m_grid[i][j]->m_ymax = ymin + (j + 1) * m_stepY;\n      m_grid[i][j]->m_i = i;\n      m_grid[i][j]->m_j = j;\n      m_grid[i][j]->m_travId = m_traversal;\n    }\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::populateGrid() {\n  // Inserts movable cells into the grid.\n\n  for (size_t i = 0; i < m_grid.size(); i++) {\n    for (size_t j = 0; j < m_grid[i].size(); j++) {\n      m_grid[i][j]->clear();\n    }\n  }\n\n  double xmin = m_arch->getMinX();\n  double ymin = m_arch->getMinY();\n\n  // Insert cells into the constructed grid.\n  m_cellToBinMap.clear();\n  for (size_t n = 0; n < m_candidates.size(); ++n) {\n    Node* ndi = m_candidates[n];\n\n    int i = std::max(\n        std::min((int)((ndi->getX() - xmin) / m_stepX), m_dimW - 1), 0);\n    int j = std::max(\n        std::min((int)((ndi->getY() - ymin) / m_stepY), m_dimH - 1), 0);\n\n    m_grid[i][j]->m_nodes.push_back(ndi);\n    m_cellToBinMap[ndi] = m_grid[i][j];\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::clearGrid()\n// Clear out any old grid.  The dimensions of the grid are also stored in the\n// class...\n{\n  for (size_t i = 0; i < m_grid.size(); i++) {\n    for (size_t j = 0; j < m_grid[i].size(); j++) {\n      delete m_grid[i][j];\n    }\n    m_grid[i].clear();\n  }\n  m_grid.clear();\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nbool DetailedMis::gatherNeighbours(Node* ndi) {\n  double singleRowHeight = m_arch->getRow(0)->getHeight();\n\n  m_neighbours.clear();\n  m_neighbours.push_back(ndi);\n\n  std::map<Node*, Bucket*>::iterator it;\n\n  // Scan the grid structure gathering up cells which are compatible with the\n  // current cell.\n\n  if (m_cellToBinMap.end() == (it = m_cellToBinMap.find(ndi))) {\n    return false;\n  }\n\n  int spanned_i = (int)(ndi->getHeight() / singleRowHeight + 0.5);\n\n  std::deque<Bucket*> Q;\n  Q.push_back(it->second);\n  ++m_traversal;\n  while (Q.size() > 0) {\n    Bucket* currPtr = Q.front();\n    Q.pop_front();\n\n    if (currPtr->m_travId == m_traversal) {\n      continue;\n    }\n    currPtr->m_travId = m_traversal;\n\n    // Scan all the cells in this bucket.  If they are compatible with the\n    // original cell, then add them to the neighbour list.\n    for (size_t j = 0; j < currPtr->m_nodes.size(); j++) {\n      Node* ndj = currPtr->m_nodes[j];\n\n      int spanned_j = (int)(ndj->getHeight() / singleRowHeight + 0.5);\n\n      // Check to make sure the cell is not the original, that they have\n      // the same region, that they have the same size (if applicable),\n      // and that they have the same color (if applicable).\n      bool compat = true;\n      if (compat) {\n        // Same node!\n        if (ndj == ndi) {\n          compat = false;\n        }\n      }\n      if (compat) {\n        // Must be the same color to avoid sharing nets.\n        if (m_useSameColor &&\n            m_colors[ndi->getId()] != m_colors[ndj->getId()]) {\n          compat = false;\n        }\n      }\n      if (compat) {\n        // Must be the same size.\n        if (m_useSameSize && (ndi->getWidth() != ndj->getWidth() ||\n                              ndi->getHeight() != ndj->getHeight())) {\n          compat = false;\n        }\n      }\n      if (compat) {\n        // Must span the same number of rows and also be voltage compatible.\n        if (spanned_i != spanned_j ||\n            ndi->getBottomPower() != ndj->getBottomPower() ||\n            ndi->getTopPower() != ndj->getTopPower()) {\n          compat = false;\n        }\n      }\n      if (compat) {\n        // Must be in the same region.\n        if (ndj->getRegionId() != ndi->getRegionId()) {\n          compat = false;\n        }\n      }\n\n      // If compatible, include this current cell.\n      if (compat) {\n        m_neighbours.push_back(ndj);\n      }\n    }\n\n    if (m_neighbours.size() >= m_maxProblemSize) {\n      break;\n    }\n\n    // Add more bins to the queue if we have not yet collected enough cells.\n    if (currPtr->m_i - 1 >= 0)\n      Q.push_back(m_grid[currPtr->m_i - 1][currPtr->m_j]);\n    if (currPtr->m_i + 1 <= m_dimW - 1)\n      Q.push_back(m_grid[currPtr->m_i + 1][currPtr->m_j]);\n    if (currPtr->m_j - 1 >= 0)\n      Q.push_back(m_grid[currPtr->m_i][currPtr->m_j - 1]);\n    if (currPtr->m_j + 1 <= m_dimH - 1)\n      Q.push_back(m_grid[currPtr->m_i][currPtr->m_j + 1]);\n  }\n  return true;\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\nvoid DetailedMis::solveMatch() {\n  if (m_neighbours.size() <= 1) {\n    return;\n  }\n  std::vector<Node*>& nodes = m_neighbours;\n  double singleRowHeight = m_arch->getRow(0)->getHeight();\n\n  int nNodes = (int)nodes.size();\n  int nSpots = (int)nodes.size();\n  std::vector<std::pair<double, double> >\n      pos;  // Original location of each node.\n  pos.resize(nNodes);\n  std::vector<std::vector<DetailedSeg*> >\n      seg;  // Original segments for each node.\n  seg.resize(nNodes);\n  for (size_t i = 0; i < nodes.size(); i++) {\n    Node* ndi = nodes[i];\n    pos[i] = std::make_pair(ndi->getX(), ndi->getY());     // COPY!\n    seg[i] = m_mgrPtr->m_reverseCellToSegs[ndi->getId()];  // COPY!\n  }\n\n  lemon::ListDigraph g;\n  std::vector<lemon::ListDigraph::Node> nodeForCell;\n  std::vector<lemon::ListDigraph::Node> nodeForSpot;\n  nodeForCell.resize(nNodes);\n  nodeForSpot.resize(nNodes);\n  for (size_t i = 0; i < nodes.size(); i++) {\n    nodeForCell[i] = g.addNode();\n    nodeForSpot[i] = g.addNode();\n  }\n  lemon::ListDigraph::Node supplyNode = g.addNode();\n  lemon::ListDigraph::Node demandNode = g.addNode();\n\n  // Hook up the graph.\n  lemon::ListDigraph::ArcMap<int> l_i(g);  // Lower bound on flow.\n  lemon::ListDigraph::ArcMap<int> u_i(g);  // Upper bound on flow.\n  lemon::ListDigraph::ArcMap<int> c_i(g);  // Cost of flow.\n\n  std::map<lemon::ListDigraph::Arc, std::pair<int, int> > reverseMap;\n\n  int origCost = 0, icost;\n  for (int i = 0; i < nNodes; i++) {\n    // Supply to node.\n    lemon::ListDigraph::Arc arc_sv = g.addArc(supplyNode, nodeForCell[i]);\n    l_i[arc_sv] = 0;\n    u_i[arc_sv] = 1;\n    c_i[arc_sv] = 0;\n\n    // Spot to demand.\n    lemon::ListDigraph::Arc arc_vt = g.addArc(nodeForSpot[i], demandNode);\n    l_i[arc_vt] = 0;\n    u_i[arc_vt] = 1;\n    c_i[arc_vt] = 0;\n\n    // Nodes to spots.\n    Node* ndi = nodes[i];\n    for (int j = 0; j < nSpots; j++) {\n      icost = 0;\n      if (m_obj == DetailedMis::Hpwl) {\n        icost = (int)getHpwl(ndi, pos[j].first, pos[j].second);\n      } else {\n        icost = (int)getDisp(ndi, pos[j].first, pos[j].second);\n      }\n      origCost += (i != j) ? 0 : icost;\n\n      bool addEdge = true;\n      // Reasons to skip the edge?\n      ;\n\n      // Add the edge if its okay.\n      if (addEdge) {\n        // Node to spot.\n        lemon::ListDigraph::Arc arc_vu =\n            g.addArc(nodeForCell[i], nodeForSpot[j]);\n        l_i[arc_vu] = 0;\n        u_i[arc_vu] = 1;\n        c_i[arc_vu] = icost;\n\n        reverseMap[arc_vu] = std::make_pair(i, j);\n      }\n    }\n  }\n  // Try max flow.\n  lemon::Preflow<lemon::ListDigraph> preflow(g, u_i, supplyNode, demandNode);\n  preflow.run();\n  int maxFlow = preflow.flowValue();\n  if (maxFlow != nNodes) {\n    return;\n  }\n  // Find mincost flow.\n  //lemon::CycleCanceling<lemon::ListDigraph> mincost(g);\n  lemon::NetworkSimplex<lemon::ListDigraph> mincost(g);\n  mincost.lowerMap(l_i);\n  mincost.upperMap(u_i);\n  mincost.costMap(c_i);\n  mincost.stSupply(supplyNode, demandNode, maxFlow);\n  //lemon::CycleCanceling<lemon::ListDigraph>::ProblemType ret = mincost.run();\n  lemon::NetworkSimplex<lemon::ListDigraph>::ProblemType ret = mincost.run();\n  if (ret != lemon::NetworkSimplex<lemon::ListDigraph>::OPTIMAL) {\n    return;\n  }\n\n  // Get the solution and assign nodes to new spots.  We also need to update the\n  // assignment of cells to segments!  I _believe_ it should be fine to go cell\n  // by cell and remove, reposition and update segment assignments one-by-one.\n  //\n  // This is somewhat tricky.  We need to use the target spot to figure out the\n  // segments into which the cell needs to be replaced.\n\n  lemon::ListDigraph::ArcMap<int> flow(g);\n  mincost.flowMap(flow);\n  int supplyFlow = 0;\n  int demandFlow = 0;\n  int finalCost = 0;\n  int nMoved = 0;\n\n  for (lemon::ListDigraph::ArcMap<int>::ItemIt it(flow); it != lemon::INVALID;\n       ++it) {\n    if (g.target(it) == demandNode) {\n      demandFlow += mincost.flow(it);\n    }\n    if (g.source(it) == supplyNode) {\n      supplyFlow += mincost.flow(it);\n    }\n\n    if (g.target(it) != demandNode && g.source(it) != supplyNode &&\n        mincost.flow(it) != 0) {\n      std::map<lemon::ListDigraph::Arc, std::pair<int, int> >::iterator it1 =\n          reverseMap.find(it);\n      if (reverseMap.end() == it1) {\n        m_mgrPtr->internalError( \"Unable to interpret flow during matching\" );\n      }\n\n      int i = it1->second.first;\n      int j = it1->second.second;\n\n      // If cell \"i\" is assigned to location \"i\", it means that it has not\n      // moved. We don't need to remove and reinsert it...\n\n      Node* ndi = nodes[i];\n      Node* ndj =\n          nodes[j];  // We effectively \"moved\" into this cells's location.\n      int spanned_i = (int)(ndi->getHeight() / singleRowHeight + 0.5);\n      int spanned_j = (int)(ndj->getHeight() / singleRowHeight + 0.5);\n\n      if (ndi != ndj) {\n        ++nMoved;\n        if (spanned_i != spanned_j ||\n            ndi->getWidth() != ndj->getWidth() ||\n            ndi->getHeight() != ndj->getHeight()) {\n          m_mgrPtr->internalError( \"Unable to interpret flow during matching\" );\n        }\n\n        // Remove cell \"i\" from its old segments.\n        std::vector<DetailedSeg*>& old_segs = seg[i];\n        if (spanned_i != old_segs.size()) {\n          // This means an error someplace else...\n          m_mgrPtr->internalError( \"Unable to interpret flow during matching\" );\n        }\n        for (size_t s = 0; s < old_segs.size(); s++) {\n          DetailedSeg* segPtr = old_segs[s];\n          int segId = segPtr->getSegId();\n          m_mgrPtr->removeCellFromSegment(ndi, segId);\n        }\n\n        // Update the postion of cell \"i\".\n        ndi->setX(pos[j].first);\n        ndi->setY(pos[j].second);\n\n        // Determine new segments and add cell \"i\" to its new segments.\n        std::vector<DetailedSeg*>& new_segs = seg[j];\n        if (spanned_i != new_segs.size()) {\n          // Not setup for non-same size stuff right now.\n          m_mgrPtr->internalError( \"Unable to interpret flow during matching\" );\n        }\n        for (size_t s = 0; s < new_segs.size(); s++) {\n          DetailedSeg* segPtr = new_segs[s];\n          int segId = segPtr->getSegId();\n          m_mgrPtr->addCellToSegment(ndi, segId);\n        }\n      }\n\n      icost = 0;\n      if (m_obj == DetailedMis::Hpwl) {\n        icost = (int)getHpwl(ndi, pos[j].first, pos[j].second);\n      } else {\n        icost = (int)getDisp(ndi, pos[j].first, pos[j].second);\n      }\n      finalCost += icost;\n    }\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\ndouble DetailedMis::getDisp(Node* ndi, double xi, double yi) {\n  // Compute displacement of cell ndi if placed at (xi,y1) from its orig pos.\n  double dx = std::fabs(xi - ndi->getOrigX());\n  double dy = std::fabs(yi - ndi->getOrigY());\n  return dx + dy;\n}\n\n//////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////\ndouble DetailedMis::getHpwl(Node* ndi, double xi, double yi) {\n  // Compute the HPWL of nets connected to ndi assuming ndi is at the\n  // specified (xi,yi).\n\n  double hpwl = 0.;\n  double x, y, l, r, b, t;\n  for (int pi = 0; pi < ndi->getPins().size(); pi++) {\n    Pin* pini = ndi->getPins()[pi];\n\n    Edge* edi = pini->getEdge();\n\n    int npins = edi->getPins().size();\n    if (npins <= 1 || npins > m_skipEdgesLargerThanThis) {\n      continue;\n    }\n\n    l = std::numeric_limits<double>::max();\n    r = std::numeric_limits<double>::lowest();\n    b = std::numeric_limits<double>::max();\n    t = std::numeric_limits<double>::lowest();\n\n    for (int pj = 0; pj < edi->getPins().size(); pj++) {\n      Pin* pinj = edi->getPins()[pj];\n\n      Node* ndj = pinj->getNode();\n\n      x = (ndj == ndi) ? (xi + pinj->getOffsetX())\n                       : (ndj->getX() + pinj->getOffsetX());\n      y = (ndj == ndi) ? (yi + pinj->getOffsetY())\n                       : (ndj->getY() + pinj->getOffsetY());\n\n      l = std::min(l, x);\n      r = std::max(r, x);\n      b = std::min(b, y);\n      t = std::max(t, y);\n    }\n    if (r >= l && t >= b) {\n      hpwl += ((r - l) + (t - b));\n    }\n  }\n\n  return hpwl;\n}\n\n}  // namespace dpo\n", "meta": {"hexsha": "cb423e6eaf8d5dabf7b3dec783f2d9e769b29184", "size": 26403, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/dpo/src/detailed_mis.cxx", "max_stars_repo_name": "gatecat/OpenROAD", "max_stars_repo_head_hexsha": "cd7a2f497c69a77dc056e8b966daa5de7d211a58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T17:56:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T17:56:46.000Z", "max_issues_repo_path": "src/dpo/src/detailed_mis.cxx", "max_issues_repo_name": "gatecat/OpenROAD", "max_issues_repo_head_hexsha": "cd7a2f497c69a77dc056e8b966daa5de7d211a58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dpo/src/detailed_mis.cxx", "max_forks_repo_name": "gatecat/OpenROAD", "max_forks_repo_head_hexsha": "cd7a2f497c69a77dc056e8b966daa5de7d211a58", "max_forks_repo_licenses": ["BSD-3-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.6343949045, "max_line_length": 82, "alphanum_fraction": 0.5453546945, "num_tokens": 6972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.02096423928891515, "lm_q1q2_score": 0.009421174723595199}}
{"text": "//////////////////////////////////////////////////////////////////////\n// This file is distributed under the University of Illinois/NCSA Open Source\n// License.  See LICENSE file in top directory for details.\n//\n// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.\n//\n// File developed by:\n// Miguel A. Morales, moralessilva2@llnl.gov\n//    Lawrence Livermore National Laboratory\n//\n// File created by:\n// Miguel A. Morales, moralessilva2@llnl.gov\n//    Lawrence Livermore National Laboratory\n////////////////////////////////////////////////////////////////////////////////\n\n#ifndef QMCPLUSPLUS_AFQMC_EXCITATIONS_HPP\n#define QMCPLUSPLUS_AFQMC_EXCITATIONS_HPP\n\n#include <boost/iterator/iterator_facade.hpp>\n#include <map>\n#include \"AFQMC/config.h\"\n#include \"AFQMC/Matrix/array_of_sequences.hpp\"\n\nnamespace qmcplusplus\n{\nnamespace afqmc\n{\n// CHEAT!!!\ntemplate<class TP, class integer>\nsize_t get_index(TP const& tp_, integer loc)\n{\n  if (loc == 0)\n    return size_t(std::get<0>(tp_));\n  else if (loc == 1)\n    return size_t(std::get<1>(tp_));\n  else\n    throw std::runtime_error(\" Error in qmcplusplus::afqmc::get_index<TP,integer>(). \\n\");\n}\n\ntemplate<class Vector>\nvoid push_excitation(Vector const& abij, Vector& v)\n{\n  if (abij.size() == 0)\n    return;\n  assert(v.size() % abij.size() == 0);\n  size_t n = abij.size();\n  for (typename Vector::iterator it = v.begin(); it < v.end(); it += n)\n    if (std::equal(abij.begin(), abij.end(), it))\n      return;\n  v.insert(v.end(), abij.begin(), abij.end());\n}\n\ntemplate<class Vector>\nsize_t find_excitation(Vector const& abij, Vector& v)\n{\n  if (abij.size() == 0)\n    return 0; // this assumes that the reference is 0\n  assert(v.size() % abij.size() == 0);\n  size_t n   = abij.size();\n  size_t loc = 0;\n  for (typename Vector::iterator it = v.begin(); it < v.end(); it += n, loc++)\n    if (std::equal(abij.begin(), abij.end(), it))\n      return loc;\n  APP_ABORT(\"Error: Sequence not found in find_excitation.\\n\");\n  return 0;\n}\n\ntemplate<class excitations>\nstd::map<int, int> find_active_space(bool single_list, excitations const& abij, int NMO, int NAEA, int NAEB)\n{\n  std::map<int, int> mo2active;\n  for (int i = 0; i < 2 * NMO; i++)\n    mo2active[i] = -1;\n  std::vector<size_t> count(2 * NMO);\n  // reference first\n  auto refc = abij.reference_configuration();\n  for (int i = 0; i < NAEA + NAEB; i++, ++refc)\n    ++count[*refc];\n  auto nex = abij.maximum_excitation_number();\n  for (int n = 1; n < nex[0]; ++n)\n  {\n    auto it    = abij.alpha_begin(n);\n    auto itend = abij.alpha_end(n);\n    for (; it < itend; ++it)\n    {\n      auto exct = *it + n; // skip locations\n      for (int ak = 0; ak < n; ++ak, ++exct)\n        ++count[*exct];\n    }\n  }\n  for (int n = 1; n < nex[1]; ++n)\n  {\n    auto it    = abij.beta_begin(n);\n    auto itend = abij.beta_end(n);\n    for (; it < itend; ++it)\n    {\n      auto exct = *it + n; // skip locations\n      for (int ak = 0; ak < n; ++ak, ++exct)\n        ++count[*exct];\n    }\n  }\n  if (not single_list)\n  {\n    int ik = 0;\n    for (int i = 0; i < NMO; ++i)\n      if (count[i] > 0 || count[i + NMO] > 0)\n      {\n        if (count[i] > 0)\n          mo2active[i] = ik;\n        if (count[i + NMO] > 0)\n          mo2active[i + NMO] = ik;\n        ++ik;\n      }\n  }\n  else\n  {\n    int ik = 0;\n    for (int i = 0; i < NMO; ++i)\n      if (count[i] > 0)\n        mo2active[i] = ik++;\n    ik = 0;\n    for (int i = NMO; i < 2 * NMO; ++i)\n      if (count[i] > 0)\n        mo2active[i] = ik++;\n  }\n  return mo2active;\n}\n\n/*\n * - exct stores, for each electron excitaion, the location of the orbital in the reference \n *    being excited and the index of the excited orbital.\n */\ntemplate<class Vector, class T>\nint get_excitation_number(bool getIndx, Vector& refc, Vector& confg, Vector& exct, T& ci, Vector& Iwork)\n{\n  int NE = refc.size();\n  exct.clear();\n  int cnt = 0;\n  if (getIndx)\n    std::copy(refc.begin(), refc.end(), Iwork.begin());\n  auto it = refc.data();\n  assert(Iwork.size() >= refc.size());\n  for (int i = 0; i < NE; i++, it++)\n    if (!std::binary_search(confg.begin(), confg.end(), *it))\n    {\n      if (getIndx)\n      {\n        // store the location, NOT the index!!!\n        //exct.emplace_back(*it);\n        exct.emplace_back(i);\n      }\n      cnt++;\n    }\n  if (!getIndx)\n    return cnt;\n  it       = confg.data();\n  int cnt2 = 0;\n  for (int i = 0; i < NE; i++, it++)\n    if (!std::binary_search(refc.begin(), refc.end(), *it))\n    {\n      exct.emplace_back(*it);\n      Iwork[exct[cnt2]] = *it;\n      cnt2++;\n    }\n  assert(cnt == cnt2);\n  // sort Iwork and count number of exchanges to determine permutation sign\n  // sooo slow but sooo simple too\n  for (int i = 0; i < NE; i++)\n    for (int j = i + 1; j < NE; j++)\n    {\n      if (Iwork[j] < Iwork[i])\n      {\n        ci *= T(-1.0);\n        std::swap(Iwork[i], Iwork[j]);\n      }\n    }\n  return cnt;\n}\n\ntemplate<typename intT, class csr>\ninline std::vector<size_t> get_nnz(csr const& PsiT_MO, intT* refc, size_t N, size_t shift)\n{\n  std::vector<size_t> res(N);\n  for (size_t i = 0; i < N; i++)\n    res[i] = PsiT_MO.num_non_zero_elements(*(refc + i) - shift);\n  return res;\n}\n\n\n// try putting this in shared memory later on\ntemplate<class I       = int,\n         class VType   = std::complex<double>,\n         class Alloc   = shared_allocator<I>,\n         class is_root = ma::sparse::is_root>\nstruct ph_excitations\n{\npublic:\n  using integer_type       = I;\n  using configuration_type = std::tuple<int, int, VType>;\n\nprivate:\n  using IAllocator = Alloc;\n  using CAllocator = typename Alloc::template rebind<configuration_type>::other;\n  using confg_aos  = ma::sparse::array_of_sequences<configuration_type, int, CAllocator, is_root>;\n  using index_aos  = ma::sparse::array_of_sequences<integer_type, int, IAllocator, is_root>;\n\n  IAllocator i_allocator_;\n  CAllocator c_allocator_;\n\n  template<typename Integer>\n  class Iterator\n      : public boost::\n            iterator_facade<Iterator<Integer>, Integer*, std::random_access_iterator_tag, Integer*, std::ptrdiff_t>\n  {\n  public:\n    using difference_type = std::ptrdiff_t;\n    using reference       = Integer*;\n    using const_reference = Integer const*;\n    using value_tupe      = Integer*;\n\n    Iterator(Integer* index, size_t d_) : p_index(index), D(d_) {}\n\n    // What we implement is determined by the boost::forward_traversal_tag\n  private:\n    friend class boost::iterator_core_access;\n\n    void increment() { p_index += 2 * D; }\n\n    bool equal(Iterator const& other) const { return this->p_index == other.p_index; }\n\n    reference dereference() const { return reference(p_index); }\n\n    void decrement() { p_index -= 2 * D; }\n\n    void advance(int n) { p_index += 2 * D * n; }\n\n    difference_type distance_to(Iterator const& z) const { return ((z.p_index - p_index) / 2 / D); }\n\n  private:\n    Integer* p_index;\n    size_t D;\n  };\n\n  template<typename Integer>\n  class Iterator_const : public boost::iterator_facade<Iterator_const<Integer>,\n                                                       Integer const*,\n                                                       std::random_access_iterator_tag,\n                                                       Integer const*,\n                                                       std::ptrdiff_t>\n  {\n  public:\n    using difference_type = std::ptrdiff_t;\n    using reference       = Integer const*;\n    using const_reference = Integer const*;\n    using value_tupe      = Integer*;\n\n    Iterator_const(Integer* index, size_t d_) : p_index(index), D(d_) {}\n    Iterator_const(Integer const* index, size_t d_) : p_index(index), D(d_) {}\n\n    // What we implement is determined by the boost::forward_traversal_tag\n  private:\n    friend class boost::iterator_core_access;\n\n    void increment() { p_index += 2 * D; }\n\n    bool equal(Iterator_const const& other) const { return this->p_index == other.p_index; }\n\n    reference dereference() const { return reference(p_index); }\n\n    void decrement() { p_index -= 2 * D; }\n\n    void advance(int n) { p_index += 2 * D * n; }\n\n    difference_type distance_to(Iterator_const const& z) const { return ((z.p_index - p_index) / 2 / D); }\n\n  private:\n    Integer* p_index;\n    size_t D;\n  };\n\npublic:\n  using Excitation_Iterator       = Iterator<integer_type>;\n  using Excitation_const_Iterator = Iterator_const<integer_type>;\n\n  ph_excitations() = delete;\n\n  // Note: terms_per_excitation[0] has special meaning, the number of electrons in the calculation.\n  // coefficients[0] will store the reference configuration itself.\n  ph_excitations(size_t number_of_configurations,\n                 int na_,\n                 int nb_,\n                 std::vector<size_t>& unique_alpha_counts,\n                 std::vector<size_t>& unique_beta_counts,\n                 Alloc alloc_ = Alloc{})\n      : i_allocator_(alloc_),\n        c_allocator_(alloc_),\n        NAEA(na_),\n        NAEB(nb_),\n        configurations(1, number_of_configurations, c_allocator_),\n        reference(1, NAEA + NAEB, i_allocator_),\n        unique_alpha(unique_alpha_counts.size(), unique_alpha_counts, i_allocator_),\n        unique_beta(unique_beta_counts.size(), unique_beta_counts, i_allocator_)\n  {\n    size_t emax = std::max(unique_alpha_counts.size(), unique_beta_counts.size());\n    sum_of_exct.resize(emax + 1);\n    sum_of_exct[0] = {0, 0};\n    sum_of_exct[1] = {1, 1};\n    for (size_t n = 1; n < unique_alpha.size(); ++n)\n      sum_of_exct[n + 1][0] = sum_of_exct[n][0] + unique_alpha_counts[n] / size_t(2) / n;\n    for (size_t n = unique_alpha.size() + 1; n <= emax; n++)\n      sum_of_exct[n][0] = sum_of_exct[n - 1][0];\n    for (size_t n = 1; n < unique_beta.size(); ++n)\n      sum_of_exct[n + 1][1] = sum_of_exct[n][1] + unique_beta_counts[n] / size_t(2) / n;\n    for (size_t n = unique_beta.size() + 1; n <= emax; n++)\n      sum_of_exct[n][1] = sum_of_exct[n - 1][1];\n  }\n\n  ph_excitations(ph_excitations const& other) = delete;\n  //ph_excitations(ph_excitations && other) = default;\n  ph_excitations(ph_excitations&& other)\n      : i_allocator_(other.i_allocator_),\n        c_allocator_(other.c_allocator_),\n        NAEA(other.NAEA),\n        NAEB(other.NAEB),\n        configurations(std::move(other.configurations)),\n        reference(std::move(other.reference)),\n        unique_alpha(std::move(other.unique_alpha)),\n        unique_beta(std::move(other.unique_beta)),\n        sum_of_exct(std::move(other.sum_of_exct))\n  {}\n\n  ph_excitations& operator=(ph_excitations const& other) = delete;\n  ph_excitations& operator=(ph_excitations&& other) = default;\n\n  std::array<size_t, 2> maximum_excitation_number() const { return {unique_alpha.size(), unique_beta.size()}; }\n  size_t number_of_unique_alpha_excitations(int n) const\n  {\n    if (n == 0)\n      return 1;\n    return unique_alpha.num_elements(n) / 2 / n;\n  }\n  size_t number_of_unique_beta_excitations(int n) const\n  {\n    if (n == 0)\n      return 1;\n    return unique_beta.num_elements(n) / 2 / n;\n  }\n  std::array<size_t, 2> number_of_unique_excitations(int n) const\n  {\n    if (n == 0)\n      return {1, 1};\n    std::array<size_t, 2> res{0, 0};\n    if (n < unique_alpha.size())\n      res[0] = unique_alpha.num_elements(n) / 2 / n;\n    if (n < unique_beta.size())\n      res[1] = unique_beta.num_elements(n) / 2 / n;\n    return res;\n  }\n  std::array<size_t, 2> number_of_unique_excitations() const { return sum_of_exct.back(); }\n\n  size_t number_of_configurations() const { return configurations.num_elements(0); }\n\n  // returns the number of unique excitations with particle number less than n\n  std::array<size_t, 2> number_of_unique_smaller_than(int n) const { return sum_of_exct[n]; }\n\n  template<class intIt>\n  void add_alpha(size_t n, intIt indx)\n  {\n    assert(n < unique_alpha.size());\n    assert(n > 0);\n    for (int i = 0; i < 2 * n; i++, ++indx)\n      unique_alpha.emplace_back(n, static_cast<integer_type>(*indx));\n  }\n\n  template<class intIt>\n  void add_beta(size_t n, intIt indx)\n  {\n    assert(n < unique_beta.size());\n    assert(n > 0);\n    for (int i = 0; i < 2 * n; i++, ++indx)\n      unique_beta.emplace_back(n, static_cast<integer_type>(*indx));\n  }\n\n  template<class Vector>\n  void add_reference(Vector& refa, Vector& refb)\n  {\n    for (auto k : refa)\n      reference.emplace_back(0, static_cast<integer_type>(k));\n    for (auto k : refb)\n      reference.emplace_back(0, static_cast<integer_type>(k));\n  }\n\n  // index=0 is reserved for the reference!!!\n  template<typename integer, typename value>\n  void add_configuration(integer alpha_indx, integer beta_index, value ci)\n  {\n    configurations.emplace_back(0, configuration_type{alpha_indx, beta_index, ci});\n  }\n\n  typename Excitation_Iterator::const_reference reference_configuration(int spin = 0) const\n  {\n    return to_address(reference.values(0)) + (spin == 0 ? 0 : NAEA);\n  }\n\n  typename Excitation_Iterator::reference reference_configuration(int spin = 0)\n  {\n    return to_address(reference.values(0)) + (spin == 0 ? 0 : NAEA);\n  }\n\n  configuration_type const* configurations_begin() const { return to_address(configurations.values(0)); }\n\n  configuration_type const* configurations_end() const\n  {\n    return to_address(configurations.values()) + (*configurations.pointers_end(0));\n  }\n\n  configuration_type const* configuration(int i) const { return to_address(configurations.values()) + i; }\n\n  Excitation_Iterator alpha_begin(int n)\n  {\n    assert(n > 0);\n    if (n < unique_alpha.size())\n    {\n      return Excitation_Iterator(to_address(unique_alpha.values(n)), n);\n    }\n    else\n      return alpha_end(n);\n  }\n\n  Excitation_Iterator alpha_end(int n)\n  {\n    assert(n > 0);\n    if (n < unique_alpha.size())\n      return Excitation_Iterator(to_address(unique_alpha.values()) + (*unique_alpha.pointers_end(n)), n);\n    else\n      return Excitation_Iterator(to_address(unique_alpha.values()) +\n                                     (*unique_alpha.pointers_end(unique_alpha.size() - 1)),\n                                 1);\n  }\n\n  Excitation_const_Iterator alpha_begin(int n) const\n  {\n    assert(n > 0);\n    if (n < unique_alpha.size())\n    {\n      return Excitation_const_Iterator(to_address(unique_alpha.values(n)), n);\n    }\n    else\n      return alpha_end(n);\n  }\n\n  Excitation_const_Iterator alpha_end(int n) const\n  {\n    assert(n > 0);\n    if (n < unique_alpha.size())\n      return Excitation_const_Iterator(to_address(unique_alpha.values()) + (*unique_alpha.pointers_end(n)), n);\n    else\n      return Excitation_const_Iterator(to_address(unique_alpha.values()) +\n                                           (*unique_alpha.pointers_end(unique_alpha.size() - 1)),\n                                       1);\n  }\n\n  Excitation_Iterator beta_begin(int n)\n  {\n    assert(n > 0);\n    if (n < unique_beta.size())\n      return Excitation_Iterator(to_address(unique_beta.values(n)), n);\n    else\n      return beta_end(n);\n  }\n\n  Excitation_Iterator beta_end(int n)\n  {\n    assert(n > 0);\n    if (n < unique_beta.size())\n      return Excitation_Iterator(to_address(unique_beta.values()) + (*unique_beta.pointers_end(n)), n);\n    else\n      return Excitation_Iterator(to_address(unique_beta.values()) + (*unique_beta.pointers_end(unique_beta.size() - 1)),\n                                 1);\n  }\n\n  Excitation_const_Iterator beta_begin(int n) const\n  {\n    assert(n > 0);\n    if (n < unique_beta.size())\n      return Excitation_const_Iterator(to_address(unique_beta.values(n)), n);\n    else\n      return beta_end(n);\n  }\n\n  Excitation_const_Iterator beta_end(int n) const\n  {\n    assert(n > 0);\n    if (n < unique_beta.size())\n      return Excitation_const_Iterator(to_address(unique_beta.values()) + (*unique_beta.pointers_end(n)), n);\n    else\n      return Excitation_const_Iterator(to_address(unique_beta.values()) +\n                                           (*unique_beta.pointers_end(unique_beta.size() - 1)),\n                                       1);\n  }\n\n  // for generic access\n  std::array<Excitation_Iterator, 2> unique_begin(int n)\n  {\n    return std::array<Excitation_Iterator, 2>{alpha_begin(n), beta_begin(n)};\n  }\n  std::array<Excitation_Iterator, 2> unique_end(int n)\n  {\n    return std::array<Excitation_Iterator, 2>{alpha_end(n), beta_end(n)};\n  }\n  std::array<Excitation_const_Iterator, 2> unique_begin(int n) const\n  {\n    return std::array<Excitation_const_Iterator, 2>{alpha_begin(n), beta_begin(n)};\n  }\n  std::array<Excitation_const_Iterator, 2> unique_end(int n) const\n  {\n    return std::array<Excitation_const_Iterator, 2>{alpha_end(n), beta_end(n)};\n  }\n\n  template<class Vector>\n  void get_alpha_configuration(size_t index, Vector& confg) const\n  {\n    assert(confg.size() >= NAEA);\n    std::copy_n(to_address(reference.values(0)), NAEA, confg.data());\n    if (index == 0)\n      return;\n    // could use lower bound\n    for (int i = 1; i < unique_alpha.size(); i++)\n    {\n      if (index >= sum_of_exct[i][0] && index < sum_of_exct[i + 1][0])\n      {\n        size_t dn = index - sum_of_exct[i][0];\n        auto exct = unique_alpha.values(i) + 2 * i * dn;\n        for (int n = 0; n < i; n++)\n          confg[exct[n]] = exct[n + i];\n        return;\n      }\n    }\n    APP_ABORT(\" Error in ph_excitations::get_alpha_configuration() \\n\");\n  }\n\n  template<class Vector>\n  void get_beta_configuration(size_t index, Vector& confg) const\n  {\n    assert(confg.size() >= NAEB);\n    std::copy_n(to_address(reference.values(0)) + NAEA, NAEB, confg.data());\n    if (index == 0)\n      return;\n    // could use lower bound\n    for (int i = 1; i < unique_beta.size(); i++)\n    {\n      if (index >= sum_of_exct[i][1] && index < sum_of_exct[i + 1][1])\n      {\n        size_t dn = index - sum_of_exct[i][1];\n        auto exct = unique_beta.values(i) + 2 * i * dn;\n        for (int n = 0; n < i; n++)\n          confg[exct[n]] = exct[n + i];\n        return;\n      }\n    }\n    APP_ABORT(\" Error in ph_excitations::get_beta_configuration() \\n\");\n  }\n\n  template<class Vector>\n  void get_configuration(int spin, size_t index, Vector& confg) const\n  {\n    if (spin == 0)\n      get_alpha_configuration(index, confg);\n    else\n      get_beta_configuration(index, confg);\n  }\n\nprivate:\n  // using array_of_seq until I switch to Boost.Multi to be able to use shared_allocator\n  int NAEA, NAEB;\n  confg_aos configurations;\n  index_aos reference;\n  index_aos unique_alpha;\n  index_aos unique_beta;\n  std::vector<std::array<size_t, 2>> sum_of_exct;\n};\n\n} // namespace afqmc\n\n} // namespace qmcplusplus\n\n#endif\n", "meta": {"hexsha": "aac2d5394b7faf36f9cba1f38759f543907b667b", "size": 18419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/AFQMC/Wavefunctions/Excitations.hpp", "max_stars_repo_name": "djstaros/qmcpack", "max_stars_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AFQMC/Wavefunctions/Excitations.hpp", "max_issues_repo_name": "djstaros/qmcpack", "max_issues_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "src/AFQMC/Wavefunctions/Excitations.hpp", "max_forks_repo_name": "djstaros/qmcpack", "max_forks_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.324829932, "max_line_length": 120, "alphanum_fraction": 0.6186003583, "num_tokens": 5088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845760163515857, "lm_q2_score": 0.03308597922294221, "lm_q1q2_score": 0.009415476164356226}}
{"text": "#include <QMap>\n#include <QString>\n#include <QStringList>\n#include <QTime>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <mm_plugin.h>\n\n#include \"model.h\"\n#include \"common/opencvutils.h\"\n#include \"common/qtutils.h\"\n#include \"plugins/meta.h\"\n#include \"plugins/regions.h\"\n\n//#ifdef MM_SDK_TRAINABLE\n#include <boost/smart_ptr.hpp>\n#include <exception>\n#include <iostream>\n#include <cstdlib>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <error.hpp>\n#include <global.hpp>\n#include <subset.hpp>\n#include <data_intervaller.hpp>\n#include <data_splitter.hpp>\n#include <data_splitter_5050.hpp>\n#include <data_splitter_cv.hpp>\n#include <data_splitter_resub.hpp>\n#include <data_scaler.hpp>\n#include <data_scaler_void.hpp>\n#include <data_accessor_splitting_mem.hpp>\n#include <criterion_wrapper.hpp>\n#include <distance_euclid.hpp>\n#include <classifier_knn.hpp>\n#include <seq_step_straight_threaded.hpp>\n#include <search_seq_dos.hpp>\n#include <search_seq_sfs.hpp>\n#include <search_seq_sffs.hpp>\n#include <search_monte_carlo_threaded.hpp>\n\nusing namespace FST;\n//#endif // MM_SDK_TRAINABLE\n\nusing namespace mm;\n\nenum DimensionStatus {\n    On,\n    Off,\n    Ignore\n};\n\n//#ifdef MM_SDK_TRAINABLE\ntemplate<typename DATATYPE, typename IDXTYPE, class INTERVALCONTAINER>\nclass FST3Data_Accessor_Splitting_MemMM : public Data_Accessor_Splitting_Mem<DATATYPE,IDXTYPE,INTERVALCONTAINER>\n{\n    QList<MatrixList> mll;\n    QList<DimensionStatus> dsl;\n    int features;\n    QMap<int, int> labelCounts;\n\npublic:\n    typedef Data_Accessor_Splitting_Mem<DATATYPE,IDXTYPE,INTERVALCONTAINER> DASM;\n    typedef boost::shared_ptr<Data_Scaler<DATATYPE> > PScaler;\n    typedef typename DASM::PSplitters PSplitters;\n\n    FST3Data_Accessor_Splitting_MemMM(const QList<MatrixList> &_mll, const QList<DimensionStatus> &_dsl, const PSplitters _dsp, const PScaler _dsc)\n        : Data_Accessor_Splitting_Mem<DATATYPE,IDXTYPE,INTERVALCONTAINER>(\"MM\", _dsp, _dsc), mll(_mll), dsl(_dsl)\n    {\n        features = 0;\n        foreach (DimensionStatus ds, dsl)\n            if (ds != Ignore) features++;\n        labelCounts = mll.first().labelCounts();\n    }\n\n    FST3Data_Accessor_Splitting_MemMM(const MatrixList &_ml, const PSplitters _dsp, const PScaler _dsc)\n        : Data_Accessor_Splitting_Mem<DATATYPE,IDXTYPE,INTERVALCONTAINER>(\"MM\", _dsp, _dsc)\n    {\n        mll.append(_ml);\n        features = _ml.first().total() * _ml.first().channels();\n        for (int i=0; i<features; i++)\n            dsl.append(Off);\n        labelCounts = _ml.labelCounts();\n    }\n\n    FST3Data_Accessor_Splitting_MemMM* sharing_clone() const;\n    virtual std::ostream& print(std::ostream& os) const;\n\nprotected:\n    FST3Data_Accessor_Splitting_MemMM(const Data_Accessor_Splitting_MemMM &damt, int x)\n        : Data_Accessor_Splitting_Mem<DATATYPE,IDXTYPE,INTERVALCONTAINER>(damt, x)\n    {} // weak (referencing) copy-constructor to be used in sharing_clone()\n\n    virtual void initial_data_read();    //!< \\note off-limits in shared_clone\n    virtual void initial_file_prepare() {}\n\npublic:\n    virtual unsigned int file_getNoOfClasses() const { return labelCounts.size(); }\n    virtual unsigned int file_getNoOfFeatures() const { return features; }\n    virtual IDXTYPE file_getClassSize(unsigned int cls) const { return labelCounts[cls]; }\n};\n\ntemplate<typename DATATYPE, typename IDXTYPE, class INTERVALCONTAINER>\nvoid FST3Data_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALCONTAINER>::initial_data_read() //!< \\note off-limits in shared_clone\n{\n    if (Clonable::is_sharing_clone()) throw fst_error(\"Data_Accessor_Splitting_MemMM()::initial_data_read() called from shared_clone instance.\");\n    IDXTYPE idx=0;\n\n    // TODO: Assert that ml data type is DATATYPE\n    const QList<float> labels = mll.first().labels();\n    foreach (int label, labelCounts.keys()) {\n        for (int i=0; i<labels.size(); i++) {\n            if (labels[i] == label) {\n                int dslIndex = 0;\n                foreach (const MatrixList &ml, mll) {\n                    const Matrix &m = ml[i];\n                    const int dims = m.total() * m.channels();\n                    for (int j=0; j<dims; j++)\n                        if (dsl[dslIndex++] != Ignore)\n                            this->data[idx++] = reinterpret_cast<float*>(m.data)[j];\n                }\n            }\n        }\n    }\n}\n\n/*template<typename DATATYPE, typename IDXTYPE, class INTERVALCONTAINER>\nData_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALCONTAINER>* Data_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALCONTAINER>::sharing_clone() const\n{\n        Data_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALCONTAINER> *clone=new Data_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALCONTAINER>(*this, (int)0);\n        clone->set_sharing_cloned();\n        return clone;\n}\n\ntemplate<typename DATATYPE, typename IDXTYPE, class INTERVALCONTAINER>\nstd::ostream& Data_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALCONTAINER>::print(std::ostream& os) const\n{\n        DASM::print(os);\n        os << std::endl << \"Data_Accessor_Splitting_MemMM()\";\n        return os;\n}*/\n\n//#endif // MM_SDK_TRAINABLE\n\n\nclass FST3DOS : public Feature\n{\n    friend class Maker<DOS,true>;\n\n    int delta;\n\n    mm::Remap remap;\n\n    DOS(int delta = 1)\n    {\n        this->delta = delta;\n    }\n\n    static QString args()\n    {\n        return \"delta = 1\";\n    }\n\n    static DOS *make(const QString &args)\n    {\n        QStringList words = QtUtils::parse(args);\n        if (words.size() > 1) qFatal(\"DOS::make invalid argument count.\");\n\n        int delta = 1;\n\n        bool ok;\n        switch (words.size()) {\n          case 1:\n            delta = words[0].toInt(&ok); if (!ok) qFatal(\"DOS::make expected integer delta.\");\n        }\n\n        return new DOS(delta);\n    }\n\n    QSharedPointer<Feature> clone() const\n    {\n        return QSharedPointer<Feature>(new DOS(delta));\n    }\n\n    void train(const MatrixList &data, Matrix &metadata)\n    {\n        (void) metadata;\n        //#ifdef MM_SDK_TRAINABLE\n        try {\n            typedef float RETURNTYPE; \ttypedef float DATATYPE;       typedef float REALTYPE;\n            typedef unsigned int IDXTYPE; typedef unsigned int DIMTYPE; typedef int BINTYPE;\n            typedef Subset<BINTYPE, DIMTYPE> SUBSET;\n            typedef Data_Intervaller<std::vector<Data_Interval<IDXTYPE> >,IDXTYPE> INTERVALLER;\n            typedef boost::shared_ptr<Data_Splitter<INTERVALLER,IDXTYPE> > PSPLITTER;\n            typedef Data_Splitter_CV<INTERVALLER,IDXTYPE> SPLITTERCV;\n            typedef Data_Splitter_5050<INTERVALLER,IDXTYPE> SPLITTER5050;\n            typedef Data_Splitter_Resub<INTERVALLER,IDXTYPE> SPLITTERRESUB;\n            typedef Data_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALLER> DATAACCESSOR;\n            typedef Distance_Euclid<DATATYPE,DIMTYPE,SUBSET> DISTANCE;\n            typedef Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE> CLASSIFIERKNN;\n            typedef Criterion_Wrapper<RETURNTYPE,SUBSET,CLASSIFIERKNN,DATAACCESSOR> WRAPPERKNN;\n            typedef Sequential_Step_Straight_Threaded<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,24> EVALUATOR;\n\n            // Initialize dataset\n            PSPLITTER dsp_outer(new SPLITTER5050()); // keep second half of data for independent testing of final classification performance\n            PSPLITTER dsp_inner(new SPLITTERCV(3)); // in the course of search use the first half of data by 3-fold cross-validation in wrapper FS criterion evaluation\n            boost::shared_ptr<Data_Scaler<DATATYPE> > dsc(new Data_Scaler_void<DATATYPE>()); // do not scale data\n            boost::shared_ptr<std::vector<PSPLITTER> > splitters(new std::vector<PSPLITTER>); // set-up data access\n            splitters->push_back(dsp_outer); //splitters->push_back(dsp_inner);\n            boost::shared_ptr<DATAACCESSOR> da(new DATAACCESSOR(data, splitters, dsc));\n            da->initialize();\n            da->setSplittingDepth(0); if(!da->getFirstSplit()) throw fst_error(\"50/50 data split failed.\");\n            //da->setSplittingDepth(1); if(!da->getFirstSplit()) throw fst_error(\"3-fold cross-validation failure.\");\n            boost::shared_ptr<SUBSET> sub(new SUBSET(da->getNoOfFeatures())); // initiate the storage for subset to-be-selected\n            //sub->select_all();\n\n            // Run search\n            boost::shared_ptr<CLASSIFIERKNN> cknn(new CLASSIFIERKNN); cknn->set_k(1);\n            boost::shared_ptr<WRAPPERKNN> wknn(new WRAPPERKNN);\n            wknn->initialize(cknn,da);\n            boost::shared_ptr<EVALUATOR> eval(new EVALUATOR); // set-up the standard sequential search step object (option: hybrid, ensemble, etc.)\n            //Search_DOS<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,EVALUATOR> srch(eval); // set-up Sequential Forward Floating Selection search procedure\n            //srch.set_delta(delta);\n\n            //FST::Search_SFFS<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,EVALUATOR> srch(eval);\n            //srch.set_search_direction(FST::BACKWARD);\n\n            //FST::Search_SFS<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,EVALUATOR> srch(eval);\n            //srch.set_search_direction(FST::FORWARD);\n\n            FST::Search_Monte_Carlo_Threaded<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,24> srch;\n            srch.set_cardinality_randomization(0.5); // probability of inclusion of each particular feature (~implies also the expected subset size)\n            srch.set_stopping_condition(0/*max trials*/,30/*seconds*/); // one or both values must have positive value\n\n            RETURNTYPE critval_train;\n            if(!srch.search(0,critval_train,sub,wknn,std::cout)) throw fst_error(\"Search not finished.\");\n\n            // Create map matrix\n            const int dims = sub->get_d_raw();\n            cv::Mat xMap(1, dims, CV_16SC1),\n                    yMap(1, dims, CV_16SC1);\n            int index = 0;\n            for (int i=0; i<dims; i++) {\n                if (sub->selected_raw(i)) {\n                    xMap.at<short>(0, index) = i;\n                    yMap.at<short>(0, index) = 0;\n                    index++;\n                }\n            }\n\n            remap = Remap(xMap, yMap, cv::INTER_NEAREST);\n        }\n        catch (fst_error &e) { qFatal(\"FST ERROR: %s, code=%d\", e.what(), e.code()); }\n        catch (std::exception &e) { qFatal(\"non-FST ERROR: %s\", e.what()); }\n        metadata >> remap;\n        //#else // MM_SDK_TRAINABLE\n        //qFatal(\"StreamwiseFS::train not supported.\");\n        //#endif // MM_SDK_TRAINABLE\n    }\n\n    void project(const Matrix &src, Matrix &dst) const\n    {\n        dst = src;\n        dst >> remap;\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << remap;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> remap;\n    }\n};\n\nMM_REGISTER(Feature, FST3DOS, true)\n\n\nclass FST3StreamwiseFS : public Feature\n{\n    friend class Maker<StreamwiseFS,true>;\n\n    QSharedPointer<Feature> weakLearnerTemplate;\n    int time;\n\n    mm::Dup dup;\n    mm::Remap remap;\n\n    StreamwiseFS(const QSharedPointer<Feature> &weakLearnerTemplate, int time)\n        : dup(weakLearnerTemplate, 1)\n    {\n        this->weakLearnerTemplate = weakLearnerTemplate;\n        this->time = time;\n    }\n\n    static QString args()\n    {\n        return \"<feature> weakLearnerTemplate, int time\";\n    }\n\n    static StreamwiseFS *make(const QString &args)\n    {\n        QStringList words = QtUtils::parse(args);\n        if (words.size() != 2) qFatal(\"StreamwiseFS::make invalid argument count.\");\n\n        QSharedPointer<Feature> weakLearnerTemplate = Feature::make(words[0]);\n        bool ok;\n        int time = words[1].toInt(&ok); assert(ok);\n\n        return new StreamwiseFS(weakLearnerTemplate, time);\n    }\n\n    QSharedPointer<Feature> clone() const\n    {\n        return QSharedPointer<Feature>(new StreamwiseFS(weakLearnerTemplate, time));\n    }\n\n    void train(const MatrixList &data, Matrix &metadata)\n    {\n        QList< QSharedPointer<Feature> > weakLearners;\n        QList<MatrixList> projectedDataList;\n        QList<int> weakLearnerDimsList;\n        QList<DimensionStatus> dimStatusList;\n\n        QTime timer; timer.start();\n        while (timer.elapsed() / 1000 < time) {\n            // Construct a new weak learner\n            QSharedPointer<Feature> newWeakLearner = weakLearnerTemplate->clone();\n            Matrix metadataCopy(metadata);\n            newWeakLearner->train(data, metadataCopy);\n            weakLearners.append(newWeakLearner);\n\n            MatrixList projectedData = data;\n            projectedData >> *newWeakLearner;\n            projectedDataList.append(projectedData);\n            weakLearnerDimsList.append(projectedData.first().total() * projectedData.first().channels());\n            for (int i=0; i<weakLearnerDimsList.last(); i++) dimStatusList.append(Off);\n\n            //#ifdef MM_SDK_TRAINABLE\n            try\n            {\n                typedef float RETURNTYPE; \ttypedef float DATATYPE;       typedef float REALTYPE;\n                typedef unsigned int IDXTYPE; typedef unsigned int DIMTYPE; typedef int BINTYPE;\n                typedef Subset<BINTYPE, DIMTYPE> SUBSET;\n                typedef Data_Intervaller<std::vector<Data_Interval<IDXTYPE> >,IDXTYPE> INTERVALLER;\n                typedef boost::shared_ptr<Data_Splitter<INTERVALLER,IDXTYPE> > PSPLITTER;\n                typedef Data_Splitter_CV<INTERVALLER,IDXTYPE> SPLITTERCV;\n                typedef Data_Splitter_5050<INTERVALLER,IDXTYPE> SPLITTER5050;\n                typedef Data_Accessor_Splitting_MemMM<DATATYPE,IDXTYPE,INTERVALLER> DATAACCESSOR;\n                typedef Distance_Euclid<DATATYPE,DIMTYPE,SUBSET> DISTANCE;\n                typedef Classifier_kNN<RETURNTYPE,DATATYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR,DISTANCE> CLASSIFIERKNN;\n                typedef Criterion_Wrapper<RETURNTYPE,SUBSET,CLASSIFIERKNN,DATAACCESSOR> WRAPPERKNN;\n                typedef Sequential_Step_Straight_Threaded<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,24> EVALUATOR;\n\n                // Initialize dataset\n                PSPLITTER dsp_outer(new SPLITTER5050()); // keep second half of data for independent testing of final classification performance\n                PSPLITTER dsp_inner(new SPLITTERCV(3)); // in the course of search use the first half of data by 3-fold cross-validation in wrapper FS criterion evaluation\n                boost::shared_ptr<Data_Scaler<DATATYPE> > dsc(new Data_Scaler_void<DATATYPE>()); // do not scale data\n                boost::shared_ptr<std::vector<PSPLITTER> > splitters(new std::vector<PSPLITTER>); // set-up data access\n                splitters->push_back(dsp_outer); splitters->push_back(dsp_inner);\n                boost::shared_ptr<DATAACCESSOR> da(new DATAACCESSOR(projectedDataList, dimStatusList, splitters, dsc));\n                da->initialize();\n                da->setSplittingDepth(0); if(!da->getFirstSplit()) throw fst_error(\"50/50 data split failed.\");\n                da->setSplittingDepth(1); if(!da->getFirstSplit()) throw fst_error(\"3-fold cross-validation failure.\");\n                boost::shared_ptr<SUBSET> sub(new SUBSET(da->getNoOfFeatures())); // initiate the storage for subset to-be-selected\n\n                { // Initialize subset from previous iteration results\n                    sub->deselect_all();\n                    int index = 0;\n                    for (int i=0; i<dimStatusList.size(); i++) {\n                        if (dimStatusList[i] == On) sub->select(index);\n                        if (dimStatusList[i] != Ignore) index++;\n                    }\n                }\n\n                // Run search\n                boost::shared_ptr<CLASSIFIERKNN> cknn(new CLASSIFIERKNN); cknn->set_k(3); // set-up 3-Nearest Neighbor classifier based on Euclidean distances\n                boost::shared_ptr<WRAPPERKNN> wknn(new WRAPPERKNN); // wrap the 3-NN classifier to enable its usage as FS criterion (criterion value will be estimated by 3-fold cross-val.)\n                wknn->initialize(cknn,da);\n                boost::shared_ptr<EVALUATOR> eval(new EVALUATOR); // set-up the standard sequential search step object (option: hybrid, ensemble, etc.)\n                Search_DOS<RETURNTYPE,DIMTYPE,SUBSET,WRAPPERKNN,EVALUATOR> srch(eval); // set-up Sequential Forward Floating Selection search procedure\n                srch.set_delta(1);\n                RETURNTYPE critval_train;\n                if(!srch.search(0,critval_train,sub,wknn,std::cout)) throw fst_error(\"Search not finished.\");\n\n                { // Update results\n                    int dslIndex = dimStatusList.size() - 1;\n                    int subIndex = da->getNoOfFeatures() - 1;\n                    for (int wlIndex = weakLearnerDimsList.size()-1; wlIndex >= 0; wlIndex--) {\n                        const int weakLearnerDims = weakLearnerDimsList[wlIndex];\n                        int numSelectedDims = 0;\n                        for (int i=0; i<weakLearnerDims; i++) {\n                            if (dimStatusList[dslIndex] != Ignore)\n                                dimStatusList[dslIndex] = sub->selected_raw(subIndex--) ? numSelectedDims++, On : Ignore;\n                            dslIndex--;\n                        }\n\n                        if (numSelectedDims == 0) {\n                            for (int j=0; j<weakLearnerDims; j++)\n                                dimStatusList.removeAt(dslIndex+1);\n                            weakLearnerDimsList.removeAt(wlIndex);\n                            projectedDataList.removeAt(wlIndex);\n                            weakLearners.removeAt(wlIndex);\n                        }\n                    }\n                }\n            }\n            catch (fst_error &e) { qFatal(\"FST ERROR: %s, code=%d\", e.what(), e.code()); }\n            catch (std::exception &e) { qFatal(\"non-FST ERROR: %s\", e.what()); }\n            //#else // MM_SDK_TRAINABLE\n            //qFatal(\"StreamwiseFS::train not supported.\");\n            //#endif // MM_SDK_TRAINABLE\n        }\n\n        dup = Dup(weakLearners);\n\n        // Create map matrix\n        int dims = 0;\n        foreach (DimensionStatus ds, dimStatusList) if (ds == On) dims++;\n        cv::Mat xMap(1, dims, CV_16SC1),\n                yMap(1, dims, CV_16SC1);\n        int index = 0;\n        for (int i=0; i<dimStatusList.size(); i++) {\n            if (dimStatusList[i] == On) {\n                xMap.at<short>(0, index) = i;\n                yMap.at<short>(0, index) = 0;\n                index++;\n            }\n        }\n\n        remap = Remap(xMap, yMap, cv::INTER_NEAREST);\n    }\n\n    void project(const Matrix &src, Matrix &dst) const\n    {\n        dst = src;\n        dst >> dup >> mm::Cat >> remap;\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << dup << remap;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> dup >> remap;\n    }\n};\n\nMM_REGISTER(Feature, FST3StreamwiseFS, true)\n", "meta": {"hexsha": "3de6015dec6c7b1bd240f1ba2599283546cba2cf", "size": 18883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/fst3.cpp", "max_stars_repo_name": "vollingerm/openbr", "max_stars_repo_head_hexsha": "3d52092c9ef07ff6767afdbf50011fc476ce1bc9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T08:11:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-10T03:48:31.000Z", "max_issues_repo_path": "openbr/plugins/fst3.cpp", "max_issues_repo_name": "vollingerm/openbr", "max_issues_repo_head_hexsha": "3d52092c9ef07ff6767afdbf50011fc476ce1bc9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openbr/plugins/fst3.cpp", "max_forks_repo_name": "vollingerm/openbr", "max_forks_repo_head_hexsha": "3d52092c9ef07ff6767afdbf50011fc476ce1bc9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4100877193, "max_line_length": 188, "alphanum_fraction": 0.6319970344, "num_tokens": 4816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.021287351133736785, "lm_q1q2_score": 0.009402048357875802}}
{"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 Wed 4 Apr 2018 09:58:26\n\n#ifndef MDM_SLHA_IO_H\n#define MDM_SLHA_IO_H\n\n#include \"MDM_mass_eigenstates.hpp\"\n#include \"MDM_model_slha.hpp\"\n#include \"MDM_info.hpp\"\n#include \"MDM_observables.hpp\"\n#include \"MDM_physical.hpp\"\n#include \"problems.hpp\"\n#include \"spectrum_generator_problems.hpp\"\n#include \"standard_model_two_scale_model.hpp\"\n#include \"slha_io.hpp\"\n#include \"ckm.hpp\"\n#include \"ew_input.hpp\"\n#include \"lowe.h\"\n\n#include <Eigen/Core>\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp>\n\n#define Pole(p) physical.p\n#define PHYSICAL(p) model.get_physical().p\n#define PHYSICAL_SLHA(p) model.get_physical_slha().p\n#define LOCALPHYSICAL(p) physical.p\n#define MODEL model\n#define MODELPARAMETER(p) model.get_##p()\n#define EXTRAPARAMETER(p) model.get_##p()\n#define OBSERVABLES observables\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define SCALES(p) scales.p\n\nnamespace flexiblesusy {\n\nstruct MDM_input_parameters;\nclass Spectrum_generator_settings;\n\ntemplate <class T>\nclass MDM;\n\nstruct MDM_scales {\n   double HighScale{0.}, SUSYScale{0.}, LowScale{0.};\n   double pole_mass_scale{0.};\n};\n\nclass MDM_slha_io {\npublic:\n   MDM_slha_io();\n\n   void clear();\n\n   void fill(softsusy::QedQcd& qedqcd) const { slha_io.fill(qedqcd); }\n   void fill(MDM_input_parameters&) const;\n   void fill(MDM_mass_eigenstates&) const;\n   template <class Model> void fill(MDM_slha<Model>&) const;\n   void fill(Physical_input&) const;\n   void fill(Spectrum_generator_settings&) const;\n   double get_parameter_output_scale() const;\n   const SLHA_io& get_slha_io() const { return slha_io; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   void set_block(const std::string& str, SLHA_io::Position position = SLHA_io::back) { slha_io.set_block(str, position); }\n   void set_blocks(const std::vector<std::string>& vec, SLHA_io::Position position = SLHA_io::back) { slha_io.set_blocks(vec, position); }\n   template <class Model> void set_extra(const MDM_slha<Model>&, const MDM_scales&, const MDM_observables&);\n   void set_input(const MDM_input_parameters&);\n   void set_modsel(const SLHA_io::Modsel&);\n   void set_physical_input(const Physical_input&);\n   void set_settings(const Spectrum_generator_settings&);\n   void set_sminputs(const softsusy::QedQcd&);\n   template <class... Ts> void set_spectrum(const std::tuple<Ts...>&);\n   template <class Model> void set_spectrum(const MDM_slha<Model>&);\n   template <class T> void set_spectrum(const MDM<T>&);\n   void set_spectrum(const standard_model::Standard_model& m) { slha_io.set_spectrum(m); }\n   void set_spinfo(const Spectrum_generator_problems&);\n   void set_spinfo(const Problems&);\n   void set_spinfo(const std::vector<std::string>&, const std::vector<std::string>&);\n   void set_print_imaginary_parts_of_majorana_mixings(bool);\n   void write_to(const std::string&) const;\n   void write_to_file(const std::string& file_name) const { slha_io.write_to_file(file_name); }\n   void write_to_stream(std::ostream& ostr = std::cout) const { slha_io.write_to_stream(ostr); }\n\n   static void fill_minpar_tuple(MDM_input_parameters&, int, double);\n   static void fill_extpar_tuple(MDM_input_parameters&, int, double);\n   static void fill_imminpar_tuple(MDM_input_parameters&, int, double);\n   static void fill_imextpar_tuple(MDM_input_parameters&, int, double);\n\n   template <class Model>\n   static void fill_slhaea(SLHAea::Coll&, const MDM_slha<Model>&, const softsusy::QedQcd&, const MDM_scales&, const MDM_observables&);\n\n   template <class Model>\n   static SLHAea::Coll fill_slhaea(const MDM_slha<Model>&, const softsusy::QedQcd&, const MDM_scales&, const MDM_observables&);\n\nprivate:\n   SLHA_io slha_io; ///< SLHA io class\n   bool print_imaginary_parts_of_majorana_mixings;\n\n   void set_extpar(const MDM_input_parameters&);\n   void set_imminpar(const MDM_input_parameters&);\n   void set_imextpar(const MDM_input_parameters&);\n   void set_minpar(const MDM_input_parameters&);\n   void set_mass(const MDM_physical&, bool);\n   void set_mixing_matrices(const MDM_physical&, bool);\n   template <class Model> void set_model_parameters(const MDM_slha<Model>&);\n   void set_ckm(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   void set_pmns(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   double read_scale() const;\n   void fill_drbar_parameters(MDM_mass_eigenstates&) const;\n   void fill_physical(MDM_physical&) const;\n};\n\n/**\n * Reads DR-bar parameters, pole masses and mixing matrices from a\n * SLHA output file.\n */\ntemplate <class Model>\nvoid MDM_slha_io::fill(MDM_slha<Model>& model) const\n{\n   fill(static_cast<MDM_mass_eigenstates&>(model));\n   fill_physical(model.get_physical_slha());\n}\n\ntemplate <class Model>\nvoid MDM_slha_io::fill_slhaea(\n   SLHAea::Coll& slhaea, const MDM_slha<Model>& model,\n   const softsusy::QedQcd& qedqcd, const MDM_scales& scales,\n   const MDM_observables& observables)\n{\n   MDM_slha_io slha_io;\n   const MDM_input_parameters& input = model.get_input();\n   const auto& problems = model.get_problems();\n   const bool error = problems.have_problem();\n\n   slha_io.set_spinfo(problems);\n   slha_io.set_sminputs(qedqcd);\n   slha_io.set_input(input);\n   if (!error) {\n      slha_io.set_spectrum(model);\n      slha_io.set_extra(model, scales, observables);\n   }\n\n   slhaea = slha_io.get_slha_io().get_data();\n}\n\ntemplate <class Model>\nSLHAea::Coll MDM_slha_io::fill_slhaea(\n   const MDM_slha<Model>& model, const softsusy::QedQcd& qedqcd,\n   const MDM_scales& scales, const MDM_observables& observables)\n{\n   SLHAea::Coll slhaea;\n   MDM_slha_io::fill_slhaea(slhaea, model, qedqcd, scales, observables);\n\n   return slhaea;\n}\n\n/**\n * Stores the model (DR-bar) parameters in the SLHA object.\n *\n * @param model model class\n */\ntemplate <class Model>\nvoid MDM_slha_io::set_model_parameters(const MDM_slha<Model>& model)\n{\n   {\n      std::ostringstream block;\n      block << \"Block gauge Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(g1) * 0.7745966692414834), \"g1 * 0.7745966692414834\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(g2)), \"g2\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(g3)), \"g3\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"Yu\", ToMatrix(MODELPARAMETER(Yu_slha)), \"Yu\", model.get_scale());\n   slha_io.set_block(\"Yd\", ToMatrix(MODELPARAMETER(Yd_slha)), \"Yd\", model.get_scale());\n   slha_io.set_block(\"Ye\", ToMatrix(MODELPARAMETER(Ye_slha)), \"Ye\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block SM Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(mu2)), \"mu2\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(LamH)), \"LamH\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block HMIX Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(v)), \"v\")\n      ;\n      slha_io.set_block(block);\n   }\n\n\n}\n\n/**\n * Writes extra SLHA blocks\n *\n * @param model model class\n * @param scales struct of boundary condition scales\n * @param observables struct of observables\n */\ntemplate <class Model>\nvoid MDM_slha_io::set_extra(\n   const MDM_slha<Model>& model, const MDM_scales& scales,\n   const MDM_observables& observables)\n{\n   const MDM_physical physical(model.get_physical_slha());\n\n   {\n      std::ostringstream block;\n      block << \"Block FlexibleSUSYLowEnergy Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (OBSERVABLES.a_muon), \"Delta(g-2)_muon/2 FlexibleSUSY\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block EFFHIGGSCOUPLINGS\" << '\\n'\n            << FORMAT_RANK_THREE_TENSOR(25, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon)), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(25, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon)), \"Abs(effective H-Gluon-Gluon coupling)\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices of\n * all given models in the SLHA object.\n *\n * @todo Use generic lambda instead of Set_spectrum in C++14\n *\n * @param models model classes\n */\ntemplate <class... Ts>\nvoid MDM_slha_io::set_spectrum(const std::tuple<Ts...>& models)\n{\n   Set_spectrum<MDM_slha_io> ss(this);\n   boost::fusion::for_each(models, ss);\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in BPMZ convention\n */\ntemplate <class T>\nvoid MDM_slha_io::set_spectrum(const MDM<T>& model)\n{\n   set_spectrum(MDM_slha<MDM<T> >(model));\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in SLHA convention\n */\ntemplate <class Model>\nvoid MDM_slha_io::set_spectrum(const MDM_slha<Model>& model)\n{\n   const MDM_physical physical(model.get_physical_slha());\n   const bool write_sm_masses = model.do_calculate_sm_pole_masses();\n\n   set_model_parameters(model);\n   set_mass(physical, write_sm_masses);\n   set_mixing_matrices(physical, write_sm_masses);\n\n   if (slha_io.get_modsel().quark_flavour_violated)\n      set_ckm(model.get_ckm_matrix(), model.get_scale());\n\n   if (slha_io.get_modsel().lepton_flavour_violated)\n      set_pmns(model.get_pmns_matrix(), model.get_scale());\n}\n\n} // namespace flexiblesusy\n\n#undef Pole\n#undef PHYSICAL\n#undef PHYSICAL_SLHA\n#undef LOCALPHYSICAL\n#undef MODEL\n#undef MODELPARAMETER\n#undef EXTRAPARAMETER\n#undef OBSERVABLES\n#undef LowEnergyConstant\n#undef SCALES\n\n#endif\n", "meta": {"hexsha": "f9fe93106275d378f4a113e65c90f3e26b6f6576", "size": 10627, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MDM/MDM_slha_io.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MDM/MDM_slha_io.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MDM/MDM_slha_io.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": 33.8439490446, "max_line_length": 141, "alphanum_fraction": 0.7144066999, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.02442308983220468, "lm_q1q2_score": 0.009400743882237654}}
{"text": "\n#include <NTL/ctools.h>\n\n\n#include <cstdlib>\n#include <cmath>\n\n\n\n/*\n * An IEEE double x is finite if and only if x - x == 0.\n * The function _ntl_IsFinite implements this logic;  however,\n * it does not completely trust that an optimizing compiler\n * really implements this correctly, and so it goes out of its way to\n * confuse the compiler.  For a good compiler that respects IEEE floating\n * point arithmetic, this may not be necessary, but it is better\n * to be a bit paranoid.\n *\n * Like the routine _ntl_ForceToMem below, this routine has the\n * side effect of forcing its argument into memory.\n *\n * I've checked the assembly code generated by various\n * versions of GCC, ICC, and MSVC++, and it all looks good.\n */\n\n\nlong _ntl_IsFinite(double *p)\n{\n   volatile double x = *p;\n   *p = x;\n\n   double y = x;\n   double diff = y - x;\n   return diff == 0.0;\n}\n\n\n/*\n * On machines with wide floating point registers, the routine _ntl_ForceToMem\n * is used to force a floating point double to a memory location.\n *\n */\n\nvoid _ntl_ForceToMem(double *p)\n{\n   volatile double x = *p;\n   *p = x;\n}\n\n\n\n\n/*\n * The routine _ntl_ldexp(x, e) is like the standard ldexp(x, e) routine,\n * except that it takes a long exponent e, rather than an int exponenet.\n * Some care is taken to ensure reasonable overflow/undeflow behavior.\n * If the value of e does not fit into an int, then the result\n * is x*infinity or x*0, as appropriate.\n * Of course, this can only happen on platforms where long is wider\n * than int (e.g., most 64-bit platforms).\n *\n * We go out of our way to hide the fact that we are multiplying/dividing\n * by zero, so as to avoid unnecessary warnings, and to prevent \n * overly-agressive optimizing compilers from screwing things up.\n */\n\nvolatile double _ntl_ldexp_zero = 0.0;\n\ndouble _ntl_ldexp(double x, long e)\n{\n   if (e > NTL_MAX_INT)\n      return x/_ntl_ldexp_zero;\n   else if (e < NTL_MIN_INT)\n      return x*_ntl_ldexp_zero;\n   else\n      return std::ldexp(x, ((int) e));\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "6310b77d568ce3512ad0eafdec1b08d85796c2a1", "size": 1998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "android/jni/ntl/src/ctools.cpp", "max_stars_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_stars_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "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": "android/jni/ntl/src/ctools.cpp", "max_issues_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_issues_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "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": "android/jni/ntl/src/ctools.cpp", "max_forks_repo_name": "AnthonyTudorov/PALISADE-SizeOf-Fork", "max_forks_repo_head_hexsha": "05e9903da0971933adb1ba0b9c98398c9722a45c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-24T13:38:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-24T13:38:28.000Z", "avg_line_length": 23.7857142857, "max_line_length": 78, "alphanum_fraction": 0.6966966967, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.030214586084979088, "lm_q1q2_score": 0.009387502187755623}}
{"text": "/*\nCopyright (c) 2015 - 2016, Tianwei Shen\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of libvot nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n/*! \\file vocab_tree.cpp\n * \\brief vocabulary tree functions implementations\n */\n#include <iostream>\n#include <cmath>\n#include <cassert>\n#include <limits>\n#include <thread>\n#include <algorithm>\n#include <numeric>\n\n#include \"vocab_tree.h\"\n#include \"clustering.h\"\n\n#include <Eigen/Dense>\n\nusing std::cout;\nusing std::endl;\n\ninline float l2sq(const DTYPE *a, const DTYPE *b)\n{\n\ttypedef Eigen::Matrix<DTYPE, 1, FDIM> MatrixType;\n\ttypedef Eigen::Map<const MatrixType> MapTypeConst;\t\t// a read-only map\n\n\tMapTypeConst a_map(a, FDIM);\n\tMapTypeConst b_map(b, FDIM);\n\treturn (a_map.cast<float>() - b_map.cast<float>()).squaredNorm();\n}\n\nnamespace vot\n{\n/** VocabTree Class Implementation */\nVocabTree::VocabTree():database_image_num(0), num_nodes(0), dis_type(L1), root(nullptr) {}\n\nVocabTree::VocabTree(int depth_, int branch_num_, int dim_, DistanceType dis_type_):\n    branch_num(branch_num_), depth(depth_), dim(dim_), dis_type(dis_type_), num_nodes(0) {};\n\nVocabTree::~VocabTree() {root = nullptr;}  // do nothing since root is undetermined\n\nTreeInNode::~TreeInNode()\n{\n\tif (children != nullptr) {\n\t\tdelete [] children;\n\t\tchildren = nullptr;\n\t}\n}\n\nTreeLeafNode::~TreeLeafNode()\n{\n\tinv_list.clear();\n}\n\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                     Vocabulary Tree Clear Funtions                       //\n//                                                                          //\n//////////////////////////////////////////////////////////////////////////////\nbool VocabTree::ClearTree()\n{\n\tif (root != nullptr) {\n\t\troot->ClearNode(branch_num);\n\t}\n\n\tstd::cout << \"[VocabTree] Successfully clearing the tree\\n\";\n\treturn true;\n}\n\nbool TreeInNode::ClearNode(int bf)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr)\n\t\t\tchildren[i]->ClearNode(bf);\n\t}\n\tdelete this;\n\treturn true;\n}\n\nbool TreeLeafNode::ClearNode(int bf)\n{\n\tdelete this;\n\treturn true;\n}\n\nbool TreeInNode::ClearScores(int bf)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr) {\n\t\t\tchildren[i]->ClearScores(bf);\n\t\t}\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::ClearScores(int bf)\n{\n\tscore = 0.0;\n\treturn true;\n}\n\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                     Vocabulary Tree Build Module                         //\n//                                                                          //\n//////////////////////////////////////////////////////////////////////////////\nbool VocabTree::BuildTree(size_t num_keys, int dim_, int dep, int bf, DTYPE **p, int thread_num)\n{\n\tif (dep < 1) {    \t// the root of the tree is depth 0\n\t\tstd::cout << \"[FATAL_ERROR] The depth of the tree should be larger than 1!\\n\";\n\t\treturn false;\n\t}\n\n\tbranch_num = bf;\n\tdepth = dep;\n\tdim = dim_;\n\n\tif (GlobalParam::Verbose) {\n\t\tstd::cout << \"[VocabTree Build] Begin Build Vocabulary Tree ...\\n\";\n\t\tstd::cout << \"[VocabTree Build] with depth \" << dep << \" and branch number \" << bf << \".\\n\";\n\t\tstd::cout << \"[VocabTree Build] Approximately \" << (float)sizeof(DTYPE) * dim * pow(bf, dep+1)/(1024 * 1024)\n\t\t          << \"mb memory will be used to load the tree.\\n\";\n\t}\n\n\tdouble *means = new double [branch_num * dim];\n\tint *assign = new int [num_keys];\n\tif (means == nullptr || assign == nullptr) {\n\t\tstd::cout << \"[VocabTree Build] Error allocating memory in K-means\\n\";\n\t\treturn false;\n\t}\n\n\troot = new TreeInNode();\n\troot->des = new DTYPE [dim];\n\tfor (int i = 0; i < dim; i++)\n\t\troot->des[i] = 0;\n\n\tif (!root->RecursiveBuild(num_keys, dim, depth, 0, branch_num, p, means, assign, thread_num))\n\t\treturn false;\n\n\tdelete [] means;\n\tdelete [] assign;\n\n\tstd::cout << \"[VocabTree Build] Finish building vocabulary tree!\\n\";\n\n\treturn true;\n}\n\nvoid MultiRecursiveBuild(TreeNode *children, size_t num_keys, int dim, int depth, int depth_curr, int bf, DTYPE **p, double *means, int *assign, int sub_thread_num)\n{\n\tif (children != nullptr) {\n\t\tchildren->RecursiveBuild(num_keys, dim, depth, depth_curr, bf, p, means, assign, sub_thread_num);\n\t}\n}\n\nbool TreeInNode::RecursiveBuild(size_t num_keys, int dim, int depth, int depth_curr, int bf, DTYPE **p, double *means, int *assign, int thread_num)\n{\n\tif (GlobalParam::Verbose && depth_curr < 3)\n\t\tstd::cout << \"[RecursiveBuild] K-means in depth \" << depth_curr << \"\\n\";\n\n\tdouble error = Kmeans(num_keys, dim, bf, p, means, assign, thread_num);\n\tif (std::abs(error + 1) < 10e-6) {\n\t\tstd::cerr << \"[Error] Error in TreeInNode::RecursiveBuild\\n\";\n\t\treturn false;\n\t}\n\n\t// the average distance between each cluster and the node descriptor\n\tdouble mean_distance = 0.0;\n\tfor (int i = 0; i < bf; i++) {\n\t\tfor (int j = 0; j < dim; j++) {\n\t\t\tmean_distance += (means[i*dim + j] - des[j]) * (means[i*dim + j] - des[j]);\n\t\t}\n\t}\n\tmean_distance /= bf;\n\tif (GlobalParam::Verbose && depth_curr < 3)\n\t\tstd::cout << \"[RecursiveBuild] Group/Center error: \" << error/num_keys << \"/\" << mean_distance << \"\\n\";\n\n\t// count the number of sift keys fallen into a interior node, stop split the node if there are too few keys.\n\tchildren = new TreeNode* [bf];\n\tsize_t *counts = new size_t [bf];\n\tfor (int i = 0; i < bf; i++)\n\t\tcounts[i] = 0;\n\tfor (int i = 0; i < num_keys; i++)\n\t\tcounts[assign[i]]++;\n\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (counts[i] > 0) {   \t\t// there are some keys fallen into this node\n\t\t\tif(depth_curr == depth || counts[i] < 2*bf)\n\t\t\t\tchildren[i] = new TreeLeafNode();\n\t\t\telse\n\t\t\t\tchildren[i] = new TreeInNode();\n\t\t\tchildren[i]->des = new DTYPE [dim];\n\t\t\tfor (int j = 0; j < dim; j++) {\n\t\t\t\tif (sizeof(DTYPE) == 1)          // (char) round to the nearest integer\n\t\t\t\t\tchildren[i]->des[j] = (DTYPE)(means[i*dim + j] + 0.5);\n\t\t\t\telse                            // (float)\n\t\t\t\t\tchildren[i]->des[j] = (DTYPE)means[i*dim + j];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tchildren[i] = nullptr;\n\t\t}\n\t}\n\n\t// rearrange the pointer array so that after rearrangement, the sift keys in the first cluster appear consecutively in the array first,\n\t// then the second cluster, so on and so forth\n\tsize_t idx = 0;\n\tsize_t start_idx = 0;\n\tfor (size_t i = 0; i < bf; i++) {\n\t\tfor (size_t j = start_idx; j < num_keys; j++) {\n\t\t\tif (assign[j] == i) {\n\t\t\t\t// swap the pointer\n\t\t\t\tDTYPE *temp = p[idx];\n\t\t\t\tp[idx] = p[j];\n\t\t\t\tp[j] = temp;\n\t\t\t\t// swap the assignment\n\t\t\t\tunsigned int temp_assign = assign[idx];\n\t\t\t\tassign[idx] = assign[j];\n\t\t\t\tassign[j] = temp_assign;\n\n\t\t\t\tidx++;\n\t\t\t}\n\t\t}\n\t\tstart_idx += counts[i];\n\t}\n\tassert(start_idx == num_keys);\n\n\t// recursively build the tree in the children nodes\n\tif (thread_num == 1 || thread_num < bf) {     // single-thread\n\t\tsize_t offset = 0;\n\t\tfor (int i = 0; i < bf; i++) {\n\t\t\tif (children[i] != nullptr) {\n\t\t\t\tchildren[i]->RecursiveBuild(counts[i], dim, depth, depth_curr+1, bf, p+offset, means, assign+offset, thread_num);\n\t\t\t}\n\t\t\toffset += counts[i];\n\t\t}\n\t}\n\telse {       // multi-thread\n\t\tstd::vector<std::thread> threads;\n\t\tint subtree_threads = thread_num / bf;\n\t\tsize_t offset = 0;\n\t\tstd::vector<double *>sub_means(bf);\n\t\tfor (int i = 0; i < bf; i++) {\n\t\t\tint sub_thread_num = 0;\n\t\t\tif (i == bf - 1) {\n\t\t\t\tsub_thread_num = thread_num - (bf - 1) * subtree_threads;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsub_thread_num = subtree_threads;\n\t\t\t}\n\t\t\tsub_means[i] = new double [bf * dim];\n\t\t\tmemcpy(sub_means[i], means, sizeof(double) * bf * dim);\n\t\t\tthreads.push_back(std::thread(MultiRecursiveBuild, children[i], counts[i], dim, depth, depth_curr+1, bf, p+offset, sub_means[i], assign+offset, sub_thread_num));\n\n\t\t\toffset += counts[i];\n\t\t}\n\t\tstd::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));\n\t\tfor (int i = 0; i < bf; i++) {\n\t\t\tdelete [] sub_means[i];\n\t\t}\n\t}\n\tif (depth_curr < 2) {\n\t\tfor (int i = 0; i < bf; i++) {\n\t\t\tstd::cout << \"children \" << i << \" counts: \" << counts[i] << std::endl;\n\t\t}\n\t}\n\n\tdelete [] counts;\n\treturn true;\n}\n\nbool TreeLeafNode::RecursiveBuild(size_t num_keys, int dim, int depth, int depth_curr, int bf, DTYPE **p, double *means, int *assign, int thread_num)\n{\n\treturn true;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                     Vocabulary Tree IO Module                            //\n//                                                                          //\n//////////////////////////////////////////////////////////////////////////////\n\nbool VocabTree::WriteTree(const char *filename) const\n{\n\tif (root == nullptr)\n\t\treturn false;\n\tFILE *f = fopen(filename, \"wb\");\n\tif (f == nullptr) {\n\t\tstd::cout << \"[VocabTree] Error opening file \" << filename << \" for writing tree\\n\" << std::endl;\n\t\treturn false;\n\t}\n\n\t// write header parameters\n\tfwrite(&branch_num, sizeof(int), 1, f);\n\tfwrite(&depth, sizeof(int), 1, f);\n\tfwrite(&dim, sizeof(int), 1, f);\n\tfwrite(&database_image_num, sizeof(size_t), 1, f);\n\t//fwrite(&num_nodes, sizeof(size_t), 1, f);\n\n\t// write node information recursively\n\troot->WriteNode(f, branch_num, dim);\n\tfclose(f);\n\n\treturn true;\n}\n\nbool TreeInNode::WriteNode(FILE *f, int branch_num, int dim) const\n{\n\t// write the current node's information\n\tchar *has_children = new char [branch_num];\n\tchar is_internal = 1;\n\tfwrite(&is_internal, sizeof(char), 1, f);\n\tfwrite(des, sizeof(DTYPE), dim, f);\n\tfor (int i = 0; i < branch_num; i++) {\n\t\tif (children[i] == nullptr) {\n\t\t\thas_children[i] = 0;\n\t\t}\n\t\telse {\n\t\t\thas_children[i] = 1;\n\t\t}\n\t}\n\tfwrite(has_children, sizeof(char), branch_num, f);\n\tdelete [] has_children;\n\n\t// recursively write children's information\n\tfor (int i = 0; i < branch_num; i++) {\n\t\tif (children[i] != nullptr) {\n\t\t\tchildren[i]->WriteNode(f, branch_num, dim);\n\t\t}\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::WriteNode(FILE *f, int branch_num, int dim) const\n{\n\tchar is_internal = 0;\n\tfwrite(&is_internal, sizeof(char), 1, f);\n\tfwrite(des, sizeof(DTYPE), dim, f);\n\tfwrite(&weight, sizeof(float), 1, f);\n\n\tint num_images = (int)inv_list.size();\n\tfwrite(&num_images, sizeof(int), 1, f);\n\tfor (size_t i = 0; i < num_images; i++) {\n\t\tsize_t img = inv_list[i].index;\n\t\tfloat count = inv_list[i].count;\n\t\tfwrite(&img, sizeof(size_t), 1, f);\n\t\tfwrite(&count, sizeof(float), 1, f);\n\t}\n\n\treturn true;\n}\n\n// Read a vocabulary tree\nbool VocabTree::ReadTree(const char *filename)\n{\n\tif (root != nullptr)\n\t\tClearTree();\n\tFILE *f = fopen(filename, \"rb\");\n\tif (f == nullptr) {\n\t\tstd::cout << \"[ReadTree] Error opening file \" << filename << \" for reading tree\\n\" << std::endl;\n\t\treturn false;\n\t}\n\n\t// write header parameters\n\tchar is_internal;\n\tsize_t a, b, c, d, e;\n\ta = fread(&branch_num, sizeof(int), 1, f);\n\tb = fread(&depth, sizeof(int), 1, f);\n\tc = fread(&dim, sizeof(int), 1, f);\n\te = fread(&database_image_num, sizeof(size_t), 1, f);\n\t//f = fread(&num_nodes, sizeof(size_t), 1, f);\n\td = fread(&is_internal, sizeof(char), 1, f);\n\tif (a != 1 || b != 1 || c != 1 || d != 1 || e != 1) {\n\t\tstd::cout << \"[ReadTree] Reading Error\\n\";\n\t\treturn false;\n\t}\n\n\troot = new TreeInNode();\n\troot->ReadNode(f, branch_num, dim);\n\n\t//char end = fgetc(f);\n\t//cout << (end == EOF) << endl;\n\tfclose(f);\n\tnum_nodes = root->CountNodes(branch_num);\n\tnum_leaves = IndexLeaves();\n\tsize_t num_leaves1 = root->CountLeaves(branch_num);\n\tassert(num_leaves1 == num_leaves);\n\n\treturn true;\n}\n\nbool TreeInNode::ReadNode(FILE *f, int branch_num, int dim)\n{\n\tdes = new DTYPE [dim];\n\tint a = (int)fread(des, sizeof(DTYPE), dim, f);\n\tif (a != dim) {\n\t\tstd::cout << \"[ReadNode] Reading error\\n\";\n\t\treturn false;\n\t}\n\tchar *has_children = new char [branch_num];\n\tint b = (int)fread(has_children, sizeof(char), branch_num, f);\n\tif (b != branch_num) {\n\t\tstd::cout << \"[ReadNode] Reading error\\n\";\n\t\treturn false;\n\t}\n\n\tchildren = new TreeNode *[branch_num];\n\tfor (int i = 0; i < branch_num; i++) {\n\t\tif (has_children[i] == 0) {\n\t\t\tchildren[i] = nullptr;\n\t\t}\n\t\telse {\n\t\t\tchar is_internal;\n\t\t\tint c = (int)fread(&is_internal, sizeof(char), 1, f);\n\t\t\tif (c != 1) {\n\t\t\t\tstd::cout << \"[ReadNode] Reading error\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (is_internal) {\n\t\t\t\tchildren[i] = new TreeInNode();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tchildren[i] = new TreeLeafNode();\n\t\t\t}\n\t\t\tchildren[i]->ReadNode(f, branch_num, dim);\n\t\t}\n\t}\n\n\tdelete [] has_children;\n\n\treturn true;\n}\n\nbool TreeLeafNode::ReadNode(FILE *f, int branch_num, int dim)\n{\n\tdes = new DTYPE [dim];\n\tint a = (int)fread(des, sizeof(DTYPE), dim, f);\n\tif (a != dim) {\n\t\tstd::cout << \"[ReadNode] Reading error\\n\";\n\t\treturn false;\n\t}\n\tint num_images;\n\tint b = (int)fread(&weight, sizeof(float), 1, f);\n\tint c = (int)fread(&num_images, sizeof(int), 1, f);\n\tif (b != 1 || c != 1) {\n\t\tstd::cout << \"[ReadNode] Reading error\\n\";\n\t\treturn false;\n\t}\n\n\tinv_list.resize(num_images);\n\tfor (int i = 0; i < num_images; i++) {\n\t\tsize_t img;\n\t\tfloat count;\n\t\tint d = (int)fread(&img, sizeof(size_t), 1, f);\n\t\tint e = (int)fread(&count, sizeof(float), 1, f);\n\t\tif (d != 1 || e != 1) {\n\t\t\tstd::cout << \"[ReadNode] Reading error\\n\";\n\t\t\treturn false;\n\t\t}\n\t\tinv_list[i] = ImageCount(img, count);\n\t}\n\treturn true;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                     Vocabulary Tree Utilities(Test)                      //\n//                                                                          //\n//////////////////////////////////////////////////////////////////////////////\n\nvoid VocabTree::Show() const\n{\n\tstd::cout << \"[VocabTree] depth/branch_num: \" << depth << \"/\" << branch_num << '\\n';\n\tstd::cout << \"[VocabTree] #nodes \" << num_nodes << '\\n';\n\tstd::cout << \"[VocabTree] #images \" << database_image_num << '\\n';\n}\n\nsize_t TreeInNode::CountNodes(int branch_num) const\n{\n\tsize_t num_nodes = 0;\n\tfor (int i = 0; i < branch_num; i++) {\n\t\tif (children[i] != nullptr)\n\t\t\tnum_nodes += children[i]->CountNodes(branch_num);\n\t}\n\treturn num_nodes + 1;\n}\n\nsize_t TreeLeafNode::CountNodes(int branch_num) const {return 1;}\n\nsize_t TreeInNode::CountLeaves(int branch_num) const\n{\n\tsize_t num_leaves = 0;\n\tfor (int i = 0; i < branch_num; i++) {\n\t\tif (children[i] != nullptr)\n\t\t\tnum_leaves += children[i]->CountLeaves(branch_num);\n\t}\n\treturn num_leaves;\n}\n\nsize_t TreeLeafNode::CountLeaves(int branch_num) const {return 1;}\n\nbool VocabTree::Compare(VocabTree & v) const\n{\n\tif (v.dim != dim || v.depth != depth || v.branch_num != branch_num) {\n\t\treturn false;\n\t}\n\n\tsize_t node_count = root->CountNodes(branch_num);\n\tsize_t other_node_count = v.root->CountNodes(branch_num);\n\tif (node_count != other_node_count) {\n\t\treturn false;\n\t}\n\n\tsize_t leave_count = root->CountLeaves(branch_num);\n\tsize_t other_leave_count = v.root->CountLeaves(branch_num);\n\tif (leave_count != other_leave_count) {\n\t\treturn false;\n\t}\n\n\treturn root->Compare(v.root, branch_num, dim);\n}\n\nbool TreeInNode::Compare(TreeNode *in, int branch_num, int dim) const\n{\n\tTreeInNode *other_node = dynamic_cast<TreeInNode*>(in);\n\tfor (int i = 0; i < dim; i++)\n\t{\n\t\tif (des[i] != other_node->des[i])\n\t\t\treturn false;\n\t}\n\n\tfor (int i = 0; i < branch_num; i++) {\n\t\tif (children[i] == nullptr) {\n\t\t\tif (other_node->children[i] != nullptr)\n\t\t\t\treturn false;\n\t\t}\n\t\telse {\n\t\t\tif (other_node->children[i] == nullptr)\n\t\t\t\treturn false;\n\t\t\tchildren[i]->Compare(other_node->children[i], branch_num, dim);\n\t\t}\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::Compare(TreeNode *leaf, int branch_num, int dim) const\n{\n\tTreeLeafNode *other_leaf = dynamic_cast<TreeLeafNode*>(leaf);\n\tfor (int i = 0; i < dim; i++) {\n\t\tif (des[i] != other_leaf->des[i])\n\t\t\treturn false;\n\t}\n\tif (inv_list.size() != other_leaf->inv_list.size())    // shallow comparison\n\t\treturn false;\n\treturn true;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                     Vocabulary Tree Build Database                       //\n//                                                                          //\n//////////////////////////////////////////////////////////////////////////////\nvoid MultiAddImage(TreeNode *root,\n                   float *scores,\n                   DTYPE *v,\n                   size_t image_index,\n                   int num_feature,\n                   int branch_num,\n                   int dim,\n                   bool add)\n{\n\tsize_t off = 0;\n\tfor (int i = 0; i < num_feature; i++) {\n\t\troot->DescendFeature(scores, v+off, image_index, branch_num, dim, true);\n\t\toff += dim;\n\t}\n}\n\ndouble VocabTree::AddImage2Tree(size_t image_index, SiftData &sift, int thread_num)\n{\n\tfloat *q = new float [num_leaves];\n\tfor (size_t i = 0; i < num_leaves; i++) {\n\t\tq[i] = 0.0;\n\t}\n\n\tint sift_num = sift.getFeatureNum();\n\tDTYPE *v = sift.getDesPointer();\n\n\tsize_t off = 0;\n\tif (thread_num == 1) {    \t// single-thread version\n\t\tfor (int i = 0; i < sift_num; i++) {\n\t\t\troot->DescendFeature(q, v+off, image_index, branch_num, dim, true);\n\t\t\toff += dim;\n\t\t}\n\t}\n\telse {\n\t\tstd::vector<std::thread> threads;\n\t\tfor (int i = 0; i < thread_num; i++) {\n\t\t\tint thread_feature_num = sift_num / thread_num;\n\t\t\tif (i == thread_num - 1)\n\t\t\t\tthread_feature_num = sift_num - (thread_num - 1) * thread_feature_num;\n\t\t\tthreads.push_back(std::thread(MultiAddImage, root, q, v+off, image_index, thread_feature_num, branch_num, dim, true));\n\t\t\toff += dim * thread_feature_num;\n\t\t}\n\t\tstd::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));\n\t}\n\n\tdatabase_image_num++;\n\tdelete [] q;\n\treturn 0;\n\n\t// (optional) return the image vector magnitude (unnormalized)\n\t// double mag = root->ComputeImageVectorMagnitude(branch_num, dis_type);\n\t// switch(dis_type)\n\t// {\n\t//     case L1:\n\t//         return mag;\n\t//     case L2:\n\t//         return sqrt(mag);\n\t//     default:\n\t//         std::cout << \"[ComputeImageVectorMagnitude] Wrong distance type\\n\";\n\t//         return 0;\n\t// }\n}\n\nsize_t TreeInNode::DescendFeature(float *q, DTYPE *v, size_t image_index, int branch_num, int dim, bool add)\n{\n\tint best_idx = 0;\n\tfloat min_distance = std::numeric_limits<float>::max();\n\tfor (int i = 0; i < branch_num; i++) {\n\t\tif (children[i] != nullptr) {\n\t\t\tfloat curr_dist = l2sq(v, children[i]->des);\n\t\t\tif (curr_dist < min_distance) {\n\t\t\t\tmin_distance = curr_dist;\n\t\t\t\tbest_idx = i;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tsize_t ret = children[best_idx]->DescendFeature(q, v, image_index, branch_num, dim, add);\n\treturn ret;\n}\n\nsize_t TreeLeafNode::DescendFeature(float *q, DTYPE *v, size_t image_index, int branch_num, int dim, bool add)\n{\n\tadd_lock.lock();\n\tq[id] += weight;\n\tif (add) {    \t\t// add this image to inverted list\n\t\tsize_t curr_image_num = (size_t) inv_list.size();\n\t\tif (curr_image_num == 0)\n\t\t\tinv_list.push_back(ImageCount(image_index, (float)weight));\n\t\telse {\n\t\t\tif (inv_list[curr_image_num-1].index == image_index) {\n\t\t\t\tinv_list[curr_image_num-1].count += weight;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tinv_list.push_back(ImageCount(image_index, weight));\n\t\t\t}\n\t\t}\n\t}\n\tadd_lock.unlock();\n\treturn id;\n}\n\ndouble TreeInNode::ComputeImageVectorMagnitude(int bf, DistanceType dt)\n{\n\tdouble dist = 0.0;\n\tfor (int i = 0; i < bf; i++)\n\t{\n\t\tif (children[i] != nullptr)\n\t\t\tdist += children[i]->ComputeImageVectorMagnitude(bf, dt);\n\t}\n\treturn dist;\n}\n\ndouble TreeLeafNode::ComputeImageVectorMagnitude(int bf, DistanceType dt)\n{\n\tswitch (dt) {\n\t\tcase L1:\n\t\t\treturn score;\n\t\tcase L2:\n\t\t\treturn score * score;\n\t\tdefault:\n\t\t\treturn 0.0;\n\t}\n\treturn 0;\n}\n\nbool VocabTree::SetConstantWeight()\n{\n\tif (root != nullptr) {\n\t\troot->SetConstantWeight(branch_num);\n\t}\n\treturn true;\n}\n\nbool TreeInNode::SetConstantWeight(int bf)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr) {\n\t\t\tchildren[i]->SetConstantWeight(bf);\n\t\t}\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::SetConstantWeight(int bf)\n{\n\tweight = 1.0;\n\treturn true;\n}\n\nbool VocabTree::ComputeTFIDFWeight(size_t image_num)\n{\n\tif (root != nullptr)\n\t\troot->ComputeTFIDFWeight(branch_num, image_num);\n\treturn true;\n}\n\nbool TreeInNode::ComputeTFIDFWeight(int bf, size_t n)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr)\n\t\t\tchildren[i]->ComputeTFIDFWeight(bf, n);\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::ComputeTFIDFWeight(int bf, size_t n)\n{\n\tsize_t len = inv_list.size();\n\tif (len > 0) {\n\t\tweight = (float)log((double)n / (double)len);\n\t}\n\telse {\n\t\tweight = 0;\n\t}\n\n\t// pre-apply weight-adjustment to inverted list score\n\tfor (size_t i = 0; i < len; i++) {\n\t\tinv_list[i].count *= weight;\n\t}\n\n\treturn true;\n}\n\nbool VocabTree::NormalizeDatabase(size_t start_id, size_t image_num)\n{\n\tstd::vector<float> database_mag(image_num);\n\tdatabase_mag.resize(image_num);\n\tfor (size_t i = 0; i < image_num; i++) {\n\t\tdatabase_mag[i] = 0;\n\t}\n\n\troot->ComputeDatabaseMagnitude(branch_num, dis_type, start_id, database_mag);\n\t// TODO(tianwei): figure out what is the proper way of normalizing the vocabulary tree\n\tif (dis_type == L2) { \t\t// take sqrt of the magnitude\n\t\tfor (size_t i = 0; i < image_num; i++) {\n\t\t\tdatabase_mag[i] = sqrt(database_mag[i]);\n\t\t}\n\t}\n\n\tfor (size_t i = 0; i < image_num; i++) {\n\t\tstd::cout << \"[NormalizeDatabase] Normalized image #\" << start_id+i <<\n\t\t             \" vector magnitude \" << database_mag[i] << std::endl;\n\t}\n\treturn root->NormalizeDatabase(branch_num, start_id, database_mag);\n}\n\nbool TreeInNode::ComputeDatabaseMagnitude(int bf, DistanceType dis_type, size_t start_id, std::vector<float> &database_mag)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr)\n\t\t\tchildren[i]->ComputeDatabaseMagnitude(bf, dis_type, start_id, database_mag);\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::ComputeDatabaseMagnitude(int bf, DistanceType dis_type, size_t start_id, std::vector<float> &database_mag)\n{\n\tsize_t len = inv_list.size();\n\tfor (size_t i = 0; i < len; i++) {\n\t\tsize_t index = inv_list[i].index - start_id;\n\t\tassert(index < database_mag.size());\n\t\tswitch (dis_type) {\n\t\t\tcase L1:\n\t\t\t\tdatabase_mag[index] += inv_list[i].count;\n\t\t\t\tbreak;\n\t\t\tcase L2:\n\t\t\t\tdatabase_mag[index] += inv_list[i].count * inv_list[i].count;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tstd::cout << \"[ComputeDatabaseMagnitude] Error distance type\\n\";\n\t\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool TreeInNode::NormalizeDatabase(int bf, size_t start_id, std::vector<float> &database_mag)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr)\n\t\t\tchildren[i]->NormalizeDatabase(bf, start_id, database_mag);\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::NormalizeDatabase(int bf, size_t start_id, std::vector<float> &database_mag)\n{\n\tsize_t len = inv_list.size();\n\tfor (size_t i = 0; i < len; i++) {\n\t\tsize_t index = inv_list[i].index - start_id;\n\t\tassert(index < database_mag.size());\n\t\tinv_list[i].count /= database_mag[index];\n\t}\n\treturn true;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                     Vocabulary Tree Match Module                         //\n//                                                                          //\n//////////////////////////////////////////////////////////////////////////////\nsize_t leaves_count = 0;    // global leaf counter\nbool VocabTree::Query(SiftData &sift, float *scores)\n{\n\tfloat *q = new float [num_leaves];\n\tfor (size_t i = 0; i < num_leaves; i++) {\n\t\tq[i] = 0.0;\n\t}\n\n\tint sift_num = sift.getFeatureNum();\n\tDTYPE *v = sift.getDesPointer();\n\tsize_t off = 0;\n\tfor (int i = 0; i < sift_num; i++) {\n\t\troot->DescendFeature(q, v+off, 0, branch_num, dim, false);\n\t\toff += dim;\n\t}\n\n\tdouble mag = 0.0;\n\tswitch (dis_type) {\n\t\tcase L1:\n\t\t\tfor (size_t i = 0; i < num_leaves; i++)\n\t\t\t\tmag += q[i];\n\t\t\tbreak;\n\t\tcase L2:\n\t\t\tfor (size_t i = 0; i < num_leaves; i++)\n\t\t\t\tmag += q[i] * q[i];\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tstd::cout << \"[Error] Unknow distance type in query database\\n\";\n\t\t\treturn false;\n\t}\n\tif (dis_type == L2)\n\t\tmag = sqrt(mag);\n\n\tfor (size_t i = 0; i < num_leaves; i++) {\n\t\tq[i] /= (float)mag;\n\t}\n\troot->ScoreQuery(q, branch_num, dis_type, scores);\n\n\tdelete [] q;\n\n\treturn true;\n}\n\nsize_t VocabTree::IndexLeaves()\n{\n\tleaves_count = 0;\n\troot->IndexLeaves(branch_num);\n\treturn leaves_count;\n}\n\nbool TreeInNode::IndexLeaves(int bf)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr)\n\t\t\tchildren[i]->IndexLeaves(bf);\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::IndexLeaves(int bf)\n{\n\tid = leaves_count++;\n\treturn true;\n}\n\nbool TreeInNode::FillQueryVector(float *q, int bf, float normalize)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr) {\n\t\t\tchildren[i]->FillQueryVector(q, bf, normalize);\n\t\t}\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::FillQueryVector(float *q, int bf, float normalize)\n{\n\tq[id] = score * normalize;\n\treturn true;\n}\n\nbool TreeInNode::ScoreQuery(float *q, int bf, DistanceType dt, float *scores)\n{\n\tfor (int i = 0; i < bf; i++) {\n\t\tif (children[i] != nullptr) {\n\t\t\tchildren[i]->ScoreQuery(q, bf, dt, scores);\n\t\t}\n\t}\n\treturn true;\n}\n\nbool TreeLeafNode::ScoreQuery(float *q, int bf, DistanceType dt, float *scores)\n{\n\tif (q[id] == 0.0)\n\t\treturn true;\n\tsize_t len = inv_list.size();\n\n\tfor (int i = 0; i < len; i++) {\n\t\tsize_t idx = inv_list[i].index;\n\t\tswitch (dt) {\n\t\t\tcase L1:\n\t\t\t\tscores[idx] += q[id] > inv_list[i].count ? inv_list[i].count : q[id];\n\t\t\t\tbreak;\n\t\t\tcase L2:\n\t\t\t\tscores[idx] += q[id] * inv_list[i].count;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tstd::cout << \"[ScoreQuery] Error distacne type\\n\";\n\t\t}\n\t}\n\n\treturn  true;\n}\n\n}   // end of namespace vot\n", "meta": {"hexsha": "4a1dcdbfd93a8086869403cede77791176dafe4e", "size": 26822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/libvot/src/vocab_tree/vocab_tree.cpp", "max_stars_repo_name": "zyxrrr/GraphSfM", "max_stars_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2015-09-18T13:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:14:11.000Z", "max_issues_repo_path": "software/libvot/src/vocab_tree/vocab_tree.cpp", "max_issues_repo_name": "zyxrrr/GraphSfM", "max_issues_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-12-29T21:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-31T10:44:36.000Z", "max_forks_repo_path": "software/libvot/src/vocab_tree/vocab_tree.cpp", "max_forks_repo_name": "zyxrrr/GraphSfM", "max_forks_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 60.0, "max_forks_repo_forks_event_min_datetime": "2015-09-18T13:46:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T03:26:07.000Z", "avg_line_length": 27.5662898253, "max_line_length": 164, "alphanum_fraction": 0.5960778465, "num_tokens": 7359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398145016252104, "lm_q2_score": 0.02161533311717048, "lm_q1q2_score": 0.00938065361193561}}
{"text": "/**\n *\n * Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net)\n *\n * Authors: Matthias Walter\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_BIPARTITE_HPP\n#define BOOST_GRAPH_BIPARTITE_HPP\n\n#include <utility>\n#include <vector>\n#include <exception>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/bind.hpp>\n\nnamespace boost\n{\n\nnamespace detail\n{\n\n    /**\n     * The bipartite_visitor_error is thrown if an edge cannot be colored.\n     * The witnesses are the edges incident vertices.\n     */\n\n    template < typename Vertex >\n    struct BOOST_SYMBOL_VISIBLE bipartite_visitor_error : std::exception\n    {\n        std::pair< Vertex, Vertex > witnesses;\n\n        bipartite_visitor_error(Vertex a, Vertex b) : witnesses(a, b) {}\n\n        const char* what() const throw() { return \"Graph is not bipartite.\"; }\n    };\n\n    /**\n     * Functor which colors edges to be non-monochromatic.\n     */\n\n    template < typename PartitionMap > struct bipartition_colorize\n    {\n        typedef on_tree_edge event_filter;\n\n        bipartition_colorize(PartitionMap partition_map)\n        : partition_map_(partition_map)\n        {\n        }\n\n        template < typename Edge, typename Graph >\n        void operator()(Edge e, const Graph& g)\n        {\n            typedef typename graph_traits< Graph >::vertex_descriptor\n                vertex_descriptor_t;\n            typedef color_traits<\n                typename property_traits< PartitionMap >::value_type >\n                color_traits;\n\n            vertex_descriptor_t source_vertex = source(e, g);\n            vertex_descriptor_t target_vertex = target(e, g);\n            if (get(partition_map_, source_vertex) == color_traits::white())\n                put(partition_map_, target_vertex, color_traits::black());\n            else\n                put(partition_map_, target_vertex, color_traits::white());\n        }\n\n    private:\n        PartitionMap partition_map_;\n    };\n\n    /**\n     * Creates a bipartition_colorize functor which colors edges\n     * to be non-monochromatic.\n     *\n     * @param partition_map Color map for the bipartition\n     * @return The functor.\n     */\n\n    template < typename PartitionMap >\n    inline bipartition_colorize< PartitionMap > colorize_bipartition(\n        PartitionMap partition_map)\n    {\n        return bipartition_colorize< PartitionMap >(partition_map);\n    }\n\n    /**\n     * Functor which tests an edge to be monochromatic.\n     */\n\n    template < typename PartitionMap > struct bipartition_check\n    {\n        typedef on_back_edge event_filter;\n\n        bipartition_check(PartitionMap partition_map)\n        : partition_map_(partition_map)\n        {\n        }\n\n        template < typename Edge, typename Graph >\n        void operator()(Edge e, const Graph& g)\n        {\n            typedef typename graph_traits< Graph >::vertex_descriptor\n                vertex_descriptor_t;\n\n            vertex_descriptor_t source_vertex = source(e, g);\n            vertex_descriptor_t target_vertex = target(e, g);\n            if (get(partition_map_, source_vertex)\n                == get(partition_map_, target_vertex))\n                throw bipartite_visitor_error< vertex_descriptor_t >(\n                    source_vertex, target_vertex);\n        }\n\n    private:\n        PartitionMap partition_map_;\n    };\n\n    /**\n     * Creates a bipartition_check functor which raises an error if a\n     * monochromatic edge is found.\n     *\n     * @param partition_map The map for a bipartition.\n     * @return The functor.\n     */\n\n    template < typename PartitionMap >\n    inline bipartition_check< PartitionMap > check_bipartition(\n        PartitionMap partition_map)\n    {\n        return bipartition_check< PartitionMap >(partition_map);\n    }\n\n    /**\n     * Find the beginning of a common suffix of two sequences\n     *\n     * @param sequence1 Pair of bidirectional iterators defining the first\n     * sequence.\n     * @param sequence2 Pair of bidirectional iterators defining the second\n     * sequence.\n     * @return Pair of iterators pointing to the beginning of the common suffix.\n     */\n\n    template < typename BiDirectionalIterator1,\n        typename BiDirectionalIterator2 >\n    inline std::pair< BiDirectionalIterator1, BiDirectionalIterator2 >\n    reverse_mismatch(\n        std::pair< BiDirectionalIterator1, BiDirectionalIterator1 > sequence1,\n        std::pair< BiDirectionalIterator2, BiDirectionalIterator2 > sequence2)\n    {\n        if (sequence1.first == sequence1.second\n            || sequence2.first == sequence2.second)\n            return std::make_pair(sequence1.first, sequence2.first);\n\n        BiDirectionalIterator1 iter1 = sequence1.second;\n        BiDirectionalIterator2 iter2 = sequence2.second;\n\n        while (true)\n        {\n            --iter1;\n            --iter2;\n            if (*iter1 != *iter2)\n            {\n                ++iter1;\n                ++iter2;\n                break;\n            }\n            if (iter1 == sequence1.first)\n                break;\n            if (iter2 == sequence2.first)\n                break;\n        }\n\n        return std::make_pair(iter1, iter2);\n    }\n\n}\n\n/**\n * Checks a given graph for bipartiteness and fills the given color map with\n * white and black according to the bipartition. If the graph is not\n * bipartite, the contents of the color map are undefined. Runs in linear\n * time in the size of the graph, if access to the property maps is in\n * constant time.\n *\n * @param graph The given graph.\n * @param index_map An index map associating vertices with an index.\n * @param partition_map A color map to fill with the bipartition.\n * @return true if and only if the given graph is bipartite.\n */\n\ntemplate < typename Graph, typename IndexMap, typename PartitionMap >\nbool is_bipartite(\n    const Graph& graph, const IndexMap index_map, PartitionMap partition_map)\n{\n    /// General types and variables\n    typedef\n        typename property_traits< PartitionMap >::value_type partition_color_t;\n    typedef\n        typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;\n\n    /// Declare dfs visitor\n    //    detail::empty_recorder recorder;\n    //    typedef detail::bipartite_visitor <PartitionMap,\n    //    detail::empty_recorder> dfs_visitor_t; dfs_visitor_t dfs_visitor\n    //    (partition_map, recorder);\n\n    /// Call dfs\n    try\n    {\n        depth_first_search(graph,\n            vertex_index_map(index_map).visitor(make_dfs_visitor(\n                std::make_pair(detail::colorize_bipartition(partition_map),\n                    std::make_pair(detail::check_bipartition(partition_map),\n                        put_property(partition_map,\n                            color_traits< partition_color_t >::white(),\n                            on_start_vertex()))))));\n    }\n    catch (const detail::bipartite_visitor_error< vertex_descriptor_t >&)\n    {\n        return false;\n    }\n\n    return true;\n}\n\n/**\n * Checks a given graph for bipartiteness.\n *\n * @param graph The given graph.\n * @param index_map An index map associating vertices with an index.\n * @return true if and only if the given graph is bipartite.\n */\n\ntemplate < typename Graph, typename IndexMap >\nbool is_bipartite(const Graph& graph, const IndexMap index_map)\n{\n    typedef one_bit_color_map< IndexMap > partition_map_t;\n    partition_map_t partition_map(num_vertices(graph), index_map);\n\n    return is_bipartite(graph, index_map, partition_map);\n}\n\n/**\n * Checks a given graph for bipartiteness. The graph must\n * have an internal vertex_index property. Runs in linear time in the\n * size of the graph, if access to the property maps is in constant time.\n *\n * @param graph The given graph.\n * @return true if and only if the given graph is bipartite.\n */\n\ntemplate < typename Graph > bool is_bipartite(const Graph& graph)\n{\n    return is_bipartite(graph, get(vertex_index, graph));\n}\n\n/**\n * Checks a given graph for bipartiteness and fills a given color map with\n * white and black according to the bipartition. If the graph is not\n * bipartite, a sequence of vertices, producing an odd-cycle, is written to\n * the output iterator. The final iterator value is returned. Runs in linear\n * time in the size of the graph, if access to the property maps is in\n * constant time.\n *\n * @param graph The given graph.\n * @param index_map An index map associating vertices with an index.\n * @param partition_map A color map to fill with the bipartition.\n * @param result An iterator to write the odd-cycle vertices to.\n * @return The final iterator value after writing.\n */\n\ntemplate < typename Graph, typename IndexMap, typename PartitionMap,\n    typename OutputIterator >\nOutputIterator find_odd_cycle(const Graph& graph, const IndexMap index_map,\n    PartitionMap partition_map, OutputIterator result)\n{\n    /// General types and variables\n    typedef\n        typename property_traits< PartitionMap >::value_type partition_color_t;\n    typedef\n        typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\n    vertex_iterator_t vertex_iter, vertex_end;\n\n    /// Declare predecessor map\n    typedef std::vector< vertex_descriptor_t > predecessors_t;\n    typedef iterator_property_map< typename predecessors_t::iterator, IndexMap,\n        vertex_descriptor_t, vertex_descriptor_t& >\n        predecessor_map_t;\n\n    predecessors_t predecessors(\n        num_vertices(graph), graph_traits< Graph >::null_vertex());\n    predecessor_map_t predecessor_map(predecessors.begin(), index_map);\n\n    /// Initialize predecessor map\n    for (boost::tie(vertex_iter, vertex_end) = vertices(graph);\n         vertex_iter != vertex_end; ++vertex_iter)\n    {\n        put(predecessor_map, *vertex_iter, *vertex_iter);\n    }\n\n    /// Call dfs\n    try\n    {\n        depth_first_search(graph,\n            vertex_index_map(index_map).visitor(make_dfs_visitor(\n                std::make_pair(detail::colorize_bipartition(partition_map),\n                    std::make_pair(detail::check_bipartition(partition_map),\n                        std::make_pair(\n                            put_property(partition_map,\n                                color_traits< partition_color_t >::white(),\n                                on_start_vertex()),\n                            record_predecessors(\n                                predecessor_map, on_tree_edge())))))));\n    }\n    catch (const detail::bipartite_visitor_error< vertex_descriptor_t >& error)\n    {\n        typedef std::vector< vertex_descriptor_t > path_t;\n\n        path_t path1, path2;\n        vertex_descriptor_t next, current;\n\n        /// First path\n        next = error.witnesses.first;\n        do\n        {\n            current = next;\n            path1.push_back(current);\n            next = predecessor_map[current];\n        } while (current != next);\n\n        /// Second path\n        next = error.witnesses.second;\n        do\n        {\n            current = next;\n            path2.push_back(current);\n            next = predecessor_map[current];\n        } while (current != next);\n\n        /// Find beginning of common suffix\n        std::pair< typename path_t::iterator, typename path_t::iterator >\n            mismatch = detail::reverse_mismatch(\n                std::make_pair(path1.begin(), path1.end()),\n                std::make_pair(path2.begin(), path2.end()));\n\n        /// Copy the odd-length cycle\n        result = std::copy(path1.begin(), mismatch.first + 1, result);\n        return std::reverse_copy(path2.begin(), mismatch.second, result);\n    }\n\n    return result;\n}\n\n/**\n * Checks a given graph for bipartiteness. If the graph is not bipartite, a\n * sequence of vertices, producing an odd-cycle, is written to the output\n * iterator. The final iterator value is returned. Runs in linear time in the\n * size of the graph, if access to the property maps is in constant time.\n *\n * @param graph The given graph.\n * @param index_map An index map associating vertices with an index.\n * @param result An iterator to write the odd-cycle vertices to.\n * @return The final iterator value after writing.\n */\n\ntemplate < typename Graph, typename IndexMap, typename OutputIterator >\nOutputIterator find_odd_cycle(\n    const Graph& graph, const IndexMap index_map, OutputIterator result)\n{\n    typedef one_bit_color_map< IndexMap > partition_map_t;\n    partition_map_t partition_map(num_vertices(graph), index_map);\n\n    return find_odd_cycle(graph, index_map, partition_map, result);\n}\n\n/**\n * Checks a given graph for bipartiteness. If the graph is not bipartite, a\n * sequence of vertices, producing an odd-cycle, is written to the output\n * iterator. The final iterator value is returned. The graph must have an\n * internal vertex_index property. Runs in linear time in the size of the\n * graph, if access to the property maps is in constant time.\n *\n * @param graph The given graph.\n * @param result An iterator to write the odd-cycle vertices to.\n * @return The final iterator value after writing.\n */\n\ntemplate < typename Graph, typename OutputIterator >\nOutputIterator find_odd_cycle(const Graph& graph, OutputIterator result)\n{\n    return find_odd_cycle(graph, get(vertex_index, graph), result);\n}\n}\n\n#endif /// BOOST_GRAPH_BIPARTITE_HPP\n", "meta": {"hexsha": "549d027d315d21b51e415babf3544cc1c6a2cc1d", "size": 13518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/bipartite.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": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/bipartite.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/bipartite.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": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-01-11T18:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T20:16:12.000Z", "avg_line_length": 33.3777777778, "max_line_length": 80, "alphanum_fraction": 0.6646693298, "num_tokens": 2906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577490717496246, "lm_q2_score": 0.02635535447121332, "lm_q1q2_score": 0.00937657379055915}}
{"text": "//\n//  Net.cpp\n//\n//\n//  Created by Guanglei Wang on 03/06/2017.\n//\n\n#include <gravity/Net.h>\n#include <algorithm>\n#include <map>\n#include <set>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <list>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <queue>\n#include <time.h>\n//#include <armadillo>\n#ifdef USE_BOOST\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <deque>\n#include <iterator>\n#endif\n\nusing namespace std;\nusing namespace gravity;\n\nstatic int max_line_len;\nstatic char* line = nullptr;\n\nNet::Net() {}\n\n/* returns true if an arc is already present between the given nodes */\nbool Net::duplicate(std::string n1, std::string n2, int id1) {\n    int id2 = get_arc(n1, n2)->_id;\n    \n    if (id2 < id1)\n        return true;\n    else\n        return false;\n}\n\n\nNet* Net::clone() {\n    Net* copy_net = new Net();\n    Node* node = NULL;\n    \n    for (int i=0; i<nodes.size(); i++) {\n        node = this->nodes[i];\n        copy_net->add_node(node->clone());\n    }\n    \n    Arc* arc = NULL;\n    for (int i=0; i < arcs.size(); i++) {\n        \n        /* ignores if the arc is a paralel line to an already existing arc */\n        //if (duplicate(arcs[i]->_src->_name, arcs[i]->_dest->_name, arcs[i]->_id)) {\n//            continue;\n//        }\n        arc = arcs[i]->clone();\n        \n        /* Update the source and destination to the new nodes in copy_net */\n        arc->_src = copy_net->get_node(arc->_src->_name);\n        arc->_dest = copy_net->get_node(arc->_dest->_name);\n        \n        /* Add the new arc to the list of arcs */\n        copy_net->add_arc(arc);\n        \n        /* Connects it to its source and destination */\n        arc->connect();\n    }\n    return copy_net;\n}\n\nNet* Net::clone_undirected() {\n    Net* copy_net = new Net();\n    Node* node = NULL;\n    \n    for (int i=0; i<nodes.size(); i++) {\n        node = this->nodes[i];\n        copy_net->add_node(node->clone());\n    }\n    \n    Arc* arc = NULL;\n    for (int i=0; i < arcs.size(); i++) {\n        if (copy_net->get_arc(arcs[i]->_src->_name, arcs[i]->_dest->_name)!=nullptr) {\n            continue;\n        }\n        arc = arcs[i]->clone();\n        \n        /* Update the source and destination to the new nodes in copy_net */\n        arc->_src = copy_net->get_node(arc->_src->_name);\n        arc->_dest = copy_net->get_node(arc->_dest->_name);\n        \n        /* Add the undirected arc to the list of arcs */\n        copy_net->add_undirected_arc(arc);\n        \n        /* Connects it to its source and destination */\n        arc->connect();\n    }\n    return copy_net;\n}\n\nconst bool bag_compare(const vector<Node*> & a,const vector<Node*>& b) {\n    return a.size() > b.size();\n}\n\n\nconst bool node_compare(const Node* n1, const Node* n2) {\n    return n1->fill_in > n2->fill_in;\n}\n\nvoid Net::add_node(Node* node) {\n    node->_id = (int) nodes.size();\n    \n    if (!nodeID.insert(pair<string,Node*>(node->_name, node)).second) {\n        cerr << \"ERROR: adding the same node twice!\";\n    }\n    \n    nodes.push_back(node);\n}\n\nNode* Net::get_node(string name) const{\n    return nodeID.find(name)->second;\n}\n\n/* returns the undirected arc formed by node n1 and n2 */\nArc* Net::get_arc(Node* n1, Node* n2) {\n    string src, dest, key, inv_key;\n    src = n1->_name;\n    dest = n2->_name;\n    key.clear();\n    inv_key.clear();\n    key.append(src);\n    inv_key.append(dest);\n    key.append(\",\");\n    inv_key.append(\",\");\n    key.append(dest);\n    inv_key.append(src);\n    map<string, set<Arc*>*>::iterator it= arcID.find(key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            //   if (!a->parallel) {\n            return a;\n            // }\n        }\n    }\n    it = arcID.find(inv_key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            //   if (!a->parallel) {\n            return a;\n            // }\n        }\n    }\n    return nullptr;\n}\n\n/* returns the Id of the arc formed by nodes names n1 and n2 */\n// this assumes that the graph is undirected.\nArc* Net::get_arc(std::string src, std::string dest) {\n    std::string key, inv_key;\n    key.clear();\n    inv_key.clear();\n    key.append(src);\n    inv_key.append(dest);\n    key.append(\",\");\n    inv_key.append(\",\");\n    key.append(dest);\n    inv_key.append(src);\n    map<string, set<Arc*>*>::iterator it= arcID.find(key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            return a;\n        }\n    }\n    \n    it = arcID.find(inv_key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            return a;\n        }\n    }\n    \n    return nullptr;\n}\n\nArc* Net::get_directed_arc(std::string src, std::string dest) {\n    std::string key;\n    key.clear();\n    key.append(src);\n    key.append(\",\");\n    key.append(dest);\n    map<string, set<Arc*>*>::iterator it= arcID.find(key);\n    if (it != arcID.end()) {\n        for (auto a: *it->second) {\n            return a;\n        }\n    }\n\n    return nullptr;\n}\n\nbool Net::add_arc(Arc* a) {\n    bool parallel = false;\n    set<Arc*>* s = NULL;\n    string src, dest, key;\n    src = a->_src->_name;\n    dest = a->_dest->_name;\n    if (src == dest){\n        throw invalid_argument (\"It is now allowed to make a node self connected in gravity. \\n\");\n        \n    }\n    \n    \n    key.clear();\n    key.append(src);\n    key.append(\",\");\n    key.append(dest);\n    \n    if(arcID.find(key)==arcID.end()) {\n        s = new set<Arc*>;\n        s->insert(a);\n        arcID.insert(pair<string, set<Arc*>*>(key,s));\n    }\n    else {\n        if(arcID.find(key)!=arcID.end())\n            s = arcID[key];\n        s->insert(a);\n        Warning(\"\\nWARNING: adding another Directed line between same nodes! \\n Node ID: \" << src << \" and Node ID: \" << dest << endl);\n        a->_parallel = true;\n        parallel = true;\n    }\n    arcMap[a->_name] = a;\n    arcs.push_back(a);\n    return parallel;\n}\n// undirected\nvoid Net::add_undirected_arc(Arc* a) {\n//    bool parallel = false;\n    set<Arc*>* s = NULL;\n    string src, dest, key, key_inv;\n    src = a->_src->_name;\n    dest = a->_dest->_name;\n\n    if (src == dest){\n        throw invalid_argument (\"It is now allowed to make a node self connected in gravity. \\n\");\n    \n    }\n    \n    key.clear();\n    key.append(src);\n    key.append(\",\");\n    key.append(dest);\n    \n    key_inv.clear();\n    key_inv.append(dest);\n    key_inv.append(\",\");\n    key_inv.append(src);\n    \n    if(arcID.find(key)==arcID.end()&& arcID.find(key_inv)==arcID.end()) {\n        s = new set<Arc*>;\n        s->insert(a);\n        arcID.insert(pair<string, set<Arc*>*>(key,s));\n        arcs.push_back(a);\n    }\n}\n\n\n/** remove the arc by\n1. removing it from the arcs list, but without changing the arc id.\n2. removing it from the map container.\n*/\n\nvoid Net::remove_arc(Arc* a) {\n    arcs.erase(arcs.begin()+(a->_id));\n    //arcs[a->_id] = nullptr;\n    arcID.erase(a->_src->_name+\",\"+a->_dest->_name);\n}\n\n// Reading files\nchar* Net::readline(FILE *input)\n{\n    size_t len;\n    // line, max_line_len have been declared\n    if(std::fgets(line,max_line_len,input)==NULL) return NULL;\n\n    while(strrchr(line,'\\n') == NULL)\n    {\n        max_line_len *= 2;\n        line = (char *)realloc(line,max_line_len);\n        len = strlen(line);\n        if(fgets(line+len,max_line_len-len,input) == NULL)\n            break;\n    }\n    return line;\n}\n\nvoid Net::exit_input_error(int line_num) {\n    fprintf(stderr,\"Wrong input format at line %d\\n\", line_num);\n    exit(1);\n}\n\n// Reading graphs with rudy format\nvoid Net::readrudy(const char* fname) {\n    int Num_nodes=0;\n    int Num_edges=0;\n\n    ifstream infile(fname);\n\n    string sLine;\n\n    if (infile.good())\n    {\n        getline(infile, sLine);\n        istringstream iss(sLine);\n        iss >> Num_nodes;\n        iss >> Num_edges;\n    }\n    else{\n        fprintf(stderr,\"can’t open input file %s\\n\",fname);\n        exit(1);\n    }\n    // get nodes\n\n    string name;\n    Node* node = nullptr;\n\n    for (int i= 1; i< Num_nodes + 1; i++) {\n        name = to_string(i);\n        node = new Node(name,i-1);\n        add_node(node);\n    }\n\n\n    // get arcs\n    Arc* arc = NULL;\n\n    // note that src, dest are names of nodes.\n    string src, dest;\n    double weight;\n    while(getline(infile,sLine,'\\n'))\n    {\n        istringstream iss(sLine);\n        iss >> src >> dest >> weight;\n\n        name = (int)arcs.size()+1;\n        arc = new Arc(name);\n\n        arc->_id = (int)arcs.size();\n\n        arc->_src = get_node(src);\n        arc->_dest= get_node(dest);\n        arc->_weight=weight;\n        add_arc(arc);\n        arc->connect();\n    }\n    infile.close();\n}\n\n\n\n/** construct a graph by reading an adjacency matrix */\nvoid Net::read_adjacency_matrix(const string& fname) {\n    FILE *fp = fopen(fname.c_str(),\"r\");\n    if(fp == NULL)\n    {\n            cout << \"Can’t open input file \" << fname;\n            exit(1);\n    }\n    max_line_len = 1024;\n    line = new char[max_line_len];\n\n    vector<vector<int>> matrix;\n    int temp;\n    while(readline(fp)!=NULL)\n    {\n        vector<int> row;\n        stringstream linestream(line);\n        while (linestream>>temp)\n            row.push_back(temp);\n        matrix.push_back(row);\n    }\n    \n    int n=0;\n    n =matrix.size();\n\n    string name;\n    int id = 0;\n\n    Node* node = NULL;\n    for (int i= 0; i<n; i++) {\n        name = to_string(i);\n        node = new Node(name,i);\n        add_node(node);\n    }\n\n    Arc* arc = NULL;\n    string src, dest;\n    unsigned index = 0;\n    for (int i = 0; i <(n); i++)\n        for (int j=i+1; j<n; j++) {\n            if (matrix[i][j] > 0)\n            {\n                src = to_string(i);\n                dest = to_string(j);\n                id = index;\n                arc = new Arc(src + \",\" + dest);\n                arc->_id = id;\n                arc->_src = get_node(src);\n                arc->_dest= get_node(dest);\n                add_arc(arc);\n                arc->connect();\n            }\n            index++;\n        }\n    delete[] line;\n    fclose(fp);\n}\n\nvoid Net::get_complement(const char* fname) {\n    FILE *fp = fopen(fname,\"r\");\n    if(fp == NULL)\n    {\n        fprintf(stderr,\"can’t open input file %s\\n\",fname);\n        exit(1);\n    }\n\n    max_line_len = 1024;\n    line = new char[max_line_len];\n\n    vector<vector<int>> matrix;\n    int temp;\n    while(readline(fp)!=NULL)\n    {\n        vector<int> row;\n        stringstream linestream(line);\n        while (linestream>>temp)\n            row.push_back(temp);\n        matrix.push_back(row);\n    }\n    int n=0;\n    n =matrix.size();\n\n    string name;\n    int id = 0;\n\n    Node* node = NULL;\n    for (int i= 0; i<n; i++) {\n        name = to_string(i);\n        node = new Node(name,i);\n        add_node(node);\n    }\n\n    Arc* arc = NULL;\n    string src, dest;\n\n    for (int i = 0; i <(n-1); i++)\n        for (int j=i+1; j<n; j++) {\n            if (matrix[i][j] == 0)\n            {\n                src = to_string(i);\n                dest = to_string(j);\n                id = (int)arcs.size();\n                arc = new Arc(to_string(id));\n                arc->_id = id;\n                arc->_src = get_node(src);\n                arc->_dest= get_node(dest);\n                add_arc(arc);\n                arc->connect();\n            }\n        }\n    delete[] line;\n    fclose(fp);\n}\n\n\n\n/*  @brief Remove node and all incident arcs from the network\n @note Does not remove the incident arcs from the list of arcs in the network!\n @return the id of the node removed\n */\nstring Net::remove_end_node() {\n    Node* n = nodes.back();\n    Node * nn = nullptr;\n    string n_id = n->_name;\n    for (auto a: n->branches) {\n        nn = a->neighbour(n);\n        nn->removeArc(a);\n        for (auto aa: nn->branches) {\n            if (!aa->neighbour(nn)->is_connected(n)) {\n                nn->fill_in--;\n                assert(nn->fill_in >=0);\n            }\n        }\n    }\n    nodes.pop_back();\n    return n_id;\n}\n\n// use greedy fill-in algorithm.\nvoid Net::get_tree_decomp_bags() {\n    Node* n = nullptr;\n    Node* u = nullptr;\n    Node* nn = nullptr;\n    Arc* arc = nullptr;\n    set<vector<Node*>> unique_bags;\n    string name=\"\";\n    Net* graph_clone = clone_undirected(); //\n    int nb = 0;\n    unsigned max_size = 0;\n    \n    /** cliques with less than 1 nodes are useless for us.*/\n    while (graph_clone->nodes.size()> 2) {\n        sort(graph_clone->nodes.begin(), graph_clone->nodes.end(),node_compare);\n        \n        // last element has the minimum fill-in.\n        n = graph_clone->nodes.back();\n        if(!n->_active) {\n            graph_clone->remove_end_node();\n            continue;\n        }\n        Debug(n->_name << endl);\n        Debug(graph_clone->nodes.size() << endl);\n        vector<Node*> bag_copy;\n        vector<Node*> bag;\n        DebugOff(\"new bag = { \");\n        for (auto nn: n->get_neighbours()) {\n            if(!nn->_active) continue;\n            bag_copy.push_back(nn);\n            bag.push_back(get_node(nn->_name)); // Note it takes original node.\n            DebugOff(nn->_name << \", \");\n        }\n        DebugOff(n->_name << \"}\\n\");\n        graph_clone->remove_end_node();\n        bag_copy.push_back(n);\n        bag.push_back(get_node(n->_name)); // node in this graph\n        sort(bag_copy.begin(), bag_copy.end(), [](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n        sort(bag.begin(), bag.end(), [](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n        \n        // update clone_graph and construct chordal extension.\n        for (int i = 0; i < bag_copy.size(); i++) {\n            u = bag_copy.at(i);\n            for (int j = i+1; j<bag_copy.size(); j++) {\n                nn = bag_copy.at(j);\n                if (u->is_connected(nn)) {\n                    if(get_arc(u,nn) && !get_arc(u,nn)->_active) {\n                        Arc* off_arc = get_arc(u,nn);\n                        off_arc->_imaginary = true;\n                        off_arc->_free = true;\n                    }\n                    continue;\n                }\n                name = to_string((int) graph_clone->arcs.size()+1);\n                arc = new Arc(name);\n                \n                arc->_id = arcs.size();\n                arc->_src = u;\n                arc->_dest = nn;\n                arc->_imaginary = true;\n                arc->_free = true;\n                arc->connect();\n                graph_clone->add_undirected_arc(arc);\n            }\n        }\n        if(unique_bags.insert(bag).second){\n            _bags.push_back(bag); // bag original\n            if (bag_copy.size()==3) {\n                nb++;\n            }\n        }\n        \n        if (bag_copy.size()>max_size) {\n            max_size = bag_copy.size();\n        }\n        delete n;\n    }\n    \n    \n    DebugOn(\"\\n Number of 3D bags = \" << nb << endl);\n    DebugOn(\"\\n Max clique size = \" << max_size << endl);\n    if(max_size==2){\n        this->_tree = true;\n    }\n    \n    delete graph_clone;\n    \n}\n\nstd::vector<std::vector<Node*>> Net::decompose_bags_3d(bool print_bags){\n    set<vector<Node*>> unique_bags;\n    vector<std::vector<Node*>> res;\n    for (auto &bag_copy:_bags) {\n        if(bag_copy.size()==3){\n            if(unique_bags.insert(bag_copy).second){\n                res.push_back(bag_copy);\n            }\n        }\n        else if(bag_copy.size()>3){\n            DebugOff(\"Decomposing bigger bag into 3d bags\\n\");\n            \n            for (auto i = 0; i<bag_copy.size()-2; i++) {\n                for (auto j = i+1; j<bag_copy.size()-1; j++) {\n                    for (auto k = j+1; k<bag_copy.size(); k++) {\n                        vector<Node*> new_bag;\n                        new_bag.push_back(bag_copy[i]);\n                        new_bag.push_back(bag_copy[j]);\n                        new_bag.push_back(bag_copy[k]);\n                        DebugOff(\"new bag = {\");\n                        //                        for (int i=0; i<new_bag.size();     i++) {\n                        //                            cout << new_bag.at(i)->_name << \" \";\n                        //                        }\n                        DebugOff(\"}\" << endl);\n                        if(unique_bags.insert(new_bag).second){\n                            res.push_back(new_bag);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return res;\n}\n\nstd::vector<std::vector<Node*>> Net::decompose_bags_4d(bool print_bags)\n{\n    set<vector<Node*>> unique_bags;\n    vector<std::vector<Node*>> res;\n    for (auto &bag_copy:_bags) {\n        if(bag_copy.size()==4){\n            if(unique_bags.insert(bag_copy).second){\n                res.push_back(bag_copy);\n            }\n        }\n        else if(bag_copy.size()>4){\n            DebugOff(\"Decomposing bigger bag into 4d bags\\n\");\n            \n            for (auto i = 0; i<bag_copy.size()-3; i++) {\n                for (auto j = i+1; j<bag_copy.size()-2; j++) {\n                    for (auto k = j+1; k<bag_copy.size()-1; k++) {\n                        for (auto l = k+1; l<bag_copy.size(); l++) {\n                            vector<Node*> new_bag;\n                            new_bag.push_back(bag_copy[i]);\n                            new_bag.push_back(bag_copy[j]);\n                            new_bag.push_back(bag_copy[k]);\n                            new_bag.push_back(bag_copy[l]);\n                            DebugOff(\"new bag = {\");\n                            //                        for (int i=0; i<new_bag.size();     i++) {\n                            //                            cout << new_bag.at(i)->_name << \" \";\n                            //                        }\n                            DebugOff(\"}\" << endl);\n                            if(unique_bags.insert(new_bag).second){\n                                res.push_back(new_bag);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return res;\n}\n\n/** Return the vector of arcs ignoring parallel lines **/\nindices Net::get_bus_pairs(){\n    if(!bus_pairs.empty()){\n        return bus_pairs;\n    }\n    for (auto a: arcs) {\n        if (!a->_parallel) {\n            bus_pairs.add(a->_src->_name+\",\"+a->_dest->_name);\n        }\n    }\n    return bus_pairs;\n}\n\nvoid Net::Fast_Horton(){\n    \n    Net* copy_net = clone();\n    copy_net->horton_net = new Net();\n    \n    \n    Fast_Horton(copy_net);\n    delete(copy_net);\n}\n\n/* Compare function for Dijkstra's pripority queue based on the distance from the source */\nstruct comparator {\n    bool operator() (Node* arg1, Node* arg2) {\n        return (*arg1).distance > (*arg2).distance;\n    }\n};\n\n/* Reset all distances to max value */\nvoid Net::resetDistance(){\n    for (vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); it++){\n        (*it)->distance = (int)nodes.size()+1;\n        (*it)->predecessor = NULL;\n    }\n}\n\n/* sets the cycle member fo all odes to be false */\nvoid Net::reset_nodeCycle(){\n    vector<Node*>::iterator it = nodes.begin();\n    while (it != nodes.end()) {\n        (*it)->cycle = false;\n        it++;\n    }\n}\n\n/* sets all nodesto unexplored */\nvoid Net::reset_nodeExplored(){\n    vector<Node*>::iterator it = nodes.begin();\n    while (it != nodes.end()) {\n        (*it)->explored = false;\n        it++;\n    }\n}\n\n/* Computes and returns the shortest path between src and dest in net */\nPath* Net::Dijkstra(Node* src, Node* dest, Net* net){\n    priority_queue<Node*, vector<Node*> , comparator> p_queue;\n    net->resetDistance();\n    src->distance = 0;\n    p_queue.push(src);\n    Node* current = NULL;\n    Arc* arc = NULL;\n    while (!p_queue.empty() && current != dest) {\n        current = p_queue.top();\n        p_queue.pop();\n        if (current != dest) {\n            for (vector<Arc*>::iterator it = current->branches.begin(); it != current->branches.end(); ++it) {\n                arc = (*it);\n                if (arc->neighbour(current)->distance > current->distance + 1) {\n                    arc->neighbour(current)->distance = current->distance + 1;\n                    arc->neighbour(current)->predecessor = current;\n                    p_queue.push(arc->neighbour(current));\n                }\n            }\n        }\n        /* Stop when reaching destination */\n        else\n            break;\n    }\n    \n    /* If there is no path between src and dest */\n    if(dest->predecessor==NULL)\n        return NULL;\n    /* Reconstruct path backward */\n    Path* p = new Path();\n    current = dest;\n    while (current) {\n        /* The path should contain a pointer to the original nodes not the current copy */\n        Node* n = get_node(current->_name);\n        p->nodes.push_front(n);\n        current = current->predecessor;\n    }\n    return p;\n}\n\n\nvoid Net::add_horton_nodes(Net* net){\n    Node* copy = NULL;\n    /* Add all neighbours of the end node (lowest degree) */\n    Node* end_n = net->nodes.back();\n    vector<Arc*>::iterator it = end_n->branches.begin();\n    while(it != end_n->branches.end()){\n        copy = (*it)->neighbour(end_n)->clone();\n        net->horton_net->add_node(copy);\n        it++;\n    }\n}\n\n\nvoid Net::add_horton_branches(Net* net){\n    Node* src;\n    Node* dest;\n    Path* shortest;\n    Arc* arc;\n    for (int i=0; i<net->horton_net->nodes.size()-1; i++) {\n        src = net->horton_net->nodes[i];\n        for (int j=i+1; j<net->horton_net->nodes.size(); j++) {\n            dest = net->horton_net->nodes[j];\n            /* computing shortest paths between neighbours of x in G-x */\n            shortest = Dijkstra(net->get_node(src->_name), net->get_node(dest->_name), net);\n            if (shortest!=NULL) {\n                arc = new Arc(src, dest);\n                arc->horton_path = shortest;\n                arc->weight = shortest->length();\n                net->horton_net->add_arc(arc);\n            }\n        }\n    }\n}\n\n/* Compare function for fast_horton algorithm, ranking nodes in decreasing degree */\nbool compareNodes(Node* n1, Node* n2){\n    return n1->degree() > n2->degree();\n}\n\n/* Compare function for minimal_spanning_tree algorithm, ranking arcs in decreasing wheight */\nbool compareArcs(Arc* a1, Arc* a2){\n    return a1->weight > a2->weight;\n}\n\n/* Sort nodes in decreasing degree */\nvoid Net::orderNodes(Net* net){\n    if(!net->nodes.empty())\n        sort(net->nodes.begin(), net->nodes.end(), compareNodes);\n}\n\n\n/* Sort nodes in decreasing degree */\nvoid Net::orderArcs(Net* net){\n    if(!net->arcs.empty())\n        sort(net->arcs.begin(), net->arcs.end(), compareArcs);\n}\n\n/* Erase Horton network and free memory for cloned nodes and created arcs */\nvoid Net::clear_horton_net(){\n    if (!horton_net->nodes.empty()) {\n        for (vector<Node*>::iterator it = horton_net->nodes.begin(); it != horton_net->nodes.end(); ++it) {\n            delete(*it);\n        }\n        horton_net->nodes.clear();\n    }\n    if (!horton_net->arcs.empty()) {\n        for (vector<Arc*>::iterator it = horton_net->arcs.begin(); it != horton_net->arcs.end(); ++it) {\n            delete(*it);\n        }\n        horton_net->arcs.clear();\n    }\n    \n    horton_net->nodeID.clear();\n    \n}\n    \n/*  @brief Computes a spanning tree of minimal weight in horton's network, then adds the corresponding cycles to the original network by connecting to src\n @note Implements Kruskal’s greedy algorithm\n */\nvoid Net::minimal_spanning_tree(Node* src, Net* net){\n    \n    /* Check if the network has atleast one line */\n    if (net->arcs.empty()) {\n        return;\n    }\n    \n    Path* min_tree = new Path();\n    int n = (int)net->nodes.size();\n    orderArcs(net);\n    Arc* a = NULL;\n    a = net->arcs.back();\n    min_tree->nodes.push_back(a->_src);\n    while (min_tree->nodes.size()<n) {\n        a = net->arcs.back();\n        /* Check if at least one node of the arc is not already in the path, in order to avoid creating a cycle */\n        if(find(min_tree->nodes.begin(), min_tree->nodes.end(), a->_src) == min_tree->nodes.end() && find(min_tree->nodes.begin(), min_tree->nodes.end(), a->_dest) == min_tree->nodes.end()){\n            min_tree->nodes.push_back(a->_src);\n            min_tree->nodes.push_back(a->_dest);\n            combine(src, a->horton_path);\n            cycle_basis.push_back(a->horton_path);\n        }\n        else if(find(min_tree->nodes.begin(), min_tree->nodes.end(), a->_src) == min_tree->nodes.end()){\n            min_tree->nodes.push_back(a->_src);\n            combine(src, a->horton_path);\n            cycle_basis.push_back(a->horton_path);\n        }\n        else if (find(min_tree->nodes.begin(), min_tree->nodes.end(), a->_dest) == min_tree->nodes.end()){\n            min_tree->nodes.push_back(a->_dest);\n            combine(src, a->horton_path);\n            cycle_basis.push_back(a->horton_path);\n        }\n        net->arcs.pop_back();\n    }\n    delete min_tree;\n}\n\nvoid Net::Fast_Horton(Net *net){\n    \n    \n    /* Arranging nodes in descending order of degree */\n    orderNodes(net);\n    \n    /* Removing all nodes of degree 1 */\n    while (!net->nodes.empty() && net->nodes.back()->degree()<2) {\n        net->remove_end_node();\n        orderNodes(net);\n    }\n    \n    /* net has no cycles */\n    if(net->nodes.size()<3)\n        return;\n    \n    /* Erase Horton network */\n    net->clear_horton_net();\n    \n    \n    /* Adding nodes to Horton network */\n    add_horton_nodes(net);\n    \n    /* Removing the end node from the original network */\n    string n_id = net->remove_end_node();\n    \n    /* Computing the shortest paths among neighbours of n and creating the corresponding horton network */\n    add_horton_branches(net);\n    \n    /* Computing the minimal spanning tree on the corresponding Horton network */\n    \n    minimal_spanning_tree(get_node(n_id), net->horton_net);\n    \n    while (net->nodes.size()>2)\n        Fast_Horton(net);\n}\n\n\n\n\n//Net* Net::get_chordal_extension() {\n//    Node* n = nullptr;\n//    Node* u = nullptr;\n//    Node* nn = nullptr;\n//    Arc* arc = nullptr;\n//    Arc* arc_chordal = nullptr;\n//\n//    Node* u_chordal = nullptr;\n//    Node* nn_chordal = nullptr;\n//\n//    string name=\"\";\n//    string name_chordal=\"\";\n//    Net* chordal_extension = clone();\n//    Net* graph_clone = clone_undirected();\n//    int nb = 0;\n//\n//    /** cliques with less than 1 nodes are useless for us.*/\n//    while (graph_clone->nodes.size() > 1) {\n//        sort(graph_clone->nodes.begin(), graph_clone->nodes.end(),node_compare);\n//        // last element has the minimum fill-in.\n//        n = graph_clone->nodes.back();\n//        Debug(n->_name << endl);\n//        Debug(_clone->nodes.size() << endl);\n//        vector<Node*> bag_copy;\n//        vector<Node*> bag;\n//        Debug(\"new bag_copy = { \");\n//\n//        for (auto nn: n->get_neighbours()) {\n//            bag_copy.push_back(nn);\n//            bag.push_back(get_node(nn->_name));\n//            Debug(nn->_name << \", \");\n//        }\n//\n//        graph_clone->remove_end_node();\n//        bag_copy.push_back(n);\n//        bag.push_back(get_node(n->_name)); // node in this graph\n//        sort(bag_copy.begin(), bag_copy.end(),[](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n//        sort(bag.begin(), bag.end(),[](const Node* a, const Node* b) -> bool{return a->_id < b->_id;});\n//\n//        // update graph_graph and construct chordal extension.\n//        for (int i = 0; i < bag_copy.size() - 1; i++) {\n//            u = bag_copy.at(i);\n//            u_chordal = chordal_extension->get_node(u->_name);\n//            for (int j = i+1; j<bag_copy.size(); j++) {\n//                nn = bag_copy.at(j);\n//                nn_chordal=chordal_extension->get_node(nn->_name);\n//                if (u->is_connected(nn)) {\n//                    continue;\n//                }\n//                name = to_string((int) graph_clone->arcs.size()+1);\n//                name_chordal = to_string((int)chordal_extension->arcs.size()+1);\n//\n//                arc = new Arc(name);\n//                arc_chordal = new Arc(name_chordal);\n//\n//                arc->_id = arcs.size();\n//                arc->_src = u;\n//                arc->_dest = nn;\n//                arc->connect();\n//                graph_clone->add_undirected_arc(arc);\n//\n//                arc_chordal->_id = chordal_extension->arcs.size();\n//                arc_chordal->_src = u_chordal;\n//                arc_chordal->_dest = nn_chordal;\n//                arc_chordal->connect();\n//                chordal_extension->add_undirected_arc(arc_chordal);\n//            }\n//        }\n//        _bags_copy.push_back(bag_copy);\n//        _bags.push_back(bag);\n//        if (bag_copy.size()==3) {\n//            nb++;\n//        }\n//        delete n;\n//    }\n//    // sort the bags by its size (descending order)\n//    sort(_bags.begin(), _bags.end(), bag_compare);\n//    printf(\"With greedy fill-in algirithm, the chordal graph added  %lu edges \\n\", (chordal_extension->arcs.size() - arcs.size()));\n//\n//    delete graph_clone;\n//    return chordal_extension;\n//}\n\n// get cliques from the tree decomposition\n// Two methods\n// first one: check the inclusion relationship\n// second one: use the RIP property of the tree decomposition, thus just need to check every leaf..\n// One need to execute either get_tree_decomposition or get_chordal_extension first, then run get_clique_tree.\n\n// use _bags instead of bag_copy\n//void Net::get_cliquebags (bool print) {\n//    for (unsigned i = 0; i < _bags.size(); i++) {\n//        for (unsigned j = i+1; j < _bags.size();) {\n//            if (std::includes(_bags[i].begin(),_bags[i].end(),\n//                              _bags[j].begin(), _bags[j].end()))\n//            {\n//                _bags.erase(_bags.begin()+j);\n//            }\n//            else\n//                j++;\n//        }\n//    }\n//    cout << \"Number of maximal cliques of the chordal extension = \" << _bags.size() << endl <<endl;\n//}\n\n/* Destructors */\nNet::~Net() {\n    if (!nodes.empty()) {\n        for (vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); it++) {\n            delete (*it);\n        }\n        nodes.clear();\n    }\n    if(!arcs.empty()) {\n        for (vector<Arc*>::iterator it = arcs.begin(); it != arcs.end(); it++) {\n            if(*it)\n                delete (*it);\n        }\n        arcs.clear();\n    }\n\n    if(!cycle_basis.empty()) {\n        for (vector<Path*>::iterator it = cycle_basis.begin(); it != cycle_basis.end(); it++) {\n            delete (*it);\n        }\n        arcs.clear();\n    }\n    if (horton_net!=NULL)\n        delete horton_net;\n    for (pair<string,set<Arc*>*> it:arcID) {\n        delete it.second;\n    }\n}\n\n/* Combines the src node with the path p to form a cycle */\nvoid Net::combine(Node* src, Path* p){\n    p->nodes.insert(p->nodes.begin(), src);\n    p->nodes.push_back(src);\n}\n\n\n//Net* Net::get_clique_tree(){\n//    Net* cliquetree = new Net();\n//    Node* node = nullptr;\n//    Arc*  a = nullptr;\n//    string name;\n//    get_cliquebags(true);\n//#ifdef USE_BOOST\n//    /** Note that we also need the edge information of the clique tree **/\n//    /** boost graph library or implement the expanded version of MCS algorithm by Blair and Peyton */\n//    typedef boost::adjacency_list <boost::vecS,\n//    boost::vecS,\n//    boost::undirectedS,\n//    boost::no_property,\n//    boost::property < boost::edge_weight_t, int >> Graph;\n//    typedef boost::graph_traits <Graph>::edge_descriptor Edge;\n//    //typedef boost::graph_traits <Graph>::vertex_descriptor Vertex;\n//\n//    // BUILD THE INTERSECTION GRAPH OF THE CLIQUES\n//    typedef std::pair<int, int> E;\n//    std::vector<E> edges;\n//    std::vector<int> weights;\n//    int nb_cliques = this->_bags.size();\n//    for (int i = 0; i < nb_cliques; i++) {\n//        DebugOn(\"bag \" << i << \" has \" << this->_bags[i].size() << \" nodes.\" <<endl);\n//        sort(this->_bags[i].begin(), this->_bags[i].end());\n//        for (int j = i +1; j < nb_cliques; j++) {\n//            vector<Node*> v3;\n//            sort(this->_bags[j].begin(), this->_bags[j].end());\n//            set_intersection(this->_bags[i].begin(), this->_bags[i].end(), this->_bags[j].begin(), this->_bags[j].end(), back_inserter(v3));\n//            if (v3.size() > 0) {\n//                edges.push_back(E(i, j));\n//                weights.push_back(-v3.size());\n//            }\n//        }\n//    }\n//    //size_t num_edges = edges.size();\n//\n//#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n//    Graph g(num_nodes);\n//    boost::property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);\n//    for (std::size_t j = 0; j < num_edges; ++j) {\n//        Edge e;\n//        bool inserted;\n//        boost::tie(e, inserted) = boost::add_edge(edges[j].first, edges[j].second, g);\n//        boost::weightmap[e] = weights[j];\n//    }\n//#else\n//    Graph g(edges.begin(), edges.end(), weights.begin(), nb_cliques);\n//#endif\n//    boost::property_map < Graph, boost::edge_weight_t >::type weight = get(boost::edge_weight, g);\n//    std::vector < Edge > spanning_tree;\n//    boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n//\n//    DebugOn(\"Print the total \" << spanning_tree.size() << \" edges in the clique tree:\" << endl);\n//\n//    //////////CLIQUE TREE /////////////////////////////\n//    for (int i = 0; i < nb_cliques; i++) {\n//        node= new Node(to_string(i), i);\n//        cliquetree->add_node(node);\n//    }\n//\n//    for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n//         ei != spanning_tree.end(); ++ei) {\n//        int u = source(*ei, g);\n//        int v = target(*ei, g);\n//        DebugOn(u << \" <--> \" << v\n//                << \" with weight of \" << -weight[*ei]\n//                << endl);\n//        name = (int) cliquetree->arcs.size();\n//        a = new Arc(name);\n//        a->_id = cliquetree->arcs.size();\n//\n//        // intersection\n//        vector<Node*> v3;\n//        sort(this->_bags[u].begin(), this->_bags[u].end());\n//        sort(this->_bags[v].begin(), this->_bags[v].end());\n//        set_intersection(this->_bags[u].begin(), this->_bags[u].end(),\n//                         this->_bags[v].begin(), this->_bags[v].end(),\n//                         back_inserter(v3));\n//        a->_src = cliquetree->get_node(to_string(u));\n//        a->_dest = cliquetree->get_node(to_string(v));\n//        a->_weight = -weight[*ei];\n//        a->_intersection = v3;\n//        cliquetree->add_arc(a);\n//        a->connect();\n//\n//        for (int i = 0; i < v3.size(); i++){\n//                auto  node = v3.at(i);\n//            for (int j = i+1; j < v3.size(); j++){\n//                auto arc = get_arc(node, v3.at(j));\n//                if (arc != nullptr){\n//                    a->_intersection_clique.push_back(new index_pair(index_(arc->_src->_name), index_(arc->_dest->_name), arc->_active));\n//                }\n//             //   else\n//               //     a->_intersection_clique.push_back(new index_pair(index_(node->_name), index_(v3.at(j)->_name), true));\n//            }\n//        }\n//    }\n//#endif\n//    return cliquetree;\n//}\n\n\n//void Net::chol_decompose(bool print){\n//    arma::mat adjacency_matrix = arma::zeros(nodes.size(), nodes.size());\n//    for (auto &arc: arcs){\n//        adjacency_matrix(arc->_src->_id, arc->_dest->_id) = 1;\n//        adjacency_matrix(arc->_dest->_id, arc->_src->_id) = 1;\n//\n//    }\n//    arma::mat pertubation = arma::zeros(nodes.size(),nodes.size());\n//    // if fails,  make epsilon larger.\n//    unsigned epsilon = 2;\n//    arma::mat adjacency_matrix_psd = adjacency_matrix + epsilon*pertubation.eye();\n//    arma::mat chordal_sparsity = arma::zeros(nodes.size(),nodes.size());\n//    chordal_sparsity = arma::chol(adjacency_matrix_psd);\n//    if (print){\n//        cout << \"chordal sparsity matrix: \\n \" << chordal_sparsity << endl;\n//    }\n//    unsigned num_nonzeros = 0;\n//    for (int i = 0; i < nodes.size(); i++)\n//        for (int j = i+1; j< nodes.size(); j++){\n//            if (chordal_sparsity(i, j) != 0){\n//                num_nonzeros +=1;\n//            }\n//        }\n//    printf(\"With cholesky decomposition, the chordal graph added  %lu edges \\n\", (num_nonzeros - arcs.size()));\n//}\n\n\n//std::vector<gravity::index_pair*> Net::get_bus_pairs_all(){\n//    vector<gravity::index_pair*> res;\n//    string ni, nj;\n//    for(int i = 0; i < nodes.size()-1; i++) {\n//        for(int j = i+1; j < nodes.size(); j++) {\n//            ni = nodes[i]->_name;\n//            nj = nodes[j]->_name;\n//            res.push_back(new index_pair(index_(ni), index_(nj), 1));\n//        }\n//    }\n//    return res;\n//}\n", "meta": {"hexsha": "8d87307ae40d79949c668db26a0ce78acc3fac6e", "size": 36598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Net.cpp", "max_stars_repo_name": "mikiec84/Gravity", "max_stars_repo_head_hexsha": "863a30445ca0d29ccf8c4814fc0c099d1b75e7da", "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/Net.cpp", "max_issues_repo_name": "mikiec84/Gravity", "max_issues_repo_head_hexsha": "863a30445ca0d29ccf8c4814fc0c099d1b75e7da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Net.cpp", "max_forks_repo_name": "mikiec84/Gravity", "max_forks_repo_head_hexsha": "863a30445ca0d29ccf8c4814fc0c099d1b75e7da", "max_forks_repo_licenses": ["BSD-3-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.2462809917, "max_line_length": 190, "alphanum_fraction": 0.5225148915, "num_tokens": 9332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.02635535160340121, "lm_q1q2_score": 0.009376572410214352}}
{"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/Core/Exception.h>\n#include <vw/Math/Vector.h>\n#include <asp/IsisIO/RPNEquation.h>\n\n#include <iomanip>\n#include <stack>\n#include <vector>\n\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n\nusing namespace vw;\nusing namespace asp;\n\n// Constructors\n//-----------------------------------------------------\nRPNEquation::RPNEquation() {\n  m_x_eq.clear();\n  m_x_consts.clear();\n  m_y_eq.clear();\n  m_y_consts.clear();\n  m_z_eq.clear();\n  m_z_consts.clear();\n  m_cached_time = -1;\n  m_time_offset = 0;\n}\nRPNEquation::RPNEquation( std::string x_eq,\n                          std::string y_eq,\n                          std::string z_eq ) {\n  string_to_eqn( x_eq, m_x_eq, m_x_consts );\n  string_to_eqn( y_eq, m_y_eq, m_y_consts );\n  string_to_eqn( z_eq, m_z_eq, m_z_consts );\n  m_cached_time = -1;\n  m_time_offset = 0;\n}\n\n// Update\n//-----------------------------------------------------\nvoid RPNEquation::update( double const& t ) {\n  m_cached_time = t;\n  double delta_t = t - m_time_offset;\n  m_cached_output[0] = evaluate( m_x_eq,\n                                 m_x_consts,\n                                 delta_t );\n  m_cached_output[1] = evaluate( m_y_eq,\n                                 m_y_consts,\n                                 delta_t );\n  m_cached_output[2] = evaluate( m_z_eq,\n                                 m_z_consts,\n                                 delta_t );\n}\nvoid RPNEquation::string_to_eqn( std::string& str,\n                                 std::vector<std::string>& commands,\n                                 std::vector<double>& consts ) {\n  // Breaks a string into the equation format used internally\n  commands.clear();\n  consts.clear();\n  boost::split( commands, str, boost::is_any_of(\" =\"));\n\n  // Cleaning out any tokens that are just \"\"\n  for(std::vector<std::string>::iterator iter = commands.begin();\n      iter != commands.end(); ++iter ) {\n    if ( (*iter) == \"\" ) {\n      iter = commands.erase(iter);\n      iter--;\n    }\n  }\n\n  // Pulling out the numbers\n  for(std::vector<std::string>::iterator iter = commands.begin();\n      iter != commands.end(); ++iter ) {\n    if ( isdigit( (*iter)[(*iter).size()-1] ) ) {\n      consts.push_back( atof( iter->c_str() ) );\n      *iter = \"c\";\n    }\n  }\n}\ndouble RPNEquation::evaluate( std::vector<std::string>& commands,\n                              std::vector<double>& consts,\n                              double const& t ) {\n  // Evaluates an equation in the internal format\n  if ( commands.empty() )\n    return 0;\n  int consts_index = 0;\n  std::stack<double> rpn_stack;\n  double buffer;\n  for ( std::vector<std::string>::iterator iter = commands.begin();\n        iter != commands.end(); ++iter ) {\n    if ( *iter == \"c\" ) {\n      rpn_stack.push( consts[consts_index] );\n      consts_index++;\n    } else if ( *iter == \"t\" ) {\n      rpn_stack.push( t );\n    } else if ( rpn_stack.size() < 1 ) {\n      vw_throw( IOErr() << \"Insufficient arguments for RPN command: \"\n                << *iter << \"\\n\" );\n    } else if ( *iter == \"sin\" ) {\n      buffer = sin( rpn_stack.top() );\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( *iter == \"cos\" ) {\n      buffer = cos( rpn_stack.top() );\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( *iter == \"tan\" ) {\n      buffer = tan( rpn_stack.top() );\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( *iter == \"abs\" ) {\n      buffer = fabs( rpn_stack.top() );\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( rpn_stack.size() < 2 ) {\n      vw_throw( IOErr() << \"Insufficient arguments for command: \"\n                << *iter << \"\\n\" );\n    } else if ( *iter == \"*\" ) {\n      buffer = rpn_stack.top();\n      rpn_stack.pop();\n      buffer *= rpn_stack.top();\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( *iter == \"/\" ) {\n      buffer = rpn_stack.top();\n      rpn_stack.pop();\n      buffer = rpn_stack.top() / buffer;\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( *iter == \"-\" ) {\n      buffer = rpn_stack.top();\n      rpn_stack.pop();\n      buffer = rpn_stack.top() - buffer;\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( *iter == \"+\" ) {\n      buffer = rpn_stack.top();\n      rpn_stack.pop();\n      buffer += rpn_stack.top();\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else if ( *iter == \"^\" ) {\n      buffer = rpn_stack.top();\n      rpn_stack.pop();\n      buffer = pow( rpn_stack.top(), buffer );\n      rpn_stack.pop();\n      rpn_stack.push( buffer );\n    } else {\n      vw_throw( IOErr() << \"Unknown RPN operator: \" << *iter << \"\\n\" );\n    }\n  } // End of calculator\n\n  if ( rpn_stack.size() != 1 )\n    vw_throw( IOErr() << \"Unbalanced RPN equation! More constants than need by operators.\\n\" );\n\n  return rpn_stack.top();\n}\n\n// FileIO\n//-----------------------------------------------------\nvoid RPNEquation::write( std::ofstream &f ) {\n  for ( int i = 0; i < 3; i++ ) {\n    std::vector<std::string>* eq_ptr;\n    std::vector<double>* cs_ptr;\n    switch(i) {\n    case 0:\n      eq_ptr = &m_x_eq;\n      cs_ptr = &m_x_consts;\n      break;\n    case 1:\n      eq_ptr = &m_y_eq;\n      cs_ptr = &m_y_consts;\n      break;\n    case 2:\n      eq_ptr = &m_z_eq;\n      cs_ptr = &m_z_consts;\n      break;\n    }\n\n    f << std::setprecision( 15 );\n    int cs_idx = 0;\n    for ( unsigned j = 0; j < eq_ptr->size(); j++ ) {\n      if ( (*eq_ptr)[j] == \"c\" ) {\n        f << (*cs_ptr)[cs_idx] << \" \";\n        cs_idx++;\n      } else {\n        f << (*eq_ptr)[j] << \" \";\n      }\n    }\n    f << \"\\n\";\n  }\n}\nvoid RPNEquation::read( std::ifstream &f ) {\n  std::string buffer;\n  m_cached_time = -1;\n\n  buffer = \"\";\n  std::getline( f, buffer );\n  string_to_eqn( buffer, m_x_eq, m_x_consts );\n  buffer = \"\";\n  std::getline( f, buffer );\n  string_to_eqn( buffer, m_y_eq, m_y_consts );\n  buffer = \"\";\n  std::getline( f, buffer );\n  string_to_eqn( buffer, m_z_eq, m_z_consts );\n}\n\n// Constant Access\n//-----------------------------------------------------\ndouble& RPNEquation::operator[]( size_t const& n ) {\n  m_cached_time = -1;\n  if ( n >= m_x_consts.size() + m_y_consts.size()\n       + m_z_consts.size() )\n    vw_throw( ArgumentErr() << \"RPNEquation: invalid index.\" );\n  if ( n < m_x_consts.size() )\n    return m_x_consts[n];\n  else if ( n < m_x_consts.size() + m_y_consts.size() )\n    return m_y_consts[n-m_x_consts.size()];\n  return m_z_consts[n-m_x_consts.size()-m_y_consts.size()];\n}\n", "meta": {"hexsha": "1d6336399b6c25319295d1ad04ba9e61d8ef4218", "size": 7305, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/IsisIO/RPNEquation.cc", "max_stars_repo_name": "fenglang12345/StereoPipeline-2.4.0", "max_stars_repo_head_hexsha": "a9cb9129013f278e9f65e435193b735a6b051eb9", "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/asp/IsisIO/RPNEquation.cc", "max_issues_repo_name": "fenglang12345/StereoPipeline-2.4.0", "max_issues_repo_head_hexsha": "a9cb9129013f278e9f65e435193b735a6b051eb9", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/IsisIO/RPNEquation.cc", "max_forks_repo_name": "fenglang12345/StereoPipeline-2.4.0", "max_forks_repo_head_hexsha": "a9cb9129013f278e9f65e435193b735a6b051eb9", "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.9533898305, "max_line_length": 95, "alphanum_fraction": 0.5518138261, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.02716922868024295, "lm_q1q2_score": 0.00937624402541164}}
{"text": "/////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Ion Gaztanaga  2007-2013\n//\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://www.boost.org/libs/intrusive for documentation.\n//\n/////////////////////////////////////////////////////////////////////////////\n// The implementation of splay trees is based on the article and code published\n// in C++ Users Journal \"Implementing Splay Trees in C++\" (September 1, 2005).\n//\n// The splay code has been modified and (supposedly) improved by Ion Gaztanaga.\n//\n// Here is the copyright notice of the original file containing the splay code:\n//\n//  splay_tree.h -- implementation of a STL compatible splay tree.\n//\n//  Copyright (c) 2004 Ralf Mattethat\n//\n//  Permission to copy, use, modify, sell and distribute this software\n//  is granted provided this copyright notice appears in all copies.\n//  This software is provided \"as is\" without express or implied\n//  warranty, and with no claim as to its suitability for any purpose.\n//\n/////////////////////////////////////////////////////////////////////////////\n\n#ifndef BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\n#define BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\n\n#include <boost/intrusive/detail/config_begin.hpp>\n#include <boost/intrusive/detail/assert.hpp>\n#include <boost/intrusive/intrusive_fwd.hpp>\n#include <boost/intrusive/pointer_traits.hpp>\n#include <cstddef>\n#include <boost/intrusive/detail/utilities.hpp>\n#include <boost/intrusive/bstree_algorithms.hpp>\n\nnamespace boost {\nnamespace intrusive {\n\n/// @cond\nnamespace detail {\n\ntemplate<class NodeTraits>\nstruct splaydown_rollback\n{\n   typedef typename NodeTraits::node_ptr node_ptr;\n   splaydown_rollback( const node_ptr *pcur_subtree, const node_ptr & header\n                     , const node_ptr & leftmost           , const node_ptr & rightmost)\n      : pcur_subtree_(pcur_subtree)  , header_(header)\n      , leftmost_(leftmost)   , rightmost_(rightmost)\n   {}\n\n   void release()\n   {  pcur_subtree_ = 0;  }\n\n   ~splaydown_rollback()\n   {\n      if(pcur_subtree_){\n         //Exception can only be thrown by comp, but\n         //tree invariants still hold. *pcur_subtree is the current root\n         //so link it to the header.\n         NodeTraits::set_parent(*pcur_subtree_, header_);\n         NodeTraits::set_parent(header_, *pcur_subtree_);\n         //Recover leftmost/rightmost pointers\n         NodeTraits::set_left (header_, leftmost_);\n         NodeTraits::set_right(header_, rightmost_);\n      }\n   }\n   const node_ptr *pcur_subtree_;\n   node_ptr header_, leftmost_, rightmost_;\n};\n\n}  //namespace detail {\n/// @endcond\n\n//!   A splay tree is an implementation of a binary search tree. The tree is\n//!   self balancing using the splay algorithm as described in\n//!\n//!      \"Self-Adjusting Binary Search Trees\n//!      by Daniel Dominic Sleator and Robert Endre Tarjan\n//!      AT&T Bell Laboratories, Murray Hill, NJ\n//!      Journal of the ACM, Vol 32, no 3, July 1985, pp 652-686\n//!\n//! splaytree_algorithms is configured with a NodeTraits class, which encapsulates the\n//! information about the node to be manipulated. NodeTraits must support the\n//! following interface:\n//!\n//! <b>Typedefs</b>:\n//!\n//! <tt>node</tt>: The type of the node that forms the binary search tree\n//!\n//! <tt>node_ptr</tt>: A pointer to a node\n//!\n//! <tt>const_node_ptr</tt>: A pointer to a const node\n//!\n//! <b>Static functions</b>:\n//!\n//! <tt>static node_ptr get_parent(const_node_ptr n);</tt>\n//!\n//! <tt>static void set_parent(node_ptr n, node_ptr parent);</tt>\n//!\n//! <tt>static node_ptr get_left(const_node_ptr n);</tt>\n//!\n//! <tt>static void set_left(node_ptr n, node_ptr left);</tt>\n//!\n//! <tt>static node_ptr get_right(const_node_ptr n);</tt>\n//!\n//! <tt>static void set_right(node_ptr n, node_ptr right);</tt>\ntemplate<class NodeTraits>\nclass splaytree_algorithms\n   #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n   : public bstree_algorithms<NodeTraits>\n   #endif\n{\n   /// @cond\n   private:\n   typedef bstree_algorithms<NodeTraits> bstree_algo;\n   /// @endcond\n\n   public:\n   typedef typename NodeTraits::node            node;\n   typedef NodeTraits                           node_traits;\n   typedef typename NodeTraits::node_ptr        node_ptr;\n   typedef typename NodeTraits::const_node_ptr  const_node_ptr;\n\n   //! This type is the information that will be\n   //! filled by insert_unique_check\n   typedef typename bstree_algo::insert_commit_data insert_commit_data;\n\n   public:\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n   //! @copydoc ::boost::intrusive::bstree_algorithms::get_header(const const_node_ptr&)\n   static node_ptr get_header(const const_node_ptr & n);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::begin_node\n   static node_ptr begin_node(const const_node_ptr & header);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::end_node\n   static node_ptr end_node(const const_node_ptr & header);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::swap_tree\n   static void swap_tree(const node_ptr & header1, const node_ptr & header2);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::swap_nodes(const node_ptr&,const node_ptr&)\n   static void swap_nodes(const node_ptr & node1, const node_ptr & node2);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::swap_nodes(const node_ptr&,const node_ptr&,const node_ptr&,const node_ptr&)\n   static void swap_nodes(const node_ptr & node1, const node_ptr & header1, const node_ptr & node2, const node_ptr & header2);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::replace_node(const node_ptr&,const node_ptr&)\n   static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & new_node);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::replace_node(const node_ptr&,const node_ptr&,const node_ptr&)\n   static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & header, const node_ptr & new_node);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::unlink(const node_ptr&)\n   static void unlink(const node_ptr & node);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::unlink_leftmost_without_rebalance\n   static node_ptr unlink_leftmost_without_rebalance(const node_ptr & header);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::unique(const const_node_ptr&)\n   static bool unique(const const_node_ptr & node);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::size(const const_node_ptr&)\n   static std::size_t size(const const_node_ptr & header);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::next_node(const node_ptr&)\n   static node_ptr next_node(const node_ptr & node);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::prev_node(const node_ptr&)\n   static node_ptr prev_node(const node_ptr & node);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::init(const node_ptr&)\n   static void init(const node_ptr & node);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::init_header(const node_ptr&)\n   static void init_header(const node_ptr & header);\n   \n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::erase(const node_ptr&,const node_ptr&)\n   //! Additional notes: the previous node of z is splayed. The \"splay\" parameter which indicated if splaying\n   //! should be performed, it's deprecated and will disappear in future versions.\n   static void erase(const node_ptr & header, const node_ptr & z, bool splay = true)\n   {\n      //posibility 1\n      if(splay && NodeTraits::get_left(z)){\n         splay_up(bstree_algo::prev_node(z), header);\n      }\n      /*\n      //possibility 2\n      if(splay && NodeTraits::get_left(z)){\n         node_ptr l = NodeTraits::get_left(z);\n         splay_up(l, header);\n      }*//*\n      if(splay && NodeTraits::get_left(z)){\n         node_ptr l = bstree_algo::prev_node(z);\n         splay_up_impl(l, z);\n      }*/\n      /*\n      //possibility 4\n      if(splay){\n         splay_up(z, header);\n      }*/\n\n      //if(splay)\n         //splay_up(z, header);\n      bstree_algo::erase(header, z);\n   }\n\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n   //! @copydoc ::boost::intrusive::bstree_algorithms::clone(const const_node_ptr&,const node_ptr&,Cloner,Disposer)\n   template <class Cloner, class Disposer>\n   static void clone\n      (const const_node_ptr & source_header, const node_ptr & target_header, Cloner cloner, Disposer disposer);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::clear_and_dispose(const node_ptr&,Disposer)\n   template<class Disposer>\n   static void clear_and_dispose(const node_ptr & header, Disposer disposer);\n\n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n   //! @copydoc ::boost::intrusive::bstree_algorithms::count(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional notes: the first node of the range is splayed.\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::size_t count\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {\n      std::pair<node_ptr, node_ptr> ret = equal_range(header, key, comp);\n      std::size_t n = 0;\n      while(ret.first != ret.second){\n         ++n;\n         ret.first = next_node(ret.first);\n      }\n      return n;\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::count(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional note: no splaying is performed\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::size_t count\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {  return bstree_algo::count(header, key, comp);  }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::lower_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional notes: the first node of the range is splayed. The \"splay\" parameter which indicated if splaying\n   //! should be performed, it's deprecated and will disappear in future versions.\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr lower_bound\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      //splay_down(detail::uncast(header), key, comp);\n      node_ptr y = bstree_algo::lower_bound(header, key, comp);\n      if(splay) splay_up(y, detail::uncast(header));\n      return y;\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::lower_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional note: no splaying is performed\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr lower_bound\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {  return bstree_algo::lower_bound(header, key, comp);  }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::upper_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional notes: the first node of the range is splayed. The \"splay\" parameter which indicated if splaying\n   //! should be performed, it's deprecated and will disappear in future versions.\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr upper_bound\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      //splay_down(detail::uncast(header), key, comp);\n      node_ptr y = bstree_algo::upper_bound(header, key, comp);\n      if(splay) splay_up(y, detail::uncast(header));\n      return y;\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::upper_bound(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional note: no splaying is performed\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr upper_bound\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {  return bstree_algo::upper_bound(header, key, comp);  }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::find(const const_node_ptr&, const KeyType&,KeyNodePtrCompare)\n   //! Additional notes: the found node of the lower bound is splayed. The \"splay\" parameter which indicated if splaying\n   //! should be performed, it's deprecated and will disappear in future versions.\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr find\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      if(splay) splay_down(detail::uncast(header), key, comp);\n      node_ptr end = detail::uncast(header);\n      node_ptr y = bstree_algo::lower_bound(header, key, comp);\n      node_ptr r = (y == end || comp(key, y)) ? end : y;\n      return r;\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::find(const const_node_ptr&, const KeyType&,KeyNodePtrCompare)\n   //! Additional note: no splaying is performed\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr find\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {  return bstree_algo::find(header, key, comp);  }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::equal_range(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional notes: the first node of the range is splayed. The \"splay\" parameter which indicated if splaying\n   //! should be performed, it's deprecated and will disappear in future versions.\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, node_ptr> equal_range\n      (const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      //splay_down(detail::uncast(header), key, comp);\n      std::pair<node_ptr, node_ptr> ret = bstree_algo::equal_range(header, key, comp);\n      if(splay) splay_up(ret.first, detail::uncast(header));\n      return ret;\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::equal_range(const const_node_ptr&,const KeyType&,KeyNodePtrCompare)\n   //! Additional note: no splaying is performed\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, node_ptr> equal_range\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {  return bstree_algo::equal_range(header, key, comp);  }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::bounded_range(const const_node_ptr&,const KeyType&,const KeyType&,KeyNodePtrCompare,bool,bool)\n   //! Additional notes: the first node of the range is splayed. The \"splay\" parameter which indicated if splaying\n   //! should be performed, it's deprecated and will disappear in future versions.\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, node_ptr> bounded_range\n      (const node_ptr & header, const KeyType &lower_key, const KeyType &upper_key, KeyNodePtrCompare comp\n      , bool left_closed, bool right_closed, bool splay = true)\n   {\n      std::pair<node_ptr, node_ptr> ret =\n         bstree_algo::bounded_range(header, lower_key, upper_key, comp, left_closed, right_closed);\n      if(splay) splay_up(ret.first, detail::uncast(header));\n      return ret;\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::bounded_range(const const_node_ptr&,const KeyType&,const KeyType&,KeyNodePtrCompare,bool,bool)\n   //! Additional note: no splaying is performed\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, node_ptr> bounded_range\n      (const const_node_ptr & header, const KeyType &lower_key, const KeyType &upper_key, KeyNodePtrCompare comp\n      , bool left_closed, bool right_closed)\n   {  return bstree_algo::bounded_range(header, lower_key, upper_key, comp, left_closed, right_closed);  }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal_upper_bound(const node_ptr&,const node_ptr&,NodePtrCompare)\n   //! Additional note: the inserted node is splayed\n   template<class NodePtrCompare>\n   static node_ptr insert_equal_upper_bound\n      (const node_ptr & header, const node_ptr & new_node, NodePtrCompare comp)\n   {\n      splay_down(header, new_node, comp);\n      return bstree_algo::insert_equal_upper_bound(header, new_node, comp);\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal_lower_bound(const node_ptr&,const node_ptr&,NodePtrCompare)\n   //! Additional note: the inserted node is splayed\n   template<class NodePtrCompare>\n   static node_ptr insert_equal_lower_bound\n      (const node_ptr & header, const node_ptr & new_node, NodePtrCompare comp)\n   {\n      splay_down(header, new_node, comp);\n      return bstree_algo::insert_equal_lower_bound(header, new_node, comp);\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_equal(const node_ptr&,const node_ptr&,const node_ptr&,NodePtrCompare)\n   //! Additional note: the inserted node is splayed\n   template<class NodePtrCompare>\n   static node_ptr insert_equal\n      (const node_ptr & header, const node_ptr & hint, const node_ptr & new_node, NodePtrCompare comp)\n   {\n      splay_down(header, new_node, comp);\n      return bstree_algo::insert_equal(header, hint, new_node, comp);\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_before(const node_ptr&,const node_ptr&,const node_ptr&)\n   //! Additional note: the inserted node is splayed\n   static node_ptr insert_before\n      (const node_ptr & header, const node_ptr & pos, const node_ptr & new_node)\n   {\n      bstree_algo::insert_before(header, pos, new_node);\n      splay_up(new_node, header);\n      return new_node;\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::push_back(const node_ptr&,const node_ptr&)\n   //! Additional note: the inserted node is splayed\n   static void push_back(const node_ptr & header, const node_ptr & new_node)\n   {\n      bstree_algo::push_back(header, new_node);\n      splay_up(new_node, header);\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::push_front(const node_ptr&,const node_ptr&)\n   //! Additional note: the inserted node is splayed\n   static void push_front(const node_ptr & header, const node_ptr & new_node)\n   {\n      bstree_algo::push_front(header, new_node);\n      splay_up(new_node, header);\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_check(const const_node_ptr&,const KeyType&,KeyNodePtrCompare,insert_commit_data&)\n   //! Additional note: nodes with the given key are splayed\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, bool> insert_unique_check\n      (const node_ptr & header, const KeyType &key\n      ,KeyNodePtrCompare comp, insert_commit_data &commit_data)\n   {\n      splay_down(header, key, comp);\n      return bstree_algo::insert_unique_check(header, key, comp, commit_data);\n   }\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_check(const const_node_ptr&,const node_ptr&,const KeyType&,KeyNodePtrCompare,insert_commit_data&)\n   //! Additional note: nodes with the given key are splayed\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, bool> insert_unique_check\n      (const node_ptr & header, const node_ptr &hint, const KeyType &key\n      ,KeyNodePtrCompare comp, insert_commit_data &commit_data)\n   {\n      splay_down(header, key, comp);\n      return bstree_algo::insert_unique_check(header, hint, key, comp, commit_data);\n   }\n\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n   //! @copydoc ::boost::intrusive::bstree_algorithms::insert_unique_commit(const node_ptr&,const node_ptr&,const insert_commit_data&)\n   static void insert_unique_commit\n      (const node_ptr & header, const node_ptr & new_value, const insert_commit_data &commit_data);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::is_header\n   static bool is_header(const const_node_ptr & p);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::rebalance\n   static void rebalance(const node_ptr & header);\n\n   //! @copydoc ::boost::intrusive::bstree_algorithms::rebalance_subtree\n   static node_ptr rebalance_subtree(const node_ptr & old_root);\n\n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n\n   // bottom-up splay, use data_ as parent for n    | complexity : logarithmic    | exception : nothrow\n   static void splay_up(const node_ptr & node, const node_ptr & header)\n   {\n      // If (node == header) do a splay for the right most node instead\n      // this is to boost performance of equal_range/count on equivalent containers in the case\n      // where there are many equal elements at the end\n      node_ptr n((node == header) ? NodeTraits::get_right(header) : node);\n      node_ptr t(header);\n\n      if( n == t ) return;\n\n      for( ;; ){\n         node_ptr p(NodeTraits::get_parent(n));\n         node_ptr g(NodeTraits::get_parent(p));\n\n         if( p == t )   break;\n\n         if( g == t ){\n            // zig\n            rotate(n);\n         }\n         else if ((NodeTraits::get_left(p) == n && NodeTraits::get_left(g) == p)    ||\n                  (NodeTraits::get_right(p) == n && NodeTraits::get_right(g) == p)  ){\n            // zig-zig\n            rotate(p);\n            rotate(n);\n         }\n         else{\n            // zig-zag\n            rotate(n);\n            rotate(n);\n         }\n      }\n   }\n\n   // top-down splay | complexity : logarithmic    | exception : strong, note A\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr splay_down(const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {\n      if(!NodeTraits::get_parent(header))\n         return header;\n      //Most splay tree implementations use a dummy/null node to implement.\n      //this function. This has some problems for a generic library like Intrusive:\n      //\n      // * The node might not have a default constructor.\n      // * The default constructor could throw.\n      //\n      //We already have a header node. Leftmost and rightmost nodes of the tree\n      //are not changed when splaying (because the invariants of the tree don't\n      //change) We can back up them, use the header as the null node and\n      //reassign old values after the function has been completed.\n      node_ptr t = NodeTraits::get_parent(header);\n      //Check if tree has a single node\n      if(!NodeTraits::get_left(t) && !NodeTraits::get_right(t))\n         return t;\n      //Backup leftmost/rightmost\n      node_ptr leftmost (NodeTraits::get_left(header));\n      node_ptr rightmost(NodeTraits::get_right(header));\n      {\n         //Anti-exception rollback, recovers the original header node if an exception is thrown.\n         detail::splaydown_rollback<NodeTraits> rollback(&t, header, leftmost, rightmost);\n         node_ptr null_node = header;\n         node_ptr l = null_node;\n         node_ptr r = null_node;\n\n         for( ;; ){\n            if(comp(key, t)){\n               if(NodeTraits::get_left(t) == node_ptr() )\n                  break;\n               if(comp(key, NodeTraits::get_left(t))){\n                  t = bstree_algo::rotate_right(t);\n\n                  if(NodeTraits::get_left(t) == node_ptr())\n                     break;\n                  link_right(t, r);\n               }\n               else if(comp(NodeTraits::get_left(t), key)){\n                  link_right(t, r);\n\n                  if(NodeTraits::get_right(t) == node_ptr() )\n                     break;\n                  link_left(t, l);\n               }\n               else{\n                  link_right(t, r);\n               }\n            }\n            else if(comp(t, key)){\n               if(NodeTraits::get_right(t) == node_ptr() )\n                  break;\n\n               if(comp(NodeTraits::get_right(t), key)){\n                     t = bstree_algo::rotate_left( t );\n\n                     if(NodeTraits::get_right(t) == node_ptr() )\n                        break;\n                     link_left(t, l);\n               }\n               else if(comp(key, NodeTraits::get_right(t))){\n                  link_left(t, l);\n\n                  if(NodeTraits::get_left(t) == node_ptr())\n                     break;\n\n                  link_right(t, r);\n               }\n               else{\n                  link_left(t, l);\n               }\n            }\n            else{\n               break;\n            }\n         }\n\n         assemble(t, l, r, null_node);\n         rollback.release();\n      }\n\n      //Now recover the original header except for the\n      //splayed root node.\n      //t is the current root\n      NodeTraits::set_parent(header, t);\n      NodeTraits::set_parent(t, header);\n      //Recover leftmost/rightmost pointers\n      NodeTraits::set_left (header, leftmost);\n      NodeTraits::set_right(header, rightmost);\n      return t;\n   }\n\n   private:\n\n   /// @cond\n\n   // assemble the three sub-trees into new tree pointed to by t    | complexity : constant        | exception : nothrow\n   static void assemble(const node_ptr &t, const node_ptr & l, const node_ptr & r, const const_node_ptr & null_node )\n   {\n      NodeTraits::set_right(l, NodeTraits::get_left(t));\n      NodeTraits::set_left(r, NodeTraits::get_right(t));\n\n      if(NodeTraits::get_right(l) != node_ptr()){\n         NodeTraits::set_parent(NodeTraits::get_right(l), l);\n      }\n\n      if(NodeTraits::get_left(r) != node_ptr()){\n         NodeTraits::set_parent(NodeTraits::get_left(r), r);\n      }\n\n      NodeTraits::set_left (t, NodeTraits::get_right(null_node));\n      NodeTraits::set_right(t, NodeTraits::get_left(null_node));\n\n      if( NodeTraits::get_left(t) != node_ptr() ){\n         NodeTraits::set_parent(NodeTraits::get_left(t), t);\n      }\n\n      if( NodeTraits::get_right(t) ){\n         NodeTraits::set_parent(NodeTraits::get_right(t), t);\n      }\n   }\n\n   // break link to left child node and attach it to left tree pointed to by l   | complexity : constant | exception : nothrow\n   static void link_left(node_ptr & t, node_ptr & l)\n   {\n      NodeTraits::set_right(l, t);\n      NodeTraits::set_parent(t, l);\n      l = t;\n      t = NodeTraits::get_right(t);\n   }\n\n   // break link to right child node and attach it to right tree pointed to by r | complexity : constant | exception : nothrow\n   static void link_right(node_ptr & t, node_ptr & r)\n   {\n      NodeTraits::set_left(r, t);\n      NodeTraits::set_parent(t, r);\n      r = t;\n      t = NodeTraits::get_left(t);\n   }\n\n   // rotate n with its parent                     | complexity : constant    | exception : nothrow\n   static void rotate(const node_ptr & n)\n   {\n      node_ptr p = NodeTraits::get_parent(n);\n      node_ptr g = NodeTraits::get_parent(p);\n      //Test if g is header before breaking tree\n      //invariants that would make is_header invalid\n      bool g_is_header = bstree_algo::is_header(g);\n\n      if(NodeTraits::get_left(p) == n){\n         NodeTraits::set_left(p, NodeTraits::get_right(n));\n         if(NodeTraits::get_left(p) != node_ptr())\n            NodeTraits::set_parent(NodeTraits::get_left(p), p);\n         NodeTraits::set_right(n, p);\n      }\n      else{ // must be ( p->right == n )\n         NodeTraits::set_right(p, NodeTraits::get_left(n));\n         if(NodeTraits::get_right(p) != node_ptr())\n            NodeTraits::set_parent(NodeTraits::get_right(p), p);\n         NodeTraits::set_left(n, p);\n      }\n\n      NodeTraits::set_parent(p, n);\n      NodeTraits::set_parent(n, g);\n\n      if(g_is_header){\n         if(NodeTraits::get_parent(g) == p)\n            NodeTraits::set_parent(g, n);\n         else{//must be ( g->right == p )\n            BOOST_INTRUSIVE_INVARIANT_ASSERT(false);\n            NodeTraits::set_right(g, n);\n         }\n      }\n      else{\n         if(NodeTraits::get_left(g) == p)\n            NodeTraits::set_left(g, n);\n         else  //must be ( g->right == p )\n            NodeTraits::set_right(g, n);\n      }\n   }\n\n   /// @endcond\n};\n\n/// @cond\n\ntemplate<class NodeTraits>\nstruct get_algo<SplayTreeAlgorithms, NodeTraits>\n{\n   typedef splaytree_algorithms<NodeTraits> type;\n};\n\n/// @endcond\n\n} //namespace intrusive\n} //namespace boost\n\n#include <boost/intrusive/detail/config_end.hpp>\n\n#endif //BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\n", "meta": {"hexsha": "d9ce54cdac851e82d4b3fda4b56ad7d8422bde33", "size": 27994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/intrusive/splaytree_algorithms.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-02-24T14:48:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T21:37:26.000Z", "max_issues_repo_path": "boost/intrusive/splaytree_algorithms.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-02-25T20:45:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-28T18:05:45.000Z", "max_forks_repo_path": "boost/intrusive/splaytree_algorithms.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2017-11-01T03:30:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-28T21:57:33.000Z", "avg_line_length": 40.9269005848, "max_line_length": 166, "alphanum_fraction": 0.6695720512, "num_tokens": 6897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651623644570757, "lm_q2_score": 0.03963884193722745, "lm_q1q2_score": 0.009375229712059317}}
{"text": "#include \"NuiKinfuCPUDepthTracker.h\"\n\n#include \"NuiKinfuCPUUtilities.h\"\n#include \"NuiKinfuCPUFrame.h\"\n#include \"NuiKinfuCPUFeedbackFrame.h\"\n#include \"../NuiKinfuCameraState.h\"\n\n#include \"Foundation/NuiDebugMacro.h\"\n#include \"Foundation/NuiCholesky.h\"\n\n#include <iostream>\n#include <boost/smart_ptr.hpp>\n\n#define KINFU_ICP_CORESPS_NUM 29\n#define WORK_GROUP_SIZE 128\n\nusing Eigen::AngleAxisf;\n\nNuiKinfuCPUDepthTracker::NuiKinfuCPUDepthTracker(const NuiTrackerConfig& config, UINT nWidth, UINT nHeight)\n\t: m_configuration(config)\n\t, m_error(0.0f)\n\t, m_numValidPoints(0)\n{\n\tAcquireBuffers(nWidth, nHeight);\n}\n\nNuiKinfuCPUDepthTracker::~NuiKinfuCPUDepthTracker()\n{\n\tReleaseBuffers();\n}\n\nvoid\tNuiKinfuCPUDepthTracker::AcquireBuffers( UINT nWidth, UINT nHeight)\n{\n\tconst NuiTrackerConfig::ITERATION_CLASS& iterations = m_configuration.iterations;\n\tfor (UINT i = 1; i < iterations.size(); i ++)\n\t{\n\t\tNuiFloatImage* depths = new NuiFloatImage();\n\t\tdepths->AllocateBuffer(nWidth>>i, nHeight>>i);\n\t\tm_depthsHierarchy.push_back(depths);\n\n\t\tNuiFloat3Image* vertices = new NuiFloat3Image();\n\t\tvertices->AllocateBuffer(nWidth>>i, nHeight>>i);\n\t\tm_verticesHierarchy.push_back(vertices);\n\t}\n}\n\nvoid\tNuiKinfuCPUDepthTracker::ReleaseBuffers()\n{\n\tfor (UINT i = 1; i < m_depthsHierarchy.size(); i ++)\n\t{\n\t\tNuiFloatImage* depths = m_depthsHierarchy.at(i);\n\t\tSafeDelete(depths);\n\n\t\tNuiFloat3Image* vertices = m_verticesHierarchy.at(i);\n\t\tSafeDelete(vertices);\n\t}\n\tm_depthsHierarchy.clear();\n\tm_verticesHierarchy.clear();\n}\n\nvoid NuiKinfuCPUDepthTracker::log(const std::string& fileName) const\n{\n\tm_configuration.log(fileName);\n}\n\nbool\tNuiKinfuCPUDepthTracker::EstimatePose(\n\tNuiKinfuFrame* pFrame,\n\tNuiKinfuFeedbackFrame* pFeedbackFrame,\n\tNuiKinfuCameraState* pCameraState,\n\tEigen::Affine3f *hint\n\t)\n{\n\tif(!pFrame)\n\t\treturn false;\n\tNuiKinfuCPUFrame* pCPUFrame = dynamic_cast<NuiKinfuCPUFrame*>(pFrame);\n\tif(!pCPUFrame)\n\t\treturn false;\n\n\t// half sample the input depth maps into the pyramid levels\n\tSubSampleDepths(pCPUFrame->GetFilteredDepthBuffer());\n\n\tif(!pCameraState)\n\t\treturn false;\n\n\tHierarchyDepth2vertex(pCameraState->GetCameraPos().getIntrinsics());\n\n\tif(!pFeedbackFrame)\n\t\treturn false;\n\tNuiKinfuCPUFeedbackFrame* pCPUFeedbackFrame = dynamic_cast<NuiKinfuCPUFeedbackFrame*>(pFeedbackFrame);\n\tif(!pCPUFeedbackFrame)\n\t\treturn false;\n\n\treturn IterativeClosestPoint(\n\t\tpCPUFrame->GetVertexBuffer(),\n\t\tpCPUFeedbackFrame->GetVertexBuffer(),\n\t\tpCPUFeedbackFrame->GetNormalsBuffer(),\n\t\tpCPUFrame->GetWidth(),\n\t\tpCPUFrame->GetHeight(),\n\t\tpCameraState,\n\t\thint);\n}\n\nvoid NuiKinfuCPUDepthTracker::SubSampleDepths(float* filteredDepths)\n{\n\t// Sub sample\n\tfloat depthThreshold = m_configuration.depth_threshold;\n\tconst int subSampleRadius = 1;\n\tUINT nBufferSize = (UINT)m_depthsHierarchy.size();\n\tfor (UINT i = 0; i < nBufferSize; ++i)\n\t{\n\t\tNuiFloatImage* depthsDstImg = m_depthsHierarchy.at(i);\n\t\tif(!depthsDstImg)\n\t\t\tcontinue;\n\n\t\tfloat* depthsSrcBuffer = (i > 0) ? m_depthsHierarchy.at(i-1)->GetBuffer() : filteredDepths;\n\t\tfloat* depthsDstBuffer = depthsDstImg->GetBuffer();\n\t\tif(!depthsSrcBuffer || !depthsDstBuffer)\n\t\t\tcontinue;\n\n\t\tUINT rangeX = depthsDstImg->GetWidth();\n\t\tUINT rangeY = depthsDstImg->GetHeight();\n#ifdef WITH_OPENMP\n\t\t#pragma omp parallel for\n#endif\n\t\tfor (UINT y = 0; y < rangeY; y++)\n\t\t{\n\t\t\tfor (UINT x = 0; x < rangeX; x++)\n\t\t\t{\n\t\t\t\tconst UINT dstId = y * rangeX + x;\n\n\t\t\t\tconst UINT src_x = x << 1;\n\t\t\t\tconst UINT src_y = y << 1;\n\t\t\t\tconst UINT src_size_x = rangeX << 1;\n\t\t\t\tconst UINT srcId = src_y * src_size_x + src_x;\n\t\t\t\tfloat center = depthsSrcBuffer[srcId];\n\n\t\t\t\tfloat sumDepth = 0.0f;\n\t\t\t\tint sumWeight = 0;\n\t\t\t\tfor(int cy = -subSampleRadius; cy <= subSampleRadius; ++ cy)\n\t\t\t\t{\n\t\t\t\t\tfor(int cx = -subSampleRadius; cx <= subSampleRadius; ++ cx)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst int nearX = x + cx;\n\t\t\t\t\t\tconst int nearY = y + cy;\n\t\t\t\t\t\tif( nearX>=0 && nearX<(int)rangeX && nearY>=0 && nearY<(int)rangeY )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int nearId = nearY * rangeX + nearX;\n\t\t\t\t\t\t\tfloat near = depthsSrcBuffer[nearId];\n\t\t\t\t\t\t\tif(near > 0.0f && (center == NAN_FLOAT || fabs(center - near) < depthThreshold))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsumDepth += near;\n\t\t\t\t\t\t\t\tsumWeight += 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\tdepthsDstBuffer[dstId] = (sumWeight > 0) ? sumDepth/sumWeight : NAN_FLOAT;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NuiKinfuCPUDepthTracker::HierarchyDepth2vertex(NuiCameraIntrinsics cameraIntrics)\n{\n\tfor (UINT i = 0; i < m_depthsHierarchy.size(); ++i)\n\t{\n\t\tint div = 1 << (i+1);\n\n\t\t// depth2vertex\n\t\tNuiFloatImage* depthsImg = m_depthsHierarchy.at(i);\n\t\tNuiFloat3Image* verticesImg = m_verticesHierarchy.at(i);\n\t\tif(!depthsImg || !verticesImg)\n\t\t\tcontinue;\n\n\t\tfloat* depthsBuffer = depthsImg->GetBuffer();\n\t\tVector3f* verticesBuffer = verticesImg->GetBuffer();\n\t\tif(!depthsBuffer || !verticesBuffer)\n\t\t\tcontinue;\n\n\t\tUINT rangeX = depthsImg->GetWidth();\n\t\tUINT rangeY = depthsImg->GetHeight();\n#ifdef WITH_OPENMP\n\t\t#pragma omp parallel for\n#endif\n\t\tfor (UINT y = 0; y < rangeY; y++)\n\t\t{\n\t\t\tfor (UINT x = 0; x < rangeX; x++)\n\t\t\t{\n\t\t\t\tconst UINT id = y * rangeX + x;\n\t\t\t\tfloat dp = depthsBuffer[id];\n\n\t\t\t\tif(dp != NAN_FLOAT)\n\t\t\t\t{\n\t\t\t\t\tconst float intr_fx_inv = div / cameraIntrics.m_fx;\n\t\t\t\t\tconst float intr_fy_inv = div / cameraIntrics.m_fy;\n\t\t\t\t\tconst float intr_cx = cameraIntrics.m_cx / div;\n\t\t\t\t\tconst float intr_cy = cameraIntrics.m_cy / div;\n\t\t\t\t\tverticesBuffer[id][0] = dp * ((float)x - intr_cx) * intr_fx_inv;\n\t\t\t\t\tverticesBuffer[id][1] = dp * ((float)y - intr_cy) * intr_fy_inv;\n\t\t\t\t\tverticesBuffer[id][2] = dp;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tverticesBuffer[id] = Vector3f(NAN_FLOAT, NAN_FLOAT, NAN_FLOAT);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nVector3f NuiKinfuCPUDepthTracker::InterpolateBilinear_withHoles(const Vector3f* source, Vector2f position, UINT nWidth)\n{\n\tVector3f a, b, c, d;\n\tVector3f result;\n\tEigen::Vector2i p; Vector2f delta;\n\n\tp[0] = (int)floor(position[0]); p[1] = (int)floor(position[1]);\n\tdelta[0] = position[0] - (float)p[0]; delta[1] = position[1] - (float)p[1];\n\n\ta = source[p[0] + p[1] * nWidth];\n\tb = source[(p[0] + 1) + p[1] * nWidth];\n\tc = source[p[0] + (p[1] + 1) * nWidth];\n\td = source[(p[0] + 1) + (p[1] + 1) * nWidth];\n\n\tif (_IsNan(a))\n\t\tdelta[0] = 1.0f;\n\tif (_IsNan(b))\n\t\tdelta[0] = 0.0f;\n\tif (_IsNan(c))\n\t\tdelta[1] = 1.0f;\n\tif (_IsNan(d))\n\t\tdelta[1] = 0.0f;\n\n\tresult[0] = ((float)a[0] * (1.0f - delta[0]) * (1.0f - delta[1]) + (float)b[0] * delta[0] * (1.0f - delta[1]) +\n\t\t(float)c[0] * (1.0f - delta[0]) * delta[1] + (float)d[0] * delta[0] * delta[1]);\n\tresult[1] = ((float)a[1] * (1.0f - delta[0]) * (1.0f - delta[1]) + (float)b[1] * delta[0] * (1.0f - delta[1]) +\n\t\t(float)c[1] * (1.0f - delta[0]) * delta[1] + (float)d[1] * delta[0] * delta[1]);\n\tresult[2] = ((float)a[2] * (1.0f - delta[0]) * (1.0f - delta[1]) + (float)b[2] * delta[0] * (1.0f - delta[1]) +\n\t\t(float)c[2] * (1.0f - delta[0]) * delta[1] + (float)d[2] * delta[0] * delta[1]);\n\n\treturn result;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////\n// Iterative Closest Point\nbool NuiKinfuCPUDepthTracker::IterativeClosestPoint(\n\tVector3f* verticesBuffer,\n\tVector3f* verticesPrevBuffer,\n\tVector3f* normalsPrevBuffer,\n\tUINT\tnWidth,\n\tUINT\tnHeight,\n\tNuiKinfuCameraState* pCameraState,\n\tEigen::Affine3f *hint\n\t)\n{\n\tif(!pCameraState)\n\t\treturn false;\n\n\tconst NuiCameraIntrinsics& cameraIntrinsics = pCameraState->GetCameraPos().getIntrinsics();\n\tconst Matrix3frm& Rprev = pCameraState->GetCameraPos().getRotation();\n\tconst Vector3f& tprev = pCameraState->GetCameraPos().getLocalTranslation();\n\n\tMatrix3frm Rinv;\n\tVector3f tcurr;\n\tif(hint)\n\t{\n\t\tRinv = hint->rotation().inverse();\n\t\ttcurr = hint->translation().matrix();\n\t}\n\telse\n\t{\n\t\tRinv = Rprev.inverse(); // tranform to global coo for ith camera pose\n\t\ttcurr = tprev;\n\t}\n\n\t/** \\brief array with IPC iteration numbers for each pyramid level */\n\tconst NuiTrackerConfig::ITERATION_CLASS& iterations = m_configuration.iterations;\n\tint LEVELS = (int)iterations.size();\n\tfloat distThreshStep = m_configuration.dist_threshold / LEVELS;\n\tfloat distThresh = m_configuration.dist_threshold + distThreshStep;\n\n\t//ScopeTime time(\"icp-all\");\n\tfor (int level_index = LEVELS-1; level_index>=0; --level_index)\n\t{\n\t\tVector3f* vertices = verticesBuffer;\n\t\tUINT rangeX = nWidth;\n\t\tUINT rangeY = nHeight;\n\n\t\tif(level_index > 0)\n\t\t{\n\t\t\tvertices = m_verticesHierarchy.at(level_index-1)->GetBuffer();\n\t\t\trangeX = m_verticesHierarchy.at(level_index-1)->GetWidth();\n\t\t\trangeY = m_verticesHierarchy.at(level_index-1)->GetHeight();\n\t\t}\n\t\tif(!vertices)\n\t\t\tcontinue;\n\n\t\t//Vector3f* normalsBuffer = m_normals.GetBuffer();\n\n\t\tint iter_num = iterations[level_index].m_num;\n\t\tNuiTrackerConfig::TrackerIterationType iter_type = iterations[level_index].m_type;\n\t\tbool bShortIteration = (NuiTrackerConfig::eTracker_Iteration_Both != iter_type);\n\t\tconst int numPara = bShortIteration ? 3 : 6;\n\t\tconst int numParaSQ = bShortIteration ? 3 + 2 + 1 : 6 + 5 + 4 + 3 + 2 + 1;\n\n\t\t// Reset params\n\t\tm_error = 1e20f;\n\t\tm_numValidPoints = 0;\n\t\tfloat lambda = 1.0;\n\t\tMatrix3frm lastGoodRotInv = Rinv;\n\t\tVector3f lastGoodTrans = tcurr;\n\t\tdistThresh = distThresh - distThreshStep;\n\n\t\tfor (int iter = 0; iter < iter_num; ++iter)\n\t\t{\n\t\t\tfloat sumF = 0.0f;\n\t\t\tfloat sumHessian[6 * 6], sumNabla[6];\n\t\t\tmemset(sumHessian, 0, sizeof(float) * numParaSQ);\n\t\t\tmemset(sumNabla, 0, sizeof(float) * numPara);\n\t\t\tfor (UINT y = 0; y < rangeY; y ++)\n\t\t\t{\n\t\t\t\tfor (UINT x = 0; x < rangeX; x ++)\n\t\t\t\t{\n\t\t\t\t\tconst UINT id = y * rangeX + x;\n\t\t\t\t\tVector3f vert = vertices[id];\n\t\t\t\t\tif(_IsNan(vert))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tVector3f projectedVert = Rinv * (vert - tcurr);\n\t\t\t\t\tVector3f projectedPos = Rprev * projectedVert + tprev;\n\t\t\t\t\tVector2f projPixel( projectedPos[0] * cameraIntrinsics.m_fx / projectedPos[2] + cameraIntrinsics.m_cx,\n\t\t\t\t\t\t\t\t\t\tprojectedPos[1] * cameraIntrinsics.m_fy / projectedPos[2] + cameraIntrinsics.m_cy);\n\t\t\t\t\tif(projPixel[0] < 0 || (UINT)projPixel[0] >= nWidth-1 || projPixel[1] < 0 || (UINT)projPixel[1] >= nHeight-1)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tVector3f referenceVert = InterpolateBilinear_withHoles(verticesPrevBuffer, projPixel, nWidth);\n\t\t\t\t\tif(_IsNan(referenceVert))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tVector3f ptDiff = referenceVert - projectedVert;\n\t\t\t\t\tfloat dist = ptDiff.norm();\n\t\t\t\t\tif (dist > distThresh)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tVector3f referenceNorm = InterpolateBilinear_withHoles(normalsPrevBuffer, projPixel, nWidth);\n\t\t\t\t\tif(_IsNan(referenceNorm))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t/*if (normalsBuffer)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector3f norm = normalsBuffer[id];\n\t\t\t\t\t\tfloat sine = norm.cross(referenceNorm).norm();\n\t\t\t\t\t\tif(sine < m_configuration.normal_threshold)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}*/\n\n\t\t\t\t\tfloat b = referenceNorm.dot(ptDiff);\n\n\t\t\t\t\tVector3f row0 = projectedVert.cross(referenceNorm);\n\t\t\t\t\tfloat A[6];\n\t\t\t\t\tif (NuiTrackerConfig::eTracker_Iteration_Rotation == iter_type)\n\t\t\t\t\t{\n\t\t\t\t\t\tA[0] = row0[0];\n\t\t\t\t\t\tA[1] = row0[1];\n\t\t\t\t\t\tA[2] = row0[2];\n\t\t\t\t\t}\n\t\t\t\t\telse if (NuiTrackerConfig::eTracker_Iteration_Translation == iter_type)\n\t\t\t\t\t{\n\t\t\t\t\t\tA[0] = referenceNorm[0];\n\t\t\t\t\t\tA[1] = referenceNorm[1];\n\t\t\t\t\t\tA[2] = referenceNorm[2];\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tA[0] = row0[0];\n\t\t\t\t\t\tA[1] = row0[1];\n\t\t\t\t\t\tA[2] = row0[2];\n\t\t\t\t\t\tA[3] = referenceNorm[0];\n\t\t\t\t\t\tA[4] = referenceNorm[1];\n\t\t\t\t\t\tA[5] = referenceNorm[2];\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat localF = b * b;\n\t\t\t\t\tfloat localHessian[6 + 5 + 4 + 3 + 2 + 1], localNabla[6];\n\t\t\t\t\tfor (int r = 0, counter = 0; r < numPara; r++)\n\t\t\t\t\t{\n\t\t\t\t\t\tlocalNabla[r] = b * A[r];\n\t\t\t\t\t\tfor (int c = 0; c <= r; c++, counter++)\n\t\t\t\t\t\t\tlocalHessian[counter] = A[r] * A[c];\n\t\t\t\t\t}\n\n\t\t\t\t\t// sum\n\t\t\t\t\tm_numValidPoints ++;\n\t\t\t\t\tsumF += localF;\n\t\t\t\t\tfor (int i = 0; i < numPara; i++)\n\t\t\t\t\t\tsumNabla[i] += localNabla[i];\n\t\t\t\t\tfor (int i = 0; i < numParaSQ; i++)\n\t\t\t\t\t\tsumHessian[i] += localHessian[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// build hessian\n\t\t\tfloat hessian[6 * 6];\n\t\t\tfor (int r = 0, counter = 0; r < numPara; r++)\n\t\t\t\tfor (int c = 0; c <= r; c++, counter++)\n\t\t\t\t\thessian[r + c * 6] = sumHessian[counter];\n\t\t\tfor (int r = 0; r < numPara; ++r)\n\t\t\t\tfor (int c = r + 1; c < numPara; c++)\n\t\t\t\t\thessian[r + c * 6] = hessian[c + r * 6];\n\t\t\tfloat nabla[6];\n\t\t\tmemcpy(nabla, sumNabla, numPara * sizeof(float));\n\t\t\tfloat current_error = (m_numValidPoints > 100) ? sqrt(sumF) / m_numValidPoints : 1e5f;\n\t\t\tif ((m_numValidPoints <= 0) || (current_error > m_error))\n\t\t\t{\n\t\t\t\tRinv = lastGoodRotInv;\n\t\t\t\ttcurr = lastGoodTrans;\n\t\t\t\tlambda *= 10.0f;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlastGoodRotInv = Rinv;\n\t\t\t\tlastGoodTrans = tcurr;\n\t\t\t\tm_error = current_error;\n\n\t\t\t\tfor (int i = 0; i < 6*6; ++i) hessian[i] = hessian[i] / m_numValidPoints;\n\t\t\t\tfor (int i = 0; i < 6; ++i) nabla[i] = nabla[i] / m_numValidPoints;\n\t\t\t\tlambda /= 10.0f;\n\t\t\t}\n\t\t\tfor (int i = 0; i < 6; ++i)\n\t\t\t\thessian[i+i*6] *= 1.0f + lambda;\n\n\t\t\tif(!m_numValidPoints)\n\t\t\t\tbreak;\n\n\t\t\t// ComputeDelta\n\t\t\tfloat step[6];\n\t\t\tfor (int i = 0; i < 6; i++)\n\t\t\t\tstep[i] = 0;\n\t\t\tif (bShortIteration)\n\t\t\t{\n\t\t\t\tfloat smallHessian[3 * 3];\n\t\t\t\tfor (int r = 0; r < 3; r++) for (int c = 0; c < 3; c++) smallHessian[r + c * 3] = hessian[r + c * 6];\n\n\t\t\t\tNuiCholesky cholA(smallHessian, 3);\n\t\t\t\tcholA.Backsub(step, nabla);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tNuiCholesky cholA(hessian, 6);\n\t\t\t\tcholA.Backsub(step, nabla);\n\t\t\t}\n\n\t\t\t// ApplyDelta\n\t\t\tswitch (iter_type)\n\t\t\t{\n\t\t\tcase NuiTrackerConfig::eTracker_Iteration_Rotation:\n\t\t\t\t{\n\t\t\t\t\tEigen::Matrix3f Rinc;\n\t\t\t\t\tRinc.setIdentity();\n\t\t\t\t\tRinc(0,1) = - step[2];\n\t\t\t\t\tRinc(1,0) = step[2];\n\t\t\t\t\tRinc(0,2) = step[1];\n\t\t\t\t\tRinc(2,0) = - step[1];\n\t\t\t\t\tRinc(1,2) = - step[0];\n\t\t\t\t\tRinc(2,1) = step[0];\n\t\t\t\t\tRinv = Rinc * Rinv;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase NuiTrackerConfig::eTracker_Iteration_Translation:\n\t\t\t\t{\n\t\t\t\t\ttcurr += Vector3f(step[0], step[1], step[2]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\tcase NuiTrackerConfig::eTracker_Iteration_Both:\n\t\t\t\t{\n\t\t\t\t\tEigen::Matrix3f Rinc;\n\t\t\t\t\tRinc.setIdentity();\n\t\t\t\t\tRinc(0,1) = - step[2];\n\t\t\t\t\tRinc(1,0) = step[2];\n\t\t\t\t\tRinc(0,2) = step[1];\n\t\t\t\t\tRinc(2,0) = - step[1];\n\t\t\t\t\tRinc(1,2) = - step[0];\n\t\t\t\t\tRinc(2,1) = step[0];\n\t\t\t\t\tVector3f tinc(step[3], step[4], step[5]);\n\t\t\t\t\tRinv = Rinc * Rinv;\n\t\t\t\t\ttcurr = Rinc * tcurr + tinc;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// HasConverged\n\t\t\tfloat stepLength = 0.0f;\n\t\t\tfor (int i = 0; i < 6; i++)\n\t\t\t\tstepLength += step[i] * step[i];\n\n\t\t\tif (sqrt(stepLength) / 6 < m_configuration.track_threshold)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpCameraState->UpdateCameraTransform(Rinv.inverse(), tcurr);\n\n#ifdef _DEBUG\n\t//For debug\n\t//std::cout << \"t:\" << tcurr[0] << \"\\t\" << tcurr[1] << \"\\t\" << tcurr[2] << std::endl;\n#endif\n\n\treturn true;\n}\n\n", "meta": {"hexsha": "48bf926ba4f8f71288876fffb6d88858e0ba10af", "size": 14424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SLAM/VisualOdometry/DeviceSpecific/CPU/NuiKinfuCPUDepthTracker.cpp", "max_stars_repo_name": "hustztz/NatureUserInterfaceStudio", "max_stars_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-14T13:04:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-01T09:58:27.000Z", "max_issues_repo_path": "src/SLAM/VisualOdometry/DeviceSpecific/CPU/NuiKinfuCPUDepthTracker.cpp", "max_issues_repo_name": "hustztz/NatureUserInterfaceStudio", "max_issues_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SLAM/VisualOdometry/DeviceSpecific/CPU/NuiKinfuCPUDepthTracker.cpp", "max_forks_repo_name": "hustztz/NatureUserInterfaceStudio", "max_forks_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-21T15:33:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T15:33:35.000Z", "avg_line_length": 28.171875, "max_line_length": 119, "alphanum_fraction": 0.6362312812, "num_tokens": 4850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.025565212624026678, "lm_q1q2_score": 0.009371944908692104}}
{"text": "#pragma comment(lib,\"winmm.lib\")\r\n#pragma comment(lib,\"wsock32.lib\")\r\n\r\n#include \"rtklib/rtklib.h\"\r\n#include <Eigen/Dense>\r\n\r\n#include \"utilities.h\"\r\n#include \"WeightLeastSquare.h\"\r\n#include \"SelectEphemeris.h\"\r\n\r\n#include \"shadowMatching.h\"\r\n\r\n\r\n//#define TARGETWEEK 1997\r\n//#define STARTTIME 218012\r\n//#define ENDTIME   218014\r\n\r\nstd::string main_directory = \"result\\\\\";\r\nstd::string data_name = \"v2v107M\";\r\n\r\n//read the rinex obx and nav(ephemeris) using rtklib function\r\nextern int readobsnav(gtime_t ts, gtime_t te, double ti, char **infile,\r\n\tconst int *index, int n, const prcopt_t *prcopt,\r\n\tobs_t *obs, nav_t *nav, sta_t *sta)\r\n{\r\n\tint nepoch = 0;            /* number of observation epochs */\r\n\tint i, j, ind = 0, nobs = 0, rcv = 1;\r\n\tprintf(\"%d %d %d %d\\n\", index[0], index[1], index[2], index[3]); // to read two obs file\r\n\tobs->data = NULL; obs->n = obs->nmax = 0;\r\n\tnav->eph = NULL; nav->n = nav->nmax = 0;\r\n\tnav->geph = NULL; nav->ng = nav->ngmax = 0;\r\n\tnav->seph = NULL; nav->ns = nav->nsmax = 0;\r\n\r\n\tfor (i = 0; i < n; i++) {\r\n\r\n\t\tif (index[i] != ind) {\r\n\t\t\tif (obs->n > nobs) rcv++;\r\n\t\t\tind = index[i]; nobs = obs->n;\r\n\t\t}\r\n\t\t//read rinex obs and nav file \r\n\t\tif (readrnxt(infile[i], rcv, ts, te, ti, prcopt->rnxopt[rcv <= 1 ? 0 : 1], obs, nav,\r\n\t\t\trcv <= 2 ? sta + rcv - 1 : NULL) < 0) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\tif (obs->n <= 0) {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tnepoch = sortobs(obs);\r\n\r\n\t/*\r\n\tif (nav->n<=0&&nav->ng<=0&&nav->ns<=0) {\r\n\treturn 0;\r\n\t}\r\n\t*/\r\n\t// delete duplicated ephemeris\r\n\t//uniqnav(nav);\r\n\r\n\t// set time span for progress display \r\n\tif (ts.time == 0 || te.time == 0)\r\n\t{\r\n\t\tfor (i = 0; i < obs->n; i++)\r\n\t\t\tif (obs->data[i].rcv == 1)\r\n\t\t\t\tbreak;\r\n\t\tfor (j = obs->n - 1; j >= 0; j--)\r\n\t\t\tif (obs->data[j].rcv == 1)\r\n\t\t\t\tbreak;\r\n\t\tif (i < j) {\r\n\t\t\tif (ts.time == 0) ts = obs->data[i].time;\r\n\t\t\tif (te.time == 0) te = obs->data[j].time;\r\n\t\t\tsettspan(ts, te);\r\n\t\t}\r\n\t}\r\n\r\n\treturn 1;\r\n}\r\n\r\n//read the precise ephemeris (not used in 3D-GNSS code)\r\nstatic void readpreceph(char **infile, int n, const prcopt_t *prcopt,\r\n\tnav_t *nav, sbs_t *sbs, lex_t *lex)\r\n{\r\n\tseph_t seph0 = { 0 };\r\n\tint i;\r\n\t//    char *ext;\r\n\r\n\ttrace(3, \"readpreceph: n=%d\\n\", n);\r\n\r\n\tnav->ne = nav->nemax = 0;\r\n\tnav->nc = nav->ncmax = 0;\r\n\tsbs->n = sbs->nmax = 0;\r\n\tlex->n = lex->nmax = 0;\r\n\r\n\t/* read precise ephemeris files */\r\n\tfor (i = 0; i < n; i++) {\r\n\t\tif (strstr(infile[i], \"%r\") || strstr(infile[i], \"%b\")) continue;\r\n\t\treadsp3(infile[i], nav, 0);\r\n\t}\r\n\t/* read precise clock files */\r\n\tfor (i = 0; i < n; i++) {\r\n\t\tif (strstr(infile[i], \"%r\") || strstr(infile[i], \"%b\")) continue;\r\n\t\treadrnxc(infile[i], nav);\r\n\t}\r\n\t/* read sbas message files */\r\n\tfor (i = 0; i < n; i++) {\r\n\t\tif (strstr(infile[i], \"%r\") || strstr(infile[i], \"%b\")) continue;\r\n\t\tsbsreadmsg(infile[i], prcopt->sbassatsel, sbs);\r\n\t}\r\n\t/* read lex message files */\r\n\tfor (i = 0; i < n; i++) {\r\n\t\tif (strstr(infile[i], \"%r\") || strstr(infile[i], \"%b\")) continue;\r\n\t\tlexreadmsg(infile[i], 0, lex);\r\n\t}\r\n\t/* allocate sbas ephemeris */\r\n\tnav->ns = nav->nsmax = NSATSBS * 2;\r\n\tif (!(nav->seph = (seph_t *)malloc(sizeof(seph_t)*nav->ns))) {\r\n\t\tshowmsg(\"error : sbas ephem memory allocation\");\r\n\t\ttrace(1, \"error : sbas ephem memory allocation\");\r\n\t\treturn;\r\n\t}\r\n\tfor (i = 0; i < nav->ns; i++) nav->seph[i] = seph0;\r\n\r\n}\r\n\r\n\r\n\r\n/* main function */\r\nint main(int argc, char * argv[])\r\n{\r\n\r\n#ifdef STARTTIME\r\n\tgtime_t ts = gpst2time(TARGETWEEK, STARTTIME);\r\n#else\t\r\n\tgtime_t ts = { 0 }; ts.time = 0;\t\t\t\t\t\t\t// start time (0:all)\r\n#endif\r\n\r\n#ifdef \tENDTIME\r\n\tgtime_t te = gpst2time(TARGETWEEK, ENDTIME);\r\n#else\r\n\tgtime_t te = { 0 }; te.time = 0;\t\t\t\t\t\t\t// end time (0:all)\t\r\n#endif\r\n\r\n\t\t/* Configuration of RTKLIB ------------------------*/\r\n\tint n = 0, i, stat;\r\n\r\n\tdouble ti = 0.0;\t\t\t\t\t\t// processing interval  (s) (0:all)\r\n\tdouble tu = 0.0;\t\t\t\t\t\t// unit time (s) (0:all)\t\r\n\r\n\t/* options */\r\n\tprcopt_t prcopt = prcopt_default;\t// processing option\r\n\tsolopt_t solopt = solopt_default;\t// output solution option\r\n\tfilopt_t filopt = { \"\" };\t            // file option\r\n\r\n\tprcopt.mode = 2;\t\t\t\t// 0: SPP 1: DGNSS 2:Kinematic RTK\r\n\tprcopt.navsys = SYS_ALL;\r\n\tprcopt.nf = 1;\t\t\t\t\t\t// frequency (1:L1,2:L1+L2,3:L1+L2+L5) \r\n\tprcopt.soltype = 0;\t\t\t\t\t// 0:forward,1:backward,2:combined\r\n\tprcopt.elmin = 10.0*D2R;\t\t\t\t// elevation mask (rad)\t\r\n\tprcopt.tidecorr = 0;\t\t\t\t\t// earth tide correction (0:off,1-:on) \r\n\tprcopt.posopt[4] = 0;               // use RAIM FDE (qmo)\r\n\tprcopt.tropopt = TROPOPT_SAAS;        // troposphere option: Saastamoinen model\r\n\tprcopt.ionoopt = IONOOPT_BRDC;\t\t// ionosphere option: Broad cast\r\n\tprcopt.sateph = EPHOPT_BRDC;\t\t\t// ephemeris option: broadcast ephemeris\r\n\r\n\tprcopt.modear = 1;\t\t\t\t\t// AR mode (0:off,1:continuous,2:instantaneous,3:fix and hold)\r\n\r\n\t// HKSC\r\n\tprcopt.rb[0] = -2414266.9197;           // base position for relative mode {x,y,z} (ecef) (m)\r\n\tprcopt.rb[1] = 5386768.9868;\t\t\t// base position for relative mode {x,y,z} (ecef) (m)\r\n\tprcopt.rb[2] = 2407460.0314;\t\t\t// base position for relative mode {x,y,z} (ecef) (m)\r\n\r\n\tsolopt.outopt = 1;\t\t\t\t\t// output processing options (0:no,1:yes)\r\n\tsolopt.timef = 0;\t\t\t\t\t\t// time format (0:sssss.s,1:yyyy/mm/dd hh:mm:ss.s)\r\n\tsolopt.timeu = 3;\t\t\t\t\t\t// time digits under decimal point\r\n\tsolopt.sep[0] = ',';\t\t\t\t\t// field separator\r\n\tsolopt.sstat = 0;\t\t\t\t\t\t// solution statistics level (0:off,1:states,2:residuals)\r\n\tsolopt.trace = 0;\t\t\t\t\t\t// debug trace level (0:off,1-5:debug)\r\n\tsolopt.sstat = 0;\t\t\t\t\t\t// get the solution file\r\n\tsolopt.posf = SOLF_XYZ;\r\n\tsolopt.height = 0;\r\n\r\n\tchar *rov = \"\", *base = \"\";\r\n\tchar infile_[5][1024] = { \"\" }, *infile[5];\r\n\tchar outfile[1024];\r\n\r\n\tshadowMatching SM_;\r\n\r\n\t/* set input files */\r\n\tfor (i = 0; i < 5; i++) infile[i] = infile_[i];\r\n\tstrcpy(infile[n++], \"data\\\\v2v107M2.obs\");\r\n\tstrcpy(infile[n++], \"data\\\\hksc107m.18n\");\r\n\tstrcpy(infile[n++], \"data\\\\hksc107m.18g\");\r\n\r\n\t//strcpy(infile[n++], \"data\\\\TSTb120L.obs\");\r\n\t//strcpy(infile[n++], \"data\\\\hksc1200.18n\");\r\n\t//strcpy(infile[n++], \"data\\\\hksc1200.18g\");\r\n\r\n\t/**************************************************/\r\n\r\n\r\n\t/*starting to read the obs and nav rinex data*/\r\n\tint index[4] = { 0 };\r\n\r\n\tobs_t obss = { 0 };          /* observation data */\r\n\tnav_t navs = { 0 };          /* navigation data */\r\n\tsta_t stas[MAXRCV];      /* station infomation */\r\n\tlex_t lexs = { 0 };          /* lex messages */\r\n\r\n\tif (prcopt.mode == PMODE_KINEMA || prcopt.mode == PMODE_DGPS) {\r\n\t\tindex[1] = 1;\r\n\t\tindex[2] = 2;\r\n\t\tindex[3] = 0;\r\n\t}\r\n\r\n\t// Step1: rinex obs and nav to variable obss and navs! @@@\r\n\tif (!readobsnav(ts, te, ti, infile, index, n, &prcopt, &obss, &navs, stas)) return 0;\r\n\tprintf(\"obss.n = %d\\n\", obss.n);\r\n\tprintf(\"navs.n navs.ng = %d %d\\n\", navs.n, navs.ng);\r\n\r\n\t// show raw measurement obss nav\r\n\r\n\t/*Initializa the output file in RTKLIB format*/\r\n\tFILE * fp;\r\n\t//std::string rtklibName2 = main_directory + data_name + \".pos\";\r\n\tstd::string rtklibName2 = main_directory + \"SM_\" + \".pos\";\r\n\tfopen_s(&fp, rtklibName2.c_str(), \"w\");\r\n\tsolopt.posf = SOLF_LLH;\r\n\tif (fp)\r\n\t{\r\n\t\toutheader_Q(fp, infile, n, &prcopt, &solopt, &obss);\r\n\t\tfclose(fp);\r\n\t}\r\n\t/*---------------------------*/\r\n\r\n\t/**************************************************/\r\n\r\n\t/* Step2: starting to use obs and nav rinex data @@@*/\r\n\r\n\tint i_obs, j_obs; // (i_obs,j_obs) are the (start,end) of rover obs.\r\n\t//for (i_obs = 0; i_obs<obss.n; i_obs++)\r\n\t//\tprintf(\"%d %d \\t\", i_obs, obss.data[i_obs].rcv);\r\n\tfor (i_obs = 0; i_obs < obss.n; i_obs++)\r\n\t\tif (obss.data[i_obs].rcv == 1)\r\n\t\t\tbreak;\r\n\r\n\tfor (j_obs = obss.n - 1; j_obs >= 0; j_obs--)\r\n\t\tif (obss.data[j_obs].rcv == 1)\r\n\t\t\tbreak;\r\n\r\n\tbool bFindSameData = false;\r\n\r\n\tint IndexStart = i_obs, IndexEnd = 0;\r\n\tint idx_epoch = 0;\r\n\t// note that the for is not every epoch of gps time\r\n\tfor (int idx = i_obs; idx < j_obs + 1; idx++)\r\n\t{\r\n\t\tif (idx == obss.n + 1)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\tint current_week1, current_week2;\r\n\t\tdouble current_tow1, current_tow2;\r\n\t\tcurrent_tow1 = time2gpst(obss.data[idx].time, &current_week1);\r\n\t\tcurrent_tow2 = time2gpst(obss.data[idx + 1].time, &current_week2);\r\n\r\n\t\tif ((current_week1 != current_week2) || fabs(current_tow1 - current_tow2) >0.49) // assuming 1Hz data rate. (if data rate higher than 2 Hz this does not valid)\r\n\t\t{\r\n\t\t\tIndexEnd = idx; // for current epoch\r\n\t\t\tbFindSameData = true;\r\n\t\t}\r\n\t\t//printf(\"IndexStart = %d, IndexEnd = %d\\n\", IndexStart, IndexEnd);\r\n\r\n\t\t/* Step3:find the measurements at the same epoch @@@*/\r\n\r\n\t\tif (bFindSameData)\r\n\t\t{\r\n\t\t\tidx_epoch++;\r\n\t\t\tint current_week;\r\n\t\t\tdouble current_tow;\r\n\t\t\tcurrent_tow = time2gpst(obss.data[IndexStart].time, &current_week);\r\n\t\t\tprintf(\"current_week = %4d - current_tow = %6.0f\\n\", current_week, current_tow);\r\n\r\n\t\t\t/* Step3.1:construct measurement matrix  @@@*/\r\n\t\t\tEigen::MatrixXd eAllMeasurement; // (n,3) PRN CNO Pseudorange\r\n\t\t\teAllMeasurement = ConstructMeasurementMatrix(IndexStart, IndexEnd, &obss);\r\n\r\n\t\t\t/* Step3.2: Select Ephemeris*/\r\n\t\t\tint target_idx[100], target_glo_idx[100]; // maximun number of satellite is 100. (GPS and GLONASS) \r\n\t\t\tint iNumValidSV = 0, iNumValidSV_glo = 0;\r\n\t\t\tSelectEphemeris(&navs, current_week, current_tow, target_idx, target_glo_idx, iNumValidSV, iNumValidSV_glo);\r\n\r\n\t\t\t/* Step3.3: caculating satellite positions @@@*/\r\n\t\t\t// caculating satellite positions (I suggest to make a structure about satellite position related information)\r\n\t\t\tEigen::MatrixXd eAllSVPositions; // (n,5) prn, sx, sy, sz, \r\n\t\t\teAllSVPositions = SatellitePosition(&navs, current_week, current_tow, target_idx, target_glo_idx, iNumValidSV, iNumValidSV_glo);\r\n\r\n\t\t\t/* Step3.4: WLS @@@\r\n\t\t\tinitial guess for shadow Matching is availalble,\r\n\t\t\t*/\r\n\t\t\tEigen::MatrixXd  eWLSSolutionECEF; // 6 unknowns with two clock bias variables\r\n\t\t\teWLSSolutionECEF = WeightLeastSquare(eAllSVPositions, eAllMeasurement);\r\n\r\n\t\t\t// example of coordinate transformation from ECEF to LLH (please see more in rtklib.h. hint:F12 can trace back the function)\r\n\t\t\tEigen::MatrixXd eWLSSolutionLLH(3, 1);\r\n\t\t\tdouble pos[3], r[3];\r\n\t\t\tfor (int idx = 0; idx < 3; idx++) {\r\n\t\t\t\tpos[idx] = eWLSSolutionECEF(idx);\r\n\t\t\t\t//printf(\"%d %f %f\\n\", idx, eWLSSolutionECEF(idx), pos[idx]);\r\n\t\t\t}\r\n\t\t\tecef2pos(pos, r);\r\n\t\t\tfor (int idx = 0; idx < 3; idx++) {\r\n\t\t\t\teWLSSolutionLLH(idx) = r[idx];\r\n\t\t\t\t//printf(\"%d %f %f\\n\", idx, eWLSSolutionLLH(idx), r[idx]);\r\n\t\t\t}\r\n\r\n\t\t\t// example to calculate azimuth and angle 2018/05/17 by LT Hsu\r\n\t\t\tEigen::MatrixXd eELAZAngles;\r\n\t\t\teELAZAngles = CalcELAZAngle(eWLSSolutionLLH, eAllSVPositions);\r\n\r\n\t\t\t// Add by Weisong WEN\r\n\t\t\tclock_t begin_time = clock();\r\n\t\t\tvector<shadowMatching::particle> particlesMain;\r\n\t\t\t//cout << \"eAllMeasurement.size-> \" << eAllMeasurement.rows() << \"  eELAZAngles.size->  \" << eELAZAngles.rows() << \"\\n\";\r\n\t\t\tMatrixXd llh_;\r\n\t\t\tMatrixXd ecef_;\r\n\t\t\tfor (int index = 0; index < 2; index++)\r\n\t\t\t{\r\n\t\t\t\tparticlesMain = SM_.generateParticles(eWLSSolutionECEF, 50, 2, eAllMeasurement, eELAZAngles);\r\n\t\t\t\tllh_ = SM_.weightSM_();\r\n\t\t\t\tecef_ = SM_.llh2ecef(llh_);\r\n\t\t\t\tSM_.particles.clear();\r\n\r\n\t\t\t}\r\n\t\t\tstd::cout << \"shadow matching  result: \\n\" << llh_ << \"\\n\\n\";\r\n\t\t\tstd::cout << \"one circle  used  time ---------------------------------------------------------------------------------------------> \" << float(clock() - begin_time) / CLOCKS_PER_SEC << \"\\n\\n\";\r\n\t\t\t//Output as RTKLIB format\r\n\t\t\tfopen_s(&fp, rtklibName2.c_str(), \"a\");\r\n\t\t\tif (fp)\r\n\t\t\t{\r\n\t\t\t\t//fprintf(fp, \"%4d, %9.3f,  %11.9f, %12.9f,  %9.4f, %d\\n\", current_week, current_tow, eWLSSolutionLLH(0)*R2D, eWLSSolutionLLH(1)*R2D, eWLSSolutionLLH(2),1);\r\n\t\t\t\tfprintf(fp, \"%4d, %9.3f,  %11.9f, %12.9f,  %9.4f, %d\\n\", current_week, current_tow, llh_(1), llh_(0), llh_(2), 1);\r\n\t\t\t\tfclose(fp);\r\n\t\t\t}\r\n\r\n\t\t\t// End of an epoch\r\n\t\t\tIndexStart = idx + 1; // don't touch this InderStart\r\n\t\t\t//printf(\"\\n\");\r\n\t\t\tbFindSameData = false;\r\n\r\n\t\t\t// coordinate convertion.\r\n\r\n\t\t}\r\n\r\n\r\n\r\n\t}\r\n\t/**************************************************/\r\n\r\n\t//shadowMatching SM_;\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}\r\n\r\n/* dummy application functions for shared library ----------------------------*/\r\nextern int showmsg(char *format, ...) {\r\n\tva_list arg;\r\n\tchar buff[1024];\r\n\tif (*format) {\r\n\t\tva_start(arg, format);\r\n\t\tvsprintf(buff, format, arg);\r\n\t\tva_end(arg);\r\n\t\tprintf(\"%s\\n\", buff);\r\n\t}\r\n\treturn 0;\r\n}\r\nextern void settspan(gtime_t ts, gtime_t te) {}\r\nextern void settime(gtime_t time) {}\r\n", "meta": {"hexsha": "ee636924aae70ee3085e423b7b39bbad7aec6e00", "size": 12325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rtklibros/app/shadowmatching/main.cpp", "max_stars_repo_name": "StanleyHusai/mapping", "max_stars_repo_head_hexsha": "60c984437c75e8eead95a8fb649e72066f8e5e8f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-27T05:31:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T02:16:46.000Z", "max_issues_repo_path": "rtklibros/app/shadowmatching/main.cpp", "max_issues_repo_name": "yxw027/GNSS-INS", "max_issues_repo_head_hexsha": "e5c5b7901b270a9c4d3a0ffd5555843d969f4018", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rtklibros/app/shadowmatching/main.cpp", "max_forks_repo_name": "yxw027/GNSS-INS", "max_forks_repo_head_hexsha": "e5c5b7901b270a9c4d3a0ffd5555843d969f4018", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T07:47:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T03:24:46.000Z", "avg_line_length": 32.4342105263, "max_line_length": 196, "alphanum_fraction": 0.5870993915, "num_tokens": 4198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.02887090475289319, "lm_q1q2_score": 0.0093609693214954}}
{"text": "/*\r\n\r\n   Copyright (c) 2006-2010, The Scripps Research Institute\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   Author: Dr. Oleg Trott <ot14@columbia.edu>,\r\n           The Olson Lab,\r\n           The Scripps Research Institute\r\n\r\n*/\r\n\r\n#include <boost/filesystem/convenience.hpp>  // filesystem::basename\r\n#include <boost/filesystem/exception.hpp>\r\n#include <boost/filesystem/fstream.hpp>\r\n#include <boost/program_options.hpp>\r\n#include <boost/thread/thread.hpp>  // hardware_concurrency // FIXME rm ?\r\n#include <cmath>                    // for ceila\r\n#include <exception>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>  // ligand paths\r\n\r\n#include \"lib/cache.h\"\r\n#include \"lib/coords.h\"  // add_to_output_container\r\n#include \"lib/current_weights.h\"\r\n#include \"lib/everything.h\"\r\n#include \"lib/file.h\"\r\n#include \"lib/naive_non_cache.h\"\r\n#include \"lib/non_cache.h\"\r\n#include \"lib/parallel_mc.h\"\r\n#include \"lib/parse_error.h\"\r\n#include \"lib/parse_pdbqt.h\"\r\n#include \"lib/quasi_newton.h\"\r\n#include \"lib/tee.h\"\r\n#include \"lib/weighted_terms.h\"\r\n\r\nusing boost::filesystem::path;\r\n\r\npath make_path(const std::string& str) { return boost::filesystem::path(str); }\r\n\r\nvoid doing(int verbosity, const std::string& str, tee& log) {\r\n  if (verbosity > 1) {\r\n    log << str << std::string(\" ... \");\r\n    log.flush();\r\n  }\r\n}\r\n\r\nvoid done(int verbosity, tee& log) {\r\n  if (verbosity > 1) {\r\n    log << \"done.\";\r\n    log.endl();\r\n  }\r\n}\r\nstd::string default_output(const std::string& input_name) {\r\n  std::string tmp = input_name;\r\n  if (tmp.size() >= 6 && tmp.substr(tmp.size() - 6, 6) == \".pdbqt\")\r\n    tmp.resize(tmp.size() - 6);  // FIXME?\r\n  return tmp + \"_out.pdbqt\";\r\n}\r\n\r\nvoid write_all_output(model& m, const output_container& out, sz how_many,\r\n                      const std::string& output_name,\r\n                      const std::vector<std::string>& remarks) {\r\n  if (out.size() < how_many) how_many = out.size();\r\n  VINA_CHECK(how_many <= remarks.size());\r\n  ofile f(make_path(output_name));\r\n  VINA_FOR(i, how_many) {\r\n    m.set(out[i].c);\r\n    m.write_model(f, i + 1, remarks[i]);  // so that model numbers start with 1\r\n  }\r\n}\r\n\r\nvoid do_randomization(model& m, const std::string& out_name, const vec& corner1,\r\n                      const vec& corner2, int seed, int verbosity, tee& log) {\r\n  conf init_conf = m.get_initial_conf();\r\n  rng generator(static_cast<rng::result_type>(seed));\r\n  if (verbosity > 1) {\r\n    log << \"Using random seed: \" << seed;\r\n    log.endl();\r\n  }\r\n  const sz attempts = 10000;\r\n  conf best_conf = init_conf;\r\n  fl best_clash_penalty = 0;\r\n  VINA_FOR(i, attempts) {\r\n    conf c = init_conf;\r\n    c.randomize(corner1, corner2, generator);\r\n    m.set(c);\r\n    fl penalty = m.clash_penalty();\r\n    if (i == 0 || penalty < best_clash_penalty) {\r\n      best_conf = c;\r\n      best_clash_penalty = penalty;\r\n    }\r\n  }\r\n  m.set(best_conf);\r\n  if (verbosity > 1) {\r\n    log << \"Clash penalty: \" << best_clash_penalty;  // FIXME rm?\r\n    log.endl();\r\n  }\r\n  m.write_structure(make_path(out_name));\r\n}\r\n\r\nvoid refine_structure(model& m, const precalculate& prec, non_cache& nc,\r\n                      output_type& out, const vec& cap, sz max_steps = 1000) {\r\n  change g(m.get_size());\r\n  quasi_newton quasi_newton_par;\r\n  quasi_newton_par.max_steps = max_steps;\r\n  const fl slope_orig = nc.slope;\r\n  VINA_FOR(p, 5) {\r\n    nc.slope = 100 * std::pow(10.0, 2.0 * p);\r\n    quasi_newton_par(m, prec, nc, out, g, cap);\r\n    m.set(out.c);  // just to be sure\r\n    if (nc.within(m)) break;\r\n  }\r\n  out.coords = m.get_heavy_atom_movable_coords();\r\n  if (!nc.within(m)) out.e = max_fl;\r\n  nc.slope = slope_orig;\r\n}\r\n\r\nstd::string vina_remark(fl e, fl lb, fl ub) {\r\n  std::ostringstream remark;\r\n  remark.setf(std::ios::fixed, std::ios::floatfield);\r\n  remark.setf(std::ios::showpoint);\r\n  remark << \"REMARK VINA RESULT: \" << std::setw(9) << std::setprecision(1) << e\r\n         << \"  \" << std::setw(9) << std::setprecision(3) << lb << \"  \"\r\n         << std::setw(9) << std::setprecision(3) << ub << '\\n';\r\n  return remark.str();\r\n}\r\n\r\noutput_container remove_redundant(const output_container& in, fl min_rmsd) {\r\n  output_container tmp;\r\n  VINA_FOR_IN(i, in)\r\n  add_to_output_container(tmp, in[i], min_rmsd, in.size());\r\n  return tmp;\r\n}\r\n\r\nvoid do_search(model& m, const boost::optional<model>& ref,\r\n               const scoring_function& sf, const precalculate& prec,\r\n               const igrid& ig, const precalculate& prec_widened,\r\n               const igrid& ig_widened, non_cache& nc,  // nc.slope is changed\r\n               const std::string& out_name, const vec& corner1,\r\n               const vec& corner2, const parallel_mc& par, fl energy_range,\r\n               sz num_modes, int seed, int verbosity, bool score_only,\r\n               bool local_only, tee& log, const terms& t, const flv& weights) {\r\n  conf_size s = m.get_size();\r\n  conf c = m.get_initial_conf();\r\n  fl e = max_fl;\r\n  const vec authentic_v(1000, 1000, 1000);\r\n  if (score_only) {\r\n    fl intramolecular_energy = m.eval_intramolecular(prec, authentic_v, c);\r\n    naive_non_cache nnc(&prec);  // for out of grid issues\r\n    e = m.eval_adjusted(sf, prec, nnc, authentic_v, c, intramolecular_energy);\r\n    log << \"Affinity: \" << std::fixed << std::setprecision(5) << e\r\n        << \" (kcal/mol)\";\r\n    log.endl();\r\n    flv term_values = t.evale_robust(m);\r\n    VINA_CHECK(term_values.size() == 5);\r\n    log << \"Intermolecular contributions to the terms, before weighting:\\n\";\r\n    log << std::setprecision(5);\r\n    log << \"    gauss 1     : \" << term_values[0] << '\\n';\r\n    log << \"    gauss 2     : \" << term_values[1] << '\\n';\r\n    log << \"    repulsion   : \" << term_values[2] << '\\n';\r\n    log << \"    hydrophobic : \" << term_values[3] << '\\n';\r\n    log << \"    Hydrogen    : \" << term_values[4] << '\\n';\r\n    VINA_CHECK(weights.size() == term_values.size() + 1);\r\n    fl e2 = 0;\r\n    VINA_FOR_IN(i, term_values)\r\n    e2 += term_values[i] * weights[i];\r\n    e2 = sf.conf_independent(m, e2);\r\n    if (e < 100 && std::abs(e2 - e) > 0.05) {\r\n      log << \"WARNING: the individual terms are inconsisent with the\\n\";\r\n      log << \"WARNING: affinity. Consider reporting this as a bug:\\n\";\r\n      log << \"WARNING: http://vina.scripps.edu/manual.html#bugs\\n\";\r\n    }\r\n  } else if (local_only) {\r\n    output_type out(c, e);\r\n    doing(verbosity, \"Performing local search\", log);\r\n    refine_structure(m, prec, nc, out, authentic_v, par.mc.ssd_par.evals);\r\n    done(verbosity, log);\r\n    fl intramolecular_energy = m.eval_intramolecular(prec, authentic_v, out.c);\r\n    e = m.eval_adjusted(sf, prec, nc, authentic_v, out.c,\r\n                        intramolecular_energy);\r\n\r\n    log << \"Affinity: \" << std::fixed << std::setprecision(5) << e\r\n        << \" (kcal/mol)\";\r\n    log.endl();\r\n    if (!nc.within(m))\r\n      log << \"WARNING: not all movable atoms are within the search space\\n\";\r\n\r\n    doing(verbosity, \"Writing output\", log);\r\n    output_container out_cont;\r\n    out_cont.push_back(new output_type(out));\r\n    std::vector<std::string> remarks(1, vina_remark(e, 0, 0));\r\n    write_all_output(m, out_cont, 1, out_name, remarks);  // how_many == 1\r\n    done(verbosity, log);\r\n  } else {\r\n    rng generator(static_cast<rng::result_type>(seed));\r\n    log << \"Using random seed: \" << seed;\r\n    log.endl();\r\n    output_container out_cont;\r\n    doing(verbosity, \"Performing search\", log);\r\n    par(m, out_cont, prec, ig, prec_widened, ig_widened, corner1, corner2,\r\n        generator);\r\n    done(verbosity, log);\r\n\r\n    doing(verbosity, \"Refining results\", log);\r\n    VINA_FOR_IN(i, out_cont)\r\n    refine_structure(m, prec, nc, out_cont[i], authentic_v,\r\n                     par.mc.ssd_par.evals);\r\n\r\n    if (!out_cont.empty()) {\r\n      out_cont.sort();\r\n      const fl best_mode_intramolecular_energy =\r\n          m.eval_intramolecular(prec, authentic_v, out_cont[0].c);\r\n      VINA_FOR_IN(i, out_cont)\r\n      if (not_max(out_cont[i].e))\r\n        out_cont[i].e =\r\n            m.eval_adjusted(sf, prec, nc, authentic_v, out_cont[i].c,\r\n                            best_mode_intramolecular_energy);\r\n      // the order must not change because of non-decreasing g (see paper), but\r\n      // we'll re-sort in case g is non strictly increasing\r\n      out_cont.sort();\r\n    }\r\n\r\n    const fl out_min_rmsd = 1;\r\n    out_cont = remove_redundant(out_cont, out_min_rmsd);\r\n\r\n    done(verbosity, log);\r\n\r\n    log.setf(std::ios::fixed, std::ios::floatfield);\r\n    log.setf(std::ios::showpoint);\r\n    log << '\\n';\r\n    log << \"mode |   affinity | dist from best mode\\n\";\r\n    log << \"     | (kcal/mol) | rmsd l.b.| rmsd u.b.\\n\";\r\n    log << \"-----+------------+----------+----------\\n\";\r\n\r\n    model best_mode_model = m;\r\n    if (!out_cont.empty()) best_mode_model.set(out_cont.front().c);\r\n\r\n    sz how_many = 0;\r\n    std::vector<std::string> remarks;\r\n    VINA_FOR_IN(i, out_cont) {\r\n      if (how_many >= num_modes || !not_max(out_cont[i].e) ||\r\n          out_cont[i].e > out_cont[0].e + energy_range)\r\n        break;  // check energy_range sanity FIXME\r\n      ++how_many;\r\n      log << std::setw(4) << i + 1 << \"    \" << std::setw(9)\r\n          << std::setprecision(1)\r\n          << out_cont[i].e;  // intermolecular_energies[i];\r\n      m.set(out_cont[i].c);\r\n      const model& r = ref ? ref.get() : best_mode_model;\r\n      const fl lb = m.rmsd_lower_bound(r);\r\n      const fl ub = m.rmsd_upper_bound(r);\r\n      log << \"  \" << std::setw(9) << std::setprecision(3) << lb << \"  \"\r\n          << std::setw(9) << std::setprecision(3)\r\n          << ub;  // FIXME need user-readable error messages in case of failures\r\n\r\n      remarks.push_back(vina_remark(out_cont[i].e, lb, ub));\r\n      log.endl();\r\n    }\r\n    doing(verbosity, \"Writing output\", log);\r\n    write_all_output(m, out_cont, how_many, out_name, remarks);\r\n    done(verbosity, log);\r\n\r\n    if (how_many < 1) {\r\n      log << \"WARNING: Could not find any conformations completely within the \"\r\n             \"search space.\\n\"\r\n          << \"WARNING: Check that it is large enough for all movable atoms, \"\r\n             \"including those in the flexible side chains.\";\r\n      log.endl();\r\n    }\r\n  }\r\n}\r\n\r\nvoid main_procedure(\r\n    model& m, const boost::optional<model>& ref,  // m is non-const (FIXME?)\r\n    const std::string& out_name, bool score_only, bool local_only,\r\n    bool randomize_only, bool no_cache, const grid_dims& gd, int exhaustiveness,\r\n    const flv& weights, int cpu, int seed, int verbosity, sz num_modes,\r\n    fl energy_range, tee& log) {\r\n  doing(verbosity, \"Setting up the scoring function\", log);\r\n\r\n  everything t;\r\n  VINA_CHECK(weights.size() == 6);\r\n\r\n  weighted_terms wt(&t, weights);\r\n  precalculate prec(wt);\r\n  const fl left = 0.25;\r\n  const fl right = 0.25;\r\n  precalculate prec_widened(prec);\r\n  prec_widened.widen(left, right);\r\n\r\n  done(verbosity, log);\r\n\r\n  vec corner1(gd[0].begin, gd[1].begin, gd[2].begin);\r\n  vec corner2(gd[0].end, gd[1].end, gd[2].end);\r\n\r\n  parallel_mc par;\r\n  sz heuristic =\r\n      m.num_movable_atoms() + 10 * m.get_size().num_degrees_of_freedom();\r\n  par.mc.num_steps =\r\n      unsigned(70 * 3 * (50 + heuristic) / 2);  // 2 * 70 -> 8 * 20 // FIXME\r\n  par.mc.ssd_par.evals = unsigned((25 + m.num_movable_atoms()) / 3);\r\n  par.mc.min_rmsd = 1.0;\r\n  par.mc.num_saved_mins = 20;\r\n  par.mc.hunt_cap = vec(10, 10, 10);\r\n  par.num_tasks = exhaustiveness;\r\n  par.num_threads = cpu;\r\n  par.display_progress = (verbosity > 1);\r\n\r\n  const fl slope = 1e6;  // FIXME: too large? used to be 100\r\n  if (randomize_only) {\r\n    do_randomization(m, out_name, corner1, corner2, seed, verbosity, log);\r\n  } else {\r\n    non_cache nc(m, gd, &prec,\r\n                 slope);  // if gd has 0 n's, this will not constrain anything\r\n    non_cache nc_widened(\r\n        m, gd, &prec_widened,\r\n        slope);  // if gd has 0 n's, this will not constrain anything\r\n    if (no_cache) {\r\n      do_search(m, ref, wt, prec, nc, prec_widened, nc_widened, nc, out_name,\r\n                corner1, corner2, par, energy_range, num_modes, seed, verbosity,\r\n                score_only, local_only, log, t, weights);\r\n    } else {\r\n      bool cache_needed = !(score_only || randomize_only || local_only);\r\n      if (cache_needed) doing(verbosity, \"Analyzing the binding site\", log);\r\n      cache c(\"scoring_function_version001\", gd, slope, atom_type::XS);\r\n      if (cache_needed)\r\n        c.populate(m, prec, m.get_movable_atom_types(prec.atom_typing_used()));\r\n      if (cache_needed) done(verbosity, log);\r\n      do_search(m, ref, wt, prec, c, prec, c, nc, out_name, corner1, corner2,\r\n                par, energy_range, num_modes, seed, verbosity, score_only,\r\n                local_only, log, t, weights);\r\n    }\r\n  }\r\n}\r\n\r\nstruct usage_error : public std::runtime_error {\r\n  usage_error(const std::string& message) : std::runtime_error(message) {}\r\n};\r\n\r\nstruct options_occurrence {\r\n  bool some;\r\n  bool all;\r\n  options_occurrence() : some(false), all(true) {}  // convenience\r\n  options_occurrence& operator+=(const options_occurrence& x) {\r\n    some = some || x.some;\r\n    all = all && x.all;\r\n    return *this;\r\n  }\r\n};\r\n\r\noptions_occurrence get_occurrence(\r\n    boost::program_options::variables_map& vm,\r\n    boost::program_options::options_description& d) {\r\n  options_occurrence tmp;\r\n  VINA_FOR_IN(i, d.options())\r\n  if (vm.count((*d.options()[i]).long_name()))\r\n    tmp.some = true;\r\n  else\r\n    tmp.all = false;\r\n  return tmp;\r\n}\r\n\r\nvoid check_occurrence(boost::program_options::variables_map& vm,\r\n                      boost::program_options::options_description& d) {\r\n  VINA_FOR_IN(i, d.options()) {\r\n    const std::string& str = (*d.options()[i]).long_name();\r\n    if (!vm.count(str))\r\n      std::cerr << \"Required parameter --\" << str << \" is missing!\\n\";\r\n  }\r\n}\r\n\r\nmodel parse_bundle(const std::string& rigid_name,\r\n                   const boost::optional<std::string>& flex_name_opt,\r\n                   const std::vector<std::string>& ligand_names) {\r\n  model tmp = (flex_name_opt)\r\n                  ? parse_receptor_pdbqt(make_path(rigid_name),\r\n                                         make_path(flex_name_opt.get()))\r\n                  : parse_receptor_pdbqt(make_path(rigid_name));\r\n  VINA_FOR_IN(i, ligand_names)\r\n  tmp.append(parse_ligand_pdbqt(make_path(ligand_names[i])));\r\n  return tmp;\r\n}\r\n\r\nmodel parse_bundle(const std::vector<std::string>& ligand_names) {\r\n  VINA_CHECK(!ligand_names.empty());  // FIXME check elsewhere\r\n  model tmp = parse_ligand_pdbqt(make_path(ligand_names[0]));\r\n  VINA_RANGE(i, 1, ligand_names.size())\r\n  tmp.append(parse_ligand_pdbqt(make_path(ligand_names[i])));\r\n  return tmp;\r\n}\r\n\r\nmodel parse_bundle(const boost::optional<std::string>& rigid_name_opt,\r\n                   const boost::optional<std::string>& flex_name_opt,\r\n                   const std::vector<std::string>& ligand_names) {\r\n  if (rigid_name_opt)\r\n    return parse_bundle(rigid_name_opt.get(), flex_name_opt, ligand_names);\r\n  else\r\n    return parse_bundle(ligand_names);\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n  using namespace boost::program_options;\r\n  const std::string version_string = \"AutoDock Vina 1.1.2 (May 11, 2011)\";\r\n  const std::string error_message = \"\\nThank you!\\n\";\r\n  const std::string cite_message = \"AutoDock Vina\";\r\n\r\n  try {\r\n    std::string rigid_name, ligand_name, flex_name, config_name, out_name,\r\n        log_name;\r\n    fl center_x, center_y, center_z, size_x, size_y, size_z;\r\n    int cpu = 0, seed, exhaustiveness, verbosity = 2, num_modes = 9;\r\n    fl energy_range = 2.0;\r\n\r\n    // -0.035579, -0.005156, 0.840245, -0.035069, -0.587439, 0.05846\r\n    fl weight_gauss1 = -0.035579;\r\n    fl weight_gauss2 = -0.005156;\r\n    fl weight_repulsion = 0.840245;\r\n    fl weight_hydrophobic = -0.035069;\r\n    fl weight_hydrogen = -0.587439;\r\n    fl weight_rot = 0.05846;\r\n    bool score_only = false, local_only = false, randomize_only = false,\r\n         help = false, help_advanced = false, version = false;  // FIXME\r\n\r\n    positional_options_description positional;  // remains empty\r\n\r\n    options_description inputs(\"Input\");\r\n    inputs.add_options()(\"receptor\", value<std::string>(&rigid_name),\r\n                         \"rigid part of the receptor (PDBQT)\")(\r\n        \"flex\", value<std::string>(&flex_name),\r\n        \"flexible side chains, if any (PDBQT)\")(\"ligand\",\r\n                                                value<std::string>(\r\n                                                    &ligand_name),\r\n                                                \"ligand (PDBQT)\");\r\n    // options_description search_area(\"Search area (required, except with\r\n    // --score_only)\");\r\n    options_description search_area(\"Search space (required)\");\r\n    search_area.add_options()\r\n\t\t\t(\"center_x\", value<fl>(&center_x), \"X coordinate of the center\")\r\n\t\t\t(\"center_y\", value<fl>(&center_y), \"Y coordinate of the center\")\r\n\t\t\t(\"center_z\", value<fl>(&center_z), \"Z coordinate of the center\")\r\n\t\t\t(\"size_x\", value<fl>(&size_x), \"size in the X dimension (Angstroms)\")\r\n\t\t\t(\"size_y\", value<fl>(&size_y), \"size in the Y dimension (Angstroms)\")\r\n\t\t\t(\"size_z\", value<fl>(&size_z), \"size in the Z dimension (Angstroms)\")\r\n\t\t;\r\n    // options_description outputs(\"Output prefixes (optional - by default,\r\n    // input names are stripped of .pdbqt\\nare used as prefixes. _001.pdbqt,\r\n    // _002.pdbqt, etc. are appended to the prefixes to produce the output\r\n    // names\");\r\n    options_description outputs(\"Output (optional)\");\r\n    outputs.add_options()(\"out\", value<std::string>(&out_name),\r\n                          \"output models (PDBQT), the default is chosen based \"\r\n                          \"on the ligand file name\")(\r\n        \"log\", value<std::string>(&log_name), \"optionally, write log file\");\r\n    options_description advanced(\"Advanced options (see the manual)\");\r\n    advanced.add_options()\r\n\t\t\t(\"score_only\",     bool_switch(&score_only),     \"score only - search space can be omitted\")\r\n\t\t\t(\"local_only\",     bool_switch(&local_only),     \"do local search only\")\r\n\t\t\t(\"randomize_only\", bool_switch(&randomize_only), \"randomize input, attempting to avoid clashes\")\r\n\t\t\t(\"weight_gauss1\", value<fl>(&weight_gauss1)->default_value(weight_gauss1),                \"gauss_1 weight\")\r\n\t\t\t(\"weight_gauss2\", value<fl>(&weight_gauss2)->default_value(weight_gauss2),                \"gauss_2 weight\")\r\n\t\t\t(\"weight_repulsion\", value<fl>(&weight_repulsion)->default_value(weight_repulsion),       \"repulsion weight\")\r\n\t\t\t(\"weight_hydrophobic\", value<fl>(&weight_hydrophobic)->default_value(weight_hydrophobic), \"hydrophobic weight\")\r\n\t\t\t(\"weight_hydrogen\", value<fl>(&weight_hydrogen)->default_value(weight_hydrogen),          \"Hydrogen bond weight\")\r\n\t\t\t(\"weight_rot\", value<fl>(&weight_rot)->default_value(weight_rot),                         \"N_rot weight\")\r\n\t\t;\r\n    options_description misc(\"Misc (optional)\");\r\n    misc.add_options()\r\n\t\t\t(\"cpu\", value<int>(&cpu), \"the number of CPUs to use (the default is to try to detect the number of CPUs or, failing that, use 1)\")\r\n\t\t\t(\"seed\", value<int>(&seed), \"explicit random seed\")\r\n\t\t\t(\"exhaustiveness\", value<int>(&exhaustiveness)->default_value(8), \"exhaustiveness of the global search (roughly proportional to time): 1+\")\r\n\t\t\t(\"num_modes\", value<int>(&num_modes)->default_value(9), \"maximum number of binding modes to generate\")\r\n\t\t\t(\"energy_range\", value<fl>(&energy_range)->default_value(3.0), \"maximum energy difference between the best binding mode and the worst one displayed (kcal/mol)\")\r\n\t\t;\r\n    options_description config(\"Configuration file (optional)\");\r\n    config.add_options()(\"config\", value<std::string>(&config_name),\r\n                         \"the above options can be put here\");\r\n    options_description info(\"Information (optional)\");\r\n    info.add_options()(\"help\", bool_switch(&help), \"display usage summary\")(\r\n        \"help_advanced\", bool_switch(&help_advanced),\r\n        \"display usage summary with advanced options\")(\"version\",\r\n                                                       bool_switch(&version),\r\n                                                       \"display program \"\r\n                                                       \"version\");\r\n    options_description desc, desc_config, desc_simple;\r\n    desc.add(inputs)\r\n        .add(search_area)\r\n        .add(outputs)\r\n        .add(advanced)\r\n        .add(misc)\r\n        .add(config)\r\n        .add(info);\r\n    desc_config.add(inputs)\r\n        .add(search_area)\r\n        .add(outputs)\r\n        .add(advanced)\r\n        .add(misc);\r\n    desc_simple.add(inputs)\r\n        .add(search_area)\r\n        .add(outputs)\r\n        .add(misc)\r\n        .add(config)\r\n        .add(info);\r\n\r\n    variables_map vm;\r\n    try {\r\n      // store(parse_command_line(argc, argv, desc,\r\n      // command_line_style::default_style ^ command_line_style::allow_guessing),\r\n      // vm);\r\n      store(command_line_parser(argc, argv)\r\n                .options(desc)\r\n                .style(command_line_style::default_style ^\r\n                       command_line_style::allow_guessing)\r\n                .positional(positional)\r\n                .run(),\r\n            vm);\r\n      notify(vm);\r\n    } catch (boost::program_options::error& e) {\r\n      std::cerr << \"Command line parse error: \" << e.what() << '\\n'\r\n                << \"\\nCorrect usage:\\n\"\r\n                << desc_simple << '\\n';\r\n      return 1;\r\n    }\r\n    if (vm.count(\"config\")) {\r\n      try {\r\n        path name = make_path(config_name);\r\n        ifile config_stream(name);\r\n        store(parse_config_file(config_stream, desc_config), vm);\r\n        notify(vm);\r\n      } catch (boost::program_options::error& e) {\r\n        std::cerr << \"Configuration file parse error: \" << e.what() << '\\n'\r\n                  << \"\\nCorrect usage:\\n\"\r\n                  << desc_simple << '\\n';\r\n        return 1;\r\n      }\r\n    }\r\n    if (help) {\r\n      std::cout << desc_simple << '\\n';\r\n      return 0;\r\n    }\r\n    if (help_advanced) {\r\n      std::cout << desc << '\\n';\r\n      return 0;\r\n    }\r\n    if (version) {\r\n      std::cout << version_string << '\\n';\r\n      return 0;\r\n    }\r\n\r\n    bool search_box_needed = !score_only;  // randomize_only and local_only\r\n                                           // still need the search space\r\n    bool output_produced = !score_only;\r\n    bool receptor_needed = !randomize_only;\r\n\r\n    if (receptor_needed) {\r\n      if (vm.count(\"receptor\") <= 0) {\r\n        std::cerr << \"Missing receptor.\\n\"\r\n                  << \"\\nCorrect usage:\\n\"\r\n                  << desc_simple << '\\n';\r\n        return 1;\r\n      }\r\n    }\r\n    if (vm.count(\"ligand\") <= 0) {\r\n      std::cerr << \"Missing ligand.\\n\"\r\n                << \"\\nCorrect usage:\\n\"\r\n                << desc_simple << '\\n';\r\n      return 1;\r\n    }\r\n    if (cpu < 1) cpu = 1;\r\n    if (vm.count(\"seed\") == 0) seed = auto_seed();\r\n    if (exhaustiveness < 1)\r\n      throw usage_error(\"exhaustiveness must be 1 or greater\");\r\n    if (num_modes < 1) throw usage_error(\"num_modes must be 1 or greater\");\r\n    sz max_modes_sz = static_cast<sz>(num_modes);\r\n\r\n    boost::optional<std::string> rigid_name_opt;\r\n    if (vm.count(\"receptor\")) rigid_name_opt = rigid_name;\r\n\r\n    boost::optional<std::string> flex_name_opt;\r\n    if (vm.count(\"flex\")) flex_name_opt = flex_name;\r\n\r\n    if (vm.count(\"flex\") && !vm.count(\"receptor\"))\r\n      throw usage_error(\r\n          \"Flexible side chains are not allowed without the rest of the \"\r\n          \"receptor\");  // that's the only way parsing works, actually\r\n\r\n    tee log;\r\n    if (vm.count(\"log\") > 0) log.init(log_name);\r\n\r\n    if (search_box_needed) {\r\n      options_occurrence oo = get_occurrence(vm, search_area);\r\n      if (!oo.all) {\r\n        check_occurrence(vm, search_area);\r\n        std::cerr << \"\\nCorrect usage:\\n\" << desc_simple << std::endl;\r\n        return 1;\r\n      }\r\n      if (size_x <= 0 || size_y <= 0 || size_z <= 0)\r\n        throw usage_error(\"Search space dimensions should be positive\");\r\n    }\r\n\r\n    log << cite_message << '\\n';\r\n\r\n    if (search_box_needed && size_x * size_y * size_z > 27e3) {\r\n      log << \"WARNING: The search space volume > 27000 Angstrom^3 (See FAQ)\\n\";\r\n    }\r\n\r\n    if (output_produced) {  // FIXME\r\n      if (!vm.count(\"out\")) {\r\n        out_name = default_output(ligand_name);\r\n        log << \"Output will be \" << out_name << '\\n';\r\n      }\r\n    }\r\n\r\n    grid_dims gd;  // n's = 0 via default c'tor\r\n\r\n    flv weights;\r\n    weights.push_back(weight_gauss1);\r\n    weights.push_back(weight_gauss2);\r\n    weights.push_back(weight_repulsion);\r\n    weights.push_back(weight_hydrophobic);\r\n    weights.push_back(weight_hydrogen);\r\n    weights.push_back(5 * weight_rot / 0.1 -\r\n                      1);  // linearly maps onto a different range, internally.\r\n                           // see everything.cpp\r\n\r\n    if (search_box_needed) {\r\n      const fl granularity = 0.375;\r\n      vec span(size_x, size_y, size_z);\r\n      vec center(center_x, center_y, center_z);\r\n      VINA_FOR_IN(i, gd) {\r\n        gd[i].n = sz(std::ceil(span[i] / granularity));\r\n        fl real_span = granularity * gd[i].n;\r\n        gd[i].begin = center[i] - real_span / 2;\r\n        gd[i].end = gd[i].begin + real_span;\r\n      }\r\n    }\r\n    if (vm.count(\"cpu\") == 0) {\r\n      unsigned num_cpus = boost::thread::hardware_concurrency();\r\n      if (verbosity > 1) {\r\n        if (num_cpus > 0)\r\n          log << \"Detected \" << num_cpus << \" CPU\"\r\n              << ((num_cpus > 1) ? \"s\" : \"\") << '\\n';\r\n        else\r\n          log << \"Could not detect the number of CPUs, using 1\\n\";\r\n      }\r\n      if (num_cpus > 0)\r\n        cpu = num_cpus;\r\n      else\r\n        cpu = 1;\r\n    }\r\n    if (cpu < 1) cpu = 1;\r\n    if (verbosity > 1 && exhaustiveness < cpu)\r\n      log << \"WARNING: at low exhaustiveness, it may be impossible to utilize \"\r\n             \"all CPUs\\n\";\r\n\r\n    doing(verbosity, \"Reading input\", log);\r\n\r\n    model m = parse_bundle(rigid_name_opt, flex_name_opt,\r\n                           std::vector<std::string>(1, ligand_name));\r\n\r\n    boost::optional<model> ref;\r\n    done(verbosity, log);\r\n\r\n    main_procedure(m, ref, out_name, score_only, local_only, randomize_only,\r\n                   false,  // no_cache == false\r\n                   gd, exhaustiveness, weights, cpu, seed, verbosity,\r\n                   max_modes_sz, energy_range, log);\r\n  } catch (file_error& e) {\r\n    std::cerr << \"\\n\\nError: could not open \\\"\" << e.name.filename()\r\n              << \"\\\" for \" << (e.in ? \"reading\" : \"writing\") << \".\\n\";\r\n    return 1;\r\n  } catch (boost::filesystem::filesystem_error& e) {\r\n    std::cerr << \"\\n\\nFile system error: \" << e.what() << '\\n';\r\n    return 1;\r\n  } catch (usage_error& e) {\r\n    std::cerr << \"\\n\\nUsage error: \" << e.what() << \".\\n\";\r\n    return 1;\r\n  } catch (parse_error& e) {\r\n    std::cerr << \"\\n\\nParse error on line \" << e.line << \" in file \\\"\"\r\n              << e.file.filename() << \"\\\": \" << e.reason << '\\n';\r\n    return 1;\r\n  } catch (std::bad_alloc&) {\r\n    std::cerr << \"\\n\\nError: insufficient memory!\\n\";\r\n    return 1;\r\n  }\r\n\r\n  // Errors that shouldn't happen:\r\n\r\n  catch (std::exception& e) {\r\n    std::cerr << \"\\n\\nAn error occurred: \" << e.what() << \". \" << error_message;\r\n    return 1;\r\n  } catch (internal_error& e) {\r\n    std::cerr << \"\\n\\nAn internal error occurred in \" << e.file << \"(\" << e.line\r\n              << \"). \" << error_message;\r\n    return 1;\r\n  } catch (...) {\r\n    std::cerr << \"\\n\\nAn unknown error occurred. \" << error_message;\r\n    return 1;\r\n  }\r\n}\r\n", "meta": {"hexsha": "f5c7214621debaec0c99e9d63041a8c40d1831fa", "size": 27968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "wangcaihua/vina", "max_stars_repo_head_hexsha": "43df9af51e64c521b6495f969585daf68ff50cc3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "wangcaihua/vina", "max_issues_repo_head_hexsha": "43df9af51e64c521b6495f969585daf68ff50cc3", "max_issues_repo_licenses": ["Apache-2.0"], "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": "wangcaihua/vina", "max_forks_repo_head_hexsha": "43df9af51e64c521b6495f969585daf68ff50cc3", "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.2808988764, "max_line_length": 164, "alphanum_fraction": 0.5922840389, "num_tokens": 7330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825679370240214, "lm_q2_score": 0.03358950274784212, "lm_q1q2_score": 0.009346507336672576}}
{"text": "/*******************************************************************************\n *\n * Construction and management of weak topological orderings (WTOs).\n *\n * The construction of weak topological orderings is based on F. Bourdoncle's\n * paper: \"Efficient chaotic iteration strategies with widenings\", Formal\n * Methods in Programming and Their Applications, 1993, pages 128-141.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n * Contributors: 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 <set>\n#include <vector>\n#include <forward_list>\n#include <unordered_map>\n\n#include <boost/iterator/indirect_iterator.hpp>\n\n#include \"crab/cfg_bgl.hpp\"\n#include \"crab/debug.hpp\"\n#include \"crab/interval.hpp\"\n#include \"crab/stats.hpp\"\n#include \"crab/types.hpp\"\n\nnamespace crab {\n\n\nusing vertex_descriptor_t = typename boost::graph_traits<cfg_t>::vertex_descriptor;\n\n\nusing out_edge_iterator_t = typename boost::graph_traits<cfg_t>::out_edge_iterator;\n\n\nusing edge_descriptor_t = typename boost::graph_traits<cfg_t>::edge_descriptor;\n\n\nclass wto_t;\nclass wto_vertex_t;\nclass wto_cycle_t;\nclass wto_component_visitor_t;\n\n\nclass wto_nesting_t final {\n\n    friend class wto_t;\n    friend class wto_vertex_t;\n    friend class wto_cycle_t;\n\n  private:\n    using node_list_t = std::vector<vertex_descriptor_t>;\n    using node_list_ptr = std::shared_ptr<node_list_t>;\n\n    node_list_ptr _nodes;\n\n  public:\n    using iterator = typename node_list_t::iterator;\n    using const_iterator = typename node_list_t::const_iterator;\n\n  private:\n    explicit wto_nesting_t(const node_list_ptr& l) : _nodes(std::make_shared<node_list_t>(*l)) {}\n\n    int compare(wto_nesting_t& other) const {\n        auto this_it = this->begin();\n        auto other_it = other.begin();\n        while (this_it != this->end()) {\n            if (other_it == other.end()) {\n                return 1;\n            } else if (*this_it == *other_it) {\n                ++this_it;\n                ++other_it;\n            } else {\n                return 2; // Nestings are not comparable\n            }\n        }\n        if (other_it == other.end()) {\n            return 0;\n        } else {\n            return -1;\n        }\n    }\n\n  public:\n    wto_nesting_t() : _nodes(std::make_shared<node_list_t>()) {}\n\n    void operator+=(const vertex_descriptor_t& n) {\n        this->_nodes = std::make_shared<node_list_t>(*(this->_nodes));\n        this->_nodes->push_back(n);\n    }\n\n    wto_nesting_t operator+(const vertex_descriptor_t& n) {\n        wto_nesting_t res(this->_nodes);\n        res._nodes->push_back(n);\n        return res;\n    }\n\n    iterator begin() { return _nodes->begin(); }\n\n    iterator end() { return _nodes->end(); }\n\n    const_iterator begin() const { return _nodes->begin(); }\n\n    const_iterator end() const { return _nodes->end(); }\n\n    wto_nesting_t operator^(wto_nesting_t other) const {\n        wto_nesting_t res;\n        for (const_iterator this_it = this->begin(), other_it = other.begin();\n             this_it != this->end() && other_it != other.end(); ++this_it, ++other_it) {\n            if (*this_it == *other_it) {\n                res._nodes->push_back(*this_it);\n            } else {\n                break;\n            }\n        }\n        return res;\n    }\n\n    bool operator<=(wto_nesting_t other) const { return this->compare(other) <= 0; }\n\n    bool operator==(wto_nesting_t other) const { return this->compare(other) == 0; }\n\n    bool operator>(wto_nesting_t other) const { return this->compare(other) == 1; }\n\n    void write(std::ostream& o) const {\n        o << \"[\";\n        for (auto it = this->begin(); it != this->end();) {\n            vertex_descriptor_t n = *it;\n            o << n;\n            ++it;\n            if (it != this->end()) {\n                o << \", \";\n            }\n        }\n        o << \"]\";\n    }\n}; // class nesting\n\n\ninline std::ostream& operator<<(std::ostream& o, const wto_nesting_t& n) {\n    n.write(o);\n    return o;\n}\n\n\nclass wto_component_t {\n\n  public:\n    virtual void accept(wto_component_visitor_t*) = 0;\n\n    virtual ~wto_component_t() = default;\n\n    virtual void write(std::ostream& os) const = 0;\n\n}; // class wto_component\n\n\ninline std::ostream& operator<<(std::ostream& o, const wto_component_t& c) {\n    c.write(o);\n    return o;\n}\n\n\n\nclass wto_component_visitor_t {\n\n  public:\n    virtual void visit(wto_vertex_t&) = 0;\n    virtual void visit(wto_cycle_t&) = 0;\n    virtual ~wto_component_visitor_t() = default;\n\n}; // class wto_component_visitor_t\n\n\nclass wto_vertex_t final : public wto_component_t {\n\n    friend class wto_t;\n\n  private:\n    vertex_descriptor_t _node;\n\n    explicit wto_vertex_t(vertex_descriptor_t node) : _node(std::move(node)) {}\n\n  public:\n    vertex_descriptor_t node() { return this->_node; }\n\n    void accept(wto_component_visitor_t* v) override { v->visit(*this); }\n\n    void write(std::ostream& o) const override { o << this->_node; }\n\n}; // class wto_vertex\n\n\nclass wto_cycle_t final : public wto_component_t {\n\n    friend class wto_t;\n  private:\n    using wto_component_ptr = std::shared_ptr<wto_component_t>;\n    using wto_component_list_t = std::forward_list<wto_component_ptr>;\n    using wto_component_list_ptr = std::shared_ptr<wto_component_list_t>;\n\n    vertex_descriptor_t _head;\n    wto_component_list_ptr _wto_components;\n    // number of times the wto cycle is analyzed by the fixpoint iterator\n    unsigned _num_fixpo;\n\n    wto_cycle_t(vertex_descriptor_t head, wto_component_list_ptr wto_components)\n        : _head(std::move(head)), _wto_components(std::move(wto_components)), _num_fixpo(0) {}\n\n  public:\n    using iterator = boost::indirect_iterator<typename wto_component_list_t::iterator>;\n    using const_iterator = boost::indirect_iterator<typename wto_component_list_t::const_iterator>;\n\n    vertex_descriptor_t head() { return this->_head; }\n\n    void accept(wto_component_visitor_t* v) override { v->visit(*this); }\n\n    iterator begin() { return boost::make_indirect_iterator(_wto_components->begin()); }\n\n    iterator end() { return boost::make_indirect_iterator(_wto_components->end()); }\n\n    const_iterator begin() const { return boost::make_indirect_iterator(_wto_components->begin()); }\n\n    const_iterator end() const { return boost::make_indirect_iterator(_wto_components->end()); }\n\n    void increment_fixpo_visits() { _num_fixpo++; }\n\n    void write(std::ostream& o) const override {\n        o << \"(\" << this->_head;\n        if (!this->_wto_components->empty()) {\n            o << \" \";\n            for (const_iterator it = this->begin(); it != this->end();) {\n                const wto_component_t& c = *it;\n                o << c;\n                ++it;\n                if (it != this->end()) {\n                    o << \" \";\n                }\n            }\n        }\n        o << \")\";\n        if (this->_num_fixpo > 0)\n            o << \"^{\" << this->_num_fixpo << \"}\";\n    }\n\n}; // class wto_cycle\n\nclass wto_t final {\n  private:\n    using wto_component_ptr = std::shared_ptr<wto_component_t>;\n    using wto_vertex_ptr = std::shared_ptr<wto_vertex_t>;\n    using wto_cycle_ptr = std::shared_ptr<wto_cycle_t>;\n    using wto_component_list_t = std::forward_list<wto_component_ptr>;\n    using wto_component_list_ptr = std::shared_ptr<wto_component_list_t>;\n    using dfn_t = bound_t;\n    using dfn_table_t = std::unordered_map<vertex_descriptor_t, dfn_t>;\n    using dfn_table_ptr = std::shared_ptr<dfn_table_t>;\n    using stack_t = std::vector<vertex_descriptor_t>;\n    using stack_ptr = std::shared_ptr<stack_t>;\n    using nesting_table_t = std::unordered_map<vertex_descriptor_t, wto_nesting_t>;\n    using nesting_table_ptr = std::shared_ptr<nesting_table_t>;\n\n    wto_component_list_ptr _wto_components;\n    dfn_table_ptr _dfn_table;\n    dfn_t _num;\n    stack_ptr _stack;\n    nesting_table_ptr _nesting_table;\n\n    class nesting_builder : public wto_component_visitor_t {\n      private:\n        wto_nesting_t _nesting;\n        nesting_table_ptr _nesting_table;\n\n      public:\n        explicit nesting_builder(nesting_table_ptr nesting_table) : _nesting_table(std::move(nesting_table)) {}\n\n        void visit(wto_cycle_t& cycle) override {\n            vertex_descriptor_t head = cycle.head();\n            wto_nesting_t previous_nesting = this->_nesting;\n            this->_nesting_table->insert(std::make_pair(head, this->_nesting));\n            this->_nesting += head;\n            for (typename wto_cycle_t::iterator it = cycle.begin(); it != cycle.end(); ++it) {\n                it->accept(this);\n            }\n            this->_nesting = previous_nesting;\n        }\n\n        void visit(wto_vertex_t& vertex) override {\n            this->_nesting_table->insert(std::make_pair(vertex.node(), this->_nesting));\n        }\n\n    }; // class nesting_builder\n\n    dfn_t get_dfn(const vertex_descriptor_t& n) {\n        auto it = this->_dfn_table->find(n);\n        if (it == this->_dfn_table->end()) {\n            return 0;\n        } else {\n            return it->second;\n        }\n    }\n\n    void set_dfn(const vertex_descriptor_t& n, const dfn_t& dfn) {\n        std::pair<typename dfn_table_t::iterator, bool> res = this->_dfn_table->insert(std::make_pair(n, dfn));\n        if (!res.second) {\n            (res.first)->second = dfn;\n        }\n    }\n\n    vertex_descriptor_t pop() {\n        if (this->_stack->empty()) {\n            CRAB_ERROR(\"WTO computation: empty stack\");\n        } else {\n            vertex_descriptor_t top = this->_stack->back();\n            this->_stack->pop_back();\n            return top;\n        }\n    }\n\n    void push(const vertex_descriptor_t& n) { this->_stack->push_back(n); }\n\n    wto_cycle_ptr component(cfg_t& g, const vertex_descriptor_t& vertex) {\n        auto partition = std::make_shared<wto_component_list_t>();\n        std::pair<out_edge_iterator_t, out_edge_iterator_t> succ_edges = out_edges(vertex, g);\n        for (out_edge_iterator_t it = succ_edges.first, et = succ_edges.second; it != et; ++it) {\n            vertex_descriptor_t succ = target(*it, g);\n            if (this->get_dfn(succ) == 0) {\n                this->visit(g, succ, partition);\n            }\n        }\n        return wto_cycle_ptr(new wto_cycle_t(vertex, partition));\n    }\n\n    struct visit_stack_elem {\n        using succ_iterator = out_edge_iterator_t;\n        vertex_descriptor_t _node;\n        succ_iterator _it; // begin iterator for node's successors\n        succ_iterator _et; // end iterator for node's successors\n        dfn_t _min;        // smallest dfn number of any (direct or\n                           // indirect) node's successor through node's\n                           // DFS subtree, included node.\n\n        visit_stack_elem(vertex_descriptor_t node, const std::pair<succ_iterator, succ_iterator>& succs, const dfn_t& min)\n            : _node(std::move(node)), _it(succs.first), _et(succs.second), _min(min) {}\n    };\n\n    void visit(cfg_t& g, const vertex_descriptor_t& vertex, const wto_component_list_ptr& partition) {\n\n        std::vector<visit_stack_elem> visit_stack;\n        std::set<vertex_descriptor_t> loop_nodes;\n\n        /* discover vertex */\n        push(vertex);\n        _num += 1;\n        set_dfn(vertex, _num);\n\n        visit_stack.emplace_back(vertex, out_edges(vertex, g), _num);\n        CRAB_LOG(\"wto-nonrec\", std::cout << \"WTO: Node \" << vertex << \": dfs num=\" << _num << \"\\n\";);\n        while (!visit_stack.empty()) {\n            /*\n             * Perform dfs.\n             *\n             * When this loop terminates, visit_stack.back()_node's children\n             * have been processed.  For each loop iteration we push in\n             * visit_stack one more descendant.\n             */\n            while (visit_stack.back()._it != visit_stack.back()._et) {\n                edge_descriptor_t e = *visit_stack.back()._it++;\n                vertex_descriptor_t child = target(e, g);\n                dfn_t child_dfn = get_dfn(child);\n                if (child_dfn == 0) {\n                    /* discover new vertex */\n                    push(child);\n                    _num += 1;\n                    set_dfn(child, _num);\n                    visit_stack.emplace_back(child, out_edges(child, g), _num);\n                    CRAB_LOG(\"wto-nonrec\", std::cout << \"WTO: Node \" << child << \": dfs num=\" << _num << \"\\n\";);\n                } else {\n                    if (child_dfn <= visit_stack.back()._min) {\n                        visit_stack.back()._min = child_dfn;\n                        CRAB_LOG(\"wto-nonrec\", std::cout << \"WTO: loop found \" << child << \"\\n\";);\n                        loop_nodes.insert(child);\n                    }\n                }\n            }\n\n            // propagate min from child to parent\n            vertex_descriptor_t visiting_node = visit_stack.back()._node;\n            dfn_t min_visiting_node = visit_stack.back()._min;\n            bool is_loop = loop_nodes.count(visiting_node) > 0;\n            visit_stack.pop_back();\n            if (!visit_stack.empty() && visit_stack.back()._min > min_visiting_node) {\n                visit_stack.back()._min = min_visiting_node;\n            }\n\n            auto dfn_visiting_node = get_dfn(visiting_node);\n            CRAB_LOG(\"wto-nonrec\", std::cout << \"WTO: popped node \" << visiting_node << \" dfs num= \"\n                                             << dfn_visiting_node << \": min=\" << min_visiting_node << \"\\n\";);\n\n            if (min_visiting_node == get_dfn(visiting_node)) {\n                CRAB_LOG(\"wto-nonrec\",\n                         std::cout << \"WTO: BEGIN building partition for node \" << visiting_node << \"\\n\";);\n                set_dfn(visiting_node, dfn_t::plus_infinity());\n                vertex_descriptor_t element = pop();\n                if (is_loop) {\n                    while (!(element == visiting_node)) {\n                        set_dfn(element, 0);\n                        CRAB_LOG(\"wto-nonrec\", std::cout << \"\\tWTO: node \" << element << \": dfn num=0\\n\";);\n                        element = pop();\n                    }\n                    CRAB_LOG(\"wto-nonrec\",\n                             std::cout << \"\\tWTO: adding component starting from \" << visiting_node << \"\\n\";);\n                    partition->push_front(component(g, visiting_node));\n                } else {\n                    CRAB_LOG(\"wto-nonrec\", std::cout << \"\\tWTO: adding vertex \" << visiting_node << \"\\n\";);\n                    partition->push_front(wto_vertex_ptr(new wto_vertex_t(visiting_node)));\n                }\n                CRAB_LOG(\"wto-nonrec\", std::cout << \"WTO: END building partition\\n\";);\n            }\n        } // end while (!visit_stack.empty())\n    }\n\n    void build_nesting() {\n        nesting_builder builder(this->_nesting_table);\n        for (iterator it = this->begin(); it != this->end(); ++it) {\n            it->accept(&builder);\n        }\n    }\n\n  public:\n    using iterator = boost::indirect_iterator<typename wto_component_list_t::iterator>;\n    using const_iterator = boost::indirect_iterator<typename wto_component_list_t::const_iterator>;\n\n    explicit wto_t(cfg_t& g)\n        : _wto_components(std::make_shared<wto_component_list_t>()), _dfn_table(std::make_shared<dfn_table_t>()),\n          _num(0), _stack(std::make_shared<stack_t>()), _nesting_table(std::make_shared<nesting_table_t>()) {\n        ScopedCrabStats __st__(\"Fixpo.WTO\");\n\n        this->visit(g, entry(g), this->_wto_components);\n        this->_dfn_table.reset();\n        this->_stack.reset();\n        this->build_nesting();\n    }\n\n    wto_t(const wto_t& other) = delete;\n\n    wto_t(const wto_t&& other) noexcept\n        : _wto_components(other._wto_components), _dfn_table(other._dfn_table), _num(other._num),\n          _stack(other._stack), _nesting_table(other._nesting_table) {}\n\n    wto_t& operator=(const wto_t& other) {\n        if (this != &other) {\n            this->_wto_components = other._wto_components;\n            this->_dfn_table = other._dfn_table;\n            this->_num = other._num;\n            this->_stack = other._stack;\n            this->_nesting_table = other._nesting_table;\n        }\n        return *this;\n    }\n\n    iterator begin() { return boost::make_indirect_iterator(_wto_components->begin()); }\n\n    iterator end() { return boost::make_indirect_iterator(_wto_components->end()); }\n\n    const_iterator begin() const { return boost::make_indirect_iterator(_wto_components->begin()); }\n\n    const_iterator end() const { return boost::make_indirect_iterator(_wto_components->end()); }\n\n    wto_nesting_t nesting(vertex_descriptor_t n) {\n        auto it = this->_nesting_table->find(n);\n        if (it == this->_nesting_table->end()) {\n            CRAB_ERROR(\"WTO nesting: node \", n, \" not found\");\n        } else {\n            return it->second;\n        }\n    }\n\n    void accept(wto_component_visitor_t* v) {\n        for (iterator it = this->begin(); it != this->end(); ++it) {\n            it->accept(v);\n        }\n    }\n\n    void write(std::ostream& o) const {\n        for (const_iterator it = this->begin(); it != this->end();) {\n            const wto_component_t& c = *it;\n            o << c;\n            ++it;\n            if (it != this->end()) {\n                o << \" \";\n            }\n        }\n    }\n\n    friend std::ostream& operator<<(std::ostream& o, const wto_t& wto) {\n        wto.write(o);\n        return o;\n    }\n\n}; // class wto\n\n} // namespace crab\n", "meta": {"hexsha": "e3a5e8200c017269784335ae54856704641242d3", "size": 19284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crab/wto.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/wto.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/wto.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": 35.7773654917, "max_line_length": 122, "alphanum_fraction": 0.6082244348, "num_tokens": 4657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.02843603427989483, "lm_q1q2_score": 0.009317587407966557}}
{"text": "#include <boost/serialization/vector.hpp>\n#include <boost/serialization/nvp.hpp>\n\n#include \"utilities/munkres/munkres.h\"\n\nusing boost::serialization::make_nvp;\n\ntemplate<class D>\nPDPoint<D>::\nPDPoint(RealType x, RealType y, const Data& data)\n{\n    point_.first().first = x;\n    point_.first().second = y;\n    point_.second() = data;\n}\n\n\ntemplate<class D>\ntemplate<class OtherData>\nPersistenceDiagram<D>::\nPersistenceDiagram(const PersistenceDiagram<OtherData>& other)\n{\n    points_.reserve(other.size());\n    for (typename PersistenceDiagram<OtherData>::PointVector::const_iterator cur = points_.begin();\n                                                                             cur != points_.end(); ++cur)\n        push_back(Point(cur->x(), cur->y()));\n}\n\ntemplate<class D>\ntemplate<class Iterator, class Evaluator>\nPersistenceDiagram<D>::\nPersistenceDiagram(Iterator bg, Iterator end, const Evaluator& eval)\n{\n    init(bg, end, eval, Point::Visitor());\n}\n\ntemplate<class D>\ntemplate<class Iterator, class Evaluator, class Visitor>\nPersistenceDiagram<D>::\nPersistenceDiagram(Iterator bg, Iterator end, const Evaluator& eval, const Visitor& visitor)\n{\n    init(bg, end, eval, visitor);\n}\n\ntemplate<class D>\ntemplate<class Iterator, class Evaluator, class Visitor>\nvoid\nPersistenceDiagram<D>::\ninit(Iterator bg, Iterator end, const Evaluator& evaluator, const Visitor& visitor)\n{\n    for (Iterator cur = bg; cur != end; ++cur)\n        if (cur->sign())\n        {\n            boost::optional<Point> p = make_point(cur, evaluator, visitor);\n            if (p)  push_back(*p);\n        }\n}\n\ntemplate<class Point, class Iterator, class Evaluator, class Visitor>\nboost::optional<Point>\nmake_point(Iterator i, const Evaluator& evaluator, const Visitor& visitor)\n{\n    RealType x = evaluator(&*i);\n    RealType y = Infinity;\n    if (&*(i->pair) != &*i)\n        y = evaluator(&*(i->pair));\n\n    Point p(x,y);\n    visitor.point(i, p);\n\n    if (x == y) return boost::optional<Point>();\n\n    return p;\n}\n\ntemplate<class Diagrams, class Iterator, class Evaluator, class DimensionExtractor>\nvoid    init_diagrams(Diagrams& diagrams,\n                      Iterator bg, Iterator end,\n                      const Evaluator& evaluator,\n                      const DimensionExtractor& dimension)\n{\n    // FIXME: this is specialized for Diagrams that is std::map\n    typedef             typename Diagrams::mapped_type              PDiagram;\n\n    init_diagrams(diagrams, bg, end, evaluator, dimension, typename PDiagram::Point::Visitor());\n}\n\ntemplate<class Diagrams, class Iterator, class Evaluator, class DimensionExtractor, class Visitor>\nvoid    init_diagrams(Diagrams& diagrams,\n                      Iterator bg, Iterator end,\n                      const Evaluator& evaluator,\n                      const DimensionExtractor& dimension,\n                      const Visitor& visitor)\n{\n    // FIXME: this is specialized for Diagrams that is std::map\n    typedef             typename Diagrams::mapped_type              PDiagram;\n\n    for (Iterator cur = bg; cur != end; ++cur)\n        if (cur->sign())\n        {\n            boost::optional<typename PDiagram::Point> p = make_point<typename PDiagram::Point>(cur, evaluator, visitor);\n            if (p)\n                diagrams[dimension(&*cur)].push_back(*p);\n        }\n}\n\ntemplate<class D>\nstd::ostream&\nPersistenceDiagram<D>::\noperator<<(std::ostream& out) const\n{\n    for (const_iterator cur = begin(); cur != end(); ++cur)\n        out << *cur << std::endl;\n    return out;\n}\n\ntemplate<class D>\ntemplate<class Archive>\nvoid\nPDPoint<D>::\nserialize(Archive& ar, version_type )\n{\n    ar & make_nvp(\"x\", x());\n    ar & make_nvp(\"y\", y());\n    ar & make_nvp(\"data\", data());\n}\n\ntemplate<class D>\ntemplate<class Archive>\nvoid\nPersistenceDiagram<D>::\nserialize(Archive& ar, version_type )\n{\n    ar & make_nvp(\"points\", points_);\n}\n\n\n/**\n * Some structures to compute bottleneck distance between two persistence diagrams (in bottleneck_distance() function below)\n * by setting up bipartite graphs, and finding maximum cardinality matchings in them using Boost Graph Library.\n */\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n\nstruct Edge: public std::pair<unsigned long, unsigned long>\n{\n    typedef         std::pair<unsigned long, unsigned long>                       Parent;\n\n                    Edge(unsigned long v1, unsigned long v2, RealType d):\n                        Parent(v1, v2), distance(d)                     {}\n\n    bool            operator<(const Edge& other) const                  { return distance < other.distance; }\n\n    RealType        distance;\n};\ntypedef std::vector<Edge>               EdgeVector;\ntypedef EdgeVector::const_iterator      EV_const_iterator;\n\nstruct CardinaliyComparison\n{\n    typedef         boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>         Graph;\n    typedef         std::vector<boost::graph_traits<Graph>::vertex_descriptor>                  MatchingVector;\n\n                    CardinaliyComparison(unsigned long size, EV_const_iterator begin):\n                        max_size(size), bg(begin), last(bg), g(2*max_size), mates(2*max_size)\n                    { boost::add_edge(bg->first, bg->second, g); }\n\n    bool            operator()(EV_const_iterator i1, EV_const_iterator i2)\n    {\n        //std::cout << \"Max size: \" << max_size << std::endl;\n        //std::cout << \"Comparing: (\" << i1->first << \", \" << i1->second << \") and \"\n        //          <<            \"(\" << i2->first << \", \" << i2->second << \")\" << std::endl;\n\n        // FIXME: the matching is being recomputed from scratch every time, this should be fixed\n        if (i2 > last)\n            do\n            {\n                ++last;\n                boost::add_edge(last->first, last->second, g);\n            } while (last != i2);\n        else\n            do\n            {\n                boost::remove_edge(last->first, last->second, g);\n            } while (--last != i2);\n\n        edmonds_maximum_cardinality_matching(g, &mates[0]);\n        //std::cout << \"Found matching of size: \" << matching_size(g, &mates[0]) << std::endl;\n        return matching_size(g, &mates[0]) == max_size;\n    }\n\n    unsigned long                max_size;\n    EV_const_iterator       bg;\n    EV_const_iterator       last;\n    Graph                   g;\n    MatchingVector          mates;\n};\n\n// Bottleneck distance\ntemplate<class Diagram1, class Diagram2, class Norm>\nRealType                bottleneck_distance(const Diagram1& dgm1, const Diagram2& dgm2, const Norm& norm)\n{\n    typedef         typename Diagram1::const_iterator                   Citer1;\n    typedef         typename Diagram2::const_iterator                   Citer2;\n\n    const unsigned long  max_size = dgm1.size() + dgm2.size();\n\n    // Compute all the edges and sort them by distance\n    EdgeVector   edges;\n\n    // Connect all diagonal points to each other\n    for (unsigned long i = dgm1.size(); i < max_size; ++i)\n        for (unsigned long j = max_size + dgm2.size(); j < 2*max_size; ++j)\n            edges.push_back(Edge(i, j, 0));\n\n    // Edges between real points\n    unsigned long i = 0;\n    for (Citer1 cur1 = dgm1.begin(); cur1 != dgm1.end(); ++cur1)\n    {\n        unsigned long j = max_size;\n        for (Citer2 cur2 = dgm2.begin(); cur2 != dgm2.end(); ++cur2)\n            edges.push_back(Edge(i,j++, norm(*cur1, *cur2)));\n\n        ++i;\n    }\n\n    // Edges between real points and their corresponding diagonal points\n    i = 0;\n    for (Citer1 cur1 = dgm1.begin(); cur1 != dgm1.end(); ++cur1, ++i)\n        edges.push_back(Edge(i, max_size + dgm2.size() + i, norm.diagonal(*cur1)));\n    i = max_size;\n    for (Citer2 cur2 = dgm2.begin(); cur2 != dgm2.end(); ++cur2, ++i)\n        edges.push_back(Edge(dgm1.size() + (i - max_size), i, norm.diagonal(*cur2)));\n\n\n    std::sort(edges.begin(), edges.end());\n    //for (i = 0; i < edges.size(); ++i)\n    //    std::cout << \"Edge: \" << edges[i].first << \" \" << edges[i].second << \" \" << edges[i].distance << std::endl;\n\n    // Perform cardinality based binary search\n    typedef boost::counting_iterator<EV_const_iterator>         EV_counting_const_iterator;\n    EV_counting_const_iterator bdistance = std::upper_bound(EV_counting_const_iterator(edges.begin()),\n                                                            EV_counting_const_iterator(edges.end()),\n                                                            edges.begin(),\n                                                            CardinaliyComparison(max_size, edges.begin()));\n\n    return (*bdistance)->distance;\n}\n\n// Wasserstein distance\ntemplate<class Diagram>\nRealType\nwasserstein_distance(const Diagram& dgm1, const Diagram& dgm2, long p)\n{\n    typedef         RealType                    Distance;\n    typedef         typename Diagram::Point     Point;\n    typedef         Linfty<Point, Point>        Norm;\n\n    unsigned long size = dgm1.size() + dgm2.size();\n    Norm norm;\n\n    // Setup the matrix\n    Matrix<Distance>        m(size,size);\n    for (unsigned long i = 0; i < dgm1.size(); ++i)\n        for (unsigned long j = 0; j < dgm2.size(); ++j)\n        {\n            const Point& p1 = *(dgm1.begin() + i);\n            const Point& p2 = *(dgm2.begin() + j);\n            m(i,j) = pow(norm(p1, p2),  p);\n            m(j + dgm1.size(), i + dgm2.size()) = 0;\n        }\n\n    for (unsigned long i = 0; i < dgm1.size(); ++i)\n        for (unsigned long j = dgm2.size(); j < size; ++j)\n        {\n            const Point& p1 = *(dgm1.begin() + i);\n            m(i,j) = pow(norm.diagonal(p1), p);\n        }\n\n    for (unsigned long j = 0; j < dgm2.size(); ++j)\n        for (unsigned long i = dgm1.size(); i < size; ++i)\n        {\n            const Point& p2 = *(dgm2.begin() + j);\n            m(i,j) = pow(norm.diagonal(p2), p);\n        }\n\n    // Compute weighted matching\n    Munkres munkres;\n    munkres.solve(m);\n\n    // Assume everything is assigned (i.e., that we have a perfect matching)\n    Distance sum = 0;\n    for (unsigned long i = 0; i < size; i++)\n        for (unsigned long j = 0; j < size; j++)\n            if (m(i,j) == 0)\n            {\n                //std::cout << i << \": \" << j << '\\n';\n                //sum += m[i][j];\n                if (i >= dgm1.size())\n                {\n                    if (j >= dgm2.size())\n                        sum += 0;\n                    else\n                    {\n                        const Point& p2 = *(dgm2.begin() + j);\n                        sum += pow(norm.diagonal(p2), p);\n                    }\n                } else\n                {\n                    if (j >= dgm2.size())\n                    {\n                        const Point& p1 = *(dgm1.begin() + i);\n                        sum += pow(norm.diagonal(p1), p);\n                    } else\n                    {\n                        const Point& p1 = *(dgm1.begin() + i);\n                        const Point& p2 = *(dgm2.begin() + j);\n                        sum += pow(norm(p1, p2),  p);\n                    }\n                }\n                break;\n            }\n\n    return sum;\n}\n", "meta": {"hexsha": "6ad74fcc1984e69776a06fd82d7dcb434ec3d050", "size": 11153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/topology/persistence-diagram.hpp", "max_stars_repo_name": "astrophys/TDA.long", "max_stars_repo_head_hexsha": "51bbf8970f50c32ff4591494bba241e1837927ab", "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/topology/persistence-diagram.hpp", "max_issues_repo_name": "astrophys/TDA.long", "max_issues_repo_head_hexsha": "51bbf8970f50c32ff4591494bba241e1837927ab", "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/topology/persistence-diagram.hpp", "max_forks_repo_name": "astrophys/TDA.long", "max_forks_repo_head_hexsha": "51bbf8970f50c32ff4591494bba241e1837927ab", "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.1070336391, "max_line_length": 124, "alphanum_fraction": 0.5503451986, "num_tokens": 2659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.02002344107015669, "lm_q1q2_score": 0.009308928920916025}}
{"text": "/*\nFor more information, please see: http://software.sci.utah.edu\n\nThe MIT License\n\nCopyright (c) 2015 Scientific Computing and Imaging Institute,\nUniversity of Utah.\n\nLicense for the specific language governing rights and limitations under\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\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n*/\n\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/BrainStimulator/GenerateROIStatisticsAlgorithm.h>\n#include <Core/GeometryPrimitives/Vector.h>\n#include <Core/Datatypes/Legacy/Field/Field.h>\n#include <Core/Datatypes/Legacy/Field/VField.h>\n#include <Core/Datatypes/Legacy/Field/FieldInformation.h>\n#include <Core/Datatypes/Legacy/Field/VMesh.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/Matrix.h>\n#include <Core/Datatypes/String.h>\n#include <boost/range/algorithm/count.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/format.hpp>\n#include <boost/assign.hpp>\n#include <Core/Logging/Log.h>\n#include <string> \n#include <iostream>\n\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::BrainStimulator;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Logging;\nusing namespace boost::assign;\n\nconst AlgorithmInputName GenerateROIStatisticsAlgorithm::MeshDataOnElements(\"MeshDataOnElements\");\nconst AlgorithmInputName GenerateROIStatisticsAlgorithm::PhysicalUnit(\"PhysicalUnit\");\nconst AlgorithmInputName GenerateROIStatisticsAlgorithm::AtlasMesh(\"AtlasMesh\");\nconst AlgorithmInputName GenerateROIStatisticsAlgorithm::AtlasMeshLabels(\"AtlasMeshLabels\");\nconst AlgorithmInputName GenerateROIStatisticsAlgorithm::CoordinateSpace(\"CoordinateSpace\");\nconst AlgorithmInputName GenerateROIStatisticsAlgorithm::CoordinateSpaceLabel(\"CoordinateSpaceLabel\");\nconst AlgorithmInputName GenerateROIStatisticsAlgorithm::SpecifyROI(\"SpecifyROI\");\nconst AlgorithmOutputName GenerateROIStatisticsAlgorithm::StatisticalResults(\"StatisticalResults\");\n\nALGORITHM_PARAMETER_DEF(BrainStimulator, ROITableValues);\nALGORITHM_PARAMETER_DEF(BrainStimulator, StatisticsTableValues);\nALGORITHM_PARAMETER_DEF(BrainStimulator, PhysicalUnitStr);\nALGORITHM_PARAMETER_DEF(BrainStimulator, CoordinateSpaceLabelStr);\n\nGenerateROIStatisticsAlgorithm::GenerateROIStatisticsAlgorithm()\n{\n  using namespace Parameters;\n  addParameter(ROITableValues, 0);\n  addParameter(StatisticsTableValues, 0);\n  addParameter(PhysicalUnitStr, std::string());\n  addParameter(CoordinateSpaceLabelStr, std::string());\n}\n\nnamespace\n{\n  std::string formatStatistic(double x)\n  {\n    if (IsNan(x))\n      return \"NaN\";\n    return boost::str(boost::format(\"%.3f\") % x);\n  }\n\n  std::string formatCount(double x)\n  {\n    if (IsNan(x))\n      return \"NaN\";\n    return boost::str(boost::format(\"%d\") % x);\n  }\n}\n\n/// the run function can deal with multiple inputs and performs the analysis for all ROIs in the atlas mesh and for the user specified ROI\nboost::tuple<DenseMatrixHandle, VariableHandle> GenerateROIStatisticsAlgorithm::run(FieldHandle mesh, FieldHandle AtlasMesh, const FieldHandle CoordinateSpace, const std::string& AtlasMeshLabels, const DenseMatrixHandle specROI) const\n{\n  DenseMatrixHandle output;\n\n  VField* vfield1 = mesh->vfield();\n  VField* vfield2 = AtlasMesh->vfield();  \n\n  std::vector<bool> element_selection(vfield2->vmesh()->num_elems(), true);  /// set the default element ROI selection, so all of them are included\n\n  double x=0,y=0,z=0,radius=-1,target_material=-1;\n  /// CoordinateSpace is provided and coordinates? if not don't go in this if clause\n  if (CoordinateSpace != nullptr && specROI != nullptr) \n  {\n    if ( (*specROI).ncols()==1 && (*specROI).nrows()==5 ) /// GUI input (as DenseMatrix) has the right sizes (rows, cols)?\n    {  \n      x=(*specROI)(0,0);\n      y=(*specROI)(1,0);\n      z=(*specROI)(2,0);\n      target_material=(*specROI)(3,0);\n      radius=(*specROI)(4,0);\n\n      if (radius<0) /// if radius < 0, its invalid input provide a remark and do the statistical analysis for all ROIs instead\n      {\n        remark(\"Radius needs to be > 0 and Atlas Material # needs to exist \");  \n      } else\n      {\n        if (radius>0)\n        {\n          element_selection = statistics_based_on_xyz_coodinates(AtlasMesh, CoordinateSpace, x, y, z, radius, target_material); /// redefine the element ROI selection if correct input was delivered\n        }\n      }\n    }\n\n  }\n\n  if(element_selection.size()!=vfield1->vmesh()->num_elems()) /// internal error check if selection vector really matches number of mesh elements \n  {\n    THROW_ALGORITHM_INPUT_ERROR(\"Internal Error: Element selection vector does not match number of mesh elements \"); \n  }\n\n  size_t number_of_atlas_materials;\n\n  std::set<int> labelSet;\n\n  if (target_material==-1 || radius==0) /// if default consider all materials\n  {\n    for (VMesh::Elem::index_type i=0; i < vfield2->vmesh()->num_elems(); i++) // loop over all tetrahedral elements (mesh)\n    {\n      int Label;\n      vfield2->get_value(Label, i);\n      labelSet.insert(Label);  \n    }\n  } else\n  {\n    labelSet.insert(static_cast<int>(target_material));\n  }\n\n  number_of_atlas_materials = labelSet.size();\n\n  std::vector<int> labelVector(labelSet.begin(), labelSet.end()); \n\n  std::ostringstream ostr; /// sort element labels ascending \n  std::copy(labelSet.begin(), labelSet.end(), std::ostream_iterator<int>(ostr, \", \"));\n  LOG_DEBUG(\"Sorted set of label numbers: \" << ostr.str() << std::endl);\n\n  std::vector<double> value_avr(number_of_atlas_materials);\n  std::vector<int> value_count(number_of_atlas_materials);\n  std::vector<double> value_min(number_of_atlas_materials);\n  std::vector<double> value_max(number_of_atlas_materials);\n  std::vector<double> value_std(number_of_atlas_materials); \n  std::vector<double> Sxsqr(number_of_atlas_materials);\n  std::vector<double> stddev(number_of_atlas_materials);\n  std::vector<double> var(number_of_atlas_materials);\n\n  /// to do the actual statistics we need to precompute parts of it to make it efficient (don't loop over elements twice)\n  for (VMesh::Elem::index_type i=0; i < vfield1->vmesh()->num_elems(); i++) /// loop over all tetrahedral elements (AtlasMesh)\n  {\n\n    if(element_selection[i]) ///is an particular element selected?\n    {\n      double value = 0;\n      vfield1->get_value(value, i); \n\n      int Label = 0;\n      vfield2->get_value(Label, i);   \n\n      for (VMesh::Elem::index_type j=0; j < number_of_atlas_materials; j++) /// loop over determined materials\n      {\n        if (Label==labelVector[j] || (target_material==0 && number_of_atlas_materials==1) ) /// if label is known or if default situation precalculate sum, min, max, sum^2, number of selected elements\n        {\n          value_avr[j] += value; \n          value_count[j]++;   \n          if (value>value_max[j]) value_max[j]=value;\n          if (value<value_min[j] || value_min[j]==0) value_min[j]=value;\n          Sxsqr[j]+=value*value;\n        }\n      }\n    }\n  }\n\n  output = DenseMatrixHandle(new DenseMatrix(number_of_atlas_materials, 5)); /// instantiate output\n  const double invalidDouble = std::numeric_limits<double>::quiet_NaN();\n\n  /// efficient way to compute std dev. in just one loop over all mesh elements: sqrt ( 1/(n-1) (Sx^2 - avr Sx + n avr^2 )\n  for (VMesh::Elem::index_type j=0; j < number_of_atlas_materials; j++)\n  {\n    double Sx=value_avr[j];\n\n    if (value_count[j]!=0)\n    {\n      value_avr[j]/=value_count[j]; \n      if (value_count[j]>1)\n      {\n        var[j]=static_cast<double>(1./(value_count[j]-1)*(Sxsqr[j]-2*value_avr[j]*Sx+value_count[j]*value_avr[j]*value_avr[j]));\n        stddev[j]=static_cast<double>(std::sqrt(var[j])); /// compute standard deviation, average, variance\n      } else\n      {\n        var[j]=invalidDouble;\n        stddev[j]=invalidDouble;\n      }\n\n      (*output)(j,0)=value_avr[j]; /// save statistical measures in output (DenseMatrix)\n      (*output)(j,1)=stddev[j];\n      (*output)(j,2)=value_min[j];\n      (*output)(j,3)=value_max[j];  \n      (*output)(j,4)=value_count[j];  \n    } else\n    {\n      (*output)(j,0)=invalidDouble;  /// if the number of elements is 0, provide NaN as output\n      (*output)(j,1)=invalidDouble;\n      (*output)(j,2)=invalidDouble;\n      (*output)(j,3)=invalidDouble;\n      (*output)(j,4)=invalidDouble;\n    }\n  }  \n\n  std::vector<std::string> AtlasMeshLabels_vector;\n  if (!AtlasMeshLabels.empty())\n  {\n    AtlasMeshLabels_vector = ConvertInputAtlasStringIntoVector(AtlasMeshLabels); /// cut the atlas ROI labels into pieces (std::vector)\n  }\n\n  if (AtlasMeshLabels_vector.size()==0 && number_of_atlas_materials>0)\n  {\n    AtlasMeshLabels_vector.resize(number_of_atlas_materials);\n    for (int i=0; i<number_of_atlas_materials; i++)\n    {\n      AtlasMeshLabels_vector[i]=boost::lexical_cast<std::string>(i+1); /// if no atlas ROI labels are provided use consecutive numbers\n    }\n  }\n  else\n    if (AtlasMeshLabels_vector.size() != number_of_atlas_materials)\n    {\n      if (target_material!=-1 && number_of_atlas_materials==1)\n      {\n        AtlasMeshLabels_vector.resize(1);\n        AtlasMeshLabels_vector[0]=\"specROI\";  /// if an ROI was specified by the user use specROI label for the upper table \n      }\n      else\n      {\n        THROW_ALGORITHM_INPUT_ERROR(\"Number of material Labels in AtlasMesh and AtlasMeshLabels do not match\"); \n      }\n    } \n\n    //TODO: use this example to improve Variable::List syntactical sugar\n    Variable::List elc_vals_in_table;\n    for (int i=0; i<AtlasMeshLabels_vector.size(); i++) /// loop over all materials, format numbers and put it in a Variable structure to be accessible in the GUI\n    {\n      Variable::List tmp;\n      tmp += makeVariable(\"name\", AtlasMeshLabels_vector[i]), //label name\n        makeVariable(\"col0\", formatStatistic((*output)(i,0))), //average\n        makeVariable(\"col1\", formatStatistic((*output)(i,1))), //stddev\n        makeVariable(\"col2\", formatStatistic((*output)(i,2))), //min\n        makeVariable(\"col3\", formatStatistic((*output)(i,3))), //max\n        makeVariable(\"col4\", formatCount((*output)(i,4))); //element count\n\n      elc_vals_in_table.push_back(makeVariable(\"row\" + boost::lexical_cast<std::string>(i), tmp));\n    }\n\n    VariableHandle statistics_table(new Variable(Name(\"Table\"), elc_vals_in_table));\n\n    return boost::make_tuple(output, statistics_table);\n}\n\n/// this function takes the (x,y,z) location of the user specified ROI and results in a std:vector<bool> that contains trues for ROI mesh elements and false for non-ROI mesh elements\nstd::vector<bool> GenerateROIStatisticsAlgorithm::statistics_based_on_xyz_coodinates(const FieldHandle mesh, const FieldHandle CoordinateSpace, double x, double y, double z, double radius, int target_material) const\n{\n  VField* vfield_coordspace = CoordinateSpace->vfield();\n  VMesh* vmesh_coordspace = vfield_coordspace->vmesh();\n  VField* vfield_atlas = mesh->vfield();\n  VMesh* vmesh_atlas = vfield_atlas->vmesh();\n  std::vector<bool> element_selection;\n  long closest_atlas_element=-1;\n  double distance=-1, mindis=std::numeric_limits<double>::max();\n  Vector val;\n\n  for (VMesh::Elem::index_type i=0; i < vmesh_coordspace->num_elems(); i++) /// loop over all tetrahedral elements (mesh)\n  {\n    vfield_coordspace->get_value(val,i);\n    distance = std::sqrt((x-val[0])*(x-val[0])+(y-val[1])*(y-val[1])+(z-val[2])*(z-val[2]));\n    if (distance < mindis)\n    {\n      closest_atlas_element=(long)i;\n      mindis=distance;\n    }\n  }\n\n  if (mindis>1)\n  {\n    std::ostringstream ostr1;\n    ostr1 << \"Distance from provided point (lower table in GUI: x,y,z) is more then 1 (=\" << mindis << \") distance units away from provided coordinate space (coordinates defined as element data).\" <<  std::endl;\n    THROW_ALGORITHM_INPUT_ERROR(ostr1.str()); \n\n  }\n\n  Point p;\n  VMesh::Elem::index_type atlas_index = closest_atlas_element;\n  vmesh_coordspace->get_center(p,atlas_index); \n\n  double x1=p.x(), y1=p.y(), z1=p.z();\n\n  long count_loop=0;\n\n  for (VMesh::Elem::index_type i=0; i < vmesh_atlas->num_elems(); i++) /// loop over all tetrahedral elements (mesh)\n  {\n    if (target_material!=0)  /// was the target material (Atlas Material #) provided not the default, so \"-1\"\n    {\n      int current_material=-1;\n      vfield_atlas->get_value(current_material, i);\n      if (target_material==current_material) /// if the current material is in the defined spherical ROI and of the material we are looking for?\n      {\n        VMesh::Elem::index_type tmp = count_loop;\n        vmesh_atlas->get_center(p,tmp);\n\n        distance = sqrt((x1-p.x())*(x1-p.x())+(y1-p.y())*(y1-p.y())+(z1-p.z())*(z1-p.z()));\n        if (distance > radius)\n        {\n          element_selection.push_back(false);  \n        } else\n        {\n          element_selection.push_back(true); \n        }\n      } else\n      {\n        element_selection.push_back(false); \n      }\n    } else\n    {     /// in the else close look for materials in the ROI    \n      VMesh::Elem::index_type tmp = count_loop;\n      vmesh_atlas->get_center(p,tmp);\n      distance = sqrt((x1-p.x())*(x1-p.x())+(y1-p.y())*(y1-p.y())+(z1-p.z())*(z1-p.z()));\n      if ( distance > radius)\n      {\n        element_selection.push_back(false); \n      } else\n      {\n        element_selection.push_back(true);  \n      }\n    }  \n    count_loop++;\n  }\n\n  return element_selection;\n}\n\n/// this function cuts the atlas label string into pieces (std::vector) based on the semicolon\nstd::vector<std::string> GenerateROIStatisticsAlgorithm::ConvertInputAtlasStringIntoVector(const std::string& atlasLabels) const\n{\n  std::vector<std::string> result;\n  auto atlasLabelsTrimmed = atlasLabels;\n  boost::trim_if(atlasLabelsTrimmed, boost::is_any_of(\";\")); /// use boost's trim function to get rid of all additional semicolons or\n  boost::split(result,atlasLabelsTrimmed,boost::is_any_of(\";\")); /// use boost's trim function to cut the string\n\n  return result;\n}\n\nAlgorithmOutput GenerateROIStatisticsAlgorithm::run_generic(const AlgorithmInput& input) const\n{\n\n  auto mesh_ = input.get<Field>(MeshDataOnElements);\n  auto physicalUnit_ = input.get<Datatypes::String>(PhysicalUnit);\n  auto atlasMesh_ = input.get<Field>(AtlasMesh);\n  auto atlasMeshLabels_ = input.get<Datatypes::String>(AtlasMeshLabels);\n  auto coordinateSpace_ = input.get<Field>(CoordinateSpace);\n  auto coordinateLabel_ = input.get<Datatypes::String>(CoordinateSpaceLabel);  \n  auto roiSpec = input.get<DenseMatrix>(SpecifyROI);\n\n  /// In the following check the validity of the inputs\n  if (!mesh_)  \n    THROW_ALGORITHM_INPUT_ERROR(\"First input (mesh) is empty.\");\n\n  if (!atlasMesh_)  \n    THROW_ALGORITHM_INPUT_ERROR(\"Third input (atlas mesh) is empty.\");\n\n  FieldInformation fi(mesh_);\n\n  if (!fi.is_constantdata())\n    THROW_ALGORITHM_INPUT_ERROR(\"First input (mesh) requires the data to be on the elements.\");\n\n  // making sure the field contains data\n  VField* vfield1 = mesh_->vfield();\n  if (vfield1->is_nodata())\n    THROW_ALGORITHM_INPUT_ERROR(\"First input field (mesh) contained no data.\");\n\n  // making sure the field is not in vector format\n  if (!vfield1->is_scalar())\n    THROW_ALGORITHM_INPUT_ERROR(\"First input field needs to have scalar data.\");      \n\n  FieldInformation fi2(atlasMesh_);\n\n  if (!fi2.is_constantdata())\n    THROW_ALGORITHM_INPUT_ERROR(\"First input (mesh) requires the data to be on the elements.\");\n\n  // making sure the field contains data\n  VField* vfield2 = atlasMesh_->vfield();\n  if (vfield2->is_nodata())\n    THROW_ALGORITHM_INPUT_ERROR(\"First input field (mesh) contained no data.\");\n\n  // making sure the field is not in vector format\n  if (!vfield2->is_scalar())\n    THROW_ALGORITHM_INPUT_ERROR(\"First input field needs to have scalar data.\"); \n\n  if(vfield1->vmesh()->num_elems()<1 && vfield2->vmesh()->num_elems()<1)\n    THROW_ALGORITHM_INPUT_ERROR(\"First (mesh) or second (AtlasMesh) input field does not contain elements.\"); \n\n  if(vfield2->vmesh()->num_elems() !=  vfield1->vmesh()->num_elems())\n    THROW_ALGORITHM_INPUT_ERROR(\" Number of mesh elements of first input and third input does not match.\");  \n\n  DenseMatrixHandle statistics;\n  VariableHandle Statisticstable;\n\n  /// since there are so many optional inputs to the module decide based on them and call the run function\n  const std::string& atlasMeshLabelsStr = atlasMeshLabels_ == nullptr ? std::string(\"\") : atlasMeshLabels_->value();\n  const FieldHandle coorspace_ = coordinateSpace_ == nullptr ? FieldHandle() : coordinateSpace_;\n  const DenseMatrixHandle roiSpec_ = roiSpec == nullptr ? DenseMatrixHandle() : roiSpec;\n  boost::tie(statistics, Statisticstable) = run(mesh_, atlasMesh_, coorspace_, atlasMeshLabelsStr, roiSpec_);\n\n  /// no statistics output? something went wrong then\n  if (!statistics)\n  {\n    THROW_ALGORITHM_INPUT_ERROR(\" Statistics output is null pointer! \"); \n  }\n\n  AlgorithmOutput output;\n  output[StatisticalResults] = statistics;\n  output.setAdditionalAlgoOutput(Statisticstable);\n\n  return output;\n}\n", "meta": {"hexsha": "a1c40e54c3826d7eae90b99ee143aa3b8f9a9021", "size": 18066, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/BrainStimulator/GenerateROIStatisticsAlgorithm.cc", "max_stars_repo_name": "mhansen1/SCIRun", "max_stars_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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/Core/Algorithms/BrainStimulator/GenerateROIStatisticsAlgorithm.cc", "max_issues_repo_name": "mhansen1/SCIRun", "max_issues_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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/Core/Algorithms/BrainStimulator/GenerateROIStatisticsAlgorithm.cc", "max_forks_repo_name": "mhansen1/SCIRun", "max_forks_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "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.3258928571, "max_line_length": 234, "alphanum_fraction": 0.709509576, "num_tokens": 4557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.03021458379267781, "lm_q1q2_score": 0.009286694554926792}}
{"text": "/***********************************************************************************************************************\n*  OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n*  following conditions are met:\n*\n*  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n*  disclaimer.\n*\n*  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n*  disclaimer in the documentation and/or other materials provided with the distribution.\n*\n*  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products\n*  derived from this software without specific prior written permission from the respective party.\n*\n*  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works\n*  may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without specific prior\n*  written permission from Alliance for Sustainable Energy, LLC.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n*  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED\n*  STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n*  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n*  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************************************************************/\n\n#ifndef UTILITIES_DATA_VECTOR_HPP\n#define UTILITIES_DATA_VECTOR_HPP\n\n#include \"../UtilitiesAPI.hpp\"\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace openstudio {\n\n/// Workaround to get Vector typedef, http://www.gotw.ca/gotw/079.htm\nstruct UTILITIES_API VectorStruct\n{\n  typedef boost::numeric::ublas::vector<double> VectorType;\n  typedef boost::numeric::ublas::scalar_vector<double> ScalarVectorType;\n};\n\n/// Vector\ntypedef VectorStruct::VectorType Vector;\n\n/// ScalarVector\ntypedef VectorStruct::ScalarVectorType ScalarVector;\n\n/// Helper function to construct Vector from std::vector<double>.\nUTILITIES_API Vector createVector(const std::vector<double>& values);\n\n/// Helper function to construct Vector from std::vector<long>\nUTILITIES_API Vector createVector(const std::vector<long>& values);\n\nUTILITIES_API std::vector<double> toStandardVector(const Vector& values);\n\n//////////////////////////////////////////////////////////////////////////\n// Begin SWIG'able, copy and paste into Vector.i\n//////////////////////////////////////////////////////////////////////////\n\n/** @name Operators */\n//@{\n\nUTILITIES_API bool operator==(const Vector& lhs, const Vector& rhs);\nUTILITIES_API bool operator!=(const Vector& lhs, const Vector& rhs);\n\n//@}\n/** @name Interpolation */\n//@{\n\n// The following link has hints for interpolation\n// http://o2scl.sourceforge.net/o2scl/html/index.html#intp_section\n\n/** Enum to specify the interpolation method. */\nenum InterpMethod{LinearInterp, NearestInterp, HoldLastInterp, HoldNextInterp};\n\n/** Enum to specify the extrapolation method. */\nenum ExtrapMethod{NoneExtrap, NearestExtrap};\n\n/** Data structure for holding interpolation information. */\nstruct UTILITIES_API InterpInfo{\n  bool extrapolated; // was point out of range\n  unsigned ia, ib; // indices of two nearest points\n  double wa, wb; // weights of two nearest points\n};\n\n/** Linear interpolation of the function y = f(x) at point xi. Assumes that x is strictly\n *  increasing. */\nUTILITIES_API InterpInfo interpInfo(const Vector& x, double xi);\n\n/** Linear interpolation of the function y = f(x) at point xi. Assumes that x is strictly\n *  increasing */\nUTILITIES_API double interp(const Vector& x, const Vector& y, double xi,\n                            InterpMethod interpMethod = LinearInterp,\n                            ExtrapMethod extrapMethod = NoneExtrap);\n\n/** Linear interpolation of the function y = f(x) at points xi. Assumes that x is strictly\n *  increasing. */\nUTILITIES_API Vector interp(const Vector& x, const Vector& y, const Vector& xi,\n                            InterpMethod interpMethod = LinearInterp,\n                            ExtrapMethod extrapMethod = NoneExtrap);\n\n//@}\n/** @name Common Methods and Vector Operations */\n//@{\n\n/** Generates a Vector of N points randomly drawn between and including a and b. */\nUTILITIES_API Vector randVector(double a, double b, unsigned N);\n\n/** Generates a Vector of N points linearly spaced between and including a and b. */\nUTILITIES_API Vector linspace(double a, double b, unsigned N);\n\n/** Generates a Vector linearly spaced points starting at a and ending before or at b with\n *  interval delta. */\nUTILITIES_API Vector deltaSpace(double a, double b, double delta);\n\n/** Generates a Vector of N points logarithmically spaced between and including base^a and\n *  base^b. */\nUTILITIES_API Vector logspace(double a, double b, unsigned N, double base = 10.0);\n\n/** Take the natural logarithm of elements of a Vector. */\nUTILITIES_API Vector log(const Vector& x);\n\n/** Take the logarithm of elements of a Vector with certain base. */\nUTILITIES_API Vector log(const Vector& x, double base);\n\n/** Compute the cumulative sum of a Vector. */\nUTILITIES_API Vector cumsum(const Vector& x, double runningSum = 0.0);\n\n/** Returns the dot product between lhs and rhs. */\nUTILITIES_API double dot(const Vector& lhs, const Vector& rhs);\n\n/** Returns the sum of vector's values. */\nUTILITIES_API double sum(const Vector& vector);\n\n/** Returns the largest element of vector. */\nUTILITIES_API double maximum(const Vector& vector);\n\n/** Returns the smallest element of vector. */\nUTILITIES_API double minimum(const Vector& vector);\n\n/** Returns the mean of vector's values */\nUTILITIES_API double mean(const Vector& vector);\n\n/** Returns the sample variance of vector's values. */\nUTILITIES_API double variance(const Vector& vector);\n\n/** Returns the standard deviation of vector's values. */\nUTILITIES_API double stdDev(const Vector& vector);\n\n/** Returns std::function pointer to sum(const Vector&). */\nUTILITIES_API std::function<double (const Vector&)> sumVectorFunctor();\n\n/** Returns std::function pointer to maximum(const Vector&). */\nUTILITIES_API std::function<double (const Vector&)> maximumVectorFunctor();\n\n/** Returns std::function pointer to minimum(const Vector&). */\nUTILITIES_API std::function<double (const Vector&)> minimumVectorFunctor();\n\n/** Returns std::function pointer to mean(const Vector&). */\nUTILITIES_API std::function<double (const Vector&)> meanVectorFunctor();\n\n/** Returns std::function pointer to variance(const Vector&). */\nUTILITIES_API std::function<double (const Vector&)> varianceVectorFunctor();\n\n/** Returns std::function pointer to stdDev(const Vector&). */\nUTILITIES_API std::function<double (const Vector&)> stdDevVectorFunctor();\n\n/** Evaluates functor(vector). For use in SWIG bindings. */\nUTILITIES_API double evaluateDoubleFromVectorFunctor(\n    const std::function<double (const Vector&)>& functor,\n    const Vector& vector);\n\n//@}\n\n} // openstudio\n\n#endif //UTILITIES_DATA_VECTOR_HPP\n", "meta": {"hexsha": "78fcbecb89e99843e6b5878d075cb5e36c58d1e1", "size": 7936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/data/Vector.hpp", "max_stars_repo_name": "hellok-coder/OS-Testing", "max_stars_repo_head_hexsha": "e9e18ad9e99f709a3f992601ed8d2e0662175af4", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-12T02:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T02:07:03.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/data/Vector.hpp", "max_issues_repo_name": "hellok-coder/OS-Testing", "max_issues_repo_head_hexsha": "e9e18ad9e99f709a3f992601ed8d2e0662175af4", "max_issues_repo_licenses": ["blessing"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-04T23:30:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-04T23:30:45.000Z", "max_forks_repo_path": "openstudiocore/src/utilities/data/Vector.hpp", "max_forks_repo_name": "hellok-coder/OS-Testing", "max_forks_repo_head_hexsha": "e9e18ad9e99f709a3f992601ed8d2e0662175af4", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3661202186, "max_line_length": 125, "alphanum_fraction": 0.7124495968, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478896, "lm_q2_score": 0.026355355235963267, "lm_q1q2_score": 0.009282403080611441}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 15:06:30\n\n#ifndef lowMSSM_SLHA_IO_H\n#define lowMSSM_SLHA_IO_H\n\n#include \"lowMSSM_mass_eigenstates.hpp\"\n#include \"lowMSSM_model_slha.hpp\"\n#include \"lowMSSM_info.hpp\"\n#include \"lowMSSM_observables.hpp\"\n#include \"lowMSSM_physical.hpp\"\n#include \"problems.hpp\"\n#include \"spectrum_generator_problems.hpp\"\n#include \"standard_model_two_scale_model.hpp\"\n#include \"slha_io.hpp\"\n#include \"ckm.hpp\"\n#include \"ew_input.hpp\"\n#include \"lowe.h\"\n\n#include <Eigen/Core>\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp>\n\n#define Pole(p) physical.p\n#define PHYSICAL(p) model.get_physical().p\n#define PHYSICAL_SLHA(p) model.get_physical_slha().p\n#define LOCALPHYSICAL(p) physical.p\n#define MODEL model\n#define MODELPARAMETER(p) model.get_##p()\n#define EXTRAPARAMETER(p) model.get_##p()\n#define OBSERVABLES observables\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define SCALES(p) scales.p\n\nnamespace flexiblesusy {\n\nstruct lowMSSM_input_parameters;\nclass Spectrum_generator_settings;\n\ntemplate <class T>\nclass lowMSSM;\n\nstruct lowMSSM_scales {\n   double HighScale{0.}, SUSYScale{0.}, LowScale{0.};\n   double pole_mass_scale{0.};\n};\n\nclass lowMSSM_slha_io {\npublic:\n   lowMSSM_slha_io();\n\n   void clear();\n\n   void fill(softsusy::QedQcd& qedqcd) const { slha_io.fill(qedqcd); }\n   void fill(lowMSSM_input_parameters&) const;\n   void fill(lowMSSM_mass_eigenstates&) const;\n   template <class Model> void fill(lowMSSM_slha<Model>&) const;\n   void fill(Physical_input&) const;\n   void fill(Spectrum_generator_settings&) const;\n   double get_parameter_output_scale() const;\n   const SLHA_io& get_slha_io() const { return slha_io; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   void set_block(const std::string& str, SLHA_io::Position position = SLHA_io::back) { slha_io.set_block(str, position); }\n   void set_blocks(const std::vector<std::string>& vec, SLHA_io::Position position = SLHA_io::back) { slha_io.set_blocks(vec, position); }\n   template <class Model> void set_extra(const lowMSSM_slha<Model>&, const lowMSSM_scales&, const lowMSSM_observables&);\n   void set_input(const lowMSSM_input_parameters&);\n   void set_modsel(const SLHA_io::Modsel&);\n   void set_physical_input(const Physical_input&);\n   void set_settings(const Spectrum_generator_settings&);\n   void set_sminputs(const softsusy::QedQcd&);\n   template <class... Ts> void set_spectrum(const std::tuple<Ts...>&);\n   template <class Model> void set_spectrum(const lowMSSM_slha<Model>&);\n   template <class T> void set_spectrum(const lowMSSM<T>&);\n   void set_spectrum(const standard_model::Standard_model& m) { slha_io.set_spectrum(m); }\n   void set_spinfo(const Spectrum_generator_problems&);\n   void set_spinfo(const Problems&);\n   void set_spinfo(const std::vector<std::string>&, const std::vector<std::string>&);\n   void set_print_imaginary_parts_of_majorana_mixings(bool);\n   void write_to(const std::string&) const;\n   void write_to_file(const std::string& file_name) const { slha_io.write_to_file(file_name); }\n   void write_to_stream(std::ostream& ostr = std::cout) const { slha_io.write_to_stream(ostr); }\n\n   static void fill_minpar_tuple(lowMSSM_input_parameters&, int, double);\n   static void fill_extpar_tuple(lowMSSM_input_parameters&, int, double);\n   static void fill_imminpar_tuple(lowMSSM_input_parameters&, int, double);\n   static void fill_imextpar_tuple(lowMSSM_input_parameters&, int, double);\n\n   template <class Model>\n   static void fill_slhaea(SLHAea::Coll&, const lowMSSM_slha<Model>&, const softsusy::QedQcd&, const lowMSSM_scales&, const lowMSSM_observables&);\n\n   template <class Model>\n   static SLHAea::Coll fill_slhaea(const lowMSSM_slha<Model>&, const softsusy::QedQcd&, const lowMSSM_scales&, const lowMSSM_observables&);\n\nprivate:\n   SLHA_io slha_io; ///< SLHA io class\n   bool print_imaginary_parts_of_majorana_mixings;\n\n   void set_extpar(const lowMSSM_input_parameters&);\n   void set_imminpar(const lowMSSM_input_parameters&);\n   void set_imextpar(const lowMSSM_input_parameters&);\n   void set_minpar(const lowMSSM_input_parameters&);\n   void set_mass(const lowMSSM_physical&, bool);\n   void set_mixing_matrices(const lowMSSM_physical&, bool);\n   template <class Model> void set_model_parameters(const lowMSSM_slha<Model>&);\n   void set_ckm(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   void set_pmns(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   double read_scale() const;\n   void fill_drbar_parameters(lowMSSM_mass_eigenstates&) const;\n   void fill_physical(lowMSSM_physical&) const;\n};\n\n/**\n * Reads DR-bar parameters, pole masses and mixing matrices from a\n * SLHA output file.\n */\ntemplate <class Model>\nvoid lowMSSM_slha_io::fill(lowMSSM_slha<Model>& model) const\n{\n   fill(static_cast<lowMSSM_mass_eigenstates&>(model));\n   fill_physical(model.get_physical_slha());\n}\n\ntemplate <class Model>\nvoid lowMSSM_slha_io::fill_slhaea(\n   SLHAea::Coll& slhaea, const lowMSSM_slha<Model>& model,\n   const softsusy::QedQcd& qedqcd, const lowMSSM_scales& scales,\n   const lowMSSM_observables& observables)\n{\n   lowMSSM_slha_io slha_io;\n   const lowMSSM_input_parameters& input = model.get_input();\n   const auto& problems = model.get_problems();\n   const bool error = problems.have_problem();\n\n   slha_io.set_spinfo(problems);\n   slha_io.set_sminputs(qedqcd);\n   slha_io.set_input(input);\n   if (!error) {\n      slha_io.set_spectrum(model);\n      slha_io.set_extra(model, scales, observables);\n   }\n\n   slhaea = slha_io.get_slha_io().get_data();\n}\n\ntemplate <class Model>\nSLHAea::Coll lowMSSM_slha_io::fill_slhaea(\n   const lowMSSM_slha<Model>& model, const softsusy::QedQcd& qedqcd,\n   const lowMSSM_scales& scales, const lowMSSM_observables& observables)\n{\n   SLHAea::Coll slhaea;\n   lowMSSM_slha_io::fill_slhaea(slhaea, model, qedqcd, scales, observables);\n\n   return slhaea;\n}\n\n/**\n * Stores the model (DR-bar) parameters in the SLHA object.\n *\n * @param model model class\n */\ntemplate <class Model>\nvoid lowMSSM_slha_io::set_model_parameters(const lowMSSM_slha<Model>& model)\n{\n   {\n      std::ostringstream block;\n      block << \"Block gauge Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(g1) * 0.7745966692414834), \"g1 * 0.7745966692414834\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(g2)), \"g2\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(g3)), \"g3\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"Yu\", ToMatrix(MODELPARAMETER(Yu_slha)), \"Yu\", model.get_scale());\n   slha_io.set_block(\"Yd\", ToMatrix(MODELPARAMETER(Yd_slha)), \"Yd\", model.get_scale());\n   slha_io.set_block(\"Ye\", ToMatrix(MODELPARAMETER(Ye_slha)), \"Ye\", model.get_scale());\n   slha_io.set_block(\"Te\", MODELPARAMETER(TYe_slha), \"TYe\", model.get_scale());\n   slha_io.set_block(\"Td\", MODELPARAMETER(TYd_slha), \"TYd\", model.get_scale());\n   slha_io.set_block(\"Tu\", MODELPARAMETER(TYu_slha), \"TYu\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block HMIX Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(Mu)), \"Mu\")\n            << FORMAT_ELEMENT(101, (MODELPARAMETER(BMu)), \"BMu\")\n            << FORMAT_ELEMENT(102, (MODELPARAMETER(vd)), \"vd\")\n            << FORMAT_ELEMENT(103, (MODELPARAMETER(vu)), \"vu\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"MSQ2\", MODELPARAMETER(mq2_slha), \"mq2\", model.get_scale());\n   slha_io.set_block(\"MSE2\", MODELPARAMETER(me2_slha), \"me2\", model.get_scale());\n   slha_io.set_block(\"MSL2\", MODELPARAMETER(ml2_slha), \"ml2\", model.get_scale());\n   slha_io.set_block(\"MSU2\", MODELPARAMETER(mu2_slha), \"mu2\", model.get_scale());\n   slha_io.set_block(\"MSD2\", MODELPARAMETER(md2_slha), \"md2\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block MSOFT Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(21, (MODELPARAMETER(mHd2)), \"mHd2\")\n            << FORMAT_ELEMENT(22, (MODELPARAMETER(mHu2)), \"mHu2\")\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(MassB)), \"MassB\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(MassWB)), \"MassWB\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(MassG)), \"MassG\")\n      ;\n      slha_io.set_block(block);\n   }\n\n   {\n      std::ostringstream block;\n      block << \"Block Phases Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (Re(MODELPARAMETER(PhaseGlu))), \"Re(PhaseGlu)\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block IMPhases Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (Im(MODELPARAMETER(PhaseGlu))), \"Im(PhaseGlu)\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Writes extra SLHA blocks\n *\n * @param model model class\n * @param scales struct of boundary condition scales\n * @param observables struct of observables\n */\ntemplate <class Model>\nvoid lowMSSM_slha_io::set_extra(\n   const lowMSSM_slha<Model>& model, const lowMSSM_scales& scales,\n   const lowMSSM_observables& observables)\n{\n   const lowMSSM_physical physical(model.get_physical_slha());\n\n   {\n      std::ostringstream block;\n      block << \"Block FlexibleSUSYOutput\" << '\\n'\n            << FORMAT_ELEMENT(0, (SCALES(HighScale)), \"HighScale\")\n            << FORMAT_ELEMENT(1, (SCALES(SUSYScale)), \"SUSYScale\")\n            << FORMAT_ELEMENT(2, (SCALES(LowScale)), \"LowScale\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block FlexibleSUSYLowEnergy Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(21, (OBSERVABLES.a_muon), \"Delta(g-2)_muon/2 FlexibleSUSY\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block EFFHIGGSCOUPLINGS\" << '\\n'\n            << FORMAT_RANK_THREE_TENSOR(25, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon(0))), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(35, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon(1))), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(25, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon(0))), \"Abs(effective H-Gluon-Gluon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(35, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon(1))), \"Abs(effective H-Gluon-Gluon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(36, 22, 22, (Abs(OBSERVABLES.eff_cp_pseudoscalar_photon_photon)), \"Abs(effective A-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(36, 21, 21, (Abs(OBSERVABLES.eff_cp_pseudoscalar_gluon_gluon)), \"Abs(effective A-Gluon-Gluon coupling)\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block ALPHA\" << '\\n'\n            << FORMAT_NUMBER((ArcSin(Pole(ZH(1,1)))), \"ArcSin(Pole(ZH(2,2)))\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block HMIX Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(Mu)), \"Mu\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(vu)/MODELPARAMETER(vd)), \"vu/vd\")\n            << FORMAT_ELEMENT(3, (Sqrt(Sqr(MODELPARAMETER(vd)) + Sqr(MODELPARAMETER(vu)))), \"Sqrt(Sqr(vd) + Sqr(vu))\")\n            << FORMAT_ELEMENT(4, (Sqr(MODELPARAMETER(MAh)(1))), \"Sqr(MAh(2))\")\n            << FORMAT_ELEMENT(101, (MODELPARAMETER(BMu)), \"BMu\")\n            << FORMAT_ELEMENT(102, (MODELPARAMETER(vd)), \"vd\")\n            << FORMAT_ELEMENT(103, (MODELPARAMETER(vu)), \"vu\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block Au Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_MIXING_MATRIX(1, 1, (MODELPARAMETER(TYu)(0,0)/MODELPARAMETER(Yu)(0,0)), \"TYu(1,1)/Yu(1,1)\")\n            << FORMAT_MIXING_MATRIX(2, 2, (MODELPARAMETER(TYu)(1,1)/MODELPARAMETER(Yu)(1,1)), \"TYu(2,2)/Yu(2,2)\")\n            << FORMAT_MIXING_MATRIX(3, 3, (MODELPARAMETER(TYu)(2,2)/MODELPARAMETER(Yu)(2,2)), \"TYu(3,3)/Yu(3,3)\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block Ad Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_MIXING_MATRIX(1, 1, (MODELPARAMETER(TYd)(0,0)/MODELPARAMETER(Yd)(0,0)), \"TYd(1,1)/Yd(1,1)\")\n            << FORMAT_MIXING_MATRIX(2, 2, (MODELPARAMETER(TYd)(1,1)/MODELPARAMETER(Yd)(1,1)), \"TYd(2,2)/Yd(2,2)\")\n            << FORMAT_MIXING_MATRIX(3, 3, (MODELPARAMETER(TYd)(2,2)/MODELPARAMETER(Yd)(2,2)), \"TYd(3,3)/Yd(3,3)\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block Ae Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_MIXING_MATRIX(1, 1, (MODELPARAMETER(TYe)(0,0)/MODELPARAMETER(Ye)(0,0)), \"TYe(1,1)/Ye(1,1)\")\n            << FORMAT_MIXING_MATRIX(2, 2, (MODELPARAMETER(TYe)(1,1)/MODELPARAMETER(Ye)(1,1)), \"TYe(2,2)/Ye(2,2)\")\n            << FORMAT_MIXING_MATRIX(3, 3, (MODELPARAMETER(TYe)(2,2)/MODELPARAMETER(Ye)(2,2)), \"TYe(3,3)/Ye(3,3)\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block MSOFT Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(MassB)), \"MassB\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(MassWB)), \"MassWB\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(MassG)), \"MassG\")\n            << FORMAT_ELEMENT(21, (MODELPARAMETER(mHd2)), \"mHd2\")\n            << FORMAT_ELEMENT(22, (MODELPARAMETER(mHu2)), \"mHu2\")\n            << FORMAT_ELEMENT(31, (SignedAbsSqrt(MODELPARAMETER(ml2)(0,0))), \"SignedAbsSqrt(ml2(1,1))\")\n            << FORMAT_ELEMENT(32, (SignedAbsSqrt(MODELPARAMETER(ml2)(1,1))), \"SignedAbsSqrt(ml2(2,2))\")\n            << FORMAT_ELEMENT(33, (SignedAbsSqrt(MODELPARAMETER(ml2)(2,2))), \"SignedAbsSqrt(ml2(3,3))\")\n            << FORMAT_ELEMENT(34, (SignedAbsSqrt(MODELPARAMETER(me2)(0,0))), \"SignedAbsSqrt(me2(1,1))\")\n            << FORMAT_ELEMENT(35, (SignedAbsSqrt(MODELPARAMETER(me2)(1,1))), \"SignedAbsSqrt(me2(2,2))\")\n            << FORMAT_ELEMENT(36, (SignedAbsSqrt(MODELPARAMETER(me2)(2,2))), \"SignedAbsSqrt(me2(3,3))\")\n            << FORMAT_ELEMENT(41, (SignedAbsSqrt(MODELPARAMETER(mq2)(0,0))), \"SignedAbsSqrt(mq2(1,1))\")\n            << FORMAT_ELEMENT(42, (SignedAbsSqrt(MODELPARAMETER(mq2)(1,1))), \"SignedAbsSqrt(mq2(2,2))\")\n            << FORMAT_ELEMENT(43, (SignedAbsSqrt(MODELPARAMETER(mq2)(2,2))), \"SignedAbsSqrt(mq2(3,3))\")\n            << FORMAT_ELEMENT(44, (SignedAbsSqrt(MODELPARAMETER(mu2)(0,0))), \"SignedAbsSqrt(mu2(1,1))\")\n            << FORMAT_ELEMENT(45, (SignedAbsSqrt(MODELPARAMETER(mu2)(1,1))), \"SignedAbsSqrt(mu2(2,2))\")\n            << FORMAT_ELEMENT(46, (SignedAbsSqrt(MODELPARAMETER(mu2)(2,2))), \"SignedAbsSqrt(mu2(3,3))\")\n            << FORMAT_ELEMENT(47, (SignedAbsSqrt(MODELPARAMETER(md2)(0,0))), \"SignedAbsSqrt(md2(1,1))\")\n            << FORMAT_ELEMENT(48, (SignedAbsSqrt(MODELPARAMETER(md2)(1,1))), \"SignedAbsSqrt(md2(2,2))\")\n            << FORMAT_ELEMENT(49, (SignedAbsSqrt(MODELPARAMETER(md2)(2,2))), \"SignedAbsSqrt(md2(3,3))\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices of\n * all given models in the SLHA object.\n *\n * @todo Use generic lambda instead of Set_spectrum in C++14\n *\n * @param models model classes\n */\ntemplate <class... Ts>\nvoid lowMSSM_slha_io::set_spectrum(const std::tuple<Ts...>& models)\n{\n   Set_spectrum<lowMSSM_slha_io> ss(this);\n   boost::fusion::for_each(models, ss);\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in BPMZ convention\n */\ntemplate <class T>\nvoid lowMSSM_slha_io::set_spectrum(const lowMSSM<T>& model)\n{\n   set_spectrum(lowMSSM_slha<lowMSSM<T> >(model));\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in SLHA convention\n */\ntemplate <class Model>\nvoid lowMSSM_slha_io::set_spectrum(const lowMSSM_slha<Model>& model)\n{\n   const lowMSSM_physical physical(model.get_physical_slha());\n   const bool write_sm_masses = model.do_calculate_sm_pole_masses();\n\n   set_model_parameters(model);\n   set_mass(physical, write_sm_masses);\n   set_mixing_matrices(physical, write_sm_masses);\n\n   if (slha_io.get_modsel().quark_flavour_violated)\n      set_ckm(model.get_ckm_matrix(), model.get_scale());\n\n   if (slha_io.get_modsel().lepton_flavour_violated)\n      set_pmns(model.get_pmns_matrix(), model.get_scale());\n}\n\n} // namespace flexiblesusy\n\n#undef Pole\n#undef PHYSICAL\n#undef PHYSICAL_SLHA\n#undef LOCALPHYSICAL\n#undef MODEL\n#undef MODELPARAMETER\n#undef EXTRAPARAMETER\n#undef OBSERVABLES\n#undef LowEnergyConstant\n#undef SCALES\n\n#endif\n", "meta": {"hexsha": "6d995878b5675cbc99cdc3935612e8d343214f52", "size": 17793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/lowMSSM/lowMSSM_slha_io.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/lowMSSM/lowMSSM_slha_io.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/lowMSSM/lowMSSM_slha_io.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.5724299065, "max_line_length": 148, "alphanum_fraction": 0.678412859, "num_tokens": 5239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.026355354184432096, "lm_q1q2_score": 0.009282403068670408}}
{"text": "/* Copyright (C) 2012-2015 David Bond, All Rights Reserved */\n\n#include \"COCOMOII.hpp\"\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <iomanip>\n\nnamespace mspe {\n\nnamespace team {\n  static const std::string nominal = \"nominal\";\n  static const std::string expert = \"expert\";\n  static const std::string good = \"good\";\n}\n\nnamespace defaults {\n  static const std::string team = team::nominal;\n  static constexpr float salary = 100000;\n  static constexpr float overhead = 1.4;\n}\n\nclass Arguments {\n\n  public:\n\n    Arguments() = default;\n\n    virtual ~Arguments() = default;\n\n    Arguments(Arguments&&) = delete;\n\n    Arguments& operator=(Arguments&&) = delete;\n\n    Arguments(const Arguments&) = delete;\n\n    Arguments& operator=(const Arguments&) = delete;\n\n    bool parse(int argc, char* argv[])\n    {\n      boost::program_options::options_description options;\n\n      options.add_options()\n        (\"help\", \"outputs usage\")\n        (\"sloc\", boost::program_options::value<float>(&sloc)->required(),\n           \"total source lines of code\")\n        (\"team\", boost::program_options::value<std::string>(&team)->\n           default_value(defaults::team), \"team skill level\")\n        (\"salary\", boost::program_options::value<float>(&salary)->\n           default_value(defaults::salary), \"team average salary\")\n        (\"overhead\", boost::program_options::value<float>(&overhead)->\n           default_value(defaults::overhead),\n           \"team salary overhead multiplier\");\n\n      try {\n        boost::program_options::variables_map vm;\n        auto parsed = boost::program_options::parse_command_line(argc, argv,\n                                                                 options);\n        boost::program_options::store(parsed, vm);\n\n        if (vm.count(\"help\")) {\n          std::cout << options << std::endl;\n          return false;\n        }\n        boost::program_options::notify(vm);\n      \n        return true;\n      } catch(const boost::program_options::error& e) {\n        std::cerr << \"invalid argument: \" << e.what() << std::endl\n                  << options << std::endl;\n        throw;\n      }\n    }\n\n    std::string team;\n\n    float sloc;\n\n    float salary;\n\n    float overhead;\n};\n\n} // namespace mspe\n\n/* A simple program which implements an api to use the COCOMO II model. */\nint main(int argc, char* argv[]) {\n  try {\n    mspe::Arguments args;\n\n    if (!args.parse(argc, argv)) {\n      return EXIT_FAILURE;\n    }\n\n    mspe::COCOMOII c;\n    if(args.team == mspe::team::good) {\n      c.setEAF(mspe::RELY, mspe::HIGH);\n      c.setEAF(mspe::RUSE, mspe::HIGH);\n      c.setEAF(mspe::CPLX, mspe::VERY_HIGH ) ;\n      c.setEAF(mspe::TIME, mspe::HIGH);\n      c.setEAF(mspe::PVOL, mspe::LOW);\n    } else if(args.team == mspe::team::expert) {\n      c.setEAF(mspe::SCED, mspe::NOMINAL);\n      c.setEAF(mspe::RELY, mspe::NOMINAL);\n      c.setEAF(mspe::DATA, mspe::NOMINAL);\n      c.setEAF(mspe::RUSE, mspe::NOMINAL);\n      c.setEAF(mspe::DOCU, mspe::NOMINAL);\n      c.setEAF(mspe::CPLX, mspe::NOMINAL);\n      c.setEAF(mspe::TIME, mspe::NOMINAL);\n      c.setEAF(mspe::STOR, mspe::NOMINAL);\n      c.setEAF(mspe::PVOL, mspe::NOMINAL);\n      c.setEAF(mspe::ACAP, mspe::VERY_HIGH);\n      c.setEAF(mspe::PCAP, mspe::VERY_HIGH);\n      c.setEAF(mspe::PCON, mspe::VERY_HIGH);\n      c.setEAF(mspe::AEXP, mspe::VERY_HIGH);\n      c.setEAF(mspe::PEXP, mspe::VERY_HIGH);\n      c.setEAF(mspe::LTEX, mspe::VERY_HIGH);\n      c.setEAF(mspe::TOOL, mspe::VERY_HIGH);\n      c.setEAF(mspe::SITE, mspe::EXTRA_HIGH);\n      c.setSF(mspe::PREC, mspe::NOMINAL);\n      c.setSF(mspe::FLEX, mspe::EXTRA_HIGH);\n      c.setSF(mspe::ARCH, mspe::EXTRA_HIGH);\n      c.setSF(mspe::COHE, mspe::EXTRA_HIGH);\n      c.setSF(mspe::MATU, mspe::EXTRA_HIGH);\n    } else if(args.team == mspe::team::nominal) {\n      // defaults already set\n    } else {\n      std::cerr << \"unknown team skill level\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    c.setSLOC(args.sloc/1000.0);\n    c.setOverhead(args.overhead);\n    c.setSalary(args.salary);\n\n    std::cout << std::fixed << std::setprecision(2)\n              << \"Person Months: \" << c.EFFORT()\n              << std::endl\n              << std::fixed << std::setprecision(0)\n              << \"Cost: $\" << c.COST()\n              << std::endl\n              << \"Cost & Overhead: $\" << c.COSTANDOVERHEAD()\n              << std::endl\n              << \"Cost & Overhead Per LSLOC: $\"\n              << c.COSTANDOVERHEAD()/args.sloc\n              << std::endl;\n\n    return EXIT_SUCCESS;\n  } catch (...) {\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "fd456127ee6bf42bf2bb6acc6175ce710ca14df4", "size": 4552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/COCOMOIIApi.cpp", "max_stars_repo_name": "Mokon/mspe", "max_stars_repo_head_hexsha": "e25def66b9ce9accae908d7f5d954a64106661f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/COCOMOIIApi.cpp", "max_issues_repo_name": "Mokon/mspe", "max_issues_repo_head_hexsha": "e25def66b9ce9accae908d7f5d954a64106661f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/COCOMOIIApi.cpp", "max_forks_repo_name": "Mokon/mspe", "max_forks_repo_head_hexsha": "e25def66b9ce9accae908d7f5d954a64106661f9", "max_forks_repo_licenses": ["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.9473684211, "max_line_length": 76, "alphanum_fraction": 0.5817223199, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845759920814681, "lm_q2_score": 0.032589742651931514, "lm_q1q2_score": 0.009274258346853146}}
{"text": "/* Copyright 2017 - BSD-3-Clause\n *\n * Copyright Holder (alphabetical):\n *\n * Cramer, Simon\n *\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 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/*\n * @file QuantityOfInterest.cpp\n * @author Cramer\n * @date 11 May 2018\n * @brief This file belongs to the SABCEMM projekt. See github.com/SABCEMM/SABCEMM\n */\n\n#include \"QuantityOfInterest.h\"\n#include \"QoiCalculatorExcessKurtosis.h\"\n#include \"QoiCalculatorKurtosis.h\"\n#include \"QoiCalculatorMaximum.h\"\n#include \"QoiCalculatorMean.h\"\n#include \"QoiCalculatorMinimum.h\"\n#include \"QoiCalculatorMoment.h\"\n#include \"QoiCalculatorQuantile.h\"\n#include \"QoiCalculatorSkew.h\"\n#include \"QoiCalculatorVariance.h\"\n#include \"QoiCalculatorFull.h\"\n#include \"../Writer/Writer.h\"\n#include \"QoiCalculatorHill.h\"\n#include \"QoiCalculatorAutocorrelation.h\"\n\n#include <iostream>\n\n#include <boost/assign.hpp>\n\nusing namespace std;\n\nconst std::map<std::string, QuantityOfInterest::Method> QuantityOfInterest::stringToMethod =\n        boost::assign::map_list_of\n                (\"full\", QuantityOfInterest::Method::full)\n                (\"mean\", QuantityOfInterest::Method::mean)\n                (\"variance\", QuantityOfInterest::Method::variance)\n                (\"kurtosis\", QuantityOfInterest::Method::kurtosis)\n                (\"excesskurtosis\", QuantityOfInterest::Method::excessKurtosis)\n                (\"moment\", QuantityOfInterest::Method::moment)\n                (\"skew\", QuantityOfInterest::Method::skew)\n                (\"minimum\", QuantityOfInterest::Method::minimum)\n                (\"maximum\", QuantityOfInterest::Method::maximum)\n                (\"quantile\", QuantityOfInterest::Method::quantile)\n                (\"hill\", QuantityOfInterest::Method::hill)\n                (\"autocorrelation\", QuantityOfInterest::Method::autocorrelation);\nconst std::map<QuantityOfInterest::Method, std::string> QuantityOfInterest::methodToString =\n        boost::assign::map_list_of\n                (QuantityOfInterest::Method::full, \"full\")\n                (QuantityOfInterest::Method::mean, \"mean\")\n                (QuantityOfInterest::Method::variance, \"variance\")\n                (QuantityOfInterest::Method::kurtosis, \"kurtosis\")\n                (QuantityOfInterest::Method::excessKurtosis, \"excesskurtosis\")\n                (QuantityOfInterest::Method::moment, \"moment\")\n                (QuantityOfInterest::Method::skew, \"skew\")\n                (QuantityOfInterest::Method::minimum, \"minimum\")\n                (QuantityOfInterest::Method::maximum, \"maximum\")\n                (QuantityOfInterest::Method::quantile, \"quantile\")\n                (QuantityOfInterest::Method::hill, \"hill\")\n                (QuantityOfInterest::Method::autocorrelation, \"autocorrelation\");\nconst std::map<std::string, QuantityOfInterest::Quantity> QuantityOfInterest::stringToQuantity =\n        boost::assign::map_list_of\n                (\"cash\", QuantityOfInterest::Quantity::cash)\n                (\"stock\", QuantityOfInterest::Quantity::stock)\n                (\"embgamma\", QuantityOfInterest::Quantity::embGamma)\n                (\"excessdemand\", QuantityOfInterest::Quantity::excessDemand)\n                (\"fwshares_chartist\", QuantityOfInterest::Quantity::fwSharesChartist)\n                (\"fwshares_fundamentalist\", QuantityOfInterest::Quantity::fwSharesFundamentalist)\n                (\"harrask\", QuantityOfInterest::Quantity::harrasK)\n                (\"price\", QuantityOfInterest::Quantity::price)\n                (\"switchableshares\", QuantityOfInterest::Quantity::switchableShares)\n                (\"wealth\", QuantityOfInterest::Quantity::wealth)\n                (\"return\", QuantityOfInterest::Quantity::return_)\n                (\"absreturn\", QuantityOfInterest::Quantity::absReturn)\n                (\"logreturn\", QuantityOfInterest::Quantity::logReturn)\n                (\"abslogreturn\", QuantityOfInterest::Quantity::absLogReturn);\n\nconst std::map<QuantityOfInterest::Quantity, std::string> QuantityOfInterest::quantityToString =\n        boost::assign::map_list_of\n                (QuantityOfInterest::Quantity::cash, \"cash\")\n                (QuantityOfInterest::Quantity::stock, \"stock\")\n                (QuantityOfInterest::Quantity::embGamma, \"embgamma\")\n                (QuantityOfInterest::Quantity::excessDemand, \"excessdemand\")\n                (QuantityOfInterest::Quantity::fwSharesChartist, \"fwshares_chartist\")\n                (QuantityOfInterest::Quantity::fwSharesFundamentalist, \"fwshares_fundamentalist\")\n                (QuantityOfInterest::Quantity::harrasK, \"harrask\")\n                (QuantityOfInterest::Quantity::price, \"price\")\n                (QuantityOfInterest::Quantity::switchableShares, \"switchableshares\")\n                (QuantityOfInterest::Quantity::wealth, \"wealth\")\n                (QuantityOfInterest::Quantity::return_, \"return\")\n                (QuantityOfInterest::Quantity::absReturn, \"absreturn\")\n                (QuantityOfInterest::Quantity::logReturn, \"logreturn\")\n                (QuantityOfInterest::Quantity::absLogReturn, \"abslogreturn\");\n\nQuantityOfInterest::QuantityOfInterest(QuantityOfInterest::Quantity quantity,\n                                       DataItemCollector *dataItemCollector) :\n        dataItemCollector(dataItemCollector), quantity(quantity) {\n    calculators.clear();\n    groupToTrack = -1;\n    name = \"NONE\";\n}\n\nQuantityOfInterest::QuantityOfInterest(std::string quantity,\n                                       DataItemCollector *dataItemCollector) :\n        QuantityOfInterest(\n                QuantityOfInterest::stringToQuantity.at(quantity),\n                dataItemCollector) {\n\n}\n\nQuantityOfInterest::~QuantityOfInterest() {\n    for (auto& calculator: calculators) {\n        delete calculator;\n        calculator = nullptr;\n    }\n    calculators.clear();\n}\n\nQuantityOfInterest *QuantityOfInterest::factory(DataItemCollector *dataItemCollector, Input &QOIinput) {\n    std::string type = QOIinput.getName();\n    std::string name_ = QOIinput.getName();\n    if (QOIinput(\"quantity\")){\n        type = QOIinput[\"quantity\"].getString();\n    }\n\n    QuantityOfInterest::Quantity quantity;\n    try {\n        quantity = QuantityOfInterest::stringToQuantity.at(type);\n    }\n    catch (std::out_of_range &e) {\n        throw(\"QoI unknown!\");\n    }\n\n    QuantityOfInterest *quantityOfInterest = new QuantityOfInterest(type, dataItemCollector);\n\n    quantityOfInterest->setName(name_);\n    std::vector<QoiCalculator *> calculators;\n    for (auto& method_: QOIinput.getChildren()) {\n        QuantityOfInterest::Method method;\n        try {\n            method = QuantityOfInterest::stringToMethod.at(method_.getName());\n        }\n        catch (std::out_of_range &e) {\n            continue;\n        }\n\n        QoiCalculator *calculator = nullptr;\n        switch (method) {\n            case QuantityOfInterest::Method::mean:\n                calculator = new QoiCalculatorMean();\n                break;\n            case QuantityOfInterest::Method::variance:\n                calculator = new QoiCalculatorVariance();\n                break;\n            case QuantityOfInterest::Method::kurtosis:\n                calculator = new QoiCalculatorKurtosis();\n                break;\n            case QuantityOfInterest::Method::excessKurtosis:\n                calculator = new QoiCalculatorExcessKurtosis();\n                break;\n            case QuantityOfInterest::Method::moment:\n                if(method_.hasChildren()){\n                    for(auto& m: method_.getChildren()){\n                        calculator = new QoiCalculatorMoment(m.getInt());\n                        calculators.push_back(calculator);\n                    }\n                    continue;\n                }\n                else{\n                    calculator = new QoiCalculatorMoment(method_.getInt());\n                }\n                break;\n            case QuantityOfInterest::Method::skew:\n                calculator = new QoiCalculatorSkew();\n                break;\n            case QuantityOfInterest::Method::minimum:\n                calculator = new QoiCalculatorMinimum();\n                break;\n            case QuantityOfInterest::Method::maximum:\n                calculator = new QoiCalculatorMaximum();\n                break;\n            case QuantityOfInterest::Method::quantile:\n                calculator = new QoiCalculatorQuantile();\n                break;\n            case QuantityOfInterest::Method::full:\n                calculator = new QoiCalculatorFull();\n                break;\n            case QuantityOfInterest::Method::hill:\n                if(method_.hasChildren()){\n                    for(auto& m: method_.getChildren()){\n                        calculator = new QoiCalculatorHill(m.getDouble());\n                        calculators.push_back(calculator);\n                    }\n                    continue;\n                }\n                else {\n                    calculator = new QoiCalculatorHill(method_.getDouble());\n                }\n                break;\n            case QuantityOfInterest::Method::autocorrelation:\n                if(method_.hasChildren()){\n                    for(auto& m: method_.getChildren()){\n                        calculator = new QoiCalculatorAutocorrelation(m.getSizeT());\n                        calculators.push_back(calculator);\n                    }\n                    continue;\n                }\n                else {\n                    calculator = new QoiCalculatorAutocorrelation(method_.getSizeT());\n                }\n                break;\n            default:\n                cerr << \"Quantity Of Interest \" << QuantityOfInterest::methodToString.at(method)\n                     << \" not implemented yet. It's ignored.\" << endl;\n                break;\n        }\n        calculators.push_back(calculator);\n\n    }\n\n    quantityOfInterest->setCalculators(calculators);\n\n    return quantityOfInterest;\n}\n\nvoid QuantityOfInterest::setCalculators(std::vector<QoiCalculator *> calculators) {\n    this->calculators = calculators;\n}\n\nvoid QuantityOfInterest::calculateQoI() {\n    std::vector<std::vector<double>>* data = dataItemCollector->getData();\n\n    switch (quantity) {\n        case QuantityOfInterest::Quantity::logReturn:\n            assert(data->size() == 1);\n            assert(data->at(0).size() > 1);\n\n            for(size_t i = 0; i < data->at(0).size()-1; i++){\n                // equivalent to log(data->at(0).at(i+1)) - log(data->at(0).at(i) ) but only one expensive logarithm needs to be computed\n                data->at(0).at(i) = log(data->at(0).at(i+1) / data->at(0).at(i) );\n            }\n\n            // Delete last element. We can't compute return here because we are missing data.\n            data->at(0).pop_back();\n            break;\n        case QuantityOfInterest::Quantity::absLogReturn:\n            assert(data->size() == 1);\n            assert(data->at(0).size() > 1);\n\n            for(size_t i = 0; i < data->at(0).size()-1; i++){\n                data->at(0).at(i) = abs( log( data->at(0).at(i+1) / data->at(0).at(i) ) );\n            }\n\n            // Delete last element. We can't compute return here because we are missing data.\n            data->at(0).pop_back();\n            break;\n        case QuantityOfInterest::Quantity::return_:\n            assert(data->size() == 1);\n            assert(data->at(0).size() > 1);\n\n            for(size_t i = 0; i < data->at(0).size()-1; i++){\n                data->at(0).at(i) = ( data->at(0).at(i+1) / data->at(0).at(i) ) -1 ;\n            }\n\n            // Delete last element. We can't compute return here because we are missing data.\n            data->at(0).pop_back();\n            break;\n        case QuantityOfInterest::Quantity::absReturn:\n            assert(data->size() == 1);\n            assert(data->at(0).size() > 1);\n\n            for(size_t i = 0; i < data->at(0).size()-1; i++){\n                data->at(0).at(i) = abs( data->at(0).at(i+1) / data->at(0).at(i) -1 );\n            }\n\n            // Delete last element. We can't compute return here because we are missing data.\n            data->at(0).pop_back();\n            break;\n        default:\n            assert(data->size() > 0);\n            assert(data->at(0).size() > 0);\n\n    }\n\n    for (auto calculator : calculators) {\n        calculator->calculate(data);\n    }\n    dataItemCollector->clearData();\n}\n\nvoid QuantityOfInterest::write(Writer* writer){\n    for(auto calculator : calculators){\n        std::string method_name = QuantityOfInterest::methodToString.at(calculator->getMethod());\n\n        if (calculator->getMethod() == QuantityOfInterest::Method::hill ||\n            calculator->getMethod() == QuantityOfInterest::Method::autocorrelation ||\n            calculator->getMethod() == QuantityOfInterest::Method::moment){\n            method_name += \"_\"+std::to_string(calculator->getParameter());\n        }\n        writer->addQoI(method_name, quantity, groupToTrack,\n                calculator->getResult(), this->name);\n    }\n}\n\nconst string &QuantityOfInterest::getName() const {\n    return name;\n}\n\nvoid QuantityOfInterest::setName(const string &name) {\n    this->name = name;\n}\n\nint QuantityOfInterest::getGroupToTrack() const {\n    return groupToTrack;\n}\n\nvoid QuantityOfInterest::setGroupToTrack(int groupToTrack) {\n    QuantityOfInterest::groupToTrack = groupToTrack;\n}\n", "meta": {"hexsha": "c2f075df4d273ff3df7bf449e8e4e77047ea6a52", "size": 14695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/QuantitiesOfInterest/QuantityOfInterest.cpp", "max_stars_repo_name": "SABCEMM/SABCEMM", "max_stars_repo_head_hexsha": "a87ea83b57a8a7d16591abe30e56db459e710a0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-01-08T13:38:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T05:39:26.000Z", "max_issues_repo_path": "src/QuantitiesOfInterest/QuantityOfInterest.cpp", "max_issues_repo_name": "SABCEMM/SABCEMM", "max_issues_repo_head_hexsha": "a87ea83b57a8a7d16591abe30e56db459e710a0e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/QuantitiesOfInterest/QuantityOfInterest.cpp", "max_forks_repo_name": "SABCEMM/SABCEMM", "max_forks_repo_head_hexsha": "a87ea83b57a8a7d16591abe30e56db459e710a0e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T13:39:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-08T13:39:00.000Z", "avg_line_length": 42.7180232558, "max_line_length": 137, "alphanum_fraction": 0.6103436543, "num_tokens": 3175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.024798162357733338, "lm_q1q2_score": 0.00927143300871462}}
{"text": "//=============================================================================================================\n/**\n* @file     sphere.cpp\n* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     April, 2016\n*\n* @section  LICENSE\n*\n* Copyright (C) 2016, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Implementation of the Sphere Class.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"sphere.h\"\n#include \"simplex_algorithm.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Dense>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// STL INCLUDES\n//=============================================================================================================\n\n#include <iostream>\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\nSphere::Sphere( const Vector3f& center, float radius )\n: m_center(center)\n, m_r(radius)\n{\n}\n\n\n//*************************************************************************************************************\n\nSphere Sphere::fit_sphere(const MatrixX3f& points)\n{\n    const VectorXf& x = points.col(0);\n    const VectorXf& y = points.col(1);\n    const VectorXf& z = points.col(2);\n\n    VectorXf point_means = points.colwise().mean();\n\n    VectorXf x_mean_free = x.array() - point_means(0);\n    VectorXf y_mean_free = y.array() - point_means(1);\n    VectorXf z_mean_free = z.array() - point_means(2);\n\n    Matrix3f A;\n    A << (x.cwiseProduct(x_mean_free)).mean(), 2*(x.cwiseProduct(y_mean_free)).mean(), 2*(x.cwiseProduct(z_mean_free)).mean(),\n                                            0,   (y.cwiseProduct(y_mean_free)).mean(), 2*(y.cwiseProduct(z_mean_free)).mean(),\n                                            0,                                      0,   (z.cwiseProduct(z_mean_free)).mean();\n\n    Matrix3f A_T = A.transpose();\n    A += A_T;\n\n    Vector3f b;\n    VectorXf sq_sum = x.array().pow(2)+y.array().pow(2)+z.array().pow(2);\n    b << (sq_sum.cwiseProduct(x_mean_free)).mean(),\n         (sq_sum.cwiseProduct(y_mean_free)).mean(),\n         (sq_sum.cwiseProduct(z_mean_free)).mean();\n\n    Vector3f center = A.ldlt().solve(b);\n\n    MatrixX3f tmp(points.rows(),3);\n    tmp.col(0) = x.array() - center(0);\n    tmp.col(1) = y.array() - center(1);\n    tmp.col(2) = z.array() - center(2);\n\n    float r = sqrt(tmp.array().pow(2).rowwise().sum().mean());\n\n    return Sphere(center, r);\n}\n\n\n//*************************************************************************************************************\n\nSphere Sphere::fit_sphere_simplex(const MatrixX3f& points, double simplex_size)\n{\n    VectorXf center;\n    float R;\n    fit_sphere_to_points( points, simplex_size, center, R);\n\n    return Sphere(center, R);\n}\n\n\n//*************************************************************************************************************\n\nbool Sphere::fit_sphere_to_points ( const MatrixXf &rr, float simplex_size, VectorXf &r0, float &R )\n{\n//    int   np = rr.rows();\n\n    /*\n    * Find the optimal sphere origin\n    */\n    fitUserRecNew user;\n    float      ftol            = 1e-5f;\n    int        max_eval        = 500;\n    int        report_interval = -1;\n    int        neval;\n    MatrixXf   init_simplex;\n    VectorXf   init_vals(4);\n\n    VectorXf   cm(3);\n    float      R0 = 0.1f;\n\n    user.rr = rr;\n\n    calculate_cm_ave_dist(rr, cm, R0);// [done]\n\n    init_simplex = make_initial_simplex( cm, simplex_size );\n\n    user.report = false;\n\n    for (int k = 0; k < 4; k++) {\n        init_vals[k] = fit_eval( static_cast<VectorXf>(init_simplex.row(k)), &user );\n    }\n\n    user.report = false;\n\n    //Start the minimization\n    if(!SimplexAlgorithm::simplex_minimize<float>(  init_simplex,   /* The initial simplex */\n                                                    init_vals,      /* Function values at the vertices */\n                                                    ftol,           /* Relative convergence tolerance */\n                                                    fit_eval,       /* The function to be evaluated */\n                                                    &user,          /* Data to be passed to the above function in each evaluation */\n                                                    max_eval,       /* Maximum number of function evaluations */\n                                                    neval,          /* Number of function evaluations */\n                                                    report_interval,/* How often to report (-1 = no_reporting) */\n                                                    report_func))   /* The function to be called when reporting */\n        return false;\n\n    r0 = init_simplex.row(0);\n    R = opt_rad(r0, &user);\n\n    return true;\n}\n\n\n//*************************************************************************************************************\n\nbool Sphere::report_func(int loop, const VectorXf &fitpar, double fval)\n{\n    /*\n    * Report periodically\n    */\n    const VectorXf& r0 = fitpar;\n\n    std::cout << \"loop: \" << loop << \"; r0: \" << 1000*r0[0] << \", r1: \" << 1000*r0[1] << \", r2: \" << 1000*r0[2] << \"; fval: \" << fval << std::endl;\n\n    return true;\n}\n\n\n//*************************************************************************************************************\n\nvoid Sphere::calculate_cm_ave_dist (const MatrixXf &rr, VectorXf &cm, float &avep)\n{\n    cm = rr.colwise().mean();\n    MatrixXf diff = rr.rowwise() - cm.transpose();\n    avep = diff.rowwise().norm().mean();\n}\n\n\n//*************************************************************************************************************\n\nMatrixXf Sphere::make_initial_simplex( const VectorXf &pars, float size )\n{\n    /*\n    * Make the initial tetrahedron\n    */\n    int npar = pars.size();\n\n    MatrixXf simplex = MatrixXf::Zero(npar+1,npar);\n\n    simplex.rowwise() += pars.transpose();\n\n    for (int k = 1; k < npar+1; k++) {\n        simplex(k,k-1) += size;\n    }\n\n    return simplex;\n}\n\n\n//*************************************************************************************************************\n\nfloat Sphere::fit_eval ( const VectorXf &fitpar, const void  *user_data)\n{\n    /*\n    * Calculate the cost function value\n    * Optimize for the radius inside here\n    */\n    const fitUserNew& user = (fitUserNew)user_data;\n    const VectorXf& r0 = fitpar;\n\n    float F;\n\n    MatrixXf diff = user->rr.rowwise() - r0.transpose();\n    VectorXf one = diff.rowwise().norm();\n\n    float sum = one.sum();\n    float sum2 = one.dot(one);\n\n    F = sum2 - sum*sum/user->rr.rows();\n\n    if(user->report)\n        std::cout << \"r0: \" << 1000*r0[0] << \", r1: \" << 1000*r0[1] << \", r2: \" << 1000*r0[2] << \"; R: \" << 1000*sum/user->rr.rows() << \"; fval: \"<<F<<std::endl;\n\n    return F;\n}\n\n\n//*************************************************************************************************************\n\nfloat Sphere::opt_rad(const VectorXf &r0,const fitUserNew user)\n{\n  MatrixXf diff = user->rr.rowwise() - r0.transpose();\n  return diff.rowwise().norm().mean();\n}\n", "meta": {"hexsha": "a3520dd153b4d16cc96aa9a2178e1aad470cf6e9", "size": 10048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/utils/sphere.cpp", "max_stars_repo_name": "13grife37/mne-cpp-swpold", "max_stars_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T20:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-26T16:30:25.000Z", "max_issues_repo_path": "MNE/utils/sphere.cpp", "max_issues_repo_name": "13grife37/mne-cpp-swpold", "max_issues_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/utils/sphere.cpp", "max_forks_repo_name": "13grife37/mne-cpp-swpold", "max_forks_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T15:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-23T15:55:31.000Z", "avg_line_length": 37.3531598513, "max_line_length": 161, "alphanum_fraction": 0.4418789809, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.01971912641509005, "lm_q1q2_score": 0.009244141628652178}}
{"text": "\r\n//          Copyright surrealwaffle 2018 - 2020.\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//          https://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#pragma once\r\n\r\n#include <cstddef>\r\n\r\n#include <algorithm>\r\n#include <functional>\r\n#include <iterator>\r\n#include <memory>\r\n#include <optional>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/index/rtree.hpp>\r\n#include <boost/iterator/transform_iterator.hpp>\r\n\r\n#include <sentinel/structures/object.hpp>\r\n#include <sentinel/tags/object.hpp>\r\n#include <sentinel/tags/collision_model.hpp>\r\n\r\n#include \"utility.hpp\"\r\n#include \"bsp_interface.hpp\"\r\n\r\nnamespace simulacrum {\r\n\r\nstruct this_collision_bsp_tag { };\r\ninline constexpr this_collision_bsp_tag this_collision_bsp = {};\r\n\r\nstruct collision_hierarchy_entry {\r\n    std::reference_wrapper<sentinel::object> object;\r\n    std::reference_wrapper<sentinel::tags::object> object_definition;\r\n    std::reference_wrapper<sentinel::tags::collision_model> collision_model;\r\n};\r\n\r\nboost::geometry::index::rtree<\r\n    std::pair<\r\n        boost::geometry::model::box<sentinel::real3d>,\r\n        collision_hierarchy_entry>,\r\n    boost::geometry::index::rstar<8>>\r\nbuild_dynamic_collision_hierarchy();\r\n\r\n/** \\brief Implements an adjacency list that cannot be modified once constructed.\r\n *\r\n * The user is required to implement the equality comparison operator for \\a Node and\r\n * the specialization `std::hash<Node>`.\r\n */\r\ntemplate<\r\n    class Node,\r\n    class Edge = empty_struct\r\n> class compiled_adjacency_list {\r\npublic:\r\n    struct edge_type;\r\n    using edge_iterator  = const edge_type*;\r\n    using edge_list_type = rough_span<edge_iterator>;\r\n    using nodes_container_type = std::unordered_map<Node, edge_list_type>;\r\n    using edge_container_type  = std::vector<edge_type>;\r\n\r\n    using hasher     = typename nodes_container_type::hasher;\r\n    using size_type  = typename nodes_container_type::size_type;\r\n    using value_type = typename nodes_container_type::value_type;\r\n\r\n    /** \\brief The iterator type for the elements of the adjacency structure.\r\n     *         Elements referred to by such iterators are constant pairings of\r\n     *         `(Node, edge_list_type)`.\r\n     */\r\n    using iterator  = typename nodes_container_type::const_iterator;\r\n\r\n\r\n    /** \\brief Represents a directed edge in the graph.\r\n     */\r\n    struct edge_type {\r\n        iterator source; ///< The node the edge starts from.\r\n        iterator target; ///< The node the edge goes to.\r\n        Edge     user;   ///< User data for the edge.\r\n\r\n        /** \\brief Conversion to user edge data.\r\n         */\r\n        operator Edge&() noexcept { return user; }\r\n\r\n        /** \\brief Conversion to user edge data.\r\n         */\r\n        operator const Edge&() const noexcept { return user; }\r\n\r\n        /** \\brief Member access for user edge data.\r\n         */\r\n        Edge* operator->() noexcept { return std::addressof(user); }\r\n\r\n        /** \\brief Member access for user edge data.\r\n         */\r\n        const Edge* operator->() const noexcept { return std::addressof(user); }\r\n    };\r\n\r\n    /** \\brief Constructs to an empty graph.\r\n     */\r\n    compiled_adjacency_list() = default;\r\n\r\n    /** \\brief Constructs a graph where the structure is taken in as node pairings.\r\n     *\r\n     * The edges are described as \\a Node pairings `(x,y)`, with the range of pairings\r\n     * supplied through `[neighbors_begin, neighbors_end)`.\r\n     * Every node `x` and `y` is interned and the edges are formed by the expression\r\n     * `form_edge(u, v)` where `u`, `v` and the interned counterparts of `x`, `y`.\r\n     *\r\n     * From the time the edges are formed, it is guaranteed that references to the\r\n     * interned nodes will not be invalidated, until the destructor is called.\r\n     */\r\n    template<class ForwardIt, class FormEdge>\r\n    compiled_adjacency_list(ForwardIt neighbors_begin, ForwardIt neighbors_end,\r\n                            const FormEdge& form_edge);\r\n\r\n    /** \\brief Accesses the internal node counterpart for \\a node.\r\n     *\r\n     * Has constant (on average) time-complexity.\r\n     *\r\n     * \\return An optional containing a constant reference to the interned node, or\r\n     *         `std::nullopt` if \\a node is not interned.\r\n     */\r\n    std::optional<std::reference_wrapper<const Node>>\r\n    intern(const Node& node) const;\r\n\r\n    /** \\brief Queries the graph to determine if there is a directed edge from\r\n     *         one node to another.\r\n     *\r\n     * Has logarithmic time-complexity.\r\n     * For consistency with #intern, this returns references to the user-domain\r\n     * \\a Edge, not the implementation #edge_type.\r\n     *\r\n     * \\return An optional containing a constant reference to the edge, or\r\n     *         `std::nullopt` if there is no directed edge between \\a from and \\a to.\r\n     */\r\n    std::optional<std::reference_wrapper<const Edge>>\r\n    adjacent(const Node& from, const Node& to) const;\r\n\r\n    /** \\brief Accesses the outgoing edges of a node.\r\n     *\r\n     * Has constant (on average) time-complexity.\r\n     * Unlike #adjacent, the\r\n     *\r\n     * \\return An iterable span of the outgoing edges of \\a node, or\r\n     *         an empty span if \\a node is not in the graph.\r\n     */\r\n    edge_list_type\r\n    egress_edges(const Node& node) const;\r\n\r\n    /** \\brief Returns an iterator to the first element of the adjacency structure.\r\n     */\r\n    iterator begin() const noexcept { return nodes.begin(); }\r\n\r\n    /** \\brief Returns an iterator to the element following the last element of the\r\n     *         adjacency structure.\r\n     */\r\n    iterator end() const noexcept { return nodes.end(); }\r\n\r\n    /** \\brief Gets an iterator to a given node.\r\n     *\r\n     * \\return An iterator to the graph vertex of \\a node if it is in the graph, or\r\n     *         `end()` if \\a node is not in the graph.\r\n     */\r\n    iterator find(const Node& node) const noexcept { return nodes.find(node); }\r\n\r\n    /** \\brief Returns the number of nodes in the graph.\r\n     */\r\n    size_type size() const noexcept { return nodes.size(); }\r\n\r\n    /** \\brief Returns the function that hashes the nodes.\r\n     */\r\n    hasher hash_function() const { return nodes.hash_function(); }\r\n\r\nprivate:\r\n    nodes_container_type nodes; ///< A mapping between nodes and sorted, contiguous\r\n                                ///< regions in #edges consisting of node out-edges.\r\n    edge_container_type  edges; ///< A collection of edges between the graph nodes.\r\n                                ///< Internally sorted by\r\n};\r\n\r\nstruct navigation_graph_node {\r\n    sentinel::real3d point; ///< The node position.\r\n\r\n    enum {\r\n        type_surface, ///< Indicates #bsp_index refers to a surface in the CBSP.\r\n        type_edge     ///< Indicates #bsp_index refers to an edge in the CBSP.\r\n    } cbsp_type;     ///< Determines the type of element #cbsp_index refers to.\r\n    long cbsp_index; ///< The index of the CBSP element this node is based on.\r\n\r\n    bool operator==(const navigation_graph_node& other) const noexcept {\r\n        return cbsp_type == other.cbsp_type && cbsp_index == other.cbsp_index;\r\n    }\r\n\r\n    bool operator!=(const navigation_graph_node& other) const noexcept {\r\n        return !(*this == other);\r\n    }\r\n\r\n    std::size_t hash_value() const;\r\n};\r\n\r\n} // namespace simulacrum\r\n\r\n// --------------------------------------------------\r\n// std::hash specialization for navigation_graph_node\r\n\r\nnamespace std {\r\n\r\ntemplate<>\r\nstruct hash<::simulacrum::navigation_graph_node> {\r\n    std::size_t\r\n    operator()(const ::simulacrum::navigation_graph_node& node) const noexcept\r\n    {\r\n        return node.hash_value();\r\n    }\r\n};\r\n\r\n} // namespace std\r\n\r\nnamespace simulacrum {\r\n\r\nstruct navigation_graph_edge {\r\n    sentinel::direction3d direction;\r\n    float                 distance;\r\n};\r\n\r\nclass navigation_graph {\r\npublic:\r\n    using node_type = navigation_graph_node;\r\n    using edge_type = navigation_graph_edge;\r\n    using graph_type = compiled_adjacency_list<node_type, edge_type>;\r\n    using iterator = graph_type::iterator;\r\n\r\n    navigation_graph() = default;\r\n\r\n    navigation_graph(const utility::interface_cbsp& cbsp);\r\n\r\n    navigation_graph(this_collision_bsp_tag);\r\n\r\n    iterator begin() const noexcept { return graph.begin(); }\r\n    iterator end()   const noexcept { return graph.end();   }\r\n\r\n    std::optional<iterator>\r\n    nearest_node(const sentinel::real3d& pos) const;\r\n\r\n    std::optional<iterator>\r\n    get_node(const node_type& node) const;\r\n\r\n    const graph_type&\r\n    get_graph() const { return graph; }\r\n\r\nprivate:\r\n    using spatial_point_type\r\n        = sentinel::real3d;\r\n    using spatial_indexable\r\n        = std::pair<spatial_point_type, iterator>;\r\n    using spatial_index_type\r\n        = boost::geometry::index::rtree<spatial_indexable,\r\n                                        boost::geometry::index::rstar<8>>;\r\n\r\n    graph_type         graph;\r\n    spatial_index_type spatial_index;\r\n};\r\n\r\ntemplate<class Node, class Edge>\r\ntemplate<class ForwardIt, class FormEdge>\r\ncompiled_adjacency_list<Node, Edge>::compiled_adjacency_list(\r\n        ForwardIt neighbors_begin, ForwardIt neighbors_end,\r\n        const FormEdge& form_edge)\r\n    : nodes()\r\n    , edges()\r\n{\r\n    // insert nodes with empty spans, to allocate\r\n    for (auto it = neighbors_begin; it != neighbors_end; ++it) {\r\n        const auto& [node, neighbor] = *it;\r\n\r\n        nodes.insert({node,     edge_list_type{nullptr, nullptr}});\r\n        nodes.insert({neighbor, edge_list_type{nullptr, nullptr}});\r\n    }\r\n\r\n    // form edges\r\n    edges.reserve(std::distance(neighbors_begin, neighbors_end));\r\n    for (auto it = neighbors_begin; it != neighbors_end; ++it) {\r\n        const auto& [node, neighbor] = *it;\r\n        const auto interned_node_it = nodes.find(node);\r\n        const auto interned_neighbor_it = nodes.find(neighbor);\r\n        edges.push_back({interned_node_it,\r\n                         interned_neighbor_it,\r\n                         form_edge(interned_node_it->first,\r\n                                   interned_neighbor_it->first)});\r\n    }\r\n\r\n    auto edge_source = [] (const edge_type& edge) -> const Node& { return edge.source->first; };\r\n    auto edge_target = [] (const edge_type& edge) -> const Node& { return edge.target->first; };\r\n    auto interned_cmp = [] (const Node& a, const Node& b) -> bool { return std::addressof(a) < std::addressof(b); };\r\n\r\n    auto cmp_edge_sources = [&edge_source, &interned_cmp] (const edge_type& a, const edge_type& b) {\r\n        return interned_cmp(edge_source(a), edge_source(b));\r\n    };\r\n    auto cmp_edge_targets = [&edge_target, &interned_cmp] (const edge_type& a, const edge_type& b) {\r\n        return interned_cmp(edge_target(a), edge_target(b));\r\n    };\r\n\r\n    // sort edges into spans sorted on the source node\r\n    std::sort(edges.begin(), edges.end(), cmp_edge_sources);\r\n\r\n    // properly set the edge list spans in the map\r\n    for (auto& [node, span] : nodes) {\r\n        auto [begin, end] = std::equal_range(boost::transform_iterator(edges.begin(), edge_source),\r\n                                             boost::transform_iterator(edges.end(),   edge_source),\r\n                                             node, interned_cmp);\r\n        span = edge_list_type {\r\n            std::addressof(*(begin.base())),\r\n            std::addressof(*(end.base()))\r\n        };\r\n\r\n        // put the edge list in sorted order, for lookup later\r\n        std::sort(begin.base(), end.base(), cmp_edge_targets);\r\n    }\r\n}\r\n\r\ntemplate<class Node, class Edge>\r\nstd::optional<std::reference_wrapper<const Node>>\r\ncompiled_adjacency_list<Node, Edge>::intern(const Node& node) const\r\n{\r\n    if (auto it = nodes.find(node); it != nodes.end())\r\n        return std::ref(it->first);\r\n    return std::nullopt;\r\n}\r\n\r\ntemplate<class Node, class Edge>\r\nstd::optional<std::reference_wrapper<const Edge>>\r\ncompiled_adjacency_list<Node, Edge>::adjacent(const Node& from, const Node& to_) const\r\n{\r\n    auto to = intern(to_);\r\n    auto source_it = nodes.find(from);\r\n\r\n    if (source_it == nodes.end() || !to)\r\n        return std::nullopt;\r\n\r\n    const auto& [node, span] = *source_it;\r\n    auto cmp = [] (const edge_type& edge, const Node& node) {\r\n        return std::addressof(edge.target->first) < std::addressof(node);\r\n    };\r\n    auto edge_it = std::lower_bound(span.begin(), span.end(), to.value(), cmp);\r\n    return edge_it != span.end() ? std::ref(edge_it->user) : std::nullopt;\r\n}\r\n\r\ntemplate<class Node, class Edge>\r\ntypename compiled_adjacency_list<Node, Edge>::edge_list_type\r\ncompiled_adjacency_list<Node, Edge>::egress_edges(const Node& node) const\r\n{\r\n    auto it = nodes.find(node);\r\n    return it != nodes.end() ? it->second\r\n                             : edge_list_type{edges.end(), edges.end()};\r\n}\r\n\r\ntemplate<\r\n    class MapIterator,\r\n    class ValueKeyHasher = void\r\n> struct map_iterator_hasher {\r\n    using key_reference  = decltype(std::declval<MapIterator>()->first);\r\n    using key_value_type = std::remove_cv_t<std::remove_reference_t<key_reference>>;\r\n    using hasher_type = std::conditional_t<\r\n                            std::is_void_v<ValueKeyHasher>,\r\n                            std::hash<key_value_type>,\r\n                            ValueKeyHasher>;\r\n\r\n    hasher_type hasher = hasher_type();\r\n\r\n    std::size_t operator()(const MapIterator& it) const {\r\n        return hasher(it->first);\r\n    }\r\n};\r\n\r\ntemplate<class Vertex, class Distance>\r\nstruct astar_search_entry {\r\n    Vertex   predecessor;\r\n    Distance distance; // from start\r\n    bool open;\r\n};\r\n\r\ntemplate<\r\n    class Node, class Edge,\r\n    class Heuristic,\r\n    class Visitor,\r\n    class EdgePredicate,\r\n    class Distance = decltype(std::declval<const Heuristic&>()(std::declval<const Node&>(), std::declval<const Node&>())),\r\n    class Vertex   = typename compiled_adjacency_list<Node, Edge>::iterator\r\n>\r\nstd::unordered_map<\r\n    Vertex,\r\n    astar_search_entry<Vertex, Distance>,\r\n    map_iterator_hasher<Vertex>\r\n>\r\nastar_search(const compiled_adjacency_list<Node, Edge>& graph,\r\n             const Vertex& start,\r\n             const Vertex& goal,\r\n             const Heuristic& heuristic, // invoked as heuristic(node, goal_node)\r\n             Visitor visitor,  // invoked as visitor(predecessor_node, node), returns false to halt evaluation\r\n             const EdgePredicate& edge_predicate) // invoked as edge_predicate(node, node, edge)\r\n{\r\n    using graph_type = compiled_adjacency_list<Node, Edge>;\r\n    using map_entry = astar_search_entry<Vertex, Distance>;\r\n    struct queue_entry {\r\n        Distance priority;\r\n        Vertex   vertex;\r\n    };\r\n\r\n    std::unordered_map<Vertex, map_entry, map_iterator_hasher<Vertex>> search_map;\r\n    std::priority_queue frontier = [] {\r\n        return std::priority_queue(\r\n            [] (const queue_entry& a, const queue_entry& b) { return a.priority > b.priority; },\r\n            std::vector<queue_entry>());\r\n    }();\r\n\r\n    auto push = [heuristic, &goal, &search_map, &frontier]\r\n                (Vertex   predecessor,\r\n                 Vertex   vertex,\r\n                 Distance distance) {\r\n        bool opened = false;\r\n\r\n        if (auto it = search_map.find(vertex); it == search_map.end())\r\n            search_map.emplace(vertex, map_entry{predecessor, distance, opened = true});\r\n        else if (distance < it->second.distance)\r\n            it->second = {predecessor, distance, opened = true};\r\n\r\n        if (opened)\r\n            frontier.push({distance + heuristic(vertex->first, goal->first), vertex});\r\n    };\r\n\r\n    push(start, start, static_cast<Distance>(0));\r\n    while (!frontier.empty()) {\r\n        const Vertex vertex = frontier.top().vertex;\r\n        const auto& [node, edges] = *vertex;\r\n        const map_entry& entry = search_map.at(vertex);\r\n        frontier.pop();\r\n\r\n        if (!entry.open)\r\n            continue;\r\n\r\n        const Distance distance = entry.distance;\r\n        if (!visitor(entry.predecessor->first, node) || vertex == goal)\r\n            break;\r\n\r\n        for (const typename graph_type::edge_type& edge : edges)\r\n            if (edge_predicate(edge.source->first, edge.target->first, edge))\r\n                push(edge.source, edge.target, distance + edge->distance);\r\n    }\r\n\r\n    return search_map;\r\n}\r\n\r\ntemplate<class Vertex, class Distance, class... MapArgs>\r\nstd::optional<std::vector<Vertex>>\r\nget_path(const Vertex& start,\r\n         const Vertex& goal,\r\n         const std::unordered_map<Vertex, astar_search_entry<Vertex, Distance>,\r\n                                  MapArgs...>& search_map)\r\n{\r\n    auto it = search_map.find(goal);\r\n    auto end = search_map.find(start);\r\n\r\n    if (it == search_map.end() || end == search_map.end())\r\n        return std::nullopt;\r\n\r\n    std::vector<Vertex> path;\r\n    for (; it != end; it = search_map.find(it->second.predecessor))\r\n        path.push_back(it->first);\r\n    std::reverse(path.begin(), path.end());\r\n\r\n    return std::make_optional(path);\r\n}\r\n\r\n} // namespace simulacrum\r\n", "meta": {"hexsha": "37e33d26335f7d81b214d0645b65cf786cb1df9f", "size": 17174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "simulacrum/graph.hpp", "max_stars_repo_name": "surrealwaffle/thesurrealwaffle", "max_stars_repo_head_hexsha": "6937d8e2604628a5c9141feef837d89e81f68165", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-20T23:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T04:16:42.000Z", "max_issues_repo_path": "simulacrum/graph.hpp", "max_issues_repo_name": "surrealwaffle/thesurrealwaffle", "max_issues_repo_head_hexsha": "6937d8e2604628a5c9141feef837d89e81f68165", "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": "simulacrum/graph.hpp", "max_forks_repo_name": "surrealwaffle/thesurrealwaffle", "max_forks_repo_head_hexsha": "6937d8e2604628a5c9141feef837d89e81f68165", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-21T06:32:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-21T06:32:13.000Z", "avg_line_length": 36.0041928721, "max_line_length": 123, "alphanum_fraction": 0.6290322581, "num_tokens": 3779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.028436034382815008, "lm_q1q2_score": 0.009219968582179662}}
{"text": "#ifndef _ANALYSIS_H_\n#define _ANALYSIS_H_\n\n#include <fstream>\n#include <tuple>\n#include <float.h>\n#include \"boost/algorithm/string.hpp\"\n#include \"boost/filesystem.hpp\"\n#include \"boost/asio.hpp\"\n#include \"TH2.h\"\n#include \"TGraph.h\"\n#include \"TF1.h\"\n#include \"TSystem.h\"\n#include \"TVector.h\"\n#include \"TLatex.h\"\n#include \"TMathText.h\"\n#include \"TLorentzVector.h\"\n#include \"TVector2.h\"\n#include \"TProfile.h\"\n#include \"TClonesArray.h\"\n#include \"sys/stat.h\"\n#include \"TTF.h\"\n#include \"TCanvas.h\"\n#include <boost/timer/timer.hpp>\n\n#include \"classes/DelphesClasses.h\"\n#include \"ExRootAnalysis/ExRootTreeReader.h\"\n#include \"ExRootAnalysis/ExRootTreeWriter.h\"\n#include \"ExRootAnalysis/ExRootTreeBranch.h\"\n#include \"ExRootAnalysis/ExRootResult.h\"\n#include \"ExRootAnalysis/ExRootUtilities.h\"\n\nusing namespace std;\n\nclass Analysis {\n\nprivate:\n    Analysis();\n    Analysis(const Analysis& rhs);\n    void operator = (const Analysis& rhs);\n\n     // args: inputfilename, proc_id\n    vector<tuple<string, int>>* m_input;\n    typedef vector<tuple<string, int>>::const_iterator itr_s;\n    \n    // args: processfilename, proc_id, n_proc, cross_section, uncertainty, weight\n    vector<tuple<string, int, int, double, double, double>>* m_processes;\n\n    vector<Electron*>* m_electrons;\n    vector<GenParticle*>* m_truthElectrons;\n    vector<Muon*>* m_muons;\n    vector<GenParticle*>* m_truthMuons;\n    vector<Jet*>* m_jets;\n    vector<GenParticle*>* m_truthBquarks;\n    // \n    // vector<bool>* m_electron_truth_tags;\n    // vector<bool>* m_muon_truth_tags;\n\n    GenParticle* m_hardTop;\n    GenParticle* m_hardTbar;\n    GenParticle* m_hardB;\n    GenParticle* m_hardBbar;\n    GenParticle* m_hardLepP;\n    GenParticle* m_hardLepM;\n    GenParticle* m_hardNu;\n    GenParticle* m_hardNuBar;\n    \n    vector<bool>* m_lepton_truth_tags;\n    vector<bool>* m_electron_truth_tags;\n    vector<bool>* m_muon_truth_tags;\n    vector<bool>* m_jet_truth_tags;\n\n    string m_inputFileName;\n    string m_processfilename;\n    string m_model;\n    string m_process;\n    string m_options;\n    int m_energy;\n    int m_luminosity;\n    string m_tag;\n    string m_pdf = \"CT14LL\";\n    bool m_useMassSlices = false;\n\n    bool m_xSec;\n    const string m_reconstruction;\n    bool m_useLumi;\n    const bool m_debug;\n    string m_channel;\n\n    double m_crossSection;\n    Long64_t m_nevents;\n    Long64_t m_nevents_max;\n    double m_event_time;\n\n    vector<double> iteration_weights;\n    string m_dataDirectory;\n    string m_outputFileName;\n    TFile* m_outputFile;\n    TChain* m_chain;\n    ExRootTreeReader* m_tree;\n\n    vector<int> m_cutflow;\n    vector<string> m_cutNames;\n    vector<string> m_cutTitles;\n    enum m_cutlist{\n        c_events,\n        c_twoLeptons,\n        c_oppositeCharge,\n        c_sufficientMll,\n        c_outsideZmassWindow,\n        c_sufficientMET,\n        c_sufficientJets,\n        c_sufficientBtags,\n        c_sufficientHT,\n        c_validSolution,\n        m_cuts // Keep as last entry\n    };\n\n    const double m_pi = 3.14159265358979323846;\n    const double m_mass_b = 4.18, m_mass_W = 80.4, m_mass_Z = 91.19, m_mass_top = 172.5;\n\n    const int m_minBtags;\n    int m_bTags;\n    \n    vector<double>* m_dR_lb_truth;\n    vector<double>* m_mass_ttbar_truth;\n\n    // Histograms\n    TH1D* h_cutflow;\n    TProfile* h_eff_cuts_mass_ttbar_truth;\n    TProfile* h_eff_cuts_pT_top_truth;\n    TProfile* h_eff_cuts_pT_tbar_truth;\n    TProfile* h_eff_cut_2l_mass_ttbar_truth;\n    TProfile* h_eff_cut_oc_mass_ttbar_truth;\n    TProfile* h_eff_cut_mll_mass_ttbar_truth;\n    TProfile* h_eff_cut_mZ_mass_ttbar_truth;\n    TProfile* h_eff_cut_ETmiss_mass_ttbar_truth;\n    TProfile* h_eff_cut_HT_mass_ttbar_truth;\n    TProfile* h_eff_cut_2j_mass_ttbar_truth;\n    TProfile* h_eff_cut_2b_mass_ttbar_truth;\n    TProfile* h_eff_reco_mass_ttbar_truth;\n    TProfile* h_eff_reco_pT_top_truth;\n    TProfile* h_eff_reco_pT_tbar_truth;\n\n    TH1D* h_pT_l1;\n    TH1D* h_eta_l1;\n    TH1D* h_pT_l2;\n    TH1D* h_eta_l2;\n\n    TH1D* h_pT_jets;\n    TH1D* h_eta_jets;\n    TH1D* h_pT_bjets;\n    TH1D* h_eta_bjets;\n    TH1D* h_pT_qjets;\n    TH1D* h_eta_qjets;\n\n    TH1D* h_pT_alljets;\n    TH1D* h_pT_allel;\n    TH1D* h_pT_allmu;\n    TH1D* h_eta_alljets;\n    TH1D* h_eta_allel;\n    TH1D* h_eta_allmu;\n\n    TH1D* h_HT;\n    TH1D* h_HT_truth;\n    TH1D* h_HTmet_truth;\n    TH1D* h_HTmet;\n    TH1D* h_HTjMET;\n    TH1D* h_KT_truth;\n    TH1D* h_KT;\n    TH1D* h_KTj;\n    TH1D* h_mass_vis;\n    TH1D* h_mass_bbll;\n    \n    TH1D* h_HT_all;\n    TH1D* h_KT_all;\n    TH1D* h_mass_vis_all;\n\n    TH1D* h_deltaPhi_ll;\n    TH1D* h_cosPhi;\n\n    TH1D* h_mass_W1;\n    TH1D* h_mass_W2;\n\n    // top\n    TH1D* h_pT_top;\n    TH1D* h_eta_top;\n    TH1D* h_y_top;\n    TH1D* h_phi_top;\n    TH1D* h_mass_top;\n    TH1D* h_E_top;\n    TH1D* h_pT_top_truth;\n    TH1D* h_eta_top_truth;\n    TH1D* h_y_top_truth;\n    TH1D* h_phi_top_truth;\n    TH1D* h_mass_top_truth;\n\n    // tbar\n    TH1D* h_pT_tbar;\n    TH1D* h_eta_tbar;\n    TH1D* h_y_tbar;\n    TH1D* h_phi_tbar;\n    TH1D* h_mass_tbar;\n    TH1D* h_E_tbar;\n    TH1D* h_pT_tbar_truth;\n    TH1D* h_eta_tbar_truth;\n    TH1D* h_y_tbar_truth;\n    TH1D* h_phi_tbar_truth;\n    TH1D* h_mass_tbar_truth;\n\n    // ttbar\n    TH1D* h_pT_ttbar;\n    TH1D* h_pT_ttbar_truth;\n    TH1D* h_eta_ttbar;\n    TH1D* h_eta_ttbar_truth;\n    TH1D* h_phi_ttbar;\n    TH1D* h_phi_ttbar_truth;\n    TH1D* h_mass_ttbar;\n    TH1D* h_mass_ttbar_truth;\n    TH1D* h_y_ttbar;\n    TH1D* h_y_ttbar_truth;\n    \n    // delta \n    TH1D* h_deltaPhi_tt_truth;\n    TH1D* h_deltaPhi_tt;\n    TH1D* h_deltaEta_tt_truth;\n    TH1D* h_deltaEta_tt;\n\n    // dR between truth and reco\n    TH1D* h_dR_top;\n    TH1D* h_dR_tbar;\n    TH1D* h_dR_ttbar;\n    \n    // dR between each truth lepton and its closest reco lepton\n    TH1D* h_dR_l;\n    \n    // dR between truth leptons and b-quarks and top quarks\n    TH1D* h_dR_t1t2_truth;\n    TH1D* h_dR_lb_truth;\n    // TH1D* h_dR_l1b1_truth;\n    // TH1D* h_dR_l2b2_truth;\n    TH1D* h_dR_t1l1_truth;\n    TH1D* h_dR_t2l2_truth;\n    TH1D* h_dR_t1b1_truth;\n    TH1D* h_dR_t2b2_truth;\n    \n    TH2D* h2_dR_l1b1_pTl_truth;\n    TH2D* h2_dR_l2b2_pTl_truth;\n    TH2D* h2_dR_lb_mtt_truth;\n    // TH2D* h2_dR_l1b1_mtt_truth;\n    // TH2D* h2_dR_l2b2_mtt_truth;\n    TH2D* h2_dR_t1l1_mtt_truth;\n    TH2D* h2_dR_t2l2_mtt_truth;\n    TH2D* h2_dR_t1b1_mtt_truth;\n    TH2D* h2_dR_t2b2_mtt_truth;\n    \n    TH1D* h_ETmiss;\n    TH1D* h_ETmiss_truth;\n    TH2D* h2_mtt_truth_ETmiss_truth;\n\n    // performance plots\n    TH1D* h_perf_mass_top;\n    TH1D* h_perf_pT_top;\n    TH1D* h_perf_eta_top;\n    TH1D* h_perf_phi_top;\n    TH1D* h_perf_mass_tbar;\n    TH1D* h_perf_pT_tbar;\n    TH1D* h_perf_eta_tbar;\n    TH1D* h_perf_phi_tbar;\n    TH1D* h_perf_mass_ttbar;\n    TH1D* h_perf_pT_ttbar;\n    TH1D* h_perf_eta_ttbar;\n    TH1D* h_perf_phi_ttbar;\n    TH2D* h2_perf_mass_ttbar;\n    TH2D* h2_perf_mass_ttbar_pTtop;\n    TH2D* h2_perf_mass_ttbar_pTtbar;\n    \n    // resolution\n    TH1D* h_res_pT_bjets;\n    TH2D* h2_resPtBjets_pT;\n    \n    TH1D* h_res_pT_tops;\n    TH1D* h_res_y_tops;\n    TH1D* h_res_phi_tops;\n    TH1D* h_res_eta_tops;\n    \n    TH1D* h_res_pT_ttbar;\n    TH1D* h_res_y_ttbar;\n    TH1D* h_res_mass_ttbar;\n    TH1D* h_res_eta_ttbar;\n    \n    TProfile* h_reco_quality;\n\n    TH2D* h2_mass_top_TvR;\n    TH2D* h2_pT_top_TvR;\n    TH2D* h2_eta_top_TvR;\n    TH2D* h2_phi_top_TvR;\n    TH2D* h2_mass_tbar_TvR;\n    TH2D* h2_pT_tbar_TvR;\n    TH2D* h2_eta_tbar_TvR;\n    TH2D* h2_phi_tbar_TvR;\n    TH2D* h2_mass_ttbar_TvR;\n    TH2D* h2_pT_ttbar_TvR;\n    TH2D* h2_eta_ttbar_TvR;\n    TH2D* h2_phi_ttbar_TvR;\n\n    // charge asymmetries\n    TH1D* h_mtt_tF;\n    TH1D* h_mtt_tB;\n    TH1D* h_mtt_lF;\n    TH1D* h_mtt_lB;\n    TH1D* h_HT_lF;\n    TH1D* h_HT_lB;\n    TH1D* h_KT_lF;\n    TH1D* h_KT_lB;\n    TH1D* h_mtt_tCF;\n    TH1D* h_mtt_tCB;\n    TH1D* h_mtt_lCF;\n    TH1D* h_mtt_lCB;\n    TH1D* h_HT_lCF;\n    TH1D* h_HT_lCB;\n    TH1D* h_KT_lCF;\n    TH1D* h_KT_lCB;\n\n    // TH1D* h_mtt_tlF;\n    // TH1D* h_mtt_tlB;\n\n    // top polarisation\n    TH1D* h_mtt_c1F;\n    TH1D* h_mtt_c1B;\n    TH1D* h_mtt_c2F;\n    TH1D* h_mtt_c2B;\n    // TH1D* h_mtt_philF;\n    // TH1D* h_mtt_philB;\n    // TH1D* h_mtt_ElF;\n    // TH1D* h_mtt_ElB;\n\n    // spin correlation\n    TH1D* h_mtt_c1c2F;\n    TH1D* h_mtt_c1c2B;\n    TH1D* h_mtt_cPhiF;\n    TH1D* h_mtt_cPhiB;\n    TH1D* h_mtt_DphiF;\n    TH1D* h_mtt_DphiB;\n    TH1D* h_HT_DphiF;\n    TH1D* h_HT_DphiB;\n    TH1D* h_KT_DphiF;\n    TH1D* h_KT_DphiB;\n\n    TH1D* h_cosTheta1_truth;\n    TH1D* h_cosTheta2_truth;\n    TH1D* h_cosTheta;\n    TH1D* h_cosTheta1;\n    TH1D* h_cosTheta2;\n    TH1D* h_cos1cos2;\n    TH1D* h_cosThetaStar;\n    TH1D* h_cosTheta_ttbar;\n    TH1D* h_cosTheta_l;\n    TH1D* h_cosThetaStar_l;\n    TH1D* h_deltaY_top;\n    TH1D* h_deltaY_top_truth;\n    TH1D* h_deltaEta_l;\n    \n    TH1D* h_n_electrons;\n    TH1D* h_n_muons;\n    TH1D* h_n_jets;\n    TH1D* h_n_bJets;\n    \n    TProfile* h_lepton_purity;\n    TProfile* h_jet_purity;\n\n    TH1D* h_n_truthElectrons;\n    TH1D* h_n_truthMuons;\n    TH1D* h_n_truthBquarks;\n    \n    TH1D* h_n_selElectrons;\n    TH1D* h_n_selMuons;\n    TH1D* h_n_selJets;\n    \n    TH1D* h_n_jets_no_truth_tag;\n    TH1D* h_n_uniqueElectrons;\n    TH1D* h_n_uniqueMuons;\n    TH1D* h_n_uniqueJets;\n    \n    TH1D* h_n_electrons_truth_tagged;\n    TH1D* h_n_selElectrons_truth_tagged;\n    TH1D* h_n_uniqueElectrons_truth_tagged;\n    \n    TH1D* h_n_muons_truth_tagged;\n    TH1D* h_n_selMuons_truth_tagged;\n    TH1D* h_n_uniqueMuons_truth_tagged;\n    \n    TH1D* h_n_jets_truth_tagged;\n    TH1D* h_n_selJets_truth_tagged;\n    TH1D* h_n_uniqueJets_truth_tagged;\n    TH1D* h_ntracks_truth_tagged_jets;\n\n    TH1D* h_n_passElectrons;\n    TH1D* h_n_passMuons;\n    TH1D* h_n_passJets;\n    TH1D* h_n_passBjets;\n\n    TH2D* h2_mtt_cosThetaStar;\n    TH2D* h2_mtt_delta_yt;\n    TH2D* h2_mtt_cosThetaStar_ll;\n    TH2D* h2_mtt_delta_abs_etal;\n    TH2D* h2_HT_delta_abs_etal;\n    TH2D* h2_KT_delta_abs_yt;\n    TH2D* h2_HT_cosThetaStar_ll;\n    TH2D* h2_KT_cosThetaStar_ll;\n    TH2D* h2_mtt_deltaPhi;\n    TH2D* h2_mtt_cosTheta1;\n    TH2D* h2_mtt_cosTheta2;\n    TH2D* h2_mtt_cos1cos2;\n    TH2D* h2_mvis_deltaPhi;\n    TH2D* h2_HT_deltaPhi;\n    TH2D* h2_HTmet_deltaPhi;\n    TH2D* h2_KT_deltaPhi;\n\nprotected:\n    void SetupTreesForNewFile(const string&);\n    void CleanUp();\n    void SetupInputFiles();\n    void SetupInputFile();\n    bool SetupOutputFile();\n\n    void PreLoop();\n    void PreLoopSingle();\n    void Loop();\n    void PostLoop();\n\n    void EachEvent(double);\n    void EveryEvent(double);\n    void CleanupEvent();\n    void GetHardParticles();\n    void GetTruthParticles();\n    // void GetElectrons();\n    // void GetMuons();\n    void SelectElectrons();\n    void SelectMuons();\n    void SelectJets();\n    void IsolateElectrons();\n    void IsolateMuons();\n    void OverlapRemoval();\n    void RemoveJetsCloseToElectrons();\n    void RemoveJetsCloseToMuons();\n    void RemoveElectronsInsideJets();\n    void RemoveMuonsInsideJets();\n    void TruthTagLeptons();\n    void TruthTagJets();\n    void FillPurities(int);\n    void AssignChannel();\n    void FillTaggedHistograms();\n    pair<TLorentzVector, TLorentzVector> GetLeptonMomenta();\n\n    // histograms\n    void MakeHistograms();\n    void MakeDistributions();\n    void WriteEfficiency(TH1D*, const string&, const string&);\n    void MakeDistribution1D(TH1D*, const string&, bool normalise = false);\n    void MakeDistribution2D(TH2D*, string, string, string, string);\n    void MakeDistributionAL(TH2D*, const string&, const string&);\n    void NormalizeSliceY(TH2D*);\n    void AverageEachXbin(TH2D*);\n\n    void GetGenerationCrossSection(int);\n    void GetProcessWeight(int);\n    void SetDataDirectory();\n    void AsymmetryUncertainty(TH1D*, TH1D*, TH1D*);\n    void GetBranches();\n    void EachFile(const string&);\n\n    // cutflow\n    void InitialiseCutflow();\n    void PrintCutflow();\n    void UpdateCutflow(int, bool);\n    void FillCutsEfficiencies(const vector<double>&, const int);\n    void FillRecoEfficiencies(const vector<double>&, const int);\n\n    // event selection\n    bool PassesEventSelection();\n    bool ExactlyTwoLeptons();\n    bool OppositeCharge();\n    bool SufficientJets();\n    bool SufficientBtags();\n    bool SufficientHT(double);\n    bool SufficientMET(double);\n    bool SufficientMll(const pair<TLorentzVector, TLorentzVector>&);\n    bool OutsideZmassWindow(const pair<TLorentzVector, TLorentzVector>&);\n\n    Long64_t TotalEvents();\n    Long64_t IncrementEvent(Long64_t i);\n    double TotalAsymmetry(TH1D* h_A, TH1D* h_B);\n    void Asymmetry(const string&, const string&, const string&, TH1D*, TH1D*);\n\n    // tuple\n    TClonesArray* b_Particle;\n    TClonesArray* b_Jet;\n    TClonesArray* b_Electron;\n    TClonesArray* b_Muon;\n    TClonesArray* b_MissingET;\n    TClonesArray* b_EFlowTrack;\n    TClonesArray* b_EFlowPhoton;\n    TClonesArray* b_EFlowNeutralHadron;\n    // TClonesArray* b_ScalarHT;\n    TClonesArray* b_Track;\n\npublic:\n    Analysis(const string& model, const string& process, const string& options, const int energy, const int luminosity, const int minBtags, const string& reconstruction, const string& tag, const bool slice):\n        m_inputFileName(\"\"),\n        m_processfilename(\"\"),\n        m_model(model),\n        m_process(process),\n        m_options(options),\n        m_energy(energy),\n        m_luminosity(luminosity),\n        m_minBtags(minBtags),\n        m_reconstruction(reconstruction),\n        m_tag(tag),\n        m_useMassSlices(slice),\n        m_xSec(false),\n        m_debug(false),\n        m_outputFile(nullptr),\n        m_input(nullptr),\n        m_processes(nullptr),\n        m_chain(nullptr),\n        m_tree(nullptr)\n    {\n        this->PreLoop();\n    }\n\n    Analysis(const string& inputfilename, const string& processfilename, const int luminosity, const int minBtags, const string& reconstruction, const Long64_t nevents_max = 0, const string& tag = \"\", const bool slice = false):\n        m_inputFileName(inputfilename),\n        m_processfilename(processfilename),\n        m_model(\"\"),\n        m_process(\"\"),\n        m_options(\"\"),\n        m_energy(0),\n        m_luminosity(luminosity),\n        m_minBtags(minBtags),\n        m_reconstruction(reconstruction),\n        m_nevents_max(nevents_max),\n        m_tag(tag),\n        m_useMassSlices(slice),\n        m_xSec(false),\n        m_debug(false),\n        m_outputFile(nullptr),\n        m_input(nullptr),\n        m_processes(nullptr),\n        m_chain(nullptr),\n        m_tree(nullptr)\n    {   \n        this->PreLoopSingle();\n    }\n    virtual ~Analysis();\n    void Run();\n};\n#endif\n", "meta": {"hexsha": "660b4c6dbb6c2bd0c182241c631173acb6424a90", "size": 14443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/analysis.hpp", "max_stars_repo_name": "declanmillar/x-tt-analysis", "max_stars_repo_head_hexsha": "dc617efc10ddcd2fcc46b59743b883ddd7a6b14d", "max_stars_repo_licenses": ["MIT"], "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/analysis.hpp", "max_issues_repo_name": "declanmillar/x-tt-analysis", "max_issues_repo_head_hexsha": "dc617efc10ddcd2fcc46b59743b883ddd7a6b14d", "max_issues_repo_licenses": ["MIT"], "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/analysis.hpp", "max_forks_repo_name": "declanmillar/x-tt-analysis", "max_forks_repo_head_hexsha": "dc617efc10ddcd2fcc46b59743b883ddd7a6b14d", "max_forks_repo_licenses": ["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.8372093023, "max_line_length": 227, "alphanum_fraction": 0.6807449976, "num_tokens": 4882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660016, "lm_q2_score": 0.022629201969265555, "lm_q1q2_score": 0.009217629452847941}}
{"text": "//\n// $Id$\n//\r\n//\r\n// Original author: William French <william.r.french <a.t> vanderbilt.edu>\r\n//\r\n// Copyright 2008 Vanderbilt University - Nashville, TN 37232\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n\r\n\r\n#define PWIZ_SOURCE\r\n\r\n#include \"SpectrumList_ChargeFromIsotope.hpp\"\r\n#include \"pwiz/analysis/spectrum_processing/SpectrumList_PeakPicker.hpp\"\r\n#include \"pwiz/utility/misc/Std.hpp\"\r\n#include \"pwiz/utility/misc/IntegerSet.hpp\"\r\n#include \"pwiz/utility/chemistry/Ion.hpp\"\r\n#include <boost/range/algorithm/remove_if.hpp>\r\n\r\n// Predicate for sorting score data structures \r\nbool sortScoresByMZ (scoreChain i, scoreChain j) { return (i.mzPvalue < j.mzPvalue); } \r\nbool sortScoresByKLScore (scoreChain i, scoreChain j) { return (i.intensityPvalue < j.intensityPvalue); } \r\nbool sortScoresByIntensitySum (scoreChain i, scoreChain j) { return (i.intensitySumPvalue < j.intensitySumPvalue); } \r\nbool sortScoresByOverallPvalue (scoreChain i, scoreChain j) { return (i.overallPvalue < j.overallPvalue); }\r\nbool sortScoresBySumOfRanks (scoreChain i, scoreChain j) { return (i.sumRanks < j.sumRanks); }\r\n// Predicate for sorting retention time data structure\r\nbool sortByRetentionTime (rtimeMap i, rtimeMap j) { return (i.rtime < j.rtime); }\r\n// Comparator for running upper_bound on retention time data structure\r\nbool rtimeComparator(double a, rtimeMap i) { return (i.rtime > a ); }\r\n\r\nbool pairSortFunc (pairData i, pairData j) { return (i.mz<j.mz); } // comparator for sorting of parentIon by m/z \r\nbool pairCompare (pairData i, double mz) { return (i.mz<mz); } // comparator for searching parentIon by m/z\r\n\r\nusing namespace pwiz::msdata;\r\nusing namespace pwiz::cv;\r\nusing namespace pwiz::util;\r\n\r\nnamespace pwiz {\r\nnamespace analysis {\r\n\r\n\r\nPWIZ_API_DECL SpectrumList_ChargeFromIsotope::SpectrumList_ChargeFromIsotope(\r\n    const msdata::MSData& msd,\r\n    int maxCharge,\r\n    int minCharge,\r\n    int parentsBefore,\r\n    int parentsAfter,\r\n    double isolationWidth,\r\n    int defaultChargeMax,\r\n    int defaultChargeMin)\r\n:   SpectrumListWrapper(msd.run.spectrumListPtr),\r\n    maxCharge_(maxCharge),\r\n    minCharge_(minCharge),\r\n    parentsBefore_(parentsBefore),\r\n    parentsAfter_(parentsAfter),\r\n    defaultIsolationWidth_(isolationWidth),\r\n    defaultChargeMax_(defaultChargeMax),\r\n    defaultChargeMin_(defaultChargeMin)\r\n{\r\n\r\n    srand( 1234 ); // using the same seed ensures consistency between runs, otherwise we can get different charges and precursors with the exact same settings\r\n\r\n    // set parameters\r\n    override_ = true;\r\n    sigVal_ = 0.30;\r\n    nChainsCheck_ = 8;\r\n    mzTol = 0.06; \r\n    maxIsotopePeaks = 5; // 2,3,4,5 (monoisotope included in this count)\r\n    minIsotopePeaks = 2;\r\n    massNeutron = 1.00335; // massC13 - massC12\r\n    nSamples = 10000;\r\n    upperLimitPadding = 1.25;\r\n    maxNumberPeaks = 40;\r\n    minNumberPeaks = 2;\r\n    int nCharges = maxCharge_ - minCharge_ + 1;\r\n    int nIsotopePeakPossibilities = maxIsotopePeaks - minIsotopePeaks + 1;\r\n\r\n    // fill out MS1retentionTimes\r\n    getMS1RetentionTimes(); \r\n    int surveyCnt = MS1retentionTimes.size();\r\n    double finalRetentionTime = MS1retentionTimes[surveyCnt-1].rtime;\r\n\r\n    // simulate the m/z spacing score (sum of squared errors)\r\n    simulateSSE(nCharges,nIsotopePeakPossibilities);\r\n\r\n    // simulte the relative intensity distribution (Kullback-Leibler divergence of Poisson-modeled intensities)\r\n    simulateKL(finalRetentionTime,nIsotopePeakPossibilities,surveyCnt>=9?9:surveyCnt);\r\n\r\n    // simulate the total peak intensity\r\n    simulateTotIntensity(nIsotopePeakPossibilities);\r\n\r\n}\r\n\r\nPWIZ_API_DECL SpectrumPtr SpectrumList_ChargeFromIsotope::spectrum(size_t index, bool getBinaryData) const\r\n{\r\n\r\n    SpectrumPtr s = inner_->spectrum(index, true);\r\n\r\n    // return non-MS/MS as-is\r\n    CVParam spectrumType = s->cvParamChild(MS_spectrum_type);\r\n    if (spectrumType != MS_MSn_spectrum)\r\n        return s;\r\n\r\n    // return MS1 as-is\r\n    if (!s->hasCVParam(MS_ms_level) ||\r\n        s->cvParam(MS_ms_level).valueAs<int>() < 2)\r\n        return s;\r\n\r\n    // return peakless spectrum as-is\r\n    if (s->defaultArrayLength == 0)\r\n        return s;\r\n\r\n    // return precursorless MS/MS as-is\r\n    if (s->precursors.empty() ||\r\n        s->precursors[0].selectedIons.empty())\r\n        return s;\r\n\r\n    //cout << \"Performing Turbocharger analysis!\" << endl;\r\n\r\n    // use first selected ion in first precursor\r\n    // TODO: how to deal with multiple precursors and/or selected ions?\r\n    Precursor& precursor = s->precursors[0];\r\n    SelectedIon& selectedIon = precursor.selectedIons[0];\r\n\r\n    //int vendorCharge = selectedIon.cvParam(MS_charge_state).valueAs<int>();\r\n\r\n    // erase any existing charge-state-related CV params\r\n    vector<CVParam>& cvParams = selectedIon.cvParams;\r\n    IntegerSet possibleChargeStates;\r\n    for(vector<CVParam>::iterator itr = cvParams.begin(); itr != cvParams.end(); ++itr)\r\n    {\r\n        if (itr->cvid == MS_charge_state ||\r\n            itr->cvid == MS_possible_charge_state)\r\n        {\r\n            // some files may have a bogus \"0\" charge state\r\n            if (override_ || itr->value == \"0\")\r\n            {\r\n                selectedIon.userParams.push_back(UserParam(\"old charge state\", itr->value));\r\n                itr = --cvParams.erase(itr);\r\n            }\r\n            else if (itr->cvid == MS_possible_charge_state)\r\n                possibleChargeStates.insert(itr->valueAs<int>());\r\n            else if (itr->cvid == MS_charge_state)\r\n                return s;\r\n        }\r\n    }\r\n\r\n    double precursorMZ = selectedIon.cvParam(MS_selected_ion_m_z).valueAs<double>();\r\n    int nPossibleChargeStates = maxCharge_ - minCharge_ + 1;\r\n    int nIsotopePeakPossibilities = maxIsotopePeaks - minIsotopePeaks + 1;\r\n\r\n    // Get the upper/lower bounds of the precursor isolation window.\r\n    // Of the data I've tested, only Thermo lists isolation window info.\r\n    double upperIsoWidth = precursor.isolationWindow.cvParam(MS_isolation_window_upper_offset).valueAs<double>(); \r\n    upperIsoWidth = upperIsoWidth > 0.0 ? upperIsoWidth : defaultIsolationWidth_;\r\n    double lowerIsoWidth = precursor.isolationWindow.cvParam(MS_isolation_window_lower_offset).valueAs<double>();\r\n    lowerIsoWidth = lowerIsoWidth > 0.0 ? lowerIsoWidth : defaultIsolationWidth_; \r\n    double targetIsoMZ = precursor.isolationWindow.cvParam(MS_isolation_window_target_m_z).valueAs<double>();\r\n    targetIsoMZ = targetIsoMZ > 0.0 ? targetIsoMZ : precursorMZ;\r\n\r\n    vector <int> parentIndex;\r\n    getParentIndices(s,parentIndex);\r\n\r\n    // info about chains/score across all parent scans\r\n    vector <scoreChain> allScores;\r\n    vector <isotopeChain> allChains;\r\n    vector < vector<double> > allMZs;\r\n    vector < vector<double> > allIntensities;\r\n    int allChainsCnt=0;\r\n    int assignedCharge = 0;\r\n    double assignedMZ = targetIsoMZ;\r\n\r\n    getParentPeaks(s,parentIndex,targetIsoMZ,lowerIsoWidth,upperIsoWidth,allMZs,allIntensities);\r\n\r\n    // loop over peaks in parent spectra, build isotope chains and score them\r\n    for (int i=0, iend=parentIndex.size(); i < iend; ++i)\r\n    {\r\n\r\n        int nPeaks = allMZs[i].size();\r\n        vector <double> peakMZs(nPeaks);\r\n        vector <double> peakIntensities(nPeaks);\r\n        for (int j=0, jend=nPeaks; j < jend; ++j)\r\n        {\r\n            peakMZs[j] = allMZs[i][j];\r\n            peakIntensities[j] = allIntensities[i][j];\r\n        }\r\n        vector <double> sortedPeakIntensities = peakIntensities;\r\n        sort(sortedPeakIntensities.begin(),sortedPeakIntensities.end());\r\n\r\n        vector <isotopeChain> chains;\r\n    \r\n        if ( nPeaks > 1 ) // need at least two peaks to perform analysis\r\n        {\r\n                            \r\n            for (int j=0,cnt=0; j<nPeaks; j++)\r\n            {\r\n\r\n                if ( peakMZs[j] > targetIsoMZ + upperIsoWidth ) break; // don't let the monoisotope move outside the isolation width\r\n\r\n                for (int k = j+1; k<nPeaks; k++,cnt++)\r\n                {\r\n\r\n                    double mzDiff = peakMZs[k] - peakMZs[j]; // guaranteed to give positive value\r\n                    if (mzDiff > massNeutron + mzTol) break; // subsequent sets of peaks will have spacing that is too large\r\n\r\n                    double recip = massNeutron / mzDiff;\r\n                    int possibleCharge = int(recip + 0.50); \r\n                    if ( possibleCharge > maxCharge_ || possibleCharge < minCharge_ ) continue; // Not going to generate chain extension\r\n\r\n\r\n                    if ( abs( massNeutron / double(possibleCharge) - mzDiff) < mzTol )\r\n                    {\r\n            \r\n                        // We have a hit\r\n                        // Start by checking if this can be connected to previous chains\r\n                        for (int w=0, wend=chains.size(); w < wend; ++w)\r\n                        {\r\n\r\n                            if ( possibleCharge != chains[w].charge ) continue;\r\n                            int nPeaksInChain = chains[w].indexList.size();\r\n                            if ( nPeaksInChain >= maxIsotopePeaks ) continue;\r\n                                \r\n                            int finalIndex = chains[w].indexList[chains[w].indexList.size()-1];\r\n                            if ( j == finalIndex ) // connect it and save previous chain\r\n                            {\r\n                                chains.push_back(chains[w]); // push back copy of previous chain with current size\r\n                                chains[w].indexList.push_back(k); // now extend the size of the chain\r\n                            }\r\n\r\n                        }\r\n\r\n                        // Also create a new chain of length 2\r\n                        isotopeChain newChain;\r\n                        newChain.charge = possibleCharge;\r\n                        newChain.indexList.push_back(j);\r\n                        newChain.indexList.push_back(k); \r\n                        newChain.parentIndex = i; \r\n                        chains.push_back(newChain);\r\n\r\n                    } // end if peak is within tolerance\r\n            \r\n                } // end for loop k\r\n\r\n            } // end for loop j\r\n\r\n        } // end if peak list size at least 2\r\n\r\n        // Filter any chains that are not the required length\r\n        if (chains.size() > 0)\r\n        {\r\n\r\n            vector<isotopeChain>::iterator it = chains.begin();\r\n            while ( it != chains.end() )\r\n            {\r\n                if ( it->charge > 4 && it->indexList.size() < 3 )\r\n                {\r\n                    it = chains.erase(it);\r\n                }\r\n                else\r\n                {\r\n                    ++it;\r\n                }\r\n\r\n            }\r\n\r\n        }\r\n\r\n        scoreChain initializeScore;\r\n        vector <scoreChain> scores(chains.size(),initializeScore);\r\n        if (chains.size() > 0)\r\n        {\r\n\r\n            // Now perform the scoring\r\n            vector<isotopeChain>::iterator chainIt = chains.begin();\r\n            while ( chainIt != chains.end() )\r\n            {\r\n\r\n                //////////////////////////////////////////////////////////////////////////////////////\r\n                // calculate the relative intensity score, based on the K-L score from a poisson distribution\r\n                int j = chainIt - chains.begin();\r\n                double KLscore = getKLscore( chains[j], peakMZs, peakIntensities );\r\n                int startIndex = (chains[j].indexList.size()-minIsotopePeaks)*nSamples;\r\n                vector <double> simValues;\r\n                simValues.assign(&simulatedKLs[startIndex],&simulatedKLs[startIndex+nSamples-1]);\r\n                vector< double >::iterator i1 = upper_bound(simValues.begin(),simValues.end(),KLscore); // returns iterator to first value that's > KLscore\n                int klVectorIndex = i1 - simValues.begin();\r\n                scores[j].intensityPvalue = double(klVectorIndex+1) / double(nSamples+1);\r\n                //////////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n                //////////////////////////////////////////////////////////////////////////////////////\r\n                // calculate average monoisotopic mass based on m/z positions in chain\r\n                double average=0.0;\r\n                for (int k=0, kend=chains[j].indexList.size(); k < kend; k++)\r\n                    average += peakMZs[chains[j].indexList[k]] - double(k)*massNeutron/double(chains[j].charge);\r\n                average /= double(chains[j].indexList.size());\r\n\r\n                // calculate summed square error of m/z positions in chain relative to the average monoisotopic m/z\r\n                double sse=0.0;\r\n                for (int k=0, kend=chains[j].indexList.size(); k < kend; k++)\r\n                    sse += pow( average - (peakMZs[chains[j].indexList[k]] - double(k)*massNeutron/double(chains[j].charge)),2);\r\n\r\n                // get the P value for the m/z sse\r\n                startIndex = (chains[j].indexList.size()-minIsotopePeaks)*nPossibleChargeStates*nSamples + (chains[j].charge-minCharge_)*nSamples;\r\n                simValues.assign(&simulatedSSEs[startIndex],&simulatedSSEs[startIndex+nSamples-1]);\r\n                i1 = upper_bound(simValues.begin(),simValues.end(),sse); // returns iterator to first value that's > sse\n                int mzVectorIndex = i1 - simValues.begin();\r\n                //////////////////////////////////////////////////////////////////////////////////////\r\n\r\n                //////////////////////////////////////////////////////////////////////////////////////\r\n                // now calculate the sum of intensity rank score\r\n                if ( nPeaks > maxNumberPeaks )\r\n                    throw runtime_error(\"[SpectrumList_chargeFromIsotope] nPeaks exceeds maxNumberPeaks for scoring.\");\r\n                int intensitySumRank = 0;\r\n                for (int k=0, kend=chains[j].indexList.size(); k < kend; k++)\r\n                {\r\n                    double intensity = peakIntensities[chains[j].indexList[k]];\r\n                    i1 = upper_bound(sortedPeakIntensities.begin(),sortedPeakIntensities.end(),intensity);\r\n                    //i1--;\r\n                    //int rank = nPeaks - (i1 - sortedPeakIntensities.begin()); // remember sortedPeakIntensities sorted from least to most intense\r\n                    //int rank = nPeaks - 1 - (i1 - sortedPeakIntensities.begin()); // remember sortedPeakIntensities sorted from least to most intense\r\n                    int rank = (i1 - 1) - sortedPeakIntensities.begin();\r\n                    rank = nPeaks - rank;\r\n                    intensitySumRank += rank;\r\n                }\r\n                startIndex = (nPeaks - minNumberPeaks)*nIsotopePeakPossibilities*nSamples + (chains[j].indexList.size()-minIsotopePeaks)*nSamples;\r\n                \r\n                // need to know how many samples were generated in the event that N choose k was less than nSamples\r\n                int combos;\r\n                if ( nPeaks > 40 && chains[j].indexList.size() > 2 )\r\n                {\r\n                    combos = nSamples;\r\n                }\r\n                else\r\n                {\r\n                    int combinations = nChoosek(nPeaks,chains[j].indexList.size());\r\n                    combos = combinations > nSamples ? nSamples : combinations;\r\n                }\r\n                vector <int> simIntValues;\r\n                simIntValues.assign(&simulatedIntensityRankSum[startIndex],&simulatedIntensityRankSum[startIndex+combos-1]);\r\n                vector<int>::iterator i2 = upper_bound(simIntValues.begin(),simIntValues.end(),intensitySumRank); // returns iterator to first value that's > KLscore\n                int intensitySumVectorIndex = i2 - simIntValues.begin();\r\n                //////////////////////////////////////////////////////////////////////////////////////\r\n                //////////////////////////////////////////////////////////////////////////////////////\r\n\r\n                // probability of having lower sse by random chance\r\n                scores[j].mzPvalue = double(mzVectorIndex+1) / double(nSamples+1);\r\n                // K-L score is listed above\r\n                scores[j].intensitySumPvalue = double(intensitySumVectorIndex) / double(combos); // don't add one here because we cannot beat the top rank sum\r\n                scores[j].overallPvalue = scores[j].mzPvalue * scores[j].intensityPvalue * scores[j].intensitySumPvalue;\r\n                scores[j].chainIndex = allChainsCnt++;\r\n\r\n                chainIt++;\r\n\r\n            } // end for through all chains\r\n\r\n            allChains.insert(allChains.end(),chains.begin(),chains.end());\r\n            allScores.insert(allScores.end(),scores.begin(),scores.end());\r\n\r\n        } // end if chains.size() > 0\r\n         \r\n    } // end for over parent spectra\r\n\r\n    if ( allScores.size() > 0 )\r\n    {\r\n\r\n        // rank scoring data structures, first by m/z\r\n        sort(allScores.begin(),allScores.end(),sortScoresByMZ);\r\n        for (int j=0, jend=allScores.size(); j < jend; ++j) allScores[j].mzRank = j+1;\r\n\r\n        // now rank by relative intensity K-L score\r\n        sort(allScores.begin(),allScores.end(),sortScoresByKLScore); \r\n        for (int j=0, jend=allScores.size(); j < jend; ++j) allScores[j].intensityRank = j+1;\r\n\r\n        // now rank by intensity rank sum score\r\n        sort(allScores.begin(),allScores.end(),sortScoresByIntensitySum);\r\n        for (int j=0, jend=allScores.size(); j < jend; ++j) allScores[j].intensitySumRank = j+1;\r\n\r\n        // sum all the ranks\r\n        for (int j=0, jend=allScores.size(); j < jend; ++j)\r\n            allScores[j].sumRanks = allScores[j].mzRank + allScores[j].intensityRank + allScores[j].intensitySumRank;\r\n\r\n        // Finally, sort by the sum of ranks. This appears to work better than \r\n        // sorting by the overall p-value.\r\n        sort(allScores.begin(),allScores.end(),sortScoresBySumOfRanks);\r\n\r\n\r\n        int j,jend;\r\n        int scoreListLength = allScores.size();\r\n        int bestChainIndex = -1;\r\n        for (j=0, jend = scoreListLength > nChainsCheck_ ? nChainsCheck_ : scoreListLength; j < jend; ++j)\r\n        {\r\n            if ( allScores[j].intensityPvalue < sigVal_ )\r\n            {\r\n                bestChainIndex = allScores[j].chainIndex;\r\n                break;\r\n            }\r\n        }\r\n\r\n        \r\n        if ( bestChainIndex != -1 )\r\n        {\r\n\r\n            double mzTolppm = 100.0;\r\n            double mzTolparts = mzTolppm / 1000000.0;\r\n            // search for longer version of chain\r\n            bool updateChain = true;\r\n            while ( updateChain )\r\n            {\r\n                updateChain = false;\r\n                for (int k=j+1, kend = scoreListLength > nChainsCheck_ ? nChainsCheck_ : scoreListLength; k < kend; ++k)\r\n                {\r\n\r\n                    if ( allScores[k].intensityPvalue > sigVal_ ) continue; \r\n                    //\r\n                    // trying to match chain x-y-z to w-x-y-z\r\n                    //\r\n                    // what's acceptable?\r\n                    // have: x-y-z\r\n                    //     - match: w-x-y-z, w-x-y\r\n                    //     - not a match: w-x\r\n                    //\r\n                    // have x-y\r\n                    //     - match: w-x-y\r\n                    //     - not a match w-x\r\n                    //\r\n                    // So basically require at least two m/z matches to the chain you want to replace\r\n                    //\r\n                    //\r\n                    int mapIndexK = allScores[k].chainIndex;\r\n                    if ( allChains[bestChainIndex].charge != allChains[mapIndexK].charge ) continue;\r\n                    int largeChainSize = allChains[mapIndexK].indexList.size();\r\n                    if ( largeChainSize < 3 ) continue;\r\n\r\n                    bool relatedChains = true;\r\n                    double epsilon = mzTolparts * allMZs[allChains[mapIndexK].parentIndex][allChains[mapIndexK].indexList[0]];\r\n                    for ( int w=0; w < 2; ++w )\r\n                    {\r\n                        double smallChainMZ = allMZs[allChains[bestChainIndex].parentIndex][allChains[bestChainIndex].indexList[w]];\r\n                        double largeChainMZ = allMZs[allChains[mapIndexK].parentIndex][allChains[mapIndexK].indexList[w+1]];\r\n                        if ( abs( smallChainMZ - largeChainMZ ) > epsilon )\r\n                        {\r\n                                relatedChains = false;\r\n                                break;\r\n                        }\r\n                    }\r\n                    \r\n                    if ( relatedChains )\r\n                    {\r\n                            updateChain = true;\r\n                            bestChainIndex = mapIndexK;\r\n                            j = k;\r\n                            break;\r\n                    } // end if relatedChains\r\n                } // loop over remaining chains\r\n            } // while update chain\r\n\r\n            assignedCharge = allChains[bestChainIndex].charge;\r\n            assignedMZ = allMZs[allChains[bestChainIndex].parentIndex][allChains[bestChainIndex].indexList[0]];\r\n\r\n        } // endif best chain != -1\r\n\r\n    }\r\n\r\n    // make sure the possible charge states are erased if we want to override vendor charges\r\n    if (override_ && !possibleChargeStates.empty())\r\n                cvParams.erase(boost::range::remove_if(cvParams, CVParamIs(MS_possible_charge_state)));\r\n\r\n    if ( assignedCharge != 0 ) // output single charge and m/z value\r\n    {\r\n        cvParams.push_back(CVParam(override_ ? MS_charge_state : MS_possible_charge_state, assignedCharge));\r\n        s->precursors[0].selectedIons[0].set(MS_selected_ion_m_z, assignedMZ);\r\n    }\r\n    else if ( defaultChargeMin_ > 0 ) // output default charges, if requested by user\r\n    {\r\n        for (int z = defaultChargeMin_; z <= defaultChargeMax_; ++z)\r\n            if (!possibleChargeStates.contains(z) && z != 1)\r\n                cvParams.push_back(CVParam(MS_possible_charge_state, z));\r\n    }\r\n\r\n    return s;\r\n}\r\n\r\nvoid SpectrumList_ChargeFromIsotope::getMS1RetentionTimes()\r\n{\r\n    //cout << \"Turbocharger initialization, storing and sorting survey scans by retention time. This may take a few minutes for large files.\" << endl << endl;\r\n\r\n    int nScans = inner_->size();\r\n    MS1retentionTimes.reserve( nScans );\r\n    vector <int> ms1Indices;\r\n    for (int i=0,iend=nScans; i<iend; ++i)\r\n    {\r\n\r\n        // Using FullMetadata rather than FullData avoids invoking nested filters unnecessarily\r\n        DetailLevel detailLevel = DetailLevel_FullMetadata;\r\n        SpectrumPtr s = inner_->spectrum(i,detailLevel);\r\n\r\n        // Waters: scanConfig refers to the function number\r\n        // Thermo: scanConfig corresponds to the msLevel\r\n        // Agilent: scanConfig always returns zero\r\n        // AB Sciex: scanConfig corresponds to the experiment number (for each \"cycle\" there is a MS1\r\n        //           scan and then a variable number of MS2s...the MS1 is experiment 1 and then all\r\n        //           subsequent scans are 2,3,4,...)\r\n        // Bruker: untested\r\n        if ( s->scanList.scans[0].empty() )\r\n        {\r\n            throw runtime_error(\"SpectrumList_chargeFromIsotope: no scanEvent present in raw data!\");\r\n        }\r\n        int scanConfig = s->scanList.scans[0].cvParam(MS_preset_scan_configuration).valueAs<int>();\r\n        if ( scanConfig == 0 )\r\n        {\r\n            int level = s->cvParam(MS_ms_level).valueAs<int>();\r\n            if ( level != 1 ) continue;\r\n        }\r\n        else if ( scanConfig != 1 ) continue; \r\n\r\n        double rTime = s->scanList.scans[0].cvParam(MS_scan_start_time).timeInSeconds();\r\n        rtimeMap newRtime; newRtime.rtime = rTime; newRtime.indexMap = i;\r\n        MS1retentionTimes.push_back(newRtime);\r\n    }\r\n    int surveyCnt = MS1retentionTimes.size();\r\n    if ( surveyCnt == 0 )\r\n        throw runtime_error(\"[SpectrumList_chargeFromIsotope] No survey scan found!\");\r\n    sort(MS1retentionTimes.begin(),MS1retentionTimes.end(),sortByRetentionTime); // these are generally already sorted, but just in case\r\n}\r\n\r\nvoid SpectrumList_ChargeFromIsotope::simulateSSE(const int nCharges,const int nIsotopePeakPossibilities)\r\n{\r\n    // generate a sample of random spacings to simulate the distribution\r\n    // of summed square errors in m/z space due to random variations\r\n    simulatedSSEs.resize( nSamples*nCharges*nIsotopePeakPossibilities, 0.0 );\r\n\r\n    for (int i=0; i < nIsotopePeakPossibilities; ++i)\r\n    {\r\n\r\n        int chainLength = i + minIsotopePeaks;\r\n\r\n        for (int w=0; w<nCharges; ++w)\r\n        {\r\n\r\n            int charge = minCharge_+w;\r\n            vector <double> spacings(nSamples,0.0);\r\n    \r\n            for (int j=0; j<nSamples ; ++j)\r\n            {\r\n                vector <double> mzPoints(chainLength,0.0);\r\n                double averageMonoisotope = 0.0;\r\n                for (int k=1; k < chainLength; ++k)\r\n                {\r\n                    double theoreticalMZ = double(k) * massNeutron / double(charge);\r\n                    double randomVar = -mzTol + ( (double)rand() / RAND_MAX ) * 2 * mzTol; // between -mzTol and +mzTol\r\n                    mzPoints[k] = theoreticalMZ + randomVar;\r\n                    averageMonoisotope += randomVar;\r\n                }\r\n                averageMonoisotope /= double(chainLength);\r\n\r\n                double sse = 0.0;\r\n                for (int k=0; k < chainLength; ++k)\r\n                {\r\n                    sse += pow( averageMonoisotope - (mzPoints[k] - double(k)*massNeutron/double(charge)),2);\r\n                }\r\n                spacings[j] = sse;\r\n\r\n            } // end for over nSamples\r\n            sort(spacings.begin(),spacings.end());\r\n            int startIndex = i * nCharges * nSamples + w * nSamples;\r\n            for (int j=0; j<nSamples ; ++j) simulatedSSEs[startIndex+j] = spacings[j];\r\n        } // end for over nCharges\r\n    } // end for over maxIsotopePeaks \r\n\r\n}\r\n\r\nvoid SpectrumList_ChargeFromIsotope::simulateKL(const double finalRetentionTime,const int nIsotopePeakPossibilities,const int nMS1sims)\r\n{\r\n\r\n    // grab nine survey scans from which to perform simulations\r\n    vector <int> nineMS1indices(nMS1sims,-1);\r\n    for (int i=1; i<=nMS1sims; i++) \r\n    {\r\n        double rTime = double(i) * finalRetentionTime / double(nMS1sims+1);\r\n        vector< rtimeMap >::iterator i1 = upper_bound(MS1retentionTimes.begin(),MS1retentionTimes.end(),rTime,rtimeComparator); // returns iterator to first value that's > rTime\r\n        int nearestMS1scanVectorIndex;\r\n        if ( i1 == MS1retentionTimes.begin() )\r\n            nearestMS1scanVectorIndex = 0;\r\n        else\r\n            nearestMS1scanVectorIndex = (i1 - 1) - MS1retentionTimes.begin();\r\n        if (nearestMS1scanVectorIndex<0) nearestMS1scanVectorIndex = 0;\r\n        nineMS1indices[i-1] = MS1retentionTimes[nearestMS1scanVectorIndex].indexMap; \r\n    }\r\n\r\n    ///////////////////////////////////////////////\r\n    // now simulate the K-L score\r\n    simulatedKLs.resize( nIsotopePeakPossibilities * nSamples, 0.0 );\r\n    SpectrumListPtr CWTpeakPicker = instantiatePeakPicker( nineMS1indices );\r\n    vector < vector<double> > allIntensity, allMZ;\r\n    vector < vector<int> > mostIntensePeaks;\r\n    int numberIntensePeaks = 200;\r\n    \r\n    for (int i=0,iend=nineMS1indices.size(); i < iend ; ++i)\r\n    {\r\n            \r\n        SpectrumPtr s = CWTpeakPicker->spectrum( i, true ); // this applies no filtering \r\n        BinaryData<double> peakIntensities = s->getIntensityArray()->data;\r\n        BinaryData<double> peakMZs = s->getMZArray()->data;\r\n\r\n        allIntensity.push_back( peakIntensities );\r\n        allMZ.push_back( peakMZs );\r\n\r\n        vector<double> sortedPeakIntensities = peakIntensities;\r\n        sort( sortedPeakIntensities.begin(), sortedPeakIntensities.end() );\r\n        double intensityCutoff = 0.0;\r\n        int MS1Peaks = sortedPeakIntensities.size();\r\n        if ( MS1Peaks >= numberIntensePeaks )\r\n            intensityCutoff = sortedPeakIntensities[ peakIntensities.size() - numberIntensePeaks ];\r\n\r\n        vector<int> highIntensityIndices;\r\n        for (int j=0, jend=peakIntensities.size(); j < jend; ++j)\r\n        {\r\n            if ( peakIntensities[j] >= intensityCutoff )\r\n                highIntensityIndices.push_back(j);\r\n        }\r\n\r\n        mostIntensePeaks.push_back( highIntensityIndices );\r\n\r\n    }\r\n\r\n    for (int j=0; j < nIsotopePeakPossibilities; ++j)\r\n    {\r\n\r\n        int chainLength = j + minIsotopePeaks;\r\n        vector <double> poolA(chainLength,0.0);\r\n        vector <double> poolB(chainLength,0.0);\r\n        vector <double> KLscores(nSamples,0.0);\r\n\r\n        for (int k=0; k<nSamples; ++k)\r\n        {\r\n\r\n            // get a random spectrum\r\n            int randomSpectrum = rand() % nMS1sims; // random spectrum index between 0 and 8\r\n            int peakCnt = allMZ[randomSpectrum].size();\r\n            vector<double> peakMZs(peakCnt), peakIntensities(peakCnt);\r\n            for ( int w=0, wend = peakMZs.size(); w < wend; ++w )\r\n            {\r\n                peakMZs[w] = allMZ[randomSpectrum][w];\r\n                peakIntensities[w] = allIntensity[randomSpectrum][w];\r\n            }\r\n\r\n            int randomPeakIndex = rand() % mostIntensePeaks[randomSpectrum].size(); // from 0 to .size()-1\r\n            int randomMZpoint = mostIntensePeaks[randomSpectrum][randomPeakIndex];\r\n            double targetMZvalue = peakMZs[randomMZpoint];\r\n    \r\n            std::vector<double>::iterator lowerLimit = lower_bound( peakMZs.begin(), peakMZs.end(), targetMZvalue - defaultIsolationWidth_ );\r\n            lowerLimit = lowerLimit == peakMZs.end() ? peakMZs.begin() : lowerLimit; // in case value is out of bounds\r\n            std::vector<double>::iterator upperLimit = lower_bound( peakMZs.begin(), peakMZs.end(), targetMZvalue + defaultIsolationWidth_ + upperLimitPadding );\r\n            upperLimit = upperLimit == peakMZs.end() ? peakMZs.end() - 1 : upperLimit; // in case value is out of bounds\r\n\r\n\r\n            vector <double> windowIntensity, windowMZ;\r\n            windowMZ.assign( lowerLimit, upperLimit );\r\n\r\n            // this is possible if we chose the last peak of the spetrum and there is nothing around it\r\n            if ( windowMZ.size() == 0 ) // no peaks found\r\n            {\r\n                KLscores[k] = 100; // just apply a really bad KL score\r\n                continue;\r\n            }\r\n\r\n            int lowerLimitInt = lowerLimit - peakMZs.begin(), upperLimitInt = upperLimit - peakMZs.begin(); // convert iterators to ints\r\n            windowIntensity.assign( &peakIntensities[lowerLimitInt], &peakIntensities[upperLimitInt] );\r\n\r\n            // remove any zero-intensity peaks, which will lead to NAN results in KL scoring\r\n            vector<double>::iterator winIt = windowIntensity.begin();\r\n            while ( winIt != windowIntensity.end() )\r\n            {\r\n                if ( *winIt == 0.0 )\r\n                {\r\n                    windowIntensity.erase( winIt );\r\n                    int mzIndex = winIt - windowIntensity.begin();\r\n                    windowMZ.erase( windowMZ.begin() + mzIndex );\r\n                }\r\n                else\r\n                {\r\n                    ++winIt;\r\n                }\r\n            }\r\n\r\n            // filter the peaks\r\n            int peaksInWindow = windowIntensity.size();\r\n            while ( peaksInWindow > maxNumberPeaks ) \r\n            {\r\n\r\n                vector<double>::iterator minIt = min_element( windowIntensity.begin(), windowIntensity.end() );\r\n                vector<double>::iterator maxIt = max_element( windowIntensity.begin(), windowIntensity.end() );\r\n                vector<int> elementsForDeletion;\r\n\r\n                for (int w=0, wend = windowIntensity.size(); w < wend; ++w)\r\n                {\r\n                    if ( windowIntensity[w] < *maxIt * 0.05 )\r\n                        elementsForDeletion.push_back( w );\r\n                    else if ( windowIntensity[w] == *minIt )\r\n                        elementsForDeletion.push_back( w ); // remove if element equal to min or \r\n                }\r\n    \r\n                sort(elementsForDeletion.rbegin(), elementsForDeletion.rend());\r\n                for (int elementToDelete : elementsForDeletion)\r\n                {\r\n                    windowIntensity.erase( windowIntensity.begin() + elementToDelete );\r\n                    windowMZ.erase( windowMZ.begin() + elementToDelete );\r\n                }\r\n\r\n                peaksInWindow = windowIntensity.size();\r\n\r\n            }\r\n\r\n            int windowSize = windowIntensity.size();\r\n            isotopeChain localChain;\r\n            localChain.charge = rand() % ( maxCharge_ - minCharge_ + 1 ) + minCharge_; // goes from minCharge_ to maxCharge_\r\n\r\n            vector<int> randomIndicesInWindow( chainLength );\r\n\r\n            for (int w=0; w<chainLength; ++w) randomIndicesInWindow[ w ] = rand() % windowSize;\r\n            sort( randomIndicesInWindow.begin(), randomIndicesInWindow.end() );\r\n            for (int w=0; w<chainLength; ++w) localChain.indexList.push_back( randomIndicesInWindow[w] );\r\n            KLscores[k] = getKLscore( localChain, windowMZ, windowIntensity );\r\n\r\n        }\r\n        sort(KLscores.begin(),KLscores.end());\r\n        int startIndex = j * nSamples;\r\n        for (int k=0; k<nSamples ; ++k) simulatedKLs[startIndex+k] = KLscores[k];\r\n\r\n\r\n    }\r\n        \r\n}\r\n\r\nvoid SpectrumList_ChargeFromIsotope::simulateTotIntensity(const int nIsotopePeakPossibilities)\r\n{\r\n    \r\n    // If there are fewer than 10,000 possible combinations of peaks, then\r\n    // enumerate the combinations manually. Otherwise sample 10,000 random\r\n    // combinations to approximate the distribution.\r\n    \r\n    int peakNumber = maxNumberPeaks - minNumberPeaks + 1;\r\n    simulatedIntensityRankSum.resize( nIsotopePeakPossibilities * nSamples * peakNumber, 0 );\r\n\r\n    for (int nPeaks = minNumberPeaks; nPeaks <= maxNumberPeaks; ++nPeaks)\r\n    {\r\n\r\n        int maxRandomRank = nPeaks;\r\n\r\n        for (int w=0; w < nIsotopePeakPossibilities; ++w)\r\n        {\r\n    \r\n            int chainLength = w + minIsotopePeaks;\r\n            if (chainLength > nPeaks) break;\r\n\r\n            int combinations; int sampleSize;\r\n            if ( nPeaks > 40 && chainLength > 2 )\r\n            {\r\n                // all possible combinations could be too large to be held by a normal int\r\n                combinations = nSamples;\r\n            }\r\n            else\r\n            {\r\n                combinations = nChoosek(nPeaks,chainLength);\r\n            }\r\n            sampleSize = combinations > nSamples ? nSamples : combinations;\r\n            vector <int> intensityRankSum(sampleSize,0);\r\n\r\n            if ( combinations >= nSamples ) // sample nSamples random combinations\r\n            {\r\n\r\n                for (int j=0; j<nSamples ; ++j)\r\n                {\r\n\r\n                    for (int k=0; k<chainLength; ++k)\r\n                    {\r\n                        int randomRank = rand() % maxRandomRank + 1; // generates random int between 1 and maxRandomRank\r\n                        intensityRankSum[j] += randomRank;\r\n                    }\r\n\r\n                } // end for over nSamples\r\n            }\r\n            else // enumerate all possible combinations\r\n            {\r\n                int combinationCnt=0;\r\n                vector<bool> v(nPeaks);\r\n                fill(v.begin() + chainLength, v.end(), true);\r\n                do {\r\n                    for (int j = 0; j < nPeaks; ++j) {\r\n                        if (!v[j]) {\r\n                            intensityRankSum[combinationCnt] += j+1;\r\n                        }\r\n                    }\r\n                    combinationCnt++;\r\n                } while (next_permutation(v.begin(), v.end()));\r\n            }\r\n            \r\n            sort(intensityRankSum.begin(),intensityRankSum.end());\r\n            int startIndex = (nPeaks-minNumberPeaks)*nIsotopePeakPossibilities*nSamples + w * nSamples;\r\n            for (int j=0; j<sampleSize ; ++j) simulatedIntensityRankSum[startIndex+j] = intensityRankSum[j];\r\n        \r\n        } // end for over maxIsotopePeaks \r\n\r\n    } // end for over nPeaks\r\n\r\n}\r\n\r\nvoid SpectrumList_ChargeFromIsotope::getParentIndices( const SpectrumPtr s, vector <int> & parents ) const\r\n{\r\n    int nMS1scans = MS1retentionTimes.size();\r\n\r\n    if ( nMS1scans > 0 )\r\n    {\r\n        int parentCnt = 0;\r\n        double rTime = s->scanList.scans[0].cvParam(MS_scan_start_time).timeInSeconds();\n        vector< rtimeMap >::const_iterator i1 = upper_bound(MS1retentionTimes.begin(),MS1retentionTimes.end(),rTime,rtimeComparator); // returns iterator to first value that's > rTime\n\n\t\tint nearestMS1scanVectorIndex;\n\t\tif ( i1 == MS1retentionTimes.begin() )\n\t\t\tnearestMS1scanVectorIndex = 0;\n\t\telse\n\t\t\tnearestMS1scanVectorIndex = (i1 - 1) - MS1retentionTimes.begin();\n\n        while (nearestMS1scanVectorIndex >= 0 && parentCnt < parentsBefore_)\n        {\n            parents.push_back(MS1retentionTimes[nearestMS1scanVectorIndex].indexMap);\n            nearestMS1scanVectorIndex--;\n            parentCnt++;\n        }\n        nearestMS1scanVectorIndex = i1 - MS1retentionTimes.begin();\n        parentCnt = 0; // resetting this\n        //while (i1 != MS1retentionTimes.end() && parentCnt < parentsAfter_)\n        while (nearestMS1scanVectorIndex < nMS1scans && parentCnt < parentsAfter_)\n        {\n            parents.push_back(MS1retentionTimes[nearestMS1scanVectorIndex].indexMap);\n            //i1--;\n            nearestMS1scanVectorIndex++;\n            parentCnt++;\n        }\n\r\n    }\r\n}\r\n\r\nvoid SpectrumList_ChargeFromIsotope::getParentPeaks(const SpectrumPtr s,const vector <int> & parents,const double targetIsoMZ,const double lowerIsoWidth,const double upperIsoWidth,\r\n                                                    vector< vector <double> > & mzs,vector< vector <double> > & intensities) const\r\n{\r\n\r\n    // grab the peaks from the parent scans\r\n    for (int i=0, iend=parents.size(); i < iend; ++i)\r\n    {\r\n\r\n        vector< int > currentParent(1,parents[i]);\r\n        DetailLevel detailLevel = DetailLevel_FullMetadata;\r\n        SpectrumPtr sSurvey = inner_->spectrum(parents[i], detailLevel);\r\n        vector<CVParam>& cvParams = sSurvey->cvParams;\n        vector<CVParam>::iterator itr;\n        itr = std::find(cvParams.begin(), cvParams.end(), MS_centroid_spectrum);\r\n\r\n        if ( itr != cvParams.end() ) // MS1 spectrum already centroided, just grab the peaks in the isolation window\r\n        {\r\n\r\n            SpectrumPtr sPar = inner_->spectrum( parents[i], true );\r\n            BinaryData<double>& peakMZs = sPar->getMZArray()->data;\r\n            BinaryData<double>& peakIntensities = sPar->getIntensityArray()->data;\r\n            vector<int> elementsForDeletion;\r\n\r\n            for (int j=0, jend = peakIntensities.size(); j < jend; ++j)\r\n            {\r\n                if ( peakMZs[j] < targetIsoMZ - lowerIsoWidth || peakMZs[j] > targetIsoMZ + upperIsoWidth + upperLimitPadding )\r\n                    elementsForDeletion.push_back( j );\r\n            }\r\n    \r\n            sort(elementsForDeletion.rbegin(), elementsForDeletion.rend());\r\n            for (int elementToDelete : elementsForDeletion)\r\n            {\r\n                peakIntensities.erase( peakIntensities.begin() + elementToDelete );\r\n                peakMZs.erase( peakMZs.begin() + elementToDelete );\r\n            }\r\n\n            /**\n            Reduce number of peaks in window to maxNumberPeaks if needed \n            **/\n            int peaksInWindow = peakIntensities.size();\n            while ( peaksInWindow > maxNumberPeaks ) \r\n            {\r\n\r\n                BinaryData<double>::iterator minIt = min_element( peakIntensities.begin(), peakIntensities.end() );\r\n\r\n                elementsForDeletion.clear();\r\n                for (int w=0, wend = peakIntensities.size(); w < wend; ++w)\r\n                {\r\n                    if ( peakIntensities[w] == *minIt )\r\n                        elementsForDeletion.push_back( w ); \n                }\r\n    \r\n                sort(elementsForDeletion.rbegin(), elementsForDeletion.rend());\r\n                for (int elementToDelete : elementsForDeletion)\r\n                {\r\n                    peakIntensities.erase( peakIntensities.begin() + elementToDelete );\r\n                    peakMZs.erase( peakMZs.begin() + elementToDelete );\r\n                }\r\n\r\n                peaksInWindow = peakIntensities.size();\r\n\r\n            }\r\n\r\n            mzs.push_back( peakMZs );\r\n            intensities.push_back( peakIntensities );\r\n\r\n\r\n        }\r\n        else // need to perform CWT peak-picking to grab the peaks\r\n        {\r\n\r\n            SpectrumListPtr parentPeakPicker = instantiatePeakPicker( currentParent, targetIsoMZ, lowerIsoWidth, upperIsoWidth + upperLimitPadding ); // add an additional dalton on the right to check for heavy isotopes; don't let monoisotope exceed the isolation window, though. See below.\r\n            SpectrumPtr sPar = parentPeakPicker->spectrum( 0, true );\r\n            BinaryData<double>& peakMZs = sPar->getMZArray()->data;\r\n            BinaryData<double>& peakIntensities = sPar->getIntensityArray()->data;\r\n\r\n            BinaryData<double>::iterator minIt = min_element(peakIntensities.begin(), peakIntensities.end());\r\n            BinaryData<double>::iterator maxIt = max_element(peakIntensities.begin(), peakIntensities.end());\r\n            vector<int> elementsForDeletion;\r\n\r\n            for (int j=0, jend = peakIntensities.size(); j < jend; ++j)\r\n            {\r\n                if ( peakIntensities[j] < *maxIt * 0.05 )\r\n                    elementsForDeletion.push_back( j );\r\n                else if ( peakIntensities[j] == *minIt )\r\n                    elementsForDeletion.push_back( j ); // remove if element equal to min or \r\n            }\r\n\r\n            sort(elementsForDeletion.rbegin(), elementsForDeletion.rend());\r\n            for (int elementToDelete : elementsForDeletion)\r\n            {\r\n                peakIntensities.erase( peakIntensities.begin() + elementToDelete);\r\n                peakMZs.erase( peakMZs.begin() + elementToDelete);\r\n            }\r\n\r\n            /**\n            Reduce number of peaks in window to maxNumberPeaks if needed \n            **/\n            int peaksInWindow = peakIntensities.size();\n            while ( peaksInWindow > maxNumberPeaks ) \r\n            {\r\n\r\n                BinaryData<double>::iterator minIt = min_element( peakIntensities.begin(), peakIntensities.end() );\r\n\r\n                elementsForDeletion.clear();\r\n                for (int w=0, wend = peakIntensities.size(); w < wend; ++w)\r\n                {\r\n                    if ( peakIntensities[w] == *minIt )\r\n                        elementsForDeletion.push_back( w ); \n                }\r\n    \r\n                sort(elementsForDeletion.rbegin(), elementsForDeletion.rend());\r\n                for (int elementToDelete : elementsForDeletion)\r\n                {\r\n                    peakIntensities.erase( peakIntensities.begin() + elementToDelete );\r\n                    peakMZs.erase( peakMZs.begin() + elementToDelete);\r\n                }\r\n\r\n                peaksInWindow = peakIntensities.size();\r\n\r\n            }\r\n\r\n            mzs.push_back( peakMZs );\r\n            intensities.push_back( peakIntensities );\r\n        }\r\n\r\n    }\r\n}\r\n\r\nSpectrumListPtr SpectrumList_ChargeFromIsotope::instantiatePeakPicker( const vector <int> & indices ) const\r\n{\r\n    shared_ptr<SpectrumListSimple> smallSpectrumList(new SpectrumListSimple);\r\n\r\n    for (int i=0,iend=indices.size(); i < iend ; ++i)\r\n    {\r\n        SpectrumPtr sParent = inner_->spectrum( indices[i], true);\r\n        smallSpectrumList->spectra.push_back(sParent);\r\n    }\r\n\r\n    string msLevelSets = \"1\";\r\n    IntegerSet msLevelsToCentroid;\n    msLevelsToCentroid.parse(msLevelSets);\r\n    bool preferVendor = false;\r\n    double snr = 0.0;\r\n    double mzTol = 0.05;\r\n    int fixedPeaksKeep = 0; // this is for generating peaks to simulate the K-L score\r\n    SpectrumListPtr parentPeakPicker(new SpectrumList_PeakPicker(smallSpectrumList, \r\n                                        PeakDetectorPtr(new CwtPeakDetector(snr,fixedPeaksKeep,mzTol)),\r\n                                        preferVendor, msLevelsToCentroid ) );\r\n\r\n    return parentPeakPicker;\r\n\r\n}\r\n\r\n\r\n\r\nSpectrumListPtr SpectrumList_ChargeFromIsotope::instantiatePeakPicker( const vector <int> & indices, const double targetIsoMZ, \r\n    const double lowerIsoWidth, const double upperIsoWidth ) const\r\n{\r\n\r\n    shared_ptr<SpectrumListSimple> smallSpectrumList(new SpectrumListSimple);\r\n\r\n    // parameters for re-sampling via linear interpolation\r\n    SpectrumPtr s = inner_->spectrum( indices[0], true);\r\n    vector<double> summedIntensity;\r\n    vector<double> summedMZ;\r\n\r\n    // Grab the binary data for the parent spectrum\r\n    SpectrumPtr sParent = inner_->spectrum( indices[0], true);\r\n    BinaryData<double>& parentMz = sParent->getMZArray()->data;\n    BinaryData<double>& parentIntensity = sParent->getIntensityArray()->data;\r\n\r\n    // Get window of data around the target m/z value\r\n    vector<double> windowMZ,windowIntensity;\r\n    BinaryData<double>::iterator lowerLimit = lower_bound(parentMz.begin(), parentMz.end(), targetIsoMZ - lowerIsoWidth);\r\n    lowerLimit = lowerLimit == parentMz.end() ? parentMz.begin() : lowerLimit; // in case value is out of bounds\r\n    BinaryData<double>::iterator upperLimit = lower_bound(parentMz.begin(), parentMz.end(), targetIsoMZ + upperIsoWidth);\r\n    upperLimit = upperLimit == parentMz.end() ? parentMz.end() - 1 : upperLimit; // in case value is out of bounds\r\n    windowMZ.assign( lowerLimit, upperLimit );\r\n            \r\n    if ( windowMZ.size() > 1 )\r\n    {\r\n\r\n        int lowerLimitInt = lowerLimit - parentMz.begin(), upperLimitInt = upperLimit - parentMz.begin(); // convert interators to ints\r\n        windowIntensity.assign( &parentIntensity[lowerLimitInt], &parentIntensity[upperLimitInt] );\r\n\r\n        summedMZ.assign( lowerLimit, upperLimit );\r\n        summedIntensity.assign( &parentIntensity[lowerLimitInt], &parentIntensity[upperLimitInt] );\r\n\r\n    }\r\n                \r\n    // Now fill in the spectrum data structure that will be fed to the peak-picker\r\n    smallSpectrumList->spectra.push_back(SpectrumPtr(new Spectrum));\r\n    Spectrum& pSpec = *smallSpectrumList->spectra[0];\r\n    pSpec.index = 0;\r\n    pSpec.set(MS_ms_level, 1);\r\n    pSpec.set(MS_profile_spectrum);\r\n    BinaryDataArrayPtr pSpec_mz(new BinaryDataArray), pSpec_intensity(new BinaryDataArray);\r\n    pSpec_mz->set(MS_m_z_array, \"\", MS_m_z), pSpec_intensity->set(MS_intensity_array, \"\", MS_number_of_detector_counts);\r\n    pSpec_mz->data.resize( summedIntensity.size() ), pSpec_intensity->data.resize( summedIntensity.size() );\r\n\r\n    for (size_t j=0, jend=summedIntensity.size() ; j < jend; ++j)\r\n    {\r\n        pSpec_mz->data[j] = summedMZ[j];\r\n        pSpec_intensity->data[j] = summedIntensity[j];\r\n    }\r\n    \r\n    pSpec.binaryDataArrayPtrs.push_back( pSpec_mz ), pSpec.binaryDataArrayPtrs.push_back( pSpec_intensity );\r\n    pSpec.defaultArrayLength = pSpec_mz->data.size();\r\n\r\n    string msLevelSets = \"1\";\r\n    IntegerSet msLevelsToCentroid;\n    msLevelsToCentroid.parse(msLevelSets);\r\n    bool preferVendor = false;\r\n    double snr = 0.0;\r\n    double mzTol = 0.05;\r\n    int fixedPeaksKeep = maxNumberPeaks;\r\n    SpectrumListPtr parentPeakPicker(new SpectrumList_PeakPicker(smallSpectrumList, \r\n                                        PeakDetectorPtr(new CwtPeakDetector(snr,fixedPeaksKeep,mzTol)),\r\n                                        preferVendor, msLevelsToCentroid ) );\r\n\r\n    return parentPeakPicker;\r\n\r\n}\r\n\r\n\r\n} // namespace analysis\r\n} // namespace pwiz\r\n\r\n\r\nint nChoosek(int n,int k)\r\n{\r\n    int numerator=1;\r\n    int denominator=1;\r\n    // Multiplicative formula\r\n    for (int i=0;i<k;++i)\r\n    {\r\n        numerator *= n-i;\r\n        denominator *= i+1;\r\n    }\r\n    return numerator/denominator;\r\n}\r\n\r\ndouble getKLscore( const isotopeChain chain, const vector <double> & mzs, const vector <double> & intensities )\r\n{\r\n\r\n    if ( mzs.size() != intensities.size() )\r\n         throw runtime_error(\"[SpectrumList_chargeFromIsotope, getKLscore] m/z and intensity vectors must be equal in size.\");\r\n\r\n\t//cout << \"computing the KL score\" << endl;\r\n\r\n    // First, convert from molecular weight of ion to Mstar, which is linear mapping \r\n    double lambda = 1.0 / 1800.0; // parameter for poisson model\r\n    double Mstar = lambda * mzs[chain.indexList[0]] * double(chain.charge); // from msInspect paper\r\n    double Mexp = exp( -Mstar );\r\n                    \r\n    double poissonSum = 0.0; // sum up all the poisson values to normalize\r\n    double observedIntensitySum = 0.0; // initialize this sum\r\n    double KLscore = 0.0;\r\n\r\n    vector <double> poissonVals(chain.indexList.size(),0.0);\r\n\r\n    // calculate poisson distribution and sum up the intensities for normalization\r\n    for (int k=0,kend=chain.indexList.size(); k < kend ; ++k)\r\n    {\r\n        // probability of seeing isotope with k additional ions relative to monoisotope\r\n        double poisson = Mexp * pow(Mstar,k);\r\n        for (int w=k;w>1;w--) poisson /= double(w);\r\n        poissonVals[k] = poisson; // store value\r\n\r\n        // sums for normalization\r\n        poissonSum += poisson;\r\n        observedIntensitySum += intensities[chain.indexList[k]];\r\n    }\r\n\r\n    // calculate the K-L score\r\n    for (int k=0,kend=chain.indexList.size(); k < kend ; ++k)\r\n    {\r\n        poissonVals[k] /= poissonSum; // normalize these values to use in the K-L score\r\n        double normObservedIntensity = intensities[chain.indexList[k]] / observedIntensitySum;\r\n        KLscore += normObservedIntensity * log10( normObservedIntensity / poissonVals[k]  );\r\n    }\r\n\r\n\t//cout << \"done computing the KL score\" << endl;\r\n\r\n    return KLscore;\r\n\r\n\r\n}", "meta": {"hexsha": "70c2b2bf84451fc5b4ff30f4a642596d467bd89c", "size": 50327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/analysis/spectrum_processing/SpectrumList_ChargeFromIsotope.cpp", "max_stars_repo_name": "vagisha/pwiz", "max_stars_repo_head_hexsha": "aa65186bf863cdebde3d15c293d137085365bead", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz/analysis/spectrum_processing/SpectrumList_ChargeFromIsotope.cpp", "max_issues_repo_name": "vagisha/pwiz", "max_issues_repo_head_hexsha": "aa65186bf863cdebde3d15c293d137085365bead", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/analysis/spectrum_processing/SpectrumList_ChargeFromIsotope.cpp", "max_forks_repo_name": "vagisha/pwiz", "max_forks_repo_head_hexsha": "aa65186bf863cdebde3d15c293d137085365bead", "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.9537117904, "max_line_length": 290, "alphanum_fraction": 0.5798279254, "num_tokens": 11655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733338565660004, "lm_q2_score": 0.02262919834398717, "lm_q1q2_score": 0.00921762797615102}}
{"text": "//-----------------------------------------------------------------------------\n// Created on: 28 November 2016\n//-----------------------------------------------------------------------------\n// Copyright (c) 2017, Sergey Slyadnev\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//    * Neither the name of the copyright holder(s) nor the\n//      names of all 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 THE AUTHORS OR CONTRIBUTORS 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// Own include\n#include <asiAlgo_BaseCloud.h>\n\n// asiAlgo includes\n#include <asiAlgo_PointCloudUtils.h>\n\n// OpenCascade includes\n#include <gp_Ax1.hxx>\n#include <gp_Ax3.hxx>\n#include <gp_Vec.hxx>\n\n// Eigen includes\n#include <Eigen/Dense>\n\n// Instantiate for allowed types\ntemplate class asiAlgo_BaseCloud<double>;\ntemplate class asiAlgo_BaseCloud<float>;\n\n//-----------------------------------------------------------------------------\n\nnamespace\n{\n  bool compare(const std::pair<double, int>& p1,\n               const std::pair<double, int>& p2)\n  {\n    return p1.first > p2.first;\n  }\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nasiAlgo_BaseCloud<TCoordType>::asiAlgo_BaseCloud() {}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nasiAlgo_BaseCloud<TCoordType>::asiAlgo_BaseCloud(const std::vector<TCoordType>& coords)\n: m_coords(coords) {}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::CopyTo(asiAlgo_BaseCloud<TCoordType>& copy) const\n{\n  copy.m_coords = m_coords;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::Reserve(const int nElems)\n{\n  m_coords.resize(nElems*3);\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nint asiAlgo_BaseCloud<TCoordType>::GetNumberOfElements() const\n{\n  return (int) (m_coords.size() / 3);\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nbool asiAlgo_BaseCloud<TCoordType>::IsEmpty() const\n{\n  return m_coords.size() == 0;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::AddElement(const TCoordType x,\n                                               const TCoordType y,\n                                               const TCoordType z)\n{\n  m_coords.push_back(x);\n  m_coords.push_back(y);\n  m_coords.push_back(z);\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::AddElement(const gp_XYZ& xyz)\n{\n  this->AddElement( TCoordType( xyz.X() ), TCoordType( xyz.Y() ), TCoordType( xyz.Z() ) );\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::AddElement(const gp_Pnt& xyz)\n{\n  this->AddElement( TCoordType( xyz.X() ), TCoordType( xyz.Y() ), TCoordType( xyz.Z() ) );\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::SetElement(const int        elemIndex,\n                                               const TCoordType x,\n                                               const TCoordType y,\n                                               const TCoordType z)\n{\n  m_coords[elemIndex*3 + 0] = x;\n  m_coords[elemIndex*3 + 1] = y;\n  m_coords[elemIndex*3 + 2] = z;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::GetElement(const int   elemIndex,\n                                               TCoordType& x,\n                                               TCoordType& y,\n                                               TCoordType& z) const\n{\n  x = m_coords[3*elemIndex + 0];\n  y = m_coords[3*elemIndex + 1];\n  z = m_coords[3*elemIndex + 2];\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\ngp_XYZ asiAlgo_BaseCloud<TCoordType>::GetElement(const int elemIndex) const\n{\n  TCoordType x, y, z;\n  this->GetElement(elemIndex, x, y, z);\n\n  return gp_XYZ(x, y, z);\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nconst std::vector<TCoordType>& asiAlgo_BaseCloud<TCoordType>::GetCoords() const\n{\n  return m_coords;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nHandle(TColStd_HArray1OfReal) asiAlgo_BaseCloud<TCoordType>::GetCoordsArray() const\n{\n  return asiAlgo_PointCloudUtils::AsRealArray(this);\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nstd::vector<TCoordType>& asiAlgo_BaseCloud<TCoordType>::ChangeCoords()\n{\n  return m_coords;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::ComputeBoundingBox(TCoordType& xMin, TCoordType& xMax,\n                                                       TCoordType& yMin, TCoordType& yMax,\n                                                       TCoordType& zMin, TCoordType& zMax) const\n{\n  TCoordType _xMin = std::numeric_limits<TCoordType>::max();\n  TCoordType _yMin = _xMin;\n  TCoordType _zMin = _xMin;\n  TCoordType _xMax = std::numeric_limits<TCoordType>::min();\n  TCoordType _yMax = _xMax;\n  TCoordType _zMax = _xMax;\n\n  const int nElems = this->GetNumberOfElements();\n  //\n  for ( int e = 0; e < nElems; ++e )\n  {\n    TCoordType x, y, z;\n    this->GetElement(e, x, y, z);\n\n    if ( x > _xMax )\n      _xMax = x;\n    if ( x < _xMin )\n      _xMin = x;\n    if ( y > _yMax )\n      _yMax = y;\n    if ( y < _yMin )\n      _yMin = y;\n    if ( z > _zMax )\n      _zMax = z;\n    if ( z < _zMin )\n      _zMin = z;\n  }\n\n  xMin = _xMin;\n  xMax = _xMax;\n  yMin = _yMin;\n  yMax = _yMax;\n  zMin = _zMin;\n  zMax = _zMax;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nHandle(asiAlgo_BaseCloud<TCoordType>)\n  asiAlgo_BaseCloud<TCoordType>::ExtractRegion(const asiAlgo_CloudRegion& region) const\n{\n  // Extracted base cloud\n  Handle(asiAlgo_BaseCloud<TCoordType>) result  = new asiAlgo_BaseCloud<TCoordType>;\n\n  // Extract\n  for ( asiAlgo_CloudRegion::Iterator it(region); it.More(); it.Next() )\n  {\n    const int pidx = it.Key();\n\n    TCoordType x, y, z;\n    this->GetElement(pidx, x, y, z);\n    result->AddElement(x, y, z);\n  }\n\n  return result;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::Merge(const Handle(asiAlgo_BaseCloud<TCoordType>)& cloud)\n{\n  const int nElems2Add = cloud->GetNumberOfElements();\n  //\n  for ( int e = 0; e < nElems2Add; ++e )\n  {\n    TCoordType x, y, z;\n    cloud->GetElement(e, x, y, z);\n\n    this->AddElement(x, y, z);\n  }\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nbool asiAlgo_BaseCloud<TCoordType>::ComputeInertiaAxes(gp_Ax3& axes) const\n{\n  TCoordType xCenter = 0.0;\n  TCoordType yCenter = 0.0;\n  TCoordType zCenter = 0.0;\n  TCoordType x, y, z;\n  gp_XYZ meanVertex;\n\n  for ( int i = 0; i < this->GetNumberOfElements(); ++i )\n  {\n    this->GetElement(i, x, y, z);\n    xCenter += x;\n    yCenter += y;\n    zCenter += z;\n  }\n\n  meanVertex.SetX(xCenter);\n  meanVertex.SetY(yCenter);\n  meanVertex.SetZ(zCenter);\n  meanVertex /= this->GetNumberOfElements();\n\n  Eigen::Matrix3d C;\n  for (int j = 0; j < 3; ++j)\n  {\n    for (int k = 0; k < 3; ++k)\n      C(j, k) = 0.0; // TODO: is that necessary?\n  }\n\n  for (int i = 0; i < this->GetNumberOfElements(); ++i)\n  {\n    this->GetElement(i, x, y, z);\n    gp_XYZ p = gp_XYZ(x, y, z);\n    gp_XYZ p_dash = p - meanVertex;\n\n    for (int j = 0; j < 3; ++j)\n    {\n      for (int k = 0; k < 3; ++k)\n        C(j, k) += p_dash.Coord(j + 1) * p_dash.Coord(k + 1);\n    }\n  }\n\n  for (int j = 0; j < 3; ++j)\n  {\n    for (int k = 0; k < 3; ++k)\n      C(j, k) /= (this->GetNumberOfElements());\n  }\n\n  Eigen::EigenSolver<Eigen::Matrix3d> EigenSolver(C);\n\n  Eigen::Vector3d v[3] { EigenSolver.eigenvectors().col(0).real(),\n                         EigenSolver.eigenvectors().col(1).real(),\n                         EigenSolver.eigenvectors().col(2).real() };\n\n  // Make result stable. Eigen may return vector multiplied by -1.0 for \n  // almost equivalent matrices with deviations (1e-14).\n  for (int i = 0; i < 3; ++i)\n  {\n    Eigen::Vector3d& vec = v[i];\n\n    int maxId = -1;\n    double maxValue = -1.0;\n    for (int j = 0; j < 3; ++j)\n    {\n      const double value = Abs(vec(j));\n      if (value > maxValue)\n      {\n        maxId = j;\n        maxValue = value;\n      }\n    }\n    if (vec[maxId] < 0.0)\n      vec *= -1.0;\n  }\n\n  gp_Vec V[3] = { gp_Vec(v[0].x(), v[0].y(), v[0].z()),\n                  gp_Vec(v[1].x(), v[1].y(), v[1].z()),\n                  gp_Vec(v[2].x(), v[2].y(), v[2].z()) };\n\n  std::vector< std::pair<double, int> >\n    lambda{ std::pair<double, int>(EigenSolver.eigenvalues()(0).real(), 0),\n            std::pair<double, int>(EigenSolver.eigenvalues()(1).real(), 1),\n            std::pair<double, int>(EigenSolver.eigenvalues()(2).real(), 2) };\n  //\n  std::sort(lambda.begin(), lambda.end(), compare);\n  //\n  gp_Ax1 axisX(meanVertex, V[lambda[0].second]);\n  gp_Ax1 axisY(meanVertex, V[lambda[1].second]);\n  gp_Ax1 axisZ(meanVertex, V[lambda[2].second]);\n\n  // Check if the system is right-handed\n  const double ang = axisX.Direction().AngleWithRef(axisY.Direction(), axisZ.Direction());\n  if (ang < 0)\n    axisZ.Reverse();\n\n  axes = gp_Ax3( meanVertex, axisZ.Direction(), axisX.Direction() );\n\n  return true;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nvoid asiAlgo_BaseCloud<TCoordType>::Clear()\n{\n  m_coords.clear();\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nbool asiAlgo_BaseCloud<TCoordType>::Load(const char* filename)\n{\n  std::ifstream FILE(filename);\n  if ( !FILE.is_open() )\n    return false;\n\n  while ( !FILE.eof() )\n  {\n    char str[256];\n    FILE.getline(str, 256);\n\n    std::vector<std::string> tokens;\n    std::istringstream iss(str);\n    std::copy( std::istream_iterator<std::string>(iss),\n               std::istream_iterator<std::string>(),\n               std::back_inserter< std::vector<std::string> >(tokens) );\n\n    if ( tokens.empty() || tokens.size() < 3 )\n      continue;\n\n    TCoordType x = (TCoordType) ( atof(tokens[0].c_str()) ),\n               y = (TCoordType) ( atof(tokens[1].c_str()) ),\n               z = (TCoordType) ( atof(tokens[2].c_str()) );\n\n    this->AddElement(x, y, z);\n  }\n\n  FILE.close();\n  return true;\n}\n\n//-----------------------------------------------------------------------------\n\ntemplate <typename TCoordType>\nbool asiAlgo_BaseCloud<TCoordType>::SaveAs(const char* filename) const\n{\n  std::ofstream FILE(filename);\n  if ( !FILE.is_open() )\n    return false;\n\n  for ( int e = 0; e < this->GetNumberOfElements(); ++e )\n  {\n    TCoordType x, y, z;\n    this->GetElement(e, x, y, z);\n\n    FILE << x << \" \" << y << \" \" << z << \"\\n\";\n  }\n\n  FILE.close();\n  return true;\n}\n", "meta": {"hexsha": "cfd23858f575da7e0136963707f9d7b88bd3020e", "size": 13033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/asiAlgo/points/asiAlgo_BaseCloud.cpp", "max_stars_repo_name": "CadQuery/AnalysisSitus", "max_stars_repo_head_hexsha": "f3b379ca9158325a21e50fefba8133cab51d9cd9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-04T01:36:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T07:11:01.000Z", "max_issues_repo_path": "src/asiAlgo/points/asiAlgo_BaseCloud.cpp", "max_issues_repo_name": "CadQuery/AnalysisSitus", "max_issues_repo_head_hexsha": "f3b379ca9158325a21e50fefba8133cab51d9cd9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asiAlgo/points/asiAlgo_BaseCloud.cpp", "max_forks_repo_name": "CadQuery/AnalysisSitus", "max_forks_repo_head_hexsha": "f3b379ca9158325a21e50fefba8133cab51d9cd9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-25T18:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T18:14:30.000Z", "avg_line_length": 29.823798627, "max_line_length": 96, "alphanum_fraction": 0.5295020333, "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.02161533272325623, "lm_q1q2_score": 0.009215083070022478}}
{"text": "/**********************************************************************************/\n/* This file is part of spla project                                              */\n/* https://github.com/JetBrains-Research/spla                                     */\n/**********************************************************************************/\n/* MIT License                                                                    */\n/*                                                                                */\n/* Copyright (c) 2021 JetBrains-Research                                          */\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 SPLA_SPLAMERGEBYKEY_HPP\n#define SPLA_SPLAMERGEBYKEY_HPP\n\n#include <functional>\n\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/detail/meta_kernel.hpp>\n#include <boost/hana.hpp>\n\nnamespace spla {\n\n    /**\n     * @addtogroup Internal\n     * @{\n     */\n\n    namespace detail {\n        class MergeByKeyPathKernel : public boost::compute::detail::meta_kernel {\n        public:\n            unsigned int tileSize;\n\n            MergeByKeyPathKernel()\n                : meta_kernel(\"__spla_merge_path\"), tileSize(4) {}\n\n            template<\n                    typename OutputIterator1, typename OutputIterator2,\n                    typename BinaryIndicesOperator>\n            void SetRange(const std::size_t aCount,\n                          const std::size_t bCount,\n                          OutputIterator1 resultA,\n                          OutputIterator2 resultB,\n                          BinaryIndicesOperator isFirstGt) {\n                namespace compute = boost::compute;\n                using compute::uint_;\n\n                mACount = aCount;\n                mACountArg = add_arg<uint_>(\"a_count\");\n\n                mBCount = bCount;\n                mBCountArg = add_arg<uint_>(\"b_count\");\n\n                *this << \"uint i = get_global_id(0);\\n\"\n                      << \"uint target = (i+1)*\" << tileSize << \";\\n\"\n                      << \"uint start = max(convert_int(0),convert_int(target)-convert_int(b_count));\\n\"\n                      << \"uint end = min(target,a_count);\\n\"\n                      << \"uint a_index, b_index;\\n\"\n                      << \"while(start<end)\\n\"\n                      << \"{\\n\"\n                      << \"   a_index = (start + end)/2;\\n\"\n                      << \"   b_index = target - a_index - 1;\\n\"\n                      << \"   if(!(\";\n                isFirstGt(*this, expr<uint_>(\"a_index\"), expr<uint_>(\"b_index\"));\n                *this << \"))\\n\"\n                      << \"       start = a_index + 1;\\n\"\n                      << \"   else end = a_index;\\n\"\n                      << \"}\\n\"\n                      << resultA[expr<uint_>(\"i\")] << \" = start;\\n\"\n                      << resultB[expr<uint_>(\"i\")] << \" = target - start;\\n\";\n            }\n\n            boost::compute::event exec(boost::compute::command_queue &queue) {\n                namespace compute = boost::compute;\n\n                if ((mACount + mBCount) / tileSize == 0) {\n                    return {};\n                }\n\n                set_arg(mACountArg, compute::uint_(mACount));\n                set_arg(mBCountArg, compute::uint_(mBCount));\n\n                return exec_1d(queue, 0, (mACount + mBCount) / tileSize);\n            }\n\n        private:\n            std::size_t mACount{};\n            std::size_t mACountArg{};\n            std::size_t mBCount{};\n            std::size_t mBCountArg{};\n        };\n\n        class SerialMergeByKeyKernel : boost::compute::detail::meta_kernel {\n        public:\n            unsigned int tileSize;\n\n            SerialMergeByKeyKernel()\n                : meta_kernel(\"__spla_serial_merge\"),\n                  tileSize(4) {}\n\n            template<\n                    typename InputIterator1,\n                    typename InputIterator2,\n                    typename Operator1,\n                    typename Operator2,\n                    typename Operator3>\n            void SetRange(InputIterator1 tile_first1,\n                          InputIterator1 tile_last1,\n                          InputIterator2 tile_first2,\n                          Operator1 writeIsSecondGt,\n                          Operator2 writeAssignResultToFirst,\n                          Operator3 writeAssignResultToSecond) {\n                namespace compute = boost::compute;\n                using compute::uint_;\n\n                mCount = compute::detail::iterator_range_size(tile_first1, tile_last1) - 1;\n\n                *this << \"uint i = get_global_id(0);\\n\"\n                      << \"uint start1 = \" << tile_first1[expr<uint_>(\"i\")] << \";\\n\"\n                      << \"uint end1 = \" << tile_first1[expr<uint_>(\"i+1\")] << \";\\n\"\n                      << \"uint start2 = \" << tile_first2[expr<uint_>(\"i\")] << \";\\n\"\n                      << \"uint end2 = \" << tile_first2[expr<uint_>(\"i+1\")] << \";\\n\"\n                      << \"uint index = i*\" << tileSize << \";\\n\"\n                      << \"while(start1<end1 && start2<end2)\\n\"\n                      << \"{\\n\"\n                      << \"   if(!(\";\n                writeIsSecondGt(*this, expr<uint_>(\"start1\"), expr<uint_>(\"start2\"));\n                *this << \"))\\n\"\n                      << \"   {\\n\";\n                writeAssignResultToFirst(*this, expr<uint_>(\"index\"), expr<uint_>(\"start1\"));\n                *this << \";\\n\"\n                      << \"       index++;\\n\"\n                      << \"       start1++;\\n\"\n                      << \"   }\\n\"\n                      << \"   else\\n\"\n                      << \"   {\\n\";\n                writeAssignResultToSecond(*this, expr<uint_>(\"index\"), expr<uint_>(\"start2\"));\n                *this << \";\\n\"\n                      << \"       index++;\\n\"\n                      << \"       start2++;\\n\"\n                      << \"   }\\n\"\n                      << \"}\\n\"\n                      << \"while(start1<end1)\\n\"\n                      << \"{\\n\";\n                writeAssignResultToFirst(*this, expr<uint_>(\"index\"), expr<uint_>(\"start1\"));\n                *this << \";\\n\"\n                      << \"   index++;\\n\"\n                      << \"   start1++;\\n\"\n                      << \"}\\n\"\n                      << \"while(start2<end2)\\n\"\n                      << \"{\\n\";\n                writeAssignResultToSecond(*this, expr<uint_>(\"index\"), expr<uint_>(\"start2\"));\n                *this << \";\\n\"\n                      << \"   index++;\\n\"\n                      << \"   start2++;\\n\"\n                      << \"}\\n\";\n            }\n\n            boost::compute::event exec(boost::compute::command_queue &queue) {\n                if (mCount == 0) {\n                    return boost::compute::event{};\n                }\n\n                return exec_1d(queue, 0, mCount);\n            }\n\n        private:\n            std::size_t mCount{};\n        };\n\n        template<\n                typename Operator1,\n                typename Operator2,\n                typename Operator3>\n        std::ptrdiff_t MergeByKey(\n                const std::size_t count1,\n                const std::size_t count2,\n                Operator1 compareFirstToSecond,\n                Operator2 assignResultToFirst,\n                Operator3 assignResultToSecond,\n                boost::compute::command_queue &queue) {\n            namespace compute = boost::compute;\n            using compute::uint_;\n\n            const std::size_t tileSize = 1024;\n\n            compute::vector<uint_> tileA((count1 + count2 + tileSize - 1) / tileSize + 1, queue.get_context());\n            compute::vector<uint_> tileB((count1 + count2 + tileSize - 1) / tileSize + 1, queue.get_context());\n\n            // Tile the sets\n            MergeByKeyPathKernel tilingKernel;\n            tilingKernel.tileSize = static_cast<unsigned int>(tileSize);\n            tilingKernel.SetRange(count1, count2, tileA.begin() + 1, tileB.begin() + 1, compareFirstToSecond);\n            fill_n(tileA.begin(), 1, uint_(0), queue);\n            fill_n(tileB.begin(), 1, uint_(0), queue);\n            tilingKernel.exec(queue);\n\n            fill_n(tileA.end() - 1, 1, static_cast<uint_>(count1), queue);\n            fill_n(tileB.end() - 1, 1, static_cast<uint_>(count2), queue);\n\n            // Merge\n            SerialMergeByKeyKernel mergeKernel;\n            mergeKernel.tileSize = static_cast<unsigned int>(tileSize);\n            mergeKernel.SetRange(tileA.begin(), tileA.end(), tileB.begin(),\n                                 compareFirstToSecond, assignResultToFirst, assignResultToSecond);\n\n            mergeKernel.exec(queue);\n\n            return static_cast<std::ptrdiff_t>(count1 + count2);\n        }\n\n        namespace binop {\n            using MetaKernel = boost::compute::detail::meta_kernel;\n            using MetaIdx = boost::compute::detail::meta_kernel_variable<boost::compute::uint_>;\n\n            template<typename ItA, typename ItB>\n            class IsFirstGt {\n                ItA a;\n                ItB b;\n\n            public:\n                explicit IsFirstGt(ItA itA, ItB itB) : a(std::move(itA)), b(std::move(itB)) {}\n\n                void operator()(MetaKernel &k, const MetaIdx &iFst, const MetaIdx &iSnd) {\n                    k << a[iFst] << \" > \" << b[iSnd];\n                }\n            };\n\n            template<typename ItA, typename ItB, typename ItC, typename ItD>\n            class IsFirstPairGt {\n                ItA aFst;\n                ItB aSnd;\n                ItC bFst;\n                ItD bSnd;\n\n            public:\n                explicit IsFirstPairGt(ItA itAFst, ItB itASnd, ItC itBFst, ItD itBSnd)\n                    : aFst(std::move(itAFst)), aSnd(std::move(itASnd)), bFst(std::move(itBFst)), bSnd(std::move(itBSnd)) {}\n\n                void operator()(MetaKernel &k, const MetaIdx &iFst, const MetaIdx &iSnd) {\n                    k << aFst[iFst] << \" > \" << bFst[iSnd] << \" || \"\n                      << \"(\"\n                      << aFst[iFst] << \" == \" << bFst[iSnd] << \" && \"\n                      << aSnd[iFst] << \" > \" << bSnd[iSnd]\n                      << \")\";\n                }\n            };\n\n            template<typename... Assignees>\n            class Assign {\n                boost::hana::tuple<Assignees...> mToAssign;\n\n            public:\n                explicit Assign(Assignees... toAssign)\n                    : mToAssign(toAssign...) {}\n\n                void operator()(MetaKernel &k, const MetaIdx &iRes, const MetaIdx &i) {\n                    boost::hana::for_each(mToAssign, [&](auto &p) {\n                        k << p.first[iRes] << \" = \" << p.second[i] << \";\";\n                    });\n                }\n            };\n        }// namespace binop\n\n\n    }// namespace detail\n\n    /**\n     * @brief Merges two sorted (by key) sequences of values by given keys.\n     *\n     * @param keysABegin Begin of the first key sequence\n     * @param keysAEnd End of the first key sequence\n     * @param valuesA Begin of the first value sequence\n     * @param keysBBegin Begin of the second key sequence\n     * @param keysBEnd End of the second key sequence\n     * @param valuesB Begin of the second value sequence\n     * @param keysResult Begin of the keys result\n     * @param valuesResult Begin of the values result\n     * @param queue OpenCL Command queue\n     *\n     * @return Size of the merged sequence\n     */\n    template<\n            typename ItKeysABegin,\n            typename ItKeysAEnd,\n            typename ItValuesA,\n            typename ItKeysBBegin,\n            typename ItKeysBEnd,\n            typename ItValuesB,\n            typename ItKeysResult,\n            typename ItValuesResult>\n    inline std::ptrdiff_t MergeByKeys(\n            ItKeysABegin keysABegin,\n            ItKeysAEnd keysAEnd,\n            ItValuesA valuesA,\n            ItKeysBBegin keysBBegin,\n            ItKeysBEnd keysBEnd,\n            ItValuesB valuesB,\n            ItKeysResult keysResult,\n            ItValuesResult valuesResult,\n            boost::compute::command_queue &queue) {\n\n        return detail::MergeByKey(\n                std::distance(keysABegin, keysAEnd),\n                std::distance(keysBBegin, keysBEnd),\n                detail::binop::IsFirstGt{keysABegin, keysBBegin},\n                detail::binop::Assign{std::pair{keysResult, keysABegin}, std::pair{valuesResult, valuesA}},\n                detail::binop::Assign{std::pair{keysResult, keysBBegin}, std::pair{valuesResult, valuesB}},\n                queue);\n    }\n\n    /**\n     * @brief Merges two sorted sequences.\n     *\n     * @param keysABegin Begin of the first sequence\n     * @param keysAEnd End of the first sequence\n     * @param keysBBegin Begin of the second sequence\n     * @param keysBEnd End of the second sequence\n     * @param keysResult Begin of the result\n     * @param queue OpenCL Command queue\n     *\n     * @return Size of the merged sequence\n     */\n    template<\n            typename ItKeysABegin,\n            typename ItKeysAEnd,\n            typename ItKeysBBegin,\n            typename ItKeysBEnd,\n            typename ItKeysResult>\n    inline std::ptrdiff_t MergeKeys(\n            ItKeysABegin keysABegin,\n            ItKeysAEnd keysAEnd,\n            ItKeysBBegin keysBBegin,\n            ItKeysBEnd keysBEnd,\n            ItKeysResult keysResult,\n            boost::compute::command_queue &queue) {\n\n        return detail::MergeByKey(\n                std::distance(keysABegin, keysAEnd),\n                std::distance(keysBBegin, keysBEnd),\n                detail::binop::IsFirstGt{keysABegin, keysBBegin},\n                detail::binop::Assign{std::pair{keysResult, keysABegin}},\n                detail::binop::Assign{std::pair{keysResult, keysBBegin}},\n                queue);\n    }\n\n    /**\n     * @brief Merges two sorted (by pair key)\n     *\n     * @desc In this function, key pair sequence is actually\n     * two sequences of keys. Hence, nth key of the first\n     * sequence is\n     * {@p keysFirstABegin[n], @p keysSecondABegin[n]},\n     * and of the second second is\n     * {@p keysFirstBBegin[n], @p keysSecondBBegin[n]}.\n     *\n     * @return Size of the merged sequence.\n     *\n     * @note Pair key - a key, which consists of two keys.\n     *       It is compared lexicographically: first it compares\n     *       by the first element, and then by the second.\n     */\n    template<\n            typename ItInput1,\n            typename ItInput2,\n            typename ItInput3,\n            typename ItInput4,\n            typename ItInput5,\n            typename ItInput6,\n            typename ItOutput1,\n            typename ItOutput2,\n            typename ItOutput3>\n    inline std::ptrdiff_t MergeByPairKeys(\n            ItInput1 keysFirstABegin, ItInput1 keysFirstAEnd, ItInput2 keysSecondABegin, ItInput3 valuesA,\n            ItInput4 keysFirstBBegin, ItInput4 keysFirstBEnd, ItInput5 keysSecondBBegin, ItInput6 valuesB,\n            ItOutput1 keysFirstOut, ItOutput2 keysSecondOut, ItOutput3 valuesOut,\n            boost::compute::command_queue &queue) {\n\n        return detail::MergeByKey(\n                std::distance(keysFirstABegin, keysFirstAEnd),\n                std::distance(keysFirstBBegin, keysFirstBEnd),\n                detail::binop::IsFirstPairGt{keysFirstABegin, keysSecondABegin, keysFirstBBegin, keysSecondBBegin},\n                detail::binop::Assign{\n                        std::pair{keysFirstOut, keysFirstABegin},\n                        std::pair{keysSecondOut, keysSecondABegin},\n                        std::pair{valuesOut, valuesA}},\n                detail::binop::Assign{\n                        std::pair{keysFirstOut, keysFirstBBegin},\n                        std::pair{keysSecondOut, keysSecondBBegin},\n                        std::pair{valuesOut, valuesB}},\n                queue);\n    }\n\n    /**\n     * @brief Merges two sorted (by pair key)\n     *\n     * @desc In this function, key pair sequence is actually\n     * two sequences of keys. Hence, nth key of the first\n     * sequence is\n     * {@p keysFirstABegin[n], @p keysSecondABegin[n]},\n     * and of the second second is\n     * {@p keysFirstBBegin[n], @p keysSecondBBegin[n]}.\n     *\n     * @return Size of the merged sequence.\n     *\n     * @note Pair key - a key, which consists of two keys.\n     *       It is compared lexicographically: first it compares\n     *       by the first element, and then by the second.\n     */\n    template<\n            typename ItInput1,\n            typename ItInput2,\n            typename ItInput4,\n            typename ItInput5,\n            typename ItOutput1,\n            typename ItOutput2>\n    inline std::ptrdiff_t MergePairKeys(\n            ItInput1 keysFirstABegin, ItInput1 keysFirstAEnd, ItInput2 keysSecondABegin,\n            ItInput4 keysFirstBBegin, ItInput4 keysFirstBEnd, ItInput5 keysSecondBBegin,\n            ItOutput1 keysFirstOut, ItOutput2 keysSecondOut,\n            boost::compute::command_queue &queue) {\n\n        return detail::MergeByKey(\n                std::distance(keysFirstABegin, keysFirstAEnd),\n                std::distance(keysFirstBBegin, keysFirstBEnd),\n                detail::binop::IsFirstPairGt{keysFirstABegin, keysSecondABegin, keysFirstBBegin, keysSecondBBegin},\n                detail::binop::Assign{std::pair{keysFirstOut, keysFirstABegin}, std::pair{keysSecondOut, keysSecondABegin}},\n                detail::binop::Assign{std::pair{keysFirstOut, keysFirstBBegin}, std::pair{keysSecondOut, keysSecondBBegin}},\n                queue);\n    }\n\n    /**\n     * @}\n     */\n\n}// namespace spla\n\n#endif//SPLA_SPLAMERGEBYKEY_HPP\n", "meta": {"hexsha": "2347573854a56eae4d11b244bedbec7e92de11cc", "size": 19022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/compute/SplaMergeByKey.hpp", "max_stars_repo_name": "Glebanister/spla", "max_stars_repo_head_hexsha": "6951af369e359827729fd12b08f5df0ba3dac8ef", "max_stars_repo_licenses": ["MIT"], "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/compute/SplaMergeByKey.hpp", "max_issues_repo_name": "Glebanister/spla", "max_issues_repo_head_hexsha": "6951af369e359827729fd12b08f5df0ba3dac8ef", "max_issues_repo_licenses": ["MIT"], "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/compute/SplaMergeByKey.hpp", "max_forks_repo_name": "Glebanister/spla", "max_forks_repo_head_hexsha": "6951af369e359827729fd12b08f5df0ba3dac8ef", "max_forks_repo_licenses": ["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.9911699779, "max_line_length": 124, "alphanum_fraction": 0.5027862475, "num_tokens": 4195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386099567919973, "lm_q2_score": 0.03622005222376973, "lm_q1q2_score": 0.009194858521078795}}
{"text": "// Copyright (C) 2004-2006 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n\n/**************************************************************************\n * This source file implements a variation on distributed Dijkstra's      *\n * algorithm that can expose additional parallelism by permitting         *\n * vertices within a certain distance from the minimum to be processed,   *\n * even though they may not be at their final distance. This can          *\n * introduce looping, but the algorithm will still terminate so long as   *\n * there are no negative loops.                                           *\n **************************************************************************/\n#ifndef BOOST_GRAPH_EAGER_DIJKSTRA_SHORTEST_PATHS_HPP\n#define BOOST_GRAPH_EAGER_DIJKSTRA_SHORTEST_PATHS_HPP\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <boost/assert.hpp>\n#include <boost/graph/distributed/detail/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/parallel/caching_property_map.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/graph/distributed/detail/remote_update_set.hpp>\n#include <vector>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/parallel/container_traits.hpp>\n\n#ifdef PBGL_ACCOUNTING\n#  include <boost/graph/accounting.hpp>\n#  include <numeric>\n#endif // PBGL_ACCOUNTING\n\n#ifdef MUTABLE_QUEUE\n#  include <boost/pending/mutable_queue.hpp>\n#endif\n\nnamespace boost { namespace graph { namespace distributed {\n\n#ifdef PBGL_ACCOUNTING\nstruct eager_dijkstra_shortest_paths_stats_t\n{\n  /* The value of the lookahead parameter. */\n  double lookahead;\n\n  /* Total wall-clock time used by the algorithm.*/\n  accounting::time_type execution_time;\n\n  /* The number of vertices deleted in each superstep. */\n  std::vector<std::size_t> deleted_vertices;\n\n  template<typename OutputStream>\n  void print(OutputStream& out)\n  {\n    double avg_deletions = std::accumulate(deleted_vertices.begin(),\n                                           deleted_vertices.end(),\n                                           0.0);\n    avg_deletions /= deleted_vertices.size();\n\n    out << \"Problem = \\\"Single-Source Shortest Paths\\\"\\n\"\n        << \"Algorithm = \\\"Eager Dijkstra\\\"\\n\"\n        << \"Function = eager_dijkstra_shortest_paths\\n\"\n        << \"(P) Lookahead = \" << lookahead << \"\\n\"\n        << \"Wall clock time = \" << accounting::print_time(execution_time)\n        << \"\\nSupersteps = \" << deleted_vertices.size() << \"\\n\"\n        << \"Avg. deletions per superstep = \" << avg_deletions << \"\\n\";\n  }\n};\n\nstatic eager_dijkstra_shortest_paths_stats_t eager_dijkstra_shortest_paths_stats;\n#endif\n\nnamespace detail {\n\n// Borrowed from BGL's dijkstra_shortest_paths\ntemplate <class UniformCostVisitor, class Queue,\n          class WeightMap, class PredecessorMap, class DistanceMap,\n          class BinaryFunction, class BinaryPredicate>\n struct parallel_dijkstra_bfs_visitor : bfs_visitor<>\n{\n  typedef typename property_traits<DistanceMap>::value_type distance_type;\n\n  parallel_dijkstra_bfs_visitor(UniformCostVisitor vis, Queue& Q,\n                                WeightMap w, PredecessorMap p, DistanceMap d,\n                                BinaryFunction combine, BinaryPredicate compare,\n                                distance_type zero)\n    : m_vis(vis), m_Q(Q), m_weight(w), m_predecessor(p), m_distance(d),\n      m_combine(combine), m_compare(compare), m_zero(zero)  { }\n\n  template <class Vertex, class Graph>\n  void initialize_vertex(Vertex u, Graph& g)\n    { m_vis.initialize_vertex(u, g); }\n  template <class Vertex, class Graph>\n  void discover_vertex(Vertex u, Graph& g) { m_vis.discover_vertex(u, g); }\n  template <class Vertex, class Graph>\n  void examine_vertex(Vertex u, Graph& g) { m_vis.examine_vertex(u, g); }\n\n  /* Since the eager formulation of Parallel Dijkstra's algorithm can\n     loop, we may relax on *any* edge, not just those associated with\n     white and gray targets. */\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        boost::throw_exception(negative_edge());\n\n    m_vis.examine_edge(e, g);\n\n    boost::parallel::caching_property_map<PredecessorMap> c_pred(m_predecessor);\n    boost::parallel::caching_property_map<DistanceMap> c_dist(m_distance);\n\n    distance_type old_distance = get(c_dist, target(e, g));\n\n    bool m_decreased = relax(e, g, m_weight, c_pred, c_dist,\n                             m_combine, m_compare);\n\n    /* On x86 Linux with optimization, we sometimes get into a\n       horrible case where m_decreased is true but the distance hasn't\n       actually changed. This occurs when the comparison inside\n       relax() occurs with the 80-bit precision of the x87 floating\n       point unit, but the difference is lost when the resulting\n       values are written back to lower-precision memory (e.g., a\n       double). With the eager Dijkstra's implementation, this results\n       in looping. */\n    if (m_decreased && old_distance != get(c_dist, 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  template <class Vertex, class Graph>\n  void finish_vertex(Vertex u, Graph& g) { m_vis.finish_vertex(u, g); }\n\n  UniformCostVisitor m_vis;\n  Queue& m_Q;\n  WeightMap m_weight;\n  PredecessorMap m_predecessor;\n  DistanceMap m_distance;\n  BinaryFunction m_combine;\n  BinaryPredicate m_compare;\n  distance_type m_zero;\n};\n\n  /**********************************************************************\n   * Dijkstra queue that implements arbitrary \"lookahead\"               *\n   **********************************************************************/\n  template<typename Graph, typename Combine, typename Compare,\n           typename VertexIndexMap, typename DistanceMap,\n           typename PredecessorMap>\n  class lookahead_dijkstra_queue\n    : public graph::detail::remote_update_set<\n               lookahead_dijkstra_queue<\n                 Graph, Combine, Compare, VertexIndexMap, DistanceMap,\n                 PredecessorMap>,\n               typename boost::graph::parallel::process_group_type<Graph>::type,\n               typename dijkstra_msg_value<DistanceMap, PredecessorMap>::type,\n               typename property_map<Graph, vertex_owner_t>::const_type>\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor\n      vertex_descriptor;\n    typedef lookahead_dijkstra_queue self_type;\n    typedef typename boost::graph::parallel::process_group_type<Graph>::type\n      process_group_type;\n    typedef dijkstra_msg_value<DistanceMap, PredecessorMap> msg_value_creator;\n    typedef typename msg_value_creator::type msg_value_type;\n    typedef typename property_map<Graph, vertex_owner_t>::const_type\n      OwnerPropertyMap;\n\n    typedef graph::detail::remote_update_set<self_type, process_group_type,\n                                             msg_value_type, OwnerPropertyMap>\n      inherited;\n\n    // Priority queue for tentative distances\n    typedef indirect_cmp<DistanceMap, Compare> queue_compare_type;\n\n    typedef typename property_traits<DistanceMap>::value_type distance_type;\n\n#ifdef MUTABLE_QUEUE\n    typedef mutable_queue<vertex_descriptor, std::vector<vertex_descriptor>,\n                          queue_compare_type, VertexIndexMap> queue_type;\n\n#else\n    typedef relaxed_heap<vertex_descriptor, queue_compare_type,\n                         VertexIndexMap> queue_type;\n#endif // MUTABLE_QUEUE\n\n    typedef typename process_group_type::process_id_type process_id_type;\n\n  public:\n    typedef vertex_descriptor value_type;\n\n    lookahead_dijkstra_queue(const Graph& g,\n                             const Combine& combine,\n                             const Compare& compare,\n                             const VertexIndexMap& id,\n                             const DistanceMap& distance_map,\n                             const PredecessorMap& predecessor_map,\n                             distance_type lookahead)\n      : inherited(boost::graph::parallel::process_group(g), get(vertex_owner, g)),\n        queue(num_vertices(g), queue_compare_type(distance_map, compare), id),\n        distance_map(distance_map),\n        predecessor_map(predecessor_map),\n        min_distance(0),\n        lookahead(lookahead)\n#ifdef PBGL_ACCOUNTING\n        , local_deletions(0)\n#endif\n    { }\n\n    void push(const value_type& x)\n    {\n      msg_value_type msg_value =\n        msg_value_creator::create(get(distance_map, x),\n                                  predecessor_value(get(predecessor_map, x)));\n      inherited::update(x, msg_value);\n    }\n\n    void update(const value_type& x) { push(x); }\n\n    void pop()\n    {\n      queue.pop();\n#ifdef PBGL_ACCOUNTING\n      ++local_deletions;\n#endif\n    }\n\n    value_type&       top()       { return queue.top(); }\n    const value_type& top() const { return queue.top(); }\n\n    bool empty()\n    {\n      inherited::collect();\n\n      // If there are no suitable messages, wait until we get something\n      while (!has_suitable_vertex()) {\n        if (do_synchronize()) return true;\n      }\n\n      // Return true only if nobody has any messages; false if we\n      // have suitable messages\n      return false;\n    }\n\n  private:\n    vertex_descriptor predecessor_value(vertex_descriptor v) const\n    { return v; }\n\n    vertex_descriptor\n    predecessor_value(property_traits<dummy_property_map>::reference) const\n    { return graph_traits<Graph>::null_vertex(); }\n\n    bool has_suitable_vertex() const\n    {\n      return (!queue.empty()\n              && get(distance_map, queue.top()) <= min_distance + lookahead);\n    }\n\n    bool do_synchronize()\n    {\n      using boost::parallel::all_reduce;\n      using boost::parallel::minimum;\n\n      inherited::synchronize();\n\n      // TBD: could use combine here, but then we need to stop using\n      // minimum<distance_type>() as the function object.\n      distance_type local_distance =\n        queue.empty()? (std::numeric_limits<distance_type>::max)()\n        : get(distance_map, queue.top());\n\n      all_reduce(this->process_group, &local_distance, &local_distance + 1,\n                 &min_distance, minimum<distance_type>());\n\n#ifdef PBGL_ACCOUNTING\n      std::size_t deletions = 0;\n      all_reduce(this->process_group, &local_deletions, &local_deletions + 1,\n                 &deletions, std::plus<std::size_t>());\n      if (process_id(this->process_group) == 0)\n        eager_dijkstra_shortest_paths_stats.deleted_vertices\n          .push_back(deletions);\n      local_deletions = 0;\n      BOOST_ASSERT(deletions > 0);\n#endif\n\n      return min_distance == (std::numeric_limits<distance_type>::max)();\n    }\n\n  public:\n    void\n    receive_update(process_id_type source, vertex_descriptor vertex,\n                   distance_type distance)\n    {\n      // Update the queue if the received distance is better than\n      // the distance we know locally\n      if (distance <= get(distance_map, vertex)) {\n\n        // Update the local distance map\n        put(distance_map, vertex, distance);\n\n        bool is_in_queue = queue.contains(vertex);\n\n        if (!is_in_queue)\n          queue.push(vertex);\n        else\n          queue.update(vertex);\n      }\n    }\n\n    void\n    receive_update(process_id_type source, vertex_descriptor vertex,\n                   std::pair<distance_type, vertex_descriptor> p)\n    {\n      if (p.first <= get(distance_map, vertex)) {\n        put(predecessor_map, vertex, p.second);\n        receive_update(source, vertex, p.first);\n      }\n    }\n\n  private:\n    queue_type     queue;\n    DistanceMap    distance_map;\n    PredecessorMap predecessor_map;\n    distance_type  min_distance;\n    distance_type  lookahead;\n#ifdef PBGL_ACCOUNTING\n    std::size_t    local_deletions;\n#endif\n  };\n  /**********************************************************************/\n} // end namespace detail\n\ntemplate<typename DistributedGraph, typename DijkstraVisitor,\n         typename PredecessorMap, typename DistanceMap, typename WeightMap,\n         typename IndexMap, typename ColorMap, typename Compare,\n         typename Combine, typename DistInf, typename DistZero>\nvoid\neager_dijkstra_shortest_paths\n  (const DistributedGraph& g,\n   typename graph_traits<DistributedGraph>::vertex_descriptor s,\n   PredecessorMap predecessor, DistanceMap distance,\n   typename property_traits<DistanceMap>::value_type lookahead,\n   WeightMap weight, IndexMap index_map, ColorMap color_map,\n   Compare compare, Combine combine, DistInf inf, DistZero zero,\n   DijkstraVisitor vis)\n{\n#ifdef PBGL_ACCOUNTING\n  eager_dijkstra_shortest_paths_stats.deleted_vertices.clear();\n  eager_dijkstra_shortest_paths_stats.lookahead = lookahead;\n  eager_dijkstra_shortest_paths_stats.execution_time = accounting::get_time();\n#endif\n\n  // Initialize local portion of property maps\n  typename graph_traits<DistributedGraph>::vertex_iterator ui, ui_end;\n  for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n    put(distance, *ui, inf);\n    put(predecessor, *ui, *ui);\n  }\n  put(distance, s, zero);\n\n  // Dijkstra Queue\n  typedef detail::lookahead_dijkstra_queue\n            <DistributedGraph, Combine, Compare, IndexMap, DistanceMap,\n             PredecessorMap> Queue;\n\n  Queue Q(g, combine, compare, index_map, distance,\n          predecessor, lookahead);\n\n  // Parallel Dijkstra visitor\n  detail::parallel_dijkstra_bfs_visitor\n    <DijkstraVisitor, Queue, WeightMap, PredecessorMap, DistanceMap, Combine,\n     Compare> bfs_vis(vis, Q, weight, predecessor, distance, combine, compare,\n                      zero);\n\n  set_property_map_role(vertex_color, color_map);\n  set_property_map_role(vertex_distance, distance);\n\n  breadth_first_search(g, s, Q, bfs_vis, color_map);\n\n#ifdef PBGL_ACCOUNTING\n  eager_dijkstra_shortest_paths_stats.execution_time =\n    accounting::get_time()\n    - eager_dijkstra_shortest_paths_stats.execution_time;\n#endif\n}\n\ntemplate<typename DistributedGraph, typename DijkstraVisitor,\n         typename PredecessorMap, typename DistanceMap, typename WeightMap>\nvoid\neager_dijkstra_shortest_paths\n  (const DistributedGraph& g,\n   typename graph_traits<DistributedGraph>::vertex_descriptor s,\n   PredecessorMap predecessor, DistanceMap distance,\n   typename property_traits<DistanceMap>::value_type lookahead,\n   WeightMap weight)\n{\n  typedef typename property_traits<DistanceMap>::value_type distance_type;\n\n  std::vector<default_color_type> colors(num_vertices(g), white_color);\n\n  eager_dijkstra_shortest_paths(g, s, predecessor, distance, lookahead, weight,\n                                get(vertex_index, g),\n                                make_iterator_property_map(&colors[0],\n                                                           get(vertex_index,\n                                                               g)),\n                                std::less<distance_type>(),\n                                closed_plus<distance_type>(),\n                                distance_type(),\n                                (std::numeric_limits<distance_type>::max)(),\n                                dijkstra_visitor<>());\n}\n\ntemplate<typename DistributedGraph, typename DijkstraVisitor,\n         typename PredecessorMap, typename DistanceMap>\nvoid\neager_dijkstra_shortest_paths\n  (const DistributedGraph& g,\n   typename graph_traits<DistributedGraph>::vertex_descriptor s,\n   PredecessorMap predecessor, DistanceMap distance,\n   typename property_traits<DistanceMap>::value_type lookahead)\n{\n  eager_dijkstra_shortest_paths(g, s, predecessor, distance, lookahead,\n                               get(edge_weight, g));\n}\n} // end namespace distributed\n\n#ifdef PBGL_ACCOUNTING\nusing distributed::eager_dijkstra_shortest_paths_stats;\n#endif\n\nusing distributed::eager_dijkstra_shortest_paths;\n\n} } // end namespace boost::graph\n\n#endif // BOOST_GRAPH_EAGER_DIJKSTRA_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "c6b03a225bedc3192ad7e399c3e75918e78a1e9e", "size": 16224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/graph/distributed/eager_dijkstra_shortest_paths.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/graph/distributed/eager_dijkstra_shortest_paths.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/graph/distributed/eager_dijkstra_shortest_paths.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": 36.7891156463, "max_line_length": 101, "alphanum_fraction": 0.6648175542, "num_tokens": 3438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.02635535141221375, "lm_q1q2_score": 0.009188664703146296}}
{"text": "#include \"stdafx.h\"\n#include <string>\n// mine\n#include \"pop.h\"\n#include \"params.h\"\n#include \"rnd.h\"\n#include \"data.h\"\n#include \"state.h\"\n#include \"logger.h\"\n\n#include \"InitPop.h\"\n#include \"FitnessEstimator.h\"\n#include \"Fitness.h\"\n#include \"Generation.h\"\n#include \"instructionset.h\"\n//#include \"omp.h\"\n#include \"Generationfns.h\"\n#include \"strdist.h\"\n#include <time.h>\n#include <cstring>\n#include \"p_archive.h\"\n#include \"Eqn2Line.h\"\n#include \"general_fns.h\"\n#include \"load_params.h\"\n#include \"load_data.h\"\n#include \"printing.h\"\n// #include \"runEllenGP.h\"\n//#define _CRTDBG_MAP_ALLOC\n//#include <stdlib.h>\n//#include <crtdbg.h>\n\nusing namespace std;\n#if defined(_WIN32)\n\t#include <direct.h>\n\t#define GetCurrentDir _getcwd\n#else\n\t#include <unistd.h>\n\t#include <iomanip>\n\t#define GetCurrentDir getcwd\n#endif\n\n// includes for python integration\n#include <boost/python.hpp>\nnamespace bp = boost::python;\n#include <numpy/ndarrayobject.h>\n//#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n// global parameters structure\n\nbool check_genty(vector<ind>& pop,params& p){\n\n\tfor(int count = 0; count<pop.size(); ++count)\n\t{\n\t\tfloat tmp = abs(pop[count].fitness-pop[count].fitness_v)/pop[count].fitness;\n\t\tif (pop.at(count).genty != tmp && pop.at(count).genty != p.max_fit)\n\t\t\treturn 0;\n\t}\n\treturn 1;\n}\nvoid printGenome(tribe& T,int gen,string& logname,Data& d,params& p)\n{\n\t// print genome to file in csv format\n\t// create Data file\n\t// print format: print in head-to-tail fashion with grid locations\n\t// x y gene\n\t// gene encoding: +:1,-:2,*:3,/:4,sin:5,cos:6,exp:7,log:8,constant:9,vars:10-length(vars)\n\n\t//total genes\n\t std::ofstream gout_all;\n\t std::ofstream gout_on;\n\t std::ofstream gout_off;\n\t string filename0 = logname.substr(0,logname.size()-4)+\"_g_all.csv.\"+std::to_string(static_cast<long long>(gen));\n\t gout_all.open(filename0);\n\t gout_all << \"x,y,fit,age,g,e\\n\";\n\t// on genes\n\t if (p.eHC_on){\n\n\t\t string filename = logname.substr(0,logname.size()-4)+\"_g_on.csv.\"+std::to_string(static_cast<long long>(gen));\n\t\t gout_on.open(filename);\n\t\t gout_on << \"x,y,fit,age,g,e\\n\";\n\t\t // off genes\n\n\t\t string filename2 = logname.substr(0,logname.size()-4)+\"_g_off.csv.\"+std::to_string(static_cast<long long>(gen));\n\t\t gout_off.open(filename2);\n\t\t gout_off << \"x,y,fit,age,g,e\\n\";\n\t }\n\t string out;\n\t string tmp;\n\t int k;\n\t float y,y_on, y_off;\n\t float max_fit=0;\n\t float min_fit=10000;\n\t float max_age=0;\n\t float min_age=100000;\n\t float max_line=0;\n\t float min_line = 1000;\n\t for (size_t i =0; i<T.pop.size(); ++i){\n\t\tif (log(1+T.pop[i].fitness)>max_fit) max_fit=log(1+T.pop[i].fitness);\n\t\tif (log(1+T.pop[i].fitness)<min_fit) min_fit=log(1+T.pop[i].fitness);\n\t\tif (T.pop[i].age>max_age) max_age=T.pop[i].age;\n\t\tif (T.pop[i].age<min_age) min_age=T.pop[i].age;\n\t\tfor (size_t j = 0; j<T.pop[i].line.size(); ++j){\n\t\t\tif (T.pop[i].line.size()>max_line) max_line=T.pop[i].line.size();\n\t\t\tif (T.pop[i].line.size()<min_line) min_line=T.pop[i].line.size();\n\t\t}\n\t}\n\tif(p.sel==4) T.sortpop_age();\n\telse T.sortpop();\n\n\t for (size_t i=0; i<T.pop.size(); ++i){\n\t\t y=0;\n\t\t y_on=0;\n\t\t y_off=0;\n\t\t for (int j=T.pop[i].line.size()-1; j>=0; --j){\n\t\t\t switch(T.pop[i].line[j].type){\n\t\t\t case '+':\n\t\t\t\t out=\"1\";\n\t\t\t\t break;\n\t\t\t case '-':\n\t\t\t\t out=\"2\";\n\t\t\t\t break;\n\t\t\t case '*':\n\t\t\t\t out=\"3\";\n\t\t\t\t break;\n\t\t\t case '/':\n\t\t\t\t out=\"4\";\n\t\t\t\t break;\n\t\t\t case 's':\n\t\t\t\t out=\"5\";\n\t\t\t\t break;\n\t\t\t case 'c':\n\t\t\t\t out=\"6\";\n\t\t\t\t break;\n\t\t\t case 'e':\n\t\t\t\t out=\"7\";\n\t\t\t\t break;\n\t\t\t case 'l':\n\t\t\t\t out=\"8\";\n\t\t\t\t break;\n\t\t\t case 'n':\n\t\t\t\t out=\"9\";\n\t\t\t\t break;\n\t\t\t case 'v':\n\t\t\t\t k=0;\n\t\t\t\t while (T.pop[i].line[j].varname.compare(d.label[k])!=0)\n\t\t\t\t\t ++k;\n\t\t\t\t tmp=std::to_string(static_cast<long long>(k+10));\n\t\t\t\t out = tmp;\n\t\t\t\t break;\n\t\t\t }\n\t\t\t  gout_all << float(float(i)/float(T.pop.size())) << \",\" << y/p.max_len << \",\" << (log(1+T.pop[i].fitness)-min_fit)/(max_fit-min_fit) << \",\" << (float(T.pop[i].age)-min_age)/(max_age-min_age) << \",\" << out << \",\" << T.pop[i].line[j].on << \"\\n\";\n\t\t\t ++y;\n\t\t\t if (p.eHC_on){\n\t\t\t\t if (T.pop[i].line[j].on){\n\t\t\t\t gout_on << float(float(i)/float(T.pop.size())) << \",\" << y_on/p.max_len << \",\" << (log(1+T.pop[i].fitness)-min_fit)/(max_fit-min_fit) << \",\" << (float(T.pop[i].age)-min_age)/(max_age-min_age) << \",\" << out << \",\" << T.pop[i].line[j].on << \"\\n\";\n\t\t\t\t ++y_on;\n\t\t\t\t }\n\t\t\t\t else{\n\t\t\t\t  gout_off << float(float(i)/float(T.pop.size())) << \",\" << y_off/p.max_len << \",\" << (log(1+T.pop[i].fitness)-min_fit)/(max_fit-min_fit) << \",\" << (float(T.pop[i].age)-min_age)/(max_age-min_age) << \",\" << out << \",\" << T.pop[i].line[j].on << \"\\n\";\n\t\t\t\t  ++y_off;\n\t\t\t\t }\n\t\t\t//++y;\n\t\t\t }\n\t\t }\n\t }\n\t gout_all.close();\n\t gout_off.close();\n\t\t gout_on.close();\n\t /*if (p.eHC_on) {\n\n\t }*/\n}\nvoid printstats(tribe& T,int &i,state& s,params& p,paretoarchive& A){\n//boost::progress_timer timer;\n\ns.out << \"--- Generation \" << i << \"---------------------------------------------------------------\" << \"\\n\";\ns.out << \"population size: \" << T.pop.size() << \"\\n\";\ns.out << \"Number of evals: \" << s.genevals.back() << \"\\n\";\ns.out << \"Best Fitness: \" << T.bestFit() <<\"\\n\";\ns.out << \"Best Fitness (v): \" << T.bestFit_v() <<\"\\n\";\ns.out << \"Median Fitness: \" << T.medFit_v()<<\"\\n\";\ns.out << \"Median Fitness (v): \" << T.medFit()<<\"\\n\";\ns.out << \"Mean Size: \" << T.meanSize() << \"\\n\";\ns.out << \"Mean Eff Size: \" << T.meanEffSize() << \"\\n\";\ns.out << \"Pareto Front Equations: \" << A.optimal_size << \"\\n\";\nif (p.pHC_on) {\n\ts.out << \"Parameter updates: \" << float(s.setPHCupdates()) / float(p.popsize) * 100 << \"%\\n\";\n\ts.out << \"Epigenetic updates: \" << float(s.setEHCupdates()) / float(p.popsize) * 100 << \"%\\n\";\n\ts.out << \"Epigenetic ties: \" << float(s.setEHCties()) / float(p.popsize) * 100 << \"%\\n\";\n}\ns.out << \"Beneficial Genetics: \" << s.getGoodCrossPct() << \"%\\n\";\ns.out << \"Neutral Genetics: \" << s.getNeutCrossPct() << \"%\\n\";\ns.out << \"Bad Genetics: \" << s.getBadCrossPct() << \"%\\n\";\n\nif (p.classification){\n\ts.out << \"Fitness \\t Equation \\n\";\n\tvector <sub_ind> besteqns;\n\tT.topTen(besteqns);\n\t//for(unsigned int j=0;j<min(10,int(A.pop.size()));++j)\n\t//\ts.out <<A.pop.at(j).abserror_v << \"\\t\" << A.pop.at(j).corr_v << \"\\t\" << A.pop.at(j).eqn <<\"\\n\";\n\tfor(unsigned int j=0;j<besteqns.size();++j)\n\t\ts.out << besteqns.at(j).fitness << \"\\t\" << besteqns.at(j).eqn <<\"\\n\";\n\n}\nelse{\n\ts.out << \"MAE \\t R^2 \\t Fitness \\t Equation \\n\";\n\tvector <sub_ind> besteqns;\n\tT.topTen(besteqns);\n\t//for(unsigned int j=0;j<min(10,int(A.pop.size()));++j)\n\t//\ts.out <<A.pop.at(j).abserror_v << \"\\t\" << A.pop.at(j).corr_v << \"\\t\" << A.pop.at(j).eqn <<\"\\n\";\n\tfor(unsigned int j=0;j<besteqns.size();++j){\n\t\ts.out << setprecision(3) << besteqns.at(j).abserror << \"\\t\" << setprecision(3) << besteqns.at(j).corr << \"\\t\" << setprecision(3) << besteqns.at(j).fitness << \"\\t\" << besteqns.at(j).eqn <<\"\\n\";\n\t\t/*if(boost::math::isnan(besteqns.at(j).abserror))\n\t\t{\n\t\t\tcout << \"equation with NaN error: \" + besteqns.at(j).eqn + \"\\n\";\n\t\t}*/\n\t}\n}\n//if (p.classification && p.class_m4gp){\n//\tind best_ind;\n//\tT.getbestind(best_ind);\n//\ts.out << \"best M:\\n\";\n//\ts.out << best_ind.M << \"\\n\";\n//\tfor (unsigned i = 0; i<p.number_of_classes; ++i){\n//\t\ts.out << \"best C[\" << i << \"]:\\n\";\n//\t\ts.out << best_ind.C[i] << \"\\n\";\n//\t}\n//}\ns.out << \"-------------------------------------------------------------------------------\" << \"\\n\";\n}\n\n\nint load_pop(vector<ind>& pop,params& p,state& s)\n{\n\t// load population from file filename.\n\tifstream fs(p.pop_restart_path);\n\tif(!fs.is_open())\n\t{\n\t\tstd::cerr << \"Error: couldn't open population file \" + p.pop_restart_path + \".\\n\";\n\t\texit(1);\n\t}\n\n\tstring s0;\n\tstring varname;\n\tfloat tmpf;\n\t//int tmpi;\n\tstring tmps;\n\tbool tmpb;\n\n\t//string trash;\n\t//s.erase();\n    //s.reserve(is.rdbuf()->in_avail());\n\tint i=0;\n\tint j=0;\n\twhile(!fs.eof() && i<=p.popsize)\n    {\n\t\tgetline(fs,s0,'\\n');\n\t\tistringstream ss(s0);\n\t\tss >> varname;\n\n\t\tif(varname.compare(0,6,\"gline:\") == 0 && i<p.popsize)\n\t\t{\n\t\t\t//pop.push_back(ind());\n\n\t\t\twhile (ss>>tmps){\n\t\t\t\tif (tmps.compare(\"+\")==0 || tmps.compare(\"-\")==0 || tmps.compare(\"*\")==0 || tmps.compare(\"/\")==0 || tmps.compare(\"s\")==0 || tmps.compare(\"c\")==0 || tmps.compare(\"e\")==0 || tmps.compare(\"l\")==0 || tmps.compare(\"!\") == 0 || tmps.compare(\"=\") == 0 || tmps.compare(\"<\") == 0 || tmps.compare(\">\") == 0 || tmps.compare(\"{\") == 0 || tmps.compare(\"}\")==0 || tmps.compare(\"i\") == 0 || tmps.compare(\"t\") == 0 || tmps.compare(\"&\") == 0 || tmps.compare(\"|\") == 0) // operator node\n\t\t\t\t\tpop[i].line.push_back(node(char(tmps[0])));\n\t\t\t\telse if (isdigit(tmps[0]) || tmps[0]=='-') // constant node\n\t\t\t\t\tpop[i].line.push_back(node(std::stof(tmps)));\n\t\t\t\telse //variable node\n\t\t\t\t\tpop[i].line.push_back(node(tmps));\n\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t\telse if(p.eHC_on && varname.compare(0,6,\"eline:\") == 0)\n\t\t{\n\t\t\twhile (ss>>tmpb){\n\t\t\t\tpop[i-1].line[j].on = tmpb;\n\t\t\t\t++j;\n\t\t\t}\n\t\t\tj=0;\n\t\t}\n\t\t/*else if(varname.compare(0,4,\"age:\") == 0)\n\t\t\tss>>pop[i-1].age;*/\n\t}\n\tif (!fs.eof()) s.out << \"WARNING: truncating population from file to first \" + to_string(static_cast<long long>(p.popsize)) + \" individuals...\\n\";\n\treturn i; // size of loaded population\n}\n\nvoid shuffle_data(Data& d, params& p, vector<Randclass>& r,state& s)\n{\n\tvector<int> shuffler;\n\tvector<float> newtarget;\n\tvector<vector<float>> newvals;\n\n\tfor(int i=0;i<d.vals.size();++i)\n\t\tshuffler.push_back(i);\n\n\tstd::random_shuffle(shuffler.begin(),shuffler.end(),r[omp_get_thread_num()]);\n\n\n\tif (p.EstimateFitness){\n\t\tbool tmp = s.out.print_to_file;\n\t\ts.out.print_to_file=1; // keep output from going to console\n\t\ts.out << \"data shuffle index: \";\n\t\tfor (int i=0; i<shuffler.size(); ++i)\n\t\t\ts.out << shuffler.at(i) << \" \";\n\t\ts.out << \"\\n\";\n\t\ts.out.print_to_file=tmp;\n\t}\n\tfor(int i=0;i<d.vals.size();++i)\n\t{\n\t\tnewtarget.push_back(d.target.at(shuffler.at(i)));\n\t\tnewvals.push_back(d.vals.at(shuffler.at(i)));\n\n\t}\n\tusing std::swap;\n\tstd::swap(d.target,newtarget);\n\tstd::swap(d.vals,newvals);\n}\nbool stopcondition(tribe& T,params p,Data& d,state& s,FitnessEstimator& FE)\n{\n\tif (!p.stop_condition)\n\t\treturn false;\n\tif (!p.EstimateFitness){\n\t\tif (T.bestFit() <= p.stop_threshold){\n\t\t\ts.out << \"best fitness criterion achieved: \" << T.bestFit() << \"<\" << p.stop_threshold << \"\\n\";\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t\treturn false;\n\t}\n\telse{\n\t\tvector<ind> best(1);\n\t\tT.getbestind(best[0]);\n\n\t\tp.EstimateFitness=0;\n\t\tFitness(best,p,d,s,FE);\n\t\tp.EstimateFitness=1;\n\t\tif (best[0].fitness <= p.stop_threshold){\n\t\t\ts.out << \"best fitness criterion achieved: \" << best[0].fitness << \"<\" << p.stop_threshold << \"\\n\";\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t\treturn false;\n\t}\n}\nint get_next_task(int& index,vector<int>& task_assignments)\n{\n\t// 0: evolve solution\n\t// 1: evolve fitness estimation\n\t// 2: print output (after all 0 tasks finish)\n\t// 3: update pareto archive (after all 0 tasks finish)\n\tif (index == task_assignments.size()-1)\n\t\treturn -1;\n\telse{\n\t\treturn task_assignments.at(++index);\n\t}\n}\n// template <size_t samples, size_t features>\n// void runEllenGP(dict& param_dict, float (&X)[samples][features], float (&Y)[samples],string pname,string dname)\n// numeric::array& features, numeric::array& target\n\nvoid reference_contiguous_array(PyObject* in, float* &ptr, vector<int>& dims)\n{ // returns pointer to underlying c array (ptr) from PyObject in, checking for contiguos memory storage\n\t  PyArrayObject* in_con;\n\t\tPyArray_Descr* x = PyArray_DESCR(in);\n\t\t// std::cout << \"array dtype: \" << (*x).type << \"\\n\";\n\t\t// std::cout << \"array kind: \" << (*x).kind << \"\\n\";\n\t\t// std::cout << \"array byteorder: \" << (*x).byteorder << \"\\n\";\n\t\t// std::cout << \"array flags: \" << (*x).flags << \"\\n\";\n\t\t// make sure data is contigous\n    in_con = PyArray_GETCONTIGUOUS((PyArrayObject*)in);\n\n\t\t// get pointer to c array\n    ptr = (float*)PyArray_DATA(in_con);\n\n\n\t\t// get dimensions\n\t\tint num_dim = PyArray_NDIM(in_con);\n    npy_intp* pdim = PyArray_DIMS(in_con);\n\t\t// std::cout << \"PyArray_NDIM:\" << num_dim << \"\\n\";\n\n    for (int i = 0; i < num_dim; i++){\n        dims.push_back(pdim[i]);\n\t\t\t\t// std::cout << \"dim\" << i << \": \" << dims[i] << \"\\n\";\n\t\t\t}\n\t\t// for (int i = 0; i < dims[0]; ++i){\n\t\t// \tstd::cout << \"*(ptr + \" << i << \"): \" << *(ptr+i) << \"\\n\";\n\t\t// }\n}\nvoid dereference(PyObject* o)\n{\n    Py_DECREF(o);\n}\n\nvoid line_to_py(vector<node>& line,bp::list& prog){\n\t// converts program to tuple for export to python.\n\t// cout << \"in line to py\\n\";\n\tfor (auto n: line){\n\t\tif (n.on){\n\t\t\tswitch(n.type)\n\t\t\t{\n\t\t\tcase 'v':\n\t\t\t\tif(n.varname.compare(0,6,\"target\")==0){\n\t\t\t\t\t// cout << \"autoregressing \" << n.varname << \"\\n\";\n\t\t\t\t\tprog.append(bp::make_tuple(\"y\", n.arity_float + n.arity_bool, stoi(string(n.varname.begin()+7,n.varname.end()))));\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif (n.varname.find(\"_d\") != std::string::npos) {\n\t\t\t\t\t\tsize_t pos = n.varname.find(\"_d\");\n\t\t\t\t\t\t// this is an auto-regressive variable\n\t\t\t\t\t\t// cout << \"auto-regressive variable index: \" << string(n.varname.begin()+2,n.varname.begin()+pos) << \"\\n\";\n\t\t\t\t\t\t// cout << \"auto-regressive variable delay: \" << string(n.varname.begin()+pos+2,n.varname.end()) << \"\\n\";\n\t\t\t\t\t\tprog.append(bp::make_tuple(\"xd\", n.arity_float + n.arity_bool, stoi(string(n.varname.begin()+2,n.varname.begin()+pos)),stoi(string(n.varname.begin()+pos+2,n.varname.end()))));\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\t// cout << n.varname << \" regular\\n\";\n\t\t\t\t\t\tprog.append(bp::make_tuple(\"x\", n.arity_float + n.arity_bool, stoi(string(n.varname.begin()+2,n.varname.end()))));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\tprog.append(bp::make_tuple(\"k\", n.arity_float + n.arity_bool, n.value));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprog.append(bp::make_tuple(n.type, n.arity_float + n.arity_bool));\n\t\t\t}\n\t\t}\n\t}\n}\nvoid pop_to_py(vector<ind>& archive,bp::list& arch_list){\n\t// converts program to tuple for export to python.\n\t// cout << \"pop_to_py\\n\";\n\t// cout << \"size of vector<ind> archive: \" << archive.size() << \"\\n\";\n\tfor (auto i: archive){\n\t// for (unsigned int i = 0; i < archive.size(); ++i){\n\t\t// cout << i << \"\\n\";\n\t\t// cout << i.eqn << \"\\n\";\n\t\tbp::list prog;\n\t\tline_to_py(i.line,prog);\n\t\tarch_list.append(bp::make_tuple(prog,i.fitness,i.fitness_v));\n\t}\n\t// cout << \"size of arch_list: \" << bp::len(arch_list) << \"\\n\";\n\t// cout <<\"beepbopboop\";\n}\n\nvoid runEllenGP(bp::dict& param_dict, PyObject* features, PyObject* target, bp::list& best_prog) //string pname,string dname\n{\n\t// MARK_FUNCTION\n\ttry{\n\t\tbool trials = 0;\n\t\tint trialnum = 0;\n\t\tstring pname = \"ellenGP\";\n\t\tstring dname = \"d\";\n\t\t// string paramfile = \"ellyn\";\n\t\t// string datafile = \"d\";\n\t\t//string paramfile(param_in);\n\t\t//string datafile(data_in);\n\t\t/* ===================================\n\t\tsteps:\n\t\tInitialize population\n\t\t\tmake genotypes\n\t\t\tgenotype to phenotype\n\t\t\tcalculate fitness\n\t\t\thill climb\n\t\tNext Generation\n\t\t\tSelect Parents\n\t\t\tCreate children genotypes\n\t\t\tgenotype to phenotype\n\t\t\tcalculate fitness\n\t\t\thill climb\n\t\tStore Statistics\n\t\tPrint Update\n\n\t\tINPUTS\n\t\tparamfile: parameter file\n\t\tdatafile: data set: target in first column, dependent variables in second column\n\t\t=================================== */\n\n\t\tstruct params p;\n\t\tstruct Data d;\n\t\tstruct state s;\n\n\t\tvector <Randclass> r;\n\n\t\t// load parameter file\n\t\tp.set(param_dict);\n\n\t\t// get the input array\n\t\tfloat* feat_ptr;\n\t\tvector<int> dims;\n\t\treference_contiguous_array(features, feat_ptr, dims);\n\n\t\t// set up features\n\t\td.set_train(feat_ptr,dims[0],dims[1]);\n\n\t\tfloat* target_ptr;\n\t  dims.resize(0);\n\n\t\treference_contiguous_array(target, target_ptr, dims);\n\t\td.set_target(target_ptr,dims[0]);\n\t\tPy_DECREF(features);\n\t\tPy_DECREF(target);\n\n\t\td.set_dependencies(p);\n\t\t// load_data(d,ds,p);\n\n\t\tstd::time_t t =  std::time(NULL);\n\n\n\t#if defined(_WIN32)\n\t\tstd::tm tm;\n\t\tlocaltime_s(&tm,&t);\n\t\tchar tmplog[100];\n\t\tstrftime(tmplog,100,\"%Y-%m-%d_%H-%M-%S\",&tm);\n\t#else\n\t\tstd::tm * tm = localtime(&t);\n\t\tchar tmplog[100];\n\t\tstrftime(tmplog,100,\"%F_%H-%M-%S\",tm);\n\t#endif\n\n\n\t   // string tmplog = \"777\";\n\t\tconst char * c = p.resultspath.c_str();\n\t\t#if defined(_WIN32)\n\t\t\t_mkdir(c);\n\t\t#else\n\t\t\tmkdir(c, 0777); // notice that 777 is different than 0777\n\t\t#endif\n\t\t int thrd = omp_get_thread_num();\n\t\t string thread;\n\t\t if (trials) thread = std::to_string(static_cast<long long>(trialnum));\n\t\t else thread = std::to_string(static_cast<long long>(thrd));\n\t// define save file name\n\tstring logname;\n\t#if defined(_WIN32)\n\t\tif (!p.savename.empty())\n\t\t\tlogname = p.resultspath + '/' + p.savename + \".log\";\n\t\telse\n\t  \tlogname = p.resultspath + '\\\\' + \"ellyn_\" + tmplog + \"_\" + pname + \"_\" + dname + \"_\" + thread + \".log\";\n\t#else\n\t\tif (!p.savename.empty())\n\t\t\tlogname = p.resultspath + '/' + p.savename + \".log\";\n\t\telse\n\t\t\tlogname = p.resultspath + '/' + \"ellyn_\" + tmplog + \"_\" + pname + \"_\" + dname + \"_\" + thread + \".log\";\n\t#endif\n\n\n\t\t s.out.set_ptf(trials && p.print_log); // only print to file if print_log\n\n\t\t s.out.set_v(p.verbosity>1); // only print a log file to screen if verbosity > 1\n\t\t // print log setup\n\t\t if (p.print_log){\n\t\t\t s.out.open(logname);\n\t\t\t if (!s.out.is_open()){\n\t\t\t\t cerr << \"Write-to File \" << p.resultspath + '/' + logname << \" did not open correctly.\\n\";\n\t\t\t\t exit(1);\n\t\t\t }\n\t\t \t}\n\t\t // initialize data file\n\t\t std::ofstream dfout;\n\t\t if (p.print_data)\tinitdatafile(dfout,logname,p);\n\n\n\n\t\t if (p.verbosity>0){\n\t\t\t s.out << \"_______________________________________________________________________________ \\n\";\n\t\t\t s.out << \"                                    ellenGP                                     \\n\";\n\t\t\t s.out << \"_______________________________________________________________________________ \\n\";\n\t\t\t //s.out << \"Time right now is \" << std::put_time(&tm, \"%c %Z\") << '\\n';\n\t\t\t s.out<< \"Results Path: \" << p.resultspath  << \"\\n\";\n\t\t\t if (!p.savename.empty())\n\t\t\t \ts.out << \"Save filename: \" << p.savename << \"\\n\";\n\t\t\t s.out << \"parameter name: \" << pname << \"\\n\";\n\t\t\t s.out << \"data file: \" << dname << \"\\n\";\n\t\t\t if(trials) {s.out << \"Running in Trial Mode\\n\";\n\t\t\t s.out << \"Trial ID: \" << trialnum << \"\\n\";\n\t\t\t }\n\t\t\t s.out << \"Settings: \\n\";\n\t\t\t // get evolutionary method\n\t\t\t s.out << \"Evolutionary Method: \";\n\t\t\t switch(p.sel){\n\t\t\t\t case 1:\n\t\t\t\t\t s.out << \"Standard Tournament\\n\";\n\t\t\t\t\t break;\n\t\t\t\t case 2:\n\t\t\t\t\t s.out << \"Deterministic Crowding\\n\";\n\t\t\t\t\t break;\n\t\t\t\t case 3:\n\t\t\t\t\t s.out << \"Lexicase Selection\\n\";\n\t\t\t\t\t break;\n\t\t\t\t case 4:\n\t\t\t\t\t s.out << \"Age-Fitness Pareto\\n\";\n\t\t\t\t\t break;\n\t\t\t }\n\t\t\t if (p.sel==3){\n\t\t\t\t s.out << \"Lexicase metacases:\\n\";\n\t\t\t\t// add metacases if needed\n\t\t\t\tfor (auto i: p.lex_metacases)\n\t\t\t\t\ts.out << \"\\t\" << i << \"\\n\";\n\t\t\t }\n\t\t\t if (p.ERC) s.out << \"ERCs on\\n\";\n\t\t\t if (p.pHC_on) s.out << p.pHC_its << \" iterations of Parameter Hill Climbing\\n\";\n\t\t\t if (p.eHC_on) s.out << p.eHC_its << \" iterations of Epigenetic Hill Climbing\\n\";\n\t\t\t if(p.train) s.out << \"Data split \" << p.train_pct << \"/\" << 1-p.train_pct << \" for training and validation.\\n\";\n\t\t\t s.out << \"Total Population Size: \" << p.popsize << \"\\n\";\n\t\t\t if (p.limit_evals) s.out << \"Maximum Point Evals: \" << p.max_evals << \"\\n\";\n\t\t\t else s.out << \"Maximum Generations: \" << p.g << \"\\n\";\n\t\t\t s.out << \"Number of log points: \" << p.num_log_pts << \" (0 means log all points)\\n\";\n\t\t\t if (trials && p.islands){\n\t\t\t\ts.out << \"WARNING: cannot run island populations in trial mode. This trial will run on one core.\\n\";\n\t\t\t\tp.islands = false;\n\t\t\t }\n\t\t\t s.out << \"fitness type: \" << p.fit_type << \"\\n\";\n\t\t\t s.out << \"verbosity: \" << p.verbosity << \"\\n\";\n\t\t  }\n\t\t // allow threads (release the Python GIL) python gil unlock\n\t\t// Py_BEGIN_ALLOW_THREADS{\n\t\tint nt=0;\n\t\t//int ntt=0;\n\t\t// if specified by the user, override the default omp number of threads\n\t\tif (p.islands && p.num_islands !=0){\n\t\t\tnt = p.num_islands;\n\t\t\tomp_set_num_threads(nt);\n\t\t}\n\t\telse{\n\t\t\t#pragma omp parallel\n\t\t\t{\n\t\t\t\tnt = omp_get_num_threads();\n\t\t\t}\n\t\t}\n\t\tif (p.verbosity>0) s.out << \"Number of threads: \" << nt << \"\\n\";\n\t\t//s.out << \"OMP Number of threads: \" << omp_get_num_threads() << \"\\n\";\n\t\tp.nt = nt;\n\n\t\t//initialize random number generator\n\t\tunsigned int seed1 = int(time(NULL));\n\t\tif (p.verbosity>0) s.out << \"seeds: \\n\";\n\t\tr.resize(omp_get_max_threads());\n\t\t#pragma omp parallel\n\t\t{\n\t\t\t\t//cout << \"seeder: \" << seeder <<endl;\n\t\t\t\t//cout << \"seed1: \" << seed1*seeder <<endl;\n\t\t\t\tif(!trials){\n\t\t\t\t\tif (p.verbosity>0) s.out << to_string(static_cast<long long>(seed1*(omp_get_thread_num()+1))) + \"\\n\";\n\t\t\t\t\t//r.at(seeder).SetSeed(seed1*(seeder+1));\n\t\t\t\t\tr.at(omp_get_thread_num()).SetSeed(seed1*(omp_get_thread_num()+1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tr.at(omp_get_thread_num()).SetSeed(seed1*(omp_get_thread_num()+1)*trialnum);\n\t\t}\n\t\tif(trials)\n\t\t\tif (p.verbosity>0) s.out << (omp_get_thread_num()+1)*seed1*trialnum << \"\\n\";\n\n\t\t//shuffle data for training\n\t\tif (p.shuffle_data)\n\t\t\tshuffle_data(d,p,r,s);\n\n\t\t// define class weights for wighted F1 fitness\n\t\tif (p.classification && (p.fit_type.compare(\"2\")==0 || p.fit_type.compare(\"F1W\")==0))\n\t\t\td.define_class_weights(p);\n\n\t\tboost::timer time;\n\t\tparetoarchive A;\n\t\tif (p.prto_arch_on){\n\t\t\tA.resize(p.prto_arch_size);\n\t\t\t// tribe FinalArchive(p.prto_arch_size,p.max_fit,p.min_fit);\n\t\t\t// FinalArchive.pop = A.pop;\n\t\t}\n\n\t\tvector<FitnessEstimator> FE(1);\n\t\tvector<ind> trainers;\n\t  //////////////////////////////////////////////////////////////////////////////\n\t\t// islands\n\t\t//////////////////////////////////////////////////////////////////////////////\n\t\tif (p.islands)\n\t\t{\n\t\t\t//p.parallel=false;\n\t\t\t// determine number of threads\n\n\t\t\t//int num_islands=omp_get_max_threads(); //\n\t\t\tint num_islands=nt;\n\t\t\tint subpops = p.popsize/num_islands;\n\t\t\tp.popsize = subpops*num_islands;\n\t\t\tvector<tribe> T;\n\t\t\ttribe World(subpops*num_islands,p.max_fit,p.min_fit); //total population of tribes\n\t\t\tif (p.verbosity>0) s.out << num_islands << \" islands of \" << subpops << \" individuals, total pop \" << p.popsize <<\"\\n\";\n\n\n\t\t\tfor(int i=0;i<num_islands;++i)\n\t\t\t\tT.push_back(tribe(subpops,p.max_fit,p.min_fit));\n\t\t\t// run separate islands\n\t\t\tif (p.pop_restart) // initialize population from file\n\t\t\t{\n\t\t\t\tif (p.verbosity>0) s.out << \"loading pop from \" + p.pop_restart_path + \"...\\n\";\n\t\t\t\tint tmp = load_pop(World.pop,p,s);\n\t\t\t\tif (tmp < p.popsize){\n\t\t\t\t\tif (p.verbosity>0) s.out << \"WARNING: population size loaded from file (\" << tmp << \") is smaller than set pop size (\" << p.popsize << \"). \" << (p.popsize-tmp) << \" randomly initiated individuals will be added...\\n\";\n\t\t\t\t\tvector<ind> tmppop(p.popsize-tmp);\n\t\t\t\t\tInitPop(tmppop,p,r);\n\t\t\t\t\tswap_ranges(World.pop.end()-(p.popsize-tmp),World.pop.end(),tmppop.begin());\n\t\t\t\t}\n\t\t\t\t// initialize fitness estimation pop\n\t\t\t\tif (p.EstimateFitness)\n\t\t\t\t\tInitPopFE(FE,World.pop,trainers,p,r,d,s);\n\n\t\t\t\tFitness(World.pop,p,d,s,FE[0]);\n\n\t\t\t\tstd::random_shuffle(World.pop.begin(),World.pop.end(),r[0]);\n\t\t\t\t//assign population to islands\n\t\t\t\t#pragma omp parallel for\n\t\t\t\tfor (int q = 0; q<num_islands; ++q)\n\t\t\t\t\tT[q].pop.assign(World.pop.begin()+q*subpops,World.pop.begin()+(q+1)*subpops);\n\t\t\t}\n\t\t\telse // initialize population from random\n\t\t\t{\n\t\t\t\tif (p.init_validate_on)\n\t\t\t\t{\n\t\t\t\t\tif (p.verbosity>0) s.out << \"Initial validation...\";\n\n\n\t\t\t\t\t#pragma omp parallel for\n\t\t\t\t\tfor(int i=0;i<num_islands;++i)\n\t\t\t\t\t\tInitPop(T.at(i).pop,p,r);\n\n\t\t\t\t\tif (p.EstimateFitness)\n\t\t\t\t\t{\n\t\t\t\t\t\t// construct world population\n\t\t\t\t\t\tfor(int j=0;j<T.size();++j){\n\t\t\t\t\t\t\tfor(int k=0;k<T[0].pop.size();++k){\n\t\t\t\t\t\t\t\tWorld.pop.at(j*T[0].pop.size()+k)=T.at(j).pop.at(k);\n\t\t\t\t\t\t\t\t//makenew(World.pop[j*T[0].pop.size()+k]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// initialize fitness estimation pop\n\t\t\t\t\t\tInitPopFE(FE,World.pop,trainers,p,r,d,s);\n\t\t\t\t\t}\n\t\t\t\t\t//discard invalid individuals\n\t\t\t\t\t#pragma omp parallel for\n\t\t\t\t\tfor(int i=0;i<num_islands;++i){\n\t\t\t\t\t\tfloat worstfit;\n\t\t\t\t\t\tfloat bestfit;\n\t\t\t\t\t\tvector<ind> tmppop;\n\n\t\t\t\t\t\tFitness(T.at(i).pop,p,d,s,FE[0]);\n\t\t\t\t\t\tworstfit = T.at(i).worstFit();\n\t\t\t\t\t\tbestfit = T.at(i).bestFit();\n\n\n\t\t\t\t\t\tint counter=0;\n\t\t\t\t\t\twhile(worstfit == p.max_fit && counter<100)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (vector<ind>::iterator j=T.at(i).pop.begin();j!=T.at(i).pop.end();)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif ( (*j).fitness == p.max_fit)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tj=T.at(i).pop.erase(j);\n\t\t\t\t\t\t\t\t\ttmppop.push_back(ind());\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\t++j;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tInitPop(tmppop,p,r);\n\t\t\t\t\t\t\tFitness(tmppop,p,d,s,FE[0]);\n\t\t\t\t\t\t\tT.at(i).pop.insert(T.at(i).pop.end(),tmppop.begin(),tmppop.end());\n\t\t\t\t\t\t\ttmppop.clear();\n\t\t\t\t\t\t\tworstfit = T.at(i).worstFit();\n\t\t\t\t\t\t\tcounter++;\n\t\t\t\t\t\t\tif(counter==100)\n\t\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"initial population count exceeded. Starting evolution...\\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ts.setgenevals();\n\t\t\t\t\tif (p.verbosity>0) s.out << \" number of evals: \" << s.getgenevals() << \"\\n\";\n\n\t\t\t\t}\n\t\t\t\telse // normal population initialization\n\t\t\t\t{\n\t\t\t\t\t/*bool tmp = p.EstimateFitness;\n\t\t\t\t\tp.EstimateFitness=0;*/\n\t\t\t\t\tif (p.verbosity>1) s.out << \"InitPop...\\n\";\n                    #pragma omp parallel for\n\t\t\t\t\tfor(int i=0;i<num_islands;++i)\n\t\t\t\t\t\tInitPop(T.at(i).pop,p,r);\n\n\t\t\t\t\tif (p.EstimateFitness){\n\t\t\t\t\t\t// construct world population\n\t\t\t\t\t\tfor(int j=0;j<T.size();++j){\n\t\t\t\t\t\t\tfor(int k=0;k<T[0].pop.size();++k){\n\t\t\t\t\t\t\t\tWorld.pop.at(j*T[0].pop.size()+k)=T.at(j).pop.at(k);\n\t\t\t\t\t\t\t\t//makenew(World.pop[j*T[0].pop.size()+k]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tInitPopFE(FE,World.pop,trainers,p,r,d,s);\n\t\t\t\t\t}\n\n\t\t\t\t\t#pragma omp parallel for\n\t\t\t\t\tfor(int i=0;i<num_islands;++i)\n\t\t\t\t\t\tFitness(T.at(i).pop,p,d,s,FE[0]);\n\n\t\t\t\t\t// construct world population with assigned fitness values\n\t\t\t\t\tfor(int j=0;j<T.size();++j){\n\t\t\t\t\t\tfor(int k=0;k<T[0].pop.size();++k){\n\t\t\t\t\t\t\tWorld.pop.at(j*T[0].pop.size()+k)=T.at(j).pop.at(k);\n\t\t\t\t\t\t\t//makenew(World.pop[j*T[0].pop.size()+k]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t\t// use tmpFE for updating in parallel\n\t\t\tvector<FitnessEstimator> tmpFE = FE;\n\n\t\t\tint gen=0;\n\t\t\tlong long termits,term, print_trigger;\n\t\t\tif (p.limit_evals){\n\t\t\t\ttermits = s.totalptevals();\n\t\t\t\tterm = p.max_evals;\n\t\t\t\tif (p.num_log_pts ==0) print_trigger=0;\n\t\t\t\telse print_trigger = p.max_evals/p.num_log_pts;\n\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprint_trigger=0;\n\t\t\t\ttermits=1;\n\t\t\t\tterm = p.g;\n\t\t\t}\n\t\t\tbool pass=1;\n\t\t\tint mixtrigger=p.island_gens*(p.popsize+p.popsize*p.eHC_on+p.popsize*p.pHC_on);\n\t\t\t//int trainer_trigger=0;\n\t\t\tint trainer_trigger=p.FE_train_gens;//p.FE_train_gens*(p.popsize+p.popsize*p.eHC_on+p.popsize*p.pHC_on);\n\n\t\t\tbool migrate=false;\n\t\t\tint q;\n\n\t\t\t// construct world population\n\t\t\tif (!p.EstimateFitness || !p.pop_restart){\n\t\t\t\tint cntr=0;\n\t\t\t\tfor (int q0 = 0; q0<nt;++q0){\n\t\t\t\t\tfor(int k=q0*subpops;k<(q0+1)*subpops;++k){\n\t\t\t\t\t\tWorld.pop.at(k)=T.at(q0).pop.at(cntr);\n\t\t\t\t\t\t//makenew(World.pop.at(k));\n\t\t\t\t\t\t++cntr;\n\t\t\t\t\t}\n\t\t\t\t\tcntr=0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (p.print_init_pop) printpop(World.pop,p,s,logname,3);\n\t\t\tif (p.print_genome) printGenome(World,0,logname,d,p);\n\t\t\tif (p.print_db) printDB(World.pop,logname,d,p);\n\t\t\t#pragma omp parallel private(q) shared(pass)\n\t\t\t{\n\n\t\t\t\tq = omp_get_thread_num();\n\n\t\t\t\twhile(termits<=term)\n\t\t\t\t{\n\n\n\t\t\t\t\tif(pass){\n\t\t\t\t\t\t// cout << \"thread \" + std::to_string(static_cast<long long>(q)) + \" Generation\\n\";\n\t\t\t\t\t\tGeneration(T[q].pop,p,r,d,s,FE[0]);\n\n\t\t\t\t\t\tif (stopcondition(T[q],p,d,s,FE[0])){\n\t\t\t\t\t\t\tpass=0;\n\t\t\t\t\t\t\t// cout << \"thread \" + std::to_string(static_cast<long long>(q)) + \" solution\\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (pass) {\n\t\t\t\t\t\tif (p.pHC_on && p.ERC)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor(int k=0; k<T[q].pop.size(); ++k)\n\t\t\t\t\t\t\t\t\tHillClimb(T[q].pop.at(k),p,r,d,s,FE[0]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (p.eHC_on && !p.eHC_mut)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor(int m=0; m<T[q].pop.size(); m++)\n\t\t\t\t\t\t\t\t\tEpiHC(T[q].pop.at(m),p,r,d,s,FE[0]);\n\t\t\t\t\t\t}\n                        if (p.SGD && p.ERC)\n                        {\n                            for(int k=0; k<T[q].pop.size(); ++k)\n\t\t\t\t\t\t\t\t\tStochasticGradient(T[q].pop.at(k),p,r,d,s,FE[0],gen);\n\n                        }\n\t\t\t\t\t\tif (stopcondition(T[q],p,d,s,FE[0])){\n\t\t\t\t\t\t\tpass=0;\n\t\t\t\t\t\t\t// cout << \"thread \" + std::to_string(static_cast<long long>(q)) + \" solution\\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// cout << \"thread \" + std::to_string(static_cast<long long>(q)) + \" pass val: \" + std::to_string(static_cast<long long>(pass)) + \"\\n\";\n\n\n\t\t\t\t\t\t// construct world population\n\t\t\t\t\t\tint cntr=0;\n\t\t\t\t\t\t//std::vector<ind>::iterator it = T[q].begin();\n\t\t\t\t\t\t//World.pop.assign(\n\t\t\t\t\t\tfor(int k=q*subpops;k<(q+1)*subpops;++k){\n\t\t\t\t\t\t\tWorld.pop.at(k)=T[q].pop.at(cntr);\n\t\t\t\t\t\t\t//makenew(World.pop.at(k));\n\t\t\t\t\t\t\tcntr++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// cout << \"thread \" + std::to_string(static_cast<long long>(q)) + \" World pop constructed\\n\";\n\n\t\t\t\t\t\t#pragma omp barrier\n\n\t\t\t\t\t\tif (!pass)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t// cout << \"thread \" + std::to_string(static_cast<long long>(q)) + \" past the barrier\\n\";\n\t\t\t\t\t\t#pragma omp single  nowait //coevolve fitness estimators\n\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\tif (p.EstimateFitness){\n\n\n\t\t\t\t\t\t\t\tfloat aveFEfit=0;\n\t\t\t\t\t\t\t\tfor (int u=0;u<FE.size();u++)\n\t\t\t\t\t\t\t\t\taveFEfit+=FE[u].fitness;\n\t\t\t\t\t\t\t\taveFEfit /= FE.size();\n\t\t\t\t\t\t\t\tif (aveFEfit==0)\n\t\t\t\t\t\t\t\t\tstd::random_shuffle(tmpFE.begin(),tmpFE.end(),r[omp_get_thread_num()]);\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tEvolveFE(World.pop,tmpFE,trainers,p,d,s,r);\n\t\t\t\t\t\t\t\tif (!p.limit_evals || s.totalptevals() >= print_trigger){\n\t\t\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Evolving fitness estimators...\\n\";\n\t\t\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Best FE fit: \" << FE[0].fitness <<\"\\n\";\n\t\t\t\t\t\t\t\t\tif (p.estimate_generality) s.out << \"Best FE genty: \" << FE[0].genty <<\"\\n\";\n\t\t\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Ave FE fit: \" << aveFEfit << \"\\n\";\n\t\t\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Current Fitness Estimator:\\n\";\n\n\t\t\t\t\t\t\t\t\tif (p.verbosity>0){\n\t\t\t\t\t\t\t\t\t\tfor (int b=0;b<FE[0].FEpts.size();b++)\n\t\t\t\t\t\t\t\t\t\t\t s.out << FE[0].FEpts[b] << \" \";\n\t\t\t\t\t\t\t\t\t\ts.out << \"\\n\";\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t#pragma omp single\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ts.setgenevals();\n\t\t\t\t\t\t\tif(s.totalevals()>mixtrigger)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//shuffle population\n\t\t\t\t\t\t\t\tstd::random_shuffle(World.pop.begin(),World.pop.end(),r[q]);\n\t\t\t\t\t\t\t\t//redistribute populations to islands\n\t\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Shuffling island populations...\\n\";\n\t\t\t\t\t\t\t\tmigrate = true;\n\t\t\t\t\t\t\t\tmixtrigger+=p.island_gens*(p.popsize+p.popsize*p.eHC_on+p.popsize*p.pHC_on);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tmigrate=false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t#pragma omp single\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(p.prto_arch_on){\n\t\t\t\t\t\t\t\tA.update(World.pop);\n\t\t\t\t\t\t\t\tif (p.print_archive) printpop(A.pop,p,s,logname,1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!p.limit_evals || s.totalptevals() >= print_trigger){\n\t\t\t\t\t\t\t\tif (p.print_data) printdatafile(World,s,p,r,dfout,gen,time.elapsed());\n\t\t\t\t\t\t\t\tif (p.print_every_pop) printpop(World.pop,p,s,logname,2);\n\t\t\t\t\t\t\t\tif (p.verbosity > 1) {\n\t\t\t\t\t\t\t\t\tprintstats(World,gen,s,p,A);\n\t\t\t\t\t\t\t\t\ts.out << \"Total Time: \" << (int)floor(time.elapsed()/num_islands/3600) << \" hr \" << ((int)(time.elapsed()/num_islands) % 3600)/60 << \" min \" << (int)(time.elapsed()/num_islands) % 60 << \" s\\n\";\n\t\t\t\t\t\t\t\t\ts.out << \"Total Evals: \" << s.totalevals() << \"\\n\";\n\t\t\t\t\t\t\t\t\ts.out << \"Point Evals: \" << s.totalptevals() << \"\\n\";\n\t\t\t\t\t\t\t\t\ts.out << \"Average evals per second: \" << (float)s.totalevals()/time.elapsed() << \"\\n\";\n\t\t\t\t\t\t\t\t\ts.out << \"Average point evals per second: \" << (float)s.totalptevals()/(time.elapsed()/num_islands) << \"\\n\";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (print_trigger!=0) print_trigger += p.max_evals/p.num_log_pts;\n\t\t\t\t\t\t\t\tif (p.print_genome) printGenome(World,gen,logname,d,p);\n\t\t\t\t\t\t\t\tif (p.print_db) printDB(World.pop,logname,d,p);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t++gen;\n\t\t\t\t\t\t\tif (p.limit_evals) termits = s.totalptevals();\n\t\t\t\t\t\t\telse ++termits;\n\n\t\t\t\t\t\t\tif (!p.EstimateFitness && p.estimate_generality && p.G_shuffle)\n\t\t\t\t\t\t\t\tshuffle_data(d,p,r,s);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t#pragma omp single\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (p.EstimateFitness){\n\t\t\t\t\t\t\t\t// assign tmpFE to FE\n\t\t\t\t\t\t\t\tFE.assign(tmpFE.begin(),tmpFE.end());\n\t\t\t\t\t\t\t\t/*float avefit=0;\n\t\t\t\t\t\t\t\tfor (int u=0;u<FE.size();u++)\n\t\t\t\t\t\t\t\t\tavefit+=FE[u].fitness;\n\t\t\t\t\t\t\t\tavefit /= FE.size();\n\t\t\t\t\t\t\t\tif (avefit>1)\n\t\t\t\t\t\t\t\t\tcout <<\"avefit error\\n\";*/\n\t\t\t\t\t\t\t\tif(gen>trainer_trigger) { //pick new trainers when FE pop has converged or when it has been enough generations\n\t\t\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Picking trainers...\\n\";\n\t\t\t\t\t\t\t\t\tPickTrainers(World.pop,FE,trainers,p,d,s);\n\t\t\t\t\t\t\t\t\ttrainer_trigger = gen + p.FE_train_gens; //p.island_gens*(p.popsize+p.popsize*p.eHC_on+p.popsize*p.pHC_on);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (migrate)\n\t\t\t\t\t\t\tT[q].pop.assign(World.pop.begin()+q*subpops,World.pop.begin()+(q+1)*subpops);\n\n\t\t\t\t\t\t//if (gen>p.g) pass=0;\n\n\n\t\t\t\t} if (p.verbosity>1) s.out << \"thread \" + std::to_string(static_cast<long long>(q)) + \" exited while loop...\\n\";\n\t\t\t\tif (!pass){ //make sure archive was updated and generation prints out (may be redundant)\n\t\t\t\t\t#pragma omp single\n\t\t\t\t\t{\n\t\t\t\t\t\tif(p.prto_arch_on){\n\t\t\t\t\t\t\tA.update(World.pop);\n\t\t\t\t\t\t\tif (p.print_archive) printpop(A.pop,p,s,logname,1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!p.limit_evals || s.totalptevals() >= print_trigger){\n\t\t\t\t\t\t\tif (p.print_data) printdatafile(World,s,p,r,dfout,gen,time.elapsed());\n\t\t\t\t\t\t\tif (p.print_every_pop) printpop(World.pop,p,s,logname,2);\n\t\t\t\t\t\t\tif (p.verbosity > 1) {\n\t\t\t\t\t\t\t\tprintstats(World,gen,s,p,A);\n\t\t\t\t\t\t\t\ts.out << \"Total Time: \" << (int)floor(time.elapsed()/num_islands/3600) << \" hr \" << ((int)(time.elapsed()/num_islands) % 3600)/60 << \" min \" << (int)(time.elapsed()/num_islands) % 60 << \" s\\n\";\n\t\t\t\t\t\t\t\ts.out << \"Total Evals: \" << s.totalevals() << \"\\n\";\n\t\t\t\t\t\t\t\ts.out << \"Point Evals: \" << s.totalptevals() << \"\\n\";\n\t\t\t\t\t\t\t\ts.out << \"Average evals per second: \" << (float)s.totalevals()/time.elapsed() << \"\\n\";\n\t\t\t\t\t\t\t\ts.out << \"Average point evals per second: \" << (float)s.totalptevals()/time.elapsed() << \"\\n\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (print_trigger!=0) print_trigger += p.max_evals/p.num_log_pts;\n\t\t\t\t\t\t\tif (p.print_genome) printGenome(World,gen,logname,d,p);\n\t\t\t\t\t\t\tif (p.print_db) printDB(World.pop,logname,d,p);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++gen;\n\t\t\t\t\t\tif (p.limit_evals) termits = s.totalptevals();\n\t\t\t\t\t\telse ++termits;\n\n\t\t\t\t\t\tif (!p.EstimateFitness && p.estimate_generality && p.G_shuffle)\n\t\t\t\t\t\t\tshuffle_data(d,p,r,s);\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} if (p.verbosity>1) s.out << \"exited parallel region ...\\n\";\n\n\n\t\t\tif (p.EstimateFitness || p.test_at_end){// assign real fitness values to final population and archive\n\t\t\t\tp.EstimateFitness=0;\n\t\t\t\tp.test_at_end = 0;\n\t\t\t\tFitness(World.pop,p,d,s,FE[0]);\n\t\t\t\tif (p.prto_arch_on) Fitness(A.pop,p,d,s,FE[0]);\n\t\t\t\tp.EstimateFitness=1;\n\t\t\t}\n\n\t\t\tif (p.print_data) printdatafile(World,s,p,r,dfout,gen,time.elapsed());\n\t\t\tif (p.print_best_ind) printbestind(World,p,s,logname);\n\t\t\tif (p.print_last_pop) printpop(World.pop,p,s,logname,0);\n\n\t\t\tif (p.prto_arch_on){\n\t\t\t\t// if (A.pop.empty()) A.update(World.pop);\n\n\t\t\t\tif (p.print_archive) printpop(A.pop,p,s,logname,1);\n\t\t\t\t// save archive to best_prog for python\n\t\t\t\tif (p.return_pop){\n\t\t\t\t\tWorld.sortpop();\n\t\t\t\t\tpop_to_py(World.pop,best_prog);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tpop_to_py(A.pop,best_prog);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t// save best individual to best_prog for python\n\t\t\t\tif (p.return_pop){\n\t\t\t\t\tWorld.sortpop();\n\t\t\t\t\tpop_to_py(World.pop,best_prog);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tvector<ind> best(1);\n\t\t\t\t\tWorld.getbestind(best[0]);\n\t\t\t\t\tline_to_py(best[0].line,best_prog);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/////////////////////////////////////////////////////////////////////////////\n\t\t// no islands\n\t\t//////////////////////////////////////////////////////////////////////////////\n\t\telse //no islands\n\t\t{\n\t \t\ttribe T(p.popsize,p.max_fit,p.min_fit);\n\t\t\tif (p.pop_restart) // initialize population from file\n\t\t\t{\n\t\t\t\tif (p.verbosity>0) s.out << \"loading pop from \" + p.pop_restart_path + \"...\\n\";\n\t\t\t\tint tmp = load_pop(T.pop,p,s);\n\t\t\t\tif (tmp < p.popsize){\n\t\t\t\t\tif (p.verbosity>0) s.out << \"WARNING: population size loaded from file (\" << tmp << \") is smaller than set pop size (\" << p.popsize << \"). \" << (p.popsize-tmp) << \" randomly initiated individuals will be added...\\n\";\n\t\t\t\t\tvector<ind> tmppop(p.popsize-tmp);\n\t\t\t\t\tInitPop(tmppop,p,r);\n\t\t\t\t\tswap_ranges(T.pop.end()-(p.popsize-tmp),T.pop.end(),tmppop.begin());\n\t\t\t\t}\n\t\t\t\tif (p.EstimateFitness)\n\t\t\t\t\tInitPopFE(FE,T.pop,trainers,p,r,d,s);\n\t\t\t\tFitness(T.pop,p,d,s,FE[0]);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (p.init_validate_on)\n\t\t\t\t{\n\t\t\t\t\tif (p.verbosity>0) s.out << \"Initial validation...\";\n\t\t\t\t\t//bool tmp = p.EstimateFitness;\n\t\t\t\t\t//p.EstimateFitness=0;\n\n\n\t\t\t\t\tfloat worstfit;\n\t\t\t\t\tint cnt=0;\n\t\t\t\t\t//float bestfit;\n\t\t\t\t\tvector<ind> tmppop;\n\t\t\t\t\t// s.out << \"Initialize Population...\" << \"\\n\";\n\t\t\t\t\tInitPop(T.pop,p,r);\n\t\t\t\t\tassert (T.pop.size()== p.popsize) ;\n\t\t\t\t\t// s.out << \"Gen 2 Phen...\" << \"\\n\";\n\t\t\t\t\t// s.out << \"Fitness...\" << \"\\n\";\n\t\t\t\t\tif (p.EstimateFitness)\n\t\t\t\t\t\tInitPopFE(FE,T.pop,trainers,p,r,d,s);\n\n\t\t\t\t\tFitness(T.pop,p,d,s,FE[0]);\n\t\t\t\t\tassert (T.pop.size()== p.popsize) ;\n\n\t\t\t\t\tworstfit = T.worstFit();\n\t\t\t\t\twhile(worstfit == p.max_fit && cnt<100)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (vector<ind>::iterator j=T.pop.begin();j!=T.pop.end();)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( (*j).fitness == p.max_fit)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tj=T.pop.erase(j);\n\t\t\t\t\t\t\t\ttmppop.push_back(ind());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t++j;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (p.verbosity>0) s.out << \"\\ntmppop size: \" << tmppop.size();\n\t\t\t\t\t\tInitPop(tmppop,p,r);\n\t\t\t\t\t\tFitness(tmppop,p,d,s,FE[0]);\n\n\t\t\t\t\t\tT.pop.insert(T.pop.end(),tmppop.begin(),tmppop.end());\n\t\t\t\t\t\ttmppop.clear();\n\t\t\t\t\t\tworstfit = T.worstFit();\n\t\t\t\t\t\tcnt++;\n\t\t\t\t\t\tif(cnt==100)\n\t\t\t\t\t\t\tif (p.verbosity>0) s.out << \"initial population count exceeded. Starting evolution...\\n\";\n\t\t\t\t\t}\n\t\t\t\t\t//p.EstimateFitness=tmp;\n\t\t\t\t}\n\t\t\t\telse // normal population initialization\n\t\t\t\t{\n\t\t\t\t\tInitPop(T.pop,p,r);\n\t\t\t\t\tif (p.EstimateFitness)\n\t\t\t\t\t\tInitPopFE(FE,T.pop,trainers,p,r,d,s);\n\t\t\t\t\t//bool tmp = p.EstimateFitness;\n\t\t\t\t\t//p.EstimateFitness=0;\n\t\t\t\t\tFitness(T.pop,p,d,s,FE[0]);\n\t\t\t\t\t//p.EstimateFitness=tmp;\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.setgenevals();\n\t\t\tif (p.verbosity>0) s.out << \" number of evals: \" << s.getgenevals() << \"\\n\";\n\t\t\tint its = 1;\n\t\t\tlong long termits;\n\t\t\tint gits=1;\n\n\t\t\tif (p.limit_evals) termits = s.totalptevals();\n\t\t\telse termits=1;\n\t\t\tint trigger=0;\n\t\t\tint trainer_trigger=p.FE_train_gens;//*(p.popsize+p.popsize*p.eHC_on+p.popsize*p.pHC_on);\n\n\t\t\tint gen=0;\n\t\t\tint counter=0;\n\t\t\t//if(p.sel==2) // if using deterministic crowding, increase gen size\n\t\t\t//{\n\t\t\t//\tgen = p.g*(p.popsize*(p.rt_mut+p.rt_rep) + p.popsize*p.rt_cross/2);\n\t\t\t//\ttrigger = p.popsize*(p.rt_mut+p.rt_rep)+p.popsize*p.rt_cross/2;\n\t\t\t//}\n\t\t\t//else\n\t\t\t\tgen=p.g;\n\t\t\tlong long term, print_trigger;\n\t\t\tbool printed=false;\n\n\t\t\tif (p.limit_evals) {\n\t\t\t\tterm = p.max_evals;\n\t\t\t\tif (p.num_log_pts ==0) print_trigger=0;\n\t\t\t\telse print_trigger = p.max_evals/p.num_log_pts;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tprint_trigger=0;\n\t\t\t\tterm = gen;\n\t\t\t}\n\n\n\t\t\tfloat etmp;\n\t\t\t//print initial population\n\t\t\tif (p.print_init_pop) printpop(T.pop,p,s,logname,3);\n\t\t\tif (p.print_genome) printGenome(T,0,logname,d,p);\n\t\t\tif (p.print_db) printDB(T.pop,logname,d,p);\n\n\t\t\twhile (termits<=term && !stopcondition(T,p,d,s,FE[0]))\n\t\t\t{\n\n\t\t\t\t etmp = s.numevals[omp_get_thread_num()];\n\n\t\t\t\t if (!p.EstimateFitness && p.estimate_generality && p.G_shuffle)\n\t\t\t\t\tshuffle_data(d,p,r,s);\n\n\t\t\t\t assert (T.pop.size() == p.popsize);\n\n\t\t\t\t try{\n\t\t\t\t \tGeneration(T.pop,p,r,d,s,FE[0]);\n\t\t\t\t}\n\t\t\t\tcatch(std::exception& e){\n\t\t\t\t\tstd::cerr << e.what() << std::endl;\n\t\t\t\t}\n\t\t\t\tcatch(...){\n\t\t\t\t\tstd::cerr << \"not a standard error\\n\";\n\t\t\t\t}\n\t\t\t\t assert (T.pop.size()== p.popsize);\n\t\t\t\t //s.out << \"Generation evals = \" + to_string(static_cast<long long>(s.numevals[omp_get_thread_num()]-etmp)) + \"\\n\";\n\n\n\t\t\t\t if (its>trigger)\n\t\t\t\t {\n\t\t\t\t\t if (p.pHC_on && p.ERC)\n\t\t\t\t\t {\n\t\t\t\t\t\t etmp = s.numevals[omp_get_thread_num()];\n\t\t\t\t\t\t//#pragma omp parallel for\n\t\t\t \t\t\tfor(int k=0; k<T.pop.size(); ++k)\n\t\t\t \t\t\t\tHillClimb(T.pop.at(k),p,r,d,s,FE[0]);\n\t\t\t \t\t\t //s.out << \"Hill climb evals = \" + to_string(static_cast<long long>(s.numevals[omp_get_thread_num()]-etmp)) + \"\\n\";\n\n\n\t\t\t \t\t }\n\n\t\t\t\t\t if (p.eHC_on&& !p.eHC_mut)\n\t\t\t\t\t {\n\t\t\t\t\t\t etmp = s.numevals[omp_get_thread_num()];\n\t\t\t\t\t\t// boost::progress_timer tm1;\n\t\t\t\t\t\t//#pragma omp parallel for\n\t\t\t\t\t\tfor(int m=0; m<T.pop.size(); m++)\n\t\t\t\t\t\t\tEpiHC(T.pop.at(m),p,r,d,s,FE[0]);\n\t\t\t\t\t\t //s.out << \"EHC evals = \" + to_string(static_cast<long long>(s.numevals[omp_get_thread_num()]-etmp)) + \"\\n\";\n\t\t\t\t\t }\n                     if (p.SGD && p.ERC)\n                    {\n                        for(int k=0; k<T.pop.size(); ++k)\n                                StochasticGradient(T.pop.at(k),p,r,d,s,FE[0],gen);\n\n                    }\n\t\t\t\t\ts.setgenevals();\n\t\t\t\t\t//s.out << \"Elapsed time: \\n\";\n\t\t\t\t\tif (p.prto_arch_on){\n\t\t\t\t\t\tA.update(T.pop);\n\t\t\t\t\t\tif (p.print_archive) printpop(A.pop,p,s,logname,1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!p.limit_evals || s.totalptevals() >= print_trigger){\n\t\t\t\t\t\tif (p.print_data) printdatafile(T,s,p,r,dfout,counter,time.elapsed());\n\t\t\t\t\t\tif (p.print_every_pop) printpop(T.pop,p,s,logname,2);\n\t\t\t\t\t\tif (p.verbosity > 1){\n\t\t\t\t\t\t\tprintstats(T,counter,s,p,A);\n\t\t\t\t\t\t\ts.out << \"Total Time: \" << (int)floor(time.elapsed()/3600) << \" hr \" << ((int)time.elapsed() % 3600)/60 << \" min \" << (int)time.elapsed() % 60 << \" s\\n\";\n\t\t\t\t\t\t\ts.out << \"Total Evals: \" << s.totalevals() << \"\\n\";\n\t\t\t\t\t\t\ts.out << \"Point Evals: \" << s.totalptevals() << \"\\n\";\n\t\t\t\t\t\t\ts.out << \"Average evals per second: \" << (float)s.totalevals()/time.elapsed() << \"\\n\";\n\t\t\t\t\t\t\ts.out << \"Average point evals per second: \" << (float)s.totalptevals()/time.elapsed() << \"\\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (print_trigger!=0) print_trigger += p.max_evals/p.num_log_pts;\n\t\t\t\t\t\tif (p.print_genome) printGenome(T,counter,logname,d,p);\n\t\t\t\t\t\tif (p.print_db) printDB(T.pop,logname,d,p);\n\n\t\t\t\t\t\tprinted=true;\n\t\t\t\t\t}\n\n\t\t\t\t\t//if (p.sel==2)\n\t\t\t\t\t\t//trigger+=p.popsize*(p.rt_mut+p.rt_rep)+p.popsize*p.rt_cross/2;\n\t\t\t\t\t++counter;\n\n\t\t\t\t }\n\n\t\t\t\tif (p.EstimateFitness){\n\t\t\t\t\tEvolveFE(T.pop,FE,trainers,p,d,s,r);\n\t\t\t\t\tif (!p.limit_evals || printed){\n\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Evolving fitness estimators...\\n\";\n\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Best FE fit: \" << FE[0].fitness <<\"\\n\";\n\t\t\t\t\t\tif (p.estimate_generality) s.out << \"Best FE genty: \" << FE[0].genty <<\"\\n\";\n\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Current Fitness Estimator:\\n\";\n\n\t\t\t\t\t\tif (p.verbosity>0) {\n\t\t\t\t\t\t\tfor (int b=0;b<FE[0].FEpts.size();b++)\n\t\t\t\t\t\t\t\ts.out << FE[0].FEpts[b] << \" \";\n\t\t\t\t\t\t\ts.out << \"\\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tif (p.EstimateFitness){\n\t\t\t\t\tif(counter>trainer_trigger) {\n\t\t\t\t\t\tif (p.verbosity>0) s.out << \"Picking trainers...\\n\";\n\t\t\t\t\t\tPickTrainers(T.pop,FE,trainers,p,d,s);\n\t\t\t\t\t\ttrainer_trigger= counter + p.FE_train_gens; //*(p.popsize+p.popsize*p.eHC_on+p.popsize*p.pHC_on);\n\t\t\t\t\t\t//trainer_trigger=0;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tif (p.limit_evals) termits = s.totalptevals();\n\t\t\t\telse termits++;\n\t\t\t\tits++;\n\t\t\t\tprinted=false;\n\t\t\t}\n\n\n\t\t\tif (p.EstimateFitness || p.test_at_end){// assign real fitness values to final population and archive\n\t\t\t\tp.EstimateFitness=0;\n\t\t\t\tp.test_at_end = 0;\n\t\t\t\tFitness(T.pop,p,d,s,FE[0]);\n\t\t\t\tif (p.prto_arch_on) Fitness(A.pop,p,d,s,FE[0]);\n\t\t\t\tp.EstimateFitness=1;\n\t\t\t}\n\n\t\t\t\tif (p.print_data) printdatafile(T,s,p,r,dfout,counter,time.elapsed());\n\t\t\t\tif (p.print_best_ind) printbestind(T,p,s,logname);\n\t\t\t\tif (p.print_last_pop) printpop(T.pop,p,s,logname,0);\n\n\n\t\t\tif (p.prto_arch_on){\n\t\t\t\tif (A.pop.empty()) A.update(T.pop);\n\t\t\t\tif (p.print_archive) printpop(A.pop,p,s,logname,1);\n\t\t\t\t// save archive to best_prog for python\n\t\t\t\tif (p.return_pop){\n\t\t\t\t\tT.sortpop();\n\t\t\t\t\tpop_to_py(T.pop,best_prog);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tpop_to_py(A.pop,best_prog);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t// save best individual to best_prog for python\n\n\t\t\t\tif (p.return_pop){\n\t\t\t\t\tT.sortpop();\n\t\t\t\t\tpop_to_py(T.pop,best_prog);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tvector<ind> best(1);\n\t\t\t\t\tT.getbestind(best[0]);\n\t\t\t\t\tline_to_py(best[0].line,best_prog);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif (p.verbosity>0) s.out << \"\\n Program finished sucessfully.\\n\";\n\n// Py_END_ALLOW_THREADS\t} //end python gil unlock\n\t}\n\tcatch(std::exception& e){\n\t\tstd::cerr << e.what();\n\n\t}\n\n}\n\nBOOST_PYTHON_MODULE(elgp)\n{\n    def(\"runEllenGP\", runEllenGP);\n\t\t// import_array();\n}\n", "meta": {"hexsha": "3d7fdf424435d705132318d3cd0cb0593abe6c14", "size": 43435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "afp-eplex/ellen/runEllenGP.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/runEllenGP.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/runEllenGP.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": 31.5432098765, "max_line_length": 472, "alphanum_fraction": 0.5734545873, "num_tokens": 13544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.022977369366426914, "lm_q1q2_score": 0.00918661974627545}}
{"text": "//------------------------------------------------------------------------------\n// Copyright (c) 2018 Hsienchi Kuo (Allen Institute, Hanchuan Peng's team)\n// All rights reserved.\n//------------------------------------------------------------------------------\n\n/*******************************************************************************\n*\n*  Most of NeuronStructUtil class methods intend to operate on the whole neuron struct level.\n*  As 'utility' it is called, the functionalities provided in this class include:\n*    a. [Basic neuron struct operations]                   -- cropping SWC, scaling SWC, swc registration, etc.\n*    b. [Tree - subtree operations]                        -- extracting upstream or downstream of a given tree.\n*    c. [Neuron struct profiling methods]                  -- node-tile mapping, node-location mapping, etc.\n*    d. [SWC - ImgAnalyzer::connectedComponent operations] -- Methods of this category convert SWC into vector<ImgAnalyzer::connectedComponent>\n*\n*  Most of NeuronStructUtil class methods are implemented as static functions. The input NeuronTree is always set to be const so that it will not be modified.\n*  A typical function call would need at least three input arguments:\n*\n*\t\tNeuronStructUtil::func(const NeuronTree& inputTree, NeuronTree& outputTree, other input arguments);\n*\n********************************************************************************/\n\n#include <iostream>\n#include <iterator>\n#include <set>\n#include <cmath>\n\n#include <boost/filesystem.hpp>\n\n#include \"basic_4dimage.h\"\n\n#include \"NeuronStructUtilities.h\"\n#include \"ImgProcessor.h\"\n\nusing namespace boost;\n\n/* ======================================== Segment Operations ========================================= */\nsegUnit NeuronStructUtil::segUnitConnect_executer(const segUnit& segUnit1, const segUnit& segUnit2, connectOrientation connOrt)\n{\n\tif (segUnit1.tails.size() > 1 || segUnit2.tails.size() > 1)\n\t\tthrow invalid_argument(\"Currently forked segment connection is not supported. Do nothing and return\");\n\n\tsegUnit newSeg;\n\tQList<NeuronSWC> newSegNodes;\n\tQList<NeuronSWC> endEditedNodes;\n\n\tswitch (connOrt)\n\t{\n\tcase head_tail:\n\t{\n\t\tint connTailID = *segUnit2.tails.cbegin();\n\t\tendEditedNodes = segUnit1.nodes;\n\t\tendEditedNodes.begin()->parent = connTailID; // In current implementation, the 1st element of a seg must be a root.\n\t\tnewSegNodes.append(segUnit2.nodes);\n\t\tnewSegNodes.append(endEditedNodes);\n\t\tnewSeg.nodes = newSegNodes;\n\t\tbreak;\n\t}\n\tcase tail_head:\n\t{\n\t\tint connTailID = *segUnit1.tails.cbegin();\n\t\tendEditedNodes = segUnit2.nodes;\n\t\tendEditedNodes.begin()->parent = connTailID; // In current implementation, the 1st element of a seg must be a root. \n\t\tnewSegNodes.append(segUnit1.nodes);\n\t\tnewSegNodes.append(endEditedNodes);\n\t\tnewSeg.nodes = newSegNodes;\n\t\tbreak;\n\t}\n\tcase head_head:\n\t{\n\t\tint connTailID = segUnit2.head;\n\t\tfor (map<int, vector<size_t>>::const_iterator it = segUnit2.seg_childLocMap.cbegin(); it != segUnit2.seg_childLocMap.cend(); ++it)\n\t\t{\n\t\t\tsize_t nodeLoc = segUnit2.seg_nodeLocMap.at(it->first);\n\t\t\tNeuronSWC newNode = segUnit2.nodes.at(nodeLoc);\n\t\t\tif (it->second.empty())\n\t\t\t{\n\t\t\t\t//cout << newNode.x << \" \" << newNode.y << \" \" << newNode.z << endl;\n\t\t\t\tnewNode.parent = -1;\n\t\t\t}\n\t\t\telse newNode.parent = segUnit2.nodes.at(*(it->second.cbegin())).n;\n\t\t\tendEditedNodes.push_back(newNode);\n\t\t}\n\t\tnewSegNodes.append(segUnit1.nodes);\n\t\tnewSegNodes.begin()->parent = connTailID;\n\t\tnewSegNodes.append(endEditedNodes);\n\t\tnewSeg.nodes = newSegNodes;\n\t\tbreak;\n\t}\n\tcase tail_tail:\n\t{\n\t\tint connTailID = *segUnit2.tails.cbegin();\n\t\tfor (map<int, vector<size_t>>::const_iterator it = segUnit1.seg_childLocMap.cbegin(); it != segUnit1.seg_childLocMap.cend(); ++it)\n\t\t{\n\t\t\tsize_t nodeLoc = segUnit1.seg_nodeLocMap.at(it->first);\n\t\t\tNeuronSWC newNode = segUnit1.nodes.at(nodeLoc);\n\t\t\tif (it->second.empty()) newNode.parent = connTailID;\n\t\t\telse newNode.parent = segUnit1.nodes.at(*(it->second.cbegin())).n;\n\t\t\tendEditedNodes.push_back(newNode);\n\t\t}\n\t\tnewSegNodes.append(segUnit2.nodes);\n\t\tnewSegNodes.append(endEditedNodes);\n\t\tnewSeg.nodes = newSegNodes;\n\t\tbreak;\n\t}\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn newSeg;\n}\n/* ===================================================================================================== */\n\n\n\n/* ===================================== Neuron Struct Processing ====================================== */\nNeuronTree NeuronStructUtil::swcRegister(NeuronTree& inputTree, const NeuronTree& refTree)\n{\n\tdouble xShift, yShift, zShift;\n\tdouble xScale, yScale, zScale;\n\n\tdouble xmin = 10000, ymin = 10000, zmin = 10000;\n\tdouble xmax = 0, ymax = 0, zmax = 0;\n\tfor (QList<NeuronSWC>::iterator it = inputTree.listNeuron.begin(); it != inputTree.listNeuron.end(); ++it)\n\t{\n\t\tif (it->x < xmin) xmin = it->x;\n\t\tif (it->x > xmax) xmax = it->x;\n\t\tif (it->y < ymin) ymin = it->y;\n\t\tif (it->y > ymax) ymax = it->y;\n\t\tif (it->z < zmin) zmin = it->z;\n\t\tif (it->z > zmax) zmax = it->z;\n\t}\n\tdouble refXmin = 10000, refYmin = 10000, refZmin = 10000;\n\tdouble refXmax = 0, refYmax = 0, refZmax = 0;\n\tfor (QList<NeuronSWC>::const_iterator refIt = refTree.listNeuron.begin(); refIt != refTree.listNeuron.end(); ++refIt)\n\t{\n\t\tif (refIt->x < refXmin) refXmin = refIt->x;\n\t\tif (refIt->x > refXmax) refXmax = refIt->x;\n\t\tif (refIt->y < refYmin) refYmin = refIt->y;\n\t\tif (refIt->y > refYmax) refYmax = refIt->y;\n\t\tif (refIt->z < refZmin) refZmin = refIt->z;\n\t\tif (refIt->z > refZmax) refZmax = refIt->z;\n\t}\n\n\txScale = (refXmax - refXmin) / (xmax - xmin);\n\tyScale = (refYmax - refYmin) / (ymax - ymin);\n\tzScale = (refZmax - refZmin) / (zmax - zmin);\n\txShift = refXmin - xmin * xScale;\n\tyShift = refYmin - ymin * yScale;\n\tzShift = refZmin - zmin * zScale;\n\n\tNeuronTree outputTree;\n\tfor (int i = 0; i < inputTree.listNeuron.size(); ++i)\n\t{\n\t\tNeuronSWC newNode = inputTree.listNeuron.at(i);\n\t\tnewNode.x = newNode.x * xScale + xShift;\n\t\tnewNode.y = newNode.y * yScale + yShift;\n\t\tnewNode.z = newNode.z * zScale + zShift;\n\t\toutputTree.listNeuron.push_back(newNode);\n\t}\n\n\treturn outputTree;\n}\n\nNeuronTree NeuronStructUtil::swcCombine(const vector<NeuronTree>& inputTrees)\n{\n\tNeuronTree outputTree;\n\tptrdiff_t listSize = 0;\n\tint nodeIDmax = 0;\n\tfor (vector<NeuronTree>::const_iterator it = inputTrees.begin(); it != inputTrees.end(); ++it)\n\t{\n\t\tfor (QList<NeuronSWC>::iterator outputNodeIt = outputTree.listNeuron.begin(); outputNodeIt != outputTree.listNeuron.end(); ++outputNodeIt)\n\t\t\tif (outputNodeIt->n > nodeIDmax) nodeIDmax = outputNodeIt->n;\n\n\t\toutputTree.listNeuron.append(it->listNeuron);\n\t\tfor (QList<NeuronSWC>::iterator nodeIt = outputTree.listNeuron.begin() + listSize; nodeIt != outputTree.listNeuron.end(); ++nodeIt)\n\t\t{\n\t\t\tnodeIt->n = nodeIt->n + nodeIDmax;\n\t\t\tif (nodeIt->parent == -1) continue;\n\t\t\telse nodeIt->parent = nodeIt->parent + nodeIDmax;\n\t\t}\n\n\t\tlistSize = ptrdiff_t(outputTree.listNeuron.size());\n\t}\n\n\treturn outputTree;\n}\n\nvoid NeuronStructUtil::swcSlicer(const NeuronTree& inputTree, vector<NeuronTree>& outputTrees, int thickness)\n{\n\tQList<NeuronSWC> inputList = inputTree.listNeuron;\n\tint zMax = 0;\n\tptrdiff_t thicknessPtrDiff = ptrdiff_t(thickness); // Determining largest number of z in inputTree.\n\tfor (QList<NeuronSWC>::const_iterator it = inputTree.listNeuron.begin(); it != inputTree.listNeuron.end(); ++it)\n\t{\n\t\tint z = round(it->z);\n\t\tif (z >= zMax) zMax = z;\n\t}\n\n\tint treeNum = zMax / thickness + 1;\n\tvector<ptrdiff_t> delLocs;\n\tfor (int i = 0; i < treeNum; ++i)\n\t{\n\t\tNeuronTree outputTree;\n\t\toutputTrees.push_back(outputTree);\n\t\tfor (QList<NeuronSWC>::iterator it = inputList.begin(); it != inputList.end(); ++it)\n\t\t{\n\t\t\tif (it->z <= thickness * (i + 1))\n\t\t\t{\n\t\t\t\toutputTrees.at(i).listNeuron.push_back(*it);\n\t\t\t\tdelLocs.push_back(it - inputList.begin());\n\t\t\t}\n\t\t}\n\n\t\tsort(delLocs.rbegin(), delLocs.rend());\n\t\tfor (vector<ptrdiff_t>::iterator delIt = delLocs.begin(); delIt != delLocs.end(); ++delIt) inputList.erase(inputList.begin() + *delIt);\n\t\tdelLocs.clear();\n\t}\n}\n\nmap<int, QList<NeuronSWC>> NeuronStructUtil::swcSplitByType(const NeuronTree& inputTree)\n{\n\tmap<int, QList<NeuronSWC>> outputNodeTypeMap;\n\tmap<int, boost::container::flat_set<int>> nodeIDsetMap;\n\tfor (QList<NeuronSWC>::const_iterator it = inputTree.listNeuron.begin(); it != inputTree.listNeuron.end(); ++it)\n\t{\n\t\toutputNodeTypeMap[it->type].append(*it);\n\t\tnodeIDsetMap[it->type].insert(it->n);\n\t}\n\tfor (map<int, QList<NeuronSWC>>::iterator mapIt = outputNodeTypeMap.begin(); mapIt != outputNodeTypeMap.end(); ++mapIt)\n\t{\n\t\tfor (QList<NeuronSWC>::iterator nodeIt = mapIt->second.begin(); nodeIt != mapIt->second.end(); ++nodeIt)\n\t\t{\n\t\t\tif (nodeIt->parent == -1) continue;\n\t\t\telse if (nodeIDsetMap.at(nodeIt->type).find(nodeIt->parent) == nodeIDsetMap.at(nodeIt->type).end()) nodeIt->parent = -1;\n\t\t}\n\t}\n\n\treturn outputNodeTypeMap;\n}\n\nNeuronTree NeuronStructUtil::swcSubtraction(const NeuronTree& targetTree, const NeuronTree& refTree, int type)\n{\n\tboost::container::flat_map<string, QList<NeuronSWC>> targetNodeTileMap;\n\tboost::container::flat_map<string, QList<NeuronSWC>> refNodeTileMap;\n\tNeuronStructUtil::nodeTileMapGen(targetTree, targetNodeTileMap);\n\tNeuronStructUtil::nodeTileMapGen(refTree, refNodeTileMap);\n\n\tif (type == 0)\n\t{\n\t\tvector<ptrdiff_t> delLocs;\n\t\tfor (boost::container::flat_map<string, QList<NeuronSWC>>::iterator targetTileIt = targetNodeTileMap.begin(); targetTileIt != targetNodeTileMap.end(); ++targetTileIt)\n\t\t{\n\t\t\tif (refNodeTileMap.find(targetTileIt->first) != refNodeTileMap.end())\n\t\t\t{\n\t\t\t\tfor (QList<NeuronSWC>::iterator checkIt1 = targetTileIt->second.begin(); checkIt1 != targetTileIt->second.end(); ++checkIt1)\n\t\t\t\t{\n\t\t\t\t\tfor (QList<NeuronSWC>::iterator checkIt2 = refNodeTileMap.at(targetTileIt->first).begin(); checkIt2 != refNodeTileMap.at(targetTileIt->first).end(); ++checkIt2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (checkIt1->x == checkIt2->x && checkIt1->y == checkIt2->y && checkIt1->z == checkIt2->z)\n\t\t\t\t\t\t\tdelLocs.push_back(ptrdiff_t(checkIt1 - targetTileIt->second.begin()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse continue;\n\n\t\t\tsort(delLocs.rbegin(), delLocs.rend());\n\t\t\tfor (vector<ptrdiff_t>::iterator delIt = delLocs.begin(); delIt != delLocs.end(); ++delIt) targetTileIt->second.erase(targetTileIt->second.begin() + *delIt);\n\t\t\tdelLocs.clear();\n\t\t}\n\t}\n\telse\n\t{\n\t\tvector<ptrdiff_t> delLocs;\n\t\tfor (boost::container::flat_map<string, QList<NeuronSWC>>::iterator targetTileIt = targetNodeTileMap.begin(); targetTileIt != targetNodeTileMap.end(); ++targetTileIt)\n\t\t{\n\t\t\tif (refNodeTileMap.find(targetTileIt->first) != refNodeTileMap.end())\n\t\t\t{\n\t\t\t\tfor (QList<NeuronSWC>::iterator checkIt1 = targetTileIt->second.begin(); checkIt1 != targetTileIt->second.end(); ++checkIt1)\n\t\t\t\t{\n\t\t\t\t\tfor (QList<NeuronSWC>::iterator checkIt2 = refNodeTileMap.at(targetTileIt->first).begin(); checkIt2 != refNodeTileMap.at(targetTileIt->first).end(); ++checkIt2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (checkIt1->x == checkIt2->x && checkIt1->y == checkIt2->y && checkIt1->z == checkIt2->z && checkIt2->type == type)\n\t\t\t\t\t\t\tdelLocs.push_back(ptrdiff_t(checkIt1 - targetTileIt->second.begin()));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse continue;\n\n\t\t\tsort(delLocs.rbegin(), delLocs.rend());\n\t\t\tfor (vector<ptrdiff_t>::iterator delIt = delLocs.begin(); delIt != delLocs.end(); ++delIt)\n\t\t\t{\n\t\t\t\tif (targetTileIt->second.begin() + *delIt >= targetTileIt->second.end()) continue;\n\t\t\t\telse targetTileIt->second.erase(targetTileIt->second.begin() + *delIt);\n\t\t\t}\n\t\t\tdelLocs.clear();\n\t\t}\n\t}\n\n\tNeuronTree outputTree;\n\tboost::container::flat_set<int> nodeIDs;\n\tfor (boost::container::flat_map<string, QList<NeuronSWC>>::iterator mapIt = targetNodeTileMap.begin(); mapIt != targetNodeTileMap.end(); ++mapIt)\n\t{\n\t\toutputTree.listNeuron.append(mapIt->second);\n\t\tfor (QList<NeuronSWC>::iterator nodeIt = mapIt->second.begin(); nodeIt != mapIt->second.end(); ++nodeIt)\n\t\t\tnodeIDs.insert(nodeIt->n);\n\t}\n\n\tfor (QList<NeuronSWC>::iterator nodeIt = outputTree.listNeuron.begin(); nodeIt != outputTree.listNeuron.end(); ++nodeIt)\n\t{\n\t\tif (nodeIt->parent == -1) continue;\n\t\telse \n\t\t\tif (nodeIDs.find(nodeIt->parent) == nodeIDs.end()) nodeIt->parent = -1;\n\t}\n\n\treturn outputTree;\n}\n\nvoid NeuronStructUtil::treeUpSample(const profiledTree& inputProfiledTree, profiledTree& outputProfiledTree, float intervalLength)\n{\n\tsize_t maxNodeID = 0;\n\tfor (QList<NeuronSWC>::const_iterator it = inputProfiledTree.tree.listNeuron.begin(); it != inputProfiledTree.tree.listNeuron.end(); ++it)\n\t\tif (it->n > maxNodeID) maxNodeID = it->n;\n\n\tfor (map<int, segUnit>::const_iterator segIt = inputProfiledTree.segs.begin(); segIt != inputProfiledTree.segs.end(); ++segIt)\n\t{\n\t\tQList<NeuronSWC> newSegNodes;\n\t\tmap<int, vector<QList<NeuronSWC>>> interpolatedNodeMap;\n\t\tfor (QList<NeuronSWC>::const_iterator nodeIt = segIt->second.nodes.begin(); nodeIt != segIt->second.nodes.end() - 1; ++nodeIt)\n\t\t{\n\t\t\tvector<size_t> childLocs = segIt->second.seg_childLocMap.at(nodeIt->n);\n\t\t\tfor (vector<size_t>::iterator childLocIt = childLocs.begin(); childLocIt != childLocs.end(); ++childLocIt)\n\t\t\t{\n\t\t\t\tfloat dist = sqrt((segIt->second.nodes.at(*childLocIt).x - nodeIt->x) * (segIt->second.nodes.at(*childLocIt).x - nodeIt->x) +\n\t\t\t\t\t(segIt->second.nodes.at(*childLocIt).y - nodeIt->y) * (segIt->second.nodes.at(*childLocIt).y - nodeIt->y) +\n\t\t\t\t\t(segIt->second.nodes.at(*childLocIt).z - nodeIt->z) * (segIt->second.nodes.at(*childLocIt).z - nodeIt->z));\n\t\t\t\tint intervals = int(dist / intervalLength);\n\t\t\t\tfloat intervalX = (segIt->second.nodes.at(*childLocIt).x - nodeIt->x) / float(intervals);\n\t\t\t\tfloat intervalY = (segIt->second.nodes.at(*childLocIt).y - nodeIt->y) / float(intervals);\n\t\t\t\tfloat intervalZ = (segIt->second.nodes.at(*childLocIt).z - nodeIt->z) / float(intervals);\n\n\t\t\t\tQList<NeuronSWC> interpolatedNodes;\n\t\t\t\tfor (int i = 1; i < intervals; ++i)\n\t\t\t\t{\n\t\t\t\t\tNeuronSWC newNode;\n\t\t\t\t\tnewNode.x = nodeIt->x + intervalX * float(i);\n\t\t\t\t\tnewNode.y = nodeIt->y + intervalY * float(i);\n\t\t\t\t\tnewNode.z = nodeIt->z + intervalZ * float(i);\n\t\t\t\t\tnewNode.type = nodeIt->type;\n\t\t\t\t\t++maxNodeID;\n\t\t\t\t\tnewNode.n = maxNodeID;\n\t\t\t\t\tnewNode.parent = maxNodeID - 1;\n\t\t\t\t\tinterpolatedNodes.push_back(newNode);\n\t\t\t\t}\n\t\t\t\tinterpolatedNodes.push_back(segIt->second.nodes.at(*childLocIt));\n\t\t\t\tif (interpolatedNodes.size() >= 2)\n\t\t\t\t{\n\t\t\t\t\tinterpolatedNodes.back().parent = (interpolatedNodes.end() - 2)->n;\n\t\t\t\t\tinterpolatedNodes.begin()->parent = nodeIt->n;\n\t\t\t\t}\n\n\t\t\t\tinterpolatedNodeMap[nodeIt->n].push_back(interpolatedNodes);\n\t\t\t}\n\t\t}\n\t\tfor (map<int, vector<QList<NeuronSWC>>>::iterator mapIt = interpolatedNodeMap.begin(); mapIt != interpolatedNodeMap.end(); ++mapIt)\n\t\t\tfor (vector<QList<NeuronSWC>>::iterator qlistIt = mapIt->second.begin(); qlistIt != mapIt->second.end(); ++qlistIt) newSegNodes.append(*qlistIt);\n\t\tnewSegNodes.push_front(segIt->second.nodes.at(segIt->second.seg_nodeLocMap.at(segIt->second.head)));\n\n\t\tsegUnit newSegUnit;\n\t\tnewSegUnit.nodes = newSegNodes;\n\t\toutputProfiledTree.segs.insert(pair<int, segUnit>(segIt->first, newSegUnit));\n\t\toutputProfiledTree.tree.listNeuron.append(newSegNodes);\n\t}\n}\n\nprofiledTree NeuronStructUtil::treeDownSample(const profiledTree& inputProfiledTree, int nodeInterval)\n{\n\t// -- This method \"down samples\" the input tree segment by segment. \n\t// -- A recursive down sampling method [NeuronStructExplorer::rc_segDownSample] is called in this function to deal with all possible braching points in each segment.\n\t// -- NOTE, this method is essentially used for straightening / smoothing segments when there are too many zigzagging.  \n\n\tNeuronTree outputTree;\n\tQList<NeuronSWC> currSegOutputList;\n\tfor (map<int, segUnit>::const_iterator it = inputProfiledTree.segs.begin(); it != inputProfiledTree.segs.end(); ++it)\n\t{\n\t\t//if (it->second.seg_childLocMap.empty()) continue; => Using this line is not safe. Can occasionally result in program crash.\n\t\t// The safety of seg_childLocMap needs to be investigated later.\n\t\tif (it->second.nodes.size() <= 3) continue;\n\n\t\tcurrSegOutputList.clear();\n\t\tcurrSegOutputList.push_back(*(it->second.nodes.begin()));\n\t\tNeuronStructUtil::rc_segDownSample(it->second, currSegOutputList, it->second.head, nodeInterval);\n\t\toutputTree.listNeuron.append(currSegOutputList);\n\t}\n\n\tvector<size_t> delLocs;\n\tfor (QList<NeuronSWC>::iterator nodeIt = outputTree.listNeuron.begin(); nodeIt != outputTree.listNeuron.end(); ++nodeIt)\n\t\tif (nodeIt->n == nodeIt->parent) delLocs.push_back(size_t(nodeIt - outputTree.listNeuron.begin()));\n\tsort(delLocs.rbegin(), delLocs.rend());\n\tfor (vector<size_t>::iterator delIt = delLocs.begin(); delIt != delLocs.end(); ++delIt) outputTree.listNeuron.erase(outputTree.listNeuron.begin() + ptrdiff_t(*delIt));\n\tprofiledTree outputProfiledTree(outputTree);\n\n\treturn outputProfiledTree;\n}\n\nvoid NeuronStructUtil::rc_segDownSample(const segUnit& inputSeg, QList<NeuronSWC>& outputNodeList, int branchigNodeID, int interval)\n{\n\tint currNodeID = 0, count = 0;\n\tfor (vector<size_t>::const_iterator childIt = inputSeg.seg_childLocMap.at(branchigNodeID).begin(); childIt != inputSeg.seg_childLocMap.at(branchigNodeID).end(); ++childIt)\n\t{\n\t\toutputNodeList.push_back(inputSeg.nodes.at(*childIt));\n\t\toutputNodeList.last().parent = branchigNodeID;\n\t\tcurrNodeID = inputSeg.nodes.at(*childIt).n;\n\t\tcount = 0;\n\t\twhile (inputSeg.seg_childLocMap.at(currNodeID).size() > 0)\n\t\t{\n\t\t\tif (inputSeg.seg_childLocMap.at(currNodeID).size() >= 2) // branching point found, function recursively called\n\t\t\t{\n\t\t\t\toutputNodeList.push_back(inputSeg.nodes.at(inputSeg.seg_nodeLocMap.at(currNodeID)));\n\t\t\t\toutputNodeList.last().parent = (outputNodeList.end() - 2)->n;\n\t\t\t\tNeuronStructUtil::rc_segDownSample(inputSeg, outputNodeList, currNodeID, interval);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t++count;\n\t\t\tcurrNodeID = inputSeg.nodes.at(*(inputSeg.seg_childLocMap.at(currNodeID).begin())).n;\n\t\t\tif (count % interval == 0 || inputSeg.seg_childLocMap.at(currNodeID).size() == 0) // The tail(s) of the segment needs to stay.\n\t\t\t{\n\t\t\t\toutputNodeList.push_back(inputSeg.nodes.at(inputSeg.seg_nodeLocMap.at(currNodeID)));\n\t\t\t\toutputNodeList.last().parent = (outputNodeList.end() - 2)->n;\n\t\t\t}\n\t\t}\n\t}\n}\n/* ===================================== END of [Neuron Struct Processing] ===================================== */\n\n\n\n/* ================================== SWC <-> ImgAnalyzer::connectedComponents ================================== */\nvector<connectedComponent> NeuronStructUtil::swc2signal2DBlobs(const NeuronTree& inputTree)\n{\n\t// -- Finds signal blobs \"slice by slice\" from input NeuronTree. Each slice is independent to one another.\n\t// -- Therefore, the same real blobs in 3D are consists of certain amount of 2D \"blob slices\" produced by this method. \n\t// -- Each 2D blob slice accounts for 1 ImgAnalyzer::connectedComponent.\n\n\tvector<NeuronSWC> allNodes;\n\tfor (QList<NeuronSWC>::const_iterator it = inputTree.listNeuron.begin(); it != inputTree.listNeuron.end(); ++it) allNodes.push_back(*it);\n\tbool longList = false;\n\n\tvector<connectedComponent> connComps2D;\n\tint islandCount = 0;\n\tif (allNodes.size() >= 100000)\n\t{\n\t\tlongList = true;\n\t\tcout << \"number of SWC nodes processed: \";\n\t}\n\tfor (vector<NeuronSWC>::iterator nodeIt = allNodes.begin(); nodeIt != allNodes.end(); ++nodeIt)\n\t{\n\t\tif (longList)\n\t\t{\n\t\t\tif (int(nodeIt - allNodes.begin()) % 10000 == 0) cout << int(nodeIt - allNodes.begin()) << \" \";\n\t\t}\n\n\t\tfor (vector<connectedComponent>::iterator connIt = connComps2D.begin(); connIt != connComps2D.end(); ++connIt)\n\t\t{\n\t\t\tif (connIt->coordSets.empty()) continue;\n\t\t\telse if (int(nodeIt->z) == connIt->coordSets.begin()->first)\n\t\t\t{\n\t\t\t\tfor (set<vector<int>>::iterator dotIt = connIt->coordSets[int(nodeIt->z)].begin(); dotIt != connIt->coordSets[int(nodeIt->z)].end(); ++dotIt)\n\t\t\t\t{\n\t\t\t\t\tif (int(nodeIt->x) <= dotIt->at(0) + 1 && int(nodeIt->x) >= dotIt->at(0) - 1 &&\n\t\t\t\t\t\tint(nodeIt->y) <= dotIt->at(1) + 1 && int(nodeIt->y) >= dotIt->at(1) - 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tvector<int> newCoord(3);\n\t\t\t\t\t\tnewCoord[0] = int(nodeIt->x);\n\t\t\t\t\t\tnewCoord[1] = int(nodeIt->y);\n\t\t\t\t\t\tnewCoord[2] = int(nodeIt->z);\n\t\t\t\t\t\tconnIt->coordSets[newCoord[2]].insert(newCoord);\n\t\t\t\t\t\tconnIt->size = connIt->size + 1;\n\n\t\t\t\t\t\tif (newCoord[0] < connIt->xMin) connIt->xMin = newCoord[0];\n\t\t\t\t\t\telse if (newCoord[0] > connIt->xMax) connIt->xMax = newCoord[0];\n\n\t\t\t\t\t\tif (newCoord[1] < connIt->yMin) connIt->yMin = newCoord[1];\n\t\t\t\t\t\telse if (newCoord[1] > connIt->yMax) connIt->yMax = newCoord[1];\n\n\t\t\t\t\t\tgoto NODE_INSERTED;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\t++islandCount;\n\t\t\tconnectedComponent newIsland;\n\t\t\tnewIsland.islandNum = islandCount;\n\t\t\tvector<int> newCoord(3);\n\t\t\tnewCoord[0] = int(nodeIt->x);\n\t\t\tnewCoord[1] = int(nodeIt->y);\n\t\t\tnewCoord[2] = int(nodeIt->z);\n\t\t\tset<vector<int>> coordSet;\n\t\t\tcoordSet.insert(newCoord);\n\t\t\tnewIsland.coordSets.insert(pair<int, set<vector<int>>>(newCoord[2], coordSet));\n\t\t\tnewIsland.xMax = newCoord[0];\n\t\t\tnewIsland.xMin = newCoord[0];\n\t\t\tnewIsland.yMax = newCoord[1];\n\t\t\tnewIsland.yMin = newCoord[1];\n\t\t\tnewIsland.zMin = newCoord[2];\n\t\t\tnewIsland.zMax = newCoord[2];\n\t\t\tnewIsland.size = 1;\n\t\t\tconnComps2D.push_back(newIsland);\n\t\t}\n\n\tNODE_INSERTED:\n\t\tcontinue;\n\t}\n\t//cout << endl << endl;\n\n\tvector<float> center(3);\n\tfor (vector<connectedComponent>::iterator it = connComps2D.begin(); it != connComps2D.end(); ++it)\n\t\tChebyshevCenter_connComp(*it);\n\n\treturn connComps2D;\n}\n\nvector<connectedComponent> NeuronStructUtil::swc2signal3DBlobs(const NeuronTree& inputTree)\n{\n\t// -- This method is a wrapper of NeuronStructUtil::swc2signal2DBlobs and NeuronStructUtil::merge2DConnComponent.\n\t// -- It produces 3D signal blobs by calling the two swc2signal2DBlobs and merge2DConnComponent sequentially.\n\n\tvector<connectedComponent> inputConnCompList = NeuronStructUtil::swc2signal2DBlobs(inputTree);\n\tvector<connectedComponent> outputConnCompList = NeuronStructUtil::merge2DConnComponent(inputConnCompList);\n\n\treturn outputConnCompList;\n}\n\nvector<connectedComponent> NeuronStructUtil::merge2DConnComponent(const vector<connectedComponent>& inputConnCompList)\n{\n\t// -- This method finds 3D signal blobs by grouping 2D signal blobs together, which are generated by NeuronStructUtil::swc2signal2DBlobs.\n\t// -- This method is typically called by NeuronStructUtil::swc2signal2DBlobs when identifying 3D blobs from 2D ones.\n\t// -- The approach is consists of 2 stages:\n\t//\t\t1. Identifying the same 3D blobs slice by slice.\n\t//\t\t2. Merging 3D blobs that contain the same 2D blobs.\n\n\tcout << \"Merging 2D signal blobs..\" << endl;\n\tcout << \"-- processing slice \";\n\n\tvector<connectedComponent> outputConnCompList;\n\n\tint zMax = 0;\n\n\t// -- I notice that boost's container templates are able to lift up the performace by ~30%.\n\tboost::container::flat_map<int, boost::container::flat_set<int>> b2Dtob3Dmap;\n\tb2Dtob3Dmap.clear();\n\tboost::container::flat_map<int, boost::container::flat_set<int>> b3Dcomps;  // a map from 3D connected components to all of its associated 2D connected components\n\tb3Dcomps.clear();\n\t// ---------------------------------------------------------------------------------------\n\n\t// --------- First slice, container initialization --------------\n\tint sliceBlobCount = 0;\n\tfor (vector<connectedComponent>::const_iterator it = inputConnCompList.begin(); it != inputConnCompList.end(); ++it)\n\t{\n\t\tif (it->coordSets.begin()->first > zMax) zMax = it->coordSets.begin()->first;\n\n\t\tif (it->coordSets.begin()->first == 0) // 1st slice connected components profile initialization\n\t\t{\n\t\t\t++sliceBlobCount;\n\t\t\tboost::container::flat_set<int> blob3D;\n\t\t\tblob3D.insert(sliceBlobCount);\n\t\t\tb2Dtob3Dmap.insert(pair<int, boost::container::flat_set<int>>(it->islandNum, blob3D));\n\t\t\tboost::container::flat_set<int> comps;\n\t\t\tcomps.insert(it->islandNum);\n\t\t\tb3Dcomps[sliceBlobCount] = comps;\n\t\t}\n\t}\n\t// -----------------------------------------------------------\n\n\t// ------------------------------------------- Merge 2D blobs from 2 adjacent slices -------------------------------------------\n\tvector<connectedComponent> currSliceConnComps;\n\tvector<connectedComponent> preSliceConnComps;\n\tsize_t increasedSize;\n\tfor (int i = 1; i <= zMax; ++i)\n\t{\n\t\tcurrSliceConnComps.clear();\n\t\tpreSliceConnComps.clear();\n\n\t\tincreasedSize = 0;\n\t\tfor (vector<connectedComponent>::const_iterator it = inputConnCompList.begin(); it != inputConnCompList.end(); ++it)\n\t\t\tif (it->coordSets.begin()->first == i) currSliceConnComps.push_back(*it); // collect all connected components from the current slice\n\t\tif (currSliceConnComps.empty())\n\t\t{\n\t\t\t//cout << i << \"->0 \";\n\t\t\tcontinue;\n\t\t}\n\n\t\tcout << i << \"->\";\n\t\tfor (vector<connectedComponent>::const_iterator it = inputConnCompList.begin(); it != inputConnCompList.end(); ++it)\n\t\t\tif (it->coordSets.begin()->first == i - 1) preSliceConnComps.push_back(*it);  // collect all connected components from the previous slice\n\t\tif (preSliceConnComps.empty())\n\t\t{\n\t\t\t// If the previous slice is empty, all 2D components found in the current slice will be part of new 3D components.\n\t\t\tfor (vector<connectedComponent>::iterator newCompsIt = currSliceConnComps.begin(); newCompsIt != currSliceConnComps.end(); ++newCompsIt)\n\t\t\t{\n\t\t\t\t++sliceBlobCount;\n\t\t\t\tboost::container::flat_set<int> blob3D;\n\t\t\t\tblob3D.insert(sliceBlobCount);\n\t\t\t\tb2Dtob3Dmap.insert(pair<int, boost::container::flat_set<int>>(newCompsIt->islandNum, blob3D));\n\t\t\t\tboost::container::flat_set<int> comps;\n\t\t\t\tcomps.insert(newCompsIt->islandNum);\n\t\t\t\tb3Dcomps[sliceBlobCount] = comps;\n\t\t\t\tincreasedSize = increasedSize + comps.size();\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (vector<connectedComponent>::iterator currIt = currSliceConnComps.begin(); currIt != currSliceConnComps.end(); ++currIt)\n\t\t{\n\t\t\tbool merged = false;\n\t\t\tfor (vector<connectedComponent>::iterator preIt = preSliceConnComps.begin(); preIt != preSliceConnComps.end(); ++preIt)\n\t\t\t{\n\t\t\t\t// First, use component boundaries to quickly exclude those pixels that can't be connected to any existing components.\n\t\t\t\t// And then create new components for these pixels.\n\t\t\t\tif (currIt->xMin > preIt->xMax + 2 || currIt->xMax < preIt->xMin - 2 ||\n\t\t\t\t\tcurrIt->yMin > preIt->yMax + 2 || currIt->yMax < preIt->yMin - 2) continue; \n\n\t\t\t\tfor (set<vector<int>>::iterator currDotIt = currIt->coordSets.begin()->second.begin(); currDotIt != currIt->coordSets.begin()->second.end(); ++currDotIt)\n\t\t\t\t{\n\t\t\t\t\tfor (set<vector<int>>::iterator preDotIt = preIt->coordSets.begin()->second.begin(); preDotIt != preIt->coordSets.begin()->second.end(); ++preDotIt)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (currDotIt->at(0) >= preDotIt->at(0) - 1 && currDotIt->at(0) <= preDotIt->at(0) + 1 &&\n\t\t\t\t\t\t\tcurrDotIt->at(1) >= preDotIt->at(1) - 1 && currDotIt->at(1) <= preDotIt->at(1) + 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmerged = true;\n\t\t\t\t\t\t\t// Find out to which 3D component the 2D component connected to the pixel belong.    \n\t\t\t\t\t\t\tboost::container::flat_set<int> asso3Dblob = b2Dtob3Dmap[preIt->islandNum];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Register the component of the pixel in the current slice to b2Dtob3Dmap.\n\t\t\t\t\t\t\tb2Dtob3Dmap.insert(pair<int, boost::container::flat_set<int>>(currIt->islandNum, asso3Dblob));\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Add a new entry of newly identified 2D component that is connected to the existing 3D component to b3Dcomps.\n\t\t\t\t\t\t\tfor (boost::container::flat_set<int>::iterator blob3DIt = asso3Dblob.begin(); blob3DIt != asso3Dblob.end(); ++blob3DIt)\n\t\t\t\t\t\t\t\tb3Dcomps[*blob3DIt].insert(currIt->islandNum);\n\n\t\t\t\t\t\t\tgoto BLOB_MERGED;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!merged) continue;\n\n\t\t\tBLOB_MERGED:\n\t\t\t\tmerged = true;\n\t\t\t}\n\n\t\t\tif (!merged) // All 2D blobs in the current slice fail to find its associated 3D blobs. Create new 3D blobs for them here.\n\t\t\t{\n\t\t\t\t++sliceBlobCount;\n\t\t\t\tboost::container::flat_set<int> newBlob3D;\n\t\t\t\tnewBlob3D.insert(sliceBlobCount);\n\t\t\t\tb2Dtob3Dmap.insert(pair<int, boost::container::flat_set<int>>(currIt->islandNum, newBlob3D));\n\t\t\t\tboost::container::flat_set<int> comps;\n\t\t\t\tcomps.insert(currIt->islandNum);\n\t\t\t\tb3Dcomps[sliceBlobCount] = comps;\n\t\t\t\tincreasedSize = increasedSize + comps.size();\n\t\t\t}\n\t\t}\n\t\tcout << increasedSize << \", \";\n\t}\n\tcout << endl;\n\tcout << \"Done merging 2D blobs from every 2 slices.\" << endl;\n\t// ---------------------------------------- END of [Merge 2D blobs from 2 adjacent slices] -------------------------------------------\n\n\t// ------------------------------------------ Merge 3D blobs --------------------------------------------\n\t// Merge any 3D blobs if any of them share the same 2D blob members.\n\tcout << \"Now merging 3D blobs..\" << endl;\n\tcout << \" -- original 3D blobs number: \" << b3Dcomps.size() << endl;\n\tbool mergeFinish = false;\n\tint currBaseBlob = 1;\n\twhile (!mergeFinish)\n\t{\n\t\tfor (boost::container::flat_map<int, boost::container::flat_set<int>>::iterator checkIt1 = b3Dcomps.begin(); checkIt1 != b3Dcomps.end(); ++checkIt1)\n\t\t{\n\t\t\tif (checkIt1->first < currBaseBlob) continue;\n\t\t\tfor (boost::container::flat_map<int, boost::container::flat_set<int>>::iterator checkIt2 = checkIt1 + 1; checkIt2 != b3Dcomps.end(); ++checkIt2)\n\t\t\t{\n\t\t\t\t//if (checkIt2 == checkIt1) continue;\n\t\t\t\tfor (boost::container::flat_set<int>::iterator member1 = checkIt1->second.begin(); member1 != checkIt1->second.end(); ++member1)\n\t\t\t\t{\n\t\t\t\t\tfor (boost::container::flat_set<int>::iterator member2 = checkIt2->second.begin(); member2 != checkIt2->second.end(); ++member2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (*member2 == *member1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcheckIt1->second.insert(checkIt2->second.begin(), checkIt2->second.end());\n\t\t\t\t\t\t\tb3Dcomps.erase(checkIt2);\n\t\t\t\t\t\t\tcurrBaseBlob = checkIt1->first;\n\t\t\t\t\t\t\tcout << \"  merging blob \" << checkIt1->first << \" and blob \" << checkIt2->first << endl;\n\t\t\t\t\t\t\tgoto MERGED;\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\tmergeFinish = true;\n\n\tMERGED:\n\t\tcontinue;\n\t}\n\tcout << \" -- new 3D blobs number: \" << b3Dcomps.size() << endl;\n\tcout << \"    ------------------------------\" << endl << endl;\n\t// --------------------------------------- END of [Merge 3D blobs] --------------------------------------\n\n\t// ------------------------------------- Create 3D connected component data -------------------------------------\n\tmap<int, connectedComponent> compsMap;\n\tfor (vector<connectedComponent>::const_iterator inputIt = inputConnCompList.begin(); inputIt != inputConnCompList.end(); ++inputIt)\n\t\tcompsMap.insert(pair<int, connectedComponent>(inputIt->islandNum, *inputIt));\n\tint newLabel = 0;\n\tfor (boost::container::flat_map<int, boost::container::flat_set<int>>::iterator it = b3Dcomps.begin(); it != b3Dcomps.end(); ++it)\n\t{\n\t\t++newLabel;\n\t\tconnectedComponent newComp;\n\t\tnewComp.islandNum = newLabel;\n\t\tnewComp.size = 0;\n\t\tnewComp.xMax = 0; newComp.xMin = 1000000;\n\t\tnewComp.yMax = 0; newComp.yMin = 1000000;\n\t\tnewComp.zMax = 0; newComp.zMin = 1000000;\n\t\tfor (boost::container::flat_set<int>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) // *it2 = 2D connected component's [islandNum]\n\t\t{\n\t\t\t// A 3D connected component may contain different 2D components from the same slice.\n\t\t\tif (newComp.coordSets.find(compsMap.at(*it2).coordSets.begin()->first) != newComp.coordSets.end())\n\t\t\t{\n\t\t\t\tfor (set<vector<int>>::iterator it3 = compsMap.at(*it2).coordSets.begin()->second.begin(); it3 != compsMap.at(*it2).coordSets.begin()->second.end(); ++it3)\n\t\t\t\t\tnewComp.coordSets.at(compsMap.at(*it2).coordSets.begin()->first).insert(*it3);\n\t\t\t\t\n\t\t\t\tnewComp.xMax = getMax(newComp.xMax, compsMap.at(*it2).xMax);\n\t\t\t\tnewComp.xMin = getMin(newComp.xMin, compsMap.at(*it2).xMin);\n\t\t\t\tnewComp.yMax = getMax(newComp.yMax, compsMap.at(*it2).yMax);\n\t\t\t\tnewComp.yMin = getMin(newComp.yMin, compsMap.at(*it2).yMin);\n\t\t\t\tnewComp.zMax = getMax(newComp.zMax, compsMap.at(*it2).zMax);\n\t\t\t\tnewComp.zMin = getMin(newComp.zMin, compsMap.at(*it2).zMin);\n\t\t\t\tnewComp.size = newComp.size + compsMap.at(*it2).size;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnewComp.coordSets.insert(pair<int, set<vector<int>>>(compsMap.at(*it2).coordSets.begin()->first, compsMap.at(*it2).coordSets.begin()->second));\n\t\t\t\tnewComp.xMax = getMax(newComp.xMax, compsMap.at(*it2).xMax);\n\t\t\t\tnewComp.xMin = getMin(newComp.xMin, compsMap.at(*it2).xMin);\n\t\t\t\tnewComp.yMax = getMax(newComp.yMax, compsMap.at(*it2).yMax);\n\t\t\t\tnewComp.yMin = getMin(newComp.yMin, compsMap.at(*it2).yMin);\n\t\t\t\tnewComp.zMax = getMax(newComp.zMax, compsMap.at(*it2).zMax);\n\t\t\t\tnewComp.zMin = getMin(newComp.zMin, compsMap.at(*it2).zMin);\n\t\t\t\tnewComp.size = newComp.size + compsMap.at(*it2).size;\n\t\t\t}\n\t\t}\n\n\t\toutputConnCompList.push_back(newComp);\n\t}\n\t// --------------------------------- END of [Create 3D connected component data] ---------------------------------\n\n\treturn outputConnCompList;\n}\n\nNeuronTree NeuronStructUtil::blobs2tree(const vector<connectedComponent>& inputconnComp, bool usingRadius2compNum)\n{\n\t// -- This method produces a NeuronTree that is used to store connected component information. The radius column is ususally used for component label.\n\n\tNeuronTree outputTree;\n\tfor (vector<connectedComponent>::const_iterator it = inputconnComp.begin(); it != inputconnComp.end(); ++it)\n\t{\n\t\tfor (map<int, set<vector<int>>>::const_iterator sliceIt = it->coordSets.begin(); sliceIt != it->coordSets.end(); ++sliceIt)\n\t\t{\n\t\t\tfor (set<vector<int>>::const_iterator pointIt = sliceIt->second.begin(); pointIt != sliceIt->second.end(); ++pointIt)\n\t\t\t{\n\t\t\t\tNeuronSWC newNode;\n\t\t\t\tnewNode.x = pointIt->at(0);\n\t\t\t\tnewNode.y = pointIt->at(1);\n\t\t\t\tnewNode.z = pointIt->at(2);\n\t\t\t\tnewNode.type = it->islandNum % 500;\n\t\t\t\tnewNode.parent = -1;\n\t\t\t\t\n\t\t\t\tif (usingRadius2compNum) newNode.radius = it->islandNum; // Use SWC's radius column to keep component label information.\n\n\t\t\t\toutputTree.listNeuron.push_back(newNode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn outputTree;\n}\n/* =============================== END of [SWC <-> ImgAnalyzer::connectedComponents] =============================== */\n\n\n\n/* =========================================== Miscellaneous =========================================== */\nNeuronTree NeuronStructUtil::nodeSpheresGen(float sphereRadius, float density, float stepX, float stepY, float stepZ, float xRange, float yRange, float zRange)\n{\n\tNeuronTree outputTree;\n\tfor (float x = 0; x <= xRange; x += stepX)\n\t{\n\t\tfor (float y = 0; y <= yRange; y += stepY)\n\t\t{\n\t\t\tfor (float z = 0; z <= zRange; z += stepZ)\n\t\t\t{\n\t\t\t\tNeuronTree currSphereTree = NeuronStructUtil::sphereRandNodes(sphereRadius, x, y, z, density);\n\t\t\t\tsize_t existingNodeNum = outputTree.listNeuron.size();\n\t\t\t\tfor (QList<NeuronSWC>::iterator it = currSphereTree.listNeuron.begin(); it != currSphereTree.listNeuron.end(); ++it) it->n = it->n + existingNodeNum;\n\t\t\t\toutputTree.listNeuron.append(currSphereTree.listNeuron);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn outputTree;\n}\n/* ===================================================================================================== */\n\n\n\n/* =================================== Volumetric SWC sampling methods =================================== */\nvoid NeuronStructUtil::sigNode_Gen(const NeuronTree& inputTree, NeuronTree& outputTree, float ratio, float distance)\n{\n\t// -- Randomly generate signal patches within given distance range\n\t//      ratio:    the ratio of targeted number of upsampling nodes to the number of maunal nodes in the inputTree\n\t//      distance: the radius allowed with SWC node centered\n\n\tcout << \"target signal patch number: \" << int(inputTree.listNeuron.size() * ratio) << endl;\n\tint nodeCount = 0;\n\tfor (QList<NeuronSWC>::const_iterator it = inputTree.listNeuron.begin(); it != inputTree.listNeuron.end(); ++it)\n\t{\n\t\toutputTree.listNeuron.push_back(*it);\n\t\t(outputTree.listNeuron.end() - 1)->parent = -1;\n\t\t(outputTree.listNeuron.end() - 1)->type = 2;\n\t\tint foldCount = 2;\n\t\twhile (foldCount <= ratio)\n\t\t{\n\t\t\tint randNumX = rand() % int(distance * 2) + int(it->x - distance);\n\t\t\tint randNumY = rand() % int(distance * 2) + int(it->y - distance);\n\t\t\tint randNumZ = rand() % int(distance * 2) + int(it->z - distance);\n\n\t\t\t++nodeCount;\n\t\t\tif (nodeCount % 10000 == 0) cout << nodeCount << \" signal nodes generated.\" << endl;\n\n\t\t\tNeuronSWC newNode;\n\t\t\tnewNode.x = randNumX;\n\t\t\tnewNode.y = randNumY;\n\t\t\tnewNode.z = randNumZ;\n\t\t\tnewNode.type = 2;\n\t\t\tnewNode.radius = 1;\n\t\t\tnewNode.parent = -1;\n\t\t\toutputTree.listNeuron.push_back(newNode);\n\n\t\t\t++foldCount;\n\t\t}\n\t}\n}\n\nvoid NeuronStructUtil::bkgNode_Gen(const NeuronTree& inputTree, NeuronTree& outputTree, int dims[], float ratio, float distance)\n{\n\t// -- Randomly generate background patches away from the forbidden distance\n\t//      dims:     image stack dimension\n\t//      ratio:    the ratio of targeted number of background nodes to the number of manual nodes in the inputTree\n\t//      distance: the forbidden distance from each SWC node\n\n\tQList<NeuronSWC> neuronList = inputTree.listNeuron;\n\tint targetBkgNodeNum = int(neuronList.size() * ratio);\n\tcout << targetBkgNodeNum << \" targeted bkg nodes to ge generated.\" << endl;\n\tint bkgNodeCount = 0;\n\twhile (bkgNodeCount <= targetBkgNodeNum)\n\t{\n\t\tint randNumX = rand() % (dims[0] - 20) + 10;\n\t\tint randNumY = rand() % (dims[1] - 20) + 10;\n\t\tint randNumZ = rand() % dims[2];\n\n\t\tbool flag = false;\n\t\tfor (QList<NeuronSWC>::iterator it = neuronList.begin(); it != neuronList.end(); ++it)\n\t\t{\n\t\t\tfloat distSqr;\n\t\t\tfloat diffx = float(randNumX) - it->x;\n\t\t\tfloat diffy = float(randNumY) - it->y;\n\t\t\tfloat diffz = float(randNumZ) - it->z;\n\t\t\tdistSqr = diffx * diffx + diffy * diffy + diffz * diffz;\n\n\t\t\tif (distSqr <= distance * distance)\n\t\t\t{\n\t\t\t\tflag = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (flag == false)\n\t\t{\n\t\t\t++bkgNodeCount;\n\t\t\tif (bkgNodeCount % 10000 == 0) cout << bkgNodeCount << \" bkg nodes generated.\" << endl;\n\n\t\t\tNeuronSWC newBkgNode;\n\t\t\tnewBkgNode.x = randNumX;\n\t\t\tnewBkgNode.y = randNumY;\n\t\t\tnewBkgNode.z = randNumZ;\n\t\t\tnewBkgNode.type = 3;\n\t\t\tnewBkgNode.radius = 1;\n\t\t\tnewBkgNode.parent = -1;\n\t\t\toutputTree.listNeuron.push_back(newBkgNode);\n\t\t}\n\t}\n}\n\nvoid NeuronStructUtil::bkgNode_Gen_somaArea(const NeuronTree& intputTree, NeuronTree& outputTree, int xLength, int yLength, int zLength, float ratio, float distance)\n{\n\t// -- Randomly generate background patches away from the forbidden distance. This method aims to reinforce the background recognition near soma area.\n\t//      xLength, yLength, zLength: decide the range to apply with soma centered\n\t//      ratio:    the ratio of targeted number of soma background nodes to the number of manual nodes in the inputTree\n\t//      distance: the forbidden distance from each SWC node\n\n\tNeuronSWC somaNode;\n\tfor (QList<NeuronSWC>::const_iterator it = intputTree.listNeuron.begin(); it != intputTree.listNeuron.end(); ++it)\n\t{\n\t\tif (it->parent == -1)\n\t\t{\n\t\t\tsomaNode = *it;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfloat xlb = somaNode.x - float(xLength);\n\tfloat xhb = somaNode.x + float(xLength);\n\tfloat ylb = somaNode.y - float(yLength);\n\tfloat yhb = somaNode.y + float(yLength);\n\tfloat zlb = somaNode.z - float(zLength);\n\tfloat zhb = somaNode.z + float(zLength);\n\n\tlist<NeuronSWC> confinedNodes;\n\tfor (QList<NeuronSWC>::const_iterator it = intputTree.listNeuron.begin(); it != intputTree.listNeuron.end(); ++it)\n\t\tif (xlb <= it->x && xhb >= it->x && ylb <= it->y && yhb >= it->y && zlb <= it->z && zhb >= it->z) confinedNodes.push_back(*it);\n\t\n\tint targetBkgNodeNum = int(float(xLength) * float(yLength) * float(zLength) * ratio);\n\tcout << targetBkgNodeNum << \" targeted bkg nodes to ge generated.\" << endl;\n\tint bkgNodeCount = 0;\n\twhile (bkgNodeCount <= targetBkgNodeNum)\n\t{\n\t\tint randNumX = rand() % int(xhb - xlb + 1) + int(xlb);\n\t\tint randNumY = rand() % int(yhb - ylb + 1) + int(ylb);\n\t\tint randNumZ = rand() % int(zhb - zlb + 1) + int(zlb);\n\n\t\tbool flag = false;\n\t\tfor (list<NeuronSWC>::iterator it = confinedNodes.begin(); it != confinedNodes.end(); ++it)\n\t\t{\n\t\t\tfloat distSqr;\n\t\t\tfloat diffx = float(randNumX) - it->x;\n\t\t\tfloat diffy = float(randNumY) - it->y;\n\t\t\tfloat diffz = float(randNumZ) - it->z;\n\t\t\tdistSqr = diffx * diffx + diffy * diffy + diffz * diffz;\n\n\t\t\tif (distSqr <= distance * distance)\n\t\t\t{\n\t\t\t\tflag = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (flag == false)\n\t\t{\n\t\t\t++bkgNodeCount;\n\t\t\tif (bkgNodeCount % 10000 == 0) cout << bkgNodeCount << \" bkg nodes generated within the soma area.\" << endl;\n\n\t\t\tNeuronSWC newBkgNode;\n\t\t\tnewBkgNode.x = randNumX;\n\t\t\tnewBkgNode.y = randNumY;\n\t\t\tnewBkgNode.z = randNumZ;\n\t\t\tnewBkgNode.type = 3;\n\t\t\tnewBkgNode.radius = 1;\n\t\t\tnewBkgNode.parent = -1;\n\t\t\toutputTree.listNeuron.push_back(newBkgNode);\n\t\t}\n\t}\n}\n\nvoid NeuronStructUtil::swcSlicer_DL(const NeuronTree& inputTree, vector<NeuronTree>& outputTrees, int thickness)\n{\n\t// -- Dissemble SWC files into \"slices.\" Each outputSWC file represents only 1 z slice.\n\t// thickness * 2 + 1 = the number of consecutive z slices for one SWC node to appear. This is for the purpose producing continous masks.\n\n\tQList<NeuronSWC> inputList = inputTree.listNeuron;\n\tint zMax = 0;\n\tptrdiff_t thicknessPtrDiff = ptrdiff_t(thickness); // Determining how many z sections to be included in 1 single slice.\n\tfor (QList<NeuronSWC>::iterator it = inputList.begin(); it != inputList.end(); ++it)\n\t{\n\t\tit->z = round(it->z);\n\t\tif (it->z >= zMax) zMax = it->z;\n\t}\n\n\tQList<NeuronTree> slicedTrees; // Determining number of sliced trees in the list.\n\tfor (int i = 0; i < zMax; ++i)\n\t{\n\t\tNeuronTree nt;\n\t\tslicedTrees.push_back(nt);\n\t}\n\n\tfor (QList<NeuronSWC>::iterator it = inputList.begin(); it != inputList.end(); ++it)\n\t{\n\t\tNeuronSWC currNode = *it;\n\t\tptrdiff_t sliceNo = ptrdiff_t(it->z);\n\t\t(slicedTrees.begin() + sliceNo - 1)->listNeuron.push_back(currNode); // SWC starts with 1.\n\t\tfloat currZ = currNode.z;\n\n\t\t// -- Project +/- thickness slices onto the same plane, making sure the tube can be connected accross planes. -- //\n\t\tvector<ptrdiff_t> sectionNums;\n\t\tfor (ptrdiff_t ptri = 1; ptri <= thicknessPtrDiff; ++ptri)\n\t\t{\n\t\t\tptrdiff_t minusDiff = sliceNo - ptri;\n\t\t\tptrdiff_t plusDiff = sliceNo + ptri;\n\n\t\t\tif (minusDiff < 0) continue;\n\t\t\telse sectionNums.push_back(minusDiff);\n\n\t\t\tif (plusDiff > ptrdiff_t(zMax)) continue;\n\t\t\telse sectionNums.push_back(plusDiff);\n\t\t}\n\t\tfor (vector<ptrdiff_t>::iterator ptrIt = sectionNums.begin(); ptrIt != sectionNums.end(); ++ptrIt)\n\t\t{\n\t\t\t//cout << \"current node z:\" << currNode.z << \" \" << *ptrIt << \"| \";\n\t\t\tNeuronSWC newNode = currNode;\n\t\t\tnewNode.z = float(*ptrIt);\n\t\t\t(slicedTrees.begin() + *ptrIt - 1)->listNeuron.push_back(newNode);\n\t\t}\n\t\t//cout << endl;\n\n\t\tsectionNums.clear();\n\t\t// ------------------------------------------------------------------------------------------------------------- //\n\t}\n\n\tfor (QList<NeuronTree>::iterator it = slicedTrees.begin(); it != slicedTrees.end(); ++it)\n\t\toutputTrees.push_back(*it);\n}\n/* =================================== Volumetric SWC sampling methods =================================== */", "meta": {"hexsha": "d2f86d5ff400b6941fd29b96be193bf36e8c31ea", "size": 42381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hackathon/MK/NeuronStructNavigator/NeuronStructUtilities.cpp", "max_stars_repo_name": "TotteKarlsson/vaa3d_tools", "max_stars_repo_head_hexsha": "62b741d5df140a855f166e5470eeb4ef7c812ff0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hackathon/MK/NeuronStructNavigator/NeuronStructUtilities.cpp", "max_issues_repo_name": "TotteKarlsson/vaa3d_tools", "max_issues_repo_head_hexsha": "62b741d5df140a855f166e5470eeb4ef7c812ff0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hackathon/MK/NeuronStructNavigator/NeuronStructUtilities.cpp", "max_forks_repo_name": "TotteKarlsson/vaa3d_tools", "max_forks_repo_head_hexsha": "62b741d5df140a855f166e5470eeb4ef7c812ff0", "max_forks_repo_licenses": ["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.1466019417, "max_line_length": 172, "alphanum_fraction": 0.658903754, "num_tokens": 12371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.027169230058730266, "lm_q1q2_score": 0.009185295163625424}}
{"text": "// Copyright (c) 2019 Lawson Fulton <lawsonfulton@gmail.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n\n// This is the source code for the paper Latent-space Dynamics for Reduced Deformable Simulation\n// Authors: Lawson Fulton, Vismay Modi, David Duvenaud, David I.W. Levin, Alec Jacobson\n// Published: Computer Graphics Forum, 38(2), Eurographics, 2019.\n\n\n//#define EIGEN_USE_MKL_ALL // Uncomment if you have MKL installed on your system\n#ifdef EIGEN_USE_MKL_ALL\n#include <Eigen/PardisoSupport>\n#endif\n\n// Autodef\n#include \"TypeDefs.h\"\n#include \"AutoDefUtils.h\"\n#include \"ReducedSpace.h\"\n\n#include <GaussIncludes.h>\n#include <ForceSpring.h>\n#include <FEMIncludes.h>\n#include <PhysicalSystemParticles.h>\n#include <ConstraintFixedPoint.h>\n#include <TimeStepperEulerImplicitLinear.h>\n#include <AssemblerParallel.h>\n\n#include <igl/writeDMAT.h>\n#include <igl/readDMAT.h>\n#include <igl/writeOBJ.h>\n#include <igl/writePLY.h>\n#include <igl/viewer/Viewer.h>\n#include <igl/readMESH.h>\n#include <igl/unproject_onto_mesh.h>\n#include <igl/unproject.h>\n#include <igl/get_seconds.h>\n#include <igl/jet.h>\n#include <igl/slice.h>\n#include <igl/slice_into.h>\n#include <igl/unique.h>\n#include <igl/per_corner_normals.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/point_mesh_squared_distance.h>\n#include <igl/circumradius.h>\n#include <igl/material_colors.h>\n#include <igl/snap_points.h>\n#include <igl/centroid.h>\n#include <igl/LinSpaced.h>\n#include <igl/vertex_triangle_adjacency.h>\n\n#include <time.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n#include <type_traits>\n#include <utility>\n#include <vector>\n#include <set>\n#include <thread>\n#include <future>\n\n// Third Party\n#include <boost/filesystem.hpp>\n#include <LBFGS.h>\n#include <nlohmann/json.hpp>\n#include <omp.h>\n#include<Eigen/SparseCholesky>\n\nusing json = nlohmann::json;\nnamespace fs = boost::filesystem;\nusing namespace LBFGSpp;\n\n// GAUSS Typenames\nusing namespace Gauss;\nusing namespace FEM;\nusing namespace ParticleSystem; //For Force Spring\ntypedef PhysicalSystemFEM<double, NeohookeanHFixedTet> NeohookeanTets;\ntypedef World<double, \n                        std::tuple<PhysicalSystemParticleSingle<double> *, NeohookeanTets *>,\n                        std::tuple<ForceSpringFEMParticle<double> *>,\n                        std::tuple<ConstraintFixedPoint<double> *> > MyWorld;\ntypedef TimeStepperEulerImplicitLinear<double, AssemblerParallel<double, AssemblerEigenSparseMatrix<double>>,\nAssemblerParallel<double, AssemblerEigenVector<double>> > MyTimeStepper;\n\n\n/*\n    Lots of global defines. Not ideal but works for now.\n*/\n\n// Single tetrahedral mesh to simulate\nEigen::MatrixXd V; // Verts\nEigen::MatrixXd N; // Normals\nEigen::MatrixXi T; // Tet indices\nEigen::MatrixXi F; // Face indices\nEigen::MatrixXi T_sampled; // Cubature tets\nEigen::MatrixXi F_sampled; // Cubature tet faces\nint n_dof; // Size of latent-space\n\nstd::vector<int> fixed_verts; // Verts pinned in the full-space sim\n\n// Mouse/Viewer state\nEigen::RowVector3f last_mouse; // Previous mouse position\nEigen::RowVector3d dragged_pos; // Current (dragging) mouse position\nEigen::RowVector3d dragged_mesh_pos; // Point on mesh being dragged\nint vis_vert_id = 0; // Vertex index that is being dragged\nbool is_dragging = false;\nbool per_vertex_normals = false;\nstd::vector<int> dragged_verts; // List of other vert indices that are being dragged as well (to distribute force)\nint current_frame = 0; // Simulation fram counter\ndouble spring_grab_radius = 0.03;\n\n// Debug Parameters\nint print_freq = 40; // How often to print debug info\nbool NO_WAIT = false; // Start simulation immediatly\nbool LOGGING_ENABLED = false;\nbool PLAYBACK_SIM = false;\nbool SAVE_TRAINING_DATA = false;\nbool SAVE_PNGS = false;\nint log_save_freq = 5;\njson sim_log;\njson sim_playback_json;\njson timestep_info; // Kind of hack but this gets reset at the beginning of each timestep so that we have a global structure to log to\nfs::path log_dir;\nfs::path surface_obj_dir;\nfs::path iteration_obj_dir;\nfs::path pointer_obj_dir;\nfs::path tet_obj_dir;\nfs::path save_training_data_dir;\nfs::path save_pngs_dir;\nstd::ofstream log_ofstream;\n\n// Constants\nconst int PARDISO_DOF_CUTOFF = 7000;\nconst Eigen::RowVector3d sea_green(229./255.,211./255.,91./255.);\n\n// Timing variables\n#define DO_TIMING\nint total_evals = 0;\ndouble tf_decode_time_tot = 0.0;\ndouble tf_vjp_time_tot = 0.0;\ndouble cuba_decode_time_tot = 0.0;\ndouble cuba_eval_time_tot = 0.0;\ndouble obj_grad_time_tot_no_jvp = 0.0;\ndouble precon_time_tot = 0.0;\n\n\n// -- Helper functions\nstd::string int_to_padded_str(int i) {\n    std::stringstream frame_str;\n    frame_str << std::setfill('0') << std::setw(5) << i;\n    return frame_str.str();\n}\n\nstd::vector<int> get_min_verts(int axis, bool flip_axis = false, double tol = 0.001) {\n    int dim = axis; // x\n    double min_x_val = flip_axis ?  V.col(dim).maxCoeff() : V.col(dim).minCoeff();\n    std::vector<int> min_verts;\n\n    for(int ii=0; ii<V.rows(); ++ii) {\n        if(fabs(V(ii, dim) - min_x_val) < tol) {\n            min_verts.push_back(ii);\n        }\n    }\n\n    return min_verts;\n}\n\nstd::vector<int> get_verts_in_sphere(const VectorXd &c, double r, const MatrixXd &verts) {\n    std::vector<int> min_verts;\n\n    for(int ii=0; ii<verts.rows(); ++ii) {\n        if((verts.row(ii) - c.transpose()).squaredNorm() <= r * r) {\n            min_verts.push_back(ii);\n        }\n    }\n\n    return min_verts;\n}\n\nEigen::SparseMatrix<double> construct_constraints_P(const MatrixXd &V, std::vector<int> &indices) {\n    \n    std::vector<Eigen::Triplet<double> > triplets;\n    Eigen::SparseMatrix<double> P;\n    Eigen::VectorXi sortedIndices = VectorXi::Map(indices.data(), indices.size());\n    std::sort(sortedIndices.data(), sortedIndices.data()+indices.size());\n    \n    //build a projection matrix P which projects fixed points out of a physical syste\n    int fIndex = 0;\n    \n    //total number of DOFS in system\n    \n    unsigned int n = V.rows() * 3;\n    unsigned int m = n - 3*indices.size();\n    \n    P.resize(m,n);\n    \n    //number of unconstrained DOFs\n    unsigned int rowIndex =0;\n    for(unsigned int vIndex = 0; vIndex < V.rows(); vIndex++) {\n        \n        while((vIndex < V.rows()) && (fIndex < sortedIndices.rows()) &&(vIndex == sortedIndices[fIndex])) {\n            fIndex++;\n            vIndex++;\n        }\n        \n        if(vIndex == V.rows())\n            break;\n        \n        //add triplet into matrix\n        triplets.push_back(Eigen::Triplet<double>(rowIndex,  3*vIndex,1));\n        triplets.push_back(Eigen::Triplet<double>(rowIndex+1,  3*vIndex+1, 1));\n        triplets.push_back(Eigen::Triplet<double>(rowIndex+2,  3*vIndex+2, 1));\n        \n        rowIndex+=3;\n    }\n    \n    P.setFromTriplets(triplets.begin(), triplets.end());\n    \n    //build the matrix and  return\n    return P;\n}\n\nvoid create_or_replace_dir(fs::path dir) {\n    if(fs::exists(dir)){\n        std::cout << \"Are you sure you want to delete \" << dir << \"? Y/n: \";\n        std::string input;\n        input = std::cin.get();\n        if(input == \"Y\" || input == \"y\" || input == \"\\n\") {\n            fs::remove_all(dir);\n        } else {\n            exit(1);\n        }\n    }\n    fs::create_directories(dir);\n}\n\nvoid reset_world (MyWorld &world) {\n        auto q = mapStateEigen(world); // TODO is this necessary?\n        q.setZero();\n}\n\nvoid exit_gracefully() {\n    log_ofstream.seekp(0);\n    log_ofstream << std::setw(2) << sim_log;\n    log_ofstream.close();\n\n    if(SAVE_TRAINING_DATA) {\n        fs::copy_file(log_dir / \"sim_stats.json\", save_training_data_dir / \"sim_stats.json\");\n    }\n\n    exit(0);\n}\n\n\n//--- Start of simulation code\ntemplate <typename ReducedSpaceType, typename MatrixType>\nclass GPLCObjective\n{\npublic:\n    GPLCObjective(\n        fs::path model_root,\n        json integrator_config,\n        VectorXd cur_z,\n        VectorXd prev_z,\n        MyWorld *world,\n        NeohookeanTets *tets,\n        ReducedSpaceType *reduced_space ) : \n            m_cur_z(cur_z),\n            m_prev_z(prev_z),\n            m_world(world),\n            m_tets(tets),\n            m_reduced_space(reduced_space)\n    {\n        m_save_obj_every_iteration = get_json_value(integrator_config, \"save_obj_every_iteration\", false);\n        m_cur_sub_q = sub_dec(cur_z);\n        m_prev_sub_q = sub_dec(prev_z);\n\n        m_h = integrator_config[\"timestep\"];\n        // Construct mass matrix and external forces\n        getMassMatrix(m_M_asm, *m_world);\n\n        m_M = *m_M_asm;\n\n        m_U = m_reduced_space->outer_jacobian();\n        std::cout << \"Constructing reduced mass matrix...\" << std::endl;\n        m_UTMU = m_U.transpose() * m_M * m_U;\n\n        // Check if m_UTMU is identity (mass pca)\n        if(integrator_config[\"reduced_space_type\"] != \"full\") { // Only check for non-full (dense) spaces\n            if(MatrixXd(m_UTMU).isIdentity(1e-6)) {\n                m_UTMU_is_identity = true;\n                std::cout << \"UTMU is Identity!!! Removing from calculations.\" << std::endl;\n            } else {\n                std::cout << \"UTMU is not Identity!!!\" << std::endl;\n            }\n        }\n\n        std::cout << \"Done.\" << std::endl;\n\n        VectorXd g(m_M.cols());\n        int gravity_axis = get_json_value(integrator_config, \"gravity_axis\", 1);\n        for(int i=0; i < g.size(); i += 3) {\n            g[i] = 0.0;\n            g[i+1] = 0.0;\n            g[i+2] = 0.0;\n            g[i + gravity_axis] = integrator_config[\"gravity\"];\n        }\n\n        m_F_ext = m_M * g;\n\n        m_UT_F_ext = m_U.transpose() * m_F_ext;\n        m_interaction_force = SparseVector<double>(m_F_ext.size());\n\n        m_energy_method = energy_method_from_integrator_config(integrator_config);\n        m_use_partial_decode =  (m_energy_method == PCR || m_energy_method == AN08 || m_energy_method == AN08_ALL || m_energy_method == NEW_PCR) && get_json_value(integrator_config, \"use_partial_decode\", true);\n\n        m_do_quasi_static = get_json_value(integrator_config, \"quasi_static\", false);\n\n        if(m_energy_method == PCR){\n            fs::path pca_components_path(\"pca_results/energy_pca_components.dmat\");\n            fs::path sample_tets_path(\"pca_results/energy_indices.dmat\");\n\n            MatrixXd U;\n            igl::readDMAT((model_root / pca_components_path).string(), U);\n\n            Eigen::VectorXi Is;\n            igl::readDMAT((model_root /sample_tets_path).string(), Is); //TODO do I need to sort this?\n            m_cubature_indices = Is;\n\n            // Other stuff?\n            m_energy_basis = U;\n            m_energy_sampled_basis = igl::slice(m_energy_basis, m_cubature_indices, 1);\n            m_summed_energy_basis = m_energy_basis.colwise().sum();\n            MatrixXd S_barT_S_bar = m_energy_sampled_basis.transpose() * m_energy_sampled_basis;\n            // m_energy_sampled_basis_qr = m_energy_sampled_basis.fullPivHouseholderQr();\n            \n            m_cubature_weights = m_energy_sampled_basis * S_barT_S_bar.ldlt().solve(m_summed_energy_basis); //U_bar(A^-1*u)\n            std::cout << \"Done. Will sample from \" << m_cubature_indices.size() << \" tets.\" << std::endl;\n        }\n        else if(m_energy_method == AN08 || m_energy_method == NEW_PCR) {\n            fs::path energy_model_dir;\n            \n            if(m_energy_method == AN08) {\n                energy_model_dir = model_root / (\"energy_model/an08/pca_dim_\" + std::to_string(m_U.cols()));\n                if(!boost::filesystem::exists(energy_model_dir)) { // Old version\n                    energy_model_dir = model_root / \"energy_model/an08/\";\n                }\n            }\n            if(m_energy_method == NEW_PCR) energy_model_dir = model_root / \"energy_model/new_pcr/\";\n\n            fs::path indices_path = energy_model_dir / \"indices.dmat\";\n            fs::path weights_path = energy_model_dir / \"weights.dmat\";\n\n            Eigen::VectorXi Is;\n            Eigen::VectorXd Ws;\n            igl::readDMAT(indices_path.string(), Is); //TODO do I need to sort this?\n            igl::readDMAT(weights_path.string(), Ws); \n\n            m_cubature_weights = Ws;\n            m_cubature_indices = Is;\n            std::cout << \"Done. Will sample from \" << m_cubature_indices.size() << \" tets.\" << std::endl;\n        } else if(m_energy_method == AN08_ALL) {\n            fs::path energy_model_dir = model_root / (\"energy_model/an08/pca_dim_\" + std::to_string(m_U.cols()));\n            if(!boost::filesystem::exists(energy_model_dir)) { // Old version\n                energy_model_dir = model_root / \"energy_model/an08/\";\n            }\n            load_all_an08_indices_and_weights(energy_model_dir, m_all_cubature_indices, m_all_cubature_weights);\n\n            m_cubature_weights = m_all_cubature_weights.back();\n            m_cubature_indices = m_all_cubature_indices.back();\n        }\n\n        // Computing the sampled verts\n        if (m_energy_method == AN08 || m_energy_method == PCR || m_energy_method == NEW_PCR || m_energy_method == AN08_ALL) {\n            initialize_cubature();\n        }\n    }\n\n    void initialize_cubature() {\n        // figure out the verts\n        std::set<int> vert_set;\n        int n_sample_tets = m_cubature_indices.size();\n        for(int i = 0; i < m_cubature_indices.size(); i++) {\n            int tet_index = m_cubature_indices[i];\n            for(int j = 0; j < 4; j++) {\n                int vert_index = m_tets->getImpl().getElement(tet_index)->getQDOFList()[j]->getGlobalId();\n                for(int k = 0; k < 3; k++) {\n                    vert_set.insert(vert_index + k);\n                }\n            }\n        }\n        // Put them in a vector sorted order\n        m_cubature_vert_indices = VectorXi(vert_set.size());\n        int i = 0;\n        for(auto vi: vert_set) {\n            m_cubature_vert_indices[i++] = vi;\n            // std::cout << vi << \", \" << std::endl;\n        }\n        std::sort(m_cubature_vert_indices.data(), m_cubature_vert_indices.data()+m_cubature_vert_indices.size());\n        MatrixXd denseU = m_U;  // Need to cast to dense to support sparse in full space\n        m_U_sampled = igl::slice(denseU, m_cubature_vert_indices, 1);\n\n        // Get the element references ahead of time\n        m_cubature_elements.clear();\n        for(int i = 0; i < n_sample_tets; i++) { // TODO parallel\n            int tet_index = m_cubature_indices[i];  \n            auto elem = m_tets->getImpl().getElement(tet_index);\n            m_cubature_elements.push_back(elem);\n        }\n\n        // Get the rows of U ahead of time\n        m_U_cubature_sampled.resize(n_sample_tets * 12, m_U.cols());\n        for(int i = 0; i < n_sample_tets; i++) { // TODO parallel\n            for(int k = 0; k < 4; k++) {\n                for(int j = 0; j < 3; j++) {    \n                    m_U_cubature_sampled.row(i * 12 + k * 3 + j) = m_cubature_weights(i) * denseU.row(m_cubature_elements[i]->getQDOFList()[k]->getGlobalId() + j);\n                }\n            }\n        }\n    }\n\n    void update_zs(const VectorXd &cur_z) {\n        m_prev_z = cur_z;\n        m_prev_sub_q = m_cur_sub_q;\n        m_cur_z = cur_z;\n        m_cur_sub_q = sub_dec(m_cur_z);\n    }\n\n    void set_interaction_force(const SparseVector<double> &interaction_force) {\n        m_interaction_force = interaction_force;\n    }\n\n    void set_cubature_indices_and_weights(const VectorXi &indices, const VectorXd &weights) {\n        m_cubature_weights = weights;\n        m_cubature_indices = indices;\n    }\n\n    // Just short helpers\n    VectorXd dec(const VectorXd &z) { return m_reduced_space->decode(z); }\n    VectorXd sub_dec(const VectorXd &z) { return m_reduced_space->sub_decode(z); }\n    VectorXd enc(const VectorXd &q) { return m_reduced_space->encode(q); }\n    VectorXd jtvp(const VectorXd &z, const VectorXd &q) { return m_reduced_space->jacobian_transpose_vector_product(z, q); }\n\n\n\n    double parallel_current_reduced_energy_and_forces(double &energy, VectorXd &UT_forces) {\n        #pragma omp single \n        {\n            UT_forces = VectorXd::Zero(m_U.cols());\n            energy = 0;\n        }\n\n        const int n_sample_tets = m_cubature_indices.size();\n        const int n_force_per_element = T.cols() * 3;\n        const int d = m_U.cols();\n\n        VectorXd sampled_force(n_force_per_element); // Holds the force for a single tet\n        VectorXd element_reduced_force(d);\n        element_reduced_force.setZero();\n\n        double sub_energy = 0.0;\n\n        #pragma omp for nowait \n        for(int i = 0; i < n_sample_tets; i++) {\n            int tet_index = m_cubature_indices[i];\n            auto elem = m_cubature_elements[i];\n\n            // Energy and forces\n            double tet_energy = elem->getStrainEnergy(m_world->getState());\n            elem->getInternalForce(sampled_force, m_world->getState());\n\n            element_reduced_force.noalias() += m_U_cubature_sampled.block(i*12, 0, 12, d).transpose() * sampled_force;\n            sub_energy += m_cubature_weights(i) * tet_energy;\n        }\n\n        #pragma omp critical\n        {\n            UT_forces += element_reduced_force; //Does this have to do a transpose to assign?\n            energy += sub_energy;\n        }\n    }\n\n\n    // This is where all the magic happens\n    double operator()(const VectorXd& new_z, VectorXd& grad, const int cur_iteration, const int cur_line_search_iteration)\n    {\n\n        // Update the tets with candidate configuration\n        double obj_start_time = igl::get_seconds();\n        VectorXd new_sub_q = sub_dec(new_z);\n        double tf_time = igl::get_seconds() - obj_start_time;\n        tf_decode_time_tot += tf_time;\n\n        double decode_start_time = igl::get_seconds();\n        Eigen::Map<Eigen::VectorXd> q = mapDOFEigen(m_tets->getQ(), *m_world);\n        \n        // Define up here so they are shared with threads\n        double energy;\n        VectorXd UT_internal_forces;\n        \n        #ifdef DO_TIMING\n        double energy_forces_start_tim = 0.0;\n        double predict_weight_time = 0.0;\n        double decode_time;\n        #endif\n\n        double energy_forces_start_time = igl::get_seconds();\n        if(m_energy_method != FULL) {\n            // If we are using cubature then we can leverage parallelism\n            #pragma omp parallel num_threads(8) // TODO is it possible to move this out of the optimization loop?\n            {\n                // Update our current state\n                if(m_use_partial_decode) {\n                    // We only need to update verts for the tets we actually sample\n                    #pragma omp for\n                    for(int i = 0; i < m_U_sampled.rows(); i++) {\n                        q[m_cubature_vert_indices[i]] = m_U_sampled.row(i) * new_sub_q; //sampled_q[i]; // TODO this could probably be more efficient with a sparse operator?\n                    }\n                } else {\n                    #pragma omp single\n                    {\n                        q = m_U * new_sub_q;\n                    }\n                }\n                \n                #ifdef DO_TIMING\n                    #pragma omp single\n                    {\n                        decode_time = igl::get_seconds() - decode_start_time;\n                        cuba_decode_time_tot += decode_time;\n                        energy_forces_start_time = igl::get_seconds();\n                    }\n                #endif\n                // Get energy and forces\n                parallel_current_reduced_energy_and_forces(energy, UT_internal_forces);\n            }\n        } else {\n            // Update our current state\n            q = m_U * new_sub_q;\n\n            #ifdef DO_TIMING\n            decode_time = igl::get_seconds() - decode_start_time;\n            energy_forces_start_time = igl::get_seconds();\n            #endif\n\n            // Get energy and forces\n            energy = m_tets->getStrainEnergy(m_world->getState());\n            getInternalForceVector(m_internal_force_asm, *m_tets, *m_world);\n            UT_internal_forces = m_U.transpose() * *m_internal_force_asm;\n        }\n        \n\n        #ifdef DO_TIMING\n        double energy_forces_time = igl::get_seconds() - energy_forces_start_time;\n        cuba_eval_time_tot += energy_forces_time;\n\n        double obj_and_grad_time_start = igl::get_seconds();\n        #endif\n\n        const VectorXd h_2_UT_external_forces = m_h * m_h * (m_U.transpose() * m_interaction_force + m_UT_F_ext);\n        const VectorXd sub_q_tilde = new_sub_q - 2.0 * m_cur_sub_q + m_prev_sub_q;\n        const VectorXd UTMU_sub_q_tilde = m_UTMU * sub_q_tilde;\n\n        double obj_val;\n        if(m_do_quasi_static) {\n            obj_val = m_h * m_h * energy - sub_q_tilde.transpose() * h_2_UT_external_forces;\n            grad = jtvp(new_z, - m_h * m_h * UT_internal_forces - h_2_UT_external_forces);\n            \n        } else { \n            obj_val = 0.5 * sub_q_tilde.transpose() * UTMU_sub_q_tilde\n                            + m_h * m_h * energy\n                            - sub_q_tilde.transpose() * h_2_UT_external_forces;\n            VectorXd preGrad = UTMU_sub_q_tilde - m_h * m_h * UT_internal_forces - h_2_UT_external_forces;\n\n            obj_grad_time_tot_no_jvp += igl::get_seconds() - obj_and_grad_time_start;\n            double vjp_start = igl::get_seconds();\n            grad = jtvp(new_z, preGrad);\n            tf_vjp_time_tot += igl::get_seconds() - vjp_start;\n        }\n\n        #ifdef DO_TIMING\n        double obj_and_grad_time = igl::get_seconds() - obj_and_grad_time_start;\n        double obj_time = igl::get_seconds() - obj_start_time;\n        #endif\n\n        if(LOGGING_ENABLED) {\n            timestep_info[\"iteration_info\"][\"lbfgs_iteration\"].push_back(cur_iteration);\n            timestep_info[\"iteration_info\"][\"lbfgs_line_iteration\"].push_back(cur_line_search_iteration);\n            timestep_info[\"iteration_info\"][\"lbfgs_obj_vals\"].push_back(obj_val);\n\n            #ifdef DO_TIMING\n            timestep_info[\"iteration_info\"][\"timing\"][\"tot_obj_time_s\"].push_back(obj_time);\n            timestep_info[\"iteration_info\"][\"timing\"][\"tf_time_s\"].push_back(tf_time);\n            timestep_info[\"iteration_info\"][\"timing\"][\"linear_decode_time_s\"].push_back(decode_time);\n            timestep_info[\"iteration_info\"][\"timing\"][\"energy_forces_time_s\"].push_back(energy_forces_time);\n            timestep_info[\"iteration_info\"][\"timing\"][\"predict_weight_time\"].push_back(predict_weight_time);\n            timestep_info[\"iteration_info\"][\"timing\"][\"obj_and_grad_eval_time_s\"].push_back(obj_and_grad_time);\n            #endif\n\n            if(m_save_obj_every_iteration) {\n                VectorXd q = m_reduced_space->decode(new_z);\n                Eigen::Map<Eigen::MatrixXd> dV(q.data(), V.cols(), V.rows()); // Get displacements only\n                fs::path obj_filename = iteration_obj_dir / (ZeroPadNumber(cur_iteration) + \"_\" + ZeroPadNumber(cur_line_search_iteration, 2) + \".obj\");\n                MatrixXd new_verts = V + dV.transpose();\n                igl::writeOBJ(obj_filename.string(), new_verts, F);\n            }\n        }\n\n        total_evals++;\n        return obj_val;\n    }\n\n    VectorXi get_current_tets() {\n        return m_cubature_indices;\n    }\n\n    void switch_to_next_tets(int i) { // This is an ugly dirty hack to get extra tets working for an08\n        m_cubature_weights = m_all_cubature_weights[m_all_cubature_weights.size() - (i % m_all_cubature_weights.size()) - 1];\n        m_cubature_indices = m_all_cubature_indices[m_all_cubature_weights.size() - (i % m_all_cubature_weights.size()) - 1];\n\n        initialize_cubature();\n\n        std::cout << \"Now sampling from \" << m_cubature_indices.size() << \" tets\" << std::endl;\n    }\n\nprivate:\n    VectorXd m_cur_z;\n    VectorXd m_prev_z;\n    VectorXd m_cur_sub_q;\n    VectorXd m_prev_sub_q;\n    VectorXd m_F_ext;\n    VectorXd m_UT_F_ext;\n\n    SparseVector<double> m_interaction_force;\n\n    SparseMatrix<double> m_M; // mass matrix\n    // Below is a kind of hack way to get the matrix type used in the reduced space class\n    MatrixType  m_UTMU; // reduced mass matrix\n    MatrixType  m_U;\n    MatrixXd m_U_sampled; // Always used in dense mode\n    MatrixXd m_U_cubature_sampled;\n\n    AssemblerParallel<double, AssemblerEigenSparseMatrix<double> > m_M_asm;\n    AssemblerParallel<double, AssemblerEigenVector<double> > m_internal_force_asm;\n\n    double m_h;\n\n    MyWorld *m_world;\n    NeohookeanTets *m_tets;\n\n    EnergyMethod m_energy_method;\n    ReducedSpaceType *m_reduced_space;\n    bool m_use_partial_decode = false;\n    bool m_save_obj_every_iteration = false;\n    bool m_UTMU_is_identity = false;\n    bool m_do_quasi_static = false;\n\n    MatrixXd m_energy_basis;\n    VectorXd m_summed_energy_basis;\n    MatrixXd m_energy_sampled_basis;\n    Eigen::FullPivHouseholderQR<MatrixXd> m_energy_sampled_basis_qr;\n\n    VectorXd m_cubature_weights;\n    VectorXi m_cubature_indices;\n    VectorXi m_cubature_vert_indices;\n    std::vector<NeohookeanHFixedTet<double> *> m_cubature_elements;\n\n    std::vector<VectorXd> m_all_cubature_weights;\n    std::vector<VectorXi> m_all_cubature_indices;\n};\n\ntemplate <typename ReducedSpaceType, typename MatrixType>\nclass GPLCTimeStepper {\npublic:\n    GPLCTimeStepper(fs::path model_root, json integrator_config, MyWorld *world, NeohookeanTets *tets, ReducedSpaceType *reduced_space) :\n        m_world(world), m_tets(tets), m_reduced_space(reduced_space) {\n\n        // Get parameters\n        m_energy_method = energy_method_from_integrator_config(integrator_config);\n        m_use_preconditioner = integrator_config[\"use_preconditioner\"];\n        m_full_only_rest_prefactor = get_json_value(integrator_config, \"full_only_rest_prefactor\", false);\n        m_is_full_space = integrator_config[\"reduced_space_type\"] == \"full\";\n        m_is_linear_space = integrator_config[\"reduced_space_type\"] == \"linear\";\n        m_h = integrator_config[\"timestep\"];\n        m_U = reduced_space->outer_jacobian();\n\n        // Set up lbfgs params\n        json lbfgs_config = integrator_config[\"lbfgs_config\"];\n        m_lbfgs_param.linesearch = LBFGSpp::LBFGS_LINESEARCH_BACKTRACKING_WOLFE;\n        m_lbfgs_param.m = lbfgs_config[\"lbfgs_m\"];\n        m_lbfgs_param.epsilon = lbfgs_config[\"lbfgs_epsilon\"];\n        m_lbfgs_param.delta = get_json_value(lbfgs_config, \"lbfgs_delta\", 0.0);\n        m_lbfgs_param.past = get_json_value(lbfgs_config, \"lbfgs_delta_past\", 0);\n        m_lbfgs_param.max_iterations = lbfgs_config[\"lbfgs_max_iterations\"];\n        m_solver = new LBFGSSolver<double>(m_lbfgs_param);\n\n        // Load start pose if needed\n        int start_pose_from_training_data = get_json_value(integrator_config, \"start_pose_from_training_data\", -1);\n        if(start_pose_from_training_data != -1) {\n            MatrixXd starting_data;\n            igl::readDMAT((model_root / (\"training_data/training/displacements_\" + std::to_string(start_pose_from_training_data) + \".dmat\")).string(), starting_data);\n            starting_data.transposeInPlace();\n            m_starting_pose = Eigen::Map<VectorXd>(starting_data.data(), starting_data.size());\n        } else {\n            m_starting_pose = VectorXd::Zero(V.size());\n        }\n        getMassMatrix(m_M_asm, *m_world);\n        getStiffnessMatrix(m_K_asm, *m_world);\n\n        reset_zs();\n\n        // Set up preconditioner\n        if(m_use_preconditioner) {\n            MatrixType J = reduced_space->inner_jacobian(m_cur_z);\n            std::cout << \"Constructing reduced mass and stiffness matrix...\" << std::endl;\n            double start_time = igl::get_seconds();\n            m_UTMU = m_U.transpose() * (*m_M_asm) * m_U;\n            m_UTKU = m_U.transpose() * (*m_K_asm) * m_U;\n            m_H = J.transpose() * m_UTMU * J - m_h * m_h * J.transpose() * m_UTKU * J;\n\n            m_use_pardiso = m_is_full_space && m_H.rows() > PARDISO_DOF_CUTOFF;\n            std::cout << \"Using pardiso: \" << m_use_pardiso << std::endl;\n            std::cout << \"Rows in m_H: \" << m_H.rows() << std::endl;\n            if(m_use_pardiso) {\n                m_H_solver_pardiso.compute(m_H);\n            } else {\n                m_H_solver_eigen.compute(m_H);\n            }\n            std::cout << \"Took \" << (igl::get_seconds() - start_time) << \"s\" << std::endl;\n        }\n\n        // Finally initialize the BFGS objective\n        m_gplc_objective = new GPLCObjective<ReducedSpaceType, MatrixType>(model_root, integrator_config, m_cur_z, m_prev_z, world, tets, reduced_space);\n    }\n\n    ~GPLCTimeStepper() {\n        delete m_solver;\n        delete m_gplc_objective;\n    }\n\n    void step(const SparseVector<double> &interaction_force) {\n        if(LOGGING_ENABLED) {\n            timestep_info = json(); // Clear timestep info for this frame.\n        }\n        double start_time = igl::get_seconds();\n\n        VectorXd z_param = m_cur_z; // Stores both the first guess and the final result\n        double min_val_res;\n\n        m_gplc_objective->set_interaction_force(interaction_force);\n        \n        int niter;\n        double precondition_compute_time = 0.0;\n        if(m_use_preconditioner) {\n            double precondition_start_time = igl::get_seconds();\n            if(!m_is_full_space && !m_is_linear_space) { // Only update the hessian each time for nonlinear space. \n                MatrixType J = m_reduced_space->inner_jacobian(m_cur_z);\n                m_H = J.transpose() * m_UTMU * J - m_h * m_h * J.transpose() * m_UTKU * J;\n                m_H_solver_eigen.compute(m_H);\n            }\n            if(m_is_full_space && !m_full_only_rest_prefactor){\n                getStiffnessMatrix(m_K_asm, *m_world);\n                m_UTMU = m_U.transpose() * (*m_M_asm) * m_U;\n                m_UTKU = m_U.transpose() * (*m_K_asm) * m_U;\n                m_H = m_UTMU - m_h * m_h * m_UTKU;\n                if(m_use_pardiso) {\n                    m_H_solver_pardiso.compute(m_H);\n                } else {\n                    m_H_solver_eigen.compute(m_H);\n                }\n            }\n            precondition_compute_time = igl::get_seconds() - precondition_start_time;\n            precon_time_tot += precondition_compute_time;\n            if(m_use_pardiso) {\n                niter = m_solver->minimizeWithPreconditioner(*m_gplc_objective, z_param, min_val_res, m_H_solver_pardiso);   \n            } else {\n                niter = m_solver->minimizeWithPreconditioner(*m_gplc_objective, z_param, min_val_res, m_H_solver_eigen);   \n            }\n            bool m_use_pardiso;\n        } else {\n\n            niter = m_solver->minimize(*m_gplc_objective, z_param, min_val_res);   \n        }\n        double update_time = igl::get_seconds() - start_time;\n\n\n        m_prev_z = m_cur_z;\n        m_cur_z = z_param;\n        m_gplc_objective->update_zs(m_cur_z);\n\n        m_total_time += update_time;\n        m_total_time_since_last += update_time;\n        m_tot_its_since_last += niter;\n\n        if(current_frame % print_freq == 0) {\n            std::cout << std::endl;\n            std::cout << \"Averages for last \" << print_freq << \" frames:\" << std::endl;\n\n            std::cout << \"L-BFGS Iterations: \" << m_tot_its_since_last / (double)print_freq << std::endl;\n            std::cout << \"Step time(s): \" << m_total_time_since_last / (double)print_freq << \"s\" << std::endl;\n            std::cout << \"Step time(Hz): \" << print_freq / (double)m_total_time_since_last << \"s\" << std::endl;\n            std::cout << \"Total step time avg: \" << m_total_time / (double)current_frame << \"s\" << std::endl;\n\n            std::cout << \"Avg evals / frame: \" << total_evals / (current_frame + 1.0) << std::endl;\n            std::cout << \"['cuba_eval_time_tot', 'cuba_decode_time_tot', 'obj_grad_time_tot_no_jvp', 'tf_decode_time_tot', 'tf_vjp_time_tot', 'precon_time_tot']\" << std::endl;\n            std::cout << \"[\"<<  cuba_eval_time_tot / total_evals << \", \" \n                           << cuba_decode_time_tot / total_evals <<  \", \"\n                           << obj_grad_time_tot_no_jvp / total_evals << \", \"\n                           << tf_decode_time_tot / total_evals << \", \"\n                           << tf_vjp_time_tot / total_evals << \", \"\n                           << precon_time_tot / total_evals << \"]\" << std::endl;\n\n            m_total_time_since_last = 0.0;\n            m_tot_its_since_last = 0;\n        }\n\n        if(LOGGING_ENABLED) {\n            if(current_frame % print_freq == 0) {\n                std::cout << \"LOGGING_ENABLED\" << std::endl; // just a warning\n            }\n\n            timestep_info[\"current_frame\"] = current_frame; // since at end of timestep\n            timestep_info[\"tot_step_time_s\"] = update_time;\n            timestep_info[\"precondition_time\"] = precondition_compute_time;\n            timestep_info[\"lbfgs_iterations\"] = niter;\n\n            timestep_info[\"mouse_info\"][\"dragged_pos\"] = {dragged_pos[0], dragged_pos[1], dragged_pos[2]};\n            timestep_info[\"mouse_info\"][\"dragged_mesh_pos\"] = {dragged_mesh_pos[0], dragged_mesh_pos[1], dragged_mesh_pos[2]};\n            timestep_info[\"mouse_info\"][\"is_dragging\"] = is_dragging;\n\n            sim_log[\"timesteps\"].push_back(timestep_info);\n            if(current_frame % log_save_freq == 0) {\n                log_ofstream.seekp(0);\n                log_ofstream << std::setw(2) << sim_log;\n            }\n        }\n\n\n        return;\n    }\n\n    void update_world_with_current_configuration() {\n        // TODO: is this the fastest way to do this?\n        Eigen::Map<Eigen::VectorXd> gauss_map_q = mapDOFEigen(m_tets->getQ(), *m_world);\n        VectorXd cur_q = m_reduced_space->decode(m_cur_z);\n        for(int i=0; i < cur_q.size(); i++) {\n            gauss_map_q[i] = cur_q[i];\n        }\n    }\n\n    void reset_zs() {\n        m_prev_z = m_reduced_space->encode(m_starting_pose);\n        m_cur_z = m_prev_z;\n        update_world_with_current_configuration();\n    }\n\n    ReducedSpaceType* get_reduced_space() {\n        return m_reduced_space;\n    }\n\n    VectorXd get_current_z() {\n        return m_cur_z;\n    }\n\n    VectorXd get_current_q() {\n        return m_reduced_space->decode(m_cur_z);\n    }\n\n    MatrixXd get_current_V() {\n        VectorXd q = get_current_q();\n        Eigen::Map<Eigen::MatrixXd> dV(q.data(), V.cols(), V.rows()); // Get displacements only\n        return V + dV.transpose(); \n    }\n\n    void get_current_V_faces_only(MatrixXd &newV) {\n        VectorXd sub_q = m_reduced_space->sub_decode(m_cur_z);\n        VectorXd q = m_U_F_only * sub_q ;\n        Eigen::Map<Eigen::MatrixXd> dV(q.data(), V.cols(), V.rows()); // Get displacements only\n        newV = V + dV.transpose();\n    }\n\n    VectorXi get_current_tets() {\n        return m_gplc_objective->get_current_tets();\n    }\n\n    void switch_to_next_tets(int i) {\n        m_gplc_objective->switch_to_next_tets(i);\n    }\n\n    VectorXd get_current_vert_pos(int vert_index) {\n        VectorXd sub_q = m_reduced_space->sub_decode(m_cur_z);\n\n        return V.row(vert_index).transpose() + m_U.block(vert_index * 3, 0, 3, m_U.cols()) * sub_q;\n    }\n\nprivate:\n    bool m_use_preconditioner;\n    bool m_full_only_rest_prefactor;\n    bool m_is_full_space;\n    bool m_is_linear_space;\n\n    LBFGSParam<double> m_lbfgs_param;\n    LBFGSSolver<double> *m_solver;\n    GPLCObjective<ReducedSpaceType, MatrixType> *m_gplc_objective;\n\n    VectorXd m_starting_pose;\n\n    VectorXd m_prev_z;\n    VectorXd m_cur_z;\n\n    double m_h;\n\n    MatrixType m_H;\n    typename std::conditional<\n        std::is_same<MatrixType, MatrixXd>::value,\n        Eigen::LDLT<MatrixXd>,\n        Eigen::SimplicialLDLT<SparseMatrix<double>> >::type m_H_solver_eigen;\n    \n    bool m_use_pardiso;\n    #ifdef EIGEN_USE_MKL_ALL\n    typename std::conditional<\n        std::is_same<MatrixType, MatrixXd>::value,\n        Eigen::LDLT<MatrixXd>,\n        Eigen::PardisoLDLT<SparseMatrix<double>, Eigen::Lower> >::type m_H_solver_pardiso;\n    #else\n    typename std::conditional<\n        std::is_same<MatrixType, MatrixXd>::value,\n        Eigen::LDLT<MatrixXd>,\n        Eigen::SimplicialLDLT<SparseMatrix<double>> >::type  m_H_solver_pardiso;\n    #endif\n\n    MatrixType m_H_inv;\n    MatrixType m_UTKU;\n    MatrixType m_UTMU;\n\n    MatrixType m_U;\n    SparseMatrix<double> m_U_F_only;\n\n    AssemblerParallel<double, AssemblerEigenSparseMatrix<double> > m_M_asm;\n    AssemblerParallel<double, AssemblerEigenSparseMatrix<double> > m_K_asm;\n\n    MyWorld *m_world;\n    NeohookeanTets *m_tets;\n\n    ReducedSpaceType *m_reduced_space;\n    EnergyMethod m_energy_method;\n\n    double m_total_time = 0.0;\n    double m_total_time_since_last = 0.0;\n    int m_tot_its_since_last = 0;\n    int m_total_tets = 0; // Sum the number of tets activated each frame\n};\n\n\ntemplate <typename S, typename M>\nSparseVector<double> compute_interaction_force(const Vector3d &dragged_pos, const std::vector<int> &dragged_verts, bool is_dragging, double spring_stiffness, GPLCTimeStepper<S,M> &gplc_stepper) {\n    SparseVector<double> force(n_dof);\n    if(is_dragging) {\n        force.reserve(3 * dragged_verts.size());\n        for(int vi = 0; vi < dragged_verts.size(); vi++) {\n            int dragged_vert_local = dragged_verts[vi];\n\n            Vector3d fem_attached_pos = gplc_stepper.get_current_vert_pos(dragged_vert_local);\n            Vector3d local_force = spring_stiffness * (dragged_pos - fem_attached_pos) / dragged_verts.size();\n            for(int i=0; i < 3; i++) {\n                force.insert(dragged_vert_local * 3 + i) = local_force[i];    \n            }\n        }\n    } \n    return force;\n}\n\n// VectorXd get_von_mises_stresses(NeohookeanTets *tets, MyWorld &world) {\n//     // Compute cauchy stress\n//     int n_ele = tets->getImpl().getF().rows();\n\n//     Eigen::Matrix<double, 3,3> stress = MatrixXd::Zero(3,3);\n//     VectorXd vm_stresses(n_ele);\n\n//     std::cout << \"Disabled cauchy stress for linear tets..\" << std::endl;\n//     // for(unsigned int i=0; i < n_ele; ++i) {\n//     //     tets->getImpl().getElement(i)->getCauchyStress(stress, Vec3d(0,0,0), world.getState());\n\n//     //     double s11 = stress(0, 0);\n//     //     double s22 = stress(1, 1);\n//     //     double s33 = stress(2, 2);\n//     //     double s23 = stress(1, 2);\n//     //     double s31 = stress(2, 0);\n//     //     double s12 = stress(0, 1);\n//     //     vm_stresses[i] = sqrt(0.5 * (s11-s22)*(s11-s22) + (s33-s11)*(s33-s11) + 6.0 * (s23*s23 + s31*s31 + s12*s12));\n//     // }\n\n//     return vm_stresses;\n// }\n\n\n//--- Set up and Visualization\ntemplate <typename ReducedSpaceType, typename MatrixType>\nvoid run_sim(ReducedSpaceType *reduced_space, const json &config, const fs::path &model_root) {\n    // -- Setting up GAUSS\n    MyWorld world;\n\n    auto material_config = config[\"material_config\"];\n    auto integrator_config = config[\"integrator_config\"];\n    auto visualization_config = config[\"visualization_config\"];\n\n    NeohookeanTets *tets = new NeohookeanTets(V,T);\n    n_dof = tets->getImpl().getV().rows() * 3;\n    for(auto element: tets->getImpl().getElements()) {\n        element->setDensity(material_config[\"density\"]);\n        element->setParameters(material_config[\"youngs_modulus\"], material_config[\"poissons_ratio\"]);   \n    }\n\n    world.addSystem(tets);\n    world.finalize(); //After this all we're ready to go (clean up the interface a bit later)\n    reset_world(world);\n    // --- Finished GAUSS set up\n\n    // --- My integrator set up\n    double spring_stiffness = visualization_config[\"interaction_spring_stiffness\"];\n    SparseVector<double> interaction_force(n_dof);// = VectorXd::Zero(n_dof);\n\n    GPLCTimeStepper<ReducedSpaceType, MatrixType> gplc_stepper(model_root, integrator_config, &world, tets, reduced_space);\n\n    int png_scale = get_json_value(config, \"png_scale\", 1);\n    bool show_camera_info = false;\n    bool show_stress = visualization_config[\"show_stress\"];\n    bool show_energy = false;\n    bool show_tets = false;\n    try {\n        show_energy = visualization_config.at(\"show_energy\");\n    }\n    catch (nlohmann::detail::out_of_range& e){} // Didn't exist\n\n    if(show_energy && show_stress) {\n        std::cout << \"Can't show both energy and stress. Exiting.\" << std::endl;\n        exit(1);\n    }\n\n    bool do_gpu_decode = integrator_config[\"reduced_space_type\"] != \"full\" && get_json_value(visualization_config, \"gpu_decode\", false);\n    int max_frames = get_json_value(visualization_config, \"max_frames\", 0);\n\n    /** libigl display stuff **/\n    igl::viewer::Viewer viewer;    \n\n    viewer.data.set_mesh(V,F);\n    igl::per_corner_normals(V,F,40,N);\n    viewer.data.set_normals(N);\n \n    viewer.core.show_lines = get_json_value(visualization_config, \"show_lines\", false);\n    viewer.core.invert_normals = true;\n    if(NO_WAIT) {\n        viewer.core.is_animating = true;\n    } else {\n        viewer.core.is_animating = false;\n    }\n    viewer.data.face_based = false;\n    viewer.core.line_width = get_json_value(visualization_config, \"line_width\", 2.0);\n    viewer.core.animation_max_fps = 1000.0;\n    viewer.core.background_color = Eigen::Vector4f(1.0, 1.0, 1.0, 1.0);\n    viewer.core.shininess = 120.0;\n\n    viewer.data.set_colors(Eigen::RowVector3d(0.0, 0.0, 0.0));\n\n\n    Eigen::RowVector3d free_color = Eigen::RowVector3d(94.0/255.0,185.0/255.0,238.0/255.0);\n    Eigen::RowVector3d pinned_color = Eigen::RowVector3d(51/255.0, 61.0/255.0, 123.0/255.0);\n\n    std::string space_type = integrator_config[\"reduced_space_type\"];\n    if(space_type == \"autoencoder\") {\n        free_color = Eigen::RowVector3d(86.0/255.0,180.0/255.0,233.0/255.0);\n        pinned_color = Eigen::RowVector3d(51/255.0, 61.0/255.0, 123.0/255.0);\n    } else if(space_type == \"linear\") {\n        free_color = Eigen::RowVector3d(230.0/255.0,159.0/255.0,0.0/255.0);\n        pinned_color = Eigen::RowVector3d(138/255.0, 96.0/255.0, 0.0/255.0);\n    } else {\n        free_color = Eigen::RowVector3d(209.0/255.0,41.0/255.0,61.0/255.0);\n        pinned_color = Eigen::RowVector3d(129/255.0, 25.0/255.0, 38.0/255.0);\n    }\n   \n    MatrixXd C(V.rows(), 3);\n    for(int i = 0; i < C.rows(); i++) {\n        C.row(i) = Eigen::RowVector3d(0.0, 0.0, 0.0);\n    }\n     if(!get_json_value(visualization_config, \"disable_pinned_color\", false)) {\n        for(const auto &vi : fixed_verts) {\n            C.row(vi) = Eigen::RowVector3d(1.0, 1.0, 1.0);\n        }\n    }\n\n    viewer.data.set_colors(C);\n\n\n    viewer.launch_init(true, false);    \n    viewer.opengl.shader_mesh.free();\n\n    std::string mesh_vertex_shader_string;\n    std::string mesh_fragment_shader_string;\n\n    Eigen::Matrix< float,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> U;\n    Eigen::Matrix< float,Eigen::Dynamic,1> I = igl::LinSpaced< Eigen::Matrix< float,Eigen::Dynamic,1> >(V.rows(),0,V.rows()-1);\n    Eigen::Matrix< float,Eigen::Dynamic,3,Eigen::RowMajor> tex;\n    int n = 0;\n    int m = 0;\n    int s = 0;\n    if(do_gpu_decode) {\n        MatrixXd Ud = reduced_space->outer_jacobian();\n        U = Ud.cast <float> ();\n        n = V.rows();\n        m = U.cols();\n        s = ceil(sqrt(n*m));\n        assert((U.rows() == V.rows()*3) && \"#U should be 3*#V\");\n        assert(s*s > n*m);\n        printf(\"%d %d %d\\n\",n,m,s);\n        tex = Eigen::Matrix< float,Eigen::Dynamic,3,Eigen::RowMajor>::Zero(s*s,3);\n        for(int j = 0;j<m;j++) {\n            for(int i = 0;i<n;i++) {\n                for(int c = 0;c<3;c++) {\n                    tex(i*m+j,c) = U(i*3 + c, j);///U(i+c*n,j);\n                }\n            }\n        }\n    }\n\n    viewer.core.camera_zoom = get_json_value(visualization_config, \"camera_zoom\", 1.0);\n    std::vector<float> default_angle(4, 0.0f);\n    default_angle[0] = 1.0;\n    std::vector<float> trackball_angle = get_json_value(visualization_config, \"trackball_angle\", default_angle);\n    viewer.core.trackball_angle.w() = trackball_angle[0];\n    viewer.core.trackball_angle.x() = trackball_angle[1];\n    viewer.core.trackball_angle.y() = trackball_angle[2];\n    viewer.core.trackball_angle.z() = trackball_angle[3];\n\n    mesh_vertex_shader_string =\nR\"(#version 150\nuniform mat4 model;\nuniform mat4 view;\nuniform mat4 proj;\nin vec3 position;\nin vec3 normal;\nout vec3 position_eye;\nout vec3 normal_eye;\nin vec4 Ka;\nin vec4 Kd;\nin vec4 Ks;\nin vec2 texcoord;\nout vec2 texcoordi;\nout vec4 Kai;\nout vec4 Kdi;\nout vec4 Ksi;\n\nin float id;\nuniform int n;\nuniform int m;\nuniform int s;\nuniform bool do_gpu_decode;\nuniform float q[512];\nuniform sampler2D tex;\n\nvoid main()\n{\n  vec3 displacement = vec3(0,0,0);\n  if(do_gpu_decode) {\n      for(int j = 0;j < m; j++)\n      {\n        int index = int(id)*m+j;\n        int si = index % s;\n        int sj = int((index - si)/s);\n        displacement = displacement + texelFetch(tex,ivec2(si,sj),0).xyz*q[j];\n      }\n  }\n  vec3 deformed = position + displacement;\n\n  position_eye = vec3 (view * model * vec4 (deformed, 1.0));\n  gl_Position = proj * vec4 (position_eye, 1.0);\n  Kai = Ka;\n  Kdi = Kd;\n  Ksi = Ks;\n})\";\n\n    mesh_fragment_shader_string =\nR\"(#version 150\nuniform mat4 model;\nuniform mat4 view;\nuniform mat4 proj;\nuniform vec4 fixed_color;\nuniform vec4 free_color;\nuniform vec4 pinned_color;\nin vec3 position_eye;\nuniform vec3 light_position_world;\nvec3 Ls = vec3 (1, 1, 1);\nvec3 Ld = vec3 (1, 1, 1);\nvec3 La = vec3 (1, 1, 1);\nin vec4 Ksi;\nin vec4 Kdi;\nin vec4 Kai;\nuniform float specular_exponent;\nuniform float lighting_factor;\nout vec4 outColor;\nvoid main()\n{\n  vec3 xTangent = dFdx(position_eye);\n  vec3 yTangent = dFdy(position_eye);\n  vec3 normal_eye = normalize( cross( xTangent, yTangent ) );\n\nvec3 Ia = La * vec3(Kai);    // ambient intensity\nvec3 light_position_eye = vec3 (view * vec4 (light_position_world, 1.0));\nvec3 vector_to_light_eye = light_position_eye - position_eye;\nvec3 direction_to_light_eye = normalize (vector_to_light_eye);\nfloat dot_prod = dot (direction_to_light_eye, normal_eye);\nfloat clamped_dot_prod = max (dot_prod, 0.0);\n\n\nfloat eps = 1e-6;\nvec4 KdiNew = free_color * step(Kdi.x, 1.0 - eps) + pinned_color * (1.0 - step(Kdi.x, 1.0 - eps));\nvec3 Id = Ld * vec3(KdiNew) * clamped_dot_prod;    // Diffuse intensity\n\nvec3 reflection_eye = reflect (-direction_to_light_eye, normal_eye);\nvec3 surface_to_viewer_eye = normalize (-position_eye);\nfloat dot_prod_specular = dot (reflection_eye, surface_to_viewer_eye);\ndot_prod_specular = float(abs(dot_prod)==dot_prod) * max (dot_prod_specular, 0.0);\nfloat specular_factor = pow (dot_prod_specular, specular_exponent);\nvec3 Kfi = 0.5*vec3(Ksi); // vec3(1.0,1.0,1.0);//\nvec3 Lf = Ls;\nfloat fresnel_exponent = 2*specular_exponent;\nfloat fresnel_factor = 0;\n{\n  float NE = max( 0., dot( normal_eye, surface_to_viewer_eye));\n  fresnel_factor = pow (max(sqrt(1. - NE*NE),0.0), fresnel_exponent);\n}\nvec3 Is = Ls * vec3(Ksi) * specular_factor;    // specular intensity\nvec3 If = Lf * vec3(Kfi) * fresnel_factor;     // fresnel intensity\nvec4 color = vec4(lighting_factor * (If + Is + Id) + Ia + \n  (1.0-lighting_factor) * vec3(KdiNew),(Kai.a+Ksi.a+KdiNew.a)/3);\noutColor = color;\nif (fixed_color != vec4(0.0)) outColor = fixed_color;\n})\";\n    \n    viewer.opengl.shader_mesh.init( // This needs to come after shader and before buffer setup\n          mesh_vertex_shader_string,\n          mesh_fragment_shader_string, \n          \"outColor\");\n    \n    ///////////////////////////////////////////////////////////////////\n    // Send texture and vertex attributes to GPU\n    ///////////////////////////////////////////////////////////////////\n    {\n        GLuint prog_id = viewer.opengl.shader_mesh.program_shader;\n        glUseProgram(prog_id);\n        GLuint VAO = viewer.opengl.vao_mesh;\n        glBindVertexArray(VAO);\n        GLuint IBO;\n        glGenBuffers(1, &IBO);\n        glBindBuffer(GL_ARRAY_BUFFER, IBO);\n        glBufferData(GL_ARRAY_BUFFER, sizeof(float)*I.size(), I.data(), GL_STATIC_DRAW);\n        GLint iid = glGetAttribLocation(prog_id, \"id\");\n        glVertexAttribPointer(\n          iid, 1, GL_FLOAT, GL_FALSE, 1 * sizeof(GLfloat), (GLvoid*)0);\n        glEnableVertexAttribArray(iid);\n        glBindVertexArray(0);\n        glActiveTexture(GL_TEXTURE0);\n        //glGenTextures(1, &v.opengl.vbo_tex);\n        glBindTexture(GL_TEXTURE_2D, viewer.opengl.vbo_tex);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n        // 8650×8650 texture was roughly the max I could still get 60 fps, 8700²\n        // already dropped to 1fps\n        //\n        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, s,s, 0, GL_RGB, GL_FLOAT, tex.data());\n\n        GLint cyan_diffuse_loc = glGetUniformLocation(prog_id,\"free_color\");\n        glUniform4f(cyan_diffuse_loc, free_color(0), free_color(1), free_color(2), 1.0);\n        GLint fast_red_diffuse_loc = glGetUniformLocation(prog_id,\"pinned_color\");\n        glUniform4f(fast_red_diffuse_loc, pinned_color(0), pinned_color(1), pinned_color(2), 1.0);\n    }\n\n\n\n    double cur_fps = 0.0;\n    double tot_time = 0.0; \n    double last_time = igl::get_seconds();\n    std::vector<std::shared_future<bool>> VF;\n    viewer.callback_pre_draw = [&](igl::viewer::Viewer & viewer)\n    {\n        if(show_camera_info) {\n            std::cout << \"camera_zoom: \" << viewer.core.camera_zoom << std::endl;\n            std::cout << \"trackball_angle: \" << viewer.core.trackball_angle.w() << \", \"\n                                             << viewer.core.trackball_angle.x() << \", \"\n                                             << viewer.core.trackball_angle.y() << \", \"\n                                             << viewer.core.trackball_angle.z() << std::endl;\n        }\n\n        if(do_gpu_decode) {\n            /////////////////////////////////////////////////////////\n            // Send uniforms to shader\n            /////////////////////////////////////////////////////////\n            GLuint prog_id = viewer.opengl.shader_mesh.program_shader;\n            glUseProgram(prog_id);\n            GLint n_loc = glGetUniformLocation(prog_id,\"n\");\n            glUniform1i(n_loc,n);\n            GLint m_loc = glGetUniformLocation(prog_id,\"m\");\n            glUniform1i(m_loc,m);\n            GLint s_loc = glGetUniformLocation(prog_id,\"s\");\n            glUniform1i(s_loc,s);\n            GLint do_gpu_decode_loc = glGetUniformLocation(prog_id,\"do_gpu_decode\");\n            glUniform1i(do_gpu_decode_loc, do_gpu_decode);\n        \n            VectorXd sub_qd = reduced_space->sub_decode(gplc_stepper.get_current_z());\n            VectorXf sub_q = sub_qd.cast<float>();\n            GLint q_loc = glGetUniformLocation(prog_id,\"q\");\n            glUniform1fv(q_loc,U.cols(),sub_q.data());\n\n            // Do this now so that we can stop texture from being loaded by viewer\n            if (viewer.data.dirty)\n            {\n              viewer.opengl.set_data(viewer.data, viewer.core.invert_normals);\n              viewer.data.dirty = igl::viewer::ViewerData::DIRTY_NONE;\n            }\n            viewer.opengl.dirty &= ~igl::viewer::ViewerData::DIRTY_TEXTURE;\n        }\n\n        if(is_dragging) {\n            dragged_mesh_pos = gplc_stepper.get_current_vert_pos(vis_vert_id);\n\n            MatrixXi E(1,2);\n            E(0,0) = 0;\n            E(0,1) = 1;\n            MatrixXd P(2,3);using Eigen::VectorXd;\n            P.row(0) = dragged_pos;\n            P.row(1) = dragged_mesh_pos;\n            \n            viewer.data.set_edges(P, E, sea_green);\n        } else {\n            Eigen::MatrixXd part_pos = MatrixXd::Zero(1,3);\n            part_pos(0,0)=100000.0;\n\n            MatrixXi E(1,2);\n            E(0,0) = 0;\n            E(0,1) = 1;\n            MatrixXd P(2,3);\n            P.row(0) = Eigen::RowVector3d(1000.0,1000.0, 1000.0);\n            P.row(1) = Eigen::RowVector3d(1000.0,1000.0, 1000.0);;\n            viewer.data.set_edges(P, E, sea_green);\n        }\n\n        if(viewer.core.is_animating)\n        {   \n            if(SAVE_PNGS) {\n                    std::string frame_num_string = std::to_string(current_frame);// + starting_frame_num);\n                    fs::path  png_file = save_pngs_dir / (\"image_\" + frame_num_string + \".png\");\n\n                    // Allocate temporary buffers\n                    Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> R(1280*png_scale,800*png_scale);\n                    Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> G(1280*png_scale,800*png_scale);\n                    Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> B(1280*png_scale,800*png_scale);\n                    Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> A(1280*png_scale,800*png_scale);\n\n                    // // Draw the scene in the buffers\n                    viewer.core.draw_buffer(viewer.data, viewer.opengl, false,R,G,B,A);\n                    // // Save it to a PNG\n                    std::cout << \"WRITE TO PNG DISABLED\" << std::endl;\n                }\n\n            if(!do_gpu_decode) {\n                Eigen::MatrixXd newV = gplc_stepper.get_current_V();\n\n                if(show_tets) {\n                    VectorXi tet_indices = gplc_stepper.get_current_tets();\n                    T_sampled = igl::slice(T, tet_indices, 1);\n                    igl::boundary_facets(T_sampled, F_sampled);\n\n                    viewer.data.clear();\n                    viewer.data.set_mesh(newV, F_sampled);\n                } else {\n                    viewer.data.set_vertices(newV);\n                }\n\n            }\n\n            // Play back mouse interaction from previous sim\n            if(PLAYBACK_SIM) {\n                if(current_frame >= sim_playback_json[\"timesteps\"].size()) {\n                    exit_gracefully();\n                }\n\n                json current_mouse_info = sim_playback_json[\"timesteps\"][current_frame][\"mouse_info\"];\n                dragged_pos = Eigen::RowVector3d(current_mouse_info[\"dragged_pos\"][0], current_mouse_info[\"dragged_pos\"][1], current_mouse_info[\"dragged_pos\"][2]);\n                dragged_mesh_pos = Eigen::RowVector3d(current_mouse_info[\"dragged_mesh_pos\"][0], current_mouse_info[\"dragged_mesh_pos\"][1], current_mouse_info[\"dragged_mesh_pos\"][2]);\n\n                bool was_dragging = is_dragging;\n                is_dragging = current_mouse_info[\"is_dragging\"];\n\n                if(is_dragging && !was_dragging) { // Got a click\n                    Eigen::MatrixXd curV = gplc_stepper.get_current_V();\n\n                    MatrixXd C(1,3);\n                    C.row(0) = dragged_mesh_pos;\n                    MatrixXi I;\n                    igl::snap_points(C, curV, I);\n\n                    vis_vert_id = I(0,0);\n                    \n                    dragged_verts = get_verts_in_sphere(curV.row(vis_vert_id), spring_grab_radius, curV);\n                    std::cout << \"Grabbed \" << dragged_verts.size() << std::endl;\n                }\n            }\n            \n            // Do the physics update\n            interaction_force = compute_interaction_force(dragged_pos, dragged_verts, is_dragging, spring_stiffness, gplc_stepper);\n            gplc_stepper.step(interaction_force);\n\n            if(LOGGING_ENABLED) {\n                // Only do this work if we are saving objs\n                if(get_json_value(config, \"save_objs\", false)) {\n                    Eigen::MatrixXd newV = gplc_stepper.get_current_V(); // TODO we can avoid doing this\n                    fs::path obj_filename(int_to_padded_str(current_frame) + \"_surface_faces.obj\");\n                    igl::writeOBJ((surface_obj_dir /obj_filename).string(), newV, F);\n\n\n                    if(config[\"integrator_config\"][\"use_reduced_energy\"]) {\n                        fs::path tet_obj_filename(int_to_padded_str(current_frame) + \"_sample_tets.obj\");\n\n                        // Need to recompute sample tets each time if they are changing.\n                        if(PRED_WEIGHTS_L1 == energy_method_from_integrator_config(config[\"integrator_config\"])) {\n                            VectorXd weights;\n                            VectorXi indices;\n                            gplc_stepper.get_reduced_space()->get_cubature_indices_and_weights(gplc_stepper.get_current_z(), indices, weights);\n\n                            MatrixXi sample_tets = igl::slice(T, indices, 1);\n                            igl::boundary_facets(sample_tets, F_sampled);\n\n                            igl::writeOBJ((tet_obj_dir /tet_obj_filename).string(), newV, F_sampled);                    \n                        } else {\n                            T_sampled = igl::slice(T, gplc_stepper.get_current_tets(), 1);\n                            igl::boundary_facets(T_sampled, F_sampled);\n                            igl::writeOBJ((tet_obj_dir /tet_obj_filename).string(), newV, F_sampled);                    \n                        }\n                    }\n\n                // Export the pointer line\n                MatrixXi pointerF(1, 2);\n                pointerF << 0, 1;\n                MatrixXd pointerV(2,3);\n                if(is_dragging) {\n\n                    pointerV.row(0) = newV.row(vis_vert_id);\n                    pointerV.row(1) = dragged_pos;\n                } else {\n                    pointerV << 10000, 10000, 10000, 10001, 10001, 10001; \n                }\n\n                fs::path pointer_filename(int_to_padded_str(current_frame) + \"_mouse_pointer.obj\");\n                igl::writeOBJ((pointer_obj_dir / pointer_filename).string(), pointerV, pointerF);\n                }\n\n                if(SAVE_TRAINING_DATA) {\n                    std::string frame_num_string = std::to_string(current_frame);// + starting_frame_num);\n                    auto q = gplc_stepper.get_current_q();\n                    Eigen::Map<Eigen::MatrixXd> dV(q.data(), V.cols(), V.rows()); // Get displacements only\n                    Eigen::MatrixXd displacements = dV.transpose();\n\n                    fs::path  displacements_file = save_training_data_dir / (\"displacements_\" + frame_num_string + \".dmat\");\n                    igl::writeDMAT(displacements_file.string(), displacements, false); // Don't use ascii\n                }\n            }\n\n\n            if(current_frame % print_freq == 0) {   \n                double cur_time = igl::get_seconds();\n                if(current_frame >= 1) {\n                   tot_time += cur_time - last_time;\n                }\n                \n                cur_fps = print_freq / (cur_time - last_time);\n                last_time = cur_time;\n                std::cout << \"Step time + rendering(Hz): \"<< cur_fps << std::endl;\n                std::cout << \"Avg Step time + rendering(s): \"<< tot_time / (current_frame) << std::endl;\n            }\n\n            if(max_frames != 0 && current_frame + 1 >= max_frames) {\n                exit_gracefully();\n            }\n            current_frame++;\n        }\n\n        // if(show_stress) {\n        //     // Do stress field viz\n        //     VectorXd vm_stresses = get_von_mises_stresses(tets, world);\n        //     // vm_stresses is per element... Need to compute avg value per vertex\n        //     VectorXd vm_per_vert = VectorXd::Zero(V.rows());\n        //     VectorXi neighbors_per_vert = VectorXi::Zero(V.rows());\n            \n        //     int t = 0;\n        //     for(int i=0; i < T.rows(); i++) {\n        //         for(int j=0; j < 4; j++) {\n        //             t++;\n        //             int vert_index = T(i,j);\n        //             vm_per_vert[vert_index] += vm_stresses[i];\n        //             neighbors_per_vert[vert_index]++;\n        //         }\n        //     }\n        //     for(int i=0; i < vm_per_vert.size(); i++) {\n        //         vm_per_vert[i] /= neighbors_per_vert[i];\n        //     }\n        //     VectorXd vm_per_face = VectorXd::Zero(F.rows());\n        //     for(int i=0; i < vm_per_face.size(); i++) {\n        //         vm_per_face[i] = (vm_per_vert[F(i,0)] + vm_per_vert[F(i,1)] + vm_per_vert[F(i,2)])/3.0;\n        //     }\n        //     // std::cout << vm_per_face.maxCoeff() << \" \" <<  vm_per_face.minCoeff() << std::endl;\n        //     MatrixXd C;\n        //     //VectorXd((vm_per_face.array() -  vm_per_face.minCoeff()) / vm_per_face.maxCoeff())\n        //     igl::jet(vm_per_vert / 60.0, false, C);\n        //     viewer.data.set_colors(C);\n        // }\n\n        if(show_energy) {\n            // Do stress field viz\n            VectorXd energy_per_element = tets->getImpl().getStrainEnergyPerElement(world.getState());\n            // energy_per_element is per element... Need to compute avg value per vertex\n            VectorXd energy_per_vert = VectorXd::Zero(V.rows());\n            VectorXi neighbors_per_vert = VectorXi::Zero(V.rows());\n            \n            int t = 0;\n            for(int i=0; i < T.rows(); i++) {\n                for(int j=0; j < 4; j++) {\n                    t++;\n                    int vert_index = T(i,j);\n                    energy_per_vert[vert_index] += energy_per_element[i];\n                    neighbors_per_vert[vert_index]++;\n                }\n            }\n            for(int i=0; i < energy_per_vert.size(); i++) {\n                energy_per_vert[i] /= neighbors_per_vert[i];\n            }\n            VectorXd energy_per_face = VectorXd::Zero(F.rows());\n            for(int i=0; i < energy_per_face.size(); i++) {\n                energy_per_face[i] = (energy_per_vert[F(i,0)] + energy_per_vert[F(i,1)] + energy_per_vert[F(i,2)])/3.0;\n            }\n\n            MatrixXd C;\n            \n            igl::jet(energy_per_face, false, C);\n            viewer.data.set_colors(C);\n        }\n\n        return false;\n    };\n\n    int index_counter = 0;\n    viewer.callback_key_pressed = [&](igl::viewer::Viewer &, unsigned int key, int mod)\n    {\n        switch(key)\n        {\n            case 'q':\n            {\n                exit_gracefully();\n                break;\n            }\n            case 'P':\n            case 'p':\n            {\n                viewer.core.is_animating = !viewer.core.is_animating;\n                break;\n            }\n            case 'r':\n            case 'R':\n            {\n                reset_world(world);\n                gplc_stepper.reset_zs();\n                break;\n            }\n            case 's':\n            case 'S':\n            {\n                show_stress = !show_stress;\n                show_energy = false;\n                break;\n            }\n            case 't':\n            case 'T':\n            {\n                viewer.data.clear();\n                viewer.data.set_mesh(V, F);\n                show_tets = !show_tets;\n                viewer.data.set_colors(Eigen::RowVector3d(1.0, 1.0, 0.0));\n                break;\n            }\n            case '-':\n            {\n                gplc_stepper.switch_to_next_tets(++index_counter);\n                break;\n            }\n            case '=':\n            case '+':\n            {\n                gplc_stepper.switch_to_next_tets(--index_counter);\n                break;\n            }\n            case 'n':\n            case 'N':\n            {\n                per_vertex_normals = !per_vertex_normals;\n                break;\n            }\n            case 'c':\n            case 'C':\n            {\n                show_camera_info = !show_camera_info;\n                break;\n            }\n            default:\n            return false;\n        }\n        return true;\n    };\n\n    viewer.callback_mouse_down = [&](igl::viewer::Viewer&, int, int)->bool\n    {   \n        if(!PLAYBACK_SIM) {\n            Eigen::MatrixXd curV = gplc_stepper.get_current_V(); \n            last_mouse = Eigen::RowVector3f(viewer.current_mouse_x,viewer.core.viewport(3)-viewer.current_mouse_y,0);\n            \n            int fid;\n            Eigen::Vector3f bary;\n            // Find closest point on mesh to mouse position\n            if(igl::unproject_onto_mesh(\n                last_mouse.head(2),\n                viewer.core.view * viewer.core.model,\n                viewer.core.proj, \n                viewer.core.viewport, \n                curV, F, \n                fid, bary))\n            {\n                long c;\n                bary.maxCoeff(&c);\n                vis_vert_id = F(fid,c);\n\n                dragged_pos = curV.row(vis_vert_id);\n                dragged_mesh_pos = dragged_pos; // Just using closest vert for now\n                dragged_verts = get_verts_in_sphere(dragged_mesh_pos, spring_grab_radius, curV);\n\n                std::cout << \"Grabbed \" << dragged_verts.size() << \" verts\" << std::endl;\n                is_dragging = true;\n\n                return true;\n            }\n        }\n        \n        return false; // TODO false vs true??\n    };\n\n    viewer.callback_mouse_up = [&](igl::viewer::Viewer&, int, int)->bool\n    {\n        if(!PLAYBACK_SIM) {\n            is_dragging = false;\n        }\n        return false;\n    };\n\n    viewer.callback_mouse_move = [&](igl::viewer::Viewer &, int,int)->bool\n    {\n        if(!PLAYBACK_SIM) {\n            // Eigen::MatrixXd curV = gplc_stepper.get_current_V();\n            if(is_dragging) {\n                Eigen::RowVector3f drag_mouse(\n                    viewer.current_mouse_x,\n                    viewer.core.viewport(3) - viewer.current_mouse_y,\n                    last_mouse(2));\n\n                Eigen::RowVector3f drag_scene,last_scene;\n\n                igl::unproject(\n                    drag_mouse,\n                    viewer.core.view*viewer.core.model,\n                    viewer.core.proj,\n                    viewer.core.viewport,\n                    drag_scene);\n                igl::unproject(\n                    last_mouse,\n                    viewer.core.view*viewer.core.model,\n                    viewer.core.proj,\n                    viewer.core.viewport,\n                    last_scene);\n\n                dragged_pos += ((drag_scene-last_scene)*4.5).cast<double>(); //TODO why do I need to fine tune this\n                last_mouse = drag_mouse;\n            }\n        }\n        return false;\n    };\n\n    viewer.launch_rendering(true);\n    viewer.launch_shut();\n}\n\n\nconst std::string currentDateTime() {\n    time_t     now = time(0);\n    struct tm  tstruct;\n    char       buf[80];\n    tstruct = *localtime(&now);\n    // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime\n    // for more information about date/time format\n    strftime(buf, sizeof(buf), \"%Y-%m-%d.%X\", &tstruct);\n    return buf;\n}\n\n\nint main(int argc, char **argv) {\n    \n    // Load the configuration file\n    if(argc < 2) {\n        std::cout << \"Expected model root.\" << std::endl;\n    }\n\n    fs::path model_root(argv[1]);\n    fs::path sim_config(\"sim_config.json\");\n\n    if(argc >= 3) {\n        if(std::string(argv[2]) != \"--log_name\") { // hack to save the log name I want\n            fs::path sim_recording_path(argv[2]);\n            std::ifstream recording_fin(sim_recording_path.string());\n\n            recording_fin >> sim_playback_json;\n            PLAYBACK_SIM = true;\n        }\n    }\n\n    std::ifstream fin((model_root / sim_config).string());\n    json config;\n    fin >> config;\n\n    auto integrator_config = config[\"integrator_config\"];\n    auto material_config = config[\"material_config\"];\n    auto viz_config = config[\"visualization_config\"];\n    std::string reduced_space_string = integrator_config[\"reduced_space_type\"];\n\n    print_freq = get_json_value(config[\"visualization_config\"], \"print_every_n_frames\", print_freq);\n\n    std::string log_string = \"\";\n    if(argc == 4 && std::string(argv[3]) == \"--no_wait\" ) {\n        NO_WAIT = true;\n    } else if(argc == 4) {\n        log_string = argv[3];\n    } else {\n        log_string = currentDateTime() + \"_\" + reduced_space_string;\n    }\n\n    LOGGING_ENABLED = config[\"logging_enabled\"];\n    if(LOGGING_ENABLED) {\n        sim_log[\"sim_config\"] = config;\n        sim_log[\"timesteps\"] = {};\n        fs::path sim_log_path(\"simulation_logs/\");\n        log_dir = model_root / fs::path(\"./simulation_logs/\" + log_string + \"/\");\n        surface_obj_dir = log_dir / fs::path(\"objs/surface/\");\n        pointer_obj_dir = log_dir / fs::path(\"objs/pointer/\");\n        tet_obj_dir = log_dir / fs::path(\"objs/sampled_tets/\");\n        iteration_obj_dir = log_dir / fs::path(\"objs/evaluations/\");\n        if(!boost::filesystem::exists(model_root / sim_log_path)){\n            boost::filesystem::create_directory(model_root / sim_log_path);\n        }\n\n        if(!boost::filesystem::exists(log_dir)){\n            boost::filesystem::create_directory(log_dir);\n        }\n\n        if(!boost::filesystem::exists(surface_obj_dir)){\n            boost::filesystem::create_directories(surface_obj_dir);\n        }\n\n        if(!boost::filesystem::exists(pointer_obj_dir)){\n            boost::filesystem::create_directories(pointer_obj_dir);\n        }\n\n        if(!boost::filesystem::exists(tet_obj_dir) && integrator_config[\"use_reduced_energy\"]){\n            boost::filesystem::create_directories(tet_obj_dir);\n        }\n\n        if(!boost::filesystem::exists(iteration_obj_dir) && get_json_value(integrator_config, \"save_obj_every_iteration\", false)){\n            boost::filesystem::create_directories(iteration_obj_dir);\n        }\n\n        // boost::filesystem::create_directories(log_dir);\n        fs::path log_file(\"sim_stats.json\");\n\n        log_ofstream = std::ofstream((log_dir / log_file).string());\n    }\n\n    std::string alternative_mesh_path = get_json_value(config, \"alternative_full_space_mesh\", std::string(\"\"));\n\n    // Now do the set up for stuff if we are saving training data\n    SAVE_TRAINING_DATA = get_json_value(config, \"save_training_data\", false);\n    if(SAVE_TRAINING_DATA) {\n        std::string save_training_data_path_string = get_json_value(config, \"save_training_data_path\", std::string());\n        save_training_data_dir = fs::path(save_training_data_path_string);\n        create_or_replace_dir(save_training_data_dir);\n        std::cout << \"SAVING TRAINING DATA TO \" << save_training_data_dir.string() << std::endl;\n\n        // Save the training params\n        json training_data_params;\n        training_data_params[\"density\"] = material_config[\"density\"];\n        training_data_params[\"YM\"] = material_config[\"youngs_modulus\"];\n        training_data_params[\"Poisson\"] = material_config[\"poissons_ratio\"];\n        training_data_params[\"time_step\"] = integrator_config[\"timestep\"];\n        training_data_params[\"spring_strength\"] = viz_config[\"interaction_spring_stiffness\"];\n        training_data_params[\"spring_grab_radius\"] = viz_config[\"spring_grab_radius\"];\n        training_data_params[\"fixed_axis\"] = viz_config[\"full_space_constrained_axis\"];\n        training_data_params[\"constrained_axis_eps\"] = viz_config[\"constrained_axis_eps\"];\n        training_data_params[\"flip_fixed_axis\"] = viz_config[\"flip_constrained_axis\"];\n        training_data_params[\"fixed_point_constraint\"] = viz_config[\"fixed_point_constraint\"];\n        training_data_params[\"fixed_point_radius\"] = viz_config[\"fixed_point_radius\"];\n\n        std::ofstream fout((save_training_data_dir / \"parameters.json\").string());\n        fout << training_data_params;\n        fout.close();\n\n        if(alternative_mesh_path != \"\") {\n            fs::copy_file(alternative_mesh_path, save_training_data_dir / \"tets.mesh\" );\n        } else {\n            fs::copy_file((model_root / \"tets.mesh\").string(), save_training_data_dir / \"tets.mesh\" );\n        }\n    }\n\n    SAVE_PNGS = get_json_value(config, \"save_pngs\", false);\n    if(SAVE_PNGS) {\n        // std::string save_pngs_path_string = get_json_value(config, \"save_pngs_path\", std::string());\n        save_pngs_dir =  log_dir / fs::path(\"pngs/\");\n        create_or_replace_dir(save_pngs_dir);\n    }\n\n    // Load the mesh here\n    if(alternative_mesh_path != \"\") {\n        igl::readMESH((model_root / alternative_mesh_path).string(), V, T, F);\n    } else {\n        igl::readMESH((model_root / \"tets.mesh\").string(), V, T, F);\n    }\n\n    igl::boundary_facets(T,F);\n\n    // Center mesh\n    Eigen::RowVector3d centroid;\n    igl::centroid(V, F, centroid);\n    V = V.rowwise() - centroid;\n\n    // Hacky way of setting spring grab radius to zero for reduced space\n    spring_grab_radius = get_json_value(config[\"visualization_config\"], \"spring_grab_radius\", 0.03);\n    if(reduced_space_string != \"full\") {\n        bool use_spring_grab_radius_for_reduced = get_json_value(config[\"visualization_config\"], \"use_spring_grab_radius_for_reduced\", false);\n        if(!use_spring_grab_radius_for_reduced) {\n            spring_grab_radius = get_json_value(config[\"visualization_config\"], \"spring_grab_radius\", 0.03);\n            VectorXd R;\n            igl::circumradius(V, F, R);\n            spring_grab_radius = R.maxCoeff();//Make it slightly bigger than the biggest triangle\n        }\n    }\n\n    // Do this out here so we can still visualize the constrained verts\n    int fixed_axis = -1;\n    try {\n        fixed_axis = config[\"visualization_config\"].at(\"full_space_constrained_axis\");\n    } \n    catch (nlohmann::detail::out_of_range& e){\n        std::cout << \"full_space_constrained_axis field not found in visualization_config\" << std::endl;\n        exit(1);\n    }\n    bool flip_axis = get_json_value(config[\"visualization_config\"], \"flip_constrained_axis\", false);\n    std::vector<double> fixed_vert_c = get_json_value(config[\"visualization_config\"], \"fixed_point_constraint\", std::vector<double>());\n    double fixed_vert_r = get_json_value(config[\"visualization_config\"], \"fixed_point_radius\", 0.0);\n    double constrained_axis_eps = get_json_value(config[\"visualization_config\"], \"constrained_axis_eps\", 0.01);\n\n    if(fixed_axis != -1) {\n        fixed_verts = get_min_verts(fixed_axis, flip_axis, constrained_axis_eps);\n    } else if (fixed_vert_r != -1) {\n        fixed_verts = get_verts_in_sphere(Eigen::Map<VectorXd>(fixed_vert_c.data(), 3), fixed_vert_r, V);\n    }\n\n    if(reduced_space_string == \"linear\") {\n        std::string pca_dim(std::to_string((int)integrator_config[\"pca_dim\"]));\n        fs::path pca_components_path(\"pca_results/pca_components_\" + pca_dim + \".dmat\");\n\n        MatrixXd U;\n        igl::readDMAT((model_root / pca_components_path).string(), U);\n        LinearSpace reduced_space(U);\n\n        run_sim<LinearSpace, MatrixXd>(&reduced_space, config, model_root);\n    }\n    else if(reduced_space_string == \"autoencoder\") {\n        fs::path tf_models_root(model_root / \"tf_models/\");\n        AutoencoderSpace reduced_space(tf_models_root, integrator_config);\n        run_sim<AutoencoderSpace, MatrixXd>(&reduced_space, config, model_root);  \n    }\n    else if(reduced_space_string == \"full\") {\n        std::cout << \"Constraining \" << fixed_verts.size() << \" verts\" << std::endl;\n        SparseMatrix<double> P = construct_constraints_P(V, fixed_verts); // Constrain on X axis\n        SparseConstraintSpace reduced_space(P.transpose());\n\n        run_sim<SparseConstraintSpace, SparseMatrix<double>>(&reduced_space, config, model_root);\n    }\n    else {\n        std::cout << \"Not yet implemented.\" << std::endl;\n        return 1;\n    }\n    \n    return EXIT_SUCCESS;\n\n}\n\n", "meta": {"hexsha": "61779650f9412fc86b2b059f949505040d132e3a", "size": 75860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AutoDefRuntime/src/main.cpp", "max_stars_repo_name": "ericchen321/AutoDef", "max_stars_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T03:48:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:51:50.000Z", "max_issues_repo_path": "src/AutoDefRuntime/src/main.cpp", "max_issues_repo_name": "ericchen321/AutoDef", "max_issues_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-04T12:16:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:02:41.000Z", "max_forks_repo_path": "src/AutoDefRuntime/src/main.cpp", "max_forks_repo_name": "ericchen321/AutoDef", "max_forks_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-02T11:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T11:53:23.000Z", "avg_line_length": 39.2446973616, "max_line_length": 210, "alphanum_fraction": 0.608159768, "num_tokens": 18974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296919173767833, "lm_q2_score": 0.025178844352267953, "lm_q1q2_score": 0.009139144783431506}}
{"text": "#include \"DataTools.h\"\r\n#include <boost/tokenizer.hpp> \r\n\r\n\r\nDataTools::DataTools()\r\n{}\r\n\r\nDataTools::~DataTools()\r\n{\r\n}\r\n\r\n\r\nstd::string DataTools::computeElapsedTime(const clock_t &_startTimer, const clock_t &_stopTimer)\r\n{\r\n\tint _iHours =(int)floor((float)(_stopTimer - _startTimer)/(CLOCKS_PER_SEC*60*60));\r\n\tint _iMinutes = (int)floor((float)(_stopTimer - _startTimer))/(CLOCKS_PER_SEC*60)-_iHours*60;\r\n\tint _iSeconds = ((float)(_stopTimer - _startTimer))/CLOCKS_PER_SEC - _iMinutes*60 - _iHours*60*60;\r\n\t\tchar _cHours[3], _cMinutes[3], _cSeconds[3];\r\n\t\tsprintf(_cHours,\"%d\",_iHours);\r\n\t\tif ( strlen(_cHours) < 2)\r\n\t\t\tsprintf(_cHours,\"0%d\",_iHours);\r\n\t\tsprintf(_cMinutes,\"%d\",_iMinutes);\r\n\t\tif ( strlen(_cMinutes) < 2)\r\n\t\t\tsprintf(_cMinutes,\"0%d\",_iMinutes);\r\n\t\tsprintf(_cSeconds,\"%d\",_iSeconds);\r\n\t\tif ( strlen(_cSeconds) < 2)\r\n\t\t\tsprintf(_cSeconds,\"0%d\",_iSeconds);\r\n\r\n\tstd::stringstream _ss;\r\n\t_ss <<  _cHours << \":\" << _cMinutes << \":\" << _cSeconds;\r\n\r\n\treturn _ss.str();\r\n\r\n}\r\n\r\nbool DataTools::getTrackingDataFromFile(std::string filename, std::string target, std::vector<TrackingData> &trackingVector)\r\n{\r\n\tstd::fstream _file;\r\n\tstd::string _header;\r\n\tstd::streamoff _headerOffset;\r\n\tint _fileLength;\r\n\r\n\t_file.open(filename.c_str() , std::ios::in);\r\n\r\n\t_file.seekg (0, std::ios::end);\r\n\t_fileLength = _file.tellg();\r\n\t_file.seekg (0, std::ios::beg);\r\n\r\n\r\n\t// parse the header \r\n\tbool isHeader = true;\r\n\tbool lastStar = false;\r\n\twhile (_file.good() && isHeader)\r\n\t{\r\n\t\tchar ch;\r\n\t\tch = (char) _file.get();\r\n\t\tif (ch == '*')\r\n\t\t{\r\n\t\t\tlastStar = true;\r\n\t\t} else\r\n\t\t\tif (ch == '/' && lastStar)\r\n\t\t\t{\r\n\t\t\t\tisHeader = false;\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tlastStar = false;\r\n\t\t\t}\r\n\t\t\t_header.append(1,ch);\r\n\t}\r\n\r\n\t// after header is succesfully parsed calculate header offset\r\n\t_headerOffset = _file.tellg();\r\n\r\n\twhile(! ( static_cast<int>(_file.tellg()) == -1  || static_cast<int>(_file.tellg()) >= _fileLength ))\r\n\t{\r\n\t\tfloat tmpTimeStamp;\r\n\t\tint nrTargets, nrPoints;\r\n\r\n\r\n\t\t_file >> tmpTimeStamp;\r\n\t\t//m_allTimeStamps.push_back(tmpTimeStamp);\r\n\t\t_file >> nrTargets;\r\n\t\t_file >> nrPoints;\r\n\t\t/*\r\n\t\tstd::cout << \"Time Stamp: \" << tmpTimeStamp << std::endl;\r\n\t\tstd::cout << \"Number of Targets: \" << nrTargets << std::endl;\r\n\t\tstd::cout << \"Number of Points: \" << nrPoints << std::endl;\r\n\t\t*/\r\n\r\n\t\tfor ( int i= 0; i < nrTargets; i++)\r\n\t\t{\r\n\t\t\tTrackingData td;\r\n\r\n\t\t\t//m_file.flags( std::ios_base::scientific);\t\r\n\t\t\t_file >> td.targetID\t \r\n\t\t\t\t>> td.translation[0]\t\t\t>> td.translation[1]\t\t>> td.translation[2] \r\n\t\t\t>> td.quaternion[0]\t\t\t>> td.quaternion[1]\t\t>>  td.quaternion[2]  >> td.quaternion[3]\r\n\t\t\t>> td.scale[0]\t\t\t>> td.scale[1]\t\t>> td.scale[2] \r\n\t\t\t>> td.error\t\t>> td.isValid;\r\n\r\n\t\t\ttd.timestamp = tmpTimeStamp;\r\n\t\t\tif ( td.targetID.compare( target) == 0 && td.isValid  && !_file.fail()) // avoid the empty line in file problem\r\n\t\t\t{\r\n\t\t\t\ttrackingVector.push_back(td);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t_file.clear();\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\nbool DataTools::getTargetNamesFromFile(std::string filename, std::vector<std::string> &targetNameVector)\r\n{\r\n\tstd::fstream _file;\r\n\tstd::string _header;\r\n\tstd::streamoff _headerOffset;\r\n\tint _fileLength;\r\n\r\n\t_file.open(filename.c_str() , std::ios::in);\r\n\r\n\t_file.seekg (0, std::ios::end);\r\n\t_fileLength = _file.tellg();\r\n\t_file.seekg (0, std::ios::beg);\r\n\r\n\r\n\t// parse the header \r\n\tbool isHeader = true;\r\n\tbool lastStar = false;\r\n\twhile (_file.good() && isHeader)\r\n\t{\r\n\t\tchar ch;\r\n\t\tch = (char) _file.get();\r\n\t\tif (ch == '*')\r\n\t\t{\r\n\t\t\tlastStar = true;\r\n\t\t} else\r\n\t\t\tif (ch == '/' && lastStar)\r\n\t\t\t{\r\n\t\t\t\tisHeader = false;\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tlastStar = false;\r\n\t\t\t}\r\n\t\t\t_header.append(1,ch);\r\n\t}\r\n\r\n\t// after header is succesfully parsed calculate header offset\r\n\t_headerOffset = _file.tellg();\r\n\t\r\n\t// only load up to _maxCOUNT tracking data to check for the target IDs\r\n\tint _counter = 0;\r\n\t\r\n\tint _maxCOUNT = 100;\r\n\r\n\twhile(! ( static_cast<int>(_file.tellg()) == -1  || static_cast<int>(_file.tellg()) >= _fileLength ) && _counter <= _maxCOUNT)\r\n\t{\r\n\t\t_counter++;\r\n\r\n\t\tfloat tmpTimeStamp;\r\n\t\tint nrTargets, nrPoints;\r\n\r\n\r\n\t\t_file >> tmpTimeStamp;\r\n\t\t//m_allTimeStamps.push_back(tmpTimeStamp);\r\n\t\t_file >> nrTargets;\r\n\t\t_file >> nrPoints;\r\n\t\t/*\r\n\t\tstd::cout << \"Time Stamp: \" << tmpTimeStamp << std::endl;\r\n\t\tstd::cout << \"Number of Targets: \" << nrTargets << std::endl;\r\n\t\tstd::cout << \"Number of Points: \" << nrPoints << std::endl;\r\n\t\t*/\r\n\r\n\t\tfor ( int i= 0; i < nrTargets; i++)\r\n\t\t{\r\n\t\t\tTrackingData td;\r\n\r\n\t\t\t//m_file.flags( std::ios_base::scientific);\t\r\n\t\t\t_file >> td.targetID\t \r\n\t\t\t\t>> td.translation[0]\t\t\t>> td.translation[1]\t\t>> td.translation[2] \r\n\t\t\t>> td.quaternion[0]\t\t\t>> td.quaternion[1]\t\t>>  td.quaternion[2]  >> td.quaternion[3]\r\n\t\t\t>> td.scale[0]\t\t\t>> td.scale[1]\t\t>> td.scale[2] \r\n\t\t\t>> td.error\t\t>> td.isValid;\r\n\r\n\t\t\t\r\n\t\t\tstd::vector<std::string>::iterator it = std::find(targetNameVector.begin(), targetNameVector.end(), td.targetID);\r\n\t\t\t// not found, so we can add it to the target names\r\n\t\t\tif (it == targetNameVector.end())\r\n\t\t\t{\r\n\t\t\t\ttargetNameVector.push_back(td.targetID);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t_file.clear();\r\n\r\n\treturn true;\r\n\r\n}\r\n\r\nbool DataTools::writeTrackingDataToFile(std::vector<Eigen::Transform3f, Eigen::aligned_allocator<Eigen::Transform3f>> &_data, std::string targetName, std::string filename)\r\n{\r\n\tstd::ofstream _trackingFile;\r\n\t_trackingFile.open(filename);\r\n\r\n\t// write mandatory header\r\n\t_trackingFile << \" Tracking data: timestamp <NumOfTargets> <NumOfPoints>  <TargetID> x z z qw qx qy qz sx sy sz error isValid */\" << std::endl;\r\n\r\n\tfor (int i=0; i < _data.size();i++)\r\n\t{\r\n\t\t_trackingFile << i << \"\\t1 \\t0\" << std::endl;\r\n\r\n\t\tEigen::Transform3f _trans  = _data[i];\r\n\t\tEigen::Quaternionf _quat(_trans.rotation());\r\n\r\n\t\t_trackingFile << targetName << \"\\t\" << _trans.translation().x() << \"\\t\" << _trans.translation().y() << \"\\t\" << _trans.translation().z() << \"\\t\" << _quat.w() << \"\\t\" << _quat.x() << \"\\t\" << _quat.y() << \"\\t\" << _quat.z() << \"\\t1.0\\t1.0\\t1.0\\t0\\t1\" << std::endl;\r\n\t} \r\n\r\n\t_trackingFile.close();\r\n\r\n\treturn true;\r\n}\r\n\r\nbool DataTools::getTrackingDataFromFileRelative(std::string filename, std::string target, std::string referenceTarget, std::vector<TrackingData> &trackingVector)\r\n{\r\n\tstd::fstream _file;\r\n\tstd::string _header;\r\n\tstd::streamoff _headerOffset;\r\n\tint _fileLength;\r\n\r\n\t_file.open(filename.c_str() , std::ios::in);\r\n\r\n\t_file.seekg (0, std::ios::end);\r\n\t_fileLength = _file.tellg();\r\n\t_file.seekg (0, std::ios::beg);\r\n\r\n\r\n\t// parse the header \r\n\tbool isHeader = true;\r\n\tbool lastStar = false;\r\n\twhile (_file.good() && isHeader)\r\n\t{\r\n\t\tchar ch;\r\n\t\tch = (char) _file.get();\r\n\t\tif (ch == '*')\r\n\t\t{\r\n\t\t\tlastStar = true;\r\n\t\t} else\r\n\t\t\tif (ch == '/' && lastStar)\r\n\t\t\t{\r\n\t\t\t\tisHeader = false;\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tlastStar = false;\r\n\t\t\t}\r\n\t\t\t_header.append(1,ch);\r\n\t}\r\n\r\n\t// after header is succesfully parsed calculate header offset\r\n\t_headerOffset = _file.tellg();\r\n\r\n\tint counter = 0;\r\n\r\n\twhile(! ( static_cast<int>(_file.tellg()) == -1  || static_cast<int>(_file.tellg()) >= _fileLength ))\r\n\t{\r\n\t\tfloat tmpTimeStamp;\r\n\t\tint nrTargets, nrPoints;\r\n\r\n\r\n\t\t_file >> tmpTimeStamp;\r\n\t\t//m_allTimeStamps.push_back(tmpTimeStamp);\r\n\t\t_file >> nrTargets;\r\n\t\t_file >> nrPoints;\r\n\r\n\t\t/*\r\n\t\tstd::cout << \"Time Stamp: \" << tmpTimeStamp << std::endl;\r\n\t\tstd::cout << \"Number of Targets: \" << nrTargets << std::endl;\r\n\t\tstd::cout << \"Number of Points: \" << nrPoints << std::endl;\r\n\t\t*/\r\n\r\n\t\tTrackingData _referenceTarget;\r\n\t\tTrackingData _toolTarget;\r\n\t\tbool _validReferenceTarget = false;\r\n\t\tbool _validToolTarget = false;\r\n\r\n\r\n\t\tfor ( int i= 0; i < nrTargets; i++)\r\n\t\t{\r\n\t\t\tTrackingData td;\r\n\r\n\t\t\t//m_file.flags( std::ios_base::scientific);\t\r\n\t\t\t_file >> td.targetID\t \r\n\t\t\t\t>> td.translation[0]\t\t\t>> td.translation[1]\t\t>> td.translation[2] \r\n\t\t\t>> td.quaternion[0]\t\t\t>> td.quaternion[1]\t\t>>  td.quaternion[2]  >> td.quaternion[3]\r\n\t\t\t>> td.scale[0]\t\t\t>> td.scale[1]\t\t>> td.scale[2] \r\n\t\t\t>> td.error\t\t>> td.isValid;\r\n\r\n\t\t\ttd.timestamp = tmpTimeStamp;\r\n\r\n\t\t\t// get the tracking data of the tool target\r\n\t\t\tif ( td.targetID.compare( target) == 0 && !_file.fail() && td.isValid) // avoid the empty line in file problem\r\n\t\t\t{\r\n\t\t\t\t_validToolTarget = true;\r\n\t\t\t\t_toolTarget = td;\r\n\t\t\t\t//trackingVector.push_back(td);\r\n\t\t\t} // get the tracking data of the reference target\r\n\t\t\telse if ( td.targetID.compare( referenceTarget) == 0 && !_file.fail() && td.isValid) // avoid the empty line in file problem\r\n\t\t\t{\r\n\t\t\t\t_validReferenceTarget = true;\r\n\t\t\t\t_referenceTarget = td;\r\n\t\t\t\t//trackingVector.push_back(td);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// if we have acquired both, the tool and the reference position, we got enough data\r\n\t\t// to provide the tool position in the reference target coordinate system\r\n\t\tif ( _validReferenceTarget && _validToolTarget )\r\n\t\t{\r\n\r\n\t\t\t\r\n\r\n\t\t\tEigen::Quaternionf _toolQuat( _toolTarget.quaternion[0], _toolTarget.quaternion[1], _toolTarget.quaternion[2], _toolTarget.quaternion[3]);\r\n\t\t\tEigen::Vector3f _transTool;\r\n\t\t\t_transTool << _toolTarget.translation[0], _toolTarget.translation[1], _toolTarget.translation[2];\r\n\r\n\t\t\tEigen::Quaternionf _referenceQuat( _referenceTarget.quaternion[0], _referenceTarget.quaternion[1], _referenceTarget.quaternion[2], _referenceTarget.quaternion[3]);\r\n\t\t\tEigen::Vector3f _transReference;\r\n\t\t\t_transReference << _referenceTarget.translation[0], _referenceTarget.translation[1], _referenceTarget.translation[2];\r\n\r\n\r\n\t\t\t// build the 4x4 transformation matrix from the quaternion and 3-vector (tool target)\r\n\t\t\tEigen::Transform3f _toolTrackingMatrix;\r\n\t\t\t_toolTrackingMatrix.setIdentity();\r\n\t\t\t_toolTrackingMatrix.rotate( _toolQuat.toRotationMatrix());\r\n\t\t\t_toolTrackingMatrix.translation() = _transTool;\r\n\t\t\t\r\n\t\t\t// build the 4x4 transformation matrix from the quaterion and 3-vector (reference target)\r\n\t\t\tEigen::Transform3f _referenceTrackingMatrix;\r\n\t\t\t_referenceTrackingMatrix.setIdentity();\r\n\t\t\t_referenceTrackingMatrix.rotate( _referenceQuat.toRotationMatrix());\r\n\t\t\t_referenceTrackingMatrix.translation() = _transReference;\r\n\r\n\r\n\r\n\t\t\r\n\t\t\tEigen::Transform3f  _newToolCoordinates = _referenceTrackingMatrix.inverse() * _toolTrackingMatrix;\r\n\t\t\tEigen::Quaternionf _newToolQuat(_newToolCoordinates.rotation());\r\n\t\t\tEigen::Vector3f _newToolTrans(_newToolCoordinates.translation());\r\n\r\n\r\n\t\t\t/*if ( counter == 889 || counter == 890 )\r\n\t\t\t{\r\n\t\t\t\tstd::cout << \"Reference: \" << std::endl;\r\n\t\t\t\tstd::cout << _referenceTrackingMatrix.matrix() << std::endl << std::endl;\r\n\t\t\t\tstd::cout << _referenceQuat.w() << \", \" << _referenceQuat.x() << \", \" << _referenceQuat.y() << \", \" << _referenceQuat.z() << std::endl;\r\n\r\n\t\t\t\tstd::cout << \"USProbe: \" << std::endl;\r\n\t\t\t\tstd::cout << _toolTrackingMatrix.matrix() << std::endl << std::endl;\r\n\t\t\t\tstd::cout << _toolQuat.w() << \", \" << _toolQuat.x() << \", \" << _toolQuat.y() << \", \" << _toolQuat.z() << std::endl;\r\n\t\t\t\r\n\t\t\t\tstd::cout << \"Trans: \" << std::endl;\r\n\t\t\t\tstd::cout << _newToolCoordinates.matrix() << std::endl;\r\n\t\t\t\tstd::cout << std::endl;\r\n\r\n\t\t\t\tstd::cout << \"New Quat: \"<< std::endl;\r\n\t\t\t\tstd::cout << _newToolQuat.w() << \", \" << _newToolQuat.x() << \", \" << _newToolQuat.y() << \", \" << _newToolQuat.z() << std::endl;\r\n\t\t\t\r\n\r\n\t\t\t\tstd::cout << \"Back to Rotation: \"<< std::endl;\r\n\t\t\t\tEigen::Matrix3f _testMat = _newToolQuat.toRotationMatrix();\r\n\t\t\t\tstd::cout << _testMat << std::endl;\r\n\r\n\t\t\t\t\tstd::cout << std::endl;\r\n\t\t\t}*/\r\n\r\n\t\t\tTrackingData _td;\r\n\r\n\t\t\t_td = _toolTarget;\r\n\t\t\t_td.quaternion[0] = _newToolQuat.w();\r\n\t\t\t_td.quaternion[1] = _newToolQuat.x();\r\n\t\t\t_td.quaternion[2] = _newToolQuat.y();\r\n\t\t\t_td.quaternion[3] = _newToolQuat.z();\r\n\r\n\t\t\t_td.translation[0] = _newToolTrans.x();\r\n\t\t\t_td.translation[1] = _newToolTrans.y();\r\n\t\t\t_td.translation[2] = _newToolTrans.z();\r\n\r\n\t\t\ttrackingVector.push_back(_td);\r\n\t\t}\r\n\t\tcounter++;\r\n\t}\r\n\r\n\t_file.clear();\r\n\r\n\treturn true;\r\n}\r\n\r\nbool DataTools::getVideoTimestampsFromFile(std::string filename, std::vector<float> &timestampVector)\r\n{\r\n\tstd::fstream _file;\r\n\tint _fileLength;\r\n\r\n\t_file.open(filename.c_str() , std::ios::in);\r\n\r\n\t_file.seekg (0, std::ios::end);\r\n\t_fileLength = _file.tellg();\r\n\t_file.seekg (0, std::ios::beg);\r\n\r\n\tint counter=0;\r\n\twhile(! ( static_cast<int>(_file.tellg()) == -1  || static_cast<int>(_file.tellg()) >= _fileLength ))\r\n\t{\r\n\t\tcounter++;\r\n\t\tfloat tmpTimeStamp;\r\n\t\t\r\n\t\r\n\t\t_file >> tmpTimeStamp;\r\n\r\n\t\t\r\n\t\tif( !_file.fail() ) // avoid the empty line at end of file problem\r\n\t\ttimestampVector.push_back(tmpTimeStamp);\r\n\t\t\t\r\n\t}\r\n\r\n\t\r\n\treturn true;\r\n}\r\n\r\n/* TJK_removed_CAMP:\r\nvoid DataTools::eigen2CAMP(const Eigen::Matrix4f &eigMat, CAMP::Matrix4<float> &campMat)\r\n{\r\n\tfor(int i=0;i<16;i++)\r\n\t{\r\n\t\tcampMat.c_array()[i] = eigMat(i);\r\n\t}\r\n\tcampMat = campMat.transpose();\r\n}\r\n\r\nvoid DataTools::eigen2CAMP(const Eigen::Matrix3f &eigMat, CAMP::Matrix3<float> &campMat)\r\n{\r\n\tfor(int i=0;i<9;i++)\r\n\t{\r\n\t\tcampMat.c_array()[i] = eigMat(i);\r\n\t}\r\n\tcampMat = campMat.transpose();\r\n}\r\n*/\r\n/*void DataTools::eigen2CAMP(const Eigen::Matrix4f &eigMat, CAMP::Matrix4<float> &campMat)\r\n{\r\n\tfor(int i=0;i<16;i++)\r\n\t{\r\n\t\tcampMat.c_array()[i] = eigMat(i);\r\n\t}\r\n\tcampMat = campMat.transpose();\r\n}\r\n\r\nvoid DataTools::eigen2CAMP(const Eigen::Matrix3f &eigMat, CAMP::Matrix3<float> &campMat)\r\n{\r\n\tfor(int i=0;i<9;i++)\r\n\t{\r\n\t\tcampMat.c_array()[i] = eigMat(i);\r\n\t}\r\n\tcampMat = campMat.transpose();\r\n}*/\r\n\r\n/*\r\nvoid DataTools::eigen2CAMP(const Eigen::Matrix3f &eigMat, CAMP::Matrix3<float> &campMat)\r\n{\r\n}\r\n\r\nvoid DataTools::eigen2CAMP(const Eigen::Matrix3f &eigMat, CAMP::Matrix3<float> &ampMat)\r\n{\r\n}*/", "meta": {"hexsha": "cecdf4be04ac06593da2ef6cd96a0eb81368e054", "size": 13425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DataTools.cpp", "max_stars_repo_name": "TJKlein/3D_RFUltrasound_Reconstruction", "max_stars_repo_head_hexsha": "a0afe6f56015cb1b2aa996c3136b77b156c4b105", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T03:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T10:40:59.000Z", "max_issues_repo_path": "DataTools.cpp", "max_issues_repo_name": "huiyugan/3D_RFUltrasound_Reconstruction", "max_issues_repo_head_hexsha": "f64a1c4ef97b4dcc198e5a1badd6f83283705237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DataTools.cpp", "max_forks_repo_name": "huiyugan/3D_RFUltrasound_Reconstruction", "max_forks_repo_head_hexsha": "f64a1c4ef97b4dcc198e5a1badd6f83283705237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-06-02T03:19:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T13:33:32.000Z", "avg_line_length": 28.3227848101, "max_line_length": 263, "alphanum_fraction": 0.6299441341, "num_tokens": 3983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106118322668998, "lm_q2_score": 0.05340332528017579, "lm_q1q2_score": 0.009135236010666676}}
{"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 _ABSTRACTODESYSTEM_HPP_\n#define _ABSTRACTODESYSTEM_HPP_\n\n#include <vector>\n#include <string>\n#include <algorithm>\n\n\n#include \"ChasteSerialization.hpp\"\n#include \"ChasteSerializationVersion.hpp\"\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/vector.hpp>\n#include \"ClassIsAbstract.hpp\"\n\n#include \"AbstractParameterisedSystem.hpp\"\n#include \"Exception.hpp\"\n\n/**\n * Abstract OdeSystem class.\n *\n * Sets up variables and functions for a general ODE system.\n *\n * ODE systems are specified primarily by the EvaluateYDerivatives() method,\n * which calculates the right-hand side of the system.\n *\n * Instances can store their state internally in the mStateVariables vector\n * in our base class AbstractParameterisedSystem (see also\n * GetNumberOfStateVariables(), SetStateVariables() and rGetStateVariables()),\n * although this is not essential - the vector may be empty, in which case\n * AbstractIvpOdeSolver::SolveAndUpdateStateVariable may not be used to\n * solve the system.\n *\n * ODE systems may also have a vector of parameters, which can be accessed\n * through the GetParameter() and SetParameter() methods of our base class.\n *\n * Information about what the parameters and state variables represent is\n * provided by a subclass of AbstractOdeSystemInformation.  Various wrapper\n * methods (e.g. rGetStateVariableNames()) are provided in our base class to\n * access this information.\n *\n * There are two more advanced facilities available for subclass authors.\n * An analytic form for the Jacobian matrix of the system may be provided,\n * in which case you must subclass AbstractOdeSystemWithAnalyticJacobian.\n * The GetUseAnalyticJacobian() method will test whether this is the case.\n *\n * Also, subclasses may define a condition at which ODE solvers should stop\n * prematurely.  For the Chaste solvers this is done by overriding\n * CalculateStoppingEvent(); if the more advanced CVODE solvers are being used\n * then implement CalculateRootFunction() instead to detect the stopping time\n * more accurately.\n */\nclass AbstractOdeSystem : public AbstractParameterisedSystem<std::vector<double> >\n{\n    friend class TestAbstractOdeSystem;\n\nprivate:\n\n\n    friend class boost::serialization::access;\n    /**\n     * Archive the member variables.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template<class Archive>\n    void save(Archive & archive, const unsigned int version) const\n    {\n        // Despite the fact that 3 of these variables actually live in our base class,\n        // we still archive them here to maintain backwards compatibility.\n        // Since the N_Vector version of mStateVariables and mParameters needs converting\n        // to a standard vector before archiving, this doesn't hurt too much.\n        archive & mNumberOfStateVariables;\n        archive & mUseAnalyticJacobian;\n        archive & mStateVariables;\n        archive & mParameters;\n\n        if (version > 0)\n        {\n            archive & rGetParameterNames();\n        }\n\n        // This is always set up by subclass constructors, and is essentially\n        // 'static' data, so shouldn't go in the archive.\n        //archive &mpSystemInfo;\n    }\n    /**\n     * Archive the member variables.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template<class Archive>\n    void load(Archive & archive, const unsigned int version)\n    {\n        archive & mNumberOfStateVariables;\n        archive & mUseAnalyticJacobian;\n        archive & mStateVariables;\n        std::vector<double> parameters;\n        archive & parameters;\n\n        if (version > 0)\n        {\n            std::vector<std::string> param_names;\n            archive & param_names;\n\n            CheckParametersOnLoad(parameters,param_names);\n        }\n        else\n        {\n            mParameters = parameters;\n        }\n    }\n    BOOST_SERIALIZATION_SPLIT_MEMBER()\n\nprotected:\n\n    /** Whether to use an analytic Jacobian. */\n    bool mUseAnalyticJacobian;\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param numberOfStateVariables  the number of state variables in the ODE system\n     */\n    AbstractOdeSystem(unsigned numberOfStateVariables);\n\n    /**\n     * Virtual destructor since we have virtual methods.\n     */\n    virtual ~AbstractOdeSystem();\n\n    /**\n     * Method to evaluate the derivatives of the system.\n     *\n     * @param time  the current time\n     * @param rY  the current values of the state variables\n     * @param rDY  storage for the derivatives of the system; will be filled in on return\n     */\n    virtual void EvaluateYDerivatives(double time, const std::vector<double>& rY,\n                                      std::vector<double>& rDY)=0;\n\n    /**\n     * CalculateStoppingEvent() - can be overloaded if the ODE is to be solved\n     * only until a particular event (for example, only until the y value becomes\n     * negative.\n     *\n     * After each timestep the solver will call this method on the ODE to see if\n     * it should stop there.\n     * @return true if the solver should stop now.  By default, false is returned here.\n     *\n     * @param time  the current time\n     * @param rY  the current values of the state variables\n     */\n    virtual bool CalculateStoppingEvent(double time, const std::vector<double>& rY);\n\n    /**\n     * An alternative approach to stopping events; currently only useful with CVODE.\n     * CVODE can search for roots (zeros) of this function while solving the ODE system,\n     * and home in on them to find sign transitions to high precision.\n     *\n     * The default implementation here fakes a root function using CalculateStoppingEvent.\n     *\n     * @param time  the current time\n     * @param rY  the current values of the state variables\n     * @return value of the root function\n     */\n    virtual double CalculateRootFunction(double time, const std::vector<double>& rY);\n\n    /**\n     * Get whether an analytic Jacobian is used.\n     *\n     * @return #mUseAnalyticJacobian\n     */\n    bool GetUseAnalyticJacobian();\n\n    /**\n     * \\todo move to AbstractParameterisedSystem? (1540)\n     *\n     * @return const reference to the state variables in the ODE system (used in archiving).\n     */\n    const std::vector<double>& rGetConstStateVariables() const;\n};\n\nCLASS_IS_ABSTRACT(AbstractOdeSystem)\nBOOST_CLASS_VERSION(AbstractOdeSystem, 1u)\n\n#endif //_ABSTRACTODESYSTEM_HPP_\n", "meta": {"hexsha": "29cc99d2bb90f0cf38fc04d093bb7f7c165afc97", "size": 8183, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ode/src/common/AbstractOdeSystem.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/common/AbstractOdeSystem.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/common/AbstractOdeSystem.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": 36.2079646018, "max_line_length": 92, "alphanum_fraction": 0.7161187828, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982562649804053, "lm_q2_score": 0.035144843748001434, "lm_q1q2_score": 0.009131531045000215}}
{"text": "//\n// file NotHashedFingerprint.cc\n// David Cosgrove\n// AstraZeneca\n// 3rd February 2009\n//\n\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <sstream>\n\n#include <boost/lexical_cast.hpp>\n\n#include \"ByteSwapper.H\"\n#include \"NotHashedFingerprint.H\"\n\nusing namespace std;\n\nnamespace DAC_FINGERPRINTS {\n\n\n  pNHDC NotHashedFingerprint::dist_calc_ = &NotHashedFingerprint::tanimoto;\n  pNHTDC NotHashedFingerprint::threshold_dist_calc_ =\n    &NotHashedFingerprint::tanimoto;\n  \n  // ****************************************************************************\n  NotHashedFingerprint::NotHashedFingerprint() :\n  FingerprintBase() , num_frag_nums_( 0 ) , frag_nums_( 0 ) {\n\n  }\n\n  // ****************************************************************************\n  NotHashedFingerprint::NotHashedFingerprint( const string &name ) :\n    FingerprintBase( name ) , num_frag_nums_( 0 ) , frag_nums_( 0 ) {\n\n  }\n\n  // ****************************************************************************\n  // from the product of get_string_rep.\n  NotHashedFingerprint::NotHashedFingerprint( const string &name ,\n\t\t\t\t\t      const string &rep ) :\n    FingerprintBase( name ) , num_frag_nums_( 0 ) , frag_nums_( 0 ) {\n\n    vector<uint32_t> tmp_bits;\n    istringstream iss( rep.substr( 4 ) );\n    while( 1 ) {\n      uint32_t next_bit;\n      iss >> next_bit;\n      if( iss.fail() ) {\n\tbreak;\n      }\n      tmp_bits.push_back( next_bit );\n    }\n\n    build_from_vector( tmp_bits );\n\n  }\n\n  // ****************************************************************************\n  NotHashedFingerprint::NotHashedFingerprint( const string &name ,\n\t\t\t\t\t      const std::vector<uint32_t> in_nums ) :\n    FingerprintBase( name ) , num_frag_nums_( 0 ) , frag_nums_( 0 ) {\n    \n    build_from_vector( in_nums );\n\n  }\n\n  // ****************************************************************************\n  NotHashedFingerprint::NotHashedFingerprint( const NotHashedFingerprint &fp ) :\n    FingerprintBase() , num_frag_nums_( 0 ) , frag_nums_( 0 ) {\n\n    copy_data( fp );\n\n  }\n\n  // ****************************************************************************\n  NotHashedFingerprint::~NotHashedFingerprint() {\n\n    delete [] frag_nums_;\n\n  }\n\n  // ****************************************************************************\n  NotHashedFingerprint &NotHashedFingerprint::operator=( const NotHashedFingerprint &fp ) {\n\n    if( this == &fp ) {\n      return *this;\n    }\n\n    copy_data( fp );\n\n    return *this;\n\n  }\n\n  // *******************************************************************************\n  // bitwise operators for combining fingerprints.\n  NotHashedFingerprint NotHashedFingerprint::operator&( const NotHashedFingerprint &rhs ) const {\n\n    NotHashedFingerprint ret_val( \"\" );\n\n    vector<uint32_t> v1( frag_nums_ , frag_nums_ + num_frag_nums_ );\n    sort( v1.begin() , v1.end() );\n\n    vector<uint32_t> v2( rhs.frag_nums_ , rhs.frag_nums_ + rhs.num_frag_nums_ );\n    sort( v2.begin() , v2.end() );\n\n    vector<uint32_t> v1_or_2( num_frag_nums_ + rhs.num_frag_nums_ , 0 );\n    vector<uint32_t>::iterator un_end =\n      set_intersection( v1.begin() , v1.end() , v2.begin() ,\n\t\t\tv2.end() , v1_or_2.begin() );\n\n    delete [] ret_val.frag_nums_;\n    ret_val.num_frag_nums_ = distance( v1_or_2.begin() , un_end );\n    ret_val.frag_nums_ = new uint32_t[ret_val.num_frag_nums_];\n    copy( v1_or_2.begin() , un_end , ret_val.frag_nums_ );\n\n    return ret_val;\n\n  }\n\n  // *******************************************************************************\n  NotHashedFingerprint NotHashedFingerprint::operator|( const NotHashedFingerprint &rhs ) const {\n\n    NotHashedFingerprint ret_val( \"\" );\n\n    vector<uint32_t> v1( frag_nums_ , frag_nums_ + num_frag_nums_ );\n    sort( v1.begin() , v1.end() );\n\n    vector<uint32_t> v2( rhs.frag_nums_ , rhs.frag_nums_ + rhs.num_frag_nums_ );\n    sort( v2.begin() , v2.end() );\n\n    vector<uint32_t> v1_or_2( num_frag_nums_ + rhs.num_frag_nums_ , 0 );\n    vector<uint32_t>::iterator un_end =\n      set_union( v1.begin() , v1.end() , v2.begin() , v2.end() , v1_or_2.begin() );\n\n    delete [] ret_val.frag_nums_;\n    ret_val.num_frag_nums_ = distance( v1_or_2.begin() , un_end );\n    ret_val.frag_nums_ = new uint32_t[ret_val.num_frag_nums_];\n    copy( v1_or_2.begin() , un_end , ret_val.frag_nums_ );\n\n    return ret_val;\n\n  }\n\n  // ****************************************************************************\n  NotHashedFingerprint &NotHashedFingerprint::operator&=( const NotHashedFingerprint &rhs ) {\n\n    vector<uint32_t> v1( frag_nums_ , frag_nums_ + num_frag_nums_ );\n    sort( v1.begin() , v1.end() );\n\n    vector<uint32_t> v2( rhs.frag_nums_ , rhs.frag_nums_ + rhs.num_frag_nums_ );\n    sort( v2.begin() , v2.end() );\n\n    vector<uint32_t> v1_or_2( num_frag_nums_ + rhs.num_frag_nums_ , 0 );\n    vector<uint32_t>::iterator un_end =\n      set_intersection( v1.begin() , v1.end() , v2.begin() , v2.end() ,\n\t\t\tv1_or_2.begin() );\n\n    delete [] frag_nums_;\n    num_frag_nums_ = distance( v1_or_2.begin() , un_end );\n    frag_nums_ = new uint32_t[num_frag_nums_];\n    copy( v1_or_2.begin() , un_end , frag_nums_ );\n\n    return *this;\n\n  }\n\n  // ****************************************************************************\n  NotHashedFingerprint &NotHashedFingerprint::operator|=( const NotHashedFingerprint &rhs ) {\n\n    vector<uint32_t> v1( frag_nums_ , frag_nums_ + num_frag_nums_ );\n    sort( v1.begin() , v1.end() );\n\n    vector<uint32_t> v2( rhs.frag_nums_ , rhs.frag_nums_ + rhs.num_frag_nums_ );\n    sort( v2.begin() , v2.end() );\n\n    vector<uint32_t> v1_or_2( num_frag_nums_ + rhs.num_frag_nums_ , 0 );\n    vector<uint32_t>::iterator un_end =\n      set_union( v1.begin() , v1.end() , v2.begin() , v2.end() , v1_or_2.begin() );\n\n    delete [] frag_nums_;\n    num_frag_nums_ = distance( v1_or_2.begin() , un_end );\n    frag_nums_ = new uint32_t[num_frag_nums_];\n    copy( v1_or_2.begin() , un_end , frag_nums_ );\n\n    return *this;\n\n  }\n\n  // ****************************************************************************\n  double NotHashedFingerprint::tanimoto( const NotHashedFingerprint &fp ) const {\n\n    int num_comm = num_bits_in_common( fp );\n    return( 1.0 - ( double( num_comm ) /\n\t\t    double( num_frag_nums_ + fp.num_frag_nums_ - num_comm ) ) );\n\n  }\n\n  // ****************************************************************************\n  double NotHashedFingerprint::tanimoto( const NotHashedFingerprint &f ,\n\t\t\t\t\t float thresh ) const {\n    \n    float min_dist;\n    if( num_frag_nums_ < f.num_frag_nums_ )\n      min_dist = 1.0 - float( num_frag_nums_ ) / float( f.num_frag_nums_ );\n    else\n      min_dist = 1.0 - float( f.num_frag_nums_ ) / float( num_frag_nums_ );\n    if( min_dist > thresh ) {\n      return 1.0;\n    } else\n      return tanimoto( f );\n\n  }\n\n  // ****************************************************************************\n  double NotHashedFingerprint::tversky( const NotHashedFingerprint &f ) const {\n\n    int num_in_a_not_b , num_in_b_not_a;\n    int num_in_common = num_bits_in_common( f , num_in_a_not_b , num_in_b_not_a );\n    \n    double dist = 1.0 - ( double( num_in_common ) /\n\t\t\t  ( tversky_alpha_ * double( num_in_a_not_b ) +\n\t\t\t    ( 1.0 - tversky_alpha_ ) * double( num_in_b_not_a )\n\t\t\t    + double( num_in_common ) ) ); \n\n    return dist;\n\n  }\n\n  // ****************************************************************************\n  double NotHashedFingerprint::tversky( const NotHashedFingerprint &f ,\n                                        float thresh __attribute__((unused)) ) const {\n\n    return tversky( f );\n\n  }\n\n  // ****************************************************************************\n  void NotHashedFingerprint::binary_write( gzFile fp ) const {\n\n    int name_len = finger_name_.length();\n    gzwrite( fp , reinterpret_cast<char *>( &name_len ) , sizeof( int ) );\n    gzwrite( fp , &finger_name_[0] , name_len );\n\n    gzwrite( fp , reinterpret_cast<const char *>( &num_frag_nums_ ) ,\n\t     sizeof( int ) );\n    gzwrite( fp , reinterpret_cast<const char *>( frag_nums_ ) ,\n\t     num_frag_nums_ * sizeof( uint32_t ) );\n  \n  }\n\n  // ****************************************************************************\n  void NotHashedFingerprint::binary_write( FILE *fp ) const {\n\n    int name_len = finger_name_.length();\n    fwrite( reinterpret_cast<char *>( &name_len ) , sizeof( int ) , 1 , fp );\n    fwrite( &finger_name_[0] , 1 , name_len , fp );\n\n    fwrite( reinterpret_cast<const char *>( &num_frag_nums_ ) , sizeof( int ) ,\n\t    1 , fp );\n    fwrite( reinterpret_cast<const char *>( frag_nums_ ) , sizeof( uint32_t ) ,\n\t    num_frag_nums_ , fp );\n  \n  }\n\n  // ****************************************************************************\n  bool NotHashedFingerprint::binary_read( gzFile fp , bool byte_swapping ) {\n\n    int name_len;\n    gzread( fp , reinterpret_cast<void *>( &name_len ) , sizeof( int ) );\n    if( gzeof( fp ) ) {\n      return false;\n    }\n    if( byte_swapping ) {\n      DACLIB::byte_swapper<int>( name_len );\n    }\n    finger_name_.resize( name_len , ' ' );\n    gzread( fp , reinterpret_cast<void *>( &finger_name_[0] ) , name_len );\n\n    gzread( fp , reinterpret_cast<void *>( &num_frag_nums_ ) , sizeof( int ) );\n    if( byte_swapping ) {\n      DACLIB::byte_swapper<int>( num_frag_nums_ );\n    }\n\n    delete [] frag_nums_;\n    if( num_frag_nums_ ) {\n      frag_nums_ = new uint32_t[num_frag_nums_];\n      gzread( fp , reinterpret_cast<void *>( frag_nums_ ) ,\n\t      num_frag_nums_ * sizeof( uint32_t ) );\n    } else {\n      frag_nums_ = 0;\n    }\n\n    return true;\n\n  }\n\n  // ****************************************************************************\n  bool NotHashedFingerprint::ascii_read( gzFile fp , const string &sep ) {\n\n    // in FingerprintBase.cc\n    string full_line = read_full_line( fp );\n    if( gzeof( fp ) && full_line.empty() ) {\n      return false;\n    }\n\n    full_line = convert_sep_to_new_sep( full_line , sep , \" \" );\n    istringstream iss( full_line );\n    iss >> finger_name_;\n\n    vector<uint32_t> fns;\n    while( 1 ) {\n      uint32_t next_fn;\n      iss >> next_fn;\n      if( iss.fail() ) {\n\tbreak;\n      }\n      fns.push_back( next_fn );\n    }\n\n    build_from_vector( fns );\n\n    return true;\n\n  }\n\n  // ****************************************************************************\n  void NotHashedFingerprint::ascii_write( gzFile fp , const string &sep ) const {\n\n    string act_sep = sep.empty() ? \" \" : sep;\n    gzprintf( fp , \"%s\" , finger_name_.c_str() );\n\n    // cowardly skirting round of the issue of what format string to use for\n    // uint32_t in printf!  There seems to be a buffer size issue here,\n    // strings greater than 4K are being truncated, so write each frag_num_\n    // separately.\n    ostringstream oss;\n    for( int i = 0 ; i < num_frag_nums_ ; ++i ) {\n      oss << act_sep << frag_nums_[i];\n      gzprintf( fp , \"%s\" , oss.str().c_str() );\n      oss.str( \"\" );\n    }\n    gzprintf( fp , \"\\n\" );\n\n  }\n\n  // ****************************************************************************\n  void NotHashedFingerprint::ascii_write( FILE *fp , const string &sep ) const {\n\n    string act_sep = sep.empty() ? \" \" : sep;\n    fprintf( fp , \"%s\" , finger_name_.c_str() );\n    \n    // cowardly skirting round of the issue of what format chars to use for\n    // uint32_t in printf!\n    ostringstream oss;\n    for( int i = 0 ; i < num_frag_nums_ ; ++i ) {\n      oss << act_sep << frag_nums_[i];\n    }\n    fprintf( fp , \"%s\" , oss.str().c_str() );\n    fprintf( fp , \"\\n\" );\n\n  }\n\n  // ****************************************************************************\n  string NotHashedFingerprint::get_string_rep() const {\n\n    ostringstream os;\n    os << \"__FN\";\n    for( int i = 0 ; i < num_frag_nums_ - 1 ; ++i ) {\n      os << frag_nums_[i] << \" \";\n    }\n    if( num_frag_nums_ ) {\n      os << frag_nums_[num_frag_nums_ - 1];\n    }\n\n    return os.str();\n\n  }\n\n  // ****************************************************************************\n  // count the number of bits in common between the fingerprint passed in\n  // and this one\n  int NotHashedFingerprint::num_bits_in_common( const NotHashedFingerprint &fp ) const {\n\n    // both sets of frag_nums are sorted, so can walk through them in sequence\n    uint32_t *these = frag_nums_ , *those = fp.frag_nums_;\n    uint32_t *these_stop = frag_nums_ + num_frag_nums_;\n    uint32_t *those_stop = fp.frag_nums_ + fp.num_frag_nums_;\n    int num_comm = 0;\n    while( these != these_stop && those != those_stop ) {\n      if( *these < *those ) {\n\twhile( these != these_stop && *these < *those ) {\n\t  ++these;\n\t}\n      } else {\n\twhile( those != those_stop && *those < *these ) {\n\t  ++those;\n\t} \n      }\n      if( these == these_stop || those == those_stop ) {\n\tbreak;\n      }\n      if( *these == *those ) {\n\t++num_comm;\n\t++these;\n\t++those;\n      }\n    }\n\n    return num_comm;\n\n  }\n\n  // ****************************************************************************\n  // count the number of bits in common between the fingerprint passed in\n  // and this one\n  int NotHashedFingerprint::num_bits_in_common( const NotHashedFingerprint &fp ,\n\t\t\t\t\t\tint &num_in_a_not_b ,\n\t\t\t\t\t\tint &num_in_b_not_a ) const {\n\n    num_in_a_not_b = num_in_b_not_a = 0;\n\n    // both sets of frag_nums are sorted, so can walk through them in sequence\n    uint32_t *these = frag_nums_ , *those = fp.frag_nums_;\n    uint32_t *these_stop = frag_nums_ + num_frag_nums_;\n    uint32_t *those_stop = fp.frag_nums_ + fp.num_frag_nums_;\n    int num_comm = 0;\n    while( these != these_stop && those != those_stop ) {\n      // move these or those ( whichever has lower value) until they're equal\n      // or one hits the end\n      if( *these < *those ) {\n\twhile( *these < *those ) {\n\t  ++these;\n\t  ++those;\n\t  ++num_in_a_not_b;\n\t}\n      } else {\n\twhile( *those < *these ) {\n\t  ++these;\n\t  ++those;\n\t  ++num_in_b_not_a;\n\t}\n      }\n      if( those == those_stop ) {\n\twhile( these < these_stop ) {\n\t  ++these;\n\t  ++num_in_a_not_b;\n\t}\n\tbreak;\n      } \n      if( these == these_stop ) {\n\twhile( those < those_stop ) {\n\t  ++these;\n\t  ++num_in_b_not_a;\n\t}\n\tbreak;\n      }\n      if( *those == *these ) {\n\t++num_comm;\n      }\n      ++these;\n      ++those;\n    }\n\n    return num_comm;\n\n  }\n\n  // *************************************************************************\n  void NotHashedFingerprint::set_similarity_calc( SIMILARITY_CALC sc ) {\n\n    switch( sc ) {\n      case TANIMOTO :\n\tdist_calc_ = &NotHashedFingerprint::tanimoto;\n\tthreshold_dist_calc_ = &NotHashedFingerprint::tanimoto;\n\tbreak;\n      case TVERSKY :\n\tdist_calc_ = &NotHashedFingerprint::tversky;\n\tthreshold_dist_calc_ = &NotHashedFingerprint::tversky;\n\tbreak;\n    }\n\n  }\n\n  // **************************************************************************\n  // calculate the distance between this fingerprint and the one passed in\n  // using dist_calc_\n  double NotHashedFingerprint::calc_distance( const FingerprintBase &f ) const {\n\n    return f.calc_distance( *this );\n\n  }\n\n  // **************************************************************************\n  // calculate the distance between this fingerprint and the one passed in\n  // using dist_calc_\n  double NotHashedFingerprint::calc_distance( const FingerprintBase &f ,\n\t\t\t\t\t      float threshold ) const {\n\n    return f.calc_distance( *this , threshold );\n\n  }\n\n  // **************************************************************************\n  // calculate the distance between this fingerprint and the one passed in\n  // using dist_calc_\n  double NotHashedFingerprint::calc_distance( const HashedFingerprint &f __attribute__((unused)) ) const {\n    \n    throw IncompatibleFingerprintError( \"calc_distance\" );\n\n  }\n\n  // **************************************************************************\n  // calculate the distance between this fingerprint and the one passed\n  // in using threshold_dist_calc_.  If the distance is predicted to be above\n  // the threshold, return 1.0\n  double NotHashedFingerprint::calc_distance( const HashedFingerprint &f __attribute__((unused)) ,\n                                              float threshold __attribute__((unused)) ) const {\n\n    throw IncompatibleFingerprintError( \"calc_distance\" );\n\n  }\n\n  // ****************************************************************************\n  // calculate the distance between this fingerprint and the one passed in\n  // using dist_calc_\n  double NotHashedFingerprint::calc_distance( const NotHashedFingerprint &f ) const {\n\n    return (this->*dist_calc_)( f );\n\n  }\n\n  // ****************************************************************************\n  // calculate the distance between this fingerprint and the one passed\n  // in using threshold_dist_calc_.  If the distance is predicted to be above\n  // the threshold, return 1.0\n  double NotHashedFingerprint::calc_distance( const NotHashedFingerprint &f ,\n\t\t\t\t\t      float threshold ) const {\n    \n    return (this->*threshold_dist_calc_)( f , threshold );\n  \n  }\n\n  // ****************************************************************************\n  void NotHashedFingerprint::copy_data( const NotHashedFingerprint &fp ) {\n\n    FingerprintBase::copy_data( fp );\n\n    delete [] frag_nums_;\n\n    num_frag_nums_ = fp.num_frag_nums_;\n    if( fp.frag_nums_ && num_frag_nums_ ) {\n      frag_nums_ = new uint32_t[num_frag_nums_];\n      copy( fp.frag_nums_ , fp.frag_nums_ + num_frag_nums_ , frag_nums_ );\n    } else {\n      frag_nums_ = 0;\n    }\n\n  }\n\n  // ****************************************************************************\n  void NotHashedFingerprint::build_from_vector( const vector<uint32_t> &in_nums ) {\n\n    delete [] frag_nums_;\n\n    vector<uint32_t> tmp( in_nums );\n    sort( tmp.begin() , tmp.end() );\n    tmp.erase( unique( tmp.begin() , tmp.end() ) , tmp.end() );\n\n    num_frag_nums_ = tmp.size();\n    if( num_frag_nums_ ) {\n      frag_nums_ = new uint32_t[num_frag_nums_];\n      copy( tmp.begin() , tmp.end() , frag_nums_ );\n    } else {\n      frag_nums_ = 0;\n    }\n\n  }\n\n} // end of namespace DAC_FINGERPRINTS\n", "meta": {"hexsha": "2ccb83e552b5a4df7c97fc26e94c9665a0976394", "size": 17994, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/NotHashedFingerprint.cc", "max_stars_repo_name": "OpenEye-Contrib/Flush", "max_stars_repo_head_hexsha": "71fc76cdf3348006d13d53a26fd0a6e1bc55addd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:06:19.000Z", "max_issues_repo_path": "src/NotHashedFingerprint.cc", "max_issues_repo_name": "OpenEye-Contrib/Flush", "max_issues_repo_head_hexsha": "71fc76cdf3348006d13d53a26fd0a6e1bc55addd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NotHashedFingerprint.cc", "max_forks_repo_name": "OpenEye-Contrib/Flush", "max_forks_repo_head_hexsha": "71fc76cdf3348006d13d53a26fd0a6e1bc55addd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-03-19T21:59:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-31T03:10:50.000Z", "avg_line_length": 30.8644939966, "max_line_length": 106, "alphanum_fraction": 0.5480715794, "num_tokens": 4508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074556640652345, "lm_q2_score": 0.030214587067393977, "lm_q1q2_score": 0.009086903101322619}}
{"text": "// Copyright (c) 2008-2016 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 UUID_E6519754D19211DFB8405F74DFD72085\n#define UUID_E6519754D19211DFB8405F74DFD72085\n\n#include <boost/qvm/assert.hpp>\n#include <boost/qvm/deduce_quat.hpp>\n#include <boost/qvm/detail/quat_assign.hpp>\n#include <boost/qvm/error.hpp>\n#include <boost/qvm/mat_traits.hpp>\n#include <boost/qvm/math.hpp>\n#include <boost/qvm/scalar_traits.hpp>\n#include <boost/qvm/throw_exception.hpp>\n#include <string>\n\nnamespace boost {\nnamespace qvm {\nnamespace qvm_detail {\nBOOST_QVM_INLINE_CRITICAL\nvoid const *get_valid_ptr_quat_operations() {\n  static int const obj = 0;\n  return &obj;\n}\n} // namespace qvm_detail\n\n////////////////////////////////////////////////\n\nnamespace msvc_parse_bug_workaround {\ntemplate <class A, class B> struct quats {\n  static bool const value = is_quat<A>::value && is_quat<B>::value;\n};\n} // namespace msvc_parse_bug_workaround\n\nnamespace qvm_to_string_detail {\ntemplate <class T> std::string to_string(T const &x);\n}\n\ntemplate <class A>\ninline typename boost::enable_if_c<is_quat<A>::value, std::string>::type\nto_string(A const &a) {\n  using namespace qvm_to_string_detail;\n  return '(' + to_string(quat_traits<A>::template read_element<0>(a)) + ',' +\n         to_string(quat_traits<A>::template read_element<1>(a)) + ',' +\n         to_string(quat_traits<A>::template read_element<2>(a)) + ',' +\n         to_string(quat_traits<A>::template read_element<3>(a)) + ')';\n}\n\n////////////////////////////////////////////////\n\ntemplate <class A, class B, class Cmp>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_quat<B>::value, bool>::type\n    cmp(A const &a, B const &b, Cmp f) {\n  typedef typename deduce_scalar<typename quat_traits<A>::scalar_type,\n                                 typename quat_traits<B>::scalar_type>::type T;\n  T q1[4] = {quat_traits<A>::template read_element<0>(a),\n             quat_traits<A>::template read_element<1>(a),\n             quat_traits<A>::template read_element<2>(a),\n             quat_traits<A>::template read_element<3>(a)};\n  T q2[4] = {quat_traits<B>::template read_element<0>(b),\n             quat_traits<B>::template read_element<1>(b),\n             quat_traits<B>::template read_element<2>(b),\n             quat_traits<B>::template read_element<3>(b)};\n  int i;\n  for (i = 0; i != 4; ++i)\n    if (!f(q1[i], q2[i]))\n      break;\n  if (i == 4)\n    return true;\n  for (i = 0; i != 4; ++i)\n    if (!f(q1[i], -q2[i]))\n      return false;\n  return true;\n}\n\n////////////////////////////////////////////////\n\ntemplate <class R, class A>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_quat<R>::value && is_quat<A>::value, R>::type\n    convert_to(A const &a) {\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      quat_traits<A>::template read_element<0>(a);\n  quat_traits<R>::template write_element<1>(r) =\n      quat_traits<A>::template read_element<1>(a);\n  quat_traits<R>::template write_element<2>(r) =\n      quat_traits<A>::template read_element<2>(a);\n  quat_traits<R>::template write_element<3>(r) =\n      quat_traits<A>::template read_element<3>(a);\n  return r;\n}\n\ntemplate <class R, class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<R>::value && is_mat<A>::value &&\n                             mat_traits<A>::rows == 3 &&\n                             mat_traits<A>::cols == 3,\n                         R>::type\n    convert_to(A const &a) {\n  typedef typename mat_traits<A>::scalar_type T;\n  T const mat[3][3] = {{mat_traits<A>::template read_element<0, 0>(a),\n                        mat_traits<A>::template read_element<0, 1>(a),\n                        mat_traits<A>::template read_element<0, 2>(a)},\n                       {mat_traits<A>::template read_element<1, 0>(a),\n                        mat_traits<A>::template read_element<1, 1>(a),\n                        mat_traits<A>::template read_element<1, 2>(a)},\n                       {mat_traits<A>::template read_element<2, 0>(a),\n                        mat_traits<A>::template read_element<2, 1>(a),\n                        mat_traits<A>::template read_element<2, 2>(a)}};\n  R r;\n  if (mat[0][0] + mat[1][1] + mat[2][2] > scalar_traits<T>::value(0)) {\n    T t = mat[0][0] + mat[1][1] + mat[2][2] + scalar_traits<T>::value(1);\n    T s = (scalar_traits<T>::value(1) / sqrt<T>(t)) / 2;\n    quat_traits<R>::template write_element<0>(r) = s * t;\n    quat_traits<R>::template write_element<1>(r) = (mat[2][1] - mat[1][2]) * s;\n    quat_traits<R>::template write_element<2>(r) = (mat[0][2] - mat[2][0]) * s;\n    quat_traits<R>::template write_element<3>(r) = (mat[1][0] - mat[0][1]) * s;\n  } else if (mat[0][0] > mat[1][1] && mat[0][0] > mat[2][2]) {\n    T t = mat[0][0] - mat[1][1] - mat[2][2] + scalar_traits<T>::value(1);\n    T s = (scalar_traits<T>::value(1) / sqrt<T>(t)) / 2;\n    quat_traits<R>::template write_element<0>(r) = (mat[2][1] - mat[1][2]) * s;\n    quat_traits<R>::template write_element<1>(r) = s * t;\n    quat_traits<R>::template write_element<2>(r) = (mat[1][0] + mat[0][1]) * s;\n    quat_traits<R>::template write_element<3>(r) = (mat[0][2] + mat[2][0]) * s;\n  } else if (mat[1][1] > mat[2][2]) {\n    T t = -mat[0][0] + mat[1][1] - mat[2][2] + scalar_traits<T>::value(1);\n    T s = (scalar_traits<T>::value(1) / sqrt<T>(t)) / 2;\n    quat_traits<R>::template write_element<0>(r) = (mat[0][2] - mat[2][0]) * s;\n    quat_traits<R>::template write_element<1>(r) = (mat[1][0] + mat[0][1]) * s;\n    quat_traits<R>::template write_element<2>(r) = s * t;\n    quat_traits<R>::template write_element<3>(r) = (mat[2][1] + mat[1][2]) * s;\n  } else {\n    T t = -mat[0][0] - mat[1][1] + mat[2][2] + scalar_traits<T>::value(1);\n    T s = (scalar_traits<T>::value(1) / sqrt<T>(t)) / 2;\n    quat_traits<R>::template write_element<0>(r) = (mat[1][0] - mat[0][1]) * s;\n    quat_traits<R>::template write_element<1>(r) = (mat[0][2] + mat[2][0]) * s;\n    quat_traits<R>::template write_element<2>(r) = (mat[2][1] + mat[1][2]) * s;\n    quat_traits<R>::template write_element<3>(r) = s * t;\n  }\n  return r;\n}\n\n////////////////////////////////////////////////\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value, deduce_quat<A>>::type\n    conjugate(A const &a) {\n  typedef typename deduce_quat<A>::type R;\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      quat_traits<A>::template read_element<0>(a);\n  quat_traits<R>::template write_element<1>(r) =\n      -quat_traits<A>::template read_element<1>(a);\n  quat_traits<R>::template write_element<2>(r) =\n      -quat_traits<A>::template read_element<2>(a);\n  quat_traits<R>::template write_element<3>(r) =\n      -quat_traits<A>::template read_element<3>(a);\n  return r;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T> class identity_quat_ {\n  identity_quat_(identity_quat_ const &);\n  identity_quat_ &operator=(identity_quat_ const &);\n  ~identity_quat_();\n\npublic:\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class T> struct quat_traits<qvm_detail::identity_quat_<T>> {\n  typedef qvm_detail::identity_quat_<T> this_quaternion;\n  typedef T scalar_type;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return scalar_traits<T>::value(I == 0);\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_quaternion const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < 4);\n    return scalar_traits<T>::value(i == 0);\n  }\n};\n\ntemplate <class T> struct deduce_quat<qvm_detail::identity_quat_<T>> {\n  typedef quat<T> type;\n};\n\ntemplate <class T>\nstruct deduce_quat2<qvm_detail::identity_quat_<T>,\n                    qvm_detail::identity_quat_<T>> {\n  typedef quat<T> type;\n};\n\ntemplate <class T>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::identity_quat_<T> const &identity_quat() {\n  return *(qvm_detail::identity_quat_<T> const *)\n      qvm_detail::get_valid_ptr_quat_operations();\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nset_identity(A &a) {\n  typedef typename quat_traits<A>::scalar_type T;\n  T const zero = scalar_traits<T>::value(0);\n  T const one = scalar_traits<T>::value(1);\n  quat_traits<A>::template write_element<0>(a) = one;\n  quat_traits<A>::template write_element<1>(a) = zero;\n  quat_traits<A>::template write_element<2>(a) = zero;\n  quat_traits<A>::template write_element<3>(a) = zero;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalType, class Scalar> class quaternion_scalar_cast_ {\n  quaternion_scalar_cast_(quaternion_scalar_cast_ const &);\n  quaternion_scalar_cast_ &operator=(quaternion_scalar_cast_ const &);\n  ~quaternion_scalar_cast_();\n\npublic:\n  template <class T>\n  BOOST_QVM_INLINE_TRIVIAL quaternion_scalar_cast_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n\ntemplate <bool> struct scalar_cast_quaternion_filter {};\ntemplate <> struct scalar_cast_quaternion_filter<true> { typedef int type; };\n} // namespace qvm_detail\n\ntemplate <class OriginalType, class Scalar>\nstruct quat_traits<qvm_detail::quaternion_scalar_cast_<OriginalType, Scalar>> {\n  typedef Scalar scalar_type;\n  typedef qvm_detail::quaternion_scalar_cast_<OriginalType, Scalar>\n      this_quaternion;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return scalar_type(quat_traits<OriginalType>::template read_element<I>(\n        reinterpret_cast<OriginalType const &>(x)));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_quaternion const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < 4);\n    return scalar_type(quat_traits<OriginalType>::read_element_idx(\n        i, reinterpret_cast<OriginalType const &>(x)));\n  }\n};\n\ntemplate <class Scalar, class T>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::quaternion_scalar_cast_<T, Scalar> const &\nscalar_cast(T const &x, typename qvm_detail::scalar_cast_quaternion_filter<\n                            is_quat<T>::value>::type = 0) {\n  return reinterpret_cast<\n      qvm_detail::quaternion_scalar_cast_<T, Scalar> const &>(x);\n}\n\n////////////////////////////////////////////////\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_scalar<B>::value, A &>::type\n    operator/=(A &a, B b) {\n  quat_traits<A>::template write_element<0>(a) /= b;\n  quat_traits<A>::template write_element<1>(a) /= b;\n  quat_traits<A>::template write_element<2>(a) /= b;\n  quat_traits<A>::template write_element<3>(a) /= b;\n  return a;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value && is_scalar<B>::value,\n                              deduce_quat<A>>::type\n    operator/(A const &a, B b) {\n  typedef typename deduce_quat<A>::type R;\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      quat_traits<A>::template read_element<0>(a) / b;\n  quat_traits<R>::template write_element<1>(r) =\n      quat_traits<A>::template read_element<1>(a) / b;\n  quat_traits<R>::template write_element<2>(r) =\n      quat_traits<A>::template read_element<2>(a) / b;\n  quat_traits<R>::template write_element<3>(r) =\n      quat_traits<A>::template read_element<3>(a) / b;\n  return r;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c<\n    is_quat<A>::value && is_quat<B>::value,\n    deduce_scalar<typename quat_traits<A>::scalar_type,\n                  typename quat_traits<B>::scalar_type>>::type\ndot(A const &a, B const &b) {\n  typedef typename quat_traits<A>::scalar_type Ta;\n  typedef typename quat_traits<B>::scalar_type Tb;\n  typedef typename deduce_scalar<Ta, Tb>::type Tr;\n  Ta const a0 = quat_traits<A>::template read_element<0>(a);\n  Ta const a1 = quat_traits<A>::template read_element<1>(a);\n  Ta const a2 = quat_traits<A>::template read_element<2>(a);\n  Ta const a3 = quat_traits<A>::template read_element<3>(a);\n  Tb const b0 = quat_traits<B>::template read_element<0>(b);\n  Tb const b1 = quat_traits<B>::template read_element<1>(b);\n  Tb const b2 = quat_traits<B>::template read_element<2>(b);\n  Tb const b3 = quat_traits<B>::template read_element<3>(b);\n  Tr const dp = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3;\n  return dp;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_quat<B>::value, bool>::type\n    operator==(A const &a, B const &b) {\n  return quat_traits<A>::template read_element<0>(a) ==\n             quat_traits<B>::template read_element<0>(b) &&\n         quat_traits<A>::template read_element<1>(a) ==\n             quat_traits<B>::template read_element<1>(b) &&\n         quat_traits<A>::template read_element<2>(a) ==\n             quat_traits<B>::template read_element<2>(b) &&\n         quat_traits<A>::template read_element<3>(a) ==\n             quat_traits<B>::template read_element<3>(b);\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value, deduce_quat<A>>::type\n    inverse(A const &a) {\n  typedef typename deduce_quat<A>::type R;\n  typedef typename quat_traits<A>::scalar_type TA;\n  TA aa = quat_traits<A>::template read_element<0>(a);\n  TA ab = quat_traits<A>::template read_element<1>(a);\n  TA ac = quat_traits<A>::template read_element<2>(a);\n  TA ad = quat_traits<A>::template read_element<3>(a);\n  TA m2 = ab * ab + ac * ac + ad * ad + aa * aa;\n  if (m2 == scalar_traits<TA>::value(0))\n    BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n  TA rm = scalar_traits<TA>::value(1) / m2;\n  R r;\n  quat_traits<R>::template write_element<0>(r) = aa * rm;\n  quat_traits<R>::template write_element<1>(r) = -ab * rm;\n  quat_traits<R>::template write_element<2>(r) = -ac * rm;\n  quat_traits<R>::template write_element<3>(r) = -ad * rm;\n  return r;\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value,\n                         typename quat_traits<A>::scalar_type>::type\n    mag_sqr(A const &a) {\n  typedef typename quat_traits<A>::scalar_type T;\n  T x = quat_traits<A>::template read_element<0>(a);\n  T y = quat_traits<A>::template read_element<1>(a);\n  T z = quat_traits<A>::template read_element<2>(a);\n  T w = quat_traits<A>::template read_element<3>(a);\n  return x * x + y * y + z * z + w * w;\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value,\n                         typename quat_traits<A>::scalar_type>::type\n    mag(A const &a) {\n  typedef typename quat_traits<A>::scalar_type T;\n  T x = quat_traits<A>::template read_element<0>(a);\n  T y = quat_traits<A>::template read_element<1>(a);\n  T z = quat_traits<A>::template read_element<2>(a);\n  T w = quat_traits<A>::template read_element<3>(a);\n  return sqrt<T>(x * x + y * y + z * z + w * w);\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if<msvc_parse_bug_workaround::quats<A, B>, A &>::type\n    operator-=(A &a, B const &b) {\n  quat_traits<A>::template write_element<0>(a) -=\n      quat_traits<B>::template read_element<0>(b);\n  quat_traits<A>::template write_element<1>(a) -=\n      quat_traits<B>::template read_element<1>(b);\n  quat_traits<A>::template write_element<2>(a) -=\n      quat_traits<B>::template read_element<2>(b);\n  quat_traits<A>::template write_element<3>(a) -=\n      quat_traits<B>::template read_element<3>(b);\n  return a;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value && is_quat<B>::value,\n                              deduce_quat2<A, B>>::type\n    operator-(A const &a, B const &b) {\n  typedef typename deduce_quat2<A, B>::type R;\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      quat_traits<A>::template read_element<0>(a) -\n      quat_traits<B>::template read_element<0>(b);\n  quat_traits<R>::template write_element<1>(r) =\n      quat_traits<A>::template read_element<1>(a) -\n      quat_traits<B>::template read_element<1>(b);\n  quat_traits<R>::template write_element<2>(r) =\n      quat_traits<A>::template read_element<2>(a) -\n      quat_traits<B>::template read_element<2>(b);\n  quat_traits<R>::template write_element<3>(r) =\n      quat_traits<A>::template read_element<3>(a) -\n      quat_traits<B>::template read_element<3>(b);\n  return r;\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value, deduce_quat<A>>::type\n    operator-(A const &a) {\n  typedef typename deduce_quat<A>::type R;\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      -quat_traits<A>::template read_element<0>(a);\n  quat_traits<R>::template write_element<1>(r) =\n      -quat_traits<A>::template read_element<1>(a);\n  quat_traits<R>::template write_element<2>(r) =\n      -quat_traits<A>::template read_element<2>(a);\n  quat_traits<R>::template write_element<3>(r) =\n      -quat_traits<A>::template read_element<3>(a);\n  return r;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if<msvc_parse_bug_workaround::quats<A, B>, A &>::type\n    operator*=(A &a, B const &b) {\n  typedef typename quat_traits<A>::scalar_type TA;\n  typedef typename quat_traits<B>::scalar_type TB;\n  TA const aa = quat_traits<A>::template read_element<0>(a);\n  TA const ab = quat_traits<A>::template read_element<1>(a);\n  TA const ac = quat_traits<A>::template read_element<2>(a);\n  TA const ad = quat_traits<A>::template read_element<3>(a);\n  TB const ba = quat_traits<B>::template read_element<0>(b);\n  TB const bb = quat_traits<B>::template read_element<1>(b);\n  TB const bc = quat_traits<B>::template read_element<2>(b);\n  TB const bd = quat_traits<B>::template read_element<3>(b);\n  quat_traits<A>::template write_element<0>(a) =\n      aa * ba - ab * bb - ac * bc - ad * bd;\n  quat_traits<A>::template write_element<1>(a) =\n      aa * bb + ab * ba + ac * bd - ad * bc;\n  quat_traits<A>::template write_element<2>(a) =\n      aa * bc + ac * ba + ad * bb - ab * bd;\n  quat_traits<A>::template write_element<3>(a) =\n      aa * bd + ad * ba + ab * bc - ac * bb;\n  return a;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_scalar<B>::value, A &>::type\n    operator*=(A &a, B b) {\n  quat_traits<A>::template write_element<0>(a) *= b;\n  quat_traits<A>::template write_element<1>(a) *= b;\n  quat_traits<A>::template write_element<2>(a) *= b;\n  quat_traits<A>::template write_element<3>(a) *= b;\n  return a;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value && is_quat<B>::value,\n                              deduce_quat2<A, B>>::type\n    operator*(A const &a, B const &b) {\n  typedef typename deduce_quat2<A, B>::type R;\n  typedef typename quat_traits<A>::scalar_type TA;\n  typedef typename quat_traits<B>::scalar_type TB;\n  TA const aa = quat_traits<A>::template read_element<0>(a);\n  TA const ab = quat_traits<A>::template read_element<1>(a);\n  TA const ac = quat_traits<A>::template read_element<2>(a);\n  TA const ad = quat_traits<A>::template read_element<3>(a);\n  TB const ba = quat_traits<B>::template read_element<0>(b);\n  TB const bb = quat_traits<B>::template read_element<1>(b);\n  TB const bc = quat_traits<B>::template read_element<2>(b);\n  TB const bd = quat_traits<B>::template read_element<3>(b);\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      aa * ba - ab * bb - ac * bc - ad * bd;\n  quat_traits<R>::template write_element<1>(r) =\n      aa * bb + ab * ba + ac * bd - ad * bc;\n  quat_traits<R>::template write_element<2>(r) =\n      aa * bc + ac * ba + ad * bb - ab * bd;\n  quat_traits<R>::template write_element<3>(r) =\n      aa * bd + ad * ba + ab * bc - ac * bb;\n  return r;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value && is_scalar<B>::value,\n                              deduce_quat<A>>::type\n    operator*(A const &a, B b) {\n  typedef typename deduce_quat<A>::type R;\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      quat_traits<A>::template read_element<0>(a) * b;\n  quat_traits<R>::template write_element<1>(r) =\n      quat_traits<A>::template read_element<1>(a) * b;\n  quat_traits<R>::template write_element<2>(r) =\n      quat_traits<A>::template read_element<2>(a) * b;\n  quat_traits<R>::template write_element<3>(r) =\n      quat_traits<A>::template read_element<3>(a) * b;\n  return r;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_quat<B>::value, bool>::type\n    operator!=(A const &a, B const &b) {\n  return quat_traits<A>::template read_element<0>(a) !=\n             quat_traits<B>::template read_element<0>(b) ||\n         quat_traits<A>::template read_element<1>(a) !=\n             quat_traits<B>::template read_element<1>(b) ||\n         quat_traits<A>::template read_element<2>(a) !=\n             quat_traits<B>::template read_element<2>(b) ||\n         quat_traits<A>::template read_element<3>(a) !=\n             quat_traits<B>::template read_element<3>(b);\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value, deduce_quat<A>>::type\n    normalized(A const &a) {\n  typedef typename quat_traits<A>::scalar_type T;\n  T const a0 = quat_traits<A>::template read_element<0>(a);\n  T const a1 = quat_traits<A>::template read_element<1>(a);\n  T const a2 = quat_traits<A>::template read_element<2>(a);\n  T const a3 = quat_traits<A>::template read_element<3>(a);\n  T const m2 = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n  if (m2 == scalar_traits<typename quat_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_quat<A>::type R;\n  R r;\n  quat_traits<R>::template write_element<0>(r) = a0 * rm;\n  quat_traits<R>::template write_element<1>(r) = a1 * rm;\n  quat_traits<R>::template write_element<2>(r) = a2 * rm;\n  quat_traits<R>::template write_element<3>(r) = a3 * rm;\n  return r;\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nnormalize(A &a) {\n  typedef typename quat_traits<A>::scalar_type T;\n  T const a0 = quat_traits<A>::template read_element<0>(a);\n  T const a1 = quat_traits<A>::template read_element<1>(a);\n  T const a2 = quat_traits<A>::template read_element<2>(a);\n  T const a3 = quat_traits<A>::template read_element<3>(a);\n  T const m2 = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n  if (m2 == scalar_traits<typename quat_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  quat_traits<A>::template write_element<0>(a) *= rm;\n  quat_traits<A>::template write_element<1>(a) *= rm;\n  quat_traits<A>::template write_element<2>(a) *= rm;\n  quat_traits<A>::template write_element<3>(a) *= rm;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if<msvc_parse_bug_workaround::quats<A, B>, A &>::type\n    operator+=(A &a, B const &b) {\n  quat_traits<A>::template write_element<0>(a) +=\n      quat_traits<B>::template read_element<0>(b);\n  quat_traits<A>::template write_element<1>(a) +=\n      quat_traits<B>::template read_element<1>(b);\n  quat_traits<A>::template write_element<2>(a) +=\n      quat_traits<B>::template read_element<2>(b);\n  quat_traits<A>::template write_element<3>(a) +=\n      quat_traits<B>::template read_element<3>(b);\n  return a;\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value && is_quat<B>::value,\n                              deduce_quat2<A, B>>::type\n    operator+(A const &a, B const &b) {\n  typedef typename deduce_quat2<A, B>::type R;\n  R r;\n  quat_traits<R>::template write_element<0>(r) =\n      quat_traits<A>::template read_element<0>(a) +\n      quat_traits<B>::template read_element<0>(b);\n  quat_traits<R>::template write_element<1>(r) =\n      quat_traits<A>::template read_element<1>(a) +\n      quat_traits<B>::template read_element<1>(b);\n  quat_traits<R>::template write_element<2>(r) =\n      quat_traits<A>::template read_element<2>(a) +\n      quat_traits<B>::template read_element<2>(b);\n  quat_traits<R>::template write_element<3>(r) =\n      quat_traits<A>::template read_element<3>(a) +\n      quat_traits<B>::template read_element<3>(b);\n  return r;\n}\n\ntemplate <class A, class B, class C>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<is_quat<A>::value && is_quat<B>::value &&\n                                  is_scalar<C>::value,\n                              deduce_quat2<A, B>>::type\n    slerp(A const &a, B const &b, C t) {\n  typedef typename deduce_quat2<A, B>::type R;\n  typedef typename quat_traits<R>::scalar_type TR;\n  TR const one = scalar_traits<TR>::value(1);\n  TR dp = dot(a, b);\n  TR sc = one;\n  if (dp < one) {\n    TR const theta = acos<TR>(dp);\n    TR const invsintheta = one / sin<TR>(theta);\n    TR const scale = sin<TR>(theta * (one - t)) * invsintheta;\n    TR const invscale = sin<TR>(theta * t) * invsintheta * sc;\n    return a * scale + b * invscale;\n  } else\n    return normalized(a + (b - a) * t);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T> class qref_ {\n  qref_(qref_ const &);\n  qref_ &operator=(qref_ const &);\n  ~qref_();\n\npublic:\n  template <class R> BOOST_QVM_INLINE_TRIVIAL qref_ &operator=(R const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class Q> struct quat_traits;\n\ntemplate <class Q> struct quat_traits<qvm_detail::qref_<Q>> {\n  typedef typename quat_traits<Q>::scalar_type scalar_type;\n  typedef qvm_detail::qref_<Q> this_quaternion;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return quat_traits<Q>::template read_element<I>(\n        reinterpret_cast<Q const &>(x));\n  }\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element(this_quaternion &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return quat_traits<Q>::template write_element<I>(reinterpret_cast<Q &>(x));\n  }\n};\n\ntemplate <class Q> struct deduce_quat<qvm_detail::qref_<Q>> {\n  typedef quat<typename quat_traits<Q>::scalar_type> type;\n};\n\ntemplate <class Q>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_quat<Q>::value, qvm_detail::qref_<Q> const &>::type\n    qref(Q const &a) {\n  return reinterpret_cast<qvm_detail::qref_<Q> const &>(a);\n}\n\ntemplate <class Q>\nBOOST_QVM_INLINE_TRIVIAL\n    typename enable_if_c<is_quat<Q>::value, qvm_detail::qref_<Q> &>::type\n    qref(Q &a) {\n  return reinterpret_cast<qvm_detail::qref_<Q> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T> class zero_q_ {\n  zero_q_(zero_q_ const &);\n  zero_q_ &operator=(zero_q_ const &);\n  ~zero_q_();\n\npublic:\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class T> struct quat_traits<qvm_detail::zero_q_<T>> {\n  typedef qvm_detail::zero_q_<T> this_quaternion;\n  typedef T scalar_type;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return scalar_traits<scalar_type>::value(0);\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int i, this_quaternion const &x) {\n    BOOST_QVM_ASSERT(i >= 0);\n    BOOST_QVM_ASSERT(i < 4);\n    return scalar_traits<scalar_type>::value(0);\n  }\n};\n\ntemplate <class T>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::zero_q_<T> const &zero_quat() {\n  return *(qvm_detail::zero_q_<T> const *)\n      qvm_detail::get_valid_ptr_quat_operations();\n}\n\ntemplate <class A>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nset_zero(A &a) {\n  typedef typename quat_traits<A>::scalar_type T;\n  T const zero = scalar_traits<T>::value(0);\n  quat_traits<A>::template write_element<0>(a) = zero;\n  quat_traits<A>::template write_element<1>(a) = zero;\n  quat_traits<A>::template write_element<2>(a) = zero;\n  quat_traits<A>::template write_element<3>(a) = zero;\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class V> struct rot_quat_ {\n  typedef typename vec_traits<V>::scalar_type scalar_type;\n  scalar_type a[4];\n\n  template <class Angle>\n  BOOST_QVM_INLINE rot_quat_(V const &axis, Angle angle) {\n    scalar_type const x = vec_traits<V>::template read_element<0>(axis);\n    scalar_type const y = vec_traits<V>::template read_element<1>(axis);\n    scalar_type const z = vec_traits<V>::template read_element<2>(axis);\n    scalar_type const m2 = x * x + y * y + z * z;\n    if (m2 == scalar_traits<scalar_type>::value(0))\n      BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n    scalar_type const rm =\n        scalar_traits<scalar_type>::value(1) / sqrt<scalar_type>(m2);\n    angle /= 2;\n    scalar_type const s = sin<Angle>(angle);\n    a[0] = cos<Angle>(angle);\n    a[1] = rm * x * s;\n    a[2] = rm * y * s;\n    a[3] = rm * z * s;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class V> struct quat_traits<qvm_detail::rot_quat_<V>> {\n  typedef qvm_detail::rot_quat_<V> this_quaternion;\n  typedef typename this_quaternion::scalar_type scalar_type;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return x.a[I];\n  }\n};\n\ntemplate <class V> struct deduce_quat<qvm_detail::rot_quat_<V>> {\n  typedef quat<typename vec_traits<V>::scalar_type> type;\n};\n\ntemplate <class A, class Angle>\nBOOST_QVM_INLINE\n    typename enable_if_c<is_vec<A>::value && vec_traits<A>::dim == 3,\n                         qvm_detail::rot_quat_<A>>::type\n    rot_quat(A const &axis, Angle angle) {\n  return qvm_detail::rot_quat_<A>(axis, angle);\n}\n\ntemplate <class A, class B, class Angle>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_vec<B>::value &&\n                             vec_traits<B>::dim == 3,\n                         void>::type\n    set_rot(A &a, B const &axis, Angle angle) {\n  assign(a, rot_quat(axis, angle));\n}\n\ntemplate <class A, class B, class Angle>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_vec<B>::value &&\n                             vec_traits<B>::dim == 3,\n                         void>::type\n    rotate(A &a, B const &axis, Angle angle) {\n  a *= rot_quat(axis, angle);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T> struct rotx_quat_ {\n  BOOST_QVM_INLINE_TRIVIAL\n  rotx_quat_() {}\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n\nprivate:\n  rotx_quat_(rotx_quat_ const &);\n  rotx_quat_ &operator=(rotx_quat_ const &);\n  ~rotx_quat_();\n};\n\ntemplate <int I> struct rotx_q_get {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &) {\n    return scalar_traits<T>::value(0);\n  }\n};\n\ntemplate <> struct rotx_q_get<1> {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &angle) {\n    return sin<T>(angle / 2);\n  }\n};\n\ntemplate <> struct rotx_q_get<0> {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &angle) {\n    return cos<T>(angle / 2);\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class Angle> struct quat_traits<qvm_detail::rotx_quat_<Angle>> {\n  typedef qvm_detail::rotx_quat_<Angle> this_quaternion;\n  typedef Angle scalar_type;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return qvm_detail::rotx_q_get<I>::get(reinterpret_cast<Angle const &>(x));\n  }\n};\n\ntemplate <class Angle> struct deduce_quat<qvm_detail::rotx_quat_<Angle>> {\n  typedef quat<Angle> type;\n};\n\ntemplate <class Angle>\nstruct deduce_quat2<qvm_detail::rotx_quat_<Angle>,\n                    qvm_detail::rotx_quat_<Angle>> {\n  typedef quat<Angle> type;\n};\n\ntemplate <class Angle>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::rotx_quat_<Angle> const &\nrotx_quat(Angle const &angle) {\n  return reinterpret_cast<qvm_detail::rotx_quat_<Angle> const &>(angle);\n}\n\ntemplate <class A, class Angle>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nset_rotx(A &a, Angle angle) {\n  assign(a, rotx_quat(angle));\n}\n\ntemplate <class A, class Angle>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nrotate_x(A &a, Angle angle) {\n  a *= rotx_quat(angle);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T> struct roty_quat_ {\n  BOOST_QVM_INLINE_TRIVIAL\n  roty_quat_() {}\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n\nprivate:\n  roty_quat_(roty_quat_ const &);\n  roty_quat_ &operator=(roty_quat_ const &);\n  ~roty_quat_();\n};\n\ntemplate <int I> struct roty_q_get {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &) {\n    return scalar_traits<T>::value(0);\n  }\n};\n\ntemplate <> struct roty_q_get<2> {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &angle) {\n    return sin<T>(angle / 2);\n  }\n};\n\ntemplate <> struct roty_q_get<0> {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &angle) {\n    return cos<T>(angle / 2);\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class Angle> struct quat_traits<qvm_detail::roty_quat_<Angle>> {\n  typedef qvm_detail::roty_quat_<Angle> this_quaternion;\n  typedef Angle scalar_type;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return qvm_detail::roty_q_get<I>::get(reinterpret_cast<Angle const &>(x));\n  }\n};\n\ntemplate <class Angle> struct deduce_quat<qvm_detail::roty_quat_<Angle>> {\n  typedef quat<Angle> type;\n};\n\ntemplate <class Angle>\nstruct deduce_quat2<qvm_detail::roty_quat_<Angle>,\n                    qvm_detail::roty_quat_<Angle>> {\n  typedef quat<Angle> type;\n};\n\ntemplate <class Angle>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::roty_quat_<Angle> const &\nroty_quat(Angle const &angle) {\n  return reinterpret_cast<qvm_detail::roty_quat_<Angle> const &>(angle);\n}\n\ntemplate <class A, class Angle>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nset_roty(A &a, Angle angle) {\n  assign(a, roty_quat(angle));\n}\n\ntemplate <class A, class Angle>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nrotate_y(A &a, Angle angle) {\n  a *= roty_quat(angle);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class T> struct rotz_quat_ {\n  BOOST_QVM_INLINE_TRIVIAL\n  rotz_quat_() {}\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n\nprivate:\n  rotz_quat_(rotz_quat_ const &);\n  rotz_quat_ &operator=(rotz_quat_ const &);\n  ~rotz_quat_();\n};\n\ntemplate <int I> struct rotz_q_get {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &) {\n    return scalar_traits<T>::value(0);\n  }\n};\n\ntemplate <> struct rotz_q_get<3> {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &angle) {\n    return sin<T>(angle / 2);\n  }\n};\n\ntemplate <> struct rotz_q_get<0> {\n  template <class T> static BOOST_QVM_INLINE_CRITICAL T get(T const &angle) {\n    return cos<T>(angle / 2);\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class Angle> struct quat_traits<qvm_detail::rotz_quat_<Angle>> {\n  typedef qvm_detail::rotz_quat_<Angle> this_quaternion;\n  typedef Angle scalar_type;\n\n  template <int I>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_quaternion const &x) {\n    BOOST_QVM_STATIC_ASSERT(I >= 0);\n    BOOST_QVM_STATIC_ASSERT(I < 4);\n    return qvm_detail::rotz_q_get<I>::get(reinterpret_cast<Angle const &>(x));\n  }\n};\n\ntemplate <class Angle> struct deduce_quat<qvm_detail::rotz_quat_<Angle>> {\n  typedef quat<Angle> type;\n};\n\ntemplate <class Angle>\nstruct deduce_quat2<qvm_detail::rotz_quat_<Angle>,\n                    qvm_detail::rotz_quat_<Angle>> {\n  typedef quat<Angle> type;\n};\n\ntemplate <class Angle>\nBOOST_QVM_INLINE_TRIVIAL qvm_detail::rotz_quat_<Angle> const &\nrotz_quat(Angle const &angle) {\n  return reinterpret_cast<qvm_detail::rotz_quat_<Angle> const &>(angle);\n}\n\ntemplate <class A, class Angle>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nset_rotz(A &a, Angle angle) {\n  assign(a, rotz_quat(angle));\n}\n\ntemplate <class A, class Angle>\nBOOST_QVM_INLINE_OPERATIONS typename enable_if_c<is_quat<A>::value, void>::type\nrotate_z(A &a, Angle angle) {\n  a *= rotz_quat(angle);\n}\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename enable_if_c<is_quat<A>::value && is_vec<B>::value &&\n                             vec_traits<B>::dim == 3,\n                         typename quat_traits<A>::scalar_type>::type\n    axis_angle(A const &a, B &b) {\n  typedef typename quat_traits<A>::scalar_type T;\n  T a0 = quat_traits<A>::template read_element<0>(a);\n  T a1 = quat_traits<A>::template read_element<1>(a);\n  T a2 = quat_traits<A>::template read_element<2>(a);\n  T a3 = quat_traits<A>::template read_element<3>(a);\n  if (a0 > 1) {\n    T const m2 = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n    if (m2 == scalar_traits<T>::value(0))\n      BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\n    T const s = sqrt<T>(m2);\n    a0 /= s;\n    a1 /= s;\n    a2 /= s;\n    a3 /= s;\n  }\n  if (T s = sqrt<T>(1 - a0 * a0)) {\n    vec_traits<B>::template write_element<0>(b) = a1 / s;\n    vec_traits<B>::template write_element<1>(b) = a2 / s;\n    vec_traits<B>::template write_element<2>(b) = a3 / s;\n  } else {\n    typedef typename vec_traits<B>::scalar_type U;\n    vec_traits<B>::template write_element<0>(b) = scalar_traits<U>::value(1);\n    vec_traits<B>::template write_element<1>(b) =\n        vec_traits<B>::template write_element<2>(b) =\n            scalar_traits<U>::value(0);\n  }\n  return scalar_traits<T>::value(2) * qvm::acos(a0);\n}\n\n////////////////////////////////////////////////\n\nnamespace sfinae {\nusing ::boost::qvm::assign;\nusing ::boost::qvm::cmp;\nusing ::boost::qvm::conjugate;\nusing ::boost::qvm::convert_to;\nusing ::boost::qvm::scalar_cast;\nusing ::boost::qvm::set_identity;\nusing ::boost::qvm::set_zero;\nusing ::boost::qvm::operator/=;\nusing ::boost::qvm::operator/;\nusing ::boost::qvm::dot;\nusing ::boost::qvm::operator==;\nusing ::boost::qvm::inverse;\nusing ::boost::qvm::mag;\nusing ::boost::qvm::mag_sqr;\nusing ::boost::qvm::slerp;\nusing ::boost::qvm::operator-=;\nusing ::boost::qvm::operator-;\nusing ::boost::qvm::operator*=;\nusing ::boost::qvm::operator*;\nusing ::boost::qvm::operator!=;\nusing ::boost::qvm::normalize;\nusing ::boost::qvm::normalized;\nusing ::boost::qvm::operator+=;\nusing ::boost::qvm::operator+;\nusing ::boost::qvm::qref;\nusing ::boost::qvm::rot_quat;\nusing ::boost::qvm::rotate;\nusing ::boost::qvm::rotate_x;\nusing ::boost::qvm::rotate_y;\nusing ::boost::qvm::rotate_z;\nusing ::boost::qvm::rotx_quat;\nusing ::boost::qvm::roty_quat;\nusing ::boost::qvm::rotz_quat;\nusing ::boost::qvm::set_rot;\nusing ::boost::qvm::set_rotx;\nusing ::boost::qvm::set_roty;\nusing ::boost::qvm::set_rotz;\n} // namespace sfinae\n\n////////////////////////////////////////////////\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "63cda83c0a9a5e762951b187ad5c33a0ed045e5d", "size": 40455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/quat_operations.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/quat_operations.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/quat_operations.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": 34.7551546392, "max_line_length": 79, "alphanum_fraction": 0.6594240514, "num_tokens": 11627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.024053554905801865, "lm_q1q2_score": 0.009081195206109349}}
{"text": "/* Copyright (c) 2016, Jakob Engel\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 contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"FOVUndistorter.h\"\n\n#include <Eigen/Core>\n#include <fstream>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n#include <sstream>\n\nUndistorterFOV::UndistorterFOV() {\n  remapX = nullptr;\n  remapY = nullptr;\n  valid = false;\n}\n\nUndistorterFOV::UndistorterFOV(const char* configFileName) {\n  remapX = nullptr;\n  remapY = nullptr;\n  valid = false;\n\n  // read parameters\n  std::ifstream infile(configFileName);\n  if (!infile.good()) {\n    printf(\n        \"Failed to read camera calibration (invalid format?)\\nCalibration \"\n        \"file: %s\\n\",\n        configFileName);\n    return;\n  }\n\n  std::string l1, l2, l3, l4;\n  std::getline(infile, l1);\n  std::getline(infile, l2);\n  std::getline(infile, l3);\n  std::getline(infile, l4);\n\n  // l1 & l2\n  if (std::sscanf(l1.c_str(), \"%f %f %f %f %f\", &inputCalibration[0],\n                  &inputCalibration[1], &inputCalibration[2],\n                  &inputCalibration[3], &inputCalibration[4]) == 5 &&\n      std::sscanf(l2.c_str(), \"%d %d\", &in_width, &in_height) == 2) {\n    printf(\"Input resolution: %d %d\\n\", in_width, in_height);\n    printf(\"Input Calibration (fx fy cx cy): %f %f %f %f %f\\n\",\n           in_width * inputCalibration[0], in_height * inputCalibration[1],\n           in_width * inputCalibration[2], in_height * inputCalibration[3],\n           inputCalibration[4]);\n  } else {\n    printf(\n        \"Failed to read camera calibration (invalid format?)\\nCalibration \"\n        \"file: %s\\n\",\n        configFileName);\n    return;\n  }\n\n  // l3\n  if (l3 == \"crop\") {\n    outputCalibration[0] = -1;\n    printf(\"Out: Crop\\n\");\n  } else if (l3 == \"full\") {\n    outputCalibration[0] = -2;\n    printf(\"Out: Full\\n\");\n  } else if (l3 == \"none\") {\n    printf(\"NO RECTIFICATION\\n\");\n    return;\n  } else if (std::sscanf(l3.c_str(), \"%f %f %f %f %f\", &outputCalibration[0],\n                         &outputCalibration[1], &outputCalibration[2],\n                         &outputCalibration[3], &outputCalibration[4]) == 5) {\n    printf(\"Out: %f %f %f %f %f\\n\", outputCalibration[0], outputCalibration[1],\n           outputCalibration[2], outputCalibration[3], outputCalibration[4]);\n  } else {\n    printf(\"Out: Failed to Read Output pars... not rectifying.\\n\");\n    return;\n  }\n\n  // l4\n  if (std::sscanf(l4.c_str(), \"%d %d\", &out_width, &out_height) == 2) {\n    printf(\"Output resolution: %d %d\\n\", out_width, out_height);\n  } else {\n    printf(\"Out: Failed to Read Output resolution... not rectifying.\\n\");\n    return;\n  }\n\n  valid = true;\n\n  // =============================== find optimal new camera matrix\n  // =============================== prep warp matrices\n  float dist = inputCalibration[4];\n  float d2t = 2.0f * tan(dist / 2.0f);\n\n  // current camera parameters\n  float fx = inputCalibration[0] * in_width;\n  float fy = inputCalibration[1] * in_height;\n  float cx = inputCalibration[2] * in_width - 0.5;\n  float cy = inputCalibration[3] * in_height - 0.5;\n\n  // output camera parameters\n  float ofx, ofy, ocx, ocy;\n\n  // find new camera matrix for \"crop\" and \"full\"\n  if (inputCalibration[4] == 0) {\n    ofx = inputCalibration[0] * out_width;\n    ofy = inputCalibration[1] * out_height;\n    ocx = (inputCalibration[2] * out_width) - 0.5;\n    ocy = (inputCalibration[3] * out_height) - 0.5;\n  } else if (outputCalibration[0] == -1)  // \"crop\"\n  {\n    // find left-most and right-most radius\n    float left_radius = (cx) / fx;\n    float right_radius = (in_width - 1 - cx) / fx;\n    float top_radius = (cy) / fy;\n    float bottom_radius = (in_height - 1 - cy) / fy;\n\n    float trans_left_radius = tan(left_radius * dist) / d2t;\n    float trans_right_radius = tan(right_radius * dist) / d2t;\n    float trans_top_radius = tan(top_radius * dist) / d2t;\n    float trans_bottom_radius = tan(bottom_radius * dist) / d2t;\n\n    ofy = fy *\n          ((top_radius + bottom_radius) /\n           (trans_top_radius + trans_bottom_radius)) *\n          ((float)out_height / (float)in_height);\n    ocy = (trans_top_radius / top_radius) * ofy * cy / fy;\n\n    ofx = fx *\n          ((left_radius + right_radius) /\n           (trans_left_radius + trans_right_radius)) *\n          ((float)out_width / (float)in_width);\n    ocx = (trans_left_radius / left_radius) * ofx * cx / fx;\n\n    printf(\"new K: %f %f %f %f\\n\", ofx, ofy, ocx, ocy);\n    printf(\"old K: %f %f %f %f\\n\", fx, fy, cx, cy);\n  } else if (outputCalibration[0] == -2)  // \"full\"\n  {\n    float left_radius = cx / fx;\n    float right_radius = (in_width - 1 - cx) / fx;\n    float top_radius = cy / fy;\n    float bottom_radius = (in_height - 1 - cy) / fy;\n\n    // find left-most and right-most radius\n    float tl_radius = sqrt(left_radius * left_radius + top_radius * top_radius);\n    float tr_radius =\n        sqrt(right_radius * right_radius + top_radius * top_radius);\n    float bl_radius =\n        sqrt(left_radius * left_radius + bottom_radius * bottom_radius);\n    float br_radius =\n        sqrt(right_radius * right_radius + bottom_radius * bottom_radius);\n\n    float trans_tl_radius = tan(tl_radius * dist) / d2t;\n    float trans_tr_radius = tan(tr_radius * dist) / d2t;\n    float trans_bl_radius = tan(bl_radius * dist) / d2t;\n    float trans_br_radius = tan(br_radius * dist) / d2t;\n\n    float hor = std::max(br_radius, tr_radius) + std::max(bl_radius, tl_radius);\n    float vert =\n        std::max(tr_radius, tl_radius) + std::max(bl_radius, br_radius);\n\n    float trans_hor = std::max(trans_br_radius, trans_tr_radius) +\n                      std::max(trans_bl_radius, trans_tl_radius);\n    float trans_vert = std::max(trans_tr_radius, trans_tl_radius) +\n                       std::max(trans_bl_radius, trans_br_radius);\n\n    ofy = fy * ((vert) / (trans_vert)) * ((float)out_height / (float)in_height);\n    ocy = std::max(trans_tl_radius / tl_radius, trans_tr_radius / tr_radius) *\n          ofy * cy / fy;\n\n    ofx = fx * ((hor) / (trans_hor)) * ((float)out_width / (float)in_width);\n    ocx = std::max(trans_bl_radius / bl_radius, trans_tl_radius / tl_radius) *\n          ofx * cx / fx;\n\n    printf(\"new K: %f %f %f %f\\n\", ofx, ofy, ocx, ocy);\n    printf(\"old K: %f %f %f %f\\n\", fx, fy, cx, cy);\n  } else {\n    ofx = outputCalibration[0] * out_width;\n    ofy = outputCalibration[1] * out_height;\n    ocx = outputCalibration[2] * out_width - 0.5;\n    ocy = outputCalibration[3] * out_height - 0.5;\n  }\n\n  outputCalibration[0] = ofx / out_width;\n  outputCalibration[1] = ofy / out_height;\n  outputCalibration[2] = (ocx + 0.5) / out_width;\n  outputCalibration[3] = (ocy + 0.5) / out_height;\n  outputCalibration[4] = 0;\n\n  // =============================== build rectification map\n  // ===============================\n  remapX = new float[out_width * out_height];\n  remapY = new float[out_width * out_height];\n  for (int y = 0; y < out_height; y++)\n    for (int x = 0; x < out_width; x++) {\n      remapX[x + y * out_width] = x;\n      remapY[x + y * out_width] = y;\n    }\n  distortCoordinates(remapX, remapY, out_height * out_width);\n\n  bool hasBlackPoints = false;\n  for (int i = 0; i < out_width * out_height; i++) {\n    if (remapX[i] == 0) remapX[i] = 0.01;\n    if (remapY[i] == 0) remapY[i] = 0.01;\n    if (remapX[i] == in_width - 1) remapX[i] = in_width - 1.01;\n    if (remapY[i] == in_height - 1) remapY[i] = in_height - 1.01;\n\n    if (!(remapX[i] > 0 && remapY[i] > 0 && remapX[i] < in_width - 1 &&\n          remapY[i] < in_height - 1)) {\n      // printf(\"black pixel at %d %d %f %f!\\n\", i, i, remapX[i], remapY[i]);\n      hasBlackPoints = true;\n      remapX[i] = -1;\n      remapY[i] = -1;\n    }\n  }\n\n  if (hasBlackPoints)\n    printf(\"\\n\\nFOV Undistorter: Warning! Image has black pixels.\\n\\n\\n\");\n\n  // =============================== set Krect ===============================\n  Krect.setIdentity();\n  Krect(0, 0) = outputCalibration[0] * out_width;\n  Krect(1, 1) = outputCalibration[1] * out_height;\n  Krect(0, 2) = outputCalibration[2] * out_width - 0.5;\n  Krect(1, 2) = outputCalibration[3] * out_height - 0.5;\n\n  Korg.setIdentity();\n  Korg(0, 0) = inputCalibration[0] * in_width;\n  Korg(1, 1) = inputCalibration[1] * in_height;\n  Korg(0, 2) = inputCalibration[2] * in_width - 0.5;\n  Korg(1, 2) = inputCalibration[3] * in_height - 0.5;\n}\n\nUndistorterFOV::~UndistorterFOV() {\n  if (remapX != 0) delete[] remapX;\n  if (remapY != 0) delete[] remapY;\n}\n\nvoid UndistorterFOV::distortCoordinates(float* in_x, float* in_y, int n) {\n  if (!valid) {\n    printf(\"ERROR: invalid UndistorterFOV!\\n\");\n    return;\n  }\n\n  float dist = inputCalibration[4];\n  float d2t = 2.0f * tan(dist / 2.0f);\n\n  // current camera parameters\n  float fx = inputCalibration[0] * in_width;\n  float fy = inputCalibration[1] * in_height;\n  float cx = inputCalibration[2] * in_width - 0.5;\n  float cy = inputCalibration[3] * in_height - 0.5;\n\n  float ofx = outputCalibration[0] * out_width;\n  float ofy = outputCalibration[1] * out_height;\n  float ocx = outputCalibration[2] * out_width - 0.5f;\n  float ocy = outputCalibration[3] * out_height - 0.5f;\n\n  for (int i = 0; i < n; i++) {\n    float x = in_x[i];\n    float y = in_y[i];\n    float ix = (x - ocx) / ofx;\n    float iy = (y - ocy) / ofy;\n\n    float r = sqrtf(ix * ix + iy * iy);\n    float fac = (r == 0 || dist == 0) ? 1 : atanf(r * d2t) / (dist * r);\n\n    ix = fx * fac * ix + cx;\n    iy = fy * fac * iy + cy;\n\n    in_x[i] = ix;\n    in_y[i] = iy;\n  }\n}\n\ntemplate <typename T>\nvoid UndistorterFOV::undistort(const T* input, float* output, int nPixIn,\n                               int nPixOut) const {\n  if (!valid) return;\n\n  if (nPixIn != in_width * in_height) {\n    printf(\n        \"ERROR: undistort called with wrong input image dismesions (expected \"\n        \"%d pixel, got %d pixel)\\n\",\n        in_width * in_height, nPixIn);\n    return;\n  }\n  if (nPixOut != out_width * out_height) {\n    printf(\n        \"ERROR: undistort called with wrong output image dismesions (expected \"\n        \"%d pixel, got %d pixel)\\n\",\n        out_width * out_height, nPixOut);\n    return;\n  }\n\n  for (int idx = 0; idx < out_width * out_height; idx++) {\n    // get interp. values\n    float xx = remapX[idx];\n    float yy = remapY[idx];\n\n    if (xx < 0)\n      output[idx] = 0;\n    else {\n      // get integer and rational parts\n      int xxi = xx;\n      int yyi = yy;\n      xx -= xxi;\n      yy -= yyi;\n      float xxyy = xx * yy;\n\n      // get array base pointer\n      const T* src = input + xxi + yyi * in_width;\n\n      // interpolate (bilinear)\n      output[idx] = xxyy * src[1 + in_width] + (yy - xxyy) * src[in_width] +\n                    (xx - xxyy) * src[1] + (1 - xx - yy + xxyy) * src[0];\n    }\n  }\n}\ntemplate void UndistorterFOV::undistort<float>(const float* input,\n                                               float* output, int nPixIn,\n                                               int nPixOut) const;\ntemplate void UndistorterFOV::undistort<unsigned char>(\n    const unsigned char* input, float* output, int nPixIn, int nPixOut) const;\n", "meta": {"hexsha": "b76e2358b5284ee303724f89a701e51f569eb994", "size": 12497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FOVUndistorter.cpp", "max_stars_repo_name": "KangJialiang/mono_dataset_code", "max_stars_repo_head_hexsha": "629bb559802a1c801eaa3bf6ace0a04e9db03dd0", "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/FOVUndistorter.cpp", "max_issues_repo_name": "KangJialiang/mono_dataset_code", "max_issues_repo_head_hexsha": "629bb559802a1c801eaa3bf6ace0a04e9db03dd0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FOVUndistorter.cpp", "max_forks_repo_name": "KangJialiang/mono_dataset_code", "max_forks_repo_head_hexsha": "629bb559802a1c801eaa3bf6ace0a04e9db03dd0", "max_forks_repo_licenses": ["BSD-3-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.7057142857, "max_line_length": 80, "alphanum_fraction": 0.6133472033, "num_tokens": 3772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.02405355097050176, "lm_q1q2_score": 0.009081193720373514}}
{"text": "// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. See LICENSE.txt for details.\n//\n// Author: Denis Bueno\n\n#if defined(__linux__) && !defined(_GNU_SOURCE)\n#define _GNU_SOURCE 1\n#endif\n\n\n#include \"supp/boolector_supp.h\"\n\n#include <bitset>\n#include <boost/iterator/zip_iterator.hpp>\n#include <gmpxx.h>\n#include <iostream>\n#include <llvm/Support/Casting.h>\n\n#include \"supp/std_supp.h\"\n#include \"supp/wrapstream.h\"\n\n\nusing namespace std;\nusing namespace llvm;\n\nstatic inline int log2pow2(int size) {\n  switch (size) {\n    case 1: return 0;\n    case 2: return 1;\n    case 4: return 2;\n    case 8: return 3;\n    case 16: return 4;\n    case 32: return 5;\n    case 64: return 6;\n    case 128: return 7;\n  }\n  EUFORIA_FATAL(\"size must be power of two < 256: got \" + to_string(size));\n}\n\n\n/*-----------------------------------------------------------------------------------*/\n\nnamespace boolector {\n\n\nstd::size_t hash_value(const BoolectorNodeWrapper& n) {\n  return n.hash();\n}\n\nstd::ostream& operator<<(std::ostream& os, const BoolectorNodeWrapper& n) {\n  auto *file = wrapostream(os);\n  boolector_dump_smt2_node(boolector_get_btor(n.c_node_), file, n.c_node_);\n  fclose(file);\n  return os;\n}\n\nBoolectorNodeWrapper BoolectorNodeWrapper::operator()(const BoolectorNodeWrapper& a) {\n  vector<BoolectorNodeWrapper> args({a});\n  return boolector::apply(args, *this);\n}\n\nBoolectorNodeWrapper BoolectorNodeWrapper::operator()(const std::vector<BoolectorNodeWrapper>& args) {\n  return boolector::apply(args, *this);\n}\n\n/*-----------------------------------------------------------------------------------*/\n/* btor methods */\n\n\nBtorWrapper::BtorWrapper() : c_btor_(boolector_new()), trfp(nullptr) {}\n\nBtorWrapper::~BtorWrapper() {\n  boolector_release_all(c_btor_);\n  boolector_delete(c_btor_);\n  if (trfp) fclose(trfp);\n}\n\nBtorWrapper::BtorWrapper(const BtorWrapper& other) \n  : c_btor_(boolector_clone(other.c_btor_)),\n    trfp(boolector_get_trapi(other.c_btor_)) {\n  for (auto& [name, node] : other.bitvecs) {\n    bitvecs.insert({name, matchNode(node)});\n  }\n  for (auto& [name, node] : other.arrays) {\n    arrays.insert({name, matchNode(node)});\n  }\n  for (auto& a : other.assumptions) {\n    assumptions.push_back(matchNode(a));\n  }\n  for (auto& [name, node] : other.params) {\n    params.insert({name, node});\n  }\n  for (auto& f : other.funs) {\n    funs.push_back(f);\n  }\n}\n\nvoid BtorWrapper::setOption(BtorOption o, uint32_t val) {\n  boolector_set_opt(c_btor_, o, val);\n}\n\nuint32_t BtorWrapper::getOption(BtorOption o) const {\n  return boolector_get_opt(c_btor_, o);\n}\n\nvoid BtorWrapper::PrintStats() const {\n  boolector_print_stats(c_btor_);\n}\n\nvoid BtorWrapper::ResetStats() {\n  boolector_reset_stats(c_btor_);\n}\n\n BoolectorNodeWrapper BtorWrapper::zero(int width) {\n  return Wrap(boolector_zero(c_btor_, boolector_bitvec_sort(c_btor_, width)));\n}\n\n BoolectorNodeWrapper BtorWrapper::bconst(const char *bits) {\n  return Wrap(boolector_const(c_btor_, bits));\n}\n\nBoolectorNodeWrapper BtorWrapper::bconst(const std::string& bits) {\n  return Wrap(boolector_const(c_btor_, bits.c_str()));\n}\n\nBoolectorNodeWrapper BtorWrapper::boolVal(bool b) {\n  auto ret = Wrap(b ? boolector_true(c_btor_) : boolector_false(c_btor_));\n  return ret;\n}\n\nBoolectorNodeWrapper BtorWrapper::cint(int i, int width) {\n  auto sort = width == 1 ? boolector_bool_sort(c_btor_) : boolector_bitvec_sort(c_btor_, width);\n  return Wrap(boolector_int(c_btor_, i, sort));\n}\n\nBoolectorNodeWrapper BtorWrapper::var(int width, const std::string& name) {\n  if (width < 1) EUFORIA_FATAL(\"width is not at least 1\");\n  if (auto loc = bitvecs.find(name); loc != bitvecs.end()) {\n    assert(name == loc->second.symbol());\n    assert(static_cast<unsigned>(width) == loc->second.width());\n    return loc->second;\n  }\n  \n  auto sort = boolector_bitvec_sort(c_btor_, width);\n  auto ret = Wrap(boolector_var(c_btor_, sort, name.c_str()));\n  bitvecs.insert({name, ret});\n  return ret;\n}\n  \n\nBoolectorNodeWrapper BtorWrapper::boolvar(const std::string& name) {\n  if (auto search = bools_.find(name); search != bools_.end()) {\n    assert(name == search->second.symbol());\n    return search->second;\n  }\n  auto sort = boolector_bool_sort(c_btor_);\n  auto ret = Wrap(boolector_var(c_btor_, sort, name.c_str()));\n  bools_.insert({name, ret});\n  return ret;\n}\n\nBoolectorNodeWrapper BtorWrapper::uf(BoolectorSort s, const string& name) {\n  return Wrap(boolector_uf(c_btor_, s, name.c_str()));\n}\n\nBoolectorNodeWrapper BtorWrapper::param(BoolectorSort sort, const std::string& name) {\n  if (auto loc = params.find(name); loc != params.end()) {\n    assert(boolector_is_param(c_btor_, loc->second.c_node_));\n    assert(name == loc->second.symbol());\n    return loc->second;\n  }\n  \n  auto ret = Wrap(boolector_param(c_btor_, sort, name.c_str()));\n  params.insert({name, ret});\n  return ret;\n}\n\nBoolectorNodeWrapper write(const BoolectorNodeWrapper& arr, const BoolectorNodeWrapper& c_node_, const BoolectorNodeWrapper& val) {\n  assert(arr.btor() == c_node_.btor() && c_node_.btor() == val.btor());\n//    if (boolector_is_fun_sort(arr.btor(), arr.sort())) {\n//      // write is a new fun\n//      auto name = \"ptr_in\" + to_string(++paramCtr);\n//      auto ptr_in = BoolectorNodeWrapper(boolector_param(arr.btor(), boolector_fun_get_domain_sort(arr.btor(), arr.c_node_), name.c_str()));\n//      vector<BoolectorNodeWrapper> recArg({ptr_in});\n//      auto body = ite(ptr_in.eq(c_node_), val, boolector::apply(recArg, arr));\n//      BoolectorNode **param = new BoolectorNode*[1];\n//      param[0] = ptr_in.c_node_;\n//      auto ret = BoolectorNodeWrapper(boolector_fun(arr.btor(), param, 1, body.c_node_));\n//      delete[] param;\n//      return ret;\n//    } else {\n    // use boolector_write\n    return BoolectorNodeWrapper(arr.btor(), boolector_write(arr.btor(), arr.c_node_, c_node_.c_node_, val.c_node_));\n//    }\n}\n\nBoolectorNodeWrapper read(const BoolectorNodeWrapper& arr, const BoolectorNodeWrapper& c_node_) {\n  assert(arr.btor() == c_node_.btor());\n//    if (boolector_is_fun_sort(arr.btor(), arr.sort())) {\n//      // read is an apply\n//      BoolectorNode **args = new BoolectorNode*[1];\n//      args[0] = c_node_.c_node_;\n//      auto ret = BoolectorNodeWrapper(boolector_apply(arr.btor(), args, 1, arr.c_node_));\n//      delete[] args;\n//      return ret;\n//    } else {\n    return BoolectorNodeWrapper(arr.btor(), boolector_read(arr.btor(), arr.c_node_, c_node_.c_node_));\n//    }\n}\n\nBoolectorNodeWrapper BtorWrapper::array(const std::string& name, int ptrSize, int valWidth) {\n  if (auto loc = arrays.find(name); loc != arrays.end()) {\n    assert(name == loc->second.symbol());\n    assert(boolector_is_array(loc->second.btor(), loc->second.c_node_));\n    return loc->second;\n  }\n  \n  auto sort = boolector_array_sort(c_btor_, boolector_bitvec_sort(c_btor_, ptrSize), boolector_bitvec_sort(c_btor_, valWidth));\n  auto ret = Wrap(boolector_array(c_btor_, sort, name.c_str()));\n  arrays.insert({name, ret});\n  return ret;\n}\n\nBoolectorNodeWrapper BtorWrapper::const_array(\n    int ptr_size, const BoolectorNodeWrapper& value) {\n  int val_size = static_cast<int>(value.width());\n  auto sort = boolector_array_sort(c_btor_,\n                                   boolector_bitvec_sort(c_btor_, ptr_size),\n                                   boolector_bitvec_sort(c_btor_, val_size));\n  auto ret = Wrap(boolector_const_array(c_btor_, sort, value.c_node_));\n  return ret;\n}\n\nBoolectorNodeWrapper BtorWrapper::fun(const std::vector<BoolectorNodeWrapper>& funParams, BoolectorNodeWrapper body) {\n  int paramc = static_cast<int>(funParams.size());\n  BoolectorNode **paramnodes = new BoolectorNode*[funParams.size()];\n  for (int i = 0; i < paramc; i++) {\n    paramnodes[i] = funParams[i].c_node_;\n  }\n  auto ret = Wrap(boolector_fun(c_btor_, paramnodes, paramc, body.c_node_));\n  delete[] paramnodes;\n  funs.push_back(ret);\n  return ret;\n}\n\nBoolectorSort BtorWrapper::fun_sort(BoolectorSort *args, uint32_t arity,\n                                    BoolectorSort ret) {\n  return boolector_fun_sort(c_btor_, args, arity, ret);\n}\n\nBoolectorSort BtorWrapper::array_sort(BoolectorSort index,\n                                      BoolectorSort element) {\n  return boolector_array_sort(c_btor_, index, element);\n}\n\nBoolectorSort BtorWrapper::bitvec_sort(uint32_t width) {\n  return boolector_bitvec_sort(c_btor_, width);\n}\n\nBoolectorSort BtorWrapper::bool_sort() {\n  return boolector_bool_sort(c_btor_);\n}\n\nBoolectorNodeWrapper apply(const std::vector<BoolectorNodeWrapper>& args, BoolectorNodeWrapper f) {\n  int argc = static_cast<int>(args.size());\n  BoolectorNode **argnodes = new BoolectorNode*[args.size()];\n  for (int i = 0; i < argc; i++) {\n    argnodes[i] = args[i].c_node_;\n  }\n  auto ret = BoolectorNodeWrapper(f.btor(), boolector_apply(f.btor(), argnodes, argc, f.c_node_));\n  delete[] argnodes;\n  return ret;\n}\n\n\n\nvoid BtorWrapper::fixateAssumptions() {\n  boolector_fixate_assumptions(c_btor_);\n}\n\nvoid BtorWrapper::resetAssumptions() {\n  boolector_reset_assumptions(c_btor_);\n}\n\nBtorWrapper::result BtorWrapper::simplify() {\n  ScopedTimeKeeper t(&total_simplify_time_);\n  auto result = boolector_simplify(c_btor_);\n  switch (result) {\n    case BOOLECTOR_SAT: return result::kSat;\n    case BOOLECTOR_UNSAT: return result::kUnsat;\n    case BOOLECTOR_UNKNOWN: return result::kUnknown;\n    default:\n      EUFORIA_FATAL(\"bad result from boolector\");\n  }\n}\n\nBtorWrapper::result BtorWrapper::check() {\n  ScopedTimeKeeper t(&total_check_time_);\n  auto result = boolector_sat(c_btor_);\n  assumptions.clear();\n  switch (result) {\n    case BOOLECTOR_SAT: return result::kSat;\n    case BOOLECTOR_UNSAT: return result::kUnsat;\n    default: EUFORIA_FATAL(\"unhandled switch\");\n  }\n}\n\nshared_ptr<BtorAssignment> BtorWrapper::assignment(const BoolectorNodeWrapper& n) {\n  assert(n.btor() == c_btor_);\n  shared_ptr<BtorAssignment> ret;\n  if (n.isArray()) {\n    ret = make_shared<BtorArrayAssignment>(*this, n);\n  } else {\n    assert(n.isBV());\n    ret = make_shared<BtorBvAssignment>(*this, n);\n  }\n  return ret;\n}\n\nBoolectorNodeWrapper BtorWrapper::assignmentNode(const BtorAssignment& a) {\n  switch (a.kind) {\n    case BtorAssignment::kind::BV: {\n      auto& val = static_cast<const BtorBvAssignment&>(a);\n      return bconst(val.value());\n    }\n\n    case BtorAssignment::kind::Array: {\n      auto& arrayAss = static_cast<const BtorArrayAssignment&>(a);\n      auto arr = array(arrayAss.symbol, arrayAss.ptrSize, arrayAss.valSize);\n      for (int i = 0; i < arrayAss.size(); i++) {\n        auto& c_node_ = arrayAss.indices()[i];\n        auto& val = arrayAss.values()[i];\n        auto nptr = bconst(c_node_);\n        auto nval = bconst(val);\n        arr = write(arr, nptr, nval);\n      }\n      return arr;\n    }\n      \n    default:\n      EUFORIA_FATAL(\"more imples\");\n  }\n\n}\n\n\nBoolectorNodeWrapper BtorWrapper::matchNode(const BoolectorNodeWrapper& n) const {\n  return Wrap(boolector_match_node(c_btor_, n.c_node_));\n}\n\n\nBtorWrapper::result BtorWrapper::checkSMT2(const std::string& filename) {\n  auto *fp = fopen(filename.c_str(), \"r\");\n  assert(nullptr != fp);\n  char *error_msg = nullptr;\n  int status = -1;\n  auto *outfile = fopen(\"/tmp/btor_checkSMT2_outfile\", \"w\");\n  assert(nullptr != outfile);\n  switch (boolector_parse_smt2(c_btor_, fp, filename.c_str(), outfile, &error_msg, &status)) {\n    case BOOLECTOR_SAT:\n      return result::kSat;\n    case BOOLECTOR_UNSAT:\n      return result::kUnsat;\n    case BOOLECTOR_UNKNOWN:\n      return result::kUnknown;\n    case BOOLECTOR_PARSE_ERROR:\n      EUFORIA_FATAL(\"checkSMT2: boolector parse error\");\n  }\n  EUFORIA_FATAL(\"unexpected\");\n}\n\nvoid BtorWrapper::setTrace(const std::string& filename) {\n  trfp = fopen(filename.c_str(), \"w\");\n  assert(trfp);\n  boolector_set_trapi(c_btor_, trfp);\n}\n\nvoid BtorWrapper::printModel() const {\n  char fmt[5] = \"smt2\"; // why is this not const char* \n  boolector_print_model(c_btor_, fmt, stderr);\n}\n\nvoid BtorWrapper::DumpBenchmark(std::ostream& os) const {\n  auto *file = wrapostream(os);\n  boolector_dump_smt2(c_btor_, file);\n  fclose(file);\n}\n\nvoid BtorWrapper::Print(std::ostream& os) const {\n  auto *file = wrapostream(os);\n  boolector_dump_smt2(c_btor_, file);\n  fclose(file);\n}\n\nvoid BtorWrapper::printAssertions() const {\n  //    boolector_dump_smt2(c_btor_, wrapostream(cerr));\n  //    boolector_dump_smt2(c_btor_, wraplogger(log));\n  stringstream ss;\n  boolector_dump_smt2(c_btor_, wrapstringstream(&ss));\n  logger.Log(4, \"boolector assertions:\\n{}\", ss.str());\n  //log->debug(\"boolector has {} assertions:\", assertions.size());\n  //size_t num = 0;\n  //for (auto assertion : assertions)\n  //  log->debug(\"assertion {}: {}\\n\", ++num, assertion);\n  //log->debug(\"boolector has {} assumptions:\", assumptions.size());\n  //num = 0;\n  //for (auto assump : assumptions) {\n  //  log->debug(\"assumption {}: {}\\n\", ++num, assump);\n  //}\n}\n\nvoid BtorWrapper::add(BoolectorNode *n) {\n  boolector_assert(c_btor_, n);\n}\n\nvoid BtorWrapper::assume(BoolectorNode *n) {\n  assumptions.push_back(Wrap(n));\n  boolector_assume(c_btor_, n);\n}\n\n\n\n/*-----------------------------------------------------------------------------------*/\n// assignments\n\nBtorArrayAssignment::BtorArrayAssignment(BtorWrapper& b, const BoolectorNodeWrapper& n)\n  : BtorAssignment(BtorAssignment::kind::Array, b,\n                   boolector_get_symbol(n.btor(), n.c_node_)),\n    ptrSize(boolector_get_index_width(n.btor(), n.c_node_)),\n    valSize(boolector_get_width(n.btor(), n.c_node_)) {\n  assert(b.c_btor_ == n.btor());\n  char **i;\n  char **v;\n  uint32_t size;\n  boolector_array_assignment(b.c_btor_, n.c_node_, &i, &v, &size);\n  if (size == 1 && i[0][0] == '*') {\n    // constant array\n    string val(v[0]);\n    assert(val.size() == valSize);\n    const_value_ = val;\n    boolector_free_array_assignment(b.c_btor_, i, v, size);\n    return;\n  }\n  \n  indices_.reserve(size);\n  values_.reserve(size);\n  for (uint32_t j = 0; j < size; j++) {\n    string idx(i[j]);\n    string val(v[j]);\n    assert(idx.size() == ptrSize);\n    assert(val.size() == valSize);\n    indices_.emplace_back(idx);\n    values_.emplace_back(val);\n  }\n  // Fills the vector idx_val_pairs_ with the corresponding pairs from indices_\n  // and values.\n  idx_val_pairs_.reserve(size);\n  using IdxValTuple = boost::tuple<string&,string&>;\n  std::for_each(\n      boost::make_zip_iterator(\n          boost::make_tuple(indices_.begin(), values_.begin())),\n      boost::make_zip_iterator(\n          boost::make_tuple(indices_.end(), values_.end())),\n      [&](const IdxValTuple& t) {\n          idx_val_pairs_.emplace_back(std::make_pair(boost::get<0>(t),\n                                                     boost::get<1>(t)));\n      });\n  assert(idx_val_pairs_.size() == size);\n  struct {\n    bool operator()(const pair<string,string>& iv0,\n                    const pair<string,string>& iv1) {\n      return std::get<0>(iv0) < std::get<0>(iv1);\n    }\n  } compare_on_indices;\n  // Sorts the array of pairs so that lambdas are equivalent if they're\n  // identical (see AsExpr).\n  std::sort(idx_val_pairs_.begin(), idx_val_pairs_.end(), compare_on_indices);\n  if (size)\n    boolector_free_array_assignment(b.c_btor_, i, v, size);\n}\n\nBtorArrayAssignment::~BtorArrayAssignment() = default;\n\n\n\nstatic z3::expr bvValExpr(z3::context& ctx, const std::string& ass) {\n  int width = static_cast<int>(ass.size());\n  bool bits[width];\n  for (int i = 0, j = width-1; i < width; i++, j--) {\n    bool bit = bool(ass[i] - '0');\n    bits[j] = bit;\n  }\n  return ctx.bv_val(width, bits);\n}\n\n\nz3::expr BtorArrayAssignment::AsExpr(const z3::expr& arr_in) const {\n  if (const_value_) {\n    return z3::const_array(arr_in.ctx().bv_sort(ptrSize),\n                           bvValExpr(arr_in.ctx(), *const_value_));\n  }\n\n  assert(indices_.size() == values_.size());\n  // assert(bool(arr_in));\n  z3::expr arr(arr_in.ctx());\n  unsigned i = 0;\n  for (auto&& iv_pair : idx_val_pairs_) {\n    auto idx = bvValExpr(arr.ctx(), iv_pair.first);\n    auto val = bvValExpr(arr.ctx(), iv_pair.second);\n    auto var = arr.ctx().constant((\"x\" + to_string(i++)).c_str(), idx.get_sort());\n    if (!bool(arr)) {\n      arr = z3::lambda(var,\n                       z3::ite(var == idx, val,\n                               arr.ctx().bv_val(0, val.get_sort().bv_size())));\n    } else {\n      arr = z3::lambda(var, z3::ite(var == idx, val, z3::select(arr, idx)));\n    }\n  }\n  return arr;\n}\n\n\nz3::expr BtorArrayAssignment::AsConstraint(const z3::expr& var) const {\n  if (const_value_) {\n    return var == AsExpr(var);\n  }\n  assert(indices_.size() == values_.size());\n  z3::expr_vector v(var.ctx());\n  ExprVectorInserter out(v);\n  for (unsigned i = 0; i < indices_.size(); i++) {\n    auto idx = bvValExpr(var.ctx(), indices_[i]);\n    auto val = bvValExpr(var.ctx(), values_[i]);\n    *out++ = z3::select(var, idx) == val;\n  }\n  return expr_mk_and(v);\n}\n\n\nstatic bool bitStringToVal(const std::string& index, uint64_t &val) {\n  if (index.size() <= 64) {\n    val = static_cast<uint64_t>(strtoll(index.c_str(), nullptr, 2));\n    return true;\n  }\n  return false;\n}\n\nvoid BtorArrayAssignment::print(std::ostream& os) const {\n  assert(indices_.size() == values_.size());\n  if (symbol) {\n    os << symbol;\n  }\n  os << \" btor array: [index] = value\" << endl;\n  if (const_value_) {\n    os << \"[*] = \" << *const_value_ << \";\" << std::endl;\n  } else {\n    for (unsigned i = 0; i < indices_.size(); i++) {\n      auto& idx = indices_[i];\n      auto& val = values_[i];\n      os << \"[\" << idx << \"] = \" << val << \";\" << std::endl;\n    }\n    os << \"[ ... else ... ] = 0\";\n  }\n}\n\nz3::expr BtorBvAssignment::AsExpr(const z3::expr& e) const {\n  if (e.is_bool()) {\n    return e.ctx().bool_val(ass[0] == '1');\n  }\n  return bvValExpr(e.ctx(), ass);\n}\n  \nz3::expr BtorBvAssignment::AsConstraint(const z3::expr& var) const {\n  auto expr = AsExpr(var);\n  return expr == var;\n}\n\n\nvoid BtorBvAssignment::print(ostream& os) const {\n  if (symbol && width == 1) {\n    if (strcmp(ass, \"0\") == 0) {\n      os << \"!\";\n    }\n    os << symbol;\n  } else {\n    if (symbol)\n      os << \"<\" << width << \">\" << symbol << \" = \" << ass;\n    else\n      os << \"<\" << width << \"> = \" << ass;\n  }\n}\n\nstd::ostream& operator<<(std::ostream& os, const BtorAssignment& a) {\n  a.print(os);\n  return os;\n}\n\n\n/*-----------------------------------------------------------------------------------*/\n// boolector rewriter\n\nZ3ToBtorRewriter::Z3ToBtorRewriter(std::shared_ptr<BtorWrapper> b) : B(b) {}\n  \nBoolectorNodeWrapper Z3ToBtorRewriter::visitExpr(const z3::expr& n) {\n  Z3_decl_kind k;\n  // function that does the shift\n  function<BoolectorNodeWrapper(const BoolectorNodeWrapper&,\n                                const BoolectorNodeWrapper&)> shift =\n      [&](const BoolectorNodeWrapper& n,\n          const BoolectorNodeWrapper& shift_amount) {\n        if (k == Z3_OP_BSHL) { return n.shl(shift_amount); }\n        else if (k == Z3_OP_BASHR) { return n.ashr(shift_amount); }\n        else if (k == Z3_OP_BLSHR) { return n.lshr(shift_amount); }\n        else { EUFORIA_FATAL(\"unhandled kind: {}\", k); }\n      };\n  // function that does sign/zero extension\n  function<BoolectorNodeWrapper(const BoolectorNodeWrapper&, int)> extend =\n      [&](const BoolectorNodeWrapper& n, int extend_amount) {\n        if (k == Z3_OP_BSHL) { return n.uext(extend_amount); }\n        else if (k == Z3_OP_BASHR) { return n.sext(extend_amount); }\n        else if (k == Z3_OP_BLSHR) { return n.uext(extend_amount); }\n        else { EUFORIA_FATAL(\"unhandled kind: {}\", k); }\n      };\n  switch ((k = n.decl().decl_kind())) {\n    case Z3_OP_BSHL:\n    case Z3_OP_BASHR:\n    case Z3_OP_BLSHR: {\n      BoolectorNodeWrapper ret;\n      assert(n.num_args() == 2);\n      const auto& val = Arg(n,0);\n      const auto& arg1 = Arg(n,1);\n      const unsigned val_width = val.width();\n      bitset<sizeof(val_width)*8> bits(val_width);\n      // Boolector only supports shifting bit vectors of power-of-two size, but\n      // Z3 allows you to shift any bit width vector. To express non\n      // powers-of-two in Boolector, we extend the BV to the nearest\n      // power-of-two size, shift it, and truncate the result.\n      if (bits.count() != 1) {\n        auto exp = ceil(log2(val_width));\n        // Get the next highest power of two size\n        auto new_width = pow(2, exp);\n        logger.Log(7, \"exp {}\", exp);\n        logger.Log(7, \"bits {}\", bits);\n        logger.Log(7, \"val {}\", val);\n        logger.Log(7, \"val_width {}\", val_width);\n        logger.Log(7, \"arg1 {}\", arg1);\n        logger.Log(7, \"new_width {}\", new_width);\n        // Extends the value, shifts it, then chops off the top bits\n        auto val_extended = extend(val, new_width - val_width);\n        auto shift_amount = arg1.slice(exp-1, 0);\n        ret = shift(val_extended, shift_amount);\n        ret = ret.slice(val_width-1, 0);\n        logger.Log(7, \"ret.width() {}\", ret.width());\n      } else {\n        auto hi = log2pow2(val_width)-1;\n        const auto& shift_amount = arg1.slice(hi, 0);\n        ret = shift(val, shift_amount);\n        assert(ret.width() == n.get_sort().bv_size());\n      }\n      assert(ret.width() == n.get_sort().bv_size());\n      return ret;\n      break;\n    }\n\n    default:\n      break;\n  }\n  std::ostringstream ss;\n  ss << n;\n  EUFORIA_FATAL(fmt::format(\"no generic handling: {}\", ss.str()));\n}\n\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitUNINTERPRETED(const z3::expr& e) {\n  const auto decl = e.decl();\n  const auto name = decl.name().str();\n  if (e.is_bool()) {\n    // Boolean variable\n    if (e.num_args() == 0) {\n      return B->boolvar(e.decl().name().str().c_str());\n    }\n    EUFORIA_FATAL(\"unhandled Boolean function\");\n  } else if (e.is_bv()) {\n    // Function returning a bit vector\n    if (e.num_args() == 2) {\n      // GROSS stuff\n      // So Z3 turns perfectly good (bvsrem ...) ops into uninterpreted function calls.\n      // This is because division by zero is undefined.\n      // By the way it ALSO turns (ite (not (= x 0)) (/ y x) 0) into uninterpreted calls.\n      // Anyhow, here we use the real boolector functions.\n      if (starts_with(name, \"bvsrem\")) {\n        return Arg(e,0).srem(Arg(e,1));\n      } else if (starts_with(name, \"bvsmod\")) {\n        return Arg(e,0).srem(Arg(e,1));\n      } else if (starts_with(name, \"bvsdiv\")) {\n        return Arg(e,0) / Arg(e,1);\n      } else if (starts_with(name, \"bvurem\")) {\n        return Arg(e,0).urem(Arg(e,1));\n      } else if (starts_with(name, \"bvudiv\")) {\n        return Arg(e,0).udiv(Arg(e,1));\n      }\n    }\n    // Bit vector variable\n    if (decl.is_const()) {\n      return B->var(e.get_sort().bv_size(), name);\n    } else {\n      // Uninterpreted function returning a BV\n      vector<BoolectorSort> param_sorts;\n      for (unsigned i = 0; i < decl.arity(); i++) {\n        param_sorts.push_back(TranslateSort(decl.domain(i)));\n      }\n      BoolectorSort ret_sort = TranslateSort(decl.range());\n      auto uf_sort = B->fun_sort(param_sorts.data(), param_sorts.size(),\n                                 ret_sort);\n      return B->uf(uf_sort, name);\n    }\n  } else if (e.is_array()) {\n    return B->array(e.decl().name().str(),\n                   e.get_sort().array_domain().bv_size(),\n                   e.get_sort().array_range().bv_size());\n  }\n  EUFORIA_FATAL(\"unimplemented\");\n}\n\n\nBoolectorSort Z3ToBtorRewriter::TranslateSort(const z3::sort& s) const {\n  switch (s.sort_kind()) {\n    case Z3_BOOL_SORT:\n      return B->bool_sort();\n    case Z3_BV_SORT:\n      return B->bitvec_sort(s.bv_size());\n    case Z3_ARRAY_SORT: {\n      auto index_sort = TranslateSort(s.array_domain());\n      auto value_sort = TranslateSort(s.array_range());\n      return B->array_sort(index_sort, value_sort);\n    }\n    default: {\n      EUFORIA_FATAL(fmt::format(\"Boolector doesn't support this sort: {}\",\n                                s));\n    }\n  }\n}\n\n\n//  int uniqParam = 0;\nBoolectorNodeWrapper Z3ToBtorRewriter::visitCONST_ARRAY(const z3::expr& e) {\n  return B->const_array(e.get_sort().array_domain().bv_size(),\n                        Arg(e, 0));\n\n  // use a lambda \\x. 0 to send all reads to zero\n  // this is currently unsupported by boolector :(\n//    auto ptrSort = boolector_bitvec_sort(B->c_btor_, sort.array_domain().bv_size());\n//    auto x = B->param(ptrSort, \"ptr_in\" + to_string(++uniqParam));\n//    vector<BoolectorNodeWrapper> params({x});\n//    auto zero = B->cint(0, sort.array_range().bv_size());\n//    return B->fun(params, zero);\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitDISTINCT(const z3::expr& n) {\n  BoolectorNodeWrapper ret;\n  for (unsigned i = 0; i < n.num_args(); i++) {\n    for (unsigned j = i+1; j < n.num_args(); j++) {\n      auto ne = Arg(n, i).ne(Arg(n, j));\n      ret = !ret.is_null() ? ret && ne : ne;\n    }\n  }\n  assert(!ret.is_null());\n  return ret;\n}\nBoolectorNodeWrapper Z3ToBtorRewriter::visitAND(const z3::expr& n) {\n  BoolectorNodeWrapper ret = Arg(n,0);\n  for (unsigned i = 1; i < n.num_args(); i++) {\n    ret = ret && Arg(n,i);\n  }\n  return ret;\n}\nBoolectorNodeWrapper Z3ToBtorRewriter::visitOR(const z3::expr& n) {\n  BoolectorNodeWrapper ret = Arg(n,0);\n  for (unsigned i = 1; i < n.num_args(); i++) {\n    ret = ret || Arg(n,i);\n  }\n  return ret;\n}\n\n#define BTOR_BINARY_HANDLER(KIND, EXPR) \\\nBoolectorNodeWrapper Z3ToBtorRewriter::visit##KIND(const z3::expr& n) { \\\n  assert(n.num_args() == 2); \\\n  BoolectorNodeWrapper ret(EXPR); \\\n  assert(ret.width() > 0); \\\n  assert(!n.is_bv() || (static_cast<unsigned>(ret.width()) == n.get_sort().bv_size())); \\\n  assert(!n.is_bool() || (ret.width() == 1)); \\\n  return ret; \\\n}\n\n#define BTOR_TERNARY_HANDLER(KIND, EXPR) \\\nBoolectorNodeWrapper Z3ToBtorRewriter::visit##KIND(const z3::expr& n) { \\\n  assert(n.num_args() == 3); \\\n  BoolectorNodeWrapper ret(EXPR); \\\n  assert(ret.width() > 0); \\\n  assert(!n.is_bv() || (static_cast<unsigned>(ret.width()) == n.get_sort().bv_size())); \\\n  assert(!n.is_bool() || (ret.width() == 1)); \\\n  return ret; \\\n}\n\n#define BTOR_RASSOC_HANDLER(KIND, COP) \\\nBoolectorNodeWrapper Z3ToBtorRewriter::visit##KIND(const z3::expr& n) { \\\n  BoolectorNodeWrapper ret(Arg(n,0)); \\\n  for (unsigned i = 1; i < n.num_args(); i++) { \\\n    ret = COP(ret, Arg(n,i)); \\\n  } \\\n  return ret; \\\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitTRUE(const z3::expr&) {\n  return B->boolVal(true);\n}\nBoolectorNodeWrapper Z3ToBtorRewriter::visitFALSE(const z3::expr&) {\n  return B->boolVal(false);\n}\nBoolectorNodeWrapper Z3ToBtorRewriter::visitNOT(const z3::expr& n) {\n  assert(n.num_args() == 1);\n  return !Arg(n,0);\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBIT2BOOL(const z3::expr& e) {\n  assert(Z3_get_decl_num_parameters(Z3_context(e.ctx()), Z3_func_decl(e.decl())) == 1);\n  auto bit_idx = Z3_get_decl_int_parameter(Z3_context(e.ctx()), Z3_func_decl(e.decl()), 0);\n  auto tgt = Arg(e, 0);\n  auto ret = tgt.slice(bit_idx, bit_idx);\n  assert(ret.width() == 1);\n  return ret;\n}\n\n//  BTOR_BINARY_HANDLER(EQ, Arg(n, 0).eq(Arg(n, 1)));\nBoolectorNodeWrapper Z3ToBtorRewriter::visitEQ(const z3::expr& n) {\n  assert(n.num_args() == 2);\n\n  BoolectorNodeWrapper ret(Arg(n, 0) == (Arg(n, 1)));\n\n  assert(!n.is_bv() || (ret.width() == n.get_sort().bv_size()));\n  assert(!n.is_bool() || (ret.width() == 1));\n  return ret;\n}\n\n\n\nBTOR_BINARY_HANDLER(IFF, Arg(n, 0).iff(Arg(n, 1)));\nBTOR_TERNARY_HANDLER(ITE, ite(Arg(n, 0), Arg(n, 1), Arg(n, 2)));\nBTOR_BINARY_HANDLER(IMPLIES, Arg(n, 0).implies(Arg(n, 1)));\nBTOR_BINARY_HANDLER(XOR, Arg(n, 0) ^ Arg(n, 1));\n\n\n// *** bit vector\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBNUM(const z3::expr& n) {\n  string numstr;\n  auto b = n.is_numeral(numstr);\n  assert(b);\n  _unused(b);\n  mpz_class num(numstr);\n  string binstr = num.get_str(2);\n  assert(binstr.size() <= n.get_sort().bv_size());\n  string bits(n.get_sort().bv_size(), '0');\n  copy(binstr.begin(), binstr.end(),\n       bits.begin() + (bits.size() - binstr.size()));\n  assert(bits.size() == n.get_sort().bv_size());\n  \n  //unsigned long long i = 0;\n  //b = Z3_get_numeral_uint64(Z3_context(n.ctx()), Z3_ast(n), &i);\n  //assert(b == Z3_TRUE);\n  //string allBits;\n  //for (unsigned j = 0; j < n.get_sort().bv_size(); j++) {\n  //  allBits.push_back((i>>j) & 1 ? '1' : '0');\n  //}\n  //std::reverse(begin(allBits), end(allBits));\n  //logger.Log(3, \"allbits is {}\", allBits);\n  //assert(allBits == bits);\n  //assert(allBits.size() == n.get_sort().bv_size());\n  return B->bconst(bits.c_str());\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitCONCAT(const z3::expr& n) {\n  BoolectorNodeWrapper ret = Arg(n,0);\n  for (unsigned i = 1; i < n.num_args(); i++) {\n    ret = ret.concat(Arg(n,i));\n  }\n  assert(ret.width() == n.get_sort().bv_size());\n  return ret;\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitEXTRACT(const z3::expr& e) {\n  // extract in z3 uses \"parameters\" not \"arguments\" to specify the hi and lo for extracting\n  assert(Z3_get_decl_num_parameters(Z3_context(e.ctx()), Z3_func_decl(e.decl())) == 2);\n  auto hi = Z3_get_decl_int_parameter(Z3_context(e.ctx()), Z3_func_decl(e.decl()), 0);\n  auto lo = Z3_get_decl_int_parameter(Z3_context(e.ctx()), Z3_func_decl(e.decl()), 1);\n  auto tgt = Arg(e, 0);\n  auto ret = tgt.slice(hi, lo);\n  assert(ret.width() == e.get_sort().bv_size());\n  return ret;\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitSIGN_EXT(const z3::expr& e) {\n  assert(Z3_get_decl_num_parameters(e.ctx(), e.decl()) == 1);\n  auto addedBits = Z3_get_decl_int_parameter((e.ctx()), (e.decl()), 0);\n  auto tgt = Arg(e, 0);\n  auto ret = tgt.sext(addedBits);\n  assert(ret.width() == e.get_sort().bv_size());\n  return ret;\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitZERO_EXT(const z3::expr& e) {\n  assert(Z3_get_decl_num_parameters(e.ctx(), e.decl()) == 1);\n  auto added_bits = Z3_get_decl_int_parameter((e.ctx()), (e.decl()), 0);\n  auto tgt = Arg(e, 0);\n  auto ret = tgt.uext(added_bits);\n  assert(ret.width() == e.get_sort().bv_size());\n  return ret;\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBNOT(const z3::expr& n) {\n  assert(n.num_args() == 1);\n  BoolectorNodeWrapper ret(Arg(n,0));\n  ret = ~ret;\n  assert(ret.width() == n.get_sort().bv_size());\n  return ret;\n}\n\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBNEG(const z3::expr& n) {\n  assert(n.num_args() == 1);\n  BoolectorNodeWrapper ret(Arg(n,0));\n  ret = ret.negate();\n  assert(ret.width() == n.get_sort().bv_size());\n  return ret;\n}\n\nBTOR_BINARY_HANDLER(BSUB, Arg(n, 0) - Arg(n, 1));\nBTOR_BINARY_HANDLER(BMUL, Arg(n, 0) * Arg(n, 1));\nBTOR_BINARY_HANDLER(BUDIV, Arg(n, 0).udiv(Arg(n, 1)));\nBTOR_BINARY_HANDLER(BUDIV_I, Arg(n, 0).udiv(Arg(n, 1)));\nBTOR_BINARY_HANDLER(BSDIV, Arg(n, 0) / Arg(n, 1));\nBTOR_BINARY_HANDLER(BSDIV_I, Arg(n, 0) / Arg(n, 1));\nBTOR_BINARY_HANDLER(BSMOD, Arg(n, 0) % Arg(n, 1));\nBTOR_BINARY_HANDLER(BSMOD_I, Arg(n, 0) % Arg(n, 1));\nBTOR_BINARY_HANDLER(BSREM, Arg(n, 0).srem(Arg(n, 1)));\nBTOR_BINARY_HANDLER(BSREM_I, Arg(n, 0).srem(Arg(n, 1)));\nBTOR_BINARY_HANDLER(BUREM, Arg(n, 0).urem(Arg(n, 1)));\nBTOR_BINARY_HANDLER(BUREM_I, Arg(n, 0).urem(Arg(n, 1)));\nBTOR_BINARY_HANDLER(SLT, Arg(n, 0) < Arg(n, 1));\nBTOR_BINARY_HANDLER(SLEQ, Arg(n, 0) <= Arg(n, 1));\nBTOR_BINARY_HANDLER(SGT, Arg(n, 0) > Arg(n, 1));\nBTOR_BINARY_HANDLER(SGEQ, Arg(n, 0) >= Arg(n, 1));\nBTOR_BINARY_HANDLER(ULT, Arg(n, 0).ult(Arg(n, 1)));\nBTOR_BINARY_HANDLER(ULEQ, Arg(n, 0).ulte(Arg(n, 1)));\nBTOR_BINARY_HANDLER(UGT, Arg(n, 0).ugt(Arg(n, 1)));\nBTOR_BINARY_HANDLER(UGEQ, Arg(n, 0).ugte(Arg(n, 1)));\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBADD(const z3::expr& n) {\n  BoolectorNodeWrapper ret(Arg(n,0));\n  for (unsigned i = 1; i < n.num_args(); i++) {\n    ret = ret + Arg(n,i);\n  }\n  assert(!n.is_bv() || (static_cast<unsigned>(ret.width()) == n.get_sort().bv_size()));\n  return ret;\n}\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBXOR(const z3::expr& n) {\n  BoolectorNodeWrapper ret(Arg(n,0));\n  for (unsigned i = 1; i < n.num_args(); i++) {\n    ret = ret ^ Arg(n,i);\n  }\n  assert(ret.width() == n.get_sort().bv_size());\n  return ret;\n}\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBAND(const z3::expr& n) {\n  BoolectorNodeWrapper ret(Arg(n,0));\n  for (unsigned i = 1; i < n.num_args(); i++) {\n    ret = ret & Arg(n,i);\n  }\n  assert(ret.width() == n.get_sort().bv_size());\n  return ret;\n}\nBoolectorNodeWrapper Z3ToBtorRewriter::visitBOR(const z3::expr& n) {\n  BoolectorNodeWrapper ret(Arg(n,0));\n  for (unsigned i = 1; i < n.num_args(); i++) {\n    ret = ret | Arg(n,i);\n  }\n  assert(ret.width() == n.get_sort().bv_size());\n  return ret;\n}\n\nBTOR_BINARY_HANDLER(SELECT, read(Arg(n,0), Arg(n,1)));\nBTOR_TERNARY_HANDLER(STORE, write(Arg(n,0), Arg(n,1), Arg(n,2)));\n  \n#undef BTOR_BINARY_HANDLER\n#undef BTOR_TERNARY_HANDLER\n#undef BTOR_RASSOC_HANDLER\n\n}\n\nvoid mylog(const boolector::BoolectorNodeWrapper& n) {\n  cerr << n;\n}\n\n", "meta": {"hexsha": "5de13f7790e03b94f6b891009f960b438f19e1a1", "size": 32774, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/supp/boolector_supp.cc", "max_stars_repo_name": "dbueno/euforia", "max_stars_repo_head_hexsha": "1833ce6d6c645ca41fb21026ec87e896d9e5257d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-06T23:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T23:23:35.000Z", "max_issues_repo_path": "src/supp/boolector_supp.cc", "max_issues_repo_name": "dbueno/euforia", "max_issues_repo_head_hexsha": "1833ce6d6c645ca41fb21026ec87e896d9e5257d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/supp/boolector_supp.cc", "max_forks_repo_name": "dbueno/euforia", "max_forks_repo_head_hexsha": "1833ce6d6c645ca41fb21026ec87e896d9e5257d", "max_forks_repo_licenses": ["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.774, "max_line_length": 228, "alphanum_fraction": 0.6418807591, "num_tokens": 9636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934933647101647, "lm_q2_score": 0.037892423505945697, "lm_q1q2_score": 0.00906952642342685}}
{"text": "#pragma once\n\n#include <boost/graph/bipartite.hpp>\n#include <boost/graph/detail/set_adaptor.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <vector>\n\n#include \"matroid_graph.hpp\"\n#include \"graph_utils.hpp\"\n\n#include <boost/graph/adjacency_list_io.hpp>\n\nnamespace tu\n{\n\n  /**\n   * Finds a matroid element which is parallel to a row element in minor of a given matroid or\n   * a unit vector in a column element in the minor.\n   *\n   * @param matroid The given matroid\n   * @param matrix Representation matrix of the given matroid\n   * @param minor_height Number of rows of the minor\n   * @param minor_width Number of columns of the minor\n   * @param row The element must be parallel to this row (along the minor)\n   * @return The matroid element that was found to be parallel / unit vector\n   */\n\n  template <typename MatroidType, typename MatrixType>\n  int find_parallel_to_row(const MatroidType& matroid, const MatrixType& matrix, const size_t minor_height,\n      const size_t minor_width, const size_t row)\n  {\n    /// Look for unit vector\n    size_t last = 0;\n    size_t count = 0;\n    for (size_t c = 0; c < minor_width; ++c)\n    {\n      if (matrix(row, c) != 0)\n      {\n        last = c;\n        ++count;\n      }\n    }\n    if (count == 1)\n      return matroid.name2(last);\n\n    /// Check for parallel\n    for (size_t r = 0; r < minor_height; ++r)\n    {\n      bool same = true;\n      for (size_t c = 0; c < minor_width; ++c)\n      {\n        if (matrix(r, c) != matrix(row, c))\n        {\n          same = false;\n          break;\n        }\n      }\n      if (same)\n      {\n        return matroid.name1(r);\n      }\n    }\n\n    throw std::logic_error(\"find_parallel_to_row did not find any parallel / unit vector!\");\n  }\n\n  /**\n   * A filter for a graph which excludes some edges and a given vertex\n   */\n\n  template <typename Graph>\n  struct articulation_edge_filter\n  {\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef typename boost::graph_traits<Graph>::edge_descriptor edge_descriptor;\n    typedef std::set<edge_descriptor> edge_set;\n\n    /**\n     * Constructs the filter.\n     */\n\n    articulation_edge_filter() :\n      graph_(NULL), articulation_vertex_(NULL), evil_edges_(NULL)\n    {\n    }\n\n    /**\n     * Constructs the filter\n     *\n     * @param graph The original graph\n     * @param articulation_vertex The excluded vertex\n     * @param evil_edges The set of excluded edges\n     */\n\n    articulation_edge_filter(const Graph* graph, const vertex_descriptor* articulation_vertex,\n        const edge_set* evil_edges) :\n      graph_(graph), articulation_vertex_(articulation_vertex), evil_edges_(evil_edges)\n    {\n    }\n\n    /**\n     * Filter operator\n     *\n     * @param e The edge to be considered\n     * @return true if and only if this edge is included in the filtered graph\n     */\n\n    template <typename Edge>\n    bool operator()(const Edge& e) const\n    {\n      if (evil_edges_->find(e) != evil_edges_->end())\n        return false;\n\n      if (boost::source(e, *graph_) == *articulation_vertex_)\n        return false;\n\n      if (boost::target(e, *graph_) == *articulation_vertex_)\n        return false;\n\n      return true;\n    }\n\n  private:\n    const Graph* graph_;\n    const vertex_descriptor* articulation_vertex_;\n    const edge_set* evil_edges_;\n  };\n\n  /**\n   * Constructs an articulation edge filter for a given graph.\n   *\n   * @param graph The given graph\n   * @param articulation_vertex Vertex to be excluded\n   * @param evil_edges Edges to be excluded\n   * @return The constructed filter\n   */\n\n  template <typename Graph, typename Vertex, typename EdgeSet>\n  inline struct articulation_edge_filter<Graph> make_articulation_edge_filter(const Graph* graph,\n      const Vertex* articulation_vertex, const EdgeSet* evil_edges)\n  {\n    return articulation_edge_filter<Graph> (graph, articulation_vertex, evil_edges);\n  }\n\n  /**\n   * Tries to extend a 3-connected graph of a graphic minor or detects that\n   * the extended minor is not graphic.\n   *\n   * @param graph The graph of the graphic minor\n   * @param matroid The matroid\n   * @param matrix Representation matrix of the matroid\n   * @param minor_height Number of row elements of the minor\n   * @param minor_width Number of column elements of the minor\n   * @param extension_type Type of the extension\n   * @return true if and only if the extension was possible.\n   */\n\n  template <typename MatroidType, typename MatrixType>\n  bool extend_graph(matroid_graph& graph, const MatroidType& matroid, const MatrixType& matrix,\n      const size_t minor_height, const size_t minor_width, const nested_minor_sequence::extension_type extension_type)\n  {\n    typedef boost::graph_traits<matroid_graph> traits;\n\n    matroid_element_map element_map = boost::get(edge_matroid_element, graph);\n    std::map<int, traits::edge_descriptor> reverse_element_map;\n\n    typename traits::edge_iterator edge_iter, edge_end;\n    for (boost::tie(edge_iter, edge_end) = boost::edges(graph); edge_iter != edge_end; ++edge_iter)\n    {\n      reverse_element_map[element_map[*edge_iter]] = *edge_iter;\n    }\n\n    /// Distinct extension cases\n    switch (extension_type)\n    {\n    case nested_minor_sequence::TWO_ROWS_ONE_COLUMN:\n    {\n      int first_edge_element = find_parallel_to_row(matroid, matrix, minor_height, minor_width, minor_height);\n      int second_edge_element = find_parallel_to_row(matroid, matrix, minor_height, minor_width, minor_height + 1);\n\n      /// Find vertices of corresponding edges\n\n      traits::vertex_descriptor first_vertex1 = boost::source(reverse_element_map[first_edge_element], graph);\n      traits::vertex_descriptor first_vertex2 = boost::target(reverse_element_map[first_edge_element], graph);\n      traits::vertex_descriptor second_vertex1 = boost::source(reverse_element_map[second_edge_element], graph);\n      traits::vertex_descriptor second_vertex2 = boost::target(reverse_element_map[second_edge_element], graph);\n\n      if (first_vertex1 == second_vertex2)\n        std::swap(second_vertex1, second_vertex2);\n      if (first_vertex2 == second_vertex1)\n        std::swap(first_vertex1, first_vertex2);\n      if (first_vertex2 == second_vertex2)\n      {\n        std::swap(first_vertex1, first_vertex2);\n        std::swap(second_vertex1, second_vertex2);\n      }\n      if (first_vertex1 != second_vertex1)\n        return false;\n\n      /// Remove old edges\n\n      boost::remove_edge(reverse_element_map[first_edge_element], graph);\n      boost::remove_edge(reverse_element_map[second_edge_element], graph);\n\n      /// Create new vertices\n\n      traits::vertex_descriptor first_breaker = boost::add_vertex(graph);\n      traits::vertex_descriptor second_breaker = boost::add_vertex(graph);\n\n      /// Create new edges\n\n      boost::add_edge(first_vertex2, first_breaker, first_edge_element, graph);\n      boost::add_edge(first_breaker, first_vertex1, matroid.name1(minor_height), graph);\n      boost::add_edge(second_vertex2, second_breaker, second_edge_element, graph);\n      boost::add_edge(second_breaker, second_vertex1, matroid.name1(minor_height + 1), graph);\n      boost::add_edge(first_breaker, second_breaker, matroid.name2(minor_width), graph);\n\n      return true;\n    }\n    break;\n    case nested_minor_sequence::ONE_ROW_TWO_COLUMNS:\n    {\n      int first_edge_element = find_parallel_to_row(make_transposed_matroid(matroid), make_transposed_matrix(matrix),\n          minor_width, minor_height, minor_width);\n      int second_edge_element = find_parallel_to_row(make_transposed_matroid(matroid), make_transposed_matrix(matrix),\n          minor_width, minor_height, minor_width + 1);\n\n      /// Find vertices of corresponding edges\n\n      traits::vertex_descriptor first_vertex1 = boost::source(reverse_element_map[first_edge_element], graph);\n      traits::vertex_descriptor first_vertex2 = boost::target(reverse_element_map[first_edge_element], graph);\n      traits::vertex_descriptor second_vertex1 = boost::source(reverse_element_map[second_edge_element], graph);\n      traits::vertex_descriptor second_vertex2 = boost::target(reverse_element_map[second_edge_element], graph);\n\n      if (first_vertex1 == second_vertex2)\n        std::swap(second_vertex1, second_vertex2);\n      if (first_vertex2 == second_vertex1)\n        std::swap(first_vertex1, first_vertex2);\n      if (first_vertex2 == second_vertex2)\n      {\n        std::swap(first_vertex1, first_vertex2);\n        std::swap(second_vertex1, second_vertex2);\n      }\n      if (first_vertex1 != second_vertex1)\n        return false;\n\n      /// Create new vertex\n\n      traits::vertex_descriptor additional_vertex = boost::add_vertex(graph);\n\n      /// Create new edges\n\n      boost::add_edge(first_vertex2, additional_vertex, matroid.name2(minor_width), graph);\n      boost::add_edge(second_vertex2, additional_vertex, matroid.name2(minor_width + 1), graph);\n      boost::add_edge(first_vertex1, additional_vertex, matroid.name1(minor_height), graph);\n\n      return true;\n    }\n    break;\n    case nested_minor_sequence::ONE_ROW_ONE_COLUMN:\n    {\n      int row_edge_element = find_parallel_to_row(matroid, matrix, minor_height, minor_width, minor_height);\n      int column_edge_element = find_parallel_to_row(make_transposed_matroid(matroid), make_transposed_matrix(matrix),\n          minor_width, minor_height, minor_width);\n\n      /// Find vertices of corresponding edges\n\n      traits::vertex_descriptor row_vertex1 = boost::source(reverse_element_map[row_edge_element], graph);\n      traits::vertex_descriptor row_vertex2 = boost::target(reverse_element_map[row_edge_element], graph);\n      traits::vertex_descriptor column_vertex1 = boost::source(reverse_element_map[column_edge_element], graph);\n      traits::vertex_descriptor column_vertex2 = boost::target(reverse_element_map[column_edge_element], graph);\n\n      if (row_vertex1 == column_vertex2)\n        std::swap(column_vertex1, column_vertex2);\n      if (row_vertex2 == column_vertex1)\n        std::swap(row_vertex1, row_vertex2);\n      if (row_vertex2 == column_vertex2)\n      {\n        std::swap(row_vertex1, row_vertex2);\n        std::swap(column_vertex1, column_vertex2);\n      }\n      if (row_vertex1 != column_vertex1)\n        return false;\n\n      /// Remove old edges\n\n      boost::remove_edge(reverse_element_map[row_edge_element], graph);\n\n      /// Create new vertex\n\n      traits::vertex_descriptor row_breaker = boost::add_vertex(graph);\n\n      /// Create new edges\n\n      boost::add_edge(row_vertex2, row_breaker, row_edge_element, graph);\n      boost::add_edge(row_breaker, row_vertex1, matroid.name1(minor_height), graph);\n      boost::add_edge(row_breaker, column_vertex2, matroid.name2(minor_width), graph);\n\n      return true;\n    }\n    break;\n    case nested_minor_sequence::ONE_COLUMN:\n    {\n      typedef std::set<traits::edge_descriptor> edge_set_t;\n      typedef boost::filtered_graph<matroid_graph, boost::is_in_subset<edge_set_t> > edge_subset_graph_t;\n\n      edge_set_t edge_set;\n\n      for (size_t r = 0; r < minor_height; ++r)\n      {\n        if (matrix(r, minor_width) == 1)\n          edge_set.insert(reverse_element_map[matroid.name1(r)]);\n      }\n\n      /// Check if edges form a path\n      std::vector<traits::vertex_descriptor> path;\n\n      edge_subset_graph_t edge_subset_graph(graph, boost::is_in_subset<edge_set_t>(edge_set));\n      if (!tu::util::is_path(edge_subset_graph, boost::get(boost::vertex_index, edge_subset_graph), path))\n      {\n        return false;\n      }\n\n      boost::add_edge(path[0], path[path.size() - 1], matroid.name2(minor_width), graph);\n      return true;\n    }\n    break;\n    case nested_minor_sequence::ONE_ROW:\n    {\n      typedef traits::edge_descriptor edge_t;\n      typedef traits::vertex_descriptor vertex_t;\n      typedef std::set<vertex_t> vertex_set;\n      typedef std::set<edge_t> edge_set;\n      typedef std::vector<vertex_t> vertex_vector_t;\n      typedef std::vector<edge_t> edge_vector_t;\n\n      typedef boost::vec_adj_list_vertex_id_map<boost::no_property, traits::vertices_size_type> IndexMap;\n      IndexMap index_map = boost::get(boost::vertex_index, graph);\n\n      /// Collect all 1-edges\n\n      edge_set one_edges;\n      for (size_t c = 0; c < minor_width; ++c)\n      {\n        if (matrix(minor_height, c) != 0)\n          one_edges.insert(reverse_element_map[matroid.name2(c)]);\n      }\n\n      traits::vertex_descriptor the_vertex = traits::null_vertex();\n      if (tu::util::find_star_vertex(boost::make_filtered_graph(graph, boost::is_in_subset<edge_set>(one_edges)),\n          the_vertex))\n      {\n        /// Create the new vertex and connect it with the_vertex.\n\n        traits::vertex_descriptor new_vertex = boost::add_vertex(graph);\n        boost::add_edge(the_vertex, new_vertex, matroid.name1(minor_height), graph);\n\n        /// Reconnect the 1-edges\n\n        for (edge_set::const_iterator edge_iter = one_edges.begin(); edge_iter != one_edges.end(); ++edge_iter)\n        {\n          traits::edge_descriptor edge = *edge_iter;\n          traits::vertex_descriptor other_vertex = boost::source(edge, graph);\n          if (other_vertex == the_vertex)\n            other_vertex = boost::target(edge, graph);\n          int name = element_map[edge];\n          boost::remove_edge(the_vertex, other_vertex, graph);\n          boost::add_edge(new_vertex, other_vertex, name, graph);\n        }\n\n        return true;\n      }\n\n      /// Count for each vertex the number of paths that use it\n\n      std::vector<size_t> common_vertex_count(boost::num_vertices(graph), 0);\n      for (size_t c = 0; c < minor_width; ++c)\n      {\n        if (matrix(minor_height, c) == 0)\n          continue;\n\n        edge_set edges;\n        for (size_t r = 0; r < minor_height; ++r)\n        {\n          if (matrix(r, c) == 1)\n            edges.insert(reverse_element_map[matroid.name1(r)]);\n        }\n\n        vertex_set vertices;\n        tu::util::used_vertices(boost::make_filtered_graph(graph, boost::is_in_subset<edge_set>(edges)), vertices);\n\n        for (typename vertex_set::const_iterator iter = vertices.begin(); iter != vertices.end(); ++iter)\n        {\n          common_vertex_count[boost::get(index_map, *iter)]++;\n        }\n      }\n\n      /// Find articulation points for the graph without 1-edges\n\n      vertex_vector_t articulation_points;\n      boost::articulation_points(boost::make_filtered_graph(graph, boost::is_not_in_subset<edge_set>(one_edges)),\n          std::back_inserter(articulation_points));\n\n      std::vector<traits::vertex_descriptor> the_vertex_candidates;\n      the_vertex = traits::null_vertex();\n      for (vertex_vector_t::const_iterator iter = articulation_points.begin(); iter != articulation_points.end();\n          ++iter)\n      {\n        if (common_vertex_count[boost::get(index_map, *iter)] == one_edges.size())\n        {\n          the_vertex_candidates.push_back(*iter);\n        }\n      }\n\n      if (the_vertex_candidates.empty() || the_vertex_candidates.size() > 2)\n        return false;\n\n      for (vertex_vector_t::const_iterator iter = the_vertex_candidates.begin(); iter != the_vertex_candidates.end();\n          ++iter)\n      {\n        the_vertex = *iter;\n\n        /// Filter the chosen articulation point and the one-edges and check the remaining graph\n\n        vertex_set articulation_set;\n        articulation_set.insert(the_vertex);\n        std::vector<size_t> component_vector(boost::num_vertices(graph));\n\n        size_t num_components = boost::connected_components(\n            boost::make_filtered_graph(graph, make_articulation_edge_filter(&graph, &the_vertex, &one_edges),\n                boost::is_not_in_subset<vertex_set>(articulation_set)),\n            boost::make_iterator_property_map(component_vector.begin(), index_map));\n\n        /// We should really have articulation point + 2 further components\n        assert(num_components >= 2);\n\n        typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> component_graph_t;\n        component_graph_t component_graph(num_components);\n\n        bool abort = false;\n        for (typename edge_set::const_iterator iter = one_edges.begin(); iter != one_edges.end(); ++iter)\n        {\n          typename boost::graph_traits<component_graph_t>::vertex_descriptor source, target;\n          source = boost::source(*iter, graph);\n          target = boost::target(*iter, graph);\n          if (source == the_vertex || target == the_vertex)\n            continue;\n\n          size_t source_component = component_vector[boost::get(index_map, source)];\n          size_t target_component = component_vector[boost::get(index_map, target)];\n\n          if (source_component == target_component)\n          {\n            /// There cannot be a 1-edge inside one component.\n            abort = true;\n            break;\n          }\n\n          boost::add_edge(boost::vertex(source_component, component_graph),\n              boost::vertex(target_component, component_graph), component_graph);\n        }\n\n        if (abort)\n          continue;\n\n        boost::one_bit_color_map<boost::vec_adj_list_vertex_id_map<boost::no_property, traits::vertices_size_type> > bipartition(\n            num_components, boost::get(boost::vertex_index, component_graph));\n\n        if (!boost::is_bipartite(component_graph, boost::get(boost::vertex_index, component_graph), bipartition))\n        {\n          continue;\n        }\n\n        for (size_t i = 0; i < component_vector.size(); ++i)\n        {\n          if (boost::vertex(i, graph) == the_vertex)\n            continue;\n        }\n\n        vertex_t new_vertex = boost::add_vertex(graph);\n\n        edge_vector_t reconnect_edges;\n        typename traits::out_edge_iterator out_edge_iter, out_edge_end;\n        for (boost::tie(out_edge_iter, out_edge_end) = boost::incident_edges(the_vertex, graph);\n            out_edge_iter != out_edge_end; ++out_edge_iter)\n        {\n          vertex_t incident_vertex = boost::target(*out_edge_iter, graph);\n\n          bool reconnect = boost::get(bipartition,\n              boost::vertex(component_vector[boost::get(index_map, incident_vertex)], component_graph))\n              != boost::one_bit_white;\n\n          if (one_edges.find(*out_edge_iter) != one_edges.end())\n            reconnect = !reconnect;\n\n          if (reconnect)\n            reconnect_edges.push_back(*out_edge_iter);\n        }\n\n        for (typename edge_vector_t::const_iterator iter = reconnect_edges.begin(); iter != reconnect_edges.end();\n            ++iter)\n        {\n          util::reconnect_edge(graph, *iter, the_vertex, new_vertex);\n        }\n\n        boost::add_edge(the_vertex, new_vertex, matroid.name1(minor_height), graph);\n\n        return true;\n      }\n\n      return false;\n    }\n    break;\n    default:\n      throw std::logic_error(\"Unknown extension in graphicness test.\");\n    }\n  }\n\n  /**\n   * Either constructs a graph whose forest matroid is the given matroid or detects\n   * that the given matroid is non-graphic.\n   *\n   * @param matroid The given matroid\n   * @param matrix Representation matrix of the given matroid\n   * @param nested_minors Sequence of nested minors\n   * @return The constructed graph or NULL if the matroid is not graphic.\n   */\n\n  template <typename MatroidType, typename MatrixType, typename NestedMinorSequenceType>\n  matroid_graph* construct_matroid_graph(const MatroidType& matroid, const MatrixType& matrix,\n      const NestedMinorSequenceType& nested_minors, size_t& largest_graphic_minor)\n  {\n    typedef boost::graph_traits<matroid_graph>::vertex_descriptor vertex_descriptor;\n\n    /// Initialize W3\n\n    largest_graphic_minor = 0;\n    matroid_graph* graph = new matroid_graph(4);\n\n    vertex_descriptor center_vertex = boost::vertex(0, *graph);\n    vertex_descriptor border_vertex1 = boost::vertex(1, *graph);\n    vertex_descriptor border_vertex2 = boost::vertex(2, *graph);\n    vertex_descriptor border_vertex3 = boost::vertex(3, *graph);\n\n    boost::add_edge(center_vertex, border_vertex1, matroid.name1(0), *graph).first;\n    boost::add_edge(center_vertex, border_vertex2, matroid.name1(1), *graph).first;\n    boost::add_edge(center_vertex, border_vertex3, matroid.name2(2), *graph).first;\n    boost::add_edge(border_vertex1, border_vertex2, matroid.name2(0), *graph).first;\n    boost::add_edge(border_vertex1, border_vertex3, matroid.name2(1), *graph).first;\n    boost::add_edge(border_vertex2, border_vertex3, matroid.name1(2), *graph).first;\n\n    size_t minor_height = 3;\n    size_t minor_width = 3;\n\n    for (size_t i = 0; i < nested_minors.size(); ++i)\n    {\n      if (!extend_graph(*graph, matroid, matrix, minor_height, minor_width, nested_minors.get_extension(i)))\n      {\n        delete graph;\n        return NULL;\n      }\n\n      minor_height += nested_minors.get_extension_height(i);\n      minor_width += nested_minors.get_extension_width(i);\n      largest_graphic_minor++;\n    }\n\n    return graph;\n  }\n\n} /* namespace tu */\n", "meta": {"hexsha": "937c5f1afeea822c32a52d9ea19f269f3de2a733", "size": 21012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cmr/graphicness.hpp", "max_stars_repo_name": "discopt/cmr", "max_stars_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-04-13T12:48:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T11:56:31.000Z", "max_issues_repo_path": "src/cmr/graphicness.hpp", "max_issues_repo_name": "xammy/unimodularity-test", "max_issues_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-19T09:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-27T23:18:47.000Z", "max_forks_repo_path": "src/cmr/graphicness.hpp", "max_forks_repo_name": "discopt/cmr", "max_forks_repo_head_hexsha": "669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09", "max_forks_repo_licenses": ["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.5426086957, "max_line_length": 129, "alphanum_fraction": 0.6812773653, "num_tokens": 4821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.020332353157149086, "lm_q1q2_score": 0.00905866384836502}}
{"text": "//=============================================================================================================\n/**\n* @file     adaptivemp.cpp\n* @author   Martin Henfling <martin.henfling@tu-ilmenau.de>\n*           Daniel Knobl <daniel.knobl@tu-ilmenau.de>\n*\n* @version  1.0\n* @date     July, 2014\n*\n* @section  LICENSE\n*\n* Copyright (C) 2014, Daniel Knobl and Martin Henfling All rights reserved.\n*\n* ported to mne-cpp by Martin Henfling and Daniel Knobl in May 2014\n* original code was implemented in Matlab Code by Maciej Gratkowski\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    Implemetation of the Matching Pursuit Algorithm introduced by Stephane Mallat and Zhifeng Zhang.\n*           Matlabimplemetation of Maciej Gratkowski is used as Source and reference.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"adaptivemp.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// STL INCLUDES\n//=============================================================================================================\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <unsupported/Eigen/FFT>\n#include <Eigen/SparseCore>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Qt INCLUDES\n//=============================================================================================================\n\n#include <QFuture>\n#include <QtConcurrent>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace UTILSLIB;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nAdaptiveMp::AdaptiveMp()\n: it(0)\n, max_it(0)\n, signal_energy(0)\n, current_energy(0)\n, fix_phase(0)\n, epsilon(0)\n, max_iterations(0)\n{\n\n}\n\n//*************************************************************************************************************\n\nQList<QList<GaborAtom> > AdaptiveMp::matching_pursuit(MatrixXd signal, qint32 max_iterations, qreal epsilon, bool fix_phase = false, qint32 boost = 0,\n                                                      qint32 simplex_it = 1E3, qreal simplex_reflection = 1.0, qreal simplex_expansion = 0.2 ,\n                                                      qreal simplex_contraction = 0.5, qreal simplex_full_contraction = 0.5, bool trial_separation = false)\n{\n    //stop_running = false;\n    std::cout << \"\\nAdaptive Matching Pursuit Algorithm started...\\n\";\n\n    max_it = max_iterations;\n    Eigen::FFT<double> fft;\n    MatrixXd residuum = signal; //residuum initialised with signal\n    qint32 sample_count = signal.rows();\n    qint32 channel_count = signal.cols();\n\n    signal_energy = 0;\n    qreal residuum_energy = 0;\n    qreal energy_threshold = 0;\n\n    //calculate signal_energy\n    for(qint32 channel = 0; channel < channel_count; channel++)\n    {\n        for(qint32 sample = 0; sample < sample_count; sample++)\n            signal_energy += (signal(sample, channel) * signal(sample, channel));\n\n        energy_threshold = 0.01 * epsilon * signal_energy;\n        residuum_energy = signal_energy;\n    }\n    std::cout << \"absolute energy of signal: \" << residuum_energy << \"\\n\";\n\n    while(it < max_iterations && (energy_threshold < residuum_energy) && sample_count > 1)\n    {\n        channel_count = channel_count * (boost / 100.0); //reducing the number of observed channels in the algorithm to increase speed performance\n        if(boost == 0 || channel_count == 0)\n            channel_count = 1;\n\n        //variables for dyadic sampling\n        qreal s = 1;                             //scale\n        qint32 j = 1;\n        VectorXd max_scalar_product = VectorXd::Zero(channel_count);            //inner product for choosing the best matching atom\n        qreal k = 0;                             //for modulation 2*pi*k/N\n        qint32 p = floor(sample_count / 2);      //translation\n        GaborAtom *gabor_Atom = new GaborAtom();\n        gabor_Atom->sample_count = sample_count;\n        gabor_Atom->energy = 0;\n        qreal phase = 0;\n\n        while(s < sample_count)\n        {\n            k = 0;                               //for modulation 2*pi*k/N\n            p = floor(sample_count / 2);         //translation\n            VectorXd envelope = GaborAtom::gauss_function(sample_count, s, p);\n            VectorXcd fft_envelope = RowVectorXcd::Zero(sample_count);\n            fft.fwd(fft_envelope, envelope);\n\n            while(k < sample_count/2)\n            {\n                p = floor(sample_count/2);\n                VectorXcd modulation = modulation_function(sample_count, k);\n                VectorXcd modulated_resid = VectorXcd::Zero(sample_count);\n                VectorXcd fft_modulated_resid = VectorXcd::Zero(sample_count);\n                VectorXcd fft_m_e_resid = VectorXcd::Zero(sample_count);\n                VectorXd corr_coeffs = VectorXd::Zero(sample_count);\n\n                //iteration for multichannel, depending on boost setting\n                for(qint32 chn = 0; chn < channel_count; chn++)\n                {\n                    qint32 max_index = 0;\n                    qreal maximum = 0;\n                    phase = 0;\n                    p = floor(sample_count/2);//here is difference to dr. gratkowski´s code (he didn´t reset parameter p)\n\n                    //complex correlation of signal and sinus-modulated gaussfunction\n                    for(qint32 l = 0; l< sample_count; l++)\n                        modulated_resid[l] = residuum(l, chn) * modulation[l];\n\n                    fft.fwd(fft_modulated_resid, modulated_resid);\n\n                    for( qint32 m = 0; m < sample_count; m++)\n                        fft_m_e_resid[m] = fft_modulated_resid[m] * conj(fft_envelope[m]);\n\n                    fft.inv(corr_coeffs, fft_m_e_resid);\n                    maximum = corr_coeffs[0];\n\n                    //find index of maximum correlation-coefficient to use in translation\n                    for(qint32 i = 1; i < corr_coeffs.rows(); i++)\n                        if(maximum < corr_coeffs[i])\n                        {\n                            maximum = corr_coeffs[i];\n                            max_index = i;\n                        }\n\n                    //adapting translation p to create atomtranslation correctly\n                    if(max_index >= p) p = max_index - p + 1;\n                    else p = max_index + p;\n\n                    VectorXd atom_parameters = calculate_atom(sample_count, s, p, k, chn, residuum, RETURNPARAMETERS, fix_phase);\n                    qreal temp_scalar_product = 0;\n                    if(trial_separation) temp_scalar_product = max_scalar_product[chn];\n                    else temp_scalar_product = max_scalar_product[0];\n\n                    if(std::fabs(atom_parameters[4]) >= std::fabs(temp_scalar_product))\n                    {\n                        //set highest scalarproduct, in comparison to best matching atom\n                        gabor_Atom->scale              = atom_parameters[0];\n                        gabor_Atom->translation        = atom_parameters[1];\n                        gabor_Atom->modulation         = atom_parameters[2];\n                        gabor_Atom->phase              = atom_parameters[3];\n                        gabor_Atom->max_scalar_product = atom_parameters[4];\n                        gabor_Atom->bm_channel         = chn;\n\n                        if(trial_separation)\n                        {\n                            max_scalar_product[chn]    = atom_parameters[4];\n\n                            if(atoms_in_chns.length() < channel_count)\n                                atoms_in_chns.append(*gabor_Atom);\n                            else\n                                atoms_in_chns.replace(chn, *gabor_Atom);\n                        }\n                        else\n                            max_scalar_product[0]      = atom_parameters[4];\n\n                    }\n\n                }\n                k += pow(2.0,(-j))*sample_count/2;\n\n            }\n            j++;\n            s = pow(2.0,j);\n        }\n        std::cout << \"\\n\" << \"===============\" << \" found parameters \" << it + 1 << \"===============\" << \":\\n\\n\"<<\n                     \"scale: \" << gabor_Atom->scale << \" trans: \" << gabor_Atom->translation <<\n                     \" modu: \" << gabor_Atom->modulation << \" phase: \" << gabor_Atom->phase << \" sclr_prdct: \" << gabor_Atom->max_scalar_product << \"\\n\";\n\n        //replace atoms with s==N and p = floor(N/2) by such atoms that do not have an envelope\n        k = 0;\n        s = sample_count;\n        p = floor(sample_count / 2);\n        j = floor(log10(sample_count)/log10(2));//log(sample_count) / log(2));\n        phase = 0;\n\n        //iteration for multichannel, depending on boost setting\n        for(qint32 chn = 0; chn < channel_count; chn++)\n        {\n            k = 0;\n\n            while(k < sample_count / 2)\n            {\n                VectorXd parameters_no_envelope = calculate_atom(sample_count, s, p, k, chn, residuum, RETURNPARAMETERS, fix_phase);\n\n                qreal temp_scalar_product = 0;\n                if(trial_separation) temp_scalar_product = max_scalar_product[chn];\n                else temp_scalar_product = max_scalar_product[0];\n                if(std::fabs(parameters_no_envelope[4]) > std::fabs(temp_scalar_product))\n                {\n                    //set highest scalarproduct, in comparison to best matching atom\n\n                    gabor_Atom->scale              = parameters_no_envelope[0];\n                    gabor_Atom->translation        = parameters_no_envelope[1];\n                    gabor_Atom->modulation         = parameters_no_envelope[2];\n                    gabor_Atom->phase              = parameters_no_envelope[3];\n                    gabor_Atom->max_scalar_product = parameters_no_envelope[4];\n                    gabor_Atom->bm_channel         = chn;\n\n                    if(trial_separation)\n                    {\n                        max_scalar_product[chn]    = parameters_no_envelope[4];\n                        atoms_in_chns.replace(chn, *gabor_Atom);\n                    }\n                    else\n                        max_scalar_product[0]      = parameters_no_envelope[4];\n\n                }\n                k += pow(2.0,(-j))*sample_count/2;\n\n            }\n\n        }\n        std::cout << \"      after comparison to NoEnvelope \" << \":\\n\"<< \"scale: \" << gabor_Atom->scale << \" trans: \" << gabor_Atom->translation <<\n                     \" modu: \" << gabor_Atom->modulation << \" phase: \" << gabor_Atom->phase << \" sclr_prdct: \" << gabor_Atom->max_scalar_product << \"\\n\\n\";\n\n        //simplexfunction to find minimum of target among parameters s, p, k\n\n        if(trial_separation && simplex_it != 0)\n        {\n            for(qint32 chn = 0; chn < atoms_in_chns.length(); chn++)\n            {\n                *gabor_Atom = atoms_in_chns.at(chn);\n                simplex_maximisation(simplex_it, simplex_reflection, simplex_expansion, simplex_contraction, simplex_full_contraction,\n                                     gabor_Atom, max_scalar_product, sample_count, fix_phase, residuum, trial_separation, chn);\n\n            }\n        }\n        else if(simplex_it != 0)\n            simplex_maximisation(simplex_it, simplex_reflection, simplex_expansion, simplex_contraction, simplex_full_contraction,\n                                 gabor_Atom, max_scalar_product, sample_count, fix_phase, residuum, trial_separation, gabor_Atom->bm_channel);\n\n        //calc multichannel parameters phase and max_scalar_product\n        channel_count = signal.cols();\n        VectorXd best_match = VectorXd::Zero(sample_count);\n\n\n        for(qint32 chn = 0; chn < channel_count; chn++)\n        {\n\n            if(trial_separation)\n            {\n                *gabor_Atom = atoms_in_chns.at(chn);\n                gabor_Atom->energy = 0;\n                best_match = gabor_Atom->create_real(gabor_Atom->sample_count, gabor_Atom->scale, gabor_Atom->translation,\n                                                     gabor_Atom->modulation, gabor_Atom->phase);\n            }\n            else\n            {\n                VectorXd channel_params = calculate_atom(sample_count, gabor_Atom->scale, gabor_Atom->translation,\n                                                         gabor_Atom->modulation, chn, residuum, RETURNPARAMETERS, fix_phase);\n                gabor_Atom->phase_list.append(channel_params[3]);\n\n                gabor_Atom->max_scalar_list.append(channel_params[4]);\n\n                best_match = gabor_Atom->create_real(gabor_Atom->sample_count, gabor_Atom->scale, gabor_Atom->translation,\n                                                     gabor_Atom->modulation, gabor_Atom->phase_list.at(chn));\n            }\n\n            //substract best matching Atom from Residuum in each channel\n            for(qint32 j = 0; j < gabor_Atom->sample_count; j++)\n            {\n                if(!trial_separation)\n                {\n                    residuum(j,chn) -= gabor_Atom->max_scalar_list.at(chn) * best_match[j];\n                    gabor_Atom->energy += pow(gabor_Atom->max_scalar_list.at(chn) * best_match[j], 2);\n                }\n                else\n                {\n                    residuum(j,chn) -= gabor_Atom->max_scalar_product * best_match[j];\n                    gabor_Atom->energy += pow(gabor_Atom->max_scalar_product * best_match[j], 2);\n                }\n            }\n            if(trial_separation)\n            {\n                atoms_in_chns.replace(chn, *gabor_Atom);            // change energy\n                residuum_energy -= atoms_in_chns.at(chn).energy;// / channel_count;;\n                current_energy  += atoms_in_chns.at(chn).energy;// / channel_count;;\n            }\n        }\n\n        if(!trial_separation)\n        {\n            residuum_energy -= gabor_Atom->energy;\n            current_energy  += gabor_Atom->energy;\n        }\n        else\n            /*for(qint32 i = 0; i < atoms_in_chns.length(); i++)\n            {\n                residuum_energy -= atoms_in_chns.at(i).energy / channel_count;\n                current_energy  += atoms_in_chns.at(i).energy / channel_count;\n            }*/\n\n        std::cout << \"absolute energy of residue: \" << residuum_energy << \"\\n\";\n\n        if(!trial_separation)\n            atoms_in_chns.append(*gabor_Atom);\n\n        atom_list.append(atoms_in_chns);\n\n        atoms_in_chns.clear();\n        delete gabor_Atom;\n        it++;\n\n        emit current_result(it, max_it, current_energy, signal_energy, residuum, atom_list, fix_dict_list);\n\n        if( QThread::currentThread()->isInterruptionRequested())\n        {\n            send_warning(10);\n            break;\n        }\n\n    }//end iterations\n    std::cout << \"\\nAdaptive Matching Pursuit Algorithm finished.\\n\";\n    emit finished_calc();\n    return atom_list;\n}\n\n//*************************************************************************************************************\n\nVectorXcd AdaptiveMp::modulation_function(qint32 N, qreal k)\n{\n    VectorXcd modulation = VectorXcd::Zero(N);\n\n    for(qint32 n = 0; n < N; n++)\n    {\n        modulation[n] = std::polar(1 / sqrt(qreal(N)), 2 * PI * k / qreal(N) * qreal(n));\n    }\n    return modulation;\n}\n\n//*************************************************************************************************************\n\nVectorXd AdaptiveMp::calculate_atom(qint32 sample_count, qreal scale, qint32 translation, qreal modulation, qint32 channel, MatrixXd residuum, ReturnValue return_value = RETURNATOM, bool fix_phase = false)\n{\n    GaborAtom *gabor_Atom = new GaborAtom();\n    qreal phase = 0;\n    //create complex Gaboratom\n    VectorXcd complex_gabor_atom = gabor_Atom->create_complex(sample_count, scale, translation, modulation);\n\n    //calculate Inner Product: preparation to find the parameter phase\n    std::complex<double> inner_product(0, 0);\n\n    if(fix_phase == false)\n    {\n        for(qint32 i = 0; i < sample_count; i++)\n            inner_product += residuum(i, channel) * conj(complex_gabor_atom[i]);\n    }\n    else\n    {\n        for(qint32 chn = 0; chn < residuum.cols(); chn++)\n        {\n            for(qint32 i = 0; i < sample_count; i++)\n                inner_product += residuum(i, chn) * conj(complex_gabor_atom[i]);\n        }\n        if(residuum.cols() != 0)\n            inner_product /= residuum.cols();\n    }\n\n    //calculate phase to create realGaborAtoms\n    phase = std::arg(inner_product);\n    if (phase < 0) phase = 2 * PI - phase;\n    VectorXd real_gabor_atom = gabor_Atom->create_real(sample_count, scale, translation, modulation, phase);\n\n    delete gabor_Atom;\n\n    switch(return_value)\n    {\n    case RETURNPARAMETERS:\n    {\n\n        qreal scalar_product = 0;\n\n        for(qint32 i = 0; i < sample_count; i++)\n            scalar_product += real_gabor_atom[i] * residuum(i, channel);\n\n        VectorXd atom_parameters = VectorXd::Zero(5);\n\n        atom_parameters[0] = scale;\n        atom_parameters[1] = translation;\n        atom_parameters[2] = modulation;\n        atom_parameters[3] = phase;\n        atom_parameters[4] = scalar_product;\n\n\n        return atom_parameters;\n    }\n\n    case RETURNATOM: {return real_gabor_atom;} //returns normalized realGaborAtom\n\n    default: return real_gabor_atom;// only to avoid compiler warnings\n    }\n}\n\n//*************************************************************************************************************\n\nvoid AdaptiveMp::simplex_maximisation(qint32 simplex_it, qreal simplex_reflection, qreal simplex_expansion, qreal simplex_contraction, qreal simplex_full_contraction,\n                                      GaborAtom *gabor_Atom, VectorXd max_scalar_product, qint32 sample_count, bool fix_phase, MatrixXd residuum, bool trial_separation, qint32 chn)\n{\n    //Maximisation Simplex Algorithm implemented by Botao Jia, adapted to the MP Algorithm by Martin Henfling. Copyright (C) 2010 Botao Jia\n    //ToDo: change to clean use of EIGEN, @present its mixed with Namespace std and <vector>\n    std::vector<double> init;\n\n    init.push_back(gabor_Atom->scale);\n    init.push_back(gabor_Atom->translation);\n    init.push_back(gabor_Atom->modulation);\n\n    double tol = 1E8 * std::numeric_limits<double>::epsilon();\n    std::vector<std::vector<double> > x = std::vector<std::vector<double> >();\n    qint32 iterations = simplex_it;\n    qint32 N = qint32 (init.size());                //space dimension\n\n    VectorXd atom_fxc_params = VectorXd::Zero(5);   //initialisation for contraction coefficients\n\n    qreal a = simplex_reflection, b = simplex_expansion, g = simplex_contraction, h = simplex_full_contraction;\n                                                //coefficients default a = 1, b = 0.2, g = 0.5, h = 0.5\n                                                //a: reflection  -> xr step away from worst siplex found\n                                                //b: expansion   -> xe if better with a so go in this direction with b\n                                                //g: contraction -> xc calc new worst point an bring closer to middle of simplex\n                                                //h: full contraction to x1\n    std::vector<double> xcentroid_old(N,0);     //simplex center * (N+1)\n    std::vector<double> xcentroid_new(N,0);     //simplex center * (N+1)\n    std::vector<double> vf(N+1,0);              //f evaluated at simplex vertices\n    qint32 x1 = 0, xn = 0, xnp1 = 0;            //x1:   f(x1) = min { f(x1), f(x2)...f(x_{n+1} }\n                                                //xnp1: f(xnp1) = max { f(x1), f(x2)...f(x_{n+1} }\n                                                //xn:   f(xn)<f(xnp1) && f(xn)> all other f(x_i)\n    qint32 cnt = 0; //iteration step number\n\n    if(x.size()== 0) //if no initial simplex is specified\n    {\n        //construct the trial simplex\n        //based upon the initial guess parameters\n        std::vector<double> del( init );\n        std::transform(del.begin(), del.end(), del.begin(),\n                       std::bind2nd( std::divides<double>() , 20) );//'20' is picked\n        //assuming initial trail close to true\n\n        for(qint32 i = 0; i < N; ++i)\n        {\n            std::vector<double> tmp( init );\n            tmp[i] +=  del[i];\n            x.push_back( tmp );\n        }\n\n        x.push_back(init);//x.size()=N+1, x[i].size()=N\n\n        //xcentriod\n        std::transform(init.begin(), init.end(), xcentroid_old.begin(), std::bind2nd(std::multiplies<double>(), N+1) );\n    }//constructing the simplex finished\n\n    //optimization begins\n    for(cnt=0; cnt<iterations; ++cnt)\n    {\n        for(qint32 i=0; i < N+1; ++i)\n        {\n            VectorXd atom_fx = VectorXd::Zero(sample_count);\n\n            if(gabor_Atom->scale == sample_count && gabor_Atom->translation == floor(sample_count / 2))\n                atom_fx = calculate_atom(sample_count, sample_count, floor(sample_count / 2), x[i][2], chn, residuum, RETURNATOM, fix_phase);\n\n            else\n                atom_fx = calculate_atom(sample_count, x[i][0], x[i][1], x[i][2], chn, residuum, RETURNATOM, fix_phase);\n\n            //create targetfunction of realGaborAtom and Residuum\n            double target = 0;\n            for(qint32 k = 0; k < atom_fx.rows(); k++)\n            {\n                target -=atom_fx[k]*residuum(k, chn); //ToDo: old residuum(k,0)\n            }\n\n            vf[i] = target;\n        }\n\n        x1=0; xn=0; xnp1=0;//find index of max, second max, min of vf.\n\n        for(quint32 i=0; i < vf.size(); ++i)\n        {\n            if(vf[i]<vf[x1])      x1 = i;\n            if(vf[i]>vf[xnp1])    xnp1 = i;\n        }\n\n        xn = x1;\n\n        for(quint32 i=0; i<vf.size();++i) if(vf[i]<vf[xnp1] && vf[i]>vf[xn])  xn=i;\n\n        //x1, xn, xnp1 are found\n\n        std::vector<double> xg(N, 0);//xg: centroid of the N best vertexes\n\n        for(quint32 i=0; i<x.size(); ++i) if(i!=xnp1) std::transform(xg.begin(), xg.end(), x[i].begin(), xg.begin(), std::plus<double>() );\n\n        std::transform(xg.begin(), xg.end(), x[xnp1].begin(), xcentroid_new.begin(), std::plus<double>());\n        std::transform(xg.begin(), xg.end(), xg.begin(), std::bind2nd(std::divides<double>(), N) );\n        //xg found, xcentroid_new updated\n\n        //termination condition\n        double diff=0;          //calculate the difference of the simplex centers\n\n        //see if the difference is less than the termination criteria\n        for(qint32 i=0; i<N; ++i) diff += std::fabs(xcentroid_old[i]-xcentroid_new[i]);\n\n        if (diff/N < tol) break;              //terminate the optimizer\n        else xcentroid_old.swap(xcentroid_new); //update simplex center\n\n        //reflection:\n        std::vector<double> xr(N,0);\n\n        for( qint32 i=0; i<N; ++i) xr[i]=xg[i]+a*(xg[i]-x[xnp1][i]);\n        //reflection, xr found\n\n        VectorXd atom_fxr = VectorXd::Zero(sample_count);\n\n        if(gabor_Atom->scale == sample_count && gabor_Atom->translation == floor(sample_count / 2))\n            atom_fxr = calculate_atom(sample_count, sample_count, floor(sample_count / 2), xr[2], chn, residuum, RETURNATOM, fix_phase);\n\n        else\n            atom_fxr = calculate_atom(sample_count, xr[0], xr[1], xr[2], chn, residuum, RETURNATOM, fix_phase);\n\n        //create targetfunction of realGaborAtom and Residuum\n        double fxr = 0;\n        for(qint32 k = 0; k < atom_fxr.rows(); k++) fxr -=atom_fxr[k]*residuum(k,chn);//ToDo: old residuum(k,0)\n\n        //double fxr = target;//record function at xr\n\n        if(vf[x1]<=fxr && fxr<=vf[xn]) std::copy(xr.begin(), xr.end(), x[xnp1].begin());\n\n        //expansion:\n        else if(fxr<vf[x1])\n        {\n            std::vector<double> xe(N,0);\n\n            for( qint32 i=0; i<N; ++i) xe[i]=xr[i]+b*(xr[i]-xg[i]);\n\n            VectorXd atom_fxe = VectorXd::Zero(sample_count);\n\n            if(gabor_Atom->scale == sample_count && gabor_Atom->translation == floor(sample_count / 2))\n                atom_fxe = calculate_atom(sample_count, sample_count, floor(sample_count / 2), xe[2], chn, residuum, RETURNATOM, fix_phase);\n\n            else\n                atom_fxe = calculate_atom(sample_count, xe[0], xe[1], xe[2], chn, residuum, RETURNATOM, fix_phase);\n\n            //create targetfunction of realGaborAtom and Residuum\n            double fxe = 0;\n            for(qint32 k = 0; k < atom_fxe.rows(); k++) fxe -=atom_fxe[k]*residuum(k,chn);//ToDo: old residuum(k,0)\n\n            if( fxe < fxr ) std::copy(xe.begin(), xe.end(), x[xnp1].begin() );\n            else std::copy(xr.begin(), xr.end(), x[xnp1].begin() );\n        }//expansion finished,  xe is not used outside the scope\n\n        //contraction:\n        else if( fxr > vf[xn] )\n        {\n            std::vector<double> xc(N,0);\n\n            for( qint32 i=0; i<N; ++i)\n                xc[i]=xg[i]+g*(x[xnp1][i]-xg[i]);\n\n            if(gabor_Atom->scale == sample_count && gabor_Atom->translation == floor(sample_count / 2))\n                atom_fxc_params = AdaptiveMp::calculate_atom(sample_count, sample_count, floor(sample_count / 2), xc[2], chn, residuum, RETURNPARAMETERS, fix_phase);\n\n            else\n                atom_fxc_params = AdaptiveMp::calculate_atom(sample_count, xc[0], xc[1], xc[2], chn, residuum, RETURNPARAMETERS, fix_phase);\n\n            VectorXd atom_fxc = gabor_Atom->create_real(gabor_Atom->sample_count, atom_fxc_params[0], atom_fxc_params[1], atom_fxc_params[2], atom_fxc_params[3]);\n\n            atom_fxc_params[4] = 0;\n\n            for(qint32 i = 0; i < sample_count; i++)\n                atom_fxc_params[4] += atom_fxc[i] * residuum(i, chn);\n\n            //create targetfunction of realGaborAtom and Residuum\n            double fxc = 0;\n\n            for(qint32 k = 0; k < atom_fxc.rows(); k++)\n                fxc -=atom_fxc[k]*residuum(k,chn);//ToDo: old residuum(k,0)\n\n            if( fxc < vf[xnp1] )\n                std::copy(xc.begin(), xc.end(), x[xnp1].begin() );\n\n            else\n                for( quint32 i=0; i<x.size(); ++i )\n                    if( i!=x1 )\n                        for(qint32 j=0; j<N; ++j)\n                            x[i][j] = x[x1][j] + h * ( x[i][j]-x[x1][j] );\n        }//contraction finished, xc is not used outside the scope\n    }//optimization is finished\n    //end Maximisation Copyright (C) 2010 Botao Jia\n\n    if(iterations != 0)\n    {\n\n        if(gabor_Atom->scale == sample_count && gabor_Atom->translation == floor(sample_count / 2))\n            atom_fxc_params = AdaptiveMp::calculate_atom(sample_count, sample_count, floor(sample_count / 2), x[x1][2], chn, residuum, RETURNPARAMETERS, fix_phase);\n\n        else\n            atom_fxc_params = AdaptiveMp::calculate_atom(sample_count, x[x1][0], x[x1][1], x[x1][2], chn, residuum, RETURNPARAMETERS, fix_phase);\n\n        qreal temp_scalar_product = 0;\n        if(trial_separation) temp_scalar_product = max_scalar_product[chn];\n        else temp_scalar_product = max_scalar_product[0];\n\n        if(std::fabs(atom_fxc_params[4]) > std::fabs(temp_scalar_product) && atom_fxc_params[1] < sample_count && atom_fxc_params[1] > 0)//ToDo: find a way to make the simplex not running out of bounds\n        {\n            //set highest scalarproduct, in comparison to best matching atom\n\n            gabor_Atom->scale              = atom_fxc_params[0];\n            gabor_Atom->translation        = atom_fxc_params[1];\n            gabor_Atom->modulation         = atom_fxc_params[2];\n            gabor_Atom->phase              = atom_fxc_params[3];\n            gabor_Atom->max_scalar_product = atom_fxc_params[4];\n\n            if(trial_separation)\n                atoms_in_chns.replace(chn, *gabor_Atom);\n        }\n\n        if(cnt==iterations)//max number of iteration achieves before tol is satisfied\n        {\n            send_warning(11);\n            std::cout<<\"Simplex Iteration limit of \"<<iterations<<\" achieved, result may not be optimal\\n\";\n        }\n\n        std::cout <<  \"      after simplex optimization \" << \":\\n\"<< \"scale: \" << gabor_Atom->scale << \" trans: \" << gabor_Atom->translation <<\n                      \" modu: \" << gabor_Atom->modulation << \" phase: \" << gabor_Atom->phase << \" sclr_prdct: \" << gabor_Atom->max_scalar_product << \"\\n\\n\";\n    }\n}\n\n//*************************************************************************************************************\n\nvoid AdaptiveMp::recieve_input(Eigen::MatrixXd signal, qint32 max_iterations, qreal epsilon, bool fix_phase = false, qint32 boost = 0, qint32 simplex_it = 1E3,\n                               qreal simplex_reflection = 1.0, qreal simplex_expansion = 0.2, qreal simplex_contraction = 0.5, qreal simplex_full_contraction = 0.5, bool trial_separation = false)\n{\n    matching_pursuit(signal, max_iterations, epsilon, fix_phase, boost, simplex_it, simplex_reflection, simplex_expansion, simplex_contraction, simplex_full_contraction, trial_separation);\n}\n\n//*************************************************************************************************************\n\nAdaptiveMp::~AdaptiveMp()\n{\n}\n", "meta": {"hexsha": "0e139f01fd2a35debb2674e2c898205534ab4de9", "size": 31865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/utils/mp/adaptivemp.cpp", "max_stars_repo_name": "ChunmingGu/mne-cpp-master", "max_stars_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/utils/mp/adaptivemp.cpp", "max_issues_repo_name": "ChunmingGu/mne-cpp-master", "max_issues_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/utils/mp/adaptivemp.cpp", "max_forks_repo_name": "ChunmingGu/mne-cpp-master", "max_forks_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0070621469, "max_line_length": 205, "alphanum_fraction": 0.5271928448, "num_tokens": 7250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339457, "lm_q2_score": 0.025957357857117398, "lm_q1q2_score": 0.009049906543006353}}
{"text": "/////////////////////////////////////////////////////////////////////////////\n//\n// (C) Copyright Ion Gaztanaga  2007-2012\n//\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://www.boost.org/libs/intrusive for documentation.\n//\n/////////////////////////////////////////////////////////////////////////////\n// The implementation of splay trees is based on the article and code published\n// in C++ Users Journal \"Implementing Splay Trees in C++\" (September 1, 2005).\n//\n// The code has been modified and (supposely) improved by Ion Gaztanaga.\n// Here is the header of the file used as base code:\n//\n//  splay_tree.h -- implementation of a STL compatible splay tree.\n//\n//  Copyright (c) 2004 Ralf Mattethat\n//\n//  Permission to copy, use, modify, sell and distribute this software\n//  is granted provided this copyright notice appears in all copies.\n//  This software is provided \"as is\" without express or implied\n//  warranty, and with no claim as to its suitability for any purpose.\n//\n//  Please send questions, comments, complaints, performance data, etc to\n//  ralf.mattethat@teknologisk.dk\n//\n//  Requirements for element type\n//  * must be copy-constructible\n//  * destructor must not throw exception\n//\n//    Methods marked with note A only throws an exception if the evaluation of the\n//    predicate throws an exception. If an exception is thrown the call has no\n//    effect on the containers state\n//\n//    Methods marked with note B only throws an exception if the coppy constructor\n//    or assignment operator of the predicate throws an exception. If an exception\n//    is thrown the call has no effect on the containers state\n//\n//    iterators are only invalidated, if the element pointed to by the iterator\n//    is deleted. The same goes for element references\n//\n\n#ifndef BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\n#define BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\n\n#include <boost/intrusive/detail/config_begin.hpp>\n#include <boost/intrusive/detail/assert.hpp>\n#include <boost/intrusive/intrusive_fwd.hpp>\n#include <boost/intrusive/pointer_traits.hpp>\n#include <cstddef>\n#include <boost/intrusive/detail/utilities.hpp>\n#include <boost/intrusive/detail/tree_algorithms.hpp>\n\nnamespace boost {\nnamespace intrusive {\n\n/// @cond\nnamespace detail {\n\ntemplate<class NodeTraits>\nstruct splaydown_rollback\n{\n   typedef typename NodeTraits::node_ptr node_ptr;\n   splaydown_rollback( const node_ptr *pcur_subtree, const node_ptr & header\n                     , const node_ptr & leftmost           , const node_ptr & rightmost)\n      : pcur_subtree_(pcur_subtree)  , header_(header)\n      , leftmost_(leftmost)   , rightmost_(rightmost)\n   {}\n\n   void release()\n   {  pcur_subtree_ = 0;  }\n\n   ~splaydown_rollback()\n   {\n      if(pcur_subtree_){\n         //Exception can only be thrown by comp, but\n         //tree invariants still hold. *pcur_subtree is the current root\n         //so link it to the header.\n         NodeTraits::set_parent(*pcur_subtree_, header_);\n         NodeTraits::set_parent(header_, *pcur_subtree_);\n         //Recover leftmost/rightmost pointers\n         NodeTraits::set_left (header_, leftmost_);\n         NodeTraits::set_right(header_, rightmost_);\n      }\n   }\n   const node_ptr *pcur_subtree_;\n   node_ptr header_, leftmost_, rightmost_;\n};\n\n}  //namespace detail {\n/// @endcond\n\n//!   A splay tree is an implementation of a binary search tree. The tree is\n//!   self balancing using the splay algorithm as described in\n//!\n//!      \"Self-Adjusting Binary Search Trees\n//!      by Daniel Dominic Sleator and Robert Endre Tarjan\n//!      AT&T Bell Laboratories, Murray Hill, NJ\n//!      Journal of the ACM, Vol 32, no 3, July 1985, pp 652-686\n\n//! splaytree_algorithms is configured with a NodeTraits class, which encapsulates the\n//! information about the node to be manipulated. NodeTraits must support the\n//! following interface:\n//!\n//! <b>Typedefs</b>:\n//!\n//! <tt>node</tt>: The type of the node that forms the circular list\n//!\n//! <tt>node_ptr</tt>: A pointer to a node\n//!\n//! <tt>const_node_ptr</tt>: A pointer to a const node\n//!\n//! <b>Static functions</b>:\n//!\n//! <tt>static node_ptr get_parent(const_node_ptr n);</tt>\n//!\n//! <tt>static void set_parent(node_ptr n, node_ptr parent);</tt>\n//!\n//! <tt>static node_ptr get_left(const_node_ptr n);</tt>\n//!\n//! <tt>static void set_left(node_ptr n, node_ptr left);</tt>\n//!\n//! <tt>static node_ptr get_right(const_node_ptr n);</tt>\n//!\n//! <tt>static void set_right(node_ptr n, node_ptr right);</tt>\ntemplate<class NodeTraits>\nclass splaytree_algorithms\n{\n   /// @cond\n   private:\n   typedef detail::tree_algorithms<NodeTraits>  tree_algorithms;\n   /// @endcond\n\n   public:\n   typedef typename NodeTraits::node            node;\n   typedef NodeTraits                           node_traits;\n   typedef typename NodeTraits::node_ptr        node_ptr;\n   typedef typename NodeTraits::const_node_ptr  const_node_ptr;\n\n   //! This type is the information that will be\n   //! filled by insert_unique_check\n   typedef typename tree_algorithms::insert_commit_data insert_commit_data;\n\n   /// @cond\n   private:\n   static node_ptr uncast(const const_node_ptr & ptr)\n   {  return pointer_traits<node_ptr>::const_cast_from(ptr);  }\n   /// @endcond\n\n   public:\n   static node_ptr begin_node(const const_node_ptr & header)\n   {  return tree_algorithms::begin_node(header);   }\n\n   static node_ptr end_node(const const_node_ptr & header)\n   {  return tree_algorithms::end_node(header);   }\n\n   //! <b>Requires</b>: node is a node of the tree or an node initialized\n   //!   by init(...).\n   //!\n   //! <b>Effects</b>: Returns true if the node is initialized by init().\n   //!\n   //! <b>Complexity</b>: Constant time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   static bool unique(const const_node_ptr & node)\n   {  return tree_algorithms::unique(node);  }\n\n   static void unlink(const node_ptr & node)\n   {  tree_algorithms::unlink(node);   }\n\n   //! <b>Requires</b>: node1 and node2 can't be header nodes\n   //!  of two trees.\n   //!\n   //! <b>Effects</b>: Swaps two nodes. After the function node1 will be inserted\n   //!   in the position node2 before the function. node2 will be inserted in the\n   //!   position node1 had before the function.\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Note</b>: This function will break container ordering invariants if\n   //!   node1 and node2 are not equivalent according to the ordering rules.\n   //!\n   //!Experimental function\n   static void swap_nodes(const node_ptr & node1, const node_ptr & node2)\n   {\n      if(node1 == node2)\n         return;\n\n      node_ptr header1(tree_algorithms::get_header(node1)), header2(tree_algorithms::get_header(node2));\n      swap_nodes(node1, header1, node2, header2);\n   }\n\n   //! <b>Requires</b>: node1 and node2 can't be header nodes\n   //!  of two trees with header header1 and header2.\n   //!\n   //! <b>Effects</b>: Swaps two nodes. After the function node1 will be inserted\n   //!   in the position node2 before the function. node2 will be inserted in the\n   //!   position node1 had before the function.\n   //!\n   //! <b>Complexity</b>: Constant.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Note</b>: This function will break container ordering invariants if\n   //!   node1 and node2 are not equivalent according to the ordering rules.\n   //!\n   //!Experimental function\n   static void swap_nodes(const node_ptr & node1, const node_ptr & header1, const node_ptr & node2, const node_ptr & header2)\n   {  tree_algorithms::swap_nodes(node1, header1, node2, header2);   }\n\n   //! <b>Requires</b>: node_to_be_replaced must be inserted in a tree\n   //!   and new_node must not be inserted in a tree.\n   //!\n   //! <b>Effects</b>: Replaces node_to_be_replaced in its position in the\n   //!   tree with new_node. The tree does not need to be rebalanced\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Note</b>: This function will break container ordering invariants if\n   //!   new_node is not equivalent to node_to_be_replaced according to the\n   //!   ordering rules. This function is faster than erasing and inserting\n   //!   the node, since no rebalancing and comparison is needed.\n   //!\n   //!Experimental function\n   static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & new_node)\n   {\n      if(node_to_be_replaced == new_node)\n         return;\n      replace_node(node_to_be_replaced, tree_algorithms::get_header(node_to_be_replaced), new_node);\n   }\n\n   //! <b>Requires</b>: node_to_be_replaced must be inserted in a tree\n   //!   with header \"header\" and new_node must not be inserted in a tree.\n   //!\n   //! <b>Effects</b>: Replaces node_to_be_replaced in its position in the\n   //!   tree with new_node. The tree does not need to be rebalanced\n   //!\n   //! <b>Complexity</b>: Constant.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Note</b>: This function will break container ordering invariants if\n   //!   new_node is not equivalent to node_to_be_replaced according to the\n   //!   ordering rules. This function is faster than erasing and inserting\n   //!   the node, since no rebalancing or comparison is needed.\n   //!\n   //!Experimental function\n   static void replace_node(const node_ptr & node_to_be_replaced, const node_ptr & header, const node_ptr & new_node)\n   {  tree_algorithms::replace_node(node_to_be_replaced, header, new_node);   }\n\n   //! <b>Requires</b>: p is a node from the tree except the header.\n   //!\n   //! <b>Effects</b>: Returns the next node of the tree.\n   //!\n   //! <b>Complexity</b>: Average constant time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   static node_ptr next_node(const node_ptr & p)\n   {  return tree_algorithms::next_node(p); }\n\n   //! <b>Requires</b>: p is a node from the tree except the leftmost node.\n   //!\n   //! <b>Effects</b>: Returns the previous node of the tree.\n   //!\n   //! <b>Complexity</b>: Average constant time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   static node_ptr prev_node(const node_ptr & p)\n   {  return tree_algorithms::prev_node(p); }\n\n   //! <b>Requires</b>: node must not be part of any tree.\n   //!\n   //! <b>Effects</b>: After the function unique(node) == true.\n   //!\n   //! <b>Complexity</b>: Constant.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Nodes</b>: If node is inserted in a tree, this function corrupts the tree.\n   static void init(const node_ptr & node)\n   {  tree_algorithms::init(node);  }\n\n   //! <b>Requires</b>: node must not be part of any tree.\n   //!\n   //! <b>Effects</b>: Initializes the header to represent an empty tree.\n   //!   unique(header) == true.\n   //!\n   //! <b>Complexity</b>: Constant.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Nodes</b>: If node is inserted in a tree, this function corrupts the tree.\n   static void init_header(const node_ptr & header)\n   {  tree_algorithms::init_header(header);  }\n\n   //! <b>Requires</b>: \"disposer\" must be an object function\n   //!   taking a node_ptr parameter and shouldn't throw.\n   //!\n   //! <b>Effects</b>: Empties the target tree calling\n   //!   <tt>void disposer::operator()(const node_ptr &)</tt> for every node of the tree\n   //!    except the header.\n   //!\n   //! <b>Complexity</b>: Linear to the number of element of the source tree plus the.\n   //!   number of elements of tree target tree when calling this function.\n   //!\n   //! <b>Throws</b>: If cloner functor throws. If this happens target nodes are disposed.\n   template<class Disposer>\n   static void clear_and_dispose(const node_ptr & header, Disposer disposer)\n   {  tree_algorithms::clear_and_dispose(header, disposer); }\n\n   //! <b>Requires</b>: node is a node of the tree but it's not the header.\n   //!\n   //! <b>Effects</b>: Returns the number of nodes of the subtree.\n   //!\n   //! <b>Complexity</b>: Linear time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   static std::size_t count(const const_node_ptr & node)\n   {  return tree_algorithms::count(node);   }\n\n   //! <b>Requires</b>: header is the header node of the tree.\n   //!\n   //! <b>Effects</b>: Returns the number of nodes above the header.\n   //!\n   //! <b>Complexity</b>: Linear time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   static std::size_t size(const const_node_ptr & header)\n   {  return tree_algorithms::size(header);   }\n\n   //! <b>Requires</b>: header1 and header2 must be the header nodes\n   //!  of two trees.\n   //!\n   //! <b>Effects</b>: Swaps two trees. After the function header1 will contain\n   //!   links to the second tree and header2 will have links to the first tree.\n   //!\n   //! <b>Complexity</b>: Constant.\n   //!\n   //! <b>Throws</b>: Nothing.\n   static void swap_tree(const node_ptr & header1, const node_ptr & header2)\n   {  return tree_algorithms::swap_tree(header1, header2);  }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   \"commit_data\" must have been obtained from a previous call to\n   //!   \"insert_unique_check\". No objects should have been inserted or erased\n   //!   from the set between the \"insert_unique_check\" that filled \"commit_data\"\n   //!   and the call to \"insert_commit\".\n   //!\n   //!\n   //! <b>Effects</b>: Inserts new_node in the set using the information obtained\n   //!   from the \"commit_data\" that a previous \"insert_check\" filled.\n   //!\n   //! <b>Complexity</b>: Constant time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Notes</b>: This function has only sense if a \"insert_unique_check\" has been\n   //!   previously executed to fill \"commit_data\". No value should be inserted or\n   //!   erased between the \"insert_check\" and \"insert_commit\" calls.\n   static void insert_unique_commit\n      (const node_ptr & header, const node_ptr & new_value, const insert_commit_data &commit_data)\n   {  tree_algorithms::insert_unique_commit(header, new_value, commit_data);  }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   KeyNodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. NodePtrCompare compares KeyType with a node_ptr.\n   //!\n   //! <b>Effects</b>: Checks if there is an equivalent node to \"key\" in the\n   //!   tree according to \"comp\" and obtains the needed information to realize\n   //!   a constant-time node insertion if there is no equivalent node.\n   //!\n   //! <b>Returns</b>: If there is an equivalent value\n   //!   returns a pair containing a node_ptr to the already present node\n   //!   and false. If there is not equivalent key can be inserted returns true\n   //!   in the returned pair's boolean and fills \"commit_data\" that is meant to\n   //!   be used with the \"insert_commit\" function to achieve a constant-time\n   //!   insertion function.\n   //!\n   //! <b>Complexity</b>: Average complexity is at most logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   //!\n   //! <b>Notes</b>: This function is used to improve performance when constructing\n   //!   a node is expensive and the user does not want to have two equivalent nodes\n   //!   in the tree: if there is an equivalent value\n   //!   the constructed object must be discarded. Many times, the part of the\n   //!   node that is used to impose the order is much cheaper to construct\n   //!   than the node and this function offers the possibility to use that part\n   //!   to check if the insertion will be successful.\n   //!\n   //!   If the check is successful, the user can construct the node and use\n   //!   \"insert_commit\" to insert the node in constant-time. This gives a total\n   //!   logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)).\n   //!\n   //!   \"commit_data\" remains valid for a subsequent \"insert_unique_commit\" only\n   //!   if no more objects are inserted or erased from the set.\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, bool> insert_unique_check\n      (const node_ptr & header, const KeyType &key\n      ,KeyNodePtrCompare comp, insert_commit_data &commit_data)\n   {\n      splay_down(header, key, comp);\n      return tree_algorithms::insert_unique_check(header, key, comp, commit_data);\n   }\n\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, bool> insert_unique_check\n      (const node_ptr & header, const node_ptr &hint, const KeyType &key\n      ,KeyNodePtrCompare comp, insert_commit_data &commit_data)\n   {\n      splay_down(header, key, comp);\n      return tree_algorithms::insert_unique_check(header, hint, key, comp, commit_data);\n   }\n\n   static bool is_header(const const_node_ptr & p)\n   {  return tree_algorithms::is_header(p);  }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   KeyNodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.\n   //!\n   //! <b>Effects</b>: Returns an node_ptr to the element that is equivalent to\n   //!   \"key\" according to \"comp\" or \"header\" if that element does not exist.\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr find\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      if(splay)\n         splay_down(uncast(header), key, comp);\n      node_ptr end = uncast(header);\n      node_ptr y = lower_bound(header, key, comp, false);\n      node_ptr r = (y == end || comp(key, y)) ? end : y;\n      return r;\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   KeyNodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.\n   //!\n   //! <b>Effects</b>: Returns an a pair of node_ptr delimiting a range containing\n   //!   all elements that are equivalent to \"key\" according to \"comp\" or an\n   //!   empty range that indicates the position where those elements would be\n   //!   if they there are no equivalent elements.\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, node_ptr> equal_range\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      //if(splay)\n         //splay_down(uncast(header), key, comp);\n      std::pair<node_ptr, node_ptr> ret =\n         tree_algorithms::equal_range(header, key, comp);\n\n      if(splay)\n         splay_up(ret.first, uncast(header));\n      return ret;\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   KeyNodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.\n   //!   'lower_key' must not be greater than 'upper_key' according to 'comp'. If\n   //!   'lower_key' == 'upper_key', ('left_closed' || 'right_closed') must be false.\n   //!\n   //! <b>Effects</b>: Returns an a pair with the following criteria:\n   //!\n   //!   first = lower_bound(lower_key) if left_closed, upper_bound(lower_key) otherwise\n   //!\n   //!   second = upper_bound(upper_key) if right_closed, lower_bound(upper_key) otherwise\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   //!\n   //! <b>Note</b>: This function can be more efficient than calling upper_bound\n   //!   and lower_bound for lower_key and upper_key.\n   template<class KeyType, class KeyNodePtrCompare>\n   static std::pair<node_ptr, node_ptr> bounded_range\n      (const const_node_ptr & header, const KeyType &lower_key, const KeyType &upper_key, KeyNodePtrCompare comp\n      , bool left_closed, bool right_closed, bool splay = true)\n   {\n      std::pair<node_ptr, node_ptr> ret =\n         tree_algorithms::bounded_range(header, lower_key, upper_key, comp, left_closed, right_closed);\n\n      if(splay)\n         splay_up(ret.first, uncast(header));\n      return ret;\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   KeyNodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.\n   //!\n   //! <b>Effects</b>: Returns an node_ptr to the first element that is\n   //!   not less than \"key\" according to \"comp\" or \"header\" if that element does\n   //!   not exist.\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr lower_bound\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      //if(splay)\n         //splay_down(uncast(header), key, comp);\n      node_ptr y = tree_algorithms::lower_bound(header, key, comp);\n      if(splay)\n         splay_up(y, uncast(header));\n      return y;\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   KeyNodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. KeyNodePtrCompare can compare KeyType with tree's node_ptrs.\n   //!\n   //! <b>Effects</b>: Returns an node_ptr to the first element that is greater\n   //!   than \"key\" according to \"comp\" or \"header\" if that element does not exist.\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr upper_bound\n      (const const_node_ptr & header, const KeyType &key, KeyNodePtrCompare comp, bool splay = true)\n   {\n      //if(splay)\n         //splay_down(uncast(header), key, comp);\n      node_ptr y = tree_algorithms::upper_bound(header, key, comp);\n      if(splay)\n         splay_up(y, uncast(header));\n      return y;\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   NodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. NodePtrCompare compares two node_ptrs. \"hint\" is node from\n   //!   the \"header\"'s tree.\n   //!\n   //! <b>Effects</b>: Inserts new_node into the tree, using \"hint\" as a hint to\n   //!   where it will be inserted. If \"hint\" is the upper_bound\n   //!   the insertion takes constant time (two comparisons in the worst case).\n   //!\n   //! <b>Complexity</b>: Logarithmic in general, but it is amortized\n   //!   constant time if new_node is inserted immediately before \"hint\".\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   template<class NodePtrCompare>\n   static node_ptr insert_equal\n      (const node_ptr & header, const node_ptr & hint, const node_ptr & new_node, NodePtrCompare comp)\n   {\n      splay_down(header, new_node, comp);\n      return tree_algorithms::insert_equal(header, hint, new_node, comp);\n   }\n\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   \"pos\" must be a valid iterator or header (end) node.\n   //!   \"pos\" must be an iterator pointing to the successor to \"new_node\"\n   //!   once inserted according to the order of already inserted nodes. This function does not\n   //!   check \"pos\" and this precondition must be guaranteed by the caller.\n   //!\n   //! <b>Effects</b>: Inserts new_node into the tree before \"pos\".\n   //!\n   //! <b>Complexity</b>: Constant-time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Note</b>: If \"pos\" is not the successor of the newly inserted \"new_node\"\n   //! tree invariants might be broken.\n   static node_ptr insert_before\n      (const node_ptr & header, const node_ptr & pos, const node_ptr & new_node)\n   {\n      tree_algorithms::insert_before(header, pos, new_node);\n      splay_up(new_node, header);\n      return new_node;\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   \"new_node\" must be, according to the used ordering no less than the\n   //!   greatest inserted key.\n   //!\n   //! <b>Effects</b>: Inserts new_node into the tree before \"pos\".\n   //!\n   //! <b>Complexity</b>: Constant-time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Note</b>: If \"new_node\" is less than the greatest inserted key\n   //! tree invariants are broken. This function is slightly faster than\n   //! using \"insert_before\".\n   static void push_back(const node_ptr & header, const node_ptr & new_node)\n   {\n      tree_algorithms::push_back(header, new_node);\n      splay_up(new_node, header);\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   \"new_node\" must be, according to the used ordering, no greater than the\n   //!   lowest inserted key.\n   //!\n   //! <b>Effects</b>: Inserts new_node into the tree before \"pos\".\n   //!\n   //! <b>Complexity</b>: Constant-time.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Note</b>: If \"new_node\" is greater than the lowest inserted key\n   //! tree invariants are broken. This function is slightly faster than\n   //! using \"insert_before\".\n   static void push_front(const node_ptr & header, const node_ptr & new_node)\n   {\n      tree_algorithms::push_front(header, new_node);\n      splay_up(new_node, header);\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   NodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. NodePtrCompare compares two node_ptrs.\n   //!\n   //! <b>Effects</b>: Inserts new_node into the tree before the upper bound\n   //!   according to \"comp\".\n   //!\n   //! <b>Complexity</b>: Average complexity for insert element is at\n   //!   most logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   template<class NodePtrCompare>\n   static node_ptr insert_equal_upper_bound\n      (const node_ptr & header, const node_ptr & new_node, NodePtrCompare comp)\n   {\n      splay_down(header, new_node, comp);\n      return tree_algorithms::insert_equal_upper_bound(header, new_node, comp);\n   }\n\n   //! <b>Requires</b>: \"header\" must be the header node of a tree.\n   //!   NodePtrCompare is a function object that induces a strict weak\n   //!   ordering compatible with the strict weak ordering used to create the\n   //!   the tree. NodePtrCompare compares two node_ptrs.\n   //!\n   //! <b>Effects</b>: Inserts new_node into the tree before the lower bound\n   //!   according to \"comp\".\n   //!\n   //! <b>Complexity</b>: Average complexity for insert element is at\n   //!   most logarithmic.\n   //!\n   //! <b>Throws</b>: If \"comp\" throws.\n   template<class NodePtrCompare>\n   static node_ptr insert_equal_lower_bound\n      (const node_ptr & header, const node_ptr & new_node, NodePtrCompare comp)\n   {\n      splay_down(header, new_node, comp);\n      return tree_algorithms::insert_equal_lower_bound(header, new_node, comp);\n   }\n\n   //! <b>Requires</b>: \"cloner\" must be a function\n   //!   object taking a node_ptr and returning a new cloned node of it. \"disposer\" must\n   //!   take a node_ptr and shouldn't throw.\n   //!\n   //! <b>Effects</b>: First empties target tree calling\n   //!   <tt>void disposer::operator()(const node_ptr &)</tt> for every node of the tree\n   //!    except the header.\n   //!\n   //!   Then, duplicates the entire tree pointed by \"source_header\" cloning each\n   //!   source node with <tt>node_ptr Cloner::operator()(const node_ptr &)</tt> to obtain\n   //!   the nodes of the target tree. If \"cloner\" throws, the cloned target nodes\n   //!   are disposed using <tt>void disposer(const node_ptr &)</tt>.\n   //!\n   //! <b>Complexity</b>: Linear to the number of element of the source tree plus the.\n   //!   number of elements of tree target tree when calling this function.\n   //!\n   //! <b>Throws</b>: If cloner functor throws. If this happens target nodes are disposed.\n   template <class Cloner, class Disposer>\n   static void clone\n      (const const_node_ptr & source_header, const node_ptr & target_header, Cloner cloner, Disposer disposer)\n   {  tree_algorithms::clone(source_header, target_header, cloner, disposer);   }\n\n   // delete node                        | complexity : constant        | exception : nothrow\n   static void erase(const node_ptr & header, const node_ptr & z, bool splay = true)\n   {\n//      node_base* n = t->right;\n//      if( t->left != node_ptr() ){\n//         node_base* l = t->previous();\n//         splay_up( l , t );\n//         n = t->left;\n//         n->right = t->right;\n//         if( n->right != node_ptr() )\n//            n->right->parent = n;\n//      }\n//\n//      if( n != node_ptr() )\n//         n->parent = t->parent;\n//\n//      if( t->parent->left == t )\n//         t->parent->left = n;\n//      else // must be ( t->parent->right == t )\n//         t->parent->right = n;\n//\n//      if( data_->parent == t )\n//         data_->parent = find_leftmost();\n         //posibility 1\n      if(splay && NodeTraits::get_left(z)){\n         splay_up(prev_node(z), header);\n      }\n      /*\n      //possibility 2\n      if(splay && NodeTraits::get_left(z) != node_ptr() ){\n         node_ptr l = NodeTraits::get_left(z);\n         splay_up(l, header);\n      }*//*\n      if(splay && NodeTraits::get_left(z) != node_ptr() ){\n         node_ptr l = prev_node(z);\n         splay_up_impl(l, z);\n      }*/\n      /*\n      //possibility 4\n      if(splay){\n         splay_up(z, header);\n      }*/\n\n      //if(splay)\n         //splay_up(z, header);\n      tree_algorithms::erase(header, z);\n   }\n\n   // bottom-up splay, use data_ as parent for n    | complexity : logarithmic    | exception : nothrow\n   static void splay_up(const node_ptr & node, const node_ptr & header)\n   {\n      // If (node == header) do a splay for the right most node instead\n      // this is to boost performance of equal_range/count on equivalent containers in the case\n      // where there are many equal elements at the end\n      node_ptr n((node == header) ? NodeTraits::get_right(header) : node);\n      node_ptr t(header);\n\n      if( n == t ) return;\n\n      for( ;; ){\n         node_ptr p(NodeTraits::get_parent(n));\n         node_ptr g(NodeTraits::get_parent(p));\n\n         if( p == t )   break;\n\n         if( g == t ){\n            // zig\n            rotate(n);\n         }\n         else if ((NodeTraits::get_left(p) == n && NodeTraits::get_left(g) == p)    ||\n                  (NodeTraits::get_right(p) == n && NodeTraits::get_right(g) == p)  ){\n            // zig-zig\n            rotate(p);\n            rotate(n);\n         }\n         else{\n            // zig-zag\n            rotate(n);\n            rotate(n);\n         }\n      }\n   }\n\n   // top-down splay | complexity : logarithmic    | exception : strong, note A\n   template<class KeyType, class KeyNodePtrCompare>\n   static node_ptr splay_down(const node_ptr & header, const KeyType &key, KeyNodePtrCompare comp)\n   {\n      if(!NodeTraits::get_parent(header))\n         return header;\n      //Most splay tree implementations use a dummy/null node to implement.\n      //this function. This has some problems for a generic library like Intrusive:\n      //\n      // * The node might not have a default constructor.\n      // * The default constructor could throw.\n      //\n      //We already have a header node. Leftmost and rightmost nodes of the tree\n      //are not changed when splaying (because the invariants of the tree don't\n      //change) We can back up them, use the header as the null node and\n      //reassign old values after the function has been completed.\n      node_ptr t = NodeTraits::get_parent(header);\n      //Check if tree has a single node\n      if(!NodeTraits::get_left(t) && !NodeTraits::get_right(t))\n         return t;\n      //Backup leftmost/rightmost\n      node_ptr leftmost (NodeTraits::get_left(header));\n      node_ptr rightmost(NodeTraits::get_right(header));\n      {\n         //Anti-exception rollback, recovers the original header node if an exception is thrown.\n         detail::splaydown_rollback<NodeTraits> rollback(&t, header, leftmost, rightmost);\n         node_ptr null_node = header;\n         node_ptr l = null_node;\n         node_ptr r = null_node;\n\n         for( ;; ){\n            if(comp(key, t)){\n               if(NodeTraits::get_left(t) == node_ptr() )\n                  break;\n               if(comp(key, NodeTraits::get_left(t))){\n                  t = tree_algorithms::rotate_right(t);\n\n                  if(NodeTraits::get_left(t) == node_ptr())\n                     break;\n                  link_right(t, r);\n               }\n               else if(comp(NodeTraits::get_left(t), key)){\n                  link_right(t, r);\n\n                  if(NodeTraits::get_right(t) == node_ptr() )\n                     break;\n                  link_left(t, l);\n               }\n               else{\n                  link_right(t, r);\n               }\n            }\n            else if(comp(t, key)){\n               if(NodeTraits::get_right(t) == node_ptr() )\n                  break;\n\n               if(comp(NodeTraits::get_right(t), key)){\n                     t = tree_algorithms::rotate_left( t );\n\n                     if(NodeTraits::get_right(t) == node_ptr() )\n                        break;\n                     link_left(t, l);\n               }\n               else if(comp(key, NodeTraits::get_right(t))){\n                  link_left(t, l);\n\n                  if(NodeTraits::get_left(t) == node_ptr())\n                     break;\n\n                  link_right(t, r);\n               }\n               else{\n                  link_left(t, l);\n               }\n            }\n            else{\n               break;\n            }\n         }\n\n         assemble(t, l, r, null_node);\n         rollback.release();\n      }\n\n      //Now recover the original header except for the\n      //splayed root node.\n      //t is the current root\n      NodeTraits::set_parent(header, t);\n      NodeTraits::set_parent(t, header);\n      //Recover leftmost/rightmost pointers\n      NodeTraits::set_left (header, leftmost);\n      NodeTraits::set_right(header, rightmost);\n      return t;\n   }\n\n   //! <b>Requires</b>: header must be the header of a tree.\n   //!\n   //! <b>Effects</b>: Rebalances the tree.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Complexity</b>: Linear.\n   static void rebalance(const node_ptr & header)\n   {  tree_algorithms::rebalance(header); }\n\n   //! <b>Requires</b>: old_root is a node of a tree.\n   //!\n   //! <b>Effects</b>: Rebalances the subtree rooted at old_root.\n   //!\n   //! <b>Returns</b>: The new root of the subtree.\n   //!\n   //! <b>Throws</b>: Nothing.\n   //!\n   //! <b>Complexity</b>: Linear.\n   static node_ptr rebalance_subtree(const node_ptr & old_root)\n   {  return tree_algorithms::rebalance_subtree(old_root); }\n\n\n   //! <b>Requires</b>: \"n\" must be a node inserted in a tree.\n   //!\n   //! <b>Effects</b>: Returns a pointer to the header node of the tree.\n   //!\n   //! <b>Complexity</b>: Logarithmic.\n   //!\n   //! <b>Throws</b>: Nothing.\n   static node_ptr get_header(const node_ptr & n)\n   {  return tree_algorithms::get_header(n);   }\n\n   private:\n\n   /// @cond\n\n   // assemble the three sub-trees into new tree pointed to by t    | complexity : constant        | exception : nothrow\n   static void assemble(const node_ptr &t, const node_ptr & l, const node_ptr & r, const const_node_ptr & null_node )\n   {\n      NodeTraits::set_right(l, NodeTraits::get_left(t));\n      NodeTraits::set_left(r, NodeTraits::get_right(t));\n\n      if(NodeTraits::get_right(l) != node_ptr()){\n         NodeTraits::set_parent(NodeTraits::get_right(l), l);\n      }\n\n      if(NodeTraits::get_left(r) != node_ptr()){\n         NodeTraits::set_parent(NodeTraits::get_left(r), r);\n      }\n\n      NodeTraits::set_left (t, NodeTraits::get_right(null_node));\n      NodeTraits::set_right(t, NodeTraits::get_left(null_node));\n\n      if( NodeTraits::get_left(t) != node_ptr() ){\n         NodeTraits::set_parent(NodeTraits::get_left(t), t);\n      }\n\n      if( NodeTraits::get_right(t) ){\n         NodeTraits::set_parent(NodeTraits::get_right(t), t);\n      }\n   }\n\n   // break link to left child node and attach it to left tree pointed to by l   | complexity : constant | exception : nothrow\n   static void link_left(node_ptr & t, node_ptr & l)\n   {\n      NodeTraits::set_right(l, t);\n      NodeTraits::set_parent(t, l);\n      l = t;\n      t = NodeTraits::get_right(t);\n   }\n\n   // break link to right child node and attach it to right tree pointed to by r | complexity : constant | exception : nothrow\n   static void link_right(node_ptr & t, node_ptr & r)\n   {\n      NodeTraits::set_left(r, t);\n      NodeTraits::set_parent(t, r);\n      r = t;\n      t = NodeTraits::get_left(t);\n   }\n\n   // rotate n with its parent                     | complexity : constant    | exception : nothrow\n   static void rotate(const node_ptr & n)\n   {\n      node_ptr p = NodeTraits::get_parent(n);\n      node_ptr g = NodeTraits::get_parent(p);\n      //Test if g is header before breaking tree\n      //invariants that would make is_header invalid\n      bool g_is_header = is_header(g);\n\n      if(NodeTraits::get_left(p) == n){\n         NodeTraits::set_left(p, NodeTraits::get_right(n));\n         if(NodeTraits::get_left(p) != node_ptr())\n            NodeTraits::set_parent(NodeTraits::get_left(p), p);\n         NodeTraits::set_right(n, p);\n      }\n      else{ // must be ( p->right == n )\n         NodeTraits::set_right(p, NodeTraits::get_left(n));\n         if(NodeTraits::get_right(p) != node_ptr())\n            NodeTraits::set_parent(NodeTraits::get_right(p), p);\n         NodeTraits::set_left(n, p);\n      }\n\n      NodeTraits::set_parent(p, n);\n      NodeTraits::set_parent(n, g);\n\n      if(g_is_header){\n         if(NodeTraits::get_parent(g) == p)\n            NodeTraits::set_parent(g, n);\n         else{//must be ( g->right == p )\n            BOOST_INTRUSIVE_INVARIANT_ASSERT(false);\n            NodeTraits::set_right(g, n);\n         }\n      }\n      else{\n         if(NodeTraits::get_left(g) == p)\n            NodeTraits::set_left(g, n);\n         else  //must be ( g->right == p )\n            NodeTraits::set_right(g, n);\n      }\n   }\n\n   /// @endcond\n};\n\n} //namespace intrusive\n} //namespace boost\n\n#include <boost/intrusive/detail/config_end.hpp>\n\n#endif //BOOST_INTRUSIVE_SPLAYTREE_ALGORITHMS_HPP\n", "meta": {"hexsha": "8155648983ba4a04a9ede4fff7aaa21b6b172145", "size": 38834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/intrusive/splaytree_algorithms.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/intrusive/splaytree_algorithms.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/intrusive/splaytree_algorithms.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": 38.4876114965, "max_line_length": 126, "alphanum_fraction": 0.6331565123, "num_tokens": 9901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821862, "lm_q2_score": 0.03210070393911136, "lm_q1q2_score": 0.009033318477799887}}
{"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_IEXP_IEXP_CONSTANT_HPP\n#define AMA_TENSOR_IEXP_IEXP_CONSTANT_HPP 1\n\n#include <ama/tensor/iexp/index_reorder.hpp>\n#include <ama/tensor/iexp/iexp_base.hpp>\n#include <boost/mpl/bool.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* forward declaration */\n    template <\n          typename TENSOR /* the tensor indixed */\n        , typename CTLIST /* the controvariant list */\n        , typename COLIST /* the covariant list */\n        > class iexp_constant;\n\n\n    /* specialization of iexp_traits */\n    template <typename TENSOR, typename CTLIST, typename COLIST>\n    struct iexp_traits < iexp_constant<TENSOR, CTLIST, COLIST> >\n    {\n      typedef typename TENSOR::value_type value_type;\n\n      typedef typename TENSOR::dimension_type dimension_type;\n\n      typedef CTLIST controvariant_list;\n      typedef COLIST covariant_list;\n\n      typedef ::boost::mpl::false_ is_assignable;\n    };\n\n\n    /* class declaration */\n    template <typename TENSOR, typename CTLIST, typename COLIST>\n    class iexp_constant:\n      public iexp_base< iexp_constant<TENSOR, CTLIST, COLIST> >\n    {\n    protected:\n      typedef iexp_base< iexp_constant<TENSOR, CTLIST, COLIST> > base_type;\n      typedef iexp_constant<TENSOR, CTLIST, COLIST> derived_type;\n\n    public:\n      typedef typename base_type::value_type value_type;\n      typedef typename base_type::index_list index_list;\n\n    protected:\n      typedef TENSOR tensor_type;\n\n    public:\n      /* constructor */\n      explicit iexp_constant(tensor_type const & t): m_t(t) { }\n\n    public:\n      /* retrieve the value */\n      template <typename IMAP>\n      value_type at() const\n      {\n        /* reorder the indices */\n        typedef typename index_reorder<IMAP, index_list>::type ilist;\n\n        return m_t.template at<ilist>();\n      }\n\n    protected:\n      tensor_type const & m_t;\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_IEXP_IEXP_CONSTANT_HPP */\n", "meta": {"hexsha": "d719d6baa6e4d05dafccdd876b2994e60d6c7eba", "size": 3541, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/iexp/iexp_constant.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/iexp/iexp_constant.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/iexp/iexp_constant.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.3786407767, "max_line_length": 83, "alphanum_fraction": 0.7127929963, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.0293122296913986, "lm_q1q2_score": 0.00900934878784738}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP\r\n\r\n\r\n#include <boost/geometry/algorithms/clear.hpp>\r\n#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>\r\n#include <boost/geometry/algorithms/not_implemented.hpp>\r\n#include <boost/geometry/core/closure.hpp>\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/core/exception.hpp>\r\n#include <boost/geometry/core/point_type.hpp>\r\n#include <boost/geometry/core/tag.hpp>\r\n#include <boost/geometry/core/tags.hpp>\r\n#include <boost/geometry/strategies/default_strategy.hpp>\r\n#include <boost/geometry/strategies/densify.hpp>\r\n#include <boost/geometry/util/condition.hpp>\r\n#include <boost/geometry/util/range.hpp>\r\n\r\n#include <boost/range/size.hpp>\r\n#include <boost/range/value_type.hpp>\r\n\r\n#include <boost/throw_exception.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace densify\r\n{\r\n\r\ntemplate <typename Range>\r\nstruct push_back_policy\r\n{\r\n    typedef typename boost::range_value<Range>::type point_type;\r\n\r\n    inline explicit push_back_policy(Range & rng)\r\n        : m_rng(rng)\r\n    {}\r\n\r\n    inline void apply(point_type const& p)\r\n    {\r\n        range::push_back(m_rng, p);\r\n    }\r\n\r\nprivate:\r\n    Range & m_rng;\r\n};\r\n\r\ntemplate <typename Range, typename Point>\r\ninline void convert_and_push_back(Range & range, Point const& p)\r\n{\r\n    typename boost::range_value<Range>::type p2;\r\n    geometry::detail::conversion::convert_point_to_point(p, p2);\r\n    range::push_back(range, p2);\r\n}\r\n\r\ntemplate <bool AppendLastPoint = true>\r\nstruct densify_range\r\n{\r\n    template <typename FwdRng, typename MutRng, typename T, typename Strategy>\r\n    static inline void apply(FwdRng const& rng, MutRng & rng_out,\r\n                             T const& len, Strategy const& strategy)\r\n    {\r\n        typedef typename boost::range_iterator<FwdRng const>::type iterator_t;\r\n        typedef typename boost::range_value<FwdRng>::type point_t;\r\n\r\n        iterator_t it = boost::begin(rng);\r\n        iterator_t end = boost::end(rng);\r\n\r\n        if (it == end) // empty(rng)\r\n        {\r\n            return;\r\n        }\r\n            \r\n        push_back_policy<MutRng> policy(rng_out);\r\n\r\n        iterator_t prev = it;\r\n        for ( ++it ; it != end ; prev = it++)\r\n        {\r\n            point_t const& p0 = *prev;\r\n            point_t const& p1 = *it;\r\n\r\n            convert_and_push_back(rng_out, p0);\r\n\r\n            strategy.apply(p0, p1, policy, len);\r\n        }\r\n\r\n        if (BOOST_GEOMETRY_CONDITION(AppendLastPoint))\r\n        {\r\n            convert_and_push_back(rng_out, *prev); // back(rng)\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <bool IsClosed1, bool IsClosed2> // false, X\r\nstruct densify_ring\r\n{\r\n    template <typename Geometry, typename GeometryOut, typename T, typename Strategy>\r\n    static inline void apply(Geometry const& ring, GeometryOut & ring_out,\r\n                             T const& len, Strategy const& strategy)\r\n    {\r\n        geometry::detail::densify::densify_range<true>\r\n            ::apply(ring, ring_out, len, strategy);\r\n\r\n        if (boost::size(ring) <= 1)\r\n            return;\r\n\r\n        typedef typename point_type<Geometry>::type point_t;\r\n        point_t const& p0 = range::back(ring);\r\n        point_t const& p1 = range::front(ring);\r\n\r\n        push_back_policy<GeometryOut> policy(ring_out);\r\n\r\n        strategy.apply(p0, p1, policy, len);\r\n\r\n        if (BOOST_GEOMETRY_CONDITION(IsClosed2))\r\n        {\r\n            convert_and_push_back(ring_out, p1);\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <>\r\nstruct densify_ring<true, true>\r\n    : densify_range<true>\r\n{};\r\n\r\ntemplate <>\r\nstruct densify_ring<true, false>\r\n    : densify_range<false>\r\n{};\r\n\r\n\r\n}} // namespace detail::densify\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\r\n<\r\n    typename Geometry,\r\n    typename GeometryOut,\r\n    typename Tag1 = typename tag<Geometry>::type,\r\n    typename Tag2 = typename tag<GeometryOut>::type\r\n>\r\nstruct densify\r\n    : not_implemented<Tag1, Tag2>\r\n{};\r\n\r\ntemplate <typename Geometry, typename GeometryOut>\r\nstruct densify<Geometry, GeometryOut, linestring_tag, linestring_tag>\r\n    : geometry::detail::densify::densify_range<>\r\n{};\r\n\r\ntemplate <typename Geometry, typename GeometryOut>\r\nstruct densify<Geometry, GeometryOut, multi_linestring_tag, multi_linestring_tag>\r\n{\r\n    template <typename T, typename Strategy>\r\n    static void apply(Geometry const& mls, GeometryOut & mls_out,\r\n                      T const& len, Strategy const& strategy)\r\n    {\r\n        std::size_t count = boost::size(mls);\r\n        range::resize(mls_out, count);\r\n\r\n        for (std::size_t i = 0 ; i < count ; ++i)\r\n        {\r\n            geometry::detail::densify::densify_range<>\r\n                ::apply(range::at(mls, i), range::at(mls_out, i),\r\n                        len, strategy);\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <typename Geometry, typename GeometryOut>\r\nstruct densify<Geometry, GeometryOut, ring_tag, ring_tag>\r\n    : geometry::detail::densify::densify_ring\r\n        <\r\n            geometry::closure<Geometry>::value != geometry::open,\r\n            geometry::closure<GeometryOut>::value != geometry::open\r\n        >\r\n{};\r\n\r\ntemplate <typename Geometry, typename GeometryOut>\r\nstruct densify<Geometry, GeometryOut, polygon_tag, polygon_tag>\r\n{\r\n    template <typename T, typename Strategy>\r\n    static void apply(Geometry const& poly, GeometryOut & poly_out,\r\n                      T const& len, Strategy const& strategy)\r\n    {\r\n        apply_ring(exterior_ring(poly), exterior_ring(poly_out),\r\n                   len, strategy);\r\n\r\n        std::size_t count = boost::size(interior_rings(poly));\r\n        range::resize(interior_rings(poly_out), count);\r\n\r\n        for (std::size_t i = 0 ; i < count ; ++i)\r\n        {\r\n            apply_ring(range::at(interior_rings(poly), i),\r\n                       range::at(interior_rings(poly_out), i),\r\n                       len, strategy);\r\n        }\r\n    }\r\n\r\n    template <typename Ring, typename RingOut, typename T, typename Strategy>\r\n    static void apply_ring(Ring const& ring, RingOut & ring_out,\r\n                           T const& len, Strategy const& strategy)\r\n    {\r\n        densify<Ring, RingOut, ring_tag, ring_tag>\r\n            ::apply(ring, ring_out, len, strategy);\r\n    }\r\n};\r\n\r\ntemplate <typename Geometry, typename GeometryOut>\r\nstruct densify<Geometry, GeometryOut, multi_polygon_tag, multi_polygon_tag>\r\n{\r\n    template <typename T, typename Strategy>\r\n    static void apply(Geometry const& mpoly, GeometryOut & mpoly_out,\r\n                      T const& len, Strategy const& strategy)\r\n    {\r\n        std::size_t count = boost::size(mpoly);\r\n        range::resize(mpoly_out, count);\r\n\r\n        for (std::size_t i = 0 ; i < count ; ++i)\r\n        {\r\n            apply_poly(range::at(mpoly, i),\r\n                       range::at(mpoly_out, i),\r\n                       len, strategy);\r\n        }\r\n    }\r\n\r\n    template <typename Poly, typename PolyOut, typename T, typename Strategy>\r\n    static void apply_poly(Poly const& poly, PolyOut & poly_out,\r\n                           T const& len, Strategy const& strategy)\r\n    {\r\n        densify<Poly, PolyOut, polygon_tag, polygon_tag>::\r\n            apply(poly, poly_out, len, strategy);\r\n    }\r\n};\r\n\r\n\r\n} // namespace dispatch\r\n#endif // DOXYGEN_NO_DISPATCH\r\n\r\n\r\nnamespace resolve_strategy\r\n{\r\n\r\nstruct densify\r\n{\r\n    template <typename Geometry, typename Distance, typename Strategy>\r\n    static inline void apply(Geometry const& geometry,\r\n                             Geometry& out,\r\n                             Distance const& max_distance,\r\n                             Strategy const& strategy)\r\n    {\r\n        dispatch::densify<Geometry, Geometry>\r\n            ::apply(geometry, out, max_distance, strategy);\r\n    }\r\n\r\n    template <typename Geometry, typename Distance>\r\n    static inline void apply(Geometry const& geometry,\r\n                             Geometry& out,\r\n                             Distance const& max_distance,\r\n                             default_strategy)\r\n    {\r\n        typedef typename strategy::densify::services::default_strategy\r\n            <\r\n                typename cs_tag<Geometry>::type\r\n            >::type strategy_type;\r\n        \r\n        /*BOOST_CONCEPT_ASSERT(\r\n            (concepts::DensifyStrategy<strategy_type>)\r\n        );*/\r\n\r\n        apply(geometry, out, max_distance, strategy_type());\r\n    }\r\n};\r\n\r\n} // namespace resolve_strategy\r\n\r\n\r\nnamespace resolve_variant {\r\n\r\ntemplate <typename Geometry>\r\nstruct densify\r\n{\r\n    template <typename Distance, typename Strategy>\r\n    static inline void apply(Geometry const& geometry,\r\n                             Geometry& out,\r\n                             Distance const& max_distance,\r\n                             Strategy const& strategy)\r\n    {\r\n        resolve_strategy::densify::apply(geometry, out, max_distance, strategy);\r\n    }\r\n};\r\n\r\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\r\nstruct densify<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\r\n{\r\n    template <typename Distance, typename Strategy>\r\n    struct visitor: boost::static_visitor<void>\r\n    {\r\n        Distance const& m_max_distance;\r\n        Strategy const& m_strategy;\r\n\r\n        visitor(Distance const& max_distance, Strategy const& strategy)\r\n            : m_max_distance(max_distance)\r\n            , m_strategy(strategy)\r\n        {}\r\n\r\n        template <typename Geometry>\r\n        void operator()(Geometry const& geometry, Geometry& out) const\r\n        {\r\n            densify<Geometry>::apply(geometry, out, m_max_distance, m_strategy);\r\n        }\r\n    };\r\n\r\n    template <typename Distance, typename Strategy>\r\n    static inline void\r\n    apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry,\r\n          boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>& out,\r\n          Distance const& max_distance,\r\n          Strategy const& strategy)\r\n    {\r\n        boost::apply_visitor(\r\n            visitor<Distance, Strategy>(max_distance, strategy),\r\n            geometry,\r\n            out\r\n        );\r\n    }\r\n};\r\n\r\n} // namespace resolve_variant\r\n\r\n\r\n/*!\r\n\\brief Densify a geometry using a specified strategy\r\n\\ingroup densify\r\n\\tparam Geometry \\tparam_geometry\r\n\\tparam Distance A numerical distance measure\r\n\\tparam Strategy A type fulfilling a DensifyStrategy concept\r\n\\param geometry Input geometry, to be densified\r\n\\param out Output geometry, densified version of the input geometry\r\n\\param max_distance Distance threshold (in units depending on strategy)\r\n\\param strategy Densify strategy to be used for densification\r\n\r\n\\qbk{distinguish,with strategy}\r\n\\qbk{[include reference/algorithms/densify.qbk]}\r\n\r\n\\qbk{\r\n[heading Available Strategies]\r\n\\* [link geometry.reference.strategies.strategy_densify_cartesian Cartesian]\r\n\\* [link geometry.reference.strategies.strategy_densify_spherical Spherical]\r\n\\* [link geometry.reference.strategies.strategy_densify_geographic Geographic]\r\n\r\n[heading Example]\r\n[densify_strategy]\r\n[densify_strategy_output]\r\n\r\n[heading See also]\r\n\\* [link geometry.reference.algorithms.line_interpolate line_interpolate]\r\n}\r\n*/\r\ntemplate <typename Geometry, typename Distance, typename Strategy>\r\ninline void densify(Geometry const& geometry,\r\n                    Geometry& out,\r\n                    Distance const& max_distance,\r\n                    Strategy const& strategy)\r\n{\r\n    concepts::check<Geometry>();\r\n\r\n    if (max_distance <= Distance(0))\r\n    {\r\n        BOOST_THROW_EXCEPTION(geometry::invalid_input_exception());\r\n    }\r\n\r\n    geometry::clear(out);\r\n\r\n    resolve_variant::densify\r\n        <\r\n            Geometry\r\n        >::apply(geometry, out, max_distance, strategy);\r\n}\r\n\r\n\r\n/*!\r\n\\brief Densify a geometry\r\n\\ingroup densify\r\n\\tparam Geometry \\tparam_geometry\r\n\\tparam Distance A numerical distance measure\r\n\\param geometry Input geometry, to be densified\r\n\\param out Output geometry, densified version of the input geometry\r\n\\param max_distance Distance threshold (in units depending on coordinate system)\r\n\r\n\\qbk{[include reference/algorithms/densify.qbk]}\r\n\r\n\\qbk{\r\n[heading Example]\r\n[densify]\r\n[densify_output]\r\n\r\n[heading See also]\r\n\\* [link geometry.reference.algorithms.line_interpolate line_interpolate]\r\n}\r\n*/\r\ntemplate <typename Geometry, typename Distance>\r\ninline void densify(Geometry const& geometry,\r\n                    Geometry& out,\r\n                    Distance const& max_distance)\r\n{\r\n    densify(geometry, out, max_distance, default_strategy());\r\n}\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DENSIFY_HPP\r\n", "meta": {"hexsha": "33571972c2617b05601f57265024f4dde34b7d80", "size": 12904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/algorithms/densify.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": 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": "deps/boost/include/boost/geometry/algorithms/densify.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": 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": "deps/boost/include/boost/geometry/algorithms/densify.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": 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": 29.8013856813, "max_line_length": 86, "alphanum_fraction": 0.6333694978, "num_tokens": 2769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.033085981487302796, "lm_q1q2_score": 0.009000199261588682}}
{"text": "/**\n * @file preform_hybrid.cpp\n *\n */\n\n#define AND &&\n#define OR ||\n#define MISS kFloatMissing\n\n#include \"preform_hybrid.h\"\n#include \"forecast_time.h\"\n#include \"level.h\"\n#include \"logger.h\"\n#include \"plugin_factory.h\"\n#include \"util.h\"\n#include <boost/thread.hpp>\n#include <iostream>\n\n#include \"hitool.h\"\n\nusing namespace std;\nusing namespace himan;\nusing namespace himan::plugin;\n\n// 0. Mallissa sadetta (RR>0; RR = rainfall + snowfall, [RR]=mm/h)\n//\n// 1. Jäätävää tihkua, jos\n//     RR <= 0.2\n//     -10 < T2m < 0\n//     sade ei konvektiivista (ConvPre mm/h = 0)\n//     stratus (base<300m ja määrä vähintään 5/8)\n//     stratuksessa (heikkoa) nousuliikettä (0<wAvg<50mm/s)\n//     stratus riittävän paksu (dz>800m)\n//     stratus Ttop > -12C\n//     stratus avgT > -12C\n//     -10C < T2m < 0C\n//     kuiva kerros (paksuus>1.5km, jossa N<30%) stratuksen yläpuolella\n//\n// 2. Jäätävää vesisadetta, jos\n//     T2m <= 0\n//     riittävän paksu/lämmin (pinta-ala>100mC) sulamiskerros pinnan yläpuolella\n//     riittävän paksu/kylmä (pinta-ala<-100mC) pakkaskerros pinnassa sulamiskerroksen alapuolella\n//     jos on stratus, sulamiskerros sen yllä ei saa olla kuiva\n//\n// 3. Tihkua tai vettä, jos\n//     riittävän paksu ja lämmin plussakerros pinnan yläpuolella\n//\n//   3.1 Tihkua, jos\n//        RR <= 0.3\n//        stratus (base<300m ja määrä vähintään 5/8)\n//        stratus riittävän paksu (dz>500m)\n//        kuiva kerros (dz>1.5km, jossa N<30%) stratuksen yläpuolella\n//\n//   3.2 Muuten vettä\n//\n//   3.3 Jos pinnan plussakerroksessa on kuivaa (rhAvg<rhMelt), muutetaan olomuoto vedestä rännäksi\n//\n// 4. Räntää, jos\n//     ei liian paksu/lämmin plussakerros pinnan yläpuolella\n//\n//   4.1 Jos pinnan plussakerroksessa on kuivaa (rhAvg<rhMelt), muutetaan olomuoto rännästä lumeksi\n//\n// 5. Muuten lunta\n//     korkeintaan ohut plussakerros pinnan yläpuolella\n\n// Korkein sallittu pilven alarajan korkeus, jotta kysessä stratus [m]\nconst double baseLimit = 300.;\n\n// Vaadittu min. stratuksen paksuus tihkussa ja jäätävässä tihkussa [m]\nconst double stLimit = 500.;\nconst double fzStLimit = 800.;\n\n// Kylmin sallittu stratuksen topin T ja kylmin sallittu st:n keskim. T [C] jäätävässä tihkussa\nconst double stTlimit = -12.;\n\n// Kynnysarvo \"riittävän yhtenäisen/ei kerroksittaisen\" stratuksen keskim. N-arvolle [%]\nconst double Nlimit = 70.;\n\n// Vaadittu 2m lämpötilaväli (oltava näiden välissä) [C] jäätävässä tihkussa\nconst double sfcMax = 0.;\nconst double sfcMin = -10.;\n\n// Max. sallittu pilven (keskimääräinen) määrä (N) stratuksen yläpuolisessa kerroksessa [%] (jäätävässä) tihkussa\n// (käytetään myös jäätävässä sateessa vaadittuna pilven minimimääränä)\nconst double dryNlim = 0.3;\n\n// Kynnysarvo vaaditulle stratuksen yläpuolisen kuivan kerroksen paksuudelle [m] jää]\n// Raja-arvot tihkun ja jäätävän tihkun max intensiteetille [mm/h]\n// (pienemmällä jäätävän tihkun raja-arvolla voi hieman rajoittaa sen esiintymistä)\nconst double dzLim = 0.3;\nconst double fzdzLim = 0.2;\n\n// Raja-arvot pinnan pakkaskerroksen (MA) ja sen yläpuolisen sulamiskerroksen (PA) pinta-alalle jäätävässä sateessa [mC]\nconst double fzraMA = -100.;\nconst double fzraPA = 100.;\n\n// Pinnan yläpuolisen plussakerroksen pinta-alan raja-arvot [mC, \"metriastetta\"]:\nconst double waterArea = 200.;  // alkup. PK:n arvo oli 300\nconst double snowArea = 50.;    // alkup. PK:n arvo oli 50\n\n// Max sallittu nousuliike st:ssa [mm/s]\nconst double wMax = 50.;\n\nconst param stratusBaseParam(\"STRATUS-BASE-M\");\nconst param stratusTopParam(\"STRATUS-TOP-M\");\nconst param stratusTopTempParam(\"STRATUS-TOP-T-K\");\nconst param stratusMeanTempParam(\"STRATUS-MEAN-T-K\");\nconst param stratusMeanCloudinessParam(\"STRATUS-MEAN-N-PRCNT\");\nconst param stratusUpperLayerNParam(\"STRATUS-UPPER-LAYER-N-PRCNT\");\nconst param stratusVerticalVelocityParam(\"STRATUS-VERTICAL-VELOCITY-MMS\");\n\nconst param minusAreaParam(\"MINUS-AREA-MC\");        // metriastetta, mC\nconst param plusAreaParam(\"PLUS-AREA-MC\");          // metriastetta, mC\nconst param plusAreaSfcParam(\"PLUS-AREA-SFC-MC\");   // metriastetta, mC\nconst param numZeroLevelsParam(\"NUMZEROLEVELS-N\");  // nollakohtien lkm\nconst param rhAvgParam(\"RHAVG-PRCNT\");\nconst param rhAvgUpperParam(\"RHAVG-UPPER-PRCNT\");\nconst param rhMeltParam(\"RHMELT-PRCNT\");\nconst param rhMeltUpperParam(\"RHMELT-UPPER-PRCNT\");\n\npreform_hybrid::preform_hybrid()\n{\n\titsLogger = logger(\"preform_hybrid\");\n}\n\nvoid preform_hybrid::Process(std::shared_ptr<const plugin_configuration> conf)\n{\n\t// Initialize plugin\n\n\tInit(conf);\n\n\tvector<param> params({param(\"PRECFORM2-N\", 1206, 0, 1, 19)});\n\n\tif (itsConfiguration->Exists(\"potential_precipitation_form\") &&\n\t    itsConfiguration->GetValue(\"potential_precipitation_form\") == \"true\")\n\t{\n\t\tparams.push_back(param(\"POTPRECF-N\", 1226, 0, 1, 254));\n\t}\n\n\tSetParams(params);\n\n\tStart();\n}\n\n/*\n * Calculate()\n *\n * This function does the actual calculation.\n */\n\nvoid preform_hybrid::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)\n{\n\tassert(fzStLimit >= stLimit);\n\n\t// Required source parameters\n\n\tparams RRParam({param(\"RR-1-MM\"), param(\"RRR-KGM2\")});  // one hour prec OR precipitation rate (HHsade)\n\tconst param TParam(\"T-K\");\n\tconst param RHParam(\"RH-PRCNT\");\n\n\tlevel surface0mLevel(kHeight, 0);\n\tlevel surface2mLevel(kHeight, 2);\n\n\tauto myThreadedLogger = logger(\"preformHybridThread #\" + to_string(threadIndex));\n\n\tforecast_time forecastTime = myTargetInfo->Time();\n\tlevel forecastLevel = myTargetInfo->Level();\n\tforecast_type forecastType = myTargetInfo->ForecastType();\n\n\tmyThreadedLogger.Info(\"Calculating time \" + static_cast<string>(forecastTime.ValidDateTime()) + \" level \" +\n\t                      static_cast<string>(forecastLevel));\n\n\t// Source infos\n\n\tinfo_t RRInfo = Fetch(forecastTime, surface0mLevel, RRParam, forecastType, false);\n\tinfo_t TInfo = Fetch(forecastTime, surface2mLevel, TParam, forecastType, false);\n\n\tif (!RRInfo || !TInfo)\n\t{\n\t\tmyThreadedLogger.Warning(\"Skipping step \" + to_string(forecastTime.Step()) + \", level \" +\n\t\t                         static_cast<string>(forecastLevel));\n\t\treturn;\n\t}\n\n\tinfo_t stratus;\n\tinfo_t freezingArea;\n\n\t/*\n\t * Spinoff thread will calculate freezing area while main thread calculates\n\t * stratus.\n\t *\n\t * The constructor of std::thread (and boost::thread) deduces argument types\n\t * and stores them *by value*.\n\t */\n\n\tboost::thread t(&preform_hybrid::FreezingArea, this, itsConfiguration, forecastTime, forecastType,\n\t                boost::ref(freezingArea), myTargetInfo->Grid());\n\n\tStratus(itsConfiguration, forecastTime, forecastType, stratus, myTargetInfo->Grid());\n\n\tt.join();\n\n\tif (!stratus)\n\t{\n\t\tmyThreadedLogger.Error(\"stratus calculation failed, unable to proceed\");\n\t\treturn;\n\t}\n\n\tif (!freezingArea)\n\t{\n\t\tmyThreadedLogger.Error(\"freezingArea calculation failed, unable to proceed\");\n\t\treturn;\n\t}\n\n\tfreezingArea->First();\n\tstratus->First();\n\n\tmyThreadedLogger.Info(\"Stratus and freezing area calculated\");\n\n\tstring deviceType = \"CPU\";\n\n\tassert(myTargetInfo->SizeLocations() == stratus->SizeLocations());\n\tassert(myTargetInfo->SizeLocations() == freezingArea->SizeLocations());\n\tassert(myTargetInfo->SizeLocations() == TInfo->SizeLocations());\n\tassert(myTargetInfo->SizeLocations() == RRInfo->SizeLocations());\n\n\tmyTargetInfo->FirstParam();\n\n\tbool noPotentialPrecipitationForm = (myTargetInfo->SizeParams() == 1);\n\n\tint DRIZZLE = 0;\n\tint RAIN = 1;\n\tint SLEET = 2;\n\tint SNOW = 3;\n\tint FREEZING_DRIZZLE = 4;\n\tint FREEZING_RAIN = 5;\n\n\tLOCKSTEP(myTargetInfo, stratus, freezingArea, TInfo, RRInfo)\n\t{\n\t\tstratus->Param(stratusBaseParam);\n\t\tdouble base = stratus->Value();\n\n\t\tstratus->Param(stratusTopParam);\n\t\tdouble top = stratus->Value();\n\n\t\tstratus->Param(stratusUpperLayerNParam);\n\t\tdouble upperLayerN = stratus->Value();\n\n\t\tstratus->Param(stratusVerticalVelocityParam);\n\t\tdouble wAvg = stratus->Value();\n\n\t\tstratus->Param(stratusMeanCloudinessParam);\n\t\tdouble Navg = stratus->Value();\n\n\t\tstratus->Param(stratusMeanTempParam);\n\t\tdouble stTavg = stratus->Value();\n\n\t\tstratus->Param(stratusTopTempParam);\n\t\tdouble Ttop = stratus->Value();\n\n\t\tfreezingArea->Param(plusAreaParam);\n\t\tdouble plusArea = freezingArea->Value();\n\n\t\tfreezingArea->Param(plusAreaSfcParam);\n\t\tdouble plusAreaSfc = freezingArea->Value();\n\n\t\tfreezingArea->Param(minusAreaParam);\n\t\tdouble minusArea = freezingArea->Value();\n\n\t\tfreezingArea->Param(numZeroLevelsParam);\n\t\tdouble nZeroLevel = freezingArea->Value();\n\n\t\tfreezingArea->Param(rhAvgParam);\n\t\tdouble rhAvg = freezingArea->Value();\n\n\t\tfreezingArea->Param(rhAvgUpperParam);\n\t\tdouble rhAvgUpper = freezingArea->Value();\n\n\t\tfreezingArea->Param(rhMeltParam);\n\t\tdouble rhMelt = freezingArea->Value();\n\n\t\tfreezingArea->Param(rhMeltUpperParam);\n\t\tdouble rhMeltUpper = freezingArea->Value();\n\n\t\tdouble RR = RRInfo->Value();\n\t\tdouble T = TInfo->Value();\n\n\t\tif (RR == MISS || T == MISS)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (RR == 0 && noPotentialPrecipitationForm)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble PreForm = MISS;\n\n\t\t// Unit conversions\n\n\t\tT -= himan::constants::kKelvin;  // K --> C\n\n\t\tif (Ttop != MISS)\n\t\t{\n\t\t\tTtop -= himan::constants::kKelvin;\n\t\t}\n\n\t\tif (stTavg != MISS)\n\t\t{\n\t\t\tstTavg -= himan::constants::kKelvin;\n\t\t}\n\n\t\tif (Navg != MISS)\n\t\t{\n\t\t\tNavg *= 100;  // --> %\n\t\t}\n\n\t\tassert(T >= -80 && T < 80);\n\t\tassert(!noPotentialPrecipitationForm || RR > 0);\n\t\tassert(Navg == MISS || (Navg >= 0 && Navg <= 100));\n\n\t\t// Start algorithm\n\t\t// Possible values for preform: 0 = tihku, 1 = vesi, 2 = räntä, 3 = lumi, 4 = jäätävä tihku, 5 = jäätävä sade\n\n\t\t// 1. jäätävää tihkua? (tai lumijyväsiä)\n\n\t\tif (base != MISS AND top != MISS AND upperLayerN != MISS AND wAvg != MISS AND Navg != MISS AND stTavg !=\n\t\t    MISS AND Ttop !=\n\t\t    MISS AND RR <=\n\t\t        fzdzLim AND\n\t\t            base<baseLimit AND(top - base) >= fzStLimit AND wAvg<wMax AND wAvg >= 0 AND Navg> Nlimit AND Ttop>\n\t\t                stTlimit AND stTavg > stTlimit AND T > sfcMin AND T <= sfcMax AND upperLayerN < dryNlim)\n\t\t{\n\t\t\tPreForm = FREEZING_DRIZZLE;\n\t\t}\n\n\t\t// 2. jäätävää vesisadetta? (tai jääjyväsiä (ice pellets), jos pakkaskerros hyvin paksu, ja/tai sulamiskerros\n\t\t// ohut)\n\t\t// Löytyykö riittävän paksut: pakkaskerros pinnasta ja sen yläpuolelta plussakerros, jossa pilveä/ei liian\n\t\t// kuivaa?\n\t\t// (Huom. hyvin paksu pakkaskerros (tai ohut sulamiskerros) -> oikeasti jääjyväsiä/ice pellets fzra sijaan)\n\n\t\tif (PreForm == MISS AND plusArea != MISS AND minusArea != MISS AND rhAvgUpper != MISS AND rhMeltUpper !=\n\t\t    MISS AND plusArea >\n\t\t        fzraPA AND minusArea<fzraMA AND T <= 0 AND(upperLayerN == MISS OR upperLayerN > dryNlim) AND rhAvgUpper>\n\t\t            rhMeltUpper)\n\t\t{\n\t\t\tPreForm = FREEZING_RAIN;\n\t\t}\n\n\t\t// 3. Lunta, räntää, tihkua vai vettä? PK:n koodia mukaillen\n\n\t\tif (PreForm == MISS)\n\t\t{\n\t\t\t// Tihkua tai vettä jos \"riitävän paksu lämmin kerros pinnan yläpuolella\"\n\n\t\t\tif (plusArea != MISS AND plusArea > waterArea)\n\t\t\t{\n\t\t\t\t// Tihkua jos riittävän paksu stratus heikolla sateen intensiteetillä ja yläpuolella kuiva kerros\n\t\t\t\t// AND (ConvPre=0) poistettu alla olevasta (ConvPre mm/h puuttuu EC:stä; Hirlam-versiossa pidetään\n\t\t\t\t// mukana)\n\t\t\t\tif (base != MISS && top != MISS && Navg != MISS && upperLayerN != MISS && RR <= dzLim &&\n\t\t\t\t    base < baseLimit && (top - base) > stLimit && Navg > Nlimit && upperLayerN < dryNlim)\n\t\t\t\t{\n\t\t\t\t\tPreForm = DRIZZLE;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tPreForm = RAIN;\n\t\t\t\t}\n\n\t\t\t\t// Jos pinnan plussakerroksessa on kuivaa, korjataan olomuodoksi räntä veden sijaan\n\n\t\t\t\tif (nZeroLevel != MISS AND rhAvg != MISS AND rhMelt != MISS AND nZeroLevel ==\n\t\t\t\t    1 AND rhAvg < rhMelt AND plusArea < 4000)\n\t\t\t\t{\n\t\t\t\t\tPreForm = SLEET;\n\t\t\t\t}\n\n\t\t\t\t// Lisäys, jolla korjataan vesi/tihku lumeksi, jos pintakerros pakkasella (mutta jäätävän sateen/tihkun\n\t\t\t\t// kriteerit eivät toteudu,\n\t\t\t\t// esim. paksu plussakerros pakkas-st/sc:n yllä)\n\t\t\t\tif (minusArea != MISS OR(plusAreaSfc != MISS AND plusAreaSfc < snowArea))\n\t\t\t\t{\n\t\t\t\t\tPreForm = SNOW;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Räntää jos \"ei liian paksu lämmin kerros pinnan yläpuolella\"\n\n\t\t\tif (plusArea != MISS AND plusArea >= snowArea AND plusArea <= waterArea)\n\t\t\t{\n\t\t\t\tPreForm = SLEET;\n\n\t\t\t\t// Jos pinnan plussakerroksessa on kuivaa, korjataan olomuodoksi lumi rännän sijaan\n\n\t\t\t\tif (nZeroLevel != MISS AND rhAvg != MISS AND rhMelt != MISS AND nZeroLevel == 1 AND rhAvg < rhMelt)\n\t\t\t\t{\n\t\t\t\t\tPreForm = SNOW;\n\t\t\t\t}\n\n\t\t\t\t// lisäys, jolla korjataan räntä lumeksi, kun pintakerros pakkasella tai vain ohuelti plussalla\n\n\t\t\t\tif (minusArea != MISS OR(plusAreaSfc != MISS AND plusAreaSfc < snowArea))\n\t\t\t\t{\n\t\t\t\t\tPreForm = SNOW;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Muuten lunta (PlusArea<50: \"korkeintaan ohut lämmin kerros pinnan yläpuolella\")\n\n\t\t\tif (plusArea == MISS OR plusArea < snowArea)\n\t\t\t{\n\t\t\t\tPreForm = SNOW;\n\t\t\t}\n\t\t}\n\n\t\t// FINISHED\n\n\t\tif (RR == 0)\n\t\t{\n\t\t\t// If RR is zero, we can only have potential prec form\n\t\t\tmyTargetInfo->ParamIndex(1);\n\t\t\tmyTargetInfo->Value(PreForm);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// If there is precipitation, we have at least regular prec form\n\t\t\tmyTargetInfo->ParamIndex(0);\n\t\t\tmyTargetInfo->Value(PreForm);\n\n\t\t\tif (!noPotentialPrecipitationForm)\n\t\t\t{\n\t\t\t\t// Also potential prec form\n\t\t\t\tmyTargetInfo->ParamIndex(1);\n\t\t\t\tmyTargetInfo->Value(PreForm);\n\t\t\t}\n\t\t}\n\t}\n\n\tmyThreadedLogger.Info(\"[\" + deviceType + \"] Missing values: \" + to_string(myTargetInfo->Data().MissingCount()) +\n\t                      \"/\" + to_string(myTargetInfo->Data().Size()));\n}\n\nvoid preform_hybrid::FreezingArea(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime,\n                                  const forecast_type& ftype, shared_ptr<info>& result, const grid* baseGrid)\n{\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(conf);\n\th->Time(ftime);\n\th->ForecastType(ftype);\n\n\tvector<param> params = {minusAreaParam, plusAreaParam,   plusAreaSfcParam, numZeroLevelsParam,\n\t                        rhAvgParam,     rhAvgUpperParam, rhMeltParam,      rhMeltUpperParam};\n\tvector<forecast_time> times = {ftime};\n\tvector<level> levels = {level(kHeight, 0, \"HEIGHT\")};\n\n\tauto ret = make_shared<info>(*conf->Info());\n\tret->Params(params);\n\tret->Levels(levels);\n\tret->Times(times);\n\tret->Create(baseGrid);\n\n\tvector<double> constData1(ret->Data().Size(), 0);\n\n\tauto constData2 = constData1;\n\tfill(constData2.begin(), constData2.end(), 5000);\n\n\tauto constData3 = constData1;\n\tfill(constData3.begin(), constData3.end(), himan::constants::kKelvin);  // 0C\n\n\tvector<double> numZeroLevels, zeroLevel1, zeroLevel2, zeroLevel3, zeroLevel4;\n\tvector<double> Tavg01, Tavg12, Tavg23, Tavg34;\n\tvector<double> plusArea, minusArea, plusAreaSfc;\n\tvector<double> rhAvg01, rhAvgUpper12, rhAvgUpper23;\n\n\tauto log = logger(\"preform_hybrid-freezing_area\");\n\n\ttry\n\t{\n\t\t// 0-kohtien lkm pinnasta (yläraja 5km, jotta ylinkin nollakohta varmasti löytyy)\n\n\t\tparam wantedParam(\"T-K\");\n\n\t\tlog.Trace(\"Counting number of zero levels\");\n\n\t\tnumZeroLevels = h->VerticalCount(wantedParam, constData1, constData2, constData3);\n\n\t\tret->Param(numZeroLevelsParam);\n\t\tret->Data().Set(numZeroLevels);\n\n#ifdef DEBUG\n\t\tfor (size_t i = 0; i < numZeroLevels.size(); i++)\n\t\t{\n\t\t\tassert(numZeroLevels[i] != MISS);\n\t\t}\n\n\t\tutil::DumpVector(numZeroLevels, \"num zero levels\");\n#endif\n\n\t\tzeroLevel1.resize(numZeroLevels.size(), MISS);\n\t\tzeroLevel2.resize(numZeroLevels.size(), MISS);\n\t\tzeroLevel3.resize(numZeroLevels.size(), MISS);\n\t\tzeroLevel4.resize(numZeroLevels.size(), MISS);\n\n\t\trhAvgUpper12.resize(numZeroLevels.size(), MISS);\n\t\trhAvgUpper23.resize(numZeroLevels.size(), MISS);\n\n\t\t// Keskim. lämpötila 1. nollarajan alapuolella, 1/2. ja 2/3. nollarajojen välisissä kerroksissa [C]\n\t\tTavg01.resize(numZeroLevels.size(), MISS);\n\t\tTavg12.resize(numZeroLevels.size(), MISS);\n\t\tTavg23.resize(numZeroLevels.size(), MISS);\n\t\tTavg34.resize(numZeroLevels.size(), MISS);\n\n\t\t// 1. nollarajan alapuolisen, 2/3. nollarajojen välisen, ja koko T>0 alueen koko [mC, \"metriastetta\"]\n\t\tplusArea = zeroLevel1;\n\t\tplusAreaSfc = zeroLevel1;\n\n\t\t// Mahdollisen pinta- tai 1/2. nollarajojen välisen pakkaskerroksen koko [mC, \"metriastetta\"]\n\t\tminusArea = zeroLevel1;\n\n\t\tlog.Trace(\"Searching for first zero level height\");\n\t\tzeroLevel1 = h->VerticalHeight(wantedParam, constData1, constData2, constData3, 1);\n\n#ifdef DEBUG\n\t\tutil::DumpVector(zeroLevel1, \"zero level 1\");\n#endif\n\n\t\tlog.Trace(\"Searching for average temperature between ground level and first zero level\");\n\t\tTavg01 = h->VerticalAverage(wantedParam, constData1, zeroLevel1);\n\n#ifdef DEBUG\n\t\tutil::DumpVector(Tavg01, \"tavg 01\");\n#endif\n\n\t\twantedParam = param(\"RH-PRCNT\");\n\n\t\tlog.Trace(\"Searching for average humidity between ground and first zero level\");\n\t\t// Keskimääräinen RH nollarajan alapuolisessa plussakerroksessa\n\t\trhAvg01 = h->VerticalAverage(wantedParam, constData1, zeroLevel1);\n\n#ifdef DEBUG\n\t\tutil::DumpVector(rhAvg01, \"rh avg 01\");\n#endif\n\n\t\t// Only the first zero layer with at least one non-missing element is required\n\t\t// to be present. All other zero layers (2,3,4) are optional.\n\n\t\ttry\n\t\t{\n\t\t\t// Values between zero levels 1 <--> 2\n\t\t\twantedParam = param(\"T-K\");\n\n\t\t\tlog.Trace(\"Searching for second zero level height\");\n\t\t\tzeroLevel2 = h->VerticalHeight(wantedParam, constData1, constData2, constData3, 2);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(zeroLevel2, \"zero level 2\");\n#endif\n\n\t\t\tlog.Trace(\"Searching for average temperature between first and second zero level\");\n\t\t\tTavg12 = h->VerticalAverage(wantedParam, zeroLevel1, zeroLevel2);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(Tavg12, \"tavg 12\");\n#endif\n\n\t\t\tlog.Trace(\"Searching for average humidity between first and second zero level\");\n\n\t\t\t// Keskimääräinen RH pakkaskerroksen yläpuolisessa plussakerroksessa\n\t\t\twantedParam = param(\"RH-PRCNT\");\n\n\t\t\trhAvgUpper12 = h->VerticalAverage(wantedParam, zeroLevel1, zeroLevel2);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(rhAvgUpper12, \"rh avg upper 12\");\n#endif\n\n\t\t\t// 2 <--> 3\n\t\t\twantedParam = param(\"T-K\");\n\n\t\t\tlog.Trace(\"Searching for third zero level height\");\n\t\t\tzeroLevel3 = h->VerticalHeight(wantedParam, constData1, constData2, constData3, 3);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(zeroLevel3, \"zero level 3\");\n#endif\n\n\t\t\tlog.Trace(\"Searching for average temperature between second and third zero level\");\n\t\t\tTavg23 = h->VerticalAverage(wantedParam, zeroLevel2, zeroLevel3);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(Tavg23, \"tavg 23\");\n#endif\n\n\t\t\twantedParam = param(\"RH-PRCNT\");\n\n\t\t\tlog.Trace(\"Searching for average humidity between second and third zero level\");\n\n\t\t\t// Keskimääräinen RH ylemmässä plussakerroksessa\n\t\t\trhAvgUpper23 = h->VerticalAverage(wantedParam, zeroLevel2, zeroLevel3);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(rhAvgUpper23, \"rh avg upper 23\");\n#endif\n\n\t\t\t// 3 <--> 4\n\t\t\twantedParam = param(\"T-K\");\n\n\t\t\tlog.Trace(\"Searching for fourth zero level height\");\n\t\t\tzeroLevel4 = h->VerticalHeight(wantedParam, constData1, constData2, constData3, 4);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(zeroLevel4, \"zero level 4\");\n#endif\n\n\t\t\tlog.Trace(\"Searching for average temperature between third and fourth zero level\");\n\t\t\tTavg34 = h->VerticalAverage(wantedParam, zeroLevel3, zeroLevel4);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(Tavg34, \"tavg 34\");\n#endif\n\t\t}\n\t\tcatch (const HPExceptionType& e)\n\t\t{\n\t\t\tif (e == kFileDataNotFound)\n\t\t\t{\n\t\t\t\tlog.Debug(\"Some zero level not found from entire data\");\n\t\t\t}\n\t\t}\n\t}\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"FreezingArea() caught exception \" + to_string(e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// Keskimääräinen rhMelt nollarajan alapuolisessa plussakerroksessa, ja pakkaskerroksen yläpuolisessa\n\t// plussakerroksessa\n\tvector<double> rhMeltUpper(rhAvg01.size(), MISS);\n\tvector<double> rhMelt(rhAvg01.size(), MISS);\n\n\t// Keskimääräinen RH nollarajan alapuolisessa plussakerroksessa, ja pakkaskerroksen yläpuolisessa plussakerroksessa\n\tvector<double> rhAvgUpper(rhAvg01.size(), MISS);\n\tvector<double> rhAvg(rhAvg01.size(), MISS);\n\n\tfor (size_t i = 0; i < numZeroLevels.size(); i++)\n\t{\n\t\tshort numZeroLevel = static_cast<short>(numZeroLevels[i]);\n\n\t\tdouble pa = MISS, ma = MISS, pasfc = MISS;\n\n\t\t// Kommentteja Simolta nollakohtien lukumäärään:\n\t\t// * Nollakohtien löytymättömyys ei ole ongelma, sillä tällöin olomuoto on aina lumi tai jäätävä tihku\n\t\t// * Parittomilla nollakohdilla ei voi tulla koskaan jäätävää sadetta koska pintakerros on plussalla\n\t\t//   (jolloin ainakin yleensä pätee oletus ettei jäätävää sadetta voi esiintyä)\n\n\t\t// nollarajoja parillinen määrä (pintakerros pakkasella)\n\n\t\tif (numZeroLevel % 2 == 0)\n\t\t{\n\t\t\tdouble zl1 = zeroLevel1[i], zl2 = zeroLevel2[i];\n\t\t\tdouble ta1 = Tavg01[i], ta2 = Tavg12[i];\n\n\t\t\tdouble paloft = MISS;\n\n\t\t\tif (zl1 != MISS && zl2 != MISS && ta1 != MISS && ta2 != MISS)\n\t\t\t{\n\t\t\t\tta1 -= constants::kKelvin;\n\t\t\t\tta2 -= constants::kKelvin;\n\t\t\t\tma = zl1 * ta1;\n\t\t\t\tpaloft = (zl2 - zl1) * ta2;\n\n\t\t\t\t// Keskimääräinen rhMelt pakkaskerroksen yläpuolisessa plussakerroksessa\n\t\t\t\trhMeltUpper[i] = 9.5 * exp((-17.27 * ta2) / (ta2 + 238.3)) * (10.5 - ta2);\n\t\t\t}\n\n\t\t\trhAvgUpper[i] = rhAvgUpper12[i];\n\n\t\t\t// Jos ylempänä toinen T>0 kerros, lasketaan myös sen koko (vähintään 4 nollarajaa) ja lisätään se alemman\n\t\t\t// kerroksen kokoon\n\t\t\t// (mahdollisista vielä ylempänä olevista plussakerroksista ei välitetä)\n\t\t\t// (tässäkin pitäisi tarkkaan ottaen tutkia rhAvgUpper, eli sulaako kerroksen läpi putoava lumi)\n\n\t\t\tif (numZeroLevel >= 4)\n\t\t\t{\n\t\t\t\tdouble zl3 = zeroLevel3[i], zl4 = zeroLevel4[i];\n\t\t\t\tta2 = Tavg34[i];\n\n\t\t\t\tif (zl3 != MISS && zl4 != MISS && ta2 != MISS && paloft != MISS)\n\t\t\t\t{\n\t\t\t\t\tpaloft = paloft + (zl4 - zl3) * (ta2 - constants::kKelvin);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpa = paloft;\n\t\t}\n\n\t\t// nollarajoja pariton määrä (pintakerros plussalla)\n\n\t\telse if (numZeroLevel % 2 == 1)\n\t\t{\n\t\t\tdouble zl1 = zeroLevel1[i], ta1 = Tavg01[i];\n\t\t\tdouble paloft = MISS;\n\n\t\t\tif (zl1 != MISS && ta1 != MISS)\n\t\t\t{\n\t\t\t\tta1 -= constants::kKelvin;\n\t\t\t\tpasfc = zl1 * ta1;\n\t\t\t\tpa = pasfc;\n\n\t\t\t\t// Lisäys 3.2.2015: Suhteellisen kosteuden (raja-) arvot pinnan plussakerroksessa:\n\t\t\t\t// Jos nollarajan alapuolisessa plussakerroksessa on kuivaa, asetetaan olomuodoksi lumi\n\t\t\t\t// (Shaviv, 2006: http://www.sciencebits.com/SnowAboveFreezing)\n\n\t\t\t\t// rhMelt = suht. kosteuden raja-arvo, jota pienemmillä kosteuksilla lumihiutaleet eivät sula\n\n\t\t\t\t// Keskimääräinen rhMelt nollarajan alapuolisessa plussakerroksessa\n\n\t\t\t\trhMelt[i] = 9.5 * exp((-17.27 * ta1) / (ta1 + 238.3)) * (10.5 - ta1);\n\t\t\t}\n\n\t\t\t// Keskimääräinen RH nollarajan alapuolisessa plussakerroksessa\n\t\t\trhAvg[i] = rhAvg01[i];\n\n\t\t\t// Jos ylempänä toinen T>0 kerros, lasketaan myös sen koko (vähintään 3 nollarajaa)\n\t\t\t// (mahdollisista vielä ylempänä olevista plussakerroksista ei välitetä)\n\n\t\t\tif (numZeroLevel >= 3)\n\t\t\t{\n\t\t\t\tdouble zl2 = zeroLevel2[i], zl3 = zeroLevel3[i];\n\t\t\t\tdouble ta2 = Tavg23[i];\n\n\t\t\t\tif (zl2 != MISS && zl3 != MISS && ta2 != MISS)\n\t\t\t\t{\n\t\t\t\t\tta2 -= constants::kKelvin;\n\n\t\t\t\t\tpaloft = (zl3 - zl2) * ta2;\n\n\t\t\t\t\t// Keskimääräinen rhMelt ylemmässä plussakerroksessa\n\t\t\t\t\trhMeltUpper[i] = 9.5 * exp((-17.27 * ta2) / (ta2 + 238.3)) * (10.5 - ta2);\n\n\t\t\t\t\t// Keskimääräinen RH ylemmässä plussakerroksessa\n\t\t\t\t\trhAvgUpper[i] = rhAvgUpper23[i];\n\n\t\t\t\t\tif (rhAvgUpper[i] != MISS AND rhMeltUpper[i] != MISS AND rhAvgUpper[i] > rhMeltUpper[i] &&\n\t\t\t\t\t    pasfc != MISS)\n\t\t\t\t\t{\n\t\t\t\t\t\tpa = pasfc + paloft;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tplusArea[i] = pa;\n\t\tplusAreaSfc[i] = pasfc;\n\t\tminusArea[i] = ma;\n\t}\n\n#ifdef DEBUG\n\tutil::DumpVector(minusArea);\n\tutil::DumpVector(plusArea);\n\tutil::DumpVector(plusAreaSfc);\n\tutil::DumpVector(rhAvg);\n\tutil::DumpVector(rhAvgUpper);\n\tutil::DumpVector(rhMelt);\n\tutil::DumpVector(rhMeltUpper);\n#endif\n\n\tret->Param(minusAreaParam);\n\tret->Data().Set(minusArea);\n\n\tret->Param(plusAreaParam);\n\tret->Data().Set(plusArea);\n\n\tret->Param(plusAreaSfcParam);\n\tret->Data().Set(plusAreaSfc);\n\n\tret->Param(rhAvgParam);\n\tret->Data().Set(rhAvg);\n\n\tret->Param(rhAvgUpperParam);\n\tret->Data().Set(rhAvgUpper);\n\n\tret->Param(rhMeltParam);\n\tret->Data().Set(rhMelt);\n\n\tret->Param(rhMeltUpperParam);\n\tret->Data().Set(rhMeltUpper);\n\n\tresult = ret;\n}\n\nvoid preform_hybrid::Stratus(shared_ptr<const plugin_configuration> conf, const forecast_time& ftime,\n                             const forecast_type& ftype, shared_ptr<info>& result, const grid* baseGrid)\n{\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(conf);\n\th->Time(ftime);\n\th->ForecastType(ftype);\n\n\t// Kerroksen paksuus pinnasta [m], josta etsitään stratusta (min. BaseLimit+FZstLimit)\n\tconst double layer = 2000.;\n\n\t// N-kynnysarvo vaaditulle min. stratuksen määrälle [%] (50=yli puoli taivasta):\n\tconst double stCover = 0.5;\n\n\t// Kynnysarvo vaaditulle stratuksen yläpuolisen kuivan kerroksen paksuudelle [m] (jäätävässä) tihkussa:\n\tconst double drydz = 1500.;\n\n\tvector<param> params = {\n\t    stratusBaseParam,           stratusTopParam,         stratusTopTempParam,         stratusMeanTempParam,\n\t    stratusMeanCloudinessParam, stratusUpperLayerNParam, stratusVerticalVelocityParam};\n\tvector<forecast_time> times = {ftime};\n\tvector<level> levels = {level(kHeight, 0, \"HEIGHT\")};\n\n\tauto ret = make_shared<info>(*conf->Info());\n\tret->Params(params);\n\tret->Levels(levels);\n\tret->Times(times);\n\tret->Create(baseGrid);\n\n\tvector<double> constData1(ret->Data().Size(), 0);\n\n\tauto constData2 = constData1;\n\tauto log = logger(\"preform_hybrid-stratus\");\n\n\ttry\n\t{\n\t\t// baseThreshold ja topThreshold:\n\t\t// (Paikan mukaan vaihtuva) N-kynnysarvo stratuksen ala- ja ylärajalle [%] (tarkkaa stCover arvoa ei aina löydy)\n\n\t\tvector<param> wantedParamList({param(\"N-0TO1\"), param(\"N-PRCNT\")});\n\n\t\tlog.Info(\"Searching for stratus lower limit\");\n\n\t\tauto baseThreshold = h->VerticalMinimum(wantedParamList, 0, stLimit);\n\n\t\tfor (size_t i = 0; i < baseThreshold.size(); i++)\n\t\t{\n\t\t\tassert(baseThreshold[i] != MISS);\n\n\t\t\tif (baseThreshold[i] < stCover)\n\t\t\t{\n\t\t\t\tbaseThreshold[i] = stCover;\n\t\t\t}\n\t\t}\n\n#ifdef DEBUG\n\t\tutil::DumpVector(baseThreshold);\n#endif\n\n\t\tret->Param(stratusBaseParam);\n\t\tret->Data().Set(baseThreshold);\n\n\t\tlog.Info(\"Searching for stratus upper limit\");\n\n\t\tauto topThreshold = h->VerticalMinimum(wantedParamList, stLimit, layer);\n\n\t\tfor (size_t i = 0; i < topThreshold.size(); i++)\n\t\t{\n\t\t\tassert(topThreshold[i] != MISS);\n\t\t\tif (topThreshold[i] < stCover)\n\t\t\t{\n\t\t\t\ttopThreshold[i] = stCover;\n\t\t\t}\n\t\t}\n\n#ifdef DEBUG\n\t\tutil::DumpVector(topThreshold);\n#endif\n\n\t\t// Stratus Base/top [m]\n\t\t// _findh: 0 = viimeinen löytyvä arvo pinnasta ylöspäin, 1 = ensimmäinen löytyvä arvo\n\n\t\tlog.Info(\"Searching for stratus base accurate value\");\n\n\t\tauto stratusBase = h->VerticalHeight(wantedParamList, 0, stLimit, baseThreshold);\n\n\t\tret->Param(stratusBaseParam);\n\t\tret->Data().Set(stratusBase);\n\n#ifdef DEBUG\n\t\tutil::DumpVector(stratusBase);\n#endif\n\n\t\tlog.Info(\"Searching for stratus top accurate value\");\n\t\tauto stratusTop = h->VerticalHeight(wantedParamList, stLimit, layer, topThreshold, 0);\n\n\t\tret->Param(stratusTopParam);\n\t\tret->Data().Set(stratusTop);\n\n#ifdef DEBUG\n\t\tutil::DumpVector(stratusTop);\n#endif\n\n\t\ttry\n\t\t{\n\t\t\tlog.Info(\"Searching for cloudiness in layers above stratus top\");\n\n\t\t\tassert(constData1.size() == constData2.size() && constData1.size() == stratusTop.size());\n\n\t\t\tfor (size_t i = 0; i < constData1.size(); i++)\n\t\t\t{\n\t\t\t\tif (stratusTop[i] == MISS)\n\t\t\t\t{\n\t\t\t\t\tconstData1[i] = MISS;\n\t\t\t\t\tconstData2[i] = MISS;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tconstData1[i] = stratusTop[i] + 100;\n\t\t\t\t\tconstData2[i] = stratusTop[i] + drydz;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto upperLayerN = h->VerticalAverage(wantedParamList, constData1, constData2);\n\n\t\t\tret->Param(stratusUpperLayerNParam);\n\t\t\tret->Data().Set(upperLayerN);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(upperLayerN);\n#endif\n\n\t\t\tlog.Info(\"Searching for stratus mean cloudiness\");\n\n\t\t\t// Stratuksen keskimääräinen N\n\t\t\tauto stratusMeanN = h->VerticalAverage(wantedParamList, stratusBase, stratusTop);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(stratusMeanN);\n#endif\n\n\t\t\tret->Param(stratusMeanCloudinessParam);\n\t\t\tret->Data().Set(stratusMeanN);\n\n\t\t\tlog.Info(\"Searching for stratus top temperature\");\n\n\t\t\tparam wantedParam(\"T-K\");\n\n\t\t\t// Stratuksen Topin lämpötila (jäätävä tihku)\n\t\t\tauto stratusTopTemp = h->VerticalValue(wantedParam, stratusTop);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(stratusTopTemp);\n#endif\n\n\t\t\tret->Param(stratusTopTempParam);\n\t\t\tret->Data().Set(stratusTopTemp);\n\n\t\t\tlog.Info(\"Searching for stratus mean temperature\");\n\n\t\t\tfor (size_t i = 0; i < constData1.size(); i++)\n\t\t\t{\n\t\t\t\tdouble lower = stratusBase[i];\n\t\t\t\tdouble upper = stratusTop[i];\n\n\t\t\t\tif (lower == MISS || upper == MISS)\n\t\t\t\t{\n\t\t\t\t\tconstData1[i] = MISS;\n\t\t\t\t\tconstData2[i] = MISS;\n\t\t\t\t}\n\t\t\t\telse if (fabs(lower - upper) < 100)\n\t\t\t\t{\n\t\t\t\t\tconstData1[i] = lower;\n\t\t\t\t\tconstData2[i] = upper;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tconstData1[i] = lower + 50;\n\t\t\t\t\tconstData2[i] = upper - 50;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// St:n keskimääräinen lämpötila (poissulkemaan kylmät <-10C stratukset, joiden toppi >-10C) (jäätävä tihku)\n\t\t\tauto stratusMeanTemp = h->VerticalAverage(wantedParam, constData1, constData2);\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(stratusMeanTemp);\n#endif\n\n\t\t\tret->Param(stratusMeanTempParam);\n\t\t\tret->Data().Set(stratusMeanTemp);\n\n\t\t\tlog.Info(\"Searching for mean vertical velocity in stratus\");\n\n\t\t\twantedParam = param(\"VV-MMS\");\n\n\t\t\tvector<double> stratusVerticalVelocity;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// Keskimääräinen vertikaalinopeus st:ssa [mm/s]\n\t\t\t\tstratusVerticalVelocity = h->VerticalAverage(wantedParam, stratusBase, stratusTop);\n\t\t\t}\n\t\t\tcatch (const HPExceptionType& e)\n\t\t\t{\n\t\t\t\tif (e == kFileDataNotFound)\n\t\t\t\t{\n\t\t\t\t\tlog.Debug(\"Trying for param VV-MS\");\n\t\t\t\t\twantedParam = param(\"VV-MS\");\n\n\t\t\t\t\tstratusVerticalVelocity = h->VerticalAverage(wantedParam, stratusBase, stratusTop);\n\n\t\t\t\t\tfor (double& d : stratusVerticalVelocity)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (d != kFloatMissing) d *= 1000;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n#ifdef DEBUG\n\t\t\tutil::DumpVector(stratusVerticalVelocity, \"stratus vertical velocity\");\n#endif\n\n\t\t\tret->Param(stratusVerticalVelocityParam);\n\t\t\tret->Data().Set(stratusVerticalVelocity);\n\t\t}\n\t\tcatch (const HPExceptionType& e)\n\t\t{\n\t\t\tif (e != kFileDataNotFound)\n\t\t\t{\n\t\t\t\tthrow runtime_error(\"Stratus() caught exception \" + to_string(e));\n\t\t\t}\n\t\t}\n\t}\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"Stratus() caught exception \" + to_string(e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\n\tresult = ret;\n}\n", "meta": {"hexsha": "0a817c98be6f2a0e902dede8fd9c148b4c9d4928", "size": 30072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-plugins/source/preform_hybrid.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/preform_hybrid.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/preform_hybrid.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": 28.6127497621, "max_line_length": 120, "alphanum_fraction": 0.6901104017, "num_tokens": 9896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.018264282192687338, "lm_q1q2_score": 0.008989463002697306}}
{"text": "#include <Python.h>\n#include <windows.h>\n#ifdef min\n#undef min\n#undef max\n#endif\n\n#include <set>\n#include <vector>\n#include <numpy/arrayobject.h>\n#include <maya/MGlobal.h>\n#include <maya/MPoint.h>\n#include <maya/MMatrix.h>\n#include <maya/MQuaternion.h>\n#include <maya/MTransformationMatrix.h>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/Eigen>\n#include <tbb/blocked_range.h>\n#include <tbb/parallel_for.h>\n#include <osqp/osqp.h>\n#include <osqp/auxil.h>\n\n#pragma region Macros\ninline void SET_LONG2(PyArrayObject* m, long i0, long i1, long v)\n{\n    *reinterpret_cast<npy_longlong*>(PyArray_GETPTR2(m, i0, i1)) = static_cast<npy_longlong>(v);\n}\ninline void SET_DOUBLE2(PyArrayObject* m, long i0, long i1, double v)\n{\n    *reinterpret_cast<npy_float64*>(PyArray_GETPTR2(m, i0, i1)) = static_cast<npy_float64>(v);\n}\ninline void SET_DOUBLE4(PyArrayObject* m, long i0, long i1, long i2, long i3, double v)\n{\n    *reinterpret_cast<npy_float64*>(PyArray_GETPTR4(m, i0, i1, i2, i3)) = static_cast<npy_float64>(v);\n}\ninline long GET_LONG2(PyArrayObject* m, long i0, long i1)\n{\n    return static_cast<long>(*reinterpret_cast<npy_longlong*>(PyArray_GETPTR2(m, i0, i1)));\n}\ninline double GET_DOUBLE2(PyArrayObject* m, long i0, long i1)\n{\n    return static_cast<double>(*reinterpret_cast<npy_float64*>(PyArray_GETPTR2(m, i0, i1)));\n}\ninline double GET_DOUBLE3(PyArrayObject* m, long i0, long i1, long i2)\n{\n    return static_cast<double>(*reinterpret_cast<npy_float64*>(PyArray_GETPTR3(m, i0, i1, i2)));\n}\ninline double GET_DOUBLE4(PyArrayObject* m, long i0, long i1, long i2, long i3)\n{\n    return static_cast<double>(*reinterpret_cast<npy_float64*>(PyArray_GETPTR4(m, i0, i1, i2, i3)));\n}\n#pragma endregion\n\nstruct Input\n{\n    //! number of model vertices\n    long numVertices;\n    //! number of sample frames\n    long numSamples;\n    //! desirable number of joints\n    long numJoints;\n    //! local neighbors (0 / 1 / 2)\n    long numRings;\n    //! rest/bind shape (numVertices)\n    std::vector<MPoint> restShape;\n    //! samples (numSamples x numVertices)\n    std::vector<MPoint> sample;\n    //! neighbor information\n    std::vector<std::vector<std::pair<int, double>>> neighbor;\n    //! model normalization matrix\n    MMatrix normalizer;\n\n    Input() :\n        numVertices(0), numSamples(0), numJoints(0), normalizer(MMatrix::identity)\n\t{\n\t}\n\t~Input()\n\t{\n\t\trestShape.clear();\n\t\tsample.clear();\n        neighbor.clear();\n\t}\n};\n\nstruct Output\n{\n    //! number of inserted joints\n    long numJoints;\n    //! number of skinning joint index (max influence)\n    long numIndices;\n    //! skinning weight (numVertices x numIndices)\n    std::vector<double> skinWeight;\n    //! skinning joint index (numVertices x numIndices)\n    std::vector<long> skinIndex;\n    //! skinning matrix (numJoints x numSamples)\n    std::vector<MTransformationMatrix> skinMatrix;\n    //! rest joint position (numJoints)\n    std::vector<MPoint> restJointPos;\n    //! clusters each vertex belongs\n    std::vector<std::vector<int>> vertCluster;\n\t\n\tOutput() :\n        numJoints(0), numIndices(0)\n\t{\n\t}\n\t~Output()\n\t{\n\t\tskinWeight.clear();\n\t\tskinIndex.clear();\n\t\tskinMatrix.clear();\n        restJointPos.clear();\n\t}\n};\n\n#pragma region Subroutines for joint transformation\nMTransformationMatrix calcRegistrationT(long numPoints, std::vector<MPoint>::const_iterator ps, std::vector<MPoint>::const_iterator pd)\n{\n    MTransformationMatrix transform;\n    MPoint cs = MVector::zero, cd = MVector::zero;\n    std::vector<MPoint>::const_iterator sit = ps;\n    std::vector<MPoint>::const_iterator dit = pd;\n    for (long i = 0; i < numPoints; ++i, ++sit, ++dit)\n    {\n        cs += *sit;\n        cd += *dit;\n    }\n    transform.setTranslation((cd - cs) / static_cast<double>(numPoints), MSpace::kTransform);\n    return transform;\n}\n\nMTransformationMatrix calcRegistrationRT(long numPoints, std::vector<MPoint>::const_iterator ps, std::vector<MPoint>::const_iterator pd)\n{\n    MTransformationMatrix transform;\n    MPoint cs = MVector::zero, cd = MVector::zero;\n    std::vector<MPoint>::const_iterator sit = ps;\n    std::vector<MPoint>::const_iterator dit = pd;\n    for (long i = 0; i < numPoints; ++i, ++sit, ++dit)\n    {\n        cs += *sit;\n        cd += *dit;\n    }\n    cs = cs / static_cast<double>(numPoints);\n    cd = cd / static_cast<double>(numPoints);\n    if (numPoints < 3)\n    {\n        transform.setTranslation(cd - cs, MSpace::kTransform);\n        return transform;\n    }\n\n    Eigen::Matrix<double, 4, 4> moment;\n    double sxx = 0, sxy = 0, sxz = 0, syx = 0, syy = 0, syz = 0, szx = 0, szy = 0, szz = 0;\n    sit = ps;\n    dit = pd;\n    for (long i = 0; i < numPoints; ++i, ++sit, ++dit)\n    {\n        sxx += (sit->x - cs.x) * (dit->x - cd.x);\n        sxy += (sit->x - cs.x) * (dit->y - cd.y);\n        sxz += (sit->x - cs.x) * (dit->z - cd.z);\n        syx += (sit->y - cs.y) * (dit->x - cd.x);\n        syy += (sit->y - cs.y) * (dit->y - cd.y);\n        syz += (sit->y - cs.y) * (dit->z - cd.z);\n        szx += (sit->z - cs.z) * (dit->x - cd.x);\n        szy += (sit->z - cs.z) * (dit->y - cd.y);\n        szz += (sit->z - cs.z) * (dit->z - cd.z);\n    }\n    moment(0, 0) = sxx + syy + szz;\n    moment(0, 1) = syz - szy;        moment(1, 0) = moment(0, 1);\n    moment(0, 2) = szx - sxz;        moment(2, 0) = moment(0, 2);\n    moment(0, 3) = sxy - syx;        moment(3, 0) = moment(0, 3);\n    moment(1, 1) = sxx - syy - szz;\n    moment(1, 2) = sxy + syx;        moment(2, 1) = moment(1, 2);\n    moment(1, 3) = szx + sxz;        moment(3, 1) = moment(1, 3);\n    moment(2, 2) = -sxx + syy - szz;\n    moment(2, 3) = syz + szy;        moment(3, 2) = moment(2, 3);\n    moment(3, 3) = -sxx - syy + szz;\n\n    if (moment.norm() > 0)\n    {\n        Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>> es(moment);\n        long maxi = 0;\n        for (long i = 1; i < 4; ++i)\n        {\n            if (es.eigenvalues()(maxi).real() < es.eigenvalues()(i).real())\n            {\n                maxi = i;\n            }\n        }\n        transform.setRotationQuaternion(\n            es.eigenvectors()(1, maxi).real(),\n            es.eigenvectors()(2, maxi).real(),\n            es.eigenvectors()(3, maxi).real(),\n            es.eigenvectors()(0, maxi).real());\n    }\n    MPoint cs0 = cs * transform.asMatrix();\n    transform.setTranslation(cd - cs0, MSpace::kTransform);\n    return transform;\n}\n\nMTransformationMatrix calcRegistrationSRT(long numPoints, std::vector<MPoint>::const_iterator ps, std::vector<MPoint>::const_iterator pd)\n{\n    const long numIterations = 50;\n    const double threshold = 1.0e-8;\n    const double scaleLowerBound = 1.0e-3;\n    MTransformationMatrix transform = calcRegistrationRT(numPoints, ps, pd);\n\n    MVector scale(1.0, 1.0, 1.0);\n    MVector denom(0.0, 0.0, 0.0);\n    std::vector<MPoint>::const_iterator sit = ps;\n    for (long i = 0; i < numPoints; ++i, ++sit)\n    {\n        denom[0] += (*sit)[0] * (*sit)[0];\n        denom[1] += (*sit)[1] * (*sit)[1];\n        denom[2] += (*sit)[2] * (*sit)[2];\n    }\n    std::vector<MPoint> sstm(numPoints);\n    sit = ps;\n    for (long i = 0; i < numPoints; ++i, ++sit)\n    {\n        sstm[i][0] = (*sit)[0];\n        sstm[i][1] = (*sit)[1];\n        sstm[i][2] = (*sit)[2];\n    }\n    std::vector<MPoint> dstm(numPoints);\n    for (long l = 0; l < numIterations; ++l)\n    {\n        MMatrix im = transform.asMatrix().inverse();\n        std::vector<MPoint>::const_iterator dit = pd;\n        for (long i = 0; i < numPoints; ++i, ++dit)\n        {\n            dstm[i] = *dit * im;\n        }\n        for (long d = 0; d < 3; ++d)\n        {\n            double ds = 0.0;\n            sit = ps;\n            for (long i = 0; i < numPoints; ++i, ++sit)\n            {\n                ds += (*sit)[d] * dstm[i][d];\n            }\n            scale[d] = denom[d] < threshold ? 1.0 : ds / denom[d];\n            sit = ps;\n            for (long i = 0; i < numPoints; ++i, ++sit)\n            {\n                sstm[i][d] = scale[d] * (*sit)[d];\n            }\n        }\n        transform = calcRegistrationRT(numPoints, sstm.begin(), pd);\n    }\n    double sv[3] = { scale[0], scale[1], scale[2] };\n    transform.setScale(sv, MSpace::kTransform);\n    return transform;\n}\n\ntypedef MTransformationMatrix(*RegistrationFunc)(long numPoints, std::vector<MPoint>::const_iterator ps, std::vector<MPoint>::const_iterator pd);\n\nRegistrationFunc registrationFuncs[3] = {\n    calcRegistrationT,\n    calcRegistrationRT,\n    calcRegistrationSRT };\n\nvoid computeSamplePoints(std::vector<MPoint>& sample, long sid, long joint, const Output& output, const Input& input)\n{\n    const long numVertices = input.numVertices;\n    const long& numIndices = output.numIndices;\n\n    for (long v = 0; v < numVertices; ++v)\n    {\n        sample[v] = input.sample[sid * numVertices + v];\n        const MPoint& s = input.restShape[v];\n        for (long i = 0; i < numIndices; ++i)\n        {\n            const long jnt = output.skinIndex[v * numIndices + i];\n            if (jnt >= 0 && jnt != joint)\n            {\n                const double w = output.skinWeight[v * numIndices + i];\n                const MTransformationMatrix& at = output.skinMatrix[sid * input.numJoints + jnt];\n                sample[v] -= w * (s * at.asMatrix());\n            }\n        }\n    }\n}\n\nvoid subtractCentroid(std::vector<MPoint>& model, std::vector<MPoint>& sample, MPoint& corModel, MPoint& corSample, const Eigen::VectorXd& weight, const Output& output, const Input& input)\n{\n    const long numVertices = input.numVertices;\n\n    double wsqsum = 0;\n    corModel = MVector::zero;\n    corSample = MVector::zero;\n    for (long v = 0; v < numVertices; ++v)\n    {\n        const double w = weight[v];\n        corModel += w * w * input.restShape[v];\n        corSample += w * sample[v];\n        wsqsum += w * w;\n    }\n    corModel = corModel / wsqsum;\n    corSample = corSample / wsqsum;\n    for (long v = 0; v < numVertices; ++v)\n    {\n        model[v] = weight[v] * (input.restShape[v] - corModel);\n        sample[v] -= weight[v] * corSample;\n    }\n}\n#pragma endregion\n\n#pragma region Bone transformation\nclass JointTransformUpdator\n{\nprivate:\n    Output* output;\n    const Input* input;\n    const Eigen::VectorXd* weight;\n    int transformType;\n    long joint;\n\npublic:\n    JointTransformUpdator(Output* output_, const Input* input_,\n        const Eigen::VectorXd* weight_, int joint_, int transformType_)\n        : output(output_), input(input_),\n        weight(weight_), joint(joint_), transformType(transformType_)\n    {\n    }\n    void operator ()(const tbb::blocked_range<int>& range) const\n    {\n        std::vector<MPoint> model(input->numVertices);\n        std::vector<MPoint> sample(input->numVertices);\n        for (long s = range.begin(); s != range.end(); ++s)\n        {\n            if (s == 0)\n            {\n                output->skinMatrix[joint] = MTransformationMatrix::identity;\n                continue;\n            }\n            computeSamplePoints(sample, s, joint, *output, *input);\n            MPoint corModel(0, 0, 0), corSample(0, 0, 0);\n            subtractCentroid(model, sample, corModel, corSample, *weight, *output, *input);\n            MTransformationMatrix transform = registrationFuncs[transformType](model.size(), model.begin(), sample.begin());\n            MVector d = corSample - corModel * transform.asMatrix();\n            transform.setTranslation(d + transform.getTranslation(MSpace::kTransform), MSpace::kTransform);\n            output->skinMatrix[s * input->numJoints + joint] = transform;\n        }\n    }\n};\n\nvoid updateJointTransformProc(Output& output, int transformType, const Input& input, long selection = -1)\n{\n    const long numVertices = input.numVertices;\n    const long numSamples  = input.numSamples;\n    const long numJoints    = output.numJoints;\n    const long numIndices  = output.numIndices;\n\n    Eigen::VectorXd weight = Eigen::VectorXd::Zero(numVertices);\n    long begin = selection < 0 ? 0 : selection;\n    long end = selection < 0 ? numJoints : selection + 1;\n    for (long joint = begin; joint < end; ++joint)\n    {\n        for (long v = 0; v < numVertices; ++v)\n        {\n            weight[v] = 0.0;\n            for (long i = 0; i < numIndices; ++i)\n            {\n                long jnt = output.skinIndex[v * numIndices + i];\n                if (jnt == joint)\n                {\n                    weight[v] = output.skinWeight[v * numIndices + i];\n                    break;\n                }\n            }\n        }\n        double wsqsum = weight.dot(weight);\n        if (wsqsum > 1.0e-8)\n        {\n            tbb::blocked_range<int> blockedRange(0, numSamples);\n            JointTransformUpdator transformUpdator(&output, &input, &weight, joint, transformType);\n            tbb::parallel_for(blockedRange, transformUpdator);\n        }\n        else\n        {\n            for (int s = 0; s < numSamples; ++s)\n            {\n                output.skinMatrix[s * input.numJoints + joint] = MTransformationMatrix::identity;\n            }\n            char buf[256];\n            sprintf(buf, \"Fixed joint #%d\", joint);\n            MGlobal::displayInfo(buf);\n        }\n    }\n}\n\nstatic PyObject* updateJointTransform(PyObject *self, PyObject *args)\n{\n    PyObject* pin            = PyTuple_GET_ITEM(args, 0);\n    PyObject* pout           = PyTuple_GET_ITEM(args, 1);\n    const long transformType = PyInt_AsLong(PyTuple_GET_ITEM(args, 2));\n    Input* const input   = reinterpret_cast<Input*>(PyCapsule_GetPointer(pin, \"SSDSInput\"));\n    Output* const output = reinterpret_cast<Output*>(PyCapsule_GetPointer(pout, \"SSDSOutput\"));\n    updateJointTransformProc(*output, transformType, *input);\n    return Py_None;\n}\n#pragma endregion \n\n#pragma region Skinning weight\nEigen::VectorXd solveWeightQP(Eigen::SparseMatrix<c_float, 0, c_int>& pm, Eigen::VectorXd& qv)\n{\n    const int n = static_cast<int>(pm.rows());\n    Eigen::SparseMatrix<c_float, 0, c_int> a(n + 1, n);\n    std::vector<c_float> q(n), l(n + 1, 0.0), u(n + 1, 1.0);\n    for (int i = 0; i < n; ++i)\n    {\n        a.coeffRef(0, i) = 1.0;\n        a.coeffRef(i + 1, i) = 1.0;\n        q[i] = qv[i];\n    }\n    l[0] = u[0] = 1.0;\n    a.makeCompressed();\n    pm.makeCompressed();\n\n    // Problem settings\n    OSQPSettings settings;\n    osqp_set_default_settings(&settings);\n    settings.polish = 0;\n    settings.adaptive_rho = 0;\n    settings.warm_start = 0;\n    settings.eps_abs = 1.0e-12; // experimentally set\n    settings.eps_rel = 1.0e-12; // experimentally set\n\n    OSQPData osqpData;\n    osqpData.n = n;\n    osqpData.m = n + 1;\n    osqpData.P = csc_matrix(n, n, pm.nonZeros(), pm.valuePtr(), pm.innerIndexPtr(), pm.outerIndexPtr());\n    osqpData.q = q.data();\n    osqpData.A = csc_matrix(n + 1, n, a.nonZeros(), a.valuePtr(), a.innerIndexPtr(), a.outerIndexPtr());\n    osqpData.l = l.data();\n    osqpData.u = u.data();\n\n    OSQPWorkspace* osqpWork = osqp_setup(&osqpData, &settings);\n    c_int retval = osqp_solve(osqpWork);\n    settings.rho = compute_rho_estimate(osqpWork);\n    Eigen::VectorXd weight(n);\n    for (int i = 0; i < n; ++i)\n    {\n        weight[i] = osqpWork->solution->x[i];\n    }\n    osqp_cleanup(osqpWork);\n\n    settings.warm_start = 1;\n    osqpWork = osqp_setup(&osqpData, &settings);\n    osqp_warm_start_x(osqpWork, weight.data());\n    retval = osqp_solve(osqpWork);\n    for (int i = 0; i < n; ++i)\n    {\n        weight[i] = osqpWork->solution->x[i];\n    }\n    osqp_cleanup(osqpWork);\n    c_free(osqpData.A);\n    c_free(osqpData.P);\n    return weight;\n}\n\nclass SkinWeightUpdator\n{\nprivate:\n    Output* output;\n    const Input* input;\n    const int numIndices;\n    const double smoothness;\n    std::vector<double> prevWeight;\n    std::vector<long> prevIndex;\npublic:\n    SkinWeightUpdator(Output* output_, const Input* input_,\n        int numMaxInfluences_, double smoothness_)\n        : output(output_), input(input_),\n        numIndices(numMaxInfluences_), smoothness(smoothness_ == 0 ? 0 : std::pow(10.0, smoothness_ - 8))\n    {\n        prevWeight = output->skinWeight;\n        prevIndex = output->skinIndex;\n    }\n    void operator ()(const tbb::blocked_range<int>& range) const\n    {\n        const int numVertices = input->numVertices;\n        const int numSamples  = input->numSamples;\n        const int numJoints   = output->numJoints;\n        const double epsilon  = 1.0e-3;\n\n        Eigen::MatrixXd sbasis   = Eigen::MatrixXd::Zero(numIndices, numSamples * 3);\n        Eigen::VectorXd sample   = Eigen::VectorXd::Zero(numSamples * 3);\n        Eigen::VectorXd slaplacm = Eigen::VectorXd::Zero(numIndices);\n        Eigen::VectorXd slaplacv = Eigen::VectorXd::Zero(numIndices);\n        for (int v = range.begin(); v != range.end(); ++v)\n        {\n            const std::vector<int>& vertCluster = output->vertCluster[v];\n            const int numActJoints = vertCluster.size();\n            Eigen::MatrixXd basis   = Eigen::MatrixXd::Zero(numActJoints, numSamples * 3);\n            Eigen::VectorXd laplacm = Eigen::VectorXd::Zero(numActJoints);\n            Eigen::VectorXd laplacv = Eigen::VectorXd::Zero(numActJoints);\n\n            for (int i = 0; i < numIndices; ++i)\n            {\n                output->skinIndex[v * numIndices + i] = -1;\n                output->skinWeight[v * numIndices + i] = 0;\n            }\n            // Laplacian term\n            double lsum = 0.0;\n            laplacv.setZero();\n\n            for (auto it = input->neighbor[v].begin(); it != input->neighbor[v].end(); ++it)\n            {\n                const int nvid = it->first;\n                lsum -= it->second;\n                for (int i = 0; i < numIndices; ++i)\n                {\n                    const int nbid = prevIndex[nvid * numIndices + i];\n                    auto nbit = std::find(output->vertCluster[v].begin(), output->vertCluster[v].end(), nbid);\n                    if (nbid >= 0 && nbit != output->vertCluster[v].end())\n                    {\n                        laplacv[nbit - output->vertCluster[v].begin()] -= it->second * prevWeight[nvid * numIndices + i];\n                    }\n                }\n            }\n            laplacm.setConstant(smoothness * lsum);\n            laplacv *= -smoothness;\n            \n\n            // variables\n            const MPoint& restVertex = input->restShape[v];\n            for (int s = 0; s < numSamples; ++s)\n            {\n                for (int j = 0; j < numActJoints; ++j)\n                {\n                    const int jid = vertCluster[j];\n                    const MTransformationMatrix& rt = output->skinMatrix[s * numJoints + jid];\n                    MPoint tv = restVertex * rt.asMatrix();\n                    basis(j, s * 3 + 0) = tv.x;\n                    basis(j, s * 3 + 1) = tv.y;\n                    basis(j, s * 3 + 2) = tv.z;\n                }\n                sample[s * 3 + 0] = input->sample[s * numVertices + v].x;\n                sample[s * 3 + 1] = input->sample[s * numVertices + v].y;\n                sample[s * 3 + 2] = input->sample[s * numVertices + v].z;\n            }\n            // optimization\n            Eigen::SparseMatrix<c_float, 0, c_int> gm =\n                (basis * basis.transpose()\n                    + laplacm.asDiagonal().toDenseMatrix()\n                    ).sparseView();\n            gm.makeCompressed();\n            Eigen::VectorXd gv = -basis * sample + laplacv;\n            double scale = std::max(std::abs(gv.minCoeff()), std::abs(gv.maxCoeff()));\n\n            Eigen::VectorXd weight = solveWeightQP(gm, gv);\n            double weightSum = 0;\n            for (int i = 0; i < numIndices; ++i)\n            {\n                double maxw = epsilon;\n                int bestjoint = -1;\n                for (int j = 0; j < numActJoints; ++j)\n                {\n                    if (weight[j] > maxw)\n                    {\n                        maxw = weight[j];\n                        bestjoint = j;\n                    }\n                }\n                if (bestjoint < 0)\n                {\n                    break;\n                }\n                output->skinIndex[v * numIndices + i] = bestjoint;\n                output->skinWeight[v * numIndices + i] = maxw;\n                weightSum += maxw;\n                weight[bestjoint] = -1.0;\n            }\n            // subproblem\n            if (weightSum < 1.0)\n            {\n                sbasis.setZero();\n                slaplacm.setZero();\n                slaplacv.setZero();\n                for (int i = 0; i < numIndices; ++i)\n                {\n                    int j = output->skinIndex[v * numIndices + i];\n                    if (j >= 0)\n                    {\n                        for (int s = 0; s < numSamples * 3; ++s)\n                        {\n                            sbasis(i, s) = basis(j, s);\n                        }\n                        slaplacm[i] = laplacm[j];\n                        slaplacv[i] = laplacv[j];\n                    }\n                }\n                Eigen::SparseMatrix<c_float, 0, c_int> sgm =\n                    (sbasis * sbasis.transpose()\n                        + slaplacm.asDiagonal().toDenseMatrix()\n                        ).sparseView();\n                Eigen::VectorXd sgv = -sbasis * sample + slaplacv;\n                sgm.makeCompressed();\n                weight = solveWeightQP(sgm, sgv);\n                weightSum = 0;\n                for (int i = 0; i < numIndices; ++i)\n                {\n                    if (weight[i] < epsilon)\n                    {\n                        output->skinWeight[v * numIndices + i] = 0;\n                        output->skinIndex[v * numIndices + i] = -1;\n                    }\n                    else\n                    {\n                        output->skinWeight[v * numIndices + i] = weight[i];\n                        weightSum += weight[i];\n                    }\n                }\n            }\n            for (int i = 0; i < numIndices; ++i)\n            {\n                output->skinIndex[v * numIndices + i] = output->skinIndex[v * numIndices + i] < 0\n                    ? -1 : vertCluster[output->skinIndex[v * numIndices + i]];\n                output->skinWeight[v * numIndices + i] /= weightSum;\n            }\n        }\n    }\n};\n\nstatic PyObject* updateSkinWeight(PyObject *self, PyObject *args)\n{\n    PyObject* pin        = PyTuple_GET_ITEM(args, 0);\n    PyObject* pout       = PyTuple_GET_ITEM(args, 1);\n    double smoothness   = PyFloat_AsDouble(PyTuple_GET_ITEM(args, 2));\n    Input* const input   = reinterpret_cast<Input*>(PyCapsule_GetPointer(pin, \"SSDSInput\"));\n\tOutput* const output = reinterpret_cast<Output*>(PyCapsule_GetPointer(pout, \"SSDSOutput\"));\n    SkinWeightUpdator weightUpdater(output, input, output->numIndices, smoothness);\n    tbb::blocked_range<int> blockedRange(0, input->numVertices);\n\ttbb::parallel_for(blockedRange, weightUpdater);\n    return Py_None;\n}\n#pragma endregion \n\n#pragma region Clustering\n// see https://sites.google.com/view/fumiyanarita/project/la_ssdr_mdmc\nstatic void detectNeighborClusters(const Input& input, Output& output)\n{\n    MGlobal::displayInfo(\"Detecting neighbor clusters\");\n    const long& numIndices = output.numIndices;\n\n    std::vector<std::set<int>> clusters(output.numJoints);\n    for (int v = 0; v < input.numVertices; ++v)\n    {\n        const int primjid = output.skinIndex[v * numIndices];\n        if (input.numRings == 0)\n        {\n            for (int j = 0; j < output.numJoints; ++j)\n            {\n                for (int v = 0; v < output.numJoints; ++v)\n                {\n                    clusters[j].insert(v);\n                }\n            }\n        }\n        else\n        {\n            clusters[primjid].insert(0);\n            clusters[primjid].insert(primjid);\n            // one-ring neighbors\n            for (auto nvit = input.neighbor[v].begin(); nvit != input.neighbor[v].end(); ++nvit)\n            {\n                const int nvid = nvit->first;\n                clusters[primjid].insert(output.skinIndex[nvid * numIndices]);\n                if (input.numRings == 1)\n                {\n                    continue;\n                }\n                // two-ring neighbors\n                for (auto nnvit = input.neighbor[nvid].begin(); nnvit != input.neighbor[nvid].end(); ++nnvit)\n                {\n                    const int nnvid = nnvit->first;\n                    clusters[primjid].insert(output.skinIndex[nnvid * numIndices]);\n                }\n            }\n        }\n    }\n    for (int v = 0; v < input.numVertices; ++v)\n    {\n        const int primjid = output.skinIndex[v * numIndices];\n        output.vertCluster[v] = std::vector<int>(clusters[primjid].begin(), clusters[primjid].end());\n    }\n}\n\nlong bindVertexToJoint(Output& output, const Input& input)\n{\n    const long numVertices = input.numVertices;\n    const long numSamples  = input.numSamples;\n    const long numIndices  = output.numIndices;\n\n    std::vector<int> numJointVertices(output.numJoints, 0);\n    for (long v = 0; v < numVertices; ++v)\n    {\n        long bestJoint = 0;\n        double minErr = std::numeric_limits<double>::max();\n        const MPoint& restShapePos = input.restShape[v];\n        for (long j = 0; j < output.numJoints; ++j)\n        {\n            double errsq = 0;\n            for (long s = 0; s < numSamples; ++s)\n            {\n                MMatrix am = output.skinMatrix[s * input.numJoints + j].asMatrix();\n                MVector diff = input.sample[s * numVertices + v] - restShapePos * am;\n                errsq += diff * diff;\n            }\n            errsq *= (input.restShape[v] - output.restJointPos[j]).length();\n            if (errsq < minErr)\n            {\n                bestJoint = j;\n                minErr = errsq;\n            }\n        }\n        ++numJointVertices[bestJoint];\n        output.skinIndex[v * numIndices + 0] = bestJoint;\n    }\n\n    std::vector<int>::iterator smallestBoneSize = std::min_element(numJointVertices.begin(), numJointVertices.end());\n    while (*smallestBoneSize <= 0)\n    {\n        const long smallestBone = static_cast<int>(smallestBoneSize - numJointVertices.begin());\n        numJointVertices.erase(numJointVertices.begin() + smallestBone);\n        output.restJointPos.erase(output.restJointPos.begin() + smallestBone);\n        for (long s = 0; s < input.numSamples; ++s)\n        {\n            for (int j = output.numJoints - 2; j >= smallestBone; --j)\n            {\n                output.skinMatrix[s * input.numJoints + j] = output.skinMatrix[s * input.numJoints + j + 1];\n            }\n        }\n        for (long v = 0; v < numVertices; ++v)\n        {\n            if (output.skinIndex[v * numIndices + 0] >= smallestBone)\n            {\n                --output.skinIndex[v * numIndices + 0];\n            }\n        }\n        --output.numJoints;\n        smallestBoneSize = std::min_element(numJointVertices.begin(), numJointVertices.end());\n    }\n    return static_cast<int>(numJointVertices.size());\n}\n\nlong findMostStableVertex(const Input& input)\n{\n    const long numVertices = input.numVertices;\n    const long numSamples = input.numSamples;\n    double minErrorSq = std::numeric_limits<double>::max();\n    long mostStableVertex = -1;\n    for (int v = 0; v < numVertices; ++v)\n    {\n        double errSq = 0;\n        for (int s = 0; s < numSamples; ++s)\n        {\n            MVector diff = input.sample[s * numVertices + v] - input.restShape[v];\n            errSq += diff * diff;\n        }\n        if (errSq < minErrorSq)\n        {\n            minErrorSq = errSq;\n            mostStableVertex = v;\n        }\n    }\n    return mostStableVertex;\n}\n\nlong findDistantVertex(const Input& input, const Output& output, const std::set<long>& covered)\n{\n    const long numVertices = input.numVertices;\n    const long numSamples  = input.numSamples;\n    const long numIndices  = output.numIndices;\n    double maxErrorSq      = -std::numeric_limits<double>::max();\n    long mostDistantVertex = -1;\n    for (int v = 0; v < numVertices; ++v)\n    {\n        if (covered.find(v) != covered.end())\n        {\n            continue;\n        }\n        long index = output.skinIndex[v * numIndices + 0];\n        double errSq = 0;\n        for (int s = 0; s < numSamples; ++s)\n        {\n            MMatrix bm = output.skinMatrix[s * input.numJoints + index].asMatrix();\n            MVector diff = input.sample[s * numVertices + v] - input.restShape[v] * bm;\n            errSq += diff * diff;\n        }\n        if (errSq > maxErrorSq)\n        {\n            maxErrorSq = errSq;\n            mostDistantVertex = v;\n        }\n    }\n    return mostDistantVertex;\n}\n\n// solving p-center problem\nstatic PyObject* clusterVerticesPcenter(PyObject* self, PyObject* args)\n{\n    PyObject* pin = PyTuple_GET_ITEM(args, 0);\n    PyObject* pout = PyTuple_GET_ITEM(args, 1);\n    const long transformType = PyInt_AsLong(PyTuple_GET_ITEM(args, 2));\n    const Input& input = *reinterpret_cast<Input*>(PyCapsule_GetPointer(pin, \"SSDSInput\"));\n    Output& output = *reinterpret_cast<Output*>(PyCapsule_GetPointer(pout, \"SSDSOutput\"));\n    const long& numIndices = output.numIndices;\n\n    output.numJoints = input.numJoints;\n    std::fill(output.skinIndex.begin(), output.skinIndex.end(), -1);\n    std::fill(output.skinWeight.begin(), output.skinWeight.end(), 0.0);\n    std::fill(output.skinMatrix.begin(), output.skinMatrix.end(), MTransformationMatrix::identity);\n    std::fill(output.restJointPos.begin(), output.restJointPos.end(), MPoint::origin);\n\n    char buf[512];\n    long stableVertex = findMostStableVertex(input);\n    output.skinIndex[stableVertex * numIndices] = 0;\n    output.skinWeight[stableVertex * numIndices] = 1.0;\n    output.restJointPos[0] = input.restShape[stableVertex];\n    std::vector<long> jointVertices(output.numJoints);\n    jointVertices[0] = stableVertex;\n    sprintf(buf, \"Added to Vertex %d (stable)\", stableVertex);\n    MGlobal::displayInfo(buf);\n\n    for (int jid = 1; jid < input.numJoints; ++jid)\n    {\n        double maxDist = -1.0;\n        int distantVertex = -1;\n        for (int i = 0; i < input.numVertices; ++i)\n        {\n            if (std::find(jointVertices.begin(), jointVertices.end(), i) != jointVertices.end())\n            {\n                continue;\n            }\n            double mindist = std::numeric_limits<double>::max();\n            for (int j = 0; j < jid; ++j)\n            {\n                const int joint = jointVertices[j];\n                MVector v = input.restShape[i] - input.restShape[joint];\n                if (mindist > v.length())\n                {\n                    mindist = v.length();\n                }\n            }\n            if (mindist > maxDist)\n            {\n                maxDist = mindist;\n                distantVertex = i;\n            }\n        }\n        output.restJointPos[jid] = input.restShape[distantVertex];\n        jointVertices[jid] = distantVertex;\n        sprintf(buf, \"Added to Vertex %d, %f\", distantVertex, maxDist);\n        MGlobal::displayInfo(buf);\n    }\n\n    for (int i = 0; i < input.numVertices; ++i)\n    {\n        double minDist = std::numeric_limits<double>::max();\n        int nearestJoint = -1;\n        for (int j = 0; j < output.numJoints; ++j)\n        {\n            const int joint = jointVertices[j];\n            MVector v = input.restShape[i] - input.restShape[joint];\n            if (v.length() < minDist)\n            {\n                minDist = v.length();\n                nearestJoint = j;\n            }\n        }\n        output.skinIndex[i * numIndices] = nearestJoint;\n        output.skinWeight[i * numIndices] = 1.0;\n    }\n    detectNeighborClusters(input, output);\n    updateJointTransformProc(output, transformType, input);\n    return PyInt_FromLong(output.numJoints);\n}\n\nstatic PyObject* clusterVerticesAdaptive(PyObject *self, PyObject *args)\n{\n    PyObject* pin            = PyTuple_GET_ITEM(args, 0);\n    PyObject* pout           = PyTuple_GET_ITEM(args, 1);\n    const long transformType = PyInt_AsLong(PyTuple_GET_ITEM(args, 2));\n    const Input& input = *reinterpret_cast<Input*>(PyCapsule_GetPointer(pin, \"SSDSInput\"));\n    Output& output     = *reinterpret_cast<Output*>(PyCapsule_GetPointer(pout, \"SSDSOutput\"));\n    const long& numIndices = output.numIndices;\n\n    output.numJoints   = 0;\n    std::fill(output.skinIndex.begin(), output.skinIndex.end(), -1);\n    std::fill(output.skinWeight.begin(), output.skinWeight.end(), 0.0);\n    std::fill(output.skinMatrix.begin(), output.skinMatrix.end(), MTransformationMatrix::identity);\n    output.restJointPos.clear();\n\n    std::set<long> covered;\n    char buf[512];\n\n    long stableVertex = findMostStableVertex(input);\n    output.skinIndex[stableVertex * numIndices] = 0;\n    output.skinWeight[stableVertex * numIndices] = 1.0;\n    output.restJointPos.push_back(input.restShape[stableVertex]);\n    covered.insert(stableVertex);\n    sprintf(buf, \"Added to Vertex %d (stable)\", stableVertex);\n    MGlobal::displayInfo(buf);\n\n    for (int i = 0; i < input.neighbor[stableVertex].size(); ++i)\n    {\n        long neighbor = input.neighbor[stableVertex][i].first;\n        if (neighbor < 0)\n        {\n            continue;\n        }\n        output.skinIndex[neighbor * numIndices] = 0;\n        output.skinWeight[neighbor * numIndices] = 1.0;\n        covered.insert(neighbor);\n    }\n    updateJointTransformProc(output, transformType, input, 0);\n    for (int v = 0; v < input.numVertices; ++v)\n    {\n        output.skinIndex[v * numIndices] = 0;\n        output.skinWeight[v * numIndices] = 1.0;\n    }\n    output.numJoints = 1;\n\n    for (int iteration = 0; iteration < input.numJoints + 10; ++iteration)\n    {\n        if (output.numJoints >= input.numJoints || covered.size() >= input.numVertices)\n        {\n            break;\n        }\n        long distantVertex = findDistantVertex(input, output, covered);\n        output.skinIndex[distantVertex * numIndices] = output.numJoints;\n        output.restJointPos.push_back(input.restShape[distantVertex]);\n        covered.insert(distantVertex);\n        for (int i = 0; i < input.neighbor[distantVertex].size(); ++i)\n        {\n            long neighbor = input.neighbor[distantVertex][i].first;\n            if (neighbor < 0)\n            {\n                continue;\n            }\n            output.skinIndex[neighbor * numIndices] = output.numJoints;\n            covered.insert(neighbor);\n        }\n        updateJointTransformProc(output, transformType, input, output.numJoints);\n        ++output.numJoints;\n        output.numJoints = bindVertexToJoint(output, input);\n\n        sprintf(buf, \"Added to Vertex %d\", distantVertex);\n        MGlobal::displayInfo(buf);\n    }\n    detectNeighborClusters(input, output);\n    return PyInt_FromLong(output.numJoints);\n}\n#pragma endregion\n\n#pragma region Initialization\nstatic PyObject* initialize(PyObject *self, PyObject *args)\n{\n    PyArrayObject* initPos          = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 0));\n    PyArrayObject* shapeSample      = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 1));\n    PyArrayObject* neighborVertices = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 2));\n    const long numJoints            = PyInt_AsLong(PyTuple_GET_ITEM(args, 3));\n    const long numIndices           = PyInt_AsLong(PyTuple_GET_ITEM(args, 4));\n    const long numRings             = PyInt_AsLong(PyTuple_GET_ITEM(args, 5));\n    const long numVertices = static_cast<long>(initPos->dimensions[0]);\n    const long numSamples  = static_cast<long>(shapeSample->dimensions[0]);\n    // allocation\n    Input* input       = new Input();\n    input->numVertices = numVertices;\n    input->numSamples  = numSamples;\n    input->numJoints   = numJoints;\n    input->numRings    = numRings;\n    input->restShape   = std::vector<MPoint>(numVertices);\n    input->sample      = std::vector<MPoint>(numSamples * numVertices);\n    input->neighbor    = std::vector<std::vector<std::pair<int, double>>>(numVertices);\n    Output* output       = new Output();\n    output->numJoints    = 0;\n    output->numIndices   = numIndices;\n    output->skinIndex    = std::vector<long>(numVertices * numIndices, -1);\n    output->skinWeight   = std::vector<double>(numVertices * numIndices, 0.0);\n    output->skinMatrix   = std::vector<MTransformationMatrix>(numSamples * numJoints, MTransformationMatrix::identity);\n    output->restJointPos = std::vector<MPoint>(numJoints);\n    output->vertCluster  = std::vector<std::vector<int>>(numVertices);\n    // size normalization\n    MVector centroid(0, 0, 0);\n    MVector minPos(1.0e10, 1.0e10, 1.0e10), maxPos(-1.0e10, -1.0e10, -1.0e10);\n    for (int v = 0; v < numVertices; ++v)\n    {\n        MVector p(GET_DOUBLE2(initPos, v, 0),\n                  GET_DOUBLE2(initPos, v, 1),\n                  GET_DOUBLE2(initPos, v, 2));\n        input->restShape[v] = p;\n        centroid += p;\n        for (int i = 0; i < 3; ++i)\n        {\n            minPos[i] = std::min(minPos[i], p[i]);\n            maxPos[i] = std::max(maxPos[i], p[i]);\n        }\n    }\n    centroid /= numVertices;\n    double scale = std::max(std::max(maxPos.x - minPos.x, maxPos.y - minPos.y), maxPos.z - minPos.z);\n    MMatrix m = MMatrix::identity;\n    m(0, 0) = m(1, 1) = m(2, 2) = 1.0 / scale;\n    m(3, 0) = -centroid.x / scale;\n    m(3, 1) = -centroid.y / scale;\n    m(3, 2) = -centroid.z / scale;\n    input->normalizer = m;\n    // normalized samples\n    for (int v = 0; v < numVertices; ++v)\n    {\n        input->restShape[v] = input->restShape[v] * input->normalizer;\n        for (int s = 0; s < numSamples; ++s)\n        {\n            MPoint p(GET_DOUBLE3(shapeSample, s, v, 0),\n                     GET_DOUBLE3(shapeSample, s, v, 1),\n                     GET_DOUBLE3(shapeSample, s, v, 2));\n            input->sample[s * numVertices + v] = p * input->normalizer;\n        }\n    }\n    // one-ring neighbor [Le and Deng 2014]\n    for (int v = 0; v < numVertices; ++v)\n    {\n\t\tdouble lv = 0.0;\n        for (int i = 0; i < neighborVertices->dimensions[1]; ++i)\n        {\n            long n = GET_LONG2(neighborVertices, v, i);\n            if (n < 0)\n            {\n                continue;\n            }\n            double len = (input->restShape[v] - input->restShape[n]).length();\n            if (len > 0)\n            {\n\t\t\t\t// [Le and Deng 2014]\n\t\t\t\tdouble dsqsum = 0;\n\t\t\t\tfor (int s = 0; s < input->numSamples; ++s)\n\t\t\t\t{\n\t\t\t\t\tfloat diff = (input->restShape[v] - input->restShape[n]).length()\n\t\t\t\t\t\t- (input->sample[s * numVertices + v] - input->sample[s * numVertices + n]).length();\n\t\t\t\t\tdsqsum += diff * diff;\n\t\t\t\t}\n\t\t\t\tdsqsum += 1.0e-10;\n\t\t\t\tdouble dvn = 1.0 / std::sqrt(dsqsum / input->numSamples);\n                input->neighbor[v].push_back(std::make_pair(n, dvn));\n                lv += dvn;\n            }\n        }\n\t\tfor (int n = 0; n < input->neighbor[v].size(); ++n)\n\t\t{\n\t\t\tinput->neighbor[v][n].second /= -lv;\n\t\t}\n\t}\n    PyObject* retval = PyTuple_New(2);\n    PyTuple_SetItem(retval, 0, PyCapsule_New(input,  \"SSDSInput\", nullptr));\n    PyTuple_SetItem(retval, 1, PyCapsule_New(output, \"SSDSOutput\", nullptr));\n    return retval;\n}\n\nstatic PyObject* release(PyObject *self, PyObject *args)\n{\n\tPyObject* pin = PyTuple_GET_ITEM(args, 0);\n\tPyObject* pout = PyTuple_GET_ITEM(args, 1);\n\tdelete reinterpret_cast<Input*>(PyCapsule_GetPointer(pin, \"SSDSInput\"));\n\tdelete reinterpret_cast<Output*>(PyCapsule_GetPointer(pout, \"SSDSOutput\"));\n\treturn Py_None;\n}\n\nstatic PyObject* retrieveResult(PyObject *self, PyObject *args)\n{\n\tPyObject* pin                = PyTuple_GET_ITEM(args, 0);\n\tPyObject* pout               = PyTuple_GET_ITEM(args, 1);\n\tPyArrayObject* skinIndex     = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 2));\n\tPyArrayObject* skinWeight    = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 3));\n\tPyArrayObject* skinMatrix    = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 4));\n    PyArrayObject* restJointPos = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 5));\n    Input* const input     = reinterpret_cast<Input*>(PyCapsule_GetPointer(pin, \"SSDSInput\"));\n\tOutput* const output   = reinterpret_cast<Output*>(PyCapsule_GetPointer(pout, \"SSDSOutput\"));\n    const long& numIndices = output->numIndices;\n\n    MMatrix inm = input->normalizer.inverse();\n\tfor (int s = 0; s < input->numSamples; ++s)\n\t{\n\t\tfor (int b = 0; b < output->numJoints; ++b)\n\t\t{\n\t\t\tMMatrix m = input->normalizer * output->skinMatrix[s * output->numJoints + b].asMatrix() * inm;\n\t\t\tfor (int i = 0; i < 4; ++i)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 4; ++j)\n\t\t\t\t{\n\t\t\t\t\tSET_DOUBLE4(skinMatrix, b, s, i, j, m(i, j));\n\t\t\t\t}\n\t\t\t}\n        }\n\t}\n    for (int v = 0; v < input->numVertices; ++v)\n    {\n        for (long i = 0; i < numIndices; ++i)\n        {\n            SET_LONG2(skinIndex, v, i, output->skinIndex[v * numIndices + i]);\n            SET_DOUBLE2(skinWeight, v, i, output->skinWeight[v * numIndices + i]);\n        }\n    }\n    for (int j = 0; j < output->numJoints; ++j)\n    {\n        MPoint cp = output->restJointPos[j] * inm;\n        SET_DOUBLE2(restJointPos, j, 0, cp.x);\n        SET_DOUBLE2(restJointPos, j, 1, cp.y);\n        SET_DOUBLE2(restJointPos, j, 2, cp.z);\n    }\n\treturn Py_None;\n}\n#pragma endregion\n\nstatic PyMethodDef methods[] = {\n    { \"initialize\", initialize, METH_VARARGS, \"initialize\" },\n    { \"clusterVerticesPcenter\", clusterVerticesPcenter, METH_VARARGS, \"clusterVerticesPcenter\" },\n    { \"clusterVerticesAdaptive\", clusterVerticesAdaptive, METH_VARARGS, \"clusterVerticesAdaptive\" },\n    { \"updateJointTransform\", updateJointTransform, METH_VARARGS, \"updateJointTransform\" },\n    { \"updateSkinWeight\", updateSkinWeight, METH_VARARGS, \"updateSkinWeight\" },\n\t{ \"retrieveResult\", retrieveResult, METH_VARARGS, \"retrieveResult\" },\n\t{ \"release\", release, METH_VARARGS, \"release\" },\n\t{ NULL, NULL, 0, NULL }\n};\n\nPyMODINIT_FUNC initnative(void)\n{\n    Py_InitModule(\"native\", methods);\n    import_array();\n\tEigen::initParallel();\n}\n", "meta": {"hexsha": "e78d7741dcbcc5a8d1c6572e4099d63a56e9ff64", "size": 41701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "native/native.cpp", "max_stars_repo_name": "TomohikoMukai/ssds", "max_stars_repo_head_hexsha": "eb3063eb010a0165ee3a339e279defb255bb2827", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2018-10-27T00:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T13:06:49.000Z", "max_issues_repo_path": "native/native.cpp", "max_issues_repo_name": "TomohikoMukai/ssds", "max_issues_repo_head_hexsha": "eb3063eb010a0165ee3a339e279defb255bb2827", "max_issues_repo_licenses": ["MIT"], "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/native.cpp", "max_forks_repo_name": "TomohikoMukai/ssds", "max_forks_repo_head_hexsha": "eb3063eb010a0165ee3a339e279defb255bb2827", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T08:39:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T22:31:57.000Z", "avg_line_length": 36.8058252427, "max_line_length": 188, "alphanum_fraction": 0.5704419558, "num_tokens": 11233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.019124038183431884, "lm_q1q2_score": 0.008965169843635244}}
{"text": "//=============================================================================================================\n/**\n * @file     fiff_cov.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\n *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n *           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>\n * @since    0.1.0\n * @date     July, 2012\n *\n * @section  LICENSE\n *\n * Copyright (C) 2012, Lorenz Esch, Matti Hamalainen, Christoph Dinh. 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 the FiffCov Class.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"fiff_cov.h\"\n#include \"fiff_stream.h\"\n#include \"fiff_info_base.h\"\n#include \"fiff_dir_node.h\"\n\n#include <utils/mnemath.h>\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QPair>\n\n//=============================================================================================================\n// EIGEN INCLUDES\n//=============================================================================================================\n\n#include <Eigen/SVD>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace FIFFLIB;\nusing namespace UTILSLIB;\nusing namespace Eigen;\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nFiffCov::FiffCov()\n: kind(-1)\n, diag(false)\n, dim(-1)\n, nfree(-1)\n{\n    qRegisterMetaType<QSharedPointer<FIFFLIB::FiffCov> >(\"QSharedPointer<FIFFLIB::FiffCov>\");\n    qRegisterMetaType<FIFFLIB::FiffCov>(\"FIFFLIB::FiffCov\");\n}\n\n//=============================================================================================================\n\nFiffCov::FiffCov(QIODevice &p_IODevice)\n: kind(-1)\n, diag(false)\n, dim(-1)\n, nfree(-1)\n{\n    FiffStream::SPtr t_pStream(new FiffStream(&p_IODevice));\n\n    if(!t_pStream->open())\n    {\n        printf(\"\\tNot able to open IODevice.\\n\");//ToDo Throw here\n        return;\n    }\n\n    if(!t_pStream->read_cov(t_pStream->dirtree(), FIFFV_MNE_NOISE_COV, *this))\n        printf(\"\\tFiff covariance not found.\\n\");//ToDo Throw here\n\n    qRegisterMetaType<QSharedPointer<FIFFLIB::FiffCov> >(\"QSharedPointer<FIFFLIB::FiffCov>\");\n    qRegisterMetaType<FIFFLIB::FiffCov>(\"FIFFLIB::FiffCov\");\n}\n\n//=============================================================================================================\n\nFiffCov::FiffCov(const FiffCov &p_FiffCov)\n: QSharedData(p_FiffCov)\n, kind(p_FiffCov.kind)\n, diag(p_FiffCov.diag)\n, dim(p_FiffCov.dim)\n, names(p_FiffCov.names)\n, data(p_FiffCov.data)\n, projs(p_FiffCov.projs)\n, bads(p_FiffCov.bads)\n, nfree(p_FiffCov.nfree)\n, eig(p_FiffCov.eig)\n, eigvec(p_FiffCov.eigvec)\n{\n    qRegisterMetaType<QSharedPointer<FIFFLIB::FiffCov> >(\"QSharedPointer<FIFFLIB::FiffCov>\");\n    qRegisterMetaType<FIFFLIB::FiffCov>(\"FIFFLIB::FiffCov\");\n}\n\n//=============================================================================================================\n\nFiffCov::~FiffCov()\n{\n}\n\n//=============================================================================================================\n\nvoid FiffCov::clear()\n{\n    kind = -1;\n    diag = false;\n    dim = -1;\n    names.clear();\n    data = MatrixXd();\n    projs.clear();\n    bads.clear();\n    nfree = -1;\n    eig = VectorXd();\n    eigvec = MatrixXd();\n}\n\n//=============================================================================================================\n\nFiffCov FiffCov::pick_channels(const QStringList &p_include, const QStringList &p_exclude)\n{\n    RowVectorXi sel = FiffInfoBase::pick_channels(this->names, p_include, p_exclude);\n    FiffCov res;//No deep copy here - since almost everything else is adapted anyway\n\n    res.kind = this->kind;\n    res.diag = this->diag;\n    res.dim = sel.size();\n\n    for(qint32 k = 0; k < sel.size(); ++k)\n        res.names << this->names[sel(k)];\n\n    res.data.resize(res.dim, res.dim);\n    for(qint32 i = 0; i < res.dim; ++i)\n        for(qint32 j = 0; j < res.dim; ++j)\n            res.data(i, j) = this->data(sel(i), sel(j));\n    res.projs = this->projs;\n\n    for(qint32 k = 0; k < this->bads.size(); ++k)\n        if(res.names.contains(this->bads[k]))\n            res.bads << this->bads[k];\n    res.nfree = this->nfree;\n\n    return res;\n}\n\n//=============================================================================================================\n\nFiffCov FiffCov::prepare_noise_cov(const FiffInfo &p_Info, const QStringList &p_ChNames) const\n{\n    FiffCov p_NoiseCov(*this);\n\n    VectorXi C_ch_idx = VectorXi::Zero(p_NoiseCov.names.size());\n    qint32 count = 0;\n    for(qint32 i = 0; i < p_ChNames.size(); ++i)\n    {\n        qint32 idx = p_NoiseCov.names.indexOf(p_ChNames[i]);\n        if(idx > -1)\n        {\n            C_ch_idx[count] = idx;\n            ++count;\n        }\n    }\n    C_ch_idx.conservativeResize(count);\n\n    MatrixXd C(count, count);\n\n    if(!p_NoiseCov.diag)\n        for(qint32 i = 0; i < count; ++i)\n            for(qint32 j = 0; j < count; ++j)\n                C(i,j) = p_NoiseCov.data(C_ch_idx(i), C_ch_idx(j));\n    else\n    {\n        qWarning(\"Warning in FiffCov::prepare_noise_cov: This has to be debugged - not done before!\");\n        C = MatrixXd::Zero(count, count);\n        for(qint32 i = 0; i < count; ++i)\n            C.diagonal()[i] = p_NoiseCov.data(C_ch_idx(i),0);\n    }\n\n    MatrixXd proj;\n    qint32 ncomp = p_Info.make_projector(proj, p_ChNames);\n\n    //Create the projection operator\n    if (ncomp > 0 && proj.rows() == count)\n    {\n        printf(\"Created an SSP operator (subspace dimension = %d)\\n\", ncomp);\n        C = proj * (C * proj.transpose());\n    } else {\n        qWarning(\"Warning in FiffCov::prepare_noise_cov: No projections applied since no projectors specified or projector dimensions do not match!\");\n    }\n\n    RowVectorXi pick_meg = p_Info.pick_types(true, false, false, defaultQStringList, p_Info.bads);\n    RowVectorXi pick_eeg = p_Info.pick_types(false, true, false, defaultQStringList, p_Info.bads);\n\n    QStringList meg_names, eeg_names;\n\n    for(qint32 i = 0; i < pick_meg.size(); ++i)\n        meg_names << p_Info.chs[pick_meg[i]].ch_name;\n    VectorXi C_meg_idx = VectorXi::Zero(p_NoiseCov.names.size());\n    count = 0;\n    for(qint32 k = 0; k < C.rows(); ++k)\n    {\n        if(meg_names.indexOf(p_ChNames[k]) > -1)\n        {\n            C_meg_idx[count] = k;\n            ++count;\n        }\n    }\n    if(count > 0)\n        C_meg_idx.conservativeResize(count);\n    else\n        C_meg_idx = VectorXi();\n\n    //\n    for(qint32 i = 0; i < pick_eeg.size(); ++i)\n        eeg_names << p_Info.chs[pick_eeg(0,i)].ch_name;\n    VectorXi C_eeg_idx = VectorXi::Zero(p_NoiseCov.names.size());\n    count = 0;\n    for(qint32 k = 0; k < C.rows(); ++k)\n    {\n        if(eeg_names.indexOf(p_ChNames[k]) > -1)\n        {\n            C_eeg_idx[count] = k;\n            ++count;\n        }\n    }\n\n    if(count > 0)\n        C_eeg_idx.conservativeResize(count);\n    else\n        C_eeg_idx = VectorXi();\n\n    bool has_meg = C_meg_idx.size() > 0;\n    bool has_eeg = C_eeg_idx.size() > 0;\n\n    MatrixXd C_meg, C_eeg;\n    VectorXd C_meg_eig, C_eeg_eig;\n    MatrixXd C_meg_eigvec, C_eeg_eigvec;\n    if (has_meg)\n    {\n        count = C_meg_idx.rows();\n        C_meg = MatrixXd(count,count);\n        for(qint32 i = 0; i < count; ++i)\n            for(qint32 j = 0; j < count; ++j)\n                C_meg(i,j) = C(C_meg_idx(i), C_meg_idx(j));\n        MNEMath::get_whitener(C_meg, false, QString(\"MEG\"), C_meg_eig, C_meg_eigvec);\n    }\n\n    if (has_eeg)\n    {\n        count = C_eeg_idx.rows();\n        C_eeg = MatrixXd(count,count);\n        for(qint32 i = 0; i < count; ++i)\n            for(qint32 j = 0; j < count; ++j)\n                C_eeg(i,j) = C(C_eeg_idx(i), C_eeg_idx(j));\n        MNEMath::get_whitener(C_eeg, false, QString(\"EEG\"), C_eeg_eig, C_eeg_eigvec);\n    }\n\n    qint32 n_chan = p_ChNames.size();\n    p_NoiseCov.eigvec = MatrixXd::Zero(n_chan, n_chan);\n    p_NoiseCov.eig = VectorXd::Zero(n_chan);\n\n    if(has_meg)\n    {\n        for(qint32 i = 0; i < C_meg_idx.rows(); ++i)\n            for(qint32 j = 0; j < C_meg_idx.rows(); ++j)\n                p_NoiseCov.eigvec(C_meg_idx[i], C_meg_idx[j]) = C_meg_eigvec(i, j);\n        for(qint32 i = 0; i < C_meg_idx.rows(); ++i)\n            p_NoiseCov.eig(C_meg_idx[i]) = C_meg_eig[i];\n    }\n    if(has_eeg)\n    {\n        for(qint32 i = 0; i < C_eeg_idx.rows(); ++i)\n            for(qint32 j = 0; j < C_eeg_idx.rows(); ++j)\n                p_NoiseCov.eigvec(C_eeg_idx[i], C_eeg_idx[j]) = C_eeg_eigvec(i, j);\n        for(qint32 i = 0; i < C_eeg_idx.rows(); ++i)\n            p_NoiseCov.eig(C_eeg_idx[i]) = C_eeg_eig[i];\n    }\n\n    if (C_meg_idx.size() + C_eeg_idx.size() != n_chan)\n    {\n        printf(\"Error in FiffCov::prepare_noise_cov: channel sizes do no match!\\n\");//ToDo Throw here\n        return FiffCov();\n    }\n\n    p_NoiseCov.data = C;\n    p_NoiseCov.dim = p_ChNames.size();\n    p_NoiseCov.diag = false;\n    p_NoiseCov.names = p_ChNames;\n\n    return p_NoiseCov;\n}\n\n//=============================================================================================================\n\nFiffCov FiffCov::regularize(const FiffInfo& p_info, double p_fRegMag, double p_fRegGrad, double p_fRegEeg, bool p_bProj, QStringList p_exclude) const\n{\n    FiffCov cov(*this);\n\n    if(p_exclude.size() == 0)\n    {\n        p_exclude = p_info.bads;\n        for(qint32 i = 0; i < cov.bads.size(); ++i)\n            if(!p_exclude.contains(cov.bads[i]))\n                p_exclude << cov.bads[i];\n    }\n\n    //Allways exclude all STI channels from covariance computation\n    int iNoStimCh = 0;\n\n    for(int i=0; i<p_info.chs.size(); i++) {\n        if(p_info.chs[i].kind == FIFFV_STIM_CH) {\n            p_exclude << p_info.chs[i].ch_name;\n            iNoStimCh++;\n        }\n    }\n\n    RowVectorXi sel_eeg = p_info.pick_types(false, true, false, defaultQStringList, p_exclude);\n    RowVectorXi sel_mag = p_info.pick_types(QString(\"mag\"), false, false, defaultQStringList, p_exclude);\n    RowVectorXi sel_grad = p_info.pick_types(QString(\"grad\"), false, false, defaultQStringList, p_exclude);\n\n    QStringList info_ch_names = p_info.ch_names;\n    QStringList ch_names_eeg, ch_names_mag, ch_names_grad;\n    for(qint32 i = 0; i < sel_eeg.size(); ++i)\n        ch_names_eeg << info_ch_names[sel_eeg(i)];\n    for(qint32 i = 0; i < sel_mag.size(); ++i)\n        ch_names_mag << info_ch_names[sel_mag(i)];\n    for(qint32 i = 0; i < sel_grad.size(); ++i)\n        ch_names_grad << info_ch_names[sel_grad(i)];\n\n    // This actually removes bad channels from the cov, which is not backward\n    // compatible, so let's leave all channels in\n    FiffCov cov_good = cov.pick_channels(info_ch_names, p_exclude);\n    QStringList ch_names = cov_good.names;\n\n    std::vector<qint32> idx_eeg, idx_mag, idx_grad;\n    for(qint32 i = 0; i < ch_names.size(); ++i)\n    {\n        if(ch_names_eeg.contains(ch_names[i]))\n            idx_eeg.push_back(i);\n        else if(ch_names_mag.contains(ch_names[i]))\n            idx_mag.push_back(i);\n        else if(ch_names_grad.contains(ch_names[i]))\n            idx_grad.push_back(i);\n    }\n\n    MatrixXd C(cov_good.data);\n\n    //Subtract number of found stim channels because they are still in C but not the idx_eeg, idx_mag or idx_grad\n    if((unsigned) C.rows() - iNoStimCh != idx_eeg.size() + idx_mag.size() + idx_grad.size()) {\n        printf(\"Error in FiffCov::regularize: Channel dimensions do not fit.\\n\");//ToDo Throw\n    }\n\n    QList<FiffProj> t_listProjs;\n    if(p_bProj)\n    {\n        t_listProjs = p_info.projs + cov_good.projs;\n        FiffProj::activate_projs(t_listProjs);\n    }\n\n    //Build regularization MAP\n    QMap<QString, QPair<double, std::vector<qint32> > > regData;\n    regData.insert(\"EEG\", QPair<double, std::vector<qint32> >(p_fRegEeg, idx_eeg));\n    regData.insert(\"MAG\", QPair<double, std::vector<qint32> >(p_fRegMag, idx_mag));\n    regData.insert(\"GRAD\", QPair<double, std::vector<qint32> >(p_fRegGrad, idx_grad));\n\n    //\n    //Regularize\n    //\n    QMap<QString, QPair<double, std::vector<qint32> > >::Iterator it;\n    for(it = regData.begin(); it != regData.end(); ++it)\n    {\n        QString desc(it.key());\n        double reg = it.value().first;\n        std::vector<qint32> idx = it.value().second;\n\n        if(idx.size() == 0 || reg == 0.0)\n            printf(\"\\tNothing to regularize within %s data.\\n\", desc.toUtf8().constData());\n        else\n        {\n            printf(\"\\tRegularize %s: %f\\n\", desc.toUtf8().constData(), reg);\n            MatrixXd this_C(idx.size(), idx.size());\n            for(quint32 i = 0; i < idx.size(); ++i)\n                for(quint32 j = 0; j < idx.size(); ++j)\n                    this_C(i,j) = cov_good.data(idx[i], idx[j]);\n\n            MatrixXd U;\n            qint32 ncomp;\n            if(p_bProj)\n            {\n                QStringList this_ch_names;\n                for(quint32 k = 0; k < idx.size(); ++k)\n                    this_ch_names << ch_names[idx[k]];\n\n                MatrixXd P;\n                ncomp = FiffProj::make_projector(t_listProjs, this_ch_names, P); //ToDo: Synchronize with mne-python and debug\n\n                JacobiSVD<MatrixXd> svd(P, ComputeFullU);\n                //Sort singular values and singular vectors\n                VectorXd t_s = svd.singularValues();\n                MatrixXd t_U = svd.matrixU();\n                MNEMath::sort<double>(t_s, t_U);\n\n                U = t_U.block(0,0, t_U.rows(), t_U.cols()-ncomp);\n\n                if (ncomp > 0)\n                {\n                    printf(\"\\tCreated an SSP operator for %s (dimension = %d).\\n\", desc.toUtf8().constData(), ncomp);\n                    this_C = U.transpose() * (this_C * U);\n                }\n            }\n\n            double sigma = this_C.diagonal().mean();\n            this_C.diagonal() = this_C.diagonal().array() + reg * sigma;  // modify diag inplace\n            if(p_bProj && ncomp > 0)\n                this_C = U * (this_C * U.transpose());\n\n            for(qint32 i = 0; i < this_C.rows(); ++i)\n                for(qint32 j = 0; j < this_C.cols(); ++j)\n                    C(idx[i],idx[j]) = this_C(i,j);\n        }\n    }\n\n    // Put data back in correct locations\n    RowVectorXi idx = FiffInfo::pick_channels(cov.names, info_ch_names, p_exclude);\n    for(qint32 i = 0; i < idx.size(); ++i)\n        for(qint32 j = 0; j < idx.size(); ++j)\n            cov.data(idx[i], idx[j]) = C(i, j);\n\n    return cov;\n}\n\n//=============================================================================================================\n\nFiffCov& FiffCov::operator= (const FiffCov &rhs)\n{\n    if (this != &rhs) // protect against invalid self-assignment\n    {\n        kind = rhs.kind;\n        diag = rhs.diag;\n        dim = rhs.dim;\n        names = rhs.names;\n        data = rhs.data;\n        projs = rhs.projs;\n        bads = rhs.bads;\n        nfree = rhs.nfree;\n        eig = rhs.eig;\n        eigvec = rhs.eigvec;\n    }\n    // to support chained assignment operators (a=b=c), always return *this\n    return *this;\n}\n", "meta": {"hexsha": "285debb85df94c8f14684e3b06ea6220ec15908d", "size": 17118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fiff/fiff_cov.cpp", "max_stars_repo_name": "jobehrens/mne-cpp", "max_stars_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 130.0, "max_stars_repo_stars_event_min_datetime": "2015-02-01T23:47:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T01:46:11.000Z", "max_issues_repo_path": "libraries/fiff/fiff_cov.cpp", "max_issues_repo_name": "jobehrens/mne-cpp", "max_issues_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 519.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T12:44:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T18:12:52.000Z", "max_forks_repo_path": "libraries/fiff/fiff_cov.cpp", "max_forks_repo_name": "jobehrens/mne-cpp", "max_forks_repo_head_hexsha": "5156f578736bbb67cc9ae1fc41a7cefba3b10f7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 138.0, "max_forks_repo_forks_event_min_datetime": "2015-04-02T12:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T13:21:25.000Z", "avg_line_length": 35.6625, "max_line_length": 150, "alphanum_fraction": 0.5320130856, "num_tokens": 4487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577487985229844, "lm_q2_score": 0.025178842340659164, "lm_q1q2_score": 0.008957999608567978}}
{"text": "﻿/*\n @file\n @author Toshihide Hara, Tokyo university of science\n\n @brief MTRAP: (Pairwise) Sequence alignment algorithm by a new measure based on transition probability between two consecutive pairs of residues\n\n === HOW TO USE ===\n [1] Sequence Alignment\n mtrap [option] inName outName\n [2] Output Binary format Transition-quantity Matrix\n mtrap -tm inName -outbintm outName\n or\n bash> for i in `ls *.tq` ; do mtrap -tm $i -outbintm ${i%.*}.btq  ; done\n\n=== TODO ===\n20120316\n= general =\n・new が失敗したときNULLがかえってくるとはかぎらない\n・staticは，初期化においてマルチスレッド+VCで問題を起こす\n20120311\n・OPEN MPをOnにすると，Profile作成は高速化するがIterativeRefinementsはたまに遅くなる．原因不明．HyperThreadやキャッシュが原因？\n= genetic distance & guide tree =\n・案内木構築法としてNJ,WSPS等を実装\n・案内木のための遺伝距離行列としてEER以外にもp-distance(clustal互換)等を実装すべき\n\n $Revision: $\n*/\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <cassert>\n#include <cctype>\n#include <map>\n#include <string>\n#include <fstream>\n#include <cmath>\n#include <ctime>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <shand/format.hpp>\n#include \"distance.h\"\n#include \"scorematrix.h\"\n#include \"tqmatrix.h\"\n#include \"mtrap.h\"\n#include \"pairwise.h\"\n#include \"probalign.h\"\n#include \"utility.h\"\n#include \"entropy.h\"\n#include \"primarylibrary.h\"\n#include \"search.h\"\n#include \"sequences.h\"\n#include \"globaloption.h\"\n#include \"tree.h\"\n#include \"estimatefamily.h\"\n#include \"config.h\"\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\nusing namespace std;\n\nvoid help_line(const string& option, const string& value, const string& explain){\n    cerr << left << setw(10) << option;\n    if(value != \"\")\n    {\n        cerr << right << setw(17) << (\"[\" + value + \"]  \");\n    }else{\n        cerr << right << setw(17) << \" \";\n    }\n    cerr << explain;\n    cerr << endl;\n}\n\nvoid printHelp(){\n    cerr << \"==================\" << endl;\n    cerr << \"  MTRAP Ver. \" << string(VERSION);\n#ifdef _OPENMP\n    cerr << \" [USE OPENMP]\";\n#endif\n#ifdef USE_PROBALIGN\n    cerr << \" [USE PROBALIGN]\";\n#endif\n#ifdef DEBUG\n    cerr << \" [DEBUG VERSION]\";\n#endif\n    cerr << endl;\n\n    cerr << \"=== HOW TO USE ===\" << endl;\n    cerr << \"mtrap [OPTIONS] inputfile outputfile\" << endl;\n    cerr << endl;\n    cerr << \"===   OPTIONS  === \" << endl;\n    cerr << \"= GENERAL =\" << endl;\n    help_line(\"-I\",\"...\",\"add search path e.g. -I ~/mymatrix\");\n    help_line(\"-filelist\",\"...\",\"\");\n    help_line(\"-i\",\"...\",\"input file (FASTA format)\");\n    help_line(\"-o\",\"...\",\"output file\");\n    help_line(\"-nosort\",\"\",\"the results are not sorted\");\n    help_line(\"-noestimation\",\"\",\"do not estimate a family\");\n    help_line(\"-cds\",\"GENETICCODES (comma separate)\",\"\\\"protein\\\" coding DNA sequence\");\n    cerr << \"             GENETICCODE 0: The Standard Code (transl_table=1)\" << endl;\n    cerr << \"                         1: The Vertebrate Mitochondrial Code (transl_table=2)\" << endl;\n    cerr << \"                         2: The Invertebrate Mitochondrial Code (transl_table=5)\" << endl;\n    cerr << \"                         3: The Bacterial, Archaeal and Plant Plastid Code (transl_table=11)\" << endl;\n    cerr << endl;\n    cerr << \"= GAP =\" << endl;\n    help_line(\"-go\",DS(globalOption.gap_open),\"gap open [score]\");\n    help_line(\"-ge\",DS(globalOption.gap_ext),\"gap extension [score]\");\n    cerr << endl;\n    cerr << \"= MULTIPLE ALIGNMENT =\" << endl;\n    help_line(\"-itr\",IS(globalOption.numIterativeRefReps),\"set the number of iterations\");\n    help_line(\"-c\",IS(globalOption.numConsistencyReps),\"set the number of consistency transformations\");\n    cerr << endl;\n    cerr << \"= SUBSTITUTION MATRIX =\" << endl;\n    help_line(\"-m\",globalOption.smatrixName,\"substitution matrix e.g. CGONNET250, EBLOSUM62\");\n    help_line(\"-rm\",globalOption.rmatrixName,\"ramachandran matrix e.g. MRAMA1\");\n    help_line(\"-averageExtendedAA\",\"\",\"average extended amino acids (B,Z and X) substitutions\");\n    cerr << endl;\n    cerr << \"= TRANSITION QUANTITY MATRIX =\" << endl;\n    help_line(\"-tm\",globalOption.tmatrixName,\"transition-quantity matrix\");\n    help_line(\"-e\",DS(ScoreMatrix::epsilon),\"epsilon, weight for transition quantity\");\n    cerr << endl;\n    cerr << \"= RAMACHANDRAN QUANTITY =\" << endl;\n    help_line(\"-gamma\",DS(ScoreMatrix::gamma),\"gamma, weight for ramachandran matrix\");\n    cerr << endl;\n    cerr << \"= PARTITION FUNCTION POSTERIOR PROBABILITY =\" << endl;\n    help_line(\"-pf\",DS(1 - globalOption.mtrap_degree),\"the degree of partition function\");\n    help_line(\"-pm\",globalOption.pmatrixName,\"substitution matrix used for partition function\");\n    help_line(\"-pgo\",DS(globalOption.gap_open_part),\"gap open [score] for partition function\");\n    help_line(\"-pge\",DS(globalOption.gap_ext_part),\"gap extension [score] for partition function\");\n    help_line(\"-beta\",DS(globalOption.beta),\"beta, weight for partition function\");\n#ifndef USE_PROBALIGN\n    help_line(\"-beta2\",DS(globalOption.betaTQ),\"beta2, weight for a part of TQ of partition function\");\n#endif\n    cerr << endl;\n    cerr << \"= GENERATING MODE =\" << endl;\n    help_line(\"-primarylibrary\",\"ID\",\"output T-Coffee primary library, ID: sequence identity (same as T-Coffee)\");\n    cerr << endl;\n    help_line(\"-count\",\"MODES FILELIST WEIGHTLIST\",\"count the frequency of transition\");\n    cerr << \"           MODES 0: normal 1:skip gap-gap site 2:set zero gap site\" << endl;\n    cerr << \"                 3: direct prob 4: without lower case 5: global TQ\" << endl;\n    cerr << \"                 f: symmetrize the frequencies not the tq\" << endl;\n    cerr << \"                 n: do not round the substitution matrix\" << endl;\n    help_line(\"-outbintm\",\"FILENAME\",\"output binary format transition-quantity matrix\");\n    cerr << endl;\n//    cerr << \"= DATABASE SEARCH MODE (UNDER CONSTRUCTION) =\" << endl;\n//    cerr << \"-search query database : query and database must be multiple fasta format. The option -o should be used together.\" << endl;\n//    cerr << \"-search_allpair database : database must be ASTRAL SCOP fasta format. The option -o should be used together.\" << endl;\n//    cerr << \"-searchlimit query database\" << endl;\n//    cerr << endl;\n//  cerr << \"= DEBUG =\" << endl;\n//\tcerr << \"-pass output pass matrix filename\" << endl;\n//\tcerr << \"-oldeer use traditional entropy evolution rate\" << endl;\n//\tcerr << \"-gmode value[0] 0: A,B 1: width=1(B=0)  2: mirror only(A=-1,B=0)\" << endl;\n//\tcerr << \"!!! Set -gmode before -m -tm !!!\" << endl;\n//\tcerr << \"-withoutT: Gap cost without transition value\" << endl;\n}\n\n\n//! load the list for batch style aligment.\n/*!\n\n    \\param fileName comma separated style, i.e. input filename, output filename[ret].\n*/\nvoid loadFilelist(const string& fileName)\n{\n    ifstream ifs(fileName.c_str());\n    string buff;\n\n    while(ifs && getline(ifs, buff))\n    {\n        vector<string> vs;\n        mySplit(buff, \", \", vs);\n        if(vs.size() == 0)break;\n        globalOption.inputFilenameList.push_back(vs[0]);\n        globalOption.outputFilenameList.push_back(vs[1]);\n    }\n\n    ifs.close();\n}\n\nvoid setOptionDefaultValue()\n{\n    // set primary default value\n    globalOption.tmatrixName = \"SABmark1.63_sup_weighted.btq\";\n    globalOption.smatrixName = \"VTML200I\"; // \"CGONNET250\";\n    globalOption.pmatrixName = \"VTML200I\"; // CGONNET160\";\n    globalOption.rmatrixName = \"MRAMA1\";\n    globalOption.fmatrixDir = \"fsmatrix-sabmark1.65\";\n\n    globalOption.csvSCOP_SAB_ID_Name = \"scop1.75-id-with-sab1.65-group.csv\";\n    globalOption.csvSAB_seq_group_Name = \"fsmatrix-sabmark1.65/summary_sequence.csv\";\n\n    globalOption.familyEstimation = false;\n    globalOption.familyDatabaseName = \"fsmatrix-sabmark1.65/SABmark1.65.fasta\";\n\n    globalOption.CDSMode = false;\n    globalOption.CDS_type.clear();\n\n    globalOption.gap_open = -11;\n    globalOption.gap_ext = -0.3;\n    globalOption.gap_open_part = -22;\n    globalOption.gap_ext_part = -1;\n    globalOption.mtrap_degree = 0.3;\n    globalOption.beta = 0.2;\n    globalOption.betaTQ = 1.5;\n    ScoreMatrix::gapWithoutTscore = false;\n    ScoreMatrix::epsilon = 0.775;\n    ScoreMatrix::gamma = 0.0;\n    globalOption.primaryLibraryDistance = Distance::GID;\n    globalOption.numConsistencyReps = 2;\n    globalOption.numIterativeRefReps = 10;\n    globalOption.sortByInputOrder = true;\n\n    // set secondary default value\n\n\n}\n\nint setOption(int argc, char ** argv, int priority)\n{\n    vec_string vecARGV;\n    for(int i=1; i<argc; i++)vecARGV.push_back(string(argv[i]));\n\n    // First priority options\n    if(priority==0)\n    {\n        // default value\n        setOptionDefaultValue();\n\n        for(vector<string>::iterator i=vecARGV.begin(); i!=vecARGV.end(); ++i)\n        {\n            if(i->size() > 0 && i->at(0) == '-')\n            {\n                if(*i == \"-I\"){\n                    i++; fileSearchDirList.push_back(*i + \"/\");\n                }\n            }\n        }\n        return 0;\n    }else if(priority==1){\n        // Second priority options\n        for(vector<string>::iterator i=vecARGV.begin(); i!=vecARGV.end(); ++i)\n        {\n            if(i->at(0) == '-')\n            {\n                if(*i == \"-o\"){i++; globalOption.outputFilenameList.push_back(*i);\n                }else if(*i == \"-i\"){i++; globalOption.inputFilenameList.push_back(*i);\n                }else if(*i == \"-nosort\"){ globalOption.sortByInputOrder = false;\n                }else if(*i == \"-noestimation\"){ globalOption.familyEstimation = false;\n                }else if(*i == \"-cds\"){\n                    i++;\n                    globalOption.CDSMode = true;\n                    VS tmpVec;\n                    mySplit(*i, \",\", tmpVec);\n                    globalOption.CDS_type.clear();\n                    for(VS::const_iterator itr=tmpVec.begin(); itr!=tmpVec.end(); ++itr) globalOption.CDS_type.push_back(SI(*itr));\n                }else if(*i == \"-pass\"){i++; globalOption.outputFilename_pass = *i;\n                }else if(*i == \"-go\"){i++; globalOption.gap_open = string2binary<double>(*i);\n                }else if(*i == \"-ge\"){i++; globalOption.gap_ext = string2binary<double>(*i);\n                }else if(*i == \"-pgo\"){i++; globalOption.gap_open_part = string2binary<double>(*i);\n                }else if(*i == \"-pge\"){i++; globalOption.gap_ext_part = string2binary<double>(*i);\n                }else if(*i == \"-itr\"){i++; globalOption.numIterativeRefReps = string2binary<int>(*i);\n                }else if(*i == \"-c\"){i++; globalOption.numConsistencyReps = string2binary<int>(*i);\n                }else if(*i == \"-gmode\"){i++; ScoreMatrix::TRANS_MODE = string2binary<int>(*i);\n                }else if(*i == \"-oldeer\"){globalOption.optOLDEER = true;\n                }else if(*i == \"-m\"){i++; globalOption.smatrixName = *i;\n                }else if(*i == \"-tm\"){i++; globalOption.tmatrixName = *i;\n                }else if(*i == \"-rm\"){i++; globalOption.rmatrixName = *i;\n                }else if(*i == \"-pm\"){i++; globalOption.pmatrixName = *i;\n                }else if(*i == \"-averageExtendedAA\"){ScoreMatrix::averageExtendedAA = true;\n                }else if(*i == \"-e\"){i++; ScoreMatrix::epsilon = string2binary<double>(*i);\n                }else if(*i == \"-beta\"){i++; globalOption.beta = string2binary<double>(*i);\n                }else if(*i == \"-beta2\"){i++; globalOption.betaTQ = string2binary<double>(*i);\n                }else if(*i == \"-gamma\"){i++; ScoreMatrix::gamma = string2binary<double>(*i);\n                }else if(*i == \"-pf\"){i++; globalOption.mtrap_degree = 1.0 - string2binary<double>(*i);\n                }else if(*i == \"-withoutT\"){ScoreMatrix::gapWithoutTscore = true;\n                }else if(*i == \"-filelist\"){i++; loadFilelist(*i);\n                }else if(*i == \"-outbintm\"){i++; globalOption.outputFilenameList.push_back(*i); globalOption.binoutMode = true;\n                }else if(*i == \"-search\"){i++; globalOption.inputFilenameList.push_back(*i); i++; globalOption.inputFilenameList.push_back(*i); globalOption.searchMode = true;\n                }else if(*i == \"-search_allpair\"){i++; globalOption.inputFilenameList.push_back(*i); globalOption.search_allPairMode = true;\n                }else if(*i == \"-searchlimit\"){i++; globalOption.limitQuery = string2binary<int>(*i); i++; globalOption.limitDatabase = string2binary<int>(*i);\n                }else if(*i == \"-primarylibrary\"){\n                    i++; globalOption.primaryLibraryMode = true;\n                    if(*i == \"gid\"){globalOption.primaryLibraryDistance = Distance::GID;\n                    }else if(*i == \"lid\"){globalOption.primaryLibraryDistance = Distance::LID;\n                    }else if(*i == \"pdist\"){globalOption.primaryLibraryDistance = Distance::PDIST;\n                    }else if(*i == \"eer\"){globalOption.primaryLibraryDistance = Distance::EER;\n                    }else if(*i == \"eer2\"){globalOption.primaryLibraryDistance = Distance::EER2;\n                    }else if(*i == \"ecd\"){globalOption.primaryLibraryDistance = Distance::ECD;\n                    }else if(*i == \"ecdr\"){globalOption.primaryLibraryDistance = Distance::ECDR;\n                    }else{\n                        putError(*i + \" mode is not implemented\", false);\n                        return 1;\n                    }\n                }else if(*i == \"-count\"){\n                    i++; if(i==vecARGV.end()) { putError(\"command line may have some mistakes.\", true); }\n                    for(int j=0; j<(int)i->size(); j++)\n                    {\n                        if(i->at(j) == '0'){\n                            ScoreMatrix::countModeSkipGapGapSite = false;\n                            ScoreMatrix::countModeSetZeroGapSite = false;\n                            ScoreMatrix::countModeDirectProb = false;\n                        }else if(i->at(j) == '1'){\n                            ScoreMatrix::countModeSkipGapGapSite = true;\n                        }else if(i->at(j) == '2'){\n                            ScoreMatrix::countModeSetZeroGapSite = true;\n                        }else if(i->at(j) == '3'){\n                            ScoreMatrix::countModeDirectProb = true;\n                        }else if(i->at(j) == '4'){\n                            ScoreMatrix::countModeWithoutLowerCase = true;\n                        }else if(i->at(j) == '5'){\n                            ScoreMatrix::countModeGlobalTQ = true;\n                        }else if(i->at(j) == 'f'){\n                            ScoreMatrix::countModeSymmetrizeFreq = true;\n                        }else if(i->at(j) == 'n'){\n                            ScoreMatrix::countModeNoRound = true;\n                        }\n                    }\n                    // input: database\n                    i++; if(i==vecARGV.end()) { putError(\"command line may have some mistakes.\", true); }\n                    globalOption.inputFilenameList.push_back(*i);\n                    // input: sequence weight\n                    i++; if(i==vecARGV.end()) { putError(\"command line may have some mistakes.\", true); }\n                    globalOption.inputFilenameList.push_back(*i);\n                    // output\n                    i++; if(i==vecARGV.end()) { putError(\"command line may have some mistakes.\", true); }\n                    globalOption.outputFilenameList.push_back(*i);\n                    globalOption.countMode = true;\n                }else if(*i == \"-I\"){\n                    ++i;\n                    // reservation for first priority.\n                }else{\n                    return 1;\n                }\n            }else{\n                if(globalOption.inputFilenameList.size() == 0){\n                    globalOption.inputFilenameList.push_back(*i);\n                }else if(globalOption.outputFilenameList.size() == 0){\n                    globalOption.outputFilenameList.push_back(*i);\n                }else{\n                    putError(\"too many filenames.\", false);\n                    return 1;\n                }\n            }\n        }\n    } // end of priority\n\n    // === error check ===\n    if(globalOption.searchMode)\n    {\n        assert(globalOption.inputFilenameList.size() == 2 && globalOption.outputFilenameList.size() == 1);\n    }else if(globalOption.search_allPairMode){\n        assert(globalOption.inputFilenameList.size() == 1 && globalOption.outputFilenameList.size() == 1);\n    }else if(globalOption.primaryLibraryMode){\n        assert(globalOption.inputFilenameList.size() == 1 && globalOption.outputFilenameList.size() == 1);\n    }else if(globalOption.countMode){\n        assert(globalOption.inputFilenameList.size() == 2 && globalOption.outputFilenameList.size() == 1);\n    }else if(globalOption.binoutMode){\n        assert(globalOption.inputFilenameList.size() == 0 && globalOption.outputFilenameList.size() == 1);\n    }else{\n        if(globalOption.inputFilenameList.size() == 0)\n        {\n            cerr << \"no input filename.\" << endl;\n            return 1;\n        }\n        if(globalOption.outputFilenameList.size() == 0)\n        {\n            cerr << \"no output filename.\" << endl;\n            return 1;\n        }\n        assert(globalOption.inputFilenameList.size() == globalOption.outputFilenameList.size());\n    }\n\n\n    if(globalOption.familyEstimation)\n    {\n        // --- load { SCOP sccs: SABmark group } information ---\n        globalOption.setMapSccsGroup();\n        // --- load { SABmark sequence: SABmark group } information ---\n        globalOption.setMapSeqGroup();\n    }\n\n    // --- load matrices ---\n    setMatrixConfiguration();\n\n    return 0;\n}\n\n\nvoid setMatrixConfiguration()\n{\n    static string previous_smatrix = \"\";\n    static string previous_rmatrix = \"\";\n    static string previous_pmatrix = \"\";\n    static string previous_tmatrix = \"\";\n\n    bool shouldRecalcDist = false;\n\n    // load ramachandran matrix\n    if(previous_rmatrix != globalOption.rmatrixName && ScoreMatrix::gamma > 0.0)\n    {\n        ScoreMatrix::setRamachandran(fixFilePath(globalOption.rmatrixName));\n        previous_rmatrix = globalOption.rmatrixName;\n    }\n\n    // load substitution matrix used for partition function\n    // this matrix should NOT be normalized\n    if(previous_pmatrix != globalOption.pmatrixName)\n    {\n        ScoreMatrix::loadMatrix(fixFilePath(globalOption.pmatrixName), false, ScoreMatrix::pmatrix);\n        previous_pmatrix = globalOption.pmatrixName;\n        shouldRecalcDist = true;\n    }\n\n    // load substitution matrix\n    if(previous_smatrix != globalOption.smatrixName)\n    {\n        ScoreMatrix::loadMatrix(fixFilePath(globalOption.smatrixName), true, ScoreMatrix::amatrix);\n        previous_smatrix = globalOption.smatrixName;\n        shouldRecalcDist = true;\n\n        // normalize gap scores\n        if(ScoreMatrix::normalized)\n        {\n            globalOption.gap_open_metric = ScoreMatrix::score_to_dist(globalOption.gap_open, 1);\n            globalOption.gap_ext_metric = ScoreMatrix::score_to_dist(globalOption.gap_ext, 1);\n            shouldRecalcDist = true;\n        }\n    }\n\n    // load transition quantity matrix\n    if(globalOption.tmatrixName != \"\" && previous_tmatrix != globalOption.tmatrixName)\n    {\n        ScoreMatrix::loadTMatrix(fixFilePath(globalOption.tmatrixName));\n        previous_tmatrix = globalOption.tmatrixName;\n        shouldRecalcDist = true;\n    }\n\n    if(shouldRecalcDist)\n    {\n        ScoreMatrix::calcDistTQplusDiffTable(globalOption);\n    }\n\n    // --- DEBUG ---\n#ifdef DEBUG\n    putLog(\"::setOption():\");\n    putLog(\"score metric matrix (amatrix):\");\n    ScoreMatrix::showScoreMatrix(ScoreMatrix::amatrix);\n    putLog(\"score metric matrix (pmatrix):\");\n    ScoreMatrix::showScoreMatrix(ScoreMatrix::pmatrix);\n    putLog(\"gap open = \" + DS(globalOption.gap_open));\n    putLog(\"gap ext  = \" + DS(globalOption.gap_ext));\n    putLog(\"gap open metric = \" + DS(globalOption.gap_open_metric));\n    putLog(\"gap ext  metric = \" + DS(globalOption.gap_ext_metric));\n    putLog(\"beta = \" + DS(globalOption.beta));\n    putLog(\"betaTQ = \" + DS(globalOption.betaTQ));\n    putLog(\"exp(beta * gap open) = \" + DS(exp(globalOption.beta * globalOption.gap_open)));\n    putLog(\"exp(beta * gap ext)  = \" + DS(exp(globalOption.beta * globalOption.gap_ext)));\n    putLog(\"exp(-beta * gap open) = \" + DS(exp(-globalOption.beta * globalOption.gap_open_metric)));\n    putLog(\"exp(-beta * gap ext)  = \" + DS(exp(-globalOption.beta * globalOption.gap_ext_metric)));\n    putLog(\"TRANS_A=\" + DS(ScoreMatrix::TRANS_A));\n    putLog(\"TRANS_B=\" + DS(ScoreMatrix::TRANS_B));\n#endif\n}\n\n/* Profile version of Multiple Sequence Alignment\n* outFile == \"\" の時は標準出力にアライメントを出力する\n* profileは２次元配列を１次元で管理したもの．サイズは(seq1len+1)*(seq2len+1)．また，profile[i][0]=profile[0][j]=0である．\n* sparseMatrixはprofileの２次元管理版．０に近い成分は切り捨てたもの\n* TODO: ペアワイズアライメント時はProfileを生成せずに直接アライメントを出力し高速化をすべき\n*/\nvoid runMSA(const string& inFile, const string& outFile)\n{\n    clock_t t1, t2, t3, t4;\n    t1 = clock();\n\n    // --- read the input sequences ---\n    const Sequences* pInputSeqs = new Sequences(inFile, true);\n    const int numSeqs = pInputSeqs->seqs.size();\n\n    // --- translate protein coding DNA sequence to AAs\n    const Sequences* pCDSSeqs = ((globalOption.CDSMode) ? pInputSeqs->genTranslatedSeqs(globalOption.CDS_type) : NULL);\n    if(globalOption.CDSMode) putLog(\"CDS translated.\");\n\n    const Sequences& refSeqs = ((pCDSSeqs != NULL) ? *pCDSSeqs : *pInputSeqs);\n\n    // --- generate the sparse profiles and distances ---\n    // 右上三角成分のみ利用(numSeqs*(numSeqs-1)/2だけ余分にメモリを確保している)\n    //putLog(\"generate the sparse profiles and distances\");\n    VVPROFILE distances(numSeqs, VPROFILE(numSeqs, PROFILE_ZERO));\n    VVpSM sparseProfiles(numSeqs, VpSM(numSeqs, (SparseMatrix*)NULL));\n\n    // --- estimate family ---\n    if(globalOption.familyEstimation)\n    {\n        string fmatrixName = globalOption.smatrixName;\n        VS estimatedGroups;\n        const string mostFamousGroup = ScoreMatrix::estimateGroups(estimatedGroups, refSeqs, true);\n        if(mostFamousGroup != \"\")\n        {\n            fmatrixName = fixFilePath(globalOption.fmatrixDir + \"/\" + mostFamousGroup + \".mat\");\n            putLog(\"family is estimated. use family specific matrix [\" + fmatrixName + \"]\");\n        }else{\n            putLog(\"family is not estimated. use default matrix [\" + fmatrixName + \"]\");\n        }\n\n        // --- load family specific matrix ---\n        const string old_smatrix = globalOption.smatrixName;\n        globalOption.smatrixName = fmatrixName;\n        setMatrixConfiguration();\n        globalOption.smatrixName = old_smatrix;\n    }\n\n    // --- output the parameters ---\n//    putLog(\"=== ALIGNMENT PARAMETERS ===\");\n//    putLog(\"-gap_open = \" + DS(globalOption.gap_open) + \"(\" + DS(globalOption.gap_open_metric) + \")\");\n//    putLog(\"-gap_ext  = \" + DS(globalOption.gap_ext) + \"(\" + DS(globalOption.gap_ext_metric) + \")\");\n//    putLog(\"\");\n\n    // --- Open MP ---\n#ifdef _OPENMP\n    globalOption.numProfilePairs = numSeqs * (numSeqs - 1) / 2;\n    globalOption.profilePairs = new pair<int,int>[globalOption.numProfilePairs];\n    int pairIndex = 0;\n    for(int i=0; i<numSeqs-1; i++)\n    {\n        for(int j=i+1; j<numSeqs; j++)\n        {\n            globalOption.profilePairs[pairIndex].first = i;\n            globalOption.profilePairs[pairIndex].second = j;\n            pairIndex++;\n        }\n    }\n#endif\n#ifdef _OPENMP\n#pragma omp parallel for private(pairIndex) default(shared) schedule(dynamic)\n    for(pairIndex=0; pairIndex<globalOption.numProfilePairs; pairIndex++)\n    {\n        int i = globalOption.profilePairs[pairIndex].first;\n        int j = globalOption.profilePairs[pairIndex].second;\n#else\n    for (int i=0; i<numSeqs-1; i++)\n    {\n        for (int j=i+1; j<numSeqs; j++)\n        {\n#endif\n            VPROFILE* profile_mtrap(NULL);\n            VPROFILE* profile_postprob(NULL);\n\n            string& seq1 = *(refSeqs.seqs[i]);\n            string& seq2 = *(refSeqs.seqs[j]);\n            string& name1 = *(refSeqs.names[i]);\n            string& name2 = *(refSeqs.names[j]);\n            // --- compute profile and distance ---\n            // MTRAP\n            AlignerMTRAP aligner_mtrap(&name1, &seq1, &name2, &seq2, &globalOption);\n            PROFILE_TYPE distance_mtrap = aligner_mtrap.calcPathMatrix();\n            profile_mtrap = aligner_mtrap.genProfile();\n\n            // MTRAP with partition function\n            if(fabs(globalOption.mtrap_degree - 1.0) > 1.0e-10)\n            {\n#ifdef USE_PROBALIGN\n                // Probalign\n                Probalign aligner_probalign;\n                profile_postprob = aligner_probalign.genProfile(&seq1, &seq2);\n#else\n                // Transition quantity with partition function posterior probability\n                // To use beta2=0.0 is similar to Probalign\n                profile_postprob = aligner_mtrap.genPartProfile();\n#endif\n            }\n\n#ifdef DEBUG\n            aligner_mtrap.showPathMatrix();\n            string* dAlignStr = aligner_mtrap.genAlignment();\n            putLog(\"alignment: \" + *dAlignStr);\n            delete dAlignStr;\n            putLog(\"profile (mtrap):\");\n            showProfile(profile_mtrap, seq1.size(), seq2.size());\n            if(fabs(globalOption.mtrap_degree - 1.0) > 1.0e-10)\n            {\n                putLog(\"profile (postprob):\");\n                showProfile(profile_postprob, seq1.size(), seq2.size());\n            }\n#endif\n            // --- combine all profiles and generate the sparse profile ---\n            if(fabs(globalOption.mtrap_degree - 1.0) > 1.0e-10)\n            {\n                VPROFILE::iterator ptr_mtrap = profile_mtrap->begin();\n                VPROFILE::iterator ptr_postprob = profile_postprob->begin();\n                // TODO: Eigenにマップして合成すれば高速化になるはず\n                for(size_t ii=0; ii<seq1.size(); ii++)\n                {\n                    for(size_t jj=0; jj<seq2.size(); jj++)\n                    {\n                        *ptr_mtrap = globalOption.mtrap_degree * (*ptr_mtrap) + (1.0 - globalOption.mtrap_degree) * (*ptr_postprob);\n                        ptr_mtrap++;\n                        ptr_postprob++;\n                    }\n                }\n            }\n\n            // consider the size of prefix '@'\n            sparseProfiles[i][j] = new SparseMatrix(seq1.size()-1, seq2.size()-1, *profile_mtrap);\n            // --- set the distance ---\n            distances[i][j] = distance_mtrap;\n            // --- finalize ---\n            delete profile_mtrap;\n            if(fabs(globalOption.mtrap_degree - 1.0) > 1.0e-10)\n            {\n                delete profile_postprob;\n            }\n#ifndef _OPENMP\n        }\n#endif\n    }\n\n    // --- create the guide tree ---\n    t2 = clock();\n#ifdef DEBUG\n    putLog(\"create the guide tree\");\n#endif\n    tr_node* pGuideTree = genTreeUPGMA(distances);\n#ifdef DEBUG\n    putLog(pGuideTree->toString());\n#endif\n    // --- calculate the sequeces weights ---\n#ifdef DEBUG\n    putLog(\"calculate the sequences weights\");\n#endif\n    VPROFILE seqsWeights(numSeqs);\n    pGuideTree->setClustalWeight(seqsWeights);\n#ifdef DEBUG\n    for(size_t i=0; i<seqsWeights.size(); i++) putLog(\"weight of leaf\" + binary2string<int>(i) + \"=\" + binary2string<double>(seqsWeights[i]));\n#endif\n\n    // --- perform the consistency transformation ---\n#ifdef DEBUG\n    putLog(\"perform the consistency tranformation\");\n#endif\n    for (int r=0; r<globalOption.numConsistencyReps; r++)\n    {\n#ifdef DEBUG\n        putLog(\"consistency transform \" + IS(r+1) + \".\");\n#endif\n        doConsistencyTrans(seqsWeights, &refSeqs, sparseProfiles);\n    }\n\n    // --- compute the final multiple alignment ---\n    t3 = clock();\n    //putLog(\"compute the final multiple alignment\");\n    Sequences* finalAlignment = genFinalAlignment(pGuideTree, &refSeqs, sparseProfiles, &seqsWeights, globalOption);\n\n    // --- output ---\n    // console\n    //finalAlignment->output(std::cout, ((globalOption.CDSMode) ? const_cast<Sequences*>(pInputSeqs) : NULL));\n    // file\n    if(outFile != \"\")\n    {\n        ofstream ofs(outFile.c_str());\n        finalAlignment->output(ofs, ((globalOption.CDSMode) ? const_cast<Sequences*>(pInputSeqs) : NULL));\n        ofs.close();\n    }\n\n    // --- finalize ---\n    for (int i=0; i<numSeqs-1; i++)\n    {\n        for (int j=i+1; j<numSeqs; j++)\n        {\n            delete sparseProfiles[i][j];\n        }\n    }\n\n    delete pInputSeqs;\n    delete pCDSSeqs;\n    delete pGuideTree;\n\n    delete finalAlignment;\n\n#ifdef _OPENMP\n    delete [] globalOption.profilePairs;\n#endif\n\n    t4 = clock();\n    cerr << \"generate the profiles  :\" << (double)(t2 - t1) / CLOCKS_PER_SEC << endl;\n    cerr << \"generate the guide tree:\" << (double)(t3 - t2) / CLOCKS_PER_SEC << endl;\n    cerr << \"iterative refinements  :\" << (double)(t4 - t3) / CLOCKS_PER_SEC << endl;\n    cerr << \"all                    :\" << (double)(t4 - t1) / CLOCKS_PER_SEC << endl;\n}\n\n\nint main(int argc, char **argv)\n{\n    // === INITIALIZE ===\n#ifdef _OPENMP\n    Eigen::initParallel();\n    Eigen::setNbThreads(0);\n#endif\n\n    initFileSearchDir();\n    ScoreMatrix::init();\n    setOption(argc, argv, 0);\n\n    // === OPTION ===\n    if(setOption(argc, argv, 1) > 0)\n    {\n        printHelp();\n        return 1;\n    }\n\n    // === OUTPUT THE INPUT PARAMETERS ===\n    putLog(\"=== SEARCH DIRS ===\");\n    for(VS::iterator i=fileSearchDirList.begin(); i!=fileSearchDirList.end(); ++i) putLog(*i);\n    putLog(\"\");\n\n    if(globalOption.searchMode)\n    {\n        cout << \"query: \" << globalOption.inputFilenameList.at(0) << endl;\n        cout << \"database: \" << globalOption.inputFilenameList.at(1) << endl;\n        cout << \"output: \" << globalOption.outputFilenameList.at(0) << endl;\n        search(globalOption.inputFilenameList.at(0), globalOption.inputFilenameList.at(1), globalOption.outputFilenameList.at(0));\n    }else if(globalOption.search_allPairMode){\n        cout << \"database: \" << globalOption.inputFilenameList.at(0) << endl;\n        cout << \"output: \" << globalOption.outputFilenameList.at(0) << endl;\n        search_allPair(globalOption.inputFilenameList.at(0), globalOption.outputFilenameList.at(0));\n    }else if(globalOption.primaryLibraryMode){\n        cout << \"database: \" << globalOption.inputFilenameList.at(0) << endl;\n        cout << \"output: \" << globalOption.outputFilenameList.at(0) << endl;\n        makePrimaryLibrary(globalOption.inputFilenameList.at(0), globalOption.outputFilenameList.at(0));\n    }else if(globalOption.countMode){\n        cout << \"database: \" << globalOption.inputFilenameList.at(0) << endl;\n        cout << \"sequence weight: \" << globalOption.inputFilenameList.at(1) << endl;\n        cout << \"output: \" << globalOption.outputFilenameList.at(0) << endl;\n        ScoreMatrix::generateMatrix(globalOption.inputFilenameList.at(0), globalOption.inputFilenameList.at(1), globalOption.outputFilenameList.at(0));\n    }else if(globalOption.binoutMode){\n        cout << \"generate binary format Transition-quantity matrix.\" << endl;\n        ScoreMatrix::outputBinaryTQ( globalOption.outputFilenameList.at(0) );\n    }else{\n        for(int i=0; i<(int)globalOption.inputFilenameList.size(); i++)\n        {\n#ifdef _OPENMP\n            //set OpenMP to use dynamic number of threads which is equal to the number of processor cores on the host\n            //omp_set_num_threads(2);\n            cerr << \"OpenMP : Enabled (Max # of threads = \" << omp_get_max_threads() << \")\" << endl;\n#endif\n            runMSA(globalOption.inputFilenameList.at(i), globalOption.outputFilenameList.at(i));\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "d12b4e150168ed107eb4bda7d3ab9c0df57f4c2e", "size": 31245, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mtrap.cpp", "max_stars_repo_name": "toshihr/mtrap", "max_stars_repo_head_hexsha": "e6001ef79c89bbb7c5b731fe6ade4659add5d1ea", "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/mtrap.cpp", "max_issues_repo_name": "toshihr/mtrap", "max_issues_repo_head_hexsha": "e6001ef79c89bbb7c5b731fe6ade4659add5d1ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mtrap.cpp", "max_forks_repo_name": "toshihr/mtrap", "max_forks_repo_head_hexsha": "e6001ef79c89bbb7c5b731fe6ade4659add5d1ea", "max_forks_repo_licenses": ["BSD-3-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.3841059603, "max_line_length": 175, "alphanum_fraction": 0.5982717235, "num_tokens": 7953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.022977371708082953, "lm_q1q2_score": 0.00892942117748086}}
{"text": "/*\nCopyright (c) 2013-2018,  Los Alamos National Security, LLC (LANS)\nand the University Corporation for Atmospheric Research (UCAR).\n\nUnless noted otherwise source code is licensed under the BSD license.\nAdditional copyright and license information can be found in the LICENSE file\ndistributed with this code, or at http://mpas-dev.github.com/license.html\n*/\n\n// ===================================================\n//! Includes\n// ===================================================\n//#include <boost/program_options.hpp>\n#include <cstring>\n#include <vector>\n#include <mpi.h>\n#include <list>\n#include <iostream>\n#include <fstream>\n#include <unistd.h>\n#include <fcntl.h>\n#include <limits>\n#include <cmath>\n#include <map>\n\n#ifndef MPASLI_EXTERNAL_INTERFACE_DISABLE_MANGLING\n#define velocity_solver_init_mpi velocity_solver_init_mpi_\n#define velocity_solver_finalize velocity_solver_finalize_\n#define velocity_solver_init_l1l2 velocity_solver_init_l1l2_\n#define velocity_solver_solve_l1l2 velocity_solver_solve_l1l2_\n#define velocity_solver_init_fo velocity_solver_init_fo_\n#define velocity_solver_solve_fo velocity_solver_solve_fo_\n#define velocity_solver_init_stokes velocity_solver_init_stokes_\n#define velocity_solver_solve_stokes velocity_solver_solve_stokes_\n#define velocity_solver_compute_2d_grid velocity_solver_compute_2d_grid_\n#define velocity_solver_set_grid_data velocity_solver_set_grid_data_\n#define velocity_solver_extrude_3d_grid velocity_solver_extrude_3d_grid_\n#define velocity_solver_export_l1l2_velocity velocity_solver_export_l1l2_velocity_\n#define velocity_solver_export_2d_data velocity_solver_export_2d_data_\n#define velocity_solver_export_fo_velocity velocity_solver_export_fo_velocity_\n#define velocity_solver_estimate_SS_SMB velocity_solver_estimate_ss_smb_\n#define interface_init_log interface_init_log_\n#define interface_redirect_stdout interface_redirect_stdout_\n#define interface_reset_stdout interface_reset_stdout_\n#define write_ascii_mesh write_ascii_mesh_\n#endif\n\n//#include <lifev/core/algorithm/PreconditionerIfpack.hpp>\n//#include <lifev/core/algorithm/PreconditionerML.hpp>\n\n//#include <lifev/ice_sheet/solver/IceProblem.hpp>\n\nstruct exchange {\n  const int procID;\n  const std::vector<int> vec;\n  mutable std::vector<int> buffer;\n  mutable std::vector<double> doubleBuffer;\n  mutable MPI_Request reqID;\n\n  exchange(int _procID, int const* vec_first, int const* vec_last,\n      int fieldDim = 1);\n};\n\ntypedef std::list<exchange> exchangeList_Type;\n\ntypedef unsigned int ID;\ntypedef unsigned int UInt;\nconst ID NotAnId = std::numeric_limits<int>::max();\n\n// ===================================================\n//! Interface function\n// ===================================================\nextern \"C\" {\n\nint velocity_solver_init_mpi(int* fComm);\n\nvoid velocity_solver_finalize();\n\nvoid velocity_solver_set_parameters(double const* gravity_F, double const* ice_density_F, double const* ocean_density_F,\n                        double const* sea_level_F, double const* flowParamA_F,\n                        double const* flowLawExponent_F, double const* dynamic_thickness_F,\n                        double const* clausius_clapeyron_coeff,\n                        int const* li_mask_ValueDynamicIce, int const* li_mask_ValueIce,\n                        bool const* use_GLP_F);\n\nvoid velocity_solver_init_l1l2(double const* levelsRatio);\n\nvoid velocity_solver_init_fo(double const* levelsRatio);\n\nvoid velocity_solver_solve_l1l2(double const* lowerSurface_F,\n    double const* thickness_F, double const* beta_F, double const* temperature_F,\n    double* const dirichletVelocityXValue = 0, double* const dirichletVelocitYValue = 0,\n    double* u_normal_F = 0,\n    double* xVelocityOnCell = 0, double* yVelocityOnCell = 0);\n\nvoid velocity_solver_solve_fo(double const* bedTopography_F, double const* lowerSurface_F,\n    double const* thickness_F, double const* beta_F, double const* smb_F, double const* temperature_F, double const* stiffnessFactor_F,\n    double const* effecPress_F,\n    double* const dirichletVelocityXValue = 0, double* const dirichletVelocitYValue = 0,\n    double* u_normal_F = 0, double* dissipation_heat_F = 0,\n    double* xVelocityOnCell = 0, double* yVelocityOnCell = 0, double const * deltat = 0,\n    int *error = 0 );\n\n\nvoid velocity_solver_compute_2d_grid(int const* verticesMask_F, int const* _cellsMask_F, int const* dirichletNodesMask_F, int const* floatingEdgeMask_F);\n\nvoid velocity_solver_set_grid_data(int const* _nCells_F, int const* _nEdges_F,\n    int const* _nVertices_F, int const* _nLayers, int const* _nCellsSolve_F,\n    int const* _nEdgesSolve_F, int const* _nVerticesSolve_F,\n    int const* _maxNEdgesOnCell_F, double const* radius_F,\n    int const* _cellsOnEdge_F, int const* _cellsOnVertex_F,\n    int const* _verticesOnCell_F, int const* _verticesOnEdge_F,\n    int const* _edgesOnCell_F, int const* _nEdgesOnCells_F,\n    int const* _indexToCellID_F,\n    double const* _xCell_F, double const* _yCell_F, double const* _zCell_F,\n    double const* _xVertex_F, double const* _yVertex_F, double const* _zVertex_F,\n    double const* _areaTriangle_F,\n    int const* sendCellsArray_F, int const* recvCellsArray_F,\n    int const* sendEdgesArray_F, int const* recvEdgesArray_F,\n    int const* sendVerticesArray_F, int const* recvVerticesArray_F);\n\nvoid velocity_solver_extrude_3d_grid(double const* levelsRatio_F,\n    double const* lowerSurface_F, double const* thickness_F);\n\nvoid velocity_solver_export_l1l2_velocity();\n\nvoid velocity_solver_export_fo_velocity();\n\n//void velocity_solver_estimate_SS_SMB (const double* u_normal_F, double* sfcMassBal);\n\nvoid interface_init_log();\n\nvoid interface_redirect_stdout(int const* iTimestep);\n\nvoid interface_reset_stdout();\n\nvoid write_ascii_mesh(int const* indexToCellID_F,\n    double const* bedTopography_F, double const* lowerSurface_F,\n    double const* beta_F, double const* temperature_F,\n    double const* stiffnessFactor_F,\n    double const* effecPress_F,\n    double const* thickness_F, double const* thicknessUncertainty_F,\n    double const* smb_F, double const* smbUncertainty_F,\n    double const* bmb_F, double const* bmbUncertainty_F,\n    double const* observedSurfaceVelocityX_F, double const* observedSurfaceVelocityY_F,\n    double const* observedVelocityUncertainty_F, \n    double const* observedThicknessTendency_F, double const * observedThicknessTendencyUncertainty_F);\n\n} // extern \"C\"\n\nextern int velocity_solver_init_mpi__(int* fComm);\nextern void velocity_solver_finalize__();\n\n#ifdef LIFEV\nextern void velocity_solver_init_l1l2__(const std::vector<double>& layersRatio, const std::vector<double>& velocityOnVertices, bool initialize_velocity);\n\nextern void velocity_solver_solve_l1l2__(const std::vector<double>& elevationData,\n    const std::vector<double>& thicknessData, const std::vector<double>& betaData,\n    const std::vector<double>& temperatureData, const std::vector<int>& indexToVertexID,\n    std::vector<double>& velocityOnVertices);\n\nextern void velocity_solver_init_fo__(const std::vector<double>& layersRatio, const std::vector<double>& velocityOnVertices, const std::vector<int>& indexToVertexID, bool initialize_velocity);\n\nextern void velocity_solver_export_l1l2_velocity__(const std::vector<double>& layersRatio, const std::vector<double>& elevationData, const std::vector<double>& regulThk,\n    const std::vector<int>& mpasIndexToVertexID, MPI_Comm reducedComm);\n\n#endif\n\nextern void velocity_solver_set_physical_parameters__(double const& gravity, double const& ice_density, double const& ocean_density, double const& sea_level, double const& flowParamA, \n                        double const& flowLawExponent, double const& dynamic_thickness, bool const& useGLP, double const& clausiusClapeyronCoeff); \n\nextern void velocity_solver_solve_fo__(int nLayers, int nGlobalVertices,\n    int nGlobalTriangles, bool ordering, bool first_time_step,\n    const std::vector<int>& indexToVertexID,\n    const std::vector<int>& indexToTriangleID, double minBeta,\n    const std::vector<double>& regulThk,\n    const std::vector<double>& levelsNormalizedThickness,\n    const std::vector<double>& elevationData,\n    const std::vector<double>& thicknessData,\n    const std::vector<double>& betaData,\n    const std::vector<double>& bedTopographyData,\n    const std::vector<double>& smbData,\n    const std::vector<double>& stiffnessFactorData,\n    const std::vector<double>& effecPressData,\n    const std::vector<double>& temperatureOnTetra,\n    std::vector<double>& dissipationHeatOnTetra,\n    std::vector<double>& velocityOnVertices,\n    int& error,\n    const double& deltat = 0.0);\n\n\n#ifdef LIFEV\nextern void velocity_solver_compute_2d_grid__(int nGlobalTriangles,\n     int nGlobalVertices, int nGlobalEdges,\n     const std::vector<int>& indexToVertexID,\n     const std::vector<double>& verticesCoords,\n     const std::vector<bool>& isVertexBoundary,\n     const std::vector<int>& verticesOnTria,\n     const std::vector<bool>& isBoundaryEdge,\n     const std::vector<int>& trianglesOnEdge,\n     const std::vector<int>& trianglesPositionsOnEdge,\n     const std::vector<int>& verticesOnEdge,\n     const std::vector<int>& indexToEdgeID,\n     const std::vector<int>& indexToTriangleID,\n     const std::vector < std::pair<int, int> >& procOnInterfaceEdge);\n\n#else\nextern void velocity_solver_compute_2d_grid__(MPI_Comm);\n#endif\n\n\nextern void velocity_solver_export_2d_data__(MPI_Comm reducedComm,\n    const std::vector<double>& elevationData,\n    const std::vector<double>& thicknessData,\n    const std::vector<double>& betaData,\n    const std::vector<int>& indexToVertexID);\n\nextern void velocity_solver_extrude_3d_grid__(int nLayers, int nGlobalTriangles,\n    int nGlobalVertices, int nGlobalEdges, int Ordering, MPI_Comm reducedComm,\n    const std::vector<int>& indexToVertexID,\n    const std::vector<int>& mpasIndexToVertexID,\n    const std::vector<double>& verticesCoords,\n    const std::vector<bool>& isVertexBoundary,\n    const std::vector<int>& verticesOnTria,\n    const std::vector<bool>& isBoundaryEdge,\n    const std::vector<int>& trianglesOnEdge,\n    const std::vector<int>& trianglesPositionsOnEdge,\n    const std::vector<int>& verticesOnEdge,\n    const std::vector<int>& indexToEdgeID,\n    const std::vector<int>& indexToTriangleID,\n    const std::vector<int>& dirichletNodes,\n    const std::vector<int>&floatingEdges);\n\n//extern void velocity_solver_export_l1l2_velocity__();\n\nextern void velocity_solver_export_fo_velocity__(MPI_Comm reducedComm);\n\n\n#ifdef LIFEV\nextern int  velocity_solver_initialize_iceProblem__(bool keep_proc, MPI_Comm reducedComm);\n#endif\n\n//extern void velocity_solver_estimate_SS_SMB__ (const double* u_normal_F, double* sfcMassBal);\n\nexchangeList_Type unpackMpiArray(int const* array);\n\nbool isGhostTriangle(int i, double relTol = 1e-1);\n\ndouble signedTriangleArea(const double* x, const double* y);\n\ndouble signedTriangleArea(const double* x, const double* y, const double* z);\n\nvoid createReducedMPI(int nLocalEntities, MPI_Comm& reduced_comm_id);\n\nvoid import2DFields(std::map<int, int> bdExtensionMap, double const* bedTopography_F, double const* lowerSurface_F, double const* thickness_F,\n    double const* beta_F = 0, double const* stiffnessFactor_F = 0, double const* effecPress_F = 0, double const* temperature_F = 0, double const* smb_F = 0, double eps = 0);\n\nvoid import2DFieldsObservations(std::map<int, int> bdExtensionMap,\n            double const * lowerSurface_F, \n            double const * thickness_F, double const * thicknessUncertainty_F,\n            double const * smbUncertainty_F,\n            double const * bmb_F, double const * bmbUncertainty_F,\n            double const * observedSurfaceVelocityX_F, double const * observedSurfaceVelocityY_F,\n            double const * observedSurfaceVelocityUncertainty_F,\n            double const * observedThicknessTendency_F, double const * observedThicknessTendencyUncertainty_F,\n            int const * indexToCellID_F);\n \nvoid write_ascii_mesh_field(std::vector<double> fieldData, std::string filenamebase);\n\nvoid write_ascii_mesh_field_int(std::vector<int> fieldData, std::string filenamebase);\n\nstd::vector<int> extendMaskByOneLayer(int const* verticesMask_F);\n\nvoid extendMaskByOneLayer(int const* verticesMask_F,\n    std::vector<int>& extendedFVerticesMask);\n\nvoid importP0Temperature();\n\nvoid exportDissipationHeat(double * dissipationHeat_F);\n\nvoid get_prism_velocity_on_FEdges(double* uNormal,\n    const std::vector<double>& velocityOnCells,\n    const std::vector<int>& edgeToFEdge);\n\nint initialize_iceProblem(int nTriangles);\n\nvoid createReverseCellsExchangeLists(exchangeList_Type& sendListReverse_F,\n    exchangeList_Type& receiveListReverse_F,\n    const std::vector<int>& fVertexToTriangleID,\n    const std::vector<int>& fCellToVertexID);\n\nvoid createReverseEdgesExchangeLists(exchangeList_Type& sendListReverse_F,\n    exchangeList_Type& receiveListReverse_F,\n    const std::vector<int>& fVertexToTriangleID,\n    const std::vector<int>& fEdgeToEdgeID);\n\nvoid mapCellsToVertices(const std::vector<double>& velocityOnCells,\n    std::vector<double>& velocityOnVertices, int fieldDim, int numLayers,\n    int ordering);\n\nvoid mapVerticesToCells(const std::vector<double>& velocityOnVertices,\n    double* velocityOnCells, int fieldDim, int numLayers, int ordering);\n\nvoid computeLocalOffset(int nLocalEntities, int& localOffset,\n    int& nGlobalEntities);\n\nvoid getProcIds(std::vector<int>& field, int const* recvArray);\n\nvoid getProcIds(std::vector<int>& field, exchangeList_Type const* recvList);\n\nvoid allToAll(std::vector<int>& field, int const* sendArray,\n    int const* recvArray, int fieldDim = 1);\n\nvoid allToAll(std::vector<int>& field, exchangeList_Type const* sendList,\n    exchangeList_Type const* recvList, int fieldDim = 1);\n\nvoid allToAll(double* field, exchangeList_Type const* sendList,\n    exchangeList_Type const* recvList, int fieldDim = 1);\n\nint prismType(long long int const* prismVertexMpasIds, int& minIndex);\nvoid tetrasFromPrismStructured (long long int const* prismVertexMpasIds, long long int const* prismVertexGIds, long long int tetrasIdsOnPrism[][4]);\nvoid computeMap();\n\nvoid setBdFacesOnPrism (const std::vector<std::vector<std::vector<int> > >& prismStruct, const std::vector<int>& prismFaceIds, std::vector<int>& tetraPos, std::vector<int>& facePos);\nvoid tetrasFromPrismStructured (int const* prismVertexMpasIds, int const* prismVertexGIds, int tetrasIdsOnPrism[][4]);\nvoid procsSharingVertex(const int vertex, std::vector<int>& procIds);\n\nbool belongToTria(double const* x, double const* t, double bcoords[3], double eps = 1e-3);\n\n\n\n", "meta": {"hexsha": "dbcf210bd8bce3652b7fe2eba1bd4b10f7375677", "size": 14608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/mpas-source/src/core_landice/mode_forward/Interface_velocity_solver.hpp", "max_stars_repo_name": "liranpeng/E3SM-2CRM", "max_stars_repo_head_hexsha": "a15f0430555f4da7cd7189e8513c48fb6d896f3c", "max_stars_repo_licenses": ["zlib-acknowledgement", "FTL", "RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "components/mpas-source/src/core_landice/mode_forward/Interface_velocity_solver.hpp", "max_issues_repo_name": "liranpeng/E3SM-2CRM", "max_issues_repo_head_hexsha": "a15f0430555f4da7cd7189e8513c48fb6d896f3c", "max_issues_repo_licenses": ["zlib-acknowledgement", "FTL", "RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "components/mpas-source/src/core_landice/mode_forward/Interface_velocity_solver.hpp", "max_forks_repo_name": "liranpeng/E3SM-2CRM", "max_forks_repo_head_hexsha": "a15f0430555f4da7cd7189e8513c48fb6d896f3c", "max_forks_repo_licenses": ["zlib-acknowledgement", "FTL", "RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0, "max_line_length": 192, "alphanum_fraction": 0.7678669222, "num_tokens": 3496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.017986207297244074, "lm_q1q2_score": 0.00892284645574761}}
{"text": "#include \"hyperquadtree.hpp\"\n//#include <boost/python.hpp>\n#include <algorithm>\n#include <iterator>\nnamespace gd {\n//using namespace boost::python;\n\nvoid py_export_schw_hyperquadtree() {\n\t//NTree<2, double> quadtree(1.,2.,4.,6.);\n\t/*class_<DFGrid, boost::noncopyable >(\"DFGrid\", init<int, int, double, double, Galaxy*>())\n\t\t.def(\"output_grid\", &DFGrid::output_grid) \n\t\t.def(\"n_dofs\", &DFGrid::n_dofs) \n\t\t.def(\"refine_global\", &DFGrid::refine_global)\n\t\t.def(\"shape_value\", &DFGrid::shape_value)\n\t\t.def(\"print_dof_indices_per_face\", &DFGrid::print_dof_indices_per_face)\n\t\t.def(\"print_dof_indices_per_face_on_level\", &DFGrid::print_dof_indices_per_face_on_level)\n\t\t.def(\"print_vertices\", &DFGrid::print_vertices)\n\t\t\t;*/\n}\n\n//template<size_t... Indices>\n//tuple<> get_indices(\n\nstruct DoSomething\n{\n    template<typename T>\n    void operator()(T& t) const\n    {\n        //t.do_sth();\n\t\t//printf(\"blaat\");\n    }\n};\n\nconst int gs_scale = 300;\n\n// this makes gcc happy\ntemplate<size_t N, typename... Tail>\nstruct action;\n\n/*template<int A, int B>\nstruct static_min {\n\tenum { value = A < B : A ? B };\n};*/\ntemplate<int N>\nstruct gridder {\n\ttemplate<class Tree, class P>\n\tvoid grid(Tree *tree, ofstream& f, P p1, P p2, int *gridsizes) {\n\t\tcout << \"Error: gridding not implemented for N = \" << N << endl;\n\t}\n};\n\ntemplate<>\nstruct gridder<2>\n{\n\ttemplate<class Tree, class P>\n\tvoid grid(Tree *tree, ofstream& f, P p1, P p2, int *gridsizes) {\n\t\tdouble x1 = get<0>(p1);\n\t\tdouble x2 = get<0>(p2);\n\t\tdouble y1 = get<1>(p1);\n\t\tdouble y2 = get<1>(p2);\n\t\tcout << \"x range\" << x1 << \" - \" << x2 << endl;\n\t\tcout << \"y range\" << y1 << \" - \" << y2 << endl;\n\t\tf << \"[\";\n\t\tfor(int xi = 0; xi < gridsizes[0]; xi++) {\n\t\t\tdouble x = x1 + xi * (x2-x1) / (gridsizes[0]-1);\n\t\t\tf << \"[\";\n\t\t\tfor(int yi = 0; yi < gridsizes[1]; yi++) {\n\t\t\t\tdouble y = y1 + yi * (y2-y1) / (gridsizes[1]-1);\n\t\t\t\t//cout << \"x,y\" << x << \"\\t\" << y << \"\\t\" << tree->eval(x, y) << endl;\n\t\t\t\t//cout << \"x,y\" << x << \"\\t\" << y << \"\\t\" << tree->eval(x, y) << endl;\n\t\t\t\tf << tree->eval(x, y) << \",\";\n\t\t\t}\n\t\t\tf << \"],\";\n\t\t\t//cout << endl;\n\t\t}\n\t\tf << \"]\";\n\t\tf.close();\n\t}\n};\ntemplate<>\nstruct gridder<3>\n{\n\ttemplate<class Tree, class P>\n\tvoid grid(Tree *tree, ofstream& f, P p1, P p2, int *gridsizes) {\n\t\tdouble x1 = get<0>(p1);\n\t\tdouble x2 = get<0>(p2);\n\t\tdouble y1 = get<1>(p1);\n\t\tdouble y2 = get<1>(p2);\n\t\tdouble z1 = get<2>(p1);\n\t\tdouble z2 = get<2>(p2);\n\t\tcout << \"x range\" << x1 << \" - \" << x2 << endl;\n\t\tcout << \"y range\" << y1 << \" - \" << y2 << endl;\n\t\tcout << \"z range\" << z1 << \" - \" << z2 << endl;\n\t\tf << \"[\";\n\t\tfor(int xi = 0; xi < gridsizes[0]; xi++) {\n\t\t\tf << \"[\";\n\t\t\tdouble x = x1 + xi * (x2-x1) / (gridsizes[0]-1);\n\t\t\tfor(int yi = 0; yi < gridsizes[1]; yi++) {\n\t\t\t\tf << \"[\";\n\t\t\t\tdouble y = y1 + yi * (y2-y1) / (gridsizes[1]-1);\n\t\t\t\tfor(int zi = 0; zi < gridsizes[2]; zi++) {\n\t\t\t\t\tdouble z = z1 + zi * (z2-z1) / (gridsizes[2]-1);\n\t\t\t\t\t//cout << \"x,y\" << x << \"\\t\" << y << \"\\t\" << tree->eval(x, y) << endl;\n\t\t\t\t\t//cout << \"x,y\" << x << \"\\t\" << y << \"\\t\" << tree->eval(x, y) << endl;\n\t\t\t\t\tf << tree->eval(x, y, z) << \",\";\n\t\t\t\t}\n\t\t\t\tf << \"],\";\n\t\t\t}\n\t\t\t//cout << endl;\n\t\t\tf << \"],\";\n\t\t}\n\t\tf << \"]\";\n\t\tf.close();\n\t}\n};\n\ntemplate<size_t N, typename T, typename... Tail>\nstruct action<N, T, Tail...>  {\n\ttypedef NTree<N, T, T, Tail...> HTree;\n\ttypedef typename HTree::Point Point;\n\ttypedef action<N-1, Tail...> sub_action_type;\n\tint dim;\n\tsub_action_type sub_action;\n\tHTree* tree;\n\tPoint p1, p2;\n\n\taction(int dim) : dim(dim), sub_action(dim), tree(NULL) {}\n\tvoid init(int subdivides, string name) {\n\t\t//QuadTree::Point p1(0.0,0.0);\t\t\n\t\tif(N == dim) {\n\t\t\ttree = new HTree(p1, p2);\n\t\t\t//cout << \"output: \" << name << endl;\n\t\t\twhile(subdivides--) tree->rootNode.split();\n\t\t\t//tree->output(name);\n\t\t\t//tree.output_unknown(name);\n\t\t\t//tree->output_ps((name+\".ps\").c_str(), gs_scale, gs_scale);\n\t\t}\n\t\telse if(N >= 1) {\n\t\t\tsub_action.init(subdivides, name);\n\t\t}\n\t}\n\tvoid optimize(double absfraction=0.2, double relfraction=0.05, int Nabsmin=1, int Nrelmin=0, int maxlevel=8, int max_level_difference=0) {\n\t\tif(N == dim) {\n\t\t\tdouble error = 0;\n\t\t\tcout << \"integral is: \" << tree->integrate(error) << endl;\n\t\t\tcout << \"error    is: \" << error << endl;\n\t\t\ttree->optimize(absfraction, relfraction, Nabsmin, Nrelmin, maxlevel, max_level_difference);\n\t\t} else {\n\t\t\tsub_action.optimize(absfraction, relfraction, Nabsmin, Nrelmin, maxlevel, max_level_difference);\n\t\t}\n\t}\n\tvoid limit_level_difference(int max_level_difference) {\n\t\tif(N == dim) {\n\t\t\t//double error = 0;\n\t\t\ttree->limit_level_difference(max_level_difference);\n\t\t} else {\n\t\t\tsub_action.limit_level_difference(max_level_difference);\n\t\t}\n\t} \n\tvoid read(string inputname) {\n\t\tif(N == dim) {\n\t\t\tifstream f;\n\t\t\tstring filename_state = inputname + \".state\";\n\t\t\tf.open(filename_state.c_str());\n\t\t\tcout << \"reading from: \" << filename_state << endl; \n\t\t\tif(!f.is_open())\n\t\t\t\tthrow runtime_error((string(\"file doesn't exists: \") + filename_state));\n\t\t\t\n\t\t\t//Point p1, p2;\n\t\t\tf >> p1 >> p2;\n\t\t\tcout << p1 << \", \" << p2 << endl;\n\n\t\t\tvector<bool> splits;\n\t\t\tcopy(istream_iterator<bool>(f), istream_iterator<bool>(), back_inserter(splits));\n\t\t\t//copy(splits.begin(), splits.end(), ostream_iterator<bool>(cout, \" \"));\n\t\t\tcout << \"size: \" << splits.size() << endl;\n\t\t\t\n\t\t\t//HTree tree(p1, p2);\n\t\t\ttree = new HTree(p1, p2);\n\t\t\tauto b = splits.begin();\n\t\t\ttree->rootNode.split(&b);\n\t\t\tassert(b == splits.end());\n\t\t\ttree->readpoints(inputname+\".known\");\n\t\t\ttree->readpoints(inputname+\".solved\");\n\t\t\t/*tree.output_ps((outputname+\".check.ps\").c_str(), gs_scale, gs_scale);\n\t\t\ttree.readpoints(inputname+\".known\");\n\t\t\ttree.readpoints(inputname+\".solved\");\n\t\t\tdouble error = 0;\n\t\t\tcout << \"integral is: \" << tree.integrate(error) << endl;\n\t\t\tcout << \"error    is: \" << error << endl;\n\t\t\ttree.optimize(0.0, 0.0, 10, 0);\n\t\t\ttree.output(outputname);\n\t\t\ttree.output_ps((outputname+\".ps\").c_str(), gs_scale, gs_scale);*/\n\n\t\t} else if(N >= 1) {\n\t\t\tsub_action.read(inputname);\n\t\t}\n\t}\n\tvoid write(string filename) {\n\t\tif(N == dim) {\n\t\t\ttree->output(filename);\n\t\t\ttree->output_ps((filename+\".eps\").c_str(), gs_scale, gs_scale);\n\t\t}\n\t\telse if(N >= 1) {\n\t\t\tsub_action.write(filename);\n\t\t}\n\t}\n\tvoid grid(string name, int* gridsizes) {\n\t\tif(N == dim) {\n\t\t\tofstream f;\n\t\t\tstring filename = name+\".grid\";\n\t\t\tf.open(filename);\n\t\t\tcout << \"output filename: \" << filename << endl;\n\t\t\tgridder<N> g;\n\t\t\tg.grid(tree, f, p1, p2, gridsizes);\n\t\t}\n\t\telse if(N >= 1) {\n\t\t\tsub_action.grid(name, gridsizes);\n\t\t}\n\t}\n\tvoid set_point1(T value, int point_dim) {\n\t\tif(N == dim) {\n\t\t\tdo_tuple(p1, point_dim, [&](T& tuple_ref, bool last) { tuple_ref = value;} ); \n\t\t}\n\t\telse if(N >= 1) {\n\t\t\tsub_action.set_point1(value, point_dim);\n\t\t}\n\t}\n\tvoid set_point2(T value, int point_dim) {\n\t\tif(N == dim) {\n\t\t\tdo_tuple(p2, point_dim, [&](T& tuple_ref, bool last) { tuple_ref = value;} ); \n\t\t}\n\t\telse if(N >= 1) {\n\t\t\tsub_action.set_point2(value, point_dim);\n\t\t}\n\t}\n\t\n}; \ntemplate<typename T>\nstruct action<1, T> {\n\taction(int dim) {}\n\t\n\tvoid set_point1(T value, int point_dim) {\n\t}\n\tvoid set_point2(T value, int point_dim) {\n\t}\n\tvoid init(int subdivides, string name) {\n\t}\n\tvoid read(string inputname) {\n\t}\n\tvoid write(string inputname) {\n\t}\n\tvoid optimize(double absfraction=0.2, double relfraction=0.05, int Nabsmin=1, int Nrelmin=0, int maxlevel=8, int max_level_difference=0) {}\n\tvoid grid(string name, int* gridsizes) {}\n\tvoid limit_level_difference(int max_level_difference) {\n\t} \n};\n\n\n#include <unistd.h>\n#include <getopt.h>\n\nint option_do_init = 0;\nint option_do_help = 0;\noption options[] = {\n\t{\"init\", no_argument, 0, 'i'},\n\t{\"grid\", no_argument, 0, 'g'},\n\t{\"initialize\", no_argument, 0, 'i'},\n\t{\"optimize\", no_argument, 0, 't'},\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"dimension\", required_argument, 0, 'd'},\n\t{\"limit-level-difference\", required_argument, 0, 'l'},\n\t{\"subdivides\", required_argument, 0, 's'},\n\t{\"output\", required_argument, 0, 'o'},\n\t{\"input\", optional_argument, 0, 'n'},\n\t{0}\n};\n\nextern \"C\" int main(int argc, char* const * argv) {\n\t//tuple<double, double, double> t(1,2,3);\n\t//tuple<double, double> t2 = get_indices<1,2>(t);\n\t//tuple<double, double> t(1,2);\n\t//std::cout << *boost::fusion::begin(t) << '\\n';\n\n\t//boost::fusion::for_each(t, DoSomething());\n\t//return 0;\n\n\t/*cout << \"test: \" << log(0) << endl;\n\tcout << \"test: \" << exp(log(0)) << endl;\n\tcout << \"test: \" << isinf(log(0)) << endl;\n\tcout << \"test: \" << (log(0) < 0) << endl;\n\tcout << \"test: \" << save_exp(log(0)) << endl;*/\n\tint indexptr;\n\tint c;\n\tint dim = 0;\n\tint subdivides = 0;\n\tint max_level_difference = 0;\n\tbool init = false;\n\tbool optimize = false;\n\tbool do_grid = false;\n\t//bool do_limit_level_difference = false;\n\tstring outputname;\n\tstring inputname;\n\twhile((c = getopt_long(argc, argv, \"gn:o:ihd:s:tl:\", &options[0], &indexptr)) != -1) {\n\t\tswitch(c) {\n\t\t\tcase 0:\n\t\t\t\tprintf(\"long option: %s\", options[indexptr].name);\n\t\t\t\tif(optarg)\n\t\t\t\t\tprintf(\"with arg: %s\", optarg);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\tprintf(\"usage: %s -d <dim> [options]\\n\", argv[0]);\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tprintf(\"initialize\\n\");\n\t\t\t\tinit = true;\n\t\t\t\tbreak;\n\t\t\tcase 'g':\n\t\t\t\tprintf(\"grid\\n\");\n\t\t\t\tdo_grid = true;\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tdim = atoi(optarg);\n\t\t\t\tprintf(\"dimension: %i\\n\", dim);\n\t\t\t\tbreak;\n\t\t\tcase 'l':\n\t\t\t\tmax_level_difference = atoi(optarg);\n\t\t\t\tprintf(\"maximum limit difference: %i\\n\", max_level_difference);\n\t\t\t\t//do_limit_level_difference = true;\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\toutputname = string(optarg);\n\t\t\t\tprintf(\"output: %s\\n\", outputname.c_str());\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\tinputname = string(optarg);\n\t\t\t\tprintf(\"input: %s\\n\", inputname.c_str());\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\toptimize = true;\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tif(optarg == NULL) {\n\t\t\t\t\tfprintf(stderr, \"subdivides requires int argument\\n\");\n\t\t\t\t\texit(-1);\n\t\t\t\t}\n\t\t\t\tsubdivides = atoi(optarg);\n\t\t\t\tprintf(\"subdivide: %d\\n\", subdivides);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tabort();\n\t\t}\n\t}\n\n\ttypedef action<5, double, double, double, double, double> action_highest_type;\n\taction_highest_type action_highest(dim);\n\tif(init) {\n\t\tfor (int i = optind; i < argc; i++) {\n\t\t\tint index = i - optind; // 0 based index\n\t\t\tif(index >= dim) {\n\t\t\t\t//printf (\"do %s\\n\", argv[i]);\n\t\t\t\tdouble value = atof(argv[i]);\n\t\t\t\taction_highest.set_point2(value, index-dim);\n\t\t\t} else {\n\t\t\t\t//printf (\"do %s\\n\", argv[i]);\n\t\t\t\tdouble value = atof(argv[i]);\n\t\t\t\taction_highest.set_point1(value, index);\n\t\t\t}\n\t\t}\n\t\t/*cout << \"p1 \" << action_init_highest.p1 << endl; \n\t\tcout << \"p2 \" << action_init_highest.p2 << endl;\n\t\tcout << \"p1 \" << action_init_highest.sub_action.p1 << endl; \n\t\tcout << \"p2 \" << action_init_highest.sub_action.p2 << endl;\n\t\tcout << \"p1s \" << tuple_size<typename action_init_highest_type::Point>::value << endl;*/ \n\t\t//action_init_highest.subdivide(dim, outputname);\n\t\taction_highest.init(subdivides, outputname);\n\t\taction_highest.write(outputname);\n\t}\n\tif(optimize) {\n\t\tif((argc-optind) != 5) {\n\t\t\tfprintf(stderr, \"please give optimization parameters\\n\");\n\t\t\texit(2);\n\t\t}\n\t\tdouble absfraction=atof(argv[optind+0]);\n\t\tdouble relfraction=atof(argv[optind+1]);\n\t\tint Nabsmin=atoi(argv[optind+2]);\n\t\tint Nrelmin=atoi(argv[optind+3]);\n\t\tint maxlevel=atoi(argv[optind+4]);\n\t\tcout << \"absfraction, relfraction, Nabsmin, Nrelmin\" << absfraction << \",\" <<  relfraction << \",\" <<  Nabsmin << \",\" << Nrelmin << endl;\n\t\taction_highest.read(inputname);\n\t\taction_highest.optimize(absfraction, relfraction, Nabsmin, Nrelmin, maxlevel, max_level_difference);\n\t\t/*if(do_limit_level_difference) {\n\t\t\taction_highest.limit_level_difference(max_level_difference);\n\t\t}*/\n\t\taction_highest.write(outputname);\n\t}\n\tif(do_grid) {\n\t\tcout << \"starting gridding...\" << endl;\n\t\taction_highest.read(inputname);\n\t\tcout << \"starting gridding...\" << endl;\n\t\tif((argc-optind) != dim) {\n\t\t\tfprintf(stderr, \"please give gridsize with proper dimension\\n\");\n\t\t\texit(2);\n\t\t}\n\t\tcout << \"starting gridding...\" << endl;\n\t\tint * gridsizes = new int[argc-optind];\n\t\tfor (int i = optind; i < argc; i++) {\n\t\t\tint index = i - optind; // 0 based index\n\t\t\tgridsizes[index] = atoi(argv[i]);\n\t\t\tprintf (\"gridsizes[%d] = %d\\n\", index, gridsizes[index]);\n\t\t}\n\t\tcout << \"starting gridding...\" << endl;\n\t\taction_highest.grid(inputname, gridsizes);\n\t\tdelete gridsizes;\n\t\t//action_init_highest.do_grid(dim, subdivides, inputname, outputname);\n\t}\n\n\n\treturn 0;\n\n\tint count = atoi(argv[1]);\n\tdouble absfraction = atof(argv[2]);\n\tint Nabsmin = atoi(argv[3]);\n\tdouble relfraction = atof(argv[4]);\n\tint Nrelmin = atoi(argv[5]);\n\tcout << \"Nabsmin: \" << Nabsmin << endl;\n\tdouble error = 0;\n\t//int optimize = atoi(argv[6]);\n\tNLinear<1, 2, double> linear(3., 2.);\n\tNLinear<1, 2, double> linear2(4., 6.);\n\tNLinear<2, 2, double> bilinear(linear, linear2);\n\tcout << \"integral \" << linear.integrate() << \", \" << linear.integrate(0., 1., 0., 1.) << endl;\n\tcout << \"integral \" << linear2.integrate() << \", \" << linear2.integrate(0., 1., 0., 1.)  << endl;\n\tcout << \"integral \" << linear2.integrate(0., 1.0) << endl;\n\tcout << \"integral \" << bilinear.integrate() << endl;\n\tcout << \"integral \" << bilinear.integrate(0., 1., 0., 1.) << endl;\n\tcout << \"integral \" << bilinear.integrate(0., 0.5, 0., 0.5) << endl;\n\tcout << \"integral \" << bilinear.integrate2(0., 0.5, 0., 1., 0., 0.5, 0., 1.0) << endl;\n\tcout << \"integral \" << bilinear.integrate2(0.5, 3., 4., 10., 1., 5., 3., 8.0) << endl;\n\t//cout << \"integral \" << bilinear.integrate2(1., 5., 3., 8.0, 0.5, 3., 4., 10.) << endl;\n\ttypedef NTree<2, double, double, double> QuadTree;\n\ttypedef NTree<3, double, double, double, double> OcTree;\n\tQuadTree::Point p1(0.0,0.0);\n\tQuadTree::Point p2(14.0, 14.);\n\tset<QuadTree::Point> s;\n\ts.insert(p1);\n\ts.insert(p1);\n\ts.insert(p2);\n\tQuadTree quadtree(p1, p2);\n\tOcTree::Point v1(0.0,0.0,0.0);\n\tOcTree::Point v2(14.0,14.0,14.0);\n\tOcTree octree(v1, v2);\n\t//quadtree.add_point(0., 1.);\n\t//quadtree.rootNode.printinfo();\n\t/*quadtree.rootNode.walkrange([](double x1, double x2, double y1, double y2) {\n\t\tcout << \"quad x:[\" << x1 << \",\" << x2 << \"]\" << \" y:[\" << y1 << \",\" << y2 << \"]\" << endl;\n\t});\n\tquadtree.rootNode.walk([](double x, double y, double value) {\n\t\tcout << \"point x:[\" << x << \"]\" << \" y:[\" << y << \"] value:\"  << value << endl;\n\t});\n\tquadtree.rootNode.eval([](double x, double y) {\n\t\treturn x*y;\n\t});\n\tquadtree.rootNode.walk([](double x, double y, double value) {\n\t\tcout << \"point x:[\" << x << \"]\" << \" y:[\" << y << \"] value:\"  << value << endl;\n\t});*/\n\t/*for_each(quadtree.points.begin(), quadtree.points.end(), [](QuadTree::Point p) {\n\t\tcout << \"p x:[\" << get<0>(p) << \"]\" << \" y:[\" << get<1>(p) << \"]\" << endl;\n\t});*/\n\tcout << \"split\" << endl;\n\tfflush(stdout);\n\tcout << \"octree: # vertices: \" << octree.points.size() << endl;\n\toctree.rootNode.split();\n\t//octree.rootNode.split();\n\tcout << \"octree: # vertices: \" << octree.points.size() << endl;\n\tcout << \"quadtree: # vertices: \" << quadtree.points.size() << endl;\n\tquadtree.rootNode.split();\n\tcout << \"quadtree: # vertices: \" << quadtree.points.size() << endl;\n\t\n\t//octree.rootNode.split();\n\t//quadtree.rootNode.split();\n\toctree.eval([](OcTree::Point p) {\n\t\tdouble x = get<0>(p);\n\t\tdouble y = get<1>(p);\n\t\tdouble z = get<2>(p);\n\t\treturn exp(-0.5*( pow(x-2,2) + pow(y-2, 2) + pow(z-9,2)) ) * 1./(2*M_PI); \n\t});\n\n\tquadtree.eval([](QuadTree::Point p) {\n\t\tdouble x = get<0>(p);\n\t\tdouble y = get<1>(p);\n\t\treturn \n\t\t\texp(-0.5*( pow(x-2,2) + pow(y-2, 2) ) ) * 1./(2*M_PI);// + \n\t\t\t//exp(-0.5*( pow(x-8,2) + pow(y-8, 2) ) ) * 1./(2*M_PI); \n\t});\n\tcout << \"integrated: \" << quadtree.integrate(error) << endl;\n\t//cout << \"integrated(oc): \" << octree.integrate() << endl;\n\tfor(int i = 0; i < count; i++) {\n\t\t//quadtree.rootNode.split();\n\t\tif(optimize) {\n\t\t\tquadtree.optimize(absfraction, relfraction, Nabsmin, Nrelmin);\n\t\t\toctree.optimize(absfraction, relfraction, Nabsmin, Nrelmin);\n\t\t}\n\t\telse {\n\t\t\tquadtree.rootNode.split();\n\t\t\toctree.rootNode.split();\n\t\t}\n\t\tquadtree.eval([](QuadTree::Point p) {\n\t\t\tdouble x = get<0>(p);\n\t\t\tdouble y = get<1>(p);\n\t\t\treturn \n\t\t\t\texp(-0.5*( pow(x-2,2) + pow(y-2, 2) ) ) * 1./(2*M_PI);// + \n\t\t\t\t//exp(-0.5*( pow(x-8,2) + pow(y-8, 2) ) ) * 1./(2*M_PI); \n\t\t});\n\t\toctree.eval([](OcTree::Point p) {\n\t\t\tdouble x = get<0>(p);\n\t\t\tdouble y = get<1>(p);\n\t\t\tdouble z = get<2>(p);\n\t\t\treturn exp(-0.5*( pow(x-2,2) + pow(y-2, 2) + pow(z-9,2)) ) * 1./(2*M_PI); \n\t\t});\n\t\terror = 0.;\n\t\tcout << \"# of points: \" << quadtree.points.size() << endl;\n\t\tcout << \"integrated: \" << quadtree.integrate(error);\n\t\tcout << \" error = \" << error << endl;\n\t\terror = 0.;\n\t\tcout << \"# of points(oc): \" << octree.points.size() << endl;\n\t\tcout << \"integrated(oc): \" << octree.integrate(error);\n\t\tcout << \" error = \" << error << endl;\n\t}\n/*\n\tquadtree.rootNode.split();\n\tquadtree.rootNode.left.subleft->split();\n\tquadtree.rootNode.left.subleft->right.subright->split();\n\tquadtree.rootNode.left.subleft->right.subright->left.subleft->split();\n\tquadtree.rootNode.left.subleft->right.subright->left.subleft->right.subright->split();\n\tquadtree.rootNode.split();*/\n/*quadtree.rootNode.walk([](double x, double y, double value) {\n\t\tcout << \"point x:[\" << x << \"]\" << \" y:[\" << y << \"] value:\"  << value << endl;\n\t});*/\n\t/*for_each(quadtree.points.begin(), quadtree.points.end(), [](QuadTree::Point p) {\n\t\tcout << \"p x:[\" << get<0>(p) << \"]\" << \" y:[\" << get<1>(p) << \"]\" << endl;\n\t});*/\n\tquadtree.output_ps(\"quadtree.ps\", 30., 30., 1.);\n\tquadtree.output_gpl(\"quadtree.gpl\", 30., 30., 1.);\n\toctree.output_ps<0,1>(\"octree_xy.ps\", 30., 30., 1.);\n\toctree.output_ps<0,2>(\"octree_xz.ps\", 30., 30., 1.);\n\tquadtree.output(\"quadtree.ntree\");\n\t/*cout << \"size: \" << quadtree.points.size() << endl;\n\tquadtree.rootNode.split();\n\tcout << \"size: \" << quadtree.points.size() << endl;\n\tquadtree.rootNode.split();\n\tcout << \"size: \" << quadtree.points.size() << endl;*/\n\t//quadtree.rootNode.left.split()\n}\n\n};", "meta": {"hexsha": "a9b89523a9cb2cc50be68eb6bfb36cbc0985c899", "size": 17722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/hyperquadtree.cpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/hyperquadtree.cpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/hyperquadtree.cpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8168761221, "max_line_length": 140, "alphanum_fraction": 0.5940074484, "num_tokens": 5863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388515, "lm_q2_score": 0.020023442276298795, "lm_q1q2_score": 0.008921035222082546}}
{"text": "/*\n * MIT License\n * \n * Copyright (c) 2015 Alexis LE GOADEC\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 * Définition de l'algorithme décidant la connexité d'un hypergraphe.\n */\n#ifndef ALGORITHM_INCLUDE_CONNECTED_HH_\n#define ALGORITHM_INCLUDE_CONNECTED_HH_\n\n#include \"../model/HypergrapheAbstrait.hh\"\n#include \"../model/AlgorithmeAbstrait.hh\"\n\n#include <boost/shared_ptr.hpp>\n#include <stack>\n#include <vector>\n\n/**\n * Algorithme décidant la connexité d'un hypergraphe.\n */\nclass Connected : public AlgorithmeAbstrait {\n\npublic:\n\n\t/**\n\t * Constructeur.\n\t * @param boost::shared_ptr<HypergrapheAbstrait> Pointeur partagé vers l'hypergraphe.\n\t */\n\tConnected(boost::shared_ptr<HypergrapheAbstrait>&);\n\n\t/**\n\t * Obtenir la structure de résultats.\n\t */\n\tRStructure getResult() const;\n\n\t/**\n\t * Destructeur.\n\t */\n\t~Connected();\n\n\nprotected:\n\n\t/**\n\t * Fonction de lancement de l'algorithme.\n\t */\n\tvoid runAlgorithme();\n\n\t/**\n\t * Exploration verticale d'un chemin de la matrice.\n\t * @param Vecteur des visités.\n\t * @param Pile des \"à visiter\".\n\t * @param Identifiant de la ligne.\n\t */\n\tvoid exploreVertical(std::vector<unsigned int>&, std::stack<unsigned int>&, unsigned int);\n\n\t/**\n\t * Exploration horizontale d'un chemin dans la matrice.\n\t * @param Vecteur des visités.\n\t * @param Pile des \"à visiter\".\n\t * @param Identifiant de la colonne.\n\t */\n\tvoid exploreHorizontal(std::vector<unsigned int>&, std::stack<unsigned int>&, unsigned int);\n\n\t/**\n\t * Vérifier si un hyper-vertex a déjà été visité.\n\t * @param Vecteur des hyper-vertex visités.\n\t * @param Identifiant à vérifier.\n\t * @return True si déjà visité, False sinon.\n\t */\n\tbool isVertexVisited(std::vector<unsigned int>&, unsigned int) const;\n\n\t/**\n\t * Vérifier si une hyper-arête a déjà été visitée.\n\t * @param Vecteur des hyper-arêtes visités.\n\t * @param Identifiant à vérifier.\n\t * @return True si déjà visité, False sinon.\n\t */\n\tbool isEdgeVisited(std::vector<unsigned int>&, unsigned int) const;\n\n/*\n\n\tbool isPath(HyperVertex&, HyperVertex&) const;\n\n\tbool isVisited(std::vector<HyperEdge>&, const HyperEdge&) const;\n\n*/\n\n\nprotected:\n\n\t/**\n\t * Pointeur partagé vers l'hypergraphe.\n\t */\n\tboost::shared_ptr<HypergrapheAbstrait>\n\t_ptrHypergrapheAbstrait;\n\n\t/**\n\t * Structure de résultat.\n\t */\n\tRStructure _result;\n\n};\n\n\n#endif /* ALGORITHM_INCLUDE_CONNECTED_HH_ */\n", "meta": {"hexsha": "920f4e680779e6b8d585f995225bc146e99a0b5a", "size": 3364, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/Hypergraph/algorithm/Connected.hh", "max_stars_repo_name": "ehzawad/HyperGraphLib", "max_stars_repo_head_hexsha": "a1424437a01ad5a9e0efa71d723d32fd58ca589c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2016-05-25T06:25:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T09:15:38.000Z", "max_issues_repo_path": "include/Hypergraph/algorithm/Connected.hh", "max_issues_repo_name": "ehzawad/HyperGraphLib", "max_issues_repo_head_hexsha": "a1424437a01ad5a9e0efa71d723d32fd58ca589c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-05-08T15:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T07:25:19.000Z", "max_forks_repo_path": "include/Hypergraph/algorithm/Connected.hh", "max_forks_repo_name": "ehzawad/HyperGraphLib", "max_forks_repo_head_hexsha": "a1424437a01ad5a9e0efa71d723d32fd58ca589c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-02-12T23:12:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T06:34:55.000Z", "avg_line_length": 26.28125, "max_line_length": 93, "alphanum_fraction": 0.7226516052, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.026355352559338546, "lm_q1q2_score": 0.00891014179922067}}
{"text": "// Copyright (c) 2014-2017, The Monero Project\n// Copyright (c) 2018-2019, The Scala Project\n// Copyright (c) 2017 The Masari Project(next_difficulty_v3)\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other\n//    materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    used to endorse or promote products derived from this software without specific\n//    prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers\n\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <cstdint>\n#include \"include_base_utils.h\"\n#include <vector>\n#include <boost/math/special_functions/round.hpp>\n#include <boost/algorithm/clamp.hpp>\n\n#include \"int-util.h\"\n#include \"crypto/hash.h\"\n#include \"cryptonote_config.h\"\n#include \"misc_language.h\"\n#include \"difficulty.h\"\n#include \"warnings.h\"\n\n#define MAX_AVERAGE_TIMESPAN          (uint64_t) DIFFICULTY_TARGET*6\n#define MIN_AVERAGE_TIMESPAN          (uint64_t) DIFFICULTY_TARGET/24\n\n#undef SCALA_DEFAULT_LOG_CATEGORY\n#define SCALA_DEFAULT_LOG_CATEGORY \"difficulty\"\n\nnamespace cryptonote {\n\nusing std::size_t;\nusing std::uint64_t;\nusing std::vector;\n\n#if defined(__x86_64__)\nstatic inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n    low = mul128(a, b, &high);\n}\n\n#else\n\nstatic inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n    // __int128 isn't part of the standard, so the previous function wasn't portable. mul128() in Windows is fine,\n    // but this portable function should be used elsewhere. Credit for this function goes to latexi95.\n\n    uint64_t aLow = a & 0xFFFFFFFF;\n    uint64_t aHigh = a >> 32;\n    uint64_t bLow = b & 0xFFFFFFFF;\n    uint64_t bHigh = b >> 32;\n\n    uint64_t res = aLow * bLow;\n    uint64_t lowRes1 = res & 0xFFFFFFFF;\n    uint64_t carry = res >> 32;\n\n    res = aHigh * bLow + carry;\n    uint64_t highResHigh1 = res >> 32;\n    uint64_t highResLow1 = res & 0xFFFFFFFF;\n\n    res = aLow * bHigh;\n    uint64_t lowRes2 = res & 0xFFFFFFFF;\n    carry = res >> 32;\n\n    res = aHigh * bHigh + carry;\n    uint64_t highResHigh2 = res >> 32;\n    uint64_t highResLow2 = res & 0xFFFFFFFF;\n\n    //Addition\n\n    uint64_t r = highResLow1 + lowRes2;\n    carry = r >> 32;\n    low = (r << 32) | lowRes1;\n    r = highResHigh1 + highResLow2 + carry;\n    uint64_t d3 = r & 0xFFFFFFFF;\n    carry = r >> 32;\n    r = highResHigh2 + carry;\n    high = d3 | (r << 32);\n}\n\n#endif\n\nstatic inline bool cadd(uint64_t a, uint64_t b) {\n    return a + b < a;\n}\n\nstatic inline bool cadc(uint64_t a, uint64_t b, bool c) {\n    return a + b < a || (c && a + b == (uint64_t) -1);\n}\n\nbool check_hash(const crypto::hash &hash, difficulty_type difficulty) {\n    uint64_t low, high, top, cur;\n    // First check the highest word, this will most likely fail for a random hash.\n    mul(swap64le(((const uint64_t *) &hash)[3]), difficulty, top, high);\n    if (high != 0) {\n        return false;\n    }\n    mul(swap64le(((const uint64_t *) &hash)[0]), difficulty, low, cur);\n    mul(swap64le(((const uint64_t *) &hash)[1]), difficulty, low, high);\n    bool carry = cadd(cur, low);\n    cur = high;\n    mul(swap64le(((const uint64_t *) &hash)[2]), difficulty, low, high);\n    carry = cadc(cur, low, carry);\n    carry = cadc(high, top, carry);\n    return !carry;\n}\n\ndifficulty_type next_difficulty(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {\n\n    if(timestamps.size() > DIFFICULTY_WINDOW)\n    {\n        timestamps.resize(DIFFICULTY_WINDOW);\n        cumulative_difficulties.resize(DIFFICULTY_WINDOW);\n    }\n\n\n    size_t length = timestamps.size();\n    assert(length == cumulative_difficulties.size());\n    if (length <= 1) {\n        return 1;\n    }\n    static_assert(DIFFICULTY_WINDOW >= 2, \"Window is too small\");\n    assert(length <= DIFFICULTY_WINDOW);\n    sort(timestamps.begin(), timestamps.end());\n    size_t cut_begin, cut_end;\n    static_assert(2 * DIFFICULTY_CUT <= DIFFICULTY_WINDOW - 2, \"Cut length is too large\");\n    if (length <= DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT) {\n        cut_begin = 0;\n        cut_end = length;\n    } else {\n        cut_begin = (length - (DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT) + 1) / 2;\n        cut_end = cut_begin + (DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT);\n    }\n    assert(/*cut_begin >= 0 &&*/ cut_begin + 2 <= cut_end && cut_end <= length);\n    uint64_t time_span = timestamps[cut_end - 1] - timestamps[cut_begin];\n    if (time_span == 0) {\n        time_span = 1;\n    }\n    difficulty_type total_work = cumulative_difficulties[cut_end - 1] - cumulative_difficulties[cut_begin];\n    assert(total_work > 0);\n    uint64_t low, high;\n    mul(total_work, target_seconds, low, high);\n    // blockchain errors \"difficulty overhead\" if this function returns zero.\n    // TODO: consider throwing an exception instead\n    if (high != 0 || low + time_span - 1 < low) {\n        return 0;\n    }\n    return (low + time_span - 1) / time_span;\n}\n\n//Was good but not as good as v3.\ndifficulty_type next_difficulty_v2(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {\n\n    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V2)\n    {\n        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V2);\n        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V2);\n    }\n\n    size_t length = timestamps.size();\n    assert(length == cumulative_difficulties.size());\n    if (length <= 1) {\n        return 1;\n    }\n\n    sort(timestamps.begin(), timestamps.end());\n    size_t cut_begin, cut_end;\n    static_assert(2 * DIFFICULTY_CUT_V2 <= DIFFICULTY_BLOCKS_COUNT_V2 - 2, \"Cut length is too large\");\n    if (length <= DIFFICULTY_BLOCKS_COUNT_V2 - 2 * DIFFICULTY_CUT_V2) {\n        cut_begin = 0;\n        cut_end = length;\n    }\n    else {\n        cut_begin = (length - (DIFFICULTY_BLOCKS_COUNT_V2 - 2 * DIFFICULTY_CUT_V2) + 1) / 2;\n        cut_end = cut_begin + (DIFFICULTY_BLOCKS_COUNT_V2 - 2 * DIFFICULTY_CUT_V2);\n    }\n    assert(/*cut_begin >= 0 &&*/ cut_begin + 2 <= cut_end && cut_end <= length);\n    uint64_t total_timespan = timestamps[cut_end - 1] - timestamps[cut_begin];\n    if (total_timespan == 0) {\n        total_timespan = 1;\n    }\n\n    uint64_t timespan_median = 0;\n    if (cut_begin > 0 && length >= cut_begin * 2 + 3) {\n        std::vector<std::uint64_t> time_spans;\n        for (size_t i = length - cut_begin * 2 - 3; i < length - 1; i++) {\n            uint64_t time_span = timestamps[i + 1] - timestamps[i];\n            if (time_span == 0) {\n                time_span = 1;\n            }\n            time_spans.push_back(time_span);\n\n            //LOG_PRINT_L3(\"Timespan \" << i << \": \" << (time_span / 60) / 60 << \":\" << (time_span > 3600 ? (time_span % 3600) / 60 : time_span / 60) << \":\" << time_span % 60 << \" (\" << time_span << \")\");\n        }\n        timespan_median = epee::misc_utils::median(time_spans);\n    }\n\n    uint64_t timespan_length = length - cut_begin * 2 - 1;\n    //LOG_PRINT_L2(\"Timespan Median: \" << timespan_median << \", Timespan Average: \" << total_timespan / timespan_length);\n\n    uint64_t total_timespan_median = timespan_median > 0 ? timespan_median * timespan_length : total_timespan * 7 / 10;\n    uint64_t adjusted_total_timespan = (total_timespan * 8 + total_timespan_median * 3) / 10; //  0.8A + 0.3M (the median of a poisson distribution is 70% of the mean, so 0.25A = 0.25/0.7 = 0.285M)\n    if (adjusted_total_timespan > MAX_AVERAGE_TIMESPAN * timespan_length) {\n        adjusted_total_timespan = MAX_AVERAGE_TIMESPAN * timespan_length;\n    }\n    if (adjusted_total_timespan < MIN_AVERAGE_TIMESPAN * timespan_length) {\n        adjusted_total_timespan = MIN_AVERAGE_TIMESPAN * timespan_length;\n    }\n\n    difficulty_type total_work = cumulative_difficulties[cut_end - 1] - cumulative_difficulties[cut_begin];\n    assert(total_work > 0);\n\n    uint64_t low, high;\n    mul(total_work, target_seconds, low, high);\n    if (high != 0) {\n        return 0;\n    }\n\n    uint64_t next_diff = (low + adjusted_total_timespan - 1) / adjusted_total_timespan;\n    if (next_diff < 1) next_diff = 1;\n    //LOG_PRINT_L2(\"Total timespan: \" << total_timespan << \", Adjusted total timespan: \" << adjusted_total_timespan << \", Total work: \" << total_work << \", Next diff: \" << next_diff << \", Hashrate (H/s): \" << next_diff / target_seconds);\n\n    return next_diff;\n}\n\ndifficulty_type next_difficulty_v3(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds, bool v4) {\n\n    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V3)\n    {\n        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V3);\n        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V3);\n    }\n\n    size_t length = timestamps.size();\n    assert(length == cumulative_difficulties.size());\n    if (length <= 1) {\n        return 1;\n    }\n\n    uint64_t weighted_timespans = 0;\n    uint64_t target;\n\n    if (true) {\n        uint64_t previous_max = timestamps[0];\n        for (size_t i = 1; i < length; i++) {\n            uint64_t timespan;\n            uint64_t max_timestamp;\n\n            if (timestamps[i] > previous_max) {\n                max_timestamp = timestamps[i];\n            } else {\n                max_timestamp = previous_max;\n            }\n\n            timespan = max_timestamp - previous_max;\n            if (timespan == 0) {\n                timespan = 1;\n            } else if (timespan > 10 * target_seconds) {\n                timespan = 10 * target_seconds;\n            }\n\n            weighted_timespans += i * timespan;\n            previous_max = max_timestamp;\n        }\n        // adjust = 0.99 for N=60, leaving the + 1 for now as it's not affecting N\n        target = 99 * (((length + 1) / 2) * target_seconds) / 100;\n    } else {\n        for (size_t i = 1; i < length; i++) {\n            uint64_t timespan;\n            if (timestamps[i - 1] >= timestamps[i]) {\n                timespan = 1;\n            } else {\n                timespan = timestamps[i] - timestamps[i - 1];\n            }\n            if (timespan > 10 * target_seconds) {\n                timespan = 10 * target_seconds;\n            }\n            weighted_timespans += i * timespan;\n        }\n        target = ((length + 1) / 2) * target_seconds;\n    }\n\n    uint64_t minimum_timespan = target_seconds * length / 2;\n    if (weighted_timespans < minimum_timespan) {\n        weighted_timespans = minimum_timespan;\n    }\n\n    difficulty_type total_work = cumulative_difficulties.back() - cumulative_difficulties.front();\n    assert(total_work > 0);\n\n    uint64_t low, high;\n    mul(total_work, target, low, high);\n\n    if (high != 0) {\n        return 0;\n    }\n    return low / weighted_timespans;\n}\n\n\n\ndifficulty_type next_difficulty_v4(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {\n\n    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V4)\n    {\n        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V4);\n        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V4);\n    }\n\n    size_t length_cumul_diff = cumulative_difficulties.size();\n    if(length_cumul_diff >= DIFFICULTY_BLOCKS_COUNT_V4 - 1) {\n        std::vector<difficulty_type> first_diffs;\n        std::vector<difficulty_type> mid_diffs;\n        std::vector<difficulty_type> last_diffs;\n        for (size_t i = 0; i < (DIFFICULTY_BLOCKS_COUNT_V4-30); i++) {\n            first_diffs.push_back(cumulative_difficulties[i]);\n        }\n        for (size_t i = (DIFFICULTY_BLOCKS_COUNT_V4-30); i < (DIFFICULTY_BLOCKS_COUNT_V4-10); i++) {\n            mid_diffs.push_back(cumulative_difficulties[i]);\n        }\n        for (size_t i = (DIFFICULTY_BLOCKS_COUNT_V4*-10); i < DIFFICULTY_BLOCKS_COUNT_V4; i++) {\n            last_diffs.push_back(cumulative_difficulties[i]);\n        }\n        difficulty_type median_first = epee::misc_utils::median(first_diffs);\n        difficulty_type median_mid = epee::misc_utils::median(mid_diffs);\n        difficulty_type median_last = epee::misc_utils::median(last_diffs);\n\n\n        if(median_first > (median_mid*6/5) && median_mid > (median_last*10/9))\n        {\n            timestamps.resize(25);\n            cumulative_difficulties.resize(25);\n        }\n        else if(median_mid > (median_first*6/5) && median_last > (median_mid*10/9)) {\n            timestamps.resize(25);\n            cumulative_difficulties.resize(25);\n        }\n\n    }\n\n    size_t length = timestamps.size();\n    assert(length == cumulative_difficulties.size());\n    if (length <= 1) {\n        return 1;\n    }\n\n\n    uint64_t weighted_timespans = 0;\n    uint64_t target;\n\n    int nbShortTsLastNBlocks = 0;\n    bool lastTimeWasShort=false;\n    int lastShortTimeInARaw = 0;\n\n    int nbLongTsLastNBlocks = 0;\n    //bool lastTimeWasLong=false;\n\n    if (true) {\n        uint64_t previous_max = timestamps[0];\n\n        for (size_t i = 1; i < length; i++) {\n            uint64_t timespan;\n            uint64_t max_timestamp;\n\n            if (timestamps[i] > previous_max) {\n                max_timestamp = timestamps[i];\n            } else {\n                max_timestamp = previous_max;\n            }\n\n            timespan = max_timestamp - previous_max;\n            if (timespan == 0) {\n                timespan = 1;\n            } else if (timespan > 11 * target_seconds) {\n                timespan = 11 * target_seconds;\n            }\n            if(i>=(length-7)) {\n                if(timespan < 30) {\n                    nbShortTsLastNBlocks ++;\n                    lastTimeWasShort = true;\n                    lastShortTimeInARaw ++;\n                } else {\n                    lastTimeWasShort = false;\n                    lastShortTimeInARaw=0;\n                }\n                if(timespan >100) {\n                    nbLongTsLastNBlocks ++;\n                    //lastTimeWasLong = true;\n                } else {\n                    //lastTimeWasLong = false;\n                }\n            }\n\n            weighted_timespans += i * timespan;\n            previous_max = max_timestamp;\n        }\n        // adjust faster if many blocks fount too fast\n\n        if(lastTimeWasShort) {\n            if(nbShortTsLastNBlocks >= 7) {\n                weighted_timespans = weighted_timespans *1/2;\n            } else if(nbShortTsLastNBlocks == 6) {\n                weighted_timespans = weighted_timespans *3/5;\n                if(lastShortTimeInARaw ==6) {\n                    weighted_timespans = weighted_timespans *7/8;\n                }\n            } else if(nbShortTsLastNBlocks == 5) {\n                weighted_timespans = weighted_timespans *4/5;\n                if(lastShortTimeInARaw ==5) {\n                    weighted_timespans = weighted_timespans *7/8;\n                }\n            } else if(nbShortTsLastNBlocks == 4) {\n                weighted_timespans = weighted_timespans *9/10;\n                if(lastShortTimeInARaw ==4) {\n                    weighted_timespans = weighted_timespans *7/8;\n                }\n            } else if(nbShortTsLastNBlocks == 3  ) {\n                weighted_timespans = weighted_timespans *11/12;\n                if(lastShortTimeInARaw ==3) {\n                    weighted_timespans = weighted_timespans *7/8;\n                }\n            }\n        }\n\n        // adjust = 0.99 for N=60, leaving the + 1 for now as it's not affecting N\n        target = 99 * (((length + 1) / 2) * target_seconds) / 100;\n    }\n\n    uint64_t minimum_timespan = target_seconds * length / 2;\n    if (weighted_timespans < minimum_timespan) {\n        weighted_timespans = minimum_timespan;\n    }\n\n    difficulty_type total_work = cumulative_difficulties.back() - cumulative_difficulties.front();\n    assert(total_work > 0);\n\n    uint64_t low, high;\n    mul(total_work, target, low, high);\n\n    if (high != 0) {\n\n        return 0;\n    }\n    return (low / weighted_timespans);\n}\n\ndifficulty_type next_difficulty_v5(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {\n\n    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V4)\n    {\n        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V4);\n        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V4);\n    }\n\n    size_t timestamp_count = timestamps.size();\n    assert(timestamp_count == cumulative_difficulties.size());\n    if (timestamp_count <= 1) {\n       return 1;\n    }\n\n    uint64_t prev_max_timestamp = timestamps[0];\n    uint64_t weighted_timespans = 0;\n    uint64_t target;\n\n    int short_time_count = 0;\n    bool last_was_short_time = false;\n\n    for (size_t i = 1; i < timestamp_count; i++) {\n\tuint64_t max_timestamp = std::max(prev_max_timestamp, timestamps[i]);\n        uint64_t timespan = boost::algorithm::clamp<uint64_t>(max_timestamp - prev_max_timestamp, 1, 11 * target_seconds);\n \tlast_was_short_time = false;\n\n        if (i >= (timestamp_count - 7)) {\n\t    if (timespan < 90) {\n                short_time_count++;\n                last_was_short_time = true;\n            }\n        }\n        weighted_timespans += i * timespan;\n \tprev_max_timestamp = max_timestamp;\n    }\n\n    // Adjust faster if many blocks found too fast\n    if (last_was_short_time) {\n\tswitch (short_time_count) {\n\t    case 7: weighted_timespans = weighted_timespans * 3 / 5; break;\n\t    case 6: weighted_timespans = weighted_timespans * 5 / 7; break;\n\t    case 5: weighted_timespans = weighted_timespans * 4 / 5; break;\n\t    case 4: weighted_timespans = weighted_timespans * 9 / 10; break;\n\t    case 3: weighted_timespans = weighted_timespans * 11 / 12; break;\n\t}\n    }\n\n    // adjust = 0.99 for N=60, leaving the + 1 for now as it's not affecting N\n    target = 99 * (((timestamp_count + 1) / 2) * target_seconds) / 100;\n\n    uint64_t minimum_timespan = target_seconds * timestamp_count / 2;\n    if (weighted_timespans < minimum_timespan) {\n        weighted_timespans = minimum_timespan;\n    }\n\n    difficulty_type total_work = cumulative_difficulties.back() - cumulative_difficulties.front();\n    assert(total_work > 0);\n\n    uint64_t low, high;\n    mul(total_work, target, low, high);\n\n    if (high != 0) {\n        return 0;\n    }\n    return (low / weighted_timespans);\n}\n}\n", "meta": {"hexsha": "a5c412b3caa38ca334c342dbd702bdf1edbefcfd", "size": 19450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_stars_repo_name": "blackrangersoftware/brs-scala", "max_stars_repo_head_hexsha": "d460e4f53a931e154869eb8f25873fbc3f8a2117", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_issues_repo_name": "blackrangersoftware/brs-scala", "max_issues_repo_head_hexsha": "d460e4f53a931e154869eb8f25873fbc3f8a2117", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_forks_repo_name": "blackrangersoftware/brs-scala", "max_forks_repo_head_hexsha": "d460e4f53a931e154869eb8f25873fbc3f8a2117", "max_forks_repo_licenses": ["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.2197392924, "max_line_length": 237, "alphanum_fraction": 0.633059126, "num_tokens": 5159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.026355351555604343, "lm_q1q2_score": 0.008910141108343251}}
{"text": "/*!\n * \\file bingocpp_pymodule.cc\n *\n * \\author Geoffrey F. Bomarito\n * \\date\n *\n * This file contains the python bindings of the BingoCpp library.\n * \n * Notices\n * -------\n * Copyright 2018 United States Government as represented by the Administrator of \n * the National Aeronautics and Space Administration. No copyright is claimed in \n * the United States under Title 17, U.S. Code. All Other Rights Reserved.\n *  \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, ANY \n * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR \n * FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR \n * FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE \n * 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, IF \n * PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT \"AS IS.\" \n * \n * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE \n * UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY \n * PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY \n * LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH USE, \n * INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE \n * OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED \n * STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR \n * RECIPIENT, TO THE EXTENT PERMITTED BY LAW.  RECIPIENT'S SOLE REMEDY FOR ANY \n * SUCH MATTER SHALL BE THE IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.\n */\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Dense> \n\n#include \"BingoCpp/agraph.h\"\n#include \"BingoCpp/backend.h\"\n#include \"BingoCpp/explicit_regression.h\"\n#include \"BingoCpp/implicit_regression.h\"\n#include \"BingoCpp/utils.h\"\n\n#include \"python/py_equation.h\"\n\nnamespace py = pybind11;\nusing namespace bingo;\n\nPYBIND11_MODULE(bingocpp, m) {\n  m.doc() = \"bingocpp module\";  // optional module docstring\n  m.def(\"is_cpp\", &backend::IsCpp, \"is the backend c++\");\n  m.def(\"evaluate\", &backend::Evaluate, \"evaluate\");\n  m.def(\"simplify_and_evaluate\", &backend::SimplifyAndEvaluate,\n        \"evaluate after simplification\");\n  m.def(\"evaluate_with_derivative\", &backend::EvaluateWithDerivative,\n        \"evaluate with derivative\");\n  m.def(\"simplify_and_evaluate_with_derivative\",\n        &backend::SimplifyAndEvaluateWithDerivative,\n        \"evaluate with derivative after simplification\");\n  m.def(\"get_utilized_commands\",\n        &backend::GetUtilizedCommands,\n        \"get the commands that are utilized in a stack\");\n  m.def(\"simplify_stack\", &backend::SimplifyStack,\n        \"simplify stack to only utilized commands\");\n\n  py::class_<Equation, PyEquation /* <---trampoline */>(m, \"Equation\")\n    .def(py::init<>())\n    .def(\"evaluate_equation_at\",\n         &Equation::EvaluateEquationAt)\n    .def(\"evaluate_equation_with_x_gradient_at\",\n         &Equation::EvaluateEquationWithXGradientAt)\n    .def(\"evaluate_equation_with_local_opt_gradient_at\",\n          &Equation::EvaluateEquationWithLocalOptGradientAt)\n    .def(\"get_latex_string\", &Equation::GetLatexString)\n    .def(\"get_stack_string\", &Equation::GetStackString)\n    .def(\"get_console_string\", &Equation::GetConsoleString)\n    .def(\"get_complexity\", &Equation::GetComplexity);\n\n  py::class_<AGraph, Equation>(m, \"AGraph\")\n    .def(py::init<bool & >(), py::arg(\"manual_constants\") = false)\n    .def(\"is_cpp\", &AGraph::IsCpp)\n    .def_property(\"command_array\",\n                  &AGraph::GetCommandArrayModifiable,\n                  &AGraph::SetCommandArray)\n    .def_property(\"fitness\",\n                  &AGraph::GetFitness,\n                  &AGraph::SetFitness)\n    .def_property(\"fit_set\",\n                  &AGraph::IsFitnessSet,\n                  &AGraph::SetFitness)\n    .def_property(\"genetic_age\",\n                  &AGraph::GetGeneticAge,\n                  &AGraph::SetGeneticAge)\n    .def_property(\"constants\",\n                  &AGraph::GetLocalOptimizationParamsModifiable,\n                  &AGraph::SetLocalOptimizationParams)\n    .def(\"notify_command_array_modification\",\n         &AGraph::NotifyCommandArrayModificiation)\n    .def(\"needs_local_optimization\", &AGraph::NeedsLocalOptimization)\n    .def(\"get_utilized_commands\", &AGraph::GetUtilizedCommands)\n    .def(\"get_number_local_optimization_params\",\n        &AGraph::GetNumberLocalOptimizationParams)\n    .def(\"get_local_optimization_params\",\n        &AGraph::GetLocalOptimizationParamsModifiable)\n    .def(\"set_local_optimization_params\", &AGraph::SetLocalOptimizationParams)\n    .def(\"evaluate_equation_at\", &AGraph::EvaluateEquationAt)\n    .def(\"evaluate_equation_with_x_gradient_at\",\n        &AGraph::EvaluateEquationWithXGradientAt)\n    .def(\"evaluate_equation_with_local_opt_gradient_at\",\n        &AGraph::EvaluateEquationWithLocalOptGradientAt)\n    .def(\"__str__\", &AGraph::GetConsoleString)\n    .def(\"get_latex_string\", &AGraph::GetLatexString)\n    .def(\"get_console_string\", &AGraph::GetConsoleString)\n    .def(\"get_stack_string\", &AGraph::GetStackString)\n    .def(\"get_complexity\", &AGraph::GetComplexity)\n    .def(\"distance\", &AGraph::Distance)\n    .def(\"copy\", &AGraph::Copy);\n  \n  py::class_<ImplicitTrainingData>(m, \"ImplicitTrainingData\")\n    .def(py::init<Eigen::ArrayXXd &>())\n    .def(py::init<Eigen::ArrayXXd &, Eigen::ArrayXXd &>())\n    .def_readwrite(\"x\", &ImplicitTrainingData::x)\n    .def_readwrite(\"dx_dt\", &ImplicitTrainingData::dx_dt)\n    .def(\"__getitem__\", \n         (ImplicitTrainingData *(ImplicitTrainingData::*)(int))\n         &ImplicitTrainingData::GetItem)\n    .def(\"__getitem__\",\n         (ImplicitTrainingData *(ImplicitTrainingData::*)(const std::vector<int>&))\n         &ImplicitTrainingData::GetItem)\n    .def(\"__len__\", &ImplicitTrainingData::Size);\n  \n  py::class_<ExplicitTrainingData>(m, \"ExplicitTrainingData\")\n    .def(py::init<Eigen::ArrayXXd &, Eigen::ArrayXXd&>())\n    .def_readwrite(\"x\", &ExplicitTrainingData::x)\n    .def_readwrite(\"y\", &ExplicitTrainingData::y)\n    .def(\"__getitem__\", \n         (ExplicitTrainingData *(ExplicitTrainingData::*)(int))\n         &ExplicitTrainingData::GetItem)\n    .def(\"__getitem__\",\n         (ExplicitTrainingData *(ExplicitTrainingData::*)(const std::vector<int>&))\n         &ExplicitTrainingData::GetItem)\n    .def(\"__len__\", &ExplicitTrainingData::Size);\n  \n  py::class_<ExplicitRegression>(m, \"ExplicitRegression\")\n    .def(py::init<ExplicitTrainingData *, std::string &>(),\n        py::arg(\"training_data\"),\n        py::arg(\"metric\")=\"mae\")\n    .def(\"__call__\", &ExplicitRegression::EvaluateIndividualFitness)\n    .def(\"evaluate_fitness_vector\", &ExplicitRegression::EvaluateFitnessVector);\n  \n  py::class_<ImplicitRegression>(m, \"ImplicitRegression\")\n    .def(py::init<ImplicitTrainingData *, int &, bool &, std::string &>(),\n         py::arg(\"training_data\"),\n         py::arg(\"required_params\") = -1,\n         py::arg(\"normalize_dot\") = false,\n         py::arg(\"metric\") = \"mae\")\n    .def(\"__call__\", &ImplicitRegression::EvaluateIndividualFitness)\n    .def(\"evaluate_fitness_vector\", &ImplicitRegression::EvaluateFitnessVector);\n\n  m.def(\"calculate_partials\", &CalculatePartials);\n  m.def(\"savitzky_golay\", &SavitzkyGolay);\n  m.def(\"gen_fact\", &GenFact);\n  m.def(\"gram_poly\", &GramPoly);\n  m.def(\"gram_weight\", &GramWeight);\n}", "meta": {"hexsha": "e1670b861b3674dda75506a6c2f4c3f48418cb01", "size": 7937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/bingocpp_pymodule.cpp", "max_stars_repo_name": "imikejackson/bingocpp", "max_stars_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T09:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T14:01:30.000Z", "max_issues_repo_path": "app/bingocpp_pymodule.cpp", "max_issues_repo_name": "imikejackson/bingocpp", "max_issues_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-29T19:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T22:17:53.000Z", "max_forks_repo_path": "app/bingocpp_pymodule.cpp", "max_forks_repo_name": "imikejackson/bingocpp", "max_forks_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-10-18T02:43:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T22:08:39.000Z", "avg_line_length": 45.3542857143, "max_line_length": 84, "alphanum_fraction": 0.704548318, "num_tokens": 2072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404563, "lm_q2_score": 0.04468087090869868, "lm_q1q2_score": 0.00890525492542185}}
{"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\n#include \"bempp/common/config_ahmed.hpp\"\n#include \"bempp/common/config_trilinos.hpp\"\n\n#include \"identity_operator.hpp\"\n\n#include \"ahmed_aux.hpp\"\n#include \"assembly_options.hpp\"\n#include \"boundary_operator.hpp\"\n#include \"cluster_construction_helper.hpp\"\n#include \"discrete_dense_boundary_operator.hpp\"\n#include \"discrete_sparse_boundary_operator.hpp\"\n#include \"context.hpp\"\n\n#include \"../common/types.hpp\"\n#include \"../fiber/basis.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/quadrature_strategy.hpp\"\n#include \"../fiber/local_assembler_for_operators.hpp\"\n#include \"../fiber/opencl_handler.hpp\"\n#include \"../fiber/raw_grid_geometry.hpp\"\n#include \"../fiber/scalar_function_value_functor.hpp\"\n#include \"../fiber/default_collection_of_basis_transformations.hpp\"\n#include \"../grid/entity_iterator.hpp\"\n#include \"../grid/geometry_factory.hpp\"\n#include \"../grid/grid.hpp\"\n#include \"../grid/grid_view.hpp\"\n#include \"../grid/mapper.hpp\"\n#include \"../space/space.hpp\"\n\n#include \"../common/boost_make_shared_fwd.hpp\"\n#include <boost/type_traits/is_complex.hpp>\n\n#include <tbb/tick_count.h>\n\n#include <stdexcept>\n#include <vector>\n\n#ifdef WITH_TRILINOS\n// This is a workaround of the problem of the abs() function being declared\n// both in Epetra and in AHMED. It relies of the implementation detail (!) that\n// in Epetra the declaration of abs is put between #ifndef __IBMCPP__ ...\n// #endif. So it may well break in future versions of Trilinos. The ideal\n// solution would be for AHMED to use namespaces.\n#ifndef __IBMCPP__\n#define __IBMCPP__\n#include <Epetra_FECrsMatrix.h>\n#include <Epetra_LocalMap.h>\n#include <Epetra_SerialComm.h>\n#undef __IBMCPP__\n#else\n#include <Epetra_FECrsMatrix.h>\n#include <Epetra_LocalMap.h>\n#include <Epetra_SerialComm.h>\n#endif\n#endif // WITH_TRILINOS\n\nnamespace Bempp\n{\n\n#ifdef WITH_TRILINOS\n// Internal helper functions for Epetra\nnamespace\n{\n\ntemplate <typename ValueType>\nint epetraSumIntoGlobalValues(Epetra_FECrsMatrix& matrix,\n                              const std::vector<int>& rowIndices,\n                              const std::vector<int>& colIndices,\n                              const arma::Mat<ValueType>& values);\n\n// Specialisation for double -- no intermediate array is needed\ntemplate <>\ninline int epetraSumIntoGlobalValues<double>(\n        Epetra_FECrsMatrix& matrix,\n        const std::vector<int>& rowIndices,\n        const std::vector<int>& colIndices,\n        const arma::Mat<double>& values)\n{\n    assert(rowIndices.size() == values.n_rows);\n    assert(colIndices.size() == values.n_cols);\n    return matrix.SumIntoGlobalValues(rowIndices.size(), &rowIndices[0],\n                                      colIndices.size(), &colIndices[0],\n                                      values.memptr(),\n                                      Epetra_FECrsMatrix::COLUMN_MAJOR);\n}\n\n// Specialisation for float\ntemplate <>\ninline int epetraSumIntoGlobalValues<float>(\n        Epetra_FECrsMatrix& matrix,\n        const std::vector<int>& rowIndices,\n        const std::vector<int>& colIndices,\n        const arma::Mat<float>& values)\n{\n    // Convert data from float into double (expected by Epetra)\n    arma::Mat<double> doubleValues(values.n_rows, values.n_cols);\n    std::copy(values.begin(), values.end(), doubleValues.begin());\n    return epetraSumIntoGlobalValues<double>(\n                matrix, rowIndices, colIndices, doubleValues);\n}\n\n// Specialisation for std::complex<float>.\n// WARNING: at present only the real part is taken into account!\n// This is sufficient as long as we provide real-valued basis functions only.\ntemplate <>\ninline int epetraSumIntoGlobalValues<std::complex<float> >(\n        Epetra_FECrsMatrix& matrix,\n        const std::vector<int>& rowIndices,\n        const std::vector<int>& colIndices,\n        const arma::Mat<std::complex<float> >& values)\n{\n    // Extract the real part of \"values\" into an array of type double\n    arma::Mat<double> doubleValues(values.n_rows, values.n_cols);\n    // Check whether arma::real returns a view or a copy (if the latter,\n    // this assert will fail)\n    for (size_t i = 0; i < values.n_elem; ++i)\n        doubleValues[i] = values[i].real();\n    return epetraSumIntoGlobalValues<double>(\n                matrix, rowIndices, colIndices, doubleValues);\n}\n\n// Specialisation for std::complex<double>.\n// WARNING: at present only the real part is taken into account!\n// This is sufficient as long as we provide real-valued basis functions only.\ntemplate <>\ninline int epetraSumIntoGlobalValues<std::complex<double> >(\n        Epetra_FECrsMatrix& matrix,\n        const std::vector<int>& rowIndices,\n        const std::vector<int>& colIndices,\n        const arma::Mat<std::complex<double> >& values)\n{\n    // Extract the real part of \"values\" into an array of type double\n    arma::Mat<double> doubleValues(values.n_rows, values.n_cols);\n    for (size_t i = 0; i < values.n_elem; ++i)\n        doubleValues[i] = values[i].real();\n    return epetraSumIntoGlobalValues<double>(\n                matrix, rowIndices, colIndices, doubleValues);\n}\n\n} // anonymous namespace\n#endif\n\n////////////////////////////////////////////////////////////////////////////////\n// IdentityOperatorId\n\ntemplate <typename BasisFunctionType, typename ResultType>\nIdentityOperatorId<BasisFunctionType, ResultType>::IdentityOperatorId(\n        const IdentityOperator<BasisFunctionType, ResultType>& op) :\n    m_domain(op.domain().get()), m_range(op.range().get()),\n    m_dualToRange(op.dualToRange().get())\n{\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nsize_t IdentityOperatorId<BasisFunctionType, ResultType>::hash() const\n{\n    typedef IdentityOperator<BasisFunctionType, ResultType>\n            OperatorType;\n    size_t result = tbb::tbb_hasher(typeid(OperatorType).name());\n    tbb_hash_combine(result, m_domain);\n    tbb_hash_combine(result, m_range);\n    tbb_hash_combine(result, m_dualToRange);\n    return result;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nbool IdentityOperatorId<BasisFunctionType, ResultType>::isEqual(\n        const AbstractBoundaryOperatorId &other) const\n{\n    // dynamic_cast won't suffice since we want to make sure both objects\n    // are of exactly the same type (dynamic_cast would succeed for a subclass)\n    if (typeid(other) == typeid(*this))\n    {\n        const IdentityOperatorId& otherCompatible =\n            static_cast<const IdentityOperatorId&>(other);\n        return (m_domain == otherCompatible.m_domain &&\n                m_range == otherCompatible.m_range &&\n                m_dualToRange == otherCompatible.m_dualToRange);\n    }\n    else\n        return false;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// IdentityOperator\n\n/** \\cond PRIVATE */\ntemplate <typename BasisFunctionType, typename ResultType>\nstruct IdentityOperator<BasisFunctionType, ResultType>::Impl\n{\n    typedef Fiber::ScalarFunctionValueFunctor<CoordinateType>\n    TransformationFunctor;\n\n    Impl() : transformations(TransformationFunctor())\n    {}\n\n    Fiber::DefaultCollectionOfBasisTransformations<TransformationFunctor>\n    transformations;\n};\n/** \\endcond */\n\ntemplate <typename BasisFunctionType, typename ResultType>\nIdentityOperator<BasisFunctionType, ResultType>::IdentityOperator(\n        const shared_ptr<const Space<BasisFunctionType> >& domain,\n        const shared_ptr<const Space<BasisFunctionType> >& range,\n        const shared_ptr<const Space<BasisFunctionType> >& dualToRange,\n        const std::string& label,\n        int symmetry) :\n    Base(domain, range, dualToRange, label,\n         (symmetry & AUTO_SYMMETRY ?\n              (domain == dualToRange ?\n                   (boost::is_complex<BasisFunctionType>() ?\n                        HERMITIAN :\n                        SYMMETRIC | HERMITIAN) :\n                   NO_SYMMETRY) :\n              symmetry)),\n    m_impl(new Impl),\n    m_id(boost::make_shared<IdentityOperatorId<BasisFunctionType, ResultType> >(\n             *this))\n{\n    if (domain->grid() != range->grid() ||\n            range->grid() != dualToRange->grid())\n        throw std::invalid_argument(\n                \"IdentityOperator::IdentityOperator(): \"\n                \"all three function spaces must be defined on the same grid.\");\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nIdentityOperator<BasisFunctionType, ResultType>::IdentityOperator(\n        const IdentityOperator& other) :\n    Base(other), m_impl(new Impl(*other.m_impl)),\n    m_id(other.m_id)\n{\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nIdentityOperator<BasisFunctionType, ResultType>::~IdentityOperator()\n{\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nIdentityOperator<BasisFunctionType, ResultType>&\nIdentityOperator<BasisFunctionType, ResultType>::\noperator=(const IdentityOperator& rhs)\n{\n    if (this != &rhs) {\n        Base::operator=(rhs);\n        m_impl.reset(new Impl(*rhs.m_impl));\n        m_id = rhs.m_id;\n    }\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<const AbstractBoundaryOperatorId>\nIdentityOperator<BasisFunctionType, ResultType>::id() const\n{\n    return m_id;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nbool IdentityOperator<BasisFunctionType, ResultType>::isLocal() const\n{\n    return true;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<DiscreteBoundaryOperator<ResultType> >\nIdentityOperator<BasisFunctionType, ResultType>::assembleWeakFormImpl(\n        const Context<BasisFunctionType, ResultType>& context) const\n{\n    bool verbose = (context.assemblyOptions().verbosityLevel() >=\n                    VerbosityLevel::DEFAULT);\n    if (verbose)\n        std::cout << \"Assembling the weak form of operator '\"\n                  << this->label() << \"'...\" << std::endl;\n\n    tbb::tick_count start = tbb::tick_count::now();\n    std::auto_ptr<LocalAssembler> assembler =this->makeAssembler(\n                *context.quadStrategy(), context.assemblyOptions());\n    shared_ptr<DiscreteBoundaryOperator<ResultType> > result =\n            assembleWeakFormInternalImpl(*assembler, context.assemblyOptions());\n    tbb::tick_count end = tbb::tick_count::now();\n\n    if (verbose)\n        std::cout << \"Assembly of the weak form of operator '\" << this->label()\n                  << \"' took \" << (end - start).seconds() << \" s\" << std::endl;\n    return result;\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nshared_ptr<DiscreteBoundaryOperator<ResultType> >\nIdentityOperator<BasisFunctionType, ResultType>::assembleWeakFormInternalImpl(\n        LocalAssembler& assembler,\n        const AssemblyOptions& options) const\n{\n#ifdef WITH_TRILINOS\n    if (options.isSparseStorageOfMassMatricesEnabled())\n        return shared_ptr<DiscreteBoundaryOperator<ResultType> >(\n                    assembleWeakFormInSparseMode(assembler, options).release());\n#endif\n    return shared_ptr<DiscreteBoundaryOperator<ResultType> >(\n                    assembleWeakFormInDenseMode(assembler, options).release());\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nIdentityOperator<BasisFunctionType, ResultType>::assembleWeakFormInDenseMode(\n        LocalAssembler& assembler,\n        const AssemblyOptions& options) const\n{\n    const Space<BasisFunctionType>& testSpace = *this->dualToRange();\n    const Space<BasisFunctionType>& trialSpace = *this->domain();\n\n    // Fill local submatrices\n    std::auto_ptr<GridView> view = testSpace.grid()->leafView();\n    const size_t elementCount = view->entityCount(0);\n    std::vector<int> elementIndices(elementCount);\n    for (size_t i = 0; i < elementCount; ++i)\n        elementIndices[i] = i;\n    std::vector<arma::Mat<ResultType> > localResult;\n    assembler.evaluateLocalWeakForms(elementIndices, localResult);\n\n    // Create the operator's matrix\n    arma::Mat<ResultType> result(testSpace.globalDofCount(),\n                                 trialSpace.globalDofCount());\n    result.fill(0.);\n\n    // Retrieve global DOFs corresponding to local DOFs on all elements\n    std::vector<std::vector<GlobalDofIndex> > trialGdofs(elementCount);\n    std::vector<std::vector<GlobalDofIndex> > testGdofs(elementCount);\n\n    // Gather global DOF lists\n    const Mapper& mapper = view->elementMapper();\n    std::auto_ptr<EntityIterator<0> > it = view->entityIterator<0>();\n    while (!it->finished())\n    {\n        const Entity<0>& element = it->entity();\n        const int elementIndex = mapper.entityIndex(element);\n        testSpace.getGlobalDofs(element, testGdofs[elementIndex]);\n        trialSpace.getGlobalDofs(element, trialGdofs[elementIndex]);\n        it->next();\n    }\n\n    // Distribute local matrices into the global matrix\n    for (size_t e = 0; e < elementCount; ++e)\n        for (size_t trialIndex = 0; trialIndex < trialGdofs[e].size(); ++trialIndex)\n            for (size_t testIndex = 0; testIndex < testGdofs[e].size(); ++testIndex)\n                result(testGdofs[e][testIndex], trialGdofs[e][trialIndex]) +=\n                        localResult[e](testIndex, trialIndex);\n\n    return std::auto_ptr<DiscreteBoundaryOperator<ResultType> >(\n                new DiscreteDenseBoundaryOperator<ResultType>(result));\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nIdentityOperator<BasisFunctionType, ResultType>::assembleWeakFormInSparseMode(\n        LocalAssembler& assembler,\n        const AssemblyOptions& options) const\n{\n#ifdef WITH_TRILINOS\n    if (boost::is_complex<BasisFunctionType>::value)\n        throw std::runtime_error(\n                \"IdentityOperator::assembleWeakFormInSparseMode(): \"\n                \"sparse-mode assembly of identity operators for \"\n                \"complex-valued basis functions is not supported yet\");\n\n    const Space<BasisFunctionType>& testSpace = *this->dualToRange();\n    const Space<BasisFunctionType>& trialSpace = *this->domain();\n\n    // Fill local submatrices\n    std::auto_ptr<GridView> view = testSpace.grid()->leafView();\n    const size_t elementCount = view->entityCount(0);\n    std::vector<int> elementIndices(elementCount);\n    for (size_t i = 0; i < elementCount; ++i)\n        elementIndices[i] = i;\n    std::vector<arma::Mat<ResultType> > localResult;\n    assembler.evaluateLocalWeakForms(elementIndices, localResult);\n\n    // Estimate number of entries in each row\n\n    //    This will be useful when we begin to use MPI\n    //    // Get global DOF indices for which this process is responsible\n    //    const int testGlobalDofCount = testSpace.globalDofCount();\n    //    Epetra_Map rowMap(testGlobalDofCount, 0 /* index-base */, comm);\n    //    std::vector<int> myTestGlobalDofs(rowMap.MyGlobalElements(),\n    //                                      rowMap.MyGlobalElements() +\n    //                                      rowMap.NumMyElements());\n    //    const int myTestGlobalDofCount = myTestGlobalDofs.size();\n\n    const int testGlobalDofCount = testSpace.globalDofCount();\n    const int trialGlobalDofCount = trialSpace.globalDofCount();\n    arma::Col<int> nonzeroEntryCountEstimates(testGlobalDofCount);\n    nonzeroEntryCountEstimates.fill(0);\n\n    // Global DOF indices corresponding to local DOFs on elements\n    std::vector<std::vector<GlobalDofIndex> > trialGdofs(elementCount);\n    std::vector<std::vector<GlobalDofIndex> > testGdofs(elementCount);\n\n    // Fill above lists\n    const Mapper& mapper = view->elementMapper();\n    std::auto_ptr<EntityIterator<0> > it = view->entityIterator<0>();\n    while (!it->finished())\n    {\n        const Entity<0>& element = it->entity();\n        const int elementIndex = mapper.entityIndex(element);\n        testSpace.getGlobalDofs(element, testGdofs[elementIndex]);\n        trialSpace.getGlobalDofs(element, trialGdofs[elementIndex]);\n        it->next();\n    }\n\n    // Upper estimate for the number of global trial DOFs coupled to a given\n    // global test DOF: sum of the local trial DOF counts for each element that\n    // contributes to the global test DOF in question\n    for (size_t e = 0; e < elementCount; ++e)\n        for (size_t testLdof = 0; testLdof < testGdofs[e].size(); ++testLdof)\n            nonzeroEntryCountEstimates(testGdofs[e][testLdof]) +=\n                    trialGdofs[e].size();\n\n    Epetra_SerialComm comm; // To be replaced once we begin to use MPI\n    Epetra_LocalMap rowMap(testGlobalDofCount, 0 /* index_base */, comm);\n    Epetra_LocalMap colMap(trialGlobalDofCount, 0 /* index_base */, comm);\n    shared_ptr<Epetra_FECrsMatrix> result = boost::make_shared<Epetra_FECrsMatrix>(\n                Copy, rowMap, colMap,\n                nonzeroEntryCountEstimates.memptr());\n\n    // TODO: make each process responsible for a subset of elements\n    // Find maximum number of local dofs per element\n    size_t maxLdofCount = 0;\n    for (size_t e = 0; e < elementCount; ++e)\n        maxLdofCount = std::max(maxLdofCount,\n                                testGdofs[e].size() * trialGdofs[e].size());\n\n    // Initialise sparse matrix with zeros at required positions\n    arma::Col<double> zeros(maxLdofCount);\n    zeros.fill(0.);\n    for (size_t e = 0; e < elementCount; ++e)\n        result->InsertGlobalValues(testGdofs[e].size(), &testGdofs[e][0],\n                                   trialGdofs[e].size(), &trialGdofs[e][0],\n                                   zeros.memptr());\n    // Add contributions from individual elements\n    for (size_t e = 0; e < elementCount; ++e)\n        epetraSumIntoGlobalValues(\n                    *result, testGdofs[e], trialGdofs[e], localResult[e]);\n    result->GlobalAssemble();\n\n    // If assembly mode is equal to ACA and we have AHMED,\n    // construct the block cluster tree. Otherwise leave it uninitialized.\n    typedef ClusterConstructionHelper<BasisFunctionType> CCH;\n    typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n    typedef ExtendedBemCluster<AhmedDofType> AhmedBemCluster;\n    typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n\n    shared_ptr<AhmedBemBlcluster> blockCluster;\n    shared_ptr<IndexPermutation> test_o2pPermutation, test_p2oPermutation;\n    shared_ptr<IndexPermutation> trial_o2pPermutation, trial_p2oPermutation;\n#ifdef WITH_AHMED\n    if (options.assemblyMode() == AssemblyOptions::ACA) {\n        const AcaOptions& acaOptions = options.acaOptions();\n        bool indexWithGlobalDofs = acaOptions.globalAssemblyBeforeCompression;\n\n        typedef ClusterConstructionHelper<BasisFunctionType> CCH;\n        shared_ptr<AhmedBemCluster> testClusterTree;\n        CCH::constructBemCluster(testSpace, indexWithGlobalDofs, acaOptions,\n                                 testClusterTree,\n                                 test_o2pPermutation, test_p2oPermutation);\n        // TODO: construct a hermitian H-matrix if possible\n        shared_ptr<AhmedBemCluster> trialClusterTree;\n        CCH::constructBemCluster(trialSpace, indexWithGlobalDofs, acaOptions,\n                                 trialClusterTree,\n                                 trial_o2pPermutation, trial_p2oPermutation);\n        unsigned int blockCount = 0;\n        blockCluster.reset(CCH::constructBemBlockCluster(\n                               acaOptions, false /* hermitian */,\n                               *testClusterTree, *trialClusterTree, blockCount)\n                           .release());\n    }\n#endif\n\n    // Create and return a discrete operator represented by the matrix that\n    // has just been calculated\n    return std::auto_ptr<DiscreteBoundaryOperator<ResultType> >(\n        new DiscreteSparseBoundaryOperator<ResultType>(\n                    result, this->symmetry(), NO_TRANSPOSE,\n                    blockCluster, trial_o2pPermutation, test_o2pPermutation));\n#else // WITH_TRILINOS\n    throw std::runtime_error(\"IdentityOperator::assembleWeakFormInSparseMode(): \"\n                             \"To enable assembly in sparse mode, recompile BEM++ \"\n                             \"with the symbol WITH_TRILINOS defined.\");\n#endif\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<typename IdentityOperator<BasisFunctionType, ResultType>::LocalAssembler>\nIdentityOperator<BasisFunctionType, ResultType>::makeAssemblerImpl(\n        const QuadratureStrategy& quadStrategy,\n        const shared_ptr<const GeometryFactory>& testGeometryFactory,\n        const shared_ptr<const GeometryFactory>& trialGeometryFactory,\n        const shared_ptr<const Fiber::RawGridGeometry<CoordinateType> >& testRawGeometry,\n        const shared_ptr<const Fiber::RawGridGeometry<CoordinateType> >& trialRawGeometry,\n        const shared_ptr<const std::vector<const Fiber::Basis<BasisFunctionType>*> >& testBases,\n        const shared_ptr<const std::vector<const Fiber::Basis<BasisFunctionType>*> >& trialBases,\n        const shared_ptr<const Fiber::OpenClHandler>& openClHandler,\n        const ParallelizationOptions&,\n        VerbosityLevel::Level /* verbosityLevel*/,\n        bool /* cacheSingularIntegrals */) const\n{\n    shared_ptr<const Fiber::CollectionOfBasisTransformations<CoordinateType> >\n            transformations = make_shared_from_ref(m_impl->transformations);\n\n    if (testGeometryFactory.get() != trialGeometryFactory.get() ||\n            testRawGeometry.get() != trialRawGeometry.get())\n        throw std::invalid_argument(\"IdentityOperator::makeAssemblerImpl(): \"\n                                    \"the test and trial spaces must be defined \"\n                                    \"on the same grid\");\n    return quadStrategy.makeAssemblerForIdentityOperators(\n                testGeometryFactory, testRawGeometry,\n                testBases, trialBases,\n                transformations, transformations,\n                openClHandler);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBoundaryOperator<BasisFunctionType, ResultType>\nidentityOperator(const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n                 const shared_ptr<const Space<BasisFunctionType> >& domain,\n                 const shared_ptr<const Space<BasisFunctionType> >& range,\n                 const shared_ptr<const Space<BasisFunctionType> >& dualToRange,\n                 const std::string& label,\n                 int symmetry)\n{\n    typedef IdentityOperator<BasisFunctionType, ResultType> Id;\n    return BoundaryOperator<BasisFunctionType, ResultType>(\n                context,\n                boost::make_shared<Id>(domain, range, dualToRange,\n                                       label, symmetry));\n}\n\n#define INSTANTIATE_NONMEMBER_CONSTRUCTOR(BASIS, RESULT) \\\n    template BoundaryOperator<BASIS, RESULT> \\\n    identityOperator( \\\n        const shared_ptr<const Context<BASIS, RESULT> >&, \\\n        const shared_ptr<const Space<BASIS> >&, \\\n        const shared_ptr<const Space<BASIS> >&, \\\n        const shared_ptr<const Space<BASIS> >&, \\\n        const std::string&, \\\n        int)\nFIBER_ITERATE_OVER_BASIS_AND_RESULT_TYPES(INSTANTIATE_NONMEMBER_CONSTRUCTOR);\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(IdentityOperator);\n\n} // namespace Bempp\n", "meta": {"hexsha": "b447ba00e63f998dfd82703c355a7d398396a90f", "size": 24233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/identity_operator.cpp", "max_stars_repo_name": "nicolas-chaulet/bempp", "max_stars_repo_head_hexsha": "0f5cc72e0e542437e787db5704978456b0ad9e35", "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/identity_operator.cpp", "max_issues_repo_name": "nicolas-chaulet/bempp", "max_issues_repo_head_hexsha": "0f5cc72e0e542437e787db5704978456b0ad9e35", "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/identity_operator.cpp", "max_forks_repo_name": "nicolas-chaulet/bempp", "max_forks_repo_head_hexsha": "0f5cc72e0e542437e787db5704978456b0ad9e35", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T09:46:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T09:46:44.000Z", "avg_line_length": 42.2177700348, "max_line_length": 97, "alphanum_fraction": 0.6837370528, "num_tokens": 5491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.020332352081193057, "lm_q1q2_score": 0.00890198153340987}}
{"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 <boost/function.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/thread.hpp>\n#include <Eigen/Core>\n#include \"genfile/SNPDataSourceProcessor.hpp\"\n#include \"genfile/SNPDataSourceChain.hpp\"\n#include \"genfile/SampleFilteringSNPDataSource.hpp\"\n#include \"genfile/SampleMappingSNPDataSource.hpp\"\n#include \"genfile/wildcard.hpp\"\n#include \"genfile/ToGP.hpp\"\n#include \"statfile/BuiltInTypeStatSink.hpp\"\n#include \"integration/NewtonRaphson.hpp\"\n#include \"integration/Derivative.hpp\"\n#include \"db/Connection.hpp\"\n#include \"db/SQLStatement.hpp\"\n#include \"db/Error.hpp\"\n#include \"components/HaplotypeFrequencyComponent/FlatTableDBOutputter.hpp\"\n#include \"components/HaplotypeFrequencyComponent/HaplotypeFrequencyComponent.hpp\"\n\n// #define DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT 1\nstruct HaplotypeFrequencyLogLikelihood ;\n\nvoid HaplotypeFrequencyComponent::declare_options( appcontext::OptionProcessor& options ) {\n\toptions.declare_group( \"LD computation options\" ) ;\n\toptions[ \"-compute-ld-with\" ]\n\t\t.set_description( \"Compute LD pairwise metrics between the main dataset and SNPs.\" )\n\t\t.set_takes_values(2) ;\n\toptions[ \"-old\" ]\n\t\t.set_description( \"Specify file to write LD metrics to\" )\n\t\t.set_takes_single_value() ;\n\toptions[ \"-max-ld-distance\" ]\n\t\t.set_description( \"Maximum physical distance between SNPs, above which LD will not be computed. \"\n\t\t\t\"A value of zero indicates LD between all SNPs will be computed. \"\n\t\t\t\"A plain number indicates distance in base pairs, or you add a Mb or kb suffix to specify the \"\n\t\t\t\"distance in megabases or kilobases if desired.\" )\n\t\t.set_takes_single_value()\n\t\t.set_default_value( \"0\" ) ;\n\toptions[ \"-min-r2\" ]\n\t\t.set_description( \"Minimum squared correlation between variants.  LD results for pairs of variants with \"\n\t\t\t\"lower than this squared correlation will not be output.\" )\n\t\t.set_takes_single_value()\n\t\t.set_default_value( \"0\" ) ;\n\toptions[ \"-prior-ld-weight\" ]\n\t\t.set_description( \"Weight w to place on shrinkage prior in computation of pairwise LD. \"\n\t\t\t\"This is interpreted as adding dummy observations of w/4 for each of the four possible haplotypes, \"\n\t\t\t\"or equivalently, to placing a Dirichlet(w/4, w/4, w/4, w/4) prior on the vector of haplotype frequencies.\" )\n\t\t.set_takes_single_value()\n\t\t.set_default_value( 1.0 ) ;\n\toptions.option_implies_option( \"-compute-ld-with\", \"-old\" ) ;\n\toptions.option_implies_option( \"-prior-ld-weight\", \"-compute-ld-with\" ) ;\n\toptions.option_implies_option( \"-max-ld-distance\", \"-compute-ld-with\" ) ;\n\toptions.option_implies_option( \"-min-r2\", \"-compute-ld-with\" ) ;\n}\n\nnamespace {\n\tuint64_t parse_physical_distance( std::string distance ) {\n\t\tstd::size_t number_part_length = std::string::npos ;\n\t\tuint64_t multiplier = 1 ;\n\t\t// allowable suffixes are mb, kb, bp.\n\t\t\n\t\tif( distance.size() == 0 ) {\n\t\t\tthrow genfile::BadArgumentError( \"parse_physical_distance()\", \"distance=\\\"\" + distance + \"\\\"\" ) ;\n\t\t}\n\t\t\n\t\tif( distance[ distance.size() - 1 ] != 'b' && distance[ distance.size() - 1 ] != 'b' ) {\n\t\t\t// no suffix.\n\t\t\tnumber_part_length = distance.size() ;\n\t\t\tmultiplier = 1 ;\n\t\t}\n\t\telse {\n\t\t\tif( distance.size() < 3 ) {\n\t\t\t\tthrow genfile::BadArgumentError( \"parse_physical_distance()\", \"distance=\\\"\" + distance + \"\\\"\" ) ;\n\t\t\t}\n\t\t\tnumber_part_length = distance.size() - 2 ;\n\t\t\tstd::string suffix = genfile::string_utils::to_lower( distance.substr( distance.size() - 2, 2 ) ) ;\n\t\t\tif( suffix == \"bp\" ) {\n\t\t\t\tmultiplier = 1 ;\n\t\t\t} else if( suffix == \"kb\" ) {\n\t\t\t\tmultiplier = 1000 ;\n\t\t\t} else if( suffix == \"mb\" ) {\n\t\t\t\tmultiplier = 1000000 ;\n\t\t\t} else {\n\t\t\t\tthrow genfile::BadArgumentError( \"parse_physical_distance()\", \"distance=\\\"\" + distance + \"\\\"\" ) ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tuint64_t const result = genfile::string_utils::to_repr< double >( distance.substr( 0, number_part_length ) ) * multiplier ;\n\t\tstd::cerr << \"Parsed distance \\\"\" + distance + \"\\\" as \" + genfile::string_utils::to_string( result ) + \" base pairs.\\n\" ;\n\t\treturn result ;\n\t}\n}\n\nnamespace {\n\tgenfile::SampleStratification compute_stratification( genfile::CohortIndividualSource const& samples, std::string const& variable ) {\n\t\tgenfile::SampleStratification result ;\n\t\tgenfile::CohortIndividualSource::ColumnSpec const spec = samples.get_column_spec() ;\n\t\tif( !spec[ variable ].is_discrete() ) {\n\t\t\tthrow genfile::BadArgumentError( \"void impl::compute_strata()\", \"variable=\\\"\" + variable + \"\\\"\" ) ;\n\t\t}\n\n\t\tfor( std::size_t i = 0; i < samples.get_number_of_individuals(); ++i ) {\n\t\t\tgenfile::VariantEntry const& entry = samples.get_entry( i, variable ) ;\n\t\t\tif( !entry.is_missing() ) {\n\t\t\t\tresult.add_sample( variable + \"=\" + entry.as< std::string >(), i ) ;\n\t\t\t}\n\t\t}\n\n\t\treturn result ;\n\t}\n}\n\nHaplotypeFrequencyComponent::UniquePtr HaplotypeFrequencyComponent::create(\n\tgenfile::CohortIndividualSource const& source_samples,\n\tstd::string const& source_sample_id_column,\n\tgenfile::CohortIndividualSource::UniquePtr samples,\n\tstd::string const& ld_sample_id_column,\n\tgenfile::SNPDataSource::UniquePtr source,\n\tappcontext::OptionProcessor const& options,\n\tappcontext::UIContext& ui_context\n) {\n\tsource.reset(\n\t\tnew genfile::SampleMappingSNPDataSource(\n\t\t\tsource_samples,\n\t\t\tsource_sample_id_column,\n\t\t\t*samples,\n\t\t\tld_sample_id_column,\n\t\t\tsource\n\t\t)\n\t) ;\n\n\tHaplotypeFrequencyComponent::UniquePtr result ;\n\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\tstd::cerr << \"LD SNP samples: \" << source->number_of_samples() << \" (matched from \" << source->get_parent_source().number_of_samples() << \" in raw data).\\n\" ;\n#endif\n\tresult.reset(\n\t\tnew HaplotypeFrequencyComponent(\n\t\t\tsource,\n\t\t\tui_context\n\t\t)\n\t) ;\n\t\n\tresult->set_max_distance( parse_physical_distance( options.get< std::string >( \"-max-ld-distance\" ))) ;\n\tresult->set_min_r2( options.get< double >( \"-min-r2\" )) ;\n\t{\n\t\tdouble const w = options.get< double >( \"-prior-ld-weight\" ) ;\n\t\tEigen::MatrixXd prior(2,2) ;\n\t\tprior\n\t\t\t<< w/4, w/4,\n\t\t\t   w/4, w/4\n\t\t;\n\t\tresult->set_prior( prior ) ;\n\t}\n\n\tusing namespace genfile::string_utils ;\n\tstd::string filename = options.get_value< std::string >( \"-old\" ) ;\n\tif( filename.size() >= 9 && filename.substr( 0, 9 ) == \"sqlite://\" ) {\n\t\tfilename = filename.substr( 9, filename.size() ) ;\n\t}\n\tstd::vector< std::string > outputFilenameElts = genfile::string_utils::split( filename, \":\" ) ;\n\tassert( outputFilenameElts.size() > 0 ) ;\n\tif( outputFilenameElts.size() > 2 ) {\n\t\tthrow genfile::BadArgumentError(\n\t\t\t\"HaplotypeFrequencyComponent::create()\",\n\t\t\t\"-old \\\"\" + options.get_value< std::string >( \"-old\" ) + \"\\\"\",\n\t\t\t\"Value should be of the form [sqlite://]<filename>[:<tablename>]\"\n\t\t) ;\n\t}\n\t\n\thaplotype_frequency_component::FlatTableDBOutputter::UniquePtr outputter\n\t\t= haplotype_frequency_component::FlatTableDBOutputter::create(\n\t\t\toutputFilenameElts[0],\n\t\t\toptions.get_value< std::string >( \"-analysis-name\" ),\n\t\t\t\"HaplotypeFrequencyComponent\",\n\t\t\toptions.get_values_as_map()\n\t) ;\n\tif( outputFilenameElts.size() == 2 ) {\n\t\toutputter->set_table_name( outputFilenameElts[1] ) ;\n\t}\n\t\n\tif( options.check( \"-stratify\" )) {\n\t\tresult->set_stratification( compute_stratification( source_samples, options.get< std::string >( \"-stratify\" )) ) ;\n\t}\n\n\tresult->send_results_to( outputter ) ;\n\treturn result ;\n}\n\nHaplotypeFrequencyComponent::HaplotypeFrequencyComponent(\n\tgenfile::SNPDataSource::UniquePtr source,\n\tappcontext::UIContext& ui_context\n):\n\tm_source( source ),\n\tm_ui_context( ui_context ),\n\tm_threshhold( 0.9 ),\n\tm_max_distance( 200000 ),\n\tm_min_r2( 0.0 ),\n\tm_prior( Eigen::Matrix2d::Zero() )\n{\n}\n\nvoid HaplotypeFrequencyComponent::set_max_distance( uint64_t distance ) {\n\tm_max_distance = distance ;\n}\n\nvoid HaplotypeFrequencyComponent::set_min_r2( double min_r2 ) {\n\tassert( min_r2 >= 0.0 ) ;\n\tm_min_r2 = min_r2 ;\n}\n\nvoid HaplotypeFrequencyComponent::set_prior( Eigen::Matrix2d const& matrix ) {\n\tassert( matrix.array().minCoeff() >= 0.0 ) ;\n\tm_prior = matrix ;\n}\n\nvoid HaplotypeFrequencyComponent::set_stratification( genfile::SampleStratification stratification ) {\n\tm_stratification = stratification ;\n}\n\nvoid HaplotypeFrequencyComponent::begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& ) {\n\tassert( m_source->number_of_samples() == number_of_samples ) ;\n}\n\nvoid HaplotypeFrequencyComponent::processed_snp(\n\tgenfile::VariantIdentifyingData const& target_snp,\n\tgenfile::VariantDataReader& target_data_reader\n) {\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\tstd::cerr << \"Processing \" << target_snp << \"...\\n\" ;\n#endif\n\tgenfile::VariantIdentifyingData source_snp ;\n\tm_source->reset_to_start() ;\n\twhile( m_source->get_snp_identifying_data( &source_snp )) {\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\t\tstd::cerr << \"Comparing to \" << source_snp << \"...\\n\" ;\n#endif\n\t\tif(\n\t\t\t( m_max_distance == 0 )\n\t\t\t||\n\t\t\t(\n\t\t\t\t( source_snp.get_position().chromosome() == target_snp.get_position().chromosome() )\n\t\t\t\t&&\n\t\t\t\t( std::abs( int64_t( source_snp.get_position().position() ) - int64_t( target_snp.get_position().position() ) ) <= m_max_distance )\n\t\t\t)\n\t\t) {\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\t\t\tstd::cerr << \"Computing LD measures for \" << source_snp << \" : \" << target_snp << \"...\\n\" ;\n#endif\n\t\t\tgenfile::VariantDataReader::UniquePtr source_data_reader = m_source->read_variant_data() ;\n\t\t\tcompute_ld_measures( source_snp, *source_data_reader, target_snp, target_data_reader ) ;\n\t\t}\n\t\telse {\n\t\t\tm_source->ignore_snp_probability_data() ;\n\t\t}\n\t}\n}\n\nnamespace {\n\tstruct CallSetter: public genfile::VariantDataReader::PerSampleSetter {\n\t\tenum { ePhased = 0x80000000 } ;\n\n\t\tCallSetter(\n\t\t\tstd::vector< int >* result,\n\t\t\tstd::vector< uint32_t >* ploidy\n\t\t):\n\t\t\tm_result( result ),\n\t\t\tm_ploidy( ploidy )\n\t\t{\n\t\t\tassert( result ) ;\n\t\t}\n\n\t\tvoid initialise( std::size_t nSamples, std::size_t nAlleles ) {\n\t\t\tif( nAlleles != 2 ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::initialise()\",\n\t\t\t\t\t\"nAlleles=\" + genfile::string_utils::to_string( nAlleles ),\n\t\t\t\t\t\"Only biallelic variants are currently supported.\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tm_result->clear() ; // ploidy 2\n\t\t\tm_result->resize( nSamples, -1 ) ;\n\t\t\tm_ploidy->clear() ;\n\t\t\tm_ploidy->resize( nSamples, 0 ) ;\n\t\t}\n\n\t\tbool set_sample( std::size_t n ) {\n\t\t\tm_sample_i = n ;\n\t\t\treturn true ;\n\t\t}\n\n\t\tvoid set_number_of_entries(\n\t\t\tuint32_t ploidy, std::size_t n,\n\t\t\tgenfile::OrderType const order_type,\n\t\t\tgenfile::ValueType const value_type\n\t\t) {\n\t\t\tif( ploidy > 2 ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"ploidy=\" + genfile::string_utils::to_string( ploidy ),\n\t\t\t\t\t\"Only haploid or diploid samples are currently supported.\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tif( value_type != genfile::eAlleleIndex ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"value_type=\" + genfile::string_utils::to_string( value_type ),\n\t\t\t\t\t\"Expected a hard-called genotype, consider using threshholded calls.\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tif( order_type != genfile::ePerOrderedHaplotype && order_type != genfile::ePerUnorderedHaplotype ) {\n\t\t\t\tthrow genfile::BadArgumentError(\n\t\t\t\t\t\"Callsetter::set_number_of_entries()\",\n\t\t\t\t\t\"order_type=\" + genfile::string_utils::to_string( order_type ),\n\t\t\t\t\t\"Expected a hard-called genotype, consider using threshholded calls.\"\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tassert( value_type == genfile::eAlleleIndex ) ;\n\t\t\tm_order_type = order_type ;\n\t\t\tuint32_t storedPloidy = ploidy ;\n\t\t\tif( m_order_type == genfile::ePerOrderedHaplotype ) {\n\t\t\t\tstoredPloidy |= ePhased ;\n\t\t\t}\n\t\t\t(*m_ploidy)[m_sample_i] = storedPloidy ;\n\t\t\t(*m_result)[m_sample_i] = 0 ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, genfile::MissingValue const value ) {\n\t\t\t(*m_result)[m_sample_i] = -1; \n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, Integer const value ) {\n\t\t\t// Only accumulate if not missing\n\t\t\tint& stored = (*m_result)[m_sample_i] ;\n\t\t\tif( stored != -1 ) {\n\t\t\t\tif( m_order_type == genfile::ePerUnorderedHaplotype ) {\n\t\t\t\t\t// Compute count of 2nd allele\n\t\t\t\t\t(*m_result)[m_sample_i] += value ;\n\t\t\t\t}\n\t\t\t\telse if( m_order_type == genfile::ePerOrderedHaplotype ) {\n\t\t\t\t\t// Put haplotype allele counts in seperate bits.\n\t\t\t\t\t(*m_result)[m_sample_i] += (value << entry_i) ;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tassert(0) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, double const value ) {\n\t\t\tassert(0) ; // expecting GT field\n\t\t}\n\n\t\tvoid finalise() {\n\t\t\t// nothing to do\n\t\t}\n\t\t\n\tprivate:\n\t\tstd::vector< int >* m_result ;\n\t\tstd::vector< uint32_t >* m_ploidy ;\n\t\tstd::size_t m_sample_i ;\n\t\tgenfile::OrderType m_order_type ;\n\t} ;\n\t\n\tvoid tabulate_calls(\n\t\tstd::vector< genfile::SampleRange > const& sample_set,\n\t\tstd::vector< int > left_calls,\n\t\tstd::vector< uint32_t > left_ploidy,\n\t\tstd::vector< int > right_calls,\n\t\tstd::vector< uint32_t > right_ploidy,\n\t\tEigen::Matrix3d* diploid_table,\n\t\tEigen::Matrix2d* haploid_table\n\t) {\n\t\tfor( std::size_t range_i = 0; range_i < sample_set.size(); ++range_i ) {\n\t\t\tfor( std::size_t j = sample_set[range_i].begin(); j < sample_set[range_i].end(); ++j ) {\n\t\t\t\tif( right_ploidy[j] == left_ploidy[j] && left_calls[j] != -1 && right_calls[j] != -1 ) {\n\t\t\t\t\tuint32_t const ploidy = left_ploidy[j] & 0xF;\n\t\t\t\t\tuint32_t const phased = left_ploidy[j] & CallSetter::ePhased ;\n\t\t\t\t\tswitch( ploidy ) {\n\t\t\t\t\t\tcase 0: break; // zeroploid, nothing to do\n\t\t\t\t\t\tcase 1:\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT > 1\n\t\t\t\t\t\t\tstd::cerr << \"Setting haploid: \" << left_calls[j] << \", \" << right_calls[j] << \".\\n\" ;\n#endif\n\t\t\t\t\t\t\t++((*haploid_table)( left_calls[j], right_calls[j] )) ;\n\t\t\t\t\t\t\tbreak ;\n\t\t\t\t\t\tcase 2:\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT > 1\n\t\t\t\t\t\t\tstd::cerr << \"Setting diploid: \" << left_calls[j] << \", \" << right_calls[j] << \".\\n\" ;\n#endif\n\t\t\t\t\t\t\tif( phased != 0 ) {\n\t\t\t\t\t\t\t\t++(*haploid_table)(\n\t\t\t\t\t\t\t\t\t(left_calls[j] & 0x1),\n\t\t\t\t\t\t\t\t\t(right_calls[j] & 0x1)\n\t\t\t\t\t\t\t\t) ;\n\t\t\t\t\t\t\t\t++(*haploid_table)(\n\t\t\t\t\t\t\t\t\t(left_calls[j] & 0x2) >> 1,\n\t\t\t\t\t\t\t\t\t(right_calls[j] & 0x2) >> 1\n\t\t\t\t\t\t\t\t) ;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t++(*diploid_table)( left_calls[j], right_calls[j] ) ;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak ;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tassert(0) ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\t\tstd::cerr << \"Haploid table:\\n\" << *haploid_table << \"\\n\" ;\n\t\tstd::cerr << \"Diploid table:\\n\" << *diploid_table << \"\\n\" ;\n#endif\n\t} ;\n\n\tstruct DosageSetter: public genfile::VariantDataReader::PerSampleSetter {\n\t\tDosageSetter(\n\t\t\tEigen::MatrixXd* result,\n\t\t\tEigen::MatrixXd* nonmissingness,\n\t\t\tint column\n\t\t):\n\t\t\tm_result( result ),\n\t\t\tm_nonmissingness( nonmissingness ),\n\t\t\tm_order_type( genfile::eUnknownOrderType ),\n\t\t\tm_result_column( column )\n\t\t{\n\t\t\tassert( result ) ;\n\t\t\tassert( column >= 0 && column < result->cols() ) ;\n\t\t}\n\n\t\tvoid initialise( std::size_t nSamples, std::size_t nAlleles ) {\n\t\t\tassert( nAlleles == 2 ) ;\n\t\t\tassert( m_result->rows() == nSamples ) ;\n\t\t\tassert( m_nonmissingness->rows() == nSamples ) ;\n\t\t}\n\n\t\tbool set_sample( std::size_t n ) {\n\t\t\tm_sample_i = n ;\n\t\t\tm_order_type = genfile::eUnknownOrderType ;\n\t\t\treturn true ;\n\t\t}\n\n\t\tvoid set_number_of_entries(\n\t\t\tuint32_t ploidy, std::size_t n,\n\t\t\tgenfile::OrderType const order_type,\n\t\t\tgenfile::ValueType const value_type\n\t\t) {\n\t\t\tassert( ploidy <= 2 ) ;\n\t\t\tassert( (order_type == genfile::ePerOrderedHaplotype || genfile::ePerUnorderedGenotype) && value_type == genfile::eProbability ) ;\n\t\t\tm_order_type = order_type ;\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT > 1\n\t\t\tstd::cerr << m_order_type << \", \" << m_sample_i << \", \" << m_result_column << \"\\n\" << std::flush ;\n\t\t\tstd::cerr << m_result->rows() << \" x \" << m_result->cols() << \".\\n\" << std::flush ;\n\t\t\tstd::cerr << m_nonmissingness->rows() << \" x \" << m_nonmissingness->cols() << \".\\n\" << std::flush ;\n#endif\n\t\t\t(*m_result)(m_sample_i,m_result_column) = 0 ;\n\t\t\t(*m_nonmissingness)(m_sample_i,m_result_column) = 0 ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, genfile::MissingValue const value ) {\n\t\t\t(*m_result)(m_sample_i, m_result_column) = 0 ;\n\t\t\t(*m_nonmissingness)(m_sample_i,m_result_column) = 0 ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, double const value ) {\n\t\t\t// For biallelic variants, genotypes come in the order of\n\t\t\t// the number of B alleles, so this computes dosage:\n\t\t\tif( m_order_type == genfile::ePerOrderedHaplotype ) {\n\t\t\t\t// genotypes come in the order A, B (1st hap); A, B (2nd hap)\n\t\t\t\t// assumption is variant is biallelic.\n\t\t\t\t(*m_result)(m_sample_i, m_result_column) += (entry_i % 2) * value ;\n\t\t\t} else {\n\t\t\t\t// order type = genfile::ePerUnorderedGenotype\n\t\t\t\t// genotypes come in the order AA, AB, BB, \n\t\t\t\t(*m_result)(m_sample_i, m_result_column) += entry_i * value ;\n\t\t\t}\n\t\t\t(*m_nonmissingness)(m_sample_i,m_result_column) = 1 ;\n\t\t}\n\n\t\tvoid set_value( std::size_t entry_i, Integer const value ) {\n\t\t\tassert(0) ; // expecting GT field\n\t\t}\n\n\t\tvoid finalise() {\n\t\t\t// nothing to do\n\t\t}\n\t\t\n\tprivate:\n\t\tEigen::MatrixXd* m_result ;\n\t\tEigen::MatrixXd* m_nonmissingness ;\n\t\tgenfile::OrderType m_order_type ;\n\t\tint m_result_column ;\n\t\tstd::size_t m_sample_i ;\n\t} ;\n}\n\nvoid HaplotypeFrequencyComponent::compute_ld_measures(\n\tgenfile::VariantIdentifyingData const& source_snp,\n\tgenfile::VariantDataReader& source_data_reader,\n\tgenfile::VariantIdentifyingData const& target_snp,\n\tgenfile::VariantDataReader& target_data_reader\n) {\n\tif( source_snp.number_of_alleles() == 2 && target_snp.number_of_alleles() == 2 ) {\n\t\tstd::vector< int > source_calls ;\n\t\tstd::vector< uint32_t > source_ploidy ;\n\t\tstd::vector< int > target_calls ;\n\t\tstd::vector< uint32_t > target_ploidy ;\n\t\tEigen::MatrixXd dosages( source_data_reader.get_number_of_samples(), 2 ) ;\n\t\tEigen::MatrixXd nonmissingness( source_data_reader.get_number_of_samples(), 2 ) ;\n\n\t\tbool haveCalls = false ;\n\t\ttry {\n\t\t\tsource_data_reader.get( \":genotypes:\", CallSetter( &source_calls, &source_ploidy ) ) ;\n\t\t\ttarget_data_reader.get( \":genotypes:\", CallSetter( &target_calls, &target_ploidy ) ) ;\n\t\t\thaveCalls = true ;\n\t\t} catch( ... ) {\n\t\t}\n\n\t\t{\n\t\t\tDosageSetter source_setter( &dosages, &nonmissingness, 0 ) ;\n\t\t\tDosageSetter target_setter( &dosages, &nonmissingness, 1 ) ;\n\t\t\tsource_data_reader.get( \":genotypes:\", genfile::to_GP_unphased( source_setter ) ) ;\n\t\t\ttarget_data_reader.get( \":genotypes:\", genfile::to_GP_unphased( target_setter ) ) ;\n\t\t}\n\t\t\n\t\t// we treat any data point that is missing in one sample as missing in both\n\t\tfor( int i = 0; i < nonmissingness.rows(); ++i ) {\n\t\t\tif( nonmissingness.row(i).sum() < 2 ) {\n\t\t\t\tnonmissingness.row(i).setZero() ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcompute_ld_measures(\n\t\t\tsource_snp,\n\t\t\tsource_calls,\n\t\t\tsource_ploidy,\n\t\t\ttarget_snp,\n\t\t\ttarget_calls,\n\t\t\ttarget_ploidy,\n\t\t\tdosages,\n\t\t\tnonmissingness,\n\t\t\thaveCalls\n\t\t) ;\n\t}\n}\n\nvoid HaplotypeFrequencyComponent::compute_ld_measures(\n\tgenfile::VariantIdentifyingData const& source_snp,\n\tstd::vector< int > const& source_calls,\n\tstd::vector< uint32_t > const& source_ploidy,\n\tgenfile::VariantIdentifyingData const& target_snp,\n\tstd::vector< int > const& target_calls,\n\tstd::vector< uint32_t > const& target_ploidy,\n\tEigen::MatrixXd const& dosages,\n\tEigen::MatrixXd const& nonmissingness,\n\tbool const runEM\n) {\n\tif( m_stratification ) {\n\t\tbool output = (m_min_r2 == 0.0 ) ;\n\t\tfor( std::size_t i = 0; i < m_stratification->number_of_strata(); ++i ) {\n\t\t\ttry {\n\t\t\t\tif( runEM ) {\n\t\t\t\t\toutput = compute_em_ld_measures(\n\t\t\t\t\t\tsource_snp,\n\t\t\t\t\t\tsource_calls,\n\t\t\t\t\t\tsource_ploidy,\n\t\t\t\t\t\ttarget_snp,\n\t\t\t\t\t\ttarget_calls,\n\t\t\t\t\t\ttarget_ploidy,\n\t\t\t\t\t\tm_stratification->stratum_name(i) + \":\",\n\t\t\t\t\t\tm_stratification->stratum(i),\n\t\t\t\t\t\toutput\n\t\t\t\t\t) || output ;\n\t\t\t\t}\n\t\t\t\toutput = compute_dosage_ld_measures(\n\t\t\t\t\tsource_snp,\n\t\t\t\t\ttarget_snp,\n\t\t\t\t\tdosages,\n\t\t\t\t\tnonmissingness,\n\t\t\t\t\tm_stratification->stratum_name(i) + \":\",\n\t\t\t\t\tm_stratification->stratum(i),\n\t\t\t\t\toutput\n\t\t\t\t) || output ;\n\t\t\t} catch( genfile::OperationFailedError const& e ) {\n\t\t\t\tm_ui_context.logger() << \"!! HaplotypeFrequencyComponent::compute_ld_measures(): \"\n\t\t\t\t\t<< \"stratum \" << m_stratification->stratum_name(i) << \": \"\n\t\t\t\t\t<< \"could not compute LD measures between SNPs \"\n\t\t\t\t\t<< source_snp << \" and \" << target_snp << \".\\n\"\n\t\t\t\t\t<< \"!! reason: \" << e.get_message() << \"\\n\" ;\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttry {\n\t\t\tbool output = (m_min_r2 == 0.0 ) ;\n\t\t\tif( runEM ) {\n\t\t\t\toutput = compute_em_ld_measures(\n\t\t\t\t\tsource_snp,\n\t\t\t\t\tsource_calls, source_ploidy,\n\t\t\t\t\ttarget_snp,\n\t\t\t\t\ttarget_calls, target_ploidy,\n\t\t\t\t\t\"\",\n\t\t\t\t\tstd::vector< genfile::SampleRange  >( 1, genfile::SampleRange( 0, dosages.rows() ) ),\n\t\t\t\t\toutput\n\t\t\t\t) ;\n\t\t\t}\n\t\t\tcompute_dosage_ld_measures(\n\t\t\t\tsource_snp,\n\t\t\t\ttarget_snp,\n\t\t\t\tdosages,\n\t\t\t\tnonmissingness,\n\t\t\t\t\"\",\n\t\t\t\tstd::vector< genfile::SampleRange  >( 1, genfile::SampleRange( 0, dosages.rows() ) ),\n\t\t\t\toutput\n\t\t\t) ;\n\t\t} catch( genfile::OperationFailedError const& e ) {\n\t\t\tm_ui_context.logger() << \"!! HaplotypeFrequencyComponent::compute_ld_measures(): \"\n\t\t\t\t<< \"could not compute LD measures between SNPs \"\n\t\t\t\t<< source_snp << \" and \" << target_snp << \".\\n\"\n\t\t\t\t<< \"!! reason: \" << e.get_message() << \"\\n\" ;\n\t\t}\n\t}\n}\n\nbool HaplotypeFrequencyComponent::compute_dosage_ld_measures(\n\tgenfile::VariantIdentifyingData const& source_snp,\n\tgenfile::VariantIdentifyingData const& target_snp,\n\tEigen::MatrixXd const& dosages,\n\tEigen::MatrixXd const& nonmissingness,\n\tstd::string const& variable_name_stub,\n\tstd::vector< genfile::SampleRange > const& sample_set,\n\tbool alwaysOutput\n) {\n\tbool includeInOutput = alwaysOutput ;\n\tEigen::RowVectorXd means = Eigen::RowVectorXd::Zero(2) ;\n\tEigen::RowVectorXd totals = Eigen::RowVectorXd::Zero(2) ;\n\tfor( std::size_t i = 0; i < sample_set.size(); ++i ) {\n\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\t\tstd::cerr << sample_set[i].begin() << \"-\" << sample_set[i].end() << \":\\n\" ;\n\t\tstd::cerr << dosages.rows() << \"x\" << dosages.cols()\n\t\t\t<< \", \" << nonmissingness.rows() << \"x\" << nonmissingness.cols() << \".\\n\" ;\n\t\tstd::cerr << dosages.block( 0, 0, std::min( int( dosages.rows() ), 10 ), dosages.cols() ) << \".\\n\" ;\n#endif\n\t\tmeans.array() += (\n\t\t\tdosages.block( sample_set[i].begin(), 0, sample_set[i].end() - sample_set[i].begin(), 2 ).array()\n\t\t\t* nonmissingness.block( sample_set[i].begin(), 0, sample_set[i].end() - sample_set[i].begin(), 2 ).array()\n\t\t).colwise().sum() ;\n\t\t\n\t\ttotals += nonmissingness.block( sample_set[i].begin(), 0, sample_set[i].end() - sample_set[i].begin(), 2 ).colwise().sum() ;\n\t}\n\n\tmeans.array() /= totals.array() ;\n\n\tEigen::Matrix2d covariance = Eigen::Matrix2d::Zero() ;\n\tEigen::Matrix2d nonmissing = Eigen::Matrix2d::Zero() ;\n\tfor( std::size_t i = 0; i < sample_set.size(); ++i ) {\n\t\t//Eigen::MatrixBase< Eigen::MatrixXd > block = (\n\t\tEigen::MatrixXd block = (\n\t\t\t(dosages.block( sample_set[i].begin(), 0,  sample_set[i].end() - sample_set[i].begin(), 2 ).rowwise() - means ).array()\n\t\t\t\t* nonmissingness.block( sample_set[i].begin(), 0,  sample_set[i].end() - sample_set[i].begin(), 2 ).array()\n\t\t) ;\n\t\tEigen::Block< Eigen::MatrixXd const > nonmissing_block = nonmissingness.block(\n\t\t\tsample_set[i].begin(), 0,  sample_set[i].end() - sample_set[i].begin(), 2\n\t\t) ;\n\n\t\tcovariance += block.transpose() * block ;\n\t\tnonmissing += nonmissing_block.transpose() * nonmissing_block ;\n\t}\n\t// Compute correlation as:\n\t// \n\tdouble r = covariance(0,1) / std::sqrt( covariance(0,0) * covariance(1,1) ) ;\n\n\tincludeInOutput = includeInOutput || (r*r >= m_min_r2 ) ;\n\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\tstd::cerr << \"means = \" << means << \".\\n\" ;\n\tstd::cerr << \"cov =\\n\" << covariance << \".\\n\" ;\n\tstd::cerr << \"r =\\n\" << r << \".\\n\" ;\n#endif\n\n\tif( includeInOutput ) {\n\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"dosage_r\", r  ) ;\n\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"dosage_r2\", r*r ) ;\n\t}\n\treturn includeInOutput ;\n}\n\nbool HaplotypeFrequencyComponent::compute_em_ld_measures(\n\tgenfile::VariantIdentifyingData const& source_snp,\n\tstd::vector< int > const& source_calls,\n\tstd::vector< uint32_t > const& source_ploidy,\n\tgenfile::VariantIdentifyingData const& target_snp,\n\tstd::vector< int > const& target_calls,\n\tstd::vector< uint32_t > const& target_ploidy,\n\tstd::string const& variable_name_stub,\n\tstd::vector< genfile::SampleRange > const& sample_set,\n\tbool alwaysOutput\n) {\n\t// Construct table of genotypes at each SNP.\n\tEigen::Matrix3d diploid_table = Eigen::Matrix3d::Zero() ;\n\tEigen::Matrix2d haploid_table = Eigen::Matrix2d::Zero() ;\n\t\n\ttabulate_calls(\n\t\tsample_set,\n\t\tsource_calls, source_ploidy,\n\t\ttarget_calls, target_ploidy,\n\t\t&diploid_table,\n\t\t&haploid_table\n\t) ;\n\t\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\tstd::cerr << \"SNP1: \" << source_snp << \"\\n\"\n\t\t<< \"SNP2: \" << target_snp << \"\\n\"\n\t\t<< \"diploids: \" << diploid_table << \".\\n\"\n\t\t<< \"haploids: \" << haploid_table << \".\\n\" ;\n\tstd::cerr << \"alwaysOutput is \" << ( alwaysOutput ? \"true\" : \"false\" ) << \".\\n\" ;\n#endif\n\n\tgenfile::VariantEntry::Integer const N = diploid_table.sum() + haploid_table.sum() ;\n\tbool includeInOutput = alwaysOutput ;\n\tgenfile::VariantEntry const missing = genfile::MissingValue() ;\n\n\tif( includeInOutput ) {\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"number_of_genotypes\", diploid_table.sum() ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"number_of_haplotypes\", haploid_table.sum() ) ;\n\t}\n\n\tif( N == 0 ) {\n\t\tif( includeInOutput ) {\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi00\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi01\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi10\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi11\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"D\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"Dprime\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"r\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"r2\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"dosage_r\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"dosage_r2\", missing ) ;\n\t\t}\n\t} else {\n\t\ttry {\n\t\t\tHaplotypeFrequencyLogLikelihood ll( diploid_table, haploid_table + m_prior ) ;\n\t\t\tHaplotypeFrequencyLogLikelihood::Vector pi( 4 ) ;\n\t\t\tpi.tail( 3 ) = ll.get_MLE_by_EM() ;\n\t\t\tpi(0) = 1.0 - pi.tail( 3 ).sum() ;\n\t\t\tdouble D = pi(0) * pi(3) - pi(1) * pi(2) ;\n\t\t\tdouble max_D ;\n\t\t\tif( D < 0 ) {\n\t\t\t\tmax_D = std::min( (pi(0) + pi(1)) * (pi(0)+pi(2)), (pi(1)+pi(3))*(pi(2)+pi(3)) ) ;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmax_D = std::min( (pi(0) + pi(1)) * (pi(1)+pi(3)), (pi(0)+pi(2))*(pi(2)+pi(3)) ) ;\n\t\t\t}\n\t\t\tdouble const Dprime = D / max_D ;\n\t\t\tdouble const r = D / std::sqrt( (pi(0)+pi(1)) * (pi(2)+pi(3)) * (pi(0)+pi(2)) * (pi(1)+pi(3))) ;\n\t\t\tdouble const r2 = r*r ;\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\t\t\tstd::cerr << \"r = \\n\" << std::setprecision(3) << r << \".\\n\" ;\n\t\t\tstd::cerr << \"r^2 = \" << r2 << \".\\n\" ;\n\t\t\tstd::cerr << \"D =\\n\" << D << \".\\n\" ;\n\t\t\tstd::cerr << \"Dprime =\\n\" << Dprime << \".\\n\" ;\n\t\t\tstd::cerr << \"pi = \" << pi.transpose() << \"\\n\" ;\n#endif\n\t\t\t\n\t\t\tincludeInOutput = includeInOutput || (r2 >= m_min_r2 ) ;\n\t\t\tif( includeInOutput ) {\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi00\", pi(0) ) ;\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi01\", pi(1) ) ;\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi10\", pi(2) ) ;\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi11\", pi(3) ) ;\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"D\", D ) ;\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"Dprime\", Dprime ) ;\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"r\", r ) ;\n\t\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"r2\", r2 ) ;\n\t\t\t}\n#if DEBUG_HAPLOTYPE_FREQUENCY_COMPONENT\n\t\tstd::cerr << \"Output complete.\\n\" ;\n#endif\n\t\t}\n\t\tcatch( genfile::OperationFailedError const& ) {\n\t\t\tm_ui_context.logger() << \"!! Could not compute haplotype frequencies for \" << source_snp << \", \" << target_snp << \".\\n\"\n\t\t\t\t<< \"!! table is:\\n\" << diploid_table << \".\\n\" ;\n\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi00\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi01\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi10\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"pi11\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"D\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"Dprime\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"r\", missing ) ;\n\t\t\tm_sink->store_per_variant_pair_data( source_snp, target_snp, variable_name_stub + \"r2\", missing ) ;\n\t\t}\n\t\n\n\t}\n\treturn includeInOutput ;\n}\n\nvoid HaplotypeFrequencyComponent::end_processing_snps() {\n\tif( m_sink.get() ) {\n\t\tm_sink->finalise() ;\n\t}\n}\n\nvoid HaplotypeFrequencyComponent::send_results_to( haplotype_frequency_component::FlatTableDBOutputter::UniquePtr sink ) {\n\tm_sink = sink ;\n}\n", "meta": {"hexsha": "33de2f8c890f62c04d3e81ed829d494077883dab", "size": 29686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/HaplotypeFrequencyComponent/src/HaplotypeFrequencyComponent.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/HaplotypeFrequencyComponent/src/HaplotypeFrequencyComponent.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/HaplotypeFrequencyComponent/src/HaplotypeFrequencyComponent.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": 36.4245398773, "max_line_length": 159, "alphanum_fraction": 0.6786363943, "num_tokens": 8869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.02161533280203908, "lm_q1q2_score": 0.00888629825698888}}
{"text": "#include <boost/intrusive/Fenwick_tree/fenwick_tree_algorithms.hpp>\n#include <boost/intrusive/Fenwick_tree/fenwick_tree_hook.hpp>\n#include <boost/intrusive/Fenwick_tree/fenwick_tree_iterator.hpp>\n\n\n#include<boost/intrusive/any_hook.hpp>\n#include <boost/intrusive/detail/get_value_traits.hpp>\n#include \"boost/intrusive/options.hpp\"\n#include <boost/intrusive/detail/is_stateful_value_traits.hpp>\n#include <boost/intrusive/detail/default_header_holder.hpp>\n#include \"boost/intrusive/detail/size_holder.hpp\"\n#include<iostream>\n#include <boost/intrusive/detail/config_begin.hpp>\n#include <boost/intrusive/intrusive_fwd.hpp>\n#include <boost/intrusive/detail/assert.hpp>\n#include <boost/intrusive/pointer_traits.hpp>\n#include <boost/intrusive/detail/mpl.hpp>\n#include <boost/intrusive/link_mode.hpp>\n#include <boost/intrusive/detail/reverse_iterator.hpp>\n#include <boost/intrusive/detail/uncast.hpp>\n#include <boost/intrusive/detail/array_initializer.hpp>\n#include <boost/intrusive/detail/exception_disposer.hpp>\n#include <boost/intrusive/detail/equal_to_value.hpp>\n#include <boost/intrusive/detail/key_nodeptr_comp.hpp>\n#include <boost/intrusive/detail/simple_disposers.hpp>\n#include <boost/intrusive/detail/algorithm.hpp>\n\n#include <boost/move/utility_core.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/intrusive/detail/minimal_less_equal_header.hpp>//std::less\n#include <cstddef>   //std::size_t, etc.\n\n#include <queue>\n\nnamespace boost {\n    namespace intrusive {\n\nstruct default_fenwick_tree_hook_applier\n{  \n    template <class T> \n    struct apply\n    { \n        typedef typename T::default_fenwick_tree_hook type;  \n    };  \n};\n\ntemplate<>\nstruct is_default_hook_tag<default_fenwick_tree_hook_applier>\n{  static const bool value = true;  };\n\nstruct fenwick_tree_defaults\n{\n   typedef default_fenwick_tree_hook_applier proto_value_traits;\n   static const bool constant_time_size = true;\n   typedef std::size_t size_type;\n   typedef void header_holder_type;\n};\n/*!\nThis class contains all the basic methods supported by fenwick tree. \n*/\ntemplate<typename ValueTraits, class SizeType, bool ConstantTimeSize, typename HeaderHolder>\nclass fenwick_tree_impl\n{\n    public:\n    typedef ValueTraits                                               value_traits;\n    typedef typename value_traits::node_traits node_traits;\n    typedef typename node_traits::node node;\n    typedef typename node::node_ptr node_ptr;\n    typedef typename value_traits::pointer pointer;\n    typedef typename pointer_traits<pointer>::element_type            value_type;\n    typedef typename pointer_traits<pointer>::reference               reference;\n    typedef fenwick_tree_algorithms<node_traits> algo;\n    typedef typename node_traits::const_node_ptr                      const_node_ptr;\n    typedef SizeType                                                  size_type;\n    typedef fenwick_tree_iterator<value_traits, false>                        iterator;\n    typedef fenwick_tree_iterator<value_traits, true>                         const_iterator;\n    typedef typename value_type::data_type data_type;\n    typedef typename detail::get_header_holder_type\n      < value_traits, HeaderHolder >::type                           header_holder_type;\n   private: \n   ///@cond\n   static const bool constant_time_size = ConstantTimeSize;\n   static const bool stateful_value_traits = detail::is_stateful_value_traits<value_traits>::value;\n   static const bool has_container_from_iterator =\n        detail::is_same< header_holder_type, detail::default_header_holder< node_traits > >::value;\n\n   ///@endcond\n   private:\n    typedef detail::size_holder<constant_time_size, size_type>          size_traits;\n   \n   node_ptr get_root_node()\n   { return data_.root_plus_size_.m_header.get_node(); }\n\n   const_node_ptr get_root_node() const\n   { return data_.root_plus_size_.m_header.get_node(); }\n\n   struct root_plus_size : public size_traits\n   {\n      header_holder_type m_header;\n   };\n\n   struct data_t : public ValueTraits\n   {\n      typedef typename fenwick_tree_impl::value_traits value_traits;\n      root_plus_size root_plus_size_;\n   } data_;\n    \n\n   size_traits &priv_size_traits()\n   {  return data_.root_plus_size_;  }\n\n   const size_traits &priv_size_traits() const\n   {  return data_.root_plus_size_;  }\n\n   const value_traits &priv_value_traits() const\n   {\n     return data_;  \n   }\n\n   value_traits &priv_value_traits()\n   {\n      return data_;\n   }\n\n   typedef typename boost::intrusive::value_traits_pointers\n      <ValueTraits>::const_value_traits_ptr const_value_traits_ptr;\n\n   const_value_traits_ptr priv_value_traits_ptr() const\n   {  return pointer_traits<const_value_traits_ptr>::pointer_to(this->priv_value_traits());  }\n\n\n    private:\n    \n    value_type *ptr;\n    value_type *input;\n\n    int start,end;\n    int total_nodes=0,max_index=0,level_one_nodes=0;\n    int leaf_nodes=0;\n    \n    node_ptr root;\n   \n   public:\n    /*!\n    This is a initialisation function where all the variables required for supporting fenwick tree are created and initialised with apporopriate values.\n    \\param input input array \n    \\param start starting index of input array\n    \\param end last index of input array \n    \\return Nothing <p></p>\n    <b> Complexity </b> O(N)\n    */\n    fenwick_tree_impl(value_type input[],int start,int end)\n    {\n        this->input=input;\n        this->start=start;\n        this->end=end;\n        total_nodes=end-start+2;\n        leaf_nodes=(total_nodes-1)/2+(total_nodes-1)%2;\n        max_index=total_nodes-1;\n        ptr=(value_type*)malloc((total_nodes-leaf_nodes)*sizeof(value_type));\n        root=value_traits::to_node_ptr(ptr[0]);\n        int nearest_pow=1;\n        while(nearest_pow<=max_index)\n        {\n            level_one_nodes++;\n            nearest_pow*=2;\n        }\n        root->children=(node_ptr*)malloc((level_one_nodes)*sizeof(node_ptr));\n        int nt=0;\n        std::queue<int> node_index;\n        node_index.push(0);\n        std::map<int,int> index_new,new_index;\n        while(!node_index.empty())\n        {\n            int index=node_index.front();\n            node_ptr temp_node;\n            if(index%2==1)\n            {\n                temp_node=value_traits::to_node_ptr(input[index-1]);\n            }\n            else\n            {\n                temp_node=value_traits::to_node_ptr(ptr[nt]);\n                index_new.insert(std::make_pair(nt,index));\n                new_index.insert(std::make_pair(index,nt));\n                nt++;\n            }\n            int temp=1,child_cnt=0;\n            while((index&temp)!=temp && (index|temp)<=max_index)\n            {\n                child_cnt++;\n                node_index.push(index|temp);\n                temp*=2;\n            }\n            temp_node->children=(node_ptr*)malloc(child_cnt*sizeof(node_ptr));\n            temp_node->child_cnt=child_cnt;\n            node_index.pop();\n        }\n        for(int i=0;i<total_nodes-leaf_nodes;i++)\n        {\n            node_ptr node=value_traits::to_node_ptr(ptr[i]);\n            int index=index_new[i];\n            int temp=1,child_par=0;\n            while((index&temp)!=temp && (index|temp)<=max_index)\n            {\n                int a=index|temp;\n                if(temp==1)\n                {\n                    node->children[child_par]=value_traits::to_node_ptr(input[(index|temp)-1]);\n                }\n                else\n                {\n                    node->children[child_par]=value_traits::to_node_ptr(ptr[new_index[index|temp]]);\n                }\n                child_par++;\n                temp*=2;\n            }      \n        }\n    }\n    private:\n        int cnt_run=1;\n    public:\n    /*!\n    This function builds the fenwick tree based on the given inputs\n    \\param func merging function\n    \\return Nothing\n    <p></p>\n    <b>Complexity :  </b> O(Nlog(N))    */\n    void build(auto func)\n    {\n        for(int i=0;i<total_nodes-leaf_nodes;i++)\n        {\n            ptr[i].value.a=0;\n        }\n        build_computation(func);\n    }\n    private:\n    void build_computation(auto func)\n    {\n        for(int i=0;i<=end;i++)\n        {\n            update(func,i,input[i]);\n        }\n    }\n    public:\n    /*!\n    This function updates fenwick tree according to the given inputs\n    \\param func merging function\n    \\param index updated index\n    \\param val updated_value\n    \\return Nothing\n    <p></p>\n    <b>Complexity :  </b> O(log(N))\n    */\n    void update(auto func,int index,value_type val)\n    {\n        std::stack<int> bit_pos;\n        int temp=1,position=0;\n        while(temp<=index+1)\n        {\n            int sb=temp&(index+1);\n            if(sb==temp)\n            {\n                bit_pos.push(position);\n            }    \n            position++;\n            temp*=2;\n        }\n        update_computation(root,func,bit_pos,val);\n    }\n    private:\n    void update_computation(node_ptr curr_node,auto func,std::stack<int> &bit_pos,value_type val)\n    {\n        while(bit_pos.size()!=0)\n        {\n            int child=bit_pos.top();\n            bit_pos.pop();\n            int curr_cnt=curr_node->child_cnt;\n            int size=bit_pos.size();\n            if(bit_pos.size()!=0)\n            {\n                for(int i=child+1;i<curr_cnt;i++)\n                {\n                    if(i!=0)\n                    {\n                        pointer p=value_traits::to_value_ptr(curr_node->children[i]);\n                        p->value=func(p->value,val.value);\n                    }\n                }\n            }\n            else\n            {\n                for(int i=child;i<curr_cnt;i++)\n                {\n                    if(i!=0)\n                    {\n                        pointer p=value_traits::to_value_ptr(curr_node->children[i]);\n                        p->value=func(p->value,val.value);\n                    }\n                }\n            }\n            curr_node=curr_node->children[child];\n        }\n    }\n    data_type curr_value;\n    public:\n    /*!\n    This function queries the fenwick tree and returns the answer corresponding to the given inputs.\n    \\param func merging function\n    \\param index index till which fenwick tree needs to be queried.\n    \\return the query value over the range given in input.<p></p>\n    <b>Complexity :  </b> O(log(N)) \n    */\n    data_type query(auto func,int index)\n    {\n        std::stack<int> bit_pos;\n        int temp=1,cnt=0;\n        while(temp<=index+1)\n        {\n            int a=temp&(index+1);\n            if(a==temp)\n            {\n                bit_pos.push(cnt);\n            }    \n            cnt++;\n            temp*=2;\n        }\n        query_computation(root,func,bit_pos);\n        return curr_value;\n    }\n    private:\n    void query_computation(node_ptr curr_node,auto func,std::stack<int> &bit_pos)\n    {\n        int flag=1;\n        while(!bit_pos.empty())\n        {\n            int child=bit_pos.top();\n            bit_pos.pop();\n            pointer p=value_traits::to_value_ptr(curr_node->children[child]);\n            if(flag)\n            {\n                curr_value=p->value;\n                flag=0;\n            }\n            else\n            {\n                curr_value=func(curr_value,p->value);\n            }\n            curr_node=curr_node->children[child];\n        }\n    }    \n    public:\n    /*!\nThis returns an iterator to the root node or source node of fenwick tree.\n*/\n    iterator get_root()\n    {\n        return iterator(root,this->priv_value_traits_ptr());\n    }\n};\n\n#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\ntemplate<class T, class ...Options>\n#else\ntemplate<class T, class O1 = void, class O2 = void, class O3 = void, class O4 = void>\n#endif\nstruct make_fenwick_tree\n{\n   public:\n   typedef typename pack_options\n      < fenwick_tree_defaults,\n      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\n         O1, O2, O3, O4\n         #else\n         Options...\n         #endif\n         >::type packed_options;\n\n   typedef typename detail::get_value_traits\n      <T, typename packed_options::proto_value_traits>::type value_traits;\n   /*!\n   <ul>\n    <li>This is the main class which contains all the methods supported by fenwick tree.</li>\n    <li>This class is derived into \"fenwick_tree\" class by giving appropriate inputs.</li>\n   </ul>\n   */\n   typedef fenwick_tree_impl\n      <value_traits,\n        typename packed_options::size_type,\n         packed_options::constant_time_size,\n         typename packed_options::header_holder_type\n   > implementation_defined;\n   typedef implementation_defined type;\n};\n\n#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED\n\n#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\ntemplate<class T, class O1, class O2, class O3, class O4>\n#else\ntemplate<class T, class ...Options>\n#endif\nclass fenwick_tree \n   : public make_fenwick_tree<T,\n      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\n      O1, O2, O3, O4\n      #else\n      Options...\n      #endif\n   >::type\n{\n    public:\n       typedef typename make_fenwick_tree\n      <T,\n      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\n      O1, O2, O3, O4\n      #else\n      Options...\n      #endif\n      >::type      Base;\n\n public:\n   typedef typename Base::value_traits          value_traits;\n   \n    public:\n    /*!\n        <ul>\n        <li> This is the first and main function used while working with any data structure.</li>\n        <li>This calls the \"fenwick_tree_impl\" function which does initialisation and declaration of variables.</li>\n        </ul>\n    */\n    fenwick_tree(T input[],int start,int end)\n        : Base(input,start,end)\n    {\n\n    };\n};\n\n}\n}\n#endif ", "meta": {"hexsha": "5eecf5b78d5da89c6947608aa7c40b31fbb2d05a", "size": 13574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/intrusive/Fenwick_tree/fenwick_tree.hpp", "max_stars_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_stars_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T18:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-22T17:12:44.000Z", "max_issues_repo_path": "include/boost/intrusive/Fenwick_tree/fenwick_tree.hpp", "max_issues_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_issues_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-05-31T10:01:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-26T15:14:26.000Z", "max_forks_repo_path": "include/boost/intrusive/Fenwick_tree/fenwick_tree.hpp", "max_forks_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_forks_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "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.7104072398, "max_line_length": 152, "alphanum_fraction": 0.6097686754, "num_tokens": 3090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.0206459314924601, "lm_q1q2_score": 0.008880792992210472}}
{"text": "#include \"lipton-tarjan.h\"\n#include \"colors.h\"\n#include \"strutil.h\"\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <csignal>\n#include <boost/lexical_cast.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp> \n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/range/irange.hpp> \n#include <boost/graph/copy.hpp>\nusing namespace std;\nusing namespace boost; \n#define STLALL(x) (x).begin(), (x).end()\n\n#define HEADER_COL GREEN\n\nint levi_civita(uint i, uint j, uint k)\n{\n        if( i == j || j == k || k == i ) return 0; \n        if( i == 1 && j == 2 && k == 3 ) return 1;\n        if( i == 2 && j == 3 && k == 1 ) return 1;\n        if( i == 3 && j == 1 && k == 2 ) return 1;\n        return -1;\n} \n\nbool on_cycle(VertDesc v, vector<VertDesc> const& cycle, Graph const& g)\n{\n        return find(STLALL(cycle), v) != cycle.end();\n}\n\nbool on_cycle(EdgeDesc e, vector<VertDesc> const& cycle, Graph const& g)\n{\n        auto src = source(e, g);\n        auto tar = target(e, g);\n        return on_cycle(src, cycle, g) && on_cycle(tar, cycle, g);\n}\n\nenum InsideOut {INSIDE, OUTSIDE, ON};\n\nInsideOut edge_inside_cycle(EdgeDesc e, VertDesc common_vert, vector<VertDesc> const& cycle, Graph const& g, Embedding const& em)\n{\n        //cout << \"cycle: \";\n        for( uint i = 0; i < cycle.size(); ++i ) cout << cycle[i] << ' ';\n        //cout << '\\n';\n        auto src = source(e, g);\n        auto tar = target(e, g);\n        if( on_cycle(e, cycle, g) ) return ON;\n        //cout << \"      testing if edge \" << src << \", \" << tar << \" is inside the cycle: \";\n        //cout << \"      common_vert:    \" << common_vert   << '\\n';\n        auto it     = find(STLALL(cycle), common_vert);\n        if( it == cycle.end() ){ cout << \"      not here at all!\\n\"; assert(0); }\n        assert(*it == common_vert);\n        auto before = it   == cycle.begin() ?  cycle.end  ()-1   : it-1;\n        auto after  = it+1 == cycle.end  () ?  cycle.begin()     : it+1; \n        auto other  = (source(e, g) == common_vert) ?  target(e, g)        : source(e, g); \n        \n        //cout << '\\n';\n        //cout << \"      it:     \" << *it         << '\\n';\n        //cout << \"      v:      \" << common_vert << '\\n';\n        //cout << \"      before: \" << *before     << '\\n';\n        //cout << \"      after:  \" << *after      << '\\n';\n        //cout << \"      other:  \" << other       << '\\n';\n\n        vector<uint> perm;\n        set<VertDesc> seenbefore;\n        for( auto& tar_it : em[*it] ){ // why does this contain duplicates?\n                auto src = source(tar_it, g);\n                auto tar = target(tar_it, g);\n                if( src != common_vert ) swap(src, tar);\n                assert(src == common_vert);\n                if( seenbefore.find(tar) != seenbefore.end() ) continue;\n                seenbefore.insert(tar);\n\n                if(      tar == other   ) perm.push_back(1);\n                else if( tar == *before ) perm.push_back(2);\n                else if( tar == *after  ) perm.push_back(3);\n        } \n        assert(perm.size() == 3);\n        if( levi_civita(perm[0], perm[1], perm[2]) == 1 ){ return INSIDE;\n        } else { return OUTSIDE; }\n}\n\n\nstruct BFSVert\n{\n        BFSVert() : parent(Graph::null_vertex()), level(0), descendant_cost(0) {}\n\n        VertDesc parent;\n        int      level;\n        uint     descendant_cost;\n};\n\nstruct BFSVisitorData\n{\n        map<VertDesc, set<VertDesc>> children;\n        map<VertDesc, BFSVert>       verts;\n        int                          num_levels;\n        Graph*                       g;\n        VertDesc                     root;\n\n        BFSVisitorData(Graph* g) : g(g), num_levels(0), root(Graph::null_vertex()) {}\n\n        void reset(Graph* g)\n        {\n                children.clear();\n                verts   .clear();\n                num_levels = 0;\n                this->g = g;\n                root = Graph::null_vertex();\n        }\n        \n        bool is_tree_edge(EdgeDesc e) const\n        { \n                //cout << \"testing is tree edge \" << to_string(e, *g) << '\\n';\n                auto src = source(e, *g);\n                auto tar = target(e, *g); \n                auto src_it = verts.find(src);\n                auto tar_it = verts.find(tar);\n                //cout << \"src: \" << src << '\\n';\n                //cout << \"tar: \" << tar << '\\n';\n                assert(src_it != verts.end());\n                assert(tar_it != verts.end());\n                return src_it->second.parent == tar || tar_it->second.parent == src;\n        }\n\n        uint edge_cost(EdgeDesc e, vector<VertDesc> const& cycle, Graph const& g) const\n        {\n                assert(is_tree_edge(e));\n\n                auto v = source(e, g); \n                auto w = target(e, g); \n                auto v_it = verts.find(v); assert(v_it != verts.end());\n                auto w_it = verts.find(w); assert(w_it != verts.end());\n                if( !on_cycle(v, cycle, g) ) swap(v, w);\n\n                assert( on_cycle(v, cycle, g));\n                assert(!on_cycle(w, cycle, g));\n\n                uint total = num_vertices(g);\n\n                assert(w_it->second.parent == v || v_it->second.parent == w);\n                return w_it->second.parent == v ? w_it->second.descendant_cost : total - v_it->second.descendant_cost;\n        } \n\n        void print_costs  () const {for( auto& v : verts ) cout << \"descendant cost of vertex \" << v.first << \" is \" << v.second.descendant_cost << '\\n';}\n        void print_parents() const {for( auto& v : verts ) cout << \"parent of \" << v.first << \" is \" << v.second.parent << '\\n';}\n};\n\nstruct BFSVisitor : public default_bfs_visitor\n{\n        BFSVisitorData& data;\n\n        BFSVisitor(BFSVisitorData& data) : data(data) {}\n\n        template<typename Edge, typename Graph> void tree_edge(Edge e, Graph const& g)\n        {\n                auto parent = source(e, g);\n                auto child  = target(e, g);\n                cout << \"  tree edge \" << parent << \", \" << child << '\\n';\n                data.verts[child].parent = parent;\n                data.verts[child].level  = data.verts[parent].level + 1;\n                data.num_levels = max(data.num_levels, data.verts[child].level + 1);\n                if( Graph::null_vertex() != parent ) data.children[parent].insert(child);\n\n                VertDesc v = child;\n                data.verts[v].descendant_cost = 1;\n                //cout << \"     vertex/descendant cost: \";\n                //cout << v << '/'  << data.verts[v].descendant_cost << \"   \";\n                while( data.verts[v].level ){\n                        v =  data.verts[v].parent;\n                        ++data.verts[v].descendant_cost;\n                        //cout << v << '/'  << data.verts[v].descendant_cost << \"   \";\n                } \n                //cout << '\\n';\n        } \n};\n\nuint theorem4(uint partition, Graph const& g)\n{\n        /*\n        Assume G is connected.\n        Partition the vertices into levels according to their distance from some vertex v.\n        L[l] = # of vertices on level l\n        If r is the maximum distance of any vertex from v, define additional levels -1 and r+1 containing no vertices\n        l1 = the level such that the sum of costs in levels 0 thru l1-1 < 1/2, but the sum of costs in levels 0 thru l1 is >= 1/2\n        (If no such l1 exists, the total cost of all vertices < 1/2, and B = C = {} and return true)\n        k = # of vertices on levels 0 thru l1.\n        Find a level l0 such that l0 <= l1 and |L[l0]| + 2(l1-l0) <= 2sqrt(k)\n        Find a level l2 such that l1+1 <= l2 and |L[l2] + 2(l2-l1-1) <= 2sqrt(n-k)\n        If 2 such levels exist, then by Lemma 3 the vertices of G can be partitioned into three sets A, B, C such that no edge joins a vertex in A with a vertex in B,\n        neither A or C has cost > 2/3, and C contains no more than 2(sqrt(k) + sqrt(n-k)) vertices.\n        But 2(sqrt(k) + sqrt(n-k) <= 2(sqrt(n/2) + sqrt(n/2)) = 2sqrt(2)sqrt(n)\n        Thus the theorem holds if suitable levels l0 and l2 exist\n                Suppose a suitable level l0 does not exist.  Then, for i <= l1, L[i] >= 2sqrt(k) - 2(l1-i)\n                Since L[0] = 1, this means 1 >= 2sqrt(k) - 2l1 and l1 + 1/2 >= sqrt(k).  Thus l1 = floor(l1 + 1/2) > \n                Contradiction\n\n        Now suppose G is not connected\n        Let G1, G2, ... , Gk be the connected components of G, with vertex sets V1, V2, ... , Vk respectively.\n        If no connected component has total vertex cost > 1/3, let i be the minimum index such that the total cost of V1 U V2 U ... U Vi > 1/3\n        A = V1 U V2 U ... U Vi\n        B = Vi+1 U Vi+2 U ... U Vk\n        C = {}\n        Since i is minimum and the cost of Vi <= 1/3, the cost of A <= 2/3. return true;\n        If some connected component (say Gi) has total vertex cost between 1/3 and 2/3,\n        A = Vi\n        B = V1 U ... U Vi-1 U Vi+1 U ... U Vk\n        C = {}\n        return true\n\n        Finally, if some connected component (say Gi) has total vertex cost exceeding 2/3,\n        apply the above argument to Gi\n        Let A*, B*, C* be the resulting partition.\n        A = set among A* and B* with greater cost\n        C = C*\n        B = remanining vertices of G\n        Then A and B have cost <= 2/3, g\n        return true;\n\n        In all cases the separator C is either empty or contained in only one connected component of G\n        */\n        return partition;\n}\n\nstruct ScanVisitor\n{\n        map<VertDesc, bool>*          table;\n        Graph*                        g;\n        VertDesc                      x;\n        int                           l0;\n        set<pair<VertDesc, VertDesc>> edges_to_add, edges_to_delete;\n\n        ScanVisitor(map<VertDesc, bool>* table, Graph* g, VertDesc x, int l0) : table(table), g(g), x(x), l0(l0) {}\n\n        void foundedge(VertDesc V, EdgeDesc e)\n        {\n                auto v = source(e, *g);\n                auto w = target(e, *g);\n                if( V != v ) swap(v, w);\n                assert(V == v);\n                cout << \"foundedge \" << v << \", \" << w;\n                if ( !(*table)[w] ){\n                        (*table)[w] = true;\n                        assert(x != w); \n                        cout << \"   !!!!!!!going to add \" << x << \", \" << w;\n                        edges_to_add.insert(make_pair(x, w));\n                }\n                cout << \"     going to delete \" << v << \", \" << w;\n                edges_to_delete.insert(make_pair(v, w)); \n                cout << '\\n';\n        }\n\n        void finish()\n        {\n                cout << \"finishing\\n\";\n                cout << \"edges to add size: \" << edges_to_add.size() << '\\n';\n                cout << \"adding: \";\n                for( auto& p : edges_to_add    ){\n                        assert(p.first != p.second);\n                        cout << '(' << p.first << \", \" << p.second << \")   \";\n                        add_edge(p.first, p.second, *g);\n                }\n                cout << '\\n';\n                cout << \"edges to remove size: \" << edges_to_delete.size() << '\\n';\n                cout << \"removing: \";\n                for( auto& p : edges_to_delete ){ \n                        cout << '(' << p.first << \", \" << p.second << \")   \";\n                        remove_edge(p.first, p.second, *g);\n                }\n                cout << '\\n';\n        }\n\n        void scan_nonsubtree_edges(VertDesc v, Graph const& g, Embedding const& em, BFSVisitorData const& bfs)\n        {\n                auto v_it = bfs.verts.find(v);\n                assert(v_it != bfs.verts.end());\n                if( v_it->second.level > l0 ) return;\n                for( auto e : em[v] ){\n                        auto src = source(e, g);\n                        auto tar = target(e, g);\n                        if( src == tar ) continue; // ?????\n\n                        if( !bfs.is_tree_edge(e) ){\n                                foundedge(v, e);\n                                continue;\n                        }\n                        if( src != v ) swap(src, tar);\n                        assert(src == v); \n                        auto tar_it = bfs.verts.find(tar);\n                        if( tar_it->second.level > l0 ) foundedge(v, e);\n                }\n                //cout << \"looking for children of \" << v << '\\n';\n                auto vvv   = bfs.children.find(v);\n                if( vvv == bfs.children.end() ) return; // no children\n                //cout << \"from \" << v << \" looking for children\\n\";\n                for( auto& c : vvv->second ){\n                        //cout << \"child: \" << c << '\\n'; \n                        scan_nonsubtree_edges(c, g, em, bfs);\n                }\n        }\n\n};\n\nvoid reset_vertex_indices(Graph& g)\n{\n        VertIter vi, vend;\n        uint i = 0;\n        for( tie(vi, vend) = vertices(g); vi != vend; ++vi, ++i ) put(vertex_index, g, *vi, i); \n}\n\nstruct Em\n{\n        EmbeddingStorage* storage;\n        Embedding*        em;\n        Graph*            g;\n\n        Em(Graph* g) : g(g), storage(new EmbeddingStorage(num_vertices(*g))), em(new Embedding(storage->begin())) \n        {\n                testplanar();\n        } \n\n        bool testplanar() {return boyer_myrvold_planarity_test(boyer_myrvold_params::graph = *g, boyer_myrvold_params::embedding = *em);}\n\n        void print()\n        {\n                cout << CYAN << \"\\n************** Embedding ************\\n\" << RESET;\n                VertIter vi, vend;\n                for( tie(vi, vend) = vertices(*g); vi != vend; ++vi ){\n                        cout << \"vert \" << *vi << \": \";\n                        Embedding& embedding = *em;\n                        for( auto ei = embedding[*vi].begin(); ei != embedding[*vi].end(); ++ei ){\n                                auto src = source(*ei, *g);\n                                auto tar = target(*ei, *g);\n                                if( tar == *vi ) swap(src, tar);\n                                cout << tar << ' ';\n                        }\n                        cout << \"\\n\"; \n                }\n                cout << CYAN << \"*************************************\\n\" << RESET;\n        }\n\n        ~Em()\n        {\n                delete storage;\n                delete em;\n        }\n};\n\nEdgeIndex reset_edge_index(Graph const& g)\n{\n        EdgeIndex edgedesc_to_uint; \n        EdgesSizeType num_edges = 0;\n        EdgeIter ei, ei_end;\n        for( tie(ei, ei_end) = edges(g); ei != ei_end; ++ei ) edgedesc_to_uint[*ei] = num_edges++;\n        return edgedesc_to_uint;\n} \n\nvoid makemaxplanar(Graph& g)\n{ \n        auto index = reset_edge_index(g);\n        Em em(&g);\n        em.testplanar();\n        make_biconnected_planar(g, *em.em, index);\n\n        reset_edge_index(g);\n        em.testplanar();\n\n        make_maximal_planar(g, *em.em);\n\n        reset_edge_index(g);\n        assert(em.testplanar());\n} \n\nvector<VertDesc> ancestors(VertDesc v, BFSVisitorData const& vis)\n{\n        //cout << \"first v: \" << v << '\\n';\n        //cout << \"root: \" << vis.root << '\\n';\n        vector<VertDesc> ans = {v};\n        while( v != vis.root ){\n                auto v_it = vis.verts.find(v);\n                assert(v_it != vis.verts.end());\n                v = v_it->second.parent;\n                ans.push_back(v);\n                //cout << \"pushing back v: \" << v << '\\n';\n        }\n        return ans;\n}\n\nVertDesc common_ancestor(vector<VertDesc> const& ancestors_v, vector<VertDesc> const& ancestors_w, BFSVisitorData const& vis)\n{\n        uint i, j;\n        for( i = 0; i < ancestors_v.size(); ++i ) for( j = 0; j < ancestors_w.size(); ++j ) if( ancestors_v[i] == ancestors_w[j] ) return ancestors_v[i];\n        assert(0);\n        return ancestors_v[i];\n}\n\nvector<VertDesc> get_cycle(VertDesc v, VertDesc w, VertDesc ancestor, BFSVisitorData const& vis_data)\n{\n        vector<VertDesc> cycle, tmp;\n        VertDesc cur;\n        cur = v; while( cur != ancestor ){ cycle.push_back(cur); auto cur_it = vis_data.verts.find(cur); cur = cur_it->second.parent; } cycle.push_back(ancestor); \n        cur = w; while( cur != ancestor ){ tmp  .push_back(cur); auto cur_it = vis_data.verts.find(cur); cur = cur_it->second.parent; }\n        reverse(STLALL(tmp));\n        cycle.insert(cycle.end(), STLALL(tmp));\n        return cycle;\n}\n\nvector<VertDesc> get_cycle(VertDesc v, VertDesc w, BFSVisitorData const& vis_data)\n{ \n        auto parents_v   = ancestors(v, vis_data);\n        auto parents_w   = ancestors(w, vis_data); \n        auto ancestor    = common_ancestor(parents_v, parents_w, vis_data);\n        cout << \"common ancestor: \" << ancestor << '\\n'; \n        return get_cycle(v, w, ancestor, vis_data);\n}\n\nvoid kill_vertex(VertDesc v, Graph& g)\n{\n        cout << \"killing vertex \" << v << '\\n';\n        auto i = vert2uint[v];\n        uint2vert.erase(i);\n        vert2uint.erase(v);\n        clear_vertex(v, g);\n        remove_vertex(v, g);\n}\n\nEdgeDesc arbitrary_nontree_edge(Graph const& g, BFSVisitorData const& vis_data)\n{ \n        EdgeIter ei, ei_end;\n        for( tie(ei, ei_end) = edges(g); ei != ei_end; ++ei ){\n                auto src = source(*ei, g);\n                auto tar = target(*ei, g);\n                assert(edge(src, tar, g).second); // exists\n                assert(src != tar); \n                if( !vis_data.is_tree_edge(*ei) ) break;\n        }\n        assert(ei != ei_end);\n        assert(!vis_data.is_tree_edge(*ei));\n        EdgeDesc chosen_edge = *ei;\n        cout << \"arbitrarily choosing nontree edge: \" << to_string(chosen_edge, g) << '\\n';\n        return chosen_edge;\n}\n\nset<VertDesc> get_neighbors(VertDesc v, Graph const& g)\n{ \n        set<VertDesc> neighbors;\n        OutEdgeIter e_cur, e_end;\n        for( tie(e_cur, e_end) = out_edges(v, g); e_cur != e_end; ++e_cur ){ auto ne = target(*e_cur, g); neighbors.insert(ne); cout << \"      vertex \" << v << \" has neighbor \" << ne << '\\n'; }\n        return neighbors;\n}\n\nset<VertDesc> get_intersection(set<VertDesc> const& a, set<VertDesc> const& b)\n{\n        set<VertDesc> c;\n        set_intersection(STLALL(a), STLALL(b), inserter(c, c.begin())); \n        for( auto& i : c ) cout << \"      set intersection: \" << i << '\\n'; \n        assert(c.size() == 2);\n        return c;\n} \n\nstruct CycleCost\n{\n        uint inside {}, outside {};\n};\n\nbool cost_swapped = false;\n\nCycleCost compute_cycle_cost(vector<VertDesc> const& cycle, Graph const& g, BFSVisitorData const& vis_data, Em const& em)\n{\n        CycleCost cc;\n        for( auto& v : cycle ){\n                //cout << \"   scanning cycle vert \" << v << '\\n';\n                for( auto e = out_edges(v, g); e.first != e.second; ++e.first ) if( vis_data.is_tree_edge(*e.first) && !on_cycle(*e.first, cycle, g) ){\n                        uint cost = vis_data.edge_cost(*e.first, cycle, g);\n                        //cout << \"      scanning incident tree edge \" << to_string(*e.first, g) << \"   cost: \" << cost << '\\n';\n                        auto insideout = edge_inside_cycle(*e.first, v, cycle, g, *em.em);\n                        assert(insideout != ON);\n                        bool is_inside = (insideout == INSIDE);\n                        (is_inside ? cc.inside : cc.outside) += cost;\n                }\n        }\n        return cc;\n}\n\nstruct NotPlanar\n{\n};\n\nPartition lipton_tarjan(Graph& g, Graph& g_orig)\n{\n        cout << HEADER_COL << \"---------------------------- 1 - Check Planarity  ------------\\n\" << RESET;\n        Em em1(&g);\n        if( !em1.testplanar() ) throw NotPlanar();\n        cout << \"planar ok\\n\";\n        print_graph(g);\n\n        cout << HEADER_COL << \"---------------------------- 2 - Connected Components --------\\n\" << RESET;\n        VertDescMap idx; \n        associative_property_map<VertDescMap> vertid_to_component(idx);\n        VertIter vit, vjt;\n        tie(vit, vjt) = vertices(g);\n        for( uint i = 0; vit != vjt; ++vit, ++i ) put(vertid_to_component, *vit, i);\n        uint components = connected_components(g, vertid_to_component);\n\n        cout << \"# of components: \" << components << '\\n';\n        vector<uint> verts_per_comp(components, 0);\n        for( tie(vit, vjt) = vertices(g); vit != vjt; ++vit ) ++verts_per_comp[vertid_to_component[*vit]];\n        uint biggest_component = 0;\n        uint biggest_size      = 0;\n        bool too_big           = false;\n        for( uint i = 0; i < components; ++i ){\n                if( 3*verts_per_comp[i] > 2*num_vertices(g) ){\n                        cout << \"too big\\n\";\n                        too_big = true;\n                }\n                if( verts_per_comp[i] > biggest_size ){\n                        biggest_size = verts_per_comp[i];\n                        biggest_component = i;\n                }\n        }\n\n        if( !too_big ){\n                theorem4(0, g);\n                return {};\n        }\n        cout << \"biggest component: \" << biggest_component << '\\n';\n\n        cout << HEADER_COL << \"---------------------------- 3 - BFS and Levels ------------\\n\" << RESET;\n        BFSVisitorData vis_data(&g);\n        auto root = *vertices(g).first;\n        vis_data.root = root;\n        breadth_first_search(g, root, visitor(BFSVisitor(vis_data)));\n\n        vector<uint> L(vis_data.num_levels + 1, 0);\n        for( auto& d : vis_data.verts ) ++L[d.second.level];\n\n        for( tie(vit, vjt) = vertices(g); vit != vjt; ++vit ) cout << \"level/cost of vert \" << *vit << \": \" << vis_data.verts[*vit].level << '\\n';\n        for( uint i = 0; i < L.size(); ++i ) cout << \"L[\" << i << \"]: \" << L[i] << '\\n';\n\n        cout << HEADER_COL << \"---------------------------- 4 - l1 and k  ------------\\n\" << RESET;\n        uint k = L[0]; \n        int l[3];\n        l[1] = 0;\n        while( k <= num_vertices(g)/2 ) k += L[++l[1]];\n        cout << \"k:  \" << k    << \"      # of verts in levels 0 thru l1\\n\";\n        cout << \"l1: \" << l[1] << \"      total cost of levels 0 thru l1 barely exceeds 1/2\\n\";\n\n        cout << HEADER_COL << \"---------------------------- 5 - Find More Levels -------\\n\" << RESET;\n        float sq  = 2 * sqrt(k); \n        float snk = 2 * sqrt(num_vertices(g) - k); \n        cout << \"sq:    \" << sq << '\\n';\n        cout << \"snk:   \" << snk << '\\n';\n\n        l[0] = l[1];     for( ;; ){ float val = L.at(l[0]) + 2*(l[1] - l[0]);     if( val <= sq  ) break; --l[0]; } cout << \"l0: \" << l[0] << \"     highest level <= l1\\n\";\n        l[2] = l[1] + 1; for( ;; ){ float val = L.at(l[2]) + 2*(l[2] - l[1] - 1); if( val <= snk ) break; ++l[2]; } cout << \"l2: \" << l[2] << \"     lowest  level >= l1 + 1\\n\";\n\n        cout << HEADER_COL << \"---------------------------- 6 - Shrinktree -------------\\n\" << RESET;\n        cout << \"n: \" << num_vertices(g) << '\\n'; \n\n        vector<VertDesc> replaceverts;\n        tie(vit, vjt) = vertices(g); \n        for( auto next = vit; vit != vjt; vit = next ){\n                ++next;\n                if( vis_data.verts[*vit].level >= l[2] ){\n                        cout << \"deleting vertex \" << *vit << \" of level l2 \" << vis_data.verts[*vit].level << \" >= \" << l[2] << '\\n';\n                        kill_vertex(*vit, g);\n                }\n                if( vis_data.verts[*vit].level <= l[0] ){\n                        cout << \"going to replace vertex \" << *vit << \" of level l0 \" << vis_data.verts[*vit].level << \" <= \" << l[0] << '\\n';\n                        replaceverts.push_back(*vit);\n                }\n        }\n\n        auto x = add_vertex(g); uint2vert[vert2uint[x] = 999999] = x; \n        map<VertDesc, bool> t;\n        for( tie(vit, vjt) = vertices(g); vit != vjt; ++vit ){\n                t[*vit] = vis_data.verts[*vit].level <= l[0];\n                cout << \"vertex \" << *vit << \" at level \" << vis_data.verts[*vit].level << \" is \" << (t[*vit] ? \"TRUE\" : \"FALSE\") << '\\n';\n        }\n\n        reset_vertex_indices(g);\n        reset_edge_index(g);\n        Em em(&g);\n        assert(em.testplanar());\n\n        ScanVisitor svis(&t, &g, x, l[0]);\n        svis.scan_nonsubtree_edges(*vertices(g).first, g, *em.em, vis_data);\n        svis.finish();\n\n        auto x_gone = Graph::null_vertex();\n        if( !degree(x, g) ){\n                cout << \"no edges to x found, deleting\\n\";\n                kill_vertex(x, g);\n                x_gone = *vertices(g).first;\n                cout << \"x_gone: \" << x_gone << '\\n';\n        } else {\n                // delete all vertices x has replaced\n                for( auto& v : replaceverts ) kill_vertex(v, g);\n        }\n\n        cout << HEADER_COL << \"-------------------- 7 - New BFS and Make Max Planar -----\\n\" << RESET;\n        reset_vertex_indices(g);\n        reset_edge_index(g);\n        vis_data.reset(&g);\n        vis_data.root = (x_gone != Graph::null_vertex()) ? x_gone : x;\n        ++vis_data.verts[vis_data.root].descendant_cost;\n\n        cout << \"root: \" << vis_data.root << '\\n'; \n        cout << \"n:    \" << num_vertices(g) << '\\n';\n\n        breadth_first_search(g, x_gone != Graph::null_vertex() ? x_gone: x, visitor(BFSVisitor(vis_data))); \n        makemaxplanar(g);\n        reset_vertex_indices(g);\n        reset_edge_index(g);\n\n        print_graph(g);\n\n        cout << HEADER_COL << \"----------------------- 8 - Locate Cycle -----------------\\n\" << RESET; \n        auto chosen_edge = arbitrary_nontree_edge(g, vis_data);\n        auto v1          = source(chosen_edge, g);\n        auto w1          = target(chosen_edge, g); \n        cout << \"ancestors v1...\\n\";\n        auto parents_v   = ancestors(v1, vis_data);\n        cout << \"ancestors v2...\\n\";\n        auto parents_w   = ancestors(w1, vis_data); \n        auto ancestor    = common_ancestor(parents_v, parents_w, vis_data);\n        cout << \"common ancestor: \" << ancestor << '\\n'; \n        auto cycle = get_cycle(v1, w1, ancestor, vis_data);\n\n        Em   em2(&g);\n        auto cc = compute_cycle_cost(cycle, g, vis_data, em2); \n        if( cc.outside > cc.inside ){\n                swap(cc.outside, cc.inside);\n                cost_swapped = true;\n                cout << \"!!!!!! cost swapped !!!!!!!!\\n\";\n        }\n        cout << \"total inside cost:  \" << cc.inside  << '\\n'; \n        cout << \"total outside cost: \" << cc.outside << '\\n'; \n\n        cout << HEADER_COL << \"---------------------------- 9 - Improve Separator -----------\\n\" << RESET;\n        print_edges(g);\n\n        while( cc.inside > num_vertices(g)*2./3 ){ \n                cout << RED << \"chosen_edge: \" << to_string(chosen_edge, g) << '\\n';\n                cout << \"const inside: \" << cc.inside  << '\\n';\n                cout << \"const outide: \" << cc.outside << '\\n';\n                cout << \"looking for a better cycle\\n\" << RESET;\n\n                auto vi = source(chosen_edge, g);\n                auto wi = target(chosen_edge, g);\n                assert(!vis_data.is_tree_edge(chosen_edge));\n                EdgeDesc next_edge;\n                cout << \"   vi: \" << vi << '\\n';\n                cout << \"   wi: \" << wi << '\\n';\n\n                auto neighbors_v = get_neighbors(vi, g);\n                auto neighbors_w = get_neighbors(wi, g); \n                auto intersect   = get_intersection(neighbors_v, neighbors_w); \n                assert(intersect.size() == 2);\n                cout << \"   intersectbegin: \" << *intersect.begin() << '\\n';\n\n                auto eee = edge(vi, *intersect.begin(), g);\n                cout << \"eee: \" << to_string(eee.first, g) << '\\n';\n                assert(eee.second);\n\n                InsideOut insideout = edge_inside_cycle(eee.first, *intersect.begin(), cycle, g, *em2.em);\n                auto y = (insideout == INSIDE) ? *intersect.begin() : *(++intersect.begin());\n\n                cout << \"   y: \" << y << '\\n';\n                auto viy_e = edge(vi, y, g); assert(viy_e.second); auto viy = viy_e.first;\n                auto ywi_e = edge(y, wi, g); assert(ywi_e.second); auto ywi = ywi_e.first; \n                if ( vis_data.is_tree_edge(viy) || vis_data.is_tree_edge(ywi) ){\n                        cout << MAGENTA << \"   at least one tree edge\\n\" << RESET;\n                        next_edge = vis_data.is_tree_edge(viy) ? ywi : viy;\n                        assert(!vis_data.is_tree_edge(next_edge));\n\n                        // Compute the cost inside the (vi+1 wi+1) cycle from the cost inside the (vi, wi) cycle and the cost of vi, y, and wi.  See Fig 4.\n                        uint cost1 = vis_data.verts[vi].descendant_cost;\n                        uint cost2 = vis_data.verts[y ].descendant_cost;\n                        uint cost3 = vis_data.verts[wi].descendant_cost;\n                        uint cost4 = cc.inside;\n                        auto new_cycle = get_cycle(source(next_edge, g), target(next_edge, g), vis_data);\n                        cc = compute_cycle_cost(new_cycle, g, vis_data, em2); // !! CHEATED !!\n                        if( cost_swapped ) swap(cc.outside, cc.inside);\n                } else {\n                        // Determine the tree path from y to the (vi, wi) cycle by following parent pointers from y.\n                        cout << MAGENTA << \"   neither are tree edges\\n\" << RESET;\n                        auto path = ancestors(y, vis_data);\n                        uint i;\n                        for( i = 0; !on_cycle(path[i], cycle, g); ++i );\n\n                        // Let z be the vertex on the (vi, wi) cycle reached during the search.\n                        auto z = path[i++];\n                        cout << \"    z: \" << z << '\\n';\n                        path.erase(path.begin()+i, path.end());\n                        assert(path.size() == i);\n\n                        // Compute the total cost af all vertices except z on this tree path.\n                        uint path_cost = path.size() - 1;\n                        cout << \"    y-to-z-minus-z cost: \" << path_cost << '\\n';\n\n                        // Scan the tree edges inside the (y, wi) cycle, alternately scanning an edge in one cycle and an edge in the other cycle.\n                        // Stop scanning when all edges inside one of the cycles have been scanned.  Compute the cost inside this cycle by summing the associated costs of all scanned edges.\n                        // Use this cost, the cost inside the (vi, wi) cycle, and the cost on the tree path from y to z to compute the cost inside the other cycle.\n                        auto cycle1 = get_cycle(vi, y, vis_data);\n                        auto cycle2 = get_cycle(y, wi, vis_data);\n\n                        auto cost1  = compute_cycle_cost(cycle1, g, vis_data, em2);\n                        auto cost2  = compute_cycle_cost(cycle2, g, vis_data, em2);\n                        if( cost_swapped ){\n                                swap(cost1.inside, cost1.outside);\n                                swap(cost2.inside, cost2.outside);\n                        }\n\n                        // Let (vi+1, wi+1) be the edge among (vi, y) and (i, wi) whose cycle has more cost inside it.\n                        if( cost1.inside > cost2.inside ){ next_edge = edge(vi, y, g).first; cc = cost1; }\n                        else                             { next_edge = edge(y, wi, g).first; cc = cost2; }\n                } \n                chosen_edge = next_edge;\n        }\n        cout << \"found cycle with inside cost < 2/3: \" << cc.inside << '\\n';\n        print_cycle(cycle);\n\n        cout << HEADER_COL << \"\\n------------ 10  - Construct Vertex Partition --------------\\n\" << RESET;\n        print_graph(g_orig, false);\n        cout << \"l0: \" << l[0] << '\\n';\n        cout << \"l1: \" << l[1] << '\\n';\n        cout << \"l2: \" << l[2] << '\\n';\n\n        uint r = vis_data.num_levels;\n        cout << \"r: \" << r << '\\n';\n\n        if( l[1] >= l[2] ){ \n                cout << MAGENTA << \"l1 is less than l2\\n\" << RESET; \n                vector<VertDesc> part_a, part_b, part_c;\n                VertIter vei, vend;\n                for( tie(vei, vend) = vertices(g_orig); vei != vend; ++vei ){ \n                        auto v = *vei;\n                        cout << \"level of \" << v << \": \" << vis_data.verts[v].level << \"  \";\n                        if( vis_data.verts[v].level <  l[1] )                                  { cout << v << \" belongs to first part\\n\";  part_a.push_back(v); continue; }\n                        if( vis_data.verts[v].level >= l[1]+1 && vis_data.verts[v].level <= r ){ cout << v << \" belongs to middle part\\n\"; part_b.push_back(v); continue; }\n                        if( vis_data.verts[v].level == l[1] )                                  { cout << v << \" belongs to last part\\n\";   part_c.push_back(v); continue; }\n                        assert(0);\n                } \n                cout << GREEN;\n                cout <<   \"A = all verts on levels 0    thru l1-1: \"; for( auto& a : part_a ) cout << a << ' ';\n                cout << \"\\nB = all verts on levels l1+1 thru r   : \"; for( auto& b : part_b ) cout << b << ' ';\n                cout << \"\\nC = all verts on llevel l1            : \"; for( auto& c : part_c ) cout << c << ' ';\n                cout << RESET;\n                return {};\n        } \n\n        vector<VertDesc> part_a, part_b, part_c, deleted_part;\n        VertIter vei, vend;\n        for( tie(vei, vend) = vertices(g_orig); vei != vend; ++vei ){ \n                auto v = *vei;\n                cout << \"level of \" << v << \": \" << vis_data.verts[v].level << \", \";\n                if( vis_data.verts[v].level == l[1] || vis_data.verts[v].level == l[2] ){     cout << v << \" is deleted\\n\";             deleted_part.push_back(v); continue;}\n                if( vis_data.verts[v].level <  l[1] ){                                        cout << v << \" belongs to first part\\n\";  part_a.push_back(v);       continue;}\n                if( vis_data.verts[v].level >= l[1]+1 && vis_data.verts[v].level <= l[2]-1 ){ cout << v << \" belongs to middle part\\n\"; part_b.push_back(v);       continue;}\n                if( vis_data.verts[v].level >  l[2]  ){                                       cout << v << \" belongs to last part\\n\";   part_c.push_back(v);       continue;}\n                assert(0);\n        }\n\n        //the only part which can have cost > 2/3 is the middle part\n        assert(part_a.size() <= 2*num_vertices(g_orig)/3);\n        assert(part_c.size() <= 2*num_vertices(g_orig)/3);\n        if( part_b.size() <= 2*num_vertices(g_orig)/3 ){\n                cout << MAGENTA << \"middle part NOT biggest\\n\" << RESET;\n                vector<VertDesc>* costly_part, * other1, * other2;\n                if( part_a.size() > part_b.size() && part_a.size() > part_c.size() ){ costly_part = &part_a; other1 = &part_b; other2 = &part_c; cout << \"part a is most costly\\n\";}\n                if( part_b.size() > part_a.size() && part_b.size() > part_c.size() ){ costly_part = &part_b; other1 = &part_a; other2 = &part_c; cout << \"part b is most costly\\n\";}\n                if( part_c.size() > part_a.size() && part_c.size() > part_b.size() ){ costly_part = &part_c; other1 = &part_a; other2 = &part_b; cout << \"part c is most costly\\n\";}\n                cout << \"part a size: \" << part_a.size() << '\\n';\n                cout << \"part b size: \" << part_b.size() << '\\n';\n                cout << \"part c size: \" << part_c.size() << '\\n';\n                cout <<   \"A = most costly part of the 3: \"; for( auto& a : *costly_part ) cout << a << ' ';\n                cout << \"\\nB = remaining 2 parts        : \"; for( auto& b : *other1      ) cout << b << ' '; for( auto& b : *other2 ) cout << b << ' '; \n                cout << \"\\nC =                          : \"; for( auto& v : deleted_part ) cout << v << ' '; cout << '\\n';\n        } else {\n                cout << MAGENTA << \"middle part biggest\\n\" << RESET;\n                //delete all verts on level l2 and above\n                //shrink all verts on levels l1 and belowe to a single vertex of cost zero\n                //The new graph has a spanning tree radius of l2 - l1 -1 whose root corresponds to vertices on levels l1 and below in the original graph\n                r = l[2] - l[1] - 1;\n                //Apply Lemma 2 to the new graph, A* B* C*\n                cout << \"A = set among A* and B* with greater cost\\n\";\n                cout << \"C = verts on levels l1 and l2 in the original graph plus verts in C* minus the root\\n\";\n                cout << \"B = remaining verts\\n\";\n                //By Lemma 2, A has total cost <= 2/3\n                //But A U C* has total cost >= 1/3, so B also has total cost <= 2/3\n                //Futhermore, C contains no more than L[l1] + L[l2] + 2(l2 - l1 - 1)\n        }\n        return {};\n}\n", "meta": {"hexsha": "9aaa9494abe5f3069f951748a3b8def544c5f2fc", "size": 37030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lipton-tarjan.cpp", "max_stars_repo_name": "FashGek/chazelle-triangulation", "max_stars_repo_head_hexsha": "3ef89edb225dbfdd09ce8fde103fe657d01bcc98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T04:19:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T04:19:49.000Z", "max_issues_repo_path": "lipton-tarjan.cpp", "max_issues_repo_name": "FashGek/chazelle-triangulation", "max_issues_repo_head_hexsha": "3ef89edb225dbfdd09ce8fde103fe657d01bcc98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lipton-tarjan.cpp", "max_forks_repo_name": "FashGek/chazelle-triangulation", "max_forks_repo_head_hexsha": "3ef89edb225dbfdd09ce8fde103fe657d01bcc98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-20T04:20:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-20T04:20:18.000Z", "avg_line_length": 45.6034482759, "max_line_length": 193, "alphanum_fraction": 0.4817985417, "num_tokens": 9541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.02064592893143859, "lm_q1q2_score": 0.008880791287306289}}
{"text": "\r\n#include <cassert>\r\n#include <cmath>\r\n#include <map>\r\n#include <algorithm>\r\n#include <stdexcept>\r\n#include <sstream>\r\n#include <ostream>\r\n\r\n#include <boost/graph/copy.hpp>\r\n\r\n#include \"ggl/chem/MoleculeUtil.hh\"\r\n#include \"ggl/chem/AromaticityPerception.hh\"\r\n\r\n\r\nnamespace ggl {\r\nnamespace chem {\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\tbool\r\n\tAromaticityPerception::AdjacencyComp::\r\n\toperator() ( AromaticityPerception::AdjacencyData* e1, AromaticityPerception::AdjacencyData* e2)  {\r\n\r\n\t\tassert (e1 != NULL);\r\n\t\tassert (e2 != NULL);\r\n\r\n\t\t// check if (e1 smaller e2)\r\n\r\n\t\t // check for equality\r\n\t\tbool bothSameOpenEdges = e1->openEdges == e2->openEdges;\r\n\t\tbool bothSameRemValence = e1->remValence == e2->remValence;\r\n\r\n\t\t // less conditions\r\n\t\tbool e1NoOpenEdge = e1->openEdges == 0;\r\n\t\tbool e2NoOpenEdge = e2->openEdges == 0;\r\n\t\tbool e1LessOpenEdges = e1->openEdges < e2->openEdges;\r\n\t\tbool e1LessRemValence = e1->remValence < e2->remValence;\r\n\t\tbool e1LessAromEdges = e1->aromaticEdges < e2->aromaticEdges;\r\n\t\tbool e1OnlySingleEdges = e1->openEdges == e1->remValence;\r\n\t\tbool e2OnlySingleEdges = e2->openEdges == e2->remValence;\r\n\r\n\t\t////////////////// e1/e2 has no edges left\r\n\r\n\t\t  // no open edge check\r\n\t\tif (e1NoOpenEdge || e2NoOpenEdge) {\r\n\t\t\t  // e1 has to have no open edge to be smaller\r\n\t\t\treturn\t(!e1NoOpenEdge && e2NoOpenEdge);\r\n\t\t}\r\n\r\n\t\t////////////  both have at least 1 open edge\r\n\r\n\t\t  // single edges are smallest\r\n\t\tif (e1OnlySingleEdges && ! e2OnlySingleEdges) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\t  // single edges tie break via remaining valence\r\n\t\tif (e1OnlySingleEdges && e2OnlySingleEdges) {\r\n\t\t\treturn e1LessRemValence || (bothSameRemValence && e1LessAromEdges);\r\n\t\t}\r\n\r\n\t\t  // final sorting via number of open edges\r\n\t\treturn\te1LessOpenEdges\r\n\t\t\t\t||\r\n\t\t\t\t(bothSameOpenEdges && e1LessRemValence)\r\n\t\t\t\t||\r\n\t\t\t\t(bothSameOpenEdges && bothSameRemValence && e1LessAromEdges)\r\n\t\t\t\t;\r\n\r\n\t}\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\tvoid\r\n\tAromaticityPerception::\r\n\tcorrectAromaticity( Molecule & mol, const bool checkValence )\r\n\t throw (std::runtime_error)\r\n\t{\r\n\t\t  // clear temporary data\r\n\t\tclearData();\r\n\t\t  // identify all rings\r\n\t\tfindAllRings( mol );\r\n\r\n\t\t  // prune rings to remove fused representation\r\n\t\tpruneFusedRings( allRings );\r\n\r\n\t\t  // prune rings that cannot be aromatic\r\n\t\tpruneNonSingleDoubleBondRings( allRings, mol );\r\n\r\n\t\t  // identify all aromatic rings\r\n\t\tidentifyAromaticEdges(mol);\r\n\r\n\t\t  // relabel according to identified aromatic rings\r\n\t\trelabelMolecule(mol, checkValence);\r\n\t}\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n\tvoid\r\n\tAromaticityPerception::\r\n\tpruneNonSingleDoubleBondRings( std::vector< RingDescriptor* > & rings\r\n\t\t\t\t\t, const Molecule & mol )\r\n\t{\r\n\r\n\t\t  // access to edge label\r\n\t\tboost::property_map<\tMolecule , PropEdgeLabel >\r\n\t\t\t::const_type edgeLabel = boost::get( PropEdgeLabel(), mol );\r\n\r\n\t\tconst MoleculeUtil::BondLabelData * bond = NULL;\r\n\r\n\t\t  // check each ring\r\n\t\tfor (size_t i=0; i<rings.size(); ) {\r\n\r\n\t\t\tbool remove = false;\r\n\t\t\t  // check each bond if not single, double, or aromatic bond\r\n\t\t\tfor (EdgeSet::const_iterator e = rings.at(i)->edges.begin(); !remove && e != rings.at(i)->edges.end(); ++e) {\r\n\t\t\t\t  // get bond data\r\n\t\t\t\tbond = MoleculeUtil::getBondData( edgeLabel[\r\n\t\t\t\t\t\t\t\t\t\t  boost::edge( boost::vertex(e->first,mol), boost::vertex(e->second,mol), mol).first\r\n\t\t\t\t                                                                          ] );\r\n\t\t\t\tassert(bond != NULL);\r\n\t\t\t\tremove = bond->valence > 2 || bond->valence < 1;\r\n\t\t\t}\r\n\t\t\t  // check if this ring has to be removed\r\n\t\t\tif (remove) {\r\n\t\t\t\t  // delete element\r\n\t\t\t\tdelete rings[i];\r\n\t\t\t\t  // delete entry\r\n\t\t\t\trings.erase(rings.begin()+i);\r\n\t\t\t} else {\r\n\t\t\t\t  // go to next element\r\n\t\t\t\t++i;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n\tvoid\r\n\tAromaticityPerception::\r\n\tpruneFusedRings( std::vector< RingDescriptor* > & rings )\r\n\t{\r\n\r\n\t\t  // sort rings by size\r\n\t\tRingSizeLess ringSizeLess;\r\n\t\tstd::sort( rings.begin(), rings.end(), ringSizeLess );\r\n\r\n//std::cerr <<\"\\nNEXT\\n\";\r\n\t\t  // prune rings\r\n\t\tsize_t numOfprunedRings = 0;\r\n\t\tfor (int i=rings.size()-1; i>=0; i--) {\r\n//std::cerr <<\"next ring = \";\r\n//for (RingList::const_iterator x=rings.at(i)->ring.begin(); x!=rings.at(i)->ring.end(); ++x) {\r\n//\tstd::cerr <<*x <<\" \";\r\n//}\r\n\t\t\tbool canBePruned = false;\r\n\t\t\tfor( size_t c=0; !canBePruned && c < (size_t)i; ++c ) {\r\n\t\t\t\t  // skip already deleted rings\r\n\t\t\t\tif (rings.at(c) == NULL) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\t  // stop if ring is of equal size or larger\r\n\t\t\t\tif (rings.at(c)->edges.size() >= rings.at(i)->edges.size()) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t  // check for containment of this ring c within ring i\r\n\r\n\t\t\t\t  // get iterators on edge sets to compare\r\n\t\t\t\tEdgeSet::const_iterator largeEdge = rings.at(i)->edges.begin(), largeEnd = rings.at(i)->edges.end();\r\n\t\t\t\tEdgeSet::const_iterator curEdge = rings.at(c)->edges.begin(), curEnd = rings.at(c)->edges.end();\r\n\t\t\t\t  // sequential check\r\n\t\t\t\tsize_t curOverlap = 0;\r\n\t\t\t\t  // check only until up to two differences have been found\r\n\t\t\t\twhile(largeEdge != largeEnd && curEdge != curEnd) {\r\n\t\t\t\t\t  // check if overlap\r\n\t\t\t\t\tif (*largeEdge == *curEdge) {\r\n\t\t\t\t\t\t++curOverlap;\r\n\t\t\t\t\t\t++largeEdge;\r\n\t\t\t\t\t\t++curEdge;\r\n\t\t\t\t\t  // check which counter to increase\r\n\t\t\t\t\t} else if (*largeEdge < *curEdge) {\r\n\t\t\t\t\t\t++largeEdge;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t++curEdge;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t  // check if smaller current ring is contained excluding one edge\r\n\t\t\t\t  // if only one edge is left : ring is contained\r\n\t\t\t\tcanBePruned = (curOverlap+1 == rings.at(c)->edges.size());\r\n\r\n\t\t\t}\r\n\t\t\t  // prune ring if obsolete\r\n\t\t\tif (canBePruned) {\r\n\t\t\t\t  // remove ring descriptor at position i\r\n\t\t\t\tdelete rings[i];\r\n\t\t\t\t  // set to NULL to remember deletion\r\n\t\t\t\trings[i] = NULL;\r\n\t\t\t\t  // count pruning\r\n\t\t\t\tnumOfprunedRings++;\r\n//std::cerr <<\" pruned\";\r\n\t\t\t}\r\n//std::cerr <<\"\\n\";\r\n\t\t}\r\n\r\n\t\t  // shift remaining rings to the front\r\n\t\tif (numOfprunedRings>0) {\r\n\t\t\tsize_t fillPos = 0;\r\n\t\t\tfor( size_t i=0; i<rings.size(); ++i ) {\r\n\t\t\t\tif (rings.at(i) != NULL) {\r\n\t\t\t\t\t  // check if overwrite is needed\r\n\t\t\t\t\tif (fillPos < i) {\r\n\t\t\t\t\t\trings[fillPos] = rings[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t\t  // increase overwrite counter\r\n\t\t\t\t\tfillPos++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t  // drop deleted elements\r\n\t\t\trings.resize(rings.size()-numOfprunedRings);\r\n\t\t}\r\n\r\n\t}\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n\tvoid\r\n\tAromaticityPerception::\r\n\trelabelMolecule( Molecule & result, const bool checkValence )\r\n\t throw (std::runtime_error)\r\n\t{\r\n//\t\t  // new molecule to be filled\r\n//\t\tMolecule result(mol);\r\n\r\n\t\t  // property maps for access\r\n\t\tboost::property_map<\tMolecule , PropNodeLabel >\r\n\t\t\t::type resultNodeLabel = boost::get( PropNodeLabel(), result );\r\n\r\n\t\tboost::property_map<\tMolecule , PropNodeIndex >\r\n\t\t\t::type resultNodeIndex = boost::get( PropNodeIndex(), result );\r\n\r\n\t\tboost::property_map<\tMolecule , PropEdgeLabel >\r\n\t\t\t::type resultEdgeLabel = boost::get( PropEdgeLabel(), result );\r\n\r\n\t\t  // collect all nodes participating in aromatic edges\r\n\t\tstd::set< size_t > aromaticNodes;\r\n\t\tfor (EdgeSet::const_iterator e = aromaticEdges.begin();\r\n\t\t\t\te != aromaticEdges.end(); ++e)\r\n\t\t{\r\n\t\t\taromaticNodes.insert(e->first);\r\n\t\t\taromaticNodes.insert(e->second);\r\n\t\t}\r\n\r\n\t\t  // relabel aromatic nodes\r\n\t\tboost::graph_traits<Molecule>::vertex_iterator vi, vi_end;\r\n\t\tboost::tie(vi, vi_end) = vertices( result );\r\n\t\tfor (; vi != vi_end; ++vi) {\r\n\t\t\t  // check if the node should be aromatic\r\n\t\t\tconst bool shouldBeAromatic = aromaticNodes.find(resultNodeIndex[*vi]) != aromaticNodes.end();\r\n\t\t\t  // get atom data of current label to check if currently aromatic\r\n\t\t\tstd::string nodeLabel = resultNodeLabel[*vi];\r\n\t\t\tconst std::string atomLabel = MoleculeUtil::getAtom(nodeLabel);\r\n\t\t\tconst MoleculeUtil::AtomLabelData * atomData\r\n\t\t\t\t= MoleculeUtil::getAtomData(atomLabel);\r\n\t\t\tassert( atomData != NULL /*unknown atom label*/);\r\n\t\t\t  // check if relabeling is needed\r\n\t\t\tif (\t((atomData->isAromatic != 0 && !shouldBeAromatic)\r\n\t\t\t\t\t||\t(atomData->isAromatic == 0 && shouldBeAromatic))\r\n\t\t\t\t&& (MoleculeUtil::getAromaticPendant(atomLabel) != NULL))\r\n\t\t\t{\r\n\t\t\t\t  // relabel\r\n\t\t\t\t  // get aromatic/non-aromatic pendant\r\n\t\t\t\tconst std::string* newAtom = MoleculeUtil::getAromaticPendant(atomLabel);\r\n\t\t\t\tassert( newAtom != NULL /*obviously we tried to relabel a non-aromatic atom*/);\r\n\t\t\t\t  // replace atom label within node label (can be complex label)\r\n\t\t\t\tnodeLabel.replace( nodeLabel.find(atomLabel), newAtom->size(), *newAtom );\r\n\t\t\t\t  // set new node label\r\n\t\t\t\tresultNodeLabel[*vi] = nodeLabel;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t  // relabel edges\r\n\r\n\t\t  // get access to edge descriptors\r\n\t\tboost::graph_traits<Molecule>::edge_iterator ei, e_end;\r\n\t\tboost::tie(ei, e_end) = boost::edges( result );\r\n\t\tEdgeSet arom2nonaromEdges;\r\n\t\t  // dummy label to set for all edges that are currently aromatic but\r\n\t\t  // have to be relabeled to non-aromatic\r\n\t\tconst std::string UNCERTAIN_EDGE_LABEL = std::string(\"????\");\r\n\t\t  // check all edges if they have to be relabeled\r\n\t\tfor (; ei != e_end; ++ei) {\r\n\t\t\tEdge curEdge( resultNodeIndex[boost::source(*ei,result)]\r\n\t\t\t\t\t\t\t\t, resultNodeIndex[boost::target(*ei,result)] );\r\n\t\t\tif (curEdge.first > curEdge.second) {\r\n\t\t\t\tcurEdge = Edge(curEdge.second, curEdge.first);\r\n\t\t\t}\r\n\t\t\t  // check if the edge should be aromatic\r\n\t\t\tconst bool shouldBeAromatic = aromaticEdges.find(curEdge) != aromaticEdges.end();\r\n\t\t\tstd::string bondLabel = resultEdgeLabel[*ei];\r\n\t\t\tconst MoleculeUtil::BondLabelData * bondData\r\n\t\t\t\t\t\t= MoleculeUtil::getBondData( bondLabel );\r\n\t\t\tassert( bondData != NULL /*unknown bond label*/);\r\n\t\t\t  // check if aromatic relabeling needed\r\n\t\t\tif ( bondData->isAromatic == 0 && shouldBeAromatic ) {\r\n\t\t\t\tconst std::string* newBond = MoleculeUtil::getAromaticPendant(bondLabel);\r\n\t\t\t\tassert( newBond != NULL /*obviously we tried to relabel a non-aromatic bond*/);\r\n\t\t\t\tresultEdgeLabel[*ei] = *newBond;\r\n\t\t\t} else\r\n\t\t\t  // check if non-aromatic relabeling needed\r\n\t\t\tif ( bondData->isAromatic != 0 && !shouldBeAromatic ) {\r\n\t\t\t\tarom2nonaromEdges.insert(curEdge);\r\n\t\t\t\tresultEdgeLabel[*ei] = UNCERTAIN_EDGE_LABEL;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t  // relabel formerly aromatic edges to non-aromatic\r\n\r\n\t\tif ( !arom2nonaromEdges.empty() ) {\r\n\r\n\t\t\t  // get labels for single and double bonds from MoleculeUtil\r\n\t\t\tconst MoleculeUtil::BondDataMap & bondDataMap = MoleculeUtil::getBondData();\r\n\t\t\tstd::string singleBondLabel=\"\", doubleBondLabel=\"\", aromBondLabel=\"\";\r\n\t\t\tfor (MoleculeUtil::BondDataMap::const_iterator bd=bondDataMap.begin();\r\n\t\t\t\t\tbd != bondDataMap.end(); ++bd)\r\n\t\t\t{\r\n\t\t\t\tif (bd->second.valence == 1 && bd->second.isAromatic == 0) {\r\n\t\t\t\t\tsingleBondLabel = bd->first;\r\n\t\t\t\t}\r\n\t\t\t\tif (bd->second.valence == 2 && bd->second.isAromatic == 0) {\r\n\t\t\t\t\tdoubleBondLabel = bd->first;\r\n\t\t\t\t}\r\n\t\t\t\tif (bd->second.valence == 1 && bd->second.isAromatic != 0) {\r\n\t\t\t\t\taromBondLabel = bd->first;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tassert(singleBondLabel != \"\");\r\n\t\t\tassert(doubleBondLabel != \"\");\r\n\t\t\tassert(aromBondLabel != \"\");\r\n\r\n\t\t\tstd::vector< AdjacencyData* > nodes2relabel(boost::num_vertices(result), NULL);\r\n\t\t\tstd::vector< AdjacencyData* >::const_iterator nIt;\r\n\r\n\t\t\tsize_t nodes2relabelCount = 0;\r\n\t\t\tfor( EdgeSet::const_iterator e = arom2nonaromEdges.begin();\r\n\t\t\t\t\te != arom2nonaromEdges.end(); ++e )\r\n\t\t\t{\r\n\t\t\t\tAdjacencyData *curNode = NULL;\r\n\t\t\t\tcurNode = nodes2relabel[ e->first ];\r\n\t\t\t\t  // check if adjacent from node was already handled, if not do\r\n\t\t\t\tif (curNode == NULL) {\r\n\t\t\t\t\tboost::graph_traits<Molecule>::vertex_descriptor node\r\n\t\t\t\t\t\t= boost::vertex( e->first, result );\r\n\t\t\t\t\tint remainingValence = (int)MoleculeUtil::getAtomData( resultNodeLabel[node] )->valence;\r\n\t\t\t\t\tremainingValence += MoleculeUtil::getCharge( resultNodeLabel[node] );\r\n\r\n\t\t\t\t\tsize_t adjAromaticEdges = 0;\r\n\t\t\t\t\tsize_t openEdges = 0;\r\n\t\t\t\t\t  // iterate over all adjacent edges and reduce remaining valence\r\n\t\t\t\t\tboost::graph_traits<Molecule>::out_edge_iterator oei, oe_end;\r\n\t\t\t\t\tboost::tie(oei, oe_end) = boost::out_edges( node, result );\r\n\t\t\t\t\tfor (; oei != oe_end; ++oei) {\r\n\t\t\t\t\t\t  // update information based on already labeled edges\r\n\t\t\t\t\t\tif (resultEdgeLabel[*oei] != UNCERTAIN_EDGE_LABEL) {\r\n\t\t\t\t\t\t\tremainingValence -= (int)MoleculeUtil::getBondData( resultEdgeLabel[*oei] )->valence;\r\n\t\t\t\t\t\t\tadjAromaticEdges += (MoleculeUtil::getBondData( resultEdgeLabel[*oei] )->isAromatic!=0?1:0);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t  // count edges to be relabeled\r\n\t\t\t\t\t\t\t++openEdges;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tassert(adjAromaticEdges == 0 || adjAromaticEdges >= 2  /*either involved in at least one aromatic ring or not at all*/);\r\n\t\t\t\t\t  // insert new node information\r\n\t\t\t\t\tnodes2relabel[e->first] = new AdjacencyData( e->first, remainingValence, openEdges, adjAromaticEdges );\r\n\t\t\t\t\t++nodes2relabelCount;\r\n\t\t\t\t}\r\n\t\t\t\t  // check if adjacent target node was already handled, if not do\r\n\t\t\t\tcurNode = nodes2relabel[ e->second ];\r\n\t\t\t\tif (curNode == NULL) {\r\n\t\t\t\t\tboost::graph_traits<Molecule>::vertex_descriptor node\r\n\t\t\t\t\t\t= boost::vertex( e->second, result );\r\n\t\t\t\t\tint remainingValence = (int)MoleculeUtil::getAtomData( resultNodeLabel[node] )->valence;\r\n\t\t\t\t\tremainingValence += MoleculeUtil::getCharge( resultNodeLabel[node] );\r\n\r\n\t\t\t\t\tsize_t adjAromaticEdges = 0;\r\n\t\t\t\t\tsize_t openEdges = 0;\r\n\t\t\t\t\t  // iterate over all adjacent edges and reduce remaining valence\r\n\t\t\t\t\tboost::graph_traits<Molecule>::out_edge_iterator oei, oe_end;\r\n\t\t\t\t\tboost::tie(oei, oe_end) = boost::out_edges( node, result );\r\n\t\t\t\t\tfor (; oei != oe_end; ++oei) {\r\n\t\t\t\t\t\t  // update information based on already labeled edges\r\n\t\t\t\t\t\tif (resultEdgeLabel[*oei] != UNCERTAIN_EDGE_LABEL) {\r\n\t\t\t\t\t\t\tremainingValence -= (int)MoleculeUtil::getBondData( resultEdgeLabel[*oei] )->valence;\r\n\t\t\t\t\t\t\tadjAromaticEdges += (MoleculeUtil::getBondData( resultEdgeLabel[*oei] )->isAromatic!=0?1:0);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t  // count edges to be relabeled\r\n\t\t\t\t\t\t\t++openEdges;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tassert(adjAromaticEdges == 0 || adjAromaticEdges >= 2  /*either involved in at least one aromatic ring or not at all*/);\r\n\t\t\t\t\t  // insert new node information\r\n\t\t\t\t\tnodes2relabel[e->second] = new AdjacencyData( e->second, remainingValence, openEdges, adjAromaticEdges );\r\n\t\t\t\t\t++nodes2relabelCount;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t  // get sorted access to the adjacent nodes\r\n\t\t\tstd::vector< AdjacencyData* > nodes2relabelSorted(nodes2relabelCount,NULL);\r\n\t\t\tsize_t i=0;\r\n\t\t\tfor (nIt = nodes2relabel.begin(); nIt != nodes2relabel.end(); ++nIt) {\r\n\t\t\t\tif( *nIt != NULL) {\r\n\t\t\t\t\t  // store pointer to according AdjacencyData object\r\n\t\t\t\t\tnodes2relabelSorted[i] = *nIt;\r\n\t\t\t\t\t++i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tassert( i == nodes2relabelCount );\r\n\r\n//\t\t\tstd::cerr <<\"\\n DEBUG after init :\\n\";\r\n//\t\t\tfor (size_t x=0; x < nodes2relabelSorted.size(); ++x) {\r\n//\t\t\t\tstd::cerr <<\"    \" <<x <<\" \" <<nodes2relabelSorted.at(x);\r\n//\t\t\t\tif (nodes2relabelSorted.at(x) != NULL) {\r\n//\t\t\t\t\tstd::cerr <<\" \"<< \"id \" <<nodes2relabelSorted.at(x)->nodeID <<\" rem \" <<nodes2relabelSorted.at(x)->remValence <<\" oe \" <<nodes2relabelSorted.at(x)->openEdges <<\" ae \" <<nodes2relabelSorted.at(x)->aromaticEdges;\r\n//\t\t\t\t}\r\n//\t\t\t\tstd::cerr <<\"\\n\";\r\n//\t\t\t}\r\n\r\n\t\t\tstd::sort( nodes2relabelSorted.begin(), nodes2relabelSorted.end(), AdjacencyComp() );\r\n\r\n\r\n//\t\t\tstd::cerr <<\"\\n DEBUG after first sort :\\n\";\r\n//\t\t\tfor (size_t x=0; x < nodes2relabelSorted.size(); ++x) {\r\n//\t\t\t\tstd::cerr <<\"    \" <<x <<\" \" <<nodes2relabelSorted.at(x);\r\n//\t\t\t\tif (nodes2relabelSorted.at(x) != NULL) {\r\n//\t\t\t\t\tstd::cerr <<\" \"<< \"id \" <<nodes2relabelSorted.at(x)->nodeID <<\" rem \" <<nodes2relabelSorted.at(x)->remValence <<\" oe \" <<nodes2relabelSorted.at(x)->openEdges <<\" ae \" <<nodes2relabelSorted.at(x)->aromaticEdges;\r\n//\t\t\t\t}\r\n//\t\t\t\tstd::cerr <<\"\\n\";\r\n//\t\t\t}\r\n\r\n\r\n\t\t\ttry {\r\n\r\n\t\t\t// iterate relabeling of front entry + sort till all done or\r\n\t\t\t// no deterministic relabeling possible\r\n\t\t\twhile ( !nodes2relabelSorted.empty() && (*nodes2relabelSorted.begin())->openEdges > 0 )\r\n\t\t\t{\r\n\r\n\t\t\t\tAdjacencyData & curNode = *(*nodes2relabelSorted.begin());\r\n\r\n//std::cerr <<\" DEBUG curNode : id = \"<<curNode.nodeID <<\" val = \" <<curNode.valence <<\" edges = \" <<curNode.edges <<\" arom = \" <<curNode.aromaticEdges<<\"\\n\";\r\n\t\t\t\t// iterate over all uncertain edges and relabel\r\n\t\t\t\tboost::graph_traits<Molecule>::out_edge_iterator oei, oe_end;\r\n\t\t\t\tboost::tie(oei, oe_end) = boost::out_edges( boost::vertex( curNode.nodeID, result ), result );\r\n\r\n\t\t\t\t  // check if only single bonds left\r\n\t\t\t\tif ( curNode.remValence == curNode.openEdges ) {\r\n\t\t\t\t\t// find all edges and label with valence 1\r\n\t\t\t\t\tfor (; oei != oe_end; ++oei) {\r\n\t\t\t\t\t\tif (resultEdgeLabel[*oei] == UNCERTAIN_EDGE_LABEL) {\r\n\t\t\t\t\t\t\tresultEdgeLabel[*oei] = singleBondLabel;\r\n\t\t\t\t\t\t\t// update adjacent node information\r\n\t\t\t\t\t\t\tsize_t targetNode = resultNodeIndex[boost::target( *oei, result )];\r\n\t\t\t\t\t\t\tassert(nodes2relabel[ targetNode ] != NULL);\r\n\t\t\t\t\t\t\t// check if valence of target node compatible\r\n\t\t\t\t\t\t\tif ( checkValence && (nodes2relabel[ targetNode ]->openEdges == 0 || nodes2relabel[ targetNode ]->remValence == 0) ) {\r\n\t\t\t\t\t\t\t\tthrow std::runtime_error(\"ggl::chem::AromaticityPerception::relabelMolecule : tried to add single bond but target has no valence left\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tnodes2relabel[ targetNode ]->openEdges--;\r\n\t\t\t\t\t\t\tnodes2relabel[ targetNode ]->remValence -= 1;\r\n\t\t\t\t\t\t\t// check if remaining valence of target node sufficient\r\n\t\t\t\t\t\t\tif ( checkValence && (nodes2relabel[ targetNode ]->openEdges > nodes2relabel[ targetNode ]->remValence) )\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tthrow std::runtime_error(\"ggl::chem::AromaticityPerception::relabelMolecule : after single bond insert not enough valence left within target node\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else\r\n\t\t\t\tif ( curNode.openEdges == 1 ) {\r\n\t\t\t\t\t// find edge and label according to valence\r\n\t\t\t\t\tfor (; oei != oe_end; ++oei) {\r\n\t\t\t\t\t\tif (resultEdgeLabel[*oei] == UNCERTAIN_EDGE_LABEL) {\r\n\t\t\t\t\t\t\tsize_t edgeValence = 0;\r\n\t\t\t\t\t\t\t// relabel according to valence\r\n\t\t\t\t\t\t\tswitch (curNode.remValence) {\r\n\t\t\t\t\t\t\tcase 1 : resultEdgeLabel[*oei] = singleBondLabel;\r\n\t\t\t\t\t\t\t\tedgeValence = 1;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\tcase 2 :\r\n\t\t\t\t\t\t\t\t  // check if node is already involved in aromatic ring\r\n\t\t\t\t\t\t\t\tif (curNode.aromaticEdges >= 2) {\r\n\t\t\t\t\t\t\t\t\t  // one electron will be used by the aromatic ring\r\n\t\t\t\t\t\t\t\t\t  // thus only one left for a single bond\r\n\t\t\t\t\t\t\t\t\tresultEdgeLabel[*oei] = singleBondLabel;\r\n\t\t\t\t\t\t\t\t\tedgeValence = 1;\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t  // two electrons available for the bond\r\n\t\t\t\t\t\t\t\t\tresultEdgeLabel[*oei] = doubleBondLabel;\r\n\t\t\t\t\t\t\t\t\tedgeValence = 2;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\tcase 3 :\r\n\t\t\t\t\t\t\t\t  // check if involved in aromatic ring -> error if not\r\n\t\t\t\t\t\t\t\tif (curNode.aromaticEdges < 2) {\r\n\t\t\t\t\t\t\t\t\tthrow std::runtime_error(\"ggl::chem::AromaticityPerception::relabelMolecule : remaining atom valence left for a single bond relabeling is too high (>2), no canonical labeling possible\");\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t  // two electrons available for the bond\r\n\t\t\t\t\t\t\t\tresultEdgeLabel[*oei] = doubleBondLabel;\r\n\t\t\t\t\t\t\t\tedgeValence = 2;\r\n\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\tcase 0 :\r\n\t\t\t\t\t\t\t\tthrow std::runtime_error(\"ggl::chem::AromaticityPerception::relabelMolecule : remaining atom valence for bond relabeling is zero, no relabeling possible\");\r\n\t\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\t\tthrow std::runtime_error(\"ggl::chem::AromaticityPerception::relabelMolecule : remaining atom valence left for a single bond relabeling is too high (>2), no canonical labeling possible\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t// update adjacent node information\r\n\t\t\t\t\t\t\tsize_t targetNode = resultNodeIndex[boost::target( *oei, result )];\r\n\t\t\t\t\t\t\tassert(nodes2relabel[targetNode] != NULL);\r\n\t\t\t\t\t\t\t// check if valence of target node compatible\r\n\t\t\t\t\t\t\tif ( checkValence && (nodes2relabel[ targetNode ]->openEdges == 0 || nodes2relabel[ targetNode ]->remValence < edgeValence) ) {\r\n\t\t\t\t\t\t\t\tthrow std::runtime_error(\"ggl::chem::AromaticityPerception::relabelMolecule : tried to add bond but target has no valence left\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tnodes2relabel[ targetNode ]->openEdges--;\r\n\t\t\t\t\t\t\tnodes2relabel[ targetNode ]->remValence -= edgeValence;\r\n\t\t\t\t\t\t\t// check if remaining valence of target node sufficient\r\n\t\t\t\t\t\t\tif ( checkValence && (nodes2relabel[ targetNode ]->openEdges > nodes2relabel[ targetNode ]->remValence) )\r\n\t\t\t\t\t\t\t{\r\n//for (EdgeSet::const_iterator ae=aromaticEdges.begin(); ae!=aromaticEdges.end(); ++ae) {\r\n//\tstd::cerr <<\" \" <<ae->first <<\"-\" <<ae->second;\r\n//}\r\n//for (std::vector< AdjacencyData* >::const_iterator nIt = nodes2relabelSorted.begin(); nIt != nodes2relabelSorted.end(); ++nIt, ++i) {\r\n//\tstd::cerr <<\" list : id = \"<<(*nIt)->nodeID <<\" val = \" <<(*nIt)->valence <<\" edges = \" <<(*nIt)->edges <<\" arom = \" <<(*nIt)->aromaticEdges;\r\n//}\r\n//std::cerr\t<<\"\\n\\n\"\r\n//\t\t<<\"current relabeled graph:\\n\"\r\n//\t\t<<Molecule_Graph(result)\r\n//\t\t<<\"\\n\"\r\n//\t\t<<\"last edge = (\"<<curNode.nodeID <<\",\"<<targetNode<<\")\\n\";\r\n\r\n\t\t\t\t\t\t\t\tthrow std::runtime_error(\"ggl::chem::AromaticityPerception::relabelMolecule : after bond insert not enough valence left within target node\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\r\n\t\t\t\t\t// NO DETERMINISTIC NON-AROMATIC LABELING POSSIBLE !!!\r\n\t\t\t\t\t// due to ordering: all following nodes have the same problem\r\n\t\t\t\t\t// or are already correctly relabeled\r\n\r\n//\t\t\t\t\tstd::cout <<\"\\n ERROR : deterministic labeling not possible !\\n cur node = \"\r\n//\t\t\t\t\t\t\t<<curNode.nodeID <<\" open = \" <<curNode.openEdges <<\" val = \" <<curNode.remValence <<\" arom = \" <<curNode.aromaticEdges <<\"\\n\"\r\n//\t\t\t\t\t\t\t<<Molecule_Graph(result)\r\n//\t\t\t\t\t\t\t<<std::endl;\r\n\r\n\t\t\t\t\tbreak;  // -> break and apply special handling\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t\t  // update curNode data\r\n\t\t\t\tcurNode.remValence = 0;\r\n\t\t\t\tcurNode.openEdges = 0;\r\n\r\n\t\t\t\t--nodes2relabelCount;\r\n\r\n\t\t\t\t  // update sorting due to changes in adjacent nodes' data\r\n\t\t\t\tstd::swap( *nodes2relabelSorted.begin(), *(nodes2relabelSorted.begin()+nodes2relabelCount) );\r\n\t\t\t\tstd::sort( nodes2relabelSorted.begin(), nodes2relabelSorted.begin()+nodes2relabelCount, AdjacencyComp() );\r\n\r\n\t\t\t}\r\n\r\n\t\t\t  // check if there are any edges left to be labeled non-aromatic\r\n\t\t\t  // but no deterministic labeling possible\r\n\t\t\t  // --> make these bonds/rings aromatic\r\n\t\t\tif (!nodes2relabelSorted.empty() && (*nodes2relabelSorted.begin())->openEdges > 0) {\r\n\t\t\t\t  // container that will hold all remaining edges to rename\r\n\t\t\t\tEdgeSet remainingEdges;\r\n\t\t\t\tboost::tie(ei, e_end) = boost::edges( result );\r\n\t\t\t\t  // check all edges if they have to be relabeled\r\n\t\t\t\t  // TODO slow : replace by iteration of ring bonds or dedicated container of non-aromatic bonds\r\n\t\t\t\tfor (; ei != e_end; ++ei) {\r\n\t\t\t\t\t  // add uncertain edge to container\r\n\t\t\t\t\tif (resultEdgeLabel[*ei] == UNCERTAIN_EDGE_LABEL) {\r\n\t\t\t\t\t\tEdge curEdge( resultNodeIndex[boost::source(*ei,result)]\r\n\t\t\t\t\t\t\t\t\t\t\t, resultNodeIndex[boost::target(*ei,result)] );\r\n\t\t\t\t\t\tif (curEdge.first > curEdge.second) {\r\n\t\t\t\t\t\t\tcurEdge = Edge(curEdge.second, curEdge.first);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tremainingEdges.insert(curEdge);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t  // iterate until all edges have been assigned\r\n\t\t\t\twhile( !remainingEdges.empty() ) {\r\n\t\t\t\t\t  // find RingDescriptor that covers most remaining edges\r\n\t\t\t\t\tRingDescriptor *nextRing = NULL;\r\n\t\t\t\t\tsize_t maxEdgeOverlap = 0;\r\n\t\t\t\t\tfor (size_t i=0; i<allRings.size(); ++i) {\r\n\t\t\t\t\t\t  // check if prediction was non-aromatic\r\n\t\t\t\t\t\tif (allRings.at(i)->predState == RingDescriptor::NonAromatic) {\r\n\t\t\t\t\t\t\tsize_t curOverlap = 0;\r\n\t\t\t\t\t\t\tEdgeSet::const_iterator remainEdge = remainingEdges.begin(), remainEnd = remainingEdges.end();\r\n\t\t\t\t\t\t\tEdgeSet::const_iterator curEdge = allRings.at(i)->edges.begin(), curEnd = allRings.at(i)->edges.end();\r\n\t\t\t\t\t\t\twhile(remainEdge != remainEnd && curEdge != curEnd) {\r\n\t\t\t\t\t\t\t\t  // check if overlap\r\n\t\t\t\t\t\t\t\tif (*remainEdge == *curEdge) {\r\n\t\t\t\t\t\t\t\t\t++curOverlap;\r\n\t\t\t\t\t\t\t\t\t++remainEdge;\r\n\t\t\t\t\t\t\t\t\t++curEdge;\r\n\t\t\t\t\t\t\t\t  // check which counter to increase\r\n\t\t\t\t\t\t\t\t} else if (*remainEdge < *curEdge) {\r\n\t\t\t\t\t\t\t\t\t++remainEdge;\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t++curEdge;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t  // check if new maximum found\r\n\t\t\t\t\t\t\tif (curOverlap > maxEdgeOverlap) {\r\n\t\t\t\t\t\t\t\t  // update maximum data\r\n\t\t\t\t\t\t\t\tmaxEdgeOverlap = curOverlap;\r\n\t\t\t\t\t\t\t\tnextRing = allRings[i];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t  // check if the remaining edges are part of a known ring\r\n\t\t\t\t\tif (nextRing == NULL) {\r\n\r\n\t\t\t\t\t\t// TODO check if now a deterministic labeling is possible ?!?!\r\n\r\n\t\t\t\t\t\tstd::stringstream err;\r\n\t\t\t\t\t\terr\t<<\"\\n RUNTIME ERROR in ggl::chem::AromaticityPerception::relabelMolecule :\\n\\n\"\r\n\t\t\t\t\t\t\t\t<<\" No deterministic non-aromatic relabeling possible. \\n\"\r\n\t\t\t\t\t\t\t\t<<\"\\n\"\r\n\t\t\t\t\t\t\t\t<<\" Remaining (formerly aromatic) edges that cannot be assigned are not part of any (predicted) ring.\\n\"\r\n\t\t\t\t\t\t\t\t<<\" Edges = \";\r\n\t\t\t\t\t\tfor (EdgeSet::const_iterator edge=remainingEdges.begin(); edge!=remainingEdges.end(); ++edge) {\r\n\t\t\t\t\t\t\terr <<\" \" <<edge->first <<\"-\" <<edge->second <<\", \";\r\n\t\t\t\t\t\t}\r\n\t//\t\t\t\t\terr <<\"\\n\";\r\n\t//\t\t\t\t\tfor (std::vector< AdjacencyData* >::const_iterator nIt = nodes2relabelSorted.begin(); nIt != nodes2relabelSorted.end(); ++nIt, ++i) {\r\n\t//\t\t\t\t\t\terr <<\" list : id = \"<<(*nIt)->nodeID <<\" val = \" <<(*nIt)->valence <<\" edges = \" <<(*nIt)->edges <<\" arom = \" <<(*nIt)->aromaticEdges<<\"\\n\";\r\n\t//\t\t\t\t\t}\r\n\t\t\t\t\t\terr\t<<\"\\n\"\r\n\t\t\t\t\t\t\t\t<<\" Current relabeled graph:\\n\"\r\n\t\t\t\t\t\t\t\t<<Molecule_Graph(result)\r\n\t\t\t\t\t\t\t\t<<\"\\n\";\r\n\r\n\t\t\t\t\t\tthrow std::runtime_error(err.str());\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t  // make this ring aromatic as well\r\n\t\t\t\t\tnextRing->predState = RingDescriptor::Aromatic;\r\n\r\n\t\t\t\t\t  // relabel all nodes if not already aromatic\r\n\t\t\t\t\tfor (RingList::const_iterator curID = nextRing->ring.begin(); curID != nextRing->ring.end(); ++curID) {\r\n\t\t\t\t\t\t  // get access to according node\r\n\t\t\t\t\t\tMolecule::vertex_descriptor curNode = boost::vertex( *curID, result );\r\n\t\t\t\t\t\t  // get atom data of current label to check if currently aromatic\r\n\t\t\t\t\t\tstd::string nodeLabel = resultNodeLabel[curNode];\r\n\t\t\t\t\t\tconst std::string atomLabel = MoleculeUtil::getAtom(nodeLabel);\r\n\t\t\t\t\t\tconst MoleculeUtil::AtomLabelData * atomData\r\n\t\t\t\t\t\t\t= MoleculeUtil::getAtomData(atomLabel);\r\n\t\t\t\t\t\tassert( atomData != NULL /*unknown atom label*/);\r\n\t\t\t\t\t\t  // check if relabeling is needed\r\n\t\t\t\t\t\tif (\t(atomData->isAromatic == 0)\r\n\t\t\t\t\t\t\t&& (MoleculeUtil::getAromaticPendant(atomLabel) != NULL))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t  // relabel\r\n\t\t\t\t\t\t\t  // get aromatic/non-aromatic pendant\r\n\t\t\t\t\t\t\tconst std::string* newAtom = MoleculeUtil::getAromaticPendant(atomLabel);\r\n\t\t\t\t\t\t\tassert( newAtom != NULL /*obviously we tried to relabel a non-aromatic atom*/);\r\n\t\t\t\t\t\t\t  // replace atom label within node label (can be complex label)\r\n\t\t\t\t\t\t\tnodeLabel.replace( nodeLabel.find(atomLabel), newAtom->size(), *newAtom );\r\n\t\t\t\t\t\t\t  // set new node label\r\n\t\t\t\t\t\t\tresultNodeLabel[curNode] = nodeLabel;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t  // relabel ring edges to aromatic labels\r\n\t\t\t\t\tfor (EdgeSet::const_iterator curEdge = nextRing->edges.begin(); curEdge != nextRing->edges.end(); ++curEdge) {\r\n\t\t\t\t\t\t  // get access to according edge\r\n\t\t\t\t\t\tMolecule::edge_descriptor curResEdge = boost::edge( boost::vertex(curEdge->first,result)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, boost::vertex(curEdge->second,result), result ).first;\r\n\t\t\t\t\t\t  // check if edge label still unknown\r\n\t\t\t\t\t\tif (resultEdgeLabel[curResEdge] == UNCERTAIN_EDGE_LABEL) {\r\n\t\t\t\t\t\t\t  // make this an aromatic edge\r\n\t\t\t\t\t\t\tresultEdgeLabel[curResEdge] = aromBondLabel;\r\n\t\t\t\t\t\t\t  // remove from remaining edges\r\n\t\t\t\t\t\t\tremainingEdges.erase(*curEdge);\r\n\t\t\t\t\t\t\t  // skip remaining handling for this edge\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t  // check if the edge should be aromatic\r\n\t\t\t\t\t\tstd::string bondLabel = resultEdgeLabel[curResEdge];\r\n\t\t\t\t\t\tconst MoleculeUtil::BondLabelData * bondData\r\n\t\t\t\t\t\t\t\t\t= MoleculeUtil::getBondData( bondLabel );\r\n\t\t\t\t\t\tassert( bondData != NULL /*unknown bond label*/);\r\n\t\t\t\t\t\t  // check if aromatic relabeling needed\r\n\t\t\t\t\t\tif ( bondData->isAromatic == 0 ) {\r\n\t\t\t\t\t\t\tresultEdgeLabel[curResEdge] = aromBondLabel;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} // while remainingEdges not empty\r\n\t\t\t}\r\n\r\n\t\t\t} catch (std::runtime_error & e) {\r\n\t\t\t\t // remove local data\r\n\t\t\t\tfor (nIt = nodes2relabel.begin(); nIt != nodes2relabel.end(); ++nIt) {\r\n\t\t\t\t\tif( *nIt != NULL) {\r\n\t\t\t\t\t\tdelete (*nIt);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t  // remove temporary data\r\n\t\t\t\tclearData();\r\n\t\t\t\t  // forward error to next level\r\n\t\t\t\tthrow std::runtime_error(e.what());\r\n\t\t\t}\r\n\r\n\t\t\t // remove local data\r\n\t\t\tfor (nIt = nodes2relabel.begin(); nIt != nodes2relabel.end(); ++nIt) {\r\n\t\t\t\tif( *nIt != NULL) {\r\n\t\t\t\t\tdelete (*nIt);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} // IF relabeling aromatic -> non-aromatic necessary\r\n\r\n\t}\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\tAromaticityPerception::\r\n\tRingDescriptor::\r\n\tRingDescriptor()\r\n\t : edges()\r\n\t\t, ring()\r\n\t\t, predState(Unknown)\r\n\t\t, predCertainty(0)\r\n\t{\r\n\t}\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\tAromaticityPerception::\r\n\tRingDescriptor::\r\n\tRingDescriptor(\tconst RingList & ringList )\r\n\t : edges()\r\n\t\t, ring(ringList)\r\n\t\t, predState(Unknown)\r\n\t\t, predCertainty(0)\r\n\t{\r\n\t\t  // generate edge list description\r\n\t\tRingList::const_iterator cur=ringList.begin(), last=ringList.begin();\r\n\t\tfor (cur++; cur!=ringList.end(); ++cur,++last) {\r\n\t\t\tif (*cur<*last) {\r\n\t\t\t\tedges.insert( Edge(*cur,*last) );\r\n\t\t\t} else {\r\n\t\t\t\tedges.insert( Edge(*last,*cur) );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n}} // namespaces\r\n", "meta": {"hexsha": "1d0b9addc1d155b721d7a94a11c91e6946f9c626", "size": 29910, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ggl/chem/AromaticityPerception.cc", "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/ggl/chem/AromaticityPerception.cc", "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/ggl/chem/AromaticityPerception.cc", "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": 38.1992337165, "max_line_length": 218, "alphanum_fraction": 0.6022066199, "num_tokens": 7877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.028870908617445883, "lm_q1q2_score": 0.008873705217756423}}
{"text": "////////////////////////////////////////////////////////////////\n// Orkid Media Engine\n// Copyright 1996-2020, Michael T. Mayers.\n// Distributed under the Boost Software License - Version 1.0 - August 17, 2003\n// see http://www.boost.org/LICENSE_1_0.txt\n////////////////////////////////////////////////////////////////\n\n#include <ork/kernel/orklut.hpp>\n#include <ork/math/plane.h>\n#include <ork/lev2/gfx/meshutil/submesh.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\ntemplate class ork::orklut<std::string, ork::meshutil::submesh_ptr_t>;\n\nnamespace ork::meshutil {\n\nconst vertexpool vertexpool::EmptyPool;\n\n/////////////////////////////////////////////////////////////////////////\nsubmesh::submesh(const vertexpool& vpool)\n    : _vtxpool(vpool)\n    , _surfaceArea(0)\n    , _mergeEdges(true) {\n  for (int i = 0; i < kmaxsidesperpoly; i++)\n    _polyTypeCounter[i] = 0;\n}\n/////////////////////////////////////////////////////////////////////////\n// eigen to submesh converter for interfacing\n//  with various python/numpy packages\n/////////////////////////////////////////////////////////////////////////\nsubmesh_ptr_t submeshFromEigen(\n    const Eigen::MatrixXd& verts, //\n    const Eigen::MatrixXi& faces,\n    const Eigen::MatrixXd& uvs,\n    const Eigen::MatrixXd& colors,\n    const Eigen::MatrixXd& normals,\n    const Eigen::MatrixXd& binormals,\n    const Eigen::MatrixXd& tangents) {\n  auto rval           = std::make_shared<submesh>();\n  size_t numVerts     = verts.rows();\n  size_t numFaces     = faces.rows();\n  size_t sidesPerFace = faces.cols();\n  size_t numUvs       = uvs.rows();\n  size_t numColors    = colors.rows();\n  size_t numNormals   = normals.rows();\n  size_t numBinormals = binormals.rows();\n  size_t numTangents  = tangents.rows();\n  /////////////////////////////////////////////\n  OrkAssert(verts.cols() == 3);                                          // make sure we have vec3's\n  auto generateVertex = [&](int faceindex, int facevtxindex) -> vertex { //\n    vertex outv;\n    const Eigen::MatrixXi& face = faces.row(faceindex);\n    int per_vert_index          = face(facevtxindex);\n    /////////////////////////////////////////////\n    // position\n    /////////////////////////////////////////////\n    auto inp_pos = verts.row(per_vert_index);\n    outv.mPos    = fvec3(inp_pos(0), inp_pos(1), inp_pos(2));\n    /////////////////////////////////////////////\n    // normal\n    /////////////////////////////////////////////\n    auto donormal = [&](int index) {\n      OrkAssert(normals.cols() == 3);\n      auto inp  = normals.row(index);\n      outv.mNrm = fvec3(inp(0), inp(1), inp(2));\n    };\n    if (numNormals == numVerts) // per vertex\n      donormal(per_vert_index);\n    else if (numNormals == numFaces) // per face\n      donormal(faceindex);\n    else if (numNormals == 0) {\n    } // no normals\n    else\n      OrkAssert(false);\n    /////////////////////////////////////////////\n    // binormal\n    /////////////////////////////////////////////\n    auto dobinormal = [&](int index) {\n      OrkAssert(binormals.cols() == 3);\n      auto inp                 = binormals.row(index);\n      outv.mUV[0].mMapBiNormal = fvec3(inp(0), inp(1), inp(2));\n    };\n    if (numBinormals == numVerts) // per vertex\n      dobinormal(per_vert_index);\n    else if (numBinormals == numFaces) // per face\n      dobinormal(faceindex);\n    else if (numBinormals == 0) {\n    } // no binormals\n    else\n      OrkAssert(false);\n    /////////////////////////////////////////////\n    // tangent\n    /////////////////////////////////////////////\n    auto dotangent = [&](int index) {\n      OrkAssert(tangents.cols() == 3);\n      auto inp                = tangents.row(index);\n      outv.mUV[0].mMapTangent = fvec3(inp(0), inp(1), inp(2));\n    };\n    if (numTangents == numVerts) // per vertex\n      dotangent(per_vert_index);\n    else if (numTangents == numFaces) // per face\n      dotangent(faceindex);\n    else if (numTangents == 0) {\n    } // no tangents\n    else\n      OrkAssert(false);\n    /////////////////////////////////////////////\n    // texturecoord\n    /////////////////////////////////////////////\n    auto dotexcoord = [&](int index) {\n      OrkAssert(uvs.cols() == 2);\n      auto inp                 = uvs.row(index);\n      outv.mUV[0].mMapTexCoord = fvec2(inp(0), inp(1));\n    };\n    if (numUvs == numVerts) // per vertex\n      dotexcoord(per_vert_index);\n    else if (numUvs == numFaces) // per face\n      dotexcoord(faceindex);\n    else if (numUvs == 0) {\n    } // no texcoords\n    else\n      OrkAssert(false);\n    /////////////////////////////////////////////\n    // color\n    /////////////////////////////////////////////\n    auto docolor = [&](int index) {\n      auto inp = colors.row(index);\n      switch (colors.cols()) {\n        case 1: // luminance\n          outv.mCol[0] = fvec4(inp(0), inp(0), inp(0), 1);\n          break;\n        case 3: // rgb\n          outv.mCol[0] = fvec4(inp(0), inp(1), inp(2), 1);\n          break;\n        case 4: // rgba\n          outv.mCol[0] = fvec4(inp(0), inp(1), inp(2), inp(3));\n          break;\n        default:\n          OrkAssert(false);\n          break;\n      }\n    };\n    if (numColors == numVerts)\n      docolor(per_vert_index);\n    else if (numColors == numFaces)\n      docolor(faceindex);\n    else if (numColors == 1)\n      docolor(0);\n    else if (numColors == 0)\n      outv.mCol[0] = fvec4(1, 1, 1, 1);\n    else\n      OrkAssert(false);\n    return outv;\n  }; // auto generateVertex = [&](int faceindex, int facevtxindex) -> vertex { //\n  /////////////////////////////////////////////\n  for (int f = 0; f < numFaces; f++) {\n    switch (sidesPerFace) {\n      case 3: {\n        auto o0 = rval->newMergeVertex(generateVertex(f, 0));\n        auto o1 = rval->newMergeVertex(generateVertex(f, 1));\n        auto o2 = rval->newMergeVertex(generateVertex(f, 2));\n        rval->MergePoly(poly(o0, o1, o2));\n        break;\n      }\n      case 4: {\n        auto o0 = rval->newMergeVertex(generateVertex(f, 0));\n        auto o1 = rval->newMergeVertex(generateVertex(f, 1));\n        auto o2 = rval->newMergeVertex(generateVertex(f, 2));\n        auto o3 = rval->newMergeVertex(generateVertex(f, 3));\n        rval->MergePoly(poly(o0, o1, o2, o3));\n        break;\n      }\n      default:\n        OrkAssert(false);\n        break;\n    }\n  }\n  return rval;\n}\n/////////////////////////////////////////////////////////////////////////\nsubmesh::~submesh() {\n}\n/////////////////////////////////////////////////////////////////////////\nsvar64_t submesh::annotation(const char* annokey) const {\n  static const char* defret(\"\");\n  auto it = _annotations.find(std::string(annokey));\n  if (it != _annotations.end()) {\n    return (*it).second;\n  }\n  return defret;\n}\n/////////////////////////////////////////////////////////////////////////\nvoid submesh::MergeAnnos(const AnnotationMap& mrgannos, bool boverwrite) {\n  for (AnnotationMap::const_iterator it = mrgannos.begin(); it != mrgannos.end(); it++) {\n    const std::string& key      = it->first;\n    const auto& val             = it->second;\n    AnnotationMap::iterator itf = _annotations.find(key);\n    if (itf == _annotations.end()) {\n      _annotations[key] = val;\n    } else if (boverwrite) {\n      itf->second = val;\n    }\n  }\n}\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::ImportPolyAnnotations(const annopolylut& apl) {\n  int inumpolys = (int)_orderedPolys.size();\n  for (int ip = 0; ip < inumpolys; ip++) {\n    auto ply            = _orderedPolys[ip];\n    const AnnoMap* amap = apl.Find(*this, *ply);\n    if (amap) {\n      ply->SetAnnoMap(amap);\n    }\n  }\n}\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::ExportPolyAnnotations(annopolylut& apl) const {\n  int inumpolys = (int)_orderedPolys.size();\n  for (int ip = 0; ip < inumpolys; ip++) {\n    auto ply            = _orderedPolys[ip];\n    U64 uhash           = apl.HashItem(*this, *ply);\n    const AnnoMap* amap = ply->GetAnnoMap();\n    apl.mAnnoMap[uhash] = amap;\n  }\n}\n///////////////////////////////////////////////////////////////////////////////\nconst AABox& submesh::aabox() const {\n  if (_aaBoxDirty) {\n    _aaBox.BeginGrow();\n    int inumvtx = (int)RefVertexPool().GetNumVertices();\n    for (int i = 0; i < inumvtx; i++) {\n      const vertex& v = RefVertexPool().GetVertex(i);\n      _aaBox.Grow(v.mPos);\n    }\n    _aaBox.EndGrow();\n    _aaBoxDirty = false;\n  }\n  return _aaBox;\n}\n///////////////////////////////////////////////////////////////////////////////\nconst edge& submesh::RefEdge(U64 edgekey) const {\n  auto it = _edgemap.find(edgekey);\n  OrkAssert(it != _edgemap.end());\n  return *it->second;\n}\n///////////////////////////////////////////////////////////////////////////////\nvertex_ptr_t submesh::newMergeVertex(const vertex& vtx) {\n  _aaBoxDirty = true;\n  return _vtxpool.newMergeVertex(vtx);\n}\n///////////////////////////////////////////////////////////////////////////////\npoly& submesh::RefPoly(int i) {\n  OrkAssert(orkvector<int>::size_type(i) < _orderedPolys.size());\n  return *_orderedPolys[i];\n}\n///////////////////////////////////////////////////////////////////////////////\nconst poly& submesh::RefPoly(int i) const {\n  OrkAssert(orkvector<int>::size_type(i) < _orderedPolys.size());\n  return *_orderedPolys[i];\n}\n///////////////////////////////////////////////////////////////////////////////\nconst orkvector<poly_ptr_t>& submesh::RefPolys() const {\n  return _orderedPolys;\n}\n/////////////////////////////////////////////////////////////////////////\nvoid submesh::FindNSidedPolys(orkvector<int>& output, int inumsides) const {\n  int inump = (int)_orderedPolys.size();\n  for (int i = 0; i < inump; i++) {\n    const poly& ply = RefPoly(i);\n    if (ply.GetNumSides() == inumsides) {\n      output.push_back(i);\n    }\n  }\n}\n///////////////////////////////////////////////////////////////////////////////\nint submesh::GetNumPolys(int inumsides) const {\n  int iret = 0;\n  if (0 == inumsides) {\n    iret = (int)_orderedPolys.size();\n  } else {\n    OrkAssert(inumsides < kmaxsidesperpoly);\n    iret = _polyTypeCounter[inumsides];\n  }\n  return iret;\n}\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::GetEdges(const poly& ply, orkvector<edge>& Edges) const {\n  int icnt  = 0;\n  int icntf = 0;\n  for (int is = 0; is < ply.GetNumSides(); is++) {\n    U64 ue  = ply.mEdges[is]->GetHashKey();\n    auto it = _edgemap.find(ue);\n    if (it != _edgemap.end()) {\n      Edges.push_back(*it->second);\n      icntf++;\n    }\n    icnt++;\n  }\n}\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::GetAdjacentPolys(int ply, orkset<int>& output) const {\n  orkvector<edge> edges;\n  GetEdges(RefPoly(ply), edges);\n  for (orkvector<edge>::const_iterator edgeIter = edges.begin(); edgeIter != edges.end(); edgeIter++) {\n    orkset<int> connectedPolys;\n    GetConnectedPolys(*edgeIter, connectedPolys);\n    for (orkset<int>::const_iterator it2 = connectedPolys.begin(); it2 != connectedPolys.end(); it2++) {\n      int ic = *it2;\n      if (ic != ply) {\n        output.insert(connectedPolys.begin(), connectedPolys.end());\n      }\n    }\n  }\n}\n///////////////////////////////////////////////////////////////////////////////\nedge_constptr_t submesh::edgeBetween(int aind, int bind) const {\n  const poly& a = RefPoly(aind);\n  const poly& b = RefPoly(bind);\n  for (int eaind = 0; eaind < a.miNumSides; eaind++)\n    for (int ebind = 0; ebind < b.miNumSides; ebind++)\n      if (a.mEdges[eaind] == b.mEdges[ebind])\n        return std::const_pointer_cast<const edge>(a.mEdges[eaind]);\n  return nullptr;\n}\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::GetConnectedPolys(const edge& ed, orkset<int>& output) const {\n  U64 keyA    = ed.GetHashKey();\n  auto itfind = _edgemap.find(keyA);\n  if (itfind != _edgemap.end()) {\n    auto edfound = itfind->second;\n    int inump    = edfound->GetNumConnectedPolys();\n    for (int ip = 0; ip < inump; ip++) {\n      int ipi = edfound->GetConnectedPoly(ip);\n      output.insert(ipi);\n    }\n  }\n}\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::MergeSubMesh(const submesh& inp_mesh) {\n  float ftimeA     = float(OldSchool::GetRef().GetLoResTime());\n  int inumpingroup = inp_mesh.GetNumPolys();\n  for (int i = 0; i < inumpingroup; i++) {\n    const poly& ply = inp_mesh.RefPoly(i);\n    int inumpv      = ply.GetNumSides();\n    poly NewPoly;\n    NewPoly.miNumSides = inumpv;\n    for (int iv = 0; iv < inumpv; iv++) {\n      int ivi               = ply.GetVertexID(iv);\n      const vertex& src_vtx = inp_mesh.RefVertexPool().GetVertex(ivi);\n      NewPoly._vertices[iv] = newMergeVertex(src_vtx);\n    }\n    NewPoly.SetAnnoMap(ply.GetAnnoMap());\n    MergePoly(NewPoly);\n  }\n  float ftimeB = float(OldSchool::GetRef().GetLoResTime());\n  float ftime  = (ftimeB - ftimeA);\n  orkprintf(\"<<PROFILE>> <<submesh::MergeSubMesh %f seconds>>\\n\", ftime);\n}\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::MergePoly(const poly& ply) {\n  int ipolyindex = GetNumPolys();\n  poly nply      = ply;\n  int inumv      = ply.GetNumSides();\n  OrkAssert(inumv <= kmaxsidesperpoly);\n  ///////////////////////////////\n  // zero area poly removal\n  switch (inumv) {\n    case 3: {\n      if ((ply._vertices[0]->_poolindex == ply._vertices[1]->_poolindex) ||\n          (ply._vertices[1]->_poolindex == ply._vertices[2]->_poolindex) ||\n          (ply._vertices[2]->_poolindex == ply._vertices[0]->_poolindex)) {\n        orkprintf(\n            \"Mesh::MergePoly() removing zero area tri<%d %d %d>\\n\",\n            ply._vertices[0]->_poolindex,\n            ply._vertices[1]->_poolindex,\n            ply._vertices[2]->_poolindex);\n\n        return;\n      }\n      break;\n    }\n    case 4: {\n      if ((ply._vertices[0]->_poolindex == ply._vertices[1]->_poolindex) ||\n          (ply._vertices[0]->_poolindex == ply._vertices[2]->_poolindex) ||\n          (ply._vertices[0]->_poolindex == ply._vertices[3]->_poolindex) ||\n          (ply._vertices[1]->_poolindex == ply._vertices[2]->_poolindex) ||\n          (ply._vertices[1]->_poolindex == ply._vertices[3]->_poolindex) ||\n          (ply._vertices[2]->_poolindex == ply._vertices[3]->_poolindex)) {\n        orkprintf(\n            \"Mesh::MergePoly() removing zero area quad<%d %d %d %d>\\n\",\n            ply._vertices[0]->_poolindex,\n            ply._vertices[1]->_poolindex,\n            ply._vertices[2]->_poolindex,\n            ply._vertices[3]->_poolindex);\n\n        return;\n      }\n      break;\n    }\n    default:\n      break;\n      // TODO n-sided polys\n  }\n  //////////////////////////////\n  // dupe check\n  U64 ucrc   = ply.HashIndices();\n  auto itfhm = _polymap.find(ucrc);\n  ///////////////////////////////\n  if (itfhm == _polymap.end()) // no match\n  {\n    int inewpi = (int)_orderedPolys.size();\n    //////////////////////////////////////////////////\n    // connect to vertices\n    for (int i = 0; i < inumv; i++) {\n      auto vtx = ply._vertices[i];\n      // vtx->ConnectToPoly(inewpi);\n    }\n    //////////////////////////////////////////////////\n    // add edges\n    if (_mergeEdges) {\n      for (int i = 0; i < inumv; i++) {\n        int i0  = (i);\n        int i1  = (i + 1) % inumv;\n        int iv0 = ply.GetVertexID(i0);\n        int iv1 = ply.GetVertexID(i1);\n        auto v0 = _vtxpool._orderedVertices[iv0];\n        auto v1 = _vtxpool._orderedVertices[iv1];\n\n        edge Edge(v0, v1);\n        nply.mEdges[i] = MergeEdge(Edge, ipolyindex);\n      }\n    }\n    nply.SetAnnoMap(ply.GetAnnoMap());\n    auto new_poly = std::make_shared<poly>(nply);\n    _orderedPolys.push_back(new_poly);\n    _polymap[ucrc] = new_poly;\n    //////////////////////////////////////////////////\n    // add n sided counters\n    _polyTypeCounter[inumv]++;\n    //////////////////////////////////////////////////\n    float farea = ply.ComputeArea(_vtxpool, ork::fmtx4::Identity());\n    _surfaceArea += farea;\n  }\n  _aaBoxDirty = true;\n}\n///////////////////////////////////////////////////////////////////////////////\nedge_ptr_t submesh::MergeEdge(const edge& ed, int ipolyindex) {\n  U64 crcA    = ed.GetHashKey();\n  auto itfind = _edgemap.find(crcA);\n\n  edge_ptr_t rval;\n\n  if (_edgemap.end() != itfind) {\n    rval     = itfind->second;\n    U64 crcB = rval->GetHashKey();\n    OrkAssert(ed.Matches(*rval));\n  } else {\n    rval           = std::make_shared<edge>(ed);\n    _edgemap[crcA] = rval;\n  }\n  if (ipolyindex >= 0) {\n    rval->ConnectToPoly(ipolyindex);\n  }\n\n  _aaBoxDirty = true;\n  return rval;\n}\n///////////////////////////////////////////////////////////////////////////////\n// addPoly helper methods\n///////////////////////////////////////////////////////////////////////////////\nvoid submesh::addQuad(fvec3 p0, fvec3 p1, fvec3 p2, fvec3 p3, fvec4 c) {\n  vertex muvtx[4];\n  muvtx[0].set(p0, fvec3(), fvec3(), fvec2(), c);\n  muvtx[1].set(p1, fvec3(), fvec3(), fvec2(), c);\n  muvtx[2].set(p2, fvec3(), fvec3(), fvec2(), c);\n  muvtx[3].set(p3, fvec3(), fvec3(), fvec2(), c);\n  auto v0 = newMergeVertex(muvtx[0]);\n  auto v1 = newMergeVertex(muvtx[1]);\n  auto v2 = newMergeVertex(muvtx[2]);\n  auto v3 = newMergeVertex(muvtx[3]);\n  MergePoly(poly(v0, v1, v2, v3));\n}\nvoid submesh::addQuad(fvec3 p0, fvec3 p1, fvec3 p2, fvec3 p3, fvec2 uv0, fvec2 uv1, fvec2 uv2, fvec2 uv3, fvec4 c) {\n  vertex muvtx[4];\n  fvec3 p0p1 = (p1 - p0).Normal();\n  fvec3 p0p2 = (p2 - p0).Normal();\n  fvec3 nrm  = p0p1.Cross(p0p2);\n  // todo compute tangent space from uv gradients\n  fvec3 bin = p0p1;\n  muvtx[0].set(p0, nrm, bin, uv0, c);\n  muvtx[1].set(p1, nrm, bin, uv1, c);\n  muvtx[2].set(p2, nrm, bin, uv2, c);\n  muvtx[3].set(p3, nrm, bin, uv3, c);\n\n  auto v0 = newMergeVertex(muvtx[0]);\n  auto v1 = newMergeVertex(muvtx[1]);\n  auto v2 = newMergeVertex(muvtx[2]);\n  auto v3 = newMergeVertex(muvtx[3]);\n  MergePoly(poly(v0, v1, v2, v3));\n}\nvoid submesh::addQuad(\n    fvec3 p0,\n    fvec3 p1,\n    fvec3 p2,\n    fvec3 p3,\n    fvec3 n0,\n    fvec3 n1,\n    fvec3 n2,\n    fvec3 n3,\n    fvec2 uv0,\n    fvec2 uv1,\n    fvec2 uv2,\n    fvec2 uv3,\n    fvec4 c) { /// add quad helper method\n  vertex muvtx[4];\n  fvec3 p0p1 = (p1 - p0).Normal();\n  fvec3 bin  = p0p1;\n  muvtx[0].set(p0, n0, bin, uv0, c);\n  muvtx[1].set(p1, n1, bin, uv1, c);\n  muvtx[2].set(p2, n2, bin, uv2, c);\n  muvtx[3].set(p3, n3, bin, uv3, c);\n\n  auto v0 = newMergeVertex(muvtx[0]);\n  auto v1 = newMergeVertex(muvtx[1]);\n  auto v2 = newMergeVertex(muvtx[2]);\n  auto v3 = newMergeVertex(muvtx[3]);\n  MergePoly(poly(v0, v1, v2, v3));\n}\n///////////////////////////////////////////////////////////////////////////////\n/*\nvoid SubMesh::GenIndexBuffers( void )\n{\n    int inumvtx = RefVertexPool().VertexPool.size();\n\n    orkvector<int> TrianglePolyIndices;\n    orkvector<int> QuadPolyIndices;\n\n    FindNSidedPolys( TrianglePolyIndices, 3 );\n    FindNSidedPolys( QuadPolyIndices, 4 );\n\n    int inumtri( TrianglePolyIndices.size() );\n    int inumquad( QuadPolyIndices.size() );\n\n    mpBaseTriangleIndices = new U16[ inumtri*3 ];\n    mpBaseQuadIndices = new U16[ inumquad*4 ];\n\n    for( int itri=0; itri<inumtri; itri++ )\n    {\n        int iti = TrianglePolyIndices[itri];\n\n        const poly & tri = RefPoly( iti );\n\n        int i0 = tri.miVertices[0];\n        int i1 = tri.miVertices[1];\n        int i2 = tri.miVertices[2];\n\n        OrkAssert( i0<inumvtx );\n        OrkAssert( i1<inumvtx );\n        OrkAssert( i2<inumvtx );\n\n        mpBaseTriangleIndices[ (itri*3)+0 ] = U16(i0);\n        mpBaseTriangleIndices[ (itri*3)+1 ] = U16(i1);\n        mpBaseTriangleIndices[ (itri*3)+2 ] = U16(i2);\n    }\n\n    for( int iqua=0; iqua<inumquad; iqua++ )\n    {\n        int iqi = QuadPolyIndices[iqua];\n\n        const poly & qu = RefPoly( iqi );\n\n        int i0 = qu.miVertices[0];\n        int i1 = qu.miVertices[1];\n        int i2 = qu.miVertices[2];\n        int i3 = qu.miVertices[3];\n\n        OrkAssert( i0<inumvtx );\n        OrkAssert( i1<inumvtx );\n        OrkAssert( i2<inumvtx );\n        OrkAssert( i3<inumvtx );\n\n        mpBaseQuadIndices[ (iqua*4)+0 ] = U16(i0);\n        mpBaseQuadIndices[ (iqua*4)+1 ] = U16(i1);\n        mpBaseQuadIndices[ (iqua*4)+2 ] = U16(i2);\n        mpBaseQuadIndices[ (iqua*4)+3 ] = U16(i3);\n    }\n\n}*/\n} // namespace ork::meshutil\n", "meta": {"hexsha": "10cbc9418412318d54aff79b1a91fad1ab30c004", "size": 20254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ork.lev2/src/gfx/meshutil/submesh.cpp", "max_stars_repo_name": "tweakoz/orkid", "max_stars_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T04:21:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T05:19:27.000Z", "max_issues_repo_path": "ork.lev2/src/gfx/meshutil/submesh.cpp", "max_issues_repo_name": "tweakoz/orkid", "max_issues_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2019-08-23T04:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T04:04:11.000Z", "max_forks_repo_path": "ork.lev2/src/gfx/meshutil/submesh.cpp", "max_forks_repo_name": "tweakoz/orkid", "max_forks_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-02-20T18:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T03:47:55.000Z", "avg_line_length": 34.2707275804, "max_line_length": 116, "alphanum_fraction": 0.5084427767, "num_tokens": 5713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.025957355596589876, "lm_q1q2_score": 0.008866578403492358}}
{"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 SLHA_IO_H\n#define SLHA_IO_H\n\n#include <string>\n#include <iosfwd>\n#include <vector>\n#include <Eigen/Core>\n#include <boost/format.hpp>\n#include <boost/function.hpp>\n#include \"slhaea.h\"\n#include \"config.h\"\n#include \"logger.hpp\"\n#include \"error.hpp\"\n#include \"wrappers.hpp\"\n#include \"numerics2.hpp\"\n#include \"pmns.hpp\"\n\nnamespace softsusy {\n   class QedQcd;\n   class DoubleMatrix;\n   class ComplexMatrix;\n}\n\nnamespace flexiblesusy {\n\n   class Spectrum_generator_settings;\n   class Physical_input;\n\n   namespace {\n      /// SLHA line formatter for the MASS block entries\n      const boost::format mass_formatter(\" %9d   %16.8E   # %s\\n\");\n      /// SLHA line formatter for the mixing matrix entries (NMIX, UMIX, VMIX, ...)\n      const boost::format mixing_matrix_formatter(\" %2d %2d   %16.8E   # %s\\n\");\n      /// SLHA line formatter for vector entries\n      const boost::format vector_formatter(\" %5d   %16.8E   # %s\\n\");\n      /// SLHA number formatter\n      const boost::format number_formatter(\"         %16.8E   # %s\\n\");\n      /// SLHA line formatter for entries with three indices\n      const boost::format tensor_formatter(\" %8d %8d %8d   %16.8E   # %s\\n\");\n      /// SLHA scale formatter\n      const boost::format scale_formatter(\"%9.8E\");\n      /// SLHA line formatter for the one-element entries (HMIX, GAUGE, MSOFT, ...)\n      const boost::format single_element_formatter(\" %5d   %16.8E   # %s\\n\");\n      /// SLHA line formatter for the SPINFO block entries\n      const boost::format spinfo_formatter(\" %5d   %s\\n\");\n   }\n\n#define FORMAT_MASS(pdg,mass,name)                                      \\\n   boost::format(mass_formatter) % (pdg) % (mass) % (name)\n#define FORMAT_MIXING_MATRIX(i,k,entry,name)                            \\\n   boost::format(mixing_matrix_formatter) % (i) % (k) % (entry) % (name)\n#define FORMAT_ELEMENT(pdg,value,name)                                  \\\n   boost::format(single_element_formatter) % (pdg) % (value) % (name)\n#define FORMAT_SCALE(n)                                                 \\\n   boost::format(scale_formatter) % (n)\n#define FORMAT_NUMBER(n,str)                                            \\\n   boost::format(number_formatter) % (n) % (str)\n#define FORMAT_SPINFO(n,str)                                            \\\n   boost::format(spinfo_formatter) % (n) % (str)\n#define FORMAT_RANK_THREE_TENSOR(i,j,k,entry,name)                      \\\n   boost::format(tensor_formatter) % (i) % (j) % (k) % (entry) % (name)\n\n/**\n * @class SLHA_io\n * @brief Handles reading and writing of SLHA files\n *\n * Reading: There are two ways to read block entries from SLHA files:\n * a) using the read_block() function with a %SLHA_io::Tuple_processor\n * or b) using the read_entry() function for each entry.  Note, that\n * a) is much faster than b) (more than 1000 times) because b) needs\n * to search for the block each time read_entry() is called.\n *\n * Example how to use a tuple processor (fast!):\n * \\code{.cpp}\nvoid process_tuple(double* array, int key, double value) {\n   array[key] = value;\n}\n\nvoid read_file() {\n   double array[1000];\n\n   SLHA_io reader;\n   reader.read_from_file(\"file.slha\");\n\n   SLHA_io::Tuple_processor processor\n      = boost::bind(&process_tuple, array, _1, _2);\n\n   reader.read_block(\"MyBlock\", processor);\n}\n * \\endcode\n *\n * Example how to use a for loop (slow!):\n * \\code{.cpp}\nvoid read_file() {\n   double array[1000];\n\n   SLHA_io reader;\n   reader.read_from_file(\"file.slha\");\n\n   for (int i = 0; i < 1000; i++) {\n      array[i] = reader.read_entry(\"MyBlock\", i);\n   }\n}\n * \\endcode\n */\nclass SLHA_io {\npublic:\n   typedef boost::function<void(int, double)> Tuple_processor;\n   enum Position { front, back };\n   struct Modsel {\n      bool quark_flavour_violated;   ///< key = 6\n      bool lepton_flavour_violated;  ///< key = 6\n      double parameter_output_scale; ///< key = 12\n      Modsel()\n         : quark_flavour_violated(false)\n         , lepton_flavour_violated(false)\n         , parameter_output_scale(0.)\n         {}\n      void clear() {\n         quark_flavour_violated = false;\n         lepton_flavour_violated = false;\n         parameter_output_scale = 0.;\n      }\n   };\n\n   struct CKM_wolfenstein {\n      double lambdaW, aCkm, rhobar, etabar;\n      CKM_wolfenstein() : lambdaW(0.), aCkm(0.), rhobar(0.), etabar(0.) {}\n      void clear() {\n         lambdaW = 0.;\n         aCkm    = 0.;\n         rhobar  = 0.;\n         etabar  = 0.;\n      }\n   };\n\n   class ReadError : public Error {\n   public:\n      ReadError(const std::string& message_) : message(message_) {}\n      virtual ~ReadError() {}\n      virtual std::string what() const { return message; }\n   private:\n      std::string message;\n   };\n\n   SLHA_io();\n   ~SLHA_io() {}\n\n   void clear();\n\n   // reading functions\n   bool block_exists(const std::string&) const;\n   void fill(softsusy::QedQcd&) const;\n   void fill(Spectrum_generator_settings&) const;\n   void fill(Physical_input&) const;\n   const Modsel& get_modsel() const { return modsel; }\n   const SLHAea::Coll& get_data() const { return data; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   double read_block(const std::string&, const Tuple_processor&) const;\n   template <class Derived>\n   double read_block(const std::string&, Eigen::MatrixBase<Derived>&) const;\n   double read_block(const std::string&, double&) const;\n   double read_entry(const std::string&, int) const;\n   void read_modsel();\n   double read_scale(const std::string&) const;\n\n   // writing functions\n   void set_data(const SLHAea::Coll& data_) { data = data_; }\n   void set_block(const std::ostringstream&, Position position = back);\n   void set_block(const std::string&, Position position = back);\n   void set_blocks(const std::vector<std::string>&, Position position = back);\n   void set_block(const std::string&, double, const std::string&, double scale = 0.);\n   template<class Scalar, int M, int N>\n   void set_block(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, N>&, const std::string&, double scale = 0.);\n   template<class Scalar, int M>\n   void set_block(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, 1>&, const std::string&, double scale = 0.);\n   template<class Scalar, int M, int N>\n   void set_block_imag(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, N>&, const std::string&, double scale = 0.);\n   template<class Scalar, int M>\n   void set_block_imag(const std::string&, const Eigen::Matrix<std::complex<Scalar>, M, 1>&, const std::string&, double scale = 0.);\n   template <class Derived>\n   void set_block(const std::string&, const Eigen::MatrixBase<Derived>&, const std::string&, double scale = 0.);\n   template <class Derived>\n   void set_block_imag(const std::string&, const Eigen::MatrixBase<Derived>&, const std::string&, double scale = 0.);\n   void set_block(const std::string&, const softsusy::DoubleMatrix&, const std::string&, double scale = 0.);\n   void set_block(const std::string&, const softsusy::ComplexMatrix&, const std::string&, double scale = 0.);\n   void set_sminputs(const softsusy::QedQcd&);\n   void write_to_file(const std::string&);\n   void write_to_stream(std::ostream& = std::cout);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>&,\n                                                         Eigen::Matrix<double, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_slha(double&,\n                                                         Eigen::Matrix<double, 1, 1>&);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>&,\n                                                         Eigen::Matrix<std::complex<double>, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_slha(double&,\n                                                         Eigen::Matrix<std::complex<double>, 1, 1>&);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>&,\n                                                       Eigen::Matrix<double, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_hk(double&,\n                                                       Eigen::Matrix<double, 1, 1>&);\n\n   template<int N>\n   static void convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>&,\n                                                       Eigen::Matrix<std::complex<double>, N, N>&);\n\n   static void convert_symmetric_fermion_mixings_to_hk(double&,\n                                                       Eigen::Matrix<std::complex<double>, 1, 1>&);\n\nprivate:\n   SLHAea::Coll data;          ///< SHLA data\n   Modsel modsel;              ///< data from block MODSEL\n   template <class Scalar>\n   static Scalar convert_to(const std::string&); ///< convert string\n   static std::string to_lower(const std::string&); ///< string to lower case\n   static void process_sminputs_tuple(softsusy::QedQcd&, int, double);\n   static void process_modsel_tuple(Modsel&, int, double);\n   static void process_vckmin_tuple(CKM_wolfenstein&, int, double);\n   static void process_upmnsin_tuple(PMNS_parameters&, int, double);\n   static void process_flexiblesusy_tuple(Spectrum_generator_settings&, int, double);\n   static void process_flexiblesusyinput_tuple(Physical_input&, int, double);\n};\n\ntemplate <class Scalar>\nScalar SLHA_io::convert_to(const std::string& str)\n{\n   Scalar value;\n   try {\n      value = SLHAea::to<Scalar>(str);\n   }  catch (const boost::bad_lexical_cast& error) {\n      const std::string msg(\"cannot convert string \\\"\" + str + \"\\\" to \"\n                            + typeid(Scalar).name());\n      throw ReadError(msg);\n   }\n   return value;\n}\n\n/**\n * Fills a matrix from a SLHA block\n *\n * @param block_name block name\n * @param matrix matrix to be filled\n *\n * @return scale (or 0 if no scale is defined)\n */\ntemplate <class Derived>\ndouble SLHA_io::read_block(const std::string& block_name, Eigen::MatrixBase<Derived>& matrix) const\n{\n   SLHAea::Coll::const_iterator block =\n      data.find(data.cbegin(), data.cend(), block_name);\n\n   const int cols = matrix.cols(), rows = matrix.rows();\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 (cols == 1) {\n            // vector\n            if (line->size() >= 2) {\n               const int i = convert_to<int>((*line)[0]) - 1;\n               if (0 <= i && i < rows) {\n                  const double value = convert_to<double>((*line)[1]);\n                  matrix(i,0) = value;\n               }\n            }\n         } else {\n            // martix\n            if (line->size() >= 3) {\n               const int i = convert_to<int>((*line)[0]) - 1;\n               const int k = convert_to<int>((*line)[1]) - 1;\n               if (0 <= i && i < rows && 0 <= k && k < cols) {\n                  const double value = convert_to<double>((*line)[2]);\n                  matrix(i,k) = value;\n               }\n            }\n         }\n      }\n\n      ++block;\n      block = data.find(block, data.cend(), block_name);\n   }\n\n   return scale;\n}\n\ntemplate<class Scalar, int NRows>\nvoid SLHA_io::set_block(const std::string& name,\n                        const Eigen::Matrix<std::complex<Scalar>, NRows, 1>& 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 <= NRows; ++i) {\n      ss << boost::format(vector_formatter) % i % Re(matrix(i-1,0))\n         % (\"Re(\" + symbol + \"(\" + ToString(i) + \"))\");\n   }\n\n   set_block(ss);\n}\n\ntemplate<class Scalar, int NRows, int NCols>\nvoid SLHA_io::set_block(const std::string& name,\n                        const Eigen::Matrix<std::complex<Scalar>, NRows, NCols>& 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 <= NRows; ++i) {\n      for (int k = 1; k <= NCols; ++k) {\n         ss << boost::format(mixing_matrix_formatter) % i % k\n            % Re(matrix(i-1,k-1))\n            % (\"Re(\" + symbol + \"(\" + ToString(i) + \",\"\n               + ToString(k) + \"))\");\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate<class Scalar, int NRows>\nvoid SLHA_io::set_block_imag(const std::string& name,\n                             const Eigen::Matrix<std::complex<Scalar>, NRows, 1>& 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 <= NRows; ++i) {\n      ss << boost::format(vector_formatter) % i % Im(matrix(i-1,0))\n         % (\"Im(\" + symbol + \"(\" + ToString(i) + \"))\");\n   }\n\n   set_block(ss);\n}\n\ntemplate<class Scalar, int NRows, int NCols>\nvoid SLHA_io::set_block_imag(const std::string& name,\n                             const Eigen::Matrix<std::complex<Scalar>, NRows, NCols>& 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 <= NRows; ++i) {\n      for (int k = 1; k <= NCols; ++k) {\n         ss << boost::format(mixing_matrix_formatter) % i % k\n            % Im(matrix(i-1,k-1))\n            % (\"Im(\" + symbol + \"(\" + ToString(i) + \",\"\n               + ToString(k) + \"))\");\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate <class Derived>\nvoid SLHA_io::set_block(const std::string& name,\n                        const Eigen::MatrixBase<Derived>& 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   const int rows = matrix.rows();\n   const int cols = matrix.cols();\n   for (int i = 1; i <= rows; ++i) {\n      if (cols == 1) {\n         ss << boost::format(vector_formatter) % i % matrix(i-1,0)\n            % (symbol + \"(\" + ToString(i) + \")\");\n      } else {\n         for (int k = 1; k <= cols; ++k) {\n            ss << boost::format(mixing_matrix_formatter) % i % k % matrix(i-1,k-1)\n               % (symbol + \"(\" + ToString(i) + \",\" + ToString(k) + \")\");\n         }\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate <class Derived>\nvoid SLHA_io::set_block_imag(const std::string& name,\n                             const Eigen::MatrixBase<Derived>& 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   const int rows = matrix.rows();\n   const int cols = matrix.cols();\n   for (int i = 1; i <= rows; ++i) {\n      if (cols == 1) {\n         ss << boost::format(vector_formatter) % i % Im(matrix(i-1,0))\n            % (\"Im(\" + symbol + \"(\" + ToString(i) + \"))\");\n      } else {\n         for (int k = 1; k <= cols; ++k) {\n            ss << boost::format(mixing_matrix_formatter) % i % k % Im(matrix(i-1,k-1))\n               % (\"Im(\" + symbol + \"(\" + ToString(i) + \",\" + ToString(k) + \"))\");\n         }\n      }\n   }\n\n   set_block(ss);\n}\n\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>&,\n                                                        Eigen::Matrix<double, N, N>&)\n{\n}\n\n/**\n * Converts the given vector of masses and the corresponding (complex)\n * mixing matrix to SLHA convention: Matrix rows with non-zero\n * imaginary parts are multiplied by i and the corresponding mass\n * eigenvalue is multiplied by -1.  As a result the mixing matrix will\n * be real and the mass eigenvalues might be positive or negative.  It\n * is assumed that these mixings result from diagonalizing a symmetric\n * fermion mass matrix in the convention of Haber and Kane,\n * Phys. Rept. 117 (1985) 75-263.  This conversion makes sense only if\n * the original symmetric mass matrix is real-valued.\n *\n * @param m vector of masses\n * @param z mixing matrix\n */\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_slha(Eigen::Array<double, N, 1>& m,\n                                                        Eigen::Matrix<std::complex<double>, N, N>& z)\n{\n   for (int i = 0; i < N; i++) {\n      // check if i'th row contains non-zero imaginary parts\n      if (!is_zero(z.row(i).imag().cwiseAbs().maxCoeff())) {\n         z.row(i) *= std::complex<double>(0.0,1.0);\n         m(i) *= -1;\n#ifdef ENABLE_DEBUG\n         if (!is_zero(z.row(i).imag().cwiseAbs().maxCoeff())) {\n            WARNING(\"Row \" << i << \" 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}\n\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>&,\n                                                      Eigen::Matrix<double, N, N>&)\n{\n}\n\n/**\n * Converts the given vector of masses and the corresponding (real)\n * mixing matrix to Haber-Kane convention (Phys. Rept. 117 (1985)\n * 75-263): Masses are positive and mixing matrices can be complex.\n *\n * @param m vector of masses\n * @param z mixing matrix\n */\ntemplate<int N>\nvoid SLHA_io::convert_symmetric_fermion_mixings_to_hk(Eigen::Array<double, N, 1>& m,\n                                                      Eigen::Matrix<std::complex<double>, N, N>& z)\n{\n   for (int i = 0; i < N; i++) {\n      if (m(i) < 0.) {\n         z.row(i) *= std::complex<double>(0.0,1.0);\n         m(i) *= -1;\n      }\n   }\n}\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "7ca657d19bae2b57fc418cdbc3c75cc3e9218642", "size": 19061, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/slha_io.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/slha_io.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/slha_io.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": 35.7617260788, "max_line_length": 132, "alphanum_fraction": 0.5753633073, "num_tokens": 4881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.03258974159488465, "lm_q1q2_score": 0.00886520982761869}}
{"text": "#pragma once\n#include <boost/pending/disjoint_sets.hpp>\n#include \"xtensor/xtensor.hpp\"\n#include \"affogato/util.hxx\"\n#include <queue>\n#include <functional>\n\nnamespace affogato {\nnamespace segmentation {\n\n    //\n    // mutex helper functions:\n    // check_mutex: check if mutex exists between two representatives\n    // insert_mutex: insert mutex between two representatives\n    // merge_mutexex: merge mutex constrained of two mutex stores\n    //\n\n\n    template<class MUTEX_STORAGE>\n    inline bool check_mutex(const uint64_t ru, const uint64_t rv,\n                            const MUTEX_STORAGE & mutexes) {\n        // get iterators to the mutex vectors of rep u and rep v\n        auto mutex_it_u = mutexes[ru].begin();\n        auto mutex_it_v = mutexes[rv].begin();\n\n        // check if the mutex vectors contain the same mutex edge\n        while (mutex_it_u != mutexes[ru].end() && mutex_it_v != mutexes[rv].end()) {\n            if (*mutex_it_u < *mutex_it_v) {\n                ++mutex_it_u;\n            } else  {\n                if (!(*mutex_it_v < *mutex_it_u)) {\n                    return true;\n                }\n                ++mutex_it_v;\n            }\n        }\n        return false;\n    }\n\n\n    // insert 'mutex_edge_id' into the vectors containing mutexes of 'ru' and 'rv'\n    template<class MUTEX_STORAGE>\n    inline void insert_mutex(const uint64_t ru, const uint64_t rv,\n                             const uint64_t mutex_edge_id, MUTEX_STORAGE & mutexes) {\n        mutexes[ru].insert(std::upper_bound(mutexes[ru].begin(),\n                                            mutexes[ru].end(),\n                                            mutex_edge_id), mutex_edge_id);\n        mutexes[rv].insert(std::upper_bound(mutexes[rv].begin(),\n                                            mutexes[rv].end(),\n                                            mutex_edge_id), mutex_edge_id);\n    }\n\n\n    // merge the mutex edges by merging from 'root_from' to 'root_to'\n    template<class MUTEX_STORAGE>\n    inline void merge_mutexes(const uint64_t root_from, const uint64_t root_to,\n                              MUTEX_STORAGE & mutexes) {\n        if (mutexes[root_from].size() == 0) {\n            return;\n        }\n\n        if (mutexes[root_to].size() == 0){\n            mutexes[root_to] = mutexes[root_from];\n            return;\n        }\n\n        std::vector<uint64_t> merge_buffer;\n        merge_buffer.reserve(std::max(mutexes[root_from].size(), mutexes[root_to].size()));\n\n        std::merge(mutexes[root_from].begin(), mutexes[root_from].end(),\n                   mutexes[root_to].begin(), mutexes[root_to].end(),\n                   std::back_inserter(merge_buffer));\n\n        mutexes[root_to] = merge_buffer;\n        mutexes[root_from].clear();\n    }\n\n\n    // compute mutex clustering for a graph with attrative and mutex edges\n    template<class EDGE_ARRAY, class WEIGHT_ARRAY, class NODE_ARRAY>\n    void compute_mws_clustering(const size_t number_of_labels,\n                                const xt::xexpression<EDGE_ARRAY> & uvs_exp,\n                                const xt::xexpression<EDGE_ARRAY> & mutex_uvs_exp,\n                                const xt::xexpression<WEIGHT_ARRAY> & weights_exp,\n                                const xt::xexpression<WEIGHT_ARRAY> & mutex_weights_exp,\n                                xt::xexpression<NODE_ARRAY> & node_labeling_exp) {\n\n        // casts\n        const auto & uvs = uvs_exp.derived_cast();\n        const auto & mutex_uvs = mutex_uvs_exp.derived_cast();\n        const auto & weights = weights_exp.derived_cast();\n        const auto & mutex_weights = mutex_weights_exp.derived_cast();\n        auto & node_labeling = node_labeling_exp.derived_cast();\n\n        // make ufd\n        std::vector<uint64_t> ranks(number_of_labels);\n        std::vector<uint64_t> parents(number_of_labels);\n        boost::disjoint_sets<uint64_t*, uint64_t*> ufd(&ranks[0], &parents[0]);\n        for(uint64_t label = 0; label < number_of_labels; ++label) {\n            ufd.make_set(label);\n        }\n\n        // determine number of edge types\n        const size_t num_edges = uvs.shape()[0];\n        const size_t num_mutex = mutex_uvs.shape()[0];\n\n        // argsort ALL edges\n        // we sort in ascending order\n        std::vector<size_t> indices(num_edges + num_mutex);\n        std::iota(indices.begin(), indices.end(), 0);\n        std::sort(indices.begin(), indices.end(), [&](const size_t a, const size_t b){\n            const double val_a = (a < num_edges) ? weights(a) : mutex_weights(a - num_edges);\n            const double val_b = (b < num_edges) ? weights(b) : mutex_weights(b - num_edges);\n            return val_a > val_b;\n        });\n\n        // data-structure storing mutex edges\n        typedef std::vector<std::vector<uint64_t>> MutexStorage;\n        MutexStorage mutexes(number_of_labels);\n\n        // iterate over all edges\n        for(const size_t edge_id : indices) {\n\n            // check whether this edge is mutex via the edge offset\n            const bool is_mutex_edge = edge_id >= num_edges;\n\n            // find the edge-id or mutex id and the connected nodes\n            const size_t id = is_mutex_edge ? edge_id - num_edges : edge_id;\n            const uint64_t u = is_mutex_edge ? mutex_uvs(id, 0) : uvs(id, 0);\n            const uint64_t v = is_mutex_edge ? mutex_uvs(id, 1) : uvs(id, 1);\n\n            // find the current representatives\n            uint64_t ru = ufd.find_set(u);\n            uint64_t rv = ufd.find_set(v);\n\n            // if the nodes are already connected, do nothing\n            if(ru == rv) {\n                continue;\n            }\n\n            // if we already have a mutex, we do not need to do anything\n            // (if this is a regular edge, we do not link, if it is a mutex edge\n            //  we do not need to insert the redundant mutex constraint)\n            if(check_mutex(ru, rv, mutexes)) {\n                continue;\n            }\n\n            if(is_mutex_edge) {\n\n                // insert mutex constraint\n                insert_mutex(ru, rv, id, mutexes);\n\n            } else {\n\n                // link the nodes and merge their mutex constraints\n                ufd.link(u, v);\n                // check  if we have to swap the roots\n                if(ufd.find_set(ru) == rv) {\n                    std::swap(ru, rv);\n                }\n                // merge mutexes from rv -> ru\n                merge_mutexes(rv, ru, mutexes);\n            }\n        }\n\n        // get node labeling into output\n        for(size_t label = 0; label < number_of_labels; ++label) {\n            node_labeling[label] = ufd.find_set(label);\n        }\n\n        util::export_consecutive_labels(ufd, number_of_labels, node_labeling);\n    }\n\n\n    // compute mutex segmentation via kruskal\n    template<class WEIGHT_ARRAY, class NODE_ARRAY, class INDICATOR_ARRAY>\n    void compute_mws_segmentation(const xt::xexpression<WEIGHT_ARRAY> & sorted_flat_indices_exp,\n                                  const xt::xexpression<INDICATOR_ARRAY> & valid_edges_exp,\n                                  const std::vector<std::vector<int>> & offsets,\n                                  const size_t number_of_attractive_channels,\n                                  const std::vector<int> & image_shape,\n                                  xt::xexpression<NODE_ARRAY> & node_labeling_exp) {\n\n        // casts\n        const auto & sorted_flat_indices = sorted_flat_indices_exp.derived_cast();\n        const auto & valid_edges = valid_edges_exp.derived_cast();\n        auto & node_labeling = node_labeling_exp.derived_cast();\n\n        // determine number of nodes and attractive edges\n        const size_t number_of_nodes = node_labeling.size();\n        const size_t number_of_attractive_edges = number_of_nodes * number_of_attractive_channels;\n        const size_t number_of_offsets = offsets.size();\n        const size_t ndims = offsets[0].size();\n\n        std::vector<int64_t> array_stride(ndims);\n        int64_t current_stride = 1;\n        for (int i = ndims-1; i >= 0; --i){\n            array_stride[i] = current_stride;\n            current_stride *= image_shape[i];\n        }\n\n        std::vector<int64_t> offset_strides;\n        for (const auto & offset: offsets){\n            int64_t stride = 0;\n            for (int i = 0; i < offset.size(); ++i){\n                stride += offset[i] * array_stride[i];\n            }\n            offset_strides.push_back(stride);\n        }\n\n        // make ufd\n        std::vector<uint64_t> ranks(number_of_nodes);\n        std::vector<uint64_t> parents(number_of_nodes);\n        boost::disjoint_sets<uint64_t*, uint64_t*> ufd(&ranks[0], &parents[0]);\n        for(uint64_t label = 0; label < number_of_nodes; ++label) {\n            ufd.make_set(label);\n        }\n\n        // data-structure storing mutex edges\n        typedef std::vector<std::vector<uint64_t>> MutexStorage;\n        MutexStorage mutexes(number_of_nodes);\n\n        // iterate over all edges\n        for(const size_t edge_id : sorted_flat_indices) {\n\n            if(!valid_edges(edge_id)){\n                continue;\n            }\n\n            // check whether this edge is mutex via the edge offset\n            const bool is_mutex_edge = edge_id >= number_of_attractive_edges;\n\n            // get nodes connected by edge of edge_id\n\n            // const auto affCoord_ = xt::unravel_from_strides(edge_id, strides, layout);\n            const uint64_t u = edge_id % number_of_nodes;\n            const uint64_t v = u + offset_strides[edge_id / number_of_nodes];\n\n            // find the current representatives\n            uint64_t ru = ufd.find_set(u);\n            uint64_t rv = ufd.find_set(v);\n\n            // if the nodes are already connected, do nothing\n            if(ru == rv) {\n                continue;\n            }\n\n            // if we already have a mutex, we do not need to do anything\n            // (if this is a regular edge, we do not link, if it is a mutex edge\n            //  we do not need to insert the redundant mutex constraint)\n            if(check_mutex(ru, rv, mutexes)) {\n                continue;\n            }\n\n            if(is_mutex_edge) {\n\n                // insert the mutex edge into both mutex edge storages\n                insert_mutex(ru, rv, edge_id, mutexes);\n\n            } else {\n\n                ufd.link(u, v);\n                // check  if we have to swap the roots\n                if(ufd.find_set(ru) == rv) {\n                    std::swap(ru, rv);\n                }\n                // merge mutexes from rv -> ru\n                merge_mutexes(rv, ru, mutexes);\n            }\n        }\n\n        // get node labeling into output (with consecutive relabeling)\n        util::export_consecutive_labels(ufd, number_of_nodes, node_labeling);\n    }\n\n    // helper function for mws prim implementation:\n    // add all neighbors of given node to the priority queue\n    template <class WEIGHT_ARRAY, class VALID_ARRAY, class UFD, class PRIORITY_QUEUE>\n    inline void add_neighbours(const uint64_t & position,\n                               const std::vector<int64_t> & offset_strides,\n                               const size_t & number_of_nodes,\n                               const WEIGHT_ARRAY & edge_weights,\n                               const VALID_ARRAY & valid_edges,\n                               UFD & ufd,\n                               const xt::xtensor<bool, 1> & visited,\n                               PRIORITY_QUEUE & pq){\n\n        const uint64_t ru = ufd.find_set(position);\n        for(int i = 0; i < offset_strides.size(); ++i){\n            // go in positive offset direction\n            const uint64_t edge_id = position + i * number_of_nodes;\n            if (valid_edges(edge_id) && !visited(edge_id)){\n                const uint64_t neighbour = position + offset_strides[i];\n                const uint64_t rv = ufd.find_set(neighbour);\n                if (ru != rv){\n                    pq.push(std::make_tuple(edge_weights(edge_id), edge_id, position, neighbour));\n                }\n            }\n\n            // check that position - offset_stride lies within 0 and number_of_nodes\n            const bool within_bounds = (offset_strides[i] > 0 || position < number_of_nodes + offset_strides[i])\n                                    && (offset_strides[i] < 0 || offset_strides[i] <= position);\n\n            // go in negative offset direction\n            if (within_bounds){\n                const uint64_t neg_neighbour = position - offset_strides[i];\n                const uint64_t neg_edge_id = neg_neighbour + i * number_of_nodes;\n                if (valid_edges(neg_edge_id) && !visited(neg_edge_id)){\n                    const uint64_t rv = ufd.find_set(neg_neighbour);\n                    if (ru != rv){\n                        pq.push(std::make_tuple(edge_weights(neg_edge_id), neg_edge_id, position, neg_neighbour));\n                    }\n                }\n            }\n        }\n    }\n\n\n    // compute mutex segmentation via prim's algorithm\n    template<class WEIGHT_ARRAY, class NODE_ARRAY, class INDICATOR_ARRAY>\n    void compute_mws_prim_segmentation(const xt::xexpression<WEIGHT_ARRAY> & edge_weight_exp,\n                                       const xt::xexpression<INDICATOR_ARRAY> & valid_edges_exp,\n                                       const std::vector<std::vector<int>> & offsets,\n                                       const size_t number_of_attractive_channels,\n                                       const std::vector<int> & image_shape,\n                                       xt::xexpression<NODE_ARRAY> & node_labeling_exp) {\n        // typedef\n        typedef std::tuple<float, uint64_t, uint64_t, uint64_t> PQElement;\n        auto pq_compare = [](PQElement left, PQElement right) {return std::get<0>(left) < std::get<0>(right);};\n        typedef std::priority_queue<PQElement, std::vector<PQElement>,\n                                    decltype(pq_compare)> EdgePriorityQueue;\n        typedef boost::disjoint_sets<uint64_t*, uint64_t*> NodeUnionFind;\n\n        // casts\n        const auto & edge_weights = edge_weight_exp.derived_cast();\n        const auto & valid_edges = valid_edges_exp.derived_cast();\n        auto & node_labeling = node_labeling_exp.derived_cast();\n\n        const size_t number_of_nodes = node_labeling.size();\n        const size_t number_of_attractive_edges = number_of_nodes * number_of_attractive_channels;\n        const size_t number_of_offsets = offsets.size();\n        const size_t ndims = offsets[0].size();\n        xt::xtensor<bool, 1> visited = xt::zeros<bool>({edge_weights.size()});\n\n        std::vector<int64_t> array_stride(ndims);\n        int64_t current_stride = 1;\n        for (int i = ndims-1; i >= 0; --i){\n            array_stride[i] = current_stride;\n            current_stride *= image_shape[i];\n        }\n\n        std::vector<int64_t> offset_strides;\n        for (const auto & offset: offsets){\n            int64_t stride = 0;\n            for (int i = 0; i < offset.size(); ++i){\n                stride += offset[i] * array_stride[i];\n            }\n            offset_strides.push_back(stride);\n        }\n\n        // make ufd\n        std::vector<uint64_t> ranks(number_of_nodes);\n        std::vector<uint64_t> parents(number_of_nodes);\n        NodeUnionFind node_ufd(&ranks[0], &parents[0]);\n        for(uint64_t label = 0; label < number_of_nodes; ++label) {\n            node_ufd.make_set(label);\n        }\n\n        // data-structure storing mutex edges\n        typedef std::vector<std::vector<uint64_t>> MutexStorage;\n        MutexStorage mutexes(number_of_nodes);\n        EdgePriorityQueue pq(pq_compare);\n\n        // start prim from top left node\n        add_neighbours(0,\n                       offset_strides,\n                       number_of_nodes,\n                       edge_weights,\n                       valid_edges,\n                       node_ufd,\n                       visited,\n                       pq);\n\n        // iterate over all edges\n        while(!pq.empty()) {\n            // extract next element from the queue\n            const PQElement position_vector = pq.top();\n            pq.pop();\n            const uint64_t edge_id = std::get<1>(position_vector);\n            const uint64_t u = std::get<2>(position_vector);\n            const uint64_t v = std::get<3>(position_vector);\n\n            if(visited(edge_id)) {\n                continue;\n            }\n            visited(edge_id) = 1;\n\n            // find the current representatives\n            // and skip if roots are identical\n            uint64_t ru = node_ufd.find_set(u);\n            uint64_t rv = node_ufd.find_set(v);\n            if(ru == rv) {\n                continue;\n            }\n\n            // check whether this edge is mutex via the edge offset\n            const bool is_mutex_edge = edge_id >= number_of_attractive_edges;\n\n            // if we already have a mutex, we do not need to do anything\n            // (if this is a regular edge, we do not link, if it is a mutex edge\n            //  we do not need to insert the redundant mutex constraint)\n            if(check_mutex(ru, rv, mutexes)) {\n                continue;\n            }\n\n            if(is_mutex_edge) {\n                insert_mutex(ru, rv, edge_id, mutexes);\n            } else {\n\n                node_ufd.link(u, v);\n                // check  if we have to swap the roots\n                if(node_ufd.find_set(ru) == rv) {\n                    std::swap(ru, rv);\n                }\n                merge_mutexes(rv, ru, mutexes);\n            }\n            // add the next node to pq\n            add_neighbours(v,\n                           offset_strides,\n                           number_of_nodes,\n                           edge_weights,\n                           valid_edges,\n                           node_ufd,\n                           visited,\n                           pq);\n        }\n\n        // get node labeling into output (with consecutive relabeling)\n        util::export_consecutive_labels(node_ufd, number_of_nodes, node_labeling);\n    }\n\n}\n}\n", "meta": {"hexsha": "a38bd1f6c230e3da6a962cd5e1c94720e5b57ffd", "size": 18015, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/affogato/segmentation/mutex_watershed.hxx", "max_stars_repo_name": "constantinpape/affogato", "max_stars_repo_head_hexsha": "22ea369313b01e10f5cfefa21b7db0df719f75b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-04-11T00:47:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T23:41:06.000Z", "max_issues_repo_path": "include/affogato/segmentation/mutex_watershed.hxx", "max_issues_repo_name": "constantinpape/affogato", "max_issues_repo_head_hexsha": "22ea369313b01e10f5cfefa21b7db0df719f75b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-05-28T16:12:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T18:21:03.000Z", "max_forks_repo_path": "include/affogato/segmentation/mutex_watershed.hxx", "max_forks_repo_name": "constantinpape/affogato", "max_forks_repo_head_hexsha": "22ea369313b01e10f5cfefa21b7db0df719f75b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T12:16:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T12:16:23.000Z", "avg_line_length": 40.5743243243, "max_line_length": 114, "alphanum_fraction": 0.5536497363, "num_tokens": 3922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353745, "lm_q2_score": 0.021948254234666665, "lm_q1q2_score": 0.008857587906468536}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n * \\file     lev_mar_optimizer.cpp\n * \\author   Collin Johnson\n *\n * Definition of LevMarOptimizer.\n */\n\n#include \"hssh/global_topological/mapping/lev_mar_optimizer.h\"\n#include \"hssh/global_topological/chi.h\"\n#include \"hssh/global_topological/global_path.h\"\n#include \"hssh/global_topological/global_place.h\"\n#include \"hssh/global_topological/topological_map.h\"\n#include <boost/range/adaptor/map.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <cassert>\n#include <iostream>\n#include <levmar.h>\n\n// #define DEBUG_INITIAL_P\n// #define DEBUG_X\n// #define DEBUG_JACOBIAN\n// #define DEBUG_INCREMENTAL_P\n// #define DEBUG_LAMBDA\n// #define DEBUG_COVARIANCE\n// #define DEBUG_FINAL_P\n// #define DEBUG_LEV_MAR\n\nnamespace vulcan\n{\nnamespace hssh\n{\n\n// Callbacks for talking with levmar\nvoid levmar_func(double* p, double* hx, int m, int n, void* adata);\nvoid levmar_jacobian(double* p, double* j, int m, int n, void* adata);\n\n\nLevMarOptimizer::LevMarOptimizer(const lev_mar_optimizer_params_t& params) : params_(params)\n{\n}\n\n\nChi LevMarOptimizer::optimizeMap(const TopologicalMap& map)\n{\n    // Clear out any previous results\n    idToPIndex.clear();\n    xLambdaIndices.clear();\n\n    p.clear();\n    x.clear();\n    variance.clear();\n    xError.clear();\n    covariance.clear();\n\n    countEdges(map);\n\n    // Only run the optimization if there are at least as many edges as places. Otherwise,\n    // the optimization is actually unconstrained and thus won't produce different results\n    // from just laying out the places using the lambda values.\n    // The first place is fixed at (0, 0, 0), then all places afterward are relative to this initial place.\n    if ((numEdges + 1 < map.numPlaces()) || (map.numPlaces() == 0)) {\n        return Chi(map);\n    }\n\n    //     if(numEdges >= map.numPlaces())\n    //     {\n    setupPVector(map);\n    setupXVector(map);\n    //         calculateJacobian();\n    runLevmar();\n\n    return createChiFromP();\n    //     }\n    //     else\n    //     {\n    //         return Chi(map);\n    //     }\n}\n\n\nvoid LevMarOptimizer::setupPVector(const TopologicalMap& map)\n{\n    assert(map.numPlaces() > 0);\n    numPlaces = map.numPlaces();\n\n    p.resize(numPlaces * 3);\n    covariance.resize(p.size() * p.size());\n    std::fill(covariance.begin(), covariance.end(), 0.0);\n    std::fill(p.begin(), p.end(), 0.0);\n\n    int pIndex = 0;\n    // Skip the first place because it is the free parameter that we fix to be (0, 0, 0).\n    auto beginIt = map.places().begin();\n    initialId_ = beginIt->first;\n    ++beginIt;\n    for (auto& place : boost::make_iterator_range(beginIt, map.places().end())) {\n        pose_t pose = map.referenceFrame(place.second->id());\n\n        p[pIndex * 3] = pose.x;\n        p[pIndex * 3 + 1] = pose.y;\n        p[pIndex * 3 + 2] = pose.theta;\n\n        idToPIndex[place.first] = pIndex;\n\n        ++pIndex;\n    }\n\n    // Save the initial, fixed at the end of the pVector, so the optimization can safely refer to it without actually\n    // trying to overwrite it. The value is always 0, so it should work okay.\n    idToPIndex[initialId_] = pIndex;\n    p[pIndex * 3] = 0.0;\n    p[pIndex * 3 + 1] = 0.0;\n    p[pIndex * 3 + 2] = 0.0;\n\n#ifdef DEBUG_INITIAL_P\n    std::cout << \"DEBUG:LevMar:Initial p-vector (initial mean poses):\\n\";\n    for (std::size_t n = 0; n < numPlaces; ++n) {\n        std::cout << '(' << p[n * 3] << ',' << p[n * 3 + 1] << ',' << p[n * 3 + 2] << \")\\n\";\n    }\n#endif\n}\n\n\nvoid LevMarOptimizer::setupXVector(const TopologicalMap& map)\n{\n    const std::size_t kXMinSize = numEdges * 3;\n\n    if (x.capacity() < kXMinSize) {\n        x.reserve(kXMinSize);\n        variance.reserve(kXMinSize);\n        xError.reserve(kXMinSize);\n    }\n\n    std::size_t xIndex = 0;\n\n    for (auto& segment : boost::adaptors::values(map.segments())) {\n        // Ignore frontiers the front half of a loop, as the constraint will be added for the end segment\n        if (segment->isFrontier()) {\n            continue;\n        }\n\n        // Check the indices to see if this is a well-constrained segment, which means both ends have been visited.\n        // Don't add lambdas for frontier segments because they aren't actually useful information for constraining\n        // the Chi value\n\n        std::pair<int, int> pIndices(idToPIndex[segment->plusPlace().id()], idToPIndex[segment->minusPlace().id()]);\n\n        assert(xIndex == xLambdaIndices.size());\n        assert(xIndex * 3 == variance.size());\n\n#ifdef DEBUG_X\n        std::cout << \"Segment from \" << segment->plusPlace().id() << \" to \" << segment->minusPlace().id()\n                  << \" idx:\" << pIndices.first << \" to \" << pIndices.second << '\\n';\n#endif\n\n        const std::vector<Lambda>& lambdas = segment->getAllLambdas();\n        for (auto lambdaIt = lambdas.begin(), lambdaEnd = lambdas.end(); lambdaIt != lambdaEnd; ++lambdaIt) {\n            const Lambda& segmentLambda = *lambdaIt;\n\n            double xVar = segmentLambda.xVariance;\n            double yVar = segmentLambda.yVariance;\n            double thetaVar = segmentLambda.thetaVariance;\n\n            variance.push_back(xVar);\n            variance.push_back(yVar);\n            variance.push_back(thetaVar);\n\n            x.push_back(segmentLambda.x / xVar);\n            x.push_back(segmentLambda.y / yVar);\n            x.push_back(segmentLambda.theta / thetaVar);\n\n            xLambdaIndices.push_back(pIndices);\n            ++xIndex;\n\n#ifdef DEBUG_X\n            std::cout << '(' << segmentLambda.x << ',' << segmentLambda.y << ',' << segmentLambda.theta << \")\\n\";\n#endif\n        }\n    }\n\n#ifdef DEBUG_X\n    std::cout << \"DEBUG:LevMar:x-vector (measurements):\\n\";\n    for (std::size_t n = 0; n < numEdges; ++n) {\n        std::cout << '(' << x[n * 3] << ',' << x[n * 3 + 1] << ',' << x[n * 3 + 2] << \")\\n\";\n    }\n\n    std::cout << \"DEBUG:LevMar:Measurement variance:\\n\";\n    for (std::size_t i = 0; i < numEdges; ++i) {\n        for (std::size_t j = 0; j < 3; ++j) {\n            std::cout << variance[i * 3 + j] << ' ';\n        }\n        std::cout << '\\n';\n    }\n#endif\n}\n\n\nvoid LevMarOptimizer::countEdges(const TopologicalMap& map)\n{\n    numEdges = 0;\n\n    for (auto& segment : boost::adaptors::values(map.segments())) {\n        if (!segment->isFrontier()) {\n            numEdges += segment->getAllLambdas().size();\n        }\n    }\n}\n\n\nvoid LevMarOptimizer::runLevmar(void)\n{\n    // Need to have at least as many edges as places in order to optimizer, otherwise graph is tree-structured\n    //     if(numEdges < numPlaces)\n    //     {\n    //         return;\n    //     }\n\n    assert(xLambdaIndices.size() == numEdges);\n\n    if (work.size() < LM_DIF_WORKSZ(p.size(), x.size())) {\n        work.resize(LM_DIF_WORKSZ(p.size(), x.size()));\n        std::fill(work.begin(), work.end(), 0.0);\n    }\n\n    double opts[5];\n    double info[LM_INFO_SZ];\n\n    opts[0] = params_.initialMu;\n    opts[1] = params_.stopThreshold;\n    opts[2] = params_.stopThreshold;\n    opts[3] = params_.stopThreshold;\n    opts[4] = 1.0;\n\n    //     dlevmar_der(levmar_func, levmar_jacobian, p, x, numPlaces*3, numEdges*3, params_.maxIterations, opts, info,\n    //     work, covariance, this); dlevmar_dif(levmar_func, p, x, numPlaces*3, numEdges*3, params_.maxIterations, opts,\n    //     info, work, covariance, this);\n    dlevmar_dif(\n      levmar_func,\n      p.data(),\n      x.data(),\n      // handle the case where there's a single area, so it needs to have the error computed, which will be large\n      (p.size() > 3) ? p.size() - 3 : p.size(),   // ignoring the final place, which will always be (0,0,0)\n      x.size(),\n      params_.maxIterations,\n      opts,\n      info,\n      work.data(),\n      covariance.data(),\n      this);\n\n    finalError = info[1];\n\n#ifdef DEBUG_JACOBIAN\n    std::vector<double> error(x.size());\n    dlevmar_chkjac(levmar_func, levmar_jacobian, p.data(), p.size() - 3, x.size(), this, error.data());\n\n    std::cout << \"DEBUG:LevMar:Jacobian check:\\n\";\n    for (std::size_t n = 0; n < error.size(); ++n) {\n        std::cout << error[n] << '\\n';\n    }\n#endif\n\n#ifdef DEBUG_LEV_MAR\n    std::cout << \"DEBUG:LevMar:Optimization info:\\n\"\n              << \"Initial error:\" << info[0] << '\\n'\n              << \"Final error:  \" << info[1] << '\\n'\n              << \"Iterations:   \" << info[5] << '\\n'\n              << \"Termination:  \" << info[6] << '\\n'\n              << \"Func evals:   \" << info[7] << '\\n'\n              << \"Jacob evals:  \" << info[8] << '\\n'\n              << \"Sys solved:   \" << info[9] << '\\n';\n#endif\n}\n\n\nChi LevMarOptimizer::createChiFromP(void)\n{\n    std::unordered_map<Id, pose_distribution_t> finalPoses;\n\n    for (auto& index : idToPIndex) {\n        int idx = index.second * 3;\n\n        pose_distribution_t pose;\n        pose.x = p[idx];\n        pose.y = p[idx + 1];\n        pose.theta = wrap_to_pi(p[idx + 2]);\n        pose.uncertainty[0] = pose.x;\n        pose.uncertainty[1] = pose.y;\n        pose.uncertainty[2] = pose.theta;\n\n        // Copy out the covariance off the block diagonal -- don't care about the other cross-correlation terms\n        for (int y = 0; y < 3; ++y) {\n            for (int x = 0; x < 3; ++x) {\n                pose.uncertainty(x, y) = covariance[((idx + y) * numPlaces * 3) + idx + x];\n            }\n        }\n\n        finalPoses[index.first] = pose;\n    }\n\n#ifdef DEBUG_FINAL_P\n    std::cout << \"DEBUG::LevMar: Mean poses:\\n\";\n    for (auto& idToPose : finalPoses) {\n        std::cout << idToPose.first << \":\\n\"\n                  << idToPose.second.uncertainty.getMean() << '\\n'\n                  << idToPose.second.uncertainty.getCovariance();\n    }\n#endif\n\n#ifdef DEBUG_COVARIANCE\n    //     std::cout<<\"DEBUG:LevMar:Covariance:\\n\";\n    //     for(std::size_t i = 0; i < numPlaces*3; ++i)\n    //     {\n    //         for(std::size_t j = 0; j < numPlaces*3; ++j)\n    //         {\n    //             printf(\"%.2f \", covariance[i*numPlaces*3 + j]);\n    // //             std::cout<<covariance[i*numPlaces*3 + j]<<' ';\n    //         }\n    //         std::cout<<'\\n';\n    //     }\n    std::cout << \"DEBUG:LevMar:Covariance diag:\\n\";\n    for (std::size_t i = 0; i < numPlaces * 3; ++i) {\n        printf(\"%.2f \", dlevmar_stddev(covariance.data(), numPlaces * 3, i));   // covariance[i*numPlaces*3 + i*3]);\n        std::cout << '\\n';\n    }\n#endif\n\n    // Error minimizes (lambda_chi - lambda_obs)^T cov_obs^-1 (lambda_chi - lambda_obs)\n    // To get log-likelihood, just multiply by -0.5, which gives the Gaussian log-likelihood\n    return Chi(finalPoses, -0.5 * finalError);\n}\n\n\nvoid LevMarOptimizer::calculateLambdas(double* newP, double* hx, int m, int n)\n{\n    pose_t start;\n    pose_t end;\n\n    for (std::size_t i = 0; i < xLambdaIndices.size(); ++i) {\n        // Only consider the new poses if they have valid indices. If out of range, that means it should be 0,0,0\n        // per the design of the p matrix\n        if (xLambdaIndices[i].first * 3 < m) {\n            int startIdx = xLambdaIndices[i].first * 3;\n            start.x = newP[startIdx];\n            start.y = newP[startIdx + 1];\n            start.theta = wrap_to_pi(newP[startIdx + 2]);\n        }\n        // At the origin\n        else {\n            start.x = 0.0f;\n            start.y = 0.0f;\n            start.theta = 0.0f;\n        }\n\n        if (xLambdaIndices[i].second * 3 < m) {\n            int endIdx = xLambdaIndices[i].second * 3;\n            end.x = newP[endIdx];\n            end.y = newP[endIdx + 1];\n            end.theta = wrap_to_pi(newP[endIdx + 2]);\n        }\n        // At the origin\n        else {\n            end.x = 0.0f;\n            end.y = 0.0f;\n            end.theta = 0.0f;\n        }\n\n        auto diff = end.transformToNewFrame(start);\n\n        int xIdx = i * 3;\n        int yIdx = xIdx + 1;\n        int thetaIdx = xIdx + 2;\n\n        hx[xIdx] = diff.x / variance[xIdx];\n        hx[yIdx] = diff.y / variance[yIdx];\n        hx[thetaIdx] = diff.theta / variance[thetaIdx];\n\n        xError[xIdx] = x[xIdx] - hx[xIdx];\n        xError[yIdx] = x[yIdx] - hx[yIdx];\n        xError[thetaIdx] = wrap_to_pi(x[thetaIdx] - hx[thetaIdx]);\n    }\n\n#ifdef DEBUG_INCREMENTAL_P\n    std::cout << \"DEBUG:LevMar:Incremental p-vector:\\n\";\n    for (int i = 0; i * 3 < m; ++i) {\n        std::cout << '(' << newP[i * 3] << ',' << newP[i * 3 + 1] << ',' << newP[i * 3 + 2] << \")\\n\";\n    }\n#endif\n\n#ifdef DEBUG_LAMBDA\n    std::cout << \"DEBUG:LevMar:Incremental lambdas (hx-vector):\\n\";\n    for (std::size_t i = 0; i < numEdges; ++i) {\n        std::cout << '(' << hx[i * 3] << ',' << hx[i * 3 + 1] << ',' << hx[i * 3 + 2] << \")\\n\";\n    }\n\n    std::cout << \"DEBUG:LevMar:Residuals (x-hx):\\n\";\n    for (std::size_t i = 0; i < numEdges; ++i) {\n        std::cout << '(' << (x[i * 3] - hx[i * 3]) << ',' << (x[i * 3 + 1] - hx[i * 3 + 1]) << ','\n                  << (x[i * 3 + 2] - hx[i * 3 + 2]) << \")\\n\";\n    }\n#endif\n}\n\n\nvoid LevMarOptimizer::calculateJacobian(double* j, int m, int n)\n{\n    // The residuals are (p_i - p_j - x_n)^2. Thus the Jacobian is +1 for J_n_i and -1 for J_n_j.\n\n    std::size_t rowStart = 0;\n    std::size_t rowStep = numPlaces * 3;\n\n    memset(j, 0, m * m * sizeof(double));\n\n    // The Jacobian is two diagonal blocks for (x,y,theta).  second = end place, first = start place. so lambda = p_end\n    // - p_start\n    for (std::size_t i = 0; i < numEdges; ++i) {\n        if (xLambdaIndices[i].second * 3 < n) {\n            j[rowStart + xLambdaIndices[i].second * 3] = xError[i * 3];\n        }\n        if (xLambdaIndices[i].first * 3 < n) {\n            j[rowStart + xLambdaIndices[i].first * 3] = -xError[i * 3];\n        }\n\n        rowStart += rowStep;\n\n        if (xLambdaIndices[i].second * 3 < n) {\n            j[rowStart + xLambdaIndices[i].second * 3 + 1] = xError[i * 3 + 1];\n        }\n        if (xLambdaIndices[i].first * 3 < n) {\n            j[rowStart + xLambdaIndices[i].first * 3 + 1] = -xError[i * 3 + 1];\n        }\n\n        rowStart += rowStep;\n\n        if (xLambdaIndices[i].second * 3 < n) {\n            j[rowStart + xLambdaIndices[i].second * 3 + 2] = xError[i * 3 + 2];\n        }\n        if (xLambdaIndices[i].first * 3 < n) {\n            j[rowStart + xLambdaIndices[i].first * 3 + 2] = -xError[i * 3 + 2];\n        }\n\n        rowStart += rowStep;\n    }\n\n#ifdef DEBUG_JACOBIAN\n    rowStart = 0;\n    std::cout << \"DEBUG:LevMar:Jacobian:\\n\";\n    for (std::size_t n = 0; n < numEdges * 3; ++n) {\n        for (std::size_t i = 0; i < numPlaces * 3; ++i) {\n            std::cout << j[rowStart + i] << ' ';\n        }\n        std::cout << '\\n';\n        rowStart += rowStep;\n    }\n#endif\n}\n\n// Create friend functions to issue as the callbacks used by levmar. The adata will point to this, which will then\n// be used to call the\nvoid levmar_func(double* p, double* hx, int m, int n, void* adata)\n{\n    LevMarOptimizer* optimizer = static_cast<LevMarOptimizer*>(adata);\n    optimizer->calculateLambdas(p, hx, m, n);\n}\n\n\nvoid levmar_jacobian(double* p, double* j, int m, int n, void* adata)\n{\n    LevMarOptimizer* optimizer = static_cast<LevMarOptimizer*>(adata);\n    optimizer->calculateJacobian(j, m, n);\n}\n\n}   // namespace hssh\n}   // namespace vulcan\n", "meta": {"hexsha": "c071384f0be756381592e46792d4ec0c9953dc30", "size": 15404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hssh/global_topological/mapping/lev_mar_optimizer.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/hssh/global_topological/mapping/lev_mar_optimizer.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/hssh/global_topological/mapping/lev_mar_optimizer.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 31.826446281, "max_line_length": 120, "alphanum_fraction": 0.566800831, "num_tokens": 4530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.022977369784579756, "lm_q1q2_score": 0.00884426835413353}}
{"text": "//\r\n//=======================================================================\r\n// Copyright 2002 Marc Wintermantel (wintermantel@even-ag.ch)\r\n// ETH Zurich, Center of Structure Technologies\r\n// (https://web.archive.org/web/20050307090307/http://www.structures.ethz.ch/)\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\r\n#ifndef BOOST_GRAPH_SLOAN_HPP\r\n#define BOOST_GRAPH_SLOAN_HPP\r\n\r\n#define WEIGHT1 1 // default weight for the distance in the Sloan algorithm\r\n#define WEIGHT2 2 // default weight for the degree in the Sloan algorithm\r\n\r\n#include <boost/config.hpp>\r\n#include <vector>\r\n#include <queue>\r\n#include <algorithm>\r\n#include <limits>\r\n#include <boost/pending/queue.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/visitors.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/cuthill_mckee_ordering.hpp>\r\n\r\n////////////////////////////////////////////////////////////\r\n//\r\n// Sloan-Algorithm for graph reordering\r\n//(optimzes profile and wavefront, not primiraly bandwidth\r\n//\r\n////////////////////////////////////////////////////////////\r\n\r\nnamespace boost\r\n{\r\n\r\n/////////////////////////////////////////////////////////////////////////\r\n// Function that returns the maximum depth of\r\n// a rooted level strucutre (RLS)\r\n//\r\n/////////////////////////////////////////////////////////////////////////\r\ntemplate < class Distance > typename Distance::value_type RLS_depth(Distance& d)\r\n{\r\n    typename Distance::value_type h_s = 0;\r\n    typename Distance::iterator iter;\r\n\r\n    for (iter = d.begin(); iter != d.end(); ++iter)\r\n    {\r\n        if (*iter > h_s)\r\n        {\r\n            h_s = *iter;\r\n        }\r\n    }\r\n\r\n    return h_s;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////\r\n// Function that returns the width of the largest level of\r\n// a rooted level strucutre (RLS)\r\n//\r\n/////////////////////////////////////////////////////////////////////////\r\ntemplate < class Distance, class my_int >\r\ntypename Distance::value_type RLS_max_width(Distance& d, my_int depth)\r\n{\r\n\r\n    typedef typename Distance::value_type Degree;\r\n\r\n    // Searching for the maximum width of a level\r\n    std::vector< Degree > dummy_width(depth + 1, 0);\r\n    typename std::vector< Degree >::iterator my_it;\r\n    typename Distance::iterator iter;\r\n    Degree w_max = 0;\r\n\r\n    for (iter = d.begin(); iter != d.end(); ++iter)\r\n    {\r\n        dummy_width[*iter]++;\r\n    }\r\n\r\n    for (my_it = dummy_width.begin(); my_it != dummy_width.end(); ++my_it)\r\n    {\r\n        if (*my_it > w_max)\r\n            w_max = *my_it;\r\n    }\r\n\r\n    return w_max;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////\r\n// Function for finding a good starting node for Sloan algorithm\r\n//\r\n// This is to find a good starting node. \"good\" is in the sense\r\n// of the ordering generated.\r\n/////////////////////////////////////////////////////////////////////////\r\ntemplate < class Graph, class ColorMap, class DegreeMap >\r\ntypename graph_traits< Graph >::vertex_descriptor sloan_start_end_vertices(\r\n    Graph& G, typename graph_traits< Graph >::vertex_descriptor& s,\r\n    ColorMap color, DegreeMap degree)\r\n{\r\n    typedef typename property_traits< DegreeMap >::value_type Degree;\r\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n    typedef typename std::vector<\r\n        typename graph_traits< Graph >::vertices_size_type >::iterator vec_iter;\r\n    typedef typename graph_traits< Graph >::vertices_size_type size_type;\r\n\r\n    typedef typename property_map< Graph, vertex_index_t >::const_type VertexID;\r\n\r\n    s = *(vertices(G).first);\r\n    Vertex e = s;\r\n    Vertex i;\r\n    Degree my_degree = get(degree, s);\r\n    Degree dummy, h_i, h_s, w_i, w_e;\r\n    bool new_start = true;\r\n    Degree maximum_degree = 0;\r\n\r\n    // Creating a std-vector for storing the distance from the start vertex in\r\n    // dist\r\n    std::vector< typename graph_traits< Graph >::vertices_size_type > dist(\r\n        num_vertices(G), 0);\r\n\r\n    // Wrap a property_map_iterator around the std::iterator\r\n    boost::iterator_property_map< vec_iter, VertexID, size_type, size_type& >\r\n        dist_pmap(dist.begin(), get(vertex_index, G));\r\n\r\n    // Creating a property_map for the indices of a vertex\r\n    typename property_map< Graph, vertex_index_t >::type index_map\r\n        = get(vertex_index, G);\r\n\r\n    // Creating a priority queue\r\n    typedef indirect_cmp< DegreeMap, std::greater< Degree > > Compare;\r\n    Compare comp(degree);\r\n    std::priority_queue< Vertex, std::vector< Vertex >, Compare > degree_queue(\r\n        comp);\r\n\r\n    // step 1\r\n    // Scan for the vertex with the smallest degree and the maximum degree\r\n    typename graph_traits< Graph >::vertex_iterator ui, ui_end;\r\n    for (boost::tie(ui, ui_end) = vertices(G); ui != ui_end; ++ui)\r\n    {\r\n        dummy = get(degree, *ui);\r\n\r\n        if (dummy < my_degree)\r\n        {\r\n            my_degree = dummy;\r\n            s = *ui;\r\n        }\r\n\r\n        if (dummy > maximum_degree)\r\n        {\r\n            maximum_degree = dummy;\r\n        }\r\n    }\r\n    // end 1\r\n\r\n    do\r\n    {\r\n        new_start = false; // Setting the loop repetition status to false\r\n\r\n        // step 2\r\n        // initialize the the disance std-vector with 0\r\n        for (typename std::vector< typename graph_traits<\r\n                 Graph >::vertices_size_type >::iterator iter\r\n             = dist.begin();\r\n             iter != dist.end(); ++iter)\r\n            *iter = 0;\r\n\r\n        // generating the RLS (rooted level structure)\r\n        breadth_first_search(G, s,\r\n            visitor(\r\n                make_bfs_visitor(record_distances(dist_pmap, on_tree_edge()))));\r\n\r\n        // end 2\r\n\r\n        // step 3\r\n        // calculating the depth of the RLS\r\n        h_s = RLS_depth(dist);\r\n\r\n        // step 4\r\n        // pushing one node of each degree in an ascending manner into\r\n        // degree_queue\r\n        std::vector< bool > shrink_trace(maximum_degree, false);\r\n        for (boost::tie(ui, ui_end) = vertices(G); ui != ui_end; ++ui)\r\n        {\r\n            dummy = get(degree, *ui);\r\n\r\n            if ((dist[index_map[*ui]] == h_s) && (!shrink_trace[dummy]))\r\n            {\r\n                degree_queue.push(*ui);\r\n                shrink_trace[dummy] = true;\r\n            }\r\n        }\r\n\r\n        // end 3 & 4\r\n\r\n        // step 5\r\n        // Initializing w\r\n        w_e = (std::numeric_limits< Degree >::max)();\r\n        // end 5\r\n\r\n        // step 6\r\n        // Testing for termination\r\n        while (!degree_queue.empty())\r\n        {\r\n            i = degree_queue.top(); // getting the node with the lowest degree\r\n                                    // from the degree queue\r\n            degree_queue.pop(); // ereasing the node with the lowest degree from\r\n                                // the degree queue\r\n\r\n            // generating a RLS\r\n            for (typename std::vector< typename graph_traits<\r\n                     Graph >::vertices_size_type >::iterator iter\r\n                 = dist.begin();\r\n                 iter != dist.end(); ++iter)\r\n                *iter = 0;\r\n\r\n            breadth_first_search(G, i,\r\n                boost::visitor(make_bfs_visitor(\r\n                    record_distances(dist_pmap, on_tree_edge()))));\r\n\r\n            // Calculating depth and width of the rooted level\r\n            h_i = RLS_depth(dist);\r\n            w_i = RLS_max_width(dist, h_i);\r\n\r\n            // Testing for termination\r\n            if ((h_i > h_s) && (w_i < w_e))\r\n            {\r\n                h_s = h_i;\r\n                s = i;\r\n                while (!degree_queue.empty())\r\n                    degree_queue.pop();\r\n                new_start = true;\r\n            }\r\n            else if (w_i < w_e)\r\n            {\r\n                w_e = w_i;\r\n                e = i;\r\n            }\r\n        }\r\n        // end 6\r\n\r\n    } while (new_start);\r\n\r\n    return e;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n// Sloan algorithm with a given starting Vertex.\r\n//\r\n// This algorithm requires user to provide a starting vertex to\r\n// compute Sloan ordering.\r\n//////////////////////////////////////////////////////////////////////////\r\ntemplate < class Graph, class OutputIterator, class ColorMap, class DegreeMap,\r\n    class PriorityMap, class Weight >\r\nOutputIterator sloan_ordering(Graph& g,\r\n    typename graph_traits< Graph >::vertex_descriptor s,\r\n    typename graph_traits< Graph >::vertex_descriptor e,\r\n    OutputIterator permutation, ColorMap color, DegreeMap degree,\r\n    PriorityMap priority, Weight W1, Weight W2)\r\n{\r\n    // typedef typename property_traits<DegreeMap>::value_type Degree;\r\n    typedef typename property_traits< PriorityMap >::value_type Degree;\r\n    typedef typename property_traits< ColorMap >::value_type ColorValue;\r\n    typedef color_traits< ColorValue > Color;\r\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n    typedef typename std::vector<\r\n        typename graph_traits< Graph >::vertices_size_type >::iterator vec_iter;\r\n    typedef typename graph_traits< Graph >::vertices_size_type size_type;\r\n\r\n    typedef typename property_map< Graph, vertex_index_t >::const_type VertexID;\r\n\r\n    // Creating a std-vector for storing the distance from the end vertex in it\r\n    typename std::vector< typename graph_traits< Graph >::vertices_size_type >\r\n        dist(num_vertices(g), 0);\r\n\r\n    // Wrap a property_map_iterator around the std::iterator\r\n    boost::iterator_property_map< vec_iter, VertexID, size_type, size_type& >\r\n        dist_pmap(dist.begin(), get(vertex_index, g));\r\n\r\n    breadth_first_search(g, e,\r\n        visitor(make_bfs_visitor(record_distances(dist_pmap, on_tree_edge()))));\r\n\r\n    // Creating a property_map for the indices of a vertex\r\n    typename property_map< Graph, vertex_index_t >::type index_map\r\n        = get(vertex_index, g);\r\n\r\n    // Sets the color and priority to their initial status\r\n    Degree cdeg;\r\n    typename graph_traits< Graph >::vertex_iterator ui, ui_end;\r\n    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)\r\n    {\r\n        put(color, *ui, Color::white());\r\n        cdeg = get(degree, *ui) + 1;\r\n        put(priority, *ui, W1 * dist[index_map[*ui]] - W2 * cdeg);\r\n    }\r\n\r\n    // Priority list\r\n    typedef indirect_cmp< PriorityMap, std::greater< Degree > > Compare;\r\n    Compare comp(priority);\r\n    std::list< Vertex > priority_list;\r\n\r\n    // Some more declarations\r\n    typename graph_traits< Graph >::out_edge_iterator ei, ei_end, ei2, ei2_end;\r\n    Vertex u, v, w;\r\n\r\n    put(color, s,\r\n        Color::green()); // Sets the color of the starting vertex to gray\r\n    priority_list.push_front(s); // Puts s into the priority_list\r\n\r\n    while (!priority_list.empty())\r\n    {\r\n        priority_list.sort(comp); // Orders the elements in the priority list in\r\n                                  // an ascending manner\r\n\r\n        u = priority_list\r\n                .front(); // Accesses the last element in the priority list\r\n        priority_list\r\n            .pop_front(); // Removes the last element in the priority list\r\n\r\n        if (get(color, u) == Color::green())\r\n        {\r\n            // for-loop over all out-edges of vertex u\r\n            for (boost::tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei)\r\n            {\r\n                v = target(*ei, g);\r\n\r\n                put(priority, v, get(priority, v) + W2); // updates the priority\r\n\r\n                if (get(color, v)\r\n                    == Color::white()) // test if the vertex is inactive\r\n                {\r\n                    put(color, v,\r\n                        Color::green()); // giving the vertex a preactive status\r\n                    priority_list.push_front(\r\n                        v); // writing the vertex in the priority_queue\r\n                }\r\n            }\r\n        }\r\n\r\n        // Here starts step 8\r\n        *permutation++\r\n            = u; // Puts u to the first position in the permutation-vector\r\n        put(color, u, Color::black()); // Gives u an inactive status\r\n\r\n        // for loop over all the adjacent vertices of u\r\n        for (boost::tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei)\r\n        {\r\n\r\n            v = target(*ei, g);\r\n\r\n            if (get(color, v) == Color::green())\r\n            { // tests if the vertex is inactive\r\n\r\n                put(color, v,\r\n                    Color::red()); // giving the vertex an active status\r\n                put(priority, v, get(priority, v) + W2); // updates the priority\r\n\r\n                // for loop over alll adjacent vertices of v\r\n                for (boost::tie(ei2, ei2_end) = out_edges(v, g); ei2 != ei2_end;\r\n                     ++ei2)\r\n                {\r\n                    w = target(*ei2, g);\r\n\r\n                    if (get(color, w) != Color::black())\r\n                    { // tests if vertex is postactive\r\n\r\n                        put(priority, w,\r\n                            get(priority, w) + W2); // updates the priority\r\n\r\n                        if (get(color, w) == Color::white())\r\n                        {\r\n\r\n                            put(color, w, Color::green()); // gives the vertex a\r\n                                                           // preactive status\r\n                            priority_list.push_front(\r\n                                w); // puts the vertex into the priority queue\r\n\r\n                        } // end if\r\n\r\n                    } // end if\r\n\r\n                } // end for\r\n\r\n            } // end if\r\n\r\n        } // end for\r\n\r\n    } // end while\r\n\r\n    return permutation;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////////////////\r\n// Same algorithm as before, but without the weights given (taking default\r\n// weights\r\ntemplate < class Graph, class OutputIterator, class ColorMap, class DegreeMap,\r\n    class PriorityMap >\r\nOutputIterator sloan_ordering(Graph& g,\r\n    typename graph_traits< Graph >::vertex_descriptor s,\r\n    typename graph_traits< Graph >::vertex_descriptor e,\r\n    OutputIterator permutation, ColorMap color, DegreeMap degree,\r\n    PriorityMap priority)\r\n{\r\n    return sloan_ordering(\r\n        g, s, e, permutation, color, degree, priority, WEIGHT1, WEIGHT2);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n// Sloan algorithm without a given starting Vertex.\r\n//\r\n// This algorithm finds a good starting vertex itself to\r\n// compute Sloan-ordering.\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\ntemplate < class Graph, class OutputIterator, class Color, class Degree,\r\n    class Priority, class Weight >\r\ninline OutputIterator sloan_ordering(Graph& G, OutputIterator permutation,\r\n    Color color, Degree degree, Priority priority, Weight W1, Weight W2)\r\n{\r\n    typedef typename boost::graph_traits< Graph >::vertex_descriptor Vertex;\r\n\r\n    Vertex s, e;\r\n    e = sloan_start_end_vertices(G, s, color, degree);\r\n\r\n    return sloan_ordering(\r\n        G, s, e, permutation, color, degree, priority, W1, W2);\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////////////////\r\n// Same as before, but without given weights (default weights are taken instead)\r\ntemplate < class Graph, class OutputIterator, class Color, class Degree,\r\n    class Priority >\r\ninline OutputIterator sloan_ordering(Graph& G, OutputIterator permutation,\r\n    Color color, Degree degree, Priority priority)\r\n{\r\n    return sloan_ordering(\r\n        G, permutation, color, degree, priority, WEIGHT1, WEIGHT2);\r\n}\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_GRAPH_SLOAN_HPP\r\n", "meta": {"hexsha": "14afe2cfd84b1c580d232ccbd4d1cfe83d1720b6", "size": 15988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/sloan_ordering.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/sloan_ordering.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/sloan_ordering.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": 35.6080178174, "max_line_length": 90, "alphanum_fraction": 0.5427195397, "num_tokens": 3290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.022286182982299584, "lm_q1q2_score": 0.008826847627047149}}
{"text": "// Copyright (c) 2008-2016 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 UUID_20D98340A3EB11DEB2180CD156D89593\n#define UUID_20D98340A3EB11DEB2180CD156D89593\n\n#include <boost/qvm/assert.hpp>\n#include <boost/qvm/deduce_mat.hpp>\n#include <boost/qvm/detail/transp_impl.hpp>\n#include <boost/qvm/enable_if.hpp>\n#include <boost/qvm/inline.hpp>\n\nnamespace boost {\nnamespace qvm {\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Row, class OriginalMatrix> class del_row_ {\n  del_row_(del_row_ const &);\n  del_row_ &operator=(del_row_ const &);\n  ~del_row_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL del_row_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int I, class OriginalMatrix>\nstruct mat_traits<qvm_detail::del_row_<I, OriginalMatrix>> {\n  typedef qvm_detail::del_row_<I, OriginalMatrix> this_matrix;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const rows = mat_traits<OriginalMatrix>::rows - 1;\n  static int const cols = mat_traits<OriginalMatrix>::cols;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template read_element<Row + (Row >= I),\n                                                             Col>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template write_element<Row + (Row >= I),\n                                                              Col>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        row + (row >= I), col, reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        row + (row >= I), col, reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat<qvm_detail::del_row_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat2<qvm_detail::del_row_<J, OriginalMatrix>,\n                   qvm_detail::del_row_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int Row, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::del_row_<Row, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    del_row(A const &a) {\n  return reinterpret_cast<typename qvm_detail::del_row_<Row, A> const &>(a);\n}\n\ntemplate <int Row, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::del_row_<Row, A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    del_row(A &a) {\n  return reinterpret_cast<typename qvm_detail::del_row_<Row, A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Col, class OriginalMatrix> class del_col_ {\n  del_col_(del_col_ const &);\n  del_col_ &operator=(del_col_ const &);\n  ~del_col_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL del_col_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int J, class OriginalMatrix>\nstruct mat_traits<qvm_detail::del_col_<J, OriginalMatrix>> {\n  typedef qvm_detail::del_col_<J, OriginalMatrix> this_matrix;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const rows = mat_traits<OriginalMatrix>::rows;\n  static int const cols = mat_traits<OriginalMatrix>::cols - 1;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template read_element<Row,\n                                                             Col + (Col >= J)>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template write_element<Row,\n                                                              Col + (Col >= J)>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        row, col + (col >= J), reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        row, col + (col >= J), reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat<qvm_detail::del_col_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat2<qvm_detail::del_col_<J, OriginalMatrix>,\n                   qvm_detail::del_col_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int Col, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::del_col_<Col, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    del_col(A const &a) {\n  return reinterpret_cast<typename qvm_detail::del_col_<Col, A> const &>(a);\n}\n\ntemplate <int Col, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::del_col_<Col, A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    del_col(A &a) {\n  return reinterpret_cast<typename qvm_detail::del_col_<Col, A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Row, int Col, class OriginalMatrix> class del_row_col_ {\n  del_row_col_(del_row_col_ const &);\n  ~del_row_col_();\n\npublic:\n  BOOST_QVM_INLINE_TRIVIAL\n  del_row_col_ &operator=(del_row_col_ const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class T>\n  BOOST_QVM_INLINE_TRIVIAL del_row_col_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int I, int J, class OriginalMatrix>\nstruct mat_traits<qvm_detail::del_row_col_<I, J, OriginalMatrix>> {\n  typedef qvm_detail::del_row_col_<I, J, OriginalMatrix> this_matrix;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const rows = mat_traits<OriginalMatrix>::rows - 1;\n  static int const cols = mat_traits<OriginalMatrix>::cols - 1;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template read_element<Row + (Row >= I),\n                                                             Col + (Col >= J)>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template write_element<Row + (Row >= I),\n                                                              Col + (Col >= J)>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        row + (row >= I), col + (col >= J),\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        row + (row >= I), col + (col >= J),\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <int I, int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat<qvm_detail::del_row_col_<I, J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int I, int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat2<qvm_detail::del_row_col_<I, J, OriginalMatrix>,\n                   qvm_detail::del_row_col_<I, J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int Row, int Col, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::del_row_col_<Row, Col, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    del_row_col(A const &a) {\n  return reinterpret_cast<\n      typename qvm_detail::del_row_col_<Row, Col, A> const &>(a);\n}\n\ntemplate <int Row, int Col, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::del_row_col_<Row, Col, A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    del_row_col(A &a) {\n  return reinterpret_cast<typename qvm_detail::del_row_col_<Row, Col, A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Row, class OriginalMatrix> class neg_row_ {\n  neg_row_(neg_row_ const &);\n  neg_row_ &operator=(neg_row_ const &);\n  ~neg_row_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL neg_row_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int I, class OriginalMatrix>\nstruct mat_traits<qvm_detail::neg_row_<I, OriginalMatrix>> {\n  typedef qvm_detail::neg_row_<I, OriginalMatrix> this_matrix;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const rows = mat_traits<OriginalMatrix>::rows;\n  static int const cols = mat_traits<OriginalMatrix>::cols;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return Row == I\n               ? -mat_traits<OriginalMatrix>::template read_element<Row, Col>(\n                     reinterpret_cast<OriginalMatrix const &>(x))\n               : mat_traits<OriginalMatrix>::template read_element<Row, Col>(\n                     reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return row == I\n               ? -mat_traits<OriginalMatrix>::read_element_idx(\n                     row, col, reinterpret_cast<OriginalMatrix const &>(x))\n               : mat_traits<OriginalMatrix>::read_element_idx(\n                     row, col, reinterpret_cast<OriginalMatrix const &>(x));\n  }\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat<qvm_detail::neg_row_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat2<qvm_detail::neg_row_<J, OriginalMatrix>,\n                   qvm_detail::neg_row_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int Row, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::neg_row_<Row, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    neg_row(A const &a) {\n  return reinterpret_cast<typename qvm_detail::neg_row_<Row, A> const &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Col, class OriginalMatrix> class neg_col_ {\n  neg_col_(neg_col_ const &);\n  neg_col_ &operator=(neg_col_ const &);\n  ~neg_col_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL neg_col_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int J, class OriginalMatrix>\nstruct mat_traits<qvm_detail::neg_col_<J, OriginalMatrix>> {\n  typedef qvm_detail::neg_col_<J, OriginalMatrix> this_matrix;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const rows = mat_traits<OriginalMatrix>::rows;\n  static int const cols = mat_traits<OriginalMatrix>::cols;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return Col == J\n               ? -mat_traits<OriginalMatrix>::template read_element<Row, Col>(\n                     reinterpret_cast<OriginalMatrix const &>(x))\n               : mat_traits<OriginalMatrix>::template read_element<Row, Col>(\n                     reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return col == J\n               ? -mat_traits<OriginalMatrix>::read_element_idx(\n                     row, col, reinterpret_cast<OriginalMatrix const &>(x))\n               : mat_traits<OriginalMatrix>::read_element_idx(\n                     row, col, reinterpret_cast<OriginalMatrix const &>(x));\n  }\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat<qvm_detail::neg_col_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int J, class OriginalMatrix, int R, int C>\nstruct deduce_mat2<qvm_detail::neg_col_<J, OriginalMatrix>,\n                   qvm_detail::neg_col_<J, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int Col, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::neg_col_<Col, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    neg_col(A const &a) {\n  return reinterpret_cast<typename qvm_detail::neg_col_<Col, A> const &>(a);\n}\n\n////////////////////////////////////////////////\n\ntemplate <class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::transposed_<A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    transposed(A const &a) {\n  return reinterpret_cast<typename qvm_detail::transposed_<A> const &>(a);\n}\n\ntemplate <class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::transposed_<A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    transposed(A &a) {\n  return reinterpret_cast<typename qvm_detail::transposed_<A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Row1, int Row2, class OriginalMatrix> class swap_rows_ {\n  swap_rows_(swap_rows_ const &);\n  swap_rows_ &operator=(swap_rows_ const &);\n  ~swap_rows_();\n\npublic:\n  template <class T>\n  BOOST_QVM_INLINE_TRIVIAL swap_rows_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int R1, int R2, class OriginalMatrix>\nstruct mat_traits<qvm_detail::swap_rows_<R1, R2, OriginalMatrix>> {\n  typedef qvm_detail::swap_rows_<R1, R2, OriginalMatrix> this_matrix;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const rows = mat_traits<OriginalMatrix>::rows;\n  static int const cols = mat_traits<OriginalMatrix>::cols;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template read_element<\n        (Row == R1 && R1 != R2) * R2 + (Row == R2 && R1 != R2) * R1 +\n            ((Row != R1 && Row != R2) || R1 == R2) * Row,\n        Col>(reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template write_element<\n        (Row == R1 && R1 != R2) * R2 + (Row == R2 && R1 != R2) * R1 +\n            ((Row != R1 && Row != R2) || R1 == R2) * Row,\n        Col>(reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        row == R1 ? R2 : row == R2 ? R1 : row, col,\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        row == R1 ? R2 : row == R2 ? R1 : row, col,\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <int R1, int R2, class OriginalMatrix, int R, int C>\nstruct deduce_mat<qvm_detail::swap_rows_<R1, R2, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int R1, int R2, class OriginalMatrix, int R, int C>\nstruct deduce_mat2<qvm_detail::swap_rows_<R1, R2, OriginalMatrix>,\n                   qvm_detail::swap_rows_<R1, R2, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int R1, int R2, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::swap_rows_<R1, R2, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    swap_rows(A const &a) {\n  return reinterpret_cast<typename qvm_detail::swap_rows_<R1, R2, A> const &>(\n      a);\n}\n\ntemplate <int R1, int R2, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::swap_rows_<R1, R2, A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    swap_rows(A &a) {\n  return reinterpret_cast<typename qvm_detail::swap_rows_<R1, R2, A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <int Row1, int Row2, class OriginalMatrix> class swap_cols_ {\n  swap_cols_(swap_cols_ const &);\n  swap_cols_ &operator=(swap_cols_ const &);\n  ~swap_cols_();\n\npublic:\n  template <class T>\n  BOOST_QVM_INLINE_TRIVIAL swap_cols_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <int C1, int C2, class OriginalMatrix>\nstruct mat_traits<qvm_detail::swap_cols_<C1, C2, OriginalMatrix>> {\n  typedef qvm_detail::swap_cols_<C1, C2, OriginalMatrix> this_matrix;\n  typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\n  static int const rows = mat_traits<OriginalMatrix>::rows;\n  static int const cols = mat_traits<OriginalMatrix>::cols;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template read_element<\n        Row, (Col == C1 && C1 != C2) * C2 + (Col == C2 && C1 != C2) * C1 +\n                 ((Col != C1 && Col != C2) || C1 == C2) * Col>(\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return mat_traits<OriginalMatrix>::template write_element<\n        Row, (Col == C1 && C1 != C2) * C2 + (Col == C2 && C1 != C2) * C1 +\n                 ((Col != C1 && Col != C2) || C1 == C2) * Col>(\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::read_element_idx(\n        row, col == C1 ? C2 : col == C2 ? C1 : col,\n        reinterpret_cast<OriginalMatrix const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return mat_traits<OriginalMatrix>::write_element_idx(\n        row, col == C1 ? C2 : col == C2 ? C1 : col,\n        reinterpret_cast<OriginalMatrix &>(x));\n  }\n};\n\ntemplate <int C1, int C2, class OriginalMatrix, int R, int C>\nstruct deduce_mat<qvm_detail::swap_cols_<C1, C2, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int C1, int C2, class OriginalMatrix, int R, int C>\nstruct deduce_mat2<qvm_detail::swap_cols_<C1, C2, OriginalMatrix>,\n                   qvm_detail::swap_cols_<C1, C2, OriginalMatrix>, R, C> {\n  typedef mat<typename mat_traits<OriginalMatrix>::scalar_type, R, C> type;\n};\n\ntemplate <int C1, int C2, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::swap_cols_<C1, C2, A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    swap_cols(A const &a) {\n  return reinterpret_cast<typename qvm_detail::swap_cols_<C1, C2, A> const &>(\n      a);\n}\n\ntemplate <int C1, int C2, class A>\ntypename boost::enable_if_c<is_mat<A>::value,\n                            qvm_detail::swap_cols_<C1, C2, A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    swap_cols(A &a) {\n  return reinterpret_cast<typename qvm_detail::swap_cols_<C1, C2, A> &>(a);\n}\n\n////////////////////////////////////////////////\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "5d2bba9184999c2755ee27e1360bfb0e82eeb664", "size": 25397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/map_mat_mat.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/map_mat_mat.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/map_mat_mat.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": 35.6199158485, "max_line_length": 80, "alphanum_fraction": 0.6662991692, "num_tokens": 6751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242354120407358, "lm_q2_score": 0.0271692311418275, "lm_q1q2_score": 0.008809226854100431}}
{"text": "/*\n * GloveVLBL.cpp\n *\n *  Created on: 2014/09/13\n *      Author: miwa\n */\n#include \"GloveVLBL.h\"\n#include <gzstream.h>\n#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <boost/filesystem.hpp>\n#include <algorithm>\n#include <unordered_set>\n#include <cmath>\nusing namespace std;\nusing namespace boost::filesystem;\n\ntemplate<class T>\ncoin::GloveVLBL<T>::GloveVLBL(const string& freq_file, const string& coocc_file, int dim): coocc_file_(coocc_file), dim_(dim) {\n\ttotal_ = load_word_counts(freq_file, word_indices_, word_strings_, word_counts_);\n\tfunction<double()> rand(bind(uniform_real_distribution<double>(-.5/dim, .5/dim), default_random_engine(0)));\n\twords_.resize(word_indices_.size());\n\tint nwords = 0;\n\tfor(pair<string, int> word:word_indices_){\n\t\twords_[word.second] = new T(word.second, dim_, rand);\n\t\tnwords++;\n\t}\n\tassert(nwords == word_indices_.size());\n\tinit_table();\n}\n\ntemplate<class T>\ncoin::GloveVLBL<T>::GloveVLBL(const string& freq_file, const string& model_file) : coocc_file_(\"\") {\n\tif(freq_file == \"-g\"){\n\t\tload_glove_vector(model_file, false);\n\t}else if(freq_file == \"-l\"){\n\t\t// log-bilinear\n\t\tload_glove_vector(model_file, true);\n\t}else{\n\t\ttotal_ = load_word_counts(freq_file, word_indices_, word_strings_, word_counts_);\n\t\tload_model(model_file);\n\t}\n}\n\ntemplate<class T>\ncoin::GloveVLBL<T>::GloveVLBL(const string& freq_file, const string& coocc_file, const string& model_file): coocc_file_(coocc_file) {\n\ttotal_ = load_word_counts(freq_file, word_indices_, word_strings_, word_counts_);\n\tload_model(model_file);\n\tinit_table();\n}\n\ntemplate<class T>\nbool more(const pair<T, double>& left, const pair<T, double>& right ) {\n    if( left.second < right.second ){\n    \treturn false;\n    }else if(right.second < left.second){\n    \treturn true;\n    }else{\n    \treturn left.first < right.first;\n    }\n}\n\n\n\ntemplate<class T>\nstring coin::GloveVLBL<T>::filename(int index) const{\n\tostringstream oss;\n\toss << tmpdir_ << \"/\" << index;\n\treturn oss.str();\n}\n\nstring current(){\n\tostringstream oss;\n\tchrono::system_clock::time_point p = chrono::system_clock::now();\n\ttime_t t = chrono::system_clock::to_time_t(p);\n  char time_string[100];\n  struct tm *tm = localtime(&t);\n  strftime(time_string,sizeof(time_string),\"%F_%T\",tm);\n  oss << time_string;\n\treturn oss.str();\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::load_dict(const std::string& dict, std::unordered_map<int, set<int>>& map){\n\tifstream in(dict.c_str());\t\n\tif(!in){\n\t\tcerr << dict << \" not found!!\" << endl;\n\t\texit(0);\n\t}\n\tstring line;\n\tstring word;\n\twhile(in && getline(in, line)){\n\t\tpreprocess(line);\n\t\tistringstream iss(line);\n\t\tiss >> word;\n\t\tif(word_indices_.find(word) != word_indices_.end()){\n\t\t\tint target_id = word_indices_[word];\n\t\t\twhile(iss >> word){\n\t\t\t\tif(word_indices_.find(word) != word_indices_.end()){\n\t\t\t\t\tint ref_id = word_indices_[word];\n\t\t\t\t\tif(target_id == ref_id)continue;\n\t\t\t\t\tif(target_id < ref_id){\n\t\t\t\t\t\tif(map.find(target_id) == map.end()){\n\t\t\t\t\t\t\tmap[target_id] = set<int>();\n\t\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t\tmap[target_id].insert(ref_id);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tif(map.find(ref_id) == map.end()){\n\t\t\t\t\t\t\tmap[ref_id] = set<int>();\n\t\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t\tmap[ref_id].insert(target_id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::load_dict(){\n\tload_dict(\"data/dict/synonym.txt\", synonyms_);\n\tload_dict(\"data/dict/antonym.txt\", antonyms_);\n\tcerr << \"synonyms:\" << synonyms_.size() << \", \" << \"antonyms:\" << antonyms_.size() << endl;\n}\n\ntemplate<class T>\nbool coin::GloveVLBL<T>::includes_pair(unordered_map<int, set<int> >& map, int w1, int w2){\n\tif(w1 < w2){\n\t\tif(map.find(w1) != map.end() && map[w1].find(w2) != map[w1].end()){\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\tif(map.find(w2) != map.end() && map[w2].find(w1) != map[w2].end()){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::init_table(){\n\tload_dict();\n\tnwords_ = words_.size();\n    tmpdir_ = \"tmp/\"+current();\n\tif(!is_directory(tmpdir_)){\n\t\tif(!create_directories(tmpdir_)){\n\t\t\tcerr << \"cannot create directory: \" << tmpdir_ << endl;\n\t\t\texit(-1);\n\t\t}\t\t\n\t}\n\tvector<pair<int32_t, count_t>> neg_sample_word_counts;\t\n\tneg_sample_word_counts.reserve(nwords_);\n\tdouble neg_sample_total = 0.;\n\tvector<double> subsampling;\n\tsubsampling.resize(nwords_);\n\tint index = 0;\n\tfor(double wc:word_counts_){\n\t\t//subsampling (word2vec)\n\t\tdouble s = wc / (SUBSAMPLING * total_);\n\t\tdouble p = min((sqrt(s) + 1.) / s, 1.);\n\t\t//double p = min(sqrt(total_ * SUBSAMPLING / wc), 1.); // mikolov's paper\n\t\tsubsampling[index] = p;\n\t\t//neg_sampling\n\t\tcount_t pc = pow(wc, .75);\n\t\tneg_sample_word_counts.push_back(pair<int32_t, count_t>(index, pc));\n\t\tneg_sample_total += pc;\n\t\tindex++;\n\t}\n\tvector<count_t> subsampled_counts;\n\tsubsampled_counts.resize(nwords_, 0);\n\t{\n\t\tifstream coocc_in(coocc_file_, ios::in | ios::binary);\n\t\tif(!coocc_in){\n\t\t\tcerr << coocc_file_ << \" not found!!\" << endl;\n\t\t\texit(0);\n\t\t}\n\t\tint32_t w1, w2;\n\t\tdouble count;\n\t\tdouble subsampled_count_total = 0.;\n\t\tint64_t count_total = 0;\n\t\tint64_t total = 0;\n\t\twhile(!coocc_in.eof()){\n\t\t\tcoocc_in.read((char *)&w1, sizeof(int32_t));\n\t\t\tif(coocc_in.eof())break;\n\t\t\tcoocc_in.read((char *)&w2, sizeof(int32_t));\n\t\t\tcoocc_in.read((char *)&count, sizeof(double));\n\t\t\t\n\t\t\tdouble subsampled_count = count * subsampling[w1] * subsampling[w2];\n\t\t\tsubsampled_counts[w1] += subsampled_count;\n\t\t\tsubsampled_count_total += subsampled_count;\n\t\t\tcount_total += count;\n\t\t\ttotal++;\n\t\t}\n\t\tcoocc_in.close();\n\t\tcerr << count_total << \" (\" << (int64_t) subsampled_count_total << \" sampled) cooccurrences, \" << total << \" unique cooccurrences\" << endl;\n\t}\n\tset<int64_t> antonym_set;\n\tfor(pair<int, std::set<int> > pairs:antonyms_){\n\t\tint w1 = pairs.first;\n\t\tfor(int w2: pairs.second){\n\t\t\tantonym_set.insert(to_scalar(w2, w1));\n\t\t\tantonym_set.insert(to_scalar(w1, w2));\n\t\t}\n\t}\n\tset<int64_t> synonym_set;\n\tfor(pair<int, std::set<int> > pairs:synonyms_){\n\t\tint w1 = pairs.first;\n\t\tfor(int w2: pairs.second){\n\t\t\tsynonym_set.insert(to_scalar(w2, w1));\n\t\t\tsynonym_set.insert(to_scalar(w1, w2));\n\t\t}\n\t}\n\tsort(neg_sample_word_counts.begin(), neg_sample_word_counts.end(), more<int32_t>);\n\t{\n\t\tchar *buf[FILES];\n\t\tofstream *tmp_files[FILES];\n\t\tfor(int i = 0;i < FILES;++i){\n\t\t\tbuf[i] = new char[BUFSIZE];\n\t\t\ttmp_files[i] = new ofstream(filename(i), ios::out | ios::binary | ios::trunc);\n\t\t\ttmp_files[i]->rdbuf()->pubsetbuf(buf[i], BUFSIZE);\n\t\t}\n   \t\t\n\t\tunsigned long long next_random = 0.;\n\n\t\tint64_t updates = 0;\n\t\tdouble total_counts = 0., total_neg_counts = 0.;\n\t\tint64_t antonym_matches = 0, synonym_matches = 0;\n\t\tint file_idx = 0;\n\t\tvector<int32_t> *cooccurrences = new vector<int32_t>[nwords_];\n\t\t{\t\n\t\t\tifstream coocc_in(coocc_file_, ios::in | ios::binary);\n\t\t\tif(!coocc_in){\n\t\t\t\tcerr << coocc_file_ << \" not found!!\" << endl;\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\tint32_t w1, w2;\n\t\t\tdouble coocc_count;\n\t\t\twhile(!coocc_in.eof()){\n\t\t\t\tcoocc_in.read((char *)&w1, sizeof(int32_t));\n\t\t\t\tif(coocc_in.eof())break;\n\t\t\t\tcoocc_in.read((char *)&w2, sizeof(int32_t));\n\t\t\t\tcoocc_in.read((char *)&coocc_count, sizeof(double));\n\n\t\t\t\tassert(w1 < nwords_);\n\t\t\t\tcooccurrences[w1].push_back(w2);\n\n\t\t\t\tcount_t count = coocc_count * subsampling[w1] * subsampling[w2];\n\t\t\t\tcount_t cnt = (subsampled_counts[w1] * K) / neg_sample_total;\n\t\t\t\tcount_t neg_count = cnt * pow(word_counts_[w2], .75);\n\t\t\t\tif(count < MIN_COUNT){\n\t\t\t\t\tcount = 0.;\n\t\t\t\t}else if(count < 1.){\n\t\t\t\t\tnext_random = next_random * (unsigned long long)25214903917 + 11;\n\t\t\t\t\tcount = ((next_random & 0xFFFF) / (count_t)65536 < count) ? 1. : 0.;\n\t\t\t\t} \n\t\t\t\tif(neg_count < MIN_COUNT){\n\t\t\t\t\tneg_count = 0.;\n\t\t\t\t}else if(neg_count < 1.){\n\t\t\t\t\tnext_random = next_random * (unsigned long long)25214903917 + 11;\n\t\t\t\t\tneg_count = ((next_random & 0xFFFF) / (count_t)65536 < neg_count) ? 1. : 0.;\n\t\t\t\t} \n\t\t\t\tif(count > 0. || neg_count > 0.){\n\t\t\t\t\tif(synonym_set.find(to_scalar(w1, w2)) != synonym_set.end()){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(antonym_set.find(to_scalar(w1, w2)) != antonym_set.end()){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\ttotal_counts += count;\n\t\t\t\t\ttotal_neg_counts += neg_count;\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&w1, sizeof(int32_t));\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&w2, sizeof(int32_t));\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&count, sizeof(count_t));\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&neg_count, sizeof(count_t));\n\t\t\t\t\tupdates++;\n\t\t\t\t\tfile_idx = (file_idx+1) % FILES;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcoocc_in.close();\n\t\t}\n\t\tfor(int i = 0;i < nwords_;++i){\n\t\t\tpair<int32_t, count_t>& w1cnt = neg_sample_word_counts[i];\n\n\t\t\tvector<int32_t>& coocc = cooccurrences[w1cnt.first];\n\t\t\tsort(coocc.begin(), coocc.end());\n\n\t\t\tint l = 0, r = nwords_ - 1, m = (l+r) / 2;\n\t\t\tcount_t cnt = (subsampled_counts[w1cnt.first] * K) / neg_sample_total;\n\t\t\tcount_t icnt = MIN_COUNT / cnt;\n\t\t\twhile(l < r){\n\t\t\t\tif(neg_sample_word_counts[m].second >= icnt){\n\t\t\t\t\tl = m + 1;\n\t\t\t\t}else{\n\t\t\t\t\tr = m;\n\t\t\t\t}\n\t\t\t\tm = (l + r) / 2;\n\t\t\t}\n\t\t\tassert(m == 0 || neg_sample_word_counts[m - 1].second >= icnt);\n\t\t\tassert(m == nwords_ - 1 || neg_sample_word_counts[m].second < icnt);\n\t\t\tfor(int j = 0;j < m;++j){\n\t\t\t\tpair<int32_t, count_t>& w2cnt = neg_sample_word_counts[j];\n\t\t\t\tif(binary_search(coocc.begin(), coocc.end(), w2cnt.first)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcount_t count = 0.;\n\t\t\t\tcount_t neg_count = cnt * w2cnt.second;\n\n\t\t\t\tassert(neg_count >= MIN_COUNT);\n\t\t\t\tif(neg_count < 1.){\n\t\t\t\t\tnext_random = next_random * (unsigned long long)25214903917 + 11;\n\t\t\t\t\tneg_count = ((next_random & 0xFFFF) / (count_t)65536 < neg_count) ? 1. : 0.;\n\t\t\t\t} \n\t\t\t\tif(neg_count > 0.){\n\t\t\t\t\tif(synonym_set.find(to_scalar(w1cnt.first, w2cnt.first)) != synonym_set.end()){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(antonym_set.find(to_scalar(w1cnt.first, w2cnt.first)) != antonym_set.end()){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\ttotal_counts += count;\n\t\t\t\t\ttotal_neg_counts += neg_count;\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&w1cnt.first, sizeof(int32_t));\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&w2cnt.first, sizeof(int32_t));\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&count, sizeof(count_t));\n\t\t\t\t\ttmp_files[file_idx]->write((char *)&neg_count, sizeof(count_t));\n\t\t\t\t\tupdates++;\n\t\t\t\t\tfile_idx = (file_idx+1) % FILES;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(int64_t synonym:synonym_set){\n\t\t\tpair<int32_t, int32_t> p = to_pair(synonym);\n\t\t\tcount_t count = SYN_WEIGHT;\n\t\t\tcount_t neg_count = 0.;\n\t\t\tsynonym_matches++;\n\t\t\tif(antonym_set.find(synonym) != antonym_set.end()){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttmp_files[file_idx]->write((char *)&p.first, sizeof(int32_t));\n\t\t\ttmp_files[file_idx]->write((char *)&p.second, sizeof(int32_t));\n\t\t\ttmp_files[file_idx]->write((char *)&count, sizeof(count_t));\n\t\t\ttmp_files[file_idx]->write((char *)&neg_count, sizeof(count_t));\n\t\t\tfile_idx = (file_idx+1) % FILES;\n\t\t}\n\t\tfor(int64_t antonym:antonym_set){\n\t\t\tpair<int32_t, int32_t> p = to_pair(antonym);\n\t\t\tcount_t count = 0.;\n\t\t\tcount_t neg_count = ANT_WEIGHT;\n\t\t\tantonym_matches++;\n\t\t\ttmp_files[file_idx]->write((char *)&p.first, sizeof(int32_t));\n\t\t\ttmp_files[file_idx]->write((char *)&p.second, sizeof(int32_t));\n\t\t\ttmp_files[file_idx]->write((char *)&count, sizeof(count_t));\n\t\t\ttmp_files[file_idx]->write((char *)&neg_count, sizeof(count_t));\n\t\t\tfile_idx = (file_idx+1) % FILES;\n\t\t}\n\t\tprint_mem();\n\t\tcerr << \"Total updates: \" << updates << \", counts: \" << total_counts << \", neg_counts: \" << total_neg_counts << endl;\n\t\tcerr << \"Total synonym matches: \" << synonym_matches << \", antonym matches: \" << antonym_matches << endl;\n\t\tfor(int i = 0;i < FILES;++i){\n\t\t\ttmp_files[i]->close();\n\t\t\tdelete tmp_files[i];\n\t\t\tdelete[] buf[i];\n\t\t}\n\t\tdelete[] cooccurrences;\n\t}\n\tmerge_files();\n}\n\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::merge_files(){\n#ifdef _OPENMP\n#pragma omp parallel num_threads(N_THREADS)\n#endif\n\t{\n\t\tint size = FILES / N_THREADS;\n\t\tint start = omp_get_thread_num() * size;\n\t\tchar *buf_in = new char[BUFSIZE];\n\t\tchar *buf_out = new char[BUFSIZE];\n\t\tstring tmp_filename = filename(omp_get_thread_num())+\".tmp\";\n\t\tofstream out_file(tmp_filename, ios::out | ios::binary);\n\t\tdefault_random_engine rand(omp_get_thread_num());\n\t\tout_file.rdbuf()->pubsetbuf(buf_out, BUFSIZE);\n\t\tint nupdates = 0;\n\t\tvector<UpdateEntry> updates;\n\t\tupdates.reserve(SHUFFLE_SIZE+1); \n\t\tfor(int i = 0;i < size;++i){\n\t\t\tstring in_filename = filename(start+i);\n\t\t\tifstream in_file(in_filename, ios::in | ios::binary);\n\t\t\tin_file.rdbuf()->pubsetbuf(buf_in, BUFSIZE);\n\t\t\twhile(true){\n\t\t\t\tint32_t w1, w2;\n\t\t\t\tcount_t count, neg_count;\n\t\t\t\tin_file.read((char *)&w1, sizeof(int32_t));\n\t\t\t\tif(in_file.eof())break;\n\t\t\t\tin_file.read((char *)&w2, sizeof(int32_t));\n\t\t\t\tin_file.read((char *)&count, sizeof(count_t));\n\t\t\t\tin_file.read((char *)&neg_count, sizeof(count_t));\n\t\t\t\tupdates.push_back(UpdateEntry(w1, w2, count, neg_count));\n\t\t\t\tnupdates++;\n\t\t\t\tif(nupdates > SHUFFLE_SIZE){\n\t\t\t\t\tshuffle(updates.begin(), updates.end(), rand);\n\t\t\t\t\tfor(UpdateEntry entry:updates){\n\t\t\t\t\t\tout_file.write((char*)&entry.w1, sizeof(int32_t));\n\t\t\t\t\t\tout_file.write((char*)&entry.w2, sizeof(int32_t));\n\t\t\t\t\t\tout_file.write((char*)&entry.count, sizeof(count_t));\n\t\t\t\t\t\tout_file.write((char*)&entry.neg_count, sizeof(count_t));\n\t\t\t\t\t}\n\t\t\t\t\tupdates.clear();\n\t\t\t\t\tnupdates = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tin_file.close();\n\t\t\ttry{\n\t\t\t\tremove(path(in_filename));\t\n\t\t\t}catch(filesystem_error& ex) {\n\t\t\t\tcerr << ex.what() << endl;\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t}\n\t\tif(nupdates > 0){\n\t\t\tshuffle(updates.begin(), updates.end(), rand);\n\t\t\tfor(UpdateEntry entry:updates){\n\t\t\t\tout_file.write((char*)&entry.w1, sizeof(int32_t));\n\t\t\t\tout_file.write((char*)&entry.w2, sizeof(int32_t));\n\t\t\t\tout_file.write((char*)&entry.count, sizeof(count_t));\n\t\t\t\tout_file.write((char*)&entry.neg_count, sizeof(count_t));\n\t\t\t}\n\t\t}\n\t\tout_file.close();\n\t\tdelete[] buf_in;\n\t\tdelete[] buf_out;\n\t}\n\tfor(int i = 0;i < N_THREADS;i++){\n\t\trename(path(filename(i)+\".tmp\"), path(filename(i)));\n\t}\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::load_glove_vector(const std::string& glove_file, const bool skip_id){\n\tifstream glove_in(glove_file, ios::in);\n\tif(!glove_in){\n\t\tcerr << glove_file << \" not found!!\" << endl;\n\t}\n\tstring line;\n\tint windex = 0;\n\tif(skip_id){\n\t\tgetline(glove_in, line); // skip header\n\t}\n\twhile(glove_in && getline(glove_in, line)){\n\t\tint dim = 0;\n\t\tistringstream iss(line);\n\t\tstring word;\n\t\tiss >> word;\n\t\tvector<double> embed;\n\t\tdouble bias = 0.;\n\t\tif(skip_id){\n\t\t\tint id; double gram;\n\t\t\tiss >> id >> bias >> gram;\n\t\t}\n\t\twhile(iss){\n\t\t\tdouble v;\n\t\t\tiss >> v;\n\t\t\tif(iss){\n\t\t\t\tembed.push_back(v);\n\t\t\t\tdim++;\n\t\t\t}\n\t\t}\n\t\tdim_ = dim;\n\t\tpreprocess(word);\n\t\tif(word_indices_.find(word) == word_indices_.end()){\n\t\t\tword_indices_[word] = windex;\n\t\t\tword_strings_.push_back(word);\n\t\t\tVector embeddings(dim);\n\t\t\tfor(int i = 0;i < dim;i++){\n\t\t\t\tembeddings[i] = embed[i];\n\t\t\t}\n\t\t\twords_.push_back(new T(windex, embeddings, bias));\n\t\t\twindex++;\n\t\t}else{\n\t\t\t//TODO: lowercase\n\t\t}\n\t}\n\tcerr << windex << \" words are loaded.\" << endl;\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::save_model(const string& model_file){\n\tofstream os(model_file, ios::binary | ios::out | ios::trunc);\n\tos.write((char *)&niters_, sizeof(int));\n\tos.write((char *)&dim_, sizeof(int));\n\tint size = words_.size();\n\tos.write((char *)&size, sizeof(int));\n\tfor(T* word:words_){\n\t\tword->save(os);\n\t}\n\tassert(words_.size() == word_indices_.size());\n\tos.close();\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::save_text_model(const string& model_file){\n\tofstream os(model_file, ios::out | ios::trunc);\n\tos << dim_ << \" \" << words_.size() << endl;\n\tfor(T* word:words_){\n        os << word_strings_[word->id()];\n\t\tword->save_text(os);\n        os << endl;\n\t}\n\tassert(words_.size() == word_indices_.size());\n\tos.close();\n}\n\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::load_model(const string& model_file){\n\tifstream is(model_file, ios::binary | ios::in );\n\tif(!is){\n\t\tcerr << \"error in opening model file: \" << model_file << endl; \n\t\texit(0);\n\t}\n\tis.read((char *)&niters_, sizeof(int));\n\tis.read((char *)&dim_, sizeof(int));\n\tfor(T* word:words_){\n\t\tdelete word;\n\t}\n\tint size = 0;\n\tis.read((char *)&size, sizeof(int));\n\twords_.resize(size);\n\tfor(int i = 0;i < size;i++){\n\t\tT* word = new T(dim_, is);\n\t\twords_[word->id()] = word;\n\t}\n\tis.close();\n}\n\ntemplate<class T>\ncoin::GloveVLBL<T>::~GloveVLBL(){\n\tfor(T* word:words_){\n\t\tdelete word;\n\t}\n\tif(is_directory(tmpdir_)){\n\t\tremove_all(tmpdir_);\n\t}\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::similar_words(const string& word, int limit, bool reverse){\n\tif(word_indices_.find(word) == word_indices_.end()){\n\t\tcout << \"no word vector for \" << word << endl;\n    int i = 0;\n    while(true){\n      if(++i > limit)break;\n      cout << \"unknown\" << \"\\t\" << 0.0000 << endl;\n    }\n\t\treturn;\n\t}\n\tT *w = words_[word_indices_[word]];\n\tlist<pair<int, double>> sim_words;\n\tfor(T* comp:words_){\n\t\tif(w == comp)continue;\n    if(reverse){\n      sim_words.push_back(pair<int, double>(comp->id(), -w->similarity(*comp)));\n    }else{\n      sim_words.push_back(pair<int, double>(comp->id(), w->similarity(*comp)));\n    }\n\t}\n\tsim_words.sort(more<int>);\n\tint i = 0;\n\tfor(pair<int, double> sim_word:sim_words){\n\t\tif(++i > limit)break;\n    if(reverse){\n      cout << word_strings_[sim_word.first] << \"\\t\" << -sim_word.second << endl;\n    }else{\n      cout << word_strings_[sim_word.first] << \"\\t\" << sim_word.second << endl;\n    }\n\t}\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::antonym_score(const std::string& file){\n\tifstream in(file.c_str());\n\tif(!in){\n\t\tcerr << file << \" not found!!\" << endl;\n\t\treturn;\n\t}\n\tload_dict();\n\tstring line;\n\tstring target, word, ans_word;\n\tint w1idx, w2idx;\n\tT* w1;\n\tT* w2;\n\tint correct = 0, total = 0, answer = 0;\n\twhile(in && getline(in, line)){\n\t\ttotal++;\n\t\tpreprocess(line);\n\t\tistringstream iss(line);\n\t\tiss >> target;\n\t\ttarget = target.substr(0, target.size() - 1);\n\t\tif(word_indices_.find(target) != word_indices_.end()){\n\t\t\tw1idx = word_indices_[target];\n\t\t\tw1 = words_[w1idx];\n\t\t}else{\n\t\t\tw1idx = -1;\n\t\t\tcontinue;\n\t\t}\n\t\tans_word = \"\";\n\t\tdouble min_sim = 1000000.;\n\t\tbool skip = false;\n\t\tfor(int i = 0;i < 5;++i){\n\t\t\tiss >> word;\n\t\t\tdouble sim = 100.;\n\t\t\tif(word_indices_.find(word) != word_indices_.end()){\n\t\t\t\tw2idx = word_indices_[word];\n\t\t\t\tw2 = words_[w2idx];\n\t\t\t\tsim = w1->similarity(*w2);\n\t\t\t}else{\n\t\t\t\tw2idx = -1;\n\t\t\t\tskip = true;\n\t\t\t}\n\t\t\tif(sim < min_sim){\n\t\t\t\tmin_sim = sim;\n\t\t\t\tans_word = word;\n\t\t\t} \n\t\t\tif(includes_pair(antonyms_, w1idx, w2idx)){\n\t\t\t\tcerr << target << \":\" << word << \":\" << sim << \"*\" << endl;\n\t\t\t}else{\n\t\t\t\tcerr << target << \":\" << word << \":\" << sim << endl;\n\t\t\t}\n\t\t}\n\t\tiss >> word;\n\t\tassert(word == \"::\");\n\t\tiss >> word;\n\t\tcerr << \"====\" << target << \":\" << word << \" => \" << ans_word << endl;\n\t\tif(skip){\n\t\t\tcontinue;\n\t\t}\n\t\tif(ans_word == word){\n\t\t\tcorrect++;\n\t\t}\n\t\tanswer++;\n\t}\n\tdouble p = correct/(double)answer;\n\tdouble r = correct/(double)total;\n\tdouble f = 2. * p * r / (p + r);\n\tcerr << \"P/R/F: \" << p << \" / \" << r << \" / \" << f << endl;\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::conv(const string& gzfile){\n\tigzstream in(gzfile.c_str());\n\tif(!in){\n\t\tcerr << gzfile << \" not found!!\" << endl;\n\t\treturn;\n\t}\n\tstring line;\n\tstring word;\n\twhile(in && getline(in, line)){\n\t\tpreprocess(line);\n\t\tistringstream iss(line);\n\t\tVector v(Vector::Zero(dim_));\n\t\twhile(iss >> word){\n\t\t\tif(word_indices_.find(word) != word_indices_.end()){\n\t\t\t\tv += words_[word_indices_[word]]->embeddings();\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0;i < dim_;++i){\n\t\t\tcout << v[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\tin.close();\n}\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::iterate(){\n\tdouble cost = 0.;\n\tlong nupdates = 0;\n\tTimer t;\n\tomp_lock_t lock[nwords_];\n\tfor (int i = 0;i < nwords_;++i){\n\t  omp_init_lock(&(lock[i]));\n\t}\n\n#ifdef _OPENMP\n#pragma omp parallel num_threads(N_THREADS) reduction(+:nupdates) reduction(+:cost) default(shared)\n#endif\n\t{\n\t\t//unsigned long long next_random = niters_ * omp_get_thread_num();\n\t\tchar *buf = new char[BUFSIZE];\n\t\tifstream in_file(filename(omp_get_thread_num()), ios::in | ios::binary);\n\t\tin_file.rdbuf()->pubsetbuf(buf, BUFSIZE);\t\t\n\t\twhile(true){\n\t\t\tint32_t w1idx, w2idx;\n\t\t\tcount_t count, neg_count;\n\t\t\tin_file.read((char *)&w1idx, sizeof(int32_t));\n\t\t\tif(in_file.eof())break;\n\t\t\tin_file.read((char *)&w2idx, sizeof(int32_t));\n\t\t\tin_file.read((char *)&count, sizeof(count_t));\n\t\t\tin_file.read((char *)&neg_count, sizeof(count_t));\t\n\n\t\t\t// if(count < 1. && count > 0.){\n\t\t\t// \tnext_random = next_random * (unsigned long long)25214903917 + 11;\n\t\t\t// \tcount = ((next_random & 0xFFFF) / (count_t)65536 < count) ? 1. : 0.;\n\t\t\t// }\t\t\t\n\t\t\t// if(neg_count < 1. && neg_count > 0.){\n\t\t\t// \tnext_random = next_random * (unsigned long long)25214903917 + 11;\n\t\t\t// \tneg_count = ((next_random & 0xFFFF) / (count_t)65536 < neg_count) ? 1. : 0.;\n\t\t\t// }\t\t   \n\n\t\t\tT* w1 = words_[w1idx];\t\t\t  \n\t\t\tT* w2 = words_[w2idx];\t\t\t  \n\n\t\t\t// ivlbl\n\t\t\tdouble q = sigmoid(w1->t_embeddings().dot(w2->c_embeddings()) + w2->c_bias());\n\t\t\t//double q = sigmoid(w1->t_embeddings().dot(w2->c_embeddings())); // no bias\n\t\t\tdouble diff = count * (1. - q) - neg_count * q;\n\t\t\tif(q > 0. && q < 1.){\n\t\t\t\tcost -= count * log(q) + neg_count * log(1. - q);\n\t\t\t}\n\t\t\tif(diff == 0.){\n\t\t\t    continue;\n\t\t\t}\n\t\t\tVector w2update(w1->t_embeddings());\n\n\t\t\tomp_set_lock(&(lock[w1idx]));\n\t\t\tw1->update_t(w2->c_embeddings(), 0., diff);\n\t\t\tomp_unset_lock(&(lock[w1idx]));\n\t\t\t\n\t\t\tomp_set_lock(&(lock[w2idx]));\n\t\t\tw2->update_c(w2update, 1., diff);\n\t\t\t//w2->update_c(w2update, 0., diff); // no bias \n\t\t\tomp_unset_lock(&(lock[w2idx]));\n\t\t\t// #pragma omp critical\n\t\t\t// {\n\t\t\t// \tcerr << q << \":\" << count << \":\" << neg_count << \":\" << sigmoid(w1->t_embeddings().dot(w2->c_embeddings()) + w2->c_bias()) << endl;\n\t\t\t//}\n\t\t\tnupdates++;\n\t\t}\n\t\tin_file.close();\n\t\tdelete[] buf;\n\t}\n\tniters_++;\n\t//reset_history();\n\n    for(int i = 0; i < nwords_;++i){\n        omp_destroy_lock(&(lock[i]));\n\t}\n\tdouble time = (double)t.seconds();\n\tcerr << \"cost: \" << cost << \", updates: \" << nupdates << \", time: \" << time << \" seconds, speed:\" << nupdates / (N_THREADS * time) << \" [words/threads/sec]\" << endl;\n}\n\n\ntemplate<class T>\nvoid coin::GloveVLBL<T>::reset_history(){\n\tfor(T* w:words_){\n\t\tw->reset_history();\n\t}\n}\n\n\ntemplate<class T>\nT coin::GloveVLBL<T>::calc_mean_word(){\n\tT mean(dim_);\n\tfor(T* word:words_){\n\t\tmean.add(*word);\n\t}\n\tmean.mult(1. / words_.size());\n\treturn mean;\n}\n\ncoin::SymmetricWord::SymmetricWord(const SymmetricWord& word):\n\tbias_(word.bias()), grad_(word.grad_), embeddings_(word.embeddings()){};\n\ncoin::SymmetricWord& coin::SymmetricWord::operator=(const SymmetricWord& word) {\n\tbias_ = word.bias();\n\tgrad_ = word.grad_;\n\tembeddings_ = word.embeddings();\n\treturn *this;\n}\n\ncoin::SymmetricWord::SymmetricWord(int dim):\n\tWord(0), bias_(0.), grad_(0.), embeddings_(Vector::Zero(dim)){\n}\n\ncoin::SymmetricWord::SymmetricWord(int id, int dim, function<double()> &rand):\n\tWord(id), bias_(0.), grad_(0.), embeddings_(Vector(dim)){\n\tfor(int i = 0;i < dim;++i){\n\t\tembeddings_[i] = rand();\n\t}\n\tassert(dim == embeddings_.size());\n}\n\ncoin::SymmetricWord::SymmetricWord(int id, const Vector &v, double bias):\n\tWord(id), bias_(bias), grad_(0.), embeddings_(v){\n}\n\n\ninline void coin::SymmetricWord::update(const Vector& vector_grad, const double bias_grad, const double scale){\n\tgrad_ += (vector_grad.squaredNorm() + bias_grad * bias_grad) / (vector_grad.size() + 1.) * scale * scale;\n \tdouble alpha = RHO * scale / sqrt(grad_);\n \tembeddings_ += alpha * vector_grad;\n \tbias_ += alpha * bias_grad;\n}\n\nvoid coin::SymmetricWord::save(ostream& os){\n\tos.write((char *)&id_, sizeof(int));\n\tos.write((char *)&bias_, sizeof(double));\n\tos.write((char *)&grad_, sizeof(double));\n\tfor(int i = 0;i < embeddings_.size();++i){\n\t\tos.write((char*)&embeddings_[i], sizeof(double));\n\t}\n}\n\nvoid coin::SymmetricWord::save_text(ostream& os){\n\tfor(int i = 0;i < embeddings_.size();++i){\n\t\tos << \" \" << embeddings_[i];\n\t}\n    os << \" \" << bias_;\n}\n\nvoid coin::SymmetricWord::load(istream& is){\n\tis.read((char *)&id_, sizeof(int));\n\tis.read((char *)&bias_, sizeof(double));\n\tis.read((char *)&grad_, sizeof(double));\n\tfor(int i = 0;i < embeddings_.size();++i){\n\t\tis.read((char*)&embeddings_[i], sizeof(double));\n\t}\n}\n\nvoid coin::SymmetricWord::add(const SymmetricWord& word){\n\tembeddings_ += word.embeddings();\n\tbias_ += word.bias();\n}\n\nvoid coin::SymmetricWord::mult(const double mult){\n\tembeddings_ *= mult;\n\tbias_ *= mult;\n}\n\n// explicit instantiation of a template\nnamespace coin{\n\ttemplate class GloveVLBL<SymmetricWord>;\n};\n\n", "meta": {"hexsha": "623261efb0ef3e52d38462268830952767ad03a9", "size": 24243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GloveVLBL.cpp", "max_stars_repo_name": "Sureshkeyin/AntonymDetection", "max_stars_repo_head_hexsha": "71f6c025a3da6642fe4e3deccbdf341ddf643ed4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2016-02-16T19:30:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T01:52:26.000Z", "max_issues_repo_path": "src/GloveVLBL.cpp", "max_issues_repo_name": "Sureshkeyin/AntonymDetection", "max_issues_repo_head_hexsha": "71f6c025a3da6642fe4e3deccbdf341ddf643ed4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-21T20:12:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T20:12:20.000Z", "max_forks_repo_path": "src/GloveVLBL.cpp", "max_forks_repo_name": "Sureshkeyin/AntonymDetection", "max_forks_repo_head_hexsha": "71f6c025a3da6642fe4e3deccbdf341ddf643ed4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-02-18T09:09:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:07:43.000Z", "avg_line_length": 28.6221959858, "max_line_length": 166, "alphanum_fraction": 0.6326774739, "num_tokens": 7331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.023330769657341693, "lm_q1q2_score": 0.00880831438000826}}
{"text": "/*\n    Copyright (c) 2011-2014 University of Zurich\n    \n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n    \n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n    \n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n*/\n\n#ifndef PLLL_INCLUDE_GUARD__LLL2_GENERIC_CPP\n#define PLLL_INCLUDE_GUARD__LLL2_GENERIC_CPP\n\n#include \"lll2-internal.hpp\"\n\n#include \"lattice.cpp\"\n#include \"lllimpl.cpp\"\n#include \"enumimpl.hpp\"\n#include \"enumimpl-preproc.cpp\"\n#include \"bkzimpl.cpp\"\n#include \"svpimpl.cpp\"\n#include \"verifyimpl.cpp\"\n#include \"matrixconversion.hpp\"\n#include \"lll2-callback.cpp\"\n#include \"lll2-deepinsertion.cpp\"\n\n#include <boost/bind.hpp>\n\nnamespace plll\n{\n    template<class RealTypeContext, class IntTypeContext>\n    GSInterface<RealTypeContext, IntTypeContext> * createGSInterface(Verbose & verbose, RealTypeContext & rc, IntTypeContext & ic,\n                                                                     LatticeReduction::GramSchmidt gs, bool restarts,\n                                                                     linalg::math_matrix<typename IntTypeContext::Integer> & A);\n    \n    template<class RealTypeContext, class IntTypeContext>\n    class LRIImplementation : public LRIInterface\n    {\n        class GSIImplementation;\n        friend class GSIImplementation;\n        \n    private:\n        mutable RealTypeContext d_rc;\n        mutable IntTypeContext d_ic;\n        MatrixConversion<IntTypeContext> d_intlattice;\n        Verbose d_verbose;\n        mutable STD_AUTO_PTR<GSInterface<RealTypeContext, IntTypeContext> > d_gs;\n        mutable STD_AUTO_PTR<Lattice<RealTypeContext, IntTypeContext> > d_lattice_object;\n        mutable Transform * d_lattice_object_trans;\n        LatticeReduction::SVPMode d_svp;\n        unsigned d_max_cores;\n        \n        void handle_exception(std::exception * e) const\n        {\n            if (reduction_error * ee = dynamic_cast<reduction_error*>(e))\n            {\n                d_verbose(LatticeReduction::VL_Error) << \"FATAL ERROR during reduction: \" << ee->what();\n            }\n            else if (change_interface_exception * ee = dynamic_cast<change_interface_exception*>(e))\n            {\n                d_verbose(LatticeReduction::VL_Error) << ee->what();\n            }\n            else if (feature_not_implemented * ee = dynamic_cast<feature_not_implemented*>(e))\n            {\n                d_verbose(LatticeReduction::VL_Error) << ee->what();\n            }\n            else if (dynamic_cast<LatticeReduction::stop_reduction*>(e) != NULL)\n            {\n                d_verbose(LatticeReduction::VL_Information) << \"Stopping reduction requested\";\n            }\n            else if (dynamic_cast<LatticeReduction::stop_enumeration*>(e) != NULL)\n            {\n                d_verbose(LatticeReduction::VL_Error) << \"FATAL ERROR: Enumeration stopping request caught outside enumeration code.\";\n            }\n            else if (dynamic_cast<std::bad_alloc*>(e) != NULL)\n            {\n                d_verbose(LatticeReduction::VL_Error) << \"FATAL ERROR: Memory allocation failed!\";\n            }\n            else\n                d_verbose(LatticeReduction::VL_Error) << \"FATAL ERROR: Unhandled standard exception: \" << e->what();\n        }\n        \n        void handle_unknown_exception() const\n        {\n            d_verbose(LatticeReduction::VL_Error) << \"FATAL ERROR: Unknown exception! Re-throwing.\";\n        }\n        \n        void setupLattice(Transform * transform) const\n        {\n            if (d_lattice_object.get() == NULL)\n                d_lattice_object.reset(new Lattice<RealTypeContext, IntTypeContext>(d_gs.get(), d_rc, d_ic, d_stats, 0, d_gs->getDimension() - 1));\n            else\n            {\n                if (transform == d_lattice_object_trans)\n                    return;\n            }\n            if (d_lattice_object_trans)\n            {\n                d_lattice_object->removeAllNotifiers();\n                d_lattice_object_trans->releaseTransformObject();\n                d_lattice_object_trans = NULL;\n            }\n            if (transform)\n            {\n                d_lattice_object_trans = transform;\n                d_lattice_object->addNotifier(transform->createTransformObject<IntTypeContext>(d_ic));\n            }\n        }\n        \n        void freeLattice() const\n        {\n            if (d_lattice_object_trans)\n            {\n                if (d_lattice_object.get())\n                    d_lattice_object->removeAllNotifiers();\n                d_lattice_object_trans->releaseTransformObject();\n                d_lattice_object_trans = NULL;\n            }\n            d_lattice_object.reset();\n        }\n        \n        class GSIImplementation : public LatticeReduction::GramSchmidtInformer\n        {\n        private:\n            LRIImplementation & d_i;\n            \n        public:\n            GSIImplementation(LRIImplementation & i)\n                : d_i(i)\n            {\n            }\n            \n            virtual ~GSIImplementation()\n            {\n            }\n            \n            virtual double getGSCoefficientD(unsigned i, unsigned j) const\n            {\n                d_i.setupLattice(NULL);\n                d_i.d_lattice_object->update(i + 1);\n                return arithmetic::convert<double>(d_i.d_lattice_object->getCoeff(i, j));\n            }\n            \n            virtual long double getGSCoefficientLD(unsigned i, unsigned j) const\n            {\n                d_i.setupLattice(NULL);\n                d_i.d_lattice_object->update(i + 1);\n                return arithmetic::convert<long double>(d_i.d_lattice_object->getCoeff(i, j));\n            }\n            \n            virtual arithmetic::Real getGSCoefficientR(unsigned i, unsigned j, const arithmetic::RealContext & rc) const\n            {\n                d_i.setupLattice(NULL);\n                d_i.d_lattice_object->update(i + 1);\n                return arithmetic::convert(d_i.d_lattice_object->getCoeff(i, j), rc);\n            }\n            \n            virtual double getGSSqNormD(unsigned i) const\n            {\n                d_i.setupLattice(NULL);\n                d_i.d_lattice_object->update(i + 1);\n                return arithmetic::convert<double>(d_i.d_lattice_object->getNormSq(i));\n            }\n            \n            virtual long double getGSSqNormLD(unsigned i) const\n            {\n                d_i.setupLattice(NULL);\n                d_i.d_lattice_object->update(i + 1);\n                return arithmetic::convert<long double>(d_i.d_lattice_object->getNormSq(i));\n            }\n            \n            virtual arithmetic::Real getGSSqNormR(unsigned i, const arithmetic::RealContext & rc) const\n            {\n                d_i.setupLattice(NULL);\n                d_i.d_lattice_object->update(i + 1);\n                return arithmetic::convert(d_i.d_lattice_object->getNormSq(i), rc);\n            }\n            \n            virtual double computeProjectionLengthD(unsigned k, unsigned b,\n                                                    const linalg::math_rowvector<arithmetic::Integer> & vec) const\n            {\n                d_i.setupLattice(NULL);\n                typename RealTypeContext::Real result(d_i.d_rc);\n                VectorConversionConst<IntTypeContext> v(d_i.d_ic, vec);\n                d_i.d_lattice_object->computeProjectionLength(result, k, b, v.vector());\n                return arithmetic::convert<double>(result);\n            }\n            \n            virtual long double computeProjectionLengthLD(unsigned k, unsigned b,\n                                                          const linalg::math_rowvector<arithmetic::Integer> & vec) const\n            {\n                d_i.setupLattice(NULL);\n                typename RealTypeContext::Real result(d_i.d_rc);\n                VectorConversionConst<IntTypeContext> v(d_i.d_ic, vec);\n                d_i.d_lattice_object->computeProjectionLength(result, k, b, v.vector());\n                return arithmetic::convert<long double>(result);\n            }\n            \n            virtual arithmetic::Real computeProjectionLengthR(unsigned k, unsigned b,\n                                                              const linalg::math_rowvector<arithmetic::Integer> & vec,\n                                                              const arithmetic::RealContext & rc) const\n            {\n                d_i.setupLattice(NULL);\n                typename RealTypeContext::Real result(d_i.d_rc);\n                VectorConversionConst<IntTypeContext> v(d_i.d_ic, vec);\n                d_i.d_lattice_object->computeProjectionLength(result, k, b, v.vector());\n                return arithmetic::convert(result, rc);\n            }\n        };\n        \n        GSIImplementation d_gsi;\n        \n    public:\n        LRIImplementation(LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf, linalg::math_matrix<arithmetic::Integer> & lattice,\n                          LatticeReduction::GramSchmidt gs, bool gsr, LatticeReduction::SVPMode svp, unsigned max_cores,\n                          const RealTypeContext & rc, const IntTypeContext & ic)\n            : LRIInterface(lattice), d_rc(rc), d_ic(ic), d_intlattice(d_ic, d_lattice, true, true), d_verbose(vol, vf),\n              d_gs(createGSInterface(d_verbose, d_rc, d_ic, gs, gsr, d_intlattice.matrix())),\n              d_lattice_object(), d_lattice_object_trans(NULL), d_svp(svp), d_max_cores(max_cores), d_gsi(*this)\n        {\n        }\n        \n        virtual ~LRIImplementation()\n        {\n        }\n        \n        virtual void setupVerbose(LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf)\n        {\n            d_verbose.setup(vol, vf);\n        }\n        \n        virtual void ensureMinimumPrecision(unsigned long p)\n        {\n            if (RealTypeContext::is_variable_precision && (p > d_rc.getRealPrecision()))\n                d_rc.setRealPrecision((p + 7) & ~7); // make multiple of 8\n        }\n        \n        virtual const LatticeReduction::GramSchmidtInformer * getInformer() const\n        {\n            return &d_gsi;\n        }\n        \n        virtual void forceGSRebuild(bool makeSureAllComputed)\n        {\n            if (d_lattice_object.get())\n            {\n                d_lattice_object->reset();\n                if (makeSureAllComputed)\n                    d_lattice_object->update(d_lattice_object->dimension());\n            }\n        }\n        \n        virtual double getGSCoefficientD(unsigned i, unsigned j) const\n        {\n            setupLattice(NULL);\n            d_lattice_object->update(i + 1);\n            return arithmetic::convert<double>(d_lattice_object->getCoeff(i, j));\n        }\n        \n        virtual long double getGSCoefficientLD(unsigned i, unsigned j) const\n        {\n            setupLattice(NULL);\n            d_lattice_object->update(i + 1);\n            return arithmetic::convert<long double>(d_lattice_object->getCoeff(i, j));\n        }\n        \n        virtual arithmetic::Real getGSCoefficientR(unsigned i, unsigned j, const arithmetic::RealContext & rc) const\n        {\n            setupLattice(NULL);\n            d_lattice_object->update(i + 1);\n            return arithmetic::convert(d_lattice_object->getCoeff(i, j), rc);\n        }\n        \n        virtual double getGSSqNormD(unsigned i) const\n        {\n            setupLattice(NULL);\n            d_lattice_object->update(i + 1);\n            return arithmetic::convert<double>(d_lattice_object->getNormSq(i));\n        }\n        \n        virtual long double getGSSqNormLD(unsigned i) const\n        {\n            setupLattice(NULL);\n            d_lattice_object->update(i + 1);\n            return arithmetic::convert<long double>(d_lattice_object->getNormSq(i));\n        }\n        \n        virtual arithmetic::Real getGSSqNormR(unsigned i, const arithmetic::RealContext & rc) const\n        {\n            setupLattice(NULL);\n            d_lattice_object->update(i + 1);\n            return arithmetic::convert(d_lattice_object->getNormSq(i), rc);\n        }\n        \n        virtual void modFlip(Transform & transform, unsigned i)\n        {\n            setupLattice(&transform);\n            d_lattice_object->flip(i);\n        }\n        \n        virtual void modSwap(Transform & transform, unsigned i, unsigned j)\n        {\n            setupLattice(&transform);\n            d_lattice_object->swap(i, j);\n        }\n        \n        virtual void modAdd(Transform & transform, unsigned i, unsigned j, const arithmetic::Integer & lambda)\n        {\n            setupLattice(&transform);\n            d_lattice_object->add(i, arithmetic::convert(lambda, d_ic), j);\n        }\n        \n        template<class Enumerator, class CallbackFunction>\n        static void removeZeroVectors(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                                      Lattice<RealTypeContext, IntTypeContext> & lattice)\n        {\n            unsigned r = 0, c = 0;\n            while (r < lattice.dimension())\n            {\n                if (lattice.isRowZero(r))\n                {\n                    lattice.removeZeroVector(r);\n                    ++c;\n                }\n                else\n                    ++r;\n            }\n            if (c > 0)\n                if (workspace.verbose().yieldsOutput(LatticeReduction::VL_Information))\n                    workspace.verbose()(LatticeReduction::VL_Information) << \"Removed \" << c << \" additional zero vectors!\";\n            lattice.compactify();\n        }\n        \n        static void setupPruning(StandardEnumSettings & settings, bool enable, double p = 0.5, bool extreme = false)\n        {\n            if (enable)\n            {\n                if (extreme)\n                    settings.d_pruning = StandardEnumSettings::PM_GNR110_Poly8;\n                else\n                {\n                    settings.d_pruning = StandardEnumSettings::PM_Piecewise;\n                    settings.d_pruning_parameter = p;\n                    // ...\n                }\n            }\n            else\n                settings.d_pruning = StandardEnumSettings::PM_None;\n        }\n        \n        template<class Enumerator>\n        void prepareEnumerator(Enumerator & enumerator, bool LLLonly = false) const\n        {\n            typedef typename Enumerator::PreprocessorStackT::Entry EntryT;\n            EntryT entry, lllentry;\n            entry.d_minalpha.setContext(d_rc);\n            arithmetic::convert(entry.d_minalpha, 0.999, d_rc);\n            lllentry.d_method = EntryT::RM_LLL;\n            lllentry.d_minalpha.setContext(d_rc);\n            lllentry.d_minalpha = entry.d_minalpha;\n            \n            // Add simple LLL\n            enumerator.getPreprocessorStack().begin_add(entry);\n            enumerator.getPreprocessorStack().end_add();\n            if (LLLonly)\n                return;\n            \n            // For higher dimensions, add better preprocessing\n            entry.d_min_dim = 21;\n            entry.d_max_dim = 30;\n            entry.d_method = EntryT::RM_BKZ;\n            entry.d_bkz_mode = LatticeReduction::BKZ_HanrotPujolStehleSVP;\n            entry.d_windowsize = 10;\n            entry.d_force_tours = true;\n            entry.d_bkz_tours = arithmetic::convert<arithmetic::Integer>(100);\n            entry.d_enumboundselectionmethod = EBS_Standard;\n            entry.d_enum_repetitions = 1;\n            setupPruning(entry.d_enumsettings, false); // no pruning\n            enumerator.getPreprocessorStack().begin_add(entry);\n            {\n                enumerator.getPreprocessorStack().begin_add(lllentry);\n                enumerator.getPreprocessorStack().end_add();\n            }\n            enumerator.getPreprocessorStack().end_add();\n            // For higher dimensions, add better preprocessing\n            entry.d_min_dim = 31;\n            entry.d_max_dim = 40;\n            entry.d_method = EntryT::RM_BKZ;\n            entry.d_bkz_mode = LatticeReduction::BKZ_HanrotPujolStehleSVP;\n            entry.d_windowsize = 16;\n            entry.d_force_tours = true;\n            entry.d_bkz_tours = arithmetic::convert<arithmetic::Integer>(400);\n            entry.d_enumboundselectionmethod = EBS_Standard;\n            entry.d_enum_repetitions = 1;\n            setupPruning(entry.d_enumsettings, false); // no pruning\n            enumerator.getPreprocessorStack().begin_add(entry);\n            {\n                enumerator.getPreprocessorStack().begin_add(lllentry);\n                enumerator.getPreprocessorStack().end_add();\n            }\n            enumerator.getPreprocessorStack().end_add();\n            // For higher dimensions, add better preprocessing\n            entry.d_min_dim = 41;\n            entry.d_max_dim = std::numeric_limits<unsigned>::max();\n            entry.d_method = EntryT::RM_BKZ;\n            entry.d_bkz_mode = LatticeReduction::BKZ_HanrotPujolStehleSVP;\n            entry.d_windowsize = 20;\n            entry.d_force_tours = true;\n            entry.d_bkz_tours = arithmetic::convert<arithmetic::Integer>(1200);\n            entry.d_enumboundselectionmethod = EBS_Standard;\n//        entry.d_enumboundselectionmethod = EBS_GaussianHeuristic105;\n            entry.d_enum_repetitions = 1;\n            setupPruning(entry.d_enumsettings, false); // no pruning\n            enumerator.getPreprocessorStack().begin_add(entry);\n            {\n                enumerator.getPreprocessorStack().begin_add(lllentry);\n                enumerator.getPreprocessorStack().end_add();\n                entry.d_min_dim = 10;\n                entry.d_max_dim = std::numeric_limits<unsigned>::max();\n                entry.d_method = EntryT::RM_BKZ;\n                entry.d_bkz_mode = LatticeReduction::BKZ_HanrotPujolStehleSVP;\n                entry.d_windowsize = 10;\n                entry.d_force_tours = true;\n                entry.d_bkz_tours = arithmetic::convert<arithmetic::Integer>(100);\n                entry.d_enumboundselectionmethod = EBS_Standard;\n                entry.d_enum_repetitions = 1;\n                setupPruning(entry.d_enumsettings, false); // no pruning\n                enumerator.getPreprocessorStack().begin_add(entry);\n                {\n                    enumerator.getPreprocessorStack().begin_add(lllentry);\n                    enumerator.getPreprocessorStack().end_add();\n                }\n                enumerator.getPreprocessorStack().end_add();\n            }\n            enumerator.getPreprocessorStack().end_add();\n/*\n            // For higher dimensions, add better preprocessing\n            entry.d_min_dim = 50;\n            entry.d_max_dim = std::numeric_limits<unsigned>::max();\n            entry.d_method = EntryT::RM_BKZ;\n            entry.d_bkz_mode = LatticeReduction::BKZ_HanrotPujolStehleSVP;\n            entry.d_windowsize = 40;\n            entry.d_force_tours = true;\n            entry.d_bkz_tours = arithmetic::convert<arithmetic::Integer>(2400);\n            entry.d_enumboundselectionmethod = EBS_Standard;\n//        entry.d_enumboundselectionmethod = EBS_GaussianHeuristic105;\n            entry.d_enum_repetitions = 1;\n            setupPruning(entry.d_enumsettings, true, 0.1); // pruning\n            enumerator.getPreprocessorStack().begin_add(entry);\n            {\n                enumerator.getPreprocessorStack().begin_add(lllentry);\n                enumerator.getPreprocessorStack().end_add();\n                entry.d_min_dim = 10;\n                entry.d_max_dim = std::numeric_limits<unsigned>::max();\n                entry.d_method = EntryT::RM_BKZ;\n                entry.d_bkz_mode = LatticeReduction::BKZ_HanrotPujolStehleSVP;\n                entry.d_windowsize = 16;\n                entry.d_force_tours = true;\n                entry.d_bkz_tours = arithmetic::convert<arithmetic::Integer>(250);\n                entry.d_enumboundselectionmethod = EBS_Standard;\n                entry.d_enum_repetitions = 1;\n                setupPruning(entry.d_enumsettings, false); // no pruning\n                enumerator.getPreprocessorStack().begin_add(entry);\n                {\n                    enumerator.getPreprocessorStack().begin_add(lllentry);\n                    enumerator.getPreprocessorStack().end_add();\n                }\n                enumerator.getPreprocessorStack().end_add();\n            }\n            enumerator.getPreprocessorStack().end_add();\n*/\n        }\n        \n        /////////////// PROJECTED SORTING ///////////////\n        \n        void sortProjected(unsigned & begin, unsigned & end, TransformNotifier<IntTypeContext> * T)\n        {\n            freeLattice();\n            try\n            {\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end);\n                lattice.addNotifier(T);\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, EmptyCallback<RealTypeContext, IntTypeContext>(), 0, d_max_cores, NULL);\n                // Implement a simple insertion sort\n                typename RealTypeContext::Real len(d_rc), minlen(d_rc);\n                for (unsigned i = begin; i < end; ++i)\n                {\n                    lattice.update(end + 1);\n                    minlen = lattice.getNormSq(i);\n                    unsigned mini = i;\n                    for (unsigned j = i + 1; j <= end; ++j)\n                    {\n                        lattice.computeProjectionLengthBV(len, i, j);\n                        if (len < minlen)\n                        {\n                            mini = j;\n                            minlen = len;\n                        }\n                    }\n                    for (unsigned j = mini; j > i; --j)\n                        lattice.swap(j, j - 1);\n                }\n                removeZeroVectors(workspace, lattice);\n                begin = lattice.range().begin();\n                end = lattice.range().end();\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        /////////////// SIZE REDUCTION ///////////////\n        \n        void sizereduction(unsigned & begin, unsigned & end, TransformNotifier<IntTypeContext> * T)\n        {\n            freeLattice();\n            try\n            {\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end);\n                lattice.addNotifier(T);\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, EmptyCallback<RealTypeContext, IntTypeContext>(), 0, d_max_cores, NULL);\n                workspace.sizereduction(lattice);\n                removeZeroVectors(workspace, lattice);\n                begin = lattice.range().begin();\n                end = lattice.range().end();\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        template<typename CallbackObject, typename LatticeObject>\n        void setupCallback_impl(CallbackObject & cb,\n                                LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                                LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                                unsigned & begin, LatticeObject & lattice, arithmetic::IntegerContext *)\n        {\n            if ((cf != NULL) || (cf2 != NULL))\n            {\n                if (cf != NULL)\n                    cb.setCallback(cf, cf_int, begin);\n                else\n                    cb.setCallback(boost::bind(CallbackAdaptor, _1, cf2), cf_int, begin);\n            }\n            if ((mcf != NULL) || (mcf2 != NULL))\n            {\n                if (mcf != NULL)\n                    cb.setMinCallback(lattice, mcf);\n                else\n                    cb.setMinCallback(lattice, boost::bind(MinCallbackAdaptor, _1, _2, _3, mcf2));\n            }\n        }\n        \n        template<typename CallbackObject, typename LatticeObject>\n        void setupCallback_impl(CallbackObject & cb,\n                                LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                                LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                                unsigned & begin, LatticeObject & lattice, arithmetic::NIntContext<long int> *)\n        {\n            if ((cf != NULL) || (cf2 != NULL))\n            {\n                if (cf2 != NULL)\n                    cb.setCallback(cf2, cf_int, begin);\n                else\n                    cb.setCallback(boost::bind(CallbackAdaptor_LI, _1, cf), cf_int, begin);\n            }\n            if ((mcf != NULL) || (mcf2 != NULL))\n            {\n                if (mcf2 != NULL)\n                    cb.setMinCallback(lattice, mcf2);\n                else\n                    cb.setMinCallback(lattice, boost::bind(MinCallbackAdaptor_LI, _1, _2, _3, mcf));\n            }\n        }\n        \n        template<typename CallbackObject, typename LatticeObject>\n        void setupCallback(CallbackObject & cb,\n                           LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                           LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                           MaxBitsCallbackFunction mbcf,\n                           unsigned & begin, LatticeObject & lattice)\n        {\n            setupCallback_impl(cb, cf, cf2, cf_int, mcf, mcf2, begin, lattice, static_cast<IntTypeContext*>(NULL));\n            if (mbcf != NULL)\n                cb.setMaxBitsCallback(lattice, mbcf);\n        }\n        \n        /////////////// LLL ///////////////\n        \n        template<class Enumerator, class CallbackFunction, class Reorderer>\n        void lll_internal(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                          Lattice<RealTypeContext, IntTypeContext> & lattice, LatticeReduction::LLLMode mode,\n                          bool anneal, LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::LLL_AnnealFunction af, Reorderer & reorder)\n        {\n            if (anneal)\n            {\n                lattice.range().dupRange();\n                typedef typename Enumerator::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = EntryT::RM_None;\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().getPreprocessorStack().begin_preprocess();\n                switch (mode)\n                {\n                case LatticeReduction::LLL_Classic:\n                {\n                    if (af == NULL)\n                        workspace.partialLLL_Anneal(lattice, acf, &DefaultLLLAnnealFunction<IntTypeContext>, reorder);\n                    else\n                        workspace.partialLLL_Anneal(lattice, acf, LLLAnnealWrapper<IntTypeContext>(af, &d_gsi), reorder);\n                }\n                break;\n                case LatticeReduction::LLL_Unprojected:\n                case LatticeReduction::LLL_Siegel:\n                    lattice.range().popRange();\n                    workspace.verbose()(LatticeReduction::VL_Warning) << \"No annealing implemented for this LLL mode!\";\n                    throw feature_not_implemented();\n                }\n                workspace.enumerator().getPreprocessorStack().end_preprocess();\n            }\n            else\n            {\n                typedef typename Enumerator::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = EntryT::RM_LLL;\n                entry.d_lll_mode = mode;\n                entry.d_enumalg = d_svp;\n                setupPruning(entry.d_enumsettings, false); // no pruning\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().preprocess(workspace, lattice, reorder);\n            }\n            return;\n        }\n        \n        template<class Enumerator, class CallbackFunction>\n        void lll_internal(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                          Lattice<RealTypeContext, IntTypeContext> & lattice, LatticeReduction::LLLMode mode,\n                          bool anneal, LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::LLL_AnnealFunction af,\n                          LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode, LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            switch (di)\n            {\n            case LatticeReduction::DI_None:\n            {\n                NoReorder<RealTypeContext, IntTypeContext> r;\n                lll_internal(workspace, lattice, mode, anneal, acf, af, r);\n                break;\n            }\n            case LatticeReduction::DI_Classic:\n            {\n                DoClassicDeepInsertion<RealTypeContext, IntTypeContext> r(di_mode, di_choice, di_bs, d_stats);\n                lll_internal(workspace, lattice, mode, anneal, acf, af, r);\n                break;\n            }\n            case LatticeReduction::DI_MinimizePotential1:\n            {\n                DoMinPotDeepInsertion<RealTypeContext, IntTypeContext> r(d_intlattice.matrix().rows(), di_mode, di_choice, di_bs, d_stats, true);\n                lll_internal(workspace, lattice, mode, anneal, acf, af, r);\n                break;\n            }\n            case LatticeReduction::DI_MinimizePotential2:\n            {\n                DoMinPotDeepInsertion<RealTypeContext, IntTypeContext> r(d_intlattice.matrix().rows(), di_mode, di_choice, di_bs, d_stats, false);\n                lll_internal(workspace, lattice, mode, anneal, acf, af, r);\n                break;\n            }\n            }\n        }\n        \n        void lll(unsigned & begin, unsigned & end, TransformNotifier<IntTypeContext> * T, double alpha, LatticeReduction::LLLMode mode,\n                 LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                 LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2, MaxBitsCallbackFunction mbcf,\n                 bool anneal, LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::LLL_AnnealFunction af,\n                 LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode, LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            freeLattice();\n            try\n            {\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, Callback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, Callback<RealTypeContext, IntTypeContext>(end - begin + 1), 0, d_max_cores, NULL, NULL);\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end);\n                lattice.addNotifier(T);\n                setupCallback(workspace.getCallbackObject(), cf, cf2, cf_int, mcf, mcf2, mbcf, begin, lattice);\n                d_gs->adjustAlpha(alpha);\n                \n                lll_internal(workspace, lattice, mode, anneal, acf, af, di, di_mode, di_choice, di_bs);\n                removeZeroVectors(workspace, lattice);\n                \n                begin = lattice.range().begin();\n                end = lattice.range().end();\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        /////////////// BKZ ///////////////\n        \n        template<class Enumerator, class CallbackFunction, class Reorderer>\n        inline void bkz_internal(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                                 Lattice<RealTypeContext, IntTypeContext> & lattice,\n                                 unsigned blocksize, LatticeReduction::BKZMode mode,\n                                 bool anneal, LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::BKZ_AnnealFunction af,\n                                 Reorderer & reorder)\n        {\n            if (anneal)\n            {\n                lattice.range().dupRange();\n                typedef typename Enumerator::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = EntryT::RM_None;\n                entry.d_enumalg = d_svp;\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                prepareEnumerator(workspace.enumerator());\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().getPreprocessorStack().begin_preprocess();\n                switch (mode)\n                {\n                case LatticeReduction::BKZ_SchnorrEuchner:\n                {\n                    if (af == NULL)\n                        workspace.partialBKZ_Anneal(lattice, blocksize, acf, &DefaultBKZAnnealFunction<IntTypeContext>, reorder, false);\n                    else\n                        workspace.partialBKZ_Anneal(lattice, blocksize, acf, BKZAnnealWrapper<IntTypeContext>(af, &d_gsi), reorder, false);\n                }\n                break;\n                case LatticeReduction::BKZ_Simplified:\n                {\n                    if (af == NULL)\n                        workspace.partialBKZ_Anneal(lattice, blocksize, acf, &DefaultBKZAnnealFunction<IntTypeContext>, reorder, true);\n                    else\n                        workspace.partialBKZ_Anneal(lattice, blocksize, acf, BKZAnnealWrapper<IntTypeContext>(af, &d_gsi), reorder, true);\n                }\n                break;\n                case LatticeReduction::BKZ_HanrotPujolStehleSVP:\n                case LatticeReduction::BKZ_HanrotPujolStehleHKZ:\n                case LatticeReduction::BKZ_SemiBlock2k: // Schnorr's Semi-block-2k-reduction (blocksize is made even by rounding up)\n                case LatticeReduction::BKZ_PrimalDual: // Koy's primal-dual BKZ\n                case LatticeReduction::BKZ_SlideReduction: // Gama-Nguyen Slide Reduction (Gama, Nguyen: \"Finding Short Lattice Vectors within Mordell's Inequality\")\n                case LatticeReduction::BKZ_ImprovedSlideReduction: // Schnorr's improved and accelerated Slide Reduction\n                case LatticeReduction::BKZ_ImprovedSlideReduction2: // Schnorr's improved and accelerated Slide Reduction (using a larger DSVP and a single SVP)\n                case LatticeReduction::BKZ_ImprovedSlideReduction3: // Schnorr's improved and accelerated Slide Reduction (using a single larger SVP and a DSVP)\n                case LatticeReduction::BKZ_SamplingReduction:\n                case LatticeReduction::BKZ_Experimental:\n                    lattice.range().popRange();\n                    workspace.verbose()(LatticeReduction::VL_Warning) << \"No annealing implemented for this BKZ mode!\";\n                    throw feature_not_implemented();\n                }\n                workspace.enumerator().getPreprocessorStack().end_preprocess();\n            }\n            else\n            {\n                typedef typename Enumerator::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = EntryT::RM_BKZ;\n                entry.d_bkz_mode = mode;\n                entry.d_windowsize = blocksize;\n                entry.d_enumalg = d_svp;\n                setupPruning(entry.d_enumsettings, false); // no pruning\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                prepareEnumerator(workspace.enumerator());\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().preprocess(workspace, lattice, reorder);\n            }\n            return;\n        }\n        \n        template<class Enumerator, class CallbackFunction>\n        inline void bkz_internal(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                                 Lattice<RealTypeContext, IntTypeContext> & lattice,\n                                 unsigned blocksize, LatticeReduction::BKZMode mode,\n                                 bool anneal, LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::BKZ_AnnealFunction af,\n                                 LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode, LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            switch (di)\n            {\n            case LatticeReduction::DI_None:\n            {\n                NoReorder<RealTypeContext, IntTypeContext> r;\n                bkz_internal(workspace, lattice, blocksize, mode, anneal, acf, af, r);\n                break;\n            }\n            case LatticeReduction::DI_Classic:\n            {\n                DoClassicDeepInsertion<RealTypeContext, IntTypeContext> r(di_mode, di_choice, di_bs, d_stats);\n                bkz_internal(workspace, lattice, blocksize, mode, anneal, acf, af, r);\n                break;\n            }\n            case LatticeReduction::DI_MinimizePotential1:\n            {\n                DoMinPotDeepInsertion<RealTypeContext, IntTypeContext> r(lattice.dimension(), di_mode, di_choice, di_bs, d_stats, true);\n                bkz_internal(workspace, lattice, blocksize, mode, anneal, acf, af, r);\n                break;\n            }\n            case LatticeReduction::DI_MinimizePotential2:\n            {\n                DoMinPotDeepInsertion<RealTypeContext, IntTypeContext> r(lattice.dimension(), di_mode, di_choice, di_bs, d_stats, false);\n                bkz_internal(workspace, lattice, blocksize, mode, anneal, acf, af, r);\n                break;\n            }\n            }\n        }\n        \n        void bkz(unsigned & begin, unsigned & end, TransformNotifier<IntTypeContext> * T, double alpha, unsigned blocksize,\n                 LatticeReduction::BKZMode mode, LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2,\n                 double cf_int, LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                 MaxBitsCallbackFunction mbcf, LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2,\n                 bool anneal, LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::BKZ_AnnealFunction af,\n                 LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode, LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            freeLattice();\n            try\n            {\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, Callback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, Callback<RealTypeContext, IntTypeContext>(end - begin + 1), blocksize, d_max_cores, ecf, ecf2);\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end);\n                lattice.addNotifier(T);\n                setupCallback(workspace.getCallbackObject(), cf, cf2, cf_int, mcf, mcf2, mbcf, begin, lattice);\n                d_gs->adjustAlpha(alpha);\n                \n                bkz_internal(workspace, lattice, blocksize, mode, anneal, acf, af, di, di_mode, di_choice, di_bs);\n                removeZeroVectors(workspace, lattice);\n                \n                begin = lattice.range().begin();\n                end = lattice.range().end();\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        /////////////// HKZ ///////////////\n        \n        void hkz(unsigned & begin, unsigned & end, TransformNotifier<IntTypeContext> * T, bool dual,\n                 LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                 LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                 MaxBitsCallbackFunction mbcf,\n                 LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2)\n        {\n            freeLattice();\n            try\n            {\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, Callback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, Callback<RealTypeContext, IntTypeContext>(end - begin + 1), end - begin + 1, d_max_cores, ecf, ecf2);\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end);\n                lattice.addNotifier(T);\n                setupCallback(workspace.getCallbackObject(), cf, cf2, cf_int, mcf, mcf2, mbcf, begin, lattice);\n                d_gs->adjustAlpha(0.999);\n                \n                typedef typename Enumerator<RealTypeContext, IntTypeContext>::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = dual ? EntryT::RM_HKZDual : EntryT::RM_HKZ;\n                entry.d_enumalg = d_svp;\n                setupPruning(entry.d_enumsettings, false); // no pruning\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                prepareEnumerator(workspace.enumerator());\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().preprocess(workspace, lattice);\n                removeZeroVectors(workspace, lattice);\n                \n                begin = lattice.range().begin();\n                end = lattice.range().end();\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        /////////////// SVP ///////////////\n        \n        inline void svp(unsigned & begin, unsigned & end, TransformNotifier<IntTypeContext> * T, bool make_basis, bool extreme, bool dual,\n                        LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                        LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                        MaxBitsCallbackFunction mbcf,\n                        LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2)\n        {\n            freeLattice();\n            try\n            {\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, Callback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, Callback<RealTypeContext, IntTypeContext>(end - begin + 1), end - begin + 1, d_max_cores, ecf, ecf2);\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end);\n                lattice.addNotifier(T);\n                setupCallback(workspace.getCallbackObject(), cf, cf2, cf_int, mcf, mcf2, mbcf, begin, lattice);\n                d_gs->adjustAlpha(0.999);\n                \n                lattice.range().dupRange();\n                typedef typename Enumerator<RealTypeContext, IntTypeContext>::PreprocessorStackT::Entry EntryT;\n                EntryT entry, entry2;\n                entry.d_method = dual ? EntryT::RM_SVPDual : EntryT::RM_SVP;\n                entry.d_enumalg = d_svp;\n                setOne(entry.d_minalpha);\n                if (extreme)\n                {\n                    entry.d_enumboundselectionmethod = EBS_GaussianHeuristic105;\n                    entry.d_enum_repetitions = 256;\n                    setupPruning(entry.d_enumsettings, true, 0, true); // extreme pruning\n                    workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                    prepareEnumerator(workspace.enumerator(), true); // add LLL step\n                    entry2.d_method = EntryT::RM_BKZ;\n                    entry2.d_bkz_mode = LatticeReduction::BKZ_HanrotPujolStehleSVP;\n                    entry2.d_windowsize = (end - begin + 1) / 5 + 10; // 110 => 30, 120 => 32\n                    workspace.enumerator().getPreprocessorStack().begin_add(entry2);\n                    prepareEnumerator(workspace.enumerator());\n                    workspace.enumerator().getPreprocessorStack().end_add();\n                    workspace.enumerator().getPreprocessorStack().end_add();\n                }\n                else\n                {\n                    setupPruning(entry.d_enumsettings, false); // no pruning\n                    workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                    prepareEnumerator(workspace.enumerator());\n                    workspace.enumerator().getPreprocessorStack().end_add();\n                }\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().preprocess(workspace, lattice);\n                removeZeroVectors(workspace, lattice);\n                \n                begin = lattice.range().begin();\n                end = lattice.range().end();\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        /////////////// VERIFICATION ///////////////\n        \n        virtual bool isSizeReduced(unsigned begin, unsigned end) const\n        {\n            try\n            {\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end, true);\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, EmptyCallback<RealTypeContext, IntTypeContext>(), 0, d_max_cores, NULL);\n                return isSR(workspace, lattice);\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n                return false;\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        template<class Enumerator, class CallbackFunction>\n        bool isDI_Classic(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                          Lattice<RealTypeContext, IntTypeContext> & lattice,\n                          LatticeReduction::DIChoice di_choice, unsigned di_bs) const\n        {\n            lattice.update(d_intlattice.matrix().rows());\n            typename RealTypeContext::Real res(lattice.rc());\n            \n            for (unsigned j = lattice.range().begin() + 1; j <= lattice.range().end(); ++j)\n            {\n                unsigned i = lattice.range().begin();\n                for (; i < j; ++i)\n                {\n                    if (i >= lattice.range().begin() + di_bs)\n                    {\n                        if (di_choice == LatticeReduction::DIC_First)\n                        {\n                            i = j;\n                            break;\n                        }\n                        if ((di_choice != LatticeReduction::DIC_All) && (i + di_bs < j))\n                            i = j - di_bs;\n                    }\n                    \n                    lattice.computeProjectionLengthBV(res, i, j);\n                    if (res < lattice.getLLLalpha() * lattice.getNormSq(i))\n                    {\n                        if (workspace.verbose().yieldsOutput(LatticeReduction::VL_Information))\n                            workspace.verbose()(LatticeReduction::VL_Information) << \"Deep Insertion condition failed for (\" << i << \", \" << j << \")\\n\";\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n        \n        template<class Enumerator, class CallbackFunction>\n        bool isDI_MinPot(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                         Lattice<RealTypeContext, IntTypeContext> & lattice,\n                         LatticeReduction::DIChoice di_choice, unsigned di_bs, int mode = 0) const\n        {\n            lattice.update(d_intlattice.matrix().rows());\n            typedef typename arithmetic::HugeExponent<RealTypeContext>::Type Huge;\n            typename RealTypeContext::Real t(lattice.rc());\n            Huge minpot(lattice.rc()), pot(lattice.rc());\n            for (unsigned j = lattice.range().begin() + 1; j <= lattice.range().end(); ++j)\n            {\n                unsigned i = j - 1;\n                minpot = Huge(lattice.getLLLalpha());\n                setOne(pot);\n                \n                unsigned blockbegin = lattice.range().begin();\n                if ((di_choice == LatticeReduction::DIC_Block) && (blockbegin + di_bs < i))\n                    blockbegin = i - di_bs;\n                if (blockbegin == i)\n                    continue;\n                \n                for (; i >= blockbegin; --i)\n                {\n                    // Update potential\n                    pot *= square(Huge(lattice.getNormSq(i - 1)));\n                    lattice.computeProjectionLengthBV(t, i - 1, i);\n                    pot /= square(Huge(t));\n                    \n                    // Check whether we want to actually compare the potential for this position\n                    bool doComp = true;\n                    if (i > lattice.range().begin() + di_bs)\n                    {\n                        if (di_choice == LatticeReduction::DIC_First)\n                            doComp = false;\n                        if ((di_choice != LatticeReduction::DIC_All) && (i + di_bs <= j))\n                            doComp = false;\n                    }\n                    else\n                        if ((di_choice == LatticeReduction::DIC_Block) && (i + di_bs <= j))\n                            doComp = false;\n                    \n                    // Compare potential\n                    if (doComp)\n                        if (pot < minpot)\n                        {\n                            if (workspace.verbose().yieldsOutput(LatticeReduction::VL_Information))\n                                workspace.verbose()(LatticeReduction::VL_Information) << \"MinPot Deep Insertion condition failed for (\" << i << \", \" << j << \")\\n\";\n                            return false;\n                        }\n                }\n            }\n            return true;\n        }\n        \n        template<class Enumerator, class CallbackFunction>\n        bool isDI(Workspace<RealTypeContext, IntTypeContext, Enumerator, CallbackFunction> & workspace,\n                  Lattice<RealTypeContext, IntTypeContext> & lattice,\n                  LatticeReduction::DIMethod di, LatticeReduction::DIChoice di_choice, unsigned di_bs) const\n        {\n            switch (di)\n            {\n            case LatticeReduction::DI_None: return true;\n            case LatticeReduction::DI_Classic: return isDI_Classic(workspace, lattice, di_choice, di_bs);\n            case LatticeReduction::DI_MinimizePotential1: return isDI_MinPot(workspace, lattice, di_choice, di_bs, 0);\n            case LatticeReduction::DI_MinimizePotential2: return isDI_MinPot(workspace, lattice, di_choice, di_bs, 1);\n            }\n            return true; // unnecessary, but g++ complains if this is missing...\n        }\n        \n        virtual bool isLLLBasis(unsigned begin, unsigned end, double alpha, LatticeReduction::LLLMode mode,\n                                LatticeReduction::DIMethod di, LatticeReduction::DIChoice di_choice, unsigned di_bs) const\n        {\n            try\n            {\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end, true);\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, EmptyCallback<RealTypeContext, IntTypeContext>(), 0, d_max_cores, NULL);\n                d_gs->adjustAlpha(alpha);\n                if (!(isSR(workspace, lattice) && isDI(workspace, lattice, di, di_choice, di_bs)))\n                    return false;\n                switch (mode)\n                {\n                case LatticeReduction::LLL_Classic:\n                    return isLLL(workspace, lattice,\n                                 Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >::LovaszCondition);\n                case LatticeReduction::LLL_Unprojected:\n                    return isLLL(workspace, lattice,\n                                 Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >::UnprojectedLovaszCondition);\n                case LatticeReduction::LLL_Siegel:\n                    return isLLL(workspace, lattice,\n                                 Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >::SiegelCondition);\n                }\n                return false;\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n                return false;\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        virtual bool isBKZBasis(unsigned begin, unsigned end, double alpha, unsigned blocksize, LatticeReduction::BKZMode mode,\n                                LatticeReduction::DIMethod di, LatticeReduction::DIChoice di_choice, unsigned di_bs) const\n        {\n            try\n            {\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end, true);\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, EmptyCallback<RealTypeContext, IntTypeContext>(), blocksize, d_max_cores);\n                d_gs->adjustAlpha(alpha);\n                typedef typename Enumerator<RealTypeContext, IntTypeContext>::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = EntryT::RM_None;\n                entry.d_enumalg = d_svp;\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                prepareEnumerator(workspace.enumerator());\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().getPreprocessorStack().begin_preprocess();\n                bool result = true;\n                switch (mode)\n                {\n                case LatticeReduction::BKZ_SchnorrEuchner:\n                case LatticeReduction::BKZ_Simplified:\n                case LatticeReduction::BKZ_SamplingReduction:\n                    result = isSR(workspace, lattice) && isDI(workspace, lattice, di, di_choice, di_bs) && isBKZ(workspace, lattice, blocksize);\n                    break;\n                case LatticeReduction::BKZ_HanrotPujolStehleSVP:\n                case LatticeReduction::BKZ_HanrotPujolStehleHKZ:\n                case LatticeReduction::BKZ_Experimental:\n                    // Don't know how to check this!!! ??? ...\n                    result = isSR(workspace, lattice) && isDI(workspace, lattice, di, di_choice, di_bs)\n                        && isLLL(workspace, lattice,\n                                 Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >::LovaszCondition);\n                    break;\n                case LatticeReduction::BKZ_SemiBlock2k: // Schnorr's Semi-block-2k-reduction (blocksize is made even by rounding up)\n                    result = isSR(workspace, lattice) && isDI(workspace, lattice, di, di_choice, di_bs) && isBKZ_SemiBlock2k(workspace, lattice, blocksize);\n                    break;\n                case LatticeReduction::BKZ_PrimalDual: // Koy's primal-dual BKZ\n                    result = isSR(workspace, lattice) && isDI(workspace, lattice, di, di_choice, di_bs) && isBKZ_PrimalDual(workspace, lattice, blocksize);\n                    break;\n                case LatticeReduction::BKZ_SlideReduction: // Gama-Nguyen Slide Reduction (Gama, Nguyen: \"Finding Short Lattice Vectors within Mordell's Inequality\")\n                    result = isSR(workspace, lattice) && isDI(workspace, lattice, di, di_choice, di_bs) && isBKZ_Slide(workspace, lattice, blocksize);\n                    break;\n                case LatticeReduction::BKZ_ImprovedSlideReduction: // Schnorr's improved and accelerated Slide Reduction\n                case LatticeReduction::BKZ_ImprovedSlideReduction2: // Schnorr's improved and accelerated Slide Reduction (using a larger DSVP and a single SVP)\n                case LatticeReduction::BKZ_ImprovedSlideReduction3: // Schnorr's improved and accelerated Slide Reduction (using a single larger SVP and a DSVP)\n                    result = isSR(workspace, lattice) && isDI(workspace, lattice, di, di_choice, di_bs) && isBKZ_ImprovedSlide(workspace, lattice, blocksize);\n                    break;\n                }\n                workspace.enumerator().getPreprocessorStack().end_preprocess();\n                // Default:\n                return result;\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n                return false;\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        virtual bool isHKZBasis(unsigned begin, unsigned end, bool dual) const\n        {\n            try\n            {\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end, true);\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, EmptyCallback<RealTypeContext, IntTypeContext>(), lattice.range().dimension(), d_max_cores);\n                d_gs->adjustAlpha(1);\n                if (!isSR(workspace, lattice))\n                    return false;\n                typedef typename Enumerator<RealTypeContext, IntTypeContext>::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = EntryT::RM_None;\n                entry.d_enumalg = d_svp;\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                prepareEnumerator(workspace.enumerator());\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().getPreprocessorStack().begin_preprocess();\n                bool result = isHKZ(workspace, lattice, dual);\n                workspace.enumerator().getPreprocessorStack().end_preprocess();\n                return result;\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n                return false;\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        virtual bool isSVPBasis(unsigned begin, unsigned end, bool dual) const\n        {\n            try\n            {\n                Lattice<RealTypeContext, IntTypeContext> lattice(d_gs.get(), d_rc, d_ic, d_stats, begin, end, true);\n                Workspace<RealTypeContext, IntTypeContext, Enumerator<RealTypeContext, IntTypeContext>, EmptyCallback<RealTypeContext, IntTypeContext> >\n                    workspace(d_verbose, EmptyCallback<RealTypeContext, IntTypeContext>(), lattice.range().dimension(), d_max_cores);\n                d_gs->adjustAlpha(1);\n                typedef typename Enumerator<RealTypeContext, IntTypeContext>::PreprocessorStackT::Entry EntryT;\n                EntryT entry;\n                entry.d_method = EntryT::RM_None;\n                entry.d_enumalg = d_svp;\n                workspace.enumerator().getPreprocessorStack().begin_add(entry);\n                prepareEnumerator(workspace.enumerator());\n                workspace.enumerator().getPreprocessorStack().end_add();\n                workspace.enumerator().getPreprocessorStack().finalize_adding();\n                workspace.enumerator().getPreprocessorStack().begin_preprocess();\n                bool result = isSVP(workspace, lattice, dual);\n                workspace.enumerator().getPreprocessorStack().end_preprocess();\n                return result;\n            }\n            catch (std::exception & e)\n            {\n                handle_exception(&e);\n                return false;\n            }\n            catch (...)\n            {\n                handle_unknown_exception();\n                throw;\n            }\n        }\n        \n        /////////////// WRAPPERS ///////////////\n        \n        virtual void sortProjected(unsigned & begin, unsigned & end, Transform & transform)\n        {\n            sortProjected(begin, end, transform.createTransformObject<IntTypeContext>(d_ic));\n            d_intlattice.update_original();\n            transform.releaseTransformObject();\n        }\n        \n        virtual void sizereduction(unsigned & begin, unsigned & end, Transform & transform)\n        {\n            sizereduction(begin, end, transform.createTransformObject<IntTypeContext>(d_ic));\n            d_intlattice.update_original();\n            transform.releaseTransformObject();\n        }\n        \n        virtual void lll(unsigned & begin, unsigned & end, Transform & transform, double alpha, LatticeReduction::LLLMode mode,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                         MaxBitsCallbackFunction mbcf, bool anneal, LatticeReduction::AnnealCallbackFunction acf,\n                         LatticeReduction::LLL_AnnealFunction af, LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode,\n                         LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            lll(begin, end, transform.createTransformObject<IntTypeContext>(d_ic), alpha, mode, cf, cf2, cf_int,\n                mcf, mcf2, mbcf, anneal, acf, af, di, di_mode, di_choice, di_bs);\n            d_intlattice.update_original();\n            transform.releaseTransformObject();\n        }\n        \n        virtual void bkz(unsigned & begin, unsigned & end, Transform & transform, double alpha, unsigned blocksize, LatticeReduction::BKZMode mode,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2, MaxBitsCallbackFunction mbcf,\n                         LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2,\n                         bool anneal, LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::BKZ_AnnealFunction af,\n                         LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode, LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            bkz(begin, end, transform.createTransformObject<IntTypeContext>(d_ic), alpha, blocksize, mode, cf, cf2, cf_int,\n                mcf, mcf2, mbcf, ecf, ecf2, anneal, acf, af, di, di_mode, di_choice, di_bs);\n            d_intlattice.update_original();\n            transform.releaseTransformObject();\n        }\n        \n        virtual void hkz(unsigned & begin, unsigned & end, Transform & transform, bool dual,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                         MaxBitsCallbackFunction mbcf,\n                         LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2)\n        {\n            hkz(begin, end, transform.createTransformObject<IntTypeContext>(d_ic), dual,\n                cf, cf2, cf_int, mcf, mcf2, mbcf, ecf, ecf2);\n            d_intlattice.update_original();\n            transform.releaseTransformObject();\n        }\n        \n        virtual void svp(unsigned & begin, unsigned & end, Transform & transform, bool make_basis, bool extreme, bool dual,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                         MaxBitsCallbackFunction mbcf,\n                         LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2)\n        {\n            svp(begin, end, transform.createTransformObject<IntTypeContext>(d_ic), make_basis, extreme, dual,\n                cf, cf2, cf_int, mcf, mcf2, mbcf, ecf, ecf2);\n            d_intlattice.update_original();\n            transform.releaseTransformObject();\n        }\n    };\n    \n    template<class RealTypeContext, class IntTypeContext>\n    LRIInterface * CreateLRIInterfaceWithContexts(LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf,\n                                                  linalg::math_matrix<arithmetic::Integer> & lattice, LatticeReduction::GramSchmidt gs, bool gsr,\n                                                  LatticeReduction::SVPMode svp, unsigned max_cores,\n                                                  const RealTypeContext & rc, const IntTypeContext & ic)\n    {\n        return new LRIImplementation<RealTypeContext, IntTypeContext>(vol, vf, lattice, gs, gsr, svp, max_cores, rc, ic);\n    }\n}\n\n#endif\n", "meta": {"hexsha": "df81e8b6e883e3b516640c41c037d786bd659a84", "size": 68678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plll/src/lattices/lll2-generic.cpp", "max_stars_repo_name": "KudrinMatvey/myfplll", "max_stars_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plll/src/lattices/lll2-generic.cpp", "max_issues_repo_name": "KudrinMatvey/myfplll", "max_issues_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plll/src/lattices/lll2-generic.cpp", "max_forks_repo_name": "KudrinMatvey/myfplll", "max_forks_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4985294118, "max_line_length": 199, "alphanum_fraction": 0.5667462652, "num_tokens": 14208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.02161533394439043, "lm_q1q2_score": 0.008804647468696762}}
{"text": "#include \"FOPTICS.h\"\n#include \"gaboom.h\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\nboost::random::mt19937 gen;\n\nstruct RNG \n{\n    int operator() (int n) {\n        return std::rand() / (1.0 + RAND_MAX) * n;\n    }\n};\n\nbool definitelyGreaterThan(float a, float b, float epsilon)\n{\n    return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\nbool definitelyLessThan(float a, float b, float epsilon)\n{\n    return (b - a) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);\n}\n\n//Normalizes any number to an arbitrary range \n//by assuming the range wraps around when going below min or above max \nfloat normalize_IC_interval(const genlim* gene_lim, float value)\n{\n\tfloat start = gene_lim->min;\n\tfloat end = gene_lim->max;\n\tfloat width = end - start;\n\tfloat offsetValue = value - start; // value relative to 0\n\treturn ( offsetValue - ( std::floor( offsetValue / width) * width) ) + start;\n}\n\nClusterOrdering::ClusterOrdering(int id, int predID, float reach) : objectID(id), predecessorID(predID), reachability(reach)\n{}\n\ninline bool const ClusterOrdering::operator==(const ClusterOrdering& rhs)\n{\n\tif(*this == rhs)\n\t\treturn true;\n\tif(typeid(rhs) != typeid(ClusterOrdering))\n\t\treturn false;\n\n\treturn ( this->objectID == rhs.objectID );\n}\n\ninline bool const ClusterOrdering::operator< (const ClusterOrdering& rhs)\n{\n\tif(this->reachability > rhs.reachability || isUndefinedDist(this->reachability))\n\t\t\treturn false;\n\t\telse if(this->reachability < rhs.reachability)\n\t\t\treturn true;\n\t\tif(this->objectID > rhs.objectID)\n\t\t\treturn true;\n\t\telse if(this->objectID < rhs.objectID)\n\t\t\treturn false;\n\t\t// if nothing else is true, return 0\n\t\treturn 0;\n}\n\ninline bool const ClusterOrdering::operator> (const ClusterOrdering& rhs)\n{\n\tif(this->reachability > rhs.reachability || isUndefinedDist(this->reachability))\n\t\treturn true;\n\telse if(this->reachability < rhs.reachability)\n\t\t\treturn false;\n\tif(this->objectID > rhs.objectID)\n\t\treturn false;\n\telse if(this->objectID < rhs.objectID)\n\t\treturn true;\n\t\t// if nothing else is true, return 0\n\t\treturn 0;\n}\n/*****************************************\\\n\t\t\t\tFastOPTICS\n\\*****************************************/\n// Constructor and Algorithm main+only call\n// int FastOPTICS::iOrder;\nFastOPTICS::FastOPTICS(FA_Global* FA, GB_Global* GB, VC_Global* VC, chromosome* chrom, genlim* gen_lim, atom* atoms, resid* residue, gridpoint* cleftgrid, int nChrom, BindingPopulation& Population, int nPoints)\n{\t\n// Declarations\n\t///////////////////////////////////////////////////////\n\t// Entropy\n\tthis->Population = &Population;\n\t// FlexAID\n    this->FA = FA;\n    this->GB = GB;\n    this->VC = VC;\n    this->cleftgrid = cleftgrid;\n    this->atoms = atoms;\n    this->residue = residue;\n    this->chroms = chrom;\n    this->gene_lim = gen_lim;\n\tthis->N = nChrom;\n    \n\t// FastOPTICS\n    this->nDimensions = this->FA->num_het_atm*3;\t// use with Vectorized_Cartesian_Coordinates()\n    // this->nDimensions = this->FA->npar + 2; \t// use with Vectorized_Chromosome()\n    \n    this->minPoints = nPoints;\n    \n    // FastOPTICS::iOrder = 0;\n    this->iOrder = 0;\n\tthis->order.reserve(this->N);\n\tthis->reachDist.reserve(this->N);\n\tthis->processed.reserve(this->N);\n\tthis->inverseDensities.reserve(this->N);\n\tthis->points.reserve(this->N);\n\tthis->neighbors.reserve(this->N);\n    \n\tfor(int i = 0; i < this->N; ++i)\n\t{\n\t\t// need to transform the chromosomes into vector f\n\t\t// std::vector<float> vChrom(this->FastOPTICS::Vectorized_Chromosome(&chrom[i])); // Copy constructor\n\t\tstd::vector<float> vChrom( this->Vectorized_Cartesian_Coordinates(i) ); // Copy constructor\n\t\tif(vChrom.size() == this->nDimensions)\n\t\t{\n\t\t\t// std::pair<first, second> is pushed to this->points[]\n\t\t\t// \tfirst  -> chromosome* pChrom (pointer to chromosome)\n\t\t\t// \tsecond -> vChrom[FA->npar+n] (vectorized chromosome)\n\t\t\tthis->order.push_back(-1);\n\t\t\tthis->reachDist.push_back(UNDEFINED_DIST);\n\t\t\tthis->processed.push_back(false);\n\t\t\tthis->inverseDensities.push_back(0.0f);\n\t\t\tthis->points.push_back( std::make_pair( (chromosome*)&chrom[i], vChrom) ) ;\n\t\t}\n\t}\n\n};\n\nvoid FastOPTICS::Execute_FastOPTICS(char* end_strfile, char* tmp_end_strfile)\n{\n\t// vector of point indexes \n\tstd::vector< int > ptInd;\n    ptInd.reserve(this->N);\n    for(int k = 0; k < this->N; ++k)\n    {\n        ptInd.push_back(k);\n    }\n\t\n\t// Build object, compute projections, density estimates and density neighborhoods (in serial order of function calls below)\n\tRandomProjectedNeighborsAndDensities::RandomProjectedNeighborsAndDensities MultiPartition(this->points, this->minPoints, this); // use minPoints amount of random projections\n\tMultiPartition.computeSetBounds(ptInd);\n\tMultiPartition.getInverseDensities(this->inverseDensities);\n\tMultiPartition.getNeighbors(this->neighbors);\n    \n\t// Compute OPTICS ordering\n\tfor(int ipt = 0; ipt < this->N; ipt++) \t\t// starting from 0\n//\tfor(int ipt = this->N-1; ipt >= 0; --ipt)\t// starting from this->N-1\n    {\n\t\tif(!this->processed[ipt]) this->ExpandClusterOrder(ipt);\n    }\n    \n    // Would it be useful to normalize 'reachability distance' ?\n    // this->normalizeDistances();\n    // output the projected distances\n    \n    MultiPartition.output_projected_distance(end_strfile, tmp_end_strfile);\n    \n\t// Order chromosome and their reachDist in OPTICS\n    //  points pairs contain :\n    //   first  -> pair<chromosome*, index>\n    //   second -> float reachDist\n\tfor(int i = 0; i < this->N; ++i)\n\t{\n\t\tif( (this->points[i]).first != NULL && (this->points[i].first)->app_evalue < 0 )\n\t\t{\n\t\t\t// Calling Pose constructor for the current chromosome\n\t\t\tPose::Pose Pose((this->points[i]).first, i, this->order[i], this->reachDist[i], this->Population->Temperature, (this->points[i]).second);\n\t\t\t// OPTICS.push(Pose);\n            this->OPTICS.push_back(Pose);\n\t\t}\n\t}\n    std::sort(this->OPTICS.begin(), this->OPTICS.end(), PoseClassifier::PoseClassifier());\n\n\t// Build BindingModes (aggregation of Poses in BindingModes)\n    int i = 0; // used to have an idea of the number of loop completed (iterators are less convenient for that information while debugging)\n \tBindingMode::BindingMode Current(this->Population);\n\tfor(std::vector< Pose >::iterator it = this->OPTICS.begin(); it != this->OPTICS.end(); ++i, ++it)\n\t{\n\n        if(isUndefinedDist(it->reachDist) && it->order == 0) { Current.add_Pose(*it); }\n        else if(it->reachDist <= this->FA->cluster_rmsd*(1 + RandomProjectedNeighborsAndDensities::sizeTolerance)) { Current.add_Pose(*it); }\n\n       \tif(it->reachDist > this->FA->cluster_rmsd*(1 + RandomProjectedNeighborsAndDensities::sizeTolerance) || isUndefinedDist(it->reachDist))\n        {\n\t\t\tif(Current.get_BindingMode_size() >= this->minPoints)\n\t\t\t{\n\t\t\t\tthis->Population->add_BindingMode(Current);\n                Current.clear_Poses();\n            }\n        }\n\t}\n}\n\nvoid FastOPTICS::output_OPTICS(char* end_strfile, char* tmp_end_strfile)\n{\n\t// output variables\n    char sufix[25];\n    \n    // priting OPTICS variable to '__minPoints.optics' file\n    sprintf(sufix,\"__%d.optics\",this->minPoints);\n    strcpy(tmp_end_strfile,end_strfile);\n\tstrcat(tmp_end_strfile,sufix);\n    FILE* outfile;// = fopen(tmp_end_strfile,\"w\");\n\tif(!OpenFile_B(tmp_end_strfile,\"w\",&outfile))\n\t{\n\t\tTerminate(6);\n\t}\n\telse\n\t{\n        fprintf(outfile, \"#ORDER\\t#INDEX\\t#reachDist\\t#CF\\t#prevRMSD\\t#nextRMSD\\n\");\n\t\tfor(std::vector<Pose>::iterator it = this->OPTICS.begin(); it != this->OPTICS.end(); ++it)\n\t\t{\n\t\t\tfloat prevDist = (it == this->OPTICS.begin()) \t? 0.0f : this->compute_vect_distance(it->vPose, (it-1)->vPose);\n\t\t\tfloat nextDist = ((it+1) == this->OPTICS.end()) ? 0.0f : this->compute_vect_distance(it->vPose, (it+1)->vPose);\n            if(!isUndefinedDist(it->reachDist))\tfprintf(outfile, \"%d\\t%d\\t%8g\\t%8g\\t%8g\\t%8g\\n\", it->order, it->chrom_index, it->reachDist, it->CF, prevDist, nextDist);\n            else fprintf(outfile, \"%d\\t%d\\t%8g\\t%8g\\t%8g\\t%8g\\n\", it->order, it->chrom_index, UNDEFINED_DIST, it->CF, prevDist, nextDist);\n\t\t}\n   }\n   CloseFile_B(&outfile,\"w\");;//fclose(outfile);\n}\n\nvoid FastOPTICS::output_3d_OPTICS_ordering(char* end_strfile, char* tmp_end_strfile)\n{\n\t// File and Output variables declarations\n    cfstr CF; /* complementarity function value */\n    resid *pRes = NULL;\n    cfstr* pCF = NULL;\n\tchar sufix[25];\n    char remark[MAX_REMARK];\n\tchar tmpremark[MAX_REMARK];\n\n\tsprintf(sufix, \"__%d.optics.pdb\", this->minPoints);\n\tstrcpy(tmp_end_strfile, end_strfile);\n\tstrcat(tmp_end_strfile,sufix);\n\tFILE* outfile;\n\tif(!OpenFile_B(tmp_end_strfile, \"w\", &outfile))\n\t{\n\t\tTerminate(5);\n\t}\n\telse\n\t{\n        int nModel = 1;\n\t\tfor(std::vector<Pose>::iterator Pose = this->OPTICS.begin(); Pose != this->OPTICS.end(); ++Pose, ++nModel)\n\t\t{\n\t\t\tfor(int k = 0; k < this->GB->num_genes; ++k) this->FA->opt_par[k] = Pose->chrom->genes[k].to_ic;\n\t\t\tCF = ic2cf(this->FA, this->VC, this->atoms, this->residue, this->cleftgrid, this->GB->num_genes, this->FA->opt_par);\n\t\t\tstrcpy(remark,\"REMARK optimized structure\\n\");\n\t\t\tsprintf(tmpremark,\"REMARK Fast OPTICS clustering algorithm used to order Poses in OPTICS\\n\");\n\t\t\tstrcat(remark,tmpremark);\n\t\t\tsprintf(tmpremark,\"REMARK CF=%8.5f\\n\",get_cf_evalue(&CF));\n\t\t\tstrcat(remark,tmpremark);\n\t\t\tsprintf(tmpremark,\"REMARK CF.app=%8.5f\\n\",get_apparent_cf_evalue(&CF));\n\t\t\tstrcat(remark,tmpremark);\n\n\t\t\tfor(int j = 0; j < this->FA->num_optres; ++j)\n\t\t\t{\n\t\t\t\tpRes = &this->residue[this->FA->optres[j].rnum];\n\t\t\t\tpCF  = &this->FA->optres[j].cf;\n\t\t        \n\t\t        sprintf(tmpremark,\"REMARK optimizable residue %s %c %d\\n\", pRes->name, pRes->chn, pRes->number);\n\t\t        strcat(remark,tmpremark);\n\t\t        \n\t\t        sprintf(tmpremark ,\"REMARK CF.com=%8.5f\\n\", pCF->com);\n\t\t        strcat(remark, tmpremark);\n\t\t        sprintf(tmpremark ,\"REMARK CF.sas=%8.5f\\n\", pCF->sas);\n\t\t        strcat(remark, tmpremark);\n\t\t        sprintf(tmpremark ,\"REMARK CF.wal=%8.5f\\n\", pCF->wal);\n\t\t        strcat(remark, tmpremark);\n\t\t        sprintf(tmpremark ,\"REMARK CF.con=%8.5f\\n\", pCF->con);\n\t\t        strcat(remark, tmpremark);\n\t\t        sprintf(tmpremark, \"REMARK Residue has an overall SAS of %.3f\\n\", pCF->totsas);\n\t\t        strcat(remark, tmpremark);\n\t\t\t}\n\t\t    \n\t\t    for(int j=0; j < this->FA->npar; ++j)\n\t\t\t{\n\t\t\t\tsprintf(tmpremark, \"REMARK [%8.3f]\\n\",this->FA->opt_par[j]);\n\t\t\t\tstrcat(remark,tmpremark);\n\t\t\t}\n\n\t\t\t// 4. if(REF) prints RMSD to REF\n\t\t\tif(this->FA->refstructure == 1)\n\t\t\t{\n\t\t\t\tbool Hungarian = false;\n\t\t\t\tsprintf(tmpremark,\"REMARK %8.5f RMSD to ref. structure (no symmetry correction)\\n\",\n\t\t\t\tcalc_rmsd(this->FA,this->atoms,this->residue,this->cleftgrid,this->FA->npar,this->FA->opt_par, Hungarian));\n\t\t\t\tstrcat(remark,tmpremark);\n\t\t\t\tHungarian = true;\n\t\t\t\tsprintf(tmpremark,\"REMARK %8.5f RMSD to ref. structure     (symmetry corrected)\\n\",\n\t\t\t\tcalc_rmsd(this->FA,this->atoms,this->residue,this->cleftgrid,this->FA->npar,this->FA->opt_par, Hungarian));\n\t\t\t\tstrcat(remark,tmpremark);\n\t\t\t}\n\t        \n\t\t\t// 5. write_pdb(FA,atoms,residue,tmp_end_strfile,remark)\n\t\t\tif(Pose == this->OPTICS.begin() && Pose+1 == this->OPTICS.end())\n\t\t\t{\n\t\t\t\t// case where there is only one pose to write (Pose == OPTICS.begin() && Pose++ == OPTICS.end())\n\t\t\t\twrite_MODEL_pdb(true, true, nModel, this->FA,this->atoms,this->residue,tmp_end_strfile,remark);\n\t\t\t}\n\t\t\telse if(Pose == this->OPTICS.begin())\n\t\t\t{\n\t\t\t\t// first MODEL to be written\n\t\t\t\twrite_MODEL_pdb(true, false, nModel, this->FA,this->atoms,this->residue,tmp_end_strfile,remark);\n\t\t\t}\n\t\t\telse if(Pose+1 == this->OPTICS.end())\n\t\t\t{\n\t\t\t\t// last MODEL to be written\n\t\t\t\twrite_MODEL_pdb(false, true, nModel, this->FA,this->atoms,this->residue,tmp_end_strfile,remark);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// any MODEL in between to be written\n\t\t\t\twrite_MODEL_pdb(false, false, nModel, this->FA,this->atoms,this->residue,tmp_end_strfile,remark);\n\t\t\t}\n\t}\n}\n}\n\nstd::vector<float> FastOPTICS::Vectorized_Chromosome(chromosome* chrom)\n{\n    float norm = 0.0f;\n\tstd::vector<float> vChrom(this->nDimensions, 0.0f);\n\t// getting nDim-2 because the Dim=0 fills 3 memory cases\n\tfor(int j = 0; j < this->nDimensions-2; ++j)\n\t{\n\t\tif(j == 0) //  building the first 3 comp. from genes[0] which are CartCoord x,y,z\n\t\t{\n\t\t\tfor(int i = 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\t// vChrom[i] = static_cast<float>(this->cleftgrid[static_cast<unsigned int>((*chrom).genes[j].to_ic)].coor[i] - this->FA->ori[i]);\n\t\t\t\tif(i == 0)\n\t\t\t\t{\n                    vChrom[i] = static_cast<float>(this->cleftgrid[static_cast<unsigned int>((*chrom).genes[j].to_ic)].coor[i] - this->FA->ori[i]);\n\t\t\t\t\t// vChrom[i] = static_cast<float>(this->cleftgrid[static_cast<unsigned int>((*chrom).genes[j].to_ic)].dis);\n\t\t\t\t\t// vChrom[i] *= vChrom[i];\n\t\t\t\t}\n\t\t\t\tif(i == 1)\n\t\t\t\t{\n\t\t\t\t\tvChrom[i] = static_cast<float>(this->cleftgrid[static_cast<unsigned int>((*chrom).genes[j].to_ic)].coor[i] - this->FA->ori[i]);\n\t\t\t\t\t// vChrom[i] = static_cast<float>(this->cleftgrid[static_cast<unsigned int>((*chrom).genes[j].to_ic)].ang);\n\t\t\t\t\t// vChrom[i] = static_cast<float>( RandomDouble( (*chrom).genes[j].to_int32) );\n\t\t\t\t\t// vChrom[i] *= vChrom[i];\n\t\t\t\t}\n\t\t\t\tif(i == 2)\n\t\t\t\t{\n                    vChrom[i] = static_cast<float>(this->cleftgrid[static_cast<unsigned int>((*chrom).genes[j].to_ic)].coor[i] - this->FA->ori[i]);\n\t\t\t\t\t// vChrom[i] = static_cast<float>(this->cleftgrid[static_cast<unsigned int>((*chrom).genes[j].to_ic)].dih);\n\t\t\t\t\t// vChrom[i] = static_cast<float>( genetoic(&this->gene_lim[i],(*chrom).genes[j].to_int32) );\n\t\t\t\t\t// vChrom[i] *= vChrom[i];\n\t\t\t\t}\n                norm += vChrom[i]*vChrom[i];\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// j+2 is used from {j = 1 to N} to build further comp. of genes[j]\n\t\t\t// vChrom[j+2] = static_cast<float>(genetoic(&gene_lim[j], (*chrom).genes[j].to_int32));\n\t\t\tvChrom[j+2] = static_cast<float>((*chrom).genes[j].to_ic);\n\t\t\t// vChrom[j+2] = static_cast<float>( RandomDouble( (*chrom).genes[j].to_int32) );\n            norm += vChrom[j+2]*vChrom[j+2];\n\t\t}\n\t}\n    \n  // norm = sqrtf(norm);\n  // for(int k = 0; k < this->nDimensions; ++k) { vChrom[k]/=norm; }\n   \n   return vChrom;\n}\n\nstd::vector<float> FastOPTICS::Vectorized_Cartesian_Coordinates(int chrom_index)\n{\n\tint i = 0,j = 0,l = 0,m = 0;\n\tint cat;\n\tint rot;\n\n\tuint grd_idx;\n\tint normalmode=-1;\n\tint rot_idx=0;\n\n    std::vector<float> vChrom(this->nDimensions);\n\n\tint npar = this->GB->num_genes;\n\t\n\tj = chrom_index;\n\n\tfor(i=0;i<npar;i++){ this->FA->opt_par[i] = this->chroms[j].genes[i].to_ic; }\n\n\tfor(i=0;i<npar;i++)\n\t{\n\t\t//printf(\"[%8.3f]\",FA->opt_par[i]);\n  \n\t\tif(this->FA->map_par[i].typ==-1) \n\t\t{ //by index\n\t\t\tgrd_idx = (uint)this->FA->opt_par[i];\n\t\t\t//printf(\"this->FA->opt_par(index): %d\\n\", grd_idx);\n\t\t\t//PAUSE;\n\t\t\tthis->atoms[this->FA->map_par[i].atm].dis = this->cleftgrid[grd_idx].dis;\n\t\t\tthis->atoms[this->FA->map_par[i].atm].ang = this->cleftgrid[grd_idx].ang;\n\t\t\tthis->atoms[this->FA->map_par[i].atm].dih = this->cleftgrid[grd_idx].dih;\n\n\t\t}\n\t\telse if(this->FA->map_par[i].typ == 0)\n\t\t{\n\t\t\tthis->atoms[this->FA->map_par[i].atm].dis = (float)this->FA->opt_par[i];\n\t\t}\n\t\telse if(this->FA->map_par[i].typ == 1)\n\t\t{\n\t\t\tthis->atoms[this->FA->map_par[i].atm].ang = (float)this->FA->opt_par[i];\n\t\t}\n\t\telse if(this->FA->map_par[i].typ == 2)\n\t\t{\n\t\t\tthis->atoms[this->FA->map_par[i].atm].dih = (float)this->FA->opt_par[i];\n\n\t\t\tj=this->FA->map_par[i].atm;\n\t\t\tcat=this->atoms[j].rec[3];\n\t\t\tif(cat != 0)\n\t\t\t{\n\t\t\t\twhile(cat != this->FA->map_par[i].atm)\n\t\t\t\t{\n\t\t\t\t\tthis->atoms[cat].dih=this->atoms[j].dih + this->atoms[cat].shift; \n\t\t\t\t\tj=cat;\n\t\t\t\t\tcat=this->atoms[j].rec[3];\n\t\t\t\t}\n\t\t\t}\n\t\t}else if(this->FA->map_par[i].typ == 3)\n\t\t{ //by index\n\t\t\tgrd_idx = (uint)this->FA->opt_par[i];\n\n\t\t\t// serves as flag , but also as grid index\n\t\t\tnormalmode=grd_idx;\n\n\t\t}else if(this->FA->map_par[i].typ == 4)\n\t\t{\n\t\t\trot_idx = (int)(this->FA->opt_par[i]+0.5);\n\n\t\t\tthis->residue[this->atoms[this->FA->map_par[i].atm].ofres].rot=rot_idx;\n\t\t}\n  \n\t}\n\n\tif(normalmode > -1) alter_mode(this->atoms,this->residue,this->FA->normal_grid[normalmode],this->FA->res_cnt,this->FA->normal_modes);\n\n\t/* rebuild cartesian coordinates of optimized residues*/\n    for(i=0;i<this->FA->nors;i++) buildcc(this->FA,this->atoms,this->FA->nmov[i],this->FA->mov[i]);\n\n\t// residue that is optimized geometrically (ligand)\n\tl=this->atoms[this->FA->map_par[0].atm].ofres;\n\n\trot=this->residue[l].rot;\n    m=0;\n\tfor(i=this->residue[l].fatm[rot];i<=this->residue[l].latm[rot];i++)\n\t{\n\t\tfor(j=0;j<3;j++) vChrom[m*3+j] = this->atoms[i].coor[j];\n        ++m;\n\t}\n\treturn vChrom;\n}\n\nvoid FastOPTICS::ExpandClusterOrder(int ipt)\n{\n    std::priority_queue< ClusterOrdering, std::vector<ClusterOrdering>, ClusterOrderingComparator::ClusterOrderingComparator > queue;\n\tClusterOrdering tmp(ipt,0,1e6f);\n\tqueue.push(tmp);\n\n    while(!queue.empty())\n\t{\n\t\tClusterOrdering current = queue.top();\n\t\tqueue.pop();\n\t\tint currPt = current.objectID;\n\t\t\n\t\tif(this->processed[currPt] == true) continue;\n\t\t\n\t\tthis->order[this->iOrder] = currPt;\n\t\t// incrementing STATIC rank ordering ()\n\t\t// FastOPTICS::iOrder++;\n\t\tthis->iOrder++;\n\t\tthis->processed[currPt] = true;\n\t\t\n\t\tfloat coredist = this->inverseDensities[currPt];\n\t\tfor( std::vector<int>::iterator it = this->neighbors[currPt].begin(); it != this->neighbors[currPt].end(); ++it)\n\t\t{\n\t\t\tint iNeigh = *it;\n\t\t\tif(this->processed[iNeigh] == true) continue;\n\n\t\t\tfloat nrdist = this->compute_distance(this->points[iNeigh], this->points[currPt]);\n\n\t\t\tif(coredist > nrdist)\n\t\t\t\tnrdist = coredist;\n\t\t\tif(isUndefinedDist(this->reachDist[iNeigh]))\n\t\t\t\tthis->reachDist[iNeigh] = nrdist;\n\t\t\telse if(nrdist < this->reachDist[iNeigh])\n\t\t\t\tthis->reachDist[iNeigh] = nrdist;\n\t\t\ttmp = ClusterOrdering::ClusterOrdering(iNeigh, currPt, nrdist);\n\t\t\tqueue.push(tmp);\n\t\t}\n        std::make_heap(const_cast<ClusterOrdering*>(&queue.top()),\n                       const_cast<ClusterOrdering*>(&queue.top() + queue.size()),\n                       ClusterOrderingComparator::ClusterOrderingComparator()\n                       );\n\t}\n}\n\nfloat FastOPTICS::compute_distance(std::pair< chromosome*,std::vector<float> > & a, std::pair< chromosome*,std::vector<float> > & b)\n{\n\tfloat distance = 0.0f;\n\n\t// simple distance calculation below\n\tfor(int i = 0; i < this->nDimensions; ++i)\n\t{\n\t\tfloat tempDist = (a.second[i]-b.second[i]);\n        distance +=  tempDist * tempDist;\n\t}\n\n   \t\t\treturn sqrtf(distance);\n   \t\n   \t// if(boost::math::isfinite(distance))\n   \t// {\n   \t// \t\treturn sqrtf(distance);\n   \t// }\n    // else if( boost::math::isinf(distance) && distance > FLT_EPSILON )\n    // {\n    //     \treturn UNDEFINED_DIST;\n    // }\n    // else \treturn 0.0f;\n   \t}\n\nfloat FastOPTICS::compute_vect_distance(std::vector<float> a, std::vector<float> b)\n{\n\tfloat distance = 0.0f;\n\n\t// simple distance calculation below\n\tfor(int i = 0; i < this->nDimensions; ++i)\n    {\n\t\tfloat tempDist = (a[i]-b[i]);\n        distance +=  tempDist * tempDist;\n    }\n\n\treturn sqrtf(distance);\n}\n\nint FastOPTICS::get_minPoints() { return this->minPoints; }\n/*****************************************\\\n\t\t\tRandomProjections\n\\*****************************************/\n\n// STATIC variables declaration\nint const RandomProjectedNeighborsAndDensities::logOProjectionConstant;\nfloat RandomProjectedNeighborsAndDensities::sizeTolerance;\n\n// Constructor\nRandomProjectedNeighborsAndDensities::RandomProjectedNeighborsAndDensities(std::vector< std::pair< chromosome*,std::vector<float> > >& inPoints, int minSplitSize, FastOPTICS* top)\n{\n\tthis->top = top;\n\tthis->minSplitSize = minSplitSize;\n\tRandomProjectedNeighborsAndDensities::sizeTolerance = static_cast<float>(2.0f/3.0f);\n\n\tif( inPoints.size() < 1 )\n\t{\n\t\tthis->N = 0;\n\t\tthis->nDimensions = 0;\n\t\tthis->nProject1D = 0;\n\t\treturn;\n\t}\n\telse\n\t{\n        this->points = inPoints;\n\t\tthis->N = this->points.size();\n\t\tthis->nDimensions = this->top->nDimensions;\n\t\tthis->nPointsSetSplits = static_cast<int>(RandomProjectedNeighborsAndDensities::logOProjectionConstant * log(this->N * this->nDimensions + 1)/log(2));\n\t\tthis->nProject1D = static_cast<int>(RandomProjectedNeighborsAndDensities::logOProjectionConstant * log(this->N * this->nDimensions + 1)/log(2));\n\t\t// line below calls copy-constructor\n\t}\n\tthis->projectedPoints.reserve(this->nProject1D);\n\tfor(int i = 0; i < this->nProject1D; ++i)\n\t{\n        this->projectedPoints.push_back(std::vector<float>(this->N));\n\t}\n//\tthis->splitsets.reserve(this->nPointsSetSplits);\n//\tfor(int j = 0; j< this->nPointsSetSplits; ++j)\n//\t{\n\t\t// this->splitsets.push_back(std::vector<int>());\n//\t}\n}\n\nvoid RandomProjectedNeighborsAndDensities::computeSetBounds(std::vector< int > & ptList)\n{\n\tstd::vector< std::vector<float> > tempProj(this->nProject1D);\n\t// perform projection of points\n\tfor(int j = 0; j<this->nProject1D; ++j)\n\t{\n        // std::vector<float> currentRp = this->Randomized_InternalCoord_Vector();\n        std::vector<float> currentRp(this->Randomized_CartesianCoord_Vector());\n        \n\t\tint k = 0;\n\t\tstd::vector<int>::iterator it = ptList.begin();\n\t\twhile(it != ptList.end())\n\t\t{\n\t\t\tfloat sum = 0.0f;\n\t\t\t// std::vector<float>::iterator vecPt = this->points[(*it)].second.begin();\n\t\t\tstd::vector<float> vecPt(this->points[(*it)].second);\n\t\t\tstd::vector<float>::iterator currPro = (this->projectedPoints[j]).begin();\n\t\t\tfor(int m = 0; m < this->nDimensions; ++m)\n\t\t\t\tsum += currentRp[m] * vecPt[m];\n\n\t\t\tcurrPro[k] = sum;\n\n\t\t\t++k;\n            ++it;\n\t\t}\n\t}\n\n\t// Split Points Set\n    \n\tstd::vector<int> projInd(this->nProject1D);\n\tprojInd.reserve(this->nProject1D);\n\tfor(int j = 0; j < this->nProject1D; ++j) \n\t{\n//\t\tprojInd.push_back(j);\n        projInd[j] = j;\n\t}\n\tfor(int avgP = 0; avgP < this->nPointsSetSplits; avgP++)\n\t{\n\t\t// Shuffle projections\n\t\tfor(int i = 0; i < this->nProject1D; ++i)\n        {\n//\t\t\ttempProj.push_back(this->projectedPoints[i]);\n            tempProj[i] = this->projectedPoints[i];\n        }\n//        std::random_shuffle(projInd.begin(), projInd.end(), ([](int n) { return rand() % n; }) );\n        std::random_shuffle(projInd.begin(), projInd.end());\n\t\t\n\t\tint i = 0;\n        for(std::vector<int>::iterator it = projInd.begin(); it != projInd.end(); ++it, i++)\n\t\t{\n\t\t\tint cind = (*it);\n\t\t\t// look this line to be sure that the vector is pushed in this->projectedPoints\n\t\t\tthis->projectedPoints[cind] = tempProj[i];\n\t\t}\n\n\t\t//split points set\n\t\tint nPoints = ptList.size();\n\t\tstd::vector<int> ind(nPoints);\n\t\tind.reserve(nPoints);\n\t\tfor(int l = 0; l < nPoints; ++l)\n\t\t{\n\t\t\tind[l] = l;\n\t\t}\n\t\tthis->SplitUpNoSort(ind,0);\n\t}\n}\n\nvoid RandomProjectedNeighborsAndDensities::SplitUpNoSort(std::vector< int >& ind, int dim)\n{\n\tint nElements = ind.size();\n\tdim = dim % this->nProject1D;\n\tstd::vector<float>::iterator tProj = (this->projectedPoints[dim]).begin();\n\tint splitPos;\n\n\t// save set such that used for density or neighborhood computation\n\tif(nElements > this->minSplitSize*(1 - RandomProjectedNeighborsAndDensities::sizeTolerance) && nElements < this->minSplitSize*(1 + RandomProjectedNeighborsAndDensities::sizeTolerance))\n\t{\n\t\tstd::vector<float> cpro(nElements);\n\t\tfor(int i = 0; i < nElements; ++i)\t\n\t\t{\n//\t\t\tcpro.push_back(tProj[ind[i]]);\n            cpro[i] = tProj[ind[i]];\n\t\t}\n\t\t// sprting cpro[] && ind[] concurrently\n\t\tthis->quicksort_concurrent_Vectors(cpro, ind, 0, nElements-1);\n\t\tthis->splitsets.push_back(ind);\n\t}\n\n\t// compute splitting element\n\tif(nElements > this->minSplitSize)\n\t{\n\t\t//pick random splitting element based on position\n\t\tint randInt = static_cast<int>(std::floor( (RandomDouble()*static_cast<double>(nElements)) ));\n\t\tfloat rs = tProj[ind[randInt]];\n\t\tint minInd = 0;\n\t\tint maxInd = nElements - 1;\n\t\twhile(minInd < maxInd)\n\t\t{\n\t\t\tfloat currEle = tProj[ind[minInd]];\n\t\t\tif(currEle > rs)\n\t\t\t{\n\t\t\t\twhile(minInd < maxInd && tProj[ind[maxInd]] > rs) maxInd--;\n\t\t\t\tif(minInd == maxInd) break;\n\t\t\t\t\n\t\t\t\tint currInd = ind[minInd];\n\t\t\t\tind[minInd] = ind[maxInd];\n\t\t\t\tind[maxInd] = currInd;\n\t\t\t\tmaxInd--;\n\t\t\t}\n\t\t\tminInd++;\n\t\t}\n\t\tif( minInd == nElements-1 ) minInd = nElements/2;\n\n\t\t// split set recursively\n\t\tsplitPos = minInd + 1;\n\t\t\n\t\t// std::vector<int> ind2(splitPos);\n\t\tstd::vector<int> ind2(splitPos);\n\t\tfor(int l = 0; l < splitPos; ++l)\n\t\t{\n\t\t\t ind2[l] = ind[l];\n//\t\t\tind2.push_back(ind[l]);\n\t\t}\n\t\tthis->SplitUpNoSort(ind2,dim+1);\n\t\t\n        std::vector<int> ind3(nElements - splitPos);\n//        ind2 = std::vector<int>( nElements-splitPos );\n\t\tfor(int l = 0; l < nElements-splitPos; ++l)\n\t\t{\n\t\t\t ind3[l] = ind[l+splitPos];\n//\t\t\tind3.push_back(ind[l+splitPos]);\n\t\t}\n\t\tthis->SplitUpNoSort(ind3,dim+1);\n\t}\n}\n\nvoid RandomProjectedNeighborsAndDensities::getInverseDensities(std::vector< float > & inverseDensities)\n{\n\tinverseDensities.reserve(this->N);\n\tstd::vector<int> nDists(this->N);\n\tnDists.reserve(this->N);\n//\tfor(std::vector< std::vector< int> >::iterator it1 = this->splitsets.begin(); it1 != this->splitsets.end(); ++it1)\n    for(int i = 0; i < this->splitsets.size(); ++i)\n\t{\n//\t\tstd::vector<int>::iterator pinSet = it1->begin();\n        std::vector<int> & pinSet = this->splitsets.at(i);\n\t\t\n//\t\tint len = it1->size();\n        int len = pinSet.size();\n\t\tint indoff = static_cast<int>(round(len/2));\n\t\tint oldind = pinSet[indoff];\n\t\tfor(int i = 0; i < len; ++i)\n\t\t{\n\t\t\tint ind = pinSet[i];\n\t\t\tif(ind == indoff) continue;\n\t\t\t\n\t\t\tfloat dist = this->top->compute_distance(this->points[ind],this->points[oldind]);\n\t\t\tinverseDensities[oldind] += dist;\n\t\t\tnDists[oldind]++;\n\t\t\tinverseDensities[ind] += dist;\n\t\t\tnDists[ind]++;\n\t\t}\n\t}\n\tfor(int l = 0; l < this->N; ++l)\n\t{\n\t\tif(nDists[l] == 0) inverseDensities[l] = UNDEFINED_DIST;\n\t\telse inverseDensities[l] /= nDists[l];\n\t}\n}\n\nvoid RandomProjectedNeighborsAndDensities::getNeighbors(std::vector< std::vector< int > > & neighs)\n{\n\tneighs.reserve(this->N);\n\tfor(int l = 0; l < this->N; l++)\n\t{\n\t\tstd::vector<int> list;\n\t\tneighs.push_back(list);\n\t}\n\n\t// go through all sets\n\tfor(std::vector< std::vector< int > >::iterator it1 = this->splitsets.begin(); it1 != this->splitsets.end(); ++it1)\n\t{\n\t\t// for each set (each projected line)\n\t\tstd::vector<int>::iterator pinSet = it1->begin();\n\t\tint len = it1->size();\n\t\tint ind = pinSet[0];\n\t\tint indoff = static_cast<int>(round(len/2));\n\t\tint oldind = pinSet[indoff];\n\n\t\t// add all points as neighbors to middle point\n\t\t//  +\n\t\t// add the middle point to all other points in set\n\t\tfor(int i = 0; i < len; ++i)\n\t\t{\n\t\t\tind = pinSet[i];\n\n\t\t\t// The following block of code uses an iterator to check \n\t\t\tstd::vector<int> & cneighs = neighs.at(ind);\n\t\t\t// std::vector<int>::iterator itPos = std::find(cneighs.begin(),cneighs.end(),oldind);\n\t\t\t// if(itPos == cneighs.end()) //element not found in cneigh\n\t\t\tif( !std::binary_search(cneighs.begin(), cneighs.end(), oldind) )\n\t\t\t{\n\t\t\t\tcneighs.push_back(oldind);\n\t\t\t\tstd::sort(cneighs.begin(),cneighs.end());\n\t\t\t\tcneighs.erase(std::unique(cneighs.begin(), cneighs.end()), cneighs.end());\n\t\t\t}\n\n\t\t\tstd::vector<int> & cneighs2 = neighs.at(oldind);\n\t\t\t// itPos = std::find(cneighs2.begin(), cneighs2.end(), ind);\n\t\t\t// if(itPos == cneighs2.end()) // element not found in cneighs2\n\t\t\tif( !std::binary_search(cneighs2.begin(), cneighs2.end(), ind) )\n\t\t\t{\n\t\t\t\tcneighs2.push_back(oldind);\n\t\t\t\tstd::sort(cneighs2.begin(),cneighs2.end());\n\t\t\t\tcneighs2.erase(std::unique(cneighs2.begin(), cneighs2.end()), cneighs2.end());\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nvoid FastOPTICS::normalizeDistances()\n{\n\tfloat max = 0.0f;\n\tstd::vector<float> & Distances = this->reachDist;\n\tfor(std::vector<float>::iterator it = Distances.begin(); it != Distances.end(); ++it) if(*it > max && !isUndefinedDist(*it)) max = *it;\n\tfor(std::vector<float>::iterator it = Distances.begin(); it != Distances.end(); ++it) if(!isUndefinedDist(*it)) *it /= max;\n}\n\nstd::vector<float> RandomProjectedNeighborsAndDensities::Randomized_InternalCoord_Vector()\n{\n    std::vector<float> vChrom(this->nDimensions);\n\n\tfloat sum = 0.0f;\n\tfor(int j = 0; j < this->nDimensions-2; ++j)\n\t{\n\t\tif(j == 0) //  building the first 3 comp. from genes[0] which are CartCoord x,y,z\n\t\t{\n            double doubleGeneIC = genetoic(&this->top->gene_lim[j],roll_die());\n            for(int i = 0; i < 3; ++i)\n\t\t\t{\n\t\t\t\t// vChrom[i] = static_cast<float>(this->top->cleftgrid[static_cast<unsigned int>(doubleGeneIC)].coor[i] - this->top-÷>FA->ori[i]);\n\t\t\t\tif(i == 0)\n\t\t\t\t{\n\t\t\t\t\tvChrom[i] = static_cast<float>(this->top->cleftgrid[static_cast<unsigned int>(doubleGeneIC)].coor[i] - this->top->FA->ori[i]);\n//\t\t\t\t\tvChrom[i] = static_cast<float>(this->top->cleftgrid[static_cast<unsigned int>(doubleGeneIC)].dis);\n//                    vChrom[i] *= vChrom[i];\n\t\t\t\t}\n\t\t\t\tif(i == 1)\n\t\t\t\t{\n                    vChrom[i] = static_cast<float>(this->top->cleftgrid[static_cast<unsigned int>(doubleGeneIC)].coor[i] - this->top->FA->ori[i]);\n//\t\t\t\t\tvChrom[i] = static_cast<float>(this->top->cleftgrid[static_cast<unsigned int>(doubleGeneIC)].ang);\n//                    vChrom[i] *= vChrom[i];\n\t\t\t\t}\n\t\t\t\tif(i == 2)\n\t\t\t\t{\n                    vChrom[i] = static_cast<float>(this->top->cleftgrid[static_cast<unsigned int>(doubleGeneIC)].coor[i] - this->top->FA->ori[i]);\n//\t\t\t\t\tvChrom[i] = static_cast<float>(this->top->cleftgrid[static_cast<unsigned int>(doubleGeneIC)].dih);\n//                    vChrom[i] *= vChrom[i];\n\t\t\t\t}\n\t\t\t\tsum += vChrom[i]*vChrom[i];\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// j+2 is used from {j = 1 to N} to build further comp. of genes[j]\n\t\t\t// vChrom[j+2] = static_cast<float>(RandomDouble(random_dice()));\n\t\t\tvChrom[j+2] = static_cast<float>(genetoic(&this->top->gene_lim[j],roll_die()));\n\t\t\tsum += vChrom[j+2]*vChrom[j+2];\n\t\t}\n\t}\n\tsum = sqrtf(sum);\n\t// for(int k = 0; k < this->nDimensions; ++k) { vChrom[k]/=sum; }\n\n    \n\treturn vChrom;\n}\n\nstd::vector<float> RandomProjectedNeighborsAndDensities::Randomized_CartesianCoord_Vector()\n{\n    float norm = 0.0f;\n\n    int i = 0,j = 0,l = 0,m = 0;\n\tint cat;\n\tint rot;\n\n\tuint grd_idx;\n\tint normalmode=-1;\n\tint rot_idx=0;\n\n    std::vector<float> vChrom(this->nDimensions);\n\n\tint npar = this->top->GB->num_genes;\n\n\tfor(i=0;i<npar;i++){ this->top->FA->opt_par[i] = genetoic(&this->top->gene_lim[i],roll_die()); }\n\n\tfor(i=0;i<npar;i++)\n\t{\n  \n\t\tif(this->top->FA->map_par[i].typ==-1) \n\t\t{ //by index\n\t\t\tgrd_idx = (uint)this->top->FA->opt_par[i];\n\n\t\t\tthis->top->atoms[this->top->FA->map_par[i].atm].dis = this->top->cleftgrid[grd_idx].dis;\n\t\t\tthis->top->atoms[this->top->FA->map_par[i].atm].ang = this->top->cleftgrid[grd_idx].ang;\n\t\t\tthis->top->atoms[this->top->FA->map_par[i].atm].dih = this->top->cleftgrid[grd_idx].dih;\n\n\t\t}\n\t\telse if(this->top->FA->map_par[i].typ == 0)\n\t\t{\n\t\t\tthis->top->atoms[this->top->FA->map_par[i].atm].dis = (float)this->top->FA->opt_par[i];\n\t\t}\n\t\telse if(this->top->FA->map_par[i].typ == 1)\n\t\t{\n\t\t\tthis->top->atoms[this->top->FA->map_par[i].atm].ang = (float)this->top->FA->opt_par[i];\n\t\t}\n\t\telse if(this->top->FA->map_par[i].typ == 2)\n\t\t{\n\t\t\tthis->top->atoms[this->top->FA->map_par[i].atm].dih = (float)this->top->FA->opt_par[i];\n\n\t\t\tj=this->top->FA->map_par[i].atm;\n\t\t\tcat=this->top->atoms[j].rec[3];\n\t\t\tif(cat != 0)\n\t\t\t{\n\t\t\t\twhile(cat != this->top->FA->map_par[i].atm)\n\t\t\t\t{\n\t\t\t\t\tthis->top->atoms[cat].dih=this->top->atoms[j].dih + this->top->atoms[cat].shift; \n\t\t\t\t\tj=cat;\n\t\t\t\t\tcat=this->top->atoms[j].rec[3];\n\t\t\t\t}\n\t\t\t}\n\t\t}else if(this->top->FA->map_par[i].typ == 3)\n\t\t{ //by index\n\t\t\tgrd_idx = (uint)this->top->FA->opt_par[i];\n\n\t\t\t// serves as flag , but also as grid index\n\t\t\tnormalmode=grd_idx;\n\n\t\t}else if(this->top->FA->map_par[i].typ == 4)\n\t\t{\n\t\t\trot_idx = (int)(this->top->FA->opt_par[i]+0.5);\n\n\t\t\tthis->top->residue[this->top->atoms[this->top->FA->map_par[i].atm].ofres].rot=rot_idx;\n\t\t}\n  \n\t}\n\n\tif(normalmode > -1) alter_mode(this->top->atoms,this->top->residue,this->top->FA->normal_grid[normalmode],this->top->FA->res_cnt,this->top->FA->normal_modes);\n\n\t/* rebuild cartesian coordinates of optimized residues*/\n    for(i=0;i<this->top->FA->nors;i++) buildcc(this->top->FA,this->top->atoms,this->top->FA->nmov[i],this->top->FA->mov[i]);\n\n\t// residue that is optimized geometrically (ligand)\n\tl=this->top->atoms[this->top->FA->map_par[0].atm].ofres;\n\n\trot=this->top->residue[l].rot;\n    m=0;\n\tfor(i=this->top->residue[l].fatm[rot];i<=this->top->residue[l].latm[rot];i++)\n\t{\n\t\tfor(j=0;j<3;j++)\n\t\t{\n\t\t\tvChrom[m*3+j] = this->top->atoms[i].coor[j];\n\t\t\tnorm += vChrom[m*3+j]*vChrom[m*3+j];\n\t\t}\n        ++m;\n\t}\n\tnorm = sqrtf(norm);\n//   \tfor(i = 0; i < this->nDimensions; ++i) vChrom[i] /= norm;\n\treturn vChrom;\n}\n\nvoid RandomProjectedNeighborsAndDensities::quicksort_concurrent_Vectors(std::vector<float>& data, std::vector<int>& index, int beg, int end)\n{\n\tint l, r, p;\n\tfloat pivot;\n\tstd::vector<float>::iterator xData, yData;\n\tstd::vector<int>::iterator xIndex, yIndex;\n\twhile(beg < end)\n\t{\n\t\tl = beg; p = beg + (end-beg)/2; r = end;\n\t\tpivot = data[p];\n\t\t\n\t\twhile(1)\n\t\t{\n\t\t\twhile( (l<=r) && QS_ASC(data[l],pivot) <= 0 ) ++l;\n\t\t\twhile( (l<=r) && QS_ASC(data[r],pivot)  > 0 ) --r;\n\t\n\t\t\tif (l > r) break;\n\t\t\txData = data.begin()+l; yData = data.begin()+r;\n\t\t\txIndex = index.begin()+l; yIndex = index.begin()+r;\n\t\t\tthis->swap_element_in_vectors(xData, yData, xIndex, yIndex);\n\t\t\tif (p == r) p = l;\n\t\t\t++l; --r;\n\t\t}\n\t\txData = data.begin()+p; yData = data.begin()+r;\n\t\txIndex = index.begin()+p; yIndex = index.begin()+r;\n\t\tthis->swap_element_in_vectors(xData, yData, xIndex, yIndex);\n\n\t\t--r;\n\n\t\tif( (r-beg) < (end-l) )\n\t\t{\n\t\t\tthis->quicksort_concurrent_Vectors(data, index, beg, r);\n\t\t\tbeg = l;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis->quicksort_concurrent_Vectors(data, index, l, end);\n\t\t\tend = r;\n\t\t}\n\t}\n}\n\nvoid RandomProjectedNeighborsAndDensities::swap_element_in_vectors(std::vector<float>::iterator xData, std::vector<float>::iterator yData, std::vector<int>::iterator xIndex, std::vector<int>::iterator yIndex)\n{\n\tfloat tData = *xData; *xData = *yData; *yData = tData;\n\tint tIndex = *xIndex; *xIndex = *yIndex; *yIndex = tIndex;\n}\n\nvoid RandomProjectedNeighborsAndDensities::output_projected_distance(char* end_strfile, char* tmp_end_strfile)\n{\n\tchar sufix[25];\n\tsprintf(sufix, \"__%d.projDist\", this->top->minPoints);\n\tstrcpy(tmp_end_strfile, end_strfile);\n\tstrcat(tmp_end_strfile,sufix);\n\tFILE* outfile;\n\tif(!OpenFile_B(tmp_end_strfile,\"w\",&outfile))\n\t{\n\t\tTerminate(5);\n\t}\n\telse\n\t{\n\t\tfor(int i = 0; i < this->N; ++i)\n\t\t{\n            for(int j = 0; j < this->nProject1D; ++j)\n\t\t\t{\n                std::vector<float> & it = this->projectedPoints.at(j);\n\t\t\t\tfprintf(outfile, \"%6f\", it[i]);\n                if(j < this->nProject1D-1) fprintf(outfile, \"\\t\");\n                else fprintf(outfile, \"\\n\");\n}\n\t\t}\n\t}\n\tCloseFile_B(&outfile,\"w\");;//fclose(outfile);\n}\n\n// This function generates a RandomInt32 who can be used as *genes->to_int32 value\n// int RandomProjectedNeighborsAndDensities::Dice()\n// {\n// \tunsigned int tt = static_cast<unsigned int>(time(0));\n// \tsrand(tt);\n// \tRNGType rng(tt);\n// \tboost::uniform_int<> one_to_max_int32( 0, MAX_RANDOM_VALUE );\n// \tboost::variate_generator< RNGType, boost::uniform_int<> > dice(rng, one_to_max_int32);\n// \treturn dice();\n// }\n\nint roll_die()\n{\n    boost::random::uniform_int_distribution<> dist(0, MAX_RANDOM_VALUE);\n    return dist(gen);\n}\nint roll_rand_die()\n{\n\tint n;\n\treturn rand()%n;\n}\n", "meta": {"hexsha": "7e77c2f48153ee2f187e7fcf3d6fa8ce0a2d0d47", "size": 34883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LIB/FOPTICS.cpp", "max_stars_repo_name": "bkmgit/FlexAID", "max_stars_repo_head_hexsha": "e66298e545eb863d57c1064ccd29e98a6674b225", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-02-28T02:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:02:51.000Z", "max_issues_repo_path": "LIB/FOPTICS.cpp", "max_issues_repo_name": "bkmgit/FlexAID", "max_issues_repo_head_hexsha": "e66298e545eb863d57c1064ccd29e98a6674b225", "max_issues_repo_licenses": ["Apache-2.0"], "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/FOPTICS.cpp", "max_forks_repo_name": "bkmgit/FlexAID", "max_forks_repo_head_hexsha": "e66298e545eb863d57c1064ccd29e98a6674b225", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-06-07T20:27:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T08:56:39.000Z", "avg_line_length": 33.0331439394, "max_line_length": 210, "alphanum_fraction": 0.636241149, "num_tokens": 10990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.0194193463380643, "lm_q1q2_score": 0.008802048808441845}}
{"text": "#include <cstdint>\n#include <cfloat>\n#include <cassert>\n#include <string>\n#include <queue>\n#include <map>\n#include <vector>\n#include <boost/format.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/utility/value_init.hpp>\n#include \"Alignment.hpp\"\n#include \"AlnGraphBoost.hpp\"\n\nAlnGraphBoost::AlnGraphBoost(const std::string& backbone) {\n    // initialize the graph structure with the backbone length + enter/exit\n    // vertex\n    size_t blen = backbone.length();\n    _g = G(blen+2);\n    for (size_t i = 0; i < blen+1; i++)\n        boost::add_edge(i, i+1, _g);\n\n    VtxIter curr, last;\n    boost::tie(curr, last) = boost::vertices(_g);\n    _enterVtx = *curr++;\n    _g[_enterVtx].base = '^';\n    _g[_enterVtx].backbone = true;\n    for (size_t i = 0; i < blen; i++, ++curr) {\n        VtxDesc v = *curr;\n        _g[v].backbone = true;\n        _g[v].weight = 1;\n        _g[v].base = backbone[i];\n        _bbMap[v] = v;\n    }\n    _exitVtx = *curr;\n    _g[_exitVtx].base = '$';\n    _g[_exitVtx].backbone = true;\n}\n\nAlnGraphBoost::AlnGraphBoost(const size_t blen) {\n    _g = G(blen+2);\n    for (size_t i = 0; i < blen+1; i++)\n        boost::add_edge(i, i+1, _g);\n\n    VtxIter curr, last;\n    boost::tie(curr, last) = boost::vertices(_g);\n    _enterVtx = *curr++;\n    _g[_enterVtx].base = '^';\n    _g[_enterVtx].backbone = true;\n    for (size_t i = 0; i < blen; ++i, ++curr) {\n        VtxDesc v = *curr;\n        _g[v].backbone = true;\n        _g[v].weight = 1;\n        _g[v].deleted = false;\n        _g[v].base = 'N';\n        _bbMap[v] = v;\n    }\n    _exitVtx = *curr;\n    _g[_exitVtx].base = '$';\n    _g[_exitVtx].backbone = true;\n}\n\nvoid AlnGraphBoost::addAln(dagcon::Alignment& aln) {\n    IndexMap index = boost::get(boost::vertex_index, _g);\n    // tracks the position on the backbone\n    uint32_t bbPos = aln.start;\n    VtxDesc prevVtx = _enterVtx;\n    for (size_t i = 0; i < aln.qstr.length(); i++) {\n        char queryBase = aln.qstr[i], targetBase = aln.tstr[i];\n        assert(queryBase != '.');\n        assert(targetBase != '.');\n        VtxDesc currVtx = index[bbPos];\n        // match\n        if (queryBase == targetBase) {\n            _g[_bbMap[currVtx]].coverage++;\n\n            // NOTE: for empty backbones\n            _g[_bbMap[currVtx]].base = targetBase;\n\n            _g[currVtx].weight++;\n            addEdge(prevVtx, currVtx);\n            bbPos++;\n            prevVtx = currVtx;\n        // query deletion\n        } else if (queryBase == '-' && targetBase != '-') {\n            _g[_bbMap[currVtx]].coverage++;\n\n            // NOTE: for empty backbones\n            _g[_bbMap[currVtx]].base = targetBase;\n\n            bbPos++;\n        // query insertion\n        } else if (queryBase != '-' && targetBase == '-') {\n            // create new node and edge\n            VtxDesc newVtx = boost::add_vertex(_g);\n            _g[newVtx].base = queryBase;\n            _g[newVtx].weight++;\n            _g[newVtx].backbone = false;\n            _g[newVtx].deleted = false;\n            _bbMap[newVtx] = bbPos;\n            addEdge(prevVtx, newVtx);\n            prevVtx = newVtx;\n        }\n    }\n    addEdge(prevVtx, _exitVtx);\n}\n\nvoid AlnGraphBoost::addEdge(VtxDesc u, VtxDesc v) {\n    // Check if edge exists with prev node.  If it does, increment edge counter,\n    // otherwise add a new edge.\n    InEdgeIter ii, ie;\n    bool edgeExists = false;\n    for (boost::tie(ii, ie) = boost::in_edges(v, _g); ii != ie; ++ii) {\n        EdgeDesc e = *ii;\n        if (boost::source(e , _g) == u) {\n            // increment edge count\n            _g[e].count++;\n            edgeExists = true;\n        }\n    }\n    if (! edgeExists) {\n        // add new edge\n        std::pair<EdgeDesc, bool> p = boost::add_edge(u, v, _g);\n        _g[p.first].count++;\n    }\n}\n\nvoid AlnGraphBoost::mergeNodes() {\n    std::queue<VtxDesc> seedNodes;\n    seedNodes.push(_enterVtx);\n\n    while(true) {\n        if (seedNodes.size() == 0)\n            break;\n\n        VtxDesc u = seedNodes.front();\n        seedNodes.pop();\n        mergeInNodes(u);\n        mergeOutNodes(u);\n\n        OutEdgeIter oi, oe;\n        for (boost::tie(oi, oe) = boost::out_edges(u, _g); oi != oe; ++oi) {\n            EdgeDesc e = *oi;\n            _g[e].visited = true;\n            VtxDesc v = boost::target(e, _g);\n            InEdgeIter ii, ie;\n            int notVisited = 0;\n            for (boost::tie(ii, ie) = boost::in_edges(v, _g); ii != ie; ++ii) {\n                if (_g[*ii].visited == false)\n                    notVisited++;\n            }\n\n            // move onto the boost::target node after we visit all incoming edges for\n            // the boost::target node\n            if (notVisited == 0)\n                seedNodes.push(v);\n        }\n    }\n}\n\nvoid AlnGraphBoost::mergeInNodes(VtxDesc n) {\n    std::map<char, std::vector<VtxDesc>> nodeGroups;\n    InEdgeIter ii, ie;\n    // Group neighboring nodes by base\n    for(boost::tie(ii, ie) = boost::in_edges(n, _g); ii != ie; ++ii) {\n        VtxDesc inNode = boost::source(*ii, _g);\n        if (out_degree(inNode, _g) == 1) {\n            nodeGroups[_g[inNode].base].push_back(inNode);\n        }\n    }\n\n    // iterate over node groups, merge an accumulate information\n    for(auto kvp = nodeGroups.cbegin(); kvp != nodeGroups.end(); ++kvp) {\n        std::vector<VtxDesc> nodes = (*kvp).second;\n        if (nodes.size() <= 1)\n            continue;\n\n        std::vector<VtxDesc>::const_iterator ni = nodes.cbegin();\n        VtxDesc an = *ni++;\n        OutEdgeIter anoi, anoe;\n        boost::tie(anoi, anoe) = boost::out_edges(an, _g);\n\n        // Accumulate out edge information\n        for (; ni != nodes.cend(); ++ni) {\n            OutEdgeIter oi, oe;\n            boost::tie(oi, oe) = boost::out_edges(*ni, _g);\n            _g[*anoi].count += _g[*oi].count;\n            _g[an].weight += _g[*ni].weight;\n        }\n\n        // Accumulate in edge information, merges nodes\n        ni = nodes.cbegin();\n        ++ni;\n        for (; ni != nodes.cend(); ++ni) {\n            InEdgeIter ii, ie;\n            VtxDesc n = *ni;\n            for (boost::tie(ii, ie) = boost::in_edges(n, _g); ii != ie; ++ii) {\n                VtxDesc n1 = boost::source(*ii, _g);\n                EdgeDesc e;\n                bool exists;\n                boost::tie(e, exists) = edge(n1, an, _g);\n                if (exists) {\n                    _g[e].count += _g[*ii].count;\n                } else {\n                    std::pair<EdgeDesc, bool> p = boost::add_edge(n1, an, _g);\n                    _g[p.first].count = _g[*ii].count;\n                    _g[p.first].visited = _g[*ii].visited;\n                }\n            }\n            markForReaper(n);\n        }\n        mergeInNodes(an);\n    }\n}\n\nvoid AlnGraphBoost::mergeOutNodes(VtxDesc n) {\n    std::map<char, std::vector<VtxDesc>> nodeGroups;\n    OutEdgeIter oi, oe;\n    for(boost::tie(oi, oe) = boost::out_edges(n, _g); oi != oe; ++oi) {\n        VtxDesc outNode = boost::target(*oi, _g);\n        if (in_degree(outNode, _g) == 1) {\n            nodeGroups[_g[outNode].base].push_back(outNode);\n        }\n    }\n\n    for(auto kvp = nodeGroups.cbegin(); kvp != nodeGroups.end(); ++kvp) {\n        std::vector<VtxDesc> nodes = (*kvp).second;\n        if (nodes.size() <= 1)\n            continue;\n\n        std::vector<VtxDesc>::const_iterator ni = nodes.cbegin();\n        VtxDesc an = *ni++;\n        InEdgeIter anii, anie;\n        boost::tie(anii, anie) = boost::in_edges(an, _g);\n\n        // Accumulate inner edge information\n        for (; ni != nodes.cend(); ++ni) {\n            InEdgeIter ii, ie;\n            boost::tie(ii, ie) = boost::in_edges(*ni, _g);\n            _g[*anii].count += _g[*ii].count;\n            _g[an].weight += _g[*ni].weight;\n        }\n\n        // Accumulate and merge outer edge information\n        ni = nodes.cbegin();\n        ++ni;\n        for (; ni != nodes.cend(); ++ni) {\n            OutEdgeIter oi, oe;\n            VtxDesc n = *ni;\n            for (boost::tie(oi, oe) = boost::out_edges(n, _g); oi != oe; ++oi) {\n                VtxDesc n2 = boost::target(*oi, _g);\n                EdgeDesc e;\n                bool exists;\n                boost::tie(e, exists) = edge(an, n2, _g);\n                if (exists) {\n                    _g[e].count += _g[*oi].count;\n                } else {\n                    std::pair<EdgeDesc, bool> p = boost::add_edge(an, n2, _g);\n                    _g[p.first].count = _g[*oi].count;\n                    _g[p.first].visited = _g[*oi].visited;\n                }\n            }\n            markForReaper(n);\n        }\n    }\n}\n\nvoid AlnGraphBoost::markForReaper(VtxDesc n) {\n    _g[n].deleted = true;\n    clear_vertex(n, _g);\n    _reaperBag.push_back(n);\n}\n\nvoid AlnGraphBoost::reapNodes() {\n    int reapCount = 0;\n    std::sort(_reaperBag.begin(), _reaperBag.end());\n    std::vector<VtxDesc>::iterator curr = _reaperBag.begin();\n    for (; curr != _reaperBag.end(); ++curr) {\n        assert(_g[*curr].backbone==false);\n        remove_vertex(*curr-reapCount++, _g);\n    }\n}\n\nconst std::string AlnGraphBoost::consensus(int minWeight) {\n    // get the best scoring path\n    std::vector<AlnNode> path = bestPath();\n\n    // consensus sequence\n    std::string cns;\n\n    // track the longest consensus path meeting minimum weight\n    int offs = 0, bestOffs = 0, length = 0, idx = 0;\n    bool metWeight = false;\n    std::vector<AlnNode>::iterator curr = path.begin();\n    for (; curr != path.end(); ++curr) {\n        AlnNode n = *curr;\n        if (n.base == _g[_enterVtx].base || n.base == _g[_exitVtx].base)\n            continue;\n\n        cns += n.base;\n\n        // initial beginning of minimum weight section\n        if (!metWeight && n.weight >= minWeight) {\n            offs = idx;\n            metWeight = true;\n        } else if (metWeight && n.weight < minWeight) {\n        // concluded minimum weight section, update if longest seen so far\n            if ((idx - offs) > length) {\n                bestOffs = offs;\n                length = idx - offs;\n            }\n            metWeight = false;\n        }\n        idx++;\n    }\n\n    // include end of sequence\n    if (metWeight && (idx - offs) > length) {\n        bestOffs = offs;\n        length = idx - offs;\n    }\n\n    return cns.substr(bestOffs, length);\n}\n\nvoid AlnGraphBoost::consensus(std::vector<CnsResult>& seqs, int minWeight, size_t minLen) {\n    seqs.clear();\n\n    // get the best scoring path\n    std::vector<AlnNode> path = bestPath();\n\n    // consensus sequence\n    std::string cns;\n\n    // track the longest consensus path meeting minimum weight\n    int offs = 0, idx = 0;\n    bool metWeight = false;\n    std::vector<AlnNode>::iterator curr = path.begin();\n    for (; curr != path.end(); ++curr) {\n        AlnNode n = *curr;\n        if (n.base == _g[_enterVtx].base || n.base == _g[_exitVtx].base)\n            continue;\n\n        cns += n.base;\n\n        // initial beginning of minimum weight section\n        if (!metWeight && n.weight >= minWeight) {\n            offs = idx;\n            metWeight = true;\n        } else if (metWeight && n.weight < minWeight) {\n        // concluded minimum weight section, add sequence to supplied vector\n            metWeight = false;\n            CnsResult result;\n            result.range[0] = offs;\n            result.range[1] = idx;\n            size_t length = idx - offs;\n            result.seq = cns.substr(offs, length);\n            if (length >= minLen) seqs.push_back(result);\n        }\n        idx++;\n    }\n\n    // include end of sequence\n    if (metWeight) {\n        size_t length = idx - offs;\n        CnsResult result;\n        result.range[0] = offs;\n        result.range[1] = idx;\n        result.seq = cns.substr(offs, length);\n        if (length >= minLen) seqs.push_back(result);\n    }\n}\n\nconst std::vector<AlnNode> AlnGraphBoost::bestPath() {\n    EdgeIter ei, ee;\n    for (boost::tie(ei, ee) = edges(_g); ei != ee; ++ei)\n        _g[*ei].visited = false;\n\n    std::map<VtxDesc, EdgeDesc> bestNodeScoreEdge;\n    std::map<VtxDesc, float> nodeScore;\n    std::queue<VtxDesc> seedNodes;\n\n    // start at the end and make our way backwards\n    seedNodes.push(_exitVtx);\n    nodeScore[_exitVtx] = 0.0f;\n\n    while (true) {\n        if (seedNodes.size() == 0)\n            break;\n\n        VtxDesc n = seedNodes.front();\n        seedNodes.pop();\n\n        bool bestEdgeFound = false;\n        float bestScore = -FLT_MAX;\n        EdgeDesc bestEdgeD = boost::initialized_value;\n        OutEdgeIter oi, oe;\n        for(boost::tie(oi, oe) = boost::out_edges(n, _g); oi != oe; ++oi) {\n            EdgeDesc outEdgeD = *oi;\n            VtxDesc outNodeD = boost::target(outEdgeD, _g);\n            AlnNode outNode = _g[outNodeD];\n            float newScore, score = nodeScore[outNodeD];\n            if (outNode.backbone && outNode.weight == 1) {\n                newScore = score - 10.0f;\n            } else {\n                AlnNode bbNode = _g[_bbMap[outNodeD]];\n                newScore = _g[outEdgeD].count - bbNode.coverage*0.5f + score;\n            }\n\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                bestEdgeD = outEdgeD;\n                bestEdgeFound = true;\n            }\n        }\n\n        if (bestEdgeFound) {\n            nodeScore[n]= bestScore;\n            bestNodeScoreEdge[n] = bestEdgeD;\n        }\n\n        InEdgeIter ii, ie;\n        for (boost::tie(ii, ie) = boost::in_edges(n, _g); ii != ie; ++ii) {\n            EdgeDesc inEdge = *ii;\n            _g[inEdge].visited = true;\n            VtxDesc inNode = boost::source(inEdge, _g);\n            int notVisited = 0;\n            OutEdgeIter oi, oe;\n            for (boost::tie(oi, oe) = boost::out_edges(inNode, _g); oi != oe; ++oi) {\n                if (_g[*oi].visited == false)\n                    notVisited++;\n            }\n\n            // move onto the target node after we visit all incoming edges for\n            // the target node\n            if (notVisited == 0)\n                seedNodes.push(inNode);\n        }\n    }\n\n    // construct the final best path\n    VtxDesc prev = _enterVtx, next;\n    std::vector<AlnNode> bpath;\n    while (true) {\n        bpath.push_back(_g[prev]);\n        if (bestNodeScoreEdge.count(prev) == 0) {\n            break;\n        } else {\n            EdgeDesc bestOutEdge = bestNodeScoreEdge[prev];\n            _g[prev].bestOutEdge = bestOutEdge;\n            next = boost::target(bestOutEdge, _g);\n            _g[next].bestInEdge = bestOutEdge;\n            prev = next;\n        }\n    }\n\n    return bpath;\n}\n\nvoid AlnGraphBoost::printGraph() {\n    reapNodes();\n    boost::write_graphviz(std::cout, _g,\n        make_label_writer(get(&AlnNode::base, _g)),\n        make_label_writer(get(&AlnEdge::count, _g)));\n}\n\nbool AlnGraphBoost::danglingNodes() {\n    VtxIter curr, last;\n    boost::tie(curr, last) = boost::vertices(_g);\n    bool found = false;\n    for (;curr != last; ++curr) {\n        if (_g[*curr].deleted)\n            continue;\n        if (_g[*curr].base == _g[_enterVtx].base || _g[*curr].base == _g[_exitVtx].base)\n            continue;\n\n        int indeg = out_degree(*curr, _g);\n        int outdeg = in_degree(*curr, _g);\n        if (outdeg > 0 && indeg > 0) continue;\n\n        found = true;\n    }\n    return found;\n}\n\nAlnGraphBoost::~AlnGraphBoost(){}\n", "meta": {"hexsha": "c850039dcf6774696c21670a2084c3a57e5639a0", "size": 15262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/AlnGraphBoost.cpp", "max_stars_repo_name": "dthadi3/pbdagcon", "max_stars_repo_head_hexsha": "c14c422e609a914f0139f7222202ac1bce7e3ef1", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-02-24T19:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T18:45:36.000Z", "max_issues_repo_path": "src/cpp/AlnGraphBoost.cpp", "max_issues_repo_name": "dthadi3/pbdagcon", "max_issues_repo_head_hexsha": "c14c422e609a914f0139f7222202ac1bce7e3ef1", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2015-06-04T00:03:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-27T05:16:59.000Z", "max_forks_repo_path": "src/cpp/AlnGraphBoost.cpp", "max_forks_repo_name": "dthadi3/pbdagcon", "max_forks_repo_head_hexsha": "c14c422e609a914f0139f7222202ac1bce7e3ef1", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T09:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T18:45:40.000Z", "avg_line_length": 31.2745901639, "max_line_length": 91, "alphanum_fraction": 0.5273227624, "num_tokens": 4276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.031618768751487156, "lm_q1q2_score": 0.008798137213606519}}
{"text": "#ifndef FSTSEARCHBRANCHANDBOUNDPARTIALPREDICTION_H\n#define FSTSEARCHBRANCHANDBOUNDPARTIALPREDICTION_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    search_branch_and_bound_partial_prediction.hpp\n   \\brief   Implements Branch and Bound with Partial Prediction (BBPP) method, i.e., with predicted node ordering\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 availables 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 <ctime>\n#include <cstdlib> //rand\n#include \"branch_and_bound_predictor.hpp\"\n#include \"search_branch_and_bound.hpp\"\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"result_tracker.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 Branch and Bound with Partial Prediction (BBPP) method, i.e., with predicted node ordering\n\n\tBBPP is generally slower than FBB but faster than IBB. Its principle is\n\tidentical to that of Improved Branch & Bound (IBB), but it replaces\n\tlarge amount of criterion evaluations needed for ordering nodes in tree levels\n\tby quickly predicted values. The optimality of final result is not jeopardized\n\tbut considerable amount of time is saved. See FBB for a more radical but still\n\toptimality preserving use of value prediction.\n\n\t\\warning All Branch & Bound feature selection algorithms require the used\n\tCRITERION to be monotonic with respect to cardinality. More precisely, it must\n\thold that removing a feature from a set MUST NOT increase criterion value.\n\tOtherwise there is no guarantee as of the optimality of obtained results\n\twith respect to the used criterion.\n\n\t\\note All Branch & Bound algorithms by definition yield the solution with the \n\tsame maximum criterion value, therefore the main concern regarding particular\n\tBranch & Bound algorithm is only its search speed.\n\n\t\\note Due to possibly high number of subsets to be tested expect\n\texcessive computational time. \n\t\n\t\\note Result tracking in case of Branch & Bound algorithms records only results\n\tof target cardinality.\n*/\n\ntemplate<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION, class PREDICTOR>\nclass Search_Branch_And_Bound_Partial_Prediction : public Search_Branch_And_Bound<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>{\npublic:\n\ttypedef Search_Branch_And_Bound<RETURNTYPE,DIMTYPE,SUBSET,CRITERION> parent;\n\ttypedef typename parent::PCriterion PCriterion;\n\ttypedef typename parent::PSubset PSubset;\n\ttypedef typename parent::PNode PNode;\n\ttypedef typename parent::Node Node;\n\ttypedef typename parent::NodeType NodeType;\n\tSearch_Branch_And_Bound_Partial_Prediction():Search_Branch_And_Bound<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>() {notify(\"Search_Branch_And_Bound_Partial_Prediction constructor.\");}\n\tvirtual ~Search_Branch_And_Bound_Partial_Prediction() {notify(\"Search_Branch_And_Bound_Partial_Prediction destructor.\");}\n\n\t// for search() implementation see parent class\n\n\tvirtual std::ostream& print(std::ostream& os) const {os << \"Branch & Bound with Partial Prediction (BBPP)  [Search_Branch_And_Bound_Partial_Prediction() with \" << _predictor << \"]\"; return os;};\nprotected:\n\tPREDICTOR _predictor;\n\t\n\t// the following may be overriden in descendant Branch and Bound specialization classes\n\tvirtual void initialize(const DIMTYPE d, const DIMTYPE n, const PCriterion crit) {_predictor.initialize(n);} //!< called before search - enables set-up of additional structures in descendants\n\tvirtual void process_leafs();\n\tvirtual void pre_evaluate_availables(); //!< assign values to each feature in availables - to be used for node ordering\n\tvirtual void post_process_tree_level(); //!< enables to substitute missing COMPUTED values in nodes just after level creation, if needed\n\tvirtual bool cut_possible(); //!< tests current node for the possibility to cut its sub-branch\n};\n\ntemplate<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION, class PREDICTOR>\nvoid Search_Branch_And_Bound_Partial_Prediction<RETURNTYPE,DIMTYPE,SUBSET,CRITERION,PREDICTOR>::process_leafs()\n{\n\tassert(parent::get_criterion());\n\tconst PSubset &currentset=parent::get_currentset();\n\tNode &parentnode=parent::get_parent_node();\n\tRETURNTYPE value;\n\tPNode avail;\n\tfor(bool got=getFirstAvailable(avail);got;got=getNextAvailable(avail)) \n\t{\n\t\tassert(currentset->selected_raw(avail->feature));\n\t\tcurrentset->deselect_raw(avail->feature);\n\t\tif(!parent::get_criterion()->evaluate(value,currentset)) throw FST::fst_error(\"Criterion evaluation failure.\"); \n\t\tupdate_bound(value,currentset); //adds to tracker\n\t\t// conditionally update prediction info\n\t\tif(parentnode.type==parent::COMPUTED) _predictor.learn(avail->feature,parentnode.value-value);\n\t\tcurrentset->select_raw(avail->feature);\n\t}\n}\n\ntemplate<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION, class PREDICTOR>\nvoid Search_Branch_And_Bound_Partial_Prediction<RETURNTYPE,DIMTYPE,SUBSET,CRITERION,PREDICTOR>::pre_evaluate_availables() \n{\n\tassert(parent::get_criterion());\n\tconst PSubset &currentset=parent::get_currentset(); assert(currentset);\n\tNode &parentnode=parent::get_parent_node(); assert(parentnode.type==parent::COMPUTED);\n\n\t// pre-evaluate available features before next tree level construction\n\tPNode avail;\n\tRETURNTYPE val;\n\tfor(bool got=getFirstAvailable(avail);got;got=getNextAvailable(avail)) \n\t{\n\t\tif(_predictor.predict(avail->feature,val)) { //value could be predicted\n\t\t\tavail->value=parentnode.value-val;\n\t\t\tavail->type=parent::PREDICTED;\n\t\t} else { //value could not be predicted\n\t\t\tassert(currentset->selected_raw(avail->feature));\n\t\t\tcurrentset->deselect_raw(avail->feature);\n\t\t\tif(!parent::get_criterion()->evaluate(avail->value,currentset)) throw FST::fst_error(\"Criterion evaluation failure.\"); \n\t\t\tavail->type=parent::COMPUTED;\n\t\t\tcurrentset->select_raw(avail->feature);\n\t\t\t// conditionally update prediction info\n\t\t\tif(parentnode.type==parent::COMPUTED) _predictor.learn(avail->feature,parentnode.value-avail->value);\n\t\t}\n\t}\n}\n\ntemplate<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION, class PREDICTOR>\nvoid Search_Branch_And_Bound_Partial_Prediction<RETURNTYPE,DIMTYPE,SUBSET,CRITERION,PREDICTOR>::post_process_tree_level()\n{\n\tassert(parent::get_criterion());\n\tconst PSubset &currentset=parent::get_currentset();\tassert(currentset);\n\tNode &parentnode=parent::get_parent_node();\tassert(parentnode.type==parent::PREDICTED || parentnode.type==parent::COMPUTED);\n\n\t// enable to re-evaluate chosen candidate values (e.g., supply missing true criterion values, etc.)\n\tPNode nod;\n\tfor(bool got=getFirstNode(nod);got;got=getNextNode(nod)) \n\t{\n\t\tif(nod->type!=parent::COMPUTED) {\n\t\t\tassert(currentset->selected_raw(nod->feature));\n\t\t\tcurrentset->deselect_raw(nod->feature);\n\t\t\tif(!parent::get_criterion()->evaluate(nod->value,currentset)) throw FST::fst_error(\"Criterion evaluation failure.\"); \n\t\t\tnod->type=parent::COMPUTED;\n\t\t\tcurrentset->select_raw(nod->feature);\n\t\t\t// conditionally update prediction info\n\t\t\tif(parentnode.type==parent::COMPUTED) _predictor.learn(nod->feature,parentnode.value-nod->value);\n\t\t}\n\t}\n}\n\ntemplate<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION, class PREDICTOR>\nbool Search_Branch_And_Bound_Partial_Prediction<RETURNTYPE,DIMTYPE,SUBSET,CRITERION,PREDICTOR>::cut_possible()\n{\n\tif(parent::is_bound_valid()) {\n\t\tNode &currentnode=parent::get_current_node(); assert(currentnode.type==parent::COMPUTED);\n\t\tif(currentnode.value<=parent::get_bound_value()) { // BBPP ensures that the value must have been COMPUTED by now\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n} // namespace\n#endif // FSTSEARCHBRANCHANDBOUNDPARTIALPREDICTION_H ///:~\n", "meta": {"hexsha": "6199f7a63096b0dcfaa99927264f9d3716581890", "size": 11916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_search/search_branch_and_bound_partial_prediction.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_search/search_branch_and_bound_partial_prediction.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_search/search_branch_and_bound_partial_prediction.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": 52.2631578947, "max_line_length": 195, "alphanum_fraction": 0.7399295065, "num_tokens": 2778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.02800751898336501, "lm_q1q2_score": 0.008795776600594175}}
{"text": "/*\nRobotic Arm Mouse Control with Inverse Kinematics\n\nLicenced under the MIT License:\n\nCopyright (c) 2015 Pontus Lundström\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--\nThis program controls a servo-driven, turntable-shoulder-elbow topology robotic\narm by mouse with a static Inverse Kinematics (IK) solver. It sends servo PWM\ncommands over serial connection to an ATmega MCU which does the actual servo\ndriving.\n\nWritten hastily in (ugly) C++11 - downgradeable to C++03 with minimal changes.\n\nDependencies:\n  GLFW 3.x\n  boost::asio\n\nOn UNIX-like systems, compile with:\n$ g++ -std=c++11 arm_control.cpp -o arm_control -lglfw -lboost_system\n\nExample of use:\n$ ./arm_control /dev/ttyUSB0\n\n*/\n\n#include <boost/asio.hpp>\n\n#include <GLFW/glfw3.h>\n\n#include <array>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <thread>\n\n#define NDEBUG // Comment/remove to enable debug output\n\n#ifdef NDEBUG\n#define DEBUG_OUTPUT(a)\n#else\n#define DEBUG_OUTPUT(a) a\n#endif\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nnamespace\n{\n\n// Class for mapping angles to servo PWM data\nclass servo_mapping\n{\npublic:\n    servo_mapping(double min_angle, double max_angle,\n                  double min_delay, double max_delay) :\n        m_min_angle(min_angle),\n        m_max_angle(max_angle),\n        m_min_delay(min_delay),\n        m_max_delay(max_delay)\n    {}\n    double min_angle() const { return m_min_angle; }\n    double max_angle() const { return m_max_angle; }\n    double min_delay() const { return m_min_delay; }\n    double max_delay() const { return m_max_delay; }\n    double delay_from_angle(double angle) const\n    {\n        // Interpolate linearly & clamp to [m_min_delay, m_max_delay]\n        double delay = m_min_delay + (angle - m_min_angle) *\n                       (m_max_delay - m_min_delay) / (m_max_angle - m_min_angle);\n        if (m_min_delay > m_max_delay)\n        {\n            return (delay > m_min_delay) ? m_min_delay :\n                   ((delay < m_max_delay) ? m_max_delay : delay);    \n        }\n        return (delay < m_min_delay) ? m_min_delay :\n               ((delay > m_max_delay) ? m_max_delay : delay);\n    }\n    double angle_from_delay(double delay) const\n    {\n        // Interpolate linearly & clamp to [m_min_angle, m_max_angle]\n        double angle = m_min_angle + (delay - m_min_delay) *\n                       (m_max_angle - m_min_angle) / (m_max_delay - m_min_delay);\n        if (m_min_angle > m_max_angle)\n        {\n            return (angle > m_min_angle) ? m_min_angle :\n                   ((angle < m_max_angle) ? m_max_angle : angle);    \n        }\n        return (angle < m_min_angle) ? m_min_angle :\n               ((angle > m_max_angle) ? m_max_angle : angle);\n    }\nprivate:\n    double m_min_angle;\n    double m_max_angle;\n    double m_min_delay;\n    double m_max_delay;\n};\n\n// Data structures for IK\nstruct joint\n{\n    double d;\n    double s;\n    double theta;\n    double theta_min;\n    double theta_max;\n};\n\nstruct point\n{\n    double x;\n    double y;\n    double z;\n};\n\nstd::array<joint*, 3> arm_joints{nullptr, nullptr, nullptr};\npoint* wrist_position = nullptr;\n\n// Static IK scheme for turntable-shoulder-elbow topology\n// Returns the number of valid solutions (0...2)\nint ik(point const& goal, joint& j1, joint& j2, joint& j3)\n{\n    double epsilon = 1e-10;\n\n    const auto& px = goal.x;\n    const auto& py = goal.y;\n    const auto& pz = goal.z;\n\n    const auto& s1 = j1.s;\n    \n    // Solve for turntable\n    double D = sqrt(py*py*(px*px + py*py - s1*s1));\n    j1.d = D / py;\n    j1.theta = atan2((py*py*s1 - px*D) / (px*px*py + py*py*py),\n                     (px*s1 + D) / (px*px + py*py));\n\n    const auto& d1 = j1.d;\n    const auto& d2 = j2.d;\n    const auto& d3 = j3.d;\n\n    const auto& s2 = j2.s;\n    const auto& s3 = j3.s;\n\n    double d12 = d1*d1;\n    double d13 = d1*d12;\n    double d14 = d12*d12;\n    double d22 = d2*d2;\n    double d23 = d2*d22;\n    double d24 = d22*d22;\n    double d32 = d3*d3;\n    double d33 = d3*d32;\n    double pz2 = pz*pz;\n    double pz3 = pz*pz2;\n    double s22 = s2*s2;\n    double s23 = s2*s22;\n    double s32 = s3*s3;\n    double s33 = s3*s32;\n\n    double temp1 = d2*pz - d1*s2;\n    double temp2 = d12 + pz2;\n    double radicand = -temp1*temp1*(d14 - 2*(d22 + d32 - pz2 + s22 + s32)*d12 + d24 + d32*d32 + pz2*pz2 + s22*s22 + s32*s32 - 2*d32*pz2 - 2*d32*s22 - 2*pz2*s22 + 2*d32*s32 - 2*pz2*s32 - 2*s22*s32 - 2*d22*(d32 + pz2 - s22 + s32));\n\n    // Neither division by zero nor negative radicand of square root is allowed\n    if (abs(temp1) < epsilon || temp2 < epsilon || radicand < 0)\n    {\n        if (abs(temp1) < epsilon)\n        {\n            DEBUG_OUTPUT(std::cerr << \"abs(temp1) < epsilon\" << std::endl);\n        }\n        if (temp2 < epsilon)\n        {\n            DEBUG_OUTPUT(std::cerr << \"temp2 < epsilon\" << std::endl);\n        }\n        if (radicand < 0)\n        {\n            DEBUG_OUTPUT(std::cerr << \"radicand < 0\" << std::endl);\n        }\n        // NO SOLUTION!\n        return 0;\n    }\n    else\n    {\n        double temp3 = sqrt(radicand);\n\n        // Solution 1\n        double theta2_1 = atan2(\n        -(s22*d14 - 2*d2*pz*s2*d13 + ((pz2 + s22)*d22 + s22*(-d32 + pz2 + s22 - s32))*d12 + (-2*s2*pz3 - 2*s23*pz + 2*s2*s32*pz - 2*d22*s2*pz + 2*d32*s2*pz + temp3)*d2*d1 + (pz*d24 + pz*(-d32 + pz2 + s22 - s32)*d22 + temp3*s2)*pz)/(-temp1*temp2),\n        (d2*d13 + pz*s2*d12 + d2*(d22 - d32 + pz2 + s22 - s32)*d1 + pz*s23 - pz*s2*s32 - temp3 + pz3*s2 + d22*pz*s2 - d32*pz*s2)/temp2);\n\n        double theta3_1 = atan2(\n        (pz*s3*d24 + pz*s33*d22 - pz3*s3*d22 + pz*s22*s3*d22 + d32*pz*s3*d22 - d3*pz*s23*d2 - d3*pz*s2*s32*d2 - d3*temp3*d2 + d3*pz3*s2*d2 - d33*pz*s2*d2 + d12*pz*(d3*s2 - d2*s3)*d2 - s2*s3*temp3 - d23*d3*pz*s2 + d13*s2*(d2*s3 - d3*s2) + d1*s2*(d3*s2 - d2*s3)*(d22 + d32 - pz2 + s22 + s32))/temp1,\n        -(d3*pz*d24 + pz*s2*s3*d23 + d3*pz*(d32 - pz2 + s22 + s32)*d22 + (-s2*pz3 + s23*pz + s2*s32*pz + d32*s2*pz + temp3)*s3*d2 - d12*pz*(d2*d3 + s2*s3)*d2 - d3*s2*temp3 + d13*s2*(d2*d3 + s2*s3) - d1*s2*(d2*d3 + s2*s3)*(d22 + d32 - pz2 + s22 + s32))/temp1);\n\n        // Solution 2\n        double theta2_2 = atan2(\n        (-s22*d14 + 2*d2*pz*s2*d13-((pz2 + s22)*d22 + s22*(-d32 + pz2 + s22 - s32))*d12 + (2*s2*pz3 + 2*s23*pz - 2*s2*s32*pz + 2*d22*s2*pz - 2*d32*s2*pz + temp3)*d2*d1 + (pz*(d32 - pz2 - s22 + s32)*d22 - d24*pz + temp3*s2)*pz)/(-temp1*temp2),\n        (d2*d13 + pz*s2*d12 + d2*(d22 - d32 + pz2 + s22 - s32)*d1 + pz*s23 - pz*s2*s32 + temp3 + pz3*s2 + d22*pz*s2 - d32*pz*s2)/temp2);\n\n        double theta3_2 = atan2(\n        (pz*s3*d24 + pz*s33*d22 - pz3*s3*d22 + pz*s22*s3*d22 + d32*pz*s3*d22 - d3*pz*s23*d2 - d3*pz*s2*s32*d2 + temp3*d3*d2 + d3*pz3*s2*d2 - d33*pz*s2*d2 + d12*pz*(d3*s2 - d2*s3)*d2 - d23*d3*pz*s2 + temp3*s2*s3 + d13*s2*(d2*s3 - d3*s2) + d1*s2*(d3*s2 - d2*s3)*(d22 + d32 - pz2 + s22 + s32))/temp1,\n        -(d3*pz*d24 + pz*s2*s3*d23 - d3*pz3*d22 + d3*pz*s22*d22 + d3*pz*s32*d22 + d33*pz*d22 + pz*s2*s33*d2 - s3*temp3*d2 + pz*s23*s3*d2 - pz3*s2*s3*d2 + d32*pz*s2*s3*d2 - d12*pz*(d2*d3 + s2*s3)*d2 + temp3*d3*s2 + d13*s2*(d2*d3 + s2*s3) - d1*s2*(d2*d3 + s2*s3)*(d22 + d32 - pz2 + s22 + s32))/temp1);\n\n        // Choose which solution is better\n        bool solution1_inbound = true;\n        if (theta2_1 < j2.theta_min || theta2_1 > j2.theta_max || theta3_1 < j3.theta_min || theta3_1 > j3.theta_max)\n        {\n            // Solution 1 is out of bounds\n            solution1_inbound = false;\n        }\n        if (theta2_2 < j2.theta_min || theta2_2 > j2.theta_max || theta3_2 < j3.theta_min || theta3_2 > j3.theta_max)\n        {\n            // Solution 2 is out of bounds\n            DEBUG_OUTPUT(std::cerr << \"Solution 2 is out of bounds.\" << std::endl);\n            if (solution1_inbound)\n            {\n                // Solution 1 is the only valid solution\n                j2.theta = theta2_1;\n                j3.theta = theta3_1;\n                return 1;\n            }\n            else\n            {\n                DEBUG_OUTPUT(std::cerr << \"Both solutions are out of bounds.\" << std::endl);\n                // NO VALID SOLUTION!\n                return 0;\n            }\n        }    \n        else\n        {\n            if (solution1_inbound)\n            {\n                // Both solutions are valid -> choose one for which theta2 is greater\n                if (theta2_1 > theta2_2)\n                {\n                    j2.theta = theta2_1;\n                    j3.theta = theta3_1;\n                    return 2;\n                }\n                else\n                {\n                    j2.theta = theta2_2;\n                    j3.theta = theta3_2;\n                    return 2;\n                }\n            }\n            else\n            {\n                DEBUG_OUTPUT(std::cerr << \"Solution 1 is out of bounds.\" << std::endl);\n                // Solution 2 is the only valid solution\n                j2.theta = theta2_2;\n                j3.theta = theta3_2;\n                return 1;\n            }\n        }\n    }\n}\n\n// Invokes IK for input point and updates position if solution exists\nvoid move_arm(point const& new_position)\n{\n    joint new_joints[3];\n    for (size_t i = 0; i < 3; ++i)\n    {\n        new_joints[i] = *arm_joints[i];\n    }\n\n    if (ik(new_position, new_joints[0], new_joints[1], new_joints[2]) > 0)\n    {\n        *wrist_position = new_position;\n        for (size_t i = 0; i < 3; ++i)\n        {\n            *arm_joints[i] = new_joints[i];\n        }        \n    }\n}\n\n// Wrist planar position (xy-plane) control callback\nvoid cursor_callback(GLFWwindow*, double cursor_x, double cursor_y)\n{\n    const double cursor_sensitivity = 0.02;\n\n    static double old_x = 0.0;\n    static double old_y = 0.0;\n\n    double delta_x = cursor_x - old_x;\n    double delta_y = cursor_y - old_y;\n\n    point new_position{wrist_position->x + cursor_sensitivity * delta_x,\n                       wrist_position->y - cursor_sensitivity * delta_y,\n                       wrist_position->z};\n\n    // Ignore initial mouse position event\n    static bool debounce = true;\n    if (!debounce)\n    {    \n        move_arm(new_position);\n    }\n    else\n    {\n        debounce = false;\n    }\n\n    old_x = cursor_x;\n    old_y = cursor_y;\n}\n\n// Wrist height (z-axis) control callback\nvoid scroll_callback(GLFWwindow*, double, double offset)\n{\n    const double scroll_sensitivity = 3.0;\n    \n    point new_position{wrist_position->x, wrist_position->y,\n                       wrist_position->z + scroll_sensitivity * offset};\n    \n    // Ignore initial mouse position event\n    static bool debounce = true;\n    if (!debounce)\n    {\n        move_arm(new_position); \n    }\n    else\n    {\n        debounce = false;\n    }\n}\n\ntemplate <typename T>\nT deg2rad(T a)\n{\n    return a*T(M_PI/180);\n}\n\ntemplate <typename T>\nT rad2deg(T a)\n{\n    return a*T(180/M_PI);\n}\n\n}\n\nint main(int argc, char const *argv[])\n{\n    try\n    {\n        // Set fixed float width for stdout\n        std::cout.setf(std::ios::fixed, std:: ios::floatfield);\n        std::cout.precision(1);\n\n        if (argc < 2)\n        {\n            std::cout << \"Usage:\\narm_control <serial_device>\" << std::endl;\n            return 0;\n        }\n\n        auto serial_device = argv[1];\n        std::cout << \"Begin robot arm control on serial interface '\" << serial_device << \"'\\n\\n\"\n                  << \"Can't find the mouse cursor? \"\n                  << \"Don't panic, this is necessary to capture mouse input.\\n\"\n                  << \"Press Q or Alt+F4 to kill the program and regain mouse control.\\n\" << std::endl;\n\n        //=== Arm configuration parameters =========================================\n\n        // Joint angle limits\n        const double turntable_min_angle = deg2rad( -90.0);\n        const double turntable_max_angle = deg2rad(  90.0);\n        const double shoulder_min_angle  = deg2rad( -11.5);\n        const double shoulder_max_angle  = deg2rad( 136.0);\n        // TODO: measure\n        const double elbow_min_angle     = deg2rad(-170.0);\n        const double elbow_max_angle     = deg2rad(  10.0);\n\n        std::array<servo_mapping, 3> servos =\n            {servo_mapping{turntable_min_angle, turntable_max_angle,  600, 2315},\n             servo_mapping{shoulder_min_angle,  shoulder_max_angle,  2100,  650},\n             servo_mapping{elbow_min_angle,     elbow_max_angle,     2100,  700}};\n\n        // Joint topology, lengths in millimeters (mm)\n        joint j1{0.0,   -23.0, 0.0, turntable_min_angle, turntable_max_angle};\n        joint j2{248.0, -25.0, 0.0,  shoulder_min_angle,  shoulder_max_angle};\n        joint j3{272.0,   0.0, 0.0,     elbow_min_angle,     elbow_max_angle};\n        arm_joints[0] = &j1;\n        arm_joints[1] = &j2;\n        arm_joints[2] = &j3;\n\n        // Initial wrist position\n        point goal{0.0, 100.0, 50.0};\n        wrist_position = &goal;\n        //=== Arm configuration parameters =========================================\n\n        // Initialize joint angles with IK\n        if (ik(goal, j1, j2, j3) == 0)\n        {\n            std::cerr << \"Initial position is not reachable!\" << std::endl;\n            return -1337;\n        }\n\n        // Initialize serial communication\n        boost::asio::io_service io;\n        boost::asio::serial_port serial(io, serial_device);\n        serial.set_option(boost::asio::serial_port::baud_rate(57600));\n\n        // Initialize GLFW\n        if (!glfwInit())\n            return -1;\n\n        // Create a windowed mode window and its OpenGL context */\n        auto window = glfwCreateWindow(320, 240, \"Robot arm control\", NULL, NULL);\n        if (!window)\n        {\n            glfwTerminate();\n            return -1;\n        }\n\n        // Make the window's rendering context current\n        glfwMakeContextCurrent(window);\n\n        // This hides the cursor and enables infinite cursor movement\n        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);\n\n        // Setup mouse event callbacks\n        glfwSetScrollCallback(window, scroll_callback);\n        glfwSetCursorPosCallback(window, cursor_callback);\n\n        // Loop until the user closes the window */\n        while (!glfwWindowShouldClose(window))\n        {\n            glfwSwapBuffers(window);\n\n            // Poll and process events\n            glfwPollEvents();\n\n            std::cout << \"\\rWrist position: [\" << goal.x << \", \" << goal.y << \", \" << goal.z << \"]\"\n                      << \"  Joint angles: [\" << rad2deg(arm_joints[0]->theta) << \", \"\n                                             << rad2deg(arm_joints[1]->theta) << \", \"\n                                             << rad2deg(arm_joints[2]->theta) << \"] \";\n            for (size_t i = 0; i < 3; ++i)\n            {\n                DEBUG_OUTPUT(std::cerr << \"Send command for servo #\" << i << std::endl);\n                // Get delay from angle & encode servo index\n                uint16_t command = servos[i].delay_from_angle(arm_joints[i]->theta);\n\n                DEBUG_OUTPUT(std::cerr << \"\\t\" << command << std::endl);\n                command |= (i << 12);\n\n                // Send servo command\n                boost::asio::write(serial, boost::asio::buffer(&command, 2));\n            }\n            std::cout << \"          \" << std::flush;\n            \n            std::this_thread::sleep_for(std::chrono::milliseconds(5));\n\n            if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)\n                break;\n        }\n        std::cout << \"\\n\" << std::endl;\n        glfwTerminate();\n        \n        return 0;\n    }\n    catch (boost::system::system_error& e)\n    {\n        std::cerr << \"\\n\\nSerial communication error: \" << e.what() << \"\\n\" << std::endl;\n        glfwTerminate();\n        return -1;\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << \"\\n\\nSomething went wrong: \" << e.what() << \"\\n\" << std::endl;\n        glfwTerminate();\n        return -2;\n    }\n    catch (...)\n    {\n        std::cerr << \"\\n\\nUnknown error! :(\" << \"\\n\" << std::endl;\n        glfwTerminate();\n        return -666;\n    }\n}\n", "meta": {"hexsha": "96514e5f356e3dc655ed078e62fee0da814a587f", "size": 16951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/arm_control.cpp", "max_stars_repo_name": "SPuntte/roboarm", "max_stars_repo_head_hexsha": "3efa6cc0850eea4a626c4ce6b9431c913ca71e77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/arm_control.cpp", "max_issues_repo_name": "SPuntte/roboarm", "max_issues_repo_head_hexsha": "3efa6cc0850eea4a626c4ce6b9431c913ca71e77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/arm_control.cpp", "max_forks_repo_name": "SPuntte/roboarm", "max_forks_repo_head_hexsha": "3efa6cc0850eea4a626c4ce6b9431c913ca71e77", "max_forks_repo_licenses": ["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.902, "max_line_length": 299, "alphanum_fraction": 0.5648634299, "num_tokens": 4946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.022629198055612778, "lm_q1q2_score": 0.00879411429430807}}
{"text": "/* \n * The Biomechanical ToolKit\n * Copyright (c) 2009-2014, Arnaud Barré\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\n *       copyright notice, this list of conditions and the following\n *       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\n *       provided with the distribution.\n *     * Neither the name(s) of the copyright holders nor the names\n *       of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written\n *       permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"btkWrenchDirectionAngleFilter.h\"\n\n#include <Eigen/Geometry>\n\nnamespace btk\n{\n  /**\n   * @class WrenchDirectionAngleFilter btkWrenchDirectionAngleFilter.h\n   * @brief Calculate the direction angle of the force vector for each wrench.\n   *\n   * The direction angle is projected on each plane of the global frame in this order:\n   *  - Angle yOz: set in the X component of the output ;\n   *  - Angle xOz: set in the Y component of the output ;\n   *  - Angle xOy: set in the Z component of the output.\n   *\n   * The output angles are expressed in degrees and the range is between 0 and 360 degrees.\n   * Then a shift from 360 to 0 is possible if the force turns around itself.\n   * \n   * @ingroup BTKBasicFilters\n   */\n  \n  /**\n   * @typedef WrenchDirectionAngleFilter::Pointer\n   * Smart pointer associated with a WrenchDirectionAngleFilter object.\n   */\n  \n  /**\n   * @typedef WrenchDirectionAngleFilter::ConstPointer\n   * Smart pointer associated with a const WrenchDirectionAngleFilter object.\n   */\n    \n  /**\n   * @fn static Pointer WrenchDirectionAngleFilter::New();\n   * Creates a smart pointer associated with a WrenchDirectionAngleFilter object.\n   */\n\n  /**\n   * @fn WrenchCollection::Pointer WrenchDirectionAngleFilter::GetInput()\n   * Gets the input registered with this process.\n   */\n\n  /**\n   * @fn void WrenchDirectionAngleFilter::SetInput(Wrench::Pointer input)\n   * Sets the input required with this process. This input is transformed in a collection of wrenches with a single force platform.\n   */\n  \n  /**\n   * @fn void WrenchDirectionAngleFilter::SetInput(WrenchCollection::Pointer input)\n   * Sets the input required with this process.\n   */\n  \n  /**\n   * @fn PointCollection::Pointer WrenchDirectionAngleFilter::GetOutput()\n   * Gets the output created with this process.\n   */\n  \n  /**\n   * Constructor. Sets the number of inputs and outputs to 1.\n   */\n  WrenchDirectionAngleFilter::WrenchDirectionAngleFilter()\n  : ProcessObject()\n  {\n    this->SetInputNumber(1);\n    this->SetOutputNumber(1);\n  };\n\n  /**\n   * @fn ForcePlatformCollection::Pointer WrenchDirectionAngleFilter::GetInput(int idx)\n   * Returns the input at the index @a idx.\n   */\n  \n  /**\n   * @fn WrenchCollection::Pointer WrenchDirectionAngleFilter::GetOutput(int idx)\n   * Returns the output at the index @a idx.\n   */\n  \n  /**\n   * Creates a PointCollection:Pointer object and return it as a DataObject::Pointer.\n   */\n  DataObject::Pointer WrenchDirectionAngleFilter::MakeOutput(int /* idx */)\n  {\n    return PointCollection::New();\n  };\n  \n  /**\n   * Generates the outputs' data.\n   */\n  void WrenchDirectionAngleFilter::GenerateData()\n  {\n    PointCollection::Pointer output = this->GetOutput();\n    output->Clear();\n    WrenchCollection::Pointer input = this->GetInput();\n    const double radToDeg = 180.0 / M_PI;\n    if (input)\n    {\n      for (WrenchCollection::ConstIterator it = input->Begin() ; it != input->End() ; ++it)\n      {\n        int numFrames = (*it)->GetForce()->GetFrameNumber();\n        Point::Pointer dirAngle = Point::New((*it)->GetPosition()->GetLabel() + \".DA\", numFrames, Point::Angle);\n        for (int i = 0 ; i < numFrames ; ++i)\n        {\n          if ((*it)->GetPosition()->GetResiduals().coeff(i) >= 0)\n          {\n            dirAngle->GetValues().coeffRef(i,0) = atan2(-(*it)->GetForce()->GetValues().coeff(i,2), -(*it)->GetForce()->GetValues().coeff(i,1)) * radToDeg + 180.0;\n            dirAngle->GetValues().coeffRef(i,1) = atan2(-(*it)->GetForce()->GetValues().coeff(i,2), -(*it)->GetForce()->GetValues().coeff(i,0)) * radToDeg + 180.0;\n            dirAngle->GetValues().coeffRef(i,2) = atan2(-(*it)->GetForce()->GetValues().coeff(i,1), -(*it)->GetForce()->GetValues().coeff(i,0)) * radToDeg + 180.0;\n          }\n          else\n          {\n            dirAngle->GetResiduals().coeffRef(i) = -1.0;\n          }\n        }\n        output->InsertItem(dirAngle);\n      }\n    }\n  };\n};\n\n", "meta": {"hexsha": "d005f9eda43f703c5c772ee958b55bc7f2ec5eac", "size": 5596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/BasicFilters/btkWrenchDirectionAngleFilter.cpp", "max_stars_repo_name": "mitkof6/BTKCore", "max_stars_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_stars_repo_licenses": ["Barr", "Unlicense"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-04-21T20:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:35:03.000Z", "max_issues_repo_path": "Code/BasicFilters/btkWrenchDirectionAngleFilter.cpp", "max_issues_repo_name": "mitkof6/BTKCore", "max_issues_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_issues_repo_licenses": ["Barr", "Unlicense"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2015-06-23T20:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-17T17:08:57.000Z", "max_forks_repo_path": "Code/BasicFilters/btkWrenchDirectionAngleFilter.cpp", "max_forks_repo_name": "mitkof6/BTKCore", "max_forks_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_forks_repo_licenses": ["Barr", "Unlicense"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T11:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T20:37:04.000Z", "avg_line_length": 36.3376623377, "max_line_length": 163, "alphanum_fraction": 0.6747676912, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404168757891037, "lm_q2_score": 0.028870910079709197, "lm_q1q2_score": 0.008777960222573758}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Ilias Khairullin <ilias@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_MULTIPRECISION_MODULAR_FUNCTIONS_FIXED_PRECISION_HPP\n#define BOOST_MULTIPRECISION_MODULAR_FUNCTIONS_FIXED_PRECISION_HPP\n\n#include <nil/crypto3/multiprecision/modular/modular_policy_fixed.hpp>\n\n#include <boost/mpl/if.hpp>\n\n#include <type_traits>\n#include <utility>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace multiprecision {\n            namespace backends {\n\n                template<typename Backend>\n                class modular_functions_fixed;\n\n                //\n                // the function works correctly only with consistent backend objects,\n                // i.e. their limbs should not be manipulated directly\n                // as it breaks backend logic of size determination\n                // (or real size of such objects should be adjusted then)\n                //\n                template<typename Backend>\n                constexpr typename boost::mpl::if_c<is_trivial_cpp_int<Backend>::value,\n                                                    typename trivial_limb_type<max_precision<Backend>::value>::type,\n                                                    limb_type>::type\n                    get_limb_value(const Backend& b, const std::size_t i) {\n                    if (i < b.size()) {\n                        return b.limbs()[i];\n                    }\n                    return 0;\n                }\n\n                //\n                // function return real limb of nontrivial backend.\n                //\n                template<typename, typename Backend>\n                constexpr typename boost::enable_if_c<!is_trivial_cpp_int<Backend>::value, limb_type>::type\n                    custom_get_limb_value(const Backend& b, const std::size_t i) {\n                    return b.limbs()[i];\n                }\n\n                //\n                // function works with trivial backend.\n                // return value of logical limb as if trivial backend consists of several logical limbs.\n                //\n                template<typename internal_limb_type, typename Backend>\n                constexpr typename boost::enable_if_c<\n                    is_trivial_cpp_int<Backend>::value &&\n                        sizeof(typename trivial_limb_type<max_precision<Backend>::value>::type) >=\n                            sizeof(internal_limb_type),\n                    internal_limb_type>::type\n                    custom_get_limb_value(const Backend& b, const std::size_t i) {\n                    return static_cast<internal_limb_type>(b.limbs()[0] >> (sizeof(internal_limb_type) * CHAR_BIT * i));\n                }\n\n                //\n                // function set limb value of nontrivial backend.\n                //\n                template<typename, typename Backend>\n                constexpr typename boost::enable_if_c<!is_trivial_cpp_int<Backend>::value>::type\n                    custom_set_limb_value(Backend& b, const std::size_t i, limb_type v) {\n                    b.limbs()[i] = v;\n                }\n\n                //\n                // WARNING: using of this function is correct in current implementation of modular adaptor\n                // DO NOT USE THIS FUNCTION IN GENERAL CASE\n                //\n                // function works with trivial backend.\n                // set value of logical limb as if trivial backend consists of several logical limbs.\n                // modified logical limb is supposed to have zero value.\n                //\n                template<typename internal_limb_type, typename Backend>\n                constexpr typename boost::enable_if_c<\n                    is_trivial_cpp_int<Backend>::value &&\n                    sizeof(typename trivial_limb_type<max_precision<Backend>::value>::type) >=\n                        sizeof(internal_limb_type)>::type\n                    custom_set_limb_value(Backend& b, const std::size_t i, internal_limb_type v) {\n                    using local_limb_type = typename trivial_limb_type<max_precision<Backend>::value>::type;\n\n                    //\n                    // commented part seems to be correct in general case\n                    //\n                    // std::size_t upper_bytes_count = sizeof(local_limb_type) - sizeof(internal_limb_type) * (i + 1);\n                    // std::size_t lower_bytes_count = sizeof(internal_limb_type) * i;\n                    // unsigned char byte_mask = ~0;\n                    //\n                    // local_limb_type mask = 0;\n                    // for (std::size_t j = 0; j < upper_bytes_count; j++)\n                    // {\n                    //    mask |= byte_mask;\n                    //    mask <<= CHAR_BIT;\n                    // }\n                    // mask <<= (sizeof(internal_limb_type) - 1) * CHAR_BIT;\n                    // if (lower_bytes_count)\n                    // {\n                    //    for (std::size_t j = 0; j < lower_bytes_count - 1; j++)\n                    //    {\n                    //       mask |= byte_mask;\n                    //       mask <<= CHAR_BIT;\n                    //    }\n                    //    mask |= byte_mask;\n                    // }\n                    //\n                    // b.limbs()[0] &= mask;\n                    b.limbs()[0] |= (static_cast<local_limb_type>(v) << (sizeof(internal_limb_type) * CHAR_BIT * i));\n                }\n\n                template<typename Backend>\n                constexpr typename std::enable_if<!is_trivial_cpp_int<Backend>::value>::type\n                    adjust_backend_size(Backend& b, std::size_t mod_size) {\n                    assert(mod_size + 1 <= Backend::internal_limb_count);\n                    b.resize(b.limbs()[mod_size] != 0 ? mod_size + 1 : mod_size, 1);\n                }\n\n                template<typename Backend>\n                constexpr typename std::enable_if<is_trivial_cpp_int<Backend>::value>::type\n                    adjust_backend_size(Backend& b, std::size_t mod_size) {\n                    assert(mod_size == 1);\n                    b.resize(mod_size, 1);\n                }\n\n                template<typename Backend>\n                constexpr bool check_modulus_constraints(const Backend& m) {\n                    using ui_type = typename std::tuple_element<0, typename Backend::unsigned_types>::type;\n                    using default_ops::eval_lt;\n\n                    return !eval_lt(m, static_cast<ui_type>(0u));\n                }\n\n                template<typename Backend>\n                constexpr bool check_montgomery_constraints(const Backend& m) {\n                    using ui_type = typename std::tuple_element<0, typename Backend::unsigned_types>::type;\n                    using default_ops::eval_eq;\n                    using default_ops::eval_modulus;\n\n                    Backend tmp;\n                    eval_modulus(tmp, m, static_cast<ui_type>(2u));\n                    return !eval_eq(tmp, static_cast<ui_type>(0u));\n                }\n\n                template<typename Backend>\n                constexpr bool check_montgomery_constraints(const modular_functions_fixed<Backend>& mo) {\n                    return check_montgomery_constraints(mo.get_mod().backend());\n                }\n\n                //\n                // a little trick to prevent error in constexpr execution of eval_right_shift\n                // due to non-constexpr nature of right_shift_byte\n                //\n                template<typename Backend>\n                constexpr void custom_right_shift(Backend& b, unsigned s) {\n                    using default_ops::eval_left_shift;\n                    using default_ops::eval_right_shift;\n\n                    if (!s) {\n                        return;\n                    }\n\n                    limb_type byte_shift_mask = CHAR_BIT - 1;\n                    if ((s & byte_shift_mask) == 0) {\n                        eval_right_shift(b, s - 1u);\n                        eval_right_shift(b, 1u);\n                    } else {\n                        eval_right_shift(b, s);\n                    }\n                }\n\n                template<unsigned MinBits, cpp_integer_type SignType, cpp_int_check_type Checked>\n                class modular_functions_fixed<modular_fixed_cpp_int_backend<MinBits, SignType, Checked>> {\n                protected:\n                    typedef modular_fixed_cpp_int_backend<MinBits, SignType, Checked> Backend;\n\n                public:\n                    typedef modular_policy<Backend> policy_type;\n\n                protected:\n                    typedef typename policy_type::internal_limb_type internal_limb_type;\n                    typedef typename policy_type::internal_double_limb_type internal_double_limb_type;\n\n                    typedef typename policy_type::Backend_doubled_1 Backend_doubled_1;\n                    typedef typename policy_type::Backend_quadruple_1 Backend_quadruple_1;\n                    typedef typename policy_type::Backend_padded_limbs Backend_padded_limbs;\n                    typedef typename policy_type::Backend_doubled_limbs Backend_doubled_limbs;\n                    typedef typename policy_type::Backend_doubled_padded_limbs Backend_doubled_padded_limbs;\n\n                    typedef typename policy_type::number_type number_type;\n                    typedef typename policy_type::dbl_lmb_number_type dbl_lmb_number_type;\n\n                    constexpr static auto limb_bits = policy_type::limb_bits;\n\n                    constexpr void initialize_modulus(const number_type& m) {\n                        BOOST_ASSERT(check_modulus_constraints(m.backend()));\n\n                        get_mod() = m;\n                    }\n\n                    constexpr void initialize_barrett_params() {\n                        using default_ops::eval_bit_set;\n                        using default_ops::eval_divide;\n                        using default_ops::eval_msb;\n\n                        get_mu() = static_cast<internal_limb_type>(0u);\n\n                        eval_bit_set(get_mu(), 2u * (1u + eval_msb(get_mod().backend())));\n                        eval_divide(get_mu(), get_mod().backend());\n                    }\n\n                    constexpr void initialize_montgomery_params() {\n                        if (check_montgomery_constraints(get_mod().backend())) {\n                            find_const_variables();\n                            find_modulus_mask();\n                        }\n                    }\n\n                    constexpr internal_limb_type monty_inverse(internal_limb_type a) {\n                        BOOST_ASSERT(check_montgomery_constraints(get_mod().backend()));\n\n                        internal_limb_type b = 1;\n                        internal_limb_type r = 0;\n\n                        for (size_t i = 0; i != limb_bits; ++i) {\n                            const internal_limb_type bi = b % 2;\n                            r >>= 1;\n                            r += bi << (limb_bits - 1);\n\n                            b -= a * bi;\n                            b >>= 1;\n                        }\n\n                        // Now invert in addition space\n                        r = (~static_cast<internal_limb_type>(0) - r) + 1;\n\n                        return r;\n                    }\n\n                    constexpr void find_const_variables() {\n                        using default_ops::eval_bit_set;\n                        using default_ops::eval_gt;\n                        using default_ops::eval_multiply;\n\n                        BOOST_ASSERT(check_montgomery_constraints(get_mod().backend()) &&\n                                     check_modulus_constraints(get_mod().backend()));\n\n                        get_p_dash() = monty_inverse(get_mod().backend().limbs()[0]);\n\n                        Backend_doubled_padded_limbs r;\n                        eval_bit_set(r, get_mod().backend().size() * limb_bits);\n                        eval_multiply(r, r);\n                        barrett_reduce(r);\n\n                        get_r2() = static_cast<Backend>(r);\n                    }\n\n                    constexpr void find_modulus_mask() {\n                        get_modulus_mask() = static_cast<internal_limb_type>(1u);\n                        eval_left_shift(get_modulus_mask(), get_mod().backend().size() * limb_bits);\n                        eval_subtract(get_modulus_mask(),\n                                      decltype(m_modulus_mask)(static_cast<internal_limb_type>(1u)));\n                    }\n\n                    constexpr void initialize(const number_type& m) {\n                        initialize_modulus(m);\n                        initialize_barrett_params();\n                        initialize_montgomery_params();\n                    }\n\n                public:\n                    constexpr auto& get_mod() {\n                        return m_mod;\n                    }\n                    constexpr auto& get_mu() {\n                        return m_barrett_mu;\n                    }\n                    constexpr auto& get_r2() {\n                        return m_montgomery_r2;\n                    }\n                    constexpr auto& get_p_dash() {\n                        return m_montgomery_p_dash;\n                    }\n                    constexpr auto& get_modulus_mask() {\n                        return m_modulus_mask;\n                    }\n\n                    constexpr const auto& get_mod() const {\n                        return m_mod;\n                    }\n                    constexpr const auto& get_mu() const {\n                        return m_barrett_mu;\n                    }\n                    constexpr const auto& get_r2() const {\n                        return m_montgomery_r2;\n                    }\n                    constexpr auto get_p_dash() const {\n                        return m_montgomery_p_dash;\n                    }\n                    constexpr const auto& get_modulus_mask() const {\n                        return m_modulus_mask;\n                    }\n\n                    constexpr modular_functions_fixed() {\n                    }\n\n                    constexpr modular_functions_fixed(const number_type& m) {\n                        initialize(m);\n                    }\n\n                    constexpr modular_functions_fixed(const modular_functions_fixed& o) {\n                        get_mod() = o.get_mod();\n                        get_mu() = o.get_mu();\n                        get_r2() = o.get_r2();\n                        get_p_dash() = o.get_p_dash();\n                        get_modulus_mask() = o.get_modulus_mask();\n                    }\n\n                    template<typename Backend1>\n                    constexpr void barrett_reduce(Backend1& result) const {\n                        barrett_reduce(result, result);\n                    }\n\n                    //\n                    // this overloaded barrett_reduce is intended to work with built-in integral types\n                    //\n                    template<typename Backend1, typename Backend2>\n                    constexpr typename std::enable_if<boost::is_integral<Backend2>::value>::type\n                        barrett_reduce(Backend1& result, Backend2 input) const {\n                        using input_number_type = typename boost::mpl::if_c<\n                            bool(sizeof(int) * CHAR_BIT > MinBits),\n                            number<modular_fixed_cpp_int_backend<sizeof(int) * CHAR_BIT, SignType, Checked>>,\n                            number_type>::type;\n\n                        input_number_type input_b(input);\n                        barrett_reduce(result, input_b.backend());\n                    }\n\n                    template<typename Backend1, typename Backend2,\n                             typename = typename boost::enable_if_c<\n                                 /// result should fit in the output parameter\n                                 max_precision<Backend1>::value >= max_precision<Backend>::value &&\n                                 /// to prevent problems with trivial cpp_int\n                                 max_precision<Backend2>::value >= max_precision<Backend>::value>::type>\n                    constexpr void barrett_reduce(Backend1& result, Backend2 input) const {\n                        using default_ops::eval_add;\n                        using default_ops::eval_eq;\n                        using default_ops::eval_lt;\n                        using default_ops::eval_modulus;\n                        using default_ops::eval_msb;\n                        using default_ops::eval_multiply;\n                        using default_ops::eval_subtract;\n\n                        //\n                        // to prevent problems with trivial cpp_int\n                        //\n                        Backend2 modulus(get_mod().backend());\n\n                        if (eval_lt(input, modulus)) {\n                            while (eval_lt(input, 0u)) {\n                                eval_add(input, modulus);\n                            }\n                        } else if (eval_msb(input) < 2u * eval_msb(modulus) + 1u) {\n                            Backend_quadruple_1 t1(input);\n\n                            eval_multiply(t1, get_mu());\n                            custom_right_shift(t1, 2u * (1u + eval_msb(modulus)));\n                            eval_multiply(t1, modulus);\n                            eval_subtract(input, t1);\n\n                            if (!eval_lt(input, modulus)) {\n                                eval_subtract(input, modulus);\n                            }\n                        } else {\n                            eval_modulus(input, modulus);\n                        }\n                        result = input;\n                    }\n\n                    template<typename Backend1>\n                    constexpr void montgomery_reduce(Backend1& result) const {\n                        montgomery_reduce(result, result);\n                    }\n\n                    template<typename Backend1, typename Backend2,\n                             typename = typename boost::enable_if_c<\n                                 /// result should fit in the output parameter\n                                 max_precision<Backend1>::value >= max_precision<Backend>::value &&\n                                 /// input number should be represented by backend of appropriate size\n                                 max_precision<Backend_doubled_limbs>::value >= max_precision<Backend2>::value>::type>\n                    constexpr void montgomery_reduce(Backend1& result, const Backend2& input) const {\n                        using default_ops::eval_add;\n                        using default_ops::eval_bitwise_and;\n                        using default_ops::eval_left_shift;\n                        using default_ops::eval_lt;\n                        using default_ops::eval_multiply;\n                        using default_ops::eval_subtract;\n\n                        Backend_doubled_padded_limbs accum(input);\n                        Backend_doubled_padded_limbs prod;\n\n                        for (auto i = 0; i < get_mod().backend().size(); ++i) {\n                            eval_multiply(\n                                prod, get_mod().backend(),\n                                static_cast<internal_limb_type>(custom_get_limb_value<internal_limb_type>(accum, i) *\n                                                                /// to prevent overflow error in constexpr\n                                                                static_cast<double_limb_type>(get_p_dash())));\n                            eval_left_shift(prod, i * limb_bits);\n                            eval_add(accum, prod);\n                        }\n\n                        custom_right_shift(accum, get_mod().backend().size() * limb_bits);\n\n                        if (!eval_lt(accum, get_mod().backend())) {\n                            eval_subtract(accum, get_mod().backend());\n                        }\n                        eval_bitwise_and(accum, m_modulus_mask);\n                        result = accum;\n                    }\n\n                    template<typename Backend1, typename Backend2>\n                    constexpr void regular_add(Backend1& result, const Backend2& y) const {\n                        regular_add(result, result, y);\n                    }\n\n                    template<typename Backend1, typename Backend2, typename Backend3,\n                             /// result should fit in the output parameter\n                             typename = typename boost::enable_if_c<max_precision<Backend1>::value >=\n                                                                    max_precision<Backend>::value>::type>\n                    constexpr void regular_add(Backend1& result, const Backend2& x, const Backend3& y) const {\n                        using default_ops::eval_add;\n                        using default_ops::eval_lt;\n\n                        // TODO: maybe reduce input parameters\n                        /// input parameters should be lesser than modulus\n                        // BOOST_ASSERT(eval_lt(x, get_mod().backend()) && eval_lt(y, get_mod().backend()));\n\n                        Backend_padded_limbs tmp(x);\n                        eval_add(tmp, y);\n                        barrett_reduce(result, tmp);\n                    }\n\n                    template<typename Backend1, typename Backend2>\n                    constexpr void regular_mul(Backend1& result, const Backend2& y) const {\n                        regular_mul(result, result, y);\n                    }\n\n                    template<typename Backend1, typename Backend2, typename Backend3,\n                             /// result should fit in the output parameter\n                             typename = typename boost::enable_if_c<max_precision<Backend1>::value >=\n                                                                    max_precision<Backend>::value>::type>\n                    constexpr void regular_mul(Backend1& result, const Backend2& x, const Backend3& y) const {\n                        using default_ops::eval_lt;\n                        using default_ops::eval_multiply;\n\n                        // TODO: maybe reduce input parameters\n                        /// input parameters should be lesser than modulus\n                        // BOOST_ASSERT(eval_lt(x, get_mod().backend()) && eval_lt(y, get_mod().backend()));\n\n                        Backend_doubled_limbs tmp(x);\n                        eval_multiply(tmp, y);\n                        barrett_reduce(result, tmp);\n                    }\n\n                    template<typename Backend1, typename Backend2>\n                    constexpr void montgomery_mul(Backend1& result, const Backend2& y) const {\n                        montgomery_mul(result, result, y);\n                    }\n\n                    //\n                    // WARNING: could be errors here due to trivial backend -- more tests needed\n                    //\n                    template<typename Backend1, typename Backend2, typename Backend3,\n                             /// result should fit in the output parameter\n                             typename = typename boost::enable_if_c<max_precision<Backend1>::value >=\n                                                                    max_precision<Backend>::value>::type>\n                    constexpr void montgomery_mul(Backend1& result, const Backend2& x, const Backend3& y) const {\n                        using default_ops::eval_bitwise_and;\n                        using default_ops::eval_lt;\n                        using default_ops::eval_subtract;\n\n                        // TODO: maybe reduce input parameters\n                        /// input parameters should be lesser than modulus\n                        // BOOST_ASSERT(eval_lt(x, get_mod().backend()) && eval_lt(y, get_mod().backend()));\n\n                        Backend_padded_limbs A(internal_limb_type(0u));\n\n                        for (auto i = 0; i < get_mod().backend().size(); i++) {\n                            internal_limb_type u_i =\n                                (A.limbs()[0] + get_limb_value(x, i) * get_limb_value(y, 0)) * get_p_dash();\n\n                            // A += x[i] * y + u_i * m followed by a 1 limb-shift to the right\n                            internal_limb_type k = 0;\n                            internal_limb_type k2 = 0;\n\n                            internal_double_limb_type z =\n                                static_cast<internal_double_limb_type>(get_limb_value(y, 0)) *\n                                    static_cast<internal_double_limb_type>(get_limb_value(x, i)) +\n                                A.limbs()[0] + k;\n                            internal_double_limb_type z2 =\n                                static_cast<internal_double_limb_type>(get_limb_value(get_mod().backend(), 0)) *\n                                    static_cast<internal_double_limb_type>(u_i) +\n                                static_cast<internal_limb_type>(z) + k2;\n                            k = static_cast<internal_limb_type>(z >> std::numeric_limits<internal_limb_type>::digits);\n                            k2 = static_cast<internal_limb_type>(z2 >> std::numeric_limits<internal_limb_type>::digits);\n\n                            for (auto j = 1; j < get_mod().backend().size(); ++j) {\n                                internal_double_limb_type t =\n                                    static_cast<internal_double_limb_type>(get_limb_value(y, j)) *\n                                        static_cast<internal_double_limb_type>(get_limb_value(x, i)) +\n                                    A.limbs()[j] + k;\n                                internal_double_limb_type t2 =\n                                    static_cast<internal_double_limb_type>(get_limb_value(get_mod().backend(), j)) *\n                                        static_cast<internal_double_limb_type>(u_i) +\n                                    static_cast<internal_limb_type>(t) + k2;\n                                A.limbs()[j - 1] = static_cast<internal_limb_type>(t2);\n                                k = static_cast<internal_limb_type>(t >>\n                                                                    std::numeric_limits<internal_limb_type>::digits);\n                                k2 = static_cast<internal_limb_type>(t2 >>\n                                                                     std::numeric_limits<internal_limb_type>::digits);\n                            }\n                            internal_double_limb_type tmp =\n                                static_cast<internal_double_limb_type>(\n                                    custom_get_limb_value<internal_limb_type>(A, get_mod().backend().size())) +\n                                k + k2;\n                            custom_set_limb_value<internal_limb_type>(A, get_mod().backend().size() - 1,\n                                                                      static_cast<internal_limb_type>(tmp));\n                            custom_set_limb_value<internal_limb_type>(\n                                A, get_mod().backend().size(),\n                                static_cast<internal_limb_type>(tmp >>\n                                                                std::numeric_limits<internal_limb_type>::digits));\n                        }\n                        //\n                        // recover correct size of backend content\n                        //\n                        adjust_backend_size(A, get_mod().backend().size());\n\n                        if (!eval_lt(A, get_mod().backend())) {\n                            eval_subtract(A, get_mod().backend());\n                        }\n                        // TODO: maybe bitwise AND is not necessary\n                        // eval_bitwise_and(A, get_modulus_mask());\n                        result = A;\n                    }\n\n                    template<typename Backend1, typename Backend2>\n                    constexpr void regular_exp(Backend1& result, const Backend2& exp) const {\n                        regular_exp(result, result, exp);\n                    }\n\n                    template<typename Backend1, typename Backend2, typename Backend3,\n                             /// result should fit in the output parameter\n                             typename = typename boost::enable_if_c<max_precision<Backend1>::value >=\n                                                                    max_precision<Backend>::value>::type>\n                    constexpr void regular_exp(Backend1& result, Backend2& a, Backend3 exp) const {\n                        using default_ops::eval_eq;\n                        using default_ops::eval_lt;\n                        using default_ops::eval_multiply;\n\n                        // TODO: maybe reduce input parameter\n                        /// input parameter should be lesser than modulus\n                        // BOOST_ASSERT(eval_lt(a, get_mod().backend()));\n\n                        if (eval_eq(exp, static_cast<internal_limb_type>(0u))) {\n                            result = static_cast<internal_limb_type>(1u);\n                            return;\n                        }\n                        if (eval_eq(get_mod().backend(), static_cast<internal_limb_type>(1u))) {\n                            result = static_cast<internal_limb_type>(0u);\n                            return;\n                        }\n\n                        Backend_doubled_limbs base(a), res(static_cast<internal_limb_type>(1u));\n\n                        while (true) {\n                            internal_limb_type lsb = exp.limbs()[0] & 1u;\n                            custom_right_shift(exp, static_cast<internal_limb_type>(1u));\n                            if (lsb) {\n                                eval_multiply(res, base);\n                                barrett_reduce(res);\n                                if (eval_eq(exp, static_cast<internal_limb_type>(0u))) {\n                                    break;\n                                }\n                            }\n                            eval_multiply(base, base);\n                            barrett_reduce(base);\n                        }\n                        result = res;\n                    }\n\n                    template<typename Backend1, typename Backend2>\n                    constexpr void montgomery_exp(Backend1& result, const Backend2& exp) const {\n                        montgomery_exp(result, result, exp);\n                    }\n\n                    template<typename Backend1, typename Backend2, typename Backend3,\n                             /// result should fit in the output parameter\n                             typename = typename boost::enable_if_c<max_precision<Backend1>::value >=\n                                                                    max_precision<Backend>::value>::type>\n                    constexpr void montgomery_exp(Backend1& result, const Backend2& a, Backend3 exp) const {\n                        using default_ops::eval_eq;\n                        using default_ops::eval_lt;\n                        using default_ops::eval_multiply;\n\n                        // TODO: maybe reduce input parameter\n                        /// input parameter should be lesser than modulus\n                        // BOOST_ASSERT(eval_lt(a, get_mod().backend()));\n\n                        Backend_doubled_limbs tmp(static_cast<internal_limb_type>(1u));\n                        eval_multiply(tmp, get_r2());\n                        montgomery_reduce(tmp);\n                        Backend R_mod_m(tmp);\n\n                        Backend base(a);\n\n                        if (eval_eq(exp, static_cast<internal_limb_type>(0u))) {\n                            result = static_cast<internal_limb_type>(1u);\n                            //\n                            // TODO: restructure code\n                            // adjust_modular\n                            //\n                            eval_multiply(result, get_r2());\n                            montgomery_reduce(result);\n                            return;\n                        }\n                        if (eval_eq(get_mod().backend(), static_cast<internal_limb_type>(1u))) {\n                            result = static_cast<internal_limb_type>(0u);\n                            return;\n                        }\n\n                        while (true) {\n                            internal_limb_type lsb = exp.limbs()[0] & 1u;\n                            custom_right_shift(exp, static_cast<internal_limb_type>(1u));\n                            if (lsb) {\n                                montgomery_mul(R_mod_m, base);\n                                if (eval_eq(exp, static_cast<internal_limb_type>(0u))) {\n                                    break;\n                                }\n                            }\n                            montgomery_mul(base, base);\n                        }\n                        result = R_mod_m;\n                    }\n\n                    constexpr void swap(modular_functions_fixed& o) {\n                        get_mod().swap(o.get_mod());\n                        get_mu().swap(o.get_mu());\n                        get_r2().swap(o.get_r2());\n\n                        auto tmp_p_dash = get_p_dash();\n                        get_p_dash() = o.get_p_dash();\n                        o.get_p_dash() = tmp_p_dash;\n\n                        get_modulus_mask().swap(o.get_modulus_mask());\n                    }\n\n                    constexpr modular_functions_fixed& operator=(const modular_functions_fixed& o) {\n                        modular_functions_fixed tmp(o);\n                        swap(tmp);\n\n                        return *this;\n                    }\n\n                    constexpr modular_functions_fixed& operator=(const number_type& m) {\n                        initialize(m);\n\n                        return *this;\n                    }\n\n                protected:\n                    // TODO: replace number_type on backend type\n                    number_type m_mod;\n                    Backend_doubled_1 m_barrett_mu;\n                    Backend m_montgomery_r2;\n                    internal_limb_type m_montgomery_p_dash = 0;\n                    Backend_padded_limbs m_modulus_mask;\n                };\n\n            }    // namespace backends\n        }        // namespace multiprecision\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // BOOST_MULTIPRECISION_MODULAR_FUNCTIONS_FIXED_PRECISION_HPP\n", "meta": {"hexsha": "d24d94d332d3b0630cc3313b1cb5492725e87255", "size": 34900, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/include/nil/crypto3/multiprecision/modular/modular_functions_fixed.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/modular/modular_functions_fixed.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/modular/modular_functions_fixed.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": 50.288184438, "max_line_length": 120, "alphanum_fraction": 0.4659312321, "num_tokens": 5960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.02887090652849842, "lm_q1q2_score": 0.00877795877872729}}
{"text": "/*******************************************************************************\n *\n * Construction and management of weak topological orderings (WTOs).\n *\n * The construction of weak topological orderings is based on F. Bourdoncle's\n * paper: \"Efficient chaotic iteration strategies with widenings\", Formal\n * Methods in Programming and Their Applications, 1993, pages 128-141.\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_WTO_HPP\n#define IKOS_WTO_HPP\n\n#include <vector>\n#include <deque>\n#include <map>\n#include <boost/shared_ptr.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/container/slist.hpp>\n#include <crab/common/types.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/domains/intervals.hpp>\n\nnamespace ikos {\n\n  template< typename NodeName, typename CFG >\n  class wto;\n\n  template< typename NodeName, typename CFG >\n  class wto_vertex;\n\n  template< typename NodeName, typename CFG >\n  class wto_cycle;\n\n  template< typename NodeName, typename CFG >\n  class wto_component_visitor;\n\n  template< typename NodeName, typename CFG >\n  class wto_nesting: public writeable {\n    \n    friend class wto< NodeName, CFG >;\n    friend class wto_vertex< NodeName, CFG >;\n    friend class wto_cycle< NodeName, CFG >;\n    \n  public:\n    typedef wto_nesting< NodeName, CFG > wto_nesting_t;\n    \n  private:\n    typedef std::vector< NodeName > node_list_t;\n    typedef boost::shared_ptr< node_list_t > node_list_ptr;\n\n  private:\n    node_list_ptr _nodes;\n    \n  public:\n    class iterator: public boost::iterator_facade< iterator,\n                                                   NodeName&,\n                                                   boost::forward_traversal_tag,\n                                                   NodeName&> {\n      friend class boost::iterator_core_access;\n      \n    private:\n      typename node_list_t::iterator _it;\n      node_list_ptr _l;\n      \n    public:\n      iterator(node_list_ptr l, bool b): _it(b ? l->begin() : l->end()), _l(l) { }\n      \n    private:\n      void increment() { \n\t++(this->_it);\n      }\n      \n      bool equal(const iterator& other) const {\n\treturn (this->_l == other._l && this->_it == other._it);\n      }\n      \n      NodeName& dereference() const {\n\tif (this->_it != this->_l->end()) {\n\t  return *(this->_it);\n\t} else {\n\t  CRAB_ERROR(\"WTO nesting: trying to dereference an empty iterator\");\n\t}\n      }\n      \n    }; // class iterator\n    \n  private:\n    wto_nesting(node_list_ptr l): _nodes(boost::make_shared<node_list_t>(*l)) { }\n\n    int compare(wto_nesting_t& other) {\n      iterator this_it = this->begin(), other_it = other.begin();\n      while (this_it != this->end()) {\n\tif (other_it == other.end()) {\n\t  return 1;\n\t} else if (*this_it == *other_it) {\n\t  ++this_it;\n\t  ++other_it;\n\t} else {\n\t  return 2; // Nestings are not comparable\n\t}\n      }\n      if (other_it == other.end()) {\n\treturn 0;\n      } else {\n\treturn -1;\n      }\n    }\n    \n  public:\n    wto_nesting(): _nodes(boost::make_shared<node_list_t>()) { }\n\n    void operator+=(NodeName n) {\n      this->_nodes = boost::make_shared<node_list_t>(*(this->_nodes));\n      this->_nodes->push_back(n);\n    }\n    \n    wto_nesting_t operator+(NodeName n) {\n      wto_nesting_t res(this->_nodes);\n      res._nodes->push_back(n);\n      return res;\n    }\n\n    iterator begin() {\n      return iterator(this->_nodes, true);\n    }\n\n    iterator end() {\n      return iterator(this->_nodes, false);\n    }\n    \n    wto_nesting_t operator^(wto_nesting_t other) {\n      wto_nesting_t res;\n      for (iterator this_it = this->begin(), other_it = other.begin(); \n           this_it != this->end() && other_it != other.end(); \n           ++this_it, ++other_it) {\n        if (*this_it == *other_it) {\n          res._nodes->push_back(*this_it);\n        } else {\n          break;\n        }\n      }\n      return res;\n    }\n    \n    bool operator<=(wto_nesting_t other) {\n      return this->compare(other) <= 0;\n    }\n    \n    bool operator==(wto_nesting_t other) {\n      return this->compare(other) == 0;\n    }\n    \n    bool operator>=(wto_nesting_t other) {\n      return this->operator<=(other, *this);\n    }\n    \n    bool operator>(wto_nesting_t other) {\n      return this->compare(other) == 1;\n    }\n    \n    void write(crab::crab_os& o) {\n      o << \"[\";\n      for (iterator it = this->begin(); it != this->end(); ) {\n\tNodeName n = *it;\n\to << n;\n\t++it;\n\tif (it != this->end()) {\n\t  o << \", \";\n\t}\n      }\n      o << \"]\";\n    }\n    \n  }; // class nesting\n  \n  template< typename NodeName, typename CFG >\n  class wto_component: public writeable {\n\n  public:\n    typedef wto_nesting< NodeName, CFG > wto_nesting_t;\n    \n  public:\n    virtual void accept(wto_component_visitor< NodeName, CFG > *) = 0;\n\n    virtual ~wto_component() { }\n\n  }; // class wto_component\n\n  template< typename NodeName, typename CFG >\n  class wto_vertex: public wto_component< NodeName, CFG > {\n\n    friend class wto< NodeName, CFG >;\n\n  private:\n    NodeName _node;\n\n  private:\n    wto_vertex(NodeName node): _node(node) { }\n\n  public:\n    NodeName node() {\n      return this->_node;\n    }\n\n    void accept(wto_component_visitor< NodeName, CFG > *v) {\n      v->visit(*this);\n    }\n    \n    void write(crab::crab_os& o) {\n      o << this->_node;\n    }   \n\n  }; // class wto_vertex\n\n  template< typename NodeName, typename CFG >\n  class wto_cycle: public wto_component< NodeName, CFG > {\n\n    friend class wto< NodeName, CFG >;\n    \n  public:\n    typedef wto_component< NodeName, CFG > wto_component_t;\n    \n  private:\n    typedef boost::shared_ptr< wto_component_t > wto_component_ptr;\n    typedef boost::container::slist< wto_component_ptr > wto_component_list_t;\n    typedef boost::shared_ptr< wto_component_list_t > wto_component_list_ptr;\n\n  private:\n    NodeName _head;\n    wto_component_list_ptr _wto_components;\n    \n  private:\n    wto_cycle(NodeName head, \n              wto_component_list_ptr wto_components): \n        _head(head), _wto_components(wto_components) { }\n    \n  public:\n    class iterator: public boost::iterator_facade< iterator,\n                                                   wto_component_t&,\n                                                   boost::forward_traversal_tag,\n                                                   wto_component_t&> {\n      \n      friend class boost::iterator_core_access;\n      \n    private:\n      typename wto_component_list_t::iterator _it;\n      wto_component_list_ptr _l;\n      \n    public:\n      iterator(wto_component_list_ptr l, bool b): \n          _it(b ? l->begin() : l->end()), _l(l) { }\n      \n     private:\n      void increment() { \n        ++(this->_it);\n      }\n      \n      bool equal(const iterator& other) const {\n        return (this->_l == other._l && this->_it == other._it);\n      }\n      \n      wto_component_t& dereference() const {\n        if (this->_it != this->_l->end()) {\n          return **(this->_it);\n        } else {\n          CRAB_ERROR(\"WTO cycle: trying to dereference an empty iterator\");\n\t}\n      }\n      \n    }; // class iterator\n    \n  public:\n\n    NodeName head() {\n      return this->_head;\n    }\n    \n    void accept(wto_component_visitor< NodeName, CFG > *v) {\n      v->visit(*this);\n    }\n    \n    iterator begin() {\n      return iterator(this->_wto_components, true);\n    }\n    \n    iterator end() {\n      return iterator(this->_wto_components, false);\n    }\n    \n    void write(crab::crab_os& o) {\n      o << \"(\" << this->_head;\n      if (!this->_wto_components->empty()) {\n\to << \" \";\n\tfor (iterator it = this->begin(); it != this->end(); ) {\n\t  wto_component_t& c = *it;\n\t  o << c;\n\t  ++it;\n\t  if (it != this->end()) {\n\t    o << \" \";\n\t  }\n\t}\n      }\n      o << \")\";\n    }\n    \n  }; // class wto_cycle\n  \n  template< typename NodeName, typename CFG >\n  class wto_component_visitor {\n\n  public:\n    typedef wto_vertex< NodeName, CFG > wto_vertex_t;\n    typedef wto_cycle< NodeName, CFG > wto_cycle_t;\n\n  public:\n    virtual void visit(wto_vertex_t&) = 0;\n    virtual void visit(wto_cycle_t&) = 0;\n    virtual ~wto_component_visitor() {}\n\n  }; // class wto_component_visitor\n\n  template< typename NodeName, typename CFG >\n  class wto: public writeable {\n    \n  public:\n    typedef wto_nesting< NodeName, CFG > wto_nesting_t;\n    typedef wto_component< NodeName, CFG > wto_component_t;\n    typedef wto_vertex< NodeName, CFG > wto_vertex_t;\n    typedef wto_cycle< NodeName, CFG > wto_cycle_t;\n    typedef wto< NodeName, CFG > wto_t;\n  \n  private:\n    typedef boost::shared_ptr< wto_component_t > wto_component_ptr;\n    typedef boost::shared_ptr< wto_vertex_t > wto_vertex_ptr;\n    typedef boost::shared_ptr< wto_cycle_t > wto_cycle_ptr;\n    typedef boost::container::slist< wto_component_ptr > wto_component_list_t;\n    typedef boost::shared_ptr< wto_component_list_t > wto_component_list_ptr;\n    typedef bound< z_number > dfn_t;\n    typedef std::map< NodeName, dfn_t > dfn_table_t;\n    typedef boost::shared_ptr< dfn_table_t > dfn_table_ptr;\n    typedef std::deque< NodeName > stack_t;\n    typedef boost::shared_ptr< stack_t > stack_ptr;\n    typedef std::map< NodeName, wto_nesting_t > nesting_table_t;\n    typedef boost::shared_ptr< nesting_table_t > nesting_table_ptr;\n    \n  private:\n    wto_component_list_ptr _wto_components;\n    dfn_table_ptr _dfn_table;\n    dfn_t _num;\n    stack_ptr _stack;\n    nesting_table_ptr _nesting_table;\n\n  private:\n    class nesting_builder: public wto_component_visitor< NodeName, CFG > {\n      \n    public:\n      typedef wto_vertex< NodeName, CFG > wto_vertex_t;\n      typedef wto_cycle< NodeName, CFG > wto_cycle_t;\n      \n    private:\n      wto_nesting_t _nesting;\n      nesting_table_ptr _nesting_table;\n      \n    public:\n      nesting_builder(nesting_table_ptr nesting_table): \n          _nesting_table(nesting_table) { }\n\n      void visit(wto_cycle_t& cycle) {\n        NodeName head = cycle.head();\n        wto_nesting_t previous_nesting = this->_nesting;\n        this->_nesting_table->insert(std::make_pair(head, this->_nesting));\n        this->_nesting += head;\n        for (typename wto_cycle_t::iterator it = cycle.begin(); it != cycle.end(); ++it) {\n          it->accept(this);\n        }\n        this->_nesting = previous_nesting;\n      }\n      \n      void visit(wto_vertex_t& vertex) {\n        this->_nesting_table->insert(std::make_pair(vertex.node(), this->_nesting));\n      }\n      \n    }; // class nesting_builder\n\n  private:\n    dfn_t get_dfn(NodeName n) {\n      typename dfn_table_t::iterator it = this->_dfn_table->find(n);\n      if (it == this->_dfn_table->end()) {\n        return 0;\n      } else {\n        return it->second;\n      }\n    }\n    \n    void set_dfn(NodeName n, dfn_t dfn) {\n      std::pair< typename dfn_table_t::iterator, bool > res = \n          this->_dfn_table->insert(std::make_pair(n, dfn));\n      if (!res.second) {\n        (res.first)->second = dfn;\n      }\n    }\n    \n    NodeName pop() {\n      if (this->_stack->empty()) {\n        CRAB_ERROR(\"WTO computation: empty stack\");\n      } else {\n        NodeName top = this->_stack->back();\n        this->_stack->pop_back();\n        return top;\n      }\n    }\n\n    void push(NodeName n) {\n      this->_stack->push_back(n);\n    }\n\n    wto_cycle_ptr component(CFG cfg, NodeName vertex) {\n      auto partition = boost::make_shared<wto_component_list_t>();\n      auto next_nodes = cfg.next_nodes(vertex);\n      for (NodeName succ : next_nodes) {\n        if (this->get_dfn(succ) == 0) {\n          this->visit(cfg, succ, partition);\n        }\n      }\n      return wto_cycle_ptr(new wto_cycle_t(vertex, partition));\n    }\n    \n    dfn_t visit(CFG cfg, NodeName vertex, wto_component_list_ptr partition) {\n      dfn_t head = 0, min = 0;\n      bool loop;\n      NodeName element;\n\n      this->push(vertex);\n      this->_num += 1;\n      head = this->_num;\n      this->set_dfn(vertex, head);\n      loop = false;\n      auto next_nodes = cfg.next_nodes(vertex);\n      for (NodeName succ: next_nodes) {\n        dfn_t succ_dfn = this->get_dfn(succ);\n        if (succ_dfn == 0) {\n          min = this->visit(cfg, succ, partition);\n        } else {\n          min = succ_dfn;\n        }\n        if (min <= head) {\n          head = min;\n\t  loop = true;\n        }\n      }\n      if (head == this->get_dfn(vertex)) {\n        this->set_dfn(vertex, dfn_t::plus_infinity());\n        element = this->pop();\n        if (loop) {\n          while (!(element == vertex)) {\n            this->set_dfn(element, 0);\n            element = this->pop();\n          }\n          partition->push_front(boost::static_pointer_cast< wto_component_t, \n                                wto_cycle_t >(this->component(cfg, vertex)));\n        } else {\n          partition->push_front(boost::static_pointer_cast< wto_component_t, \n                                wto_vertex_t >(wto_vertex_ptr(new wto_vertex_t(vertex))));\n\t}\n      }\n      return head;\n    }\n    \n    void build_nesting() {\n      nesting_builder builder(this->_nesting_table);\n      for (iterator it = this->begin(); it != this->end(); ++it) {\n        it->accept(&builder);\n      }\n    }\n\n  public:\n    class iterator: public boost::iterator_facade< iterator,\n                                                   wto_component_t&,\n                                                   boost::forward_traversal_tag,\n                                                   wto_component_t&> {\n      \n      friend class boost::iterator_core_access;\n      \n     private:\n      typename wto_component_list_t::iterator _it;\n      wto_component_list_ptr _l;\n      \n     public:\n      iterator(wto_component_list_ptr l, bool b): \n          _it(b ? l->begin() : l->end()), _l(l) { }\n      \n    private:\n      void increment() { \n        ++(this->_it);\n      }\n      \n      bool equal(const iterator& other) const {\n        return (this->_l == other._l && this->_it == other._it);\n      }\n      \n      wto_component_t& dereference() const {\n        if (this->_it != this->_l->end()) {\n          return **(this->_it);\n        } else {\n          CRAB_ERROR(\"WTO: trying to dereference an empty iterator\");\n        }\n      }\n      \n    }; // class iterator    \n    \n  public:\n    wto(CFG cfg): \n        _wto_components(boost::make_shared<wto_component_list_t>()), \n        _dfn_table(boost::make_shared<dfn_table_t>()), \n        _num(0), _stack(boost::make_shared<stack_t>()), \n        _nesting_table(boost::make_shared<nesting_table_t>()) {\n      crab::ScopedCrabStats __st__(\"Fixpo.WTO\");\n\n      this->visit(cfg, cfg.entry(), this->_wto_components);\n      this->_dfn_table.reset();\n      this->_stack.reset();\n      this->build_nesting();\n    }\n\n    wto(const wto_t& other): _wto_components(other._wto_components), \n                             _nesting_table(other._nesting_table) { }\n\n    wto_t& operator=(wto_t other) {\n      this->_wto_components = other._wto_components;\n      this->_nesting_table = other._nesting_table;\n      return *this;\n    }\n\n    iterator begin() {\n      return iterator(this->_wto_components, true);\n    }\n\n    iterator end() {\n      return iterator(this->_wto_components, false);\n    }\n\n    wto_nesting_t nesting(NodeName n) {\n      typename nesting_table_t::iterator it = this->_nesting_table->find(n);\n      if (it == this->_nesting_table->end()) {\n        CRAB_ERROR(\"WTO nesting: node \", n,\" not found\");\n      } else {\n        return it->second;\n      }\n    }\n\n    void accept(wto_component_visitor< NodeName, CFG > *v) {\n      for (iterator it = this->begin(); it != this->end(); ++it) {\n        it->accept(v);\n      }\n    }\n    \n    void write(crab::crab_os& o) {\n      for (iterator it = this->begin(); it != this->end(); ) {\n        wto_component_t& c = *it;\n        o << c;\n        ++it;\n        if (it != this->end()) {\n          o << \" \";\n        }\n      }\n    }    \n    \n  }; // class wto\n\n} // namespace ikos\n\n#endif // IKOS_WTO_HPP\n", "meta": {"hexsha": "07f63884f5f228f54e7325843cd9490d811128a0", "size": 17752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/iterators/wto.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/iterators/wto.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/iterators/wto.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": 29.1973684211, "max_line_length": 90, "alphanum_fraction": 0.5972284813, "num_tokens": 4534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.02976009685023655, "lm_q1q2_score": 0.008755866066360196}}
{"text": "/**\n * @file validate.cpp\n * @brief This contains utility function validate things like forward kinematics match inverse kinematics\n *\n * @author Levi Armstrong\n * @date April 15, 2018\n * @version TODO\n * @bug No known bugs\n *\n * @copyright Copyright (c) 2013, 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 <Eigen/Geometry>\n#include <console_bridge/console.h>\n#include <algorithm>\n#include <sstream>\nTESSERACT_COMMON_IGNORE_WARNINGS_POP\n\n#include <tesseract_common/utils.h>\n#include <tesseract_kinematics/core/validate.h>\n\nnamespace tesseract_kinematics\n{\nbool checkKinematics(const KinematicGroup& manip, double tol)\n{\n  Eigen::Isometry3d test1;\n  Eigen::Isometry3d test2;\n  Eigen::VectorXd seed_angles(manip.numJoints());\n  Eigen::VectorXd joint_angles2(manip.numJoints());\n  std::vector<std::string> tip_links = manip.getAllPossibleTipLinkNames();\n  std::vector<std::string> working_frames = manip.getAllValidWorkingFrames();\n  const int nj = static_cast<int>(manip.numJoints());\n\n  std::vector<std::vector<double>> passed_data;\n  std::vector<std::vector<double>> failed_data;\n  int translation_failures{ 0 };\n  int angular_failures{ 0 };\n  double translation_max{ 0 };\n  double angular_max{ 0 };\n\n  std::vector<std::pair<std::string, std::string>> checks;\n  checks.reserve(tip_links.size() + working_frames.size());\n\n  for (const auto& tip_link : tip_links)\n    checks.emplace_back(working_frames[0], tip_link);\n\n  for (const auto& working_frame : working_frames)\n    checks.emplace_back(working_frame, tip_links[0]);\n\n  for (const auto& check : checks)\n  {\n    seed_angles.setZero();\n    joint_angles2.setZero();\n\n    for (int t = 0; t < nj; ++t)\n    {\n      joint_angles2[t] = M_PI_4;\n\n      auto poses1 = manip.calcFwdKin(joint_angles2);\n      test1 = poses1.at(check.first).inverse() * poses1.at(check.second);\n      KinGroupIKInput ik_input(test1, check.first, check.second);\n      IKSolutions sols = manip.calcInvKin({ ik_input }, seed_angles);\n      for (const auto& sol : sols)\n      {\n        auto poses2 = manip.calcFwdKin(sol);\n        test2 = poses2.at(check.first).inverse() * poses2.at(check.second);\n\n        double translation_distance = (test1.translation() - test2.translation()).norm();\n        double angular_distance =\n            Eigen::Quaterniond(test1.linear()).angularDistance(Eigen::Quaterniond(test2.linear()));\n        if (translation_distance > tol || angular_distance > tol)\n        {\n          if (translation_distance > tol)\n            ++translation_failures;\n\n          if (angular_distance > tol)\n            ++angular_failures;\n\n          if (angular_distance > angular_max)\n            angular_max = angular_distance;\n\n          if (translation_distance > translation_max)\n            translation_max = translation_distance;\n\n          std::vector<double> data{ translation_distance, tol, angular_distance, tol };\n          for (Eigen::Index i = 0; i < sol.rows(); ++i)\n            data.push_back(sol(i));\n\n          failed_data.push_back(data);\n        }\n        else\n        {\n          std::vector<double> data{ translation_distance, tol, angular_distance, tol };\n          for (Eigen::Index i = 0; i < sol.rows(); ++i)\n            data.push_back(sol(i));\n\n          passed_data.push_back(data);\n        }\n      }\n\n      joint_angles2[t] = 0;\n    }\n  }\n\n  if (!failed_data.empty())\n  {\n    CONSOLE_BRIDGE_logError(\"checkKinematics failed %d out of %d\\n           Translation failures %d out of %d (max: \"\n                            \"%f)\\n           Angular failures %d out of %d (max: %f)\",\n                            failed_data.size(),\n                            (failed_data.size() + passed_data.size()),\n                            translation_failures,\n                            failed_data.size(),\n                            translation_max,\n                            angular_failures,\n                            failed_data.size(),\n                            angular_max);\n    std::stringstream msg;\n    msg << std::endl;\n    msg << \"*****************************\" << std::endl;\n    msg << \"******** Failed Data ********\" << std::endl;\n    msg << \"*****************************\" << std::endl;\n\n    std::string header = \"Trans. Dist. (m), tol, Angle Dist. (rad), tol\";\n    for (const auto& jn : manip.getJointNames())\n      header += \", \" + jn;\n\n    msg << header << std::endl;\n    for (const auto& d : failed_data)\n    {\n      for (const auto& val : d)\n        msg << val << \", \";\n      msg << std::endl;\n    }\n\n    msg << \"*****************************\" << std::endl;\n    msg << \"******** Passed Data ********\" << std::endl;\n    msg << \"*****************************\" << std::endl;\n    if (passed_data.empty())\n    {\n      msg << \"No Data!\" << std::endl;\n    }\n    else\n    {\n      for (const auto& d : passed_data)\n      {\n        for (const auto& val : d)\n          msg << val << \", \";\n        msg << std::endl;\n      }\n    }\n\n    CONSOLE_BRIDGE_logError(\"%s\", msg.str().c_str());\n    return false;\n  }\n\n  return true;\n}\n}  // namespace tesseract_kinematics\n", "meta": {"hexsha": "9c1340e5696e4701762389ab29fd2d55d5d3f97e", "size": 5722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tesseract_kinematics/core/src/validate.cpp", "max_stars_repo_name": "daoran/tesseract", "max_stars_repo_head_hexsha": "2c593d12a0a470bd2672fdf6ff86843dd69b6e4a", "max_stars_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "Apache-2.0"], "max_stars_count": 118.0, "max_stars_repo_stars_event_min_datetime": "2018-07-10T13:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T20:39:32.000Z", "max_issues_repo_path": "tesseract_kinematics/core/src/validate.cpp", "max_issues_repo_name": "daoran/tesseract", "max_issues_repo_head_hexsha": "2c593d12a0a470bd2672fdf6ff86843dd69b6e4a", "max_issues_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "Apache-2.0"], "max_issues_count": 493.0, "max_issues_repo_issues_event_min_datetime": "2018-08-06T13:24:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T19:18:16.000Z", "max_forks_repo_path": "tesseract_kinematics/core/src/validate.cpp", "max_forks_repo_name": "daoran/tesseract", "max_forks_repo_head_hexsha": "2c593d12a0a470bd2672fdf6ff86843dd69b6e4a", "max_forks_repo_licenses": ["BSD-3-Clause", "BSD-2-Clause", "Apache-2.0"], "max_forks_count": 60.0, "max_forks_repo_forks_event_min_datetime": "2018-07-11T07:32:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T07:42:05.000Z", "avg_line_length": 32.6971428571, "max_line_length": 118, "alphanum_fraction": 0.6001398113, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421498454004374, "lm_q2_score": 0.02976009082656091, "lm_q1q2_score": 0.008755864662446915}}
{"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 <engine/map/dungeonlayout.hpp>\n\n#include <boost/multi_index_container.hpp>\n#include <boost/multi_index/hashed_index.hpp>\n#include <boost/multi_index/ordered_index.hpp>\n#include <boost/multi_index/member.hpp>\n#include <boost/multi_index/identity.hpp>\n\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/function_property_map.hpp>\n\n#include <boost/geometry/index/rtree.hpp>\n#include <math/geometrytraits.hpp>\n#include <math/mathtools.hpp>\n\n#include <math/segment.hpp>\n\n#include <math/polygon_def.hpp>\n\n#include <gen/graphutils.hpp>\nnamespace eXl\n{\n  using RoomIndexEntry = std::pair<AABB2Di, uint32_t>;\n  using RoomIndex = boost::geometry::index::rtree<RoomIndexEntry, boost::geometry::index::linear<16, 4>>;\n\n  typedef DungeonGraph::Graph Graph;\n  typedef Graph::vertex_descriptor Vertex;\n  typedef Graph::edge_descriptor Edge;\n\n  //struct NodeWithDegree\n  //{\n  //  Vertex vtx;\n  //  uint32_t degree;\n  //};\n  //\n  //struct NodeIdentity\n  //{\n  //  typedef Vertex result_type;\n  //  result_type operator()(NodeWithDegree const& iEntry) const\n  //  {\n  //    return iEntry.vtx;\n  //  }\n  //};\n  //\n  //struct NodeDegree\n  //{\n  //  typedef uint32_t result_type;\n  //  result_type operator()(NodeWithDegree const& iEntry) const\n  //  {\n  //    return iEntry.degree;\n  //  }\n  //};\n  //\n  //typedef boost::multi_index::multi_index_container<NodeWithDegree,\n  //  boost::multi_index::indexed_by<\n  //  boost::multi_index::hashed_unique<NodeIdentity>\n  //  ,boost::multi_index::ordered_non_unique<NodeDegree>\n  //  >  \n  //> NodeDegreeMap;\n\n  struct PhysicalNodesFilter\n  {\n    PhysicalNodesFilter()\n    {}\n\n    PhysicalNodesFilter(DungeonGraph const& iGraph)\n      : m_Graph(&iGraph)\n    {}\n\n    bool operator()(const DungeonGraph::GraphVtx& e) const\n    {\n      DungeonGraph::NodeProperties const* props = m_Graph->GetProperties(e);\n      return props->IsPhysical() && props->GetSize() > 0;\n    }\n\n    bool operator()(const DungeonGraph::GraphEdge& e) const\n    {\n      return m_Graph->GetProperties(e)->m_PhysicalConnection;\n    }\n\n    DungeonGraph const* m_Graph;\n  };\n\n  struct MSTFilter\n  {\n    MSTFilter()\n    {}\n\n    MSTFilter(Set<Edge> const& iEdges)\n      :m_Edges(&iEdges)\n    {}\n\n    template <typename Edge>\n    bool operator()(const Edge& e) const\n    {\n      return m_Edges->count(e) > 0;\n    }\n    Set<Edge> const* m_Edges;\n  };\n\n  struct GraphFilter\n  {\n    GraphFilter()\n    {}\n\n    GraphFilter(Set<Vertex> const& iVtx)\n      :m_Vtx(&iVtx)\n    {}\n\n    bool operator()(const Vertex& vtx) const\n    {\n      return m_Vtx->count(vtx) > 0;\n    }\n    Set<Vertex> const* m_Vtx;\n  };\n\n  namespace\n  {\n\n    int const s_DoorSize = 4;\n    int const s_MaxRoomSize = 5;\n\n    Vector2i SampleRoom(DungeonGraph const& iGraph, Vertex iVtx, Random& iRand)\n    {\n      DungeonGraph::NodeProperties const* props = iGraph.GetProperties(iVtx);\n\n      Vector2i baseSize = Vector2i(iRand() % 10 + 4, iRand() % 10 + 4);\n\n      //uint32_t const roomSize = Mathi::Min(s_MaxRoomSize, props != nullptr ? props->GetSize() : 1);\n      //\n      //Vector2i baseSize = Vector2i::ONE * 2 * (roomSize + 1);\n      //\n      //switch(iRand() % 3)\n      //{\n      //case 0:\n      //  baseSize += Vector2i::ONE * Mathi::Max(roomSize / 4, 1);\n      //  break;\n      //case 1:\n      //  baseSize.m_Data[0] += roomSize / 2;\n      //  break;\n      //case 2:\n      //  baseSize.m_Data[1] += roomSize / 2;\n      //  break;\n      //}\n      return baseSize;\n    };\n\n    void AddRoomConfSpace(Vector2i const& iBoxToLayoutSize, AABB2Di const& iBox, Vector<Segmenti>& oSegs) \n    {\n      for(int dim = 0; dim<2; ++dim)\n      {\n        int otherDim = 1 - dim;\n        Segmenti minSeg;\n        minSeg.m_Ext1 = minSeg.m_Ext2 = iBox.m_Data[0];\n        minSeg.m_Ext1.m_Data[otherDim] -= iBoxToLayoutSize.m_Data[otherDim];\n        minSeg.m_Ext2 = minSeg.m_Ext1;\n        minSeg.m_Ext2.m_Data[dim] = iBox.m_Data[1].m_Data[dim];\n\n        minSeg.m_Ext1.m_Data[dim] -= (iBoxToLayoutSize.m_Data[dim] - s_DoorSize);\n        minSeg.m_Ext2.m_Data[dim] -= s_DoorSize;\n\n        oSegs.push_back(minSeg);\n\n        Segmenti maxSeg = minSeg;\n        maxSeg.m_Ext1.m_Data[otherDim] = maxSeg.m_Ext2.m_Data[otherDim] = iBox.m_Data[1].m_Data[otherDim];\n\n        oSegs.push_back(maxSeg);\n      }\n    };\n\n    Vector<Segmentf> MergeConfSpace (Vector<Segmentf> const& iSpace1, Vector<Segmentf> const& iSpace2)\n    {\n      Vector<Segmentf> result;\n      for(auto const& seg1 : iSpace1)\n      {\n        bool seg1IsPoint = seg1.m_Ext1 == seg1.m_Ext2;\n        for(auto const& seg2 : iSpace2)\n        {\n          bool seg2IsPoint = seg2.m_Ext1 == seg2.m_Ext2;\n          if(seg1IsPoint)\n          {\n            if(seg2IsPoint)\n            {\n              if(seg1 == seg2)\n              {\n                result.push_back(seg1);\n              }\n            }\n            else\n            {\n              if(seg2.IsOnSegment(seg1.m_Ext1))\n              {\n                result.push_back(seg1);\n              }\n            }\n          }\n          else\n          {\n            if(seg2IsPoint)\n            {\n              if(seg1.IsOnSegment(seg2.m_Ext1))\n              {\n                result.push_back(seg2);\n              }\n            }\n            else\n            {\n              Vector2f oPoint;\n              uint32_t res = seg1.Intersect(seg2, oPoint);\n              if((res & Segmentf::PointOnSegments) == Segmentf::PointOnSegments)\n              {\n                //Intersection limited to a point.\n                Segmentf resultSegment;\n                resultSegment.m_Ext1 = resultSegment.m_Ext2 = oPoint;\n                result.push_back(resultSegment);\n              }\n              else if(res & Segmentf::ConfoundSegments)\n              {\n                Segmentf resultSegment;\n                //Segments overlap.\n                if(seg1.IsOnSegment(seg2.m_Ext1))\n                {\n                  resultSegment.m_Ext1 = seg2.m_Ext1;\n                }\n                else\n                {\n                  resultSegment.m_Ext1 = seg2.m_Ext2;\n                }\n\n                if(seg2.IsOnSegment(seg1.m_Ext1))\n                {\n                  resultSegment.m_Ext2 = seg1.m_Ext1;\n                }\n                else\n                {\n                  resultSegment.m_Ext2 = seg1.m_Ext2;\n                }\n              }\n            }\n          }\n        }\n      }\n\n      return result;\n    };\n  }\n\n  void ComputeMaxConfSpace(Vector<Segmenti>& ioConfSpace)\n  {\n    unsigned int const s_NumSegPerRoom = 4;\n\n    //Compute maximum configuration space.\n    Vector<std::pair<size_t, Segmenti>> segments;\n    boost::polygon::intersect_segments(segments, ioConfSpace.begin(), ioConfSpace.end());\n\n    //Create graph of connected segments and get the biggest connected component.\n    Map<Vector2i, uint32_t> pointMap;\n    Vector<Vector2i> vertices;\n    Vector<Segmenti> edges;\n    Vector<Set<uint32_t>> vtxMap;\n    Vector<Set<uint32_t>>  edgeMap;\n    Map<std::pair<uint32_t, uint32_t>, uint32_t> connections;\n    uint32_t numEdges = 0;\n    uint32_t numVtx = 0;\n\n    for(auto const& seg : segments)\n    {\n      auto insertRes = pointMap.insert(std::make_pair(seg.second.m_Ext1, numVtx));\n      if(insertRes.second)\n      {\n        ++numVtx;\n        vertices.push_back(seg.second.m_Ext1);\n        vtxMap.push_back(Set<uint32_t>());\n      }\n      auto vtx1 = insertRes.first->second;\n      vtxMap[vtx1].insert(seg.first / s_NumSegPerRoom);\n\n      insertRes = pointMap.insert(std::make_pair(seg.second.m_Ext2, numVtx));\n      if(insertRes.second)\n      {\n        ++numVtx;\n        vertices.push_back(seg.second.m_Ext1);\n        vtxMap.push_back(Set<uint32_t>());\n      }\n      auto vtx2 = insertRes.first->second;\n      vtxMap[vtx2].insert(seg.first / s_NumSegPerRoom);\n\n      auto edgeDesc = std::make_pair(vtx1, vtx2);\n      if(edgeDesc.first > edgeDesc.second)\n      {\n        std::swap(edgeDesc.first, edgeDesc.second);\n      }\n      auto newEdge = connections.insert(std::make_pair(edgeDesc, numEdges));\n      if(newEdge.second)\n      {\n        ++numEdges;\n        edges.push_back(seg.second);\n        edgeMap.push_back(Set<uint32_t>());\n      }\n      edgeMap[newEdge.first->second].insert(seg.first / s_NumSegPerRoom);\n    }\n\n    ioConfSpace.clear();\n\n    uint32_t maxScore = 0;\n    for(auto const& entry : vtxMap)\n    {\n      auto curScore = entry.size();\n      if(curScore > maxScore)\n      {\n        maxScore = curScore;\n      }\n    }\n    for(auto const& edge : connections)\n    {\n      if(edgeMap[edge.second].size() == maxScore)\n      {\n        ioConfSpace.push_back(edges[edge.second]);\n        vtxMap[edge.first.first].clear();\n        vtxMap[edge.first.second].clear();\n      }\n    }\n\n    for(auto const& vtx : pointMap)\n    {\n      if(vtxMap[vtx.second].size() == maxScore)\n      {\n        ioConfSpace.push_back({vtx.first, vtx.first});\n      }\n    }\n  }\n\n  Vector<Segmenti> CullConfigurationSpace(Vector2i const& iRoomSize, Vector<Segmenti> const& iConfSpace, RoomIndex const& iRoomIndex)\n  {\n    Vector<Segmenti> finalConfSpace;\n    Vector<RoomIndexEntry> results;\n    for(auto const& seg : iConfSpace)\n    {\n      results.clear();\n      if(seg.m_Ext1 == seg.m_Ext2)\n      {\n        AABB2Di boxToTest(seg.m_Ext1, iRoomSize);\n        iRoomIndex.query(boost::geometry::index::overlaps(boxToTest), std::back_inserter(results));\n        for(auto& result : results)\n        {\n          if(boxToTest.Intersect(result.first))\n            continue;\n        }\n        finalConfSpace.push_back(seg);\n      }\n      else\n      {\n        int dim = seg.m_Ext1.m_Data[0] != seg.m_Ext2.m_Data[0] ? 0 : 1;\n        int otherDim = 1 - dim;\n\n        int minSeg = seg.m_Ext1.m_Data[dim] < seg.m_Ext2.m_Data[dim] ? 0 : 1;\n        int maxSeg = 1 - minSeg;\n\n        Vector2i const* segPts = reinterpret_cast<Vector2i const*>(&seg);\n        AABB2Di boxToTest;\n        boxToTest.m_Data[0] = segPts[minSeg];\n        boxToTest.m_Data[1] = segPts[maxSeg] + iRoomSize;\n\n        Segmenti finalSeg;\n        finalSeg.m_Ext1 = segPts[minSeg];\n        finalSeg.m_Ext2 = segPts[maxSeg];\n\n        Vector<AABB2Di> interBoxes;\n\n        iRoomIndex.query(boost::geometry::index::overlaps(boxToTest), std::back_inserter(results));\n        for(auto& result : results)\n        {\n          if(boxToTest.Intersect(result.first))\n          {\n            AABB2Di intersection;\n            intersection.SetCommonBox(result.first, boxToTest);\n\n            interBoxes.push_back(intersection);\n          }\n        }\n\n        std::sort(interBoxes.begin(), interBoxes.end(), [dim](AABB2Di const& iBox1, AABB2Di const& iBox2)\n        {\n          return iBox1.m_Data[0].m_Data[dim] < iBox2.m_Data[0].m_Data[dim];\n        });\n\n        for(auto& box : interBoxes)\n        {\n          if(box.m_Data[0].m_Data[dim] <= finalSeg.m_Ext1.m_Data[dim])\n          {\n            finalSeg.m_Ext1.m_Data[dim] = Mathi::Max(box.m_Data[1].m_Data[dim], finalSeg.m_Ext1.m_Data[dim]);\n          }\n          else \n          {\n            if(box.m_Data[0].m_Data[dim] > finalSeg.m_Ext1.m_Data[dim] + iRoomSize.m_Data[dim])\n            {\n              Segmenti seg;\n              seg.m_Ext1 = seg.m_Ext2 = finalSeg.m_Ext1;\n              seg.m_Ext2.m_Data[dim] = box.m_Data[0].m_Data[dim] - iRoomSize.m_Data[dim];\n\n              finalConfSpace.push_back(seg);\n            }\n\n            finalSeg.m_Ext1.m_Data[dim] = box.m_Data[1].m_Data[dim];\n          }\n        }\n\n        if(finalSeg.m_Ext2.m_Data[dim] - finalSeg.m_Ext1.m_Data[dim] > 0)\n        {\n          finalConfSpace.push_back(finalSeg);\n        }\n      }\n    }\n\n    return finalConfSpace;\n  }\n\n  struct RoomViolation\n  {\n    Map<uint32_t, float> m_Overlaps;\n    Map<uint32_t, float> m_MissingDoor;\n  };\n\n  //Insert the room and compute its energy regarding collision against other rooms.\n  template <typename FilteredGraph>\n  void InsertRoomAndUpdateViolations(Vertex iVtx, uint32_t const iRoomIdx, AABB2Di const& iRoom, \n    RoomIndex& iRoomIndex, Map<uint32_t, RoomViolation>& oMap, \n    FilteredGraph const& iGraph, Map<Vertex, uint32_t> const& iVtxToRoom, Layout const& iCurLayout)\n  {\n    Vector<RoomIndexEntry> results;\n    Set<uint32_t> touchingRooms;\n\n    iRoomIndex.query(\n      boost::geometry::index::intersects(iRoom),\n      std::back_inserter(results));\n\n    float totArea = 0;\n    for(auto const& entry : results)\n    {\n      AABB2Di intersectionBox;\n      intersectionBox.SetCommonBox(iRoom, entry.first);\n\n      auto size = intersectionBox.GetSize();\n\n      if(size.X() > 0 || size.Y() > 0)\n      {\n        if(size.X() * size.Y() == 0)\n        {\n          if(size.X() + size.Y() >= s_DoorSize)\n          {\n            touchingRooms.insert(entry.second);\n          }\n        }\n        else\n        {\n          float curArea = size.X() * size.Y();\n          if(curArea > 0)\n          {\n            totArea += curArea;\n            if(size.X() >= s_DoorSize || size.Y() >= s_DoorSize)\n            {\n              touchingRooms.insert(entry.second);\n            }\n\n            auto insertRes = oMap.insert(std::make_pair(entry.second, RoomViolation()));\n            insertRes.first->second.m_Overlaps[iRoomIdx] = curArea;\n\n            insertRes = oMap.insert(std::make_pair(iRoomIdx, RoomViolation()));\n            insertRes.first->second.m_Overlaps[entry.second] = curArea;\n          }\n        }\n      }\n    }\n\n    iRoomIndex.insert(std::make_pair(iRoom, iRoomIdx));\n\n    Vector2f center1 = MathTools::ToFVec(iRoom.m_Data[0]) + MathTools::ToFVec(iRoom.GetSize()) * 0.5;\n\n    for(auto edge : OutEdgesIter(iGraph, iVtx))\n    {\n      Vertex target = GetTarget(iVtx, edge);\n      uint32_t neighIdx = iVtxToRoom.find(target)->second;\n\n      auto const& neightRoom = iCurLayout[neighIdx].m_Box;\n\n      if(touchingRooms.count(neighIdx) == 0)\n      {\n        Vector2f center2 = MathTools::ToFVec(neightRoom.m_Data[0]) + MathTools::ToFVec(neightRoom.GetSize()) * 0.5;\n        float sqDist = (center2 - center1).SquaredLength();\n\n        auto insertRes = oMap.insert(std::make_pair(neighIdx, RoomViolation()));\n        insertRes.first->second.m_MissingDoor[iRoomIdx] = sqDist;\n\n        insertRes = oMap.insert(std::make_pair(iRoomIdx, RoomViolation()));\n        insertRes.first->second.m_MissingDoor[neighIdx] = sqDist;\n      }\n    }\n  }\n\n  void RemoveRoomAndUpdateViolations(uint32_t const iRoomIdx, AABB2Di const& iRoom, RoomIndex& iRoomIndex, Map<uint32_t, RoomViolation>& oMap)\n  {\n    iRoomIndex.remove(RoomIndexEntry(iRoom, iRoomIdx));\n\n    auto violations = oMap.find(iRoomIdx);\n    if(violations != oMap.end())\n    {\n      for(auto overlap : violations->second.m_Overlaps)\n      {\n        auto otherViolation = oMap.find(overlap.first);\n        if(otherViolation != oMap.end())\n        {\n          otherViolation->second.m_Overlaps.erase(iRoomIdx);\n        }\n      }\n      for(auto missingDoor : violations->second.m_MissingDoor)\n      {\n        auto otherViolation = oMap.find(missingDoor.first);\n        if(otherViolation != oMap.end())\n        {\n          otherViolation->second.m_MissingDoor.erase(iRoomIdx);\n        }\n      }\n      oMap.erase(violations);\n    }\n  }\n\n  AABB2Di SampleConfigurationSpace(Vector2i const& iRoomSize, Random& iRand, Vector<Segmenti> const& iConfSpace, RoomIndex const& iRoomIndex)\n  {\n    Vector<Segmenti> culledConfSpace = CullConfigurationSpace(iRoomSize, iConfSpace, iRoomIndex);\n\n    Vector<Segmenti> const& confSpace = (culledConfSpace.empty() ? iConfSpace : culledConfSpace);\n\n    Multimap<float, AABB2Di> sampledPos;\n    while(sampledPos.size() < 20)\n    {\n      // Should try to get a uniform sampling.\n      auto const& seg = confSpace[iRand() % confSpace.size()];\n      Vector2i roomOrigin;\n      if(seg.m_Ext1 != seg.m_Ext2)\n      {\n        Vector2i segDir = seg.m_Ext2 - seg.m_Ext1;\n        uint32_t segLen = Mathi::Abs(Mathi::Max(segDir.X(), segDir.Y()));\n        segDir /= segLen;\n        segLen = iRand() % segLen;\n\n        roomOrigin = seg.m_Ext1 + segDir * segLen;\n      }\n      else\n      {\n        roomOrigin = seg.m_Ext1;\n      }\n\n      AABB2Di newBox;\n      newBox.m_Data[0] = roomOrigin;\n      newBox.m_Data[1] = roomOrigin + iRoomSize;\n\n      Vector<RoomIndexEntry> results;\n\n      iRoomIndex.query(\n        boost::geometry::index::intersects(newBox),\n        std::back_inserter(results));\n\n      float totArea = 0;\n      for(auto const& entry : results)\n      {\n        AABB2Di intersectionBox;\n        intersectionBox.SetCommonBox(newBox, entry.first);\n\n        auto size = intersectionBox.GetSize();\n\n        totArea += size.X() * size.Y();\n      }\n\n      sampledPos.insert(std::make_pair(totArea, newBox));\n\n      if(totArea == 0)\n        break;\n    }\n\n    return sampledPos.begin()->second;\n  }\n\n  using PhysicalGraph = boost::filtered_graph<Graph, PhysicalNodesFilter, PhysicalNodesFilter>;\n\n  Vector<Vector<Vertex>> GetChainList(/*DungeonGraph const& iGraph, */PhysicalGraph const& graph)\n  {\n    auto const& idxMap = boost::get(boost::vertex_index, graph);\n\n    //Test if the graph can be layout.\n    if (!boost::boyer_myrvold_planarity_test(graph))\n    {\n      return Vector<Vector<Vertex>>();\n    }\n    Vector<Vector<Vertex>> cycles;\n    Vector<Vector<Vertex>> chains;\n\n    Set<Edge> origEdges;\n    for (auto edges = boost::edges(graph); edges.first != edges.second; ++edges.first)\n    {\n      origEdges.insert(*edges.first);\n    }\n\n    auto dummyWhFunc = [](Edge) {return 1.0; };\n\n    Set<Edge> mstEdges;\n    boost::kruskal_minimum_spanning_tree(graph, std::inserter(mstEdges, mstEdges.begin()),\n      boost::weight_map(boost::make_function_property_map<Edge>(dummyWhFunc)).vertex_index_map(idxMap));\n\n    //--> Could replace it with a planar embedding and process faces.\n    Set<Edge> cycleEdges;\n    std::set_difference(origEdges.begin(), origEdges.end(), mstEdges.begin(), mstEdges.end(), std::inserter(cycleEdges, cycleEdges.begin()));\n\n    //NodeDegreeMap nodeDegreeMap;\n    Map<Vertex, uint32_t> nodeDegreeMap;\n    for (auto vtx : VerticesIter(graph))\n    {\n      nodeDegreeMap.insert({ vtx, uint32_t(boost::degree(vtx, graph)) });\n    }\n\n    MSTFilter filter(mstEdges);\n\n    boost::filtered_graph<PhysicalGraph, MSTFilter, boost::keep_all> filteredGr(graph, filter, boost::keep_all());\n\n    for (auto edge : cycleEdges)\n    {\n      Vector<Vertex> newCycle;\n      Vertex ext1 = edge.m_source;\n      Vertex ext2 = edge.m_target;\n\n      Vector<Vertex> p(boost::num_vertices(filteredGr), ext1);\n      Vector<float> d(boost::num_vertices(filteredGr));\n\n      boost::dijkstra_shortest_paths(filteredGr, ext1,\n        boost::make_iterator_property_map(p.begin(), idxMap),\n        boost::make_iterator_property_map(d.begin(), idxMap),\n        boost::make_function_property_map<Edge>(dummyWhFunc),\n        idxMap,\n        std::less<float>(), boost::closed_plus<float>(), Mathf::MAX_REAL, 0.0, boost::dijkstra_visitor<boost::null_visitor>());\n\n      float dist1 = d[idxMap[ext1]];\n      float dist2 = d[idxMap[ext2]];\n\n      Vertex farthestVtx = dist1 > dist2 ? ext1 : ext2;\n      Vertex nearestVtx = dist1 > dist2 ? ext2 : ext1;\n\n      do\n      {\n        newCycle.push_back(farthestVtx);\n        farthestVtx = p[idxMap[farthestVtx]];\n      } while (farthestVtx != nearestVtx);\n\n      newCycle.push_back(farthestVtx);\n\n      cycles.emplace_back(std::move(newCycle));\n    }\n\n    std::sort(cycles.begin(), cycles.end(),\n      [](Vector<Vertex> const& iCycle1, Vector<Vertex> const& iCycle2)\n    {\n      return iCycle1.size() < iCycle2.size();\n    });\n\n    for (int i = 0; i < (int)cycles.size(); ++i)\n    {\n      bool cycleNested = false;\n      auto& curCycle = cycles[i];\n      auto cycleCopy = curCycle;\n      for (auto& vtx : curCycle)\n      {\n        for (auto outEdge : OutEdgesIter(graph, vtx))\n        {\n          auto entry = nodeDegreeMap.find(outEdge.m_target);\n          if (entry != nodeDegreeMap.end())\n          {\n            entry->second--;\n          }\n          //auto entry = nodeDegreeMap.get<0>().find(outEdge.m_target);\n          //if (entry != nodeDegreeMap.get<0>().end())\n          //{\n          //  NodeWithDegree node = *entry;\n          //  node.degree--;\n          //  nodeDegreeMap.replace(entry, node);\n          //}\n        }\n        if (nodeDegreeMap.count(vtx) == 0)\n        {\n          cycleNested = true;\n          vtx = Graph::null_vertex();\n        }\n        else\n        {\n          nodeDegreeMap.erase(vtx);\n        }\n      }\n\n      //Consecutive sequences of non-null vertices are chains to add.\n      if (cycleNested)\n      {\n        Vector<Vertex> newChain;\n        for (int i = -1; i < (int)curCycle.size(); ++i)\n        {\n          int loopedIdx = i >= 0 ? i : curCycle.size() - 1;\n          Vertex vtx = curCycle[loopedIdx];\n\n          if (vtx != Graph::null_vertex())\n          {\n            newChain.push_back(vtx);\n          }\n          else\n          {\n            if (!newChain.empty())\n            {\n              // Add vertex for connection.\n              newChain.push_back(cycleCopy[loopedIdx]);\n              chains.emplace_back(std::move(newChain));\n            }\n          }\n        }\n\n        if (!newChain.empty())\n        {\n          chains.emplace_back(std::move(newChain));\n        }\n\n        cycles[i] = std::move(cycles.back());\n        cycles.pop_back();\n        --i;\n      }\n    }\n\n    Vertex pathSearchStartVtx = Graph::null_vertex();\n    for (auto vtx : VerticesIter(filteredGr))\n    {\n      auto edges = boost::out_edges(vtx, filteredGr);\n      if (std::distance(edges.first, edges.second) == 1)\n      {\n        pathSearchStartVtx = vtx;\n        break;\n      }\n    }\n\n    if (pathSearchStartVtx != Graph::null_vertex())\n    {\n      Vector<Vertex> p(boost::num_vertices(filteredGr), pathSearchStartVtx);\n      Vector<float> d(boost::num_vertices(filteredGr));\n\n      boost::dijkstra_shortest_paths(filteredGr, pathSearchStartVtx,\n        boost::make_iterator_property_map(p.begin(), idxMap),\n        boost::make_iterator_property_map(d.begin(), idxMap),\n        boost::make_function_property_map<Edge>(dummyWhFunc), idxMap,\n        std::less<float>(), boost::closed_plus<float>(), Mathf::MAX_REAL, 0.0, boost::dijkstra_visitor<boost::null_visitor>());\n\n      while (!nodeDegreeMap.empty())\n      {\n        //auto chainExtremityEntry = nodeDegreeMap.get<1>().begin();\n        auto chainExtremityEntry = std::min_element(nodeDegreeMap.begin(), nodeDegreeMap.end(),\n          [](std::pair<Vertex, uint32_t> const& iElem1, std::pair<Vertex, uint32_t> const& iElem2)\n        {\n          return iElem1.second < iElem2.second;\n        });\n\n        //if (chainExtremityEntry->vtx == pathSearchStartVtx)\n        if (chainExtremityEntry->first == pathSearchStartVtx)\n        {\n          nodeDegreeMap.erase(chainExtremityEntry);\n          continue;\n        }\n\n        Vector<Vertex> newChain;\n        Vertex chainExtremity = chainExtremityEntry->first;\n        if (chainExtremityEntry->second == 0)\n        {\n          nodeDegreeMap.erase(chainExtremityEntry);\n          //Was connected to cycles\n          auto edges = boost::out_edges(chainExtremity, filteredGr);\n          if (std::distance(edges.first, edges.second) >= 1)\n          {\n            newChain.push_back(edges.first->m_target);\n          }\n        }\n        else\n        {\n          //auto iter = nodeDegreeMap.get<0>().find(chainExtremity);\n          //NodeWithDegree entry = *iter;\n          \n          eXl_ASSERT(chainExtremityEntry->second == 1);\n\n          while (true)\n          {\n            newChain.push_back(chainExtremity);\n            //degree--;\n            //if (degree == 0)\n            {\n              nodeDegreeMap.erase(chainExtremity);\n              chainExtremityEntry = nodeDegreeMap.end();\n            }\n\n            {\n              auto predecessor = p[idxMap[chainExtremity]];\n              if (predecessor == chainExtremity)\n              {\n                break;\n              }\n\n              chainExtremity = predecessor;\n            }\n\n            chainExtremityEntry = nodeDegreeMap.find(chainExtremity);\n            if (chainExtremityEntry == nodeDegreeMap.end())\n            {\n              // Was removed when processing cycles, stop here.\n              break;\n            }\n            // decrease degree of next node.\n            //entry = *iter;\n            uint32_t& degree = chainExtremityEntry->second;\n            degree--;\n            //nodeDegreeMap.replace(iter, entry);\n            if (degree == 0)\n            {\n              nodeDegreeMap.erase(chainExtremity);\n            }\n            else\n            {\n              //nodeDegreeMap.replace(iter, entry);\n              if (degree != 1)\n              {\n                //Next vertex has more neighbours.\n                break;\n              }\n            }\n          }\n        }\n        newChain.push_back(chainExtremity);\n\n        chains.emplace_back(std::move(newChain));\n      }\n    }\n\n    if (cycles.empty() && chains.empty())\n    {\n      return Vector<Vector<Vertex>>();\n    }\n\n    //First process smaller cycle.\n    //Next order all chain through a BFS exploration.\n\n    Vector<Vector<Vertex>> orderedChains;\n    orderedChains.reserve(cycles.size() + chains.size());\n    if (!cycles.empty())\n    {\n      orderedChains.emplace_back(std::move(cycles.front()));\n      cycles.front() = std::move(cycles.back());\n      cycles.pop_back();\n\n      for (auto& cycle : cycles)\n      {\n        chains.emplace_back(std::move(cycle));\n      }\n      cycles.clear();\n    }\n    else\n    {\n      orderedChains.push_back(std::move(chains.back()));\n      chains.pop_back();\n    }\n\n    Map<Vertex, Set<uint32_t>> vtxChains;\n\n    for (uint32_t i = 0; i < chains.size(); ++i)\n    {\n      auto const& chain = chains[i];\n      for (auto vtx : chain)\n      {\n        auto& set = vtxChains.insert(std::make_pair(vtx, Set<uint32_t>())).first->second;\n        set.insert(i);\n      }\n    }\n\n    uint32_t curChainBegin = 0;\n    uint32_t curChainEnd = 1;\n    uint32_t nextChainEnd = 1;\n\n    uint32_t remainingChains = chains.size();\n    while (remainingChains > 0)\n    {\n      for (; curChainBegin < curChainEnd; ++curChainBegin)\n      {\n        auto& curChain = orderedChains[curChainBegin];\n        for (auto vtx : curChain)\n        {\n          for (auto edge : OutEdgesIter(graph, vtx))\n          {\n            auto entry = vtxChains.find(edge.m_target);\n            if (entry != vtxChains.end())\n            {\n              for (auto connectedChain : entry->second)\n              {\n                if (!chains[connectedChain].empty())\n                {\n                  orderedChains.emplace_back(chains[connectedChain]);\n                  chains[connectedChain].clear();\n                  ++nextChainEnd;\n                  --remainingChains;\n                }\n              }\n            }\n          }\n        }\n      }\n      eXl_ASSERT_REPAIR_RET(curChainEnd != nextChainEnd, Vector<Vector<Vertex>>());\n      curChainEnd = nextChainEnd;\n    }\n\n    return orderedChains;\n  }\n\n  LayoutCollection LayoutGraph(DungeonGraph const& iGraph, Random& iRand)\n  {\n    auto const& fullGraph = iGraph.GetGraph();\n    \n    PhysicalNodesFilter phFilter;\n    PhysicalGraph graph(fullGraph, phFilter, phFilter);\n\n    Vector<Vector<Vertex>> orderedChains = GetChainList(graph);\n\n    if (orderedChains.empty())\n    {\n      return LayoutCollection();\n    }\n\n    uint32_t curChainToAdd = 0;\n\n    Vector<LayoutCollection> layoutStack;\n\n    layoutStack.push_back(LayoutCollection());\n    layoutStack.back().push_back(Layout());\n\n    while(!layoutStack.empty() && layoutStack.size() < (orderedChains.size() + 1))\n    {\n      uint32_t chainToLayoutIdx = layoutStack.size() - 1;\n\n      LayoutCollection const& baseLayoutCol = layoutStack.back(); \n        \n      LayoutCollection nextCollection;\n\n      uint32_t const s_NumAttempts = 50;\n      uint32_t const s_CollectionSize = 15;\n\n      for(uint32_t attempt = 0; attempt < s_NumAttempts && nextCollection.size() < s_CollectionSize; ++attempt)\n      {\n        Layout const& baseLayout = baseLayoutCol[attempt % baseLayoutCol.size()];\n        Layout curLayout = baseLayout;\n        Set<Vertex> vtxToConsider;\n        // Copy chain to layout because vtx might not be sorted in connection order.\n        Vector<Vertex> chainToLayout = orderedChains[chainToLayoutIdx];\n\n        Map<Vertex, uint32_t> vtxToRoom;\n\n        Vector<RoomIndexEntry> roomEntries;\n        for(unsigned int i = 0; i<curLayout.size(); ++i)\n        {\n          roomEntries.push_back(std::make_pair(curLayout[i].m_Box, i));\n          vtxToConsider.insert(curLayout[i].m_Node);\n          vtxToRoom.insert(std::make_pair(curLayout[i].m_Node, i));\n        }\n        \n        RoomIndex roomIndex(roomEntries.begin(), roomEntries.end());\n        // Initial layout is intersection free.\n\n        //Only consider current layout + chain vtx.\n        boost::filtered_graph<decltype(graph), boost::keep_all, GraphFilter> filteredGr(graph, boost::keep_all(), GraphFilter(vtxToConsider));\n\n        float curEnergy = 0.0;\n        Map<uint32_t, RoomViolation> violatingRoom;\n\n        uint32_t expectedSize = curLayout.size() + chainToLayout.size();\n\n        for(int i = 0; i<chainToLayout.size(); ++i)\n        {\n          auto chainVtx = chainToLayout[i];\n\n          if(vtxToConsider.count(chainVtx))\n          {\n            // Chain extermities are repeated\n            chainToLayout[i] = chainToLayout.back();\n            chainToLayout.pop_back();\n            --expectedSize;\n            i = -1;\n            continue;\n          }\n\n          vtxToConsider.insert(chainVtx);\n\n          Vector<Segmenti> confSpace;\n          Vector<Segmenti> maxConfSpace;\n          vtxToConsider.insert(chainVtx);\n\n          Vector2i roomSize = SampleRoom(iGraph, chainVtx, iRand);\n\n          if(curLayout.empty())\n          {\n            Room newRoom;\n            newRoom.m_Node = chainVtx;\n            newRoom.m_Box = AABB2Di(Vector2i::ZERO, roomSize);\n            vtxToRoom[chainVtx] = curLayout.size();\n            roomIndex.insert(RoomIndexEntry(newRoom.m_Box, curLayout.size()));\n            curLayout.push_back(newRoom);\n\n            chainToLayout[i] = chainToLayout.back();\n            chainToLayout.pop_back();\n            i = -1;\n\n            continue;\n          }\n          else\n          {\n            uint32_t numNeigh = 0;\n            for(auto edge : OutEdgesIter(filteredGr, chainVtx))\n            {\n              auto target = GetTarget(chainVtx, edge);\n\n              auto const& neightRoom = curLayout[vtxToRoom[target]].m_Box;\n              \n              AddRoomConfSpace(roomSize, neightRoom, confSpace);\n              ++numNeigh;\n            }\n\n            if(numNeigh == 0)\n            {\n              vtxToConsider.erase(chainVtx);\n              continue;\n            }\n            else\n            {\n              // Found a way to connect the graph.\n              chainToLayout[i] = chainToLayout.back();\n              chainToLayout.pop_back();\n              i = -1;\n            }\n\n            if(numNeigh > 1)\n            {\n              ComputeMaxConfSpace(confSpace);\n            }\n          }\n\n          if(!confSpace.empty())\n          {\n            Room newRoom;\n            newRoom.m_Node = chainVtx;\n            newRoom.m_Box = SampleConfigurationSpace(roomSize, iRand, confSpace, roomIndex);\n\n            uint32_t newRoomIdx = curLayout.size();\n\n            vtxToRoom[chainVtx] = newRoomIdx;\n            curLayout.push_back(newRoom);\n            vtxToConsider.insert(chainVtx);\n\n            InsertRoomAndUpdateViolations(chainVtx, newRoomIdx, newRoom.m_Box, roomIndex, violatingRoom, filteredGr, vtxToRoom, curLayout);\n          }\n          else\n          {\n            // This layout cannot be extended.\n            break;\n          }\n\n          if(!violatingRoom.empty())\n          {\n            RoomIndex wkIndex = roomIndex;\n            Layout wkLayout = curLayout;\n\n            // Block area is between (3*3) and (6*6), so let's just take 15 as an average for now.\n            float const s_AreaFactor = 15 * 100;\n            uint32_t s_MaxTrials = 500;\n\n            auto ComputeTotalEnergy = [&violatingRoom, s_AreaFactor] ()\n            {\n              float sumCol = 0;\n              float sumDist = 0;\n              for(auto const& room : violatingRoom)\n              {\n                for(auto const& overlap : room.second.m_Overlaps)\n                {\n                  sumCol += overlap.second;\n                }\n                for(auto const& missingDoor : room.second.m_MissingDoor)\n                {\n                  sumDist += missingDoor.second;\n                }\n              }\n\n              return exp(sumCol / s_AreaFactor) * exp(sumDist / s_AreaFactor) - 1;\n            };\n\n            float prevEnergy = ComputeTotalEnergy();\n            float const initTemp = 0.6;\n            float const finalTemp = 0.2;\n            float const tempRatio = pow(0.2 / 0.6, 1.0 / float(s_MaxTrials));\n            float const kB = 1.38064852e10-23;\n            float temp = initTemp;\n\n            Vector<uint32_t> candidates;\n            candidates.reserve(curLayout.size());\n\n            for(uint32_t trial = 0; trial < s_MaxTrials && !violatingRoom.empty(); ++trial)\n            {\n              candidates.clear();\n              for(auto room : violatingRoom)\n              {\n                candidates.push_back(room.first);\n              }\n\n              uint32_t roomIdx = candidates[iRand() % candidates.size()];\n              Room& curRoom = wkLayout[roomIdx];\n              AABB2Di prevRoom = curRoom.m_Box;\n              RemoveRoomAndUpdateViolations(roomIdx, curRoom.m_Box, wkIndex, violatingRoom);\n\n              Vector2i roomSize = curRoom.m_Box.GetSize();\n\n              bool changeRoom = (iRand() % 10) > 7;\n              if(changeRoom)\n              {\n                roomSize = SampleRoom(iGraph, curRoom.m_Node, iRand);\n              }\n\n              uint32_t numNeigh = 0;\n              for(auto edge : OutEdgesIter(filteredGr, curRoom.m_Node))\n              {\n                auto target = GetTarget(curRoom.m_Node, edge);\n\n                auto const& neightRoom = curLayout[vtxToRoom[target]].m_Box;\n\n                AddRoomConfSpace(roomSize, neightRoom, confSpace);\n                ++numNeigh;\n              }\n\n              if(numNeigh > 1)\n              {\n                ComputeMaxConfSpace(confSpace);\n              }\n\n              if(confSpace.empty())\n              {\n                InsertRoomAndUpdateViolations(curRoom.m_Node, roomIdx, curRoom.m_Box, wkIndex, violatingRoom, filteredGr, vtxToRoom, wkLayout);\n                continue;\n              }\n              else\n              {\n                curRoom.m_Box = SampleConfigurationSpace(roomSize, iRand, confSpace, wkIndex);\n                InsertRoomAndUpdateViolations(curRoom.m_Node, roomIdx, curRoom.m_Box, wkIndex, violatingRoom, filteredGr, vtxToRoom, wkLayout);\n              }\n\n              float curEnergy = ComputeTotalEnergy();\n              float deltaEnergy = curEnergy - prevEnergy;\n\n              if(deltaEnergy <= Mathf::ZERO_TOLERANCE\n              || exp(deltaEnergy / (temp * kB)) > iRand())\n              {\n                //Accept move.\n                roomIndex = wkIndex;\n                curLayout = wkLayout;\n                prevEnergy = curEnergy;\n              }\n              else\n              {\n                RemoveRoomAndUpdateViolations(roomIdx, curRoom.m_Box, wkIndex, violatingRoom);\n                curRoom.m_Box = prevRoom;\n                InsertRoomAndUpdateViolations(curRoom.m_Node, roomIdx, curRoom.m_Box, wkIndex, violatingRoom, filteredGr, vtxToRoom, wkLayout);\n              }\n              temp *= tempRatio;\n            }\n          }\n        }\n\n        if(violatingRoom.empty() && curLayout.size() == expectedSize)\n        {\n          nextCollection.push_back(curLayout);\n        }\n        else\n        {\n          //printf(\"Blah\");\n        }\n      }\n\n      if(nextCollection.empty())\n      {\n        if(!layoutStack.empty() /*&& layoutStack.back().empty()*/)\n        {\n          // Could not build on top on previous conf, backtrack.\n          layoutStack.pop_back();\n        }\n      }\n      else\n      {\n        layoutStack.emplace_back(std::move(nextCollection));\n      }\n    }\n\n    if(!layoutStack.empty())\n    {\n      return layoutStack.back();\n    }\n    else \n    {\n      return LayoutCollection();\n    }\n  }\n}", "meta": {"hexsha": "5e03cbcd41acf940bff2a0ff0939b2a9f2d5f959", "size": 37425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/engine/map/dungeonlayout.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/engine/map/dungeonlayout.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/engine/map/dungeonlayout.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": 30.6260229133, "max_line_length": 460, "alphanum_fraction": 0.5780360721, "num_tokens": 9189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.018833128307170766, "lm_q1q2_score": 0.008755550943880332}}
{"text": "// Copyright (C) 2014 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// BSD 3-Clause License\n\n// Copyright (c) 2020, Chenyu\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\n//    list of conditions and the following disclaimer.\n\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived from\n//    this software without specific prior written permission.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\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 \"solver/qp_solver.h\"\n\n#include <glog/logging.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <limits>\n#include <string>\n\n#include \"math/sparse_cholesky_llt.h\"\n#include \"util/stringprintf.h\"\n\nnamespace DAGSfM {\n\nQPSolver::QPSolver(const Options& options, const Eigen::SparseMatrix<double>& P,\n                   const Eigen::VectorXd& q, const double r)\n    : options_(options), P_(P), q_(q), r_(r) {\n  CHECK_EQ(P_.rows(), P_.cols()) << \"P must be a symmetric matrix.\";\n  CHECK_EQ(P_.cols(), q_.size())\n      << \"The dimensions of P and q must be consistent.\";\n\n  // Set the lower and upper bounds to be negative and positive infinity (i.e\n  // no bounds).\n  lb_.setConstant(P_.cols(), -std::numeric_limits<double>::infinity());\n  ub_.setConstant(P_.cols(), std::numeric_limits<double>::infinity());\n\n  // Set up the linear solver to compute the cholesky decomposition of:\n  //     P_ + rho * eye(N)\n  Eigen::SparseMatrix<double> spd_mat(P_.rows(), P_.cols());\n  spd_mat.setIdentity();\n  spd_mat *= options_.rho;\n  spd_mat += P_;\n\n  linear_solver_.Compute(spd_mat);\n  CHECK_EQ(linear_solver_.Info(), Eigen::Success);\n}\n\nvoid QPSolver::SetMaxIterations(const int max_iterations) {\n  options_.max_num_iterations = max_iterations;\n}\n\nvoid QPSolver::SetUpperBound(const Eigen::VectorXd& ub) { ub_ = ub.array(); }\n\nvoid QPSolver::SetLowerBound(const Eigen::VectorXd& lb) { lb_ = lb.array(); }\n\n// Solve the quadratic program.\nbool QPSolver::Solve(Eigen::VectorXd* solution) {\n  // Ensure the bounds are valid. If there are any invalid bounds then the\n  // difference between the bounds would be a negative value.\n  int coeff_index = -1;\n  if ((ub_ - lb_).minCoeff(&coeff_index) < 0) {\n    LOG(WARNING) << \"You specified invalid lower or upper bounds for the \"\n                    \"problem. lower_bound[\"\n                 << coeff_index << \"] = \" << lb_[coeff_index]\n                 << \" but upper_bound[\" << coeff_index\n                 << \"] = \" << ub_[coeff_index];\n    return false;\n  }\n\n  CHECK_NOTNULL(solution)->setZero(q_.size());\n  Eigen::VectorXd& x = *solution;\n  Eigen::VectorXd z(P_.rows()), u(P_.rows());\n  z.setZero();\n  u.setZero();\n\n  Eigen::VectorXd z_old(z.size()), x_hat(P_.rows());\n\n  // Precompute some convergence terms.\n  const double primal_abs_tolerance_eps =\n      std::sqrt(P_.rows()) * options_.absolute_tolerance;\n  const double dual_abs_tolerance_eps =\n      std::sqrt(P_.rows()) * options_.absolute_tolerance;\n  VLOG(2) << \"Iteration   Residual         R norm          S norm          \"\n             \"Primal eps      Dual eps\";\n  const std::string row_format =\n      \"  % 4d      % 4.4e     % 4.4e     % 4.4e     % 4.4e     % 4.4e\";\n\n  // Run the iterations.\n  for (int i = 0; i < options_.max_num_iterations; i++) {\n    // Update x.\n    x.noalias() = linear_solver_.Solve(options_.rho * (z - u) - q_);\n    if (linear_solver_.Info() != Eigen::Success) {\n      return false;\n    }\n\n    // Update x_hat.\n    std::swap(z, z_old);\n    x_hat.noalias() = options_.alpha * x + (1.0 - options_.alpha) * z_old;\n\n    // Update z.\n    z.noalias() = ub_.min(lb_.max((x_hat + u).array())).matrix();\n\n    // Update u.\n    u.noalias() += x_hat - z;\n\n    // Compute the convergence terms.\n    const double objval = 0.5 * x.dot(P_ * x) + q_.dot(x) + r_;\n    const double r_norm = (x - z).norm();\n    const double s_norm = (-options_.rho * (z - z_old)).norm();\n    const double max_norm = std::max({x.norm(), z.norm()});\n    const double primal_eps =\n        primal_abs_tolerance_eps + options_.relative_tolerance * max_norm;\n    const double dual_eps =\n        dual_abs_tolerance_eps +\n        options_.relative_tolerance * (options_.rho * u).norm();\n\n    // Log the result to the screen.\n    VLOG(2) << StringPrintf(row_format.c_str(), objval, i, r_norm, s_norm,\n                            primal_eps, dual_eps);\n    // Determine if the minimizer has converged.\n    if (r_norm < primal_eps && s_norm < dual_eps) {\n      break;\n    }\n  }\n  return true;\n}\n\n}  // namespace DAGSfM\n", "meta": {"hexsha": "81e5456cdf69f38be5f36e80ceee44141a170b17", "size": 7395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solver/qp_solver.cpp", "max_stars_repo_name": "Yzhbuaa/DAGSfM", "max_stars_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 255.0, "max_stars_repo_stars_event_min_datetime": "2018-12-14T05:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T12:15:32.000Z", "max_issues_repo_path": "src/solver/qp_solver.cpp", "max_issues_repo_name": "Yzhbuaa/DAGSfM", "max_issues_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2018-12-25T03:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T03:33:25.000Z", "max_forks_repo_path": "src/solver/qp_solver.cpp", "max_forks_repo_name": "Yzhbuaa/DAGSfM", "max_forks_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2018-12-14T06:09:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T08:29:31.000Z", "avg_line_length": 39.972972973, "max_line_length": 80, "alphanum_fraction": 0.6877620014, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.021287353539753633, "lm_q1q2_score": 0.008751462417380585}}
{"text": "#ifndef OFFLINECACLAAG_HPP\n#define OFFLINECACLAAG_HPP\n\n#include <vector>\n#include <string>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include \"arch/AACAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include \"bib/OrnsteinUhlenbeckNoise.hpp\"\n#include <bib/MetropolisHasting.hpp>\n#include <bib/XMLEngine.hpp>\n#include \"nn/MLP.hpp\"\n#include \"nn/DODevMLP.hpp\"\n\ntypedef struct _sample {\n  std::vector<double> s;\n  std::vector<double> pure_a;\n  std::vector<double> a;\n  std::vector<double> next_s;\n  double r;\n  bool goal_reached;\n\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar& BOOST_SERIALIZATION_NVP(s);\n    ar& BOOST_SERIALIZATION_NVP(pure_a);\n    ar& BOOST_SERIALIZATION_NVP(a);\n    ar& BOOST_SERIALIZATION_NVP(next_s);\n    ar& BOOST_SERIALIZATION_NVP(r);\n    ar& BOOST_SERIALIZATION_NVP(goal_reached);\n  }\n\n  bool operator< (const _sample& b) const {\n    for (uint i = 0; i < s.size(); i++) {\n      if(s[i] != b.s[i])\n        return s[i] < b.s[i];\n    }\n\n    for (uint i = 0; i < a.size(); i++) {\n      if(a[i] != b.a[i])\n        return a[i] < b.a[i];\n    }\n\n    return false;\n  }\n\n} sample;\n\ntemplate<typename NN = MLP>\nclass OfflineCaclaAg : public arch::AACAgent<NN, arch::AgentProgOptions> {\n public:\n  typedef NN PolicyImpl;\n\n  OfflineCaclaAg(unsigned int _nb_motors, unsigned int _nb_sensors)\n    : arch::AACAgent<NN, arch::AgentProgOptions>(_nb_motors, _nb_sensors), nb_sensors(_nb_sensors), empty_action(0) {\n\n  }\n\n  virtual ~OfflineCaclaAg() {\n    delete vnn;\n    delete ann;\n    \n    delete ann_testing;\n    if(batch_norm_critic != 0)\n      delete vnn_testing;\n\n    delete hidden_unit_v;\n    delete hidden_unit_a;\n    \n    if(oun == nullptr)\n      delete oun;\n  }\n\n  const std::vector<double>& _run(double reward, const std::vector<double>& sensors,\n                                  bool learning, bool goal_reached, bool) override {\n\n    // protect batch norm from testing data and poor data\n    vector<double>* next_action = ann_testing->computeOut(sensors);\n    if (last_action.get() != nullptr && learning)\n      trajectory.push_back( {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached});\n\n    last_pure_action.reset(new vector<double>(*next_action));\n    if(learning) {\n      if(gaussian_policy == 1) {\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(gaussian_policy == 2) {\n        oun->step(*next_action);\n      } else if(gaussian_policy == 3 && bib::Utils::rand01() < noise2) {\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(gaussian_policy == 4) {\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise * pow(noise2, noise3 - ((double) step)));\n        delete next_action;\n        next_action = randomized_action;\n      } else if(bib::Utils::rand01() < noise) { //e-greedy\n        for (uint i = 0; i < next_action->size(); i++)\n          next_action->at(i) = bib::Utils::randin(-1.f, 1.f);\n      }\n    }\n    last_action.reset(next_action);\n\n    ann_testing->neutral_action(sensors, next_action);\n\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    step++;\n    \n    return *next_action;\n  }\n\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map*) override {\n//     bib::Seed::setFixedSeedUTest();\n    hidden_unit_v           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_v\"));\n    hidden_unit_a           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_a\"));\n    noise                   = pt->get<double>(\"agent.noise\");\n    gaussian_policy         = pt->get<uint>(\"agent.gaussian_policy\");\n    update_delta_neg        = pt->get<bool>(\"agent.update_delta_neg\");\n    vnn_from_scratch        = pt->get<bool>(\"agent.vnn_from_scratch\");\n    update_critic_first     = pt->get<bool>(\"agent.update_critic_first\");\n    number_fitted_iteration = pt->get<uint>(\"agent.number_fitted_iteration\");\n    stoch_iter_actor        = pt->get<uint>(\"agent.stoch_iter_actor\");\n    stoch_iter_critic       = pt->get<uint>(\"agent.stoch_iter_critic\");\n    batch_norm_actor        = pt->get<uint>(\"agent.batch_norm_actor\");\n    batch_norm_critic       = pt->get<uint>(\"agent.batch_norm_critic\");\n    actor_output_layer_type = pt->get<uint>(\"agent.actor_output_layer_type\");\n    hidden_layer_type       = pt->get<uint>(\"agent.hidden_layer_type\");\n    alpha_a                 = pt->get<double>(\"agent.alpha_a\");\n    alpha_v                 = pt->get<double>(\"agent.alpha_v\");\n    lambda                  = pt->get<double>(\"agent.lambda\");\n    momentum                = pt->get<uint>(\"agent.momentum\");\n    corrected_update_ac     = false;\n    gae                     = false;\n    inverting_gradient      = false;\n    update_each_episode = 1;\n    \n    if(gaussian_policy == 2){\n      double oun_theta = pt->get<double>(\"agent.noise2\");\n      double oun_dt = pt->get<double>(\"agent.noise3\");\n      oun = new bib::OrnsteinUhlenbeckNoise<double>(this->nb_motors, noise, oun_theta, oun_dt);\n    } else if (gaussian_policy == 3){\n      noise2 = pt->get<double>(\"agent.noise2\");\n    } else if (gaussian_policy == 4){\n      noise2 = pt->get<double>(\"agent.noise2\");\n      noise3 = pt->get<double>(\"agent.noise3\");\n    }\n    \n    try {\n      update_each_episode     = pt->get<uint>(\"agent.update_each_episode\");\n    } catch(boost::exception const& ) {\n    }\n    \n    try {\n      corrected_update_ac   = pt->get<bool>(\"agent.corrected_update_ac\");\n    } catch(boost::exception const& ) {\n    }\n    try {\n      inverting_gradient   = pt->get<bool>(\"agent.inverting_gradient\");\n    } catch(boost::exception const& ) {\n    }\n    if(corrected_update_ac){\n      try {\n        corrected_update_ac_factor   = pt->get<double>(\"agent.corrected_update_ac_factor\");\n      } catch(boost::exception const& ) {\n      }\n    }\n    \n    if(lambda >= 0.)\n      gae = pt->get<bool>(\"agent.gae\");\n    \n    if(lambda >=0. && batch_norm_critic != 0){\n      LOG_DEBUG(\"to be done!\");\n      exit(1);\n    }\n    \n    ann = new NN(nb_sensors, *hidden_unit_a, this->nb_motors, alpha_a, 1, hidden_layer_type, actor_output_layer_type, batch_norm_actor, true, momentum);\n    if(std::is_same<NN, DODevMLP>::value)\n      ann->exploit(pt, nullptr);\n    \n    vnn = new NN(nb_sensors, nb_sensors, *hidden_unit_v, alpha_v, 1, -1, hidden_layer_type, batch_norm_critic, false, momentum);\n    if(std::is_same<NN, DODevMLP>::value)\n      vnn->exploit(pt, ann);\n    \n    ann_testing = new NN(*ann, false, ::caffe::Phase::TEST);\n    if(batch_norm_critic != 0)\n      vnn_testing = new NN(*vnn, false, ::caffe::Phase::TEST);\n    \n    if(std::is_same<NN, DODevMLP>::value){\n      try {\n        if(pt->get<bool>(\"devnn.reset_learning_algo\")){\n          LOG_ERROR(\"NFAC cannot reset anything with DODevMLP\");\n          exit(1);\n        }\n      } catch(boost::exception const& ) {\n      }\n    }\n    \n    bestever_score = std::numeric_limits<double>::lowest();\n  }\n\n  void _start_episode(const std::vector<double>& sensors, bool learning) override {\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    last_action = nullptr;\n    last_pure_action = nullptr;\n    \n    step = 0;\n    if(gaussian_policy == 2)\n      oun->reset();\n    \n    ratio_valid_advantage = -1;\n    \n    if(std::is_same<NN, DODevMLP>::value && learning){\n      DODevMLP * ann_cast = static_cast<DODevMLP *>(ann);\n      bool changed_ann = std::get<1>(ann_cast->inform(episode, this->last_sum_weighted_reward));\n//       don't need to inform vnn because they share parameters\n//       static_cast<DODevMLP *>(vnn)->inform(episode, this->last_sum_weighted_reward);\n      if(changed_ann && ann_cast->ewc_enabled() && ann_cast->ewc_force_constraint()){\n        static_cast<DODevMLP *>(vnn)->ewc_setup();\n//         else if(changed_vnn && !changed_ann) //impossible cause of ann structure\n      }\n    }\n    \n    double* weights = new double[ann->number_of_parameters(false)];\n    ann->copyWeightsTo(weights, false);\n    ann_testing->copyWeightsFrom(weights, false);\n    delete[] weights;\n  }\n\n  double update_critic() {\n    double V_pi_s0 = 0.f;\n    if (trajectory.size() > 0) {\n      //remove trace of old policy\n      auto iter = [&]() {\n        std::vector<double> all_states(trajectory.size() * nb_sensors);\n        std::vector<double> all_next_states(trajectory.size() * nb_sensors);\n        std::vector<double> v_target(trajectory.size());\n        int li=0;\n        for (auto it : trajectory) {\n          std::copy(it.s.begin(), it.s.end(), all_states.begin() + li * nb_sensors);\n          std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + li * nb_sensors);\n          li++;\n        }\n\n        decltype(vnn_testing->computeOutVFBatch(all_next_states, empty_action)) all_nextV;\n        if(batch_norm_critic != 0)\n        {\n          double* weights = new double[vnn->number_of_parameters(false)];\n          vnn->copyWeightsTo(weights, false);\n          vnn_testing->copyWeightsFrom(weights, false);\n          delete[] weights;\n          all_nextV = vnn_testing->computeOutVFBatch(all_next_states, empty_action);\n        } else \n          all_nextV = vnn->computeOutVFBatch(all_next_states, empty_action);\n\n        li=0;\n        for (auto it : trajectory) {\n          double target = it.r;\n          if (!it.goal_reached) {\n            double nextV = all_nextV->at(li);\n            target += this->gamma * nextV;\n          }\n\n          v_target[li] = target;\n          li++;\n        }\n\n        ASSERT((uint)li == trajectory.size(), \"\");\n        if(vnn_from_scratch){\n          delete vnn;\n          vnn = new NN(nb_sensors, nb_sensors, *hidden_unit_v, alpha_v, trajectory.size(), -1, hidden_layer_type, batch_norm_critic, false, momentum);\n        }\n        if(lambda < 0.f && batch_norm_critic == 0)\n          vnn->learn_batch(all_states, empty_action, v_target, stoch_iter_critic);\n        else if(lambda < 0.f){\n          for(uint sia = 0; sia < stoch_iter_critic; sia++){\n            delete vnn->computeOutVFBatch(all_states, empty_action);\n            {\n              double* weights = new double[vnn->number_of_parameters(false)];\n              vnn->copyWeightsTo(weights, false);\n              vnn_testing->copyWeightsFrom(weights, false);\n              delete[] weights;\n            }\n            auto all_V = vnn_testing->computeOutVFBatch(all_states, empty_action);\n            \n            const auto q_values_blob = vnn->getNN()->blob_by_name(MLP::q_values_blob_name);\n            double* q_values_diff = q_values_blob->mutable_cpu_diff();\n            uint i=0;\n            double s = trajectory.size();\n            for (auto it : trajectory){\n              q_values_diff[i] = (all_V->at(i)-v_target[i])/s;\n              i++;\n            }\n            vnn->critic_backward();\n            vnn->updateFisher(trajectory.size());\n            vnn->regularize();\n            vnn->getSolver()->ApplyUpdate();\n            vnn->getSolver()->set_iter(vnn->getSolver()->iter() + 1);\n            delete all_V;\n          }\n        }\n        else {\n          auto all_V = vnn->computeOutVFBatch(all_states, empty_action);\n          std::vector<double> deltas(trajectory.size());\n//           \n//        Simple computation for lambda return\n//           \n//          bib::Logger::PRINT_ELEMENTS(*all_V, \"V0 \");\n          li=0;\n          for (auto it : trajectory){\n            deltas[li] = v_target[li] - all_V->at(li);\n            ++li;\n          }\n//          bib::Logger::PRINT_ELEMENTS(deltas, \"deltas \");\n          \n          std::vector<double> diff(trajectory.size());\n          li=trajectory.size() - 1;\n          double prev_delta = 0.;\n          int index_ep = trajectory_end_points.size() - 1;\n          for (auto it : trajectory) {\n            if (index_ep >= 0 && trajectory_end_points[index_ep] - 1 == li){\n                prev_delta = 0.;\n                index_ep--;\n            }\n            diff[li] = deltas[li] + prev_delta;\n            prev_delta = this->gamma * lambda * diff[li];\n            --li;\n          }\n          ASSERT(diff[trajectory.size() -1] == deltas[trajectory.size() -1], \"pb lambda\");\n          \n// //           comment following lines to compare with the other formula\n          li=0;\n          for (auto it : trajectory){\n            diff[li] = diff[li] + all_V->at(li);\n            ++li;\n          }\n          \n//          bib::Logger::PRINT_ELEMENTS(diff, \"target \");\n          V_pi_s0 = diff[0];\n          vnn->learn_batch(all_states, empty_action, diff, stoch_iter_critic);\n// // \n// //        The mechanic formula\n// //        \n//           std::vector<double> diff2(trajectory.size());\n//           li=0;\n//           for (auto it : trajectory){\n//             diff2[li] = 0;\n//             double sum_n = 0.f;\n//             for(int n=1;n<=((int)trajectory.size()) - li - 1;n++){\n//               double sum_i = 0.f;\n//               for(int i=li;i<=li+n-1;i++)\n//                 sum_i += std::pow(this->gamma, i-li) * trajectory[i].r;\n//               sum_i += std::pow(this->gamma, n) * all_nextV->at(li+n-1);\n//               sum_i *= pow(lambda, n-1);\n//               sum_n += sum_i;\n//             }\n//             sum_n *= (1.f-lambda);\n//             \n//             double sum_L = 0.f;\n//             for(int i=li;i<(int)trajectory.size();i++)\n//               sum_L += std::pow(this->gamma, i-li) * trajectory[i].r;\n//             if(trajectory[trajectory.size()-1].goal_reached)\n//               sum_n += std::pow(lambda, trajectory.size() - li - 1) * sum_L;\n//             else {\n//               sum_L += std::pow(this->gamma, ((int)trajectory.size()) - li) * all_nextV->at(trajectory.size()-1);\n//               sum_n += std::pow(lambda, trajectory.size() - li - 1) * sum_L;\n//             }\n//             \n//             sum_n -= all_V->at(li);\n//             \n//             diff2[li] = sum_n;\n//             ++li;\n//           }\n//           bib::Logger::PRINT_ELEMENTS(diff2, \"mech form \");\n//           \n//           if(trajectory[trajectory.size()-1].goal_reached)\n//             exit(1);\n          delete all_V;\n        }\n        \n        delete all_nextV;\n      };\n\n      for(uint i=0; i<number_fitted_iteration; i++)\n        iter();\n    }\n    \n    return V_pi_s0;\n  }\n\n  void end_episode(bool learning) override {\n//     LOG_FILE(\"policy_exploration\", ann->hash());\n    if(!learning){\n      if(ann->ewc_best_method() >= 4){\n        ann->update_best_param_previous_task(this->sum_weighted_reward);\n        vnn->update_best_param_previous_task(this->sum_weighted_reward);\n      }\n      return;\n    }\n    \n    //learning phase\n    if(ann->ewc_best_method() <= 3){\n      ann->update_best_param_previous_task(this->sum_weighted_reward);\n      vnn->update_best_param_previous_task(this->sum_weighted_reward);\n    }\n    \n    trajectory_end_points.push_back(trajectory.size());\n    if (episode % update_each_episode != 0)\n      return;\n\n    if(trajectory.size() > 0){\n      vnn->increase_batchsize(trajectory.size());\n      if(batch_norm_critic != 0)\n        vnn_testing->increase_batchsize(trajectory.size());\n    }\n    \n    double V_pi_s0 = 0;\n    if(update_critic_first)\n      V_pi_s0 = update_critic();\n\n    if (trajectory.size() > 0) {\n      std::vector<double> sensors(trajectory.size() * nb_sensors);\n      std::vector<double> actions(trajectory.size() * this->nb_motors);\n      std::vector<bool> disable_back(trajectory.size() * this->nb_motors, false);\n      const std::vector<bool> disable_back_ac(this->nb_motors, true);\n//       std::vector<double> deltas_blob(trajectory.size() * this->nb_motors);\n      std::vector<double> deltas(trajectory.size());\n\n      std::vector<double> all_states(trajectory.size() * nb_sensors);\n      std::vector<double> all_next_states(trajectory.size() * nb_sensors);\n      int li=0;\n      for (auto it : trajectory) {\n        std::copy(it.s.begin(), it.s.end(), all_states.begin() + li * nb_sensors);\n        std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + li * nb_sensors);\n        li++;\n      }\n\n      decltype(vnn->computeOutVFBatch(all_next_states, empty_action)) all_nextV, all_mine;\n      if(batch_norm_critic != 0)\n      {\n        double* weights = new double[vnn->number_of_parameters(false)];\n        vnn->copyWeightsTo(weights, false);\n        vnn_testing->copyWeightsFrom(weights, false);\n        delete[] weights;\n        all_nextV = vnn_testing->computeOutVFBatch(all_next_states, empty_action);\n        all_mine = vnn_testing->computeOutVFBatch(all_states, empty_action);\n      } else {\n        all_nextV = vnn->computeOutVFBatch(all_next_states, empty_action);\n        all_mine = vnn->computeOutVFBatch(all_states, empty_action);\n      }\n      \n      li=0;\n      for (auto it : trajectory){\n        sample sm = it;\n        double v_target = sm.r;\n        if (!sm.goal_reached) {\n          double nextV = all_nextV->at(li);\n          v_target += this->gamma * nextV;\n        }\n        \n        deltas[li] = v_target - all_mine->at(li);\n        ++li;\n      }\n      \n      if(gae){\n        //           \n        //        Simple computation for lambda return\n        //           \n        std::vector<double> diff(trajectory.size());\n        li=trajectory.size() - 1;\n        double prev_delta = 0.;\n        int index_ep = trajectory_end_points.size() - 1;\n        for (auto it : trajectory) {\n          if (index_ep >= 0 && trajectory_end_points[index_ep] - 1 == li){\n              prev_delta = 0.;\n              index_ep--;\n          }\n          diff[li] = deltas[li] + prev_delta;\n          prev_delta = this->gamma * lambda * diff[li];\n          --li;\n        }\n        ASSERT(diff[trajectory.size() -1] == deltas[trajectory.size() -1], \"pb lambda\");\n\n        li=0;\n        for (auto it : trajectory){\n//           diff[li] = diff[li] + all_V->at(li);\n          deltas[li] = diff[li];\n          ++li;\n        }\n      }\n      \n      uint n=0;\n      li=0;\n//       double dmax = std::max((double)0.f, *std::max_element(deltas.begin(), deltas.end()));\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        sample sm = *it;\n\n        std::copy(it->s.begin(), it->s.end(), sensors.begin() + li * nb_sensors);\n        if(deltas[li] > 0.) {\n          std::copy(it->a.begin(), it->a.end(), actions.begin() + li * this->nb_motors);\n          n++;\n        } else if(update_delta_neg) {\n          std::copy(it->pure_a.begin(), it->pure_a.end(), actions.begin() + li * this->nb_motors);\n        } else {\n          std::copy(it->a.begin(), it->a.end(), actions.begin() + li * this->nb_motors);\n          std::copy(disable_back_ac.begin(), disable_back_ac.end(), disable_back.begin() + li * this->nb_motors);\n        }\n//         std::fill(deltas_blob.begin() + li * this->nb_motors, deltas_blob.begin() + (li+1) * this->nb_motors, deltas[li]);\n        li++;\n      }\n\n      ratio_valid_advantage = ((float)n) / ((float) trajectory.size());\n      \n      if(n > 0) {\n        for(uint sia = 0; sia < stoch_iter_actor; sia++){\n          ann->increase_batchsize(trajectory.size());\n          //learn BN\n          auto ac_out = ann->computeOutBatch(sensors);\n          if(batch_norm_actor != 0) {\n            //re-compute ac_out with BN as testing\n            double* weights = new double[ann->number_of_parameters(false)];\n            ann->copyWeightsTo(weights, false);\n            ann_testing->copyWeightsFrom(weights, false);\n            delete[] weights;\n            delete ac_out;\n            ann_testing->increase_batchsize(trajectory.size());\n            ac_out = ann_testing->computeOutBatch(sensors);\n          }\n          ann->ZeroGradParameters();\n          \n          const auto actor_actions_blob = ann->getNN()->blob_by_name(MLP::actions_blob_name);\n          auto ac_diff = actor_actions_blob->mutable_cpu_diff();\n          for(int i=0; i<actor_actions_blob->count(); i++){\n            if(disable_back[i]){\n              ac_diff[i] = 0.00000000f;\n            } else {\n              double x = actions[i] - ac_out->at(i);\n              if(!corrected_update_ac){\n                ac_diff[i] = -x;\n                if(inverting_gradient){\n                  const double min_ = -1.0; \n                  const double max_ = 1.0;\n                  \n                  if (ac_diff[i] < 0)\n                    ac_diff[i] *= (max_ - ac_out->at(i)) / (max_ - min_);\n                  else if (ac_diff[i] > 0)\n                    ac_diff[i] *= (ac_out->at(i) - min_) / (max_ - min_);\n                }\n              } else {\n                ac_diff[i] = -x * corrected_update_ac_factor;\n              }\n            }\n          }\n          ann->actor_backward();\n          ann->updateFisher(n);\n          ann->regularize();\n          ann->getSolver()->ApplyUpdate();\n          ann->getSolver()->set_iter(ann->getSolver()->iter() + 1);\n          delete ac_out;\n        }\n      } else if(batch_norm_actor != 0){\n        ann->increase_batchsize(trajectory.size());\n        delete ann->computeOutBatch(sensors);\n      }\n\n      delete all_nextV;\n      delete all_mine;\n      \n      if(batch_norm_actor != 0)\n        ann_testing->increase_batchsize(1);\n    }\n\n    if(!update_critic_first){\n      update_critic();\n    }\n    \n    nb_sample_update= trajectory.size();\n    trajectory.clear();\n    trajectory_end_points.clear();\n    \n    ann->ewc_decay_update();\n    vnn->ewc_decay_update();\n  }\n  \n  void end_instance(bool learning) override {\n    if(learning)\n      episode++;\n  }\n\n  void save(const std::string& path, bool savebest, bool learning) override {\n    if(savebest) {\n      if(!learning && this->sum_weighted_reward >= bestever_score) {\n        bestever_score = this->sum_weighted_reward;\n        ann->save(path+\".actor\");\n      }\n    } else {\n      ann->save(path+\".actor\");\n      vnn->save(path+\".critic\");\n    } \n  }\n  \n  void save_run() override {\n    ann->save(\"continue.actor\");\n    vnn->save(\"continue.critic\");\n    struct algo_state st = {episode};\n    bib::XMLEngine::save(st, \"algo_state\", \"continue.algo_state.data\");\n  }\n\n  void load(const std::string& path) override {\n    ann->load(path+\".actor\");\n    vnn->load(path+\".critic\");\n  }\n  \n  void load_previous_run() override {\n    ann->load(\"continue.actor\");\n    vnn->load(\"continue.critic\");\n    auto p3 = bib::XMLEngine::load<struct algo_state>(\"algo_state\", \"continue.algo_state.data\");\n    episode = p3->episode;\n    delete p3;\n  }\n\n  double criticEval(const std::vector<double>&, const std::vector<double>&) override {\n    LOG_INFO(\"not implemented\");\n    return 0;\n  }\n\n  arch::Policy<NN>* getCopyCurrentPolicy() override {\n//         return new arch::Policy<MLP>(new MLP(*ann) , gaussian_policy ? arch::policy_type::GAUSSIAN : arch::policy_type::GREEDY, noise, decision_each);\n    return nullptr;\n  }\n\n protected:\n  void _display(std::ostream& out) const override {\n    out << std::setw(12) << std::fixed << std::setprecision(10) << this->sum_weighted_reward/this->gamma << \" \" << this->sum_reward << \n        \" \" << std::setw(8) << std::fixed << std::setprecision(5) << vnn->error() << \" \" << noise << \" \" << nb_sample_update <<\n          \" \" << std::setprecision(3) << ratio_valid_advantage << \" \" << vnn->weight_l1_norm() << \" \" << ann->weight_l1_norm();\n  }\n\n  void _dump(std::ostream& out) const override {\n    out << std::setw(25) << std::fixed << std::setprecision(22) <<\n    this->sum_weighted_reward/this->gamma << \" \" << this->sum_reward << \" \" << std::setw(8) << std::fixed <<\n        std::setprecision(5) << vnn->error() << \" \" << nb_sample_update <<\n        \" \" << std::setprecision(3) << ratio_valid_advantage ;\n  }\n  \n  double sign(double x){\n    if(x>=0)\n      return 1.f;\n    return -1.f;\n  }\n\n private:\n  uint nb_sensors;\n  uint episode = 1;\n  uint step = 0;\n\n  double noise, noise2, noise3;\n  uint gaussian_policy;\n  bool vnn_from_scratch, update_critic_first,\n        update_delta_neg, corrected_update_ac, gae;\n  bool inverting_gradient;\n  uint number_fitted_iteration, stoch_iter_actor, stoch_iter_critic;\n  uint batch_norm_actor, batch_norm_critic, actor_output_layer_type, hidden_layer_type, momentum;\n  double lambda, corrected_update_ac_factor;\n\n  std::shared_ptr<std::vector<double>> last_action;\n  std::shared_ptr<std::vector<double>> last_pure_action;\n  std::vector<double> last_state;\n  double alpha_v, alpha_a;\n\n  std::deque<sample> trajectory;\n  std::deque<int> trajectory_end_points;\n\n  NN* ann;\n  NN* vnn;\n  NN* ann_testing;\n  NN* vnn_testing;\n\n  std::vector<uint>* hidden_unit_v;\n  std::vector<uint>* hidden_unit_a;\n  std::vector<double> empty_action; //dummy action cause c++ cannot accept null reference\n  double bestever_score;\n  int update_each_episode;\n  bib::OrnsteinUhlenbeckNoise<double>* oun = nullptr;\n  float ratio_valid_advantage=0;\n  int nb_sample_update = 0;\n  \n  struct algo_state {\n    uint episode;\n    \n    friend class boost::serialization::access;\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int) {\n      ar& BOOST_SERIALIZATION_NVP(episode);\n    }\n  };\n};\n\n#endif\n\n", "meta": {"hexsha": "4ba6a0297bc25bbf6b2fea62cb28aa893edba0ac", "size": 25480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/cacla/include/OfflineCaclaAg.hpp", "max_stars_repo_name": "matthieu637/ddrl", "max_stars_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T09:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T13:50:23.000Z", "max_issues_repo_path": "agent/cacla/include/OfflineCaclaAg.hpp", "max_issues_repo_name": "matthieu637/ddrl", "max_issues_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-10-09T14:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T15:01:00.000Z", "max_forks_repo_path": "agent/cacla/include/OfflineCaclaAg.hpp", "max_forks_repo_name": "matthieu637/ddrl", "max_forks_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T09:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T14:35:40.000Z", "avg_line_length": 35.7363253857, "max_line_length": 160, "alphanum_fraction": 0.5858712716, "num_tokens": 6545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.02033235237800851, "lm_q1q2_score": 0.008745907168851109}}
{"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 \"PyImath.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathBasicTypes.h\"\n#include \"PyImathFixedArray.h\"\n#include \"PyImathFixedVArray.h\"\n#include \"PyImathBufferProtocol.h\"\n\nusing namespace boost::python;\n\nnamespace PyImath {\n\nvoid\nregister_basicTypes()\n{\n    class_<BoolArray> bclass = BoolArray::register_(\"Fixed length array of bool\");\n    add_comparison_functions(bclass);\n\n    class_<SignedCharArray> scclass = SignedCharArray::register_(\"Fixed length array of signed chars\");\n    add_arithmetic_math_functions(scclass);\n    add_mod_math_functions(scclass);\n    add_comparison_functions(scclass);\n    add_ordered_comparison_functions(scclass);\n\n    class_<UnsignedCharArray> ucclass = UnsignedCharArray::register_(\"Fixed length array of unsigned chars\");\n    add_arithmetic_math_functions(ucclass);\n    add_mod_math_functions(ucclass);\n    add_comparison_functions(ucclass);\n    add_ordered_comparison_functions(ucclass);\n    add_buffer_protocol<UnsignedCharArray>(ucclass);\n\n    class_<ShortArray> sclass = ShortArray::register_(\"Fixed length array of shorts\");\n    add_arithmetic_math_functions(sclass);\n    add_mod_math_functions(sclass);\n    add_comparison_functions(sclass);\n    add_ordered_comparison_functions(sclass);\n\n    class_<UnsignedShortArray> usclass = UnsignedShortArray::register_(\"Fixed length array of unsigned shorts\");\n    add_arithmetic_math_functions(usclass);\n    add_mod_math_functions(usclass);\n    add_comparison_functions(usclass);\n    add_ordered_comparison_functions(usclass);\n\n    class_<IntArray> iclass = IntArray::register_(\"Fixed length array of ints\");\n    add_arithmetic_math_functions(iclass);\n    add_mod_math_functions(iclass);\n    add_comparison_functions(iclass);\n    add_ordered_comparison_functions(iclass);\n    add_explicit_construction_from_type<float>(iclass);\n    add_explicit_construction_from_type<double>(iclass);\n    add_buffer_protocol<IntArray>(iclass);\n\n    class_<UnsignedIntArray> uiclass = UnsignedIntArray::register_(\"Fixed length array of unsigned ints\");\n    add_arithmetic_math_functions(uiclass);\n    add_mod_math_functions(uiclass);\n    add_comparison_functions(uiclass);\n    add_ordered_comparison_functions(uiclass);\n    add_explicit_construction_from_type<float>(uiclass);\n    add_explicit_construction_from_type<double>(uiclass);\n\n    class_<FloatArray> fclass = FloatArray::register_(\"Fixed length array of floats\");\n    add_arithmetic_math_functions(fclass);\n    add_pow_math_functions(fclass);\n    add_comparison_functions(fclass);\n    add_ordered_comparison_functions(fclass);\n    add_explicit_construction_from_type<int>(fclass);\n    add_explicit_construction_from_type<double>(fclass);\n    add_buffer_protocol<FloatArray>(fclass);\n\n    class_<DoubleArray> dclass = DoubleArray::register_(\"Fixed length array of doubles\");\n    add_arithmetic_math_functions(dclass);\n    add_pow_math_functions(dclass);\n    add_comparison_functions(dclass);\n    add_ordered_comparison_functions(dclass);\n    add_explicit_construction_from_type<int>(dclass);\n    add_explicit_construction_from_type<float>(dclass);\n    add_buffer_protocol<DoubleArray>(dclass);\n\n    class_<VIntArray>   ivclass = VIntArray::register_(\"Variable fixed length array of ints\");\n    class_<VFloatArray> fvclass = VFloatArray::register_(\"Variable fixed length array of floats\");\n    class_<VV2iArray> v2ivclass = VV2iArray::register_(\"Variable fixed length array of V2i\");\n    class_<VV2fArray> v2fvclass = VV2fArray::register_(\"Variable fixed length array of V2f\");\n    // Don't add other functionality until its defined better.\n}\n\n} // namespace PyImath\n", "meta": {"hexsha": "805514b09c0df725873c8e0fd7d5d70c5b824ef5", "size": 3763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/PyImath/PyImathBasicTypes.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/PyImathBasicTypes.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/PyImathBasicTypes.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": 39.6105263158, "max_line_length": 112, "alphanum_fraction": 0.7826202498, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.024798163033404527, "lm_q1q2_score": 0.008733957211879176}}
{"text": "/*******************************************************************\n* Copyright (c) 2010-2013 MiGraNT - DTAI.cs.kuleuven.be\n* License details in the root directory of this distribution in\n* the LICENSE file\n********************************************************************/\n\n#include \"treeDecompositionDAG.hpp\"\n#include <iostream>\n#include <stack>\n#include <queue>\n#include <set>\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n\n#include <boost/graph/topological_sort.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"treeDecompositionDAGAndNode.hpp\"\n\n#include <boost/graph/graphviz.hpp>\n\nnamespace treeDAG {\n\nTreeDecompositionDAG::AndNodeTransformer::AndNodeTransformer()\n    : dag_(0)\n{\n}\n\nTreeDecompositionDAG::AndNodeTransformer::AndNodeTransformer(bool isSource, const TreeDecompositionDAG * dag)\n    : dag_(dag),\n      isSource_(isSource)\n{\n}\n\nTreeDecompositionDAGAndNode TreeDecompositionDAG::AndNodeTransformer::operator()(boost::graph_traits<Graph>::edge_descriptor edge) const\n{\n    return TreeDecompositionDAGAndNode(dag_, isSource_ ? boost::source(edge, dag_->structure_) : boost::target(edge, dag_->structure_) );\n}\n\nTreeDecompositionDAG::ComponentTransformer::ComponentTransformer(const Graph * graph)\n    : graph_(graph)\n{\n}\n\nconst TreeDecompositionSubgraph & TreeDecompositionDAG::ComponentTransformer::operator()(boost::graph_traits<Graph>::vertex_descriptor vd) const\n{\n    return graph_->operator [](vd).vertices;\n}\n\n\nTreeDecompositionDAG::ComponentFilter::ComponentFilter(const Graph * graph)\n    : graph_(graph)\n{\n}\n\nbool TreeDecompositionDAG::ComponentFilter::operator()(const TreeDecompositionSubgraph & component) const\n{\n    return component.size() != 0;\n}\n\n\nTreeDecompositionDAG::TreeDecompositionDAG(std::size_t patternSize)\n    : patternSize_(patternSize)\n{\n\n}\n\nTreeDecompositionDAG::TreeDecompositionDAG(const TreeDecompositionDAG & rhs)\n    : structure_(rhs.structure_),\n      patternSize_(rhs.patternSize_)\n{\n    refillMap();\n}\n\nvoid TreeDecompositionDAG::reset(std::size_t patternSize)\n{\n    structure_.clear();\n    map_.clear();\n    patternSize_ = patternSize;\n}\n\nTreeDecompositionDAG & TreeDecompositionDAG::operator=(const TreeDecompositionDAG & rhs)\n{\n    if(&rhs == this)\n        return *this;\n\n    patternSize_ = rhs.patternSize();\n    structure_ = rhs.structure_;\n\n    refillMap();\n\n    return *this;\n}\n\nstd::size_t TreeDecompositionDAG::patternSize() const\n{\n    return patternSize_;\n}\n\nstd::size_t TreeDecompositionDAG::numComponents() const\n{\n    return map_.size();\n}\n\nbool TreeDecompositionDAG::hasComponent(const TreeDecompositionSubgraph & component) const\n{\n    return map_.find(component) != map_.end();\n}\n\nvoid TreeDecompositionDAG::addComponent(const TreeDecompositionSubgraph & component)\n{\n    addOrFindNode(component);\n}\n\nstd::pair<TreeDecompositionDAG::ChildIterator, TreeDecompositionDAG::ChildIterator> TreeDecompositionDAG::children(const TreeDecompositionSubgraph & component) const\n{\n    Node n = findExistingNode(component);\n    if(n == invalidDescriptor())\n        return std::make_pair(ChildIterator(), ChildIterator());\n\n    typedef boost::graph_traits<Graph>::out_edge_iterator oei;\n    std::pair<oei, oei> p = boost::out_edges(n, structure_);\n\n    return std::make_pair(\n                boost::make_transform_iterator(p.first, AndNodeTransformer(false, this)),\n                boost::make_transform_iterator(p.second, AndNodeTransformer(false, this))\n                );\n}\n\nstd::pair<TreeDecompositionDAG::ParentIterator, TreeDecompositionDAG::ParentIterator> TreeDecompositionDAG::parents(const TreeDecompositionSubgraph &component) const\n{\n    Node n = findExistingNode(component);\n    if(n == invalidDescriptor())\n        return std::make_pair(ParentIterator(), ParentIterator());\n\n    typedef boost::graph_traits<Graph>::in_edge_iterator iet;\n    std::pair<iet, iet> p = boost::in_edges(n, structure_);\n\n    return std::make_pair(\n                boost::make_transform_iterator(p.first, AndNodeTransformer(true, this)),\n                boost::make_transform_iterator(p.second, AndNodeTransformer(true, this))\n                );\n}\n\nstd::pair<TreeDecompositionDAG::ComponentIterator, TreeDecompositionDAG::ComponentIterator> TreeDecompositionDAG::components() const\n{\n    typedef boost::graph_traits<Graph>::vertex_iterator vit;\n    typedef boost::transform_iterator<ComponentTransformer, vit> transform_it;\n\n    ComponentTransformer transformer(&structure_);\n    ComponentFilter filter(&structure_);\n\n    std::pair<vit, vit> p = boost::vertices(structure_);\n    std::pair<transform_it, transform_it> p2(\n                boost::make_transform_iterator(p.first, transformer),\n                boost::make_transform_iterator(p.second, transformer)\n                );\n\n    return std::make_pair(\n        boost::make_filter_iterator(filter, p2.first, p2.second),\n        boost::make_filter_iterator(filter, p2.second, p2.second)\n                );\n}\n\nTreeDecompositionDAG::Node TreeDecompositionDAG::findExistingNode(const TreeDecompositionSubgraph & component) const\n{\n    boost::unordered_map<TreeDecompositionSubgraph, Node>::const_iterator it = map_.find(component);\n    if(it == map_.end())\n        return invalidDescriptor();\n\n    return it->second;\n}\n\n\nconst std::pair<TreeDecompositionSubgraph, TreeDecompositionDAG::Node> TreeDecompositionDAG::addOrFindNode(const TreeDecompositionSubgraph & component)\n{\n    boost::unordered_map<TreeDecompositionSubgraph, Node>::const_iterator it = map_.find(component);\n\n    // a new node\n    if(it == map_.end())\n    {\n        TreeDecompositionDAGLabel lbl;\n        lbl.vertices = component;\n        lbl.type = TreeDecompositionDAGLabel::NODE_ChildrenOR;\n        Node n = boost::add_vertex(lbl, structure_);\n\n        it = map_.insert(std::make_pair(component, n)).first;\n    }\n\n    return *it;\n}\nvoid TreeDecompositionDAG::remapIndices(const std::vector<std::size_t> &newIndices)\n\n{\n    if(newIndices.size() != patternSize())\n        throw std::logic_error(\"Not a valid indices map\");\n\n    // count them all\n    bool valid = true;\n    std::vector<std::size_t> cnt(patternSize());\n\n    // set the new indices\n    for(std::size_t i =0; i < newIndices.size() && valid; ++i)\n        if(newIndices[i] >= patternSize())\n            valid = false;\n        else\n            ++cnt[newIndices[i]];\n\n    for(std::size_t i = 0; i < cnt.size(); ++i)\n        if(cnt[i] != 1)\n            valid = false;\n\n    if(!valid)\n        throw std::logic_error(\"Not a valid indices map\");\n\n    typedef boost::graph_traits<Graph>::vertex_iterator vit;\n    for(std::pair<vit, vit> p = boost::vertices(structure_); p.first != p.second; ++p.first)\n    {\n        TreeDecompositionDAGLabel & lbl = structure_[*p.first];\n        if(lbl.type == TreeDecompositionDAGLabel::NODE_ChildrenOR)\n            remapComponent(newIndices, lbl.vertices);\n    }\n\n    map_.clear();\n    refillMap();\n}\n\nvoid TreeDecompositionDAG::remapComponent(const std::vector<std::size_t> & newIndices, TreeDecompositionSubgraph & subgraph)\n{\n    TreeDecompositionSubgraph newComp(subgraph.size());\n\n    for(std::size_t i = 0; i < subgraph.size(); ++i)\n        newComp[newIndices[i]] = subgraph[i];\n\n    std::swap(subgraph, newComp);\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::addUnaryAnd(const TreeDecompositionSubgraph & child, const TreeDecompositionSubgraph & parent, TreeDecompositionDAGLabel::NodeType type)\n{\n    const std::pair<TreeDecompositionSubgraph, Node> & c = addOrFindNode(child);\n    const std::pair<TreeDecompositionSubgraph, Node> & p = addOrFindNode(parent);\n\n    // check whether this link already exists\n    for(std::pair<ChildIterator, ChildIterator> p1 = children(parent); p1.first != p1.second; ++p1.first)\n    {\n        TreeDecompositionDAGAndNode andNode = *p1.first;\n        if(andNode.type() == type && andNode.childAt(0) == child)\n            return p.first;\n    }\n\n\n    // add the link\n    TreeDecompositionDAGLabel lbl;\n    lbl.type = type;\n    Node andNode = boost::add_vertex(lbl, structure_);\n\n    boost::add_edge(p.second, andNode, structure_);\n    boost::add_edge(andNode, c.second, structure_);\n\n    return p.first;\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::addNaryAnd(std::vector<TreeDecompositionSubgraph> childComponents, const TreeDecompositionSubgraph & parent, TreeDecompositionDAGLabel::NodeType type)\n{\n    // sort the children\n    std::sort(childComponents.begin(), childComponents.end());\n\n    // find the parent node\n    const std::pair<TreeDecompositionSubgraph, Node> & p = addOrFindNode(parent);\n\n\n    // check whether this link already exists\n    for(std::pair<ChildIterator, ChildIterator> p1 = children(parent); p1.first != p1.second; ++p1.first)\n    {\n        const TreeDecompositionDAGAndNode & andNode = *p1.first;\n        if(andNode.type() != type || andNode.numberOfChildren() != childComponents.size())\n            continue;\n\n        bool allSame = true;\n        for(std::size_t i = 0; i < andNode.numberOfChildren() && allSame; ++i)\n            if(andNode.childAt(i) != childComponents[i])\n                allSame = false;\n\n        if(allSame)\n            return p.first;\n    }\n\n    // now find the child nodes\n    std::vector<Node> childNodes(childComponents.size());\n    for(std::size_t i = 0; i < childNodes.size(); ++i)\n        childNodes[i] = addOrFindNode(childComponents[i]).second;\n\n    // add the link\n    TreeDecompositionDAGLabel lbl;\n    lbl.type = type;\n    Node andNode = boost::add_vertex(lbl, structure_);\n\n    boost::add_edge(p.second, andNode, structure_);\n    for(std::size_t i = 0; i < childNodes.size(); ++i)\n        boost::add_edge(andNode, childNodes[i], structure_);\n\n    return p.first;\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::addBinaryAnd(const TreeDecompositionSubgraph & childA, const TreeDecompositionSubgraph & childB, const TreeDecompositionSubgraph & parent, TreeDecompositionDAGLabel::NodeType type)\n{\n    std::vector<TreeDecompositionSubgraph> nodes(2);\n    nodes[0] = childA;\n    nodes[1] = childB;\n\n    return addNaryAnd(nodes, parent, type);\n}\n\n// addition methods\nTreeDecompositionSubgraph TreeDecompositionDAG::addList(std::size_t vertex)\n{\n    if(vertex > patternSize())\n        throw errOutOfBounds();\n\n    TreeDecompositionSubgraph child(patternSize());\n    TreeDecompositionSubgraph parent(patternSize());\n    parent[vertex] = TreeDecompositionSubgraph::ActiveVertex;\n\n    return addUnaryAnd(child, parent, TreeDecompositionDAGLabel::NODE_ChildrenList);\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::addExtend(const TreeDecompositionSubgraph & child, std::size_t vertexToExtend)\n{\n    if(vertexToExtend > patternSize())\n        throw errOutOfBounds();\n\n    TreeDecompositionSubgraph parent(child);\n\n    if(parent[vertexToExtend] != TreeDecompositionSubgraph::UnseenVertex)\n        throw errNotUnseen();\n\n    parent[vertexToExtend] = TreeDecompositionSubgraph::ActiveVertex;\n\n    return addUnaryAnd(child, parent, TreeDecompositionDAGLabel::NODE_ChildrenExtend);\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::addProject(const TreeDecompositionSubgraph & child, std::size_t vertexToProjectAway)\n{\n    if(vertexToProjectAway > patternSize())\n        throw errOutOfBounds();\n\n    TreeDecompositionSubgraph parent(child);\n    if(parent[vertexToProjectAway] != TreeDecompositionSubgraph::ActiveVertex)\n        throw errNotActive();\n\n    parent[vertexToProjectAway] = TreeDecompositionSubgraph::ProjectedAwayVertex;\n\n    return addUnaryAnd(child, parent, TreeDecompositionDAGLabel::NODE_ChildrenProject);\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::addJoin(const TreeDecompositionSubgraph & lhsComponent, const TreeDecompositionSubgraph & rhsComponent)\n{   \n    TreeDecompositionSubgraph parent(lhsComponent);\n    parent += rhsComponent;\n\n    return addBinaryAnd(lhsComponent, rhsComponent, parent, TreeDecompositionDAGLabel::NODE_ChildrenJoin);\n}\n\n\n// removal method\nvoid TreeDecompositionDAG::removeNode(const TreeDecompositionSubgraph & component)\n{\n    boost::unordered_map<TreeDecompositionSubgraph, Node>::iterator it = map_.find(component);\n    if(it == map_.end())\n        return;\n\n    Node n = it->second;\n\n    typedef boost::graph_traits<Graph>::in_edge_iterator iet;\n    typedef boost::graph_traits<Graph>::out_edge_iterator oei;\n\n    std::set<Node> toRemove;\n    for(std::pair<iet, iet> p = boost::in_edges(n, structure_); p.first != p.second; ++p.first)\n        toRemove.insert(boost::source(*p.first, structure_));\n    for(std::pair<oei, oei> p = boost::out_edges(n, structure_); p.first != p.second; ++p.first)\n        toRemove.insert(boost::target(*p.first, structure_));\n\n\n    for(std::set<Node>::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it)\n    {\n        Node n2 = *it;\n        boost::clear_vertex(n2, structure_);\n        boost::remove_vertex(n2, structure_);\n    }\n\n    boost::remove_vertex(n, structure_);\n    map_.erase(it);\n}\n\n\nvoid TreeDecompositionDAG::removeSubtree(const TreeDecompositionSubgraph & component)\n{\n    // find the root node\n    Node root = findExistingNode(component);\n    if(root == invalidDescriptor())\n        return;\n\n\n\n    // visit the subtree which belongs uniquely to this node\n    boost::unordered_map<Node, std::size_t> degreeMap;\n    boost::unordered_set<Node> toRemove;\n    std::queue<Node> todo;\n\n    degreeMap.insert(std::make_pair(root, boost::in_degree(root, structure_)));\n    todo.push(root);\n\n    while(!todo.empty())\n    {\n        Node cur = todo.front();\n        todo.pop();\n\n        toRemove.insert(cur);\n\n        // check the children of the children\n        typedef boost::graph_traits<Graph>::out_edge_iterator oei;\n        for(std::pair<oei, oei> pAnd = boost::out_edges(cur, structure_); pAnd.first != pAnd.second; ++pAnd.first)\n        {\n            // add the and node\n            Node andNode = boost::target(*pAnd.first, structure_);\n            toRemove.insert(andNode);\n\n            // and add the children which reside only in the subtree\n            for(std::pair<oei, oei> pChild = boost::out_edges(andNode, structure_); pChild.first != pChild.second; ++pChild.first)\n            {\n                Node childNode = boost::target(*pChild.first, structure_);\n                std::size_t & curD = degreeMap[childNode];\n                ++curD;\n\n                // have we seen al the in edges?\n                if(boost::in_degree(childNode, structure_) == curD)\n                    todo.push(childNode);\n            }\n        }\n    }\n\n    // add the and node parent of the component\n    {\n        typedef boost::graph_traits<Graph>::in_edge_iterator iet;\n        for(std::pair<iet, iet> p = boost::in_edges(root, structure_); p.first != p.second; ++p.first)\n            toRemove.insert(boost::source(*p.first, structure_));\n\n    }\n\n    // first clear all the nodes (edges)\n    for(boost::unordered_set<Node>::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it)\n    {\n        Node node = *it;\n        boost::clear_vertex(node, structure_);\n\n        // remove from the map if it is an a or node\n        if(structure_[node].type == TreeDecompositionDAGLabel::NODE_ChildrenOR)\n            map_.erase(structure_[node].vertices);\n\n        // and remove from the graph\n        boost::remove_vertex(node, structure_);\n    }\n}\n\nstd::logic_error TreeDecompositionDAG::errOutOfBounds() const\n{\n    return std::logic_error(\"TreeDecompositionDAG: The supplied vertex is out of bound\");\n}\nstd::logic_error TreeDecompositionDAG::errNotActive() const\n{\n    return std::logic_error(\"TreeDecompositionDAG: The supplied vertex is not active\");\n}\nstd::logic_error TreeDecompositionDAG::errAlreadyActive() const\n{\n    return std::logic_error(\"TreeDecompositionDAG: The supplied vertex is active\");\n}\n\nstd::logic_error TreeDecompositionDAG::errBadRange() const\n{\n    return std::logic_error(\"TreeDecompositionDAG: The supplied range is invalid\");\n}\n\nstd::logic_error TreeDecompositionDAG::errNotUnseen() const\n{\n    return std::logic_error(\"TreeDecompositionDAG: The supplied vertex is not unseen\");\n}\n\nTreeDecompositionDAG::Node TreeDecompositionDAG::invalidDescriptor()\n{\n    return boost::graph_traits<Graph>::null_vertex();\n}\n\nTreeDecompositionDAG::InsertResult TreeDecompositionDAG::checkForInsertion(const TreeDecompositionSubgraph & component, const TreeDecompositionSubgraph & toInsert) const\n{\n    bool thisPossible = true;\n    for(std::size_t i = 0; i < patternSize(); ++i)\n    {\n        if(toInsert[i] == TreeDecompositionSubgraph::ActiveVertex)\n        {\n            if(component[i] == TreeDecompositionSubgraph::UnseenVertex)\n                return NotPossible;\n            else if(component[i] == TreeDecompositionSubgraph::ProjectedAwayVertex)\n                thisPossible = false;\n        }\n        else if(toInsert[i] == TreeDecompositionSubgraph::ProjectedAwayVertex)\n        {\n            if(component[i] != TreeDecompositionSubgraph::UnseenVertex)\n                return NotPossible;\n        }\n    }\n\n    return thisPossible ? CanInsert : MaybeIntoChildren;\n}\n\nbool TreeDecompositionDAG::constructInsertColorMap(Node rootNode, std::set<TreeDecompositionSubgraph> insertNodes, std::map<Node, InsertResult> & map) const\n{\n    map.clear();\n\n    std::stack<Node> todo;\n    todo.push(rootNode);\n    std::set<Node> visitedNodes;\n    std::stack<Node> toVisit;\n\n    // depth first visiting of all nodes\n    while(todo.empty())\n    {\n        Node curNode = todo.top();\n        todo.pop();\n\n        // bookkeeping\n        if(visitedNodes.count(curNode) > 0)\n            continue;\n        visitedNodes.insert(curNode);\n\n        // get the label\n        const TreeDecompositionSubgraph & comp = structure_[curNode].vertices;\n\n        // is this one of the nodes we are looking for?\n        std::set<TreeDecompositionSubgraph>::iterator it = insertNodes.find(comp);\n        if(it != insertNodes.end())\n        {\n            map.insert(std::make_pair(curNode, CanInsert));\n            toVisit.push(curNode);\n        }\n\n        // and continue the of the children\n        typedef boost::graph_traits<Graph>::in_edge_iterator iet;\n        for(std::pair<iet, iet> p1 = boost::in_edges(curNode, structure_); p1.first != p1.second; ++p1.first)\n        {\n            Node andNode = boost::source(*p1.first, structure_);\n            for(std::pair<iet, iet> p2 = boost::in_edges(andNode, structure_); p2.first != p2.second; ++p2.first)\n            {\n                Node childNode = boost::source(*p2.first, structure_);\n                todo.push(childNode);\n            }\n        }\n    }\n\n    // check if all nodes found\n    if(insertNodes.size() != map.size())\n        return false;\n\n    // no go bottom up, and tag all nodes (till rootnode)\n    std::set<Node> visitedParents;\n    while(!toVisit.empty())\n    {\n        Node curNode = toVisit.top();\n        toVisit.pop();\n\n        // bookkeeping\n        if(!visitedParents.insert(curNode).second)\n            continue;\n\n        // if no color, assign intoChild color\n        if(map.count(curNode) == 0)\n            map.insert(std::make_pair(curNode, MaybeIntoChildren));\n\n        // and go to the parents\n        typedef boost::graph_traits<Graph>::out_edge_iterator oei;\n        for(std::pair<oei, oei> p1 = boost::out_edges(curNode, structure_); p1.first != p1.second; ++p1.first)\n        {\n            Node andNode = boost::target(*p1.first, structure_);\n            Node parentNode = boost::target(*boost::out_edges(andNode, structure_).first, structure_);\n\n            if(visitedNodes.count(parentNode) > 0)\n            {\n                map.insert(std::make_pair(andNode, MaybeIntoChildren));\n                toVisit.push(parentNode);\n            }\n        }\n    }\n\n    return true;\n}\n\nTreeDecompositionDAG::InsertResult TreeDecompositionDAG::findInMap(const TreeDecompositionSubgraph & component, const InsertionMap & map) const\n{\n    InsertionMap::const_iterator it = map.find(component);\n    return it == map.end() ? NotPossible : it->second;\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::insert(const TreeDecompositionSubgraph & rootComponent, const TreeDecompositionSubgraph & toInsertComponent, const InsertionMap & insertionMap)\n{\n    // check for validity\n    if(!hasComponent(rootComponent))\n        throw errBadRange();\n\n    if(findInMap(rootComponent, insertionMap) == NotPossible)\n        throw errBadRange();\n\n\n    std::stack<TreeDecompositionSubgraph> todo;\n    std::set<TreeDecompositionSubgraph> handledNodes;\n    todo.push(rootComponent);\n\n    while(!todo.empty())\n    {\n        TreeDecompositionSubgraph curComp = todo.top();\n        todo.pop();\n\n        // already handled?\n        if(!handledNodes.insert(curComp).second)\n            continue;\n\n        InsertResult result = findInMap(curComp, insertionMap);\n        if(result == NotPossible)\n            continue;\n\n        if(result == CanInsert)\n        {\n            if(!partial_order_compare(curComp, toInsertComponent))\n                addJoin(curComp, toInsertComponent);\n        }\n\n        // loop over the children\n        for(std::pair<ChildIterator, ChildIterator> p = children(curComp); p.first != p.second; ++p.first)\n        {\n            const TreeDecompositionDAGAndNode & andNode = *p.first;\n\n            switch(andNode.type())\n            {\n            case TreeDecompositionDAGLabel::NODE_ChildrenExtend:\n            {\n                const TreeDecompositionSubgraph & child = andNode.childAt(0);\n                if(findInMap(child, insertionMap) != NotPossible)\n                {\n                    todo.push(child);\n                    addExtend(createInsertComponent(child, toInsertComponent), andNode.extendVertex());\n                }\n\n                break;\n            }\n\n            case TreeDecompositionDAGLabel::NODE_ChildrenProject:\n            {\n                const TreeDecompositionSubgraph & child = andNode.childAt(0);\n                if(findInMap(child, insertionMap) != NotPossible)\n                {\n                    todo.push(child);\n                    addProject(createInsertComponent(child, toInsertComponent), andNode.projectAwayVertices().begin(), andNode.projectAwayVertices().end());\n                }\n\n                break;\n            }\n\n\n            case TreeDecompositionDAGLabel::NODE_ChildrenJoin:\n            {\n                std::vector<TreeDecompositionSubgraph> children(andNode.numberOfChildren());\n\n                for(std::size_t i = 0; i < andNode.numberOfChildren(); ++i)\n                    children[i] = andNode.childAt(i);\n\n                for(std::size_t i = 0; i < andNode.numberOfChildren(); ++i)\n                {\n                    if(findInMap(children[i], insertionMap) != NotPossible)\n                    {\n                        todo.push(children[i]);\n                        children[i] = createInsertComponent(children[i], toInsertComponent);\n                        addJoin(children.begin(), children.end());\n\n                        children[i] = andNode.childAt(i);\n                    }\n                }\n                break;\n            }\n\n            default:\n                break;\n            }\n\n        }\n    }\n\n    return createInsertComponent(rootComponent, toInsertComponent);\n}\n\nTreeDecompositionSubgraph TreeDecompositionDAG::createInsertComponent(const TreeDecompositionSubgraph & node, const TreeDecompositionSubgraph & toInsertComponent) const\n{\n    TreeDecompositionSubgraph result(patternSize());\n\n    for(std::size_t i = 0 ; i < patternSize(); ++i)\n        result[i] = (node[i] == TreeDecompositionSubgraph::UnseenVertex ? toInsertComponent[i] : node[i]);\n\n    return result;\n}\n\n\n\nnamespace {\n\ntemplate <typename LabelMap>\nstruct TreeDecompositionDAGLabel_DOTWriter\n{\n    typedef typename boost::property_traits<LabelMap>::key_type KeyType;\n    typedef std::set<TreeDecompositionSubgraph> Keys;\n\n    TreeDecompositionDAGLabel_DOTWriter(const LabelMap & map, const Keys & selectedKeys = Keys())\n        : map_(map),\n          selectedKeys_(selectedKeys)\n    {\n    }\n\n    template <typename VertexDescriptor>\n    void operator()(std::ostream & str, const VertexDescriptor & vd) const\n    {\n        typedef typename boost::property_traits<LabelMap>::value_type LabelType;\n        const LabelType & label = boost::get(map_, vd);\n\n        str << \"[label=\\\"\";\n\n        if((label.type & TreeDecompositionDAGLabel::NODE_ORANDMASK) == TreeDecompositionDAGLabel::NODE_ChildrenAND)\n        {\n            switch(label.type)\n            {\n            case TreeDecompositionDAGLabel::NODE_ChildrenExtend:\n                str << \"Extend\";\n                break;\n            case TreeDecompositionDAGLabel::NODE_ChildrenJoin:\n                str << \"Join\";\n                break;\n            case TreeDecompositionDAGLabel::NODE_ChildrenList:\n                str << \"List\";\n                break;\n            case TreeDecompositionDAGLabel::NODE_ChildrenProject:\n                str << \"Project\";\n                break;\n            default:\n                str << \"Unknown\";\n                break;\n            }\n        }\n        else\n        {\n            str << \"{\";\n            unsigned int written = 0;\n            for(unsigned int i = 0; i < label.vertices.size(); ++i)\n                if(label.vertices[i] == TreeDecompositionSubgraph::ActiveVertex)\n                {\n                    if(written++ != 0)\n                        str << \", \";\n                    str << \"v\" << i;\n                }\n            str << \"}, *{\";\n            written = 0;\n            for(unsigned int i = 0; i < label.vertices.size(); ++i)\n                if(label.vertices[i] == TreeDecompositionSubgraph::ProjectedAwayVertex)\n                {\n                    if(written++ != 0)\n                        str << \", \";\n                    str << \"v\" << i;\n                }\n            str << \"}\";\n        }\n\n        str << \"\\\"\";\n\n        if(selectedKeys_.count(label.vertices) > 0)\n            str << \"color=red; style=filled;\";\n\n\n        str << \"]\";\n    }\n\n    LabelMap map_;\n    Keys selectedKeys_;\n\n};\n\n\n\ntemplate <typename VertexLabelWriter, typename DAGType>\nvoid write_dot_format_helper(\n        const DAGType & dag,\n        std::ostream & stream,\n        const std::set<TreeDecompositionSubgraph> & chosenNodes = std::set<TreeDecompositionSubgraph>())\n{\n    typedef typename boost::property_map<DAGType, boost::vertex_bundle_t>::const_type DAG_Label;\n    typedef typename boost::graph_traits<DAGType>::vertex_iterator vertexIterator;\n    typedef typename boost::graph_traits<DAGType>::vertex_descriptor vertexDescriptor;\n    typedef std::map<vertexDescriptor, std::size_t> VertexIDAssocContainer;\n    typedef VertexLabelWriter LabelWriter;\n\n    // create vertexID MAP\n    VertexIDAssocContainer map;\n    boost::associative_property_map<VertexIDAssocContainer> vertexIDMap(map);\n\n    // fill the map\n    unsigned int count = 0;\n    for(std::pair<vertexIterator, vertexIterator> p = boost::vertices(dag); p.first != p.second; ++p.first)\n        map[*p.first] = count++;\n\n\n    DAG_Label lmap = boost::get(boost::vertex_bundle, dag);\n    VertexLabelWriter w(lmap, chosenNodes);\n\n    boost::write_graphviz(stream, dag, w, boost::default_writer(), boost::default_writer(), vertexIDMap);\n}\n\n} //  namespace\n\nvoid TreeDecompositionDAG::writeGraphviz(std::ostream & stream, const std::set<TreeDecompositionSubgraph> & activeComponents) const\n{\n    typedef boost::property_map<Graph, boost::vertex_bundle_t>::const_type DAG_Label;\n    typedef TreeDecompositionDAGLabel_DOTWriter<DAG_Label> LabelWriter;\n\n    write_dot_format_helper<LabelWriter>(structure_, stream, activeComponents);\n}\n\nvoid TreeDecompositionDAG::cleanUp(const TreeDecompositionSubgraph & rootComponent)\n{\n    Node node = findExistingNode(rootComponent);\n    if(node == invalidDescriptor())\n    {\n        structure_.clear();\n        map_.clear();\n    }\n\n    // visit all child nodes\n    std::set<Node> visitedNodes;\n    std::stack<Node> todo;\n    todo.push(node);\n\n    while(!todo.empty())\n    {\n        Node curNode = todo.top();\n        todo.pop();\n\n        // already seen\n        if(!visitedNodes.insert(curNode).second)\n            continue;\n\n        typedef boost::graph_traits<Graph>::out_edge_iterator oei;\n        for(std::pair<oei, oei> p1 = boost::out_edges(curNode, structure_); p1.first != p1.second; ++p1.first)\n        {\n            Node andNode = boost::target(*p1.first, structure_);\n            visitedNodes.insert(andNode);\n\n            for(std::pair<oei, oei> p2 = boost::out_edges(andNode, structure_); p2.first != p2.second; ++p2.first)\n            {\n                todo.push(boost::target(*p2.first, structure_));\n            }\n        }\n    }\n\n    // list all nodes to remove\n    typedef boost::graph_traits<Graph>::vertex_iterator vit;\n    std::list<TreeDecompositionSubgraph> toRemove;\n    for(std::pair<vit, vit> p = boost::vertices(structure_); p.first != p.second; ++p.first)\n    {\n        const TreeDecompositionDAGLabel & lbl = structure_[*p.first];\n        if(lbl.type == TreeDecompositionDAGLabel::NODE_ChildrenOR && visitedNodes.count(*p.first) == 0)\n            toRemove.push_back(lbl.vertices);\n    }\n\n    for(std::list<TreeDecompositionSubgraph>::iterator it = toRemove.begin(); it != toRemove.end(); ++it)\n        removeNode(*it);\n}\n\nnamespace {\n\nstd::size_t convertToInt(const std::string & str)\n{\n    return boost::lexical_cast<std::size_t>(str);\n}\n\n\n\nstd::string convertToString(const TreeDecompositionDAGLabel & label)\n{\n    std::stringstream str;\n    str << static_cast<int>(label.type) << ',' << label.vertices.size() << ',';\n    for(std::size_t i = 0; i < label.vertices.size(); ++i)\n    {\n        if(label.vertices[i] == TreeDecompositionSubgraph::ActiveVertex)\n            str << \"a\";\n        else if(label.vertices[i] == TreeDecompositionSubgraph::ProjectedAwayVertex)\n            str << \"p\";\n        else if(label.vertices[i] == TreeDecompositionSubgraph::UnseenVertex)\n            str << \"u\";\n        else\n            throw std::logic_error(\"Bad formatted TreeDecompositionSubgraph\");\n    }\n\n    return str.str();\n}\n\nTreeDecompositionDAGLabel convertFromString(const std::string & str)\n{\n    std::vector<std::string> vct;\n    boost::split(vct, str, boost::is_any_of(\",\"));\n\n    if(vct.size() < 2)\n        throw std::logic_error(\"Bad formatted TreeDecompositionSubgraph\");\n\n    TreeDecompositionDAGLabel lbl;\n    lbl.type = static_cast<TreeDecompositionDAGLabel::NodeType>(convertToInt(vct[0]));\n    lbl.vertices = TreeDecompositionSubgraph(convertToInt(vct[1]));\n\n    if(lbl.vertices.size() != 0)\n    {\n        if(vct.size() < 3 || vct[2].size() != lbl.vertices.size())\n            throw std::logic_error(\"Bad formatted TreeDecompositionSubgraph\");\n\n        for(std::size_t i = 0; i < lbl.vertices.size(); ++i)\n            if(vct[2][i] == 'a')\n                lbl.vertices[i] = TreeDecompositionSubgraph::ActiveVertex;\n            else if(vct[2][i] == 'p')\n                lbl.vertices[i] = TreeDecompositionSubgraph::ProjectedAwayVertex;\n            else if(vct[2][i] == 'u')\n                lbl.vertices[i] = TreeDecompositionSubgraph::UnseenVertex;\n            else\n                throw std::logic_error(\"Bad formatted TreeDecompositionSubgraph\");\n\n    }\n\n    return lbl;\n}\n\n} //  namespace\n\n\nvoid TreeDecompositionDAG::serialize(std::ostream & stream) const\n{\n    typedef boost::graph_traits<Graph>::vertex_iterator vit;\n\n    stream << \"t # \" << patternSize() << std::endl;\n\n    // write the vertices\n    std::map<Node, std::size_t> positionMap;\n    std::size_t count = 0;\n    for(std::pair<vit, vit> p = vertices(structure_); p.first != p.second; ++p.first, ++count)\n    {\n        Node v = *p.first;\n        stream << \"v \" << count << \" \" << convertToString(structure_[v]) << std::endl;\n        positionMap.insert(std::make_pair(v, count));\n    }\n\n    // write the edges\n    typedef boost::graph_traits<Graph>::edge_iterator eit;\n    for(std::pair<eit, eit> p = boost::edges(structure_); p.first != p.second; ++p.first)\n    {\n        Node src = boost::source(*p.first, structure_);\n        Node tgt = boost::target(*p.first, structure_);\n\n        stream << \"e \" << positionMap.find(src)->second << \" \" << positionMap.find(tgt)->second << \"  \" << std::endl;\n    }\n}\n\nbool TreeDecompositionDAG::deserialize(std::istream & stream)\n{\n    std::string line;\n    std::size_t pos = 0;\n\n    std::vector<Node> nodevct;\n\n    try\n    {\n        while(std::getline(stream, line))\n        {\n            std::vector<std::string> vct;\n            boost::split(vct, line, boost::is_any_of(\" \"));\n\n            if(vct.empty())\n                continue;\n\n            if(pos == 0)\n            {\n                if(vct.size() != 3 && vct[0] != \"t\" && vct[1] != \"#\")\n                    return false;\n\n                patternSize_ = convertToInt(vct[2]);\n\n                // initialise the graph\n                structure_.clear();\n                pos = 1;\n            }\n            else if(pos == 1)\n            {\n                if(vct[0]  != \"v\")\n                {\n                    pos = 2;\n                }\n                else\n                {\n                    nodevct.push_back(boost::add_vertex(convertFromString(vct[2]), structure_));\n                }\n            }\n            if(pos == 2)\n            {\n                if(vct[0] != \"e\")\n                    return false;\n\n                std::size_t src = convertToInt(vct[1]);\n                std::size_t dst = convertToInt(vct[2]);\n                boost::add_edge(nodevct[src], nodevct[dst], structure_);\n            }\n        }\n    }\n    catch(...)\n    {\n        structure_.clear();\n        patternSize_ = 0;\n        map_.clear();\n    }\n\n    refillMap();\n\n    return true;\n}\n\nvoid TreeDecompositionDAG::refillMap()\n{\n    map_.clear();\n\n    typedef boost::graph_traits<Graph>::vertex_iterator vit;\n    for(std::pair<vit, vit> p = boost::vertices(structure_); p.first != p.second; ++p.first)\n    {\n        const TreeDecompositionDAGLabel & lbl = structure_[*p.first];\n        if(lbl.type == TreeDecompositionDAGLabel::NODE_ChildrenOR)\n            map_.insert(std::make_pair(lbl.vertices, *p.first));\n    }\n}\n\nvoid TreeDecompositionDAG::writeGraphviz(std::ostream & stream) const\n{\n    writeGraphviz(stream, std::set<TreeDecompositionSubgraph>());\n}\n\nnamespace {\n\ntypedef std::map<TreeDecompositionSubgraph, std::size_t> DegreeMap;\ntypedef std::set<TreeDecompositionSubgraph> VisitedNodeSet;\n\nVisitedNodeSet visitSubdag(const TreeDecompositionDAG & dag, const TreeDecompositionSubgraph & rootComponent)\n{\n    VisitedNodeSet visitedSubgraph;\n    std::stack<TreeDecompositionSubgraph> todo;\n    todo.push(rootComponent);\n\n    // loop over the children of the root component\n    while(!todo.empty())\n    {\n        TreeDecompositionSubgraph comp = todo.top();\n        todo.pop();\n\n        // already seen?\n        if(!visitedSubgraph.insert(comp).second)\n            continue;\n\n        // visit all the children\n        for(std::pair<TreeDecompositionDAG::ChildIterator, TreeDecompositionDAG::ChildIterator> p = dag.children(comp); p.first != p.second; ++p.first)\n        {\n            const TreeDecompositionDAGAndNode & andNode = *p.first;\n            for(std::size_t i = 0; i < andNode.numberOfChildren(); ++i)\n                todo.push(andNode.childAt(i));\n        }\n    }\n\n    return visitedSubgraph;\n}\n\nDegreeMap fillDegreeMap(const VisitedNodeSet & visitedNodes, const TreeDecompositionDAG & dag)\n{\n    DegreeMap map;\n    for(VisitedNodeSet::const_iterator it = visitedNodes.begin(); it != visitedNodes.end(); ++it)\n    {\n        const TreeDecompositionSubgraph & comp = *it;\n        std::size_t count = 0;\n        for(std::pair<TreeDecompositionDAG::ParentIterator, TreeDecompositionDAG::ParentIterator> p = dag.parents(comp); p.first != p.second; ++p.first)\n        {\n            const TreeDecompositionDAGAndNode & andNode = *p.first;\n            count += visitedNodes.count(andNode.parent());\n        }\n\n        map.insert(std::make_pair(comp, count));\n    }\n\n    return map;\n}\n\nstd::list<TreeDecompositionSubgraph> extractAndRemoveZeros(DegreeMap & map)\n{\n    std::list<TreeDecompositionSubgraph> zeros;\n\n    for(DegreeMap::const_iterator it = map.begin(); it != map.end(); ++it)\n        if(it->second == 0)\n            zeros.push_back(it->first);\n\n    for(std::list<TreeDecompositionSubgraph>::const_iterator it = zeros.begin(); it != zeros.end(); ++it)\n        map.erase(*it);\n\n    return zeros;\n}\n\n\n\n\n} //  namespace\n\nstd::vector<TreeDecompositionSubgraph> TreeDecompositionDAG::topologicalOrder(const TreeDecompositionSubgraph & rootComponent) const\n{\n    VisitedNodeSet nodes = visitSubdag(*this, rootComponent);\n    DegreeMap degreeMap = fillDegreeMap(nodes, *this);\n\n    std::vector<TreeDecompositionSubgraph> result;\n\n    // perform the sorting\n    while(!degreeMap.empty())\n    {\n        // extract the non-zero's\n        const std::list<TreeDecompositionSubgraph> & zeros = extractAndRemoveZeros(degreeMap);\n        if(zeros.empty())\n            throw std::logic_error(\"TreeDecompositionDAG: Not in DAG order\");\n\n        // add them to the list\n        result.insert(result.end(), zeros.begin(), zeros.end());\n\n        // and process the children\n        for(std::list<TreeDecompositionSubgraph>::const_iterator it = zeros.begin(); it != zeros.end(); ++it)\n        {\n            const TreeDecompositionSubgraph & comp = *it;\n            for(std::pair<ChildIterator, ChildIterator> p = children(comp); p.first != p.second; ++p.first)\n            {\n                const TreeDecompositionDAGAndNode & andNode = *p.first;\n                for(std::size_t i = 0; i < andNode.numberOfChildren(); ++i)\n                    --degreeMap[andNode.childAt(i)];\n            }\n        }\n    }\n\n    return result;\n}\n\nstd::vector<TreeDecompositionSubgraph> TreeDecompositionDAG::topologicalOrder() const\n{\n    VisitedNodeSet nodes;\n\n    typedef boost::graph_traits<Graph>::vertex_iterator vit;\n    for(std::pair<vit, vit> p = boost::vertices(structure_); p.first != p.second; ++p.first)\n    {\n        const TreeDecompositionDAGLabel & lbl = structure_[*p.first];\n        if(lbl.type == TreeDecompositionDAGLabel::NODE_ChildrenOR)\n            nodes.insert(lbl.vertices);\n    }\n\n    DegreeMap degreeMap = fillDegreeMap(nodes, *this);\n\n    std::vector<TreeDecompositionSubgraph> result;\n\n    // perform the sorting\n    while(!degreeMap.empty())\n    {\n        // extract the non-zero's\n        const std::list<TreeDecompositionSubgraph> & zeros = extractAndRemoveZeros(degreeMap);\n        if(zeros.empty())\n            throw std::logic_error(\"TreeDecompositionDAG: Not in DAG order\");\n\n        // add them to the list\n        result.insert(result.end(), zeros.begin(), zeros.end());\n\n        // and process the children\n        for(std::list<TreeDecompositionSubgraph>::const_iterator it = zeros.begin(); it != zeros.end(); ++it)\n        {\n            const TreeDecompositionSubgraph & comp = *it;\n            for(std::pair<ChildIterator, ChildIterator> p = children(comp); p.first != p.second; ++p.first)\n            {\n                const TreeDecompositionDAGAndNode & andNode = *p.first;\n                for(std::size_t i = 0; i < andNode.numberOfChildren(); ++i)\n                    --degreeMap[andNode.childAt(i)];\n            }\n        }\n    }\n\n    return result;\n}\n\nnamespace {\n\nstd::size_t childrenTreewidth(const TreeDecompositionDAGAndNode & andNode, const std::map<TreeDecompositionSubgraph, std::size_t> & sizeMap)\n{\n    std::size_t curMax = sizeMap.find(andNode.childAt(0))->second;\n    if(andNode.numberOfChildren() == 2)\n        curMax = std::max(curMax, sizeMap.find(andNode.childAt(1))->second);\n\n    return curMax;\n}\n\n\n} //  namespace\n\nvoid TreeDecompositionDAG::removeAndNode(const TreeDecompositionDAGAndNode & andNode)\n{\n    Node n = findExistingNode(andNode.parent());\n    if(n == invalidDescriptor())\n        return;\n\n    // find the node\n    typedef boost::graph_traits<Graph>::out_edge_iterator oei;\n\n    for(std::pair<oei, oei> p = boost::out_edges(n, structure_); p.first != p.second; ++p.first)\n    {\n        Node an = boost::target(*p.first, structure_);\n\n        if(TreeDecompositionDAGAndNode(this, an) == andNode)\n        {\n            boost::clear_vertex(an, structure_);\n            boost::remove_vertex(an, structure_);\n\n            return;\n        }\n    }\n}\n\nstd::size_t TreeDecompositionDAG::calculateTreewidth(const TreeDecompositionSubgraph & rootComponent) const\n{\n    const std::vector<TreeDecompositionSubgraph> & order = topologicalOrder(rootComponent);\n    std::map<TreeDecompositionSubgraph, std::size_t> sizeMap;\n\n    std::size_t result = 0;\n\n\n    for(std::vector<TreeDecompositionSubgraph>::const_reverse_iterator it = order.rbegin(); it != order.rend(); ++it)\n    {\n        const TreeDecompositionSubgraph & component = *it;\n        std::size_t curSize = component.count(TreeDecompositionSubgraph::ActiveVertex);\n\n        // find the minimum value over the children\n        std::size_t minValue = std::numeric_limits<std::size_t>::max();\n        for(std::pair<ChildIterator, ChildIterator> p = children(component); p.first != p.second; ++p.first)\n            minValue = std::min(minValue, childrenTreewidth(*p.first, sizeMap));\n\n        // update the value\n        curSize = minValue == std::numeric_limits<std::size_t>::max() ? curSize : std::max(curSize, minValue);\n\n        // insert in the map\n        sizeMap.insert(std::make_pair(component, curSize));\n\n        result = std::max(curSize, result);\n    }\n\n    return result - 1;\n}\n\nvoid TreeDecompositionDAG::makeMinimalTreewidth(const TreeDecompositionSubgraph & rootComponent)\n{\n    std::list<TreeDecompositionDAGAndNode> toRemove;\n\n    const std::vector<TreeDecompositionSubgraph> & order = topologicalOrder(rootComponent);\n    std::map<TreeDecompositionSubgraph, std::size_t> sizeMap;\n\n\n    for(std::vector<TreeDecompositionSubgraph>::const_reverse_iterator it = order.rbegin(); it != order.rend(); ++it)\n    {\n        const TreeDecompositionSubgraph & component = *it;\n        std::size_t curSize = component.count(TreeDecompositionSubgraph::ActiveVertex);\n\n        // find the minimum value over the children\n        std::size_t minValue = std::numeric_limits<std::size_t>::max();\n        for(std::pair<ChildIterator, ChildIterator> p = children(component); p.first != p.second; ++p.first)\n            minValue = std::min(minValue, childrenTreewidth(*p.first, sizeMap));\n\n        // find the children which should be removed\n        for(std::pair<ChildIterator, ChildIterator> p = children(component); p.first != p.second; ++p.first)\n        {\n            const TreeDecompositionDAGAndNode & andNode = *p.first;\n            if(childrenTreewidth(andNode, sizeMap) > minValue)\n                toRemove.push_back(andNode);\n        }\n\n        // update the value\n        curSize = minValue == std::numeric_limits<std::size_t>::max() ? curSize : std::max(curSize, minValue);\n\n        // insert in the map\n        sizeMap.insert(std::make_pair(component, curSize));\n    }\n\n    // and now remove these links\n    for(std::list<TreeDecompositionDAGAndNode>::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it)\n        removeAndNode(*it);\n}\n\nbool TreeDecompositionDAG::isBinary() const\n{\n    typedef boost::graph_traits<Graph>::vertex_iterator vit;\n    for(std::pair<vit, vit> p = boost::vertices(structure_); p.first != p.second; ++p.first)\n        if(structure_[*p.first].type != TreeDecompositionDAGLabel::NODE_ChildrenOR && boost::out_degree(*p.first, structure_) > 2)\n            return false;\n\n    return true;\n}\n\n\nTreeDecompositionSubgraph TreeDecompositionDAG::getRootNode() const\n{\n    TreeDecompositionSubgraph result;\n\n    for(std::pair<ComponentIterator, ComponentIterator> p = components(); p.first != p.second; ++p.first)\n    {\n        std::pair<ParentIterator, ParentIterator> pit = parents(*p.first);\n        if(pit.first == pit.second)\n        {\n            if(result.size() != 0)\n                throw std::logic_error(\"TreeDecompositionDAG: The treedecomposition dag has multiple roots\");\n\n            result = *p.first;\n        }\n    }\n\n    return result;\n}\n\nstd::vector<TreeDecompositionSubgraph> TreeDecompositionDAG::getRootNodes() const\n{\n    std::vector<TreeDecompositionSubgraph> roots;\n    for(std::pair<ComponentIterator, ComponentIterator> p = components(); p.first != p.second; ++p.first)\n    {\n        std::pair<ParentIterator, ParentIterator> pit = parents(*p.first);\n        if(pit.first == pit.second)\n            roots.push_back(*p.first);\n    }\n\n    return roots;\n}\n\nnamespace {\n\nvoid findCompleteJoinVertices(const TreeDecompositionDAGAndNode & andNode, std::vector<TreeDecompositionSubgraph> & completeNodes, std::vector<TreeDecompositionSubgraph> & nonCompleteNodes)\n{\n    assert(andNode.type() == TreeDecompositionDAGLabel::NODE_ChildrenJoin);\n    const std::vector<std::size_t> & joinVertices = andNode.joinVertices();\n\n    for(std::size_t i = 0; i < andNode.numberOfChildren(); ++i)\n    {\n        const TreeDecompositionSubgraph & cur = andNode.childAt(i);\n\n        bool allSet = true;\n        for(std::vector<std::size_t>::const_iterator it = joinVertices.begin(); it != joinVertices.end() && allSet; ++it)\n            if(cur[*it] != TreeDecompositionSubgraph::ActiveVertex)\n                allSet = false;\n\n        if(allSet)\n            completeNodes.push_back(cur);\n        else\n            nonCompleteNodes.push_back(cur);\n    }\n}\n\nvoid performAllPermutationsJoin(std::vector<TreeDecompositionSubgraph> & completeChildren, std::vector<TreeDecompositionSubgraph> & nonCompleteChildren, TreeDecompositionDAG & dag)\n{\n    std::sort(completeChildren.begin(), completeChildren.end());\n    std::sort(nonCompleteChildren.begin(), nonCompleteChildren.end());\n\n    TreeDecompositionSubgraph result;\n    do\n    {\n        TreeDecompositionSubgraph curResult = completeChildren[0];\n        for(std::size_t i = 1; i < completeChildren.size(); ++i)\n            curResult = dag.addJoin(curResult, completeChildren[i]);\n\n        result = curResult;\n    }\n    while(std::next_permutation(completeChildren.begin(), completeChildren.end()));\n\n    do\n    {\n        TreeDecompositionSubgraph curResult = result;\n        for(std::size_t i = 0; i < nonCompleteChildren.size(); ++i)\n            curResult = dag.addJoin(curResult, nonCompleteChildren[i]);\n    }\n    while(std::next_permutation(nonCompleteChildren.begin(), nonCompleteChildren.end()));\n}\n\nvoid performSimpleJoin(std::vector<TreeDecompositionSubgraph> & completeChildren, std::vector<TreeDecompositionSubgraph> & nonCompleteChildren, TreeDecompositionDAG & dag)\n{\n    TreeDecompositionSubgraph result = completeChildren[0];\n    for(std::size_t i = 1; i < completeChildren.size(); ++i)\n        result = dag.addJoin(result, completeChildren[i]);\n\n    for(std::size_t i = 0; i < nonCompleteChildren.size(); ++i)\n        result = dag.addJoin(result, nonCompleteChildren[i]);\n}\n\nvoid make_binary_node(const TreeDecompositionDAGAndNode & andNode, TreeDecompositionDAG & dag, bool usePermutations)\n{\n    TreeDecompositionSubgraph parent = andNode.parent();\n    std::vector<TreeDecompositionSubgraph> completeChildren, nonCompleteChildren;\n\n    // find the complete and the non-complete children\n    findCompleteJoinVertices(andNode, completeChildren, nonCompleteChildren);\n    assert(!completeChildren.empty());\n\n    // remove the and node\n    dag.removeAndNode(andNode);\n\n    // and now join the children\n    if(usePermutations)\n        performAllPermutationsJoin(completeChildren, nonCompleteChildren, dag);\n    else\n        performSimpleJoin(completeChildren, nonCompleteChildren, dag);\n}\n\n} //  namespace\n\nvoid make_binary_treedecomposition(TreeDecompositionDAG & dag, bool useAllPermutations)\n{\n    std::stack<TreeDecompositionDAGAndNode> nonBinaryAndNodes;\n\n    typedef TreeDecompositionDAG::ComponentIterator cit;\n    typedef TreeDecompositionDAG::ChildIterator chit;\n\n    // find out all the non-binary and nodes\n    for(std::pair<cit, cit> p = dag.components(); p.first != p.second; ++p.first)\n    {\n        for(std::pair<chit, chit> p2 = dag.children(*p.first); p2.first != p2.second; ++p2.first)\n        {\n            const TreeDecompositionDAGAndNode & andNode = *p2.first;\n            if(andNode.type() == TreeDecompositionDAGLabel::NODE_ChildrenJoin && andNode.numberOfChildren() > 2)\n                nonBinaryAndNodes.push(andNode);\n        }\n    }\n\n    // and make them binary\n    while(!nonBinaryAndNodes.empty())\n    {\n        TreeDecompositionDAGAndNode andNode = nonBinaryAndNodes.top();\n        nonBinaryAndNodes.pop();\n        make_binary_node(andNode, dag, useAllPermutations);\n    }\n}\n\nvoid swap(TreeDecompositionDAG & lhs, TreeDecompositionDAG & rhs)\n{\n    using std::swap;\n\n    swap(lhs.structure_, rhs.structure_);\n    swap(lhs.map_, rhs.map_);\n    swap(lhs.patternSize_, rhs.patternSize_);\n}\n\n} // treeDAG namespace\n", "meta": {"hexsha": "21bba5f73a29aea580e7a93dd0359a90a29c0c3c", "size": 48785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "treeDAG/treeDecompositionDAG.cpp", "max_stars_repo_name": "thomasfannes/treeDAG", "max_stars_repo_head_hexsha": "c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "treeDAG/treeDecompositionDAG.cpp", "max_issues_repo_name": "thomasfannes/treeDAG", "max_issues_repo_head_hexsha": "c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "treeDAG/treeDecompositionDAG.cpp", "max_forks_repo_name": "thomasfannes/treeDAG", "max_forks_repo_head_hexsha": "c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c", "max_forks_repo_licenses": ["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.3230874317, "max_line_length": 228, "alphanum_fraction": 0.646551194, "num_tokens": 11903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.024053554643448508, "lm_q1q2_score": 0.008730699950359811}}
{"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\n#include <Eigen/Dense>\n#include <assimp/Importer.hpp>\n#include <assimp/postprocess.h>\n#include <assimp/scene.h>\n#include <fcl/geometry/bvh/BVH_model.h>\n#include <fcl/narrowphase/collision.h>\n#include <functional>\n#include <memory>\n#include <mpt/discrete_motion_validator.hpp>\n#include <mpt/goal_state.hpp>\n#include <mpt/log.hpp>\n#include <mpt/se3_space.hpp>\n#include <mpt/uniform_sampler.hpp>\n#include <nigh/kdtree_batch.hpp>\n\n#include <cuda.h>\n\n#define BATCH_SIZE 32\n#define NN_TYPE KDTreeBatch\n#define SCALAR_TYPE float\nnamespace mpt_demo::impl {\n    static constexpr std::intmax_t SO3_WEIGHT = 50;\n    using Vec3 = Eigen::Matrix<float, 3, 1>;\n\n    // silence the warnings \"taking address of packed member 'a1' of\n    // class or structure 'aiMatrix4x4t<float>' may result in an\n    // unaligned pointer value\" We use static_asserts to ensure\n    // unaligned structures will not happen.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Waddress-of-packed-member\"\n\n    template <typename Scalar>\n    auto mapToEigen(const aiMatrix4x4t<Scalar>& m) {\n        using EigenType = const Eigen::Matrix<Scalar, 4, 4, Eigen::RowMajor>;\n        static_assert(sizeof(EigenType) == sizeof(m));\n        return Eigen::Map<EigenType>(&m.a1);\n    }\n\n    template <typename Scalar>\n    auto mapToEigen(const aiVector3t<Scalar>& v) {\n        using EigenType = const Eigen::Matrix<Scalar, 3, 1>;\n        static_assert(sizeof(EigenType) == sizeof(v));\n        return Eigen::Map<const EigenType>(&v.x);\n    }\n#pragma GCC diagnostic pop\n\n    template <typename Scalar, typename Fn>\n    std::size_t visitVertices(\n        const aiScene* scene, const aiNode *node,\n        Eigen::Transform<Scalar, 3, Eigen::Affine> transform,\n        Fn&& visitor)\n    {\n        std::size_t count = 0;\n        transform *= mapToEigen(node->mTransformation).template cast<Scalar>();\n        for (unsigned i=0 ; i < node->mNumMeshes ; ++i) {\n            const aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];\n            count += mesh->mNumVertices;\n            for (unsigned j=0 ; j < mesh->mNumVertices ; ++j)\n                visitor(transform * mapToEigen(mesh->mVertices[j]).template cast<Scalar>());\n        }\n        for (unsigned i=0 ; i < node->mNumChildren ; ++i)\n            count += visitVertices(scene, node->mChildren[i], transform, std::forward<Fn>(visitor));\n        return count;\n    }\n\n    template <typename Scalar, typename Fn>\n    static std::size_t visitTriangles(\n        const aiScene *scene, const aiNode *node,\n        Eigen::Transform<Scalar, 3, Eigen::Affine> transform,\n        Fn&& visitor)\n    {\n        std::size_t count = 0;\n\n        transform *= mapToEigen(node->mTransformation).template cast<Scalar>();\n        for (unsigned i=0 ; i<node->mNumMeshes ; ++i) {\n            const aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];\n            for (unsigned j=0 ; j<mesh->mNumFaces ; ++j) {\n                const aiFace& face = mesh->mFaces[j];\n                if (face.mNumIndices < 3)\n                    continue;\n\n                // Support trangular decomposition by fanning out\n                // around vertex 0.  The indexing follows as:\n                //\n                //   0---1   0 1 2\n                //  /|\\ /    0 2 3\n                // 4-3-2     0 3 4\n                //\n                Vec3 v0 = transform * mapToEigen(mesh->mVertices[face.mIndices[0]]).template cast<Scalar>();\n                Vec3 v1 = transform * mapToEigen(mesh->mVertices[face.mIndices[1]]).template cast<Scalar>();\n                for (unsigned k=2 ; k<face.mNumIndices ; ++k) {\n                    Vec3 v2 = transform * mapToEigen(mesh->mVertices[face.mIndices[k]]).template cast<Scalar>();\n                    visitor(v0, v1, v2);\n                    v1 = v2;\n                }\n                count += face.mNumIndices - 2;\n            }\n        }\n        for (unsigned i=0 ; i<node->mNumChildren ; ++i)\n            count += visitTriangles(scene, node->mChildren[i], transform, std::forward<Fn>(visitor));\n\n        return count;\n    }\n\n\n\n    // Triangle class encapsulates coordinates of vertices, instead of storing\n    // vertex indices and then looking them up in an array.\n    // Having local copies of vertex coordinates is less space effecient, but\n    // reduces number of accesses to standard memory. It also creates more total\n    // work to do, since now transformations need to be done multiple times for\n    // each vertex, but since the transformations will be parallelized,  we believe\n    // this trade off will be negligible in terms of time saved accessing memory.\n    template <typename Scalar>\n    class Triangle {\n        using Vec3 = Eigen::Matrix<Scalar, 3, 1>;\n\n    public:\n        // coordinates of triangle vertices\n        Vec3 A;\n        Vec3 B;\n        Vec3 C;\n\n        Triangle() {}\n\n        __host__ __device__ Triangle(Vec3 vertex_a, Vec3 vertex_b, Vec3 vertex_c):\n            A(vertex_a),\n            B(vertex_b),\n            C(vertex_c) {}\n\n\n    };\n\n\n\n    template <typename Scalar>\n    class Mesh {\n        using Vec3 = Eigen::Matrix<Scalar, 3, 1>;\n        using Transform = Eigen::Transform<Scalar, 3, Eigen::Affine>;\n\n        std::string name_;\n        fcl::BVHModel<fcl::OBBRSS<Scalar>> model_;\n\n    public:\n        std::vector<Triangle<Scalar>> host_triangles_; // RAM copy of triangles\n        Triangle<Scalar> *d_triangles_; //pointer to GPU copy of triangles for a mesh\n\n        Mesh(const std::string& name, bool shiftToCenter)\n            : name_(name)\n        {\n            Assimp::Importer importer;\n            // these options are the same as from OMPL app to strive\n            // for parity\n            static constexpr auto readOpts =\n                aiProcess_Triangulate | aiProcess_JoinIdenticalVertices |\n                aiProcess_SortByPType | aiProcess_OptimizeGraph | aiProcess_OptimizeMeshes;\n\n            const aiScene *scene = importer.ReadFile(name, readOpts);\n            if (scene == nullptr)\n                throw std::invalid_argument(\"could not load mesh file '\" + name + \"'\");\n\n            if (!scene->HasMeshes())\n                throw std::invalid_argument(\"mesh file '\" + name + \"' does not contain meshes\");\n\n            Vec3 center = Vec3::Zero();\n            std::size_t nVertices = visitVertices(\n                scene,\n                scene->mRootNode,\n                Transform::Identity(),\n                [&] (const Vec3& v) { center += v; });\n            center /= nVertices;\n\n            Transform rootTransform = Transform::Identity();\n\n            if (shiftToCenter)\n                rootTransform *= Eigen::Translation<Scalar, 3>(-center);\n\n            model_.beginModel();\n            std::size_t nTris = visitTriangles(\n                scene,\n                scene->mRootNode,\n                rootTransform,\n                [&] (const Vec3& a, const Vec3& b, const Vec3& c) {\n                    model_.addTriangle(a, b, c);\n                });\n            model_.endModel();\n            model_.computeLocalAABB();\n\n            for (int i = 0; i < model_.num_tris; i++) {\n                host_triangles_.emplace_back(   model_.vertices[model_.tri_indices[i][0]],\n                                                model_.vertices[model_.tri_indices[i][1]],\n                                                model_.vertices[model_.tri_indices[i][2]]);\n            }\n\n            cudaMalloc((void **) &d_triangles_, sizeof(Triangle<Scalar>) * host_triangles_.size());\n\n            cudaMemcpy(d_triangles_, &host_triangles_[0], host_triangles_.size() * sizeof(Triangle<float>), cudaMemcpyHostToDevice);\n            cudaDeviceSynchronize(); // consider not having cudaDeviceSynchronize here, instead maybe call it at the start of valid.\n\n            MPT_LOG(INFO) << \"Loaded mesh '\" << name << \"' (\" << nVertices << \" vertices, \" << nTris\n                          << \" triangles, center=\" << center << \")\";\n        }\n\n\n    };\n\n    template <auto>\n    class member_function;\n\n    template <typename T, typename R, R T::* fn>\n    class member_function<fn> {\n        T& obj_;\n    public:\n        member_function(T& obj) : obj_(obj) {}\n        template <typename ... Args>\n        decltype(auto) operator() (Args&& ... args) { return (obj_.*fn)(std::forward<Args>(args)...); }\n        template <typename ... Args>\n        decltype(auto) operator() (Args&& ... args) const { return (obj_.*fn)(std::forward<Args>(args)...); }\n    };\n}\n\n\n\nnamespace mpt_demo {\n    using namespace unc::robotics;\n    using Vec3 = Eigen::Matrix<float, 3, 1>;\n\n\n    // CUDA helper functions\n    //////////////////////////////////////////////////////////////////////////////////\n__device__ int coplanar_tri_tri(double N[3],double V0[3],double V1[3],double V2[3],\n                     double U0[3],double U1[3],double U2[3]);\n\n// some vector macros\n\n    #define THRESHOLD 0.01f\n\n    #define FABS(x) (x>=0?x:-x)        /* implement as is fastest on your machine */\n\n    #define CROSS(dest,v1,v2)                       \\\n                dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \\\n                dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \\\n                dest[2]=v1[0]*v2[1]-v1[1]*v2[0];\n\n\n\n    #define   sVpsV_2( Vr, s1,  V1,s2, V2);\\\n        {\\\n    Vr[0] = s1*V1[0] + s2*V2[0];\\\n    Vr[1] = s1*V1[1] + s2*V2[1];\\\n    }\\\n\n    #define myVpV(g,v2,v1);\\\n    {\\\n        g[0] = v2[0]+v1[0];\\\n        g[1] = v2[1]+v1[1];\\\n        g[2] = v2[2]+v1[2];\\\n        }\\\n\n    #define myVmV(g,v2,v1);\\\n    {\\\n        g[0] = v2[0]-v1[0];\\\n        g[1] = v2[1]-v1[1];\\\n        g[2] = v2[2]-v1[2];\\\n        }\\\n\n\n    // 2D intersection of segment and triangle.\n    #define seg_collide3( q, r)\\\n    {\\\n        p1[0]=SF*P1[0];\\\n        p1[1]=SF*P1[1];\\\n        p2[0]=SF*P2[0];\\\n        p2[1]=SF*P2[1];\\\n        det1 = p1[0]*q[1]-q[0]*p1[1];\\\n        gama1 = (p1[0]*r[1]-r[0]*p1[1])*det1;\\\n        alpha1 = (r[0]*q[1] - q[0]*r[1])*det1;\\\n        alpha1_legal = (alpha1>=0) && (alpha1<=(det1*det1)  && (det1!=0));\\\n        det2 = p2[0]*q[1] - q[0]*p2[1];\\\n        alpha2 = (r[0]*q[1] - q[0]*r[1]) *det2;\\\n        gama2 = (p2[0]*r[1] - r[0]*p2[1]) * det2;\\\n        alpha2_legal = (alpha2>=0) && (alpha2<=(det2*det2) && (det2 !=0));\\\n        det3=det2-det1;\\\n        gama3=((p2[0]-p1[0])*(r[1]-p1[1]) - (r[0]-p1[0])*(p2[1]-p1[1]))*det3;\\\n        if (alpha1_legal)\\\n        {\\\n            if (alpha2_legal)\\\n            {\\\n                if ( ((gama1<=0) && (gama1>=-(det1*det1))) || ((gama2<=0) && (gama2>=-(det2*det2))) || (gama1*gama2<0)) return 12;\\\n            }\\\n            else\\\n            {\\\n                if ( ((gama1<=0) && (gama1>=-(det1*det1))) || ((gama3<=0) && (gama3>=-(det3*det3))) || (gama1*gama3<0)) return 13;\\\n                }\\\n        }\\\n        else\\\n        if (alpha2_legal)\\\n        {\\\n            if ( ((gama2<=0) && (gama2>=-(det2*det2))) || ((gama3<=0) && (gama3>=-(det3*det3))) || (gama2*gama3<0)) return 23;\\\n            }\\\n        return 0;\\\n        }\n\n\n\n\n    //main procedure\n\n    __device__ int tr_tri_intersect3D (double C1[3], double P1[3], double P2[3],\n            double D1[3], double Q1[3], double Q2[3])\n    {\n        double  t[3],p1[3], p2[3],r[3],r4[3];\n        double beta1, beta2, beta3;\n        double gama1, gama2, gama3;\n        double det1, det2, det3;\n        double dp0, dp1, dp2;\n        double dq1,dq2,dq3,dr, dr3;\n        double alpha1, alpha2;\n        bool alpha1_legal, alpha2_legal;\n        double  SF;\n        bool beta1_legal, beta2_legal;\n                \n        myVmV(r,D1,C1);\n        // determinant computation\t\n        dp0 = P1[1]*P2[2]-P2[1]*P1[2];\n        dp1 = P1[0]*P2[2]-P2[0]*P1[2];\n        dp2 = P1[0]*P2[1]-P2[0]*P1[1];\n        dq1 = Q1[0]*dp0 - Q1[1]*dp1 + Q1[2]*dp2;\n        dq2 = Q2[0]*dp0 - Q2[1]*dp1 + Q2[2]*dp2;\n        dr  = -r[0]*dp0  + r[1]*dp1  - r[2]*dp2;\n\n        \n        \n        beta1 = dr*dq2;  // beta1, beta2 are scaled so that beta_i=beta_i*dq1*dq2\n        beta2 = dr*dq1;\n        beta1_legal = (beta2>=0) && (beta2 <=dq1*dq1) && (dq1 != 0);\n        beta2_legal = (beta1>=0) && (beta1 <=dq2*dq2) && (dq2 != 0);\n            \n        dq3=dq2-dq1;\n        dr3=+dr-dq1;   // actually this is -dr3\n        \n\n        if ((dq1 == 0) && (dq2 == 0))\n        {\n            if (dr!=0) return 0;  // triangles are on parallel planes\n            else\n            {\t\t\t\t\t\t// triangles are on the same plane\n                double C2[3],C3[3],D2[3],D3[3], N1[3];\n                // We use the coplanar test of Moller which takes the 6 vertices and 2 normals  \n                //as input.\n                myVpV(C2,C1,P1);\n                myVpV(C3,C1,P2);\n                myVpV(D2,D1,Q1);\n                myVpV(D3,D1,Q2);\n                CROSS(N1,P1,P2);\n                return coplanar_tri_tri(N1,C1, C2,C3,D1,D2,D3);\n            }\n        }\n\n        else if (!beta2_legal && !beta1_legal) return 0;// fast reject-all vertices are on\n                                                        // the same side of the triangle plane\n\n\n        else if (beta2_legal && beta1_legal)    //beta1, beta2\n        {\n            SF = dq1*dq2;\n            sVpsV_2(t,beta2,Q2, (-beta1),Q1);\n        }\n        \n        else if (beta1_legal && !beta2_legal)   //beta1, beta3\n        {\n            SF = dq1*dq3;\n            beta1 =beta1-beta2;   // all betas are multiplied by a positive SF\n            beta3 =dr3*dq1;\n            sVpsV_2(t,(SF-beta3-beta1),Q1,beta3,Q2);\n        }\n        \n        else if (beta2_legal && !beta1_legal) //beta2, beta3\n        {\n            SF = dq2*dq3;\n            beta2 =beta1-beta2;   // all betas are multiplied by a positive SF\n            beta3 =dr3*dq2;\n            sVpsV_2(t,(SF-beta3),Q1,(beta3-beta2),Q2);\n            Q1=Q2;\n            beta1=beta2;\n        }\n        sVpsV_2(r4,SF,r,beta1,Q1);\n        seg_collide3(t,r4);  // calculates the 2D intersection\n        return 0;\n    }\n\n        /* this edge to edge test is based on Franlin Antonio's gem:\n    \"Faster Line Segment Intersection\", in Graphics Gems III,\n    pp. 199-202 */\n    #define FABS(x) (x>=0?x:-x)        /* implement as is fastest on your machine */\n    #define EDGE_EDGE_TEST(V0,U0,U1)                      \\\n    Bx=U0[i0]-U1[i0];                                   \\\n    By=U0[i1]-U1[i1];                                   \\\n    Cx=V0[i0]-U0[i0];                                   \\\n    Cy=V0[i1]-U0[i1];                                   \\\n    f=Ay*Bx-Ax*By;                                      \\\n    d=By*Cx-Bx*Cy;                                      \\\n    if((f>0 && d>=0 && d<=f) || (f<0 && d<=0 && d>=f))  \\\n    {                                                   \\\n        e=Ax*Cy-Ay*Cx;                                    \\\n        if(f>0)                                           \\\n        {                                                 \\\n        if(e>=0 && e<=f) return 1;                      \\\n        }                                                 \\\n        else                                              \\\n        {                                                 \\\n        if(e<=0 && e>=f) return 1;                      \\\n        }                                                 \\\n    }                                \n\n    #define EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2) \\\n    {                                              \\\n    double Ax,Ay,Bx,By,Cx,Cy,e,d,f;               \\\n    Ax=V1[i0]-V0[i0];                            \\\n    Ay=V1[i1]-V0[i1];                            \\\n    /* test edge U0,U1 against V0,V1 */          \\\n    EDGE_EDGE_TEST(V0,U0,U1);                    \\\n    /* test edge U1,U2 against V0,V1 */          \\\n    EDGE_EDGE_TEST(V0,U1,U2);                    \\\n    /* test edge U2,U1 against V0,V1 */          \\\n    EDGE_EDGE_TEST(V0,U2,U0);                    \\\n    }\n\n    #define POINT_IN_TRI(V0,U0,U1,U2)           \\\n    {                                           \\\n    double a,b,c,d0,d1,d2;                     \\\n    /* is T1 completly inside T2? */          \\\n    /* check if V0 is inside tri(U0,U1,U2) */ \\\n    a=U1[i1]-U0[i1];                          \\\n    b=-(U1[i0]-U0[i0]);                       \\\n    c=-a*U0[i0]-b*U0[i1];                     \\\n    d0=a*V0[i0]+b*V0[i1]+c;                   \\\n                                                \\\n    a=U2[i1]-U1[i1];                          \\\n    b=-(U2[i0]-U1[i0]);                       \\\n    c=-a*U1[i0]-b*U1[i1];                     \\\n    d1=a*V0[i0]+b*V0[i1]+c;                   \\\n                                                \\\n    a=U0[i1]-U2[i1];                          \\\n    b=-(U0[i0]-U2[i0]);                       \\\n    c=-a*U2[i0]-b*U2[i1];                     \\\n    d2=a*V0[i0]+b*V0[i1]+c;                   \\\n    if(d0*d1>0.0)                             \\\n    {                                         \\\n        if(d0*d2>0.0) return 1;                 \\\n    }                                         \\\n    }\n\n    //This procedure testing for intersection between coplanar triangles is taken\n    // from Tomas Moller's\n    //\"A Fast Triangle-Triangle Intersection Test\",Journal of Graphics Tools, 2(2), 1997\n    __device__ int coplanar_tri_tri(double N[3],double V0[3],double V1[3],double V2[3],\n                        double U0[3],double U1[3],double U2[3])\n    {\n    double A[3];\n    short i0,i1;\n    /* first project onto an axis-aligned plane, that maximizes the area */\n    /* of the triangles, compute indices: i0,i1. */\n    A[0]=FABS(N[0]);\n    A[1]=FABS(N[1]);\n    A[2]=FABS(N[2]);\n    if(A[0]>A[1])\n    {\n        if(A[0]>A[2])\n        {\n            i0=1;      /* A[0] is greatest */\n            i1=2;\n        }\n        else\n        {\n            i0=0;      /* A[2] is greatest */\n            i1=1;\n        }\n    }\n    else   /* A[0]<=A[1] */\n    {\n        if(A[2]>A[1])\n        {\n            i0=0;      /* A[2] is greatest */\n            i1=1;\n        }\n        else\n        {\n            i0=0;      /* A[1] is greatest */\n            i1=2;\n        }\n        }\n\n        /* test all edges of triangle 1 against the edges of triangle 2 */\n        EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2);\n        EDGE_AGAINST_TRI_EDGES(V1,V2,U0,U1,U2);\n        EDGE_AGAINST_TRI_EDGES(V2,V0,U0,U1,U2);\n\n        /* finally, test if tri1 is totally contained in tri2 or vice versa */\n        POINT_IN_TRI(V0,U0,U1,U2);\n        POINT_IN_TRI(U0,V0,V1,V2);\n\n        return 0;\n    }\n\n    // void detect_collision_all_robot_host(\n    //         impl::Triangle<float> *obstacles, size_t obs_size,\n    //         impl::Triangle<float> *robot, size_t rob_size,\n    //         bool *collisions, Eigen::Transform<float, 3, Eigen::Isometry> tf){\n\n    //     float threshold = 0.0001f;\n\n\n    //     for (size_t idx = 0; idx < obs_size ; idx++){\n    //         impl::Triangle<float> obs = obstacles[idx];\n    //         Vec3 obs_vec1 = obs.B - obs.A;\n    //         Vec3 obs_vec2 = obs.C - obs.A;\n\n\n    //         Vec3 obs_norm = obs_vec1.cross(obs_vec2);\n\n    //         // scalar that satisfies obs_norm * X + obs_d = 0dot\n    //         float obs_d = -1 * obs_norm.dot(obs.A);\n\n    //         // case where vertices of a 'triangle' are colinear- ignore collision\n    //         // todo, do line intersection test with triangle\n    //         if (fabsf(obs_norm[0]) < threshold && fabsf(obs_norm[1]) < threshold && fabsf(obs_norm[2]) < threshold){\n    //             collisions[idx] = false;\n\n    //             return;\n    //         }\n\n\n    //         float obs_center_vertex[] = {obs.A[0], obs.A[1], obs.A[2]};\n    //         float obs_edge_B[] =      {obs.B[0] - obs.A[0], obs.B[1] - obs.A[1], obs.B[2] - obs.A[2]};\n    //         float obs_edge_C[] =      {obs.C[0] - obs.A[0], obs.C[1] - obs.A[1], obs.C[2] - obs.A[2]};\n    //         //test for intersection against all robot triangles\n    //         ////////////////////////////////////////////////////////////////////////\n    //         bool has_collision = false;\n    //         for (int i = 0; i < rob_size; i++){\n    //             impl::Triangle<float> pre_trans_rob = robot[i];\n    //             impl::Triangle<float> rob(  tf * pre_trans_rob.A,\n    //                                         tf * pre_trans_rob.B,\n    //                                         tf * pre_trans_rob.C);\n\n\n\n    //             float rob_center_vertex[] = {rob.A[0], rob.A[1], rob.A[2]};\n    //             float rob_edge_B[] =      {rob.B[0] - rob.A[0], rob.B[1] - rob.A[1], rob.B[2] - rob.A[2]};\n    //             float rob_edge_C[] =      {rob.C[0] - rob.A[0], rob.C[1] - rob.A[1], rob.C[2] - rob.A[2]};\n\n    //             if (tr_tri_intersect3D      (obs_center_vertex, obs_edge_B, obs_edge_C,\n    //                                         rob_center_vertex, rob_edge_B, rob_edge_C)){\n    //                 has_collision=true;\n    //                 collisions[idx] = has_collision;\n    //                 return;\n\n    //                 // printf(\"Robot Triangle %d: \\n{(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)} \\nintersects triangle\\n{(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)}\\n\", i,\n    //                 //     rob_center_vertex[0], rob_center_vertex[1], rob_center_vertex[2],\n    //                 //     rob_edge_B[0], rob_edge_B[1], rob_edge_B[2],\n    //                 //     rob_edge_C[0], rob_edge_C[1], rob_edge_C[2],\n    //                 //     obs_center_vertex[0], obs_center_vertex[1], obs_center_vertex[2],\n    //                 //     obs_edge_B[0], obs_edge_B[1], obs_edge_B[2],\n    //                 //     obs_edge_C[0], obs_edge_C[1], obs_edge_C[2]);\n    //                 // break;\n    //             }\n    //         }\n    //         collisions[idx] = has_collision;\n    //     }\n\n    // }\n\n\n\n    // one environment triangle vs all robot triangles\n    // void detect_collision_all_robot(\n    __global__  void detect_collision_all_robot(\n            impl::Triangle<float> *obstacles, size_t obs_size,\n            impl::Triangle<float> *robot, size_t rob_size,\n            bool *collisions, Eigen::Transform<float, 3, Eigen::Isometry> tf){\n\n        // want some tolerance when comparing to 0 to account for float errors\n        float threshold = 0.0001f;\n\n        int idx = threadIdx.x + blockIdx.x * blockDim.x;\n\n        // edge case where thread doesn't matter\n        if (idx >= obs_size){\n            return;\n        }\n\n        if (idx != 96){\n            return;\n        }\n        // if (idx == 0){\n            // printf(\"There are %d obstacle triangles\", obs_size );\n            // for (int i = 0; i < obs_size; i++){\n            //     printf(\"Triangle %d: {(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)} \\n \", i,\n            //                         obstacles[i].A[0], obstacles[i].A[1], obstacles[i].A[2],\n            //                         obstacles[i].B[0], obstacles[i].B[1], obstacles[i].B[2],\n            //                         obstacles[i].C[0], obstacles[i].C[1], obstacles[i].C[2]);\n            // }\n        //     printf(\"There are %d robot triangles\", rob_size );\n        //     // for (int i = 0; i < rob_size; i++){\n        //     //     printf(\"Triangle %d: {(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)} \\n \", i,\n        //     //                         robot[i].A[0], robot[i].A[1], robot[i].A[2],\n        //     //                         robot[i].B[0], robot[i].B[1], robot[i].B[2],\n        //     //                         robot[i].C[0], robot[i].C[1], robot[i].C[2]);\n        //     // }\n        // }\n        impl::Triangle<float> obs = obstacles[idx];\n\n        // calculate normal for our obstacle triangle\n        ////////////////////////////////////////////////////////////////////////\n\n        Vec3 obs_vec1 = obs.B - obs.A;\n        Vec3 obs_vec2 = obs.C - obs.A;\n\n\n        Vec3 obs_norm = obs_vec1.cross(obs_vec2);\n\n        // scalar that satisfies obs_norm * X + obs_d = 0dot\n        float obs_d = -1 * obs_norm.dot(obs.A);\n\n        // case where vertices of a 'triangle' are colinear- ignore collision\n        // todo, do line intersection test with triangle\n        // if (fabsf(obs_norm[0]) < threshold && fabsf(obs_norm[1]) < threshold && fabsf(obs_norm[2]) < threshold){\n        //     collisions[idx] = false;\n\n        //     return;\n        // }\n\n\n        double obs_center_vertex[] = {obs.A[0], obs.A[1], obs.A[2]};\n        double obs_edge_B[] =      {obs.B[0] - obs.A[0], obs.B[1] - obs.A[1], obs.B[2] - obs.A[2]};\n        double obs_edge_C[] =      {obs.C[0] - obs.A[0], obs.C[1] - obs.A[1], obs.C[2] - obs.A[2]};\n        //test for intersection against all robot triangles\n        ////////////////////////////////////////////////////////////////////////\n        bool has_collision = false;\n        for (int i = 0; i < rob_size; i++){\n\n            impl::Triangle<float> pre_trans_rob = robot[i];\n            impl::Triangle<float> rob(  tf * pre_trans_rob.A,\n                                        tf * pre_trans_rob.B,\n                                        tf * pre_trans_rob.C);\n\n\n\n            double rob_center_vertex[] = {rob.A[0], rob.A[1], rob.A[2]};\n            double rob_edge_B[] =      {rob.B[0] - rob.A[0], rob.B[1] - rob.A[1], rob.B[2] - rob.A[2]};\n            double rob_edge_C[] =      {rob.C[0] - rob.A[0], rob.C[1] - rob.A[1], rob.C[2] - rob.A[2]};\n\n            // printf(\"Result is %d\", tr_tri_intersect3D      (obs_center_vertex, obs_edge_B, obs_edge_C,\n            //                              rob_center_vertex, rob_edge_B, rob_edge_C));\n            if (tr_tri_intersect3D      (rob_center_vertex, rob_edge_B, rob_edge_C,\n                                         obs_center_vertex, obs_edge_B, obs_edge_C)){\n                has_collision=true;\n                // printf(\"Robot Triangle %d: \\n{(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)} \\nintersects env triangle %d\\n{(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)}\\n\", i,\n                //     rob_center_vertex[0], rob_center_vertex[1], rob_center_vertex[2],\n                //     rob_edge_B[0], rob_edge_B[1], rob_edge_B[2],\n                //     rob_edge_C[0], rob_edge_C[1], rob_edge_C[2],\n                //     idx,\n                //     obs_center_vertex[0], obs_center_vertex[1], obs_center_vertex[2],\n                //     obs_edge_B[0], obs_edge_B[1], obs_edge_B[2],\n                //     obs_edge_C[0], obs_edge_C[1], obs_edge_C[2]);\n                break;\n            }\n        }\n        collisions[idx] = has_collision;\n    }\n\n\n    template <typename Scalar, int nParts = 1, bool selfCollision = false>\n    class SE3RigidBodyScenario {\n\n        static_assert(nParts == 1, \"only single body motions are supported currently (TODO: add multibody)\");\n\n    public:\n\n        using Space = mpt::SE3Space<Scalar, impl::SO3_WEIGHT>; // weight SO(3) by 50\n        using Bounds = std::tuple<mpt::Unbounded, mpt::BoxBounds<Scalar, 3>>;\n        using State = typename Space::Type;\n        using Distance = typename Space::Distance;\n        using Goal = mpt::GoalState<Space>;\n        using TravelTime = Scalar;\n\n        // TODO: remove explicit Nearest and use default\n        using Nearest = unc::robotics::nigh::KDTreeBatch<8>;\n\n    private:\n        using Config = typename Space::Type;\n        // fcl::Transform3<Scalar> is an alias for\n        // Eigen::Transform<Scalar, 3, Eigen::Isometry> though in a\n        // previous version the last template parameter was\n        // Eigen::AffineCompact.  Isometry seems like a better option,\n        // so it seems unlikely to change, but regardless, we use\n        // fcl's alias for it instead of directly using Eigen's type.\n        using Transform = Eigen::Transform<Scalar, 3, Eigen::Isometry>;\n\n        // The meshes are immutable and can be rather large.  Since\n        // scenarios are copied to each thread, we use a shared\n        // pointer to avoid copying the environment and robot meshes.\n        std::shared_ptr<impl::Mesh<Scalar>> environment_;\n        std::shared_ptr<std::vector<impl::Mesh<Scalar>>> robot_;\n\n        Space space_;\n        Bounds bounds_;\n\n        static constexpr Distance goalRadius = 1e-6;\n        Goal goal_;\n\n        static Transform stateToTransform(const Config& q) {\n            return Eigen::Translation<Scalar, 3>(std::get<1>(q))\n                * Eigen::Quaternion(std::get<0>(q));\n        }\n\n    public:\n\n        // the collision detection function\n        // is called in prrt.hpp or pprm.hpp or whatever algorithm this is compiled to use\n        bool valid(const Config& q) const {\n\n            int num_env_triangles = environment_->host_triangles_.size();\n\n            if (robot_->size() > 1){\n                throw new std::runtime_error(\"Only single robots supported\");\n            }\n            size_t num_rob_triangles = (*robot_)[0].host_triangles_.size();\n\n\n            Transform tf = stateToTransform(q);\n\n            // array of booleans, d_collisions[i] = true -> environment_.triangle[i] is\n            bool host_collisions[num_env_triangles];\n            bool *d_collisions;\n            cudaMalloc((void **) &d_collisions, sizeof(bool) * num_env_triangles);\n\n            size_t block_size = 256;\n            size_t numBlocks = num_env_triangles / block_size +1;\n\n\n            // for (int i = 0; i < num_rob_triangles; i++){\n\n            //     printf(\"Triangle %d: {(%f, %f, %f), (%f, %f, %f), (%f, %f, %f)} \\n \", i,\n            //                         (*robot_)[0].host_triangles_[i].A[0], (*robot_)[0].host_triangles_[i].A[1], (*robot_)[0].host_triangles_[i].A[2],\n            //                         (*robot_)[0].host_triangles_[i].B[0], (*robot_)[0].host_triangles_[i].B[1], (*robot_)[0].host_triangles_[i].B[2],\n            //                         (*robot_)[0].host_triangles_[i].C[0], (*robot_)[0].host_triangles_[i].C[1], (*robot_)[0].host_triangles_[i].C[2]);\n            // }\n\n            cudaDeviceSynchronize();\n            // detect_collision_all_robot_host(&(environment_->host_triangles_[0]), num_env_triangles,\n            //                                 &((*robot_)[0].host_triangles_[0]), num_rob_triangles,\n            //                                 host_collisions, tf);\n            detect_collision_all_robot<<< numBlocks, 256>>>(  environment_->d_triangles_, num_env_triangles,\n                                                    (*robot_)[0].d_triangles_, num_rob_triangles,\n                                                    d_collisions, tf);\n            cudaDeviceSynchronize();\n\n            cudaMemcpy(host_collisions, d_collisions, num_env_triangles * sizeof(bool), cudaMemcpyDeviceToHost);\n            cudaDeviceSynchronize();\n\n            bool isValid = true;\n            for (int i = 0; i <num_env_triangles; i ++){\n                isValid = isValid && !host_collisions[i];\n                // if (host_collisions[i]){\n                //     int zero = 0;\n                //     // std::cout << \"env_triangl-e \" << i <<\" collides\\n\";\n                // }\n            }\n            // std::cout << isValid << std::endl;\n            // if (isValid){\n            //     std::cout << \"no collisions for state \" << q << std::endl;\n            // }\n            // else {\n            //     std::cout << \"there is a collision for state \" << q << std::endl;\n            // }\n            return isValid;\n\n\n            // TODO - write to a single global flag instead of an array of collisions\n            // TODO - have each CUDA thread check a single triangle triangle, instead of\n            //        all triangles in a robot\n            // TODO - check the collisions in a loop instead of using cudaDeviceSynchronize, continuing\n            //        whenever we've determined there's a collision0\\\n            // TODO - initialize vector of bools in construction of scenario, to avoid excessive calls\n            //        to cudaMalloc and CUDA free\n            // TODO - precompute norms for environment / robot, transform as necessary.\n        }\n\n        // // TODO make this use use some cuda algorithm\n        // std::vector<bool> validBatch(const std::vector<Config> qs) const {\n        //     std::vector<Transform> tfs[robot_->size()];\n        //     std::vector<bool> collisions[robot_->size()];\n\n        //     for (const auto& q : qs) {\n        //         for (const auto& robot : *robot_) {\n        //             for (size_t j = 0)\n        //             // consider doing the \"state to transform\" within the gpu\n        //             // could calculate the transform on cpu for one robot point, send a batch, calculate the next transform, send another batch, etc\n        //             // ^ that's a good idea, i like it.\n        //             Transform tf = stateToTransform(q);\n        //         }\n        //     }\n\n        //     return collisions;\n        // }\n\n\n    private:\n        using Validator = impl::member_function<&SE3RigidBodyScenario::valid>;\n\n    public:\n        const mpt::DiscreteMotionValidator<Space, Validator> link_;\n\n        template <typename Min, typename Max>\n        SE3RigidBodyScenario(\n            const std::string& envMesh,\n            const std::vector<std::string>& robotMeshes,\n            const Config& goal,\n            const Eigen::MatrixBase<Min>& min,\n            const Eigen::MatrixBase<Max>& max,\n            Scalar checkResolution)\n            : environment_(std::make_shared<impl::Mesh<Scalar>>(envMesh, false))\n            , robot_(std::make_shared<std::vector<impl::Mesh<Scalar>>>())\n            , bounds_(mpt::Unbounded{}, mpt::BoxBounds<Scalar, 3>(min, max)) // environment_.minBounds(), environment_.maxBounds())),\n            , goal_(goalRadius, goal)\n            // , link_(space_, environment_->extents()*checkResolution, Validator(*this))\n            , link_(space_, ((max - min).norm() + Scalar(impl::SO3_WEIGHT*M_PI/2))*checkResolution, Validator(*this))\n        {\n            robot_->reserve(robotMeshes.size());\n            for (const std::string& mesh : robotMeshes) {\n                robot_->emplace_back(mesh, true);\n            }\n            MPT_LOG(DEBUG) << \"Volume min: \" << min.transpose();\n            MPT_LOG(DEBUG) << \"Volume max: \" << max.transpose();\n        }\n\n        const Space& space() const {\n            return space_;\n        }\n\n        const Bounds& bounds() const {\n            return bounds_;\n        }\n\n        const Goal& goal() const {\n            return goal_;\n        }\n\n        bool link(const Config& a, const Config& b) const {\n            return link_(a, b);\n        }\n\n        // TODO: this shouldn't be necessary\n        TravelTime travelTime(Distance dist, bool) const { return dist; }\n    };\n}\n\n", "meta": {"hexsha": "78bdc9d34fa34ceda1a5262dbd925b6f8bf5fefb", "size": 36026, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "demo/cuda_se3_rigid_body_scenario.hpp", "max_stars_repo_name": "Funkativity/mpt", "max_stars_repo_head_hexsha": "c992d5edea3925b4980f990089cc604c69221d17", "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": "demo/cuda_se3_rigid_body_scenario.hpp", "max_issues_repo_name": "Funkativity/mpt", "max_issues_repo_head_hexsha": "c992d5edea3925b4980f990089cc604c69221d17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/cuda_se3_rigid_body_scenario.hpp", "max_forks_repo_name": "Funkativity/mpt", "max_forks_repo_head_hexsha": "c992d5edea3925b4980f990089cc604c69221d17", "max_forks_repo_licenses": ["BSD-3-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.2075892857, "max_line_length": 170, "alphanum_fraction": 0.5025537112, "num_tokens": 9636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.024053552369719504, "lm_q1q2_score": 0.008730698462057004}}
{"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_EXTENSIONS_ALGORITHMS_DETAIL_OVERLAY_DISSOLVER_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_ALGORITHMS_DETAIL_OVERLAY_DISSOLVER_HPP\n\n\n#include <deque>\n#include <vector>\n\n#include <boost/range.hpp>\n\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/core/ring_type.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/interior_rings.hpp>\n\n#include <boost/geometry/algorithms/disjoint.hpp>\n#include <boost/geometry/algorithms/expand.hpp>\n#include <boost/geometry/algorithms/detail/overlay/get_turns.hpp>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/algorithms/union.hpp>\n#include <boost/geometry/algorithms/reverse.hpp>\n\n\n#include <boost/geometry/geometries/concepts/check.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\n\nnamespace detail { namespace inserter\n{\n\n\ntemplate<typename Tag1, typename Tag2>\nstruct insert_geometry\n{};\n\ntemplate<>\nstruct insert_geometry<ring_tag, polygon_tag>\n{\n    template<typename Ring, typename Collection>\n    static inline void apply(Ring const& ring, Collection& collection)\n    {\n        collection.resize(collection.size() + 1);\n        geometry::exterior_ring(collection.back()) = ring;\n    }\n};\n\n\n\n\ntemplate<>\nstruct insert_geometry<polygon_tag, polygon_tag>\n{\n    template<typename Geometry, typename Collection>\n    static inline void apply(Geometry const& geometry, Collection& collection)\n    {\n        collection.push_back(geometry);\n    }\n};\n\ntemplate<typename Geometry, typename Collection>\ninline void insert(Geometry const& geometry, Collection& collection)\n{\n    insert_geometry\n        <\n            typename geometry::tag<Geometry>::type,\n            typename geometry::tag\n                <\n                    typename boost::range_value<Collection>::type\n                >::type\n        >::apply(geometry, collection);\n}\n\n}} // namespace detail::inserter\n\n\n\nnamespace detail { namespace dissolver\n{\n\nclass plusmin_policy\n{\n    template\n    <\n        typename Geometry1,\n        typename Geometry2,\n        typename RescalePolicy,\n        typename OutputCollection\n    >\n    static inline bool check_negative(Geometry1 a, Geometry2 b, // pass-by-value\n                    RescalePolicy const& rescale_policy,\n                    OutputCollection& output_collection)\n    {\n        // Precondition: a = positive, b = negative\n\n        // 1: make b positive to get proper intersection\n        geometry::reverse(b);\n        {\n            // 2: Check if there is overlap\n            OutputCollection difference;\n            geometry::intersection(a, b, difference);\n            if(difference.size() <= 0)\n            {\n                return false;\n            }\n        }\n\n        // There is overlap and we want to remove it, by subtracting it from b\n\n        //negative = true;\n\n        typedef typename geometry::point_type<Geometry2>::type point_type;\n\n        typedef overlay::turn_info\n            <\n                point_type,\n                typename segment_ratio_type<point_type, RescalePolicy>::type\n            > turn_info;\n        std::deque<turn_info> turns;\n\n        // Get (and stop on) any intersection\n        detail::disjoint::disjoint_interrupt_policy policy;\n        geometry::get_turns\n            <\n                false, false,\n                overlay::assign_null_policy\n            >(a, b, rescale_policy, turns, policy);\n\n        if (! policy.has_intersections)\n        {\n            // There is overlap but no intersections -> b is inside a.\n            // So keep A and keep B, do not change anything\n            return false;\n        }\n\n        // There are intersections.\n        // 3: make a negative\n        geometry::reverse(a); // now negative\n\n        // This will calculate B minus A, result is then positive\n        OutputCollection difference;\n        geometry::intersection(a, b, difference);\n\n        // Add original a to output (NOT necessary! TODO avoid this)\n        {\n            geometry::reverse(a); // positive again\n            detail::inserter::insert(a, output_collection);\n        }\n\n        // Make negative output negative again\n        typedef typename boost::range_iterator<OutputCollection>::type iterator_type;\n        for(iterator_type it = boost::begin(difference);\n            it != boost::end(difference);\n            ++it)\n        {\n            geometry::reverse(*it);\n            detail::inserter::insert(*it, output_collection);\n        }\n        return true;\n    }\n\n\npublic :\n\n    template\n    <\n        typename Geometry1,\n        typename Geometry2,\n        typename RescalePolicy,\n        typename OutputCollection\n    >\n    static inline bool apply(Geometry1 const& a, Geometry2 const& b,\n                    RescalePolicy const& rescale_policy,\n                    OutputCollection& output_collection)\n    {\n        typedef typename geometry::coordinate_type<Geometry2>::type coordinate_type;\n        coordinate_type area_a = geometry::area(a);\n        coordinate_type area_b = geometry::area(b);\n\n        // DEBUG\n        /*\n        int n = boost::size(output_collection);\n        typedef typename geometry::point_type<Geometry2>::type point_type;\n        std::cout << \"Combine \"\n            << area_a << \" with \" << \" \" << area_b\n            << \" { \" << geometry::wkt(geometry::return_centroid<point_type>(a))\n            << geometry::wkt(geometry::return_centroid<point_type>(b)) << \" }\"\n             << std::endl;\n        */\n        // END DEBUG\n\n        coordinate_type zero = coordinate_type();\n        if (area_a > zero && area_b > zero)\n        {\n            geometry::union_(a, b, output_collection);\n            return true;\n        }\n        else if (area_a > zero && area_b < zero)\n        {\n            return check_negative(a, b, rescale_policy, output_collection);\n        }\n        else if (area_a < zero && area_b > zero)\n        {\n            return check_negative(b, a, rescale_policy, output_collection);\n        }\n\n        // both negative (?) TODO\n        // DEBUG\n        /*\n        for (int i = n; i < boost::size(output_collection); i++)\n        {\n            typedef typename geometry::point_type<Geometry2>::type point_type;\n            std::cout << \"Result \"\n                << geometry::area(output_collection[i])\n                << \" \" << geometry::wkt(geometry::return_centroid<point_type>(output_collection[i]))\n                << std::endl;\n        }\n        */\n        // END DEBUG\n        return false;\n\n    }\n\n};\n\n\ntemplate <typename CombinePolicy>\nstruct dissolver_generic\n{\n\n\n    // Small structure to access elements by index;\n    // this avoids copying or accessing elements by address (pointer)\n    template <typename Box>\n    struct dissolve_helper\n    {\n        int source; // 0,1\n        int index; // index in the original array\n        bool dissolved;\n        Box box;\n        double area;\n\n        dissolve_helper()\n        {}\n\n        dissolve_helper(int i, Box b, double a, int s)\n            : source(s)\n            , index(i)\n            , dissolved(false)\n            , box(b)\n            , area(a)\n        {}\n    };\n\n\n    struct get_geometry\n    {\n        template <typename Range>\n        inline static typename boost::range_value<Range>::type const& apply(\n            Range const& range, int index)\n        {\n            return range[index];\n        }\n    };\n\n    template\n    <\n        typename Vector,\n        typename HelperVector\n    >\n    static inline void init_helper(Vector const& v, HelperVector& helper,\n        int index = 0, int source = 0)\n    {\n        typedef typename boost::range_value<Vector>::type value_type;\n        typedef typename geometry::point_type<value_type>::type point_type;\n        typedef model::box<point_type> box_type;\n        for(typename boost::range_iterator<Vector const>::type\n            it = boost::begin(v);\n            it != boost::end(v);\n            ++it, ++index)\n        {\n            helper.push_back(dissolve_helper<box_type>(index,\n                    geometry::return_envelope<box_type>(*it),\n                    geometry::area(*it),\n                    source));\n        }\n    }\n\n    template\n    <\n        typename Element,\n        typename Geometry1, typename Geometry2,\n        typename RescalePolicy,\n        typename OutputCollection\n    >\n    static inline bool call_policy(\n            Element const& , Element const& ,\n            Geometry1 const& geometry1, Geometry2 const& geometry2,\n            RescalePolicy const& rescale_policy,\n            OutputCollection& output_collection)\n    {\n        if (! geometry::disjoint(geometry1, geometry2))\n        {\n            /*std::cout << \"Process \" << element1.source << \"/\" << element1.index\n                << \" and \" << element2.source << \"/\" << element2.index\n                << \"  (\" << element2.dissolved << \",\" << element2.dissolved << \")\"\n                << std::endl;\n            */\n            return CombinePolicy::apply(geometry1, geometry2,\n                            rescale_policy, output_collection);\n        }\n        return false;\n    }\n\n\n    template\n    <\n        int Dimension,\n        typename HelperVector,\n        typename IndexVector,\n        typename InputRange,\n        typename RescalePolicy,\n        typename OutputCollection,\n        typename Box\n    >\n    static inline bool divide_and_conquer(HelperVector& helper_vector\n                , IndexVector& index_vector\n                , InputRange const& input_range\n                , RescalePolicy const& rescale_policy\n                , OutputCollection& output_collection\n                , Box const& total_box\n                , bool& changed\n                , int iteration = 0\n                )\n    {\n        //std::cout << \"divide_and_conquer \" << iteration << std::endl;\n        typedef typename geometry::coordinate_type<Box>::type coordinate_type;\n        typedef typename boost::range_value<HelperVector>::type helper_type;\n        typedef typename boost::range_iterator<IndexVector const>::type iterator_type;\n\n        //if (boost::size(index_vector) >= 16 && iteration < 100)\n        // Not yet using divide and conquer\n        if (false)\n        {\n            // 1: separate box into 2 (either horizontally or vertically)\n            Box lower_box = total_box, upper_box = total_box;\n            coordinate_type two = 2.0;\n            coordinate_type mid\n                = (geometry::get<min_corner, Dimension>(total_box)\n                    + geometry::get<max_corner, Dimension>(total_box)) / two;\n\n            geometry::set<max_corner, Dimension>(lower_box, mid);\n            geometry::set<min_corner, Dimension>(upper_box, mid);\n\n            // 2: divide indices into two sublists\n            IndexVector lower_list, upper_list;\n            for(iterator_type it = boost::begin(index_vector);\n                it != boost::end(index_vector);\n                ++it)\n            {\n                helper_type const& element = helper_vector[*it];\n                if (! geometry::disjoint(lower_box, element.box))\n                {\n                    lower_list.push_back(*it);\n                }\n                if (! geometry::disjoint(upper_box, element.box))\n                {\n                    upper_list.push_back(*it);\n                }\n            }\n\n            //std::cout << lower_list.size() << \", \" << upper_list.size()<< std::endl;\n\n            // 3: recursively call function (possibly divide in other dimension)\n            divide_and_conquer<1 - Dimension>(helper_vector,\n                lower_list, input_range, rescale_policy, output_collection, lower_box, changed, iteration + 1);\n            divide_and_conquer<1 - Dimension>(helper_vector,\n                upper_list, input_range, rescale_policy, output_collection, upper_box, changed, iteration + 1);\n            return changed;\n        }\n\n        // There are less then 16 elements, handle them quadraticly\n\n        int n = boost::size(output_collection);\n\n        for(iterator_type it1 = boost::begin(index_vector);\n            it1 != boost::end(index_vector);\n            ++it1)\n        {\n            helper_type& element1 = helper_vector[*it1];\n\n            bool unioned = false;\n            for(iterator_type it2 = boost::begin(index_vector);\n                ! unioned && it2 != it1;\n                ++it2)\n            {\n                helper_type& element2 = helper_vector[*it2];\n\n                // If they are NOT disjoint, union them\n                if (! element1.dissolved\n                    && ! element2.dissolved\n                    && ! geometry::disjoint(element1.box, element2.box))\n                {\n                    // Runtime type check here...\n                    if ((element1.source == 0 && element2.source == 0\n                        && call_policy\n                            (\n                                element1, element2,\n                                get_geometry::apply(input_range, element1.index),\n                                get_geometry::apply(input_range, element2.index),\n                                rescale_policy,\n                                output_collection\n                            )\n                        )\n                        || (element1.source == 0 && element2.source == 1\n                        && call_policy\n                            (\n                                element1, element2,\n                                get_geometry::apply(input_range, element1.index),\n                                get_geometry::apply(output_collection, element2.index),\n                                rescale_policy,\n                                output_collection\n                            )\n                        )\n                        || (element1.source == 1 && element2.source == 0\n                        && call_policy\n                            (\n                                element1, element2,\n                                get_geometry::apply(output_collection, element1.index),\n                                get_geometry::apply(input_range, element2.index),\n                                rescale_policy,\n                                output_collection\n                            )\n                        )\n                        || (element1.source == 1 && element2.source == 1\n                        && call_policy\n                            (\n                                element1, element2,\n                                get_geometry::apply(output_collection, element1.index),\n                                get_geometry::apply(output_collection, element2.index),\n                                rescale_policy,\n                                output_collection\n                            )\n                        )\n                        )\n                    {\n                        changed = true;\n                        element1.dissolved = true;\n                        element2.dissolved = true;\n\n                        unioned = true;\n/*std::cout << \"Assign \" << element1.source << \"/\" << element1.index\n<< \" and \" << element2.source << \"/\" << element2.index\n<< \"  (\" << element2.dissolved << \",\" << element2.dissolved << \")\"\n<< std::endl;\n*/\n                    }\n                }\n            }\n        }\n\n        // Append new records in output collection to helper class\n        init_helper(std::make_pair(boost::begin(output_collection) + n,\n            boost::end(output_collection)), helper_vector, n, 1);\n\n        return changed;\n    }\n\n    template <typename T>\n    static inline bool helper_dissolved(T const& t)\n    {\n      return t.dissolved;\n    }\n\n\n\n    template\n    <\n        typename InputRange,\n        typename RescalePolicy,\n        typename OutputCollection\n    >\n    static inline void apply(InputRange const& input_range\n                , RescalePolicy const& rescale_policy\n                , OutputCollection& output_collection\n                )\n    {\n        typedef typename boost::range_value<OutputCollection>::type output_type;\n\n        typedef typename geometry::point_type<output_type>::type point_type;\n        typedef model::box<point_type> box_type;\n        typedef dissolve_helper<box_type> dissolve_helper_type;\n        typedef std::vector<dissolve_helper_type> helper_vector_type;\n\n        // Vector with indices to both input_range (source 0) and output_collection (source 1)\n        helper_vector_type helper_vector;\n\n        // Vector with indices to helper-vector, for divide and conquer\n        std::vector<int> index_vector;\n\n\n        init_helper(input_range, helper_vector);\n\n        // Fill intrusive list with copies, and determine bounding box\n        box_type total_box;\n        geometry::assign_inverse(total_box);\n        int index = 0;\n        for(typename boost::range_iterator<helper_vector_type const>::type\n            it = boost::begin(helper_vector);\n            it != boost::end(helper_vector);\n            ++it, ++index)\n        {\n            index_vector.push_back(index);\n            geometry::expand(total_box, it->box);\n        }\n\n        std::vector<output_type> unioned_collection;\n\n        int size = 0, previous_size = 0;\n        int n = 0;\n\n        bool changed = false;\n        while(divide_and_conquer<1>\n            (helper_vector, index_vector, input_range, rescale_policy, unioned_collection, total_box, changed) && n < 5)\n        {\n            // Remove everything which is already dissolved.\n            helper_vector.erase\n                (\n                    std::remove_if\n                        (\n                            helper_vector.begin(),\n                            helper_vector.end(),\n                            helper_dissolved<dissolve_helper_type>\n                        ),\n                    helper_vector.end()\n                );\n\n            previous_size = size;\n            size = helper_vector.size();\n            n = previous_size == size ? n + 1 : 0;\n\n            // Re-initialize the list\n            index_vector.clear();\n            index = 0;\n            for(typename boost::range_iterator<helper_vector_type const>::type\n                it = boost::begin(helper_vector);\n                it != boost::end(helper_vector);\n                ++it, ++index)\n            {\n                index_vector.push_back(index);\n            }\n\n            changed = false;\n\n            //std::cout << \" \" << size;\n        }\n\n        // Add input+output to real output\n        typedef typename boost::range_iterator<helper_vector_type>::type iterator_type;\n        for(iterator_type it = boost::begin(helper_vector);\n            it != boost::end(helper_vector);\n            ++it)\n        {\n            if (! it->dissolved)\n            {\n                switch(it->source)\n                {\n                    case 0 :\n                        detail::inserter::insert(\n                            get_geometry::apply(input_range, it->index),\n                            output_collection);\n                        break;\n                    case 1 :\n                        detail::inserter::insert(\n                            get_geometry::apply(unioned_collection, it->index),\n                            output_collection);\n                        break;\n                }\n            }\n        }\n    }\n};\n\n\n}} // namespace detail::dissolver\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate\n<\n    typename GeometryTag1,\n    typename GeometryTag2,\n    typename Policy\n>\nstruct dissolver\n{};\n\n\ntemplate<typename Policy>\nstruct dissolver<ring_tag, polygon_tag, Policy>\n    : detail::dissolver::dissolver_generic<Policy>\n{};\n\ntemplate<typename Policy>\nstruct dissolver<polygon_tag, polygon_tag, Policy>\n    : detail::dissolver::dissolver_generic<Policy>\n{};\n\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\ntemplate\n<\n    typename InputRange,\n    typename OutputCollection\n>\ninline void dissolver(InputRange const& input_range,\n        OutputCollection& output_collection)\n{\n    typedef typename boost::range_value<InputRange>::type geometry_in;\n    typedef typename boost::range_value<OutputCollection>::type geometry_out;\n    concept::check<geometry_in const>();\n    concept::check<geometry_out>();\n\n    dispatch::dissolver\n    <\n        typename tag<geometry_in>::type,\n        typename tag<geometry_out>::type,\n        detail::dissolver::plusmin_policy\n    >::apply(input_range, output_collection);\n}\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_ALGORITHMS_DETAIL_OVERLAY_DISSOLVER_HPP\n", "meta": {"hexsha": "f54dfecd25f73f4ce85d2a08cf4d9b844213fb42", "size": 20860, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/algorithms/detail/overlay/dissolver.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/algorithms/detail/overlay/dissolver.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/algorithms/detail/overlay/dissolver.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 31.7503805175, "max_line_length": 120, "alphanum_fraction": 0.5533557047, "num_tokens": 4133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.021615333826216148, "lm_q1q2_score": 0.00872323195457334}}
{"text": "//  Copyright (c) 2007-2012 Hartmut Kaiser\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#include <hpx/hpx_fwd.hpp>\n#include <hpx/runtime/components/component_factory.hpp>\n\n#include <hpx/util/assert.hpp>\n\n#include <cmath>\n#include <memory>\n\n#include <boost/move/move.hpp>\n\n#include \"partition3d.hpp\"\n#include \"../read_values.hpp\"\n\n///////////////////////////////////////////////////////////////////////////////\nnamespace sheneos { namespace server\n{\n    partition3d::partition3d()\n      : energy_shift_(0)\n    {\n        std::memset(min_value_, 0, sizeof(min_value_));\n        std::memset(max_value_, 0, sizeof(max_value_));\n        std::memset(delta_, 0, sizeof(delta_));\n    }\n\n    inline void\n    partition3d::init_dimension(std::string const& datafilename, int d,\n        dimension const& dim, char const* name, boost::scoped_array<double>& values)\n    {\n        // Store all parameters.\n        dim_[d] = dim;\n\n        // Account for necessary overlap on the right hand side of the data\n        // interval (the interpolation algorithm we're using does not go beyond\n        // the left hand side).\n        std::size_t count = dim.count_;\n        if (dim.offset_ + dim.count_ < dim.size_-2) {\n            dim_[d].count_ += 2;\n            ++count;\n        }\n\n        // Read the full data range.\n        values.reset(new double[dim_[d].count_]);\n        extract_data(datafilename, name, values.get(), dim.offset_, dim_[d].count_);\n\n        // Extract range (without ghost-zones).\n        min_value_[d] = values[0];\n        max_value_[d] = values[count-1];\n        delta_[d] = values[1] - values[0];\n    }\n\n    inline void\n    partition3d::init_data(std::string const& datafilename,\n        char const* name, boost::scoped_array<double>& values,\n        std::size_t array_size)\n    {\n        values.reset(new double[array_size]);\n        extract_data(datafilename, name, values.get(), dim_[dimension::ye],\n            dim_[dimension::temp], dim_[dimension::rho]);\n    }\n\n    void partition3d::init(std::string const& datafilename,\n        dimension const& dimx, dimension const& dimy, dimension const& dimz)\n    {\n        init_dimension(datafilename, dimension::ye, dimx, \"ye\", ye_values_);\n        init_dimension(datafilename, dimension::temp, dimy, \"logtemp\", logtemp_values_);\n        init_dimension(datafilename, dimension::rho, dimz, \"logrho\", logrho_values_);\n\n        // Initialize the energy shift.\n        extract_data(datafilename, \"energy_shift\", &energy_shift_, 0, 1);\n\n        // Read our slice of data.\n        std::size_t array_size = dim_[dimension::ye].count_ *\n            dim_[dimension::temp].count_ * dim_[dimension::rho].count_;\n\n        init_data(datafilename, \"logpress\", logpress_values_, array_size);\n        init_data(datafilename, \"logenergy\", logenergy_values_, array_size);\n        init_data(datafilename, \"entropy\", entropy_values_, array_size);\n        init_data(datafilename, \"munu\", munu_values_, array_size);\n        init_data(datafilename, \"cs2\", cs2_values_, array_size);\n        init_data(datafilename, \"dedt\", dedt_values_, array_size);\n        init_data(datafilename, \"dpdrhoe\", dpdrhoe_values_, array_size);\n        init_data(datafilename, \"dpderho\", dpderho_values_, array_size);\n#if SHENEOS_SUPPORT_FULL_API\n        init_data(datafilename, \"muhat\", muhat_values_, array_size);\n        init_data(datafilename, \"mu_e\", mu_e_values_, array_size);\n        init_data(datafilename, \"mu_p\", mu_p_values_, array_size);\n        init_data(datafilename, \"mu_n\", mu_n_values_, array_size);\n        init_data(datafilename, \"Xa\", xa_values_, array_size);\n        init_data(datafilename, \"Xh\", xh_values_, array_size);\n        init_data(datafilename, \"Xp\", xp_values_, array_size);\n        init_data(datafilename, \"Xn\", xn_values_, array_size);\n        init_data(datafilename, \"Abar\", abar_values_, array_size);\n        init_data(datafilename, \"Zbar\", zbar_values_, array_size);\n        init_data(datafilename, \"gamma\", gamma_values_, array_size);\n#endif\n    }\n\n    inline std::size_t\n    partition3d::get_index(dimension::type d, double value)\n    {\n        if (value < min_value_[d] || value > max_value_[d]) {\n            HPX_THROW_EXCEPTION(hpx::bad_parameter,\n                \"sheneos::partition3d::get_index\",\n                \"argument out of range\");\n            return 0;\n        }\n\n        std::size_t index = static_cast<std::size_t>(\n            (value - min_value_[d]) / delta_[d]);\n\n        // Either the index has to be inside bounds or the requested value\n        // corresponds to the right end edge of the managed data range.\n        HPX_ASSERT(index < dim_[d].count_ ||\n            (index == dim_[d].count_ && value == max_value_[d]));\n\n        return index;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    inline std::size_t\n    index(std::size_t x, std::size_t y, std::size_t z, dimension const* dim)\n    {\n        std::size_t idx = z + (y + x * dim[dimension::temp].count_) *\n            dim[dimension::rho].count_;\n\n        HPX_ASSERT(idx < dim[dimension::ye].count_ *\n            dim[dimension::temp].count_ * dim[dimension::rho].count_);\n\n        return idx;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    inline double partition3d::tl_interpolate(double* values,\n        std::size_t idx_x, std::size_t idx_y, std::size_t idx_z,\n        double delta_ye, double delta_logtemp, double delta_logrho)\n    {\n        double value000 = values[index(idx_x,   idx_y,   idx_z,   dim_)];\n        double value001 = values[index(idx_x,   idx_y,   idx_z+1, dim_)];\n        double value010 = values[index(idx_x,   idx_y+1, idx_z,   dim_)];\n        double value011 = values[index(idx_x,   idx_y+1, idx_z+1, dim_)];\n        double value100 = values[index(idx_x+1, idx_y,   idx_z,   dim_)];\n        double value101 = values[index(idx_x+1, idx_y,   idx_z+1, dim_)];\n        double value110 = values[index(idx_x+1, idx_y+1, idx_z,   dim_)];\n        double value111 = values[index(idx_x+1, idx_y+1, idx_z+1, dim_)];\n\n        double comp_delta_ye = 1. - delta_ye;\n        double comp_delta_logtemp = 1. - delta_logtemp;\n        double comp_delta_logrho = 1. - delta_logrho;\n\n        return value000 * comp_delta_ye * comp_delta_logtemp * comp_delta_logrho +\n               value001 * comp_delta_ye * comp_delta_logtemp * delta_logrho +\n               value010 * comp_delta_ye * delta_logtemp      * comp_delta_logrho +\n               value011 * comp_delta_ye * delta_logtemp      * delta_logrho +\n               value100 * delta_ye      * comp_delta_logtemp * comp_delta_logrho +\n               value101 * delta_ye      * comp_delta_logtemp * delta_logrho +\n               value110 * delta_ye      * delta_logtemp      * comp_delta_logrho +\n               value111 * delta_ye      * delta_logtemp      * delta_logrho;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    std::vector<double> partition3d::interpolate(double ye, double temp,\n        double rho, boost::uint32_t eosvalues)\n    {\n        double logrho = std::log10(rho);\n        double logtemp = std::log10(temp);\n\n        std::size_t idx_ye = get_index(dimension::ye, ye);\n        std::size_t idx_logtemp = get_index(dimension::temp, logtemp);\n        std::size_t idx_logrho = get_index(dimension::rho, logrho);\n\n        double delta_ye = (ye - ye_values_[idx_ye]) / delta_[dimension::ye];\n        double delta_logtemp = (logtemp - logtemp_values_[idx_logtemp]) / delta_[dimension::temp];\n        double delta_logrho = (logrho - logrho_values_[idx_logrho]) / delta_[dimension::rho];\n\n        std::vector<double> results;\n        results.reserve(19);\n\n        // Calculate all required values.\n        if (eosvalues & logpress) {\n            double value = tl_interpolate(logpress_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n            results.push_back(std::pow(10., value));\n        }\n        if (eosvalues & logenergy) {\n            double value = tl_interpolate(logenergy_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n            results.push_back(std::pow(10., value) - energy_shift_);\n        }\n        if (eosvalues & entropy) {\n            results.push_back(tl_interpolate(entropy_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho));\n        }\n        if (eosvalues & munu) {\n            results.push_back(tl_interpolate(munu_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho));\n        }\n        if (eosvalues & cs2) {\n            results.push_back(tl_interpolate(cs2_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho));\n        }\n        if (eosvalues & dedt) {\n            results.push_back(tl_interpolate(dedt_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho));\n        }\n        if (eosvalues & dpdrhoe) {\n            results.push_back(tl_interpolate(dpdrhoe_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho));\n        }\n        if (eosvalues & dpderho) {\n            results.push_back(tl_interpolate(dpderho_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho));\n        }\n\n        return results;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    namespace detail\n    {\n        inline int numberof_setbits(boost::uint32_t i)\n        {\n            i = i - ((i >> 1) & 0x55555555);\n            i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n            return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;\n        }\n\n        inline bool more_than_one_value_requested(boost::uint32_t i)\n        {\n            return numberof_setbits(i) > 1;\n        }\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    double partition3d::interpolate_one(double ye, double temp,\n        double rho, boost::uint32_t eosvalue)\n    {\n        double logrho = std::log10(rho);\n        double logtemp = std::log10(temp);\n\n        std::size_t idx_ye = get_index(dimension::ye, ye);\n        std::size_t idx_logtemp = get_index(dimension::temp, logtemp);\n        std::size_t idx_logrho = get_index(dimension::rho, logrho);\n\n        double delta_ye = (ye - ye_values_[idx_ye]) / delta_[dimension::ye];\n        double delta_logtemp = (logtemp - logtemp_values_[idx_logtemp]) / delta_[dimension::temp];\n        double delta_logrho = (logrho - logrho_values_[idx_logrho]) / delta_[dimension::rho];\n\n        if (detail::more_than_one_value_requested(eosvalue)) {\n            HPX_THROW_EXCEPTION(hpx::bad_parameter,\n                \"partition3d::interpolate_one\",\n                \"requested to interpolate more than one physical value: \" +\n                boost::lexical_cast<std::string>(eosvalue));\n        }\n\n        // Calculate all required values.\n        switch (eosvalue) {\n        case logpress:\n            {\n                double value = tl_interpolate(logpress_values_.get(),\n                    idx_ye, idx_logtemp, idx_logrho,\n                    delta_ye, delta_logtemp, delta_logrho);\n                return std::pow(10., value);\n            }\n        case logenergy:\n            {\n                double value = tl_interpolate(logenergy_values_.get(),\n                    idx_ye, idx_logtemp, idx_logrho,\n                    delta_ye, delta_logtemp, delta_logrho);\n                return std::pow(10., value) - energy_shift_;\n            }\n        case entropy:\n            return tl_interpolate(entropy_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n\n        case munu:\n            return tl_interpolate(munu_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n\n        case cs2:\n            return tl_interpolate(cs2_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n\n        case dedt:\n            return tl_interpolate(dedt_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n\n        case dpdrhoe:\n            return tl_interpolate(dpdrhoe_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n\n        case dpderho:\n            return tl_interpolate(dpderho_values_.get(),\n                idx_ye, idx_logtemp, idx_logrho,\n                delta_ye, delta_logtemp, delta_logrho);\n\n        default:\n            break;\n        }\n\n        HPX_THROW_EXCEPTION(hpx::bad_parameter, \"partition3d::interpolate_one\",\n            \"requested to interpolate unknown physical value: \" +\n            boost::lexical_cast<std::string>(eosvalue));\n\n        return 0;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    inline double partition3d::interpolate_one(sheneos_coord const& c,\n        boost::uint32_t eosvalue)\n    {\n        return interpolate_one(c.ye_, c.temp_, c.rho_, eosvalue);\n    }\n\n    inline std::vector<double> partition3d::interpolate(\n        sheneos_coord const& c, boost::uint32_t eosvalues)\n    {\n        return interpolate(c.ye_, c.temp_, c.rho_, eosvalues);\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    std::vector<double>\n    partition3d::interpolate_one_bulk(std::vector<sheneos_coord> const& coords,\n        boost::uint32_t eosvalue)\n    {\n        std::vector<double> result;\n        result.reserve(coords.size());\n\n        // interpolate as requested\n        std::vector<sheneos_coord>::const_iterator end = coords.end();\n        for (std::vector<sheneos_coord>::const_iterator it = coords.begin();\n            it != end; ++it)\n        {\n            result.push_back(interpolate_one(*it, eosvalue));\n        }\n\n        return result;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    std::vector<std::vector<double> >\n    partition3d::interpolate_bulk(std::vector<sheneos_coord> const& coords,\n        boost::uint32_t eosvalues)\n    {\n        std::vector<std::vector<double> > result;\n        result.reserve(coords.size());\n\n        // interpolate as requested\n        std::vector<sheneos_coord>::const_iterator end = coords.end();\n        for (std::vector<sheneos_coord>::const_iterator it = coords.begin();\n            it != end; ++it)\n        {\n            result.push_back(boost::move(interpolate(*it, eosvalues)));\n        }\n\n        return result;\n    }\n}}\n\n///////////////////////////////////////////////////////////////////////////////\nnamespace hpx { namespace serialization\n{\n    ///////////////////////////////////////////////////////////////////////////\n    // Implement the serialization functions.\n    void serialize(input_archive& ar,\n        sheneos::sheneos_coord& coord, unsigned int const)\n    {\n        ar & coord.ye_ & coord.temp_ & coord.rho_;\n    }\n\n    void serialize(output_archive& ar,\n        sheneos::sheneos_coord& coord, unsigned int const)\n    {\n        ar & coord.ye_ & coord.temp_ & coord.rho_;\n    }\n}}\n\n///////////////////////////////////////////////////////////////////////////////\ntypedef sheneos::server::partition3d partition3d_type;\n\n///////////////////////////////////////////////////////////////////////////////\n// Serialization support for the actions.\nHPX_REGISTER_ACTION(partition3d_type::init_action,\n    sheneos_partition3d_init_action);\nHPX_REGISTER_ACTION(partition3d_type::interpolate_action,\n    sheneos_partition3d_interpolate_action);\nHPX_REGISTER_ACTION(partition3d_type::interpolate_one_action,\n    sheneos_partition3d_interpolate_one_action);\nHPX_REGISTER_ACTION(partition3d_type::interpolate_bulk_action,\n    sheneos_partition3d_interpolate_bulk_action);\nHPX_REGISTER_ACTION(partition3d_type::interpolate_one_bulk_action,\n    sheneos_partition3d_interpolate_one_bulk_action);\n\nHPX_REGISTER_COMPONENT(\n    hpx::components::simple_component<partition3d_type>,\n    sheneos_partition_type);\n\nHPX_REGISTER_ACTION(\n    hpx::lcos::base_lco_with_value<std::vector<std::vector<double> > >::set_value_action,\n    set_value_action_vector_vector_double);\nHPX_DEFINE_GET_COMPONENT_TYPE_STATIC(\n    hpx::lcos::base_lco_with_value<std::vector<std::vector<double> > >,\n    hpx::components::component_base_lco_with_value);\n\nHPX_REGISTER_ACTION(\n    hpx::lcos::base_lco_with_value<std::vector<double> >::set_value_action,\n    set_value_action_vector_double);\nHPX_DEFINE_GET_COMPONENT_TYPE_STATIC(\n    hpx::lcos::base_lco_with_value<std::vector<double> >,\n    hpx::components::component_base_lco_with_value);\n", "meta": {"hexsha": "105ca3ee756418036d41c6c792fd3c58377e5d4e", "size": 17113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/sheneos/sheneos/server/partition3d.cpp", "max_stars_repo_name": "akemp/hpx", "max_stars_repo_head_hexsha": "1ddf7282e322c30d82f2be044071aed14807ebe1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/sheneos/sheneos/server/partition3d.cpp", "max_issues_repo_name": "akemp/hpx", "max_issues_repo_head_hexsha": "1ddf7282e322c30d82f2be044071aed14807ebe1", "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/sheneos/sheneos/server/partition3d.cpp", "max_forks_repo_name": "akemp/hpx", "max_forks_repo_head_hexsha": "1ddf7282e322c30d82f2be044071aed14807ebe1", "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.9836448598, "max_line_length": 98, "alphanum_fraction": 0.5920060773, "num_tokens": 4038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.021615330635510816, "lm_q1q2_score": 0.008723230666910475}}
{"text": "#include <iostream>\n#include <string>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <boost/filesystem/convenience.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n#include \"uraster.hpp\"\n\nconst float L_H = 86.0;\nconst float L_V = 69.0;\n// [mm/px]\t{ ein pixel an sich ist 6,7 µm }\n#define RES_H (L_H * 100.0 / 1280.0)\n#define RES_V (L_V * 100.0 / 1024.0)\n\ntypedef std::vector<cv::Point> CvBlob;\ntypedef std::vector<CvBlob> CvBlobs;\n\nnamespace po = boost::program_options;\n\nstd::string _gradient;\nstd::string _watermark_file;\nstd::string _base;\nstd::string _base_name;\nfloat _border_factor, _font_scale, _histogram_scale,\n\t\t\t_rot_x, _rot_y, _rot_z;\nuint32_t _threshold, _mm, image_width;\ncv::Mat _lut;\ncv::Mat _watermark;\n\nbool _draw_miniature = false;\n\nvoid print(cv::Point& s) {\n\tstd::cout << \"x: \" << s.x << \" y: \" << s.y << std::endl;\n}\nvoid print(cv::Mat& m) {\n\tstd::cout << \"w: \" << m.cols << \" h: \" << m.rows << std::endl;\n}\nvoid print(cv::Size& s) {\n\tstd::cout << \"w: \" << s.width << \" h: \" << s.height << std::endl;\n}\nvoid print(cv::Rect& r) {\n\tstd::cout << \"x: \" << r.x << \" y: \" << r.y << \" w: \" << r.width << \" h: \" << r.height << std::endl;\n}\n\ncv::Size get_miniature_size() {\n\tconst float f = (float)image_width / (float)_mm;\n\treturn cv::Size(f * L_H, f * L_V);\n}\n\nvoid overlay_image(cv::Mat& src, cv::Mat& overlay, const cv::Point& location) {\n\tfor (int y = std::max(location.y, 0); y < src.rows; ++y) {\n\t\tint fY = y - location.y;\n\t\tif (fY >= overlay.rows) break;\n\t\tfor (int x = std::max(location.x, 0); x < src.cols; ++x) {\n\t\t\tint fX = x - location.x;\n\t\t\tif (fX >= overlay.cols) break;\n\t\t\tdouble opacity = ((double)overlay.data[fY * overlay.step + fX * overlay.channels() + 3]) / 255.0;\n\t\t\tfor (int c = 0; opacity > 0 && c < src.channels(); ++c) {\n\t\t\t\tunsigned char overlayPx = overlay.data[fY * overlay.step + fX * overlay.channels() + c];\n\t\t\t\tunsigned char srcPx = src.data[y * src.step + x * src.channels() + c];\n\t\t\t\tsrc.data[y * src.step + src.channels() * x + c] = srcPx * (1. - opacity) + overlayPx * opacity;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid load_watermark() {\n\t_watermark = cv::imread(_watermark_file, cv::IMREAD_UNCHANGED);\n\tif (_watermark.empty()) {\n\t\tstd::cerr << \"Error: Watermark file \\\"\" << _watermark_file << \"\\\" not readable\" << std::endl;\n\t\texit(1);\n\t}\n}\n\nvoid draw_watermark(cv::Mat& in, int pos) {\n\tif (pos == 0) {\n\t\toverlay_image(in, _watermark, cv::Point(10, in.rows - _watermark.rows - 10));\n\t} else {\n\t\toverlay_image(in, _watermark, cv::Point(in.cols - _watermark.cols - 10, 10));\n\t}\n}\n\nvoid draw_legend(cv::Mat& in, int pos) {\n\tconst int w = 10, h = 100, border = 1, offset_x = 10, offset_y = 10, o_t_x = 10;\n\tcv::Mat legend, lut_transposed, tmp;\n\tcv::transpose(_lut, lut_transposed);\n\tcv::flip(lut_transposed, lut_transposed, 0);\n\tcv::resize(lut_transposed, legend, cv::Size(w, h), 0, 0, cv::INTER_LINEAR);\n\tcv::line(legend, cv::Point(0, legend.rows*3.0/4), cv::Point(legend.cols, legend.rows*3.0/4), cv::Scalar(255, 255, 255));\n\tcv::line(legend, cv::Point(0, legend.rows/2), cv::Point(legend.cols, legend.rows/2), cv::Scalar(255, 255, 255));\n\tcv::line(legend, cv::Point(0, legend.rows/4), cv::Point(legend.cols, legend.rows/4), cv::Scalar(255, 255, 255));\n\tcv::copyMakeBorder(legend, tmp, border, border, border, border, cv::BORDER_CONSTANT, cv::Scalar(255, 255, 255));\n\n\tauto text = \"10257%\";\n\tint baseline = 0;\n\tcv::Size text_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, _font_scale, 1, &baseline);\n\tint text_x = offset_x + w + o_t_x;\n\tint text_y = offset_y + text_size.height / 3;\n\tcv::putText(in, \"100%\", cv::Point_<int> (text_x, text_y), cv::FONT_HERSHEY_SIMPLEX, _font_scale/2, cv::Scalar(255, 255, 255));\n\tcv::putText(in, \" 75%\", cv::Point_<int> (text_x, text_y + legend.rows/4), cv::FONT_HERSHEY_SIMPLEX, _font_scale/2, cv::Scalar(255, 255, 255));\n\tcv::putText(in, \" 50%\", cv::Point_<int> (text_x, text_y + legend.rows/2), cv::FONT_HERSHEY_SIMPLEX, _font_scale/2, cv::Scalar(255, 255, 255));\n\tcv::putText(in, \" 25%\", cv::Point_<int>(text_x, text_y + legend.rows*3.0/4), cv::FONT_HERSHEY_SIMPLEX, _font_scale/2, cv::Scalar(255, 255, 255));\n\tcv::putText(in, \"  0%\", cv::Point_<int>(text_x, text_y + legend.rows-1), cv::FONT_HERSHEY_SIMPLEX, _font_scale/2, cv::Scalar(255, 255, 255));\n\n\tif (pos == 0) {\n\t\t//overlay_image(in, legend, cv::Point(10, in.rows - legend.rows - 10));\n\t\ttmp.copyTo(in(cv::Rect(offset_x, offset_y, w+2*border, h+2*border)));\n\t} else {\n\t\tlegend.copyTo(in(cv::Rect(in.cols - legend.cols - 10, 10, w, h)));\n\t}\n}\n\nvoid load_lut() {\n\t_lut = cv::imread(_gradient, cv::IMREAD_UNCHANGED);\n\tif (_lut.empty()) {\n\t\tstd::cerr << \"Error: Gradient file \\\"\" << _gradient << \"\\\" not readable\" << std::endl;\n\t\texit(1);\n\t}\n\tif (_lut.cols != 256 || _lut.rows != 1) {\n\t\tstd::cerr << \"Error: Gradient file \\\"\" << _gradient << \"\\\" needs to be 256x1 px\" << std::endl;\n\t\texit(1);\n\t}\n}\n\nint adjust(double color, double factor) {\n\tconst int max_intensity = 255;\n\tconst float gamma = 0.8f;\n\tif (color == 0.0)\n\t\treturn 0;\n\treturn round(max_intensity * pow(color * factor, gamma));\n}\n\ncv::Scalar wavelength_to_rgb(int wave_length) {\n\tfloat r, g, b;\n\n\tswitch(wave_length) {\n\t\tcase 380 ... 439:\n\t\t\tr = -(wave_length - 440) / (440 - 380);\n\t\t\tg = 0.0;\n\t\t\tb = 1.0;\n\t\t\tbreak;\n\t\tcase 440 ... 489:\n\t\t\tr = 0.0;\n\t\t\tg = (wave_length - 440) / (490 - 440);\n\t\t\tb = 1.0;\n\t\t\tbreak;\n\t\tcase 490 ... 509:\n\t\t\tr = 0.0;\n\t\t\tg = 1.0;\n\t\t\tb = -(wave_length - 510) / (510 - 490);\n\t\t\tbreak;\n\t\tcase 510 ... 579:\n\t\t\tr = (wave_length - 510) / (580 - 510);\n\t\t\tg = 1.0;\n\t\t\tb = 0.0;\n\t\t\tbreak;\n\t\tcase 580 ... 644:\n\t\t\tr = 1.0;\n\t\t\tg = -(wave_length - 645) / (645 - 580);\n\t\t\tb = 0.0;\n\t\t\tbreak;\n\t\tcase 645 ... 780:\n\t\t\tr = 1.0;\n\t\t\tg = 0.0;\n\t\t\tb = 0.0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tr = 1.0;\n\t\t\tg = 1.0;\n\t\t\tb = 1.0;\n\t\t\tbreak;\n\t}\n\n\tfloat factor;\n\n\tswitch(wave_length) {\n\t\tcase 380 ... 419:\n\t\t\tfactor = 0.3 + 0.7 * (wave_length - 380) / (420 - 380);\n\t\t\tbreak;\n\t\tcase 420 ... 700:\n\t\t\tfactor = 1.0;\n\t\t\tbreak;\n\t\tcase 701 ... 780:\n\t\t\tfactor = 0.3 + 0.7 * (780 - wave_length) / (780 - 700);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfactor = 0.0;\n\t\t\tbreak;\n\t}\n\n\tauto result = cv::Scalar(adjust(b, factor), adjust(g, factor), adjust(r, factor));\n\treturn result;\n}\n\ncv::Mat preprocess(cv::Mat& in) {\n\tcv::Mat blurred, result, thresholded;\n\tcv::medianBlur(in, blurred, 3);\n\tcv::threshold(blurred, thresholded, _threshold, 255, CV_THRESH_BINARY);\n\tcv::morphologyEx(thresholded, result, cv::MORPH_CLOSE, cv::Mat(), cv::Point(-1,-1), 3);\n\treturn result;\n}\n\nCvBlobs find_blobs(cv::Mat& image) {\n\tCvBlobs result;\n\tauto preprocessed = preprocess(image);   // irgendwie frisst der opencv das nicht wenn ich das direkt findContours uebergebe\n\t//imwrite(\"pre.png\", preprocessed);\n\tfindContours(preprocessed, result, CV_RETR_LIST, CV_CHAIN_APPROX_NONE/*, offset*/);\n\treturn result;\n}\n\nCvBlob get_biggest_blob(CvBlobs blobs) {\n\tif (blobs.size() == 1) return blobs[0];\n\treturn *(std::max_element(begin(blobs), end(blobs),[](std::vector<cv::Point> a, std::vector<cv::Point> b) {\n\t\t\t\treturn cv::contourArea(a) < cv::contourArea(b);\n\t\t\t\t}));\n}\n\nfloat get_scaling(cv::Mat& input, bool log = false) {\n\tcv::Mat out(input.size(), CV_8U);\n\tdouble min, max;\n\tcv::minMaxLoc(input, &min, &max);\n\tif (log) {\n\t\tstd::cout << \"min:max \" << min << \":\" << max << std::endl;\n\t}\n\treturn 255.0/(max-min);\n}\n\ncv::Rect get_square_rect(const cv::Rect& r, const cv::Size& max_size, const cv::Point_<float> centroid) {\n\t// ziel: quadratischer bereich zum ausschneiden\n\t// so gross wie die groesste seite...\n\tauto length = std::max(r.width, r.height);\n\t// ... aber nicht groesser als die bilddimensionen hergeben\n\tlength = std::min(length, max_size.width);\n\tlength = std::min(length, max_size.height);\n\tcv::Rect result(r);\n\n\t// wenn eine seite zu kurz ist, kasten groesser machen\n\tif (r.width < length) {\n\t\tresult.x -= (length-result.width)/2;\n\t\tresult.x = std::max(result.x, 0);\n\t}\n\tif (r.height < length) {\n\t\tresult.y -= (length-result.height)/2;\n\t\tresult.y = std::max(result.y, 0);\n\t}\n\n\t// wenn eine seite zu lang ist, bildausschnitt um den zentrumspunkt verschieben\n\tif (r.width > length) {\n\t\tresult.x = centroid.x - length / 2;\n\t}\n\tif (r.height > length) {\n\t\tresult.y = centroid.y - length / 2;\n\t}\n\n\tresult.width = length;\n\tresult.height = length;\n\tresult.x = std::max(result.x, 0);\n\tresult.y = std::max(result.y, 0);\n\n\t// kasten geht ueber den rechten bildrand -> auf x nach links schieben\n\tif (result.x + result.width > max_size.width) {\n\t\tresult.x = max_size.width - result.width;\n\t}\n\t// kasten geht ueber den unteren bildrand -> auf y nach oben schieben\n\tif (result.y + result.height > max_size.height) {\n\t\tresult.y = max_size.height - result.height;\n\t}\n\treturn result;\n}\n\ncv::Mat get_bw_image(cv::Mat& src, int target_width, int color) {\n\tcv::Mat result;\n\tcv::Mat tmp;\n\tcv::cvtColor(src, tmp, CV_GRAY2RGB);\n\tauto rgb = wavelength_to_rgb(color);\n\tfor(int y = 0; y < src.rows; y++) {\n\t\tfor(int x = 0; x < src.cols; x++) {\n\t\t\tconst auto c = src.at<uchar>(y, x);\n\t\t\tif (c == 0) {\n\t\t\t\ttmp.at<cv::Vec3b>(y, x)[0] = 255;\n\t\t\t\ttmp.at<cv::Vec3b>(y, x)[1] = 255;\n\t\t\t\ttmp.at<cv::Vec3b>(y, x)[2] = 255;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfloat k = c/255.0;\n\t\t\tint r = round((1 - k) * 255.0);\n\t\t\ttmp.at<cv::Vec3b>(y, x)[0] = k*rgb[0] + r;\t// blend channels with white\n\t\t\ttmp.at<cv::Vec3b>(y, x)[1] = k*rgb[1] + r;\n\t\t\ttmp.at<cv::Vec3b>(y, x)[2] = k*rgb[2] + r;\n\t\t}\n\t}\n\tcv::resize(tmp, result, cv::Size(target_width, target_width), 0, 0, cv::INTER_LANCZOS4);\n\treturn result;\n}\n\ncv::Mat get_color_image(cv::Mat src, int target_width, int target_height) {\n\tcv::Mat result, tmp, color;\n\tcv::cvtColor(src, tmp, CV_GRAY2BGR);\n\tcv::LUT(tmp, _lut, color);\n\tcv::resize(color, result, cv::Size(target_width, target_height), 0, 0, cv::INTER_LANCZOS4);\n\treturn result;\n}\n\nfloat round_to_(const float x, const float factor) {\n\treturn floor(x/factor + 0.5) * factor;\n}\n\nfloat draw_scale(cv::Mat& src, cv::Point_<int> position, float scale, int orig_size, cv::Scalar color_scale) {\n\tauto total_width_mum = src.rows * RES_H / scale;\n\tint scale_length = 500;\n\tint scale_size_mum = 0;\n\twhile (scale_size_mum == 0) {\n\t\tscale_size_mum = (int)round_to_(total_width_mum/5, scale_length);\n\t\tscale_length /= 10;\n\t}\n\tauto scale_size_px = scale_size_mum / RES_H * scale;\n\tconst int handle_bar_length = 4;\n\tcv::line(src, cv::Point_<int>(scale_size_px, position.y-handle_bar_length), cv::Point_<int>(scale_size_px, position.y+handle_bar_length), color_scale, 1);\n\tcv::line(src, cv::Point_<int>(scale_size_px, position.y), cv::Point_<int>(scale_size_px+ scale_size_px, position.y), color_scale);\n\tcv::line(src, cv::Point_<int>(scale_size_px + scale_size_px, position.y-handle_bar_length), cv::Point_<int>(scale_size_px + scale_size_px, position.y+handle_bar_length), color_scale, 1);\n\n\tint baseline = 0;\n\tauto text = std::to_string(scale_size_mum) + \" micron\";\n\tcv::Size text_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, _font_scale, 1, &baseline);\n\tcv::putText(src, text, cv::Point_<int>(scale_size_px + (scale_size_px - text_size.width) / 2, position.y + text_size.height + 10), cv::FONT_HERSHEY_SIMPLEX, _font_scale, color_scale);\n\treturn scale_size_px;\n}\n\nvoid write_image(std::string add, std::string type, cv::Mat src) {\n\tauto filename = _base + _base_name + \"_\" + add + \".\" + type;\n\tstd::cout << \"writing: \" << filename << \" \" << std::endl;\n\tif (add != \"hi\") {\n\t\tdraw_watermark(src, 0);\n\t} else  {\n\t\tdraw_watermark(src, 1);\n\t}\n\tif (add == \"3d\" || add == \"bp\" || add == \"wi\") {\n\t\tdraw_legend(src, 0);\n\t}\n\tcv::imwrite(filename, src);\n}\n\ncv::Point_<float> get_blob_center(CvBlob b) {\n\tauto mu = cv::moments(b, true);\n\treturn cv::Point_<float>(mu.m10/mu.m00, mu.m01/mu.m00);\n}\n\nvoid draw_cross(cv::Mat& src, cv::Point_<float> px, cv::Scalar color) {\n\tconst int thickness = 1;\n\tcv::Point pt1(px.x - 100, px.y - 100);\n\tcv::Point pt2(px.x + 100, px.y + 100);\n\tif (cv::clipLine(src.size(), pt1, pt2)) {   // line is visible (not entirely outside the image) => draw the clipped version\n\t\tcv::line(src, pt1, pt2, color, thickness);\n\t}\n\tcv::Point pt3(px.x + 100, px.y - 100);\n\tcv::Point pt4(px.x - 100, px.y + 100);\n\tif (cv::clipLine(src.size(), pt3, pt4)) {\n\t\tcv::line(src, pt3, pt4, color, thickness);\n\t}\n}\n\ncv::Point_<float> find_center(cv::Mat& src, cv::Rect r) {\n\tcv::Mat tmp;\n\tcv::threshold(src, tmp, 50, 255, CV_THRESH_BINARY);\n\tauto blobs = find_blobs(tmp);\n\tif (blobs.size() == 0) {\n\t\treturn cv::Point_<float> (r.x + r.width/2, r.y + r.height/2);\n\t}\n\tauto blob = get_biggest_blob(blobs);\n\treturn get_blob_center(blob);\n}\n\ncv::Mat add_miniature(cv::Mat& reference_grey, cv::Mat& reference_color, cv::Mat& full_color, cv::Scalar text_color) {\n\tcv::Mat result, full_resize, grey_resize;\n\tauto s = get_miniature_size();\n\tcv::resize(full_color, full_resize, s);\n\tcv::resize(reference_grey, grey_resize, cv::Size(reference_color.cols, reference_color.rows), 0, 0, cv::INTER_LANCZOS4);\n\tfloat smallest = 256;\n\tint corner;\n\tcv::Rect r;\n\tfor (int i = 0; i < 4; i++) {\n\t\tcv::Rect ri(0, 0, s.width, s.height);\n\t\tif (!(i & 2)) ri.x = grey_resize.cols - s.width; // spiegelung an y achse\n\t\tif (i & 1) ri.y = grey_resize.rows - s.height; // spiegelung an x achse\n\t\tfloat mean = cv::mean(grey_resize(ri))[0];\n\t\tif (mean < smallest) {\n\t\t\tsmallest = mean;\n\t\t\tcorner = i;\n\t\t\tr = cv::Rect(ri.x, ri.y, s.width, s.height);\n\t\t}\n\t}\n\tresult = reference_color;\n\tcv::rectangle(full_resize, cv::Rect(0, 0, full_resize.cols, full_resize.rows), text_color, 3);\n\tfull_resize.copyTo(result(r));\n\t//if (corner == 0) return result;\n\tif (corner == 1) cv::flip(reference_color, result,  0);\n\tif (corner == 2) cv::flip(reference_color, result,  1);\t// spiegelung an y\n\tif (corner == 3) cv::flip(reference_color, result, -1);\n\tint baseline = 0;\n\tauto text = \"1:1\";\n\tauto text_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, _font_scale, 1, &baseline);\n\tcv::putText(result, text, cv::Point_<int>(result.rows - text_size.width, full_resize.cols), cv::FONT_HERSHEY_SIMPLEX, _font_scale, text_color);\n\treturn result;\n}\n\nvoid fft_shift_mask(cv::Mat mag_i) {\n\t// crop if it has an odd number of rows or columns\n\tmag_i = mag_i(cv::Rect(0, 0, mag_i.cols & -2, mag_i.rows & -2));\n\n\tint cx = mag_i.cols/2;\n\tint cy = mag_i.rows/2;\n\n\tcv::Mat q0(mag_i, cv::Rect(0, 0, cx, cy));   // Top-Left - Create a ROI per quadrant\n\tcv::Mat q1(mag_i, cv::Rect(cx, 0, cx, cy));  // Top-Right\n\tcv::Mat q2(mag_i, cv::Rect(0, cy, cx, cy));  // Bottom-Left\n\tcv::Mat q3(mag_i, cv::Rect(cx, cy, cx, cy)); // Bottom-Right\n\n\tcv::Mat tmp;                            // swap quadrants (Top-Left with Bottom-Right)\n\tq0.copyTo(tmp);\n\tq3.copyTo(q0);\n\ttmp.copyTo(q3);\n\tq1.copyTo(tmp);                     // swap quadrant (Top-Right with Bottom-Left)\n\tq2.copyTo(q1);\n\ttmp.copyTo(q2);\n}\n\n/** src needs to be padded already */\ncv::Mat fft_compute_dft(cv::Mat src) {\n\t// copy the source image, on the border add zero values\n\tcv::Mat planes[] = { cv::Mat_< float> (src), cv::Mat::zeros(src.size(), CV_32F) };\n\t// create a complex matrix\n\tcv::Mat complex;\n\tcv::merge(planes, 2, complex);\n\tcv::dft(complex, complex, cv::DFT_COMPLEX_OUTPUT);  // fourier transform\n\treturn complex;\n}\n\nvoid fft_update_magnitude(cv::Mat complex) {\n\tcv::Mat mag_i;\n\tcv::Mat planes[] = {\n\t\tcv::Mat::zeros(complex.size(), CV_32F),\n\t\tcv::Mat::zeros(complex.size(), CV_32F)\n\t};\n\tcv::split(complex, planes); // planes[0] = Re(DFT(I)), planes[1] = Im(DFT(I))\n\tcv::magnitude(planes[0], planes[1], mag_i); // sqrt(Re(DFT(I))^2 + Im(DFT(I))^2)\n\t// switch to logarithmic scale: log(1 + magnitude)\n\tmag_i += cv::Scalar::all(1);\n\tcv::log(mag_i, mag_i);\n\tfft_shift_mask(mag_i); // rearrage quadrants\n\t// Transform the magnitude matrix into a viewable image (float values 0-1)\n\tcv::normalize(mag_i, mag_i, 1, 0, cv::NORM_INF);\n}\n\ncv::Mat fft_update_result(cv::Mat complex) {\n\tcv::Mat work;\n\tcv::idft(complex, work);\n\t// equivalent to:\n\t// dft(complex, result, DFT_INVERSE + DFT_SCALE);\n\tcv::Mat planes[] = {\n\t\tcv::Mat::zeros(complex.size(), CV_32F),\n\t\tcv::Mat::zeros(complex.size(), CV_32F)\n\t};\n\tcv::split(work, planes); // planes[0] = Re(DFT(I)), planes[1] = Im(DFT(I))\n\tcv::magnitude(planes[0], planes[1], work); // sqrt(Re(DFT(I))^2 + Im(DFT(I))^2)\n\tcv::normalize(work, work, 0, 255, cv::NORM_MINMAX);\n\tcv::Mat result;\n\twork.convertTo(result, CV_8U);\n\treturn result;\n}\n\ncv::Mat get_fft_mask(cv::Size s, cv::Rect& size_dot) {\n\tconst int w = s.width, h = s.height;\n\tconst int d = s.width <= 120 ? h/4 : h/15;\n\tconst int radius_mask_dot = std::max(std::max(size_dot.width, size_dot.height) >> 1, w/3);\n\tconst int f = std::max(1, h/120);\n\tcv::Mat result = cv::Mat::zeros(s, CV_32F);;\n\tcv::circle(result, cv::Point2i(w/2, h/2), radius_mask_dot, cv::Scalar(255), CV_FILLED);\n\tcv::rectangle(result, cv::Point_<int>(0, h/2-f), cv::Point_<int>(w/2-d, h/2+f), cv::Scalar(0), CV_FILLED); // left\n\tcv::rectangle(result, cv::Point_<int>(w/2+d, h/2-f), cv::Point_<int>(w, h/2+f), cv::Scalar(0), CV_FILLED); // right\n\tcv::rectangle(result, cv::Point_<int>(w/2-f, 0), cv::Point_<int>(w/2+f, h/2-d), cv::Scalar(0), CV_FILLED); // top\n\tcv::rectangle(result, cv::Point_<int>(w/2-f, h/2+d), cv::Point_<int>(w/2+f, h), cv::Scalar(0), CV_FILLED); // bottom\n\t//cv::imwrite(\"mask.png\", result);\n\treturn result;\n}\n\n\ncv::Mat fft_apply_mask(cv::Mat& src, cv::Mat mask) {\n\tcv::Mat complex = fft_compute_dft(src);\n\tfft_update_magnitude(complex);\n\tfft_update_result(complex);\n\tfft_shift_mask(mask);\n\tcv::Mat planes[] = {cv::Mat::zeros(complex.size(), CV_32F), cv::Mat::zeros(complex.size(), CV_32F)};\n\tcv::Mat kernel_spec;\n\tplanes[0] = mask; // real\n\tplanes[1] = mask; // imaginar\n\tcv::merge(planes, 2, kernel_spec);\n\tcv::mulSpectrums(complex, kernel_spec, complex, cv::DFT_ROWS);\n\t//cv::mulSpectrums(complex, kernel_spec, complex, cv::DFT_ROWS); // only DFT_ROWS accepted\n\tfft_update_magnitude(complex);     // show spectrum\n\treturn fft_update_result(complex);\n}\n\ncv::Mat fft_denoise(cv::Mat& src, cv::Rect& size_dot) {\n\tauto complex = fft_compute_dft(src);\n\tfft_update_magnitude(complex);\n\tfft_update_result(complex);\n\treturn fft_apply_mask(src, get_fft_mask(complex.size(), size_dot));\n}\n\n/** to not scale tiny images too large, increase border area on small images */\ncv::Rect add_border(cv::Rect in, int image_width) {\n\tcv::Rect result(in);\n\tif (result.width / (float)image_width < _border_factor) {\n\t\tauto border_v = (std::ceil(image_width * _border_factor) - result.width);\n\t\tresult.width += border_v;\n\t\tresult.x -= border_v/2;\n\t}\n\tif (result.height / (float)image_width < _border_factor) {\n\t\tauto border_h = (std::ceil(image_width * _border_factor) - result.height);\n\t\tresult.height += border_h;\n\t\tresult.y -= border_h/2;\n\t}\n\treturn result;\n}\n\ncv::Rect adjust_border_for_fft(const cv::Rect in) {\n\tcv::Rect result;\n\tint q = cv::getOptimalDFTSize(in.width);\n\tint r = cv::getOptimalDFTSize(in.height);\n\tresult.x = in.x - (q-in.width)/2;\n\tresult.y = in.y - (r-in.height)/2;\n\tresult.width = q;\n\tresult.height = r;\n\treturn result;\n}\n\ncv::Mat get_denoised_image(cv::Mat& src, int target_sidelength = -1, bool prevent_large_scaling = true) {\n\tcv::Mat src_8u, src_normalized_8u, src_normalized_32f;\n\n\t/* rescale from min_value in image,max_value to 0..1023 */\n\tauto scaling = get_scaling(src);\n\tcv::normalize(src, src_normalized_32f, 0, 1023, cv::NORM_MINMAX);\n\tsrc.convertTo(src_8u, CV_8U, scaling);\n\tsrc_normalized_32f.convertTo(src_normalized_8u, CV_8U, scaling);\n\n\tauto blobs = find_blobs(src_normalized_8u);\n\tif (blobs.size() == 0) {\n\t\tstd::cerr << \"No blobs found.\";\n\t\texit(1);\n\t}\n\tauto blob = get_biggest_blob(blobs);\n\tauto size_dot = boundingRect(blob);\n\tcv::Rect roi;\n\tif (prevent_large_scaling) {\n\t\troi = target_sidelength == -1 ? cv::Rect(0, 0, src.cols, src.rows) : add_border(size_dot, target_sidelength);\n\t} else {\n\t\troi = size_dot;\n\t}\n\troi = adjust_border_for_fft(roi);\n\tif (target_sidelength != -1) {\n\t\troi = get_square_rect(roi, src_8u.size(), find_center(src_8u, roi));\n\t}\n\tcv::Mat src_rect_32f;\n\tsrc(roi).copyTo(src_rect_32f);\n\treturn fft_denoise(src_rect_32f, size_dot);\n}\n\ncv::Mat generate_2d_beam_profiles(cv::Mat& src, int target_sidelength, int wavelength, cv::Mat& denoised_full) {\n\tauto result_denoised_bw = get_bw_image(src, target_sidelength, wavelength);\n\tauto result_denoised_colorized = get_color_image(src, target_sidelength, target_sidelength);\n\tcv::Mat result = result_denoised_bw.clone();\n\n\tif (_draw_miniature) {\n\t\tauto s = get_miniature_size();\n\t\tauto miniature_colorized = get_color_image(denoised_full, s.width, s.height);\n\t\tauto miniature_bw = get_bw_image(denoised_full, s.width, wavelength);\n\t\t//write_image(base, \"ref\", \"png\", denoised_full);\n\t\tresult_denoised_colorized = add_miniature(src, result_denoised_colorized, miniature_colorized, cv::Scalar(255, 255, 255));\n\t\tresult_denoised_bw = add_miniature(src, result_denoised_bw, miniature_bw, cv::Scalar(0, 0, 0));\n\t}\n\n\tdraw_scale(result_denoised_bw, cv::Point_<int>(10, 10), (float)target_sidelength/(float)src.cols, src.rows, cv::Scalar(0, 0, 0));\n\tdraw_scale(result_denoised_colorized, cv::Point_<int>(10, 10), (float)target_sidelength/(float)src.cols, src.rows, cv::Scalar(255, 255, 255));\n\twrite_image(\"bp\", \"png\", result_denoised_colorized);\n\t//write_image(\"c\", \"png\", result_denoised_colorized);\n\twrite_image(\"bw\", \"png\", result_denoised_bw);\n\treturn result;\n}\n\nvoid draw_histogram(cv::Mat& src, cv::Mat& dst, const int hist_size, cv::Scalar color, const int target_sidelength, cv::Rect roi, int wavelength) {\n\tauto laser_color = wavelength_to_rgb(wavelength);\n\tcv::Mat hist_i_h, tmp;\n\tbool transposed = false;\n\tif (roi.width > roi.height) {\n\t\ttransposed = true;\n\t\ttranspose(src(roi), tmp);\n\t} else {\n\t\ttmp = src(roi);\n\t}\n\tcv::normalize(tmp, hist_i_h, 0, 255, cv::NORM_MINMAX);\n\tint bin_w = std::round((double)hist_i_h.rows / hist_size);\n\t//std::cout << bin_w << std::endl;\n\tif (!transposed) {\n\t\tfor( int i = 1; i < hist_size; i++) {   // vertical\n\t\t\t//std::cout << +hist_i_h.at<uchar>(i-1) << \" \";\n\t\t\tcv::line(dst,\n\t\t\t\t\tcv::Point(0, bin_w*(i)),\n\t\t\t\t\tcv::Point(hist_i_h.at<uchar>(i) * _histogram_scale - 1, bin_w*(i)),\n\t\t\t\t\tlaser_color, 1\n\t\t\t\t\t);\n\t\t\tcv::line(dst,\n\t\t\t\t\tcv::Point(hist_i_h.at<uchar>(i-1) * _histogram_scale, bin_w*(i-1)),\n\t\t\t\t\tcv::Point(hist_i_h.at<uchar>(i) * _histogram_scale, bin_w*(i)),\n\t\t\t\t\tcolor, 2\n\t\t\t\t\t);\n\t\t}\n\t} else {\n\t\tfor( int i = 1; i < hist_size; i++) {   // horizontal\n\t\t\t//std::cout << +hist_i_h.at<uchar>(i-1) << \" \";\n\t\t\tcv::line(dst,\n\t\t\t\t\tcv::Point(bin_w*(i), target_sidelength),\n\t\t\t\t\tcv::Point(bin_w*(i), target_sidelength - hist_i_h.at<uchar>(i) * _histogram_scale + 1),\n\t\t\t\t\tlaser_color, 1\n\t\t\t\t\t);\n\t\t\tcv::line(dst,\n\t\t\t\t\tcv::Point(bin_w*(i-1), target_sidelength - hist_i_h.at<uchar>(i-1) * _histogram_scale),\n\t\t\t\t\tcv::Point(bin_w*(i), target_sidelength - hist_i_h.at<uchar>(i) * _histogram_scale),\n\t\t\t\t\tcolor, 2\n\t\t\t\t\t);\n\t\t}\n\t}\n}\n\nvoid generate_histogram_images(cv::Mat& src, int target_sidelength, std::string name, int wavelength) {\n\tauto result_denoised_colorized = get_color_image(src, target_sidelength, target_sidelength);\n\tauto result_denoised_bw = get_bw_image(src, target_sidelength, wavelength);\n\tcv::Mat resized_bw;\n\tcv::resize(src, resized_bw, cv::Size(target_sidelength, target_sidelength), 0, 0, cv::INTER_LANCZOS4);\n\tauto scale_size = draw_scale(result_denoised_bw, cv::Point_<int>(10, 10), (float)target_sidelength/(float)src.cols, src.rows, cv::Scalar(0, 0, 0));\n\tfor (float i = 0; i < result_denoised_bw.cols; i+= scale_size/5) {\n\t\tauto color = cv::Scalar(222, 222, 222);\n\t\tcv::line(result_denoised_bw, cv::Point(i, 0), cv::Point(i, result_denoised_bw.cols), color, 1);\n\t\tcv::line(result_denoised_bw, cv::Point(0, result_denoised_bw.cols - i - 1), cv::Point(result_denoised_bw.cols, result_denoised_bw.cols - i - 1), color, 1);\n\t}\n\tfor (float i = 0; i < result_denoised_bw.cols; i+= scale_size) {\n\t\tauto color = cv::Scalar(128, 128, 128);\n\t\tcv::line(result_denoised_bw, cv::Point(i, 0), cv::Point(i, result_denoised_bw.cols), color, 1);\n\t\tcv::line(result_denoised_bw, cv::Point(0, result_denoised_bw.cols - i - 1), cv::Point(result_denoised_bw.cols, result_denoised_bw.cols - i - 1), color, 1);\n\t}\n\tdraw_scale(result_denoised_bw, cv::Point_<int>(10, 10), (float)target_sidelength/(float)src.cols, src.rows, cv::Scalar(0, 0, 0));\n\n\tdraw_histogram(resized_bw, result_denoised_bw, resized_bw.cols, cv::Scalar(0, 0, 0), target_sidelength, cv::Rect(0, resized_bw.rows/2-1, resized_bw.cols, 1), wavelength);\n\tdraw_histogram(resized_bw, result_denoised_bw, resized_bw.cols, cv::Scalar(0, 0, 0), target_sidelength, cv::Rect(resized_bw.cols/2-1, 0, 1, resized_bw.rows), wavelength);\n\tdraw_scale(result_denoised_colorized, cv::Point_<int>(10, 10), (float)target_sidelength/(float)src.cols, src.rows, cv::Scalar(255, 255, 255));\n\twrite_image(\"hi\", \"png\", result_denoised_bw);\n}\n\nuraster::VertVsOut vertex_shader(const Eigen::Vector3f& vin, const Eigen::Matrix4f& mvp, float t) {\n\turaster::VertVsOut vout;\n\tvout.p = mvp * Eigen::Vector4f(vin[0], vin[1], vin[2], 1.0f);\n\tfloat index = vin[1];\n\tvout.color = Eigen::Vector3f(index, index, index);\n\treturn vout;\n}\n\nuraster::VertVsOut vertex_shader_wireframe(const Eigen::Vector3f& vin, const Eigen::Matrix4f& mvp, float t) {\n\turaster::VertVsOut vout;\n\tvout.p = mvp * Eigen::Vector4f(vin[0], vin[1], vin[2], 1.0f);\n\tfloat index = vin[1];\n\tvout.color = Eigen::Vector3f(index, index, index);\n\treturn vout;\n}\n\nuraster::Pixel fragment_shader(const uraster::VertVsOut& fsin) {\n\turaster::Pixel p;\n\tint index = std::round(fsin.color[0] * 255.0);\n\tif (index < 10) index = 10;\n\tauto at_index = _lut.at<cv::Vec3b>(0, index);\n\tp.color = Eigen::Vector4f(at_index[0], at_index[1], at_index[2], -1e10f);\n\treturn p;\n}\n\nuraster::Pixel fragment_shader_wireframe(const uraster::VertVsOut& fsin) {\n\turaster::Pixel p;\n\n\tif (!(fsin.position()[3] < 0.04)) {\n\t\tp.color = Eigen::Vector4f(0, 0, 0, 0);\n\t\treturn p;\n\t}\n\n\tint index = std::round(fsin.color[0] * 255.0);\n\tauto at_index = _lut.at<cv::Vec3b>(0, index);\n\tp.color = Eigen::Vector4f(at_index[0], at_index[1], at_index[2], fsin.position()[3]);\n\tp.color = Eigen::Vector4f(at_index[0], at_index[1], at_index[2], 0);\n\treturn p;\n}\n\nuraster::Pixel fragment_shader_wireframe_bw(const uraster::VertVsOut& fsin) {\n\turaster::Pixel p;\n\n\tif (!(fsin.position()[3] < 0.04)) {\n\t\tauto col = std::min(fsin.color[0]/2.0 * 255.0 + 127, 255.0);\n\t\tp.color = Eigen::Vector4f(col, col, col, 0);\n\t\t//p.color = Eigen::Vector4f(255, 255, 255, 0);\n\t\treturn p;\n\t}\n\tp.color = Eigen::Vector4f(0, 0, 0, 0);\n\treturn p;\n}\n\nuraster::Pixel fragment_shader_wireframe_bw_shaded(const uraster::VertVsOut& fsin) {\n\turaster::Pixel p;\n\n\tif (!(fsin.position()[3] < 0.04)) {\n\t\tfloat theta=M_PI;\n\t\tEigen::Vector3f ld(1.0,sin(theta),cos(theta));\n\t\t//(fsin.n == normalenvektor dreieck)\n\t\tEigen::Vector3f po;\n\t\tpo[0] = fsin.p[0];\n\t\tpo[1] = fsin.p[1];\n\t\tpo[2] = fsin.p[2];\n\t\tfloat intensity=ld.normalized().dot(po);\n\n\t\t//auto col = std::min(fsin.color()[0]/2.0 * 255.0 + 127, 255.0);\n\t\tauto col = (intensity+1)/2.0;\n\t\t//col = col * 200 + 55;\n\t\t//\n\t\tcol = 150 + intensity*200;\n\n\t\tcol = col < 0 ? 0 : col; col = col > 255 ? 255 : col;\n\t\tp.color = Eigen::Vector4f(col, col, col, 0);\n\t\t//p.color = Eigen::Vector4f(255, 255, 255, 0);\n\t\treturn p;\n\t}\n\tp.color = Eigen::Vector4f(0, 0, 0, 0);\n\treturn p;\n}\n\nvoid generate_triangulation(std::vector<Eigen::Vector3f>& vectors, std::vector<std::size_t>& tid, cv::Mat& src) {\n\tint i = 0;\n\tconst int dist = 1;\n\tfor(int y = 0; y < src.rows-2*dist; y+=dist) {\n\t\tfor(int x = 0; x < src.cols-2*dist; x+=dist) {\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*x/src.cols - 1, src.at<uchar>(y, x)/255.0, 2.0*y/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x)/src.cols - 1, src.at<uchar>(y+dist, x)/255.0, 2.0*(y+dist)/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x+dist)/src.cols - 1, src.at<uchar>(y, x+dist)/255.0, 2.0*(y)/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x+dist)/src.cols - 1, src.at<uchar>(y+dist, x+dist)/255.0, 2.0*(y+dist)/src.rows - 1));\n\t\t\ttid.push_back(i-1); // reuse previous two vertices\n\t\t\ttid.push_back(i-2);\n\t\t\ttid.push_back(i++);\n\t\t}\n\t}\n}\n\nvoid generate_triangulation_wireframe(std::vector<Eigen::Vector3f>& vectors, std::vector<std::size_t>& tid, cv::Mat& src) {\n\tint i = 0;\n\tconst int dist = 20;\n\tfor(int y = 0; y < src.rows-2*dist; y+=dist) {\n\t\tfor(int x = 0; x < src.cols-2*dist; x+=dist) {\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*x/src.cols - 1, src.at<uchar>(y, x)/255.0, 2.0*y/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x)/src.cols - 1, src.at<uchar>(y+dist, x)/255.0, 2.0*(y+dist)/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x+dist)/src.cols - 1, src.at<uchar>(y, x+dist)/255.0, 2.0*(y)/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t}\n\t}\n\tfor(int y = 0; y < src.rows-2*dist; y+=dist) {\n\t\tfor(int x = 0; x < src.cols-2*dist; x+=dist) {\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x+dist)/src.cols - 1, src.at<uchar>(y, x+dist)/255.0, 2.0*(y)/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x)/src.cols - 1, src.at<uchar>(y+dist, x)/255.0, 2.0*(y+dist)/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t\tvectors.push_back(Eigen::Vector3f(2.0*(x+dist)/src.cols - 1, src.at<uchar>(y+dist, x+dist)/255.0, 2.0*(y+dist)/src.rows - 1));\n\t\t\ttid.push_back(i++);\n\t\t}\n\t}\n}\n\ncv::Mat mo_close(cv::Mat src) {\n\tcv::Mat dst;\n\tint morph_size = 1; // 21\n\tcv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size( 2*morph_size + 1, 2*morph_size+1 ), cv::Point( morph_size, morph_size ) );\n\tcv::morphologyEx( src, dst, cv::MORPH_CLOSE, element, cv::Point(-1, -1), 1);\n\tcv::morphologyEx( dst, src, cv::MORPH_OPEN, element, cv::Point(-1, -1), 1);\n\treturn src;\n}\n\n\n//cv::Mat mo_thinning(cv::Mat src) {\n//\tcv::threshold(img, img, 127, 255, cv::THRESH_BINARY);\n//\tcv::Mat skel(img.size(), CV_8UC1, cv::Scalar(0));\n//\tcv::Mat temp;\n//\tcv::Mat eroded;\n//\n//\tcv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(3, 3));\n//\n//\tbool done;\n//\tdo\n//\t{\n//\t\tcv::erode(img, eroded, element);\n//\t\tcv::dilate(eroded, temp, element); // temp = open(img)\n//\t\tcv::subtract(img, temp, temp);\n//\t\tcv::bitwise_or(skel, temp, skel);\n//\t\teroded.copyTo(img);\n//\n//\t\tdone = (cv::countNonZero(img) == 0);\n//\t} while (!done);\n//}\n\nvoid save_3d_image(std::string name, uraster::Framebuffer<uraster::Pixel>& tp, int target_sidelength, bool close = false) {\n\tcv::Mat result = cv::Mat(target_sidelength, target_sidelength, CV_8UC3);\n\tfor(int y = 0; y < target_sidelength; y++) {\n\t\tfor(int x = 0; x < target_sidelength; x++) {\n\t\t\tauto px = tp(x, y);\n\t\t\tresult.at<cv::Vec3b>(y, x)[0] = px.color[0];\n\t\t\tresult.at<cv::Vec3b>(y, x)[1] = px.color[1];\n\t\t\tresult.at<cv::Vec3b>(y, x)[2] = px.color[2];\n\t\t}\n\t}\n\t//if (close) result = mo_close(result);\n\twrite_image(name, \"png\", result);\n}\n\nEigen::Matrix4f get_camera_matrix() {\n\tEigen::Matrix4f camera_matrix = Eigen::Matrix4f::Identity();\n\tEigen::Matrix3f m;\n\tm = Eigen::AngleAxisf(_rot_x*M_PI, Eigen::Vector3f::UnitX()) * Eigen::AngleAxisf(_rot_y*M_PI, Eigen::Vector3f::UnitY()) * Eigen::AngleAxisf(_rot_z*M_PI, Eigen::Vector3f::UnitZ());\n\tEigen::Matrix4f camera_transform;\n\tcamera_transform.setIdentity();\n\tcamera_transform.block<3, 3>(0, 0) = m;\t// rotation\n\tcamera_matrix *= camera_transform;\n\treturn camera_matrix;\n}\n\nvoid generate_3d_image_triangulation(cv::Mat& src, int target_sidelength) {\n\tstd::vector<Eigen::Vector3f> vectors;\n\tstd::vector<std::size_t> tid;\n\tgenerate_triangulation(vectors, tid, src);\n\turaster::Framebuffer<uraster::Pixel> tp(target_sidelength, target_sidelength);\n\turaster::draw(tp, &*vectors.begin(), &*vectors.end(), &*tid.begin(), &*tid.end(),\n\t\t\t(uraster::VertVsOut*)nullptr, (uraster::VertVsOut*)nullptr,\n\t\t\tstd::bind(vertex_shader, std::placeholders::_1, get_camera_matrix(), 0.0),\n\t\t\tfragment_shader\n\t\t\t);\n\tsave_3d_image(\"3d\", tp, target_sidelength);\n\tvectors.clear();\n\ttid.clear();\n\tgenerate_triangulation_wireframe(vectors, tid, src);\n\ttp.clear();\n\turaster::draw(tp, &*vectors.begin(), &*vectors.end(), &*tid.begin(), &*tid.end(),\n\t\t\t(uraster::VertVsOut*)nullptr, (uraster::VertVsOut*)nullptr,\n\t\t\tstd::bind(vertex_shader, std::placeholders::_1, get_camera_matrix(), 0.0),\n\t\t\tfragment_shader_wireframe, true\n\t\t\t);\n\tsave_3d_image(\"wi\", tp, target_sidelength, true);\n\turaster::Pixel p;\n\tp.color = Eigen::Vector4f(255, 255, 255, -1);\n\ttp.clear(p);\n\turaster::draw(tp, &*vectors.begin(), &*vectors.end(), &*tid.begin(), &*tid.end(),\n\t\t\t(uraster::VertVsOut*)nullptr, (uraster::VertVsOut*)nullptr,\n\t\t\tstd::bind(vertex_shader, std::placeholders::_1, get_camera_matrix(), 0.0),\n\t\t\tfragment_shader_wireframe_bw_shaded, true\n\t\t\t);\n\tsave_3d_image(\"wb\", tp, target_sidelength, true);\n}\n\nvoid generate_3d_image_wireframe(cv::Mat& src, int target_sidelength) {\n\tstd::vector<Eigen::Vector3f> vectors;\n\tstd::vector<std::size_t> tid;\n}\n\n\nvoid handle_image(cv::Mat& src, int target_sidelength, int wavelength) {\n\tauto denoised_square = get_denoised_image(src, target_sidelength);\n\tcv::Mat denoised_full, denoised_noborder, denoised_noborder_tmp;\n\tif (_draw_miniature) denoised_full = get_denoised_image(src);\n\tdenoised_noborder_tmp = get_denoised_image(src, target_sidelength, false);\n\tcv::resize(denoised_noborder_tmp, denoised_noborder, cv::Size(target_sidelength, target_sidelength), 0, 0, cv::INTER_LANCZOS4);\n\tauto bw_scaled = generate_2d_beam_profiles(denoised_square, target_sidelength, wavelength, denoised_full);\n\tgenerate_histogram_images(denoised_square, target_sidelength, \"bp\", wavelength);\n\tgenerate_3d_image_triangulation(denoised_noborder, target_sidelength);\n\tgenerate_3d_image_wireframe(denoised_noborder, target_sidelength);\n}\n\n\nint main(int argc, char** argv) {\n\tstd::string infile;\n\tuint32_t wavelength;\n\n\ttry {\n\t\tpo::options_description desc(\"Allowed options\");\n\t\tdesc.add_options()\n\t\t\t(\"help,h\", \"print usage message\")\n\t\t\t(\"input-file,i\", po::value<std::string>(&infile)->required(), \"input file\")\n\t\t\t(\"output-folder,o\", po::value<std::string>(&_base)->default_value(\"out/\"), \"output folder\")\n\t\t\t(\"sidelength,s\", po::value<uint32_t>(&image_width)->default_value(550), \"length of each side, output is square\")\n\t\t\t(\"wavelength,w\", po::value<uint32_t>(&wavelength)->default_value(650), \"wavelength in nm\")\n\t\t\t(\"gradient,g\", po::value<std::string>(&_gradient)->default_value(\"gradient.png\"), \"gradient file\")\n\t\t\t(\"watermark,w\", po::value<std::string>(&_watermark_file)->default_value(\"emboss.png\"), \"watermark\")\n\t\t\t(\"border-factor,b\", po::value<float>(&_border_factor)->default_value(0.2f, \"0.2\"), \"ratio to add a border before upscaling\")\n\t\t\t(\"font-scale,f\", po::value<float>(&_font_scale)->default_value(0.5f, \"0.5\"), \"font size\")\n\t\t\t(\"histogram-scale,r\", po::value<float>(&_histogram_scale)->default_value(0.5f, \"0.5\"), \"histogram scaling\")\n\t\t\t(\"threshold,t\", po::value<uint32_t>(&_threshold)->default_value(40), \"lower threshold to discard\")\n\t\t\t(\"size-mm,mm\", po::value<uint32_t>(&_mm), \"size in mm, if embedded in pdf / printed\")\n\t\t\t(\"rotate-x,x\", po::value<float>(&_rot_x)->default_value(-0.25f, \"-0.25\"), \"x-axis rotation\")\n\t\t\t(\"rotate-y,y\", po::value<float>(&_rot_y)->default_value(0.25f, \"0.25\"), \"y-axis rotation\")\n\t\t\t(\"rotate-z,z\", po::value<float>(&_rot_z)->default_value(1.0f, \"1\"), \"z-axis rotation\")\n\t\t\t;\n\n\t\tpo::positional_options_description p;\n\t\tp.add(\"input-file\", -1);\n\t\tpo::variables_map vm;\n\t\tpo::store(po::command_line_parser(argc, argv).\n\t\t\t\toptions(desc).positional(p).run(), vm);\n\n\t\tif (vm.count(\"help\")) {\n\t\t\tstd::cout << desc << \"\\n\";\n\t\t\treturn 0;\n\t\t}\n\n\t\tpo::notify(vm);\n\n\t\tif (vm.count(\"size-mm\")) {\n\t\t\t_draw_miniature = true;\n\t\t}\n\t} catch (std::exception& e) {\n\t\tstd::cerr << \"Error: \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\n\tload_lut();\n\tload_watermark();\n\n\tif (!boost::filesystem::is_directory(_base)) {\n\t\tstd::cerr << \"Error: \\\"\" << _base << \"\\\" is not a directory\" << std::endl;\n\t\treturn 1;\n\t}\n\tif (boost::filesystem::is_directory(infile)) {\n\t\tstd::cerr << \"Error: \\\"\" << infile << \"\\\" is a directory\" << std::endl;\n\t\treturn 1;\n\t}\n\tif (!boost::filesystem::exists(infile)) {\n\t\tstd::cerr << \"Error: File \\\"\" << infile << \"\\\" does not exist\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tcv::Mat image = cv::imread(infile, CV_LOAD_IMAGE_ANYDEPTH);\n\tif (image.empty()) {\n\t\tstd::cerr << \"Error: File \\\"\" << infile << \"\\\" not readable\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::cout << \"Processing: \" << infile << std::endl;\n\tboost::filesystem::path p(infile);\n\t_base_name = p.stem().string();\n\thandle_image(image, image_width, wavelength);\n\treturn 0;\n}\n\n", "meta": {"hexsha": "d5dca7cbdef8375e91f017da161081bf6d1b0cb8", "size": 36363, "ext": "cc", "lang": "C++", "max_stars_repo_path": "beamprofile.cc", "max_stars_repo_name": "psychoticbeef/3dfromintensity", "max_stars_repo_head_hexsha": "ae63a1fb2e3de9c92d7b1fa6cd09ba59f5d60554", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "beamprofile.cc", "max_issues_repo_name": "psychoticbeef/3dfromintensity", "max_issues_repo_head_hexsha": "ae63a1fb2e3de9c92d7b1fa6cd09ba59f5d60554", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "beamprofile.cc", "max_forks_repo_name": "psychoticbeef/3dfromintensity", "max_forks_repo_head_hexsha": "ae63a1fb2e3de9c92d7b1fa6cd09ba59f5d60554", "max_forks_repo_licenses": ["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.681865285, "max_line_length": 187, "alphanum_fraction": 0.66171658, "num_tokens": 12197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.018264278786037792, "lm_q1q2_score": 0.00870438361077959}}
{"text": "/* \n * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"kmcmultiple.h\"\n#include <votca/xtp/gnode.h>\n#include <votca/tools/property.h>\n#include <votca/tools/constants.h>\n#include <boost/format.hpp>\n#include <votca/ctp/topology.h>\n#include <locale>\n\n\nusing namespace std;\n\nnamespace votca {\n    namespace xtp {\n\n    \n\n\nvoid KMCMultiple::Initialize(tools::Property *options){\n    std::string key = \"options.\" + Identify();\n\n    _runtime=options->ifExistsReturnElseThrowRuntimeError<double>(key+\".runtime\");\n    _seed=options->ifExistsReturnElseThrowRuntimeError<int>(key+\".seed\");\n    _numberofcharges=options->ifExistsReturnElseThrowRuntimeError<int>(key+\".numberofcharges\");\n    _injection_name=options->ifExistsReturnElseThrowRuntimeError<std::string>(key+\".injectionpattern\");\n  _intermediateoutput_frequency=options->ifExistsReturnElseReturnDefault<int>(key+\".intermediateoutput\",1E9);\n\n        _maxrealtime=options->ifExistsReturnElseReturnDefault<double>(key+\".maxrealtime\",1E10);\n        _trajectoryfile=options->ifExistsReturnElseReturnDefault<std::string>(key+\".trajectoryfile\",\"trajectory.csv\");\n        _temperature=options->ifExistsReturnElseReturnDefault<double>(key+\".temperature\",300);\n        _rates=options->ifExistsReturnElseReturnDefault<std::string>(key+\".rates\",\"statefile\");\n        \n     \n        _injectionmethod = options->ifExistsReturnElseReturnDefault<std::string>(key+\".injectionmethod\",\"random\");\n\t\n        if (_injectionmethod != \"random\"){\n\t    cout << \"WARNING in kmcmultiple: Unknown injection method. It will be set to random injection.\" << endl;\n            _injectionmethod = \"random\";\n        }\n         _field = options->ifExistsReturnElseReturnDefault<tools::vec>(key+\".field\",tools::vec(0,0,0));\n         double mtonm=1E9;\n       _field /=mtonm ;//Converting from V/m to V/nm \n      \n        _outputtime = options->ifExistsReturnElseReturnDefault<double>(key+\".outputtime\",0);\n        _timefile = options->ifExistsReturnElseReturnDefault<std::string>(key+\".timefile\",\"timedependence.csv\");\n\t\n        std::string carriertype=options->ifExistsReturnElseReturnDefault<std::string>(key+\".carriertype\",\"e\");\n        _carriertype=StringtoCarriertype(carriertype);\n     \n        \n        lengthdistribution = options->ifExistsReturnElseReturnDefault<double>(key+\".jumplengthdist\",0);\n        if(lengthdistribution>0){\n            dolengthdistributon=true;\n        }\n\n        return;\n}      \n        \n\n\nvoid KMCMultiple::RunVSSM(ctp::Topology *top)\n{\n\n    int realtime_start = time(NULL);\n    cout << endl << \"Algorithm: VSSM for Multiple Charges\" << endl;\n    cout << \"number of charges: \" << _numberofcharges << endl;\n    cout << \"number of nodes: \" << _nodes.size() << endl;\n    \n    bool checkifoutput=(_outputtime != 0);\n    double nexttrajoutput=0;\n//    double nexttrajoutput=_runtime;\n    unsigned long maxsteps=_runtime;\n    unsigned long outputstep=_outputtime;\n    bool stopontime=false;\n    \n\n    if(_runtime > 100){ \n        cout << \"stop condition: \" << maxsteps << \" steps.\" << endl;\n        \n        if(checkifoutput){\n\t    cout << \"output frequency: \";\n            cout << \"every \" << outputstep << \" steps.\" << endl;\n        }\n    }\n    else{\n        stopontime =true;\n        cout << \"stop condition: \" << _runtime << \" seconds runtime.\" << endl;\n       \n        if(checkifoutput){\n\t    cout << \"output frequency: \";\n            cout << \"every \" << _outputtime << \" seconds.\" << endl;\n        }\n    }\n    cout << \"(If you specify runtimes larger than 100 kmcmultiple assumes that you are specifying the number of steps for both runtime and outputtime.)\" << endl;\n    \n    if(!stopontime && _outputtime != 0 && floor(_outputtime) != _outputtime){\n        throw runtime_error(\"ERROR in kmcmultiple: runtime was specified in steps (>100) and outputtime in seconds (not an integer). Please use the same units for both input parameters.\");\n    }\n    \n    if(_numberofcharges > _nodes.size()){\n        throw runtime_error(\"ERROR in kmcmultiple: specified number of charges is greater than the number of nodes. This conflicts with single occupation.\");\n    }\n\n    fstream traj;\n    fstream tfile;\n    \n    if(checkifoutput){   \n        \n        cout << \"Writing trajectory to \" << _trajectoryfile << \".\" << endl; \n        traj.open (_trajectoryfile.c_str(), fstream::out);\n    \n        traj << \"'time[s]'\\t\";\n        traj << \"'steps'\\t\";\n        for(unsigned int i=0; i<_numberofcharges; i++){\n            traj << \"'carrier\" << i+1 << \"_x'\\t\";    \n            traj << \"'carrier\" << i+1 << \"_y'\\t\";    \n            traj << \"'carrier\" << i+1 << \"_z\";    \n            if(i<_numberofcharges-1){\n                traj << \"'\\t\";\n            }\n        }\n        traj << endl;\n\n        cout << \"Writing time dependence of energy and mobility to \" << _timefile << \".\" << endl; \n        tfile.open (_timefile.c_str(), fstream::out);\n        tfile << \"time[s]\\t steps\\tenergy_per_carrier[eV]\\tmobility[nm**2/Vs]\\tdistance_fielddirection[nm]\\tdistance_absolute[nm]\" << endl;\n        \n    }\n\n    double absolute_field = tools::abs(_field);\n\n    RandomlyCreateCharges();\n    vector<tools::vec> startposition(_numberofcharges,tools::vec(0.0));\n    for(unsigned int i=0; i<_numberofcharges; i++) {\n        startposition[i]=_carriers[i]->getCurrentPosition();\n    }\n    \n    \n    traj << 0 << \"\\t\";\n    traj << 0 << \"\\t\";\n    for(unsigned int i=0; i<_numberofcharges; i++) {\n        traj << startposition[i].getX()  << \"\\t\";\n        traj << startposition[i].getY() << \"\\t\";\n        traj << startposition[i].getZ();\n        if (i<_numberofcharges-1) {\n            traj << \"\\t\";\n        }\n        else{\n            traj << endl;\n        }\n    }\n  \n    vector<int> forbiddennodes;\n    vector<int> forbiddendests;\n    \n    tools::matrix avgdiffusiontensor;\n    avgdiffusiontensor.ZeroMatrix();\n    \n    unsigned long diffusionresolution=1000;\n    double simtime = 0.0;\n    unsigned long step = 0;\n    \n    while(((stopontime && simtime < _runtime) || (!stopontime && step < maxsteps))){\n        \n        if((time(NULL) - realtime_start) > _maxrealtime*60.*60.)\n        {\n            cout  << endl << \"Real time limit of \" << _maxrealtime << \" hours (\" << int(_maxrealtime*60*60 +0.5) <<\" seconds) has been reached. Stopping here.\" << endl << endl;\n            break;\n        }\n        \n        double cumulated_rate = 0;\n        for(unsigned int i=0; i<_numberofcharges; i++)\n        {\n            cumulated_rate += _carriers[i]->getCurrentEscapeRate();\n        }\n        if(cumulated_rate == 0)\n        {   // this should not happen: no possible jumps defined for a node\n            throw runtime_error(\"ERROR in kmcmultiple: Incorrect rates in the database file. All the escape rates for the current setting are 0.\");\n        }\n        \n        double dt =Promotetime(cumulated_rate);\n        \n        simtime += dt;\n        step++;\n        if(tools::globals::verbose) {cout << \"simtime += \" << dt << endl << endl;}\n        \n        \n        \n        \n        for(unsigned int i=0; i<_numberofcharges; i++)\n        {\n            _carriers[i]->updateOccupationtime(dt);\n        }\n\n        \n        ResetForbiddenlist(forbiddennodes);\n        bool level1step = true;\n        while(level1step){\n\n            // determine which electron will escape\n            \n            GNode* newnode= NULL;\n            Chargecarrier* affectedcarrier=ChooseAffectedCarrier(cumulated_rate); \n            \n            if(CheckForbidden(affectedcarrier->getCurrentNodeId(), forbiddennodes)) {continue;}\n            \n            // determine where it will jump to\n            ResetForbiddenlist(forbiddendests);\n            while(true){\n            // LEVEL 2\n                if(tools::globals::verbose) {cout << \"There are \" <<affectedcarrier->getCurrentNode()->events.size() << \" possible jumps for this charge:\"; }\n              \n\n                GLink* event=ChooseHoppingDest(affectedcarrier->getCurrentNode());\n                newnode = _nodes[event->destination];\n                if(newnode==affectedcarrier->getCurrentNode()){\n                    cout<<event->dr<<endl;\n                }\n\n                if(newnode == NULL){\n                    if(tools::globals::verbose) {\n                        cout << endl << \"Node \" << affectedcarrier->getCurrentNodeId()+1  << \" is SURROUNDED by forbidden destinations and zero rates. \"\n                                \"Adding it to the list of forbidden nodes. After that: selection of a new escape node.\" << endl; \n                    }\n                    AddtoForbiddenlist(affectedcarrier->getCurrentNodeId(), forbiddennodes);\n                    break; // select new escape node (ends level 2 but without setting level1step to 1)\n                }\n                if(tools::globals::verbose) {cout << endl << \"Selected jump: \" << newnode->id+1 << endl; }\n                \n                // check after the event if this was allowed\n                if(CheckForbidden(newnode->id, forbiddendests)){\n                    if(tools::globals::verbose) {cout << \"Node \" << newnode->id+1  << \" is FORBIDDEN. Now selection new hopping destination.\" << endl; }\n                    continue;\n                }\n\n                // if the new segment is unoccupied: jump; if not: add to forbidden list and choose new hopping destination\n                if(newnode->occupied){\n                    if(CheckSurrounded(affectedcarrier->getCurrentNode(), forbiddendests)){\n                        if(tools::globals::verbose) {\n                            cout << \"Node \" << affectedcarrier->getCurrentNodeId()+1  << \" is SURROUNDED by forbidden destinations. \"\n                                    \"Adding it to the list of forbidden nodes. After that: selection of a new escape node.\" << endl; \n                        }\n                        AddtoForbiddenlist(affectedcarrier->getCurrentNodeId(), forbiddennodes);\n                        break; // select new escape node (ends level 2 but without setting level1step to 1)\n                    }\n                    if(tools::globals::verbose) {cout << \"Selected segment: \" << newnode->id+1 << \" is already OCCUPIED. Added to forbidden list.\" << endl << endl;}\n                    AddtoForbiddenlist(newnode->id, forbiddendests);\n                    if(tools::globals::verbose) {cout << \"Now choosing different hopping destination.\" << endl; }\n                    continue; // select new destination\n                }\n                else{\n                    affectedcarrier->jumpfromCurrentNodetoNode(newnode);\n                    affectedcarrier->dr_travelled +=event->dr;\n                    AddtoJumplengthdistro(event,dt);\n                    level1step = false;\n                    if(tools::globals::verbose) {cout << \"Charge has jumped to segment: \" << newnode->id+1 << \".\" << endl;}\n                    \n                    break; // this ends LEVEL 2 , so that the time is updated and the next MC step started\n                }\n\n                if(tools::globals::verbose) {cout << \".\" << endl;}\n            // END LEVEL 2\n            }\n        // END LEVEL 1\n        }    \n              \n        //outputstuff\n        \n        if(step%diffusionresolution==0){     \n            for(unsigned int i=0; i<_numberofcharges; i++){\n                avgdiffusiontensor += (_carriers[i]->dr_travelled)|(_carriers[i]->dr_travelled);\n            }\n        }\n        \n        if (step != 0 && step % _intermediateoutput_frequency == 0) {\n\n            if (absolute_field == 0) {\n                unsigned long diffusionsteps = step / diffusionresolution;\n                tools::matrix result = avgdiffusiontensor / (diffusionsteps * 2 * simtime * _numberofcharges);\n                cout << endl << \"Step: \" << step << \" Diffusion tensor averaged over all carriers (nm^2/s):\" << endl << result << endl;\n            } else {\n                double average_mobility = 0;\n                cout << endl << \"Mobilities (nm^2/Vs): \" << endl;\n                for (unsigned int i = 0; i < _numberofcharges; i++) {\n                    tools::vec velocity = _carriers[i]->dr_travelled / simtime;\n                    cout << std::scientific << \"    charge \" << i + 1 << \": mu=\" << (velocity * _field) / (absolute_field * absolute_field) << endl;\n                    average_mobility += (velocity * _field) / (absolute_field * absolute_field);\n                }\n                average_mobility /= _numberofcharges;\n                cout << std::scientific << \"  Overall average mobility in field direction <mu>=\" << average_mobility << \" nm^2/Vs  \" << endl;\n            }\n        }\n\n        \n        \n        if(checkifoutput) { \n            bool outputsteps=(!stopontime && step%outputstep==0);\n            bool outputtime=(stopontime && simtime>nexttrajoutput);\n            if(outputsteps || outputtime){\n                // write to trajectory file\n                nexttrajoutput = simtime + _outputtime;\n                traj << simtime << \"\\t\";\n            traj << step << \"\\t\";\n                for(unsigned int i=0; i<_numberofcharges; i++) {\n                    traj << startposition[i].getX() + _carriers[i]->dr_travelled.getX() << \"\\t\";\n                    traj << startposition[i].getY() + _carriers[i]->dr_travelled.getY() << \"\\t\";\n                    traj << startposition[i].getZ() + _carriers[i]->dr_travelled.getZ();\n                    if (i<_numberofcharges-1) {\n                        traj << \"\\t\";\n                    }\n                    else{\n                        traj << endl;\n                    }\n                }\n                \n              \n                double currentenergy = 0;\n                double currentmobility = 0;\n                tools::vec dr_travelled_current = tools::vec (0,0,0);\n                double dr_travelled_field=0.0;\n                tools::vec avgvelocity_current = tools::vec(0,0,0);\n                if(absolute_field != 0){\n                    for(unsigned int i=0; i<_numberofcharges; i++){\n                        dr_travelled_current += _carriers[i]->dr_travelled;\n                        currentenergy += _carriers[i]->getCurrentEnergy();\n                    }\n                    dr_travelled_current /= _numberofcharges;\n                    currentenergy /= _numberofcharges;\n                    avgvelocity_current = dr_travelled_current/simtime; \n                    currentmobility = (avgvelocity_current*_field) /absolute_field/absolute_field;\n                    dr_travelled_field=(dr_travelled_current*_field)/absolute_field;\n                }\n                \n                tfile << simtime << \"\\t\"<< step << \"\\t\"<< currentenergy << \"\\t\" << currentmobility << \"\\t\" <<\n                        dr_travelled_field << \"\\t\" << tools::abs(dr_travelled_current)<<\"\\t\"<< endl;\n              \n            }\n        }\n      \n    }//KMC \n    \n    \n    \n    if(checkifoutput)\n    {   \n        traj.close();\n        tfile.close();\n    }\n\n    \n    vector< ctp::Segment* >& seg = top->Segments();\n    for (unsigned i = 0; i < seg.size(); i++) {\n            double occupationprobability=_nodes[i]->occupationtime / simtime;\n            seg[i]->setOcc(occupationprobability,_carriertype);\n        }\n\n    cout << endl << \"finished KMC simulation after \" << step << \" steps.\" << endl;\n    cout << \"simulated time \" << simtime << \" seconds.\" << endl;\n    cout << \"runtime: \";\n    cout << endl << endl;\n    \n    tools::vec avg_dr_travelled = tools::vec (0,0,0);\n    for(unsigned int i=0; i<_numberofcharges; i++){\n        cout << std::scientific << \"    charge \" << i+1 << \": \" << _carriers[i]->dr_travelled/simtime << endl;\n        avg_dr_travelled += _carriers[i]->dr_travelled;\n    }\n    avg_dr_travelled /= _numberofcharges;\n    \n    tools::vec avgvelocity = avg_dr_travelled/simtime; \n    cout << std::scientific << \"  Overall average velocity (nm/s): \" << avgvelocity << endl;\n\n    cout << endl << \"Distances travelled (nm): \" << endl;\n    for(unsigned int i=0; i<_numberofcharges; i++){\n        cout << std::scientific << \"    charge \" << i+1 << \": \" << _carriers[i]->dr_travelled << endl;\n    }\n    \n    // calculate mobilities\n   \n    if (absolute_field != 0){\n        double average_mobility = 0;\n        cout << endl << \"Mobilities (nm^2/Vs): \" << endl;\n        for(unsigned int i=0; i<_numberofcharges; i++){\n            tools::vec velocity = _carriers[i]->dr_travelled/simtime;\n            cout << std::scientific << \"    charge \" << i+1 << \": mu=\" << (velocity*_field)/(absolute_field*absolute_field) << endl;\n            average_mobility += (velocity*_field) /(absolute_field*absolute_field);\n        }\n        average_mobility /= _numberofcharges;\n        cout << std::scientific << \"  Overall average mobility in field direction <mu>=\" << average_mobility << \" nm^2/Vs  \" << endl;\n      }\n    cout << endl;\n    \n    // calculate diffusion tensor\n    unsigned long diffusionsteps=step/diffusionresolution;\n    avgdiffusiontensor /= (diffusionsteps*2*simtime*_numberofcharges);\n    cout<<endl<<\"Diffusion tensor averaged over all carriers (nm^2/s):\" << endl << avgdiffusiontensor << endl;\n    \n  \n\n    tools::matrix::eigensystem_t diff_tensor_eigensystem;\n    cout<<endl<<\"Eigenvalues: \"<<endl<<endl;\n    avgdiffusiontensor.SolveEigensystem(diff_tensor_eigensystem);\n    for(int i=0; i<=2; i++)\n    {\n        cout<<\"Eigenvalue: \"<<diff_tensor_eigensystem.eigenvalues[i]<<endl<<\"Eigenvector: \";\n               \n        cout<<diff_tensor_eigensystem.eigenvecs[i].x()<<\"   \";\n        cout<<diff_tensor_eigensystem.eigenvecs[i].y()<<\"   \";\n        cout<<diff_tensor_eigensystem.eigenvecs[i].z()<<endl<<endl;\n    }\n    \n    // calculate average mobility from the Einstein relation\n    if (absolute_field == 0){\n        cout << \"The following value is calculated using the Einstein relation and assuming an isotropic medium\" << endl;\n       double avgD  = 1./3. * (diff_tensor_eigensystem.eigenvalues[0] + diff_tensor_eigensystem.eigenvalues[1] + diff_tensor_eigensystem.eigenvalues[2] );\n       double average_mobility = std::abs(avgD / tools::conv::kB / _temperature);\n       cout << std::scientific << \"  Overall average mobility <mu>=\" << average_mobility << \" nm^2/Vs \"  << endl;\n    }\n    \n  PrintJumplengthdistro();\n    \n\n    \n    return;\n}\n\n\n\n\nbool KMCMultiple::EvaluateFrame(ctp::Topology *top){\n    std::cout << std::endl;      \n    std::cout << \"-----------------------------------\" << std::endl;      \n    std::cout << \"      KMC FOR MULTIPLE CHARGES\" << std::endl;\n    std::cout << \"-----------------------------------\" << std::endl << std::endl;      \n \n    // Initialise random number generator\n    if(tools::globals::verbose) { cout << endl << \"Initialising random number generator\" << endl; }\n    srand(_seed); // srand expects any integer in order to initialise the random number generator\n    _RandomVariable = tools::Random2();\n    _RandomVariable.init(rand(), rand(), rand(), rand());\n    \n    LoadGraph(top);\n    \n        \n        if(_rates == \"calculate\")\n        {\n            cout << \"Calculating rates (i.e. rates from state file are not used).\" << endl;\n            InitialRates();\n        }\n        else\n        {\n            cout << \"Using rates from state file.\" << endl;\n        }\n    \n\n    RunVSSM(top);\n\n    return true;\n}\n    \n    }\n}\n", "meta": {"hexsha": "101de52cc7b48ae8c722485b9a70671e89adf83a", "size": 19808, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/calculators/kmcmultiple.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/calculators/kmcmultiple.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/calculators/kmcmultiple.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4393305439, "max_line_length": 188, "alphanum_fraction": 0.5670941034, "num_tokens": 4659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.028007522025783438, "lm_q1q2_score": 0.00870177978116882}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sprog (gas-phase chemical kinetics).\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Mixture class declared in the\n    gpc_mixture.h header file.\n\n  Licence:\n    This file is part of \"sprog\".\n\n    sprog 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 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"gpc_params.h\"\n#include \"gpc_mixture.h\"\n#include \"gpc_idealgas.h\"\n#include \"gpc_transport_factory.h\"\n#include \"gpc_mech.h\"\n#include <vector>\n#include <stdexcept>\n#include <boost/serialization/vector.hpp>\n//#include <bits/stl_vector.h>\n\nusing namespace Sprog;\nusing namespace Sprog::Thermo;\nusing namespace std;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (private).\nMixture::Mixture(void)\n: m_vmodel(Sprog::iAir)\n{\n    m_data.clear();\n    m_species = NULL;\n}\n\n// Default constructor (public, requires species list).\nMixture::Mixture(const SpeciesPtrVector &sp)\n: m_vmodel(Sprog::iAir)\n{\n    SetSpecies(sp);\n}\n\n/*\nMixture::Mixture(const SpeciesPtrVector &sp, const int NumGasSp, const int NumSurfSp)\n{\n    SetSpecies(sp);\n\tgasSpeciesCount =  NumGasSp; \n\tsurfSpeciesCount = \tNumSurfSp; \n}\n*/\n\n// Copy constructor.\nMixture::Mixture(const Mixture &copy)\n: m_vmodel(copy.m_vmodel)\n{\n    *this = copy;\n}\n\n\n// Stream-reading constructor.\nMixture::Mixture(std::istream &in, const SpeciesPtrVector &sp)\n{\n    Deserialize(in);\n    SetSpecies(sp);\n}\n\n// Default destructor.\nMixture::~Mixture(void)\n{\n    m_data.clear();\n}\n\n\n// OPERATOR OVERLOADING.\n\n// Assignment operator.\nMixture &Mixture::operator=(const Mixture &mix)\n{\n    // Check for self assignment.\n    if (this != &mix) {\n        m_data.assign(mix.m_data.begin(), mix.m_data.end());\n        m_species = mix.m_species;\n\t\tgasSpeciesCount = mix.gasSpeciesCount;\n\t\tsurfSpeciesCount = mix.surfSpeciesCount; \n    }\n\n    return *this;\n}\n\n// Returns the PAH formation rate. \ndouble Mixture::PAHFormationRate() const\n{\n    return m_data[PAHFormationIndex()];\n}\n\n// Set the PAH formation rate.\nvoid Mixture::SetPAHFormationRate(double r)\n{\n    m_data[PAHFormationIndex()] = r;\n}\n\n\n// TEMPERATURE.\n\n// Returns the mixture temperature.\ndouble Mixture::Temperature() const\n{\n    return m_data[temperatureIndex()];\n}\n\n\n// Set the mixture temperature.\nvoid Mixture::SetTemperature(double T)\n{\n    m_data[temperatureIndex()] = T;\n}\n\n// Set convective velocity\nvoid Mixture::SetConvectiveVelocity(double u)\n{\n    m_data[ConvectiveVelocityIndex()] = u;\n}\n\n// Get convective velocity\ndouble Mixture::GetConvectiveVelocity() const\n{\n    return m_data[ConvectiveVelocityIndex()];\n}\n\n// Set thermophoretic velocity\nvoid Mixture::SetThermophoreticVelocity(double v)\n{\n    m_data[ThermophoreticVelocityIndex()] = v;\n}\n\n// Get thermophoretic velocity\ndouble Mixture::GetThermophoreticVelocity() const\n{\n    return m_data[ThermophoreticVelocityIndex()];\n}\n\n// Set diffusion term\nvoid Mixture::SetDiffusionTerm(double D)\n{\n    m_data[DiffusionTermIndex()] = D;\n}\n\n// Get diffusion term\ndouble Mixture::GetDiffusionTerm() const\n{\n    return m_data[DiffusionTermIndex()];\n}\n// CONCENTRATIONS/FRACTIONS.\n\n// Returns the vector of mixture species mole fractions. (NO NEED CHANGING)\nconst fvector &Mixture::MoleFractions() const\n{\n    return m_data;\n}\n\n// Returns a vector of species concentrations. (Modified) (C, Debugged)\nvoid Mixture::GetConcs(fvector &concs) const\n{\n    // Resize output vector.\n    const size_t numSpecies = m_species->size();\n    concs.resize(numSpecies);\n\n    // Loop over all mole fractions and convert to concentrations.\n    const double density = m_data[densityIndex()];\n\t\n    for (unsigned int i = 0; i != gasSpeciesCount; ++i) {\n        concs[i] = m_data[i] * density;\n    }\n\n\t// Concentration for surface species\t\n    for (unsigned int i =  gasSpeciesCount; i != m_species->size(); ++i) {\n\t\n\tstring spName = (*m_species)[0]->Mechanism()->GetSpecies(i)->Name(); \n\tstring phName = (*m_species)[0]->Mechanism()->GetSpecies(spName)->PhaseName();\n\tdouble site_d =  (*m_species)[0]->Mechanism()->FindSiteDensity(phName);\n\tint sp_occ = (*m_species)[0]->Mechanism()->FindSiteOccup(spName);\n\t\n        concs[i] = m_data[i] * site_d/sp_occ;\n    }\n}\n\n// Returns a vector of species mass fractions. (Modified) (C, Not used in mops, sprogc)\nvoid Mixture::GetMassFractions(fvector &fracs) const\n{\n    // Clear output vector.\n    fracs.resize(m_species->size());\n\n    // Loop over all mole fractions and convert to mass fractions:\n    //   y = x * wt / sum(x*wt)\n    double val, tot = 0.0;\n    for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n        val = m_data[i] * (*m_species)[i]->MolWt();\n        fracs[i] = val;\n        tot += val;\n    }\n    tot = 1.0 / tot;\n    for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n        fracs[i] *= tot;\n    }\n\t\n\t\n\t\n\tstd::vector<double> TOT; \n\t\n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\tval = 0.0;\n\t\ttot = 0.0;\n\t\tstd::string phname =  (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\tval = m_data[i] * (*m_species)[i]->MolWt();\n\t\t\tfracs[i] = val;\n\t\t\ttot += val;\n\t\t\t}\n\t\n\t\t}\n\t   TOT.push_back(tot); \n\t}\n\t\n\t\n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\tTOT[j] = 1.0/ TOT[j];\n\t\tstd::string phname =  (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\tfracs[i] *= TOT[j];\n\t\t\t}\n\t\t}\n\t   \n\t}\n\t\n}\n\n// Returns the mole fraction of species i. (UNMODIFIED) (C)\ndouble Mixture::MoleFraction(unsigned int i) const\n{\n    if (i < m_species->size()) {\n        return m_data[i];\n    } else {\n        return 0.0;\n    }\n}\n\n// Returns the molar concentration of species i. (Modified by mm864, currently unused in mops-sprogc) (C)\ndouble Mixture::MolarConc(unsigned int i) const\n{\n    if (i < gasSpeciesCount) {\n\t\treturn m_data[i] * m_data[densityIndex()];\n    } \n\telse {\n        return MolarSurfConc(i);\n    }\n}\n\n// Returns the molar surface concentration of species i. (Modified by mm864) (C, currently unused in mops-sprogc)\ndouble Mixture::MolarSurfConc(unsigned int i) const\n{\n    if ((i >= gasSpeciesCount) && (i < m_species->size()) ) {\n      string phName = (*m_species)[i]->PhaseName();\n      double siteDen = 0.0; \n      siteDen = (*m_species)[0]->Mechanism()->FindSiteDensity(phName);\n\n      return m_data[i] * siteDen / ((*m_species)[i]->SiteOccupancy()); // m_data should contains site fraction !! \n    } else {\n        return 0.0;\n    }\n}\n\n// Returns the mass fraction of species i. (modified by mm864)  (C, currently unused in mops-sprogc)\ndouble Mixture::MassFraction(unsigned int i) const\n{\n    if (i < gasSpeciesCount) {\n        // Get total x * W.\n        double tot = 0.0;\n        for (unsigned int j=0; j!=gasSpeciesCount; ++j) {\n            tot += m_data[j] * (*m_species)[j]->MolWt();\n        }\n\n        // Return mass fraction.\n        return m_data[i] * (*m_species)[i]->MolWt() / tot;\n    } \n\t\n\telse if((i >= gasSpeciesCount) && (i < m_species->size()) ) {\n\t\n\tfvector massFrac;\n\tGetMassFractions(massFrac); \n\t\n\treturn massFrac[i];\n\t\n\t}\n\t\n\telse {\n        return 0.0;\n    }\n}\n\n// Sets the vector of species mole fractions. (modified by mm864) (C, debugged)\nvoid Mixture::SetFracs(const fvector &fracs)\n{\n    double tot =0.0;\n\n    // Set the mole fractions.\n    for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n        m_data[i] = fracs[i];\n        tot += fracs[i];\n    }\n\n    // Ensure that the mole fractions are normalised.\n    if (tot != 1.0) {\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            m_data[i] /= tot;\n            \n        }\n    }\n    \n\t\n\t// Surface species\n\tstd::vector<double> Z; \n\n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\tdouble ztot = 0.0;\n\tstd::string phname =  (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\tcout << \"phasename\" << phname << endl;\n\t\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\tm_data[i] = fracs[i];\n\t\t\tztot += fracs[i];\n\t\t\t}\t\n\t\t}\n\t    Z.push_back(ztot); // NOTE Z will allocate Z = 0.0 for gas phase but it won't mess up the next stage below\n\t\n\t}\n\n\t// Ensure that the mole fractions are normalised. \n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\n\tif ((Z[j] != 1.0) && ( (*m_species)[0]->Mechanism()->Phase(j)->Name().compare(\"gas\") != 0)) {\n\t\n\t\t\tstd::string phname = (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\n\t\t\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\t\tm_data[i] /= Z[j];\n\t\t\t\t}\n\t\t\t}\n    }\n\t\n    }\n\n\t\n}\n\n// Sets the species mole fractions from an array of values. (modified by mm864) (C, currently not used in mops-sprogc)\nvoid Mixture::SetFracs(const double fracs[], int n)\n{\n\n\t/*\n    // Check that the array of of sufficient length.\n    if ((unsigned)n >= gasSpeciesCount) {\n        double tot = 0.0;\n\n        // Set the fractions.\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            m_data[i] = fracs[i];\n            tot += fracs[i];\n        }\n\n        // Ensure that the mole fractions are normalised.\n        if (tot != 1.0) {\n            for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n                m_data[i] /= tot;\n            }\n        }\n    }\n\t*/\n\t\t\n\t// Check that the array of of sufficient length.\n    if ((unsigned)n >= m_species->size()) {\n        \n        // Set the fractions.\n        \n\t\t// Surface and gas species\n\t\tstd::vector<double> Z; \n\t\t\n\t\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\tdouble fractot = 0.0;\n\t\tstd::string phname =  (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\tcout << \"phasename\" << phname << endl;\n\t\tfor (unsigned int i=0; i!=m_species->size(); ++i) {\n\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\tm_data[i] = fracs[i];\n\t\t\tfractot += fracs[i];\n\t\t\t}\t\n\t\t}\n\t    Z.push_back(fractot); \n\t\n\t}\n\t\n\t// Ensure that the mole fractions are normalised.\n\t\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\n\t\tif ((Z[j] != 1.0)) {\n\t\n\t\t\tstd::string phname = (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\n\t\t\tfor (unsigned int i=0; i!=m_species->size(); ++i) {\n\t\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\t\tm_data[i] /= Z[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\t}\n\n\t\t\n\t\t\n    }\n\t\n\t\n}\n\n// Sets the species mole fractions using the supplied molar concentrations?? (modified by mm864 , currently not used in mops-sprogc)\nvoid Mixture::SetConcs(const fvector &concs) // Is this correct?\n{\n    // Check that the concentration vector is of sufficient length.\n    if (concs.size() >= m_species->size()) {\n        // Sum up the total concentration.\n\t\t\n\t\t\n        m_data[densityIndex()] = 0.0;\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            m_data[i] = concs[i];\n            m_data[densityIndex()] += concs[i];\n        }\n\n        // Convert values to mole fractions.\n        double invdens = 1.0 / m_data[densityIndex()];\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            m_data[i] *= invdens;\n        }\n\t\t\n\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\tstring phName = (*m_species)[i]->PhaseName();\n\t\tdouble siteDen = 0.0; \n\t\tsiteDen = (*m_species)[0]->Mechanism()->FindSiteDensity(phName);\n\t\tm_data[i] = concs [i] * ((*m_species)[i]->SiteOccupancy()) / siteDen; // m_data should contains site fraction !! \n\t}\n\t\t\n\n    }\n}\n\n// Sets the species mole fractions using the supplied mass fractions. (modified by mm864, currently not in used for mops-sprogc) (?) Can you have mass frac in surface\nvoid Mixture::SetMassFracs(const fvector &fracs)\n{\n    // Check that the mass fraction vector is of sufficient length.\n    if (fracs.size() >= m_species->size()) {\n        double val = 0.0, tot = 0.0, totfrac = 0.0;\n\t\n        // Check that the fractions are normalised by summing up\n        // the total fractions, and dividing the values by this\n        // sum in the next step.\n        //std::cout << \"Mass fractions:\";\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            totfrac += fracs[i];\n            //std::cout << ' ' << fracs[i];\n        }\n        //std::cout << \" tot \" << totfrac << std::endl;\n\n        // Convert to mole fractions:\n        //   x = y / (wt * sum(y/wt))\n        //std::cout << \"Mole fractions (1):\";\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            val = fracs[i] / (totfrac * (*m_species)[i]->MolWt());\n            m_data[i] = val;\n            //std::cout << ' ' << val;\n            tot += val;\n        }\n        //std::cout << \" tot \" << tot << std::endl;\n\n        tot = 1.0 / tot;\n        //std::cout << \"Mole fractions (2):\";\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            m_data[i] *= tot;\n            //std::cout << ' ' << m_data[i];\n        }\n        //std::cout << \" tot \" << 1.0 / tot << std::endl;\n\n\t\t// Surface Mole Fraction from mass fraction \n\t\t\n\t\t\n\t\tstd::vector<double> TOT; \n\t\n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\tval = 0.0, tot = 0.0, totfrac = 0.0;\n\t\t\n\t\tstd::string phname =  (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\t\n\t\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\ttotfrac += fracs[i];\n\t\t\tval = fracs[i] / (totfrac * (*m_species)[i]->MolWt());\n            m_data[i] = val;\n\t\t\ttot += val;\n\t\t\t}\n\t\n\t\t}\n\t   TOT.push_back(tot); \n\t}\n\t\n\t\n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\tTOT[j] = 1.0/ TOT[j];\n\t\tstd::string phname =  (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n\t\t\tm_data[i] *= TOT[j];\n\t\t\t}\n\t\t}\n\t   \n\t}\n\t\n\t\t\n    }\n}\n\n// Checks the vector of mole fractions for validity by settings all negative\n// values to zero, and by normalising the values so that they sum\n// to one. (Modified by mm864) (C, Debugged)\nvoid Mixture::Normalise()\n{\n    double xtot = 0.0;\n\n    for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n        if (m_data[i] < 0.0) m_data[i] = 0.0;\n        xtot += m_data[i];\n    }\n\n    if (xtot != 1.0) {\n        for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n            m_data[i] /= xtot;\n        }\n    }\n\t\n\tstd::vector<double> Z; \n\t\n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\tdouble ztot = 0.0;\n\tstd::string phname =  (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\n\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n        if (m_data[i] < 0.0) m_data[i] = 0.0;\n        ztot += m_data[i];\n    }\n\t\n\t}\n\tZ.push_back(ztot); // NOTE Z will allocate Z = 0.0 for gas phase but it won't mess up the next stage below\n\t\n\t}\n\t\n\tfor (unsigned int j = 0; j!=(*m_species)[0]->Mechanism()->PhaseCount(); ++j){\n\t\n\tif ((Z[j] != 1.0) && ( (*m_species)[0]->Mechanism()->Phase(j)->Name().compare(\"gas\") != 0)) {\n\t\n        std::string phname = (*m_species)[0]->Mechanism()->Phase(j)->Name();\n\t\n\t\tfor (unsigned int i=gasSpeciesCount; i!=m_species->size(); ++i) {\n\t\tif (((*m_species)[i]->PhaseName()).compare(phname) == 0 ){\n        m_data[i] /= Z[j];\n        }\n\t\t}\n    }\n\t\n    }\n\n\t\n}\n\n\n// MIXTURE DENSITY. (UPDATED)\n\n// Returns the mixture molar density. (C)\ndouble Mixture::Density() const\n{\n    return m_data[densityIndex()];\n}\n\n// Returns the mixture mass density. (include gas phase only) (C, currently not in used for mops-sprogc)\ndouble Mixture::MassDensity() const\n{\n    double rho = 0.0;\n\n    // Calcualate mass density:\n    //   rho_mass = rho_mole * sum(x * wt)\n    for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n        rho += m_data[i] * (*m_species)[i]->MolWt();\n    }\n    rho *= m_data[densityIndex()];\n\n    return rho;\n}\n\n// Sets the mixture molar density. (C, debugged)\nvoid Mixture::SetDensity(double dens)\n{\n    m_data[densityIndex()] = dens;\n}\n\n// Sets the molar density using the supplied mass density. (THIS SHOULD BE: SET MOLAR DENSITY) (C, currently not in used for mops-sprogc)\nvoid Mixture::SetMassDensity(double dens) // (include gas phase only)\n{\n    double sum = 0.0;\n\n    // Calcualate molar density:\n    //   rho_mass = rho_mole * sum(x * wt)\n    for (unsigned int i=0; i!=gasSpeciesCount; ++i) {\n        sum += m_data[i] * (*m_species)[i]->MolWt();\n    }\n   m_data[densityIndex()] = dens / sum;\n}\n\n\n// MIXTURE CONTEXT. (NO NEED CHANGING)\n\n// Returns a pointer to the vector of species used to define the mixture.\nconst SpeciesPtrVector *const Mixture::Species() const\n{\n    return m_species;\n}\n\n// Sets the vector of species used to define the mixture.\nvoid Mixture::SetSpecies(const Sprog::SpeciesPtrVector &sp)\n{\n    m_species = &sp;\n    m_data.resize(m_species->size()+sNumNonSpeciesData);\n\n\tgasSpeciesCount =0;\n\n\n\tfor (unsigned int j = 0; j != m_species->size(); j++){\n\t\tif (((*m_species)[j]->PhaseName()).compare(\"gas\") == 0){\n\t\n\t\t\tgasSpeciesCount++; \n\t\t}\n\t}\n\n\tsurfSpeciesCount = m_species->size() - gasSpeciesCount;  \n}\n\n\n\n// RAW DATA. (NO NEED CHANGING)\n\ndouble *const Mixture::RawData()\n{\n    return &(m_data[0]);\n}\n\nconst double *const Mixture::RawData() const\n{\n    return &(m_data[0]);\n}\n\n// READ/WRITE/COPY FUNCTIONS. (C)\n\n// Creates a copy of the mixture object.\nMixture *const Mixture::Clone() const\n{\n    return new Mixture(*this);\n}\n\n// Identifies the mixture type for serialisation.\nSerial_MixtureType Mixture::SerialType() const\n{\n    return Serial_Mixture;\n}\n\n// returns the avg mol wt given the mass fractions added by Vinod (modified by mm864, not in used for mops-sprogc)\ndouble Mixture::getAvgMolWt(Sprog::fvector &massFrac) const{\n\tdouble avgMolWt = 0.0;\n\tfor(unsigned int i=0; i!= gasSpeciesCount; i++)\n\t\tavgMolWt += massFrac[i]/(*m_species)[i]->MolWt();\n\n\treturn 1.0/avgMolWt;\n}\n\ndouble Mixture::getAvgMolWt() const { // (modified by mm864, not in used for mops-sprogc)\n    double avgMolWt = 0.0;\n    vector<double> moleFrac = MoleFractions();\n    for(unsigned int i=0; i!= gasSpeciesCount; i++) \n        avgMolWt += moleFrac[i]*(*m_species)[i]->MolWt();\n\n    return avgMolWt;\n\n}\n\n/*!\n * Mean collision cross-section.  This is used, for example,\n * in mean path calculations, although for historical reasons\n * there may be some hard coded instances of related values in\n * Mopssuite.\n *\n * @return Mean collision cross-sectional area in \\f$m^2\\f$.\n */\ndouble Mixture::getMeanCollisionSection() const { // Restricted to gas phase (mm864)\n    double avgColDiam2 = 0.0;\n    for (unsigned i = 0; i!= gasSpeciesCount; ++i) {\n        avgColDiam2 += MoleFraction(i) * (*m_species)[i]->getCollisionDiameter() * (*m_species)[i]->getCollisionDiameter();\n    }\n    return avgColDiam2 * Sprog::PI;\n}\n\n// Following transport related routines are added by Vinod\n// returns the mixture viscosity in Kg/m-s\ndouble Mixture::getViscosity() const{\n\n\tSprog::Transport::MixtureTransport mt;\n\treturn mt.getViscosity(Temperature(),*this);\n}\n\n\n/*!\n * This prevents segmentation faults when accessing the Champan Enksog viscosity\n * model from Sweep.\n *\n * @param mix   Mixture for which to check integrity of transport data\n *\n * @exception   std::runtime_error      No transport data found for species\n */\nvoid Mixture::checkForTransportData() const\n{\n    const SpeciesPtrVector *spv = Species();\n    std::cout << \"Checking for transport data.\" << std::endl;\n    // Loop over all species and check they have transport data\n    for (size_t k = 0; k != spv->size(); ++k) {\n        if (!(*spv)[k]->hasTransportData()) {\n            throw runtime_error(\"No transport data supplied for species \" +\n                    (*spv)[k]->Name() + \".\");\n        }\n    }\n}\n\n// returns the mixture thermal conductivity in J/m-s-K\ndouble Mixture::getThermalConductivity(double pre) const{\n\tSprog::Transport::MixtureTransport mt;\n\treturn mt.getThermalConductivity(Temperature(),pre,*this);\n}\n\nconst vector<double> Mixture::getMolarSpecificHeat(){\n\n        vector<double> cpMols;\n\tSprog::Thermo::IdealGas ig(*this->Species());\n\tig.CalcCps(Temperature(),cpMols);\n        return cpMols;\n}\n\nconst vector<double> Mixture::getMolarEnthalpy(double T){\n\tvector<double> enthalpy;\n\tSprog::Thermo::IdealGas ig(*this->Species());\n\tig.CalcHs(T,enthalpy);\n\treturn enthalpy;\n\n}\n\nconst vector<double> Mixture::getMolarEnthalpy(){\n    vector<double> enthalpy;\n    Sprog::Thermo::IdealGas ig(*this->Species());\n    ig.CalcHs(Temperature(),enthalpy);\n    return enthalpy;\n}\n\n// returns the mixture specific heat capacity in J/Kg K (modified by mm864)\ndouble Mixture::getSpecificHeatCapacity(double T){\n\tdouble cp = 0.0;\n\tvector<double> cpMols, massFrac;\n\tSprog::Thermo::IdealGas ig(*this->Species());\n\tig.CalcCps(T,cpMols);\n\tGetMassFractions(massFrac);\n\tfor(unsigned int i=0; i !=gasSpeciesCount; i++) // OVER GAS PHASE ONLY\n\t\tcp += massFrac[i]*(cpMols[i])/(*m_species)[i]->MolWt();\n\n\treturn cp;\n}\n\n//return the specific heat capacity for the given mixture in J/kg K (modified by mm864)\ndouble Mixture::getSpecificHeatCapacity(){\n\tdouble cp = 0.0;\n\tvector<double> cpMols, massFrac;\n\tSprog::Thermo::IdealGas ig(*this->Species());\n\tig.CalcCps(Temperature(),cpMols);\n\tGetMassFractions(massFrac);\n\tfor(unsigned int i=0; i != gasSpeciesCount; i++) // OVER GAS PHASE ONLY\n\t\tcp += massFrac[i]*(cpMols[i])/(*m_species)[i]->MolWt();\n\n\treturn cp;\n}\n\n// returns the vector of mixture diffusion coefficient in m^2/s\nconst vector<double> Mixture::getMixtureDiffusionCoeff(const double pre) const{\n\tSprog::Transport::MixtureTransport mt;\n\treturn mt.getMixtureDiffusionCoeff(Temperature(),pre,*this);\n}\n\n// Writes the mixture to a binary data stream.\nvoid Mixture::Serialize(std::ostream &out) const\n{\n\n    /*unsigned int size = m_data.size();\n\n    boost::archive::text_oarchive oa(out);\n    oa << size << m_data;*/\n\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Output the data vector size.\n        unsigned int sz = m_data.size();\n        out.write((char*)&sz, sizeof(sz));\n\n        // Output all elements in the data vector.\n        fvector::const_iterator i;\n        for (i=m_data.begin(); i!=m_data.end(); i++) {\n            out.write((char*)&(*i), sizeof(*i));\n        }\n\n        // Write the viscosity model\n        sz = m_vmodel;\n        out.write((char*)&sz, sizeof(sz));\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sprog, Mixture::Serialize).\");\n    }\n}\n\n// Reads the mixture data from a binary data stream.\nvoid Mixture::Deserialize(std::istream &in)\n{\n\n    /*unsigned int size = m_data.size();\n\n    boost::archive::text_iarchive oa(in);\n    oa >> size >> m_data;*/\n\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        switch (version) {\n            case 0:\n                // Read the data vector size.\n                unsigned int sz;\n                in.read(reinterpret_cast<char*>(&sz), sizeof(sz));\n\n                // Fill the data vector.\n                double val;\n                m_data.reserve(sz);\n                for (unsigned int i=0; i<sz; i++) {\n                    in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                    m_data[i]=val;\n                }\n\n                // The mixture has no species associated it with right now.\n                m_species = NULL;\n\n                // Read the viscosity model\n                in.read(reinterpret_cast<char*>(&sz), sizeof(sz));\n                m_vmodel = (Sprog::ViscosityModel)sz;\n\n                break;\n            default:\n                throw runtime_error(\"Mixture serialized version number \"\n                                    \"is invalid (Sprog, Mixture::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready (Sprog, Mixture::Deserialize).\");\n    }\n}\n", "meta": {"hexsha": "c15ef304cb96386c5b0546752d06712d9c29533c", "size": 25339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sprogc/source/gpc_mixture.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sprogc/source/gpc_mixture.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sprogc/source/gpc_mixture.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 27.5423913043, "max_line_length": 166, "alphanum_fraction": 0.6178223292, "num_tokens": 7206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.03308597493257518, "lm_q1q2_score": 0.008696378442499385}}
{"text": "//Copyright (c) 2015 Zachary Kann\n//\n//Permission is hereby granted, free of charge, to any person obtaining a copy\n//of this software and associated documentation files (the \"Software\"), to deal\n//in the Software without restriction, including without limitation the rights\n//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//copies of the Software, and to permit persons to whom the Software is\n//furnished to do so, subject to the following conditions:\n//\n//The above copyright notice and this permission notice shall be included in all\n//copies or substantial portions of the Software.\n//\n//THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//SOFTWARE.\n\n// ---\n// Author: Zachary Kann\n\n// A set of functions for calculation of electric field / frequency maps\n// as outlined in the papers of Skinner et al. See, for example, S.M. Gruenbaum,\n// et al. J. Chem. Theory Comput. 2013 9 (7), 3109. These maps are necessary\n// for calculation of vibrational spectra using the methodology  outline in the\n// aforementioned papers.\n\n// Abbreviations:\n//   FTIR = fourier-transform infrared\n//   SFG = sum-frequency generation\n\n#include <armadillo>\n\n#ifndef _Z_MAP_HPP_\n#define _Z_MAP_HPP_\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.\nextern double SwitchFunction(const double z, const double u_z,\n                             const double dipPos, const double zcenter,\n                             const double zboxL, const double rswitch,\n                             const double rswitch2, const double rswitch3);\n\n// Electric field / frequency map for three-site water models (e.g., SPC/E)\r\nextern void ThreeSiteMap(const double eh, const arma::rowvec& u,\n                         double& omega01, double& chi01, arma::rowvec& mu01,\n                         double& muprime, arma::rowvec& alphaDiag,\n                         arma::rowvec& alphaOffDiag, const bool doOH);\n\n// Electric field / frequency map for four-site water models (e.g., TIP4P\n// and E3B) as needed for Raman or FTIR spectra calculations.\r\nextern void FourSiteMap(const double eh, const arma::rowvec& u, double& omega01,\n                        double& chi01, arma::rowvec& mu01, double& muprime,\n                        arma::rowvec& alphaDiag, arma::rowvec& alphaOffDiag,\n                        const bool doOH);\n\n// Electric field / frequency map for four-site water models (e.g., TIP4P\n// and E3B) as needed for FTIR (not Raman) spectra calculations.\nextern void FourSiteMapIR(const double eh, const arma::rowvec& u,\n                           double& omega01, double& chi01, arma::rowvec& mu01,\n                           double& muprime, const bool doOH);\n\n// Electric field / frequency map for four-site water models (e.g., TIP4P\n// and E3B) as needed for 2DIR spectra calculations.\nextern void FourSiteMap2DIR(const double eh, double& omega01, double& omega12,\n                             double& chi01, double& chi12, double& mu01,\n                             double& mu12, double& muprime,\n                             const bool doOH);\n\n// Electric field / frequency map for four-site water models (e.g., TIP4P\n// and E3B) as needed for SFG spectra calculations.\r\nextern void FourSiteMapSFG(const double eh, arma::rowvec u,\n                            const double switcher, double& omega01,\n                            double& mu01, double& alpha, const double avgFreq);\n\n// Calculates the intramolecular coupling between OH groups for inclusion\n// in the system Hamiltonian needed for coupled spectra calculations\r\nextern double IntraCouple(const double eh1, const double eh2,\n                          const double omega011, const double omega012,\n                          const arma::rowvec& chi01, const bool doOH);\n\n// Calculates the intermolecular coupling between OH groups for inclusion\n// in the system Hamiltonian needed for coupled spectra calculations\r\nextern 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// TODO(Zak): update to use Hist and Hist.print()\nextern void PrintSpectra(const arma::cx_rowvec& spectra,\n                         const std::string& filename, const int corr,\n                         const int nzeros, const double deltaT,\n                         const double avgFreq);\n\n#endif\n", "meta": {"hexsha": "5327bd508155f42a21d8a6ab150d833f677a4fbb", "size": 5063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/z_map.hpp", "max_stars_repo_name": "thekannman/z_terahertz", "max_stars_repo_head_hexsha": "3fdf2d42c1c7fb58757074527b43e0a33a059c22", "max_stars_repo_licenses": ["MIT"], "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/z_map.hpp", "max_issues_repo_name": "thekannman/z_terahertz", "max_issues_repo_head_hexsha": "3fdf2d42c1c7fb58757074527b43e0a33a059c22", "max_issues_repo_licenses": ["MIT"], "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_map.hpp", "max_forks_repo_name": "thekannman/z_terahertz", "max_forks_repo_head_hexsha": "3fdf2d42c1c7fb58757074527b43e0a33a059c22", "max_forks_repo_licenses": ["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.63, "max_line_length": 80, "alphanum_fraction": 0.6669958523, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.02002343997366392, "lm_q1q2_score": 0.008689801517012862}}
{"text": "#include <iomanip>\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/iostreams/filtering_stream.hpp>\r\n#include <boost/iostreams/filter/gzip.hpp>\r\n#include \"parsing_error.hpp\"\r\n#include \"ligand.hpp\"\r\n\r\nusing boost::filesystem::ifstream;\r\nusing boost::filesystem::ofstream;\r\n\r\nligand::ligand(boost::filesystem::ifstream& ifs) : num_active_torsions(0)\r\n{\r\n\t// Initialize necessary variables for constructing a ligand.\r\n\tlines.reserve(200); // A ligand typically consists of <= 200 lines.\r\n\tframes.reserve(30); // A ligand typically consists of <= 30 frames.\r\n\tframes.push_back(frame(0, 0, 1, 0, 0, 0)); // ROOT is also treated as a frame. The parent and rotorX of ROOT frame are dummy.\r\n\theavy_atoms.reserve(100); // A ligand typically consists of <= 100 heavy atoms.\r\n\thydrogens.reserve(50); // A ligand typically consists of <= 50 hydrogens.\r\n\r\n\t// Initialize helper variables for parsing.\r\n\tvector<size_t> numbers; ///< Atom serial numbers.\r\n\tnumbers.reserve(100); // A ligand typically consists of <= 100 heavy atoms.\r\n\tvector<vector<size_t>> bonds; ///< Covalent bonds.\r\n\tbonds.reserve(100); // A ligand typically consists of <= 100 heavy atoms.\r\n\tsize_t current = 0; // Index of current frame, initialized to ROOT frame.\r\n\tframe* f = &frames.front(); // Pointer to the current frame.\r\n\tf->rotorYidx = 0; // Assume the rotorY of ROOT frame is the first atom.\r\n\tsize_t num_lines = 0; // Used to track line number for reporting parsing errors, if any.\r\n\tstring line;\r\n\tline.reserve(79); // According to PDBQT specification, the last item AutoDock atom type locates at 1-based [78, 79].\r\n\r\n\t// Parse ROOT, ATOM/HETATM, ENDROOT, BRANCH, ENDBRANCH, TORSDOF.\r\n\twhile (getline(ifs, line))\r\n\t{\r\n\t\t++num_lines;\r\n\t\tif (starts_with(line, \"ATOM\") || starts_with(line, \"HETATM\"))\r\n\t\t{\r\n\t\t\t// Whenever an ATOM/HETATM line shows up, the current frame must be the last one.\r\n\t\t\tBOOST_ASSERT(current == frames.size() - 1);\r\n\t\t\tBOOST_ASSERT(f == &frames.back());\r\n\r\n\t\t\t// This line will be dumped to the output ligand file.\r\n\t\t\tlines.push_back(line);\r\n\r\n\t\t\t// Parse and validate AutoDock4 atom type.\r\n\t\t\tconst string ad_type_string = line.substr(77, isspace(line[78]) ? 1 : 2);\r\n\t\t\tconst size_t ad = parse_ad_type_string(ad_type_string);\r\n\t\t\tif (ad == AD_TYPE_SIZE) throw parsing_error(num_lines, \"Atom type \" + ad_type_string + \" is not supported by idock.\");\r\n\r\n\t\t\t// Parse the Cartesian coordinate.\r\n\t\t\tstring name = line.substr(12, 4);\r\n\t\t\tboost::algorithm::trim(name);\r\n\t\t\tatom a(static_cast<string&&>(name), vec3(right_cast<fl>(line, 31, 38), right_cast<fl>(line, 39, 46), right_cast<fl>(line, 47, 54)), ad);\r\n\r\n\t\t\tif (a.is_hydrogen()) // Current atom is a hydrogen.\r\n\t\t\t{\r\n\t\t\t\t// For a polar hydrogen, the bonded hetero atom must be a hydrogen bond donor.\r\n\t\t\t\tif (ad == AD_TYPE_HD)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t i = heavy_atoms.size(); i > f->habegin;)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tatom& b = heavy_atoms[--i];\r\n\t\t\t\t\t\tif (!b.is_hetero()) continue; // Only a hetero atom can be a hydrogen bond donor.\r\n\t\t\t\t\t\tif (a.is_neighbor(b))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tb.donorize();\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\r\n\t\t\t\t// Save the hydrogen.\r\n\t\t\t\thydrogens.push_back(a);\r\n\t\t\t}\r\n\t\t\telse // Current atom is a heavy atom.\r\n\t\t\t{\r\n\t\t\t\t// Find bonds between the current atom and the other atoms of the same frame.\r\n\t\t\t\tBOOST_ASSERT(bonds.size() == heavy_atoms.size());\r\n\t\t\t\tbonds.push_back(vector<size_t>());\r\n\t\t\t\tbonds.back().reserve(4); // An atom typically consists of <= 4 bonds.\r\n\t\t\t\tfor (size_t i = heavy_atoms.size(); i > f->habegin;)\r\n\t\t\t\t{\r\n\t\t\t\t\tatom& b = heavy_atoms[--i];\r\n\t\t\t\t\tif (a.is_neighbor(b))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbonds[heavy_atoms.size()].push_back(i);\r\n\t\t\t\t\t\tbonds[i].push_back(heavy_atoms.size());\r\n\r\n\t\t\t\t\t\t// If carbon atom b is bonded to hetero atom a, b is no longer a hydrophobic atom.\r\n\t\t\t\t\t\tif (a.is_hetero() && !b.is_hetero())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tb.dehydrophobicize();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t// If carbon atom a is bonded to hetero atom b, a is no longer a hydrophobic atom.\r\n\t\t\t\t\t\telse if (!a.is_hetero() && b.is_hetero())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ta.dehydrophobicize();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Set rotorYidx if the serial number of current atom is rotorYsrn.\r\n\t\t\t\tnumbers.push_back(right_cast<size_t>(line, 7, 11));\r\n\t\t\t\tif (current && (numbers.back() == f->rotorYsrn)) // current > 0, i.e. BRANCH frame.\r\n\t\t\t\t{\r\n\t\t\t\t\tf->rotorYidx = heavy_atoms.size();\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Save the heavy atom.\r\n\t\t\t\theavy_atoms.push_back(a);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (starts_with(line, \"BRANCH\"))\r\n\t\t{\r\n\t\t\t// This line will be dumped to the output ligand file.\r\n\t\t\tlines.push_back(line);\r\n\r\n\t\t\t// Parse \"BRANCH   X   Y\". X and Y are right-justified and 4 characters wide.\r\n\t\t\tconst size_t rotorXsrn = right_cast<size_t>(line,  7, 10);\r\n\t\t\tconst size_t rotorYsrn = right_cast<size_t>(line, 11, 14);\r\n\r\n\t\t\t// Find the corresponding heavy atom with x as its atom serial number in the current frame.\r\n\t\t\tfor (size_t i = f->habegin; true; ++i)\r\n\t\t\t{\r\n\t\t\t\tif (numbers[i] == rotorXsrn)\r\n\t\t\t\t{\r\n\t\t\t\t\t// Insert a new frame whose parent is the current frame.\r\n\t\t\t\t\tframes.push_back(frame(current, rotorXsrn, rotorYsrn, i, heavy_atoms.size(), hydrogens.size()));\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// Now the current frame is the newly inserted BRANCH frame.\r\n\t\t\tcurrent = frames.size() - 1;\r\n\r\n\t\t\t// Update the pointer to the current frame.\r\n\t\t\tf = &frames[current];\r\n\r\n\t\t\t// The ending index of atoms of previous frame is the starting index of atoms of current frame.\r\n\t\t\tframes[current - 1].haend = f->habegin;\r\n\t\t\tframes[current - 1].hyend = f->hybegin;\r\n\t\t}\r\n\t\telse if (starts_with(line, \"ENDBRANCH\"))\r\n\t\t{\r\n\t\t\t// This line will be dumped to the output ligand file.\r\n\t\t\tlines.push_back(line);\r\n\r\n\t\t\t// A frame may be empty, e.g. \"BRANCH   4   9\" is immediately followed by \"ENDBRANCH   4   9\".\r\n\t\t\t// This emptiness is likely to be caused by invalid input structure, especially when all the atoms are located in the same plane.\r\n\t\t\tif (f->habegin == heavy_atoms.size()) throw parsing_error(num_lines, \"An empty BRANCH has been detected, indicating the input ligand structure is probably invalid.\");\r\n\r\n\t\t\t// If the current frame consists of rotor Y and a few hydrogens only, e.g. -OH and -NH2,\r\n\t\t\t// the torsion of this frame will have no effect on scoring and is thus redundant.\r\n\t\t\tif ((current == frames.size() - 1) && (f->habegin + 1 == heavy_atoms.size()))\r\n\t\t\t{\r\n\t\t\t\tf->active = false;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t++num_active_torsions;\r\n\t\t\t}\r\n\r\n\t\t\t// Set up bonds between rotorX and rotorY.\r\n\t\t\tbonds[f->rotorYidx].push_back(f->rotorXidx);\r\n\t\t\tbonds[f->rotorXidx].push_back(f->rotorYidx);\r\n\r\n\t\t\t// Dehydrophobicize rotorX and rotorY if necessary.\r\n\t\t\tatom& rotorY = heavy_atoms[f->rotorYidx];\r\n\t\t\tatom& rotorX = heavy_atoms[f->rotorXidx];\r\n\t\t\tif ((rotorY.is_hetero()) && (!rotorX.is_hetero())) rotorX.dehydrophobicize();\r\n\t\t\tif ((rotorX.is_hetero()) && (!rotorY.is_hetero())) rotorY.dehydrophobicize();\r\n\r\n\t\t\t// Calculate parent_rotorY_to_current_rotorY and parent_rotorX_to_current_rotorY.\r\n\t\t\tconst frame& p = frames[f->parent];\r\n\t\t\tf->parent_rotorY_to_current_rotorY =  rotorY.coordinate - heavy_atoms[p.rotorYidx].coordinate;\r\n\t\t\tf->parent_rotorX_to_current_rotorY = (rotorY.coordinate - rotorX.coordinate).normalize();\r\n\r\n\t\t\t// Now the parent of the following frame is the parent of current frame.\r\n\t\t\tcurrent = f->parent;\r\n\r\n\t\t\t// Update the pointer to the current frame.\r\n\t\t\tf = &frames[current];\r\n\t\t}\r\n\t\telse if (starts_with(line, \"ROOT\") || starts_with(line, \"ENDROOT\") || starts_with(line, \"TORSDOF\"))\r\n\t\t{\r\n\t\t\t// This line will be dumped to the output ligand file.\r\n\t\t\tlines.push_back(line);\r\n\t\t\tif (starts_with(line, \"TORSDOF\")) break;\r\n\t\t}\r\n\t}\r\n\tBOOST_ASSERT(lines.size() <= num_lines); // Some lines like \"REMARK\", \"WARNING\", \"TER\" will not be dumped to the output ligand file.\r\n\tBOOST_ASSERT(current == 0); // current should remain its original value if \"BRANCH\" and \"ENDBRANCH\" properly match each other.\r\n\tBOOST_ASSERT(f == &frames.front()); // The frame pointer should remain its original value if \"BRANCH\" and \"ENDBRANCH\" properly match each other.\r\n\r\n\t// Determine num_heavy_atoms and num_hydrogens.\r\n\tnum_heavy_atoms = heavy_atoms.size();\r\n\tnum_hydrogens = hydrogens.size();\r\n\tframes.back().haend = num_heavy_atoms;\r\n\tframes.back().hyend = num_hydrogens;\r\n\r\n\t// Determine num_frames, num_torsions, flexibility_penalty_factor.\r\n\tnum_frames = frames.size();\r\n\tBOOST_ASSERT(num_frames >= 1);\r\n\tnum_torsions = num_frames - 1;\r\n\tBOOST_ASSERT(num_torsions + 1 == num_frames);\r\n\tBOOST_ASSERT(num_torsions >= num_active_torsions);\r\n\tBOOST_ASSERT(num_heavy_atoms + num_hydrogens + (num_torsions << 1) + 3 == lines.size()); // ATOM/HETATM lines + BRANCH/ENDBRANCH lines + ROOT/ENDROOT/TORSDOF lines == lines.size()\r\n\tflexibility_penalty_factor = 1 / (1 + 0.05846 * (num_active_torsions + 0.5 * (num_torsions - num_active_torsions)));\r\n\tBOOST_ASSERT(flexibility_penalty_factor <= 1);\r\n\r\n\t// Update heavy_atoms[].coordinate and hydrogens[].coordinate relative to frame origin.\r\n\tfor (size_t k = 0; k < num_frames; ++k)\r\n\t{\r\n\t\tconst frame& f = frames[k];\r\n\t\tconst vec3 origin = heavy_atoms[f.rotorYidx].coordinate;\r\n\t\tfor (size_t i = f.habegin; i < f.haend; ++i)\r\n\t\t{\r\n\t\t\theavy_atoms[i].coordinate -= origin;\r\n\t\t}\r\n\t\tfor (size_t i = f.hybegin; i < f.hyend; ++i)\r\n\t\t{\r\n\t\t\thydrogens[i].coordinate -= origin;\r\n\t\t}\r\n\t}\r\n\r\n\t// Find intra-ligand interacting pairs that are not 1-4.\r\n\tinteracting_pairs.reserve(num_heavy_atoms * num_heavy_atoms);\r\n\tvector<size_t> neighbors;\r\n\tneighbors.reserve(10); // An atom typically consists of <= 10 neighbors.\r\n\tfor (size_t k1 = 0; k1 < num_frames; ++k1)\r\n\t{\r\n\t\tconst frame& f1 = frames[k1];\r\n\t\tfor (size_t i = f1.habegin; i < f1.haend; ++i)\r\n\t\t{\r\n\t\t\t// Find neighbor atoms within 3 consecutive covalent bonds.\r\n\t\t\tconst vector<size_t>& i0_bonds = bonds[i];\r\n\t\t\tconst size_t num_i0_bonds = i0_bonds.size();\r\n\t\t\tfor (size_t i0 = 0; i0 < num_i0_bonds; ++i0)\r\n\t\t\t{\r\n\t\t\t\tconst size_t b1 = i0_bonds[i0];\r\n\t\t\t\tif (find(neighbors.begin(), neighbors.end(), b1) == neighbors.end())\r\n\t\t\t\t{\r\n\t\t\t\t\tneighbors.push_back(b1);\r\n\t\t\t\t}\r\n\t\t\t\tconst vector<size_t>& i1_bonds = bonds[b1];\r\n\t\t\t\tconst size_t num_i1_bonds = i1_bonds.size();\r\n\t\t\t\tfor (size_t i1 = 0; i1 < num_i1_bonds; ++i1)\r\n\t\t\t\t{\r\n\t\t\t\t\tconst size_t b2 = i1_bonds[i1];\r\n\t\t\t\t\tif (find(neighbors.begin(), neighbors.end(), b2) == neighbors.end())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tneighbors.push_back(b2);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconst vector<size_t>& i2_bonds = bonds[b2];\r\n\t\t\t\t\tconst size_t num_i2_bonds = i2_bonds.size();\r\n\t\t\t\t\tfor (size_t i2 = 0; i2 < num_i2_bonds; ++i2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tconst size_t b3 = i2_bonds[i2];\r\n\t\t\t\t\t\tif (find(neighbors.begin(), neighbors.end(), b3) == neighbors.end())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tneighbors.push_back(b3);\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\r\n\t\t\t// Determine if interacting pairs can be possibly formed.\r\n\t\t\tfor (size_t k2 = k1 + 1; k2 < num_frames; ++k2)\r\n\t\t\t{\r\n\t\t\t\tconst frame& f2 = frames[k2];\r\n\t\t\t\tfor (size_t j = f2.habegin; j < f2.haend; ++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (((k1 == f2.parent) && ((j == f2.rotorYidx) || (i == f2.rotorXidx))) || (find(neighbors.begin(), neighbors.end(), j) != neighbors.end())) continue;\r\n\t\t\t\t\tconst size_t type_pair_index = triangular_matrix_permissive_index(heavy_atoms[i].xs, heavy_atoms[j].xs);\r\n\t\t\t\t\tinteracting_pairs.push_back(interacting_pair(i, j, type_pair_index));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// Clear the current neighbor set for the next atom.\r\n\t\t\tneighbors.clear();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvector<size_t> ligand::get_atom_types() const\r\n{\r\n\tvector<size_t> atom_types;\r\n\tatom_types.reserve(10); // A ligand typically consists of <= 10 XScore atom types.\r\n\tfor (size_t i = 0; i < num_heavy_atoms; ++i)\r\n\t{\r\n\t\tconst size_t t = heavy_atoms[i].xs;\r\n\t\tif (find(atom_types.begin(), atom_types.end(), t) == atom_types.end()) atom_types.push_back(t);\r\n\t}\r\n\treturn atom_types;\r\n}\r\n\r\nbool ligand::evaluate(const conformation& conf, const scoring_function& sf, const box& b, const vector<array3d<fl>>& grid_maps, const fl e_upper_bound, fl& e, fl& f, change& g) const\r\n{\r\n\tif (!b.within(conf.position))\r\n\t\treturn false;\r\n\r\n\t// Initialize frame-wide conformational variables.\r\n\tvector<vec3> origins; ///< Origin coordinate, which is rotorY.\r\n\tvector<vec3> axes; ///< Vector pointing from rotor Y to rotor X.\r\n\tvector<qtn4> orientations_q; ///< Orientation in the form of quaternion.\r\n\tvector<mat3> orientations_m; ///< Orientation in the form of 3x3 matrix.\r\n\tvector<vec3> forces; ///< Aggregated derivatives of heavy atoms.\r\n\tvector<vec3> torques; /// Torque of the force.\r\n\torigins.resize(num_frames);\r\n\taxes.resize(num_frames);\r\n\torientations_q.resize(num_frames);\r\n\torientations_m.resize(num_frames);\r\n\tforces.resize(num_frames, zero3); // Initialize forces to zero3 for subsequent aggregation.\r\n\ttorques.resize(num_frames, zero3); // Initialize torques to zero3 for subsequent aggregation.\r\n\r\n\t// Initialize atom-wide conformational variables.\r\n\tvector<vec3> coordinates; ///< Heavy atom coordinates.\r\n\tvector<vec3> derivatives; ///< Heavy atom derivatives.\r\n\tcoordinates.resize(num_heavy_atoms);\r\n\tderivatives.resize(num_heavy_atoms);\r\n\r\n\t// Apply position and orientation to ROOT frame.\r\n\tconst frame& root = frames.front();\r\n\torigins.front() = conf.position;\r\n\torientations_q.front() = conf.orientation;\r\n\torientations_m.front() = conf.orientation.to_mat3();\r\n\tfor (size_t i = root.habegin; i < root.haend; ++i)\r\n\t{\r\n\t\tcoordinates[i] = origins.front() + orientations_m.front() * heavy_atoms[i].coordinate;\r\n\t\tif (!b.within(coordinates[i]))\r\n\t\t\treturn false;\r\n\t}\r\n\r\n\t// Apply torsions to BRANCH frames.\r\n\tfor (size_t k = 1, t = 0; k < num_frames; ++k)\r\n\t{\r\n\t\tconst frame& f = frames[k];\r\n\r\n\t\t// Update origin.\r\n\t\torigins[k] = origins[f.parent] + orientations_m[f.parent] * f.parent_rotorY_to_current_rotorY;\r\n\t\tif (!b.within(origins[k]))\r\n\t\t\treturn false;\r\n\r\n\t\t// If the current BRANCH frame does not have an active torsion, skip it.\r\n\t\tif (!f.active)\r\n\t\t{\r\n\t\t\tBOOST_ASSERT(f.habegin + 1 == f.haend);\r\n\t\t\tBOOST_ASSERT(f.habegin == f.rotorYidx);\r\n\t\t\tcoordinates[f.rotorYidx] = origins[k];\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// Update orientation.\r\n\t\tBOOST_ASSERT(f.parent_rotorX_to_current_rotorY.normalized());\r\n\t\taxes[k] = orientations_m[f.parent] * f.parent_rotorX_to_current_rotorY;\r\n\t\tBOOST_ASSERT(axes[k].normalized());\r\n\t\torientations_q[k] = qtn4(axes[k], conf.torsions[t++]) * orientations_q[f.parent];\r\n\t\tBOOST_ASSERT(orientations_q[k].is_normalized());\r\n\t\torientations_m[k] = orientations_q[k].to_mat3();\r\n\r\n\t\t// Update coordinates.\r\n\t\tfor (size_t i = f.habegin; i < f.haend; ++i)\r\n\t\t{\r\n\t\t\tcoordinates[i] = origins[k] + orientations_m[k] * heavy_atoms[i].coordinate;\r\n\t\t\tif (!b.within(coordinates[i]))\r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t// Check steric clash between atoms of different frames except for (rotorX, rotorY) pair.\r\n/*\tfor (size_t k1 = num_frames - 1; k1 > 0; --k1)\r\n\t{\r\n\t\tconst frame& f1 = frames[k1];\r\n\t\tfor (size_t i1 = f1.habegin; i1 < f1.haend; ++i1)\r\n\t\t{\r\n\t\t\tfor (size_t k2 = 0; k2 < k1; ++k2)\r\n\t\t\t{\r\n\t\t\t\tconst frame& f2 = frames[k2];\r\n\t\t\t\tfor (size_t i2 = f2.habegin; i2 < f2.haend; ++i2)\r\n\t\t\t\t{\r\n\t\t\t\t\tif ((distance_sqr(coordinates[i1], coordinates[i2]) < sqr(heavy_atoms[i1].covalent_radius() + heavy_atoms[i2].covalent_radius())) && (!((k2 == f1.parent) && (i1 == f1.rotorYidx) && (i2 == f1.rotorXidx))))\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}*/\r\n\r\n\te = 0;\r\n\tfor (size_t i = 0; i < num_heavy_atoms; ++i)\r\n\t{\r\n\t\t// Retrieve the grid map in need.\r\n\t\tconst array3d<fl>& grid_map = grid_maps[heavy_atoms[i].xs];\r\n\t\tBOOST_ASSERT(grid_map.initialized());\r\n\r\n\t\t// Find the index and fraction of the current coordinates.\r\n\t\tconst array<size_t, 3> index = b.grid_index(coordinates[i]);\r\n\r\n\t\t// Assert the validity of index.\r\n\t\tBOOST_ASSERT(index[0] < b.num_grids[0]);\r\n\t\tBOOST_ASSERT(index[1] < b.num_grids[1]);\r\n\t\tBOOST_ASSERT(index[2] < b.num_grids[2]);\r\n\r\n\t\t// (x0, y0, z0) is the beginning corner of the partition.\r\n\t\tconst size_t x0 = index[0];\r\n\t\tconst size_t y0 = index[1];\r\n\t\tconst size_t z0 = index[2];\r\n\t\tconst fl e000 = grid_map(x0, y0, z0);\r\n\r\n\t\t// The derivative of probe atoms can be precalculated at the cost of massive memory storage.\r\n\t\tconst fl e100 = grid_map(x0 + 1, y0,     z0    );\r\n\t\tconst fl e010 = grid_map(x0,     y0 + 1, z0    );\r\n\t\tconst fl e001 = grid_map(x0,     y0,     z0 + 1);\r\n\t\tderivatives[i][0] = (e100 - e000) * b.grid_granularity_inverse;\r\n\t\tderivatives[i][1] = (e010 - e000) * b.grid_granularity_inverse;\r\n\t\tderivatives[i][2] = (e001 - e000) * b.grid_granularity_inverse;\r\n\r\n\t\te += e000; // Aggregate the energy.\r\n\t}\r\n\r\n\t// Save inter-molecular free energy into f.\r\n\tf = e;\r\n\r\n\t// Calculate intra-ligand free energy.\r\n\tconst size_t num_interacting_pairs = interacting_pairs.size();\r\n\tfor (size_t i = 0; i < num_interacting_pairs; ++i)\r\n\t{\r\n\t\tconst interacting_pair& p = interacting_pairs[i];\r\n\t\tconst vec3 r = coordinates[p.i2] - coordinates[p.i1];\r\n\t\tconst fl r2 = r.norm_sqr();\r\n\t\tif (r2 < scoring_function::Cutoff_Sqr)\r\n\t\t{\r\n\t\t\tconst scoring_function_element element = sf.evaluate(p.type_pair_index, r2);\r\n\t\t\te += element.e;\r\n\t\t\tconst vec3 derivative = element.dor * r;\r\n\t\t\tderivatives[p.i1] -= derivative;\r\n\t\t\tderivatives[p.i2] += derivative;\r\n\t\t}\r\n\t}\r\n\r\n\t// If the free energy is no better than the upper bound, refuse this conformation.\r\n\tif (e >= e_upper_bound) return false;\r\n\r\n\t// Calculate and aggregate the force and torque of BRANCH frames to their parent frame.\r\n\tfor (size_t k = num_frames - 1, t = num_active_torsions; k > 0; --k)\r\n\t{\r\n\t\tconst frame&  f = frames[k];\r\n\r\n\t\tfor (size_t i = f.habegin; i < f.haend; ++i)\r\n\t\t{\r\n\t\t\t// The derivatives with respect to the position, orientation, and torsions\r\n\t\t\t// would be the negative total force acting on the ligand,\r\n\t\t\t// the negative total torque, and the negative torque projections, respectively,\r\n\t\t\t// where the projections refer to the torque applied to the branch moved by the torsion,\r\n\t\t\t// projected on its rotation axis.\r\n\t\t\tforces[k]  += derivatives[i];\r\n\t\t\ttorques[k] += cross_product(coordinates[i] - origins[k], derivatives[i]);\r\n\t\t}\r\n\r\n\t\t// Aggregate the force and torque of current frame to its parent frame.\r\n\t\tforces[f.parent]  += forces[k];\r\n\t\ttorques[f.parent] += torques[k] + cross_product(origins[k] - origins[f.parent], forces[k]);\r\n\r\n\t\t// If the current BRANCH frame does not have an active torsion, skip it.\r\n\t\tif (!f.active) continue;\r\n\r\n\t\t// Save the torsion.\r\n\t\tg[6 + (--t)] = torques[k] * axes[k]; // dot product\r\n\t}\r\n\r\n\t// Calculate and aggregate the force and torque of ROOT frame.\r\n\tfor (size_t i = root.habegin; i < root.haend; ++i)\r\n\t{\r\n\t\tforces.front()  += derivatives[i];\r\n\t\ttorques.front() += cross_product(coordinates[i] - origins.front(), derivatives[i]);\r\n\t}\r\n\r\n\t// Save the aggregated force and torque to g.\r\n\tg[0] = forces.front()[0];\r\n\tg[1] = forces.front()[1];\r\n\tg[2] = forces.front()[2];\r\n\tg[3] = torques.front()[0];\r\n\tg[4] = torques.front()[1];\r\n\tg[5] = torques.front()[2];\r\n\r\n\treturn true;\r\n}\r\n\r\nresult ligand::compose_result(const fl e, const fl f, const conformation& conf) const\r\n{\r\n\tvector<vec3> origins(num_frames);\r\n\tvector<qtn4> orientations_q(num_frames);\r\n\tvector<mat3> orientations_m(num_frames);\r\n\tvector<vec3> heavy_atoms(num_heavy_atoms);\r\n\tvector<vec3> hydrogens(num_hydrogens);\r\n\r\n\torigins.front() = conf.position;\r\n\torientations_q.front() = conf.orientation;\r\n\torientations_m.front() = conf.orientation.to_mat3();\r\n\r\n\t// Calculate the coordinates of both heavy atoms and hydrogens of ROOT frame.\r\n\tconst frame& root = frames.front();\r\n\tfor (size_t i = root.habegin; i < root.haend; ++i)\r\n\t{\r\n\t\theavy_atoms[i] = origins.front() + orientations_m.front() * this->heavy_atoms[i].coordinate;\r\n\t}\r\n\tfor (size_t i = root.hybegin; i < root.hyend; ++i)\r\n\t{\r\n\t\thydrogens[i]   = origins.front() + orientations_m.front() * this->hydrogens[i].coordinate;\r\n\t}\r\n\r\n\t// Calculate the coordinates of both heavy atoms and hydrogens of BRANCH frames.\r\n\tfor (size_t k = 1, t = 0; k < num_frames; ++k)\r\n\t{\r\n\t\tconst frame& f = frames[k];\r\n\r\n\t\t// Update origin.\r\n\t\torigins[k] = origins[f.parent] + orientations_m[f.parent] * f.parent_rotorY_to_current_rotorY;\r\n\r\n\t\t// Update orientation.\r\n\t\torientations_q[k] = qtn4(orientations_m[f.parent] * f.parent_rotorX_to_current_rotorY, f.active ? conf.torsions[t++] : 0) * orientations_q[f.parent];\r\n\t\torientations_m[k] = orientations_q[k].to_mat3();\r\n\r\n\t\t// Update coordinates.\r\n\t\tfor (size_t i = f.habegin; i < f.haend; ++i)\r\n\t\t{\r\n\t\t\theavy_atoms[i] = origins[k] + orientations_m[k] * this->heavy_atoms[i].coordinate;\r\n\t\t}\r\n\t\tfor (size_t i = f.hybegin; i < f.hyend; ++i)\r\n\t\t{\r\n\t\t\thydrogens[i]   = origins[k] + orientations_m[k] * this->hydrogens[i].coordinate;\r\n\t\t}\r\n\t}\r\n\r\n\treturn result(conf, e, f, static_cast<vector<vec3>&&>(heavy_atoms), static_cast<vector<vec3>&&>(hydrogens));\r\n}\r\n\r\nvoid ligand::write_model(boost::iostreams::filtering_ostream& ligands_pdbqt_gz, const summary& s, const result& r, const box& b, const vector<array3d<fl>>& grid_maps)\r\n{\r\n\t// Dump binding conformations to the output ligand file.\r\n\tusing namespace std;\r\n\tligands_pdbqt_gz\r\n\t\t<< \"REMARK 921   NORMALIZED FREE ENERGY PREDICTED BY IDOCK:\" << setw(8) << r.f * flexibility_penalty_factor << \" KCAL/MOL\\n\"\r\n\t\t<< \"REMARK 922        TOTAL FREE ENERGY PREDICTED BY IDOCK:\" << setw(8) << r.e       << \" KCAL/MOL\\n\"\r\n\t\t<< \"REMARK 923 INTER-LIGAND FREE ENERGY PREDICTED BY IDOCK:\" << setw(8) << r.f       << \" KCAL/MOL\\n\"\r\n\t\t<< \"REMARK 924 INTRA-LIGAND FREE ENERGY PREDICTED BY IDOCK:\" << setw(8) << (r.e - r.f) << \" KCAL/MOL\\n\"\r\n\t\t<< \"REMARK 927      BINDING AFFINITY PREDICTED BY RF-SCORE:\" << setw(8) << s.rfscore << \" PKD\\n\"\r\n\t;\r\n\tconst size_t num_lines = lines.size();\r\n\tsize_t heavy_atom = 0, hydrogen = 0;\r\n\tfor (size_t j = 0; j < num_lines; ++j)\r\n\t{\r\n\t\tconst string& line = lines[j];\r\n\t\tif (line.size() >= 79) // This line starts with \"ATOM\" or \"HETATM\"\r\n\t\t{\r\n\t\t\tconst bool is_hydrogen = line[77] == 'H' && (line[78] == ' ' || line[78] == 'D');\r\n\t\t\tconst fl   atom_energy = is_hydrogen ? 0 : grid_maps[heavy_atoms[heavy_atom].xs](b.grid_index(r.heavy_atoms[heavy_atom]));\r\n\t\t\tconst vec3& coordinate = is_hydrogen ? r.hydrogens[hydrogen++] : r.heavy_atoms[heavy_atom++];\r\n\t\t\tligands_pdbqt_gz\r\n\t\t\t\t<< line.substr(0, 30)\r\n\t\t\t\t<< setw(8) << coordinate[0]\r\n\t\t\t\t<< setw(8) << coordinate[1]\r\n\t\t\t\t<< setw(8) << coordinate[2]\r\n\t\t\t\t<< line.substr(54, 16)\r\n\t\t\t\t<< setw(6) << atom_energy\r\n\t\t\t\t<< line.substr(76);\r\n\t\t}\r\n\t\telse // This line starts with \"ROOT\", \"ENDROOT\", \"BRANCH\", \"ENDBRANCH\", TORSDOF\", which will not change during docking.\r\n\t\t{\r\n\t\t\tligands_pdbqt_gz << line;\r\n\t\t}\r\n\t\tligands_pdbqt_gz << '\\n';\r\n\t}\r\n\tassert(heavy_atom == r.heavy_atoms.size());\r\n\tassert(hydrogen == r.hydrogens.size());\r\n}\r\n", "meta": {"hexsha": "5f45499523fa9ec18e650ceea966b1a9fe75a9d1", "size": 22519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "idock/src/ligand.cpp", "max_stars_repo_name": "kingdavid72/Calici-Nebular", "max_stars_repo_head_hexsha": "6bd51f63c7de37605dcbfbd3669462a997638ffb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-02-09T00:53:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T13:36:20.000Z", "max_issues_repo_path": "idock/src/ligand.cpp", "max_issues_repo_name": "kingdavid72/Calici-Nebular", "max_issues_repo_head_hexsha": "6bd51f63c7de37605dcbfbd3669462a997638ffb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-06-16T18:07:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-15T23:45:34.000Z", "max_forks_repo_path": "idock/src/ligand.cpp", "max_forks_repo_name": "kingdavid72/Calici-Nebular", "max_forks_repo_head_hexsha": "6bd51f63c7de37605dcbfbd3669462a997638ffb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-04-15T12:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T11:30:46.000Z", "avg_line_length": 39.0954861111, "max_line_length": 210, "alphanum_fraction": 0.6557573605, "num_tokens": 6583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918075, "lm_q2_score": 0.02758528032814983, "lm_q1q2_score": 0.00866317232080724}}
{"text": "#include \"algorithms/synthesis/syrec_synthesis.hpp\"\n\n#include \"core/syrec/expression.hpp\"\n#include \"core/syrec/program.hpp\"\n#include \"core/syrec/variable.hpp\"\n#include \"core/utils/timer.hpp\"\n\n#include <boost/dynamic_bitset.hpp>\n#include <cmath>\n#include <functional>\n#include <memory>\n#include <numeric>\n\nnamespace syrec {\n\n    struct annotater {\n        explicit annotater(circuit& circ, const std::stack<statement::ptr>& stmts):\n            _circ(circ),\n            _stmts(stmts) {}\n\n        // Operator needs this signature to work\n        void operator()(gate& g) const {\n            if (!_stmts.empty()) {\n                _circ.annotate(g, \"lno\", std::to_string(_stmts.top()->line_number));\n            }\n        }\n\n    private:\n        circuit&                          _circ;\n        const std::stack<statement::ptr>& _stmts;\n    };\n\n    // Helper Functions for the synthesis methods\n    standard_syrec_synthesizer::standard_syrec_synthesizer(circuit& circ, const program& prog [[maybe_unused]]):\n        _circ(circ) {\n        free_const_lines_map.insert(std::make_pair(false, std::vector<unsigned>()));\n        free_const_lines_map.insert(std::make_pair(true, std::vector<unsigned>()));\n\n        // root anlegen\n        cct_man.current = add_vertex(cct_man.tree);\n        cct_man.root    = cct_man.current;\n        // Blatt anlegen\n        cct_man.current                                             = add_vertex(cct_man.tree);\n        get(boost::vertex_name, cct_man.tree)[cct_man.current].circ = std::make_shared<circuit>();\n        get(boost::vertex_name, cct_man.tree)[cct_man.current].circ->gate_added.connect(annotater(*get(boost::vertex_name, cct_man.tree)[cct_man.current].circ, _stmts));\n        add_edge(cct_man.root, cct_man.current, cct_man.tree);\n    }\n\n    void standard_syrec_synthesizer::set_main_module(const module::ptr& main_module) {\n        assert(modules.empty());\n        modules.push(main_module);\n    }\n\n    bool standard_syrec_synthesizer::on_module(const module::ptr& main) {\n        for (const auto& stat: main->statements) {\n            if (!full_statement(stat)) {\n                if (!on_statement(stat)) {\n                    return false;\n                }\n            }\n        }\n        return assemble_circuit(cct_man.root);\n    }\n    /// checking the entire statement\n    bool standard_syrec_synthesizer::full_statement(const statement::ptr& statement) {\n        bool okay = false;\n        if (auto* stat = dynamic_cast<assign_statement*>(statement.get())) {\n            okay = full_statement(*stat);\n        } else {\n            return false;\n        }\n\n        return okay;\n    }\n\n    bool standard_syrec_synthesizer::full_statement(const assign_statement& statement) {\n        std::vector<unsigned> d, dd, stat_lhs, comp, ddd;\n        std::vector<unsigned> lines;\n        get_variables(statement.lhs, stat_lhs);\n\n        op_rhs_lhs_expression(statement.rhs, d);\n\n        if (op_vec.empty()) {\n            return false;\n        }\n        flow(statement.rhs, ddd);\n\n        /// Only when the rhs input signals are repeated (since the results are stored in the rhs)\n\n        if (check_repeats()) {\n            flow(statement.rhs, dd);\n\n            if (exp_op_vector.size() == 1) {\n                if (exp_op_vector.at(0) == 1 or exp_op_vector.at(0) == 2) {\n                    /// cancel out the signals\n\n                    exp_op_vector.clear();\n                    assign_op_vector.clear();\n                    exp_lhs_vector.clear();\n                    exp_rhs_vector.clear();\n                    op_vec.clear();\n                } else {\n                    if (statement.op == 1) {\n                        expression_single_op(1, exp_lhs_vector.at(0), stat_lhs);\n                        expression_single_op(1, exp_rhs_vector.at(0), stat_lhs);\n                        exp_op_vector.clear();\n                        assign_op_vector.clear();\n                        exp_lhs_vector.clear();\n                        exp_rhs_vector.clear();\n                        op_vec.clear();\n                    } else {\n                        expression_single_op(statement.op, exp_lhs_vector.at(0), stat_lhs);\n                        expression_single_op(exp_op_vector.at(0), exp_rhs_vector.at(0), stat_lhs);\n                        exp_op_vector.clear();\n                        assign_op_vector.clear();\n                        exp_lhs_vector.clear();\n                        exp_rhs_vector.clear();\n                        op_vec.clear();\n                    }\n                }\n\n            } else {\n                if (exp_lhs_vector.at(0) == exp_rhs_vector.at(0)) {\n                    if (exp_op_vector.at(0) == 1 or exp_op_vector.at(0) == 2) {\n                        /// cancel out the signals\n                    } else if (exp_op_vector.at(0) != 1 or exp_op_vector.at(0) != 2) {\n                        expression_single_op(statement.op, exp_lhs_vector.at(0), stat_lhs);\n                        expression_single_op(exp_op_vector.at(0), exp_rhs_vector.at(0), stat_lhs);\n                    }\n                } else {\n                    solver(stat_lhs, statement.op, exp_lhs_vector.at(0), exp_op_vector.at(0), exp_rhs_vector.at(0));\n                }\n\n                unsigned              j = 0;\n                unsigned              z;\n                std::vector<unsigned> stat_assign_op;\n                if ((exp_op_vector.size() % 2) == 0) {\n                    z = ((exp_op_vector.size()) / (2));\n                } else {\n                    z = (((exp_op_vector.size()) - 1) / (2));\n                }\n\n                for (unsigned k = 0; k <= z - 1; k++) {\n                    stat_assign_op.push_back(assign_op_vector.at(k));\n                }\n\n                /// Assignment operations\n\n                std::reverse(stat_assign_op.begin(), stat_assign_op.end());\n\n                /// If reversible assignment is \"-\", the assignment operations must negated appropriately\n\n                if (statement.op == 1) {\n                    for (unsigned int& i: stat_assign_op) {\n                        if (i == 0) {\n                            i = 1;\n                        } else if (i == 1) {\n                            i = 0;\n                        } else {\n                            continue;\n                        }\n                    }\n                }\n\n                for (unsigned i = 1; i <= exp_op_vector.size() - 1; i++) {\n                    /// when both rhs and lhs exist\n                    if ((exp_lhs_vector.at(i) != comp) && (exp_rhs_vector.at(i) != comp)) {\n                        if (exp_lhs_vector.at(i) == exp_rhs_vector.at(i)) {\n                            if (exp_op_vector.at(i) == 1 or exp_op_vector.at(i) == 2) {\n                                /// cancel out the signals\n                                j = j + 1;\n                            } else if (exp_op_vector.at(i) != 1 or exp_op_vector.at(i) != 2) {\n                                if (stat_assign_op.at(j) == 1) {\n                                    expression_single_op(1, exp_lhs_vector.at(i), stat_lhs);\n                                    expression_single_op(1, exp_rhs_vector.at(i), stat_lhs);\n                                    j = j + 1;\n                                } else {\n                                    expression_single_op(stat_assign_op.at(j), exp_lhs_vector.at(i), stat_lhs);\n                                    expression_single_op(exp_op_vector.at(i), exp_rhs_vector.at(i), stat_lhs);\n                                    j = j + 1;\n                                }\n                            }\n                        } else {\n                            solver(stat_lhs, stat_assign_op.at(j), exp_lhs_vector.at(i), exp_op_vector.at(i), exp_rhs_vector.at(i));\n                            j = j + 1;\n                        }\n                    }\n\n                    /// when only rhs exists\n                    else if ((exp_lhs_vector.at(i) == comp) && (exp_rhs_vector.at(i) != comp)) {\n                        exp_evaluate(lines, stat_assign_op.at(j), exp_rhs_vector.at(i), stat_lhs);\n\n                        j = j + 1;\n                    }\n\n                    /// when only lhs exists\n                    else if ((exp_lhs_vector.at(i) != comp) && (exp_rhs_vector.at(i) == comp)) {\n                        exp_evaluate(lines, stat_assign_op.at(j), exp_rhs_vector.at(i), stat_lhs);\n\n                        j = j + 1;\n                    } else if ((exp_lhs_vector.at(i) == comp) && (exp_rhs_vector.at(i) == comp)) {\n                    }\n                }\n                exp_op_vector.clear();\n                assign_op_vector.clear();\n                exp_lhs_vector.clear();\n                exp_rhs_vector.clear();\n                op_vec.clear();\n            }\n        } else {\n            exp_op_vector.clear();\n            assign_op_vector.clear();\n            exp_lhs_vector.clear();\n            exp_rhs_vector.clear();\n            op_vec.clear();\n            return false;\n        }\n\n        exp_op_vector.clear();\n        assign_op_vector.clear();\n        exp_lhs_vector.clear();\n        exp_rhs_vector.clear();\n        op_vec.clear();\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::flow(const expression::ptr& expression, std::vector<unsigned>& v) {\n        if (auto* binary = dynamic_cast<binary_expression*>(expression.get())) {\n            return flow(*binary, v);\n        } else if (auto* var = dynamic_cast<variable_expression*>(expression.get())) {\n            return flow(*var, v);\n        } else {\n            return false;\n        }\n    }\n\n    bool standard_syrec_synthesizer::flow(const variable_expression& expression, std::vector<unsigned>& v) {\n        get_variables(expression.var, v);\n        return true;\n    }\n\n    /// generating LHS and RHS (can be whole expressions as well)\n    bool standard_syrec_synthesizer::flow(const binary_expression& expression, std::vector<unsigned>& v [[maybe_unused]]) {\n        std::vector<unsigned> lhs, rhs, comp;\n        assign_op_vector.push_back(expression.op);\n\n        if (!flow(expression.lhs, lhs) || !flow(expression.rhs, rhs)) {\n            return false;\n        }\n\n        exp_lhs_vector.push_back(lhs);\n        exp_rhs_vector.push_back(rhs);\n        exp_op_vector.push_back(expression.op);\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::solver(const std::vector<unsigned>& stat_lhs, unsigned stat_op, const std::vector<unsigned>& exp_lhs, unsigned exp_op, const std::vector<unsigned>& exp_rhs) {\n        std::vector<unsigned> lines;\n        if (stat_op == exp_op) {\n            if (exp_op == 1) {\n                expression_single_op(1, exp_lhs, stat_lhs);\n                expression_single_op(0, exp_rhs, stat_lhs);\n            } else {\n                expression_single_op(stat_op, exp_lhs, stat_lhs);\n                expression_single_op(stat_op, exp_rhs, stat_lhs);\n            }\n        } else {\n            sub_flag = true;\n            exp_evaluate(lines, exp_op, exp_lhs, exp_rhs);\n            sub_flag = false;\n            exp_evaluate(lines, stat_op, lines, stat_lhs);\n            sub_flag = true;\n            if (exp_op < 3) {\n                expression_op_inverse(exp_op, exp_lhs, exp_rhs);\n            }\n        }\n        sub_flag = false;\n        return true;\n    }\n\n    /// If the input signals are repeated (i.e., rhs input signals are repeated)\n    bool standard_syrec_synthesizer::check_repeats() {\n        std::vector check_lhs_vec(exp_lhs_vector.cbegin(), exp_lhs_vector.cend());\n        std::vector check_rhs_vec(exp_rhs_vector.cbegin(), exp_rhs_vector.cend());\n\n        for (unsigned k = 0; k < check_lhs_vec.size(); k++) {\n            if (check_lhs_vec.at(k).empty()) {\n                check_lhs_vec.erase(check_lhs_vec.begin() + (k));\n            }\n        }\n\n        for (unsigned k = 0; k < check_rhs_vec.size(); k++) {\n            if (check_rhs_vec.at(k).empty()) {\n                check_rhs_vec.erase(check_rhs_vec.begin() + (k));\n            }\n        }\n\n        for (int i = 0; i < int(check_rhs_vec.size()); i++) {\n            for (int j = 0; j < int(check_rhs_vec.size()); j++) {\n                if (j != i) {\n                    if (check_rhs_vec.at(i) == check_rhs_vec.at(j)) {\n                        exp_op_vector.clear();\n                        exp_lhs_vector.clear();\n                        exp_rhs_vector.clear();\n                        return true;\n                    }\n                }\n            }\n        }\n\n        for (auto& i: check_lhs_vec) {\n            for (auto& j: check_rhs_vec) {\n                if (i == j) {\n                    exp_op_vector.clear();\n                    exp_lhs_vector.clear();\n                    exp_rhs_vector.clear();\n                    return true;\n                }\n            }\n        }\n\n        exp_op_vector.clear();\n        exp_lhs_vector.clear();\n        exp_rhs_vector.clear();\n        return false;\n    }\n\n    /// generating LHS and RHS (not whole expressions, just the corresponding variables)\n    bool standard_syrec_synthesizer::op_rhs_lhs_expression(const expression::ptr& expression, std::vector<unsigned>& v) {\n        if (auto* binary = dynamic_cast<binary_expression*>(expression.get())) {\n            return op_rhs_lhs_expression(*binary, v);\n        } else if (auto* var = dynamic_cast<variable_expression*>(expression.get())) {\n            return op_rhs_lhs_expression(*var, v);\n        } else {\n            return false;\n        }\n    }\n\n    bool standard_syrec_synthesizer::op_rhs_lhs_expression(const variable_expression& expression, std::vector<unsigned>& v) {\n        get_variables(expression.var, v);\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::op_rhs_lhs_expression(const binary_expression& expression, std::vector<unsigned>& v) {\n        std::vector<unsigned> lhs, rhs;\n\n        if (!op_rhs_lhs_expression(expression.lhs, lhs) || !op_rhs_lhs_expression(expression.rhs, rhs)) {\n            return false;\n        }\n\n        v = rhs;\n        op_vec.push_back(expression.op);\n        return true;\n    }\n\n    /////////When the input signals are not repeated//////////////////\n    bool standard_syrec_synthesizer::on_statement(const statement::ptr& statement) {\n        _stmts.push(statement);\n        bool okay = false;\n        if (auto* swap_stat = dynamic_cast<swap_statement*>(statement.get())) {\n            okay = on_statement(*swap_stat);\n        } else if (auto* unary_stat = dynamic_cast<unary_statement*>(statement.get())) {\n            okay = on_statement(*unary_stat);\n        } else if (auto* assign_stat = dynamic_cast<assign_statement*>(statement.get())) {\n            okay = on_statement(*assign_stat);\n        } else if (auto* if_stat = dynamic_cast<if_statement*>(statement.get())) {\n            okay = on_statement(*if_stat);\n        } else if (auto* for_stat = dynamic_cast<for_statement*>(statement.get())) {\n            okay = on_statement(*for_stat);\n        } else if (auto* call_stat = dynamic_cast<call_statement*>(statement.get())) {\n            okay = on_statement(*call_stat);\n        } else if (auto* uncall_stat = dynamic_cast<uncall_statement*>(statement.get())) {\n            okay = on_statement(*uncall_stat);\n        } else if (auto* skip_stat = dynamic_cast<skip_statement*>(statement.get())) {\n            okay = on_statement(*skip_stat);\n        } else {\n            return false;\n        }\n\n        _stmts.pop();\n        return okay;\n    }\n\n    bool standard_syrec_synthesizer::on_statement(const swap_statement& statement) {\n        std::vector<unsigned> lhs, rhs;\n\n        get_variables(statement.lhs, lhs);\n        get_variables(statement.rhs, rhs);\n\n        assert(lhs.size() == rhs.size());\n\n        swap(lhs, rhs);\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_statement(const unary_statement& statement) {\n        // load variable\n        std::vector<unsigned> var;\n        get_variables(statement.var, var);\n\n        switch (statement.op) {\n            case unary_statement::invert:\n                bitwise_negation(var);\n                break;\n            case unary_statement::increment:\n                increment(var);\n                break;\n            case unary_statement::decrement:\n                decrement(var);\n                break;\n            default:\n                return false;\n        }\n        return true;\n    }\n\n    /// Function when the assignment statements does not include repeated input signals\n    bool standard_syrec_synthesizer::on_statement(const assign_statement& statement) {\n        std::vector<unsigned> lhs, rhs, d;\n\n        get_variables(statement.lhs, lhs);\n\n        op_rhs_lhs_expression(statement.rhs, d);\n        on_expression(statement.rhs, rhs, lhs, statement.op);\n        op_vec.clear();\n\n        bool status = false;\n\n        switch (statement.op) {\n            case assign_statement::add: {\n                if (!exp_opp.empty() && exp_opp.top() == statement.op) {\n                    status = increase_new(lhs, exp_lhss.top());\n                    status = increase_new(lhs, exp_rhss.top());\n                    exp_opp.pop();\n                    exp_lhss.pop();\n                    exp_rhss.pop();\n                } else {\n                    status = increase_new(lhs, rhs);\n                }\n                while (!exp_opp.empty()) {\n                    expression_op_inverse(exp_opp.top(), exp_lhss.top(), exp_rhss.top());\n                    sub_flag = false;\n                    exp_opp.pop();\n                    exp_lhss.pop();\n                    exp_rhss.pop();\n                }\n            } break;\n\n            case assign_statement::subtract: {\n                if (!exp_opp.empty() && exp_opp.top() == statement.op) {\n                    status = decrease_new(lhs, exp_lhss.top());\n                    status = increase_new(lhs, exp_rhss.top());\n                    exp_opp.pop();\n                    exp_lhss.pop();\n                    exp_rhss.pop();\n                } else {\n                    status = decrease_new(lhs, rhs);\n                }\n                while (!exp_opp.empty()) {\n                    expression_op_inverse(exp_opp.top(), exp_lhss.top(), exp_rhss.top());\n                    sub_flag = false;\n                    exp_opp.pop();\n                    exp_lhss.pop();\n                    exp_rhss.pop();\n                }\n            } break;\n\n            case assign_statement::exor: {\n                if (!exp_opp.empty() && exp_opp.top() == statement.op) {\n                    status = bitwise_cnot(lhs, exp_lhss.top());\n                    status = bitwise_cnot(lhs, exp_rhss.top());\n                    exp_opp.pop();\n                    exp_lhss.pop();\n                    exp_rhss.pop();\n                } else {\n                    status = bitwise_cnot(lhs, rhs);\n                }\n                while (!exp_opp.empty()) {\n                    expression_op_inverse(exp_opp.top(), exp_lhss.top(), exp_rhss.top());\n                    sub_flag = false;\n                    exp_opp.pop();\n                    exp_lhss.pop();\n                    exp_rhss.pop();\n                }\n            } break;\n\n            default:\n                return false;\n        }\n\n        return status;\n    }\n\n    bool standard_syrec_synthesizer::on_statement(const if_statement& statement) {\n        // calculate expression\n        std::vector<unsigned> expression_result, lhs_stat;\n        unsigned              op = 0u;\n        on_expression(statement.condition, expression_result, lhs_stat, op);\n        assert(expression_result.size() == 1u);\n\n        // add new helper line\n        unsigned helper_line = expression_result.front();\n\n        // activate this line\n        add_active_control(helper_line);\n\n        for (const auto& stat: statement.then_statements) {\n            if (!full_statement(stat)) {\n                if (!on_statement(stat)) {\n                    return false;\n                }\n            }\n        }\n\n        // toggle helper line\n        remove_active_control(helper_line);\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(helper_line);\n        add_active_control(helper_line);\n\n        for (const auto& stat: statement.else_statements) {\n            if (!full_statement(stat)) {\n                if (!on_statement(stat)) {\n                    return false;\n                }\n            }\n        }\n\n        // de-active helper line\n        remove_active_control(helper_line);\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(helper_line);\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_statement(const for_statement& statement) {\n        const auto [nfrom, nto] = statement.range;\n\n        const unsigned     from          = nfrom ? nfrom->evaluate(loop_map) : 1u; // default value is 1u\n        const unsigned     to            = nto->evaluate(loop_map);\n        const unsigned     step          = statement.step ? statement.step->evaluate(loop_map) : 1u; // default step is +1\n        const std::string& loop_variable = statement.loop_variable;\n\n        if (from <= to) {\n            for (unsigned i = from; i <= to; i += step) {\n                // adjust loop variable if necessary\n\n                if (!loop_variable.empty()) {\n                    loop_map[loop_variable] = i;\n                }\n\n                for (const auto& stat: statement.statements) {\n                    if (!full_statement(stat)) {\n                        if (!on_statement(stat)) {\n                            return false;\n                        }\n                    }\n                }\n            }\n        }\n\n        else if (from > to) {\n            for (int i = (int)from; i >= (int)to; i -= (int)step) {\n                // adjust loop variable if necessary\n\n                if (!loop_variable.empty()) {\n                    loop_map[loop_variable] = i;\n                }\n\n                for (const auto& stat: statement.statements) {\n                    if (!full_statement(stat)) {\n                        if (!on_statement(stat)) {\n                            return false;\n                        }\n                    }\n                }\n            }\n        }\n        // clear loop variable if necessary\n        if (!loop_variable.empty()) {\n            assert(loop_map.erase(loop_variable) == 1u);\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_statement(const call_statement& statement) {\n        // 1. Adjust the references module's parameters to the call arguments\n        for (unsigned i = 0u; i < statement.parameters.size(); ++i) {\n            const std::string& parameter        = statement.parameters.at(i);\n            const auto&        module_parameter = statement.target->parameters.at(i);\n\n            module_parameter->set_reference(modules.top()->find_parameter_or_variable(parameter));\n        }\n\n        // 2. Create new lines for the module's variables\n        add_variables(_circ, statement.target->variables);\n\n        modules.push(statement.target);\n        for (const auto& stat: statement.target->statements) {\n            if (!full_statement(stat)) {\n                if (!on_statement(stat)) {\n                    return false;\n                }\n            }\n        }\n\n        modules.pop();\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_statement(const uncall_statement& statement) {\n        // 1. Adjust the references module's parameters to the call arguments\n        for (unsigned i = 0u; i < statement.parameters.size(); ++i) {\n            const std::string& parameter        = statement.parameters.at(i);\n            const auto&        module_parameter = statement.target->parameters.at(i);\n\n            module_parameter->set_reference(modules.top()->find_parameter_or_variable(parameter));\n        }\n\n        // 2. Create new lines for the module's variables\n        add_variables(_circ, statement.target->variables);\n\n        modules.push(statement.target);\n\n        const auto statements = statement.target->statements;\n        for (auto it = statements.rbegin(); it != statements.rend(); ++it) {\n            const auto reverse_statement = (*it)->reverse();\n            if (!full_statement(reverse_statement)) {\n                if (!on_statement(reverse_statement)) {\n                    return false;\n                }\n            }\n        }\n\n        modules.pop();\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_statement(const skip_statement& statement [[maybe_unused]]) {\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_expression(const expression::ptr& expression, std::vector<unsigned>& lines, std::vector<unsigned>& lhs_stat, unsigned op) {\n        if (auto* numeric = dynamic_cast<numeric_expression*>(expression.get())) {\n            return on_expression(*numeric, lines);\n        } else if (auto* variable = dynamic_cast<variable_expression*>(expression.get())) {\n            return on_expression(*variable, lines);\n        } else if (auto* binary = dynamic_cast<binary_expression*>(expression.get())) {\n            return on_expression(*binary, lines, lhs_stat, op);\n        } else if (auto* shift = dynamic_cast<shift_expression*>(expression.get())) {\n            return on_expression(*shift, lines, lhs_stat, op);\n        } else {\n            return false;\n        }\n    }\n\n    bool standard_syrec_synthesizer::on_expression(const numeric_expression& expression, std::vector<unsigned>& lines) {\n        get_constant_lines(expression.bitwidth(), expression.value->evaluate(loop_map), lines);\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_expression(const variable_expression& expression, std::vector<unsigned>& lines) {\n        get_variables(expression.var, lines);\n        return true;\n    }\n\n    /// Function when the assignment statements consist of binary expressions and does not include repeated input signals\n\n    bool standard_syrec_synthesizer::on_expression(const binary_expression& expression, std::vector<unsigned>& lines, std::vector<unsigned>& lhs_stat, unsigned op) {\n        std::vector<unsigned> lhs, rhs;\n\n        if (!on_expression(expression.lhs, lhs, lhs_stat, op) || !on_expression(expression.rhs, rhs, lhs_stat, op)) {\n            return false;\n        }\n\n        exp_lhss.push(lhs);\n        exp_rhss.push(rhs);\n        exp_opp.push(expression.op);\n\n        if (exp_opp.size() == op_vec.size()) {\n            if (exp_opp.top() == op) {\n                return true;\n            }\n        }\n\n        switch (expression.op) {\n            case binary_expression::add: // +\n                increase_new(rhs, lhs);\n                lines = rhs;\n                break;\n            case binary_expression::subtract: // -\n                decrease_new_assign(rhs, lhs);\n                lines = rhs;\n                break;\n            case binary_expression::exor: // ^\n                bitwise_cnot(rhs, lhs);   // duplicate lhs\n                lines = rhs;\n                break;\n            case binary_expression::multiply: // *\n                get_constant_lines(expression.bitwidth(), 0u, lines);\n                multiplication(lines, lhs, rhs);\n                break;\n            case binary_expression::divide: // /\n                get_constant_lines(expression.bitwidth(), 0u, lines);\n                division(lines, lhs, rhs);\n                break;\n            case binary_expression::modulo: {\n                get_constant_lines(expression.bitwidth(), 0u, lines);\n                std::vector<unsigned> quot;\n                get_constant_lines(expression.bitwidth(), 0u, quot);\n\n                bitwise_cnot(lines, lhs); // duplicate lhs\n                modulo(quot, lines, rhs);\n            } break;\n            case binary_expression::logical_and: // &&\n                lines.emplace_back(get_constant_line(false));\n                conjunction(lines.at(0), lhs.at(0), rhs.at(0));\n                break;\n            case binary_expression::logical_or: // ||\n                lines.emplace_back(get_constant_line(false));\n                disjunction(lines.at(0), lhs.at(0), rhs.at(0));\n                break;\n            case binary_expression::bitwise_and: // &\n                get_constant_lines(expression.bitwidth(), 0u, lines);\n                bitwise_and(lines, lhs, rhs);\n                break;\n            case binary_expression::bitwise_or: // |\n                get_constant_lines(expression.bitwidth(), 0u, lines);\n                bitwise_or(lines, lhs, rhs);\n                break;\n            case binary_expression::less_than: // <\n                lines.emplace_back(get_constant_line(false));\n                less_than(lines.at(0), lhs, rhs);\n                break;\n            case binary_expression::greater_than: // >\n                lines.emplace_back(get_constant_line(false));\n                greater_than(lines.at(0), lhs, rhs);\n                break;\n            case binary_expression::equals: // =\n                lines.emplace_back(get_constant_line(false));\n                equals(lines.at(0), lhs, rhs);\n                break;\n            case binary_expression::not_equals: // !=\n                lines.emplace_back(get_constant_line(false));\n                not_equals(lines.at(0), lhs, rhs);\n                break;\n            case binary_expression::less_equals: // <=\n                lines.emplace_back(get_constant_line(false));\n                less_equals(lines.at(0), lhs, rhs);\n                break;\n            case binary_expression::greater_equals: // >=\n                lines.emplace_back(get_constant_line(false));\n                greater_equals(lines.at(0), lhs, rhs);\n                break;\n            default:\n                return false;\n        }\n\n        return true;\n    }\n\n    /// This function is used when input signals (rhs) are equal (just to solve statements individually)\n    bool standard_syrec_synthesizer::exp_evaluate(std::vector<unsigned>& lines, unsigned op, const std::vector<unsigned>& lhs, const std::vector<unsigned>& rhs) {\n        switch (op) {\n            case binary_expression::add: // +\n                increase_new(rhs, lhs);\n                lines = rhs;\n                break;\n            case binary_expression::subtract: // -\n                if (sub_flag) {\n                    decrease_new_assign(rhs, lhs);\n                    lines = rhs;\n                } else {\n                    decrease_new(rhs, lhs);\n                    lines = rhs;\n                }\n                break;\n            case binary_expression::exor: // ^\n                bitwise_cnot(rhs, lhs);   // duplicate lhs\n                lines = rhs;\n                break;\n            default:\n                return false;\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::on_expression(const shift_expression& expression, std::vector<unsigned>& lines, std::vector<unsigned>& lhs_stat, unsigned op) {\n        std::vector<unsigned> lhs;\n        if (!on_expression(expression.lhs, lhs, lhs_stat, op)) {\n            return false;\n        }\n\n        unsigned rhs = expression.rhs->evaluate(loop_map);\n\n        switch (expression.op) {\n            case shift_expression::left: // <<\n                get_constant_lines(expression.bitwidth(), 0u, lines);\n                left_shift(lines, lhs, rhs);\n                break;\n            case shift_expression::right: // <<\n                get_constant_lines(expression.bitwidth(), 0u, lines);\n                right_shift(lines, lhs, rhs);\n                break;\n            default:\n                return false;\n        }\n\n        return true;\n    }\n\n    //**********************************************************************\n    //*****                      Unary Operations                      *****\n    //**********************************************************************\n\n    bool standard_syrec_synthesizer::bitwise_negation(const std::vector<unsigned>& dest) {\n        for (unsigned idx: dest) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(idx);\n        }\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::decrement(const std::vector<unsigned>& dest) {\n        for (unsigned int i: dest) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(i);\n            add_active_control(i);\n        }\n\n        for (unsigned int i: dest) {\n            remove_active_control(i);\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::increment(const std::vector<unsigned>& dest) {\n        for (unsigned int i: dest) {\n            add_active_control(i);\n        }\n\n        for (int i = int(dest.size()) - 1; i >= 0; --i) {\n            remove_active_control(dest.at(i));\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(dest.at(i));\n        }\n\n        return true;\n    }\n\n    //**********************************************************************\n    //*****                     Binary Operations                      *****\n    //**********************************************************************\n\n    bool standard_syrec_synthesizer::bitwise_and(const std::vector<unsigned>& dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        bool ok = true;\n        for (unsigned i = 0u; i < dest.size(); ++i) {\n            ok &= conjunction(dest.at(i), src1.at(i), src2.at(i));\n        }\n        return ok;\n    }\n\n    bool standard_syrec_synthesizer::bitwise_cnot(const std::vector<unsigned>& dest, const std::vector<unsigned>& src) {\n        for (unsigned i = 0u; i < src.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src.at(i), dest.at(i));\n        }\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::bitwise_or(const std::vector<unsigned>& dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        bool ok = true;\n        for (unsigned i = 0u; i < dest.size(); ++i) {\n            ok &= disjunction(dest.at(i), src1.at(i), src2.at(i));\n        }\n        return ok;\n    }\n\n    bool standard_syrec_synthesizer::conjunction(unsigned dest, unsigned src1, unsigned src2) {\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(src1, src2, dest);\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::decrease_with_carry(const std::vector<unsigned>& dest, const std::vector<unsigned>& src, unsigned carry) {\n        for (unsigned i = 0u; i < src.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(dest.at(i));\n        }\n\n        increase_with_carry(dest, src, carry);\n\n        for (unsigned i = 0u; i < src.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(dest.at(i));\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::disjunction(unsigned dest, unsigned src1, unsigned src2) {\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src1, dest);\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src2, dest);\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(src1, src2, dest);\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::division(const std::vector<unsigned>& dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        if (!modulo(dest, src1, src2)) return false;\n\n        std::vector<unsigned> sum;\n        std::vector<unsigned> partial;\n\n        for (unsigned i = 1u; i < src1.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(src2.at(i));\n        }\n\n        for (unsigned i = 1u; i < src1.size(); ++i) {\n            add_active_control(src2.at(i));\n        }\n\n        for (int i = int(src1.size()) - 1; i >= 0; --i) {\n            partial.push_back(src2.at(src1.size() - 1u - i));\n            sum.insert(sum.begin(), src1.at(i));\n            add_active_control(dest.at(i));\n            increase_new(sum, partial);\n            remove_active_control(dest.at(i));\n            if (i > 0) {\n                for (unsigned j = (src1.size() - i); j < src1.size(); ++j) {\n                    remove_active_control(src2.at(j));\n                }\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(src2.at(src1.size() - i));\n                for (unsigned j = (src1.size() + 1u - i); j < src1.size(); ++j) {\n                    add_active_control(src2.at(j));\n                }\n            }\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::equals(unsigned dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        for (unsigned i = 0u; i < src1.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src2.at(i), src1.at(i));\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(src1.at(i));\n        }\n\n        gate::line_container controls(src1.begin(), src1.end());\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_multi_control_toffoli(controls, dest);\n\n        for (unsigned i = 0u; i < src1.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src2.at(i), src1.at(i));\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(src1.at(i));\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::greater_equals(unsigned dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        if (!greater_than(dest, src2, src1)) return false;\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(dest);\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::greater_than(unsigned dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        return less_than(dest, src2, src1);\n    }\n\n    bool standard_syrec_synthesizer::increase_new(const std::vector<unsigned>& rhs, const std::vector<unsigned>& lhs) {\n        unsigned bitwidth = rhs.size();\n\n        if (bitwidth == 1) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(0), rhs.at(0));\n        } else {\n            for (unsigned i = 1; i <= bitwidth - 1; ++i) {\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(i), rhs.at(i));\n            }\n            for (unsigned i = bitwidth - 2; i >= 1; --i) {\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(i), lhs.at(i + 1));\n            }\n            for (unsigned i = 0; i <= bitwidth - 2; ++i) {\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(rhs.at(i), lhs.at(i), lhs.at(i + 1));\n            }\n\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(bitwidth - 1), rhs.at(bitwidth - 1));\n\n            for (unsigned i = bitwidth - 2; i >= 1; --i) {\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(lhs.at(i), rhs.at(i), lhs.at(i + 1));\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(i), rhs.at(i));\n            }\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(lhs.at(0), rhs.at(0), lhs.at(1));\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(0), rhs.at(0));\n\n            for (unsigned i = 1; i <= bitwidth - 2; ++i) {\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(i), lhs.at(i + 1));\n            }\n            for (unsigned i = 1; i <= bitwidth - 1; ++i) {\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(lhs.at(i), rhs.at(i));\n            }\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::decrease_new(const std::vector<unsigned>& rhs, const std::vector<unsigned>& lhs) {\n        for (unsigned int rh: rhs) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(rh);\n        }\n\n        increase_new(rhs, lhs);\n\n        for (unsigned int rh: rhs) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(rh);\n        }\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::decrease_new_assign(const std::vector<unsigned>& rhs, const std::vector<unsigned>& lhs) {\n        for (unsigned int lh: lhs) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(lh);\n        }\n\n        increase_new(rhs, lhs);\n\n        for (unsigned int lh: lhs) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(lh);\n        }\n\n        for (unsigned i = 0u; i < lhs.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(rhs.at(i));\n        }\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::expression_op_inverse(unsigned op, const std::vector<unsigned>& exp_lhs, const std::vector<unsigned>& exp_rhs) {\n        switch (op) {\n            case binary_expression::add: // +\n                decrease_new(exp_rhs, exp_lhs);\n                break;\n            case binary_expression::subtract: // -\n                decrease_new_assign(exp_rhs, exp_lhs);\n                break;\n            case binary_expression::exor: // ^\n                bitwise_cnot(exp_rhs, exp_lhs);\n                break;\n            default:\n                return false;\n        }\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::expression_single_op(unsigned op, const std::vector<unsigned>& exp_lhs, const std::vector<unsigned>& exp_rhs) {\n        switch (op) {\n            case binary_expression::add: // +\n                increase_new(exp_rhs, exp_lhs);\n                break;\n            case binary_expression::subtract: // -\n                if (sub_flag) {\n                    decrease_new_assign(exp_rhs, exp_lhs);\n                } else {\n                    decrease_new(exp_rhs, exp_lhs);\n                }\n                break;\n            case binary_expression::exor: // ^\n                bitwise_cnot(exp_rhs, exp_lhs);\n                break;\n            default:\n                return false;\n        }\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::increase_with_carry(const std::vector<unsigned>& dest, const std::vector<unsigned>& src, unsigned carry) {\n        unsigned bitwidth = src.size();\n\n        if (bitwidth == 0) return true;\n\n        for (unsigned i = 1u; i < bitwidth; ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src.at(i), dest.at(i));\n        }\n\n        if (bitwidth > 1) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src.at(bitwidth - 1), carry);\n        }\n        for (int i = (int)bitwidth - 2; i > 0; --i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src.at(i), src.at(i + 1));\n        }\n\n        for (unsigned i = 0u; i < bitwidth - 1; ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(src.at(i), dest.at(i), src.at(i + 1));\n        }\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(src.at(bitwidth - 1), dest.at(bitwidth - 1), carry);\n\n        for (int i = (int)bitwidth - 1; i > 0; --i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src.at(i), dest.at(i));\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_toffoli(dest.at(i - 1), src.at(i - 1), src.at(i));\n        }\n\n        for (unsigned i = 1u; i < bitwidth - 1u; ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src.at(i), src.at(i + 1));\n        }\n\n        for (unsigned i = 0u; i < bitwidth; ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src.at(i), dest.at(i));\n        }\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::less_equals(unsigned dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        if (!less_than(dest, src2, src1)) return false;\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(dest);\n\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::less_than(unsigned dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        return (decrease_with_carry(src1, src2, dest) && increase_new(src1, src2));\n    }\n\n    bool standard_syrec_synthesizer::modulo(const std::vector<unsigned>& dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        std::vector<unsigned> sum;\n        std::vector<unsigned> partial;\n\n        for (unsigned i = 1u; i < src1.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(src2.at(i));\n        }\n\n        for (unsigned i = 1u; i < src1.size(); ++i) {\n            add_active_control(src2.at(i));\n        }\n\n        for (int i = int(src1.size()) - 1; i >= 0; --i) {\n            partial.push_back(src2.at(src1.size() - 1u - i));\n            sum.insert(sum.begin(), src1.at(i));\n            decrease_with_carry(sum, partial, dest.at(i));\n            add_active_control(dest.at(i));\n            increase_new(sum, partial);\n            remove_active_control(dest.at(i));\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(dest.at(i));\n            if (i > 0) {\n                for (unsigned j = (src1.size() - i); j < src1.size(); ++j) {\n                    remove_active_control(src2.at(j));\n                }\n                (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(src2.at(src1.size() - i));\n                for (unsigned j = (src1.size() + 1u - i); j < src1.size(); ++j) {\n                    add_active_control(src2.at(j));\n                }\n            }\n        }\n        return true;\n    }\n\n    bool standard_syrec_synthesizer::multiplication(const std::vector<unsigned>& dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        if ((src1.empty()) || (dest.empty())) return true;\n\n        std::vector<unsigned> sum     = dest;\n        std::vector<unsigned> partial = src2;\n\n        bool ok = true;\n\n        add_active_control(src1.at(0));\n        ok = ok && bitwise_cnot(sum, partial);\n        remove_active_control(src1.at(0));\n\n        for (unsigned i = 1; i < dest.size(); ++i) {\n            sum.erase(sum.begin());\n            partial.pop_back();\n            add_active_control(src1.at(i));\n            ok = ok && increase_new(sum, partial);\n            remove_active_control(src1.at(i));\n        }\n\n        return ok;\n    }\n\n    bool standard_syrec_synthesizer::not_equals(unsigned dest, const std::vector<unsigned>& src1, const std::vector<unsigned>& src2) {\n        if (!equals(dest, src1, src2)) return false;\n        (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(dest);\n        return true;\n    }\n\n    void standard_syrec_synthesizer::swap(const std::vector<unsigned>& dest1, const std::vector<unsigned>& dest2) {\n        for (unsigned i = 0u; i < dest1.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_fredkin(dest1.at(i), dest2.at(i));\n        }\n    }\n\n    //**********************************************************************\n    //*****                      Shift Operations                      *****\n    //**********************************************************************\n\n    void standard_syrec_synthesizer::left_shift(const std::vector<unsigned>& dest, const std::vector<unsigned>& src1, unsigned src2) {\n        for (unsigned i = 0u; (i + src2) < dest.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src1.at(i), dest.at(i + src2));\n        }\n    }\n\n    void standard_syrec_synthesizer::right_shift(const std::vector<unsigned>& dest, const std::vector<unsigned>& src1, unsigned src2) {\n        for (unsigned i = src2; i < dest.size(); ++i) {\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_cnot(src1.at(i), dest.at(i - src2));\n        }\n    }\n\n    //**********************************************************************\n    //*****                     Efficient Controls                     *****\n    //**********************************************************************\n\n    void standard_syrec_synthesizer::add_active_control(unsigned control) {\n        // aktuelles Blatt vollendet, zurueck zum parent\n        cct_man.current = source(*(in_edges(cct_man.current, cct_man.tree).first), cct_man.tree);\n\n        // child fuer neuen control anlegen\n        cct_node child                                        = add_vertex(cct_man.tree);\n        get(boost::vertex_name, cct_man.tree)[child].control  = control;\n        get(boost::vertex_name, cct_man.tree)[child].controls = get(boost::vertex_name, cct_man.tree)[cct_man.current].controls;\n        get(boost::vertex_name, cct_man.tree)[child].controls.insert(control);\n        // get( boost::vertex_name, cct_man.tree )[child].circ = std::shared_ptr<circuit>( new circuit() );\n        add_edge(cct_man.current, child, cct_man.tree);\n        cct_man.current = child;\n\n        // neues Blatt anlegen\n        cct_node leaf                                        = add_vertex(cct_man.tree);\n        get(boost::vertex_name, cct_man.tree)[leaf].controls = get(boost::vertex_name, cct_man.tree)[cct_man.current].controls;\n        get(boost::vertex_name, cct_man.tree)[leaf].circ     = std::make_shared<circuit>();\n        get(boost::vertex_name, cct_man.tree)[leaf].circ->gate_added.connect(annotater(*get(boost::vertex_name, cct_man.tree)[leaf].circ, _stmts));\n        add_edge(cct_man.current, leaf, cct_man.tree);\n        cct_man.current = leaf;\n    }\n\n    void standard_syrec_synthesizer::remove_active_control(unsigned control [[maybe_unused]]) {\n        // aktuelles Blatt vollendet, zurueck zum parent\n        cct_man.current = source(*(in_edges(cct_man.current, cct_man.tree).first), cct_man.tree);\n\n        // aktueller Knoten abgeschlossen, zurueck zum parent\n        cct_man.current = source(*(in_edges(cct_man.current, cct_man.tree).first), cct_man.tree);\n\n        // neues Blatt anlegen\n        cct_node leaf                                        = add_vertex(cct_man.tree);\n        get(boost::vertex_name, cct_man.tree)[leaf].controls = get(boost::vertex_name, cct_man.tree)[cct_man.current].controls;\n        get(boost::vertex_name, cct_man.tree)[leaf].circ     = std::make_shared<circuit>();\n        get(boost::vertex_name, cct_man.tree)[leaf].circ->gate_added.connect(annotater(*get(boost::vertex_name, cct_man.tree)[leaf].circ, _stmts));\n        add_edge(cct_man.current, leaf, cct_man.tree);\n        cct_man.current = leaf;\n    }\n\n    bool standard_syrec_synthesizer::assemble_circuit(const cct_node& current) {\n        // leaf\n        if (out_edges(current, cct_man.tree).first == out_edges(current, cct_man.tree).second /*get( boost::vertex_name, cct_man.tree )[current].circ.get()->num_gates() > 0u*/) {\n            _circ.insert_circuit(_circ.num_gates(), *(get(boost::vertex_name, cct_man.tree)[current].circ), get(boost::vertex_name, cct_man.tree)[current].controls);\n            return true;\n        }\n        // assemble optimized circuits of successors\n        for (auto edge_it = out_edges(current, cct_man.tree).first; edge_it != out_edges(current, cct_man.tree).second; ++edge_it) {\n            if (!assemble_circuit(target(*edge_it, cct_man.tree))) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    void standard_syrec_synthesizer::get_variables(const variable_access::ptr& var, std::vector<unsigned>& lines) {\n        unsigned offset = _var_lines[var->get_var()];\n\n        if (!var->indexes.empty()) {\n            // check if it is all numeric_expressions\n            unsigned n = var->get_var()->dimensions.size(); // dimensions\n            if ((unsigned)std::count_if(var->indexes.cbegin(), var->indexes.cend(), [&](const auto& p) { return dynamic_cast<numeric_expression*>(p.get()); }) == n) {\n                for (unsigned i = 0u; i < n; ++i) {\n                    offset += dynamic_cast<numeric_expression*>(var->indexes.at(i).get())->value->evaluate(loop_map) *\n                              std::accumulate(var->get_var()->dimensions.begin() + i + 1u, var->get_var()->dimensions.end(), 1u, std::multiplies<>()) *\n                              var->get_var()->bitwidth;\n                }\n            }\n        }\n\n        if (var->range) {\n            auto [nfirst, nsecond] = *var->range;\n\n            unsigned first  = nfirst->evaluate(loop_map);\n            unsigned second = nsecond->evaluate(loop_map);\n\n            if (first < second) {\n                for (unsigned i = first; i <= second; ++i) {\n                    lines.emplace_back(offset + i);\n                }\n            } else {\n                for (int i = (int)first; i >= (int)second; --i) {\n                    lines.emplace_back(offset + i);\n                }\n            }\n        } else {\n            for (unsigned i = 0u; i < var->get_var()->bitwidth; ++i) {\n                lines.emplace_back(offset + i);\n            }\n        }\n    }\n\n    /**\n   * Function to access array variables\n   *\n   * The array variable that corresponds to the given indexes is exchanged (via swap operations) with some given helper lines\n   *\n   * \\param offset is the first line number associated to the array\n   * \\param dimensions is the dimensions of the array\n   * \\param indexes is the indexes of the array\n   * \\param bitwidth is the bitwidth of the variables within the array\n   * \\param lines is the destination, where\n   */\n    unsigned standard_syrec_synthesizer::get_constant_line(bool value) {\n        unsigned const_line = 0u;\n\n        if (!free_const_lines_map[value].empty()) {\n            const_line = free_const_lines_map[value].back();\n            free_const_lines_map[value].pop_back();\n        } else if (!free_const_lines_map[!value].empty()) {\n            const_line = free_const_lines_map[!value].back();\n            free_const_lines_map[!value].pop_back();\n            (*(get(boost::vertex_name, cct_man.tree)[cct_man.current].circ)).append_not(const_line);\n        } else {\n            const_line = _circ.add_line((std::string(\"const_\") + std::to_string(value)), \"garbage\", value, true);\n        }\n\n        return const_line;\n    }\n\n    void standard_syrec_synthesizer::get_constant_lines(unsigned bitwidth, unsigned value, std::vector<unsigned>& lines) {\n        boost::dynamic_bitset<> number(bitwidth, value);\n\n        for (unsigned i = 0u; i < bitwidth; ++i) {\n            lines.emplace_back(get_constant_line(number.test(i)));\n        }\n    }\n\n    void standard_syrec_synthesizer::add_variable(circuit& circ, const std::vector<unsigned>& dimensions, const variable::ptr& var,\n                                                  constant _constant, bool _garbage, const std::string& arraystr) {\n        if (dimensions.empty()) {\n            for (unsigned i = 0u; i < var->bitwidth; ++i) {\n                std::string name = var->name + arraystr + \".\" + std::to_string(i);\n                circ.add_line(name, name, _constant, _garbage);\n            }\n        } else {\n            unsigned              len = dimensions.front();\n            std::vector<unsigned> new_dimensions(dimensions.begin() + 1u, dimensions.end());\n\n            for (unsigned i = 0u; i < len; ++i) {\n                add_variable(circ, new_dimensions, var, _constant, _garbage, arraystr + \"[\" + std::to_string(i) + \"]\");\n            }\n        }\n    }\n\n    void standard_syrec_synthesizer::add_variables(circuit& circ, const variable::vec& variables) {\n        for (const auto& var: variables) {\n            // entry in var lines map\n            _var_lines.insert(std::make_pair(var, circ.get_lines()));\n\n            // types of constant and garbage\n            constant _constant = (var->type == variable::out || var->type == variable::wire) ? constant(false) : constant();\n            bool     _garbage  = (var->type == variable::in || var->type == variable::wire);\n\n            add_variable(circ, var->dimensions, var, _constant, _garbage, std::string());\n        }\n    }\n\n    bool syrec_synthesis(circuit& circ, const program& program, const properties::ptr& settings, const properties::ptr& statistics) {\n        // Settings parsing\n        auto variable_name_format  = get<std::string>(settings, \"variable_name_format\", \"%1$s%3$s.%2$d\");\n        auto main_module           = get<std::string>(settings, \"main_module\", std::string());\n        auto statement_synthesizer = standard_syrec_synthesizer(circ, program);\n\n        // get the main module\n        module::ptr main;\n\n        if (!main_module.empty()) {\n            main = program.find_module(main_module);\n            if (!main) {\n                std::cerr << \"Program has no module: \" << main_module << std::endl;\n                return false;\n            }\n        } else {\n            main = program.find_module(\"main\");\n            if (!main) {\n                main = program.modules().front();\n            }\n        }\n\n        // declare as top module\n        statement_synthesizer.set_main_module(main);\n\n        // create lines for global variables\n        statement_synthesizer.add_variables(circ, main->parameters);\n        statement_synthesizer.add_variables(circ, main->variables);\n\n        // Run-time measuring\n        timer<properties_timer> t;\n\n        if (statistics) {\n            properties_timer rt(statistics);\n            t.start(rt);\n        }\n        // synthesize the statements\n        bool synth_okay = statement_synthesizer.on_module(main);\n\n        if (statistics) {\n            t.stop();\n        }\n\n        return synth_okay;\n    }\n\n} // namespace syrec\n", "meta": {"hexsha": "c17aebffe3f6bca249775885cff4b6d780623abc", "size": 58253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithms/synthesis/syrec_synthesis.cpp", "max_stars_repo_name": "SmaranTum/syrec", "max_stars_repo_head_hexsha": "7fd0eece4c3376e52c1f5f17add71a49e5826dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-19T21:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T21:51:58.000Z", "max_issues_repo_path": "src/algorithms/synthesis/syrec_synthesis.cpp", "max_issues_repo_name": "SmaranTum/syrec", "max_issues_repo_head_hexsha": "7fd0eece4c3376e52c1f5f17add71a49e5826dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2022-02-28T17:03:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T16:02:39.000Z", "max_forks_repo_path": "src/algorithms/synthesis/syrec_synthesis.cpp", "max_forks_repo_name": "cda-tum/syrec", "max_forks_repo_head_hexsha": "43dcdd997edd02c80304f53f66118f9dd0fc5f68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-02T10:35:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T15:52:24.000Z", "avg_line_length": 41.2264685067, "max_line_length": 195, "alphanum_fraction": 0.542409833, "num_tokens": 12928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.02228618728442906, "lm_q1q2_score": 0.008660814440882311}}
{"text": "// Copyright (c) 2017 Shota SUGIHARA\n// Distributed under the MIT License.\n#include \"particles.h\"\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <boost/format.hpp>\n#include <Eigen/LU>\n\nnamespace tiny_mps {\n\nParticles::Particles(int size, const Condition& condition)\n    : condition_(condition), dimension(condition.dimension), inflow_stride(0.0) {\n  initialize(size);\n  setInitialParticleNumberDensity();\n  setLaplacianLambda();\n}\n\nParticles::Particles(const std::string& path, const Condition& condition)\n    : condition_(condition), dimension(condition.dimension), inflow_stride(0.0) {\n  readGridFile(path, condition);\n  updateParticleNumberDensity();\n  setInitialParticleNumberDensity();\n  setLaplacianLambda();\n  checkSurfaceParticles();\n}\n\nParticles::Particles(const Particles& other)\n    : condition_(other.condition_),\n      dimension(other.dimension) {\n  size = other.size;\n  ghost_stack = other.ghost_stack;\n  initial_particle_number_density = other.initial_particle_number_density;\n  laplacian_lambda_pressure = other.laplacian_lambda_pressure;\n  laplacian_lambda_viscosity = other.laplacian_lambda_viscosity;\n  initial_neighbor_particles = other.initial_neighbor_particles;\n  inflow_stride = other.inflow_stride;\n  position = other.position;\n  velocity = other.velocity;\n  pressure = other.pressure;\n  particle_number_density = other.particle_number_density;\n  temporary_position = other.temporary_position;\n  temporary_velocity = other.temporary_velocity;\n  correction_velocity = other.correction_velocity;\n  particle_types = other.particle_types;\n  boundary_types = other.boundary_types;\n  neighbor_particles = other.neighbor_particles;\n  source_term = other.source_term;\n  voxel_ratio = other.voxel_ratio;\n}\n\nParticles& Particles::operator=(const Particles& other) {\n  if (this != &other) {\n    size = other.size;\n    ghost_stack = other.ghost_stack;\n    initial_particle_number_density = other.initial_particle_number_density;\n    laplacian_lambda_pressure = other.laplacian_lambda_pressure;\n    laplacian_lambda_viscosity = other.laplacian_lambda_viscosity;\n    initial_neighbor_particles = other.initial_neighbor_particles;\n    inflow_stride = other.inflow_stride;\n    position = other.position;\n    velocity = other.velocity;\n    pressure = other.pressure;\n    particle_number_density = other.particle_number_density;\n    temporary_position = other.temporary_position;\n    temporary_velocity = other.temporary_velocity;\n    correction_velocity = other.correction_velocity;\n    particle_types = other.particle_types;\n    boundary_types = other.boundary_types;\n    neighbor_particles = other.neighbor_particles;\n    source_term = other.source_term;\n    voxel_ratio = other.voxel_ratio;\n  }\n  return *this;\n}\n\nParticles::~Particles() {}\n\nvoid Particles::initialize(int size) {\n  this->size = size;\n  position = Eigen::MatrixXd::Zero(3, size);\n  velocity = Eigen::MatrixXd::Zero(3, size);\n  pressure = Eigen::VectorXd::Zero(size);\n  particle_number_density = Eigen::VectorXd::Zero(size);\n  temporary_position = Eigen::MatrixXd::Zero(3, size);\n  temporary_velocity = Eigen::MatrixXd::Zero(3, size);\n  particle_types = Eigen::VectorXi::Zero(size);\n  boundary_types = Eigen::VectorXi::Zero(size);\n  correction_velocity = Eigen::MatrixXd::Zero(3, size);\n  neighbor_particles = Eigen::VectorXi::Zero(size);\n  source_term = Eigen::VectorXd::Zero(size);\n  voxel_ratio = Eigen::VectorXd::Zero(size);\n}\n\nvoid Particles::readGridFile(const std::string& path, const Condition& condition) {\n  std::ifstream ifs(path);\n  if (ifs.fail()) {\n    std::cerr << \"Error: in readGridFile() in particles.cpp\" << std::endl;\n    std::cerr << \"Failed to read files: \" << path << std::endl;\n    throw std::ios_base::failure(\"Error: in readGridFile() in particles.cpp.\");\n  }\n  std::string tmp_str;\n  getline(ifs, tmp_str);      //Line 0: Start time\n  getline(ifs, tmp_str);      //Line 1: particles_number\n  int ptcl_num = 0;\n  {\n    std::stringstream ss;\n    ss.str(tmp_str);\n    ss >> ptcl_num;\n    initialize(ptcl_num + condition.extra_ghost_particles);\n  }\n  int i_counter = 0;\n  while(getline(ifs, tmp_str)) {\n    std::stringstream ss;\n    ss.str(tmp_str);\n    ss >> particle_types(i_counter);\n    for(int i_dim = 0; i_dim < 3; ++i_dim) {\n      double tmp;\n      ss >> tmp;\n      if (i_dim < dimension) position(i_dim, i_counter) = tmp;\n    }\n    for(int i_dim = 0; i_dim < 3; ++i_dim) {\n      double tmp;\n      ss >> tmp;\n      if (i_dim < dimension) velocity(i_dim, i_counter) = tmp;\n    }\n    ss >> pressure(i_counter);\n    ++i_counter;\n  }\n  for (int i_particle = ptcl_num; i_particle < size; ++i_particle) {\n    particle_types(i_particle) = ParticleType::GHOST;\n    ghost_stack.push(i_particle);\n  }\n  std::cout << \"Succeed in reading grid file: \" << path << std::endl;\n}\n\nvoid Particles::writeVtkFile(const std::string& path, const std::string& title) const {\n  std::ofstream ofs(path);\n  if(ofs.fail()) {\n    std::cerr << \"Error: in writeVtkFile() in particles.cpp.\" << std::endl;\n    throw std::ios_base::failure(\"Error: in writeVtkFile() in particles.cpp.\");\n  }\n  ofs << \"# vtk DataFile Version 2.0\" << std::endl;\n  ofs << title << std::endl;\n  ofs << \"ASCII\" << std::endl;\n  ofs << \"DATASET UNSTRUCTURED_GRID\" << std::endl;\n  ofs << std::endl;\n  ofs << \"POINTS \" << size << \" double\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << position(0, i) << \" \" << position(1, i) << \" \" << position(2, i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"CELLS \" << size << \" \" << size * 2 << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << 1 << \" \" << i << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"CELL_TYPES \" << size << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << 1 << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"POINT_DATA \" << size << std::endl;\n  ofs << \"SCALARS Pressure double\" << std::endl;\n  ofs << \"LOOKUP_TABLE Pressure\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << pressure(i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"VECTORS Velocity double\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << velocity(0, i) << \" \" << velocity(1, i) << \" \" << velocity(2, i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"SCALARS Type int\" << std::endl;\n  ofs << \"LOOKUP_TABLE Type\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << particle_types(i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"SCALARS ParticleNumberDensity double\" << std::endl;\n  ofs << \"LOOKUP_TABLE ParticleNumberDensity\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << particle_number_density(i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"SCALARS NeighborParticles int\" << std::endl;\n  ofs << \"LOOKUP_TABLE NeighborParticles\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << neighbor_particles(i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"SCALARS BoundaryCondition int\" << std::endl;\n  ofs << \"LOOKUP_TABLE BoundaryCondition\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << boundary_types(i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"VECTORS CorrectionVelocity double\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << correction_velocity(0, i) << \" \" << correction_velocity(1, i) << \" \" << correction_velocity(2, i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"SCALARS SourceTerm double\" << std::endl;\n  ofs << \"LOOKUP_TABLE SourceTerm\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << source_term(i) << std::endl;\n  }\n  ofs << std::endl;\n  ofs << \"SCALARS VoxelsRatio double\" << std::endl;\n  ofs << \"LOOKUP_TABLE VoxelsRatio\" << std::endl;\n  for(int i = 0; i < size; ++i) {\n    ofs << voxel_ratio(i) << std::endl;\n  }\n  std::cout << \"Succeed in writing vtk file: \" << path << std::endl;\n}\n\nbool Particles::saveInterval(const std::string& path, const Timer& timer) const {\n  if (!timer.isOutputTime()) return false;\n  std::string output_index = (boost::format(\"%04d\") % timer.getOutputCount()).str();\n  writeVtkFile((boost::format(path) % output_index).str(), (boost::format(\"Time: %s\") % timer.getCurrentTime()).str());\n  return true;\n}\n\nvoid Particles::setInitialParticleNumberDensity() {\n  const int xy_max = (int)condition_.pnd_influence;\n  const int z_max = (dimension == 3)? xy_max : 0;\n  double pnd = 0;\n  int count = 0;\n  for (int i_z = -z_max; i_z <= z_max; ++i_z) {\n    for (int i_y = -xy_max; i_y <= xy_max; ++i_y) {\n      for (int i_x = -xy_max; i_x <= xy_max; ++i_x) {\n        if (i_x == 0 && i_y == 0 && i_z == 0) continue;\n        Eigen::Vector3d vec(i_x, i_y, i_z);\n        vec *= condition_.average_distance;\n        pnd += weightForParticleNumberDensity(vec);\n        count += weightCount(vec, condition_.pnd_weight_radius);\n      }\n    }\n  }\n  initial_particle_number_density = pnd;\n  initial_neighbor_particles = count;\n  std::cout << \"Initial particle number density: \" << initial_particle_number_density << std::endl;\n  std::cout << \"Initial neighbor particles: \" << initial_neighbor_particles << std::endl;\n}\n\nvoid Particles::setLaplacianLambda() {\n  {\n    const int xy_max = (int)condition_.laplacian_pressure_influence;\n    const int z_max = (dimension == 3)? xy_max : 0;\n    double numerator = 0.0;\n    double denominator = 0.0;\n    for (int i_z = -z_max; i_z <= z_max; ++i_z) {\n      for (int i_y = -xy_max; i_y <= xy_max; ++i_y) {\n        for (int i_x = -xy_max; i_x <= xy_max; ++i_x) {\n          if (i_x == 0 && i_y == 0 && i_z == 0) continue;\n          Eigen::Vector3d vec(i_x, i_y, i_z);\n          vec *= condition_.average_distance;\n          double w = weightForLaplacianPressure(vec);\n          numerator += vec.squaredNorm() * w;\n          denominator += w;\n        }\n      }\n    }\n    laplacian_lambda_pressure = numerator / denominator;\n  }\n  {\n    const int xy_max = (int)condition_.laplacian_viscosity_influence;\n    const int z_max = (dimension == 3)? xy_max : 0;\n    double numerator = 0.0;\n    double denominator = 0.0;\n    for (int i_z = -z_max; i_z <= z_max; ++i_z) {\n      for (int i_y = -xy_max; i_y <= xy_max; ++i_y) {\n        for (int i_x = -xy_max; i_x <= xy_max; ++i_x) {\n          if (i_x == 0 && i_y == 0 && i_z == 0) continue;\n          Eigen::Vector3d vec(i_x, i_y, i_z);\n          vec *= condition_.average_distance;\n          double w = weightForLaplacianViscosity(vec);\n          numerator += vec.squaredNorm() * w;\n          denominator += w;\n        }\n      }\n    }\n    laplacian_lambda_viscosity = numerator / denominator;\n  }\n  std::cout << \"Laplacian lambda for Pressure: \" << laplacian_lambda_pressure << std::endl;\n  std::cout << \"Laplacian lambda for Viscosity: \" << laplacian_lambda_viscosity << std::endl;\n  std::cout << \"Relaxation coefficient of PND: \" << condition_.relaxation_coefficient_pnd << std::endl;\n  std::cout << \"Relaxation coefficient of velocity divergence: \" << condition_.relaxation_coefficient_vel_div << std::endl;\n}\n\nbool Particles::nextLoop(const std::string& path, Timer& timer) {\n  std::cout << std::endl;\n  timer.limitCurrentDeltaTime(getMaxSpeed(), condition_);\n  timer.printCompuationTime();\n  timer.printTimeInfo();\n  showParticlesInfo();\n  std::cout << boost::format(\"Max velocity: %f\") % getMaxSpeed() << std::endl;\n  saveInterval(path, timer);\n  if (checkNeedlessCalculation()) {\n    std::cerr << \"Error: All particles have become ghost.\" << std::endl;\n    writeVtkFile((boost::format(path) % \"err\").str(), (boost::format(\"Time: %s\") % timer.getCurrentTime()).str());\n    throw std::range_error(\"Error: All particles have become ghost.\");\n  }\n  if (timer.isUnderMinDeltaTime()) {\n    std::cerr << \"Error: Delta time has become so small.\" << std::endl;\n    writeVtkFile((boost::format(path) % \"err\").str(), (boost::format(\"Time: %s\") % timer.getCurrentTime()).str());\n    throw std::range_error(\"Error: Delta time has become so small.\");\n  }\n  if (!timer.hasNextLoop()) {\n    std::cout << std::endl << \"Total \";\n    timer.printCompuationTime();\n    std::cout << \"Succeed in simulation.\" << std::endl;\n    return false;\n  }\n  timer.update();\n  temporary_velocity = velocity;\n  temporary_position = position;\n  return true;\n}\n\nbool Particles::checkNeedlessCalculation() const {\n  if (pressure.hasNaN() || velocity.hasNaN() || position.hasNaN()) {\n    std::cerr << \"Error: Data contains NaN.\" << std::endl;\n    return true;\n  }\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) == ParticleType::NORMAL) return false;\n  }\n  std::cerr << \"Error: No normal particles.\" << std::endl;\n  return true;\n}\n\nvoid Particles::extendStorage(int extra_size) {\n  position.conservativeResize(3, size + extra_size);\n  velocity.conservativeResize(3, size + extra_size);\n  temporary_position.conservativeResize(3, size + extra_size);\n  temporary_velocity.conservativeResize(3, size + extra_size);\n  correction_velocity.conservativeResize(3, size + extra_size);\n  pressure.conservativeResize(size + extra_size);\n  particle_number_density.conservativeResize(size + extra_size);\n  neighbor_particles.conservativeResize(size + extra_size);\n  boundary_types.conservativeResize(size + extra_size);\n  particle_types.conservativeResize(size + extra_size);\n  source_term.conservativeResize(size + extra_size);\n  voxel_ratio.conservativeResize(size + extra_size);\n\n  position.block(0, size, 3, extra_size)            = Eigen::MatrixXd::Zero(3, extra_size);\n  velocity.block(0, size, 3, extra_size)            = Eigen::MatrixXd::Zero(3, extra_size);\n  temporary_position.block(0, size, 3, extra_size)  = Eigen::MatrixXd::Zero(3, extra_size);\n  temporary_velocity.block(0, size, 3, extra_size)  = Eigen::MatrixXd::Zero(3, extra_size);\n  correction_velocity.block(0, size, 3, extra_size) = Eigen::MatrixXd::Zero(3, extra_size);\n  pressure.segment(size, extra_size)                = Eigen::VectorXd::Zero(extra_size);\n  particle_number_density.segment(size, extra_size) = Eigen::VectorXd::Zero(extra_size);\n  neighbor_particles.segment(size, extra_size)      = Eigen::VectorXi::Zero(extra_size);\n  source_term.segment(size, extra_size)             = Eigen::VectorXd::Zero(extra_size);\n  voxel_ratio.segment(size, extra_size)             = Eigen::VectorXd::Zero(extra_size);\n  for (int i_particle = size; i_particle < size + extra_size; ++i_particle) {\n    particle_types(i_particle) = ParticleType::GHOST;\n    boundary_types(i_particle) = BoundaryType::OTHERS;\n    ghost_stack.push(i_particle);\n  }\n  size += extra_size;\n  std::cout << \"Added ghost particles: \" << extra_size << std::endl;\n}\n\nint Particles::addParticle() {\n  if (ghost_stack.empty()) {\n    if (condition_.additional_ghost_particles > 0) {\n      extendStorage(condition_.additional_ghost_particles);\n      int new_index = ghost_stack.top();\n      ghost_stack.pop();\n      particle_types(new_index) = ParticleType::NORMAL;\n      return new_index;\n    } else {\n      std::cerr << \"Error: Can't make new particles.\" << std::endl\n                << \"Extra ghost particles has run out.\" << std::endl\n                << \"Additional ghost particles: \" << condition_.additional_ghost_particles << std::endl;\n      throw std::bad_array_new_length();\n      exit(EXIT_FAILURE);\n    }\n  } else {\n    int new_index = ghost_stack.top();\n    ghost_stack.pop();\n    particle_types(new_index) = ParticleType::NORMAL;\n    return new_index;\n  }\n}\n\nvoid Particles::setGhostParticle(int index) {\n  if (index < 0 || index >= size) {\n    std::cerr << \"Error: Index is out of range.\" << std::endl;\n    std::cerr << \"Size: \" << size << \", Index: \" << std::endl;\n    throw std::out_of_range(\"Error: Index is out of range.\");\n  }\n  particle_types(index) = ParticleType::GHOST;\n  boundary_types(index) = BoundaryType::OTHERS;\n  position.col(index).setZero();\n  velocity.col(index).setZero();\n  pressure(index) = 0.0;\n  particle_number_density(index) = 0.0;\n  neighbor_particles(index) = 0.0;\n  temporary_position.col(index).setZero();\n  temporary_velocity.col(index).setZero();\n  correction_velocity.col(index).setZero();\n  source_term(index) = 0.0;\n  voxel_ratio(index) = 0.0;\n  ghost_stack.push(index);\n  std::cout << \"Changed ghost particle: \" << index << std::endl;\n}\n\nvoid Particles::removeOutsideParticles(const Eigen::Vector3d& minpos, const Eigen::Vector3d& maxpos) {\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) == ParticleType::GHOST) continue;\n    for (int i_dim = 0; i_dim < dimension; ++i_dim) {\n      if (position.col(i_particle)(i_dim) < minpos(i_dim) || position.col(i_particle)(i_dim) > maxpos(i_dim)) {\n        setGhostParticle(i_particle);\n      }\n    }\n  }\n}\n\nvoid Particles::removeFastParticles(double max_speed) {\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) == ParticleType::GHOST) continue;\n    if (velocity.col(i_particle).norm() > max_speed) setGhostParticle(i_particle);\n  }\n}\n\nvoid Particles::calculateTemporaryParticleNumberDensity() {\n  Grid grid(condition_.pnd_weight_radius, temporary_position, particle_types.array() != ParticleType::GHOST, dimension);\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) == ParticleType::GHOST) {\n      particle_number_density(i_particle) = 0.0;\n      neighbor_particles(i_particle) = 0;\n      continue;\n    }\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    double pnd = 0.0;\n    int count = 0;\n    for (int j_particle : neighbors) {\n      if (particle_types(i_particle) == ParticleType::GHOST) continue;\n      Eigen::Vector3d r_ij = temporary_position.col(j_particle) - temporary_position.col(i_particle);\n      pnd += weightForParticleNumberDensity(r_ij);\n      ++count;\n    }\n    particle_number_density(i_particle) = pnd;\n    neighbor_particles(i_particle) = count;\n  }\n}\n\nvoid Particles::updateParticleNumberDensity() {\n  Grid grid(condition_.pnd_weight_radius, position, particle_types.array() != ParticleType::GHOST, dimension);\n  updateParticleNumberDensity(grid);\n}\n\nvoid Particles::updateParticleNumberDensity(const Grid& grid) {\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) == ParticleType::GHOST) {\n      particle_number_density(i_particle) = 0.0;\n      neighbor_particles(i_particle) = 0;\n      continue;\n    }\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    double pnd = 0.0;\n    int count = 0;\n    for (int j_particle : neighbors) {\n      if (particle_types(i_particle) == ParticleType::GHOST) continue;\n      Eigen::Vector3d r_ij = position.col(j_particle) - position.col(i_particle);\n      pnd += weightForParticleNumberDensity(r_ij);\n      ++count;\n    }\n    particle_number_density(i_particle) = pnd;\n    neighbor_particles(i_particle) = count;\n  }\n}\n\nvoid Particles::updateVoxelRatio(int width, const Grid& grid) {\n  if (condition_.dimension == 2) {\n    for (int i_particle = 0; i_particle < size; ++i_particle) {\n      if (particle_types(i_particle) == ParticleType::GHOST\n       || boundary_types(i_particle) == BoundaryType::OTHERS) {\n        voxel_ratio(i_particle) = 0;\n        continue;\n      }\n      Grid::Neighbors neighbors;\n      grid.getNeighborsInBox(i_particle, neighbors);\n      const int voxels_size = width * width;\n      std::vector<int> voxels(voxels_size);\n      double shift = width * condition_.average_distance / 2.0;\n      for (int idx = 0; idx < voxels_size; ++idx) voxels[idx] = 0;\n      double center_hash = voxels_size / 2;\n      if (boundary_types(i_particle) == BoundaryType::SURFACE) {\n        voxels[center_hash] = 1;\n      } else {\n        if (voxels[center_hash] != 1) voxels[center_hash] = 2;\n      }\n      bool near_surface = false;\n      for (int j_particle : neighbors) {\n        if (particle_types(j_particle) == ParticleType::GHOST) continue;\n        Eigen::Vector3d r_ij = temporary_position.col(j_particle) - temporary_position.col(i_particle);\n        int x_idx = std::floor((r_ij(0) + shift) / condition_.average_distance);\n        int y_idx = std::floor((r_ij(1) + shift) / condition_.average_distance);\n        if (x_idx < 0 || x_idx >= width || y_idx < 0 || y_idx >= width) continue;\n        int hash = x_idx + y_idx * width;\n        if (hash < 0 || hash >= voxels_size) continue;\n        if (boundary_types(j_particle) == BoundaryType::SURFACE) {\n          voxels[hash] = 1;\n          near_surface = true;\n        } else {\n          if (voxels[hash] != 1) voxels[hash] = 2;\n        }\n      }\n      double val_sum = 0;\n      for (int idx = 0; idx < voxels_size; ++idx) {\n        val_sum += voxels[idx];\n      }\n      voxel_ratio(i_particle) = (near_surface)? val_sum / (voxels_size * 2) : 1.0;\n    }\n  } else {\n    throw std::out_of_range(\"Not implemented for 3d.\");\n  }\n}\n\nvoid Particles::moveInflowParticles(const Timer& timer) {\n  inflow_stride += condition_.inflow_velocity.norm() * timer.getCurrentDeltaTime();\n  Eigen::Vector3d inflow_normalized = condition_.inflow_velocity.normalized();\n  if (inflow_stride >= condition_.average_distance) {\n    for (int i_particle = 0; i_particle < size; ++i_particle) {\n      if (particle_types(i_particle) == ParticleType::INFLOW) {\n        int new_index = addParticle();\n        particle_types(new_index) = ParticleType::NORMAL;\n        boundary_types(new_index) = boundary_types(i_particle);\n        position.col(new_index) = position.col(i_particle);\n        velocity.col(new_index) = velocity.col(i_particle);\n        pressure(new_index) = pressure(i_particle);\n        particle_number_density(new_index) = particle_number_density(i_particle);\n        neighbor_particles(new_index) = neighbor_particles(i_particle);\n        temporary_position.col(new_index) = temporary_position.col(i_particle);\n        temporary_velocity.col(new_index) = temporary_velocity.col(i_particle);\n        correction_velocity.col(new_index) = correction_velocity.col(i_particle);\n        temporary_velocity.col(i_particle) = condition_.inflow_velocity;\n        velocity.col(i_particle) = condition_.inflow_velocity;\n        temporary_position.col(i_particle) -= inflow_normalized  * condition_.average_distance;\n        position.col(i_particle) -= inflow_normalized  * condition_.average_distance;\n      }\n      if (particle_types(i_particle) == ParticleType::DUMMY_INFLOW) {\n        temporary_velocity.col(i_particle) = condition_.inflow_velocity;\n        velocity.col(i_particle) = condition_.inflow_velocity;\n        temporary_position.col(i_particle) -= inflow_normalized * condition_.average_distance;\n        position.col(i_particle) -= inflow_normalized * condition_.average_distance;\n      }\n    }\n    inflow_stride -= condition_.average_distance;\n  } else {\n    for (int i_particle = 0; i_particle < size; ++i_particle) {\n      if (particle_types(i_particle) == ParticleType::INFLOW || particle_types(i_particle) == ParticleType::DUMMY_INFLOW ) {\n        temporary_velocity.col(i_particle) = condition_.inflow_velocity;\n        velocity.col(i_particle) = condition_.inflow_velocity;\n      }\n    }\n  }\n}\n\nvoid Particles::calculateTemporaryVelocity(const Eigen::Vector3d& force, const Timer& timer) {\n  Grid grid(condition_.laplacian_viscosity_weight_radius, position,\n            particle_types.array() == ParticleType::NORMAL || particle_types.array() == ParticleType::INFLOW,\n            condition_.dimension);\n  calculateTemporaryVelocity(force, timer, grid);\n}\n\nvoid Particles::calculateTemporaryVelocity(const Eigen::Vector3d& force, const Timer& timer, Grid& grid) {\n  double delta_time = timer.getCurrentDeltaTime();\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) == ParticleType::NORMAL) {\n      temporary_velocity.col(i_particle) += delta_time * force;\n      if (condition_.viscosity_calculation) {\n        Grid::Neighbors neighbors;\n        grid.getNeighbors(i_particle, neighbors);\n        Eigen::Vector3d lap_vec(0.0, 0.0, 0.0);\n        for (int j_particle : neighbors) {\n          Eigen::Vector3d u_ij = velocity.col(j_particle) - velocity.col(i_particle);\n          Eigen::Vector3d r_ij = position.col(j_particle) - position.col(i_particle);\n          lap_vec += u_ij * weightForLaplacianViscosity(r_ij) * 2 * dimension / (laplacian_lambda_viscosity * initial_particle_number_density);\n        }\n        temporary_velocity.col(i_particle) += lap_vec * condition_.kinematic_viscosity * delta_time;\n      }\n    }\n  }\n}\n\nvoid Particles::updateTemporaryPosition(const Timer& timer) {\n  temporary_position = position + timer.getCurrentDeltaTime() * temporary_velocity;\n}\n\nvoid Particles::solvePressurePoisson(const Timer& timer) {\n  Grid grid(condition_.laplacian_pressure_weight_radius, temporary_position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  using T = Eigen::Triplet<double>;\n  double lap_r = grid.getGridWidth()/condition_.average_distance;\n  int n_size = (int)(std::pow(lap_r * 2, dimension));\n  double delta_time = timer.getCurrentDeltaTime();\n  Eigen::SparseMatrix<double> p_mat(size, size);\n  source_term.setZero();\n  std::vector<T> coeffs(size * n_size);\n  std::vector<int> neighbors(n_size * 2);\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) {\n      coeffs.push_back(T(i_particle, i_particle, 1.0));\n      continue;\n    } else if (boundary_types(i_particle) == BoundaryType::SURFACE) {\n      coeffs.push_back(T(i_particle, i_particle, 1.0));\n      continue;\n    }\n    grid.getNeighbors(i_particle, neighbors);\n    double sum = 0.0;\n    double div_vel = 0.0;\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = temporary_position.col(j_particle) - temporary_position.col(i_particle);\n      double mat_ij = weightForLaplacianPressure(r_ij) * 2 * dimension\n              / (laplacian_lambda_pressure * initial_particle_number_density);\n      sum -= mat_ij;\n      div_vel += (temporary_velocity.col(j_particle) - temporary_velocity.col(i_particle)).dot(r_ij)\n              * weightForLaplacianPressure(r_ij) * condition_.dimension / (r_ij.squaredNorm() * initial_particle_number_density);\n      if (boundary_types(j_particle) == BoundaryType::INNER) {\n        coeffs.push_back(T(i_particle, j_particle, mat_ij));\n      }\n    }\n    sum -= condition_.weak_compressibility * condition_.mass_density / (delta_time * delta_time);\n    coeffs.push_back(T(i_particle, i_particle, sum));\n    source_term(i_particle) = div_vel * condition_.mass_density * condition_.relaxation_coefficient_vel_div / delta_time\n                - (particle_number_density(i_particle) - initial_particle_number_density)\n                * condition_.relaxation_coefficient_pnd * condition_.mass_density / (delta_time * delta_time * initial_particle_number_density);\n  }\n  p_mat.setFromTriplets(coeffs.begin(), coeffs.end()); // Finished setup matrix\n  solveConjugateGradient(p_mat);\n}\n\nvoid Particles::solvePressurePoissonTanakaMasunaga(const Timer& timer) {\n  Grid grid(condition_.laplacian_pressure_weight_radius, position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  using T = Eigen::Triplet<double>;\n  double lap_r = grid.getGridWidth()/condition_.average_distance;\n  int n_size = (int)(std::pow(lap_r * 2, dimension));\n  double delta_time = timer.getCurrentDeltaTime();\n  Eigen::SparseMatrix<double> p_mat(size, size);\n  std::vector<T> coeffs(size * n_size);\n  std::vector<int> neighbors(n_size * 2);\n  source_term.setZero();\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) {\n      coeffs.push_back(T(i_particle, i_particle, 1.0));\n      continue;\n    } else if (boundary_types(i_particle) == BoundaryType::SURFACE) {\n      coeffs.push_back(T(i_particle, i_particle, 1.0));\n      continue;\n    }\n    grid.getNeighbors(i_particle, neighbors);\n    double sum = 0.0;\n    double div_vel = 0.0;\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = position.col(j_particle) - position.col(i_particle);\n      double mat_ij = weightForLaplacianPressure(r_ij) * 2 * dimension\n              / (laplacian_lambda_pressure * initial_particle_number_density);\n      sum -= mat_ij;\n      div_vel += (temporary_velocity.col(j_particle) - temporary_velocity.col(i_particle)).dot(r_ij)\n              * weightForLaplacianPressure(r_ij) * condition_.dimension / (r_ij.squaredNorm() * initial_particle_number_density);\n      if (boundary_types(j_particle) == BoundaryType::INNER) {\n        coeffs.push_back(T(i_particle, j_particle, mat_ij));\n      }\n    }\n    sum -= condition_.weak_compressibility * condition_.mass_density / (delta_time * delta_time);\n    coeffs.push_back(T(i_particle, i_particle, sum));\n    source_term(i_particle) = div_vel * condition_.mass_density * condition_.relaxation_coefficient_vel_div / delta_time\n                - (particle_number_density(i_particle) - initial_particle_number_density)\n                * condition_.relaxation_coefficient_pnd * condition_.mass_density / (delta_time * delta_time * initial_particle_number_density);\n  }\n  p_mat.setFromTriplets(coeffs.begin(), coeffs.end()); // Finished setup matrix\n  solveConjugateGradient(p_mat);\n}\n\nvoid Particles::solvePressurePoissonTamai(const Timer& timer) {\n  Grid grid(condition_.laplacian_pressure_weight_radius, temporary_position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  using T = Eigen::Triplet<double>;\n  double lap_r = grid.getGridWidth()/condition_.average_distance;\n  int n_size = (int)(std::pow(lap_r * 2, dimension));\n  double delta_time = timer.getCurrentDeltaTime();\n  Eigen::SparseMatrix<double> p_mat(size, size);\n  std::vector<T> coeffs(size * n_size);\n  std::vector<int> neighbors(n_size * 2);\n  source_term.setZero();\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) {\n      coeffs.push_back(T(i_particle, i_particle, 1.0));\n      continue;\n    } else if (boundary_types(i_particle) == BoundaryType::SURFACE) {\n      coeffs.push_back(T(i_particle, i_particle, 1.0));\n      continue;\n    }\n    grid.getNeighbors(i_particle, neighbors);\n    double sum = 0.0;\n    double div_vel = 0.0;\n    double div_tmp_vel = 0.0;\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = temporary_position.col(j_particle) - temporary_position.col(i_particle);\n      double mat_ij = weightForLaplacianPressure(r_ij) * 2 * dimension\n              / (laplacian_lambda_pressure * initial_particle_number_density);\n      sum -= mat_ij;\n      div_vel += (velocity.col(j_particle) - velocity.col(i_particle)).dot(r_ij)\n              * weightForLaplacianPressure(r_ij) * condition_.dimension / (r_ij.squaredNorm() * initial_particle_number_density);\n      div_tmp_vel += (temporary_velocity.col(j_particle) - temporary_velocity.col(i_particle)).dot(r_ij)\n              * weightForLaplacianPressure(r_ij) * condition_.dimension / (r_ij.squaredNorm() * initial_particle_number_density);\n              if (boundary_types(j_particle) == BoundaryType::INNER) {\n        coeffs.push_back(T(i_particle, j_particle, mat_ij));\n      }\n    }\n    sum -= condition_.weak_compressibility * condition_.mass_density / (delta_time * delta_time);\n    coeffs.push_back(T(i_particle, i_particle, sum));\n    double pnd_diff = (particle_number_density(i_particle) - initial_particle_number_density * voxel_ratio(i_particle)) / (initial_particle_number_density * voxel_ratio(i_particle));\n    source_term(i_particle) = (div_tmp_vel + std::abs(pnd_diff) * div_vel + std::abs(div_vel) * pnd_diff) * condition_.mass_density / delta_time;\n  }\n  p_mat.setFromTriplets(coeffs.begin(), coeffs.end()); // Finished setup matrix\n  solveConjugateGradient(p_mat);\n}\n\nvoid Particles::solveConjugateGradient(Eigen::SparseMatrix<double> p_mat) {\n  Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> cg;\n  cg.compute(p_mat);\n  if (cg.info() != Eigen::ComputationInfo::Success) {\n    std::cerr << \"Error: Failed decompostion.\" << std::endl;\n  }\n  pressure = cg.solve(source_term);\n  if (cg.info() != Eigen::ComputationInfo::Success) {\n    std::cerr << \"Error: Failed solving.\" << std::endl;\n  }\n  std::cout << \"Solver - iterations: \" << cg.iterations() << \", estimated error: \" << cg.error() << std::endl;\n}\n\nvoid Particles::setZeroOnNegativePressure(){\n  for (int i = 0; i < size; ++i) {\n    if (pressure(i) < 0) pressure(i) = 0;\n  }\n}\n\nvoid Particles::correctVelocity(const Timer& timer) {\n  Grid grid(condition_.gradient_radius, temporary_position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  correctVelocity(timer, grid);\n}\n\nvoid Particles::correctVelocity(const Timer& timer, const Grid& grid) {\n  correction_velocity.setZero();\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) != ParticleType::NORMAL) continue;\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) continue;\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    double p_min = pressure(i_particle);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      p_min = std::min(pressure(j_particle), p_min);\n    }\n    Eigen::Vector3d tmp(0.0, 0.0, 0.0);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = temporary_position.col(j_particle) - temporary_position.col(i_particle);\n      tmp += r_ij * (pressure(j_particle) - p_min) * weightForGradientPressure(r_ij) / r_ij.squaredNorm();\n    }\n    if (dimension == 2) tmp(2) = 0;\n    correction_velocity.col(i_particle) -= tmp * dimension * timer.getCurrentDeltaTime() / (initial_particle_number_density * condition_.mass_density);\n  }\n  temporary_velocity += correction_velocity;\n}\n\nvoid Particles::correctVelocityExplicitly(const Timer& timer) {\n  Grid grid(condition_.gradient_radius, position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  correction_velocity.setZero();\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) != ParticleType::NORMAL) continue;\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) continue;\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    double p_min = pressure(i_particle);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      p_min = std::min(pressure(j_particle), p_min);\n    }\n    Eigen::Vector3d tmp(0.0, 0.0, 0.0);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = position.col(j_particle) - position.col(i_particle);\n      tmp += r_ij * (pressure(j_particle) - p_min) * weightForGradientPressure(r_ij) / r_ij.squaredNorm();\n    }\n    if (dimension == 2) tmp(2) = 0;\n    correction_velocity.col(i_particle) -= tmp * dimension * timer.getCurrentDeltaTime() / (initial_particle_number_density * condition_.mass_density);\n  }\n  temporary_velocity += correction_velocity;\n}\n\nvoid Particles::correctTanakaMasunagaVelocity(const Timer& timer) {\n  Grid grid(condition_.gradient_radius, position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  correction_velocity.setZero();\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) != ParticleType::NORMAL) continue;\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) continue;\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    Eigen::Vector3d tmp(0.0, 0.0, 0.0);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = position.col(j_particle) - position.col(i_particle);\n      tmp += r_ij * (pressure(j_particle) + pressure(i_particle)) * weightForGradientPressure(r_ij) / r_ij.squaredNorm();\n    }\n    if (dimension == 2) tmp(2) = 0;\n    correction_velocity.col(i_particle) -= tmp * dimension * timer.getCurrentDeltaTime() / (initial_particle_number_density * condition_.mass_density);\n  }\n  temporary_velocity += correction_velocity;\n}\n\nvoid Particles::correctVelocityWithTensor(const Timer& timer) {\n  Grid grid(condition_.gradient_radius, temporary_position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  correction_velocity.setZero();\n  int tensor_count = 0;\n  int not_tensor_count = 0;\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) != ParticleType::NORMAL) continue;\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) continue;\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    Eigen::Matrix3d tensor = Eigen::Matrix3d::Zero();\n    Eigen::Vector3d tmp_vel(0.0, 0.0, 0.0);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = temporary_position.col(j_particle) - temporary_position.col(i_particle);\n      Eigen::Vector3d n_ij = r_ij.normalized();\n      Eigen::Matrix3d tmp_tensor = Eigen::Matrix3d::Zero();\n      tmp_tensor << n_ij(0) * n_ij(0), n_ij(0) * n_ij(1), n_ij(0) * n_ij(2),\n                    n_ij(1) * n_ij(0), n_ij(1) * n_ij(1), n_ij(1) * n_ij(2),\n                    n_ij(2) * n_ij(0), n_ij(2) * n_ij(1), n_ij(2) * n_ij(2);\n      tensor += tmp_tensor * weightForGradientPressure(r_ij) / initial_particle_number_density;\n      tmp_vel += r_ij * (pressure(j_particle) - pressure(i_particle)) * weightForGradientPressure(r_ij) / r_ij.squaredNorm();\n    }\n    if (dimension == 2) {\n      tmp_vel(2) = 0;\n      tensor(2, 2) = 1.0;\n    }\n    if (tensor.determinant() > 1.0e-10) {\n      correction_velocity.col(i_particle) -= tensor.inverse() * tmp_vel * timer.getCurrentDeltaTime() / (initial_particle_number_density * condition_.mass_density);\n      ++tensor_count;\n    } else {\n      correction_velocity.col(i_particle) -= tmp_vel * dimension * timer.getCurrentDeltaTime() / (initial_particle_number_density * condition_.mass_density);\n      ++not_tensor_count;\n      // std::cout << abs(tensor.determinant()) << std::endl <<  tensor << std::endl;\n    }\n  }\n  std::cout << \"Tensor: \" << tensor_count << \", Not Tensor: \" << not_tensor_count << std::endl;\n\n  temporary_velocity += correction_velocity;\n}\n\nvoid Particles::correctVelocityTanakaMasunagaWithTensor(const Timer& timer) {\n  Grid grid(condition_.gradient_radius, position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  correction_velocity.setZero();\n  int tensor_count = 0;\n  int not_tensor_count = 0;\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) != ParticleType::NORMAL) continue;\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) continue;\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    Eigen::Matrix3d tensor = Eigen::Matrix3d::Zero();\n    Eigen::Vector3d tmp_vel(0.0, 0.0, 0.0);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d r_ij = position.col(j_particle) - position.col(i_particle);\n      Eigen::Vector3d n_ij = r_ij.normalized();\n      Eigen::Matrix3d tmp_tensor = Eigen::Matrix3d::Zero();\n      tmp_tensor << n_ij(0) * n_ij(0), n_ij(0) * n_ij(1), n_ij(0) * n_ij(2),\n                    n_ij(1) * n_ij(0), n_ij(1) * n_ij(1), n_ij(1) * n_ij(2),\n                    n_ij(2) * n_ij(0), n_ij(2) * n_ij(1), n_ij(2) * n_ij(2);\n      tensor += tmp_tensor * weightForGradientPressure(r_ij) / initial_particle_number_density;\n      tmp_vel += r_ij * (pressure(j_particle) - pressure(i_particle)) * weightForGradientPressure(r_ij) / r_ij.squaredNorm();\n    }\n    if (dimension == 2) {\n      tmp_vel(2) = 0;\n      tensor(2, 2) = 1.0;\n    }\n    if (tensor.determinant() > 1.0e-10) {\n      correction_velocity.col(i_particle) -= tensor.inverse() * tmp_vel * timer.getCurrentDeltaTime() / (initial_particle_number_density * condition_.mass_density);\n      ++tensor_count;\n    } else {\n      correction_velocity.col(i_particle) -= tmp_vel * dimension * timer.getCurrentDeltaTime() / (initial_particle_number_density * condition_.mass_density);\n      ++not_tensor_count;\n      // std::cout << abs(tensor.determinant()) << std::endl <<  tensor << std::endl;\n    }\n  }\n  std::cout << \"Tensor: \" << tensor_count << \", Not Tensor: \" << not_tensor_count << std::endl;\n\n  temporary_velocity += correction_velocity;\n}\n\nvoid Particles::updateVelocityAndPosition() {\n  velocity = temporary_velocity;\n  position = temporary_position;\n}\n\nvoid Particles::checkSurfaceParticles() {\n  for(int i = 0; i < getSize(); ++i) {\n    if (particle_types(i) == ParticleType::NORMAL || particle_types(i) == ParticleType::WALL\n        || particle_types(i) == ParticleType::INFLOW) {\n      if (particle_number_density(i) < condition_.surface_threshold_pnd * initial_particle_number_density\n              && neighbor_particles(i) < condition_.surface_threshold_number * initial_neighbor_particles) {\n        boundary_types(i) = BoundaryType::SURFACE;\n      } else {\n        boundary_types(i) = BoundaryType::INNER;\n      }\n    } else {\n      boundary_types(i) = BoundaryType::OTHERS;\n    }\n  }\n}\n\nvoid Particles::checkSurfaceParticlesRemovingIsolated() {\n  for(int i = 0; i < getSize(); ++i) {\n    if (particle_types(i) == ParticleType::NORMAL || particle_types(i) == ParticleType::WALL\n        || particle_types(i) == ParticleType::INFLOW) {\n      if (particle_number_density(i) < condition_.surface_threshold_pnd * initial_particle_number_density\n              && neighbor_particles(i) < condition_.surface_threshold_number * initial_neighbor_particles) {\n        boundary_types(i) = BoundaryType::SURFACE;\n      } else {\n        if (neighbor_particles(i) <= 3) boundary_types(i) = BoundaryType::SURFACE;\n        else boundary_types(i) = BoundaryType::INNER;\n      }\n    } else {\n      boundary_types(i) = BoundaryType::OTHERS;\n    }\n  }\n}\n\nvoid Particles::giveCollisionRepulsionForce() {\n  giveCollisionRepulsionForce(condition_.collision_influence, condition_.restitution_coefficent);\n}\n\nvoid Particles::giveCollisionRepulsionForce(double influence_ratio, double restitution_coefficient) {\n  Grid grid(influence_ratio * condition_.average_distance, temporary_position, boundary_types.array() != BoundaryType::OTHERS, condition_.dimension);\n  Eigen::Matrix3Xd impulse_vel = Eigen::MatrixXd::Zero(3, size);\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) != ParticleType::NORMAL) continue;\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) continue;\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    for (int j_particle : neighbors) {\n      if (boundary_types(j_particle) == BoundaryType::OTHERS) continue;\n      Eigen::Vector3d n_ij = (temporary_position.col(j_particle) - temporary_position.col(i_particle)).normalized();\n      Eigen::Vector3d u_ij = temporary_velocity.col(j_particle) - temporary_velocity.col(i_particle);\n      impulse_vel.col(i_particle) += n_ij * u_ij.dot(n_ij) * (restitution_coefficient + 1) / 2;\n    }\n  }\n  temporary_velocity += impulse_vel;\n}\n\nvoid Particles::shiftParticles(double influence_ratio, double alpha) {\n  double influence_radius = influence_ratio * condition_.average_distance;\n  Grid grid(influence_radius, temporary_position, particle_types.array() != ParticleType::GHOST, condition_.dimension);\n  Eigen::Matrix3Xd shift_vec = Eigen::MatrixXd::Zero(3, size);\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (particle_types(i_particle) != ParticleType::NORMAL) continue;\n    if (boundary_types(i_particle) == BoundaryType::OTHERS) continue;\n    Grid::Neighbors neighbors;\n    grid.getNeighbors(i_particle, neighbors);\n    for (int j_particle : neighbors) {\n      if (particle_types(j_particle) == ParticleType::GHOST) continue;\n      Eigen::Vector3d r_ij = temporary_position.col(j_particle) - temporary_position.col(i_particle);\n      shift_vec.col(i_particle) += r_ij * weightStandard(r_ij, influence_radius) * influence_radius / r_ij.squaredNorm();\n    }\n  }\n  temporary_position += shift_vec * alpha * condition_.average_distance;\n}\n\ndouble Particles::weightForParticleNumberDensity(const Eigen::Vector3d& vec) const {\n  return weightStandard(vec, condition_.pnd_weight_radius);\n}\n\ndouble Particles::weightForGradientPressure(const Eigen::Vector3d& vec) const {\n  return weightStandard(vec, condition_.gradient_radius);\n}\n\ndouble Particles::weightForLaplacianPressure(const Eigen::Vector3d& vec) const {\n  return weightStandard(vec, condition_.laplacian_pressure_weight_radius);\n}\n\ndouble Particles::weightForLaplacianViscosity(const Eigen::Vector3d& vec) const {\n  return weightStandard(vec, condition_.laplacian_viscosity_weight_radius);\n}\n\nvoid Particles::showParticlesInfo() {\n  int inner = 0;\n  int surface = 0;\n  int ghost = 0;\n  for (int i_particle = 0; i_particle < size; ++i_particle) {\n    if (boundary_types(i_particle) == BoundaryType::INNER) ++inner;\n    if (boundary_types(i_particle) == BoundaryType::SURFACE) ++surface;\n    if (particle_types(i_particle) == ParticleType::GHOST) ++ghost;\n  }\n  std::cout << \"Particles - \"\n            << \"inners: \" << inner << \", surfaces: \" << surface\n            << \", others: \" << size - (inner + surface) << \" (ghosts: \" << ghost << \")\" << std::endl;\n}\n\n} // namespace tiny_mps", "meta": {"hexsha": "bba7f6ec62222e6081cfde9b6b4ead43e73e48d8", "size": 45629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/particles.cpp", "max_stars_repo_name": "rubensamarojr/TinyMPS", "max_stars_repo_head_hexsha": "975a92f4f1a86e8c2bd844fa26684e582495efb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T22:10:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T22:10:30.000Z", "max_issues_repo_path": "src/particles.cpp", "max_issues_repo_name": "rubensamarojr/TinyMPS", "max_issues_repo_head_hexsha": "975a92f4f1a86e8c2bd844fa26684e582495efb9", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "rubensamarojr/TinyMPS", "max_forks_repo_head_hexsha": "975a92f4f1a86e8c2bd844fa26684e582495efb9", "max_forks_repo_licenses": ["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.0434353406, "max_line_length": 182, "alphanum_fraction": 0.6869753885, "num_tokens": 11776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861801254413975, "lm_q2_score": 0.022286185823328388, "lm_q1q2_score": 0.008660813241851261}}
{"text": "#pragma once\n\n#include <string>\n#include <vector>\n#include <iostream>\n#include <boost/unordered_map.hpp>\n#include <boost/algorithm/string.hpp>\n#include <math.h>\n\n#include \"query.hpp\"\n#include \"data_statistic.hpp\"\n#include \"mymath.hpp\"\n#include \"timer.hpp\"\n\nusing namespace std;\n\n#define COST_THRESHOLD 350\n\nstruct plan {\n  double cost;      // now min cost\n  vector<int64_t> orders; // now best orders\n  double result_num;     // record intermediate results\n};\n\nstruct select_record{\n  int p;\n  int d;\n  double v;\n  bool operator > (const select_record & other) const {\n    return v > other.v;\n  }\n  bool operator < (const select_record & other) const {\n    return v < other.v;\n  }\n  bool operator == (const select_record & other) const {\n    return v == other.v;\n  }\n};\n\ntemplate <class T>\nclass Minimum_maintenance {\n  private:\n    T * _stack[2]; // 0 store Descending sequence, 1 store other's\n    int _iter[2];    // store iter\n    int * _order;    // for push and pop\n    int * _fakedeepcopy ;\n  public:\n    Minimum_maintenance(){\n      cout<<\"NOT SUPPORT\"<<endl;\n      assert(0);\n    }\n    Minimum_maintenance(int s){\n      if(s < 1)//protect\n        s = 1;\n      _iter[0] = 0;\n      _iter[1] = 0;\n      _stack[0] = new T[s];\n      _stack[1] = new T[s];\n      _order = new int[s];\n      //cout<<\"NEW    [] +++++++++++++++++++\"<<endl;\n    }\n    Minimum_maintenance(const Minimum_maintenance& copy){\n      _stack[0]   = copy._stack[0];\n      _stack[1]   = copy._stack[1];\n      _iter [0]   = copy._iter [0];\n      _iter [1]   = copy._iter [1];\n      _order      = copy._order;\n    }\n    ~Minimum_maintenance(){\n      delete [] _stack[0];\n      delete [] _stack[1];\n      delete [] _order;\n      //cout<<\"DELETE [] -------------------\"<<endl;\n    }\n    void push(const T & ms){\n      int i;\n      if(_iter[0] == 0 || _stack[0][_iter[0] - 1] > ms){\n        i = 0;\n      }else{\n        i = 1;\n      }\n      _stack[i][_iter[i]] = ms;\n\n      _order[_iter[0]+_iter[1]] = i;\n      _iter[i] ++ ;\n    }\n    void pop(){\n      if(_iter[0]+_iter[1]){\n        _iter[_order[ _iter[0] + _iter[1] - 1 ]]--;\n      }\n    }\n    bool top(T & ms){\n      if(!(_iter[0]+_iter[1]))\n        return false;\n      int o = _order[ _iter[0] + _iter[1] - 1];\n      ms = _stack[0][ _iter[0] - 1];\n      return true;\n    }\n    bool const empty(){\n      return _iter[0] == 0;\n    }\n};\n\nclass Planner {\n    // members\n    data_statistic * statistic ;\n    vector<int64_t> triples;\n    double min_cost;\n    vector<int64_t> path;\n    bool is_empty;            // help identify empty queries\n\n    // for dfs\n    vector<int64_t> min_path;\n    int _chains_size_div_4 ;\n    int * min_select_record ;\n    unordered_map<int, shared_ptr<Minimum_maintenance<select_record>> > * min_select;\n\n    // store all orders for DP\n    vector<int> subgraph[11]; // for 2^10 all orders\n\n    // functions\n    // dfs traverse , traverse all the valid orders\n    bool com_traverse(unsigned int pt_bits, double cost, double pre_results) {\n      if(pt_bits == ( 1 << _chains_size_div_4 ) - 1){\n        //cout << \"estimated cost : \" << cost << endl;\n        bool ctn = true;\n        if (min_cost == std::numeric_limits<double>::max() && cost < COST_THRESHOLD && (path[0] >= (1 << NBITS_IDX)) ) {\n          ctn = false;  // small query\n          cout << \"small query and use heuristic.\\n\";\n        }\n        if (cost < min_cost) {\n          min_cost = cost;\n          min_path = path;\n        }\n        return ctn;\n      }\n      for(int pt_pick = 0; pt_pick < _chains_size_div_4; pt_pick++){\n        if( pt_bits & ( 1 << pt_pick ) )\n          continue ;\n        int i = 4 * pt_pick;\n        double add_cost = 0;\n        int o1 = triples[i];\n        int p = triples[i+1];\n        int d = triples[i+2];\n        int o2 = triples[i+3];\n        if (path.size() == 0) {\n          if (o1 < 0 && o2 < 0) {\n            //continue;\n            // use index vertex\n            path.push_back(p);\n            path.push_back(0);\n            path.push_back(IN);\n            path.push_back(o1);\n            add_cost = double(statistic->global_pscount[p]) / statistic->world->size(); //find subjects\n            // next iteration\n            //cout << \"pick : \" << o1 << \" \" << p << \" \" << d << \" \" << o2 << endl;\n            //cout << \"add_cost : \" << add_cost << endl;\n            double new_cost = cost + add_cost;\n            if (new_cost > min_cost) {\n              path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n              continue;\n            }\n            double select_num_s = (double)statistic->global_pscount[p];\n            select_record srs = {p,d,select_num_s};\n            (*min_select)[o1] = std::unique_ptr<Minimum_maintenance<select_record> > \n              ( new Minimum_maintenance<select_record>(2 * _chains_size_div_4));\n            (*min_select)[o1]->push(srs);\n            bool ctn = com_traverse(pt_bits, new_cost, add_cost);\n            (*min_select)[o1]->pop();\n            if (!ctn) return ctn;\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n            // different direction\n            path.push_back(p);\n            path.push_back(0);\n            path.push_back(OUT);\n            path.push_back(o2);\n            add_cost = double(statistic->global_pocount[p]) / statistic->world->size(); //find objects\n            // next iteration\n            //cout << \"pick : \" << o1 << \" \" << p << \" \" << d << \" \" << o2 << endl;\n            //cout << \"add_cost : \" << add_cost << endl;\n            new_cost = cost + add_cost;\n            if (new_cost > min_cost) {\n              path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n              continue;\n            }\n            double select_num_o = (double)statistic->global_pocount[p];\n            select_record sro = {p,IN,select_num_o};\n            (*min_select)[o2] = std::unique_ptr<Minimum_maintenance<select_record> > \n              ( new Minimum_maintenance<select_record> (2 * _chains_size_div_4));\n            (*min_select)[o2]->push(sro);\n            ctn = com_traverse(pt_bits, new_cost, add_cost);\n            (*min_select)[o2]->pop();\n            if (!ctn) return ctn;\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n          }\n          if (o1 > 0) {\n            path.push_back(o1);\n            path.push_back(p);\n            path.push_back(d);\n            path.push_back(o2);\n            add_cost = double(statistic->global_ptcount[p]) / statistic->global_pscount[p];\n\n            // next iteration\n            //cout << \"pick : \" << o1 << \" \" << p << \" \" << d << \" \" << o2 << endl;\n            //cout << \"add_cost : \" << add_cost << endl;\n            double new_cost = cost + add_cost;\n            if (new_cost > min_cost) {\n              path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n              continue;\n            }\n            new_add_selectivity(o1, p, o2);\n            bool ctn = com_traverse(pt_bits | (1 << pt_pick), new_cost, add_cost);\n            unadd_selectivity();\n            if (!ctn) return ctn;\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          } else if (o2 > 0) {\n            path.push_back(o2);\n            path.push_back(p); \n            path.push_back(IN);\n            path.push_back(o1); \n            // for type triples\n            if (p == TYPE_ID) {\n              add_cost = statistic->global_pscount[o2];\n              //cout << \"type \" << o2 << \" : \" << add_cost << endl;\n            } else { // normal triples\n              add_cost = double(statistic->global_ptcount[p]) / statistic->global_pocount[p];\n            }\n\n            // next iteration\n            //cout << \"pick : \" << o1 << \" \" << p << \" \" << d << \" \" << o2 << endl;\n            //cout << \"add_cost : \" << add_cost << endl;\n            double new_cost = cost + add_cost;\n            if (new_cost > min_cost) {\n              path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n              continue;\n            }\n            new_add_selectivity(o1, p, o2);\n            bool ctn = com_traverse(pt_bits | (1 << pt_pick), new_cost, add_cost);\n            unadd_selectivity();\n            if (!ctn) return ctn;\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          }\n        } else {\n          if (min_select->find(o1) != min_select->end() && !(*min_select)[o1]->empty()) {\n            path.push_back(o1);\n            path.push_back(p);\n            path.push_back(d);\n            path.push_back(o2);\n            double prune_result;\n            select_record sr ;\n            if(!(*min_select)[o1]->top(sr))\n              cout<<\"ERROR o1 on .top\\n\";\n            int pre_p = sr.p;\n            int pre_d = sr.d;\n            // prune based on correlation and constant\n            if (p == TYPE_ID && o2 > 0) {\n              prune_result = com_prune(pre_results, pre_p, pre_d, o2, OUT);\n              add_cost = prune_result;\n            } else if (o2 >= 0){\n              prune_result = com_prune(pre_results, pre_p, pre_d, p, OUT);\n              prune_result = double(prune_result) / statistic->global_pocount[p];\n              add_cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pscount[p]);\n            } else {\n              prune_result = com_prune(pre_results, pre_p, pre_d, p, OUT);\n              add_cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pscount[p]);\n            }\n\n            // next iteration\n            //cout << \"pick : \" << o1 << \" \" << p << \" \" << d << \" \" << o2 << endl;\n            //cout << \"add_cost : \" << add_cost << endl;\n            double new_cost = cost + add_cost;\n            if (new_cost > min_cost) {\n              path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n              continue;\n            }\n            new_add_selectivity(o1, p, o2);\n            bool ctn = com_traverse(pt_bits | (1 << pt_pick), new_cost, add_cost);\n            unadd_selectivity();\n            if (!ctn) return ctn; \n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          }\n          if (min_select->find(o2) != min_select->end() && !(*min_select)[o2]->empty() ) {\n            path.push_back(o2);\n            path.push_back(p);\n            path.push_back(IN);\n            path.push_back(o1);\n            double prune_result;\n            select_record sr ;\n            if(!(*min_select)[o2]->top(sr))\n              cout<<\"ERROR o2 on .top\\n\";            \n            int pre_p = sr.p;\n            int pre_d = sr.d;\n            // prune based on correlation and constant\n            prune_result = com_prune(pre_results, pre_p, pre_d, p, IN);\n            if (o1 >= 0) {\n              prune_result = double(prune_result) / statistic->global_pscount[p];\n            }\n            add_cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pocount[p]);\n\n            // next iteration\n            //cout << \"pick : \" << o1 << \" \" << p << \" \" << d << \" \" << o2 << endl;\n            //cout << \"add_cost : \" << add_cost << endl;\n            double new_cost = cost + add_cost;\n            if (new_cost > min_cost) {\n              path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n              continue;\n            }\n            new_add_selectivity(o1, p, o2);\n            bool ctn = com_traverse(pt_bits | (1 << pt_pick), new_cost, add_cost);\n            unadd_selectivity();\n            if (!ctn) return ctn;\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          }\n        }\n      }\n\n      return true;\n    }\n\n    // dynamic programming planner\n    void dp_plan() {\n      int count = triples.size() / 4; // number of triples\n      int size = pow(2,count);    // size of DP state\n\n      // initial the DP array\n      plan *state = new plan[size];\n      plan initial;\n      initial.cost = std::numeric_limits<double>::max();\n      initial.result_num = 0;\n      state[0].cost = 0;\n      state[0].result_num = 0;\n      for (int i = 1; i < size; i++)\n        state[i] = initial;\n\n      //cout << \"count:\" << count << \" size : \" << size << endl;\n      // DP\n      for (int i = 1; i < count+1; i++) {\n        for (int k = 0,klimit=subgraph[i].size() ; k < klimit; k++) {\n          int bit_state = subgraph[i][k];\n          if (bit_state >= size) continue;\n          plan& best_plan = state[bit_state];\n          int best_m = -1;  // record best one\n          int best_dir = OUT;\n          // f[i][x] = min {f[i-1][x1] + cost, ...}\n          // to compute from all the i-1 state\n          for (int m = 0; m < count; m++) {\n            if ((bit_state & (1 << m)) > 0) {\n              int son_state = bit_state ^ (1 << m);\n              double pre_cost = state[son_state].cost;\n              if (pre_cost == std::numeric_limits<double>::max()) continue;  // previous order invalid\n              double pre_results = state[son_state].result_num;\n              vector<pair<double, int> > cost_dir;\n              cost_add(pre_results, son_state, m*4, cost_dir);\n              if (cost_dir.size() == 0) continue;  // order invalid\n              //cout << \"pre_results : \" << pre_results << endl;\n              if (cost_dir.size() == 1) {  // one direction\n                double new_cost = cost_dir[0].first + pre_cost;\n                //cout << \"new_cost : \" << new_cost << endl;\n                if (best_plan.cost > new_cost) {\n                  best_plan.cost = new_cost;\n                  best_plan.result_num = cost_dir[0].first;\n                  best_plan.orders = state[son_state].orders;\n                  best_m = m;\n                  best_dir = cost_dir[0].second;\n                }\n              } else if (cost_dir.size() == 2) { // both direction\n                double new_cost0 = cost_dir[0].first + pre_cost;\n                double new_cost1 = cost_dir[1].first + pre_cost;\n                //cout << \"new_cost0 : \" << new_cost0 << endl;\n                //cout << \"new_cost1 : \" << new_cost1 << endl;\n                if (new_cost0 < new_cost1) {\n                  if (best_plan.cost > new_cost0) {\n                    best_plan.cost = new_cost0;\n                    best_plan.result_num = cost_dir[0].first;\n                    best_plan.orders = state[son_state].orders;\n                    best_m = m;\n                    best_dir = cost_dir[0].second;\n                  }\n                } else {\n                  if (best_plan.cost > new_cost1) {\n                    best_plan.cost = new_cost1;\n                    best_plan.result_num = cost_dir[1].first;\n                    best_plan.orders = state[son_state].orders;\n                    best_m = m;\n                    best_dir = cost_dir[1].second;\n                  }\n                }\n                // if i == 1 then is index vertex\n                // best_m = -1\n                // push something\n                if (i == 1) {\n                  best_m = -1;\n                  int vertex1,vertex2;\n                  if (best_dir == OUT) {\n                    vertex1 = triples[4*m + 3];\n                    vertex2 = triples[4*m];\n                  }\n                  else {\n                    vertex1 = triples[4*m];\n                    vertex2 = triples[4*m + 3];\n                  }\n                  // push index execution\n                  best_plan.orders.push_back(triples[4*m+1]);\n                  best_plan.orders.push_back(0);\n                  best_plan.orders.push_back(best_dir);\n                  best_plan.orders.push_back(vertex1);\n                  // push the other direction\n                  best_plan.orders.push_back(vertex1);\n                  best_plan.orders.push_back(triples[4*m+1]);\n                  best_plan.orders.push_back(1-best_dir);\n                  best_plan.orders.push_back(vertex2);\n                  best_plan.result_num = statistic->global_ptcount[triples[4*m+1]]; // revise the result num\n                }\n\n              }\n            }\n          }\n          // already find the best order\n          if (best_m >= 0) {\n            if (best_dir == OUT) {\n              best_plan.orders.push_back(triples[4*best_m]);\n              best_plan.orders.push_back(triples[4*best_m+1]);\n              best_plan.orders.push_back(triples[4*best_m+2]);\n              best_plan.orders.push_back(triples[4*best_m+3]);\n            } else {\n              best_plan.orders.push_back(triples[4*best_m+3]);\n              best_plan.orders.push_back(triples[4*best_m+1]);\n              best_plan.orders.push_back(IN);\n              best_plan.orders.push_back(triples[4*best_m]);\n            }\n          }\n\n        }\n      }\n      cout << \"DP query planning is finished.\\n\";\n\n      // state[size - 1] has the final best plan\n      min_path = state[size - 1].orders;\n      min_cost = state[size - 1].cost;\n\n    }\n\n    int bitcount(int i) {\n      i = i - ((i >> 1) & 0x55555555);\n      i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n      return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;\n    }\n\n    void cost_add(double pre_results, int bit_set, int next, vector<pair<double, int> >& cost_dir) {\n      unordered_map<int, vector<int> > selec;\n      double cost = 0;\n      for (int i = 0, ilimit = triples.size(); i < ilimit; i = i + 4) {\n        int tmp = i / 4;\n        if ( (bit_set & (0x1 << tmp)) == false ) continue;\n        add_selectivity(selec, triples[i], triples[i+1], triples[i+3]);\n      }\n\n      int o1 = triples[next];\n      int p = triples[next+1];\n      int o2 = triples[next+3];\n\n      // if selec empty\n      if (selec.empty()) { \n        if (o1 < 0 && o2 < 0) {\n          // s < 0 , o < 0, two direction\n          // begin from s\n          cost = double(statistic->global_pscount[p]) / statistic->world->size(); //find subjects\n          cost += statistic->global_ptcount[p];\n          if (cost == 0) cost = 1;\n          cost_dir.push_back(make_pair(cost, IN));\n          // begin from o\n          cost = double(statistic->global_pocount[p]) / statistic->world->size(); //find objects\n          cost += statistic->global_ptcount[p];\n          if (cost == 0) cost = 1;\n          cost_dir.push_back(make_pair(cost, OUT));\n        }\n        if (o1 > 0 && o2 < 0) {\n          // s > 0, o < 0\n          cost = double(statistic->global_ptcount[p]) / statistic->global_pscount[p];\n          cost_dir.push_back(make_pair(cost, OUT));\n        }\n        if (o1 < 0 && o2 > 0) {\n          // s < 0, o > 0\n          if (p == TYPE_ID) {\n            cost = statistic->global_pscount[o2];\n          } else { // normal triples\n            cost = double(statistic->global_ptcount[p]) / statistic->global_pocount[p];\n          }\n          cost_dir.push_back(make_pair(cost, IN));\n        }\n      }\n      // not empty\n      else {\n        if (selec.find(o1) != selec.end()) {\n          // s match previous\n          double prune_result;\n          int pre_p = selec[o1][0];\n          int pre_d = selec[o1][1];\n          if (p == TYPE_ID && o2 > 0) {\n            prune_result = com_prune(pre_results, pre_p, pre_d, o2, OUT);\n            cost = prune_result;\n          } else if (o2 >= 0){\n            prune_result = com_prune(pre_results, pre_p, pre_d, p, OUT);\n            prune_result = double(prune_result) / statistic->global_pocount[p];\n            cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pscount[p]);\n          } else {\n            prune_result = com_prune(pre_results, pre_p, pre_d, p, OUT);\n            cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pscount[p]);\n          }\n          if (cost == 0) cost = 1;\n          cost_dir.push_back(make_pair(cost, OUT));\n        }\n\n        if (selec.find(o2) != selec.end()) {\n          // o match previous\n          double prune_result;\n          int pre_p = selec[o2][0];\n          int pre_d = selec[o2][1];\n          prune_result = com_prune(pre_results, pre_p, pre_d, p, IN);\n          if (o1 >= 0) {\n            prune_result = double(prune_result) / statistic->global_pscount[p];\n          }\n          cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pocount[p]);\n          if (cost == 0) cost = 1;\n          cost_dir.push_back(make_pair(cost, IN));\n        }\n      }\n\n    }\n\n    // prune using correlation estimation\n    double com_prune(double pre_results, int pre_p, int pre_d, int p, int d) {\n      double result_num;\n      double x,y;\n      // handle corner case first\n      if (pre_p == p) {\n        return pre_results;\n      }\n\n      // out out correlation\n      if (pre_d == OUT && d == OUT) {\n        if (pre_p < p){\n          x = double(statistic->global_ppcount[make_pair(pre_p,p)].out_out);\n        } else {\n          x = double(statistic->global_ppcount[make_pair(p,pre_p)].out_out);\n        }\n        y = statistic->global_pscount[pre_p];\n      }\n\n      // in out correlation\n      if (pre_d == IN && d == OUT) {\n        if (pre_p < p){\n          x = double(statistic->global_ppcount[make_pair(pre_p,p)].in_out);\n        } else {\n          x = double(statistic->global_ppcount[make_pair(p,pre_p)].out_in);\n        }\n        y = statistic->global_pocount[pre_p];\n      }\n\n      // in in correlation\n      if (pre_d == IN && d == IN) {\n        if (pre_p < p){\n          x = double(statistic->global_ppcount[make_pair(pre_p,p)].in_in);\n        } else {\n          x = double(statistic->global_ppcount[make_pair(p,pre_p)].in_in);\n        }\n        y = statistic->global_pocount[pre_p];\n      }\n\n      // out in correlation\n      if (pre_d == OUT && d == IN) {\n        if (pre_p < p){\n          x = double(statistic->global_ppcount[make_pair(pre_p,p)].out_in);\n        } else {\n          x = double(statistic->global_ppcount[make_pair(p,pre_p)].in_out);\n        }\n        y = statistic->global_pscount[pre_p];\n      }\n\n      //cout << \"prune ratio (x/y) : \" << x << \" / \" << y  << endl;\n      result_num = pre_results * (x/y);\n      if (x == 0) is_empty = true;\n      return result_num;\n    }\n\n    void new_add_selectivity(int o1, int p, int o2) {\n      if (o1 < 0 && o2 > 0) {\n        double select_num;\n        if (p == TYPE_ID) {\n          select_num = (double)statistic->global_pscount[o2];\n          p = o2;\n        } else {\n          select_num = double(statistic->global_pscount[p]) / statistic->global_pocount[p];\n        }\n        select_record sr = {p,OUT,select_num};\n        if (min_select->find(o1) == min_select->end())\n          (*min_select)[o1] = std::unique_ptr<Minimum_maintenance<select_record> > \n            ( new Minimum_maintenance<select_record> (2 * _chains_size_div_4));\n        (*min_select)[o1]->push(sr);\n        min_select_record[min_select_record[0] + 1] = o1;\n        min_select_record[min_select_record[0] + 2] = 1;\n        min_select_record[0] += 2 ;\n      }else if (o2 < 0 && o1 > 0) {\n        double select_num = double(statistic->global_pocount[p]) / statistic->global_pscount[p];\n        select_record sr = {p,IN,select_num};\n        if (min_select->find(o2) == min_select->end())\n          (*min_select)[o2] = std::unique_ptr<Minimum_maintenance<select_record> > \n            ( new Minimum_maintenance<select_record> (2 * _chains_size_div_4));\n        (*min_select)[o2]->push(sr);\n\n        min_select_record[min_select_record[0] + 1] = o2;\n        min_select_record[min_select_record[0] + 2] = 1;\n        min_select_record[0] += 2 ;\n      }else if (o1 < 0 && o2 < 0) {\n        double select_num_s = statistic->global_pscount[p];\n        double select_num_o = statistic->global_pocount[p];\n        select_record sro1 = {p,OUT,select_num_s};\n        if (min_select->find(o1) == min_select->end())\n          (*min_select)[o1] = std::unique_ptr<Minimum_maintenance<select_record> > \n            ( new Minimum_maintenance<select_record> (2 * _chains_size_div_4));\n        (*min_select)[o1]->push(sro1);\n\n        select_record sro2 = {p,IN,select_num_o};\n        if (min_select->find(o2) == min_select->end())\n          (*min_select)[o2] = std::unique_ptr<Minimum_maintenance<select_record> > \n            ( new Minimum_maintenance<select_record> (2 * _chains_size_div_4));\n        (*min_select)[o2]->push(sro2);\n\n        min_select_record[min_select_record[0] + 1] = o1;\n        min_select_record[min_select_record[0] + 2] = o2;\n        min_select_record[min_select_record[0] + 3] = 2;\n        min_select_record[0] += 3 ;\n      }else{\n        min_select_record[min_select_record[0] + 1] = 0;\n        min_select_record[0] += 1 ;\n      }\n    }\n\n    void unadd_selectivity(){\n      int lastpos = min_select_record[0];\n      if(lastpos == 0)\n        return ;\n      int lastnum = min_select_record[lastpos];\n      assert(lastpos > lastnum);\n      int i;\n      for(i = 1 ; i <= lastnum ; i++){\n        (*min_select)[min_select_record[lastpos - i]]->pop();\n      }\n      min_select_record[0] -= lastnum + 1;\n    }\n\n    void add_selectivity(unordered_map<int, vector<int> >& tmp_selec, int o1, int p, int o2) {\n      if (o1 < 0 && o2 > 0) {\n        int select_num;\n        if (p == TYPE_ID) {\n          select_num = statistic->global_pscount[o2];\n          p = o2;\n        } else {\n          select_num = double(statistic->global_pscount[p]) / statistic->global_pocount[p];\n        }\n        if (tmp_selec.find(o1) == tmp_selec.end()) {\n          tmp_selec[o1].push_back(p);\n          tmp_selec[o1].push_back(OUT);\n          tmp_selec[o1].push_back(select_num);\n        } else {\n          int pre_select_num = tmp_selec[o1][2];\n          if (pre_select_num > select_num) {\n            vector<int> new_tmp;\n            new_tmp.push_back(p);\n            new_tmp.push_back(OUT);\n            new_tmp.push_back(select_num);\n            tmp_selec[o1] = new_tmp;\n          }\n        }\n      }\n      if (o2 < 0 && o1 > 0) {\n        int select_num = double(statistic->global_pocount[p]) / statistic->global_pscount[p];\n        if (tmp_selec.find(o2) == tmp_selec.end()) {\n          tmp_selec[o2].push_back(p);\n          tmp_selec[o2].push_back(IN);\n          tmp_selec[o2].push_back(select_num);\n        } else {\n          int pre_select_num = tmp_selec[o2][2];\n          if (pre_select_num > select_num) {\n            vector<int> new_tmp;\n            new_tmp.push_back(p);\n            new_tmp.push_back(IN);\n            new_tmp.push_back(select_num);\n            tmp_selec[o2] = new_tmp;\n          }\n        }\n      }\n      if (o1 < 0 && o2 < 0) {\n        int select_num_s = statistic->global_pscount[p];\n        int select_num_o = statistic->global_pocount[p];\n        if (tmp_selec.find(o1) == tmp_selec.end()) {\n          tmp_selec[o1].push_back(p);\n          tmp_selec[o1].push_back(OUT);\n          tmp_selec[o1].push_back(select_num_s);\n        } else {\n          int pre_select_num = tmp_selec[o1][2];\n          if (pre_select_num > select_num_s) {\n            vector<int> new_tmp;\n            new_tmp.push_back(p);\n            new_tmp.push_back(OUT);\n            new_tmp.push_back(select_num_s);\n            tmp_selec[o1] = new_tmp;\n          }\n        }\n        if (tmp_selec.find(o2) == tmp_selec.end()) {\n          tmp_selec[o2].push_back(p);\n          tmp_selec[o2].push_back(IN);\n          tmp_selec[o2].push_back(select_num_o);\n        } else {\n          int pre_select_num = tmp_selec[o2][2];\n          if (pre_select_num > select_num_o) {\n            vector<int> new_tmp;\n            new_tmp.push_back(p);\n            new_tmp.push_back(IN);\n            new_tmp.push_back(select_num_o);\n            tmp_selec[o2] = new_tmp;\n          }\n        }\n      }\n    }\n\n    // for testing purpose\n    void get_all_plans(vector<int64_t> triples, unordered_map<int, vector<int> > max_selec,\n        double cost, double pre_results) {\n      if (triples.empty()) {\n        cout << \"estimated cost : \" << cost << endl;\n        if (cost < min_cost) {\n          min_cost = cost;\n          min_path = path;\n        }\n        // record this new order\n        plan new_order;\n        new_order.cost = cost;\n        new_order.orders = path;\n        boost::unordered_map<int,int> convert;\n        for (int i = 0, ilimit = new_order.orders.size(); i < ilimit; i++) {\n          if (new_order.orders[i] < 0 ){\n            if (convert.find(new_order.orders[i]) == convert.end()) {\n              int value =  -1 - convert.size();\n              convert[new_order.orders[i]] = value;\n              new_order.orders[i] = value;\n            } else {\n              new_order.orders[i] = convert[new_order.orders[i]];\n            }\n          }\n        }\n        all_plans.push_back(new_order);\n        return;\n      }\n      for (int i = 0 , ilimit = triples.size(); i < ilimit; i = i+4) {\n        double add_cost = 0;\n        int o1 = triples[i];\n        int p = triples[i+1];\n        int d = triples[i+2];\n        int o2 = triples[i+3];\n        if (path.size() == 0) {\n          if (o1 < 0 && o2 < 0) {\n            //continue;\n            // use index vertex\n            path.push_back(p);\n            path.push_back(0);\n            path.push_back(IN);\n            path.push_back(o1);\n            add_cost = double(statistic->global_pscount[p]) / statistic->world->size(); //find subjects\n            if (add_cost == 0) add_cost = 1;\n            // next iteration\n            double new_cost = cost + add_cost;\n            unordered_map<int, vector<int> > tmp_selec = max_selec;\n            int select_num_s = statistic->global_pscount[p];\n            tmp_selec[o1].push_back(p);\n            tmp_selec[o1].push_back(d);\n            tmp_selec[o1].push_back(select_num_s);\n            get_all_plans(triples, tmp_selec, new_cost, add_cost);\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n            // different direction\n            path.push_back(p);\n            path.push_back(0);\n            path.push_back(OUT);\n            path.push_back(o2);\n            add_cost = double(statistic->global_pocount[p]) / statistic->world->size(); //find objects\n            if (add_cost == 0) add_cost = 1;\n            // next iteration\n            new_cost = cost + add_cost;\n            tmp_selec = max_selec;\n            int select_num_o = statistic->global_pocount[p];\n            tmp_selec[o2].push_back(p);\n            tmp_selec[o2].push_back(IN);\n            tmp_selec[o2].push_back(select_num_o);\n            get_all_plans(triples, tmp_selec, new_cost, add_cost);\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n          }\n          if (o1 > 0) {\n            path.push_back(o1);\n            path.push_back(p);\n            path.push_back(d);\n            path.push_back(o2);\n            double inter_results = 0;\n            add_cost = double(statistic->global_ptcount[p]) / statistic->global_pscount[p];\n            inter_results = double(add_cost) / statistic->world->size();\n\n            // next iteration\n            double new_cost = cost + add_cost;\n            vector<int64_t> tmp = triples;\n            tmp.erase(tmp.begin() + i, tmp.begin() + i + 4);\n            unordered_map<int, vector<int> > tmp_selec = max_selec;\n            add_selectivity(tmp_selec, o1, p, o2);\n            get_all_plans(tmp, tmp_selec, new_cost, inter_results);\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          } else if (o2 > 0) {\n            path.push_back(o2);\n            path.push_back(p); \n            path.push_back(IN);\n            path.push_back(o1); \n            double inter_results = 0;\n            // for type triples\n            if (p == TYPE_ID) {\n              add_cost = double(statistic->global_pscount[o2]) / statistic->world->size();\n              inter_results = add_cost;\n            } else { // normal triples\n              add_cost = double(statistic->global_ptcount[p]) / statistic->global_pocount[p];\n              inter_results = double(add_cost) / statistic->world->size();\n            }\n\n            // next iteration\n            double new_cost = cost + add_cost;\n            vector<int64_t> tmp = triples;\n            tmp.erase(tmp.begin() + i, tmp.begin() + i + 4);\n            unordered_map<int, vector<int> > tmp_selec = max_selec;\n            add_selectivity(tmp_selec, o1, p, o2);\n            get_all_plans(tmp, tmp_selec, new_cost, inter_results);\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          }\n        } else {\n          if (max_selec.find(o1) != max_selec.end()) {\n            path.push_back(o1);\n            path.push_back(p);\n            path.push_back(d);\n            path.push_back(o2);\n            double prune_result;\n            int pre_p = max_selec[o1][0];\n            int pre_d = max_selec[o1][1];\n            // prune based on correlation and constant\n            if (p == TYPE_ID && o2 > 0) {\n              prune_result = com_prune(pre_results, pre_p, pre_d, o2, OUT);\n              add_cost = prune_result;\n            } else if (o2 >= 0){\n              prune_result = com_prune(pre_results, pre_p, pre_d, p, OUT);\n              prune_result = double(prune_result) / statistic->global_pocount[p];\n              add_cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pscount[p]);\n            } else {\n              prune_result = com_prune(pre_results, pre_p, pre_d, p, OUT);\n              add_cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pscount[p]);\n            }\n            if (add_cost == 0) add_cost = 1;\n\n            // next iteration\n            double new_cost = cost + add_cost;\n            vector<int64_t> tmp = triples;\n            tmp.erase(tmp.begin() + i, tmp.begin() + i + 4);\n            unordered_map<int, vector<int> > tmp_selec = max_selec;\n            add_selectivity(tmp_selec, o1, p, o2);\n            get_all_plans(tmp, tmp_selec, new_cost, add_cost);\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          }\n          if (max_selec.find(o2) != max_selec.end()) {\n            path.push_back(o2);\n            path.push_back(p);\n            path.push_back(IN);\n            path.push_back(o1);\n            double prune_result;\n            int pre_p = max_selec[o2][0];\n            int pre_d = max_selec[o2][1];\n            // prune based on correlation and constant\n            prune_result = com_prune(pre_results, pre_p, pre_d, p, IN);\n            if (o1 >= 0) {\n              prune_result = double(prune_result) / statistic->global_pscount[p];\n            }\n            add_cost = prune_result * (double(statistic->global_ptcount[p]) / statistic->global_pocount[p]);\n            if (add_cost == 0) add_cost = 1;\n\n            // next iteration\n            double new_cost = cost + add_cost;\n            vector<int64_t> tmp = triples;\n            tmp.erase(tmp.begin() + i, tmp.begin() + i + 4);\n            unordered_map<int, vector<int> > tmp_selec = max_selec;\n            add_selectivity(tmp_selec, o1, p, o2);\n            get_all_plans(tmp, tmp_selec, new_cost, add_cost);\n            path.pop_back(); path.pop_back(); path.pop_back(); path.pop_back();\n\n          }\n        }\n      }\n    }\n    \npublic:\n    Planner() {\n      for (int i = 0; i < 1024; i++) {\n        int c = bitcount(i);\n        subgraph[c].push_back(i);\n      }\n    }\n\n    void choose_computing_device(request_or_reply& r, data_statistic* statistic){\n        //TODO: write a metrics to use statistic to decide to use GPU or CPU\n        if (r.start_from_index() && global_default_use_gpu_handle) {\n            r.comp_dev = GPU_comp;\n        } else {\n            r.comp_dev = CPU_comp;\n        }\n\n    }\n\n    bool generate_plan(request_or_reply& r, data_statistic* statistic) {\n      this->statistic = statistic;\n      min_path.clear();\n      path.clear();\n      is_empty = false;\n      double cost = 0;\n      min_cost = std::numeric_limits<double>::max();\n      if (min_cost != std::numeric_limits<double>::max()) assert(false);\n\n      uint64_t t_prepare1 = timer::get_usec();\n      // prepare for heuristic\n      for (int i = 0, ilimit = r.cmd_chains.size(); i < ilimit; i = i + 4) {\n        if (r.cmd_chains[i] >= (1 << NBITS_IDX) || r.cmd_chains[i + 3] >= (1 << NBITS_IDX)) {\n          if (i == 0) break;\n          int ta,tb,tc,td;\n          ta = r.cmd_chains[i];\n          tb = r.cmd_chains[i + 1];\n          tc = r.cmd_chains[i + 2];\n          td = r.cmd_chains[i + 3];\n          r.cmd_chains[i] = r.cmd_chains[0];\n          r.cmd_chains[i + 1] = r.cmd_chains[1];\n          r.cmd_chains[i + 2] = r.cmd_chains[2];\n          r.cmd_chains[i + 3] = r.cmd_chains[3];\n          r.cmd_chains[0] = ta;\n          r.cmd_chains[1] = tb;\n          r.cmd_chains[2] = tc;\n          r.cmd_chains[3] = td;\n          break;\n        }\n      }\n      uint64_t t_prepare2 = timer::get_usec();\n      //cout << \"prepare time : \" << t_prepare2 - t_prepare1 << \" us\" << endl;\n\n      uint64_t t_traverse1 = timer::get_usec();\n      this->triples = r.cmd_chains;\n      this->min_select = new unordered_map<int, shared_ptr<Minimum_maintenance<select_record>>>;\n      _chains_size_div_4 = r.cmd_chains.size()/4 ;\n      min_select_record = new int [ 1 + 6 * _chains_size_div_4 ];\n      min_select_record[0] = 0;\n      com_traverse(0, cost, 0);\n      delete [] min_select_record ;\n      delete this->min_select;\n      uint64_t t_traverse2 = timer::get_usec();\n      //cout << \"traverse time : \" << t_traverse2 - t_traverse1 << \" us\" << endl;\n\n      if (is_empty == true) {\n        cout << \"identified empty result query.\" << endl;\n        cout << \"query planning is finished.\" << endl;\n        return false;\n      }\n\n      // check for middle heuristic, swap the direction\n      /*if (min_path[0] == min_path[5]) {\n        int count_s = statistic->global_pscount[min_path[0]];\n        int count_o = statistic->global_pocount[min_path[0]];\n        if ((min_path[2] == 0 && count_s < count_o) || (min_path[2] == 1 && count_s > count_o)) {\n          min_path[2] = 1 - min_path[2];\n          min_path[6] = 1 - min_path[6];\n          min_path[3] = min_path[7];\n          min_path[7] = min_path[4];\n          min_path[4] = min_path[3];\n        }\n      }*/\n\n      uint64_t t_convert1 = timer::get_usec();\n      boost::unordered_map<int,int> convert;\n      for (int i = 0, ilimit = min_path.size(); i < ilimit; i++) {\n        if (min_path[i] < 0 ){\n          if (convert.find(min_path[i]) == convert.end()) {\n            int value =  -1 - convert.size();\n            convert[min_path[i]] = value;\n            min_path[i] = value;\n          } else {\n            min_path[i] = convert[min_path[i]];\n          }\n        }\n      }\n      uint64_t t_convert2 = timer::get_usec();\n      //cout << \"convert time : \" << t_convert2 - t_convert1 << \" us\" << endl;\n\n      //for (int i = 0, ilimit = r.cmd_chains.size(); i < ilimit; i = i + 4) \n      //  cout << \"cmd_chain \" << \" : \" << r.cmd_chains[i] << \" \" \n      //    << r.cmd_chains[i+1] << \" \" \n      //    << r.cmd_chains[i+2] << \" \" \n      //    << r.cmd_chains[i+3] << \" \"\n      //    << \"ps : \" << statistic->global_pscount[r.cmd_chains[i+1]] \n      //    << \" pt : \" << statistic->global_ptcount[r.cmd_chains[i+1]]\n      //    << \" po : \" << statistic->global_pocount[r.cmd_chains[i+1]]\n      //    << endl;\n\n      //for (int i = 0, ilimit = min_path.size(); i < ilimit; i = i + 4)\n      //  cout << \"min_path \" << \" : \" << min_path[i] << \" \"\n      //    << min_path[i+1] << \" \"\n      //    << min_path[i+2] << \" \"\n      //    << min_path[i+3] << endl;\n      cout << \"query planning is finished.\" << endl;\n      cout << \"estimated cost: \" << min_cost << endl;\n\n      r.cmd_chains = min_path;\n      return true; \n\n    }\n\n    bool generate_dp_plan(request_or_reply& r, data_statistic* statistic) {\n      this->statistic = statistic;\n      min_path.clear();\n      min_cost = std::numeric_limits<double>::max();\n      is_empty = false;\n\n      cout << \"using DP query planning.\" << endl;\n      this->triples = r.cmd_chains;\n      dp_plan();\n      //cout << \"min_path size : \" << min_path.size() << endl;\n\n      if (is_empty == true) return false;\n\n      //cout << \"before convert: \" << endl;\n      //for (int i = 0, ilimit = min_path.size(); i < ilimit ; i = i + 4) \n      //  cout << \"min_path \" << \" : \" << min_path[i] << \" \" \n      //    << min_path[i+1] << \" \" \n      //    << min_path[i+2] << \" \" \n      //    << min_path[i+3] << endl;\n\n\n      boost::unordered_map<int,int> convert;\n      for (int i = 0, ilimit = min_path.size(); i < ilimit ; i++) {\n        if (min_path[i] < 0 ){\n          if (convert.find(min_path[i]) == convert.end()) {\n            int value =  -1 - convert.size();\n            convert[min_path[i]] = value;\n            min_path[i] = value;\n          } else {\n            min_path[i] = convert[min_path[i]];\n          }\n        }\n      }\n      //for (int i = 0, ilimit = r.cmd_chains.size(); i < ilimit ; i = i + 4) \n      //  cout << \"cmd_chain \" << \" : \" << r.cmd_chains[i] << \" \" \n      //    << r.cmd_chains[i+1] << \" \" \n      //    << r.cmd_chains[i+2] << \" \" \n      //    << r.cmd_chains[i+3] << \" \"\n      //    << \"ps : \" << statistic->global_pscount[r.cmd_chains[i+1]] \n      //    << \" pt : \" << statistic->global_ptcount[r.cmd_chains[i+1]]\n      //    << \" po : \" << statistic->global_pocount[r.cmd_chains[i+1]]\n      //    << endl;\n      //for (int i = 0, ilimit = min_path.size(); i < ilimit ; i = i + 4) \n      //  cout << \"min_path \" << \" : \" << min_path[i] << \" \" \n      //    << min_path[i+1] << \" \" \n      //    << min_path[i+2] << \" \" \n      //    << min_path[i+3] << endl;\n      cout << \"estimated cost: \" << min_cost << endl;\n\n      r.cmd_chains = min_path;\n      return true; \n    }\n\n    // for test\n    vector<plan> all_plans;\n    void test_planner(request_or_reply& r, data_statistic* statistic) {\n      this->statistic = statistic;\n      min_path.clear();\n      path.clear();\n      all_plans.clear();\n      is_empty = false;\n      double cost = 0;\n      min_cost = std::numeric_limits<double>::max();\n      unordered_map<int, vector<int> > max_selec;\n\n      get_all_plans(r.cmd_chains, max_selec, cost, 0);\n      cout << \"plan space size: \" << all_plans.size() << endl;\n\n      cout << \"get_all_plans is finish.\\n\";\n    }\n\n};\n\n", "meta": {"hexsha": "1841f510f11e7c30cdfdcb6a1e7c90d16eb745a6", "size": 42076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/planner.hpp", "max_stars_repo_name": "WukongGPU/WukongGPU", "max_stars_repo_head_hexsha": "7810ecc1328b21230d448c6e64cc6fbd21f3b089", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-13T02:08:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T07:34:31.000Z", "max_issues_repo_path": "core/planner.hpp", "max_issues_repo_name": "WukongGPU/WukongGPU", "max_issues_repo_head_hexsha": "7810ecc1328b21230d448c6e64cc6fbd21f3b089", "max_issues_repo_licenses": ["Apache-2.0"], "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/planner.hpp", "max_forks_repo_name": "WukongGPU/WukongGPU", "max_forks_repo_head_hexsha": "7810ecc1328b21230d448c6e64cc6fbd21f3b089", "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.1468721668, "max_line_length": 120, "alphanum_fraction": 0.520058941, "num_tokens": 11119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.017712297601560973, "lm_q1q2_score": 0.00864862081138046}}
{"text": "// Copyright 2013, Ji Zhang, Carnegie Mellon University\n// Further contributions copyright (c) 2016, Southwest Research Institute\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 notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    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 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// This is an implementation of the algorithm described in the following paper:\n//   J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time.\n//     Robotics: Science and Systems Conference (RSS). Berkeley, CA, July 2014.\n\n\n#include \"loam_velodyne/BasicLaserMapping.h\"\n#include \"loam_velodyne/nanoflann_pcl.h\"\n#include \"math_utils.h\"\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n\nnamespace loam\n{\n\nusing std::sqrt;\nusing std::fabs;\nusing std::asin;\nusing std::atan2;\nusing std::pow;\n\n\nBasicLaserMapping::BasicLaserMapping(const float& scanPeriod, const size_t& maxIterations) :\n   _scanPeriod(scanPeriod),\n   _stackFrameNum(1),\n   _mapFrameNum(5),\n   _frameCount(0),\n   _mapFrameCount(0),\n   _maxIterations(maxIterations),\n   _deltaTAbort(0.05),\n   _deltaRAbort(0.05),\n   _laserCloudCenWidth(10),\n   _laserCloudCenHeight(5),\n   _laserCloudCenDepth(10),\n   _laserCloudWidth(21),\n   _laserCloudHeight(11),\n   _laserCloudDepth(21),\n   _laserCloudNum(_laserCloudWidth * _laserCloudHeight * _laserCloudDepth),\n   _laserCloudCornerLast(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudSurfLast(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudFullRes(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudCornerStack(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudSurfStack(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudCornerStackDS(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudSurfStackDS(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudSurround(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudSurroundDS(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudCornerFromMap(new pcl::PointCloud<pcl::PointXYZI>()),\n   _laserCloudSurfFromMap(new pcl::PointCloud<pcl::PointXYZI>())\n{\n   // initialize frame counter\n   _frameCount = _stackFrameNum - 1;\n   _mapFrameCount = _mapFrameNum - 1;\n\n   // setup cloud vectors\n   _laserCloudCornerArray.resize(_laserCloudNum);\n   _laserCloudSurfArray.resize(_laserCloudNum);\n   _laserCloudCornerDSArray.resize(_laserCloudNum);\n   _laserCloudSurfDSArray.resize(_laserCloudNum);\n\n   for (size_t i = 0; i < _laserCloudNum; i++)\n   {\n      _laserCloudCornerArray[i].reset(new pcl::PointCloud<pcl::PointXYZI>());\n      _laserCloudSurfArray[i].reset(new pcl::PointCloud<pcl::PointXYZI>());\n      _laserCloudCornerDSArray[i].reset(new pcl::PointCloud<pcl::PointXYZI>());\n      _laserCloudSurfDSArray[i].reset(new pcl::PointCloud<pcl::PointXYZI>());\n   }\n\n   // setup down size filters\n   _downSizeFilterCorner.setLeafSize(0.2, 0.2, 0.2);\n   _downSizeFilterSurf.setLeafSize(0.4, 0.4, 0.4);\n}\n\n\nvoid BasicLaserMapping::transformAssociateToMap()\n{\n   _transformIncre.pos = _transformBefMapped.pos - _transformSum.pos;\n   rotateYXZ(_transformIncre.pos, -(_transformSum.rot_y), -(_transformSum.rot_x), -(_transformSum.rot_z));\n\n   float sbcx = _transformSum.rot_x.sin();\n   float cbcx = _transformSum.rot_x.cos();\n   float sbcy = _transformSum.rot_y.sin();\n   float cbcy = _transformSum.rot_y.cos();\n   float sbcz = _transformSum.rot_z.sin();\n   float cbcz = _transformSum.rot_z.cos();\n\n   float sblx = _transformBefMapped.rot_x.sin();\n   float cblx = _transformBefMapped.rot_x.cos();\n   float sbly = _transformBefMapped.rot_y.sin();\n   float cbly = _transformBefMapped.rot_y.cos();\n   float sblz = _transformBefMapped.rot_z.sin();\n   float cblz = _transformBefMapped.rot_z.cos();\n\n   float salx = _transformAftMapped.rot_x.sin();\n   float calx = _transformAftMapped.rot_x.cos();\n   float saly = _transformAftMapped.rot_y.sin();\n   float caly = _transformAftMapped.rot_y.cos();\n   float salz = _transformAftMapped.rot_z.sin();\n   float calz = _transformAftMapped.rot_z.cos();\n\n   float srx = -sbcx * (salx*sblx + calx * cblx*salz*sblz + calx * calz*cblx*cblz)\n      - cbcx * sbcy*(calx*calz*(cbly*sblz - cblz * sblx*sbly)\n                     - calx * salz*(cbly*cblz + sblx * sbly*sblz) + cblx * salx*sbly)\n      - cbcx * cbcy*(calx*salz*(cblz*sbly - cbly * sblx*sblz)\n                     - calx * calz*(sbly*sblz + cbly * cblz*sblx) + cblx * cbly*salx);\n   _transformTobeMapped.rot_x = -asin(srx);\n\n   float srycrx = sbcx * (cblx*cblz*(caly*salz - calz * salx*saly)\n                          - cblx * sblz*(caly*calz + salx * saly*salz) + calx * saly*sblx)\n      - cbcx * cbcy*((caly*calz + salx * saly*salz)*(cblz*sbly - cbly * sblx*sblz)\n                     + (caly*salz - calz * salx*saly)*(sbly*sblz + cbly * cblz*sblx) - calx * cblx*cbly*saly)\n      + cbcx * sbcy*((caly*calz + salx * saly*salz)*(cbly*cblz + sblx * sbly*sblz)\n                     + (caly*salz - calz * salx*saly)*(cbly*sblz - cblz * sblx*sbly) + calx * cblx*saly*sbly);\n   float crycrx = sbcx * (cblx*sblz*(calz*saly - caly * salx*salz)\n                          - cblx * cblz*(saly*salz + caly * calz*salx) + calx * caly*sblx)\n      + cbcx * cbcy*((saly*salz + caly * calz*salx)*(sbly*sblz + cbly * cblz*sblx)\n                     + (calz*saly - caly * salx*salz)*(cblz*sbly - cbly * sblx*sblz) + calx * caly*cblx*cbly)\n      - cbcx * sbcy*((saly*salz + caly * calz*salx)*(cbly*sblz - cblz * sblx*sbly)\n                     + (calz*saly - caly * salx*salz)*(cbly*cblz + sblx * sbly*sblz) - calx * caly*cblx*sbly);\n   _transformTobeMapped.rot_y = atan2(srycrx / _transformTobeMapped.rot_x.cos(),\n                                      crycrx / _transformTobeMapped.rot_x.cos());\n\n   float srzcrx = (cbcz*sbcy - cbcy * sbcx*sbcz)*(calx*salz*(cblz*sbly - cbly * sblx*sblz)\n                                                  - calx * calz*(sbly*sblz + cbly * cblz*sblx) + cblx * cbly*salx)\n      - (cbcy*cbcz + sbcx * sbcy*sbcz)*(calx*calz*(cbly*sblz - cblz * sblx*sbly)\n                                        - calx * salz*(cbly*cblz + sblx * sbly*sblz) + cblx * salx*sbly)\n      + cbcx * sbcz*(salx*sblx + calx * cblx*salz*sblz + calx * calz*cblx*cblz);\n   float crzcrx = (cbcy*sbcz - cbcz * sbcx*sbcy)*(calx*calz*(cbly*sblz - cblz * sblx*sbly)\n                                                  - calx * salz*(cbly*cblz + sblx * sbly*sblz) + cblx * salx*sbly)\n      - (sbcy*sbcz + cbcy * cbcz*sbcx)*(calx*salz*(cblz*sbly - cbly * sblx*sblz)\n                                        - calx * calz*(sbly*sblz + cbly * cblz*sblx) + cblx * cbly*salx)\n      + cbcx * cbcz*(salx*sblx + calx * cblx*salz*sblz + calx * calz*cblx*cblz);\n   _transformTobeMapped.rot_z = atan2(srzcrx / _transformTobeMapped.rot_x.cos(),\n                                      crzcrx / _transformTobeMapped.rot_x.cos());\n\n   Vector3 v = _transformIncre.pos;\n   rotateZXY(v, _transformTobeMapped.rot_z, _transformTobeMapped.rot_x, _transformTobeMapped.rot_y);\n   _transformTobeMapped.pos = _transformAftMapped.pos - v;\n}\n\n\n\nvoid BasicLaserMapping::transformUpdate()\n{\n   if (0 < _imuHistory.size())\n   {\n      size_t imuIdx = 0;\n\n      while (imuIdx < _imuHistory.size() - 1 && toSec(_laserOdometryTime - _imuHistory[imuIdx].stamp) + _scanPeriod > 0)\n      {\n         imuIdx++;\n      }\n\n      IMUState2 imuCur;\n\n      if (imuIdx == 0 || toSec(_laserOdometryTime - _imuHistory[imuIdx].stamp) + _scanPeriod > 0)\n      {\n         // scan time newer then newest or older than oldest IMU message\n         imuCur = _imuHistory[imuIdx];\n      }\n      else\n      {\n         float ratio = (toSec(_imuHistory[imuIdx].stamp - _laserOdometryTime) - _scanPeriod)\n            / toSec(_imuHistory[imuIdx].stamp - _imuHistory[imuIdx - 1].stamp);\n\n         IMUState2::interpolate(_imuHistory[imuIdx], _imuHistory[imuIdx - 1], ratio, imuCur);\n      }\n\n      _transformTobeMapped.rot_x = 0.998 * _transformTobeMapped.rot_x.rad() + 0.002 * imuCur.pitch.rad();\n      _transformTobeMapped.rot_z = 0.998 * _transformTobeMapped.rot_z.rad() + 0.002 * imuCur.roll.rad();\n   }\n\n   _transformBefMapped = _transformSum;\n   _transformAftMapped = _transformTobeMapped;\n}\n\n\n\nvoid BasicLaserMapping::pointAssociateToMap(const pcl::PointXYZI& pi, pcl::PointXYZI& po)\n{\n   po.x = pi.x;\n   po.y = pi.y;\n   po.z = pi.z;\n   po.intensity = pi.intensity;\n\n   rotateZXY(po, _transformTobeMapped.rot_z, _transformTobeMapped.rot_x, _transformTobeMapped.rot_y);\n\n   po.x += _transformTobeMapped.pos.x();\n   po.y += _transformTobeMapped.pos.y();\n   po.z += _transformTobeMapped.pos.z();\n}\n\n\n\nvoid BasicLaserMapping::pointAssociateTobeMapped(const pcl::PointXYZI& pi, pcl::PointXYZI& po)\n{\n   po.x = pi.x - _transformTobeMapped.pos.x();\n   po.y = pi.y - _transformTobeMapped.pos.y();\n   po.z = pi.z - _transformTobeMapped.pos.z();\n   po.intensity = pi.intensity;\n\n   rotateYXZ(po, -_transformTobeMapped.rot_y, -_transformTobeMapped.rot_x, -_transformTobeMapped.rot_z);\n}\n\n\n\nvoid BasicLaserMapping::transformFullResToMap()\n{\n   // transform full resolution input cloud to map\n   for (auto& pt : *_laserCloudFullRes)\n      pointAssociateToMap(pt, pt);\n}\n\nbool BasicLaserMapping::createDownsizedMap()\n{\n   // create new map cloud according to the input output ratio\n   _mapFrameCount++;\n   if (_mapFrameCount < _mapFrameNum)\n      return false;\n\n   _mapFrameCount = 0;\n\n   // accumulate map cloud\n   _laserCloudSurround->clear();\n   for (auto ind : _laserCloudSurroundInd)\n   {\n      *_laserCloudSurround += *_laserCloudCornerArray[ind];\n      *_laserCloudSurround += *_laserCloudSurfArray[ind];\n   }\n\n   // down size map cloud\n   _laserCloudSurroundDS->clear();\n   _downSizeFilterCorner.setInputCloud(_laserCloudSurround);\n   _downSizeFilterCorner.filter(*_laserCloudSurroundDS);\n   return true;\n}\n\nbool BasicLaserMapping::process(Time const& laserOdometryTime)\n{\n   // skip some frames?!?\n   _frameCount++;\n   if (_frameCount < _stackFrameNum)\n   {\n      return false;\n   }\n   _frameCount = 0;\n   _laserOdometryTime = laserOdometryTime;\n\n   pcl::PointXYZI pointSel;\n\n   // relate incoming data to map\n   transformAssociateToMap();\n\n   for (auto const& pt : _laserCloudCornerLast->points)\n   {\n      pointAssociateToMap(pt, pointSel);\n      _laserCloudCornerStack->push_back(pointSel);\n   }\n\n   for (auto const& pt : _laserCloudSurfLast->points)\n   {\n      pointAssociateToMap(pt, pointSel);\n      _laserCloudSurfStack->push_back(pointSel);\n   }\n\n   pcl::PointXYZI pointOnYAxis;\n   pointOnYAxis.x = 0.0;\n   pointOnYAxis.y = 10.0;\n   pointOnYAxis.z = 0.0;\n   pointAssociateToMap(pointOnYAxis, pointOnYAxis);\n\n   auto const CUBE_SIZE = 50.0;\n   auto const CUBE_HALF = CUBE_SIZE / 2;\n\n   int centerCubeI = int((_transformTobeMapped.pos.x() + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenWidth;\n   int centerCubeJ = int((_transformTobeMapped.pos.y() + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenHeight;\n   int centerCubeK = int((_transformTobeMapped.pos.z() + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenDepth;\n\n   if (_transformTobeMapped.pos.x() + CUBE_HALF < 0) centerCubeI--;\n   if (_transformTobeMapped.pos.y() + CUBE_HALF < 0) centerCubeJ--;\n   if (_transformTobeMapped.pos.z() + CUBE_HALF < 0) centerCubeK--;\n\n   while (centerCubeI < 3)\n   {\n      for (int j = 0; j < _laserCloudHeight; j++)\n      {\n         for (int k = 0; k < _laserCloudDepth; k++)\n         {\n            for (int i = _laserCloudWidth - 1; i >= 1; i--)\n            {\n               const size_t indexA = toIndex(i, j, k);\n               const size_t indexB = toIndex(i - 1, j, k);\n               std::swap(_laserCloudCornerArray[indexA], _laserCloudCornerArray[indexB]);\n               std::swap(_laserCloudSurfArray[indexA], _laserCloudSurfArray[indexB]);\n            }\n         }\n      }\n      centerCubeI++;\n      _laserCloudCenWidth++;\n   }\n\n   while (centerCubeI >= _laserCloudWidth - 3)\n   {\n      for (int j = 0; j < _laserCloudHeight; j++)\n      {\n         for (int k = 0; k < _laserCloudDepth; k++)\n         {\n            for (int i = 0; i < _laserCloudWidth - 1; i++)\n            {\n               const size_t indexA = toIndex(i, j, k);\n               const size_t indexB = toIndex(i + 1, j, k);\n               std::swap(_laserCloudCornerArray[indexA], _laserCloudCornerArray[indexB]);\n               std::swap(_laserCloudSurfArray[indexA], _laserCloudSurfArray[indexB]);\n            }\n         }\n      }\n      centerCubeI--;\n      _laserCloudCenWidth--;\n   }\n\n   while (centerCubeJ < 3)\n   {\n      for (int i = 0; i < _laserCloudWidth; i++)\n      {\n         for (int k = 0; k < _laserCloudDepth; k++)\n         {\n            for (int j = _laserCloudHeight - 1; j >= 1; j--)\n            {\n               const size_t indexA = toIndex(i, j, k);\n               const size_t indexB = toIndex(i, j - 1, k);\n               std::swap(_laserCloudCornerArray[indexA], _laserCloudCornerArray[indexB]);\n               std::swap(_laserCloudSurfArray[indexA], _laserCloudSurfArray[indexB]);\n            }\n         }\n      }\n      centerCubeJ++;\n      _laserCloudCenHeight++;\n   }\n\n   while (centerCubeJ >= _laserCloudHeight - 3)\n   {\n      for (int i = 0; i < _laserCloudWidth; i++)\n      {\n         for (int k = 0; k < _laserCloudDepth; k++)\n         {\n            for (int j = 0; j < _laserCloudHeight - 1; j++)\n            {\n               const size_t indexA = toIndex(i, j, k);\n               const size_t indexB = toIndex(i, j + 1, k);\n               std::swap(_laserCloudCornerArray[indexA], _laserCloudCornerArray[indexB]);\n               std::swap(_laserCloudSurfArray[indexA], _laserCloudSurfArray[indexB]);\n            }\n         }\n      }\n      centerCubeJ--;\n      _laserCloudCenHeight--;\n   }\n\n   while (centerCubeK < 3)\n   {\n      for (int i = 0; i < _laserCloudWidth; i++)\n      {\n         for (int j = 0; j < _laserCloudHeight; j++)\n         {\n            for (int k = _laserCloudDepth - 1; k >= 1; k--)\n            {\n               const size_t indexA = toIndex(i, j, k);\n               const size_t indexB = toIndex(i, j, k - 1);\n               std::swap(_laserCloudCornerArray[indexA], _laserCloudCornerArray[indexB]);\n               std::swap(_laserCloudSurfArray[indexA], _laserCloudSurfArray[indexB]);\n            }\n         }\n      }\n      centerCubeK++;\n      _laserCloudCenDepth++;\n   }\n\n   while (centerCubeK >= _laserCloudDepth - 3)\n   {\n      for (int i = 0; i < _laserCloudWidth; i++)\n      {\n         for (int j = 0; j < _laserCloudHeight; j++)\n         {\n            for (int k = 0; k < _laserCloudDepth - 1; k++)\n            {\n               const size_t indexA = toIndex(i, j, k);\n               const size_t indexB = toIndex(i, j, k + 1);\n               std::swap(_laserCloudCornerArray[indexA], _laserCloudCornerArray[indexB]);\n               std::swap(_laserCloudSurfArray[indexA], _laserCloudSurfArray[indexB]);\n            }\n         }\n      }\n      centerCubeK--;\n      _laserCloudCenDepth--;\n   }\n\n   _laserCloudValidInd.clear();\n   _laserCloudSurroundInd.clear();\n   for (int i = centerCubeI - 2; i <= centerCubeI + 2; i++)\n   {\n      for (int j = centerCubeJ - 2; j <= centerCubeJ + 2; j++)\n      {\n         for (int k = centerCubeK - 2; k <= centerCubeK + 2; k++)\n         {\n            if (i >= 0 && i < _laserCloudWidth &&\n                j >= 0 && j < _laserCloudHeight &&\n                k >= 0 && k < _laserCloudDepth)\n            {\n\n               float centerX = 50.0f * (i - _laserCloudCenWidth);\n               float centerY = 50.0f * (j - _laserCloudCenHeight);\n               float centerZ = 50.0f * (k - _laserCloudCenDepth);\n\n               pcl::PointXYZI transform_pos = (pcl::PointXYZI) _transformTobeMapped.pos;\n\n               bool isInLaserFOV = false;\n               for (int ii = -1; ii <= 1; ii += 2)\n               {\n                  for (int jj = -1; jj <= 1; jj += 2)\n                  {\n                     for (int kk = -1; kk <= 1; kk += 2)\n                     {\n                        pcl::PointXYZI corner;\n                        corner.x = centerX + 25.0f * ii;\n                        corner.y = centerY + 25.0f * jj;\n                        corner.z = centerZ + 25.0f * kk;\n\n                        float squaredSide1 = calcSquaredDiff(transform_pos, corner);\n                        float squaredSide2 = calcSquaredDiff(pointOnYAxis, corner);\n\n                        float check1 = 100.0f + squaredSide1 - squaredSide2\n                           - 10.0f * sqrt(3.0f) * sqrt(squaredSide1);\n\n                        float check2 = 100.0f + squaredSide1 - squaredSide2\n                           + 10.0f * sqrt(3.0f) * sqrt(squaredSide1);\n\n                        if (check1 < 0 && check2 > 0)\n                        {\n                           isInLaserFOV = true;\n                        }\n                     }\n                  }\n               }\n\n               size_t cubeIdx = i + _laserCloudWidth * j + _laserCloudWidth * _laserCloudHeight * k;\n               if (isInLaserFOV)\n               {\n                  _laserCloudValidInd.push_back(cubeIdx);\n               }\n               _laserCloudSurroundInd.push_back(cubeIdx);\n            }\n         }\n      }\n   }\n\n   // prepare valid map corner and surface cloud for pose optimization\n   _laserCloudCornerFromMap->clear();\n   _laserCloudSurfFromMap->clear();\n   for (auto const& ind : _laserCloudValidInd)\n   {\n      *_laserCloudCornerFromMap += *_laserCloudCornerArray[ind];\n      *_laserCloudSurfFromMap += *_laserCloudSurfArray[ind];\n   }\n\n   // prepare feature stack clouds for pose optimization\n   for (auto& pt : *_laserCloudCornerStack)\n      pointAssociateTobeMapped(pt, pt);\n\n   for (auto& pt : *_laserCloudSurfStack)\n      pointAssociateTobeMapped(pt, pt);\n\n   // down sample feature stack clouds\n   _laserCloudCornerStackDS->clear();\n   _downSizeFilterCorner.setInputCloud(_laserCloudCornerStack);\n   _downSizeFilterCorner.filter(*_laserCloudCornerStackDS);\n   size_t laserCloudCornerStackNum = _laserCloudCornerStackDS->size();\n\n   _laserCloudSurfStackDS->clear();\n   _downSizeFilterSurf.setInputCloud(_laserCloudSurfStack);\n   _downSizeFilterSurf.filter(*_laserCloudSurfStackDS);\n   size_t laserCloudSurfStackNum = _laserCloudSurfStackDS->size();\n\n   _laserCloudCornerStack->clear();\n   _laserCloudSurfStack->clear();\n\n   // run pose optimization\n   optimizeTransformTobeMapped();\n\n   // store down sized corner stack points in corresponding cube clouds\n   for (int i = 0; i < laserCloudCornerStackNum; i++)\n   {\n      pointAssociateToMap(_laserCloudCornerStackDS->points[i], pointSel);\n\n      int cubeI = int((pointSel.x + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenWidth;\n      int cubeJ = int((pointSel.y + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenHeight;\n      int cubeK = int((pointSel.z + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenDepth;\n\n      if (pointSel.x + CUBE_HALF < 0) cubeI--;\n      if (pointSel.y + CUBE_HALF < 0) cubeJ--;\n      if (pointSel.z + CUBE_HALF < 0) cubeK--;\n\n      if (cubeI >= 0 && cubeI < _laserCloudWidth &&\n          cubeJ >= 0 && cubeJ < _laserCloudHeight &&\n          cubeK >= 0 && cubeK < _laserCloudDepth)\n      {\n         size_t cubeInd = cubeI + _laserCloudWidth * cubeJ + _laserCloudWidth * _laserCloudHeight * cubeK;\n         _laserCloudCornerArray[cubeInd]->push_back(pointSel);\n      }\n   }\n\n   // store down sized surface stack points in corresponding cube clouds\n   for (int i = 0; i < laserCloudSurfStackNum; i++)\n   {\n      pointAssociateToMap(_laserCloudSurfStackDS->points[i], pointSel);\n\n      int cubeI = int((pointSel.x + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenWidth;\n      int cubeJ = int((pointSel.y + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenHeight;\n      int cubeK = int((pointSel.z + CUBE_HALF) / CUBE_SIZE) + _laserCloudCenDepth;\n\n      if (pointSel.x + CUBE_HALF < 0) cubeI--;\n      if (pointSel.y + CUBE_HALF < 0) cubeJ--;\n      if (pointSel.z + CUBE_HALF < 0) cubeK--;\n\n      if (cubeI >= 0 && cubeI < _laserCloudWidth &&\n          cubeJ >= 0 && cubeJ < _laserCloudHeight &&\n          cubeK >= 0 && cubeK < _laserCloudDepth)\n      {\n         size_t cubeInd = cubeI + _laserCloudWidth * cubeJ + _laserCloudWidth * _laserCloudHeight * cubeK;\n         _laserCloudSurfArray[cubeInd]->push_back(pointSel);\n      }\n   }\n\n   // down size all valid (within field of view) feature cube clouds\n   for (auto const& ind : _laserCloudValidInd)\n   {\n      _laserCloudCornerDSArray[ind]->clear();\n      _downSizeFilterCorner.setInputCloud(_laserCloudCornerArray[ind]);\n      _downSizeFilterCorner.filter(*_laserCloudCornerDSArray[ind]);\n\n      _laserCloudSurfDSArray[ind]->clear();\n      _downSizeFilterSurf.setInputCloud(_laserCloudSurfArray[ind]);\n      _downSizeFilterSurf.filter(*_laserCloudSurfDSArray[ind]);\n\n      // swap cube clouds for next processing\n      _laserCloudCornerArray[ind].swap(_laserCloudCornerDSArray[ind]);\n      _laserCloudSurfArray[ind].swap(_laserCloudSurfDSArray[ind]);\n   }\n\n   transformFullResToMap();\n   _downsizedMapCreated = createDownsizedMap();\n\n   return true;\n}\n\n\nvoid BasicLaserMapping::updateIMU(IMUState2 const& newState)\n{\n   _imuHistory.push(newState);\n}\n\nvoid BasicLaserMapping::updateOdometry(double pitch, double yaw, double roll, double x, double y, double z)\n{\n   _transformSum.rot_x = pitch;\n   _transformSum.rot_y = yaw;\n   _transformSum.rot_z = roll;\n\n   _transformSum.pos.x() = float(x);\n   _transformSum.pos.y() = float(y);\n   _transformSum.pos.z() = float(z);\n}\n\nvoid BasicLaserMapping::updateOdometry(Twist const& twist)\n{\n   _transformSum = twist;\n}\n\nnanoflann::KdTreeFLANN<pcl::PointXYZI> kdtreeCornerFromMap;\nnanoflann::KdTreeFLANN<pcl::PointXYZI> kdtreeSurfFromMap;\n\nvoid BasicLaserMapping::optimizeTransformTobeMapped()\n{\n   if (_laserCloudCornerFromMap->size() <= 10 || _laserCloudSurfFromMap->size() <= 100)\n      return;\n\n   pcl::PointXYZI pointSel, pointOri, /*pointProj, */coeff;\n\n   std::vector<int> pointSearchInd(5, 0);\n   std::vector<float> pointSearchSqDis(5, 0);\n\n   kdtreeCornerFromMap.setInputCloud(_laserCloudCornerFromMap);\n   kdtreeSurfFromMap.setInputCloud(_laserCloudSurfFromMap);\n\n   Eigen::Matrix<float, 5, 3> matA0;\n   Eigen::Matrix<float, 5, 1> matB0;\n   Eigen::Vector3f matX0;\n   Eigen::Matrix3f matA1;\n   Eigen::Matrix<float, 1, 3> matD1;\n   Eigen::Matrix3f matV1;\n\n   matA0.setZero();\n   matB0.setConstant(-1);\n   matX0.setZero();\n\n   matA1.setZero();\n   matD1.setZero();\n   matV1.setZero();\n\n   bool isDegenerate = false;\n   Eigen::Matrix<float, 6, 6> matP;\n\n   size_t laserCloudCornerStackNum = _laserCloudCornerStackDS->size();\n   size_t laserCloudSurfStackNum = _laserCloudSurfStackDS->size();\n\n   for (size_t iterCount = 0; iterCount < _maxIterations; iterCount++)\n   {\n      _laserCloudOri.clear();\n      _coeffSel.clear();\n\n      for (int i = 0; i < laserCloudCornerStackNum; i++)\n      {\n         pointOri = _laserCloudCornerStackDS->points[i];\n         pointAssociateToMap(pointOri, pointSel);\n         kdtreeCornerFromMap.nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);\n\n         if (pointSearchSqDis[4] < 1.0)\n         {\n            Vector3 vc(0, 0, 0);\n\n            for (int j = 0; j < 5; j++)\n               vc += Vector3(_laserCloudCornerFromMap->points[pointSearchInd[j]]);\n            vc /= 5.0;\n\n            Eigen::Matrix3f mat_a;\n            mat_a.setZero();\n\n            for (int j = 0; j < 5; j++)\n            {\n               Vector3 a = Vector3(_laserCloudCornerFromMap->points[pointSearchInd[j]]) - vc;\n\n               mat_a(0, 0) += a.x() * a.x();\n               mat_a(0, 1) += a.x() * a.y();\n               mat_a(0, 2) += a.x() * a.z();\n               mat_a(1, 1) += a.y() * a.y();\n               mat_a(1, 2) += a.y() * a.z();\n               mat_a(2, 2) += a.z() * a.z();\n            }\n            matA1 = mat_a / 5.0;\n\n            Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> esolver(matA1);\n            matD1 = esolver.eigenvalues().real();\n            matV1 = esolver.eigenvectors().real();\n\n            if (matD1(0, 2) > 3 * matD1(0, 1))\n            {\n\n               float x0 = pointSel.x;\n               float y0 = pointSel.y;\n               float z0 = pointSel.z;\n               float x1 = vc.x() + 0.1 * matV1(0, 2);\n               float y1 = vc.y() + 0.1 * matV1(1, 2);\n               float z1 = vc.z() + 0.1 * matV1(2, 2);\n               float x2 = vc.x() - 0.1 * matV1(0, 2);\n               float y2 = vc.y() - 0.1 * matV1(1, 2);\n               float z2 = vc.z() - 0.1 * matV1(2, 2);\n\n               float a012 = sqrt(((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))\n                                 * ((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))\n                                 + ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))\n                                 * ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))\n                                 + ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))\n                                 * ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1)));\n\n               float l12 = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2));\n\n               float la = ((y1 - y2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))\n                           + (z1 - z2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))) / a012 / l12;\n\n               float lb = -((x1 - x2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))\n                            - (z1 - z2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12;\n\n               float lc = -((x1 - x2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))\n                            + (y1 - y2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12;\n\n               float ld2 = a012 / l12;\n\n//                // TODO: Why writing to a variable that's never read? Maybe it should be used afterwards?\n//                pointProj = pointSel;\n//                pointProj.x -= la * ld2;\n//                pointProj.y -= lb * ld2;\n//                pointProj.z -= lc * ld2;\n\n               float s = 1 - 0.9f * fabs(ld2);\n\n               coeff.x = s * la;\n               coeff.y = s * lb;\n               coeff.z = s * lc;\n               coeff.intensity = s * ld2;\n\n               if (s > 0.1)\n               {\n                  _laserCloudOri.push_back(pointOri);\n                  _coeffSel.push_back(coeff);\n               }\n            }\n         }\n      }\n\n      for (int i = 0; i < laserCloudSurfStackNum; i++)\n      {\n         pointOri = _laserCloudSurfStackDS->points[i];\n         pointAssociateToMap(pointOri, pointSel);\n         kdtreeSurfFromMap.nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);\n\n         if (pointSearchSqDis[4] < 1.0)\n         {\n            for (int j = 0; j < 5; j++)\n            {\n               matA0(j, 0) = _laserCloudSurfFromMap->points[pointSearchInd[j]].x;\n               matA0(j, 1) = _laserCloudSurfFromMap->points[pointSearchInd[j]].y;\n               matA0(j, 2) = _laserCloudSurfFromMap->points[pointSearchInd[j]].z;\n            }\n            matX0 = matA0.colPivHouseholderQr().solve(matB0);\n\n            float pa = matX0(0, 0);\n            float pb = matX0(1, 0);\n            float pc = matX0(2, 0);\n            float pd = 1;\n\n            float ps = sqrt(pa * pa + pb * pb + pc * pc);\n            pa /= ps;\n            pb /= ps;\n            pc /= ps;\n            pd /= ps;\n\n            bool planeValid = true;\n            for (int j = 0; j < 5; j++)\n            {\n               if (fabs(pa * _laserCloudSurfFromMap->points[pointSearchInd[j]].x +\n                        pb * _laserCloudSurfFromMap->points[pointSearchInd[j]].y +\n                        pc * _laserCloudSurfFromMap->points[pointSearchInd[j]].z + pd) > 0.2)\n               {\n                  planeValid = false;\n                  break;\n               }\n            }\n\n            if (planeValid)\n            {\n               float pd2 = pa * pointSel.x + pb * pointSel.y + pc * pointSel.z + pd;\n\n               //                // TODO: Why writing to a variable that's never read? Maybe it should be used afterwards?\n               //                pointProj = pointSel;\n               //                pointProj.x -= pa * pd2;\n               //                pointProj.y -= pb * pd2;\n               //                pointProj.z -= pc * pd2;\n\n               float s = 1 - 0.9f * fabs(pd2) / sqrt(calcPointDistance(pointSel));\n\n               coeff.x = s * pa;\n               coeff.y = s * pb;\n               coeff.z = s * pc;\n               coeff.intensity = s * pd2;\n\n               if (s > 0.1)\n               {\n                  _laserCloudOri.push_back(pointOri);\n                  _coeffSel.push_back(coeff);\n               }\n            }\n         }\n      }\n\n      float srx = _transformTobeMapped.rot_x.sin();\n      float crx = _transformTobeMapped.rot_x.cos();\n      float sry = _transformTobeMapped.rot_y.sin();\n      float cry = _transformTobeMapped.rot_y.cos();\n      float srz = _transformTobeMapped.rot_z.sin();\n      float crz = _transformTobeMapped.rot_z.cos();\n\n      size_t laserCloudSelNum = _laserCloudOri.size();\n      if (laserCloudSelNum < 50)\n         continue;\n\n      Eigen::Matrix<float, Eigen::Dynamic, 6> matA(laserCloudSelNum, 6);\n      Eigen::Matrix<float, 6, Eigen::Dynamic> matAt(6, laserCloudSelNum);\n      Eigen::Matrix<float, 6, 6> matAtA;\n      Eigen::VectorXf matB(laserCloudSelNum);\n      Eigen::VectorXf matAtB;\n      Eigen::VectorXf matX;\n\n      for (int i = 0; i < laserCloudSelNum; i++)\n      {\n         pointOri = _laserCloudOri.points[i];\n         coeff = _coeffSel.points[i];\n\n         float arx = (crx*sry*srz*pointOri.x + crx * crz*sry*pointOri.y - srx * sry*pointOri.z) * coeff.x\n            + (-srx * srz*pointOri.x - crz * srx*pointOri.y - crx * pointOri.z) * coeff.y\n            + (crx*cry*srz*pointOri.x + crx * cry*crz*pointOri.y - cry * srx*pointOri.z) * coeff.z;\n\n         float ary = ((cry*srx*srz - crz * sry)*pointOri.x\n                      + (sry*srz + cry * crz*srx)*pointOri.y + crx * cry*pointOri.z) * coeff.x\n            + ((-cry * crz - srx * sry*srz)*pointOri.x\n               + (cry*srz - crz * srx*sry)*pointOri.y - crx * sry*pointOri.z) * coeff.z;\n\n         float arz = ((crz*srx*sry - cry * srz)*pointOri.x + (-cry * crz - srx * sry*srz)*pointOri.y)*coeff.x\n            + (crx*crz*pointOri.x - crx * srz*pointOri.y) * coeff.y\n            + ((sry*srz + cry * crz*srx)*pointOri.x + (crz*sry - cry * srx*srz)*pointOri.y)*coeff.z;\n\n         matA(i, 0) = arx;\n         matA(i, 1) = ary;\n         matA(i, 2) = arz;\n         matA(i, 3) = coeff.x;\n         matA(i, 4) = coeff.y;\n         matA(i, 5) = coeff.z;\n         matB(i, 0) = -coeff.intensity;\n      }\n\n      matAt = matA.transpose();\n      matAtA = matAt * matA;\n      matAtB = matAt * matB;\n      matX = matAtA.colPivHouseholderQr().solve(matAtB);\n\n      if (iterCount == 0)\n      {\n         Eigen::Matrix<float, 1, 6> matE;\n         Eigen::Matrix<float, 6, 6> matV;\n         Eigen::Matrix<float, 6, 6> matV2;\n\n         Eigen::SelfAdjointEigenSolver< Eigen::Matrix<float, 6, 6> > esolver(matAtA);\n         matE = esolver.eigenvalues().real();\n         matV = esolver.eigenvectors().real();\n\n         matV2 = matV;\n\n         isDegenerate = false;\n         float eignThre[6] = { 100, 100, 100, 100, 100, 100 };\n         for (int i = 0; i < 6; i++)\n         {\n            if (matE(0, i) < eignThre[i])\n            {\n               for (int j = 0; j < 6; j++)\n               {\n                  matV2(i, j) = 0;\n               }\n               isDegenerate = true;\n            }\n            else\n            {\n               break;\n            }\n         }\n         matP = matV.inverse() * matV2;\n      }\n\n      if (isDegenerate)\n      {\n         Eigen::Matrix<float, 6, 1> matX2(matX);\n         matX = matP * matX2;\n      }\n\n      _transformTobeMapped.rot_x += matX(0, 0);\n      _transformTobeMapped.rot_y += matX(1, 0);\n      _transformTobeMapped.rot_z += matX(2, 0);\n      _transformTobeMapped.pos.x() += matX(3, 0);\n      _transformTobeMapped.pos.y() += matX(4, 0);\n      _transformTobeMapped.pos.z() += matX(5, 0);\n\n      float deltaR = sqrt(pow(rad2deg(matX(0, 0)), 2) +\n                          pow(rad2deg(matX(1, 0)), 2) +\n                          pow(rad2deg(matX(2, 0)), 2));\n      float deltaT = sqrt(pow(matX(3, 0) * 100, 2) +\n                          pow(matX(4, 0) * 100, 2) +\n                          pow(matX(5, 0) * 100, 2));\n\n      if (deltaR < _deltaRAbort && deltaT < _deltaTAbort)\n         break;\n   }\n\n   transformUpdate();\n}\n\n\n} // end namespace loam", "meta": {"hexsha": "349f0ba8de828851365b893ac1ea03a0dba186d5", "size": 33608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utility/loam_velodyne/src/lib/BasicLaserMapping.cpp", "max_stars_repo_name": "joeyzhu00/FusionAD", "max_stars_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utility/loam_velodyne/src/lib/BasicLaserMapping.cpp", "max_issues_repo_name": "joeyzhu00/FusionAD", "max_issues_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utility/loam_velodyne/src/lib/BasicLaserMapping.cpp", "max_forks_repo_name": "joeyzhu00/FusionAD", "max_forks_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac", "max_forks_repo_licenses": ["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.8913282108, "max_line_length": 122, "alphanum_fraction": 0.5805760533, "num_tokens": 10302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.02161533358986759, "lm_q1q2_score": 0.008642061987702966}}
{"text": "/*\n * Copyright (c) 2011-2019, 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_COLLISION_DART_DARTCOLLIDE_HPP_\n#define DART_COLLISION_DART_DARTCOLLIDE_HPP_\n\n#include <thread>\n#include <unordered_map>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <assimp/scene.h>\n#include <ccd/ccd.h>\n#include <ccd/vec3.h>\n\n#include \"dart/collision/CollisionDetector.hpp\"\n\nnamespace dart {\nnamespace collision {\n\nint collide(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const CollisionOption& option,\n    CollisionResult& result);\n\n/// This is for when we use the sphere collision routines for capsule-ends. If\n/// we have a capsule in deep inter-penetration with another object, we want to\n/// only detect collisions on one half of the sphere. This is easy to decide,\n/// because it's the Z coordinate of the collision in the local space for the\n/// sphere. TOP will allow only Z > 0, BOTTOM will allow only Z < 0, and BOTH\n/// will allow either configuration.\nenum ClipSphereHalfspace\n{\n  BOTH = 0,\n  TOP = 1,\n  BOTTOM = 2\n};\n\n/// This is for pipe-edge collisions, when found by the face-face collision\n/// algorithm. We want to be able to ensure that all contacts lie exactly in the\n/// plane of the mesh/box that is responsible for the collision.\nenum PinToFace\n{\n  AVERAGE = 0,\n  FACE_A = 1,\n  FACE_B = 2\n};\n\nint collideBoxBox(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& T0,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideBoxSphere(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& T0,\n    const s_t& r1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result,\n    ClipSphereHalfspace halfspace = ClipSphereHalfspace::BOTH);\n\nint collideSphereBox(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const s_t& r0,\n    const Eigen::Isometry3s& T0,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result,\n    ClipSphereHalfspace halfspace = ClipSphereHalfspace::BOTH);\n\nint collideSphereSphere(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const s_t& r0,\n    const Eigen::Isometry3s& c0,\n    const s_t& r1,\n    const Eigen::Isometry3s& c1,\n    const CollisionOption& option,\n    CollisionResult& result,\n    ClipSphereHalfspace halfspace0 = ClipSphereHalfspace::BOTH,\n    ClipSphereHalfspace halfspace1 = ClipSphereHalfspace::BOTH);\n\nint collideBoxBoxAsMesh(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& T0,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideMeshBox(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const aiScene* mesh0,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& c0,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& c1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideBoxMesh(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& c0,\n    const aiScene* mesh1,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& c1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideMeshSphere(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const aiScene* mesh0,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& c0,\n    const s_t& r1,\n    const Eigen::Isometry3s& c1,\n    const CollisionOption& option,\n    CollisionResult& result,\n    ClipSphereHalfspace halfspace = ClipSphereHalfspace::BOTH);\n\nint collideSphereMesh(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const s_t& r0,\n    const Eigen::Isometry3s& c0,\n    const aiScene* mesh1,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& c1,\n    const CollisionOption& option,\n    CollisionResult& result,\n    ClipSphereHalfspace halfspace = ClipSphereHalfspace::BOTH);\n\nint collideMeshMesh(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const aiScene* mesh0,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& c0,\n    const aiScene* mesh1,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& c1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideCapsuleCapsule(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    s_t height0,\n    s_t radius0,\n    const Eigen::Isometry3s& T0,\n    s_t height1,\n    s_t radius1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideSphereCapsule(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    s_t radius0,\n    const Eigen::Isometry3s& T0,\n    s_t height1,\n    s_t radius1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideCapsuleSphere(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    s_t height0,\n    s_t radius0,\n    const Eigen::Isometry3s& T0,\n    s_t radius1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideBoxCapsule(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& T0,\n    s_t height1,\n    s_t radius1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideCapsuleBox(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    s_t height0,\n    s_t radius0,\n    const Eigen::Isometry3s& T0,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideMeshCapsule(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const aiScene* mesh0,\n    const Eigen::Vector3s& size0,\n    const Eigen::Isometry3s& T0,\n    s_t height1,\n    s_t radius1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideCapsuleMesh(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    s_t height0,\n    s_t radius0,\n    const Eigen::Isometry3s& T0,\n    const aiScene* mesh1,\n    const Eigen::Vector3s& size1,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\nint collideCylinderSphere(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const s_t& cyl_rad,\n    const s_t& half_height,\n    const Eigen::Isometry3s& T0,\n    const s_t& sphere_rad,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result,\n    ClipSphereHalfspace halfspace = ClipSphereHalfspace::BOTH);\n\nint collideCylinderPlane(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    const s_t& cyl_rad,\n    const s_t& half_height,\n    const Eigen::Isometry3s& T0,\n    const Eigen::Vector3s& plane_normal,\n    const Eigen::Isometry3s& T1,\n    const CollisionOption& option,\n    CollisionResult& result);\n\n/////////////////////////////////////////////////////////////////////\n// Interface with libccd:\n/////////////////////////////////////////////////////////////////////\n\n// Get the `pos` vec for CCD for this pair of objects\nccd_vec3_t& getCachedCcdPos(CollisionObject* o1, CollisionObject* o2);\n\n// Get the `dir` vec for CCD for this pair of objects\nccd_vec3_t& getCachedCcdDir(CollisionObject* o1, CollisionObject* o2);\n\n// We need to define structs for each object type that we pass to libccd, with\n// all relevant info about the object.\nstruct ccdBox\n{\n  const Eigen::Vector3s* size;\n  const Eigen::Isometry3s* transform;\n};\n\nstruct ccdSphere\n{\n  s_t radius;\n  const Eigen::Isometry3s* transform;\n};\n\nstruct ccdMesh\n{\n  const aiScene* mesh;\n  const Eigen::Isometry3s* transform;\n  const Eigen::Vector3s* scale;\n};\n\nstruct ccdCapsule\n{\n  s_t radius;\n  s_t height;\n  const Eigen::Isometry3s* transform;\n};\n\n// We also need to define \"support\" functions that will find the furthest point\n// in the object along the direction \"_dir\", and return it in \"_vec\" for each\n// type of object.\n\nvoid ccdSupportBox(const void* _obj, const ccd_vec3_t* _dir, ccd_vec3_t* _out);\nvoid ccdSupportSphere(\n    const void* _obj, const ccd_vec3_t* _dir, ccd_vec3_t* _out);\nvoid ccdSupportMesh(const void* _obj, const ccd_vec3_t* _dir, ccd_vec3_t* _out);\nvoid ccdSupportCapsule(\n    const void* _obj, const ccd_vec3_t* _dir, ccd_vec3_t* _out);\n\n// Finally, we need to define the \"center\" function for objects. This returns\n// the approximate center of each object.\n\nvoid ccdCenterBox(const void* _obj, ccd_vec3_t* _center);\nvoid ccdCenterSphere(const void* _obj, ccd_vec3_t* _center);\nvoid ccdCenterMesh(const void* _obj, ccd_vec3_t* _center);\nvoid ccdCenterCapsule(const void* _obj, ccd_vec3_t* _center);\n\n// In order to differentiate between different types of contact, we need to be\n// able to get all the vertices that are within some small epsilon of being on\n// the \"witness\" plane returned by ccd.\n\nstd::vector<Eigen::Vector3s> ccdPointsAtWitnessBox(\n    ccdBox* box, ccd_vec3_t* dir, bool neg);\nstd::vector<Eigen::Vector3s> ccdPointsAtWitnessMesh(\n    ccdMesh* mesh, ccd_vec3_t* dir, bool neg);\n\n/// This is responsible for creating and annotating all the contact objects with\n/// all the metadata we need in order to get accurate gradients.\nint createMeshMeshContacts(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    CollisionResult& result,\n    ccd_vec3_t* dir,\n    const std::vector<Eigen::Vector3s>& pointsAWitness,\n    const std::vector<Eigen::Vector3s>& pointsBWitness);\n\n/// This is responsible for creating and annotating all the contact objects with\n/// all the metadata we need in order to get accurate gradients.\nint createMeshSphereContact(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    CollisionResult& result,\n    ccd_vec3_t* dir,\n    const std::vector<Eigen::Vector3s>& meshPointsWitness,\n    const Eigen::Vector3s& sphereCenter,\n    s_t sphereRadius,\n    ClipSphereHalfspace halfspace = ClipSphereHalfspace::BOTH);\n\n/// This is responsible for creating and annotating all the contact objects with\n/// all the metadata we need in order to get accurate gradients.\nint createSphereMeshContact(\n    CollisionObject* o1,\n    CollisionObject* o2,\n    CollisionResult& result,\n    ccd_vec3_t* dir,\n    const Eigen::Vector3s& sphereCenter,\n    s_t sphereRadius,\n    const std::vector<Eigen::Vector3s>& meshPointsWitness,\n    ClipSphereHalfspace halfspace = ClipSphereHalfspace::BOTH);\n\n/*\n/// This is necessary preparation for rapidly checking if another point is\n/// contained within the convex shape. This sorts the shape by angle from\nthe\n/// center, and trims out any points that lie inside the convex polygon.\nvoid prepareConvex2DShape(std::vector<Eigen::Vector2s>& shape);\n\n/// This checks whether a 2D shape contains a point. This assumes that shape\nwas\n/// sorted using prepareConvex2DShape().\nbool convex2DShapeContains(\n    const Eigen::Vector2s& point, const std::vector<Eigen::Vector2s>&\nshape);\n*/\n\n/// This trims out any points that lie inside the convex polygon, without\n/// changing the order.\nvoid keepOnlyConvex2DHull(\n    std::vector<Eigen::Vector3s>& shape,\n    const Eigen::Vector3s& origin,\n    const Eigen::Vector3s& basis2dX,\n    const Eigen::Vector3s& basis2dY);\n\n/// This is necessary preparation for rapidly checking if another point is\n/// contained within the convex shape. This sorts the shape by angle from\n/// the center, and trims out any points that lie inside the convex polygon.\nvoid prepareConvex2DShape(\n    std::vector<Eigen::Vector3s>& shape,\n    const Eigen::Vector3s& origin,\n    const Eigen::Vector3s& basis2dX,\n    const Eigen::Vector3s& basis2dY);\n\n/// This checks whether a 2D shape contains a point. This assumes that shape was\n/// sorted using prepareConvex2DShape().\nbool convex2DShapeContains(\n    const Eigen::Vector3s& point,\n    const std::vector<Eigen::Vector3s>& shape,\n    const Eigen::Vector3s& origin,\n    const Eigen::Vector3s& basis2dX,\n    const Eigen::Vector3s& basis2dY);\n\n/// This transforms a 3D point down to a 2D point in the given 3D plane\nEigen::Vector2s pointInPlane(\n    const Eigen::Vector3s& point,\n    const Eigen::Vector3s& origin,\n    const Eigen::Vector3s& basis2dX,\n    const Eigen::Vector3s& basis2dY);\n\ns_t angle2D(const Eigen::Vector2s& from, const Eigen::Vector2s& to);\n\n// This implements the \"2D cross product\" as redefined here:\n// https://stackoverflow.com/a/565282/13177487\ninline s_t crossProduct2D(const Eigen::Vector2s& v, const Eigen::Vector2s& w);\n\n/// This returns true if the two line segments defined by (p0,p1) and (q0,q1)\n/// intersect. If they do intersect, this writes the intersection point to\n/// `out`.\nbool get2DLineIntersection(\n    const Eigen::Vector2s& p0,\n    const Eigen::Vector2s& p1,\n    const Eigen::Vector2s& q0,\n    const Eigen::Vector2s& q1,\n    Eigen::Vector2s& out);\n\n/// This sets the default settings for CCD in a single spot in the DARTCollide\n/// code, so it's easy to tweak settings across all collision pairs.\ninline void setCcdDefaultSettings(ccd_t& ccd);\n\n/// This allows us to prevent weird effects where we don't want to carry over\n/// cacheing\nvoid clearCcdCache();\n\n/// This is the static cache for all the CCD collision search data\nstatic std::unordered_map<std::thread::id, std::unordered_map<long, ccd_vec3_t>>\n    _ccdDirCache;\nstatic std::unordered_map<std::thread::id, std::unordered_map<long, ccd_vec3_t>>\n    _ccdPosCache;\n\n} // namespace collision\n} // namespace dart\n\n#endif // DART_COLLISION_DART_DARTCOLLIDE_HPP_\n", "meta": {"hexsha": "d1ed85eeb636021826f2b25653d2586a0defe0e2", "size": 15183, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/collision/dart/DARTCollide.hpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "dart/collision/dart/DARTCollide.hpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/collision/dart/DARTCollide.hpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 31.8970588235, "max_line_length": 80, "alphanum_fraction": 0.719949944, "num_tokens": 4092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.021615332486907682, "lm_q1q2_score": 0.008642061855887987}}
{"text": "// Copyright University of Warwick 2014\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Authors:\n// John Back\n\n/*! \\file LpcAbsCurve.hh\n    \\brief File containing the declaration of the LpcAbsCurve class\n*/\n\n/*! \\class LpcAbsCurve\n    \\brief Class that defines an abstract local principal curve\n*/\n\n#ifndef LPC_ABS_CURVE_HH\n#define LPC_ABS_CURVE_HH\n\n#include \"LACE/LpcBinRange.hh\"\n#include \"LACE/LpcPathLength.hh\"\n#include \"LACE/LpcPoint.hh\"\n#include \"LACE/LpcResiduals.hh\"\n\n#include <Eigen/Dense>\n#include <vector>\n\nclass LpcHitCollection;\n\nclass LpcAbsCurve {\n\npublic:\n\n    //! Constructor storing the local principal curve result\n    /*!\n      \\param [in] index The index number of the curve\n      \\param [in] startPoint The scaled starting position for the lpc\n      \\param [in] lpcPoints The calculated scaled lpc points\n      \\param [in] eigenVectors The largest eigenvectors (row = lpc point, col = x,y,z,...)\n      \\param [in] cosAngles The cosine of the angles between adjacent eigenvectors\n      \\param [in] lpcPath The cumulative path length object along the curve\n      \\param [in] rho The ratio of the eigenvalues (2nd/1st) for each lpc point\n      \\param [in] c0 The adjusted kernel function denominator exponent scale factors\n      \\param [in] highRhoPoints The scaled local neighbourhood points when rho > rho0 (~0.4)\n      \\param [in] theHits The pointer to the constant hit collection used to find the curve\n      \\param [in] flag An integer status flag (default value of -1 to mean the \"main curve\")\n     */\n    LpcAbsCurve(int index,\n\t\tconst LpcPoint& startPoint, \n\t\tconst std::vector<LpcPoint>& lpcPoints,\n\t\tconst Eigen::MatrixXd& eigenVectors, \n\t\tconst Eigen::VectorXd& cosAngles,\n\t\tconst LpcPathLength& lpcPath, \n\t\tconst Eigen::VectorXd& rho, \n\t\tconst Eigen::VectorXd& c0,\n\t\tconst std::vector<LpcPoint>& highRhoPoints,\n\t\tconst LpcHitCollection* theHits,\n\t\tint flag = -1);\n\n    //! Empty constructor\n    LpcAbsCurve();\n\n    //! Destructor\n    virtual ~LpcAbsCurve();\n  \n    //! Enumeration to specify the curve type\n    enum LpcCurveType {Abstract = -1, Main = 0, Branch = 1};\n\n    // Accessor methods for retrieving the results in either the original internal\n    // storage format or using helper classes, e.g. LpcPoint of LpcPathlength\n\n    //! Get the curve type (LpcCurveType enum)\n    /*!\n      \\return an integer to specify the curve type (LpcCurveType enum)\n    */\n    int getType() const {return type_;}\n\n    //! Get the curve index number \n    /*!\n      \\return the curve index number\n    */\n    int getIndex() const {return index_;}\n\n    //! Get the status flag integer (-1 = main curve; equal to main curve index for branches)\n    /*!\n      \\return the status flag integer\n    */\n    int getFlag() const {return flag_;}\n\n    //! Get the number of dimensions\n    /*!\n      \\return the number of dimensions\n    */\n    int getNDimensions() const {return nDim_;}\n\n    //! Get the starting point as an LpcPoint object\n    /*!\n      \\returns the starting point as an LpcPoint object with index = -1\n    */\n    LpcPoint getStartPoint() const {return startPoint_;}\n\n    //! Get the number of lpc points\n    /*!\n      \\returns the number of lpc points\n    */\n    int getNLpcPoints() const {return lpcPoints_.size();}\n\n    //! Get the lpc points as a vector of LpcPoint objects\n    /*!\n      \\returns a vector of LpcPoint objects\n    */\n    std::vector<LpcPoint> getLpcPoints() const {return lpcPoints_;}\n\n    //! Get the principal eigenvectors with the largest eigenvalues of the local covariance matrix\n    /*!\n      \\returns the eigenvectors as an Eigen MatrixXd (row = eigenvector, column = x,y,z,... components)\n    */\n    Eigen::MatrixXd getEigenVectors() const {return eigenVectors_;}\n\n    //! Get the cosine of the angles between neighbouring principal (largest) eigenvectors\n    /*!\n      \\returns the cosine of the angles as an Eigen VectorXd\n    */\n    Eigen::VectorXd getCosAngles() const {return cosAngles_;}\n\n    //! Get the cumulative path length info along the curve (scaled and unscaled)\n    /*!\n      \\returns the LpcPathlengths object containing all path length segments\n    */\n    LpcPathLength getPathLength() const {return lpcPath_;}\n\n    //! Get the ratio of the eigenvalues (2nd/1st) for each lpc point\n    /*!\n      \\returns the ratio of the eigenvalues as an Eigen VectorXd\n    */\n    Eigen::VectorXd getRho() const {return rho_;}\n\n    //! Get the c0 coefficients used to scale the kernel factor\n    /*!\n      \\returns the c0 coefficients as an Eigen VectorXd\n    */\n    Eigen::VectorXd getc0() const {return c0_;}\n\n    //! Get the local neighbourhood points (\"x\" or \"u\") with eigenvalue ratios > rho0\n    /*!\n      \\returns a stl vector of LpcPoint objects, with both scaled and unscaled co-ordinates\n    */\n    std::vector<LpcPoint> getHighRhoPoints() const {return highRhoPoints_;}\n\n    //! Get the pointer to the constant hit collection used for this curve\n    /*!\n      \\returns a pointer to the constant hit collection used for the curve\n    */\n    const LpcHitCollection* getHitCollection() const {return theHits_;}\n\n    //! Get the lpc-to-hit residuals object (use it to access individual residuals)\n    /*!\n      \\returns the lpc residuals object\n    */\n    LpcResiduals getResiduals() const {return residuals_;}\n\n    //! Print method, which is read-only (no contents can be changed)\n    virtual void print() const;\n\n    //! Reset the curve index number\n    /*!\n      \\param [in] index the new index number\n    */\n    void setIndex(int index) {index_ = index;}\n\n    //! Reset the status flag integer\n    /*!\n      \\param [in] flag The status flag integer\n    */\n    void setFlag(int flag) {flag_ = flag;}\n\n    //! Store the lpc point peak and range for the 1-|cosAngle| peaks (LpcFeatures class)\n    /*!\n      \\param [in] passedPeaks Vector of the lpc point indices that correspond to the peaks\n      \\param [in] peakRanges Vector of LpcBinRanges to specify the neighbourhood of each peak\n    */\n    void storeCosPeaks(const std::vector<int>& passedPeaks, \n\t\t       const std::vector<LpcBinRange>& peakRanges) {\n\tpassedPeaks_ = passedPeaks; peakRanges_ = peakRanges;}\n\n    //! Retrieve the lpc point integers that correspond to the cosine angle peaks\n    /*!\n      \\return the vector of lpc point integers corrsponding to the peaks\n    */\n    std::vector<int> getCosPeakIndices() const {return passedPeaks_;}\n\n    //! Retrieve the lpc point ranges corresponding to the neighbourhood of the cosine peaks\n    /*!\n      \\return the vector of LpcBinRange objects for each cosine peak range\n    */\n    std::vector<LpcBinRange> getCosPeakRanges() const {return peakRanges_;}\n\n\nprotected:\n\n    //! Method to calculate the lpc-to-hit residuals and store them in residuals_\n    void findResiduals();\n\n    //! Integer specifying the curve type defined by the LpcCurveType enumeration\n    int type_;\n\n    //! The index number of the curve\n    int index_;\n\n    //! The starting local point of the lpc\n    LpcPoint startPoint_;\n\n    //! The lpc points (\"m(u)\" or \"mu\"), equivalent to the local weighted mean\n    std::vector<LpcPoint> lpcPoints_;\n\n    //! The largest eigenvectors of the covariance matrix (row = lpc point, col = x,y,z)\n    Eigen::MatrixXd eigenVectors_;\n\n    //! The cosine between neighbouring principal eigenvectors\n    Eigen::VectorXd cosAngles_;\n\n    //! The path lengths along the lpc (scaled and unscaled)\n    LpcPathLength lpcPath_;\n\n    //! The ratio of the eigenvalues between neighbouring eigenvectors\n    Eigen::VectorXd rho_;\n\n    //! The c0 coefficients used to scale the kernel factor\n    Eigen::VectorXd c0_;\n\n    //! The local neighbourhood points (\"x\" or \"u\") with eigenvalue ratios > rho0\n    std::vector<LpcPoint> highRhoPoints_;\n\n    //! The pointer to the constant used hit collection which is owned by the event\n    const LpcHitCollection* theHits_;\n\n    //! The number of dimensions\n    int nDim_;\n\n    //! The integer status flag\n    int flag_;\n\n    //! The object storing the lpc to hit residuals\n    LpcResiduals residuals_;\n\n    //! The vector of lpc point indices for the cosine peaks\n    std::vector<int> passedPeaks_;\n\n    //! The vector of LpcBinRanges for the lpc point range around each cosine peak\n    std::vector<LpcBinRange> peakRanges_;\n\nprivate:\n\n    //! Copy constructor\n    LpcAbsCurve(const LpcAbsCurve& other);\n\n    //! Assignment operator\n    LpcAbsCurve& operator=(const LpcAbsCurve& other);\n\n};\n\n#endif\n\n", "meta": {"hexsha": "34160f58d257065189832a0b5773e8a857148d3d", "size": 8521, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/LACE/LpcAbsCurve.hh", "max_stars_repo_name": "petrmanek/LACE", "max_stars_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T13:13:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T13:13:34.000Z", "max_issues_repo_path": "include/LACE/LpcAbsCurve.hh", "max_issues_repo_name": "petrmanek/LACE", "max_issues_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/LACE/LpcAbsCurve.hh", "max_forks_repo_name": "petrmanek/LACE", "max_forks_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-19T21:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-14T13:37:26.000Z", "avg_line_length": 32.3992395437, "max_line_length": 103, "alphanum_fraction": 0.6866564957, "num_tokens": 2118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195521959384, "lm_q2_score": 0.022629199250306712, "lm_q1q2_score": 0.00862669320475459}}
{"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-2016.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Timo Sachsenberg $\n// $Authors: Eva Lange, Clemens Groepl $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/ANALYSIS/MAPMATCHING/PoseClusteringAffineSuperimposer.h>\n#include <OpenMS/FILTERING/BASELINE/MorphologicalFilter.h>\n#include <OpenMS/MATH/STATISTICS/BasicStatistics.h>\n#include <OpenMS/DATASTRUCTURES/ListUtils.h>\n#include <OpenMS/MATH/MISC/LinearInterpolation.h>\n\n#include <fstream>\n#include <vector>\n#include <map>\n#include <cmath>\n#include <algorithm>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n\n// #define Debug_PoseClusteringAffineSuperimposer\n\nnamespace OpenMS\n{\n\n  PoseClusteringAffineSuperimposer::PoseClusteringAffineSuperimposer() :\n    BaseSuperimposer()\n  {\n    setName(getProductName());\n\n    defaults_.setValue(\"mz_pair_max_distance\", 0.5, \"Maximum of m/z deviation of corresponding elements in different maps.  \"\n                                                    \"This condition applies to the pairs considered in hashing.\");\n    defaults_.setMinFloat(\"mz_pair_max_distance\", 0.);\n\n    defaults_.setValue(\"rt_pair_distance_fraction\", 0.1, \"Within each of the two maps, the pairs considered for pose clustering \"\n                                                         \"must be separated by at least this fraction of the total elution time \"\n                                                         \"interval (i.e., max - min).  \", ListUtils::create<String>(\"advanced\"));\n    defaults_.setMinFloat(\"rt_pair_distance_fraction\", 0.);\n    defaults_.setMaxFloat(\"rt_pair_distance_fraction\", 1.);\n\n    defaults_.setValue(\"num_used_points\", 2000, \"Maximum number of elements considered in each map \"\n                                                \"(selected by intensity).  Use this to reduce the running time \"\n                                                \"and to disregard weak signals during alignment.  For using all points, set this to -1.\");\n    defaults_.setMinInt(\"num_used_points\", -1);\n\n    defaults_.setValue(\"scaling_bucket_size\", 0.005, \"The scaling of the retention time \"\n                                                     \"interval is being hashed into buckets of this size during pose \"\n                                                     \"clustering.  A good choice for this would be a bit smaller than the \"\n                                                     \"error you would expect from repeated runs.\");\n    defaults_.setMinFloat(\"scaling_bucket_size\", 0.);\n\n    defaults_.setValue(\"shift_bucket_size\", 3.0, \"The shift at the lower (respectively, higher) end of the retention time \"\n                                                 \"interval is being hashed into buckets of this size during pose \"\n                                                 \"clustering.  A good choice for this would be about \"\n                                                 \"the time between consecutive MS scans.\");\n    defaults_.setMinFloat(\"shift_bucket_size\", 0.);\n\n    defaults_.setValue(\"max_shift\", 1000.0, \"Maximal shift which is considered during histogramming (in seconds).  \"\n                                            \"This applies for both directions.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setMinFloat(\"max_shift\", 0.);\n\n    defaults_.setValue(\"max_scaling\", 2.0, \"Maximal scaling which is considered during histogramming.  \"\n                                           \"The minimal scaling is the reciprocal of this.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setMinFloat(\"max_scaling\", 1.);\n\n    defaults_.setValue(\"dump_buckets\", \"\", \"[DEBUG] If non-empty, base filename where hash table buckets will be dumped to.  \"\n                                           \"A serial number for each invocation will be appended automatically.\", ListUtils::create<String>(\"advanced\"));\n\n    defaults_.setValue(\"dump_pairs\", \"\", \"[DEBUG] If non-empty, base filename where the individual hashed pairs will be dumped to (large!).  \"\n                                         \"A serial number for each invocation will be appended automatically.\", ListUtils::create<String>(\"advanced\"));\n\n    defaultsToParam_();\n    return;\n  }\n\n  /**\n    @brief Initialize hash maps for the algorithm.\n\n    The hash maps will contain a histogram of the values to be estimated.\n\n  */\n  void initializeHashTables(\n    Math::LinearInterpolation<double, double>& scaling_hash_1,\n    Math::LinearInterpolation<double, double>& scaling_hash_2,\n    Math::LinearInterpolation<double, double>& rt_low_hash_,\n    Math::LinearInterpolation<double, double>& rt_high_hash_,\n    const double max_scaling, const double max_shift,\n    const double scaling_bucket_size, const double shift_bucket_size,\n    const double rt_low, const double rt_high)\n  {\n    const Int scaling_buckets_num_half = (Int) ceil(log(max_scaling) / scaling_bucket_size) + 1;\n\n    // set scale to scaling_bucket_size and establish initial mapping of scaling_buckets_num_half to zero\n\n    scaling_hash_1.getData().clear();\n    scaling_hash_1.getData().resize(2 * scaling_buckets_num_half + 1);\n    scaling_hash_1.setMapping(scaling_bucket_size, scaling_buckets_num_half, 0.);\n\n    scaling_hash_2.getData().clear();\n    scaling_hash_2.getData().resize(2 * scaling_buckets_num_half + 1);\n    scaling_hash_2.setMapping(scaling_bucket_size, scaling_buckets_num_half, 0.); // map scaling_buckets_num_half to zero\n\n    // (over)estimate the required number of buckets for shifting\n    const Int rt_buckets_num_half = 4 + 2 * (Int) ceil((max_shift * max_scaling) / shift_bucket_size);\n    const Int rt_buckets_num = 1 + 2 * rt_buckets_num_half;\n\n    // set scale to shift_bucket_size and establish initial mapping of rt_buckets_num_half to rt_low/rt_high\n    rt_low_hash_.getData().clear();\n    rt_low_hash_.getData().resize(rt_buckets_num);\n    rt_low_hash_.setMapping(shift_bucket_size, rt_buckets_num_half, rt_low);\n\n    rt_high_hash_.getData().clear();\n    rt_high_hash_.getData().resize(rt_buckets_num);\n    rt_high_hash_.setMapping(shift_bucket_size, rt_buckets_num_half, rt_high);\n  }\n\n  /**\n    @brief Estimates scaling by trying different (weighted) affine transformations.\n\n    Basically try all combinations of two pairs from map model (i,j) and two\n    pairs from map scene (k,l) and compute shift and scale based on these\n    four points. The computed value is weighed by the intensity of all\n    points, thus this is a density-based approach.\n\n    In the first round, compute and store every combination. In the second\n    round, only consider quadruplets where the scaling factor matches the\n    estimated bounds of (scale_low_1,scale_high_1), discard all other data.\n\n  */\n  void affineTransformationHashing(const bool do_dump_pairs,\n                                   const std::vector<Peak2D> & model_map,\n                                   const std::vector<Peak2D> & scene_map,\n                                   Math::LinearInterpolation<double, double>& scaling_hash_1,\n                                   Math::LinearInterpolation<double, double>& scaling_hash_2,\n                                   Math::LinearInterpolation<double, double>& rt_low_hash_,\n                                   Math::LinearInterpolation<double, double>& rt_high_hash_,\n                                   const int hashing_round,\n                                   const double rt_pair_min_distance,\n                                   const String dump_pairs_basename,\n                                   const Int dump_buckets_serial,\n                                   const double mz_pair_max_distance,\n                                   const double winlength_factor_baseline,\n                                   const double total_intensity_ratio,\n                                   const double scale_low_1,\n                                   const double scale_high_1,\n                                   const double rt_low, const double rt_high)\n  {\n    Size const model_map_size = model_map.size();   // i j\n    Size const scene_map_size = scene_map.size();   // k l\n\n    String dump_pairs_filename;\n    std::ofstream dump_pairs_file;\n    if (do_dump_pairs)\n    {\n      dump_pairs_filename = dump_pairs_basename + \"_phase_two_\" + String(dump_buckets_serial);\n      dump_pairs_file.open(dump_pairs_filename.c_str());\n      dump_pairs_file << \"#\" << ' ' << \"i\" << ' ' << \"j\" << ' ' << \"k\" << ' ' << \"l\" << ' ' << std::endl;\n    }\n\n    // first point in model map (i)\n    for (Size i = 0, i_low = 0, i_high = 0, k_low = 0, k_high = 0; i < model_map_size - 1; ++i)\n    {\n      // Adjust window around i in model map (get all features in a m/z range of item i in the model map)\n      while (i_low < model_map_size && model_map[i_low].getMZ() < model_map[i].getMZ() - mz_pair_max_distance)\n        ++i_low;\n      while (i_high < model_map_size && model_map[i_high].getMZ() <= model_map[i].getMZ() + mz_pair_max_distance)\n        ++i_high;\n      // stop if there are too many features are in our window\n      double i_winlength_factor = 1. / (i_high - i_low);\n      i_winlength_factor -= winlength_factor_baseline;\n      if (i_winlength_factor <= 0)\n        continue;\n\n      // Adjust window around k in scene map (get all features in a m/z range of item i in the scene map)\n      while (k_low < scene_map_size && scene_map[k_low].getMZ() < model_map[i].getMZ() - mz_pair_max_distance)\n        ++k_low;\n      while (k_high < scene_map_size && scene_map[k_high].getMZ() <= model_map[i].getMZ() + mz_pair_max_distance)\n        ++k_high;\n\n      // Iterate through all matching features in the scene map that are\n      // within the m/z distance of item i from the model map.\n      // first point in scene map (k)\n      for (Size k = k_low; k < k_high; ++k)\n      {\n        // stop if there are too many features are in our window\n        double k_winlength_factor = 1. / (k_high - k_low);\n        k_winlength_factor -= winlength_factor_baseline;\n        if (k_winlength_factor <= 0)\n          continue;\n\n        // compute similarity of intensities i k by taking the ratio of the two intensities\n        double similarity_ik;\n        {\n          const double int_i = model_map[i].getIntensity();\n          const double int_k = scene_map[k].getIntensity() * total_intensity_ratio;\n          similarity_ik = (int_i < int_k) ? int_i / int_k : int_k / int_i;\n          // weight is inverse proportional to number of elements with similar mz\n          similarity_ik *= i_winlength_factor;\n          similarity_ik *= k_winlength_factor;\n        }\n\n        // second point in model map (j)\n        for (Size j = i + 1, j_low = i_low, j_high = i_low, l_low = k_low, l_high = k_high; j < model_map_size; ++j)\n        {\n          // diff in model map -> skip features that are too far away in RT\n          double diff_model = model_map[j].getRT() - model_map[i].getRT();\n          if (fabs(diff_model) < rt_pair_min_distance)\n            continue;\n\n          // Adjust window around j in model map\n          while (j_low < model_map_size && model_map[j_low].getMZ() < model_map[i].getMZ() - mz_pair_max_distance)\n            ++j_low;\n          while (j_high < model_map_size && model_map[j_high].getMZ() <= model_map[i].getMZ() + mz_pair_max_distance)\n            ++j_high;\n          double j_winlength_factor = 1. / (j_high - j_low);\n          j_winlength_factor -= winlength_factor_baseline;\n          if (j_winlength_factor <= 0)\n            continue;\n\n          // Adjust window around l in scene map\n          while (l_low < scene_map_size && scene_map[l_low].getMZ() < model_map[j].getMZ() - mz_pair_max_distance)\n            ++l_low;\n          while (l_high < scene_map_size && scene_map[l_high].getMZ() <= model_map[j].getMZ() + mz_pair_max_distance)\n            ++l_high;\n\n          // second point in scene map (l)\n          for (Size l = l_low; l < l_high; ++l)\n          {\n            double l_winlength_factor = 1. / (l_high - l_low);\n            l_winlength_factor -= winlength_factor_baseline;\n            if (l_winlength_factor <= 0)\n              continue;\n\n            // diff in scene map -> skip features that are too far away in RT\n            double diff_scene = scene_map[l].getRT() - scene_map[k].getRT();\n\n            // avoid cross mappings (i,j) -> (k,l) (e.g. i_rt < j_rt and k_rt > l_rt)\n            // and point pairs with equal retention times (e.g. i_rt == j_rt)\n            if (fabs(diff_scene) < rt_pair_min_distance || ((diff_model > 0) != (diff_scene > 0)))\n              continue;\n\n            // compute the transformation (i,j) -> (k,l)\n            double scaling = diff_model / diff_scene;\n            double shift = model_map[i].getRT() - scene_map[k].getRT() * scaling;\n\n            // compute similarity of intensities i k j l\n            double similarity_ik_jl;\n            {\n              // compute similarity of intensities j l\n              const double int_j = model_map[j].getIntensity();\n              const double int_l = scene_map[l].getIntensity() * total_intensity_ratio;\n              double similarity_jl = (int_j < int_l) ? int_j / int_l : int_l / int_j;\n              // weight is inverse proportional to number of elements with similar mz\n              similarity_jl *= j_winlength_factor;\n              similarity_jl *= l_winlength_factor;\n              similarity_ik_jl = similarity_ik * similarity_jl;\n            }\n\n            // hash the images of scaling, rt_low and rt_high into their respective hash tables\n            // store the scaling parameter and the (estimated) transformation of start/end of the maps in hashes\n            //   -> in round 2, discard values outside of scale_low_1 and\n            //   scale_high_1 (estimated before in scalingEstimate)\n            if (hashing_round == 1)\n            {\n              // hashing round 1 (estimate the scaling only)\n              scaling_hash_1.addValue(log(scaling), similarity_ik_jl);\n            }\n            else if (scaling >= scale_low_1 && scaling <= scale_high_1)\n            {\n              // hashing round 2 (estimate scaling and shift)\n              scaling_hash_2.addValue(log(scaling), similarity_ik_jl);\n\n              const double rt_low_image = shift + rt_low * scaling;\n              rt_low_hash_.addValue(rt_low_image, similarity_ik_jl);\n              const double rt_high_image = shift + rt_high * scaling;\n              rt_high_hash_.addValue(rt_high_image, similarity_ik_jl);\n\n              if (do_dump_pairs)\n              {\n                dump_pairs_file << i << ' ' << model_map[i].getRT() << ' ' << model_map[i].getMZ() << ' ' << j << ' ' << model_map[j].getRT() << ' '\n                                << model_map[j].getMZ() << ' ' << k << ' ' << scene_map[k].getRT() << ' ' << scene_map[k].getMZ() << ' ' << l << ' '\n                                << scene_map[l].getRT() << ' ' << scene_map[l].getMZ() << ' ' << similarity_ik_jl << ' ' << std::endl;\n              }\n            }\n          }   // l\n        }   // j\n      }   // k\n    }   // i\n  }\n\n  /**\n    @brief Estimates likely position of the scale factor based on scaling_hash_1.\n\n    Uses the histogram given in scaling_hash_1 to perform some filtering and\n    correction of the data and then estimate the mean of the scaling factor\n    and standard deviation, thus returning a likely range for the scaling\n    factor. Outliers are removed in an iterative process.\n\n    Returns scale_centroid_1 (mean), scale_low_1 (lower bound) and\n    scale_high_1 (upper bound) of the scaling factor.\n\n  */\n  void scalingEstimate(\n    Math::LinearInterpolation<double, double>& scaling_hash_1,\n    const bool do_dump_buckets,\n    const UInt struc_elem_length_datapoints,\n    const String dump_buckets_basename,\n    const Int dump_buckets_serial,\n    const double scaling_histogram_crossing_slope,\n    const double scaling_cutoff_stdev_multiplier,\n    const UInt loops_mean_stdev_cutoff,\n    double& scale_low_1,\n    double& scale_high_1,\n    double& scale_centroid_1)\n  {\n    typedef Math::LinearInterpolation<double, double> LinearInterpolationType_;\n    UInt filtering_stage = 0;\n\n    // optionally, dump before filtering\n    String dump_buckets_filename;\n    std::ofstream dump_buckets_file;\n    if (do_dump_buckets)\n    {\n      dump_buckets_filename = dump_buckets_basename + \"_scale_\" + String(dump_buckets_serial);\n      dump_buckets_file.open(dump_buckets_filename.c_str());\n\n      dump_buckets_file << \"# rt scale hash table buckets dump ( scale, height ) : \" << dump_buckets_filename << std::endl;\n      dump_buckets_file << \"# unfiltered hash data\\n\";\n      for (Size index = 0; index < scaling_hash_1.getData().size(); ++index)\n      {\n        const double log_of_scale = scaling_hash_1.index2key(index);\n        const double height = scaling_hash_1.getData()[index];\n        dump_buckets_file << log_of_scale << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_file << '\\n';\n    }\n\n    ++filtering_stage;\n\n    // ***************************************************************************\n    // Data filtering: apply tophat filter to histogram of different scales\n    // ***************************************************************************\n    MorphologicalFilter morph_filter;\n    Param morph_filter_param;\n    morph_filter_param.setValue(\"struc_elem_unit\", \"DataPoints\");\n    morph_filter_param.setValue(\"struc_elem_length\", double(struc_elem_length_datapoints));\n    morph_filter_param.setValue(\"method\", \"tophat\");\n    morph_filter.setParameters(morph_filter_param);\n    LinearInterpolationType_::container_type buffer(scaling_hash_1.getData().size());\n    morph_filter.filterRange(scaling_hash_1.getData().begin(), scaling_hash_1.getData().end(), buffer.begin());\n    scaling_hash_1.getData().swap(buffer);\n\n    // optionally, dump after filtering\n    if (do_dump_buckets)\n    {\n      dump_buckets_file << \"# tophat filtered hash data\\n\";\n      for (Size index = 0; index < scaling_hash_1.getData().size(); ++index)\n      {\n        const double log_of_scale = scaling_hash_1.index2key(index);\n        const double height = scaling_hash_1.getData()[index];\n        dump_buckets_file << log_of_scale << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_file << '\\n';\n    }\n\n    ++filtering_stage;\n\n    // ***************************************************************************\n    // Data cutoff: estimate cutoff for filtered histogram\n    // compute freq_cutoff using a fancy criterion to distinguish between the\n    // noise level of the histogram and enriched histogram bins\n    // ***************************************************************************\n    double freq_cutoff;\n    do\n    {\n      std::copy(scaling_hash_1.getData().begin(), scaling_hash_1.getData().end(), buffer.begin());\n      std::sort(buffer.begin(), buffer.end(), std::greater<double>());\n      double freq_intercept = scaling_hash_1.getData().front();\n      double freq_slope = (scaling_hash_1.getData().back() - scaling_hash_1.getData().front()) / double(buffer.size())\n                          / scaling_histogram_crossing_slope;\n      if (!freq_slope || !buffer.size())\n      {\n        // in fact these conditions are actually impossible, but let's be really sure ;-)\n        freq_cutoff = 0;\n      }\n      else\n      {\n        // -> basically trying to find the intersection where sorted values fall\n        // below fitted line with slop \"freq_slope\"\n        Size index = 1;   // not 0 (!)\n        while (buffer[index] >= freq_intercept + freq_slope * double(index))\n        {\n          ++index;\n        }\n        freq_cutoff = buffer[--index];   // note that we have index >= 1\n      }\n    }\n    while (0);\n\n    // ***************************************************************************\n    // apply freq_cutoff, setting smaller values to zero\n    for (Size index = 0; index < scaling_hash_1.getData().size(); ++index)\n    {\n      if (scaling_hash_1.getData()[index] < freq_cutoff)\n      {\n        scaling_hash_1.getData()[index] = 0;\n      }\n    }\n\n    // optionally, dump after noise filtering using freq_cutoff\n    if (do_dump_buckets)\n    {\n      dump_buckets_file << \"# after freq_cutoff, which is: \" << freq_cutoff << '\\n';\n      for (Size index = 0; index < scaling_hash_1.getData().size(); ++index)\n      {\n        const double log_of_scale = scaling_hash_1.index2key(index);\n        const double height = scaling_hash_1.getData()[index];\n        dump_buckets_file << log_of_scale << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_file << '\\n';\n    }\n\n    // ***************************************************************************\n    // iterative cut-off based on mean and stdev - relies upon scaling_cutoff_stdev_multiplier which is a bit hard to set right.\n    // ***************************************************************************\n    Math::BasicStatistics<double> statistics;\n    std::vector<double>::const_iterator data_begin = scaling_hash_1.getData().begin();\n    const Size data_size = scaling_hash_1.getData().size();\n    Size data_range_begin = 0;\n    Size data_range_end = data_size;\n    for (UInt loop = 0; loop < loops_mean_stdev_cutoff; ++loop)     // MAGIC ALERT: number of loops\n    {\n      statistics.update(data_begin + data_range_begin, data_begin + data_range_end);\n      double mean = statistics.mean() + data_range_begin;\n      double stdev = sqrt(statistics.variance());\n      data_range_begin = floor(std::max<double>(mean - scaling_cutoff_stdev_multiplier * stdev, 0));\n      data_range_end = ceil(std::min<double>(mean + scaling_cutoff_stdev_multiplier * stdev + 1, data_size));\n      const double log_outside_mean = scaling_hash_1.index2key(mean);\n      const double log_outside_stdev = stdev * scaling_hash_1.getScale();\n      scale_low_1 = exp(log_outside_mean - log_outside_stdev);\n      scale_centroid_1 = exp(log_outside_mean);\n      scale_high_1 = exp(log_outside_mean + log_outside_stdev);\n      if (do_dump_buckets)\n      {\n        dump_buckets_file << \"# loop: \" << loop << \"  mean: \" << log_outside_mean << \" [\" << exp(log_outside_mean) << \"]  stdev: \" << log_outside_stdev\n                          << \" [\" << scale_centroid_1 << \"]  (mean-stdev): \" << log_outside_mean - log_outside_stdev << \" [\" << scale_low_1 << \"]  (mean+stdev): \"\n                          << log_outside_mean + log_outside_stdev << \" [\" << scale_high_1 << \"]  data_range_begin: \" << data_range_begin << \"  data_range_end: \"\n                          << data_range_end << std::endl;\n      }\n    }\n\n    if (do_dump_buckets)\n    {\n      dump_buckets_file << \"# EOF\" << std::endl;\n      dump_buckets_file.close();\n    }\n  }\n\n  void shiftEstimate(\n    const bool do_dump_buckets,\n    Math::LinearInterpolation<double, double>& rt_low_hash_,\n    Math::LinearInterpolation<double, double>& rt_high_hash_,\n    const Int dump_buckets_serial,\n    const UInt struc_elem_length_datapoints,\n    const double scaling_histogram_crossing_slope,\n    const double scaling_cutoff_stdev_multiplier,\n    const UInt loops_mean_stdev_cutoff,\n    const String dump_buckets_basename,\n    double& rt_low_centroid,\n    double& rt_high_centroid)\n  {\n    UInt filtering_stage = 0;\n\n    // optionally, dump before filtering\n    String dump_buckets_low_filename;\n    std::ofstream dump_buckets_low_file;\n    String dump_buckets_high_filename;\n    std::ofstream dump_buckets_high_file;\n    if (do_dump_buckets)\n    {\n      dump_buckets_low_filename = dump_buckets_basename + \"_low_\" + String(dump_buckets_serial);\n      dump_buckets_low_file.open(dump_buckets_low_filename.c_str());\n\n      dump_buckets_low_file << \"# rt low hash table buckets dump ( scale, height ) : \" << dump_buckets_low_filename << std::endl;\n      dump_buckets_low_file << \"# unfiltered hash data\\n\";\n      for (Size index = 0; index < rt_low_hash_.getData().size(); ++index)\n      {\n        const double rt_image = rt_low_hash_.index2key(index);\n        const double height = rt_low_hash_.getData()[index];\n        dump_buckets_low_file << rt_image << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_low_file << '\\n';\n\n      dump_buckets_high_filename = dump_buckets_basename + \"_high_\" + String(dump_buckets_serial);\n      dump_buckets_high_file.open(dump_buckets_high_filename.c_str());\n\n      dump_buckets_high_file << \"# rt high hash table buckets dump ( scale, height ) : \" << dump_buckets_high_filename << std::endl;\n      dump_buckets_high_file << \"# unfiltered hash data\\n\";\n      for (Size index = 0; index < rt_high_hash_.getData().size(); ++index)\n      {\n        const double rt_image = rt_high_hash_.index2key(index);\n        const double height = rt_high_hash_.getData()[index];\n        dump_buckets_high_file << rt_image << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_high_file << '\\n';\n    }\n\n    ++filtering_stage;\n\n    // apply tophat filter to histogram\n    MorphologicalFilter morph_filter;\n    Param morph_filter_param;\n    morph_filter_param.setValue(\"struc_elem_unit\", \"DataPoints\");\n    morph_filter_param.setValue(\"struc_elem_length\", double(struc_elem_length_datapoints));\n    morph_filter_param.setValue(\"method\", \"tophat\");\n    morph_filter.setParameters(morph_filter_param);\n\n    typedef Math::LinearInterpolation<double, double> LinearInterpolationType_;\n    LinearInterpolationType_::container_type buffer(rt_low_hash_.getData().size());\n    morph_filter.filterRange(rt_low_hash_.getData().begin(), rt_low_hash_.getData().end(), buffer.begin());\n    rt_low_hash_.getData().swap(buffer);\n    morph_filter.filterRange(rt_high_hash_.getData().begin(), rt_high_hash_.getData().end(), buffer.begin());\n    rt_high_hash_.getData().swap(buffer);\n\n    // optionally, dump after filtering\n    if (do_dump_buckets)\n    {\n      dump_buckets_low_file << \"# tophat filtered hash data\\n\";\n      for (Size index = 0; index < rt_low_hash_.getData().size(); ++index)\n      {\n        const double rt_image = rt_low_hash_.index2key(index);\n        const double height = rt_low_hash_.getData()[index];\n        dump_buckets_low_file << rt_image << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_low_file << '\\n';\n\n      dump_buckets_high_file << \"# tophat filtered hash data\\n\";\n      for (Size index = 0; index < rt_high_hash_.getData().size(); ++index)\n      {\n        const double rt_image = rt_high_hash_.index2key(index);\n        const double height = rt_high_hash_.getData()[index];\n        dump_buckets_high_file << rt_image << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_high_file << '\\n';\n    }\n\n    ++filtering_stage;\n\n    // compute freq_cutoff using a fancy criterion to distinguish between the noise level of the histogram and enriched histogram bins\n    double freq_cutoff_low;\n    double freq_cutoff_high;\n    do\n    {\n      {\n        std::copy(rt_low_hash_.getData().begin(), rt_low_hash_.getData().end(), buffer.begin());\n        std::sort(buffer.begin(), buffer.end(), std::greater<double>());\n        double freq_intercept = rt_low_hash_.getData().front();\n        double freq_slope = (rt_low_hash_.getData().back() - rt_low_hash_.getData().front()) / double(buffer.size())\n                            / scaling_histogram_crossing_slope;\n        if (!freq_slope || !buffer.size())\n        {\n          // in fact these conditions are actually impossible, but let's be really sure ;-)\n          freq_cutoff_low = 0;\n        }\n        else\n        {\n          Size index = 1; // not 0 (!)\n          while (buffer[index] >= freq_intercept + freq_slope * double(index))\n          {\n            ++index;\n          }\n          freq_cutoff_low = buffer[--index]; // note that we have index >= 1\n        }\n      }\n      {\n        std::copy(rt_high_hash_.getData().begin(), rt_high_hash_.getData().end(), buffer.begin());\n        std::sort(buffer.begin(), buffer.end(), std::greater<double>());\n        double freq_intercept = rt_high_hash_.getData().front();\n        double freq_slope = (rt_high_hash_.getData().back() - rt_high_hash_.getData().front()) / double(buffer.size())\n                            / scaling_histogram_crossing_slope;\n        if (!freq_slope || !buffer.size())\n        {\n          // in fact these conditions are actually impossible, but let's be really sure ;-)\n          freq_cutoff_high = 0;\n        }\n        else\n        {\n          Size index = 1; // not 0 (!)\n          while (buffer[index] >= freq_intercept + freq_slope * double(index))\n          {\n            ++index;\n          }\n          freq_cutoff_high = buffer[--index]; // note that we have index >= 1\n        }\n      }\n    }\n    while (0);\n\n    // apply freq_cutoff, setting smaller values to zero\n    for (Size index = 0; index < rt_low_hash_.getData().size(); ++index)\n    {\n      if (rt_low_hash_.getData()[index] < freq_cutoff_low)\n      {\n        rt_low_hash_.getData()[index] = 0;\n      }\n    }\n    for (Size index = 0; index < rt_high_hash_.getData().size(); ++index)\n    {\n      if (rt_high_hash_.getData()[index] < freq_cutoff_high)\n      {\n        rt_high_hash_.getData()[index] = 0;\n      }\n    }\n\n    // optionally, dump after noise filtering using freq_cutoff\n    if (do_dump_buckets)\n    {\n      dump_buckets_low_file << \"# after freq_cutoff, which is: \" << freq_cutoff_low << '\\n';\n      for (Size index = 0; index < rt_low_hash_.getData().size(); ++index)\n      {\n        const double rt_image = rt_low_hash_.index2key(index);\n        const double height = rt_low_hash_.getData()[index];\n        dump_buckets_low_file << rt_image << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_low_file << '\\n';\n\n      dump_buckets_high_file << \"# after freq_cutoff, which is: \" << freq_cutoff_high << '\\n';\n      for (Size index = 0; index < rt_high_hash_.getData().size(); ++index)\n      {\n        const double rt_image = rt_high_hash_.index2key(index);\n        const double height = rt_high_hash_.getData()[index];\n        dump_buckets_high_file << rt_image << '\\t' << height << '\\t' << filtering_stage << '\\n';\n      }\n      dump_buckets_high_file << '\\n';\n    }\n\n    // iterative cut-off based on mean and stdev - relies upon scaling_cutoff_stdev_multiplier which is a bit hard to set right.\n    {\n      Math::BasicStatistics<double> statistics;\n      std::vector<double>::const_iterator data_begin = rt_low_hash_.getData().begin();\n      const Size data_size = rt_low_hash_.getData().size();\n      Size data_range_begin = 0;\n      Size data_range_end = data_size;\n      for (UInt loop = 0; loop < loops_mean_stdev_cutoff; ++loop)   // MAGIC ALERT: number of loops\n      {\n        statistics.update(data_begin + data_range_begin, data_begin + data_range_end);\n        double mean = statistics.mean() + data_range_begin;\n        double stdev = sqrt(statistics.variance());\n        data_range_begin = floor(std::max<double>(mean - scaling_cutoff_stdev_multiplier * stdev, 0));\n        data_range_end = ceil(std::min<double>(mean + scaling_cutoff_stdev_multiplier * stdev + 1, data_size));\n        const double outside_mean = rt_low_hash_.index2key(mean);\n        const double outside_stdev = stdev * rt_low_hash_.getScale();\n        // rt_low_low = (outside_mean - outside_stdev);\n        rt_low_centroid = (outside_mean);\n        // rt_low_high = (outside_mean + outside_stdev);\n        if (do_dump_buckets)\n        {\n          dump_buckets_low_file << \"# loop: \" << loop << \"  mean: \" << outside_mean << \"  stdev: \" << outside_stdev << \"  (mean-stdev): \" << outside_mean\n          - outside_stdev << \"  (mean+stdev): \" << outside_mean + outside_stdev << \"  data_range_begin: \" << data_range_begin << \"  data_range_end: \"\n                                << data_range_end << std::endl;\n        }\n      }\n    }\n\n    // iterative cut-off based on mean and stdev - relies upon scaling_cutoff_stdev_multiplier which is a bit hard to set right.\n    {\n      Math::BasicStatistics<double> statistics;\n      std::vector<double>::const_iterator data_begin = rt_high_hash_.getData().begin();\n      const Size data_size = rt_high_hash_.getData().size();\n      Size data_range_begin = 0;\n      Size data_range_end = data_size;\n      for (UInt loop = 0; loop < loops_mean_stdev_cutoff; ++loop)   // MAGIC ALERT: number of loops\n      {\n        statistics.update(data_begin + data_range_begin, data_begin + data_range_end);\n        double mean = statistics.mean() + data_range_begin;\n        double stdev = sqrt(statistics.variance());\n        data_range_begin = floor(std::max<double>(mean - scaling_cutoff_stdev_multiplier * stdev - 1, 0));\n        data_range_end = ceil(std::min<double>(mean + scaling_cutoff_stdev_multiplier * stdev + 2, data_size));\n        const double outside_mean = rt_high_hash_.index2key(mean);\n        const double outside_stdev = stdev * rt_high_hash_.getScale();\n        // rt_high_low = (outside_mean - outside_stdev);\n        rt_high_centroid = (outside_mean);\n        // rt_high_high = (outside_mean + outside_stdev);\n        if (do_dump_buckets)\n        {\n          dump_buckets_high_file << \"# loop: \" << loop << \"  mean: \" << outside_mean << \"  stdev: \" << outside_stdev << \"  (mean-stdev): \" << outside_mean\n          - outside_stdev << \"  (mean+stdev): \" << outside_mean + outside_stdev << \"  data_range_begin: \" << data_range_begin << \"  data_range_end: \"\n                                 << data_range_end << std::endl;\n        }\n      }\n    }\n    if (do_dump_buckets)\n    {\n      dump_buckets_low_file << \"# EOF\" << std::endl;\n      dump_buckets_low_file.close();\n      dump_buckets_high_file << \"# EOF\" << std::endl;\n      dump_buckets_high_file.close();\n    }\n  }\n\n  double computeIntensityRatio(const std::vector<Peak2D> & model_map, const std::vector<Peak2D> & scene_map)\n  {\n    double total_int_model_map = 0;\n    for (Size i = 0; i < model_map.size(); ++i)\n    {\n      total_int_model_map += model_map[i].getIntensity();\n    }\n\n    double total_int_scene_map = 0;\n    for (Size i = 0; i < scene_map.size(); ++i)\n    {\n      total_int_scene_map += scene_map[i].getIntensity();\n    }\n\n    return total_int_model_map / total_int_scene_map;\n  }\n\n  void PoseClusteringAffineSuperimposer::run(const std::vector<Peak2D> & map_model,\n                                             const std::vector<Peak2D> & map_scene, \n                                             TransformationDescription & transformation)\n\n  {\n    if (map_model.empty() || map_scene.empty())\n    {\n      throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n                                       \"One of the input maps is empty! This is not allowed!\");\n    }\n\n    //**************************************************************************\n    // Parameters\n    //**************************************************************************\n\n    // number of data points in structuring element for tophat filter, which removes baseline from histogram\n    const UInt struc_elem_length_datapoints = 21;\n    // used when distinguishing noise level and enriched histogram bins\n    const double scaling_histogram_crossing_slope = 3.0;\n    // multiplier for stdev in cutoff for outliers\n    const double scaling_cutoff_stdev_multiplier = 1.5;\n    // number of loops in stdev cutoff for outliers\n    const UInt loops_mean_stdev_cutoff = 3;\n    // Each m/z window is given unit weight. If there are too many pairs for a\n    // window, the individual contributions will be very small, but running\n    // time will be high, so we provide a cutoff for this.  Typically this will\n    // exclude compounds which elute over the whole retention time range from\n    // consideration.\n    // This may lead to the exclusion of certain m/z windows that are very\n    // crowded.\n    const double winlength_factor_baseline = 0.1;\n\n    /// Maximum deviation in mz of two partner points\n    const double mz_pair_max_distance = param_.getValue(\"mz_pair_max_distance\");\n\n    //**************************************************************************\n    // Working variables\n    //**************************************************************************\n    typedef Math::LinearInterpolation<double, double> LinearInterpolationType_;\n    // these are a set of hashes that transform bins to actual RT values ...\n    LinearInterpolationType_ scaling_hash_1; //scaling estimate from round 1 hashing\n    LinearInterpolationType_ scaling_hash_2; //scaling estimate from round 2 hashing\n    LinearInterpolationType_ rt_low_hash_; // rt shift estimate of map start\n    LinearInterpolationType_ rt_high_hash_; // rt shift estimate of map end\n    UInt actual_progress = 0;\n\n    startProgress(0, 100, \"affine pose clustering\");\n    setProgress(++actual_progress);\n    // Optionally, we will write dumps of the hash table buckets.\n    bool do_dump_buckets = false;\n    String dump_buckets_basename;\n    if (param_.getValue(\"dump_buckets\") != \"\")\n    {\n      do_dump_buckets = true;\n      dump_buckets_basename = param_.getValue(\"dump_buckets\");\n    }\n    setProgress(++actual_progress);\n\n    // Even more optionally, we will write dumps of the hashed pairs.\n    bool do_dump_pairs = false;\n    String dump_pairs_basename;\n    if (param_.getValue(\"dump_pairs\") != \"\")\n    {\n      do_dump_pairs = true;\n      dump_pairs_basename = param_.getValue(\"dump_pairs\");\n    }\n    setProgress(++actual_progress);\n\n    //**************************************************************************\n    // Step 1: Select the most abundant data points only.\n    //**************************************************************************\n    // use copy to truncate\n    std::vector<Peak2D> model_map(map_model);\n    std::vector<Peak2D> scene_map(map_scene);\n    {\n      // truncate the data as necessary\n      const Size num_used_points = (Int) param_.getValue(\"num_used_points\");\n\n      // sort the last data points by ascending intensity (from the right, using reverse iterators)\n      //  -> linear in complexity, should be faster than sorting and then taking cutoff\n      if (model_map.size() > num_used_points)\n      {\n        std::nth_element(model_map.rbegin(), model_map.rbegin() + (model_map.size() - num_used_points),\n            model_map.rend(), Peak2D::IntensityLess());\n        model_map.resize(num_used_points);\n      }\n      setProgress(++actual_progress);\n      if (scene_map.size() > num_used_points)\n      {\n        std::nth_element(scene_map.rbegin(), scene_map.rbegin() + (scene_map.size() - num_used_points),\n            scene_map.rend(), Peak2D::IntensityLess());\n        scene_map.resize(num_used_points);\n      }\n      setProgress(++actual_progress);\n    }\n    // sort by ascending m/z\n    std::sort(model_map.begin(), model_map.end(), Peak2D::MZLess());\n    std::sort(scene_map.begin(), scene_map.end(), Peak2D::MZLess());\n    setProgress((actual_progress = 10));\n\n    //**************************************************************************\n    // Preprocessing\n    //**************************************************************************\n    // take estimates of the minimal / maximal element from both maps\n    // possible improvement: use the truncated map from above which should be\n    // more reliable (one outlier of low intensity could derail the estimate\n    // below)\n    const double model_minrt = std::min_element(map_model.begin(), map_model.end(), Peak2D::RTLess())->getRT();\n    const double scene_minrt = std::min_element(map_scene.begin(), map_scene.end(), Peak2D::RTLess())->getRT();\n    const double model_maxrt = std::max_element(map_model.begin(), map_model.end(), Peak2D::RTLess())->getRT();\n    const double scene_maxrt = std::max_element(map_scene.begin(), map_scene.end(), Peak2D::RTLess())->getRT();\n    const double rt_low =  (model_minrt + scene_minrt) / 2.;\n    const double rt_high = (model_maxrt + scene_maxrt) / 2.;\n\n    //**************************************************************************\n    // Sanity check\n    //**************************************************************************\n    {\n      // crude estimate of the shift and slope\n      double shift = std::fabs(model_minrt - scene_minrt);\n      double slope = (model_maxrt - model_minrt) / (scene_maxrt - scene_minrt);\n\n      if ( (double)param_.getValue(\"max_scaling\") < slope * 1.2 || \n           1.0 / (double)param_.getValue(\"max_scaling\") > slope / 1.2)\n      {\n        std::cout << \"WARNING: your map likely has a scaling around \" << slope\n          << \" but your parameters only allow for a maximal scaling of \" <<\n          param_.getValue(\"max_scaling\") << std::endl;\n        std::cout << \"It is strongly adviced to adjust your max_scaling factor\" << std::endl;\n      }\n\n      if ( (double)param_.getValue(\"max_shift\") < shift * 1.2)\n      {\n        std::cout << \"WARNING: your map likely has a shift around \" << shift\n          << \" but your parameters only allow for a maximal shift of \" <<\n          param_.getValue(\"max_shift\") << std::endl;\n        std::cout << \"It is strongly adviced to adjust your max_shift factor\" << std::endl;\n      }\n\n    }\n    \n\n    // Distance in RT two points need to have at most to be considered for clustering\n    const double rt_pair_min_distance = (double) param_.getValue(\"rt_pair_distance_fraction\") * (rt_high - rt_low);\n\n    //**************************************************************************\n    // Step 2: Initialize the hash tables: rt_scaling_hash_, rt_low_hash_, and\n    //         rt_high_hash_. (over)estimate the required number of buckets\n    //         for scaling\n    //         Note: the user-specified bucket size only applies to scales\n    //         around 1.  The hashing uses a log transformation because we do\n    //         not like skewed distributions.\n    //**************************************************************************\n    initializeHashTables(scaling_hash_1, scaling_hash_2, rt_low_hash_, rt_high_hash_,\n                         param_.getValue(\"max_scaling\"), param_.getValue(\"max_shift\"),\n                         param_.getValue(\"scaling_bucket_size\"), param_.getValue(\"shift_bucket_size\"),\n                         rt_low, rt_high);\n\n    setProgress(++actual_progress);\n\n    //**************************************************************************\n    // Step 3: compute the ratio of the total intensities of both maps, for\n    //         normalization\n    //**************************************************************************\n    double total_intensity_ratio = computeIntensityRatio(model_map, scene_map);\n    setProgress((actual_progress = 20));\n\n    // The serial number is incremented for each invocation of this, to avoid\n    // overwriting of hash table dumps.\n    static Int dump_buckets_serial = 0;\n    ++dump_buckets_serial;\n\n    //**************************************************************************\n    // Step 4: Hashing\n    //         Compute the transformations between each point pair in the model\n    //         map and each point pair in the scene map and hash the affine\n    //         transformation.\n    //\n    //         To speed up the calculation of the final transformation, we\n    //         confine the number of considered point pairs.  We match a point\n    //         p in the model map only onto those points p' in the scene map\n    //         that lie in a certain mz interval.\n    //**************************************************************************\n\n    ///////////////////////////////////////////////////////////////////\n    // Step 4.1 First round of hashing: Estimate the scaling\n    affineTransformationHashing(\n      do_dump_pairs,\n      model_map, scene_map,\n      scaling_hash_1, scaling_hash_2, rt_low_hash_, rt_high_hash_,\n      1,\n      rt_pair_min_distance,\n      dump_pairs_basename,\n      dump_buckets_serial,\n      mz_pair_max_distance,\n      winlength_factor_baseline,\n      total_intensity_ratio,\n      -1, // only used in 2nd round of hashing\n      -1, // only used in 2nd round of hashing\n      rt_low, rt_high);\n    setProgress((actual_progress = 30));\n\n    ///////////////////////////////////////////////////////////////////\n    // Step 4.2 Estimate the scaling factor (and potential bounds) based on the\n    // histogram work on rt_scaling_hash_\n    double scale_low_1;\n    double scale_centroid_1;\n    double scale_high_1;\n    scalingEstimate(\n      scaling_hash_1,\n      do_dump_buckets,\n      struc_elem_length_datapoints,\n      dump_buckets_basename,\n      dump_buckets_serial,\n      scaling_histogram_crossing_slope,\n      scaling_cutoff_stdev_multiplier,\n      loops_mean_stdev_cutoff,\n      scale_low_1,\n      scale_high_1,\n      scale_centroid_1);\n    setProgress((actual_progress = 40));\n\n    ///////////////////////////////////////////////////////////////////\n    // Step 4.3 Second round of hashing: Estimate the shift at both ends and\n    // thereby re-estimate the scaling. This uses the first guess of the\n    // scaling to reduce noise in the histograms.\n    affineTransformationHashing(\n      do_dump_pairs,\n      model_map, scene_map,\n      scaling_hash_1, scaling_hash_2, rt_low_hash_, rt_high_hash_,\n      2,\n      rt_pair_min_distance,\n      dump_pairs_basename,\n      dump_buckets_serial,\n      mz_pair_max_distance,\n      winlength_factor_baseline,\n      total_intensity_ratio,\n      scale_low_1,\n      scale_high_1,\n      rt_low, rt_high);\n    setProgress((actual_progress = 50));\n\n    ///////////////////////////////////////////////////////////////////\n    // Step 4.4 Estimate the shift factor at start/end of the map based on the\n    // histogram work on rt_low_hash_ and rt_high_hash_\n    double rt_low_centroid;\n    double rt_high_centroid;\n    shiftEstimate(\n      do_dump_buckets,\n      rt_low_hash_,\n      rt_high_hash_,\n      dump_buckets_serial,\n      struc_elem_length_datapoints,\n      scaling_histogram_crossing_slope,\n      scaling_cutoff_stdev_multiplier,\n      loops_mean_stdev_cutoff,\n      dump_buckets_basename,\n      rt_low_centroid,\n      rt_high_centroid);\n    setProgress(80);\n\n    //**************************************************************************\n    // Step 5: Estimate transform\n    //         Compute the shifts at the low and high ends by either using the\n    //         estimated centroids from the distribution (new method) or by\n    //         looking at (around) the fullest bins (old method).\n    //**************************************************************************\n\n    double rt_low_image;\n    double rt_high_image;\n\n    // 5.1 use centroids for images of rt_low and rt_high\n#if 1\n    rt_low_image = rt_low_centroid;\n    rt_high_image = rt_high_centroid;\n#else\n    // Alternative: use maximum bins instead (i.e. most likely shift)\n    // (Note: this is a fossil which would disregard most of the above\n    // computations! The code is left here for developers/debugging only.)\n    // This does not fully take into account the shape of the histogram and may\n    // be potentially not be as robust as working on histogram data\n\n    const Size rt_low_max_index = std::distance(rt_low_hash_.getData().begin(),\n                                                std::max_element(rt_low_hash_.getData().begin(), rt_low_hash_.getData().end()));\n    rt_low_image = rt_low_hash_.index2key(rt_low_max_index);\n\n    const Size rt_high_max_index = std::distance(rt_high_hash_.getData().begin(), std::max_element(rt_high_hash_.getData().begin(),\n                                                                                                   rt_high_hash_.getData().end()));\n    rt_high_image = rt_high_hash_.index2key(rt_high_max_index);\n#endif\n\n    setProgress(++actual_progress);\n\n    // 5.2 compute slope and intercept from matching high/low retention times\n    {\n      Param params;\n      const double slope = ((rt_high_image - rt_low_image) / (rt_high - rt_low));\n      params.setValue(\"slope\", slope);\n\n      const double intercept = rt_low_image - rt_low * slope;\n      params.setValue(\"intercept\", intercept);\n\n      if (boost::math::isinf(slope) || boost::math::isnan(slope) || boost::math::isinf(intercept) || boost::math::isnan(intercept))\n      {\n        throw Exception::InvalidValue(__FILE__, __LINE__, __PRETTY_FUNCTION__,\n                                      String(\"Superimposer could not compute an initial transformation!\") +\n                                      \"You can try to increase 'max_num_peaks_considered' to solve this.\", String(intercept * slope));\n      }\n\n      transformation.fitModel(\"linear\", params);       // no data, but explicit parameters\n    }\n\n    setProgress(++actual_progress);\n    endProgress();\n  }\n\n  void PoseClusteringAffineSuperimposer::run(const ConsensusMap& map_model,\n                                             const ConsensusMap& map_scene,\n                                             TransformationDescription& transformation)\n  {\n    std::vector<Peak2D> c_map_model, c_map_scene;\n    for (ConsensusMap::const_iterator it = map_model.begin(); it != map_model.end(); ++it)\n    {\n      Peak2D c;\n      c.setIntensity( it->getIntensity() );\n      c.setRT( it->getRT() );\n      c.setMZ( it->getMZ() );\n      c_map_model.push_back(c);\n    }\n    for (ConsensusMap::const_iterator it = map_scene.begin(); it != map_scene.end(); ++it)\n    {\n      Peak2D c;\n      c.setIntensity( it->getIntensity() );\n      c.setRT( it->getRT() );\n      c.setMZ( it->getMZ() );\n      c_map_scene.push_back(c);\n    }\n\n    run(c_map_model, c_map_scene, transformation);\n  }\n\n} // namespace OpenMS\n", "meta": {"hexsha": "b1e729503a7ac69978dae181cd9c6a3fa3e28e7b", "size": 51372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/MAPMATCHING/PoseClusteringAffineSuperimposer.cpp", "max_stars_repo_name": "freestyle076/MyOpenMS", "max_stars_repo_head_hexsha": "99a484ce8fe598a95934e782f3ec47acab33c013", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-06T14:12:09.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-06T14:12:09.000Z", "max_issues_repo_path": "src/openms/source/ANALYSIS/MAPMATCHING/PoseClusteringAffineSuperimposer.cpp", "max_issues_repo_name": "freestyle076/MyOpenMS", "max_issues_repo_head_hexsha": "99a484ce8fe598a95934e782f3ec47acab33c013", "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/MAPMATCHING/PoseClusteringAffineSuperimposer.cpp", "max_forks_repo_name": "freestyle076/MyOpenMS", "max_forks_repo_head_hexsha": "99a484ce8fe598a95934e782f3ec47acab33c013", "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": 47.2169117647, "max_line_length": 162, "alphanum_fraction": 0.6100599548, "num_tokens": 11328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.019124034899065213, "lm_q1q2_score": 0.008594200706937892}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Sat 26 May 2018 14:35:45\n\n#ifndef ScalarSingletDM_Z3_SLHA_IO_H\n#define ScalarSingletDM_Z3_SLHA_IO_H\n\n#include \"ScalarSingletDM_Z3_mass_eigenstates.hpp\"\n#include \"ScalarSingletDM_Z3_model_slha.hpp\"\n#include \"ScalarSingletDM_Z3_info.hpp\"\n#include \"ScalarSingletDM_Z3_observables.hpp\"\n#include \"ScalarSingletDM_Z3_physical.hpp\"\n#include \"problems.hpp\"\n#include \"spectrum_generator_problems.hpp\"\n#include \"standard_model_two_scale_model.hpp\"\n#include \"slha_io.hpp\"\n#include \"ckm.hpp\"\n#include \"ew_input.hpp\"\n#include \"lowe.h\"\n\n#include <Eigen/Core>\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/fusion/adapted/std_tuple.hpp>\n\n#define Pole(p) physical.p\n#define PHYSICAL(p) model.get_physical().p\n#define PHYSICAL_SLHA(p) model.get_physical_slha().p\n#define LOCALPHYSICAL(p) physical.p\n#define MODEL model\n#define MODELPARAMETER(p) model.get_##p()\n#define EXTRAPARAMETER(p) model.get_##p()\n#define OBSERVABLES observables\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define SCALES(p) scales.p\n\nnamespace flexiblesusy {\n\nstruct ScalarSingletDM_Z3_input_parameters;\nclass Spectrum_generator_settings;\n\ntemplate <class T>\nclass ScalarSingletDM_Z3;\n\nstruct ScalarSingletDM_Z3_scales {\n   double HighScale{0.}, SUSYScale{0.}, LowScale{0.};\n   double pole_mass_scale{0.};\n};\n\nclass ScalarSingletDM_Z3_slha_io {\npublic:\n   ScalarSingletDM_Z3_slha_io();\n\n   void clear();\n\n   void fill(softsusy::QedQcd& qedqcd) const { slha_io.fill(qedqcd); }\n   void fill(ScalarSingletDM_Z3_input_parameters&) const;\n   void fill(ScalarSingletDM_Z3_mass_eigenstates&) const;\n   template <class Model> void fill(ScalarSingletDM_Z3_slha<Model>&) const;\n   void fill(Physical_input&) const;\n   void fill(Spectrum_generator_settings&) const;\n   double get_parameter_output_scale() const;\n   const SLHA_io& get_slha_io() const { return slha_io; }\n   void read_from_file(const std::string&);\n   void read_from_source(const std::string&);\n   void read_from_stream(std::istream&);\n   void set_block(const std::string& str, SLHA_io::Position position = SLHA_io::back) { slha_io.set_block(str, position); }\n   void set_blocks(const std::vector<std::string>& vec, SLHA_io::Position position = SLHA_io::back) { slha_io.set_blocks(vec, position); }\n   template <class Model> void set_extra(const ScalarSingletDM_Z3_slha<Model>&, const ScalarSingletDM_Z3_scales&, const ScalarSingletDM_Z3_observables&);\n   void set_input(const ScalarSingletDM_Z3_input_parameters&);\n   void set_modsel(const SLHA_io::Modsel&);\n   void set_physical_input(const Physical_input&);\n   void set_settings(const Spectrum_generator_settings&);\n   void set_sminputs(const softsusy::QedQcd&);\n   template <class... Ts> void set_spectrum(const std::tuple<Ts...>&);\n   template <class Model> void set_spectrum(const ScalarSingletDM_Z3_slha<Model>&);\n   template <class T> void set_spectrum(const ScalarSingletDM_Z3<T>&);\n   void set_spectrum(const standard_model::Standard_model& m) { slha_io.set_spectrum(m); }\n   void set_spinfo(const Spectrum_generator_problems&);\n   void set_spinfo(const Problems&);\n   void set_spinfo(const std::vector<std::string>&, const std::vector<std::string>&);\n   void set_print_imaginary_parts_of_majorana_mixings(bool);\n   void write_to(const std::string&) const;\n   void write_to_file(const std::string& file_name) const { slha_io.write_to_file(file_name); }\n   void write_to_stream(std::ostream& ostr = std::cout) const { slha_io.write_to_stream(ostr); }\n\n   static void fill_minpar_tuple(ScalarSingletDM_Z3_input_parameters&, int, double);\n   static void fill_extpar_tuple(ScalarSingletDM_Z3_input_parameters&, int, double);\n   static void fill_imminpar_tuple(ScalarSingletDM_Z3_input_parameters&, int, double);\n   static void fill_imextpar_tuple(ScalarSingletDM_Z3_input_parameters&, int, double);\n\n   template <class Model>\n   static void fill_slhaea(SLHAea::Coll&, const ScalarSingletDM_Z3_slha<Model>&, const softsusy::QedQcd&, const ScalarSingletDM_Z3_scales&, const ScalarSingletDM_Z3_observables&);\n\n   template <class Model>\n   static SLHAea::Coll fill_slhaea(const ScalarSingletDM_Z3_slha<Model>&, const softsusy::QedQcd&, const ScalarSingletDM_Z3_scales&, const ScalarSingletDM_Z3_observables&);\n\nprivate:\n   SLHA_io slha_io; ///< SLHA io class\n   bool print_imaginary_parts_of_majorana_mixings;\n\n   void set_extpar(const ScalarSingletDM_Z3_input_parameters&);\n   void set_imminpar(const ScalarSingletDM_Z3_input_parameters&);\n   void set_imextpar(const ScalarSingletDM_Z3_input_parameters&);\n   void set_minpar(const ScalarSingletDM_Z3_input_parameters&);\n   void set_mass(const ScalarSingletDM_Z3_physical&, bool);\n   void set_mixing_matrices(const ScalarSingletDM_Z3_physical&, bool);\n   template <class Model> void set_model_parameters(const ScalarSingletDM_Z3_slha<Model>&);\n   void set_ckm(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   void set_pmns(const Eigen::Matrix<std::complex<double>,3,3>&, double);\n   double read_scale() const;\n   void fill_drbar_parameters(ScalarSingletDM_Z3_mass_eigenstates&) const;\n   void fill_physical(ScalarSingletDM_Z3_physical&) const;\n};\n\n/**\n * Reads DR-bar parameters, pole masses and mixing matrices from a\n * SLHA output file.\n */\ntemplate <class Model>\nvoid ScalarSingletDM_Z3_slha_io::fill(ScalarSingletDM_Z3_slha<Model>& model) const\n{\n   fill(static_cast<ScalarSingletDM_Z3_mass_eigenstates&>(model));\n   fill_physical(model.get_physical_slha());\n}\n\ntemplate <class Model>\nvoid ScalarSingletDM_Z3_slha_io::fill_slhaea(\n   SLHAea::Coll& slhaea, const ScalarSingletDM_Z3_slha<Model>& model,\n   const softsusy::QedQcd& qedqcd, const ScalarSingletDM_Z3_scales& scales,\n   const ScalarSingletDM_Z3_observables& observables)\n{\n   ScalarSingletDM_Z3_slha_io slha_io;\n   const ScalarSingletDM_Z3_input_parameters& input = model.get_input();\n   const auto& problems = model.get_problems();\n   const bool error = problems.have_problem();\n\n   slha_io.set_spinfo(problems);\n   slha_io.set_sminputs(qedqcd);\n   slha_io.set_input(input);\n   if (!error) {\n      slha_io.set_spectrum(model);\n      slha_io.set_extra(model, scales, observables);\n   }\n\n   slhaea = slha_io.get_slha_io().get_data();\n}\n\ntemplate <class Model>\nSLHAea::Coll ScalarSingletDM_Z3_slha_io::fill_slhaea(\n   const ScalarSingletDM_Z3_slha<Model>& model, const softsusy::QedQcd& qedqcd,\n   const ScalarSingletDM_Z3_scales& scales, const ScalarSingletDM_Z3_observables& observables)\n{\n   SLHAea::Coll slhaea;\n   ScalarSingletDM_Z3_slha_io::fill_slhaea(slhaea, model, qedqcd, scales, observables);\n\n   return slhaea;\n}\n\n/**\n * Stores the model (DR-bar) parameters in the SLHA object.\n *\n * @param model model class\n */\ntemplate <class Model>\nvoid ScalarSingletDM_Z3_slha_io::set_model_parameters(const ScalarSingletDM_Z3_slha<Model>& model)\n{\n   {\n      std::ostringstream block;\n      block << \"Block gauge Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(g1) * 0.7745966692414834), \"g1 * 0.7745966692414834\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(g2)), \"g2\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(g3)), \"g3\")\n      ;\n      slha_io.set_block(block);\n   }\n   slha_io.set_block(\"Yu\", ToMatrix(MODELPARAMETER(Yu_slha)), \"Yu\", model.get_scale());\n   slha_io.set_block(\"Yd\", ToMatrix(MODELPARAMETER(Yd_slha)), \"Yd\", model.get_scale());\n   slha_io.set_block(\"Ye\", ToMatrix(MODELPARAMETER(Ye_slha)), \"Ye\", model.get_scale());\n   {\n      std::ostringstream block;\n      block << \"Block HMIX Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(v)), \"v\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block SM Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (MODELPARAMETER(muH)), \"muH\")\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(LamH)), \"LamH\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block MSOFT Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(22, (MODELPARAMETER(muS)), \"muS\")\n            << FORMAT_ELEMENT(22, (MODELPARAMETER(mu3)), \"mu3\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block HDM Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(2, (MODELPARAMETER(LamSH)), \"LamSH\")\n            << FORMAT_ELEMENT(3, (MODELPARAMETER(LamS)), \"LamS\")\n      ;\n      slha_io.set_block(block);\n   }\n\n\n}\n\n/**\n * Writes extra SLHA blocks\n *\n * @param model model class\n * @param scales struct of boundary condition scales\n * @param observables struct of observables\n */\ntemplate <class Model>\nvoid ScalarSingletDM_Z3_slha_io::set_extra(\n   const ScalarSingletDM_Z3_slha<Model>& model, const ScalarSingletDM_Z3_scales& scales,\n   const ScalarSingletDM_Z3_observables& observables)\n{\n   const ScalarSingletDM_Z3_physical physical(model.get_physical_slha());\n\n   {\n      std::ostringstream block;\n      block << \"Block FlexibleSUSYLowEnergy Q= \" << FORMAT_SCALE(model.get_scale()) << '\\n'\n            << FORMAT_ELEMENT(1, (OBSERVABLES.a_muon), \"Delta(g-2)_muon/2 FlexibleSUSY\")\n      ;\n      slha_io.set_block(block);\n   }\n   {\n      std::ostringstream block;\n      block << \"Block EFFHIGGSCOUPLINGS\" << '\\n'\n            << FORMAT_RANK_THREE_TENSOR(25, 22, 22, (Abs(OBSERVABLES.eff_cp_higgs_photon_photon)), \"Abs(effective H-Photon-Photon coupling)\")\n            << FORMAT_RANK_THREE_TENSOR(25, 21, 21, (Abs(OBSERVABLES.eff_cp_higgs_gluon_gluon)), \"Abs(effective H-Gluon-Gluon coupling)\")\n      ;\n      slha_io.set_block(block);\n   }\n\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices of\n * all given models in the SLHA object.\n *\n * @todo Use generic lambda instead of Set_spectrum in C++14\n *\n * @param models model classes\n */\ntemplate <class... Ts>\nvoid ScalarSingletDM_Z3_slha_io::set_spectrum(const std::tuple<Ts...>& models)\n{\n   Set_spectrum<ScalarSingletDM_Z3_slha_io> ss(this);\n   boost::fusion::for_each(models, ss);\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in BPMZ convention\n */\ntemplate <class T>\nvoid ScalarSingletDM_Z3_slha_io::set_spectrum(const ScalarSingletDM_Z3<T>& model)\n{\n   set_spectrum(ScalarSingletDM_Z3_slha<ScalarSingletDM_Z3<T> >(model));\n}\n\n/**\n * Stores the model (DR-bar) parameters, masses and mixing matrices in\n * the SLHA object.\n *\n * @param model model class in SLHA convention\n */\ntemplate <class Model>\nvoid ScalarSingletDM_Z3_slha_io::set_spectrum(const ScalarSingletDM_Z3_slha<Model>& model)\n{\n   const ScalarSingletDM_Z3_physical physical(model.get_physical_slha());\n   const bool write_sm_masses = model.do_calculate_sm_pole_masses();\n\n   set_model_parameters(model);\n   set_mass(physical, write_sm_masses);\n   set_mixing_matrices(physical, write_sm_masses);\n\n   if (slha_io.get_modsel().quark_flavour_violated)\n      set_ckm(model.get_ckm_matrix(), model.get_scale());\n\n   if (slha_io.get_modsel().lepton_flavour_violated)\n      set_pmns(model.get_pmns_matrix(), model.get_scale());\n}\n\n} // namespace flexiblesusy\n\n#undef Pole\n#undef PHYSICAL\n#undef PHYSICAL_SLHA\n#undef LOCALPHYSICAL\n#undef MODEL\n#undef MODELPARAMETER\n#undef EXTRAPARAMETER\n#undef OBSERVABLES\n#undef LowEnergyConstant\n#undef SCALES\n\n#endif\n", "meta": {"hexsha": "ebbbd87c1bcb84d3f5e2b53e4e45daee4be465a9", "size": 12252, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/ScalarSingletDM_Z3/ScalarSingletDM_Z3_slha_io.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/ScalarSingletDM_Z3/ScalarSingletDM_Z3_slha_io.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/ScalarSingletDM_Z3/ScalarSingletDM_Z3_slha_io.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.1272727273, "max_line_length": 179, "alphanum_fraction": 0.7312275547, "num_tokens": 3290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.022977368990089356, "lm_q1q2_score": 0.008590682736298526}}
{"text": "/**\n * @Author: Maxime Agor (4rzael)\n * @Date:   Sat Jun 23 2018\n * @Email:  maxime.agor23@gmail.com\n * @Project: CUDA-Based Simulator of Quantum Systems\n * @Filename: ASTGenerator.cpp\n * @Last modified by:   4rzael\n * @Last modified time: Sat Jun 23 2018, 14:31:04\n * @License: MIT License\n */\n\n#include <string>\n#include <fstream>\n#include <ctime>\n#include <boost/spirit/home/x3.hpp>\n\n#include \"Parser/AST.hpp\"\n#include \"Parser/ASTGenerator.hpp\"\n#include \"Logger.hpp\"\n#include \"Errors.hpp\"\n\nusing namespace boost::spirit::x3;\nusing namespace Parser;\nusing namespace Parser::AST;\n\nnamespace Parser {\n    /* This describes the grammar, which will be parsed using the library boost spirit x3\n     * It can probably be simplified, by using the skip[] operation instead of the *WS,\n     * which might even make compilation faster.\n     */\n    namespace Rules {\n        /* Whitespace rules */\n        const auto WS = omit[+(lit('\\t') | '\\f' | '\\r' | '\\n' | ' ')];\n        const auto NEWLINE = omit[+(-lit('\\r') >> lit('\\n'))];\n\n        /* Whitespace-aware constructs */\n        const auto COMMA = *WS >> ',' >> *WS;\n        const auto PLUS = *WS >> char_('+') >> *WS;\n        const auto MINUS = *WS >> char_('-') >> *WS;\n        const auto TIMES = *WS >> char_('*') >> *WS;\n        const auto POWER = *WS >> char_('^') >> *WS;\n        const auto DIVIDE = *WS >> char_('/') >> *WS;\n        const auto LEFT_PARENTHESIS = *WS >> '(' >> *WS;\n        const auto RIGHT_PARENTHESIS = *WS >> ')' >> *WS;\n        const auto NONSPACED_RIGHT_PARENTHESIS = *WS >> ')';\n        const auto LEFT_BRACKET = *WS >> '[' >> *WS;\n        const auto RIGHT_BRACKET = *WS >> ']' >> *WS;\n\n        /* Basic Types */\n        const auto UNARY_OP = rule<class UNARY_OP, std::string>()\n                            = string(\"sin\") | string(\"cos\") | string(\"tan\") | string(\"exp\") | string(\"ln\") | string(\"sqrt\");\n\n        const auto RESERVED_ID = (omit[UNARY_OP] |\n            \"U\" | \"CX\" | \"reset\" | \"creg\" | \"qreg\" | \"include\" |\n            \"measure\" | \"gate\" | \"barrier\" | \"OPENQASM\");\n        const auto ID_BASE = rule<class ID_BASE, std::string>()\n                = char_(\"a-z\") >> *(alnum | char_('_'));\n        const auto ID = rule<class ID, std::string>()\n                = !RESERVED_ID >> ID_BASE;\n\n        const auto FILENAME = +(alnum | char_('.') | char_('_') | char_('-') | char_('/') | char_('\\\\'));\n        const auto FLOAT = rule<class FLOAT, t_float>()\n                        = (double_ | ID);\n        const auto UINT = uint_;\n\n        /* Float expressions types */\n        const auto float_expr_basic = rule<class float_expr_basic, t_float>()\n                                    = FLOAT;\n        rule<struct float_expr_class, t_float_expression> const float_expr = \"float_expr\";\n        rule<struct float_expr_term_class, t_float_expression> const float_expr_term = \"float_expr_term\";\n        rule<struct float_expr_factor_class, t_float_expr_operand> const float_expr_factor = \"float_expr_factor\";\n\n        const auto float_expr_def = float_expr_term\n            >> *((PLUS >> float_expr_term) | (MINUS >> float_expr_term));\n\n        const auto float_expr_term_def = float_expr_factor\n            >> *((TIMES >> float_expr_factor) | (DIVIDE >> float_expr_factor) | (POWER >> float_expr_factor));\n\n        const auto float_expr_factor_def = float_expr_basic |\n            (omit[LEFT_PARENTHESIS] >> float_expr >> omit[RIGHT_PARENTHESIS]) |\n            (string(\"-\") >> float_expr) |\n            (UNARY_OP >> omit[LEFT_PARENTHESIS] >> float_expr >> omit[RIGHT_PARENTHESIS]);\n\n        BOOST_SPIRIT_DEFINE(float_expr)\n        BOOST_SPIRIT_DEFINE(float_expr_term)\n        BOOST_SPIRIT_DEFINE(float_expr_factor)\n\n        /* Complex types */\n        const auto bit = rule<class bit, t_bit>()\n                       = ID >> LEFT_BRACKET >> UINT >> RIGHT_BRACKET;\n        const auto reg = ID;\n        const auto variable = rule<class variable, t_variable>()\n                            = bit | reg;\n        const auto qargs = rule<class qargs, t_qargs>()\n                         = variable % COMMA;\n        const auto expr_list = rule<class expr_list, t_expr_list>()\n                             = float_expr % COMMA;\n        const auto id_list = rule<class id_list, t_id_list>()\n                           = reg % COMMA;\n\n        /* Statements */\n        const auto creg_statement = rule<class creg_statement, t_creg_statement>()\n                            = \"creg\" >> WS >> bit;\n        const auto qreg_statement = rule<class qreg_statement, t_qreg_statement>()\n                            = \"qreg\" >> WS >> bit;\n        const auto include_statement = rule<class include_statement, t_include_statement>()\n                            = \"include\" >> WS >> '\"' >> FILENAME >> '\"';\n        const auto cx_statement = rule<class cx_statement, t_cx_statement>()\n                                = \"CX\" >> WS >> qargs;\n        const auto measure_statement = rule<class measure_statement, t_measure_statement>()\n                                     = \"measure\" >> WS >> variable >> *WS >> \"->\" >> *WS >> variable;\n        const auto barrier_statement = rule<class barrier_statement, t_barrier_statement>()\n                                     = \"barrier\" >> WS >> id_list;\n        const auto reset_statement = rule<class reset_statement, t_reset_statement>()\n                                   = \"reset\" >> WS >> variable;\n\n        const auto gate_call_statement = rule<class gate_call_statement, t_gate_call_statement>()\n                                       = (ID\n                                       >> -(LEFT_PARENTHESIS >> -(expr_list) >> NONSPACED_RIGHT_PARENTHESIS)\n                                       >> WS >> qargs);\n\n        /* U Statements */\n        const auto u_param = rule<class u_param, t_expr_list>()\n                           = repeat(1,1)[float_expr] >> repeat(2,2)[omit[COMMA] >> float_expr];\n\n        const auto u_statement = rule<class u_statement, t_u_statement>()\n                               = \"U\" >> omit[LEFT_PARENTHESIS]\n                               >> u_param \n                               >> omit[NONSPACED_RIGHT_PARENTHESIS >> WS] \n                               >> variable;;\n\n        /* Statement types */\n        const auto statement = rule<class statement, t_statement>()\n                    = (creg_statement |\n                       qreg_statement |\n                       include_statement |\n                       cx_statement |\n                       measure_statement |\n                       barrier_statement |\n                       reset_statement |\n                       u_statement |\n                       gate_call_statement)\n                    >> *WS >> ';';\n\n        /* Operations available inside the body of a gate */\n        const auto gate_ops = rule<class gate_ops, t_statement>()\n                    = (cx_statement |\n                       u_statement |\n                       barrier_statement |\n                       gate_call_statement)\n                    >> *WS >> ';';\n\n        /* Operations available inside a conditional statement */\n        const auto qop = rule<class qop, t_statement>()\n                    = (cx_statement |\n                       u_statement |\n                       gate_call_statement |\n                       measure_statement |\n                       reset_statement) >> *WS >> ';';\n\n        const auto comment = omit[lexeme[\"//\" >> *(~char_('\\n'))]];\n        const auto conditional_statement = rule<class conditional_statement, t_conditional_statement>()\n                                        = \"if\" >> LEFT_PARENTHESIS >>\n                                          reg >>\n                                          *WS >> \"==\" >> *WS >>\n                                          UINT >> NONSPACED_RIGHT_PARENTHESIS >> WS >>\n                                          qop;\n\n        /* Gate declaration */\n        const auto gate_code_block = rule<class gate_code_block, std::vector<t_statement>>()\n                                   = *WS >> '{' >> *(gate_ops | WS) >> '}' >> *WS;\n        const auto gate_declaration = rule<class gate_declaration, t_gate_declaration>()\n            = \"gate\" >> WS\n            >>  ID\n            >>  -(omit[LEFT_PARENTHESIS] >> -(id_list) >> omit[NONSPACED_RIGHT_PARENTHESIS])\n            >>  WS >> id_list\n            >>  gate_code_block;\n\n        /* Code */\n        const auto VERSION = omit[lexeme[\"OPENQASM 2.0;\"]];\n        const auto header = omit[*WS >> VERSION >> NEWLINE];\n\n        const auto openQASM = rule<class start, t_openQASM>()\n                            = header >> *(WS | statement | conditional_statement | gate_declaration);\n    }\n}\n\nt_openQASM ASTGenerator::operator()(std::string const &filename) {\n    /* Reads the file */\n    std::ifstream file;\n    file.exceptions (std::ios::failbit);\n    file.open(filename);\n\n    std::stringstream ss;\n    ss << file.rdbuf();\n    std::string str = ss.str();\n\n    auto iter = str.begin();\n    auto iterEnd = str.end();\n\n    /* Parse the AST */\n    t_openQASM res;\n    phrase_parse(iter, iterEnd, Parser::Rules::openQASM, Parser::Rules::comment, res);\n\n    /* If some of the content have not been parsed, it means that the parser failed */\n    if (iter != iterEnd) {\n        std::stringstream errorStream(std::string(iter, iterEnd));\n        std::string line;\n        std::getline(errorStream, line);\n\n        const auto lineNb = std::count(str.begin(), iter, '\\n') + 1;\n\n        LOG(Logger::ERROR, \"Parsing failed at line \" << lineNb << \": \" << line);\n        throw OpenQASMError();\n    }\n\n    return res;\n}\n", "meta": {"hexsha": "a5a591b75418cf33627a1882dc76cf91e7bb7d4f", "size": 9576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Parser/ASTGenerator.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/Parser/ASTGenerator.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/Parser/ASTGenerator.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": 43.7260273973, "max_line_length": 124, "alphanum_fraction": 0.5275689223, "num_tokens": 2107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798741512455283, "lm_q2_score": 0.03461884182719031, "lm_q1q2_score": 0.008585037099330676}}
{"text": "#ifndef DUNE_OSEEN_INTEGRATORS_BASE_HH\n#define DUNE_OSEEN_INTEGRATORS_BASE_HH\n\n#include <dune/stuff/grid/entity.hh>\n#include <dune/stuff/common/misc.hh>\n#include <dune/stuff/common/profiler.hh>\n#include <dune/stuff/fem/localmatrix_proxy.hh>\n#include <dune/fem/oseen/stab_coeff.hh>\n\n#include <boost/integer/static_min_max.hpp>\n\n\nnamespace Dune {\nnamespace Oseen {\nnamespace Assembler {\n\n    namespace {\n        template<int i,typename IntegratorTuple,typename InfoType,typename FunctorType>\n        struct ApplySingle\n        {\n            static inline void visit(IntegratorTuple& tuple, const InfoType& info)\n            {\n                FunctorType::apply(get<tuple_size<IntegratorTuple>::value-i>(tuple), info);\n                ApplySingle<i-1,IntegratorTuple,InfoType,FunctorType>::visit(tuple,info);\n            }\n        };\n\n        template<typename IntegratorTuple,typename InfoType,typename FunctorType>\n\tstruct ApplySingle<0, IntegratorTuple,InfoType,FunctorType>\n        {\n            static inline void visit(IntegratorTuple&, const InfoType&)\n            {}\n        };\n    }\n\ttemplate < class SigmaJacobianRangeType, class VelocityRangeType >\n\tstatic SigmaJacobianRangeType\n\t\t\tprepareVelocityRangeTypeForSigmaDivergence( const VelocityRangeType& arg )\n\t{\n\t\tSigmaJacobianRangeType ret( 0.0 );\n\t\tassert( arg.dim() == ret[0].dim() );\n\t\tfor ( int i = 0; i < int(arg.dim()) ; ++i ) {\n\t\t\tfor ( int j = 0; j < int(arg.dim()); ++j ) {\n\t\t\t\tVelocityRangeType row( 0.0 );\n\t\t\t\trow[ j ] = arg[ i ];\n\t\t\t\tret[ i * arg.dim() + j ] = row;\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\ttemplate < class Traits >\n\tstatic typename Traits::VelocityJacobianRangeType preparePressureRangeTypeForVelocityDivergence(\n\t\t\t\t\t\t\t\t\t\t\t\tconst typename Traits::PressureRangeType& arg )\n\t{\n\t\ttypename Traits::VelocityJacobianRangeType ret( 0.0 );\n\t\tfor ( unsigned int i = 0; i < ret[0].dim(); ++i ) {\n\t\t\ttypename Traits::VelocityRangeType row( 0.0 );\n\t\t\trow[ i ] = arg;\n\t\t\tret[ i ] = row;\n\t\t}\n\t\treturn ret;\n\t}\n\n    //! bring back the super useful evaluateSingle and evaluateGradientSingle which were removed from FEM's Basefunctionset\n    template < class WrappedBasefuntionsetImp >\n    class BasefunctionsetWrapper : public WrappedBasefuntionsetImp {\n            typedef typename WrappedBasefuntionsetImp::RangeFieldType\n                RangeFieldType;\n            typedef typename WrappedBasefuntionsetImp::RangeType\n                RangeType;\n            typedef typename WrappedBasefuntionsetImp::JacobianRangeType\n                JacobianRangeType;\n            typedef typename WrappedBasefuntionsetImp::DomainType\n                DomainType;\n            typedef typename WrappedBasefuntionsetImp::FunctionSpaceType\n                FunctionSpaceType;\n        public:\n            typedef WrappedBasefuntionsetImp\n                WrappedBasefuntionsetType;\n        BasefunctionsetWrapper( const WrappedBasefuntionsetType& wrapped )\n            : WrappedBasefuntionsetType( wrapped )\n        {}\n\n        /** \\copydoc Dune::BaseFunctionSetInterface::evaluateSingle(const int baseFunction,const PointType &x,const RangeType &psi) const */\n        template< class PointType >\n        inline RangeFieldType evaluateSingle ( const int baseFunction,\n                                               const PointType &x,\n                                               const RangeType &psi ) const\n        {\n          RangeType phi;\n          WrappedBasefuntionsetType::evaluate( baseFunction, x, phi );\n          return phi * psi;\n        }\n\n        /** \\copydoc Dune::BaseFunctionSetInterface::evaluateGradientSingle(const int baseFunction,const EntityType &entity,const PointType &x,const JacobianRangeType &psi) const */\n        template< class EntityType, class PointType >\n        inline RangeFieldType evaluateGradientSingle( const int baseFunction,\n                                                      const EntityType &entity,\n                                                      const PointType &x,\n                                                      const JacobianRangeType &psi ) const\n        {\n          const auto& geometry = entity.geometry();\n          const auto& jacobianInverseTransposed\n            = geometry.jacobianInverseTransposed( coordinate( x ) );\n\n          JacobianRangeType gradPhi;\n          WrappedBasefuntionsetType::jacobian( baseFunction, x, gradPhi );\n\n          RangeFieldType result = 0;\n          for( int i = 0; i < FunctionSpaceType :: dimRange; ++i )\n          {\n            DomainType gradScaled( 0 );\n            jacobianInverseTransposed.umv( gradPhi[ i ], gradScaled );\n            result += gradScaled * psi[ i ];\n          }\n          return result;\n        }\n    };\n\n    template < class Traits >\n    struct PolOrder {\n        static const int value = 2 * ( boost::static_signed_max<\n                                            boost::static_signed_max< Traits::pressureSpaceOrder,\n                                                                Traits::velocitySpaceOrder >::value,\n                                            Traits::sigmaSpaceOrder >::value\n                                      + 1 ) ;\n    };\n\n\ttemplate < class Traits, class IntegratorTuple >\n\tclass Coordinator\n\t{\n\tprotected:\n\t\ttypedef Coordinator< Traits, IntegratorTuple >\n\t\t\tCoordinatorType;\n\n\t\tconst typename Traits::DiscreteModelType&\t\t\t\t\tdiscrete_model_;\n\t\tconst typename Traits::GridPartType&\t\t\t\t\t\tgrid_part_;\n\t\tconst typename Traits::DiscreteVelocityFunctionSpaceType&\tvelocity_space_;\n\t\tconst typename Traits::DiscretePressureFunctionSpaceType&\tpressure_space_;\n\t\tconst typename Traits::DiscreteSigmaFunctionSpaceType&\t\tsigma_space_;\n\n\tpublic:\n\t\ttypedef typename Traits::ElementCoordinateType\n\t\t\tElementCoordinateType;\n\t\ttypedef typename Traits::SigmaRangeType\n\t\t\tSigmaRangeType;\n\t\ttypedef typename Traits::VelocityRangeType\n\t\t\tVelocityRangeType;\n\t\ttypedef typename Traits::PressureRangeType\n\t\t\tPressureRangeType;\n\t\ttypedef typename Traits::VelocityJacobianRangeType\n\t\t\tVelocityJacobianRangeType;\n\t\ttypedef typename Traits::PressureJacobianRangeType\n\t\t\tPressureJacobianRangeType;\n        typedef BasefunctionsetWrapper< typename Traits::DiscreteSigmaFunctionSpaceType::BaseFunctionSetType >\n\t\t\t\tSigmaBaseFunctionSetType;\n        typedef BasefunctionsetWrapper< typename Traits::DiscreteVelocityFunctionSpaceType::BaseFunctionSetType >\n\t\t\tVelocityBaseFunctionSetType;\n        typedef BasefunctionsetWrapper< typename Traits::DiscretePressureFunctionSpaceType::BaseFunctionSetType >\n\t\t\tPressureBaseFunctionSetType;\n\n\t\tCoordinator(const typename Traits::DiscreteModelType&\t\t\t\t\tdiscrete_model,\n\t\t\t\t\t\tconst typename Traits::GridPartType&\t\t\t\t\t\tgrid_part,\n\t\t\t\t\t\tconst typename Traits::DiscreteVelocityFunctionSpaceType&\tvelocity_space,\n\t\t\t\t\t\tconst typename Traits::DiscretePressureFunctionSpaceType&\tpressure_space,\n\t\t\t\t\t\tconst typename Traits::DiscreteSigmaFunctionSpaceType&\t\tsigma_space)\n\t\t\t\t\t:discrete_model_(discrete_model),\n\t\t\t\t\tgrid_part_(grid_part),\n\t\t\t\t\tvelocity_space_(velocity_space),\n\t\t\t\t\tpressure_space_(pressure_space),\n\t\t\t\t\tsigma_space_(sigma_space)\n\t\t{}\n\n\t\t//! just to avoid overly long argument lists\n\t\tstruct InfoContainerVolume {\n\t\t\tconst typename Traits::EntityType& entity;\n            const typename Traits::EntityType::Geometry geometry;\n\n\t\t\tconst SigmaBaseFunctionSetType\n\t\t\t\t\tsigma_basefunction_set_element;\n\t\t\tconst VelocityBaseFunctionSetType\n\t\t\t\t\tvelocity_basefunction_set_element;\n\t\t\tconst PressureBaseFunctionSetType\n\t\t\t\t\tpressure_basefunction_set_element;\n\t\t\tconst int numSigmaBaseFunctionsElement;\n\t\t\tconst int numVelocityBaseFunctionsElement;\n\t\t\tconst int numPressureBaseFunctionsElement;\n\t\t\tconst typename Traits::VolumeQuadratureType volumeQuadratureElement;\n\t\t\tconst typename Traits::DiscreteModelType&\tdiscrete_model;\n\t\t\tconst double eps;\n\t\t\tconst double viscosity;\n\t\t\tconst double convection_scaling;\n\t\t\tconst double pressure_gradient_scaling;\n\t\t\t//! generalized stokes alpha\n\t\t\tconst double alpha;\n\t\t\tconst typename Traits::GridPartType& grid_part;\n\t\t\tInfoContainerVolume(const CoordinatorType& interface,\n\t\t\t\t\t\t\t\tconst typename Traits::EntityType& ent,\n\t\t\t\t\t\t\t\tconst typename Traits::DiscreteModelType& discrete_modelIn,\n\t\t\t\t\t\t\t\tconst typename Traits::GridPartType& grid_partIn)\n\t\t\t\t: entity( ent ),\n\t\t\t\t  geometry( entity.geometry() ),\n\t\t\t\t  sigma_basefunction_set_element( interface.sigma_space_.baseFunctionSet( entity ) ),\n\t\t\t\t  velocity_basefunction_set_element( interface.velocity_space_.baseFunctionSet( entity ) ),\n\t\t\t\t  pressure_basefunction_set_element( interface.pressure_space_.baseFunctionSet( entity ) ),\n                  numSigmaBaseFunctionsElement( sigma_basefunction_set_element.size() ),\n                  numVelocityBaseFunctionsElement( velocity_basefunction_set_element.size() ),\n                  numPressureBaseFunctionsElement( pressure_basefunction_set_element.size() ),\n                  volumeQuadratureElement( entity, PolOrder<Traits>::value ),\n\t\t\t\t  discrete_model( discrete_modelIn ),\n\t\t\t\t  eps( DSC_CONFIG_GET( \"eps\", 1.0e-14 ) ),\n\t\t\t\t  viscosity( discrete_modelIn.viscosity() ),\n\t\t\t\t  convection_scaling( discrete_modelIn.convection_scaling() ),\n\t\t\t\t  pressure_gradient_scaling( discrete_modelIn.pressure_gradient_scaling() ),\n\t\t\t\t  alpha( discrete_modelIn.alpha() ),\n\t\t\t\t  grid_part( grid_partIn )\n\t\t\t{}\n\t\t\tvirtual ~InfoContainerVolume() {}\n\t\t};\n\t\tstruct InfoContainerFace : public InfoContainerVolume {\n            const typename Traits::IntersectionIteratorType::Intersection& intersection;\n            const typename Traits::IntersectionIteratorType::Intersection::Geometry intersectionGeometry;\n\t\t\tconst typename Traits::FaceQuadratureType faceQuadratureElement;\n\t\t\tconst double lengthOfIntersection;\n\t\t\tconst StabilizationCoefficients& stabil_coeff;\n\t\t\tconst double C_11;\n\t\t\tconst double D_11;\n\t\t\ttypename Traits::VelocityRangeType D_12;\n\n\t\t\tInfoContainerFace (const CoordinatorType& interface,\n\t\t\t\t\t\t\t\tconst typename Traits::EntityType& ent,\n\t\t\t\t\t\t\t   const typename Traits::IntersectionIteratorType::Intersection& inter,\n\t\t\t\t\t\t\t\tconst typename Traits::DiscreteModelType& discrete_modelIn,\n\t\t\t\t\t\t\t   const typename Traits::GridPartType& grid_partIn )\n\t\t\t\t:InfoContainerVolume( interface, ent, discrete_modelIn, grid_partIn ),\n\t\t\t\t  intersection( inter ),\n\t\t\t\t  intersectionGeometry( intersection.geometry() ),\n\t\t\t\t  faceQuadratureElement( interface.sigma_space_.gridPart(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  intersection,\n                                                                  PolOrder<Traits>::value,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  Traits::FaceQuadratureType::INSIDE ),\n                  lengthOfIntersection( intersection.geometry().volume() ),\n\t\t\t\t  stabil_coeff( discrete_modelIn.getStabilizationCoefficients() ),\n\t\t\t\t  C_11( penalty<-1>(ent,intersection, stabil_coeff, lengthOfIntersection ) ),\n\t\t\t\t  D_11( penalty<1>(ent,intersection, stabil_coeff, lengthOfIntersection ) ),\n\t\t\t\t  D_12( 1 )//vector!\n\t\t\t{\n\t\t\t\tD_12 /= D_12.two_norm();\n\t\t\t\tD_12 *= stabil_coeff.Factor(\"D12\");\n\t\t\t}\n\t\t};\n\n\t\tstatic double charactisticSize(const typename Traits::EntityType& entity,\n\t\t\t\t\t\t\t\t\t   const typename Traits::IntersectionIteratorType::Intersection& intersection)\n\t\t{\n            return entity.geometry().volume() / intersection.geometry().volume();\n\t\t}\n\n\t\ttemplate <int power>\n\t\tstatic double penalty(const typename Traits::EntityType& entity,\n\t\t\t\t\t\t\t  const typename Traits::EntityType& neighbour,\n\t\t\t\t\t\t\t  const typename Traits::IntersectionIteratorType::Intersection& intersection,\n\t\t\t\t\t\t\t  const Dune::StabilizationCoefficients& stabil_coeff,\n\t\t\t\t\t\t\t  const double lengthOfIntersection )\n\t\t{\n\t\t\tconst int penalty_form = DSC_CONFIG_GET( \"penalty_form\", 1 );\n\t\t\tswitch (penalty_form) {\n\t\t\t\tcase 1:\n\t\t\t\t{\n\t\t\t\t\tconst double entity_measure = std::pow( charactisticSize( entity, intersection), double(power) );\n\t\t\t\t\tconst double neighbour_measure = std::pow( charactisticSize( neighbour, intersection), double(power) );\n\t\t\t\t\treturn (entity_measure+neighbour_measure)/2.0;\n\t\t\t\t}\n\t\t\t\tcase 2:\n\t\t\t\t{\n                    const double entity_diameter = std::pow( DSG::geometryDiameter( entity ), double(power) );\n                    const double neighbour_diameter = std::pow( DSG::geometryDiameter( neighbour ), double(power) );\n\t\t\t\t\treturn std::max(entity_diameter, neighbour_diameter);\n\t\t\t\t}\n\t\t\t\tcase 3:\n\t\t\t\t{\n                    const double entity_diameter = std::pow( DSG::geometryDiameter( entity ), double(power) );\n                    const double neighbour_diameter = std::pow( DSG::geometryDiameter( neighbour ), double(power) );\n\t\t\t\t\treturn std::max(entity_diameter, neighbour_diameter) * ( power > 0 ? stabil_coeff.Factor(\"C11\") : stabil_coeff.Factor(\"D11\") );\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\tcase 4:\n\t\t\t\t{\n//\t\t\t\t\treturn std::pow( intersection.intersectionGlobal().volume(), double(power) );\n\t\t\t\t\tif (power==-1)\n\t\t\t\t\t\treturn stabil_coeff.Factor(\"C11\") * std::pow( lengthOfIntersection, stabil_coeff.Power(\"C11\") );\n\t\t\t\t\telse\n\t\t\t\t\t\treturn stabil_coeff.Factor(\"D11\") * std::pow( lengthOfIntersection, stabil_coeff.Power(\"D11\") );\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t}\n\t\ttemplate <int power>\n\t\tstatic double penalty(const typename Traits::EntityType& entity,\n\t\t\t\t\t\t\t  const typename Traits::IntersectionIteratorType::Intersection& intersection,\n\t\t\t\t\t\t\t  const Dune::StabilizationCoefficients& stabil_coeff,\n\t\t\t\t\t\t\t  const double lengthOfIntersection)\n\t\t{\n\t\t\treturn penalty<power>( entity, entity, intersection, stabil_coeff, lengthOfIntersection );\n\t\t}\n\n\t\tstruct InfoContainerInteriorFace : public InfoContainerFace {\n            const typename Traits::EntityType& neighbour;\n\t\t\tconst SigmaBaseFunctionSetType\n\t\t\t\t\tsigma_basefunction_set_neighbour;\n\t\t\tconst VelocityBaseFunctionSetType\n\t\t\t\t\tvelocity_basefunction_set_neighbour;\n\t\t\tconst PressureBaseFunctionSetType\n\t\t\t\t\tpressure_basefunction_set_neighbour;\n\t\t\tconst int numSigmaBaseFunctionsNeighbour;\n\t\t\tconst int numVelocityBaseFunctionsNeighbour;\n\t\t\tconst int numPressureBaseFunctionsNeighbour;\n\t\t\tconst typename Traits::FaceQuadratureType faceQuadratureNeighbour;\n\t\t\tconst double C_11;//yupp, we're hiding the base class members here\n\t\t\tconst double D_11;\n\n\t\t\tInfoContainerInteriorFace (const CoordinatorType& interface,\n\t\t\t\t\t\t\t\tconst typename Traits::EntityType& ent,\n\t\t\t\t\t\t\t   const typename Traits::EntityType& nei,\n\t\t\t\t\t\t\t   const typename Traits::IntersectionIteratorType::Intersection& inter,\n\t\t\t\t\t\t\t\tconst typename Traits::DiscreteModelType& discrete_modelIn,\n\t\t\t\t\t\t\t\tconst typename Traits::GridPartType& grid_partIn )\n                :InfoContainerFace( interface, ent, inter, discrete_modelIn, grid_partIn ),\n\t\t\t\t  neighbour( nei ),\n\t\t\t\t  sigma_basefunction_set_neighbour( interface.sigma_space_.baseFunctionSet( neighbour ) ),\n\t\t\t\t  velocity_basefunction_set_neighbour( interface.velocity_space_.baseFunctionSet( neighbour ) ),\n\t\t\t\t  pressure_basefunction_set_neighbour( interface.pressure_space_.baseFunctionSet( neighbour ) ),\n                  numSigmaBaseFunctionsNeighbour( sigma_basefunction_set_neighbour.size() ),\n                  numVelocityBaseFunctionsNeighbour( velocity_basefunction_set_neighbour.size() ),\n                  numPressureBaseFunctionsNeighbour( pressure_basefunction_set_neighbour.size() ),\n\t\t\t\t  faceQuadratureNeighbour( interface.sigma_space_.gridPart(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  inter,\n                                                                  PolOrder<Traits>::value,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  Traits::FaceQuadratureType::OUTSIDE ),\n\t\t\t\t  C_11( penalty<-1>( ent, nei, inter, InfoContainerFace::stabil_coeff, InfoContainerFace::lengthOfIntersection ) ),\n\t\t\t\t  D_11( penalty<1>( ent, nei, inter, InfoContainerFace::stabil_coeff, InfoContainerFace::lengthOfIntersection ) )\n\t\t\t{\n\t\t\t\t//some integration logic depends on this\n\t\t\t\tassert( InfoContainerFace::faceQuadratureElement.nop() == faceQuadratureNeighbour.nop() );\n\t\t\t}\n\t\t};\n\n\t\tstruct ApplyVolume {\n\t\t\ttemplate < class IntegratorType >\n\t\t\tstatic void apply( IntegratorType& integrator, const InfoContainerVolume& info )\n\t\t\t{\n\t\t\t\tDSC::Profiler::ScopedTiming s(integrator.name);\n\t\t\t\tintegrator.applyVolume( info );\n\t\t\t}\n\t\t};\n\n\t\tstruct ApplyInteriorFace {\n\t\t\ttemplate < class IntegratorType >\n\t\t\tstatic void apply( IntegratorType& integrator, const InfoContainerInteriorFace& info )\n\t\t\t{\n\t\t\t\tDSC::Profiler::ScopedTiming s(integrator.name);\n\t\t\t\tintegrator.applyInteriorFace( info );\n\t\t\t}\n\t\t};\n\n\t\tstruct ApplyBoundaryFace {\n\t\t\ttemplate < class IntegratorType >\n\t\t\tstatic void apply( IntegratorType& integrator, const InfoContainerFace& info )\n\t\t\t{\n\t\t\t\tDSC::Profiler::ScopedTiming s(integrator.name);\n\t\t\t\tintegrator.applyBoundaryFace( info );\n\t\t\t}\n\t\t};\n\n        //! A gloryfied For loop in 28 lines\n\t\ttemplate < class FunctorType, class InfoType >\n\t\tclass ForEachIntegrator {\n\t\t    public:\n\t\t\t//! \\brief Constructor\n\t\t\t//! \\param tuple The tuple which we want to process.\n\t\t\tForEachIntegrator(IntegratorTuple& tuple, const InfoType& info)\n\t\t\t{\n\t\t\t    ApplySingle<tuple_size<IntegratorTuple>::value,IntegratorTuple,InfoType,FunctorType>::visit(tuple, info);\n\t\t\t}\n\t\t};\n\n\t\tvoid apply ( IntegratorTuple& integrator_tuple ) const\n\t\t{\n\t\t\tDSC::Profiler::ScopedTiming assembler_time(\"assembler\");\n            const auto& gridView = grid_part_.grid().leafView();\n\n            for ( const auto& entity : DSC::viewRange(gridView))\n\t\t\t{\n                const InfoContainerVolume e_info( *this, entity, discrete_model_,grid_part_ );\n                ForEachIntegrator<ApplyVolume,InfoContainerVolume>( integrator_tuple, e_info );\n\n\t\t\t\t// walk the intersections\n\t\t\t\tconst typename Traits::IntersectionIteratorType intItEnd = gridView.iend( entity );\n\t\t\t\tfor (   typename Traits::IntersectionIteratorType intIt = gridView.ibegin( entity );\n\t\t\t\t\t\tintIt != intItEnd;\n\t\t\t\t\t\t++intIt )\n\t\t\t\t{\n\t\t\t\t\tconst typename Traits::IntersectionIteratorType::Intersection& intersection = *intIt;\n\n\t\t\t\t\t// if we are inside the grid\n\t\t\t\t\tif ( intersection.neighbor() && !intersection.boundary() )\n\t\t\t\t\t{\n\t\t\t\t\t\t//! DO NOT TRY TO DEREF outside() DIRECTLY\n                        const typename Traits::IntersectionIteratorType::Intersection::EntityPointer neighbourPtr = intersection.outside();\n                        const InfoContainerInteriorFace i_info( *this, entity, *neighbourPtr, intersection, discrete_model_,grid_part_ );\n                        ForEachIntegrator<ApplyInteriorFace,InfoContainerInteriorFace>( integrator_tuple, i_info );\n\t\t\t\t\t}\n\t\t\t\t\telse if ( !intersection.neighbor() && intersection.boundary() )\n\t\t\t\t\t{\n                        const InfoContainerFace o_info( *this, entity, intersection, discrete_model_, grid_part_ );\n                        ForEachIntegrator<ApplyBoundaryFace,InfoContainerFace>( integrator_tuple, o_info );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n} // end namespace Assembler\n} // end namespace Oseen\n} // end namespace Dune\n\n#endif // DUNE_OSEEN_INTEGRATORS_BASE_HH\n\n/** Copyright (c) 2012, Rene Milk \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 * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies, \n * either expressed or implied, of the FreeBSD Project.\n**/\n\n", "meta": {"hexsha": "540992754c02b8e50fe82c19906bb8efda842769", "size": 20308, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/fem/oseen/assembler/base.hh", "max_stars_repo_name": "renemilk/DUNE-FEM-Oseen", "max_stars_repo_head_hexsha": "2cc2a1a70f81469f13a2330be285960a13f78fdf", "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/fem/oseen/assembler/base.hh", "max_issues_repo_name": "renemilk/DUNE-FEM-Oseen", "max_issues_repo_head_hexsha": "2cc2a1a70f81469f13a2330be285960a13f78fdf", "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/fem/oseen/assembler/base.hh", "max_forks_repo_name": "renemilk/DUNE-FEM-Oseen", "max_forks_repo_head_hexsha": "2cc2a1a70f81469f13a2330be285960a13f78fdf", "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": 44.3406113537, "max_line_length": 181, "alphanum_fraction": 0.6951447705, "num_tokens": 4427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.021615333314127606, "lm_q1q2_score": 0.008561145737305499}}
{"text": "#ifndef REGISTRATION_ROPS_CUSTOM_LRF_HPP\n#define REGISTRATION_ROPS_CUSTOM_LRF_HPP\n\n#include <array>\n#include <numeric> // for accumulate\n#include <Eigen/Eigenvalues> // for EigenSolver\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT>\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::ROPSEstimationWithLocalReferenceFrames () :\n        number_of_bins_ (5),\n        number_of_rotations_ (3),\n        support_radius_ (1.0f),\n        sqr_support_radius_ (1.0f),\n        step_ (22.5f),\n        triangles_ (0),\n        triangles_of_the_point_ (0)\n{\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT>\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::~ROPSEstimationWithLocalReferenceFrames ()\n{\n    triangles_.clear ();\n    triangles_of_the_point_.clear ();\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::setNumberOfPartitionBins (unsigned int number_of_bins)\n{\n    if (number_of_bins != 0)\n        number_of_bins_ = number_of_bins;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> unsigned int\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::getNumberOfPartitionBins () const\n{\n    return (number_of_bins_);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::setNumberOfRotations (unsigned int number_of_rotations)\n{\n    if (number_of_rotations != 0)\n    {\n        number_of_rotations_ = number_of_rotations;\n        step_ = 90.0f / static_cast <float> (number_of_rotations_ + 1);\n    }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> unsigned int\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::getNumberOfRotations () const\n{\n    return (number_of_rotations_);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::setSupportRadius (float support_radius)\n{\n    if (support_radius > 0.0f)\n    {\n        support_radius_ = support_radius;\n        sqr_support_radius_ = support_radius * support_radius;\n    }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> float\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::getSupportRadius () const\n{\n    return (support_radius_);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::setTriangles (const std::vector <pcl::Vertices>& triangles)\n{\n    triangles_ = triangles;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::getTriangles (std::vector <pcl::Vertices>& triangles) const\n{\n    triangles = triangles_;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::computeFeature (PointCloudOut &output)\n{\n    if (this->frames_never_defined_ && this->triangles_.empty()) {\n        PCL_ERROR(\"Either local reference frames or triangle must be provided for RoPS estimation!\");\n    }\n    bool use_custom_frames = true;\n    if (this->frames_never_defined_) {\n        this->buildListOfPointsTriangles();\n        use_custom_frames = false;\n    }\n\n    //feature size = number_of_rotations * number_of_axis_to_rotate_around * number_of_projections * number_of_central_moments\n    unsigned int feature_size = number_of_rotations_ * 3 * 3 * 5;\n    const auto number_of_points = indices_->size ();\n    output.clear ();\n    output.reserve (number_of_points);\n\n    for (const auto& idx: *indices_)\n    {\n        pcl::Indices local_points;\n        Eigen::Matrix3f lrf_matrix;\n        if (use_custom_frames) {\n            const PointRF &frame = this->frames_->points[idx];\n            for (int d = 0; d < 3; ++d) {\n                lrf_matrix.row(0)[d] = frame.x_axis[d];\n                lrf_matrix.row(1)[d] = frame.y_axis[d];\n                lrf_matrix.row(2)[d] = frame.z_axis[d];\n            }\n            std::vector <float> distances;\n            this->tree_->radiusSearch((*this->input_)[idx], this->support_radius_, local_points, distances);\n        } else {\n            std::set<unsigned int> local_triangles;\n            getLocalSurface((*this->input_)[idx], local_triangles, local_points);\n            computeLRF((*this->input_)[idx], local_triangles, lrf_matrix);\n        }\n\n        PointCloudIn transformed_cloud;\n        transformCloud ((*input_)[idx], lrf_matrix, local_points, transformed_cloud);\n\n        std::array<PointInT, 3> axes;\n        axes[0].x = 1.0f; axes[0].y = 0.0f; axes[0].z = 0.0f;\n        axes[1].x = 0.0f; axes[1].y = 1.0f; axes[1].z = 0.0f;\n        axes[2].x = 0.0f; axes[2].y = 0.0f; axes[2].z = 1.0f;\n        std::vector <float> feature;\n        for (const auto &axis : axes)\n        {\n            float theta = step_;\n            do\n            {\n                //rotate local surface and get bounding box\n                PointCloudIn rotated_cloud;\n                Eigen::Vector3f min, max;\n                rotateCloud (axis, theta, transformed_cloud, rotated_cloud, min, max);\n\n                //for each projection (XY, XZ and YZ) compute distribution matrix and central moments\n                for (unsigned int i_proj = 0; i_proj < 3; i_proj++)\n                {\n                    Eigen::MatrixXf distribution_matrix;\n                    distribution_matrix.resize (number_of_bins_, number_of_bins_);\n                    getDistributionMatrix (i_proj, min, max, rotated_cloud, distribution_matrix);\n\n                    // TODO remove this needless copy due to API design\n                    std::vector <float> moments;\n                    computeCentralMoments (distribution_matrix, moments);\n\n                    feature.insert (feature.end (), moments.begin (), moments.end ());\n                }\n\n                theta += step_;\n            } while (theta < 90.0f);\n        }\n\n        const float norm = std::accumulate(\n                feature.cbegin(), feature.cend(), 0.f, [](const auto& sum, const auto& val) {\n                    return sum + std::abs(val);\n                });\n        float invert_norm;\n        if (norm < std::numeric_limits <float>::epsilon ())\n            invert_norm = 1.0f;\n        else\n            invert_norm = 1.0f / norm;\n\n        output.emplace_back ();\n        for (std::size_t i_dim = 0; i_dim < feature_size; i_dim++)\n            output.back().histogram[i_dim] = feature[i_dim] * invert_norm;\n    }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::buildListOfPointsTriangles ()\n{\n    triangles_of_the_point_.clear ();\n\n    std::vector <unsigned int> dummy;\n    dummy.reserve (100);\n    triangles_of_the_point_.resize (surface_->points. size (), dummy);\n\n    for (std::size_t i_triangle = 0; i_triangle < triangles_.size (); i_triangle++)\n        for (const auto& vertex: triangles_[i_triangle].vertices)\n            triangles_of_the_point_[vertex].push_back (i_triangle);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::getLocalSurface (\n        const PointInT& point, std::set <unsigned int>& local_triangles, pcl::Indices& local_points) const\n{\n    std::vector <float> distances;\n    tree_->radiusSearch (point, support_radius_, local_points, distances);\n\n    for (const auto& pt: local_points)\n        local_triangles.insert (triangles_of_the_point_[pt].begin (),\n                                triangles_of_the_point_[pt].end ());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::computeLRF (\n        const PointInT& point, const std::set <unsigned int>& local_triangles, Eigen::Matrix3f& lrf_matrix) const\n{\n    std::size_t number_of_triangles = local_triangles.size ();\n\n    std::vector<Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > scatter_matrices;\n    std::vector <float> triangle_area (number_of_triangles), distance_weight (number_of_triangles);\n\n    scatter_matrices.reserve (number_of_triangles);\n    triangle_area.clear ();\n    distance_weight.clear ();\n\n    float total_area = 0.0f;\n    const float coeff = 1.0f / 12.0f;\n    const float coeff_1_div_3 = 1.0f / 3.0f;\n\n    Eigen::Vector3f feature_point (point.x, point.y, point.z);\n\n    for (const auto& triangle: local_triangles)\n    {\n        Eigen::Vector3f pt[3];\n        for (unsigned int i_vertex = 0; i_vertex < 3; i_vertex++)\n        {\n            const unsigned int index = triangles_[triangle].vertices[i_vertex];\n            pt[i_vertex] (0) = (*surface_)[index].x;\n            pt[i_vertex] (1) = (*surface_)[index].y;\n            pt[i_vertex] (2) = (*surface_)[index].z;\n        }\n\n        const float curr_area = ((pt[1] - pt[0]).cross (pt[2] - pt[0])).norm ();\n        triangle_area.push_back (curr_area);\n        total_area += curr_area;\n\n        distance_weight.push_back (std::pow (support_radius_ - (feature_point - (pt[0] + pt[1] + pt[2]) * coeff_1_div_3).norm (), 2.0f));\n\n        Eigen::Matrix3f curr_scatter_matrix;\n        curr_scatter_matrix.setZero ();\n        for (const auto &i_pt : pt)\n        {\n            Eigen::Vector3f vec = i_pt - feature_point;\n            curr_scatter_matrix += vec * (vec.transpose ());\n            for (const auto &j_pt : pt)\n                curr_scatter_matrix += vec * ((j_pt - feature_point).transpose ());\n        }\n        scatter_matrices.emplace_back (coeff * curr_scatter_matrix);\n    }\n\n    if (std::abs (total_area) < std::numeric_limits <float>::epsilon ())\n        total_area = 1.0f / total_area;\n    else\n        total_area = 1.0f;\n\n    Eigen::Matrix3f overall_scatter_matrix;\n    overall_scatter_matrix.setZero ();\n    std::vector<float> total_weight (number_of_triangles);\n    const float denominator = 1.0f / 6.0f;\n    for (std::size_t i_triangle = 0; i_triangle < number_of_triangles; i_triangle++)\n    {\n        const float factor = distance_weight[i_triangle] * triangle_area[i_triangle] * total_area;\n        overall_scatter_matrix += factor * scatter_matrices[i_triangle];\n        total_weight[i_triangle] = factor * denominator;\n    }\n\n    Eigen::Vector3f v1, v2, v3;\n    computeEigenVectors (overall_scatter_matrix, v1, v2, v3);\n\n    float h1 = 0.0f;\n    float h3 = 0.0f;\n    std::size_t i_triangle = 0;\n    for (const auto& triangle: local_triangles)\n    {\n        Eigen::Vector3f pt[3];\n        for (unsigned int i_vertex = 0; i_vertex < 3; i_vertex++)\n        {\n            const unsigned int index = triangles_[triangle].vertices[i_vertex];\n            pt[i_vertex] (0) = (*surface_)[index].x;\n            pt[i_vertex] (1) = (*surface_)[index].y;\n            pt[i_vertex] (2) = (*surface_)[index].z;\n        }\n\n        float factor1 = 0.0f;\n        float factor3 = 0.0f;\n        for (const auto &i_pt : pt)\n        {\n            Eigen::Vector3f vec = i_pt - feature_point;\n            factor1 += vec.dot (v1);\n            factor3 += vec.dot (v3);\n        }\n        h1 += total_weight[i_triangle] * factor1;\n        h3 += total_weight[i_triangle] * factor3;\n        i_triangle++;\n    }\n\n    if (h1 < 0.0f) v1 = -v1;\n    if (h3 < 0.0f) v3 = -v3;\n\n    v2 = v3.cross (v1);\n\n    lrf_matrix.row (0) = v1;\n    lrf_matrix.row (1) = v2;\n    lrf_matrix.row (2) = v3;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::computeEigenVectors (\n        const Eigen::Matrix3f& matrix,\n        Eigen::Vector3f& major_axis, Eigen::Vector3f& middle_axis, Eigen::Vector3f& minor_axis) const\n{\n    Eigen::EigenSolver <Eigen::Matrix3f> eigen_solver;\n    eigen_solver.compute (matrix);\n\n    Eigen::EigenSolver <Eigen::Matrix3f>::EigenvectorsType eigen_vectors;\n    Eigen::EigenSolver <Eigen::Matrix3f>::EigenvalueType eigen_values;\n    eigen_vectors = eigen_solver.eigenvectors ();\n    eigen_values = eigen_solver.eigenvalues ();\n\n    unsigned int temp = 0;\n    unsigned int major_index = 0;\n    unsigned int middle_index = 1;\n    unsigned int minor_index = 2;\n\n    if (eigen_values.real () (major_index) < eigen_values.real () (middle_index))\n    {\n        temp = major_index;\n        major_index = middle_index;\n        middle_index = temp;\n    }\n\n    if (eigen_values.real () (major_index) < eigen_values.real () (minor_index))\n    {\n        temp = major_index;\n        major_index = minor_index;\n        minor_index = temp;\n    }\n\n    if (eigen_values.real () (middle_index) < eigen_values.real () (minor_index))\n    {\n        temp = minor_index;\n        minor_index = middle_index;\n        middle_index = temp;\n    }\n\n    major_axis = eigen_vectors.col (major_index).real ();\n    middle_axis = eigen_vectors.col (middle_index).real ();\n    minor_axis = eigen_vectors.col (minor_index).real ();\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::transformCloud (\n        const PointInT& point, const Eigen::Matrix3f& matrix,\n        const pcl::Indices& local_points, PointCloudIn& transformed_cloud) const\n{\n    const auto number_of_points = local_points.size ();\n    transformed_cloud.clear ();\n    transformed_cloud.reserve (number_of_points);\n\n    for (const auto& idx: local_points)\n    {\n        Eigen::Vector3f transformed_point ((*surface_)[idx].x - point.x,\n                                           (*surface_)[idx].y - point.y,\n                                           (*surface_)[idx].z - point.z);\n\n        transformed_point = matrix * transformed_point;\n\n        PointInT new_point;\n        new_point.x = transformed_point (0);\n        new_point.y = transformed_point (1);\n        new_point.z = transformed_point (2);\n        transformed_cloud.emplace_back (new_point);\n    }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::rotateCloud (\n        const PointInT& axis, const float angle, const PointCloudIn& cloud, PointCloudIn& rotated_cloud,\n        Eigen::Vector3f& min, Eigen::Vector3f& max) const\n{\n    Eigen::Matrix3f rotation_matrix;\n    const float x = axis.x;\n    const float y = axis.y;\n    const float z = axis.z;\n    const float rad = M_PI / 180.0f;\n    const float cosine = std::cos (angle * rad);\n    const float sine = std::sin (angle * rad);\n    rotation_matrix << cosine + (1 - cosine) * x * x,      (1 - cosine) * x * y - sine * z,    (1 - cosine) * x * z + sine * y,\n            (1 - cosine) * y * x + sine * z,    cosine + (1 - cosine) * y * y,      (1 - cosine) * y * z - sine * x,\n            (1 - cosine) * z * x - sine * y,    (1 - cosine) * z * y + sine * x,    cosine + (1 - cosine) * z * z;\n\n    const auto number_of_points = cloud.size ();\n\n    rotated_cloud.header = cloud.header;\n    rotated_cloud.width = number_of_points;\n    rotated_cloud.height = 1;\n    rotated_cloud.clear ();\n    rotated_cloud.reserve (number_of_points);\n\n    min (0) = std::numeric_limits <float>::max ();\n    min (1) = std::numeric_limits <float>::max ();\n    min (2) = std::numeric_limits <float>::max ();\n    max (0) = -std::numeric_limits <float>::max ();\n    max (1) = -std::numeric_limits <float>::max ();\n    max (2) = -std::numeric_limits <float>::max ();\n\n    for (const auto& pt: cloud.points)\n    {\n        Eigen::Vector3f point (pt.x, pt.y, pt.z);\n        point = rotation_matrix * point;\n\n        PointInT rotated_point;\n        rotated_point.x = point (0);\n        rotated_point.y = point (1);\n        rotated_point.z = point (2);\n        rotated_cloud.emplace_back (rotated_point);\n\n        for (int i = 0; i < 3; ++i)\n        {\n            min(i) = std::min(min(i), point(i));\n            max(i) = std::max(max(i), point(i));\n        }\n    }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::getDistributionMatrix (\n        const unsigned int projection, const Eigen::Vector3f& min, const Eigen::Vector3f& max,\n        const PointCloudIn& cloud, Eigen::MatrixXf& matrix) const\n{\n    matrix.setZero ();\n\n    const unsigned int coord[3][2] = {\n            {0, 1},\n            {0, 2},\n            {1, 2}};\n\n    const float u_bin_length = (max (coord[projection][0]) - min (coord[projection][0])) / number_of_bins_;\n    const float v_bin_length = (max (coord[projection][1]) - min (coord[projection][1])) / number_of_bins_;\n\n    for (const auto& pt: cloud.points)\n    {\n        Eigen::Vector3f point (pt.x, pt.y, pt.z);\n\n        const float u_length = point (coord[projection][0]) - min[coord[projection][0]];\n        const float v_length = point (coord[projection][1]) - min[coord[projection][1]];\n\n        const float u_ratio = u_length / u_bin_length;\n        unsigned int row = static_cast <unsigned int> (u_ratio);\n        if (row == number_of_bins_) row--;\n\n        const float v_ratio = v_length / v_bin_length;\n        unsigned int col = static_cast <unsigned int> (v_ratio);\n        if (col == number_of_bins_) col--;\n\n        matrix (row, col) += 1.0f;\n    }\n\n    matrix /= std::max<float> (1, cloud.size ());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\ntemplate <typename PointInT, typename PointOutT, typename PointRFT> void\nROPSEstimationWithLocalReferenceFrames <PointInT, PointOutT, PointRFT>::computeCentralMoments (\n        const Eigen::MatrixXf& matrix, std::vector <float>& moments) const\n{\n    float mean_i = 0.0f;\n    float mean_j = 0.0f;\n\n    for (unsigned int i = 0; i < number_of_bins_; i++)\n        for (unsigned int j = 0; j < number_of_bins_; j++)\n        {\n            const float m = matrix (i, j);\n            mean_i += static_cast <float> (i + 1) * m;\n            mean_j += static_cast <float> (j + 1) * m;\n        }\n\n    const unsigned int number_of_moments_to_compute = 4;\n    const float power[number_of_moments_to_compute][2] = {\n            {1.0f, 1.0f},\n            {2.0f, 1.0f},\n            {1.0f, 2.0f},\n            {2.0f, 2.0f}};\n\n    float entropy = 0.0f;\n    moments.resize (number_of_moments_to_compute + 1, 0.0f);\n    for (unsigned int i = 0; i < number_of_bins_; i++)\n    {\n        const float i_factor = static_cast <float> (i + 1) - mean_i;\n        for (unsigned int j = 0; j < number_of_bins_; j++)\n        {\n            const float j_factor = static_cast <float> (j + 1) - mean_j;\n            const float m = matrix (i, j);\n            if (m > 0.0f)\n                entropy -= m * std::log (m);\n            for (unsigned int i_moment = 0; i_moment < number_of_moments_to_compute; i_moment++)\n                moments[i_moment] += std::pow (i_factor, power[i_moment][0]) * std::pow (j_factor, power[i_moment][1]) * m;\n        }\n    }\n\n    moments[number_of_moments_to_compute] = entropy;\n}\n\n#endif\n", "meta": {"hexsha": "0afb1800d7e9158c6af3d187039614fddca133aa", "size": 21337, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/impl/rops_custom_lrf.hpp", "max_stars_repo_name": "aleksandrina-streltsova/lidar-global-registration", "max_stars_repo_head_hexsha": "00cc919f17fe5b6854b575ca0aea3712ce034df6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/impl/rops_custom_lrf.hpp", "max_issues_repo_name": "aleksandrina-streltsova/lidar-global-registration", "max_issues_repo_head_hexsha": "00cc919f17fe5b6854b575ca0aea3712ce034df6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/impl/rops_custom_lrf.hpp", "max_forks_repo_name": "aleksandrina-streltsova/lidar-global-registration", "max_forks_repo_head_hexsha": "00cc919f17fe5b6854b575ca0aea3712ce034df6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1117533719, "max_line_length": 137, "alphanum_fraction": 0.5710268548, "num_tokens": 5132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.01854656366449319, "lm_q1q2_score": 0.008550277047915474}}
{"text": "// Copyright (C) 2005-2006 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_DISTRIBUTED_FRUCHTERMAN_REINGOLD_HPP\n#define BOOST_GRAPH_DISTRIBUTED_FRUCHTERMAN_REINGOLD_HPP\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <boost/graph/fruchterman_reingold.hpp>\n\nnamespace boost { namespace graph { namespace distributed {\n\nclass simple_tiling\n{\n public:\n  simple_tiling(int columns, int rows, bool flip = true) \n    : columns(columns), rows(rows), flip(flip)\n  {\n  }\n\n  // Convert from a position (x, y) in the tiled display into a\n  // processor ID number\n  int operator()(int x, int y) const\n  {\n    return flip? (rows - y - 1) * columns + x : y * columns + x;\n  }\n\n  // Convert from a process ID to a position (x, y) in the tiled\n  // display\n  std::pair<int, int> operator()(int id)\n  {\n    int my_col = id % columns;\n    int my_row = flip? rows - (id / columns) - 1 : id / columns;\n    return std::make_pair(my_col, my_row);\n  }\n\n  int columns, rows;\n\n private:\n  bool flip;\n};\n\n// Force pairs function object that does nothing\nstruct no_force_pairs\n{\n  template<typename Graph, typename ApplyForce>\n  void operator()(const Graph&, const ApplyForce&)\n  {\n  }\n};\n\n// Computes force pairs in the distributed case.\ntemplate<typename PositionMap, typename DisplacementMap, typename LocalForces,\n         typename NonLocalForces = no_force_pairs>\nclass distributed_force_pairs_proxy\n{\n public:\n  distributed_force_pairs_proxy(const PositionMap& position, \n                                const DisplacementMap& displacement,\n                                const LocalForces& local_forces,\n                                const NonLocalForces& nonlocal_forces = NonLocalForces())\n    : position(position), displacement(displacement), \n      local_forces(local_forces), nonlocal_forces(nonlocal_forces)\n  {\n  }\n\n  template<typename Graph, typename ApplyForce>\n  void operator()(const Graph& g, ApplyForce apply_force)\n  {\n    // Flush remote displacements\n    displacement.flush();\n\n    // Receive updated positions for all of our neighbors\n    synchronize(position);\n\n    // Reset remote displacements \n    displacement.reset();\n\n    // Compute local repulsive forces\n    local_forces(g, apply_force);\n\n    // Compute neighbor repulsive forces\n    nonlocal_forces(g, apply_force);\n  }\n\n protected:\n  PositionMap position;\n  DisplacementMap displacement;\n  LocalForces local_forces;\n  NonLocalForces nonlocal_forces;\n};\n\ntemplate<typename PositionMap, typename DisplacementMap, typename LocalForces>\ninline \ndistributed_force_pairs_proxy<PositionMap, DisplacementMap, LocalForces>\nmake_distributed_force_pairs(const PositionMap& position, \n                             const DisplacementMap& displacement,\n                             const LocalForces& local_forces)\n{\n  typedef \n    distributed_force_pairs_proxy<PositionMap, DisplacementMap, LocalForces>\n    result_type;\n  return result_type(position, displacement, local_forces);\n}\n\ntemplate<typename PositionMap, typename DisplacementMap, typename LocalForces,\n         typename NonLocalForces>\ninline \ndistributed_force_pairs_proxy<PositionMap, DisplacementMap, LocalForces,\n                              NonLocalForces>\nmake_distributed_force_pairs(const PositionMap& position, \n                             const DisplacementMap& displacement,\n                             const LocalForces& local_forces,\n                             const NonLocalForces& nonlocal_forces)\n{\n  typedef \n    distributed_force_pairs_proxy<PositionMap, DisplacementMap, LocalForces,\n                                  NonLocalForces>\n      result_type;\n  return result_type(position, displacement, local_forces, nonlocal_forces);\n}\n\n// Compute nonlocal force pairs based on the shared borders with\n// adjacent tiles.\ntemplate<typename PositionMap>\nclass neighboring_tiles_force_pairs\n{\n public:\n  typedef typename property_traits<PositionMap>::value_type Point;\n  typedef typename point_traits<Point>::component_type Dim;\n\n  enum bucket_position { left, top, right, bottom, end_position };\n  \n  neighboring_tiles_force_pairs(PositionMap position, Point origin,\n                                Point extent, simple_tiling tiling)\n    : position(position), origin(origin), extent(extent), tiling(tiling)\n  {\n  }\n\n  template<typename Graph, typename ApplyForce>\n  void operator()(const Graph& g, ApplyForce apply_force)\n  {\n    // TBD: Do this some smarter way\n    if (tiling.columns == 1 && tiling.rows == 1)\n      return;\n\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n\n    // TBD: num_vertices(g) should be the global number of vertices?\n    Dim two_k = Dim(2) * sqrt(extent[0] * extent[1] / num_vertices(g));\n\n    std::vector<vertex_descriptor> my_vertices[4];\n    std::vector<vertex_descriptor> neighbor_vertices[4];\n   \n    // Compute cutoff positions\n    Dim cutoffs[4];\n    cutoffs[left] = origin[0] + two_k;\n    cutoffs[top] = origin[1] + two_k;\n    cutoffs[right] = origin[0] + extent[0] - two_k;\n    cutoffs[bottom] = origin[1] + extent[1] - two_k;\n\n    // Compute neighbors\n    typename PositionMap::process_group_type pg = position.process_group();\n    std::pair<int, int> my_tile = tiling(process_id(pg));\n    int neighbors[4] = { -1, -1, -1, -1 } ;\n    if (my_tile.first > 0)\n      neighbors[left] = tiling(my_tile.first - 1, my_tile.second);\n    if (my_tile.second > 0)\n      neighbors[top] = tiling(my_tile.first, my_tile.second - 1);\n    if (my_tile.first < tiling.columns - 1)\n      neighbors[right] = tiling(my_tile.first + 1, my_tile.second);\n    if (my_tile.second < tiling.rows - 1)\n      neighbors[bottom] = tiling(my_tile.first, my_tile.second + 1);\n\n    // Sort vertices along the edges into buckets\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      if (position[v][0] <= cutoffs[left]) my_vertices[left].push_back(v); \n      if (position[v][1] <= cutoffs[top]) my_vertices[top].push_back(v); \n      if (position[v][0] >= cutoffs[right]) my_vertices[right].push_back(v); \n      if (position[v][1] >= cutoffs[bottom]) my_vertices[bottom].push_back(v); \n    }\n\n    // Send vertices to neighbors, and gather our neighbors' vertices\n    bucket_position pos;\n    for (pos = left; pos < end_position; pos = bucket_position(pos + 1)) {\n      if (neighbors[pos] != -1) {\n        send(pg, neighbors[pos], 0, my_vertices[pos].size());\n        if (!my_vertices[pos].empty())\n          send(pg, neighbors[pos], 1, \n               &my_vertices[pos].front(), my_vertices[pos].size());\n      }\n    }\n\n    // Pass messages around\n    synchronize(pg);\n    \n    // Receive neighboring vertices\n    for (pos = left; pos < end_position; pos = bucket_position(pos + 1)) {\n      if (neighbors[pos] != -1) {\n        std::size_t incoming_vertices;\n        receive(pg, neighbors[pos], 0, incoming_vertices);\n\n        if (incoming_vertices) {\n          neighbor_vertices[pos].resize(incoming_vertices);\n          receive(pg, neighbors[pos], 1, &neighbor_vertices[pos].front(),\n                  incoming_vertices);\n        }\n      }\n    }\n\n    // For each neighboring vertex, we need to get its current position\n    for (pos = left; pos < end_position; pos = bucket_position(pos + 1))\n      for (typename std::vector<vertex_descriptor>::iterator i = \n             neighbor_vertices[pos].begin(); \n           i != neighbor_vertices[pos].end();\n           ++i)\n        request(position, *i);\n    synchronize(position);\n\n    // Apply forces in adjacent bins. This is O(n^2) in the worst\n    // case. Oh well.\n    for (pos = left; pos < end_position; pos = bucket_position(pos + 1)) {\n      for (typename std::vector<vertex_descriptor>::iterator i = \n             my_vertices[pos].begin(); \n           i != my_vertices[pos].end();\n           ++i)\n        for (typename std::vector<vertex_descriptor>::iterator j = \n               neighbor_vertices[pos].begin(); \n             j != neighbor_vertices[pos].end();\n             ++j)\n          apply_force(*i, *j);\n    }\n  }\n\n protected:\n  PositionMap position;\n  Point origin;\n  Point extent;\n  simple_tiling tiling;\n};\n\ntemplate<typename PositionMap>\ninline neighboring_tiles_force_pairs<PositionMap>\nmake_neighboring_tiles_force_pairs\n (PositionMap position, \n  typename property_traits<PositionMap>::value_type origin,\n  typename property_traits<PositionMap>::value_type extent,\n  simple_tiling tiling)\n{\n  return neighboring_tiles_force_pairs<PositionMap>(position, origin, extent,\n                                                    tiling);\n}\n\ntemplate<typename DisplacementMap, typename Cooling>\nclass distributed_cooling_proxy\n{\n public:\n  typedef typename Cooling::result_type result_type;\n\n  distributed_cooling_proxy(const DisplacementMap& displacement,\n                            const Cooling& cooling)\n    : displacement(displacement), cooling(cooling)\n  {\n  }\n\n  result_type operator()()\n  {\n    // Accumulate displacements computed on each processor\n    synchronize(displacement.data->process_group);\n\n    // Allow the underlying cooling to occur\n    return cooling();\n  }\n\n protected:\n  DisplacementMap displacement;\n  Cooling cooling;\n};\n\ntemplate<typename DisplacementMap, typename Cooling>\ninline distributed_cooling_proxy<DisplacementMap, Cooling>\nmake_distributed_cooling(const DisplacementMap& displacement,\n                         const Cooling& cooling)\n{\n  typedef distributed_cooling_proxy<DisplacementMap, Cooling> result_type;\n  return result_type(displacement, cooling);\n}\n\ntemplate<typename Point>\nstruct point_accumulating_reducer {\n  BOOST_STATIC_CONSTANT(bool, non_default_resolver = true);\n\n  template<typename K>\n  Point operator()(const K&) const { return Point(); }\n\n  template<typename K>\n  Point operator()(const K&, const Point& p1, const Point& p2) const \n  { return Point(p1[0] + p2[0], p1[1] + p2[1]); }\n};\n\ntemplate<typename Graph, typename PositionMap, \n         typename AttractiveForce, typename RepulsiveForce,\n         typename ForcePairs, typename Cooling, typename DisplacementMap>\nvoid\nfruchterman_reingold_force_directed_layout\n (const Graph&    g,\n  PositionMap     position,\n  typename property_traits<PositionMap>::value_type const& origin,\n  typename property_traits<PositionMap>::value_type const& extent,\n  AttractiveForce attractive_force,\n  RepulsiveForce  repulsive_force,\n  ForcePairs      force_pairs,\n  Cooling         cool,\n  DisplacementMap displacement)\n{\n  typedef typename property_traits<PositionMap>::value_type Point;\n\n  // Reduction in the displacement map involves summing the forces\n  displacement.set_reduce(point_accumulating_reducer<Point>());\n\n  // We need to track the positions of all of our neighbors\n  BGL_FORALL_VERTICES_T(u, g, Graph)\n    BGL_FORALL_ADJ_T(u, v, g, Graph)\n      request(position, v);\n\n  // Invoke the \"sequential\" Fruchterman-Reingold implementation\n  boost::fruchterman_reingold_force_directed_layout\n    (g, position, origin, extent,\n     attractive_force, repulsive_force,\n     make_distributed_force_pairs(position, displacement, force_pairs),\n     make_distributed_cooling(displacement, cool),\n     displacement);\n}\n\ntemplate<typename Graph, typename PositionMap, \n         typename AttractiveForce, typename RepulsiveForce,\n         typename ForcePairs, typename Cooling, typename DisplacementMap>\nvoid\nfruchterman_reingold_force_directed_layout\n (const Graph&    g,\n  PositionMap     position,\n  typename property_traits<PositionMap>::value_type const& origin,\n  typename property_traits<PositionMap>::value_type const& extent,\n  AttractiveForce attractive_force,\n  RepulsiveForce  repulsive_force,\n  ForcePairs      force_pairs,\n  Cooling         cool,\n  DisplacementMap displacement,\n  simple_tiling   tiling)\n{\n  typedef typename property_traits<PositionMap>::value_type Point;\n\n  // Reduction in the displacement map involves summing the forces\n  displacement.set_reduce(point_accumulating_reducer<Point>());\n\n  // We need to track the positions of all of our neighbors\n  BGL_FORALL_VERTICES_T(u, g, Graph)\n    BGL_FORALL_ADJ_T(u, v, g, Graph)\n      request(position, v);\n\n  // Invoke the \"sequential\" Fruchterman-Reingold implementation\n  boost::fruchterman_reingold_force_directed_layout\n    (g, position, origin, extent,\n     attractive_force, repulsive_force,\n     make_distributed_force_pairs\n      (position, displacement, force_pairs,\n       make_neighboring_tiles_force_pairs(position, origin, extent, tiling)),\n     make_distributed_cooling(displacement, cool),\n     displacement);\n}\n\n} } } // end namespace boost::graph::distributed\n\n#endif // BOOST_GRAPH_DISTRIBUTED_FRUCHTERMAN_REINGOLD_HPP\n", "meta": {"hexsha": "a89aea3dd15ca3328f3102a7dc1172d113db5d3b", "size": 12963, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/graph/distributed/fruchterman_reingold.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/distributed/fruchterman_reingold.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/distributed/fruchterman_reingold.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": 33.6701298701, "max_line_length": 101, "alphanum_fraction": 0.6981408625, "num_tokens": 3000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.026355354566807064, "lm_q1q2_score": 0.008545338903253156}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2013, 2014, 2015.\n// Modifications copyright (c) 2013-2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_LA_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_LA_HPP\n\n#include <boost/geometry/core/assert.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n\n#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>\n#include <boost/geometry/algorithms/detail/overlay/get_turn_info_for_endpoint.hpp>\n\n// TEMP, for spikes detector\n//#include <boost/geometry/algorithms/detail/overlay/get_turn_info_ll.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry {\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace overlay {\n\ntemplate<typename AssignPolicy>\nstruct get_turn_info_linear_areal\n{\n    // Currently only Linear spikes are handled\n    // Areal spikes are ignored\n    static const bool handle_spikes = true;\n\n    template\n    <\n        typename Point1,\n        typename Point2,\n        typename TurnInfo,\n        typename RobustPolicy,\n        typename OutputIterator\n    >\n    static inline OutputIterator apply(\n                Point1 const& pi, Point1 const& pj, Point1 const& pk,\n                Point2 const& qi, Point2 const& qj, Point2 const& qk,\n                bool is_p_first, bool is_p_last,\n                bool is_q_first, bool is_q_last,\n                TurnInfo const& tp_model,\n                RobustPolicy const& robust_policy,\n                OutputIterator out)\n    {\n        typedef intersection_info<Point1, Point2, typename TurnInfo::point_type, RobustPolicy>\n            inters_info;\n\n        inters_info inters(pi, pj, pk, qi, qj, qk, robust_policy);\n\n        char const method = inters.d_info().how;\n\n        // Copy, to copy possibly extended fields\n        TurnInfo tp = tp_model;\n\n        // Select method and apply\n        switch(method)\n        {\n            case 'a' : // collinear, \"at\"\n            case 'f' : // collinear, \"from\"\n            case 's' : // starts from the middle\n                get_turn_info_for_endpoint<true, true>(\n                    pi, pj, pk, qi, qj, qk,\n                    is_p_first, is_p_last, is_q_first, is_q_last,\n                    tp_model, inters, method_none, out);\n                break;\n\n            case 'd' : // disjoint: never do anything\n                break;\n\n            case 'm' :\n            {\n                if ( get_turn_info_for_endpoint<false, true>(\n                        pi, pj, pk, qi, qj, qk,\n                        is_p_first, is_p_last, is_q_first, is_q_last,\n                        tp_model, inters, method_touch_interior, out) )\n                {\n                    // do nothing\n                }\n                else\n                {\n                    typedef touch_interior\n                        <\n                            TurnInfo\n                        > policy;\n\n                    // If Q (1) arrives (1)\n                    if ( inters.d_info().arrival[1] == 1 )\n                    {\n                        policy::template apply<0>(pi, pj, pk, qi, qj, qk,\n                                    tp, inters.i_info(), inters.d_info(),\n                                    inters.sides());\n                    }\n                    else\n                    {\n                        // Swap p/q\n                        side_calculator\n                            <\n                                typename inters_info::robust_point2_type,\n                                typename inters_info::robust_point1_type\n                            > swapped_side_calc(inters.rqi(), inters.rqj(), inters.rqk(),\n                                                inters.rpi(), inters.rpj(), inters.rpk());\n                        policy::template apply<1>(qi, qj, qk, pi, pj, pk,\n                                    tp, inters.i_info(), inters.d_info(),\n                                    swapped_side_calc);\n                    }\n\n                    if ( tp.operations[1].operation == operation_blocked )\n                    {\n                        tp.operations[0].is_collinear = true;\n                    }\n\n                    replace_method_and_operations_tm(tp.method,\n                                                     tp.operations[0].operation,\n                                                     tp.operations[1].operation);\n                    \n                    // this function assumes that 'u' must be set for a spike\n                    calculate_spike_operation(tp.operations[0].operation,\n                                              inters, is_p_last);\n                    \n                    AssignPolicy::apply(tp, pi, qi, inters);\n\n                    *out++ = tp;\n                }\n            }\n            break;\n            case 'i' :\n            {\n                crosses<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                                         tp, inters.i_info(), inters.d_info());\n\n                replace_operations_i(tp.operations[0].operation, tp.operations[1].operation);\n\n                AssignPolicy::apply(tp, pi, qi, inters);\n                *out++ = tp;\n            }\n            break;\n            case 't' :\n            {\n                // Both touch (both arrive there)\n                if ( get_turn_info_for_endpoint<false, true>(\n                        pi, pj, pk, qi, qj, qk,\n                        is_p_first, is_p_last, is_q_first, is_q_last,\n                        tp_model, inters, method_touch, out) )\n                {\n                    // do nothing\n                }\n                else \n                {\n                    touch<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                            tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                    if ( tp.operations[1].operation == operation_blocked )\n                    {\n                        tp.operations[0].is_collinear = true;\n                    }\n\n                    // workarounds for touch<> not taking spikes into account starts here\n                    // those was discovered empirically\n                    // touch<> is not symmetrical!\n                    // P spikes and Q spikes may produce various operations!\n                    // Only P spikes are valid for L/A\n                    // TODO: this is not optimal solution - think about rewriting touch<>\n\n                    if ( tp.operations[0].operation == operation_blocked )\n                    {\n                        // a spike on P on the same line with Q1\n                        if ( inters.is_spike_p() )\n                        {\n                            if ( inters.sides().qk_wrt_p1() == 0 )\n                            {\n                                tp.operations[0].is_collinear = true;\n                            }\n                            else\n                            {\n                                tp.operations[0].operation = operation_union;                                \n                            }\n                        }\n                    }\n                    else if ( tp.operations[0].operation == operation_continue\n                           && tp.operations[1].operation == operation_continue )\n                    {\n                        // P spike on the same line with Q2 (opposite)\n                        if ( inters.sides().pk_wrt_q1() == -inters.sides().qk_wrt_q1()\n                          && inters.is_spike_p() )\n                        {\n                            tp.operations[0].operation = operation_union;\n                            tp.operations[1].operation = operation_union;\n                        }\n                    }\n                    else if ( tp.operations[0].operation == operation_none\n                           && tp.operations[1].operation == operation_none )\n                    {\n                        // spike not handled by touch<>\n                        if ( inters.is_spike_p() )\n                        {\n                            tp.operations[0].operation = operation_intersection;\n                            tp.operations[1].operation = operation_union;\n\n                            if ( inters.sides().pk_wrt_q2() == 0 )\n                            {\n                                tp.operations[0].operation = operation_continue; // will be converted to i\n                                tp.operations[0].is_collinear = true;\n                            }\n                        }\n                    }\n\n                    // workarounds for touch<> not taking spikes into account ends here\n\n                    replace_method_and_operations_tm(tp.method,\n                                                     tp.operations[0].operation,\n                                                     tp.operations[1].operation);\n\n                    bool ignore_spike\n                        = calculate_spike_operation(tp.operations[0].operation,\n                                                    inters, is_p_last);\n\n// TODO: move this into the append_xxx and call for each turn?\n                    AssignPolicy::apply(tp, pi, qi, inters);\n\n                    if ( ! BOOST_GEOMETRY_CONDITION(handle_spikes)\n                      || ignore_spike\n                      || ! append_opposite_spikes<append_touches>( // for 'i' or 'c' i???\n                                tp, inters, is_p_last, is_q_last, out) )\n                    {\n                        *out++ = tp;\n                    }\n                }\n            }\n            break;\n            case 'e':\n            {\n                if ( get_turn_info_for_endpoint<true, true>(\n                        pi, pj, pk, qi, qj, qk,\n                        is_p_first, is_p_last, is_q_first, is_q_last,\n                        tp_model, inters, method_equal, out) )\n                {\n                    // do nothing\n                }\n                else\n                {\n                    tp.operations[0].is_collinear = true;\n\n                    if ( ! inters.d_info().opposite )\n                    {\n                        // Both equal\n                        // or collinear-and-ending at intersection point\n                        equal<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                            tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                        turn_transformer_ec<false> transformer(method_touch);\n                        transformer(tp);\n                    \n// TODO: move this into the append_xxx and call for each turn?\n                        AssignPolicy::apply(tp, pi, qi, inters);\n                        \n                        // conditionally handle spikes\n                        if ( ! BOOST_GEOMETRY_CONDITION(handle_spikes)\n                          || ! append_collinear_spikes(tp, inters, is_p_last, is_q_last,\n                                                       method_touch, append_equal, out) )\n                        {\n                            *out++ = tp; // no spikes\n                        }\n                    }\n                    else\n                    {\n                        equal_opposite\n                            <\n                                TurnInfo,\n                                AssignPolicy\n                            >::apply(pi, qi,\n                                     tp, out, inters);\n                    }\n                }\n            }\n            break;\n            case 'c' :\n            {\n                // Collinear\n                if ( get_turn_info_for_endpoint<true, true>(\n                        pi, pj, pk, qi, qj, qk,\n                        is_p_first, is_p_last, is_q_first, is_q_last,\n                        tp_model, inters, method_collinear, out) )\n                {\n                    // do nothing\n                }\n                else\n                {\n                    tp.operations[0].is_collinear = true;\n\n                    if ( ! inters.d_info().opposite )\n                    {\n                        method_type method_replace = method_touch_interior;\n                        append_version_c version = append_collinear;\n\n                        if ( inters.d_info().arrival[0] == 0 )\n                        {\n                            // Collinear, but similar thus handled as equal\n                            equal<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                                    tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                            method_replace = method_touch;\n                            version = append_equal;\n                        }\n                        else\n                        {\n                            collinear<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                                    tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                            //method_replace = method_touch_interior;\n                            //version = append_collinear;\n                        }\n\n                        turn_transformer_ec<false> transformer(method_replace);\n                        transformer(tp);\n\n// TODO: move this into the append_xxx and call for each turn?\n                        AssignPolicy::apply(tp, pi, qi, inters);\n                        \n                        // conditionally handle spikes\n                        if ( ! BOOST_GEOMETRY_CONDITION(handle_spikes)\n                          || ! append_collinear_spikes(tp, inters, is_p_last, is_q_last,\n                                                       method_replace, version, out) )\n                        {\n                            // no spikes\n                            *out++ = tp;\n                        }\n                    }\n                    else\n                    {\n                        // Is this always 'm' ?\n                        turn_transformer_ec<false> transformer(method_touch_interior);\n\n                        // conditionally handle spikes\n                        if ( BOOST_GEOMETRY_CONDITION(handle_spikes) )\n                        {\n                            append_opposite_spikes<append_collinear_opposite>(\n                                    tp, inters, is_p_last, is_q_last, out);\n                        }\n\n                        // TODO: ignore for spikes?\n                        //       E.g. pass is_p_valid = !is_p_last && !is_pj_spike,\n                        //       the same with is_q_valid\n\n                        collinear_opposite\n                            <\n                                TurnInfo,\n                                AssignPolicy\n                            >::apply(pi, pj, pk, qi, qj, qk,\n                                tp, out, inters,\n                                inters.sides(), transformer,\n                                !is_p_last, true); // qk is always valid\n                    }\n                }\n            }\n            break;\n            case '0' :\n            {\n                // degenerate points\n                if ( BOOST_GEOMETRY_CONDITION(AssignPolicy::include_degenerate) )\n                {\n                    only_convert::apply(tp, inters.i_info());\n\n                    if ( is_p_first\n                      && equals::equals_point_point(pi, tp.point) )\n                    {\n                        tp.operations[0].position = position_front;\n                    }\n                    else if ( is_p_last\n                           && equals::equals_point_point(pj, tp.point) )\n                    {\n                        tp.operations[0].position = position_back;\n                    }\n                    // tp.operations[1].position = position_middle;\n\n                    AssignPolicy::apply(tp, pi, qi, inters);\n                    *out++ = tp;\n                }\n            }\n            break;\n            default :\n            {\n#if defined(BOOST_GEOMETRY_DEBUG_ROBUSTNESS)\n                std::cout << \"TURN: Unknown method: \" << method << std::endl;\n#endif\n#if ! defined(BOOST_GEOMETRY_OVERLAY_NO_THROW)\n                throw turn_info_exception(method);\n#endif\n            }\n            break;\n        }\n\n        return out;\n    }\n\n    template <typename Operation,\n              typename IntersectionInfo>\n    static inline bool calculate_spike_operation(Operation & op,\n                                                 IntersectionInfo const& inters,\n                                                 bool is_p_last)\n    {\n        bool is_p_spike = ( op == operation_union || op == operation_intersection )\n                       && ! is_p_last\n                       && inters.is_spike_p();\n\n        if ( is_p_spike )\n        {\n            int const pk_q1 = inters.sides().pk_wrt_q1();\n            \n            bool going_in = pk_q1 < 0; // Pk on the right\n            bool going_out = pk_q1 > 0; // Pk on the left\n\n            int const qk_q1 = inters.sides().qk_wrt_q1();\n\n            // special cases\n            if ( qk_q1 < 0 ) // Q turning R\n            { \n                // spike on the edge point\n                // if it's already known that the spike is going out this musn't be checked\n                if ( ! going_out\n                  && equals::equals_point_point(inters.rpj(), inters.rqj()) )\n                {\n                    int const pk_q2 = inters.sides().pk_wrt_q2();\n                    going_in = pk_q1 < 0 && pk_q2 < 0; // Pk on the right of both\n                    going_out = pk_q1 > 0 || pk_q2 > 0; // Pk on the left of one of them\n                }\n            }\n            else if ( qk_q1 > 0 ) // Q turning L\n            {\n                // spike on the edge point\n                // if it's already known that the spike is going in this musn't be checked\n                if ( ! going_in\n                  && equals::equals_point_point(inters.rpj(), inters.rqj()) )\n                {\n                    int const pk_q2 = inters.sides().pk_wrt_q2();\n                    going_in = pk_q1 < 0 || pk_q2 < 0; // Pk on the right of one of them\n                    going_out = pk_q1 > 0 && pk_q2 > 0; // Pk on the left of both\n                }\n            }\n\n            if ( going_in )\n            {\n                op = operation_intersection;\n                return true;\n            }\n            else if ( going_out )\n            {\n                op = operation_union;\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n    enum append_version_c { append_equal, append_collinear };\n\n    template <typename TurnInfo,\n              typename IntersectionInfo,\n              typename OutIt>\n    static inline bool append_collinear_spikes(TurnInfo & tp,\n                                               IntersectionInfo const& inters,\n                                               bool is_p_last, bool /*is_q_last*/,\n                                               method_type method, append_version_c version,\n                                               OutIt out)\n    {\n        // method == touch || touch_interior\n        // both position == middle\n\n        bool is_p_spike = ( version == append_equal ?\n                            ( tp.operations[0].operation == operation_union\n                           || tp.operations[0].operation == operation_intersection ) :\n                            tp.operations[0].operation == operation_continue )\n                       && ! is_p_last\n                       && inters.is_spike_p();\n\n        // TODO: throw an exception for spike in Areal?\n        /*bool is_q_spike = tp.operations[1].operation == operation_continue\n                       && inters.is_spike_q();\n\n        // both are collinear spikes on the same IP, we can just follow both\n        if ( is_p_spike && is_q_spike )\n        {\n            return false;\n        }\n        // spike on Linear - it's turning back on the boundary of Areal\n        else*/\n        if ( is_p_spike )\n        {\n            tp.method = method;\n            tp.operations[0].operation = operation_blocked;\n            tp.operations[1].operation = operation_union;\n            *out++ = tp;\n            tp.operations[0].operation = operation_continue; // boundary\n            //tp.operations[1].operation = operation_union;\n            *out++ = tp;\n\n            return true;\n        }\n        // spike on Areal - Linear is going outside\n        /*else if ( is_q_spike )\n        {\n            tp.method = method;\n            tp.operations[0].operation = operation_union;\n            tp.operations[1].operation = operation_continue;\n            *out++ = tp;\n            *out++ = tp;\n\n            return true;\n        }*/\n\n        return false;\n    }\n\n    enum append_version_o { append_touches, append_collinear_opposite };\n\n    template <append_version_o Version,\n              typename TurnInfo,\n              typename IntersectionInfo,\n              typename OutIt>\n    static inline bool append_opposite_spikes(TurnInfo & tp,\n                                              IntersectionInfo const& inters,\n                                              bool is_p_last, bool /*is_q_last*/,\n                                              OutIt out)\n    {\n        static const bool is_version_touches = (Version == append_touches);\n\n        bool is_p_spike = ( is_version_touches ?\n                            ( tp.operations[0].operation == operation_continue\n                           || tp.operations[0].operation == operation_intersection ) : // i ???\n                            true )\n                       && ! is_p_last\n                       && inters.is_spike_p();\n        \n        // TODO: throw an exception for spike in Areal?\n        /*bool is_q_spike = ( ( Version == append_touches\n                           && tp.operations[1].operation == operation_continue )\n                         || ( Version == append_collinear_opposite\n                           && tp.operations[1].operation == operation_none ) )\n                       && inters.is_spike_q();\n\n        if ( is_p_spike && is_q_spike )\n        {\n            // u/u or nothing?\n            return false;\n        }\n        else*/\n        if ( is_p_spike )\n        {\n            if ( BOOST_GEOMETRY_CONDITION(is_version_touches)\n              || inters.d_info().arrival[0] == 1 )\n            {\n                if ( BOOST_GEOMETRY_CONDITION(is_version_touches) )\n                {\n                    tp.operations[0].is_collinear = true;\n                    //tp.operations[1].is_collinear = false;\n                    tp.method = method_touch;\n                }\n                else\n                {\n                    tp.operations[0].is_collinear = true;\n                    //tp.operations[1].is_collinear = false;\n\n                    BOOST_GEOMETRY_ASSERT(inters.i_info().count > 1);\n                    base_turn_handler::assign_point(tp, method_touch_interior, inters.i_info(), 1);\n\n                    AssignPolicy::apply(tp, inters.pi(), inters.qi(), inters);\n                }\n\n                tp.operations[0].operation = operation_blocked;\n                tp.operations[1].operation = operation_continue; // boundary\n                *out++ = tp;\n                tp.operations[0].operation = operation_continue; // boundary\n                //tp.operations[1].operation = operation_continue; // boundary\n                *out++ = tp;\n\n                return true;\n            }\n        }\n        /*else if ( is_q_spike )\n        {\n            tp.operations[0].is_collinear = true;\n            tp.method = is_version_touches ? method_touch : method_touch_interior;\n            tp.operations[0].operation = operation_continue;\n            tp.operations[1].operation = operation_continue; // boundary\n            *out++ = tp;\n            *out++ = tp;\n\n            return true;\n        }*/\n\n        return false;\n    }\n\n    static inline void replace_method_and_operations_tm(method_type & method,\n                                                        operation_type & op0,\n                                                        operation_type & op1)\n    {\n        if ( op0 == operation_blocked && op1 == operation_blocked )\n        {\n            // NOTE: probably only if methods are WRT IPs, not segments!\n            method = (method == method_touch ? method_equal : method_collinear);\n        }\n\n        // Assuming G1 is always Linear\n        if ( op0 == operation_blocked )\n        {\n            op0 = operation_continue;\n        }\n\n        if ( op1 == operation_blocked )\n        {\n            op1 = operation_continue;\n        }\n        else if ( op1 == operation_intersection )\n        {\n            op1 = operation_union;\n        }\n\n        // spikes in 'm'\n        if ( method == method_error )\n        {\n            method = method_touch_interior;\n            op0 = operation_union;\n            op1 = operation_union;\n        }\n    }\n\n    template <bool IsFront>\n    class turn_transformer_ec\n    {\n    public:\n        explicit turn_transformer_ec(method_type method_t_or_m)\n            : m_method(method_t_or_m)\n        {}\n\n        template <typename Turn>\n        void operator()(Turn & turn) const\n        {\n            operation_type & op0 = turn.operations[0].operation;\n            operation_type & op1 = turn.operations[1].operation;\n\n            // NOTE: probably only if methods are WRT IPs, not segments!\n            if ( BOOST_GEOMETRY_CONDITION(IsFront)\n              || op0 == operation_intersection || op0 == operation_union\n              || op1 == operation_intersection || op1 == operation_union )\n            {\n                turn.method = m_method;\n            }\n\n            turn.operations[0].is_collinear = op0 != operation_blocked;\n\n            // Assuming G1 is always Linear\n            if ( op0 == operation_blocked )\n            {\n                op0 = operation_continue;\n            }\n\n            if ( op1 == operation_blocked )\n            {\n                op1 = operation_continue;\n            }\n            else if ( op1 == operation_intersection )\n            {\n                op1 = operation_union;\n            }\n        }\n\n    private:\n        method_type m_method;\n    };\n\n    static inline void replace_operations_i(operation_type & /*op0*/, operation_type & op1)\n    {\n        // assuming Linear is always the first one\n        op1 = operation_union;\n    }\n\n    // NOTE: Spikes may NOT be handled for Linear endpoints because it's not\n    //       possible to define a spike on an endpoint. Areal geometries must\n    //       NOT have spikes at all. One thing that could be done is to throw\n    //       an exception when spike is detected in Areal geometry.\n    \n    template <bool EnableFirst,\n              bool EnableLast,\n              typename Point1,\n              typename Point2,\n              typename TurnInfo,\n              typename IntersectionInfo,\n              typename OutputIterator>\n    static inline bool get_turn_info_for_endpoint(\n                            Point1 const& pi, Point1 const& /*pj*/, Point1 const& /*pk*/,\n                            Point2 const& qi, Point2 const& /*qj*/, Point2 const& /*qk*/,\n                            bool is_p_first, bool is_p_last,\n                            bool /*is_q_first*/, bool is_q_last,\n                            TurnInfo const& tp_model,\n                            IntersectionInfo const& inters,\n                            method_type /*method*/,\n                            OutputIterator out)\n    {\n        namespace ov = overlay;\n        typedef ov::get_turn_info_for_endpoint<AssignPolicy, EnableFirst, EnableLast> get_info_e;\n\n        const std::size_t ip_count = inters.i_info().count;\n        // no intersection points\n        if ( ip_count == 0 )\n            return false;\n\n        if ( !is_p_first && !is_p_last )\n            return false;\n\n// TODO: is_q_last could probably be replaced by false and removed from parameters\n\n        linear_intersections intersections(pi, qi, inters.result(), is_p_last, is_q_last);\n        linear_intersections::ip_info const& ip0 = intersections.template get<0>();\n        linear_intersections::ip_info const& ip1 = intersections.template get<1>();\n\n        const bool opposite = inters.d_info().opposite;\n\n        // ANALYSE AND ASSIGN FIRST\n\n        // IP on the first point of Linear Geometry\n        bool was_first_point_handled = false;\n        if ( BOOST_GEOMETRY_CONDITION(EnableFirst)\n          && is_p_first && ip0.is_pi && !ip0.is_qi ) // !q0i prevents duplication\n        {\n            TurnInfo tp = tp_model;\n            tp.operations[0].position = position_front;\n            tp.operations[1].position = position_middle;\n\n            if ( opposite ) // opposite -> collinear\n            {\n                tp.operations[0].operation = operation_continue;\n                tp.operations[1].operation = operation_union;\n                tp.method = ip0.is_qj ? method_touch : method_touch_interior;\n            }\n            else\n            {\n                method_type replaced_method = method_touch_interior;\n\n                if ( ip0.is_qj )\n                {\n                    side_calculator\n                        <\n                            typename IntersectionInfo::robust_point1_type,\n                            typename IntersectionInfo::robust_point2_type,\n                            typename IntersectionInfo::robust_point2_type\n                        > side_calc(inters.rqi(), inters.rpi(), inters.rpj(),\n                                    inters.rqi(), inters.rqj(), inters.rqk());\n\n                    std::pair<operation_type, operation_type>\n                        operations = get_info_e::operations_of_equal(side_calc);\n\n                    tp.operations[0].operation = operations.first;\n                    tp.operations[1].operation = operations.second;\n\n                    replaced_method = method_touch;\n                }\n                else\n                {\n                    side_calculator\n                        <\n                            typename IntersectionInfo::robust_point1_type,\n                            typename IntersectionInfo::robust_point2_type,\n                            typename IntersectionInfo::robust_point2_type,\n                            typename IntersectionInfo::robust_point1_type,\n                            typename IntersectionInfo::robust_point1_type,\n                            typename IntersectionInfo::robust_point2_type,\n                            typename IntersectionInfo::robust_point1_type,\n                            typename IntersectionInfo::robust_point2_type\n                        > side_calc(inters.rqi(), inters.rpi(), inters.rpj(),\n                                    inters.rqi(), inters.rpi(), inters.rqj());\n\n                    std::pair<operation_type, operation_type>\n                        operations = get_info_e::operations_of_equal(side_calc);\n\n                    tp.operations[0].operation = operations.first;\n                    tp.operations[1].operation = operations.second;\n                }\n\n                turn_transformer_ec<true> transformer(replaced_method);\n                transformer(tp);\n            }\n\n            // equals<> or collinear<> will assign the second point,\n            // we'd like to assign the first one\n            base_turn_handler::assign_point(tp, tp.method, inters.i_info(), 0);\n\n            // NOTE: is_collinear is not set for the first endpoint of L\n            // for which there is no preceding segment\n            // here is_p_first_ip == true\n            tp.operations[0].is_collinear = false;\n\n            AssignPolicy::apply(tp, pi, qi, inters);\n            *out++ = tp;\n\n            was_first_point_handled = true;\n        }\n\n        // ANALYSE AND ASSIGN LAST\n\n        // IP on the last point of Linear Geometry\n        if ( BOOST_GEOMETRY_CONDITION(EnableLast)\n          && is_p_last\n          && ( ip_count > 1 ? (ip1.is_pj && !ip1.is_qi) : (ip0.is_pj && !ip0.is_qi) ) ) // prevents duplication\n        {\n            TurnInfo tp = tp_model;\n            \n            if ( inters.i_info().count > 1 )\n            {\n                //BOOST_GEOMETRY_ASSERT( result.template get<1>().dir_a == 0 && result.template get<1>().dir_b == 0 );\n                tp.operations[0].is_collinear = true;\n                tp.operations[1].operation = opposite ? operation_continue : operation_union;\n            }\n            else //if ( result.template get<0>().count == 1 )\n            {\n                side_calculator\n                    <\n                        typename IntersectionInfo::robust_point1_type,\n                        typename IntersectionInfo::robust_point2_type,\n                        typename IntersectionInfo::robust_point2_type\n                    > side_calc(inters.rqi(), inters.rpj(), inters.rpi(),\n                                inters.rqi(), inters.rqj(), inters.rqk());\n\n                std::pair<operation_type, operation_type>\n                    operations = get_info_e::operations_of_equal(side_calc);\n\n                tp.operations[0].operation = operations.first;\n                tp.operations[1].operation = operations.second;\n\n                turn_transformer_ec<false> transformer(method_none);\n                transformer(tp);\n\n                tp.operations[0].is_collinear = tp.both(operation_continue);\n            }\n\n            tp.method = ( ip_count > 1 ? ip1.is_qj : ip0.is_qj ) ? method_touch : method_touch_interior;\n            tp.operations[0].operation = operation_blocked;\n            tp.operations[0].position = position_back;\n            tp.operations[1].position = position_middle;\n            \n            // equals<> or collinear<> will assign the second point,\n            // we'd like to assign the first one\n            unsigned int ip_index = ip_count > 1 ? 1 : 0;\n            base_turn_handler::assign_point(tp, tp.method, inters.i_info(), ip_index);\n\n            AssignPolicy::apply(tp, pi, qi, inters);\n            *out++ = tp;\n\n            // don't ignore the first IP if the segment is opposite\n            return !( opposite && ip_count > 1 ) || was_first_point_handled;\n        }\n\n        // don't ignore anything for now\n        return false;\n    }\n};\n\n}} // namespace detail::overlay\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_LA_HPP\n", "meta": {"hexsha": "c095d6394790d5c04b3ae8ce9639a75a21f479e3", "size": 34697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/overlay/get_turn_info_la.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/overlay/get_turn_info_la.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/overlay/get_turn_info_la.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": 39.6537142857, "max_line_length": 118, "alphanum_fraction": 0.4694930397, "num_tokens": 6572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.01883312806623931, "lm_q1q2_score": 0.008536338431214065}}
{"text": "/*!\n * \\file   pred_corr_solver.cpp\n * \\author Robert I A Patterson\n *\n * \\brief  Routines for solving with predictor corrector coupling\n *\n *  Copyright (C) 2009 Robert I A Patterson.\n *\n\n Licence:\n    This file is part of \"brush\".\n\n    brush is free software; you can redistribute it and/or\n    modify it under the terms of the GNU General Public License\n    as published by the Free Software Foundation; either version 2\n    of the License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Prof Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n */\n#include \"pred_corr_solver.h\"\n\n#include \"reactor1d.h\"\n#include \"local_geometry1d.h\"\n\n#include \"swp_cell.h\"\n#include \"swp_solver.h\"\n\n#include \"choose_index.hpp\"\n\n#include <stdexcept>\n#include <limits>\n#include <algorithm>\n#include <vector>\n#include <list>\n#include <cassert>\n#include <boost/functional/hash.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nusing namespace Brush;\n\n/*!\n * This method has a number of anonymous arguments, which are provided as part\n * of the design for a two-way gas-particle coupled solver.  The arguments are\n * anonymous, because their values are not currently used.  Names are given in\n * the header file and should be copied here when they are needed.\n *\n *@param[in]    reset_chem              Chemical species concentrations as function of spatial position\n *@param[in]    corrector_iterations    Number of corrector iterations to perform during full coupling\n *@param[in]    split_diffusion         True if diffusion is to be simulated via splitting\n *@param[in]    drift_adjustment        Only relevant when split_diffusion is true, see \\ref mDiffusionDriftAdjustment\n *@param[in]    split_advection         True if advection is to be simulated via splitting\n *@param[in]    strang_advection        Use Strang splitting between transport and particle processes\n *@param[in]    cstr_transport          Transport between cell centres with CSTR random jumps\n *\n *@todo     Need generalisation to move away from using ResetChemistry\n */\n/*\n * Following parameters are skipped from the doxygen documentation, becuase they are not\n * names, which is because they are not yet used.\n * param[in]                            Relative tolerance for ODE solver used for gas phase\n * param[in]                            Absolute tolerance for ODE solver used for gas phase\n */\nBrush::PredCorrSolver::PredCorrSolver(const ResetChemistry& reset_chem,\n                                      const unsigned corrector_iterations,\n                                      const double , const double ,\n                                      const bool split_diffusion,\n                                      const double drift_adjustment,\n                                      const bool split_advection,\n                                      const bool strang_splitting,\n                                      const bool cstr_transport)\n    : mResetChemistry(reset_chem)\n    , mCorrectorIterations(corrector_iterations)\n    , mDeferralRatio(10.0)\n    , mSplitDiffusion(split_diffusion)\n    , mDiffusionDriftAdjustment(drift_adjustment)\n    , mSplitAdvection(split_advection)\n    , mStrangTransportSplitting(strang_splitting)\n    , mCSTRTransport(cstr_transport)\n{}\n\n/*!\n * Advance the solution to t_stop by means of n_steps equal length application\n * of the predictor corrector algorithm.\n *\n *\\param[in,out]        reac        Reactor describing system state\n *\\param[in]            t_start     Time from which to advance solution\n *\\param[in]            t_stop      Time to which to advance solution\n *\\param[in]            n_steps     Number of predictor corrector steps (ie number of splits between transport and particle processes)\n *\\param[in]            seed        Value that is unique to this particular time interval and path to use in seeding the RNGs\n */\nvoid Brush::PredCorrSolver::solve(Reactor1d &reac, const double t_start, const double t_stop, const int n_steps,\n                                  size_t seed) const {\n    const double dt = (t_stop - t_start) / n_steps;\n\n    // Start building a RNG seed for this part of the calculation.  The\n    // result should be different in each call, if this function is called\n    // repeatedly in order to simulate forward in time.\n    boost::hash_combine(seed, t_start);\n    boost::hash_combine(seed, t_stop);\n\n    // Build one RNG for each cell, so that the cells can be simulated\n    // independently apart from inter-cell transport.\n    std::vector<Sweep::rng_type> cellRNGs(reac.getNumCells());\n    for(unsigned i = 0; i < reac.getNumCells(); ++i) {\n        // Now make a RNG seed that is unique for each cell\n        size_t cellSeed = seed;\n        boost::hash_combine(cellSeed, i);\n        cellRNGs[i].seed(cellSeed);\n    }\n\n    for(int i = 1; i <= n_steps; ++i) {\n        predictorCorrectorStep(reac, t_start + (i - 1) * dt, t_start + i * dt, cellRNGs);\n    }\n}\n\n/*!\n * Advance the solution to t_stop by means of a predictor step followed\n * by zero or more corrector iterations\n *\n *\\param[in,out]        reac        Reactor describing system state\n *\\param[in]            t_start     Time from which to advance solution\n *\\param[in]            t_stop      Time to which to advance solution\n *\\param[in]            cell_rngs   Vector of independent RNGs, one for each cell\n *\n *\\pre  reac.getNumCells() == cell_rngs.size()\n */\nvoid Brush::PredCorrSolver::predictorCorrectorStep(Reactor1d &reac, const double t_start,\n                                                   const double t_stop,\n                                                   std::vector<Sweep::rng_type>& cell_rngs) const {\n    //std::cout << \"Predictor corrector step from \" << t_start << \" to \" << t_stop << '\\n';\n\n    //=========== Predictor step =====================\n    // Advance the chemistry\n    solveChemistry(reac, t_start, t_stop);\n\n\n    solveParticlesByCell(reac, t_start, t_stop, cell_rngs);\n\n//    std::cout << \"Particle counts and sample volume at end of predictorCorrectorStep \";\n//    for(size_t i = 0; i < reac.getNumCells(); ++i) {\n//        std::cout << reac.getCell(i).ParticleCount() << ' ' << reac.getCell(i).SampleVolume();\n//    }\n//    std::cout << std::endl;\n\n    //=========== Corrector steps ====================\n    for(unsigned i = 0; i < mCorrectorIterations; ++i) {\n        ;\n    }\n}\n\n\n/*!\n * Advance the chemistry part of the solution without performing any particle\n * events.  In this implementation the stop time is ignored and the chemistry\n * is interpolated from the reset object for the reactor time.\n *\n *\\param[in,out]        reac        Reactor describing system state\n *\\param[in]            t_start     Time from which to advance solution\n *\\param[in]            t_stop      Time to which to advance solution\n */\nvoid Brush::PredCorrSolver::solveChemistry(Reactor1d &reac,\n                                           const double t_start, const double t_stop) const {\n\n    // Expansion and contraction of the gas phase changes the particle\n    // concentration, since the same mass of gas still contains the same\n    // number of soot particles.  The change in volume containing a fixed mass\n    // of gas is inversely proportional to the change in gas mass density.\n    const size_t numCells = reac.getNumCells();\n    const Sweep::Mechanism &mech = reac.getParticleMechanism();\n\n    fvector oldDensity(numCells);\n    for(size_t i = 0; i != numCells; ++i) {\n        Sweep::Cell & mix = reac.getCell(i);\n        oldDensity[i] = mix.GasPhase().MassDensity();\n\n//        fvector chemRates;\n//    \tmech.CalcGasChangeRates(t_start, mix, Geometry::LocalGeometry1d(reac.getGeometry(), i),\n//    \t                        chemRates);\n//    \t//create system object (rhs functor) here\n\n    }\n\n    // Update the chemistry to the new time\n    reac.ReplaceChemistry(mResetChemistry, true);\n\n    // Update the soot particle concentration to account for the expansion /\n    // contraction of the gas.\n    for(size_t i = 0; i != numCells; ++i) {\n        Sweep::Cell & mix = reac.getCell(i);\n\n        // Collect data for calculating the new value\n        mix.AdjustSampleVolume(oldDensity[i] / mix.GasPhase().MassDensity());\n    }\n}\n\n/*!\n * Advance the particle part of the solution, which may also affect the chemical\n * species concentrations.\n *\n * Note that the flags activating split simulation of particle transport do not\n * disable any diffusion processes that may have been specified in the particle\n * mechanism.\n *\n *\\param[in,out]        reac        Reactor describing system state\n *\\param[in]            t_start     Time from which to advance solution\n *\\param[in]            t_stop      Time to which to advance solution\n *\\param[in]            cell_rngs   Vector of independent RNGs, one for each cell\n */\nvoid Brush::PredCorrSolver::solveParticlesByCell(Reactor1d &reac, const double t_start, const double t_stop,\n                                                 std::vector<Sweep::rng_type>& cell_rngs) const {\n\n    const size_t numCells = reac.getNumCells();\n    const Sweep::Mechanism &mech = reac.getParticleMechanism();\n\n    // Select time step for Strang or first order splitting\n    const double firstStop = mStrangTransportSplitting ? (t_start + t_stop) / 2.0 : t_stop;\n\n#pragma omp parallel for schedule(dynamic) ordered\n    for(int i = numCells; i > 0; --i) {\n        // Get details of cell i\n        Sweep::Cell& cell = reac.getCell(i - 1);\n        Geometry::LocalGeometry1d geom(reac.getGeometry(), i - 1);\n\n        solveParticlesInOneCell(cell, geom, mech, t_start, firstStop, cell_rngs[i - 1]);\n    }\n\n    // Now do the split particle transport, if there is any\n    if(mSplitDiffusion || mSplitAdvection) {\n        splitParticleTransport(reac, t_start, t_stop, cell_rngs);\n    }\n\n    if(mStrangTransportSplitting) {\n        // Do the second part of the particle simulation for the Strang splitting\n#pragma omp parallel for schedule(dynamic) ordered\n        for(int i = numCells; i > 0; --i) {\n            // Get details of cell i\n            Sweep::Cell& cell = reac.getCell(i - 1);\n            Geometry::LocalGeometry1d geom(reac.getGeometry(), i - 1);\n\n            solveParticlesInOneCell(cell, geom, mech, firstStop, t_stop, cell_rngs[i - 1]);\n        }\n    }\n\n}\n\n/*!\n * Advance the particle part of the solution, which may also affect the chemical\n * species concentrations.\n *\n * @todo  The choice of deferral length should be integrated with Sweep::Solver\n * with a view to using Sweep::Solver::Run()\n *\n *\\param[in,out]        cell        Contents of one grid cell\n *\\param[in]            geom        Position information regarding adjoining cells\n *\\param[in]            mech        Mechanism defining the particle processes\n *\\param[in]            t           Time from which to advance solution\n *\\param[in]            t_stop      Time to which to advance solution\n *\\param[in,out]        rng         RNG to use for the simulation\n */\nvoid Brush::PredCorrSolver::solveParticlesInOneCell(Sweep::Cell &cell, const Geometry::LocalGeometry1d &geom,\n                                                    const Sweep::Mechanism &mech, double t, double t_stop,\n                                                    Sweep::rng_type &rng) const {\n    // Carry out a repeated sequence of jump process simulation (with LPDA updates\n    // for particles involved in jumps) followed by LPDA updates for the full\n    // population.\n    do {\n        // Ignore the individual rate term information in the final argument\n        fvector dummyVec;\n        const double deferredRate = mech.CalcDeferredRateTerms(t, cell ,geom, dummyVec);\n\n        // Calculate both the rates of the individual jump processes and the total\n        fvector jumpRates;\n        double jumpRate = mech.CalcJumpRateTerms(t, cell, geom, jumpRates);\n\n        // Calculate the latest time at which all particles must be updated\n        // with deferred events.\n        double maxDeferralEnd = t_stop;\n        if(deferredRate / jumpRate > mDeferralRatio) {\n            // A large number of deferred events are expected between jump events\n            // so force updates to take place more frequently by shortening the\n            // time until the next update of all particles.\n            maxDeferralEnd = std::min(t_stop, mDeferralRatio * deferredRate);\n        }\n\n        // Simulate jumps upto maxDeferralEnd\n        // Put a very small tolerance on the comparison\n        while(t <= maxDeferralEnd * (1.0 - std::numeric_limits<double>::epsilon())) {\n            // Perform one non-deferred event\n\n            jumpRate = mech.CalcJumpRateTerms(t, cell, geom, jumpRates);\n            Sweep::Solver::timeStep(t, maxDeferralEnd, cell, geom, mech,\n                                    jumpRates, jumpRate, rng);\n        }\n\n        // Perform all events from deferred processes.\n        if (mech.AnyDeferred()) {\n            mech.LPDA(maxDeferralEnd, cell, rng);\n        }\n    } while(t <= t_stop * (1.0 - std::numeric_limits<double>::epsilon()));\n\n }\n\n/*!\n *@param[in,out]    reac        Reactor in which particles are being transported\n *@param[in]        t_start     Time at which position was last calculated by splitting\n *@param[in]        t_stop      Time upto which transport is to be simulated\n *@param[in,out]    cell_rngs   Random number generators, one per cell\n */\nvoid Brush::PredCorrSolver::splitParticleTransport(Reactor1d &reac, const double t_start,\n                                                   const double t_stop, std::vector<Sweep::rng_type>& cell_rngs) const {\n    const size_t numCells = reac.getNumCells();\n\n    // Element i of the outer vector will contain the outflow from cell i of the reactor.\n    // Element j of the inner vector will contain particles destined for cell j of the reactor.\n    // After this vector of vectors of lists had been populated, it will be necessary to merge\n    // the lists of particles being transported into each cell of the reactor.\n    std::vector<inflow_lists_vector> inflowLists(numCells, inflow_lists_vector(numCells));\n    std::vector<double> statisticalWeights(numCells);\n    std::vector<double> cellVolumes(numCells);\n    std::vector<double> maxCapacities(numCells);\n    std::vector<double> velocities(numCells);\n\n    // Loop over each cell updating particles positions and removing any\n    // particles that are moving to new cells.\n#pragma omp parallel for schedule(dynamic)\n    for(long int i = 0; i < numCells; ++i) {\n        Sweep::Cell &mix = reac.getCell(i);\n\n        // Flamelet advection needs some information on adjoining cells to calculate gradients\n        const Geometry::LocalGeometry1d geom(reac.getGeometry(), i);\n        //std::vector<const Sweep::Cell*> neighbouringCells(2, NULL);\n        std::vector<const Sweep::Cell*> neighbouringCells(2);\n        neighbouringCells[0] = neighbouringCells[1] = NULL;\n\n        // See if there is a left neighbour\n        int neighbourIndex = geom.calcDestination(Geometry::left);\n        if(neighbourIndex >= 0)\n            neighbouringCells[0] = &(reac.getCell(neighbourIndex));\n\n        // See if there is a right neighbour\n        neighbourIndex = geom.calcDestination(Geometry::right);\n        if(neighbourIndex >= 0)\n            neighbouringCells[1] = &(reac.getCell(neighbourIndex));\n\n        // The weight will be needed when the particles are put back into the cell\n        statisticalWeights[i] = 1.0 / mix.SampleVolume();\n        cellVolumes[i] = geom.cellVolume();\n        maxCapacities[i] = static_cast<double>(mix.Particles().Capacity());\n        velocities[i] = mix.GasPhase().Velocity();\n\n        // Remove all particles from the cell and add them\n        // to the inflow list for the appropriate cell\n        inflowLists[i] = updateParticleListPositions(t_start, t_stop, mix, i,\n                                                     reac.getParticleMechanism(),\n                                                     reac.getGeometry(), neighbouringCells,\n                                                     cell_rngs[i]);\n    }// loop over all cells and build up lists of particles that are moving cells\n\n    // There has to be a synchronisation point here, in that parallel replacement of\n    // particles in cells cannot begin until the positions and cells of all particles\n    // have been calculated.\n\n#pragma omp parallel for schedule(dynamic)\n    for(long int i = 0; i < numCells; ++i) {\n        // i is the index of the destination cell\n\n        // Build up a list of particle pointers to pass into the cell\n        // this variable is local to each loop iteration\n        Sweep::PartPtrList partList;\n\n        for(size_t j = 0; j != numCells; ++j) {\n            // Adjustment factor for particle statistical weight\n            const double weightFactor = (maxCapacities[j] * statisticalWeights[j]) /\n                                      (maxCapacities[i] * statisticalWeights[i]);\n\n            const double repeatCountConst =  cellVolumes[j] * maxCapacities[i] * velocities[i]\n                                         / cellVolumes[i] / maxCapacities[j] / velocities[j];\n//            if(i == j + 1) {\n//                std::cout << j << ' ' << \" max capac \" << maxCapacities[j] << \" inv sample vol \" << statisticalWeights[j] << \" cell volume \" << cellVolumes[j] <<std::endl;\n//                std::cout << i << ' ' << \" max capac \" << maxCapacities[i] << \" inv sample vol \" << statisticalWeights[i] << \" cell volume \" << cellVolumes[i] <<std::endl;\n//                std::cout << j << ' ' << i << ' ' << \" repeat count \" << repeatCountConst << \" weight factor \" << weightFactor  << std::endl;\n//            }\n\n            // Work through the particles coming from cell j\n            std::list<Sweep::Particle*>::const_iterator it = inflowLists[j][i].begin();\n            const std::list<Sweep::Particle*>::const_iterator itEnd = inflowLists[j][i].end();\n            while(it != itEnd) {\n                // Repeat count in destination cell (may be less than one), fractional parts are probability\n                // of a particle being added to destination.\n                double repeatCount = repeatCountConst;\n\n                (*it)->setStatisticalWeight((*it)->getStatisticalWeight() * weightFactor);\n\n                while(repeatCount > 0) {\n                    if(repeatCount > 1) {\n                        partList.push_back((*it)->Clone());\n                    }\n                    else {\n                        // Final copy of the particle can be the original, but is only added with\n                        // probability repeatCount.\n                        boost::random::bernoulli_distribution<double> particleDecider(repeatCount);\n                        if(particleDecider(cell_rngs[i]))\n                            partList.push_back((*it));\n                        else {\n                            delete (*it);\n                        }\n                    }\n                    repeatCount -= 1.0;\n                }\n                ++it;\n            }\n        }\n        if(partList.size() > reac.getCell(i).Particles().Capacity())\n            std::cout << \"Setting \" << partList.size() << \" particles on cell with center \" << reac.getGeometry().cellCentre(i) << std::endl;\n\n        reac.getCell(i).SetParticles(partList.begin(), partList.end(), statisticalWeights[i], cell_rngs[i]);\n    }\n}\n\n/*!\n *@param[in]        t_start             Time at which position was last calculated by splitting\n *@param[in]        t_stop              Time at which new position must be calculated\n *@param[in]        mix                 Mixture in which the particle is moving\n *@param[in]        mech                Mechanism specifying calculation of particle transport properties\n *@param[in]        geom                Information on locations of surrounding cells\n *@param[in]        neighbouringCells   Pointers to the contents of surrounding cells\n *@param[in,out]    sp                  Particle requiring updated position\n *@param[in,out]    rng                 Random number generator\n */\nvoid Brush::PredCorrSolver::updateParticlePosition(const double t_start, const double t_stop, const Sweep::Cell &mix,\n                                                   const Sweep::Mechanism &mech,\n                                                   const Geometry::LocalGeometry1d & geom,\n                                                   const std::vector<const Sweep::Cell*> & neighbouringCells,\n                                                   Sweep::Particle& sp, Sweep::rng_type &rng) const\n{\n    double newPosition = sp.getPosition();\n    {\n        const double dt = t_stop - t_start; //sp.getPositionTime();\n        assert(dt >= 0.0);\n        if(mSplitAdvection){\n            const double velocity = mech.AdvectionVelocity(mix, sp, neighbouringCells, geom);\n            newPosition += dt * velocity;\n        }\n        if(mSplitDiffusion){\n            const double diffusionCoeff = mech.DiffusionCoefficient(mix, sp);\n            typedef boost::normal_distribution<double> normal_distrib;\n            normal_distrib diffusionDistrib(0.0, std::sqrt(diffusionCoeff * dt));\n            boost::variate_generator<Sweep::rng_type&, normal_distrib> diffusionGenerator(rng, diffusionDistrib);\n            newPosition += diffusionGenerator();\n\n            if(mDiffusionDriftAdjustment > 0.0) {\n                // Drift correction to allow for different forms of stochastic integral\n                const double drift = mDiffusionDriftAdjustment * mech.GradDiffusionCoefficient(mix, sp, neighbouringCells, geom);\n                newPosition += dt * drift;\n            }\n        }\n    }\n    sp.setPositionAndTime(newPosition, t_stop);\n}\n\n\n/*!\n * CSTR stands for Continuously Stirred Tank Reactor, a chemical engineering term\n * referring to a perfectly mixed reactor.  Because it is perfectly mixed particles\n * cannot be said to flow through the reactor, rather they have a residence time\n * distribution.  In this case the expected residence time is taken as the length\n * of the reactor divided by the velocity and each particle has a probability of\n * leaving the reactor at each time step.  The probability is given by the ratio\n * of the time step length to the expected residence time.\n *\n *@param[in]        t_start             Time at which position was last calculated by splitting\n *@param[in]        t_stop              Time at which new position must be calculated\n *@param[in]        mix                 Mixture in which the particle is moving\n *@param[in]        mech                Mechanism specifying calculation of particle transport properties\n *@param[in]        geom                Information on locations of surrounding cells\n *@param[in]        neighbouringCells   Pointers to the contents of surrounding cells\n *@param[in,out]    sp                  Particle requiring updated position\n *@param[in,out]    rng                 Random number generator\n *\n *@pre      The expected residence time of the particle must be greater than the time step length.\n */\nvoid Brush::PredCorrSolver::updateParticlePositionCSTR(const double t_start, const double t_stop, const Sweep::Cell &mix,\n                                                       const Sweep::Mechanism &mech,\n                                                       const Geometry::LocalGeometry1d & geom,\n                                                       const std::vector<const Sweep::Cell*> & neighbouringCells,\n                                                       Sweep::Particle& sp, Sweep::rng_type &rng) const\n{\n    // Time over which transport is occurring\n    const double dt = t_stop - t_start;\n\n    // Probability according to CSTR that particle leaves cell in this time step\n    const double p = mech.AdvectionVelocity(mix, sp, neighbouringCells, geom) * dt / geom.cellVolume();\n    assert(p <= 1);\n\n    // The particle will either end up at the centre of this cell or the next\n    double newPosition = geom.cellCentre();\n\n    // Generate a sample to decide if the particle leaves\n    boost::random::bernoulli_distribution<double> leaveCell(p);\n    if(leaveCell(rng))\n        // Add the distance to the next cell centre\n        newPosition += geom.calcSpacing(Geometry::right);\n\n    sp.setPositionAndTime(newPosition, t_stop);\n}\n\n\n/*!\n *@param[in]        t_start             Time at which position was last calculated by splitting\n *@param[in]        t_stop              Time at which new position must be calculated\n *@param[in,out]    mix                 Mixture from which the particles are moving\n *@param[in]        cell_index          Index of cell containing the particles to be transported\n *@param[in]        mech                Mechanism specifying calculation of particle transport properties\n *@param[in]        geom                Information on locations of surrounding cells\n *@param[in]        neighbouringCells   Pointers to the contents of surrounding cells\n *@param[in,out]    rng                 Random number generator\n *\n *@return       Vector of lists of particles to be transported into other cells\n */\nBrush::PredCorrSolver::inflow_lists_vector\n  Brush::PredCorrSolver::updateParticleListPositions(const double t_start, const double t_stop, Sweep::Cell &mix,\n                                                     const size_t cell_index, const Sweep::Mechanism &mech,\n                                                     const Geometry::Geometry1d & geom,\n                                                     const std::vector<const Sweep::Cell*> & neighbouringCells,\n                                                     Sweep::rng_type &rng) const {\n    // Build up the return value in this vector of lists\n    inflow_lists_vector outflow(geom.numCells());\n\n    // The local geometry will be needed repeatedly for this cell\n    Geometry::LocalGeometry1d localGeom(geom, cell_index);\n\n    // Now go through the particles updating their position\n    Sweep::Ensemble::iterator itPart = mix.Particles().begin();\n    const Sweep::Ensemble::iterator itPartEnd = mix.Particles().end();\n    while(itPart != itPartEnd ) {\n        // Actually calculate new position of particle\n        if(mCSTRTransport)\n            updateParticlePositionCSTR(t_start, t_stop, mix, mech, localGeom, neighbouringCells, **itPart, rng);\n        else\n            updateParticlePosition(t_start, t_stop, mix, mech, localGeom, neighbouringCells, **itPart, rng);\n\n        // Find the index of the cell into which the particle is moving\n        const int destination = geom.containingCell((*itPart)->getPosition());\n\n        if(destination >= 0) {\n            // On moving to a new cell reset the coagulation count\n            if(static_cast<unsigned>(destination) != cell_index)\n               (*itPart)->resetCoagCount();\n\n            // Add the details of the particle to a list ready for inserting\n            // into its destination cell\n            outflow[destination].push_back(*itPart);\n\n        }\n        else {\n            // Particle has left simulation domain\n            delete *itPart;\n            *itPart = NULL;\n        }\n\n        // Remove the particle from this cell and move the iterator on\n        // to the next particle\n        ++itPart;\n    } // loop over all particles in cell i updating their position\n\n    // Empty the particle ensemble\n    mix.Particles().TakeParticles();\n\n    return outflow;\n}\n", "meta": {"hexsha": "0d763fa334f362e217d23fdbd5f76031bb9b3f6b", "size": 28037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/brush/source/pred_corr_solver.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/brush/source/pred_corr_solver.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/brush/source/pred_corr_solver.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 47.2799325464, "max_line_length": 173, "alphanum_fraction": 0.6233905197, "num_tokens": 6024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918074, "lm_q2_score": 0.027169229763340127, "lm_q1q2_score": 0.008532511414184601}}
{"text": "/*\n\nCopyright (c) 2005-2021, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef ABSTRACTGENERALIZEDRUSHLARSENCARDIACCELL_HPP_\n#define ABSTRACTGENERALIZEDRUSHLARSENCARDIACCELL_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"ClassIsAbstract.hpp\"\n#include \"AbstractCardiacCell.hpp\"\n#include \"PetscTools.hpp\"\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/**\n * This is the base class for cardiac cells solved using the GRL methods (GRL1 and GRL2).\n * Modified from AbstractRushLarsenCardiacCell.hpp\n */\nclass AbstractGeneralizedRushLarsenCardiacCell : 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     * Some notes for future reference:\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    AbstractGeneralizedRushLarsenCardiacCell(\n            unsigned numberOfStateVariables,\n            unsigned voltageIndex,\n            boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);\n\n    /** Virtual destructor */\n    virtual ~AbstractGeneralizedRushLarsenCardiacCell();\n\n    /**\n     * Simulates this cell's behaviour between the time interval [tStart, tEnd],\n     * with timestep #mDt.\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     * but the other state variables are updated.\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\n\n    /**\n     * @return whether the ODE system has an analytic Jacobian (#mHasAnalyticJacobian).\n     */\n    bool HasAnalyticJacobian() const;\n\n    /**\n     * Force the use of a numerical Jacobian, even if an analytic form is provided.\n     * This is needed for a handful of troublesome models.\n     *\n     * @param useNumericalJacobian  Whether to use a numerical instead of the analytic Jacobian.\n     */\n    void ForceUseOfNumericalJacobian(bool useNumericalJacobian = true);\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     * Update the values of all variables except the transmembrane potential using a GRL method.\n     *\n     * @param time  the current simulation time\n     */\n    virtual void ComputeOneStepExceptVoltage(double time)=0;\n\n    /**\n     * Perform a forward Euler step to update the transmembrane potential.\n     *\n     * @param time  the current simulation time\n     */\n    virtual void UpdateTransmembranePotential(double time)=0;\n\n    /** The diagonal of the Jacobian, working memory for use by subclasses. */\n    std::vector<double> mPartialF;\n\n    /** The derivatives, working memory for use by subclasses. */\n    std::vector<double> mEvalF;\n\n    /** The state at the beginning of the current step, working memory for use by subclasses. */\n    std::vector<double> mYInit;\n\n    /** Whether we have an analytic Jacobian. */\n    bool mHasAnalyticJacobian;\n};\n\nCLASS_IS_ABSTRACT(AbstractGeneralizedRushLarsenCardiacCell)\n\n#endif // ABSTRACTGENERALIZEDRUSHLARSENCARDIACCELL_HPP_\n", "meta": {"hexsha": "d468f5c811a888468463f80688cbe6b07d753172", "size": 7134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/odes/AbstractGeneralizedRushLarsenCardiacCell.hpp", "max_stars_repo_name": "mdp19pn/Chaste", "max_stars_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T08:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T11:39:26.000Z", "max_issues_repo_path": "heart/src/odes/AbstractGeneralizedRushLarsenCardiacCell.hpp", "max_issues_repo_name": "mdp19pn/Chaste", "max_issues_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-06-14T13:48:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:42:07.000Z", "max_forks_repo_path": "heart/src/odes/AbstractGeneralizedRushLarsenCardiacCell.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": 36.7731958763, "max_line_length": 99, "alphanum_fraction": 0.7261003645, "num_tokens": 1619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.021948252915177383, "lm_q1q2_score": 0.008529486737537131}}
{"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 \"color.h\"\n#include \"util/util.h\"\n#include \"util/sse_defs.h\"\n#include <vector>\n#include <Eigen/Core>\nusing namespace Eigen;\n#include <emmintrin.h>\n\ntemplate<typename F>\nstd::vector<float> initTable( F f, int N, float s ) {\n\tstd::vector<float> r( N );\n\tfor( int i=0; i<N; i++ )\n\t\tr[i] = f(s*i);\n\treturn r;\n}\nstatic const std::vector<float> ltable = initTable( [](float y){ return (y > ((6.0/29)*(6.0/29)*(6.0/29)) ? 116*pow((double)y,1.0/3.0)-16 : y*((29.0/3)*(29.0/3)*(29.0/3)))/270.; }, 1025, 1.0 / 1024. );\nstatic const std::vector<float> stable = initTable( [](float v){ return (v < 0.4045f ? v / 12.92f : pow( (v+0.055f)/1.055f, 2.4f ) ); }, 1025, 1.0 / 1024. );\n\ninline float mapTable( float v, const float * t, int N ) {\n\tif( v < 0 )  v = 0;\n\tif( v > N-1 ) v = N-1;\n\treturn t[(int)v];\n}\ntemplate<typename T>\nT min( T a, T b ) {\n\treturn std::min(a,b);\n}\ntemplate<> __m128 min<__m128>( __m128 a, __m128 b ) {\n\treturn _mm_min_ps(a,b);\n}\ntemplate<typename T>\nT max( T a, T b ) {\n\treturn std::max(a,b);\n}\ntemplate<> __m128 max<__m128>( __m128 a, __m128 b ) {\n\treturn _mm_max_ps(a,b);\n}\ntemplate<typename T>\nstatic T c( float a ) {\n\treturn a;\n}\ntemplate<> __m128 c<__m128>( float a ) {\n\treturn _mm_set1_ps( a );\n}\ninline __m128 mapTable( __m128 v, const float * t, int N ) {\n\tfloat * vv = (float*)&v;\n\treturn _mm_set_ps( mapTable( vv[3], t, N ), mapTable( vv[2], t, N ), mapTable( vv[1], t, N ), mapTable( vv[0], t, N ) );\n}\ntemplate<typename T>\nvoid rgb2xyz( T & x, T & y, T & z, const T & r, const T & g, const T & b ) {\n\tx = c<T>(0.430574f)*r + c<T>(0.341550f)*g + c<T>(0.178325f)*b;\n\ty = c<T>(0.222015f)*r + c<T>(0.706655f)*g + c<T>(0.071330f)*b;\n\tz = c<T>(0.020183f)*r + c<T>(0.129553f)*g + c<T>(0.939180f)*b;\n}\ntemplate<typename T>\nT gcorr( const T & v ) {\n\treturn mapTable( c<T>(1024)*v, stable.data(), stable.size() );\n}\ntemplate<typename T>\nvoid srgb2xyz( T & x, T & y, T & z, T r, T g, T b ) {\n\tr = gcorr( r );\n\tg = gcorr( g );\n\tb = gcorr( b );\n\tx = c<T>(0.4124564f)*r + c<T>(0.3575761f)*g + c<T>(0.1804375f)*b;\n\ty = c<T>(0.2126729f)*r + c<T>(0.7151522f)*g + c<T>(0.0721750f)*b;\n\tz = c<T>(0.0193339f)*r + c<T>(0.1191920f)*g + c<T>(0.9503041f)*b;\n}\ntemplate<typename T> void xyz2luv( T& l, T& u, T& v, T x, T y, T z ) {\n\tconst T un = c<T>(0.197833f), vn = c<T>(0.468331f);\n\tl = mapTable( c<T>(1024.f)*y, ltable.data(), ltable.size() );\n\tz = c<T>(1.f) / (x + c<T>(15.f)*y + c<T>(3.f)*z + c<T>(1e-35f) );\n\tu = l * (c<T>(13.f)*(c<T>(4.f)*x*z - un)) + c<T>(88.f/270.f);\n\tv = l * (c<T>(13.f)*(c<T>(9.f)*y*z - vn)) + c<T>(134.f/270.f);\n}\ntemplate<typename T> void xyz2lab( T& l, T& a, T& b, T x, T y, T z ) {\n\tx *= c<T>(1.f/0.950456f);\n\tz *= c<T>(1.f/1.088754f);\n\tx = mapTable( c<T>(1024)*x, ltable.data(), ltable.size() );\n\ty = mapTable( c<T>(1024)*y, ltable.data(), ltable.size() );\n\tz = mapTable( c<T>(1024)*z, ltable.data(), ltable.size() );\n\tl = y;\n\ta = c<T>(500.f/116.f)*(x-y);\n\tb = c<T>(200.f/116.f)*(y-z);\n}\nenum ColorType{\n\tLUV,\n\tLAB\n};\ntemplate<bool SRGB,ColorType type,typename T>\nstatic void convertRGB( T& c1, T& c2, T& c3, const T & R, const T & G, const T & B ) {\n\tT x,y,z;\n\tif (SRGB)\n\t\tsrgb2xyz( x,y,z, R,G,B );\n\telse\n\t\trgb2xyz( x,y,z, R,G,B );\n\tif (type==LUV)\n\t\txyz2luv( c1,c2,c3, x,y,z );\n\telse\n\t\txyz2lab( c1,c2,c3, x,y,z );\n}\ntemplate<bool SRGB,ColorType type>\nstatic void convertRGB( Image & luv, const Image & rgb ) {\n\tif( rgb.C()!= 3 )\n\t\tthrow std::invalid_argument( \"RGB image required!\" );\n\tconst int W = rgb.W(), H = rgb.H();\n\tluv.create( W, H, 3 );\n\tint i;\n\tfor( i=0; i+3<W*H; i+=4 ) {\n\t\t__m128 r = _mm_set_ps( rgb[3*i+0], rgb[3*(i+1)+0], rgb[3*(i+2)+0], rgb[3*(i+3)+0] );\n\t\t__m128 g = _mm_set_ps( rgb[3*i+1], rgb[3*(i+1)+1], rgb[3*(i+2)+1], rgb[3*(i+3)+1] );\n\t\t__m128 b = _mm_set_ps( rgb[3*i+2], rgb[3*(i+1)+2], rgb[3*(i+2)+2], rgb[3*(i+3)+2] );\n\t\t__m128 l,u,v;\n\t\tconvertRGB<SRGB,type>( l, u, v, r, g, b );\n\t\tfloat * ll = (float*)&l, * uu = (float*)&u, * vv = (float*)&v;\n\t\tfor( int k=0; k<4; k++ ){\n\t\t\tluv[3*(i+k)+0] = ll[k];\n\t\t\tluv[3*(i+k)+1] = uu[k];\n\t\t\tluv[3*(i+k)+2] = vv[k];\n\t\t}\n\t}\n\tfor( i=0; i<W*H; i++ )\n\t\tconvertRGB<SRGB,type>( luv[3*i+0],luv[3*i+1],luv[3*i+2], rgb[3*i+0],rgb[3*i+1],rgb[3*i+2] ); \n}\nvoid rgb2luv( Image & luv, const Image & rgb ) {\n\tconvertRGB<false,LUV>( luv, rgb );\n}\nvoid srgb2luv( Image & luv, const Image & rgb ) {\n\tconvertRGB<true,LUV>( luv, rgb );\n}\nvoid rgb2lab( Image & lab, const Image & rgb ) {\n\tconvertRGB<false,LAB>( lab, rgb );\n}\nvoid srgb2lab( Image & lab, const Image & rgb ) {\n\tconvertRGB<true,LAB>( lab, rgb );\n}\nvoid rgb2hsv( Image & hsv, const Image & rgb ) {\n\tif( rgb.C()!= 3 )\n\t\tthrow std::invalid_argument( \"RGB image required!\" );\n\tconst int W = rgb.W(), H = rgb.H();\n\thsv.create( W, H, 3 );\n\tconst int N = W*H;\n\tfor( int i=0; i<N; i++ ) {\n\t\tfloat s,v;\n\t\thsv[3*i+2] = v = std::max(rgb[3*i+0],std::max(rgb[3*i+1],rgb[3*i+2]));\n\t\thsv[3*i+1] = s = v-std::min(rgb[3*i+0],std::min(rgb[3*i+1],rgb[3*i+2]));\n\t\tif( v == rgb[3*i+0] )\n\t\t\thsv[3*i+0] = (rgb[3*i+1] - rgb[3*i+2]) / (6.*s+1e-10);\n\t\telse if( v == rgb[3*i+1] )\n\t\t\thsv[3*i+0] = (2+rgb[3*i+2] - rgb[3*i+0]) / (6.*s+1e-10);\n\t\telse if( v == rgb[3*i+2] )\n\t\t\thsv[3*i+0] = (4+rgb[3*i+0] - rgb[3*i+1]) / (6.*s+1e-10);\n\t\tif( hsv[3*i+0] < 0 )\n\t\t\thsv[3*i+0] += 1;\n\t}\n}\n", "meta": {"hexsha": "11e4e05c8baf8dd3bc022ce4b7f2b38ea3269d62", "size": 6770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sd_maskrcnn/gop/lib/imgproc/color.cpp", "max_stars_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_stars_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 183.0, "max_stars_repo_stars_event_min_datetime": "2018-10-12T05:16:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:56:56.000Z", "max_issues_repo_path": "sd_maskrcnn/gop/lib/imgproc/color.cpp", "max_issues_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_issues_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2018-10-25T06:50:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T08:51:35.000Z", "max_forks_repo_path": "sd_maskrcnn/gop/lib/imgproc/color.cpp", "max_forks_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_forks_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T10:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:56:29.000Z", "avg_line_length": 37.1978021978, "max_line_length": 201, "alphanum_fraction": 0.5982274742, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.017442486619631048, "lm_q1q2_score": 0.008516876589035613}}
{"text": "// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n/* decision_tree_generator.cc\n   Jeremy Barnes, 15 March 2006\n   Copyright (c) 2006 Jeremy Barnes  All rights reserved.\n   $Source$\n\n   Generator for decision trees.\n*/\n\n#include \"decision_tree_generator.h\"\n#include \"mldb/plugins/jml/jml/registry.h\"\n#include \"training_index.h\"\n#include \"weighted_training.h\"\n#include \"stump_training_core.h\"\n#include \"stump_training.h\"\n#include \"stump_training_bin.h\"\n#include \"stump_regress.h\"\n#include \"binary_symmetric.h\"\n#include \"mldb/utils/smart_ptr_utils.h\"\n#include \"mldb/base/thread_pool.h\"\n#include <boost/timer/timer.hpp>\n\n#include <random>\n#include <mutex>\n\n\nusing namespace std;\n\n\nnamespace ML {\n\n// Tuning parameters for the compacting code.  This controls how frequently\n// we compact.  Compacting makes operations faster, but takes time and\n// memory.\n\n/// If there are less than 1 in COMPACT_SPARSENESS_RATIO non-zero entries,\n/// then we compact the dataset.\nstatic constexpr int COMPACT_SPARSENESS_RATIO=8;\n\n/// On entry, if we have a density less than COMPACT_INITIAL_DENSITY,\n/// we compact the dataset.\nstatic constexpr float COMPACT_INITIAL_DENSITY=0.5;\n\n\n\n/// Glue code to allow the templated version of compactDataset to find\n/// the first weight, no matter what types are passed in.\nfloat getFirstWeight(const float * f)\n{\n    return *f;\n}\n\nfloat getFirstWeight(float f)\n{\n    return f;\n}\n\ntemplate<class Weights>\nvoid compact_dataset(const Training_Data & data,\n                     const vector<float> & in_class,\n                     const Weights & weights,\n                     const distribution<float> & binary_weights,\n                     int num_non_zero,\n                     Training_Data & new_data,\n                     vector<float> & new_in_class,\n                     Weights & new_weights,\n                     distribution<float> & new_binary_weights,\n                     const vector<Feature> & features,\n                     const Feature & predicted)\n{\n    /* Compact the dataset, since we only need a fraction of it.  We\n       simply recreate all of the strucutres, but with the entries that\n       would have been zero not there anymore.\n       \n       Note that this can lead to high memory usage, and is not necessary.\n       If there are problems with memory, we could disable this code and\n       the algorithm would continue to function.\n    */\n\n    new_in_class.reserve(num_non_zero);\n\n    if (binary_weights.empty())\n        new_weights.reserve(num_non_zero);\n    else new_binary_weights.reserve(num_non_zero);\n\n    for (unsigned i = 0;  i < in_class.size();  ++i) {\n        // NOTE: here we assume that either all class weights are zero, or\n        // none are zero.  That way we only need to look at the first weight.\n        if (binary_weights.empty()) {\n            if (in_class[i] <= 0.0f || getFirstWeight(weights[i]) == 0.0f) continue;\n            new_in_class.push_back(in_class[i]);\n            new_weights.push_back(weights[i]);\n        }\n        else {\n            if (in_class[i] <= 0.0f || binary_weights[i] == 0.0f) continue;\n            new_in_class.push_back(in_class[i]);\n            new_binary_weights.push_back(binary_weights[i]);\n        }\n    }\n\n    // Create a filtered version of the dataset\n    new_data.initFiltered(data, in_class, predicted, features);\n}\n\n\n/*****************************************************************************/\n/* DECISION_TREE_GENERATOR                                                   */\n/*****************************************************************************/\n\nDecision_Tree_Generator::\nDecision_Tree_Generator()\n{\n    defaults();\n}\n\nDecision_Tree_Generator::~Decision_Tree_Generator()\n{\n}\n\nvoid\nDecision_Tree_Generator::\nconfigure(const Configuration & config, vector<string> & unparsedKeys)\n{\n    Classifier_Generator::configure(config, unparsedKeys);\n\n    config.findAndRemove(trace, \"trace\", unparsedKeys);\n    config.findAndRemove(max_depth, \"max_depth\", unparsedKeys);\n    config.findAndRemove(update_alg, \"update_alg\", unparsedKeys);\n    config.findAndRemove(random_feature_propn, \"random_feature_propn\", unparsedKeys);\n    config.findAndRemove(verbosity, \"verbosity\", unparsedKeys);\n}\n\nvoid\nDecision_Tree_Generator::\ndefaults()\n{\n    Classifier_Generator::defaults();\n    trace = 0;\n    max_depth = -1;\n    update_alg = Stump::PROB;\n    random_feature_propn = 1.0;\n}\n\nConfig_Options\nDecision_Tree_Generator::\noptions() const\n{\n    Config_Options result = Classifier_Generator::options();\n    result\n        .add(\"trace\", trace, \"0-\",\n             \"trace execution of training in a very fine-grained fashion\")\n        .add(\"max_depth\", max_depth, \"0- or -1\",\n             \"give maximum tree depth.  -1 means go until data separated\")\n        .add(\"update_alg\", update_alg,\n             \"select the type of output that the tree gives\")\n        .add(\"random_feature_propn\", random_feature_propn, \"0.0-1.0\",\n             \"proportion of the features to enable (for random forests)\");\n    \n    return result;\n}\n\nvoid\nDecision_Tree_Generator::\ninit(std::shared_ptr<const Feature_Space> fs, Feature predicted)\n{\n    Classifier_Generator::init(fs, predicted);\n    model = Decision_Tree(fs, predicted);\n}\n\nstd::shared_ptr<Classifier_Impl>\nDecision_Tree_Generator::\ngenerate(Thread_Context & context,\n         const Training_Data & training_set,\n         const Training_Data & validation_set,\n         const distribution<float> & training_ex_weights,\n         const distribution<float> & validate_ex_weights,\n         const std::vector<Feature> & features, int) const\n{\n    boost::timer::cpu_timer timer;\n\n    Feature predicted = model.predicted();\n\n    boost::multi_array<float, 2> weights\n        = expand_weights(training_set, training_ex_weights, predicted);\n\n    Decision_Tree current\n        = train_weighted(context, training_set, weights, features, max_depth);\n    \n    if (verbosity > 2)\n        cerr << current.print() << endl;\n    \n    return std::make_shared<Decision_Tree>(std::move(current));\n}\n\nstd::shared_ptr<Classifier_Impl>\nDecision_Tree_Generator::\ngenerate(Thread_Context & context,\n         const Training_Data & training_set,\n         const boost::multi_array<float, 2> & weights,\n         const std::vector<Feature> & features,\n         float & Z,\n         int recursion) const\n{\n    //boost::timer::cpu_timer timer;\n\n    //Feature predicted = model.predicted();\n\n    Decision_Tree current\n        = train_weighted(context, training_set, weights, features, max_depth);\n    \n    if (verbosity > 2) cerr << current.print() << endl;\n    \n    return make_sp(current.make_copy());\n}\n\nDecision_Tree\nDecision_Tree_Generator::\ntrain_weighted(Thread_Context & context,\n               const Training_Data & data,\n               const boost::multi_array<float, 2> & weights,\n               const std::vector<Feature> & features,\n               int max_depth) const\n{\n    Decision_Tree result = model;\n\n    Feature predicted = model.predicted();\n\n    /* Record which examples are in our class and with what weight they\n       are there. */\n    distribution<float> in_class(data.example_count(), 1.0);\n\n    int nlw = weights.shape()[1];\n\n    for (unsigned i = 0;  i < data.example_count();  ++i) {\n        bool nonZero = false;\n        for (unsigned j = 0;  j < nlw && !nonZero;  ++j) {\n            nonZero = weights[i][j] != 0;\n        }\n\n        in_class[i] = nonZero;\n    }\n    \n    bool regression_problem\n        = result.feature_space()->info(predicted).type() == REAL;\n\n    if (random_feature_propn < 0.0 || random_feature_propn > 1.0)\n        throw Exception(\"random_feature_propn is not between 0.0 and 1.0\");\n\n\n    vector<Feature> filtered_features;\n    if (random_feature_propn < 1.0) {\n\n        int iter = 0;\n        while (filtered_features.empty() && iter < 50) {\n            typedef mt19937 engine_type;\n            engine_type engine(context.random());\n            std::uniform_real_distribution<> rng(0, 1);\n            \n            for (unsigned i = 0;  i < features.size();  ++i) {\n                if (rng(engine) < random_feature_propn)\n                    filtered_features.push_back(features[i]);\n            }\n        }\n        \n        if (filtered_features.empty())\n            throw Exception(\"random_feature_propn is too low\");\n    }\n    else filtered_features.insert(filtered_features.end(),\n                                  features.begin(), features.end());\n\n    if (max_depth == -1)\n        max_depth = 50;\n\n    if (regression_problem) {\n        vector<float> weights_vec(data.example_count());\n        for (unsigned x = 0;  x < weights_vec.size();  ++x)\n            weights_vec[x] = weights[x][0];\n\n        result.tree.root = train_recursive_regression\n            (context, data, weights_vec, filtered_features, in_class,\n             0, max_depth, result.tree);\n    }\n    else {\n\n        convert_bin_sym(const_cast<boost::multi_array<float, 2> &>(weights),\n                        data, predicted, features);\n\n        int advance = get_advance(weights);\n        vector<const float *> weights_vec(data.example_count());\n\n        for (unsigned x = 0;  x < weights_vec.size();  ++x)\n            weights_vec[x] = &weights[x][0];\n\n        int numNonZero = 0;\n\n        for (unsigned i = 0;  i < weights_vec.size();  ++i) {\n            if (weights_vec[i][0] != 0.0)\n                ++numNonZero;\n        }\n        \n        //cerr << \"numNonZero = \" << numNonZero << endl;\n\n        if (numNonZero < COMPACT_INITIAL_DENSITY * weights_vec.size()) {\n            Training_Data new_data(data.feature_space());\n            distribution<float> new_in_class;\n            vector<const float *> new_weights;\n            distribution<float> new_binary_weights;\n\n            compact_dataset(data, in_class, weights_vec, {} /* binary weights */, numNonZero,\n                            new_data, new_in_class, new_weights, new_binary_weights,\n                            features, model.predicted());\n\n            result.tree.root = train_recursive\n                (context, new_data, new_weights, advance, filtered_features,\n                 new_in_class, 0, max_depth, result.tree);\n        }\n        else {\n            result.tree.root = train_recursive\n                (context, data, weights_vec, advance, filtered_features, in_class,\n                 0, max_depth, result.tree);\n        }\n\n        result.encoding = Stump::update_to_encoding(update_alg);\n\n        /* Validate that the examples in the training set are indeed split\n           the way it says */\n        // TODO\n    }\n    \n    return result;\n}\n\nnamespace {\n\n/** Structure in which we hold the results of the line search over potential\n    split points. */\ntemplate<class W, class Z, class Tracer = No_Trace>\nstruct Tree_Accum {\n\n    Tree_Accum(const Feature_Space & fs, int nl,\n               const Tracer & tracer = Tracer())\n        : tracer(tracer), best_w(nl),\n          best_arg(numeric_limits<float>::quiet_NaN()),\n          best_z(Z::worst),\n          best_feature(MISSING_FEATURE), fs(fs)\n    {\n    }\n\n    Tracer tracer;\n    \n    Z calc_z;\n\n    W best_w;\n    float best_arg;\n    std::atomic<float> best_z;  // read without the lock and strictly decrementing\n    Feature best_feature;\n\n    bool has_result() const { return best_feature != MISSING_FEATURE; }\n\n    std::mutex lock;\n\n    const Feature_Space & fs;\n\n    /** Method that gets called when we start a new feature.  We use it to\n        pre-cache part of the work from the Z calculation, as we are\n        assured that the MISSING buckets of W will never change after this\n        method is called.\n\n        Return value is used to allow an early exit from the training process,\n        due to it being impossible for this feature to have a high enough\n        value to be included.\n    */\n    bool start(const Feature & feature, const W & w, double & missing)\n    {\n        bool optional = fs.info(feature).optional();\n        missing = calc_z.missing(w, optional);\n        bool keep_going = calc_z.can_beat(w, missing, best_z);\n\n        return keep_going;\n    }\n\n    /** Method that gets called when we have found a potential split point. */\n    float add_z(const Feature & feature, const W & w, float arg, float z)\n    {\n        if (false) {\n        // Check that the dataset was split evenly enough, ie that at least\n        // 10% of the data is in one bucket\n\n            double w_true = w(0,true,0) + w(0,true,1);\n            double w_false = w(0,false,0) + w(0,false,1);\n            double w_missing = w(0,MISSING,0) + w(0,MISSING,1);\n            double w_total = (w_true + w_false + w_missing);\n            w_true /= w_total;  w_false /= w_total;  w_missing /= w_total;\n            double threshold = 0.2;\n\n            int n = (w_true > threshold)\n                + (w_false > threshold)\n                + (w_missing > threshold);\n            \n            if (n < 2) { z += (1 - z) * 0.9; };\n        }\n\n\n        bool print_feat = false;\n        //print_feat = fs.print(feature) == \"language_cosine\";\n        if (tracer || print_feat)\n            tracer(\"tree accum\", 3)\n                << \"  accum: feature \" << feature << \" arg \" << arg\n                << \" (\" << fs.print(feature, arg)\n                << \"; 0x\" << format(\"%08x\", reinterpret_as_int(arg))\n                << \") z \" << z << \"  \" << fs.print(feature)\n                << (z < best_z ? \" ****\" : \"\")\n                << endl;\n\n        if (tracer || print_feat)\n            tracer(\"tree accum\", 4) << w.print() << endl;\n        \n        auto isBetter = [&] ()\n        {\n            // Break ties in a consistent manner: first compare z, then feature, then argument\n            // so that the output is always deterministic\n            return less_all(z, best_z.load(), feature, best_feature, arg, best_arg);\n        };\n\n        if (z <= best_z) {  // first check only checks z to avoid taking the lock\n            std::unique_lock<std::mutex> guard(lock);\n\n            if (isBetter()) {\n\n#if 0 // MLDB-784... sparse features can have a non-finite split                \n                if (!isfinite(arg)) {  // will never happen\n                    static std::mutex mutex;\n                    std::unique_lock<std::mutex> guard(mutex);\n\n                    cerr << \"Best arg had non-finite split\" << endl;\n                    cerr << \"feature = \" << fs.print(feature) << endl;\n                    cerr << \"info = \" << fs.info(feature) << endl;\n                    cerr << \"z = \" << z << endl;\n                    cerr << \"arg = \" << arg << endl;\n\n                    cerr << \"Beating previous best\" << endl;\n                    cerr << \"feature = \" << fs.print(best_feature) << endl;\n                    cerr << \"info = \" << fs.info(best_feature) << endl;\n                    cerr << \"z = \" << best_z << endl;\n                    cerr << \"arg = \" << best_arg << endl;\n                }\n#endif // MLDB-784\n\n                if (tracer || print_feat)\n                    tracer(\"tree accum\", 4) << w.print() << endl;\n                // A better one.  This replaces whatever we had accumulated so\n                // far.\n                best_z = z;\n                best_w = w;\n                best_arg = arg;\n                best_feature = feature;\n            }\n        }\n        \n        return z;\n    }\n\n    float add(const Feature & feature, const W & w, float arg, double missing)\n    {\n        // If the decision tree generator is having a really tough time\n        // separating the classes, and it's a bucketed feature, than it\n        // may send back a -INF for arg (which means split on missing or\n        // not missing), even if there is no missing feature, due to\n        // numerical issues.  Since the decision tree can't handle a split\n        // point of -INIFINITY, we return that we don't want this split\n        // point so that it will continue looking for something better.\n\n        //if (!isfinite(arg)) {\n        //    return Z::none;\n        //}\n\n        float z = calc_z.non_missing(w, missing);\n        return add_z(feature, w, arg, z);\n    }\n\n    float add_presence(const Feature & feature, const W & w, float arg,\n                       double missing)\n    {\n        float z = calc_z.non_missing_presence(w, missing);\n        return add_z(feature, w, arg, z);\n    }\n\n    void finish(const Feature & feature)\n    {\n        // nothing to do here, at the moment\n    }\n\n    Split split()\n    {\n        if (!has_result()) return Split();\n        Split result(best_feature, best_arg, fs);\n        return result;\n    }\n\n    double z() const\n    {\n        return best_z;\n    }\n};\n\ntemplate<class W>\nvoid\nget_probs(distribution<float> & probs, const W & w_,\n          Stump::Update update, float epsilon = 0.0)\n{\n#if 1\n    W w = w_;\n    for (unsigned j = 1;  j < 3;  ++j) {\n        for (unsigned l = 0;  l < w.nl();  ++l) {\n            w(l, 0, true) += w(l, j, true);\n            w(l, 0, false) += w(l, j, false);\n        }\n    }\n\n    probs.resize(w.nl());\n    \n    //cerr << \"get_probs(): w_ = \" << endl << w_.print() << endl << \"w = \" << endl\n    //     << w.print() << endl << \" probs = \" << probs << endl;\n\n    C_any c(update);\n    return c(probs.data(), 0, w, epsilon, false);\n\n#else\n    distribution<float> result(w.nl());\n\n    for (unsigned j = 0;  j < 3;  ++j)\n        for (unsigned l = 0;  l < w.nl();  ++l)\n            result[l] += w(l, j, true);\n\n    result.normalize();\n    return result;\n#endif\n}\n\nvoid\nfillin_leaf(Tree::Leaf & leaf,\n            const Training_Data & data,\n            const Feature & predicted,\n            const vector<const float *> & weights,\n            int advance,\n            const distribution<float> & in_class,\n            Stump::Update update_alg,\n            float examples = -1.0)\n{\n    /* Use the stump trainer to accumulate for us. */\n\n    if (examples == -1.0) examples = in_class.total();\n\n    //cerr << \"new_leaf: advance = \" << advance << endl;\n    \n    if (advance < 0)\n        throw Exception(\"invalid advance\");\n\n    leaf.examples = examples;\n\n    if (advance != 0) {\n        typedef W_normal W;\n        typedef Z_normal Z;\n        typedef Stump_Trainer<W, Z> Trainer;\n        Trainer trainer;\n\n        W w = trainer.calc_default_w(data, predicted, in_class, weights, advance);\n\n        double epsilon = xdiv<double>(1.0, examples);\n        get_probs(leaf.pred, w, update_alg, epsilon);\n\n        //cerr << \"new_leaf norm: dist = \" << dist << \" W = \" << endl\n        //     << w.print() << endl;\n    }\n    else {\n        typedef W_binsym W;\n        typedef Z_binsym Z;\n        typedef Stump_Trainer<W, Z> Trainer;\n        Trainer trainer;\n        \n        //cerr << \"getting default W\" << endl;\n\n        W w = trainer.calc_default_w(data, predicted, in_class, weights, advance);\n\n        double epsilon = xdiv<double>(1.0, examples);\n        get_probs(leaf.pred, w, update_alg, epsilon);\n\n        //cerr << \"new_leaf binsym: dist = \" << dist << \" W = \" << endl\n        //     << w.print() << endl;\n    }\n}\n\nvoid\nfillin_leaf_regression(Tree::Leaf & leaf,\n                       const Training_Data & data,\n                       const Feature & predicted,\n                       const vector<float> & weights,\n                       const distribution<float> & in_class,\n                       float examples = -1.0)\n{\n    /* Calculate the weighted mean over the examples in this class. */\n    int nx = data.example_count();\n\n    double total_weight = 0.0;\n    double total_val = 0.0;\n\n    const vector<Label> & labels = data.index().labels(predicted);\n\n    for (unsigned x = 0;  x < nx;  ++x) {\n        float w = weights[x] * in_class[x];\n        float val = labels[x].value();\n        total_weight += w;\n        total_val += w * val;\n    }\n\n    distribution<float> dist(1, total_val / total_weight);\n\n    if (examples == -1.0) examples = in_class.total();\n\n    leaf.pred = dist;\n    leaf.examples = examples;\n}\n\nvoid split_dataset(const Training_Data & data,\n                   const Split & split,\n                   const distribution<float> & in_class,\n                   distribution<float> & class_true,\n                   distribution<float> & class_false,\n                   distribution<float> & class_missing,\n                   double & total_true,\n                   double & total_false,\n                   double & total_missing,\n                   bool validate)\n{\n    // TODO: we could use the index for the feature instead?\n\n    /* Split these examples based upon what the split said. */\n    int nx = data.example_count();\n\n    class_true = distribution<float>(nx);\n    class_false = distribution<float>(nx);\n    class_missing = distribution<float>(nx);\n\n    total_true = 0.0;\n    total_false = 0.0;\n    total_missing = 0.0;\n\n    Joint_Index index = data.index().dist(split.feature(), BY_EXAMPLE,\n                                          IC_VALUE | IC_DIVISOR | IC_EXAMPLE);\n\n    int last_example = -1;\n    for (unsigned i = 0;  i < index.size();  ++i) {\n        int example = index[i].example();\n\n        // Any which we skipped over are missing\n        for (++last_example; last_example < example; ++last_example) {\n            float w = in_class[last_example];\n            if (w == 0.0) continue;\n            //cerr << \"missing: example = \" << example << \" last_example = \"\n            //     << last_example << endl;\n            class_missing[last_example] += w;\n            total_missing += w;\n        }\n        \n        last_example = example;\n\n        float w = in_class[example];\n        if (w == 0.0) continue;\n\n        float val = index[i].value();\n        float divisor = index[i].divisor();\n        w *= divisor;\n        \n        if (MLDB_UNLIKELY(isnan(val))) {\n            // We only have NaN values explicitly represented if there is a\n            // feature that is both present and missing in the same example.\n            // In that case, we need to deal with the missing part here.\n            class_missing[example] += w;\n            total_missing += w;\n            continue;\n        }\n\n        int decision;\n        try {\n            decision = split.apply(val);\n        } catch (...) {\n            cerr << \"exception on split: \" << split.print(*data.feature_space())\n                 << endl;\n            throw;\n        }\n\n        switch(decision) {\n        case false:\n            class_false[example] += w;\n            total_false += w;\n            break;\n        case true:\n            class_true[example] += w;\n            total_true += w;\n            break;\n        case MISSING:\n            class_missing[example] += w;\n            total_missing += w;\n            break;\n        default:\n            throw Exception(\"split_dataset: bad decision\");\n        };\n    }\n\n    // Any examples we never touched are also missing\n    for (++last_example; last_example < nx;  ++last_example) {\n        float w = in_class[last_example];\n        if (w == 0.0) continue;\n        class_missing[last_example] += w;\n        total_missing += w;\n    }\n\n    /* For validation: make sure that each is in exactly one */\n    if (validate) {\n        for (unsigned x = 0;  x < nx;  ++x) {\n            double w_total = class_true[x] + class_false[x] + class_missing[x];\n            double error = in_class[x] - w_total;\n            if (abs(error) > 0.000001) {\n                cerr << \"x = \" << x << endl;\n                cerr << \"orig  = \" << in_class[x] << endl;\n                cerr << \"false = \" << class_false[x] << endl;\n                cerr << \"true  = \" << class_true[x] << endl;\n                cerr << \"miss  = \" << class_missing[x] << endl;\n                cerr << \"total = \" << w_total << endl;\n                cerr << \"error = \" << error << endl;\n                throw Exception(\"split_weights: weights don't add up\");\n            }\n        }\n    }\n}\n\n/// The training code expects weights to be double-indexed, by first example\n/// number and second label, so you can do weights[example][label] to extract\n/// the label.  In the optimization for the binary symmetric case (where we\n/// always have 2 identical weights, one for each label) we have all of the\n/// weights in a single array.  This code adds an extra dimension to the\n/// weights, allowing us to call AddDimension(weights)[example][label] and\n/// have it return weights[example].\nstruct AddDimension {\n    AddDimension(const distribution<float> & vals)\n        : vals(vals)\n    {\n    }\n\n    const distribution<float> & vals;\n\n    const float * operator [] (int n) const { return &vals[n]; };\n};\n\nint get_advance(const AddDimension &)\n{\n    return 0;\n}\n\ntemplate<typename W, typename Z>\nstruct TreeTrainer {\n    Tree & tree;\n    int max_depth;\n    const vector<Feature> & features;\n    int advance;\n    int nl;\n    Feature predicted;\n    int trace;\n    Stump::Update update_alg;\n    std::shared_ptr<const Feature_Space> feature_space;\n    bool validate;\n\n    TreeTrainer(Tree & tree,\n                int max_depth,\n                const vector<Feature> & features,\n                int advance,\n                Feature predicted,\n                int trace,\n                Stump::Update update_alg,\n                std::shared_ptr<const Feature_Space> feature_space,\n                bool validate)\n        : tree(tree), max_depth(max_depth),\n          features(features), advance(advance),\n          predicted(predicted), trace(trace),\n          update_alg(update_alg),\n          feature_space(feature_space),\n          validate(validate)\n    {\n        nl = feature_space->info(predicted).value_count();\n    }\n        \n    \n    typedef Stump_Trainer<W, Z> WeightTrainer;\n\n    typedef No_Trace TrainerTracer;\n    typedef Tree_Accum<W, Z, Stream_Tracer> Accum;\n    typedef Stump_Trainer<W, Z, TrainerTracer> SplitTrainer;\n        \n    void do_branch(Tree::Ptr & ptr,\n                   Thread_Context & context,\n                   const Training_Data & data,\n                   const vector<const float *> & weights,\n                   const distribution<float> & binary_weights,\n                   int advance,\n                   const vector<Feature> & features,\n                   const distribution<float> & new_in_class,\n                   double total_in_class,\n                   int new_depth, int max_depth,\n                   Tree & tree,\n                   MLDB::ThreadPool & tp) const\n    {\n#if 0\n        if (total_in_class > 1024) {\n            // Worth multithreading... do it\n            if (group_to_wait_on == -1) {\n                // Create a new group\n                group_to_wait_on = context.worker().get_group(NO_JOB,\n                                                              \"decision tree\",\n                                                              context.group());\n            }\n            Thread_Context child_context = context.child(group_to_wait_on);\n\n            Train_Recursive_Job job(ptr, this, child_context, data, weights,\n                                    advance,\n                                    features, new_in_class, new_depth, max_depth,\n                                    tree);\n\n            context.worker().add(job, \"train decision tree branch\",\n                                 child_context.group());\n        }\n#else\n        if (false) ;\n#endif\n        else if (total_in_class > 0.0)\n            ptr = this->train(context, data, weights, new_in_class, binary_weights,\n                              new_depth);\n        else {\n            // Leaf only\n            ptr = tree.new_leaf();\n            fillin_leaf(*ptr.leaf(), data, predicted, weights,\n                        advance, new_in_class, update_alg, 0.0);\n        }\n    }\n\n    // This structure needs to be defererenceable and incrementable, and always\n    // return 1 when dereferenced.  It's like an iterator into an infinite array\n    // of ones.\n    struct AlwaysOne {\n        float operator * () const { return 1.0f; }\n        void operator ++ () {}\n    };\n\n    Tree::Ptr\n    train(Thread_Context & context,\n          const Training_Data & data,\n          const std::vector<const float *> & weights,\n          const distribution<float> & in_class,\n          const distribution<float> & binary_weights,\n          int depth) const\n    {\n        bool debug = false;\n\n#if 0\n        int numNonZero = 0;\n        for (unsigned i = 0;  i <  in_class.size();  ++i) {\n            if (weights[i][0] * in_class[i] != 0)\n                ++numNonZero;\n            if (i < 10 && false) {\n                cerr << i << \" p \" << weights[i] << \" weight \" << weights[i][0]\n                     << \" in_class \" << in_class[i] << \" total \" << weights[i][0] * in_class[i] << endl;\n            }\n        }\n        //cerr << \"in class: \" << numNonZero << \" of \" << in_class.size() << endl;\n#endif    \n\n#if 0\n        if (numNonZero * 20 < in_class.size()) {\n            cerr << \"warning: extremely sparse examples: \" << numNonZero << \" of \"\n                 << in_class.size() << endl;\n        }\n#endif    \n\n        if (depth > 100 && max_depth == -1)\n            throw Exception(\"Decision_Tree_Generator::train_recursive(): \"\n                            \"depth of 100 reached\");\n        if (debug)\n            cerr << \"train_recursive: depth \" << depth << endl;\n\n        double total_weight = in_class.total();\n\n\n#if 0\n        if (debug) {\n            cerr << \"predicted = \" << predicted << endl;\n            cerr << \"fs = \" << data.feature_space()->print() << endl;\n            cerr << \"data[0] = \" << data.feature_space()->print(data[0]) << endl;\n            cerr << \"data.example_count() = \" << data.example_count() << endl;\n\n            cerr << \"data.label_count(predicted) = \" << data.label_count(predicted)\n                 << endl;\n            cerr << \"data.label_count(model.predicted()) = \"\n                 << data.label_count(model.predicted())\n                 << endl;\n        }\n#endif\n\n        W default_w(nl);\n\n        /* Check for zero impurity, and return a leaf if we have it. */\n        double class_weights[nl];\n\n        // What would we have as a leaf if we were to stop splitting here?\n        Tree::Leaf leaf;\n        leaf.examples = total_weight;\n        double epsilon = xdiv<double>(1.0, total_weight);\n\n        /* Use the stump trainer to accumulate for us. */\n        WeightTrainer weightTrainer;\n        \n        if (binary_weights.empty()) {\n            default_w = weightTrainer.calc_default_w(data, predicted, in_class, weights, advance);\n        }\n        else default_w = weightTrainer.calc_default_w(data, predicted, in_class, AddDimension(binary_weights),\n                                                      advance);\n\n        // Calculate how many classes (labels) have non-zero weight.  We need at least\n        // 2 distinct labels for training to make sense; otherwise we bail out\n\n        double maxClassWeight = 0.0;\n        double totalClassWeight = 0.0;\n        int numNonZeroClasses = 0;\n        for (unsigned l = 0;  l < nl;  ++l) {\n            double w = 0.0;  // weight for the label class\n            for (unsigned j = 0;  j < 3;  ++j)\n                w += default_w(l, j, true);\n            class_weights[l] = w;\n            maxClassWeight = std::max(maxClassWeight, w);\n            totalClassWeight += w;\n            if (w != 0)\n                numNonZeroClasses += 1;\n        }\n        \n        // Fill in the prediction that this would have made if we stopped\n        // training here.  This is used, notably, if we prune the tree and\n        // for explanations.\n        get_probs(leaf.pred, default_w, update_alg, epsilon);\n\n        // Look for early stopping conditions:\n        if (maxClassWeight == 1.0       // minimum impurity; one per class\n            || depth == max_depth       // reached maximum depth\n            || numNonZeroClasses <= 1   // only one non-zero weighted label left\n            || total_weight < 1.0       // split up finer than one example\n            || totalClassWeight == 0.0  // weights too small to count\n            || in_class.size() == 1     // only one example\n            || false) {\n            Tree::Leaf * result = tree.new_leaf();\n            *result = leaf;\n            return result;\n        }\n    \n        int num_non_zero = std::count_if(in_class.begin(), in_class.end(), [] (auto f) { return f > 0.0; });\n    \n        if (debug) {\n            cerr << \"in_class.size() = \" << in_class.size() << \" num_non_zero = \"\n                 << num_non_zero << \" total_weight = \" << total_weight\n                 << endl;\n        }\n\n        if (num_non_zero * COMPACT_SPARSENESS_RATIO < in_class.size()) {\n            Training_Data new_data(data.feature_space());\n            distribution<float> new_in_class;\n            distribution<float> new_binary_weights;\n            vector<const float *> new_weights;\n\n            compact_dataset(data, in_class, weights, binary_weights, num_non_zero,\n                            new_data, new_in_class,\n                            new_weights,\n                            new_binary_weights,\n                            features, predicted);\n\n            /* Restart, with the new training data. */\n            return train(context, new_data, new_weights,\n                         new_in_class, new_binary_weights, depth);\n        }\n        \n        Split split;\n        float best_z = 0.0;\n\n        Accum accum(*feature_space, nl, trace);\n        SplitTrainer splitTrainer;\n    \n        if (binary_weights.empty())\n            splitTrainer.test_all\n                (context, default_w, features, data, predicted,\n                 weights, in_class, accum, advance);\n        else \n            splitTrainer.test_all\n                (context, default_w, features, data, predicted,\n                 AddDimension(binary_weights), in_class, accum, advance);\n        \n        split = accum.split();\n        best_z = accum.z();\n\n        if (split.feature() == MISSING_FEATURE) {\n            Tree::Leaf * result = tree.new_leaf();\n            *result = leaf;\n            return result;\n        }\n\n        if (debug) {\n            cerr << \" decision tree training: best split is \"\n                 << split.print(*feature_space) << endl;\n            cerr << \"z = \" << best_z << endl;\n        }\n\n        // We used to not allow the decision tree to learn a perfect split.  Now we allow it\n        // but we make sure that the next level down only leaf nodes will be created as there\n        // will be only one label.\n        if (best_z == 0.0 && false) {\n            // No impurity at all\n            Tree::Leaf * result = tree.new_leaf();\n            *result = leaf;\n            return result;\n        }\n    \n        /* Split these examples based upon what the split said. */\n        distribution<float> class_true;\n        distribution<float> class_false;\n        distribution<float> class_missing;\n        double total_true;\n        double total_false;\n        double total_missing;\n\n        //boost::timer::cpu_timer timer;\n        split_dataset(data, split, in_class,\n                      class_true, class_false, class_missing,\n                      total_true, total_false, total_missing,\n                      validate);\n\n        int numClasses = (total_true != 0) + (total_false != 0) + (total_missing != 0);\n\n        // If we classify everything into one class, then we can't split any\n        // further.\n        if (numClasses < 2) {\n            Tree::Leaf * result = tree.new_leaf();\n            *result = leaf;\n            return result;\n        }\n\n        if (debug) {\n            //cerr << timer.elapsed().wall << \"s split\" << endl;\n        \n            cerr << \" totals: true \" << total_true << \" false \" << total_false\n                 << \" missing \" << total_missing << endl;\n        \n            cerr << \" totals2: true \" << class_true.total()\n                 << \" false \" << class_false.total()\n                 << \" missing \" << class_missing.total() << endl;\n        }\n\n        Tree::Node * node = tree.new_node();\n        node->split = split;\n        node->z = best_z;\n        node->examples = total_weight;\n        node->pred = leaf.pred;\n\n        MLDB::ThreadPool tp;\n        \n        do_branch(node->child_true,\n                  context, data, weights, binary_weights, advance, features,\n                  class_true, total_true, depth + 1, max_depth,\n                  tree, tp);\n\n        do_branch(node->child_false,\n                  context, data, weights, binary_weights, advance, features,\n                  class_false, total_false, depth + 1, max_depth,\n                  tree, tp);\n    \n        do_branch(node->child_missing,\n                  context, data, weights, binary_weights, advance, features,\n                  class_missing, total_missing, depth + 1, max_depth,\n                  tree, tp);\n\n        tp.waitForAll();\n        \n        return node;\n    }\n};\n\n} // file scope\n\nstruct Decision_Tree_Generator::Train_Recursive_Job {\n\n    Tree::Ptr & ptr;\n    const Decision_Tree_Generator * generator;\n    Thread_Context context;\n    const Training_Data & data;\n    const vector<const float *> & weights;\n    int advance;\n    const vector<Feature> & features;\n    const distribution<float> & in_class;\n    int depth;\n    int max_depth;\n    Tree & tree;\n\n    Train_Recursive_Job(Tree::Ptr & ptr,\n                        const Decision_Tree_Generator * generator,\n                        const Thread_Context & context,\n                        const Training_Data & data,\n                        const vector<const float *> & weights,\n                        int advance,\n                        const vector<Feature> & features,\n                        const distribution<float> & in_class,\n                        int depth, int max_depth,\n                        Tree & tree)\n        : ptr(ptr), generator(generator), context(context), data(data),\n          weights(weights), advance(advance), features(features),\n          in_class(in_class), depth(depth), max_depth(max_depth),\n          tree(tree)\n    {\n    }\n\n    void operator () ()\n    {\n        ptr = generator->train_recursive(context, data, weights, advance,\n                                         features, in_class, depth,\n                                         max_depth, tree);\n    }\n};\n\nTree::Ptr\nDecision_Tree_Generator::\ntrain_recursive(Thread_Context & context,\n                const Training_Data & data,\n                const vector<const float *> & weights,\n                int advance,\n                const vector<Feature> & features,\n                const distribution<float> & in_class,\n                int depth, int max_depth,\n                Tree & tree) const\n{\n    if (advance == 0) {\n        // binary symmetric, we can use an optimized version\n        typedef W_binsym W;\n        typedef Z_binsym Z;\n\n        // Pre-calculate a more memory friendly version of in_class\n        distribution<float> binary_weights(in_class.size(), 0.0);\n        for (unsigned i = 0;  i < in_class.size();  ++i) {\n            binary_weights[i] = weights[i][0];\n        }\n\n        TreeTrainer<W, Z> trainer(tree, max_depth, features, advance,\n                                  predicted, trace, update_alg, feature_space,\n                                  validate);\n        return trainer.train(context, data, weights, in_class, binary_weights, depth);\n    }\n    else {\n        // generalized version\n        typedef W_normal W;\n        typedef Z_normal Z;\n        TreeTrainer<W, Z> trainer(tree, max_depth, features, advance,\n                                  predicted, trace, update_alg, feature_space,\n                                  validate);\n        return trainer.train(context, data, weights, in_class, {} /* binary weights */, depth);\n    }\n}\n\nTree::Ptr\nDecision_Tree_Generator::\ntrain_recursive_regression(Thread_Context & context,\n                           const Training_Data & data,\n                           const vector<float> & weights,\n                           const vector<Feature> & features_,\n                           const distribution<float> & in_class,\n                           int depth, int max_depth,\n                           Tree & tree) const\n{\n    if (depth > 100 && max_depth == -1)\n        throw Exception(\"Decision_Tree_Generator::train_recursive_regression(): \"\n                        \"depth of 100 reached\");\n\n    size_t nx = data.example_count();\n\n    Tree::Leaf leaf;\n    fillin_leaf_regression(leaf, data, model.predicted(), weights, in_class);\n\n    const vector<Label> & labels = data.index().labels(model.predicted());\n\n    /* Check for all of the labels in the class having the same value. */\n    {\n        float val_found = NAN;\n        bool all_same = true;\n        for (unsigned x = 0;  x < nx;  ++x) {\n            if (in_class[x] == 0.0) continue;  // not in our class\n            if (weights[x] == 0.0) continue;   // no weight; doesn't count\n            if (isnan(val_found)) val_found = labels[x].value();\n            else if (val_found != labels[x].value()) {\n                all_same = false;\n                break;\n            }\n        }\n\n        if (all_same) {\n            Tree::Leaf * result = tree.new_leaf();\n            *result = leaf;\n            return result;\n        }\n    }\n        \n    double total_weight = in_class.total();\n\n    if (depth == max_depth || total_weight < 1.0) {\n        Tree::Leaf * result = tree.new_leaf();\n        *result = leaf;\n        return result;\n    }\n    \n    int num_non_zero = std::count_if(in_class.begin(), in_class.end(), [] (auto f) { return f > 0.0; });\n\n    //cerr << \"in_class.size() = \" << in_class.size() << \" num_non_zero = \"\n    //     << num_non_zero << \" total_weight = \" << total_weight\n    //     << endl;\n\n    if (num_non_zero * 16 < in_class.size()) {\n        Training_Data new_data(data.feature_space());\n        distribution<float> new_in_class;\n        vector<float> new_weights;\n        distribution<float> new_binary_weights;\n\n        compact_dataset(data, in_class, weights, {} /* binary weights */, num_non_zero,\n                        new_data, new_in_class, new_weights, new_binary_weights, features_,\n                        model.predicted());\n\n        /* Restart, with the new training data. */\n        return train_recursive_regression\n            (context, new_data, new_weights, features_, new_in_class, depth,\n             max_depth, tree);\n    }\n    \n    //cerr << \"training decision tree with total weight \"\n    //     << total_weight << \" at depth \" << depth << endl;\n    \n    typedef W_regress W;\n    typedef Z_regress Z;\n    \n    typedef Tree_Accum<W, Z, Stream_Tracer> Accum;\n    //typedef Tree_Accum<W, Z> Accum;\n    typedef Stump_Trainer<W, Z> Trainer;\n    \n    Accum accum(*model.feature_space(), nl, trace);\n    Trainer trainer;\n    \n    vector<Feature> features = features_;\n    \n    /* We need it in a fixed array like this. */\n    boost::multi_array<float, 2> weights2(boost::extents[weights.size()][1]);\n    std::copy(weights.begin(), weights.end(), weights2.data());\n    trainer.test_all_and_sort(features, data, model.predicted(), weights2,\n                              in_class, accum);\n    \n    //cerr << \"z = \" << accum.best_z << endl;\n    //cerr << \"w = \" << endl << accum.best_w.print() << endl;\n\n    if (accum.best_z == 0.0 || accum.best_feature == MISSING_FEATURE) {\n        Tree::Leaf * result = tree.new_leaf();\n        *result = leaf;\n        return result;\n    }\n\n    distribution<float> class_true;\n    distribution<float> class_false;\n    distribution<float> class_missing;\n\n    double total_true;\n    double total_false;\n    double total_missing;\n\n    //boost::timer::cpu_timer timer;\n    split_dataset(data, accum.split(), in_class,\n                  class_true, class_false, class_missing,\n                  total_true, total_false, total_missing,\n                  validate);\n\n    //cerr << timer.elapsed().wall << \"s split\" << endl;\n\n    //cerr << \" totals: true \" << total_true << \" false \" << total_false\n    //     << \" missing \" << total_missing << endl;\n\n    Tree::Node * node = tree.new_node();\n    node->split = accum.split();\n    node->z = accum.z();\n    node->examples = total_weight;\n    node->pred = leaf.pred;\n\n    node->child_true\n        = train_recursive_regression(context, data, weights, features,\n                                     class_true, depth + 1, max_depth,\n                                     tree);\n    node->child_false\n        = train_recursive_regression(context, data, weights, features,\n                                     class_false, depth + 1, max_depth,\n                                     tree); \n    node->child_missing\n        = train_recursive_regression(context, data, weights, features,\n                                     class_missing, depth + 1, max_depth,\n                                     tree);\n    \n    return node;\n}\n\n\n/*****************************************************************************/\n/* REGISTRATION                                                              */\n/*****************************************************************************/\n\nnamespace {\n\nRegister_Factory<Classifier_Generator, Decision_Tree_Generator>\n    DECISION_TREE_REGISTER(\"decision_tree\");\n\n} // file scope\n\n} // namespace ML\n", "meta": {"hexsha": "617f85840cb31657df9643917d208ec57920e47a", "size": 45017, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/jml/decision_tree_generator.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/jml/decision_tree_generator.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/jml/decision_tree_generator.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": 33.9494720965, "max_line_length": 110, "alphanum_fraction": 0.5494368794, "num_tokens": 9953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.0244230906754343, "lm_q1q2_score": 0.008514991753810021}}
{"text": "/**********************************************************************************/\n/* This file is part of spla project                                              */\n/* https://github.com/JetBrains-Research/spla                                     */\n/**********************************************************************************/\n/* MIT License                                                                    */\n/*                                                                                */\n/* Copyright (c) 2021 JetBrains-Research                                          */\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 SPLA_SPLAREDUCE_HPP\n#define SPLA_SPLAREDUCE_HPP\n\n#include <boost/compute/algorithm/reduce.hpp>\n\n#include <compute/metautil/SplaMetaUtil.hpp>\n\n\nnamespace spla {\n\n    namespace detail {\n\n        inline void InplaceReduce(const boost::compute::vector<unsigned char> &values,\n                                  std::size_t valueByteSize,\n                                  const std::string &functionBody,\n                                  boost::compute::command_queue &queue) {\n            std::size_t inputSize = values.size() / valueByteSize;\n            if (inputSize < 2) {\n                return;\n            }\n\n            const compute::context &context = queue.get_context();\n\n            const std::size_t blockSize = 64;\n            const std::size_t valuesPerThread = 8;\n            std::size_t blockCount = inputSize / (blockSize * valuesPerThread);\n            if (blockCount * blockSize * valuesPerThread != inputSize)\n                blockCount++;\n\n            compute::vector<unsigned char> output(blockCount * valueByteSize, context);\n\n            compute::detail::meta_kernel k(\"inplace_reduce\");\n            size_t inputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, \"input\");\n            size_t inputSizeArg = k.add_arg<const uint_>(\"input_size\");\n            size_t outputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, \"output\");\n            size_t scratchArg = k.add_arg<unsigned char *>(compute::memory_object::local_memory, \"scratch\");\n\n            ReduceOp reduceOp1(k, \"inplace_reduce_reduce_1\", functionBody, valueByteSize,\n                               Visibility::Unspecified,\n                               Visibility::Global,\n                               Visibility::Unspecified);\n\n            ReduceOp reduceOp2(k, \"inplace_reduce_reduce_2\", functionBody, valueByteSize,\n                               Visibility::Local,\n                               Visibility::Local,\n                               Visibility::Unspecified);\n\n            k << \"const uint gid = get_global_id(0);\\n\"\n              << \"const uint lid = get_local_id(0);\\n\"\n              << \"const uint values_per_thread = \" << uint_(valuesPerThread) << \";\\n\"\n              << \"const uint index = gid * values_per_thread;\\n\"\n              << \"if(index < input_size){\\n\"\n              << DeclareVal{\"sum\", valueByteSize} << \";\\n\"\n              << AssignVal{ValVar{\"sum\"}, ValArrItem{\"input\", \"index\", valueByteSize}, valueByteSize} << \";\\n\"\n              << \"for(uint i = 1; i < values_per_thread && (index + i) < input_size; i++) {\\n\"\n              << reduceOp1.Apply(ValVar{\"sum\"}, ValArrItem{\"input\", \"index+i\", valueByteSize}, ValVar{\"sum\"}) << \";\\n\"\n              << \"}\\n\"\n              << AssignVal{ValArrItem(\"scratch\", \"lid\", valueByteSize), ValVar(\"sum\"), valueByteSize} << \";\\n\"\n              << \"}\\n\"\n              << \"for(uint i = 1; i < get_local_size(0); i <<= 1){\\n\"\n              << \"    barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n              << \"    uint mask = (i << 1) - 1;\\n\"\n              << \"    uint next_index = (gid + i) * values_per_thread;\\n\"\n                 \"    if((lid & mask) == 0 && next_index < input_size){\\n\"\n              << reduceOp2.Apply(ValArrItem(\"scratch\", \"lid\", valueByteSize), ValArrItem(\"scratch\", \"lid+i\", valueByteSize), ValArrItem(\"scratch\", \"lid\", valueByteSize))\n              << \"    }\\n\"\n              << \"}\\n\"\n              << \"if(lid == 0){\\n\"\n              << AssignVal{ValArrItem(\"output\", \"get_group_id(0)\", valueByteSize), ValArrItem(\"scratch\", \"0\", valueByteSize), valueByteSize} << \";\\n\"\n              << \"}\\n\";\n\n            const compute::buffer *inputBuffer = &values.get_buffer();\n            const compute::buffer *outputBuffer = &output.get_buffer();\n\n            compute::kernel kernel = k.compile(context);\n\n            while (inputSize > 1) {\n                kernel.set_arg(inputArg, *inputBuffer);\n                kernel.set_arg(inputSizeArg, static_cast<uint_>(inputSize));\n                kernel.set_arg(outputArg, *outputBuffer);\n                kernel.set_arg(scratchArg, compute::local_buffer<unsigned char>(blockSize * valueByteSize));\n\n                queue.enqueue_1d_range_kernel(kernel,\n                                              0,\n                                              blockCount * blockSize,\n                                              blockSize);\n\n                inputSize = static_cast<std::size_t>(std::ceil(static_cast<float>(inputSize) / (blockSize * valuesPerThread)));\n\n                blockCount = inputSize / (blockSize * valuesPerThread);\n                if (blockCount * blockSize * valuesPerThread != inputSize)\n                    blockCount++;\n\n                std::swap(inputBuffer, outputBuffer);\n            }\n\n            if (inputBuffer != &values.get_buffer()) {\n                ::boost::compute::copy(output.begin(),\n                                       output.begin() + static_cast<std::ptrdiff_t>(valueByteSize),\n                                       values.begin(),\n                                       queue);\n            }\n        }\n\n        inline std::size_t Reduce(const boost::compute::vector<unsigned char> &values,\n                                  std::size_t valueByteSize,\n                                  boost::compute::vector<unsigned char> &result,\n                                  std::size_t blockSize,\n                                  const std::string &functionBody,\n                                  boost::compute::command_queue &queue) {\n            using namespace boost;\n\n            const compute::context &context = queue.get_context();\n            const std::size_t nValues = values.size() / valueByteSize;\n            const std::size_t blockCount = nValues / 2 / blockSize;\n            const auto totalBlockCount = static_cast<std::size_t>(\n                    std::ceil(static_cast<float>(nValues) / 2.f / static_cast<float>(blockSize)));\n\n            if (blockCount != 0) {\n                compute::detail::meta_kernel k(\"block_reduce\");\n                std::size_t outputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, \"output\");\n                std::size_t blockArg = k.add_arg<unsigned char *>(compute::memory_object::local_memory, \"block\");\n\n                ReduceOp reduceOpGlobal(k, \"block_reduce_reduce_global\", functionBody, valueByteSize,\n                                        Visibility::Global,\n                                        Visibility::Global,\n                                        Visibility::Local);\n                ReduceOp reduceOpLocal(k, \"block_reduce_reduce_local\", functionBody, valueByteSize,\n                                       Visibility::Local,\n                                       Visibility::Local,\n                                       Visibility::Unspecified);\n\n                k << \"const uint gid = get_global_id(0);\\n\"\n                  << \"const uint lid = get_local_id(0);\\n\"\n                  << reduceOpGlobal.Apply(ValArrItem(values, \"gid*2+0\", valueByteSize, k),\n                                          ValArrItem(values, \"gid*2+1\", valueByteSize, k),\n                                          ValArrItem(\"block\", \"lid\", valueByteSize))\n                  << \"for(uint i = 1; i < \" << uint_(blockSize) << \"; i <<= 1){\\n\"\n                  << \"    barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n                  << \"    uint mask = (i << 1) - 1;\\n\"\n                  << \"    if((lid & mask) == 0){\\n\"\n                  << reduceOpLocal.Apply(ValArrItem(\"block\", \"lid\", valueByteSize),\n                                         ValArrItem(\"block\", \"lid+i\", valueByteSize),\n                                         ValArrItem(\"block\", \"lid\", valueByteSize))\n                  << \"    }\\n\"\n                  << \"}\\n\"\n                  << \"if(lid == 0)\\n\"\n                  << AssignVal{ValArrItem{\"output\", \"get_group_id(0)\", valueByteSize},\n                               ValArrItem{\"block\", \"0\", valueByteSize},\n                               valueByteSize}\n                  << \";\\n\";\n\n                compute::kernel kernel = k.compile(context);\n                kernel.set_arg(outputArg, result.get_buffer());\n                kernel.set_arg(blockArg, compute::local_buffer<unsigned char>(blockSize * valueByteSize));\n\n                queue.enqueue_1d_range_kernel(kernel,\n                                              0,\n                                              blockCount * blockSize,\n                                              blockSize);\n            }\n\n            // serially reduce any leftovers\n            if (blockCount * blockSize * 2 < nValues) {\n                std::size_t lastBlockStart = blockCount * blockSize * 2;\n\n                compute::detail::meta_kernel k(\"extra_serial_reduce\");\n                const std::size_t countArg = k.add_arg<uint_>(\"count\");\n                const std::size_t offsetArg = k.add_arg<uint_>(\"offset\");\n                const std::size_t outputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, \"output\");\n                const std::size_t outputOffsetArg = k.add_arg<uint_>(\"output_offset\");\n\n                ReduceOp reduceOp(k, \"leftover_reduce_reduce\", functionBody, valueByteSize,\n                                  Visibility::Unspecified,\n                                  Visibility::Global,\n                                  Visibility::Unspecified);\n\n                k << DeclareVal{\"result\", valueByteSize} << \";\\n\"\n                  << AssignVal{ValVar{\"result\"}, ValArrItem{values, \"offset\", valueByteSize, k}, valueByteSize}\n                  << \"for(uint i = offset + 1; i < count; i++)\\n\"\n                  << reduceOp.Apply(ValVar{\"result\"},\n                                    ValArrItem(values, \"i\", valueByteSize, k),\n                                    ValVar{\"result\"})\n                  << AssignVal{ValArrItem{\"output\", \"output_offset\", valueByteSize},\n                               ValVar{\"result\"},\n                               valueByteSize}\n                  << \";\\n\";\n\n                compute::kernel kernel = k.compile(context);\n                kernel.set_arg(countArg, static_cast<uint_>(nValues));\n                kernel.set_arg(offsetArg, static_cast<uint_>(lastBlockStart));\n                kernel.set_arg(outputArg, result.get_buffer());\n                kernel.set_arg(outputOffsetArg, static_cast<uint_>(blockCount));\n\n                queue.enqueue_task(kernel);\n            }\n\n            return totalBlockCount;\n        }\n\n        inline boost::compute::vector<unsigned char> BlockReduce(const boost::compute::vector<unsigned char> &values,\n                                                                 std::size_t valueByteSize,\n                                                                 std::size_t blockSize,\n                                                                 const std::string &functionBody,\n                                                                 boost::compute::command_queue &queue) {\n            using namespace boost;\n\n            const compute::context &ctx = queue.get_context();\n            const std::size_t nValues = values.size() / valueByteSize;\n\n            auto totalBlockCount = static_cast<std::size_t>(\n                    std::ceil(static_cast<float>(nValues) / 2.f / static_cast<float>(blockSize)));\n            compute::vector<unsigned char> resultVector(totalBlockCount * valueByteSize, ctx);\n\n            Reduce(values, valueByteSize, resultVector, blockSize, functionBody, queue);\n\n            return resultVector;\n        }\n\n        inline void GenericReduce(const boost::compute::vector<unsigned char> &values,\n                                  std::size_t valueByteSize,\n                                  boost::compute::vector<unsigned char> &result,\n                                  const std::string &functionBody,\n                                  boost::compute::command_queue &queue) {\n            using namespace boost;\n\n            const std::size_t blockSize = 256;\n\n            compute::vector<unsigned char> results = BlockReduce(values, valueByteSize, blockSize, functionBody, queue);\n\n            if (results.size() / valueByteSize > 1) {\n                InplaceReduce(results,\n                              valueByteSize,\n                              functionBody,\n                              queue);\n            }\n\n            compute::copy_n(results.begin(), valueByteSize, result.begin(), queue);\n        }\n\n    }// namespace detail\n\n    inline boost::compute::vector<unsigned char> Reduce(const boost::compute::vector<unsigned char> &values,\n                                                        std::size_t valueByteSize,\n                                                        const std::string &reduceOp,\n                                                        boost::compute::command_queue &queue) {\n        using namespace boost;\n\n        const compute::context &ctx = queue.get_context();\n        boost::compute::vector<unsigned char> result(valueByteSize, ctx);\n        compute::fill(result.begin(), result.end(), 0, queue);\n\n        detail::GenericReduce(values, valueByteSize, result, reduceOp, queue);\n\n        return result;\n    }\n\n}// namespace spla\n\n#endif//SPLA_SPLAREDUCE_HPP\n", "meta": {"hexsha": "4500cc1136488a297460a394396f6ea374b79800", "size": 15474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/compute/SplaReduce.hpp", "max_stars_repo_name": "Glebanister/spla", "max_stars_repo_head_hexsha": "6951af369e359827729fd12b08f5df0ba3dac8ef", "max_stars_repo_licenses": ["MIT"], "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/compute/SplaReduce.hpp", "max_issues_repo_name": "Glebanister/spla", "max_issues_repo_head_hexsha": "6951af369e359827729fd12b08f5df0ba3dac8ef", "max_issues_repo_licenses": ["MIT"], "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/compute/SplaReduce.hpp", "max_forks_repo_name": "Glebanister/spla", "max_forks_repo_head_hexsha": "6951af369e359827729fd12b08f5df0ba3dac8ef", "max_forks_repo_licenses": ["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.9163763066, "max_line_length": 169, "alphanum_fraction": 0.4895308259, "num_tokens": 2923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.02368946888690692, "lm_q1q2_score": 0.008513145735840139}}
{"text": "// Copyright 2020 Dow, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n\n#include \"Analysis.h\"\n\n#include <algorithm>\n#include <chrono>\n#include <iostream>\n#include <iterator>\n#include <filesystem>\n#include <fstream>\n#include <memory>\n#include <type_traits>\n#include <string>\n#include <utility>\n#include <vector>\n\n// TODO: replace Boost.Accumulators with MKL\n// https://software.intel.com/en-us/mkl-ssnotes-computing-quantiles-for-streaming-data\n\n#include <boost/algorithm/string.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/p_square_quantile.hpp>\n#include <boost/accumulators/statistics/rolling_count.hpp>\n#include <boost/accumulators/statistics/rolling_mean.hpp>\n#include <boost/accumulators/statistics/rolling_sum.hpp>\n#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>\n#include <boost/accumulators/statistics/density.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <fmt/format.h>\n\nnamespace ncpost {\n\n// Utility function to determine if all vectors have equal length.\ntemplate <typename... Args>\nbool equal_length(const std::vector<Args>&... args) {\n    if constexpr (sizeof...(Args) == 0) {\n        return true;\n    } else {\n        return [](const auto& v0, const auto&... rest) {\n            return ((v0.size() == rest.size()) && ...);\n        }(args...);\n    }\n}\n\n// EXPECTED DIMENSIONS:\n//   rec, arc, net, grp, ave, time, strlen\n//\n// EXPECTED VARIABLES:\n//   double x(rec)\n//   double y(rec)\n//   double zelev(rec)\n//   double zhill(rec)\n//   double zflag(rec)\n//   int rec(rec)\n//   int arc(rec)\n//   char arcid(arc, strlen)\n//   int net(rec)\n//   char netid(net, strlen)\n//   char grp(grp, strlen)\n//   int ave(ave)\n//   int time(time)\n//   byte clmsg(time)\n\nanalysis::analysis(const std::string& filepath)\n    : file_(filepath, ncpp::file::read), ds_(file_)\n{\n    static auto fn = [](std::size_t){};\n    progressfn_ = fn;\n}\n\nstd::string analysis::library_version()\n{\n    return ncpp::library_version();\n}\n\nstd::string analysis::model_version() const\n{\n    std::string source_string;\n    if (ds_.atts.contains(\"source\"))\n        ds_.atts[\"source\"].read(source_string);\n    return source_string;\n}\n\nstd::string analysis::model_options() const\n{\n    std::string options_string;\n    if (ds_.atts.contains(\"options\"))\n        ds_.atts[\"options\"].read(options_string);\n    return options_string;\n}\n\nstd::string analysis::title() const\n{\n    std::string title_string;\n    if (ds_.atts.contains(\"title\"))\n        ds_.atts[\"title\"].read(title_string);\n    return title_string;\n}\n\nstd::vector<output_type_t> analysis::output_types() const\n{\n    std::vector<output_type_t> result;\n    std::array<std::string, 4> vars{\"conc\", \"depos\", \"ddep\", \"wdep\"};\n    for (const auto& var : vars) {\n        if (ds_.vars.contains(var)) {\n            output_type_t item;\n            item.name = var;\n            ds_.vars[var].atts[\"units\"].read(item.units);\n            boost::algorithm::to_lower(item.units);\n            result.push_back(item);\n        }\n    }\n    return result;\n}\n\nstd::vector<int> analysis::averaging_periods() const\n{\n    if (ds_.vars.contains(\"ave\"))\n        return ds_.vars[\"ave\"].values<int>();\n    return {};\n}\n\nstd::vector<std::string> analysis::source_groups() const\n{\n    if (ds_.vars.contains(\"grp\"))\n        return ds_.vars[\"grp\"].values<std::string>();\n    return {};\n}\n\nstd::vector<std::string> analysis::receptor_arcids() const\n{\n    if (ds_.vars.contains(\"arcid\"))\n        return ds_.vars[\"arcid\"].values<std::string>();\n    return {};\n}\n\nstd::vector<std::string> analysis::receptor_netids() const\n{\n    if (ds_.vars.contains(\"netid\"))\n        return ds_.vars[\"netid\"].values<std::string>();\n    return {};\n}\n\nstd::size_t analysis::receptor_count() const\n{\n    if (ds_.vars.contains(\"rec\"))\n        return ds_.vars[\"rec\"].size();\n    return 0;\n}\n\nstd::vector<receptor_t> analysis::receptors() const\n{\n    if (receptor_count() == 0)\n        return {};\n\n    const auto recs  = ds_.vars[\"rec\"].values<int>();\n    const auto x     = ds_.vars[\"x\"].values<double>();\n    const auto y     = ds_.vars[\"y\"].values<double>();\n    const auto zelev = ds_.vars[\"zelev\"].values<double>();\n    const auto zhill = ds_.vars[\"zhill\"].values<double>();\n    const auto zflag = ds_.vars[\"zflag\"].values<double>();\n\n    if (!equal_length(recs, x, y, zelev, zhill, zflag))\n        throw std::out_of_range(\"Receptor coordinate length mismatch.\");\n\n    const auto arcids = receptor_arcids();\n    const auto netids = receptor_netids();\n\n    std::vector<int> arcs;\n    if (!arcids.empty() && ds_.vars.contains(\"arc\") && ds_.vars[\"arc\"].size() == recs.size()) {\n        arcs = ds_.vars[\"arc\"].values<int>();\n    }\n\n    std::vector<int> nets;\n    if (!netids.empty() && ds_.vars.contains(\"net\") && ds_.vars[\"net\"].size() == recs.size()) {\n        nets = ds_.vars[\"net\"].values<int>();\n    }\n\n    std::vector<receptor_t> result;\n\n    result.reserve(recs.size());\n    for (std::size_t i = 0; i < recs.size(); ++i)\n    {\n        std::string arcid;\n        std::string netid;\n\n        if (!arcs.empty() && arcs[i] > 0)\n            arcid = arcids.at(static_cast<std::size_t>(arcs[i] - 1));\n        if (!nets.empty() && nets[i] > 0)\n            netid = netids.at(static_cast<std::size_t>(nets[i] - 1));\n\n        result.emplace_back(receptor_t{ recs[i], x[i], y[i], zelev[i], zhill[i], zflag[i], arcid, netid });\n    }\n\n    return result;\n}\n\nstd::size_t analysis::time_step_count() const\n{\n    if (ds_.vars.contains(\"time\"))\n        return ds_.vars[\"time\"].size();\n    return 0;\n}\n\nstd::vector<time_step_t> analysis::time_steps() const\n{\n    if (time_step_count() == 0)\n        return {};\n\n    auto time = ds_.vars[\"time\"].values<date::sys_seconds>();\n\n    std::vector<unsigned char> clmsg;\n    if (ds_.vars.contains(\"clmsg\"))\n        clmsg = ds_.vars[\"clmsg\"].values<unsigned char>();\n\n    std::vector<time_step_t> result;\n    result.reserve(time.size());\n    for (std::size_t i = 0; i < time.size(); ++i) {\n        unsigned char iclmsg = clmsg.empty() ? 0xff : clmsg[i];\n        result.emplace_back(time_step_t{ time[i], iclmsg });\n    }\n\n    return result;\n}\n\nnamespace accumulators {\n\nnamespace ba = boost::accumulators;\n\nstruct epa_rolling_mean\n{\n    using rmacc_t = ba::accumulator_set<double, ba::stats<ba::tag::rolling_mean>>;\n    using rsacc_t = ba::accumulator_set<double, ba::stats<ba::tag::rolling_sum, ba::tag::rolling_count>>;\n    using maxacc_t = ba::accumulator_set<double, ba::features<ba::tag::max>>;\n\n    epa_rolling_mean(int ave, int hours)\n        : ave_(ave), value_(0),\n          rsacc1_(rsacc_t(ba::tag::rolling_window::window_size = hours / ave)),\n          rsacc2_(rsacc_t(ba::tag::rolling_window::window_size = hours / ave)),\n          rmacc_(rmacc_t(ba::tag::rolling_window::window_size = hours / ave))\n    {\n        // This should evaluate true for any short-term averaging periods:\n        // (1, 2, 3, 4, 6, 8, 12, 24)\n        if (hours % ave != 0)\n            throw std::runtime_error(\"Invalid averaging period.\");\n    }\n\n    void operator()(double val, unsigned char cmflag)\n    {\n        if (ave_ == 1) {\n            // Apply EPA averaging policy for 1 hour averaging period.\n            double cm = (cmflag == 0) ? 0 : 1;\n            rsacc1_(val);\n            rsacc2_(cm);\n\n            // Current number of elements in the rolling window.\n            double n = static_cast<double>(ba::rolling_count(rsacc1_));\n\n            if (n <= 24) {\n                // Short-term average. See SUBROUTINE AVER in AERMOD calc2.f\n                double numerator = ba::rolling_sum(rsacc1_);\n                double denominator = std::max(n - ba::rolling_sum(rsacc2_), std::round(n * 0.75 + 0.4));\n                value_ = numerator / denominator;\n            }\n            else {\n                // Long-term average. See SUBROUTINE PERAVE in AERMOD output.f\n                double numerator = ba::rolling_sum(rsacc1_);\n                double denominator = n - ba::rolling_sum(rsacc2_);\n                value_ = numerator / denominator;\n            }\n        }\n        else {\n            // Calculate standard rolling mean. Averaging already applied by AERMOD.\n            rmacc_(val);\n            value_ = ba::rolling_mean(rmacc_);\n        }\n\n        // Track the maximum value.\n        maxacc_(value_);\n    }\n\n    double value() const\n    {\n        return value_;\n    }\n\n    double max() const\n    {\n        return ba::max(maxacc_);\n    }\n\nprivate:\n    int ave_;\n    double value_;\n    rsacc_t rsacc1_; // rolling sum concentration (ave == 1)\n    rsacc_t rsacc2_; // rolling sum valid hours (ave == 1)\n    rmacc_t rmacc_;  // rolling mean concentration (ave != 1)\n    maxacc_t maxacc_;\n};\n\n} // namespace accumulators\n\n\nvoid analysis::set_progress_function(const std::function<void(std::size_t)>& fn)\n{\n    progressfn_ = fn;\n}\n\nvoid analysis::export_time_series(const options::general& opts, const options::tsexport& exopts) const\n{\n    using rmacc_t = accumulators::epa_rolling_mean;\n\n    // Read the output matrix.\n    auto recs = receptors();\n    auto arcids = receptor_arcids();\n    auto netids = receptor_netids();\n    auto times = time_steps();\n    auto matrix = output_matrix(opts.averaging_period, opts.source_group, opts.output_type, opts.scale_factor);\n    auto allave = ds_.vars[\"ave\"].values<int>();\n    int minave = *std::min_element(allave.begin(), allave.end());\n\n    std::ofstream ofs(exopts.output_file);\n\n    // Write CSV header.\n    fmt::memory_buffer header;\n\n    if (opts.averaging_period == 1)\n        fmt::format_to(header, \"arcid,netid,receptor,time,calm_missing,x,y,zelev,zhill,zflag,{}\", opts.output_type);\n    else\n        fmt::format_to(header, \"arcid,netid,receptor,time,x,y,zelev,zhill,zflag,{}\", opts.output_type);\n\n    if (exopts.rm_windows.size() > 0) {\n        for (const auto& w : exopts.rm_windows) {\n            fmt::format_to(header, \",{}[RM{}]\", opts.output_type, w);\n        }\n    }\n\n    fmt::format_to(header, \"\\n\");\n    ofs << fmt::to_string(header);\n\n    // Write CSV records.\n    for (std::size_t j = 0; j < matrix.size2(); ++j) // receptors\n    {\n        progressfn_(j);\n\n        const auto& rec = recs.at(j);\n\n        // Create the rolling mean accumulators.\n        std::vector<rmacc_t> rmaccs;\n        rmaccs.reserve(exopts.rm_windows.size());\n        for (double w : exopts.rm_windows) {\n            rmaccs.emplace_back(rmacc_t(opts.averaging_period, static_cast<int>(w) * 24));\n        }\n\n        fmt::memory_buffer buffer1;\n        fmt::format_to(buffer1, \"{},{},{:d},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f}\",\n            rec.arcid, rec.netid, rec.id, rec.x, rec.y,\n            rec.zelev, rec.zhill, rec.zflag);\n\n        for (std::size_t i = 0; i < matrix.size1(); ++i) // time steps\n        {\n            std::vector<double> rmvals(exopts.rm_windows.size(), 0);\n\n            const auto ts = times.at(i * opts.averaging_period / minave);\n            const double val = matrix.at_element(i, j); // ntime * nrecs, column-major\n\n            for (auto&& rmacc : rmaccs)\n                rmacc(val, ts.calm_missing);\n\n            fmt::memory_buffer buffer2;\n\n            if (opts.averaging_period == 1)\n                fmt::format_to(buffer2, \",{},{},{:.6g}\", date::format(\"%F %R\", ts.time), ts.calm_missing, val);\n            else\n                fmt::format_to(buffer2, \",{},{:.6g}\", date::format(\"%F %R\", ts.time), val);\n\n            for (const auto& rmacc : rmaccs)\n                fmt::format_to(buffer2, \",{}\", rmacc.value());\n\n            ofs << fmt::to_string(buffer1) << fmt::to_string(buffer2) << \"\\n\";\n        }\n    }\n\n    ofs.close();\n}\n\nvoid analysis::calc_receptor_stats(const options::general& opts, const options::statistics& statopts, statistics_type& out) const\n{\n    using namespace boost::accumulators;\n\n    if (!statopts.calc_avg && !statopts.calc_max && !statopts.calc_std &&\n        !statopts.percentiles.size() && !statopts.maxrm_windows.size())\n        return;\n\n    // Define the statistical accumulator types.\n    using avgacc_t = accumulator_set<double, features<tag::mean>>;\n    using maxacc_t = accumulator_set<double, features<tag::max>>;\n    using varacc_t = accumulator_set<double, features<tag::variance>>;\n    using p2acc_t = accumulator_set<double, stats<tag::p_square_quantile>>;\n    using rmacc_t = accumulators::epa_rolling_mean;\n\n    // Read the output matrix.\n    std::size_t nrecs = receptor_count();\n    auto times = time_steps();\n    auto matrix = output_matrix(opts.averaging_period, opts.source_group, opts.output_type, opts.scale_factor);\n    auto allave = ds_.vars[\"ave\"].values<int>();\n    int minave = *std::min_element(allave.begin(), allave.end());\n\n    // Initialize the output vectors for basic statistics.\n    if (statopts.calc_avg)\n        out.avg.resize(nrecs);\n    if (statopts.calc_max)\n        out.max.resize(nrecs);\n    if (statopts.calc_std)\n        out.std.resize(nrecs);\n\n    // Initialize the output vectors for P2 calculations.\n    for (double p : statopts.percentiles) {\n        std::vector<double> v(nrecs, 0);\n        out.p2.push_back(v);\n    }\n\n    // Initialize the output vectors for rolling mean calculations.\n    for (double w : statopts.maxrm_windows) {\n        std::vector<double> v(nrecs, 0);\n        out.rm.push_back(v);\n    }\n\n    // Analyze the data array for each receptor.\n    for (std::size_t j = 0; j < matrix.size2(); ++j) // receptors\n    {\n        progressfn_(j);\n\n        // Create the accumulators.\n        avgacc_t avgacc;\n        maxacc_t maxacc;\n        varacc_t varacc;\n\n        std::vector<p2acc_t> p2accs;\n        p2accs.reserve(statopts.percentiles.size());\n        for (double p : statopts.percentiles)\n            p2accs.emplace_back(p2acc_t(quantile_probability = p));\n\n        std::vector<rmacc_t> rmaccs;\n        rmaccs.reserve(statopts.maxrm_windows.size());\n        for (double w : statopts.maxrm_windows)\n            rmaccs.emplace_back(rmacc_t(opts.averaging_period, static_cast<int>(w) * 24));\n\n        // Main update loop.\n        for (std::size_t i = 0; i < matrix.size1(); ++i) // time steps\n        {\n            const auto ts = times.at(i * opts.averaging_period / minave);\n            const double val = matrix.at_element(i, j); // ntime * nrecs, column-major\n\n            if (statopts.calc_avg)\n                avgacc(val);\n            if (statopts.calc_max)\n                maxacc(val);\n            if (statopts.calc_std)\n                varacc(val);\n            for (auto&& p2acc : p2accs)\n                p2acc(val);\n            for (auto&& rmacc : rmaccs)\n                rmacc(val, ts.calm_missing);\n        }\n\n        // Extract results.\n        if (statopts.calc_avg)\n            out.avg[j] = mean(avgacc);\n        if (statopts.calc_max)\n            out.max[j] = max(maxacc);\n        if (statopts.calc_std)\n            out.std[j] = sqrt(variance(varacc));\n        for (std::size_t iacc = 0; iacc < p2accs.size(); ++iacc)\n            out.p2.at(iacc).at(j) = p_square_quantile(p2accs[iacc]);\n        for (std::size_t iacc = 0; iacc < p2accs.size(); ++iacc)\n            out.rm.at(iacc).at(j) = rmaccs[iacc].max();\n    }\n}\n\nvoid analysis::calc_histogram(const options::general& opts, const options::histogram& histopts, histogram_type& out) const\n{\n    using namespace boost::accumulators;\n\n    using cdfacc_t = accumulator_set<double, stats<tag::p_square_cumulative_distribution>>;\n    using pdfacc_t = accumulator_set<double, stats<tag::density>>;\n\n    if (!histopts.calc_cdf && !histopts.calc_pdf)\n        return;\n\n    // Read the data array.\n    auto matrix = output_matrix(opts.averaging_period, opts.source_group, opts.output_type, opts.scale_factor);\n\n    // Create the accumulators.\n    cdfacc_t cdfacc(tag::p_square_cumulative_distribution::num_cells = static_cast<std::size_t>(histopts.cdf_bins));\n\n    // If selected cache size exceeds sample count, use all samples.\n    std::size_t cache_size = std::max(static_cast<std::size_t>(histopts.pdf_cache_size), matrix.data().size());\n\n    pdfacc_t pdfacc(tag::density::num_bins = static_cast<std::size_t>(histopts.pdf_bins),\n                    tag::density::cache_size = cache_size);\n\n    // Analyze the data array.\n    for (std::size_t j = 0; j < matrix.size2(); ++j) // receptors\n    {\n        progressfn_(j);\n\n        for (std::size_t i = 0; i < matrix.size1(); ++i) { // time steps\n            const double val = matrix.at_element(i, j); // ntime * nrecs, column-major\n            if (histopts.calc_cdf)\n                cdfacc(val);\n            if (histopts.calc_pdf)\n                pdfacc(val);\n        }\n    }\n\n    // Extract results.\n    typedef boost::iterator_range<std::vector<std::pair<double, double>>::iterator> histogram_t;\n    if (histopts.calc_cdf) {\n        histogram_t cdf = p_square_cumulative_distribution(cdfacc);\n        out.cdf.insert(out.cdf.end(), std::make_move_iterator(cdf.begin()), std::make_move_iterator(cdf.end()));\n    }\n    if (histopts.calc_pdf) {\n        histogram_t pdf = density(pdfacc);\n        out.pdf.insert(out.pdf.end(), std::make_move_iterator(pdf.begin()), std::make_move_iterator(pdf.end()));\n    }\n}\n\nmatrix_t analysis::output_matrix(int ave, const std::string& grp, const std::string& var, double sf) const\n{\n    auto slice = ds_.vars[var].select(\n        ncpp::selection<int>{\"ave\", ave, ave},\n        ncpp::selection<std::string>{\"grp\", grp, grp});\n\n    // Get full matrix dimensions.\n    std::size_t ntime = ds_.vars[\"time\"].size();\n    std::size_t nrecs = ds_.vars[\"rec\"].size();\n    auto allave = ds_.vars[\"ave\"].values<int>();\n    int minave = *std::min_element(allave.begin(), allave.end());\n\n    // Recalculate ntime to exclude fill values for multiple averaging periods.\n    ntime = ntime / static_cast<std::size_t>(ave / minave);\n\n    // Read the data array and remove fill values.\n    auto values = slice.values<double, aligned_allocator_t>();\n    values.erase(std::remove(values.begin(), values.end(), NC_FILL_DOUBLE), values.end());\n    if (values.size() != ntime * nrecs)\n        throw std::runtime_error(\"Data array has unexpected missing values.\");\n\n    matrix_t result(ntime, nrecs); // column-major\n    std::copy(values.begin(), values.end(), result.data().begin());\n\n    //matrix_t result = slice.matrix<double, aligned_allocator_t>();\n    //auto end = std::remove(result.data().begin(), result.data().end(), NC_FILL_DOUBLE);\n    //if (std::distance(result.data().begin(), end) != ntime * nrecs)\n    //    throw std::runtime_error(\"Data array has unexpected missing values.\");\n    //result.resize(ntime, nrecs); // column-major\n\n    // Apply scale factor.\n    if (sf != 1.0)\n        result *= sf;\n\n    return result;\n}\n\n} // namespace ncpost\n", "meta": {"hexsha": "1de28e8a7cbba64fb46af0deda69b680723069f7", "size": 19312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis/Analysis.cpp", "max_stars_repo_name": "sofea-model/sofea", "max_stars_repo_head_hexsha": "a6ee54b59c6f96929592118ee77e286f71238c9e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analysis/Analysis.cpp", "max_issues_repo_name": "sofea-model/sofea", "max_issues_repo_head_hexsha": "a6ee54b59c6f96929592118ee77e286f71238c9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-31T06:21:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-31T06:26:52.000Z", "max_forks_repo_path": "src/analysis/Analysis.cpp", "max_forks_repo_name": "sofea-model/sofea", "max_forks_repo_head_hexsha": "a6ee54b59c6f96929592118ee77e286f71238c9e", "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.011965812, "max_line_length": 129, "alphanum_fraction": 0.6205468103, "num_tokens": 5016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.02887090475289319, "lm_q1q2_score": 0.008494252080856003}}
{"text": "/*\n parsephon.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 \"parsephon.h\"\n#include \"conductivity.h\"\n#include \"dielec.h\"\n#include \"dynamical.h\"\n#include \"error.h\"\n#include \"ewald.h\"\n#include \"fcs_phonon.h\"\n#include \"gruneisen.h\"\n#include \"integration.h\"\n#include \"isotope.h\"\n#include \"kpoint.h\"\n#include \"memory.h\"\n#include \"phonon_dos.h\"\n#include \"phonon_velocity.h\"\n#include \"anharmonic_core.h\"\n#include \"mode_analysis.h\"\n#include \"scph.h\"\n#include \"symmetry_core.h\"\n#include \"system.h\"\n#include \"thermodynamics.h\"\n#include \"write_phonons.h\"\n#include <sys/stat.h>\n#include <sstream>\n#include <istream>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\nusing namespace PHON_NS;\n\nInput::Input(PHON *phon) : Pointers(phon)\n{\n    from_stdin = false;\n    job_title = \"\";\n}\n\nInput::~Input()\n{\n    if (ifs_input.is_open()) ifs_input.close();\n}\n\nvoid Input::parce_input(int narg,\n                        char **arg)\n{\n    if (narg == 1) {\n\n        from_stdin = true;\n\n    } else {\n\n        from_stdin = false;\n\n        ifs_input.open(arg[1], std::ios::in);\n        if (!ifs_input) {\n            std::cout << \"No such file or directory: \" << arg[1] << std::endl;\n            exit(\"parse_input\", \"could not open the file\");\n        }\n    }\n\n    if (!locate_tag(\"&general\"))\n        exit(\"parse_input\",\n                    \"&general entry not found in the input file\");\n    parse_general_vars();\n\n    if (!locate_tag(\"&cell\"))\n        exit(\"parse_input\",\n                    \"&cell entry not found in the input file\");\n    parse_cell_parameter();\n\n    const auto use_defaults_for_analysis = !locate_tag(\"&analysis\");\n    parse_analysis_vars(use_defaults_for_analysis);\n\n    if (!locate_tag(\"&kpoint\"))\n        exit(\"parse_input\",\n                    \"&kpoint entry not found in the input file\");\n    parse_kpoints();\n\n    if (phon->mode == \"SCPH\") {\n        if (!locate_tag(\"&scph\"))\n            exit(\"parse_input\",\n                        \"&scph entry not found in the input file\");\n        parse_scph_vars();\n    }\n}\n\nvoid Input::parse_general_vars()\n{\n    // Read input parameters in the &general-field.\n\n    int i;\n    int nkd;\n    struct stat st;\n    std::string str_tmp;\n    const std::vector<std::string> input_list{\n          \"PREFIX\", \"MODE\", \"NSYM\", \"TOLERANCE\", \"PRINTSYM\", \"FCSXML\", \"FC2XML\",\n          \"TMIN\", \"TMAX\", \"DT\", \"NBANDS\", \"NONANALYTIC\", \"BORNINFO\", \"NA_SIGMA\",\n          \"ISMEAR\", \"EPSILON\", \"EMIN\", \"EMAX\", \"DELTA_E\", \"RESTART\", \"TREVSYM\",\n          \"NKD\", \"KD\", \"MASS\", \"TRISYM\", \"PREC_EWALD\", \"CLASSICAL\", \"BCONNECT\", \"BORNSYM\",\n          \"VERBOSITY\"\n    };\n\n    std::vector<std::string> no_defaults{\"PREFIX\", \"MODE\", \"FCSXML\", \"NKD\", \"KD\"};\n    std::vector<std::string> kdname_v, masskd_v;\n    std::map<std::string, std::string> general_var_dict;\n\n    double *masskd = nullptr;\n    std::string *kdname = nullptr;\n\n    if (from_stdin) {\n        std::cin.ignore();\n    } else {\n        ifs_input.ignore();\n    }\n\n    get_var_dict(input_list, general_var_dict);\n\n    for (auto &no_default: no_defaults) {\n        if (general_var_dict.find(no_default) == general_var_dict.end()) {\n            exit(\"parse_general_vars\",\n                        \"The following variable is not found in &general input region: \",\n                        no_default.c_str());\n        }\n    }\n\n    const auto prefix = general_var_dict[\"PREFIX\"];\n    auto mode = general_var_dict[\"MODE\"];\n    auto file_result = prefix + \".result\";\n\n    std::transform(mode.begin(), mode.end(), mode.begin(), toupper);\n\n    const auto fcsinfo = general_var_dict[\"FCSXML\"];\n    assign_val(nkd, \"NKD\", general_var_dict);\n\n    split_str_by_space(general_var_dict[\"KD\"], kdname_v);\n\n    if (kdname_v.size() != nkd) {\n        exit(\"parse_general_vars\",\n                    \"The number of entries for KD is inconsistent with NKD\");\n    } else {\n        allocate(kdname, nkd);\n        for (i = 0; i < nkd; ++i) {\n            kdname[i] = kdname_v[i];\n        }\n    }\n\n    if (!general_var_dict[\"MASS\"].empty()) {\n        split_str_by_space(general_var_dict[\"MASS\"], masskd_v);\n\n        if (masskd_v.size() != nkd) {\n            exit(\"parse_general_vars\",\n                        \"The number of entries for MASS is inconsistent with NKD\");\n        } else {\n            allocate(masskd, nkd);\n            for (i = 0; i < nkd; ++i) {\n                masskd[i] = my_cast<double>(masskd_v[i]);\n            }\n        }\n    }\n\n\n    // Default values\n\n    auto Tmin = 0.0;\n    auto Tmax = 1000.0;\n    auto dT = 10.0;\n\n    auto emin = 0.0;\n    auto emax = 1000.0;\n    auto delta_e = 10.0;\n\n    unsigned int nonanalytic = 0;\n    auto nsym = 0;\n    auto tolerance = 1.0e-6;\n    auto printsymmetry = false;\n    auto sym_time_reversal = false;\n    auto use_triplet_symmetry = true;\n    auto classical = false;\n    unsigned int band_connection = 0;\n    unsigned int bornsym = 0;\n    unsigned int verbosity = 1;\n\n    auto prec_ewald = 1.0e-12;\n\n    // if file_result exists in the current directory,\n    // restart mode will be automatically turned on.\n    auto restart = stat(file_result.c_str(), &st) == 0;\n\n    auto nbands = -1;\n    std::string borninfo;\n    std::string fc2info;\n\n    auto ismear = -1;\n    auto epsilon = 10.0;\n    auto na_sigma = 0.1;\n\n    // Assign given values\n\n    assign_val(Tmin, \"TMIN\", general_var_dict);\n    assign_val(Tmax, \"TMAX\", general_var_dict);\n    assign_val(dT, \"DT\", general_var_dict);\n\n    assign_val(emin, \"EMIN\", general_var_dict);\n    assign_val(emax, \"EMAX\", general_var_dict);\n    assign_val(delta_e, \"DELTA_E\", general_var_dict);\n\n    assign_val(nsym, \"NSYM\", general_var_dict);\n    assign_val(sym_time_reversal, \"TREVSYM\", general_var_dict);\n    assign_val(tolerance, \"TOLERANCE\", general_var_dict);\n    assign_val(printsymmetry, \"PRINTSYM\", general_var_dict);\n\n    assign_val(nonanalytic, \"NONANALYTIC\", general_var_dict);\n    assign_val(restart, \"RESTART\", general_var_dict);\n\n    assign_val(nbands, \"NBANDS\", general_var_dict);\n    assign_val(borninfo, \"BORNINFO\", general_var_dict);\n    assign_val(fc2info, \"FC2XML\", general_var_dict);\n\n    assign_val(ismear, \"ISMEAR\", general_var_dict);\n    assign_val(epsilon, \"EPSILON\", general_var_dict);\n    assign_val(na_sigma, \"NA_SIGMA\", general_var_dict);\n    assign_val(classical, \"CLASSICAL\", general_var_dict);\n    assign_val(band_connection, \"BCONNECT\", general_var_dict);\n    assign_val(use_triplet_symmetry, \"TRISYM\", general_var_dict);\n    assign_val(bornsym, \"BORNSYM\", general_var_dict);\n    assign_val(verbosity, \"VERBOSITY\", general_var_dict);\n\n    if (band_connection > 2) {\n        exit(\"parse_general_vars\", \"BCONNECT-tag can take 0, 1, or 2.\");\n    }\n\n    if (nonanalytic == 3) {\n        assign_val(prec_ewald, \"PREC_EWALD\", general_var_dict);\n        if (prec_ewald <= 0.0 || prec_ewald >= 1.0) {\n            exit(\"parse_general_vars\",\n                        \"PREC_EWALD should be a small positive value.\");\n        }\n        ewald->is_longrange = true;\n        ewald->file_longrange = boost::lexical_cast<std::string>(general_var_dict[\"BORNINFO\"]);\n        ewald->prec_ewald = prec_ewald;\n        ewald->rate_ab = 6.0 / pi;\n\n    } else {\n        ewald->is_longrange = false;\n    }\n\n    if (nonanalytic > 3) {\n        exit(\"parse_general_vars\",\n                    \"NONANALYTIC-tag can take 0, 1, 2, or 3.\");\n    }\n    if (nonanalytic && borninfo == \"\") {\n        exit(\"parse_general_vars\",\n                    \"BORNINFO must be specified when NONANALYTIC > 0.\");\n    }\n    // if (nonanalytic == 3) {\n    //     if (mode == \"SCPH\") {\n    //         exit(\"parse_general_vars\",\n    //                     \"Sorry. NONANALYTIC=3 is not supported for MODE = SCPH.\");\n    //     }\n    // }\n\n    // Copy the values to appropriate classes.\n\n    job_title = prefix;\n    writes->file_result = file_result;\n    phon->mode = mode;\n    phon->restart_flag = restart;\n    symmetry->nsym = nsym;\n    symmetry->tolerance = tolerance;\n    symmetry->printsymmetry = printsymmetry;\n    symmetry->time_reversal_sym = sym_time_reversal;\n\n    system->Tmin = Tmin;\n    system->Tmax = Tmax;\n    system->dT = dT;\n    system->nkd = nkd;\n\n    allocate(system->symbol_kd, nkd);\n    for (i = 0; i < nkd; ++i) {\n        system->symbol_kd[i] = kdname[i];\n    }\n    if (kdname) {\n        deallocate(kdname);\n    }\n\n    if (!general_var_dict[\"MASS\"].empty()) {\n        allocate(system->mass_kd, nkd);\n        for (i = 0; i < nkd; ++i) {\n            system->mass_kd[i] = masskd[i];\n        }\n    }\n    if (masskd) {\n        deallocate(masskd);\n    }\n\n    dos->emax = emax;\n    dos->emin = emin;\n    dos->delta_e = delta_e;\n\n    dynamical->nonanalytic = nonanalytic;\n    dynamical->na_sigma = na_sigma;\n    dynamical->symmetrize_borncharge = bornsym;\n    writes->nbands = nbands;\n    dynamical->file_born = borninfo;\n    dynamical->band_connection = band_connection;\n    integration->epsilon = epsilon;\n    fcs_phonon->file_fcs = fcsinfo;\n    fcs_phonon->file_fc2 = fc2info;\n    fcs_phonon->update_fc2 = !fc2info.empty();\n    thermodynamics->classical = classical;\n    integration->ismear = ismear;\n    anharmonic_core->use_triplet_symmetry = use_triplet_symmetry;\n\n    general_var_dict.clear();\n}\n\nvoid Input::parse_scph_vars()\n{\n    // Read input parameters in the &scph-field.\n\n    struct stat st{};\n    const std::vector<std::string> input_list{\n          \"KMESH_SCPH\", \"KMESH_INTERPOLATE\", \"MIXALPHA\", \"MAXITER\",\n          \"RESTART_SCPH\", \"IALGO\", \"SELF_OFFDIAG\", \"TOL_SCPH\",\n          \"LOWER_TEMP\", \"WARMSTART\", \"BUBBLE\"\n    };\n    std::vector<std::string> no_defaults{\"KMESH_SCPH\", \"KMESH_INTERPOLATE\"};\n    std::vector<int> kmesh_v, kmesh_interpolate_v;\n    std::map<std::string, std::string> scph_var_dict;\n\n    if (from_stdin) {\n        std::cin.ignore();\n    } else {\n        ifs_input.ignore();\n    }\n\n    get_var_dict(input_list, scph_var_dict);\n\n    for (auto &no_default: no_defaults) {\n        if (scph_var_dict.find(no_default) == scph_var_dict.end()) {\n            exit(\"parse_general_vars\",\n                        \"The following variable is not found in &scph input region: \",\n                        no_default.c_str());\n        }\n    }\n\n    auto file_dymat = this->job_title + \".scph_dymat\";\n\n    // Default values\n\n    auto tolerance_scph = 1.0e-10;\n    unsigned int maxiter = 1000;\n    auto mixalpha = 0.1;\n    auto selenergy_offdiagonal = true;\n    unsigned int ialgo_scph = 0;\n    auto lower_temp = true;\n    auto warm_start = true;\n    unsigned int bubble = 0;\n\n    // if file_dymat exists in the current directory,\n    // restart mode will be automatically turned on for SCPH calculations.\n\n    auto restart_scph = stat(file_dymat.c_str(), &st) == 0;\n\n    // Assign given values\n\n    assign_val(restart_scph, \"RESTART_SCPH\", scph_var_dict);\n    assign_val(maxiter, \"MAXITER\", scph_var_dict);\n    assign_val(mixalpha, \"MIXALPHA\", scph_var_dict);\n    assign_val(selenergy_offdiagonal, \"SELF_OFFDIAG\", scph_var_dict);\n    assign_val(ialgo_scph, \"IALGO\", scph_var_dict);\n    assign_val(tolerance_scph, \"TOL_SCPH\", scph_var_dict);\n    assign_val(lower_temp, \"LOWER_TEMP\", scph_var_dict);\n    assign_val(warm_start, \"WARMSTART\", scph_var_dict);\n    assign_val(bubble, \"BUBBLE\", scph_var_dict);\n\n    auto str_tmp = scph_var_dict[\"KMESH_SCPH\"];\n\n    if (!str_tmp.empty()) {\n\n        std::istringstream is(str_tmp);\n\n        while (true) {\n            str_tmp.clear();\n            is >> str_tmp;\n            if (str_tmp.empty()) {\n                break;\n            }\n            kmesh_v.push_back(my_cast<unsigned int>(str_tmp));\n        }\n\n        if (kmesh_v.size() != 3) {\n            exit(\"parse_general_vars\",\n                        \"The number of entries for KMESH_SCPH has to be 3.\");\n        }\n    } else {\n        exit(\"parse_general_vars\",\n                    \"Please specify KMESH_SCPH for mode = SCPH\");\n    }\n\n    str_tmp = scph_var_dict[\"KMESH_INTERPOLATE\"];\n    if (!str_tmp.empty()) {\n\n        std::istringstream is(str_tmp);\n\n        while (true) {\n            str_tmp.clear();\n            is >> str_tmp;\n            if (str_tmp.empty()) {\n                break;\n            }\n            kmesh_interpolate_v.push_back(my_cast<unsigned int>(str_tmp));\n        }\n\n        if (kmesh_interpolate_v.size() != 3) {\n            exit(\"parse_general_vars\",\n                        \"The number of entries for KMESH_INTERPOLATE has to be 3.\");\n        }\n    } else {\n        exit(\"parse_general_vars\",\n                    \"Please specify KMESH_INTERPOLATE for mode = SCPH\");\n    }\n\n    // Copy the values to appropriate classes.\n\n    for (auto i = 0; i < 3; ++i) {\n        scph->kmesh_scph[i] = kmesh_v[i];\n        scph->kmesh_interpolate[i] = kmesh_interpolate_v[i];\n    }\n    scph->mixalpha = mixalpha;\n    scph->maxiter = maxiter;\n    scph->restart_scph = restart_scph;\n    scph->selfenergy_offdiagonal = selenergy_offdiagonal;\n    scph->ialgo = ialgo_scph;\n    scph->tolerance_scph = tolerance_scph;\n    scph->lower_temp = lower_temp;\n    scph->warmstart_scph = warm_start;\n    scph->bubble = bubble;\n\n    kmesh_v.clear();\n    kmesh_interpolate_v.clear();\n\n    scph_var_dict.clear();\n}\n\nvoid Input::parse_analysis_vars(const bool use_default_values)\n{\n    // Read input parameters in the &analysis field.\n    int i;\n\n    std::vector<std::string> input_list{\n          \"PRINTEVEC\", \"PRINTXSF\", \"PRINTVEL\", \"QUARTIC\", \"KS_INPUT\",\n          \"REALPART\", \"ISOTOPE\", \"ISOFACT\",\n          \"FSTATE_W\", \"FSTATE_K\", \"PRINTMSD\", \"DOS\", \"PDOS\", \"TDOS\",\n          \"GRUNEISEN\", \"NEWFCS\", \"DELTA_A\", \"ANIME\", \"ANIME_CELLSIZE\",\n          \"ANIME_FORMAT\", \"ANIME_FRAMES\", \"SPS\", \"PRINTV3\", \"PRINTPR\",\n          \"FC2_EWALD\", \"KAPPA_SPEC\", \"SELF_W\", \"UCORR\", \"SHIFT_UCORR\",\n          \"KAPPA_COHERENT\",\n          \"DIELEC\", \"SELF_ENERGY\", \"PRINTV4\", \"ZMODE\", \"PROJECTION_AXES\"\n    };\n\n#ifdef _FE_BUBBLE\n    input_list.push_back(\"FE_BUBBLE\");\n#endif\n\n    unsigned int cellsize[3] = {1, 1, 1};\n    int shift_ucorr[3] = {0, 0, 0};\n    double anime_kpoint_double[3] = {0., 0., 0.};\n\n    double *isotope_factor = nullptr;\n    std::string ks_input, anime_format;\n    std::map<std::string, std::string> analysis_var_dict;\n    std::vector<std::string> isofact_v, anime_kpoint, anime_cellsize;\n    std::vector<std::string> projection_axes;\n\n    // Default values\n\n    auto print_xsf = false;\n    auto print_anime = false;\n\n    auto print_vel = false;\n    auto print_evec = false;\n    auto print_msd = false;\n    auto print_ucorr = false;\n    auto anime_frames = 20;\n\n    bool compute_dos = true;\n    bool projected_dos = false;\n    bool two_phonon_dos = false;\n    int scattering_phase_space = 0;\n    bool print_gruneisen = false;\n    bool print_newfcs = false;\n    int print_V3 = 0;\n    int print_V4 = 0;\n    bool participation_ratio = false;\n\n    auto delta_a = 0.001;\n\n    auto quartic_mode = 0;\n    auto calc_realpart = false;\n    auto include_isotope = 0;\n    auto fstate_omega = false;\n    auto fstate_k = false;\n    auto bubble_omega = false;\n\n    auto calculate_kappa_spec = 0;\n\n    auto print_fc2_ewald = false;\n    auto print_self_consistent_fc2 = false;\n    auto calc_FE_bubble = false;\n    auto calc_coherent = 0;\n\n    auto calculate_dielectric_constant = 0;\n    auto calc_selfenergy = 0;\n    auto print_zmode = false;\n\n    auto do_projection = false;\n\n    // Assign values to variables\n\n    if (!use_default_values) {\n        get_var_dict(input_list, analysis_var_dict);\n\n        assign_val(print_vel, \"PRINTVEL\", analysis_var_dict);\n        assign_val(print_evec, \"PRINTEVEC\", analysis_var_dict);\n        assign_val(print_msd, \"PRINTMSD\", analysis_var_dict);\n        assign_val(print_ucorr, \"UCORR\", analysis_var_dict);\n\n        assign_val(compute_dos, \"DOS\", analysis_var_dict);\n        assign_val(projected_dos, \"PDOS\", analysis_var_dict);\n        assign_val(two_phonon_dos, \"TDOS\", analysis_var_dict);\n        assign_val(scattering_phase_space, \"SPS\", analysis_var_dict);\n        assign_val(print_gruneisen, \"GRUNEISEN\", analysis_var_dict);\n        assign_val(print_newfcs, \"NEWFCS\", analysis_var_dict);\n        assign_val(delta_a, \"DELTA_A\", analysis_var_dict);\n\n        assign_val(quartic_mode, \"QUARTIC\", analysis_var_dict);\n        assign_val(calc_realpart, \"REALPART\", analysis_var_dict);\n        assign_val(include_isotope, \"ISOTOPE\", analysis_var_dict);\n        assign_val(fstate_omega, \"FSTATE_W\", analysis_var_dict);\n        assign_val(fstate_k, \"FSTATE_K\", analysis_var_dict);\n        assign_val(ks_input, \"KS_INPUT\", analysis_var_dict);\n        assign_val(calculate_kappa_spec, \"KAPPA_SPEC\", analysis_var_dict);\n        assign_val(calc_coherent, \"KAPPA_COHERENT\", analysis_var_dict);\n        assign_val(bubble_omega, \"SELF_W\", analysis_var_dict);\n        assign_val(calc_selfenergy, \"SELF_ENERGY\", analysis_var_dict);\n\n        assign_val(print_xsf, \"PRINTXSF\", analysis_var_dict);\n        assign_val(print_V3, \"PRINTV3\", analysis_var_dict);\n        assign_val(print_V4, \"PRINTV4\", analysis_var_dict);\n        assign_val(participation_ratio, \"PRINTPR\", analysis_var_dict);\n        assign_val(print_fc2_ewald, \"FC2_EWALD\", analysis_var_dict);\n        assign_val(calculate_dielectric_constant, \"DIELEC\", analysis_var_dict);\n        assign_val(print_zmode, \"ZMODE\", analysis_var_dict);\n#ifdef _FE_BUBBLE\n        assign_val(calc_FE_bubble, \"FE_BUBBLE\", analysis_var_dict);\n#endif\n\n        if (analysis_var_dict.find(\"ANIME\") == analysis_var_dict.end()) {\n            print_anime = false;\n        } else {\n            print_anime = true;\n        }\n\n        if (analysis_var_dict.find(\"PROJECTION_AXES\") != analysis_var_dict.end()) {\n            do_projection = true;\n        }\n    }\n\n    if (include_isotope) {\n\n        if (!analysis_var_dict[\"ISOFACT\"].empty()) {\n            split_str_by_space(analysis_var_dict[\"ISOFACT\"], isofact_v);\n\n            if (isofact_v.size() != system->nkd) {\n                exit(\"parse_analysis_vars\",\n                            \"The number of entries for ISOFACT is inconsistent with NKD\");\n            } else {\n                allocate(isotope_factor, system->nkd);\n                for (i = 0; i < system->nkd; ++i) {\n                    isotope_factor[i] = my_cast<double>(isofact_v[i]);\n                }\n            }\n        }\n\n    }\n\n    if (print_anime) {\n        split_str_by_space(analysis_var_dict[\"ANIME\"], anime_kpoint);\n\n        if (anime_kpoint.size() != 3) {\n            exit(\"parse_analysis_vars\",\n                        \"The number of entries for ANIME should be 3.\");\n        }\n        for (i = 0; i < 3; ++i) {\n            anime_kpoint_double[i] = my_cast<double>(anime_kpoint[i]);\n        }\n\n        split_str_by_space(analysis_var_dict[\"ANIME_CELLSIZE\"], anime_cellsize);\n\n        if (anime_cellsize.size() != 3) {\n            exit(\"parse_analysis_vars\",\n                        \"The number of entries for ANIME_CELLSIZE should be 3.\");\n        }\n\n        for (i = 0; i < 3; ++i) {\n            try {\n                cellsize[i] = boost::lexical_cast<unsigned int>(anime_cellsize[i]);\n            }\n            catch (std::exception &e) {\n                std::cout << e.what() << std::endl;\n                exit(\"parse_analysis_vars\",\n                            \"ANIME_CELLSIZE must be a set of positive integers.\");\n            }\n            if (cellsize[i] < 1) {\n                exit(\"parse_analysis_vars\",\n                            \"Please give positive integers for ANIME_CELLSIZE.\");\n            }\n        }\n\n        assign_val(anime_format, \"ANIME_FORMAT\", analysis_var_dict);\n        std::transform(anime_format.begin(), anime_format.end(),\n                       anime_format.begin(), toupper);\n\n        if (anime_format.empty()) anime_format = \"XYZ\";\n\n        if (anime_format != \"XSF\" && anime_format != \"AXSF\" && anime_format != \"XYZ\") {\n            exit(\"parse_analysis_vars\", \"Invalid ANIME_FORMAT\");\n        }\n\n        assign_val(anime_frames, \"ANIME_FRAMES\", analysis_var_dict);\n    }\n\n    if (print_ucorr) {\n        std::string str_shift_ucorr;\n        std::vector<std::string> list_shift_ucorr;\n        assign_val(str_shift_ucorr, \"SHIFT_UCORR\", analysis_var_dict);\n\n        if (!str_shift_ucorr.empty()) {\n            split_str_by_space(str_shift_ucorr, list_shift_ucorr);\n            if (list_shift_ucorr.size() != 3) {\n                exit(\"parse_analysis_vars\",\n                            \"The number of entries for SHIFT_UCORR must be 3.\");\n            }\n\n            for (i = 0; i < 3; ++i) {\n                try {\n                    shift_ucorr[i] = boost::lexical_cast<int>(list_shift_ucorr[i]);\n                }\n                catch (std::exception &e) {\n                    std::cout << e.what() << std::endl;\n                    exit(\"parse_analysis_vars\",\n                                \"SHIFT_UCORR must be an array of integers.\");\n                }\n            }\n        }\n    }\n\n    if (do_projection) {\n        std::string str_projection_axes;\n        assign_val(str_projection_axes, \"PROJECTION_AXES\", analysis_var_dict);\n        std::vector<double> direction(3);\n        std::vector<std::vector<double>> projection_directions;\n        if (!str_projection_axes.empty()) {\n            std::vector<std::string> str_projection_each, str_vec;\n            boost::split(str_projection_each, str_projection_axes, boost::is_any_of(\",\"));\n\n            if (str_projection_each.size() > 2) {\n                warn(\"parse_analysis_vars\",\n                            \"Too many entries for PROJECTION_AXES. Only the first two will be used.\");\n            }\n\n            for (i = 0; i < str_projection_each.size(); ++i) {\n                split_str_by_space(str_projection_each[i], str_vec);\n                if (str_vec.size() != 3) {\n                    exit(\"parse_analysis_vars\",\n                                \"The number of entries for each vector in PROJECTION_AXES must be 3.\");\n                }\n                for (auto j = 0; j < 3; ++j) {\n                    try {\n                        direction[j] = boost::lexical_cast<double>(str_vec[j]);\n                    }\n                    catch (std::exception &e) {\n                        std::cout << e.what() << std::endl;\n                        exit(\"parse_analysis_vars\",\n                                    \"subset of PROJECTION_AXES must be an array of doubles.\");\n                    }\n                }\n                projection_directions.push_back(direction);\n            }\n        }\n\n        dynamical->set_projection_directions(projection_directions);\n    }\n\n    // Copy the values to appropriate classes\n\n    phonon_velocity->print_velocity = print_vel;\n    dynamical->print_eigenvectors = print_evec;\n    dynamical->participation_ratio = participation_ratio;\n//    writes->print_xsf = print_xsf;\n//    writes->print_anime = print_anime;\n//    writes->print_ucorr = print_ucorr;\n\n    writes->setWriteOptions(print_msd,\n                            print_xsf,\n                            print_anime,\n                            anime_format,\n                            anime_frames,\n                            cellsize,\n                            anime_kpoint_double,\n                            print_ucorr,\n                            shift_ucorr,\n                            print_zmode);\n\n//    if (print_anime) {\n//        for (i = 0; i < 3; ++i) {\n//            writes->anime_kpoint[i] = my_cast<double>(anime_kpoint[i]);\n//            writes->anime_cellsize[i] = cellsize[i];\n//        }\n//        writes->anime_format = anime_format;\n//    }\n//\n//    writes->print_msd = print_msd;\n\n    dos->compute_dos = compute_dos;\n    dos->projected_dos = projected_dos;\n    dos->two_phonon_dos = two_phonon_dos;\n    dos->scattering_phase_space = scattering_phase_space;\n\n    conductivity->calc_kappa_spec = calculate_kappa_spec;\n    conductivity->calc_coherent = calc_coherent;\n    anharmonic_core->quartic_mode = quartic_mode;\n    dielec->calc_dielectric_constant = calculate_dielectric_constant;\n\n    mode_analysis->ks_input = ks_input;\n    mode_analysis->calc_realpart = calc_realpart;\n    mode_analysis->calc_fstate_omega = fstate_omega;\n    mode_analysis->calc_fstate_k = fstate_k;\n    mode_analysis->print_V3 = print_V3;\n    mode_analysis->print_V4 = print_V4;\n    mode_analysis->spectral_func = bubble_omega;\n    mode_analysis->calc_selfenergy = calc_selfenergy;\n    isotope->include_isotope = include_isotope;\n\n    gruneisen->print_gruneisen = print_gruneisen;\n    gruneisen->print_newfcs = print_newfcs;\n    gruneisen->delta_a = delta_a;\n    thermodynamics->calc_FE_bubble = calc_FE_bubble;\n\n    ewald->print_fc2_ewald = print_fc2_ewald;\n\n    if (include_isotope) {\n        if (!analysis_var_dict[\"ISOFACT\"].empty()) {\n            allocate(isotope->isotope_factor, system->nkd);\n            for (i = 0; i < system->nkd; ++i) {\n                isotope->isotope_factor[i] = isotope_factor[i];\n            }\n        }\n    }\n    if (isotope_factor) {\n        deallocate(isotope_factor);\n    }\n\n    if (phon->mode == \"SCPH\") {\n        scph->print_self_consistent_fc2 = print_self_consistent_fc2;\n    }\n\n    analysis_var_dict.clear();\n}\n\nvoid Input::parse_cell_parameter()\n{\n    // Read the cell parameter\n\n    int i, j;\n    double a;\n    double lavec_tmp[3][3];\n    std::string line;\n    std::string line_wo_comment, line_tmp;\n    std::vector<std::string> line_vec, line_split;\n    std::string::size_type pos_first_comment_tag;\n\n    line_vec.clear();\n\n    if (from_stdin) {\n\n        while (std::getline(std::cin, line)) {\n\n            // Ignore comment region\n            pos_first_comment_tag = line.find_first_of('#');\n\n            if (pos_first_comment_tag == std::string::npos) {\n                line_wo_comment = line;\n            } else {\n                line_wo_comment = line.substr(0, pos_first_comment_tag);\n            }\n\n            trim_if(line_wo_comment, boost::is_any_of(\"\\t\\r\\n \"));\n\n            if (line_wo_comment.empty()) continue;\n            if (is_endof_entry(line_wo_comment)) break;\n\n            line_vec.push_back(line_wo_comment);\n        }\n\n    } else {\n        while (std::getline(ifs_input, line)) {\n\n            // Ignore comment region\n            pos_first_comment_tag = line.find_first_of('#');\n\n            if (pos_first_comment_tag == std::string::npos) {\n                line_wo_comment = line;\n            } else {\n                line_wo_comment = line.substr(0, pos_first_comment_tag);\n            }\n\n            trim_if(line_wo_comment, boost::is_any_of(\"\\t\\r\\n \"));\n\n            if (line_wo_comment.empty()) continue;\n            if (is_endof_entry(line_wo_comment)) break;\n\n            line_vec.push_back(line_wo_comment);\n        }\n    }\n\n    if (line_vec.size() != 4) {\n        exit(\"parse_cell_parameter\",\n                    \"Too few or too much lines for the &cell field.\\n \\\n                                            The number of valid lines for the &cell field should be 4.\");\n    }\n\n    for (i = 0; i < 4; ++i) {\n\n        line = line_vec[i];\n        split(line_split, line,\n              boost::is_any_of(\"\\t \"), boost::token_compress_on);\n\n        if (i == 0) {\n            // Lattice factor a\n            if (line_split.size() == 1) {\n                a = boost::lexical_cast<double>(line_split[0]);\n            } else {\n                exit(\"parse_cell_parameter\",\n                            \"Unacceptable format for &cell field.\");\n            }\n\n        } else {\n            // Lattice vectors a1, a2, a3\n            if (line_split.size() == 3) {\n                for (j = 0; j < 3; ++j) {\n                    lavec_tmp[j][i - 1] = boost::lexical_cast<double>(line_split[j]);\n                }\n            } else {\n                exit(\"parse_cell_parameter\",\n                            \"Unacceptable format for &cell field.\");\n            }\n        }\n    }\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            system->lavec_p[i][j] = a * lavec_tmp[i][j];\n        }\n    }\n}\n\nvoid Input::parse_kpoints()\n{\n    // Read the settings in the &kpoint field.\n\n    int kpmode;\n    std::string line, line_wo_comment, str_tmp;\n    std::vector<std::string> kpelem, line_vec;\n    std::string::size_type pos_first_comment_tag;\n\n    line_vec.clear();\n\n    if (from_stdin) {\n\n        while (std::getline(std::cin, line)) {\n\n            // Ignore comment region\n            pos_first_comment_tag = line.find_first_of('#');\n\n            if (pos_first_comment_tag == std::string::npos) {\n                line_wo_comment = line;\n            } else {\n                line_wo_comment = line.substr(0, pos_first_comment_tag);\n            }\n\n            trim_if(line_wo_comment, boost::is_any_of(\"\\t\\r\\n \"));\n\n            if (line_wo_comment.empty()) continue;\n            if (is_endof_entry(line_wo_comment)) break;\n\n            line_vec.push_back(line_wo_comment);\n        }\n\n    } else {\n        while (std::getline(ifs_input, line)) {\n\n            // Ignore comment region\n            pos_first_comment_tag = line.find_first_of('#');\n\n            if (pos_first_comment_tag == std::string::npos) {\n                line_wo_comment = line;\n            } else {\n                line_wo_comment = line.substr(0, pos_first_comment_tag);\n            }\n\n            trim_if(line_wo_comment, boost::is_any_of(\"\\t\\r\\n \"));\n\n            if (line_wo_comment.empty()) continue;\n            if (is_endof_entry(line_wo_comment)) break;\n\n            line_vec.push_back(line_wo_comment);\n        }\n    }\n\n    for (int i = 0; i < line_vec.size(); ++i) {\n        line = line_vec[i];\n        split(kpelem, line, boost::is_any_of(\"\\t \"), boost::token_compress_on);\n\n        if (i == 0) {\n            // kpmode\n            if (kpelem.size() == 1) {\n                try {\n                    kpmode = boost::lexical_cast<int>(kpelem[0]);\n                }\n                catch (std::exception &e) {\n                    std::cout << e.what() << std::endl;\n                    exit(\"parse_kpoints\",\n                                \"KPMODE must be an integer. [0, 1, or 2]\");\n                }\n\n                if (!(kpmode >= 0 && kpmode <= 3)) {\n                    exit(\"parse_kpoints\",\n                                \"KPMODE must be 0, 1, or 2.\");\n                }\n\n            } else {\n                exit(\"parse_kpoints\",\n                            \"Unacceptable format for the &kpoint field.\");\n            }\n\n        } else {\n            // Read each entry of kpoint\n\n            if (kpmode == 0 && kpelem.size() != 3) {\n                exit(\"parse_kpoints\",\n                            \"The number of columns must be 3 when KPMODE = 0\");\n            }\n            if (kpmode == 1 && kpelem.size() != 9) {\n                exit(\"parse_kpoints\",\n                            \"The number of columns must be 9 when KPMODE = 1\");\n            }\n            if (kpmode == 2 && kpelem.size() != 3) {\n                exit(\"parse_kpoints\",\n                            \"The number of columns must be 3 when KPMODE = 2\");\n            }\n            if (kpmode == 3 && kpelem.size() != 8) {\n                exit(\"parse_kpoints\",\n                            \"The number of columns must be 8 when KPMODE = 3\");\n            }\n\n            kpoint->kpInp.emplace_back(kpelem);\n        }\n    }\n\n    kpoint->kpoint_mode = kpmode;\n}\n\nint Input::locate_tag(const std::string &key)\n{\n    int ret = 0;\n    std::string line, line2;\n\n    if (from_stdin) {\n\n        // The following two lines do nothing when MPI version is executed.\n        // I don't know why this happens.\n        std::cin.clear();\n        std::cin.seekg(0, std::ios_base::beg);\n\n        while (std::cin >> line) {\n#ifdef _USE_BOOST\n            boost::to_lower(line);\n            boost::trim(line);\n#else\n            std::transform(line.begin(), line.end(), line.begin(), tolower);\n            line2 = line;\n            line = trim(line2);\n#endif\n            if (line == key) {\n                ret = 1;\n                break;\n            }\n        }\n        return ret;\n\n    }\n    ifs_input.clear();\n    ifs_input.seekg(0, std::ios_base::beg);\n\n    while (ifs_input >> line) {\n#ifdef _USE_BOOST\n        boost::to_lower(line);\n        boost::trim(line);\n#else\n        std::transform(line.begin(), line.end(), line.begin(), tolower);\n        line2 = line;\n        line = trim(line2);\n#endif\n        if (line == key) {\n            ret = 1;\n            break;\n        }\n    }\n    return ret;\n}\n\nvoid Input::get_var_dict(const std::vector<std::string> &input_list,\n                         std::map<std::string, std::string> &var_dict)\n{\n    std::string line, key, val;\n    std::string line_wo_comment, line_tmp;\n    std::string::size_type pos_first_comment_tag;\n    std::vector<std::string> str_entry, str_varval;\n    std::set<std::string> keyword_set;\n\n    for (const auto &it: input_list) {\n        keyword_set.insert(it);\n    }\n\n    var_dict.clear();\n\n    if (from_stdin) {\n\n        while (std::getline(std::cin, line)) {\n\n            // Ignore comment region\n            pos_first_comment_tag = line.find_first_of('#');\n\n            if (pos_first_comment_tag == std::string::npos) {\n                line_wo_comment = line;\n            } else {\n                line_wo_comment = line.substr(0, pos_first_comment_tag);\n            }\n#ifdef _USE_BOOST\n            boost::trim_left(line_wo_comment);\n#else\n            line_tmp = line_wo_comment;\n            line_wo_comment = ltrim(line_tmp);\n#endif\n            if (line_wo_comment.empty()) continue;\n            if (is_endof_entry(line_wo_comment)) break;\n\n            // Split the input line by ';'\n#ifdef _USE_BOOST\n            boost::split(str_entry, line_wo_comment, boost::is_any_of(\";\"));\n#else\n            str_entry = my_split(line_wo_comment, ';');\n#endif\n\n            for (auto it = str_entry.begin(); it != str_entry.end(); ++it) {\n\n                // Split the input entry by '='\n#ifdef _USE_BOOST\n                std::string str_tmp = boost::trim_copy(*it);\n#else\n                std::string str_tmp = trim(*it);\n#endif\n                if (!str_tmp.empty()) {\n#ifdef _USE_BOOST\n                    boost::split(str_varval, str_tmp, boost::is_any_of(\"=\"));\n#else\n                    str_varval = my_split(str_tmp, '=');\n#endif\n                    if (str_varval.size() != 2) {\n                        exit(\"get_var_dict\",\n                                    \"Unacceptable format\");\n                    }\n#ifdef _USE_BOOST\n                    key = boost::to_upper_copy(boost::trim_copy(str_varval[0]));\n                    val = boost::trim_copy(str_varval[1]);\n#else\n                    key = trim(str_varval[0]);\n                    std::transform(key.begin(), key.end(), key.begin(), toupper);\n                    val = trim(str_varval[1]);\n#endif\n                    if (keyword_set.find(key) == keyword_set.end()) {\n                        std::cout << \"Could not recognize the variable \" << key << std::endl;\n                        exit(\"get_var_dict\",\n                                    \"Invalid variable found\");\n                    }\n\n                    if (var_dict.find(key) != var_dict.end()) {\n                        std::cout << \"Variable \" << key\n                                  << \" appears twice in the input file.\" << std::endl;\n                        exit(\"get_var_dict\",\n                                    \"Redundant input parameter\");\n                    }\n\n                    // If everything is OK, add the variable and the corresponding value\n                    // to the dictionary.\n\n                    var_dict.insert(std::map<std::string, std::string>::value_type(key, val));\n                }\n            }\n        }\n    } else {\n\n        while (std::getline(ifs_input, line)) {\n\n            // Ignore comment region\n            pos_first_comment_tag = line.find_first_of('#');\n\n            if (pos_first_comment_tag == std::string::npos) {\n                line_wo_comment = line;\n            } else {\n                line_wo_comment = line.substr(0, pos_first_comment_tag);\n            }\n#ifdef _USE_BOOST\n            boost::trim_left(line_wo_comment);\n#else\n            line_tmp = line_wo_comment;\n            line_wo_comment = ltrim(line_tmp);\n#endif\n            if (line_wo_comment.empty()) continue;\n            if (is_endof_entry(line_wo_comment)) break;\n\n            // Split the input line by ';'\n#ifdef _USE_BOOST\n            boost::split(str_entry, line_wo_comment, boost::is_any_of(\";\"));\n#else\n            str_entry = my_split(line_wo_comment, ';');\n#endif\n            for (auto &it: str_entry) {\n\n                // Split the input entry by '='\n\n#ifdef _USE_BOOST\n                std::string str_tmp = boost::trim_copy(*it);\n#else\n                std::string str_tmp = trim(it);\n#endif\n                if (!str_tmp.empty()) {\n#ifdef _USE_BOOST\n                    boost::split(str_varval, str_tmp, boost::is_any_of(\"=\"));\n#else\n                    str_varval = my_split(str_tmp, '=');\n#endif\n\n                    if (str_varval.size() != 2) {\n                        exit(\"get_var_dict\",\n                                    \"Unacceptable format\");\n                    }\n\n#ifdef _USE_BOOST\n                    key = boost::to_upper_copy(boost::trim_copy(str_varval[0]));\n                    val = boost::trim_copy(str_varval[1]);\n#else\n                    key = trim(str_varval[0]);\n                    std::transform(key.begin(), key.end(), key.begin(), toupper);\n                    val = trim(str_varval[1]);\n#endif\n\n                    if (keyword_set.find(key) == keyword_set.end()) {\n                        std::cout << \"Could not recognize the variable \"\n                                  << key << std::endl;\n                        exit(\"get_var_dict\",\n                                    \"Invalid variable found\");\n                    }\n\n                    if (var_dict.find(key) != var_dict.end()) {\n                        std::cout << \"Variable \" << key\n                                  << \" appears twice in the input file.\" << std::endl;\n                        exit(\"get_var_dict\",\n                                    \"Redundant input parameter\");\n                    }\n\n                    // If everything is OK, add the variable and the corresponding value\n                    // to the dictionary.\n\n                    var_dict.insert(std::map<std::string, std::string>::value_type(key, val));\n                }\n            }\n        }\n\n    }\n    keyword_set.clear();\n}\n\nbool Input::is_endof_entry(const std::string &str) const\n{\n    return str[0] == '/';\n}\n\nvoid Input::split_str_by_space(const std::string &str,\n                               std::vector<std::string> &str_vec) const\n{\n    std::string str_tmp;\n    std::istringstream is(str);\n\n    str_vec.clear();\n\n    while (1) {\n        str_tmp.clear();\n        is >> str_tmp;\n        if (str_tmp.empty()) {\n            break;\n        }\n        str_vec.push_back(str_tmp);\n    }\n    str_tmp.clear();\n}\n\ntemplate<typename T>\nvoid Input::assign_val(T &val,\n                       const std::string &key,\n                       std::map<std::string, std::string> dict)\n{\n    // Assign a value to the variable \"key\" using the boost::lexica_cast.\n\n    if (!dict[key].empty()) {\n        try {\n            val = boost::lexical_cast<T>(dict[key]);\n        }\n        catch (std::exception &e) {\n            std::cout << e.what() << std::endl;\n            std::string str_tmp = \"Invalid entry for the \" + key + \" tag.\\n\";\n            str_tmp += \" Please check the input value.\";\n            exit(\"assign_val\", str_tmp.c_str());\n        }\n    }\n}\n\ntemplate<typename T_to, typename T_from>\nT_to Input::my_cast(T_from const &x)\n{\n    std::stringstream ss;\n    T_to ret;\n\n    ss << x;\n    ss >> ret;\n\n    return ret;\n}\n", "meta": {"hexsha": "c12c46441163692b63bfd31a82ef4258e84a12ab", "size": 39839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/parsephon.cpp", "max_stars_repo_name": "by-student-2017/alamode", "max_stars_repo_head_hexsha": "97bc8daccadc4bbc8859daf9098af0bc810ae463", "max_stars_repo_licenses": ["MIT"], "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/parsephon.cpp", "max_issues_repo_name": "by-student-2017/alamode", "max_issues_repo_head_hexsha": "97bc8daccadc4bbc8859daf9098af0bc810ae463", "max_issues_repo_licenses": ["MIT"], "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/parsephon.cpp", "max_forks_repo_name": "by-student-2017/alamode", "max_forks_repo_head_hexsha": "97bc8daccadc4bbc8859daf9098af0bc810ae463", "max_forks_repo_licenses": ["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.4932806324, "max_line_length": 105, "alphanum_fraction": 0.5594015914, "num_tokens": 9918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020279, "lm_q2_score": 0.03410042792094889, "lm_q1q2_score": 0.008456477353805664}}
{"text": "/*\r\n===============================================================================\r\n   This is a re-implementation of TM-align algorithm in C/C++. The code was \r\n   is written by Jianyi Yang and later updated by Jianjie Wu at The Yang Zhang \r\n   lab, Department of Computational Medicine and Bioinformatics, University of \r\n   Michigan, 100 Washtenaw Avenue, Ann Arbor, MI 48109-2218. Please report bugs \r\n   and questions to jianjiew@umich.edu or zhng@umich.edu\r\n\r\n   DISCLAIMER:\r\n     Permission to use, copy, modify, and distribute this program for \r\n     any purpose, with or without fee, is hereby granted, provided that\r\n     the notices on the head, the reference information, and this\r\n     copyright notice appear in all copies or substantial portions of \r\n     the Software. It is provided \"as is\" without express or implied \r\n     warranty.\r\n   *************** updating history ********************************\r\n   2012/01/24: A C/C++ code of TM-align was constructed by Jianyi Yang\r\n   2016/05/21: Several updates of this program were made by Jianjie Wu, including\r\n              (1) fixed several compiling bugs\r\n\t      (2) made I/O of C/C++ version consistent with the Fortran version\r\n\t      (3) added outputs including full-atom and ligand structures\r\n\t      (4) added options of '-i', '-I' and '-m'\r\n   2016/05/25: fixed a bug on PDB file reading\r\n===============================================================================\r\n*/\r\n/* 2017/10 modified by RMR for high throughput running */\r\n\r\n#include \"basic_define.h\"\r\n#include <iomanip>\t//for setprecision in double printout\r\n#include <unistd.h>\r\n\r\n#include <boost/algorithm/string.hpp>\t//to split string\r\n\r\nchar version[20];                          //version \r\n \r\n \r\n//global variables\r\ndouble D0_MIN;                             //for d0\r\ndouble Lnorm;                              //normalization length\r\ndouble score_d8, d0, d0_search, dcu0;      //for TMscore search\r\ndouble **score;            \t\t\t       //Input score table for dynamic programming\r\nbool   **path;                             //for dynamic programming  \r\ndouble **val;                              //for dynamic programming  \r\nint    xlen, ylen, minlen;                 //length of proteins\r\nint tempxlen, tempylen, tempMinlen;\r\ndouble **xa, **ya;                         //for input vectors xa[0...xlen-1][0..2], ya[0...ylen-1][0..2]\r\n                                           //in general, ya is regarded as native structure --> superpose xa onto ya\r\nint    *xresno, *yresno;                   //residue numbers, used in fragment gapless threading \r\ndouble **xtm, **ytm;                       //for TMscore search engine\r\ndouble **xt;                               //for saving the superposed version of r_1 or xtm\r\nchar   *seqx, *seqy;                       //for the protein sequence \r\nint    *secx, *secy;                       //for the secondary structure \r\ndouble **r1, **r2;                         //for Kabsch rotation \r\ndouble t[3], u[3][3];                      //Kabsch translation vector and rotation matrix\r\n\r\nint atomxlen, atomylen;        // length of atoms\r\nint *ia1, *ia2;                // ATOM indices, used for display\r\nchar  **aa1, **aa2;           // \"N\", or \"CA\", or \"C\" \r\ndouble **xyza1, **xyza2;      // for input vectors xa[0...xlen-1][0..2], ya[0...ylen-1][0..2], just for display\r\nchar **ra1, **ra2;           // for the protein sequence \r\nint  *ir1, *ir2;             // residue numbers, used in fragment gapless threading \r\n\r\nchar sequence[10][MAXLEN];// get value from alignment file\r\ndouble TM_ali, rmsd_ali;// TMscore and rmsd from standard_TMscore func, \r\nint L_ali;// Aligned length from standard_TMscore func, \r\n\r\nchar *ins1, *ins2, *ains1, *ains2;// flag characters for data read from PDB file, which begins with \"ATOM\", and locates at s(27), usually are spaces\r\nint **nres1, **nres2;// number of atoms, nres1(i,j): the number of atoms for ith residue, j usually is 32 for a space\r\n\r\n\r\n//argument variables\r\nchar out_reg[MAXLEN];\r\ndouble Lnorm_ass, Lnorm_d0, d0_scale, d0A, d0B, d0u, d0a;\r\nbool o_opt, a_opt, u_opt, d_opt, v_opt;\r\nbool i_opt;// flags for -i, with user given initial alignment file\r\nbool m_opt;// flags for -m, output rotation matrix\r\nbool I_opt;// flags for -I, stick to user given initial alignment file\r\n\r\ndouble TM3, TM4, TM5;\r\n\r\nusing namespace std;\r\n\r\n\r\n#include \"basic_fun.h\"\r\n#include \"NW.h\"\r\n#include \"Kabsch.h\"\r\n#include \"TMalign.h\"\r\n\r\n\r\nvoid print_help(char *arg)\r\n{\r\n\r\n\tcout <<endl;\r\n\tcout << \" ***************************************************************************************************\" << endl\r\n\t\t << \" * TM-align (Version \"<< version <<\"): An algorithm for protein structure alignment and comparison        *\" << endl\r\n\t\t << \" * Based on statistics:                                                                            *\" << endl\r\n\t\t << \" *          0.0 < TM-score < 0.30, random structural similarity                                    *\" << endl\r\n\t\t << \" *          0.5 < TM-score < 1.00, in about the same fold                                          *\" << endl\r\n\t\t << \" * Reference: Y Zhang and J Skolnick, Nucl Acids Res 33, 2302-9 (2005)                             *\" << endl\r\n\t\t << \" * Please email your comments and suggestions to Yang Zhang (zhng@umich.edu)                       *\" << endl\r\n\t\t << \" ** Modified by Rostam Razban (10/2017) for high-throughput jobs                                   *\" << endl\r\n\t\t << \" ** automatically accesses pdb files for respective organism in proteomevis_scripts repository     *\" << endl\r\n\t\t << \" ** for unadultered version, download from Yang Zhang Group Website                                *\" << endl\r\n\t\t << \" ***************************************************************************************************\" << endl;\t\r\n\tcout << endl\r\n\t\t << \" Usage: .\" << arg << \" [Options] (run in valid organism directory)\" << endl << endl\r\n\t\t << \" Options:\" << endl\r\n\t\t << \"       -h    print this help\" << endl << endl\r\n\t\t << \"       --all    run all pdb files in 0-identify_structure/3-length_check/'organism'/seq2struc.txt\" << endl << endl\r\n\t\t << \"       --extra    only run for extra pdb files in extra.txt (generate extra.txt file by running setup_extra_file.py)\" << endl << endl\r\n\t\t << \"       --EXTRA    only run for extra pdb files for yeast_ecoli (need to still run --extra as well)\" << endl << endl\r\n\t\t << \"       (Options -u, -a, -d -o won't change the final structure alignment)\" << endl << endl\r\n\t\t << \" Example usages:\" << endl\r\n\t\t << \"        \"<< arg <<\" --all\" << endl\r\n\t\t << \"        \"<< arg <<\" --extra\" << endl;\r\n       \r\n  exit(EXIT_SUCCESS);\r\n\r\n}\t//worth adding option to compute list? or maybe faster way is to use GPU. do list cuz talkes time to parse initiate program and parse output \r\n\r\n\r\n\r\nvoid parameter_set4search(int xlen, int ylen)\r\n{\r\n\t//parameter initilization for searching: D0_MIN, Lnorm, d0, d0_search, score_d8\r\n\tD0_MIN=0.5; \r\n\tdcu0=4.25;                       //update 3.85-->4.25\r\n \r\n\tLnorm=getmin(xlen, ylen);        //normaliz TMscore by this in searching\r\n    if(Lnorm<=19)                    //update 15-->19\r\n    {\r\n        d0=0.168;                   //update 0.5-->0.168\r\n    }\r\n    else\r\n    {\r\n        d0=(1.24*pow((Lnorm*1.0-15), 1.0/3)-1.8);\r\n    }\r\n\tD0_MIN=d0+0.8;              //this should be moved to above\r\n    d0=D0_MIN;                  //update: best for search    \r\n\r\n\r\n\td0_search=d0;\t\r\n\tif(d0_search>8) d0_search=8;\r\n\tif(d0_search<4.5) d0_search=4.5;\r\n\r\n\r\n    score_d8=1.5*pow(Lnorm*1.0, 0.3)+3.5; //remove pairs with dis>d8 during search & final\r\n}\r\n\r\nvoid parameter_set4final(double len)\r\n{\r\n\tD0_MIN=0.5; \r\n \r\n\tLnorm=len;            //normaliz TMscore by this in searching\r\n    if(Lnorm<=21)         \r\n    {\r\n        d0=0.5;          \r\n    }\r\n    else\r\n    {\r\n        d0=(1.24*pow((Lnorm*1.0-15), 1.0/3)-1.8);\r\n    }\r\n    if(d0<D0_MIN) d0=D0_MIN;   \r\n\r\n\td0_search=d0;\t\r\n\tif(d0_search>8) d0_search=8;\r\n\tif(d0_search<4.5) d0_search=4.5;  \r\n\r\n}\r\n\r\n\r\nvoid parameter_set4scale(int len, double d_s)\r\n{\r\n \r\n\td0=d_s;          \r\n\tLnorm=len;            //normaliz TMscore by this in searching\r\n\r\n\td0_search=d0;\t\r\n\tif(d0_search>8) d0_search=8;\r\n\tif(d0_search<4.5) d0_search=4.5;  \r\n\r\n}\r\n\r\nvector<string> get_pdb_chain_list(string xread_pdb)\r\n{\r\n\tifstream myfile;\r\n\tvector<string> pdb_chain_list;\r\n\tmyfile.open(xread_pdb.c_str());\r\n\tstring firstLine;\r\n\tgetline(myfile, firstLine);\r\n\tif( !(myfile.is_open()) )\r\n\t{   \r\n\tstd::cout << \"Error Opening File\";\r\n\tstd::exit(0);   \r\n\t}\r\n\r\n\tstd::vector<std::string> words;\r\n\tboost::split(words, firstLine, boost::is_any_of(\"\\t\"), boost::token_compress_on);\r\n\r\n\tint pdb_i;\t//unable to get std:find() to work\r\n\tfor( int a = 0; a < words.size(); a = a + 1 ) {\r\n\t\tif (words[a]==\"pdb\") {\r\n\t\t\tpdb_i = a;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tstd::string line;\r\n\twhile( myfile.good() )\r\n\t{\r\n\t\tstd::getline( myfile, line);\r\n\t\tstd::stringstream ss(line);\r\n\t\tstd::string word;\r\n\t\tint count=0;\r\n\t\twhile (std::getline(ss,word,'\\t'))\r\n\t\t{\r\n//\t\t\tstd::cout << \"Word: \" << word << std::endl;\r\n//\t\t\tstd::cout << count << std::endl;\r\n\t\t\tif (count==pdb_i){\r\n\t\t\t\tpdb_chain_list.push_back(word);\r\n\t\t\t\tbreak;\t\r\n\t\t\t}\r\n\t\t\tcount++;\r\n\t\t}\r\n\t}\t\r\n\t// remove duplicates from list\r\n\tsort( pdb_chain_list.begin(), pdb_chain_list.end() );\r\n\tpdb_chain_list.erase( unique( pdb_chain_list.begin(), pdb_chain_list.end() ), pdb_chain_list.end() );\r\n\treturn pdb_chain_list;\r\n}\r\n\r\n\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tstrcpy(version, \"20160521\");\r\n\r\n    if (argc < 2) \r\n    {\r\n        print_help(argv[0]);        \r\n    } \r\n\t\r\n\t\r\n\tclock_t t1, t2;\r\n\tt1 = clock();\r\n\r\n    /*********************************************************************************/\r\n\t/*                                get argument                                   */ \r\n    /*********************************************************************************/\r\n    char xname[MAXLEN], yname[MAXLEN],  Lnorm_ave[MAXLEN];\r\n\tbool A_opt, B_opt, h_opt=false;\r\n\tA_opt = B_opt = o_opt = a_opt = u_opt = d_opt = v_opt = false;\r\n\ti_opt = false;// set -i flag to be false\r\n\tm_opt = false;// set -m flag to be false\r\n\tchar fname_lign[MAXLEN] = \"\";\r\n\tchar fname_matrix[MAXLEN] = \"\";// set names to \"\"\r\n\tI_opt = false;// set -I flag to be false\r\n\tbool extra_opt = false;\r\n\tbool extra_ecoli = false;\r\n\r\n\tint nameIdx = 0;\t//no longer needed\r\n\tstd::string xread_pdb; \r\n\tstd::string yread_pdb; \r\n\tstd::string pre_xname; \r\n\tstd::string pre_yname; \r\n\r\n//\tchar organism[MAXLEN];\r\n\r\n\tfor(int i = 1; i < argc; i++)\r\n\t{\r\n\t\tif ( !strcmp(argv[i],\"-o\") && i < (argc-1) ) \r\n\t\t{\r\n\t\t\tstrcpy(out_reg, argv[i + 1]);      o_opt = true; i++;\r\n\t\t}\r\n\t\telse if ( !strcmp(argv[i],\"-u\") && i < (argc-1) ) \r\n\t\t{\r\n\t\t\tLnorm_ass = atof(argv[i + 1]); u_opt = true; i++;\r\n\t\t}\r\n\t\telse if ( !strcmp(argv[i],\"-a\") && i < (argc-1) ) \r\n\t\t{\r\n\t\t\tstrcpy(Lnorm_ave, argv[i + 1]);     a_opt = true; i++;\r\n\t\t}\t//set a_opt to true always\r\n\t\telse if ( !strcmp(argv[i],\"-d\") && i < (argc-1) ) \r\n\t\t{\r\n\t\t\td0_scale = atof(argv[i + 1]); d_opt = true; i++;\r\n\t\t}\r\n\t\telse if ( !strcmp(argv[i],\"-v\") ) \r\n\t\t{\r\n\t\t\tv_opt = true; \r\n\t\t}\r\n\t\telse if ( !strcmp(argv[i],\"-h\") ) \r\n\t\t{ \r\n\t\t\th_opt = true; \r\n\t\t}\r\n\t\telse if ( !strcmp(argv[i],\"-i\") && i < (argc-1) ) \r\n\t\t{\r\n\t\t\tstrcpy(fname_lign, argv[i + 1]);      i_opt = true; i++;\r\n\t\t}\r\n\t\telse if (!strcmp(argv[i], \"-m\") && i < (argc-1) ) \r\n\t\t{\r\n\t\t\tstrcpy(fname_matrix, argv[i + 1]);      m_opt = true; i++;\r\n\t\t}// get filename for rotation matrix\r\n\t\telse if (!strcmp(argv[i], \"-I\") && i < (argc-1) ) \r\n\t\t{\r\n\t\t\tstrcpy(fname_lign, argv[i + 1]);      I_opt = true; i++;\r\n\t\t}\r\n\t\telse if ( !strcmp(argv[i],\"--extra\") || !strcmp(argv[i],\"--EXTRA\")) \r\n\t\t{\r\n\t\t\textra_opt = true; \r\n\t\t\tif (!strcmp(argv[i],\"--EXTRA\")){\r\n\t\t\t\textra_ecoli = true;\t\r\n\t\t\t} \r\n\t\t}\r\n\t\telse{}\t\r\n\t}\r\n\t\r\n\tstd::string cwd = getcwd(NULL, 0);\t//organism determined from the directory in which the program is called\r\n\tstd::size_t found = cwd.find_last_of(\"/\\\\\");\r\n\tstd::string organism = cwd.substr(found+1);\r\n\r\n\tstd::string dir_read = \"../../../0-identify_structure/3-length_check/\";\r\n\tstd::string dir_pdb = \"../../../0-identify_structure/2-get_pdb_chain/\";\r\n\tif (organism == \"yeast\" || organism == \"ecoli\")\r\n\t{\r\n\t\tyread_pdb = dir_read + organism + \"/seq2struc.txt\" ;\r\n\t\tpre_xname = dir_pdb + organism + \"/\" ;\r\n\t\tpre_yname = pre_xname;\r\n\t\tif (extra_opt){\r\n\t\t\txread_pdb = \"extra.txt\";\r\n\t\t}\r\n\t\telse {\r\n\t\t\txread_pdb = yread_pdb;\t\r\n\t\t}\r\n\t}\r\n\telse if (organism == \"yeast_ecoli\")\r\n\t{\r\n\t\tif (not extra_opt){\r\n\t\t\txread_pdb = dir_read + \"yeast\" + \"/seq2struc.txt\" ;\r\n\t\t\tyread_pdb = dir_read + \"ecoli\" + \"/seq2struc.txt\" ;\r\n\t\t}\r\n\t\telse if (extra_ecoli){\r\n\t\t\txread_pdb = dir_read + \"yeast\" + \"/seq2struc.txt\" ;\t\t\r\n\t\t\tyread_pdb = \"../ecoli/extra.txt\";\r\n\t\t}\r\n\t\telse if (not extra_ecoli){\r\n\t\t\txread_pdb = \"../yeast/extra.txt\";\t\r\n\t\t\tyread_pdb = \"extra.txt\" ;\t\t\r\n\t\t}\r\n\t\telse{}\r\n\r\n\t\tpre_xname = dir_pdb + \"yeast/\";\t\r\n\t\tpre_yname = dir_pdb + \"ecoli/\";\r\n\t}\r\n\telse {\r\n\t\tcout << \"Make sure to run in valid organism directory\" << endl;\r\n\t\tprint_help(argv[0]);    \t\t\t\r\n\t}\r\n\r\n\tif(!B_opt || !A_opt)\r\n\t{\r\n\r\n\t\tif( h_opt )\r\n\t\t{\r\n\t\t\tprint_help(argv[0]);    \t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tif(v_opt)\r\n\t\t{\r\n\t\t\tcout <<endl;\r\n\t\t\tcout << \" *****************************************************************************\" << endl\r\n\t\t\t\t << \" * TM-align (Version \"<< version <<\"): A protein structural alignment algorithm     *\" << endl\r\n\t\t\t\t << \" * Reference: Y Zhang and J Skolnick, Nucl Acids Res 33, 2302-9 (2005)       *\" << endl\r\n\t\t\t\t << \" * Please email your comments and suggestions to Yang Zhang (zhng@umich.edu) *\" << endl\r\n\t\t\t\t << \" *****************************************************************************\" << endl;\t\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t}\r\n/*\r\n\tif( !B_opt )\r\n\t{\r\n\t\tcout << \"Please provide structure B\" << endl;\r\n\t\texit(EXIT_FAILURE);\r\n\t}\t\t\r\n\tif( !A_opt )\r\n\t{\r\n\t\tcout << \"Please provide structure A\" << endl;\r\n\t\texit(EXIT_FAILURE);\r\n\t}\r\n*/\r\n\r\n\tif( a_opt )\r\n\t{\r\n\t\tif(!strcmp(Lnorm_ave, \"T\"))\r\n\t\t{\r\n\t\t}\r\n\t\telse if(!strcmp(Lnorm_ave, \"F\"))\r\n\t\t{\r\n\t\t\ta_opt=false;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tcout << \"Wrong value for option -a!  It should be T or F\" << endl;\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t}\r\n\tif( u_opt )\r\n\t{\r\n\t\tif(Lnorm_ass<=0)\r\n\t\t{\r\n\t\t\tcout << \"Wrong value for option -u!  It should be >0\" << endl;\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t}\r\n\tif( d_opt )\r\n\t{\r\n\t\tif(d0_scale<=0)\r\n\t\t{\r\n\t\t\tcout << \"Wrong value for option -d!  It should be >0\" << endl;\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t}\r\n\t////// read initial alignment file from 'alignment.txt' //////\r\n\tstring basename = string(argv[0]);\r\n\tint idx = basename.find_last_of(\"\\\\\");\r\n\tbasename = basename.substr(0, idx + 1);\r\n\tif (i_opt || I_opt)// Ask TM-align to start with an alignment,specified in fasta file 'align.txt'\r\n\t{\r\n\t\tif (fname_lign == \"\")\r\n\t\t{\r\n\t\t\tcout << \"Please provide a file name for option -i!\" << endl;\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t\t// open alignment file\r\n\t\tint n_p = 0;// number of structures in alignment file\r\n\t\tstring line;\r\n\r\n\t\tstring fullpath = basename + fname_lign;\r\n\t\tchar path1[1000];\r\n\t\tstrcpy(path1, fullpath.c_str());\r\n\t\tifstream fileIn(path1);\r\n\t\tif (fileIn.is_open())\r\n\t\t{\r\n\t\t\tbool bContinue = true;\r\n\t\t\twhile (fileIn.good() && bContinue)\r\n\t\t\t{\r\n\t\t\t\tgetline(fileIn, line);\r\n\t\t\t\tif (line.compare(0, 1, \">\") == 0)// Flag for a new structure\r\n\t\t\t\t{\r\n\t\t\t\t\tstrcpy(sequence[n_p], \"\");\r\n\t\t\t\t\tn_p++;\r\n\t\t\t\t\tif (n_p > 2)\r\n\t\t\t\t\t\tbContinue = false;\r\n\t\t\t\t}\r\n\t\t\t\telse// Read data\r\n\t\t\t\t{\r\n\t\t\t\t\tif (n_p > 0 && line!=\"\")\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstrcat(sequence[n_p-1], line.c_str());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfileIn.close();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tcout << \"\\nAlignment file does not exist.\\n\";\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t\r\n\t\tif (n_p < 2)\r\n\t\t{\r\n\t\t\tcout << \"\\nERROR: Fasta format is wrong, two proteins should be included.\\n\";\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (strlen(sequence[0]) != strlen(sequence[1]))\r\n\t\t\t{\r\n\t\t\t\tcout << \"\\nWarning: FASTA format may be wrong, the length in alignment should be equal respectively to the aligned proteins.\\n\";\r\n\t\t\t\texit(EXIT_FAILURE);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (m_opt)// Output TM - align rotation matrix: matrix.txt\r\n\t{\r\n\t\tif (fname_matrix == \"\")\r\n\t\t{\r\n\t\t\tcout << \"Please provide a file name for option -m!\" << endl;\r\n\t\t\texit(EXIT_FAILURE);\r\n\t\t}\r\n\t}\r\n\r\n\ta_opt = true;\t//always calculate avg TM\r\n\r\n\tvector<string> xpdb_chain_list = get_pdb_chain_list(xread_pdb);\r\n\tvector<string> ypdb_chain_list = get_pdb_chain_list(yread_pdb);\r\n\r\n\tofstream outfile(\"output.txt\");\r\n\toutfile << \"pdb1\\tpdb2\\tTM\\tSID\\tTM1\\tTM2\\tsid\\tnal\\talign1\\talign2\\n\";\r\n\tfor( int a = 0; a < xpdb_chain_list.size(); a = a + 1 ) {\r\n\t\tstrcpy(xname, pre_xname.c_str());\r\n\t\tstrcat (xname, xpdb_chain_list[a].c_str());\r\n\t\tstrcat (xname, \".pdb\");\r\n\r\n\tfor( int b = 0; b < ypdb_chain_list.size(); b = b + 1 ) {\t\r\n\t\tstrcpy(yname, pre_yname.c_str());\r\n\t\tstrcat (yname, ypdb_chain_list[b].c_str());\r\n\t\tstrcat (yname, \".pdb\");\r\n\r\n\t\tvector<string>::iterator it_y_in_x = std::find(xpdb_chain_list.begin(), xpdb_chain_list.end(), ypdb_chain_list[b]);\r\n\t\tif( it_y_in_x != xpdb_chain_list.end()) {\r\n\t\t\tvector<string>::iterator it_x_in_y = std::find(ypdb_chain_list.begin(), ypdb_chain_list.end(), xpdb_chain_list[a]);\r\n\t\t\tint pos_x_in_y = distance(ypdb_chain_list.begin(), it_x_in_y);\r\n\t\t\tif (pos_x_in_y <= b){\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t}\r\n\r\n//\t\tcout << xname << \" \" << yname << endl;//\tfind which structure giving trouble\r\n\r\n    /*********************************************************************************/\r\n\t/*                                load data                                      */ \r\n    /*********************************************************************************/\r\n\r\n    load_PDB_allocate_memory(xname, yname);\r\n\r\n\r\n    \r\n\r\n    /*********************************************************************************/\r\n\t/*                                parameter set                                  */ \r\n    /*********************************************************************************/\r\n\tparameter_set4search(xlen, ylen);          //please set parameters in the function\r\n    int simplify_step     = 40;               //for similified search engine\r\n    int score_sum_method  = 8;                //for scoring method, whether only sum over pairs with dis<score_d8\r\n        \r\n\tint i;\r\n    int *invmap0          = new int[ylen+1]; \r\n    int *invmap           = new int[ylen+1]; \r\n    double TM, TMmax=-1;\r\n\tfor(i=0; i<ylen; i++)\r\n\t{\r\n\t\tinvmap0[i]=-1;\r\n\t}\t\r\n\r\n\r\n\r\n\tdouble ddcc=0.4;\r\n\tif(Lnorm <= 40) ddcc=0.1;   //Lnorm was setted in parameter_set4search\r\n\tdouble local_d0_search = d0_search;\r\n\r\n\t//*********************************************************************************//\r\n\t//                  get initial alignment from user's input:                       //\r\n\t//                  Stick to the initial alignment                                 //\r\n\t//*********************************************************************************//\r\n\tchar dest[1000];\r\n\tbool bAlignStick = false;\r\n\tif (I_opt)// if input has set parameter for \"-I\"\r\n\t{\r\n\t\tfor (int j = 1; j < ylen; j++)// Set aligned position to be \"-1\"\r\n\t\t\tinvmap[j] = -1;\r\n\r\n\t\tint i1 = -1;// in C version, index starts from zero, not from one\r\n\t\tint i2 = -1;\r\n\t\tint L1 = strlen(sequence[0]);\r\n\t\tint L2 = strlen(sequence[1]);\r\n\t\tint L = min(L1, L2);// Get positions for aligned residues\r\n\t\tfor (int kk1 = 0; kk1 < L; kk1++)\r\n\t\t{\r\n\t\t\tif (sequence[0][kk1] != '-')\r\n\t\t\t\ti1++;\r\n\t\t\tif (sequence[1][kk1] != '-')\r\n\t\t\t{\r\n\t\t\t\ti2++;\r\n\t\t\t\tif (i2 >= ylen || i1 >= xlen)\r\n\t\t\t\t\tkk1 = L;\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif (sequence[0][kk1] != '-')\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tinvmap[i2] = i1;\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\t\r\n\t\t//--------------- 2. Align proteins from original alignment\r\n\t\tdouble prevD0_MIN = D0_MIN;// stored for later use\r\n\t\tint prevLnorm = Lnorm;\r\n\t\tdouble prevd0 = d0;\r\n\t\tTM_ali = standard_TMscore(xa, ya, xlen, ylen, invmap, L_ali, rmsd_ali);\r\n\t\tD0_MIN = prevD0_MIN;\r\n\t\tLnorm = prevLnorm;\r\n\t\td0 = prevd0;\r\n\t\tTM = detailed_search_standard(xa, ya, xlen, ylen, invmap, t, u, 40, 8, local_d0_search, true);\r\n\t\tif (TM > TMmax)\r\n\t\t{\r\n\t\t\tTMmax = TM;\r\n\t\t\tfor (i = 0; i<ylen; i++)\r\n\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t}\r\n\t\tbAlignStick = true;\r\n\t}\r\n\r\n    /*********************************************************************************/\r\n\t/*         get initial alignment with gapless threading                          */ \r\n    /*********************************************************************************/\r\n\tif (!bAlignStick)\r\n\t{\r\n\t\tget_initial(xa, ya, xlen, ylen, invmap0);\r\n\t\t//find the max TMscore for this initial alignment with the simplified search_engin\r\n\t\tTM = detailed_search(xa, ya, xlen, ylen, invmap0, t, u, simplify_step, score_sum_method, local_d0_search);\r\n\t\tif (TM>TMmax)\r\n\t\t{\r\n\t\t\tTMmax = TM;\r\n\t\t}\r\n\t\t//run dynamic programing iteratively to find the best alignment\r\n\t\tTM = DP_iter(xa, ya, xlen, ylen, t, u, invmap, 0, 2, 30, local_d0_search);\r\n\t\tif (TM>TMmax)\r\n\t\t{\r\n\t\t\tTMmax = TM;\r\n\t\t\tfor (int i = 0; i<ylen; i++)\r\n\t\t\t{\r\n\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\r\n\t\t/*********************************************************************************/\r\n\t\t/*         get initial alignment based on secondary structure                    */\r\n\t\t/*********************************************************************************/\r\n\t\tget_initial_ss(xa, ya, xlen, ylen, invmap);\r\n\t\tTM = detailed_search(xa, ya, xlen, ylen, invmap, t, u, simplify_step, score_sum_method, local_d0_search);\r\n\t\tif (TM>TMmax)\r\n\t\t{\r\n\t\t\tTMmax = TM;\r\n\t\t\tfor (int i = 0; i<ylen; i++)\r\n\t\t\t{\r\n\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (TM > TMmax*0.2)\r\n\t\t{\r\n\t\t\tTM = DP_iter(xa, ya, xlen, ylen, t, u, invmap, 0, 2, 30, local_d0_search);\r\n\t\t\tif (TM>TMmax)\r\n\t\t\t{\r\n\t\t\t\tTMmax = TM;\r\n\t\t\t\tfor (int i = 0; i<ylen; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/*********************************************************************************/\r\n\t\t/*         get initial alignment based on local superposition                    */\r\n\t\t/*********************************************************************************/\r\n\t\t//=initial5 in original TM-align\r\n\t\tif (get_initial5(xa, ya, xlen, ylen, invmap))\r\n\t\t{\r\n\t\t\tTM = detailed_search(xa, ya, xlen, ylen, invmap, t, u, simplify_step, score_sum_method, local_d0_search);\r\n\t\t\tif (TM>TMmax)\r\n\t\t\t{\r\n\t\t\t\tTMmax = TM;\r\n\t\t\t\tfor (int i = 0; i<ylen; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (TM > TMmax*ddcc)\r\n\t\t\t{\r\n\t\t\t\tTM = DP_iter(xa, ya, xlen, ylen, t, u, invmap, 0, 2, 2, local_d0_search);\r\n\t\t\t\tif (TM>TMmax)\r\n\t\t\t\t{\r\n\t\t\t\t\tTMmax = TM;\r\n\t\t\t\t\tfor (int i = 0; i<ylen; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tinvmap0[i] = invmap[i];\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\telse\r\n\t\t{\r\n\t\t\tcout << endl << endl << \"Warning: initial alignment from local superposition fail!\" << endl << endl << endl;\r\n\t\t}\r\n\r\n\r\n\r\n\r\n\r\n\t\t/*********************************************************************************/\r\n\t\t/*    get initial alignment based on previous alignment+secondary structure      */\r\n\t\t/*********************************************************************************/\r\n\t\t//=initial3 in original TM-align\r\n\t\tget_initial_ssplus(xa, ya, xlen, ylen, invmap0, invmap);\r\n\t\tTM = detailed_search(xa, ya, xlen, ylen, invmap, t, u, simplify_step, score_sum_method, local_d0_search);\r\n\t\tif (TM>TMmax)\r\n\t\t{\r\n\t\t\tTMmax = TM;\r\n\t\t\tfor (i = 0; i<ylen; i++)\r\n\t\t\t{\r\n\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (TM > TMmax*ddcc)\r\n\t\t{\r\n\t\t\tTM = DP_iter(xa, ya, xlen, ylen, t, u, invmap, 0, 2, 30, local_d0_search);\r\n\t\t\tif (TM>TMmax)\r\n\t\t\t{\r\n\t\t\t\tTMmax = TM;\r\n\t\t\t\tfor (i = 0; i<ylen; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\r\n\r\n\t\t/*********************************************************************************/\r\n\t\t/*        get initial alignment based on fragment gapless threading              */\r\n\t\t/*********************************************************************************/\r\n\t\t//=initial4 in original TM-align\r\n\t\tget_initial_fgt(xa, ya, xlen, ylen, xresno, yresno, invmap);\r\n\t\tTM = detailed_search(xa, ya, xlen, ylen, invmap, t, u, simplify_step, score_sum_method, local_d0_search);\r\n\t\tif (TM>TMmax)\r\n\t\t{\r\n\t\t\tTMmax = TM;\r\n\t\t\tfor (i = 0; i<ylen; i++)\r\n\t\t\t{\r\n\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (TM > TMmax*ddcc)\r\n\t\t{\r\n\t\t\tTM = DP_iter(xa, ya, xlen, ylen, t, u, invmap, 1, 2, 2, local_d0_search);\r\n\t\t\tif (TM>TMmax)\r\n\t\t\t{\r\n\t\t\t\tTMmax = TM;\r\n\t\t\t\tfor (i = 0; i<ylen; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t//*********************************************************************************//\r\n\t\t//                  get initial alignment from user's input:                       //\r\n\t\t//*********************************************************************************//\r\n\t\tif (i_opt)// if input has set parameter for \"-i\"\r\n\t\t{\r\n\t\t\tfor (int j = 0; j < ylen; j++)// Set aligned position to be \"-1\"\r\n\t\t\t\tinvmap[j] = -1;\r\n\t\t\r\n\t\t\tint i1 = -1;// in C version, index starts from zero, not from one \r\n\t\t\tint i2 = -1;\r\n\t\t\tint L1 = strlen(sequence[0]);\r\n\t\t\tint L2 = strlen(sequence[1]);\r\n\t\t\tint L = min(L1, L2);// Get positions for aligned residues\r\n\t\t\tfor (int kk1 = 0; kk1 < L; kk1++)\r\n\t\t\t{\r\n\t\t\t\tif (sequence[0][kk1] != '-')\r\n\t\t\t\t\ti1++;\r\n\t\t\t\tif (sequence[1][kk1] != '-')\r\n\t\t\t\t{\r\n\t\t\t\t\ti2++;\r\n\t\t\t\t\tif (i2 >= ylen || i1 >= xlen)\r\n\t\t\t\t\t\tkk1 = L;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (sequence[0][kk1] != '-')\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tinvmap[i2] = i1;\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\r\n\t\t\t//--------------- 2. Align proteins from original alignment\r\n\t\t\tdouble prevD0_MIN = D0_MIN;// stored for later use\r\n\t\t\tint prevLnorm = Lnorm;\r\n\t\t\tdouble prevd0 = d0;\r\n\t\t\tTM_ali = standard_TMscore(xa, ya, xlen, ylen, invmap, L_ali, rmsd_ali);\r\n\t\t\tD0_MIN = prevD0_MIN;\r\n\t\t\tLnorm = prevLnorm;\r\n\t\t\td0 = prevd0;\r\n\r\n\t\t\tTM = detailed_search_standard(xa, ya, xlen, ylen, invmap, t, u, 40, 8, local_d0_search, true);\r\n\t\t\tif (TM > TMmax)\r\n\t\t\t{\r\n\t\t\t\tTMmax = TM;\r\n\t\t\t\tfor (i = 0; i<ylen; i++)\r\n\t\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t}\r\n\t\t\tTM = DP_iter(xa, ya, xlen, ylen, t, u, invmap, 0, 2, 30, local_d0_search);// Different from get_initial, get_initial_ss and get_initial_ssplus\r\n\t\t\tif (TM>TMmax)\r\n\t\t\t{\r\n\t\t\t\tTMmax = TM;\r\n\t\t\t\tfor (i = 0; i<ylen; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tinvmap0[i] = invmap[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t\r\n    //*********************************************************************************//\r\n    //     The alignment will not be changed any more in the following                 //\r\n    //*********************************************************************************//\r\n\t//check if the initial alignment is generated approately\t\r\n\tbool flag=false;\r\n\tfor(i=0; i<ylen; i++)\r\n\t{\r\n\t\tif(invmap0[i]>=0)\r\n\t\t{\r\n\t\t\tflag=true;\r\n\t\t\tbreak;\t\t\t\r\n\t\t}\t\t\t\r\n\t}\t\t\r\n\tif(!flag) \r\n\t{\r\n\t\tcout << \"There is no alignment between the two proteins!\" << endl;\r\n\t\tcout << \"Program stop with no result!\" << endl;\r\n\t\treturn 1;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n    //*********************************************************************************//\r\n    //       Detailed TMscore search engine  --> prepare for final TMscore             //\r\n    //*********************************************************************************//       \r\n    //run detailed TMscore search engine for the best alignment, and \r\n\t//extract the best rotation matrix (t, u) for the best alginment\r\n\tsimplify_step=1;\r\n    score_sum_method=8;\r\n\tTM = detailed_search_standard(xa, ya, xlen, ylen, invmap0, t, u, simplify_step, score_sum_method, local_d0_search, false);\r\n\t\t\r\n\r\n\t//select pairs with dis<d8 for final TMscore computation and output alignment\r\n\tint n_ali8, k=0;\r\n\tint n_ali=0;\r\n\tint *m1, *m2;\r\n\tdouble d;\r\n\tm1=new int[xlen]; //alignd index in x\r\n\tm2=new int[ylen]; //alignd index in y\r\n\tdo_rotation(xa, xt, xlen, t, u);\r\n\tk=0;\r\n    for(int j=0; j<ylen; j++)\r\n    {\r\n        i=invmap0[j];\r\n        if(i>=0)//aligned\r\n        {\r\n\t\t\tn_ali++;        \r\n            d=sqrt(dist(&xt[i][0], &ya[j][0]));\r\n\t\t\tif (d <= score_d8 || (I_opt == true))\r\n\t\t\t{\r\n\t\t\t\tm1[k]=i;\r\n\t\t\t\tm2[k]=j;\r\n\r\n\t\t\t\txtm[k][0]=xa[i][0];\r\n                xtm[k][1]=xa[i][1];\r\n                xtm[k][2]=xa[i][2];\r\n                    \r\n                ytm[k][0]=ya[j][0];\r\n                ytm[k][1]=ya[j][1];\r\n                ytm[k][2]=ya[j][2];\t\t\t\r\n\r\n\t\t\t\tr1[k][0] = xt[i][0];\r\n\t\t\t\tr1[k][1] = xt[i][1];\r\n\t\t\t\tr1[k][2] = xt[i][2];\r\n\t\t\t\tr2[k][0] = ya[j][0];\r\n\t\t\t\tr2[k][1] = ya[j][1];\r\n\t\t\t\tr2[k][2] = ya[j][2];\r\n\t\t\t\t\r\n\t\t\t\tk++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tn_ali8=k;\r\n\r\n\tdouble rmsd0 = 0.0;\r\n\tKabsch(r1, r2, n_ali8, 0, &rmsd0, t, u);// rmsd0 is used for final output, only recalculate rmsd0, not t & u\r\n\trmsd0 = sqrt(rmsd0 / n_ali8);\r\n\r\n\r\n\r\n\r\n    //*********************************************************************************//\r\n    //                               Final TMscore                                     //\r\n    //                     Please set parameters for output                            //\r\n    //*********************************************************************************//\r\n\tdouble rmsd;\r\n\tdouble t0[3], u0[3][3];\r\n\tdouble TM1, TM2;\r\n\tdouble d0_out=5.0;  \r\n    simplify_step=1;\r\n    score_sum_method=0;\r\n\r\n\tdouble d0_0, TM_0;\r\n\tdouble Lnorm_0=ylen;\r\n\t\r\n\t\r\n\t//normalized by length of structure A\r\n\tparameter_set4final(Lnorm_0);\r\n\td0A=d0;\r\n\td0_0=d0A;\r\n\tlocal_d0_search = d0_search;\r\n\tTM1 = TMscore8_search(xtm, ytm, n_ali8, t0, u0, simplify_step, score_sum_method, &rmsd, local_d0_search);\r\n\tTM_0 = TM1;\r\n\r\n\t//normalized by length of structure B\r\n\tparameter_set4final(xlen+0.0);\r\n\td0B=d0;\r\n\tlocal_d0_search = d0_search;\r\n\tTM2 = TMscore8_search(xtm, ytm, n_ali8, t, u, simplify_step, score_sum_method, &rmsd, local_d0_search);\r\n\r\n\r\n\r\n\r\n\r\n\tif(a_opt)\r\n\t{\r\n\t\t//normalized by average length of structures A, B\r\n\t\tLnorm_0=(xlen+ylen)*0.5;\r\n\t\tparameter_set4final(Lnorm_0);\r\n\t\td0a=d0;\r\n\t\td0_0=d0a;\r\n\t\tlocal_d0_search = d0_search;\r\n\r\n\t\tTM3 = TMscore8_search(xtm, ytm, n_ali8, t0, u0, simplify_step, score_sum_method, &rmsd, local_d0_search);\r\n\t\tTM_0=TM3;\r\n\t}\r\n\tif(u_opt)\r\n\t{\t\r\n\t\t//normalized by user assigned length\t\t\r\n\t\tparameter_set4final(Lnorm_ass);\t\t\r\n\t\td0u=d0;\t\t\r\n\t\td0_0=d0u;\r\n\t\tLnorm_0=Lnorm_ass;\r\n\t\tlocal_d0_search = d0_search;\r\n\t\tTM4 = TMscore8_search(xtm, ytm, n_ali8, t0, u0, simplify_step, score_sum_method, &rmsd, local_d0_search);\r\n\t\tTM_0=TM4;\r\n\t}\r\n\tif(d_opt)\r\n\t{\t\r\n\t\t//scaled by user assigned d0\r\n\t\tparameter_set4scale(ylen, d0_scale);\r\n\t\td0_out=d0_scale;\r\n\t\td0_0=d0_scale;\r\n\t\t//Lnorm_0=ylen;\r\n\t\tLnorm_d0=Lnorm_0;\r\n\t\tlocal_d0_search = d0_search;\r\n\t\tTM5 = TMscore8_search(xtm, ytm, n_ali8, t0, u0, simplify_step, score_sum_method, &rmsd, local_d0_search);\r\n\t\tTM_0=TM5;\r\n\t}\r\n\r\n    int ali_len=xlen+ylen; //maximum length of alignment\r\n      char *seqM, *seqxA, *seqyA;\r\n      seqM=new char[ali_len];\r\n      seqxA=new char[ali_len];\r\n      seqyA=new char[ali_len];\r\n\tint seq_id = output_results(xname, yname, xlen, ylen, t0, u0, TM1, TM2, rmsd0, d0_out, m1, m2, n_ali8, n_ali, TM_0, Lnorm_0, d0_0, fname_matrix, seqM, seqxA, seqyA);\t//this is a hack. no longer need full output fxn\r\n\toutfile << xpdb_chain_list[a] << \"\\t\" << ypdb_chain_list[b] << \"\\t\"; \r\n\toutfile << std::setprecision(4) << TM3 << \"\\t\" << (float)seq_id/(float)n_ali8 << \"\\t\" << TM1 << \"\\t\" << TM2 << \"\\t\" << seq_id << \"\\t\" << n_ali8 << \"\\t\" << seqxA << \"\\t\" << seqy << \"\\n\";\r\n\r\n\t    //*********************************************************************************//\r\n    //                            Done! Free memory                                    //\r\n    //*********************************************************************************//           \r\n\tfree_memory();\r\n\r\n    delete [] invmap0;\r\n    delete [] invmap;\r\n\tdelete [] m1;\r\n\tdelete [] m2;\r\n\r\n\r\n\r\n}\r\n}\r\n\toutfile.close();\r\n\r\n\r\n    t2 = clock();    \r\n    float diff = ((float)t2 - (float)t1)/CLOCKS_PER_SEC;\r\n    printf(\"\\nTotal running time is %5.2f seconds\\n\", diff);        \r\n \treturn 0;\t\r\n}\r\n", "meta": {"hexsha": "dcd6a016adf4a84f038fa9976efdaf439768bd91", "size": 31585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "1-property_proteomevis/tm_and_sid/TMalignc/TMalign.cpp", "max_stars_repo_name": "proteins247/proteomevis_scripts", "max_stars_repo_head_hexsha": "33d864f02787659a5d75103baad556fb48b3bd1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-11T06:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-11T06:14:10.000Z", "max_issues_repo_path": "1-property_proteomevis/tm_and_sid/TMalignc/TMalign.cpp", "max_issues_repo_name": "proteins247/proteomevis_scripts", "max_issues_repo_head_hexsha": "33d864f02787659a5d75103baad556fb48b3bd1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1-property_proteomevis/tm_and_sid/TMalignc/TMalign.cpp", "max_forks_repo_name": "proteins247/proteomevis_scripts", "max_forks_repo_head_hexsha": "33d864f02787659a5d75103baad556fb48b3bd1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T19:13:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-28T19:13:24.000Z", "avg_line_length": 31.5534465534, "max_line_length": 216, "alphanum_fraction": 0.5003957575, "num_tokens": 9059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.021948254514558344, "lm_q1q2_score": 0.008448149712877828}}
{"text": "#ifndef ATM_SUBSTRINGS_HPP\n#define ATM_SUBSTRINGS_HPP\n\n#include <cmath>\n#include <map>\n#include <vector>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/iterator.hpp>\n#include <boost/range/sub_range.hpp>\n#include <boost/range/value_type.hpp>\n#include \"sast/sast.hpp\"\n\n\nnamespace atm {\n\ntemplate <class RandomAccessRange, class Index>\nstruct substrings {\n    using range_type = RandomAccessRange;\n    using char_type = typename boost::range_value<RandomAccessRange>::type;\n    using index_type = Index;\n\nprotected:\n    using sast_type = sast::sast<RandomAccessRange, index_type>;\n\npublic:\n    struct substr {\n        using iterator       = typename boost::range_iterator<RandomAccessRange>::type;\n        using const_iterator = typename boost::range_const_iterator<RandomAccessRange>::type;\n\n        index_type pos()           const { return i_->pos(); }\n        boost::sub_range<const std::vector<index_type>> allpos() const { return i_->allpos(); }\n        index_type length()        const { return i_->length() - ii_; }\n        index_type frequency()     const { return i_->frequency(); }\n        double     spurity()       const { return parent_->strict_purity(i_, ii_); }\n        double     lpurity()       const { return parent_->loose_purity(i_, ii_); }\n        double     luniversality() const { return parent_->left_universality(i_, ii_); }\n        double     runiversality() const { return parent_->right_universality(i_, ii_); }\n\n        iterator begin() { return boost::begin(parent_->input_) + pos(); }\n        iterator end()   { return boost::begin(parent_->input_) + pos() + length(); }\n        const_iterator begin() const { return boost::const_begin(parent_->input_) + pos(); }\n        const_iterator end()   const { return boost::const_begin(parent_->input_) + pos() + length(); }\n\n        substr(const substrings* parent, typename sast_type::const_iterator i, int ii)\n            : parent_(parent), i_(i), ii_(ii)\n        {}\n\n    private:\n        const substrings* parent_;\n        typename sast_type::const_iterator i_;\n        int ii_;\n    };\n\nprivate:\n    template <class> struct substring_iterator;\n\npublic:\n    using iterator       = substring_iterator<substr>;\n    using const_iterator = substring_iterator<const substr>;\n\n    substrings(const sast_type& sast)\n        : sast_(sast),\n          input_(sast_.input())\n    {}\n\n    iterator begin() { return iterator(this, sast_.begin(), 0); }\n    iterator end()   { return iterator(this, sast_.begin() + (sast_.size() - 1), 0); }\n    const_iterator begin() const { return const_iterator(this, sast_.begin(), 0); }\n    const_iterator end()   const { return const_iterator(this, sast_.begin() + (sast_.size() - 1), 0); }\n\nprivate:\n    template <class Value>\n    struct substring_iterator\n        : public boost::iterator_facade<\n            substring_iterator<Value>,\n            Value,\n            boost::random_access_traversal_tag,\n            Value,\n            int>\n    {\n        substring_iterator()\n            : parent_(0), i_(), ii_(-1)\n        {}\n\n        substring_iterator(const substrings* parent, typename sast_type::const_iterator i, int ii)\n            : parent_(parent), i_(i), ii_(ii)\n        {}\n\n        template <class OtherValue>\n        substring_iterator(const substring_iterator<OtherValue>& other)\n            : parent_(other.parent_), i_(other.i_), ii_(other.ii_)\n        {}\n\n        void next_branching() {\n            ++i_;\n            ii_ = 0;\n        }\n\n        void prev_branching() {\n            --i_;\n            auto j = i_.parent();\n            ii_ = (i_->length() - j->length()) - 1;\n        }\n\n    private:\n        friend class boost::iterator_core_access;\n        template <class> friend struct substring_iterator;\n\n        void increment() {\n            auto j = i_.parent();\n            if (ii_ + 1 < i_->length() - j->length()) {\n                ++ii_;\n            }\n            else {\n                next_branching();\n            }\n        }\n\n        void decrement() {\n            if (ii_ - 1 >= 0) {\n                --ii_;\n            }\n            else {\n                prev_branching();\n            }\n        }\n\n        void advance(int n) {\n            if (n >= 0) {\n                auto j = i_.parent();\n                while (ii_ + n >= i_->length() - j->length()) {\n                    n -= (i_->length() - j->length()) - ii_;\n                    next_branching();\n                    j = i_.parent();\n                }\n                ii_ += n;\n            }\n            else {\n                while (ii_ + n < 0) {\n                    n += ii_ + 1;\n                    prev_branching();\n                }\n                ii_ += n;\n            }\n        }\n\n        int distance_to(const substring_iterator<Value>& other) const {\n            int d = 0;\n            if (other.i_ - this->i_ > 0 || (other.i_ == this->i_ && other.ii_ >= this->ii_)) {\n                auto i = this->i_;\n                int ii = this->ii_;\n                while (other.i_ - i > 0) {\n                    auto j = i.parent();\n                    d += (i->length() - j->length()) - ii;\n                    ++i;\n                    ii = 0;\n                }\n                d += other.ii_ - ii_;\n            }\n            else {\n                auto i = other.i_;\n                int ii = other.ii_;\n                while (this->i_ - i > 0) {\n                    auto j = i.parent();\n                    d += (i->length() - j->length()) - ii;\n                    ++i;\n                    ii = 0;\n                }\n                d += other.ii_ - ii_;\n                d = -d;\n            }\n            return d;\n        }\n\n        template <class OtherValue>\n        bool equal(const substring_iterator<OtherValue>& other) const {\n            return this->parent_ == other.parent_\n                && this->i_ == other.i_\n                && this->ii_ == other.ii_;\n        }\n\n        Value dereference() const {\n            return substr(parent_, i_, ii_);\n        }\n\n        const substrings* parent_;\n        typename sast_type::const_iterator i_;\n        int ii_;\n    };\n\nprotected:\n    double strict_purity(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n        const auto freq_substr = n->frequency();\n        const auto len_substr  = n->length() - ii;\n\n        // substrと同じ出現回数のsub-substrを数える。\n        uint64_t count = 0;\n        {\n            // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n            // ノードiに対応する部分文字列をsubstr[i]とすると、substr[i]の末尾\n            // を削って得られる部分文字列の内で、substr[i]と同じ頻度をもつもの\n            // はsuffix tree上ではノードiにまとめられている\n            // （分岐が無い <=> 頻度が同じ）。\n\n            // ノードiの親ノードjを見つける。\n            const auto m = n.parent();\n\n            // substrの末尾を0文字以上削って得られるsub-substrの内で、出現\n            // 回数がsubstrと同じものの数はd[i] - d[j]である。\n            count += n->length() - m->length() - ii;\n        }\n        for (int j = 1; j < len_substr; ++j) {\n            // substrの先頭をj文字削ったsub-substrを考える。\n            const auto len_subsubstr = len_substr - j;\n\n            // sub-substrに対応するノードを見つける。\n            // {内部,葉}ノードに対応する部分文字列から先頭の1文字を削って得られ\n            // る文字列には、必ず対応する{内部,葉}ノードが存在する。\n            // ii ＞ 0 の場合、d[k] == len_subsubstr を満たす「ノード」が必ずし\n            // も存在するとは限らない。よって、\n            // d[node_to_parent_node[k]] < len_subsubstr <= d[k] を満たす k を\n            // 見つける。\n            auto m = n;\n            for (int l = 0; l < j; ++l) {\n                m = m.suffix();\n            }\n            while (m.parent()->length() >= len_subsubstr) {\n                m = m.parent();\n            }\n            const auto kk = m->length() - len_subsubstr;  // ノードiでii文字削ると、ノードkではkk文字削ったことに相当する。\n\n            // sub-substrの出現回数をチェックする。\n            const auto freq_subsubstr = m->frequency();\n            if (freq_subsubstr == freq_substr) {\n                // ノードkの親ノードmを見つける。\n                const auto mp = m.parent();\n\n                // sub-substrの末尾を0文字以上削って得られる\n                // sub-sub-substrの内で、出現回数がsub-substrと同じもの\n                // の数はd[k] - d[m]である。\n                count += m->length() - mp->length() - kk;\n            }\n        }\n\n        // strict purity of substr\n        const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n        const double spurity = static_cast<double>(count) / num_subsubstrs;\n\n        return spurity;\n    }\n\n    double loose_purity(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n        const auto freq_substr = n->frequency();\n        const auto len_substr  = n->length() - ii;\n\n        double support = 0;\n        {\n            // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n            for (auto m = n, p = n.parent(); m->length() > 0; m = p, p = p.parent()) {\n                const auto num_subsubstrs_of_same_frequency = m->length() - p->length() - (m == n ? ii : 0);\n                const auto freq_subsubstr = m->frequency();\n                const double sup = static_cast<double>(freq_substr) / freq_subsubstr;\n                support += num_subsubstrs_of_same_frequency * sup;\n            }\n        }\n        for (int j = 1; j < len_substr; ++j) {\n            // substrの先頭をj文字削ったsub-substrを考える。\n            const auto len_subsubstr = len_substr - j;\n\n            // sub-substrに対応するノードを見つける。\n            // ii ＞ 0 の場合、d[k] == len_subsubstr を満たす「ノード」が必ずし\n            // も存在するとは限らない。よって、\n            // d[node_to_parent_node[k]] < len_subsubstr <= d[k] を満たす k を\n            // 見つける。\n            auto m = n;\n            for (int l = 0; l < j; ++l) {\n                m = m.suffix();\n            }\n            while (m.parent()->length() >= len_subsubstr) {\n                m = m.parent();\n            }\n            const auto kk = m->length() - len_subsubstr;  // ノードiでii文字削ると、ノードkではkk文字削ったことに相当する。\n\n            // sub-substrの末尾を0文字以上削って得られるsub-substrについて考える。\n            for (auto o = m, p = m.parent(); o->length() > 0; o = p, p = p.parent()) {\n                const auto num_subsubstrs_of_same_frequency = o->length() - p->length() - (o == m ? kk : 0);\n                const auto freq_subsubstr = o->frequency();\n                const double sup = static_cast<double>(freq_substr) / freq_subsubstr;\n                support += num_subsubstrs_of_same_frequency * sup;\n            }\n        }\n\n        // loose purity of substr\n        const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n        const double lpurity = support / num_subsubstrs;\n\n        return lpurity;\n    }\n\n    std::map<char_type, int> left_extensions(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n\n        std::map<char_type, int> char_dist;\n        for (auto pos : n->allpos()) {\n            const auto& c = boost::const_begin(input_)[pos - 1];\n            char_dist[c] += 1;\n        }\n\n        return char_dist;\n    }\n\n    std::map<char_type, int> right_extensions(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n        const auto len_substr  = n->length() - ii;\n\n        std::map<char_type, int> char_dist;\n        for (auto pos : n->allpos()) {\n            const auto& c = boost::const_begin(input_)[pos + len_substr];\n            char_dist[c] += 1;\n        }\n\n        return char_dist;\n    }\n\n    double left_universality(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n        const auto freq_substr = n->frequency();\n\n        std::map<char_type, int> char_dist = left_extensions(n, ii);\n\n        double e = 0;\n        for (const auto& kv : char_dist) {\n            const double p = static_cast<double>(kv.second) / freq_substr;\n            e += -p * std::log(p);\n        }\n        const double u = 1 - std::exp(-e);\n\n        return u;\n    }\n\n    double right_universality(typename sast_type::const_iterator n, const int ii) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列の末尾をii文字削ったsubstrを扱う。\n        // iiが満たさなければならない条件: 0 <= ii < d[i] - d[node_to_parent_node[i]]\n        const auto freq_substr = n->frequency();\n\n        std::map<char_type, int> char_dist = right_extensions(n, ii);\n\n        double e = 0;\n        for (const auto& kv : char_dist) {\n            const double p = static_cast<double>(kv.second) / freq_substr;\n            e += -p * std::log(p);\n        }\n        const double u = 1 - std::exp(-e);\n\n        return u;\n    }\n\n    const sast_type& sast_;\n    const RandomAccessRange& input_;\n};\n\n}  // namespace atm\n\n\n#endif  /* ATM_SUBSTRINGS_HPP */\n", "meta": {"hexsha": "fa14c7662c8794551d1db15eaaec58c29b665385", "size": 13093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/atm/substrings.hpp", "max_stars_repo_name": "yuttie/atm", "max_stars_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/atm/substrings.hpp", "max_issues_repo_name": "yuttie/atm", "max_issues_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/atm/substrings.hpp", "max_forks_repo_name": "yuttie/atm", "max_forks_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0080213904, "max_line_length": 108, "alphanum_fraction": 0.5351714657, "num_tokens": 3848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.019124038567772696, "lm_q1q2_score": 0.008446571594674388}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2016 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include <trilinoswrap/Amesos2Wrapper.h>\n#include <trilinoswrap/TrilinosAdapterException.h>\n#include <trilinoswrap/util.h>\n\n#include <escript/SolverOptions.h>\n\n#include <Amesos2.hpp>\n#include <Tpetra_CrsMatrix.hpp>\n\n#include <boost/python/dict.hpp>\n\nusing Teuchos::RCP;\n\nnamespace bp = boost::python;\n\nnamespace esys_trilinos {\n\ntemplate<class Matrix, class Vector>\nRCP<DirectSolverType<Matrix,Vector> > createDirectSolver(\n                                               const escript::SolverBuddy& sb,\n                                               RCP<const Matrix> A,\n                                               RCP<Vector> X,\n                                               RCP<const Vector> B)\n{\n    using util::extractParamIfSet;\n\n    typedef typename Matrix::scalar_type ST;\n\n    RCP<DirectSolverType<Matrix,Vector> > solver;\n    RCP<Teuchos::ParameterList> amesosParams = Teuchos::parameterList(\"Amesos2\");\n    const bp::dict& pyParams = sb.getTrilinosParameters();\n\n    const escript::SolverOptions method = sb.getSolverMethod();\n    // did user request specific direct solver or not?\n    const bool dontcare = method == escript::SO_METHOD_DIRECT;\n\n    if ((dontcare || method == escript::SO_METHOD_DIRECT_TRILINOS) &&\n            Amesos2::query(\"klu2\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"klu2\", A, X, B);\n        Teuchos::ParameterList solverParams(solver->name());\n        // the doco says these params exist but clearly they don't :-(\n        //solverParams.set(\"DiagPivotThresh\", sb.getDiagonalDominanceThreshold());\n        //solverParams.set(\"SymmetricMode\", sb.isSymmetric());\n        extractParamIfSet<std::string>(\"Trans\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"Equil\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"IterRefine\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"SymmetricMode\", pyParams, solverParams);\n        extractParamIfSet<ST>(\"DiagPivotThresh\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"ColPerm\", pyParams, solverParams);\n        amesosParams->set(solver->name(), solverParams);\n    } else if ((dontcare || method == escript::SO_METHOD_DIRECT_MUMPS) &&\n            Amesos2::query(\"MUMPS\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"MUMPS\", A, X, B);\n        Teuchos::ParameterList solverParams(solver->name());\n        if (sb.isVerbose()) {\n            solverParams.set(\"ICNTL(4)\", 4);\n        }\n        extractParamIfSet<int>(\"ICNTL(1)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"ICNTL(2)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"ICNTL(3)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"ICNTL(4)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"ICNTL(6)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"ICNTL(9)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"ICNTL(11)\", pyParams, solverParams);\n        amesosParams->set(solver->name(), solverParams);\n    } else if ((dontcare || method == escript::SO_METHOD_DIRECT_TRILINOS) &&\n            Amesos2::query(\"Basker\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"Basker\", A, X, B);\n    } else if ((dontcare || method == escript::SO_METHOD_DIRECT_SUPERLU) &&\n            Amesos2::query(\"superludist\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"superludist\", A, X, B);\n        Teuchos::ParameterList solverParams(solver->name());\n        extractParamIfSet<int>(\"npcol\", pyParams, solverParams);\n        extractParamIfSet<int>(\"nprow\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"ColPerm\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"ReplaceTinyPivot\", pyParams, solverParams);\n        amesosParams->set(solver->name(), solverParams);\n    } else if ((dontcare || method == escript::SO_METHOD_DIRECT_SUPERLU) &&\n            Amesos2::query(\"superlu\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"superlu\", A, X, B);\n        Teuchos::ParameterList solverParams(solver->name());\n        solverParams.set(\"DiagPivotThresh\", sb.getDiagonalDominanceThreshold());\n        solverParams.set(\"ILU_DropTol\", sb.getDropTolerance());\n        solverParams.set(\"SymmetricMode\", sb.isSymmetric());\n        extractParamIfSet<std::string>(\"Trans\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"Equil\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"IterRefine\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"SymmetricMode\", pyParams, solverParams);\n        extractParamIfSet<ST>(\"DiagPivotThresh\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"ColPerm\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"ILU_Flag\", pyParams, solverParams);\n        extractParamIfSet<ST>(\"ILU_DropTol\", pyParams, solverParams);\n        extractParamIfSet<ST>(\"ILU_FillFactor\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"ILU_Norm\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"ILU_MILU\", pyParams, solverParams);\n        extractParamIfSet<ST>(\"ILU_FillTol\", pyParams, solverParams);\n        amesosParams->set(solver->name(), solverParams);\n    } else if ((dontcare || method == escript::SO_METHOD_DIRECT_SUPERLU) &&\n            Amesos2::query(\"superlumt\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"superlumt\", A, X, B);\n        Teuchos::ParameterList solverParams(solver->name());\n#ifdef _OPENMP  \n        solverParams.set(\"nprocs\", omp_get_max_threads());\n#else\n        solverParams.set(\"nprocs\", 1);\n#endif\n        solverParams.set(\"DiagPivotThresh\", sb.getDiagonalDominanceThreshold());\n        solverParams.set(\"SymmetricMode\", sb.isSymmetric());\n        extractParamIfSet<int>(\"nprocs\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"trans\", pyParams, solverParams);\n        extractParamIfSet<int>(\"panel_size\", pyParams, solverParams);\n        extractParamIfSet<int>(\"relax\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"Equil\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"SymmetricMode\", pyParams, solverParams);\n        extractParamIfSet<ST>(\"DiagPivotThresh\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"ColPerm\", pyParams, solverParams);\n        amesosParams->set(solver->name(), solverParams);\n    } else if ((dontcare || method == escript::SO_METHOD_DIRECT_PARDISO) &&\n            Amesos2::query(\"pardiso_mkl\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"pardiso_mkl\", A, X, B);\n        Teuchos::ParameterList solverParams(solver->name());\n        extractParamIfSet<int>(\"IPARM(2)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"IPARM(4)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"IPARM(8)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"IPARM(10)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"IPARM(18)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"IPARM(24)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"IPARM(25)\", pyParams, solverParams);\n        extractParamIfSet<int>(\"IPARM(60)\", pyParams, solverParams);\n        amesosParams->set(solver->name(), solverParams);\n    } else if (Amesos2::query(\"amesos2_cholmod\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"amesos2_cholmod\", A, X, B);\n        Teuchos::ParameterList solverParams(solver->name());\n        solverParams.set(\"DiagPivotThresh\", sb.getDiagonalDominanceThreshold());\n        solverParams.set(\"SymmetricMode\", sb.isSymmetric());\n        extractParamIfSet<std::string>(\"Trans\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"Equil\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"IterRefine\", pyParams, solverParams);\n        extractParamIfSet<bool>(\"SymmetricMode\", pyParams, solverParams);\n        extractParamIfSet<ST>(\"DiagPivotThresh\", pyParams, solverParams);\n        extractParamIfSet<std::string>(\"ColPerm\", pyParams, solverParams);\n        amesosParams->set(solver->name(), solverParams);\n    } else if (Amesos2::query(\"lapack\")) {\n        solver = Amesos2::create<Matrix, Vector>(\"lapack\", A, X, B);\n    } else {\n        if (dontcare) {\n            throw TrilinosAdapterException(\"Could not find an Amesos2 direct solver!\");\n        } else {\n            throw TrilinosAdapterException(\"The requested direct solver is not available!\");\n        }\n    }\n    solver->setParameters(amesosParams);\n    return solver;\n}\n\ntypedef Tpetra::CrsMatrix<real_t,LO,GO,NT> RealMatrix;\ntypedef Tpetra::CrsMatrix<cplx_t,LO,GO,NT> ComplexMatrix;\n\n// instantiate\ntemplate\nRCP<DirectSolverType<RealMatrix, RealVector> >\ncreateDirectSolver<RealMatrix,RealVector>(const escript::SolverBuddy& sb,\n                                          RCP<const RealMatrix> A,\n                                          RCP<RealVector> X,\n                                          RCP<const RealVector> B);\ntemplate\nRCP<DirectSolverType<ComplexMatrix, ComplexVector> >\ncreateDirectSolver<ComplexMatrix, ComplexVector>(\n                                          const escript::SolverBuddy& sb,\n                                          RCP<const ComplexMatrix> A,\n                                          RCP<ComplexVector> X,\n                                          RCP<const ComplexVector> B);\n\n/* Amesos2 does not currently support block matrices!\ntemplate\nRCP<DirectSolverType<RealBlockMatrix, RealBlockVector> >\ncreateDirectSolver<RealBlockMatrix,RealBlockVector>(\n                                          const escript::SolverBuddy& sb,\n                                          RCP<const RealBlockMatrix> A,\n                                          RCP<RealBlockVector> X,\n                                          RCP<const RealBlockVector> B);\ntemplate\nRCP<DirectSolverType<ComplexBlockMatrix, ComplexBlockVector> >\ncreateDirectSolver<ComplexBlockMatrix, ComplexBlockVector>(\n                                          const escript::SolverBuddy& sb,\n                                          RCP<const ComplexBlockMatrix> A,\n                                          RCP<ComplexBlockVector> X,\n                                          RCP<const ComplexBlockVector> B);\n*/\n\n}  // end of namespace\n\n", "meta": {"hexsha": "c582397b93ccb84513a23736231c21a01c152efd", "size": 10736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trilinoswrap/src/Amesos2Wrapper.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "trilinoswrap/src/Amesos2Wrapper.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "trilinoswrap/src/Amesos2Wrapper.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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.3684210526, "max_line_length": 92, "alphanum_fraction": 0.6342213115, "num_tokens": 2592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512971193602087, "lm_q2_score": 0.03067579927371769, "lm_q1q2_score": 0.008439823817585146}}
{"text": "#pragma once\n\n#include <boost/current_function.hpp>\n#include <boost/noncopyable.hpp>\n#include <terark/bitmap.hpp>\n#include \"fsa.hpp\"\n\n#if defined(__clang__) //|| defined(__GNUC__) || defined(__GNUG__)\n\t#pragma clang diagnostic push\n\t#pragma clang diagnostic ignored \"-Wunused-lambda-capture\"\n#endif\n\nnamespace terark {\n\n#define ASSERT_isNotFree(s)       assert(!this->is_free(s))\n#define ASSERT_isNotFree2(au,s)   assert(!au->is_free(s))\n\ntemplate<class VertexID>\nclass BFS_GraphWalker {\nprotected:\n\tsize_t _M_depth = 0;\n\tsize_t idx = 0;\n\tvalvec<VertexID> q1, q2;\n\tfebitvec     color;\npublic:\n\tvoid resize(size_t VertexNum) {\n\t\tassert(q1.size() == idx);\n\t\tassert(q2.empty());\n\t\tq1.reserve(std::min<size_t>(VertexNum, 512));\n\t\tq2.reserve(std::min<size_t>(VertexNum, 512));\n\t\tq1.erase_all();\n\t\tidx = 0;\n\t\t_M_depth = 0;\n\t\tcolor.resize_no_init(VertexNum);\n\t\tcolor.fill(0);\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tassert(root < color.size());\n\t\tq1.push_back(root);\n\t\tcolor.set1(root);\n\t}\n\tVertexID next() {\n\t\tassert(idx <= q1.size());\n\t\tif (q1.size() == idx) {\n\t\t\tq1.swap(q2);\n\t\t\tidx = 0;\n\t\t\t_M_depth++;\n\t\t\tq2.erase_all();\n\t\t}\n\t\tassert(!q1.empty());\n\t\treturn q1[idx++];\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i];\n\t\t\tif (this->color.is0(child)) {\n\t\t\t\tthis->q2.push_back(child);\n\t\t\t\tthis->color.set1(child);\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i].target;\n\t\t\tif (this->color.is0(child)) {\n\t\t\t\tthis->q2.push_back(child);\n\t\t\t\tthis->color.set1(child);\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color.is0(child)) {\n\t\t\t\t\tthis->q2.push_back(child);\n\t\t\t\t\tthis->color.set1(child);\n\t\t\t\t}\n\t\t\t});\n\t}\n\ttemplate<class Graph, class OnEdge>\n\tvoid putChildren2(const Graph* g, VertexID parent, OnEdge on_edge) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest(parent,\n\t\t\t[&,parent](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color.is0(child)) {\n\t\t\t\t\tif (on_edge(parent, child, true)) {\n\t\t\t\t\t\tthis->q2.push_back(child);\n\t\t\t\t\t\tthis->color.set1(child);\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\ton_edge(parent, child, false);\n\t\t\t});\n\t}\n\tbool is_finished() const { return q1.size() + q2.size() == idx; }\n\tsize_t depth() const { return _M_depth; }\n};\n\ntemplate<class VertexID, class ColorID = VertexID>\nclass BFS_MultiPassGraphWalker {\nprotected:\n\tsize_t  _M_depth = 0;\n\tsize_t  idx = 0;\n\tColorID color_id = 0;\n\tvalvec<VertexID> q1, q2;\n\tvalvec< ColorID> color;\npublic:\n\tvoid resize(size_t VertexNum) {\n\t\tassert(q1.size() == idx);\n\t\tassert(q2.empty());\n\t\tq1.reserve(std::min<size_t>(VertexNum, 512));\n\t\tq2.reserve(std::min<size_t>(VertexNum, 512));\n\t\tq1.erase_all();\n\t\tidx = 0;\n\t\t_M_depth = 0;\n\t\tcolor.resize(VertexNum);\n\t\tcolor_id++;\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tassert(root < color.size());\n\t\tcolor[root] = color_id;\n\t\tq1.push_back(root);\n\t}\n\tVertexID next() {\n\t\tassert(idx <= q1.size());\n\t\tif (q1.size() == idx) {\n\t\t\tq1.swap(q2);\n\t\t\tidx = 0;\n\t\t\t_M_depth++;\n\t\t\tq2.erase_all();\n\t\t}\n\t\tassert(!q1.empty());\n\t\treturn q1[idx++];\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i];\n\t\t\tassert(this->color[child] <= color_id);\n\t\t\tif (this->color[child] < color_id) {\n\t\t\t\tthis->color[child] = color_id;\n\t\t\t\tthis->q2.push_back(child);\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i].target;\n\t\t\tassert(this->color[child] <= color_id);\n\t\t\tif (this->color[child] < color_id) {\n\t\t\t\tthis->color[child] = color_id;\n\t\t\t\tthis->q2.push_back(child);\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tassert(this->color[child] <= color_id);\n\t\t\t\tif (this->color[child] < color_id) {\n\t\t\t\t\tthis->color[child] = color_id;\n\t\t\t\t\tthis->q2.push_back(child);\n\t\t\t\t}\n\t\t\t});\n\t}\n\ttemplate<class Graph, class OnEdge>\n\tvoid putChildren2(const Graph* g, VertexID parent, OnEdge on_edge) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest(parent,\n\t\t\t[&,parent](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tassert(this->color[child] <= color_id);\n\t\t\t\tif (this->color[child] < color_id) {\n\t\t\t\t\tif (on_edge(parent, child, true)) {\n\t\t\t\t\t\tthis->color[child] = color_id;\n\t\t\t\t\t\tthis->q2.push_back(child);\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\ton_edge(parent, child, false);\n\t\t\t});\n\t}\n\tbool is_finished() const { return q1.size() + q2.size() == idx; }\n\tsize_t depth() const { return _M_depth; }\n};\n\ntemplate<class VertexID>\nclass BFS_TreeWalker {\nprotected:\n\tsize_t _M_depth = 0;\n\tsize_t idx = 0;\n\tvalvec<VertexID> q1, q2;\npublic:\n\tvoid resize(size_t VertexNum) {\n\t\tassert(q1.size() == idx);\n\t\tassert(q2.empty());\n\t\tq1.reserve(std::min<size_t>(VertexNum, 512));\n\t\tq2.reserve(std::min<size_t>(VertexNum, 512));\n\t\tq1.erase_all();\n\t\tidx = 0;\n\t\t_M_depth = 0;\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tq1.push_back(root);\n\t}\n\tVertexID next() {\n\t\tassert(idx <= q1.size());\n\t\tif (q1.size() == idx) {\n\t\t\tq1.swap(q2);\n\t\t\tidx = 0;\n\t\t\t_M_depth++;\n\t\t\tq2.erase_all();\n\t\t}\n\t\tassert(!q1.empty());\n\t\treturn q1[idx++];\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i];\n\t\t\tthis->q2.push_back(child);\n\t\t};\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i].target;\n\t\t\tthis->q2.push_back(child);\n\t\t};\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tthis->q2.push_back(child);\n\t\t\t});\n\t}\n\ttemplate<class Graph, class OnEdge>\n\tvoid putChildren2(const Graph* g, VertexID parent, OnEdge on_edge) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest(parent,\n\t\t\t[&,parent](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (on_edge(parent, child, true)) {\n\t\t\t\t\tthis->q2.push_back(child);\n\t\t\t\t}\n\t\t\t});\n\t}\n\tbool is_finished() const { return q1.size() + q2.size() == idx; }\n\tsize_t depth() const { return _M_depth; }\n};\n\n\n/// The Fastest Graph Walker: similar with DFS and BFS,\n/// but neither of them!\n/// PFS is: Performance First Search\ntemplate<class VertexID>\nclass PFS_GraphWalker {\nprotected:\n\tvalvec<VertexID> stack;\n\tfebitvec     color;\npublic:\n\tvoid resize(size_t VertexNum) {\n\t\tassert(stack.empty());\n\t\tcolor.resize_no_init(VertexNum);\n\t\tcolor.fill(0);\n\t\tstack.reserve(512);\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tassert(root < color.size());\n\t\tstack.push_back(root);\n\t\tcolor.set1(root);\n\t}\n\tVertexID next() {\n\t\tassert(!stack.empty());\n\t\tVertexID x = stack.back();\n\t\tstack.pop_back();\n\t\treturn x;\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i];\n\t\t\tif (this->color.is0(child)) {\n\t\t\t\tthis->stack.push_back(child);\n\t\t\t\tthis->color.set1(child);\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i].target;\n\t\t\tif (this->color.is0(child)) {\n\t\t\t\tthis->stack.push_back(child);\n\t\t\t\tthis->color.set1(child);\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color.is0(child)) {\n\t\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t\tthis->color.set1(child);\n\t\t\t\t}\n\t\t\t});\n\t}\n\ttemplate<class Graph, class OnEdge>\n\tvoid putChildren2(const Graph* g, VertexID parent, OnEdge on_edge) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[&,parent](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color.is0(child)) {\n\t\t\t\t\tif (on_edge(parent, child, true)) {\n\t\t\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t\t\tthis->color.set1(child);\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\ton_edge(parent, child, false);\n\t\t\t});\n\t}\n\tbool is_finished() const { return stack.empty(); }\n};\n\ntemplate<class VertexID>\nclass DFS_GraphWalker { // in DFS Preorder\nprotected:\n\tvalvec<VertexID> stack;\n\tfebitvec     color;\npublic:\n\tvoid resize(size_t VertexNum) {\n\t\tassert(stack.empty());\n\t\tcolor.resize_no_init(VertexNum);\n\t\tcolor.fill(0);\n\t\tstack.reserve(512);\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tassert(root < color.size());\n\t\tstack.push_back(root);\n\t\t// don't call color.set1(root)\n\t}\n\tVertexID next() {\n\t\tassert(!stack.empty());\n\t\tVertexID x = stack.back();\n\t\tassert(color.is0(x));\n\t\tcolor.set1(x);\n\t\tdo stack.pop_back(); // skip all visited states in stack\n\t\twhile (!stack.empty() && color.is1(stack.back()));\n\t\treturn x;\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i];\n\t\t\tif (this->color.is0(child)) {\n\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t// Don't call color.set1(child) here!\n\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i].target;\n\t\t\tif (this->color.is0(child)) {\n\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t// Don't call color.set1(child) here!\n\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color.is0(child)) {\n\t\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t\t// Don't call color.set1(child) here!\n\t\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t\t}\n\t\t\t});\n\t}\n\ttemplate<class Graph, class OnEdge>\n\tvoid putChildren2(const Graph* g, VertexID parent, OnEdge on_edge) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[&,parent](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color.is0(child)) {\n\t\t\t\t\tif (on_edge(parent, child, true)) {\n\t\t\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t\t\t// Don't call color.set1(child) here!\n\t\t\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\ton_edge(parent, child, false);\n\t\t\t});\n\t}\n\tbool is_finished() const { return stack.empty(); }\n};\n\ntemplate<class VertexID, class ColorID = VertexID>\nclass DFS_MultiPassGraphWalker { // in DFS Preorder\nprotected:\n\tvalvec<VertexID> stack;\n\tvalvec< ColorID> color;\n\tColorID          color_id = 0;\npublic:\n\tvoid resize(size_t VertexNum) {\n\t\tassert(stack.empty());\n\t\tstack.reserve(512);\n\t\tcolor.resize(VertexNum);\n\t\tcolor_id++;\n\t\t// don't set color[root] = color_id;\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tassert(root < color.size());\n\t\tstack.push_back(root);\n\t\t// don't call color.set1(root)\n\t}\n\tVertexID next() { // in DFS Preorder\n\t\tassert(!stack.empty());\n\t\tVertexID x = stack.back();\n\t\tassert(color[x] < color_id);\n\t\tcolor[x] = color_id;\n\t\tdo stack.pop_back(); // skip all visited states in stack\n\t\twhile (!stack.empty() && color[stack.back()] == color_id);\n\t\treturn x;\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i];\n\t\t\tif (this->color[child] < color_id) {\n\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t// Don't set color[child] = color_id here!\n\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i].target;\n\t\t\tif (this->color[child] < color_id) {\n\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t// Don't set color[child] = color_id here!\n\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t}\n\t\t}\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color[child] < color_id) {\n\t\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t\t// Don't set color[child] = color_id here!\n\t\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t\t}\n\t\t\t});\n\t}\n\ttemplate<class Graph, class OnEdge>\n\tvoid putChildren2(const Graph* g, VertexID parent, OnEdge on_edge) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[&,parent](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (this->color[child] < color_id) {\n\t\t\t\t\tif (on_edge(parent, child, true)) {\n\t\t\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t\t\t// Don't set color[child] = color_id here!\n\t\t\t\t\t\t// so there may have multiple copy of child in stack\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\ton_edge(parent, child, false);\n\t\t\t});\n\t}\n\tbool is_finished() const { return stack.empty(); }\n};\n\ntemplate<class VertexID>\nclass DFS_TreeWalker { // in DFS Preorder\nprotected:\n\tvalvec<VertexID> stack;\npublic:\n\tvoid resize(size_t /*VertexNum*/) {\n\t\tstack.reserve(512);\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tstack.push_back(root);\n\t}\n\tVertexID next() {\n\t\tassert(!stack.empty());\n\t\tVertexID x = stack.back();\n\t\tstack.pop_back();\n\t\treturn x;\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i];\n\t\t\tthis->stack.push_back(child);\n\t\t}\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tfor(size_t i = n_children; i > 0; ) {\n\t\t\tsize_t child = children[--i].target;\n\t\t\tthis->stack.push_back(child);\n\t\t}\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tthis->stack.push_back(child);\n\t\t\t});\n\t}\n\ttemplate<class Graph, class OnEdge>\n\tvoid putChildren2(const Graph* g, VertexID parent, OnEdge on_edge) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tg->for_each_dest_rev(parent,\n\t\t\t[&,parent](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tif (on_edge(parent, child, true)) {\n\t\t\t\t\tthis->stack.push_back(child);\n\t\t\t\t}\n\t\t\t});\n\t}\n\tbool is_finished() const { return stack.empty(); }\n};\n\n// C of CFS means:\n//   1. C == (B + D) / 2\n//   2. Cache friendly\n// First 2 level in BFS order, others in DFS order\ntemplate<class VertexID>\nclass CFS_TreeWalker {\nprotected:\n\tvalvec<VertexID> m_q1, m_q2;\n\tsize_t m_depth;\n\tsize_t m_q1_pos;\n\tstatic const size_t MaxBFS_Depth = 2;\npublic:\n\tvoid resize(size_t /*VertexNum*/) {\n\t\tm_q1.erase_all(); m_q1.reserve(512);\n\t\tm_q2.erase_all(); m_q2.reserve(512);\n\t\tm_depth = 0;\n\t\tm_q1_pos = 0;\n\t}\n\tvoid putRoot(VertexID root) {\n\t\tassert(0 == m_depth);\n\t\tm_q1.push_back(root);\n\t}\n\tVertexID next() {\n\t\tassert(m_q1.size() + m_q2.size() > 0);\n\t\tif (m_depth < MaxBFS_Depth) {\n\t\t\tassert(m_q1_pos <= m_q1.size());\n\t\t\tif (m_q1_pos < m_q1.size()) {\n\t\t\t\treturn m_q1[m_q1_pos++];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tm_depth++;\n\t\t\t\tm_q1.erase_all();\n\t\t\t\tif (m_depth < MaxBFS_Depth) {\n\t\t\t\t\tm_q1.swap(m_q2);\n\t\t\t\t\tm_q1_pos = 1;\n\t\t\t\t\treturn m_q1[0];\n\t\t\t\t} else {\n\t\t\t\t\tstd::reverse(m_q2.begin(), m_q2.end());\n\t\t\t\t\treturn m_q2.pop_val();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn m_q2.pop_val();\n\t\t}\n\t}\n\tvoid putChildrenT(const size_t* children, size_t n_children) {\n\t\tsize_t oldsize = m_q2.size();\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i];\n\t\t\tthis->m_q2.push_back(child);\n\t\t}\n\t\tif (m_depth >= MaxBFS_Depth) {\n\t\t\tstd::reverse(m_q2.begin() + oldsize, m_q2.end());\n\t\t}\n\t}\n\ttemplate<class T>\n\tvoid putChildrenT(const T* children, size_t n_children) {\n\t\tsize_t oldsize = m_q2.size();\n\t\tfor(size_t i = 0; i < n_children; ++i) {\n\t\t\tsize_t child = children[i].target;\n\t\t\tthis->m_q2.push_back(child);\n\t\t}\n\t\tif (m_depth >= MaxBFS_Depth) {\n\t\t\tstd::reverse(m_q2.begin() + oldsize, m_q2.end());\n\t\t}\n\t}\n\ttemplate<class Graph>\n\tvoid putChildren(const Graph* g, VertexID parent) {\n\t\tassert(parent < GraphTotalVertexes(g));\n\t\tsize_t oldsize = m_q2.size();\n\t\tg->for_each_dest(parent,\n\t\t\t[this,g](VertexID child) {\n\t\t\t\tassert(child < GraphTotalVertexes(g));\n\t\t\t\tASSERT_isNotFree2(g, child);\n\t\t\t\tthis->m_q2.push_back(child);\n\t\t\t});\n\t\tif (m_depth >= MaxBFS_Depth) {\n\t\t\tstd::reverse(m_q2.begin() + oldsize, m_q2.end());\n\t\t}\n\t}\n\tbool is_finished() const {\n\t\tif (m_depth < MaxBFS_Depth) {\n\t\t\tassert(m_q1_pos <= m_q1.size() + m_q2.size());\n\t\t\treturn m_q1_pos >= m_q1.size() + m_q2.size();\n\t\t} else {\n\t\t\treturn m_q2.empty();\n\t\t}\n\t}\n};\n\n#if defined(__clang__) //|| defined(__GNUC__) || defined(__GNUG__)\n\t#pragma clang diagnostic pop\n#endif\n\n} // namespace terark\n", "meta": {"hexsha": "6d5a088fb6ee7939ebbeaf37de736300bccc6803", "size": 17584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/terark/fsa/graph_walker.hpp", "max_stars_repo_name": "rockeet/terark-zip", "max_stars_repo_head_hexsha": "3235373d04b7cf5d584259111b3a057c45cc1708", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-11-19T04:57:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T12:44:17.000Z", "max_issues_repo_path": "src/terark/fsa/graph_walker.hpp", "max_issues_repo_name": "rockeet/terark-zip", "max_issues_repo_head_hexsha": "3235373d04b7cf5d584259111b3a057c45cc1708", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/terark/fsa/graph_walker.hpp", "max_forks_repo_name": "rockeet/terark-zip", "max_forks_repo_head_hexsha": "3235373d04b7cf5d584259111b3a057c45cc1708", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T10:17:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T10:17:01.000Z", "avg_line_length": 26.6828528073, "max_line_length": 69, "alphanum_fraction": 0.651444495, "num_tokens": 5185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.03789242323432295, "lm_q1q2_score": 0.00843864791471108}}
{"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 <cfloat>\n#include <cfenv>\n#include <cstdlib>\n#include <cmath>\n#include <boost/predef.h>\n\n#include \"ivarp/cuda.hpp\"\n\n// we need to access the rounding mode.\n// a prover program changes the rounding mode to round-down globally when a proof starts;\n// rounding mode switches are then restricted to operations that cannot use the opposite trick.\n// changing the rounding mode may break things with a lot of compiler optimizations.\n// the biggest problems in that regard are compile-time constant folding (if it goes wrong),\n// reordering of instructions across rounding-mode changes, and omission of \"equivalent\" computations that\n// are not equivalent due to a changed rounding mode.\n// GCC needs -frounding-math. Clang must deal without it, as it does not support the flag at all.\n// Across all compilers we support, CLang is by far the least reliable w.r.t. rounding modes; the opacify() function should take care of this.\n// MSVC needs /fp:strict but still sometimes breaks things with constant folding; it also lacks an inline assembler that could be used to work around bugs like this.\n// Thus, we have to resort to actual assembly (yuck!).\n// Moreover, we have to get rid of extended precision and double-rounding and other problems occurring with the x87 FPU;\n// we enforce use of sse2 which does not have extended precision to get rid of these issues.\n\n// Check that these flags worked:\n#ifdef __FLT_EVAL_METHOD__\n#define IVARP_FLT_EVAL_METHOD __FLT_EVAL_METHOD__\n#endif\n#if !defined(IVARP_FLT_EVAL_METHOD) && defined(FLT_EVAL_METHOD)\n#define IVARP_FLT_EVAL_METHOD FLT_EVAL_METHOD\n#endif\n\n#ifndef IVARP_FLT_EVAL_METHOD\n#error \"Could not detect floating-point evaluation method to ensure there are no double-rounding issues!\"\n#endif\n\n#if IVARP_FLT_EVAL_METHOD != 0 && IVARP_FLT_EVAL_METHOD != 1\n#error \"Could not ensure that there are no double-rounding issues!\"\n#elif IVARP_FLT_EVAL_METHOD != 0\n#warning \"float and double evaluation both use double precision!\"\n#endif\n#undef IVARP_FLT_EVAL_METHOD // don't clutter the global namespace.\n\n#if defined(_MSC_VER) && !defined(_M_FP_STRICT) // for MSVC, check the strict flag.\n#error \"MSVC is not using strict floating-point mode (/fp:strict)!\"\n#endif\n\n#if defined(_MSC_VER) && !defined(__llvm__)\n#pragma fenv_access (on)\n#endif\n\n// SSE2 detection for CLang & GCC.\n#if defined(__GNUC__)\n#ifndef __SSE2_MATH__\n#error \"Could not determine whether we are using SSE2!\"\n#endif\n#endif\n\n/// IVARP_ENSURE_ATLOAD_ROUNDDOWN: If the rounding mode is not set to round-down at global initialization time,\n/// set it to round-down for the scope of the function in which this macro is invoked.\n#if defined(_WIN32) || defined(__WIN32__)\n#define IVARP_ENSURE_ATLOAD_ROUNDDOWN() ::ivarp::SetRoundDown ivarp_ensure_rounddown_\n#else\n#define IVARP_ENSURE_ATLOAD_ROUNDDOWN() (static_cast<void>(0))\n#endif\n\n// SSE2 detection for MSVC.\n#if defined(_MSC_VER) && !defined(_M_X64) // 64-bit always uses at least SSE2.\n#ifndef _M_IX86_FP\n#error \"Could not determine whether we are using SSE2!\"\n#elif _M_IX86_FP < 2\n#error \"Compilation does not use (at least) SSE2!\"\n#endif\n#endif\n\n#if defined(__GNUC__)\n#include <xmmintrin.h>\n#else\n#include <emmintrin.h>\n#endif\n\n#if defined(_MM_FUNCTIONALITY)\n#error \"SSE2 intrinsics actually use a fallback implementation based on the x87 FPU.\"\n#endif\n\n#include \"ivarp/symbol_export.hpp\"\n\nnamespace ivarp {\n    static inline double opacify(double d) noexcept;\n    static inline void do_opacify(double& d) noexcept;\n    static inline float opacify(float f) noexcept;\n    static inline void do_opacify(float& f) noexcept;\n\n    class SetRound {\n    protected:\n        static constexpr int invalid_rounding_mode = -42;\n        static_assert(invalid_rounding_mode != FE_DOWNWARD, \"invalid_rounding_mode is not invalid!\");\n        static_assert(invalid_rounding_mode != FE_TONEAREST, \"invalid_rounding_mode is not invalid!\");\n        static_assert(invalid_rounding_mode != FE_UPWARD, \"invalid_rounding_mode is not invalid!\");\n        static_assert(invalid_rounding_mode != FE_TOWARDZERO, \"invalid_rounding_mode is not invalid!\");\n\n        explicit SetRound() noexcept :\n            m_prev(invalid_rounding_mode)\n        {}\n\n        explicit SetRound(int m) noexcept :\n            m_prev(std::fegetround())\n        {\n            std::fesetround(m);\n        }\n\n        ~SetRound() {\n            if(m_prev != invalid_rounding_mode) {\n                std::fesetround(m_prev);\n            }\n        }\n\n        int m_prev;\n    };\n\n    class SetRoundDown : private SetRound {\n    public:\n        explicit SetRoundDown() noexcept :\n            SetRound(FE_DOWNWARD)\n        {}\n\n        SetRoundDown(SetRoundDown&& o) noexcept :\n            SetRound()\n        {\n            m_prev = o.m_prev;\n            o.m_prev = invalid_rounding_mode;\n        }\n\n        SetRoundDown(const SetRoundDown&) = delete;\n        SetRoundDown &operator=(const SetRoundDown&) = delete;\n        SetRoundDown &operator=(SetRoundDown&&) = delete;\n        ~SetRoundDown() = default;\n    };\n\n    class SetRoundUp : private SetRound {\n    public:\n        explicit SetRoundUp() noexcept :\n            SetRound(FE_UPWARD)\n        {}\n\n        SetRoundUp(SetRoundUp&& o) noexcept :\n            SetRound()\n        {\n            m_prev = o.m_prev;\n            o.m_prev = invalid_rounding_mode;\n        }\n\n        SetRoundUp(const SetRoundUp&) = delete;\n        SetRoundUp &operator=(const SetRoundUp&) = delete;\n        SetRoundUp &operator=(SetRoundUp&&) = delete;\n        ~SetRoundUp() = default;\n    };\n}\n\nvoid ivarp::do_opacify(float &f) noexcept {\n#if BOOST_COMP_GNUC && !defined(IVARP_FORCE_OPACIFY)\n    (void)f;\n#elif BOOST_COMP_CLANG\n    asm volatile(\"\" : \"+mx\"(f));\n#else\n    volatile float f_ = f;\n    f = f_;\n#endif\n}\n\nvoid ivarp::do_opacify(double &d) noexcept {\n#if BOOST_COMP_GNUC && !defined(IVARP_FORCE_OPACIFY)\n    (void)d;\n#elif BOOST_COMP_CLANG\n    asm volatile(\"\" : \"+mx\"(d));\n#else\n    volatile double d_ = d;\n    d = d_;\n#endif\n}\n\nfloat ivarp::opacify(float f) noexcept {\n    do_opacify(f);\n    return f;\n}\n\ndouble ivarp::opacify(double d) noexcept {\n    do_opacify(d);\n    return d;\n}\n", "meta": {"hexsha": "dbbb58740801b5472848ac4bf8589525ac708a00", "size": 7430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ivarp/include/ivarp/rounding.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/rounding.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/rounding.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": 34.2396313364, "max_line_length": 165, "alphanum_fraction": 0.7114401077, "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2365162364457076, "lm_q2_score": 0.035678552928463655, "lm_q1q2_score": 0.008438557060469204}}
{"text": "#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n#include <boost/log/core.hpp>\n#include <boost/log/expressions.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/program_options.hpp>\n#include <cstdlib>\n#include <iostream>\n#include <regex>\n#include <string>\n\n#include \"coordinate_formatter.h\"\n#include \"lodepng/source/lodepng.h\"\n#include \"multibrot_opencl/multibrot_parallel_calculator.h\"\n#include \"utils/utils.h\"\n\n#ifdef WIN32\n#include <tchar.h>\n#include <windows.h>\n#endif\n\nnamespace {\nconstexpr const char* kDefaultSizePix = \"10000x10000\";\nconstexpr const char* kFirstPhaseTempFileRegexpr = R\"(^multibrot_\\d+_\\d+\\.png$)\";\nconstexpr const char* kRowTempFileRegexpr = R\"(row_\\d+\\.png)\";\n\ntemplate <typename P>\nstruct Constants {\n    static const LodePNGColorType pixel_format;\n    static const unsigned bit_depth;\n};\n\nconst LodePNGColorType Constants<cl_uchar>::pixel_format = LCT_GREY;\nconst unsigned Constants<cl_uchar>::bit_depth = 8;\n\nconst LodePNGColorType Constants<cl_ushort>::pixel_format = LCT_GREY;\nconst unsigned Constants<cl_ushort>::bit_depth = 16;\n\nconst LodePNGColorType Constants<cl_uchar4>::pixel_format = LCT_RGBA;\nconst unsigned Constants<cl_uchar4>::bit_depth = 8;\n\nconst LodePNGColorType Constants<cl_ushort4>::pixel_format = LCT_RGBA;\nconst unsigned Constants<cl_ushort4>::bit_depth = 16;\n\n#ifdef WIN32\nboost::filesystem::path FindTempDirectoryWin() {\n    TCHAR temp_buffer[MAX_PATH + 1];\n    GetTempPathA(MAX_PATH + 1, temp_buffer);\n    return boost::filesystem::path{temp_buffer};\n}\n#endif\n\n// Find a folder dedicated to temporary files\n// TODO move this to a separate class or contribute to another library?\nboost::filesystem::path FindTempDirectory() {\n#ifdef UNIX\n    return \"/tmp/multibrot_console/\";\n#elif defined WIN32\n    // Cache it, it may be relatively expensive\n    static boost::filesystem::path temp_dir = FindTempDirectoryWin();\n    return temp_dir / \"multibrot_console\";\n#else\n    // Use a subfolder in current folder on other systems\n    return \"./multibrot_console/\";\n#endif\n}\n\nvoid RemoveTemporaryFiles(const char* regexpr) {\n    std::regex regex{regexpr};\n    for (auto& dir : boost::filesystem::directory_iterator(FindTempDirectory())) {\n        if (std::regex_match(dir.path().filename().string(), regex)) {\n            BOOST_LOG_TRIVIAL(debug) << \"Removing file \" << dir.path();\n            if (!boost::filesystem::remove(dir.path())) {\n                BOOST_LOG_TRIVIAL(error) << \"Attempt to remove temporary file \" << dir.path()\n                                         << \" that didn't exist in the first place\";\n            }\n        }\n    }\n}\n\n// TODO move this to a separate class and remove temp folder in its destructor\nvoid PrepareTempFolder() {\n    using namespace boost::filesystem;\n    const path temp_folder = FindTempDirectory();\n    if (exists(temp_folder)) {\n        if (!is_directory(temp_folder)) {\n            throw std::runtime_error(\"Temporary folder name is taken by another file.\");\n        }\n    } else {\n        create_directories(temp_folder);\n    }\n}\n\ntemplate <typename P>\nvoid Execute(size_t total_width, size_t total_height, double power, int max_iterations) {\n    CoordinateFormatter formatter{total_width, total_height};\n\n    std::complex<double> min{-2.5, -2.0};\n    std::complex<double> max{1.5, 2.0};\n    MultibrotParallelCalculator<P> calculator{\n        total_width,\n        total_height,\n    };\n\n    PrepareTempFolder();\n    BOOST_LOG_TRIVIAL(info) << \"Deleting left-over temporary files from previous operation \"\n                               \"multibrot_*_xxxxx.png\";\n    RemoveTemporaryFiles(kFirstPhaseTempFileRegexpr);\n\n    BOOST_LOG_TRIVIAL(info) << \"Deleting left-over temporary files from previous operation \"\n                               \"row_xxxxx.png\";\n    RemoveTemporaryFiles(kRowTempFileRegexpr);\n\n    // TODO make these cached data structures thread-safe?\n    // List of segments stored by their y coordinates\n    // TODO is storing segments is needed at all?\n    std::unordered_map<size_t, std::vector<ImagePartitioner::Segment>> segments;\n    const boost::filesystem::path temp_folder{FindTempDirectory()};\n\n    calculator.Calculate(\n        min, max, power, max_iterations,\n        [&](const boost::compute::device& device, const ImagePartitioner::Segment& segment,\n            const P* result) {\n            auto segment_vector_iter = segments.find(segment.y);\n            if (segment_vector_iter == segments.end()) {\n                segment_vector_iter =\n                    segments\n                        .insert(std::make_pair(segment.y, std::vector<ImagePartitioner::Segment>()))\n                        .first;\n            }\n            segment_vector_iter->second.push_back(segment);\n\n            std::string filename = (boost::format(\"multibrot_%1%_%2%.png\") %\n                                    formatter.Format(segment.x) % formatter.Format(segment.y))\n                                       .str();\n            unsigned error = lodepng::encode(\n                (temp_folder / filename).string(), reinterpret_cast<const unsigned char*>(result),\n                segment.width_pix, segment.height_pix, Constants<P>::pixel_format,\n                Constants<P>::bit_depth);\n            if (error) {\n                BOOST_LOG_TRIVIAL(info) << \"Error when building PNG based on data by device \"\n                                        << device.name() << \" with size \" << segment.width_pix\n                                        << \"x\" << segment.height_pix << \" pixels.\";\n            }\n            BOOST_LOG_TRIVIAL(info)\n                << \"Batch on device \" << device.name() << \" with size \" << segment.width_pix << \"x\"\n                << segment.height_pix << \" pixels finished.\";\n        });\n\n    for (auto& row : segments) {\n        // TODO change call to ImageMagick by Magick++ library, that way there's no need\n        // to call dangerous method system(), installing it beforehand\n        // and possibly can be done in parallel\n        BOOST_LOG_TRIVIAL(info)\n            << \"Row building error code is \"\n            << system((boost::format(\n                           \"magick montage %1%/multibrot_*_%2%.png -tile x1 -mode Concatenate \"\n                           \"%1%/row_%2%.png\") %\n                       FindTempDirectory() % formatter.Format(row.first))\n                          .str()\n                          .c_str());\n    }\n\n    BOOST_LOG_TRIVIAL(info) << \"Deleting temporary files multibrot_*_xxxxx.png\";\n    RemoveTemporaryFiles(kFirstPhaseTempFileRegexpr);\n\n    BOOST_LOG_TRIVIAL(info) << \"Started building result image, it may take a while\";\n    BOOST_LOG_TRIVIAL(info)\n        << \"Result building error code is \"\n        << system((boost::format(\n                       \"magick montage %1%/row_*.png -tile 1x -mode Concatenate multibrot.png\") %\n                   FindTempDirectory())\n                      .str()\n                      .c_str());\n\n    BOOST_LOG_TRIVIAL(info) << \"Deleting temporary files row_xxxxx.png\";\n    RemoveTemporaryFiles(kRowTempFileRegexpr);\n}\n}  // namespace\n\nint main(int argc, char** argv) {\n    namespace log = boost::log::trivial;\n\n    double power = 2.0;\n    int bitdepth = 8;\n    bool color = true;\n    std::string size_pix;\n    int max_iterations = 255;\n    boost::program_options::options_description desc(\"Multibrot set plotter - console version.\");\n    {\n        using namespace boost::program_options;\n        // clang-format off\n        desc.add_options()\n            (\"help,h\", \"produce help message\")\n            (\"verbose,v\", \"verbose mode (more output is written to the console)\")\n            (\"version,V\", \"print version\")\n            (\"size,s\", value<std::string>(&size_pix)->default_value(std::string(kDefaultSizePix)),\n                \"image size in pixels, should be given separated by x. Default is 10000x10000 \"\n                \"(ten thousand by ten thousand pixels).\")\n            (\"power,p\", value<double>(&power)->default_value(2.0),\n                \"complex number power used during plotting. May be any real positive number \"\n                \"(negative values are possible but not supported at a moment). \"\n                \"Use 2 for a classic Mandelbrot set. Default is 2\")\n            (\"color,c\", \"build a color image. This is the default value.\")\n            (\"grayscale,g\", \"build a grayscale image. Mutually exclusive with --color\")\n            (\"bitdepth,b\", value<int>(&bitdepth)->default_value(8),\n                \"image bit depth. Values values are 8 are 16. Default value is 8\")\n            (\"max-iterations,m\", value<int>(&max_iterations)->default_value(255),\n                \"max iteration number. Must be less or equal to 255 \"\n                \"if bit depth is 8, or less or equal to 2^16 (65535) if bit depth is 16. \"\n                \"Default value is 255.\")\n            ;\n        // clang-format on\n    }\n\n    boost::program_options::variables_map vm;\n    try {\n        boost::program_options::store(\n            boost::program_options::parse_command_line(argc, argv, desc), vm);\n    } catch (boost::program_options::invalid_command_line_syntax& e) {\n        BOOST_LOG_TRIVIAL(fatal) << \"Invalid command line arguments: \" << e.what();\n        BOOST_LOG_TRIVIAL(fatal) << desc;\n        return EXIT_FAILURE;\n    } catch (std::exception& e) {\n        BOOST_LOG_TRIVIAL(fatal) << \"Caught exception when parsing command line arguments: \"\n                                 << e.what();\n        BOOST_LOG_TRIVIAL(fatal) << desc;\n        return EXIT_FAILURE;\n    }\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\")) {\n        BOOST_LOG_TRIVIAL(fatal) << desc;\n        return EXIT_FAILURE;\n    }\n\n    if (vm.count(\"verbose\")) {\n        BOOST_LOG_TRIVIAL(fatal) << desc;\n        return EXIT_FAILURE;\n    }\n\n    log::severity_level min_severity = (vm.count(\"verbose\") > 0) ? log::trace : log::info;\n    boost::log::core::get()->set_filter(log::severity >= min_severity);\n\n    // TODO support negative powers\n    if (power < 0) {\n        BOOST_LOG_TRIVIAL(fatal) << \"Sorry, negative powers are not yet supported.\";\n        BOOST_LOG_TRIVIAL(fatal) << desc;\n        return EXIT_FAILURE;\n    }\n\n    size_t total_width = 10000;\n    size_t total_height = 10000;\n    {\n        // Parse requested image size\n        size_t x_pos = 0;\n        total_width = std::stoull(size_pix, &x_pos);\n        if (size_pix.at(x_pos) != 'x' && size_pix.at(x_pos) != 'X') {\n            BOOST_LOG_TRIVIAL(fatal) << \"Size parameter has wrong format.\";\n            BOOST_LOG_TRIVIAL(fatal) << desc;\n            return EXIT_FAILURE;\n        }\n        total_height = std::strtoull(size_pix.c_str() + x_pos + 1, nullptr, 10);\n    }\n\n    if (vm.count(\"grayscale\") && vm.count(\"color\")) {\n        BOOST_LOG_TRIVIAL(fatal)\n            << \"Given mutually exclusive options --grayscale and --color parameters. \"\n               \"Select one of them.\";\n        BOOST_LOG_TRIVIAL(fatal) << desc;\n        return EXIT_FAILURE;\n    }\n\n    color = vm.count(\"grayscale\") == 0;\n\n    if (bitdepth != 8 && bitdepth != 16) {\n        BOOST_LOG_TRIVIAL(fatal) << \"Given incoorect bitdepth \" << bitdepth\n                                 << \", the only acceptable value are 8 and 16.\";\n        BOOST_LOG_TRIVIAL(fatal) << desc;\n        return EXIT_FAILURE;\n    }\n\n    try {\n        if (color) {\n            if (bitdepth == 8) {\n                Execute<cl_uchar4>(total_width, total_height, power, max_iterations);\n            } else if (bitdepth == 16) {\n                Execute<cl_ushort4>(total_width, total_height, power, max_iterations);\n            }\n        } else {\n            if (bitdepth == 8) {\n                Execute<cl_uchar>(total_width, total_height, power, max_iterations);\n            } else if (bitdepth == 16) {\n                Execute<cl_ushort>(total_width, total_height, power, max_iterations);\n            }\n        }\n    } catch (std::exception& e) {\n        BOOST_LOG_TRIVIAL(fatal) << \"Caught fatal exception: \" << e.what();\n        throw;\n    } catch (...) {\n        BOOST_LOG_TRIVIAL(fatal) << \"Caught fatal error\";\n        throw;\n    }\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0040283bde5cbb8c4049a09cd75ce35470a068db", "size": 12071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multibrot_console/multibrot_console_main.cpp", "max_stars_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_stars_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multibrot_console/multibrot_console_main.cpp", "max_issues_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_issues_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multibrot_console/multibrot_console_main.cpp", "max_forks_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_forks_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.319218241, "max_line_length": 100, "alphanum_fraction": 0.6108027504, "num_tokens": 2781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.029312230327373224, "lm_q1q2_score": 0.008435116496393091}}
{"text": "/*-----------------------------------------------------------------------------+\r\nCopyright (c) 2007-2012: Joachim Faulhaber\r\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\r\n+------------------------------------------------------------------------------+\r\n   Distributed under the Boost Software License, Version 1.0.\r\n      (See accompanying file LICENCE.txt or copy at\r\n           http://www.boost.org/LICENSE_1_0.txt)\r\n+-----------------------------------------------------------------------------*/\r\n#ifndef BOOST_ICL_INTERVAL_BASE_MAP_HPP_JOFA_990223\r\n#define BOOST_ICL_INTERVAL_BASE_MAP_HPP_JOFA_990223\r\n\r\n#include <limits>\r\n#include <boost/mpl/and.hpp>\r\n#include <boost/mpl/or.hpp>\r\n#include <boost/mpl/not.hpp>\r\n\r\n#include <boost/icl/detail/notate.hpp> \r\n#include <boost/icl/detail/design_config.hpp>\r\n#include <boost/icl/detail/on_absorbtion.hpp>\r\n#include <boost/icl/detail/interval_map_algo.hpp>\r\n#include <boost/icl/detail/exclusive_less_than.hpp>\r\n\r\n#include <boost/icl/associative_interval_container.hpp>\r\n\r\n#include <boost/icl/type_traits/is_interval_splitter.hpp>\r\n#include <boost/icl/map.hpp>\r\n\r\nnamespace boost{namespace icl\r\n{\r\n\r\ntemplate<class DomainT, class CodomainT>\r\nstruct mapping_pair\r\n{\r\n    DomainT   key;\r\n    CodomainT data;\r\n\r\n    mapping_pair():key(), data(){}\r\n\r\n    mapping_pair(const DomainT& key_value, const CodomainT& data_value)\r\n        :key(key_value), data(data_value){}\r\n\r\n    mapping_pair(const std::pair<DomainT,CodomainT>& std_pair)\r\n        :key(std_pair.first), data(std_pair.second){}\r\n};\r\n\r\n/** \\brief Implements a map as a map of intervals (base class) */\r\ntemplate\r\n<\r\n    class SubType,\r\n    typename DomainT,\r\n    typename CodomainT,\r\n    class Traits = icl::partial_absorber,\r\n    ICL_COMPARE Compare  = ICL_COMPARE_INSTANCE(ICL_COMPARE_DEFAULT, DomainT),\r\n    ICL_COMBINE Combine  = ICL_COMBINE_INSTANCE(icl::inplace_plus, CodomainT),\r\n    ICL_SECTION Section  = ICL_SECTION_INSTANCE(icl::inter_section, CodomainT), \r\n    ICL_INTERVAL(ICL_COMPARE) Interval = ICL_INTERVAL_INSTANCE(ICL_INTERVAL_DEFAULT, DomainT, Compare),\r\n    ICL_ALLOC   Alloc    = std::allocator\r\n>\r\nclass interval_base_map\r\n{\r\npublic:\r\n    //==========================================================================\r\n    //= Associated types\r\n    //==========================================================================\r\n    typedef interval_base_map<SubType,DomainT,CodomainT,\r\n                              Traits,Compare,Combine,Section,Interval,Alloc>\r\n                              type;\r\n\r\n    /// The designated \\e derived or \\e sub_type of this base class\r\n    typedef SubType sub_type;\r\n\r\n    /// Auxilliary type for overloadresolution\r\n    typedef type overloadable_type;\r\n\r\n    /// Traits of an itl map\r\n    typedef Traits traits;\r\n\r\n    //--------------------------------------------------------------------------\r\n    //- Associated types: Related types\r\n    //--------------------------------------------------------------------------\r\n    /// The atomized type representing the corresponding container of elements\r\n    typedef typename icl::map<DomainT,CodomainT,\r\n                              Traits,Compare,Combine,Section,Alloc> atomized_type;\r\n\r\n    //--------------------------------------------------------------------------\r\n    //- Associated types: Data\r\n    //--------------------------------------------------------------------------\r\n    /// Domain type (type of the keys) of the map\r\n    typedef DomainT   domain_type;\r\n    typedef typename boost::call_traits<DomainT>::param_type domain_param;\r\n    /// Domain type (type of the keys) of the map\r\n    typedef CodomainT codomain_type;\r\n    /// Auxiliary type to help the compiler resolve ambiguities when using std::make_pair\r\n    typedef mapping_pair<domain_type,codomain_type> domain_mapping_type;\r\n    /// Conceptual is a map a set of elements of type \\c element_type\r\n    typedef domain_mapping_type element_type;\r\n    /// The interval type of the map\r\n    typedef ICL_INTERVAL_TYPE(Interval,DomainT,Compare) interval_type;\r\n    /// Auxiliary type for overload resolution\r\n    typedef std::pair<interval_type,CodomainT> interval_mapping_type;\r\n    /// Type of an interval containers segment, that is spanned by an interval\r\n    typedef std::pair<interval_type,CodomainT> segment_type;\r\n\r\n    //--------------------------------------------------------------------------\r\n    //- Associated types: Size\r\n    //--------------------------------------------------------------------------\r\n    /// The difference type of an interval which is sometimes different form the domain_type\r\n    typedef typename difference_type_of<domain_type>::type difference_type;\r\n    /// The size type of an interval which is mostly std::size_t\r\n    typedef typename size_type_of<domain_type>::type size_type;\r\n\r\n    //--------------------------------------------------------------------------\r\n    //- Associated types: Functors\r\n    //--------------------------------------------------------------------------\r\n    /// Comparison functor for domain values\r\n    typedef ICL_COMPARE_DOMAIN(Compare,DomainT)      domain_compare;\r\n    typedef ICL_COMPARE_DOMAIN(Compare,segment_type) segment_compare;\r\n    /// Combine functor for codomain value aggregation\r\n    typedef ICL_COMBINE_CODOMAIN(Combine,CodomainT)  codomain_combine;\r\n    /// Inverse Combine functor for codomain value aggregation\r\n    typedef typename inverse<codomain_combine>::type inverse_codomain_combine;\r\n    /// Intersection functor for codomain values\r\n\r\n    typedef typename mpl::if_\r\n    <has_set_semantics<codomain_type>\r\n    , ICL_SECTION_CODOMAIN(Section,CodomainT)     \r\n    , codomain_combine\r\n    >::type                                            codomain_intersect;\r\n\r\n\r\n    /// Inverse Combine functor for codomain value intersection\r\n    typedef typename inverse<codomain_intersect>::type inverse_codomain_intersect;\r\n\r\n    /// Comparison functor for intervals which are keys as well\r\n    typedef exclusive_less_than<interval_type> interval_compare;\r\n\r\n    /// Comparison functor for keys\r\n    typedef exclusive_less_than<interval_type> key_compare;\r\n\r\n    //--------------------------------------------------------------------------\r\n    //- Associated types: Implementation and stl related\r\n    //--------------------------------------------------------------------------\r\n    /// The allocator type of the set\r\n    typedef Alloc<std::pair<const interval_type, codomain_type> > \r\n        allocator_type;\r\n\r\n    /// Container type for the implementation \r\n    typedef ICL_IMPL_SPACE::map<interval_type,codomain_type,\r\n                                key_compare,allocator_type> ImplMapT;\r\n\r\n    /// key type of the implementing container\r\n    typedef typename ImplMapT::key_type   key_type;\r\n    /// value type of the implementing container\r\n    typedef typename ImplMapT::value_type value_type;\r\n    /// data type of the implementing container\r\n    typedef typename ImplMapT::value_type::second_type data_type;\r\n\r\n    /// pointer type\r\n    typedef typename ImplMapT::pointer         pointer;\r\n    /// const pointer type\r\n    typedef typename ImplMapT::const_pointer   const_pointer;\r\n    /// reference type\r\n    typedef typename ImplMapT::reference       reference;\r\n    /// const reference type\r\n    typedef typename ImplMapT::const_reference const_reference;\r\n\r\n    /// iterator for iteration over intervals\r\n    typedef typename ImplMapT::iterator iterator;\r\n    /// const_iterator for iteration over intervals\r\n    typedef typename ImplMapT::const_iterator const_iterator;\r\n    /// iterator for reverse iteration over intervals\r\n    typedef typename ImplMapT::reverse_iterator reverse_iterator;\r\n    /// const_iterator for iteration over intervals\r\n    typedef typename ImplMapT::const_reverse_iterator const_reverse_iterator;\r\n\r\n    /// element iterator: Depreciated, see documentation.\r\n    typedef boost::icl::element_iterator<iterator> element_iterator; \r\n    /// const element iterator: Depreciated, see documentation.\r\n    typedef boost::icl::element_iterator<const_iterator> element_const_iterator; \r\n    /// element reverse iterator: Depreciated, see documentation.\r\n    typedef boost::icl::element_iterator<reverse_iterator> element_reverse_iterator; \r\n    /// element const reverse iterator: Depreciated, see documentation.\r\n    typedef boost::icl::element_iterator<const_reverse_iterator> element_const_reverse_iterator; \r\n    \r\n    typedef typename on_absorbtion<type, codomain_combine, \r\n                                Traits::absorbs_identities>::type on_codomain_absorbtion;\r\n\r\npublic:\r\n    BOOST_STATIC_CONSTANT(bool, \r\n        is_total_invertible = (   Traits::is_total \r\n                               && has_inverse<codomain_type>::value));\r\n\r\n    BOOST_STATIC_CONSTANT(int, fineness = 0); \r\n\r\npublic:\r\n\r\n    //==========================================================================\r\n    //= Construct, copy, destruct\r\n    //==========================================================================\r\n    /** Default constructor for the empty object */\r\n    interval_base_map()\r\n    {\r\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));\r\n        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));\r\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));\r\n        BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));\r\n    }\r\n\r\n    /** Copy constructor */\r\n    interval_base_map(const interval_base_map& src): _map(src._map)\r\n    {\r\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));\r\n        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));\r\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));\r\n        BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));\r\n    }\r\n\r\n#   ifndef BOOST_ICL_NO_CXX11_RVALUE_REFERENCES\r\n    //==========================================================================\r\n    //= Move semantics\r\n    //==========================================================================\r\n\r\n    /** Move constructor */\r\n    interval_base_map(interval_base_map&& src): _map(boost::move(src._map))\r\n    {\r\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<DomainT>));\r\n        BOOST_CONCEPT_ASSERT((LessThanComparableConcept<DomainT>));\r\n        BOOST_CONCEPT_ASSERT((DefaultConstructibleConcept<CodomainT>));\r\n        BOOST_CONCEPT_ASSERT((EqualComparableConcept<CodomainT>));\r\n    }\r\n\r\n    /** Move assignment operator */\r\n    interval_base_map& operator = (interval_base_map src) \r\n    {                           //call by value sice 'src' is a \"sink value\" \r\n        this->_map = boost::move(src._map);\r\n        return *this; \r\n    }\r\n\r\n    //==========================================================================\r\n#   else \r\n\r\n    /** Copy assignment operator */\r\n    interval_base_map& operator = (const interval_base_map& src) \r\n    { \r\n        this->_map = src._map;\r\n        return *this; \r\n    }\r\n\r\n#   endif // BOOST_ICL_NO_CXX11_RVALUE_REFERENCES\r\n\r\n    /** swap the content of containers */\r\n    void swap(interval_base_map& object) { _map.swap(object._map); }\r\n\r\n    //==========================================================================\r\n    //= Containedness\r\n    //==========================================================================\r\n    /** clear the map */\r\n    void clear() { icl::clear(*that()); }\r\n\r\n    /** is the map empty? */\r\n    bool empty()const { return icl::is_empty(*that()); }\r\n\r\n    //==========================================================================\r\n    //= Size\r\n    //==========================================================================\r\n    /** An interval map's size is it's cardinality */\r\n    size_type size()const\r\n    {\r\n        return icl::cardinality(*that());\r\n    }\r\n\r\n    /** Size of the iteration over this container */\r\n    std::size_t iterative_size()const \r\n    { \r\n        return _map.size(); \r\n    }\r\n\r\n    //==========================================================================\r\n    //= Selection\r\n    //==========================================================================\r\n\r\n    /** Find the interval value pair, that contains \\c key */\r\n    const_iterator find(const domain_type& key_value)const\r\n    { \r\n        return icl::find(*this, key_value);\r\n    }\r\n\r\n    /** Find the first interval value pair, that collides with interval \r\n        \\c key_interval */\r\n    const_iterator find(const interval_type& key_interval)const\r\n    { \r\n        return _map.find(key_interval); \r\n    }\r\n\r\n    /** Total select function. */\r\n    codomain_type operator()(const domain_type& key_value)const\r\n    {\r\n        const_iterator it_ = icl::find(*this, key_value);\r\n        return it_==end() ? identity_element<codomain_type>::value()\r\n                          : (*it_).second;\r\n    }\r\n\r\n    //==========================================================================\r\n    //= Addition\r\n    //==========================================================================\r\n\r\n    /** Addition of a key value pair to the map */\r\n    SubType& add(const element_type& key_value_pair) \r\n    {\r\n        return icl::add(*that(), key_value_pair);\r\n    }\r\n\r\n    /** Addition of an interval value pair to the map. */\r\n    SubType& add(const segment_type& interval_value_pair) \r\n    {\r\n        this->template _add<codomain_combine>(interval_value_pair);\r\n        return *that();\r\n    }\r\n\r\n    /** Addition of an interval value pair \\c interval_value_pair to the map. \r\n        Iterator \\c prior_ is a hint to the position \\c interval_value_pair can be \r\n        inserted after. */\r\n    iterator add(iterator prior_, const segment_type& interval_value_pair) \r\n    {\r\n        return this->template _add<codomain_combine>(prior_, interval_value_pair);\r\n    }\r\n\r\n    //==========================================================================\r\n    //= Subtraction\r\n    //==========================================================================\r\n    /** Subtraction of a key value pair from the map */\r\n    SubType& subtract(const element_type& key_value_pair)\r\n    { \r\n        return icl::subtract(*that(), key_value_pair);\r\n    }\r\n\r\n    /** Subtraction of an interval value pair from the map. */\r\n    SubType& subtract(const segment_type& interval_value_pair)\r\n    {\r\n        on_invertible<type, is_total_invertible>\r\n            ::subtract(*that(), interval_value_pair);\r\n        return *that();\r\n    }\r\n\r\n    //==========================================================================\r\n    //= Insertion\r\n    //==========================================================================\r\n    /** Insertion of a \\c key_value_pair into the map. */\r\n    SubType& insert(const element_type& key_value_pair) \r\n    {\r\n        return icl::insert(*that(), key_value_pair);\r\n    }\r\n\r\n    /** Insertion of an \\c interval_value_pair into the map. */\r\n    SubType& insert(const segment_type& interval_value_pair)\r\n    { \r\n        _insert(interval_value_pair); \r\n        return *that();\r\n    }\r\n\r\n    /** Insertion of an \\c interval_value_pair into the map. Iterator \\c prior_. \r\n        serves as a hint to insert after the element \\c prior point to. */\r\n    iterator insert(iterator prior, const segment_type& interval_value_pair)\r\n    { \r\n        return _insert(prior, interval_value_pair);\r\n    }\r\n\r\n    /** With <tt>key_value_pair = (k,v)</tt> set value \\c v for key \\c k */\r\n    SubType& set(const element_type& key_value_pair) \r\n    { \r\n        return icl::set_at(*that(), key_value_pair);\r\n    }\r\n\r\n    /** With <tt>interval_value_pair = (I,v)</tt> set value \\c v \r\n        for all keys in interval \\c I in the map. */\r\n    SubType& set(const segment_type& interval_value_pair)\r\n    { \r\n        return icl::set_at(*that(), interval_value_pair);\r\n    }\r\n\r\n    //==========================================================================\r\n    //= Erasure\r\n    //==========================================================================\r\n    /** Erase a \\c key_value_pair from the map. */\r\n    SubType& erase(const element_type& key_value_pair) \r\n    { \r\n        icl::erase(*that(), key_value_pair);\r\n        return *that();\r\n    }\r\n\r\n    /** Erase an \\c interval_value_pair from the map. */\r\n    SubType& erase(const segment_type& interval_value_pair);\r\n\r\n    /** Erase a key value pair for \\c key. */\r\n    SubType& erase(const domain_type& key) \r\n    { \r\n        return icl::erase(*that(), key); \r\n    }\r\n\r\n    /** Erase all value pairs within the range of the \r\n        interval <tt>inter_val</tt> from the map.   */\r\n    SubType& erase(const interval_type& inter_val);\r\n\r\n\r\n    /** Erase all value pairs within the range of the interval that iterator \r\n        \\c position points to. */\r\n    void erase(iterator position){ this->_map.erase(position); }\r\n\r\n    /** Erase all value pairs for a range of iterators <tt>[first,past)</tt>. */\r\n    void erase(iterator first, iterator past){ this->_map.erase(first, past); }\r\n\r\n    //==========================================================================\r\n    //= Intersection\r\n    //==========================================================================\r\n    /** The intersection of \\c interval_value_pair and \\c *this map is added to \\c section. */\r\n    void add_intersection(SubType& section, const segment_type& interval_value_pair)const\r\n    {\r\n        on_definedness<SubType, Traits::is_total>\r\n            ::add_intersection(section, *that(), interval_value_pair);\r\n    }\r\n\r\n    //==========================================================================\r\n    //= Symmetric difference\r\n    //==========================================================================\r\n    /** If \\c *this map contains \\c key_value_pair it is erased, otherwise it is added. */\r\n    SubType& flip(const element_type& key_value_pair)\r\n    { \r\n        return icl::flip(*that(), key_value_pair); \r\n    }\r\n\r\n    /** If \\c *this map contains \\c interval_value_pair it is erased, otherwise it is added. */\r\n    SubType& flip(const segment_type& interval_value_pair)\r\n    {\r\n        on_total_absorbable<SubType, Traits::is_total, Traits::absorbs_identities>\r\n            ::flip(*that(), interval_value_pair);\r\n        return *that();\r\n    }\r\n\r\n    //==========================================================================\r\n    //= Iterator related\r\n    //==========================================================================\r\n\r\n    iterator lower_bound(const key_type& interval)\r\n    { return _map.lower_bound(interval); }\r\n\r\n    iterator upper_bound(const key_type& interval)\r\n    { return _map.upper_bound(interval); }\r\n\r\n    const_iterator lower_bound(const key_type& interval)const\r\n    { return _map.lower_bound(interval); }\r\n\r\n    const_iterator upper_bound(const key_type& interval)const\r\n    { return _map.upper_bound(interval); }\r\n\r\n    std::pair<iterator,iterator> equal_range(const key_type& interval)\r\n    { \r\n        return std::pair<iterator,iterator>\r\n               (lower_bound(interval), upper_bound(interval)); \r\n    }\r\n\r\n    std::pair<const_iterator,const_iterator> \r\n        equal_range(const key_type& interval)const\r\n    { \r\n        return std::pair<const_iterator,const_iterator>\r\n               (lower_bound(interval), upper_bound(interval)); \r\n    }\r\n\r\n    iterator begin() { return _map.begin(); }\r\n    iterator end()   { return _map.end(); }\r\n    const_iterator begin()const { return _map.begin(); }\r\n    const_iterator end()const   { return _map.end(); }\r\n    reverse_iterator rbegin() { return _map.rbegin(); }\r\n    reverse_iterator rend()   { return _map.rend(); }\r\n    const_reverse_iterator rbegin()const { return _map.rbegin(); }\r\n    const_reverse_iterator rend()const   { return _map.rend(); }\r\n\r\nprivate:\r\n    template<class Combiner>\r\n    iterator _add(const segment_type& interval_value_pair);\r\n\r\n    template<class Combiner>\r\n    iterator _add(iterator prior_, const segment_type& interval_value_pair);\r\n\r\n    template<class Combiner>\r\n    void _subtract(const segment_type& interval_value_pair);\r\n\r\n    iterator _insert(const segment_type& interval_value_pair);\r\n    iterator _insert(iterator prior_, const segment_type& interval_value_pair);\r\n\r\nprivate:\r\n    template<class Combiner>\r\n    void add_segment(const interval_type& inter_val, const CodomainT& co_val, iterator& it_);\r\n\r\n    template<class Combiner>\r\n    void add_main(interval_type& inter_val, const CodomainT& co_val, \r\n                  iterator& it_, const iterator& last_);\r\n\r\n    template<class Combiner>\r\n    void add_rear(const interval_type& inter_val, const CodomainT& co_val, iterator& it_);\r\n\r\n    void add_front(const interval_type& inter_val, iterator& first_);\r\n\r\nprivate:\r\n    void subtract_front(const interval_type& inter_val, iterator& first_);\r\n\r\n    template<class Combiner>\r\n    void subtract_main(const CodomainT& co_val, iterator& it_, const iterator& last_);\r\n\r\n    template<class Combiner>\r\n    void subtract_rear(interval_type& inter_val, const CodomainT& co_val, iterator& it_);\r\n\r\nprivate:\r\n    void insert_main(const interval_type&, const CodomainT&, iterator&, const iterator&);\r\n    void erase_rest (      interval_type&, const CodomainT&, iterator&, const iterator&);\r\n\r\n    template<class FragmentT>\r\n    void total_add_intersection(SubType& section, const FragmentT& fragment)const\r\n    {\r\n        section += *that();\r\n        section.add(fragment);\r\n    }\r\n\r\n    void partial_add_intersection(SubType& section, const segment_type& operand)const\r\n    {\r\n        interval_type inter_val = operand.first;\r\n        if(icl::is_empty(inter_val)) \r\n            return;\r\n\r\n        std::pair<const_iterator, const_iterator> exterior = equal_range(inter_val);\r\n        if(exterior.first == exterior.second)\r\n            return;\r\n\r\n        for(const_iterator it_=exterior.first; it_ != exterior.second; it_++) \r\n        {\r\n            interval_type common_interval = (*it_).first & inter_val; \r\n            if(!icl::is_empty(common_interval))\r\n            {\r\n                section.template _add<codomain_combine>  (value_type(common_interval, (*it_).second) );\r\n                section.template _add<codomain_intersect>(value_type(common_interval, operand.second));\r\n            }\r\n        }\r\n    }\r\n\r\n    void partial_add_intersection(SubType& section, const element_type& operand)const\r\n    {\r\n        partial_add_intersection(section, make_segment<type>(operand));\r\n    }\r\n\r\n\r\nprotected:\r\n\r\n    template <class Combiner>\r\n    iterator gap_insert(iterator prior_, const interval_type& inter_val, \r\n                                         const codomain_type& co_val   )\r\n    {\r\n        // inter_val is not conained in this map. Insertion will be successful\r\n        BOOST_ASSERT(this->_map.find(inter_val) == this->_map.end());\r\n        BOOST_ASSERT((!on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val)));\r\n        return this->_map.insert(prior_, value_type(inter_val, version<Combiner>()(co_val)));\r\n    }\r\n\r\n    template <class Combiner>\r\n    std::pair<iterator, bool>\r\n    add_at(const iterator& prior_, const interval_type& inter_val, \r\n                                   const codomain_type& co_val   )\r\n    {\r\n        // Never try to insert an identity element into an identity element absorber here:\r\n        BOOST_ASSERT((!(on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val))));\r\n\r\n        iterator inserted_ \r\n            = this->_map.insert(prior_, value_type(inter_val, Combiner::identity_element()));\r\n\r\n        if((*inserted_).first == inter_val && (*inserted_).second == Combiner::identity_element())\r\n        {\r\n            Combiner()((*inserted_).second, co_val);\r\n            return std::pair<iterator,bool>(inserted_, true);\r\n        }\r\n        else\r\n            return std::pair<iterator,bool>(inserted_, false);\r\n    }\r\n\r\n    std::pair<iterator, bool>\r\n    insert_at(const iterator& prior_, const interval_type& inter_val, \r\n                                      const codomain_type& co_val   )\r\n    {\r\n        iterator inserted_\r\n            = this->_map.insert(prior_, value_type(inter_val, co_val));\r\n\r\n        if(inserted_ == prior_)\r\n            return std::pair<iterator,bool>(inserted_, false);\r\n        else if((*inserted_).first == inter_val)\r\n            return std::pair<iterator,bool>(inserted_, true);\r\n        else\r\n            return std::pair<iterator,bool>(inserted_, false);\r\n    }\r\n\r\n\r\nprotected:\r\n    sub_type* that() { return static_cast<sub_type*>(this); }\r\n    const sub_type* that()const { return static_cast<const sub_type*>(this); }\r\n\r\nprotected:\r\n    ImplMapT _map;\r\n\r\n\r\nprivate:\r\n    //--------------------------------------------------------------------------\r\n    template<class Type, bool is_total_invertible>\r\n    struct on_invertible;\r\n\r\n    template<class Type>\r\n    struct on_invertible<Type, true>\r\n    {\r\n        typedef typename Type::segment_type segment_type;\r\n        typedef typename Type::inverse_codomain_combine inverse_codomain_combine;\r\n\r\n        static void subtract(Type& object, const segment_type& operand)\r\n        { object.template _add<inverse_codomain_combine>(operand); }\r\n    };\r\n\r\n    template<class Type>\r\n    struct on_invertible<Type, false>\r\n    {\r\n        typedef typename Type::segment_type segment_type;\r\n        typedef typename Type::inverse_codomain_combine inverse_codomain_combine;\r\n\r\n        static void subtract(Type& object, const segment_type& operand)\r\n        { object.template _subtract<inverse_codomain_combine>(operand); }\r\n    };\r\n\r\n    friend struct on_invertible<type, true>;\r\n    friend struct on_invertible<type, false>;\r\n    //--------------------------------------------------------------------------\r\n\r\n    //--------------------------------------------------------------------------\r\n    template<class Type, bool is_total>\r\n    struct on_definedness;\r\n\r\n    template<class Type>\r\n    struct on_definedness<Type, true>\r\n    {\r\n        static void add_intersection(Type& section, const Type& object, \r\n                                     const segment_type& operand)\r\n        { object.total_add_intersection(section, operand); }\r\n    };\r\n\r\n    template<class Type>\r\n    struct on_definedness<Type, false>\r\n    {\r\n        static void add_intersection(Type& section, const Type& object, \r\n                                     const segment_type& operand)\r\n        { object.partial_add_intersection(section, operand); }\r\n    };\r\n\r\n    friend struct on_definedness<type, true>;\r\n    friend struct on_definedness<type, false>;\r\n    //--------------------------------------------------------------------------\r\n\r\n    //--------------------------------------------------------------------------\r\n    template<class Type, bool has_set_semantics> \r\n    struct on_codomain_model;\r\n\r\n    template<class Type>\r\n    struct on_codomain_model<Type, true>\r\n    {\r\n        typedef typename Type::interval_type interval_type;\r\n        typedef typename Type::codomain_type codomain_type;\r\n        typedef typename Type::segment_type  segment_type;\r\n        typedef typename Type::codomain_combine codomain_combine;\r\n        typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;\r\n\r\n        static void add(Type& intersection, interval_type& common_interval, \r\n                        const codomain_type& flip_value, const codomain_type& co_value)\r\n        {\r\n            codomain_type common_value = flip_value;\r\n            inverse_codomain_intersect()(common_value, co_value);\r\n            intersection.template \r\n                _add<codomain_combine>(segment_type(common_interval, common_value));\r\n        }\r\n    };\r\n\r\n    template<class Type>\r\n    struct on_codomain_model<Type, false>\r\n    {\r\n        typedef typename Type::interval_type interval_type;\r\n        typedef typename Type::codomain_type codomain_type;\r\n        typedef typename Type::segment_type  segment_type;\r\n        typedef typename Type::codomain_combine codomain_combine;\r\n\r\n        static void add(Type& intersection, interval_type& common_interval, \r\n                        const codomain_type&, const codomain_type&)\r\n        {\r\n            intersection.template \r\n              _add<codomain_combine>(segment_type(common_interval, \r\n                                                  identity_element<codomain_type>::value()));\r\n        }\r\n    };\r\n\r\n    friend struct on_codomain_model<type, true>;\r\n    friend struct on_codomain_model<type, false>;\r\n    //--------------------------------------------------------------------------\r\n\r\n\r\n    //--------------------------------------------------------------------------\r\n    template<class Type, bool is_total, bool absorbs_identities>\r\n    struct on_total_absorbable;\r\n\r\n    template<class Type>\r\n    struct on_total_absorbable<Type, true, true>\r\n    {\r\n        static void flip(Type& object, const typename Type::segment_type&)\r\n        { icl::clear(object); }\r\n    };\r\n\r\n#ifdef BOOST_MSVC \r\n#pragma warning(push)\r\n#pragma warning(disable:4127) // conditional expression is constant\r\n#endif                        \r\n\r\n    template<class Type>\r\n    struct on_total_absorbable<Type, true, false>\r\n    {\r\n        typedef typename Type::segment_type  segment_type;\r\n        typedef typename Type::codomain_type codomain_type;\r\n\r\n        static void flip(Type& object, const segment_type& operand)\r\n        { \r\n            object += operand;\r\n            ICL_FORALL(typename Type, it_, object)\r\n                (*it_).second = identity_element<codomain_type>::value();\r\n\r\n            if(mpl::not_<is_interval_splitter<Type> >::value)\r\n                icl::join(object);\r\n        }\r\n    };\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning(pop)\r\n#endif\r\n\r\n    template<class Type, bool absorbs_identities>\r\n    struct on_total_absorbable<Type, false, absorbs_identities>\r\n    {\r\n        typedef typename Type::segment_type   segment_type;\r\n        typedef typename Type::codomain_type  codomain_type;\r\n        typedef typename Type::interval_type  interval_type;\r\n        typedef typename Type::value_type     value_type;\r\n        typedef typename Type::const_iterator const_iterator;\r\n        typedef typename Type::set_type       set_type;\r\n        typedef typename Type::inverse_codomain_intersect inverse_codomain_intersect;\r\n\r\n        static void flip(Type& object, const segment_type& interval_value_pair)\r\n        {\r\n            // That which is common shall be subtracted\r\n            // That which is not shall be added\r\n            // So interval_value_pair has to be 'complementary added' or flipped\r\n            interval_type span = interval_value_pair.first;\r\n            std::pair<const_iterator, const_iterator> exterior \r\n                = object.equal_range(span);\r\n\r\n            const_iterator first_ = exterior.first;\r\n            const_iterator end_   = exterior.second;\r\n\r\n            interval_type covered, left_over, common_interval;\r\n            const codomain_type& x_value = interval_value_pair.second;\r\n            const_iterator it_ = first_;\r\n\r\n            set_type eraser;\r\n            Type     intersection;\r\n\r\n            while(it_ != end_  ) \r\n            {\r\n                const codomain_type& co_value = (*it_).second;\r\n                covered = (*it_++).first;\r\n                //[a      ...  : span\r\n                //     [b ...  : covered\r\n                //[a  b)       : left_over\r\n                left_over = right_subtract(span, covered);\r\n\r\n                //That which is common ...\r\n                common_interval = span & covered;\r\n                if(!icl::is_empty(common_interval))\r\n                {\r\n                    // ... shall be subtracted\r\n                    icl::add(eraser, common_interval);\r\n\r\n                    on_codomain_model<Type, has_set_semantics<codomain_type>::value>\r\n                        ::add(intersection, common_interval, x_value, co_value);\r\n                }\r\n\r\n                icl::add(object, value_type(left_over, x_value)); //That which is not shall be added\r\n                // Because this is a collision free addition I don't have to distinguish codomain_types.\r\n\r\n                //...      d) : span\r\n                //... c)      : covered\r\n                //     [c  d) : span'\r\n                span = left_subtract(span, covered);\r\n            }\r\n\r\n            //If span is not empty here, it is not in the set so it shall be added\r\n            icl::add(object, value_type(span, x_value));\r\n\r\n            //finally rewrite the common segments\r\n            icl::erase(object, eraser);\r\n            object += intersection;\r\n        }\r\n    };\r\n    //--------------------------------------------------------------------------\r\n} ;\r\n\r\n\r\n//==============================================================================\r\n//= Addition detail\r\n//==============================================================================\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::add_front(const interval_type& inter_val, iterator& first_)\r\n{\r\n    // If the collision sequence has a left residual 'left_resid' it will\r\n    // be split, to provide a standardized start of algorithms:\r\n    // The addend interval 'inter_val' covers the beginning of the collision sequence.\r\n\r\n    // only for the first there can be a left_resid: a part of *first_ left of inter_val\r\n    interval_type left_resid = right_subtract((*first_).first, inter_val);\r\n\r\n    if(!icl::is_empty(left_resid))\r\n    {   //            [------------ . . .\r\n        // [left_resid---first_ --- . . .\r\n        iterator prior_ = cyclic_prior(*this, first_);\r\n        const_cast<interval_type&>((*first_).first) \r\n            = left_subtract((*first_).first, left_resid);\r\n        //NOTE: Only splitting\r\n        this->_map.insert(prior_, segment_type(left_resid, (*first_).second));\r\n    }\r\n    //POST:\r\n    // [----- inter_val ---- . . .\r\n    // ...[-- first_ --...\r\n}\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::add_segment(const interval_type& inter_val, const CodomainT& co_val, iterator& it_)\r\n{\r\n    interval_type lead_gap = right_subtract(inter_val, (*it_).first);\r\n    if(!icl::is_empty(lead_gap))\r\n    {\r\n        // [lead_gap--- . . .\r\n        //          [-- it_ ...\r\n        iterator prior_ = it_==this->_map.begin()? it_ : prior(it_); \r\n        iterator inserted_ = this->template gap_insert<Combiner>(prior_, lead_gap, co_val);\r\n        that()->handle_inserted(prior_, inserted_);\r\n    }\r\n\r\n    // . . . --------- . . . addend interval\r\n    //      [-- it_ --)      has a common part with the first overval\r\n    Combiner()((*it_).second, co_val);\r\n    that()->template handle_left_combined<Combiner>(it_++);\r\n}\r\n\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::add_main(interval_type& inter_val, const CodomainT& co_val, \r\n               iterator& it_, const iterator& last_)\r\n{\r\n    interval_type cur_interval;\r\n    while(it_!=last_)\r\n    {\r\n        cur_interval = (*it_).first ;\r\n        add_segment<Combiner>(inter_val, co_val, it_);\r\n        // shrink interval\r\n        inter_val = left_subtract(inter_val, cur_interval);\r\n    }\r\n}\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::add_rear(const interval_type& inter_val, const CodomainT& co_val, iterator& it_)\r\n{\r\n    iterator prior_ = cyclic_prior(*that(), it_);\r\n    interval_type cur_itv = (*it_).first ;\r\n\r\n    interval_type lead_gap = right_subtract(inter_val, cur_itv);\r\n    if(!icl::is_empty(lead_gap))\r\n    {   //         [lead_gap--- . . .\r\n        // [prior)          [-- it_ ...\r\n        iterator inserted_ = this->template gap_insert<Combiner>(prior_, lead_gap, co_val);\r\n        that()->handle_inserted(prior_, inserted_);\r\n    }\r\n\r\n    interval_type end_gap = left_subtract(inter_val, cur_itv);\r\n    if(!icl::is_empty(end_gap))\r\n    {\r\n        // [----------------end_gap)\r\n        //  . . . -- it_ --)\r\n        Combiner()((*it_).second, co_val);\r\n        that()->template gap_insert_at<Combiner>(it_, prior_, end_gap, co_val);\r\n    }\r\n    else\r\n    {\r\n        // only for the last there can be a right_resid: a part of *it_ right of x\r\n        interval_type right_resid = left_subtract(cur_itv, inter_val);\r\n\r\n        if(icl::is_empty(right_resid))\r\n        {\r\n            // [---------------)\r\n            //      [-- it_ ---)\r\n            Combiner()((*it_).second, co_val);\r\n            that()->template handle_preceeded_combined<Combiner>(prior_, it_);\r\n        }\r\n        else\r\n        {\r\n            // [--------------)\r\n            //      [-- it_ --right_resid)\r\n            const_cast<interval_type&>((*it_).first) = right_subtract((*it_).first, right_resid);\r\n\r\n            //NOTE: This is NOT an insertion that has to take care for correct application of\r\n            // the Combiner functor. It only reestablished that state after splitting the\r\n            // 'it_' interval value pair. Using _map_insert<Combiner> does not work here.\r\n            iterator insertion_ = this->_map.insert(it_, value_type(right_resid, (*it_).second));\r\n            that()->handle_reinserted(insertion_);\r\n\r\n            Combiner()((*it_).second, co_val);\r\n            that()->template handle_preceeded_combined<Combiner>(insertion_, it_);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n//==============================================================================\r\n//= Addition\r\n//==============================================================================\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator\r\n    interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::_add(const segment_type& addend)\r\n{\r\n    typedef typename on_absorbtion<type,Combiner,\r\n                                absorbs_identities<type>::value>::type on_absorbtion_;\r\n\r\n    const interval_type& inter_val = addend.first;\r\n    if(icl::is_empty(inter_val)) \r\n        return this->_map.end();\r\n\r\n    const codomain_type& co_val = addend.second;\r\n    if(on_absorbtion_::is_absorbable(co_val))\r\n        return this->_map.end();\r\n\r\n    std::pair<iterator,bool> insertion \r\n        = this->_map.insert(value_type(inter_val, version<Combiner>()(co_val)));\r\n\r\n    if(insertion.second)\r\n        return that()->handle_inserted(insertion.first);\r\n    else\r\n    {\r\n        // Detect the first and the end iterator of the collision sequence\r\n        iterator first_ = this->_map.lower_bound(inter_val),\r\n                 last_  = prior(this->_map.upper_bound(inter_val));\r\n        //assert(end_ == this->_map.upper_bound(inter_val));\r\n        iterator it_ = first_;\r\n        interval_type rest_interval = inter_val;\r\n\r\n        add_front         (rest_interval,         it_       );\r\n        add_main<Combiner>(rest_interval, co_val, it_, last_);\r\n        add_rear<Combiner>(rest_interval, co_val, it_       );\r\n        return it_;\r\n    }\r\n}\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator\r\n    interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::_add(iterator prior_, const segment_type& addend)\r\n{\r\n    typedef typename on_absorbtion<type,Combiner,\r\n                                absorbs_identities<type>::value>::type on_absorbtion_;\r\n\r\n    const interval_type& inter_val = addend.first;\r\n    if(icl::is_empty(inter_val)) \r\n        return prior_;\r\n\r\n    const codomain_type& co_val = addend.second;\r\n    if(on_absorbtion_::is_absorbable(co_val))\r\n        return prior_;\r\n\r\n    std::pair<iterator,bool> insertion \r\n        = add_at<Combiner>(prior_, inter_val, co_val);\r\n\r\n    if(insertion.second)\r\n        return that()->handle_inserted(insertion.first);\r\n    else\r\n    {\r\n        // Detect the first and the end iterator of the collision sequence\r\n        std::pair<iterator,iterator> overlap = equal_range(inter_val);\r\n        iterator it_   = overlap.first,\r\n                 last_ = prior(overlap.second);\r\n        interval_type rest_interval = inter_val;\r\n\r\n        add_front         (rest_interval,         it_       );\r\n        add_main<Combiner>(rest_interval, co_val, it_, last_);\r\n        add_rear<Combiner>(rest_interval, co_val, it_       );\r\n        return it_;\r\n    }\r\n}\r\n\r\n//==============================================================================\r\n//= Subtraction detail\r\n//==============================================================================\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::subtract_front(const interval_type& inter_val, iterator& it_)\r\n{\r\n    interval_type left_resid = right_subtract((*it_).first, inter_val);\r\n\r\n    if(!icl::is_empty(left_resid)) //                     [--- inter_val ---)\r\n    {                              //[prior_) [left_resid)[--- it_ . . .\r\n        iterator prior_ = cyclic_prior(*this, it_); \r\n        const_cast<interval_type&>((*it_).first) = left_subtract((*it_).first, left_resid);\r\n        this->_map.insert(prior_, value_type(left_resid, (*it_).second));\r\n        // The segemnt *it_ is split at inter_val.first(), so as an invariant\r\n        // segment *it_ is always \"under\" inter_val and a left_resid is empty.\r\n    }\r\n}\r\n\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::subtract_main(const CodomainT& co_val, iterator& it_, const iterator& last_)\r\n{\r\n    while(it_ != last_)\r\n    {\r\n        Combiner()((*it_).second, co_val);\r\n        that()->template handle_left_combined<Combiner>(it_++);\r\n    }\r\n}\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::subtract_rear(interval_type& inter_val, const CodomainT& co_val, iterator& it_)\r\n{\r\n    interval_type right_resid = left_subtract((*it_).first, inter_val);\r\n\r\n    if(icl::is_empty(right_resid))\r\n    {\r\n        Combiner()((*it_).second, co_val);\r\n        that()->template handle_combined<Combiner>(it_);\r\n    }\r\n    else\r\n    {\r\n        const_cast<interval_type&>((*it_).first) = right_subtract((*it_).first, right_resid);\r\n        iterator next_ = this->_map.insert(it_, value_type(right_resid, (*it_).second));\r\n        Combiner()((*it_).second, co_val);\r\n        that()->template handle_succeeded_combined<Combiner>(it_, next_);\r\n    }\r\n}\r\n\r\n//==============================================================================\r\n//= Subtraction\r\n//==============================================================================\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\n    template<class Combiner>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::_subtract(const segment_type& minuend)\r\n{\r\n    interval_type inter_val = minuend.first;\r\n    if(icl::is_empty(inter_val)) \r\n        return;\r\n\r\n    const codomain_type& co_val = minuend.second;\r\n    if(on_absorbtion<type,Combiner,Traits::absorbs_identities>::is_absorbable(co_val)) \r\n        return;\r\n\r\n    std::pair<iterator, iterator> exterior = equal_range(inter_val);\r\n    if(exterior.first == exterior.second)\r\n        return;\r\n\r\n    iterator last_  = prior(exterior.second);\r\n    iterator it_    = exterior.first;\r\n    subtract_front          (inter_val,         it_       );\r\n    subtract_main <Combiner>(           co_val, it_, last_);\r\n    subtract_rear <Combiner>(inter_val, co_val, it_       );\r\n}\r\n\r\n//==============================================================================\r\n//= Insertion\r\n//==============================================================================\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::insert_main(const interval_type& inter_val, const CodomainT& co_val, \r\n                  iterator& it_, const iterator& last_)\r\n{\r\n    iterator end_   = boost::next(last_);\r\n    iterator prior_ = cyclic_prior(*this,it_), inserted_;\r\n    interval_type rest_interval = inter_val, left_gap, cur_itv;\r\n    interval_type last_interval = last_ ->first;\r\n\r\n    while(it_ != end_  )\r\n    {\r\n        cur_itv = (*it_).first ;            \r\n        left_gap = right_subtract(rest_interval, cur_itv);\r\n\r\n        if(!icl::is_empty(left_gap))\r\n        {\r\n            inserted_ = this->_map.insert(prior_, value_type(left_gap, co_val));\r\n            it_ = that()->handle_inserted(inserted_);\r\n        }\r\n\r\n        // shrink interval\r\n        rest_interval = left_subtract(rest_interval, cur_itv);\r\n        prior_ = it_;\r\n        ++it_;\r\n    }\r\n\r\n    //insert_rear(rest_interval, co_val, last_):\r\n    interval_type end_gap = left_subtract(rest_interval, last_interval);\r\n    if(!icl::is_empty(end_gap))\r\n    {\r\n        inserted_ = this->_map.insert(prior_, value_type(end_gap, co_val));\r\n        it_ = that()->handle_inserted(inserted_);\r\n    }\r\n    else\r\n        it_ = prior_;\r\n}\r\n\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator\r\n    interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::_insert(const segment_type& addend)\r\n{\r\n    interval_type inter_val = addend.first;\r\n    if(icl::is_empty(inter_val)) \r\n        return this->_map.end();\r\n\r\n    const codomain_type& co_val = addend.second;\r\n    if(on_codomain_absorbtion::is_absorbable(co_val)) \r\n        return this->_map.end();\r\n\r\n    std::pair<iterator,bool> insertion = this->_map.insert(addend);\r\n\r\n    if(insertion.second)\r\n        return that()->handle_inserted(insertion.first);\r\n    else\r\n    {\r\n        // Detect the first and the end iterator of the collision sequence\r\n        iterator first_ = this->_map.lower_bound(inter_val),\r\n                 last_  = prior(this->_map.upper_bound(inter_val));\r\n        //assert((++last_) == this->_map.upper_bound(inter_val));\r\n        iterator it_ = first_;\r\n        insert_main(inter_val, co_val, it_, last_);\r\n        return it_;\r\n    }\r\n}\r\n\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline typename interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>::iterator\r\n    interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::_insert(iterator prior_, const segment_type& addend)\r\n{\r\n    interval_type inter_val = addend.first;\r\n    if(icl::is_empty(inter_val)) \r\n        return prior_;\r\n\r\n    const codomain_type& co_val = addend.second;\r\n    if(on_codomain_absorbtion::is_absorbable(co_val)) \r\n        return prior_;\r\n\r\n    std::pair<iterator,bool> insertion = insert_at(prior_, inter_val, co_val);\r\n\r\n    if(insertion.second)\r\n        return that()->handle_inserted(insertion.first);\r\n    {\r\n        // Detect the first and the end iterator of the collision sequence\r\n        std::pair<iterator,iterator> overlap = equal_range(inter_val);\r\n        iterator it_    = overlap.first,\r\n                 last_  = prior(overlap.second);\r\n        insert_main(inter_val, co_val, it_, last_);\r\n        return it_;\r\n    }\r\n}\r\n\r\n//==============================================================================\r\n//= Erasure segment_type\r\n//==============================================================================\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline void interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::erase_rest(interval_type& inter_val, const CodomainT& co_val, \r\n                 iterator& it_, const iterator& last_)\r\n{\r\n    // For all intervals within loop: (*it_).first are contained_in inter_val\r\n    while(it_ != last_)\r\n        if((*it_).second == co_val)\r\n            this->_map.erase(it_++); \r\n        else it_++;\r\n\r\n    //erase_rear:\r\n    if((*it_).second == co_val)\r\n    {\r\n        interval_type right_resid = left_subtract((*it_).first, inter_val);\r\n        if(icl::is_empty(right_resid))\r\n            this->_map.erase(it_);\r\n        else\r\n            const_cast<interval_type&>((*it_).first) = right_resid;\r\n    }\r\n}\r\n\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline SubType& interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::erase(const segment_type& minuend)\r\n{\r\n    interval_type inter_val = minuend.first;\r\n    if(icl::is_empty(inter_val)) \r\n        return *that();\r\n\r\n    const codomain_type& co_val = minuend.second;\r\n    if(on_codomain_absorbtion::is_absorbable(co_val))\r\n        return *that();\r\n\r\n    std::pair<iterator,iterator> exterior = equal_range(inter_val);\r\n    if(exterior.first == exterior.second)\r\n        return *that();\r\n\r\n    iterator first_ = exterior.first, end_ = exterior.second, \r\n             last_  = cyclic_prior(*this, end_);\r\n    iterator second_= first_; ++second_;\r\n\r\n    if(first_ == last_) \r\n    {   //     [----inter_val----)\r\n        //   .....first_==last_.....\r\n        // only for the last there can be a right_resid: a part of *it_ right of minuend\r\n        interval_type right_resid = left_subtract((*first_).first, inter_val);\r\n\r\n        if((*first_).second == co_val)\r\n        {   \r\n            interval_type left_resid = right_subtract((*first_).first, inter_val);\r\n            if(!icl::is_empty(left_resid)) //            [----inter_val----)\r\n            {                              // [left_resid)..first_==last_......\r\n                const_cast<interval_type&>((*first_).first) = left_resid;\r\n                if(!icl::is_empty(right_resid))\r\n                    this->_map.insert(first_, value_type(right_resid, co_val));\r\n            }\r\n            else if(!icl::is_empty(right_resid))\r\n                const_cast<interval_type&>((*first_).first) = right_resid;\r\n            else\r\n                this->_map.erase(first_);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // first AND NOT last\r\n        if((*first_).second == co_val)\r\n        {\r\n            interval_type left_resid = right_subtract((*first_).first, inter_val);\r\n            if(icl::is_empty(left_resid))\r\n                this->_map.erase(first_);\r\n            else\r\n                const_cast<interval_type&>((*first_).first) = left_resid;\r\n        }\r\n\r\n        erase_rest(inter_val, co_val, second_, last_);\r\n    }\r\n\r\n     return *that();\r\n}\r\n\r\n//==============================================================================\r\n//= Erasure key_type\r\n//==============================================================================\r\ntemplate <class SubType, class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc>\r\ninline SubType& interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc>\r\n    ::erase(const interval_type& minuend)\r\n{\r\n    if(icl::is_empty(minuend)) \r\n        return *that();\r\n\r\n    std::pair<iterator, iterator> exterior = equal_range(minuend);\r\n    if(exterior.first == exterior.second)\r\n        return *that();\r\n\r\n    iterator first_ = exterior.first,\r\n             end_   = exterior.second,\r\n             last_  = prior(end_);\r\n\r\n    interval_type left_resid  = right_subtract((*first_).first, minuend);\r\n    interval_type right_resid =  left_subtract(last_ ->first, minuend);\r\n\r\n    if(first_ == last_ )\r\n        if(!icl::is_empty(left_resid))\r\n        {\r\n            const_cast<interval_type&>((*first_).first) = left_resid;\r\n            if(!icl::is_empty(right_resid))\r\n                this->_map.insert(first_, value_type(right_resid, (*first_).second));\r\n        }\r\n        else if(!icl::is_empty(right_resid))\r\n            const_cast<interval_type&>((*first_).first) = left_subtract((*first_).first, minuend);\r\n        else\r\n            this->_map.erase(first_);\r\n    else\r\n    {   //            [-------- minuend ---------)\r\n        // [left_resid   fst)   . . . .    [lst  right_resid)\r\n        iterator second_= first_; ++second_;\r\n\r\n        iterator start_ = icl::is_empty(left_resid)? first_: second_;\r\n        iterator stop_  = icl::is_empty(right_resid)? end_  : last_ ;\r\n        this->_map.erase(start_, stop_); //erase [start_, stop_)\r\n\r\n        if(!icl::is_empty(left_resid))\r\n            const_cast<interval_type&>((*first_).first) = left_resid;\r\n\r\n        if(!icl::is_empty(right_resid))\r\n            const_cast<interval_type&>(last_ ->first) = right_resid;\r\n    }\r\n\r\n    return *that();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// type traits\r\n//-----------------------------------------------------------------------------\r\ntemplate \r\n<\r\n    class SubType,\r\n    class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE)  Interval, ICL_ALLOC Alloc\r\n>\r\nstruct is_map<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >\r\n{ \r\n    typedef is_map<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;\r\n    BOOST_STATIC_CONSTANT(bool, value = true); \r\n};\r\n\r\ntemplate \r\n<\r\n    class SubType,\r\n    class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE)  Interval, ICL_ALLOC Alloc\r\n>\r\nstruct has_inverse<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >\r\n{ \r\n    typedef has_inverse<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;\r\n    BOOST_STATIC_CONSTANT(bool, value = (has_inverse<CodomainT>::value)); \r\n};\r\n\r\ntemplate \r\n<\r\n    class SubType,\r\n    class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE)  Interval, ICL_ALLOC Alloc\r\n>\r\nstruct is_interval_container<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >\r\n{ \r\n    typedef is_interval_container<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;\r\n    BOOST_STATIC_CONSTANT(bool, value = true); \r\n};\r\n\r\ntemplate \r\n<\r\n    class SubType,\r\n    class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE)  Interval, ICL_ALLOC Alloc\r\n>\r\nstruct absorbs_identities<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >\r\n{\r\n    typedef absorbs_identities<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;\r\n    BOOST_STATIC_CONSTANT(bool, value = (Traits::absorbs_identities)); \r\n};\r\n\r\ntemplate \r\n<\r\n    class SubType,\r\n    class DomainT, class CodomainT, class Traits, ICL_COMPARE Compare, ICL_COMBINE Combine, ICL_SECTION Section, ICL_INTERVAL(ICL_COMPARE) Interval, ICL_ALLOC Alloc\r\n>\r\nstruct is_total<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> >\r\n{\r\n    typedef is_total<icl::interval_base_map<SubType,DomainT,CodomainT,Traits,Compare,Combine,Section,Interval,Alloc> > type;\r\n    BOOST_STATIC_CONSTANT(bool, value = (Traits::is_total)); \r\n};\r\n\r\n\r\n\r\n}} // namespace icl boost\r\n\r\n#endif\r\n\r\n\r\n", "meta": {"hexsha": "33b53430ad33057318ffaba84986513eb6786bbb", "size": 58089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/icl/interval_base_map.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": 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": "deps/boost/include/boost/icl/interval_base_map.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": 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": "deps/boost/include/boost/icl/interval_base_map.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": 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": 41.7606038821, "max_line_length": 187, "alphanum_fraction": 0.5954311488, "num_tokens": 12507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.02368946992082154, "lm_q1q2_score": 0.008428118638474633}}
{"text": "/*\n\n\n\tThis file is part of PEST++.\n\n\tPEST++ is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tPEST++ is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with PEST++.  If not, see<http://www.gnu.org/licenses/>.\n*/\n#include \"network_wrapper.h\"\n#include <ostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <fstream>\n#include <iomanip>\n#include <utility>\n#include <cassert>\n#include <memory>\n#include <Eigen/Dense>\n#include <utility>\n#include <cmath>\n#include <cfloat>\n#include \"Transformable.h\"\n#include \"pest_error.h\"\n#include \"utilities.h\"\n\n\nusing std::string;\nusing std::map;\nusing std::ostream;\nusing std::endl;\nusing std::isnormal;\nusing namespace pest_utils;\nusing namespace Eigen;\n\nconst double Transformable::no_data = -9.99E99;\n\nTransformable::Transformable(const Transformable &copyin) : items(copyin.items)\n{\n}\n\nTransformable::Transformable(const Transformable &&copyin)\n{\n\titems = std::move(copyin.items);\n}\n\nTransformable::Transformable(const Transformable &copyin, const vector<string> &copy_names)\n{\n\tfor (vector<string>::const_iterator b=copy_names.begin(), e=copy_names.end(); b!=e; ++b) {\n\t\titems[*b] = copyin.get_rec(*b);\n\t}\n}\n\nTransformable::Transformable(const vector<string> &names, const Eigen::VectorXd &values)\n{\n\tassert(names.size() == values.size());\n\tif(names.size() != values.size())\n\t{\n\t\tthrow PestIndexError(\"Transformable::Transformable(const vector<string> &names, Eigen::VectorXd &values)\",\n\t\t\t\"size of names vector does not match the size of the values vector\");\n\t}\n\tsize_t len = min(size_t(names.size()), size_t(values.size()));\n\tfor (size_t i=0; i<len; ++i)\n\t{\n\t\titems[names[i]] = values(i);\n\t}\n}\n\n\nconst Transformable& Transformable::operator=(const Transformable &rhs)\n{\n\titems = rhs.items;\n\treturn *this;\n}\n\nbool Transformable::operator==(const Transformable &rhs) const\n{\n\treturn items.size() == rhs.items.size()\n\t\t&& std::equal(items.begin(), items.end(),\n\t\t\t\t\t  rhs.items.begin());\n}\n\nbool Transformable::operator!=(const Transformable &rhs) const\n{\n\treturn !(*this == rhs);\n}\n\nTransformable& Transformable::operator+=(const Transformable &rhs)\n{\n\tfor(auto &i : items)\n\t{\n\t\tauto iter = rhs.items.find(i.first);\n\t\tassert(iter != rhs.items.end());\n\t\ti.second += iter->second;\n\t}\n\treturn *this;\n }\n\n\nTransformable& Transformable::operator-=(const Transformable &rhs)\n{\n\tfor(auto &i : items)\n\t{\n\t\tauto iter = rhs.items.find(i.first);\n\t\tassert(iter != rhs.items.end());\n\t\ti.second -= iter->second;\n\t}\n\treturn *this;\n }\n\nTransformable& Transformable::operator*=(double scale)\n{\n\tfor(auto &i : items)\n\t{\n\t\ti.second *= scale;\n\t}\n\t return *this;\n}\n\nTransformable Transformable::operator-(const Transformable &rhs) const\n{\n\tTransformable ret_val(*this);\n\tret_val -= rhs;\n\treturn ret_val;\n}\n\nTransformable Transformable::operator+(const Transformable &rhs) const\n{\n\tTransformable ret_val(*this);\n\tret_val += rhs;\n\treturn ret_val;\n\n\n}\n\nTransformable Transformable::operator*(double scale) const\n{\n\tTransformable ret_val(*this);\n\tret_val *= scale;\n\treturn ret_val;\n}\n\ndouble &Transformable::operator[](const string &name)\n{\n\treturn items[name];\n}\n\nvector<string> Transformable::get_notnormal_keys()\n{\n\tvector<string> not_normal;\n\tfor (auto &i : items)\n\t{\n\t\tif ((isnormal(i.second)) || (i.second ==0.0))\n\t\t\tcontinue;\n\t\tnot_normal.push_back(i.first);\n\t}\n\treturn not_normal;\n}\n\npair<Transformable::iterator,bool> Transformable::insert(const string &name, double value)\n{\n\tpair<string, double> rec(name, value);\n\treturn items.insert(rec);\n}\n\npair<Transformable::iterator,bool>  Transformable::insert(const pair<string, double> &x)\n{\n\treturn items.insert(x);\n}\n\nvoid Transformable::insert(const vector<string> &name_vec, const vector<double> &value_vec)\n{\n\tassert(name_vec.size() == value_vec.size());\n\tint vec_size = name_vec.size();\n\titems.reserve(vec_size);\n\tfor(int i=0; i<vec_size; ++i)\n\t{\n\t\tinsert(pair<string, double>(name_vec[i], value_vec[i]));\n\t}\n}\n\nvoid Transformable::insert(iterator first, iterator last )\n{\n\titems.insert(first, last);\n}\n\nvoid Transformable::insert(const Transformable &insert_items)\n{\n\tfor(auto &ipar : insert_items)\n\t{\n\t\titems[ipar.first] = ipar.second;\n\t}\n}\n\nsize_t Transformable::erase(const string &name)\n{\n\treturn items.erase(name);\n}\n\nvoid Transformable::erase(iterator position)\n{\n\titems.erase(position);\n}\n\nvoid Transformable::erase(const Parameters &erase_pars)\n{\n\tauto end_erase_pars = erase_pars.end();\n\tauto end_items = items.end();\n\tauto item_iter = items.end();;\n\tfor(auto iter = erase_pars.begin(); iter != end_erase_pars;) {\n\t\titem_iter = items.find((*iter).first);\n\t\tif (item_iter != end_items)\n\t\t{\n\t\t   items.erase(item_iter++);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++iter;\n\t   }\n\t}\n}\n\nvoid Transformable::erase(const vector<string> &erase_par_names)\n{\n\tauto end_erase_pars = erase_par_names.end();\n\tauto end_items = items.end();\n\tauto item_iter = items.end();;\n\tfor(auto iter = erase_par_names.begin(); iter != end_erase_pars;) {\n\t\titem_iter = items.find((*iter));\n\t\tif (item_iter != end_items)\n\t\t{\n\t\t   items.erase(item_iter++);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++iter;\n\t   }\n\t}\n}\n\nTransformable::iterator Transformable::find(const string &name)\n{\n\treturn items.find(name);\n}\n\nTransformable::const_iterator Transformable::find(const string &name) const\n{\n\treturn items.find(name);\n}\n\nconst double* Transformable::get_rec_ptr(const string &name) const\n{\n\tconst double *ret_val = 0;\n\tTransformable::const_iterator iter = find(name);\n\tif (iter != end()) {\n\t\tret_val = &((*iter).second);\n\t}\n\treturn ret_val;\n}\n\ndouble Transformable::get_rec(const string &name) const\n{\n\tdouble ret_val = no_data;\n\tTransformable::const_iterator iter = find(name);\n\tif (iter != end()) {\n\t\tret_val = (*iter).second;\n\t}\n\telse {\n\t\tthrow(Transformable_value_error(name));\n\t}\n\treturn ret_val;\n}\n\nvoid Transformable::update_rec(const string &name, double value)\n{\n\tTransformable::iterator iter = find(name);\n\tassert(iter != end());\n\tif (iter != end()) {\n\t\t(*iter).second = value;\n\t}\n\telse {\n\t\tthrow(Transformable_value_error(name));\n\t}\n}\n\nvoid Transformable::update(const vector<string> &names, const vector<double> &values)\n{\n\titems.clear();\n\tassert(names.size() == values.size());\n\tsize_t n_rec = names.size();\n\titems.reserve(n_rec);\n\tfor (size_t i=0; i<n_rec; ++i)\n\t{\n\t\titems.insert(make_pair(names[i], values[i]));\n\t}\n}\nvoid Transformable::update_without_clear(const vector<string> &names, const vector<double> &values)\n{\n\tassert(names.size() == values.size());\n\tsize_t n_rec = names.size();\n\titems.reserve(n_rec);\n\tfor (size_t i=0; i<n_rec; ++i)\n\t{\n\t\titems[names[i]] = values[i];\n\t}\n}\n\nvoid Transformable::update_without_clear(const vector<string> &names, const Eigen::VectorXd &values)\n{\n\tassert(names.size() == values.size());\n\tsize_t n_rec = names.size();\n\titems.reserve(n_rec);\n\tfor (size_t i = 0; i<n_rec; ++i)\n\t{\n\t\titems[names[i]] = values[i];\n\t}\n}\n\nvector<double> Transformable::get_data_vec(const vector<string> &keys) const\n{\n\tvector<double> v;\n\tv.resize(keys.size(), 0.0);\n\n\tdouble value;\n\tint i = 0;\n\n\tfor(vector<string>::const_iterator b=keys.begin(), e=keys.end();\n\t\tb!=e; ++b, ++i)\n\t{\n\t\tvalue = get_rec((*b));\n\t\tv[i] = value;\n\t}\n\treturn v;\n}\n\n\nEigen::VectorXd Transformable::get_data_eigen_vec(const vector<string> &keys) const\n{\n\tVectorXd vec;\n\tvec.resize(keys.size());\n\tint i = 0;\n\tfor (auto &k : keys)\n\t{\n\t\tvec(i++) = get_rec(k);\n\t}\n\treturn vec;\n}\n\nEigen::VectorXd Transformable::get_partial_data_eigen_vec(const vector<string> &keys) const\n{\n\tVectorXd vec;\n\tvec.resize(keys.size());\n\tint i = 0;\n\tauto end = items.end();\n\tfor (auto &k : keys)\n\t{\n\t\tauto iter = items.find(k);\n\t\tif (iter != end)\n\t\t{\n\t\t\tvec(i) = get_rec(k);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvec(i) = 0;\n\t\t}\n\t\t++i;\n\t}\n\treturn vec;\n}\n\n\n\n\n\nvector<string> Transformable::get_keys() const\n{\n\tvector<string> ret_val;\n\tret_val.reserve(size());\n\tfor(Transformable::const_iterator b=begin(), e=end();\n\t\tb!=e; ++b)\n\t{\n\t\tret_val.push_back((*b).first);\n\t}\n\treturn ret_val;\n}\n\ndouble Transformable::l2_norm() const\n{\n   double norm=0;\n   for (auto &i : items)\n   {\n\tnorm += pow(i.second, 2.0);\n   }\n   norm = sqrt(norm);\n   return norm;\n}\n\n\ndouble  Transformable::l2_norm(const Transformable &d1, const Transformable &d2)\n{\n\tdouble norm = 0.0;\n\tconst auto it_end = d1.end();\n\tassert(d1.size() == d2.size());\n\tfor (const auto &i_d2 : d2.items)\n\t{\n\t\tauto it_d1 = d1.find(i_d2.first);\n\t\tif (it_d1 != it_end)\n\t\t{\n\t\t\tnorm += pow(it_d1->second - i_d2.second, 2.0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert(true);\n\t\t}\n\t}\n\tnorm = sqrt(norm);\n\treturn norm;\n}\n\nostream& operator<<(ostream& out, const Transformable &rhs)\n{\n\tfor(Transformable::const_iterator b=rhs.begin(), e=rhs.end();\n\t\tb!=e; ++b)\n\t{\n\t\tout << b->first << \" = \" << b->second << endl;\n\t}\n\treturn out;\n}\n\n\n\n\nvoid Parameters::read_par_file(ifstream &fin,  map<string, double> &offset, map<string, double> &scale)\n{\n\tclear();\n\toffset.clear();\n\tscale.clear();\n\n\tvector<string> tokens;\n\tstring line;\n\tgetline(fin, line);\n\twhile (getline(fin, line))\n\t{\n\t\tstrip_ip(line);\n\t\tif (line.length() > 0)\n\t\t{\n\t\t\ttokens.clear();\n\t\t\ttokenize(line, tokens);\n\t\t\tstring name = upper_cp(tokens[0]);\n\t\t\tdouble par_val = convert_cp<double>(tokens[1]);\n\t\t\tdouble offset_val = convert_cp<double>(tokens[2]);\n\t\t\tdouble scale_val = convert_cp<double>(tokens[3]);\n\t\t\tinsert(name, par_val);\n\t\t\toffset[name] = offset_val;\n\t\t\tscale[name] = scale_val;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "079e9db397de82f0d658f92993678da9c5f4f5de", "size": 9703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/PEST++/src/libs/common/Transformable.cpp", "max_stars_repo_name": "usgs/neversink_workflow", "max_stars_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "max_stars_repo_licenses": ["CC0-1.0"], "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": "source/PEST++/src/libs/common/Transformable.cpp", "max_issues_repo_name": "usgs/neversink_workflow", "max_issues_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "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": "source/PEST++/src/libs/common/Transformable.cpp", "max_forks_repo_name": "usgs/neversink_workflow", "max_forks_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "max_forks_repo_licenses": ["CC0-1.0"], "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": 20.6446808511, "max_line_length": 108, "alphanum_fraction": 0.6820570957, "num_tokens": 2571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.024053551801287286, "lm_q1q2_score": 0.00838615382302188}}
{"text": "/*\n// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n#ifndef STAPL_SKELETONS_FUNCTIONAL_SCAN_HPP\n#define STAPL_SKELETONS_FUNCTIONAL_SCAN_HPP\n\n#include <type_traits>\n#include <stapl/skeletons/utility/utility.hpp>\n#include <stapl/skeletons/utility/tags.hpp>\n#include <stapl/skeletons/utility/skeleton.hpp>\n#include <stapl/skeletons/flows/repeat_flows.hpp>\n#include <stapl/skeletons/flows/scan_flows.hpp>\n#include <stapl/skeletons/param_deps/scan_broadcast_pd.hpp>\n#include <stapl/skeletons/param_deps/scan_blelloch_broadcast_pd.hpp>\n#include <stapl/skeletons/param_deps/scan_expand_from_pow_two_pd.hpp>\n#include <stapl/skeletons/param_deps/binomial_tree_pd.hpp>\n#include <stapl/skeletons/spans/balanced.hpp>\n#include <stapl/skeletons/spans/binomial_tree.hpp>\n#include <stapl/skeletons/spans/nearest_pow_two.hpp>\n#include <stapl/skeletons/operators/compose.hpp>\n#include \"pointer_jumping.hpp\"\n#include \"reduce_to_pow_two.hpp\"\n#include \"binary_tree.hpp\"\n#include \"tree.hpp\"\n\n#include <boost/mpl/has_xxx.hpp>\n\nnamespace stapl {\nnamespace skeletons {\n\nBOOST_MPL_HAS_XXX_TRAIT_DEF(first_argument_type)\n\ntemplate <typename Op,\n          bool with_arg_type = has_first_argument_type<Op>::value>\nstruct scan_operand_type\n{\n  using type = typename std::decay<Op>::type::first_argument_type;\n};\n\n\ntemplate <typename Op>\nstruct scan_operand_type<Op, false>\n{\n  using type = typename std::decay<Op>::type::result_type;\n};\n\n\nnamespace skeletons_impl {\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Determines the scan algorithm used.\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Tag>\nstruct scan_algorithm_tag_type;\n\n\ntemplate <typename Tag, typename IE>\nstruct scan_algorithm_tag_type<tags::scan<Tag, IE>>\n{\n  using type = Tag;\n};\n\ntemplate <typename Op, typename Tag>\nstruct inclusive_scan;\n\n\ntemplate <typename Op, typename T, typename Tag>\nstruct exclusive_scan;\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Hillis Steele scan skeleton is a pointer-jumping based\n/// inclusive scan algorithm which has half the height of the scan\n/// algorithm in Joseph Jaja's book, but it performs \\f$O(n logn)\\f$\n/// operations and hence is not work optimal.\n///\n/// @tparam Op the operation to be used to compute the scan results\n///\n/// @see flows::repeat_flows::piped\n/// @see flows::repeat_flows::input_wrapper\n/// @see pointer_jumping\n/// @see scan\n///\n/// @ingroup skeletonsFunctionalInternal\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Op>\nstruct inclusive_scan<Op, tags::hillis_steele>\n  : public decltype(\n             skeletons::pointer_jumping<\n               flows::repeat_flows::input_wrapper<flows::repeat_flows::piped>\n             >(std::declval<Op>()))\n{\n  using skeleton_tag_type = tags::scan<tags::hillis_steele, tags::inclusive>;\n  using base_type = decltype(\n                      skeletons::pointer_jumping<\n                        flows::repeat_flows::input_wrapper<\n                          flows::repeat_flows::piped>\n                      >(std::declval<Op>()));\n\n  explicit inclusive_scan(Op const& op)\n    : base_type(op)\n  { }\n\n  Op get_op() const\n  {\n    return base_type::get_op();\n  }\n\n  void define_type(typer& t)\n  {\n    t.base<base_type>(*this);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Binomial scan is one of the common implementations of\n/// MPI_Scan.\n///\n/// A binomial scan consists of an up-phase and a down-phase. In the\n/// up-phase, one or more reduction trees (depending on whether the\n/// input size is a power-of-two or not) reduce the values and prepare\n/// partial results for the down-phase. In the down-phase, partial\n/// results are combined to produce the final result.\n///\n/// @code\n/// O O O O O O\n/// |\\| |\\| |\\|\n/// | O_| O | O\n/// | | |\\| | |\n/// | | | O | |\n/// | | | | | |\n/// | | | O | |\n/// | | | |\\|_|\n/// | O | O | O\n/// | |\\| |\\| |\n/// O O O O O O\n/// @endcode\n///\n/// @tparam Op the operation to be used to compute the scan results\n///\n/// @see flows::repeat_flows::output_from_all\n/// @see flows::repeat_flows::\n/// @see flows::scan_f::scan_broadcast\n/// @see spans::binomial_tree\n/// @see binomial_tree_pd\n///\n/// @ingroup skeletonsFunctionalInternal\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Op>\nstruct inclusive_scan<Op, tags::binomial>\n  : public decltype(\n             skeletons::compose<\n               flows::repeat_flows::input_wrapper<\n                 flows::compose_flows::input_to_all\n               >\n             >(skeletons::repeat<flows::repeat_flows::output_from_all>(\n                 skeletons::elem<\n                   spans::binomial_tree<spans::balanced<>, tags::up_phase>\n                 >(skeletons::binomial_tree_pd<tags::up_phase>(\n                     std::declval<Op>())),\n                 log_lazysize<2>()),\n               skeletons::repeat<flows::repeat_flows::scan_broadcast>(\n                 skeletons::elem<\n                   spans::binomial_tree<spans::balanced<>, tags::down_phase>\n                 >(skeletons::binomial_tree_pd<tags::down_phase>(\n                     std::declval<Op>())),\n                 log_ceil_lazysize<2>()))\n           )\n{\n  using skeleton_tag_type = tags::scan<tags::binomial, tags::inclusive>;\n  using base_type = decltype(\n                      skeletons::compose<\n                        flows::repeat_flows::input_wrapper<\n                          flows::compose_flows::input_to_all\n                        >\n                      >(skeletons::repeat<flows::repeat_flows::output_from_all>(\n                          skeletons::elem<\n                            spans::binomial_tree<\n                              spans::balanced<>, tags::up_phase>\n                          >(skeletons::binomial_tree_pd<tags::up_phase>(\n                              std::declval<Op>())),\n                          log_lazysize<2>()),\n                        skeletons::repeat<flows::repeat_flows::scan_broadcast>(\n                          skeletons::elem<\n                            spans::binomial_tree<\n                              spans::balanced<>, tags::down_phase>\n                          >(skeletons::binomial_tree_pd<tags::down_phase>(\n                              std::declval<Op>())),\n                          log_ceil_lazysize<2>())));\n\n  explicit inclusive_scan(Op const& op)\n    : base_type(\n        skeletons::compose<\n          flows::repeat_flows::input_wrapper<flows::compose_flows::input_to_all>\n        >(skeletons::repeat<flows::repeat_flows::output_from_all>(\n            skeletons::elem<\n              spans::binomial_tree<spans::balanced<>, tags::up_phase>\n            >(skeletons::binomial_tree_pd<tags::up_phase>(op)),\n            log_lazysize<2>()),\n          skeletons::repeat<flows::repeat_flows::scan_broadcast>(\n            skeletons::elem<\n              spans::binomial_tree<spans::balanced<>, tags::down_phase>\n            >(skeletons::binomial_tree_pd<tags::down_phase>(op)),\n            log_ceil_lazysize<2>()))\n      )\n  { }\n\n  Op get_op() const\n  {\n    return base_type::template get_skeleton<0>().nested_skeleton().\n             nested_skeleton().get_op();\n  }\n\n  void define_type(typer& t)\n  {\n    t.base<base_type>(*this);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief This scan skeleton is based on the algorithm given in\n/// <b>An Introduction to Parallel Algorithms</b> by Joseph Jaja, page\n/// 48. This algorithm's time complexity is \\f$O(log n)\\f$. It\n/// consists of a reduction tree followed by a modified broadcast\n/// skeleton. This scan skeleton is an inclusive scan.\n///\n/// @tparam Op the operation to be used to compute the scan results\n///\n/// @see flows::compose_flows::input_to_all\n/// @see flows::repeat_flows::output_from_all\n/// @see flows::repeat_flows::scan_broadcast\n/// @see scan_broadcast_pd\n///\n/// @ingroup skeletonsFunctionalInternal\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Op>\nstruct inclusive_scan<Op, tags::jaja>\n  : public decltype(\n             skeletons::compose<flows::compose_flows::input_to_all>(\n               skeletons::binary_tree<\n                 tags::left_skewed,\n                 flows::repeat_flows::output_from_all,\n                 spans::nearest_pow_two<spans::balanced<>>, true\n               >(std::declval<Op>()),\n               skeletons::reverse_tree<\n                 2, flows::repeat_flows::scan_broadcast,\n                 spans::reverse_tree<\n                   spans::nearest_pow_two<spans::balanced<>>, tags::left_skewed\n                 >\n               >(skeletons::scan_broadcast_pd(std::declval<Op>()))))\n{\n  using skeleton_tag_type = tags::scan<tags::jaja, tags::inclusive>;\n\n  using base_type = decltype(\n                      skeletons::compose<flows::compose_flows::input_to_all>(\n                        skeletons::binary_tree<\n                          tags::left_skewed,\n                          flows::repeat_flows::output_from_all,\n                          spans::nearest_pow_two<spans::balanced<>>, true\n                        >(std::declval<Op>()),\n                        skeletons::reverse_tree<\n                          2, flows::repeat_flows::scan_broadcast,\n                          spans::reverse_tree<\n                            spans::nearest_pow_two<spans::balanced<>>,\n                            tags::left_skewed\n                          >\n                        >(skeletons::scan_broadcast_pd(std::declval<Op>()))));\n\n  explicit inclusive_scan(Op const& op)\n    : base_type(\n        skeletons::compose<flows::compose_flows::input_to_all>(\n          skeletons::binary_tree<\n            tags::left_skewed,\n            flows::repeat_flows::output_from_all,\n            spans::nearest_pow_two<spans::balanced<>>, true\n          >(op),\n          skeletons::reverse_tree<\n            2, flows::repeat_flows::scan_broadcast,\n            spans::reverse_tree<\n              spans::nearest_pow_two<spans::balanced<>>, tags::left_skewed\n            >\n          >(skeletons::scan_broadcast_pd(op)))\n      )\n  { }\n\n  Op get_op() const\n  {\n    return base_type::template get_skeleton<0>().get_op();\n  }\n\n  void define_type(typer& t)\n  {\n    t.base<base_type>(*this);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Blelloch scan is an exclusive scan algorithm which is\n/// similar to the inclusive scan mentioned in Joseph Jaja's book\n/// (@see inclusive_scan(op,tags::jaja)).\n///\n/// @tparam Op the operation to be used to compute the scan results\n/// @tparam T  the type of the initial value for the exclusive scan.\n///\n/// @see flows::compose_flows::input_to_all\n/// @see flows::repeat_flows::output_from_all\n/// @see flows::repeat_flows::scan_broadcast\n/// @see scan_blelloch_broadcast_pd\n/// @see\n///\n/// @ingroup skeletonsFunctionalInternal\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Op, typename T>\nstruct exclusive_scan<Op, T, tags::blelloch>\n  : public decltype(\n             skeletons::compose<\n               flows::repeat_flows::input_wrapper<\n                 flows::compose_flows::input_to_all>\n             >(skeletons::binary_tree<\n                 tags::right_aligned,\n                 flows::repeat_flows::output_from_all,\n                 spans::nearest_pow_two<spans::balanced<>>, true\n               >(std::declval<Op>()),\n               skeletons::reverse_tree<\n                 2, flows::repeat_flows::scan_broadcast,\n                 spans::reverse_tree<\n                   spans::nearest_pow_two<spans::balanced<>>,\n                   tags::right_aligned\n                 >\n               >(skeletons::scan_blelloch_broadcast_pd(\n                  std::declval<Op>(), T())))\n           )\n{\n  using skeleton_tag_type = tags::scan<tags::blelloch, tags::exclusive>;\n\n  using base_type = decltype(\n                      skeletons::compose<\n                         flows::repeat_flows::input_wrapper<\n                           flows::compose_flows::input_to_all\n                         >\n                      >(skeletons::binary_tree<\n                          tags::right_aligned,\n                          flows::repeat_flows::output_from_all,\n                          spans::nearest_pow_two<spans::balanced<>>, true\n                        >(std::declval<Op>()),\n                        skeletons::reverse_tree<\n                          2, flows::repeat_flows::scan_broadcast,\n                          spans::reverse_tree<\n                            spans::nearest_pow_two<spans::balanced<>>,\n                            tags::right_aligned\n                          >\n                        >(skeletons::scan_blelloch_broadcast_pd(\n                            std::declval<Op>(), T()))));\n\n  exclusive_scan(Op const& op, T const& initial_value)\n    : base_type(\n        skeletons::compose<\n          flows::repeat_flows::input_wrapper<flows::compose_flows::input_to_all>\n        >(skeletons::binary_tree<\n            tags::right_aligned,\n            flows::repeat_flows::output_from_all,\n            spans::nearest_pow_two<spans::balanced<>>, true\n          >(op),\n          skeletons::reverse_tree<\n            2, flows::repeat_flows::scan_broadcast,\n            spans::reverse_tree<\n              spans::nearest_pow_two<spans::balanced<>>, tags::right_aligned\n            >\n          >(skeletons::scan_blelloch_broadcast_pd(op, initial_value))\n        )\n      )\n  { }\n\n  Op get_op() const\n  {\n    return base_type::template get_skeleton<0>().get_op();\n  }\n\n  void define_type(typer& t)\n  {\n    t.base<base_type>(*this);\n  }\n};\n\n} // namespace skeletons_impl\n\n\nnamespace result_of {\n\ntemplate <typename Tag, typename Op>\nusing inclusive_scan = skeletons_impl::inclusive_scan<Op, Tag>;\n\ntemplate <typename Tag, typename Op, typename T>\nusing exclusive_scan = skeletons_impl::exclusive_scan<Op, T, Tag>;\n\n}\n\n//////////////////////////////////////////////////////////////////////\n/// @brief An inclusive scan is a scan in which each element in the\n/// output is the result of cumulative application of the operation\n/// on the elements before it including itself.\n///\n/// For example,  if + is used as the operation, each element in the\n/// output is the sum of all elements before it, and the first element\n/// is the neutral value. An exclusive scan of [1, 2, 3, 4, ...] would\n/// be [1, 3, 6, 10, ...].\n///\n/// @param Tag determines the type of inclusive scan to be used.\n/// @param op  the operation to be used to compute the scan results\n///\n/// @see scan\n///\n/// @ingroup skeletonsFunctional\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Tag, typename Op>\nresult_of::inclusive_scan<Tag, Op>\ninclusive_scan(Op const& op)\n{\n  return result_of::inclusive_scan<Tag, Op>(op);\n}\n\n//////////////////////////////////////////////////////////////////////\n/// @brief An exclusive scan is a scan in which each element in the\n/// output is the result of cumulative application of the operation\n/// on the elements before it.\n///\n/// @param T   value type of the operator\n/// @param op  the operation to be used to compute the scan results\n/// @param Tag determines the type of inclusive scan to be used.\n///\n/// @see scan\n///\n/// @ingroup skeletonsFunctional\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Tag, typename Op, typename T>\nresult_of::exclusive_scan<Tag, Op, T>\nexclusive_scan(Op const& op, T const& initial_value)\n{\n  return result_of::exclusive_scan<Tag, Op, T>(op, initial_value);\n}\n\nnamespace skeletons_impl {\n\ntemplate<typename Op, typename Tag>\nstruct scan;\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Most of the inclusive scan skeletons cannot work directly on\n/// inputs with non-power-of-two sizes. As a result, we have to first\n/// convert the input to the closest power of two and then perform the\n/// scan operation.\n///\n/// @ingroup skeletonsFunctional\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Op, typename Tag>\nstruct scan<Op, tags::scan<Tag, tags::inclusive>>\n  : public decltype(\n             skeletons::compose<flows::compose_flows::scan>(\n               skeletons::reduce_to_pow_two(std::declval<Op>()),\n               skeletons::inclusive_scan<Tag>(std::declval<Op>()),\n               skeletons::elem(skeletons::scan_expand_from_pow_two_pd(\n                                 std::declval<Op>(),\n                                 tags::scan<Tag, tags::inclusive>())))\n           )\n{\n  using skeleton_tag_type = tags::scan<Tag, tags::inclusive>;\n  using base_type = decltype(\n                      skeletons::compose<flows::compose_flows::scan>(\n                        skeletons::reduce_to_pow_two(std::declval<Op>()),\n                        skeletons::inclusive_scan<Tag>(std::declval<Op>()),\n                        skeletons::elem(skeletons::scan_expand_from_pow_two_pd(\n                                          std::declval<Op>(),\n                                          tags::scan<Tag, tags::inclusive>())))\n                    );\n\n  explicit scan(Op const& op)\n    : base_type(\n        skeletons::compose<flows::compose_flows::scan>(\n          skeletons::reduce_to_pow_two(op),\n          skeletons::inclusive_scan<Tag>(op),\n          skeletons::elem(skeletons::scan_expand_from_pow_two_pd(\n                           op, tags::scan<Tag, tags::inclusive>())))\n      )\n  { }\n\n  Op get_op() const\n  {\n    return base_type::template get_skeleton<0>().get_op();\n  }\n\n  void define_type(typer& t)\n  {\n    t.base<base_type>(*this);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Most of the exclusive scan skeletons cannot work directly on\n/// inputs with non-power-of-two sizes. As a result, we have to first\n/// convert the input to the closest power of two and then perform the\n/// scan operation.\n///\n/// @ingroup skeletonsFunctional\n//////////////////////////////////////////////////////////////////////\ntemplate<typename Op, typename Tag>\nstruct scan<Op, tags::scan<Tag, tags::exclusive>>\n  : public decltype(\n             skeletons::compose<flows::compose_flows::scan>(\n               skeletons::reduce_to_pow_two(std::declval<Op>()),\n               skeletons::exclusive_scan<Tag>(\n                 std::declval<Op>(),\n                 typename scan_operand_type<Op>::type()),\n               skeletons::elem(\n                 skeletons::scan_expand_from_pow_two_pd(\n                   std::declval<Op>(),\n                   tags::scan<Tag, tags::exclusive>()))))\n{\n  using skeleton_tag_type = tags::scan<Tag, tags::exclusive>;\n  using value_t = typename scan_operand_type<Op>::type;\n  using base_type = decltype(\n                      skeletons::compose<flows::compose_flows::scan>(\n                        skeletons::reduce_to_pow_two(std::declval<Op>()),\n                        skeletons::exclusive_scan<Tag>(\n                          std::declval<Op>(), value_t()),\n                        skeletons::elem(\n                          skeletons::scan_expand_from_pow_two_pd(\n                            std::declval<Op>(),\n                            tags::scan<Tag, tags::exclusive>()))));\n\n  scan(Op const& op, value_t const& initial_value)\n    : base_type(\n        skeletons::compose<flows::compose_flows::scan>(\n          skeletons::reduce_to_pow_two(op),\n          skeletons::exclusive_scan<Tag>(op, initial_value),\n          skeletons::elem(\n            skeletons::scan_expand_from_pow_two_pd(\n              op, tags::scan<Tag, tags::exclusive>()))))\n  { }\n\n  Op get_op() const\n  {\n    return base_type::template get_skeleton<0>().get_op();\n  }\n\n  void define_type(typer& t)\n  {\n    t.base<base_type>(*this);\n  }\n};\n\n\n} // namespace skeletons_impl\n\n\nnamespace result_of {\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Hillis-Steele scan can work on inputs with non-power-of-two\n/// sizes, therefore, we do not need to wrap it with extra steps.\n///\n/// @ingroup skeletonsFunctional\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Tag, typename Op>\nusing scan = typename std::conditional<\n               std::is_same<\n                 tags::binomial,\n                 typename skeletons_impl::scan_algorithm_tag_type<Tag>::type\n               >::value ||\n               std::is_same<\n                 tags::hillis_steele,\n                 typename skeletons_impl::scan_algorithm_tag_type<Tag>::type\n               >::value,\n               skeletons_impl::inclusive_scan<\n                 typename std::decay<Op>::type,\n                 typename skeletons_impl::scan_algorithm_tag_type<Tag>::type>,\n               skeletons_impl::scan<typename std::decay<Op>::type, Tag>>::type;\n\n} // namespace result_of\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief A scan skeleton which is specialized based on the tag\n/// given.\n///\n/// @ingroup skeletonsFunctionalAlgorithm\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Tag = tags::binomial,\n          typename Op>\nresult_of::scan<tags::scan<Tag, tags::inclusive>, Op>\nscan(Op&& op)\n{\n  using std::is_same;\n  static_assert(\n    is_same<Tag, tags::binomial>::value      ||\n    is_same<Tag, tags::hillis_steele>::value ||\n    is_same<Tag, tags::jaja>::value,\n    \"The requested inclusive scan algorithm is not supported\");\n  return result_of::scan<tags::scan<Tag, tags::inclusive>, Op>(\n           std::forward<Op>(op));\n}\n\n//////////////////////////////////////////////////////////////////////\n/// @brief In an exclusive scan each element in the result is the\n/// result of the cumulative operation on all elements before it.\n///\n/// For example,  if + is used as the operation, each element in the\n/// output is the sum of all elements before it, and the first element\n/// is the neutral value. An exclusive scan of [1, 2, 3, 4, ...] would\n/// be [0, 1, 3, 6, 10, ...].\n///\n/// @param  op            the operation to be used to compute the scan\n///                       results\n/// @param  initial_value the value for the first element of the output\n/// @tparam Tag           the type of exclusive scan to be used\n///\n/// @return an exclusive scan specified by the @c Tag\n///\n/// @see exclusive_scan\n///\n/// @ingroup skeletonsFunctionalAlgorithm\n//////////////////////////////////////////////////////////////////////\ntemplate <typename Tag = tags::blelloch,\n          typename Op, typename T>\nresult_of::scan<tags::scan<Tag, tags::exclusive>, Op>\nscan(Op&& op, T const& initial_value)\n{\n  using std::is_same;\n  static_assert(is_same<Tag, tags::blelloch>::value,\n                \"The requested exclusive scan algorithm is not supported\");\n\n  return result_of::scan<tags::scan<Tag, tags::exclusive>, Op>(\n           std::forward<Op>(op), initial_value);\n}\n\n} // namespace skeletons\n} // namespace stapl\n\n#endif // STAPL_SKELETONS_FUNCTIONAL_SCAN_HPP\n", "meta": {"hexsha": "c3df0787bc58bc9f45a18e92b159deb8c9721c1d", "size": 23425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stapl_release/stapl/skeletons/functional/scan.hpp", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": "stapl_release/stapl/skeletons/functional/scan.hpp", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/stapl/skeletons/functional/scan.hpp", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-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.0384615385, "max_line_length": 80, "alphanum_fraction": 0.5633724653, "num_tokens": 4995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.023330770293987616, "lm_q1q2_score": 0.008384242642776788}}
{"text": "/*\n\nCopyright (c) 2005-2021, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef ELECTRODESSTIMULSUFACTORY_HPP_\n#define ELECTRODESSTIMULSUFACTORY_HPP_\n\n#include <boost/shared_ptr.hpp>\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/shared_ptr.hpp>\n\n#include \"AbstractTetrahedralMesh.hpp\"\n#include \"DistributedVector.hpp\"\n#include \"AbstractChasteRegion.hpp\"\n#include \"AbstractStimulusFactory.hpp\"\n#include \"LinearBasisFunction.hpp\"\n\n/**\n * This class implements the specification of tow electrodes with a RegularStimulus applied to them.\n * It makes sure the compatibility conditions is verified by scaling the magnitude of the second electrode\n * according to the flux flowing thorugh each of them.\n *\n * User needs to pass in a vector of pairs of electrodes and, for each pair, the stimulation parameters.\n * This class will then implement the CreateStimulusForNode accordingly by creating a RegularStimulus object\n * for each node. Each node belonging to any \"first electrode\" will have an extracellular volume stimulus equals to the value that is passed in,\n * while each node belonging to any \"second elecrode\" will have an extracellular volume stimulus corrected by the flux (proportional to electrode volume)\n * in such a way that compatibility conditions of the extended bidomain equations are followed.\n *\n * It is possible to ground all second electrodes by calling GroundSecondElectrode. In this case, the member variable\n * mGroundSecondElectrode will have size > 0 and other classes can behave accordingly (e.g., problem class will set Dirichlet\n * boundary conditions accordingly).\n *\n */\ntemplate<unsigned DIM>\nclass ElectrodesStimulusFactory : public AbstractStimulusFactory<DIM>\n{\nprotected:\n\n    friend class TestStimulusFactory;//for testing\n\n    /**\n     * Vector of pairs, each pair representing a pair of electrodes.\n     */\n    std::vector<std::pair<AbstractChasteRegion<DIM>*, AbstractChasteRegion<DIM>*> >& mrElectrodePairs;\n\n    /**\n     * Vector of stimuli magnitudes (microA / cm^3). Must be the same size as mrElectrodePairs.\n     */\n    std::vector<double>& mrMagnitudes;\n    /**\n     * Vector of stimuli durations (ms). Must be the same size as mrElectrodePairs.\n     */\n    std::vector<double>& mrDurations;\n    /**\n     * Vector of stimuli periods (ms). Must be the same size as mrElectrodePairs.\n     */\n    std::vector<double>& mrPeriods;\n    /**\n     * Vector of stimuli start times (ms). Must be the same size as mrElectrodePairs.\n     */\n    std::vector<double>& mrStarts;\n    /**\n     * Vector of stimuli end times (ms). Must be the same size as mrElectrodePairs.\n     */\n    std::vector<double>& mrEnds;\n\n    /**\n     * Used to store temporarily magnitudes of electrode 1 for correction\n     */\n    std::vector<double> mMagnitudesElectrode1;\n\n    /**\n     * Used to store temporarily magnitudes of electrode 2 for correction\n     */\n    std::vector<double> mMagnitudesElectrode2;\n\n\n    /** Whether the second electrode is grounded */\n    bool mGroundSecondElectrode;\n\n    /**\n     * Helper method to check if any of the electrodes intersects with the other.\n     * it needs to check whether any element that conatins any node of electrode 1\n     * does not conatin also nodes of eledtrode 2\n     */\n    void CheckForElectrodesIntersection();\n\n    /** typedef for basis function*/\n    typedef LinearBasisFunction<DIM> BasisFunction;\n\n\n    /**\n     * Helper method to compute electrode flux. This method is the main functionality of this class.\n     *\n     * It essentially computes the contribution of each electrode to the RHS vector of the linear system.\n     * The loops over elements and gauss points mimicks the ones in AssembleOnElement.\n     * Interpolation is done for the value of the magnitude of the electrode.\n     *\n     * NOTE that this method assumes the use of a 2nd order Gauss quadrature rule (the default value of Chaste FE assemblers).\n     *\n     * @param pRegion  the electrode\n     * @param stimulusMagnitude the stimulus magnitude\n     * @return electrode flux\n     */\n    double ComputeElectrodeTotalFlux(AbstractChasteRegion<DIM>* pRegion, double stimulusMagnitude);\n\n\npublic:\n\n\n    /**\n     * Constructor. Electrodes and stimulation parameters need to be passed in.\n     *\n     * @param rElectrodePairs the pairs of electrodes\n     * @param rStimulusMagnitudes the magnitudes of the stimuli (microA / cm^3). First electrode will have magnitude value and second electrode will have -magnitude (before being corrected to ensure equal flux).\n     * @param rDurations the duration of each stimulus (ms)\n     * @param rPeriods the period of each stimulus (ms)\n     * @param rStarts the start time of each stimulus (ms).\n     * @param rEnds the end of each stimulation (ms)\n     */\n    ElectrodesStimulusFactory(std::vector<std::pair<AbstractChasteRegion<DIM>*, AbstractChasteRegion<DIM>*> >& rElectrodePairs,\n                              std::vector<double>& rStimulusMagnitudes,\n                              std::vector<double>& rDurations,\n                              std::vector<double>& rPeriods,\n                              std::vector<double>& rStarts,\n                              std::vector<double>& rEnds);\n\n    /**\n     * @return Creates an appropriate stimulus for each node as to abide compatibility conditions.\n     *\n     * @param pNode the node for which to create the stimulus\n     */\n    boost::shared_ptr<AbstractStimulusFunction> CreateStimulusForNode(Node<DIM>* pNode);\n\n    /**\n     * Destructor\n     */\n    ~ElectrodesStimulusFactory();\n\n    /**\n     * This method checks whether the users wanted a grounded electrode.\n     * If so, it fills in mGroundedRegions accordingly.\n     *\n     * If not, it calls ComputeElectrodeTotalFlux and scales the magnitudes of the electrodes stimuli accordingly\n     */\n    void SetCompatibleExtracellularStimulus();\n\n    /**\n     * Allow the user to ground the second electrode\n     *\n     * @param grounded : true if second electrode is grounded\n     */\n    void GroundSecondElectrode(bool grounded);\n};\n\n#endif /*ELECTRODESSTIMULSUFACTORY_HPP_*/\n", "meta": {"hexsha": "b4751829e6160ddb1a1e5f7e600203631c9860c2", "size": 7785, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/stimulus/tissue_electrodes/ElectrodesStimulusFactory.hpp", "max_stars_repo_name": "mdp19pn/Chaste", "max_stars_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T08:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T11:39:26.000Z", "max_issues_repo_path": "heart/src/stimulus/tissue_electrodes/ElectrodesStimulusFactory.hpp", "max_issues_repo_name": "mdp19pn/Chaste", "max_issues_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-06-14T13:48:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:42:07.000Z", "max_forks_repo_path": "heart/src/stimulus/tissue_electrodes/ElectrodesStimulusFactory.hpp", "max_forks_repo_name": "mdp19pn/Chaste", "max_forks_repo_head_hexsha": "f7b6bafa64287d567125b587b29af6d8bd7aeb90", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T13:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T18:57:35.000Z", "avg_line_length": 41.1904761905, "max_line_length": 211, "alphanum_fraction": 0.7284521516, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.023330768426492954, "lm_q1q2_score": 0.008384241971666139}}
{"text": "// Boost.Geometry\n// This file is manually converted from PROJ4\n\n// This file was modified by Oracle on 2018.\n// Modifications copyright (c) 2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// 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// This file was converted to Geometry Library by Adam Wulkiewicz\n\n// Original copyright notice:\n// Author:   Frank Warmerdam, warmerdam@pobox.com\n\n// Copyright (c) 2000, Frank Warmerdam\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_SRS_PROJECTIONS_IMPL_PJ_GRIDINFO_HPP\n#define BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_PJ_GRIDINFO_HPP\n\n\n#include <boost/algorithm/string.hpp>\n\n#include <boost/geometry/core/assert.hpp>\n\n#include <boost/cstdint.hpp>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n\nnamespace boost { namespace geometry { namespace projections\n{\n\nnamespace detail\n{\n\n/************************************************************************/\n/*                             swap_words()                             */\n/*                                                                      */\n/*      Convert the byte order of the given word(s) in place.           */\n/************************************************************************/\n\ninline bool is_lsb()\n{\n    static const int byte_order_test = 1;\n    static bool result = (1 == ((const unsigned char *) (&byte_order_test))[0]);\n    return result;\n}\n\ninline void swap_words( char *data, int word_size, int word_count )\n{\n    for (int word = 0; word < word_count; word++)\n    {\n        for (int i = 0; i < word_size/2; i++)\n        {\n            std::swap(data[i], data[word_size-i-1]);\n        }\n\n        data += word_size;\n    }\n}\n\ninline bool cstr_equal(const char * s1, const char * s2, std::size_t n)\n{\n    return std::equal(s1, s1 + n, s2);\n}\n\nstruct is_trimmable_char\n{\n    inline bool operator()(char ch)\n    {\n        return ch == '\\n' || ch == ' ';\n    }\n};\n\n// structs originally defined in projects.h\n\nstruct pj_ctable\n{\n    struct lp_t  { double lam, phi; };\n    struct flp_t { float lam, phi; };\n    struct ilp_t { boost::int32_t lam, phi; };\n\n    std::string id;         // ascii info\n    lp_t ll;                // lower left corner coordinates\n    lp_t del;               // size of cells\n    ilp_t lim;              // limits of conversion matrix\n    std::vector<flp_t> cvs; // conversion matrix\n\n    inline void swap(pj_ctable & r)\n    {\n        id.swap(r.id);\n        std::swap(ll, r.ll);\n        std::swap(del, r.del);\n        std::swap(lim, r.lim);\n        cvs.swap(r.cvs);\n    }\n};\n\nstruct pj_gi_load\n{\n    enum format_t { missing = 0, ntv1, ntv2, gtx, ctable, ctable2 };\n    typedef boost::long_long_type offset_t;\n\n    explicit pj_gi_load(std::string const& gname = \"\",\n                        format_t f = missing,\n                        offset_t off = 0,\n                        bool swap = false)\n        : gridname(gname)\n        , format(f)\n        , grid_offset(off)\n        , must_swap(swap)\n    {}\n\n    std::string gridname; // identifying name of grid, eg \"conus\" or ntv2_0.gsb\n\n    format_t format;      // format of this grid, ie \"ctable\", \"ntv1\", \"ntv2\" or \"missing\".\n\n    offset_t grid_offset; // offset in file, for delayed loading\n    bool must_swap;       // only for NTv2\n\n    pj_ctable ct;\n\n    inline void swap(pj_gi_load & r)\n    {\n        gridname.swap(r.gridname);\n        std::swap(format, r.format);\n        std::swap(grid_offset, r.grid_offset);\n        std::swap(must_swap, r.must_swap);\n        ct.swap(r.ct);\n    }\n\n};\n\nstruct pj_gi\n    : pj_gi_load\n{\n    explicit pj_gi(std::string const& gname = \"\",\n                   pj_gi_load::format_t f = missing,\n                   pj_gi_load::offset_t off = 0,\n                   bool swap = false)\n        : pj_gi_load(gname, f, off, swap)\n    {}\n\n    std::vector<pj_gi> children;\n\n    inline void swap(pj_gi & r)\n    {\n        pj_gi_load::swap(r);\n        children.swap(r.children);\n    }\n};\n\ntypedef std::vector<pj_gi> pj_gridinfo;\n\n\n/************************************************************************/\n/*                   pj_gridinfo_load_ctable()                          */\n/*                                                                      */\n/*      Load the data portion of a ctable formatted grid.               */\n/************************************************************************/\n\n// Originally nad_ctable_load() defined in nad_init.c\ntemplate <typename IStream>\nbool pj_gridinfo_load_ctable(IStream & is, pj_gi_load & gi)\n{\n    pj_ctable & ct = gi.ct;\n\n    // Move the input stream by the size of the proj4 original CTABLE\n    std::size_t header_size = 80\n                            + 2 * sizeof(pj_ctable::lp_t)\n                            + sizeof(pj_ctable::ilp_t)\n                            + sizeof(pj_ctable::flp_t*);\n    is.seekg(header_size);\n\n    // read all the actual shift values\n    std::size_t a_size = ct.lim.lam * ct.lim.phi;\n    ct.cvs.resize(a_size);\n\n    std::size_t ch_size = sizeof(pj_ctable::flp_t) * a_size;\n    is.read(reinterpret_cast<char*>(&ct.cvs[0]), ch_size);\n\n    if (is.fail() || is.gcount() != ch_size)\n    {\n        ct.cvs.clear();\n        //ctable loading failed on fread() - binary incompatible?\n        return false;\n    }\n\n    return true;\n}\n\n/************************************************************************/\n/*                  pj_gridinfo_load_ctable2()                          */\n/*                                                                      */\n/*      Load the data portion of a ctable2 formatted grid.              */\n/************************************************************************/\n\n// Originally nad_ctable2_load() defined in nad_init.c\ntemplate <typename IStream>\nbool pj_gridinfo_load_ctable2(IStream & is, pj_gi_load & gi)\n{\n    pj_ctable & ct = gi.ct;\n\n    is.seekg(160);\n\n    // read all the actual shift values\n    std::size_t a_size = ct.lim.lam * ct.lim.phi;\n    ct.cvs.resize(a_size);\n\n    std::size_t ch_size = sizeof(pj_ctable::flp_t) * a_size;\n    is.read(reinterpret_cast<char*>(&ct.cvs[0]), ch_size);\n\n    if (is.fail() || is.gcount() != ch_size)\n    {\n        //ctable2 loading failed on fread() - binary incompatible?\n        ct.cvs.clear();\n        return false;\n    }\n\n    if (! is_lsb())\n    {\n        swap_words(reinterpret_cast<char*>(&ct.cvs[0]), 4, (int)a_size * 2);\n    }\n\n    return true;\n}\n\n/************************************************************************/\n/*                      pj_gridinfo_load_ntv1()                         */\n/*                                                                      */\n/*      NTv1 format.                                                    */\n/*      We process one line at a time.  Note that the array storage     */\n/*      direction (e-w) is different in the NTv1 file and what          */\n/*      the CTABLE is supposed to have.  The phi/lam are also           */\n/*      reversed, and we have to be aware of byte swapping.             */\n/************************************************************************/\n\n// originally in pj_gridinfo_load() function\ntemplate <typename IStream>\ninline bool pj_gridinfo_load_ntv1(IStream & is, pj_gi_load & gi)\n{\n    static const double s2r = math::d2r<double>() / 3600.0;\n\n    std::size_t const r_size = gi.ct.lim.lam * 2;\n    std::size_t const ch_size = sizeof(double) * r_size;\n\n    is.seekg(gi.grid_offset);\n\n    std::vector<double> row_buf(r_size);\n    gi.ct.cvs.resize(gi.ct.lim.lam * gi.ct.lim.phi);\n\n    for (boost::int32_t row = 0; row < gi.ct.lim.phi; row++ )\n    {\n        is.read(reinterpret_cast<char*>(&row_buf[0]), ch_size);\n\n        if (is.fail() || is.gcount() != ch_size)\n        {\n            gi.ct.cvs.clear();\n            return false;\n        }\n\n        if (is_lsb())\n            swap_words(reinterpret_cast<char*>(&row_buf[0]), 8, (int)r_size);\n\n        // convert seconds to radians\n        for (boost::int32_t i = 0; i < gi.ct.lim.lam; i++ )\n        {\n            pj_ctable::flp_t & cvs = gi.ct.cvs[row * gi.ct.lim.lam + (gi.ct.lim.lam - i - 1)];\n\n            cvs.phi = (float) (row_buf[i*2] * s2r);\n            cvs.lam = (float) (row_buf[i*2+1] * s2r);\n        }\n    }\n\n    return true;\n}\n\n/* -------------------------------------------------------------------- */\n/*                         pj_gridinfo_load_ntv2()                      */\n/*                                                                      */\n/*      NTv2 format.                                                    */\n/*      We process one line at a time.  Note that the array storage     */\n/*      direction (e-w) is different in the NTv2 file and what          */\n/*      the CTABLE is supposed to have.  The phi/lam are also           */\n/*      reversed, and we have to be aware of byte swapping.             */\n/* -------------------------------------------------------------------- */\n\n// originally in pj_gridinfo_load() function\ntemplate <typename IStream>\ninline bool pj_gridinfo_load_ntv2(IStream & is, pj_gi_load & gi)\n{\n    static const double s2r = math::d2r<double>() / 3600.0;\n\n    std::size_t const r_size = gi.ct.lim.lam * 4;\n    std::size_t const ch_size = sizeof(float) * r_size;\n\n    is.seekg(gi.grid_offset);\n\n    std::vector<float> row_buf(r_size);\n    gi.ct.cvs.resize(gi.ct.lim.lam * gi.ct.lim.phi);\n\n    for (boost::int32_t row = 0; row < gi.ct.lim.phi; row++ )\n    {\n        is.read(reinterpret_cast<char*>(&row_buf[0]), ch_size);\n\n        if (is.fail() || is.gcount() != ch_size)\n        {\n            gi.ct.cvs.clear();\n            return false;\n        }\n\n        if (gi.must_swap)\n        {\n            swap_words(reinterpret_cast<char*>(&row_buf[0]), 4, (int)r_size);\n        }\n\n        // convert seconds to radians\n        for (boost::int32_t i = 0; i < gi.ct.lim.lam; i++ )\n        {\n            pj_ctable::flp_t & cvs = gi.ct.cvs[row * gi.ct.lim.lam + (gi.ct.lim.lam - i - 1)];\n\n            // skip accuracy values\n            cvs.phi = (float) (row_buf[i*4] * s2r);\n            cvs.lam = (float) (row_buf[i*4+1] * s2r);\n        }\n    }\n\n    return true;\n}\n\n/************************************************************************/\n/*                   pj_gridinfo_load_gtx()                             */\n/*                                                                      */\n/*      GTX format.                                                     */\n/************************************************************************/\n\n// originally in pj_gridinfo_load() function\ntemplate <typename IStream>\ninline bool pj_gridinfo_load_gtx(IStream & is, pj_gi_load & gi)\n{\n    boost::int32_t words = gi.ct.lim.lam * gi.ct.lim.phi;\n    std::size_t const ch_size = sizeof(float) * words;\n\n    is.seekg(gi.grid_offset);\n\n    // TODO: Consider changing this unintuitive code\n    // NOTE: Vertical shift data (one float per point) is stored in a container\n    // holding horizontal shift data (two floats per point).\n    gi.ct.cvs.resize((words + 1) / 2);\n\n    is.read(reinterpret_cast<char*>(&gi.ct.cvs[0]), ch_size);\n\n    if (is.fail() || is.gcount() != ch_size)\n    {\n        gi.ct.cvs.clear();\n        return false;\n    }\n\n    if (is_lsb())\n    {\n        swap_words(reinterpret_cast<char*>(&gi.ct.cvs[0]), 4, words);\n    }\n\n    return true;\n}\n\n/************************************************************************/\n/*                          pj_gridinfo_load()                          */\n/*                                                                      */\n/*      This function is intended to implement delayed loading of       */\n/*      the data contents of a grid file.  The header and related       */\n/*      stuff are loaded by pj_gridinfo_init().                         */\n/************************************************************************/\n\ntemplate <typename IStream>\ninline bool pj_gridinfo_load(IStream & is, pj_gi_load & gi)\n{\n    if (! gi.ct.cvs.empty())\n    {\n        return true;\n    }\n\n    if (! is.is_open())\n    {\n        return false;\n    }\n\n    // Original platform specific CTable format.\n    if (gi.format == pj_gi::ctable)\n    {\n        return pj_gridinfo_load_ctable(is, gi);\n    }\n    // CTable2 format.\n    else if (gi.format == pj_gi::ctable2)\n    {\n        return pj_gridinfo_load_ctable2(is, gi);\n    }\n    // NTv1 format.\n    else if (gi.format == pj_gi::ntv1)\n    {\n        return pj_gridinfo_load_ntv1(is, gi);\n    }\n    // NTv2 format.\n    else if (gi.format == pj_gi::ntv2)\n    {\n        return pj_gridinfo_load_ntv2(is, gi);\n    }\n    // GTX format.\n    else if (gi.format == pj_gi::gtx)\n    {\n        return pj_gridinfo_load_gtx(is, gi);\n    }\n    else\n    {\n        return false;\n    }\n}\n\n/************************************************************************/\n/*                        pj_gridinfo_parent()                          */\n/*                                                                      */\n/*      Seek a parent grid file by name from a grid list                */\n/************************************************************************/\n\ntemplate <typename It>\ninline It pj_gridinfo_parent(It first, It last, std::string const& name)\n{\n    for ( ; first != last ; ++first)\n    {\n        if (first->ct.id == name)\n            return first;\n\n        It parent = pj_gridinfo_parent(first->children.begin(), first->children.end(), name);\n        if( parent != first->children.end() )\n            return parent;\n    }\n\n    return last;\n}\n\n/************************************************************************/\n/*                       pj_gridinfo_init_ntv2()                        */\n/*                                                                      */\n/*      Load a ntv2 (.gsb) file.                                        */\n/************************************************************************/\n\ntemplate <typename IStream>\ninline bool pj_gridinfo_init_ntv2(std::string const& gridname,\n                                  IStream & is,\n                                  pj_gridinfo & gridinfo)\n{\n    BOOST_STATIC_ASSERT( sizeof(boost::int32_t) == 4 );\n    BOOST_STATIC_ASSERT( sizeof(double) == 8 );\n\n    static const double s2r = math::d2r<double>() / 3600.0;\n\n    std::size_t gridinfo_orig_size = gridinfo.size();\n\n    // Read the overview header.\n    char header[11*16];\n\n    is.read(header, sizeof(header));\n    if( is.fail() )\n    {\n        return false;\n    }\n\n    bool must_swap = (header[8] == 11)\n                   ? !is_lsb()\n                   : is_lsb();\n\n    // NOTE: This check is not implemented in proj4\n    if (! cstr_equal(header + 56, \"SECONDS\", 7))\n    {\n        return false;\n    }\n\n    // Byte swap interesting fields if needed.\n    if( must_swap )\n    {\n        swap_words( header+8, 4, 1 );\n        swap_words( header+8+16, 4, 1 );\n        swap_words( header+8+32, 4, 1 );\n        swap_words( header+8+7*16, 8, 1 );\n        swap_words( header+8+8*16, 8, 1 );\n        swap_words( header+8+9*16, 8, 1 );\n        swap_words( header+8+10*16, 8, 1 );\n    }\n\n    // Get the subfile count out ... all we really use for now.\n    boost::int32_t num_subfiles;\n    memcpy( &num_subfiles, header+8+32, 4 );\n\n    // Step through the subfiles, creating a PJ_GRIDINFO for each.\n    for( boost::int32_t subfile = 0; subfile < num_subfiles; subfile++ )\n    {\n        // Read header.\n        is.read(header, sizeof(header));\n        if( is.fail() )\n        {\n            return false;\n        }\n\n        if(! cstr_equal(header, \"SUB_NAME\", 8))\n        {\n            return false;\n        }\n\n        // Byte swap interesting fields if needed.\n        if( must_swap )\n        {\n            swap_words( header+8+16*4, 8, 1 );\n            swap_words( header+8+16*5, 8, 1 );\n            swap_words( header+8+16*6, 8, 1 );\n            swap_words( header+8+16*7, 8, 1 );\n            swap_words( header+8+16*8, 8, 1 );\n            swap_words( header+8+16*9, 8, 1 );\n            swap_words( header+8+16*10, 4, 1 );\n        }\n\n        // Initialize a corresponding \"ct\" structure.\n        pj_ctable ct;\n        pj_ctable::lp_t ur;\n\n        ct.id = std::string(header + 8, 8);\n\n        ct.ll.lam = - *((double *) (header+7*16+8)); /* W_LONG */\n        ct.ll.phi = *((double *) (header+4*16+8));   /* S_LAT */\n\n        ur.lam = - *((double *) (header+6*16+8));     /* E_LONG */\n        ur.phi = *((double *) (header+5*16+8));       /* N_LAT */\n\n        ct.del.lam = *((double *) (header+9*16+8));\n        ct.del.phi = *((double *) (header+8*16+8));\n\n        ct.lim.lam = (boost::int32_t) (fabs(ur.lam-ct.ll.lam)/ct.del.lam + 0.5) + 1;\n        ct.lim.phi = (boost::int32_t) (fabs(ur.phi-ct.ll.phi)/ct.del.phi + 0.5) + 1;\n\n        ct.ll.lam *= s2r;\n        ct.ll.phi *= s2r;\n        ct.del.lam *= s2r;\n        ct.del.phi *= s2r;\n\n        boost::int32_t gs_count;\n        memcpy( &gs_count, header + 8 + 16*10, 4 );\n        if( gs_count != ct.lim.lam * ct.lim.phi )\n        {\n            return false;\n        }\n\n        //ct.cvs.clear();\n\n        // Create a new gridinfo for this if we aren't processing the\n        // 1st subfile, and initialize our grid info.\n\n        // Attach to the correct list or sublist.\n\n        // TODO is offset needed?\n        pj_gi gi(gridname, pj_gi::ntv2, is.tellg(), must_swap);\n        gi.ct = ct;\n\n        if( subfile == 0 )\n        {\n            gridinfo.push_back(gi);\n        }\n        else if( cstr_equal(header+24, \"NONE\", 4) )\n        {\n            gridinfo.push_back(gi);\n        }\n        else\n        {\n            pj_gridinfo::iterator git = pj_gridinfo_parent(gridinfo.begin() + gridinfo_orig_size,\n                                                           gridinfo.end(),\n                                                           std::string((const char*)header+24, 8));\n\n            if( git == gridinfo.end() )\n            {\n                gridinfo.push_back(gi);\n            }\n            else\n            {\n                git->children.push_back(gi);\n            }\n        }\n\n        // Seek past the data.\n        is.seekg(gs_count * 16, std::ios::cur);\n    }\n\n    return true;\n}\n\n/************************************************************************/\n/*                       pj_gridinfo_init_ntv1()                        */\n/*                                                                      */\n/*      Load an NTv1 style Canadian grid shift file.                    */\n/************************************************************************/\n\ntemplate <typename IStream>\ninline bool pj_gridinfo_init_ntv1(std::string const& gridname,\n                                  IStream & is,\n                                  pj_gridinfo & gridinfo)\n{\n    BOOST_STATIC_ASSERT( sizeof(boost::int32_t) == 4 );\n    BOOST_STATIC_ASSERT( sizeof(double) == 8 );\n\n    static const double d2r = math::d2r<double>();\n\n    // Read the header.\n    char header[176];\n\n    is.read(header, sizeof(header));\n    if( is.fail() )\n    {\n        return false;\n    }\n\n    // Regularize fields of interest.\n    if( is_lsb() )\n    {\n        swap_words( header+8, 4, 1 );\n        swap_words( header+24, 8, 1 );\n        swap_words( header+40, 8, 1 );\n        swap_words( header+56, 8, 1 );\n        swap_words( header+72, 8, 1 );\n        swap_words( header+88, 8, 1 );\n        swap_words( header+104, 8, 1 );\n    }\n\n    // NTv1 grid shift file has wrong record count, corrupt?\n    if( *((boost::int32_t *) (header+8)) != 12 )\n    {\n        return false;\n    }\n\n    // NOTE: This check is not implemented in proj4\n    if (! cstr_equal(header + 120, \"SECONDS\", 7))\n    {\n        return false;\n    }\n\n    // Fill in CTABLE structure.\n    pj_ctable ct;\n    pj_ctable::lp_t ur;\n\n    ct.id = \"NTv1 Grid Shift File\";\n\n    ct.ll.lam = - *((double *) (header+72));\n    ct.ll.phi = *((double *) (header+24));\n    ur.lam = - *((double *) (header+56));\n    ur.phi = *((double *) (header+40));\n    ct.del.lam = *((double *) (header+104));\n    ct.del.phi = *((double *) (header+88));\n    ct.lim.lam = (boost::int32_t) (fabs(ur.lam-ct.ll.lam)/ct.del.lam + 0.5) + 1;\n    ct.lim.phi = (boost::int32_t) (fabs(ur.phi-ct.ll.phi)/ct.del.phi + 0.5) + 1;\n\n    ct.ll.lam *= d2r;\n    ct.ll.phi *= d2r;\n    ct.del.lam *= d2r;\n    ct.del.phi *= d2r;\n    //ct.cvs.clear();\n\n    // is offset needed?\n    gridinfo.push_back(pj_gi(gridname, pj_gi::ntv1, is.tellg()));\n    gridinfo.back().ct = ct;\n\n    return true;\n}\n\n/************************************************************************/\n/*                       pj_gridinfo_init_gtx()                         */\n/*                                                                      */\n/*      Load a NOAA .gtx vertical datum shift file.                     */\n/************************************************************************/\n\ntemplate <typename IStream>\ninline bool pj_gridinfo_init_gtx(std::string const& gridname,\n                                 IStream & is,\n                                 pj_gridinfo & gridinfo)\n{\n    BOOST_STATIC_ASSERT( sizeof(boost::int32_t) == 4 );\n    BOOST_STATIC_ASSERT( sizeof(double) == 8 );\n\n    static const double d2r = math::d2r<double>();\n\n    // Read the header.\n    char header[40];\n\n    is.read(header, sizeof(header));\n    if( is.fail() )\n    {\n        return false;\n    }\n\n    // Regularize fields of interest and extract.\n    double         xorigin, yorigin, xstep, ystep;\n    boost::int32_t rows, columns;\n\n    if( is_lsb() )\n    {\n        swap_words( header+0, 8, 4 );\n        swap_words( header+32, 4, 2 );\n    }\n\n    memcpy( &yorigin, header+0, 8 );\n    memcpy( &xorigin, header+8, 8 );\n    memcpy( &ystep, header+16, 8 );\n    memcpy( &xstep, header+24, 8 );\n\n    memcpy( &rows, header+32, 4 );\n    memcpy( &columns, header+36, 4 );\n\n    // gtx file header has invalid extents, corrupt?\n    if( xorigin < -360 || xorigin > 360\n        || yorigin < -90 || yorigin > 90 )\n    {\n        return false;\n    }\n\n    // Fill in CTABLE structure.\n    pj_ctable ct;\n\n    ct.id = \"GTX Vertical Grid Shift File\";\n\n    ct.ll.lam = xorigin;\n    ct.ll.phi = yorigin;\n    ct.del.lam = xstep;\n    ct.del.phi = ystep;\n    ct.lim.lam = columns;\n    ct.lim.phi = rows;\n\n    // some GTX files come in 0-360 and we shift them back into the\n    // expected -180 to 180 range if possible. This does not solve\n    // problems with grids spanning the dateline.\n    if( ct.ll.lam >= 180.0 )\n        ct.ll.lam -= 360.0;\n\n    if( ct.ll.lam >= 0.0 && ct.ll.lam + ct.del.lam * ct.lim.lam > 180.0 )\n    {\n        //\"This GTX spans the dateline!  This will cause problems.\" );\n    }\n\n    ct.ll.lam *= d2r;\n    ct.ll.phi *= d2r;\n    ct.del.lam *= d2r;\n    ct.del.phi *= d2r;\n    //ct.cvs.clear();\n\n    // is offset needed?\n    gridinfo.push_back(pj_gi(gridname, pj_gi::gtx, 40));\n    gridinfo.back().ct = ct;\n\n    return true;\n}\n\n/************************************************************************/\n/*                   pj_gridinfo_init_ctable2()                         */\n/*                                                                      */\n/*      Read the header portion of a \"ctable2\" format grid.             */\n/************************************************************************/\n\n// Originally nad_ctable2_init() defined in nad_init.c\ntemplate <typename IStream>\ninline bool pj_gridinfo_init_ctable2(std::string const& gridname,\n                                     IStream & is,\n                                     pj_gridinfo & gridinfo)\n{\n    BOOST_STATIC_ASSERT( sizeof(boost::int32_t) == 4 );\n    BOOST_STATIC_ASSERT( sizeof(double) == 8 );\n\n    char header[160];\n\n    is.read(header, sizeof(header));\n    if( is.fail() )\n    {\n        return false;\n    }\n\n    if( !is_lsb() )\n    {\n        swap_words( header +  96, 8, 4 );\n        swap_words( header + 128, 4, 2 );\n    }\n\n    // ctable2 - wrong header!\n    if (! cstr_equal(header, \"CTABLE V2\", 9))\n    {\n        return false;\n    }\n\n    // read the table header\n    pj_ctable ct;\n\n    ct.id = std::string(header + 16, std::find(header + 16, header + 16 + 80, '\\0'));\n    //memcpy( &ct.ll.lam,  header +  96, 8 );\n    //memcpy( &ct.ll.phi,  header + 104, 8 );\n    //memcpy( &ct.del.lam, header + 112, 8 );\n    //memcpy( &ct.del.phi, header + 120, 8 );\n    //memcpy( &ct.lim.lam, header + 128, 4 );\n    //memcpy( &ct.lim.phi, header + 132, 4 );\n    memcpy( &ct.ll,  header +  96, 40 );\n\n    // do some minimal validation to ensure the structure isn't corrupt\n    if ( ct.lim.lam < 1 || ct.lim.lam > 100000\n      || ct.lim.phi < 1 || ct.lim.phi > 100000 )\n    {\n        return false;\n    }\n\n    // trim white space and newlines off id\n    boost::trim_right_if(ct.id, is_trimmable_char());\n\n    //ct.cvs.clear();\n\n    gridinfo.push_back(pj_gi(gridname, pj_gi::ctable2));\n    gridinfo.back().ct = ct;\n\n    return true;\n}\n\n/************************************************************************/\n/*                    pj_gridinfo_init_ctable()                         */\n/*                                                                      */\n/*      Read the header portion of a \"ctable\" format grid.              */\n/************************************************************************/\n\n// Originally nad_ctable_init() defined in nad_init.c\ntemplate <typename IStream>\ninline bool pj_gridinfo_init_ctable(std::string const& gridname,\n                                    IStream & is,\n                                    pj_gridinfo & gridinfo)\n{\n    BOOST_STATIC_ASSERT( sizeof(boost::int32_t) == 4 );\n    BOOST_STATIC_ASSERT( sizeof(double) == 8 );\n\n    // 80 + 2*8 + 2*8 + 2*4\n    char header[120];\n\n    // NOTE: in proj4 data is loaded directly into CTABLE\n\n    is.read(header, sizeof(header));\n    if( is.fail() )\n    {\n        return false;\n    }\n\n    // NOTE: in proj4 LSB is not checked here\n\n    // read the table header\n    pj_ctable ct;\n\n    ct.id = std::string(header, std::find(header, header + 80, '\\0'));\n    memcpy( &ct.ll, header + 80, 40 );\n\n    // do some minimal validation to ensure the structure isn't corrupt\n    if ( ct.lim.lam < 1 || ct.lim.lam > 100000\n      || ct.lim.phi < 1 || ct.lim.phi > 100000 )\n    {\n        return false;\n    }\n\n    // trim white space and newlines off id\n    boost::trim_right_if(ct.id, is_trimmable_char());\n\n    //ct.cvs.clear();\n\n    gridinfo.push_back(pj_gi(gridname, pj_gi::ctable));\n    gridinfo.back().ct = ct;\n\n    return true;\n}\n\n/************************************************************************/\n/*                          pj_gridinfo_init()                          */\n/*                                                                      */\n/*      Open and parse header details from a datum gridshift file       */\n/*      returning a list of PJ_GRIDINFOs for the grids in that          */\n/*      file.  This superceeds use of nad_init() for modern             */\n/*      applications.                                                   */\n/************************************************************************/\n\ntemplate <typename IStream>\ninline bool pj_gridinfo_init(std::string const& gridname,\n                             IStream & is,\n                             pj_gridinfo & gridinfo)\n{\n    char header[160];\n\n    // Check if the stream is opened.\n    if (! is.is_open()) {\n        return false;\n    }\n\n    // Load a header, to determine the file type.\n    is.read(header, sizeof(header));\n\n    if ( is.fail() ) {\n        return false;\n    }\n\n    is.seekg(0);\n\n    // Determine file type.\n    if ( cstr_equal(header + 0, \"HEADER\", 6)\n      && cstr_equal(header + 96, \"W GRID\", 6)\n      && cstr_equal(header + 144, \"TO      NAD83   \", 16) )\n    {\n        return pj_gridinfo_init_ntv1(gridname, is, gridinfo);\n    }\n    else if( cstr_equal(header + 0, \"NUM_OREC\", 8)\n          && cstr_equal(header + 48, \"GS_TYPE\", 7) )\n    {\n        return pj_gridinfo_init_ntv2(gridname, is, gridinfo);\n    }\n    else if( boost::algorithm::ends_with(gridname, \"gtx\")\n          || boost::algorithm::ends_with(gridname, \"GTX\") )\n    {\n        return pj_gridinfo_init_gtx(gridname, is, gridinfo);\n    }\n    else if( cstr_equal(header + 0, \"CTABLE V2\", 9) )\n    {\n        return pj_gridinfo_init_ctable2(gridname, is, gridinfo);\n    }\n    else\n    {\n        return pj_gridinfo_init_ctable(gridname, is, gridinfo);\n    }\n}\n\n\n} // namespace detail\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_PJ_GRIDINFO_HPP\n", "meta": {"hexsha": "f38c8ce729e9485722ebd1ffd50f86811cecf5d1", "size": 29691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/impl/pj_gridinfo.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/impl/pj_gridinfo.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/impl/pj_gridinfo.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": 30.8959417274, "max_line_length": 99, "alphanum_fraction": 0.492842949, "num_tokens": 7316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510108, "lm_q2_score": 0.031143831996063107, "lm_q1q2_score": 0.008375866078955466}}
{"text": "/*\n * FindCenter.cpp\n *\n *  Created on: 2017-05-26\n *      Author: ivan\n */\n\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <boost/static_assert.hpp>\n\n#include \"zip.h\"\n#include \"GraphOperations.h\"\n#define BAD_OUTPUT 10101010\n\nusing namespace std;\nusing namespace graph_buzz;\n\n/*******************************************************\n * Tree\n */\n\nGraphOperations::TreeVertex::TreeVertex ( Vertex id, int depth )\n{\n    _m = id;\n    _depth = depth;\n    _children = new std::vector<TreeVertex>();\n    _m_parent = NULL;\n}\n\nvoid GraphOperations::TreeVertex::SetParent ( TreeVertex* parent )\n{\n    _m_parent = parent;\n}\n\nvoid GraphOperations::TreeVertex::SetChild ( TreeVertex* child )\n{\n    _children->push_back ( *child );\n}\n\nstd::vector<GraphOperations::TreeVertex>* GraphOperations::TreeVertex::GetChildren()\n{\n    return _children;\n}\n\nGraphOperations::TreeVertex* GraphOperations::TreeVertex::GetParent()\n{\n    return _m_parent;\n}\n\nVertex GraphOperations::TreeVertex::GetId()\n{\n    return _m;\n}\n\n/*********************************************************************\n***** File related operations\n**********************************************************************/\n\nvoid GraphOperations::WriteGraphToFile ( const Graph& g, const std::string& filename )\n{\n    std::ofstream graphStream;\n    graphStream.open ( filename.c_str() );\n    boost::write_graphviz ( graphStream, g );\n    graphStream.close();\n}\nstd::string GraphOperations::WriteGraphToDotString ( const Graph& g, dynamic_properties& dp )\n{\n    std::stringstream stream;\n    boost::write_graphviz_dp ( stream, g, dp );\n    return stream.str();\n}\n\nstd::string GraphOperations::WriteGraphToString ( const Graph& g, dynamic_properties& dp )\n{\n    std::stringstream stream;\n    boost::write_graphviz_dp ( stream, g, dp );\n\n    std::string delimiter = \"\\n\";\n    std::string result = \"\";\n    std::string s = stream.str();\n\n    size_t pos = 0;\n    std::string token;\n    int i = 0;\n    while ( ( pos = s.find ( delimiter ) ) != std::string::npos ) {\n        token = s.substr ( 0, pos );\n        if ( i > num_vertices ( g ) ) {\n            result += token;\n        }\n        s.erase ( 0, pos + delimiter.length() );\n        i++;\n    }\n\n    boost::replace_all ( result, \";}\",\";\" );\n    boost::replace_all ( result, \"--\",\"-\" );\n    boost::replace_all ( result, \" \",\"\" );\n    return result;\n}\n\nvoid GraphOperations::OpenFromXML ( Graph& g, dynamic_properties& dp, const std::string& filename )\n{\n    std::ifstream inFile;\n\n    inFile.open ( filename.c_str(), std::ifstream::in );\n    read_graphml ( inFile, g, dp );\n}\n\nvoid GraphOperations::OpenFromString ( Graph& g, dynamic_properties& dp, char buffer [] )\n{\n    membuf sbuf ( buffer, buffer + strlen ( buffer ) );\n    std::istream in ( &sbuf );\n    read_graphml ( in, g, dp );\n}\n\nvoid GraphOperations::SetNames ( Graph& g, NameMap& nameMap )\n{\n    for ( int i = 0; i < num_vertices ( g ); i++ ) {\n        std::stringstream ss;\n        ss << ( i + 15 );\n        nameMap[i] = i;\n    }\n}\n\n/*********************************************************************\n***** Graph properties\n**********************************************************************/\n\nvoid GraphOperations::SetWeights ( Graph& g, DistanceMap& distanceMap, float weight )\n{\n    // sets the weight\n    graph_traits<Graph>::edge_iterator ei, ee;\n    for ( tie ( ei, ee ) = edges ( g ); ei != ee; ++ei ) {\n        put ( edge_weight, g, *ei, weight );\n    }\n\n    for ( int i = 0; i < num_edges ( g ); i++ ) {\n        distanceMap[i] = weight;\n    }\n}\n\nvoid GraphOperations::RemoveEdges ( Graph &g )\n{\n    // Removes all edges to and from vertex.\n    graph_traits<Graph>::vertex_iterator i, end;\n    for ( tie ( i, end ) = vertices ( g ); i != end; ++i ) {\n        //cout << \"Name: \" << get(nameMap, *i) << endl;\n        clear_vertex ( *i, g );\n    }\n}\n\nvoid GraphOperations::PrintGraphProperties ( Graph& g, NameMap& nameMap, DistanceMap& distanceMap )\n{\n    for ( int i = 0; i < num_vertices ( g ); i++ ) {\n        cout << \"Vertex: \" << nameMap[i] << endl;\n    }\n\n    for ( int i = 0; i < num_edges ( g ); i++ ) {\n        cout << \"Weight: \" << distanceMap[i] << endl;\n    }\n}\n// pair vertice and value\nstd::vector< std::pair<int, float> > GraphOperations::GetCentralities ( Graph& g, NameMap& nameMap, IndexMap& indexMap )\n{\n    DistanceMatrix dsts ( num_vertices ( g ) );\n    DistanceMatrixMap dm ( dsts, g );\n    WeightMap wm ( 1 );\n    floyd_warshall_all_pairs_shortest_paths ( g, dm, weight_map ( wm ) );\n\n    // centrality\n    ClosenessContainer cents ( num_vertices ( g ) );\n    ClosenessMap cm ( cents, g );\n    all_closeness_centralities ( g, dm, cm );\n\n    std::vector< std::pair<int, float> > centralities;\n    graph_traits<Graph>::vertex_iterator i, end;\n    for ( boost::tie ( i, end ) = vertices ( g ); i != end; ++i ) {\n        centralities.push_back ( std::make_pair ( ( int ) get ( indexMap, *i ), ( float ) get ( cm, *i ) ) );\n    }\n\n    std::sort ( centralities.begin(), centralities.end(), boost::bind ( &std::pair<int, float>::second, _1 ) > boost::bind ( &std::pair<int, float>::second, _2 ) );\n    return centralities;\n}\n\n/*********************************************************************\n***** Graph related opreations\n**********************************************************************/\n\nVertex GraphOperations::GetFreeNeighbor ( Graph& g, Vertex vertex, std::vector<Vertex> taken )\n{\n    // loop through neighbours and extract one of the neigbours not in the taken list\n    Graph::adjacency_iterator neighbourIt, neighbourEnd;\n    tie ( neighbourIt, neighbourEnd ) = adjacent_vertices ( vertex, g );\n\n    for ( ; neighbourIt != neighbourEnd; ++neighbourIt ) {\n        Vertex v_current_neighbor = *neighbourIt;\n        if ( std::find ( taken.begin(), taken.end(), v_current_neighbor ) == taken.end() ) {\n            return v_current_neighbor;\n        }\n    }\n    return BAD_OUTPUT;\n}\n\nVertex GraphOperations::GetTakenNeighbor ( Graph& g, Vertex vertex, std::vector<Vertex> taken )\n{\n    // loop through neighbours and extract one of the neigbours not in the taken list\n    Graph::adjacency_iterator neighbourIt, neighbourEnd;\n    tie ( neighbourIt, neighbourEnd ) = adjacent_vertices ( vertex, g );\n\n    for ( ; neighbourIt != neighbourEnd; ++neighbourIt ) {\n        Vertex v_current_neighbor = *neighbourIt;\n        if ( std::find ( taken.begin(), taken.end(), v_current_neighbor ) != taken.end() ) {\n            return v_current_neighbor;\n        }\n    }\n    return BAD_OUTPUT;\n}\n\nGraph GraphOperations::ConstructSubgraph ( Graph g, std::vector<int> subtree_vertices )\n{\n    Graph subgraph;\n    BOOST_FOREACH ( int member, subtree_vertices ) {\n        //std::cout<<\"Member: \"<<member<<std::endl;\n        NameMap nameMap = boost::get ( boost::vertex_name, subgraph );\n        Vertex a = add_vertex ( subgraph );\n        std::stringstream int_stream;\n        int_stream << member;\n        nameMap[a] = int_stream.str();\n    }\n\n    NameMap v_names = boost::get ( boost::vertex_name, subgraph );\n    graph_traits<Graph>::vertex_iterator s_i, s_end;\n    graph_traits<Graph>::vertex_iterator t_i, t_end;\n\n    for ( tie ( s_i, s_end ) = vertices ( subgraph ); s_i != s_end; ++s_i ) {\n        for ( tie ( t_i, t_end ) = vertices ( subgraph ); t_i != t_end; ++t_i ) {\n            int v_source = *s_i;\n            int v_target = *t_i;\n            int v_source_name = lexical_cast<int> ( get ( v_names, v_source ) );\n            int v_target_name = lexical_cast<int> ( get ( v_names, v_target ) );\n            if ( EdgeExists ( g, v_source_name, v_target_name ) && !EdgeExists ( subgraph, v_target, v_source ) ) {\n                add_edge ( v_source, v_target, subgraph );\n            }\n        }\n    }\n    return subgraph;\n}\n\nbool GraphOperations::EdgeExists ( Graph g, int member, int submember )\n{\n    graph_traits<Graph>::edge_iterator ei, ee;\n    for ( tie ( ei, ee ) = edges ( g ); ei != ee; ++ei ) {\n        int v_source = source ( *ei, g );\n        int v_target = target ( *ei, g );\n        if ( v_source == member && v_target == submember ) {\n            return true;\n        }\n    }\n    return false;\n}\n\n\nbool GraphOperations::IsIn ( std::vector<int> elements, int element )\n{\n    BOOST_FOREACH ( int current, elements ) {\n        if ( current == element ) {\n            return true;\n        }\n    }\n    return false;\n}\n\n\nstd::vector<GraphOperations::TreeVertex*> GraphOperations::zipit ( std::vector<TreeVertex*> next_level_nodes, std::vector<TreeVertex>* children, int depth )\n{\n    std::vector<TreeVertex*> children_list;\n    std::vector<TreeVertex*> zipped_list;\n    for ( std::vector<TreeVertex>::iterator it = children->begin(); it != children->end(); ++it ) {\n        //children_list.push_back ( new TreeVertex ( ( *it ).GetId(), depth ) );\n        children_list.push_back ( & ( *it ) );\n\n    }\n    int longer_list = ( ( next_level_nodes.size() < children_list.size() ) ? next_level_nodes.size() : children_list.size() );\n    //std::cout<<\"Main: \" << next_level_nodes.size() << \"Children\" << children_list.size() <<std::endl;\n    //std::cout<<\"Longer: \" << longer_list << std::endl;\n\n    std::vector<TreeVertex*>::iterator nln_iterator = next_level_nodes.begin();\n    std::vector<TreeVertex*>::iterator cld_iterator = children_list.begin();\n\n    while ( nln_iterator != next_level_nodes.end() || cld_iterator != children_list.end() ) {\n        if ( nln_iterator != next_level_nodes.end() ) {\n            //std::cout << \"Added \" << (*nln_iterator)->GetId() << std::endl;\n            //zipped_list.push_back ( new TreeVertex ( ( *nln_iterator )->GetId(), depth ) );\n            zipped_list.push_back ( ( *nln_iterator ) );\n            ++nln_iterator;\n        }\n        if ( cld_iterator != children_list.end() ) {\n            //std::cout << \"Added(2) \" << (*cld_iterator)->GetId() << std::endl;\n            //zipped_list.push_back ( new TreeVertex ( ( *cld_iterator )->GetId(), depth ) );\n            zipped_list.push_back ( ( *cld_iterator ) );\n            ++cld_iterator;\n        }\n    }\n    /*\n        std::cout << \"Returning: \" << zipped_list.size() << std::endl;\n        BOOST_FOREACH ( TreeVertex* current_vertex, zipped_list ) {\n            std::cout<<\"Current: \" << current_vertex->GetId() << \" \";\n        }\n    */\n    //delete children_list;\n    return zipped_list;\n\n}\n\n\nstd::vector<int> GraphOperations::NonNeigbourVertices ( Graph g, std::vector< std::pair<int, float> > centralities )\n{\n    std::vector<int> result;\n    NameMap nameMap = boost::get ( boost::vertex_name, g );\n\n    // reverse sort\n    std::sort ( centralities.begin(), centralities.end(), boost::bind ( &std::pair<int, float>::second, _1 ) > boost::bind ( &std::pair<int, float>::second, _2 ) );\n    int v_least_central = vertex ( centralities[0].first, g ); // < change\n    result.push_back ( v_least_central );\n\n    for ( int node = 0; node < centralities.size(); node++ ) {\n        bool push_it = true;\n        BOOST_FOREACH ( int root, result ) {\n            if ( AreNeigbours ( g, root, centralities[node].first ) || centralities[node].first == root ) {\n                push_it = false;\n            }\n        }\n        if ( push_it ) {\n            result.push_back ( centralities[node].first );\n        }\n    }\n   \n    return result;\n}\n\n\nstd::vector<int> GraphOperations::GetBorderCycle(Graph g, std::vector<int> existing_candidates){\n  std::vector<int> cycle;\n  cycle.push_back(existing_candidates.at(0));\n  int cycle_size = 0;\n  int last_to_add = existing_candidates.at(0);\n  bool chain_not_complete = true;\n  int missed = 0;\n  \n  while(chain_not_complete) {\n    BOOST_FOREACH ( int vertex, existing_candidates ) {\n      if(!IsIn(cycle, vertex) && AreNeigbours(g, cycle.at(cycle_size), vertex)){\n\t//std::cout<<\"Add? \" << vertex <<\", \" << NumNeigborsWithDegree(g, vertex, 2) << std::endl;\n\tif(cycle_size >= 2 && NumNeigborsWithDegree(g, cycle.at(cycle_size), 2) > 2){\n\t  //std::cout<<\"pred? \" << cycle.at(cycle_size) <<\", \" << NumNeigborsWithDegree(g, cycle.at(cycle_size), 2) << std::endl;\n\t  if(!AreNeigbours(g, cycle.at(cycle_size - 1), vertex) || AreNeigbours(g, cycle.at(0), last_to_add)){\n\t    std::cout<<\"Adding: \" << vertex << std::endl;\n\t    cycle.push_back(vertex);\n\t    last_to_add = vertex;\n\t    cycle_size++;\n\t    missed = 0;\n\t    break;\n\t  }\n\t} else {\n\t  std::cout<<\"Adding: \" << vertex << std::endl;\n\t  cycle.push_back(vertex);\n\t  last_to_add = vertex;\n\t  cycle_size++;\n\t  missed = 0;\n\t  break;\n\t}\n      }\n    } // end foreach\n    //std::cout<<\"Stuck? \"<< cycle.at(0) << last_to_add <<std::endl;\n    missed++;\n    if(cycle_size > 2 && AreNeigbours(g, cycle.at(0), last_to_add)){\n      chain_not_complete = false;\n    } else if(missed > existing_candidates.size()){\n      chain_not_complete = false;\n    }\n  }\n  //cycle.pop_back();\n  //cycle.at(cycle_size) = cycle.at(0);\n  return cycle;\n}\n\n\nstd::vector<int> GraphOperations::SortedByDegree ( Graph g, std::vector<int> existing_candidates, bool include_ones )\n{\n    std::vector<int> result = existing_candidates;\n    std::vector< std::pair<int, int> > degree_sorted;\n    //std::cout<<\"Degree:\" << degree(0, g) <<std::endl;\n    for ( int i = 0; i < num_vertices ( g ); i++ ) {\n\tif(include_ones){\n\t  degree_sorted.push_back ( std::make_pair ( i, degree ( i, g ) ) );\n\t} else {\n\t  if(degree( i, g ) >= 2){\n\t    degree_sorted.push_back ( std::make_pair ( i, degree ( i, g ) ) );\n\t  }\n\t}\n    }\n\n    std::sort ( degree_sorted.begin(), degree_sorted.end(), boost::bind ( &std::pair<int, int>::second, _1 ) < boost::bind ( &std::pair<int, int>::second, _2 ) );\n    for ( int candidate = 0; candidate < degree_sorted.size(); candidate++ ) {\n        if ( !IsIn ( existing_candidates, degree_sorted[candidate].first ) ) {\n            result.push_back ( degree_sorted[candidate].first );\n        }\n    }\n\n    return result;\n}\n\nint GraphOperations::NumNeigborsWithDegree ( Graph g, int starting_node, int desired_degree )\n{\n    int neighbour_count = 0;\n    Graph::adjacency_iterator neighbourIt, neighbourEnd;\n    tie ( neighbourIt, neighbourEnd ) = adjacent_vertices ( starting_node, g );\n    \n    for ( ; neighbourIt != neighbourEnd; ++neighbourIt ) {\n      int v_current_neighbor = *neighbourIt;\n      if(degree(v_current_neighbor, g) > desired_degree){\n\t  neighbour_count++; \n      }\n    }\n    return neighbour_count;\n}\n\n\n\nbool GraphOperations::AreNeigbours ( Graph g, int starting_node, int ending_node )\n{\n    Graph::adjacency_iterator neighbourIt, neighbourEnd;\n    tie ( neighbourIt, neighbourEnd ) = adjacent_vertices ( starting_node, g );\n    for ( ; neighbourIt != neighbourEnd; ++neighbourIt ) {\n        int v_current_neighbor = *neighbourIt;\n        if ( v_current_neighbor == ending_node ) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint GraphOperations::TreeSize(TreeVertex* vertex, int max_depth ){\n  TreeVertex* root;\n  root = vertex->GetParent();    \n  if(vertex->GetParent() == NULL){\n    root = vertex;\n  } else {\n    while(root->GetParent() != NULL){\n      root = root->GetParent();\n    } \n  }  \n  std::cout<<\"Root is: \" << root->GetId();\n  \n  std::vector<TreeVertex*> current_children_list;\n    for ( std::vector<TreeVertex>::iterator it = root->GetChildren()->begin(); it != root->GetChildren()->end(); ++it ) {\n      current_children_list.push_back ( & ( *it ) );\n  }\n  \n    std::vector<int> subtree_vertices;\n    subtree_vertices.push_back ( ( int ) root->GetId());\n\n  int current_depth = 0;\n  // find all chilldren and build a list\n  while ( current_depth < max_depth ) {\n      std::vector<TreeVertex*> next_children_list;\n      for ( std::vector<TreeVertex*>::iterator cc_i = current_children_list.begin(); cc_i != current_children_list.end(); ++cc_i ) {\n\t  subtree_vertices.push_back ( ( int ) ( *cc_i )->GetId() );\n\t  std::vector<TreeVertex>* current_childrens_children = ( *cc_i )->GetChildren();\n\t  for ( std::vector<TreeVertex>::iterator c_i = current_childrens_children->begin(); c_i != current_childrens_children->end(); ++c_i ) {\n\t      next_children_list.push_back ( & ( *c_i ) );\n\t  }\n      }\n      current_depth++;\n      current_children_list = next_children_list;\n  }\n  \n  return subtree_vertices.size();\n\n}\n\nGraph GraphOperations::ExtractSubgraph ( Graph g, TreeVertex* branch, int max_depth )\n{\n    // write the children in the list\n    std::vector<TreeVertex*> current_children_list;\n    for ( std::vector<TreeVertex>::iterator it = branch->GetChildren()->begin(); it != branch->GetChildren()->end(); ++it ) {\n        current_children_list.push_back ( & ( *it ) );\n    }\n\n    std::vector<int> subtree_vertices;\n    subtree_vertices.push_back ( ( int ) branch->GetId() );\n    int current_depth = 0;\n\n    // find all chilldren and build a list\n    while ( current_depth < max_depth ) {\n        std::vector<TreeVertex*> next_children_list;\n        for ( std::vector<TreeVertex*>::iterator cc_i = current_children_list.begin(); cc_i != current_children_list.end(); ++cc_i ) {\n            subtree_vertices.push_back ( ( int ) ( *cc_i )->GetId() );\n            std::vector<TreeVertex>* current_childrens_children = ( *cc_i )->GetChildren();\n            for ( std::vector<TreeVertex>::iterator c_i = current_childrens_children->begin(); c_i != current_childrens_children->end(); ++c_i ) {\n                next_children_list.push_back ( & ( *c_i ) );\n            }\n        }\n        current_depth++;\n        current_children_list = next_children_list;\n    }\n\n    Graph subgraph = ConstructSubgraph ( g, subtree_vertices );\n    return subgraph;\n}\n\nvoid GraphOperations::SetupRootCandidates(Graph g, std::vector<TreeVertex*> &subtrees, std::vector<Vertex> &taken_vertices, int num_partitions, std::vector< std::pair<int, float> > centralities){\n \n    std::vector<int> cycle_candidates;\n    cycle_candidates = SortedByDegree ( g, cycle_candidates, false);\n    cycle_candidates = GetBorderCycle ( g, cycle_candidates );\n    \n    std::cout<<\"Creating tree using the border cycle \" << std::endl;\n    std::cout << \"Chain size: \" << cycle_candidates.size() << std::endl;\n    BOOST_FOREACH ( int c, cycle_candidates ) {\n      std::cout<< \"Chain: \" << c << std::endl;\n    }\n    \n    if((cycle_candidates.size() / 3) < num_partitions){\n      int nth = cycle_candidates.size() / (cycle_candidates.size() / 3);\n      for(int i = 0; i < cycle_candidates.size(); i+=nth){\n\tsubtrees.push_back ( new TreeVertex ( cycle_candidates[i], 0 ) );\n\ttaken_vertices.push_back ( cycle_candidates[i] );\n\t//cout<<\"Added(c): \" << cycle_candidates[i] << std::endl;\n\tif(taken_vertices.size() >= num_partitions) break;\n      }\n      \n      std::vector<int> neighbour_candidates = NonNeigbourVertices ( g, centralities );\n\n      neighbour_candidates = SortedByDegree ( g, neighbour_candidates, true);\n      while(subtrees.size() < num_partitions){\n\tfor(int i = 0; i < neighbour_candidates.size(); i++){\n\t  if(!IsIn(cycle_candidates, neighbour_candidates[i])){\n\t    std::cout<<\"Pushing: \" << neighbour_candidates[i] << std::endl;\n\t    subtrees.push_back ( new TreeVertex ( neighbour_candidates[i], 0 ) );\n\t    taken_vertices.push_back ( neighbour_candidates[i] );\n\t    cycle_candidates.push_back ( neighbour_candidates[i] );\n\t    break;\n\t  }\n\t}\n\t\n      }\n    } else {\n      int nth = cycle_candidates.size() / num_partitions;\n      for(int i = 0; i < cycle_candidates.size(); i+=nth){\n\tsubtrees.push_back ( new TreeVertex ( cycle_candidates[i], 0 ) );\n\ttaken_vertices.push_back ( cycle_candidates[i] );\n\tcout<<\"Added(c): \" << cycle_candidates[i] << std::endl;\n\tif(taken_vertices.size() >= num_partitions) break;\n      }\n    }\n}\n\nvoid GraphOperations::ConstructForest(Graph g, std::vector<TreeVertex*> &subtrees, std::vector<Vertex> &taken_vertices, std::vector<TreeVertex*> &current_level_nodes, int num_partitions, int max_depth){\n    bool increase_depth = false;\n    int d = 0;\n    int depth = max_depth;\n    \n    while ( d < depth ) {\n        // check to move to next depth level\n        if ( increase_depth ) {\n            std::vector<TreeVertex*> next_level_nodes;\n            BOOST_FOREACH ( TreeVertex* current_vertex, current_level_nodes ) {\n                std::vector<TreeVertex>* children = current_vertex->GetChildren();\n                next_level_nodes = zipit ( next_level_nodes, children, d );\n            }\n            current_level_nodes = next_level_nodes;\n            increase_depth = false;\n        }\n        if ( current_level_nodes.empty() ) {\n            break;\n        }\n        // add children non-greedy\n        int empty_set_counter = current_level_nodes.size();\n        BOOST_FOREACH ( TreeVertex* current_vertex, current_level_nodes ) {\n            Vertex neigbour = GetFreeNeighbor ( g, vertex ( current_vertex->GetId(), g ), taken_vertices );\n\t    std::cout<<\"TreeSize: \" << TreeSize(current_vertex, depth);\n            if ( neigbour != BAD_OUTPUT && !(TreeSize(current_vertex, depth) > 3)) {\n                taken_vertices.push_back ( neigbour );\n                TreeVertex* new_child = new TreeVertex ( neigbour, d + 1 );\n                new_child->SetParent ( current_vertex );\n                current_vertex->SetChild ( new_child );\n                //cout<< current_vertex->GetId() << \" takes \" << new_child->GetId() << std::endl;\n            } else {\n                empty_set_counter -= 1;\n                if ( empty_set_counter == 0 ) {\n                    d++;\n                    increase_depth = true;\n                }\n            }\n        }\n    }\n  \n}\n\nGraphOperations::TreeVertex* GraphOperations::FindChild(std::vector<TreeVertex*> subtrees, int node_id){\n  \n  int max_depth = 5;\n  TreeVertex* result = NULL;\n  std::vector<TreeVertex*> current_children_list;\n  BOOST_FOREACH ( TreeVertex* branch, subtrees ) current_children_list.push_back ( branch );\n  \n  int current_depth = 0;\n  // find all chilldren and build a list\n  while ( current_depth < max_depth ) {\n      std::vector<TreeVertex*> next_children_list;\n      for ( std::vector<TreeVertex*>::iterator cc_i = current_children_list.begin(); cc_i != current_children_list.end(); ++cc_i ) {\n\t  //subtree_vertices.push_back ( ( int ) ( *cc_i )->GetId() );\n\t  if(( int ) ( *cc_i )->GetId() == node_id) {\n\t    result = *cc_i;\n\t    return result;\n\t    \n\t  }\n\t  std::vector<TreeVertex>* current_childrens_children = ( *cc_i )->GetChildren();\n\t  for ( std::vector<TreeVertex>::iterator c_i = current_childrens_children->begin(); c_i != current_childrens_children->end(); ++c_i ) {\n\t      next_children_list.push_back ( & ( *c_i ) );\n\t  }\n      }\n      current_depth++;\n      current_children_list = next_children_list;\n  }\n \n  return result;\n  \n  \n}\n\n/*********************************************************************\n***** Tree related opreations\n**********************************************************************/\n\nstd::string GraphOperations::CreateBalancedForest ( std::string text, int num_partitions, int max_depth)\n{\n    Graph g;\n    dynamic_properties dp;\n\n    const std::string vn = \"vertex_name\";\n    dp.property ( vn,get ( vertex_name,g ) );\n    \n    //num_partitions = 20;\n\n    // convert string to char array\n    char *graph_xml = new char[text.size() +1];\n    graph_xml[text.size()]=0;\n    memcpy ( graph_xml,text.c_str(),text.size() );\n\n    OpenFromString ( g, dp, graph_xml );\n    //OpenFromXML(g, dp, \"../samples/graph-li.xml\");\n    //OpenFromXML(g, dp, \"../samples/temp.xml\");\n\n    //---\n    // Create data for Dijkstra\n    std::vector<Vertex> predecessors ( boost::num_vertices ( g ) ); \t// To store parents\n    std::vector<Weight> distances ( boost::num_edges ( g ) ); \t\t// To store distances\n\n    IndexMap indexMap = boost::get ( boost::vertex_index, g );\n    NameMap nameMap = boost::get ( boost::vertex_name, g );\n\n    PredecessorMap predecessorMap ( &predecessors[0], indexMap );\n    DistanceMap distanceMap ( &distances[0], indexMap );\n\n    SetWeights ( g, distanceMap, 1.0f );\n    //PrintGraphProperties(g, nameMap, distanceMap);\n\n    std::vector< std::pair<int, float> > centralities = GetCentralities ( g, nameMap, indexMap );\n\n    if ( centralities.size() < num_partitions ) {\n        std::cout<<\"You know... the number of partitions is bigger than you have vertices! (HELLOO??ERROR!!!)\" <<std::endl;\n        return NULL;\n    }\n\n    std::vector<TreeVertex*> subtrees;\n    std::vector<TreeVertex*> current_level_nodes;\n    std::vector<Vertex> taken_vertices;\n    \n    \n    std::vector<int> vertex_range;\n    for ( int i = 0; i < num_vertices (g); i++ ) {\n        vertex_range.push_back ( i );\n    }\n    // removes extra edges? - definetly destroys the names (only for Kheperas)\n    //g = ConstructSubgraph ( g, vertex_range ); //-- same?\n    \n    // Setup root candidates (pass by ref... blah)\n    SetupRootCandidates(g, subtrees, taken_vertices, num_partitions, centralities);\n    \n    BOOST_FOREACH ( int c, taken_vertices ) {\n      std::cout<< \"Roots: \" << c << std::endl;\n    }\n    \n    \n    BOOST_FOREACH ( TreeVertex* branch, subtrees ) current_level_nodes.push_back ( branch );\n    \n    // create forest \n    ConstructForest(g, subtrees, taken_vertices, current_level_nodes, num_partitions, max_depth);\n    \n    std::cout<<std::endl<<\"Taken vertices: \" << taken_vertices.size() << std::endl;\n    \n    if(taken_vertices.size() < num_vertices(g)) {\n       std::cout<< \"Handling islands...\" << std::endl;\n      // handle islands \n      std::vector<int> taken_vertices_list;\n      std::vector<int> non_taken_vertices;\n    \n      BOOST_FOREACH(int v, taken_vertices) \n\ttaken_vertices_list.push_back(v);\n\n      BOOST_FOREACH(int v, vertex_range) \n\tif(!IsIn(taken_vertices_list, v)) non_taken_vertices.push_back(v);\n      \n      BOOST_FOREACH(int current_island, non_taken_vertices){\n\tVertex neigbour = GetTakenNeighbor ( g, vertex ( current_island, g ), taken_vertices );\n\tTreeVertex* v = FindChild(subtrees, (int) neigbour);\n\tstd::cout<<\"Candidate for \" << current_island << \" is \" << v->GetId() << std::endl;\n\tif(v != NULL){\n\t  taken_vertices.push_back ( current_island );\n\t  TreeVertex* new_child = new TreeVertex ( current_island, 0);\n\t  new_child->SetParent ( v );\n\t  v->SetChild ( new_child );\n\t  std::cout << \"Added : \" << current_island << std::endl;\n\t}\n\n      }\n      \n    \n      std::cout<<std::endl<<\"Taken vertices: \" << taken_vertices.size() << std::endl;\n    }\n\n    // For each tree, print it\n    std::string final_output = \"\";\n    std::vector<Graph> partitions;\n    int i = 0; \n    \n    std::vector< std::pair<int, int> > original_names;\n    //NameMap nameMap = boost::get ( boost::vertex_name, g );\n    for ( int i = 0; i < num_vertices ( g ); i++ ) {\n      original_names.push_back(std::make_pair(i, std::atoi(nameMap[i].c_str())));\n      std::cout<<\"Original: \" << i << \", \" << nameMap[i] << std::endl;\n    }\n    \n    BOOST_FOREACH ( TreeVertex* current_vertex, subtrees ) {\n\n        Graph partition = ExtractSubgraph ( g, current_vertex, max_depth );\n        partitions.push_back ( partition );\n        // print\n        dynamic_properties dp;\n        dp.property ( \"node_id\", get ( vertex_name, partition ) );\n\tGraph tree = ConstructTreeFromGraph(partition);\n\t\n\tfinal_output += WriteGraphToString ( tree, dp );\n\t//std::cout<< \"Partition: \" << final_output << std::endl;\n        std::cout<<\"Partition: \" << WriteGraphToDotString ( tree, dp ) <<std::endl;\n\tstd::cout<< \"Tree: \" << i << \", size: \"<< num_vertices(partition) << std::endl;\n\ti++;\n\n    }\n\n    //dynamic_properties dp2;\n    //dp2.property ( \"node_id\", get ( vertex_name, partitions[0] ) );\n    //return WriteGraphToString ( partitions[0], dp2 );\n    \n    // khepera name hack\n    for(int i = original_names.size() - 1; i >= 0 ; i--){\n      stringstream first, second;\n      first << original_names[i].first;\n      second << original_names[i].second;     \n      std::cout<<\"Replacing: \" << first.str() << \" with \" << second.str() << \", \" << final_output << std::endl;\n      boost::replace_all(final_output, first.str(), second.str());\n    }\n    \n    return final_output;\n}\n\nstd::string GraphOperations::CreateTree ( std::string text )\n{\n\n    Graph g;\n    dynamic_properties dp;\n\n    const std::string vn = \"vertex_name\";\n    dp.property ( vn,get ( vertex_name,g ) );\n    \n\n    // convert string to char array\n    char *graphml = new char[text.size() +1];\n    graphml[text.size()]=0;\n    memcpy ( graphml,text.c_str(),text.size() );\n    \n    OpenFromString(g, dp, graphml);\n    //OpenFromXML ( g, dp, \"../samples/graph-li.xml\" );\n\n    \n    Graph tree = ConstructTreeFromGraph(g);\n\n    dynamic_properties dp2;\n    dp2.property ( \"node_id\", get ( vertex_name, tree ) );\n    // WriteGraphToFile ( tree, \"tree.dot\" );\n    return WriteGraphToString ( tree, dp2 );\n    //return text;\n}\n\nGraph GraphOperations::ConstructTreeFromGraph(Graph g)\n{\n    // Create data for Dijkstra\n    std::vector<Vertex> predecessors ( boost::num_vertices ( g ) ); \t// To store parents\n    std::vector<Weight> distances ( boost::num_edges ( g ) ); \t\t// To store distances\n\n    IndexMap indexMap = boost::get ( boost::vertex_index, g );\n    NameMap nameMap = boost::get ( boost::vertex_name, g );\n\n    PredecessorMap predecessorMap ( &predecessors[0], indexMap );\n    DistanceMap distanceMap ( &distances[0], indexMap );\n\n    // set names and weights\n    //SetNames(g, nameMap);\n    SetWeights ( g, distanceMap, 1.0f );\n    //PrintGraphProperties(g, nameMap, distanceMap);\n    \n      // floyd warshall\n    std::vector< std::pair<int, float> > centralities = GetCentralities ( g, nameMap, indexMap );\n\n    // dijkstra\n    Vertex v0 = vertex ( centralities[0].first, g ); // < change\n    boost::dijkstra_shortest_paths ( g, v0, boost::distance_map ( distanceMap ).predecessor_map ( predecessorMap ) );\n\n    Graph tree;\n    boost::copy_graph ( g, tree );\n    RemoveEdges ( tree );\n\n    typedef std::vector<Graph::edge_descriptor> PathType;\n\n    for ( int i = 0; i < num_vertices ( g ); i++ ) {\n        PathType path;\n        Vertex v3= vertex ( i, g );\n        Vertex v = v3; // We want to start at the destination and work our way back to the source\n        for ( Vertex u = predecessorMap[v];  u != v; v = u, u = predecessorMap[v] ) {\n            std::pair<Graph::edge_descriptor, bool> edgePair = boost::edge ( u, v, g );\n            Graph::edge_descriptor edge = edgePair.first;\n            path.push_back ( edge );\n            if ( boost::edge ( u,v, tree ).second == false ) {\n                add_edge ( u, v, 1, tree );    // source, destination, weight, tree\n            }\n        }\n    }\n\n    return tree;\n}\n\n\nstd::string GraphOperations::GetShortestPath(std::string text, int source, int destination)\n{  \n    Graph g;\n    dynamic_properties dp;\n\n    const std::string vn = \"vertex_name\";\n    dp.property ( vn,get ( vertex_name,g ) );\n\n    // convert string to char array\n    char *graph_xml = new char[text.size() +1];\n    graph_xml[text.size()]=0;\n    memcpy ( graph_xml,text.c_str(),text.size() );\n\n    OpenFromString ( g, dp, graph_xml );\n\n    // Create data for Dijkstra\n    std::vector<Vertex> predecessors ( boost::num_vertices ( g ) ); \t// To store parents\n    std::vector<Weight> distances ( boost::num_edges ( g ) ); \t\t// To store distances\n\n    IndexMap indexMap = boost::get ( boost::vertex_index, g );\n    NameMap nameMap = boost::get ( boost::vertex_name, g );\n\n    PredecessorMap predecessorMap ( &predecessors[0], indexMap );\n    DistanceMap distanceMap ( &distances[0], indexMap );\n    \n    \n    /** khepera hack */\n    Vertex v0;\n    Vertex v3;\n    \n    std::vector< std::pair<int, int> > original_names;\n    for ( int i = 0; i < num_vertices ( g ); i++ ) {\n      original_names.push_back(std::make_pair(i, std::atoi(nameMap[i].c_str())));\n      if(std::atoi(nameMap[i].c_str()) == source){\n\t  v3 = vertex ( i, g );\n\t  //std::cout<<\"Selected \" << i << \" as \" << source << std::endl;\n      }\n      if(std::atoi(nameMap[i].c_str()) == destination) {\n\tv0 = vertex ( i, g );\n\t//std::cout<<\"Selected \" << i << \" as \" << destination << std::endl;\t\n      }\n  \n      //std::cout<<\"Original: \" << i << \", \" << nameMap[i] << std::endl;\n    }\n\n    // set names and weights\n    //SetNames(g, nameMap);\n    SetWeights ( g, distanceMap, 1.0f );\n    //PrintGraphProperties(g, nameMap, distanceMap);\n\n      // floyd warshall\n    //std::vector< std::pair<int, float> > centralities = GetCentralities ( g, nameMap, indexMap );\n\n\n    \n    // dijkstra\n    boost::dijkstra_shortest_paths ( g, v0, boost::distance_map ( distanceMap ).predecessor_map ( predecessorMap ) );\n    //std::cout<<\"S start...\" << std::endl;\n\n    \n    std::string shortest_path = \"\";\n    int path_steps = 0;\n\tVertex v = v3; // We want to start at the destination and work our way back to the source\n\tfor ( Vertex u = predecessorMap[v];  u != v; v = u, u = predecessorMap[v] ) {\n\t\tstd::ostringstream ss;\n\t\tss << v;\n\t\tshortest_path += \";\" + ss.str();\n\t\tpath_steps++;\n\t}\n\t\n      // khepera name hack\n      for(int i = original_names.size() - 1; i >= 0 ; i--){\n\tstringstream first, second;\n\tfirst << original_names[i].first;\n\tsecond << original_names[i].second;     \n\t//std::cout<<\"Replacing: \" << first.str() << \" with \" << second.str() << \", \" << shortest_path << std::endl;\n\tboost::replace_all(shortest_path, first.str(), second.str());\n      }\n\n      std::ostringstream ss;\n      ss << destination;\n      shortest_path += \";\" + ss.str();\n      ss.str(\"\");\n      ss.clear();\n      ss << path_steps;\n      shortest_path = ss.str() + shortest_path;\n\n    return shortest_path;\n}\n\n\n", "meta": {"hexsha": "cbefe96403f722296cf0fccb3e580e31aad8c138", "size": 33309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BoostGraphCentrality/GraphOperations.cpp", "max_stars_repo_name": "isvogor-foi/BuzzExt", "max_stars_repo_head_hexsha": "1008901029fd32d666d9eaad1cfbbd1cabe610eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BoostGraphCentrality/GraphOperations.cpp", "max_issues_repo_name": "isvogor-foi/BuzzExt", "max_issues_repo_head_hexsha": "1008901029fd32d666d9eaad1cfbbd1cabe610eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BoostGraphCentrality/GraphOperations.cpp", "max_forks_repo_name": "isvogor-foi/BuzzExt", "max_forks_repo_head_hexsha": "1008901029fd32d666d9eaad1cfbbd1cabe610eb", "max_forks_repo_licenses": ["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.1731784583, "max_line_length": 202, "alphanum_fraction": 0.6071932511, "num_tokens": 8524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2018132126589859, "lm_q2_score": 0.04146227182308095, "lm_q1q2_score": 0.008367634280756115}}
{"text": "#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <string>\n#include <vector>\n#include <Eigen/Geometry>\n#include \"mpi.h\"\n\n//for creating folders\n#include <sys/types.h> // required for stat.h\n#include <sys/stat.h>\t//required to create a folder\n\n#include \"General_Utilities.hpp\"\n#include \"Physical_Parameters.hpp\"\n#include \"ER_General.hpp\"\n#include \"ER_CRESSTII.hpp\"\n#include \"ER_LUX.hpp\"\n\nusing namespace std;\nusing namespace std::chrono;\n\n\n\nint main(int argc, char *argv[])\n{\t\n\t\n//INITIALIZATION \t\n////////////////////////////////////////////////////////////\n\t//Read config file created by the simulation code. argv is the SimID\n\t\tstd::string id(argv[1]);\n\t\tstd::string path = \"../data/\"+id+\".cfg\";\n\t\tRead_Config_File(path.c_str());\n\t//MPI Enviroment\n\t\t// Initialize the MPI environment\n\t    \tMPI_Init(NULL, NULL);\n\t    // Get the number of processes\n\t    \tint numprocs;\n\t    \tMPI_Comm_size(MPI_COMM_WORLD, &numprocs);\n\t    // Get the ID number of the process\n\t    \tint myRank;\n\t    \tMPI_Comm_rank(MPI_COMM_WORLD, &myRank);\n\n\t//Starting time\n\t    high_resolution_clock::time_point tStart,tEnd;\n\t    if(myRank==0)\n\t    {\n\t    \ttStart = high_resolution_clock::now();\n\t    }\n\n\t//Divide the isodetection rings between the processes.\n    \tstd::vector<int> iList = WorkDivision(numprocs,Isodetection_Rings);\n\t \tMPI_Barrier(MPI_COMM_WORLD);\n\t \tif(myRank==0&&numprocs>Isodetection_Rings)\n\t \t{\n\t \t\tcout <<\"Warning: More MPI processes than isodetection rings. \" <<numprocs-Isodetection_Rings <<\" have nothing to do.\" <<endl;\n\t \t}\n\t\n\t//Create folder for histograms DaMaSCUS/results/SimID_histograms\n\t\tif(myRank==0)\n\t\t{\n\t\t\tstd::chrono::time_point<std::chrono::system_clock> start;\n\t\t\tstart = std::chrono::system_clock::now();\n\t\t\tstd::time_t start_time = std::chrono::system_clock::to_time_t(start);\n\t\t\tcout <<\"\\n##############################\"<<endl\n\t\t\t<<\"DaMaSCUS\"<<version<<\" - Data Analysis\"<<endl<<endl\n\t\t\t<<\"Starting Time:\\t\" <<std::ctime(&start_time)\n\t\t\t<<\"Simulation ID:\\t\" <<SimID <<endl\n\t\t\t<<\"Experiment:\\t\" <<experiment <<endl<<endl;\n\t\t\tcout <<\"Creating folder for histograms.\"<<endl;\n\t\t\tstd::string sPath = \"../results/\"+SimID+\"_histograms\";\n\t\t\tmode_t nMode = 0733; // UNIX style permissions\n\t\t\tint nError = 0;\n\t\t\t#if defined(_WIN32)\n\t\t\t\tnError = _mkdir(sPath.c_str()); // can be used on Windows\n\t\t\t#else \n\t\t\t  nError = mkdir(sPath.c_str(),nMode); // can be used on non-Windows\n\t\t\t#endif\n\t\t\tif (nError != 0) \n\t\t\t{\n\t\t\t  cout <<\"Folder already exists, existing data will be overwritten.\" <<endl<<endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout <<\"Done.\" <<endl<<endl;\n\t\t\t}\n\t\t}\n\t//Temporary binary output files, which will be translated to ascii at the end.\n\t\tif(myRank==0)cout <<\"Creating temporary files.\"<<endl;\n\t\tMPI_Offset offset;\n \t\tMPI_File   file_speed;\n \t\tMPI_File   file_rate;\n \t  \tMPI_Status status;\n \t  \t//Speed output\n\t\t \tstring SpeedFilename=\"../results/\"+SimID+\".speedTemp\";\n\t\t \tint test=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(SpeedFilename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_speed);\n\t\t    //if it already exists, it will be overwritten!\n\t\t\tif(test != MPI_SUCCESS)\n\t\t\t{\n\t  \t\t\tif (myRank == 0) MPI_File_delete(const_cast<char*>(SpeedFilename.c_str()),MPI_INFO_NULL);\n\t  \t\t\t//MPI_Barrier(MPI_COMM_WORLD);\n\t\t  \t\ttest=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(SpeedFilename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_speed);\n\t\t  \t}\n\t\t  \t//Offset for (ring,vMean,vError)\n\t   \t\toffset = iList[myRank] * 3 * sizeof(double);\n\t  \t\tMPI_File_seek(file_speed, offset,MPI_SEEK_SET);\n\t  \t//Event rate output\n\t  \t\tstring RateFilename=\"../results/\"+SimID+\".rateTemp\";\n\t \t\ttest=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(RateFilename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_rate);\n\t\t   \t//if it already exists, it will be overwritten!\n\t\t\t\tif(test != MPI_SUCCESS)\n\t\t\t\t{\n\t\t \t\t\t\tif (myRank == 0) MPI_File_delete(const_cast<char*>(RateFilename.c_str()),MPI_INFO_NULL);\n\t\t  \t\t\ttest=MPI_File_open(MPI_COMM_WORLD,const_cast<char*>(RateFilename.c_str()),MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_WRONLY,MPI_INFO_NULL, &file_rate);\n\t\t  \t\t}\n\t\t \t\t//Offset for (ring,rate,error,analytic rate)\n\t   \t\t\toffset = iList[myRank] * 4 * sizeof(double);\n\t  \t\t\tMPI_File_seek(file_rate, offset,MPI_SEEK_SET);  \t\n\t\n\t//Synchronize processes:\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\n////////////////////////////////////////////////////////////\n\t\t//DM Density\t\n \t\t//The master reads and copies the rho file from the /data directory. Afterwards he shares the vector with everyone.\n\t\t\tstd::vector<std::vector<double>> rho(Isodetection_Rings, vector<double>(2));\n\t\t\tif(myRank==0)\n\t\t\t{\n\t\t\t\tcout <<\"Reading in local DM densities.\"<<endl;\n\t\t\t\tifstream f2;\n\t\t\t\tofstream copy;\n\t\t\t\tf2.open(\"../data/\"+SimID+\".rho\");\n\t\t\t\tcopy.open(\"../results/\"+SimID+\".rho\");\n\t\t\t\tif(f2.is_open())\n\t\t\t\t{\n\t\t\t\t\tfor(int i =0;i<Isodetection_Rings;i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint ring;\n\t\t\t\t\t\tdouble b1,b2;\n\t\t\t\t\t\tf2 >> ring;\n\t\t\t\t\t\tf2 >> b1;\n\t\t\t\t\t\tf2 >> b2;\n\t\t\t\t\t\tcopy <<ring <<\"\\t\" <<b1 <<\"\\t\" <<b2 <<endl;\n\t\t\t\t\t\trho[i][0]=b1*GeV/cm/cm/cm;\n\t\t\t\t\t\trho[i][1]=b2*GeV/cm/cm/cm;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcout <<SimID+\".rho does not exist.\"<<endl;\n\t\t\t\t}\n\t\t\t\tf2.close();\n\t\t\t\tcopy.close();\n\t\t\t}\n\t\t\t//Broadcast the rho vector\n\t\t\tif(myRank==0) cout <<\"Broadcast local DM densities to all MPI processes.\" <<endl;\n\t\t\t\tfor(int k=0;k<Isodetection_Rings;k++)\n\t\t\t\t{\n\t\t\t\t\tMPI_Bcast(&rho[k].front(),2,MPI_DOUBLE,0,MPI_COMM_WORLD);\n\t\t\t\t}\n\t\t\t\n\n\n\t//Go through the files and analyze isodetection ring by ring.\n\t\tif(myRank==0) \n\t\t{\n\t\t\tcout <<\"Start data analysis...\" <<endl<<endl\n\t\t\t<<\"MPI rank\\tIsodetection ring\\tLocal Progress\\tComputing time[s]\\tResidual time estimate[s]\"<<endl;\n\t\t}\n\t\t\t\n\t\tdouble R_A; //the analytic result for the event rate must only be computed once.\n\t\tdouble durationMean=0.0; //for the estimation of the residual time\n\t\tfor(int i=iList[myRank];i<iList[myRank+1];i++)\n\t\t{\n\t\t\t//Beginning time of this isodetection ring\n\t\t\t\thigh_resolution_clock::time_point tIRstart;\n\t\t\t\ttIRstart = high_resolution_clock::now();\n\t\t\t\n\t\t\t//Open Files\n\t\t\t\tMPI_File VelocityFile,WeightFile;\n\t\t\t\tMPI_Status status;\n\t\t\t\tstring VelocityFilename=\"../data/\"+SimID+\"_data/velocity.\"+std::to_string(i);\n\t\t\t\tstring WeightFilename=\"../data/\"+SimID+\"_data/weights.\"+std::to_string(i);\n\t\t\t\tint rc = MPI_File_open(MPI_COMM_SELF, const_cast<char*>(VelocityFilename.c_str()), MPI_MODE_RDONLY, MPI_INFO_NULL, &VelocityFile );\n\t\t\t\tif (rc) cout <<\"Unable to read file \" <<VelocityFilename <<\".\"<<endl;\n\t\t\t\trc = MPI_File_open(MPI_COMM_SELF, const_cast<char*>(WeightFilename.c_str()), MPI_MODE_RDONLY, MPI_INFO_NULL, &WeightFile );\n\t\t\t\tif (rc) cout <<\"Unable to read file \" <<WeightFilename <<\".\"<<endl;\n\n\t\t\t//First we calculate the histogram domain, the weighted speed average, variance and standard error. \n\t\t\t\tstd::vector<double> AverageSpeed;\n\t\t\t\t//1. Compute the weighted average speed and find the maximum speed in the sample, which defines our histogram's domain. \n\t\t\t\t\tdouble vMax = 0.0;\n\t\t\t\t\tdouble vMin=0.0;\n\t\t\t\t\tdouble WeightSum=0.0;\n\t\t\t\t\tdouble SpeedSum=0.0;\n\t\t\t\t\tfor(int j=0;j<SampleSize;j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tEigen::Vector3d v;\n\t\t\t\t\t\tMPI_File_read(VelocityFile,v.data(),v.size(),MPI_DOUBLE,&status);\n\t\t\t\t\t\tdouble speed=v.norm();\n\t\t\t\t\t\tif(speed>vMax)\t\t\tvMax=speed;\n\t\t\t\t\t\t//Compute weighted mean speed;\n\t\t\t\t\t\t\tdouble weight;\n\t\t\t\t\t\t\tMPI_File_read(WeightFile,&weight,1,MPI_DOUBLE,&status);\n\t\t\t\t\t\t\tWeightSum+=weight;\n\t\t\t\t\t\t\tSpeedSum+=speed*weight;\n\t\t\t\t\t}\n\t\t\t\t\tdouble MeanSpeed=SpeedSum/WeightSum;\n\t\t\t\t\n\t\t\t\t//2. Now we can compute the variance for Scott's rule, as well as the standard error (not deviation!) of the Mean Velocity with Cochran formula\n\t\t\t\t\tdouble SpeedVariance=0.0;\n\t\t\t\t\tdouble MeanWeight=WeightSum/SampleSize;\n\t\t\t\t\tdouble sum1=0.0;\n\t\t\t\t\tdouble sum2=0.0;\n\t\t\t\t\tdouble sum3=0.0;\n\t\t\t\t\t//Jump back to the top of file \n\t\t\t\t\t\tMPI_File_seek(VelocityFile, 0,MPI_SEEK_SET);\n\t\t\t\t\t\tMPI_File_seek(WeightFile,0,MPI_SEEK_SET);\n\t\t\t\t\tfor(int j=0;j<SampleSize;j++)\n\t\t\t\t\t{\n\t\t\t\t\t\t//Read in velocity and data weight\n\t\t\t\t\t\t\tEigen::Vector3d v;\n\t\t\t\t\t\t\tdouble weight;\n\t\t\t\t\t\t\tMPI_File_read(VelocityFile,v.data(),v.size(),MPI_DOUBLE,&status);\n\t\t\t\t\t\t\tMPI_File_read(WeightFile,&weight,1,MPI_DOUBLE,&status);\n\t\t\t\t\t\t\tdouble speed=v.norm();\t\t\t\t\t\n\t\t\t\t\t\t//Compute variance of the sample;\n\t\t\t\t\t\t\tSpeedVariance+=weight*pow(speed-MeanSpeed,2.0)/WeightSum;\n\t\t\t\t\t\t//Standard Error\n\t\t\t\t\t\t\tsum1+=pow(weight*speed-MeanWeight*MeanSpeed,2.0);\n\t\t\t\t\t\t\tsum2+=(weight-MeanWeight)*(weight*speed-MeanWeight*MeanSpeed);\n\t\t\t\t\t\t\tsum3+=pow(weight-MeanWeight,2.0);\n\t\t\t\t\t}\n\t\t\t\t\tdouble StandardError = sqrt(SampleSize/(SampleSize-1)/pow(WeightSum,2.0)*(sum1-2.0*MeanSpeed*sum2+pow(MeanSpeed,2.0)*sum3));\n\t\t\t\t\t//Save the average speed and standard error into a file\n\t\t\t\t\t\tAverageSpeed.push_back(i);\n\t\t\t\t\t\tAverageSpeed.push_back(MeanSpeed);\n\t\t\t\t\t\tAverageSpeed.push_back(StandardError);\n\t\t\t\t\t\tMPI_File_write(file_speed,AverageSpeed.data(),AverageSpeed.size(),MPI_DOUBLE,&status);\n\t\t\t\t//3. Use Scott's rule for the bin width\n\t\t\t\t\tdouble h = 3.5*sqrt(SpeedVariance)/pow(SampleSize,1.0/3.0);\n\t\t\t\t\tdouble bins = ceil((vMax-vMin)/h);\n\t\t\t\n\t\t\t//Create Histogram including errors\n\t\t\t\tvector< vector<double> > VelocityHistogram (bins, vector<double>(4));\n\t\t\t\tfor(int j =0;j<bins;j++)\n\t\t\t\t{\n\t\t\t\t\tVelocityHistogram[j][0]=vMin+j*h+h/2.0;\t//x coordinate / bin position\n\t\t\t\t\tVelocityHistogram[j][1]=0.0;\t\t\t//y coordinate / bin height\n\t\t\t\t\tVelocityHistogram[j][2]=h/2.0;\t\t\t//error on x \n\t\t\t\t\tVelocityHistogram[j][3]=0.0;\t\t\t//error on y\n\t\t\t\t} \n\t\t\t\t//Jump back to the top of file \n\t\t\t\t\tMPI_File_seek(VelocityFile, 0,MPI_SEEK_SET);\n\t\t\t\t\tMPI_File_seek(WeightFile,0,MPI_SEEK_SET);\n\t\t\t\tfor(int j=0;j<SampleSize;j++)\n\t\t\t\t{\n\t\t\t\t\tEigen::Vector3d v;\n\t\t\t\t\tdouble weight;\n\t\t\t\t\tint bin;\n\t\t\t\t\tMPI_File_read(VelocityFile,v.data(),v.size(),MPI_DOUBLE,&status);\n\t\t\t\t\tMPI_File_read(WeightFile,&weight,1,MPI_DOUBLE,&status);\n\t\t\t\t\tbin=(v.norm()-vMin)/h;\n\t\t\t\t\tVelocityHistogram[bin][1]+=weight;\n\t\t\t\t\tVelocityHistogram[bin][3]+=weight*weight;\n\t\t\t\t\t// WeightSum+=weight;\n\t\t\t\t\t// VelocitySum+=v.norm()*weight;\n\t\t\t\t}\n\t\t\t\t//Normalize the histogram and the average, and the errors\n\t\t\t\t\tfor (int j=0;j<bins;j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tVelocityHistogram[j][1]/=h*WeightSum;\n\t\t\t\t\t\tVelocityHistogram[j][3]/=h*h*WeightSum*WeightSum;\n\t\t\t\t\t\tVelocityHistogram[j][3]=sqrt(VelocityHistogram[j][3]);\n\t\t\t\t\t} \t\t\t\n\n\t\t\t//Close Files\n\t\t\t\tMPI_File_close( &VelocityFile );\n\t\t\t\tMPI_File_close( &WeightFile );\n\t\t\t//Save velocity histogram\n\t\t\t\tofstream f;\n\t\t\t\tf.open(\"../results/\"+SimID+\"_histograms/speed.\"+std::to_string(i));\n\t\t\t\tfor(int j=0;j<bins;j++) f<<VelocityHistogram[j][0] <<\"\\t\" <<VelocityHistogram[j][1] <<\"\\t\" <<VelocityHistogram[j][2]<<\"\\t\" <<VelocityHistogram[j][3] <<endl;\n\t\t\t\tf.close();\n\t\t\t//Create and save eta-Histogram\n\t\t\t\tstd::vector<std::vector<double>> etaH = EtaHistogram(VelocityHistogram);\n\t\t\t\tf.open(\"../results/\"+SimID+\"_histograms/eta.\"+std::to_string(i));\n\t\t\t\tfor(unsigned int j=0;j<etaH.size();j++) f<<etaH[j][0] <<\"\\t\"<<etaH[j][1] <<\"\\t\"<<etaH[j][2] <<\"\\t\"<<etaH[j][3]<<endl;\n\t\t\t\tf.close();\n\t\t\t//Calculate the event rate.\n\t\t\t\tstd::vector<double> TotalRate;\n\t\t\t\tif(experiment==\"CRESST-II\")\n\t\t\t\t{\n\t\t\t\t\t//Create Recoil Spectrum Histograms\n\t\t\t\t\t\tstd::vector<std::vector<double>> dRdEH_O = dRdEHistogram(0.22,16,rho[i],mChi,sigma0,etaH);\n\t\t\t\t\t\tstd::vector<std::vector<double>> dRdEH_Ca = dRdEHistogram(0.14,40,rho[i],mChi,sigma0,etaH);\n\t\t\t\t\t\tstd::vector<std::vector<double>> dRdEH_W = dRdEHistogram(0.64,184,rho[i],mChi,sigma0,etaH);\n\t\t\t\t\t //Save dRdE histograms for CRESST-II\t\n\t\t\t\t\t\tf.open(\"../results/\"+SimID+\"_histograms/dRdE.\"+std::to_string(i));\n\t\t\t\t\t\t//Emin and Emax for the histogram\n\t\t\t\t\t\t\tdouble Emin=0.3*keV;\n\t\t\t\t\t\t\tstd::vector<double> EmaxV;\n\t\t\t\t\t\t\tEmaxV.push_back(dRdEH_O.back()[0]+3.0*62*eV);\n\t\t\t\t\t\t\tEmaxV.push_back(dRdEH_Ca.back()[0]+3.0*62*eV);\n\t\t\t\t\t\t\tEmaxV.push_back(dRdEH_W.back()[0]+3.0*62*eV);\n\t\t\t\t\t\t\tdouble Emax = *std::max_element( EmaxV.begin(), EmaxV.end() );\t\n\t\t\t\t\t\t\t//For very low signal rates we only save the first low 0.1keV of the spectrum.\n\t\t\t\t\t\t\tif(Emax<0.4*keV) Emax=0.4*keV;\n\t\t\t\t\t\tdouble dE=(Emax-Emin)/100.;\n\t\t\t\t\t\t//Below 0.3keV the efficiency is assumed to zero. 0.3 keV is the threshold\n\t\t\t\t\t\tfor(double E=0.3*keV;E<=Emax;E+=dE)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::vector<double> dR = dRdE_CRESSTII_MC(E,dRdEH_O,dRdEH_Ca,dRdEH_W,vEarth.norm());\n\t\t\t\t\t\t\tf <<E <<\"\\t\" <<dR[0] <<\"\\t\" <<dE/2.0<<\"\\t\" <<dR[1] <<\"\\t\" <<dRdE_CRESSTII_A(E,rhoDM,mChi,sigma0,vEarth.norm()) <<endl; \n\t\t\t\t\t\t}\n\t\t\t\t\t\tf.close();\n\t\t\t\t\t//Calculate Total event rate\n\t\t\t\t\t\t//Compute the analytic result at the first iteration\n\t\t\t\t\t\t\tif(i==iList[myRank])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tR_A = R_CRESSTII_A(rhoDM,mChi,sigma0,vEarth.norm());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t//Compute result for MC\n\t\t\t\t\t\t\tstd::vector<double> R_MC = R_CRESSTII_MC(dRdEH_O,dRdEH_Ca,dRdEH_W,mChi,vEarth.norm());;\n\t\t\t\t\t\t\t// cout <<\"MPI Process:\\t\" <<myRank <<\"\\t IsoRing:\\t\" <<i<<\"\\tR = \"<<R_MC[0] <<\"+-\"<<R_MC[1] <<\"\\t(\"<<R_A<<\")\"<<endl;\n\t\t\t\t\t//Save rate including the analytic result for the transparent earth\n\t\t\t\t\t\tTotalRate.push_back(i);\n\t\t\t\t\t\tTotalRate.push_back(R_MC[0]);\n\t\t\t\t\t\tTotalRate.push_back(R_MC[1]);\n\t\t\t\t\t\tTotalRate.push_back(R_A);\n\t\t\t\t\t\tMPI_File_write(file_rate,TotalRate.data(),TotalRate.size(),MPI_DOUBLE,&status);\n\n\t\t\t\t}\n\t\t\t\telse if(experiment==\"LUX\")\n\t\t\t\t{\n\t\t\t\t\t//Create and save dRdE-Histogram\n\t\t\t\t\t\tstd::vector<std::vector<double>> dRdEH = dRdEHistogram(1,131,rho[i],mChi,sigma0,etaH);\n\t\t\t\t\t\tf.open(\"../results/\"+SimID+\"_histograms/dRdE.\"+std::to_string(i));\n\t\t\t\t\t\tfor(unsigned int j=0;j<dRdEH.size();j++) f<<dRdEH[j][0] <<\"\\t\"<<dRdEH[j][1] <<\"\\t\"<<dRdEH[j][2] <<\"\\t\"<<dRdEH[j][3]<<\"\\t\"<<dRdErA(dRdEH[j][0],1,131,rhoDM,mChi,sigma0,vEarth.norm())<<endl;\n\t\t\t\t\t\tf.close();\n\t\t\t\t\t//Calculate Total event rate\n\t\t\t\t\t\t//Compute the analytic result at the first iteration\n\t\t\t\t\t\t\tif(i==iList[myRank]) R_A = R_LUX_A(rhoDM,mChi,sigma0,vEarth.norm());\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t//Compute the MC result\n\t\t\t\t\t\t\tstd::vector<double> R_MC = R_LUX_MC(dRdEH);\n\n\t\t\t\t\t//Save rate including the analytic result for the transparent earth\n\t\t\t\t\t\tTotalRate.push_back(i);\n\t\t\t\t\t\tTotalRate.push_back(R_MC[0]);\n\t\t\t\t\t\tTotalRate.push_back(R_MC[1]);\n\t\t\t\t\t\tTotalRate.push_back(R_A);\n\t\t\t\t\t\tMPI_File_write(file_rate,TotalRate.data(),TotalRate.size(),MPI_DOUBLE,&status);\n\t\t\t\t}\n\t\t\t\telse if(experiment!=\"None\")\n\t\t\t\t{\n\t\t\t\t\tif(myRank==0) cout <<\"Error: Experiment not recognized. No detection rate will be computed.\" <<endl;\n\t\t\t\t\texperiment=\"None\";\n\t\t\t\t}\n\t\t\t\t//Console output to give an indication of the progress\n\t\t\t\t\t//computing time of this isodetection ring\n\t\t\t\t\t\thigh_resolution_clock::time_point tIRend;\n\t\t\t\t\t\ttIRend = high_resolution_clock::now();\n\t\t\t\t\t\tdouble durationIR =1e-6*duration_cast<microseconds>( tIRend - tIRstart ).count();\n\t\t\t\t\t//Mean computing time of all finished isodetection rings so far. This will be used to make the prognosis.\n\t\t\t\t\t\tdurationMean=1.0*(i-iList[myRank])/(i-iList[myRank]+1)*durationMean+1.0*durationIR/(i-iList[myRank]+1);\n\t\t\t\t\t\n\t\t\t\t\tcout <<myRank<<\"\\t\\t\" <<i<<\"\\t\\t\\t\" <<floor(100.0*(i-iList[myRank]+1)/(iList[myRank+1]-iList[myRank]))<<\"\\%\\t\\t\"<<ceil(durationIR)<<\"\\t\\t\\t\"<<ceil((iList[myRank+1]-i-1)*durationMean)<<endl;\t\n\t\t\t\t\n\n\t\t}\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\tif(myRank==0) cout <<\"\\nData analysis complete.\" <<endl;\n\t\tMPI_File_close(&file_speed);\n\t\tMPI_File_close(&file_rate);\n\t\t\n\t\t\n\n\t//Create ASCII Output\n\t\tif(myRank==0)\n\t\t{\n\t\t\tcout <<\"Creating ASCII output.\" <<endl;\n\t\t\t//Binary Input files\n\t\t\t//Speed\n\t\t\t\tMPI_File speedfile;\n\t\t\t\tint rc = MPI_File_open(MPI_COMM_SELF, const_cast<char*>(SpeedFilename.c_str()), MPI_MODE_RDONLY, MPI_INFO_NULL, &speedfile );\n\t\t\t\tif (rc) cout <<\"Unable to read file \" <<SpeedFilename <<\".\"<<endl;\n\t\t\t\t//ASCII Output files\n\t\t\t\t\tofstream f;\n\t\t\t\t\tf.open(\"../results/\"+SimID+\".speed\");\n\t\t\t\t//Write results in ascii files.\n\t\t\t\t\tfor(int ring=0;ring<Isodetection_Rings;ring++)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::vector<double> speedbuffer (3);\n\t\t\t\t\t\tMPI_File_read(speedfile,speedbuffer.data(),speedbuffer.size(),MPI_DOUBLE,&status);\n\t\t\t\t\t\tf <<180.0 / Isodetection_Rings * ring <<\"\\t\" <<speedbuffer[1]<<\"\\t\"<<speedbuffer[2]<<endl;\n\t\t\t\t\t}\n\t\t\t\t//Close file\n\t\t\t\t\tf.close();\n\t\t\t\t\tMPI_File_close(&speedfile);\n\t\t\t//Rate\n\t\t\t\tif(experiment!=\"None\")\n\t\t\t\t{\n\t\t\t\t\tMPI_File ratefile;\n\t\t\t\t\trc = MPI_File_open(MPI_COMM_SELF, const_cast<char*>(RateFilename.c_str()), MPI_MODE_RDONLY, MPI_INFO_NULL, &ratefile );\n\t\t\t\t\tif (rc) cout <<\"Unable to read file \" <<RateFilename <<\".\"<<endl;\n\t\t\t\t\t//ASCII Output files\n\t\t\t\t\t\tofstream g;\n\t\t\t\t\t\tg.open(\"../results/\"+SimID+\".\"+experiment);\n\t\t\t\t\t//Write results in ascii files.\n\t\t\t\t\t\tfor(int ring=0;ring<Isodetection_Rings;ring++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::vector<double> ratebuffer (4);\n\t\t\t\t\t\t\tMPI_File_read(ratefile,ratebuffer.data(),ratebuffer.size(),MPI_DOUBLE,&status);\n\t\t\t\t\t\t\tg <<180.0 / Isodetection_Rings * ring <<\"\\t\" <<ratebuffer[1]<<\"\\t\"<<ratebuffer[2]<<\"\\t\"<<ratebuffer[3]<<endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t//Close files\n\t\t\t\t\t\tg.close();\n\t\t\t\t\t\tMPI_File_close(&ratefile);\n\t\t\t\t}\n\t\t}\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\t\n\t\t\n\t\n//FINALIZE\n\t//Master process finishes logfile\n\t\tif(myRank==0)\n\t\t{\n\t\t\t//Delete temporary files\n\t\t\t\tcout <<\"Delete temporary files and finish.\" <<endl;\n\t\t\t\tMPI_File_delete(const_cast<char*>(SpeedFilename.c_str()),MPI_INFO_NULL);\n\t\t\t\tMPI_File_delete(const_cast<char*>(RateFilename.c_str()),MPI_INFO_NULL);\n\t\t\t//Ending time and computing time\n\t\t\t\ttEnd = high_resolution_clock::now();\n\t\t\t\tdouble durationTotal =1e-6*duration_cast<microseconds>( tEnd - tStart ).count();\n\t\t\t\tcout <<\"\\nProcessing Time:\\t\"<< durationTotal<<\"s (\"<< floor(durationTotal/3600.0)<<\":\"<<floor(fmod(durationTotal/60.0,60.0))<<\":\"<<floor(fmod(durationTotal,60.0))<<\":\"<<floor(fmod(1000*durationTotal,1000.0))<<\").\"<<endl\n\t\t\t\t<<\"##############################\"<<endl;\n\t\t\t//LogFile\n\t\t\t\tLogFile_Analysis(durationTotal,numprocs);\n\t\t\t\t\n\t\t}\t\n\t// Finalize the MPI environment.\n\t    MPI_Finalize();\n   \n\treturn 0;\n}\n\n\n", "meta": {"hexsha": "60315ca65020f2d4c87d423f5d37e686ffc3011e", "size": 17789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis/main.cpp", "max_stars_repo_name": "temken/DaMaSCUS", "max_stars_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-13T13:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T19:35:12.000Z", "max_issues_repo_path": "src/analysis/main.cpp", "max_issues_repo_name": "temken/DaMaSCUS", "max_issues_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-06-06T14:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:01:56.000Z", "max_forks_repo_path": "src/analysis/main.cpp", "max_forks_repo_name": "temken/DaMaSCUS", "max_forks_repo_head_hexsha": "14be6907230e5ef1b93809a6fb5842330497a7a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-09T09:48:10.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-09T09:48:10.000Z", "avg_line_length": 39.6191536748, "max_line_length": 224, "alphanum_fraction": 0.6480971387, "num_tokens": 5256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.018264274511027485, "lm_q1q2_score": 0.008349270485207201}}
{"text": "/*\n*\nCOPYRIGHT AND LICENSE\n\nCopyright (c) 2011 The Regents of the University of California.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or\nwithout modification, are permitted provided that the following\nconditions are met:\n\n1. Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following\ndisclaimer in the documentation and/or other materials provided\nwith the distribution.\n\n3. All advertising materials mentioning features or use of this\nsoftware must display the following acknowledgement: This product\nincludes software developed by the San Diego Supercomputer Center.\n\n4. Neither the names of the Centers nor the names of the contributors\nmay be used to endorse or promote products derived from this\nsoftware without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS\nOR 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\nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\nAND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\nANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n*\n*\n* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)\n* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)\n*\n*/\n\n#include <points2grid/config.h>\n#include <points2grid/Interpolation.hpp>\n#include <points2grid/Global.hpp>\n\n#include <points2grid/OutCoreInterp.hpp>\n#include <points2grid/InCoreInterp.hpp>\n#include <points2grid/MpiInterp.hpp>\n\n#include <string.h>\n#include <math.h>\n#include <float.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <time.h>\n#include <stdio.h>\n#include <assert.h>\n\n#include <points2grid/lasfile.hpp>\n#include <points2grid/debug.hpp>\n\n#include <boost/scoped_ptr.hpp>\n\n\n#include <fstream>  // std::ifstream\n#include <iostream> // std::cerr\n#include <string.h>\n\n#include \"mpi.h\"\n#include \"signal.h\"\n\n/////////////////////////////////////////////////////////////\n// Public Methods\n/////////////////////////////////////////////////////////////\n\nInterpolation::Interpolation(double x_dist, double y_dist, double radius,\n                             int _window_size, int _interpolation_mode = INTERP_AUTO,\n                             int _rank = 0, int _process_count = 1, int _reader_count = 1, long _buffer_size = 10000, mpi_times *_timer = NULL) : GRID_DIST_X (x_dist), GRID_DIST_Y(y_dist)\n{\n    rank = _rank;\n    process_count = _process_count;\n    reader_count = _reader_count;\n    buffer_size = _buffer_size;\n    timer = _timer;\n\n    radius_sqr = radius * radius;\n    window_size = _window_size;\n    interpolation_mode = _interpolation_mode;\n    input_files = NULL;\n    input_file_count = 0;\n\n\n    min_x = DBL_MAX;\n    min_y = DBL_MAX;\n\n    max_x = -DBL_MAX;\n    max_y = -DBL_MAX;\n\n    shapes = NULL;\n    shape_count = 0;\n\n}\n\nInterpolation::~Interpolation()\n{\n    delete interp;\n}\n\nint Interpolation::init(char **inputNames, int inputNamesSize, int inputFormat, int bigtiff, int epsg_code, double *bbox,\n                        int *_classifications, int _classification_count, int _first_returns, int _last_returns, SHPHandle _shape_filter, int _fill_empty)\n{\n\n    clock_t t0, t1;\n\n    t0 = clock();\n\n    char *inputName = inputNames[0];\n    classifications = _classifications;\n    classification_count = _classification_count;\n    first_returns = _first_returns;\n    last_returns = _last_returns;\n    shape_filter = _shape_filter;\n    fill_empty = _fill_empty;\n\n\n\n    if(inputName == NULL)\n    {\n        cerr << \"Wrong Input File Name\" << endl;\n        return -1;\n    }\n\n    if (interpolation_mode != INTERP_MPI)\n    {\n        // Only the first file is used for non mpi runs, set input_files[0].name is needed during interpolation\n        // set it now...\n        input_files = (input_file_info *) malloc (sizeof(input_file_info));\n        input_file_count = 1;\n        input_files[0].name = (char *) malloc ((strlen(inputNames[0]) + 1) * sizeof(char));\n        strcpy (input_files[0].name, inputNames[0]);\n\n        if (inputFormat == INPUT_ASCII)\n        {\n            FILE *fp;\n            char line[1024];\n            double data_x, data_y;\n\n            if ((fp = fopen (inputName, \"r\")) == NULL)\n            {\n                cerr << \"file open error\" << endl;\n                return -1;\n            }\n\n            // throw the first line away - it contains the header\n            fgets (line, sizeof(line), fp);\n\n            // read the data points to find min and max values\n            while (fgets (line, sizeof(line), fp) != NULL)\n            {\n                data_x = atof (strtok (line, \",\\n\"));\n                if (min_x > data_x)\n                    min_x = data_x;\n                if (max_x < data_x)\n                    max_x = data_x;\n\n                data_y = atof (strtok (NULL, \",\\n\"));\n                if (min_y > data_y)\n                    min_y = data_y;\n                if (max_y < data_y)\n                    max_y = data_y;\n\n            }\n\n            fclose (fp);\n        }\n        else\n        { // las input\n\n            las_file las;\n            las.open (inputName);\n\n            min_x = las.minimums ()[0];\n            min_y = las.minimums ()[1];\n            max_x = las.maximums ()[0];\n            max_y = las.maximums ()[1];\n\n            las.close ();\n\n        }\n    }\n    else if (interpolation_mode == INTERP_MPI)\n    {\n        if (rank < reader_count)\n        {\n            input_files = (input_file_info *) malloc (\n                    inputNamesSize * sizeof(input_file_info));\n            input_file_count = inputNamesSize;\n            for (int i = 0; i < input_file_count; i++)\n            {\n                input_files[i].name = (char *) malloc (\n                        (strlen (inputNames[i]) + 1) * sizeof(char));\n                strcpy (input_files[i].name, inputNames[i]);\n\n                input_files[i].min_x = 0;\n                input_files[i].min_y = 0;\n                input_files[i].max_x = 0;\n                input_files[i].max_y = 0;\n                input_files[i].point_count = 0;\n                input_files[i].peek_rank = -1;\n            }\n\n            for (int i = 0; i < input_file_count; i++)\n            {\n                if (rank == i % reader_count)\n                {\n                    las_file las;\n                    las.open (input_files[i].name);\n                    input_files[i].min_x = las.minimums ()[0];\n                    input_files[i].min_y = las.minimums ()[1];\n                    input_files[i].max_x = las.maximums ()[0];\n                    input_files[i].max_y = las.maximums ()[1];\n                    input_files[i].point_count = las.points_count ();\n                    input_files[i].peek_rank = rank;\n                    las.close ();\n//                    printf(\"%s (%i of %i), point_count = %li\\n\", \n//                            input_files[i].name, i, input_file_count, \n//                            input_files[i].point_count);\n\n                }\n            }\n            for (int i = 0; i < input_file_count; i++)\n            {\n                if (input_files[i].peek_rank != -1)\n                {\n                    for (int j = 0; j < reader_count; j++)\n                    {\n                        if (rank != j)\n                        {\n\n                            MPI_Send (input_files[i].name, strlen(input_files[i].name)+1, MPI_CHAR, j, 1, MPI_COMM_WORLD);\n                            MPI_Send (&(input_files[i].min_x), 1, MPI_DOUBLE, j, 2, MPI_COMM_WORLD);\n                            MPI_Send (&(input_files[i].min_y), 1, MPI_DOUBLE, j, 3, MPI_COMM_WORLD);\n                            MPI_Send (&(input_files[i].max_x), 1, MPI_DOUBLE, j, 4, MPI_COMM_WORLD);\n                            MPI_Send (&(input_files[i].max_y), 1, MPI_DOUBLE, j, 5, MPI_COMM_WORLD);\n                            MPI_Send (&(input_files[i].point_count), 1, MPI_LONG, j, 6, MPI_COMM_WORLD);\n                            MPI_Send (&(input_files[i].peek_rank), 1, MPI_INT, j, 7, MPI_COMM_WORLD);\n                        }\n                    }\n\n                }\n            }\n\n            for (int i = 0; i < input_file_count; i++)\n            {\n                if (input_files[i].peek_rank == -1)\n                {\n                    MPI_Recv (input_files[i].name, strlen(input_files[i].name)+1, MPI_CHAR, i % reader_count, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n                    MPI_Recv (&(input_files[i].min_x), 1, MPI_DOUBLE, i % reader_count, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n                    MPI_Recv (&(input_files[i].min_y), 1, MPI_DOUBLE, i % reader_count, 3, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n                    MPI_Recv (&(input_files[i].max_x), 1, MPI_DOUBLE, i % reader_count, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n                    MPI_Recv (&(input_files[i].max_y), 1, MPI_DOUBLE, i % reader_count, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n                    MPI_Recv (&(input_files[i].point_count), 1, MPI_LONG, i % reader_count, 6, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n                    MPI_Recv (&(input_files[i].peek_rank), 1, MPI_INT, i % reader_count, 7, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n//                    printf(\"received %s (%i of %i)\\n\", input_files[i].name, \n//                            i, input_file_count);\n                }\n            }\n            min_x = min_y = DBL_MAX;\n            max_x = max_y = DBL_MIN;\n\n            for (int i = 0; i < input_file_count; i++)\n            {\n                if (input_files[i].min_x < min_x)\n                {\n                    min_x = input_files[i].min_x;\n                }\n                if (input_files[i].min_y < min_y)\n                {\n                    min_y = input_files[i].min_y;\n                }\n                if (input_files[i].max_x > max_x)\n                {\n                    max_x = input_files[i].max_x;\n                }\n                if (input_files[i].max_y > max_y)\n                {\n                    max_y = input_files[i].max_y;\n                }\n            }\n        }\n//        if (rank == 0) {\n//            printf(\"region = (%8.4f, %8.4f), (%8.4f, %8.4f)\\n\", \n//                    min_x, min_y, max_x, max_y);\n//        }\n    }\n\n    t1 = clock();\n\n    //////////////////////////////////////////////////////////////////////\n    // Intialization Step excluding min/max searching\n    //////////////////////////////////////////////////////////////////////\n\n    // send input file info collected above by the readers to the \n    // writers so all have it\n    if(rank == 0){\n        for(int i = reader_count; i < process_count; i++){\n            MPI_Send (&min_x, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD);\n            MPI_Send (&min_y, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD);\n            MPI_Send (&max_x, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD);\n            MPI_Send (&max_y, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD);\n        }\n    }\n    if(rank>=reader_count){\n        MPI_Recv(&min_x, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n        MPI_Recv(&min_y, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n        MPI_Recv(&max_x, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n        MPI_Recv(&max_y, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n    }\n\n    // assign min max values to bbox, return if there is no overlap\n    if (bbox != NULL)\n    {\n        if (rectangles_overlap (min_x, min_y, max_x, max_y, bbox[0], bbox[1],\n                                bbox[2], bbox[3]))\n        {\n            min_x = bbox[0];\n            min_y = bbox[1];\n            max_x = bbox[2];\n            max_y = bbox[3];\n        }\n        else\n        {\n            cerr << \"BBOX and LAS input data do not overlap\" << endl;\n            return -1;\n        }\n\n    }\n\n    // all processes set raster size\n    GRID_SIZE_X = (int)(ceil((max_x - min_x)/GRID_DIST_X)) + 1;\n    GRID_SIZE_Y = (int)(ceil((max_y - min_y)/GRID_DIST_Y)) + 1;\n\n    //dbg(3, (\"GRID_SIZE_x %i, grid_size y %i, rank %i\\n\", GRID_SIZE_X, GRID_SIZE_Y, rank);\n\n    // Construct an Interp based on the mode\n    if (interpolation_mode == INTERP_AUTO) {\n        // if the size is too big to fit in memory,\n        // then construct out-of-core structure\n        if(GRID_SIZE_X * GRID_SIZE_Y > MEM_LIMIT) {\n            interpolation_mode= INTERP_OUTCORE;\n        } else {\n            interpolation_mode = INTERP_INCORE;\n        }\n    }\n\n    if (interpolation_mode == INTERP_OUTCORE) {\n\n        // this is untested and remains for historical reasons\n        cerr << \"Using out of core interp code\" << endl;\n        interp = new OutCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);\n        if(interp == NULL)\n        {\n            cerr << \"OutCoreInterp construction error\" << endl;\n            return -1;\n        }\n        cerr << \"Interpolation uses out-of-core algorithm\" << endl;\n\n    } else if (interpolation_mode == INTERP_MPI){\n\n        interp = new MpiInterp(this, GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size, rank, process_count, reader_count, buffer_size, timer);\n\n    } else {\n\n        interp = new InCoreInterp(GRID_DIST_X, GRID_DIST_Y, GRID_SIZE_X, GRID_SIZE_Y, radius_sqr, min_x, max_x, min_y, max_y, window_size);\n\n    }\n\n    interp->set_bigtiff(bigtiff);\n    interp->set_epsg_code(epsg_code);\n    if(interp->init() < 0)\n    {\n        cerr << \"inter->init() error\" << endl;\n        return -1;\n    }\n\n    return 0;\n}\n\nint Interpolation::interpolation(char *outputName,\n                                 int inputFormat,\n                                 int outputFormat,\n                                 unsigned int outputType)\n{\n    if(timer)\n    {\n        if(rank == reader_count)printf(\"Readers sending points to writers...\\n\");\n        timer->interp_start = time(NULL);\n    }\n\n    int rc;\n\n    double data_x, data_y;\n    double data_z;\n    // This case is for historical preservation only, not used or tested\n    if (inputFormat == INPUT_ASCII && interpolation_mode != INTERP_MPI) {\n        FILE *fp;\n        char line[1024];\n\n        if((fp = fopen(input_files[0].name, \"r\")) == NULL)\n        {\n            printf(\"file open error\\n\");\n            return -1;\n        }\n\n        // throw the first line away - it contains the header\n        fgets(line, sizeof(line), fp);\n\n        // read every point and generate DEM\n        while(fgets(line, sizeof(line), fp) != NULL)\n        {\n            data_x = atof(strtok(line, \",\\n\"));\n            data_y = atof(strtok(NULL, \",\\n\"));\n            data_z = atof(strtok(NULL, \",\\n\"));\n\n            data_x -= min_x;\n            data_y -= min_y;\n\n            //if((rc = interp->update(arrX[i], arrY[i], arrZ[i])) < 0)\n            if((rc = interp->update(data_x, data_y, data_z)) < 0)\n            {\n                cerr << \"interp->update() error while processing \" << endl;\n                return -1;\n            }\n        }\n\n        fclose(fp);\n    } \n\n    else\n    { // input format is LAS\n        if (interpolation_mode == INTERP_MPI)\n        {\n            if (interp->getIsReader ())\n            {\n                if (input_file_count == 1) // Single input file\n                {\n                    if (rectangles_overlap (min_x, min_y, max_x, max_y,\n                                            input_files[0].min_x,\n                                            input_files[0].min_y,\n                                            input_files[0].max_x,\n                                            input_files[0].max_y))\n                    {\n                        las_file las;\n                        las.open (input_files[0].name);\n\n                        size_t count = las.points_count ();\n                        size_t index (0);\n                        size_t stride = count / interp->getReaderCount ();\n                        size_t left_over_count = count\n                                % interp->getReaderCount ();\n                        index = rank * stride;\n                        count = (rank + 1) * stride;\n                        if (rank == interp->getReaderCount () - 1)\n                        {\n                            count += left_over_count;\n                        }\n                        size_t points_processed(0);\n                        while (index < count)\n                        {\n                            data_x = las.getX (index);\n                            data_y = las.getY (index);\n                            data_z = las.getZ (index);\n                            if (point_contained (data_x, data_y, min_x, min_y,\n                                                 max_x, max_y))\n                            {\n                                if (pass_filter(las, index))\n                                {\n                                    points_processed ++;\n                                    data_x -= min_x;\n                                    data_y -= min_y;\n                                    //\n                                    //cerr << \"calling update rank \"<< rank << endl;\n                                    if ((rc = interp->update (data_x, data_y,\n                                                              data_z)) < 0)\n                                    {\n                                        cerr\n                                                << \"interp->update() error while processing \"\n                                                << endl;\n                                        return -1;\n                                    }\n                                }\n                            }\n                            index++;\n                        }\n                        dbg(5, \"rank = %i, index = %li, points_processed = %li\", rank, index, points_processed);\n                    }\n                    interp->getReadDone ()[rank] = 1;\n\n                    for (int i = 0; i < process_count; i++)\n                    {\n                        if (interp->getWriters ()[i])\n                        {\n                            interp->updateGridPointSend (i, 1, 1, 1, 1);\n                        }\n                    }\n                }\n\n                else // (input_file_count > 1)\n                {\n\n                    for (int i = 0; i < input_file_count; i++)\n                    {\n                        if (input_files[i].peek_rank == rank)\n                        {\n                            if (rectangles_overlap (min_x, min_y, max_x, max_y,\n                                                    input_files[i].min_x,\n                                                    input_files[i].min_y,\n                                                    input_files[i].max_x,\n                                                    input_files[i].max_y))\n                            {\n                                dbg(5,\n                                    \"start read and send rank %i, peek_rank %i, name %s, point_count %li, global and file min_x, miny %lf, %lf, %lf, %lf\\n\",\n                                    rank, input_files[i].peek_rank,\n                                    input_files[i].name,\n                                    input_files[i].point_count, min_x,\n                                    input_files[i].min_x, min_y,\n                                    input_files[i].min_y);\n\n                                las_file las;\n                                las.open (input_files[i].name);\n\n                                size_t count = input_files[i].point_count;\n                                size_t index (0);\n                                size_t points_processed (0);\n                                while (index < count)\n                                {\n                                    data_x = las.getX (index);\n                                    data_y = las.getY (index);\n                                    data_z = las.getZ (index);\n\n                                    if (point_contained (data_x, data_y, min_x,\n                                                         min_y, max_x, max_y))\n                                    {\n                                        if (pass_filter (las, index))\n                                        {\n                                            points_processed++;\n                                            data_x -= min_x;\n                                            data_y -= min_y;\n                                            if ((rc = interp->update (data_x,\n                                                                      data_y,\n                                                                      data_z))\n                                                    < 0)\n                                            {\n                                                cerr\n                                                        << \"interp->update() error while processing \"\n                                                        << endl;\n                                                return -1;\n                                            }\n                                        }\n                                    }\n                                    index++;\n                                }\n                                dbg(3, \"rank = %i, index = %li, points_processed = %li\", rank, index, points_processed);\n                                las.close ();\n                            }\n                            dbg(2, \"*** rank %i, input file %s done with read and send ***\", rank, input_files[i].name);\n                        }\n                    }\n\n                    interp->getReadDone ()[rank] = 1;\n\n                    for (int i = 0; i < process_count; i++)\n                    {\n                        if (interp->getWriters ()[i])\n                        {\n                            interp->updateGridPointSend (i, 1, 1, 1, 1);\n                        }\n                    }\n\n                }\n            }\n            else if (interp->getIsWriter ())            // rank is a writer\n            {\n                interp->updateGridPointRecv ();\n            }\n            //MPI_Barrier (MPI_COMM_WORLD);\n        }\n        else // interpolation_mode is other than INTERP_MPI,\n             // single input file only supported, bbox supported, filters supported\n\n        {\n            if (rectangles_overlap (min_x, min_y, max_x, max_y,\n                                    input_files[0].min_x, input_files[0].min_y,\n                                    input_files[0].max_x, input_files[0].max_y))\n            {\n\n                las_file las;\n                las.open (input_files[0].name);\n\n                size_t count = las.points_count ();\n                size_t index (0);\n                size_t points_processed(0);\n                while (index < count)\n                {\n                    data_x = las.getX (index);\n                    data_y = las.getY (index);\n                    data_z = las.getZ (index);\n                    if (point_contained (data_x, data_y, min_x, min_y, max_x,\n                                         max_y))\n                    {\n                        if (pass_filter (las, index))\n                        {\n                            points_processed++;\n                            data_x -= min_x;\n                            data_y -= min_y;\n\n                            if ((rc = interp->update (data_x, data_y, data_z))\n                                    < 0)\n                            {\n                                cerr\n                                        << \"interp->update() error while processing \"\n                                        << endl;\n                                return -1;\n                            }\n                        }\n                    }\n                    index++;\n                }\n                dbg(3, \"index = %li, points_processed = %li\", index, points_processed);\n            }\n        }\n    }\n    if(timer)timer->interp_end = time(NULL);\n\n    if((rc = interp->finish(outputName, outputFormat, outputType)) < 0)\n    {\n        cerr << \"interp->finish() error\" << endl;\n        return -1;\n    }\n\n\n    return 0;\n}\n\nvoid Interpolation::setRadius(double r)\n{\n    radius_sqr = r * r;\n}\n\nunsigned int Interpolation::getGridSizeX()\n{\n    return GRID_SIZE_X;\n}\n\nunsigned int Interpolation::getGridSizeY()\n{\n    return GRID_SIZE_Y;\n}\n\n// rx1, ry1 = lower left, rx2, ry2 = upper right\nint Interpolation::point_contained(double x, double y, double rx1, double ry1, double rx2, double ry2)\n{\n    return (x >= rx1 && x <= rx2 && y >= ry1 && y <= ry2);\n}\n// rx1, ry1 = lower left, rx2, ry2 = upper right of first rectangle, sx1, sy1 = lower left, sx2, sy2 = upper right of second rectangle\nint Interpolation::rectangles_overlap (double rx1, double ry1, double rx2, double ry2, double sx1, double sy1, double sx2, double sy2)\n{\n    return sx1 < rx2 && sx2 > rx1 && sy1 < ry2 && sy2 > ry1;\n}\n\nint Interpolation::pass_filter (las_file &las, size_t index)\n{\n\n\n    if(!in_shape(las.getX(index), las.getY(index)))\n    {\n        return 0;\n    }\n\n    if(classification_count == 0 && first_returns == 0 && last_returns == 0)\n    {\n        return 1;\n    }\n    // At this point there either is no shape_filter shape_filter has been passed, check the point attr filters\n    int point_classification = las.getClassification(index);\n    for(int i=0; i < classification_count; i++)\n    {\n        if(point_classification == classifications[i])\n        {\n            return 1;\n        }\n    }\n    if (first_returns && las.getReturnNumber(index)==1)\n    {\n        return 1;\n    }\n    if (last_returns && las.getReturnNumber(index) == las.getReturnCount(index))\n    {\n        return 1;\n    }\n\n    return 0;\n\n}\n\n//static int in_shape_count = 0;\n\nint Interpolation::in_shape(double x, double y)\n{\n//    in_shape_count++;\n//    if(in_shape_count % 100000 == 0){\n//        printf(\"in_shape %lf %lf %i %i\\n\", x, y, rank, in_shape_count);\n//    }\n    if(shape_filter == NULL)\n    {\n        return 1;\n    }\n\n    if(shapes == NULL)\n    {\n        init_shape_filter_index();\n    }\n\n    ShapeItemVisitor visitor;\n    shape_filter_index.query(y, y, &visitor);\n    std::vector<void*> found_segments;\n    found_segments = visitor.items;\n\n    geos::geom::Coordinate las_point;\n    las_point.x = x;\n    las_point.y = y;\n    int cross_count = 0;\n\n    for (std::size_t i = 0; i < found_segments.size (); i++)\n    {\n\n        ShapeSegment *segment = (ShapeSegment *)(found_segments[i]);\n        double x1 =\n                shapes[segment->shape]->padfX[segment->vertex_1];\n        double y1 =\n                shapes[segment->shape]->padfY[segment->vertex_1];\n        double x2 =\n                shapes[segment->shape]->padfX[segment->vertex_1 + 1];\n        double y2 =\n                shapes[segment->shape]->padfY[segment->vertex_1 + 1];\n\n        geos::geom::Coordinate p1 (x1, y1);\n        geos::geom::Coordinate p2 (x2, y2);\n\n        cross_count += countSegment (p1, p2, las_point);\n        //printf(\"%i %li %li  %lf    %lf %lf   %lf     %lf %lf\\n\", cross_count, i, found_segments.size (), x, x1,x2, y ,  y1, y2);\n\n    }\n\n    return cross_count % 2;\n}\n\n\nint Interpolation::init_shape_filter_index()\n{\n    shape_count = shape_filter->nRecords;\n    shapes = (SHPObject **) malloc(shape_count * sizeof(SHPObject *));\n\n    for(int i=0; i<shape_count; i++)\n    {\n        shapes[i] =  SHPReadObject(shape_filter, i);\n        int part_cnt = shapes[i]->nParts;\n        for(int j=0; j<part_cnt; j++)\n        {\n            int start_vertex = shapes[i]->panPartStart[j];\n            int end_vertex;\n            if(j < part_cnt - 1)\n            {\n                end_vertex = shapes[i]->panPartStart[j+1] - 1;\n            }\n            else\n            {\n                end_vertex =  shapes[i]->nVertices - 1;\n            }\n            for(int k = start_vertex; k < end_vertex; k++)\n            {\n                double min =shapes[i]->padfY[k];\n                double max =shapes[i]->padfY[k+1];\n\n                if(max<min){\n                    double tmp = min;\n                    min = max;\n                    max = tmp;\n                }\n\n                ShapeSegment *segment = (ShapeSegment *)malloc(sizeof(ShapeSegment));\n                segment->shape = i;\n                segment->vertex_1 = k;\n                shape_filter_index.insert(min, max, segment);\n\n            }\n        }\n    }\n\n    return 1;\n}\n\nint\nInterpolation::countSegment(const geos::geom::Coordinate& p1,\n                                 const geos::geom::Coordinate& p2, const geos::geom::Coordinate& point)\n{\n        // This code is from geos v3.6 RayCrossingCounter.cpp\n        // and adapted for this use\n        int cross = 0;\n        // For each segment, check if it crosses\n        // a horizontal ray running from the test point in\n        // the positive x direction.\n\n        // check if the segment is strictly to the left of the test point\n        if (p1.x < point.x && p2.x < point.x)\n                return 0;\n\n        // check if the point is equal to the current ring vertex\n        if (point.x == p2.x && point.y == p2.y)\n        {\n                //isPointOnSegment = true;\n                return 0;\n        }\n\n        // For horizontal segments, check if the point is on the segment.\n        // Otherwise, horizontal segments are not counted.\n        if (p1.y == point.y && p2.y == point.y)\n        {\n                //double minx = p1.x;\n                //double maxx = p2.x;\n\n                //if (minx > maxx)\n                //{\n                //        minx = p2.x;\n                //        maxx = p1.x;\n                //}\n\n                //if (point.x >= minx && point.x <= maxx)\n                        //isPointOnSegment = true;\n\n                return 0;\n        }\n\n        // Evaluate all non-horizontal segments which cross a horizontal ray\n        // to the right of the test pt.\n        // To avoid double-counting shared vertices, we use the convention that\n        // - an upward edge includes its starting endpoint, and excludes its\n        //   final endpoint\n        // - a downward edge excludes its starting endpoint, and includes its\n        //   final endpoint\n        if (((p1.y > point.y) && (p2.y <= point.y)) ||\n                ((p2.y > point.y) && (p1.y <= point.y)) )\n        {\n                // For an upward edge, orientationIndex will be positive when p1->p2\n                // crosses ray. Conversely, downward edges should have negative sign.\n\n                int sign = orientationIndex(p1, p2, point);\n                if (sign == 0)\n                {\n                        //isPointOnSegment = true;\n                        return 0;\n                }\n\n                if (p2.y < p1.y)\n                        sign = -sign;\n\n                // The segment crosses the ray if the sign is strictly positive.\n                if (sign > 0)\n                        cross++;\n        }\n        return cross;\n}\n\n\n// This code is from geos v3.6 RayCrossingCounter.cpp\n// and called from the countSegment method\n// it avoids counting common segment vertex crossings\nint\nInterpolation::orientationIndex(const geos::geom::Coordinate& p1,\n         const geos::geom::Coordinate& p2, const geos::geom::Coordinate& q)\n{\n        // travelling along p1->p2, turn counter clockwise to get to q return 1,\n        // travelling along p1->p2, turn clockwise to get to q return -1,\n        // p1, p2 and q are colinear return 0.\n        double dx1=p2.x-p1.x;\n        double dy1=p2.y-p1.y;\n        double dx2=q.x-p2.x;\n        double dy2=q.y-p2.y;\n        return geos::algorithm::RobustDeterminant::signOfDet2x2(dx1,dy1,dx2,dy2);\n}\n\n\n\n", "meta": {"hexsha": "a9ab6ea15d9f326b6ec008490a7284bdb3b46859", "size": 32187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Interpolation.cpp", "max_stars_repo_name": "IllinoisStateGeologicalSurvey/p_point2grid", "max_stars_repo_head_hexsha": "8aad94f1d606143ef287944f30f6815c328074ba", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-25T21:26:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T21:26:25.000Z", "max_issues_repo_path": "src/Interpolation.cpp", "max_issues_repo_name": "IllinoisStateGeologicalSurvey/p_point2grid", "max_issues_repo_head_hexsha": "8aad94f1d606143ef287944f30f6815c328074ba", "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": "src/Interpolation.cpp", "max_forks_repo_name": "IllinoisStateGeologicalSurvey/p_point2grid", "max_forks_repo_head_hexsha": "8aad94f1d606143ef287944f30f6815c328074ba", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8031145717, "max_line_length": 197, "alphanum_fraction": 0.4750365054, "num_tokens": 7092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.024423087568799, "lm_q1q2_score": 0.008342499295751251}}
{"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#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include <cmath>\n#include <geometry_msgs/msg/transform_stamped.hpp>\n#include <memory>\n#include <object_detection/object_polygon_detail.hpp>\n#include <string>\n#include <vector>\n\nnamespace autoware\n{\nnamespace rviz_plugins\n{\nnamespace object_detection\n{\nnamespace detail\n{\nusing Marker = visualization_msgs::msg::Marker;\n\nvisualization_msgs::msg::Marker::SharedPtr get_path_confidence_marker_ptr(\n  const autoware_auto_perception_msgs::msg::PredictedPath & predicted_path,\n  const std_msgs::msg::ColorRGBA & path_confidence_color)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->type = visualization_msgs::msg::Marker::TEXT_VIEW_FACING;\n  marker_ptr->ns = std::string(\"path confidence\");\n  marker_ptr->action = visualization_msgs::msg::Marker::MODIFY;\n  marker_ptr->lifetime = rclcpp::Duration::from_seconds(0.2);\n  marker_ptr->scale.x = 0.5;\n  marker_ptr->scale.y = 0.5;\n  marker_ptr->scale.z = 0.5;\n  marker_ptr->pose = initPose();\n  marker_ptr->color = path_confidence_color;\n  marker_ptr->pose.position = predicted_path.path.back().position;\n  marker_ptr->text = std::to_string(predicted_path.confidence);\n  marker_ptr->color.a = std::max(\n    static_cast<double>(std::min(static_cast<double>(predicted_path.confidence), 0.999)), 0.5);\n  return marker_ptr;\n}\n\nvisualization_msgs::msg::Marker::SharedPtr get_predicted_path_marker_ptr(\n  const autoware_auto_perception_msgs::msg::Shape & shape,\n  const autoware_auto_perception_msgs::msg::PredictedPath & predicted_path,\n  const std_msgs::msg::ColorRGBA & predicted_path_color)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->type = visualization_msgs::msg::Marker::LINE_LIST;\n  marker_ptr->ns = std::string(\"path\");\n  marker_ptr->action = visualization_msgs::msg::Marker::MODIFY;\n  marker_ptr->lifetime = rclcpp::Duration::from_seconds(0.2);\n  marker_ptr->pose = initPose();\n  marker_ptr->color = predicted_path_color;\n  marker_ptr->color.a = std::max(\n    static_cast<double>(std::min(static_cast<double>(predicted_path.confidence), 0.999)), 0.5);\n  marker_ptr->scale.x = 0.03 * marker_ptr->color.a;\n  calc_path_line_list(predicted_path, marker_ptr->points);\n  for (size_t k = 0; k < marker_ptr->points.size(); ++k) {\n    marker_ptr->points.at(k).z -= shape.dimensions.z / 2.0;\n  }\n  return marker_ptr;\n}\n\nvisualization_msgs::msg::Marker::SharedPtr get_twist_marker_ptr(\n  const geometry_msgs::msg::PoseWithCovariance & pose_with_covariance,\n  const geometry_msgs::msg::TwistWithCovariance & twist_with_covariance)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->type = visualization_msgs::msg::Marker::LINE_LIST;\n  marker_ptr->ns = std::string(\"twist\");\n  marker_ptr->scale.x = 0.03;\n  marker_ptr->action = visualization_msgs::msg::Marker::MODIFY;\n  marker_ptr->pose = pose_with_covariance.pose;\n\n  geometry_msgs::msg::Point pt_s;\n  pt_s.x = 0.0;\n  pt_s.y = 0.0;\n  pt_s.z = 0.0;\n  marker_ptr->points.push_back(pt_s);\n\n  geometry_msgs::msg::Point pt_e;\n  pt_e.x = twist_with_covariance.twist.linear.x;\n  pt_e.y = twist_with_covariance.twist.linear.y;\n  pt_e.z = twist_with_covariance.twist.linear.z;\n  marker_ptr->points.push_back(pt_e);\n\n  marker_ptr->lifetime = rclcpp::Duration::from_seconds(0.2);\n  marker_ptr->color.a = 0.999;\n  marker_ptr->color.r = 1.0;\n  marker_ptr->color.g = 0.0;\n  marker_ptr->color.b = 0.0;\n\n  return marker_ptr;\n}\n\nvisualization_msgs::msg::Marker::SharedPtr get_velocity_text_marker_ptr(\n  const geometry_msgs::msg::Twist & twist, const geometry_msgs::msg::Point & vis_pos,\n  const std_msgs::msg::ColorRGBA & color_rgba)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->type = visualization_msgs::msg::Marker::TEXT_VIEW_FACING;\n  marker_ptr->ns = std::string(\"velocity\");\n  marker_ptr->scale.x = 0.5;\n  marker_ptr->scale.z = 0.5;\n\n  double vel = std::sqrt(\n    twist.linear.x * twist.linear.x + twist.linear.y * twist.linear.y +\n    twist.linear.z * twist.linear.z);\n  marker_ptr->text = std::to_string(static_cast<int>(vel * 3.6)) + std::string(\"[km/h]\");\n  marker_ptr->action = visualization_msgs::msg::Marker::MODIFY;\n  marker_ptr->pose.position = vis_pos;\n  marker_ptr->lifetime = rclcpp::Duration::from_seconds(0.2);\n  marker_ptr->color = color_rgba;\n  return marker_ptr;\n}\n\nvisualization_msgs::msg::Marker::SharedPtr get_pose_with_covariance_marker_ptr(\n  const geometry_msgs::msg::PoseWithCovariance & pose_with_covariance)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->type = visualization_msgs::msg::Marker::LINE_LIST;\n  marker_ptr->ns = std::string(\"position covariance\");\n  marker_ptr->scale.x = 0.03;\n  marker_ptr->action = visualization_msgs::msg::Marker::MODIFY;\n  marker_ptr->pose = pose_with_covariance.pose;\n  marker_ptr->pose.orientation.x = 0.0;\n  marker_ptr->pose.orientation.y = 0.0;\n  marker_ptr->pose.orientation.z = 0.0;\n  marker_ptr->pose.orientation.w = 1.0;\n  geometry_msgs::msg::Point point;\n  Eigen::Matrix2d eigen_pose_with_covariance;\n  eigen_pose_with_covariance << pose_with_covariance.covariance[0],\n    pose_with_covariance.covariance[1], pose_with_covariance.covariance[6],\n    pose_with_covariance.covariance[7];\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> solver(eigen_pose_with_covariance);\n  double sigma1 = 2.448 * std::sqrt(solver.eigenvalues().x());  // 2.448 sigma is 95%\n  double sigma2 = 2.448 * std::sqrt(solver.eigenvalues().y());  // 2.448 sigma is 95%\n  Eigen::Vector2d e1 = solver.eigenvectors().col(0);\n  Eigen::Vector2d e2 = solver.eigenvectors().col(1);\n  point.x = -e1.x() * sigma1;\n  point.y = -e1.y() * sigma1;\n  point.z = 0;\n  marker_ptr->points.push_back(point);\n  point.x = e1.x() * sigma1;\n  point.y = e1.y() * sigma1;\n  point.z = 0;\n  marker_ptr->points.push_back(point);\n  point.x = -e2.x() * sigma2;\n  point.y = -e2.y() * sigma2;\n  point.z = 0;\n  marker_ptr->points.push_back(point);\n  point.x = e2.x() * sigma2;\n  point.y = e2.y() * sigma2;\n  point.z = 0;\n  marker_ptr->points.push_back(point);\n  marker_ptr->lifetime = rclcpp::Duration::from_seconds(0.2);\n  marker_ptr->color.a = 0.999;\n  marker_ptr->color.r = 1.0;\n  marker_ptr->color.g = 1.0;\n  marker_ptr->color.b = 1.0;\n  return marker_ptr;\n}\n\nvisualization_msgs::msg::Marker::SharedPtr get_uuid_marker_ptr(\n  const std::string & uuid, const geometry_msgs::msg::Point & centroid,\n  const std_msgs::msg::ColorRGBA & color_rgba)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->type = Marker::TEXT_VIEW_FACING;\n  marker_ptr->ns = std::string(\"uuid\");\n  marker_ptr->text = uuid.substr(0, 4);\n  marker_ptr->action = Marker::MODIFY;\n  marker_ptr->scale.z = 0.5;\n  marker_ptr->color = color_rgba;\n  marker_ptr->pose.position = centroid;\n  return marker_ptr;\n}\n\nvisualization_msgs::msg::Marker::SharedPtr get_label_marker_ptr(\n  const geometry_msgs::msg::Point & centroid, const geometry_msgs::msg::Quaternion & orientation,\n  const std::string label, const std_msgs::msg::ColorRGBA & color_rgba)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->type = visualization_msgs::msg::Marker::TEXT_VIEW_FACING;\n  marker_ptr->ns = std::string(\"label\");\n  marker_ptr->scale.x = 0.5;\n  marker_ptr->scale.z = 0.5;\n  marker_ptr->text = label;\n  marker_ptr->action = visualization_msgs::msg::Marker::MODIFY;\n  marker_ptr->pose = marker_ptr->pose = to_pose(centroid, orientation);\n  marker_ptr->lifetime = rclcpp::Duration::from_seconds(0.2);\n  marker_ptr->color = color_rgba;\n  return marker_ptr;\n}\n\nvisualization_msgs::msg::Marker::SharedPtr get_shape_marker_ptr(\n  const autoware_auto_perception_msgs::msg::Shape & shape_msg,\n  const geometry_msgs::msg::Point & centroid, const geometry_msgs::msg::Quaternion & orientation,\n  const std_msgs::msg::ColorRGBA & color_rgba)\n{\n  auto marker_ptr = std::make_shared<Marker>();\n  marker_ptr->ns = std::string(\"shape\");\n\n  using autoware_auto_perception_msgs::msg::Shape;\n  if (shape_msg.type == Shape::BOUNDING_BOX) {\n    marker_ptr->type = visualization_msgs::msg::Marker::LINE_LIST;\n    calc_bounding_box_line_list(shape_msg, marker_ptr->points);\n  } else if (shape_msg.type == Shape::CYLINDER) {\n    marker_ptr->type = visualization_msgs::msg::Marker::LINE_LIST;\n    calc_cylinder_line_list(shape_msg, marker_ptr->points);\n  } else if (shape_msg.type == Shape::POLYGON) {\n    marker_ptr->type = visualization_msgs::msg::Marker::LINE_LIST;\n    calc_polygon_line_list(shape_msg, marker_ptr->points);\n  } else {\n    marker_ptr->type = visualization_msgs::msg::Marker::LINE_LIST;\n    calc_polygon_line_list(shape_msg, marker_ptr->points);\n  }\n\n  marker_ptr->action = visualization_msgs::msg::Marker::MODIFY;\n  marker_ptr->pose = to_pose(centroid, orientation);\n  marker_ptr->lifetime = rclcpp::Duration::from_seconds(0.2);\n  marker_ptr->scale.x = 0.03;\n  marker_ptr->color = color_rgba;\n\n  return marker_ptr;\n}\n\nvoid calc_bounding_box_line_list(\n  const autoware_auto_perception_msgs::msg::Shape & shape,\n  std::vector<geometry_msgs::msg::Point> & points)\n{\n  geometry_msgs::msg::Point point;\n  point.x = shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  // up surface\n  point.x = shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  // down surface\n  point.x = shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n\n  point.x = shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n  point.x = -shape.dimensions.x / 2.0;\n  point.y = -shape.dimensions.y / 2.0;\n  point.z = -shape.dimensions.z / 2.0;\n  points.push_back(point);\n}\n\nvoid calc_cylinder_line_list(\n  const autoware_auto_perception_msgs::msg::Shape & shape,\n  std::vector<geometry_msgs::msg::Point> & points)\n{\n  const double radius = shape.dimensions.x * 0.5;\n  {\n    constexpr int n = 20;\n    geometry_msgs::msg::Point center;\n    center.x = 0.0;\n    center.y = 0.0;\n    center.z = shape.dimensions.z * 0.5;\n    calc_circle_line_list(center, radius, points, n);\n    center.z = -shape.dimensions.z * 0.5;\n    calc_circle_line_list(center, radius, points, n);\n  }\n  {\n    constexpr int n = 4;\n    for (int i = 0; i < n; ++i) {\n      geometry_msgs::msg::Point point;\n      point.x = std::cos(\n        (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n        M_PI / static_cast<double>(n)) *\n        radius;\n      point.y = std::sin(\n        (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n        M_PI / static_cast<double>(n)) *\n        radius;\n      point.z = shape.dimensions.z * 0.5;\n      points.push_back(point);\n      point.x = std::cos(\n        (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n        M_PI / static_cast<double>(n)) *\n        radius;\n      point.y = std::sin(\n        (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n        M_PI / static_cast<double>(n)) *\n        radius;\n      point.z = -shape.dimensions.z * 0.5;\n      points.push_back(point);\n    }\n  }\n}\n\nvoid calc_circle_line_list(\n  const geometry_msgs::msg::Point center, const double radius,\n  std::vector<geometry_msgs::msg::Point> & points, const int n)\n{\n  for (int i = 0; i < n; ++i) {\n    geometry_msgs::msg::Point point;\n    point.x = std::cos(\n      (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n      M_PI / static_cast<double>(n)) *\n      radius +\n      center.x;\n    point.y = std::sin(\n      (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n      M_PI / static_cast<double>(n)) *\n      radius +\n      center.y;\n    point.z = center.z;\n    points.push_back(point);\n    point.x = std::cos(\n      (static_cast<double>(i + 1.0) / static_cast<double>(n)) * 2.0 * M_PI +\n      M_PI / static_cast<double>(n)) *\n      radius +\n      center.x;\n    point.y = std::sin(\n      (static_cast<double>(i + 1.0) / static_cast<double>(n)) * 2.0 * M_PI +\n      M_PI / static_cast<double>(n)) *\n      radius +\n      center.y;\n    point.z = center.z;\n    points.push_back(point);\n  }\n}\n\nvoid calc_polygon_line_list(\n  const autoware_auto_perception_msgs::msg::Shape & shape,\n  std::vector<geometry_msgs::msg::Point> & points)\n{\n  if (shape.footprint.points.size() < 2) {\n    RCLCPP_WARN(\n      rclcpp::get_logger(\"ObjectPolygonDisplayBase\"),\n      \"there are no enough footprint to visualize polygon\");\n    return;\n  }\n  for (size_t i = 0; i < shape.footprint.points.size(); ++i) {\n    geometry_msgs::msg::Point point;\n    point.x = shape.footprint.points.at(i).x;\n    point.y = shape.footprint.points.at(i).y;\n    point.z = shape.dimensions.z / 2.0;\n    points.push_back(point);\n    point.x = shape.footprint.points\n      .at(static_cast<int>(i + 1) % static_cast<int>(shape.footprint.points.size()))\n      .x;\n    point.y = shape.footprint.points\n      .at(static_cast<int>(i + 1) % static_cast<int>(shape.footprint.points.size()))\n      .y;\n    point.z = shape.dimensions.z / 2.0;\n    points.push_back(point);\n  }\n  for (size_t i = 0; i < shape.footprint.points.size(); ++i) {\n    geometry_msgs::msg::Point point;\n    point.x = shape.footprint.points.at(i).x;\n    point.y = shape.footprint.points.at(i).y;\n    point.z = -shape.dimensions.z / 2.0;\n    points.push_back(point);\n    point.x = shape.footprint.points\n      .at(static_cast<int>(i + 1) % static_cast<int>(shape.footprint.points.size()))\n      .x;\n    point.y = shape.footprint.points\n      .at(static_cast<int>(i + 1) % static_cast<int>(shape.footprint.points.size()))\n      .y;\n    point.z = -shape.dimensions.z / 2.0;\n    points.push_back(point);\n  }\n  for (size_t i = 0; i < shape.footprint.points.size(); ++i) {\n    geometry_msgs::msg::Point point;\n    point.x = shape.footprint.points.at(i).x;\n    point.y = shape.footprint.points.at(i).y;\n    point.z = shape.dimensions.z / 2.0;\n    points.push_back(point);\n    point.x = shape.footprint.points.at(i).x;\n    point.y = shape.footprint.points.at(i).y;\n    point.z = -shape.dimensions.z / 2.0;\n    points.push_back(point);\n  }\n}\n\nvoid calc_path_line_list(\n  const autoware_auto_perception_msgs::msg::PredictedPath & paths,\n  std::vector<geometry_msgs::msg::Point> & points)\n{\n  for (int i = 0; i < static_cast<int>(paths.path.size()) - 1; ++i) {\n    geometry_msgs::msg::Point point;\n    point.x = paths.path.at(i).position.x;\n    point.y = paths.path.at(i).position.y;\n    point.z = paths.path.at(i).position.z;\n    points.push_back(point);\n    point.x = paths.path.at(i + 1).position.x;\n    point.y = paths.path.at(i + 1).position.y;\n    point.z = paths.path.at(i + 1).position.z;\n    points.push_back(point);\n    calc_circle_line_list(point, 0.25, points, 10);\n  }\n}\n\n}  // namespace detail\n}  // namespace object_detection\n}  // namespace rviz_plugins\n}  // namespace autoware\n", "meta": {"hexsha": "5f65fce8c72ea8d1baf76524bb4cd86fcb07197d", "size": 18162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/autoware_auto_perception_rviz_plugin/src/object_detection/object_polygon_detail.cpp", "max_stars_repo_name": "TakahiroNISHIOKA/autoware.universe", "max_stars_repo_head_hexsha": "67459763bd61a57e044132174dd1c403550c1f00", "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": "common/autoware_auto_perception_rviz_plugin/src/object_detection/object_polygon_detail.cpp", "max_issues_repo_name": "TakahiroNISHIOKA/autoware.universe", "max_issues_repo_head_hexsha": "67459763bd61a57e044132174dd1c403550c1f00", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2022-01-24T10:26:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:19:01.000Z", "max_forks_repo_path": "common/util/rviz_plugins/autoware_auto_perception_rviz_plugin/src/object_detection/object_polygon_detail.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": 35.6817288802, "max_line_length": 97, "alphanum_fraction": 0.6826891312, "num_tokens": 5272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.029312233719238127, "lm_q1q2_score": 0.008341558346481726}}
{"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#define BOOST_PYTHON_MAX_ARITY 17\n\n#include \"PyImathMatrix.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathDecorators.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include <boost/python/tuple.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/raw_function.hpp>\n#include \"PyImath.h\"\n#include \"PyImathVec.h\"\n#include \"PyImathMathExc.h\"\n#include <ImathVec.h>\n#include <ImathMatrixAlgo.h>\n#include <Iex.h>\n\nnamespace PyImath {\n\ntemplate<> const char *PyImath::M22fArray::name() { return \"M22fArray\"; }\ntemplate<> const char *PyImath::M22dArray::name() { return \"M22dArray\"; }\n\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\n\ntemplate <class T, int len>\nstruct MatrixRow {\n    explicit MatrixRow(T *data) : _data(data) {}\n    T & operator [] (int i) { return _data[i]; }\n    T *_data;\n\n    static const char *name;\n    static void register_class()\n    {\n        typedef PyImath::StaticFixedArray<MatrixRow,T,len> MatrixRow_helper;\n        class_<MatrixRow> matrixRow_class(name,no_init);\n        matrixRow_class\n            .def(\"__len__\", MatrixRow_helper::len)\n            .def(\"__getitem__\", MatrixRow_helper::getitem,return_value_policy<copy_non_const_reference>())\n            .def(\"__setitem__\", MatrixRow_helper::setitem)\n            ;\n    }\n};\n\ntemplate <> const char *MatrixRow<float,2>::name = \"M22fRow\";\ntemplate <> const char *MatrixRow<double,2>::name = \"M22dRow\";\n\n\ntemplate <class Container, class Data, int len>\nstruct IndexAccessMatrixRow {\n    typedef MatrixRow<Data,len> result_type;\n    static MatrixRow<Data,len> apply(Container &c, int i) { return MatrixRow<Data,len>(c[i]); }\n};\n\ntemplate <class T> struct Matrix22Name { static const char *value; };\ntemplate<> const char *Matrix22Name<float>::value  = \"M22f\";\ntemplate<> const char *Matrix22Name<double>::value = \"M22d\";\n\ntemplate <class T>\nstatic std::string Matrix22_str(const Matrix22<T> &v)\n{\n    std::stringstream stream;\n    stream << Matrix22Name<T>::value << \"(\";\n    for (int row = 0; row < 2; row++)\n    {\n        stream << \"(\";\n\tfor (int col = 0; col < 2; col++)\n\t{\n\t    stream << v[row][col];\n            stream << (col != 1 ? \", \" : \"\");\n\t}\n        stream << \")\" << (row != 1 ? \", \" : \"\");\n    }\n    stream << \")\";\n    return stream.str();\n}\n\n// Non-specialized repr is same as str\ntemplate <class T>\nstatic std::string Matrix22_repr(const Matrix22<T> &v)\n{\n    return Matrix22_str(v);\n}\n\n// Specialization for float to full precision\ntemplate <>\nstd::string Matrix22_repr(const Matrix22<float> &v)\n{\n    return (boost::format(\"%s((%.9g, %.9g), (%.9g, %.9g))\")\n                        % Matrix22Name<float>::value\n                        % v[0][0] % v[0][1]\n                        % v[1][0] % v[1][1]).str();\n}\n\n// Specialization for double to full precision\ntemplate <>\nstd::string Matrix22_repr(const Matrix22<double> &v)\n{\n    return (boost::format(\"%s((%.17g, %.17g), (%.17g, %.17g))\")\n                        % Matrix22Name<double>::value\n                        % v[0][0] % v[0][1]\n                        % v[1][0] % v[1][1]).str();\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\ninvert22 (Matrix22<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.invert(singExc);\n}\n\ntemplate <class T>\nstatic Matrix22<T>\ninverse22 (Matrix22<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.inverse(singExc);\n}\n\ntemplate <class T, class U>\nstatic const Matrix22<T> &\niadd22(Matrix22<T> &m, const Matrix22<U> &m2)\n{\n    MATH_EXC_ON;\n    Matrix22<T> m3;\n    m3.setValue (m2);\n    return m += m3;\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\niadd22T(Matrix22<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    return mat += a;\n}\n\ntemplate <class T>\nstatic Matrix22<T>\nadd22(Matrix22<T> &m, const Matrix22<T> &m2)\n{\n    MATH_EXC_ON;\n    return m + m2;\n}\n\ntemplate <class T, class U>\nstatic const Matrix22<T> &\nisub22(Matrix22<T> &m, const Matrix22<U> &m2)\n{\n    MATH_EXC_ON;\n    Matrix22<T> m3;\n    m3.setValue (m2);\n    return m -= m3;\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nisub22T(Matrix22<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    return mat -= a;\n}\n\ntemplate <class T>\nstatic Matrix22<T>\nsub22(Matrix22<T> &m, const Matrix22<T> &m2)\n{\n    MATH_EXC_ON;\n    return m - m2;\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nnegate22 (Matrix22<T> &m)\n{\n    MATH_EXC_ON;\n    return m.negate();\n}\n\ntemplate <class T>\nstatic Matrix22<T>\nneg22 (Matrix22<T> &m)\n{\n    MATH_EXC_ON;\n    return -m;\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nimul22T(Matrix22<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m *= t;\n}\n\ntemplate <class T>\nstatic Matrix22<T>\nmul22T(Matrix22<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m * t;\n}\n\ntemplate <class T>\nstatic Matrix22<T>\nrmul22T(Matrix22<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return t * m;\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nidiv22T(Matrix22<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m /= t;\n}\n\ntemplate <class T>\nstatic Matrix22<T>\ndiv22T(Matrix22<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m / t;\n}\n\ntemplate <class T>\nvoid\nouterProduct22(Matrix22<T> &mat, const Vec2<T> &a, const Vec2<T> &b)\n{\n    MATH_EXC_ON;\n    mat = IMATH_NAMESPACE::outerProduct(a,b);\n}\n\ntemplate <class TV,class TM>\nstatic void\nmultDirMatrix22(Matrix22<TM> &mat, const Vec2<TV> &src, Vec2<TV> &dst)\n{\n    MATH_EXC_ON;\n    mat.multDirMatrix(src, dst);    \n}\n\ntemplate <class TV,class TM>\nstatic Vec2<TV>\nmultDirMatrix22_return_value(Matrix22<TM> &mat, const Vec2<TV> &src)\n{\n    MATH_EXC_ON;\n    Vec2<TV> dst;\n    mat.multDirMatrix(src, dst);    \n    return dst;\n}\n\ntemplate <class TV,class TM>\nstatic FixedArray<Vec2<TV> >\nmultDirMatrix22_array(Matrix22<TM> &mat, const FixedArray<Vec2<TV> >&src)\n{\n    MATH_EXC_ON;\n    size_t len = src.len();\n    FixedArray<Vec2<TV> > dst(len);\n    for (size_t i=0; i<len; ++i) mat.multDirMatrix(src[i], dst[i]);    \n    return dst;\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nrotate22(Matrix22<T> &mat, const T &r)\n{\n    MATH_EXC_ON;\n    return mat.rotate(r);    \n}\n\ntemplate <class T>\nstatic void\nextractEuler(Matrix22<T> &mat, Vec2<T> &dstObj)\n{\n    MATH_EXC_ON;\n    T dst;\n    IMATH_NAMESPACE::extractEuler(mat, dst);\n    dstObj.setValue(dst, T (0));\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nscaleSc22(Matrix22<T> &mat, const T &s)\n{\n    MATH_EXC_ON;\n    Vec2<T> sVec(s, s);\n    return mat.scale(sVec);\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nscaleV22(Matrix22<T> &mat, const Vec2<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.scale(s);\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nscale22Tuple(Matrix22<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        \n        return mat.scale(s);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.scale needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nsetRotation22(Matrix22<T> &mat, const T &r)\n{\n    MATH_EXC_ON;\n    return mat.setRotation(r);    \n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nsetScaleSc22(Matrix22<T> &mat, const T &s)\n{\n    MATH_EXC_ON;\n    Vec2<T> sVec(s, s);\n    return mat.setScale(sVec);\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nsetScaleV22(Matrix22<T> &mat, const Vec2<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.setScale(s);\n}\n\ntemplate <class T>\nstatic const Matrix22<T> &\nsetScale22Tuple(Matrix22<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        \n        return mat.setScale(s);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.setScale needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic void\nsetValue22(Matrix22<T> &mat, const Matrix22<T> &value)\n{\n    MATH_EXC_ON;\n    mat.setValue(value);\n}\n\ntemplate <class T>\nstatic Matrix22<T>\nsubtractTL22(Matrix22<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix22<T> m(mat.x);\n    for(int i = 0; i < 2; ++i)\n        for(int j = 0; j < 2; ++j)\n            m.x[i][j] -= a;\n    \n    return m;\n}\n\ntemplate <class T>\nstatic Matrix22<T>\nsubtractTR22(Matrix22<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix22<T> m(mat.x);\n    for(int i = 0; i < 2; ++i)\n        for(int j = 0; j < 2; ++j)\n            m.x[i][j] = a - m.x[i][j];\n    \n    return m;\n}\n\n\ntemplate <class T>\nstatic Matrix22<T>\nadd22T(Matrix22<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix22<T> m(mat.x);\n    for(int i = 0; i < 2; ++i)\n        for(int j = 0; j < 2; ++j)\n            m.x[i][j] += a;\n    \n    return m;\n}\n\ntemplate <class S, class T>\nstatic Matrix22<T>\nmul22(Matrix22<T> &mat1, Matrix22<S> &mat2)\n{\n    MATH_EXC_ON;\n    Matrix22<T> mat2T;\n    mat2T.setValue (mat2);\n    return mat1 * mat2T;\n}\n\ntemplate <class S, class T>\nstatic Matrix22<T>\nrmul22(Matrix22<T> &mat2, Matrix22<S> &mat1)\n{\n    MATH_EXC_ON;\n    Matrix22<T> mat1T;\n    mat1T.setValue (mat1);\n    return mat1T * mat2;\n}\n\ntemplate <class S, class T>\nstatic const Matrix22<T> &\nimul22(Matrix22<T> &mat1, Matrix22<S> &mat2)\n{\n    MATH_EXC_ON;\n    Matrix22<T> mat2T;\n    mat2T.setValue (mat2);\n    return mat1 *= mat2T;\n}\n\ntemplate <class T>\nstatic bool\nlessThan22(Matrix22<T> &mat1, const Matrix22<T> &mat2)\n{\n    for(int i = 0; i < 2; ++i){\n        for(int j = 0; j < 2; ++j){\n            if(mat1[i][j] > mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return (mat1 != mat2);            \n}\n\ntemplate <class T>\nstatic bool\nlessThanEqual22(Matrix22<T> &mat1, const Matrix22<T> &mat2)\n{\n    for(int i = 0; i < 2; ++i){\n        for(int j = 0; j < 2; ++j){\n            if(mat1[i][j] > mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return true;            \n}\n\ntemplate <class T>\nstatic bool\ngreaterThan22(Matrix22<T> &mat1, const Matrix22<T> &mat2)\n{\n    for(int i = 0; i < 2; ++i){\n        for(int j = 0; j < 2; ++j){\n            if(mat1[i][j] < mat2[i][j]){\n                std::cout << mat1[i][j] << \" \" << mat2[i][j] << std::endl;\n                return false;\n            }\n        }\n    }\n    \n    return (mat1 != mat2);            \n}\n\ntemplate <class T>\nstatic bool\ngreaterThanEqual22(Matrix22<T> &mat1, const Matrix22<T> &mat2)\n{\n    for(int i = 0; i < 2; ++i){\n        for(int j = 0; j < 2; ++j){\n            if(mat1[i][j] < mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return true;            \n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(invert22_overloads, invert22, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(inverse22_overloads, inverse22, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(outerProduct22_overloads, outerProduct22, 3, 3);\n\ntemplate <class T>\nstatic Matrix22<T> * Matrix2_tuple_constructor(const tuple &t0, const tuple &t1)\n{\n  if(t0.attr(\"__len__\")() == 2 && t1.attr(\"__len__\")() == 2)\n  {\n      return new Matrix22<T>(extract<T>(t0[0]),  extract<T>(t0[1]),\n                             extract<T>(t1[0]),  extract<T>(t1[1]));\n  }\n  else\n      THROW(IEX_NAMESPACE::LogicExc, \"Matrix22 takes 2 tuples of length 2\");\n}\n\ntemplate <class T, class S>\nstatic Matrix22<T> *Matrix2_matrix_constructor(const Matrix22<S> &mat)\n{\n    Matrix22<T> *m = new Matrix22<T>;\n    \n    for(int i = 0; i < 2; ++i)\n        for(int j = 0; j < 2; ++j)\n            m->x[i][j] = T (mat.x[i][j]);\n    \n    return m;\n}\n\ntemplate <class T>\nclass_<Matrix22<T> >\nregister_Matrix22()\n{\n    typedef PyImath::StaticFixedArray<Matrix22<T>,T,2,IndexAccessMatrixRow<Matrix22<T>,T,2> > Matrix22_helper;\n\n    MatrixRow<T,2>::register_class();\n    class_<Matrix22<T> > matrix22_class(Matrix22Name<T>::value, Matrix22Name<T>::value,init<Matrix22<T> >(\"copy construction\"));\n    matrix22_class\n        .def(init<>(\"initialize to identity\"))\n        .def(init<T>(\"initialize all entries to a single value\"))\n        .def(init<T,T,T,T>(\"make from components\"))\n        .def(\"__init__\", make_constructor(Matrix2_tuple_constructor<T>))\n        .def(\"__init__\", make_constructor(Matrix2_matrix_constructor<T,float>))\n        .def(\"__init__\", make_constructor(Matrix2_matrix_constructor<T,double>))\n        \n\t//.def_readwrite(\"x00\", &Matrix22<T>::x[0][0])\n\t//.def_readwrite(\"x01\", &Matrix22<T>::x[0][1])\n\t//.def_readwrite(\"x02\", &Matrix22<T>::x[0][2])\n\t//.def_readwrite(\"x10\", &Matrix22<T>::x[1][0])\n\t//.def_readwrite(\"x11\", &Matrix22<T>::x[1][1])\n\t//.def_readwrite(\"x12\", &Matrix22<T>::x[1][2])\n\t//.def_readwrite(\"x20\", &Matrix22<T>::x[2][0])\n\t//.def_readwrite(\"x21\", &Matrix22<T>::x[2][1])\n\t//.def_readwrite(\"x22\", &Matrix22<T>::x[2][2])\n        .def(\"baseTypeEpsilon\", &Matrix22<T>::baseTypeEpsilon,\"baseTypeEpsilon() epsilon value of the base type of the vector\")\n        .staticmethod(\"baseTypeEpsilon\")\n        .def(\"baseTypeMax\", &Matrix22<T>::baseTypeMax,\"baseTypeMax() max value of the base type of the vector\")\n        .staticmethod(\"baseTypeMax\")\n        .def(\"baseTypeMin\", &Matrix22<T>::baseTypeMin,\"baseTypeMin() min value of the base type of the vector\")\n        .staticmethod(\"baseTypeMin\")\n        .def(\"baseTypeSmallest\", &Matrix22<T>::baseTypeSmallest,\"baseTypeSmallest() smallest value of the base type of the vector\")\n        .staticmethod(\"baseTypeSmallest\")\n        .def(\"equalWithAbsError\", &Matrix22<T>::equalWithAbsError,\"m1.equalWithAbsError(m2,e) true if the elements \"\n             \"of v1 and v2 are the same with an absolute error of no more than e, \"\n             \"i.e., abs(m1[i] - m2[i]) <= e\")\n        .def(\"equalWithRelError\", &Matrix22<T>::equalWithRelError,\"m1.equalWithAbsError(m2,e) true if the elements \"\n             \"of m1 and m2 are the same with an absolute error of no more than e, \"\n             \"i.e., abs(m1[i] - m2[i]) <= e * abs(m1[i])\")\n        // need a different version for matrix data access\n        .def(\"__len__\", Matrix22_helper::len)\n        .def(\"__getitem__\", Matrix22_helper::getitem)\n\t//.def(\"__setitem__\", Matrix22_helper::setitem)\n        .def(\"makeIdentity\",&Matrix22<T>::makeIdentity,\"makeIdentity() make this matrix the identity matrix\")\n        .def(\"transpose\",&Matrix22<T>::transpose,return_internal_reference<>(),\"transpose() transpose this matrix\")\n        .def(\"transposed\",&Matrix22<T>::transposed,\"transposed() return a transposed copy of this matrix\")\n        .def(\"invert\",&invert22<T>,invert22_overloads(\"invert() invert this matrix\")[return_internal_reference<>()])\n        .def(\"inverse\",&inverse22<T>,inverse22_overloads(\"inverse() return an inverted copy of this matrix\"))\n        .def(\"determinant\",&Matrix22<T>::determinant,\"determinant() return the determinant of this matrix\")\n        .def(self == self) // NOSONAR - suppress SonarCloud bug report.\n        .def(self != self) // NOSONAR - suppress SonarCloud bug report.\n        .def(\"__iadd__\", &iadd22<T, float>,return_internal_reference<>())\n        .def(\"__iadd__\", &iadd22<T, double>,return_internal_reference<>())\n        .def(\"__iadd__\", &iadd22T<T>,return_internal_reference<>())\n        .def(\"__add__\", &add22<T>)\n        .def(\"__isub__\", &isub22<T, float>,return_internal_reference<>())\n        .def(\"__isub__\", &isub22<T, double>,return_internal_reference<>())\n        .def(\"__isub__\", &isub22T<T>,return_internal_reference<>())\n        .def(\"__sub__\", &sub22<T>)\n        .def(\"negate\",&negate22<T>,return_internal_reference<>(),\"negate() negate all entries in this matrix\")\n        .def(\"__neg__\", &neg22<T>)\n        .def(\"__imul__\", &imul22T<T>,return_internal_reference<>())\n        .def(\"__mul__\", &mul22T<T>)\n        .def(\"__rmul__\", &rmul22T<T>)\n        .def(\"__idiv__\", &idiv22T<T>,return_internal_reference<>())\n        .def(\"__itruediv__\", &idiv22T<T>,return_internal_reference<>())\n        .def(\"__div__\", &div22T<T>)\n        .def(\"__truediv__\", &div22T<T>)\n        .def(\"__add__\", &add22T<T>)\n        .def(\"__radd__\", &add22T<T>)\n        .def(\"__sub__\", &subtractTL22<T>)\n        .def(\"__rsub__\", &subtractTR22<T>)\n        .def(\"__mul__\", &mul22<float, T>)\n        .def(\"__mul__\", &mul22<double, T>)\n        .def(\"__rmul__\", &rmul22<float, T>)\n        .def(\"__rmul__\", &rmul22<double, T>)\n        .def(\"__imul__\", &imul22<float, T>,return_internal_reference<>())\n        .def(\"__imul__\", &imul22<double, T>,return_internal_reference<>())\n        .def(\"__lt__\", &lessThan22<T>)\n        .def(\"__le__\", &lessThanEqual22<T>)\n        .def(\"__gt__\", &greaterThan22<T>)\n        .def(\"__ge__\", &greaterThanEqual22<T>)\n\t//.def(self_ns::str(self))\n        .def(\"__str__\",&Matrix22_str<T>)\n        .def(\"__repr__\",&Matrix22_repr<T>)\n\n         .def(\"extractEuler\", &extractEuler<T>, \t\t\t\t\n              \"M.extractEuler(r) -- extracts the \"\n\t\t\t  \"rotation component of M into r. \"\n              \"Assumes that M contains no shear or \"\n              \"non-uniform scaling; results are \"\n              \"meaningless if it does.\")\n              \n         .def(\"multDirMatrix\", &multDirMatrix22<double,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix22_return_value<double,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix22_array<double,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix22<float,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix22_return_value<float,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix22_array<float,T>, \"mult matrix\")\n\n         .def(\"rotate\", &rotate22<T>, return_internal_reference<>(),\"rotate matrix\")\n\n         .def(\"scale\", &scaleSc22<T>, return_internal_reference<>(),\"scale matrix\")\n         .def(\"scale\", &scaleV22<T>, return_internal_reference<>(),\"scale matrix\")\n         .def(\"scale\", &scale22Tuple<T>, return_internal_reference<>(),\"scale matrix\")\n\n         .def(\"setRotation\", &setRotation22<T>, return_internal_reference<>(),\"setRotation()\")\n         .def(\"setScale\", &setScaleSc22<T>, return_internal_reference<>(),\"setScale()\")\n         .def(\"setScale\", &setScaleV22<T>, return_internal_reference<>(),\"setScale()\")\n         .def(\"setScale\", &setScale22Tuple<T>, return_internal_reference<>(),\"setScale()\")\n\n         .def(\"setValue\", &setValue22<T>, \"setValue()\")\n         ;\n\n    decoratecopy(matrix22_class);\n\n    return matrix22_class;\n/*\n    const Matrix22 &\toperator = (const Matrix22 &v);\n    const Matrix22 &\toperator = (T a);\n    T *\t\t\tgetValue ();\n    const T *\t\tgetValue () const;\n    template <class S> void getValue (Matrix22<S> &v) const;\n    template <class S> Matrix22 & setValue (const Matrix22<S> &v);\n    template <class S> Matrix22 & setTheMatrix (const Matrix22<S> &v);\n    template <class S> void multVecMatrix(const Vec2<S> &src, Vec2<S> &dst) const;\n    template <class S> void multDirMatrix(const Vec2<S> &src, Vec2<S> &dst) const;\n    template <class S> const Matrix22 &\tsetRotation (S r);\n    template <class S> const Matrix22 &\trotate (S r);\n    const Matrix22 &\tsetScale (T s);\n    template <class S> const Matrix22 &\tsetScale (const Vec2<S> &s);\n    template <class S> const Matrix22 &\tscale (const Vec2<S> &s);\n    template <class S> const Matrix22 &\tsetTranslation (const Vec2<S> &t);\n    Vec2<T>\t\ttranslation () const;\n    template <class S> const Matrix22 &\ttranslate (const Vec2<S> &t);\n    template <class S> const Matrix22 &\tsetShear (const S &h);\n    template <class S> const Matrix22 &\tsetShear (const Vec2<S> &h);\n    template <class S> const Matrix22 &\tshear (const S &xy);\n    template <class S> const Matrix22 &\tshear (const Vec2<S> &h);\n*/\n}\n\ntemplate <class T>\nstatic void\nsetM22ArrayItem(FixedArray<IMATH_NAMESPACE::Matrix22<T> > &ma,\n                Py_ssize_t index,\n                const IMATH_NAMESPACE::Matrix22<T> &m)\n{\n    ma[ma.canonical_index(index)] = m;\n}\n\ntemplate <class T>\nclass_<FixedArray<IMATH_NAMESPACE::Matrix22<T> > >\nregister_M22Array()\n{\n    class_<FixedArray<IMATH_NAMESPACE::Matrix22<T> > > matrixArray_class = FixedArray<IMATH_NAMESPACE::Matrix22<T> >::register_(\"Fixed length array of IMATH_NAMESPACE::Matrix22\");\n    matrixArray_class\n         .def(\"__setitem__\", &setM22ArrayItem<T>)\n        ;\n    return matrixArray_class;\n}\n\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Matrix22<float> > register_Matrix22<float>();\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Matrix22<double> > register_Matrix22<double>();\n\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Matrix22<float> > > register_M22Array<float>();\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Matrix22<double> > > register_M22Array<double>();\n\n\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Matrix22<float> FixedArrayDefaultValue<IMATH_NAMESPACE::Matrix22<float> >::value() { return IMATH_NAMESPACE::Matrix22<float>(); }\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Matrix22<double> FixedArrayDefaultValue<IMATH_NAMESPACE::Matrix22<double> >::value() { return IMATH_NAMESPACE::Matrix22<double>(); }\n}\n", "meta": {"hexsha": "296e97eb934a6792e4c78452d35002683c7dbf02", "size": 22555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathMatrix22.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/PyImathMatrix22.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/PyImathMatrix22.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": 30.6037991859, "max_line_length": 179, "alphanum_fraction": 0.6296608291, "num_tokens": 6519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.02517883941468303, "lm_q1q2_score": 0.008337210751150032}}
{"text": "#include <skelly_sim.hpp>\n\n#include <rng.hpp>\n\n#include <Eigen/Core>\n#include <fstream>\n#include <unordered_map>\n\n#include <body.hpp>\n#include <fiber.hpp>\n#include <params.hpp>\n#include <parse_util.hpp>\n#include <periphery.hpp>\n#include <solver_hydro.hpp>\n#include <system.hpp>\n\n#include <mpi.h>\n#include <sys/mman.h>\n\n#include <spdlog/cfg/env.h>\n#include <spdlog/sinks/null_sink.h>\n#include <spdlog/sinks/stdout_color_sinks.h>\n#include <spdlog/spdlog.h>\n\nnamespace System {\nParams params_;                    ///< Simulation input parameters\nFiberContainer fc_;                ///< Fibers\nBodyContainer bc_;                 ///< Bodies\nstd::unique_ptr<Periphery> shell_; ///< Periphery\nstd::ofstream ofs_;                ///< Trajectory output file stream. Opened at initialization\n\nFiberContainer fc_bak_;   ///< Copy of fibers for timestep reversion\nBodyContainer bc_bak_;    ///< Copy of bodies for timestep reversion\nint rank_;                ///< MPI rank\nint size_;                ///< MPI size\ntoml::value param_table_; ///< Parsed input table\n\n/// @brief Time varying system properties that are extrinsic to the physical objects\nstruct {\n    double dt;         ///< Current timestep size\n    double time = 0.0; ///< Current system time\n} properties;\n\n/// @brief Structure for trajectory output via msgpack\n///\n/// This can be extended easily, so long as you update the corresponding input_map_t and potentially the System::write()\n/// function if you can't use a reference in the output_map for some reason.\ntypedef struct output_map_t {\n    double &time = properties.time;                          ///< System::properties\n    double &dt = properties.dt;                              ///< System::properties\n    FiberContainer &fibers = fc_;                            ///< System::fc_\n    BodyContainer &bodies = bc_;                             ///< System::bc_\n    std::pair<std::string, std::string> rng_state;           ///< string representation of split/unsplit state in RNG\n    MSGPACK_DEFINE_MAP(time, dt, rng_state, fibers, bodies); ///< Helper routine to specify serialization\n} output_map_t;\noutput_map_t output_map; ///< Output data for msgpack dump\n\n/// @brief Structure for importing frame of trajectory into the simulation\n///\n/// We can't use output_map_t here, but rather a similar struct which uses copies of the member\n/// variables (rather than references) which are then used to update the System variables.\ntypedef struct input_map_t {\n    double time;                                             ///< System::properties\n    double dt;                                               ///< System::properties\n    FiberContainer fibers;                                   ///< System::fc_\n    BodyContainer bodies;                                    ///< System::bc_\n    std::pair<std::string, std::string> rng_state;           ///< string representation of split/unsplit state in RNG\n    MSGPACK_DEFINE_MAP(time, dt, rng_state, fibers, bodies); ///< Helper routine to specify serialization\n} input_map_t;\n\n/// Flush current simulation state to trajectory file.\nvoid write() {\n    output_map.rng_state = RNG::dump_state();\n    msgpack::pack(ofs_, output_map);\n    ofs_.flush();\n}\n\n/// @brief Set system state to last state found in trajectory files\n///\n/// @param[in] if_file input file name of trajectory file for this rank\nvoid resume_from_trajectory(std::string if_file) {\n    int fd = open(if_file.c_str(), O_RDONLY);\n    if (fd == -1)\n        throw std::runtime_error(\"Unable to open trajectory file \" + if_file + \" for resume.\");\n\n    struct stat sb;\n    if (fstat(fd, &sb) == -1)\n        throw std::runtime_error(\"Error statting \" + if_file + \" for resume.\");\n\n    std::size_t buflen = sb.st_size;\n\n    const char *addr = static_cast<const char *>(mmap(NULL, buflen, PROT_READ, MAP_PRIVATE, fd, 0u));\n    if (addr == MAP_FAILED)\n        throw std::runtime_error(\"Error mapping \" + if_file + \" for resume.\");\n\n    std::size_t offset = 0;\n    msgpack::object_handle oh;\n    // FIXME: There is probably a way to not have to read the entire trajectory\n    while (offset != buflen)\n        msgpack::unpack(oh, addr, buflen, offset);\n\n    // FIXME: add assertion that system time is the same across all ranks to resume functionality\n\n    // FIXME: This is a bug-prone way to unpack. Should make proper clone functions that merge\n    // the minimum representation with existing data automatically (node data, etc)\n    msgpack::object obj = oh.get();\n    input_map_t const &min_state = obj.as<input_map_t>();\n    output_map.time = min_state.time;\n    output_map.dt = min_state.dt;\n    fc_.fibers.clear();\n    for (const auto &min_fib : min_state.fibers.fibers) {\n        Fiber new_fib = min_fib;\n        new_fib.init(params_.eta);\n        new_fib.x_ = min_fib.x_;\n        fc_.fibers.push_back(new_fib);\n    }\n    for (int i = 0; i < bc_.bodies.size(); ++i) {\n        bc_.bodies[i]->position_ = min_state.bodies.bodies[i]->position_;\n        bc_.bodies[i]->orientation_ = min_state.bodies.bodies[i]->orientation_;\n    }\n    output_map.rng_state = min_state.rng_state;\n    RNG::init(output_map.rng_state);\n}\n\n// TODO: Refactor all preprocess stuff. It's awful\n\n/// @brief Convert fiber initial positions/orientations to full coordinate representation\n/// @param[out] fiber_table Explicitly instantiated element of fiber config\n/// @param[in] origin origin of coordinate system for fiber\nvoid resolve_fiber_position(toml::value &fiber_table, Eigen::Vector3d &origin) {\n    int64_t n_nodes = toml::find_or<int64_t>(fiber_table, \"n_nodes\", -1);\n    double length = toml::find<double>(fiber_table, \"length\");\n\n    Eigen::VectorXd x_array = parse_util::convert_array<>(toml::find_or<toml::array>(fiber_table, \"x\", {}));\n    Eigen::VectorXd x_0 = parse_util::convert_array<>(toml::find_or<toml::array>(fiber_table, \"relative_position\", {}));\n    Eigen::VectorXd u = parse_util::convert_array<>(toml::find_or<toml::array>(fiber_table, \"orientation\", {}));\n\n    if (n_nodes == -1) {\n        n_nodes = x_array.size() / 3;\n        if (n_nodes == 0)\n            throw std::runtime_error(\"Attempt to initialize fiber without point count or positions.\");\n    }\n\n    if ((x_array.size() && x_0.size()) || (x_array.size() && u.size()))\n        throw std::runtime_error(\"Fiber supplied 'relative_position' or 'orientation' with node positions 'x', \"\n                                 \"ambiguous initialization.\");\n\n    // FIXME: Make test for this case\n    if (x_0.size() == 3 && u.size() == 3) {\n        Eigen::MatrixXd x(3, n_nodes);\n        Eigen::ArrayXd s = Eigen::ArrayXd::LinSpaced(n_nodes, 0, length).transpose();\n        for (int i = 0; i < 3; ++i)\n            x.row(i) = origin(i) + x_0(i) + u(i) * s;\n\n        fiber_table.as_table()[\"x\"] = toml::array();\n        toml::array &x_tab = fiber_table.at(\"x\").as_array();\n        for (int i = 0; i < x.size(); ++i) {\n            x_tab.push_back(x.data()[i]);\n        }\n    }\n}\n\n/// @brief Generate uniformly distributed point on unit sphere\nEigen::Vector3d uniform_on_sphere() {\n    const double u = 2 * (RNG::uniform_unsplit()) - 1;\n    const double theta = 2 * M_PI * RNG::uniform_unsplit();\n    const double factor = sqrt(1 - u * u);\n    return Eigen::Vector3d{factor * cos(theta), factor * sin(theta), u};\n}\n\n/// @brief Update config to appropriately fill nucleation sites with fibers\n/// @param[out] fiber_array Updated fiber array with pointers to nucleation sites\n/// @param[out] body_array Updated body array with nucleation sites fixed to current fiber position\nvoid resolve_nucleation_sites(toml::array &fiber_array, toml::array &body_array) {\n    using std::make_pair;\n    const int n_bodies = body_array.size();\n    std::map<std::pair<int, int>, int> occupied;\n    std::vector<int> n_sites(n_bodies);\n\n    // Pass through fibers for assigned bodies\n    for (size_t i_fib = 0; i_fib < fiber_array.size(); ++i_fib) {\n        toml::value &fiber_table = fiber_array.at(i_fib);\n        int i_body = toml::find_or<int>(fiber_table, \"parent_body\", -1);\n        int i_site = toml::find_or<int>(fiber_table, \"parent_site\", -1);\n\n        if (i_body >= n_bodies) {\n            std::cerr << \"Invalid body reference \" << i_body << \" on fiber \" << i_fib << \": \\n\"\n                      << fiber_table << std::endl;\n            throw std::runtime_error(\"Invalid body reference.\\n\");\n        }\n\n        // unattached or site find automated. move to next fiber\n        if (i_body < 0 || i_site < 0)\n            continue;\n\n        // check for duplicate assignment\n        auto site_pair = make_pair(i_body, i_site);\n        if (occupied.count(site_pair) > 0) {\n            const int j_fib = occupied[site_pair];\n            // clang-format off\n                std::cerr << \"Multiple fibers bound to site: (\"\n                          << i_body << \", \" << i_site << \")\"\n                          << \" from fibers (\" << i_fib << \", \" << j_fib << \") \" << \".\\n\"\n                          << fiber_table << \"\\n\\n\" << fiber_array.at(j_fib) << \"\\n\";\n                throw std::runtime_error(\"Multiple fibers bound to site.\\n\");\n            // clang-format on\n        }\n\n        occupied[site_pair] = i_fib;\n    }\n\n    // Pass through fibers for unassigned bodies\n    std::vector<int> test_site(n_bodies); //< current site to try for insertion\n    for (size_t i_fib = 0; i_fib < fiber_array.size(); ++i_fib) {\n        toml::value &fiber_table = fiber_array.at(i_fib);\n        int i_body = toml::find_or<int>(fiber_table, \"parent_body\", -1);\n        int i_site = toml::find_or<int>(fiber_table, \"parent_site\", -1);\n\n        // unattached or site already assigned. move to next fiber\n        if (i_body < 0 || i_site >= 0) {\n            Eigen::Vector3d origin{0.0, 0.0, 0.0};\n            if (i_body < 0) // Initialize free fiber\n                resolve_fiber_position(fiber_table, origin);\n            continue;\n        }\n\n        // Find an empty site\n        while (occupied.count(make_pair(i_body, test_site[i_body])) != 0)\n            test_site[i_body]++;\n\n        // Store in map so body knows where to grab\n        occupied[make_pair(i_body, test_site[i_body])] = i_fib;\n    }\n\n    std::vector<std::map<int, Eigen::Vector3d>> nucleation_sites(n_bodies);\n    for (const auto &site_map : occupied) {\n        auto [i_body, i_site] = site_map.first;\n        auto i_fib = site_map.second;\n        toml::value &fiber_table = fiber_array.at(i_fib);\n        toml::array &body_position = body_array.at(i_body).at(\"position\").as_array();\n\n        fiber_table[\"parent_body\"] = i_body;\n        fiber_table[\"parent_site\"] = i_site;\n        Eigen::Vector3d origin = parse_util::convert_array<>(body_position);\n\n        resolve_fiber_position(fiber_table, origin);\n\n        if (fiber_table.contains(\"x\")) {\n            Eigen::VectorXd x_array = parse_util::convert_array<>(fiber_table.at(\"x\").as_array());\n            nucleation_sites[i_body][i_site] = x_array.segment(0, 3) - origin;\n        }\n    }\n\n    for (int i_body = 0; i_body < n_bodies; ++i_body) {\n        toml::value &body_table = body_array.at(i_body);\n        if (!body_table.contains(\"nucleation_sites\"))\n            body_table[\"nucleation_sites\"] = toml::array();\n\n        int n_nucleation_sites = toml::find_or<int>(body_table, \"n_nucleation_sites\", nucleation_sites[i_body].size());\n        double radius = body_table[\"radius\"].as_floating();\n        // FIXME: add min_separation parameter\n        const double min_separation2 = pow(params_.dynamic_instability.min_separation, 2);\n\n        for (int i = 0; i < n_nucleation_sites; ++i) {\n            if (nucleation_sites[i_body].count(i))\n                continue;\n\n            bool collision = false;\n            do {\n                collision = false;\n                nucleation_sites[i_body][i] = radius * uniform_on_sphere();\n                Eigen::Vector3d &r_i = nucleation_sites[i_body][i];\n\n                for (auto &j_pair : nucleation_sites[i_body]) {\n                    const int &j = j_pair.first;\n                    const Eigen::Vector3d &r_j = j_pair.second;\n                    if (i == j)\n                        continue;\n                    Eigen::Vector3d dr = r_j - r_i;\n                    double dr2 = dr.dot(dr);\n                    if (dr2 < min_separation2) {\n                        collision = true;\n                        break;\n                    }\n                }\n            } while (collision);\n        }\n\n        toml::array &x = body_table[\"nucleation_sites\"].as_array();\n        for (auto &[site, xvec] : nucleation_sites[i_body])\n            for (int i = 0; i < 3; ++i)\n                x.push_back(xvec[i]);\n    }\n\n    for (const auto &site_map : occupied) {\n        auto [i_body, i_site] = site_map.first;\n        auto i_fib = site_map.second;\n        toml::value &fiber_table = fiber_array.at(i_fib);\n        toml::array &body_position = body_array.at(i_body).at(\"position\").as_array();\n        toml::array &nucleation_sites = body_array.at(i_body).at(\"nucleation_sites\").as_array();\n\n        fiber_table[\"parent_body\"] = i_body;\n        fiber_table[\"parent_site\"] = i_site;\n        Eigen::Vector3d origin = parse_util::convert_array<>(body_position);\n        Eigen::VectorXd sites = parse_util::convert_array<>(nucleation_sites);\n\n        if (!fiber_table.contains(\"x\")) {\n            Eigen::Vector3d site_pos = Eigen::Map<Eigen::Vector3d>(sites.data() + i_site * 3, 3);\n            Eigen::Vector3d fiber_origin = site_pos;\n            Eigen::Vector3d fiber_orientation = fiber_origin.normalized();\n            fiber_table[\"relative_position\"] = {fiber_origin[0], fiber_origin[1], fiber_origin[2]};\n            fiber_table[\"orientation\"] = {fiber_orientation[0], fiber_orientation[1], fiber_orientation[2]};\n\n            resolve_fiber_position(fiber_table, origin);\n        }\n    }\n}\n\n/// @file\n/// @brief Initialize classes with proper interdependencies\n\n/// @brief Patch up input toml config to go from implicit to explicit instantiations\n///\n/// Some classes have interdependencies, but in order to avoid the objects having explicit\n/// dependencies on each other through initialization while maintaining a simple config format,\n/// we preprocess the toml config to have TOML communicate these dependencies by explicitly\n/// instantiating config values.\n///\n/// The main example of the utility of this approach is Fiber-Body connections through\n/// \"nucleation sites\". The body nucleation site is _constrained_ to be at the same position as\n/// its associated Fiber minus end. Ultimately the Body doesn't care what Fiber it's attached\n/// to, just that it has nucleation sites that rotate/move with it. The Fibers, however, have\n/// to know which Body they're attached to to constrain their motion. Rather than forcing the\n/// user to supply the Fiber minus end and which (body,site) combo it sits at on the Fiber\n/// object to the body object, and the nucleation site coordinates in an ordered array on the\n/// body object, it's much easier for the user to simply supply a fiber and a body it's attached\n/// to, and then automatically sort out the interconnections programmatically.\n///\n/// This presents an ordering problem for initialization though, since the FiberContainer needs\n/// to communicate the nucleation positions to the BodyContainer, but the BodyContainer needs\n/// to communicate what (body,site) combo the Fiber is attached to back to the\n/// FiberContainer. If you initialize the bodies first, they won't know how to initialize\n/// nucleation sites. If you initialize fibers first, they have to communicate the bodies\n/// they're attached to the body objects and then get a response on what site they are\n/// assigned. This initialization cycle can be removed by just preprocessing the config so that\n/// all data on all MPI ranks is consistent at system initialization time, and all objects know\n/// the relevant data to fully initialize at object creation time.\n///\n/// @param[out] config global toml config after initial parsing\nvoid preprocess(toml::value &config) {\n    spdlog::info(\"Preprocessing config file\");\n\n    // Body-fiber interactions through nucleation sites\n    if (config.contains(\"fibers\") && config.contains(\"bodies\"))\n        resolve_nucleation_sites(config[\"fibers\"].as_array(), config[\"bodies\"].as_array());\n    else if (config.contains(\"fibers\")) {\n        toml::array &fiber_array = config[\"fibers\"].as_array();\n        for (size_t i_fib = 0; i_fib < fiber_array.size(); ++i_fib) {\n            toml::value &fiber_table = fiber_array.at(i_fib);\n            Eigen::Vector3d origin{0.0, 0.0, 0.0};\n            resolve_fiber_position(fiber_table, origin);\n        }\n    }\n}\n\n/// @brief Calculate forces/torques on the bodies and velocities on the fibers due to attachment constraints\n/// @param[in] fibers_xt [4 x num_fiber_nodes_local] Vector of fiber node positions and tensions on current rank.\n/// Ordering is [fib1.nodes.x, fib1.nodes.y, fib1.nodes.z, fib1.T, fib2.nodes.x, ...]\n/// @param[in] body_velocities [6 x n_bodies] Matrix of body center of mass velocities and angular velocities\nstd::pair<Eigen::MatrixXd, Eigen::MatrixXd> calculate_body_fiber_link_conditions(VectorRef &fibers_xt,\n                                                                                 MatrixRef &body_velocities) {\n    using Eigen::ArrayXXd;\n    using Eigen::MatrixXd;\n    using Eigen::Vector3d;\n\n    auto &fc = fc_;\n    auto &bc = bc_;\n\n    Eigen::MatrixXd force_torque_on_bodies = MatrixXd::Zero(6, bc.get_global_count());\n    Eigen::MatrixXd velocities_on_fiber = MatrixXd::Zero(7, fc.get_local_count());\n\n    int xt_offset = 0;\n    int i_fib = 0;\n    for (const auto &fib : fc.fibers) {\n        const auto &fib_mats = fib.matrices_.at(fib.n_nodes_);\n        const int n_pts = fib.n_nodes_;\n\n        auto &[i_body, i_site] = fib.binding_site_;\n        if (i_body < 0)\n            continue;\n\n        Vector3d site_pos = bc.get_nucleation_site(i_body, i_site) - bc.at(i_body).get_position();\n        MatrixXd x_new(3, fib.n_nodes_);\n        x_new.row(0) = fibers_xt.segment(xt_offset + 0 * fib.n_nodes_, fib.n_nodes_);\n        x_new.row(1) = fibers_xt.segment(xt_offset + 1 * fib.n_nodes_, fib.n_nodes_);\n        x_new.row(2) = fibers_xt.segment(xt_offset + 2 * fib.n_nodes_, fib.n_nodes_);\n\n        double T_new_0 = fibers_xt(xt_offset + 3 * n_pts);\n\n        Vector3d xs_0 = fib.xs_.col(0);\n        Eigen::MatrixXd xss_new = pow(2.0 / fib.length_, 2) * x_new * fib_mats.D_2_0;\n        Eigen::MatrixXd xsss_new = pow(2.0 / fib.length_, 3) * x_new * fib_mats.D_3_0;\n        Vector3d xss_new_0 = xss_new.col(0);\n        Vector3d xsss_new_0 = xsss_new.col(0);\n\n        // FIRST FROM FIBER ON-TO BODY\n        // Force by fiber on body at s = 0, Fext = -F|s=0 = -(EXsss - TXs)\n        // Bending term + Tension term:\n        Vector3d F_body = -fib.bending_rigidity_ * xsss_new_0 + xs_0 * T_new_0;\n\n        // Torque by fiber on body at s = 0\n        // Lext = (L + link_loc x F) = -E(Xss x Xs) - link_loc x (EXsss - TXs)\n        // bending contribution :\n        Vector3d L_body = -fib.bending_rigidity_ * site_pos.cross(xsss_new_0);\n\n        // tension contribution :\n        L_body += site_pos.cross(xs_0) * T_new_0;\n\n        // fiber's torque L:\n        L_body += fib.bending_rigidity_ * xs_0.cross(xss_new_0);\n\n        // Store the contribution of each fiber in this array\n        force_torque_on_bodies.col(i_body).segment(0, 3) += F_body;\n        force_torque_on_bodies.col(i_body).segment(3, 3) += L_body;\n\n        // SECOND FROM BODY ON-TO FIBER\n        // Translational and angular velocities at the attachment point are calculated\n        Vector3d v_body = body_velocities.block(0, i_body, 3, 1);\n        Vector3d w_body = body_velocities.block(3, i_body, 3, 1);\n\n        // dx/dt = U + Omega x link_loc (move to LHS so -U -Omega x link_loc)\n        Vector3d v_fiber = -v_body - w_body.cross(site_pos);\n\n        // tension condition = -(xs*vx + ys*vy + zs*wz)\n        double tension_condition = -xs_0.dot(v_body) + (xs_0.cross(site_pos)).dot(w_body);\n\n        // Rotational velocity condition on fiber\n        // FIXME: Fiber torque assumes body is a sphere :(\n        Vector3d w_fiber = site_pos.normalized().cross(w_body);\n\n        velocities_on_fiber.block(0, i_fib, 3, 1) = v_fiber;\n        velocities_on_fiber(3, i_fib) = tension_condition;\n        velocities_on_fiber.block(4, i_fib, 3, 1) = w_fiber;\n\n        i_fib++;\n        xt_offset += 4 * n_pts;\n    }\n\n    // Sum up fiber contributions from all other ranks to body torques\n    MPI_Allreduce(MPI_IN_PLACE, force_torque_on_bodies.data(), force_torque_on_bodies.size(), MPI_DOUBLE, MPI_SUM,\n                  MPI_COMM_WORLD);\n\n    return std::make_pair(force_torque_on_bodies, velocities_on_fiber);\n}\n\n/// @brief Get number of physical nodes local to MPI rank for each object type [fibers, shell, bodies]\nstd::tuple<int, int, int> get_local_node_counts() {\n    return std::make_tuple(fc_.get_local_node_count(), shell_->get_local_node_count(), bc_.get_local_node_count());\n}\n\n/// @brief Get GMRES solution size local to MPI rank for each object type [fibers, shell, bodies]\nstd::tuple<int, int, int> get_local_solution_sizes() {\n    return std::make_tuple(fc_.get_local_solution_size(), shell_->get_local_solution_size(),\n                           bc_.get_local_solution_size());\n}\n\n/// @brief Map 1D array data to a three-tuple of Vector Maps [fibers, shell, bodies]\nstd::tuple<VectorMap, VectorMap, VectorMap> get_solution_maps(double *x) {\n    using Eigen::Map;\n    using Eigen::VectorXd;\n    auto [fib_sol_size, shell_sol_size, body_sol_size] = System::get_local_solution_sizes();\n    return std::make_tuple(VectorMap(x, fib_sol_size), VectorMap(x + fib_sol_size, shell_sol_size),\n                           VectorMap(x + fib_sol_size + shell_sol_size, body_sol_size));\n}\n\n/// @brief Map 1D array data to a three-tuple of const Vector Maps [fibers, shell, bodies]\nstd::tuple<CVectorMap, CVectorMap, CVectorMap> get_solution_maps(const double *x) {\n    using Eigen::Map;\n    using Eigen::VectorXd;\n    auto [fib_sol_size, shell_sol_size, body_sol_size] = System::get_local_solution_sizes();\n    return std::make_tuple(CVectorMap(x, fib_sol_size), CVectorMap(x + fib_sol_size, shell_sol_size),\n                           CVectorMap(x + fib_sol_size + shell_sol_size, body_sol_size));\n}\n\n/// @brief Map Eigen Matrix node data to a three-tuple of Matrix Block references (use like view)\n///\n/// @param[in] x [3 x n_nodes_local] Matrix where you want the views\n/// @return Three-tuple of node data [3 x n_fiber_nodes, 3 x n_bodiy_nodes, 3 x n_periphery_nodes]\ntemplate <typename Derived>\nstd::tuple<Eigen::Block<Derived>, Eigen::Block<Derived>, Eigen::Block<Derived>>\nget_node_maps(Eigen::MatrixBase<Derived> &x) {\n    auto [fib_nodes, shell_nodes, body_nodes] = get_local_node_counts();\n    return std::make_tuple(Eigen::Block<Derived>(x.derived(), 0, 0, 3, fib_nodes),\n                           Eigen::Block<Derived>(x.derived(), 0, fib_nodes, 3, shell_nodes),\n                           Eigen::Block<Derived>(x.derived(), 0, fib_nodes + shell_nodes, 3, body_nodes));\n}\n\n/// @brief Apply and return preconditioner results from fibers/body/shell\n///\n/// \\f[ P^{-1} * x = y \\f]\n/// @param [in] x [local_solution_size] Vector to apply preconditioner on\n/// @return [local_solution_size] Preconditioned input vector\nEigen::VectorXd apply_preconditioner(VectorRef &x) {\n    const auto [fib_sol_size, shell_sol_size, body_sol_size] = get_local_solution_sizes();\n    const int sol_size = fib_sol_size + shell_sol_size + body_sol_size;\n    assert(sol_size == x.size());\n    Eigen::VectorXd res(sol_size);\n\n    auto [x_fibers, x_shell, x_bodies] = get_solution_maps(x.data());\n    auto [res_fibers, res_shell, res_bodies] = get_solution_maps(res.data());\n\n    res_fibers = fc_.apply_preconditioner(x_fibers);\n    res_shell = shell_->apply_preconditioner(x_shell);\n    res_bodies = bc_.apply_preconditioner(x_bodies);\n\n    return res;\n}\n\n/// @brief Nucleate/grow/destroy Fibers based on dynamic instability rules. See white paper for details\n///\n/// Modifies:\n/// - FiberContainer::fibers [for nucleation/catastrophe]\n/// - Fiber::v_growth_\n/// - Fiber::length_\n/// - Fiber::length_prev_\nvoid dynamic_instability() {\n    const double dt = properties.dt;\n    FiberContainer &fc = fc_;\n    BodyContainer &bc = bc_;\n    Params &params = params_;\n    if (params_.dynamic_instability.n_nodes == 0)\n        return;\n\n    size_t n_sites = 0;\n    std::vector<int> body_offsets(bc.bodies.size() + 1);\n    int i_body = 0;\n    for (const auto &body : bc.bodies) {\n        n_sites += body->nucleation_sites_.cols();\n        body_offsets[i_body + 1] = body_offsets[i_body] + body->nucleation_sites_.cols();\n        i_body++;\n    }\n\n    auto site_index = [&body_offsets](std::pair<int, int> binding_site) -> int {\n        assert(binding_site.first >= 0 && binding_site.second >= 0);\n        return body_offsets[binding_site.first] + binding_site.second;\n    };\n\n    auto binding_site_from_index = [&body_offsets](int index) -> std::pair<int, int> {\n        for (size_t i_body = 0; i_body < body_offsets.size() - 1; ++i_body) {\n            if (index < body_offsets[i_body + 1]) {\n                return {i_body, index - body_offsets[i_body]};\n            }\n        }\n        return {-1, -1};\n    };\n\n    std::vector<uint8_t> occupied_flat(bc.get_global_site_count(), 0);\n    auto fib = fc.fibers.begin();\n    while (fib != fc.fibers.end()) {\n        fib->v_growth_ = params.dynamic_instability.v_growth;\n        double f_cat = params.dynamic_instability.f_catastrophe;\n        if (fib->near_periphery) {\n            fib->v_growth_ *= params.dynamic_instability.v_grow_collision_scale;\n            f_cat *= params.dynamic_instability.f_catastrophe_collision_scale;\n        }\n\n        if (RNG::uniform() > exp(-dt * f_cat)) {\n            fib = fc.fibers.erase(fib);\n        } else {\n            if (fib->attached_to_body())\n                occupied_flat[site_index(fib->binding_site_)] = 1;\n            fib->length_prev_ = fib->length_;\n            fib->length_ += dt * fib->v_growth_;\n            fib++;\n        }\n    }\n\n    MPI_Reduce(rank_ == 0 ? MPI_IN_PLACE : occupied_flat.data(), occupied_flat.data(), occupied_flat.size(), MPI_BYTE,\n               MPI_LOR, 0, MPI_COMM_WORLD);\n\n    std::unordered_map<int, bool> active_sites;\n    std::unordered_map<int, bool> inactive_sites;\n    std::vector<std::pair<int, int>> to_nucleate;\n    if (rank_ == 0) {\n        for (size_t i = 0; i < occupied_flat.size(); ++i) {\n            if (occupied_flat[i])\n                active_sites[i] = true;\n            else\n                inactive_sites[i] = true;\n        }\n\n        // FIXME: Is this right? I feel like the nucleation rate should be proportional to the\n        // sites, or the area, or something rather than a global parameter\n        int n_to_nucleate = std::min(RNG::poisson_int(dt * params.dynamic_instability.nucleation_rate),\n                                     static_cast<int>(inactive_sites.size()));\n        int n_trials = 100;\n        while (n_to_nucleate && n_trials) {\n            int passive_site_index =\n                std::next(inactive_sites.begin(), RNG::uniform_int(0, inactive_sites.size()))->first;\n\n            auto [i_body, i_site] = binding_site_from_index(passive_site_index);\n            Eigen::Vector3d site_pos_i = bc.at(i_body).nucleation_sites_.col(i_site);\n            bool valid_site = true;\n            const double min_ds2 = pow(params.dynamic_instability.min_separation, 2);\n            for (auto &[active_site_index, dum] : active_sites) {\n                auto [j_body, j_site] = binding_site_from_index(active_site_index);\n                Eigen::Vector3d site_pos_j = bc.at(j_body).nucleation_sites_.col(j_site);\n\n                if ((site_pos_j - site_pos_i).squaredNorm() < min_ds2) {\n                    valid_site = false;\n                    break;\n                }\n            }\n\n            if (valid_site) {\n                n_trials = 100;\n                active_sites[passive_site_index] = true;\n                inactive_sites.erase(passive_site_index);\n                to_nucleate.push_back({i_body, i_site});\n                n_to_nucleate--;\n            } else {\n                n_trials--;\n            }\n        }\n    }\n\n    int n_fibers = fc.fibers.size();\n    std::vector<int> fiber_counts(rank_ == 0 ? size_ : 0);\n    MPI_Gather(&n_fibers, 1, MPI_INT, fiber_counts.data(), 1, MPI_INT, 0, MPI_COMM_WORLD);\n\n    using fiber_struct = struct {\n        int rank;\n        std::pair<int, int> binding_site;\n    };\n\n    std::vector<fiber_struct> new_fibers;\n    for (const auto &binding_site : to_nucleate) {\n        const int fiber_rank = std::min_element(fiber_counts.begin(), fiber_counts.end()) - fiber_counts.begin();\n        new_fibers.push_back({fiber_rank, binding_site});\n        spdlog::info(\"Queueing fiber insertion to rank {} to site [{}, {}]\", fiber_rank, binding_site.first,\n                     binding_site.second);\n        fiber_counts[fiber_rank]++;\n    }\n\n    int n_new = new_fibers.size();\n    MPI_Bcast(&n_new, 1, MPI_INT, 0, MPI_COMM_WORLD);\n    new_fibers.resize(n_new);\n    MPI_Bcast(new_fibers.data(), sizeof(fiber_struct) * new_fibers.size(), MPI_CHAR, 0, MPI_COMM_WORLD);\n    if (n_new)\n        spdlog::info(\"Sent {} fibers to nucleate\", new_fibers.size());\n\n    for (const auto &min_fib : new_fibers) {\n        if (min_fib.rank == rank_) {\n            Fiber fib(params.dynamic_instability.n_nodes, params.dynamic_instability.bending_rigidity, params.eta);\n            fib.length_ = params.dynamic_instability.min_length;\n            fib.length_prev_ = params.dynamic_instability.min_length;\n            fib.v_growth_ = 0.0;\n            fib.binding_site_ = min_fib.binding_site;\n\n            Eigen::MatrixXd x(3, fib.n_nodes_);\n            Eigen::ArrayXd s = Eigen::ArrayXd::LinSpaced(fib.n_nodes_, 0, fib.length_).transpose();\n            Eigen::Vector3d origin = bc_.get_nucleation_site(fib.binding_site_.first, fib.binding_site_.second);\n            Eigen::Vector3d u = (origin - bc_.bodies[fib.binding_site_.first]->position_).normalized();\n\n            for (int i = 0; i < 3; ++i)\n                fib.x_.row(i) = origin(i) + u(i) * s;\n\n            fc.fibers.push_back(fib);\n            spdlog::get(\"SkellySim global\")\n                ->info(\"Inserted fiber on rank {} at site [{}, {}]\", rank_, min_fib.binding_site.first,\n                       min_fib.binding_site.second);\n        }\n    }\n}\n\n/// @brief Apply and return entire operator on system state vector for fibers/body/shell\n///\n/// \\f[ A * x = y \\f]\n/// @param [in] x [local_solution_size] Vector to apply matvec on\n/// @return [local_solution_size] Vector y, the result of the operator applied to x.\nEigen::VectorXd apply_matvec(VectorRef &x) {\n    using Eigen::Block;\n    using Eigen::MatrixXd;\n    const FiberContainer &fc = fc_;\n    const Periphery &shell = *shell_;\n    const BodyContainer &bc = bc_;\n    const double eta = params_.eta;\n\n    const auto [fib_node_count, shell_node_count, body_node_count] = get_local_node_counts();\n    const int total_node_count = fib_node_count + shell_node_count + body_node_count;\n\n    const auto [fib_sol_size, shell_sol_size, body_sol_size] = get_local_solution_sizes();\n    const int sol_size = fib_sol_size + shell_sol_size + body_sol_size;\n    assert(sol_size == x.size());\n    Eigen::VectorXd res(sol_size);\n\n    MatrixXd r_all(3, total_node_count), v_all(3, total_node_count);\n    auto [r_fibers, r_shell, r_bodies] = get_node_maps(r_all);\n    auto [v_fibers, v_shell, v_bodies] = get_node_maps(v_all);\n    r_fibers = fc.get_local_node_positions();\n    r_shell = shell.get_local_node_positions();\n    r_bodies = bc.get_local_node_positions();\n\n    auto [x_fibers, x_shell, x_bodies] = get_solution_maps(x.data());\n    auto [res_fibers, res_shell, res_bodies] = get_solution_maps(res.data());\n\n    // calculate fiber-fiber velocity\n    MatrixXd fw = fc.apply_fiber_force(x_fibers);\n    Block<MatrixXd> r_shellbody = r_all.block(0, r_fibers.cols(), 3, r_shell.cols() + r_bodies.cols());\n    MatrixXd v_fib2all = fc.flow(fw, r_shellbody, eta);\n\n    MatrixXd r_fibbody(3, r_fibers.cols() + r_bodies.cols());\n    r_fibbody.block(0, 0, 3, r_fibers.cols()) = r_fibers;\n    r_fibbody.block(0, r_fibers.cols(), 3, r_bodies.cols()) = r_bodies;\n    MatrixXd v_shell2fibbody = shell.flow(r_fibbody, x_shell, eta);\n\n    MatrixXd body_velocities, body_densities, v_fib_boundary, force_torque_bodies;\n    std::tie(body_velocities, body_densities) = bc.unpack_solution_vector(x_bodies);\n    std::tie(force_torque_bodies, v_fib_boundary) =\n        System::calculate_body_fiber_link_conditions(x_fibers, body_velocities);\n\n    v_all = v_fib2all;\n    v_fibers += v_shell2fibbody.block(0, 0, 3, r_fibers.cols());\n    v_bodies += v_shell2fibbody.block(0, r_fibers.cols(), 3, r_bodies.cols());\n    v_all += bc.flow(r_all, body_densities, force_torque_bodies, eta);\n\n    res_fibers = fc.matvec(x_fibers, v_fibers, v_fib_boundary);\n    res_shell = shell.matvec(x_shell, v_shell);\n    res_bodies = bc.matvec(v_bodies, body_densities, body_velocities);\n\n    return res;\n}\n\n/// @brief Generate next trial system state for the current System::properties::dt\n///\n/// @note Modifies anything that evolves in time.\n/// @return If the Matrix solver converged to the requested tolerance with no issue.\nbool step() {\n    using Eigen::MatrixXd;\n    Params &params = params_;\n    Periphery &shell = *shell_;\n    FiberContainer &fc = fc_;\n    BodyContainer &bc = bc_;\n    const double eta = params.eta;\n    const double dt = properties.dt;\n\n    // Since DI can change size of fiber containers, must call first.\n    System::dynamic_instability();\n\n    const auto [fib_node_count, shell_node_count, body_node_count] = get_local_node_counts();\n\n    MatrixXd r_trg_external(3, shell_node_count + body_node_count);\n    r_trg_external.block(0, 0, 3, shell_node_count) = shell.get_local_node_positions();\n    r_trg_external.block(0, shell_node_count, 3, body_node_count) = bc.get_local_node_positions();\n\n    fc.update_cache_variables(dt, eta);\n\n    MatrixXd f_on_fibers = fc.generate_constant_force();\n    MatrixXd v_all = fc.flow(f_on_fibers, r_trg_external, eta);\n\n    bc.update_cache_variables(eta);\n\n    // Check for an add external body forces\n    Eigen::MatrixXd force_torque_bodies = Eigen::MatrixXd::Zero(6, bc.bodies.size());\n    for (size_t i = 0; i < bc.bodies.size(); ++i) {\n        const auto &body = bc.bodies[i];\n        force_torque_bodies.col(i).segment(0, 3) += body->external_force_;\n    }\n\n    if (force_torque_bodies.any()) {\n        const int total_node_count = fib_node_count + shell_node_count + body_node_count;\n        MatrixXd r_all(3, total_node_count);\n        auto [r_fibers, r_shell, r_bodies] = get_node_maps(r_all);\n        r_fibers = fc.get_local_node_positions();\n        r_shell = shell.get_local_node_positions();\n        r_bodies = bc.get_local_node_positions();\n\n        v_all += bc.flow(r_all, Eigen::MatrixXd::Zero(r_bodies.rows(), r_bodies.cols()), force_torque_bodies, eta);\n    }\n\n    bc.update_RHS(v_all.block(0, fib_node_count + shell_node_count, 3, body_node_count));\n\n    fc.update_RHS(dt, v_all.block(0, 0, 3, fib_node_count), f_on_fibers);\n    fc.update_boundary_conditions(shell, params.periphery_binding_flag);\n    fc.apply_bc_rectangular(dt, v_all.block(0, 0, 3, fib_node_count), f_on_fibers);\n\n    shell.update_RHS(v_all.block(0, fib_node_count, 3, shell_node_count));\n\n    Solver<P_inv_hydro, A_fiber_hydro> solver_;\n    solver_.set_RHS();\n    bool converged = solver_.solve();\n    CVectorMap sol = solver_.get_solution();\n\n    double residual = solver_.get_residual();\n    spdlog::info(\"Residual: {}\", residual);\n\n    auto [fiber_sol, shell_sol, body_sol] = get_solution_maps(sol.data());\n\n    size_t offset = 0;\n    for (auto &fib : fc.fibers) {\n        for (int i = 0; i < 3; ++i)\n            fib.x_.row(i) = sol.segment(offset + i * fib.n_nodes_, fib.n_nodes_);\n        offset += 4 * fib.n_nodes_;\n    }\n\n    Eigen::MatrixXd body_velocities, body_densities;\n    std::tie(body_velocities, body_densities) = bc.unpack_solution_vector(body_sol);\n    for (int i = 0; i < body_velocities.cols(); ++i) {\n        std::stringstream ss;\n        ss << body_velocities.col(i).transpose();\n        spdlog::debug(\"body velocities {}: [{}]\", i, ss.str());\n    }\n\n    for (int i = 0; i < bc.bodies.size(); ++i) {\n        auto &body = bc.bodies[i];\n        Eigen::Vector3d x_new = body->position_ + body_velocities.col(i).segment(0, 3) * dt;\n        Eigen::Vector3d phi = body_velocities.col(i).segment(3, 3) * dt;\n        double phi_norm = phi.norm();\n        Eigen::Quaterniond orientation_new = body->orientation_;\n        if (phi_norm) {\n            double s = std::cos(0.5 * phi_norm);\n            Eigen::Vector3d p = std::sin(0.5 * phi_norm) * phi / phi_norm;\n            orientation_new = Eigen::Quaterniond(s, p[0], p[1], p[2]) * body->orientation_;\n        }\n        std::stringstream ss;\n        ss << x_new.transpose();\n        spdlog::debug(\"Moving body {}: [{}]\", i, ss.str());\n\n        body->move(x_new, orientation_new);\n    }\n\n    // Re-pin fibers to bodies\n    for (auto &fib : fc.fibers) {\n        if (fib.binding_site_.first >= 0) {\n            Eigen::Vector3d delta =\n                bc.get_nucleation_site(fib.binding_site_.first, fib.binding_site_.second) - fib.x_.col(0);\n            fib.x_.colwise() += delta;\n        }\n    }\n\n    return converged;\n}\n\n/// @brief store copies of Fiber and Body containers in case time step is rejected\nvoid backup() {\n    fc_bak_ = fc_;\n    bc_bak_ = bc_;\n}\n\n/// @brief restore copies of Fiber and Body containers to the state when last backed up\nvoid restore() {\n    fc_ = fc_bak_;\n    bc_ = bc_bak_;\n}\n\n/// @brief Run the simulation!\nvoid run() {\n    Params &params = params_;\n\n    System::write();\n    while (properties.time < params.t_final) {\n        System::backup();\n        bool converged = System::step();\n        double fiber_error = 0.0;\n        for (const auto &fib : fc_.fibers) {\n            const auto &mats = fib.matrices_.at(fib.n_nodes_);\n            const Eigen::MatrixXd xs = std::pow(2.0 / fib.length_, 1) * fib.x_ * mats.D_1_0;\n            for (int i = 0; i < fib.n_nodes_; ++i)\n                fiber_error = std::max(fabs(xs.col(i).norm() - 1.0), fiber_error);\n        }\n        MPI_Allreduce(MPI_IN_PLACE, &fiber_error, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);\n\n        double dt_new = properties.dt;\n        bool accept = false;\n        if (converged && fiber_error <= params.fiber_error_tol) {\n            accept = true;\n            const double tol_window = 0.9 * params.fiber_error_tol;\n            if (fiber_error <= tol_window)\n                dt_new = std::min(params.dt_max, properties.dt * params.beta_up);\n        } else {\n            dt_new = properties.dt * params.beta_down;\n            accept = false;\n        }\n\n        if (converged && System::check_collision()) {\n            spdlog::info(\"Collision detected, rejecting solution and taking a smaller timestep\");\n            dt_new = properties.dt * 0.5;\n            accept = false;\n        }\n\n        if (dt_new < params.dt_min) {\n            spdlog::info(\"System time, dt, fiber_error: {}, {}, {}\", properties.time, dt_new, fiber_error);\n            spdlog::critical(\"Timestep smaller than minimum allowed\");\n            throw std::runtime_error(\"Timestep smaller than dt_min\");\n        }\n\n        if (accept) {\n            spdlog::info(\"Accepting timestep and advancing time\");\n            properties.time += properties.dt;\n            double &dt_write = params_.dt_write;\n            if ((int)(properties.time / dt_write) > (int)((properties.time - properties.dt) / dt_write))\n                System::write();\n        } else {\n            spdlog::info(\"Rejecting timestep\");\n            System::restore();\n        }\n        properties.dt = dt_new;\n        spdlog::info(\"System time, dt, fiber_error: {}, {}, {}\", properties.time, dt_new, fiber_error);\n    }\n\n    System::write();\n}\n\n/// @brief Check for any collisions between objects\nbool check_collision() {\n    BodyContainer &bc = bc_;\n    FiberContainer &fc = fc_;\n    Periphery &shell = *shell_;\n    const double threshold = 0.0;\n    using Eigen::VectorXd;\n\n    char collided = false;\n    for (const auto &body : bc.bodies)\n        if (!collided && body->check_collision(shell, threshold))\n            collided = true;\n\n    for (const auto &fiber : fc.fibers)\n        if (!collided && shell.check_collision(fiber.x_, threshold))\n            collided = true;\n\n    for (auto &body1 : bc.bodies)\n        for (auto &body2 : bc.bodies)\n            if (!collided && body1 != body2 && body1->check_collision(*body2, threshold))\n                collided = true;\n\n    MPI_Allreduce(MPI_IN_PLACE, &collided, 1, MPI_CHAR, MPI_LOR, MPI_COMM_WORLD);\n\n    return collided;\n}\n\n/// @brief Return copy of fiber container's RHS\nEigen::VectorXd get_fiber_RHS() { return fc_.get_RHS(); }\n/// @brief Return copy of body container's RHS\nEigen::VectorXd get_body_RHS() { return bc_.get_RHS(); }\n/// @brief Return copy of shell's RHS\nEigen::VectorXd get_shell_RHS() { return shell_->get_RHS(); }\n\n/// @brief get pointer to params struct\nParams *get_params() { return &params_; }\n/// @brief get pointer to body container\nBodyContainer *get_body_container() { return &bc_; }\n/// @brief get pointer to fiber container\nFiberContainer *get_fiber_container() { return &fc_; }\n/// @brief get pointer to shell\nPeriphery *get_shell() { return shell_.get(); }\n/// @brief get pointer to param table struct\ntoml::value *get_param_table() { return &param_table_; }\n\n/// @brief Initialize entire system. Needs to be called once at the beginning of the program execution\n/// @param[in] input_file String of toml config file specifying system parameters and initial conditions\n/// @param[in] resume_flag true if simulation is resuming from prior execution state, false otherwise.\nvoid init(const std::string &input_file, bool resume_flag) {\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank_);\n    MPI_Comm_size(MPI_COMM_WORLD, &size_);\n    spdlog::logger sink = rank_ == 0\n                              ? spdlog::logger(\"SkellySim\", std::make_shared<spdlog::sinks::ansicolor_stdout_sink_st>())\n                              : spdlog::logger(\"SkellySim\", std::make_shared<spdlog::sinks::null_sink_st>());\n    spdlog::set_default_logger(std::make_shared<spdlog::logger>(sink));\n    spdlog::stdout_color_mt(\"STKFMM\");\n    spdlog::stdout_color_mt(\"Belos\");\n    spdlog::stdout_color_mt(\"SkellySim global\");\n    spdlog::cfg::load_env_levels();\n\n    param_table_ = toml::parse(input_file);\n    params_ = Params(param_table_.at(\"params\"));\n    RNG::init(params_.seed);\n    preprocess(param_table_);\n\n    if (param_table_.contains(\"fibers\"))\n        fc_ = FiberContainer(param_table_.at(\"fibers\").as_array(), params_);\n\n    if (param_table_.contains(\"periphery\")) {\n        const toml::value &periphery_table = param_table_.at(\"periphery\");\n        if (!params_.shell_precompute_file.length())\n            throw std::runtime_error(\"Periphery specified, but no precompute file. Set [params] shell_precompute_file \"\n                                     \"in your input config and run the precompute script.\");\n        if (toml::find_or(periphery_table, \"shape\", \"\") == std::string(\"sphere\"))\n            shell_ = std::make_unique<SphericalPeriphery>(params_.shell_precompute_file, periphery_table, params_);\n        else {\n            throw std::runtime_error(\"Unknown shape for periphery set in input file. Valid values are 'sphere'\");\n        }\n    } else {\n        shell_ = std::make_unique<Periphery>();\n    }\n\n    if (param_table_.contains(\"bodies\"))\n        bc_ = BodyContainer(param_table_.at(\"bodies\").as_array(), params_);\n    properties.dt = params_.dt_initial;\n\n    std::string filename = \"skelly_sim.out.\" + std::to_string(rank_);\n    if (resume_flag) {\n        resume_from_trajectory(filename);\n        ofs_ = std::ofstream(filename, std::ofstream::out | std::ofstream::binary | std::ofstream::app);\n    } else {\n        ofs_ = std::ofstream(filename, std::ofstream::out | std::ofstream::binary);\n    }\n}\n} // namespace System\n", "meta": {"hexsha": "d6489874ef20d9d4981aabc5b01673fb4b122f15", "size": 44151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/system.cpp", "max_stars_repo_name": "lu1and10/SkellySim", "max_stars_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/system.cpp", "max_issues_repo_name": "lu1and10/SkellySim", "max_issues_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/system.cpp", "max_forks_repo_name": "lu1and10/SkellySim", "max_forks_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "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.757185332, "max_line_length": 120, "alphanum_fraction": 0.6418654164, "num_tokens": 11200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393357, "lm_q2_score": 0.021615330556727975, "lm_q1q2_score": 0.008320003238319263}}
{"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_IEXP_SUM_HPP\n#define AMA_TENSOR_IEXP_SUM_HPP 1\n\n#include <ama/tensor/iexp/iexp_copy.hpp>\n#include <ama/tensor/detail/copy.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/size.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    namespace mpl = ::boost::mpl;\n\n    /* apply the sum: a trick to remove the last operation */\n    template <typename T> T sum_op(T const & a, T const & b) { return a + b; }\n    template <typename T> T sum_op(T const & a, mpl::na const &) { return a; }\n\n    /* this struct implement the sum */\n    template <\n          typename D               /* the dimensione of tensor */\n        , typename O               /* the order of tensor */\n        , typename I = first<O>    /* the first multi-index */\n        , typename R = mpl::false_ /* this type is true for the last multi-index */\n        >\n    struct sum\n    {\n      template <typename IMAP, typename ISUM, typename IEXP>\n      static\n      typename IEXP::value_type\n      apply(IEXP const & iexp)\n      {\n        BOOST_MPL_ASSERT_MSG(\n              (mpl::equal_to< mpl::size<I> , mpl::size<ISUM> >::value)\n            , YOU_GIVE_A_INCORRECT_LIST_OF_INDICES\n            , (I, ISUM));\n\n        /* append to map */\n        typedef typename mpl::fold<\n              IMAP\n            , typename make_imap<ISUM, I>::type\n            , mpl::insert<mpl::_1, mpl::_2>\n            >::type imap;\n\n        /* increment the multi-index */\n        typedef typename increment<D,I>::type increment_type;\n\n        /* the first is the multi-index incremented */\n        typedef typename mpl::first<increment_type>::type i;\n        /* the second is a boolean flag toidentify the last multi-index */\n        typedef typename mpl::second<increment_type>::type r;\n\n        /* return */\n        return sum_op(iexp.template at<imap>(),\n                      sum<D,O,i,r>::template apply<IMAP, ISUM>(iexp));\n      }\n    };\n\n\n\n\n    /* partial specialization, end the iterative call */\n    template <typename D, typename O, typename I>\n    struct sum<D,O,I,mpl::true_>\n    {\n      template <typename IMAP, typename ISUM, typename IEXP>\n      static mpl::na apply(IEXP const &) { return mpl::na(); }\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_IEXP_SUM_HPP */\n", "meta": {"hexsha": "05b72357017ef02f03a3edf3c9aa83c7ad90a168", "size": 3996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/iexp/sum.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/iexp/sum.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/iexp/sum.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": 37.3457943925, "max_line_length": 83, "alphanum_fraction": 0.6629129129, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418373713166, "lm_q2_score": 0.03161876863742241, "lm_q1q2_score": 0.008310735244078668}}
{"text": "/**\n * Copyright 2004-present Facebook. All Rights Reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include \"source/calibration/GeometricCalibration.h\"\n\n#include <future>\n#include <iostream>\n#include <random>\n#include <unordered_map>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/timer/timer.hpp>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <opencv2/opencv.hpp>\n\n#include <folly/FileUtil.h>\n#include <folly/Format.h>\n#include <folly/dynamic.h>\n#include <folly/json.h>\n\n#include \"source/calibration/Calibration.h\"\n#include \"source/util/Camera.h\"\n#include \"source/util/CvUtil.h\"\n#include \"source/util/MathUtil.h\"\n#include \"source/util/ThreadPool.h\"\n\nusing namespace fb360_dep;\nusing namespace fb360_dep::calibration;\n\nDEFINE_int32(cap_traces, 0, \"speed up solver by capping the number of traces\");\nDEFINE_double(ceres_function_tolerance, 1e-6, \"ceres function tolerance\");\nDEFINE_int32(\n    ceres_threads,\n    -1,\n    \"number of threads used by ceres. requires compiled support for multithreading (default 1)\");\nDEFINE_string(debug_dir, \"\", \"path to debug output\");\nDEFINE_double(debug_error_scale, 0, \"show scaled reprojection errors\");\nDEFINE_double(debug_matches_overlap, 1, \"show matches if overlap exceeds this fraction\");\nDEFINE_bool(\n    dir_per_frame,\n    false,\n    \"is there a directory per frame?\\n\"\n    \"i.e. is an image path of the form: \\n\"\n    \"    <frame index>/ ... /<camera id>.<extension>\\n\"\n    \"    e.g. 1/cam2.bmp or 000001/isp_out/cam14.png\\n\"\n    \"the default is a directory per camera. i.e. an image is of the form:\\n\"\n    \"    .../<camera id>/<frame index>.<extension>\\n\"\n    \"    e.g. cam2/123.bmp or rgb/cam14/000123.png\");\nDEFINE_bool(discard_outside_fov, true, \"discard matches outside fov\");\nDEFINE_string(errors_dir, \"\", \"directory where errors will be saved\");\nDEFINE_int32(experiments, 1, \"calibrate multiple times\");\nDEFINE_bool(force_in_front, true, \"no intersections behind camera\");\nDEFINE_bool(keep_invalid_traces, false, \"keep traces with multiple points from the same camera\");\nDEFINE_bool(lock_distortion, true, \"lock the distorion\");\nDEFINE_bool(lock_focal, false, \"lock the focal\");\nDEFINE_bool(lock_positions, true, \"don't calibrate position\");\nDEFINE_bool(lock_principals, false, \"don't calibrate principals\");\nDEFINE_bool(lock_rotations, false, \"don't calibrate rotation\");\nDEFINE_double(max_error, 0.5, \"maximum allowable error for calibration to be valid\");\nDEFINE_int32(min_traces, 10, \"minimum number of traces for camera to be sufficiently constrained\");\nDEFINE_double(outlier_factor, 5, \"reject if error is factor * median\");\nDEFINE_double(\n    outlier_z_threshold,\n    3,\n    \"z score threshold on traces to consider a camera an outlier\");\nDEFINE_int32(pass_count, 10, \"number of passes\");\nDEFINE_double(perturb_focals, 0, \"pertub focals (pixels / radian)\");\nDEFINE_double(perturb_positions, 0, \"perturb positions (m)\");\nDEFINE_double(perturb_principals, 0, \"pertub principals (pixels)\");\nDEFINE_double(perturb_rotations, 0, \"perturb rotations (radians)\");\nDEFINE_int32(point_count, 10000, \"artificial points to generate\");\nDEFINE_double(point_error_stddev, 0.5, \"error added to artificial points\");\nDEFINE_double(point_min_dist, 1, \"minimum distance of artificial points\");\nDEFINE_string(points_file, \"\", \"path to output calibration points file, default next to output\");\nDEFINE_string(\n  points_file_json,\n  \"\",\n  \"path to output calibration points file including reference points, default next to output\");\nDEFINE_string(reference_camera, \"\", \"reference camera to lock if positions are unlocked\");\nDEFINE_double(\n    remove_sparse_overlaps,\n    0,\n    \"reject overlaps with fewer than this fraction of the average match count\");\nDEFINE_bool(report_per_camera_errors, false, \"per camera reprojection error statistics\");\nDEFINE_bool(robust, true, \"use Huber loss function\");\nDEFINE_int32(seed, -1, \"seed for random number generator\");\nDEFINE_bool(shared_distortion, true, \"all cameras in a group share the same distortion\");\nDEFINE_bool(\n    shared_principal_and_focal,\n    false,\n    \"all cameras in a group share the same focal, principal\");\nDEFINE_bool(\n    weight_by_trace_count,\n    false,\n    \"weight the residual error by the number of traces per camera\");\nDEFINE_bool(weighted_statistics, false, \"compute statistics of weighted residuals\");\n\nstd::unordered_map<std::string, int> cameraIdToIndex;\nstd::unordered_map<std::string, int> cameraGroupToIndex;\n\nstd::string imageIdFormat() {\n  return FLAGS_dir_per_frame ? \"<frame index>/ ... /<camera id>.<extension>\"\n                             : \".../<camera id>/<frame index>.<extension>\";\n}\n\nvoid buildCameraIndexMaps(const Camera::Rig& rig) {\n  for (int i = 0; i < int(rig.size()); ++i) {\n    cameraIdToIndex[rig[i].id] = i;\n    cameraGroupToIndex[rig[i].group] = i; // last camera in group wins\n  }\n}\n\nusing ImageId = std::string;\n\nstd::string getCameraId(const ImageId& image) {\n  // image is actually a path\n  filesystem::path path = image;\n  if (FLAGS_dir_per_frame) {\n    return path.stem().native();\n  }\n  return path.parent_path().filename().native();\n}\n\nint getFrameIndex(const ImageId& image) {\n  // image is actually a path\n  filesystem::path path = image;\n  if (FLAGS_dir_per_frame) {\n    return std::stoi(path.begin()->native());\n  }\n  return std::stoi(path.stem().native());\n}\n\nbool hasCameraIndex(const ImageId& image) {\n  return cameraIdToIndex.count(getCameraId(image));\n}\n\nint getCameraIndex(const ImageId& image) {\n  return cameraIdToIndex.at(getCameraId(image));\n}\n\n// create a string that adheres to the format of an image path\nImageId makeArtificialPath(int frame, const std::string& cameraId) {\n  if (FLAGS_dir_per_frame) {\n    return std::to_string(frame) + \"/\" + cameraId;\n  }\n  return cameraId + \"/\" + std::to_string(frame);\n}\n\n// input path includes basename and extension\ncv::Mat_<cv::Vec3w> loadImage(const filesystem::path& path) {\n  const filesystem::path colorDir = FLAGS_color;\n  return cv_util::loadImage<cv::Vec3w>(colorDir / path);\n}\n\nfolly::dynamic parseJsonFile(const std::string& path) {\n  std::string json;\n  folly::readFile(path.c_str(), json);\n  CHECK(!json.empty()) << \"could not read JSON file: \" << path;\n  return folly::parseJson(json);\n}\n\n// a feature is a point in an image\nstruct Feature {\n  Camera::Vector2 position; // position of the feature in its image, in pixels\n  int trace; // index of trace that feature belongs to (or -1 if none)\n\n  Feature(const Camera::Vector2& position) : position(position), trace(-1) {}\n};\n\n// a featuremap holds, for each image, a vector of its features\nusing FeatureMap = std::unordered_map<ImageId, std::vector<Feature>>;\n\n// an overlap is a pair of images and the matches between their features\nstruct Overlap {\n  std::array<ImageId, 2> images;\n  std::vector<std::array<size_t, 2>> matches;\n\n  Overlap(const ImageId& image0, const ImageId& image1) {\n    images[0] = image0;\n    images[1] = image1;\n  }\n\n  bool isIntraFrame() const {\n    return getFrameIndex(images[0]) == getFrameIndex(images[1]);\n  }\n};\n\n// a trace is a world coordinate and a list of observations that reference it\nstruct Trace {\n  Camera::Vector3 position;\n\n  std::vector<std::pair<ImageId, int>> references;\n\n  void add(const ImageId& image, const int index) {\n    references.emplace_back(image, index);\n  }\n\n  // inherit trace's references\n  void inherit(Trace& trace, FeatureMap& featureMap, int me) {\n    for (const auto& ref : trace.references) {\n      featureMap[ref.first][ref.second].trace = me;\n    }\n    references.insert(references.end(), trace.references.begin(), trace.references.end());\n    trace.references.clear();\n  }\n\n  void clear(FeatureMap& featureMap) {\n    for (const auto& ref : references) {\n      featureMap[ref.first][ref.second].trace = -1;\n    }\n    references.clear();\n  }\n};\n\n/* Parse features from <parsed> JSON which has structure\n    {\n        \"images\": {\n            image_name: [{\"x\": x, \"y\": y, ...}]\n        },\n        ...\n    }\n    where image_name is defined as in imageIdFormat, above.\n*/\nFeatureMap loadFeatureMap(const folly::dynamic& parsed) {\n  FeatureMap result;\n\n  for (const auto& image : parsed[\"images\"].items()) {\n    const ImageId path = image.first.getString();\n    if (!hasCameraIndex(path)) {\n      LOG(INFO) << folly::sformat(\"ignoring image id {}\", path);\n      continue;\n    }\n    std::vector<Feature>& features = result[path];\n    for (const auto& feature : image.second) {\n      features.emplace_back(Camera::Vector2(feature[\"x\"].asDouble(), feature[\"y\"].asDouble()));\n    }\n  }\n\n  CHECK(!result.empty()) << \"verify image id format: \" << imageIdFormat();\n  LOG(INFO) << folly::sformat(\"{} images loaded\", result.size());\n\n  return result;\n}\n\n/* Parse matches from <parsed> JSON which has structure\n    {\n        \"all_matches\": [{\n            \"image1\": image_name1,\n            \"image2\": image_name1,\n            \"matches\": [{\n                \"idx1\": idx1,\n                \"idx2\": idx2\n            }]\n        }],\n        ...\n    }\n*/\nstd::vector<Overlap> loadOverlaps(const folly::dynamic& parsed) {\n  std::vector<Overlap> result;\n\n  size_t count = 0;\n  for (const auto& overlap : parsed[\"all_matches\"]) {\n    ImageId path0 = overlap[\"image1\"].getString();\n    ImageId path1 = overlap[\"image2\"].getString();\n    if (!hasCameraIndex(path0) || !hasCameraIndex(path1)) {\n      continue;\n    }\n    result.emplace_back(path0, path1);\n    for (const auto& match : overlap[\"matches\"]) {\n      // A threshold of 0 indicates that score should be ignored\n      // Check if score should be ignored before attempting to access\n      // match[\"score\"] since it might not be defined in the json\n      if (FLAGS_match_score_threshold == 0 ||\n          FLAGS_match_score_threshold <= match[\"score\"].asDouble()) {\n        result.back().matches.push_back(\n            {{size_t(match[\"idx1\"].asInt()), size_t(match[\"idx2\"].asInt())}});\n      }\n    }\n    count += 2 * result.back().matches.size();\n  }\n\n  LOG(INFO) << folly::sformat(\"{} feature observations loaded\", count);\n\n  return result;\n}\n\nOverlap& findOrAddOverlap(std::vector<Overlap>& overlaps, const ImageId& i0, const ImageId& i1) {\n  for (Overlap& overlap : overlaps) {\n    if (overlap.images[0] == i0 && overlap.images[1] == i1) {\n      return overlap;\n    }\n    // make sure we don't have the image pair (i1, i0) in there\n    CHECK(overlap.images[0] != i1 || overlap.images[1] != i0);\n  }\n  // image pair (i0, i1) not found: add it\n  overlaps.emplace_back(i0, i1);\n  return overlaps.back();\n}\n\ntemplate <typename T>\nCamera::Vector2 keypointError(T& gen) {\n  std::normal_distribution<> rng(0, FLAGS_point_error_stddev);\n  return {rng(gen), rng(gen)};\n}\n\nvoid generateArtificalPoints(\n    FeatureMap& featureMap,\n    std::vector<Overlap>& overlaps,\n    const std::vector<Camera>& cameras) {\n  std::mt19937 mt;\n  for (int p = 0; p < FLAGS_point_count; ++p) {\n    // create a random unit vector\n    double longitude = std::uniform_real_distribution<>(-M_PI, +M_PI)(mt);\n    double z = std::uniform_real_distribution<>(-1, 1)(mt);\n    Camera::Vector3 rig(sqrt(1 - z * z) * cos(longitude), sqrt(1 - z * z) * sin(longitude), z);\n    CHECK_NEAR(rig.squaredNorm(), 1, 0.001);\n\n    // divide unit vector by random disparity\n    rig /= std::uniform_real_distribution<>(0, 1 / FLAGS_point_min_dist)(mt);\n\n    // add keypoint to every camera that sees rig\n    std::vector<ImageId> images;\n    for (const Camera& camera : cameras) {\n      if (camera.sees(rig)) {\n        ImageId image = makeArtificialPath(0, camera.id);\n        featureMap[image].emplace_back(camera.pixel(rig) + keypointError(mt));\n        images.push_back(image);\n      }\n    }\n\n    // add a match for every pair of cameras that see rig\n    for (int index1 = 0; index1 < int(images.size()); ++index1) {\n      const ImageId& i1 = images[index1];\n      for (int index0 = 0; index0 < index1; ++index0) {\n        const ImageId& i0 = images[index0];\n        Overlap& overlap = findOrAddOverlap(overlaps, i0, i1);\n        overlap.matches.push_back({{featureMap[i0].size() - 1, featureMap[i1].size() - 1}});\n      }\n    }\n  }\n}\n\nCamera::Vector3 triangulate(const Observations& observations) {\n  return triangulateNonlinear(observations, FLAGS_force_in_front);\n}\n\n// return reprojection errors for each camera\nstd::vector<std::vector<Camera::Real>> reprojectionErrors(\n    const std::vector<Overlap>& overlaps,\n    const FeatureMap& featureMap,\n    const std::vector<Trace>& traces,\n    const std::vector<Camera>& cameras) {\n  std::vector<std::vector<Camera::Real>> errors(ssize(cameras));\n  for (const Overlap& overlap : overlaps) {\n    if (!overlap.isIntraFrame()) {\n      continue;\n    }\n    const std::reference_wrapper<const ImageId> images[2] = {overlap.images[0], overlap.images[1]};\n    const int idxs[2] = {getCameraIndex(images[0]), getCameraIndex(images[1])};\n    const std::reference_wrapper<const std::vector<Feature>> features[2] = {\n        featureMap.at(images[0]), featureMap.at(images[1])};\n    for (const auto& match : overlap.matches) {\n      std::array<const Feature, 2> kps = {\n          {features[0].get()[match[0]], features[1].get()[match[1]]}};\n      CHECK_EQ(kps[0].trace, kps[1].trace) << \"matching features belong to different traces\";\n      Camera::Vector3 rig = kps[0].trace < 0\n          ? triangulate({{cameras[idxs[0]], kps[0].position}, {cameras[idxs[1]], kps[1].position}})\n          : traces[kps[0].trace].position;\n      for (ssize_t i = 0; i < ssize(match); ++i) {\n        const Camera::Vector2 pixel = cameras[idxs[i]].pixel(rig);\n        errors[idxs[i]].push_back((pixel - kps[i].position).squaredNorm());\n      }\n    }\n  }\n\n  return errors;\n}\n\n// report reprojection errors for each camera\nvoid reportReprojectionErrors(\n    const std::vector<Overlap>& overlaps,\n    const FeatureMap& featureMap,\n    const std::vector<Trace>& traces,\n    const std::vector<Camera>& cameras) {\n  if (!FLAGS_report_per_camera_errors) {\n    return;\n  }\n  std::vector<std::vector<Camera::Real>> errors =\n      reprojectionErrors(overlaps, featureMap, traces, cameras);\n  for (ssize_t i = 0; i < ssize(cameras); ++i) {\n    std::sort(errors[i].begin(), errors[i].end());\n    std::ostringstream line;\n    for (int percentile : {50, 90, 99}) {\n      int index = percentile * (ssize(errors[i]) - 1) / 100.0 + 0.5;\n      line << folly::format(\"{}%: {:.2f} \", percentile, sqrt(errors[i][index]));\n    }\n    LOG(INFO) << folly::sformat(\n        \"{}: {} reproj. percentile {}\", cameras[i].id, ssize(errors[i]), line.str());\n  }\n}\n\nvoid removeOutliersFromCameras(\n    std::vector<Overlap>& overlaps,\n    const FeatureMap& featureMap,\n    const std::vector<Trace>& traces,\n    const std::vector<Camera>& cameras,\n    const Camera::Real outlierFactor) {\n  // compute reprojection errors for each camera\n  std::vector<std::vector<Camera::Real>> errors =\n      reprojectionErrors(overlaps, featureMap, traces, cameras);\n\n  // compute median for each camera\n  std::vector<Camera::Real> medians(ssize(errors));\n  for (ssize_t i = 0; i < ssize(errors); ++i) {\n    medians[i] = calcPercentile(errors[i]);\n  }\n\n  std::unordered_map<ImageId, int> outliers;\n\n  // remove matches that neither endpoint wants to keep around\n  std::vector<ssize_t> errorIdxs(ssize(errors), 0);\n  int total = 0;\n  int inlierTotal = 0;\n  for (Overlap& overlap : overlaps) {\n    if (!overlap.isIntraFrame()) {\n      continue;\n    }\n    const std::reference_wrapper<const ImageId> images[2] = {overlap.images[0], overlap.images[1]};\n    const int idxs[2] = {getCameraIndex(images[0]), getCameraIndex(images[1])};\n\n    // move the inliers to front of overlap.matches and resize to fit\n    int inliers = 0;\n    for (const auto& match : overlap.matches) {\n      bool inlier = false;\n      for (ssize_t i = 0; i < ssize(match); ++i) {\n        int cameraIndex = idxs[i];\n        if (errors[cameraIndex][errorIdxs[cameraIndex]++] < medians[cameraIndex] * outlierFactor) {\n          inlier = true;\n        }\n      }\n      if (inlier) {\n        overlap.matches[inliers++] = match;\n      }\n    }\n    outliers[overlap.images[0]] += ssize(overlap.matches) - inliers;\n    outliers[overlap.images[1]] += ssize(overlap.matches) - inliers;\n    total += ssize(overlap.matches);\n    overlap.matches.resize(inliers);\n    inlierTotal += inliers;\n  }\n\n  // sanity check that we consumed all the errors\n  for (ssize_t i = 0; i < ssize(errors); ++i) {\n    CHECK_EQ(errorIdxs[i], ssize(errors[i]));\n  }\n  if (FLAGS_log_verbose) {\n    for (const auto& p : outliers) {\n      LOG(INFO) << folly::sformat(\"Removed {} outliers from {}\", p.second, p.first);\n    }\n  }\n  LOG(INFO) << folly::sformat(\"{} of {} matches were inliers\", inlierTotal, total);\n}\n\nvoid removeInvalidTraces(std::vector<Trace>& traces, FeatureMap& featureMap) {\n  int total = 0;\n  int removed = 0;\n  for (Trace& trace : traces) {\n    if (!trace.references.empty()) {\n      ++total;\n    }\n    std::unordered_set<ImageId> uniqueCameras;\n    for (const auto& ref : trace.references) {\n      if (!uniqueCameras.insert(ref.first).second) {\n        // image referenced more than once, remove the trace\n        trace.clear(featureMap);\n        ++removed;\n        break;\n      }\n    }\n  }\n  LOG(INFO) << folly::sformat(\"removed {} out of {} traces\", removed, total);\n}\n\nvoid triangulateTracesThread(\n    std::vector<Trace>& traces,\n    const size_t begin,\n    const size_t end,\n    const FeatureMap& featureMap,\n    const std::vector<Camera>& cameras) {\n  for (size_t i = begin; i < end; ++i) {\n    Trace& trace = traces[i];\n    if (!trace.references.empty()) {\n      Observations observations;\n      for (const auto& ref : trace.references) {\n        const Feature& feature = featureMap.at(ref.first)[ref.second];\n        const Camera& camera = cameras[getCameraIndex(ref.first)];\n        observations.emplace_back(camera, feature.position);\n      }\n      trace.position = triangulate(observations);\n    }\n  }\n}\n\nvoid triangulateTraces(\n    std::vector<Trace>& traces,\n    const FeatureMap& featureMap,\n    const std::vector<Camera>& cameras) {\n  const int threadCount = ThreadPool::getThreadCountFromFlag(FLAGS_threads);\n  std::vector<std::thread> threads;\n  for (int thread = 0; thread < threadCount; ++thread) {\n    threads.emplace_back(\n        triangulateTracesThread,\n        std::ref(traces),\n        thread * traces.size() / threadCount,\n        (thread + 1) * traces.size() / threadCount,\n        std::cref(featureMap),\n        std::cref(cameras));\n  }\n  for (std::thread& thread : threads) {\n    thread.join();\n  }\n}\n\nstd::vector<Trace> assembleTraces(FeatureMap& featureMap, const std::vector<Overlap>& overlaps) {\n  // mark all features as unreferenced\n  for (auto& features : featureMap) {\n    for (Feature& feature : features.second) {\n      feature.trace = -1;\n    }\n  }\n  std::vector<Trace> traces;\n  int nonemptyTraceCount = 0;\n  for (const Overlap& overlap : overlaps) {\n    const std::reference_wrapper<std::vector<Feature>> features[2] = {\n        featureMap[overlap.images[0]], featureMap[overlap.images[1]]};\n    for (const auto& match : overlap.matches) {\n      const std::reference_wrapper<int> indexes[2] = {features[0].get()[match[0]].trace,\n                                                      features[1].get()[match[1]].trace};\n      if (indexes[0] < 0 && indexes[1] < 0) { // neither belongs to a trace, start new trace\n        traces.emplace_back();\n        nonemptyTraceCount++;\n        for (ssize_t i = 0; i < ssize(indexes); ++i) {\n          indexes[i].get() = traces.size() - 1;\n          traces[indexes[i]].add(overlap.images[i], match[i]);\n        }\n      } else if (indexes[0] < 0) { // 0 does not belong to a trace, add to 1's trace\n        indexes[0].get() = indexes[1];\n        traces[indexes[0]].add(overlap.images[0], match[0]);\n      } else if (indexes[1] < 0) { // 1 does not belong to a trace, add to 0's trace\n        indexes[1].get() = indexes[0];\n        traces[indexes[1]].add(overlap.images[1], match[1]);\n      } else if (indexes[0] != indexes[1]) { // merge two traces, 0 inherits 1's references\n        traces[indexes[0]].inherit(traces[indexes[1]], featureMap, indexes[0]);\n        --nonemptyTraceCount;\n      }\n    }\n  }\n\n  LOG(INFO) << folly::sformat(\"found {} nonempty traces\", nonemptyTraceCount);\n\n  return traces;\n}\n\ncv::Mat_<cv::Vec3w> blend(const cv::Mat_<cv::Vec3w>& mat0, const cv::Mat_<cv::Vec3w>& mat1) {\n  if (mat0.empty()) {\n    return 0.5 * mat1;\n  }\n  cv::Mat_<cv::Vec3w> result;\n  cv::addWeighted(mat0, 0.5, mat1, 0.5, 0, result);\n  return result;\n}\n\n// draw a line that starts out red, ends up green\nvoid drawRedGreenLine(\n    cv::Mat_<cv::Vec3w>& dst,\n    const Camera::Vector2& r,\n    const Camera::Vector2& g,\n    const Camera::Vector2& m) {\n  const cv::Scalar red(0, 0, 255);\n  const cv::Scalar green(0, 255, 0);\n  cv::line(dst, cv::Point2f(r.x(), r.y()), cv::Point2f(m.x(), m.y()), red, 2);\n  cv::line(dst, cv::Point2f(g.x(), g.y()), cv::Point2f(m.x(), m.y()), green, 2);\n}\n\ntemplate <typename T>\ncv::Mat_<T> projectImageBetweenCamerasNearest(\n    const Camera& dst,\n    const Camera& src,\n    const cv::Mat_<T>& srcImage) {\n  cv::Mat_<T> dstImage(cv::Size(dst.resolution.x(), dst.resolution.y()));\n  for (int y = 0; y < dstImage.rows; ++y) {\n    for (int x = 0; x < dstImage.cols; ++x) {\n      Camera::Vector3 rig = dst.rigNearInfinity({x + 0.5, y + 0.5});\n      Camera::Vector2 srcPixel;\n      if (src.sees(rig, srcPixel)) {\n        dstImage(y, x) = srcImage.empty() ? cv_util::createBGR<T>(255, 255, 255)\n                                          : srcImage(srcPixel.y(), srcPixel.x());\n      } else {\n        dstImage(y, x) = cv_util::createBGR<T>(0, 0, 0);\n      }\n    }\n  }\n  return dstImage;\n}\n\ncv::Mat_<cv::Vec3w> renderOverlap(\n    const Overlap& overlap,\n    const FeatureMap& featureMap,\n    const std::vector<Trace>& traces,\n    const std::vector<Camera>& cameras) {\n  // transform image 1 into image 0's space and overlay the two\n  const ImageId& image0 = overlap.images[0];\n  const ImageId& image1 = overlap.images[1];\n  const Camera& camera0 = cameras[getCameraIndex(image0)];\n  const Camera& camera1 = cameras[getCameraIndex(image1)];\n  const std::vector<Feature>& features0 = featureMap.at(image0);\n  const std::vector<Feature>& features1 = featureMap.at(image1);\n  cv::Mat_<cv::Vec3w> result = blend(\n      loadImage(image0), projectImageBetweenCamerasNearest(camera0, camera1, loadImage(image1)));\n  for (const auto& match : overlap.matches) {\n    Camera::Vector2 p0 = features0[match[0]].position;\n    Camera::Vector2 p1 = features1[match[1]].position;\n    int trace = features0[match[0]].trace;\n    CHECK_EQ(trace, features1[match[1]].trace);\n    Camera::Vector3 rig =\n        trace < 0 ? triangulate({{camera0, p0}, {camera1, p1}}) : traces[trace].position;\n    drawRedGreenLine(\n        result,\n        p0, // p0 in red\n        camera0.pixel(camera1.rigNearInfinity(p1)), // transformed p1 in green\n        camera0.pixel(rig)); // via transformed triangulation\n  }\n\n  return result;\n}\n\ncv::Mat_<cv::Vec3w> renderReprojections(\n    const ImageId& image,\n    const Camera& camera,\n    const std::vector<Feature>& features,\n    const std::vector<Trace>& traces,\n    const Camera::Real scale) {\n  cv::Mat_<cv::Vec3w> result = 0.5f * loadImage(image);\n  cv::Mat_<cv::Vec3f> errors = cv::Mat::zeros(result.size(), CV_32FC3);\n  const cv::Scalar green(0, 255, 0);\n  const cv::Scalar red(0, 0, 255);\n  for (const Feature& feature : features) {\n    if (feature.trace >= 0) {\n      // draw red line from image feature to reprojected world point\n      // then continue in green in the same direction but scale x as far\n      Camera::Vector2 proj = camera.pixel(traces[feature.trace].position);\n      Camera::Vector2 error = proj - feature.position;\n\n      // OpenCV can only save 1, 3, 4 channels so the third is simply an artifact\n      errors(cv::Point(feature.position.x(), feature.position.y())) =\n          cv::Vec3f(error.x(), error.y(), 0.0f);\n      drawRedGreenLine(result, feature.position, proj + scale * error, proj);\n    }\n  }\n\n  if (FLAGS_errors_dir != \"\") {\n    filesystem::create_directories(FLAGS_errors_dir);\n    std::string errorsFile = folly::sformat(\"{}/{}.exr\", FLAGS_errors_dir, getCameraId(image));\n    cv_util::imwriteExceptionOnFail(errorsFile, errors);\n  }\n\n  return result;\n}\n\nstd::string getReprojectionReport(\n    const ceres::Problem& problem,\n    const double* parameter = nullptr) {\n  std::vector<double> norms =\n      getReprojectionErrorNorms(problem, parameter, FLAGS_weighted_statistics);\n  double total = 0;\n  double totalSq = 0;\n  for (double norm : norms) {\n    total += norm;\n    totalSq += norm * norm;\n  }\n\n  std::ostringstream result;\n  result << \"reprojections \" << norms.size() << \" \"\n         << \"RMSE \" << sqrt(totalSq / norms.size()) << \" \"\n         << \"average \" << total / norms.size() << \" \"\n         << \"median \" << calcPercentile(norms, 0.5) << \" \"\n         << \"90% \" << calcPercentile(norms, 0.9) << \" \"\n         << \"99% \" << calcPercentile(norms, 0.99) << \" \";\n\n  result << \"worst 3: \";\n  std::sort(norms.begin(), norms.end());\n  for (int i = norms.size() - 3; i < int(norms.size()); ++i) {\n    result << norms[i] << \" \";\n  }\n\n  return result.str();\n}\n\ndouble acosClamp(double x) {\n  return std::acos(std::min(std::max(-1.0, x), 1.0));\n}\n\nstd::string getCameraRmseReport(\n    const std::vector<Camera>& cameras,\n    const std::vector<Camera>& groundTruth) {\n  Camera::Real position = 0;\n  Camera::Real rotation = 0;\n  Camera::Real principal = 0;\n  Camera::Real distortion = 0;\n  Camera::Real focal = 0;\n\n  for (int i = 0; i < int(cameras.size()); ++i) {\n    {\n      auto before = groundTruth[i].position;\n      auto after = cameras[i].position;\n      position += (after - before).squaredNorm();\n    }\n    for (int v = 0; v < 3; ++v) {\n      auto before = groundTruth[i].rotation.row(v);\n      auto after = cameras[i].rotation.row(v);\n      rotation += (after - before).squaredNorm();\n    }\n    {\n      auto before = groundTruth[i].principal;\n      auto after = cameras[i].principal;\n      principal += (after - before).squaredNorm();\n    }\n    {\n      auto before = groundTruth[i].getDistortion();\n      auto after = cameras[i].getDistortion();\n      distortion += (after - before).squaredNorm();\n    }\n    {\n      auto before = groundTruth[i].focal;\n      auto after = cameras[i].focal;\n      focal += (after - before).squaredNorm();\n    }\n  }\n\n  Camera::Real angle = 0;\n  int angleCount = 0;\n  for (int i = 0; i < int(cameras.size()); ++i) {\n    for (int j = 0; j < i; ++j) {\n      for (int v = 2; v < 3; ++v) {\n        // angle between camera i and j\n        auto before = acosClamp(groundTruth[i].rotation.row(v).dot(groundTruth[j].rotation.row(v)));\n        if (before > 1) {\n          continue; // only count angles less than a radian\n        }\n        auto after = acosClamp(cameras[i].rotation.row(v).dot(cameras[j].rotation.row(v)));\n        angle += (after - before) * (after - before);\n        ++angleCount;\n      }\n    }\n  }\n\n  // average\n  position /= cameras.size();\n  rotation /= 3 * cameras.size();\n  principal /= cameras.size();\n  distortion /= cameras.size();\n  focal /= cameras.size();\n  angle /= angleCount;\n\n  std::ostringstream result;\n  result << \"RMSEs: \"\n         << \"Pos \" << sqrt(position) << \" \"\n         << \"Rot \" << sqrt(rotation) << \" \"\n         << \"Principal \" << sqrt(principal) << \" \"\n         << \"Distortion \" << sqrt(distortion) << \" \"\n         << \"Focal \" << sqrt(focal) << \" \"\n         << \"Angle \" << sqrt(angle) << \" \";\n\n  return result.str();\n}\n\ntemplate <typename T>\ndouble* parameterBlock(T& t) {\n  return t.data();\n}\n\ntemplate <>\ndouble* parameterBlock(Camera::Real& t) {\n  return &t;\n}\n\ntemplate <>\ndouble* parameterBlock(Trace& t) {\n  return t.position.data();\n}\n\ntemplate <typename T>\nvoid lockParameter(ceres::Problem& problem, T& param, const bool lock = true) {\n  if (lock) {\n    problem.SetParameterBlockConstant(parameterBlock(param));\n  } else {\n    problem.SetParameterBlockVariable(parameterBlock(param));\n  }\n}\n\ntemplate <typename T>\nvoid lockParameters(ceres::Problem& problem, std::vector<T>& params, const bool lock = true) {\n  for (T& param : params) {\n    lockParameter(problem, param, lock);\n  }\n}\n\nvoid reasonableResize(cv::Mat_<cv::Vec3w>& mat) {\n  const double kWidth = 1200;\n  const double kHeight = 800;\n  double factor = std::min(kWidth / mat.cols, kHeight / mat.rows);\n  if (factor < 1) {\n    cv::resize(mat, mat, {}, factor, factor, cv::INTER_AREA);\n  }\n}\n\nvoid showMatches(\n    const std::vector<Camera>& cameras,\n    const FeatureMap& featureMap,\n    const std::vector<Overlap>& overlaps,\n    const std::vector<Trace>& traces,\n    const int pass) {\n  // visualization for debugging\n  for (const Overlap& overlap : overlaps) {\n    const int idx0 = getCameraIndex(overlap.images[0]);\n    const int idx1 = getCameraIndex(overlap.images[1]);\n    if (cameras[idx0].overlap(cameras[idx1]) > FLAGS_debug_matches_overlap) {\n      cv::Mat_<cv::Vec3w> image = renderOverlap(overlap, featureMap, traces, cameras);\n      reasonableResize(image);\n\n      if (!FLAGS_debug_dir.empty()) {\n        std::string filename = FLAGS_debug_dir + \"/\" + \"pass\" + std::to_string(pass) + \"_\" +\n            getCameraId(overlap.images[0]) + \"-\" + getCameraId(overlap.images[1]) + \".png\";\n        imwrite(filename, image);\n      } else {\n        cv::imshow(\"overlap\", image);\n        cv::waitKey();\n      }\n    }\n  }\n}\n\nvoid showReprojections(\n    const std::vector<Camera>& cameras,\n    const FeatureMap& featureMap,\n    const std::vector<Trace>& traces,\n    const Camera::Real scale) {\n  for (const auto& entry : featureMap) {\n    const ImageId& image = entry.first;\n    const std::vector<Feature>& features = entry.second;\n    const Camera& camera = cameras[getCameraIndex(image)];\n    cv::Mat_<cv::Vec3w> render = renderReprojections(image, camera, features, traces, scale);\n    reasonableResize(render);\n    if (!FLAGS_debug_dir.empty()) {\n      std::string filename = FLAGS_debug_dir + \"/\" + camera.id + \".png\";\n      imwrite(filename, render);\n    } else {\n      cv::imshow(\"reprojections\", render);\n      cv::waitKey();\n    }\n  }\n}\n\n// returns true with a probability of numerator / denominator\nbool randomSample(int numerator, int denominator) {\n  static std::default_random_engine e;\n  return numerator > std::uniform_int_distribution<>(0, denominator - 1)(e);\n}\n\nvoid solve(ceres::Problem& problem) {\n  ceres::Solver::Options options;\n  options.use_inner_iterations = true;\n  options.max_num_iterations = 500;\n  options.minimizer_progress_to_stdout = false;\n  options.num_threads = ThreadPool::getThreadCountFromFlag(FLAGS_ceres_threads);\n  if (options.num_threads == 0) {\n    options.num_threads = 1;\n  }\n  options.function_tolerance = FLAGS_ceres_function_tolerance;\n\n  ceres::Solver::Summary summary;\n\n  LOG(INFO) << getReprojectionReport(problem);\n\n  int previousFLAGS_v = FLAGS_v; // save FLAGS_v\n  if (FLAGS_log_verbose) {\n    FLAGS_v = std::max(1, FLAGS_v); // overwrite FLAGS_v\n  }\n  Solve(options, &problem, &summary);\n  FLAGS_v = previousFLAGS_v; // restore FLAGS_v\n\n  LOG(INFO) << summary.BriefReport();\n  if (FLAGS_log_verbose) {\n    LOG(INFO) << summary.FullReport();\n  }\n\n  if (summary.termination_type == ceres::NO_CONVERGENCE) {\n    throw std::runtime_error(\"Failed to converge\");\n  }\n\n  LOG(INFO) << getReprojectionReport(problem);\n}\n\nvoid validateMatchCount(const std::vector<Camera>& cameras, const std::vector<int>& counts) {\n  const double sum = std::accumulate(counts.begin(), counts.end(), 0.0);\n  const double mean = sum / counts.size();\n\n  const double sqSum = std::inner_product(counts.begin(), counts.end(), counts.begin(), 0.0);\n  const double stdev = std::sqrt(sqSum / counts.size() - mean * mean);\n\n  std::vector<std::string> lowTraceErrors;\n  for (int i = 0; i < int(counts.size()); ++i) {\n    if (FLAGS_log_verbose) {\n      LOG(INFO) << folly::sformat(\"Camera: {} Traces: {}\", cameras[i].id, counts[i]);\n    }\n    const double z = (counts[i] - mean) / stdev;\n    if (-z > FLAGS_outlier_z_threshold || counts[i] < FLAGS_min_traces) {\n      lowTraceErrors.push_back(\n          folly::sformat(\"Too few matches in camera {}: {}\", cameras[i].id, counts[i]));\n    }\n  }\n\n  if (!lowTraceErrors.empty()) {\n    std::string errorString = boost::algorithm::join(lowTraceErrors, \"\\n\");\n    throw std::runtime_error(errorString);\n  }\n}\n\nvoid savePointsFileJson(FeatureMap& featureMap, const std::vector<Trace>& traces) {\n  folly::dynamic arrayOfTraces = folly::dynamic::array();\n  for (const Trace& trace : traces) {\n    if (trace.references.empty()) {\n      continue; // don't output zombie traces, a different trace has the references now\n    }\n    folly::dynamic arrayOfFeatures = folly::dynamic::array();\n    for (const auto& ref : trace.references) {\n      const ImageId& image = ref.first;\n      const Feature& feature = featureMap[image][ref.second];\n      folly::dynamic featureSerialized = folly::dynamic::object\n        (\"y\", feature.position.y())\n        (\"x\", feature.position.x())\n        (\"image_id\", ref.first);\n      arrayOfFeatures.push_back(featureSerialized);\n    }\n    folly::dynamic traceSerialized = folly::dynamic::object\n      (\"features\", arrayOfFeatures)\n      (\"number of references\", trace.references.size())\n      (\"z\", trace.position.z())\n      (\"y\", trace.position.y())\n      (\"x\", trace.position.x());\n    arrayOfTraces.push_back(traceSerialized);\n  }\n\n  folly::dynamic points = folly::dynamic::object(\"points\", arrayOfTraces);\n  CHECK(folly::writeFile(folly::toPrettyJson(points), FLAGS_points_file_json.c_str()));\n}\n\nvoid savePointsFile(FeatureMap& featureMap, const std::vector<Trace>& traces) {\n  std::ofstream file(FLAGS_points_file);\n  for (const Trace& trace : traces) {\n    if (trace.references.empty()) {\n      continue; // don't output zombie traces, a different trace has the references now\n    }\n    file << folly::format(\"{} {} {} \", trace.position.x(), trace.position.y(), trace.position.z());\n    file << folly::format(\"1 \"); // delimiter\n    file << folly::format(\"0 0 0\"); // RGB value for the point\n    file << \"\\n\";\n  }\n}\n\nstd::vector<int> calculateCameraWeights(\n    const std::vector<Camera>& cameras,\n    const std::vector<Trace>& traces) {\n  std::vector<int> weights(cameras.size(), 1);\n  if (FLAGS_weight_by_trace_count) {\n    for (ssize_t i = 0; i < ssize(cameras); ++i) {\n      int cameraTraces = 0;\n      for (const Trace& trace : traces) {\n        for (const auto& reference : trace.references) {\n          if (cameras[i].id == cameras[getCameraIndex(reference.first)].id) {\n            cameraTraces++;\n            continue;\n          }\n        }\n      }\n      weights[i] = cameraTraces;\n    }\n  }\n  return weights;\n}\n\nbool positionsUnlocked(int pass) {\n  return !FLAGS_lock_positions && pass != 0;\n}\n\ndouble refine(\n    std::vector<Camera>& cameras,\n    const std::vector<Camera>& groundTruth,\n    FeatureMap featureMap,\n    std::vector<Overlap> overlaps,\n    const int pass) {\n  boost::timer::cpu_timer timer;\n  // remove outlier matches\n  LOG(INFO) << \"Removing outlier matches...\";\n  removeOutliersFromCameras(overlaps, featureMap, {}, cameras, FLAGS_outlier_factor);\n\n  // assemble and remove outlier traces\n  LOG(INFO) << \"Assembling traces and removing outlier traces...\";\n  std::vector<Trace> traces = assembleTraces(featureMap, overlaps);\n  triangulateTraces(traces, featureMap, cameras);\n  removeOutliersFromCameras(overlaps, featureMap, traces, cameras, FLAGS_outlier_factor);\n\n  // final triangulation\n  LOG(INFO) << \"Reassembling traces with outliers removed and removing invalid traces...\";\n  traces = assembleTraces(featureMap, overlaps);\n  if (!FLAGS_keep_invalid_traces) {\n    removeInvalidTraces(traces, featureMap);\n  }\n  triangulateTraces(traces, featureMap, cameras);\n\n  std::vector<int> weights = calculateCameraWeights(cameras, traces);\n\n  // visualization for debugging\n  showMatches(cameras, featureMap, overlaps, traces, pass);\n\n  // read camera parameters from cameras\n  std::vector<Camera::Vector3> positions;\n  std::vector<Camera::Vector3> rotations;\n  std::vector<Camera::Vector2> principals;\n  std::vector<Camera::Real> focals;\n  std::vector<Camera::Distortion> distortions;\n  for (Camera& camera : cameras) {\n    positions.push_back(camera.position);\n    rotations.push_back(camera.getRotation());\n    principals.push_back(camera.principal);\n    focals.push_back(camera.getScalarFocal());\n    distortions.push_back(camera.getDistortion());\n  }\n\n  int referenceCameraIdx = -1;\n  int relativeCameraIdx = -1;\n  Camera::Real theta;\n  Camera::Real phi;\n  Camera::Real radius = 0.0; // initialized to silence compiler but this will never get used\n\n  // If positions are unlocked, define a locked reference camera and lock the baseline between\n  // the reference camera and relative camera\n  if (positionsUnlocked(pass)) {\n    if (FLAGS_reference_camera.empty()) {\n      referenceCameraIdx = 0;\n    } else {\n      CHECK(cameraIdToIndex.count(FLAGS_reference_camera))\n          << \"bad reference_camera: \" << FLAGS_reference_camera;\n      referenceCameraIdx = cameraIdToIndex[FLAGS_reference_camera];\n    }\n    relativeCameraIdx = (referenceCameraIdx + 1) % ssize(cameras);\n\n    Camera::Vector3 relativePosition = positions[relativeCameraIdx] - positions[referenceCameraIdx];\n    cartesianToSpherical(radius, theta, phi, relativePosition);\n  }\n\n  // create the problem: add a residual for each observation\n  ceres::Problem problem;\n  std::vector<int> counts(cameras.size());\n  for (const Trace& trace : traces) {\n    if (FLAGS_cap_traces && !randomSample(FLAGS_cap_traces, traces.size())) {\n      continue;\n    }\n    for (const auto& ref : trace.references) {\n      const ImageId& image = ref.first;\n      const Feature& feature = featureMap[image][ref.second];\n      const int camera = getCameraIndex(image);\n      ++counts[camera];\n      const int group = cameraGroupToIndex[cameras[camera].group];\n      if (camera == relativeCameraIdx) {\n        SphericalReprojectionFunctor::addResidual(\n            problem,\n            theta,\n            phi,\n            rotations[camera],\n            principals[FLAGS_shared_principal_and_focal ? group : camera],\n            focals[FLAGS_shared_principal_and_focal ? group : camera],\n            distortions[FLAGS_shared_distortion ? group : camera],\n            traces[feature.trace].position,\n            radius,\n            cameras[referenceCameraIdx].position,\n            cameras[camera],\n            feature.position,\n            FLAGS_robust,\n            weights[camera]);\n      } else {\n        ReprojectionFunctor::addResidual(\n            problem,\n            positions[camera],\n            rotations[camera],\n            principals[FLAGS_shared_principal_and_focal ? group : camera],\n            focals[FLAGS_shared_principal_and_focal ? group : camera],\n            distortions[FLAGS_shared_distortion ? group : camera],\n            traces[feature.trace].position,\n            cameras[camera],\n            feature.position,\n            FLAGS_robust,\n            weights[camera]);\n      }\n    }\n  }\n\n  validateMatchCount(cameras, counts);\n\n  // lock focal and distortion\n  if (pass == 0 || FLAGS_lock_focal) {\n    if (FLAGS_shared_principal_and_focal) {\n      for (const auto& mapping : cameraGroupToIndex) {\n        lockParameter(problem, focals[mapping.second]);\n      }\n    } else {\n      lockParameters(problem, focals);\n    }\n  }\n  if (pass == 0 || FLAGS_lock_distortion) {\n    if (FLAGS_shared_distortion) {\n      for (const auto& mapping : cameraGroupToIndex) {\n        lockParameter(problem, distortions[mapping.second]);\n      }\n    } else {\n      lockParameters(problem, distortions);\n    }\n  }\n  if (FLAGS_lock_principals) {\n    lockParameters(problem, principals);\n  }\n\n  // lock position\n  LOG(INFO) << folly::sformat(\"Pass: {}\", pass);\n  // If positions are unlocked, only lock the position and rotation of the reference camera\n  if (positionsUnlocked(pass)) {\n    problem.SetParameterBlockConstant(positions[referenceCameraIdx].data());\n    problem.SetParameterBlockConstant(rotations[referenceCameraIdx].data());\n  } else {\n    lockParameters(problem, positions);\n  }\n\n  if (FLAGS_lock_rotations) {\n    lockParameters(problem, rotations);\n  }\n\n  if (FLAGS_robust) {\n    std::vector<calibration::ReprojectionErrorOutlier> errorsIgnored =\n        getReprojectionErrorOutliers(problem);\n    LOG(INFO) << folly::sformat(\"Number of down-weighted outliers: {}\", errorsIgnored.size());\n    std::sort(errorsIgnored.begin(), errorsIgnored.end(), math_util::sortdescPair<double, double>);\n    LOG(INFO) << folly::sformat(\"Highest 3 (true/weighted): {}/{}, {}/{}, {}/{}\",\n        errorsIgnored[2].first, errorsIgnored[2].second,\n        errorsIgnored[1].first, errorsIgnored[1].second,\n        errorsIgnored[0].first, errorsIgnored[0].second);\n  }\n  reportReprojectionErrors(overlaps, featureMap, traces, cameras);\n  solve(problem);\n  if (positionsUnlocked(pass)) {\n    positions[relativeCameraIdx] = sphericalToCartesian(radius, theta, phi);\n    positions[relativeCameraIdx] += positions[referenceCameraIdx];\n  }\n\n  std::vector<double> norms =\n      getReprojectionErrorNorms(problem, nullptr, FLAGS_weighted_statistics);\n  double median = calcPercentile(norms, 0.5);\n  if (pass == FLAGS_pass_count - 1 && median > FLAGS_max_error) {\n    LOG(INFO) << folly::sformat(\"Warning: Final pass median error too high: {}\", median);\n  }\n\n  // write optimized camera parameters back into cameras\n  for (int i = 0; i < int(cameras.size()); ++i) {\n    const int group = cameraGroupToIndex[cameras[i].group];\n    cameras[i] = makeCamera(\n        cameras[i],\n        positions[i],\n        rotations[i],\n        principals[FLAGS_shared_principal_and_focal ? group : i],\n        focals[FLAGS_shared_principal_and_focal ? group : i],\n        distortions[FLAGS_shared_distortion ? group : i]);\n  }\n\n  reportReprojectionErrors(overlaps, featureMap, traces, cameras);\n\n  if (FLAGS_points_file != \"\" && pass == FLAGS_pass_count - 1) {\n    savePointsFile(featureMap, traces);\n  }\n  if (FLAGS_points_file_json != \"\" && pass == FLAGS_pass_count - 1) {\n    savePointsFileJson(featureMap, traces);\n  }\n\n  // visualization for debugging\n  if (FLAGS_debug_error_scale && pass == FLAGS_pass_count - 1) {\n    showReprojections(cameras, featureMap, traces, FLAGS_debug_error_scale);\n  }\n\n  if (FLAGS_enable_timing) {\n    LOG(INFO) << folly::sformat(\"Pass {} timing :{}\", pass, timer.format());\n  }\n  return median;\n}\n\ndouble geometricCalibration() {\n  CHECK_NE(FLAGS_rig_in, \"\");\n  CHECK_NE(FLAGS_rig_out, \"\");\n\n  if (FLAGS_debug_error_scale || FLAGS_debug_matches_overlap < 1) {\n    CHECK_NE(FLAGS_color, \"\");\n  }\n\n  if (!FLAGS_debug_dir.empty()) {\n    filesystem::create_directories(FLAGS_debug_dir);\n  }\n\n  const Camera::Rig groundTruth = Camera::loadRig(FLAGS_rig_in);\n  buildCameraIndexMaps(groundTruth);\n  double medianError = 0;\n\n  if (FLAGS_seed != -1) {\n    std::srand(FLAGS_seed);\n  }\n\n  for (int experiment = 0; experiment < FLAGS_experiments; ++experiment) {\n    Camera::Rig cameras = groundTruth;\n\n    Camera::perturbCameras(\n        cameras,\n        FLAGS_perturb_positions,\n        FLAGS_perturb_rotations,\n        FLAGS_perturb_principals,\n        FLAGS_perturb_focals);\n\n    FeatureMap featureMap;\n    std::vector<Overlap> overlaps;\n\n    if (!FLAGS_matches.empty()) {\n      folly::dynamic parsed = parseJsonFile(FLAGS_matches);\n      featureMap = loadFeatureMap(parsed);\n      overlaps = loadOverlaps(parsed);\n    } else {\n      generateArtificalPoints(featureMap, overlaps, groundTruth);\n    }\n\n    LOG(INFO) << getCameraRmseReport(cameras, groundTruth);\n    boost::timer::cpu_timer timer;\n\n    for (int pass = 0; pass < FLAGS_pass_count; ++pass) {\n      medianError = refine(cameras, groundTruth, featureMap, overlaps, pass);\n      std::cout << \"pass \" << pass << \": \" << getCameraRmseReport(cameras, groundTruth)\n                << std::endl;\n    }\n    if (FLAGS_enable_timing) {\n      LOG(INFO) << folly::sformat(\"Aggregate timing: {}\", timer.format());\n    }\n    Camera::saveRig(FLAGS_rig_out, cameras);\n  }\n\n  return medianError;\n}\n", "meta": {"hexsha": "557fde17b61441eb73c523780fcf600ebbd4efbe", "size": 44138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/calibration/GeometricCalibration.cpp", "max_stars_repo_name": "tksharpless/facebook360_dep", "max_stars_repo_head_hexsha": "37f238c26f98db5622c282e08a722d68bd471997", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-10-15T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T03:31:14.000Z", "max_issues_repo_path": "source/calibration/GeometricCalibration.cpp", "max_issues_repo_name": "tksharpless/facebook360_dep", "max_issues_repo_head_hexsha": "37f238c26f98db5622c282e08a722d68bd471997", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/calibration/GeometricCalibration.cpp", "max_forks_repo_name": "tksharpless/facebook360_dep", "max_forks_repo_head_hexsha": "37f238c26f98db5622c282e08a722d68bd471997", "max_forks_repo_licenses": ["BSD-3-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.8916996047, "max_line_length": 100, "alphanum_fraction": 0.6560106937, "num_tokens": 11518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.020023442459047604, "lm_q1q2_score": 0.008307703454865908}}
{"text": "#pragma once\n\n#include <functional>\n#include <set>\n#include <unordered_set>\n#include <boost/container/flat_set.hpp>\n\n#include \"nifty/tools/changable_priority_queue.hxx\"\n#include \"nifty/graph/edge_contraction_graph.hxx\"\n#include \"nifty/graph/agglo/cluster_policies/cluster_policies_common.hxx\"\n\n\n\nnamespace nifty{\nnamespace graph{\nnamespace agglo{\n\n\ntemplate<\n    class GRAPH,bool ENABLE_UCM\n>\nclass NewPolicy{\n\n    typedef NewPolicy<\n        GRAPH, ENABLE_UCM\n    > SelfType;\n\nprivate:    \n    typedef typename GRAPH:: template EdgeMap<uint8_t> UInt8EdgeMap;\n    typedef typename GRAPH:: template EdgeMap<double> FloatEdgeMap;\n    typedef typename GRAPH:: template NodeMap<double> FloatNodeMap;\n\n\n    typedef boost::container::flat_set<uint64_t> SetType;\n    //typedef std::set<uint64_t> SetType;\n    //typedef std::unordered_set<uint64_t> SetType;\n\n\n\n\npublic:\n    // input types\n    typedef GRAPH                                       GraphType;\n    typedef FloatEdgeMap                                EdgePrioType;\n    typedef FloatEdgeMap                                EdgeSizesType;\n    typedef FloatNodeMap                                NodeSizesType;\n\n    struct SettingsType{\n\n        enum UpdateRule{\n            SMOOTH_MAX,\n            GENERALIZED_MEAN\n            //HISTOGRAM_RANK\n        };\n\n        UpdateRule updateRule0{GENERALIZED_MEAN};\n        UpdateRule updateRule1{GENERALIZED_MEAN};\n\n        bool zeroInit = false;\n        double p0{1.0};\n        double p1{1.0};\n        double gamma{0.9}\n        uint64_t numberOfNodesStop{1};\n        //uint64_t numberOfBins{40};\n    };\n\n\n    typedef EdgeContractionGraph<GraphType, SelfType>   EdgeContractionGraphType;\n\n    friend class EdgeContractionGraph<GraphType, SelfType, ENABLE_UCM> ;\nprivate:\n\n    // internal types\n\n\n    typedef nifty::tools::ChangeablePriorityQueue< double , std::greater<double> > QueueType;\n\npublic:\n\n    template<class MERGE_PRIOS, class NOT_MERGE_PRIOS, class IS_LOCAL_EDGE, class EDGE_SIZES>\n    NewPolicy(const GraphType &, \n                              const MERGE_PRIOS & , \n                              const NOT_MERGE_PRIOS &,\n                              const IS_LOCAL_EDGE &,\n                              const EDGE_SIZES & , \n                              const SettingsType & settings = SettingsType());\n\n\n    std::pair<uint64_t, double> edgeToContractNext() const;\n    bool isDone();\n\n    // callback called by edge contraction graph\n    \n    EdgeContractionGraphType & edgeContractionGraph();\n\nprivate:\n    double pqMergePrio(const uint64_t edge) const;\n\npublic:\n    // callbacks called by edge contraction graph\n    void contractEdge(const uint64_t edgeToContract);\n    void mergeNodes(const uint64_t aliveNode, const uint64_t deadNode);\n    void mergeEdges(const uint64_t aliveEdge, const uint64_t deadEdge);\n    void contractEdgeDone(const uint64_t edgeToContract);\n\n    bool isMergeAllowed(const uint64_t edge){\n        if(isLocalEdge_[edge]){\n            // todo this isPureLocal_ seems to be legacy\n            // check if needed\n           return isPureLocal_[edge] ? true : mergePrios_[edge] > notMergePrios_[edge];\n        }\n        else{\n            return false;\n        }\n    }\n    \n\n    const EdgePrioType & mergePrios() const {\n        return mergePrios_;\n    }\n    const EdgePrioType & notMergePrios() const {\n        return notMergePrios_;\n    }\n    const EdgeSizesType & edgeSizes() const {\n        return edgeSizes_;\n    }\n\n    \nprivate:\n\n    const double getMergePrio(const uint64_t edge)const{\n        return mergePrios_[edge];\n    }\n\n    const double notMergePrio(const uint64_t edge)const{\n        return notMergePrios_[edge];\n    }\n\n    // INPUT\n    const GraphType &   graph_;\n\n\n\n    EdgePrioType mergePrios_;\n    EdgePrioType notMergePrios_; \n\n    UInt8EdgeMap isLocalEdge_;\n    UInt8EdgeMap isPureLocal_;\n    UInt8EdgeMap isPureLifted_;\n    EdgeSizesType       edgeSizes_;\n    SettingsType        settings_;\n    \n    // INTERNAL\n    EdgeContractionGraphType edgeContractionGraph_;\n    QueueType pq_;\n\n\n    uint64_t edgeToContractNext_;\n    double   edgeToContractNextMergePrio_;\n};\n\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ntemplate<class MERGE_PRIOS, class NOT_MERGE_PRIOS, class IS_LOCAL_EDGE,class EDGE_SIZES>\ninline NewPolicy<GRAPH, ENABLE_UCM>::\nNewPolicy(\n    const GraphType & graph,\n    const MERGE_PRIOS & mergePrios,\n    const NOT_MERGE_PRIOS & notMergePrios,\n    const IS_LOCAL_EDGE & isLocalEdge,\n    const EDGE_SIZES      & edgeSizes,\n    const SettingsType & settings\n)\n:   graph_(graph),\n    mergePrios_(graph),\n    notMergePrios_(graph),\n    isLocalEdge_(graph),\n    isPureLocal_(graph),\n    isPureLifted_(graph),\n    edgeSizes_(graph),\n    pq_(graph.edgeIdUpperBound()+1),\n    settings_(settings),\n    edgeContractionGraph_(graph, *this)\n{\n   \n    graph_.forEachEdge([&](const uint64_t edge){\n        isLocalEdge_[edge] = isLocalEdge[edge];\n\n        notMergePrios_[edge] = notMergePrios[edge];\n        mergePrios_[edge] = mergePrios[edge];\n\n        if(settings_.zeroInit){\n            if(isLocalEdge_[edge]) \n                notMergePrios_[edge] = 0.0;\n            else\n                mergePrios_[edge] = 0.0;\n        }\n        \n        isPureLocal_[edge] = isLocalEdge[edge];\n        isPureLifted_[edge] = !isLocalEdge[edge];\n\n        edgeSizes_[edge] = edgeSizes[edge];\n        pq_.push(edge, this->pqMergePrio(edge));\n    });\n}\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline std::pair<uint64_t, double> \nNewPolicy<GRAPH, ENABLE_UCM>::\nedgeToContractNext() const {    \n    return std::pair<uint64_t, double>(edgeToContractNext_,edgeToContractNextMergePrio_) ;\n}\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline bool \nNewPolicy<GRAPH, ENABLE_UCM>::\nisDone()     {\n    if(edgeContractionGraph_.numberOfNodes() <= settings_.numberOfNodesStop){\n        //std::cout<<\"done a1\\n\";\n        return  true;\n    }\n    else if(pq_.empty() || pq_.topPriority() <  -0.0000001){\n        //std::cout<<\"done a2\\n\";\n        return  true;\n    }\n    else{\n        while(pq_.topPriority() > -0.0000001 ){\n            const auto nextActioneEdge = pq_.top();\n            if(isLocalEdge_[nextActioneEdge]){\n                if(this->isMergeAllowed(nextActioneEdge)){\n                    edgeToContractNext_ = nextActioneEdge;\n                    edgeToContractNextMergePrio_ = pq_.topPriority();\n                    //std::cout<<\"not done\\n\";\n                    return false;\n                }\n                else{\n                    pq_.push(nextActioneEdge, -1.0);\n                }\n            }\n            else{\n                pq_.push(nextActioneEdge, -1.0);\n            }\n        }\n        //std::cout<<\"done b\\n\";\n        return true;\n    }\n}\n\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline double \nNewPolicy<GRAPH, ENABLE_UCM>::\npqMergePrio(\n    const uint64_t edge\n) const {\n    return isLocalEdge_[edge] ?  mergePrios_[edge] : -1.0; \n}\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline void \nNewPolicy<GRAPH, ENABLE_UCM>::\ncontractEdge(\n    const uint64_t edgeToContract\n){\n    //std::cout<<\"contract edge: \"<<edgeToContract<<\"\\n\"; \n    pq_.deleteItem(edgeToContract);\n}\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline typename NewPolicy<GRAPH, ENABLE_UCM>::EdgeContractionGraphType & \nNewPolicy<GRAPH, ENABLE_UCM>::\nedgeContractionGraph(){\n    return edgeContractionGraph_;\n}\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline void \nNewPolicy<GRAPH, ENABLE_UCM>::\nmergeNodes(\n    const uint64_t aliveNode, \n    const uint64_t deadNode\n){\n\n}\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline void \nNewPolicy<GRAPH, ENABLE_UCM>::\nmergeEdges(\n    const uint64_t aliveEdge, \n    const uint64_t deadEdge\n){\n    //std::cout<<\"    merge edges: a/d \"<<aliveEdge<<\" \"<<deadEdge<<\" \\n\"; \n    NIFTY_CHECK_OP(aliveEdge,!=,deadEdge,\"\");\n    NIFTY_CHECK(pq_.contains(aliveEdge),\"\");\n    NIFTY_CHECK(pq_.contains(deadEdge),\"\");\n    \n\n    pq_.deleteItem(deadEdge);\n\n   \n\n    auto generalized_mean = [](\n        const long double a,\n        const long double d,\n        const long double wa,\n        const long double wd,\n        const long double p\n    ){\n        const long double  eps = 0.000000001;\n        if(std::isinf(p)){\n            // max\n            if(p>0){\n                return std::max(a,d);\n            }\n            // min\n            else{\n                return std::min(a,d);\n            }\n        }\n        else if(p > 1.0-eps && p< 1.0+ eps){\n            return (wa*a + wd*d)/(wa+wd);\n        }\n        else{\n            const auto wad = wa+wd;\n            const auto nwa = wa/wad;\n            const auto nwd = wd/wad;\n            const auto sa = nwa * std::pow(a, p);\n            const auto sd = nwd * std::pow(d, p);\n            return std::pow(sa+sd, 1.0/p);\n        }\n    };\n\n    auto smooth_max = [](\n        const long double a,\n        const long double d,\n        const long double wa,\n        const long double wd,\n        const long double p\n    ){\n        const long double  eps = 0.000000001;\n        if(std::isinf(p)){\n            // max\n            if(p>0){\n                return std::max(a,d);\n            }\n            // min\n            else{\n                return std::min(a,d);\n            }\n        }\n        else if(p > 0.0-eps && p< 0.0+ eps){\n            return (wa*a + wd*d)/(wa+wd);\n        }\n        else{\n\n            const auto eaw = wa * std::exp(a*p);\n            const auto edw = wd * std::exp(d*p);\n            return (a*eaw + d*edw)/(eaw + edw);\n        }\n    };\n\n\n    //  sizes\n    const auto sa = edgeSizes_[aliveEdge];\n    const auto sd = edgeSizes_[deadEdge];\n    const auto zi = settings_.zeroInit ;\n\n\n\n    // update merge prio\n    if(zi && isPureLifted_[aliveEdge] && !isPureLifted_[deadEdge]){\n        mergePrios_[aliveEdge] = mergePrios_[deadEdge];\n    }\n    else if(zi && !isPureLifted_[aliveEdge] && isPureLifted_[deadEdge]){\n        mergePrios_[deadEdge] = mergePrios_[aliveEdge];\n    }\n    else{\n        if(settings_.updateRule0 == SettingsType::GENERALIZED_MEAN){\n            mergePrios_[aliveEdge]    = generalized_mean(mergePrios_[aliveEdge],     mergePrios_[deadEdge],    sa, sd, settings_.p0);\n        }\n        else if(settings_.updateRule0 == SettingsType::SMOOTH_MAX){\n            mergePrios_[aliveEdge]    = smooth_max(mergePrios_[aliveEdge],     mergePrios_[deadEdge],    sa, sd, settings_.p0);\n        }\n        else{\n            NIFTY_CHECK(false,\"not yet implemented\");\n        }\n    }\n\n\n    // update notMergePrio\n    if(zi && isPureLocal_[aliveEdge] && !isPureLocal_[deadEdge]){\n        notMergePrios_[aliveEdge] = notMergePrios_[deadEdge];\n    }\n    else if(zi && !isPureLocal_[aliveEdge] && isPureLocal_[deadEdge]){\n        notMergePrios_[aliveEdge] = notMergePrios_[deadEdge];\n    }\n    else{\n        if(settings_.updateRule0 == SettingsType::GENERALIZED_MEAN){\n            notMergePrios_[aliveEdge] = generalized_mean(notMergePrios_[aliveEdge] , notMergePrios_[deadEdge], sa, sd, settings_.p1);\n        }\n        else if(settings_.updateRule0 == SettingsType::SMOOTH_MAX){\n            notMergePrios_[aliveEdge] = smooth_max(notMergePrios_[aliveEdge] , notMergePrios_[deadEdge], sa, sd, settings_.p1);\n        }\n        else{\n            NIFTY_CHECK(false,\"not yet implemented\");\n        }\n    }\n\n   \n    \n\n    edgeSizes_[aliveEdge] = sa + sd;\n\n    const auto deadIsLocalEdge = isLocalEdge_[deadEdge];\n    auto & aliveIsLocalEdge = isLocalEdge_[aliveEdge];\n    aliveIsLocalEdge = deadIsLocalEdge || aliveIsLocalEdge;\n\n    isPureLocal_[aliveEdge] = isPureLocal_[aliveEdge] && isPureLocal_[deadEdge];\n    isPureLifted_[aliveEdge] = isPureLifted_[aliveEdge] && isPureLifted_[deadEdge];\n\n\n    \n    pq_.push(aliveEdge, this->pqMergePrio(aliveEdge));\n    \n}\n\n\ntemplate<class GRAPH, bool ENABLE_UCM>\ninline void \nNewPolicy<GRAPH, ENABLE_UCM>::\ncontractEdgeDone(\n    const uint64_t edgeToContract\n){\n    //std::cout<<\"contract edge done: \"<<edgeToContract<<\"\\n\\n\";\n}\n\n\n} // namespace agglo\n} // namespace nifty::graph\n} // namespace nifty\n\n", "meta": {"hexsha": "2d8db65bc15e2636d19862b430642e89d2c9c2f7", "size": 11934, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/nifty/graph/agglo/cluster_policies/new_policy.hxx", "max_stars_repo_name": "konopczynski/nifty", "max_stars_repo_head_hexsha": "dc02ac60febaabfaf9b2ee5a854bb61436ebdc97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-06-29T07:42:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T09:25:25.000Z", "max_issues_repo_path": "include/nifty/graph/agglo/cluster_policies/new_policy.hxx", "max_issues_repo_name": "tbullmann/nifty", "max_issues_repo_head_hexsha": "00119fd4753817b931272d6d3120b6ebd334882a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-07-27T16:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:24:36.000Z", "max_forks_repo_path": "include/nifty/graph/agglo/cluster_policies/new_policy.hxx", "max_forks_repo_name": "tbullmann/nifty", "max_forks_repo_head_hexsha": "00119fd4753817b931272d6d3120b6ebd334882a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-01-25T21:21:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T09:25:16.000Z", "avg_line_length": 26.9390519187, "max_line_length": 133, "alphanum_fraction": 0.6116138763, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.023330769487569448, "lm_q1q2_score": 0.008300502030031076}}
{"text": "//\n// Copyright (c) 2010 Dariusz Gadomski <dgadomski@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, 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 and/or\n// 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 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#include <predictionserver.h>\n\n#include <comm/protocol.h>\n#include <arima/arima.h>\n#include <chaos/chaos.h>\n#include <grey/grey.h>\n#include <neural/neuralnet.h>\n#include <util.h>\n\n#include <boost/asio.hpp>\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/thread/mutex.hpp>\n\n// Must come before boost/serialization headers.\n#include <comm/connection.h>\n#include <comm/protocol.h>\n\nnamespace prediction\n{\n\nnamespace server\n{\n\nusing namespace models::dataprovider;\nusing namespace comm;\nusing namespace debug;\n\nPredictionServer::PredictionServer(boost::asio::io_service & io_service,\n        const ParsedOptions& opts) :\n    _acceptor(io_service, boost::asio::ip::tcp::endpoint(\n            boost::asio::ip::tcp::v4(), opts.ListenPort)), _algorithm(\n            opts.Algorithm), _dataProvider(new DataProvider(opts.InputFile)),\n            _opts(opts)\n//  _connection(io_service), _algorithm(opts.Algorithm), _stopFlag(false),\n//          _predictionStarted(false), _opts(opts)\n{\n    connection_ptr new_conn(new connection(_acceptor.get_io_service()));\n    _acceptor.async_accept(new_conn->socket(), boost::bind(\n            &PredictionServer::handle_accept, this,\n            boost::asio::placeholders::error, new_conn));\n\n    createPredictionModel(_algorithm);\n\n}\n\nvoid PredictionServer::handle_read(const boost::system::error_code& e,\n        connection_ptr conn)\n{\n    if (!e)\n    {\n        dbg(debug::Informational) << \"Handle read: \" << std::endl;\n        dbg(debug::Informational) << _inBuffer << std::endl;\n\n        unsigned dataStart = _inBuffer.DataOffset;\n        unsigned dataLength = _inBuffer.DataLength;\n        unsigned horizon = _inBuffer.Horizon;\n\n        std::vector<double> inputBuffer(_dataProvider->getDataVector(dataStart,\n                dataLength));\n\n        _predictionModel->provideInput(inputBuffer, horizon);\n\n        double prediction = _predictionModel->getPrediction(horizon);\n\n//      if( _algorithm == std::string(\"neural\") )\n//      {\n//          printSeq(\"!!! Input: \", inputBuffer, debug::High);\n//          dbg(debug::High) << \"!!! Prediction: \" << prediction << std::endl;\n//      }\n\n        _outBuffer = _inBuffer;\n        _outBuffer.Result = prediction;\n        _outBuffer.Algorithm = _algorithm;\n        _outBuffer.DataOffset = _inBuffer.DataOffset;\n        _outBuffer.DataLength = _inBuffer.DataLength;\n\n        conn->async_write(_outBuffer, boost::bind(\n                &PredictionServer::handle_write, this,\n                boost::asio::placeholders::error, conn));\n    }\n    else\n    {\n        dbg(debug::High) << e.message() << std::endl;\n    }\n}\n\nvoid PredictionServer::handle_write(const boost::system::error_code& e,\n        connection_ptr conn)\n{\n    if (!e)\n    {\n        dbg(debug::Informational) << \"Handle write: \" << std::endl;\n        dbg(debug::Informational) << _outBuffer << std::endl;\n\n        conn->async_read(_inBuffer, boost::bind(&PredictionServer::handle_read,\n                        this, boost::asio::placeholders::error, conn));\n    }\n    else\n    {\n        dbg(debug::High) << e.message() << std::endl;\n    }\n}\n\nvoid PredictionServer::handle_accept(const boost::system::error_code& e,\n        connection_ptr conn)\n{\n    if (!e)\n    {\n        dbg() << \"Accepted connection!\" << std::endl;\n\n        conn->async_read(_inBuffer, boost::bind(&PredictionServer::handle_read,\n                this, boost::asio::placeholders::error, conn));\n\n        connection_ptr new_conn(new connection(_acceptor.get_io_service()));\n        _acceptor.async_accept(new_conn->socket(), boost::bind(\n                &PredictionServer::handle_accept, this,\n                boost::asio::placeholders::error, new_conn));\n    }\n    else\n    {\n        // An error occurred. Log it and return. Since we are not starting a new\n        // accept operation the io_service will run out of work to do and the\n        // server will exit.\n        dbg(debug::High) << e.message() << std::endl;\n    }\n}\n\nvoid PredictionServer::createPredictionModel(const std::string& algorithm)\n{\n    models::AbstractModel *model = 0;\n\n    if (algorithm == \"arima\")\n    {\n        models::arima::Arima *arima = new models::arima::Arima();\n        std::vector<int> order;\n        order.push_back(1);\n        order.push_back(2);\n        order.push_back(1);\n        arima->setOrder(order);\n        model = arima;\n    }\n    else if (algorithm == \"grey\")\n    {\n        model = new models::grey::Grey();\n    }\n    else if (algorithm == \"chaos\")\n    {\n        model = new models::chaos::Chaos(3, 1);\n    }\n    else if (algorithm == \"neural\")\n    {\n        models::neural::NeuralNet *net = models::neural::NeuralNet::load(\"learning.net\");\n        net->setScale(1.0 / _dataProvider->getMaxValue());\n        model = net;\n    }\n\n    if (model)\n    {\n        _predictionModel = boost::shared_ptr<models::AbstractModel>(model);\n    }\n}\n\ndouble PredictionServer::getPrediction(size_t offset, size_t length,\n        size_t horizon, size_t progress)\n{\n    std::vector<double> inputVec = _dataProvider->getDataVector(offset, length);\n\n    if (progress == 0)\n    {\n        _predictionModel->provideInput(inputVec, horizon);\n    }\n\n    // get prediction - progress=0 -> prediction for t+1 etc.\n    return _predictionModel->getPrediction(progress + 1);\n}\n\n}\n}\n", "meta": {"hexsha": "e2e25582c343c2a241f65c8a0ea2b38af497fc8c", "size": 6699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "server/src/predictionserver.cpp", "max_stars_repo_name": "dargad/network-traffic-prediction", "max_stars_repo_head_hexsha": "a7b503acd70a444ad0e4fd34572e6479b75a9b6a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-03-15T12:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-23T06:32:18.000Z", "max_issues_repo_path": "server/src/predictionserver.cpp", "max_issues_repo_name": "dargad/network-traffic-prediction", "max_issues_repo_head_hexsha": "a7b503acd70a444ad0e4fd34572e6479b75a9b6a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/src/predictionserver.cpp", "max_forks_repo_name": "dargad/network-traffic-prediction", "max_forks_repo_head_hexsha": "a7b503acd70a444ad0e4fd34572e6479b75a9b6a", "max_forks_repo_licenses": ["BSD-3-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.5194174757, "max_line_length": 89, "alphanum_fraction": 0.6606956262, "num_tokens": 1548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.022629202134050945, "lm_q1q2_score": 0.008295633243502593}}
{"text": "#include <fstream>  // NOLINT(readability/streams)\n#include <iostream>  // NOLINT(readability/streams)\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <boost/iostreams/device/array.hpp>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"caffe/data_transformer.hpp\"\n#include \"caffe/layers/base_data_layer.hpp\"\n#include \"caffe/layers/molgrid_data_layer.hpp\"\n#include \"caffe/util/benchmark.hpp\"\n#include \"caffe/util/io.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\n#include <openbabel/mol.h>\n#include <openbabel/obconversion.h>\n#include <openbabel/obiter.h>\n#include <boost/timer/timer.hpp>\n\n\n//allocate and initialize atom type data\nnamespace smina_atom_type\n{\n  info data[NumTypes] = {{},};\n\n  struct atom_data_initializer {\n    atom_data_initializer() {\n      for(size_t i = 0u; i < smina_atom_type::NumTypes; ++i)\n        smina_atom_type::data[i] = smina_atom_type::default_data[i];\n    }\n  };\n\n  atom_data_initializer initialize_defaults;\n}\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nMolGridDataLayer<Dtype>::~MolGridDataLayer<Dtype>() {\n  //this->StopInternalThread();\n\n  if(gpu_gridatoms) {\n    cudaFree(gpu_gridatoms);\n    gpu_gridatoms = NULL;\n  }\n  if(gpu_gridwhich) {\n    cudaFree(gpu_gridwhich);\n    gpu_gridwhich = NULL;\n  }\n\n  if(data) delete data;\n  if(data2) delete data2;\n}\n\ntemplate <typename Dtype>\nMolGridDataLayer<Dtype>::example::example(MolGridDataLayer<Dtype>::string_cache& cache, string line, bool hasaffinity, bool hasrmsd)\n  : label(0), affinity(0.0), rmsd(0.0)\n{\n  stringstream stream(line);\n  string tmp;\n  //first the label\n  stream >> label;\n  if(hasaffinity)\n   stream >> affinity;\n  if(hasrmsd)\n   stream >> rmsd;\n  //receptor\n  stream >> tmp;\n  CHECK(tmp.length() > 0) << \"Empty receptor, missing affinity/rmsd? Line:\\n\" << line;\n  receptor = cache.get(tmp);\n  //ligand\n  tmp.clear();\n  stream >> tmp;\n  CHECK(tmp.length() > 0) << \"Empty ligand, missing affinity/rmsd? Line:\\n\" << line;\n\n  ligand = cache.get(tmp);\n}\n\n\n//for in-memory inputs, set the desired label (for gradient computation)\n//note that zero affinity/rmsd means to ignore these\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::setLabels(Dtype pose, Dtype affinity, Dtype rmsd)\n{\n  labels.clear();\n  affinities.clear();\n  rmsds.clear();\n  labels.push_back(pose);\n  affinities.push_back(affinity);\n  rmsds.push_back(rmsd);\n}\n\n\n//the following really shouldn't be recalculated each evaluation (not including gradients)\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getReceptorAtoms(int batch_idx, vector<float4>& atoms)\n{\n  atoms.resize(0);\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n    if (mol.whichGrid[i] < numReceptorTypes)\n      atoms.push_back(mol.atoms[i]);\n}\n\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getLigandAtoms(int batch_idx, vector<float4>& atoms)\n{\n  atoms.resize(0);\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n    if (mol.whichGrid[i] >= numReceptorTypes)\n      atoms.push_back(mol.atoms[i]);\n}\n\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getReceptorChannels(int batch_idx, vector<short>& whichGrid)\n{\n  whichGrid.resize(0);\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n    if (mol.whichGrid[i] < numReceptorTypes)\n      whichGrid.push_back(mol.whichGrid[i]);\n}\n\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getLigandChannels(int batch_idx, vector<short>& whichGrid)\n{\n  whichGrid.resize(0);\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n    if (mol.whichGrid[i] >= numReceptorTypes)\n      whichGrid.push_back(mol.whichGrid[i]);\n}\n\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getReceptorGradient(int batch_idx, vector<float3>& gradient)\n{\n  gradient.resize(0);\n  CHECK(compute_atom_gradients) << \"Gradients requested but not computed\";\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n    if (mol.whichGrid[i] < numReceptorTypes)\n    {\n      gradient.push_back(mol.gradient[i]);\n    }\n}\n\n/*\n * Compute the transformation gradient of a rigid receptor around the center.\n * The first three numbers are the translation.  The next are the torque.\n */\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getReceptorTransformationGradient(int batch_idx, vec& force, vec& torque)\n{\n  force = vec(0,0,0);\n  torque = vec(0,0,0);\n\n  CHECK(compute_atom_gradients) << \"Gradients requested but not computed\";\n  mol_info& mol = batch_transform[batch_idx].mol;\n\n  CHECK(mol.center == mem_lig.center) << \"Centers not equal; receptor transformation gradient only supported in-mem\";\n\n\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n  {\n    if (mol.whichGrid[i] < numReceptorTypes)\n    {\n      float3 g = mol.gradient[i];\n      float4 a = mol.atoms[i];\n      vec v(g.x,g.y,g.z);\n      vec pos(a.x,a.y,a.z);\n\n      force += v;\n      torque += cross_product(pos - mol.center, v);\n    }\n  }\n}\n\n\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getMappedReceptorGradient(int batch_idx, unordered_map<string, float3>& gradient)\n{\n  CHECK(compute_atom_gradients) << \"Gradients requested but not computed\";\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n  {\n    if (mol.whichGrid[i] < numReceptorTypes)\n    {\n        string xyz = xyz_to_string(mol.atoms[i].x, mol.atoms[i].y, mol.atoms[i].z);\n        gradient[xyz] = mol.gradient[i];\n    }\n  }\n}\n\n\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getLigandGradient(int batch_idx, vector<float3>& gradient)\n{\n  CHECK(compute_atom_gradients) << \"Gradients requested but not computed\";\n  gradient.resize(0);\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n    if (mol.whichGrid[i] >= numReceptorTypes)\n    {\n      gradient.push_back(mol.gradient[i]);\n    }\n}\n\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::getMappedLigandGradient(int batch_idx, unordered_map<string, float3>& gradient)\n{\n  CHECK(compute_atom_gradients) << \"Gradients requested but not computed\";\n  mol_info& mol = batch_transform[batch_idx].mol;\n  for (unsigned i = 0, n = mol.atoms.size(); i < n; ++i)\n  {\n    if (mol.whichGrid[i] >= numReceptorTypes)\n    {\n        string xyz = xyz_to_string(mol.atoms[i].x, mol.atoms[i].y, mol.atoms[i].z);\n        gradient[xyz] = mol.gradient[i];\n    }\n  }\n}\n\n\n//modify examples to remove any without both actives an inactives\n//factored this into its own function due to the need to fully specialize setup below\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::remove_missing_and_setup(vector<typename MolGridDataLayer<Dtype>::balanced_example_provider>& examples)\n{\n  vector<balanced_example_provider> tmp;\n  for(unsigned i = 0, n = examples.size(); i < n; i++)\n  {\n    if(examples[i].num_actives() > 0 && examples[i].num_decoys() > 0) {\n      //eliminate empty buckets\n      tmp.push_back(examples[i]);\n      tmp.back().setup();\n    }\n    else if(examples[i].num_actives() > 0)\n    {\n      example tmp;\n      examples[i].next_active(tmp);\n      LOG(INFO) << \"Dropping receptor \" << tmp.receptor << \" with no decoys.\";\n    }\n    else if(examples[i].num_decoys() > 0)\n    {\n      example tmp;\n      examples[i].next_decoy(tmp);\n      LOG(INFO) << \"Dropping receptor \" << tmp.receptor << \" with no decoys.\";\n    }\n  }\n\n  swap(examples,tmp);\n}\n\n//specialized version for balanced data that remove receptors without any actives or decoys\n//annoyingly, have to specialize Dtype\ntemplate<>\ntemplate<>\nvoid MolGridDataLayer<float>::receptor_stratified_example_provider<typename MolGridDataLayer<float>::balanced_example_provider, 2>::setup()\n{\n  currenti = 0; currentk = 0;\n  remove_missing_and_setup(examples);\n  //also shuffle receptors\n  if(randomize) shuffle(examples.begin(), examples.end(), caffe::caffe_rng());\n}\n\ntemplate<>\ntemplate<>\nvoid MolGridDataLayer<double>::receptor_stratified_example_provider<typename MolGridDataLayer<double>::balanced_example_provider, 2>::setup()\n{\n  currenti = 0; currentk = 0;\n  remove_missing_and_setup(examples);\n  //also shuffle receptors\n  if(randomize) shuffle(examples.begin(), examples.end(), caffe::caffe_rng());\n}\n\n\n\n//ensure gpu memory is of sufficient size\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::allocateGPUMem(unsigned sz)\n{\n  if(sz > gpu_alloc_size) {\n    //deallocate\n    if(gpu_gridatoms) {\n      cudaFree(gpu_gridatoms);\n    }\n    if(gpu_gridwhich) {\n      cudaFree(gpu_gridwhich);\n    }\n    //allocate larger\n    CUDA_CHECK(cudaMalloc(&gpu_gridatoms, sz*sizeof(float4)));\n    CUDA_CHECK(cudaMalloc(&gpu_gridwhich, sz*sizeof(short)));\n  }\n}\n\n//allocate and return an example provider to the specifications of the parm object\ntemplate <typename Dtype>\ntypename MolGridDataLayer<Dtype>::example_provider* MolGridDataLayer<Dtype>::create_example_data(const MolGridDataParameter& parm)\n{\n  bool balanced  = parm.balanced();\n  bool strat_receptor  = parm.stratify_receptor();\n  bool strat_aff = parm.stratify_affinity_max() != parm.stratify_affinity_min();\n\n  //strat_aff > strat_receptor > balanced\n  if(strat_aff)\n  {\n    if(strat_receptor)\n    {\n      if(balanced) // sample 2 from each receptor\n      {\n        return new affinity_stratified_example_provider<receptor_stratified_example_provider<balanced_example_provider, 2> >(parm);\n      }\n      else //sample 1 from each receptor\n      {\n        return new affinity_stratified_example_provider<receptor_stratified_example_provider<uniform_example_provider, 1> >(parm);\n      }\n    }\n    else\n    {\n      if(balanced)\n      {\n        return new affinity_stratified_example_provider<balanced_example_provider>(parm);\n      }\n      else //sample 1 from each receptor\n      {\n        return new affinity_stratified_example_provider<uniform_example_provider>(parm);\n      }\n    }\n  }\n  else if(strat_receptor)\n  {\n    if(balanced) // sample 2 from each receptor\n    {\n      return new receptor_stratified_example_provider<balanced_example_provider, 2>(parm);\n    }\n    else //sample 1 from each receptor\n    {\n      return new receptor_stratified_example_provider<uniform_example_provider, 1>(parm);\n    }\n  }\n  else if(balanced)\n  {\n    return new balanced_example_provider(parm);\n  }\n  else\n  {\n    return new uniform_example_provider(parm);\n  }\n}\n\n//make sure can append to root_folder path\nstatic string sanitize_path(const string& p)\n{\n  //make sure root folder(s) have trailing slash\n  if (p.length() > 0 && p[p.length()-1] != '/')\n    return p + \"/\";\n  else\n    return p;\n}\n\n//fill in training examples\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::populate_data(const string& root_folder, const string& source,\n    MolGridDataLayer<Dtype>::example_provider* data, bool hasaffinity, bool hasrmsd)\n{\n  LOG(INFO) << \"Opening file \" << source;\n  std::ifstream infile(source.c_str());\n  CHECK((bool)infile) << \"Could not open \" << source;\n  string line;\n  while (getline(infile, line))\n  {\n    example ex(scache, line, hasaffinity, hasrmsd);\n    data->add(ex);\n  }\n  CHECK_GT(data->size(),0) << \"No examples provided in source: \" << source;\n\n  data->setup(); //done adding\n\n}\n\n//read in structure input and atom type maps\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,\n      const vector<Blob<Dtype>*>& top) {\n\n  const MolGridDataParameter& param = this->layer_param_.molgrid_data_param();\n  root_folder = param.root_folder();\n  num_rotations = param.rotate();\n  inmem = param.inmemory();\n  dimension = param.dimension();\n  resolution = param.resolution();\n  binary = param.binary_occupancy();\n  bool spherize = param.spherical_mask();\n  randtranslate = param.random_translate();\n  randrotate = param.random_rotation();\n  ligpeturb = param.peturb_ligand();\n  ligpeturb_translate = param.peturb_ligand_translate();\n  ligpeturb_rotate = param.peturb_ligand_rotate();\n  jitter = param.jitter();\n  ignore_ligand = param.ignore_ligand();\n  radiusmultiple = param.radius_multiple();\n  fixedradius = param.fixed_radius();\n  bool hasaffinity = param.has_affinity();\n  bool hasrmsd = param.has_rmsd();\n  data_ratio = param.source_ratio();\n  root_folder2 = param.root_folder2();\n\n  if(binary) radiusmultiple = 1.0;\n\n  gmaker.initialize(resolution, dimension, radiusmultiple, binary, spherize);\n\n  dim = round(dimension/resolution)+1; //number of grid points on a side\n  numgridpoints = dim*dim*dim;\n  if(numgridpoints % 512 != 0)\n    LOG(INFO) << \"Total number of grid points (\" << numgridpoints << \") is not evenly divisible by 512.\";\n\n  //shape must come from parameters\n  int batch_size = param.batch_size();\n\n  if(!inmem)\n  {\n\n    const string& source = param.source();\n    const string& source2 = param.source2();\n    root_folder = sanitize_path(param.root_folder());\n    root_folder2 = param.root_folder2();\n    if(root_folder2.length() > 0) root_folder2 = sanitize_path(root_folder2);\n    else root_folder2 = root_folder; //fall back on first\n\n    CHECK_GT(source.length(), 0) << \"No data source file provided\";\n\n    // Read source file(s) with labels and structures,\n    // each line is label [affinity] [rmsd] receptor_file ligand_file\n    data = create_example_data(param);\n    populate_data(root_folder, source, data, hasaffinity, hasrmsd);\n\n    if(source2.length() > 0)\n    {\n      CHECK_GE(data_ratio, 0) << \"Must provide non-negative ratio for two data sources\";\n      data2 = create_example_data(param);\n      populate_data(root_folder2, source2, data2, hasaffinity, hasrmsd);\n    }\n\n    LOG(INFO) << \"Total examples: \" << data->size() + (data2 ? data2->size() : 0);\n\n    // Check if we would need to randomly skip a few data points\n    if (param.rand_skip())\n    {\n      unsigned int skip = caffe_rng_rand() %  param.rand_skip();\n\n      LOG(INFO) << \"Skipping first \" << skip << \" data points from each source.\";\n\n      example dummy;\n      for(unsigned i = 0; i < skip; i++) {\n        data->next(dummy);\n      }\n      if(data2)\n      {\n        for(unsigned i = 0; i < skip; i++) {\n          data2->next(dummy);\n        }\n      }\n    }\n  }\n  else //in memory always batch size of 1\n  {\n    batch_size = 1;\n  }\n\n  CHECK_GT(batch_size, 0) << \"Positive batch size required\";\n  //keep track of atoms and transformations for each example in batch\n  batch_transform.resize(batch_size);\n\n  //initialize atom type maps\n  string recmap = param.recmap();\n  string ligmap = param.ligmap();\n\n  if (recmap.size() == 0)\n    numReceptorTypes = GridMaker::createDefaultRecMap(rmap);\n  else\n    numReceptorTypes = GridMaker::createAtomTypeMap(recmap, rmap);\n\n  if (ligmap.size() == 0)\n    numLigandTypes = GridMaker::createDefaultLigMap(lmap);\n  else\n    numLigandTypes = GridMaker::createAtomTypeMap(ligmap, lmap);\n\n\n  //setup shape of layer\n  top_shape.clear();\n  top_shape.push_back(batch_size);\n  top_shape.push_back(numReceptorTypes+numLigandTypes);\n  top_shape.push_back(dim);\n  top_shape.push_back(dim);\n  top_shape.push_back(dim);\n\n  example_size = (numReceptorTypes+numLigandTypes)*numgridpoints;\n\n  // Reshape prefetch_data and top[0] according to the batch_size.\n  top[0]->Reshape(top_shape);\n\n  // Reshape label, affinity, rmsds\n  vector<int> label_shape(1, batch_size); // [batch_size]\n\n  top[1]->Reshape(label_shape);\n\n  if (hasaffinity)\n  {\n    top[2]->Reshape(label_shape);\n    if (hasrmsd)\n    {\n      top[3]->Reshape(label_shape);\n    }\n  }\n  else if(hasrmsd)\n  {\n    top[2]->Reshape(label_shape);\n  }\n\n  if(ligpeturb) {\n    vector<int> peturbshape(2);\n    peturbshape[0] = batch_size;\n    peturbshape[1] = 6; //trans+orient\n    top.back()->Reshape(peturbshape);\n  }\n}\n\n//return quaternion representing one of 24 distinct axial rotations\ntemplate <typename Dtype>\ntypename MolGridDataLayer<Dtype>::quaternion MolGridDataLayer<Dtype>::axial_quaternion()\n{\n  unsigned rot = current_rotation;\n  qt ret;\n  //first rotate to a face\n  switch(rot%6) {\n    case 0:\n      ret = quaternion(1,0,0,0); //identity\n      break;\n    case 1: //rotate z 90\n      ret = quaternion(sqrt(0.5),0,0,sqrt(0.5));\n      break;\n    case 2: //rotate z 180\n      ret = quaternion(0,0,0,1);\n      break;\n    case 3: //rotate z 270 (-90)\n      ret = quaternion(sqrt(0.5),0,0,-sqrt(0.5));\n      break;\n    case 4: //rotate y 90\n      ret = quaternion(sqrt(0.5),0,sqrt(0.5),0);\n      break;\n    case 5: //rotate y -90\n      ret = quaternion(sqrt(0.5),0,-sqrt(0.5),0);\n      break;\n  }\n\n  //now four rotations around x axis\n  rot /= 6;\n  switch(rot%4) {\n    case 0:\n      break; //identity\n    case 1: //90 degrees\n      ret *= quaternion(sqrt(0.5),sqrt(0.5),0,0);\n      break;\n    case 2: //180\n      ret *= quaternion(0,1,0,0);\n      break;\n    case 3: //270\n      ret *= quaternion(sqrt(0.5),-sqrt(0.5),0,0);\n      break;\n  }\n  return ret;\n}\n\n\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::set_mol_info(const string& file, const vector<int>& atommap,\n    unsigned mapoffset, mol_info& minfo)\n{\n  //read mol info from file\n  //OpenBabel is SLOW, especially for the receptor, so we cache the result\n  //if this gets too annoying, can add support for spawning a thread for openbabel\n  //but since this gets amortized across many hits to the same example, not a high priority\n  using namespace OpenBabel;\n\n  vec center(0,0,0);\n  minfo.atoms.clear();\n  minfo.whichGrid.clear();\n  minfo.gradient.clear();\n\n  //also, implemented a custom gninatypes files to precalc this info\n  if(boost::algorithm::ends_with(file,\".gninatypes\"))\n  {\n    struct info {\n      float x,y,z;\n      int type;\n    } atom;\n\n    ifstream in(file.c_str());\n    CHECK(in) << \"Could not read \" << file;\n\n    int cnt = 0;\n    while(in.read((char*)&atom, sizeof(atom)))\n    {\n      smt t = (smt)atom.type;\n      int index = atommap[t];\n\n      if(index >= 0)\n      {\n        cnt++;\n        float4 ainfo;\n        ainfo.x = atom.x;\n        ainfo.y = atom.y;\n        ainfo.z = atom.z;\n        if(fixedradius <= 0)\n        \tainfo.w = xs_radius(t);\n        else\n        \tainfo.w = fixedradius;\n        float3 gradient(0,0,0);\n\n        minfo.atoms.push_back(ainfo);\n        minfo.whichGrid.push_back(index+mapoffset);\n        minfo.gradient.push_back(gradient);\n        center += vec(atom.x,atom.y,atom.z);\n      }\n      else if(t > 1) //silence on hydrogens\n      {\n       std::cerr << \"WARNING: Unknown atom type \" << t << \" in \" << file << \".  This atom will be discarded\\n\";\n      }\n    }\n\n    if(cnt == 0) {\n      std::cerr << \"WARNING: No atoms in \" << file <<\"\\n\";\n    }\n    else {\n      center /= cnt;\n    }\n  }\n  else if(!boost::algorithm::ends_with(file,\"none\")) //reserved word\n  {\n    //read mol from file and set mol info (atom coords and grid positions)\n    //types are mapped using atommap values plus offset\n    OpenBabel::OBConversion conv;\n    OBMol mol;\n    CHECK(conv.ReadFile(&mol, file)) << \"Could not read \" << file;\n\n    if(this->layer_param_.molgrid_data_param().addh()) {\n      mol.AddHydrogens();\n    }\n\n    minfo.atoms.reserve(mol.NumHvyAtoms());\n    minfo.whichGrid.reserve(mol.NumHvyAtoms());\n    minfo.gradient.reserve(mol.NumHvyAtoms());\n\n    int cnt = 0;\n    FOR_ATOMS_OF_MOL(a, mol)\n    {\n      smt t = obatom_to_smina_type(*a);\n      int index = atommap[t];\n\n      if(index >= 0)\n      {\n        cnt++;\n        float4 ainfo;\n        ainfo.x = a->x();\n        ainfo.y = a->y();\n        ainfo.z  = a->z();\n        if(fixedradius <= 0)\n        \tainfo.w = xs_radius(t);\n        else\n        \tainfo.w = fixedradius;\n        float3 gradient(0,0,0);\n\n        minfo.atoms.push_back(ainfo);\n        minfo.whichGrid.push_back(index+mapoffset);\n        minfo.gradient.push_back(gradient);\n        center += vec(a->x(),a->y(),a->z());\n      }\n      else\n      {\n        std::cerr << \"WARNING: Unknown atom type in \" << file << \".  This atom will be discarded\\n\";\n      }\t\n    }\n    center /= cnt;\n  }\n\n  minfo.center = center;\n\n}\n\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::set_grid_ex(Dtype *data, const MolGridDataLayer<Dtype>::example& ex,\n    const string& root_folder, MolGridDataLayer<Dtype>::mol_transform& transform, output_transform& peturb, bool gpu)\n{\n  //set grid values for example\n  //cache atom info\n  bool docache = this->layer_param_.molgrid_data_param().cache_structs();\n\n  if(docache)\n  {\n    if(molcache.count(ex.receptor) == 0)\n    {\n      set_mol_info(root_folder+ex.receptor, rmap, 0, molcache[ex.receptor]);\n    }\n    if(molcache.count(ex.ligand) == 0)\n    {\n      set_mol_info(root_folder+ex.ligand, lmap, numReceptorTypes, molcache[ex.ligand]);\n    }\n\n    set_grid_minfo(data, molcache[ex.receptor], molcache[ex.ligand], transform, peturb, gpu);\n  }\n  else\n  {\n    mol_info rec;\n    mol_info lig;\n    set_mol_info(root_folder+ex.receptor, rmap, 0, rec);\n    set_mol_info(root_folder+ex.ligand, lmap, numReceptorTypes, lig);\n    set_grid_minfo(data, rec, lig, transform, peturb, gpu);\n  }\n}\n\n\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::set_grid_minfo(Dtype *data, const MolGridDataLayer<Dtype>::mol_info& recatoms,\n  const MolGridDataLayer<Dtype>::mol_info& ligatoms, MolGridDataLayer<Dtype>::mol_transform& transform,\n  output_transform& peturb, bool gpu)\n{\n  //set grid values from mol info\n  //first clear transform from the previous batch\n  rng_t* rng = caffe_rng();\n  transform = mol_transform();\n  mol_transform ligtrans;\n\n  //include receptor and ligand atoms\n  transform.mol.append(recatoms);\n  //set center to ligand center\n  transform.mol.center = ligatoms.center;\n\n  if(ligpeturb) {\n    if(ligpeturb_rotate)\n    {\n      ligtrans.set_random_quaternion(rng);\n    }\n    else\n    {\n      ligtrans.Q = quaternion(1,0,0,0); //identity\n    }\n    ligtrans.add_random_displacement(rng, ligpeturb_translate);\n    transform.mol.transform_and_append(ligatoms, ligtrans);\n\n    //store the inverse transformation\n    peturb.x = -ligtrans.center[0];\n    peturb.y = -ligtrans.center[1];\n    peturb.z = -ligtrans.center[2];\n\n    qt qinv = conj(ligtrans.Q)/norm(ligtrans.Q); //not Cayley, not euclidean norm - already squared\n    peturb.set_from_quaternion(qinv);\n\n    //set the center to the translated value\n    transform.mol.center = ligatoms.center + ligtrans.center;\n  } else if(ignore_ligand) {\n    //do nothing - ligand is only used to set center\n  } else {\n    transform.mol.append(ligatoms);\n  }\n\n  //figure out transformation\n  transform.Q = quaternion(1,0,0,0);\n\n  if(current_rotation == 0 && !randrotate)\n    transform.Q = quaternion(1,0,0,0); //check real part to avoid mult\n\n  if (randrotate)\n  {\n    transform.set_random_quaternion(rng);\n  }\n\n  transform.center[0] = transform.mol.center[0];\n  transform.center[1] = transform.mol.center[1];\n  transform.center[2] = transform.mol.center[2];\n  if (randtranslate)\n  {\n    double radius = ligatoms.radius();\n    //don't let ligand atoms translate out of sphere inscribed in box\n    if(ignore_ligand) radius = 0;\n    double maxtrans = max(dimension/2.0 - radius,0.0);\n    transform.add_random_displacement(rng, min(randtranslate,maxtrans));\n  }\n\n  if(current_rotation > 0) {\n    transform.Q *= axial_quaternion();\n  }\n\n  //TODO move this into gridmaker.setAtoms, have it just take the mol_transform as input - separate receptor transform as well\n  gmaker.setCenter(transform.center[0], transform.center[1], transform.center[2]);\n\n  if(transform.mol.atoms.size() == 0) {\n     std::cerr << \"ERROR: No atoms in molecule.  I can't deal with this.\\n\";\n     exit(-1); //presumably you never actually want this and it results in a cuda error\n  } \n  if(jitter > 0) {\n    //add small random displacement (in-place) to atoms\n    for(unsigned i = 0, n = transform.mol.atoms.size(); i < n; i++) {\n      float4& atom = transform.mol.atoms[i];\n      float xdiff = jitter*(unit_sample(rng)*2.0-1.0);\n      atom.x += xdiff;\n      float ydiff = jitter*(unit_sample(rng)*2.0-1.0);\n      atom.y += ydiff;\n      float zdiff = jitter*(unit_sample(rng)*2.0-1.0);\n      atom.z += zdiff;\n    }\n  }\n\n  //compute grid from atom info arrays\n  if(gpu)\n  {\n    unsigned natoms = transform.mol.atoms.size();\n    allocateGPUMem(natoms);\n    CUDA_CHECK(cudaMemcpy(gpu_gridatoms, &transform.mol.atoms[0], natoms*sizeof(float4), cudaMemcpyHostToDevice));\n    CUDA_CHECK(cudaMemcpy(gpu_gridwhich, &transform.mol.whichGrid[0], natoms*sizeof(short), cudaMemcpyHostToDevice));\n\n    gmaker.setAtomsGPU<Dtype>(natoms, gpu_gridatoms, gpu_gridwhich, transform.Q, numReceptorTypes+numLigandTypes, data);\n  }\n  else\n  {\n    Grids grids(data, boost::extents[numReceptorTypes+numLigandTypes][dim][dim][dim]);\n    gmaker.setAtomsCPU(transform.mol.atoms, transform.mol.whichGrid, transform.Q.boost(), grids);\n  }\n}\n\n\n//return a string representation of the atom type(s) represented by index\n//in map - this isn't particularly efficient, but is only for debug purposes\ntemplate <typename Dtype>\nstring MolGridDataLayer<Dtype>::getIndexName(const vector<int>& map, unsigned index) const\n\t\t{\n\tstringstream ret;\n\tstringstream altret;\n\tfor (unsigned at = 0; at < smina_atom_type::NumTypes; at++)\n\t{\n\t\tif (map[at] == index)\n\t\t{\n\t\t\tret << smina_type_to_string((smt) at);\n\t\t\taltret << \"_\" << at;\n\t\t}\n\t}\n\n\tif (ret.str().length() > 32) //there are limits on file name lengths\n\t\treturn altret.str();\n\telse\n\t\treturn ret.str();\n}\n\n\n//output a grid the file in dx format (for debug)\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::outputDXGrid(std::ostream& out, Grids& grid, unsigned g, double scale) const\n{\n  unsigned n = dim;\n  out.precision(5);\n  setprecision(5);\n  out << fixed;\n  out << \"object 1 class gridpositions counts \" << n << \" \" << n << \" \" << \" \" << n << \"\\n\";\n  out << \"origin\";\n  for (unsigned i = 0; i < 3; i++)\n  {\n    out << \" \" << mem_lig.center[i]-dimension/2.0;\n  }\n  out << \"\\n\";\n  out << \"delta \" << resolution << \" 0 0\\ndelta 0 \" << resolution << \" 0\\ndelta 0 0 \" << resolution << \"\\n\";\n  out << \"object 2 class gridconnections counts \" << n << \" \" << n << \" \" << \" \" << n << \"\\n\";\n  out << \"object 3 class array type double rank 0 items [ \" << n*n*n << \"] data follows\\n\";\n  //now coordinates - x,y,z\n  out << scientific;\n  out.precision(6);\n  unsigned total = 0;\n  for (unsigned i = 0; i < n; i++)\n  {\n    for (unsigned j = 0; j < n; j++)\n    {\n      for (unsigned k = 0; k < n; k++)\n      {\n        out << grid[g][i][j][k]*scale;\n        total++;\n        if(total % 3 == 0) out << \"\\n\";\n        else out << \" \";\n      }\n    }\n  }\n}\n\n//dump dx files for every atom type, with files names starting with prefix\n//only does the very first grid for now\ntemplate<typename Dtype>\nvoid MolGridDataLayer<Dtype>::dumpDiffDX(const std::string& prefix,\n\t\tBlob<Dtype>* top, double scale) const\n{\n\tGrids grids(top->mutable_cpu_diff(),\n\t\t\tboost::extents[numReceptorTypes + numLigandTypes][dim][dim][dim]);\n    CHECK_GT(mem_lig.atoms.size(),0) << \"DX dump only works with in-memory ligand\";\n    CHECK_EQ(randrotate, false) << \"DX dump requires no rotation\";\n\tfor (unsigned a = 0, na = numReceptorTypes; a < na; a++) {\n\t\tstring name = getIndexName(rmap, a);\n\t\tstring fname = prefix + \"_rec_\" + name + \".dx\";\n\t\tofstream out(fname.c_str());\n\t\toutputDXGrid(out, grids, a, scale);\n\t}\n\tfor (unsigned a = 0, na = numLigandTypes; a < na; a++) {\n\t\t\tstring name = getIndexName(lmap, a);\n\t\t\tstring fname = prefix + \"_lig_\" + name + \".dx\";\n\t\t\tofstream out(fname.c_str());\n\t\t\toutputDXGrid(out, grids, numReceptorTypes+a, scale);\n\t}\n\n}\n\n\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n    const vector<Blob<Dtype>*>& top)\n{\n  forward(bottom, top, false);\n}\n\n\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu)\n{\n  bool hasaffinity = this->layer_param_.molgrid_data_param().has_affinity();\n  bool hasrmsd = this->layer_param_.molgrid_data_param().has_rmsd();\n\n  Dtype *top_data = NULL;\n  if(gpu)\n    top_data = top[0]->mutable_gpu_data();\n  else\n    top_data = top[0]->mutable_cpu_data();\n\n  perturbations.clear();\n  unsigned batch_size = top_shape[0];\n  output_transform peturb;\n\n  //if in memory must be set programmatically\n  if(inmem)\n  {\n    CHECK_GT(mem_rec.atoms.size(),0) << \"Receptor not set in MolGridDataLayer\";\n    CHECK_GT(mem_lig.atoms.size(),0) << \"Ligand not set in MolGridDataLayer\";\n    //memory is now available\n    set_grid_minfo(top_data, mem_rec, mem_lig, batch_transform[0], peturb, gpu); //TODO how do we know what batch position?\n    perturbations.push_back(peturb);\n\n    if (num_rotations > 0) {\n      current_rotation = (current_rotation+1)%num_rotations;\n    }\n\n    CHECK_GT(labels.size(),0) << \"Did not set labels in memory based molgrid\";\n\n  }\n  else\n  {\n    //clear batch labels\n    labels.clear();\n    affinities.clear();\n    rmsds.clear();\n\n    //percent of batch from first data source\n    unsigned dataswitch = batch_size;\n    if (data2)\n      dataswitch = batch_size*data_ratio/(data_ratio+1);\n\n    for (int batch_idx = 0; batch_idx < batch_size; ++batch_idx)\n    {\n      example ex;\n      string *root;\n      if (batch_idx < dataswitch)\n      {\n        data->next(ex);\n        root = &root_folder;\n      }\n      else\n      {\n        data2->next(ex);\n        root = &root_folder2;\n      }\n\n      labels.push_back(ex.label);\n      affinities.push_back(ex.affinity);\n      rmsds.push_back(ex.rmsd);\n\n      int offset = batch_idx*example_size;\n      set_grid_ex(top_data+offset, ex, *root, batch_transform[batch_idx], peturb, gpu);\n      perturbations.push_back(peturb);\n      //NOTE: num_rotations not actually implemented!\n    }\n\n  }\n\n  if(gpu) {\n    caffe_copy(labels.size(), &labels[0], top[1]->mutable_gpu_data());\n    if(hasaffinity) {\n      caffe_copy(affinities.size(), &affinities[0], top[2]->mutable_gpu_data());\n      if(hasrmsd) {\n        caffe_copy(rmsds.size(), &rmsds[0], top[3]->mutable_gpu_data());\n      }\n    } else if(hasrmsd) {\n      caffe_copy(rmsds.size(), &rmsds[0], top[2]->mutable_gpu_data());\n    }\n\n    if(ligpeturb) {\n      //trusting struct layout is normal\n      caffe_copy(perturbations.size()*6, (Dtype*)&perturbations[0], top.back()->mutable_gpu_data());\n    }\n\n  }\n  else {\n    caffe_copy(labels.size(), &labels[0], top[1]->mutable_cpu_data());\n    if(hasaffinity) {\n      caffe_copy(affinities.size(), &affinities[0], top[2]->mutable_cpu_data());\n      if(hasrmsd) {\n        caffe_copy(rmsds.size(), &rmsds[0], top[3]->mutable_cpu_data());\n      }\n    } else if(hasrmsd) {\n      caffe_copy(rmsds.size(), &rmsds[0], top[2]->mutable_cpu_data());\n    }\n    if(ligpeturb) {\n      //trusting struct layout is normal\n      caffe_copy(perturbations.size()*6, (Dtype*)&perturbations[0], top.back()->mutable_cpu_data());\n    }\n  }\n\n}\n\n\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n    const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom)\n{\n  backward(top, bottom, false);\n}\n\n\n/* backpropagates gradients onto atoms (note there is not actual bottom)\n * Only performed when compute_atom_gradients is true.\n */\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::backward(const vector<Blob<Dtype>*>& top, const vector<Blob<Dtype>*>& bottom, bool gpu)\n{\n  //propagate gradient grid onto atom positions\n  if(compute_atom_gradients) {\n    unsigned batch_size = top_shape[0];\n    Dtype *diff = NULL;\n    if(gpu) {\n      diff = top[0]->mutable_gpu_diff();\n      setAtomGradientsGPU(gmaker, diff, batch_size);\n    }\n    else {\n      diff = top[0]->mutable_cpu_diff();\n      for (int item_id = 0; item_id < batch_size; ++item_id) {\n\n        int offset = item_id*example_size;\n        Grids grids(diff+offset, boost::extents[numReceptorTypes+numLigandTypes][dim][dim][dim]);\n\n        mol_transform& transform = batch_transform[item_id];\n        gmaker.setCenter(transform.center[0], transform.center[1], transform.center[2]);\n        gmaker.setAtomGradientsCPU(transform.mol.atoms, transform.mol.whichGrid, \n                transform.Q.boost(), grids, transform.mol.gradient);\n      }\n    }\n  }\n}\n\ntemplate <typename Dtype>\nvoid MolGridDataLayer<Dtype>::Backward_relevance(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom)\n{\n\n  /*\n  float top_sum = 0.0;\n\n  std::cout << \"MOLGRID TOP:\";\n  for(int i = 0; i < top[0]->count(); i++)\n  {\n          top_sum += top[0]->cpu_diff()[i];\n  }\n  std::cout << \"MOLGRID TOP: \" << top_sum << '\\n';\n  */\n\n  Dtype *diff = top[0]->mutable_cpu_diff(); //TODO: implement gpu\n\n  //propagate gradient grid onto atom positions\n  unsigned batch_size = top_shape[0];\n  for (int item_id = 0; item_id < batch_size; ++item_id) {\n\n    int offset = item_id*example_size;\n    Grids grids(diff+offset, boost::extents[numReceptorTypes+numLigandTypes][dim][dim][dim]);\n\n    mol_transform& transform = batch_transform[item_id];\n    gmaker.setCenter(transform.center[0], transform.center[1], transform.center[2]);\n    gmaker.setAtomRelevanceCPU(transform.mol.atoms, transform.mol.whichGrid, transform.Q.boost(), grids,\n        transform.mol.gradient);\n  }\n\n  //float bottom_sum = 0.0;\n  //for(int i = 0; i < bottom[0]->count(); i++)\n  //{\n  //        bottom_sum += bottom[0]->cpu_diff()[i];\n  //}\n  //std::cout << \"MOLGRID BOTTOM: \" << bottom_sum << '\\n';\n\n\n}\n\n\n\nINSTANTIATE_CLASS(MolGridDataLayer);\nREGISTER_LAYER_CLASS(MolGridData);\n\n}  // namespace caffe\n", "meta": {"hexsha": "0d7f45ce0076541520dcb2590df1cc13a7cf7ae8", "size": 33560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/molgrid_data_layer.cpp", "max_stars_repo_name": "gnina/caffe", "max_stars_repo_head_hexsha": "59b3451cd54ae106de3335876ba25f68b9553098", "max_stars_repo_licenses": ["Intel", "BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-06-09T16:44:58.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-09T16:44:58.000Z", "max_issues_repo_path": "src/caffe/layers/molgrid_data_layer.cpp", "max_issues_repo_name": "gnina/caffe", "max_issues_repo_head_hexsha": "59b3451cd54ae106de3335876ba25f68b9553098", "max_issues_repo_licenses": ["Intel", "BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/layers/molgrid_data_layer.cpp", "max_forks_repo_name": "gnina/caffe", "max_forks_repo_head_hexsha": "59b3451cd54ae106de3335876ba25f68b9553098", "max_forks_repo_licenses": ["Intel", "BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-10T17:38:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-14T07:44:19.000Z", "avg_line_length": 29.8842386465, "max_line_length": 153, "alphanum_fraction": 0.6666269368, "num_tokens": 9257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.022629199291503053, "lm_q1q2_score": 0.00829563220145371}}
{"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 \"rttbDoseStatisticsCalculator.h\"\r\n\r\n#include <boost/shared_ptr.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/assign/list_of.hpp>\r\n\r\n#include \"rttbNullPointerException.h\"\r\n#include \"rttbInvalidDoseException.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n\r\nnamespace rttb\r\n{\r\n\r\n\tnamespace algorithms\r\n\t{\r\n\r\n\t\tDoseStatisticsCalculator::DoseStatisticsCalculator(DoseIteratorPointer aDoseIterator)\r\n\t\t{\r\n\t\t\tif (aDoseIterator == nullptr)\r\n\t\t\t{\r\n\t\t\t\tthrow core::NullPointerException(\"DoseIterator must not be nullptr\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t_doseIterator = aDoseIterator;\r\n\t\t\t}\r\n\r\n\t\t\t_simpleDoseStatisticsCalculated = false;\r\n\t\t\t_complexDoseStatisticsCalculated = false;\r\n\r\n\t\t\t_multiThreading = false;\r\n\t\t\t_mutex = ::boost::make_shared<std::mutex>();\r\n\t\t}\r\n\r\n\r\n\t\tDoseStatisticsCalculator::~DoseStatisticsCalculator()\r\n\t\t= default;\r\n\r\n\t\tDoseStatisticsCalculator::DoseIteratorPointer DoseStatisticsCalculator::getDoseIterator() const\r\n\t\t{\r\n\t\t\treturn _doseIterator;\r\n\t\t}\r\n\r\n\r\n\t\tDoseStatisticsCalculator::DoseStatisticsPointer DoseStatisticsCalculator::calculateDoseStatistics(\r\n\t\t\tbool computeComplexMeasures, unsigned int maxNumberMinimaPositions,\r\n\t\t\tunsigned int maxNumberMaximaPositions)\r\n\t\t{\r\n\t\t\tif (_doseIterator == nullptr)\r\n\t\t\t{\r\n\t\t\t\tthrow core::NullPointerException(\"_doseIterator must not be nullptr!\");\r\n\t\t\t}\r\n\r\n\t\t\t//\"simple\" dose statistics are mandatory\r\n\t\t\tcalculateSimpleDoseStatistics(maxNumberMinimaPositions, maxNumberMaximaPositions);\r\n\r\n\t\t\tif (computeComplexMeasures)\r\n\t\t\t{\r\n\t\t\t\t//more complex dose statistics are optional with default maximum dose and default relative x values\r\n\t\t\t\tcalculateComplexDoseStatistics(_statistics->getMaximum(), std::vector<double>(),\r\n\t\t\t\t\tstd::vector<double>());\r\n\t\t\t}\r\n\t\t\treturn _statistics;\r\n\t\t}\r\n\r\n\r\n\t\tDoseStatisticsCalculator::DoseStatisticsPointer DoseStatisticsCalculator::calculateDoseStatistics(\r\n\t\t\tDoseTypeGy referenceDose, unsigned int maxNumberMinimaPositions,\r\n\t\t\tunsigned int maxNumberMaximaPositions)\r\n\t\t{\r\n\t\t\tif (_doseIterator == nullptr)\r\n\t\t\t{\r\n\t\t\t\tthrow core::NullPointerException(\"_doseIterator must not be nullptr!\");\r\n\t\t\t}\r\n\r\n\t\t\tif (referenceDose <= 0)\r\n\t\t\t{\r\n\t\t\t\tthrow rttb::core::InvalidParameterException(\"Reference dose must be > 0 !\");\r\n\t\t\t}\r\n\r\n\t\t\t//simple dose statistics\r\n\t\t\tcalculateSimpleDoseStatistics(maxNumberMinimaPositions, maxNumberMaximaPositions);\r\n\r\n\r\n\t\t\t//more complex dose statistics with given reference dose and default x values\r\n\t\t\tcalculateComplexDoseStatistics(referenceDose, std::vector<double>(), std::vector<double>());\r\n\r\n\t\t\treturn _statistics;\r\n\t\t}\r\n\r\n\t\tDoseStatisticsCalculator::DoseStatisticsPointer DoseStatisticsCalculator::calculateDoseStatistics(\r\n\t\t\tconst std::vector<double>& precomputeDoseValues,\r\n\t\t\tconst std::vector<double>& precomputeVolumeValues, DoseTypeGy referenceDose,\r\n\t\t\tunsigned int maxNumberMinimaPositions,\r\n\t\t\tunsigned int maxNumberMaximaPositions)\r\n\t\t{\r\n\r\n\t\t\tif (_doseIterator == nullptr)\r\n\t\t\t{\r\n\t\t\t\tthrow core::NullPointerException(\"_doseIterator must not be nullptr!\");\r\n\t\t\t}\r\n\r\n\t\t\t//\"simple\" dose statistics\r\n\t\t\tcalculateSimpleDoseStatistics(maxNumberMinimaPositions, maxNumberMaximaPositions);\r\n\t\t\tif (referenceDose <= 0)\r\n\t\t\t{\r\n\t\t\t\t//more complex dose statistics with default maximum dose and relative x values\r\n\t\t\t\tcalculateComplexDoseStatistics(_statistics->getMaximum(), precomputeDoseValues,\r\n\t\t\t\t\tprecomputeVolumeValues);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t//more complex dose statistics with given reference dose and relative x values\r\n\t\t\t\tcalculateComplexDoseStatistics(referenceDose, precomputeDoseValues, precomputeVolumeValues);\r\n\t\t\t}\r\n\r\n\t\t\treturn _statistics;\r\n\r\n\t\t}\r\n\r\n\t\tvoid DoseStatisticsCalculator::calculateSimpleDoseStatistics(unsigned int maxNumberMinimaPositions,\r\n\t\t\tunsigned int maxNumberMaximaPositions)\r\n\t\t{\r\n\t\t\t_doseVector.clear();\r\n\t\t\t_voxelProportionVector.clear();\r\n\r\n\t\t\tstd::multimap<double, int> doseValueVSIndexMap;\r\n\t\t\tstd::vector<double> voxelProportionVectorTemp;\r\n\r\n\r\n\t\t\tDoseStatisticType maximumDose = 0;\r\n\t\t\tDoseStatisticType minimumDose = std::numeric_limits<DoseStatisticType>::max();\r\n\t\t\tDoseStatisticType meanDose;\r\n\t\t\tDoseStatisticType stdDeviationDose;\r\n\r\n\r\n\t\t\tDoseTypeGy sum = 0;\r\n\t\t\tVolumeType numVoxels = 0.0;\r\n\t\t\tDoseTypeGy squareSum = 0;\r\n\t\t\tVolumeType volume = 0;\r\n\r\n\t\t\t_doseIterator->reset();\r\n\t\t\tint i = 0;\r\n\t\t\tDoseTypeGy doseValue = 0;\r\n\r\n\t\t\twhile (_doseIterator->isPositionValid())\r\n\t\t\t{\r\n\t\t\t\tdoseValue = _doseIterator->getCurrentDoseValue();\r\n\r\n\t\t\t\tif (i == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tminimumDose = doseValue;\r\n\t\t\t\t\tvolume = _doseIterator->getCurrentVoxelVolume();\r\n\t\t\t\t}\r\n\r\n\t\t\t\trttb::FractionType voxelProportion = _doseIterator->getCurrentRelevantVolumeFraction();\r\n\t\t\t\tsum += doseValue * voxelProportion;\r\n\r\n\t\t\t\tnumVoxels += voxelProportion;\r\n\t\t\t\tsquareSum += doseValue * doseValue * voxelProportion;\r\n\r\n\t\t\t\tif (doseValue > maximumDose)\r\n\t\t\t\t{\r\n\t\t\t\t\tmaximumDose = doseValue;\r\n\t\t\t\t}\r\n\t\t\t\telse if (doseValue < minimumDose)\r\n\t\t\t\t{\r\n\t\t\t\t\tminimumDose = doseValue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvoxelProportionVectorTemp.push_back(voxelProportion);\r\n\t\t\t\tdoseValueVSIndexMap.insert(std::pair<double, int>(doseValue, i));\r\n\r\n\t\t\t\ti++;\r\n\t\t\t\t_doseIterator->next();\r\n\t\t\t}\r\n\r\n\t\t\tif (numVoxels != 0)\r\n\t\t\t{\r\n\t\t\t\tmeanDose = sum / numVoxels;\r\n\r\n\t\t\t\t//standard deviation is defined only for n>=2\r\n\t\t\t\tif (numVoxels >= 2)\r\n\t\t\t\t{\r\n\t\t\t\t\t//uncorrected variance is calculated\r\n\t\t\t\t\tDoseStatisticType varianceDose = (squareSum / numVoxels - meanDose * meanDose);\r\n\r\n\t\t\t\t\tif (varianceDose < errorConstant)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstdDeviationDose = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstdDeviationDose = pow(varianceDose, 0.5);\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\t\tstdDeviationDose = 0;\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\r\n\t\t\t//sort dose values and corresponding volume fractions in member variables\r\n\t\t\tfor (auto & it : doseValueVSIndexMap)\r\n\t\t\t{\r\n\t\t\t\t_doseVector.push_back((float)it.first);\r\n\t\t\t\t_voxelProportionVector.push_back(voxelProportionVectorTemp.at(it.second));\r\n\t\t\t}\r\n\r\n\t\t\tvolume *= numVoxels;\r\n\r\n\t\t\t_statistics = boost::make_shared<DoseStatistics>(minimumDose, maximumDose, meanDose,\r\n\t\t\t\tstdDeviationDose, numVoxels,\r\n\t\t\t\tvolume);\r\n\r\n\t\t\t_simpleDoseStatisticsCalculated = true;\r\n\r\n\t\t\tResultListPointer minimumVoxelPositions = computeMinimumPositions(maxNumberMinimaPositions);\r\n\t\t\tResultListPointer maximumVoxelPositions = computeMaximumPositions(maxNumberMaximaPositions);\r\n\r\n\t\t\t_statistics->setMinimumVoxelPositions(minimumVoxelPositions);\r\n\t\t\t_statistics->setMaximumVoxelPositions(maximumVoxelPositions);\r\n\t\t}\r\n\r\n\r\n\t\tvoid DoseStatisticsCalculator::calculateComplexDoseStatistics(DoseTypeGy referenceDose,\r\n\t\t\tconst std::vector<double>& precomputeDoseValues,\r\n\t\t\tconst std::vector<double>& precomputeVolumeValues)\r\n\t\t{\r\n\t\t\tif (!_simpleDoseStatisticsCalculated)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidDoseException(\"simple DoseStatistics have to be computed in order to call calculateComplexDoseStatistics()\");\r\n\t\t\t}\r\n\r\n\t\t\tstd::vector<double> precomputeDoseValuesNonConst = precomputeDoseValues;\r\n\t\t\tstd::vector<double> precomputeVolumeValuesNonConst = precomputeVolumeValues;\r\n\r\n\t\t\t//set default values\r\n\t\t\tif (precomputeDoseValues.empty())\r\n\t\t\t{\r\n\t\t\t\tstd::vector<double> defaultPrecomputeDoseValues = boost::assign::list_of(0.02)(0.05)(0.1)(0.9)(\r\n\t\t\t\t\t0.95)(0.98);\r\n\t\t\t\tprecomputeDoseValuesNonConst = defaultPrecomputeDoseValues;\r\n\t\t\t}\r\n\r\n\t\t\tif (precomputeVolumeValues.empty())\r\n\t\t\t{\r\n\t\t\t\tstd::vector<double> defaultPrecomputeVolumeValues = boost::assign::list_of(0.02)(0.05)(0.1)(0.9)(\r\n\t\t\t\t\t0.95)(0.98);\r\n\t\t\t\tprecomputeVolumeValuesNonConst = defaultPrecomputeVolumeValues;\r\n\t\t\t}\r\n\r\n\t\t\t_Vx = ::boost::make_shared<VxDoseToVolumeMeasureCollectionCalculator>(precomputeDoseValuesNonConst, referenceDose, _doseIterator);\r\n\t\t\t_Vx->compute();\r\n\r\n\t\t\t_Dx = ::boost::make_shared<DxVolumeToDoseMeasureCollectionCalculator>(precomputeVolumeValuesNonConst, _statistics->getVolume(),\r\n\t\t\t\tthis->_doseVector, this->_voxelProportionVector, this->_doseIterator->getCurrentVoxelVolume(), _statistics->getMinimum());\r\n\t\t\t_Dx->compute();\r\n\r\n\t\t\t_MOHx = ::boost::make_shared<MOHxVolumeToDoseMeasureCollectionCalculator>(precomputeVolumeValuesNonConst, _statistics->getVolume(),\r\n\t\t\t\tthis->_doseVector, this->_voxelProportionVector, this->_doseIterator->getCurrentVoxelVolume());\r\n\t\t\t_MOHx->compute();\r\n\r\n\t\t\t_MOCx = ::boost::make_shared<MOCxVolumeToDoseMeasureCollectionCalculator>(precomputeVolumeValuesNonConst, _statistics->getVolume(),\r\n\t\t\t\tthis->_doseVector, this->_voxelProportionVector, this->_doseIterator->getCurrentVoxelVolume());\r\n\t\t\t_MOCx->compute();\r\n\r\n\t\t\t_MaxOHx = ::boost::make_shared<MaxOHxVolumeToDoseMeasureCollectionCalculator>(precomputeVolumeValuesNonConst, _statistics->getVolume(),\r\n\t\t\t\tthis->_doseVector, this->_voxelProportionVector, this->_doseIterator->getCurrentVoxelVolume());\r\n\t\t\t_MaxOHx->compute();\r\n\r\n\t\t\t_MinOCx = ::boost::make_shared<MinOCxVolumeToDoseMeasureCollectionCalculator>(precomputeVolumeValuesNonConst, _statistics->getVolume(),\r\n\t\t\t\tthis->_doseVector, this->_voxelProportionVector, this->_doseIterator->getCurrentVoxelVolume(), _statistics->getMinimum(), _statistics->getMaximum());\r\n\t\t\t_MinOCx->compute();\r\n\r\n\t\t\t_statistics->setVx(_Vx->getMeasureCollection());\r\n\t\t\t_statistics->setDx(_Dx->getMeasureCollection());\r\n\t\t\t_statistics->setMOHx(_MOHx->getMeasureCollection());\r\n\t\t\t_statistics->setMOCx(_MOCx->getMeasureCollection());\r\n\t\t\t_statistics->setMaxOHx(_MaxOHx->getMeasureCollection());\r\n\t\t\t_statistics->setMinOCx(_MinOCx->getMeasureCollection());\r\n\t\t\t_statistics->setReferenceDose(referenceDose);\r\n\t\t\t_complexDoseStatisticsCalculated = true;\r\n\t\t}\r\n\r\n\t\tvoid DoseStatisticsCalculator::addPrecomputeValues(const std::vector<double>& values)\r\n\t\t{\r\n\t\t\tif (!_complexDoseStatisticsCalculated)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidDoseException(\"Complex DoseStatistics have to be computed in order to call addPrecomputeDoseValues()\");\r\n\t\t\t}\r\n\t\t\t_Vx->addPrecomputeDoseValues(values);\r\n\t\t\t_Dx->addPrecomputeVolumeValues(values);\r\n\t\t\t_MOHx->addPrecomputeVolumeValues(values);\r\n\t\t\t_MOCx->addPrecomputeVolumeValues(values);\r\n\t\t\t_MaxOHx->addPrecomputeVolumeValues(values);\r\n\t\t\t_MinOCx->addPrecomputeVolumeValues(values);\r\n\t\t}\r\n\t\tvoid DoseStatisticsCalculator::recalculateDoseStatistics()\r\n\t\t{\r\n\t\t\tif (!_complexDoseStatisticsCalculated)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidDoseException(\"Complex DoseStatistics have to be computed in order to call recalculateDoseStatistics()\");\r\n\t\t\t}\r\n\t\t\t_Vx->compute();\t\t\t\r\n\t\t\t_Dx->compute();\r\n\t\t\t_MOHx->compute();\r\n\t\t\t_MOCx->compute();\r\n\t\t\t_MaxOHx->compute();\r\n\t\t\t_MinOCx->compute();\r\n\t\t}\r\n\r\n\t\tDoseStatisticsCalculator::ResultListPointer DoseStatisticsCalculator::computeMaximumPositions(\r\n\t\t\tunsigned int maxNumberMaxima) const\r\n\t\t{\r\n\t\t\tif (!_simpleDoseStatisticsCalculated)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidDoseException(\"simple DoseStatistics have to be computed in order to call computeMaximumPositions()\");\r\n\t\t\t}\r\n\r\n\t\t\tResultListPointer maxVoxelVector =\r\n\t\t\t\tboost::make_shared<std::vector<std::pair<DoseTypeGy, VoxelGridID> > >();\r\n\r\n\t\t\tunsigned int count = 0;\r\n\t\t\tthis->_doseIterator->reset();\r\n\t\t\tDoseTypeGy doseValue = 0;\r\n\r\n\t\t\twhile (_doseIterator->isPositionValid() && count < maxNumberMaxima)\r\n\t\t\t{\r\n\t\t\t\tdoseValue = _doseIterator->getCurrentDoseValue();\r\n\r\n\t\t\t\tif (doseValue == _statistics->getMaximum())\r\n\t\t\t\t{\r\n\t\t\t\t\tVoxelGridID currentID = _doseIterator->getCurrentVoxelGridID();\r\n\t\t\t\t\tstd::pair<DoseTypeGy, VoxelGridID> voxel(doseValue, currentID);\r\n\t\t\t\t\tmaxVoxelVector->push_back(voxel);\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t_doseIterator->next();\r\n\t\t\t}\r\n\r\n\t\t\treturn maxVoxelVector;\r\n\t\t}\r\n\r\n\t\tDoseStatisticsCalculator::ResultListPointer DoseStatisticsCalculator::computeMinimumPositions(\r\n\t\t\tunsigned int maxNumberMinima) const\r\n\t\t{\r\n\t\t\tif (!_simpleDoseStatisticsCalculated)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidDoseException(\"simple DoseStatistics have to be computed in order to call computeMinimumPositions()\");\r\n\r\n\t\t\t}\r\n\r\n\t\t\tResultListPointer minVoxelVector =\r\n\t\t\t\tboost::make_shared<std::vector<std::pair<DoseTypeGy, VoxelGridID> > >();\r\n\r\n\t\t\t/*! @todo: Architecture Annotation:\r\n\t\t\t\tFinding the positions for the minimum only once reduces computation time,\r\n\t\t\t\tbut will require sensible use by the programmers. To be save the output vector\r\n\t\t\t\tminVoxelVector will be always cleared here to garantee that no false values are\r\n\t\t\t\tpresented. This change may be revoced to increase computation speed later on\r\n\t\t\t\t(only compute if(minVoxelVector->size()==0)).\r\n\t\t\t\t*/\r\n\t\t\tunsigned int count = 0;\r\n\t\t\tthis->_doseIterator->reset();\r\n\t\t\tDoseTypeGy doseValue = 0;\r\n\r\n\t\t\twhile (_doseIterator->isPositionValid() && count < maxNumberMinima)\r\n\t\t\t{\r\n\t\t\t\tdoseValue = _doseIterator->getCurrentDoseValue();\r\n\r\n\t\t\t\tif (doseValue == _statistics->getMinimum())\r\n\t\t\t\t{\r\n\t\t\t\t\tVoxelGridID currentID = _doseIterator->getCurrentVoxelGridID();\r\n\t\t\t\t\tstd::pair<DoseTypeGy, VoxelGridID> voxel(doseValue, currentID);\r\n\t\t\t\t\tminVoxelVector->push_back(voxel);\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t_doseIterator->next();\r\n\t\t\t}\r\n\r\n\t\t\treturn minVoxelVector;\r\n\t\t}\r\n\r\n\t\tvoid DoseStatisticsCalculator::setMultiThreading(const bool choice) \r\n\t\t{\r\n\t\t\t_multiThreading = choice;\r\n\t\t}\r\n\r\n\t}//end namespace algorithms\r\n}//end namespace rttb\r\n\r\n", "meta": {"hexsha": "5b423443a48e771de38e9fe89cbaccdb142328cf", "size": 13743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/algorithms/rttbDoseStatisticsCalculator.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/algorithms/rttbDoseStatisticsCalculator.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/algorithms/rttbDoseStatisticsCalculator.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": 33.4379562044, "max_line_length": 154, "alphanum_fraction": 0.7163646948, "num_tokens": 3514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010666408646392, "lm_q2_score": 0.046033904362384165, "lm_q1q2_score": 0.00829101294958433}}
{"text": "// Copyright (C) 2001 Jeremy Siek, Douglas Gregor, Brian Osman\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#ifndef BOOST_GRAPH_ISOMORPHISM_HPP\n#define BOOST_GRAPH_ISOMORPHISM_HPP\n\n#include <utility>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n#include <boost/config.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/utility.hpp>\n#include <boost/detail/algorithm.hpp>\n#include <boost/pending/indirect_cmp.hpp> // for make_indirect_pmap\n\n#ifndef BOOST_GRAPH_ITERATION_MACROS_HPP\n#define BOOST_ISO_INCLUDED_ITER_MACROS // local macro, see bottom of file\n#include <boost/graph/iteration_macros.hpp>\n#endif\n\nnamespace boost {\n\n  namespace detail {\n\n    template <typename Graph1, typename Graph2, typename IsoMapping,\n      typename Invariant1, typename Invariant2,\n      typename IndexMap1, typename IndexMap2>\n    class isomorphism_algo\n    {\n      typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;\n      typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;\n      typedef typename graph_traits<Graph1>::edge_descriptor edge1_t;\n      typedef typename graph_traits<Graph1>::vertices_size_type size_type;\n      typedef typename Invariant1::result_type invar1_value;\n      typedef typename Invariant2::result_type invar2_value;\n    \n      const Graph1& G1;\n      const Graph2& G2;\n      IsoMapping f;\n      Invariant1 invariant1;\n      Invariant2 invariant2;\n      std::size_t max_invariant;\n      IndexMap1 index_map1;\n      IndexMap2 index_map2;\n    \n      std::vector<vertex1_t> dfs_vertices;\n      typedef typename std::vector<vertex1_t>::iterator vertex_iter;\n      std::vector<int> dfs_num_vec;\n      typedef safe_iterator_property_map<typename std::vector<int>::iterator,\n                                         IndexMap1\n#ifdef BOOST_NO_STD_ITERATOR_TRAITS\n                                         , int, int&\n#endif /* BOOST_NO_STD_ITERATOR_TRAITS */\n                                         > DFSNumMap;\n      DFSNumMap dfs_num;\n      std::vector<edge1_t> ordered_edges;\n      typedef typename std::vector<edge1_t>::iterator edge_iter;\n    \n      std::vector<char> in_S_vec;\n      typedef safe_iterator_property_map<typename std::vector<char>::iterator,\n                                         IndexMap2\n#ifdef BOOST_NO_STD_ITERATOR_TRAITS\n                                         , char, char&\n#endif /* BOOST_NO_STD_ITERATOR_TRAITS */\n                                         > InSMap;\n      InSMap in_S;\n    \n      int num_edges_on_k;\n    \n      friend struct compare_multiplicity;\n      struct compare_multiplicity\n      {\n        compare_multiplicity(Invariant1 invariant1, size_type* multiplicity)\n          : invariant1(invariant1), multiplicity(multiplicity) { }\n        bool operator()(const vertex1_t& x, const vertex1_t& y) const {\n          return multiplicity[invariant1(x)] < multiplicity[invariant1(y)];\n        }\n        Invariant1 invariant1;\n        size_type* multiplicity;\n      };\n    \n      struct record_dfs_order : default_dfs_visitor\n      {\n        record_dfs_order(std::vector<vertex1_t>& v, std::vector<edge1_t>& e) \n          : vertices(v), edges(e) { }\n    \n        void discover_vertex(vertex1_t v, const Graph1&) const {\n          vertices.push_back(v);\n        }\n        void examine_edge(edge1_t e, const Graph1& G1) const {\n          edges.push_back(e);\n        }\n        std::vector<vertex1_t>& vertices;\n        std::vector<edge1_t>& edges;\n      };\n    \n      struct edge_cmp {\n        edge_cmp(const Graph1& G1, DFSNumMap dfs_num)\n          : G1(G1), dfs_num(dfs_num) { }\n        bool operator()(const edge1_t& e1, const edge1_t& e2) const {\n          using namespace std;\n          int u1 = dfs_num[source(e1,G1)], v1 = dfs_num[target(e1,G1)];\n          int u2 = dfs_num[source(e2,G1)], v2 = dfs_num[target(e2,G1)];\n          int m1 = (max)(u1, v1);\n          int m2 = (max)(u2, v2);\n          // lexicographical comparison \n          return std::make_pair(m1, std::make_pair(u1, v1))\n            < std::make_pair(m2, std::make_pair(u2, v2));\n        }\n        const Graph1& G1;\n        DFSNumMap dfs_num;\n      };\n    \n    public:\n      isomorphism_algo(const Graph1& G1, const Graph2& G2, IsoMapping f,\n                       Invariant1 invariant1, Invariant2 invariant2, std::size_t max_invariant,\n                       IndexMap1 index_map1, IndexMap2 index_map2)\n        : G1(G1), G2(G2), f(f), invariant1(invariant1), invariant2(invariant2),\n          max_invariant(max_invariant),\n          index_map1(index_map1), index_map2(index_map2)\n      {\n        in_S_vec.resize(num_vertices(G1));\n        in_S = make_safe_iterator_property_map\n          (in_S_vec.begin(), in_S_vec.size(), index_map2\n#ifdef BOOST_NO_STD_ITERATOR_TRAITS\n           , in_S_vec.front()\n#endif /* BOOST_NO_STD_ITERATOR_TRAITS */\n           );\n      }\n    \n      bool test_isomorphism()\n      {\n        {\n          std::vector<invar1_value> invar1_array;\n          BGL_FORALL_VERTICES_T(v, G1, Graph1)\n            invar1_array.push_back(invariant1(v));\n          sort(invar1_array);\n        \n          std::vector<invar2_value> invar2_array;\n          BGL_FORALL_VERTICES_T(v, G2, Graph2)\n            invar2_array.push_back(invariant2(v));\n          sort(invar2_array);\n          if (! equal(invar1_array, invar2_array))\n            return false;\n        }\n        \n        std::vector<vertex1_t> V_mult;\n        BGL_FORALL_VERTICES_T(v, G1, Graph1)\n          V_mult.push_back(v);\n        {\n          std::vector<size_type> multiplicity(max_invariant, 0);\n          BGL_FORALL_VERTICES_T(v, G1, Graph1)\n            ++multiplicity[invariant1(v)];\n          sort(V_mult, compare_multiplicity(invariant1, &multiplicity[0]));\n        }\n        \n        std::vector<default_color_type> color_vec(num_vertices(G1));\n        safe_iterator_property_map<std::vector<default_color_type>::iterator,\n                                   IndexMap1\n#ifdef BOOST_NO_STD_ITERATOR_TRAITS\n                                   , default_color_type, default_color_type&\n#endif /* BOOST_NO_STD_ITERATOR_TRAITS */\n                                   >\n          color_map(color_vec.begin(), color_vec.size(), index_map1);\n        record_dfs_order dfs_visitor(dfs_vertices, ordered_edges);\n        typedef color_traits<default_color_type> Color;\n        for (vertex_iter u = V_mult.begin(); u != V_mult.end(); ++u) {\n          if (color_map[*u] == Color::white()) {\n            dfs_visitor.start_vertex(*u, G1);\n            depth_first_visit(G1, *u, dfs_visitor, color_map);\n          }\n        }\n        // Create the dfs_num array and dfs_num_map\n        dfs_num_vec.resize(num_vertices(G1));\n        dfs_num = make_safe_iterator_property_map(dfs_num_vec.begin(),\n                                                  dfs_num_vec.size(), \n                                                  index_map1\n#ifdef BOOST_NO_STD_ITERATOR_TRAITS\n                                                  , dfs_num_vec.front()\n#endif /* BOOST_NO_STD_ITERATOR_TRAITS */\n                                                  );\n        size_type n = 0;\n        for (vertex_iter v = dfs_vertices.begin(); v != dfs_vertices.end(); ++v)\n          dfs_num[*v] = n++;\n        \n        sort(ordered_edges, edge_cmp(G1, dfs_num));\n        \n    \n        int dfs_num_k = -1;\n        return this->match(ordered_edges.begin(), dfs_num_k);\n      }\n    \n    private:\n      bool match(edge_iter iter, int dfs_num_k)\n      {\n        if (iter != ordered_edges.end()) {\n          vertex1_t i = source(*iter, G1), j = target(*iter, G2);\n          if (dfs_num[i] > dfs_num_k) {\n            vertex1_t kp1 = dfs_vertices[dfs_num_k + 1];\n            BGL_FORALL_VERTICES_T(u, G2, Graph2) {\n              if (invariant1(kp1) == invariant2(u) && in_S[u] == false) {\n                f[kp1] = u;\n                in_S[u] = true;\n                num_edges_on_k = 0;\n                \n                if (match(iter, dfs_num_k + 1))\n#if 0\n                    // dwa 2003/7/11 -- this *HAS* to be a bug!\n                    ;\n#endif \n                    return true;\n                    \n                in_S[u] = false;\n              }\n            }\n               \n          }\n          else if (dfs_num[j] > dfs_num_k) {\n            vertex1_t k = dfs_vertices[dfs_num_k];\n            num_edges_on_k -= \n              count_if(adjacent_vertices(f[k], G2), make_indirect_pmap(in_S));\n                \n            for (int jj = 0; jj < dfs_num_k; ++jj) {\n              vertex1_t j = dfs_vertices[jj];\n              num_edges_on_k -= count(adjacent_vertices(f[j], G2), f[k]);\n            }\n                \n            if (num_edges_on_k != 0)\n              return false;\n            BGL_FORALL_ADJ_T(f[i], v, G2, Graph2)\n              if (invariant2(v) == invariant1(j) && in_S[v] == false) {\n                f[j] = v;\n                in_S[v] = true;\n                num_edges_on_k = 1;\n                BOOST_USING_STD_MAX();\n                int next_k = max BOOST_PREVENT_MACRO_SUBSTITUTION(dfs_num_k, max BOOST_PREVENT_MACRO_SUBSTITUTION(dfs_num[i], dfs_num[j]));\n                if (match(boost::next(iter), next_k))\n                  return true;\n                in_S[v] = false;\n              }\n                \n                \n          }\n          else {\n            if (container_contains(adjacent_vertices(f[i], G2), f[j])) {\n              ++num_edges_on_k;\n              if (match(boost::next(iter), dfs_num_k))\n                return true;\n            }\n                \n          }\n        } else \n          return true;\n        return false;\n      }\n    \n    };\n\n    \n    template <typename Graph, typename InDegreeMap>\n    void compute_in_degree(const Graph& g, InDegreeMap in_degree_map)\n    {\n      BGL_FORALL_VERTICES_T(v, g, Graph)\n        put(in_degree_map, v, 0);\n\n      BGL_FORALL_VERTICES_T(u, g, Graph)\n        BGL_FORALL_ADJ_T(u, v, g, Graph)\n        put(in_degree_map, v, get(in_degree_map, v) + 1);\n    }\n\n  } // namespace detail\n\n\n  template <typename InDegreeMap, typename Graph>\n  class degree_vertex_invariant\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::degree_size_type size_type;\n  public:\n    typedef vertex_t argument_type;\n    typedef size_type result_type;\n\n    degree_vertex_invariant(const InDegreeMap& in_degree_map, const Graph& g)\n      : m_in_degree_map(in_degree_map), m_g(g) { }\n\n    size_type operator()(vertex_t v) const {\n      return (num_vertices(m_g) + 1) * out_degree(v, m_g)\n        + get(m_in_degree_map, v);\n    }\n    // The largest possible vertex invariant number\n    size_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { \n      return num_vertices(m_g) * num_vertices(m_g) + num_vertices(m_g);\n    }\n  private:\n    InDegreeMap m_in_degree_map;\n    const Graph& m_g;\n  };\n\n\n  template <typename Graph1, typename Graph2, typename IsoMapping, \n    typename Invariant1, typename Invariant2,\n    typename IndexMap1, typename IndexMap2>\n  bool isomorphism(const Graph1& G1, const Graph2& G2, IsoMapping f, \n                   Invariant1 invariant1, Invariant2 invariant2, \n                   std::size_t max_invariant,\n                   IndexMap1 index_map1, IndexMap2 index_map2)\n\n  {\n    // Graph requirements\n    function_requires< VertexListGraphConcept<Graph1> >();\n    function_requires< EdgeListGraphConcept<Graph1> >();\n    function_requires< VertexListGraphConcept<Graph2> >();\n    function_requires< BidirectionalGraphConcept<Graph2> >();\n    \n    typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;\n    typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;\n    typedef typename graph_traits<Graph1>::vertices_size_type size_type;\n    \n    // Vertex invariant requirement\n    function_requires< AdaptableUnaryFunctionConcept<Invariant1,\n      size_type, vertex1_t> >();\n    function_requires< AdaptableUnaryFunctionConcept<Invariant2,\n      size_type, vertex2_t> >();\n    \n    // Property map requirements\n    function_requires< ReadWritePropertyMapConcept<IsoMapping, vertex1_t> >();\n    typedef typename property_traits<IsoMapping>::value_type IsoMappingValue;\n    BOOST_STATIC_ASSERT((is_same<IsoMappingValue, vertex2_t>::value));\n    \n    function_requires< ReadablePropertyMapConcept<IndexMap1, vertex1_t> >();\n    typedef typename property_traits<IndexMap1>::value_type IndexMap1Value;\n    BOOST_STATIC_ASSERT((is_convertible<IndexMap1Value, size_type>::value));\n    \n    function_requires< ReadablePropertyMapConcept<IndexMap2, vertex2_t> >();\n    typedef typename property_traits<IndexMap2>::value_type IndexMap2Value;\n    BOOST_STATIC_ASSERT((is_convertible<IndexMap2Value, size_type>::value));\n    \n    if (num_vertices(G1) != num_vertices(G2))\n      return false;\n    if (num_vertices(G1) == 0 && num_vertices(G2) == 0)\n      return true;\n    \n    detail::isomorphism_algo<Graph1, Graph2, IsoMapping, Invariant1,\n      Invariant2, IndexMap1, IndexMap2> \n      algo(G1, G2, f, invariant1, invariant2, max_invariant, \n           index_map1, index_map2);\n    return algo.test_isomorphism();\n  }\n\n\n  namespace detail {\n  \n    template <typename Graph1, typename Graph2, \n      typename IsoMapping, \n      typename IndexMap1, typename IndexMap2,\n      typename P, typename T, typename R>\n    bool isomorphism_impl(const Graph1& G1, const Graph2& G2, \n                          IsoMapping f, IndexMap1 index_map1, IndexMap2 index_map2,\n                          const bgl_named_params<P,T,R>& params)\n    {\n      std::vector<std::size_t> in_degree1_vec(num_vertices(G1));\n      typedef safe_iterator_property_map<std::vector<std::size_t>::iterator,\n                                         IndexMap1\n#ifdef BOOST_NO_STD_ITERATOR_TRAITS\n                                         , std::size_t, std::size_t&\n#endif /* BOOST_NO_STD_ITERATOR_TRAITS */\n                                         > InDeg1;\n      InDeg1 in_degree1(in_degree1_vec.begin(), in_degree1_vec.size(), index_map1);\n      compute_in_degree(G1, in_degree1);\n\n      std::vector<std::size_t> in_degree2_vec(num_vertices(G2));\n      typedef safe_iterator_property_map<std::vector<std::size_t>::iterator, \n                                         IndexMap2\n#ifdef BOOST_NO_STD_ITERATOR_TRAITS\n                                         , std::size_t, std::size_t&\n#endif /* BOOST_NO_STD_ITERATOR_TRAITS */\n                                         > InDeg2;\n      InDeg2 in_degree2(in_degree2_vec.begin(), in_degree2_vec.size(), index_map2);\n      compute_in_degree(G2, in_degree2);\n\n      degree_vertex_invariant<InDeg1, Graph1> invariant1(in_degree1, G1);\n      degree_vertex_invariant<InDeg2, Graph2> invariant2(in_degree2, G2);\n\n      return isomorphism(G1, G2, f,\n                         choose_param(get_param(params, vertex_invariant1_t()), invariant1),\n                         choose_param(get_param(params, vertex_invariant2_t()), invariant2),\n                         choose_param(get_param(params, vertex_max_invariant_t()), (invariant2.max)()),\n                         index_map1, index_map2\n                         );  \n    }  \n   \n  } // namespace detail\n\n\n  // Named parameter interface\n  template <typename Graph1, typename Graph2, class P, class T, class R>\n  bool isomorphism(const Graph1& g1,\n                   const Graph2& g2,\n                   const bgl_named_params<P,T,R>& params)\n  {\n    typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;\n    typename std::vector<vertex2_t>::size_type n = num_vertices(g1);\n    std::vector<vertex2_t> f(n);\n    return detail::isomorphism_impl\n      (g1, g2, \n       choose_param(get_param(params, vertex_isomorphism_t()),\n                    make_safe_iterator_property_map(f.begin(), f.size(),\n                                                    choose_const_pmap(get_param(params, vertex_index1),\n                                                                      g1, vertex_index), vertex2_t())),\n       choose_const_pmap(get_param(params, vertex_index1), g1, vertex_index),\n       choose_const_pmap(get_param(params, vertex_index2), g2, vertex_index),\n       params\n       );\n  }\n\n  // All defaults interface\n  template <typename Graph1, typename Graph2>\n  bool isomorphism(const Graph1& g1, const Graph2& g2)\n  {\n    return isomorphism(g1, g2,\n                       bgl_named_params<int, buffer_param_t>(0));// bogus named param\n  }\n\n\n  // Verify that the given mapping iso_map from the vertices of g1 to the\n  // vertices of g2 describes an isomorphism.\n  // Note: this could be made much faster by specializing based on the graph\n  // concepts modeled, but since we're verifying an O(n^(lg n)) algorithm,\n  // O(n^4) won't hurt us.\n  template<typename Graph1, typename Graph2, typename IsoMap>\n  inline bool verify_isomorphism(const Graph1& g1, const Graph2& g2, IsoMap iso_map)\n  {\n#if 0\n    // problematic for filtered_graph!\n    if (num_vertices(g1) != num_vertices(g2) || num_edges(g1) != num_edges(g2))\n      return false;\n#endif\n  \n    BGL_FORALL_EDGES_T(e1, g1, Graph1) {\n      bool found_edge = false;\n      BGL_FORALL_EDGES_T(e2, g2, Graph2) {\n        if (source(e2, g2) == get(iso_map, source(e1, g1)) &&\n            target(e2, g2) == get(iso_map, target(e1, g1))) {\n          found_edge = true;\n        }\n      }\n    \n      if (!found_edge)\n        return false;\n    }\n  \n    return true;\n  }\n\n} // namespace boost\n\n#ifdef BOOST_ISO_INCLUDED_ITER_MACROS\n#undef BOOST_ISO_INCLUDED_ITER_MACROS\n#include <boost/graph/iteration_macros_undef.hpp>\n#endif\n\n#endif // BOOST_GRAPH_ISOMORPHISM_HPP\n", "meta": {"hexsha": "29f6ef2c58e72b859218ba0b71030a52fe507581", "size": 17641, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/boost/graph/isomorphism.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/isomorphism.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/isomorphism.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": 37.856223176, "max_line_length": 139, "alphanum_fraction": 0.6074485573, "num_tokens": 4241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.021948252155471467, "lm_q1q2_score": 0.008286357797727035}}
{"text": "#include \"gmsh_reader.h\"\n#include \"eigen_fusion_adapter.h\"\n\n#include <lf/geometry/geometry.h>\n#include <fstream>\n\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/adapt_struct_named.hpp>\n#include <boost/fusion/include/boost_array.hpp>\n#include <boost/fusion/include/io.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <boost/fusion/iterator.hpp>\n#include <boost/fusion/support/category_of.hpp>\n#include <boost/fusion/support/iterator_base.hpp>\n#include <boost/fusion/support/tag_of.hpp>\n#include <boost/fusion/support/tag_of_fwd.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/phoenix/function/adapt_function.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_object.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_stl.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/qi_binary.hpp>\n\nusing size_type = lf::mesh::Mesh::size_type;\n\n// Structures that represent the MshFile:\nnamespace lf::io {\n\n/// Output the element type onto the console:\nstd::ostream& operator<<(std::ostream& stream, MshFile::ElementType et) {\n  switch (et) {\n    default:\n      break;\n    case MshFile::ElementType::EDGE2:\n      stream << \"EDGE2\";\n      break;\n    case MshFile::ElementType::TRIA3:\n      stream << \"TRIA3\";\n      break;\n    case MshFile::ElementType::QUAD4:\n      stream << \"QUAD4\";\n      break;\n    case MshFile::ElementType::TET4:\n      stream << \"TET4\";\n      break;\n    case MshFile::ElementType::HEX8:\n      stream << \"HEX8\";\n      break;\n    case MshFile::ElementType::PRISM6:\n      stream << \"PRISM6\";\n      break;\n    case MshFile::ElementType::PYRAMID5:\n      stream << \"PYRAMID5\";\n      break;\n    case MshFile::ElementType::EDGE3:\n      stream << \"EDGE3\";\n      break;\n    case MshFile::ElementType::TRIA6:\n      stream << \"TRIA6\";\n      break;\n    case MshFile::ElementType::QUAD9:\n      stream << \"QUAD9\";\n      break;\n    case MshFile::ElementType::TET10:\n      stream << \"TET10\";\n      break;\n    case MshFile::ElementType::HEX27:\n      stream << \"HEX27\";\n      break;\n    case MshFile::ElementType::PRISM18:\n      stream << \"PRISM18\";\n      break;\n    case MshFile::ElementType::PYRAMID14:\n      stream << \"PYRAMID14\";\n      break;\n    case MshFile::ElementType::POINT:\n      stream << \"POINT\";\n      break;\n    case MshFile::ElementType::QUAD8:\n      stream << \"QUAD8\";\n      break;\n    case MshFile::ElementType::HEX20:\n      stream << \"HEX20\";\n      break;\n    case MshFile::ElementType::PRISM15:\n      stream << \"PRISM15\";\n      break;\n    case MshFile::ElementType::PYRAMID13:\n      stream << \"PYRAMID13\";\n      break;\n    case MshFile::ElementType::TRIA9:\n      stream << \"TRIA9\";\n      break;\n    case MshFile::ElementType::TRIA10:\n      stream << \"TRIA10\";\n      break;\n    case MshFile::ElementType::TRIA12:\n      stream << \"TRIA12\";\n      break;\n    case MshFile::ElementType::TRIA15:\n      stream << \"TRIA15\";\n      break;\n    case MshFile::ElementType::TRIA15_5:\n      stream << \"TRIA15_5\";\n      break;\n    case MshFile::ElementType::TRIA21:\n      stream << \"TRIA21\";\n      break;\n    case MshFile::ElementType::EDGE4:\n      stream << \"EDGE4\";\n      break;\n    case MshFile::ElementType::EDGE5:\n      stream << \"EDGE5\";\n      break;\n    case MshFile::ElementType::EDGE6:\n      stream << \"EDGE6\";\n      break;\n    case MshFile::ElementType::TET20:\n      stream << \"TET20\";\n      break;\n    case MshFile::ElementType::TET35:\n      stream << \"TET35\";\n      break;\n    case MshFile::ElementType::TET56:\n      stream << \"TET56\";\n      break;\n    case MshFile::ElementType::HEX64:\n      stream << \"HEX64\";\n      break;\n    case MshFile::ElementType::HEX125:\n      stream << \"HEX125\";\n      break;\n  }\n  return stream;\n}\n\n/// For debugging purposes: Write the MshFile into a stream\nstd::ostream& operator<<(std::ostream& stream, const MshFile& mf) {\n  stream << \"GMSH FILE: Ver. \" << mf.VersionNumber\n         << (mf.IsBinary ? \"(Binary)\" : \"(Text)\")\n         << \", size of double = \" << mf.DoubleSize << std::endl;\n  stream << \"=======================================================\"\n         << std::endl;\n  stream << \"PHYSICAL ENTITIES (Dimension, Number, Name):\" << std::endl;\n  for (auto pe : mf.PhysicalEntities) {\n    stream << \"  \" << pe.Dimension << \"\\t , \" << pe.Number << \"\\t , \" << pe.Name\n           << std::endl;\n  }\n  stream << \"NODES (Number, coords)\" << std::endl;\n  for (auto n : mf.Nodes) {\n    stream << \"  \" << n.first << \"\\t , \" << n.second.transpose() << std::endl;\n  }\n  stream << \"ELEMENTS (Number, Type, PhysicalEntity Nr, ElementaryEntityNr, \"\n            \"Mesh partitions to which it belongs, Node numbers in it)\"\n         << std::endl;\n  for (auto e : mf.Elements) {\n    stream << \"  \" << e.Number << \"\\t \" << e.Type << '\\t' << e.PhysicalEntityNr\n           << \"\\t\" << e.ElementaryEntityNr << \"\\t\";\n    for (auto p : e.MeshPartitions) {\n      stream << p << \", \";\n    }\n    stream << '\\t';\n    for (auto n : e.NodeNumbers) {\n      stream << n << \", \";\n    }\n    stream << std::endl;\n  }\n  stream << std::endl;\n  stream << \"PERIODIC ENTITIES:\" << std::endl;\n  for (auto pe : mf.Periodic) {\n    std::cout << \"  dim=\" << pe.Dimension\n              << \", slaveNr=\" << pe.ElementarySlaveNr\n              << \", masterNr=\" << pe.ElementaryMasterNr << std::endl;\n    for (auto nm : pe.NodeMapping) {\n      std::cout << \"    \" << nm.first << \" <-> \" << nm.second << std::endl;\n    }\n  }\n  return stream;\n}\n\n/// Number of nodes that this element type has\nsize_type NumNodes(MshFile::ElementType et) {\n  switch (et) {\n    default:\n      break;\n    case MshFile::ElementType::EDGE2:\n      return 2;\n    case MshFile::ElementType::TRIA3:\n      return 3;\n    case MshFile::ElementType::QUAD4:\n      return 4;\n    case MshFile::ElementType::TET4:\n      return 4;\n    case MshFile::ElementType::HEX8:\n      return 8;\n    case MshFile::ElementType::PRISM6:\n      return 6;\n    case MshFile::ElementType::PYRAMID5:\n      return 5;\n    case MshFile::ElementType::EDGE3:\n      return 3;\n    case MshFile::ElementType::TRIA6:\n      return 6;\n    case MshFile::ElementType::QUAD9:\n      return 9;\n    case MshFile::ElementType::TET10:\n      return 10;\n    case MshFile::ElementType::HEX27:\n      return 27;\n    case MshFile::ElementType::PRISM18:\n      return 18;\n    case MshFile::ElementType::PYRAMID14:\n      return 14;\n    case MshFile::ElementType::POINT:\n      return 1;\n    case MshFile::ElementType::QUAD8:\n      return 8;\n    case MshFile::ElementType::HEX20:\n      return 20;\n    case MshFile::ElementType::PRISM15:\n      return 15;\n    case MshFile::ElementType::PYRAMID13:\n      return 13;\n    case MshFile::ElementType::TRIA9:\n      return 9;\n    case MshFile::ElementType::TRIA10:\n      return 10;\n    case MshFile::ElementType::TRIA12:\n      return 12;\n    case MshFile::ElementType::TRIA15:\n      return 15;\n    case MshFile::ElementType::TRIA15_5:\n      return 15;\n    case MshFile::ElementType::TRIA21:\n      return 21;\n    case MshFile::ElementType::EDGE4:\n      return 4;\n    case MshFile::ElementType::EDGE5:\n      return 5;\n    case MshFile::ElementType::EDGE6:\n      return 6;\n    case MshFile::ElementType::TET20:\n      return 20;\n    case MshFile::ElementType::TET35:\n      return 35;\n    case MshFile::ElementType::TET56:\n      return 56;\n    case MshFile::ElementType::HEX64:\n      return 64;\n    case MshFile::ElementType::HEX125:\n      return 125;\n  }\n  LF_VERIFY_MSG(false, \"unknown Gmsh element type\");\n  // Make compiler happy:\n  return 0;\n}\n\nbase::RefEl RefElOf(MshFile::ElementType et) {\n  switch (et) {\n    case MshFile::ElementType::POINT:\n      return base::RefEl::kPoint();\n\n    case MshFile::ElementType::EDGE2:\n    case MshFile::ElementType::EDGE3:\n    case MshFile::ElementType::EDGE4:\n    case MshFile::ElementType::EDGE5:\n    case MshFile::ElementType::EDGE6:\n      return base::RefEl::kSegment();\n\n    case MshFile::ElementType::TRIA3:\n    case MshFile::ElementType::TRIA6:\n    case MshFile::ElementType::TRIA9:\n    case MshFile::ElementType::TRIA10:\n    case MshFile::ElementType::TRIA12:\n    case MshFile::ElementType::TRIA15:\n    case MshFile::ElementType::TRIA15_5:\n    case MshFile::ElementType::TRIA21:\n      return base::RefEl::kTria();\n\n    case MshFile::ElementType::QUAD4:\n    case MshFile::ElementType::QUAD8:\n    case MshFile::ElementType::QUAD9:\n      return base::RefEl::kQuad();\n\n    case MshFile::ElementType::TET4:\n    case MshFile::ElementType::HEX8:\n    case MshFile::ElementType::PRISM6:\n    case MshFile::ElementType::PYRAMID5:\n    case MshFile::ElementType::TET10:\n    case MshFile::ElementType::HEX27:\n    case MshFile::ElementType::PRISM18:\n    case MshFile::ElementType::PYRAMID14:\n    case MshFile::ElementType::HEX20:\n    case MshFile::ElementType::PRISM15:\n    case MshFile::ElementType::PYRAMID13:\n    case MshFile::ElementType::TET20:\n    case MshFile::ElementType::TET35:\n    case MshFile::ElementType::TET56:\n    case MshFile::ElementType::HEX64:\n    case MshFile::ElementType::HEX125:\n    default:\n      LF_VERIFY_MSG(\n          false, \"Reference element not supported for GmshElement type \" << et);\n  }\n}\n\n/// Dimension of the GmshElement type\nint DimOf(MshFile::ElementType et) {\n  switch (et) {\n    case MshFile::ElementType::POINT:\n      return 0;\n    case MshFile::ElementType::EDGE2:\n    case MshFile::ElementType::EDGE3:\n    case MshFile::ElementType::EDGE4:\n    case MshFile::ElementType::EDGE5:\n    case MshFile::ElementType::EDGE6:\n      return 1;\n    case MshFile::ElementType::TRIA3:\n    case MshFile::ElementType::QUAD4:\n    case MshFile::ElementType::TRIA6:\n    case MshFile::ElementType::QUAD9:\n    case MshFile::ElementType::QUAD8:\n    case MshFile::ElementType::TRIA9:\n    case MshFile::ElementType::TRIA10:\n    case MshFile::ElementType::TRIA12:\n    case MshFile::ElementType::TRIA15:\n    case MshFile::ElementType::TRIA15_5:\n    case MshFile::ElementType::TRIA21:\n      return 2;\n    case MshFile::ElementType::TET4:\n    case MshFile::ElementType::HEX8:\n    case MshFile::ElementType::PRISM6:\n    case MshFile::ElementType::PYRAMID5:\n    case MshFile::ElementType::TET10:\n    case MshFile::ElementType::HEX27:\n    case MshFile::ElementType::PRISM18:\n    case MshFile::ElementType::PYRAMID14:\n    case MshFile::ElementType::HEX20:\n    case MshFile::ElementType::PRISM15:\n    case MshFile::ElementType::PYRAMID13:\n    case MshFile::ElementType::TET20:\n    case MshFile::ElementType::TET35:\n    case MshFile::ElementType::TET56:\n    case MshFile::ElementType::HEX64:\n    case MshFile::ElementType::HEX125:\n      return 3;\n    default:\n      LF_VERIFY_MSG(false, \"Unknown GmshElement Type.\");\n  }\n  // Make compiler happy:\n  return -1;\n}\n}  // namespace lf::io\n\n// Boost Fusion Adaptions (needed so boost spirit can parse directly into\n// MshFile struct)\n//////////////////////////////////////////////////////////////////////////\nBOOST_FUSION_ADAPT_STRUCT(lf::io::MshFile::PhysicalEntity,\n                          (int, Dimension)(int, Number)(std::string, Name));\n\nBOOST_FUSION_ADAPT_STRUCT(\n    lf::io::MshFile::Element,\n    (size_type, Number)(lf::io::MshFile::ElementType,\n                        Type)(int, PhysicalEntityNr)(int, ElementaryEntityNr)(\n        std::vector<int>, MeshPartitions)(std::vector<size_type>, NodeNumbers));\n\n/// To circumvent comma in preprocessor invocation\nusing nodeMapping_t = std::pair<size_type, size_type>;\n\nBOOST_FUSION_ADAPT_STRUCT(lf::io::MshFile::PeriodicEntity,\n                          (int, Dimension)(int, ElementarySlaveNr)(\n                              int,\n                              ElementaryMasterNr)(std::vector<nodeMapping_t>,\n                                                  NodeMapping));\n\n/// To circumvent comma in preprocessor invocation\nusing nodePair_t = std::pair<size_type, Eigen::Vector3d>;\n\n/// To use MshFile Struct with boost spirit, node that we leave away all\n/// header information this is set using attributes.\n// NOLINTNEXTLINE\nBOOST_FUSION_ADAPT_STRUCT_NAMED(\n    lf::io::MshFile, MshFileAdapted,\n    //(double, VersionNumber)\n    //(bool, IsBinary)\n    //(int, DoubleSize)\n    (std::vector<lf::io::MshFile::PhysicalEntity>,\n     PhysicalEntities)(std::vector<nodePair_t>,\n                       Nodes)(std::vector<lf::io::MshFile::Element>, Elements)(\n        std::vector<lf::io::MshFile::PeriodicEntity>, Periodic));\n\nnamespace boost::spirit::traits {\n/*template<>\nstruct transform_attribute<hydi::io::MshFile::ElementType, int, qi::domain> {\n  using type = int&;\n  static int& pre(hydi::io::MshFile::ElementType& d) { return (int&)d; }\n  static void post(hydi::io::MshFile::ElementType& dval, const int& attr) {}\n  static void fail(hydi::io::MshFile::ElementType&) {}\n};*/\n\ntemplate <typename Enum, typename RawValue>\nstruct assign_to_attribute_from_value<\n    Enum, RawValue,\n    typename std::enable_if<std::is_enum<Enum>::value &&\n                            std::is_same<Enum, RawValue>::value ==\n                                false>::type> {\n  static void call(RawValue const& raw, Enum& cat) {\n    cat = static_cast<Enum>(raw);\n  }\n};\n\n}  // namespace boost::spirit::traits\n\nnamespace lf::io {\nnamespace /*Anonymous*/ {\n\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\nnamespace phoenix = boost::phoenix;\n\n/// A lookup table for boost spirit that can parse an element type\nstruct gmshElementType : qi::symbols<char, unsigned> {\n  gmshElementType() {\n    for (auto& et : MshFile::AllElementTypes) {\n      add(std::to_string(static_cast<int>(et)), static_cast<int>(et));\n    }\n  }\n};\n\nBOOST_PHOENIX_ADAPT_FUNCTION(int, numNodesAdapted, NumNodes, 1);\n\n/// Defines the Grammar of a msh file using boost::spirit\ntemplate <class ITERATOR>\nstruct MshGrammarText\n    : qi::grammar<ITERATOR, boost::fusion::adapted::MshFileAdapted(),\n                  ascii::space_type> {\n  MshGrammarText(\n      qi::rule<ITERATOR, std::pair<size_type, Eigen::Vector3d>()> nodeRule,\n      qi::rule<ITERATOR, std::vector<MshFile::Element>(),\n               qi::locals<size_type, int, int, int, size_type>>\n          elementGroup)\n      : MshGrammarText::base_type(start_, \"Msh File\"),\n        node_(nodeRule),\n        elementGroup_(elementGroup) {\n    using phoenix::push_back;\n    using phoenix::reserve;\n    using phoenix::val;\n    using qi::_val;\n    using qi::char_;\n    using qi::double_;\n    using qi::eps;\n    using qi::int_;\n    using qi::lexeme;\n    using qi::lit;\n    using qi::omit;\n    using qi::repeat;\n    using qi::labels::_1;\n    using qi::labels::_2;\n    using qi::labels::_3;\n    using qi::labels::_4;\n    using qi::labels::_a;\n\n    // General Parsers:\n    quotedString_ %= lexeme['\"' >> +(char_ - '\"') >> '\"'];\n    quotedString_.name(\"string\");\n    startComment_ %= !lit(\"$PhysicalNames\") >> !lit(\"$Nodes\") >>\n                     !lit(\"$Elements\") >> !lit(\"$Periodic\") >>\n                     (lit('$') >> (+(char_ - qi::eol)));\n    startComment_.name(\"Start of Comment\");\n    comment_ %=\n        startComment_[_a = qi::_1] > *(char_ - '$') >> \"$End\" >> qi::string(_a);\n    comment_.name(\"comment\");\n    qi::on_error<qi::fail>(comment_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n\n    // Physical Entities:\n    physicalEntity_ %= int_ > int_ > quotedString_;  // NOLINT\n    physicalEntity_.name(\"Physical Entity Entry\");\n    qi::on_error<qi::fail>(physicalEntity_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n    physicalEntityGroup_ %= \"$PhysicalNames\" >\n                            omit[int_[reserve(_val, qi::_1), _a = qi::_1]] >\n                            repeat(_a)[physicalEntity_] > \"$EndPhysicalNames\";\n    physicalEntityGroup_.name(\"$Physical Entity Section\");\n    qi::on_error<qi::fail>(physicalEntityGroup_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n\n    // Nodes:\n    nodeGroup_ %= \"$Nodes\" > qi::eol >\n                  omit[qi::uint_[reserve(_val, qi::_1), _a = qi::_1]] >\n                  qi::eol > repeat(_a)[node_] > -qi::eol > \"$EndNodes\";\n    nodeGroup_.name(\"$Node Section\");\n    qi::on_error<qi::fail>(node_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n    qi::on_error<qi::fail>(nodeGroup_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n\n    // Elements:\n    qi::on_error<qi::fail>(elementGroup_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n\n    // Periodic entities:\n    periodicEntityNodeMapping_ =\n        omit[qi::uint_[reserve(_val, qi::_1), _a = qi::_1]] >\n        repeat(_a)[qi::uint_ > qi::uint_];  // NOLINT\n    periodicEntityNodeMapping_.name(\"slave-master node mapping\");\n    qi::on_error<qi::fail>(periodicEntityNodeMapping_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n    periodicEntity_ =\n        int_ > int_ > int_ > periodicEntityNodeMapping_;  // NOLINT\n    periodicEntity_.name(\"periodic entity\");\n    qi::on_error<qi::fail>(periodicEntity_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n    periodicEntityGroup_ = \"$Periodic\" >\n                           omit[qi::uint_[reserve(_val, qi::_1), _a = qi::_1]] >\n                           repeat(_a)[periodicEntity_] > \"$EndPeriodic\";\n    periodicEntityGroup_.name(\"periodic entity section\");\n    qi::on_error<qi::fail>(periodicEntityGroup_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n\n    // The whole file:\n    start_ %= *comment_ >> -(physicalEntityGroup_ >> *comment_) >> nodeGroup_ >>\n              *comment_ >> elementGroup_ >> *comment_ >>\n              -(periodicEntityGroup_ >> *comment_);\n    start_.name(\"beginning of file\");\n    qi::on_error<qi::fail>(start_,\n                           errorHandler_(qi::_1, qi::_2, qi::_3, qi::_4));\n  }\n\n  qi::rule<ITERATOR, std::string(), ascii::space_type> quotedString_;\n  qi::rule<ITERATOR, std::string()> startComment_;\n  qi::rule<ITERATOR, qi::locals<std::string>, ascii::space_type> comment_;\n\n  qi::rule<ITERATOR, MshFile::PhysicalEntity(), ascii::space_type>\n      physicalEntity_;\n  qi::rule<ITERATOR, std::vector<MshFile::PhysicalEntity>(),\n           qi::locals<size_type>, ascii::space_type>\n      physicalEntityGroup_;\n\n  qi::rule<ITERATOR, std::pair<size_type, Eigen::Vector3d>()> node_;\n  qi::rule<ITERATOR, std::vector<std::pair<size_type, Eigen::Vector3d>>(),\n           qi::locals<size_type>>\n      nodeGroup_;\n\n  /// locals of elementGroup_ are: (# elements, current element type nr, # tags,\n  /// # elements read so far)\n  qi::rule<ITERATOR, std::vector<MshFile::Element>(),\n           qi::locals<size_type, int, int, int, size_type>>\n      elementGroup_;\n\n  qi::rule<ITERATOR, std::vector<std::pair<size_type, size_type>>(),\n           qi::locals<size_type>, ascii::space_type>\n      periodicEntityNodeMapping_;\n  qi::rule<ITERATOR, MshFile::PeriodicEntity(), ascii::space_type>\n      periodicEntity_;\n  qi::rule<ITERATOR, std::vector<MshFile::PeriodicEntity>(),\n           qi::locals<size_type>, ascii::space_type>\n      periodicEntityGroup_;\n\n  qi::rule<ITERATOR, boost::fusion::adapted::MshFileAdapted(),\n           ascii::space_type>\n      start_;\n\n  struct ErrorHandler {\n    template <class, class, class, class>\n    struct result {\n      using type = void;\n    };\n\n    template <class FIRST, class LAST, class ERROR_POS, class WHAT>\n    void operator()(FIRST first, LAST last, ERROR_POS /*errorPos*/,\n                    WHAT what) const {\n      std::string input(first, last);\n      if (input.length() > 40) {\n        input = input.substr(0, 40);\n      }\n      std::cout << \"Error in MshFile! Expecting \" << what << \" here: \\\"\"\n                << input << \"\\\"\" << std::endl;\n    }\n  };\n  phoenix::function<ErrorHandler> errorHandler_;\n};\n\n}  // namespace\n\nconst std::vector<MshFile::ElementType> MshFile::AllElementTypes{\n    ElementType::EDGE2,     ElementType::TRIA3,     ElementType::QUAD4,\n    ElementType::TET4,      ElementType::HEX8,      ElementType::PRISM6,\n    ElementType::PYRAMID5,  ElementType::EDGE3,     ElementType::TRIA6,\n    ElementType::QUAD9,     ElementType::TET10,     ElementType::HEX27,\n    ElementType::PRISM18,   ElementType::PYRAMID14, ElementType::POINT,\n    ElementType::QUAD8,     ElementType::HEX20,     ElementType::PRISM15,\n    ElementType::PYRAMID13, ElementType::TRIA9,     ElementType::TRIA10,\n    ElementType::TRIA12,    ElementType::TRIA15,    ElementType::TRIA15_5,\n    ElementType::TRIA21,    ElementType::EDGE4,     ElementType::EDGE5,\n    ElementType::EDGE6,     ElementType::TET20,     ElementType::TET35,\n    ElementType::TET56,     ElementType::HEX64,     ElementType::HEX125};\n\nMshFile readGMshFile(const std::string& filename) {\n  // Open file and copy into memory:hydi::io::MshFile\n  //////////////////////////////////////////////////////////////////////////\n  std::ifstream in(filename, std::ios_base::in);\n  if (!in) {\n    std::string error(\"Could not open file \");\n    error += filename;\n    throw base::LfException(error);\n  }\n  std::string storage;\n  in.unsetf(std::ios::skipws);  // No white space skipping\n  std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(),\n            std::back_inserter(storage));\n\n  // Parse header to determine if we are dealing with ASCII format or binary\n  // format + little or big endian:\n  //////////////////////////////////////////////////////////////////////////\n  MshFile result;\n  std::string::const_iterator iter = storage.begin();\n  std::string::const_iterator end = storage.end();\n  using iterator_t = std::string::const_iterator;\n\n  int one;\n  bool successful;\n  successful = qi::phrase_parse(\n      iter, end,\n      qi::lit(\"$MeshFormat\") >>\n          qi::double_[phoenix::ref(result.VersionNumber) = qi::_1] >>\n          ((qi::lit('0')[phoenix::ref(result.IsBinary) = false] >>\n            qi::int_[phoenix::ref(result.DoubleSize) = qi::_1]) |\n           (qi::lit('1')[phoenix::ref(result.IsBinary) = true] >>\n            qi::int_[phoenix::ref(result.DoubleSize) = qi::_1] >>\n            qi::little_dword[phoenix::ref(one) = qi::_1])) >>\n          \"$EndMeshFormat\",\n      ascii::space);\n  LF_VERIFY_MSG(successful, \"Could not read header of file \" << filename);\n  LF_VERIFY_MSG(result.VersionNumber == 2.2,\n                \"This GMSH Reader supports only version 2.2 of the mesh file.\");\n  LF_ASSERT_MSG(result.DoubleSize == 8, \"Size of double must be 8.\");\n\n  // Parse the rest of the document\n  //////////////////////////////////////////////////////////////////////////\n\n  // Setup parsers for node/element sections (which are different depending on\n  // binary/non-binary files):\n  //\n  // Note vec3 has no skipper because it may be used inside lexeme and lexeme\n  // can only use parsers without skippers!\n  // http://boost-spirit.com/home/2010/02/24/parsing-skippers-and-skipping-parsers/\n  // (see comment section)\n  qi::rule<iterator_t, Eigen::Vector3d> vec3;\n  qi::rule<iterator_t, std::pair<size_type, Eigen::Vector3d>()> node;\n  qi::rule<iterator_t, MshFile::Element(), qi::locals<int>> elementText;\n  qi::rule<iterator_t, MshFile::Element(MshFile::ElementType, int, int)>\n      elementBin;\n  qi::rule<iterator_t, std::vector<MshFile::Element>(),\n           qi::locals<size_type, int, int, int, size_type>>\n      elementGroup;\n\n  using phoenix::reserve;\n  using qi::omit;\n  using qi::repeat;\n  using qi::labels::_a;\n  using qi::labels::_b;\n  using qi::labels::_c;\n  using qi::labels::_d;\n  using qi::labels::_e;\n  using qi::labels::_r1;\n  using qi::labels::_r2;\n  using qi::labels::_r3;\n  using qi::labels::_val;\n\n  if (!result.IsBinary) {\n    // Text file\n    vec3 = qi::double_ >> ' ' >> qi::double_ >> ' ' >> qi::double_;\n    node = qi::uint_ >> ' ' >> vec3 >> qi::eol;\n    elementText %= qi::int_ > ' ' > qi::int_ > ' ' >\n                   qi::omit[qi::int_[qi::_a = qi::_1]] > ' ' > qi::int_ > ' ' >\n                   qi::int_ > ' ' >\n                   ((qi::eps(_a > 2) >> omit[qi::int_] >> ' ') || qi::eps) >\n                   qi::repeat(qi::_a - 3)[qi::int_ >> ' '] > (qi::uint_ % ' ') >\n                   *(qi::blank) > qi::eol;\n    elementGroup %= \"$Elements\" > qi::eol >\n                    qi::omit[qi::uint_[phoenix::reserve(qi::_val, qi::_1),\n                                       qi::_a = qi::_1]] > qi::eol >\n                    qi::repeat(qi::_a)[elementText] > \"$EndElements\";\n  } else if (result.IsBinary && one == 1) {\n    // Binary File Little Endian\n    // std::cout << \"little endian\" << std::endl;\n    vec3 %=\n        qi::little_bin_double >> qi::little_bin_double >> qi::little_bin_double;\n    node %= qi::no_skip[qi::little_dword >> vec3];\n    elementBin %= qi::little_dword >> qi::attr(_r1) >> qi::little_dword >>\n                  qi::little_dword >>\n                  ((qi::eps(_r2 > 2) >> omit[qi::little_dword]) || qi::eps) >>\n                  qi::repeat(_r2 - 3)[qi::little_dword] >>\n                  qi::repeat(_r3)[qi::little_dword];\n    elementGroup %=\n        \"$Elements\" >> qi::eol >> qi::eps[_e = 0] >>\n        omit[qi::uint_[reserve(_val, qi::_1), _a = qi::_1]] >>\n        qi::eol  // # Elements in total\n        >>\n        omit[*((qi::eps(_e < _a) >> qi::little_dword[_b = qi::_1] >>\n                qi::little_dword[_c = qi::_1] >>\n                qi::little_dword[_d = qi::_1]  // elements-header-binary\n                >>\n                repeat(_c)[elementBin(\n                    phoenix::static_cast_<MshFile::ElementType>(_b), _d,\n                    numNodesAdapted(phoenix::static_cast_<MshFile::ElementType>(\n                        _b)))[phoenix::push_back(_val, qi::_1)]]) >>\n               qi::eps[_e += _c])]  // elements-binary\n        >> qi::eol >> \"$EndElements\";\n  } else {\n    // std::cout << \"big endian\" << std::endl;\n    // Binary File Big Endian\n    vec3 %= qi::big_bin_double >> qi::big_bin_double >> qi::big_bin_double;\n    node %= qi::no_skip[qi::big_dword >> vec3];\n    elementBin %=\n        qi::big_dword >> qi::attr(_r1) >> qi::big_dword >> qi::big_dword >>\n        ((qi::eps(_r2 > 2) >> omit[qi::big_dword]) || qi::eps) >>\n        qi::repeat(_r2 - 3)[qi::big_dword] >> qi::repeat(_r3)[qi::big_dword];\n    elementGroup %=\n        \"$Elements\" >> qi::eol >> qi::eps[_e = 0] >>\n        omit[qi::uint_[reserve(_val, qi::_1), _a = qi::_1]] >>\n        qi::eol  // # Elements in total\n        >>\n        omit[*((qi::eps(_e < _a) >> qi::big_dword[_b = qi::_1] >>\n                qi::big_dword[_c = qi::_1] >>\n                qi::big_dword[_d = qi::_1]  // elements-header-binary\n                >>\n                repeat(_c)[elementBin(\n                    phoenix::static_cast_<MshFile::ElementType>(_b), _d,\n                    numNodesAdapted(phoenix::static_cast_<MshFile::ElementType>(\n                        _b)))[phoenix::push_back(_val, qi::_1)]]) >>\n               qi::eps[_e += _c])]  // elements-binary\n        >> qi::eol >> \"$EndElements\";\n  }\n\n  /// Name the elements for better error parsing:\n  vec3.name(\"vec3\");\n  node.name(\"node\");\n  elementText.name(\"element\");\n  elementBin.name(\"element\");\n  elementGroup.name(\"ElementSection\");\n\n  // Finally parse everything:\n  MshGrammarText<iterator_t> mshGrammar(node, elementGroup);\n  bool r = qi::phrase_parse(iter, end, mshGrammar, ascii::space, result);\n\n  // if (r && iter == end) std::cout << \"Parsing succeeded\" << std::endl;\n  // else if (r) std::cout << \"Parsing partially succeeded\" << std::endl;\n  // std::cout << result << std::endl;\n\n  LF_VERIFY_MSG(r, \"Could not parse file \" << filename);\n  LF_VERIFY_MSG(iter == end, \"Could not parse all of file \" << filename);\n\n  return result;\n}\n\nbool GmshReader::IsPhysicalEntity(const mesh::Entity& e,\n                                  size_type physical_entity_nr) const {\n  auto physical_entities = PhysicalEntityNr(e);\n  return std::find(physical_entities.begin(), physical_entities.end(),\n                   physical_entity_nr) != physical_entities.end();\n}\n\nGmshReader::GmshReader(std::unique_ptr<mesh::MeshFactory> factory,\n                       const ::lf::io::MshFile& msh_file)\n    : mesh_factory_(std::move(factory)) {\n  // 1) Check Gmsh_file and initialize\n  //////////////////////////////////////////////////////////////////////////\n\n  dim_t dim_mesh = mesh_factory_->DimMesh();\n  dim_t dim_world = mesh_factory_->DimWorld();\n  LF_VERIFY_MSG(\n      dim_mesh >= 2 && dim_mesh <= 3 && dim_world >= 2 && dim_world <= 3,\n      \"GmshReader supports only 2D and 3D meshes.\");\n\n  // 1) Determine which nodes of gmsh are also nodes of the LehrFEM++ mesh +\n  // count number of entities of each codimension (exclude auxilliary nodes).\n  // This is necessary because e.g. second order meshes in gmsh need a lot of\n  // auxilliary nodes to define their geometry...\n  /////////////////////////////////////////////////////////////////////////////\n  // is_main_node[i] = true means that gmsh-node i is one of the main nodes of\n  // an element\n  std::vector<bool> is_main_node(msh_file.Nodes.size(), false);\n\n  // mi2gi = mesh_index_2_gmsh_index\n  // mi2gi[c][i] contains the gmsh entities that belong to the mesh entity with\n  //             codim = c and mesh index i.\n  std::vector<std::vector<std::vector<size_type>>> mi2gi(dim_mesh + 1);\n\n  {\n    // count the number of entities for each codimension and reserve space:\n    std::vector<size_type> num_entities(mesh_factory_->DimMesh() + 1, 0);\n\n    for (const auto& e : msh_file.Elements) {\n      LF_ASSERT_MSG(DimOf(e.Type) <= dim_mesh,\n                    \"mesh_factory->DimMesh() = \"\n                        << dim_mesh\n                        << \", but msh-file contains entities with dimension \"\n                        << DimOf(e.Type));\n\n      ++num_entities[DimOf(e.Type)];\n\n      if (DimOf(e.Type) == dim_mesh) {\n        // mark main nodes\n        auto ref_el = RefElOf(e.Type);\n        for (int i = 0; i < ref_el.NumNodes(); ++i) {\n          auto node_number = e.NodeNumbers[i];\n          if (is_main_node.size() <= node_number) {\n            is_main_node.resize(node_number + 1);\n          }\n          is_main_node[e.NodeNumbers[i]] = true;\n        }\n      }\n    }\n\n    for (dim_t c = 0; c <= dim_mesh; ++c) {\n      mi2gi[c].reserve(num_entities[dim_mesh - c]);\n    }\n\n    LF_ASSERT_MSG(num_entities[dim_mesh] > 0,\n                  \"MshFile contains no elements with dimension \" << dim_mesh);\n  }\n\n  // 2) Insert main nodes into MeshFactory\n  /////////////////////////////////////////////////////////////////////////////\n\n  // gmsh_index_2_mesh_index for nodes:\n  // gi2mi[i] = j means that gmsh node with gmsh index i has mesh index j\n  std::vector<size_type> gi2mi;\n  gi2mi.resize(is_main_node.size(), -1);\n\n  // gi2i[i] = j implies msh_file.Nodes[j].first = i\n  std::vector<size_type> gi2i;\n  gi2i.resize(is_main_node.size(), -1);\n\n  for (int i = 0; i < msh_file.Nodes.size(); ++i) {\n    auto& n = msh_file.Nodes[i];\n    if (gi2i.size() <= n.first) {\n      gi2i.resize(n.first + 1, -1);\n    }\n    gi2i[n.first] = i;\n\n    if (is_main_node.size() <= n.first || !is_main_node[n.first]) {\n      continue;\n    }\n\n    size_type mi;\n    if (dim_world == 2) {\n      LF_ASSERT_MSG(\n          n.second(2) == 0,\n          \"In a 2D GmshMesh, the z-coordinate of every node must be zero\");\n      mi = mesh_factory_->AddPoint(n.second.topRows(2));\n    } else if (dim_mesh == 3) {\n      mi = mesh_factory_->AddPoint(n.second);\n    }\n    gi2mi[n.first] = mi;\n  }\n\n  // 3) Insert entities (except nodes) into MeshFactory:\n  //////////////////////////////////////////////////////////////////////////////\n\n  size_type begin = 0;\n  for (size_type end = 0; end < msh_file.Elements.size(); ++end) {\n    auto& begin_element = msh_file.Elements[begin];\n    auto& end_element = msh_file.Elements[end];\n    auto ref_el = RefElOf(end_element.Type);\n    auto codim = dim_mesh - ref_el.Dimension();\n    if (begin_element.NodeNumbers == end_element.NodeNumbers && begin != end &&\n        begin_element.Type == end_element.Type) {\n      // This entity appears more than once\n      mi2gi[codim].back().push_back(end);\n      continue;\n    }\n\n    begin = end;\n    if (ref_el == base::RefEl::kPoint()) {\n      // special case, this entity is a point (which has already been inserted)\n      auto mesh_index = gi2mi[end_element.NodeNumbers[0]];\n      if (mi2gi[dim_mesh].size() <= mesh_index) {\n        mi2gi[dim_mesh].resize(mesh_index + 1);\n      }\n      mi2gi[dim_mesh][mesh_index].push_back(end);\n    } else {\n      // gmsh element is not a point -> insert entity:\n      auto num_nodes = end_element.NodeNumbers.size();\n      Eigen::MatrixXd node_coords(dim_world, num_nodes);\n      for (size_type i = 0; i < num_nodes; ++i) {\n        auto node_coord =\n            msh_file.Nodes[gi2i[end_element.NodeNumbers[i]]].second;\n        if (dim_world == 2) {\n          node_coords.col(i) = node_coord.topRows(2);\n        } else {\n          node_coords.col(i) = node_coord;\n        }\n      }\n      std::unique_ptr<geometry::Geometry> geom;\n\n      switch (end_element.Type) {\n        case MshFile::ElementType::EDGE2:\n          ref_el = base::RefEl::kSegment();\n          geom = std::make_unique<geometry::SegmentO1>(node_coords);\n          break;\n        case MshFile::ElementType::EDGE3:\n          ref_el = base::RefEl::kSegment();\n          geom = std::make_unique<geometry::SegmentO2>(node_coords);\n          break;\n        case MshFile::ElementType::TRIA3:\n          ref_el = base::RefEl::kTria();\n          geom = std::make_unique<geometry::TriaO1>(node_coords);\n          break;\n        case MshFile::ElementType::TRIA6:\n          ref_el = base::RefEl::kTria();\n          geom = std::make_unique<geometry::TriaO2>(node_coords);\n          break;\n        case MshFile::ElementType::QUAD4:\n          ref_el = base::RefEl::kQuad();\n          geom = std::make_unique<geometry::QuadO1>(node_coords);\n          break;\n        case MshFile::ElementType::QUAD8:\n          ref_el = base::RefEl::kQuad();\n          geom = std::make_unique<geometry::QuadO2>(node_coords);\n          break;\n        case MshFile::ElementType::QUAD9:\n          ref_el = base::RefEl::kQuad();\n          geom = std::make_unique<geometry::QuadO2>(node_coords.leftCols(8));\n          break;\n        default:\n          LF_VERIFY_MSG(false, \"Gmsh element type \"\n                                   << end_element.Type\n                                   << \" not (yet) supported by GmshReader.\");\n      }\n      std::vector<size_type> main_nodes(ref_el.NumNodes());\n      for (dim_t i = 0; i < ref_el.NumNodes(); ++i) {\n        main_nodes[i] = gi2mi[end_element.NodeNumbers[i]];\n      }\n\n      mesh_factory_->AddEntity(ref_el, main_nodes, std::move(geom));\n      mi2gi[codim].emplace_back(std::vector{end});\n    }\n  }\n\n  // 4) Construct mesh\n  //////////////////////////////////////////////////////////////////////////////\n  mesh_ = mesh_factory_->Build();\n\n  // 5) Build MeshDataSet that assigns the physical entitiies:\n  //////////////////////////////////////////////////////////////////////////////\n  physical_nrs_ =\n      mesh::utils::make_AllCodimMeshDataSet<std::vector<size_type>>(mesh_);\n\n  for (dim_t c = 0; c <= dim_mesh; ++c) {\n    for (auto& e : mesh_->Entities(c)) {\n      auto mi = mesh_->Index(e);\n      if (c == dim_mesh && mi >= mi2gi[dim_mesh].size()) {\n        // this point did not appear as a gmsh element in the file -> don't\n        // assign any physical entity nr.\n        continue;\n      }\n      if (mi2gi[c].size() > mi) {\n        std::vector<size_type> temp;\n        for (auto& gmsh_index : mi2gi[c][mi]) {\n          temp.push_back(msh_file.Elements[gmsh_index].PhysicalEntityNr);\n        }\n\n        physical_nrs_->operator()(e) = std::move(temp);\n      }\n    }\n  }\n\n  // 6) Create mapping physicalEntityNr <-> physicalEntityName:\n  //////////////////////////////////////////////////////////////////////////\n\n  for (auto pe : msh_file.PhysicalEntities) {\n    name_2_nr_.insert(\n        std::pair{pe.Name, std::pair{pe.Number, dim_mesh - pe.Dimension}});\n    nr_2_name_.insert(\n        std::pair{pe.Number, std::pair{pe.Name, dim_mesh - pe.Dimension}});\n  }\n\n  if (!msh_file.Periodic.empty()) {\n    /*LOGGER_ENTRY(logger_,\n                 \"WARNING: GMSH File  contains periodic boundary relations \"\n                 \"between elements. These are ignored by GmshReader.\",\n                 3);*/\n  }\n}\n\nGmshReader::GmshReader(std::unique_ptr<mesh::MeshFactory> factory,\n                       const std::string& filename)\n    : GmshReader(std::move(factory), readGMshFile(filename)) {}\n\nsize_type GmshReader::PhysicalEntityName2Nr(const std::string& name,\n                                            dim_t codim) const {\n  LF_ASSERT_MSG(!name.empty(), \"name is empty\");\n  auto [begin, end] = name_2_nr_.equal_range(name);  // NOLINT\n  if (begin == end) {\n    throw base::LfException(\"No Physical Entity with this name found.\");\n  }\n  auto result = *begin;\n  ++begin;\n  if (begin == end) {\n    if (codim == dim_t(-1) || codim == result.second.second) {\n      return result.second.first;\n    }\n  } else {\n    if (codim == dim_t(-1)) {\n      throw base::LfException(\n          \"There are multiple physical entities with the name \" + name +\n          \", please specify also the codimension.\");\n    }\n    if (result.second.second == codim) {\n      return result.second.first;\n    }\n    while (begin->second.second != codim && begin != end) {\n      ++begin;\n    }\n    if (begin->second.second == codim) {\n      return begin->second.first;\n    }\n  }\n  throw base::LfException(\"Physical Entity with name='\" + name +\n                          \"' and codimension=\" + std::to_string(codim) +\n                          \"' not found.\");\n}\n\nstd::string GmshReader::PhysicalEntityNr2Name(size_type number,\n                                              dim_t codim) const {\n  auto [begin, end] = nr_2_name_.equal_range(number);  // NOLINT\n  if (begin == end) {\n    throw base::LfException(\"Physical entity with number \" +\n                            std::to_string(number) + \" not found.\");\n  }\n  auto result = *begin;\n  ++begin;\n  if (begin == end) {\n    if (codim == dim_t(-1) || result.second.second == codim) {\n      return result.second.first;\n    }\n  } else {\n    if (codim == dim_t(-1)) {\n      throw base::LfException(\n          \"There are multiple physical entities with the Number \" +\n          std::to_string(number) + \", please specify also the codimension\");\n    }\n    if (result.second.second == codim) {\n      return result.second.first;\n    }\n    while (begin->second.second != codim && begin != end) {\n      ++begin;\n    }\n    if (begin->second.second == codim) {\n      return begin->second.first;\n    }\n  }\n  throw base::LfException(\n      \"Physical entity with number=\" + std::to_string(number) +\n      \", codim=\" + std::to_string(codim) + \" not found.\");\n}\n\nstd::vector<std::pair<size_type, std::string>> GmshReader::PhysicalEntities(\n    dim_t codim) const {\n  std::vector<std::pair<size_type, std::string>> result;\n  for (auto& p : nr_2_name_) {\n    if (p.second.second != codim) {\n      continue;\n    }\n    result.emplace_back(p.first, p.second.first);\n  }\n  return result;\n}\n\nstd::vector<size_type> GmshReader::PhysicalEntityNr(\n    const mesh::Entity& e) const {\n  return physical_nrs_->operator()(e);\n}\n\n}  // namespace lf::io\n", "meta": {"hexsha": "3e15e79b343a8de1e05b688a4ca575cecbdbcebe", "size": 39187, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/io/gmsh_reader.cc", "max_stars_repo_name": "Pascal-So/lehrfempp", "max_stars_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/lf/io/gmsh_reader.cc", "max_issues_repo_name": "Pascal-So/lehrfempp", "max_issues_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/lf/io/gmsh_reader.cc", "max_forks_repo_name": "Pascal-So/lehrfempp", "max_forks_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "max_forks_repo_licenses": ["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.250693802, "max_line_length": 83, "alphanum_fraction": 0.5912419935, "num_tokens": 10644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.026355355618338253, "lm_q1q2_score": 0.008276913795392023}}
{"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 \"dd_synthesis_p.hpp\"\n\n#include <iostream>\n#include <map>\n#include <vector>\n#include <memory>\n\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/join.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/format.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/optional.hpp>\n#include <boost/range/adaptor/map.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/algorithm_ext/push_back.hpp>\n\n#include <puma.h>\n\n#include <cudd.h>\n#include <cuddInt.h>\n\n#include <core/io/read_pla_to_bdd.hpp>\n\n#include <reversible/circuit.hpp>\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/functions/clear_circuit.hpp>\n\nnamespace cirkit\n{\n\nnamespace internal\n{\n\n  using namespace boost::assign;\n\n  typedef boost::graph_traits<dd>::vertex_descriptor dd_node;\n  typedef boost::graph_traits<dd>::edge_descriptor   dd_edge;\n\n  struct vertex_drawer\n  {\n    explicit vertex_drawer( const dd& graph ) : _graph ( graph ) {}\n\n    template<typename Vertex>\n    void operator()( std::ostream& os, const Vertex& v ) const\n    {\n      if ( !boost::in_degree( v, _graph ) || !boost::out_degree( v, _graph ) )\n      {\n        std::string label;\n        if ( out_degree( v, _graph ) )\n        {\n          label = get_property( _graph, boost::graph_name ).labels.at( get( boost::vertex_name, _graph )[v].var );\n        }\n        else\n        {\n          label = boost::lexical_cast<std::string>( get( boost::vertex_name, _graph )[v].var );\n        }\n        os << \"[shape=\\\"rectangle\\\",label=\\\"\" << label << \"\\\"]\";\n      }\n      else\n      {\n        os << \"[label=\\\"\"\n           << get_property( _graph, boost::graph_name ).labels.at( get( boost::vertex_name, _graph )[v].var )\n           << \":\"\n           << get( boost::vertex_name, _graph )[v].dtl\n           << \"\\\"]\";\n      }\n    }\n\n  private:\n    const dd& _graph;\n  };\n\n  struct edge_drawer\n  {\n  public:\n    explicit edge_drawer( const dd& graph ) : _graph( graph ) {}\n\n    template<typename Edge>\n    void operator()( std::ostream& os, const Edge& e ) const\n    {\n      dd_node source = boost::source( e, _graph );\n\n      std::vector<std::string> properties;\n      if ( e == *boost::out_edges( source, _graph ).first && in_degree( source, _graph ) )\n      {\n        properties += \"style=dashed\";\n      }\n      if ( get( boost::edge_name, _graph )[e].complemented )\n      {\n        properties += \"color=red\";\n      }\n\n      if ( properties.size() )\n      {\n        properties.front().insert( 0, \"[\" );\n        properties.back().append( \"]\" );\n      }\n\n      os << boost::algorithm::join( properties, \",\" );\n    }\n\n  private:\n    const dd& _graph;\n  };\n\n  void dd_to_dot( const dd& graph, const std::string& filename )\n  {\n    std::filebuf fb;\n    fb.open( filename.c_str(), std::ios::out );\n    std::ostream os( &fb );\n    boost::write_graphviz( os, graph, vertex_drawer( graph ), edge_drawer( graph ) );\n    fb.close();\n  }\n\n  unsigned dd_node_var( const dd_node& node, const dd& graph )\n  {\n    return get( boost::vertex_name, graph )[node].var;\n  }\n\n  bool dd_node_is_constant( const dd_node& node, const dd& graph )\n  {\n    return !out_degree( node, graph );\n  }\n\n  dd_node dd_root_get_function_root( const dd_node& node, const dd& graph )\n  {\n    boost::graph_traits<dd>::in_edge_iterator itEdge, itEnd;\n\n    for ( boost::tie( itEdge, itEnd ) = in_edges( node, graph ); itEdge != itEnd; ++itEdge )\n    {\n      if ( in_degree( source( *itEdge, graph ), graph ) == 0 )\n      {\n        return source( *itEdge, graph );\n      }\n    }\n\n    assert( false );\n    return dd_node();\n  }\n\n  bool dd_root_is_complemented( const dd_node& node, const dd& graph )\n  {\n    return get( boost::edge_name, graph )[*out_edges( dd_root_get_function_root( node, graph ), graph ).first].complemented;\n  }\n\n  const std::vector<std::string>& dd_labels( const dd& graph )\n  {\n    return get_property( graph, boost::graph_name ).labels;\n  }\n\n  const std::vector<dd_node>& dd_roots( const dd& graph )\n  {\n    return get_property( graph, boost::graph_name ).roots;\n  }\n\n  ////////////////////////////////////////////////////////////////////////////////\n  // KFDD Code                                                                  //\n  ////////////////////////////////////////////////////////////////////////////////\n  dd_from_kfdd_settings::dd_from_kfdd_settings()\n    : default_decomposition( 0 ),\n      reordering( 0 ),\n      sift_factor( 2.5 ),\n      sifting_growth_limit( 'a' ),\n      sifting_method( 'v' ),\n      node_count( 0 )\n  {\n  }\n\n  bool OKFDD_IsComplement( utnode* node )\n  {\n    return ((ulint)node & 1) == 1;\n  }\n\n  bool OKFDD_IsConstant( dd_man* manager, utnode* node )\n  {\n    return ( node == manager->OKFDD_ONE || node == manager->OKFDD_ZERO );\n  }\n\n  utnode* OKFDD_Regular( utnode* node )\n  {\n    return (m_and(node));\n  }\n\n  bool OKFDD_Value( dd_man* manager, utnode* node )\n  {\n    if ( OKFDD_IsConstant( manager, node ) )\n    {\n      return node == manager->OKFDD_ONE;\n    }\n    else\n    {\n      assert( false );\n      return false;\n    }\n  }\n\n  dd_node dd_from_kfdd( dd& graph, dd_man* manager, utnode* node, std::map<utnode*, dd_node>& visited_map )\n  {\n    if ( visited_map.find( node ) != visited_map.end() )\n    {\n      return visited_map[node];\n    }\n\n    dd_node v = boost::add_vertex( graph );\n\n    if ( !OKFDD_IsConstant( manager, node ) )\n    {\n      dd_node low  = dd_from_kfdd( graph, manager, OKFDD_Regular( (m_and(node))->lo_p ), visited_map );\n      dd_node high = dd_from_kfdd( graph, manager, OKFDD_Regular( (m_and(node))->hi_p ), visited_map );\n\n      add_edge( v, low, graph );\n      dd_edge edge;\n      bool    ok;\n      boost::tie( edge, ok ) = add_edge( v, high, graph );\n      get( boost::edge_name, graph )[edge].complemented = OKFDD_IsComplement( (m_and(node))->hi_p );\n\n      get( boost::vertex_name, graph )[v].var = manager->OKFDD_Label( node ) - 1;\n      get( boost::vertex_name, graph )[v].dtl = (unsigned short)manager->OKFDD_PI_DTL_Table[manager->OKFDD_Label( node )];\n    }\n    else\n    {\n      get( boost::vertex_name, graph )[v].var = OKFDD_Value( manager, node );\n    }\n\n    visited_map[node] = v;\n\n    return v;\n  }\n\n  void dd_from_kfdd( dd& graph, dd_man* manager, const std::vector<utnode*>& nodes )\n  {\n    std::map<utnode*, dd_node> visited_map;\n\n    for ( std::vector<utnode*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it )\n    {\n      dd_node v = boost::add_vertex( graph );\n      bool ok;\n      dd_edge edge;\n      dd_node v2 = dd_from_kfdd( graph, manager, *it, visited_map );\n      boost::tie( edge, ok ) = add_edge( v, v2, graph );\n      get( boost::edge_name, graph )[edge].complemented = OKFDD_IsComplement( *it );\n\n      get( boost::vertex_name, graph )[v].var      = get_property( graph, boost::graph_name ).labels.size() - nodes.size() + ( it - nodes.begin() );\n      get_property( graph, boost::graph_name ).roots += v2;\n    }\n  }\n\n  void dd_from_kfdd( dd& graph, const std::string& filename, const dd_from_kfdd_settings& settings )\n  {\n    unsigned char      ut_hashsize  = 0;\n    unsigned long      ct_hashsize  = 5003;\n    unsigned long int  rc_cachesize = 1000;\n    unsigned char      ct_searchlen = 3;\n    unsigned short int var_lim     = 20000;\n\n    dd_man* dd_manager = OKFDD_Init( ut_hashsize,\n                                     ct_hashsize,\n                                     rc_cachesize,\n                                     ct_searchlen,\n                                     var_lim );\n\n    /* set some construction parameters */\n    dd_manager->OKFDD_Outputflags  = 0;\n    dd_manager->OKFDD_Version_Wait = false;\n    dd_manager->OKFDD_DTL_Default  = settings.default_decomposition;\n    dd_manager->OKFDD_Tempfactor   = 3;\n    dd_manager->OKFDD_Siftfactor   = 3;\n    dd_manager->OKFDD_Temproutine  = 3;\n    dd_manager->OKFDD_Interleaving = true;\n\n    std::string input_names, output_names;\n    dd_manager->OKFDD_Read_BLIF( const_cast<char*>( filename.c_str() ), 0, &INTERHAND, 0, 0, &input_names, &output_names );\n\n    unsigned npi = dd_manager->OKFDD_P_I;\n    unsigned npo = dd_manager->OKFDD_P_O;\n\n    switch ( settings.reordering )\n    {\n    case 0: //kfdd_synthesis_reordering_none:\n      break;\n\n    case 1: //kfdd_synthesis_reordering_exact_dtl_friedman:\n      dd_manager->OKFDD_DTL_Friedman( 0, npi - 1 );\n      break;\n\n    case 2: //kfdd_synthesis_reordering_exact_dtl_permutation:\n      dd_manager->OKFDD_DTL_Permutation( 0, npi - 1 );\n      break;\n\n    case 3: //kfdd_synthesis_reordering_dtl_sifting:\n      dd_manager->OKFDD_DTL_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      break;\n\n    case 4: //kfdd_synthesis_reordering_exact_friedman:\n      dd_manager->OKFDD_Friedman( 0, npi - 1 );\n      break;\n\n    case 5: //kfdd_synthesis_reordering_exact_permutation:\n      dd_manager->OKFDD_Permutation( 0, npi - 1 );\n      break;\n\n    case 6: //kfdd_synthesis_reordering_sifting:\n      dd_manager->OKFDD_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      break;\n\n    case 7: //kfdd_synthesis_reordering_sifting_and_dtl_sifting:\n      dd_manager->OKFDD_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      dd_manager->OKFDD_DTL_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      break;\n\n    case 8: //kfdd_synthesis_reordering_inverse:\n      dd_manager->OKFDD_Inversion( 0, npi - 1 );\n      break;\n\n    case 9: //kfdd_synthesis_reordering_quantum_sifting line-sifting:\n      dd_manager->OKFDD_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      dd_manager->OKFDD_DTL_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      dd_manager->OKFDD_DTL_Sifting_Quantum( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method, 1 );\n      break;\n\n    case 10: //kfdd_synthesis_reordering_quantum_sifting quantumcost-sifting:\n      dd_manager->OKFDD_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      dd_manager->OKFDD_DTL_Sifting( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method );\n      dd_manager->OKFDD_DTL_Sifting_Quantum( 0, npi - 1, settings.sift_factor, settings.sifting_growth_limit, settings.sifting_method, 0 );\n      break;\n    }\n\n    std::vector<std::string> labels;\n    boost::algorithm::trim( input_names );\n    boost::algorithm::trim( output_names );\n    boost::algorithm::split( labels, input_names, boost::is_any_of( \" \" ) );\n    get_property( graph, boost::graph_name ).ninputs = labels.size();\n    std::copy( labels.begin(), labels.end(), std::back_inserter( get_property( graph, boost::graph_name ).labels ) );\n    boost::algorithm::split( labels, output_names, boost::is_any_of( \" \" ) );\n    std::copy( labels.begin(), labels.end(), std::back_inserter( get_property( graph, boost::graph_name ).labels ) );\n\n    std::vector<utnode*> nodes;\n    for ( unsigned i = 0; i < npo; ++i )\n    {\n      nodes += dd_manager->OKFDD_PO_Root_Table( dd_manager->OKFDD_PO_Table( i ) );\n    }\n\n    dd_from_kfdd( graph, dd_manager, nodes );\n\n    if ( settings.node_count )\n    {\n      // TODO node counting seems to be wrong in PUMA\n      *settings.node_count = dd_manager->OKFDD_Size_all();\n      //*settings.node_count = dd_manager->OKFDD_Now_size_i;\n      // TODO This fixes node counting\n      //*settings.node_count = boost::num_vertices( graph ) - 1u - ( get_property( graph, boost::graph_name ).labels.size() - get_property( graph, boost::graph_name ).ninputs );\n    }\n  }\n\n////////////////////////////////////////////////////////////////////////////////\n// BDD Code                                                                   //\n////////////////////////////////////////////////////////////////////////////////\n\n  dd_from_bdd_settings::dd_from_bdd_settings()\n    : complemented_edges( true ),\n      reordering( CUDD_REORDER_SIFT ),\n      node_count( 0 )\n  {\n  }\n\n  dd_node dd_from_bdd( dd& graph, DdNode* node, std::map<DdNode*, dd_node>& visited_map )\n  {\n    if ( visited_map.find( node ) != visited_map.end() )\n    {\n      return visited_map[node];\n    }\n\n    dd_node v = boost::add_vertex( graph );\n\n    if ( !cuddIsConstant( node ) )\n    {\n      dd_node low  = dd_from_bdd( graph, Cudd_Regular( cuddE( node ) ), visited_map );\n      dd_node high = dd_from_bdd( graph, cuddT( node ), visited_map );\n\n      dd_edge edge;\n      bool    ok;\n      boost::tie( edge, ok ) = add_edge( v, low, graph );\n      get( boost::edge_name, graph )[edge].complemented = Cudd_IsComplement( cuddE( node ) );\n\n      add_edge( v, high, graph );\n\n      get( boost::vertex_name, graph )[v].var = node->index;\n    }\n    else\n    {\n      get( boost::vertex_name, graph )[v].var = cuddV( node );\n    }\n\n    visited_map[node] = v;\n\n    return v;\n  }\n\n  void dd_from_bdd( dd& graph, const std::vector<DdNode*>& nodes )\n  {\n    std::map<DdNode*, dd_node> visited_map;\n\n    for ( std::vector<DdNode*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it ) {\n      dd_node v = boost::add_vertex( graph );\n      bool ok;\n      dd_edge edge;\n      dd_node v2 = dd_from_bdd( graph, Cudd_Regular( *it ), visited_map );\n      boost::tie( edge, ok ) = add_edge( v, v2, graph );\n      get( boost::edge_name, graph )[edge].complemented = Cudd_IsComplement( *it );\n\n      get( boost::vertex_name, graph )[v].var = get_property( graph, boost::graph_name ).labels.size() - nodes.size() + ( it - nodes.begin() );\n      get_property( graph, boost::graph_name ).roots += v2;\n    }\n  }\n\n  void dd_from_bdd( dd& graph, const std::string& filename, const dd_from_bdd_settings& settings )\n  {\n    BDDTable bdd;\n    read_pla_to_bdd( bdd, filename );\n\n    // Reorder the BDD\n    Cudd_ReduceHeap( bdd.cudd, (Cudd_ReorderingType)settings.reordering, 0 );\n\n    // Node Count\n    if ( settings.node_count )\n    {\n      *settings.node_count = Cudd_ReadNodeCount( bdd.cudd );\n    }\n\n    // statistics about the BDD\n    if ( settings.infofilename.size() )\n    {\n      FILE *fp = 0;\n      fp = fopen( settings.infofilename.c_str(), \"w\" );\n      Cudd_PrintInfo( bdd.cudd, fp );\n      fclose( fp );\n    }\n\n    // complemented edges\n    if ( !settings.complemented_edges )\n    {\n      for ( unsigned i = 0; i < bdd.outputs.size(); ++i )\n      {\n        DdNode *tmp = Cudd_BddToAdd( bdd.cudd, bdd.outputs[i].second );\n        Cudd_Ref( tmp );\n        Cudd_RecursiveDeref( bdd.cudd, bdd.outputs[i].second );\n        bdd.outputs[i].second = tmp;\n      }\n    }\n\n    using boost::adaptors::map_keys;\n    using boost::adaptors::map_values;\n\n    std::vector<DdNode*> nodes;\n    boost::push_back( nodes, bdd.outputs | map_values );\n\n    boost::push_back( get_property( graph, boost::graph_name ).labels, bdd.inputs | map_keys );\n    boost::push_back( get_property( graph, boost::graph_name ).labels, bdd.outputs | map_keys );\n\n    get_property( graph, boost::graph_name ).ninputs = bdd.inputs.size();\n\n    dd_from_bdd( graph, nodes );\n  }\n\n  void dd_from_bdd( dd& graph, bdd_function_t& bdds, const dd_from_bdd_settings& settings )\n  {\n    bdds.first.ReduceHeap( (Cudd_ReorderingType)settings.reordering, 0 );\n\n    if ( settings.node_count )\n    {\n      *settings.node_count = bdds.first.ReadNodeCount();\n    }\n\n    std::vector<DdNode*> nodes;\n    nodes.reserve( bdds.second.size() );\n    std::vector<ADD>     adds;\n\n    if ( settings.complemented_edges )\n    {\n      for ( const auto& f : bdds.second )\n      {\n        nodes.push_back( f.getNode() );\n      }\n    }\n    else\n    {\n      for ( const auto& f : bdds.second )\n      {\n        adds.push_back( f.Add() );\n        nodes.push_back( adds.back().getNode() );\n      }\n    }\n\n    /* I/O */\n    auto& info = get_property( graph, boost::graph_name );\n    for ( auto i = 0; i < bdds.first.ReadSize(); ++i )\n    {\n      info.labels.push_back( boost::str( boost::format( \"i%d\" ) % i ) );\n    }\n\n    for ( auto i = 0u; i < bdds.second.size(); ++i )\n    {\n      info.labels.push_back( boost::str( boost::format( \"o%d\" ) % i ) );\n    }\n\n    info.ninputs = bdds.first.ReadSize();\n\n    dd_from_bdd( graph, nodes );\n  }\n\n  ////////////////////////////////////////////////////////////////////////////////\n  // DD Synthesis                                                               //\n  ////////////////////////////////////////////////////////////////////////////////\n  struct data\n  {\n    unsigned lines;\n\n    std::vector<int> constantValue;\n    std::vector<int> lineNeeded;\n    std::map<dd_node, unsigned> node2line;\n\n    unsigned up( unsigned cv )\n    {\n      unsigned ret = lines++;\n      lineNeeded += -1;\n      constantValue += cv;\n      return ret;\n    }\n  };\n\n  int reversible_generator( circuit& circ, data& d, unsigned index, unsigned dtl, int low, int high, bool low_complemented, bool high_complemented )\n  {\n    if ( low >= 0 && high >= 0 )\n    {\n      if ( low == high ) // ll case\n      {\n        switch ( dtl )\n        {\n        case 0:\n          if ( high_complemented )\n          {\n            if ( d.lineNeeded[high] )\n            {\n              unsigned tmpLine = d.up( 0 );\n\n              append_cnot( circ, index, tmpLine );\n              append_cnot( circ, low, tmpLine );\n\n              return tmpLine;\n            }\n            else\n            {\n              append_cnot( circ, index, low );\n\n              return low;\n            }\n          }\n          else if ( low_complemented )\n          {\n            if ( d.lineNeeded[high] )\n            {\n              unsigned tmpLine = d.up( 1 );\n\n              append_cnot( circ, index, tmpLine );\n              append_cnot( circ, low, tmpLine );\n\n              return tmpLine;\n            }\n            else\n            {\n              append_cnot( circ, index, low );\n              append_not( circ, low );\n\n              return low;\n            }\n          }\n          break;\n\n        case 1:\n          if ( high_complemented )\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_toffoli( circ )( index, low )( tmpLine );\n            append_cnot( circ, index, tmpLine );\n            append_cnot( circ, low, tmpLine );\n\n            return tmpLine;\n          }\n          else if ( low_complemented )\n          {\n          }\n          else\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_toffoli( circ )( index, low )( tmpLine );\n            append_cnot( circ, low, tmpLine );\n\n            return tmpLine;\n          }\n          break;\n\n        case 2:\n          if ( high_complemented )\n          {\n            unsigned tmpLine = d.up( 1 );\n\n            append_toffoli( circ )( index, low )( tmpLine );\n            append_cnot( circ, index, tmpLine );\n\n            return tmpLine;\n          }\n          else if ( low_complemented )\n          {\n          }\n          else\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_toffoli( circ )( index, low )( tmpLine );\n\n            return tmpLine;\n          }\n          break;\n        }\n      }\n      else if ( d.lineNeeded[low] || d.lineNeeded[high] )\n      {\n        switch ( dtl )\n        {\n        case 0:\n          if ( high_complemented )\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_cnot( circ, index, tmpLine );\n            append_cnot( circ, low, tmpLine );\n            append_toffoli( circ )( index, high )( tmpLine );\n            append_toffoli( circ )( index, low )( tmpLine );\n\n            return tmpLine;\n          }\n          else if ( low_complemented )\n          {\n            unsigned tmpLine = d.up( 1 );\n\n            append_cnot( circ, index, tmpLine );\n            append_cnot( circ, low, tmpLine );\n            append_toffoli( circ )( index, high )( tmpLine );\n            append_toffoli( circ )( index, low )( tmpLine );\n\n            return tmpLine;\n          }\n          else\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_cnot( circ, low, tmpLine );\n            append_toffoli( circ )( index, high )( tmpLine );\n            append_toffoli( circ )( index, low )( tmpLine );\n\n            return tmpLine;\n          }\n          break;\n\n        case 1:\n          if ( high_complemented )\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_toffoli( circ )( index, high )( tmpLine );\n            append_cnot( circ, low, tmpLine );\n            append_cnot( circ, index, tmpLine );\n\n            return tmpLine;\n          }\n          else if ( low_complemented )\n          {\n          }\n          else\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_toffoli( circ )( index, high )( tmpLine );\n            append_cnot( circ, low, tmpLine );\n\n            return tmpLine;\n          }\n          break;\n\n        case 2:\n          if ( high_complemented )\n          {\n            unsigned tmpLine = d.up( 1 );\n\n            append_toffoli( circ )( index, high )( tmpLine );\n            append_cnot( circ, low, tmpLine );\n            append_cnot( circ, high, tmpLine );\n            append_cnot( circ, index, tmpLine );\n\n            return tmpLine;\n          }\n          else if ( low_complemented )\n          {\n          }\n          else\n          {\n            unsigned tmpLine = d.up( 0 );\n\n            append_toffoli( circ )( index, high )( tmpLine );\n            append_cnot( circ, low, tmpLine );\n            append_cnot( circ, high, tmpLine );\n\n            return tmpLine;\n          }\n          break;\n        }\n      }\n      else\n      {\n        switch ( dtl )\n        {\n        case 0:\n          if ( high_complemented )\n          {\n            append_toffoli( circ )( index, low )( high );\n            append_cnot( circ, index, low );\n            append_toffoli( circ )( high, index )( low );\n\n            return low;\n          }\n          else if ( low_complemented )\n          {\n            append_not( circ, low );\n            append_toffoli( circ )( low, index )( high );\n            append_toffoli( circ )( high, index )( low );\n\n            return low;\n          }\n          else\n          {\n            append_cnot( circ, low, high );\n            append_toffoli( circ )( high, index )( low );\n\n            return low;\n          }\n          break;\n\n        case 1:\n          if ( high_complemented )\n          {\n            append_toffoli( circ )( index, high )( low );\n            append_cnot( circ, index, low );\n\n            return low;\n          }\n          else if ( low_complemented )\n          {\n          }\n          else\n          {\n            append_toffoli( circ )( index, high )( low );\n\n            return low;\n          }\n          break;\n\n        case 2:\n          if ( high_complemented )\n          {\n            append_not( circ, high );\n            append_toffoli( circ )( index, high )( low );\n            append_cnot( circ, low, high );\n\n            return high;\n          }\n          else if ( low_complemented )\n          {\n          }\n          else\n          {\n            append_toffoli( circ )( index, high )( low );\n            append_cnot( circ, low, high );\n\n            return high;\n          }\n          break;\n        }\n      }\n    }\n    else if ( low == -1 && high >= 0 )\n    {\n      switch ( dtl )\n      {\n      case 0:\n        if ( high_complemented )\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_toffoli( circ )( index, high )( tmpLine );\n\n          return tmpLine;\n        }\n        else if ( low_complemented )\n        {\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_toffoli( circ )( index, high )( tmpLine );\n          append_cnot( circ, index, tmpLine );\n\n          return tmpLine;\n        }\n        break;\n\n      case 1:\n        if ( high_complemented )\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_toffoli( circ )( index, high )( tmpLine );\n          append_cnot( circ, index, tmpLine );\n\n          return tmpLine;\n        }\n        else if ( low_complemented )\n        {\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_toffoli( circ )( index, high )( tmpLine );\n\n          return tmpLine;\n        }\n        break;\n\n      case 2:\n        if ( high_complemented )\n        {\n          unsigned tmpLine = d.up( 0 );\n\n          append_toffoli( circ )( index, high )( tmpLine );\n          append_cnot( circ, high, tmpLine );\n          append_cnot( circ, index, tmpLine );\n\n          return tmpLine;\n        }\n        else if ( low_complemented )\n        {\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_toffoli( circ )( index, high )( tmpLine );\n          append_cnot( circ, high, tmpLine );\n\n          return tmpLine;\n        }\n      }\n    }\n    else if ( low == -2 && high >= 0 )\n    {\n      switch ( dtl )\n      {\n      case 0:\n        if ( high_complemented )\n        {\n        }\n        else if ( low_complemented )\n        {\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 0 );\n\n          append_toffoli( circ )( index, high )( tmpLine );\n\n          return tmpLine;\n        }\n        break;\n      }\n    }\n    else if ( low >= 0 && high == -1 )\n    {\n      switch ( dtl )\n      {\n      case 0:\n        if ( high_complemented )\n        {\n        }\n        else if ( low_complemented )\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_toffoli( circ )( low, index )( tmpLine );\n          append_cnot( circ, low, tmpLine );\n\n          return tmpLine;\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 0 );\n\n          append_cnot( circ, index, tmpLine );\n          append_toffoli( circ )( low, index )( tmpLine );\n          append_cnot( circ, low, tmpLine );\n\n          return tmpLine;\n        }\n        break;\n\n      case 1:\n        if ( high_complemented )\n        {\n        }\n        else if ( low_complemented )\n        {\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 0 );\n\n          append_cnot( circ, low, tmpLine );\n          append_cnot( circ, index, tmpLine );\n\n          return tmpLine;\n        }\n        break;\n\n      case 2:\n        if ( high_complemented )\n        {\n        }\n        if ( low_complemented )\n        {\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_cnot( circ, low, tmpLine );\n          append_cnot( circ, index, tmpLine );\n\n          return tmpLine;\n        }\n        break;\n      }\n    }\n    else if ( low >= 0 && high == -2 )\n    {\n      switch ( dtl )\n      {\n      case 0:\n        if ( high_complemented )\n        {\n        }\n        else if ( low_complemented )\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_cnot( circ, index, tmpLine );\n          append_toffoli( circ )( low, index )( tmpLine );\n          append_cnot( circ, low, tmpLine );\n\n          return tmpLine;\n        }\n        else\n        {\n          unsigned tmpLine = d.up( 0 );\n\n          append_toffoli( circ )( low, index )( tmpLine );\n          append_cnot( circ, low, tmpLine );\n\n          return tmpLine;\n        }\n        break;\n      }\n    }\n    else if ( low == -1 && high == -1 )\n    {\n      assert( dtl != 0 );\n      assert( !low_complemented && !high_complemented );\n\n      switch ( dtl )\n      {\n      case 1:\n        {\n          unsigned tmpLine = d.up( 1 );\n\n          append_cnot( circ, index, tmpLine );\n\n          return tmpLine;\n        }\n        break;\n\n      case 2:\n        return index;\n        break;\n      }\n    }\n    else if ( low == -1 && high == -2 )\n    {\n      assert( dtl == 0 );\n      unsigned tmpLine = d.up( 1 );\n\n      append_cnot( circ, index, tmpLine );\n\n      return tmpLine;\n    }\n    else if ( low == -2 && high == -1 )\n    {\n      return index;\n    }\n\n    std::cerr << \"Missing: index: \" << index << \" dtl: \" << dtl << \" low: \" << low << \" high: \" << high << \" low_complemented: \" << low_complemented << \" high_complemented: \" << high_complemented  << std::endl;\n\n    assert( false );\n\n    return -1;\n  }\n\n  int node2line( const dd_node& node, const dd& graph, bool is_complemented, data& d )\n  {\n    int line = -1;\n\n    if ( dd_node_is_constant( node, graph ) )\n    {\n      if ( is_complemented )\n      {\n        line = dd_node_var( node, graph ) == 1 ? -2 : -1;\n      }\n      else\n      {\n        line = dd_node_var( node, graph ) == 1 ? -1 : -2;\n      }\n    }\n    else\n    {\n      std::map<dd_node, unsigned>::const_iterator it = d.node2line.find( node );\n      assert( it != d.node2line.end() );\n      assert( d.lineNeeded[it->second] > 0 || it->second < get_property( graph, boost::graph_name ).ninputs );\n      line = it->second;\n      if ( line >= (int)get_property( graph, boost::graph_name ).ninputs )\n      {\n        --d.lineNeeded[line];\n      }\n    }\n\n    return line;\n  }\n\n  void dd_synthesis( circuit& circ, data& d, const dd_node& node, const dd& graph, boost::function<int(circuit&, data&, unsigned, unsigned short, int, int, bool, bool)> gate_inserter )\n  {\n\n    if ( dd_node_is_constant( node, graph ) )\n    {\n      // should only happen, if PO is constant\n      unsigned tmpLine = d.lines;\n      ++d.lines;\n      d.lineNeeded += -1;\n      d.constantValue += (int)dd_node_var( node, graph );\n      d.node2line.insert( std::make_pair( node, tmpLine ) );\n      return;\n    }\n\n    if ( d.node2line.find( node ) != d.node2line.end() )\n    {\n      // already visited\n      return;\n    }\n\n    // get low and high\n    bool low_complemented, high_complemented;\n    dd_node lowNode, highNode;\n\n    boost::graph_traits<dd>::out_edge_iterator itEdge = out_edges( node, graph ).first;\n    low_complemented = get( boost::edge_name, graph )[*itEdge].complemented;\n    lowNode = target( *itEdge, graph );\n    ++itEdge;\n    high_complemented = get( boost::edge_name, graph )[*itEdge].complemented;\n    highNode = target( *itEdge, graph );\n\n    if ( !dd_node_is_constant( highNode, graph ) )\n    {\n      dd_synthesis( circ, d, highNode, graph, gate_inserter );\n    }\n    if ( !dd_node_is_constant( lowNode, graph ) )\n    {\n      dd_synthesis( circ, d, lowNode, graph, gate_inserter );\n    }\n\n    unsigned index = dd_node_var( node, graph );\n    int high       = node2line( highNode, graph, high_complemented, d );\n    int low        = node2line( lowNode, graph, low_complemented, d );\n\n    if ( high < 0 )\n    {\n      high_complemented = false;\n    }\n    if ( low < 0 )\n    {\n      low_complemented = false;\n    }\n\n    unsigned short dtl = get( boost::vertex_name, graph )[node].dtl;\n    int out            = gate_inserter( circ, d, index, dtl, low, high, low_complemented, high_complemented );\n\n    assert( out != -1 );\n    d.node2line.insert( std::make_pair( node, out ) );\n    assert( (int)d.lineNeeded.size() > out );\n\n    d.lineNeeded[out] = in_degree( node, graph );\n\n  }\n\n  void dd_synthesis( circuit& circ, const dd& graph, boost::function<int(circuit&, data&, unsigned, unsigned short, int, int, bool, bool)> gate_inserter )\n  {\n    // empty circuit\n    clear_circuit( circ );\n\n    // get number of inputs\n    unsigned ninputs = get_property( graph, boost::graph_name ).ninputs;\n\n    data d;\n    d.lines = ninputs;\n    d.constantValue.resize( d.lines, -1 );\n    d.lineNeeded.resize( d.lines, -1 );\n\n    // recursion\n    for ( const unsigned& node_index : dd_roots( graph ) )\n    {\n      dd_synthesis( circ, d, node_index, graph, gate_inserter );\n    }\n\n    for ( const unsigned& node_index : dd_roots( graph ) )\n    {\n      if ( dd_root_is_complemented( node_index, graph ) )\n      {\n        append_not( circ, d.node2line[node_index] );\n      }\n    }\n\n    circ.set_lines( d.lines );\n\n    // set inputs and constants\n    std::vector<std::string> inputs( d.lines );\n    std::vector<constant> constants( d.lines, constant() );\n    std::copy( dd_labels( graph ).begin(), dd_labels( graph ).begin() + ninputs, inputs.begin() );\n    std::transform( d.constantValue.begin() + ninputs, d.constantValue.end(), inputs.begin() + ninputs, []( int n ) { return boost::lexical_cast<std::string>( n ); } );\n    std::transform( d.constantValue.begin() + ninputs, d.constantValue.end(), constants.begin() + ninputs, []( int n ) { return boost::lexical_cast<bool>( n ); } );\n    circ.set_inputs( inputs );\n    circ.set_constants( constants );\n\n    // set outputs and garbage\n    std::vector<std::string> outputs( d.lines, \"g\" );\n    std::vector<bool> garbage( d.lines, true );\n    for ( const unsigned& node_index : dd_roots( graph ) )\n    {\n      unsigned index = d.node2line[node_index];\n      outputs[index] = dd_labels( graph ).at( get( boost::vertex_name, graph )[dd_root_get_function_root( node_index, graph )].var );\n      garbage[index] = false;\n    }\n    circ.set_outputs( outputs );\n    circ.set_garbage( garbage );\n\n  }\n\n  void dd_synthesis( circuit& circ, const dd& graph )\n  {\n    dd_synthesis( circ, graph, &reversible_generator );\n  }\n\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": "169871f13748ffe68709536b551fa0522c98aaaf", "size": 34346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/dd_synthesis_p.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/dd_synthesis_p.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/dd_synthesis_p.cpp", "max_forks_repo_name": "eletesta/cirkit", "max_forks_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1986863711, "max_line_length": 210, "alphanum_fraction": 0.5541838933, "num_tokens": 8895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.02800752080881603, "lm_q1q2_score": 0.008240231955120136}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_ParticleSimulationManager_def.hpp\n//! \\author Alex Robinson\n//! \\brief  The particle simulation manager class definition.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef FACEMC_PARTICLE_SIMULATION_MANAGER_DEF_HPP\n#define FACEMC_PARTICLE_SIMULATION_MANAGER_DEF_HPP\n\n// Boost Includes\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_ParticleBank.hpp\"\n#include \"MonteCarlo_SourceModuleInterface.hpp\"\n#include \"MonteCarlo_EstimatorModuleInterface.hpp\"\n#include \"MonteCarlo_CollisionModuleInterface.hpp\"\n#include \"MonteCarlo_SimulationGeneralProperties.hpp\"\n#include \"MonteCarlo_SimulationNeutronProperties.hpp\"\n#include \"MonteCarlo_SimulationElectronProperties.hpp\"\n#include \"MonteCarlo_SimulationPhotonProperties.hpp\"\n#include \"Geometry_ModuleInterface.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_ContractException.hpp\"\n#include \"Utility_GlobalOpenMPSession.hpp\"\n#include \"MonteCarlo_ElectronState.hpp\"\n#include \"MonteCarlo_PhotonState.hpp\"\n#include \"MonteCarlo_NeutronState.hpp\"\n\n\n\nnamespace MonteCarlo{\n\n// Constructor for multiple threads\n/*! \\details If OpenMP is not being used, the number of threads requested will\n * be ignored.\n */\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nParticleSimulationManager<GeometryHandler,\n\t\t\t  SourceHandler,\n\t\t\t  EstimatorHandler,\n\t\t\t  CollisionHandler>::ParticleSimulationManager( \n\t\t       const unsigned long long number_of_histories,\n\t\t       const unsigned long long start_history,\n\t\t       const unsigned long long previously_completed_histories,\n\t\t       const double previous_run_time )\n  : d_start_history( start_history ),\n    d_history_number_wall( start_history + number_of_histories ),\n    d_histories_completed( previously_completed_histories ),\n    d_end_simulation( false ),\n    d_previous_run_time( previous_run_time ),\n    d_start_time( 0.0 ),\n    d_end_time( 0.0 )\n{\n  // At least one history must be simulated\n  testPrecondition( number_of_histories > 0 );\n\n  // Assign the functions based on the mode\n  ParticleModeType mode = SimulationGeneralProperties::getParticleMode();\n  \n  switch( mode )\n  {\n  case NEUTRON_MODE:\n  {\n    d_simulate_neutron = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::simulateParticle<NeutronState>,\n\t\t\t\t\t    boost::cref( *this ),\n\t\t\t\t\t    _1,\n\t\t\t\t\t    _2 );\n    d_simulate_photon = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::ignoreParticle<PhotonState>,\n\t\t\t\t\t    boost::cref( *this ),\n\t\t\t\t\t    _1,\n\t\t\t\t\t    _2 );\n    d_simulate_electron = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::ignoreParticle<ElectronState>,\n\t\t\t\t\t    boost::cref( *this ),\n\t\t\t\t\t    _1,\n\t\t\t\t\t    _2 );\t\t   \n    break;\n  }\n  case PHOTON_MODE:\n  {\n    d_simulate_photon = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::simulateParticle<PhotonState>,\n\t\t\t\t\t    boost::cref( *this ),\n\t\t\t\t\t    _1,\n\t\t\t\t\t    _2 );\n    d_simulate_neutron = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::ignoreParticle<NeutronState>,\n\t\t\t\t\t    boost::cref( *this ),\n\t\t\t\t\t    _1,\n\t\t\t\t\t    _2 );\n    d_simulate_electron = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::ignoreParticle<ElectronState>,\n\t\t\t\t\t    boost::cref( *this ),\n\t\t\t\t\t    _1,\n\t\t\t\t\t    _2 );\n    break;\n  }\n  case ELECTRON_MODE:\n  {\n    d_simulate_electron = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::simulateParticle<ElectronState>,\n\t\t\t\t\t     boost::cref( *this ),\n\t\t\t\t\t     _1,\n\t\t\t\t\t     _2 );\n    d_simulate_neutron = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::ignoreParticle<NeutronState>,\n\t\t\t\t\t    boost::cref( *this ),\n\t\t\t\t\t    _1,\n\t\t\t\t\t    _2 );\n    d_simulate_photon = boost::bind<void>( &ParticleSimulationManager<GeometryHandler,SourceHandler,EstimatorHandler,CollisionHandler>::ignoreParticle<PhotonState>,\n\t\t\t\t\t   boost::cref( *this ),\n\t\t\t\t\t   _1,\n\t\t\t\t\t   _2 );\n    break;\n  }\n  default:\n    THROW_EXCEPTION( std::runtime_error,\n\t\t     \"Error: particle mode \" << mode << \" is not currently \"\n\t\t     << \"supported by the particle simulation manager.\" );\n  }\n}\n\n// Run the simulation set up by the user\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::runSimulation()\n{\n  std::cout << \"Starting simulation ... \";\n  std::cout.flush();\n  \n  // Set up the random number generator for the number of threads requested\n  Utility::RandomNumberGenerator::createStreams();\n\n  // Enable geometry thread support\n  GMI::enableThreadSupport(\n\t         Utility::GlobalOpenMPSession::getRequestedNumberOfThreads() );\n  \n  // Enable estimator thread support\n  EMI::enableThreadSupport( \n\t\t Utility::GlobalOpenMPSession::getRequestedNumberOfThreads() );\n  \n  // Set the start time\n  this->setStartTime( Utility::GlobalOpenMPSession::getTime() );\n\n  // Simulate the batch\n  this->runSimulationBatch( d_start_history, d_history_number_wall );\n    \n  // Set the end time\n  this->setEndTime( Utility::GlobalOpenMPSession::getTime() );\n\n  std::cout << \"done.\" << std::endl;\n}\n\n// Run the simulation batch\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::runSimulationBatch( \n                            const unsigned long long batch_start_history, \n\t\t\t    const unsigned long long batch_end_history )\n{\n  // Make sure the history range is valid\n  testPrecondition( batch_start_history <= batch_end_history );\n  testPrecondition( batch_start_history >= d_start_history );\n  testPrecondition( batch_end_history <= d_history_number_wall );\n  \n  #pragma omp parallel num_threads( Utility::GlobalOpenMPSession::getRequestedNumberOfThreads() )\n  { \n    // Create a bank for each thread\n    ParticleBank bank;\n\n    #pragma omp for\n    for( unsigned long long history = batch_start_history; history < batch_end_history; ++history )\n    {\n      // Do useful work unless the user requests an end to the simulation\n      #pragma omp flush( d_end_simulation )\n      if( !d_end_simulation )\n      {\n\t// Initialize the random number generator for this history\n\tUtility::RandomNumberGenerator::initialize( history );\n\t\n\t// Sample a particle state from the source\n\tSMI::sampleParticleState( bank, history );\n\t\n\t// Determine the starting cell of the particle\n\tfor( unsigned i = 0; i < bank.size(); ++i )\n\t{\n\t  typename GMI::InternalCellHandle start_cell;\n\t  \n\t  try{\n\t    start_cell = GMI::findCellContainingPoint( bank.top().ray() );\n\t  }\n\t  CATCH_LOST_SOURCE_PARTICLE_AND_CONTINUE( bank );\n\t  \n\t  bank.top().setCell( start_cell );\n\t  \n\t  EMI::updateEstimatorsFromParticleGenerationEvent( bank.top() );\n\t}\n\t\n\t// This history only ends when the particle bank is empty\n\twhile( bank.size() > 0 )\n\t{\n\t  switch( bank.top().getParticleType() )\n\t  {\n\t  case NEUTRON: \n\t    d_simulate_neutron( dynamic_cast<NeutronState&>( bank.top() ),\n\t\t\t\tbank );\n\t    break;\n\t  case PHOTON:\n\t    d_simulate_photon( dynamic_cast<PhotonState&>( bank.top() ),\n\t\t\t       bank );\n\t    break;\n\t  case ELECTRON:\n\t    d_simulate_electron( dynamic_cast<ElectronState&>( bank.top() ),\n\t    \t\t\t bank );\n\t    break;\n\t  default:\n\t    THROW_EXCEPTION( std::logic_error,\n\t\t\t     \"Error: particle type \"\n\t\t\t     << bank.top().getParticleType() <<\n\t\t\t     \" is not currently supported!\" );\n\t  }\n  \n\tbank.pop();\n\t}\n\t\n\t// Commit all estimator history contributions\n\tEMI::commitEstimatorHistoryContributions();\n        \n\t// Increment the number of histories completed\n        #pragma omp atomic\n\t++d_histories_completed;\n      }\n    }\n  }\n}\n\n// Set the number of particle histories to simulate\ntemplate<typename GeometryHandler,\n         typename SourceHandler,\n         typename EstimatorHandler,\n         typename CollisionHandler>\ntemplate<typename ParticleStateType>\nvoid ParticleSimulationManager<GeometryHandler,\n                               SourceHandler,\n                               EstimatorHandler,\n                               CollisionHandler>::simulateParticle( \n                                                   ParticleStateType& particle,\n\t\t\t\t\t\t   ParticleBank& bank ) const\n{\n  // Particle tracking information\n  double distance_to_surface_hit, op_to_surface_hit, remaining_subtrack_op;\n  double subtrack_start_time;\n  double ray_start_point[3];\n  \n  // Cache the start point of the ray\n  ray_start_point[0] = particle.getXPosition();\n  ray_start_point[1] = particle.getYPosition();\n  ray_start_point[2] = particle.getZPosition();\n\n  // Surface information\n  typename GMI::InternalSurfaceHandle surface_hit;\n  Teuchos::Array<double> surface_normal( 3 );\n\n  // Cell information\n  typename GMI::InternalCellHandle cell_entering, cell_leaving;\n  double cell_total_macro_cross_section;\n\n  // Check if the particle energy is below the cutoff\n  if( particle.getEnergy() < SimulationGeneralProperties::getMinParticleEnergy<ParticleStateType>() )\n    particle.setAsGone();\n  \n  while( !particle.isLost() && !particle.isGone() )\n  {\n    // Sample the mfp traveled by the particle on this subtrack\n    remaining_subtrack_op = CMI::sampleOpticalPathLength();\n    \n    // Ray trace until the necessary number of optical paths have be traveled\n    while( true )\n    {\n      // Fire a ray at the cell currently containing the particle\n      try{\n  \tdistance_to_surface_hit = 0.0;\n\t\n  \tGMI::fireRay( particle.ray(),\n  \t\t      particle.getCell(),\n  \t\t      surface_hit,\n  \t\t      distance_to_surface_hit );\n      }\n      CATCH_LOST_PARTICLE_AND_BREAK( particle );\n\n      // Get the total cross section for the cell\n      if( !CMI::isCellVoid( particle.getCell(), particle.getParticleType() ) )\n      {\n      \tcell_total_macro_cross_section = \n      \t  CMI::getMacroscopicTotalCrossSection( particle );\n      }\n      else\n  \tcell_total_macro_cross_section = 0.0;\n\n      // Convert the distance to the surface to optical path\n      op_to_surface_hit = \n  \tdistance_to_surface_hit*cell_total_macro_cross_section;\n\n      // Get the start time of this subtrack\n      subtrack_start_time = particle.getTime();\n\n      if( op_to_surface_hit < remaining_subtrack_op )\n      {\n  \t// Advance the particle to the cell boundary\n  \tparticle.advance( distance_to_surface_hit );\n\n  \t// Get the surface normal at the intersection point\n  \tGMI::getSurfaceNormal( surface_hit,\n  \t\t\t       particle.getPosition(),\n  \t\t\t       surface_normal.getRawPtr() );\t\t       \n\n  \tcell_leaving = particle.getCell();\n\t\n  \t// Find the cell on the other side of the surface hit\n  \ttry{\n  \t  cell_entering = GMI::findCellContainingPoint( particle.ray(),\n  \t\t\t\t\t\t\tcell_leaving,\n  \t\t\t\t\t\t\tsurface_hit );\n  \t}\n  \tCATCH_LOST_PARTICLE_AND_BREAK( particle );\n\n  \tparticle.setCell( cell_entering );\n\n  \t// Update estimators\n  \tEMI::updateEstimatorsFromParticleCrossingSurfaceEvent(\n  \t\t\t\t\t\t  particle,\n  \t\t\t\t\t\t  cell_entering,\n  \t\t\t\t\t\t  cell_leaving,\n  \t\t\t\t\t\t  surface_hit,\n  \t\t\t\t\t\t  distance_to_surface_hit,\n  \t\t\t\t\t\t  subtrack_start_time,\n  \t\t\t\t\t\t  surface_normal.getRawPtr() );\n\n  \t// Check if a termination cell was encountered\n  \tif( GMI::isTerminationCell( particle.getCell() ) )\n  \t{\n  \t  particle.setAsGone();\n\n  \t  break;\n  \t}\n\n  \t// Update the remaining subtrack mfp\n  \tremaining_subtrack_op -= op_to_surface_hit;\n      } \n      \n      // A collision occurs in this cell\n      else\n      {\n  \t// Advance the particle to the collision site\n  \tdouble distance = remaining_subtrack_op/cell_total_macro_cross_section;\n\t\n  \tparticle.advance( distance );\n\t\n  \t// Update estimators\n  \tEMI::updateEstimatorsFromParticleCollidingInCellEvent(\n  \t\t\t\t\t  particle,\n  \t\t\t\t\t  distance,\n  \t\t\t\t\t  subtrack_start_time,\n  \t\t\t\t\t  1.0/cell_total_macro_cross_section );\n\n\t\n\n  \tEMI::updateEstimatorsFromParticleCollidingGlobalEvent(\n  \t\t\t\t\t\t      particle,\n  \t\t\t\t\t\t      ray_start_point,\n  \t\t\t\t\t\t      particle.getPosition() );\n\n  \t// Undergo a collision with the material in the cell\n  \tCMI::collideWithCellMaterial( particle, bank, true );\n\n  \t// Indicate that a collision has occurred\n  \tGMI::newRay();\n\n  \t// Cache the current position of the new ray\n  \tray_start_point[0] = particle.getXPosition();\n  \tray_start_point[1] = particle.getYPosition();\n  \tray_start_point[2] = particle.getZPosition();\n\n  \t// Make sure the energy is above the cutoff\n  \tif( particle.getEnergy() < SimulationGeneralProperties::getMinParticleEnergy<ParticleStateType>() )\n  \t  particle.setAsGone();\n\n  \t// This subtrack is finished\n  \tbreak;\n      }\n    }\t     \n  }\n\n  // Update the global estimators\n  EMI::updateEstimatorsFromParticleCollidingGlobalEvent(\n  \t\t\t\t\t\t      particle,\n  \t\t\t\t\t\t      ray_start_point,\n  \t\t\t\t\t\t      particle.getPosition() );\n\n  // Indicate that this particle history is complete\n  GMI::newRay();\n}\n\n// Return the number of histories\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nunsigned long long  ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::getNumberOfHistories() const\n{\n  return d_history_number_wall - d_start_history;\n}\n\n// Return the number of histories completed\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nunsigned long long  ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::getNumberOfHistoriesCompleted() const\n{\n  return d_histories_completed;\n}\n\n// Increment the number of histories completed\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::incrementHistoriesCompleted( \n\t\t\t\t\t   const unsigned long long histories )\n{\n  d_histories_completed += histories;\n}\n\n// Set the number of histories completed\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::setHistoriesCompleted( \n\t\t\t\t\t   const unsigned long long histories )\n{\n  d_histories_completed = histories;\n}\n\n// Set the start time\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::setStartTime( const double start_time )\n{\n  d_start_time = start_time;\n}\n  \n// Set the end time\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::setEndTime( const double end_time )\n{\n  // Make sure the end time is valid\n  testPrecondition( end_time >= d_start_time );\n  \n  d_end_time = end_time;\n}\n\n// Set the number of particle histories to simulate\ntemplate<typename GeometryHandler,\n         typename SourceHandler,\n         typename EstimatorHandler,\n         typename CollisionHandler>\ntemplate<typename ParticleStateType>\nvoid ParticleSimulationManager<GeometryHandler,\n                               SourceHandler,\n                               EstimatorHandler,\n                               CollisionHandler>::ignoreParticle( \n                                                   ParticleStateType& particle,\n\t\t\t\t\t\t   ParticleBank& bank ) const\n{\n  particle.setAsGone();\n}\n\n// Print the data in all estimators to the desired stream\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::printSimulationSummary( \n\t\t\t\t\t\t       std::ostream &os ) const\n{\n  os << \"!!!Particle Simulation Finished!!!\" << std::endl;\n  os << \"Number of histories completed: \" << d_histories_completed <<std::endl;\n  os << \"Simulation Time (s): \" << d_end_time - d_start_time << std::endl;\n  os << \"Previous Simulation Time (s): \" << d_previous_run_time << std::endl;\n  os << std::endl;\n  \n  EMI::printEstimators( os,\n\t\t\td_histories_completed,\n\t\t\td_start_time,\n\t\t\td_end_time+d_previous_run_time );\n}\n\n// Print the data in all estimators to a parameter list\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::exportSimulationData(\n\t\t\t\t      const std::string& data_file_name ) const\n{\n  std::cout << \"Exporting simulation data ... \";\n  std::cout.flush();\n  \n  EMI::exportEstimatorData( data_file_name,\n  \t\t\t    d_start_history+d_histories_completed,\n  \t\t\t    d_histories_completed,\n  \t\t\t    d_start_time,\n  \t\t\t    d_end_time+d_previous_run_time,\n\t\t\t    true );\n\n  std::cout << \"done.\" << std::endl;\n}\n\n// Signal handler\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::signalHandler(int signal)\n{\n  // Ask the user what to do\n  std::cerr << \" Status (s), End (e), Kill (k)\" << std::endl;\n  std::string option;\n  std::cin >> option;\n  \n  if( option.compare( \"s\" ) == 0 )\n  {\n    printSimulationStateInfo();\n  }\n  else if( option.compare( \"e\" ) == 0 )\n  {\n    d_end_simulation = true;\n  }\n  else if( option.compare( \"k\" ) == 0 )\n  {\n    exit(0);\n  }\n}\n\n// Print simulation state info in collision handler\ntemplate<typename GeometryHandler,\n\t typename SourceHandler,\n\t typename EstimatorHandler,\n\t typename CollisionHandler>\nvoid ParticleSimulationManager<GeometryHandler,\n\t\t\t       SourceHandler,\n\t\t\t       EstimatorHandler,\n\t\t\t       CollisionHandler>::printSimulationStateInfo()\n{\n  double time = Utility::GlobalOpenMPSession::getTime();\n  \n  #pragma omp critical( ostream_update )\n  {\n    #pragma omp flush( d_histories_completed )\n    std::cerr << \" History: \" << d_histories_completed\n\t      << \" Run Time: \" << time - d_start_time\n\t      << std::endl;\n  }\n}\n\n} // end MonteCarlo namespace\n\n#endif // end FACEMC_PARTICLE_SIMULATION_MANAGER_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_ParticleSimulationManager_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "150506298b9b6cbaf3cc4e4c5bd4bb97a8ea8f0f", "size": 19484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/manager/src/MonteCarlo_ParticleSimulationManager_def.hpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/monte_carlo/manager/src/MonteCarlo_ParticleSimulationManager_def.hpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/monte_carlo/manager/src/MonteCarlo_ParticleSimulationManager_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": 31.5786061588, "max_line_length": 170, "alphanum_fraction": 0.690002053, "num_tokens": 4292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.03358950613381431, "lm_q1q2_score": 0.00823228455191576}}
{"text": "// 2019 Team AobaZero\n// This is a work derived from Leela Zero (May 1, 2019).\n/*\n    This file is part of Leela Zero.\n    Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors\n\n    Leela Zero 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    Leela Zero 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 Leela Zero.  If not, see <http://www.gnu.org/licenses/>.\n\n    Additional permission under GNU GPL version 3 section 7\n\n    If you modify this Program, or any covered work, by linking or\n    combining it with NVIDIA Corporation's libraries from the\n    NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural\n    Network library and/or the NVIDIA TensorRT inference library\n    (or a modified version of those libraries), containing parts covered\n    by the terms of the respective license agreement, the licensors of\n    this Program grant you additional permission to convey the resulting\n    work.\n*/\n\n#include \"config.h\"\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <cmath>\n#include <iterator>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <boost/utility.hpp>\n#include <boost/format.hpp>\n#include <boost/spirit/home/x3.hpp>\n#ifndef USE_BLAS\n#include <Eigen/Dense>\n#endif\n\n#ifdef __APPLE__\n#include <Accelerate/Accelerate.h>\n#endif\n#ifdef USE_MKL\n#include <mkl.h>\n#endif\n#ifdef USE_OPENBLAS\n#include <cblas.h>\n#endif\n#include \"zlib.h\"\n\n#include \"Network.h\"\n#include \"CPUPipe.h\"\n#ifdef USE_OPENCL\n#include \"OpenCLScheduler.h\"\n#include \"UCTNode.h\"\n#endif\n#include \"FastBoard.h\"\n#include \"FastState.h\"\n#include \"FullBoard.h\"\n#include \"GameState.h\"\n#include \"GTP.h\"\n#include \"NNCache.h\"\n#include \"Random.h\"\n#include \"ThreadPool.h\"\n#include \"Timing.h\"\n#include \"Utils.h\"\n\nnamespace x3 = boost::spirit::x3;\nusing namespace Utils;\n\n\n#ifndef USE_BLAS\n// Eigen helpers\ntemplate <typename T>\nusing EigenVectorMap =\n    Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>>;\ntemplate <typename T>\nusing ConstEigenVectorMap =\n    Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>>;\ntemplate <typename T>\nusing ConstEigenMatrixMap =\n    Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>;\n#endif\n/*\n// Symmetry helper\nstatic std::array<std::array<int, NUM_INTERSECTIONS>,\n                  Network::NUM_SYMMETRIES> symmetry_nn_idx_table;\n*/\nfloat Network::benchmark_time(int /*centiseconds*/) {\n#if 0\n    const auto cpus = cfg_num_threads;\n    ThreadGroup tg(thread_pool);\n    std::atomic<int> runcount{0};\n\n    GameState state;\n    state.init_game(BOARD_SIZE, KOMI);\n\n    // As a sanity run, try one run with self check.\n    // Isn't enough to guarantee correctness but better than nothing,\n    // plus for large nets self-check takes a while (1~3 eval per second)\n    get_output(&state, Ensemble::RANDOM_SYMMETRY, -1, false, true, true);\n\n    const Time start;\n    for (auto i = size_t{0}; i < cpus; i++) {\n        tg.add_task([this, &runcount, start, centiseconds, state]() {\n            while (true) {\n                runcount++;\n                get_output(&state, Ensemble::RANDOM_SYMMETRY, -1, false);\n                const Time end;\n                const auto elapsed = Time::timediff_centis(start, end);\n                if (elapsed >= centiseconds) {\n                    break;\n                }\n            }\n        });\n    }\n    tg.wait_all();\n\n    const Time end;\n    const auto elapsed = Time::timediff_centis(start, end);\n    return 100.0f * runcount.load() / elapsed;\n#endif\n\treturn 0;\n}\n\nvoid Network::benchmark(const GameState* const /*state*/, const int /*iterations*/) {\n#if 0\n    const auto cpus = cfg_num_threads;\n    const Time start;\n\n    ThreadGroup tg(thread_pool);\n    std::atomic<int> runcount{0};\n\n    for (auto i = size_t{0}; i < cpus; i++) {\n        tg.add_task([this, &runcount, iterations, state]() {\n            while (runcount < iterations) {\n                runcount++;\n                get_output(state, Ensemble::RANDOM_SYMMETRY, -1, false);\n            }\n        });\n    }\n    tg.wait_all();\n\n    const Time end;\n    const auto elapsed = Time::timediff_seconds(start, end);\n    myprintf(\"%5d evaluations in %5.2f seconds -> %d n/s\\n\",\n             runcount.load(), elapsed, int(runcount.load() / elapsed));\n#endif\n}\n\ntemplate<class container>\nvoid process_bn_var(container& weights) {\n    constexpr float epsilon = 1e-5f;\n    for (auto&& w : weights) {\n        w = 1.0f / std::sqrt(w + epsilon);\n    }\n}\ntemplate<class container>\nvoid modify_bn_scale_factor(container& weights) {\n\tconst float scale_factor = 1.0f / 999.982f;\n    for(auto&& w : weights) {\n        w = w * scale_factor;\n    }\n}\n\nstd::vector<float> Network::winograd_transform_f(const std::vector<float>& f,\n                                                 const int outputs,\n                                                 const int channels) {\n    // F(4x4, 3x3) Winograd filter transformation\n    // transpose(G.dot(f).dot(G.transpose()))\n    // U matrix is transposed for better memory layout in SGEMM\n    auto U = std::vector<float>(WINOGRAD_TILE * outputs * channels);\n    const auto G = std::array<float, 3 * WINOGRAD_ALPHA>\n                    { 1.0f,        0.0f,      0.0f,\n                      -2.0f/3.0f, -SQ2/3.0f, -1.0f/3.0f,\n                      -2.0f/3.0f,  SQ2/3.0f, -1.0f/3.0f,\n                      1.0f/6.0f,   SQ2/6.0f,  1.0f/3.0f,\n                      1.0f/6.0f,  -SQ2/6.0f,  1.0f/3.0f,\n                      0.0f,        0.0f,      1.0f};\n\n    auto temp = std::array<float, 3 * WINOGRAD_ALPHA>{};\n\n    constexpr auto max_buffersize = 8;\n    auto buffersize = max_buffersize;\n\n    if (outputs % buffersize != 0) {\n        buffersize = 1;\n    }\n\n    std::array<float, max_buffersize * WINOGRAD_ALPHA * WINOGRAD_ALPHA> buffer;\n\n    for (auto c = 0; c < channels; c++) {\n        for (auto o_b = 0; o_b < outputs/buffersize; o_b++) {\n            for (auto bufferline = 0; bufferline < buffersize; bufferline++) {\n                const auto o = o_b * buffersize + bufferline;\n\n                for (auto i = 0; i < WINOGRAD_ALPHA; i++) {\n                    for (auto j = 0; j < 3; j++) {\n                        auto acc = 0.0f;\n                        for (auto k = 0; k < 3; k++) {\n                            acc += G[i*3 + k] * f[o*channels*9 + c*9 + k*3 + j];\n                        }\n                        temp[i*3 + j] = acc;\n                    }\n                }\n\n                for (auto xi = 0; xi < WINOGRAD_ALPHA; xi++) {\n                    for (auto nu = 0; nu < WINOGRAD_ALPHA; nu++) {\n                        auto acc = 0.0f;\n                        for (auto k = 0; k < 3; k++) {\n                            acc += temp[xi*3 + k] * G[nu*3 + k];\n                        }\n                        buffer[(xi * WINOGRAD_ALPHA + nu) * buffersize + bufferline] = acc;\n                    }\n                }\n            }\n            for (auto i = 0; i < WINOGRAD_ALPHA * WINOGRAD_ALPHA; i++) {\n                for (auto entry = 0; entry < buffersize; entry++) {\n                    const auto o = o_b * buffersize + entry;\n                    U[i * outputs * channels\n                      + c * outputs\n                      + o] =\n                    buffer[buffersize * i + entry];\n                }\n            }\n        }\n    }\n\n    return U;\n}\n\nstd::pair<int, int> Network::load_v1_network(std::istream& wtfile) {\n    // Count size of the network\n    myprintf(\"Detecting residual layers...\");\n\n    // We are version 1 or 2\n    if (m_value_head_not_stm) {\n        myprintf(\"v%d...\", 2);\n    } else {\n        myprintf(\"v%d...\", 1);\n    }\n\n    // First line was the version number\n    auto linecount = size_t{1};\n    auto channels = 0;\n    auto line = std::string{};\n    while (std::getline(wtfile, line)) {\n        auto iss = std::stringstream{line};\n        // Third line of parameters are the convolution layer biases,\n        // so this tells us the amount of channels in the residual layers.\n        // We are assuming all layers have the same amount of filters.\n        if (linecount == 2) {\n            auto count = std::distance(std::istream_iterator<std::string>(iss),\n                                       std::istream_iterator<std::string>());\n            myprintf(\"%d channels...\", count);\n            channels = count;\n        }\n        linecount++;\n    }\n    // 1 format id, 1 input layer (4 x weights), 14 ending weights,\n    // the rest are residuals, every residual has 8 x weight lines\n    auto residual_blocks = linecount - (1 + 4 + 14);\n    if (residual_blocks % 8 != 0) {\n        myprintf(\"\\nInconsistent number of weights in the file.\\n\");\n        return {0, 0};\n    }\n\tmyprintf(\"linecount=%d...\",linecount);\n    residual_blocks /= 8;\n    myprintf(\"%d blocks.\\n\", residual_blocks);\n\n    // Re-read file and process\n    wtfile.clear();\n    wtfile.seekg(0, std::ios::beg);\n\n    // Get the file format id out of the way\n    std::getline(wtfile, line);\n\n    const auto plain_conv_layers = 1 + (residual_blocks * 2);\n    const auto plain_conv_wts = plain_conv_layers * 4;\n    linecount = 0;\n    int num = 0;\n    while (std::getline(wtfile, line)) {\n        std::vector<float> weights;\n        auto it_line = line.cbegin();\n        const auto ok = phrase_parse(it_line, line.cend(),\n                                     *x3::float_, x3::space, weights);\n        num += weights.size();\n        if (!ok || it_line != line.cend()) {\n            myprintf(\"\\nFailed to parse weight file. Error on line %d.\\n\",\n                    linecount + 2); //+1 from version line, +1 from 0-indexing\n            return {0, 0};\n        }\n        if (linecount < plain_conv_wts) {\n            if (linecount % 4 == 0) {\n                m_fwd_weights->m_conv_weights.emplace_back(weights);\n            } else if (linecount % 4 == 1) {\n                // Redundant in our model, but they encode the\n                // number of outputs so we have to read them in.\n                m_fwd_weights->m_conv_biases.emplace_back(weights);\n            } else if (linecount % 4 == 2) {\n\t\t\t\tmodify_bn_scale_factor(weights);\n                m_fwd_weights->m_batchnorm_means.emplace_back(weights);\n            } else if (linecount % 4 == 3) {\n\t\t\t\tmodify_bn_scale_factor(weights);\n                process_bn_var(weights);\n                m_fwd_weights->m_batchnorm_stddevs.emplace_back(weights);\n            }\n        } else {\n            switch (linecount - plain_conv_wts) {\n                case  0: m_fwd_weights->m_conv_pol_w = std::move(weights); break;\n                case  1: m_fwd_weights->m_conv_pol_b = std::move(weights); break;\n                case  2: modify_bn_scale_factor(weights);\n                         std::copy(cbegin(weights), cend(weights),\n                                   begin(m_bn_pol_w1)); break;\n                case  3: modify_bn_scale_factor(weights);\n                         process_bn_var(weights);\n                         std::copy(cbegin(weights), cend(weights),\n                                   begin(m_bn_pol_w2)); break;\n                case  4:\n/*\n                         if (weights.size() != OUTPUTS_POLICY\n                                               * NUM_INTERSECTIONS\n                                               * POTENTIAL_MOVES) {\n                             myprintf(\"The weights file is not for %dx%d boards.\\n\",\n                                      BOARD_SIZE, BOARD_SIZE);\n                             return {0, 0};\n                         }\n*/\n//                       std::copy(cbegin(weights), cend(weights),\n//                                 begin(m_ip_pol_w)); break;\n                         m_conv2_pol_w = std::move(weights); break;\n                case  5:\n//                       std::copy(cbegin(weights), cend(weights),\n//                                 begin(m_ip_pol_b)); break;\n                         m_conv2_pol_b = std::move(weights); break;\n                case  6: m_fwd_weights->m_conv_val_w = std::move(weights); break;\n                case  7: m_fwd_weights->m_conv_val_b = std::move(weights); break;\n                case  8: modify_bn_scale_factor(weights);\n                         std::copy(cbegin(weights), cend(weights),\n                                   begin(m_bn_val_w1)); break;\n                case  9: modify_bn_scale_factor(weights);\n                         process_bn_var(weights);\n                         std::copy(cbegin(weights), cend(weights),\n                                   begin(m_bn_val_w2)); break;\n                case 10: std::copy(cbegin(weights), cend(weights),\n                                   begin(m_ip1_val_w)); break;\n                case 11: std::copy(cbegin(weights), cend(weights),\n                                   begin(m_ip1_val_b)); break;\n                case 12: std::copy(cbegin(weights), cend(weights),\n                                   begin(m_ip2_val_w)); break;\n                case 13: std::copy(cbegin(weights), cend(weights),\n                                   begin(m_ip2_val_b)); break;\n            }\n        }\n        linecount++;\n    }\n//  process_bn_var(m_bn_pol_w2);\n//  process_bn_var(m_bn_val_w2);\n\tmyprintf(\"num=%d...linecount=%d\\n\",num,linecount);\n\n    return {channels, static_cast<int>(residual_blocks)};\n}\n\nstd::pair<int, int> Network::load_network_file(const std::string& filename) {\n    // gzopen supports both gz and non-gz files, will decompress\n    // or just read directly as needed.\n    auto gzhandle = gzopen(filename.c_str(), \"rb\");\n    if (gzhandle == nullptr) {\n        myprintf(\"Could not open weights file: %s\\n\", filename.c_str());\n        return {0, 0};\n    }\n    // Stream the gz file in to a memory buffer stream.\n    auto buffer = std::stringstream{};\n    constexpr auto chunkBufferSize = 64 * 1024;\n    std::vector<char> chunkBuffer(chunkBufferSize);\n    while (true) {\n        auto bytesRead = gzread(gzhandle, chunkBuffer.data(), chunkBufferSize);\n        if (bytesRead == 0) break;\n        if (bytesRead < 0) {\n            myprintf(\"Failed to decompress or read: %s\\n\", filename.c_str());\n            gzclose(gzhandle);\n            return {0, 0};\n        }\n        assert(bytesRead <= chunkBufferSize);\n        buffer.write(chunkBuffer.data(), bytesRead);\n    }\n    gzclose(gzhandle);\n\n    // Read format version\n    auto line = std::string{};\n    auto format_version = -1;\n    if (std::getline(buffer, line)) {\n        auto iss = std::stringstream{line};\n        // First line is the file format version id\n        iss >> format_version;\n        if (iss.fail() || (format_version != 2)) {\n            myprintf(\"Weights file is the wrong version.\\n\");\n            return {0, 0};\n        } else {\n            // Version 2 networks are identical to v1, except\n            // that they return the value for black instead of\n            // the player to move. This is used by ELF Open Go.\n\n            if (format_version == 2) {\n                m_value_head_not_stm = true;\n            } else {\n                m_value_head_not_stm = false;\n            }\n\n            return load_v1_network(buffer);\n        }\n    }\n    return {0, 0};\n}\n/*\nstd::unique_ptr<ForwardPipe>&& Network::init_net(int channels,\n    std::unique_ptr<ForwardPipe>&& pipe) {\n\n    pipe->initialize(channels);\n    pipe->push_weights(WINOGRAD_ALPHA, INPUT_CHANNELS, channels, m_fwd_weights);\n\n    return std::move(pipe);\n}\n*/\nstd::unique_ptr<ForwardPipe> Network::init_net(int channels,\n    std::unique_ptr<ForwardPipe> pipe) {\n\n    pipe->initialize(channels);\n    pipe->push_weights(WINOGRAD_ALPHA, INPUT_CHANNELS, channels, m_fwd_weights);\n    return pipe;\n}\n\n#ifdef USE_HALF\nvoid Network::select_precision(int channels) {\n    if (cfg_precision == precision_t::AUTO) {\n        auto score_fp16 = float{-1.0};\n        auto score_fp32 = float{-1.0};\n\n        myprintf(\"Initializing OpenCL (autodetecting precision).\\n\");\n\n        // Setup fp16 here so that we can see if we can skip autodetect.\n        // However, if fp16 sanity check fails we will return a fp32 and pray it works.\n        auto fp16_net = std::make_unique<OpenCLScheduler<half_float::half>>();\n        if (!fp16_net->needs_autodetect()) {\n            try {\n                myprintf(\"OpenCL: using fp16/half or tensor core compute support.\\n\");\n                m_forward = init_net(channels, std::move(fp16_net));\n                benchmark_time(1); // a sanity check run\n            } catch (...) {\n                myprintf(\"OpenCL: fp16/half or tensor core failed despite driver claiming support.\\n\");\n                myprintf(\"Falling back to single precision\\n\");\n                m_forward.reset();\n                m_forward = init_net(channels,\n                    std::make_unique<OpenCLScheduler<float>>());\n            }\n            return;\n        }\n\n        // Start by setting up fp32.\n        try {\n            m_forward.reset();\n            m_forward = init_net(channels,\n                std::make_unique<OpenCLScheduler<float>>());\n            score_fp32 = benchmark_time(100);\n        } catch (...) {\n            // empty - if exception thrown just throw away fp32 net\n        }\n\n        // Now benchmark fp16.\n        try {\n            m_forward.reset();\n            m_forward = init_net(channels, std::move(fp16_net));\n            score_fp16 = benchmark_time(100);\n        } catch (...) {\n            // empty - if exception thrown just throw away fp16 net\n        }\n\n        if (score_fp16 < 0.0f && score_fp32 < 0.0f) {\n            myprintf(\"Both single precision and half precision failed to run.\\n\");\n            throw std::runtime_error(\"Failed to initialize net.\");\n        } else if (score_fp16 < 0.0f) {\n            myprintf(\"Using OpenCL single precision (half precision failed to run).\\n\");\n            m_forward.reset();\n            m_forward = init_net(channels,\n                std::make_unique<OpenCLScheduler<float>>());\n        } else if (score_fp32 < 0.0f) {\n            myprintf(\"Using OpenCL half precision (single precision failed to run).\\n\");\n        } else if (score_fp32 * 1.05f > score_fp16) {\n            myprintf(\"Using OpenCL single precision (less than 5%% slower than half).\\n\");\n            m_forward.reset();\n            m_forward = init_net(channels,\n                std::make_unique<OpenCLScheduler<float>>());\n        } else {\n            myprintf(\"Using OpenCL half precision (at least 5%% faster than single).\\n\");\n        }\n        return;\n    } else if (cfg_precision == precision_t::SINGLE) {\n        myprintf(\"Initializing OpenCL (single precision).\\n\");\n        m_forward = init_net(channels,\n            std::make_unique<OpenCLScheduler<float>>());\n        return;\n    } else if (cfg_precision == precision_t::HALF) {\n        myprintf(\"Initializing OpenCL (half precision).\\n\");\n        m_forward = init_net(channels,\n            std::make_unique<OpenCLScheduler<half_float::half>>());\n        return;\n    }\n}\n#endif\n\nvoid Network::initialize(int /*playouts*/, const std::string & weightsfile) {\n#ifdef USE_BLAS\n#ifndef __APPLE__\n#ifdef USE_OPENBLAS\n    openblas_set_num_threads(1);\n    myprintf(\"BLAS Core: %s\\n\", openblas_get_corename());\n#endif\n#ifdef USE_MKL\n    //mkl_set_threading_layer(MKL_THREADING_SEQUENTIAL);\n    mkl_set_num_threads(1);\n    MKLVersion Version;\n    mkl_get_version(&Version);\n    myprintf(\"BLAS core: MKL %s\\n\", Version.Processor);\n#endif\n#endif\n#else\n    myprintf(\"BLAS Core: built-in Eigen %d.%d.%d library.\\n\",\n             EIGEN_WORLD_VERSION, EIGEN_MAJOR_VERSION, EIGEN_MINOR_VERSION);\n#endif\n\n    m_fwd_weights = std::make_shared<ForwardPipeWeights>();\n/*\n    // Make a guess at a good size as long as the user doesn't\n    // explicitly set a maximum memory usage.\n    m_nncache.set_size_from_playouts(playouts);\n\n    // Prepare symmetry table\n    for (auto s = 0; s < NUM_SYMMETRIES; ++s) {\n        for (auto v = 0; v < NUM_INTERSECTIONS; ++v) {\n            const auto newvtx =\n                get_symmetry({v % BOARD_SIZE, v / BOARD_SIZE}, s);\n            symmetry_nn_idx_table[s][v] =\n                (newvtx.second * BOARD_SIZE) + newvtx.first;\n            assert(symmetry_nn_idx_table[s][v] >= 0\n                   && symmetry_nn_idx_table[s][v] < NUM_INTERSECTIONS);\n        }\n    }\n*/\n    // Load network from file\n    size_t channels, residual_blocks;\n    std::tie(channels, residual_blocks) = load_network_file(weightsfile);\n    if (channels == 0) {\n        exit(EXIT_FAILURE);\n    }\n\n    auto weight_index = size_t{0};\n    // Input convolution\n    // Winograd transform convolution weights\n    m_fwd_weights->m_conv_weights[weight_index] =\n        winograd_transform_f(m_fwd_weights->m_conv_weights[weight_index],\n                             channels, INPUT_CHANNELS);\n    weight_index++;\n\n    // Residual block convolutions\n    for (auto i = size_t{0}; i < residual_blocks * 2; i++) {\n        m_fwd_weights->m_conv_weights[weight_index] =\n            winograd_transform_f(m_fwd_weights->m_conv_weights[weight_index],\n                                 channels, channels);\n        weight_index++;\n    }\n\n    // Biases are not calculated and are typically zero but some networks might\n    // still have non-zero biases.\n    // Move biases to batchnorm means to make the output match without having\n    // to separately add the biases.\n    auto bias_size = m_fwd_weights->m_conv_biases.size();\n    for (auto i = size_t{0}; i < bias_size; i++) {\n        auto means_size = m_fwd_weights->m_batchnorm_means[i].size();\n        for (auto j = size_t{0}; j < means_size; j++) {\n            m_fwd_weights->m_batchnorm_means[i][j] -= m_fwd_weights->m_conv_biases[i][j];\n            m_fwd_weights->m_conv_biases[i][j] = 0.0f;\n        }\n    }\n\n    for (auto i = size_t{0}; i < m_bn_val_w1.size(); i++) {\n        m_bn_val_w1[i] -= m_fwd_weights->m_conv_val_b[i];\n        m_fwd_weights->m_conv_val_b[i] = 0.0f;\n    }\n\n    for (auto i = size_t{0}; i < m_bn_pol_w1.size(); i++) {\n        m_bn_pol_w1[i] -= m_fwd_weights->m_conv_pol_b[i];\n        m_fwd_weights->m_conv_pol_b[i] = 0.0f;\n    }\n\n#ifdef USE_OPENCL\n    if (cfg_cpu_only) {\n        myprintf(\"Initializing CPU-only evaluation.\\n\");\n        m_forward = init_net(channels, std::make_unique<CPUPipe>());\n    } else {\n#ifdef USE_OPENCL_SELFCHECK\n        // initialize CPU reference first, so that we can self-check\n        // when doing fp16 vs. fp32 detections\n        m_forward_cpu = init_net(channels, std::make_unique<CPUPipe>());\n#endif\n#ifdef USE_HALF\n        // HALF support is enabled, and we are using the GPU.\n        // Select the precision to use at runtime.\n        select_precision(channels);\n#else\n        myprintf(\"Initializing OpenCL (single precision).\\n\");\n        m_forward = init_net(channels,\n                             std::make_unique<OpenCLScheduler<float>>());\n#endif\n    }\n\n#else //!USE_OPENCL\n    myprintf(\"Initializing CPU-only evaluation.\\n\");\n    m_forward = init_net(channels, std::make_unique<CPUPipe>());\n#endif\n\n    // Need to estimate size before clearing up the pipe.\n    get_estimated_size();\n    m_fwd_weights.reset();\n}\n\ntemplate<unsigned int inputs,\n         unsigned int outputs,\n         bool ReLU,\n         size_t W>\nstd::vector<float> innerproduct(const std::vector<float>& input,\n                                const std::array<float, W>& weights,\n                                const std::array<float, outputs>& biases) {\n    std::vector<float> output(outputs);\n\n#ifdef USE_BLAS\n    cblas_sgemv(CblasRowMajor, CblasNoTrans,\n                // M     K\n                outputs, inputs,\n                1.0f, &weights[0], inputs,\n                &input[0], 1,\n                0.0f, &output[0], 1);\n#else\n    EigenVectorMap<float> y(output.data(), outputs);\n    y.noalias() =\n        ConstEigenMatrixMap<float>(weights.data(),\n                                   inputs,\n                                   outputs).transpose()\n        * ConstEigenVectorMap<float>(input.data(), inputs);\n#endif\n    const auto lambda_ReLU = [](const auto val) { return (val > 0.0f) ?\n                                                          val : 0.0f; };\n    for (unsigned int o = 0; o < outputs; o++) {\n        auto val = biases[o] + output[o];\n        if (ReLU) {\n            val = lambda_ReLU(val);\n        }\n        output[o] = val;\n    }\n\n    return output;\n}\n\ntemplate <size_t spatial_size>\nvoid batchnorm(const size_t channels,\n               std::vector<float>& data,\n               const float* const means,\n               const float* const stddivs,\n               const float* const eltwise = nullptr) {\n    const auto lambda_ReLU = [](const auto val) { return (val > 0.0f) ?\n                                                          val : 0.0f; };\n    for (auto c = size_t{0}; c < channels; ++c) {\n        const auto mean = means[c];\n        const auto scale_stddiv = stddivs[c];\n        const auto arr = &data[c * spatial_size];\n\n        if (eltwise == nullptr) {\n            // Classical BN\n            for (auto b = size_t{0}; b < spatial_size; b++) {\n                arr[b] = lambda_ReLU(scale_stddiv * (arr[b] - mean));\n            }\n        } else {\n            // BN + residual add\n            const auto res = &eltwise[c * spatial_size];\n            for (auto b = size_t{0}; b < spatial_size; b++) {\n                arr[b] = lambda_ReLU((scale_stddiv * (arr[b] - mean)) + res[b]);\n            }\n        }\n    }\n}\n\n#ifdef USE_OPENCL_SELFCHECK\n/*\nvoid Network::compare_net_outputs(const Netresult& data,\n                                  const Netresult& ref) {\n    // Calculates L2-norm between data and ref.\n    constexpr auto max_error = 0.2f;\n\n    auto error = 0.0f;\n\n    for (auto idx = size_t{0}; idx < data.policy.size(); ++idx) {\n        const auto diff = data.policy[idx] - ref.policy[idx];\n        error += diff * diff;\n    }\n    const auto diff_pass = data.policy_pass - ref.policy_pass;\n    const auto diff_winrate = data.winrate - ref.winrate;\n    error += diff_pass * diff_pass;\n    error += diff_winrate * diff_winrate;\n\n    error = std::sqrt(error);\n\n    if (error > max_error || std::isnan(error)) {\n        printf(\"Error in OpenCL calculation: Update your device's OpenCL drivers \"\n               \"or reduce the amount of games played simultaneously.\\n\");\n        throw std::runtime_error(\"OpenCL self-check mismatch.\");\n    }\n}\n*/\ntemplate<typename T>\nT relative_difference(T a, T b) {\n    // Handle NaN\n    if (std::isnan(a) || std::isnan(b)) {\n        return std::numeric_limits<T>::max();\n    }\n    // Handle sign difference\n    if (((a < 0) != (b < 0)) && (a != 0) && (b != 0)) {\n        return std::numeric_limits<T>::max();\n    }\n    a = std::fabs(a);\n    b = std::fabs(b);\n\n    // Handle underflow\n    constexpr float small_number = 1e-3f;\n    a = std::max(a, small_number);\n    b = std::max(b, small_number);\n\n    return std::max(fabs((a - b) / a), fabs((a - b) / b));\n}\n\n//void compare_net_outputs(std::vector<float>& data,\n//                         std::vector<float>& ref) {\nvoid Network::compare_net_outputs(std::vector<scored_node>& data,\n                                  std::vector<scored_node>& ref) {\n    // We accept an error up to 5%, but output values\n    // smaller than 1/1000th are \"rounded up\" for the comparison.\n    constexpr float relative_error = 5e-2f;\n    for (auto idx = size_t{0}; idx < data.size(); ++idx) {\n        auto err = relative_difference(data[idx].first, ref[idx].first);\n        if (err > relative_error) {\n            printf(\"Error in OpenCL calculation: expected %f got %f \"\n                   \"(error=%f%%)\\n\", ref[idx].first, data[idx].first, err * 100.0);\n            printf(\"Update your GPU drivers or reduce the amount of games \"\n                   \"played simultaneously.\\n\");\n            throw std::runtime_error(\"OpenCL self-check mismatch.\");\n        }\n    }\n}\n#endif\n\nstd::vector<float> softmax(const std::vector<float>& input,\n                           const float temperature = 1.0f) {\n    auto output = std::vector<float>{};\n    output.reserve(input.size());\n\n    const auto alpha = *std::max_element(cbegin(input), cend(input));\n    auto denom = 0.0f;\n\n    for (const auto in_val : input) {\n        auto val = std::exp((in_val - alpha) / temperature);\n        denom += val;\n        output.push_back(val);\n    }\n\n    for (auto& out : output) {\n        out /= denom;\n    }\n\n    return output;\n}\n/*\nbool Network::probe_cache(const GameState* const state,\n                          Network::Netresult& result) {\n    if (m_nncache.lookup(state->board.get_hash(), result)) {\n        return true;\n    }\n    // If we are not generating a self-play game, try to find\n    // symmetries if we are in the early opening.\n    if (!cfg_noise && !cfg_random_cnt\n        && state->get_movenum()\n           < (state->get_timecontrol().opening_moves(BOARD_SIZE) / 2)) {\n        for (auto sym = 0; sym < Network::NUM_SYMMETRIES; ++sym) {\n            if (sym == Network::IDENTITY_SYMMETRY) {\n                continue;\n            }\n            const auto hash = state->get_symmetry_hash(sym);\n            if (m_nncache.lookup(hash, result)) {\n                decltype(result.policy) corrected_policy;\n                for (auto idx = size_t{0}; idx < NUM_INTERSECTIONS; ++idx) {\n                    const auto sym_idx = symmetry_nn_idx_table[sym][idx];\n                    corrected_policy[idx] = result.policy[sym_idx];\n                }\n                result.policy = std::move(corrected_policy);\n                return true;\n            }\n        }\n    }\n    return false;\n}\n*/\nNetwork::Netresult_old Network::get_output(\n    NNPlanes & planes, const bool force_selfcheck) {\n//    Netresult result;\n    Netresult_old result;\n/*\n    if (state->board.get_boardsize() != BOARD_SIZE) {\n        return result;\n    }\n\n    if (read_cache) {\n        // See if we already have this in the cache.\n        if (probe_cache(state, result)) {\n            return result;\n        }\n    }\n*/\n/*\n    if (ensemble == DIRECT) {\n        assert(symmetry >= 0 && symmetry < NUM_SYMMETRIES);\n        result = get_output_internal(state, symmetry);\n    } else if (ensemble == AVERAGE) {\n        assert(symmetry == -1);\n        for (auto sym = 0; sym < NUM_SYMMETRIES; ++sym) {\n            auto tmpresult = get_output_internal(state, sym);\n            result.winrate +=\n                tmpresult.winrate / static_cast<float>(NUM_SYMMETRIES);\n            result.policy_pass +=\n                tmpresult.policy_pass / static_cast<float>(NUM_SYMMETRIES);\n\n            for (auto idx = size_t{0}; idx < NUM_INTERSECTIONS; idx++) {\n                result.policy[idx] +=\n                    tmpresult.policy[idx] / static_cast<float>(NUM_SYMMETRIES);\n            }\n        }\n    } else {\n        assert(ensemble == RANDOM_SYMMETRY);\n        assert(symmetry == -1);\n*/\n//        const auto rand_sym = Random::get_Rng().randfix<NUM_SYMMETRIES>();\n        result = get_output_internal(planes);\n#ifdef USE_OPENCL_SELFCHECK\n        // Both implementations are available, self-check the OpenCL driver by\n        // running both with a probability of 1/2000.\n        // selfcheck is done here because this is the only place NN\n        // evaluation is done on actual gameplay.\n        if (m_forward_cpu != nullptr\n            && (force_selfcheck || Random::get_Rng().randfix<SELFCHECK_PROBABILITY>() == 0)\n        ) {\n            auto result_ref = get_output_internal(planes, true);\n            compare_net_outputs(result.first, result_ref.first);\n        }\n#else\n        (void)force_selfcheck;\n#endif\n/*\n    }\n*/\n/*\n    // v2 format (ELF Open Go) returns black value, not stm\n    if (m_value_head_not_stm) {\n        if (state->board.get_to_move() == FastBoard::WHITE) {\n            result.winrate = 1.0f - result.winrate;\n        }\n    }\n\n    if (write_cache) {\n        // Insert result into cache.\n        m_nncache.insert(state->board.get_hash(), result);\n    }\n*/\n    return result;\n}\n\nNetwork::Netresult_old Network::get_output_internal(\n    NNPlanes & planes, bool selfcheck) {\n//    assert(symmetry >= 0 && symmetry < NUM_SYMMETRIES);\n    constexpr auto width = BOARD_SIZE;\n    constexpr auto height = BOARD_SIZE;\n\n//    const auto input_data = gather_features(state, symmetry);\n    std::vector<float> input_data;\n    // Data layout is input_data[(c * height + h) * width + w]\n    input_data.reserve(INPUT_CHANNELS * width * height);\n\n    for (int c = 0; c < INPUT_CHANNELS; ++c) {\n        for (int h = 0; h < height; ++h) {\n            for (int w = 0; w < width; ++w) {\n                input_data.emplace_back(net_t(planes[c][h*B_SIZE + w]));\n            }\n        }\n    }\n\tif ( 0 ) { float s=0; for (size_t i=0; i<input_data.size(); i++) s += input_data[i]; myprintf(\"input_data.size()=%d,sum=%f\\n\",input_data.size(),s); }\n\n\n    std::vector<float> policy_data(OUTPUTS_POLICY * width * height);\n    std::vector<float> value_data(OUTPUTS_VALUE * width * height);\n#ifdef USE_OPENCL_SELFCHECK\n    if (selfcheck) {\n        m_forward_cpu->forward(input_data, policy_data, value_data);\n    } else {\n        m_forward->forward(input_data, policy_data, value_data);\n    }\n#else\n    m_forward->forward(input_data, policy_data, value_data);\n    (void) selfcheck;\n#endif\n\n\tif ( 0 ) { float s=0; for (size_t i=0; i<policy_data.size(); i++) s += policy_data[i]; myprintf(\"policy_data.size()=%d,sum=%f\\n\",policy_data.size(),s); }\n\tif ( 0 ) { float s=0; for (size_t i=0; i<value_data.size();  i++) s += value_data[i];  myprintf(\"value_data.size() =%d,sum=%f\\n\",value_data.size(),s); }\n\n    // Get the moves\n//    batchnorm<NUM_INTERSECTIONS>(OUTPUTS_POLICY, policy_data,  m_bn_pol_w1.data(), m_bn_pol_w2.data());\n    batchnorm<B_AREA>(OUTPUTS_POLICY, policy_data,  m_bn_pol_w1.data(), m_bn_pol_w2.data());\n//    const auto policy_out =\n//        innerproduct<OUTPUTS_POLICY * NUM_INTERSECTIONS, POTENTIAL_MOVES, false>(\n//            policy_data, m_ip_pol_w, m_ip_pol_b);\n//    const auto outputs = softmax(policy_out, cfg_softmax_temp);\n\n    std::vector<float> policy_out(POLICY_OUT_NUM);\n    convolve<1>(139, policy_data, m_conv2_pol_w, m_conv2_pol_b, policy_out);\t// 9*9*139 = 11259\n    const auto outputs = softmax(policy_out, cfg_softmax_temp);\n//    softmax(policy_out, softmax_data, cfg_softmax_temp);\n//    std::vector<float>& outputs = softmax_data;\n\n\n    // Now get the value\n//    batchnorm<NUM_INTERSECTIONS>(OUTPUTS_VALUE, value_data, m_bn_val_w1.data(), m_bn_val_w2.data());\n    batchnorm<B_AREA>(OUTPUTS_VALUE, value_data, m_bn_val_w1.data(), m_bn_val_w2.data());\n    const auto winrate_data =\n//        innerproduct<OUTPUTS_VALUE * NUM_INTERSECTIONS, VALUE_LAYER, true>( value_data, m_ip1_val_w, m_ip1_val_b);\n        innerproduct<OUTPUTS_VALUE * B_AREA, VALUE_LAYER, true>( value_data, m_ip1_val_w, m_ip1_val_b);\n    const auto winrate_out =\n        innerproduct<VALUE_LAYER, 1, false>(winrate_data, m_ip2_val_w, m_ip2_val_b);\n\n\n    // Map TanH output range [-1..1] to [0..1] range\n//    const auto winrate = (1.0f + std::tanh(winrate_out[0])) / 2.0f;\n    const auto winrate_sig = std::tanh(winrate_out[0]);\n/*\n    Netresult result;\n\n    for (auto idx = size_t{0}; idx < NUM_INTERSECTIONS; idx++) {\n        const auto sym_idx = symmetry_nn_idx_table[symmetry][idx];\n        result.policy[sym_idx] = outputs[idx];\n    }\n\n    result.policy_pass = outputs[NUM_INTERSECTIONS];\n    result.winrate = winrate;\n*/\n    std::vector<scored_node> result;\n    for (auto idx = size_t{0}; idx < outputs.size(); idx++) {\n//      if ( idx < 100 ) myprintf(\"%3d:%f\\n\",idx,outputs[idx]);\n//    myprintf(\"done tanh....%d,outputs.size()=%d\\n\",__LINE__,outputs.size());\n//\t\tfloat v = outputs[idx];\n//    myprintf(\"done tanh....%d,v=%f\\n\",__LINE__,v);\n//        result.emplace_back(v, idx);\n        result.emplace_back(outputs[idx], idx);\n    }\n//  myprintf(\"done net calc\\n\");\n\n    return std::make_pair(result, winrate_sig);\n//    return result;\n}\n/*\nvoid Network::show_heatmap(const FastState* const state,\n                           const Netresult& result,\n                           const bool topmoves) {\n    std::vector<std::string> display_map;\n    std::string line;\n\n    for (unsigned int y = 0; y < BOARD_SIZE; y++) {\n        for (unsigned int x = 0; x < BOARD_SIZE; x++) {\n            auto policy = 0;\n            const auto vertex = state->board.get_vertex(x, y);\n            if (state->board.get_state(vertex) == FastBoard::EMPTY) {\n                policy = result.policy[y * BOARD_SIZE + x] * 1000;\n            }\n\n            line += boost::str(boost::format(\"%3d \") % policy);\n        }\n\n        display_map.push_back(line);\n        line.clear();\n    }\n\n    for (int i = display_map.size() - 1; i >= 0; --i) {\n        myprintf(\"%s\\n\", display_map[i].c_str());\n    }\n    const auto pass_policy = int(result.policy_pass * 1000);\n    myprintf(\"pass: %d\\n\", pass_policy);\n    myprintf(\"winrate: %f\\n\", result.winrate);\n\n    if (topmoves) {\n        std::vector<Network::PolicyVertexPair> moves;\n        for (auto i=0; i < NUM_INTERSECTIONS; i++) {\n            const auto x = i % BOARD_SIZE;\n            const auto y = i / BOARD_SIZE;\n            const auto vertex = state->board.get_vertex(x, y);\n            if (state->board.get_state(vertex) == FastBoard::EMPTY) {\n                moves.emplace_back(result.policy[i], vertex);\n            }\n        }\n        moves.emplace_back(result.policy_pass, FastBoard::PASS);\n\n        std::stable_sort(rbegin(moves), rend(moves));\n\n        auto cum = 0.0f;\n        for (const auto& move : moves) {\n            if (cum > 0.85f || move.first < 0.01f) break;\n            myprintf(\"%1.3f (%s)\\n\",\n                    move.first,\n                    state->board.move_to_text(move.second).c_str());\n            cum += move.first;\n        }\n    }\n}\n\nvoid Network::fill_input_plane_pair(const FullBoard& board,\n                                    std::vector<float>::iterator black,\n                                    std::vector<float>::iterator white,\n                                    const int symmetry) {\n    for (auto idx = 0; idx < NUM_INTERSECTIONS; idx++) {\n        const auto sym_idx = symmetry_nn_idx_table[symmetry][idx];\n        const auto x = sym_idx % BOARD_SIZE;\n        const auto y = sym_idx / BOARD_SIZE;\n        const auto color = board.get_state(x, y);\n        if (color == FastBoard::BLACK) {\n            black[idx] = float(true);\n        } else if (color == FastBoard::WHITE) {\n            white[idx] = float(true);\n        }\n    }\n}\n*/\nstd::vector<float> Network::gather_features(const GameState* const /*state*/,\n                                            const int /*symmetry*/) {\nmyprintf(\"gather_features() To do!\\n\");\n//    assert(symmetry >= 0 && symmetry < NUM_SYMMETRIES);\n    auto input_data = std::vector<float>(INPUT_CHANNELS * NUM_INTERSECTIONS);\n#if 0\n    const auto to_move = state->get_to_move();\n    const auto blacks_move = to_move == FastBoard::BLACK;\n\n    const auto black_it = blacks_move ?\n                          begin(input_data) :\n                          begin(input_data) + INPUT_MOVES * NUM_INTERSECTIONS;\n    const auto white_it = blacks_move ?\n                          begin(input_data) + INPUT_MOVES * NUM_INTERSECTIONS :\n                          begin(input_data);\n    const auto to_move_it = blacks_move ?\n        begin(input_data) + 2 * INPUT_MOVES * NUM_INTERSECTIONS :\n        begin(input_data) + (2 * INPUT_MOVES + 1) * NUM_INTERSECTIONS;\n\n    const auto moves = std::min<size_t>(state->get_movenum() + 1, INPUT_MOVES);\n    // Go back in time, fill history boards\n    for (auto h = size_t{0}; h < moves; h++) {\n        // collect white, black occupation planes\n        fill_input_plane_pair(state->get_past_board(h),\n                              black_it + h * NUM_INTERSECTIONS,\n                              white_it + h * NUM_INTERSECTIONS,\n                              symmetry);\n    }\n\n    std::fill(to_move_it, to_move_it + NUM_INTERSECTIONS, float(true));\n#endif\n    return input_data;\n}\n/*\nstd::pair<int, int> Network::get_symmetry(const std::pair<int, int>& vertex,\n                                          const int symmetry,\n                                          const int board_size) {\n    auto x = vertex.first;\n    auto y = vertex.second;\n    assert(x >= 0 && x < board_size);\n    assert(y >= 0 && y < board_size);\n    assert(symmetry >= 0 && symmetry < NUM_SYMMETRIES);\n\n    if ((symmetry & 4) != 0) {\n        std::swap(x, y);\n    }\n\n    if ((symmetry & 2) != 0) {\n        x = board_size - x - 1;\n    }\n\n    if ((symmetry & 1) != 0) {\n        y = board_size - y - 1;\n    }\n\n    assert(x >= 0 && x < board_size);\n    assert(y >= 0 && y < board_size);\n    assert(symmetry != IDENTITY_SYMMETRY || vertex == std::make_pair(x, y));\n    return {x, y};\n}\n*/\nsize_t Network::get_estimated_size() {\n    if (estimated_size != 0) {\n        return estimated_size;\n    }\n    auto result = size_t{0};\n\n    const auto lambda_vector_size =  [](const std::vector<std::vector<float>> &v) {\n        auto result = size_t{0};\n        for (auto it = begin(v); it != end(v); ++it) {\n            result += it->size() * sizeof(float);\n        }\n        return result;\n    };\n\n    result += lambda_vector_size(m_fwd_weights->m_conv_weights);\n    result += lambda_vector_size(m_fwd_weights->m_conv_biases);\n    result += lambda_vector_size(m_fwd_weights->m_batchnorm_means);\n    result += lambda_vector_size(m_fwd_weights->m_batchnorm_stddevs);\n\n    result += m_fwd_weights->m_conv_pol_w.size() * sizeof(float);\n    result += m_fwd_weights->m_conv_pol_b.size() * sizeof(float);\n\n    // Policy head\n    result += OUTPUTS_POLICY * sizeof(float); // m_bn_pol_w1\n    result += OUTPUTS_POLICY * sizeof(float); // m_bn_pol_w2\n    result += OUTPUTS_POLICY * NUM_INTERSECTIONS\n                             * POTENTIAL_MOVES * sizeof(float); //m_ip_pol_w\n    result += POTENTIAL_MOVES * sizeof(float); // m_ip_pol_b\n\n    // Value head\n    result += m_fwd_weights->m_conv_val_w.size() * sizeof(float);\n    result += m_fwd_weights->m_conv_val_b.size() * sizeof(float);\n    result += OUTPUTS_VALUE * sizeof(float); // m_bn_val_w1\n    result += OUTPUTS_VALUE * sizeof(float); // m_bn_val_w2\n\n    result += OUTPUTS_VALUE * NUM_INTERSECTIONS\n                            * VALUE_LAYER * sizeof(float); // m_ip1_val_w\n    result += VALUE_LAYER * sizeof(float);  // m_ip1_val_b\n\n    result += VALUE_LAYER * sizeof(float); // m_ip2_val_w\n    result += sizeof(float); // m_ip2_val_b\n    return estimated_size = result;\n}\n\nsize_t Network::get_estimated_cache_size() {\n    return m_nncache.get_estimated_size();\n}\n\nvoid Network::nncache_resize(int max_count) {\n    return m_nncache.resize(max_count);\n}\n\n\n\nNetwork::Netresult_old Network::get_scored_moves_yss_zero(float data[][B_SIZE][B_SIZE]) {\n    Netresult_old result;\n    NNPlanes planes;\n    gather_features_yss_zero(planes, data);\n\n\tresult = get_output( planes );\n//    result = get_scored_moves_internal(NULL, planes, 0);\n/*\n\tauto net_eval = result.second;\n//    myprintf(\"eval=%f\\n\",net_eval);\n    std::vector<Network::scored_node> nodelist;\n\n    auto legal_sum = 0.0f;\n    for (const auto& node : result.first) {\n        legal_sum += node.first;\n        auto vertex = node.second;\n//\t    if ( vertex < 100 || vertex > result.first.size()-100 ) myprintf(\"%4d,%f\\n\",vertex,node.first);\n//\t    if ( vertex < 100 ) myprintf(\"%4d,%f\\n\",vertex,node.first);\n    }\n//  myprintf(\"legal_sum=%f\\n\",legal_sum);\n*/\n    return result;\n}\n\nvoid Network::gather_features_yss_zero(NNPlanes & planes, float data[][B_SIZE][B_SIZE]) {\n//    myprintf(\"gather_features_yss_zero()\\n\");\n\n    planes.resize(INPUT_CHANNELS);\n\n    int c,z;\n    for (c=0;c<INPUT_CHANNELS;c++) {\n//\t\tmyprintf(\"%d\\n\",c);\n\t\tfor (z=0;z<81;z++) {\n\t\t\tint y = z / 9;\n\t\t\tint x = z - y*9;\n\t\t\tplanes[c][z] = data[c][y][x];\n//\t\t\tmyprintf(\"%d,\",planes[c][z]);\n//\t\t\tif ( ((z+1)%9)==0 ) myprintf(\"\\n\");\n\t\t}\n\t}\n\n\treturn;\n}\n\n", "meta": {"hexsha": "bae38a937fe1ef88f92dc7a91d2938c3681db034", "size": 44068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/usi-engine/Network.cpp", "max_stars_repo_name": "bleu48/aobazero", "max_stars_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "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/usi-engine/Network.cpp", "max_issues_repo_name": "bleu48/aobazero", "max_issues_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "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/usi-engine/Network.cpp", "max_forks_repo_name": "bleu48/aobazero", "max_forks_repo_head_hexsha": "c805b80d9ed8d27ce507fc2b74fb7609d75b2426", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3897605285, "max_line_length": 154, "alphanum_fraction": 0.5764954162, "num_tokens": 11052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111088366237636, "lm_q2_score": 0.020023441399104527, "lm_q1q2_score": 0.008231854687547672}}
{"text": "/// @file\n///\n/// Provides utility functions for simulations package\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 Matthew Whiting <matthew.whiting@csiro.au>\n///\n#include <askap_simulations.h>\n\n#include <simulationutilities/SimulationUtilities.h>\n#include <simulationutilities/FluxGenerator.h>\n#include <mathsutils/MathsUtils.h>\n#include <askap/AskapLogging.h>\n#include <askap/AskapError.h>\n\n#include <casacore/scimath/Functionals/Gaussian1D.h>\n#include <casacore/scimath/Functionals/Gaussian2D.h>\n#include <casacore/scimath/Functionals/Gaussian3D.h>\n#include <casacore/casa/namespace.h>\n#include <boost/shared_ptr.hpp>\n\n#include <wcslib/wcs.h>\n#include <wcslib/wcsunits.h>\n#include <wcslib/wcsfix.h>\n#define WCSLIB_GETWCSTAB // define this so that we don't try to redefine wtbarr\n// (this is a problem when using wcslib-4.2)\n\n#include <Common/ParameterSet.h>\n\n#include <duchamp/Utils/Section.hh>\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <utility>\n#include <string>\n#include <stdlib.h>\n#include <math.h>\n\nASKAP_LOGGER(logger, \".simutils\");\n\nnamespace askap {\n\nnamespace simulations {\n\n\nconst std::string locationString(duchamp::Section &subsection)\n{\n\n    std::stringstream locationString;\n    locationString << \"_\";\n    for (uint i = 0; i < subsection.getStartList().size(); i++) {\n        locationString << \"_\" << subsection.getStart(i);\n    }\n    locationString << \"__\";\n\n    return locationString.str();\n}\n\nstruct wcsprm *parsetToWCS(const LOFAR::ParameterSet& theParset,\n                           const std::vector<unsigned int> &theAxes,\n                           const float &theEquinox,\n                           const float &theRestFreq,\n                           duchamp::Section &theSection)\n{\n\n    const unsigned int theDim = theAxes.size();\n\n    struct wcsprm *wcs = (struct wcsprm *)calloc(1, sizeof(struct wcsprm));\n    wcs->flag = -1;\n    int status = wcsini(true , theDim, wcs);\n    ASKAPCHECK(status == 0, \"WCSINI returned non-zero result - \" << status <<\n               \" = \" << wcs_errmsg[status]);\n    wcs->flag = 0;\n    std::vector<std::string> ctype, cunit;\n    std::vector<float> crval, crpix, cdelt, crota;\n    ctype = theParset.getStringVector(\"ctype\");\n\n    if (ctype.size() != theDim)\n        ASKAPTHROW(AskapError, \"Dimension mismatch: dim = \" << theDim <<\n                   \", but ctype has \" << ctype.size() << \" dimensions.\");\n\n    cunit = theParset.getStringVector(\"cunit\");\n\n    if (cunit.size() != theDim)\n        ASKAPTHROW(AskapError, \"Dimension mismatch: dim = \" << theDim <<\n                   \", but cunit has \" << cunit.size() << \" dimensions.\");\n\n    crval = theParset.getFloatVector(\"crval\");\n\n    if (crval.size() != theDim)\n        ASKAPTHROW(AskapError, \"Dimension mismatch: dim = \" << theDim <<\n                   \", but crval has \" << crval.size() << \" dimensions.\");\n\n    crpix = theParset.getFloatVector(\"crpix\");\n\n    if (crpix.size() != theDim)\n        ASKAPTHROW(AskapError, \"Dimension mismatch: dim = \" << theDim <<\n                   \", but crpix has \" << crpix.size() << \" dimensions.\");\n\n    cdelt = theParset.getFloatVector(\"cdelt\");\n\n    if (cdelt.size() != theDim)\n        ASKAPTHROW(AskapError, \"Dimension mismatch: dim = \" << theDim <<\n                   \", but cdelt has \" << cdelt.size() << \" dimensions.\");\n\n    crota = theParset.getFloatVector(\"crota\");\n\n    if (crota.size() != theDim)\n        ASKAPTHROW(AskapError, \"Dimension mismatch: dim = \" << theDim <<\n                   \", but crota has \" << crota.size() << \" dimensions.\");\n\n    for (uint i = 0; i < theDim; i++) {\n        wcs->crpix[i] = crpix[i] - theSection.getStart(i) + 1;\n        wcs->cdelt[i] = cdelt[i];\n        wcs->crval[i] = crval[i];\n        wcs->crota[i] = crota[i];\n        strcpy(wcs->cunit[i], cunit[i].c_str());\n        strcpy(wcs->ctype[i], ctype[i].c_str());\n    }\n\n    wcs->equinox = theEquinox;\n    if (theRestFreq > 0.) wcs->restfrq = theRestFreq;\n    else wcs->restfrq = 0.;\n    wcs->restwav = 0.;\n    wcsset(wcs);\n\n    int stat[NWCSFIX];\n    int *axes = new int[theDim];\n\n    for (uint i = 0; i < theDim; i++) axes[i] = theAxes[i];\n    wcsfix(1, (const int*)axes, wcs, stat);\n    wcsset(wcs);\n\n    delete [] axes;\n\n    return wcs;\n    // int nwcs = 1;\n\n    // if (isImage) {\n    //   if (this->itsWCSAllocated) wcsvfree(&nwcs, &this->itsWCS);\n\n    //   this->itsWCS = (struct wcsprm *)calloc(1, sizeof(struct wcsprm));\n    //   this->itsWCSAllocated = true;\n    //   this->itsWCS->flag = -1;\n    //   wcsini(true, wcs->naxis, this->itsWCS);\n    //   wcsfix(1, (const int*)axes, wcs, stat);\n    //   wcscopy(true, wcs, this->itsWCS);\n    //   wcsset(this->itsWCS);\n    // } else {\n    //   if (this->itsWCSsourcesAllocated)  wcsvfree(&nwcs, &this->itsWCSsources);\n\n    //   this->itsWCSsources = (struct wcsprm *)calloc(1, sizeof(struct wcsprm));\n    //   this->itsWCSsourcesAllocated = true;\n    //   this->itsWCSsources->flag = -1;\n    //   wcsini(true, wcs->naxis, this->itsWCSsources);\n    //   wcsfix(1, (const int*)axes, wcs, stat);\n    //   wcscopy(true, wcs, this->itsWCSsources);\n    //   wcsset(this->itsWCSsources);\n    // }\n\n    // wcsvfree(&nwcs, &wcs);\n\n}\n\n\nbool doAddGaussian(std::vector<unsigned int> axes, casa::Gaussian2D<casa::Double> gauss)\n{\n    float majorSigma = FWHMtoSIGMA(gauss.majorAxis());\n    float zeroPoint = majorSigma * sqrt(-2.*log(1. / (MAXFLOAT * gauss.height())));\n    int xmin = std::max(lround(gauss.xCenter() - zeroPoint), 0L);\n    int xmax = std::min(lround(gauss.xCenter() + zeroPoint), long(axes[0] - 1));\n    int ymin = std::max(lround(gauss.yCenter() - zeroPoint), 0L);\n    int ymax = std::min(lround(gauss.yCenter() + zeroPoint), long(axes[1] - 1));\n    // ASKAPLOG_DEBUG_STR(logger, axes[0] << \" \" << axes[1] << \" \" << gauss << \" \" << gauss.height() << \" \" << majorSigma << \" \" << zeroPoint << \" \" << xmin << \" \" << xmax << \" \" << ymin << \" \" << ymax);\n    return ((xmax >= xmin) && (ymax >= ymin));\n\n}\n\nbool doAddPointSource(std::vector<unsigned int> axes, std::vector<double> pix)\n{\n\n    int xpix = lround(pix[0]);\n    int ypix = lround(pix[1]);\n\n    return (xpix >= 0 && xpix < int(axes[0]) && ypix >= 0 && ypix < int(axes[1]));\n}\n\nbool doAddDisc(std::vector<unsigned int> axes, Disc &disc)\n{\n    // ranges of pixels that will have flux added to them\n    int xmin = std::max(disc.xmin(), 0);\n    int xmax = std::min(disc.xmax(), int(axes[0] - 1));\n    int ymin = std::max(disc.ymin(), 0);\n    int ymax = std::min(disc.ymax(), int(axes[1] - 1));\n\n    return (xmax >= xmin) && (ymax >= ymin);\n\n}\n\n\n\n// bool addGaussian(std::vector<float>array, std::vector<unsigned int> axes, casa::Gaussian2D<casa::Double> gauss, FluxGenerator &fluxGen, bool integrate, bool verbose)\nbool addGaussian(boost::shared_ptr<float[]>array, std::vector<unsigned int> axes, casa::Gaussian2D<casa::Double> gauss, FluxGenerator &fluxGen, bool integrate, bool verbose)\n{\n\n    float majorSigma = FWHMtoSIGMA(gauss.majorAxis()) ;\n    float zeroPointMax = majorSigma * sqrt(-2.*log(1. / (MAXFLOAT * gauss.height())));\n    float minorSigma = FWHMtoSIGMA(gauss.minorAxis());\n    float zeroPointMin = minorSigma * sqrt(-2.*log(1. / (MAXFLOAT * gauss.height())));\n    // Assume a round-number in pixel location is the *centre* of the\n    // pixel, so we round the floating-point pixel location to get the\n    // pixel it falls in\n    int xmin = std::max(lround(gauss.xCenter() - zeroPointMax), 0L);\n    int xmax = std::min(lround(gauss.xCenter() + zeroPointMax), long(axes[0] - 1));\n    int ymin = std::max(lround(gauss.yCenter() - zeroPointMax), 0L);\n    int ymax = std::min(lround(gauss.yCenter() + zeroPointMax), long(axes[1] - 1));\n    if (verbose)\n        ASKAPLOG_DEBUG_STR(logger, \"(x,y)=(\" << gauss.xCenter() << \",\" << gauss.yCenter() <<\n                           \"), FWHMmaj=\" << gauss.majorAxis() <<\n                           \", FWHMmin=\" << gauss.minorAxis() <<\n                           \", gauss.height()=\" << gauss.height() <<\n                           \", sig_maj=\" << majorSigma <<\n                           \", sig_min=\" << minorSigma <<\n                           \", ZPmax=\" << zeroPointMax <<\n                           \", ZPmin=\" << zeroPointMin <<\n                           \"   xmin=\" << xmin << \" xmax=\" << xmax <<\n                           \" ymin=\" << ymin << \" ymax=\" << ymax);\n\n    bool addSource = (xmax >= xmin) && (ymax >= ymin);\n    if (addSource) {  // if there are object pixels falling within the image boundaries\n\n        std::stringstream ss;\n\n        if (axes.size() > 0) ss << axes[0];\n\n        for (size_t i = 1; i < axes.size(); i++) ss << \"x\" << axes[i];\n\n        // Test to see whether this should be treated as a point source\n        float minSigma = FWHMtoSIGMA(std::min(gauss.majorAxis(), gauss.minorAxis()));\n//        float delta = std::min(0.01,pow(10., floor(log10(minSigma/5.))));\n//        float delta = pow(10.,floor(log10(minSigma))-1.);\n        float delta = std::min(1. / 32.,\n                               pow(10., floor(log10(minSigma / 5.) / log10(2.)) * log10(2.)));\n\n        if (verbose)\n            ASKAPLOG_DEBUG_STR(logger, \"Adding Gaussian \" << gauss <<\n                               \" with flux=\" << gauss.flux() <<\n                               \" and bounds [\" << xmin << \":\" << xmax <<\n                               \",\" << ymin << \":\" << ymax\n                               << \"] (zeropoints = \" << zeroPointMax << \",\" << zeroPointMin <<\n                               \") (dimensions of array=\" << ss.str() <<\n                               \")  delta=\" << delta << \", minSigma = \" << minSigma);\n\n        if (xmax == xmin && ymax == ymin) { // single pixel only - add as point source\n            std::vector<double> pix(2);\n            pix[0] = gauss.xCenter();\n            pix[1] = gauss.yCenter();\n            if (verbose) {\n                ASKAPLOG_DEBUG_STR(logger, \"Single pixel only, so adding as point source.\");\n            }\n            return addPointSource(array, axes, pix, fluxGen, verbose);\n        }\n//                else if (delta < 1.e-3 && integrate) { // if it is really thin and we're integrating, use the 1D approximation\n        else if (zeroPointMin < 1. && integrate) {\n            if (verbose) {\n                // ASKAPLOG_DEBUG_STR(logger, \"Since delta = \" << delta << \"( 1./\" << 1. / delta\n                //                    << \")  (minSigma=\" << minSigma << \")  we use the 1D Gaussian function\");\n                ASKAPLOG_DEBUG_STR(logger, \"Since zeroPointMin=\" << zeroPointMin <<\n                                   \", we use the 1D Gaussian function. Have delta=\" <<\n                                   delta << \", minSigma=\" << minSigma);\n            }\n            add1DGaussian(array, axes, gauss, fluxGen, verbose);\n        } else {\n            // In this case, we need to add it as a Gaussian.\n\n            // Loop over all affected pixels and find the overall normalisation for each pixel\n\n            if (integrate && verbose)\n                ASKAPLOG_DEBUG_STR(logger, \"Integrating over \" <<\n                                   (xmax - xmin + 1) * (ymax - ymin + 1) <<\n                                   \" pixels with delta=\" << delta <<\n                                   \" (1./\" << 1. / delta <<\n                                   \")  (minSigma=\" << minSigma << \")\");\n            int nstep = int(1. / delta);\n            float inputGaussFlux = gauss.flux();\n            // make it a unit Gaussian.\n            // We then scale by the correct flux for each frequency channel.\n            gauss.setFlux(1);\n\n            float dx[2], dy[2], du[4], dv[4];\n            float mindu, mindv, separation, xpos, ypos;\n            float pixelVal;\n            float xScaleFactor, yScaleFactor;\n\n            size_t pix = 0;\n\n            for (int x = xmin; x <= xmax; x++) {\n\n                dx[0] = x - 0.5 - gauss.xCenter();\n                dx[1] = x + 0.5 - gauss.xCenter();\n\n                for (int y = ymin; y <= ymax; y++) {\n\n                    pixelVal = 0.;\n\n                    // Need to check whether a given pixel is affected by the Gaussian. To\n                    // do this, we look at the \"maximal\" ellipse - given by where the\n                    // Gaussian function drops to below the smallest float. If the closest\n                    // corner of the pixel to the centre of the Gaussian lies within this\n                    // ellipse, or if the Gaussian passes through the pixel, we do the\n                    // integration.\n\n                    dy[0] = y - 0.5 - gauss.yCenter();\n                    dy[1] = y + 0.5 - gauss.yCenter();\n\n                    for (int i = 0; i < 4; i++) {\n                        du[i] = dx[i % 2] * cos(gauss.PA()) + dy[i / 2] * sin(gauss.PA());\n                        dv[i] = dy[i / 2] * cos(gauss.PA()) - dx[i % 2] * sin(gauss.PA());\n                        // dv[i] = dx[i%2] * cos(gauss.PA()) + dy[i/2] * sin(gauss.PA());\n                        // du[i] = dy[i/2] * cos(gauss.PA()) - dx[i%2] * sin(gauss.PA());\n                    }\n\n                    mindu = fabs(du[0]);\n                    for (int i = 1; i < 4; i++) {\n                        if (fabs(du[i]) < mindu) {\n                            mindu = fabs(du[i]);\n                        }\n                    }\n\n                    mindv = fabs(dv[0]);\n                    for (int i = 1; i < 4; i++) {\n                        if (fabs(dv[i]) < mindv) {\n                            mindv = fabs(dv[i]);\n                        }\n                    }\n\n                    separation = mindv * mindv / (zeroPointMax * zeroPointMax) +\n                                 mindu * mindu / (zeroPointMin * zeroPointMin);\n\n                    float xlim1, xlim2, ylim1, ylim2;\n                    findEllipseLimits(zeroPointMax, zeroPointMin, gauss.PA(),\n                                      xlim1, xlim2, ylim1, ylim2);\n//              ASKAPLOG_DEBUG_STR(logger, \"separation = \" << separation << \" (needs to be less than 1, or dx within xlim etc\");\n//              ASKAPLOG_DEBUG_STR(logger, \"xlims,ylims: \" << xlim1 << \" \" << xlim2 << \" \" << ylim1 << \" \" << ylim2);\n//              ASKAPLOG_DEBUG_STR(logger, \"dxs, dys: \" << dx[0] << \" \" << dx[1] << \" \" << dy[0] << \" \" << dy[1]);\n\n                    if (separation <= 1. ||\n                            ((dx[0] <= xlim1 && dx[1] >= xlim2) &&\n                             (dy[0] <= ylim1 && dy[1] >= ylim2))) {\n//                                     ((du[0]*du[1] < 0 || du[0]*du[2] < 0 || du[0]*du[3] < 0) && mindv < zeroPointMax) ||\n//                                     ((dv[0]*dv[1] < 0 || dv[0]*dv[2] < 0 || dv[0]*dv[3] < 0) && mindu < zeroPointMin)) {\n                        // only consider pixels within the maximal ellipse\n\n                        if (integrate) {\n\n                            xpos = x - 0.5 - delta;\n\n                            for (int dx = 0; dx <= nstep; dx++) {\n                                xpos += delta;\n                                ypos = y - 0.5 - delta;\n\n                                for (int dy = 0; dy <= nstep; dy++) {\n                                    ypos += delta;\n\n                                    // This is integration using Simpson's rule. In each direction, the\n                                    // end points get a factor of 1, then odd steps get a factor of 4, and\n                                    // even steps 2. The whole sum then gets scaled by delta/3. for each\n                                    // dimension.\n\n                                    if (dx == 0 || dx == nstep) xScaleFactor = 1;\n                                    else xScaleFactor = (dx % 2 == 1) ? 4. : 2.;\n\n                                    if (dy == 0 || dy == nstep) yScaleFactor = 1;\n                                    else yScaleFactor = (dy % 2 == 1) ? 4. : 2.;\n\n                                    pixelVal += gauss(xpos, ypos) * (xScaleFactor * yScaleFactor);\n//                  if(gauss(xpos,ypos)>0.) ASKAPLOG_DEBUG_STR(logger, xpos << \" \" << ypos << \" \" << gauss(xpos,ypos));\n\n                                }\n                            }\n\n                            pixelVal *= (delta * delta / 9.);\n                        } else {\n                            pixelVal = gauss(x, y);\n                        }\n                    }\n\n//              ASKAPLOG_DEBUG_STR(logger, du[0] << \" \" << du[1] << \" \" << du[2] << \" \" << du[3] << \"     \" << dv[0] << \" \" << dv[1] <<\" \" << dv[2] << \" \" << dv[3]);\n//              ASKAPLOG_DEBUG_STR(logger, separation << \" \" << mindu << \" \" << mindv << \" \" << nstep << \" \" << delta << \" \" << delta*delta/9. << \" \" << pixelVal);\n\n                    // For this pixel, loop over all channels and assign the correctly-scaled pixel value.\n                    for (size_t istokes = 0; istokes < fluxGen.nStokes(); istokes++) {\n                        for (size_t z = 0; z < fluxGen.nChan(); z++) {\n                            pix = x + y * axes[0] + istokes * axes[0] * axes[1] +\n                                  z * axes[0] * axes[1] * axes[2];\n//              ASKAPLOG_DEBUG_STR(logger, \"Adding flux of \" << pixelVal*fluxGen.getFlux(z,istokes) << \" (from pixelval=\"<<pixelVal<<\" and fluxGen(z)=\"<<fluxGen.getFlux(z,istokes)<<\") to (x,y,z)=(\"<<x<<\",\"<<y<<\",\"<<z<<\")\");\n                            array[pix] += pixelVal * fluxGen.getFlux(z, istokes);\n                        }\n                    }\n\n                }\n            }\n\n            gauss.setFlux(inputGaussFlux);\n\n        }\n\n    }\n\n    return addSource;\n}\n\n// void add1DGaussian(std::vector<float>array,\n//                    std::vector<unsigned int> axes,\n//                    casa::Gaussian2D<casa::Double> gauss,\n//                    FluxGenerator &fluxGen,\n//                    bool verbose)\nvoid add1DGaussian(boost::shared_ptr<float[]>array,\n                   std::vector<unsigned int> axes,\n                   casa::Gaussian2D<casa::Double> gauss,\n                   FluxGenerator &fluxGen,\n                   bool verbose)\n{\n\n    enum DIR {VERTICAL = 0, HORIZONTAL};\n    DIR direction = VERTICAL;\n    bool specialCase = true;\n    double pa = gauss.PA();\n    pa = fmod(pa, M_PI);   // in case we get a value of PA outside [0,pi)\n    double sinpa = sin(pa);\n    double cospa = cos(pa);\n    int sign = pa < M_PI / 2. ? -1 : 1;\n\n    if (cospa == 0.) direction = HORIZONTAL;\n    else if (sinpa == 0.) direction = VERTICAL;\n    else specialCase = false;\n\n    double majorSigma = FWHMtoSIGMA(gauss.majorAxis());\n    double zeroPointMax = majorSigma * sqrt(-2.*log(1. / (MAXFLOAT * gauss.height())));\n    double length = 0.;\n    double increment = 0.;\n    double x = gauss.xCenter() - zeroPointMax * sinpa;\n    double y = gauss.yCenter() + zeroPointMax * cospa;\n    if (verbose) {\n        ASKAPLOG_DEBUG_STR(logger, \"Adding a 1D Gaussian: majorSigma = \" << majorSigma <<\n                           \", zpmax = \" << zeroPointMax\n                           << \", (xcentre,ycentre)=(\" << gauss.xCenter() <<\n                           \",\" << gauss.yCenter() << \")\" <<\n                           \", pa=\" << pa << \", sign=\" << sign\n                           << \", (xstart,ystart)=(\" << x << \",\" << y <<\n                           \") and axes=[\" << axes[0] << \",\" << axes[1] << \"]\");\n    }\n    int xref = lround(x);\n    int yref = lround(y);\n    int spatialPixel = xref + axes[0] * yref;\n    ASKAPLOG_DEBUG_STR(logger, \"add1DGaussian: x=\" << x << \", xref=\" << xref << \", y=\" << y <<\n                       \", yref=\" << yref << \", axes[0]=\" << axes[0] <<\n                       \", spatialPixel=\" << spatialPixel);\n    size_t pix = 0;\n    double pixelVal = 0.;\n    bool addPixel = true;\n\n    while (length < 2.*zeroPointMax) {\n\n        // is the current pixel in the bounds of the flux array?\n        addPixel = (xref >= 0 && xref < int(axes[0])) &&\n                   (yref >= 0 && yref < int(axes[1]));\n\n        if (!specialCase) {\n            direction = (fabs((yref + 0.5 * sign - y) / cospa) < fabs((xref + 0.5 - x) / sinpa)) ?\n                        VERTICAL : HORIZONTAL;\n        }\n\n        if (direction == VERTICAL) { // Moving vertically\n            increment = std::min(2.*zeroPointMax - length, fabs((yref + sign * 0.5 - y) / cospa));\n            ASKAPCHECK(increment > 0.,\n                       \"Vertical increment negative: increment=\" << increment <<\n                       \", sign=\" << sign << \", yref=\" << yref << \", y=\" << y <<\n                       \", cospa=\" << cospa << \", length=\" << length <<\n                       \", zpmax=\" << zeroPointMax << \", pa=\" << pa << \"=\" << pa * 180. / M_PI);\n            yref += sign;\n        } else if (direction == HORIZONTAL) { // Moving horizontally\n            increment = std::min(2.*zeroPointMax - length, fabs((xref + 0.5 - x) / sinpa));\n            ASKAPCHECK(increment > 0.,\n                       \"Horizontal increment negative: increment=\" << increment <<\n                       \", xref=\" << xref << \", x=\" << x << \", sinpa=\" << sinpa <<\n                       \", length=\" << length << \", zpmax=\" << zeroPointMax <<\n                       \", pa=\" << pa << \"=\" << pa * 180. / M_PI);\n            xref++;\n        }\n\n        if (addPixel) { // only add points if we're in the array boundaries\n            pixelVal = 0.5 * (erf((length + increment - zeroPointMax) / (M_SQRT2 * majorSigma)) -\n                              erf((length - zeroPointMax) / (M_SQRT2 * majorSigma)));\n\n            for (size_t istokes = 0; istokes < fluxGen.nStokes(); istokes++) {\n                for (size_t z = 0; z < fluxGen.nChan(); z++) {\n                    pix = spatialPixel + istokes * axes[0] * axes[1] +\n                          z * axes[0] * axes[1] * axes[2];\n                    array[pix] += pixelVal * fluxGen.getFlux(z, istokes);\n                }\n            }\n        }\n\n        x += increment * sinpa;\n//                y -= sign * increment * cospa;\n        y -= increment * cospa;\n        spatialPixel = xref + axes[0] * yref;\n        length += increment;\n        ASKAPLOG_DEBUG_STR(logger, \"add1DGaussian: x=\" << x << \", xref=\" << xref <<\n                           \", y=\" << y << \", yref=\" << yref <<\n                           \", axes[0]=\" << axes[0] << \", spatialPixel=\" << spatialPixel <<\n                           \", PIXELVAL=\" << pixelVal << \", increment=\" << increment <<\n                           \", direction=\" << direction << \", length=\" << length);\n\n    }\n}\n\n// bool addPointSource(std::vector<float>array,\n//                     std::vector<unsigned int> axes,\n//                     std::vector<double> pix,\n//                     FluxGenerator &fluxGen,\n//                     bool verbose)\nbool addPointSource(boost::shared_ptr<float[]>array,\n                    std::vector<unsigned int> axes,\n                    std::vector<double> pix,\n                    FluxGenerator &fluxGen,\n                    bool verbose)\n{\n\n    int xpix = lround(pix[0]);\n    int ypix = lround(pix[1]);\n\n    bool addSource = (xpix >= 0 && xpix < int(axes[0]) && ypix >= 0 && ypix < int(axes[1]));\n\n    if (addSource)  {\n\n        if (verbose) {\n            ASKAPLOG_DEBUG_STR(logger, \"Adding Point Source with x=\" << pix[0] <<\n                               \" & y=\" << pix[1] << \" and flux0=\" << fluxGen.getFlux(0) <<\n                               \" to  axes = [\" << axes[0] << \",\" << axes[1] << \"]\");\n        }\n\n        size_t loc = 0;\n        for (size_t istokes = 0; istokes < fluxGen.nStokes(); istokes++) {\n            for (size_t z = 0 ; z < fluxGen.nChan(); z++) {\n\n                loc = xpix + axes[0] * ypix + istokes * axes[0] * axes[1] +\n                      z * axes[0] * axes[1] * axes[2];\n\n                array[loc] += fluxGen.getFlux(z, istokes);\n\n            }\n        }\n\n    }\n\n    return addSource;\n\n}\n\n// bool addDisc(std::vector<float>array,\n//              std::vector<unsigned int> axes,\n//              Disc &disc,\n//              FluxGenerator &fluxGen,\n//              bool verbose)\nbool addDisc(boost::shared_ptr<float[]>array,\n             std::vector<unsigned int> axes,\n             Disc &disc,\n             FluxGenerator &fluxGen,\n             bool verbose)\n{\n\n    // ranges of pixels that will have flux added to them\n    int xmin = std::max(disc.xmin(), 0);\n    int xmax = std::min(disc.xmax(), int(axes[0] - 1));\n    int ymin = std::max(disc.ymin(), 0);\n    int ymax = std::min(disc.ymax(), int(axes[1] - 1));\n\n    bool addSource  = (xmax >= xmin) && (ymax >= ymin);\n    if (addSource) {  // if there are object pixels falling within the image boundaries\n\n        if (verbose)\n            ASKAPLOG_DEBUG_STR(logger, \"Adding Disc \" << disc <<  \" with x=[\" << xmin <<\n                               \",\" << xmax << \"] & y=[\" << ymin << \",\" << ymax <<\n                               \"] and flux0=\" << fluxGen.getFlux(0) <<\n                               \" to  axes = [\" << axes[0] << \",\" << axes[1] << \"]\");\n\n\n        for (int y = ymin; y <= ymax; y++) {\n            for (int x = xmin; x <= xmax; x++) {\n\n\n                double discFlux = disc.flux(x, y);\n\n                for (size_t istokes = 0; istokes < fluxGen.nStokes(); istokes++) {\n                    for (size_t z = 0 ; z < fluxGen.nChan(); z++) {\n                        size_t loc = x + axes[0] * y + istokes * axes[0] * axes[1] +\n                                     z * axes[0] * axes[1] * axes[2];\n                        array[loc] += discFlux * fluxGen.getFlux(z, istokes);\n                    }\n                }\n\n            }\n        }\n\n    }\n\n    return addSource;\n\n}\n\n\n}\n\n}\n", "meta": {"hexsha": "e729397290d0ea38899a495626f48e09d6cf2ffd", "size": 26502, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/Components/Analysis/simulations/current/simulationutilities/SimulationUtilities.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Analysis/simulations/current/simulationutilities/SimulationUtilities.cc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Analysis/simulations/current/simulationutilities/SimulationUtilities.cc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.344773791, "max_line_length": 223, "alphanum_fraction": 0.4898120897, "num_tokens": 6975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.02405355215109172, "lm_q1q2_score": 0.008216272464139815}}
{"text": "//\n// CPPINTS: A C++ Program to Generate Analytical Integrals Based on Gaussian\n// Form Primitive Functions\n//\n// Copyright (C) 2015 The State University of New York at Buffalo\n// This softare uses the MIT license as below:\n//\n//\tPermission is hereby granted, free of charge, to any person obtaining \n//\ta copy of this software and associated documentation files (the \"Software\"), \n//\tto deal in the Software without restriction, including without limitation \n//\tthe rights to use, copy, modify, merge, publish, distribute, sublicense, \n//\tand/or sell copies of the Software, and to permit persons to whom the Software \n//\tis 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//\t\t\t\t\t\t    \n//\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, \n//\tINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR \n//\tPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE \n//\tFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, \n//\tARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n//\n#include \"boost/lexical_cast.hpp\"\n#include <boost/algorithm/string.hpp>   // string handling\n#include <boost/filesystem.hpp>\n#include \"inttype.h\"\n#include \"derivinfor.h\"\n#include \"rr.h\"\n#include \"nonrr.h\"\n#include \"printing.h\"\n#include \"vrrinfor.h\"\n#include \"hrrinfor.h\"\n#include \"nonrrinfor.h\"\n#include \"sqints.h\"\nusing boost::lexical_cast;\nusing namespace boost::filesystem;\nusing namespace boost;\nusing namespace derivinfor;\nusing namespace printing;\nusing namespace inttype;\nusing namespace rr;\nusing namespace nonrr;\nusing namespace vrrinfor;\nusing namespace hrrinfor;\nusing namespace nonrrinfor;\nusing namespace sqints;\n\nvoid SQInts::intCodeGeneration()\n{\n\t// this is the output shell quartet list and unsolved \n\t// integral list passing from one code section to another\n\tvector<ShellQuartet> outputSQList; \n\tvector<set<int> > unsolvedList; \n\n\t// initilize the output sq list and unsolved integral list \n\t// for deriv job, we initilize it from the derivSQList\n\t// else we will do it from inputSQList in SQIntsInfor \n\tif (infor.getJobOrder() > 0) {\n\t\toutputSQList = infor.getDerivSQList();\n\t}else{\n\t\toutputSQList = infor.getInputSQList();\n\t}\n\tfor(int iSQ=0; iSQ<(int)outputSQList.size(); iSQ++) {\n\t\tset<int> list;\n\t\toutputSQList[iSQ].getIntegralList(list);\n\t\tunsolvedList.push_back(list);\n\t}\n\n\t///////////////////////////////////////////////////////////////////////\n\t// some note before we proceed the real work:                        //\n\t// the code generation is in reverse order of the real cpp file.     //\n\t// the result is generated first, then to it's previous section;     //\n\t// finally the generation will stop at the VRR section               //\n\t//                                                                   //\n\t//      %%%             CODE GENERATION STEP                         //\n\t///////////////////////////////////////////////////////////////////////\n\n\t////////////////////////////\n\t//   derivative section   //\n\t////////////////////////////\n\tNONRR derivJob(outputSQList,unsolvedList);\n\tsize_t nLHSDeriv = 0;\n\tif (infor.getJobOrder() > 0) {\n\n\t\t// generate the integrals\n\t\tderivJob.buildRRSQList();\n\n\t\t// add the deriv section to infor\n\t\tint moduleName = DERIV;\n\t\tinfor.appendCodeSection(moduleName);\n\n\t\t// let's carry the shell quartets to the next section\n\t\t// here the unsolved list must be in integral index\n\t\t// form, so do it before array index transformation\n\t\toutputSQList.clear();\n\t\tunsolvedList.clear();\n\t\toutputSQList = derivJob.getBottomSQList();\n\t\tunsolvedList = derivJob.getBottomIntList();\n\n\t\t// update nLHS\n\t\tnLHSDeriv = (size_t)derivJob.countLHSIntNumbers();\n\t}\n\tNONRRInfor derivJobInfor(infor,derivJob);\n\tinfor.updateWithArray(derivJobInfor.fileSplit());\n\n\t////////////////////////////\n\t// possible NON-RR section//\n\t////////////////////////////\n\tNONRR nonRRJob(outputSQList,unsolvedList);\n\tsize_t nLHSNonRR = 0;\n\tif (isNONRROper(infor.getOper())) {\n\n\t\t// build the rrsq\n\t\tnonRRJob.buildRRSQList();\n\n\t\t// let's carry the shell quartets to the next section\n\t\t// here the unsolved list must be in integral index\n\t\t// form, so do it before array index transformation\n\t\toutputSQList.clear();\n\t\tunsolvedList.clear();\n\t\toutputSQList = nonRRJob.getBottomSQList();\n\t\tunsolvedList = nonRRJob.getBottomIntList();\n\n\t\t// add the non-RR section to infor\n\t\tint moduleName = NON_RR;\n\t\tinfor.appendCodeSection(moduleName);\n\n\t\t// update nLHS\n\t\tnLHSNonRR  = (size_t)nonRRJob.countLHSIntNumbers();\n\t}\n\tNONRRInfor nonRRJobInfor(infor,nonRRJob);\n\tinfor.updateWithArray(nonRRJobInfor.fileSplit());\n\n\t////////////////////////////\n\t// second HRR section     //\n\t////////////////////////////\n\tRR hrr2(HRR2,HRR,outputSQList,unsolvedList);\n\tsize_t nLHSHRR2 = 0;\n\tint firstSide  = NULL_POS;\n\tint secondSide = NULL_POS;\n\tif (infor.hasHRR()) {\n\n\t\t// determine the first and second side\n\t\thrr2.sideDeterminationInHRR(firstSide,secondSide);\n\n\t\t// now do the second side HRR\n\t\t// for generated code, second side is performed after\n\t\t// first side; so in generation of code second side \n\t\t// is prior to the first side\n\t\tif (secondSide != NULL_POS) {\n\n\t\t\t// generat rrsq\n\t\t\thrr2.generateRRSQList(secondSide);\n\n\t\t\t// let's carry the shell quartets to the next section\n\t\t\t// here the unsolved list must be in integral index\n\t\t\t// form, so do it before array index transformation\n\t\t\toutputSQList.clear();\n\t\t\tunsolvedList.clear();\n\t\t\toutputSQList = hrr2.getHRRBottomSQList();\n\t\t\tunsolvedList = hrr2.getHRRBottomIntList();\n\n\t\t\t// add the HRR2 section to infor\n\t\t\tint moduleName = HRR2;\n\t\t\tinfor.appendCodeSection(moduleName);\n\n\t\t\t// update nLHS\n\t\t\tnLHSHRR2   = (size_t)hrr2.countLHSIntNumbers();\n\t\t}\n\t}\n\tHRRInfor HRR2JobInfor(infor,hrr2);\n\tinfor.updateWithArray(HRR2JobInfor.fileSplit());\n\n\t////////////////////////////\n\t//  first HRR section     //\n\t////////////////////////////\n\tRR hrr1(HRR1,HRR,outputSQList,unsolvedList);\n\tsize_t nLHSHRR1 = 0;\n\tif (firstSide != NULL_POS) {\n\n\t\t// now do the first side\n\t\thrr1.generateRRSQList(firstSide);\n\n\t\t// now rewrite the shell quartet list\n\t\toutputSQList.clear();\n\t\tunsolvedList.clear();\n\t\toutputSQList = hrr1.getHRRBottomSQList();\n\t\tunsolvedList = hrr1.getHRRBottomIntList();\n\n\t\t// add the HRR1 section to infor\n\t\tint moduleName = HRR1;\n\t\tinfor.appendCodeSection(moduleName);\n\n\t\t// update nLHS\n\t\tnLHSHRR1   = (size_t)hrr1.countLHSIntNumbers();\n\t}\n\tHRRInfor HRR1JobInfor(infor,hrr1);\n\tinfor.updateWithArray(HRR1JobInfor.fileSplit());\n\n\t////////////////////////////\n\t//      VRR section       //\n\t////////////////////////////\n\tRR vrr(VRR,infor.getVRRMethod(),outputSQList,unsolvedList);\n\tvrr.generateRRSQList(NULL_POS);\n\n\t// update nLHS\n\tsize_t nLHSVRR = (size_t)vrr.countLHSIntNumbers();\n\n\t// add the VRR section to infor\n\tint moduleName = VRR;\n\tinfor.appendCodeSection(moduleName);\n\n\t// now build the vrr infor\n\tVRRInfor vrrInfor(infor,vrr);\n\tinfor.updateWithArray(vrrInfor.fileSplit());\n\n\t///////////////////////////////////////////////////////////////////////\n\t// now let's analyze the situation of file split. All modules has    //\n\t// been set up, and now it's time to see whether we need to make     //\n\t// some changes                                                      //\n\t//      %%%%            FILE SPLIT DETERMINATION STEP                //\n\t///////////////////////////////////////////////////////////////////////\n\n\t// do we need to re-evalate the file split status\n\t// for all of codes?\n\t// we do this when the main driver cpp file becomes too large\n\tsize_t nLHSMainCPP = 0;\n\tconst vector<int>& secInfor = infor.getSectionInfor(); \n\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\t\tint sec = secInfor[iSec];\n\t\tif (sec == DERIV) {\n\t\t\tif (! derivJobInfor.fileSplit()) {\n\t\t\t\tnLHSMainCPP = nLHSMainCPP + nLHSDeriv;\n\t\t\t}\n\t\t}else if (sec == NON_RR) {\n\t\t\tif (! nonRRJobInfor.fileSplit()) {\n\t\t\t\tnLHSMainCPP = nLHSMainCPP + nLHSNonRR;\n\t\t\t}\n\t\t}else if (sec == HRR2) {\n\t\t\tif (! HRR2JobInfor.fileSplit()) {\n\t\t\t\tnLHSMainCPP = nLHSMainCPP + nLHSHRR2;\n\t\t\t}\n\t\t}else if (sec == HRR1) {\n\t\t\tif (! HRR1JobInfor.fileSplit()) {\n\t\t\t\tnLHSMainCPP = nLHSMainCPP + nLHSHRR1;\n\t\t\t}\n\t\t}else if (sec == VRR) {\n\t\t\tif (! vrrInfor.fileSplit()) {\n\t\t\t\tnLHSMainCPP = nLHSMainCPP + nLHSVRR;\n\t\t\t}\n\t\t}\n\t}\n\n\t// do we need to split the single cpp file?\n\tbool doSplit = false;\n\tdouble nTotalLHSCoef = infor.totalLHSScaleFac;\n\tint nTotalLHSLimit   = infor.nTotalLHSLimit;\n\tif (nLHSMainCPP>(size_t)(nTotalLHSLimit*(1+nTotalLHSCoef))) {\n\t\tdoSplit = true;\n\t\tinfor.updateWithArray(true);\n\t}\n\n\t// now let's update the infor for sections\n\t// from the last section to VRR\n\tif (doSplit) {\n\t\tsize_t nLHS = nLHSMainCPP;\n\t\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\n\t\t\t// now let's update\n\t\t\tint sec = secInfor[iSec];\n\t\t\tif (sec == DERIV) {\n\t\t\t\tif (! derivJobInfor.fileSplit()) {\n\t\t\t\t\tderivJobInfor.updateFileSplit();\n\t\t\t\t\tnLHS = nLHS - nLHSDeriv;\n\t\t\t\t}\n\t\t\t}else if (sec == NON_RR) {\n\t\t\t\tif (! nonRRJobInfor.fileSplit()) {\n\t\t\t\t\tnonRRJobInfor.updateFileSplit();\n\t\t\t\t\tnLHS = nLHS - nLHSNonRR;\n\t\t\t\t}\n\t\t\t}else if (sec == HRR2) {\n\t\t\t\tif (! HRR2JobInfor.fileSplit()) {\n\t\t\t\t\tHRR2JobInfor.updateFileSplit();\n\t\t\t\t\tnLHS = nLHS - nLHSHRR2;\n\t\t\t\t}\n\t\t\t}else if (sec == HRR1) {\n\t\t\t\tif (! HRR1JobInfor.fileSplit()) {\n\t\t\t\t\tHRR1JobInfor.updateFileSplit();\n\t\t\t\t\tnLHS = nLHS - nLHSHRR1;\n\t\t\t\t}\n\t\t\t}else if (sec == VRR) {\n\t\t\t\tif (! vrrInfor.fileSplit()) {\n\t\t\t\t\tvrrInfor.updateFileSplit();\n\t\t\t\t\tnLHS = nLHS - nLHSVRR;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// do we get to a break?\n\t\t\tif (nLHS<(size_t)(nTotalLHSLimit*(1+nTotalLHSCoef))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t///////////////////////////////////////////////////////////////////////\n\t//  based on the file split status, we can figure out the input      //\n\t//  and output shell quartet status, in array or var?                //\n\t//    %%%%    SET UP MODULE INPUT/OUPUT STATUS                       //\n\t///////////////////////////////////////////////////////////////////////\n\n\t// firstly for VRR, update it's output when it's not in file split\n\tif (! vrrInfor.fileSplit()) {\n\t\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\t\t\tint sec = secInfor[iSec];\n\t\t\tif (sec == VRR) break;\n\t\t\tif (sec == DERIV && derivJobInfor.fileSplit()) {\n\t\t\t\tconst vector<ShellQuartet>& output = derivJobInfor.getInputSQList();\n\t\t\t\tvrrInfor.updateOutputSQInArray(output);\n\t\t\t}else if (sec == NON_RR && nonRRJobInfor.fileSplit()) {\n\t\t\t\tconst vector<ShellQuartet>& output = nonRRJobInfor.getInputSQList();\n\t\t\t\tvrrInfor.updateOutputSQInArray(output);\n\t\t\t}else if (sec == HRR2 && HRR2JobInfor.fileSplit()) {\n\t\t\t\tconst vector<ShellQuartet>& output = HRR2JobInfor.getInputSQList();\n\t\t\t\tvrrInfor.updateOutputSQInArray(output);\n\t\t\t}else if (sec == HRR1 && HRR1JobInfor.fileSplit()) {\n\t\t\t\tconst vector<ShellQuartet>& output = HRR1JobInfor.getInputSQList();\n\t\t\t\tvrrInfor.updateOutputSQInArray(output);\n\t\t\t}\n\t\t}\n\t}else{\n\t\tvrrInfor.subFilesForming(infor,vrr);\n\t}\n\n\t// form output sq which are in array status\n\tvector<ShellQuartet> sqlist;\n\tsqlist.reserve(500);\n\tconst vector<ShellQuartet>& vrrOutputSQ = vrrInfor.getOutputSQList();\n\tconst vector<int>& vrrOutputSQStatus    = vrrInfor.getOutputSQStatus();\n\tfor(int iSQ=0; iSQ<(int)vrrOutputSQ.size(); iSQ++) {\n\t\tif (inArrayStatus(vrrOutputSQStatus[iSQ])) {\n\t\t\tsqlist.push_back(vrrOutputSQ[iSQ]);\n\t\t}\n\t}\n\n\t// now VRR output sq has fixed, reversely update all of other modules\n\t// which has VRR module results. We note, that we only do it to these modules\n\t// when they are not in file split status \n\tif (sqlist.size() > 0) {\n\t\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\t\t\tint sec = secInfor[iSec];\n\t\t\tif (sec == VRR) break;\n\t\t\tif (sec == DERIV && ! derivJobInfor.fileSplit()) {\n\t\t\t\tderivJobInfor.updateInputSQInArray(sqlist);\n\t\t\t}else if (sec == NON_RR && ! nonRRJobInfor.fileSplit()) {\n\t\t\t\tnonRRJobInfor.updateInputSQInArray(sqlist);\n\t\t\t}else if (sec == HRR2 && ! HRR2JobInfor.fileSplit()) {\n\t\t\t\tHRR2JobInfor.updateInputSQInArray(sqlist);\n\t\t\t}else if (sec == HRR1 && ! HRR1JobInfor.fileSplit()) {\n\t\t\t\tHRR1JobInfor.updateInputSQInArray(sqlist);\n\t\t\t}\n\t\t}\n\t}\n\n\t// now let's do HRR1, we may not have HRR\n\tif (infor.hasSection(HRR1)) {\n\n\t\t// update the module output from all of following modules\n\t\tif (! HRR1JobInfor.fileSplit()) {\n\t\t\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\t\t\t\tint sec = secInfor[iSec];\n\t\t\t\tif (sec == HRR1) break;\n\t\t\t\tif (sec == DERIV && derivJobInfor.fileSplit()) {\n\t\t\t\t\tconst vector<ShellQuartet>& output = derivJobInfor.getInputSQList();\n\t\t\t\t\tHRR1JobInfor.updateOutputSQInArray(output);\n\t\t\t\t}else if (sec == NON_RR && nonRRJobInfor.fileSplit()) {\n\t\t\t\t\tconst vector<ShellQuartet>& output = nonRRJobInfor.getInputSQList();\n\t\t\t\t\tHRR1JobInfor.updateOutputSQInArray(output);\n\t\t\t\t}else if (sec == HRR2 && HRR2JobInfor.fileSplit()) {\n\t\t\t\t\tconst vector<ShellQuartet>& output = HRR2JobInfor.getInputSQList();\n\t\t\t\t\tHRR1JobInfor.updateOutputSQInArray(output);\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t\tHRR1JobInfor.formSubFiles(infor,hrr1);\n\t\t}\n\n\t\t// form output sq which are in array status\n\t\tsqlist.clear();\n\t\tconst vector<ShellQuartet>& outputSQ = HRR1JobInfor.getOutputSQList();\n\t\tconst vector<int>& outputSQStatus    = HRR1JobInfor.getOutputSQStatus();\n\t\tfor(int iSQ=0; iSQ<(int)outputSQ.size(); iSQ++) {\n\t\t\tif (inArrayStatus(outputSQStatus[iSQ])) {\n\t\t\t\tsqlist.push_back(outputSQ[iSQ]);\n\t\t\t}\n\t\t}\n\n\t\t// now HRR1 output sq has fixed, reversely update all of other modules\n\t\t// which has HRR1 module results. We note, that we only do it to these modules\n\t\t// when they are not in file split status \n\t\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\t\t\tint sec = secInfor[iSec];\n\t\t\tif (sec == HRR1) break;\n\t\t\tif (sec == DERIV && ! derivJobInfor.fileSplit()) {\n\t\t\t\tderivJobInfor.updateInputSQInArray(sqlist);\n\t\t\t}else if (sec == NON_RR && ! nonRRJobInfor.fileSplit()) {\n\t\t\t\tnonRRJobInfor.updateInputSQInArray(sqlist);\n\t\t\t}else if (sec == HRR2 && ! HRR2JobInfor.fileSplit()) {\n\t\t\t\tHRR2JobInfor.updateInputSQInArray(sqlist);\n\t\t\t}\n\t\t}\n\t}\n\n\t// now let's do HRR2, we may not have HRR2\n\tif (infor.hasSection(HRR2)) {\n\n\t\t// update the module output from all of following modules\n\t\tif (! HRR2JobInfor.fileSplit()) {\n\t\t\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\t\t\t\tint sec = secInfor[iSec];\n\t\t\t\tif (sec == HRR2) break;\n\t\t\t\tif (sec == DERIV && derivJobInfor.fileSplit()) {\n\t\t\t\t\tconst vector<ShellQuartet>& output = derivJobInfor.getInputSQList();\n\t\t\t\t\tHRR2JobInfor.updateOutputSQInArray(output);\n\t\t\t\t}else if (sec == NON_RR && nonRRJobInfor.fileSplit()) {\n\t\t\t\t\tconst vector<ShellQuartet>& output = nonRRJobInfor.getInputSQList();\n\t\t\t\t\tHRR2JobInfor.updateOutputSQInArray(output);\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t\tHRR2JobInfor.formSubFiles(infor,hrr2);\n\t\t}\n\n\t\t// form output sq which are in array status\n\t\tsqlist.clear();\n\t\tconst vector<ShellQuartet>& outputSQ = HRR2JobInfor.getOutputSQList();\n\t\tconst vector<int>& outputSQStatus    = HRR2JobInfor.getOutputSQStatus();\n\t\tfor(int iSQ=0; iSQ<(int)outputSQ.size(); iSQ++) {\n\t\t\tif (inArrayStatus(outputSQStatus[iSQ])) {\n\t\t\t\tsqlist.push_back(outputSQ[iSQ]);\n\t\t\t}\n\t\t}\n\n\t\t// now HRR2 output sq has fixed, reversely update all of other modules\n\t\t// which has HRR2 module results. We note, that we only do it to these modules\n\t\t// when they are not in file split status \n\t\tif (sqlist.size() > 0) {\n\t\t\tfor(int iSec=0; iSec<(int)secInfor.size(); iSec++) {\n\t\t\t\tint sec = secInfor[iSec];\n\t\t\t\tif (sec == HRR2) break;\n\t\t\t\tif (sec == DERIV && ! derivJobInfor.fileSplit()) {\n\t\t\t\t\tderivJobInfor.updateInputSQInArray(sqlist);\n\t\t\t\t}else if (sec == NON_RR && ! nonRRJobInfor.fileSplit()) {\n\t\t\t\t\tnonRRJobInfor.updateInputSQInArray(sqlist);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// now let's do NON-RR\n\tif (infor.hasSection(NON_RR)) {\n\n\t\t// update the module output for DERIV module\n\t\tif (! nonRRJobInfor.fileSplit()) {\n\t\t\tif (infor.hasSection(DERIV) && derivJobInfor.fileSplit()) {\n\t\t\t\tconst vector<ShellQuartet>& output = derivJobInfor.getInputSQList();\n\t\t\t\tnonRRJobInfor.updateOutputSQInArray(output);\n\t\t\t}\n\t\t}else{\n\t\t\tnonRRJobInfor.formSubFiles(infor,nonRRJob);\n\t\t}\n\n\t\t// form output sq which are in array status\n\t\tsqlist.clear();\n\t\tconst vector<ShellQuartet>& outputSQ = nonRRJobInfor.getOutputSQList();\n\t\tconst vector<int>& outputSQStatus    = nonRRJobInfor.getOutputSQStatus();\n\t\tfor(int iSQ=0; iSQ<(int)outputSQ.size(); iSQ++) {\n\t\t\tif (inArrayStatus(outputSQStatus[iSQ])) {\n\t\t\t\tsqlist.push_back(outputSQ[iSQ]);\n\t\t\t}\n\t\t}\n\n\t\t// we only need to consider the DERIV module\n\t\tif (sqlist.size() > 0) {\n\t\t\tif (infor.hasSection(DERIV) && ! derivJobInfor.fileSplit()) {\n\t\t\t\tderivJobInfor.updateInputSQInArray(sqlist);\n\t\t\t}\n\t\t}\n\t}\n\n\t// for deriv job we do not need to update the input and output\n\t// all of input shell quartet updating are finished\n\t// and output sq must be global results\n\tif (infor.hasSection(DERIV) && derivJobInfor.fileSplit()) {\n\t\tderivJobInfor.formSubFiles(infor,derivJob);\n\t}\n\n\t///////////////////////////////////////////////////////////////////////\n\t//               %%%%     PRINT OUT THE CODES                        //\n\t///////////////////////////////////////////////////////////////////////\n\tvrr.vrrPrint(infor,vrrInfor);\n\tif (infor.hasSection(HRR1)) {\n\t\thrr1.hrrPrint(infor,HRR1JobInfor);\n\t}\n\tif (infor.hasSection(HRR2)) {\n\t\thrr2.hrrPrint(infor,HRR2JobInfor);\n\t}\n\tif (infor.hasSection(NON_RR)) {\n\t\tnonRRJob.print(infor,nonRRJobInfor);\n\t}\n\tif (infor.hasSection(DERIV)) {\n\t\tderivJob.print(infor,derivJobInfor);\n\t}\n}\n\nvoid SQInts::assembleCPPFiles() const\n{\n\t// open the top cpp file\n\tstring cppFile = infor.getWorkFuncName(false,NULL_POS,-1,true);\n\tofstream CPP;\n\tCPP.open(cppFile.c_str());\n\n\t// generate the head of file\n\tinfor.headPrinting(CPP);\n\n\t// now append all of function prototype to the head\n\t// particularly, because the vrr contraction may also\n\t// in a seperate function, therefore we need to check it\n\tvector<int> modules(infor.getSectionInfor());\n\tfor(int iFunc=modules.size()-1; iFunc>=0; iFunc--) {\n\t\tint module = modules[iFunc];\n\t\tappendFuncPrototype(module,CPP);\n\t}\n\tif (hasFileDefined(VRR_CONT)) {\n\t\tappendFuncPrototype(VRR_CONT,CPP);\n\t}\n\n\t// now it's the function name\n\tstring func = infor.getFuncName();\n\tfunc = \"void \" + func;\n\tstring arg  = infor.getArgList();\n\tstring line = func + \"(\" + arg + \")\";\n\tCPP << line << endl;\n\tCPP << \"{\" << endl;\n\n\t//\n\t// now we begin to generate code starting from VRR \n\t// section, until the final section is met\n\t//\n\n\t//////////////////////////////\n\t//       VRR section        //\n\t//////////////////////////////\n\n\t// generate the VRR head\n\t// append it to the main cpp file\n\tint moduleName = VRR_HEAD;\n\tappendFile(moduleName,CPP);\n\n\t// now it's the main body of VRR\n\tmoduleName = VRR;\n\tif (hasFileDefined(moduleName)) {\n\t\tformWorkFile(moduleName);\n\t\tformFunctionCall(moduleName,CPP);\n\t}else{\n\t\tappendFile(moduleName,CPP);\n\t}\n\n\t// contraction part\n\t// for contraction if it's not in file split\n\t// mode, it will be with VRR code\n\tmoduleName = VRR_CONT;\n\tif (hasFileDefined(moduleName)) {\n\t\tformWorkFile(moduleName);\n\t\tformFunctionCall(moduleName,CPP);\n\t}\n\n\t// now let's close the VRR part\n\t// determine the number space for printing etc.\n\tint oper = infor.getOper();\n\tint nSpace = getNSpaceByOper(oper);\n\tint nSpaceStop = 2;\n\tif (resultIntegralHasAdditionalOffset(oper)) nSpaceStop += 2;\n\n\t// finally, we need to add braket closure to the vrr body\n\tline = \"}\";\n\tfor(int iSpace= nSpace-2; iSpace>=nSpaceStop; iSpace = iSpace - 2) {\n\t\tprintLine(iSpace,line,CPP);\n\t}\n\n\t// if we have significance test, then we may\n\t// test the significance first\n\t// if VRR step all of integrals are omitted,\n\t// then we do not need to do HRR accordingly\n\tif(sigCheck(oper) && ! infor.isLastSection(VRR)) {\n\t\tCPP << endl;\n\t\tline = \"/************************************************************\";\n\t\tprintLine(nSpaceStop,line,CPP);\n\t\tline = \" * let's see the significance test result. if VRR result is\";\n\t\tprintLine(nSpaceStop,line,CPP);\n\t\tline = \" * insignificant, there's no need to do following codes\";\n\t\tprintLine(nSpaceStop,line,CPP);\n\t\tline = \" ************************************************************/\";\n\t\tprintLine(nSpaceStop,line,CPP);\n\n\t\t// the handling of significance at the bottom of VRR \n\t\t// this is to see whether we do HRR part\n\t\t// for the case that VRR/HRR are in a loop \n\t\t// we can not return, just use continue\n\t\tline = \"if (! isSignificant) return;\";\n\t\tif (resultIntegralHasAdditionalOffset(oper)) {\n\t\t\tline = \"if (! isSignificant) continue;\";\n\t\t}\n\t\tprintLine(nSpaceStop,line,CPP);\n\t}\t\n\n\t//////////////////////////////\n\t//       HRR1 section etc.  //\n\t//////////////////////////////\n\tfor(int iFunc=modules.size()-1; iFunc>=0; iFunc--) {\n\t\tint module = modules[iFunc];\n\t\tif (module == VRR || module == VRR_CONT) continue;\n\t\tif (hasFileDefined(module)) {\n\n\t\t\t// form the work file\n\t\t\tformWorkFile(module);\n\n\t\t\t// append the main module file if we have\n\t\t\t// this contains the variables declare or \n\t\t\t// the results declare etc.\n\t\t\tappendFile(module,CPP,false);\n\n\t\t\t// form the function call to the result cpp file\n\t\t\tformFunctionCall(module,CPP);\n\t\t}else{\n\t\t\tappendFile(module,CPP);\n\t\t}\n\t}\n\n\t// now finalize the cpp file\n\tif (oper == ESP) {\n\t\tCPP << \"  }\" << endl;\n\t\tCPP << \"}\" << endl;\n\t}else{\n\t\tCPP << \"}\" << endl;\n\t}\n\tCPP.close();\n}\n\nbool SQInts::isFileExist() const \n{\n\tstring fileName = infor.getWorkFuncName(false,NULL_POS,-1,true);\n\tpath cppFile(fileName.c_str());\n\tif (exists(cppFile)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool SQInts::hasFileDefined(int moduleName) const\n{\n\t// we will check t he function statement\n\t// if it has, then we have the files for this section\n\tint module = -1;\n\tif (moduleName == VRR) {\n\t\tmodule = VRR_FUNC_STATEMENT;\n\t}else if (moduleName == VRR_CONT) {\n\t\tmodule = VRR_CONT_STATEMENT;\n\t}else if (moduleName == HRR1) {\n\t\tmodule = HRR1_FUNC_STATEMENT;\n\t}else if (moduleName == HRR2) {\n\t\tmodule = HRR2_FUNC_STATEMENT;\n\t}else if (moduleName == NON_RR) {\n\t\tmodule = NON_RR_FUNC_STATEMENT;\n\t}else if (moduleName == DERIV) {\n\t\tmodule = DERIV_FUNC_STATEMENT;\n\t}else {\n\t\tcrash(true,\"the input module name is invalid in SQInts::hasFileDefined\");\n\t}\n\tbool onlyWithFuncName = false;\n\tbool inFinalDir = false;\n\tstring pro = infor.getWorkFuncName(onlyWithFuncName,module,-1,inFinalDir);\n\tpath p(pro.c_str());\n\tif (exists(p)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid SQInts::appendFuncPrototype(int moduleName, ofstream& CPP) const\n{\n\t// deriv the function prototype\n\t// get the name\n\tint module = -1;\n\tif (moduleName == VRR) {\n\t\tmodule = VRR_FUNC_STATEMENT;\n\t}else if (moduleName == VRR_CONT) {\n\t\tmodule = VRR_CONT_STATEMENT;\n\t}else if (moduleName == HRR1) {\n\t\tmodule = HRR1_FUNC_STATEMENT;\n\t}else if (moduleName == HRR2) {\n\t\tmodule = HRR2_FUNC_STATEMENT;\n\t}else if (moduleName == NON_RR) {\n\t\tmodule = NON_RR_FUNC_STATEMENT;\n\t}else if (moduleName == DERIV) {\n\t\tmodule = DERIV_FUNC_STATEMENT;\n\t}else {\n\t\tcrash(true,\"the input module name is invalid in SQInts::appendFuncPrototype\");\n\t}\n\n\t// now append the prototype to the main cpp file\n\t// we note  that if the module is not in file split mode, we do not\n\t// have the prototype file\n\t// so we check it's existence\n\tbool onlyWithFuncName = false;\n\tbool inFinalDir = false;\n\tstring pro = infor.getWorkFuncName(onlyWithFuncName,module,-1,inFinalDir);\n\tpath p(pro.c_str());\n\tif (! exists(p)) {\n\t\treturn;\n\t}\n\n\t// now do the work\n\tifstream PRO;\n\tPRO.open(pro.c_str(),ios::in);\n\tstring line;\n\twhile(getline(PRO,line)) {\n\t\tCPP << line << endl;\n\t}\n\tPRO.close();\n}\n\nvoid SQInts::formFunctionCall(int moduleName, ofstream& CPP) const\n{\n\t// deriv the function prototype\n\t// get the name\n\tint module = -1;\n\tif (moduleName == VRR) {\n\t\tmodule = VRR_FUNC_STATEMENT;\n\t}else if (moduleName == VRR_CONT) {\n\t\tmodule = VRR_CONT_STATEMENT;\n\t}else if (moduleName == HRR1) {\n\t\tmodule = HRR1_FUNC_STATEMENT;\n\t}else if (moduleName == HRR2) {\n\t\tmodule = HRR2_FUNC_STATEMENT;\n\t}else if (moduleName == NON_RR) {\n\t\tmodule = NON_RR_FUNC_STATEMENT;\n\t}else if (moduleName == DERIV) {\n\t\tmodule = DERIV_FUNC_STATEMENT;\n\t}else {\n\t\tcrash(true,\"the input module name is invalid in SQInts::appendFuncPrototype\");\n\t}\n\n\t// now append the prototype to the main cpp file\n\t// we note  that if the module is not in file split mode, we do not\n\t// have the prototype file\n\t// so we check it's existence\n\tbool onlyWithFuncName = false;\n\tbool inFinalDir = false;\n\tstring pro = infor.getWorkFuncName(onlyWithFuncName,module,-1,inFinalDir);\n\tpath p(pro.c_str());\n\tif (! exists(p)) {\n\t\tcout << \"the module name \" << moduleName << endl;\n\t\tcrash(true, \"the prototype file does not exist in formFunctionCall of sqints\");\n\t}\n\n\t// now get the function statement\n\tvector<string> prototype;\n\tprototype.reserve(200);\n\tifstream PRO;\n\tPRO.open(pro.c_str(),ios::in);\n\tstring line;\n\twhile(getline(PRO,line)) {\n\n\t\t// get the function statement\n\t\tif (line.find(\"void\") == std::string::npos) continue;\n\t\tstring statement = line;\n\n\t\t// now get rid of the type information etc.\n\t\tLineParse lp(statement);\n\t\tstring result;\n\t\tresult.reserve(1000);\n\t\tfor(int i=0; i<lp.getNPieces(); i++) {\n\n\t\t\t// we begin to determine that whether this is variable name\n\t\t\tstring val = lp.findValue(i);\n\n\t\t\t// check whether this is the function name\n\t\t\tif (val.find(\"(\")!=std::string::npos) {\n\t\t\t\tint pos = val.find(\"(\");\n\t\t\t\tstring v = val.substr(0,pos+1);\n\t\t\t\tresult = result + v;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// omit these values\n\t\t\tif (val.find(\"const\")!=std::string::npos) continue;\n\t\t\tif (val.find(\"vector\")!=std::string::npos) continue;\n\t\t\tif (val.find(\"Double\")!=std::string::npos) continue;\n\t\t\tif (val.find(\"LocalMemScr\")!=std::string::npos) continue;\n\t\t\tif (val.find(\"void\")!=std::string::npos) continue;\n\n\t\t\t// if the name is turned out to be a shell quartet name,\n\t\t\t// then this is must be VRR's output result or HRR input\n\t\t\t// result array\n\t\t\t// since we all use pointer, we need to pass in pointer inside\n\t\t\tif (val.find(\"SQ\")!=std::string::npos) {\n\n\t\t\t\t// see that whether the name has ' additional to the name or not\n\t\t\t\tint len = val.length();\n\t\t\t\tif (val[len-1] == ',') {\n\t\t\t\t\tval[len-1] = '[';\n\t\t\t\t\tval.append(\"0],\");\n\t\t\t\t\tval = \"&\" + val;\n\t\t\t\t}else{\n\t\t\t\t\tval = \"&\" + val + \"[0]\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// append it to the result\n\t\t\tresult = result + val;\n\t\t}\n\t\tprototype.push_back(result);\n\t}\n\tPRO.close();\n\n\t// determine the nspace\n\tint nSpace = 2;\n\tint oper = infor.getOper();\n\tif (moduleName == VRR || moduleName == VRR_CONT) {\n\t\tnSpace = getNSpaceByOper(oper);\n\t}\n\tif (resultIntegralHasAdditionalOffset(oper)) {\n\t\tnSpace += 2;\n\t}\n\n\t// finally, append these function calls to the main file\n\tCPP << endl;\n\tfor(int i=0; i<(int)prototype.size(); i++) {\n\t\tstring func = prototype[i];\n\t\tprintLine(nSpace,func,CPP);\n\t\tCPP << endl;\n\t}\n\tCPP << endl;\n}\n\nvoid SQInts::formWorkFile(int moduleName) const \n{\n\t// let's see how many sub files we have for this given module\n\t// except VRR, VRR only have one module\n\tint iFile = 1;\n\tint nFiles = 0;\n\tbool onlyWithFuncName = false;\n\tbool inFinalDir = false;\n\twhile(true) {\n\t\tstring fileName = infor.getWorkFuncName(onlyWithFuncName,moduleName,iFile,inFinalDir);\n\t\tpath cppFile(fileName.c_str());\n\t\tif (exists(cppFile)) {\n\t\t\tnFiles++;\n\t\t}else{\n\t\t\tbreak;\n\t\t}\n\t\tiFile++;\n\t}\n\n\t// we should not have 0 sub files\n\t// because it already in file split mode\n\tif (nFiles == 0) {\n\t\tcrash(true,\"why there are no subfiles in SQInts::formWorkFile\");\n\t}\n\n\t// deriv the function prototype\n\t// get the name\n\tint module = -1;\n\tif (moduleName == VRR) {\n\t\tmodule = VRR_FUNC_STATEMENT;\n\t}else if (moduleName == VRR_CONT) {\n\t\tmodule = VRR_CONT_STATEMENT;\n\t}else if (moduleName == HRR1) {\n\t\tmodule = HRR1_FUNC_STATEMENT;\n\t}else if (moduleName == HRR2) {\n\t\tmodule = HRR2_FUNC_STATEMENT;\n\t}else if (moduleName == NON_RR) {\n\t\tmodule = NON_RR_FUNC_STATEMENT;\n\t}else if (moduleName == DERIV) {\n\t\tmodule = DERIV_FUNC_STATEMENT;\n\t}else {\n\t\tcrash(true,\"the input module name is invalid in SQInts::formWorkFile\");\n\t}\n\n\t// now let's deriv the prototype\n\tvector<string> prototype;\n\tprototype.reserve(nFiles);\n\tstring pro = infor.getWorkFuncName(onlyWithFuncName,module,-1,inFinalDir);\n\tpath p(pro.c_str());\n\tif (! exists(p)) {\n\t\tcout << \"Missing function prototype file \" << pro << endl;\n\t\tcrash(true, \"Why the function prototype file does not exist??? we need it in formWorkFile\");\n\t}\n\tifstream PRO;\n\tPRO.open(pro.c_str(),ios::in);\n\tstring line;\n\twhile(getline(PRO,line)) {\n\t\tif (line.find(\"void\") == std::string::npos) continue;\n\t\tif (line.find(\";\") != std::string::npos) {\n\t\t\tint pos = line.find(\";\");\n\t\t\tline[pos] = ' ';\n\t\t}\n\t\tprototype.push_back(line);\n\t}\n\tPRO.close();\n\n\t// also check the prototype number\n\tif (prototype.size() != (size_t)nFiles) {\n\t\tcout << \"module name \" << moduleName << endl;\n\t\tcout << \"prototype size \" << prototype.size() << endl;\n\t\tcout << \"nFiles \" << nFiles << endl;\n\t\tcrash(true,\"the prototype number does not match nFiles in SQInts::formWorkFile\");\n\t}\n\n\t// now let's form every subfile\n\tinFinalDir = true;\n\tfor(iFile = 1; iFile<=nFiles; iFile++) {\n\n\t\t// get the work file name\n\t\tint fileIndex = iFile;\n\t\tstring fileName = infor.getWorkFuncName(onlyWithFuncName,moduleName,fileIndex,inFinalDir);\n\n\t\t// now let's open it\n\t\tofstream CPP;\n\t\tCPP.open(fileName.c_str(),ios::out);\n\n\t\t// firstly create the include part\n\t\tinfor.headPrinting(CPP);\n\n\t\t// now print the function prototyoe\n\t\tstring pro = prototype[iFile-1];\n\t\tCPP << pro << endl;\n\n\t\t// add in the \"{\" so that to start the main body\n\t\tCPP << \"{\" << endl;\n\n\t\t// now let's open the work file\n\t\tstring work = infor.getWorkFuncName(onlyWithFuncName,moduleName,fileIndex,false);\n\n\t\t// check existance\n\t\tpath p(work.c_str());\n\t\tif (! exists(p)) {\n\t\t\tcout << \"Missing work file \" << work << endl;\n\t\t\tcrash(true, \"Why the main body code file does not exist??? we need it in formWorkFile\");\n\t\t}\n\n\t\t// now let's open it\n\t\tifstream workFile;\n\t\tstring line;\n\t\tworkFile.open(work.c_str(),ios::in);\n\t\twhile(getline(workFile,line)) {\n\t\t\tCPP << line << endl;\n\t\t}\n\t\tworkFile.close();\n\n\t\t// close the cpp file\n\t\tCPP << \"}\" << endl;\n\t\tCPP.close();\n\t}\n}\n\nvoid SQInts::appendFile(int moduleName, ofstream& CPP, bool checkExist) const \n{\n\t// according to the module and status,\n\t// get the work file name\n\tstring file = infor.getWorkFuncName(false,moduleName);\n\n\t// check existance\n\t// if we do not have this file, we do not do a crash\n\t// just return\n\tpath p(file.c_str());\n\tif (! exists(p)) {\n\t\tif (checkExist) {\n\t\t\tcout << \"Missing file \" << file << endl;\n\t\t\tcrash(true, \"Why the file does not exist??? we need it in appendFile function of sqints\");\n\t\t}else{\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// now let's open it\n\tifstream workFile;\n\tworkFile.open(file.c_str(),ios::in);\n\tstring line;\n\twhile(getline(workFile,line)) {\n\t\tCPP << line << endl;\n\t}\n\tworkFile.close();\n}\n\nvoid SQInts::codeGeneration() \n{\n\t// generate the tmp folder\n\t// the work dir name should be same with\n\t// the one used in function of getProjectFileDir\n\tint intOperator = infor.getOper();\n\tint jobOrder    = infor.getJobOrder();\n\tstring workDir = infor.getProjectTmpFileDir(intOperator,jobOrder);\n\tpath tmpWorkDir(workDir.c_str());\n\tcreate_directory(tmpWorkDir);\n\n\t// generate the codes\n\tintCodeGeneration();\n\n\t// now assemble cpp files\n\tassembleCPPFiles();\n\n\t// this is debugging codes\n\t//const vector<int> shellCodes = infor.getShellCodeArray();\n\t//if (intOperator == THREEBODYKI && shellCodes[0] == 3 && shellCodes[1] == 3 && shellCodes[2] == 3) {\n\t//\tcrash(true, \"job complete\");\n\t//}\n\n\t// finally, clean the tmp file\n\tremove_all(tmpWorkDir);\n}\n\n", "meta": {"hexsha": "a84f9ed997e6d1cafaeabc08974b6e44806f1d29", "size": 31449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sqints.cpp", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sqints.cpp", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sqints.cpp", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6819512195, "max_line_length": 104, "alphanum_fraction": 0.6532799135, "num_tokens": 9127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.028870904126209018, "lm_q1q2_score": 0.008215966534354996}}
{"text": "/* ****************************************************************** **\n**    OpenSees - Open System for Earthquake Engineering Simulation    **\n**          Pacific Earthquake Engineering Research Center            **\n**                                                                    **\n**                                                                    **\n** (C) Copyright 1999, The Regents of the University of California    **\n** All Rights Reserved.                                               **\n**                                                                    **\n** Commercial use of this program without express permission of the   **\n** University of California, Berkeley, is strictly prohibited.  See   **\n** file 'COPYRIGHT'  in main directory for information on usage and   **\n** redistribution,  and for a DISCLAIMER OF ALL WARRANTIES.           **\n**                                                                    **\n** Developed by:                                                      **\n**   Frank McKenna (fmckenna@ce.berkeley.edu)                         **\n**   Gregory L. Fenves (fenves@ce.berkeley.edu)                       **\n**   Filip C. Filippou (filippou@ce.berkeley.edu)                     **\n**                                                                    **\n** ****************************************************************** */\n                                                                        \n// $Revision: 1.3 $\n// $Date: 2009-07-29 21:57:42 $\n// $Source: /usr/local/cvs/OpenSees/SRC/analysis/algorithm/eigenAlgo/FrequencyAlgo.cpp,v $\n                                                                        \n                                                                        \n// File: ~/analysis/algorithm/eigenAlgo/FrequencyAlgo.C\n//\n// Written: Jun Peng\n// Created: Mon Feb. 8, 1999\n// Revision: A\n//\n// Description: This file contains the class definition of FrequencyAlgo.\n// FrequencyAlgo is a class which performs a eigen solution algorithm\n// to solve the Generalized eigen equations. It is not expected that \n// this class will have subclasses.\n//\n// This class is inheritanted from the base class of SolutionAlgorithm\n// which was created by fmk (Frank).\n\n\n#include <FrequencyAlgo.h>\n#include <AnalysisModel.h>\n#include <EigenAnalysis.h>\n#include <EigenIntegrator.h>\n#include <EigenSOE.h>\n#include <Vector.h>\n#include <Channel.h>\n#include <FEM_ObjectBroker.h>\n#include <Timer.h>\n\nFrequencyAlgo::FrequencyAlgo()\n  :EigenAlgorithm(EigenALGORITHM_TAGS_Frequency)\n{\n    // do nothing here.\n}\n\nFrequencyAlgo::~FrequencyAlgo()\n{\n    // do nothing here.\n}\n\nint \nFrequencyAlgo::solveCurrentStep(int numModes)\n{\n    AnalysisModel *theModel = this->getAnalysisModelPtr();\n    EigenSOE *theSOE = this->getEigenSOEptr();\n    EigenIntegrator *theIntegrator = this->getEigenIntegratorPtr();\n\n    if ((theModel == 0) || (theIntegrator == 0) || (theSOE == 0)) {\n       opserr << \"WARNING FrequencyAlgo::solverCurrentStep() - \";\n       opserr << \"setLinks() has not been called. \\n\";\n       return -1;\n    }\n\n    if (theIntegrator->formK() < 0) {\n       opserr << \"WARNING FrequencyAlgo::solverCurrentStep() - \";\n       opserr << \"the Integrator failed in formK().\\n\";\n       return -2;\n    }\n\n    if (theIntegrator->formM() < 0) {\n       opserr << \"WARNING FrequencyAlgo::solverCurrentStep() - \";\n       opserr << \"the Integrator failed in formK().\\n\";\n       return -3;\n    }\n\n    if (theSOE->solve(numModes, true) < 0) {\n       opserr << \"Warning FrequencyAlgo::solveCurrentStep() - \";\n       opserr << \"the EigenSOE failed in solve().\\n\";\n       return -4;\n    }\n\n    // now set the eigenvalues and eigenvectors in the model\n    theModel->setNumEigenvectors(numModes);\n    Vector theEigenvalues(numModes);\n    for (int i=1; i<=numModes; i++) {\n\ttheEigenvalues[i-1] = theSOE->getEigenvalue(i);\n\ttheModel->setEigenvector(i, theSOE->getEigenvector(i));\n    }    \n    theModel->setEigenvalues(theEigenvalues);\n    \n    return 0;\n}\n\nint \nFrequencyAlgo::sendSelf(int cTag, Channel &theChannel)\n{\n    return 0;\n}\n\nint \nFrequencyAlgo::recvSelf(int cTag, Channel &theChannel,\n\t\t\tFEM_ObjectBroker &theBroker)\n{\n    return 0;\n}\n\nvoid \nFrequencyAlgo::Print(OPS_Stream &s, int flag)\n{\n    s << \"\\t Eigen Algorithm \\n\";\n}\n\n\n", "meta": {"hexsha": "2282494f0568a66642a87dbdde3a3095ea1b4fed", "size": 4279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OpenSees/SRC/analysis/algorithm/eigenAlgo/FrequencyAlgo.cpp", "max_stars_repo_name": "kuanshi/ductile-fracture", "max_stars_repo_head_hexsha": "ccb350564df54f5c5ec3a079100effe261b46650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T14:12:03.000Z", "max_issues_repo_path": "SRC/analysis/algorithm/eigenAlgo/FrequencyAlgo.cpp", "max_issues_repo_name": "steva44/OpenSees", "max_issues_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_issues_repo_licenses": ["TCL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRC/analysis/algorithm/eigenAlgo/FrequencyAlgo.cpp", "max_forks_repo_name": "steva44/OpenSees", "max_forks_repo_head_hexsha": "417c3be117992a108c6bbbcf5c9b63806b9362ab", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-21T03:11:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-19T07:29:37.000Z", "avg_line_length": 34.232, "max_line_length": 90, "alphanum_fraction": 0.5311988782, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.02976009211734845, "lm_q1q2_score": 0.008187886278961151}}
{"text": "/*!\r\n@file\r\nDefines `boost::hana::demux`.\r\n\r\n@copyright Louis Dionne 2013-2017\r\nDistributed under the Boost Software License, Version 1.0.\r\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#ifndef BOOST_HANA_FUNCTIONAL_DEMUX_HPP\r\n#define BOOST_HANA_FUNCTIONAL_DEMUX_HPP\r\n\r\n#include <boost/hana/basic_tuple.hpp>\r\n#include <boost/hana/config.hpp>\r\n#include <boost/hana/detail/decay.hpp>\r\n\r\n#include <cstddef>\r\n#include <utility>\r\n\r\n\r\nBOOST_HANA_NAMESPACE_BEGIN\r\n    //! @ingroup group-functional\r\n    //! Invoke a function with the results of invoking other functions\r\n    //! on its arguments.\r\n    //!\r\n    //! Specifically, `demux(f)(g...)` is a function such that\r\n    //! @code\r\n    //!     demux(f)(g...)(x...) == f(g(x...)...)\r\n    //! @endcode\r\n    //!\r\n    //! Each `g` is called with all the arguments, and then `f` is called\r\n    //! with the result of each `g`. Hence, the arity of `f` must match\r\n    //! the number of `g`s.\r\n    //!\r\n    //! This is called `demux` because of a vague similarity between this\r\n    //! device and a demultiplexer in signal processing. `demux` takes what\r\n    //! can be seen as a continuation (`f`), a bunch of functions to split a\r\n    //! signal (`g...`) and zero or more arguments representing the signal\r\n    //! (`x...`). Then, it calls the continuation with the result of\r\n    //! splitting the signal with whatever functions where given.\r\n    //!\r\n    //! @note\r\n    //! When used with two functions only, `demux` is associative. In other\r\n    //! words (and noting `demux(f, g) = demux(f)(g)` to ease the notation),\r\n    //! it is true that `demux(demux(f, g), h) == demux(f, demux(g, h))`.\r\n    //!\r\n    //!\r\n    //! Signature\r\n    //! ---------\r\n    //! The signature of `demux` is\r\n    //! \\f[\r\n    //!     \\mathtt{demux} :\r\n    //!         (B_1 \\times \\dotsb \\times B_n \\to C)\r\n    //!             \\to ((A_1 \\times \\dotsb \\times A_n \\to B_1)\r\n    //!                 \\times \\dotsb\r\n    //!                 \\times (A_1 \\times \\dotsb \\times A_n \\to B_n))\r\n    //!             \\to (A_1 \\times \\dotsb \\times A_n \\to C)\r\n    //! \\f]\r\n    //!\r\n    //! This can be rewritten more tersely as\r\n    //! \\f[\r\n    //!     \\mathtt{demux} :\r\n    //!         \\left(\\prod_{i=1}^n B_i \\to C \\right)\r\n    //!         \\to \\prod_{j=1}^n \\left(\\prod_{i=1}^n A_i \\to B_j \\right)\r\n    //!         \\to \\left(\\prod_{i=1}^n A_i \\to C \\right)\r\n    //! \\f]\r\n    //!\r\n    //!\r\n    //! Link with normal composition\r\n    //! ----------------------------\r\n    //! The signature of `compose` is\r\n    //! \\f[\r\n    //!     \\mathtt{compose} : (B \\to C) \\times (A \\to B) \\to (A \\to C)\r\n    //! \\f]\r\n    //!\r\n    //! A valid observation is that this coincides exactly with the type\r\n    //! of `demux` when used with a single unary function. Actually, both\r\n    //! functions are equivalent:\r\n    //! @code\r\n    //!     demux(f)(g)(x) == compose(f, g)(x)\r\n    //! @endcode\r\n    //!\r\n    //! However, let's now consider the curried version of `compose`,\r\n    //! `curry<2>(compose)`:\r\n    //! \\f[\r\n    //!     \\mathtt{curry_2(compose)} : (B \\to C) \\to ((A \\to B) \\to (A \\to C))\r\n    //! \\f]\r\n    //!\r\n    //! For the rest of this explanation, we'll just consider the curried\r\n    //! version of `compose` and so we'll use `compose` instead of\r\n    //! `curry<2>(compose)` to lighten the notation. With currying, we can\r\n    //! now consider `compose` applied to itself:\r\n    //! \\f[\r\n    //!     \\mathtt{compose(compose, compose)} :\r\n    //!         (B \\to C) \\to (A_1 \\to A_2 \\to B) \\to (A_1 \\to A_2 \\to C)\r\n    //! \\f]\r\n    //!\r\n    //! If we uncurry deeply the above expression, we obtain\r\n    //! \\f[\r\n    //!     \\mathtt{compose(compose, compose)} :\r\n    //!         (B \\to C) \\times (A_1 \\times A_2 \\to B) \\to (A_1 \\times A_2 \\to C)\r\n    //! \\f]\r\n    //!\r\n    //! This signature is exactly the same as that of `demux` when given a\r\n    //! single binary function, and indeed they are equivalent definitions.\r\n    //! We can also generalize this further by considering\r\n    //! `compose(compose(compose, compose), compose)`:\r\n    //! \\f[\r\n    //!     \\mathtt{compose(compose(compose, compose), compose)} :\r\n    //!         (B \\to C) \\to (A_1 \\to A_2 \\to A_3 \\to B)\r\n    //!             \\to (A_1 \\to A_2 \\to A_3 \\to C)\r\n    //! \\f]\r\n    //!\r\n    //! which uncurries to\r\n    //! \\f[\r\n    //!     \\mathtt{compose(compose(compose, compose), compose)} :\r\n    //!         (B \\to C) \\times (A_1 \\times A_2 \\times A_3 \\to B)\r\n    //!             \\to (A_1 \\times A_2 \\times A_3 \\to C)\r\n    //! \\f]\r\n    //!\r\n    //! This signature is exactly the same as that of `demux` when given a\r\n    //! single ternary function. Hence, for a single n-ary function `g`,\r\n    //! `demux(f)(g)` is equivalent to the n-times composition of `compose`\r\n    //! with itself, applied to `g` and `f`:\r\n    //! @code\r\n    //!     demux(f)(g) == fold_left([compose, ..., compose], id, compose)(g, f)\r\n    //!                           //  ^^^^^^^^^^^^^^^^^^^^^ n times\r\n    //! @endcode\r\n    //!\r\n    //! More information on this insight can be seen [here][1]. Also, I'm\r\n    //! not sure how this insight could be generalized to more than one\r\n    //! function `g`, or if that is even possible.\r\n    //!\r\n    //!\r\n    //! Proof of associativity in the binary case\r\n    //! -----------------------------------------\r\n    //! As explained above, `demux` is associative when it is used with\r\n    //! two functions only. Indeed, given functions `f`, `g` and `h` with\r\n    //! suitable signatures, we have\r\n    //! @code\r\n    //!     demux(f)(demux(g)(h))(x...) == f(demux(g)(h)(x...))\r\n    //!                                 == f(g(h(x...)))\r\n    //! @endcode\r\n    //!\r\n    //! On the other hand, we have\r\n    //! @code\r\n    //!     demux(demux(f)(g))(h)(x...) == demux(f)(g)(h(x...))\r\n    //!                                 == f(g(h(x...)))\r\n    //! @endcode\r\n    //!\r\n    //! and hence `demux` is associative in the binary case.\r\n    //!\r\n    //!\r\n    //! Example\r\n    //! -------\r\n    //! @include example/functional/demux.cpp\r\n    //!\r\n    //! [1]: http://stackoverflow.com/q/5821089/627587\r\n#ifdef BOOST_HANA_DOXYGEN_INVOKED\r\n    constexpr auto demux = [](auto&& f) {\r\n        return [perfect-capture](auto&& ...g) {\r\n            return [perfect-capture](auto&& ...x) -> decltype(auto) {\r\n                // x... can't be forwarded unless there is a single g\r\n                // function, or that could cause double-moves.\r\n                return forwarded(f)(forwarded(g)(x...)...);\r\n            };\r\n        };\r\n    };\r\n#else\r\n    template <typename F>\r\n    struct pre_demux_t;\r\n\r\n    struct make_pre_demux_t {\r\n        struct secret { };\r\n        template <typename F>\r\n        constexpr pre_demux_t<typename detail::decay<F>::type> operator()(F&& f) const {\r\n            return {static_cast<F&&>(f)};\r\n        }\r\n    };\r\n\r\n    template <typename Indices, typename F, typename ...G>\r\n    struct demux_t;\r\n\r\n    template <typename F>\r\n    struct pre_demux_t {\r\n        F f;\r\n\r\n        template <typename ...G>\r\n        constexpr demux_t<std::make_index_sequence<sizeof...(G)>, F,\r\n                          typename detail::decay<G>::type...>\r\n        operator()(G&& ...g) const& {\r\n            return {make_pre_demux_t::secret{}, this->f, static_cast<G&&>(g)...};\r\n        }\r\n\r\n        template <typename ...G>\r\n        constexpr demux_t<std::make_index_sequence<sizeof...(G)>, F,\r\n                          typename detail::decay<G>::type...>\r\n        operator()(G&& ...g) && {\r\n            return {make_pre_demux_t::secret{}, static_cast<F&&>(this->f), static_cast<G&&>(g)...};\r\n        }\r\n    };\r\n\r\n    template <std::size_t ...n, typename F, typename ...G>\r\n    struct demux_t<std::index_sequence<n...>, F, G...> {\r\n        template <typename ...T>\r\n        constexpr demux_t(make_pre_demux_t::secret, T&& ...t)\r\n            : storage_{static_cast<T&&>(t)...}\r\n        { }\r\n\r\n        basic_tuple<F, G...> storage_;\r\n\r\n        template <typename ...X>\r\n        constexpr decltype(auto) operator()(X&& ...x) const& {\r\n            return hana::at_c<0>(storage_)(\r\n                hana::at_c<n+1>(storage_)(x...)...\r\n            );\r\n        }\r\n\r\n        template <typename ...X>\r\n        constexpr decltype(auto) operator()(X&& ...x) & {\r\n            return hana::at_c<0>(storage_)(\r\n                hana::at_c<n+1>(storage_)(x...)...\r\n            );\r\n        }\r\n\r\n        template <typename ...X>\r\n        constexpr decltype(auto) operator()(X&& ...x) && {\r\n            return static_cast<F&&>(hana::at_c<0>(storage_))(\r\n                static_cast<G&&>(hana::at_c<n+1>(storage_))(x...)...\r\n            );\r\n        }\r\n    };\r\n\r\n    template <typename F, typename G>\r\n    struct demux_t<std::index_sequence<0>, F, G> {\r\n        template <typename ...T>\r\n        constexpr demux_t(make_pre_demux_t::secret, T&& ...t)\r\n            : storage_{static_cast<T&&>(t)...}\r\n        { }\r\n\r\n        basic_tuple<F, G> storage_;\r\n\r\n        template <typename ...X>\r\n        constexpr decltype(auto) operator()(X&& ...x) const& {\r\n            return hana::at_c<0>(storage_)(\r\n                hana::at_c<1>(storage_)(static_cast<X&&>(x)...)\r\n            );\r\n        }\r\n\r\n        template <typename ...X>\r\n        constexpr decltype(auto) operator()(X&& ...x) & {\r\n            return hana::at_c<0>(storage_)(\r\n                hana::at_c<1>(storage_)(static_cast<X&&>(x)...)\r\n            );\r\n        }\r\n\r\n        template <typename ...X>\r\n        constexpr decltype(auto) operator()(X&& ...x) && {\r\n            return static_cast<F&&>(hana::at_c<0>(storage_))(\r\n                static_cast<G&&>(hana::at_c<1>(storage_))(static_cast<X&&>(x)...)\r\n            );\r\n        }\r\n    };\r\n\r\n    constexpr make_pre_demux_t demux{};\r\n#endif\r\nBOOST_HANA_NAMESPACE_END\r\n\r\n#endif // !BOOST_HANA_FUNCTIONAL_DEMUX_HPP\r\n", "meta": {"hexsha": "60c1efd855472a9276b04b8d4567a5b74ad47e6e", "size": 9819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/hana/functional/demux.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": 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": "deps/boost/include/boost/hana/functional/demux.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": 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": "deps/boost/include/boost/hana/functional/demux.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": 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": 36.3666666667, "max_line_length": 100, "alphanum_fraction": 0.5078928608, "num_tokens": 2704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946967146026513, "lm_q2_score": 0.03904829118858021, "lm_q1q2_score": 0.008179432726356663}}
{"text": "// Copyright (c) 2008-2016 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 UUID_3EDF999CA1C011DEBA5C8DA956D89593\n#define UUID_3EDF999CA1C011DEBA5C8DA956D89593\n\n#include <boost/qvm/assert.hpp>\n#include <boost/qvm/deduce_mat.hpp>\n#include <boost/qvm/enable_if.hpp>\n#include <boost/qvm/inline.hpp>\n#include <boost/qvm/vec_traits.hpp>\n\nnamespace boost {\nnamespace qvm {\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalVector> class col_mat_ {\n  col_mat_(col_mat_ const &);\n  col_mat_ &operator=(col_mat_ const &);\n  ~col_mat_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL col_mat_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class OriginalVector>\nstruct mat_traits<qvm_detail::col_mat_<OriginalVector>> {\n  typedef qvm_detail::col_mat_<OriginalVector> this_matrix;\n  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;\n  static int const rows = vec_traits<OriginalVector>::dim;\n  static int const cols = 1;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Col == 0);\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    return vec_traits<OriginalVector>::template read_element<Row>(\n        reinterpret_cast<OriginalVector const &>(x));\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Col == 0);\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    return vec_traits<OriginalVector>::template write_element<Row>(\n        reinterpret_cast<OriginalVector &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(col == 0);\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    return vec_traits<OriginalVector>::read_element_idx(\n        row, reinterpret_cast<OriginalVector const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(col == 0);\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    return vec_traits<OriginalVector>::write_element_idx(\n        row, reinterpret_cast<OriginalVector &>(x));\n  }\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat<qvm_detail::col_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat2<qvm_detail::col_mat_<OriginalVector>,\n                   qvm_detail::col_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value,\n                            qvm_detail::col_mat_<A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    col_mat(A const &a) {\n  return reinterpret_cast<typename qvm_detail::col_mat_<A> const &>(a);\n}\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value, qvm_detail::col_mat_<A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    col_mat(A &a) {\n  return reinterpret_cast<typename qvm_detail::col_mat_<A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalVector> class row_mat_ {\n  row_mat_(row_mat_ const &);\n  row_mat_ &operator=(row_mat_ const &);\n  ~row_mat_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL row_mat_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class OriginalVector>\nstruct mat_traits<qvm_detail::row_mat_<OriginalVector>> {\n  typedef qvm_detail::row_mat_<OriginalVector> this_matrix;\n  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;\n  static int const rows = 1;\n  static int const cols = vec_traits<OriginalVector>::dim;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row == 0);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return vec_traits<OriginalVector>::template read_element<Col>(\n        reinterpret_cast<OriginalVector const &>(x));\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row == 0);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return vec_traits<OriginalVector>::template write_element<Col>(\n        reinterpret_cast<OriginalVector &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row == 0);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return vec_traits<OriginalVector>::read_element_idx(\n        col, reinterpret_cast<OriginalVector const &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(row == 0);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return vec_traits<OriginalVector>::write_element_idx(\n        col, reinterpret_cast<OriginalVector &>(x));\n  }\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat<qvm_detail::row_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat2<qvm_detail::row_mat_<OriginalVector>,\n                   qvm_detail::row_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value,\n                            qvm_detail::row_mat_<A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    row_mat(A const &a) {\n  return reinterpret_cast<typename qvm_detail::row_mat_<A> const &>(a);\n}\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value, qvm_detail::row_mat_<A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    row_mat(A &a) {\n  return reinterpret_cast<typename qvm_detail::row_mat_<A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalVector> class translation_mat_ {\n  translation_mat_(translation_mat_ const &);\n  translation_mat_ &operator=(translation_mat_ const &);\n  ~translation_mat_();\n\npublic:\n  template <class T>\n  BOOST_QVM_INLINE_TRIVIAL translation_mat_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n\ntemplate <class M, int Row, int Col,\n          bool TransCol = (Col == mat_traits<M>::cols - 1)>\nstruct read_translation_matat;\n\ntemplate <class OriginalVector, int Row, int Col, bool TransCol>\nstruct read_translation_matat<translation_mat_<OriginalVector>, Row, Col,\n                              TransCol> {\n  static BOOST_QVM_INLINE_CRITICAL\n      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type\n      f(translation_mat_<OriginalVector> const &) {\n    return scalar_traits<typename mat_traits<\n        translation_mat_<OriginalVector>>::scalar_type>::value(0);\n  }\n};\n\ntemplate <class OriginalVector, int D>\nstruct read_translation_matat<translation_mat_<OriginalVector>, D, D, false> {\n  static BOOST_QVM_INLINE_CRITICAL\n      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type\n      f(translation_mat_<OriginalVector> const &) {\n    return scalar_traits<typename mat_traits<\n        translation_mat_<OriginalVector>>::scalar_type>::value(1);\n  }\n};\n\ntemplate <class OriginalVector, int D>\nstruct read_translation_matat<translation_mat_<OriginalVector>, D, D, true> {\n  static BOOST_QVM_INLINE_CRITICAL\n      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type\n      f(translation_mat_<OriginalVector> const &) {\n    return scalar_traits<typename mat_traits<\n        translation_mat_<OriginalVector>>::scalar_type>::value(1);\n  }\n};\n\ntemplate <class OriginalVector, int Row, int Col>\nstruct read_translation_matat<translation_mat_<OriginalVector>, Row, Col,\n                              true> {\n  static BOOST_QVM_INLINE_CRITICAL\n      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type\n      f(translation_mat_<OriginalVector> const &x) {\n    return vec_traits<OriginalVector>::template read_element<Row>(\n        reinterpret_cast<OriginalVector const &>(x));\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class OriginalVector>\nstruct mat_traits<qvm_detail::translation_mat_<OriginalVector>> {\n  typedef qvm_detail::translation_mat_<OriginalVector> this_matrix;\n  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;\n  static int const rows = vec_traits<OriginalVector>::dim + 1;\n  static int const cols = vec_traits<OriginalVector>::dim + 1;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return qvm_detail::read_translation_matat<\n        qvm_detail::translation_mat_<OriginalVector>, Row, Col>::f(x);\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col == cols - 1);\n    BOOST_QVM_STATIC_ASSERT(Col != Row);\n    return vec_traits<OriginalVector>::template write_element<Row>(\n        reinterpret_cast<OriginalVector &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return row == col\n               ? scalar_traits<scalar_type>::value(1)\n               : (col == cols - 1\n                      ? vec_traits<OriginalVector>::read_element_idx(\n                            row, reinterpret_cast<OriginalVector const &>(x))\n                      : scalar_traits<scalar_type>::value(0));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col == cols - 1);\n    BOOST_QVM_ASSERT(col != row);\n    return vec_traits<OriginalVector>::write_element_idx(\n        row, reinterpret_cast<OriginalVector &>(x));\n  }\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat<qvm_detail::translation_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat2<qvm_detail::translation_mat_<OriginalVector>,\n                   qvm_detail::translation_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value,\n                            qvm_detail::translation_mat_<A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    translation_mat(A const &a) {\n  return reinterpret_cast<typename qvm_detail::translation_mat_<A> const &>(a);\n}\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value,\n                            qvm_detail::translation_mat_<A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    translation_mat(A &a) {\n  return reinterpret_cast<typename qvm_detail::translation_mat_<A> &>(a);\n}\n\n////////////////////////////////////////////////\n\nnamespace qvm_detail {\ntemplate <class OriginalVector> class diag_mat_ {\n  diag_mat_(diag_mat_ const &);\n  diag_mat_ &operator=(diag_mat_ const &);\n  ~diag_mat_();\n\npublic:\n  template <class T> BOOST_QVM_INLINE_TRIVIAL diag_mat_ &operator=(T const &x) {\n    assign(*this, x);\n    return *this;\n  }\n\n  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {\n    R r;\n    assign(r, *this);\n    return r;\n  }\n};\n} // namespace qvm_detail\n\ntemplate <class OriginalVector>\nstruct mat_traits<qvm_detail::diag_mat_<OriginalVector>> {\n  typedef qvm_detail::diag_mat_<OriginalVector> this_matrix;\n  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;\n  static int const rows = vec_traits<OriginalVector>::dim;\n  static int const cols = vec_traits<OriginalVector>::dim;\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element(this_matrix const &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Col >= 0);\n    BOOST_QVM_STATIC_ASSERT(Col < cols);\n    return Row == Col ? vec_traits<OriginalVector>::template read_element<Row>(\n                            reinterpret_cast<OriginalVector const &>(x))\n                      : scalar_traits<scalar_type>::value(0);\n  }\n\n  template <int Row, int Col>\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {\n    BOOST_QVM_STATIC_ASSERT(Row >= 0);\n    BOOST_QVM_STATIC_ASSERT(Row < rows);\n    BOOST_QVM_STATIC_ASSERT(Row == Col);\n    return vec_traits<OriginalVector>::template write_element<Row>(\n        reinterpret_cast<OriginalVector &>(x));\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type\n  read_element_idx(int row, int col, this_matrix const &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(col >= 0);\n    BOOST_QVM_ASSERT(col < cols);\n    return row == col ? vec_traits<OriginalVector>::read_element_idx(\n                            row, reinterpret_cast<OriginalVector const &>(x))\n                      : scalar_traits<scalar_type>::value(0);\n  }\n\n  static BOOST_QVM_INLINE_CRITICAL scalar_type &\n  write_element_idx(int row, int col, this_matrix &x) {\n    BOOST_QVM_ASSERT(row >= 0);\n    BOOST_QVM_ASSERT(row < rows);\n    BOOST_QVM_ASSERT(row == col);\n    return vec_traits<OriginalVector>::write_element_idx(\n        row, reinterpret_cast<OriginalVector &>(x));\n  }\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat<qvm_detail::diag_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class OriginalVector, int R, int C>\nstruct deduce_mat2<qvm_detail::diag_mat_<OriginalVector>,\n                   qvm_detail::diag_mat_<OriginalVector>, R, C> {\n  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;\n};\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value,\n                            qvm_detail::diag_mat_<A> const &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    diag_mat(A const &a) {\n  return reinterpret_cast<typename qvm_detail::diag_mat_<A> const &>(a);\n}\n\ntemplate <class A>\ntypename boost::enable_if_c<is_vec<A>::value, qvm_detail::diag_mat_<A> &>::type\n    BOOST_QVM_INLINE_TRIVIAL\n    diag_mat(A &a) {\n  return reinterpret_cast<typename qvm_detail::diag_mat_<A> &>(a);\n}\n\n////////////////////////////////////////////////\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "c672931d2da68d7e3d4a7b26a917c1c0da71a18c", "size": 15659, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/map_vec_mat.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/map_vec_mat.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/map_vec_mat.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": 34.4911894273, "max_line_length": 80, "alphanum_fraction": 0.7045788365, "num_tokens": 3927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.025957355596589876, "lm_q1q2_score": 0.008151921338357574}}
{"text": "/**\n * grove: PreemptiveRansac.cpp\n * Copyright (c) Torr Vision Group, University of Oxford, 2017. All rights reserved.\n */\n\n#include \"ransac/interface/PreemptiveRansac.h\"\nusing namespace tvgutil;\n\n#ifdef WITH_ALGLIB\n#include <alglib/optimization.h>\n#endif\n\n#include <boost/lexical_cast.hpp>\n#include <boost/timer/timer.hpp>\n\n#include <Eigen/Dense>\n\n#ifdef WITH_OPENMP\n#include <omp.h>\n#endif\n\n#include <orx/base/MemoryBlockFactory.h>\n#include <orx/geometry/GeometryUtil.h>\nusing namespace orx;\n\n//#################### MACROS ####################\n\n// Enable/disable the print-out of more detailed timings (very verbose, so disabled by default).\n//#define ENABLE_TIMERS\n\nnamespace grove {\n\n//#################### CONSTRUCTORS ####################\n\nPreemptiveRansac::PreemptiveRansac(const SettingsContainer_CPtr& settings, const std::string& settingsNamespace)\n: m_timerCandidateGeneration(\"Candidate Generation\"),\n  m_timerFirstComputeEnergy(\"First Energy Computation\"),\n  m_timerFirstTrim(\"First Trim\"),\n  m_timerTotal(\"P-RANSAC Total\"),\n  m_poseCandidatesAfterCull(0),\n  m_settings(settings)\n{\n  // By default, we set all parameters as in SCoRe forests.\n  m_checkMinDistanceBetweenSampledModes = m_settings->get_first_value<bool>(settingsNamespace + \"checkMinDistanceBetweenSampledModes\", true);                   // Whether or not to force sampled modes to have a minimum distance between them.\n  m_checkRigidTransformationConstraint = m_settings->get_first_value<bool>(settingsNamespace + \"checkRigidTransformationConstraint\", true);                     // Setting this to false speeds things up a lot, at the expense of quality.\n  m_maxCandidateGenerationIterations = m_settings->get_first_value<uint32_t>(settingsNamespace + \"maxCandidateGenerationIterations\", 6000);                     // The maximum number of times we sample three pixel-mode pairs in the attempt to generate a pose candidate.\n  m_maxPoseCandidates = m_settings->get_first_value<uint32_t>(settingsNamespace + \"maxPoseCandidates\", 1024);                                                   // The number of initial pose candidates.\n  m_maxPoseCandidatesAfterCull = m_settings->get_first_value<uint32_t>(settingsNamespace + \"maxPoseCandidatesAfterCull\", 64);                                   // Aggressively cull hypotheses to this number.\n  m_maxTranslationErrorForCorrectPose = m_settings->get_first_value<float>(settingsNamespace + \"maxTranslationErrorForCorrectPose\", 0.05f);                     // In m.\n  m_minSquaredDistanceBetweenSampledModes = m_settings->get_first_value<float>(settingsNamespace + \"minSquaredDistanceBetweenSampledModes\", 0.3f * 0.3f);       // In m.\n\n  // Optimisation parameters defaulted as in Valentin's paper.\n  m_poseOptimisationEnergyThreshold = m_settings->get_first_value<double>(settingsNamespace + \"poseOptimisationEnergyThreshold\", 0.0);                          // Part of the termination condition for the pose optimisation.\n  m_poseOptimisationGradientThreshold = m_settings->get_first_value<double>(settingsNamespace + \"poseOptimisationGradientThreshold\", 1e-6);                     // Part of the termination condition for the pose optimisation.\n  m_poseOptimisationInlierThreshold = m_settings->get_first_value<float>(settingsNamespace + \"poseOptimizationInlierThreshold\", 0.2f);                          // In m.\n  m_poseOptimisationMaxIterations = m_settings->get_first_value<uint32_t>(settingsNamespace + \"poseOptimisationMaxIterations\", 100);                            // Maximum number of LM iterations.\n  m_poseOptimisationStepThreshold = m_settings->get_first_value<double>(settingsNamespace + \"poseOptimisationStepThreshold\", 0.0);                              // Part of the termination condition for the pose optimisation.\n  m_poseUpdate = m_settings->get_first_value<bool>(settingsNamespace + \"poseUpdate\", true);                                                                     // Whether or not to optimise the poses with LM.\n  m_printTimers = m_settings->get_first_value<bool>(settingsNamespace + \"printTimers\", false);                                                                  // Whether or not to print the timers for each phase.\n  m_ransacInliersPerIteration = m_settings->get_first_value<uint32_t>(settingsNamespace + \"ransacInliersPerIteration\", 500);                                    // The number of inliers sampled in each P-RANSAC iteration.\n  m_useAllModesPerLeafInPoseHypothesisGeneration = m_settings->get_first_value<bool>(settingsNamespace + \"useAllModesPerLeafInPoseHypothesisGeneration\", true); // If false, use the first mode only (representing the largest cluster).\n  m_usePredictionCovarianceForPoseOptimization = m_settings->get_first_value<bool>(settingsNamespace + \"usePredictionCovarianceForPoseOptimization\", true);     // If false, use L2.\n\n  // Each RANSAC iteration after the initial cull adds m_ransacInliersPerIteration inliers to the set, so we allocate enough space for all of them up-front.\n  m_nbMaxInliers = m_ransacInliersPerIteration * static_cast<uint32_t>(std::ceil(log2(m_maxPoseCandidatesAfterCull)));\n\n  // We can only update the candidate poses if ALGLIB is available. Check and throw an exception otherwise.\n#ifndef WITH_ALGLIB\n  if(m_poseUpdate)\n  {\n    throw std::runtime_error(\"Error: Enabling poseUpdate requires ALGLIB. Reconfigure in CMake with the WITH_ALGLIB option set to ON.\");\n  }\n#endif\n\n  // Allocate memory.\n  const MemoryBlockFactory& mbf = MemoryBlockFactory::instance();\n  m_inlierRasterIndicesBlock = mbf.make_block<int>(m_nbMaxInliers);\n  m_inliersMaskImage = mbf.make_image<int>();\n  m_poseCandidates = mbf.make_block<PoseCandidate>(m_maxPoseCandidates);\n\n  const uint32_t poseOptimisationBufferSize = static_cast<uint32_t>(m_nbMaxInliers * m_maxPoseCandidates);\n  m_poseOptimisationCameraPoints = mbf.make_block<Vector4f>(poseOptimisationBufferSize);\n  m_poseOptimisationPredictedModes = mbf.make_block<Keypoint3DColourCluster>(poseOptimisationBufferSize);\n\n#ifdef ENABLE_TIMERS\n  // Force the average timers to on as well if we want verbose printing.\n  m_printTimers = true;\n#endif\n\n  // Set up the remaining timers.\n  const int maxRansacIterations = static_cast<int>(ceil(log2(m_maxPoseCandidatesAfterCull)));\n  for(int i = 1; i <= maxRansacIterations; ++i)\n  {\n    m_timerInlierSampling.push_back(AverageTimer(\"Inlier Sampling \" + boost::lexical_cast<std::string>(i)));\n    m_timerPrepareOptimisation.push_back(AverageTimer(\"Prepare Optimisation \" + boost::lexical_cast<std::string>(i)));\n    m_timerOptimisation.push_back(AverageTimer(\"Optimisation \" + boost::lexical_cast<std::string>(i)));\n    m_timerComputeEnergy.push_back(AverageTimer(\"Energy Computation \" + boost::lexical_cast<std::string>(i)));\n  }\n}\n\n//#################### DESTRUCTOR ####################\n\nPreemptiveRansac::~PreemptiveRansac()\n{\n  if(m_printTimers)\n  {\n    print_timer(m_timerTotal);\n    print_timer(m_timerCandidateGeneration);\n    print_timer(m_timerFirstTrim);\n    print_timer(m_timerFirstComputeEnergy);\n\n    for(size_t i = 0; i < m_timerInlierSampling.size(); ++i)\n    {\n      print_timer(m_timerInlierSampling[i]);\n      print_timer(m_timerComputeEnergy[i]);\n      print_timer(m_timerPrepareOptimisation[i]);\n      print_timer(m_timerOptimisation[i]);\n    }\n  }\n}\n\n//#################### PROTECTED ABSTRACT MEMBER FUNCTIONS ####################\n\nvoid PreemptiveRansac::update_candidate_poses()\n{\n  // Note: This is a default implementation of the abstract function - it is intended to be called / overridden by derived classes.\n  const int nbPoseCandidates = static_cast<int>(m_poseCandidates->dataSize);\n\n#ifdef WITH_OPENMP\n  #pragma omp parallel for schedule(dynamic)\n#endif\n  for(int i = 0; i < nbPoseCandidates; ++i)\n  {\n    update_candidate_pose(i);\n  }\n}\n\n//#################### PUBLIC MEMBER FUNCTIONS ####################\n\nboost::optional<PoseCandidate> PreemptiveRansac::estimate_pose(const Keypoint3DColourImage_CPtr& keypointsImage, const ScorePredictionsImage_CPtr& predictionsImage)\n{\n  /*\n  Note: In this function and in the virtual functions of the CPU and CUDA subclasses, we directly access and overwrite\n        the dataSize member of several MemoryBlock variables instead of keeping a separate \"valid size\" variable.\n        This is done on purpose since the Update*From* functions of MemoryBlock/Images only move the first dataSize\n        elements of the block. By changing the number to the actual number of elements to move we can gain a slight\n        speed-up of the system.\n  */\n\n  m_timerTotal.start_sync();\n\n  // Copy the keypoints and predictions images into member variables to avoid explicitly passing them to every function.\n  m_keypointsImage = keypointsImage;\n  m_predictionsImage = predictionsImage;\n\n  // Step 1: Generate the initial pose candidates.\n  {\n#ifdef ENABLE_TIMERS\n    boost::timer::auto_cpu_timer t(6, \"generating initial candidates: %ws wall, %us user + %ss system = %ts CPU (%p%)\\n\");\n#endif\n    m_timerCandidateGeneration.start_nosync(); // No need to synchronize the GPU again.\n    generate_pose_candidates();\n    m_timerCandidateGeneration.stop_sync();\n  }\n\n  // Reset the number of inliers ready for the new pose estimation.\n  {\n    const bool resetMask = false;\n    reset_inliers(resetMask);\n  }\n\n  // Step 2: If necessary, aggressively cull the initial candidates to reduce the computational cost of the remaining steps.\n  if(m_poseCandidates->dataSize > m_maxPoseCandidatesAfterCull)\n  {\n    m_timerFirstTrim.start_sync();\n#ifdef ENABLE_TIMERS\n    boost::timer::auto_cpu_timer t(6, \"first trim: %ws wall, %us user + %ss system = %ts CPU (%p%)\\n\");\n#endif\n\n    // Step 2(a): First, sample a set of points from the input data to use to evaluate the quality of each candidate.\n    {\n#ifdef ENABLE_TIMERS\n      boost::timer::auto_cpu_timer t(6, \"sample inliers: %ws wall, %us user + %ss system = %ts CPU (%p%)\\n\");\n#endif\n      const bool useMask = false; // no mask for the first pass\n      sample_inliers(useMask);\n    }\n\n    // Step 2(b): Then, evaluate the candidates and sort them in non-increasing order of quality.\n    {\n#ifdef ENABLE_TIMERS\n      boost::timer::auto_cpu_timer t(6, \"compute energies and sort: %ws wall, %us user + %ss system = %ts CPU (%p%)\\n\");\n#endif\n      m_timerFirstComputeEnergy.start_sync();\n      compute_energies_and_sort();\n      m_timerFirstComputeEnergy.stop_sync();\n    }\n\n    // Step 2(c): Finally, trim the number of candidates down to the maximum number allowed. Since we previously sorted\n    //            the candidates by quality, this has the effect of keeping only the best ones.\n    m_poseCandidates->dataSize = m_maxPoseCandidatesAfterCull;\n\n    m_timerFirstTrim.stop_nosync(); // No need to synchronize the GPU again.\n  }\n\n  m_poseCandidatesAfterCull = static_cast<uint32_t>(m_poseCandidates->dataSize);\n\n#ifdef ENABLE_TIMERS\n  boost::timer::auto_cpu_timer t(6, \"ransac: %ws wall, %us user + %ss system = %ts CPU (%p%)\\n\");\n#endif\n\n  // Step 3: Reset the inlier mask and clear any inliers that might have been selected in a previous invocation of the method.\n  {\n    const bool resetMask = true;\n    reset_inliers(resetMask);\n  }\n\n  // Step 4: Run preemptive RANSAC until only a single candidate remains.\n  int iteration = 0;\n  while(m_poseCandidates->dataSize > 1)\n  {\n#ifdef ENABLE_TIMERS\n    boost::timer::auto_cpu_timer t(6, \"ransac iteration: %ws wall, %us user + %ss system = %ts CPU (%p%)\\n\");\n#endif\n\n#if 0\n    std::cout << candidates.size() << \" camera(s) remaining\" << std::endl;\n#endif\n\n    // Step 4(a): Sample a set of keypoints from the input image. Record that thay have been selected in the mask image, to avoid selecting them again.\n    m_timerInlierSampling[iteration].start_sync();\n    const bool useMask = true;\n    sample_inliers(useMask);\n    m_timerInlierSampling[iteration].stop_sync();\n\n    // Step 4(b): If pose update is enabled, optimise all remaining candidates, taking into account the newly selected inliers.\n    if(m_poseUpdate)\n    {\n      m_timerPrepareOptimisation[iteration].start_nosync(); // No need to synchronize the GPU again.\n      prepare_inliers_for_optimisation();\n      m_timerPrepareOptimisation[iteration].stop_sync();\n\n#ifdef ENABLE_TIMERS\n      boost::timer::auto_cpu_timer t(6, \"continuous optimization: %ws wall, %us user + %ss system = %ts CPU (%p%)\\n\");\n#endif\n      m_timerOptimisation[iteration].start_nosync(); // No need to synchronize the GPU again.\n      update_candidate_poses();\n      m_timerOptimisation[iteration].stop_sync();\n    }\n\n    // Step 4(c): Compute the energy for each candidate and sort them in non-increasing order of quality.\n    m_timerComputeEnergy[iteration].start_nosync(); // No need to synchronize the GPU again.\n    compute_energies_and_sort();\n    m_timerComputeEnergy[iteration].stop_sync();\n\n    // Step 4(d): Remove the worse half of the candidates.\n    m_poseCandidates->dataSize /= 2;\n\n    ++iteration;\n  }\n\n  // If we initially generated a single candidate, the update step above wouldn't have been executed (zero iterations). Force its execution.\n  if(m_poseUpdate && iteration == 0 && m_poseCandidates->dataSize == 1)\n  {\n    // Sample some inliers.\n    m_timerInlierSampling[iteration].start_sync();\n    sample_inliers(true);\n    m_timerInlierSampling[iteration].stop_sync();\n\n    // Having selected the inlier points, find the best associated modes to use during optimisation.\n    m_timerPrepareOptimisation[iteration].start_nosync(); // No need to synchronize the GPU again.\n    prepare_inliers_for_optimisation();\n    m_timerPrepareOptimisation[iteration].stop_sync();\n\n    // Run the optimisation.\n    m_timerOptimisation[iteration].start_nosync(); // No need to synchronize the GPU again.\n    update_candidate_poses();\n    m_timerOptimisation[iteration].stop_sync();\n  }\n\n  m_timerTotal.stop_nosync(); // No need to synchronize the GPU again.\n\n  // Make sure the pose candidates available on the host are up to date.\n  update_host_pose_candidates();\n\n  // Step 5: If we managed to generate at least one candidate, return the best one.\n  const PoseCandidate *candidates = m_poseCandidates->GetData(MEMORYDEVICE_CPU);\n  return m_poseCandidates->dataSize > 0 ? boost::optional<PoseCandidate>(candidates[0]) : boost::none;\n}\n\nvoid PreemptiveRansac::get_best_poses(std::vector<PoseCandidate>& poseCandidates) const\n{\n  // Set up the output container.\n  poseCandidates.clear();\n  poseCandidates.reserve(m_poseCandidatesAfterCull);\n\n  // Copy all the poses that survived the initial cull. They are ordered in blocks: the first one is the one returned by\n  // estimate_pose, the second is the one removed after the last RANSAC iteration, the third and fourth are removed in the\n  // iteration before (whilst they are not in a specific order, they are worse than those in positions 0 and 1), etc.\n  const PoseCandidate *candidates = m_poseCandidates->GetData(MEMORYDEVICE_CPU);\n  for(uint32_t poseIdx = 0; poseIdx < m_poseCandidatesAfterCull; ++poseIdx)\n  {\n    poseCandidates.push_back(candidates[poseIdx]);\n  }\n}\n\nuint32_t PreemptiveRansac::get_min_nb_required_points() const\n{\n  // We need at least the number of inliers required for a RANSAC iteration.\n  return m_ransacInliersPerIteration;\n}\n\n//#################### PROTECTED MEMBER FUNCTIONS ####################\n\nvoid PreemptiveRansac::compute_candidate_poses_kabsch()\n{\n  // We assume that the data on the CPU is up-to-date (the CUDA subclass must ensure this).\n  // This function will probably go away as soon as we implement a shared SVD solver.\n  const int nbPoseCandidates = static_cast<int>(m_poseCandidates->dataSize);\n  PoseCandidate *poseCandidates = m_poseCandidates->GetData(MEMORYDEVICE_CPU);\n\n#if 0\n  std::cout << \"Generated \" << nbPoseCandidates << \" candidates.\" << std::endl;\n#endif\n\n  // For each candidate:\n#ifdef WITH_OPENMP\n  #pragma omp parallel for\n#endif\n  for(int candidateIdx = 0; candidateIdx < nbPoseCandidates; ++candidateIdx)\n  {\n    PoseCandidate& candidate = poseCandidates[candidateIdx];\n\n    // Copy the camera and world space points into two Eigen matrices (one point per column in each) on which we can run the Kabsch algorithm.\n    Eigen::Matrix3f cameraPoints;\n    Eigen::Matrix3f worldPoints;\n    for(int i = 0; i < PoseCandidate::KABSCH_CORRESPONDENCES_NEEDED; ++i)\n    {\n      cameraPoints.col(i) = Eigen::Map<const Eigen::Vector3f>(candidate.pointsCamera[i].v);\n      worldPoints.col(i) = Eigen::Map<const Eigen::Vector3f>(candidate.pointsWorld[i].v);\n    }\n\n    // Run the Kabsch algorithm and store the resulting camera -> world transformation in the candidate's cameraPose matrix.\n    Eigen::Map<Eigen::Matrix4f>(candidate.cameraPose.m) = GeometryUtil::estimate_rigid_transform(cameraPoints, worldPoints);\n  }\n}\n\nvoid PreemptiveRansac::reset_inliers(bool resetMask)\n{\n  if(resetMask)\n  {\n    m_inliersMaskImage->ChangeDims(m_keypointsImage->noDims); // happens only once (i.e. a no-op on subsequent occasions)\n    m_inliersMaskImage->Clear();\n  }\n\n  m_inlierRasterIndicesBlock->dataSize = 0;\n}\n\nbool PreemptiveRansac::update_candidate_pose(int candidateIdx) const\n#ifdef WITH_ALGLIB\ntry\n{\n  // Fill in the struct that will be passed to the optimiser.\n  PointsForLM ptsForLM;\n  ptsForLM.nbPoints = static_cast<uint32_t>(m_inlierRasterIndicesBlock->dataSize);                          // The current number of inlier points.\n  const uint32_t candidateOffset = ptsForLM.nbPoints * candidateIdx;                                        // The linearised offset in the pose optimisation buffers.\n  ptsForLM.cameraPoints = m_poseOptimisationCameraPoints->GetData(MEMORYDEVICE_CPU) + candidateOffset;      // Pointers to the data for this candidate.\n  ptsForLM.predictedModes = m_poseOptimisationPredictedModes->GetData(MEMORYDEVICE_CPU) + candidateOffset;\n\n  // Look up the pose candidate. The assumption is that all of the pose candidates have already been copied\n  // across to the CPU (non-CPU subclasses must ensure this). The plan is ultimately to reimplement the\n  // optimisation using shared code, but for now everything is done on the CPU.\n  PoseCandidate& poseCandidate = m_poseCandidates->GetData(MEMORYDEVICE_CPU)[candidateIdx];\n\n  // Convert the candidate's current pose to a 6D twist vector that can be optimised by alglib.\n  alglib::real_1d_array xi = make_twist_from_pose(poseCandidate.cameraPose);\n\n  // Set up the optimiser itself.\n  alglib::minlmstate state;\n  const double differentiationStep = 0.0001;\n#if 1\n  alglib::minlmcreatev(6, 1, xi, differentiationStep, state);\n#else\n  alglib::minlmcreatevj(6, 1, xi, state);\n#endif\n  alglib::minlmsetcond(state, m_poseOptimisationGradientThreshold, m_poseOptimisationEnergyThreshold, m_poseOptimisationStepThreshold, m_poseOptimisationMaxIterations);\n\n  // Run the optimiser.\n  if (m_usePredictionCovarianceForPoseOptimization)\n  {\n    alglib::minlmoptimize(state, alglib_func_mahalanobis, alglib_jac_mahalanobis, alglib_rep, &ptsForLM);\n  }\n  else\n  {\n    alglib::minlmoptimize(state, alglib_func_l2, alglib_jac_l2, alglib_rep, &ptsForLM);\n  }\n\n  // Extract the results of the optimisation.\n  alglib::minlmreport report;\n  alglib::minlmresults(state, xi, report);\n  const bool succeeded = report.terminationtype >= 0;\n\n  // Iff the optimisation succeeded, update the candidate's pose.\n  if(succeeded)\n  {\n    poseCandidate.cameraPose = make_pose_from_twist(xi).GetM();\n  }\n\n  return succeeded;\n}\ncatch(const alglib::ap_error& e)\n{\n  std::cout << \"ALGLIB failed the optimisation for pose candidate: \" << candidateIdx << \". Reason: \" << e.msg << \"\\n\";\n  return false;\n}\n#else\n{\n  throw std::runtime_error(\"Error: Cannot update candidate pose. Reconfigure in CMake with the WITH_ALGLIB option set to ON.\");\n}\n#endif\n\n//#################### PRIVATE MEMBER FUNCTIONS ####################\n\nvoid PreemptiveRansac::update_host_pose_candidates() const\n{\n  // No-op by default\n}\n\n//#################### PRIVATE STATIC MEMBER FUNCTIONS ####################\n\n#ifdef WITH_ALGLIB\nvoid PreemptiveRansac::alglib_func_l2(const alglib::real_1d_array& xi, alglib::real_1d_array& phi, void *pts)\n{\n  phi[0] = compute_energy_l2(make_pose_from_twist(xi), *reinterpret_cast<PointsForLM*>(pts));\n}\n\nvoid PreemptiveRansac::alglib_func_mahalanobis(const alglib::real_1d_array& xi, alglib::real_1d_array& phi, void *pts)\n{\n  phi[0] = compute_energy_mahalanobis(make_pose_from_twist(xi), *reinterpret_cast<PointsForLM*>(pts));\n}\n\nvoid PreemptiveRansac::alglib_jac_l2(const alglib::real_1d_array& xi, alglib::real_1d_array& phi, alglib::real_2d_array& jac, void *pts)\n{\n  phi[0] = compute_energy_l2(make_pose_from_twist(xi), *reinterpret_cast<PointsForLM*>(pts), jac[0]);\n}\n\nvoid PreemptiveRansac::alglib_jac_mahalanobis(const alglib::real_1d_array& xi, alglib::real_1d_array& phi, alglib::real_2d_array& jac, void *pts)\n{\n  phi[0] = compute_energy_mahalanobis(make_pose_from_twist(xi), *reinterpret_cast<PointsForLM*>(pts), jac[0]);\n}\n\nvoid PreemptiveRansac::alglib_rep(const alglib::real_1d_array& xi, double phi, void *pts)\n{\n  return;\n}\n#endif\n\ndouble PreemptiveRansac::compute_energy_l2(const ORUtils::SE3Pose& candidateCameraPose, const PointsForLM& pts, double *jac)\n{\n  double res = 0.0;\n\n  // If we're computing the Jacobian of the 6D twist vector, initially reset it to zero.\n  if(jac)\n  {\n    for(int i = 0; i < 6; ++i)\n    {\n      jac[i] = 0.0;\n    }\n  }\n\n  // For each point under consideration:\n  for(uint32_t i = 0; i < pts.nbPoints; ++i)\n  {\n    // If the point's position in camera space is invalid, skip it.\n    if(pts.cameraPoints[i].w == 0.0f) continue;\n\n    // Compute the difference between the point's position in world space (i) as predicted by the camera\n    // pose and its position in camera space, and (ii) as predicted by the position of the chosen mode.\n    const Vector3f cameraPoint = pts.cameraPoints[i].toVector3();\n    const Vector3f transformedPt = candidateCameraPose.GetM() * cameraPoint;\n    const Vector3f diff = transformedPt - pts.predictedModes[i].position;\n\n    // Based on this difference, add an L2 distance-based error term to the resulting energy.\n#if 1\n    const double err = dot(diff, diff); // squared L2 distance\n#else\n    const double err = length(diff);    // unsquared L2 distance\n#endif\n\n    res += err;\n\n    // If we're computing the Jacobian of the 6D twist vector, update it as per equation (10.23) in\n    // \"A tutorial on SE(3) transformation parameterizations and on-manifold optimization\" (Blanco).\n    if(jac)\n    {\n#if 1\n      const Vector3f normGradient = 2 * diff;   // for squared L2 distance\n#else\n      const Vector3f normGradient = diff / err; // for unsquared L2 distance\n#endif\n\n      const Vector3f poseGradient[6] = {\n        Vector3f(1.0f, 0.0f, 0.0f),\n        Vector3f(0.0f, 1.0f, 0.0f),\n        Vector3f(0.0f, 0.0f, 1.0f),\n        -Vector3f(0.0f, transformedPt.z, -transformedPt.y),\n        -Vector3f(-transformedPt.z, 0.0f, transformedPt.x),\n        -Vector3f(transformedPt.y, -transformedPt.x, 0.0f),\n      };\n\n      for(int i = 0; i < 6; ++i)\n      {\n        jac[i] += dot(normGradient, poseGradient[i]);\n      }\n    }\n  }\n\n  return res;\n}\n\ndouble PreemptiveRansac::compute_energy_mahalanobis(const ORUtils::SE3Pose& candidateCameraPose, const PointsForLM& pts, double *jac)\n{\n  double res = 0.0;\n\n  // If we're computing the Jacobian of the 6D twist vector, initially reset it to zero.\n  if(jac)\n  {\n    for(int i = 0; i < 6; ++i)\n    {\n      jac[i] = 0.0;\n    }\n  }\n\n  // For each point under consideration:\n  for(uint32_t i = 0; i < pts.nbPoints; ++i)\n  {\n    // If the point's position in camera space is invalid, skip it.\n    if(pts.cameraPoints[i].w == 0.0f) continue;\n\n    // Compute the difference between the point's position in world space (i) as predicted by the camera\n    // pose and its position in camera space, and (ii) as predicted by the position of the chosen mode.\n    const Vector3f transformedPt = candidateCameraPose.GetM() * pts.cameraPoints[i].toVector3();\n    const Vector3f diff = transformedPt - pts.predictedModes[i].position;\n\n    // Based on this difference, add a Mahalanobis distance-based error term to the resulting energy.\n    // See also: https://en.wikipedia.org/wiki/Mahalanobis_distance.\n    const Vector3f invCovarianceTimesDiff = pts.predictedModes[i].positionInvCovariance * diff;\n#if 1\n    const float err = dot(diff, invCovarianceTimesDiff);        // squared Mahalanobis distance\n#else\n    const float err = sqrtf(dot(diff, invCovarianceTimesDiff)); // unsquared Mahalanobis distance\n#endif\n\n    res += err;\n\n    // If we're computing the Jacobian of the 6D twist vector, update it accordingly.\n    if(jac)\n    {\n#if 1\n      const Vector3f normGradient = 2 * invCovarianceTimesDiff;   // for squared Mahalanobis distance\n#else\n      const Vector3f normGradient = invCovarianceTimesDiff / err; // for unsquared Mahalanobis distance\n#endif\n\n      const Vector3f poseGradient[6] = {\n        Vector3f(1.0f, 0.0f, 0.0f),\n        Vector3f(0.0f, 1.0f, 0.0f),\n        Vector3f(0.0f, 0.0f, 1.0f),\n        -Vector3f(0.0f, transformedPt.z, -transformedPt.y),\n        -Vector3f(-transformedPt.z, 0.0f, transformedPt.x),\n        -Vector3f(transformedPt.y, -transformedPt.x, 0.0f),\n      };\n\n      for(int i = 0; i < 6; ++i)\n      {\n        jac[i] += dot(normGradient, poseGradient[i]);\n      }\n    }\n  }\n\n  return res;\n}\n\n#ifdef WITH_ALGLIB\nORUtils::SE3Pose PreemptiveRansac::make_pose_from_twist(const alglib::real_1d_array& xi)\n{\n  return ORUtils::SE3Pose(\n    static_cast<float>(xi[0]),\n    static_cast<float>(xi[1]),\n    static_cast<float>(xi[2]),\n    static_cast<float>(xi[3]),\n    static_cast<float>(xi[4]),\n    static_cast<float>(xi[5])\n  );\n}\n\nalglib::real_1d_array PreemptiveRansac::make_twist_from_pose(const ORUtils::SE3Pose& pose)\n{\n  alglib::real_1d_array xi;\n  xi.setlength(6);\n  for(int i = 0; i < 6; ++i)\n  {\n    xi[i] = static_cast<double>(pose.GetParams()[i]);\n  }\n  return xi;\n}\n#endif\n\nvoid PreemptiveRansac::print_timer(const AverageTimer& timer)\n{\n  std::cout << timer.name() << \": \" << timer.count() << \" times, avg: \" << timer.average_duration() << \".\\n\";\n}\n\n}\n", "meta": {"hexsha": "d6ba86f369a07fa24904a21127da68e0548fd823", "size": 26018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/grove/src/ransac/interface/PreemptiveRansac.cpp", "max_stars_repo_name": "torrvision/spaint", "max_stars_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-10-01T07:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T03:02:31.000Z", "max_issues_repo_path": "modules/grove/src/ransac/interface/PreemptiveRansac.cpp", "max_issues_repo_name": "torrvision/spaint", "max_issues_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2016-03-26T13:01:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-02T09:13:49.000Z", "max_forks_repo_path": "modules/grove/src/ransac/interface/PreemptiveRansac.cpp", "max_forks_repo_name": "torrvision/spaint", "max_forks_repo_head_hexsha": "9cac8100323ea42fe439f66407b832b88f72d2fd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2015-10-03T07:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T08:58:18.000Z", "avg_line_length": 42.3056910569, "max_line_length": 268, "alphanum_fraction": 0.7149281267, "num_tokens": 6718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.020964241582733717, "lm_q1q2_score": 0.008147082195266681}}
{"text": "// Copyrights(c) 2017-2018, The BitcoinFlame Project\n// Copyrights(c) 2014-2017, The Monero Project\n// \n// All rights reserved.\n// \n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n// \n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n// \n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other\n//    materials provided with the distribution.\n// \n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    used to endorse or promote products derived from this software without specific\n//    prior written permission.\n// \n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n// \n// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers\n\n#include <cassert>\n#include <cstddef>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <memory>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/lock_guard.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"common/varint.h\"\n#include \"warnings.h\"\n#include \"crypto.h\"\n#include \"hash.h\"\n\nnamespace crypto {\n\n  using std::abort;\n  using std::int32_t;\n  using std::int64_t;\n  using std::size_t;\n  using std::uint32_t;\n  using std::uint64_t;\n\n  extern \"C\" {\n#include \"crypto-ops.h\"\n#include \"random.h\"\n  }\n\n  boost::mutex random_lock;\n\n  static inline unsigned char *operator &(ec_point &point) {\n    return &reinterpret_cast<unsigned char &>(point);\n  }\n\n  static inline const unsigned char *operator &(const ec_point &point) {\n    return &reinterpret_cast<const unsigned char &>(point);\n  }\n\n  static inline unsigned char *operator &(ec_scalar &scalar) {\n    return &reinterpret_cast<unsigned char &>(scalar);\n  }\n\n  static inline const unsigned char *operator &(const ec_scalar &scalar) {\n    return &reinterpret_cast<const unsigned char &>(scalar);\n  }\n\n  /* generate a random 32-byte (256-bit) integer and copy it to res */\n  static inline void random_scalar_not_thread_safe(ec_scalar &res) {\n    unsigned char tmp[64];\n    generate_random_bytes_not_thread_safe(64, tmp);\n    sc_reduce(tmp);\n    memcpy(&res, tmp, 32);\n  }\n  static inline void random_scalar(ec_scalar &res) {\n    boost::lock_guard<boost::mutex> lock(random_lock);\n    random_scalar_not_thread_safe(res);\n  }\n\n  static inline void hash_to_scalar(const void *data, size_t length, ec_scalar &res) {\n    cn_fast_hash(data, length, reinterpret_cast<hash &>(res));\n    sc_reduce32(&res);\n  }\n\n  /* \n   * generate public and secret keys from a random 256-bit integer\n   * TODO: allow specifiying random value (for wallet recovery)\n   * \n   */\n  secret_key crypto_ops::generate_keys(public_key &pub, secret_key &sec, const secret_key& recovery_key, bool recover) {\n    ge_p3 point;\n\n    secret_key rng;\n\n    if (recover)\n    {\n      rng = recovery_key;\n    }\n    else\n    {\n      random_scalar(rng);\n    }\n    sec = rng;\n    sc_reduce32(&sec);  // reduce in case second round of keys (sendkeys)\n\n    ge_scalarmult_base(&point, &sec);\n    ge_p3_tobytes(&pub, &point);\n\n    return rng;\n  }\n\n  bool crypto_ops::check_key(const public_key &key) {\n    ge_p3 point;\n    return ge_frombytes_vartime(&point, &key) == 0;\n  }\n\n  bool crypto_ops::secret_key_to_public_key(const secret_key &sec, public_key &pub) {\n    ge_p3 point;\n    if (sc_check(&sec) != 0) {\n      return false;\n    }\n    ge_scalarmult_base(&point, &sec);\n    ge_p3_tobytes(&pub, &point);\n    return true;\n  }\n\n  bool crypto_ops::generate_key_derivation(const public_key &key1, const secret_key &key2, key_derivation &derivation) {\n    ge_p3 point;\n    ge_p2 point2;\n    ge_p1p1 point3;\n    assert(sc_check(&key2) == 0);\n    if (ge_frombytes_vartime(&point, &key1) != 0) {\n      return false;\n    }\n    ge_scalarmult(&point2, &key2, &point);\n    ge_mul8(&point3, &point2);\n    ge_p1p1_to_p2(&point2, &point3);\n    ge_tobytes(&derivation, &point2);\n    return true;\n  }\n\n  void crypto_ops::derivation_to_scalar(const key_derivation &derivation, size_t output_index, ec_scalar &res) {\n    struct {\n      key_derivation derivation;\n      char output_index[(sizeof(size_t) * 8 + 6) / 7];\n    } buf;\n    char *end = buf.output_index;\n    buf.derivation = derivation;\n    tools::write_varint(end, output_index);\n    assert(end <= buf.output_index + sizeof buf.output_index);\n    hash_to_scalar(&buf, end - reinterpret_cast<char *>(&buf), res);\n  }\n\n  bool crypto_ops::derive_public_key(const key_derivation &derivation, size_t output_index,\n    const public_key &base, public_key &derived_key) {\n    ec_scalar scalar;\n    ge_p3 point1;\n    ge_p3 point2;\n    ge_cached point3;\n    ge_p1p1 point4;\n    ge_p2 point5;\n    if (ge_frombytes_vartime(&point1, &base) != 0) {\n      return false;\n    }\n    derivation_to_scalar(derivation, output_index, scalar);\n    ge_scalarmult_base(&point2, &scalar);\n    ge_p3_to_cached(&point3, &point2);\n    ge_add(&point4, &point1, &point3);\n    ge_p1p1_to_p2(&point5, &point4);\n    ge_tobytes(&derived_key, &point5);\n    return true;\n  }\n\n  void crypto_ops::derive_secret_key(const key_derivation &derivation, size_t output_index,\n    const secret_key &base, secret_key &derived_key) {\n    ec_scalar scalar;\n    assert(sc_check(&base) == 0);\n    derivation_to_scalar(derivation, output_index, scalar);\n    sc_add(&derived_key, &base, &scalar);\n  }\n\n  struct s_comm {\n    hash h;\n    ec_point key;\n    ec_point comm;\n  };\n\n  struct s_comm_2 {\n    hash msg;\n    ec_point D;\n    ec_point X;\n    ec_point Y;\n  };\n\n  void crypto_ops::generate_signature(const hash &prefix_hash, const public_key &pub, const secret_key &sec, signature &sig) {\n    ge_p3 tmp3;\n    ec_scalar k;\n    s_comm buf;\n#if !defined(NDEBUG)\n    {\n      ge_p3 t;\n      public_key t2;\n      assert(sc_check(&sec) == 0);\n      ge_scalarmult_base(&t, &sec);\n      ge_p3_tobytes(&t2, &t);\n      assert(pub == t2);\n    }\n#endif\n    buf.h = prefix_hash;\n    buf.key = pub;\n    random_scalar(k);\n    ge_scalarmult_base(&tmp3, &k);\n    ge_p3_tobytes(&buf.comm, &tmp3);\n    hash_to_scalar(&buf, sizeof(s_comm), sig.c);\n    sc_mulsub(&sig.r, &sig.c, &sec, &k);\n  }\n\n  bool crypto_ops::check_signature(const hash &prefix_hash, const public_key &pub, const signature &sig) {\n    ge_p2 tmp2;\n    ge_p3 tmp3;\n    ec_scalar c;\n    s_comm buf;\n    assert(check_key(pub));\n    buf.h = prefix_hash;\n    buf.key = pub;\n    if (ge_frombytes_vartime(&tmp3, &pub) != 0) {\n      return false;\n    }\n    if (sc_check(&sig.c) != 0 || sc_check(&sig.r) != 0) {\n      return false;\n    }\n    ge_double_scalarmult_base_vartime(&tmp2, &sig.c, &tmp3, &sig.r);\n    ge_tobytes(&buf.comm, &tmp2);\n    hash_to_scalar(&buf, sizeof(s_comm), c);\n    sc_sub(&c, &c, &sig.c);\n    return sc_isnonzero(&c) == 0;\n  }\n\n  void crypto_ops::generate_tx_proof(const hash &prefix_hash, const public_key &R, const public_key &A, const public_key &D, const secret_key &r, signature &sig) {\n    // sanity check\n    ge_p3 R_p3;\n    ge_p3 A_p3;\n    ge_p3 D_p3;\n    if (ge_frombytes_vartime(&R_p3, &R) != 0) throw std::runtime_error(\"tx pubkey is invalid\");\n    if (ge_frombytes_vartime(&A_p3, &A) != 0) throw std::runtime_error(\"recipient view pubkey is invalid\");\n    if (ge_frombytes_vartime(&D_p3, &D) != 0) throw std::runtime_error(\"key derivation is invalid\");\n#if !defined(NDEBUG)\n    {\n      assert(sc_check(&r) == 0);\n      // check R == r*G\n      ge_p3 dbg_R_p3;\n      ge_scalarmult_base(&dbg_R_p3, &r);\n      public_key dbg_R;\n      ge_p3_tobytes(&dbg_R, &dbg_R_p3);\n      assert(R == dbg_R);\n      // check D == r*A\n      ge_p2 dbg_D_p2;\n      ge_scalarmult(&dbg_D_p2, &r, &A_p3);\n      public_key dbg_D;\n      ge_tobytes(&dbg_D, &dbg_D_p2);\n      assert(D == dbg_D);\n    }\n#endif\n\n    // pick random k\n    ec_scalar k;\n    random_scalar(k);\n    \n    // compute X = k*G\n    ge_p3 X_p3;\n    ge_scalarmult_base(&X_p3, &k);\n    \n    // compute Y = k*A\n    ge_p2 Y_p2;\n    ge_scalarmult(&Y_p2, &k, &A_p3);\n\n    // sig.c = Hs(Msg || D || X || Y)\n    s_comm_2 buf;\n    buf.msg = prefix_hash;\n    buf.D = D;\n    ge_p3_tobytes(&buf.X, &X_p3);\n    ge_tobytes(&buf.Y, &Y_p2);\n    hash_to_scalar(&buf, sizeof(s_comm_2), sig.c);\n\n    // sig.r = k - sig.c*r\n    sc_mulsub(&sig.r, &sig.c, &r, &k);\n  }\n\n  bool crypto_ops::check_tx_proof(const hash &prefix_hash, const public_key &R, const public_key &A, const public_key &D, const signature &sig) {\n    // sanity check\n    ge_p3 R_p3;\n    ge_p3 A_p3;\n    ge_p3 D_p3;\n    if (ge_frombytes_vartime(&R_p3, &R) != 0) return false;\n    if (ge_frombytes_vartime(&A_p3, &A) != 0) return false;\n    if (ge_frombytes_vartime(&D_p3, &D) != 0) return false;\n    if (sc_check(&sig.c) != 0 || sc_check(&sig.r) != 0) return false;\n\n    // compute sig.c*R\n    ge_p2 cR_p2;\n    ge_scalarmult(&cR_p2, &sig.c, &R_p3);\n\n    // compute sig.r*G\n    ge_p3 rG_p3;\n    ge_scalarmult_base(&rG_p3, &sig.r);\n\n    // compute sig.c*D\n    ge_p2 cD_p2;\n    ge_scalarmult(&cD_p2, &sig.c, &D_p3);\n\n    // compute sig.r*A\n    ge_p2 rA_p2;\n    ge_scalarmult(&rA_p2, &sig.r, &A_p3);\n\n    // compute X = sig.c*R + sig.r*G\n    public_key cR;\n    ge_tobytes(&cR, &cR_p2);\n    ge_p3 cR_p3;\n    if (ge_frombytes_vartime(&cR_p3, &cR) != 0) return false;\n    ge_cached rG_cached;\n    ge_p3_to_cached(&rG_cached, &rG_p3);\n    ge_p1p1 X_p1p1;\n    ge_add(&X_p1p1, &cR_p3, &rG_cached);\n    ge_p2 X_p2;\n    ge_p1p1_to_p2(&X_p2, &X_p1p1);\n\n    // compute Y = sig.c*D + sig.r*A\n    public_key cD;\n    public_key rA;\n    ge_tobytes(&cD, &cD_p2);\n    ge_tobytes(&rA, &rA_p2);\n    ge_p3 cD_p3;\n    ge_p3 rA_p3;\n    if (ge_frombytes_vartime(&cD_p3, &cD) != 0) return false;\n    if (ge_frombytes_vartime(&rA_p3, &rA) != 0) return false;\n    ge_cached rA_cached;\n    ge_p3_to_cached(&rA_cached, &rA_p3);\n    ge_p1p1 Y_p1p1;\n    ge_add(&Y_p1p1, &cD_p3, &rA_cached);\n    ge_p2 Y_p2;\n    ge_p1p1_to_p2(&Y_p2, &Y_p1p1);\n\n    // compute c2 = Hs(Msg || D || X || Y)\n    s_comm_2 buf;\n    buf.msg = prefix_hash;\n    buf.D = D;\n    ge_tobytes(&buf.X, &X_p2);\n    ge_tobytes(&buf.Y, &Y_p2);\n    ec_scalar c2;\n    hash_to_scalar(&buf, sizeof(s_comm_2), c2);\n\n    // test if c2 == sig.c\n    sc_sub(&c2, &c2, &sig.c);\n    return sc_isnonzero(&c2) == 0;\n  }\n\n  static void hash_to_ec(const public_key &key, ge_p3 &res) {\n    hash h;\n    ge_p2 point;\n    ge_p1p1 point2;\n    cn_fast_hash(std::addressof(key), sizeof(public_key), h);\n    ge_fromfe_frombytes_vartime(&point, reinterpret_cast<const unsigned char *>(&h));\n    ge_mul8(&point2, &point);\n    ge_p1p1_to_p3(&res, &point2);\n  }\n\n  void crypto_ops::generate_key_image(const public_key &pub, const secret_key &sec, key_image &image) {\n    ge_p3 point;\n    ge_p2 point2;\n    assert(sc_check(&sec) == 0);\n    hash_to_ec(pub, point);\n    ge_scalarmult(&point2, &sec, &point);\n    ge_tobytes(&image, &point2);\n  }\n\nPUSH_WARNINGS\nDISABLE_VS_WARNINGS(4200)\n  struct ec_point_pair {\n    ec_point a, b;\n  };\n  struct rs_comm {\n    hash h;\n    struct ec_point_pair ab[];\n  };\nPOP_WARNINGS\n\n  static inline size_t rs_comm_size(size_t pubs_count) {\n    return sizeof(rs_comm) + pubs_count * sizeof(ec_point_pair);\n  }\n\n  void crypto_ops::generate_ring_signature(const hash &prefix_hash, const key_image &image,\n    const public_key *const *pubs, size_t pubs_count,\n    const secret_key &sec, size_t sec_index,\n    signature *sig) {\n    size_t i;\n    ge_p3 image_unp;\n    ge_dsmp image_pre;\n    ec_scalar sum, k, h;\n    boost::shared_ptr<rs_comm> buf(reinterpret_cast<rs_comm *>(malloc(rs_comm_size(pubs_count))), free);\n    if (!buf)\n      abort();\n    assert(sec_index < pubs_count);\n#if !defined(NDEBUG)\n    {\n      ge_p3 t;\n      public_key t2;\n      key_image t3;\n      assert(sc_check(&sec) == 0);\n      ge_scalarmult_base(&t, &sec);\n      ge_p3_tobytes(&t2, &t);\n      assert(*pubs[sec_index] == t2);\n      generate_key_image(*pubs[sec_index], sec, t3);\n      assert(image == t3);\n      for (i = 0; i < pubs_count; i++) {\n        assert(check_key(*pubs[i]));\n      }\n    }\n#endif\n    if (ge_frombytes_vartime(&image_unp, &image) != 0) {\n      abort();\n    }\n    ge_dsm_precomp(image_pre, &image_unp);\n    sc_0(&sum);\n    buf->h = prefix_hash;\n    for (i = 0; i < pubs_count; i++) {\n      ge_p2 tmp2;\n      ge_p3 tmp3;\n      if (i == sec_index) {\n        random_scalar(k);\n        ge_scalarmult_base(&tmp3, &k);\n        ge_p3_tobytes(&buf->ab[i].a, &tmp3);\n        hash_to_ec(*pubs[i], tmp3);\n        ge_scalarmult(&tmp2, &k, &tmp3);\n        ge_tobytes(&buf->ab[i].b, &tmp2);\n      } else {\n        random_scalar(sig[i].c);\n        random_scalar(sig[i].r);\n        if (ge_frombytes_vartime(&tmp3, &*pubs[i]) != 0) {\n          abort();\n        }\n        ge_double_scalarmult_base_vartime(&tmp2, &sig[i].c, &tmp3, &sig[i].r);\n        ge_tobytes(&buf->ab[i].a, &tmp2);\n        hash_to_ec(*pubs[i], tmp3);\n        ge_double_scalarmult_precomp_vartime(&tmp2, &sig[i].r, &tmp3, &sig[i].c, image_pre);\n        ge_tobytes(&buf->ab[i].b, &tmp2);\n        sc_add(&sum, &sum, &sig[i].c);\n      }\n    }\n    hash_to_scalar(buf.get(), rs_comm_size(pubs_count), h);\n    sc_sub(&sig[sec_index].c, &h, &sum);\n    sc_mulsub(&sig[sec_index].r, &sig[sec_index].c, &sec, &k);\n  }\n\n  bool crypto_ops::check_ring_signature(const hash &prefix_hash, const key_image &image,\n    const public_key *const *pubs, size_t pubs_count,\n    const signature *sig) {\n    size_t i;\n    ge_p3 image_unp;\n    ge_dsmp image_pre;\n    ec_scalar sum, h;\n    boost::shared_ptr<rs_comm> buf(reinterpret_cast<rs_comm *>(malloc(rs_comm_size(pubs_count))), free);\n    if (!buf)\n      return false;\n#if !defined(NDEBUG)\n    for (i = 0; i < pubs_count; i++) {\n      assert(check_key(*pubs[i]));\n    }\n#endif\n    if (ge_frombytes_vartime(&image_unp, &image) != 0) {\n      return false;\n    }\n    ge_dsm_precomp(image_pre, &image_unp);\n    sc_0(&sum);\n    buf->h = prefix_hash;\n    for (i = 0; i < pubs_count; i++) {\n      ge_p2 tmp2;\n      ge_p3 tmp3;\n      if (sc_check(&sig[i].c) != 0 || sc_check(&sig[i].r) != 0) {\n        return false;\n      }\n      if (ge_frombytes_vartime(&tmp3, &*pubs[i]) != 0) {\n        return false;\n      }\n      ge_double_scalarmult_base_vartime(&tmp2, &sig[i].c, &tmp3, &sig[i].r);\n      ge_tobytes(&buf->ab[i].a, &tmp2);\n      hash_to_ec(*pubs[i], tmp3);\n      ge_double_scalarmult_precomp_vartime(&tmp2, &sig[i].r, &tmp3, &sig[i].c, image_pre);\n      ge_tobytes(&buf->ab[i].b, &tmp2);\n      sc_add(&sum, &sum, &sig[i].c);\n    }\n    hash_to_scalar(buf.get(), rs_comm_size(pubs_count), h);\n    sc_sub(&h, &h, &sum);\n    return sc_isnonzero(&h) == 0;\n  }\n}\n", "meta": {"hexsha": "8b043d47977add01ca3f4a3450a8311e53d68287", "size": 15374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypto/crypto.cpp", "max_stars_repo_name": "bitcoinflame/bitcoinflame", "max_stars_repo_head_hexsha": "53515d8fa46ad47c90ea6e4c02d571943bf710b1", "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/crypto/crypto.cpp", "max_issues_repo_name": "bitcoinflame/bitcoinflame", "max_issues_repo_head_hexsha": "53515d8fa46ad47c90ea6e4c02d571943bf710b1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crypto/crypto.cpp", "max_forks_repo_name": "bitcoinflame/bitcoinflame", "max_forks_repo_head_hexsha": "53515d8fa46ad47c90ea6e4c02d571943bf710b1", "max_forks_repo_licenses": ["BSD-3-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.3234714004, "max_line_length": 163, "alphanum_fraction": 0.6473917003, "num_tokens": 4774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.016403032125488794, "lm_q1q2_score": 0.008137443022068253}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"PhreeqcIO.h\"\n\n#include <IPhreeqc.h>\n\n#include <boost/algorithm/string.hpp>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <numeric>\n\n#include \"BaseLib/Algorithm.h\"\n#include \"BaseLib/ConfigTreeUtil.h\"\n#include \"MaterialLib/MPL/Medium.h\"\n#include \"MathLib/LinAlg/Eigen/EigenVector.h\"\n#include \"MathLib/LinAlg/LinAlg.h\"\n#include \"MeshLib/Mesh.h\"\n#include \"PhreeqcIOData/AqueousSolution.h\"\n#include \"PhreeqcIOData/ChemicalSystem.h\"\n#include \"PhreeqcIOData/Dump.h\"\n#include \"PhreeqcIOData/EquilibriumReactant.h\"\n#include \"PhreeqcIOData/Exchange.h\"\n#include \"PhreeqcIOData/KineticReactant.h\"\n#include \"PhreeqcIOData/Knobs.h\"\n#include \"PhreeqcIOData/Output.h\"\n#include \"PhreeqcIOData/ReactionRate.h\"\n#include \"PhreeqcIOData/Surface.h\"\n#include \"PhreeqcIOData/UserPunch.h\"\n\nnamespace ChemistryLib\n{\nnamespace PhreeqcIOData\n{\nnamespace\n{\ntemplate <class... Ts>\nstruct overloaded : Ts...\n{\n    using Ts::operator()...;\n};\ntemplate <class... Ts>\noverloaded(Ts...) -> overloaded<Ts...>;\n\ntemplate <typename DataBlock>\nstd::ostream& operator<<(std::ostream& os,\n                         std::vector<DataBlock> const& data_blocks)\n{\n    std::copy(data_blocks.begin(), data_blocks.end(),\n              std::ostream_iterator<DataBlock>(os));\n    return os;\n}\n\nvoid setAqueousSolution(std::vector<double> const& concentrations,\n                        GlobalIndexType const& chemical_system_id,\n                        AqueousSolution& aqueous_solution)\n{\n    // components\n    auto& components = aqueous_solution.components;\n    for (unsigned component_id = 0; component_id < components.size();\n         ++component_id)\n    {\n        MathLib::LinAlg::setLocalAccessibleVector(\n            *components[component_id].amount);\n        components[component_id].amount->set(chemical_system_id,\n                                             concentrations[component_id]);\n    }\n\n    // pH\n    MathLib::LinAlg::setLocalAccessibleVector(*aqueous_solution.pH);\n    aqueous_solution.pH->set(chemical_system_id, concentrations.back());\n}\n\ntemplate <typename Reactant>\nvoid initializeReactantMolality(Reactant& reactant,\n                                GlobalIndexType const& chemical_system_id,\n                                MaterialPropertyLib::Phase const& solid_phase,\n                                MaterialPropertyLib::Phase const& liquid_phase,\n                                MaterialPropertyLib::Medium const& medium,\n                                ParameterLib::SpatialPosition const& pos,\n                                double const t)\n{\n    auto const& solid_constituent = solid_phase.component(reactant.name);\n\n    if (solid_constituent.hasProperty(\n            MaterialPropertyLib::PropertyType::molality))\n    {\n        auto const molality =\n            solid_constituent[MaterialPropertyLib::PropertyType::molality]\n                .template initialValue<double>(pos, t);\n\n        (*reactant.molality)[chemical_system_id] = molality;\n        (*reactant.molality_prev)[chemical_system_id] = molality;\n    }\n    else\n    {\n        auto const volume_fraction =\n            solid_constituent\n                [MaterialPropertyLib::PropertyType::volume_fraction]\n                    .template initialValue<double>(pos, t);\n\n        (*reactant.volume_fraction)[chemical_system_id] = volume_fraction;\n\n        (*reactant.volume_fraction_prev)[chemical_system_id] = volume_fraction;\n\n        auto const fluid_density =\n            liquid_phase[MaterialPropertyLib::PropertyType::density]\n                .template initialValue<double>(pos, t);\n\n        auto const porosity =\n            medium[MaterialPropertyLib::PropertyType::porosity]\n                .template initialValue<double>(pos, t);\n\n        auto const molar_volume =\n            solid_constituent[MaterialPropertyLib::PropertyType::molar_volume]\n                .template initialValue<double>(pos, t);\n\n        (*reactant.molality)[chemical_system_id] =\n            volume_fraction / fluid_density / porosity / molar_volume;\n\n        (*reactant.molality_prev)[chemical_system_id] =\n            (*reactant.molality)[chemical_system_id];\n    }\n}\n\ntemplate <typename Reactant>\nvoid setReactantMolality(Reactant& reactant,\n                         GlobalIndexType const& chemical_system_id,\n                         MaterialPropertyLib::Phase const& solid_phase,\n                         MaterialPropertyLib::Phase const& liquid_phase,\n                         MaterialPropertyLib::VariableArray const& vars,\n                         ParameterLib::SpatialPosition const& pos,\n                         double const t, double const dt)\n{\n    auto const& solid_constituent = solid_phase.component(reactant.name);\n\n    if (solid_constituent.hasProperty(\n            MaterialPropertyLib::PropertyType::molality))\n    {\n        (*reactant.molality_prev)[chemical_system_id] =\n            (*reactant.molality)[chemical_system_id];\n\n        return;\n    }\n\n    auto const volume_fraction =\n        (*reactant.volume_fraction)[chemical_system_id];\n\n    (*reactant.volume_fraction_prev)[chemical_system_id] =\n        (*reactant.volume_fraction)[chemical_system_id];\n\n    auto const fluid_density =\n        liquid_phase[MaterialPropertyLib::PropertyType::density]\n            .template value<double>(vars, pos, t, dt);\n\n    auto const porosity = std::get<double>(\n        vars[static_cast<int>(MaterialPropertyLib::Variable::porosity)]);\n\n    auto const molar_volume =\n        solid_constituent[MaterialPropertyLib::PropertyType::molar_volume]\n            .template value<double>(vars, pos, t, dt);\n\n    (*reactant.molality)[chemical_system_id] =\n        volume_fraction / fluid_density / porosity / molar_volume;\n\n    (*reactant.molality_prev)[chemical_system_id] =\n        (*reactant.molality)[chemical_system_id];\n}\n\ntemplate <typename Site>\nvoid initializeSiteMolality(Site& site,\n                            GlobalIndexType const& chemical_system_id,\n                            MaterialPropertyLib::Phase const& solid_phase,\n                            ParameterLib::SpatialPosition const& pos,\n                            double const t)\n{\n    auto const& solid_constituent = solid_phase.component(site.name);\n\n    auto const molality =\n        solid_constituent[MaterialPropertyLib::PropertyType::molality]\n            .template initialValue<double>(pos, t);\n\n    (*site.molality)[chemical_system_id] = molality;\n}\n\ntemplate <typename Reactant>\nvoid updateReactantVolumeFraction(Reactant& reactant,\n                                  GlobalIndexType const& chemical_system_id,\n                                  MaterialPropertyLib::Medium const& medium,\n                                  ParameterLib::SpatialPosition const& pos,\n                                  double const porosity, double const t,\n                                  double const dt)\n{\n    auto const& solid_phase = medium.phase(\"Solid\");\n    auto const& liquid_phase = medium.phase(\"AqueousLiquid\");\n\n    MaterialPropertyLib::VariableArray vars;\n\n    auto const liquid_density =\n        liquid_phase[MaterialPropertyLib::PropertyType::density]\n            .template value<double>(vars, pos, t, dt);\n\n    auto const& solid_constituent = solid_phase.component(reactant.name);\n\n    if (solid_constituent.hasProperty(\n            MaterialPropertyLib::PropertyType::molality))\n    {\n        return;\n    }\n\n    auto const molar_volume =\n        solid_constituent[MaterialPropertyLib::PropertyType::molar_volume]\n            .template value<double>(vars, pos, t, dt);\n\n    (*reactant.volume_fraction)[chemical_system_id] +=\n        ((*reactant.molality)[chemical_system_id] -\n         (*reactant.molality_prev)[chemical_system_id]) *\n        liquid_density * porosity * molar_volume;\n}\n\ntemplate <typename Reactant>\nvoid setPorosityPostReaction(Reactant& reactant,\n                             GlobalIndexType const& chemical_system_id,\n                             MaterialPropertyLib::Medium const& medium,\n                             double& porosity)\n{\n    auto const& solid_phase = medium.phase(\"Solid\");\n\n    auto const& solid_constituent = solid_phase.component(reactant.name);\n\n    if (solid_constituent.hasProperty(\n            MaterialPropertyLib::PropertyType::molality))\n    {\n        return;\n    }\n\n    porosity -= ((*reactant.volume_fraction)[chemical_system_id] -\n                 (*reactant.volume_fraction_prev)[chemical_system_id]);\n}\n\ntemplate <typename Reactant>\nstatic double averageReactantMolality(\n    Reactant const& reactant,\n    std::vector<GlobalIndexType> const& chemical_system_indices)\n{\n    double const sum = std::accumulate(\n        chemical_system_indices.begin(), chemical_system_indices.end(), 0.0,\n        [&](double const s, GlobalIndexType const id)\n        { return s + (*reactant.molality)[id]; });\n    return sum / chemical_system_indices.size();\n}\n}  // namespace\n\nPhreeqcIO::PhreeqcIO(MeshLib::Mesh const& mesh,\n                     GlobalLinearSolver& linear_solver,\n                     std::string const& project_file_name,\n                     std::string&& database,\n                     std::unique_ptr<ChemicalSystem>&& chemical_system,\n                     std::vector<ReactionRate>&& reaction_rates,\n                     std::unique_ptr<UserPunch>&& user_punch,\n                     std::unique_ptr<Output>&& output,\n                     std::unique_ptr<Dump>&& dump,\n                     Knobs&& knobs)\n    : ChemicalSolverInterface(mesh, linear_solver),\n      _phreeqc_input_file(project_file_name + \"_phreeqc.inp\"),\n      _database(std::move(database)),\n      _chemical_system(std::move(chemical_system)),\n      _reaction_rates(std::move(reaction_rates)),\n      _user_punch(std::move(user_punch)),\n      _output(std::move(output)),\n      _dump(std::move(dump)),\n      _knobs(std::move(knobs))\n{\n    // initialize phreeqc instance\n    if (CreateIPhreeqc() != phreeqc_instance_id)\n    {\n        OGS_FATAL(\n            \"Failed to initialize phreeqc instance, due to lack of memory.\");\n    }\n\n    // load specified thermodynamic database\n    if (LoadDatabase(phreeqc_instance_id, _database.c_str()) != IPQ_OK)\n    {\n        OGS_FATAL(\n            \"Failed in loading the specified thermodynamic database file: \"\n            \"{:s}.\",\n            _database);\n    }\n\n    if (SetSelectedOutputFileOn(phreeqc_instance_id, 1) != IPQ_OK)\n    {\n        OGS_FATAL(\n            \"Failed to fly the flag for the specified file {:s} where phreeqc \"\n            \"will write output.\",\n            _output->basic_output_setups.output_file);\n    }\n\n    if (_dump)\n    {\n        // Chemical composition of the aqueous solution of last time step will\n        // be written into .dmp file once the second function argument is set to\n        // one.\n        SetDumpFileOn(phreeqc_instance_id, 1);\n    }\n}\n\nPhreeqcIO::~PhreeqcIO()\n{\n    DestroyIPhreeqc(phreeqc_instance_id);\n}\n\nvoid PhreeqcIO::initialize()\n{\n    _num_chemical_systems = chemical_system_index_map.size();\n\n    _chemical_system->initialize(_num_chemical_systems);\n\n    if (_user_punch)\n    {\n        _user_punch->initialize(_num_chemical_systems);\n    }\n}\n\nvoid PhreeqcIO::initializeChemicalSystemConcrete(\n    std::vector<double> const& concentrations,\n    GlobalIndexType const& chemical_system_id,\n    MaterialPropertyLib::Medium const& medium,\n    ParameterLib::SpatialPosition const& pos,\n    double const t)\n{\n    setAqueousSolution(concentrations, chemical_system_id,\n                       *_chemical_system->aqueous_solution);\n\n    auto const& solid_phase = medium.phase(\"Solid\");\n    auto const& liquid_phase = medium.phase(\"AqueousLiquid\");\n\n    for (auto& kinetic_reactant : _chemical_system->kinetic_reactants)\n    {\n        initializeReactantMolality(kinetic_reactant, chemical_system_id,\n                                   solid_phase, liquid_phase, medium, pos, t);\n    }\n\n    for (auto& equilibrium_reactant : _chemical_system->equilibrium_reactants)\n    {\n        initializeReactantMolality(equilibrium_reactant, chemical_system_id,\n                                   solid_phase, liquid_phase, medium, pos, t);\n    }\n\n    for (auto& exchanger : _chemical_system->exchangers)\n    {\n        initializeSiteMolality(exchanger, chemical_system_id, solid_phase, pos,\n                               t);\n    }\n\n    for (auto& surface_site : _chemical_system->surface)\n    {\n        if (auto const surface_site_ptr =\n                std::get_if<MoleBasedSurfaceSite>(&surface_site))\n        {\n            initializeSiteMolality(*surface_site_ptr, chemical_system_id,\n                                   solid_phase, pos, t);\n        }\n    }\n}\n\nvoid PhreeqcIO::setChemicalSystemConcrete(\n    std::vector<double> const& concentrations,\n    GlobalIndexType const& chemical_system_id,\n    MaterialPropertyLib::Medium const* medium,\n    MaterialPropertyLib::VariableArray const& vars,\n    ParameterLib::SpatialPosition const& pos, double const t, double const dt)\n{\n    setAqueousSolution(concentrations, chemical_system_id,\n                       *_chemical_system->aqueous_solution);\n\n    auto const& solid_phase = medium->phase(\"Solid\");\n    auto const& liquid_phase = medium->phase(\"AqueousLiquid\");\n\n    for (auto& kinetic_reactant : _chemical_system->kinetic_reactants)\n    {\n        setReactantMolality(kinetic_reactant, chemical_system_id, solid_phase,\n                            liquid_phase, vars, pos, t, dt);\n    }\n\n    for (auto& equilibrium_reactant : _chemical_system->equilibrium_reactants)\n    {\n        setReactantMolality(equilibrium_reactant, chemical_system_id,\n                            solid_phase, liquid_phase, vars, pos, t, dt);\n    }\n}\n\nvoid PhreeqcIO::executeSpeciationCalculation(double const dt)\n{\n    writeInputsToFile(dt);\n\n    callPhreeqc();\n\n    readOutputsFromFile();\n}\n\nstd::vector<GlobalVector*> PhreeqcIO::getIntPtProcessSolutions() const\n{\n    auto const& aqueous_solution = _chemical_system->aqueous_solution;\n    std::vector<GlobalVector*> int_pt_process_solutions;\n    int_pt_process_solutions.reserve(aqueous_solution->components.size() + 1);\n\n    std::transform(aqueous_solution->components.begin(),\n                   aqueous_solution->components.end(),\n                   std::back_inserter(int_pt_process_solutions),\n                   [](auto const& c) { return c.amount.get(); });\n\n    int_pt_process_solutions.push_back(aqueous_solution->pH.get());\n\n    return int_pt_process_solutions;\n}\n\ndouble PhreeqcIO::getConcentration(\n    int const component_id, GlobalIndexType const chemical_system_id) const\n{\n    auto const& aqueous_solution = *_chemical_system->aqueous_solution;\n    auto& components = aqueous_solution.components;\n    auto const& pH = *aqueous_solution.pH;\n\n    return component_id < static_cast<int>(components.size())\n               ? components[component_id].amount->get(chemical_system_id)\n               : pH.get(chemical_system_id);\n}\n\nvoid PhreeqcIO::setAqueousSolutionsPrevFromDumpFile()\n{\n    if (!_dump)\n    {\n        return;\n    }\n\n    auto const& dump_file = _dump->dump_file;\n    std::ifstream in(dump_file);\n    if (!in)\n    {\n        // return if phreeqc dump file doesn't exist. Normally, this happens in\n        // the first time step.\n        return;\n    }\n\n    _dump->readDumpFile(in, _num_chemical_systems);\n\n    if (!in)\n    {\n        OGS_FATAL(\"Error when reading phreeqc dump file '{:s}'\", dump_file);\n    }\n\n    in.close();\n}\n\nvoid PhreeqcIO::writeInputsToFile(double const dt)\n{\n    DBUG(\"Writing phreeqc inputs into file '{:s}'.\", _phreeqc_input_file);\n    std::ofstream out(_phreeqc_input_file, std::ofstream::out);\n\n    if (!out)\n    {\n        OGS_FATAL(\"Could not open file '{:s}' for writing phreeqc inputs.\",\n                  _phreeqc_input_file);\n    }\n\n    out << std::scientific\n        << std::setprecision(std::numeric_limits<double>::digits10);\n    out << (*this << dt);\n\n    if (!out)\n    {\n        OGS_FATAL(\"Failed in generating phreeqc input file '{:s}'.\",\n                  _phreeqc_input_file);\n    }\n\n    out.close();\n}\n\nstd::ostream& operator<<(std::ostream& os, PhreeqcIO const& phreeqc_io)\n{\n    bool const fixing_pe =\n        phreeqc_io._chemical_system->aqueous_solution->fixing_pe;\n    if (fixing_pe)\n    {\n        os << \"PHASES\\n\"\n           << \"Fix_pe\\n\"\n           << \"e- = e-\\n\"\n           << \"log_k 0.0\\n\\n\";\n    }\n\n    os << phreeqc_io._knobs << \"\\n\";\n\n    os << *phreeqc_io._output << \"\\n\";\n\n    auto const& user_punch = phreeqc_io._user_punch;\n    if (user_punch)\n    {\n        os << *user_punch << \"\\n\";\n    }\n\n    auto const& reaction_rates = phreeqc_io._reaction_rates;\n    if (!reaction_rates.empty())\n    {\n        os << \"RATES\\n\";\n        os << reaction_rates << \"\\n\";\n    }\n\n    for (std::size_t chemical_system_id = 0;\n         chemical_system_id < phreeqc_io._num_chemical_systems;\n         ++chemical_system_id)\n    {\n        os << \"SOLUTION \" << chemical_system_id + 1 << \"\\n\";\n        phreeqc_io._chemical_system->aqueous_solution->print(\n            os, chemical_system_id);\n\n        auto const& dump = phreeqc_io._dump;\n        if (dump)\n        {\n            auto const& aqueous_solutions_prev = dump->aqueous_solutions_prev;\n            if (!aqueous_solutions_prev.empty())\n            {\n                os << aqueous_solutions_prev[chemical_system_id] << \"\\n\\n\";\n            }\n        }\n\n        os << \"USE solution none\\n\";\n        os << \"END\\n\\n\";\n\n        os << \"USE solution \" << chemical_system_id + 1 << \"\\n\\n\";\n\n        auto const& equilibrium_reactants =\n            phreeqc_io._chemical_system->equilibrium_reactants;\n        if (!equilibrium_reactants.empty() || fixing_pe)\n        {\n            os << \"EQUILIBRIUM_PHASES \" << chemical_system_id + 1 << \"\\n\";\n            for (auto const& equilibrium_reactant : equilibrium_reactants)\n            {\n                equilibrium_reactant.print(os, chemical_system_id);\n            }\n            fixing_pe\n                ? os << \"Fix_pe \"\n                     << -phreeqc_io._chemical_system->aqueous_solution->pe0\n                     << \" O2(g)\\n\\n\"\n                : os << \"\\n\";\n        }\n\n        auto const& kinetic_reactants =\n            phreeqc_io._chemical_system->kinetic_reactants;\n        if (!kinetic_reactants.empty())\n        {\n            os << \"KINETICS \" << chemical_system_id + 1 << \"\\n\";\n            for (auto const& kinetic_reactant : kinetic_reactants)\n            {\n                kinetic_reactant.print(os, chemical_system_id);\n            }\n            os << \"-steps \" << phreeqc_io._dt << \"\\n\\n\";\n        }\n\n        auto const& surface = phreeqc_io._chemical_system->surface;\n        if (!surface.empty())\n        {\n            os << \"SURFACE \" << chemical_system_id + 1 << \"\\n\";\n            std::size_t aqueous_solution_id =\n                dump->aqueous_solutions_prev.empty()\n                    ? chemical_system_id + 1\n                    : phreeqc_io._num_chemical_systems + chemical_system_id + 1;\n            os << \"-equilibrate with solution \" << aqueous_solution_id << \"\\n\";\n\n            // print unit\n            if (std::holds_alternative<DensityBasedSurfaceSite>(\n                    surface.front()))\n            {\n                os << \"-sites_units density\\n\";\n            }\n            else\n            {\n                os << \"-sites_units absolute\\n\";\n            }\n\n            for (auto const& surface_site : surface)\n            {\n                std::visit(\n                    overloaded{[&os](DensityBasedSurfaceSite const& s)\n                               {\n                                   os << s.name << \" \" << s.site_density << \" \"\n                                      << s.specific_surface_area << \" \"\n                                      << s.mass << \"\\n\";\n                               },\n                               [&os, chemical_system_id](\n                                   MoleBasedSurfaceSite const& s) {\n                                   os << s.name << \" \"\n                                      << (*s.molality)[chemical_system_id]\n                                      << \"\\n\";\n                               }},\n                    surface_site);\n            }\n\n            // overlook the effect of the buildup of charges onto the surface\n            if (std::holds_alternative<MoleBasedSurfaceSite>(surface.front()))\n            {\n                os << \"-no_edl\\n\";\n            }\n\n            os << \"SAVE solution \" << chemical_system_id + 1 << \"\\n\";\n        }\n\n        auto const& exchangers = phreeqc_io._chemical_system->exchangers;\n        if (!exchangers.empty())\n        {\n            os << \"EXCHANGE \" << chemical_system_id + 1 << \"\\n\";\n            std::size_t const aqueous_solution_id =\n                dump->aqueous_solutions_prev.empty()\n                    ? chemical_system_id + 1\n                    : phreeqc_io._num_chemical_systems + chemical_system_id + 1;\n            os << \"-equilibrate with solution \" << aqueous_solution_id << \"\\n\";\n            for (auto const& exchanger : exchangers)\n            {\n                exchanger.print(os, chemical_system_id);\n            }\n            os << \"SAVE solution \" << chemical_system_id + 1 << \"\\n\";\n        }\n\n        os << \"END\\n\\n\";\n    }\n\n    auto const& dump = phreeqc_io._dump;\n    if (dump)\n    {\n        dump->print(os, phreeqc_io._num_chemical_systems);\n    }\n\n    return os;\n}\n\nvoid PhreeqcIO::callPhreeqc()\n{\n    INFO(\"Phreeqc: Executing chemical calculation.\");\n    if (RunFile(phreeqc_instance_id, _phreeqc_input_file.c_str()) != IPQ_OK)\n    {\n        OutputErrorString(phreeqc_instance_id);\n        OGS_FATAL(\n            \"Failed in performing speciation calculation with the generated \"\n            \"phreeqc input file '{:s}'.\",\n            _phreeqc_input_file);\n    }\n}\n\nvoid PhreeqcIO::readOutputsFromFile()\n{\n    auto const& basic_output_setups = _output->basic_output_setups;\n    auto const& phreeqc_result_file = basic_output_setups.output_file;\n    DBUG(\"Reading phreeqc results from file '{:s}'.\", phreeqc_result_file);\n    std::ifstream in(phreeqc_result_file);\n\n    if (!in)\n    {\n        OGS_FATAL(\"Could not open phreeqc result file '{:s}'.\",\n                  phreeqc_result_file);\n    }\n\n    in >> *this;\n\n    if (!in)\n    {\n        OGS_FATAL(\"Error when reading phreeqc result file '{:s}'\",\n                  phreeqc_result_file);\n    }\n\n    in.close();\n}\n\nstd::istream& operator>>(std::istream& in, PhreeqcIO& phreeqc_io)\n{\n    // Skip the headline\n    in.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\n    std::string line;\n    auto const& output = *phreeqc_io._output;\n    auto const& dropped_item_ids = output.dropped_item_ids;\n\n    auto const& surface = phreeqc_io._chemical_system->surface;\n    auto const& exchangers = phreeqc_io._chemical_system->exchangers;\n\n    int const num_skipped_lines =\n        1 + (!surface.empty() ? 1 : 0) + (!exchangers.empty() ? 1 : 0);\n\n    auto& equilibrium_reactants =\n        phreeqc_io._chemical_system->equilibrium_reactants;\n    auto& kinetic_reactants = phreeqc_io._chemical_system->kinetic_reactants;\n\n    for (std::size_t chemical_system_id = 0;\n         chemical_system_id < phreeqc_io._num_chemical_systems;\n         ++chemical_system_id)\n    {\n        // Skip equilibrium calculation result of initial solution\n        for (int i = 0; i < num_skipped_lines; ++i)\n        {\n            in.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n        }\n\n        // Get calculation result of the solution after the reaction\n        if (!std::getline(in, line))\n        {\n            OGS_FATAL(\n                \"Error when reading calculation result of Solution {:d} \"\n                \"after the reaction.\",\n                chemical_system_id);\n        }\n\n        std::vector<double> accepted_items;\n        std::vector<std::string> items;\n        boost::trim_if(line, boost::is_any_of(\"\\t \"));\n        boost::algorithm::split(items, line, boost::is_any_of(\"\\t \"),\n                                boost::token_compress_on);\n        for (int item_id = 0; item_id < static_cast<int>(items.size());\n             ++item_id)\n        {\n            if (std::find(dropped_item_ids.begin(), dropped_item_ids.end(),\n                          item_id) == dropped_item_ids.end())\n            {\n                double value;\n                try\n                {\n                    value = std::stod(items[item_id]);\n                }\n                catch (const std::invalid_argument& e)\n                {\n                    OGS_FATAL(\n                        \"Invalid argument. Could not convert string '{:s}' to \"\n                        \"double for chemical system {:d}, column {:d}. \"\n                        \"Exception '{:s}' was thrown.\",\n                        items[item_id], chemical_system_id + 1, item_id,\n                        e.what());\n                }\n                catch (const std::out_of_range& e)\n                {\n                    OGS_FATAL(\n                        \"Out of range error. Could not convert string \"\n                        \"'{:s}' to double for chemical system {:d}, column \"\n                        \"{:d}. Exception '{:s}' was thrown.\",\n                        items[item_id], chemical_system_id + 1, item_id,\n                        e.what());\n                }\n                accepted_items.push_back(value);\n            }\n        }\n        assert(accepted_items.size() == output.accepted_items.size());\n\n        auto& aqueous_solution = phreeqc_io._chemical_system->aqueous_solution;\n        auto& components = aqueous_solution->components;\n        auto& user_punch = phreeqc_io._user_punch;\n        for (int item_id = 0; item_id < static_cast<int>(accepted_items.size());\n             ++item_id)\n        {\n            auto const& accepted_item = output.accepted_items[item_id];\n            auto const& item_name = accepted_item.name;\n\n            auto compare_by_name = [&item_name](auto const& item)\n            { return item.name == item_name; };\n\n            switch (accepted_item.item_type)\n            {\n                case ItemType::pH:\n                {\n                    // Update pH value\n                    MathLib::LinAlg::setLocalAccessibleVector(\n                        *aqueous_solution->pH);\n                    aqueous_solution->pH->set(\n                        chemical_system_id,\n                        std::pow(10, -accepted_items[item_id]));\n                    break;\n                }\n                case ItemType::pe:\n                {\n                    // Update pe value\n                    (*aqueous_solution->pe)[chemical_system_id] =\n                        accepted_items[item_id];\n                    break;\n                }\n                case ItemType::Component:\n                {\n                    // Update component concentrations\n                    auto& component = BaseLib::findElementOrError(\n                        components.begin(), components.end(), compare_by_name,\n                        \"Could not find component '\" + item_name + \"'.\");\n                    MathLib::LinAlg::setLocalAccessibleVector(\n                        *component.amount);\n                    component.amount->set(chemical_system_id,\n                                          accepted_items[item_id]);\n                    break;\n                }\n                case ItemType::EquilibriumReactant:\n                {\n                    // Update amounts of equilibrium reactant\n                    auto& equilibrium_reactant = BaseLib::findElementOrError(\n                        equilibrium_reactants.begin(),\n                        equilibrium_reactants.end(), compare_by_name,\n                        \"Could not find equilibrium reactant '\" + item_name +\n                            \"'.\");\n                    (*equilibrium_reactant.molality)[chemical_system_id] =\n                        accepted_items[item_id];\n                    break;\n                }\n                case ItemType::KineticReactant:\n                {\n                    // Update amounts of kinetic reactants\n                    auto& kinetic_reactant = BaseLib::findElementOrError(\n                        kinetic_reactants.begin(), kinetic_reactants.end(),\n                        compare_by_name,\n                        \"Could not find kinetic reactant '\" + item_name + \"'.\");\n                    (*kinetic_reactant.molality)[chemical_system_id] =\n                        accepted_items[item_id];\n                    break;\n                }\n                case ItemType::SecondaryVariable:\n                {\n                    assert(user_punch);\n                    auto& secondary_variables = user_punch->secondary_variables;\n                    // Update values of secondary variables\n                    auto& secondary_variable = BaseLib::findElementOrError(\n                        secondary_variables.begin(), secondary_variables.end(),\n                        compare_by_name,\n                        \"Could not find secondary variable '\" + item_name +\n                            \"'.\");\n                    (*secondary_variable.value)[chemical_system_id] =\n                        accepted_items[item_id];\n                    break;\n                }\n            }\n        }\n    }\n\n    return in;\n}\n\nstd::vector<std::string> const PhreeqcIO::getComponentList() const\n{\n    std::vector<std::string> component_names;\n    auto const& components = _chemical_system->aqueous_solution->components;\n    std::transform(components.begin(), components.end(),\n                   std::back_inserter(component_names),\n                   [](auto const& c) { return c.name; });\n\n    component_names.push_back(\"H\");\n\n    return component_names;\n}\n\nvoid PhreeqcIO::updateVolumeFractionPostReaction(\n    GlobalIndexType const& chemical_system_id,\n    MaterialPropertyLib::Medium const& medium,\n    ParameterLib::SpatialPosition const& pos, double const porosity,\n    double const t, double const dt)\n{\n    for (auto& kinetic_reactant : _chemical_system->kinetic_reactants)\n    {\n        updateReactantVolumeFraction(kinetic_reactant, chemical_system_id,\n                                     medium, pos, porosity, t, dt);\n    }\n\n    for (auto& equilibrium_reactant : _chemical_system->equilibrium_reactants)\n    {\n        updateReactantVolumeFraction(equilibrium_reactant, chemical_system_id,\n                                     medium, pos, porosity, t, dt);\n    }\n}\n\nvoid PhreeqcIO::updatePorosityPostReaction(\n    GlobalIndexType const& chemical_system_id,\n    MaterialPropertyLib::Medium const& medium,\n    double& porosity)\n{\n    for (auto& kinetic_reactant : _chemical_system->kinetic_reactants)\n    {\n        setPorosityPostReaction(kinetic_reactant, chemical_system_id, medium,\n                                porosity);\n    }\n\n    for (auto& equilibrium_reactant : _chemical_system->equilibrium_reactants)\n    {\n        setPorosityPostReaction(equilibrium_reactant, chemical_system_id,\n                                medium, porosity);\n    }\n}\n\nvoid PhreeqcIO::computeSecondaryVariable(\n    std::size_t const ele_id,\n    std::vector<GlobalIndexType> const& chemical_system_indices)\n{\n    for (auto& kinetic_reactant : _chemical_system->kinetic_reactants)\n    {\n        (*kinetic_reactant.mesh_prop_molality)[ele_id] =\n            averageReactantMolality(kinetic_reactant, chemical_system_indices);\n    }\n\n    for (auto& equilibrium_reactant : _chemical_system->equilibrium_reactants)\n    {\n        (*equilibrium_reactant.mesh_prop_molality)[ele_id] =\n            averageReactantMolality(equilibrium_reactant,\n                                    chemical_system_indices);\n    }\n}\n}  // namespace PhreeqcIOData\n}  // namespace ChemistryLib\n", "meta": {"hexsha": "c95fde08b91624e26d9474bd7806c98f30169ba2", "size": 31850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ChemistryLib/PhreeqcIO.cpp", "max_stars_repo_name": "garibay-j/ogs", "max_stars_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ChemistryLib/PhreeqcIO.cpp", "max_issues_repo_name": "garibay-j/ogs", "max_issues_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ChemistryLib/PhreeqcIO.cpp", "max_forks_repo_name": "garibay-j/ogs", "max_forks_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8849945235, "max_line_length": 80, "alphanum_fraction": 0.5874097331, "num_tokens": 6953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.019419349955895213, "lm_q1q2_score": 0.008130821808229816}}
{"text": "#pragma once\n#include <cstdint>\n#include <ostream>\n#include <filesystem>\n#include <memory>\n#include <Eigen/Dense>\n\n#ifndef ORBTOOL_CONV\n#include <foundation/PxVec3.h>\n#include <characterkinematic/PxExtended.h>\n#include <foundation/PxQuat.h>\n#endif\n\n#if defined _DEBUG\n\nextern const char* monitor_file;\nextern unsigned    monitor_line;\n\nstruct AllocEntry\n{\n\tconst void* alloc;\n\tconst char* file;\n\tunsigned line;\n\tunsigned size;\n};\n\nstruct AllocDictionary {\n\tAllocEntry* allocs;\n\tunsigned size;\n\tunsigned capacity;\n};\n\nstatic AllocDictionary alloc_dict;\n\nextern bool prepare_monitoring();\n\nstatic const auto monitoring_prepared = prepare_monitoring();\n\nextern void grow_dictionary();\n\nextern void shutdown_monitoring();\n\nextern void log_allocations();\n\nextern void monitor_allocation(const void* alloc, unsigned size, const char* file, unsigned line);\n\nextern void monitor_deallocation(const void* alloc);\n\nextern bool prepare_alloc(const char* file, unsigned line);\n\ninline void* operator new(std::size_t size)\n{\n\tauto alloc = malloc(size);\n    auto fLen = strlen(monitor_file);\n    char* file = (char*)malloc(fLen);\n    std::memcpy(file, monitor_file, fLen);\n\tmonitor_allocation(alloc, size, file, monitor_line);\n\treturn alloc;\n}\n\ninline void operator delete(void* alloc)\n{\n\tmonitor_deallocation(alloc);\n\tfree(alloc);\n}\n\n#define new prepare_alloc(__FILE__, __LINE__) ? 0 : new\n\n#else\n\nstatic void prepare_monitoring()\n{\n}\n\nstatic void shutdown_monitoring()\n{\n}\n\n#endif\n\n\n#if defined (ORBIT_DIRECTX_11) || (ORBIT_DIRECTX_12)\n\n#include <Windows.h>\n#include <wrl/client.h> \n\nnamespace orbit\n{\n\tnamespace wrl = Microsoft::WRL;\n\n\ttemplate<typename COM>\n\tusing ComPtr = wrl::ComPtr<COM>;\n}\n\n#endif\n\n#include <DirectXMath.h>\n\nnamespace orbit\n{\n#if defined (ORBIT_DIRECTX_11) || (ORBIT_DIRECTX_12)\n    using namespace DirectX;\n#endif\n  \n    using namespace Eigen;\n    namespace fs = std::filesystem;\n\n#ifndef ORBTOOL_CONV\n\n    using namespace physx;\n\n#endif\n\n    // Objects in Orbit are identified by their unique-ID. \n    using ResourceId = uint64_t;\n\n    // A Slot can have context-dependant meaning. I.e. a constant buffer slot for a \n    // shader resource. Or a Slot in the input layout.\n    using Slot = uint32_t;\n\n    class OpenGL_4_0 {};\n    class DirectX_11 {};\n    class DirectX_12 {};\n\n    using Index = size_t;\n    using Offset = size_t;\n\n    using ShaderIndex = uint32_t;\n    using MaterialFlags = uint32_t;\n\n    using Byte = uint8_t;\n\n    using Roughness = float;\n\n    template<typename T>\n    using SPtr = std::shared_ptr<T>;\n    template<typename T>\n    using UPtr = std::unique_ptr<T>;\n\n    template<typename T>\n    class Math\n    {\n    public:\n        static constexpr T PI     = static_cast<T>(3.141592653589793238462643383279);\n        static constexpr T PIDIV4 = static_cast<T>(PI * .25);\n        static constexpr T PIDIV2 = static_cast<T>(PI * .5);\n        static constexpr T TWO_PI = static_cast<T>(PI * 2.);\n        \n        static constexpr T AlignUp(const T& in, const T& alignment)\n        {\n            static_assert(std::is_integral<T>::value && \"Math<T>::AlignUp() T must be integral type.\");\n            return (in + alignment - 1) & ~(alignment - 1);\n        }\n        static constexpr T AlignDown(const T& in, const T& alignment)\n        {\n            static_assert(std::is_integral<T>::value && \"Math<T>::AlignDown() T must be integral type.\");\n            return in & ~(alignment - 1);\n        }\n        static constexpr Matrix<T, 4, 4> LookAt(\n            const Matrix<T, 3, 1>& eye,\n            const Matrix<T, 3, 1>& target,\n            const Matrix<T, 3, 1>& up)\n        {            \n            auto zaxis = (target - eye).normalized();\n            auto xaxis = up.cross(zaxis).normalized();\n            auto yaxis = zaxis.cross(xaxis);\n            \n            Matrix<T,4,4> matrix = Matrix<T, 4, 4>::Zero();\n            matrix.block<3, 1>(0, 0) = xaxis;\n            matrix.block<3, 1>(0, 1) = yaxis;\n            matrix.block<3, 1>(0, 2) = zaxis;\n            matrix(3, 0) = -xaxis.dot(eye);\n            matrix(3, 1) = -yaxis.dot(eye);\n            matrix(3, 2) = -zaxis.dot(eye);\n            matrix(3, 3) = 1;\n\n            return matrix;\n        }\n        static constexpr Matrix<T, 4, 4> Perspective(\n            T vFOV,\n            T aspectRatio,\n            T nearZ,\n            T farZ)\n        {\n            const auto d = 1.f / (nearZ - farZ);\n            const auto a = 1.f / tan(.5f * vFOV);\n\n            Matrix4f m = Matrix4f::Zero();\n            m(0, 0) = a / aspectRatio;\n            m(1, 1) = a;\n            m(2, 2) = -(nearZ + farZ) * d;\n            m(3, 2) = nearZ * farZ * d;\n            m(2, 3) = 1;\n            return m;\n        }\n\n        static constexpr Matrix<T, 4, 4> Orthogonal(T nearZ, T farZ, Vector4f normal)\n        {\n            const auto d = 1.f / (nearZ - farZ);\n            Matrix4f m = Matrix4f::Identity() - normal * normal.transpose();\n            m(2, 2) = -(nearZ + farZ) * d;\n            m(3, 2) = nearZ * farZ * d;\n            m(2, 3) = 1;\n            return m;\n        }\n\n#ifndef ORBTOOL_CONV\n\n        static constexpr PxVec3 EigenToPx3(const Vector3<T>& in)\n        {\n            return PxVec3(\n                static_cast<float>(in.x()),\n                static_cast<float>(in.y()),\n                static_cast<float>(in.z())\n            );\n        }\n\n        static constexpr Vector3<T> PxToEigen(const PxVec3& in)\n        {\n            return Vector3<T>{\n                static_cast<T>(in.x),\n                static_cast<T>(in.y),\n                static_cast<T>(in.z)\n            };\n        }\n\n        static constexpr Quaternion<T> PxToEigen(const PxQuat& in)\n        {\n            return Quaternion<T>{\n                static_cast<T>(in.x),\n                static_cast<T>(in.y),\n                static_cast<T>(in.z),\n                static_cast<T>(in.w)\n            };\n        }\n\n        static constexpr Vector3<T> PxToEigen(const PxExtendedVec3& in)\n        {\n            return Vector3<T>{\n                static_cast<T>(in.x),\n                static_cast<T>(in.y),\n                static_cast<T>(in.z)\n            };\n        }\n\n        static constexpr PxQuat EigenToPx(const Quaternion<T>& in)\n        {\n            return PxQuat(\n                static_cast<float>(in.x()),\n                static_cast<float>(in.x()),\n                static_cast<float>(in.z()),\n                static_cast<float>(in.w())\n            );\n        }\n#endif\n\n    };\n\n}\n\n#ifdef ORBIT_OPENGL\n  #ifndef GL_GLEXT_PROTOTYPES\n    #define GL_GLEXT_PROTOTYPES 1\n  #endif\n\n  #include <GL/glut.h>\n  #include <GL/gl.h>\n#elif defined(ORBIT_DIRECTX_11)\n  #include <d3d11.h>\n  //#include <d3dx11.h>\n#elif defined(ORBIT_DIRECTX_11)\n  #include <d3d12.h>\n  #include <d3dx12.h>\n#endif", "meta": {"hexsha": "d0bc6827e85bf3cfe0cd5bc9bb01015052d3e0eb", "size": 6728, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/implementation/Common.hpp", "max_stars_repo_name": "LarsHagemann/OrbitEngine", "max_stars_repo_head_hexsha": "33e01efaac617c53a701f01729581932fc81e8bf", "max_stars_repo_licenses": ["MIT"], "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/implementation/Common.hpp", "max_issues_repo_name": "LarsHagemann/OrbitEngine", "max_issues_repo_head_hexsha": "33e01efaac617c53a701f01729581932fc81e8bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-18T21:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T21:02:09.000Z", "max_forks_repo_path": "inc/implementation/Common.hpp", "max_forks_repo_name": "LarsHagemann/OrbitEngine", "max_forks_repo_head_hexsha": "33e01efaac617c53a701f01729581932fc81e8bf", "max_forks_repo_licenses": ["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.5547445255, "max_line_length": 105, "alphanum_fraction": 0.5731272295, "num_tokens": 1738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.019419348395262187, "lm_q1q2_score": 0.008130821154797591}}
{"text": "/* Copyright (c) AIRBUS and its affiliates.\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n#ifndef SKDECIDE_RIW_HH\n#define SKDECIDE_RIW_HH\n\n#include <functional>\n#include <memory>\n#include <unordered_set>\n#include <unordered_map>\n#include <vector>\n#include <queue>\n#include <list>\n#include <chrono>\n#include <random>\n\n#include <boost/container_hash/hash.hpp>\n#include <boost/range/irange.hpp>\n\n#include \"spdlog/spdlog.h\"\n#include \"spdlog/sinks/stdout_color_sinks.h\"\n\n#include \"utils/associative_container_deducer.hh\"\n#include \"utils/string_converter.hh\"\n#include \"utils/execution.hh\"\n\nnamespace skdecide {\n\n/** Use default hasher provided with domain's states */\ntemplate <typename Tdomain, typename Tfeature_vector>\nstruct DomainStateHash {\n    typedef typename Tdomain::State Key;\n\n    template <typename Tnode>\n    static const Key& get_key(const Tnode& n) {\n        return n.state;\n    }\n\n    struct Hash {\n        std::size_t operator()(const Key& k) const {\n            return typename Tdomain::State::Hash()(k);\n        }\n    };\n\n    struct Equal {\n        bool operator()(const Key& k1, const Key& k2) const {\n            return typename Tdomain::State::Equal()(k1, k2);\n        }\n    };\n};\n\n\n/** Use state binary feature vector to hash states */\ntemplate <typename Tdomain, typename Tfeature_vector>\nstruct StateFeatureHash {\n    typedef Tfeature_vector Key;\n\n    template <typename Tnode>\n    static const Key& get_key(const Tnode& n) {\n        return *n.features;\n    }\n\n    struct Hash {\n        std::size_t operator()(const Key& k) const {\n            std::size_t seed = 0;\n            for (std::size_t i = 0 ; i < k.size() ; i++) {\n                boost::hash_combine(seed, k[i]);\n            }\n            return seed;\n        }\n    };\n\n    struct Equal {\n        bool operator()(const Key& k1, const Key& k2) const {\n            std::size_t size = k1.size();\n            if (size != k2.size()) {\n                return false;\n            }\n            for (std::size_t i = 0 ; i < size ; i++) {\n                if (!(k1[i] == k2[i])) {\n                    return false;\n                }\n            }\n            return true;\n        }\n    };\n};\n\n\n/** Use Environment domain knowledge for rollouts */\ntemplate <typename Tdomain>\nstruct EnvironmentRollout {\n    std::list<typename Tdomain::Event> _action_prefix;\n\n    void init_rollout(Tdomain& domain, const std::size_t* thread_id) {\n        domain.reset(thread_id);\n        std::for_each(_action_prefix.begin(), _action_prefix.end(),\n                      [&domain, &thread_id](const typename Tdomain::Event& a){domain.step(a, thread_id);});\n    }\n\n    typename Tdomain::TransitionOutcome progress(Tdomain& domain,\n                                                 const typename Tdomain::State& state,\n                                                 const typename Tdomain::Event& action,\n                                                 const std::size_t* thread_id) {\n        return domain.step(action, thread_id);\n    }\n\n    void advance(Tdomain& domain,\n                 const typename Tdomain::State& state,\n                 const typename Tdomain::Event& action,\n                 bool record_action,\n                 const std::size_t* thread_id) {\n        if (record_action) {\n            _action_prefix.push_back(action);\n        } else {\n            domain.step(action, thread_id);\n        }\n    }\n\n    std::list<typename Tdomain::Event> action_prefix() const {\n        return _action_prefix;\n    }\n};\n\n\n/** Use Simulation domain knowledge for rollouts */\ntemplate <typename Tdomain>\nstruct SimulationRollout {\n    void init_rollout([[maybe_unused]] Tdomain& domain, [[maybe_unused]] const std::size_t* thread_id) {}\n\n    typename Tdomain::TransitionOutcome progress(Tdomain& domain,\n                                                 const typename Tdomain::State& state,\n                                                 const typename Tdomain::Event& action,\n                                                 const std::size_t* thread_id) {\n        return domain.sample(state, action, thread_id);\n    }\n\n    void advance([[maybe_unused]] Tdomain& domain,\n                 [[maybe_unused]] const typename Tdomain::State& state,\n                 [[maybe_unused]] const typename Tdomain::Event& action,\n                 [[maybe_unused]] bool record_action,\n                 [[maybe_unused]] const std::size_t* thread_id) {}\n    \n    std::list<typename Tdomain::Event> action_prefix() const {\n        return std::list<typename Tdomain::Event>();\n    }\n};\n\n\ntemplate <typename Tdomain,\n          typename Tfeature_vector,\n          template <typename...> class Thashing_policy = DomainStateHash,\n          template <typename...> class Trollout_policy = EnvironmentRollout,\n          typename Texecution_policy = SequentialExecution>\nclass RIWSolver {\npublic :\n    typedef Tdomain Domain;\n    typedef typename Domain::State State;\n    typedef typename Domain::Event Action;\n    typedef Tfeature_vector FeatureVector;\n    typedef Thashing_policy<Domain, FeatureVector> HashingPolicy;\n    typedef Trollout_policy<Domain> RolloutPolicy;\n    typedef Texecution_policy ExecutionPolicy;\n\n    RIWSolver(Domain& domain,\n              const std::function<std::unique_ptr<FeatureVector> (Domain& d, const State& s, const std::size_t* thread_id)>& state_features,\n              std::size_t time_budget = 3600000,\n              std::size_t rollout_budget = 100000,\n              std::size_t max_depth = 1000,\n              double exploration = 0.25,\n              double discount = 1.0,\n              bool online_node_garbage = false,\n              bool debug_logs = false)\n    : _domain(domain), _state_features(state_features),\n      _time_budget(time_budget), _rollout_budget(rollout_budget),\n      _max_depth(max_depth), _exploration(exploration),\n      _discount(discount), _online_node_garbage(online_node_garbage),\n      _min_reward(std::numeric_limits<double>::max()),\n      _nb_rollouts(0), _debug_logs(debug_logs) {\n        if (debug_logs) {\n            spdlog::set_level(spdlog::level::debug);\n        } else {\n            spdlog::set_level(spdlog::level::info);\n        }\n\n        std::random_device rd;\n        _gen = std::make_unique<std::mt19937>(rd());\n    }\n\n    // clears the solver (clears the search graph, thus preventing from reusing\n    // previous search results)\n    void clear() {\n        _graph.clear();\n        _min_reward = std::numeric_limits<double>::max();\n    }\n\n    // solves from state s\n    void solve(const State& s) {\n        try {\n            spdlog::info(\"Running \" + ExecutionPolicy::print_type() + \" RIW solver from state \" + s.print());\n            auto start_time = std::chrono::high_resolution_clock::now();\n            _nb_rollouts = 0;\n            std::size_t nb_of_binary_features = _state_features(_domain, s, nullptr)->size();\n\n            TupleVector feature_tuples;\n            bool found_solution = false;\n\n            for (atomic_size_t w = 1 ; w <= nb_of_binary_features ; w++) {\n                if(WidthSolver(*this, _domain, _state_features,\n                               _time_budget, _rollout_budget,\n                               _max_depth, _exploration, _discount,\n                               _min_reward, w, _graph, _rollout_policy,\n                               _execution_policy, *_gen, _gen_mutex, _time_mutex,\n                               _debug_logs).solve(s, start_time, _nb_rollouts, feature_tuples)) {\n                    found_solution = true;\n                    break;\n                }\n            }\n\n            auto end_time = std::chrono::high_resolution_clock::now();\n            auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count();\n            auto exploration_statistics = get_exploration_statistics();\n            std::string solution_str(found_solution?(\"finished to solve\"):(\"could not find a solution\"));\n            spdlog::info(\"RIW \" + solution_str + \" from state \" + s.print() +\n                         \" in \" + StringConverter::from((double) duration / (double) 1e9) + \" seconds with \" +\n                         StringConverter::from(_nb_rollouts) + \" rollouts and pruned \" +\n                         StringConverter::from(exploration_statistics.second) + \" states among \" +\n                         StringConverter::from(exploration_statistics.first) + \" visited states.\");\n        } catch (const std::exception& e) {\n            spdlog::error(\"RIW failed solving from state \" + s.print() + \". Reason: \" + e.what());\n            throw;\n        }\n    }\n\n    bool is_solution_defined_for(const State& s) const {\n        auto si = _graph.find(Node(s, _domain, _state_features, nullptr));\n        if ((si == _graph.end()) || (si->best_action == nullptr)) {// || (si->solved == false)) {\n            return false;\n        } else {\n            return true;\n        }\n    }\n\n    Action get_best_action(const State& s) {\n        auto si = _graph.find(Node(s, _domain, _state_features, nullptr));\n        if ((si == _graph.end()) || (si->best_action == nullptr)) {\n            spdlog::error(\"SKDECIDE exception: no best action found in state \" + s.print());\n            throw std::runtime_error(\"SKDECIDE exception: no best action found in state \" + s.print());\n        }\n        _rollout_policy.advance(_domain, s, *(si->best_action), true, nullptr);\n        Action best_action = *(si->best_action);\n        std::unordered_set<Node*> root_subgraph;\n        compute_reachable_subgraph(const_cast<Node&>(*si), root_subgraph); // we won't change the real key (Node::state) so we are safe\n        Node* next_node = nullptr;\n        for (auto& child : si->children) {\n            if (&std::get<0>(child) == si->best_action) {\n                next_node = std::get<2>(child);\n                break;\n            }\n        }\n        if (next_node == nullptr) {\n            spdlog::error(\"SKDECIDE exception: best action's next node from state \" + s.print() + \" not found in the graph\");\n            throw std::runtime_error(\"SKDECIDE exception: best action's next node from state \" + s.print() + \" not found in the graph\");\n        }\n        if (_debug_logs) { spdlog::debug(\"Expected outcome of best action \" + si->best_action->print() +\n                                         \": \" + next_node->state.print()); }\n        std::unordered_set<Node*> child_subgraph;\n        if (_online_node_garbage) {\n            compute_reachable_subgraph(*next_node, child_subgraph);\n        }\n        update_graph(root_subgraph, child_subgraph);\n        return best_action;\n    }\n\n    double get_best_value(const State& s) const {\n        auto si = _graph.find(Node(s, _domain, _state_features, nullptr));\n        if (si == _graph.end()) {\n            spdlog::error(\"SKDECIDE exception: no best action found in state \" + s.print());\n            throw std::runtime_error(\"SKDECIDE exception: no best action found in state \" + s.print());\n        }\n        return si->value;\n    }\n\n    std::size_t get_nb_of_explored_states() const {\n        return _graph.size();\n    }\n\n    std::size_t get_nb_of_pruned_states() const {\n        std::size_t cnt = 0;\n        for (const auto&  n : _graph)  {\n            if (n.pruned) {\n                cnt++;\n            }\n        }\n        return cnt;\n    }\n\n    std::pair<std::size_t, std::size_t> get_exploration_statistics() const {\n        std::size_t pruned = 0;\n        std::size_t explored = 0;\n        for (const auto&  n : _graph)  {\n            explored++;\n            if (n.pruned) {\n                pruned++;\n            }\n        }\n        return std::make_pair(explored, pruned);\n    }\n\n    std::size_t get_nb_rollouts() const {\n        return _nb_rollouts;\n    }\n\n    std::list<Action> action_prefix() const {\n        return _rollout_policy.action_prefix();\n    }\n\n    typename MapTypeDeducer<State, std::pair<Action, double>>::Map policy() {\n        typename MapTypeDeducer<State, std::pair<Action, double>>::Map p;\n        for (auto& n : _graph) {\n            if (n.best_action != nullptr) {\n                p.insert(std::make_pair(n.state, std::make_pair(*n.best_action, (double) n.value)));\n            }\n        }\n        return p;\n    }\n\nprivate :\n\n    typedef typename ExecutionPolicy::template atomic<std::size_t> atomic_size_t;\n    typedef typename ExecutionPolicy::template atomic<double> atomic_double;\n    typedef typename ExecutionPolicy::template atomic<bool> atomic_bool;\n\n    Domain& _domain;\n    std::function<std::unique_ptr<FeatureVector> (Domain&, const State& s, const std::size_t* thread_id)> _state_features;\n    atomic_size_t _time_budget;\n    atomic_size_t _rollout_budget;\n    atomic_size_t _max_depth;\n    atomic_double _exploration;\n    atomic_double _discount;\n    bool _online_node_garbage;\n    atomic_double _min_reward;\n    atomic_size_t _nb_rollouts;\n    RolloutPolicy _rollout_policy;\n    ExecutionPolicy _execution_policy;\n    std::unique_ptr<std::mt19937> _gen;\n    typename ExecutionPolicy::Mutex _gen_mutex;\n    typename ExecutionPolicy::Mutex _time_mutex;\n    atomic_bool _debug_logs;\n\n    struct Node {\n        State state;\n        std::unique_ptr<FeatureVector> features;\n        std::vector<std::tuple<Action, double, Node*>> children;\n        std::unordered_set<Node*> parents;\n        atomic_double value;\n        atomic_size_t depth;\n        atomic_size_t novelty;\n        Action* best_action;\n        atomic_bool terminal; // true if seen terminal from the simulator's perspective\n        atomic_bool pruned; // true if pruned from novelty measure perspective\n        atomic_bool solved; // from this node: true if all reached states are either max_depth, or terminal or pruned\n        mutable typename ExecutionPolicy::Mutex mutex;\n\n        Node(const State& s, Domain& d,\n             const std::function<std::unique_ptr<FeatureVector> (Domain&, const State&, const std::size_t*)>& state_features,\n             const std::size_t* thread_id)\n            : state(s),\n              value(-std::numeric_limits<double>::max()),\n              depth(std::numeric_limits<std::size_t>::max()),\n              novelty(std::numeric_limits<std::size_t>::max()),\n              best_action(nullptr),\n              terminal(false),\n              pruned(false),\n              solved(false) {\n            features = state_features(d, s, thread_id);\n        }\n\n        Node(const Node& n)\n            : state(n.state), features(std::move(const_cast<std::unique_ptr<FeatureVector>&>(n.features))),\n              children(n.children), parents(n.parents), value((double) n.value), depth((std::size_t) n.depth),\n              novelty((std::size_t) n.novelty), best_action(n.best_action), terminal((bool) n.terminal),\n              pruned((bool) n.pruned), solved((bool) n.solved) {}\n        \n        struct Key {\n            const typename HashingPolicy::Key& operator()(const Node& n) const {\n                return HashingPolicy::get_key(n);\n            }\n        };\n    };\n\n    typedef typename SetTypeDeducer<Node, HashingPolicy>::Set Graph;\n    Graph _graph;\n\n    typedef std::vector<std::pair<std::size_t, typename FeatureVector::value_type>> TupleType; // pair of var id and var value\n    typedef std::vector<std::unordered_map<TupleType, std::size_t, boost::hash<TupleType>>> TupleVector; // mapped to min reached depth\n\n    class WidthSolver { // known as IW(i), i.e. the fixed-width solver sequentially run by IW\n    public :\n        typedef Tdomain Domain;\n        typedef typename Domain::State State;\n        typedef typename Domain::Event Action;\n        typedef Tfeature_vector FeatureVector;\n        typedef Thashing_policy<Domain, FeatureVector> HashingPolicy;\n        typedef Trollout_policy<Domain> RolloutPolicy;\n        typedef Texecution_policy ExecutionPolicy;\n\n        WidthSolver(RIWSolver& parent_solver, Domain& domain,\n                    const std::function<std::unique_ptr<FeatureVector> (Domain& d, const State& s, const std::size_t* thread_id)>& state_features,\n                    const atomic_size_t& time_budget,\n                    const atomic_size_t& rollout_budget,\n                    const atomic_size_t& max_depth,\n                    const atomic_double& exploration,\n                    const atomic_double& discount,\n                    atomic_double& min_reward,\n                    const atomic_size_t& width,\n                    Graph& graph,\n                    RolloutPolicy& rollout_policy,\n                    ExecutionPolicy& execution_policy,\n                    std::mt19937& gen,\n                    typename ExecutionPolicy::Mutex& gen_mutex,\n                    typename ExecutionPolicy::Mutex& time_mutex,\n                    const atomic_bool& debug_logs)\n            : _parent_solver(parent_solver), _domain(domain), _state_features(state_features),\n              _time_budget(time_budget), _rollout_budget(rollout_budget),\n              _max_depth(max_depth), _exploration(exploration),\n              _discount(discount), _min_reward(min_reward), _min_reward_changed(false),\n              _width(width), _graph(graph), _rollout_policy(rollout_policy),\n              _execution_policy(execution_policy), _gen(gen), _gen_mutex(gen_mutex),\n              _time_mutex(time_mutex), _debug_logs(debug_logs) {}\n        \n        // solves from state s\n        // return true iff no state has been pruned or time or rollout budgets are consumed\n        bool solve(const State& s,\n                   const std::chrono::time_point<std::chrono::high_resolution_clock>& start_time,\n                   atomic_size_t& nb_rollouts,\n                   TupleVector& feature_tuples) {\n            try {\n                spdlog::info(\"Running \" + ExecutionPolicy::print_type() + \" RIW(\" + StringConverter::from(_width) + \") solver from state \" + s.print());\n                auto local_start_time = std::chrono::high_resolution_clock::now();\n\n                // Clear the solved bits\n                // /!\\ 'solved' bit set to 1 in RIW even if no solution found with previous width so we need to clear all the bits\n                std::for_each(_graph.begin(), _graph.end(), [](const Node& n){\n                    // we don't change the real key (Node::state) so we are safe\n                    const_cast<Node&>(n).solved = false;\n                    const_cast<Node&>(n).pruned = false;\n                });\n\n                // Create the root node containing the given state s\n                auto si = _graph.emplace(Node(s, _domain, _state_features, nullptr));\n                Node& root_node = const_cast<Node&>(*(si.first)); // we won't change the real key (Node::state) so we are safe\n                root_node.depth = 0;\n                atomic_bool states_pruned(false);\n                atomic_bool reached_end_of_trajectory_once(false);\n\n                // Vector of sets of state feature tuples generated so far, for each w <= _width\n                if (feature_tuples.size() < _width) {\n                    feature_tuples.push_back(typename TupleVector::value_type());\n                }\n                novelty(feature_tuples, root_node, true); // initialize feature_tuples with the root node's bits\n\n                boost::integer_range<std::size_t> parallel_rollouts(0, _domain.get_parallel_capacity());\n\n                std::for_each(ExecutionPolicy::policy, parallel_rollouts.begin(), parallel_rollouts.end(),\n                              [this, &start_time, &root_node, &feature_tuples, &nb_rollouts, &states_pruned,\n                               &reached_end_of_trajectory_once] (const std::size_t& thread_id) {\n                    // Start rollouts\n                    while (!root_node.solved && elapsed_time(start_time) < _time_budget && nb_rollouts < _rollout_budget) {\n                        rollout(root_node, feature_tuples, nb_rollouts,\n                                states_pruned, reached_end_of_trajectory_once,\n                                start_time, &thread_id);\n                    }\n                });\n\n                if (_debug_logs) spdlog::debug(\"time budget: \" + StringConverter::from(elapsed_time(start_time)) +\n                                               \" ms, rollout budget: \" + StringConverter::from(nb_rollouts) +\n                                               \", states pruned: \" + StringConverter::from(states_pruned));\n\n                if (static_cast<std::size_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time).count()) < _time_budget &&\n                    nb_rollouts < _rollout_budget &&\n                    !reached_end_of_trajectory_once &&\n                    states_pruned) {\n                    spdlog::info(\"RIW(\" + StringConverter::from(_width) + \") could not find a solution from state \" + s.print());\n                    return false;\n                } else {\n                    auto end_time = std::chrono::high_resolution_clock::now();\n                    auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - local_start_time).count();\n                    spdlog::info(\"RIW(\" + StringConverter::from(_width) + \") finished to solve from state \" + s.print() + \" in \" + StringConverter::from((double) duration / (double) 1e9) + \" seconds.\");\n                    return true;\n                }\n            } catch (const std::exception& e) {\n                spdlog::error(\"RIW(\" + StringConverter::from(_width) + \") failed solving from state \" + s.print() + \". Reason: \" + e.what());\n                throw;\n            }\n        }\n\n    private :\n        typedef typename ExecutionPolicy::template atomic<std::size_t> atomic_size_t;\n        typedef typename ExecutionPolicy::template atomic<double> atomic_double;\n        typedef typename ExecutionPolicy::template atomic<bool> atomic_bool;\n\n        RIWSolver& _parent_solver;\n        Domain& _domain;\n        const std::function<std::unique_ptr<FeatureVector> (Domain& d, const State& s, const std::size_t* thread_id)>& _state_features;\n        const atomic_size_t& _time_budget;\n        const atomic_size_t& _rollout_budget;\n        const atomic_size_t& _max_depth;\n        const atomic_double& _exploration;\n        const atomic_double& _discount;\n        atomic_double& _min_reward;\n        atomic_bool _min_reward_changed;\n        const atomic_size_t& _width;\n        Graph& _graph;\n        RolloutPolicy& _rollout_policy;\n        ExecutionPolicy& _execution_policy;\n        std::mt19937& _gen;\n        typename ExecutionPolicy::Mutex& _gen_mutex;\n        typename ExecutionPolicy::Mutex& _time_mutex;\n        const atomic_bool& _debug_logs;\n\n        void rollout(Node& root_node, TupleVector& feature_tuples, atomic_size_t& nb_rollouts,\n                     atomic_bool& states_pruned, atomic_bool& reached_end_of_trajectory_once,\n                     const std::chrono::time_point<std::chrono::high_resolution_clock>& start_time,\n                     const std::size_t* thread_id) {\n            // Start new rollout\n            nb_rollouts += 1;\n            Node* current_node = &root_node;\n\n            if (_debug_logs) spdlog::debug(\"New rollout\" + ExecutionPolicy::print_thread() +\n                                           \" from state: \" + current_node->state.print() +\n                                           \", depth=\" + StringConverter::from(current_node->depth) +\n                                           \", value=\" + StringConverter::from(current_node->value) +\n                                           ExecutionPolicy::print_thread());\n            _rollout_policy.init_rollout(_domain, thread_id);\n            bool break_loop = false;\n\n            while (!(current_node->solved) && !break_loop) {\n\n                std::vector<std::size_t> unsolved_children;\n                std::vector<double> probabilities;\n\n                _execution_policy.protect([this, &current_node, &unsolved_children, &probabilities, &thread_id](){\n                    if (_debug_logs) spdlog::debug(\"Current state\" + ExecutionPolicy::print_thread() + \": \" +\n                                                   current_node->state.print() +\n                                                   \", depth=\" + StringConverter::from(current_node->depth) +\n                                                   \", value=\" + StringConverter::from(current_node->value) +\n                                                   ExecutionPolicy::print_thread());\n\n                    if (current_node->children.empty()) {\n                        // Generate applicable actions\n                        auto applicable_actions = _domain.get_applicable_actions(current_node->state, thread_id).get_elements();\n                        std::for_each(applicable_actions.begin(), applicable_actions.end(), [&current_node](auto a){\n                            current_node->children.push_back(std::make_tuple(a, 0, nullptr));\n                        });\n                    }\n                    \n                    // Sample unsolved child\n                    for (std::size_t i = 0 ; i < current_node->children.size() ; i++) {\n                        Node* n = std::get<2>(current_node->children[i]);\n                        if (!n) {\n                            unsolved_children.push_back(i);\n                            probabilities.push_back(_exploration);\n                        } else if (!(n->solved)) {\n                            unsolved_children.push_back(i);\n                            probabilities.push_back((1.0 - _exploration) / ((double) n->novelty));\n                        }\n                    }\n                }, current_node->mutex);\n\n                // In parallel execution mode, child nodes can have been solved since we have checked\n                // for this current node's solve bit\n                if (unsolved_children.empty()) {\n                    if(std::is_same<ExecutionPolicy, SequentialExecution>::value) {\n                        throw std::runtime_error(\"In sequential mode, nodes labelled as unsolved must have unsolved children.\");\n                    }\n                    current_node->solved = true;\n                    break;\n                }\n\n                std::size_t pick = 0;\n                _execution_policy.protect([this, &pick, &unsolved_children, &probabilities](){\n                    pick = unsolved_children[std::discrete_distribution<>(probabilities.begin(), probabilities.end())(_gen)];\n                }, _gen_mutex);\n                bool new_node = false;\n\n                if (fill_child_node(current_node, pick, new_node, thread_id)) { // terminal state\n                    if (_debug_logs) {\n                        _execution_policy.protect([&current_node](){\n                            spdlog::debug(\"Found\" + ExecutionPolicy::print_thread() +\n                                          \" a terminal state: \" + current_node->state.print() +\n                                          \", depth=\" + StringConverter::from(current_node->depth) +\n                                          \", value=\" + StringConverter::from(current_node->value) +\n                                          ExecutionPolicy::print_thread());\n                        }, current_node->mutex);\n                    }\n                    update_node(*current_node, true);\n                    reached_end_of_trajectory_once = true;\n                    break_loop = true;\n                } else if (!novelty(feature_tuples, *current_node, new_node)) { // no new tuple or not reached with lower depth => terminal node\n                    if (_debug_logs) {\n                        _execution_policy.protect([&current_node](){\n                            spdlog::debug(\"Pruning\" + ExecutionPolicy::print_thread() +\n                                          \" state: \" + current_node->state.print() +\n                                          \", depth=\" + StringConverter::from(current_node->depth) +\n                                          \", value=\" + StringConverter::from(current_node->value) +\n                                          ExecutionPolicy::print_thread());\n                        }, current_node->mutex);\n                    }\n                    states_pruned = true;\n                    current_node->pruned = true;\n                    // /!\\ current_node can become solved with some unsolved children in case it was\n                    // already visited and novel but now some of its features are reached with lower depth\n                    update_node(*current_node, true);\n                    break_loop = true;\n                } else if (current_node->depth >= _max_depth) {\n                    if (_debug_logs) {\n                        _execution_policy.protect([&current_node](){\n                            spdlog::debug(\"Max depth reached\" + ExecutionPolicy::print_thread() +\n                                          \"in state: \" + current_node->state.print() +\n                                          \", depth=\" + StringConverter::from(current_node->depth) +\n                                          \", value=\" + StringConverter::from(current_node->value) +\n                                          ExecutionPolicy::print_thread());\n                        }, current_node->mutex);\n                    }\n                    update_node(*current_node, true);\n                    reached_end_of_trajectory_once = true;\n                    break_loop = true;\n                } else if (elapsed_time(start_time) >= _time_budget) {\n                    if (_debug_logs) {\n                        _execution_policy.protect([&current_node](){\n                            spdlog::debug(\"Time budget consumed\" + ExecutionPolicy::print_thread() +\n                                          \" in state: \" + current_node->state.print() +\n                                          \", depth=\" + StringConverter::from(current_node->depth) +\n                                          \", value=\" + StringConverter::from(current_node->value) +\n                                          ExecutionPolicy::print_thread());\n                        }, current_node->mutex);\n                    }\n                    // next test: unexpanded node considered as a temporary (i.e. not solved) terminal node\n                    // don't backup expanded node at this point otherwise the fscore initialization in update_node is wrong!\n                    bool current_node_no_children = false;\n                    _execution_policy.protect([&current_node_no_children, &current_node](){\n                        current_node_no_children = current_node->children.empty();\n                    }, current_node->mutex);\n                    if (current_node_no_children) {\n                        update_node(*current_node, false);\n                    }\n                    break_loop = true;\n                }\n            }\n        }\n\n        // Input: feature tuple vector, node for which to compute novelty depth, boolean indicating whether this node is new or not\n        // Returns true if at least one tuple is new or is reached with lower depth\n        bool novelty(TupleVector& feature_tuples, Node& n, bool nn) const {\n            // feature_tuples is a set of state variable combinations of size _width\n            std::size_t nov = n.features->size() + 1;\n            const FeatureVector& state_features = *n.features;\n            bool novel_depth = false;\n\n            for (std::size_t k = 1 ; k <= std::min((std::size_t) _width, (std::size_t) state_features.size()) ; k++) {\n                // we must recompute combinations from previous width values just in case\n                // this state would be visited for the first time across width iterations\n                generate_tuples(k, state_features.size(),\n                                [this, &state_features, &feature_tuples, &k, &novel_depth, &n, &nn, &nov](TupleType& cv){\n                    for (auto& e : cv) {\n                        e.second = state_features[e.first];\n                    }\n                    _execution_policy.protect([&feature_tuples, &cv, &k, &novel_depth, &n, &nn, &nov]()->void {\n                        auto it = feature_tuples[k-1].insert(std::make_pair(cv, (std::size_t) n.depth));\n                        novel_depth = novel_depth || it.second || (nn && (it.first->second > n.depth)) || (!nn && (it.first->second == n.depth));\n                        it.first->second = std::min(it.first->second, (std::size_t) n.depth);\n                        if(it.second) {\n                            nov = std::min(nov, k);\n                        }\n                    });\n                });\n            }\n            n.novelty = nov;\n            if (_debug_logs) spdlog::debug(\"Novelty: \" + StringConverter::from(nov));\n            if (_debug_logs) spdlog::debug(\"Novelty depth check: \" + StringConverter::from(novel_depth));\n            return novel_depth;\n        }\n\n        // Generates all combinations of size k from [0 ... (n-1)]\n        void generate_tuples(const std::size_t& k,\n                             const std::size_t& n,\n                             const std::function<void (TupleType&)>& f) const {\n            TupleType cv(k); // one combination (the first one)\n            for (std::size_t i = 0 ; i < k ; i++) {\n                cv[i].first = i;\n            }\n            f(cv);\n            bool more_combinations = true;\n            while (more_combinations) {\n                more_combinations = false;\n                // find the rightmost element that has not yet reached its highest possible value\n                for (std::size_t i = k; i > 0; i--) {\n                    if (cv[i-1].first < n - k + i - 1) {\n                        // once finding this element, we increment it by 1,\n                        // and assign the lowest valid value to all subsequent elements\n                        cv[i-1].first++;\n                        for (std::size_t j = i; j < k; j++) {\n                            cv[j].first = cv[j-1].first + 1;\n                        }\n                        f(cv);\n                        more_combinations = true;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // Get the state reachable by calling the simulator from given node by applying given action number\n        // Sets given node to the next one and returns whether the next one is terminal or not\n        bool fill_child_node(Node*& node, std::size_t action_number, bool& new_node, const std::size_t* thread_id) {\n            Node* node_child = nullptr;\n\n            _execution_policy.protect([this, &node, &node_child, &action_number](){\n                if (_debug_logs) spdlog::debug(\"Applying \" + ExecutionPolicy::print_thread() +\n                                               \" action: \" + std::get<0>(node->children[action_number]).print() +\n                                               ExecutionPolicy::print_thread());\n                node_child = std::get<2>(node->children[action_number]);\n            }, node->mutex);\n\n            if (!node_child) { // first visit\n                // Sampled child has not been visited so far, so generate it\n                typename Domain::TransitionOutcome outcome;\n                _execution_policy.protect([this, &node, &outcome, &action_number, &thread_id](){\n                    outcome = _rollout_policy.progress(_domain, node->state, std::get<0>(node->children[action_number]), thread_id);\n                }, node->mutex);\n                \n                _execution_policy.protect([this, &node_child, &thread_id, &new_node, &outcome](){\n                    auto i = _graph.emplace(Node(outcome.state(), _domain, _state_features, thread_id));\n                    new_node = i.second;\n                    node_child = &const_cast<Node&>(*(i.first)); // we won't change the real key (StateNode::state) so we are safe\n                });\n                Node& next_node = *node_child;\n                _execution_policy.protect([&node, &action_number, &outcome, &node_child](){\n                    std::get<1>(node->children[action_number]) = outcome.reward();\n                    std::get<2>(node->children[action_number]) = node_child;\n                }, node->mutex);\n                if (outcome.reward() < _min_reward) {\n                    _min_reward = outcome.reward();\n                    _min_reward_changed = true;\n                }\n                \n                _execution_policy.protect([this, &node, &next_node, &new_node, &outcome](){\n                    next_node.parents.insert(node);\n                    if (new_node) {\n                        if (_debug_logs) spdlog::debug(\"Exploring\" + ExecutionPolicy::print_thread() +\n                                                       \" new outcome: \" + next_node.state.print() +\n                                                       \", depth=\" + StringConverter::from(next_node.depth) +\n                                                       \", value=\" + StringConverter::from(next_node.value) +\n                                                       ExecutionPolicy::print_thread());\n                        next_node.depth = node->depth + 1;\n                        node = &next_node;\n                        node->terminal = outcome.terminal();\n                        if (node->terminal && _min_reward > 0.0) {\n                            _min_reward = 0.0;\n                            _min_reward_changed = true;\n                        }\n                    } else { // outcome already explored\n                        if (_debug_logs) spdlog::debug(\"Exploring\" + ExecutionPolicy::print_thread() +\n                                                       \" known outcome: \" + next_node.state.print() +\n                                                       \", depth=\" + StringConverter::from(next_node.depth) +\n                                                       \", value=\" + StringConverter::from(next_node.value) +\n                                                       ExecutionPolicy::print_thread());\n                        next_node.depth = std::min((std::size_t) next_node.depth, (std::size_t) node->depth + 1);\n                        node = &next_node;\n                    }\n                }, next_node.mutex);\n            } else { // second visit, unsolved child\n                new_node = false;\n                // call the simulator to be coherent with the new current node /!\\ Assumes deterministic environment!\n                _execution_policy.protect([this, &node, &action_number, &thread_id](){\n                    _rollout_policy.advance(_domain, node->state, std::get<0>(node->children[action_number]), false, thread_id);\n                }, node->mutex);\n                Node& next_node = *node_child;\n                next_node.depth = std::min((std::size_t) next_node.depth, (std::size_t) node->depth + 1);\n                node = node_child;\n                if (_debug_logs) {\n                    _execution_policy.protect([&node](){\n                        spdlog::debug(\"Exploring\" + ExecutionPolicy::print_thread() +\n                                      \" known outcome: \" + node->state.print() +\n                                      \", depth=\" + StringConverter::from(node->depth) +\n                                      \", value=\" + StringConverter::from(node->value) +\n                                      ExecutionPolicy::print_thread());\n                    }, next_node.mutex);\n                }\n            }\n            return (node->terminal) || (node->solved); // consider solved node as terminal to stop current rollout\n        }\n\n        void update_node(Node& node, bool solved) {\n            node.solved = solved;\n            node.value = 0;\n            std::unordered_set<Node*> frontier;\n            if (_min_reward_changed) {\n                // need for backtracking all leaf nodes in the graph\n                _execution_policy.protect([this, &frontier](){\n                    for (auto& n : _graph) {\n                        _execution_policy.protect([&n, &frontier](){\n                            if (n.children.empty()) {\n                                frontier.insert(&const_cast<Node&>(n)); // we won't change the real key (Node::state) so we are safe\n                            }\n                        }, n.mutex);\n                    }\n                });\n                _min_reward_changed = false;\n            } else {\n                frontier.insert(&node);\n            }\n            _parent_solver.backup_values(frontier);\n        }\n\n        std::size_t elapsed_time(const std::chrono::time_point<std::chrono::high_resolution_clock>& start_time) {\n            std::size_t milliseconds_duration;\n            _execution_policy.protect([&milliseconds_duration, &start_time](){\n                milliseconds_duration = static_cast<std::size_t>(\n                    std::chrono::duration_cast<std::chrono::milliseconds>(\n                        std::chrono::high_resolution_clock::now() - start_time\n                    ).count()\n                );\n            }, _time_mutex);\n            return milliseconds_duration;\n        }\n    }; // WidthSolver class\n\n    void compute_reachable_subgraph(Node& node, std::unordered_set<Node*>& subgraph) {\n        std::unordered_set<Node*> frontier;\n        frontier.insert(&node);\n        subgraph.insert(&node);\n        while(!frontier.empty()) {\n            std::unordered_set<Node*> new_frontier;\n            for (auto& n : frontier) {\n                if (n) {\n                    for (auto& child : n->children) {\n                        if (subgraph.find(std::get<2>(child)) == subgraph.end()) {\n                            new_frontier.insert(std::get<2>(child));\n                            subgraph.insert(std::get<2>(child));\n                        }\n                    }\n                }\n            }\n            frontier = new_frontier;\n        }\n    }\n\n    // Prune the nodes that are no more reachable from the root's chosen child and reduce the depth of the\n    // nodes reachable from the child node by 1\n    void update_graph(std::unordered_set<Node*>& root_subgraph, std::unordered_set<Node*>& child_subgraph) {\n        std::unordered_set<Node*> removed_subgraph;\n        // First pass: look for nodes in root_subgraph but not child_subgraph and remove\n        // those nodes from their children's parents\n        // Don't actually remove those nodes in the first pass otherwise some children to remove\n        // won't exist anymore when looking for their parents\n        std::unordered_set<Node*> frontier;\n        for (auto& n : root_subgraph) {\n            if (n) {\n                if (_online_node_garbage && (child_subgraph.find(n) == child_subgraph.end())) {\n                    for (auto& child : n->children) {\n                        if (std::get<2>(child)) {\n                            std::get<2>(child)->parents.erase(n);\n                        }\n                    }\n                    removed_subgraph.insert(n);\n                } else {\n                    n->depth -= 1;\n                    // if (n->solved) {\n                    if (n->children.empty()) {\n                        frontier.insert(n);\n                    }\n                }\n            }\n        }\n        // Second pass: actually remove nodes in root_subgraph but not in child_subgraph\n        for (auto& n : removed_subgraph) {\n            _graph.erase(Node(n->state, _domain, _state_features, nullptr));\n        }\n        // Third pass: recompute fscores\n        backup_values(frontier);\n    }\n\n    // Backup values from tip solved nodes to their parents in graph\n    void backup_values(std::unordered_set<Node*>& frontier) {\n        std::size_t depth = 0; // used to prevent infinite loop in case of cycles\n        for (auto& n : frontier) {\n            _execution_policy.protect([this, &n](){\n                if (n->pruned) {\n                    n->value = 0;\n                    for (std::size_t d = 0 ; d < (_max_depth - n->depth) ; d++) {\n                        n->value = _min_reward + (_discount * (n->value));\n                    }\n                }\n            }, n->mutex);\n        }\n\n        while (!frontier.empty() && depth <= _max_depth) {\n            depth += 1;\n            std::unordered_set<Node*> new_frontier;\n            for (auto& n : frontier) {\n                update_frontier(new_frontier, n, &_execution_policy);\n            }\n            frontier = new_frontier;\n        }\n    }\n\n    template <typename TTexecution_policy,\n              std::enable_if_t<std::is_same<TTexecution_policy, SequentialExecution>::value, int> = 0>\n    void update_frontier(std::unordered_set<Node*>& new_frontier, Node* n, [[maybe_unused]] TTexecution_policy* execution_policy) {\n        for (auto& p : n->parents) {\n            p->solved = true;\n            p->value = -std::numeric_limits<double>::max();\n            p->best_action = nullptr;\n            for (auto& nn : p->children) {\n                p->solved = p->solved && std::get<2>(nn) && std::get<2>(nn)->solved;\n                if (std::get<2>(nn)) {\n                    double tentative_value = std::get<1>(nn) + (_discount * std::get<2>(nn)->value);\n                    if (p->value < tentative_value) {\n                        p->value = tentative_value;\n                        p->best_action = &std::get<0>(nn);\n                    }\n                }\n            }\n            new_frontier.insert(p);\n        }\n    }\n\n    template <typename TTexecution_policy,\n              std::enable_if_t<std::is_same<TTexecution_policy, ParallelExecution>::value, int> = 0>\n    void update_frontier(std::unordered_set<Node*>& new_frontier, Node* n, [[maybe_unused]] TTexecution_policy* execution_policy) {\n        std::list<Node*> parents;\n        _execution_policy.protect([&n, &parents](){\n            std::copy(n->parents.begin(), n->parents.end(), std::back_inserter(parents));\n        }, n->mutex);\n        for (auto& p : parents) {\n            p->solved = true;\n            p->value = -std::numeric_limits<double>::max();\n            p->best_action = nullptr;\n            _execution_policy.protect([this, &p](){\n                for (auto& nn : p->children) {\n                    p->solved = p->solved && std::get<2>(nn) && std::get<2>(nn)->solved;\n                    if (std::get<2>(nn)) {\n                        double tentative_value = std::get<1>(nn) + (_discount * std::get<2>(nn)->value);\n                        if (p->value < tentative_value) {\n                            p->value = tentative_value;\n                            p->best_action = &std::get<0>(nn);\n                        }\n                    }\n                }\n            }, p->mutex);\n            new_frontier.insert(p);\n        }\n    }\n}; // RIWSolver class\n\n} // namespace skdecide\n\n#endif // SKDECIDE_RIW_HH\n", "meta": {"hexsha": "c33a378889410935a35328fdc02d6006472e91b8", "size": 46760, "ext": "hh", "lang": "C++", "max_stars_repo_path": "cpp/src/hub/solver/riw.hh", "max_stars_repo_name": "jeromerobert/scikit-decide", "max_stars_repo_head_hexsha": "900916e627669fb3f7520edb2aaef55e08064b25", "max_stars_repo_licenses": ["MIT"], "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/hub/solver/riw.hh", "max_issues_repo_name": "jeromerobert/scikit-decide", "max_issues_repo_head_hexsha": "900916e627669fb3f7520edb2aaef55e08064b25", "max_issues_repo_licenses": ["MIT"], "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/hub/solver/riw.hh", "max_forks_repo_name": "jeromerobert/scikit-decide", "max_forks_repo_head_hexsha": "900916e627669fb3f7520edb2aaef55e08064b25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.6070686071, "max_line_length": 202, "alphanum_fraction": 0.5376390077, "num_tokens": 9635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.02479816105143576, "lm_q1q2_score": 0.008125571620827261}}
{"text": "/* RTQL8, Copyright (c) 2011, Georgia Tech Research Corporation\n * All rights reserved.\n *\n * Author(s): Sehoon Ha <sha9@gatech.edu>\n * Georgia Tech Graphics Lab\n */\n\n #define _USE_MATH_DEFINES\n\n#include \"pydart_api.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <math.h>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n// Boost headers\n#include <boost/algorithm/string.hpp>    \n\n// Dart headers\n#include \"dart/dart.h\"\n// #include \"dart/renderer/LoadOpengl.h\"\n// #include \"dart/renderer/RenderInterface.h\"\n// #include \"dart/renderer/OpenGLRenderInterface.h\"\n// #include \"dart/simulation/World.h\"\n// #include \"dart/dynamics/Skeleton.h\"\n// #include \"dart/dynamics/BodyNode.h\"\n// #include \"dart/dynamics/Shape.h\"\n// #include \"dart/dynamics/MeshShape.h\"\n// #include \"dart/dynamics/Joint.h\"\n// #include \"dart/dynamics/DegreeOfFreedom.h\"\n// #include \"dart/constraint/ConstraintSolver.h\"\n// #include \"dart/collision/CollisionDetector.h\"\n// #include \"dart/collision/dart/DARTCollisionDetector.h\"\n// #include \"dart/collision/fcl/FCLCollisionDetector.h\"\n// #include \"dart/collision/fcl_mesh/FCLMeshCollisionDetector.h\"\n// #include \"dart/collision/bullet/BulletCollisionDetector.h\"\n// #include \"dart/constraint/ContactConstraint.h\"\n// // #include \"dart/utils/Paths.h\"\n// #include \"dart/math/Geometry.h\"\n// #include \"dart/utils/SkelParser.h\"\n// #include \"dart/utils/sdf/SoftSdfParser.h\"\n// #include \"dart/utils/urdf/DartLoader.h\"\n// #include \"dart/utils/VskParser.h\"\n// #include \"dart/utils/FileInfoWorld.h\"\n\nnamespace pydart {\n\n////////////////////////////////////////////////////////////\n// class Manager\nclass Manager {\npublic:\n    static void init();\n    static void destroy();\n    static Manager* getInstance() { return g_manager; }\n    static dart::renderer::RenderInterface* getRI() {\n        return g_ri;\n      \n    }\n\n    static dart::simulation::WorldPtr world(int index = 0);\n    static dart::dynamics::SkeletonPtr skeleton(int index);\n    static dart::dynamics::SkeletonPtr skeleton(int wid, int skid);\n    static int createWorld(double timestep);\n    static int createWorldFromSkel(const char* const path);\n    static void destroyWorld(int id);\n    \nprotected:\n    static Manager* g_manager;\n    static dart::renderer::RenderInterface* g_ri;\n\n    // std::vector<dart::simulation::WorldPtr> worlds;\n    int next_id;\n    std::map<int, dart::simulation::WorldPtr> worlds;\n\n};\n\nManager* Manager::g_manager = NULL;\ndart::renderer::RenderInterface* Manager::g_ri = NULL;\n\nvoid Manager::init() {\n    g_manager = new Manager();\n    g_ri = new dart::renderer::OpenGLRenderInterface();\n    //   g_ri->initialize();\n    g_manager->next_id = 0;\n    cout << \" [pydart_api] Initialize pydart manager OK\" << endl;\n}\n\nvoid Manager::destroy() {\n    if (g_manager) {\n        delete g_manager;\n        g_manager = NULL;\n    }\n    if (g_ri) {\n        delete g_ri;\n        g_ri = NULL;\n    }\n    cout << \" [pydart_api] Destroy pydart manager OK\" << endl;\n}\n\ndart::simulation::WorldPtr Manager::world(int index) {\n    Manager* manager = getInstance();\n    return manager->worlds[index];\n}\n\ndart::dynamics::SkeletonPtr Manager::skeleton(int index) {\n    return world()->getSkeleton(index);\n}\n\ndart::dynamics::SkeletonPtr Manager::skeleton(int wid, int skid) {\n    return world(wid)->getSkeleton(skid);\n}\n\n\nint Manager::createWorld(double timestep) {\n    Manager* manager = getInstance();\n\n    dart::simulation::WorldPtr w(new dart::simulation::World());\n    w->setTimeStep(timestep);\n    w->setGravity(Eigen::Vector3d(0.0, -9.81, 0.0));\n    // int id = manager->worlds.size();\n    // manager->worlds.push_back(w);\n    int id = manager->next_id++; \n    manager->worlds[id] = w;\n    return id;\n}\n\nint Manager::createWorldFromSkel(const char* const path) {\n    Manager* manager = getInstance();\n\n    dart::simulation::WorldPtr w(dart::utils::SkelParser::readWorld(path));\n    // w->setTimeStep(timestep);\n    // w->setGravity(Eigen::Vector3d(0.0, -9.81, 0.0));\n    int id = manager->next_id++;\n    manager->worlds[id] = w;\n    // int id = manager->worlds.size();\n    // manager->worlds.push_back(w);\n    return id;\n}\n\nvoid Manager::destroyWorld(int id) {\n    Manager* manager = getInstance();\n    dart::simulation::WorldPtr w = manager->worlds[id];\n    manager->worlds.erase(id);\n    cout << \" [pydart_api] worlds.size = \" << manager->worlds.size() << endl;\n    // w.reset();\n    cout << \" [pydart_api] Destroy world OK: \" << id << endl;\n}\n\n// class Manager\n////////////////////////////////////////////////////////////\n\n} // namespace pydart\n\nusing namespace pydart;\n\n////////////////////////////////////////////////////////////////////////////////\n// Init Functions\nvoid init() {\n    if (Manager::getInstance()) {\n        Manager::destroy();\n    }\n    Manager::init();\n}\n\nvoid destroy() {\n    Manager::destroy();\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Manipulation Functions\nint createWorld(double timestep) {\n    return Manager::createWorld(timestep);\n}\n\nint createWorldFromSkel(const char* const path) {\n    int wid = Manager::createWorldFromSkel(path);\n    std::cout << \" [pydart_api] # Skeletons in \" << path << \" = \" << numSkeletons(wid) << std::endl;\n    return wid;\n}\n\nvoid destroyWorld(int wid) {\n    Manager::destroyWorld(wid);\n}\n\nint saveWorldToFile(int wid, const char* const path) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    dart::utils::FileInfoWorld* file = new dart::utils::FileInfoWorld();\n    bool result = file->saveFile(path, world->getRecording());\n    return (int)result;\n}\n\n\nint addSkeleton(int wid, const char* const path, double frictionCoeff) {\n    using namespace dart::simulation;\n    using namespace dart::dynamics;\n    std::string strpath(path);\n    std::string ext = strpath.substr(strpath.length() - 4);\n    boost::algorithm::to_lower(ext);\n\n    SkeletonPtr skel = NULL;\n    if (ext == \".sdf\") {\n        cout << \" [pydart_api] parse as SDF (ext: \" << ext << \")\" << endl;\n        skel = dart::utils::SoftSdfParser::readSkeleton(path);\n    } else if (ext == \"urdf\") {\n        cout << \" [pydart_api] parse as URDF (ext: \" << ext << \")\" << endl;\n        dart::utils::DartLoader urdfLoader;\n        skel = urdfLoader.parseSkeleton(path);\n    } else if (ext == \".vsk\") {\n        cout << \" [pydart_api] parse as VSK (ext: \" << ext << \")\" << endl;\n\tcout << \"Not implemented yet\" << endl;\n\tstd::cin.get();\n        //skel = dart::utils::VskParser::readSkeleton(path);\n    } else {\n        cout << \" [pydart_api] bad extension (ext: \" << ext << \")\" << endl;\n        return -1;\n    }\n    // SkeletonPtr skel = urdfLoader.parseSkeleton(path);\n\n    cout << \" [pydart_api] skel [\" << path << \"] : friction = \" << frictionCoeff << endl;\n    for (size_t i = 0; i < skel->getNumBodyNodes(); ++i) {\n        dart::dynamics::BodyNode* bn = skel->getBodyNode(i);\n        bn->setFrictionCoeff(frictionCoeff);\n    }\n    \n    WorldPtr world = Manager::world(wid);\n    int id = world->getNumSkeletons();\n    world->addSkeleton(skel);\n\n    // Debug\n    dart::constraint::ConstraintSolver* solver = world->getConstraintSolver();\n    dart::collision::CollisionDetector* detector = solver->getCollisionDetector();\n    dart::collision::CollisionDetector* detector2 = new dart::collision::FCLMeshCollisionDetector();\n    solver->setCollisionDetector(detector2);\n    detector = detector2;\n\n    if (dynamic_cast<dart::collision::DARTCollisionDetector*>(detector)) {\n        std::cout << \" [pydart_api] DARTCollisionDetector!\" << std::endl;\n    } else if (dynamic_cast<dart::collision::FCLCollisionDetector*>(detector)) {\n        std::cout << \" [pydart_api] FCLCollisionDetector!\" << std::endl;\n    } else if (dynamic_cast<dart::collision::FCLMeshCollisionDetector*>(detector)) {\n        std::cout << \" [pydart_api] FCLMeshCollisionDetector!\" << std::endl;\n    } else if (dynamic_cast<dart::collision::BulletCollisionDetector*>(detector)) {\n        std::cout << \" [pydart_api] BulletCollisionDetector!\" << std::endl;\n    } else {\n        std::cout << \" [pydart_api] Unknown CollisionDetector... (maybe bullet)\" << std::endl;\n    }\n\n    dart::constraint::ContactConstraint::setErrorReductionParameter(0);\n    std::cout << \" [pydart_api] Zero ERP!!!\" << std::endl;\n    std::cout << \" [pydart_api] ERP = \" << dart::constraint::ContactConstraint::getErrorReductionParameter() << std::endl;\n    \n    return id;\n}\n\nint numSkeletons(int wid) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    return world->getNumSkeletons();\n}\n\nvoid setSkeletonJointDamping(int wid, int skid, double damping) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n\n    for (size_t i = 1; i < skel->getNumBodyNodes(); ++i) {\n        dart::dynamics::Joint* joint = skel->getJoint(i);\n        if (joint->getNumDofs() > 0) {\n            for (size_t j = 0; j < joint->getNumDofs(); ++j) {\n                joint->setDampingCoefficient(j, damping);\n            }\n        }\n    }\n\n}\n////////////////////////////////////////////////////////////////////////////////\n// Simulation Functions\nvoid resetWorld(int wid) {\n    using namespace dart::simulation;\n    using namespace dart::dynamics;\n    WorldPtr world = Manager::world(wid);\n    world->reset();\n    // Debug\n    // std::cout << \"reinitialize collision detector\" << std::endl;\n    // dart::constraint::ConstraintSolver* solver = world->getConstraintSolver();\n    // dart::collision::CollisionDetector* detector = solver->getCollisionDetector();\n    // std::cout << \"reinitialize collision detector... creating new..\" << std::endl;\n    // dart::collision::CollisionDetector* detector2 = new dart::collision::FCLMeshCollisionDetector();\n    // dart::collision::CollisionDetector* detector2 = new dart::collision::BulletCollisionDetector();\n    // dart::collision::CollisionDetector* detector2 = new dart::collision::FCLCollisionDetector();\n    // solver->setCollisionDetector(detector2);\n    // std::cout << \" [pydart_api] reinitialize collision detector... deleting old..\" << std::endl;\n    // delete detector;\n    // std::cout << \" [pydart_api] OK\" << std::endl;\n    for (int skid = 0; skid < numSkeletons(wid); skid++) {\n        SkeletonPtr skel = Manager::skeleton(wid, skid);\n\n        skel->resetCommands();\n        skel->resetPositions();\n        skel->resetVelocities();\n        skel->resetAccelerations();\n        skel->resetGeneralizedForces();\n        skel->clearExternalForces();\n        skel->clearConstraintImpulses();\n    }\n    // std::cout << \"reinitialize collision detector... done\" << std::endl;\n}\n\nvoid stepWorld(int wid) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    world->step();\n    // world->bake();\n}\n\nvoid render(int wid) {\n    using namespace dart::simulation;\n    dart::renderer::RenderInterface* ri = Manager::getRI();\n    WorldPtr world = Manager::world(wid);\n    \n    for (size_t i = 0; i < world->getNumSkeletons(); i++) {\n        world->getSkeleton(i)->draw(ri);\n    }\n}\n\nvoid renderSkeleton(int wid, int skid) {\n    using namespace dart::dynamics;\n    dart::renderer::RenderInterface* ri = Manager::getRI();\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    skel->drawMarkers(ri);\n}\n\nvoid renderSkeletonWithColor(int wid, int skid, double r, double g, double b, double a) {\n    using namespace dart::dynamics;\n    dart::renderer::RenderInterface* ri = Manager::getRI();\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    skel->draw(ri, Eigen::Vector4d(r, g, b, a), false);\n}\n\nvoid renderSkeletonMarkers(int wid, int skid) {\n    using namespace dart::dynamics;\n    dart::renderer::RenderInterface* ri = Manager::getRI();\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    skel->drawMarkers(ri);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// World Functions\ndouble getWorldTime(int wid) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    return world->getTime();\n}\n\ndouble getWorldTimeStep(int wid) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    return world->getTimeStep();\n}\n\nvoid setWorldTimeStep(int wid, double _timeStep) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    world->setTimeStep(_timeStep);\n}\n\n\nint getWorldSimFrames(int wid) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    return world->getSimFrames();\n}\n\nvoid setWorldSimFrame(int wid, int playFrame) {\n    using namespace dart::simulation;\n    WorldPtr world = Manager::world(wid);\n    if (playFrame >= world->getRecording()->getNumFrames()) {\n        return;\n    }\n    \n    size_t nSkels = world->getNumSkeletons();\n    for (size_t i = 0; i < nSkels; i++) {\n        // size_t start = world->getIndex(i);\n        // size_t size = world->getSkeleton(i)->getNumDofs();\n        world->getSkeleton(i)->setPositions(world->getRecording()->getConfig(playFrame, i));\n        world->getSkeleton(i)->computeForwardKinematics(true, true, false);\n    }\n}\n\nint getWorldNumContacts(int wid) {\n    dart::simulation::WorldPtr world = Manager::world(wid);\n    dart::collision::CollisionDetector* cd =\n        world->getConstraintSolver()->getCollisionDetector();\n    return cd->getNumContacts();\n}\n\nvoid getWorldContacts(int wid, double* outv, int len) {\n    dart::simulation::WorldPtr world = Manager::world(wid);\n    dart::collision::CollisionDetector* cd =\n        world->getConstraintSolver()->getCollisionDetector();\n    size_t n = cd->getNumContacts();\n    if (7 * n != (size_t)len) {\n        cerr << \"getWorldContacts: 7n is needed for the output vector. n = \" << n << \", len =  \" << len << endl;\n        return;\n    }\n\n    // ( v.x, v.y, v.z, p.x, p.y, p.z, id )\n    \n    int ptr = 0;\n    for (size_t i = 0; i < n; i++) {\n        Eigen::Vector3d v = cd->getContact(i).point;\n        Eigen::Vector3d f = cd->getContact(i).force;\n        for (int j = 0; j < 3; j++) {\n            outv[ptr++] = v(j);\n        }\n        for (int j = 0; j < 3; j++) {\n            outv[ptr++] = f(j);\n        }\n        outv[ptr++] = i;\n\n    }    \n}\n\nvoid setWorldCollisionPair(int wid, int skid1, int bid1, int skid2, int bid2, int bEnable) {\n    using namespace dart::simulation;\n    using namespace dart::dynamics;\n    // Get collision detector\n    WorldPtr world = Manager::world(wid);\n    dart::constraint::ConstraintSolver* solver = world->getConstraintSolver();\n    dart::collision::CollisionDetector* detector = solver->getCollisionDetector();\n\n    // Get body1 and body2\n    SkeletonPtr skel1 = Manager::skeleton(wid, skid1);\n    BodyNode* body1 = skel1->getBodyNode(bid1);\n    SkeletonPtr skel2 = Manager::skeleton(wid, skid2);\n    BodyNode* body2 = skel2->getBodyNode(bid2);\n    // cout << \" [pydart_api] set collision pair \"\n    //      << \"(skel \" << skid1 << \" body \" <<  bid1 << \") and \"\n    //      << \"(skel \" << skid2 << \" body \" <<  bid2 << \")\"\n    //      << \" as \" << bEnable << endl;\n    bool enable = (bEnable != 0);\n    if (enable) {\n        detector->enablePair(body1, body2);\n    } else {\n        detector->disablePair(body1, body2);\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Skeleton Attribute Functions\nconst char* getSkeletonName(int wid, int skid) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    return skel->getName().c_str();\n}\n\ndouble getSkeletonMass(int wid, int skid) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    return skel->getMass();\n}\n\nint getSkeletonNumDofs(int wid, int skid) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    return skel->getNumDofs();\n}\n\nint getSkeletonNumBodies(int wid, int skid) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    return skel->getNumBodyNodes();\n}\n\nint getSkeletonNumJoints(int wid, int skid) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    return skel->getNumJoints();\n}\n\nconst char* getSkeletonBodyName(int wid, int skid, int bodyid) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    return skel->getBodyNode(bodyid)->getName().c_str();\n}\n\nconst char* getSkeletonDofName(int wid, int skid, int dofid) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    // return skel->getGenCoordInfo(dofid).joint->getName().c_str();\n    return skel->getDof(dofid)->getName().c_str();\n}\n\nconst char* getSkeletonJointName(int wid, int skid, int jointid) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    return skel->getJoint(jointid)->getName().c_str();\n}\n\nint getSkeletonMobile(int wid, int skid) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    if (skel->isMobile()) {\n        return 1;\n    } else {\n        return 0;\n    }\n}    \n\nvoid setSkeletonMobile(int wid, int skid, int mobile) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    skel->setMobile(mobile != 0);\n}\n\nvoid setSkeletonSelfCollision(int wid, int skid, int bSelfCollision, int bAdjacentBodies) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    if (bSelfCollision != 0) {\n        bool _enableAdjecentBodies = (bAdjacentBodies != 0);\n        cout << \" [pydart_api] enable skeleton self collision: skid = \" << skid << endl;\n        cout << \" [pydart_api] _enableAdjecentBodies = \" << _enableAdjecentBodies << endl;\n        skel->enableSelfCollision(_enableAdjecentBodies);\n    } else {\n        cout << \" [pydart_api] disable skeleton self collision: skid = \" << skid << endl;\n        skel->disableSelfCollision();\n    }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Skeleton Pose Functions\nvoid getSkeletonPositions(int wid, int skid, double* outpose, int ndofs) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    \n    Eigen::VectorXd q = skel->getPositions();\n    for (int i = 0; i < q.size(); i++) {\n        outpose[i] = q(i);\n    }\n}\n\nvoid getSkeletonVelocities(int wid, int skid, double* outpose, int ndofs) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    \n    Eigen::VectorXd qdot = skel->getVelocities();\n    for (int i = 0; i < qdot.size(); i++) {\n        outpose[i] = qdot(i);\n    }\n}\n\nvoid getSkeletonMassMatrix(int wid, int skid, double* array2, int nrows, int ncols) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    const Eigen::MatrixXd& M = skel->getMassMatrix();\n    \n    int ptr = 0;\n    for (int i = 0; i < M.rows(); i++) {\n        for (int j = 0; j < M.cols(); j++) {\n            array2[ptr++] = M(i, j);\n        }\n    }\n}\n\nvoid getSkeletonCoriolisAndGravityForces(int wid, int skid, double* outpose, int ndofs) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    const Eigen::VectorXd& C = skel->getCoriolisAndGravityForces();\n    for (int i = 0; i < C.size(); i++) {\n        outpose[i] = C(i);\n    }\n}\n\nvoid getSkeletonConstraintForces(int wid, int skid, double* outpose, int ndofs) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    const Eigen::VectorXd& F = skel->getConstraintForces();\n    for (int i = 0; i < F.size(); i++) {\n        outpose[i] = F(i);\n    }\n}\n\n\nvoid setSkeletonPositions(int wid, int skid, double* inpose, int ndofs) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n\n    Eigen::VectorXd q(ndofs);\n    for (int i = 0; i < q.size(); i++) {\n        q(i) = inpose[i];\n    }\n    skel->setPositions(q);\n    // skel->computeForwardKinematics(true, true, false);\n}\n\nvoid setSkeletonVelocities(int wid, int skid, double* inpose, int ndofs) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n\n    Eigen::VectorXd q(ndofs);\n    for (int i = 0; i < q.size(); i++) {\n        q(i) = inpose[i];\n    }\n    skel->setVelocities(q);\n    // skel->computeForwardKinematics(true, true, false);\n}\n\nvoid setSkeletonForces(int wid, int skid, double* intorque, int ndofs) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n\n    Eigen::VectorXd tau(ndofs);\n    for (int i = 0; i < tau.size(); i++) {\n        tau(i) = intorque[i];\n    }\n    skel->setForces(tau);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Skeleton Limit Functions\nvoid getSkeletonPositionLowerLimit(int wid, int skid, double* outpose, int ndofs) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    for (int i = 0; i < ndofs; i++) {\n        outpose[i] = skel->getPositionLowerLimit(i);\n    }\n}\n\nvoid getSkeletonPositionUpperLimit(int wid, int skid, double* outpose, int ndofs) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    for (int i = 0; i < ndofs; i++) {\n        outpose[i] = skel->getPositionUpperLimit(i);\n    }\n}\n\nvoid getSkeletonForceLowerLimit(int wid, int skid, double* outpose, int ndofs) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    for (int i = 0; i < ndofs; i++) {\n        outpose[i] = skel->getForceLowerLimit(i);\n    }\n}\n\nvoid getSkeletonForceUpperLimit(int wid, int skid, double* outpose, int ndofs) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    for (int i = 0; i < ndofs; i++) {\n        outpose[i] = skel->getForceUpperLimit(i);\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Skeleton Momentum Functions\nvoid getSkeletonWorldCOM(int wid, int skid, double outv3[3]) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    // Eigen::Vector3d C = skel->getWorldCOM();\n    Eigen::Vector3d C = skel->getCOM();\n    for (int i = 0; i < C.size(); i++) {\n        outv3[i] = C(i);\n    }\n}\n\nvoid getSkeletonWorldCOMVelocity(int wid, int skid, double outv3[3]) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    // Eigen::Vector3d CV = skel->getWorldCOMVelocity();\n    Eigen::Vector3d CV = skel->getCOMLinearVelocity();\n    for (int i = 0; i < CV.size(); i++) {\n        outv3[i] = CV(i);\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// BodyNode Functions\ndouble getBodyNodeMass(int wid, int skid, int bid) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    return bn->getMass();\n}\n\nvoid getBodyNodeInertia(int wid, int skid, int bid, double outv33[3][3]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    double Ixx, Iyy, Izz, Ixy, Ixz, Iyz;\n    bn->getMomentOfInertia(Ixx, Iyy, Izz, Ixy, Ixz, Iyz);\n    outv33[0][0] = Ixx;    outv33[1][1] = Iyy;    outv33[2][2] = Izz;\n    outv33[0][1] = Ixy;    outv33[1][0] = Ixy; \n    outv33[0][2] = Ixz;    outv33[2][0] = Ixz; \n    outv33[1][2] = Iyz;    outv33[2][1] = Iyz; \n}\n\nvoid getBodyNodeLocalCOM(int wid, int skid, int bid, double outv3[3]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    const Eigen::Vector3d& x = bn->getLocalCOM();\n    for (int i = 0; i < x.size(); i++) {\n        outv3[i] = x(i);\n    }\n}\n\nvoid getBodyNodeShapeBoundingBoxDim(int wid, int skid, int bid, double outv3[3]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    // cout << \"bodynode \" << bid << \" is fetched\" << endl;\n    // Assume single shape for now\n    const int num_shapes = bn->getNumCollisionShapes();\n    if (num_shapes == 0) {\n        for (int i = 0; i < 3; i++) {\n            outv3[i] = 0.0;\n        }\n    } else {\n        dart::dynamics::ShapePtr shape = bn->getCollisionShape(0);\n        Eigen::Vector3d scale(1, 1, 1);\n        dart::dynamics::MeshShape* mshape = dynamic_cast<dart::dynamics::MeshShape*>(shape.get());\n        if (mshape) {\n            scale = mshape->getScale();\n        }\n        // cout << \"Scale:\" << scale << endl;\n        const Eigen::Vector3d& x = shape->getBoundingBoxDim();\n        for (int i = 0; i < x.size(); i++) {\n            outv3[i] = x(i) * scale(i);\n        }\n    }\n}\n\nvoid getBodyNodeWorldCOM(int wid, int skid, int bid, double outv3[3]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    // const Eigen::Vector3d& x = bn->getWorldCOM();\n    const Eigen::Vector3d& x = bn->getCOM();\n    for (int i = 0; i < x.size(); i++) {\n        outv3[i] = x(i);\n    }\n}\n\nvoid getBodyNodeWorldCOMVelocity(int wid, int skid, int bid, double outv3[3]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    // const Eigen::Vector3d& x = bn->getWorldCOMVelocity();\n    const Eigen::Vector3d& x = bn->getCOMLinearVelocity();\n    for (int i = 0; i < x.size(); i++) {\n        outv3[i] = x(i);\n    }\n}\n\nvoid getBodyNodeWorldCOMSpatialVelocity(int wid, int skid, int bid, double outv6[6]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    const Eigen::Vector6d& x = bn->getCOMSpatialVelocity();\n    for (int i = 0; i < x.size(); i++) {\n        outv6[i] = x(i);\n    }\n}\n\nvoid getBodyNodeWorldCOMSpatialAcceleration(int wid, int skid, int bid, double outv6[6]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    const Eigen::Vector6d& x = bn->getCOMSpatialAcceleration();\n    // cout << \"C = \" << bn->getCOM().transpose() << endl;\n    // cout << \"x = \" << x.transpose() << endl;\n    for (int i = 0; i < x.size(); i++) {\n        outv6[i] = x(i);\n    }\n}\n\nvoid getBodyNodeLocalCOMSpatialVelocity(int wid, int skid, int bid, double outv6[6]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    const dart::dynamics::Frame* world = dart::dynamics::Frame::World();\n    const Eigen::Vector6d& x = bn->getCOMSpatialVelocity(world, bn);\n    for (int i = 0; i < x.size(); i++) {\n        outv6[i] = x(i);\n    }\n}\n\nvoid getBodyNodeLocalCOMSpatialAcceleration(int wid, int skid, int bid, double outv6[6]) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    const dart::dynamics::Frame* world = dart::dynamics::Frame::World();\n    const Eigen::Vector6d& x = bn->getCOMSpatialAcceleration(world, bn);\n    for (int i = 0; i < x.size(); i++) {\n        outv6[i] = x(i);\n    }\n}\n\nint getBodyNodeNumContacts(int wid, int skid, int bid) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    // dart::dynamics::BodyNode* bn = skel->getBodyNode(bid);\n    dart::dynamics::BodyNodePtr bn = skel->getBodyNode(bid);\n\n    dart::simulation::WorldPtr world = Manager::world(wid);\n    dart::collision::CollisionDetector* cd =\n        world->getConstraintSolver()->getCollisionDetector();\n    size_t n = cd->getNumContacts();\n    int cnt = 0;\n    for (size_t i = 0; i < n; i++) {\n        dart::collision::Contact& c = cd->getContact(i);\n        if (c.bodyNode1.lock() == bn || c.bodyNode2.lock() == bn) {\n            cnt++;\n        }\n    }\n    return cnt;\n}\n\nvoid getBodyNodeContacts(int wid, int skid, int bid, double* outv, int len) {\n    dart::dynamics::SkeletonPtr skel = Manager::skeleton(wid, skid);\n    dart::dynamics::BodyNodePtr bn = skel->getBodyNode(bid);\n\n    dart::simulation::WorldPtr world = Manager::world(wid);\n    dart::collision::CollisionDetector* cd =\n        world->getConstraintSolver()->getCollisionDetector();\n    size_t n = cd->getNumContacts();\n\n    int m = 0;\n    for (size_t i = 0; i < n; i++) {\n        dart::collision::Contact& c = cd->getContact(i);\n        if (c.bodyNode1.lock() != bn && c.bodyNode2.lock() != bn) {\n            continue;\n        }\n        m++;\n    }\n\n    if (7 * m != len) {\n        cerr << \"getBodyNodeContacts: 7m is needed for the output vector. m = \" << m\n             << \", n = \" << n << \", len =  \" << len << endl;\n        return;\n    }\n\n    int ptr = 0;\n    for (size_t i = 0; i < n; i++) {\n        dart::collision::Contact& c = cd->getContact(i);\n        if (c.bodyNode1.lock() != bn && c.bodyNode2.lock() != bn) {\n            continue;\n        }\n        Eigen::Vector3d v = cd->getContact(i).point;\n        Eigen::Vector3d f = cd->getContact(i).force;\n        for (int j = 0; j < 3; j++) {\n            outv[ptr++] = v(j);\n        }\n        for (int j = 0; j < 3; j++) {\n            outv[ptr++] = f(j);\n        }\n        outv[ptr++] = i;\n\n    }\n}\n\nvoid getBodyNodeTransformation(int wid, int skid, int bid, double outv44[4][4]) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    BodyNode* body = skel->getBodyNode(bid);\n    if (!body) {\n        cerr << \"cannot find the body : \" << bid << endl;\n    }\n    const Eigen::Isometry3d& T = body->getTransform();\n    for (int i = 0; i < 4; i++) {\n        for (int j = 0; j < 4; j++) {\n            outv44[i][j] = T(i, j);\n        }\n    }\n}\n\nvoid getBodyNodeWorldLinearJacobian(int wid, int skid, int bid, double inv3[3], double* array2, int nrows, int ncols) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    BodyNode* body = skel->getBodyNode(bid);\n    if (!body) {\n        cerr << \"cannot find the body : \" << bid << endl;\n    }\n    Eigen::Vector3d offset(inv3[0], inv3[1], inv3[2]);\n    \n    int N = skel->getNumDofs();\n    // Eigen::MatrixXd J = body->getWorldLinearJacobian(offset);\n    dart::math::LinearJacobian J = body->getLinearJacobian(offset);\n    Eigen::MatrixXd JF = Eigen::MatrixXd::Zero(3, N);\n\n    for (int i = 0; i < J.cols(); i++) {\n        int j = body->getDependentGenCoordIndex(i);\n        JF.col(j) = J.col(i);\n    }\n\n    int ptr = 0;\n    for (int i = 0; i < JF.rows(); i++) {\n        for (int j = 0; j < JF.cols(); j++) {\n            array2[ptr++] = JF(i, j);\n        }\n    }\n}\n\nvoid addBodyNodeExtForce(int wid, int skid, int bid, double inv3[3]) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    BodyNode* body = skel->getBodyNode(bid);\n    if (!body) {\n        cerr << \"cannot find the body : \" << bid << endl;\n    }\n    Eigen::Vector3d f(inv3[0], inv3[1], inv3[2]);\n    body->addExtForce(f);\n}\n\nvoid addBodyNodeExtForceAt(int wid, int skid, int bid, double inv3[3], double inv3_2[3]) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    BodyNode* body = skel->getBodyNode(bid);\n    if (!body) {\n        cerr << \"cannot find the body : \" << bid << endl;\n    }\n    Eigen::Vector3d f(inv3[0], inv3[1], inv3[2]);\n    Eigen::Vector3d offset(inv3_2[0], inv3_2[1], inv3_2[2]);\n    body->addExtForce(f, offset);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Joint Functions\nvoid getJointTransform(int wid, int skid, int jid, double outv44[4][4]) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    Joint* joint = skel->getJoint(jid);\n    if (!joint) {\n        cerr << \"cannot find the joint : \" << jid << endl;\n    }\n    BodyNode* body = joint->getChildBodyNode();\n    const Eigen::Isometry3d& T_j = joint->getTransformFromChildBodyNode();\n    const Eigen::Isometry3d& T_b = body->getTransform();\n    const Eigen::Isometry3d& T = T_b*T_j;\n    for (int i = 0; i < 4; i++) {\n        for (int j = 0; j < 4; j++) {\n            outv44[i][j] = T(i, j);\n        }\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Marker Functions\nint getBodyNodeNumMarkers(int wid, int skid, int bid) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    BodyNode* body = skel->getBodyNode(bid);\n    return body->getNumMarkers();\n}\n\nvoid getMarkerPosition(int wid, int skid, int bid, int mid, double outv3[3]) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    BodyNode* body = skel->getBodyNode(bid);\n    Marker* marker = body->getMarker(mid);\n    if (!marker) {\n        cerr << \"cannot find the marker : \" << mid << endl;\n    }\n    const Eigen::Vector3d& x = marker->getWorldPosition();\n    for (int i = 0; i < x.size(); i++) {\n        outv3[i] = x(i);\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// C3D Functions\nint readC3D(const char* const path, double* outv, int len) {\n    dart::utils::FileInfoC3D file;\n    file.loadFile(path);\n    int nm = file.getNumMarkers();\n    int nf = file.getNumFrames();\n    if (len == 0) {\n        cout << \" [pydart_api] # Markers = \" << nm << endl;\n        cout << \" [pydart_api] # Frames = \" << nf << endl;\n        return 3 * nf * nm + 2; // return buffer size\n    } else if (len == 3 * nf * nm + 2) {\n        const int DIM = 3;\n        int ptr = 0;\n        outv[ptr++] = nf;\n        outv[ptr++] = nm;\n        for (int i = 0; i < nf; i++) {\n            for (int j = 0; j < nm; j++) {\n                Eigen::Vector3d m = file.getDataAt(i, j);\n                for (int k = 0; k < DIM; k++) {\n                    outv[ptr++] = m[k];\n                    // cout << ptr << \" / \" << i << \" \" << j << \" \" << k << \" \" << len << endl;\n                }\n            }\n        }\n        cout << \" [pydart_api] load C3D [\" << path << \"] OK\" << endl;\n        return 0;\n    } else {\n        cerr << \"invalid buffer size: \" << len << endl;\n        return -1;\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Auxiliary Functions\n\ndouble C_D(double theta_rad) {\n    return 2.0 * (1.0-fabs(cos(theta_rad))) + 0.005;\n}\n\ndouble C_L(double theta_rad) {\n    double theta = theta_rad * 180.0 / M_PI;\n    double xp[4] = {-85.0, -10.0, 30.0, 85.0};\n    double fp[4] = {-0.2, -0.4, 2.0, 0.8};\n    int lo, hi;\n    double t;\n\n    if (theta <= xp[0] || theta >= xp[3]) {\n        return 0.0;\n    } else if (theta >= xp[2]) {\n        lo = 2; hi = 3;\n    } else if (theta >= xp[1]) {\n        lo = 1; hi = 2;\n    } else {\n        lo = 0; hi = 1;\n    }\n\n    t = (theta-xp[lo]) / (xp[hi]-xp[lo]);\n    return (1.0-t)*fp[lo]+t*fp[hi];\n}\n\nEigen::Vector3d computeAerodynamics(const Eigen::Vector3d& velocity, const Eigen::Vector3d& normal, const double area) { \n    const double rho = 1000.0;\n    const double eps = 1.0e-5;\n\n    // Eigen::Vector3d& v_norm = v.normalized();\n    \n    // Zero Velocities\n    double v_norm = velocity.norm();\n    if (v_norm < eps)\n        return Eigen::Vector3d::Zero();\n\n    Eigen::Vector3d v = -velocity;\n    Eigen::Vector3d d_normal = -normal.normalized();\n    Eigen::Vector3d d_drag = v.normalized();\n\n    // Check Reverse Direction\n    if (d_normal.dot(d_drag) < 0.0)\n        return Eigen::Vector3d::Zero();\n\n    Eigen::Vector3d l = Eigen::Vector3d::Zero();\n\n    // When normal and drag direction coincide\n    if ((d_normal-d_drag).norm() < eps) {\n        if (d_normal[0] > 0.5 || d_normal[1] > 0.5) {\n            l = Eigen::Vector3d(d_normal[1],-d_normal[0],0.0);\n        } else {\n            l = Eigen::Vector3d(0.0,-d_normal[2],d_normal[1]);\n        }\n    } else {\n        l = d_drag.cross(d_normal);\n    }\n\n    l.normalize();\n    Eigen::Vector3d d_lift = l.cross(d_drag).normalized();\n\n    Eigen::Vector3d v_n = d_drag.dot(d_normal) * v;\n    Eigen::Vector3d v_t = v - v_n;\n\n    double theta = atan2(v_n.dot(d_normal),v_t.norm());\n\n    Eigen::Vector3d f_drag = 0.5 * rho * area * C_D(theta) * v_norm * v_norm * d_drag;\n    Eigen::Vector3d f_lift = 0.5 * rho * area * C_L(theta) * v_norm * v_norm * d_lift;\n    Eigen::Vector3d f_total = f_drag + f_lift;\n\n    return f_total;\n}\n\nvoid addAerodynamicForce(int wid, int skid, int bid) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    BodyNode* body = skel->getBodyNode(bid);\n    if (!body) {\n        cerr << \"cannot find the body : \" << bid << endl;\n    }\n    double d[3];\n    getBodyNodeShapeBoundingBoxDim(wid, skid, bid, d);\n    Eigen::Vector3d v = body->getCOMLinearVelocity();\n    const Eigen::Isometry3d& T = body->getTransform();\n\n    for (size_t i = 0; i < 3; i++) {\n        Eigen::Vector3d n1 = Eigen::Vector3d(T(0,i),T(1,i),T(2,i));\n        Eigen::Vector3d n2 = -n1;\n        Eigen::Vector3d offset1 = Eigen::Vector3d::Zero();\n        Eigen::Vector3d offset2 = Eigen::Vector3d::Zero();\n        offset1[i] = 0.5*d[i];\n        offset2[i] = -0.5*d[i];\n        double area = d[(i+1)%3]*d[(i+2)%3];\n\n        Eigen::Vector3d f1 = computeAerodynamics(v,n1,area);\n        Eigen::Vector3d f2 = computeAerodynamics(v,n2,area);\n\n        body->addExtForce(f1, offset1);//, offset1, false, false);\n        body->addExtForce(f2, offset2);//, offset2, false, false);\n    }\n}\n\nvoid addAerodynamicForce(int wid, int skid) {\n    using namespace dart::dynamics;\n    SkeletonPtr skel = Manager::skeleton(wid, skid);\n    for (size_t i = 0; i < skel->getNumBodyNodes(); i++) {\n        addAerodynamicForce(wid, skid, i);\n    }\n}\n\nvoid addAerodynamicForce(int wid) {\n    using namespace dart::dynamics;\n    for (int skid = 0; skid < numSkeletons(wid); skid++) {\n        addAerodynamicForce(wid, skid);\n    }\n}", "meta": {"hexsha": "3081e3fd99bee33a947b445fdcfd9f7710e6d1f3", "size": 37622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pydart/pydart_api/pydart_api.cpp", "max_stars_repo_name": "Jungdam/AlphaCon", "max_stars_repo_head_hexsha": "2c70e848ab176537560484d28869cdc3c2fc8cd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-16T05:43:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T05:52:29.000Z", "max_issues_repo_path": "pydart/pydart_api/pydart_api.cpp", "max_issues_repo_name": "Jungdam/AlphaCon", "max_issues_repo_head_hexsha": "2c70e848ab176537560484d28869cdc3c2fc8cd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pydart/pydart_api/pydart_api.cpp", "max_forks_repo_name": "Jungdam/AlphaCon", "max_forks_repo_head_hexsha": "2c70e848ab176537560484d28869cdc3c2fc8cd7", "max_forks_repo_licenses": ["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.1087941976, "max_line_length": 122, "alphanum_fraction": 0.5966455797, "num_tokens": 10751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.02297736811196841, "lm_q1q2_score": 0.00809266999580563}}
{"text": "#include <iostream>\n#include <complex>\n#include <fstream>\n\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/token_functions.hpp>\n\n#include \"simulationexecutor.h\"\n#include \"TridiagonalMatrix.h\"\n\nusing namespace boost;\nusing namespace boost::program_options;\n\nint main(int argc, char** argv) {\n    options_description desc(\n        \"Crank Nicolson solver for one dimensional waves.\\n\"\n        \"This program solves the timedependent Schroedinger equation\\n\"\n        \"for one dimensional waves.\\n\"\n        \"The only parameter which is nessesary is the simulation file.\\n\"\n        \"This simulation file contains the data and\\na path to a script to run a simulation.\\n\"\n    );\n    desc.add_options()\n            (\"help,h\", \"Show this help text\")\n            (\"files,f\", value<std::vector<std::string>>(), \"Simulation files\");\n\n    variables_map vm;\n    try {\n        store(command_line_parser(argc, argv).options(desc).run(), vm);\n        notify(vm);\n    } catch (std::exception &e) {\n        std::cout << e.what() << std::endl;\n        std::cout << desc << std::endl;\n    }\n\n    if (vm.count(\"help\")) {\n        desc.print(std::cout);\n    }\n\n    if (vm.count(\"files\")) {\n        std::vector<std::string> files = vm[\"files\"].as<std::vector<std::string>>();\n        for (auto file : files) {\n            std::cout << \"process file: \" << file << std::endl;\n            SimulationExecutor(file.c_str()); //only call constructor\n        }\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "ee5d80f3a37c7d36b1a2e0c62c50668adc73bc16", "size": 1603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "TheTimmy/CrankNicolson", "max_stars_repo_head_hexsha": "44e2e5e3fa07af17444f1e341e9021c47ab87601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "TheTimmy/CrankNicolson", "max_issues_repo_head_hexsha": "44e2e5e3fa07af17444f1e341e9021c47ab87601", "max_issues_repo_licenses": ["MIT"], "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": "TheTimmy/CrankNicolson", "max_forks_repo_head_hexsha": "44e2e5e3fa07af17444f1e341e9021c47ab87601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T06:09:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-16T06:09:34.000Z", "avg_line_length": 30.2452830189, "max_line_length": 95, "alphanum_fraction": 0.6325639426, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370636758849891, "lm_q2_score": 0.03461884132918788, "lm_q1q2_score": 0.008090643657167102}}
{"text": "/*\n              __ __ __\n             |__|__|  | __\n             |  |  |  ||__|\n  ___ ___ __ |  |  |  |\n |   |   |  ||  |  |  |    Ubiquitous Internet @ IIT-CNR\n |   |   |  ||  |  |  |    C++ edge computing libraries and tools\n |_______|__||__|__|__|    https://github.com/ccicconetti/serverlessonedge\n\nLicensed under the MIT License <http://opensource.org/licenses/MIT>\nCopyright (c) 2021 C. Cicconetti <https://ccicconetti.github.io/>\n\nPermission is hereby  granted, free of charge, to any  person obtaining a copy\nof this software and associated  documentation files (the \"Software\"), to deal\nin the Software  without restriction, including without  limitation the rights\nto  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell\ncopies  of  the Software,  and  to  permit persons  to  whom  the Software  is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE  IS PROVIDED \"AS  IS\", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR\nIMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,\nFITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE\nAUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER\nLIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"StateSim/network.h\"\n\n#include \"Support/split.h\"\n\n#include <glog/logging.h>\n\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n#include <cassert>\n#include <fstream>\n#include <sstream>\n\nnamespace uiiit {\nnamespace statesim {\n\nstruct NodeList : public std::vector<std::string> {\n  static NodeList make(const std::string&             aString,\n                       [[maybe_unused]] Counter<int>& aCounter) {\n    const auto ret = support::split<NodeList>(aString, \" \");\n    if (ret.size() <= 1) {\n      throw std::runtime_error(\"Invalid edge: \" + aString);\n    }\n    return ret;\n  }\n};\n\ntemplate <class T>\nstd::vector<T> loadFile(const std::string& aPath, Counter<int>& aCounter) {\n  std::vector<T> ret;\n  std::ifstream  myFile(aPath);\n  if (not myFile) {\n    throw std::runtime_error(\"Cannot open file for reading: \" + aPath);\n  }\n  std::string myLine;\n  while (myFile) {\n    std::getline(myFile, myLine);\n    if (myLine.empty() or myLine[0] == '#') {\n      continue;\n    }\n    ret.emplace_back(T::make(myLine, aCounter));\n  }\n  return ret;\n}\n\nstd::vector<Node> loadNodes(const std::string& aPath, Counter<int>& aCounter) {\n  return loadFile<Node>(aPath, aCounter);\n}\n\nstd::vector<Link> loadLinks(const std::string& aPath, Counter<int>& aCounter) {\n  return loadFile<Link>(aPath, aCounter);\n}\n\nstd::vector<NodeList> loadNodeLists(const std::string& aPath) {\n  Counter<int> myCounter;\n  return loadFile<NodeList>(aPath, myCounter);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// class Network\n\nNetwork::Network(const std::string& aNodesPath,\n                 const std::string& aLinksPath,\n                 const std::string& aEdgesPath)\n    : theMutex()\n    , theNodes()\n    , theLinks()\n    , theElements()\n    , theClients()\n    , theProcessing()\n    , theGraph()\n    , theCloudParams(nullptr)\n    , theCache()\n    , theCentral(nullptr) {\n  // read from files\n  Counter<int> myCounter;\n  auto         myNodes     = loadNodes(aNodesPath, myCounter);\n  auto         myLinks     = loadLinks(aLinksPath, myCounter);\n  const auto   myNodeLists = loadNodeLists(aEdgesPath);\n\n  // copy into member maps\n  for (const auto& myNode : myNodes) {\n    theNodes.emplace(myNode.name(), myNode);\n  }\n  for (const auto& myLink : myLinks) {\n    theLinks.emplace(myLink.name(), myLink);\n  }\n\n  // save pointers to processing nodes and clients into dedicated containers\n  for (auto& elem : theNodes) {\n    if (elem.second.client()) {\n      theClients.emplace_back(&elem.second);\n    }\n    theProcessing.emplace_back(&elem.second);\n  }\n\n  // add to theNodes the non-processing nodes\n  for (const auto& myNodeList : myNodeLists) {\n    for (const auto& myName : myNodeList) {\n      if (theNodes.find(myName) == theNodes.end() and\n          theLinks.find(myName) == theLinks.end()) {\n        [[maybe_unused]] const auto ret =\n            theNodes.emplace(myName, Node(myName, myCounter()));\n        assert(ret.second);\n      }\n    }\n  }\n\n  // create the list of edges (with weights)\n  std::vector<Edge>  myEdges;\n  std::vector<float> myWeights;\n  for (const auto& myNodeList : myNodeLists) {\n    assert(myNodeList.size() >= 2);\n    auto       it               = myNodeList.begin();\n    const auto mySourceId       = id(*it);\n    const auto mySourceCapacity = capacity(*it);\n    const auto mySourceLatency =\n        mySourceCapacity > 0 ? (2.0f / mySourceCapacity) : 0;\n    ++it;\n    for (; it != myNodeList.end(); ++it) {\n      const auto myTargetId       = id(*it);\n      const auto myTargetCapacity = capacity(*it);\n\n      // compute the weight as the sum of the half reciprocals of the source\n      // and target, but only if they are links\n      const auto myWeight =\n          mySourceLatency +\n          (myTargetCapacity > 0 ? (2.0f / myTargetCapacity) : 0);\n\n      myEdges.emplace_back(Edge(mySourceId, myTargetId));\n      myWeights.emplace_back(myWeight);\n\n      VLOG(2) << \"src \" << mySourceId << \" dst \" << myTargetId << \" weight \"\n              << myWeight;\n    }\n  }\n\n  initElementsGraph(myEdges, myWeights);\n}\n\nNetwork::Network(const std::set<Node>&                               aNodes,\n                 const std::set<Link>&                               aLinks,\n                 const std::map<std::string, std::set<std::string>>& aEdges,\n                 const std::set<std::string>&                        aClients)\n    : theMutex()\n    , theNodes()\n    , theLinks()\n    , theElements()\n    , theClients()\n    , theProcessing()\n    , theGraph()\n    , theCloudParams(nullptr)\n    , theCache()\n    , theCentral(nullptr) {\n  // fill theNodes, theLinks, theClients, and theProcessing making sure that\n  // names and numeric identifiers are unique\n  std::set<size_t> myIds;\n  for (const auto& myNode : aNodes) {\n    const auto ret = theNodes.emplace(myNode.name(), myNode);\n    if (not ret.second) {\n      throw std::runtime_error(\"Duplicated node name: \" + myNode.name());\n    }\n    if (not myIds.insert(myNode.id()).second) {\n      throw std::runtime_error(\"Duplicated identifier: \" +\n                               std::to_string(myNode.id()));\n    }\n    assert(ret.first != theNodes.end());\n    if (aClients.count(myNode.name()) > 0) {\n      theClients.emplace_back(&ret.first->second);\n    }\n    if (myNode.type() == Node::Type::Processing) {\n      theProcessing.emplace_back(&ret.first->second);\n    }\n  }\n  for (const auto& myLink : aLinks) {\n    const auto ret = theLinks.emplace(myLink.name(), myLink);\n    if (not ret.second) {\n      throw std::runtime_error(\"Duplicated link name: \" + myLink.name());\n    }\n    if (not myIds.insert(myLink.id()).second) {\n      throw std::runtime_error(\"Duplicated identifier: \" +\n                               std::to_string(myLink.id()));\n    }\n  }\n\n  // make sure all the clients names exist\n  if (theClients.size() != aClients.size()) {\n    std::stringstream myStream;\n    for (const auto& myClient : aClients) {\n      auto myFound = false;\n      for (const auto& myInnerClient : theClients) {\n        if (myInnerClient->name() == myClient) {\n          myFound = true;\n          break;\n        }\n      }\n      if (not myFound) {\n        myStream << ' ' << myClient;\n      }\n    }\n    throw std::runtime_error(\"Invalid clients passed: \" + myStream.str());\n  }\n\n  // create the list of edges (with weights)\n  std::vector<Edge>  myEdges;\n  std::vector<float> myWeights;\n  for (const auto& elem : aEdges) {\n    const auto mySourceId       = id(elem.first);\n    const auto mySourceCapacity = capacity(elem.first);\n    const auto mySourceLatency =\n        mySourceCapacity > 0 ? (2.0f / mySourceCapacity) : 0;\n    for (const auto& myDst : elem.second) {\n      const auto myTargetId       = id(myDst);\n      const auto myTargetCapacity = capacity(myDst);\n\n      // compute the weight as the sum of the half reciprocals of the source\n      // and target, but only if they are links\n      const auto myWeight =\n          mySourceLatency +\n          (myTargetCapacity > 0 ? (2.0f / myTargetCapacity) : 0);\n\n      myEdges.emplace_back(Edge(mySourceId, myTargetId));\n      myWeights.emplace_back(myWeight);\n\n      VLOG(2) << mySourceId << ' ' << myTargetId << ' ' << myWeight;\n    }\n  }\n\n  initElementsGraph(myEdges, myWeights);\n}\n\nvoid Network::initElementsGraph(const std::vector<Edge>&  aEdges,\n                                const std::vector<float>& aWeights) {\n  // fill the nodes/links vector indexed by the identifiers\n  theElements.resize(theNodes.size() + theLinks.size());\n  for (auto& myNode : theNodes) {\n    assert(myNode.second.id() < theElements.size());\n    theElements[myNode.second.id()] = &myNode.second;\n  }\n  for (auto& myLink : theLinks) {\n    assert(myLink.second.id() < theElements.size());\n    theElements[myLink.second.id()] = &myLink.second;\n  }\n  for ([[maybe_unused]] const auto& elem : theElements) {\n    assert(elem != nullptr);\n  }\n\n  // create the network graph\n  theGraph = Graph(aEdges.data(),\n                   aEdges.data() + aEdges.size(),\n                   aWeights.data(),\n                   theNodes.size() + theLinks.size());\n  VLOG(1) << \"Created a network with \" << theNodes.size() << \" nodes and \"\n          << theLinks.size() << \" links\";\n  assert(theElements.size() == boost::num_vertices(theGraph));\n  theCache.resize(theElements.size(), {false, PredVec()});\n\n  // print nodes and links, if verbose\n  for (const auto myElement : theElements) {\n    VLOG(2) << myElement->toString();\n  }\n}\n\nvoid Network::cloud(const double aLatency, const double aRate) {\n  if (aLatency < 0) {\n    throw std::runtime_error(\"the cloud latency (\" + std::to_string(aLatency) +\n                             \") cannot be negative\");\n  }\n  if (aRate <= 0) {\n    throw std::runtime_error(\"the cloud rate (\" + std::to_string(aRate) +\n                             \") cannot be non-positive\");\n  }\n\n  // overwrite previous settings, if any\n  theCloudParams = std::make_unique<CloudParams>(aLatency, aRate);\n}\n\nstd::pair<float, std::string> Network::nextHop(const std::string& aSrc,\n                                               const std::string& aDst) {\n  const auto myDstId      = id(aDst);\n  auto&      myCacheEntry = cacheEntry(myDstId);\n  const auto mySrcId      = id(aSrc);\n  assert(mySrcId < myCacheEntry.second.size());\n\n  const auto& myRet = myCacheEntry.second[mySrcId];\n  assert(myRet.second < theElements.size());\n  assert(theElements[myRet.second] != nullptr);\n  return {myRet.first, theElements[myRet.second]->name()};\n}\n\ndouble\nNetwork::txTime(const Node& aSrc, const Node& aDst, const size_t aBytes) {\n  // short-cut for vanishing amount of data to transfer and self tx\n  if (aBytes == 0 or &aSrc == &aDst) {\n    return 0;\n  }\n\n  const auto& myCacheEntry = cacheEntry(aDst.id());\n  assert(aSrc.id() < myCacheEntry.second.size());\n\n  auto myTxTime = 0.0;\n  auto myCur    = aSrc.id();\n  while (myCacheEntry.second[myCur].second != aDst.id()) {\n    myTxTime += theElements[myCacheEntry.second[myCur].second]->txTime(aBytes);\n    myCur = myCacheEntry.second[myCur].second;\n  }\n\n  return myTxTime;\n}\n\ndouble Network::txTimeCloud(const Node& aNode, const size_t aBytes) const {\n  // short-cut for vanishing amount of data, before even checking if the\n  // cloud parameters have been set\n  if (aBytes == 0) {\n    return 0;\n  }\n\n  if (theCloudParams.get() == nullptr) {\n    throw std::runtime_error(\"Cloud parameters not set\");\n  }\n\n  return theCloudParams->theCloudLatency +\n         (8 * aBytes) / (1e6 * theCloudParams->theCloudRate);\n}\n\nsize_t Network::hops(const Node& aSrc, const Node& aDst) {\n  const auto& myCacheEntry = cacheEntry(aDst.id());\n  assert(aSrc.id() < myCacheEntry.second.size());\n\n  size_t ret   = 0;\n  auto   myCur = aSrc.id();\n  while (myCacheEntry.second[myCur].second != aDst.id()) {\n    const auto myNext = myCacheEntry.second[myCur].second;\n    if (theElements[myNext]->device() == Element::Device::Link) {\n      ret++;\n    }\n    myCur = myNext;\n  }\n  return ret;\n}\n\nNode* Network::central() {\n  if (theCentral != nullptr) {\n    return theCentral;\n  }\n\n  const size_t        N = 1000;\n  std::vector<double> myTxTimes(theProcessing.size());\n  double              myLastWorst = 0;\n  for (const auto myCandidate : theProcessing) {\n    size_t i = 0;\n    for (const auto myTarget : theProcessing) {\n      myTxTimes[i++] = std::max(txTime(*myCandidate, *myTarget, N),\n                                txTime(*myTarget, *myCandidate, N));\n    }\n    const auto myWorst = *std::max_element(myTxTimes.begin(), myTxTimes.end());\n    if (theCentral == nullptr or myWorst < myLastWorst) {\n      myLastWorst = myWorst;\n      theCentral  = myCandidate;\n    }\n  }\n  return theCentral;\n}\n\nsize_t Network::id(const std::string& aName) const {\n  const auto it = theNodes.find(aName);\n  if (it != theNodes.end()) {\n    return it->second.id();\n  }\n  const auto jt = theLinks.find(aName);\n  if (jt != theLinks.end()) {\n    return jt->second.id();\n  }\n  throw std::runtime_error(\"Unknown node with name: \" + aName);\n}\n\nfloat Network::capacity(const std::string& aName) const {\n  const auto it = theNodes.find(aName);\n  if (it != theNodes.end()) {\n    return 0;\n  }\n  const auto jt = theLinks.find(aName);\n  if (jt != theLinks.end()) {\n    return jt->second.capacity();\n  }\n  throw std::runtime_error(\"Unknown node with name: \" + aName);\n}\n\nconst Network::Cache::value_type& Network::cacheEntry(const size_t aDstId) {\n  assert(aDstId < theCache.size());\n\n  auto& myCacheEntry = theCache[aDstId];\n\n  {\n    const std::lock_guard<std::mutex> myLock(theMutex);\n    if (myCacheEntry.first == false) {\n      assert(myCacheEntry.second.size() == 0);\n\n      // create an entry in the cache for this destination\n\n      std::vector<VertexDescriptor> myPred(theCache.size());\n      std::vector<float>            myDist(theCache.size());\n\n      boost::dijkstra_shortest_paths(\n          theGraph,\n          aDstId,\n          boost::predecessor_map(\n              boost::make_iterator_property_map(\n                  myPred.begin(), get(boost::vertex_index, theGraph)))\n              .distance_map(myDist.data()));\n\n      myCacheEntry.first = true;\n      myCacheEntry.second.resize(theCache.size());\n      for (size_t i = 0; i < theCache.size(); i++) {\n        myCacheEntry.second[i] = {myDist[i], myPred[i]};\n      }\n    }\n  }\n\n  return myCacheEntry;\n}\n\nconst Network::Cache::value_type&\nNetwork::cacheEntry(const size_t aDstId) const {\n  assert(aDstId < theCache.size());\n  const auto& myCacheEntry = theCache[aDstId];\n  if (myCacheEntry.first == false) {\n    assert(aDstId < theElements.size());\n    throw std::runtime_error(\n        \"Routing cache entry does not exist for destination: \" +\n        theElements[aDstId]->name());\n  }\n  return myCacheEntry;\n}\n} // namespace statesim\n} // namespace uiiit\n", "meta": {"hexsha": "d4d9f9eaf2a2ecf0cc42a4e2fa36adcfe7a90a59", "size": 15215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "StateSim/network.cpp", "max_stars_repo_name": "Somoshree/serverlessonedge", "max_stars_repo_head_hexsha": "3d8e0dc7867146c9c177f814a3507d027adbb0a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-07-27T08:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T09:17:21.000Z", "max_issues_repo_path": "StateSim/network.cpp", "max_issues_repo_name": "Somoshree/serverlessonedge", "max_issues_repo_head_hexsha": "3d8e0dc7867146c9c177f814a3507d027adbb0a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StateSim/network.cpp", "max_forks_repo_name": "Somoshree/serverlessonedge", "max_forks_repo_head_hexsha": "3d8e0dc7867146c9c177f814a3507d027adbb0a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-23T09:29:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T07:24:19.000Z", "avg_line_length": 32.5802997859, "max_line_length": 80, "alphanum_fraction": 0.6235294118, "num_tokens": 3972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553809087592986, "lm_q2_score": 0.046033901744859135, "lm_q1q2_score": 0.00808070322786271}}
{"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_MAC_POLY1305_FUNCTIONS_HPP\n#define CRYPTO3_MAC_POLY1305_FUNCTIONS_HPP\n\n#include <boost/endian/arithmetic.hpp>\n#include <boost/endian/conversion.hpp>\n\n#include <nil/crypto3/detail/make_uint_t.hpp>\n\n#include <nil/crypto3/mac/detail/poly1305/poly1305_policy.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace mac {\n            namespace detail {\n                struct poly1305_functions : public poly1305_policy {\n                    typedef poly1305_policy policy_type;\n\n                    constexpr static const std::size_t word_bits = policy_type::word_bits;\n                    typedef typename policy_type::word_type word_type;\n\n                    constexpr static const std::size_t key_words = policy_type::key_words;\n                    constexpr static const std::size_t key_bits = policy_type::key_bits;\n                    typedef typename policy_type::key_type key_type;\n\n                    constexpr static const std::size_t key_schedule_bits = policy_type::key_schedule_bits;\n                    constexpr static const std::size_t key_schedule_words = policy_type::key_schedule_words;\n                    typedef typename policy_type::key_schedule_type key_schedule_type;\n\n                    static void poly1305_init(key_schedule_type &X, const key_type &key) {\n                        using namespace nil::crypto3::detail;\n                        /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */\n                        const word_type t0 = boost::endian::native_to_little(\n                            make_uint_t<word_bits>(key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7]));\n                        const word_type t1 = boost::endian::native_to_little(make_uint_t<word_bits>(\n                            key[8], key[9], key[10], key[11], key[12], key[13], key[14], key[15]));\n\n                        X[0] = (t0)&0xffc0fffffff;\n                        X[1] = ((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff;\n                        X[2] = ((t1 >> 24)) & 0x00ffffffc0f;\n\n                        /* h = 0 */\n                        X[3] = 0;\n                        X[4] = 0;\n                        X[5] = 0;\n\n                        /* save pad for later */\n                        X[6] = boost::endian::native_to_little(make_uint_t<word_bits>(\n                            key[16], key[17], key[18], key[19], key[20], key[21], key[22], key[23]));\n                        X[7] = boost::endian::native_to_little(make_uint_t<word_bits>(\n                            key[24], key[25], key[26], key[27], key[28], key[29], key[30], key[31]));\n                    }\n\n                    static void poly1305_blocks(key_schedule_type &X, const uint8_t *m, size_t blocks,\n                                                bool is_final = false) {\n                        const word_type hibit = is_final ? 0 : (static_cast<word_type>(1) << 40); /* 1 << 128 */\n\n                        const word_type r0 = X[0];\n                        const word_type r1 = X[1];\n                        const word_type r2 = X[2];\n\n                        word_type h0 = X[3 + 0];\n                        word_type h1 = X[3 + 1];\n                        word_type h2 = X[3 + 2];\n\n                        const word_type s1 = r1 * (5 << 2);\n                        const word_type s2 = r2 * (5 << 2);\n\n                        while (blocks--) {\n                            /* h += m[i] */\n                            const word_type t0 = load_le<word_type>(m, 0);\n                            const word_type t1 = load_le<word_type>(m, 1);\n\n                            h0 += ((t0)&0xfffffffffff);\n                            h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff);\n                            h2 += (((t1 >> 24)) & 0x3ffffffffff) | hibit;\n\n                            /* h *= r */\n                            uint128_t d0 = uint128_t(h0) * r0 + uint128_t(h1) * s2 + uint128_t(h2) * s1;\n                            uint128_t d1 = uint128_t(h0) * r1 + uint128_t(h1) * r0 + uint128_t(h2) * s2;\n                            uint128_t d2 = uint128_t(h0) * r2 + uint128_t(h1) * r1 + uint128_t(h2) * r0;\n\n                            /* (partial) h %= p */\n                            word_type c = carry_shift(d0, 44);\n                            h0 = d0 & 0xfffffffffff;\n                            d1 += c;\n                            c = carry_shift(d1, 44);\n                            h1 = d1 & 0xfffffffffff;\n                            d2 += c;\n                            c = carry_shift(d2, 42);\n                            h2 = d2 & 0x3ffffffffff;\n                            h0 += c * 5;\n                            c = carry_shift(h0, 44);\n                            h0 = h0 & 0xfffffffffff;\n                            h1 += c;\n\n                            m += 16;\n                        }\n\n                        X[3 + 0] = h0;\n                        X[3 + 1] = h1;\n                        X[3 + 2] = h2;\n                    }\n\n                    static void poly1305_finish(key_schedule_type &X, uint8_t mac[16]) {\n                        /* fully carry h */\n                        word_type h0 = X[3 + 0];\n                        word_type h1 = X[3 + 1];\n                        word_type h2 = X[3 + 2];\n\n                        word_type c;\n                        c = (h1 >> 44);\n                        h1 &= 0xfffffffffff;\n                        h2 += c;\n                        c = (h2 >> 42);\n                        h2 &= 0x3ffffffffff;\n                        h0 += c * 5;\n                        c = (h0 >> 44);\n                        h0 &= 0xfffffffffff;\n                        h1 += c;\n                        c = (h1 >> 44);\n                        h1 &= 0xfffffffffff;\n                        h2 += c;\n                        c = (h2 >> 42);\n                        h2 &= 0x3ffffffffff;\n                        h0 += c * 5;\n                        c = (h0 >> 44);\n                        h0 &= 0xfffffffffff;\n                        h1 += c;\n\n                        /* compute h + -p */\n                        word_type g0 = h0 + 5;\n                        c = (g0 >> 44);\n                        g0 &= 0xfffffffffff;\n                        word_type g1 = h1 + c;\n                        c = (g1 >> 44);\n                        g1 &= 0xfffffffffff;\n                        word_type g2 = h2 + c - (static_cast<word_type>(1) << 42);\n\n                        /* select h if h < p, or h + -p if h >= p */\n                        c = (g2 >> ((sizeof(word_type) * 8) - 1)) - 1;\n                        g0 &= c;\n                        g1 &= c;\n                        g2 &= c;\n                        c = ~c;\n                        h0 = (h0 & c) | g0;\n                        h1 = (h1 & c) | g1;\n                        h2 = (h2 & c) | g2;\n\n                        /* h = (h + pad) */\n                        const word_type t0 = X[6];\n                        const word_type t1 = X[7];\n\n                        h0 += ((t0)&0xfffffffffff);\n                        c = (h0 >> 44);\n                        h0 &= 0xfffffffffff;\n                        h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff) + c;\n                        c = (h1 >> 44);\n                        h1 &= 0xfffffffffff;\n                        h2 += (((t1 >> 24)) & 0x3ffffffffff) + c;\n                        h2 &= 0x3ffffffffff;\n\n                        /* mac = h % (2^128) */\n                        h0 = ((h0) | (h1 << 44));\n                        h1 = ((h1 >> 20) | (h2 << 24));\n\n                        store_le(mac, h0, h1);\n\n                        /* zero out the state */\n                        clear_mem(X.data(), X.size());\n                    }\n                };\n            }    // namespace detail\n        }        // namespace mac\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_POLY1305_FUNCTIONS_HPP\n", "meta": {"hexsha": "813629e67ddf2d1a6db1520983960e32f76035cc", "size": 9206, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/mac/include/nil/crypto3/mac/detail/poly1305/poly1305_functions.hpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "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/mac/include/nil/crypto3/mac/detail/poly1305/poly1305_functions.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T18:20:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T14:26:44.000Z", "max_forks_repo_path": "libs/mac/include/nil/crypto3/mac/detail/poly1305/poly1305_functions.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": 45.5742574257, "max_line_length": 116, "alphanum_fraction": 0.4147295242, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657963619520866, "lm_q2_score": 0.016914912182652234, "lm_q1q2_score": 0.008061302694282305}}
{"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// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2013, 2014.\n// Modifications copyright (c) 2013, 2014, Oracle and/or its affiliates.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_TOUCHES_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_TOUCHES_HPP\n\n\n#include <deque>\n\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/variant_fwd.hpp>\n\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/algorithms/detail/for_each_range.hpp>\n#include <boost/geometry/algorithms/detail/overlay/overlay.hpp>\n#include <boost/geometry/algorithms/detail/overlay/self_turn_points.hpp>\n#include <boost/geometry/algorithms/disjoint.hpp>\n#include <boost/geometry/algorithms/intersects.hpp>\n#include <boost/geometry/algorithms/num_geometries.hpp>\n#include <boost/geometry/algorithms/detail/sub_range.hpp>\n#include <boost/geometry/policies/robustness/no_rescale_policy.hpp>\n\n#include <boost/geometry/algorithms/relate.hpp>\n#include <boost/geometry/algorithms/detail/relate/relate_impl.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace touches\n{\n\n// Box/Box\n\ntemplate\n<\n    std::size_t Dimension,\n    std::size_t DimensionCount\n>\nstruct box_box_loop\n{\n    template <typename Box1, typename Box2>\n    static inline bool apply(Box1 const& b1, Box2 const& b2, bool & touch)\n    {\n        typedef typename coordinate_type<Box1>::type coordinate_type1;\n        typedef typename coordinate_type<Box2>::type coordinate_type2;\n\n        coordinate_type1 const& min1 = get<min_corner, Dimension>(b1);\n        coordinate_type1 const& max1 = get<max_corner, Dimension>(b1);\n        coordinate_type2 const& min2 = get<min_corner, Dimension>(b2);\n        coordinate_type2 const& max2 = get<max_corner, Dimension>(b2);\n\n        // TODO assert or exception?\n        //BOOST_GEOMETRY_ASSERT(min1 <= max1 && min2 <= max2);\n\n        if ( max1 < min2 || max2 < min1 )\n        {\n            return false;\n        }\n\n        if ( max1 == min2 || max2 == min1 )\n        {\n            touch = true;\n        }\n        \n        return box_box_loop\n                <\n                    Dimension + 1,\n                    DimensionCount\n                >::apply(b1, b2, touch);\n    }\n};\n\ntemplate\n<\n    std::size_t DimensionCount\n>\nstruct box_box_loop<DimensionCount, DimensionCount>\n{\n    template <typename Box1, typename Box2>\n    static inline bool apply(Box1 const& , Box2 const&, bool &)\n    {\n        return true;\n    }\n};\n\nstruct box_box\n{\n    template <typename Box1, typename Box2>\n    static inline bool apply(Box1 const& b1, Box2 const& b2)\n    {\n        BOOST_STATIC_ASSERT((geofeatures_boost::is_same\n                                <\n                                    typename geometry::coordinate_system<Box1>::type,\n                                    typename geometry::coordinate_system<Box2>::type\n                                >::value\n                           ));\n        assert_dimension_equal<Box1, Box2>();\n\n        bool touches = false;\n        bool ok = box_box_loop\n                    <\n                        0,\n                        dimension<Box1>::type::value\n                    >::apply(b1, b2, touches);\n\n        return ok && touches;\n    }\n};\n\n// Areal/Areal\n\nstruct areal_interrupt_policy\n{\n    static bool const enabled = true;\n    bool found_touch;\n    bool found_not_touch;\n\n    // dummy variable required by self_get_turn_points::get_turns\n    static bool const has_intersections = false;\n\n    inline bool result()\n    {\n        return found_touch && !found_not_touch;\n    }\n\n    inline areal_interrupt_policy()\n        : found_touch(false), found_not_touch(false)\n    {}\n\n    template <typename Range>\n    inline bool apply(Range const& range)\n    {\n        // if already rejected (temp workaround?)\n        if ( found_not_touch )\n            return true;\n\n        typedef typename geofeatures_boost::range_iterator<Range const>::type iterator;\n        for ( iterator it = geofeatures_boost::begin(range) ; it != geofeatures_boost::end(range) ; ++it )\n        {\n            if ( it->has(overlay::operation_intersection) )\n            {\n                found_not_touch = true;\n                return true;\n            }\n\n            switch(it->method)\n            {\n                case overlay::method_crosses:\n                    found_not_touch = true;\n                    return true;\n                case overlay::method_equal:\n                    // Segment spatially equal means: at the right side\n                    // the polygon internally overlaps. So return false.\n                    found_not_touch = true;\n                    return true;\n                case overlay::method_touch:\n                case overlay::method_touch_interior:\n                case overlay::method_collinear:\n                    if ( ok_for_touch(*it) )\n                    {\n                        found_touch = true;\n                    }\n                    else\n                    {\n                        found_not_touch = true;\n                        return true;\n                    }\n                    break;\n                case overlay::method_none :\n                case overlay::method_disjoint :\n                case overlay::method_error :\n                    break;\n            }\n        }\n\n        return false;\n    }\n\n    template <typename Turn>\n    inline bool ok_for_touch(Turn const& turn)\n    {\n        return turn.both(overlay::operation_union)\n            || turn.both(overlay::operation_blocked)\n            || turn.combination(overlay::operation_union, overlay::operation_blocked)\n            ;\n    }\n};\n\ntemplate<typename Geometry>\nstruct check_each_ring_for_within\n{\n    bool has_within;\n    Geometry const& m_geometry;\n\n    inline check_each_ring_for_within(Geometry const& g)\n        : has_within(false)\n        , m_geometry(g)\n    {}\n\n    template <typename Range>\n    inline void apply(Range const& range)\n    {\n        typename geometry::point_type<Range>::type p;\n        geometry::point_on_border(p, range);\n        if ( !has_within && geometry::within(p, m_geometry) )\n        {\n            has_within = true;\n        }\n    }\n};\n\ntemplate <typename FirstGeometry, typename SecondGeometry>\ninline bool rings_containing(FirstGeometry const& geometry1,\n                SecondGeometry const& geometry2)\n{\n    check_each_ring_for_within<FirstGeometry> checker(geometry1);\n    geometry::detail::for_each_range(geometry2, checker);\n    return checker.has_within;\n}\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct areal_areal\n{\n    static inline\n    bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)\n    {\n        typedef detail::no_rescale_policy rescale_policy_type;\n        typedef typename geometry::point_type<Geometry1>::type point_type;\n        typedef detail::overlay::turn_info\n            <\n                point_type,\n                typename segment_ratio_type<point_type, rescale_policy_type>::type\n            > turn_info;\n\n        std::deque<turn_info> turns;\n        detail::touches::areal_interrupt_policy policy;\n        rescale_policy_type robust_policy;\n        geofeatures_boost::geometry::get_turns\n                <\n                    detail::overlay::do_reverse<geometry::point_order<Geometry1>::value>::value,\n                    detail::overlay::do_reverse<geometry::point_order<Geometry2>::value>::value,\n                    detail::overlay::assign_null_policy\n                >(geometry1, geometry2, robust_policy, turns, policy);\n\n        return policy.result()\n            && ! geometry::detail::touches::rings_containing(geometry1, geometry2)\n            && ! geometry::detail::touches::rings_containing(geometry2, geometry1);\n    }\n};\n\n// P/*\n\nstruct use_point_in_geometry\n{\n    template <typename Point, typename Geometry>\n    static inline bool apply(Point const& point, Geometry const& geometry)\n    {\n        return detail::within::point_in_geometry(point, geometry) == 0;\n    }\n};\n\n}}\n#endif // DOXYGEN_NO_DETAIL\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch {\n\n// TODO: Since CastedTags are used is Reverse needed?\n\ntemplate\n<\n    typename Geometry1, typename Geometry2,\n    typename Tag1 = typename tag<Geometry1>::type,\n    typename Tag2 = typename tag<Geometry2>::type,\n    typename CastedTag1 = typename tag_cast<Tag1, pointlike_tag, linear_tag, areal_tag>::type,\n    typename CastedTag2 = typename tag_cast<Tag2, pointlike_tag, linear_tag, areal_tag>::type,\n    bool Reverse = reverse_dispatch<Geometry1, Geometry2>::type::value\n>\nstruct touches\n    : not_implemented<Tag1, Tag2>\n{};\n\n// If reversal is needed, perform it\ntemplate\n<\n    typename Geometry1, typename Geometry2,\n    typename Tag1, typename Tag2,\n    typename CastedTag1, typename CastedTag2\n>\nstruct touches<Geometry1, Geometry2, Tag1, Tag2, CastedTag1, CastedTag2, true>\n    : touches<Geometry2, Geometry1, Tag2, Tag1, CastedTag2, CastedTag1, false>\n{\n    static inline bool apply(Geometry1 const& g1, Geometry2 const& g2)\n    {\n        return touches<Geometry2, Geometry1>::apply(g2, g1);\n    }\n};\n\n// P/P\n\ntemplate <typename Geometry1, typename Geometry2, typename Tag1, typename Tag2>\nstruct touches<Geometry1, Geometry2, Tag1, Tag2, pointlike_tag, pointlike_tag, false>\n{\n    static inline bool apply(Geometry1 const& , Geometry2 const& )\n    {\n        return false;\n    }\n};\n\n// P/*\n\ntemplate <typename Point, typename Geometry, typename Tag2, typename CastedTag2>\nstruct touches<Point, Geometry, point_tag, Tag2, pointlike_tag, CastedTag2, false>\n    : detail::touches::use_point_in_geometry\n{};\n\n// TODO: support touches(MPt, Linear/Areal)\n\n// Box/Box\n\ntemplate <typename Box1, typename Box2, typename CastedTag1, typename CastedTag2>\nstruct touches<Box1, Box2, box_tag, box_tag, CastedTag1, CastedTag2, false>\n    : detail::touches::box_box\n{};\n\ntemplate <typename Box1, typename Box2>\nstruct touches<Box1, Box2, box_tag, box_tag, areal_tag, areal_tag, false>\n    : detail::touches::box_box\n{};\n\n// L/L\n\ntemplate <typename Linear1, typename Linear2, typename Tag1, typename Tag2>\nstruct touches<Linear1, Linear2, Tag1, Tag2, linear_tag, linear_tag, false>\n    : detail::relate::relate_impl\n    <\n        detail::de9im::static_mask_touches_type,\n        Linear1,\n        Linear2\n    >\n{};\n\n// L/A\n\ntemplate <typename Linear, typename Areal, typename Tag1, typename Tag2>\nstruct touches<Linear, Areal, Tag1, Tag2, linear_tag, areal_tag, false>\n    : detail::relate::relate_impl\n    <\n        detail::de9im::static_mask_touches_type,\n        Linear,\n        Areal\n    >\n{};\n\n// A/L\ntemplate <typename Linear, typename Areal, typename Tag1, typename Tag2>\nstruct touches<Linear, Areal, Tag1, Tag2, linear_tag, areal_tag, true>\n    : detail::relate::relate_impl\n    <\n        detail::de9im::static_mask_touches_type,\n        Areal,\n        Linear\n    >\n{};\n\n// A/A\n\ntemplate <typename Areal1, typename Areal2, typename Tag1, typename Tag2>\nstruct touches<Areal1, Areal2, Tag1, Tag2, areal_tag, areal_tag, false>\n    : detail::touches::areal_areal<Areal1, Areal2>\n{};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct touches\n{\n    static bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)\n    {\n        concept::check<Geometry1 const>();\n        concept::check<Geometry2 const>();\n\n        return dispatch::touches<Geometry1, Geometry2>\n                       ::apply(geometry1, geometry2);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T), typename Geometry2>\nstruct touches<geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2>\n{\n    struct visitor: geofeatures_boost::static_visitor<bool>\n    {\n        Geometry2 const& m_geometry2;\n\n        visitor(Geometry2 const& geometry2): m_geometry2(geometry2) {}\n\n        template <typename Geometry1>\n        bool operator()(Geometry1 const& geometry1) const\n        {\n            return touches<Geometry1, Geometry2>::apply(geometry1, m_geometry2);\n        }\n    };\n\n    static inline bool\n    apply(geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry1,\n          Geometry2 const& geometry2)\n    {\n        return geofeatures_boost::apply_visitor(visitor(geometry2), geometry1);\n    }\n};\n\ntemplate <typename Geometry1, BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct touches<Geometry1, geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    struct visitor: geofeatures_boost::static_visitor<bool>\n    {\n        Geometry1 const& m_geometry1;\n\n        visitor(Geometry1 const& geometry1): m_geometry1(geometry1) {}\n\n        template <typename Geometry2>\n        bool operator()(Geometry2 const& geometry2) const\n        {\n            return touches<Geometry1, Geometry2>::apply(m_geometry1, geometry2);\n        }\n    };\n\n    static inline bool\n    apply(Geometry1 const& geometry1,\n          geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry2)\n    {\n        return geofeatures_boost::apply_visitor(visitor(geometry1), geometry2);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T1),\n          BOOST_VARIANT_ENUM_PARAMS(typename T2)>\nstruct touches<geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)>,\n               geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> >\n{\n    struct visitor: geofeatures_boost::static_visitor<bool>\n    {\n        template <typename Geometry1, typename Geometry2>\n        bool operator()(Geometry1 const& geometry1,\n                        Geometry2 const& geometry2) const\n        {\n            return touches<Geometry1, Geometry2>::apply(geometry1, geometry2);\n        }\n    };\n\n    static inline bool\n    apply(geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const& geometry1,\n          geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const& geometry2)\n    {\n        return geofeatures_boost::apply_visitor(visitor(), geometry1, geometry2);\n    }\n};\n\ntemplate <typename Geometry>\nstruct self_touches\n{\n    static bool apply(Geometry const& geometry)\n    {\n        concept::check<Geometry const>();\n\n        typedef detail::no_rescale_policy rescale_policy_type;\n        typedef typename geometry::point_type<Geometry>::type point_type;\n        typedef detail::overlay::turn_info\n            <\n                point_type,\n                typename segment_ratio_type<point_type, rescale_policy_type>::type\n            > turn_info;\n\n        typedef detail::overlay::get_turn_info\n        <\n            detail::overlay::assign_null_policy\n        > policy_type;\n\n        std::deque<turn_info> turns;\n        detail::touches::areal_interrupt_policy policy;\n        rescale_policy_type robust_policy;\n        detail::self_get_turn_points::get_turns\n        <\n            policy_type\n        >::apply(geometry, robust_policy, turns, policy);\n\n        return policy.result();\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct self_touches<geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    struct visitor: geofeatures_boost::static_visitor<bool>\n    {\n        template <typename Geometry>\n        bool operator()(Geometry const& geometry) const\n        {\n            return self_touches<Geometry>::apply(geometry);\n        }\n    };\n\n    static inline bool\n    apply(geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry)\n    {\n        return geofeatures_boost::apply_visitor(visitor(), geometry);\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\brief \\brief_check{has at least one touching point (self-tangency)}\n\\note This function can be called for one geometry (self-tangency) and\n    also for two geometries (touch)\n\\ingroup touches\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry\n\\return \\return_check{is self-touching}\n\n\\qbk{distinguish,one geometry}\n\\qbk{[def __one_parameter__]}\n\\qbk{[include reference/algorithms/touches.qbk]}\n*/\ntemplate <typename Geometry>\ninline bool touches(Geometry const& geometry)\n{\n    return resolve_variant::self_touches<Geometry>::apply(geometry);\n}\n\n\n/*!\n\\brief \\brief_check2{have at least one touching point (tangent - non overlapping)}\n\\ingroup touches\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\return \\return_check2{touch each other}\n\n\\qbk{distinguish,two geometries}\n\\qbk{[include reference/algorithms/touches.qbk]}\n */\ntemplate <typename Geometry1, typename Geometry2>\ninline bool touches(Geometry1 const& geometry1, Geometry2 const& geometry2)\n{\n    return resolve_variant::touches<Geometry1, Geometry2>::apply(geometry1, geometry2);\n}\n\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_TOUCHES_HPP\n", "meta": {"hexsha": "a18acc805796ba73d29c13985cb5f2aa788ca53e", "size": 17490, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/algorithms/touches.hpp", "max_stars_repo_name": "tonystone/geofeatures", "max_stars_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "boost/boost/geometry/algorithms/touches.hpp", "max_issues_repo_name": "tonystone/geofeatures", "max_issues_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "boost/boost/geometry/algorithms/touches.hpp", "max_forks_repo_name": "tonystone/geofeatures", "max_forks_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 30.3119584055, "max_line_length": 116, "alphanum_fraction": 0.6631217839, "num_tokens": 4044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.0247981592496461, "lm_q1q2_score": 0.008040441058302199}}
{"text": "/* $Id: MannWhitneyRanksum.cpp,v 1.6 2016/02/24 06:27:15 severin Exp $ */\n\n/***\n\nNAME - EEDB::SPStreams::MannWhitneyRanksum\n\nSYNOPSIS\n\nDESCRIPTION\n\n A simple signal procesor which is configured with a minimum expression value\n and which will only pass expressions which are greater than that value\n\nCONTACT\n\nJessica Severin <severin@gsc.riken.jp>\n\nLICENSE\n\n * Software License Agreement (BSD License)\n * ZENBU [eeDB] system\n * copyright (c) 2007-2015 Jessica Severin RIKEN OSC\n * All rights reserved.\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 Jessica Severin RIKEN OSC 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 ''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 COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nAPPENDIX\n\nThe rest of the documentation details each of the object methods. Internal methods are usually preceded with a _\n\n***/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <string.h>\n#include <string>\n#include <stdarg.h>\n#include <rapidxml.hpp>  //rapidxml must be include before boost\n#include <boost/algorithm/string.hpp>\n#include <EEDB/Experiment.h>\n#include <EEDB/Feature.h>\n#include <EEDB/Expression.h>\n#include <EEDB/Symbol.h>\n#include <EEDB/SPStream.h>\n#include <EEDB/SPStreams/MannWhitneyRanksum.h>\n\nusing namespace std;\nusing namespace MQDB;\n\n\nconst char*  EEDB::SPStreams::MannWhitneyRanksum::class_name = \"EEDB::SPStreams::MannWhitneyRanksum\";\n\n//function prototypes\nvoid _spstream_mannwhitney_delete_func(MQDB::DBObject *obj) { \n  delete (EEDB::SPStreams::MannWhitneyRanksum*)obj;\n}\nvoid _spstream_mannwhitney_xml_func(MQDB::DBObject *obj, string &xml_buffer) {\n  ((EEDB::SPStreams::MannWhitneyRanksum*)obj)->_xml(xml_buffer);\n}\nstring _spstream_mannwhitney_display_desc_func(MQDB::DBObject *obj) { \n  return ((EEDB::SPStreams::MannWhitneyRanksum*)obj)->_display_desc();\n}\nMQDB::DBObject* _spstream_mannwhitney_next_in_stream_func(EEDB::SPStream* node) {\n  return ((EEDB::SPStreams::MannWhitneyRanksum*)node)->_next_in_stream();\n}\nbool _spstream_mannwhitney_stream_by_named_region_func(EEDB::SPStream* node, string assembly_name, string chrom_name, long int start, long int end) {\n  return ((EEDB::SPStreams::MannWhitneyRanksum*)node)->_stream_by_named_region(assembly_name, chrom_name, start, end);\n}\n/*\nvoid _spstream_mannwhitney_reset_stream_node_func(EEDB::SPStream* node) {\n  ((EEDB::SPStreams::MannWhitneyRanksum*)node)->_reset_stream_node();\n}\nvoid _spstream_mannwhitney_stream_clear_func(EEDB::SPStream* node) {\n  ((EEDB::SPStreams::MannWhitneyRanksum*)node)->_stream_clear();\n}\nvoid _spstream_mannwhitney_stream_data_sources_func(EEDB::SPStream* node, string classname, string filter_logic) {\n  ((EEDB::SPStreams::MannWhitneyRanksum*)node)->_stream_data_sources(classname, filter_logic);\n}\nvoid _spstream_mannwhitney_reload_stream_data_sources_func(EEDB::SPStream* node) {\n  ((EEDB::SPStreams::MannWhitneyRanksum*)node)->_reload_stream_data_sources();\n}\n*/\n\nEEDB::SPStreams::MannWhitneyRanksum::MannWhitneyRanksum() {\n  init();\n}\n\nEEDB::SPStreams::MannWhitneyRanksum::~MannWhitneyRanksum() {\n}\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::init() {\n  EEDB::SPStream::init();\n  _classname                 = EEDB::SPStreams::MannWhitneyRanksum::class_name;\n  _module_name               = \"MannWhitneyRanksum\";\n  _funcptr_delete            = _spstream_mannwhitney_delete_func;\n  _funcptr_xml               = _spstream_mannwhitney_xml_func;\n  _funcptr_simple_xml        = _spstream_mannwhitney_xml_func;\n  _funcptr_display_desc      = _spstream_mannwhitney_display_desc_func;\n\n  //function pointer code\n  //_funcptr_reset_stream_node           = _spstream_mannwhitney_reset_stream_node_func;\n  //_funcptr_stream_clear                = _spstream_mannwhitney_stream_clear_func;\n  //_funcptr_stream_data_sources         = _spstream_mannwhitney_stream_data_sources_func;\n  //_funcptr_reload_stream_data_sources  = _spstream_mannwhitney_reload_stream_data_sources_func;\n  _funcptr_next_in_stream              = _spstream_mannwhitney_next_in_stream_func;\n  _funcptr_stream_by_named_region      = _spstream_mannwhitney_stream_by_named_region_func;\n\n  //attribute variables\n  _experiment_cache.clear();\n  _experiment_filter.clear();\n  _filter_mdkeys.clear();\n  _min_zscore = 1.6449; //equiv of pvalue 0.05\n}\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::set_mdata_key_filter(string filter) {\n  //space separated list of keys\n  _filter_mdkeys.clear();\n  if(!filter.empty()) {\n    char *str = strdup(filter.c_str());\n    char* tok = strtok(str,\" \\t\\n\");\n    while(tok) {\n      _filter_mdkeys[tok] = true;\n      fprintf(stderr, \"MannWhitneyRanksum::set_mdata_key_filter [%s]\\n\", tok);\n      tok = strtok(NULL,\" \\t\\n\");\n    }\n    free(str);\n  }\n}\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::add_mdata_key_filter(string key) {\n  fprintf(stderr, \"MannWhitneyRanksum::set_mdata_key_filter [%s]\\n\", key.c_str());\n  _filter_mdkeys[key] = true;\n}\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::set_experiment_filter(string filter) {\n  _experiment_filter = filter;\n  _experiment_cache.clear(); //clear the experiment filter cache so it can recalculate\n  //clear _mdgroup_hash\n  map<string, EEDB::MWGroup*>::iterator mdg_it;\n  for(mdg_it = _mdgroup_hash.begin(); mdg_it != _mdgroup_hash.end(); mdg_it++) {\n    EEDB::MWGroup *mdgroup = (*mdg_it).second;\n    mdgroup->release();\n  }\n  _mdgroup_hash.clear();\n}\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::set_min_zscore(double value) {\n  _min_zscore = fabs(value);\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  creation from XML section\n//\n////////////////////////////////////////////////////////////////////////////\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::_xml(string &xml_buffer) {\n  _xml_start(xml_buffer);  //from SPStream superclass\n  char strbuf[256];\n\n  snprintf(strbuf, 256, \"<min_zscore>%1.6f</min_zscore>\", _min_zscore);\n  xml_buffer += strbuf;\n  \n  if(!_experiment_filter.empty()) {\n    xml_buffer += \"<experiment_filter>\" + _experiment_filter + \"</experiment_filter>\";\n  }\n\n  if(!_filter_mdkeys.empty()) {\n    xml_buffer += \"<mdata_keys_filter>\";\n    map<string,bool>::iterator it1;\n    for(it1=_filter_mdkeys.begin(); it1!=_filter_mdkeys.end(); it1++) {\n      xml_buffer += (*it1).first+\" \";\n    }\n    xml_buffer += \"</mdata_keys_filter>\";\n  }\n  \n  _xml_end(xml_buffer);  //from superclass\n}\n\n\nstring EEDB::SPStreams::MannWhitneyRanksum::mdgroup_xml() {\n  string xml_buffer;\n  char   strbuf[1024];\n  \n  snprintf(strbuf, 1024, \"<metadata_groups count=\\\"%ld\\\">\\n\", _mdgroup_hash.size());\n  xml_buffer = strbuf;\n\n  map<string, EEDB::MWGroup*>::iterator mdg_it;\n  for(mdg_it = _mdgroup_hash.begin(); mdg_it != _mdgroup_hash.end(); mdg_it++) {\n    EEDB::MWGroup *mdgroup = (*mdg_it).second;\n    mdgroup->xml(xml_buffer);\n  }\n  xml_buffer += \"/<metadata_groups>\\n\";\n  return xml_buffer;\n}\n\n\nbool _mannwhit_mwgroup_sort_func (EEDB::MWGroup *a, EEDB::MWGroup *b) {\n  if(a == NULL) { return false; }  //a is NULL, so pick b\n  if(b == NULL) { return true; }   //b is NULL, so pick a\n  \n  if(a->avg_zscore() < b->avg_zscore()) { return false; }\n  if(a->avg_zscore() > b->avg_zscore()) { return true; }\n  \n  if(a->abundance_count < b->abundance_count) { return false; }\n  if(a->abundance_count > b->abundance_count) { return true; }\n  \n  return false;\n}\n\n\nvector<EEDB::MWGroup*>  EEDB::SPStreams::MannWhitneyRanksum::mdgroups() {\n  vector<EEDB::MWGroup*> mwgroup_array;\n\n  \n  map<string, EEDB::MWGroup*>::iterator mdg_it;\n  for(mdg_it = _mdgroup_hash.begin(); mdg_it != _mdgroup_hash.end(); mdg_it++) {\n    mwgroup_array.push_back((*mdg_it).second);\n  }\n  std::sort(mwgroup_array.begin(), mwgroup_array.end(), _mannwhit_mwgroup_sort_func);\n  \n  return mwgroup_array;\n}\n\n\nEEDB::SPStreams::MannWhitneyRanksum::MannWhitneyRanksum(void *xml_node) {\n  //constructor using a rapidxml <spstream> description\n  init();\n  if(xml_node==NULL) { return; }\n  \n  rapidxml::xml_node<>      *root_node = (rapidxml::xml_node<>*)xml_node;\n  rapidxml::xml_node<>      *node;\n\n  if(string(root_node->name()) != \"spstream\") { return; }\n\n  if((node = root_node->first_node(\"min_zscore\")) != NULL) {\n    _min_zscore = strtod(node->value(), NULL);\n  }\n  if((node = root_node->first_node(\"experiment_filter\")) != NULL) {\n    _experiment_filter = node->value();\n  }\n  if((node = root_node->first_node(\"mdata_keys_filter\")) != NULL) {\n    set_mdata_key_filter(node->value());\n  }\n}\n\nstring EEDB::SPStreams::MannWhitneyRanksum::_display_desc() {\n  return \"MannWhitneyRanksum\";\n}\n\n////////////////////////////////////////////////////////////////////////////\n//\n// callback methods \n//\n////////////////////////////////////////////////////////////////////////////\n\n/*\nvoid EEDB::SPStreams::MannWhitneyRanksum::_stream_clear() {\n  //re-initialize the stream-stack back to a clear/empty state\n  if(source_stream() != NULL) { source_stream()->stream_clear(); }\n  \n  EEDB::SPStream::_reset_stream_node();\n  fprintf(stderr, \"MannWhitneyRanksum::_stream_clear\\n\");\n  \n  _region_start = -1;\n  _region_end   = -1;\n}\n\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::_reset_stream_node() {\n  EEDB::SPStream::_reset_stream_node();\n  fprintf(stderr, \"MannWhitneyRanksum::_reset_stream_node\\n\");\n\n  _region_start = -1;\n  _region_end   = -1;\n}\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::_stream_data_sources(string classname, string filter_logic) {\n  fprintf(stderr, \"MannWhitneyRanksum::_stream_data_sources\\n\");\n}\n\nvoid EEDB::SPStreams::MannWhitneyRanksum::_reload_stream_data_sources() {\n  fprintf(stderr, \"MannWhitneyRanksum::_reload_stream_data_sources\\n\");\n}\n*/\n\n\nbool EEDB::SPStreams::MannWhitneyRanksum::_stream_by_named_region(string assembly_name, string chrom_name, long int start, long int end) {\n  _region_start = start;\n  _region_end   = end;\n  \n  fprintf(stderr,\"MannWhitneyRanksum::_stream_by_named_region[%ld] %s %s %ld .. %ld\\n\", (long)this, assembly_name.c_str(), chrom_name.c_str(), start, end);\n  \n  loadprep_experiment_metadata();\n\n  return source_stream()->stream_by_named_region(assembly_name, chrom_name, start, end);\n}\n\n\nMQDB::DBObject* EEDB::SPStreams::MannWhitneyRanksum::_next_in_stream() {\n  if(_source_stream == NULL) { return NULL; }\n\n  MQDB::DBObject *obj = _source_stream->next_in_stream();\n  if(obj == NULL) { return NULL; }\n\n  if(obj->classname() == EEDB::Feature::class_name) {\n    EEDB::Feature *feature = (EEDB::Feature*)obj;\n    analyze_feature(feature);\n  }\n  \n  //everything else is just passed through\n  return obj;\n}\n\n\n////////////////////////////////////////////////////////////////////////////\n//\n// MannWhitney ranksum analysis methods\n//\n////////////////////////////////////////////////////////////////////////////\n\n\nbool _mw_expression_rank_sort_func (EEDB::Expression *a, EEDB::Expression *b) {\n  // < function\n  if(a == NULL) { return false; }  //a is NULL, so pick b\n  if(b == NULL) { return true; }   //b is NULL, so pick a\n  \n  if(a->value() < b->value()) { return true; }\n  if(a->value() > b->value()) { return false; }\n  \n  return false;\n}\n\n\nbool EEDB::SPStreams::MannWhitneyRanksum::loadprep_experiment_metadata() {\n  if(!_experiment_cache.empty()) { return true; }\n\n  struct timeval       starttime, endtime, time_diff;\n  gettimeofday(&starttime, NULL);\n  \n  //make sure variables are clear\n  _experiment_cache.clear();   // [srcID] = experiment :: to keep cache of all experiments\n  _keyval_mdata.clear();       // [key::value] = mdata\n  _keyval_enrichment.clear();  // [key::value] = double :: pvalue stat\n  _keyval_experiment.clear();  // [key::value][expid] = bool :: mdata present in experiment\n\n  EEDB::SPStream  *stream = source_stream();\n    \n  if(!_experiment_filter.empty()) {\n    stream->stream_data_sources(\"Experiment\", _experiment_filter);\n  } else {\n    stream->stream_data_sources(\"Experiment\");\n  }\n    \n  long sources_count=0;\n  while(EEDB::Experiment *source = (EEDB::Experiment*)stream->next_in_stream()) {\n    if(source->classname() != EEDB::Experiment::class_name) { continue; }\n    \n    source->metadataset()->remove_duplicates();\n    sources_count++;\n    vector<EEDB::Metadata*> mdlist = source->metadataset()->metadata_list();\n    for(unsigned int i=0; i<mdlist.size(); i++) {\n      EEDB::Metadata *md = mdlist[i];\n      string key = md->type();\n      if(key==\"keyword\") { continue; }\n      if(!_filter_mdkeys.empty() && (_filter_mdkeys.find(key)==_filter_mdkeys.end())) { continue; }\n      \n      string value = md->data();\n      //boost::algorithm::to_lower(value);\n      string keyval = key+\"::\"+value;\n      \n      source->retain();\n      _experiment_cache[source->db_id()] = source;\n      _keyval_mdata[keyval] = md;\n      _keyval_enrichment[keyval] = 0;\n      _keyval_experiment[keyval][source->db_id()] = true;\n      \n      EEDB::DataSource::add_to_sources_cache(source);\n    }\n  }\n  fprintf(stderr,\"MannWhitneyRanksum::loadprep_experiment_metadata exps=%ld %ld  mdkeyvals=%ld\\n\",\n          sources_count, _experiment_cache.size(), _keyval_mdata.size());\n  \n  //create unique experiment-groups based on source_id-list\n  //loop on each metadata and generate a unique id-list to hash into a group\n  map<string, EEDB::Metadata*>::iterator  md_it1;\n  //fprintf(stderr, \"ranksum %ld keyval_metadata\\n\", _keyval_mdata.size());\n  for(md_it1 = _keyval_mdata.begin(); md_it1 != _keyval_mdata.end(); md_it1++) {\n    EEDB::Metadata *mdata  = (*md_it1).second;\n    string          keyval = (*md_it1).first;\n    \n    map<string, map<string, bool> >::iterator it7;\n    it7 = _keyval_experiment.find(keyval);\n    \n    list<string> src_ids;\n    map<string, EEDB::Experiment*>::iterator it4;\n    for(it4=_experiment_cache.begin(); it4!=_experiment_cache.end(); it4++) {\n      EEDB::Experiment *exp = (*it4).second;\n      if((*it7).second[exp->db_id()]) {  //present\n        src_ids.push_back(exp->db_id());\n      }\n    }\n    if(src_ids.size() < 2) { continue; } //group need at least 2 experiments\n    if(sources_count - src_ids.size() < 2) { continue; } //need at least 2 experiments in out-group\n    \n    //make unique src_id_key\n    src_ids.sort();  //sort just to make sure it is unique reproducible\n    string src_id_key;\n    list<string>::iterator s_it;\n    for(s_it=src_ids.begin(); s_it!=src_ids.end(); s_it++) {\n      src_id_key += (*s_it);\n    }\n    //create mdgroup if missing or add new metadata if exists\n    if(_mdgroup_hash.find(src_id_key) == _mdgroup_hash.end()) {\n      //first time\n      EEDB::MWGroup *mdgroup = new EEDB::MWGroup();\n      mdgroup->src_id_key = src_id_key;\n      mdgroup->add_metadata(mdata);\n      for(s_it=src_ids.begin(); s_it!=src_ids.end(); s_it++) {\n        mdgroup->add_experiment_id(*s_it);\n      }\n      mdgroup->retain();\n      _mdgroup_hash[src_id_key] = mdgroup;\n    } else {\n      //append\n      EEDB::MWGroup *mdgroup = (EEDB::MWGroup*)_mdgroup_hash[src_id_key];\n      mdgroup->add_metadata(mdata);\n    }\n  }\n  fprintf(stderr, \"  %ld src_id_key groups\\n\", _mdgroup_hash.size());\n\n  gettimeofday(&endtime, NULL);\n  timersub(&endtime, &starttime, &time_diff);\n  double   runtime  = (double)time_diff.tv_sec*1000.0 + ((double)time_diff.tv_usec)/1000.0;\n  fprintf(stderr, \"loadprep_experiment_metadata %1.3f msec\\n\", runtime);\n  return true;\n}\n\n      \nbool EEDB::SPStreams::MannWhitneyRanksum::analyze_feature(EEDB::Feature *feature) {\n  struct timeval       starttime, endtime, time_diff;\n\n  _debug=false;\n\n  if(!feature) { return false; }\n  gettimeofday(&starttime, NULL);\n\n  if(_debug) { fprintf(stderr, \"\\n\\nMannWhitneyRanksum::analyze_feature :: %s\", feature->simple_xml().c_str()); }\n  \n  //fill in all the missing experiments to convert the sparse-matrix to a full-matrix\n  vector<EEDB::Expression*>  feat_exp_array = feature->expression_array();\n  vector<EEDB::Expression*>  express_array; //final array for analysis\n\n  if(_debug) { fprintf(stderr, \"%ld filtered experiments in cache\\n\", _experiment_cache.size()); }\n  if(_debug) { fprintf(stderr, \"%ld feature expressions\\n\", feat_exp_array.size()); }\n  \n  //first place the expression which matches the known/filtered experiments into express_hash\n  map<string, EEDB::Expression*>  express_hash;   //experiment srcID to expression, fill in the missing\n  EEDB::Datatype *dtype = NULL;\n  for(unsigned i=0; i<feat_exp_array.size(); i++) {\n    EEDB::Expression *expr = feat_exp_array[i];\n    if(_experiment_cache.find(expr->experiment_dbid()) != _experiment_cache.end()) {\n      express_hash[expr->experiment_dbid()] = expr;\n      dtype = expr->datatype();\n    }\n  }\n  if(_debug) { fprintf(stderr, \"  %ld expression match the experiment filter\\n\", express_hash.size()); }\n  \n  //second fill in the missing expression with zero values\n  map<string, EEDB::Experiment*>::iterator it4;\n  for(it4=_experiment_cache.begin(); it4!=_experiment_cache.end(); it4++) {\n    EEDB::Experiment *experiment = (*it4).second;\n    if(express_hash.find(experiment->db_id()) == express_hash.end()) {\n      //missing Expression\n      EEDB::Expression *expr2 = EEDB::Expression::realloc();\n      expr2->experiment(experiment);\n      expr2->datatype(dtype);\n      expr2->value(0);\n      expr2->sig_error(0);\n      express_hash[experiment->db_id()] = expr2;\n    }\n  }\n  if(_debug) { fprintf(stderr, \"  %ld after fill in\\n\",express_hash.size()); }\n  \n  //third covert express_hash to express_array\n  map<string, EEDB::Expression*>::iterator it5;\n  for(it5=express_hash.begin(); it5!=express_hash.end(); it5++) {\n    EEDB::Expression *express = (*it5).second;\n    express_array.push_back(express);\n  }\n  \n  //ranksum sort the expression array and asign the rank number\n  std::sort(express_array.begin(), express_array.end(), _mw_expression_rank_sort_func);\n  \n  unsigned pos=0;\n  while(pos<express_array.size()) {\n    express_array[pos]->sig_error(pos+1);\n    \n    unsigned pos2 = pos;\n    double sumrank=pos+1;\n    while((pos2+1<express_array.size()) &&\n          (express_array[pos]->value() == express_array[pos2+1]->value())) {\n      sumrank += (pos2+1)+1;\n      pos2++;\n    }\n    if(pos != pos2) {  //duplicates\n      sumrank = sumrank / (pos2-pos+1);\n      for(unsigned i=pos; i<=pos2; i++) {\n        express_array[i]->sig_error(sumrank);\n      }\n      pos = pos2;\n    }\n    pos++;\n  }\n  //rank stored in the ->sig_error()\n  \n  \n  //loop on each mdgroup, foreach mdgroup check all expression/experiments to match\n  //calc rank-sum statistic for each metadata\n  long mdcount=0;\n  map<string, EEDB::MWGroup*>::iterator mdg_it;\n  for(mdg_it = _mdgroup_hash.begin(); mdg_it != _mdgroup_hash.end(); mdg_it++) {\n    EEDB::MWGroup *mdgroup = (*mdg_it).second;\n    mdgroup->reset_stats();\n\n    long group_count = 0;\n    long other_count = 0;\n    //calculate the ranksums\n    double group_sum=0.0, other_sum=0.0, totalRank=0.0;\n    double group_mean=0.0, other_mean=0.0;\n    vector<EEDB::Expression*>::iterator it6;\n    for(it6=express_array.begin(); it6!=express_array.end(); it6++) {\n      EEDB::Expression *expr = (*it6);\n      \n      if(mdgroup->has_experiment_id(expr->experiment_dbid())) {\n        group_sum += expr->sig_error();\n        group_count++;\n        //group_mean += log(expr->value());\n        group_mean += expr->value();\n      } else {\n        other_sum += expr->sig_error();\n        other_count++;\n        //other_mean += log(expr->value());\n        other_mean += expr->value();\n      }\n      totalRank += expr->sig_error();\n\n    }\n    mdgroup->other_count = other_count;\n    mdgroup->group_count = group_count;\n    mdgroup->other_sum   = other_sum;\n    mdgroup->group_sum   = group_sum;\n\n    if(group_count < 2) { continue; } //need at least 2 experiments\n    if(other_count < 2) { continue; } //need at least 2 experiments in out-group\n    \n    group_mean /= group_count;\n    other_mean /= other_count;\n    \n    //calc the wilcoxon-mann-whitney u-test\n    //redo from https://epilab.ich.ucl.ac.uk/coursematerial/statistics/non_parametric/wilcox_mann_whitney.html\n    \n    double n1 = group_count;\n    double n2 = other_count;\n    \n    double u1 = group_sum - ((n1 * (n1+1)) / 2.0);\n    //double u2 = other_sum - ((n2 * (n2+1)) / 2.0);\n    \n    //double Uobt= 0.0;\n    //if(u1<u2) { Uobt = u1; } else { Uobt = u2; }\n    double Uobt= u1;  //if I want to preserve the directionality, just use U1\n    \n    double oa = sqrt(n1*n2*(n1+n2+1)/12);\n    \n    double zscore = (Uobt -  (n1 * n2 / 2)) / oa;\n    \n    /*\n     if(group_count < other_count) {\n     na = group_count;\n     wa = group_sum;\n     nb = other_count;\n     } else {\n     na = other_count;\n     wa = other_sum;\n     nb = group_count;\n     }\n     \n     double ua = na * (na + nb + 1) / 2;\n     double oa = sqrt(na*nb*(na+nb+1)/12);\n     \n     double zscore = (wa-ua) / oa;\n     */\n    \n    //TODO: need to do table lookup for when either n1 or n2 is less than 20\n    \n    //TODO: need to do zscore to pvalue calc/lookup\n    double pvalue = zscore;\n\n    mdgroup->zscore = zscore;\n    mdgroup->pvalue = pvalue;\n\n    //fprintf(stderr, \"ok6\\n\");\n    //fprintf(stderr, \"%s\", mdgroup->simple_xml().c_str());\n\n    if(fabs(zscore)>_min_zscore) {\n      if(_debug) {\n        fprintf(stderr, \"%s\", mdgroup->simple_xml().c_str());\n        fprintf(stderr, \"SIGNIFICANT!!!!!\\n\");\n      }\n      mdcount++;\n      \n      mdgroup->other_count = other_count;\n      mdgroup->group_count = group_count;\n      mdgroup->other_sum = other_sum;\n      mdgroup->group_sum = group_sum;\n      mdgroup->zscore = zscore;\n      mdgroup->pvalue = pvalue;\n      mdgroup->abundance_count++;\n      mdgroup->abundance_zscores.push_back(zscore);\n\n      mdgroup->retain();\n      feature->metadataset()->add_metadata(mdgroup);\n    }\n    /*\n     EEDB::MetadataSet *mdset = experiment->metadataset();\n     if(mdset->find_metadata(mdata->type(), mdata->data())) {\n     _keyval_enrichment[keyval]++;\n     }\n     */\n  }\n  if(_debug) { \n    gettimeofday(&endtime, NULL);\n    timersub(&endtime, &starttime, &time_diff);\n    double   runtime  = (double)time_diff.tv_sec*1000.0 + ((double)time_diff.tv_usec)/1000.0;\n    fprintf(stderr, \"found %ld significant mann whitney groups - %1.3f msec\\n\", mdcount, runtime);\n  }\n\n  return true;\n}\n\n\n////////////////////////////////////////////////////////////////////////////\n//\n// MWGroup section\n//\n////////////////////////////////////////////////////////////////////////////\n\nconst char*  EEDB::MWGroup::class_name = \"EEDB::MWGroup\";\n\n//function prototypes\nvoid _spstream_mwgroup_delete_func(MQDB::DBObject *obj) {\n  delete (EEDB::MWGroup*)obj;\n}\nvoid _spstream_mwgroup_xml_func(MQDB::DBObject *obj, string &xml_buffer) {\n  ((EEDB::MWGroup*)obj)->_xml(xml_buffer);\n}\nvoid _spstream_mwgroup_simple_xml_func(MQDB::DBObject *obj, string &xml_buffer) {\n  ((EEDB::MWGroup*)obj)->_simple_xml(xml_buffer);\n}\n\nEEDB::MWGroup::MWGroup() {\n  init();\n}\n\nEEDB::MWGroup::~MWGroup() {\n  fprintf(stderr, \"mwgroup delete\\n\");\n}\n\nvoid EEDB::MWGroup::init() {\n  EEDB::Metadata::init();\n  _classname                 = EEDB::MWGroup::class_name;\n  _funcptr_delete            = _spstream_mwgroup_delete_func;\n  _funcptr_xml               = _spstream_mwgroup_xml_func;\n  _funcptr_simple_xml        = _spstream_mwgroup_simple_xml_func;\n  \n  //attribute variables\n  _exp_id_hash.clear();\n  src_id_key.clear();\n  _mdata_list.clear();\n  \n  other_count = 0;\n  group_count = 0;\n  other_sum = 0.0;\n  group_sum = 0.0;\n  zscore = 0.0;\n  pvalue = 0.0;\n  abundance_count = 0;\n}\n\nvoid EEDB::MWGroup::reset_stats() {\n  other_count = 0;\n  group_count = 0;\n  other_sum = 0.0;\n  group_sum = 0.0;\n  zscore = 0.0;\n  pvalue = 0.0;\n}\n\nbool EEDB::MWGroup::has_experiment_id(string value) {\n  if(_exp_id_hash.find(value) == _exp_id_hash.end()) { return false; }\n  return _exp_id_hash[value];\n}\n\nvoid EEDB::MWGroup::add_experiment_id(string value) {\n  _exp_id_hash[value] = true;\n}\n\nvoid  EEDB::MWGroup::add_metadata(EEDB::Metadata *mdata) {\n  if(!mdata) { return; }\n  if(_mdata_list.empty()) {\n    //set type/data to the first element in the group\n    _type = mdata->type();\n    _data = mdata->data();\n  }\n  _mdata_list.push_back(mdata);\n}\n\n\nvoid EEDB::MWGroup::_simple_xml(string &xml_buffer) {\n  if(_mdata_list.empty()) { return; }\n  \n  char strbuf[8192];\n  EEDB::Metadata *mdata  = _mdata_list.front();\n  \n  long src_count=0;\n  map<string,bool>::iterator it2;\n  for(it2=_exp_id_hash.begin(); it2!=_exp_id_hash.end(); it2++) {\n    if((*it2).second) { src_count++; }\n  }\n  \n  snprintf(strbuf, 8192,\n           \"<mdgroup type=\\\"%s\\\" value=\\\"%s\\\" source_count=\\\"%ld\\\" other_count=\\\"%ld\\\" group_count=\\\"%ld\\\" other_ranksum=\\\"%f\\\" group_ranksum=\\\"%f\\\" zscore=\\\"%f\\\" pvalue=\\\"%f\\\" >\",\n           html_escape(mdata->type()).c_str(), html_escape(mdata->data()).c_str(),\n           src_count, other_count, group_count, other_sum, group_sum, zscore, pvalue);\n  xml_buffer += strbuf;\n  xml_buffer += \"</mdgroup>\\n\";\n}\n\nvoid EEDB::MWGroup::_xml(string &xml_buffer) {\n  if(_mdata_list.empty()) { return; }\n  \n  char strbuf[8192];\n  EEDB::Metadata *mdata  = _mdata_list.front();\n\n  long src_count=0;\n  map<string,bool>::iterator it2;\n  for(it2=_exp_id_hash.begin(); it2!=_exp_id_hash.end(); it2++) {\n    if((*it2).second) { src_count++; }\n  }\n  \n  snprintf(strbuf, 8192,\n          \"<mdgroup type=\\\"%s\\\" value=\\\"%s\\\" source_count=\\\"%ld\\\" other_count=\\\"%ld\\\" group_count=\\\"%ld\\\" other_ranksum=\\\"%f\\\" group_ranksum=\\\"%f\\\" zscore=\\\"%f\\\" pvalue=\\\"%f\\\" >\",\n           html_escape(mdata->type()).c_str(), html_escape(mdata->data()).c_str(),\n           src_count, other_count, group_count, other_sum, group_sum, zscore, pvalue);\n  xml_buffer += strbuf;\n\n  //_exp_id_hash to get unique source ids in this group\n  for(it2=_exp_id_hash.begin(); it2!=_exp_id_hash.end(); it2++) {\n    if((*it2).second) { xml_buffer += \"<datasource id=\\\"\" + (*it2).first + \"\\\"/>\"; }\n  }\n  \n  //individual metadata which share exact same experiment group\n  list<EEDB::Metadata*>::iterator s_it;\n  for(s_it=_mdata_list.begin(); s_it!=_mdata_list.end(); s_it++) {\n    (*s_it)->xml(xml_buffer);\n  }\n  xml_buffer += \"</mdgroup>\\n\";\n}\n\nEEDB::MWGroup::MWGroup(void *xml_node) {\n  //constructor using a rapidxml <spstream> description\n  init();\n  if(xml_node==NULL) { return; }\n  \n  rapidxml::xml_node<>      *root_node = (rapidxml::xml_node<>*)xml_node;\n  //rapidxml::xml_node<>      *node;\n  \n  //TODO: need to do this to store/retrieve finished results from ZDX\n  \n  if(string(root_node->name()) != \"spstream\") { return; }\n}\n\n\nEEDB::MWGroup* EEDB::MWGroup::copy() {\n  EEDB::MWGroup *t_copy = new EEDB::MWGroup();\n  t_copy->src_id_key = src_id_key;\n  t_copy->other_count = other_count;\n  t_copy->group_count = group_count;\n  t_copy->other_sum = other_sum;\n  t_copy->group_sum = group_sum;\n  t_copy->zscore = zscore;\n  t_copy->pvalue = pvalue;\n  t_copy->abundance_count = abundance_count;\n  \n  t_copy->abundance_zscores = abundance_zscores;\n  t_copy->_mdata_list = _mdata_list;\n  t_copy->_exp_id_hash = _exp_id_hash;\n  return t_copy;\n}\n\ndouble  EEDB::MWGroup::avg_zscore() {\n  double sum=0;\n  for(unsigned i=0; i<abundance_zscores.size(); i++) {\n    sum += fabs(abundance_zscores[i]);\n  }\n  return sum/abundance_zscores.size();\n}\n\ndouble  EEDB::MWGroup::max_zscore() {\n  double max=0;\n  for(unsigned i=0; i<abundance_zscores.size(); i++) {\n    if(fabs(abundance_zscores[i]) > fabs(max)) { max = abundance_zscores[i]; }\n  }\n  return max;\n}\n\n\n\n\n", "meta": {"hexsha": "f35d859fb76e4008278a16850eb12134f7cd292b", "size": 28422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/EEDB/SPStreams/MannWhitneyRanksum.cpp", "max_stars_repo_name": "jessica-severin/ZENBU_2.11.1", "max_stars_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "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": "c++/EEDB/SPStreams/MannWhitneyRanksum.cpp", "max_issues_repo_name": "jessica-severin/ZENBU_2.11.1", "max_issues_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "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": "c++/EEDB/SPStreams/MannWhitneyRanksum.cpp", "max_forks_repo_name": "jessica-severin/ZENBU_2.11.1", "max_forks_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7153024911, "max_line_length": 180, "alphanum_fraction": 0.6642389698, "num_tokens": 8056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567817320044, "lm_q2_score": 0.028870904021761658, "lm_q1q2_score": 0.008033524838788981}}
{"text": "/* \n * Python bindings for libroom\n * Copyright (C) 2019  Robin Scheibler, Cyril Cadoux\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#include <string>\n#include <vector>\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/stl.h>\n#include <Eigen/Dense>\n\n#include \"common.hpp\"\n#include \"geometry.hpp\"\n#include \"microphone.hpp\"\n#include \"wall.hpp\"\n#include \"room.hpp\"\n\nnamespace py = pybind11;\n\nfloat libroom_eps = 1e-4;  // epsilon is set to 0.1 millimeter (100 um)\n\n\nPYBIND11_MODULE(libroom, m) {\n  m.doc() = \"Libroom room simulation extension plugin\"; // optional module docstring\n\n  // The 3D Room class\n  py::class_<Room<3>>(m, \"Room\")\n    .def(py::init<\n        const std::vector<Wall<3>> &,\n        const std::vector<int> &,\n        const std::vector<Microphone<3>> &,\n        float, int, float, float, float, float, bool\n        >())\n    .def(py::init<\n        const Vectorf<3> &,\n        const Eigen::Array<float,Eigen::Dynamic,6> &,\n        const Eigen::Array<float,Eigen::Dynamic,6> &,\n        const std::vector<Microphone<3>> &,\n        float, int, float, float, float, float, bool\n        >())\n    .def(\"set_params\", &Room<3>::set_params)\n    .def(\"add_mic\", &Room<3>::add_mic)\n    .def(\"reset_mics\", &Room<3>::reset_mics)\n    .def(\"image_source_model\", &Room<3>::image_source_model)\n    .def(\"get_wall\", &Room<3>::get_wall)\n    .def(\"get_max_distance\", &Room<3>::get_max_distance)\n    .def(\"next_wall_hit\", &Room<3>::next_wall_hit)\n    .def(\"scat_ray\", &Room<3>::scat_ray)\n    .def(\"simul_ray\", &Room<3>::simul_ray)\n    .def(\"ray_tracing\",\n        (void (Room<3>::*)(\n                             const Eigen::Matrix<float,2,Eigen::Dynamic> &angles,\n                             const Vectorf<3> source_pos\n                             )\n        )\n        &Room<3>::ray_tracing)\n    .def(\"ray_tracing\",\n        (void (Room<3>::*)(\n                             size_t nb_phis,\n                             size_t nb_thetas,\n                             const Vectorf<3> source_pos\n                             )\n        )\n        &Room<3>::ray_tracing)\n    .def(\"ray_tracing\",\n        (void (Room<3>::*)(\n                             size_t nb_rays,\n                             const Vectorf<3> source_pos\n                             )\n        )\n        &Room<3>::ray_tracing)\n    .def(\"contains\", &Room<3>::contains)\n    .def_property(\"is_hybrid_sim\", &Room<3>::get_is_hybrid_sim, &Room<3>::set_is_hybrid_sim)\n    .def_property_readonly_static(\"dim\", [](py::object /* self */) { return 3; })\n    .def_readonly(\"walls\", &Room<3>::walls)\n    .def_readonly(\"sources\", &Room<3>::sources)\n    .def_readonly(\"orders\", &Room<3>::orders)\n    .def_readonly(\"attenuations\", &Room<3>::attenuations)\n    .def_readonly(\"gen_walls\", &Room<3>::gen_walls)\n    .def_readonly(\"visible_mics\", &Room<3>::visible_mics)\n    .def_readonly(\"walls\", &Room<3>::walls)\n    .def_readonly(\"obstructing_walls\", &Room<3>::obstructing_walls)\n    .def_readonly(\"microphones\", &Room<3>::microphones)\n    .def_readonly(\"max_dist\", &Room<3>::max_dist)\n    ;\n\n  // The 2D Room class\n  py::class_<Room<2>>(m, \"Room2D\")\n    //.def(py::init<py::list, py::list, const Eigen::MatrixXf &>())\n    .def(py::init<\n        const std::vector<Wall<2>> &,\n        const std::vector<int> &,\n        const std::vector<Microphone<2>> &,\n        float, int, float, float, float, float, bool\n        >())\n    .def(py::init<\n        const Vectorf<2> &,\n        const Eigen::Array<float,Eigen::Dynamic,4> &,\n        const Eigen::Array<float,Eigen::Dynamic,4> &,\n        const std::vector<Microphone<2>> &,\n        float, int, float, float, float, float, bool\n        >())\n    .def(\"set_params\", &Room<2>::set_params)\n    .def(\"add_mic\", &Room<2>::add_mic)\n    .def(\"reset_mics\", &Room<2>::reset_mics)\n    .def(\"image_source_model\", &Room<2>::image_source_model)\n    .def(\"get_wall\", &Room<2>::get_wall)\n    .def(\"get_max_distance\", &Room<2>::get_max_distance)\n    .def(\"next_wall_hit\", &Room<2>::next_wall_hit)\n    .def(\"scat_ray\", &Room<2>::scat_ray)\n    .def(\"simul_ray\", &Room<2>::simul_ray)\n    .def(\"ray_tracing\",\n        (void (Room<2>::*)(\n                             const Eigen::Matrix<float,1,Eigen::Dynamic> &angles,\n                             const Vectorf<2> source_pos\n                            )\n        )\n        &Room<2>::ray_tracing)\n    .def(\"ray_tracing\",\n        (void (Room<2>::*)(\n                             size_t nb_phis,\n                             size_t nb_thetas,\n                             const Vectorf<2> source_pos\n                            )\n        )\n        &Room<2>::ray_tracing)\n    .def(\"ray_tracing\",\n        (void (Room<2>::*)(\n                             size_t n_rays,\n                             const Vectorf<2> source_pos\n                            )\n        )\n        &Room<2>::ray_tracing)\n    .def(\"contains\", &Room<2>::contains)\n    .def_property_readonly_static(\"dim\", [](py::object /* self */) { return 2; })\n    .def_property(\"is_hybrid_sim\", &Room<2>::get_is_hybrid_sim, &Room<2>::set_is_hybrid_sim)\n    .def_readonly(\"walls\", &Room<2>::walls)\n    .def_readonly(\"sources\", &Room<2>::sources)\n    .def_readonly(\"orders\", &Room<2>::orders)\n    .def_readonly(\"attenuations\", &Room<2>::attenuations)\n    .def_readonly(\"gen_walls\", &Room<2>::gen_walls)\n    .def_readonly(\"visible_mics\", &Room<2>::visible_mics)\n    .def_readonly(\"walls\", &Room<2>::walls)\n    .def_readonly(\"obstructing_walls\", &Room<2>::obstructing_walls)\n    .def_readonly(\"microphones\", &Room<2>::microphones)\n    .def_readonly(\"max_dist\", &Room<2>::max_dist)\n    ;\n\n  // The Wall class\n  py::class_<Wall<3>> wall_cls(m, \"Wall\");\n\n  wall_cls\n    .def(py::init<const Eigen::Matrix<float,3,Eigen::Dynamic> &, const Eigen::ArrayXf &, const Eigen::ArrayXf &, const std::string &>(),\n        py::arg(\"corners\"), py::arg(\"absorption\") = Eigen::ArrayXf::Zero(1),\n        py::arg(\"scattering\") = Eigen::ArrayXf::Zero(1), py::arg(\"name\") = \"\")\n    .def(\"area\", &Wall<3>::area)\n    .def(\"intersection\", &Wall<3>::intersection)\n    .def(\"intersects\", &Wall<3>::intersects)\n    .def(\"side\", &Wall<3>::side)\n    .def(\"reflect\", &Wall<3>::reflect)\n    .def(\"normal_reflect\", (Vectorf<3>(Wall<3>::*)(const Vectorf<3>&, const Vectorf<3>&, float) const)&Wall<3>::normal_reflect)\n    .def(\"normal_reflect\", (Vectorf<3>(Wall<3>::*)(const Vectorf<3>&) const)&Wall<3>::normal_reflect)\n    .def(\"same_as\", &Wall<3>::same_as)\n    .def_property_readonly_static(\"dim\", [](py::object /* self */) { return 3; })\n    .def_readwrite(\"absorption\", &Wall<3>::absorption)\n    .def_readwrite(\"scatter\", &Wall<3>::scatter)\n    .def_readwrite(\"name\", &Wall<3>::name)\n    .def_readonly(\"corners\", &Wall<3>::corners)\n    .def_readonly(\"origin\", &Wall<3>::origin)\n    .def_readonly(\"normal\", &Wall<3>::normal)\n    .def_readonly(\"basis\", &Wall<3>::basis)\n    .def_readonly(\"flat_corners\", &Wall<3>::flat_corners)\n    ;\n\n  py::enum_<Wall<3>::Isect>(wall_cls, \"Isect\")\n    .value(\"NONE\", Wall<3>::Isect::NONE)\n    .value(\"VALID\", Wall<3>::Isect::VALID)\n    .value(\"ENDPT\", Wall<3>::Isect::ENDPT)\n    .value(\"BNDRY\", Wall<3>::Isect::BNDRY)\n    .export_values();\n\n  // The Wall class\n  py::class_<Wall<2>> wall2d_cls(m, \"Wall2D\");\n\n  wall2d_cls\n    .def(py::init<const Eigen::Matrix<float,2,Eigen::Dynamic> &, const Eigen::ArrayXf &, const Eigen::ArrayXf &, std::string &>(),\n        py::arg(\"corners\"), py::arg(\"absorption\") = Eigen::ArrayXf::Zero(1),\n        py::arg(\"scattering\") = Eigen::ArrayXf::Zero(1), py::arg(\"name\") = \"\")\n    .def(\"area\", &Wall<2>::area)\n    .def(\"intersection\", &Wall<2>::intersection)\n    .def(\"intersects\", &Wall<2>::intersects)\n    .def(\"side\", &Wall<2>::side)\n    .def(\"reflect\", &Wall<2>::reflect)\n    .def(\"normal_reflect\", (Vectorf<2>(Wall<2>::*)(const Vectorf<2>&, const Vectorf<2>&, float) const)&Wall<2>::normal_reflect)\n    .def(\"normal_reflect\", (Vectorf<2>(Wall<2>::*)(const Vectorf<2>&) const)&Wall<2>::normal_reflect)\n    .def(\"same_as\", &Wall<2>::same_as)\n    .def_property_readonly_static(\"dim\", [](py::object /* self */) { return 2; })\n    .def_readwrite(\"absorption\", &Wall<2>::absorption)\n    .def_readwrite(\"scatter\", &Wall<2>::scatter)\n    .def_readwrite(\"name\", &Wall<2>::name)\n    .def_readonly(\"corners\", &Wall<2>::corners)\n    .def_readonly(\"origin\", &Wall<2>::origin)\n    .def_readonly(\"normal\", &Wall<2>::normal)\n    .def_readonly(\"basis\", &Wall<2>::basis)\n    .def_readonly(\"flat_corners\", &Wall<2>::flat_corners)\n    ;\n\n  // The different wall intersection cases\n  m.attr(\"WALL_ISECT_NONE\") = WALL_ISECT_NONE;\n  m.attr(\"WALL_ISECT_VALID\") = WALL_ISECT_VALID;\n  m.attr(\"WALL_ISECT_VALID_ENDPT\") = WALL_ISECT_VALID_ENDPT;\n  m.attr(\"WALL_ISECT_VALID_BNDRY\") = WALL_ISECT_VALID_BNDRY;\n\n  // The microphone class\n  py::class_<Microphone<3>>(m, \"Microphone\")\n    .def(py::init<const Vectorf<3> &, int, float, float>())\n    .def_readonly(\"loc\", &Microphone<3>::loc)\n    .def_readonly(\"hits\", &Microphone<3>::hits)\n    .def_readonly(\"histograms\", &Microphone<3>::histograms)\n    ;\n\n  py::class_<Microphone<2>>(m, \"Microphone2D\")\n    .def(py::init<const Vectorf<2> &, int, float, float>())\n    .def_readonly(\"loc\", &Microphone<2>::loc)\n    .def_readonly(\"hits\", &Microphone<2>::hits)\n    .def_readonly(\"histograms\", &Microphone<2>::histograms)\n    ;\n\n  // The 2D histogram class\n  py::class_<Histogram2D>(m, \"Histogram2D\")\n    .def(py::init<int, int>())\n    .def(\"log\", &Histogram2D::log)\n    .def(\"bin\", &Histogram2D::bin)\n    .def(\"get_hist\", &Histogram2D::get_hist)\n    .def(\"reset\", &Histogram2D::reset)\n    ;\n\n  // Structure to hold detector hit information\n  py::class_<Hit>(m, \"Hit\")\n    .def(py::init<int>())\n    .def(py::init<const float, const Eigen::ArrayXf &>())\n    .def_readonly(\"transmitted\", &Hit::transmitted)\n    .def_readonly(\"distance\", &Hit::distance)\n    ;\n\n  // getter and setter for geometric epsilon\n  m.def(\"set_eps\", [](const float &eps) { libroom_eps = eps; });\n  m.def(\"get_eps\", []() { return libroom_eps; });\n\n  // Routines for the geometry packages\n  m.def(\"ccw3p\", &ccw3p, \"Determines the orientation of three points\");\n\n  m.def(\"check_intersection_2d_segments\",\n      &check_intersection_2d_segments,\n      \"A function that checks if two line segments intersect\");\n\n  m.def(\"intersection_2d_segments\",\n      &intersection_2d_segments,\n      \"A function that finds the intersection of two line segments\");\n\n  m.def(\"intersection_3d_segment_plane\",\n      &intersection_3d_segment_plane,\n      \"A function that finds the intersection between a line segment and a plane\");\n\n  m.def(\"cross\", &cross, \"Cross product of two 3D vectors\");\n\n  m.def(\"is_inside_2d_polygon\", &is_inside_2d_polygon,\n      \"Checks if a 2D point lies in or out of a planar polygon\");\n\n  m.def(\"area_2d_polygon\", &area_2d_polygon,\n      \"Compute the signed area of a planar polygon\");\n\n  m.def(\"cos_angle_between\", &cos_angle_between,\n      \"Computes the angle between two 2D or 3D vectors\");\n\n  m.def(\"dist_line_point\", &dist_line_point,\n      \"Computes the distance between a point and an infinite line\");\n\n}\n\n", "meta": {"hexsha": "eb690702badd05d77b8cc8ddc7ea8c0dbb909902", "size": 12205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pyroomacoustics/libroom_src/libroom.cpp", "max_stars_repo_name": "kimurakeigo888/line", "max_stars_repo_head_hexsha": "34a656ce302168919c3c8a46276d8c013291dc0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyroomacoustics/libroom_src/libroom.cpp", "max_issues_repo_name": "kimurakeigo888/line", "max_issues_repo_head_hexsha": "34a656ce302168919c3c8a46276d8c013291dc0c", "max_issues_repo_licenses": ["MIT"], "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/libroom.cpp", "max_forks_repo_name": "kimurakeigo888/line", "max_forks_repo_head_hexsha": "34a656ce302168919c3c8a46276d8c013291dc0c", "max_forks_repo_licenses": ["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.2805280528, "max_line_length": 136, "alphanum_fraction": 0.6163867268, "num_tokens": 3587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339457, "lm_q2_score": 0.022977368906458788, "lm_q1q2_score": 0.00801094789201032}}
{"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 \"heom/instance.hpp\"\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <unordered_map>\n\n#include <boost/functional/hash.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n\n#include <noma/memory/memory.hpp>\n\n#include \"heom/constants.hpp\"\n\nnamespace heom {\n\n// constructor from heom_config\ninstance::instance(const config& cfg, sites_to_states_mode_t sts_mode, const hierarchy_graph& graph)\n  : sites_to_states_mode_(sts_mode)\n{\n\t// setup sizes\n\tstates_ = sites_to_states(cfg.system_sites(), sts_mode); // NOTE: site to state conversion\n\tmatsubaras_ = cfg.baths_matsubaras();\n\tbaths_per_state_ = max_baths_per_state(cfg.baths_max_per_site(), sts_mode); // NOTE: site to state conversion\n\tbaths_ = cfg.baths_number();\n\n\tado_width_ = graph.width(); //baths_ * matsubaras_;\n\tado_depth_ = graph.depth(); //cfg.system_ado_depth();\n\n\tmatrices_ = graph.nodes(); // includes halo nodes\n\tfirst_non_plus_id_ = graph.first_non_plus_uid();\n\tassert(first_non_plus_id_ > 0);\n\n\t// allocate buffer memory\n\tallocate();\n\n\t// initialise low-level instance data structures from high_level graph partition data structure\n\tfor (uid_t id = 0; id < graph.nodes(); ++id) {\n\t\t// copy tuples\n\t\tauto tuples = graph.tuples()[id].data();\n\t\tstd::copy(tuples, tuples + ado_width_, &ado_tuples_[id * ado_width_]);\n\t\t// copy plus edges\n\t\tauto plus_edges = graph.plus_edges()[id].data();\n\t\tstd::copy(plus_edges, plus_edges + ado_width_, &ado_plus_[id * ado_width_]);\n\t\t// copy minus edges\n\t\tauto minus_edges = graph.minus_edges()[id].data();\n\t\tstd::copy(minus_edges, minus_edges + ado_width_, &ado_minus_[id * ado_width_]);\n\t}\n\n\t// initialise memory\n\t// NOTE: site to state conversion for the hamiltonian happens here\n\tset_hamiltonian(reinterpret_cast<const real_t*>(state_hamiltonian(cfg.system_hamiltonian(), sites_to_states_mode_).data()));\n\n\t// compute kernel input\n\tDEBUG_ONLY( std::cout << \"instance::instance(..): begin precompute_baths_input\" << std::endl; )\n\t// TODO: this call is annoyingly slow when testing\n\tprecompute_baths_input(cfg);\n\tDEBUG_ONLY( std::cout << \"instance::instance(..): end precompute_baths_input\" << std::endl; )\n\n\t// initialize y_n (i.e. the initial value of our initial value problem)\n\tnull_hierarchy();\n\n\t// NOTE: set_hierarchy_top() needs to be called to produce actual results, for testing: set (global) first element to 1.0\n}\n\n// constructor from saved state\ninstance::instance(const std::string& filename)\n{\n\tallocate();\n\tread_file(filename);\n}\n\n// copy ctor\ninstance::instance(const instance& other)\n{\n\t// copy shallow members\n\tversion_ = other.version_;\n\thierarchy_top_only_ = other.hierarchy_top_only_;\n\thierarchy_layout_ = other.hierarchy_layout_;\n\thamiltonian_layout_ = other.hamiltonian_layout_;\n\tsites_to_states_mode_ = other.sites_to_states_mode_;\n\n\ttime_ = other.time_;\n\tfirst_non_plus_id_ = other.first_non_plus_id_;\n\n\tstates_ = other.states_;\n\tmatrices_ = other.matrices_;\n\tmatsubaras_ = other.matsubaras_;\n\tbaths_per_state_ = other.baths_per_state_;\n\tbaths_ = other.baths_;\n\tado_width_ = other.ado_width_;\n\tado_depth_ = other.ado_depth_;\n\n\tallocate();\n\n\t// copy dynamic members\n\tstd::copy(other.hierarchy_, other.hierarchy_ + other.size_hierarchy(), hierarchy_);\n\tstd::copy(other.hamiltonian_, other.hamiltonian_ + other.size_hamiltonian(), hamiltonian_);\n\n\tstd::copy(other.ado_tuples_, other.ado_tuples_ + other.size_ado_tuples(), ado_tuples_);\n\tstd::copy(other.ado_plus_, other.ado_plus_ + other.size_ado_plus(), ado_plus_);\n\tstd::copy(other.ado_minus_, other.ado_minus_ + other.size_ado_minus(), ado_minus_);\n\n\tstd::copy(other.pf_same_sum_, other.pf_same_sum_ + other.size_pf_same_sum(), pf_same_sum_);\n\tstd::copy(other.pf_same_, other.pf_same_ + other.size_pf_same(), pf_same_);\n\tstd::copy(other.pf_circ_, other.pf_circ_ + other.size_pf_circ(), pf_circ_);\n\tstd::copy(other.cbk_, other.cbk_ + other.size_cbk(), cbk_);\n\tstd::copy(other.cbk_sqrt_, other.cbk_sqrt_ + other.size_cbk_sqrt(), cbk_sqrt_);\n}\n\ninstance::~instance()\n{\n\tfree();\n}\n\nvoid instance::allocate()\n{\n\thierarchy_ = memory::aligned::instance().allocate<real_t>(size_hierarchy());\n\thamiltonian_ = memory::aligned::instance().allocate<real_t>(size_hamiltonian());\n\n\tado_tuples_ = memory::aligned::instance().allocate<std::int32_t>(size_ado_tuples());\n\tado_plus_ = memory::aligned::instance().allocate<std::int32_t>(size_ado_plus());\n\tado_minus_ = memory::aligned::instance().allocate<std::int32_t>(size_ado_minus());\n\n\tpf_same_sum_ = memory::aligned::instance().allocate<real_t>(size_pf_same_sum());\n\tpf_same_ = memory::aligned::instance().allocate<real_t>(size_pf_same());\n\tpf_circ_ = memory::aligned::instance().allocate<real_t>(size_pf_circ());\n\tcbk_ = memory::aligned::instance().allocate<real_t>(size_cbk());\n\tcbk_sqrt_ = memory::aligned::instance().allocate<real_t>(size_cbk_sqrt());\n}\n\nvoid instance::free()\n{\n\tmemory::aligned::instance().free(hierarchy_);\n\tmemory::aligned::instance().free(hamiltonian_);\n\n\tmemory::aligned::instance().free(ado_tuples_);\n\tmemory::aligned::instance().free(ado_plus_);\n\tmemory::aligned::instance().free(ado_minus_);\n\n\tmemory::aligned::instance().free(pf_same_sum_);\n\tmemory::aligned::instance().free(pf_same_);\n\tmemory::aligned::instance().free(pf_circ_);\n\tmemory::aligned::instance().free(cbk_);\n\tmemory::aligned::instance().free(cbk_sqrt_);\n}\n\nvoid instance::precompute_baths_input(const config& cfg)\n{\n\n\tcomplex_t* PFSAMESUMIn = reinterpret_cast<complex_t*>(this->pf_same_sum_);\n\tcomplex_t* PFSAMEIn = reinterpret_cast<complex_t*>(this->pf_same_);\n\tcomplex_t* PFCIRCIn = reinterpret_cast<complex_t*>(this->pf_circ_);\n\tcomplex_t* CBKIn = reinterpret_cast<complex_t*>(this->cbk_);\n\treal_t* CBKSqrtIn = reinterpret_cast<real_t*>(this->cbk_sqrt_);\n\n\t// FIXME: location of physical constants definitions?\n\tconst real_t& hbar = constants::h_bar;\n\n\treal_t beta = 1.0 / (constants::k_b * cfg.baths_temperature());\n\n\tfor(int_t b = 0; b < cfg.baths_number(); ++b)\n\t{\n\t\tcomplex_t aux;\n\n\t\tcomplex_t lambda_b { cfg.baths_lambda().at(b) }; // complexify\n\t\tcomplex_t nu_b { 1.0/cfg.baths_invnu().at(b), cfg.baths_uppercase_omega().at(b) }; // complexify\n\n\t\tPFCIRCIn[b] = nu_b * lambda_b / hbar;\n\t\taux = 2.0 * lambda_b / (beta * hbar * hbar * nu_b);\n\n\t\tfor (int_t k = 0; k < matsubaras_; ++k)\n\t\t{\n\t\t\tcomplex_t cbk, cbk0, nubk;\n\t\t\t// only the k=0 term differs with respect to complex conjugation\n\t\t\tif (k == 0)\n\t\t\t{\n\t\t\t\t//NOTE: with PADE\n\t\t\t\tcomplex_t auxsum=0.0;\n\t\t\t\tfor(int_t j = 0; j < matsubaras_; ++j)\n\t\t\t\t{\n\t\t\t\t\treal_t eta = constants::eta_pade[(matsubaras_ - 1) * constants::max_pade + j];\n\t\t\t\t\treal_t xi = constants::xi_pade [(matsubaras_ - 1) * constants::max_pade + j];\n\t\t\t\t\tauxsum += (2.0 * eta * nu_b * nu_b) / (xi * xi / (beta * beta * hbar * hbar) - nu_b * nu_b);\n\t\t\t\t}\n\t\t\t\tcbk0 = 2.0 * lambda_b / (beta * hbar) * (1.0 - auxsum);\n\n\t\t\t\t// Alternative without PADE\n\t\t\t\t//cbk0  =lambda_b*nu_b*(1.0/tan(0.5*beta*hbar*nu_b));\n\n\t\t\t\tcbk = cbk0;\n\t\t\t\tnubk = nu_b;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\t\t\t\t//NOTE: with PADE\n\t\t\t\treal_t eta = constants::eta_pade[(matsubaras_ - 1) * constants::max_pade + k];\n\t\t\t\treal_t xi = constants::xi_pade[(matsubaras_ - 1) * constants::max_pade + k];\n\t\t\t\tcbk = 4.0 * lambda_b * nu_b / (beta * beta * hbar * hbar) * (eta * xi) / (xi * xi / (beta * beta * hbar * hbar) - nu_b * nu_b);\n\t\t\t\tnubk = xi / (beta*hbar);\n\n\t\t\t\t// Alternative without PADE\n\t\t\t\t//cbk=8.0*real_t(k)*M_PI*lambda_b*nu_b/(4.0*k*k*M_PI*M_PI-beta*beta*nu_b*nu_b*hbar*hbar);\n\t\t\t\t//nubk=2.0*real_t(k)*M_PI/(beta*hbar);\n\n\t\t\t}\n\t\t\t// FIXME we define a mapping here\n\t\t\tCBKIn[b * matsubaras_ + k] = cbk;\n\t\t\tCBKSqrtIn[b * matsubaras_ + k] = sqrt(abs(cbk));\n\t\t\taux -= cbk / (hbar * nubk);\n\t\t}\n\t\tPFSAMEIn[b] = aux;\n\t}\n\n\t// pre-compute outer summation:\n\t// TODO: does not work with filtering, as it assumes all matrices are included in the propagation\n\t// TODO: do when coding post-filter compactify...\n\n\tfor (uid_t id = 0; id < matrices_; ++id)\n\t{\n\t\t// long double needed due to large summation to avoid cancellation effects\n\t\tlong double zr = 0.0L;\n\t\tlong double zi = 0.0L;\n\n\t\tfor (int b = 0; b < cfg.baths_number(); ++b)\n\t\t{\n\t\t\tcomplex_t nu_b { 1.0 / cfg.baths_invnu().at(b), cfg.baths_uppercase_omega().at(b) }; // complexify\n\n\t\t\tfor (int k = 0; k < matsubaras_; ++k)\n\t\t\t{\n\t\t\t\tlong double nubk_r,nubk_i;\n\t\t\t\tif (k==0)\n\t\t\t\t{\n\t\t\t\t\tnubk_r = static_cast<long double>(real(nu_b));\n\t\t\t\t\tnubk_i = static_cast<long double>(imag(nu_b));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// NOTE: with PADE\n\t\t\t\t\tnubk_r = constants::xi_pade[(matsubaras_ - 1) * constants::max_pade + k] / static_cast<long double>(beta*hbar);\n\t\t\t\t\t// Alternative without PADE\n\t\t\t\t\t//nubk_r=2.0L*(long double)M_PI*(long double)k/(beta*hbar);\n\n\t\t\t\t\tnubk_i = 0.0L;\n\t\t\t\t}\n\t\t\t\t// NOTE: we imply a mapping here\n\t\t\t\tint m = b * matsubaras_ + k;\n\n\t\t\t\tzr -= nubk_r * static_cast<long double>(ado_tuples_[id * ado_width_ + m]);\n\t\t\t\tzi -= nubk_i * static_cast<long double>(ado_tuples_[id * ado_width_ + m]);\n\t\t\t}\n\t\t}\n\t\tPFSAMESUMIn[id] = complex_t(zr, zi);\n\t} // sum over all HEOM matrices\n\n\t// output for comparison\n//\tDEBUG_ONLY( array_to_file(\"HAMIn\", reinterpret_cast<complex_t*>(this->hamiltonian_), this->size_hamiltonian_byte() / 2 / sizeof(real_t)); )\n//\tDEBUG_ONLY( array_to_file(\"ADOTupleIn\", this->ado_tuples_, this->size_ado_tuples_byte() / sizeof(std::int32_t)); )\n//\tDEBUG_ONLY( array_to_file(\"PlusIndexIn\", this->ado_plus_, this->size_ado_plus_byte() / sizeof(std::int32_t)); )\n//\tDEBUG_ONLY( array_to_file(\"MinusIndexIn\", this->ado_minus_, this->size_ado_minus_byte() / sizeof(std::int32_t)); )\n//\tDEBUG_ONLY( array_to_file(\"PFSAMESUMIn\", PFSAMESUMIn, this->size_pf_same_sum_byte() / 2 / sizeof(real_t)); )\n//\tDEBUG_ONLY( array_to_file(\"PFSAMEIn\", PFSAMEIn, this->size_pf_same_byte() / 2 / sizeof(real_t)); )\n//\tDEBUG_ONLY( array_to_file(\"PFCIRCIn\", PFCIRCIn, this->size_pf_circ_byte() / 2 / sizeof(real_t)); )\n//\tDEBUG_ONLY( array_to_file(\"CBKIn\", CBKIn, this->size_cbk_byte() / 2 / sizeof(real_t)); )\n}\n\ntemplate<typename T>\nstd::ifstream::char_type* cast_to_char(T* ptr)\n{\n\treturn reinterpret_cast<std::ifstream::char_type*>(ptr);\n}\n\nbool instance::read_file(std::string filename)\n{\n\ttry {\n\t\tstd::ifstream file;\n\t\tfile.open(filename, std::ios::in | std::ios::binary);\n\n\t\tif (file.fail())\n\t\t\tthrow config_error(\"could not open instance file: \" + filename);\n\n\t\t// format specifics\n\t\tfile.read(cast_to_char(&version_), sizeof version_);\n\t\tfile.read(cast_to_char(&hierarchy_top_only_), sizeof hierarchy_top_only_);\n\t\tfile.read(cast_to_char(&hierarchy_layout_), sizeof hierarchy_layout_);\n\t\tfile.read(cast_to_char(&hamiltonian_layout_), sizeof hamiltonian_layout_);\n\t\tfile.read(cast_to_char(&sites_to_states_mode_), sizeof sites_to_states_mode_);\n\n\t\t// variables\n\t\tfile.read(cast_to_char(&time_), sizeof time_);\n\t\tfile.read(cast_to_char(&first_non_plus_id_), sizeof first_non_plus_id_);\n\n\t\t// sizes\n\t\tfile.read(cast_to_char(&states_), sizeof states_);\n\t\tfile.read(cast_to_char(&matrices_), sizeof matrices_);\n\t\tfile.read(cast_to_char(&matsubaras_), sizeof matsubaras_);\n\t\tfile.read(cast_to_char(&baths_per_state_), sizeof baths_per_state_);\n\t\tfile.read(cast_to_char(&baths_), sizeof baths_);\n\t\tfile.read(cast_to_char(&ado_width_), sizeof ado_width_);\n\t\tfile.read(cast_to_char(&ado_depth_), sizeof ado_depth_);\n\n\t\t// buffers\n\t\tfile.read(cast_to_char(hierarchy_), hierarchy_top_only_ ? size_hierarchy_top_byte() : size_hierarchy_byte());\n\t\tfile.read(cast_to_char(hamiltonian_), size_hamiltonian_byte());\n\t\tfile.read(cast_to_char(ado_tuples_), size_ado_tuples_byte());\n\t\tfile.read(cast_to_char(ado_plus_), size_ado_plus_byte());\n\t\tfile.read(cast_to_char(ado_minus_), size_ado_minus_byte());\n\t\tfile.read(cast_to_char(pf_same_sum_), size_pf_same_sum_byte());\n\t\tfile.read(cast_to_char(pf_same_), size_pf_same_byte());\n\t\tfile.read(cast_to_char(pf_circ_), size_pf_circ_byte());\n\t\tfile.read(cast_to_char(cbk_), size_cbk_byte());\n\t\tfile.read(cast_to_char(cbk_sqrt_), size_cbk_sqrt_byte());\n\n\t\tfile.close();\n\t} catch (std::exception& e) {\n\t\tstd::cerr << \"instance::read_file(): Exception for file '\" << filename << \"': \" << e.what() << std::endl;\n\t\treturn false;\n\t}\n\n\treturn true;\n\n}\n\nbool instance::write_file(std::string filename)\n{\n\ttry {\n\t\tstd::ofstream file;\n\t\tfile.open(filename, std::ios::out | std::ios::binary | std::ios::trunc);\n\n\t\t// format specifics\n\t\tfile.write(cast_to_char(&version_), sizeof version_);\n\t\tfile.write(cast_to_char(&hierarchy_top_only_), sizeof hierarchy_top_only_);\n\t\tfile.write(cast_to_char(&hierarchy_layout_), sizeof hierarchy_layout_);\n\t\tfile.write(cast_to_char(&hamiltonian_layout_), sizeof hamiltonian_layout_);\n\t\tfile.write(cast_to_char(&sites_to_states_mode_), sizeof sites_to_states_mode_);\n\n\t\t// variables\n\t\tfile.write(cast_to_char(&time_), sizeof time_);\n\t\tfile.write(cast_to_char(&first_non_plus_id_), sizeof first_non_plus_id_);\n\n\t\t// sizes\n\t\tfile.write(cast_to_char(&states_), sizeof states_);\n\t\tfile.write(cast_to_char(&matrices_), sizeof matrices_);\n\t\tfile.write(cast_to_char(&matsubaras_), sizeof matsubaras_);\n\t\tfile.write(cast_to_char(&baths_per_state_), sizeof baths_per_state_);\n\t\tfile.write(cast_to_char(&baths_), sizeof baths_);\n\t\tfile.write(cast_to_char(&ado_width_), sizeof ado_width_);\n\t\tfile.write(cast_to_char(&ado_depth_), sizeof ado_depth_);\n\n\t\t// buffers\n\t\tfile.write(cast_to_char(hierarchy_), hierarchy_top_only_ ? size_hierarchy_top_byte() : size_hierarchy_byte());\n\t\tfile.write(cast_to_char(hamiltonian_), size_hamiltonian_byte());\n\t\tfile.write(cast_to_char(ado_tuples_), size_ado_tuples_byte());\n\t\tfile.write(cast_to_char(ado_plus_), size_ado_plus_byte());\n\t\tfile.write(cast_to_char(ado_minus_), size_ado_minus_byte());\n\t\tfile.write(cast_to_char(pf_same_sum_), size_pf_same_sum_byte());\n\t\tfile.write(cast_to_char(pf_same_), size_pf_same_byte());\n\t\tfile.write(cast_to_char(pf_circ_), size_pf_circ_byte());\n\t\tfile.write(cast_to_char(cbk_), size_cbk_byte());\n\t\tfile.write(cast_to_char(cbk_sqrt_), size_cbk_sqrt_byte());\n\n\t\tfile.close();\n\t} catch (std::exception& e) {\n\t\tstd::cerr << \"instance::write_file(): Exception for file '\" << filename << \"': \" << e.what() << std::endl;\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nsize_t instance::size_hierarchy() const\n{\n\treturn states_ * states_ * matrices_ * 2;\n}\n\nsize_t instance::size_hierarchy_top() const\n{\n\treturn states_ * states_ * 2; // just the top of the hierarchy\n}\n\nsize_t instance::size_hamiltonian() const\n{\n\treturn states_ * states_ * 2;\n}\n\nsize_t instance::size_ado_tuples() const\n{\n\treturn matrices_ * ado_width_;\n}\n\nsize_t instance::size_ado_plus() const\n{\n\treturn matrices_ * ado_width_;\n}\n\nsize_t instance::size_ado_minus() const\n{\n\treturn matrices_ * ado_width_;\n}\n\nsize_t instance::size_pf_same_sum() const\n{\n\treturn matrices_ * 2;\n}\n\nsize_t instance::size_pf_same() const\n{\n\treturn baths_ * 2;\n}\n\nsize_t instance::size_pf_circ() const\n{\n\treturn baths_ * 2;\n}\n\nsize_t instance::size_cbk() const\n{\n\treturn baths_ * matsubaras_ * 2;\n}\n\nsize_t instance::size_cbk_sqrt() const\n{\n\treturn baths_ * matsubaras_;\n}\n\nsize_t instance::allocated_byte() const\n{\n\treturn size_hierarchy_byte() +\n\t       size_hamiltonian_byte() +\n\t       size_ado_tuples_byte() +\n\t       size_ado_plus_byte() +\n\t       size_ado_minus_byte() +\n\t       size_pf_same_sum_byte() +\n\t       size_pf_same_byte() +\n\t       size_pf_circ_byte() +\n\t       size_cbk_byte() +\n\t       size_cbk_sqrt_byte();\n}\n\nvoid instance::null_hierarchy() const\n{\n\tfor (size_t i = 0; i < this->size_hierarchy_byte() / sizeof(real_t); ++i) {\n\t\thierarchy_[i] = 0.0;\n\t}\n}\n\nvoid instance::set_hamiltonian(const complex_matrix_t& new_hamiltonian) const\n{\n\tset_hamiltonian(reinterpret_cast<const real_t*>(new_hamiltonian.data()));\n}\n\nvoid instance::set_hamiltonian(const real_t* new_hamiltonian) const\n{\n\tfor (size_t j = 0; j < size_hamiltonian(); ++j) {\n\t\thamiltonian_[j] = new_hamiltonian[j];\n\t}\n}\n\nvoid instance::set_hamiltonian(const std::valarray<complex_t> new_hamiltonian) const\n{\n\tfor (size_t j = 0; j < size_hamiltonian(); j += 2) {\n\t\thamiltonian_[j] = new_hamiltonian[j / 2].real(); // NOTE: intended integer division\n\t\thamiltonian_[j+1] = new_hamiltonian[j / 2].imag();\n\t}\n}\n\nvoid instance::get_hierarchy_top(complex_t* buffer) const\n{\n\t// TODO: adapt for when other memory layouts are introduced, maybe use some overloaded []\n\tfor (int_t j = 0; j < states_ * states_; j += 1) {\n\t\tbuffer[j] = complex_t( hierarchy_[j * 2], hierarchy_[j * 2 + 1] );\n\t}\n}\n\nvoid instance::set_hierarchy_top() const\n{\n\thierarchy_[0] = 1.0;\n}\n\nvoid instance::set_hierarchy_top(const complex_t* new_hierarchy_top) const\n{\n\t// TODO: adapt for when other memory layouts are introduced, maybe use some overloaded []\n\tfor (int_t j = 0; j < states_ * states_; ++j) {\n\t\thierarchy_[2 * j] = new_hierarchy_top[j].real();\n\t\thierarchy_[2 * j + 1] = new_hierarchy_top[j].imag();\n\t}\n}\n\n} // namespace heom\n", "meta": {"hexsha": "c109bb240d381948d6987318ea9e650f7a4cf896", "size": 16958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dm-heom/src/heom/instance.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/heom/instance.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/heom/instance.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": 34.0522088353, "max_line_length": 142, "alphanum_fraction": 0.7145889846, "num_tokens": 4936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807713748839185, "lm_q2_score": 0.02368947181633178, "lm_q1q2_score": 0.008008868820277383}}
{"text": "#ifndef KA_PRODUCTITER_HPP\n#define KA_PRODUCTITER_HPP\n#pragma once\n#include <algorithm>\n#include <initializer_list>\n#include <iterator>\n#include <tuple>\n#include <type_traits>\n#include <boost/iterator/iterator_facade.hpp>\n#include \"integersequence.hpp\"\n#include \"macro.hpp\"\n#include \"macroregular.hpp\"\n#include \"typetraits.hpp\"\n#include \"utility.hpp\"\n\n/// @file\n///\n/// Contains a type template that implements the product of iterators, that is\n/// an iterator that groups sub-iterators and advances, dereferences, etc., them\n/// all at once.\n///\n/// # Added components\n///\n/// - Type contructors:\n///     + `product_iter_t: InputIterator... -> InputIterator`\n///\n/// - Constructor functions (with InputIterator... I, Linearizable... L):\n///     + `product_iter: I... -> product_iter_t<I...>`\n///     + `product_begin: L... -> product_iter_t<Iterator<L>...>`\n///     + `product_end: L... -> product_iter_t<Iterator<L>...>`\n///     + `product_end_same_size: L... -> product_iter_t<Iterator<L>...>`\n///\n/// - Functions (with InputIterator... I, InputIterator J, K):\n///     + `proj<n>: product_iter_t<I...> -> I_n` (i.e. nth type in I...)\n///     + `iterator_cat_ops::operator*`: J * K -> product_iter_t<J, K>\n///\n/// - Types:\n///     + `unit_iter_t: InputIterator`\n///\n/// - Constants:\n///     + `unit_iter: unit_iter_t`\n\nnamespace ka {\n\nnamespace product_iter_detail {\n  // The iterator category of a product of iterators is the lowest of all these\n  // iterators. The order is defined as: input < forward < bidirectional <\n  // random access.\n  //\n  // We need to implement a compile-time minimum algorithm, returning the\n  // minimum iterator category from a compile-time list. To do this, we first\n  // convert iterator categories to integers, then find the minimum integer, and\n  // finally convert back this integer to the corresponding iterator category.\n  // It is easier to order integers than to define the ordering for all pairs of\n  // iterator categories.\n\n  // Alias to represent a compile-time integer.\n  template<int i>\n  using Int = int_constant_t<i>;\n\n  // Alias to represent a compile-time boolean.\n  template<bool b>\n  using Bool = bool_constant_t<b>;\n\n  // Converts a type to a compile-time integer.\n  template<typename A>\n  struct ToIntImpl;\n\n  // Converts a compile-time integer to a type.\n  template<typename A>\n  struct FromIntImpl;\n\n  template<typename T>\n  using ToInt = typename ToIntImpl<T>::type;\n\n  template<typename T>\n  using FromInt = typename FromIntImpl<T>::type;\n\n// Maps a type to a compile-time integer, and vice-versa.\n#define KA_DEFINE_TYPE_TO_FROM_INT(T, i) \\\n    template<>                           \\\n    struct ToIntImpl<T> {                \\\n      using type = Int<i>;               \\\n    };                                   \\\n    template<>                           \\\n    struct FromIntImpl<Int<i>> {         \\\n      using type = T;                    \\\n    };\n\n  // Maps iterator categories to compile-time integer, and vice-versa.\n  KA_DEFINE_TYPE_TO_FROM_INT(std::input_iterator_tag, 0)\n  KA_DEFINE_TYPE_TO_FROM_INT(std::forward_iterator_tag, 1)\n  KA_DEFINE_TYPE_TO_FROM_INT(std::bidirectional_iterator_tag, 2)\n  KA_DEFINE_TYPE_TO_FROM_INT(std::random_access_iterator_tag, 3)\n#undef KA_DEFINE_TYPE_TO_FROM_INT\n\n  // Minimum of two integers.\n  template<typename A, typename B, typename ALessThanB>\n  struct MinInt2Impl;\n\n  template<int i, int j>\n  struct MinInt2Impl<Int<i>, Int<j>, true_t> {\n    using type = Int<i>;\n  };\n\n  template<int i, int j>\n  struct MinInt2Impl<Int<i>, Int<j>, false_t> {\n    using type = Int<j>;\n  };\n\n  template<typename A, typename B, typename ALessThanB>\n  using MinInt2 = typename MinInt2Impl<A, B, ALessThanB>::type;\n\n  // Minimum of n integers.\n  // Algorithm:\n  //  Incrementally replace the two head integers by the minimum one.\n  //  When the list contains one element only, it is the minimum.\n  template<typename... T>\n  struct MinIntNImpl;\n\n  template<typename T>\n  struct MinIntNImpl<T> {\n    using type = T;\n  };\n\n  template<int i, int j, typename... T>\n  struct MinIntNImpl<Int<i>, Int<j>, T...>\n    : MinIntNImpl<MinInt2<Int<i>, Int<j>, Bool<(i < j)>>, T...> {\n  };\n\n  template<typename... T>\n  using MinIntN = typename MinIntNImpl<T...>::type;\n\n  // Returns the lowest iterator category.\n  template<typename... T>\n  struct MinIterCatImpl {\n    using type = FromInt<MinIntN<ToInt<T>...>>;\n  };\n\n  // Returns the smallest of two types.\n  template<typename T, typename U, typename TLessThanU>\n  struct MinSize2 {\n    using type = T;\n  };\n\n  template<typename T, typename U>\n  struct MinSize2<T, U, false_t> {\n    using type = U;\n  };\n\n  // Returns the smallest of n types, according to `sizeof`.\n  // The algorithm is similar to `MinInt`.\n  template<typename... T>\n  struct MinSize;\n\n  template<typename T>\n  struct MinSize<T> {\n    using type = T;\n  };\n\n  template<typename T, typename U, typename... V>\n  struct MinSize<T, U, V...>\n    : MinSize<typename MinSize2<T, U, Bool<(sizeof(T) < sizeof(U))>>::type, V...> {\n  };\n\n  template<typename... T>\n  using MinIterCat = typename MinIterCatImpl<T...>::type;\n\n  // Convenient aliases to iterator affiliated types.\n  template<typename T>\n  using Value = typename std::iterator_traits<T>::value_type;\n\n  template<typename T>\n  using Reference = typename std::iterator_traits<T>::reference;\n\n  template<typename T>\n  using Difference = typename std::iterator_traits<T>::difference_type;\n\n  template<typename T>\n  using Category = typename std::iterator_traits<T>::iterator_category;\n} // namespace product_iter_detail\n\n// Base of `product_iter_t`. This macro avoids manual duplication of the code.\n// It is undefined below.\n#define KA_PRODUCT_ITER_BASE(I)                                                        \\\n  boost::iterator_facade<                                                              \\\n    product_iter_t<I...>,                                                              \\\n    std::tuple<product_iter_detail::Value<I>...>,                                      \\\n    product_iter_detail::MinIterCat<product_iter_detail::Category<I>...>,              \\\n    std::tuple<product_iter_detail::Reference<I>...>,                                  \\\n    typename product_iter_detail::MinSize<product_iter_detail::Difference<I>...>::type \\\n  >\n\n/// Product of iterators: groups sub-iterators and advances, dereferences, etc.,\n/// them all at once.\n///\n/// This type is a product in the categorical sense: it strictly groups\n/// sub-iterators with no extra-information, and comes with projections to get\n/// them back. The underlying category is constructed over those of discrete\n/// dynamical systems (sets equipped with a transformation), with the additional\n/// structure of the dereferencement.\n/// See [Conceptual Mathematics, (Lawvere-Schanuel, 2009)](https://www.cambridge.org/core/books/conceptual-mathematics/00772F4CC3D4268200C5EC86B39D415A), article III\n///\n/// This iterator has the lowest iterator category of its sub-iterators, the\n/// order being: input < forward < bidirectional < random access.\n///\n/// To construct product of iterators, use the dedicated constructor functions:\n/// `product_iter`, `product_begin`, `product_end`, `product_end_same_size`\n///\n/// Note: The operations of the product of iterators are specified in terms of\n///   laws. The following notation is used:\n///     - `i * j` denotes product of iterators `i` and `j`\n///     - `t * u` denotes product of values `t` and `u`, i.e. tuple of `t` and `u`\n///     - `n` denotes a signed integer\n///     - `i + n` denotes iterator `i` moved forward by `n` steps\n///     - `j - i` denotes distance from iterator `i` to iterator `j`\n///     - `1i` denotes iterator unit\n///     - `1` denotes unit\n///     - `=` denotes equality\n///     - `≅` denotes isomorphism\n///\n/// Laws:\n///     *(i * ...)  =  ((*i) * ...)             (dereferencement)\n///  && (i * ...) + n  =  (i + n) * ...         (forward / backward move)\n///  && (j * ...) - (i * ...)  =  n, such that\n///       (j * ...)  =  (i * ...) + n, that is\n///       + is a right group action.            (difference)\n///  && i * 1i  ≅  1i * i  ≅  i                 (multiplication by unit)\n///  && 1i + n  =  1i                           (rest state 1)\n///  && 1i - 1i  =  0                           (rest state 2)\n///  && *1i  =  1                               (dereferencement of unit)\n///\n/// Note: Output iterators are not supported as their behavior differs too much\n///   from other iterator categories (`void` value type, etc.).\n///\n/// Example: Iterating through several containers at once.\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n/// // Containers are assumed to be large enough.\n/// // std::vector<X> v;\n/// // std::array<Y, 10> a;\n/// auto b = product_iter(v.begin(), a.begin());\n/// auto e = product_iter(v.begin() + 2, a.begin() + 2);\n/// while (b != e) {\n///   auto values = *b; // `values` has type `std::tuple<X, Y>`.\n///   ... // Use `values` (`ka::apply` can be used to call non-tuple input functions.)\n///   ++b;\n/// }\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n///\n/// Example: Iterating through several containers with different sizes.\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n/// // Computing the end product iterator is O(n) since we have to determine the\n/// // smallest container first.\n/// // std::vector<X> v;  // size = 4\n/// // std::list<Y> l;    // size = 2\n/// // std::deque<Z> d;   // size = 10\n/// // `product_begin(v, l, d) == product_iter(v.begin(), l.begin(), d.begin())`\n/// auto b = product_begin(v, l, d);\n/// auto e = product_end(v, l, d); // Ends depends on the smallest container.\n/// // Will loop twice since the smallest container has size 2.\n/// while (b != e) {\n///   auto values = *b; // `values` has type `std::tuple<X, Y, Z>`.\n///   ... // Use `values` (`ka::apply` can be used to call non-tuple input functions.)\n///   ++b;\n/// }\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n///\n/// Example: Iterating through several containers with same size.\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n/// // Computing the end product iterator is O(1) since we know all containers\n/// // have same size.\n/// // std::vector<X> v;  // size = 4\n/// // std::list<Y> l;    // size = 4\n/// // std::deque<Z> d;   // size = 4\n/// auto b = product_begin(v, l, d);\n/// auto e = product_end_same_size(v, l, d); // Takes end iterator of each container.\n/// // Will loop four times.\n/// while (b != e) {\n///   auto values = *b; // `values` has type `std::tuple<X, Y, Z>`.\n///   ... // Use `values` (`ka::apply` can be used to call non-tuple input functions.)\n///   ++b;\n/// }\n/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n///\n/// InputIterator... I\ntemplate<typename... I>\nstruct product_iter_t : KA_PRODUCT_ITER_BASE(I) {\n  using base = KA_PRODUCT_ITER_BASE(I);\n#undef KA_PRODUCT_ITER_BASE\n  using typename base::reference;\n  using typename base::difference_type;\n  using indexes_type = index_sequence_for<I...>;\n  std::tuple<I...> iters;\n\n  explicit\n  product_iter_t(std::tuple<I...> const& t) : iters(t) {\n  }\n  explicit\n  product_iter_t(std::tuple<I...>&& t) : iters(std::move(t)) {\n  }\n// Regular:\n  explicit\n  product_iter_t() = default;\n\n  bool equal(product_iter_t const& x) const KA_NOEXCEPT_EXPR(iters == x.iters) {\n    return iters == x.iters;\n  }\n// InputIterator:\n\n  //     *(i * ...) = ((*i) * ...)\n  reference dereference() const {\n    return do_dereference(indexes_type{});\n  }\n  //  && (i * ...) + n = (i + n) * ...\n  void increment() {\n    do_increment(indexes_type{});\n  }\n// BidirectionalIterator (if BidirectionalIterator... I):\n  void decrement() {\n    do_decrement(indexes_type{});\n  }\n// RandomAccessIterator (if RandomAccessIterator... I):\n  /// Integral N\n  template<typename N>\n  void advance(N n) {\n    do_advance(n, indexes_type{});\n  }\n  difference_type distance_to(product_iter_t x) const {\n    // There may be an algorithm better than this O(n) one...\n    // But it strictly follows the law of difference stated above, and therefore\n    // is correct for any orbit-shapes (infinite, circular, etc.).\n    auto n = difference_type(0);\n    while (x.iters != iters) {\n      ++n;\n      x.do_increment(indexes_type{});\n    }\n    return -n;\n  }\nprivate:\n  template<std::size_t... i>\n  reference do_dereference(index_sequence<i...>) const {\n    return reference{*std::get<i>(iters)...};\n  }\n\n  template<std::size_t... i>\n  void do_increment(index_sequence<i...>) {\n    (void)std::initializer_list<int>{0, (void(++std::get<i>(iters)), 0)...};\n  }\n\n  template<std::size_t... i>\n  void do_decrement(index_sequence<i...>) {\n    (void)std::initializer_list<int>{0, (void(--std::get<i>(iters)), 0)...};\n  }\n\n  template<std::size_t... i, typename N>\n  void do_advance(N n, index_sequence<i...>) {\n    (void)std::initializer_list<int>{0, (std::advance(std::get<i>(iters), n), 0)...};\n  }\n};\n\n/// Empty specialization.\n/// This is the unit type of the category of iterators.\n///\n/// See non-specialized version for info.\ntemplate<>\nstruct product_iter_t<> : boost::iterator_facade<\n    product_iter_t<>,\n    std::tuple<>,\n    std::random_access_iterator_tag,\n    std::tuple<>,\n    std::ptrdiff_t\n  >\n{\n// InputIterator:\n  constexpr\n  reference dereference() const noexcept {\n    return std::tuple<>{};\n  }\n  constexpr\n  bool equal(product_iter_t const&) const noexcept {\n    return true;\n  }\n  // `void` cannot be returned for the method to be `constexpr`...\n  // `iterator_facade` impose no constraint on the return type, so `int` is ok.\n  constexpr\n  int increment() const noexcept {\n    return 0;\n  }\n// BidirectionalIterator (if BidirectionalIterator... I):\n  constexpr\n  int decrement() const noexcept {\n    return 0;\n  }\n// RandomAccessIterator (if RandomAccessIterator... I):\n  /// Integral N\n  template<typename N> constexpr\n  int advance(N) const noexcept {\n    return 0;\n  }\n  constexpr\n  difference_type distance_to(product_iter_t const&) const noexcept {\n    return 0;\n  }\n};\n\n/// Random access iterator that is its own successor and predecessor.\n/// Its value type is `unit_t`.\n/// As `unit_t`, this iterator type does not hold any information.\nusing unit_iter_t = product_iter_t<>;\n\n/// Unique value of `unit_iter_t`.\nconstexpr unit_iter_t unit_iter;\n\n/// Contructs a product of iterators, performing argument type deduction.\n///\n/// InputIterator... I\ntemplate<typename... I>\nauto product_iter(I&&... i) -> product_iter_t<Decay<I>...> {\n  return product_iter_t<Decay<I>...>{product(fwd<I>(i)...)};\n}\n\n// Put `begin`/`end` functions in the detail namespace to be able to leverage\n// `ADL` in `decltype` clauses.\nnamespace product_iter_detail {\n  using std::begin;\n  using std::end;\n\n  template<typename L>\n  auto adl_begin(L&& l) -> decltype(begin(fwd<L>(l))) {\n    return begin(fwd<L>(l));\n  }\n\n  template<typename L>\n  auto adl_end(L&& l) -> decltype(end(fwd<L>(l))) {\n    return end(fwd<L>(l));\n  }\n\n  // Some containers have a `size` method, returning `size_type` which is\n  // typically `std::size_t` (unsigned), while others don't have such a method.\n  // In the latter case `std::distance` is used, but it returns the iterator\n  // `difference_type`, which is typically `std::ptrdiff_t` (signed). A cast\n  // must be done. Fortunately, the context guarantees a non-null\n  // `difference_type`, so the only problem could be in a difference of ranges\n  // between `size_type` and `difference_type`.\n  template<typename T>\n  auto total_size(true_t /* HasMemberSize */, T const& t) -> decltype(t.size()) {\n    return t.size();\n  }\n\n  template<typename T>\n  auto total_size(false_t /* HasMemberSize */, T const& t) -> std::size_t {\n    return static_cast<std::size_t>(std::distance(begin(t), end(t)));\n  }\n\n  // Precondition: n <= size\n  template<typename L, typename N>\n  auto iter_at(L&& l, N n, N size) -> decltype(end(fwd<L>(l))) {\n    if (n == size) {\n      return end(fwd<L>(l));\n    }\n    return std::next(begin(fwd<L>(l)), n);\n  }\n\n  // Computes the minimum size, then advances iterators accordingly.\n  template<typename... L, std::size_t... i>\n  auto product_end(index_sequence<i...>, L&&... l)\n      -> decltype(ka::product_iter(end(fwd<L>(l))...)) {\n    // This is a slight simplification: we should use internal `distance_type`\n    // with a special case for `std::array`.\n    std::array<std::size_t, sizeof...(L)> sizes =\n      {{total_size(HasMemberSize<Decay<L>>{}, l)...}};\n    auto const it = std::min_element(sizes.begin(), sizes.end());\n    return product_iter(iter_at(fwd<L>(l), *it, sizes[i])...);\n  }\n} // namespace product_iter_detail\n\n/// Product of begin iterators.\n///\n/// invariant: product_begin(l...) == product_iter(begin(l)...)\n///\n/// Linearizable... L\ntemplate<typename... L>\nauto product_begin(L&&... l)\n    -> decltype(product_iter(product_iter_detail::adl_begin(fwd<L>(l))...)) {\n  return product_iter(product_iter_detail::adl_begin(fwd<L>(l))...);\n}\n\n/// Product of iterators aligned with the smallest end.\n///\n/// invariant: product_end(l...) == product_iter(begin(l) + n...), where\n///            n == min(size(l)...) (min and size are specification-only)\n///\n/// Complexity: Constructing the end iterator requires finding the minimum size\n///   of each range. Computing the size of a standard container is O(1), except\n///   for `std::forward_list` which is O(n). Then, finding the minimum of these\n///   sizes is O(n) in the number of containers.\n///\n/// Linearizable... L\ntemplate<typename... L>\nauto product_end(L&&... l) -> decltype(product_iter_detail::product_end(\n    index_sequence_for<L...>{}, fwd<L>(l)...)) {\n  return product_iter_detail::product_end(\n    index_sequence_for<L...>{}, fwd<L>(l)...);\n}\n\n/// Product of end iterators.\n///\n/// Precondition: (forall x,y in l...) x.size() == y.size()\n/// Invariant: product_end(l...) == product_iter(end(l)...)\n///\n/// Note: If the size is known to be the same, an alternative to create an end\n///   iterator and form a bounded range (a begin-end pair of iterators) is to\n///   directly use a counted range (a begin iterator together with a distance).\n///\n/// Linearizable... L\ntemplate<typename... L>\nauto product_end_same_size(L&&... l)\n    -> decltype(product_iter(product_iter_detail::adl_end(fwd<L>(l))...)) {\n  return product_iter(product_iter_detail::adl_end(fwd<L>(l))...);\n}\n\n/// Projection of n th iterator of the product.\ntemplate<std::size_t n, typename... I>\nauto proj(product_iter_t<I...> const& x) -> decltype(std::get<n>(x.iters)) {\n  return std::get<n>(x.iters);\n}\n\n/// Projection of n th iterator of the product.\ntemplate<std::size_t n, typename... I>\nauto proj(product_iter_t<I...>& x) -> decltype(std::get<n>(x.iters)) {\n  return std::get<n>(x.iters);\n}\n\n/// Projection of n th iterator of the product.\ntemplate<std::size_t n, typename... I>\nauto proj(product_iter_t<I...>&& x) -> decltype(std::get<n>(std::move(x.iters))) {\n  return std::get<n>(std::move(x.iters));\n}\n\n/// Categorical operators for iterators.\nnamespace iterator_cat_ops {\n\n/// InputIterator I, InputIterator J\ntemplate<typename I, typename J,\n  typename = EnableIfInputIterator<I>, typename = EnableIfInputIterator<J>>\nauto operator*(I i, J j) -> decltype(product_iter(i, j)) {\n  return product_iter(std::move(i), std::move(j));\n}\n\n} // namespace iterator_ops\n\n} // namespace ka\n\n#endif // KA_PRODUCTITER_HPP\n", "meta": {"hexsha": "17443d7a6b31866f47c1a8495c302e4ed655eb33", "size": 19455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ka/productiter.hpp", "max_stars_repo_name": "arntanguy/libqi", "max_stars_repo_head_hexsha": "7f3e1394cb26126b26fa7ff54d2de1371a1c9f96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:05:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T16:47:47.000Z", "max_issues_repo_path": "ka/productiter.hpp", "max_issues_repo_name": "arntanguy/libqi", "max_issues_repo_head_hexsha": "7f3e1394cb26126b26fa7ff54d2de1371a1c9f96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2015-04-06T21:41:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T13:24:51.000Z", "max_forks_repo_path": "ka/productiter.hpp", "max_forks_repo_name": "arntanguy/libqi", "max_forks_repo_head_hexsha": "7f3e1394cb26126b26fa7ff54d2de1371a1c9f96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T20:01:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T13:31:20.000Z", "avg_line_length": 35.0540540541, "max_line_length": 165, "alphanum_fraction": 0.622770496, "num_tokens": 4982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.02517883973471165, "lm_q1q2_score": 0.007992425393988447}}
{"text": "#pragma once\n\n#include <crest/wave/solver.hpp>\n#include <crest/geometry/indexed_mesh.hpp>\n#include <crest/quadrature/simpsons.hpp>\n#include <crest/util/stat.hpp>\n\n#include <string>\n#include <cmath>\n\n#include <boost/optional.hpp>\n\nstruct OfflineParameters\n{\n    unsigned int oversampling;\n    double mesh_resolution;\n\n    std::string basis_export_file;\n    std::string basis_import_file;\n\n    unsigned int dense_fallback_threshold;\n    double iterative_tolerance;\n\n    OfflineParameters()\n            : oversampling(0),\n              mesh_resolution(0.0),\n              dense_fallback_threshold(300),\n              iterative_tolerance(10.0 * std::numeric_limits<double>::epsilon())\n    { }\n\n    OfflineParameters & with_oversampling(unsigned int oversampling)\n    {\n        this->oversampling = oversampling;\n        return *this;\n    }\n\n    OfflineParameters & with_mesh_resolution(double mesh_resolution)\n    {\n        this->mesh_resolution = mesh_resolution;\n        return *this;\n    }\n\n    OfflineParameters & with_basis_export_file(std::string path)\n    {\n        this->basis_export_file = path;\n        return *this;\n    }\n\n    OfflineParameters & with_basis_import_file(std::string path)\n    {\n        this->basis_import_file = path;\n        return *this;\n    }\n\n    OfflineParameters & with_dense_fallback_threshold(unsigned int threshold)\n    {\n        this->dense_fallback_threshold = threshold;\n        return *this;\n    }\n\n    OfflineParameters & with_iterative_tolerance(double iterative_tolerance)\n    {\n        this->iterative_tolerance = iterative_tolerance;\n        return *this;\n    }\n};\n\nstruct OnlineParameters\n{\n    double end_time;\n    uint64_t sample_count;\n    int load_quadrature_strength;\n    bool use_coarse_rhs;\n    bool use_coarse_mass_matrix;\n    double iterative_tolerance;\n    bool measure_error;\n    double max_error_before_abort;\n\n    std::string integrator_name;\n\n    OnlineParameters()\n            : end_time(0.0),\n              sample_count(0),\n              load_quadrature_strength(4),\n              use_coarse_rhs(false),\n              use_coarse_mass_matrix(false),\n              iterative_tolerance(10.0 * std::numeric_limits<double>::epsilon()),\n              measure_error(true),\n              max_error_before_abort(std::numeric_limits<double>::max())\n    {}\n\n    OnlineParameters & with_end_time(double end_time)\n    {\n        this->end_time = end_time;\n        return *this;\n    }\n\n    OnlineParameters & with_sample_count(uint64_t sample_count)\n    {\n        this->sample_count = sample_count;\n        return *this;\n    }\n\n    OnlineParameters & with_integrator_name(std::string name)\n    {\n        this->integrator_name = name;\n        return *this;\n    }\n\n    OnlineParameters & with_coarse_rhs(bool use_coarse_rhs)\n    {\n        this->use_coarse_rhs = use_coarse_rhs;\n        return *this;\n    }\n\n    OnlineParameters & with_coarse_mass_matrix(bool use_coarse_mass_matrix)\n    {\n        this->use_coarse_mass_matrix = use_coarse_mass_matrix;\n        return *this;\n    }\n\n    OnlineParameters & with_iterative_tolerance(double iterative_tolerance)\n    {\n        this->iterative_tolerance = iterative_tolerance;\n        return *this;\n    }\n\n    OnlineParameters & with_error_measurement(bool measure_error)\n    {\n        this->measure_error = measure_error;\n        return *this;\n    }\n\n    double dt() const\n    {\n        return end_time / (sample_count - 1);\n    }\n};\n\nstruct ExperimentInput\n{\n    std::string                         name;\n    OfflineParameters                   offline_parameters;\n    boost::optional<OnlineParameters>   online_parameters;\n\n    ExperimentInput & with_name(std::string name)\n    {\n        this->name = name;\n        return *this;\n    }\n\n    ExperimentInput & with_offline_parameters(OfflineParameters parameters)\n    {\n        this->offline_parameters = parameters;\n        return *this;\n    }\n\n    ExperimentInput & with_online_parameters(OnlineParameters parameters)\n    {\n        this->online_parameters = parameters;\n        return *this;\n    }\n};\n\nstruct MeshDetails\n{\n    int num_coarse_vertices;\n    int num_coarse_elements;\n    int num_fine_vertices;\n    int num_fine_elements;\n\n    // h is diameter of element\n    double h_max_coarse;\n    double h_min_coarse;\n    double h_max_fine;\n    double h_min_fine;\n\n    MeshDetails() : num_coarse_vertices(0),\n                    num_coarse_elements(0),\n                    num_fine_vertices(0),\n                    num_fine_elements(0),\n                    h_max_coarse(0.0),\n                    h_min_coarse(0.0),\n                    h_max_fine(0.0),\n                    h_min_fine(0.0)\n    { }\n};\n\nstd::pair<double, double> extremal_diameters(const crest::IndexedMesh<double, int> & mesh)\n{\n    double hmin_squared = std::numeric_limits<double>::max();\n    double hmax_squared = 0.0;\n\n    for (int element = 0; element < mesh.num_elements(); ++element)\n    {\n        const auto triangle = mesh.triangle_for(element);\n        const auto diameter_squared = crest::diameter_squared(triangle);\n        if (diameter_squared > hmax_squared) {\n            hmax_squared = diameter_squared;\n        }\n        if (diameter_squared < hmin_squared) {\n            hmin_squared = diameter_squared;\n        }\n    }\n\n    return std::make_pair(std::sqrt(hmin_squared), std::sqrt(hmax_squared));\n};\n\nMeshDetails details_from_meshes(const crest::IndexedMesh<double, int> & coarse,\n                                const crest::IndexedMesh<double, int> & fine)\n{\n    MeshDetails details;\n    details.num_coarse_elements = coarse.num_elements();\n    details.num_coarse_vertices = coarse.num_vertices();\n    details.num_fine_elements = fine.num_elements();\n    details.num_fine_vertices = fine.num_vertices();\n\n    std::tie(details.h_min_coarse, details.h_max_coarse) = extremal_diameters(coarse);\n    std::tie(details.h_min_fine, details.h_max_fine) = extremal_diameters(fine);\n\n    return details;\n}\n\nstruct ErrorSummary\n{\n    double l2;\n    double h1;\n    double h1_semi;\n\n    ErrorSummary & with_l2(double error)\n    {\n        this->l2 = error;\n        return *this;\n    }\n\n    ErrorSummary & with_h1(double error)\n    {\n        this->h1 = error;\n        return *this;\n    }\n\n    ErrorSummary & with_h1_semi(double error)\n    {\n        this->h1_semi = error;\n        return *this;\n    }\n};\n\nstruct OfflineTiming\n{\n    double mesh_construction;\n    double basis_construction;\n    double total;\n\n    OfflineTiming() : mesh_construction(0.0), basis_construction(0.0), total(0.0) {}\n};\n\nstruct OfflineResult\n{\n    MeshDetails mesh_details;\n    OfflineTiming timing;\n\n    std::unordered_map<std::string, crest::AccumulatedDensityHistogram> stats;\n\n    OfflineResult & with_mesh_details(MeshDetails mesh_details)\n    {\n        this->mesh_details = mesh_details;\n        return *this;\n    }\n\n    OfflineResult & with_timing(OfflineTiming timing)\n    {\n        this->timing = timing;\n        return *this;\n    }\n\n    OfflineResult & with_stats(std::unordered_map<std::string, crest::AccumulatedDensityHistogram> stats)\n    {\n        this->stats = stats;\n        return *this;\n    }\n};\n\ntypedef crest::wave::SolveTiming OnlineTiming;\n\nstruct OnlineResult\n{\n    ErrorSummary error_summary;\n    OnlineTiming timing;\n    bool converged;\n\n    OnlineResult & with_error_summary(ErrorSummary summary)\n    {\n        this->error_summary = summary;\n        return *this;\n    }\n\n    OnlineResult & with_timing(OnlineTiming timing)\n    {\n        this->timing = timing;\n        return *this;\n    }\n\n    OnlineResult & with_convergence(bool converged)\n    {\n        this->converged = converged;\n        return *this;\n    }\n\n    OnlineResult() : converged(false) {}\n};\n\nstruct ExperimentResult\n{\n    std::string                         name;\n    OfflineParameters                   offline_parameters;\n    boost::optional<OnlineParameters>   online_parameters;\n    OfflineResult                       offline_result;\n    boost::optional<OnlineResult>       online_result;\n\n    ExperimentResult & with_name(std::string name)\n    {\n        this->name = name;\n        return *this;\n    }\n\n    ExperimentResult & with_offline_parameters(OfflineParameters param)\n    {\n        this->offline_parameters = param;\n        return *this;\n    }\n\n    ExperimentResult & with_online_parameters(OnlineParameters param)\n    {\n        this->online_parameters = param;\n        return *this;\n    }\n\n    ExperimentResult & with_online_parameters(boost::optional<OnlineParameters> param)\n    {\n        this->online_parameters = param;\n        return *this;\n    }\n\n    ExperimentResult & with_offline_result(OfflineResult result)\n    {\n        this->offline_result = result;\n        return *this;\n    }\n\n    ExperimentResult & with_online_result(OnlineResult result)\n    {\n        this->online_result = result;\n        return *this;\n    }\n\n    ExperimentResult & with_online_result(boost::optional<OnlineResult> result)\n    {\n        this->online_result = result;\n        return *this;\n    }\n};\n\nvoid verify_parameter_validity(const OfflineParameters & parameters);\nvoid verify_parameter_validity(const OnlineParameters & parameters);\n\nclass Experiment\n{\npublic:\n    virtual ~Experiment() {}\n\n    OfflineResult run_offline(const OfflineParameters & parameters)\n    {\n        crest::Timer timer;\n        verify_parameter_validity(parameters);\n        auto result = solve_offline(parameters);\n        result.timing.total = timer.elapsed();\n        return result;\n    }\n\n    OnlineResult run_online(const OnlineParameters & parameters,\n                            crest::wave::Integrator<double> & integrator)\n    {\n        verify_parameter_validity(parameters);\n        return solve_online(parameters, integrator);\n    }\n\nprotected:\n    virtual OfflineResult solve_offline(const OfflineParameters & parameters) = 0;\n    virtual OnlineResult solve_online(const OnlineParameters & parameters,\n                                      crest::wave::Integrator<double> & integrator) = 0;\n\n    /**\n     * Helper function for implementing solve()\n     */\n    template <typename BasisImpl, typename Function2dt, typename Function2dt_x, typename Function2dt_y>\n    OnlineResult solve_and_analyze(const Function2dt & u,\n                                   const Function2dt_x & u_x,\n                                   const Function2dt_y & u_y,\n                                   const OnlineParameters & parameters,\n                                   const crest::Basis<double, BasisImpl> & basis,\n                                   const crest::wave::InitialConditions<double> & initial_conditions,\n                                   const crest::wave::ConstrainedSystem<double> & system,\n                                   crest::wave::Integrator<double> & integrator,\n                                   const crest::wave::Initializer<double> & initializer,\n                                   double assembly_time) const\n    {\n        const auto dt = parameters.dt();\n        crest::wave::Parameters<double> param;\n        param.num_samples = parameters.sample_count;\n        param.dt = dt;\n\n        if (parameters.measure_error) {\n            const auto error_transformer = crest::wave::make_error_transformer<4>(\n                    basis, u, u_x, u_y, parameters.max_error_before_abort);\n            auto result = crest::wave::solve(system, initial_conditions,\n                                             integrator, initializer, param, error_transformer);\n\n            // Augment the result with the given assembly time. Yes, I know, this is very hacky and\n            // very poorly designed (last minute additions)\n            result.timing.assembly_time = assembly_time;\n\n            if (result.converged) {\n\n\n                std::vector<double> l2_error_at_each_step;\n                std::vector<double> h1_semi_error_at_each_step;\n                std::vector<double> h1_error_at_each_step;\n\n                for (const auto sample_error : result.result)\n                {\n                    l2_error_at_each_step.push_back(sample_error.l2);\n                    h1_semi_error_at_each_step.push_back(sample_error.h1_semi);\n                    h1_error_at_each_step.push_back(sample_error.h1);\n                }\n\n                ErrorSummary errors;\n\n                switch (param.num_samples) {\n                    case 1:\n                        errors.h1 = h1_error_at_each_step.back();\n                        errors.l2 = l2_error_at_each_step.back();\n                        errors.h1_semi = h1_semi_error_at_each_step.back();\n                        break;\n\n                    default:\n                        // TODO: Support even number of samples. Simpsons will currently throw when it\n                        // is given an even number of samples\n                        errors.l2 = crest::composite_simpsons(l2_error_at_each_step.begin(),\n                                                              l2_error_at_each_step.end(),\n                                                              dt);\n                        errors.h1_semi = crest::composite_simpsons(h1_semi_error_at_each_step.begin(),\n                                                                   h1_semi_error_at_each_step.end(),\n                                                                   dt);\n                        errors.h1 = crest::composite_simpsons(h1_error_at_each_step.begin(),\n                                                              h1_error_at_each_step.end(),\n                                                              dt);\n                        break;\n                }\n\n                return OnlineResult()\n                        .with_error_summary(errors)\n                        .with_timing(result.timing)\n                        .with_convergence(result.converged);\n            } else {\n                // If the simulation did not converge, we do not want to compute an error at all,\n                // particularly because we might have an odd number of samples (in which case the above would throw)\n                // This last part is of course unfortunate, but I don't want to spend time on fixing that at the moment.\n                return OnlineResult()\n                        .with_timing(result.timing)\n                        .with_convergence(result.converged);\n            }\n\n        } else {\n            const auto ignore_transformer = crest::wave::IgnoreTransformer<double>();\n            auto result = crest::wave::solve(system, initial_conditions, integrator,\n                                             initializer, param, ignore_transformer);\n            // Augment the result with the given assembly time. Yes, I know, this is very hacky and\n            // very poorly designed (last minute additions)\n            result.timing.assembly_time = assembly_time;\n            return OnlineResult()\n                    .with_timing(result.timing)\n                    .with_convergence(result.converged);\n        };\n    };\n};\n\ninline void verify_parameter_validity(const OnlineParameters & parameters)\n{\n    if (parameters.end_time <= 0.0 || !std::isfinite(parameters.end_time))\n    {\n        throw std::invalid_argument(\"Final time T must be finite and greater than zero.\");\n    }\n\n    if (parameters.sample_count < 1) {\n        throw std::invalid_argument(\"Number of samples N must be 1 or greater.\");\n    }\n\n    if (parameters.sample_count % 2 == 0) {\n        throw std::invalid_argument(\"Number of samples must be an odd number.\");\n    }\n}\n\ninline void verify_parameter_validity(const OfflineParameters & parameters)\n{\n    if (parameters.mesh_resolution <= 0.0 || !std::isfinite(parameters.mesh_resolution))\n    {\n        throw std::invalid_argument(\"Spatial resolution h must be finite and greater than zero.\");\n    }\n}\n\n", "meta": {"hexsha": "6696720fe961126774a89398676e6cb8e1519468", "size": 15733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/experiments/experiment.hpp", "max_stars_repo_name": "Andlon/crest", "max_stars_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/experiments/experiment.hpp", "max_issues_repo_name": "Andlon/crest", "max_issues_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-01-24T10:45:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-27T16:21:37.000Z", "max_forks_repo_path": "tests/experiments/experiment.hpp", "max_forks_repo_name": "Andlon/crest", "max_forks_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.728515625, "max_line_length": 120, "alphanum_fraction": 0.6029365029, "num_tokens": 3169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.01826427641474289, "lm_q1q2_score": 0.007926357432053416}}
{"text": "// Copyright (c) 2020, Ryo Currency Project\n// Portions copyright (c) 2016, Monero Research Labs\n//\n// Author: Shen Noether <shen.noether@gmx.com>\n//\n// Portions of this file are available under BSD-3 license. Please see ORIGINAL-LICENSE for details\n// All rights reserved.\n//\n// Authors and copyright holders give permission for following:\n//\n// 1. Redistribution and use in source and binary forms WITHOUT modification.\n//\n// 2. Modification of the source form for your own personal use.\n//\n// As long as the following conditions are met:\n//\n// 3. You must not distribute modified copies of the work to third parties. This includes\n//    posting the work online, or hosting copies of the modified work for download.\n//\n// 4. Any derivative version of this work is also covered by this license, including point 8.\n//\n// 5. Neither the name of the copyright holders nor the names of the authors may be\n//    used to endorse or promote products derived from this software without specific\n//    prior written permission.\n//\n// 6. You agree that this licence is governed by and shall be construed in accordance\n//    with the laws of England and Wales.\n//\n// 7. You agree to submit all disputes arising out of or in connection with this licence\n//    to the exclusive jurisdiction of the Courts of England and Wales.\n//\n// Authors and copyright holders agree that:\n//\n// 8. This licence expires and the work covered by it is released into the\n//    public domain on 1st of February 2021\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 \"rctOps.h\"\n#include \"common/gulps.hpp\"\n#include <boost/lexical_cast.hpp>\nusing namespace crypto;\nusing namespace std;\n\n//undef RYO_DEFAULT_LOG_CATEGORY\n//#define RYO_DEFAULT_LOG_CATEGORY\n\n#define CHECK_AND_ASSERT_THROW_MES_L1(expr, ...) \\\n\t{                                                \\\n\t\tif(!(expr))                                  \\\n\t\t{                                            \\\n\t\t\tstd::string str;\t\\\n\t\t\tstr = stream_writer::write(__VA_ARGS__);\t\\\n\t\t\t{GULPS_CAT_MAJOR(\"rctOps\"); GULPS_WARN(str);}                       \\\n\t\t\tthrow std::runtime_error(str);       \\\n\t\t}                                            \\\n\t}\n\nnamespace rct\n{\n\n//Various key initialization functions\n\n//initializes a key matrix;\n//first parameter is rows,\n//second is columns\nkeyM keyMInit(size_t rows, size_t cols)\n{\n\tkeyM rv(cols);\n\tsize_t i = 0;\n\tfor(i = 0; i < cols; i++)\n\t{\n\t\trv[i] = keyV(rows);\n\t}\n\treturn rv;\n}\n\n//Various key generation functions\n\n//generates a random scalar which can be used as a secret key or mask\nvoid skGen(key &sk)\n{\n\trandom_scalar(sk.bytes);\n}\n\n//generates a random scalar which can be used as a secret key or mask\nkey skGen()\n{\n\tkey sk;\n\tskGen(sk);\n\treturn sk;\n}\n\n//Generates a vector of secret key\n//Mainly used in testing\nkeyV skvGen(size_t rows)\n{\n\tGULPS_CAT_MAJOR(\"rctOps\");\n\tGULPS_CHECK_AND_ASSERT_THROW_MES(rows > 0, \"0 keys requested\");\n\tkeyV rv(rows);\n\tfor(size_t i = 0; i < rows; i++)\n\t\tskGen(rv[i]);\n\treturn rv;\n}\n\n//generates a random curve point (for testing)\nkey pkGen()\n{\n\tkey sk = skGen();\n\tkey pk = scalarmultBase(sk);\n\treturn pk;\n}\n\n//generates a random secret and corresponding public key\nvoid skpkGen(key &sk, key &pk)\n{\n\tskGen(sk);\n\tscalarmultBase(pk, sk);\n}\n\n//generates a random secret and corresponding public key\ntuple<key, key> skpkGen()\n{\n\tkey sk = skGen();\n\tkey pk = scalarmultBase(sk);\n\treturn make_tuple(sk, pk);\n}\n\n//generates C =aG + bH from b, a is given..\nvoid genC(key &C, const key &a, ryo_amount amount)\n{\n\tkey bH = scalarmultH(d2h(amount));\n\taddKeys1(C, a, bH);\n}\n\n//generates a <secret , public> / Pedersen commitment to the amount\ntuple<ctkey, ctkey> ctskpkGen(ryo_amount amount)\n{\n\tctkey sk, pk;\n\tskpkGen(sk.dest, pk.dest);\n\tskpkGen(sk.mask, pk.mask);\n\tkey am = d2h(amount);\n\tkey bH = scalarmultH(am);\n\taddKeys(pk.mask, pk.mask, bH);\n\treturn make_tuple(sk, pk);\n}\n\n//generates a <secret , public> / Pedersen commitment but takes bH as input\ntuple<ctkey, ctkey> ctskpkGen(const key &bH)\n{\n\tctkey sk, pk;\n\tskpkGen(sk.dest, pk.dest);\n\tskpkGen(sk.mask, pk.mask);\n\taddKeys(pk.mask, pk.mask, bH);\n\treturn make_tuple(sk, pk);\n}\n\nkey zeroCommit(ryo_amount amount)\n{\n\tkey am = d2h(amount);\n\tkey bH = scalarmultH(am);\n\treturn addKeys(G, bH);\n}\n\nkey commit(ryo_amount amount, const key &mask)\n{\n\tkey c = scalarmultBase(mask);\n\tkey am = d2h(amount);\n\tkey bH = scalarmultH(am);\n\taddKeys(c, c, bH);\n\treturn c;\n}\n\n//generates a random uint long long (for testing)\nryo_amount randRyoAmount(ryo_amount upperlimit)\n{\n\treturn 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\nvoid scalarmultBase(key &aG, const key &a)\n{\n\tge_p3 point;\n\tsc_reduce32copy(aG.bytes, a.bytes); //do this beforehand!\n\tge_scalarmult_base(&point, aG.bytes);\n\tge_p3_tobytes(aG.bytes, &point);\n}\n\n//does a * G where a is a scalar and G is the curve basepoint\nkey scalarmultBase(const key &a)\n{\n\tge_p3 point;\n\tkey aG;\n\tsc_reduce32copy(aG.bytes, a.bytes); //do this beforehand\n\tge_scalarmult_base(&point, aG.bytes);\n\tge_p3_tobytes(aG.bytes, &point);\n\treturn aG;\n}\n\n//does a * P where a is a scalar and P is an arbitrary point\nvoid scalarmultKey(key &aP, const key &P, const key &a)\n{\n\tge_p3 A;\n\tge_p2 R;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, P.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_scalarmult(&R, a.bytes, &A);\n\tge_tobytes(aP.bytes, &R);\n}\n\n//does a * P where a is a scalar and P is an arbitrary point\nkey scalarmultKey(const key &P, const key &a)\n{\n\tge_p3 A;\n\tge_p2 R;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, P.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_scalarmult(&R, a.bytes, &A);\n\tkey aP;\n\tge_tobytes(aP.bytes, &R);\n\treturn aP;\n}\n\n//Computes 8P\nkey scalarmult8(const key & P)\n{\n\tge_p3 p3;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&p3, P.bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n\tge_p2 p2;\n\tge_p3_to_p2(&p2, &p3);\n\tge_p1p1 p1;\n\tge_mul8(&p1, &p2);\n\tge_p1p1_to_p2(&p2, &p1);\n\trct::key res;\n\tge_tobytes(res.bytes, &p2);\n\treturn res;\n}\n\n//Computes aH where H= toPoint(cn_fast_hash(G)), G the basepoint\nkey scalarmultH(const key &a)\n{\n\tge_p3 A;\n\tge_p2 R;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, H.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_scalarmult(&R, a.bytes, &A);\n\tkey aP;\n\tge_tobytes(aP.bytes, &R);\n\treturn aP;\n}\n\n//Curve addition / subtractions\n\n//for curve points: AB = A + B\nvoid addKeys(key &AB, const key &A, const key &B)\n{\n\tge_p3 B2, A2;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_cached tmp2;\n\tge_p3_to_cached(&tmp2, &B2);\n\tge_p1p1 tmp3;\n\tge_add(&tmp3, &A2, &tmp2);\n\tge_p1p1_to_p3(&A2, &tmp3);\n\tge_p3_tobytes(AB.bytes, &A2);\n}\n\nrct::key addKeys(const key &A, const key &B)\n{\n\tkey k;\n\taddKeys(k, A, B);\n\treturn k;\n}\n\nrct::key addKeys(const keyV &A)\n{\n\tif (A.empty())\n\t\treturn rct::identity();\n\n\tge_p3 p3, tmp;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&p3, A[0].bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n\tfor (size_t i = 1; i < A.size(); ++i)\n\t{\n\t\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&tmp, A[i].bytes) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n\t\tge_cached p2;\n\t\tge_p3_to_cached(&p2, &tmp);\n\t\tge_p1p1 p1;\n\t\tge_add(&p1, &p3, &p2);\n\t\tge_p1p1_to_p3(&p3, &p1);\n\t}\n\n\trct::key res;\n\tge_p3_tobytes(res.bytes, &p3);\n\treturn res;\n}\n\n//addKeys1\n//aGB = aG + B where a is a scalar, G is the basepoint, and B is a point\nvoid addKeys1(key &aGB, const key &a, const key &B)\n{\n\tkey aG = scalarmultBase(a);\n\taddKeys(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\nvoid addKeys2(key &aGbB, const key &a, const key &b, const key &B)\n{\n\tge_p2 rv;\n\tge_p3 B2;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_double_scalarmult_base_vartime(&rv, b.bytes, &B2, a.bytes);\n\tge_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\nvoid precomp(ge_dsmp rv, const key &B)\n{\n\tge_p3 B2;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_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\"\nvoid addKeys3(key &aAbB, const key &a, const key &A, const key &b, const ge_dsmp B)\n{\n\tge_p2 rv;\n\tge_p3 A2;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_double_scalarmult_precomp_vartime(&rv, a.bytes, &A2, b.bytes, B);\n\tge_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\"\nvoid addKeys3(key &aAbB, const key &a, const ge_dsmp A, const key &b, const ge_dsmp B)\n{\n\tge_p2 rv;\n\tge_double_scalarmult_precomp_vartime2(&rv, a.bytes, A, b.bytes, B);\n\tge_tobytes(aAbB.bytes, &rv);\n}\n\n//subtract Keys (subtracts curve points)\n//AB = A - B where A, B are curve points\nvoid subKeys(key &AB, const key &A, const key &B)\n{\n\tge_p3 B2, A2;\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_cached tmp2;\n\tge_p3_to_cached(&tmp2, &B2);\n\tge_p1p1 tmp3;\n\tge_sub(&tmp3, &A2, &tmp2);\n\tge_p1p1_to_p3(&A2, &tmp3);\n\tge_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\nbool equalKeys(const key &a, const key &b)\n{\n\tbool rv = true;\n\tfor(int i = 0; i < 32; ++i)\n\t{\n\t\tif(a.bytes[i] != b.bytes[i])\n\t\t{\n\t\t\trv = false;\n\t\t}\n\t}\n\treturn 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\nvoid cn_fast_hash(key &hash, const void *data, const std::size_t l)\n{\n\tkeccak((const uint8_t *)data, l, hash.bytes, 32);\n}\n\nvoid hash_to_scalar(key &hash, const void *data, const std::size_t l)\n{\n\tcn_fast_hash(hash, data, l);\n\tsc_reduce32(hash.bytes);\n}\n\n//cn_fast_hash for a 32 byte key\nvoid cn_fast_hash(key &hash, const key &in)\n{\n\tkeccak((const uint8_t *)in.bytes, 32, hash.bytes, 32);\n}\n\nvoid hash_to_scalar(key &hash, const key &in)\n{\n\tcn_fast_hash(hash, in);\n\tsc_reduce32(hash.bytes);\n}\n\n//cn_fast_hash for a 32 byte key\nkey cn_fast_hash(const key &in)\n{\n\tkey hash;\n\tkeccak((const uint8_t *)in.bytes, 32, hash.bytes, 32);\n\treturn hash;\n}\n\nkey hash_to_scalar(const key &in)\n{\n\tkey hash = cn_fast_hash(in);\n\tsc_reduce32(hash.bytes);\n\treturn hash;\n}\n\n//cn_fast_hash for a 128 byte unsigned char\nkey cn_fast_hash128(const void *in)\n{\n\tkey hash;\n\tkeccak((const uint8_t *)in, 128, hash.bytes, 32);\n\treturn hash;\n}\n\nkey hash_to_scalar128(const void *in)\n{\n\tkey hash = cn_fast_hash128(in);\n\tsc_reduce32(hash.bytes);\n\treturn 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\nkey cn_fast_hash(const ctkeyV &PC)\n{\n\tif(PC.empty())\n\t\treturn rct::hash2rct(crypto::cn_fast_hash(\"\", 0));\n\tkey rv;\n\tcn_fast_hash(rv, &PC[0], 64 * PC.size());\n\treturn rv;\n}\n\nkey hash_to_scalar(const ctkeyV &PC)\n{\n\tkey rv = cn_fast_hash(PC);\n\tsc_reduce32(rv.bytes);\n\treturn 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\nkey cn_fast_hash(const keyV &keys)\n{\n\tif(keys.empty())\n\t\treturn rct::hash2rct(crypto::cn_fast_hash(\"\", 0));\n\tkey rv;\n\tcn_fast_hash(rv, &keys[0], keys.size() * sizeof(keys[0]));\n\t//dp(rv);\n\treturn rv;\n}\n\nkey hash_to_scalar(const keyV &keys)\n{\n\tkey rv = cn_fast_hash(keys);\n\tsc_reduce32(rv.bytes);\n\treturn rv;\n}\n\nkey cn_fast_hash(const key64 keys)\n{\n\tkey rv;\n\tcn_fast_hash(rv, &keys[0], 64 * sizeof(keys[0]));\n\t//dp(rv);\n\treturn rv;\n}\n\nkey hash_to_scalar(const key64 keys)\n{\n\tkey rv = cn_fast_hash(keys);\n\tsc_reduce32(rv.bytes);\n\treturn rv;\n}\n\nkey hashToPointSimple(const key &hh)\n{\n\tkey pointk;\n\tge_p1p1 point2;\n\tge_p2 point;\n\tge_p3 res;\n\tkey h = cn_fast_hash(hh);\n\tCHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&res, h.bytes) == 0, \"ge_frombytes_vartime failed at \" + boost::lexical_cast<std::string>(__LINE__));\n\tge_p3_to_p2(&point, &res);\n\tge_mul8(&point2, &point);\n\tge_p1p1_to_p3(&res, &point2);\n\tge_p3_tobytes(pointk.bytes, &res);\n\treturn pointk;\n}\n\nkey hashToPoint(const key &hh)\n{\n\tkey pointk;\n\tge_p2 point;\n\tge_p1p1 point2;\n\tge_p3 res;\n\tkey h = cn_fast_hash(hh);\n\tge_fromfe_frombytes_vartime(&point, h.bytes);\n\tge_mul8(&point2, &point);\n\tge_p1p1_to_p3(&res, &point2);\n\tge_p3_tobytes(pointk.bytes, &res);\n\treturn pointk;\n}\n\nvoid hashToPoint(key &pointk, const key &hh)\n{\n\tge_p2 point;\n\tge_p1p1 point2;\n\tge_p3 res;\n\tkey h = cn_fast_hash(hh);\n\tge_fromfe_frombytes_vartime(&point, h.bytes);\n\tge_mul8(&point2, &point);\n\tge_p1p1_to_p3(&res, &point2);\n\tge_p3_tobytes(pointk.bytes, &res);\n}\n\n//sums a vector of curve points (for scalars use sc_add)\nvoid sumKeys(key &Csum, const keyV &Cis)\n{\n\tidentity(Csum);\n\tsize_t i = 0;\n\tfor(i = 0; i < Cis.size(); i++)\n\t{\n\t\taddKeys(Csum, Csum, Cis[i]);\n\t}\n}\n\n//Elliptic Curve Diffie Helman: encodes and decodes the amount b and mask a\n// where C= aG + bH\nvoid ecdhEncode(ecdhTuple &unmasked, const key &sharedSec)\n{\n\tkey sharedSec1 = hash_to_scalar(sharedSec);\n\tkey sharedSec2 = hash_to_scalar(sharedSec1);\n\t//encode\n\tsc_add(unmasked.mask.bytes, unmasked.mask.bytes, sharedSec1.bytes);\n\tsc_add(unmasked.amount.bytes, unmasked.amount.bytes, sharedSec2.bytes);\n}\nvoid ecdhDecode(ecdhTuple &masked, const key &sharedSec)\n{\n\tkey sharedSec1 = hash_to_scalar(sharedSec);\n\tkey sharedSec2 = hash_to_scalar(sharedSec1);\n\t//decode\n\tsc_sub(masked.mask.bytes, masked.mask.bytes, sharedSec1.bytes);\n\tsc_sub(masked.amount.bytes, masked.amount.bytes, sharedSec2.bytes);\n}\n}\n", "meta": {"hexsha": "40c356f3b809650458d7e46b8ad6a7761f84c794", "size": 15405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ringct/rctOps.cpp", "max_stars_repo_name": "isajediknight/ryo-currency", "max_stars_repo_head_hexsha": "166cf188bf351e3eecff904450eda2785f9d0357", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 107.0, "max_stars_repo_stars_event_min_datetime": "2018-07-03T19:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T09:05:44.000Z", "max_issues_repo_path": "src/ringct/rctOps.cpp", "max_issues_repo_name": "isajediknight/ryo-currency", "max_issues_repo_head_hexsha": "166cf188bf351e3eecff904450eda2785f9d0357", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 87.0, "max_issues_repo_issues_event_min_datetime": "2018-06-25T14:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T08:15:47.000Z", "max_forks_repo_path": "src/ringct/rctOps.cpp", "max_forks_repo_name": "isajediknight/ryo-currency", "max_forks_repo_head_hexsha": "166cf188bf351e3eecff904450eda2785f9d0357", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2018-06-25T05:41:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T08:57:37.000Z", "avg_line_length": 27.2173144876, "max_line_length": 155, "alphanum_fraction": 0.7069133398, "num_tokens": 4811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.023689470696257528, "lm_q1q2_score": 0.007926246763844529}}
{"text": "#ifndef GEODB_ALGORITHM_HPP\n#define GEODB_ALGORITHM_HPP\n\n#include \"geodb/common.hpp\"\n\n#include <boost/range/concepts.hpp>\n#include <boost/range/metafunctions.hpp>\n#include <boost/range/sub_range.hpp>\n\n#include <algorithm>\n#include <map>\n#include <queue>\n#include <vector>\n\n/// \\file\n/// Some generic algorithms.\n\nnamespace geodb {\n\n/// Invokes the function `f` for every token in `r`.\n/// The end of a token is reached when\n///     - the end of the range was encountered\n///     - the predicate `p' returns `true`\n///\n/// `p` will be invoked with the iterator to the current element,\n/// which is always valid.\n///\n/// `f` will be invoked for each token with an argument of type\n/// `boost::sub_range<Range>`.\ntemplate<typename Range, typename Predicate, typename Function>\nvoid for_each_token_if(Range&& r, Predicate&& p, Function&& f) {\n    using iterator = typename boost::range_iterator<Range>::type;\n    using sub_range = boost::sub_range<Range>;\n\n    iterator first = boost::begin(r);\n    iterator last = boost::end(r);\n    if (first == last)\n        return;\n\n    while (1) {\n        // There is at least one more token, although it may be empty.\n        auto pos = first;\n\n        // Find the end of the current token.\n        // This is either the end of the range or the item\n        // for which p returns true.\n        // If p returns true, at least one more token must follow.\n        while (1) {\n            if (pos == last) {\n                f(sub_range(first, pos));\n                return;\n            }\n            if (p(pos)) {\n                f(sub_range(first, pos));\n                ++pos; // skip separator in output.\n                break;\n            }\n            ++pos;\n        }\n\n        first = pos;\n    }\n}\n\n/// Invokes the function `f` for every token in `r`.\n/// Tokens are separated by the seperator element.\ntemplate<typename Range, typename Function>\nvoid for_each_token(Range&& r, typename boost::range_value<Range>::type separator, Function&& f) {\n    auto predicate = [&](const auto& iter) {\n        return *iter == separator;\n    };\n    return for_each_token_if(std::forward<Range>(r), predicate, std::forward<Function>(f));\n}\n\n/// Takes the `k` smallest entries (according to `cmp`) and puts then into `out`.\n/// The first `k` elements of `out` will be in sorted order.\n/// Runtime complexity: O(n * log(k)) comparisons.\n///\n/// \\pre `k > 0`.\n/// \\pre `r` must have at least `k` elements.\n/// \\pre `out` must have space for `k` elements.\ntemplate<typename Range, typename OutRange, typename Compare>\nvoid k_smallest(Range&& r, size_t k, OutRange& out, Compare&& cmp) {\n    BOOST_CONCEPT_ASSERT(( boost::RandomAccessRangeConcept<OutRange> ));\n\n    geodb_assert(k > 0, \"invalid k\");\n    geodb_assert(boost::size(out) >= k, \"out range too small\");\n\n    auto heap_first = boost::begin(out);\n    auto heap_last = heap_first + k;\n\n    auto first = boost::const_begin(r);\n    auto last = boost::const_end(r);\n\n    // Push first k elements into the output heap.\n    // Invariant: heap stores the k smallest elements in\n    // the visited part of the range.\n    {\n        auto first_k = first + k;\n        std::copy(first, first_k, heap_first);\n        std::make_heap(heap_first, heap_last, cmp);\n        first = first_k;\n    }\n\n    // If the next element is smaller than the max,\n    // then replace the max with it. Otherwise: the element is\n    // definitely not among the smallest k.\n    for (; first != last; ++first) {\n        if(cmp(*first, *heap_first)) {\n            std::pop_heap(heap_first, heap_last, cmp);\n            heap_last[-1] = *first;\n            std::push_heap(heap_first, heap_last, cmp);\n        }\n    }\n    std::sort_heap(heap_first, heap_last, cmp);\n}\n\n/// Uses `operator<` for comparisons.\ntemplate<typename Range, typename OutRange>\nvoid k_smallest(Range&& r, size_t k, OutRange&& out) {\n    k_smallest(r, k, out, std::less<>());\n}\n\n/// Invokes the function object `f` for every pair of adjacent elements\n/// in `r`.\n///\n/// For example, if `r = [1, 2, 3]`, this algorithm will\n/// call `f(1, 2)` and `f(2, 3)`.\ntemplate<typename FwdRange, typename Function>\nvoid for_each_adjacent(FwdRange&& r, Function&& f) {\n    BOOST_CONCEPT_ASSERT(( boost::ForwardRangeConcept<FwdRange> ));\n\n    auto current = boost::begin(r);\n    auto last = boost::end(r);\n\n    if (current != last) {\n        auto previous = current;\n        ++current;\n        for (; current != last; ++current, ++previous) {\n            f(*previous, *current);\n        }\n    }\n}\n\n/// Iterate over a range of ranges and treat their elements\n/// as one large, contiguous sequence.\n/// The elements will be visited in sorted order.\n///\n/// Uses a binary heap internally to track the position in each\n/// range and thus uses O(m) additional space (where m is the number of ranges).\n/// The algorithm thus takes O(n * log m) time, where n is the number of total\n/// elements over all ranges.\n///\n/// \\param ranges\n///     A range of ranges. Every individual range must be sorted.\n/// \\param fn\n///     A function that will be invoked for every element in the ranges.\n/// \\param comp\n///     A comparison function to compare individual elements of the ranges.\n///     Defaults to std::less.\ntemplate<typename Ranges, typename Function, typename Comp = std::less<>>\nvoid for_each_sorted(const Ranges& ranges, Function&& fn, Comp&& comp = Comp()) {\n    using nested_range = typename boost::range_value<const Ranges>::type;\n    using nested_iterator = typename boost::range_const_iterator<nested_range>::type;\n\n    static_assert(std::is_lvalue_reference<typename boost::range_reference<const Ranges>::type>::value,\n                  \"nested ranges must be lvalues (i.e. no temporaries).\");\n\n    struct cursor {\n        nested_iterator current;\n        nested_iterator end;\n\n        cursor(nested_iterator current, nested_iterator end)\n            : current(current), end(end)\n        {}\n    };\n\n    struct cursor_compare {\n        Comp& value_comp;\n\n        cursor_compare(Comp& value_comp): value_comp(value_comp) {}\n\n        bool operator()(const cursor& a, const cursor& b) const {\n            return value_comp(*b.current, *a.current);\n        }\n    };\n\n    auto heap = [&]{\n        std::vector<cursor> cursors;\n        cursors.reserve(boost::size(ranges));\n\n        // Add a cursor for every range.\n        for (auto&& range : ranges) {\n            cursor c(boost::const_begin(range), boost::const_end(range));\n            if (c.current != c.end) {\n                cursors.push_back(std::move(c));\n            }\n        }\n        return std::priority_queue<cursor,\n                std::vector<cursor>,\n                cursor_compare>(cursor_compare(comp), std::move(cursors));\n    }();\n\n    // Read the min value until we have seen everything.\n    while (!heap.empty()) {\n        cursor c = heap.top();\n        heap.pop();\n\n        fn(*c.current);\n        ++c.current;\n        if (c.current != c.end) {\n            heap.push(std::move(c));\n        }\n    }\n}\n\n/// Creates a map of groups and their values.\n/// All elements with the same key value will be put into the same group.\n/// Relative order of elements within a group is preserved.\n///\n/// \\param r        The input range.\n/// \\param key      A function that maps an element of `r` to a key value.\n///\n/// \\return         A `map<key_type, std::vector<value_type>>` where `key_type`\n///                 is the return type of `key`.\ntemplate<typename Range, typename KeyFunc>\nauto group_by_key(Range&& r, KeyFunc&& key) {\n    using value_type = typename boost::range_value<Range>::type;\n    using key_type = decltype(key(std::declval<const value_type&>()));\n\n    std::map<key_type, std::vector<value_type>> result;\n    for (const auto& item : r) {\n        result[key(item)].push_back(item);\n    }\n    return result;\n}\n\n/// Assign a range to a container.\ntemplate<typename Container, typename Range>\nvoid assign(Container&& c, const Range& r) {\n    c.assign(boost::begin(r), boost::end(r));\n}\n\n/// Append a range to a container.\ntemplate<typename Container, typename Range>\nvoid append(Container&& c, const Range& r) {\n    c.insert(c.end(), boost::begin(r), boost::end(r));\n}\n\n/// True iff `r` contains `t`.\ntemplate<typename Range, typename T>\nbool contains(const Range& r, const T& t) {\n    return std::find(boost::begin(r), boost::end(r), t) != boost::end(r);\n}\n\n/// True iff `p(x)` is true for every element `x` of `r`.\ntemplate<typename Range, typename Predicate>\nbool all_of(const Range& r, Predicate p) {\n    return std::any_of(boost::begin(r), boost::end(r), p);\n}\n\n/// Copy the contents of the given range into a new vector.\ntemplate<typename Range>\nstd::vector<typename boost::range_value<Range>::type> to_vector(const Range& r) {\n    return std::vector<typename boost::range_value<Range>::type>(boost::begin(r), boost::end(r));\n}\n\n/// Removes the element at position `pos` from the vector `v`\n/// by swapping the last element of `v` into the position\n/// and decreasing the size of the vector.\n/// In other words, the order of elements will not be maintained.\n///\n/// \\pre `pos` points to an element, i.e. it is not `v.end()`.\ntemplate<typename Vector>\nvoid fast_remove(Vector&& v, typename Vector::iterator pos) {\n    geodb_assert(pos != v.end(), \"trying to remove the end iterator\");\n    goedb_assert(!v.empty(), \"trying to remove from an empty vector\");\n    const auto last = v.end() - 1;\n    if (pos != last) {\n        std::iter_swap(pos, last);\n    }\n    v.pop_back();\n}\n\n} // namespace geodb\n\n#endif // GEODB_ALGORITHM_HPP\n", "meta": {"hexsha": "c145b776d8bdae74839ad25bb7f8212ea6f8b204", "size": 9507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/geodb/algorithm.hpp", "max_stars_repo_name": "mbeckem/msc", "max_stars_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_stars_repo_licenses": ["MIT"], "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/geodb/algorithm.hpp", "max_issues_repo_name": "mbeckem/msc", "max_issues_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_issues_repo_licenses": ["MIT"], "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/geodb/algorithm.hpp", "max_forks_repo_name": "mbeckem/msc", "max_forks_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_forks_repo_licenses": ["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.0104166667, "max_line_length": 103, "alphanum_fraction": 0.6310087304, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656316, "lm_q2_score": 0.04813677572530268, "lm_q1q2_score": 0.00791929207757194}}
{"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_TRIANGLE_COUNT_HPP_INCLUDED\n#define HAVOQGT_MPI_TRIANGLE_COUNT_HPP_INCLUDED\n\n#include <algorithm>\n#include <boost/container/deque.hpp>\n#include <fstream>\n#include <havoqgt/visitor_queue.hpp>\n#include <utility>\n//#include <boost/container/flat_map.hpp>\n#include <map>\n#include <unordered_map>\n\nnamespace havoqgt {\n\nstruct dogr_edge {\n  uint32_t target_degree       = 0;\n  uint32_t edge_triangle_count = 0;\n  bool     is_j                = false;\n};\n\ntemplate <typename Visitor>\nclass lifo_queue {\n protected:\n  std::vector<Visitor> m_data;\n\n public:\n  lifo_queue() {}\n\n  bool push(Visitor const& task) {\n    m_data.push_back(task);\n    return true;\n  }\n\n  void pop() { m_data.pop_back(); }\n\n  Visitor const& top()  // const\n  {\n    return m_data.back();\n  }\n\n  size_t size() const {\n    return m_data.size();\n    ;\n  }\n\n  bool empty() const { return m_data.empty(); }\n\n  void clear() { m_data.clear(); }\n};\n\ntemplate <typename Graph>\nclass core2_visitor {\n public:\n  typedef core2_visitor<Graph>           my_type;\n  typedef typename Graph::vertex_locator vertex_locator;\n\n  core2_visitor() : vertex(), init(true) {}\n\n  core2_visitor(vertex_locator v) : vertex(v), init(true) {}\n\n  core2_visitor(vertex_locator v, bool _init) : vertex(v), init(_init) {}\n\n  template <typename AlgData>\n  bool pre_visit(AlgData& alg_data) const {\n    if (vertex.is_delegate()) {\n      if (!vertex.is_delegate_master()) {\n        return true;\n      }\n    }\n    if (std::get<1>(alg_data)[vertex]) {\n      --(std::get<0>(alg_data)[vertex]);\n\n      if (std::get<0>(alg_data)[vertex] < 2) {\n        // remove from 2 core\n        std::get<1>(alg_data)[vertex] = false;\n        std::get<0>(alg_data)[vertex] = 0;\n        return true;\n      }\n    }\n\n    // Retrun true if alive\n    // return std::get<1>(alg_data)[vertex];\n    return false;\n  }\n\n  template <typename VisitorQueueHandle, typename AlgData>\n  bool init_visit(Graph& g, VisitorQueueHandle vis_queue,\n                  AlgData& alg_data) const {\n    if (std::get<1>(alg_data)[vertex]) {\n      //   --(std::get<0>(alg_data)[vertex]);\n      if (std::get<0>(alg_data)[vertex] < 2) {\n        // remove from 2 core\n        std::get<1>(alg_data)[vertex] = false;\n        std::get<0>(alg_data)[vertex] = 0;\n        for (auto eitr = g.edges_begin(vertex); eitr != g.edges_end(vertex);\n             ++eitr) {\n          vertex_locator neighbor = eitr.target();\n          my_type        new_visitor(neighbor, false);\n          vis_queue->queue_visitor(new_visitor);\n        }\n      }\n      return true;\n    }\n    return false;\n  }\n\n  template <typename VisitorQueueHandle, typename AlgData>\n  bool visit(Graph& g, VisitorQueueHandle vis_queue, AlgData& alg_data) const {\n    if (init) {\n      if (std::get<0>(alg_data)[vertex] < 2) {\n        // remove from 2 core\n        std::get<1>(alg_data)[vertex] = false;\n        std::get<0>(alg_data)[vertex] = 0;\n        for (auto eitr = g.edges_begin(vertex); eitr != g.edges_end(vertex);\n             ++eitr) {\n          vertex_locator neighbor = eitr.target();\n          my_type        new_visitor(neighbor, false);\n          vis_queue->queue_visitor(new_visitor);\n        }\n      }\n      return true;\n    }\n\n    if (std::get<1>(alg_data)[vertex]) {\n      std::cerr << \"LOGIC ERROR\" << std::endl;\n      exit(-1);\n    }\n    // if(std::get<1>(alg_data)[vertex]) {\n    //  --(std::get<0>(alg_data)[vertex]);\n    //  if(std::get<0>(alg_data)[vertex] < 2) {\n    //    //remove from 2 core\n    //    std::get<1>(alg_data)[vertex] = false;\n    //    std::get<0>(alg_data)[vertex] = 0;\n    for (auto eitr = g.edges_begin(vertex); eitr != g.edges_end(vertex);\n         ++eitr) {\n      vertex_locator neighbor = eitr.target();\n      my_type        new_visitor(neighbor, false);\n      vis_queue->queue_visitor(new_visitor);\n    }\n    //  }\n    //  return true;\n    //}\n    // return false;\n    return true;\n  }\n\n  friend inline bool operator>(const core2_visitor& v1,\n                               const core2_visitor& v2) {\n    return false;\n  }\n\n  friend inline bool operator<(const core2_visitor& v1,\n                               const core2_visitor& v2) {\n    return false;\n  }\n\n  vertex_locator vertex;\n  bool           init;\n};\n\ntemplate <typename Graph>\nclass directed_core2 {\n public:\n  typedef directed_core2<Graph>          my_type;\n  typedef typename Graph::vertex_locator vertex_locator;\n\n  directed_core2() : vertex(), init(true) {}\n\n  directed_core2(vertex_locator v) : vertex(v), init(true) {}\n\n  directed_core2(vertex_locator v, vertex_locator _from, uint32_t _from_degree)\n      : vertex(v), from_label(_from), from_degree(_from_degree), init(false) {}\n\n  template <typename AlgData>\n  bool pre_visit(AlgData& alg_data) const {\n    // if(std::get<0>(alg_data)[vertex] >= 2) {\n    if (from_degree >= std::get<2>(alg_data).degree(\n                           vertex) /*std::get<0>(alg_data)[vertex]*/) {\n      // previously returned true, but changing here --- return true;\n      if (vertex.is_delegate()) {\n        if (!vertex.is_delegate_master()) {\n          return true;\n        }\n      }\n      if (/*std::get<0>(alg_data)[vertex]*/ std::get<2>(alg_data).degree(\n              vertex) < 2)\n        return false;\n      // only here should be low-degree & masters\n      if (from_degree > std::get<2>(alg_data).degree(\n                            vertex) /*std::get<0>(alg_data)[vertex]*/\n          || (from_degree ==\n                  std::get<2>(alg_data).degree(\n                      vertex) /*std::get<0>(alg_data)[vertex]*/\n              && vertex < from_label)) {\n        auto vv = vertex;\n        vv.set_bcast(0);\n        vv.set_intercept(0);\n        auto fl = from_label;\n        fl.set_bcast(0);\n        fl.set_intercept(0);\n\n        std::get<1>(alg_data)[vv][fl].target_degree = from_degree;\n        // std::get<1>(alg_data)[vv].add(fl, dogr_edge{from_degree, 0, 0});\n        // attempting to replicate dogr graph\n        if (vertex.is_delegate()) {\n          if (vertex.is_delegate_master()) {\n            return true;\n          }\n        }\n      }\n    }\n    //}\n    return false;\n  }\n\n  template <typename VisitorQueueHandle, typename AlgData>\n  bool init_visit(Graph& g, VisitorQueueHandle vis_queue,\n                  AlgData& alg_data) const {\n    if (/*std::get<0>(alg_data)[vertex]*/ g.degree(vertex) >= 2) {\n      // if in 2core, send degree to neighbors\n      uint32_t my_degree = /*std::get<0>(alg_data)[vertex];*/ g.degree(vertex);\n      for (auto eitr = g.edges_begin(vertex); eitr != g.edges_end(vertex);\n           ++eitr) {\n        vertex_locator neighbor = eitr.target();\n        if (neighbor == vertex) continue;\n        my_type new_visitor(neighbor, vertex, my_degree);\n        vis_queue->queue_visitor(new_visitor);\n      }\n      return true;\n    }\n    return false;\n  }\n\n  template <typename VisitorQueueHandle, typename AlgData>\n  bool visit(Graph& g, VisitorQueueHandle vis_queue, AlgData& alg_data) const {\n    if (init) {\n      if (/*std::get<0>(alg_data)[vertex]*/ g.degree(vertex) >= 2) {\n        // if in 2core, send degree to neighbors\n        uint32_t my_degree =\n            /*std::get<0>(alg_data)[vertex];*/ g.degree(vertex);\n        for (auto eitr = g.edges_begin(vertex); eitr != g.edges_end(vertex);\n             ++eitr) {\n          vertex_locator neighbor = eitr.target();\n          if (neighbor == vertex) continue;\n          my_type new_visitor(neighbor, vertex, my_degree);\n          vis_queue->queue_visitor(new_visitor);\n        }\n        return true;\n      } else {\n        return false;\n      }\n    } else {\n      auto vv = vertex;\n      vv.set_bcast(0);\n      vv.set_intercept(0);\n      auto fl = from_label;\n      fl.set_bcast(0);\n      fl.set_intercept(0);\n\n      std::get<1>(alg_data)[vv][fl].target_degree = from_degree;\n      // std::get<1>(alg_data)[vv].add(fl, dogr_edge{from_degree, 0, 0});\n      return true;\n    }\n\n    //    if(from_degree > g.degree(vertex) /*std::get<0>(alg_data)[vertex]*/ ||\n    //      (from_degree == g.degree(vertex)/*std::get<0>(alg_data)[vertex]*/ &&\n    //      vertex < from_label )) {\n    //\n    //      auto vv = vertex;\n    //      vv.set_bcast(0);\n    //      vv.set_intercept(0);\n    //      auto fl = from_label;\n    //      fl.set_bcast(0);\n    //      fl.set_intercept(0);\n    //\n    //      std::get<1>(alg_data)[vv][fl] = from_degree;\n    //    }\n    // return false;\n  }\n\n  friend inline bool operator>(const directed_core2& v1,\n                               const directed_core2& v2) {\n    return false;\n  }\n\n  friend inline bool operator<(const directed_core2& v1,\n                               const directed_core2& v2) {\n    return false;\n  }\n\n  vertex_locator vertex;\n  vertex_locator from_label;\n  uint32_t       from_degree;\n  bool           init;\n};\n\ntemplate <typename Graph>\nclass core2_wedges {\n public:\n  typedef core2_wedges<Graph>            my_type;\n  typedef typename Graph::vertex_locator vertex_locator;\n\n  core2_wedges() : vertex() {}\n\n  core2_wedges(vertex_locator v) : vertex(v) {}\n\n  core2_wedges(vertex_locator v, vertex_locator _check_close,\n               vertex_locator _from_vertex, bool _do_check_close)\n      : vertex(v),\n        check_close(_check_close),\n        from_vertex(_from_vertex),\n        do_check_close(_do_check_close) {}\n\n  template <typename AlgData>\n  bool pre_visit(AlgData& alg_data) const {\n    if (vertex.is_delegate()) {\n      if (vertex.is_delegate_master()) {\n        if (do_check_close) {\n          ++std::get<2>(alg_data);\n          ++std::get<3>(alg_data);\n          // std::get<3>(alg_data) <<\n          // std::get<4>(alg_data).locator_to_label(vertex) << \" \" <<\n          // check_close\n          // << std::endl;\n          // std::get<4>(alg_data)[vertex]++;\n          if (std::get<0>(alg_data)[vertex].count(check_close) > 0) {\n            ++std::get<1>(alg_data);\n            // std::get<5>(alg_data)[vertex]++;\n            // std::cout << \"FOUND\" << std::endl;\n            std::get<0>(alg_data)[vertex][check_close].edge_triangle_count++;\n            std::get<0>(alg_data)[vertex][check_close].is_j = true;\n            return true;  /// now returning true to count\n          }\n        } else {  // already found, edge counting\n          if (std::get<0>(alg_data)[vertex].count(check_close) == 0 ||\n              std::get<0>(alg_data)[vertex].count(from_vertex) == 0) {\n            std::cerr << \"Error in edge counting\" << std::endl;\n          }\n        }\n        return false;\n      } else {\n        if (do_check_close) {\n          if (std::get<0>(alg_data)[vertex].count(check_close) == 0) {\n            ++std::get<4>(alg_data);\n            // std::cout << \"Skipped via replication\" << std::endl;\n            // exit(-1);\n            return false;\n          }\n        }\n        return true;\n      }\n    }\n    if (do_check_close) {\n      ++std::get<2>(alg_data);\n      // std::get<4>(alg_data)[vertex]++;\n      // std::get<3>(alg_data) << std::get<4>(alg_data).locator_to_label(vertex)\n      // << \" \" << check_close << std::endl;\n      if (std::get<0>(alg_data)[vertex].count(check_close) > 0) {\n        ++std::get<1>(alg_data);\n        // std::get<5>(alg_data)[vertex]++;\n        // std::cout << \"FOUND\" << std::endl;\n        std::get<0>(alg_data)[vertex][check_close].edge_triangle_count++;\n        std::get<0>(alg_data)[vertex][check_close].is_j = true;\n        return true;\n      }\n    } else {  // already found, edge counting\n      if (std::get<0>(alg_data)[vertex].count(check_close) == 0 ||\n          std::get<0>(alg_data)[vertex].count(from_vertex) == 0) {\n        std::cerr << \"Error in edge counting\" << std::endl;\n      } else {\n        std::get<0>(alg_data)[vertex][check_close].edge_triangle_count++;\n        std::get<0>(alg_data)[vertex][from_vertex].edge_triangle_count++;\n      }\n    }\n    return false;\n  }\n\n  template <typename VisitorQueueHandle, typename AlgData>\n  bool init_visit(Graph& g, VisitorQueueHandle vis_queue,\n                  AlgData& alg_data) const {\n    if (std::get<0>(alg_data)[vertex].size() > 1) {\n      for (const auto& pair_a : std::get<0>(alg_data)[vertex]) {\n        for (const auto& pair_b : std::get<0>(alg_data)[vertex]) {\n          if (pair_a.second.target_degree < pair_b.second.target_degree ||\n              (pair_a.second.target_degree == pair_b.second.target_degree &&\n               pair_a.first < pair_b.first)) {\n            my_type new_visitor(pair_a.first, pair_b.first, vertex, true);\n            vis_queue->queue_visitor(new_visitor);\n            // std::get<3>(alg_data)[vertex]++;\n            // fake ++std::get<1>(alg_data);  //fake counting here\n          }\n        }\n      }\n      /*for(auto itr_i = std::get<0>(alg_data)[vertex].begin(); itr_i !=\n      std::get<0>(alg_data)[vertex].end(); ++itr_i) {\n        for(auto itr_j = itr_i+1; itr_j != std::get<0>(alg_data)[vertex].end();\n      ++itr_j) {\n          auto pair_a = *itr_i;\n          auto pair_b = *itr_j;\n          if(pair_a.second < pair_b.second ||\n            (pair_a.second == pair_b.second && pair_a.first < pair_b.first)) {\n              my_type new_visitor(g.label_to_locator(pair_a.first),\n      pair_b.first);\n              //vis_queue->queue_visitor(new_visitor);\n              ++std::get<1>(alg_data);  //fake counting here\n          } else {\n            my_type new_visitor(g.label_to_locator(pair_b.first), pair_a.first);\n            //vis_queue->queue_visitor(new_visitor);\n             ++std::get<1>(alg_data);  //fake counting here\n          }\n        }\n      }*/\n\n      //        ++std::get<1>(alg_data);  //fake counting here\n    }\n    return false;\n  }\n\n  template <typename VisitorQueueHandle, typename AlgData>\n  bool visit(Graph& g, VisitorQueueHandle vis_queue, AlgData& alg_data) const {\n    if (do_check_close) {\n      my_type new_visitor(from_vertex, check_close, vertex, false);\n      vis_queue->queue_visitor(new_visitor);\n      return false;\n    }\n    std::cout << \"Shoudn't be here\" << std::endl;\n    exit(-1);\n    /*    ++std::get<2>(alg_data);\n        std::get<3>(alg_data) << g.locator_to_label(vertex) << \" \" <<\n       check_close << std::endl;\n        if(std::get<0>(alg_data)[vertex].count(check_close) > 0) {\n          ++std::get<1>(alg_data);\n          //std::cout << \"FOUND\" << std::endl;\n        }\n        return false;*/\n  }\n\n  friend inline bool operator>(const core2_wedges& v1, const core2_wedges& v2) {\n    return false;\n  }\n\n  friend inline bool operator<(const core2_wedges& v1, const core2_wedges& v2) {\n    return false;\n  }\n\n  vertex_locator vertex;\n  vertex_locator check_close;\n  vertex_locator from_vertex;\n  bool           do_check_close;\n};\n\nvoid output_degree_distribution(\n    const std::map<uint64_t, uint64_t>& local_degree_count, const char* fname) {\n  int mpi_size(0), mpi_rank(0);\n  CHK_MPI(MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank));\n  CHK_MPI(MPI_Comm_size(MPI_COMM_WORLD, &mpi_size));\n\n  std::vector<std::vector<std::pair<uint64_t, uint64_t>>> send_p_vec(mpi_size);\n  std::vector<std::vector<std::pair<uint64_t, uint64_t>>> recv_p_vec(mpi_size);\n  for (auto deg_cnt : local_degree_count) {\n    send_p_vec[deg_cnt.first % uint64_t(mpi_size)].push_back(deg_cnt);\n  }\n\n  mpi_all_to_all(send_p_vec, recv_p_vec, MPI_COMM_WORLD);\n\n  std::map<uint64_t, uint64_t> partitioned_deg_count;\n  for (auto& vec_deg_cnt : recv_p_vec) {\n    for (auto deg_cnt : vec_deg_cnt) {\n      partitioned_deg_count[deg_cnt.first] += deg_cnt.second;\n    }\n  }\n\n  //\n  // Send all to Rank 0 -- this is not efficient way\n  send_p_vec.clear();\n  send_p_vec.resize(mpi_size);\n  recv_p_vec.clear();\n  recv_p_vec.resize(mpi_size);\n  for (auto vec_deg_cnt : partitioned_deg_count) {\n    send_p_vec[0].push_back(vec_deg_cnt);\n  }\n  mpi_all_to_all(send_p_vec, recv_p_vec, MPI_COMM_WORLD);\n\n  if (mpi_rank == 0) {\n    std::vector<std::pair<uint64_t, uint64_t>> all_sorted;\n    for (auto& vec_deg_cnt : recv_p_vec) {\n      for (auto deg_cnt : vec_deg_cnt) {\n        all_sorted.push_back(deg_cnt);\n      }\n    }\n    std::sort(all_sorted.begin(), all_sorted.end());\n    std::ofstream outfile(fname);\n    for (auto deg_cnt : all_sorted) {\n      outfile << deg_cnt.first << \"\\t\" << deg_cnt.second << std::endl;\n    }\n  }\n  MPI_Barrier(MPI_COMM_WORLD);\n}\nstruct vertex_locator_hash {\n  template <typename T>\n  std::size_t operator()(const T& k) const {\n    return k.hash();\n  }\n};\n\ntemplate <typename K, typename V>\nclass lazy_flat_map {\n  using data = std::pair<K, V>;\n  // struct data {\n  //   K key;\n  //   V value;\n  // };  // __attribute__((packed));\n\n public:\n  lazy_flat_map() { m_sorted = true; }\n\n  typename std::vector<data>::iterator begin() {\n    do_sort();\n    return m_data.begin();\n  }\n  typename std::vector<data>::iterator end() { return m_data.end(); }\n\n  size_t size() const { return m_data.size(); }\n\n  void add(const K& key, const V& value) {\n    m_data.push_back(data{key, value});\n    m_sorted = false;\n  }\n\n  V& operator[](const K& inkey) {\n    do_sort();\n    data tmp_key{inkey, V{}};\n    auto lb = std::lower_bound(m_data.begin(), m_data.end(), tmp_key,\n                               [](const data& left, const data& right) {\n                                 return left.first < right.first;\n                               });\n    if ((*lb).first == inkey) {\n      return (*lb).second;\n    } else {\n      std::cerr << \"NOT FOUND\" << std::endl;\n      exit(-1);\n    }\n  }\n\n  size_t count(const K& inkey) {\n    if (m_data.empty()) return 0;\n    do_sort();\n    data tmp_key{inkey, V{}};\n    auto lb = std::lower_bound(m_data.begin(), m_data.end(), tmp_key,\n                               [](const data& left, const data& right) {\n                                 return left.first < right.first;\n                               });\n    if ((*lb).first == inkey) {\n      return 1;\n    } else {\n      return 0;\n    }\n  }\n\n  void do_sort() {\n    if (!m_sorted) {\n      m_sorted = true;\n      std::sort(m_data.begin(), m_data.end(),\n                [](const data& left, const data& right) {\n                  return left.first < right.first;\n                });\n      auto last = std::unique(m_data.begin(), m_data.end(),\n                              [](const data& left, const data& right) {\n                                return left.first == right.first;\n                              });\n      m_data.erase(last, m_data.end());\n    }\n  }\n\n private:\n  bool              m_sorted;\n  std::vector<data> m_data;\n};\n\ntemplate <typename TGraph>\nuint64_t new_triangle_count(TGraph& g, const char* deg_output_fname) {\n  typedef TGraph                          graph_type;\n  typedef typename TGraph::vertex_locator vertex_locator;\n\n  int mpi_size(0), mpi_rank(0);\n  CHK_MPI(MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank));\n  CHK_MPI(MPI_Comm_size(MPI_COMM_WORLD, &mpi_size));\n\n  // std::stringstream fname_sv_partition, fname_wc_partition;\n  // fname_sv_partition << \"/p/lscratchf/havoqgtu/wedge_check_experiment/DOD_\"\n  // << mpi_rank << \"_of_\" << mpi_size;\n  // fname_wc_partition <<\n  // \"/p/lscratchf/havoqgtu/wedge_check_experiment/wedges_\" << mpi_rank <<\n  // \"_of_\" << mpi_size;\n  //\n  // std::ofstream ofs_sv_partition(fname_sv_partition.str().c_str());\n  // std::ofstream ofs_wc_partition(fname_wc_partition.str().c_str());\n\n  //\n  // 1)  Calculate 2core degree.   0 degree means that vertex is not in 2core\n  typename graph_type::template vertex_data<\n      /*lazy_flat_map*/ std::map<vertex_locator, dogr_edge>,\n      std::allocator</*lazy_flat_map*/ std::map<vertex_locator, dogr_edge>>>\n      core2_directed(g);\n  {\n    typename graph_type::template vertex_data<uint32_t,\n                                              std::allocator<uint32_t>>\n        core2_degree(g);\n    {\n      typename graph_type::template vertex_data<bool, std::allocator<bool>>\n          core2_alive(g);\n      core2_alive.reset(true);\n      for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr) {\n        core2_degree[*vitr] = g.degree(*vitr);\n      }\n      for (auto ditr = g.delegate_vertices_begin();\n           ditr != g.delegate_vertices_end(); ++ditr) {\n        core2_degree[*ditr] = g.degree(*ditr);\n      }\n\n      // // /// This computes the 2core\n      // double start_time = MPI_Wtime();\n      // {\n      //   auto alg_data = std::forward_as_tuple(core2_degree, core2_alive);\n      //   auto vq = create_visitor_queue<core2_visitor<graph_type>,\n      //   lifo_queue>(\n      //       &g, alg_data);\n      //   vq.init_visitor_traversal();\n      // }\n      // double end_time = MPI_Wtime();\n      // if (mpi_rank == 0) {\n      //   std::cout << \"2Core time = \" << end_time - start_time << std::endl;\n      // }\n\n      // for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr)\n      // {\n      //   std::cout << \"Vertex \" << g.locator_to_label(*vitr) << \" has\n      //   core2_degree = \" << core2_degree[*vitr] << std::endl;\n      // }\n      // for (auto ditr = g.delegate_vertices_begin(); ditr !=\n      // g.delegate_vertices_end(); ++ditr) {\n      //   std::cout << \"Delegate \" << g.locator_to_label(*ditr) << \" has\n      //   core2_degree = \" <<  core2_degree[*ditr] << std::endl;\n      // }\n    }\n\n    //\n    // 2)  Calculate directed 2core edges\n    // typename graph_type::template\n    // vertex_data<boost::container::flat_map<vertex_locator,uint32_t>,\n    // std::allocator<boost::container::flat_map<vertex_locator,uint32_t>> >\n    // core2_directed(g);\n    // typename graph_type::template\n    // vertex_data<std::unordered_map<vertex_locator,uint32_t,vertex_locator_hash>,\n    // std::allocator<std::unordered_map<vertex_locator,uint32_t,vertex_locator_hash>\n    // > >   core2_directed(g);\n    double start_time = MPI_Wtime();\n    {\n      auto alg_data = std::forward_as_tuple(core2_degree, core2_directed, g);\n      auto vq = create_visitor_queue<directed_core2<graph_type>, lifo_queue>(\n          &g, alg_data);\n      vq.init_visitor_traversal();\n    }\n    double end_time = MPI_Wtime();\n    if (mpi_rank == 0) {\n      std::cout << \"Directed 2Core time = \" << end_time - start_time\n                << std::endl;\n    }\n\n    uint64_t local_core2_directed_edge_count(0);\n    for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr) {\n      local_core2_directed_edge_count += core2_directed[*vitr].size();\n    }\n\n    uint64_t global_core2_directed_edge_count =\n        comm_world().all_reduce(local_core2_directed_edge_count, MPI_SUM);\n    if (comm_world().rank() == 0) {\n      std::cout << \"global_core2_directed_edge_count = \"\n                << global_core2_directed_edge_count << std::endl;\n    }\n\n    // for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr) {\n    //    ofs_sv_partition << g.locator_to_label(*vitr);\n    //    for(auto pair : core2_directed[*vitr]) {\n    //      ofs_sv_partition << \" \" << pair.first;\n    //    }\n    //    ofs_sv_partition << std::endl;\n    //}\n\n    // for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr) {\n    //   std::cout << \"Vertex \" << g.locator_to_label(*vitr) << \" :: \";\n    //     for(auto p : core2_directed[*vitr]) {\n    //       std::cout << p.first << \" \";\n    //     }\n    //     std::cout << std::endl;\n    // }\n\n    // Sort Directed 2 core -- lazy\n    MPI_Barrier(MPI_COMM_WORLD);\n    uint64_t local_max_dod(0), local_max_deg(0);\n    start_time = MPI_Wtime();\n    {\n      for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr) {\n        // core2_directed[*vitr].do_sort();\n        local_max_dod =\n            std::max(local_max_dod, uint64_t(core2_directed[*vitr].size()));\n        local_max_deg = std::max(local_max_deg, uint64_t(g.degree(*vitr)));\n      }\n      for (auto citr = g.controller_begin(); citr != g.controller_end();\n           ++citr) {\n        // core2_directed[*citr].do_sort();\n        local_max_dod =\n            std::max(local_max_dod, uint64_t(core2_directed[*citr].size()));\n        local_max_deg = std::max(local_max_deg, uint64_t(g.degree(*citr)));\n      }\n    }\n    MPI_Barrier(MPI_COMM_WORLD);\n    end_time = MPI_Wtime();\n    uint64_t global_max_dod =\n        mpi_all_reduce(local_max_dod, std::greater<uint64_t>(), MPI_COMM_WORLD);\n    uint64_t global_max_deg =\n        mpi_all_reduce(local_max_deg, std::greater<uint64_t>(), MPI_COMM_WORLD);\n    if (mpi_rank == 0) {\n      std::cout << \"Largest DOD out degree = \" << global_max_dod << std::endl;\n      std::cout << \"Largest orig degree = \" << global_max_deg << std::endl;\n    }\n    {\n      //\n      // 4)  Compute distributions\n      std::map<uint64_t, uint64_t> local_orig_degree;\n      std::map<uint64_t, uint64_t> local_2core_degree;\n      std::map<uint64_t, uint64_t> local_2core_out_degree;\n\n      uint64_t local_edge_count(0), local_dod_edge_count(0),\n          local_in_zero_count(0), local_in_zero_edges_count(0);\n\n      for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr) {\n        local_orig_degree[g.degree(*vitr)]++;\n        local_2core_degree[core2_degree[*vitr]]++;\n        local_2core_out_degree[core2_directed[*vitr].size()]++;\n        local_edge_count += g.degree(*vitr);\n        local_dod_edge_count += core2_directed[*vitr].size();\n        if (core2_degree[*vitr] == core2_directed[*vitr].size()) {\n          ++local_in_zero_count;\n          local_in_zero_edges_count += core2_directed[*vitr].size();\n        }\n      }\n      for (auto citr = g.controller_begin(); citr != g.controller_end();\n           ++citr) {\n        local_orig_degree[g.degree(*citr)]++;\n        local_2core_degree[core2_degree[*citr]]++;\n        local_2core_out_degree[core2_directed[*citr].size()]++;\n        local_edge_count += g.degree(*citr);\n        local_dod_edge_count += core2_directed[*citr].size();\n        if (core2_degree[*citr] == core2_directed[*citr].size()) {\n          ++local_in_zero_count;\n          local_in_zero_edges_count += core2_directed[*citr].size();\n        }\n      }\n\n      uint64_t global_edge_count = mpi_all_reduce(\n          local_edge_count, std::plus<uint64_t>(), MPI_COMM_WORLD);\n      uint64_t global_dod_edge_count = mpi_all_reduce(\n          local_dod_edge_count, std::plus<uint64_t>(), MPI_COMM_WORLD);\n      uint64_t global_in_zero_count = mpi_all_reduce(\n          local_in_zero_count, std::plus<uint64_t>(), MPI_COMM_WORLD);\n      uint64_t global_in_zero_edge_count = mpi_all_reduce(\n          local_in_zero_edges_count, std::plus<uint64_t>(), MPI_COMM_WORLD);\n\n      if (mpi_rank == 0) {\n        std::cout << \"global_edge_count = \" << global_edge_count << std::endl;\n        std::cout << \"global_dod_edge_count = \" << global_dod_edge_count\n                  << std::endl;\n        std::cout << \"global_in_zero_count = \" << global_in_zero_count\n                  << std::endl;\n        std::cout << \"global_in_zero_edge_count = \" << global_in_zero_edge_count\n                  << std::endl;\n      }\n\n      // std::stringstream orig_degree, tcore_degree, tcore_out_degree;\n      // orig_degree << deg_output_fname << \"_orig_degree.txt\";\n      // tcore_degree << deg_output_fname << \"_2core_degree.txt\";\n      // tcore_out_degree << deg_output_fname << \"_2core_out_degree.txt\";\n\n      // output_degree_distribution(local_orig_degree,\n      // orig_degree.str().c_str());\n      // output_degree_distribution(local_2core_degree,\n      // tcore_degree.str().c_str());\n      // output_degree_distribution(local_2core_out_degree,\n      // tcore_out_degree.str().c_str());\n    }\n  }\n\n  //\n  // 3)  Build wedges & count\n  uint64_t local_triangle_count(0), local_wedge_count(0),\n      local_master_wedge_count(0), local_delegate_skip(0);\n  MPI_Barrier(MPI_COMM_WORLD);\n  double start_time = MPI_Wtime();\n  {\n    auto alg_data = std::forward_as_tuple(\n        core2_directed, local_triangle_count, local_wedge_count,\n        local_master_wedge_count,\n        local_delegate_skip /*, count_wedges_created, count_wedges_checked, count_triangles_found*/);\n    auto vq = create_visitor_queue<core2_wedges<graph_type>, lifo_queue>(\n        &g, alg_data);\n    vq.init_visitor_traversal();\n  }\n  MPI_Barrier(MPI_COMM_WORLD);\n  double   end_time = MPI_Wtime();\n  uint64_t global_wedge_count =\n      mpi_all_reduce(local_wedge_count, std::plus<uint64_t>(), MPI_COMM_WORLD);\n  uint64_t global_master_wedge_count =\n      comm_world().all_reduce(local_master_wedge_count, MPI_SUM);\n  uint64_t global_delegate_skip =\n      comm_world().all_reduce(local_delegate_skip, MPI_SUM);\n  if (mpi_rank == 0) {\n    std::cout << \"TC on directed 2core time = \" << end_time - start_time\n              << std::endl;\n    std::cout << \"Total wedges checked = \" << global_wedge_count << std::endl;\n    std::cout << \"global_master_wedge_count = \" << global_master_wedge_count\n              << std::endl;\n    std::cout << \"global_delegate_skip = \" << global_delegate_skip << std::endl;\n  }\n\n  uint64_t local_edge_triangle_count(0);\n  uint64_t local_j_count(0);\n  uint64_t local_edge_count(0);\n  for (auto vitr = g.vertices_begin(); vitr != g.vertices_end(); ++vitr) {\n    for (const auto& edge_info : core2_directed[*vitr]) {\n      local_edge_triangle_count += edge_info.second.edge_triangle_count;\n      ++local_edge_count;\n      if (edge_info.second.is_j) {\n        ++local_j_count;\n      }\n    }\n  }\n  uint64_t local_controller_dogr_degree(0);\n  for (auto citr = g.controller_begin(); citr != g.controller_end(); ++citr) {\n    // std::cout << \"Controller  Info: \" << whoami()\n    //           << \" orig deg = \" << g.degree(*citr)\n    //           << \" dogr degree = \" << core2_directed[*citr].size() <<\n    //           std::endl;\n    local_controller_dogr_degree += core2_directed[*citr].size();\n    for (const auto& edge_info : core2_directed[*citr]) {\n      local_edge_triangle_count += edge_info.second.edge_triangle_count;\n      ++local_edge_count;\n      if (edge_info.second.is_j) {\n        ++local_j_count;\n      }\n    }\n  }\n  uint64_t global_edge_triangle_count =\n      comm_world().all_reduce(local_edge_triangle_count, MPI_SUM);\n\n  uint64_t global_j_count = comm_world().all_reduce(local_j_count, MPI_SUM);\n\n  uint64_t global_edge_count =\n      comm_world().all_reduce(local_edge_count, MPI_SUM);\n  uint64_t global_controller_dogr_degree =\n      comm_world().all_reduce(local_controller_dogr_degree, MPI_SUM);\n\n  if (comm_world().rank() == 0) {\n    std::cout << \"global_controller_dogr_degree = \"\n              << global_controller_dogr_degree << std::endl;\n    std::cout << \"global_edge_triangle_count / 3 = \"\n              << global_edge_triangle_count / 3 << std::endl;\n    std::cout << \"global_j_count = \" << global_j_count << \" ratio = \"\n              << double(global_j_count) / double(global_edge_count)\n              << std::endl;\n  }\n\n  uint64_t global_triangle_count = mpi_all_reduce(\n      local_triangle_count, std::plus<uint64_t>(), MPI_COMM_WORLD);\n  return global_triangle_count;\n}\n\n}  // end namespace havoqgt\n\n#endif  // HAVOQGT_MPI_TRIANGLE_COUNT_HPP_INCLUDED\n", "meta": {"hexsha": "cd108471a0ae7f6d12c84a4512497ae7da30f960", "size": 30939, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/havoqgt/new_triangle_count.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/new_triangle_count.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/new_triangle_count.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.9198645598, "max_line_length": 101, "alphanum_fraction": 0.6018294063, "num_tokens": 8164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.024423091829327514, "lm_q1q2_score": 0.007918831242590735}}
{"text": "#ifndef HERMIT_SPIRIT_KARMA_UTF8_HPP\n#define HERMIT_SPIRIT_KARMA_UTF8_HPP\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <boost/spirit/include/karma.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n\nnamespace hermit {\n  namespace spirit {\n    namespace karma {\n      template< typename OutputIterator >\n        class utf8 :\n          public boost::spirit::karma::grammar< OutputIterator, char32_t() > {\n            public:\n              utf8() : utf8::base_type( root ) {\n                namespace karma = boost::spirit::karma;\n                ascii_ = karma::byte_[ karma::_1 = karma::_val ];\n                block1 = ( karma::byte_ << karma::byte_ )[\n                  karma::_1 = 0xC0|( karma::_val >> 6 ),\n                  karma::_2 = 0x80|( karma::_val & 0x3F )\n                    ];\n                block2 = ( karma::byte_ << karma::byte_ << karma::byte_ )[\n                  karma::_1 = 0xE0|( karma::_val >> 12 ),\n                  karma::_2 = 0x80|( ( karma::_val >> 6 ) & 0x3F ),\n                  karma::_3 = 0x80|( karma::_val & 0x3F )\n                    ];\n                block3 = ( karma::byte_ << karma::byte_ << karma::byte_ << karma::byte_ )[\n                  karma::_1 = 0xF0|( karma::_val >> 18 ),\n                  karma::_2 = 0x80|( ( karma::_val >> 12 ) & 0x3F ),\n                  karma::_3 = 0x80|( ( karma::_val >> 6 ) & 0x3F ),\n                  karma::_4 = 0x80|( ( karma::_val ) & 0x3F )\n                    ];\n                char_raw = ascii_[\n                  karma::_pass = karma::_val <= 0x7Ful,\n                  karma::_1 = karma::_val\n                ]|\n                block1[\n                  karma::_pass = karma::_val <= 0x7FFul,\n                  karma::_1 = karma::_val\n                ]|\n                block2[\n                  karma::_pass = karma::_val <= 0xFFFFul,\n                  karma::_1 = karma::_val\n                ]|\n                block3[\n                  karma::_pass = karma::_val <= 0x1FFFFFul,\n                  karma::_1 = karma::_val\n                ];\n                root = char_raw[\n                  karma::_pass = ( karma::_val < 0xD800ul || karma::_val > 0xDFFFul ) &&\n                    ( karma::_val < 0xFDD0ul || karma::_val > 0xFDEFul ) &&\n                    ( ( karma::_val & 0xFFFFul ) < 0xFFFEul ) &&\n                    ( karma::_val <= 0x10FFFFul ),\n                  karma::_1 = karma::_val\n                ];\n              }\n            private:\n              boost::spirit::karma::rule< OutputIterator, uint32_t() > ascii_;\n              boost::spirit::karma::rule< OutputIterator, uint32_t() > block1;\n              boost::spirit::karma::rule< OutputIterator, uint32_t() > block2;\n              boost::spirit::karma::rule< OutputIterator, uint32_t() > block3;\n              boost::spirit::karma::rule< OutputIterator, char32_t() > char_raw;\n              boost::spirit::karma::rule< OutputIterator, char32_t() > root;\n          };\n      template< typename OutputIterator >\n        class utf8string :\n          public boost::spirit::karma::grammar< OutputIterator, std::u32string() > {\n            public:\n              utf8string() : utf8string::base_type( root ) {\n                root = *utf8char;\n              }\n            private:\n              utf8< OutputIterator > utf8char;\n              boost::spirit::karma::rule< OutputIterator, std::u32string() > root;\n      };\n    }\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "83fe32fc4dbc948053148c35e2f18fd029fe1676", "size": 3410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hermit/spirit/karma/utf8.hpp", "max_stars_repo_name": "Fadis/hermit", "max_stars_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T05:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-09T05:54:01.000Z", "max_issues_repo_path": "include/hermit/spirit/karma/utf8.hpp", "max_issues_repo_name": "Fadis/hermit", "max_issues_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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/hermit/spirit/karma/utf8.hpp", "max_forks_repo_name": "Fadis/hermit", "max_forks_repo_head_hexsha": "1b378fb94165e0348d11d8065d3259d14c49977b", "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.5952380952, "max_line_length": 90, "alphanum_fraction": 0.4715542522, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.01941934729572536, "lm_q1q2_score": 0.007910148481209153}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <algorithm>\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"DataStructures/VariablesTag.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Structure/OrientationMapHelpers.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Evolution/DgSubcell/ActiveGrid.hpp\"\n#include \"Evolution/DgSubcell/NeighborData.hpp\"\n#include \"Evolution/DgSubcell/Projection.hpp\"\n#include \"Evolution/DgSubcell/RdmpTci.hpp\"\n#include \"Evolution/DgSubcell/SliceData.hpp\"\n#include \"Evolution/DgSubcell/Tags/ActiveGrid.hpp\"\n#include \"Evolution/DgSubcell/Tags/Inactive.hpp\"\n#include \"Evolution/DgSubcell/Tags/Mesh.hpp\"\n#include \"Evolution/DgSubcell/Tags/NeighborData.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/InboxTags.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/MortarData.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/MortarTags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"NumericalAlgorithms/Spectral/Spectral.hpp\"\n#include \"Parallel/AlgorithmMetafunctions.hpp\"\n#include \"Parallel/GlobalCache.hpp\"\n#include \"Time/Tags.hpp\"\n#include \"Time/TimeStepId.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace evolution::dg::subcell::Actions {\n/*!\n * \\brief Sets the local data from the relaxed discrete maximum principle\n * troubled-cell indicator and sends ghost zone data to neighboring elements.\n *\n * The action proceeds as follows:\n *\n * 1. Computes the maximum and minimum of each evolved variable, which is used\n *    by the relaxed discrete maximum principle troubled-cell indicator.\n * 2. Determine in which directions we have neighbors\n * 3. Slice the variables provided by GhostDataMutator to send to our neighbors\n *    for ghost zones\n * 4. Send the ghost zone data, appending the max/min for the TCI at the end of\n *    the `std::vector<double>` we are sending.\n *\n * Some notes:\n * - In the future we will need to send the cell-centered fluxes to do\n *   high-order FD without additional reconstruction being necessary.\n *\n * GlobalCache:\n * - Uses:\n *   - `ParallelComponent` proxy\n *\n * DataBox:\n * - Uses:\n *   - `domain::Tags::Mesh<Dim>`\n *   - `subcell::Tags::Mesh<Dim>`\n *   - `domain::Tags::Element<Dim>`\n *   - `Tags::TimeStepId`\n *   - `Tags::Next<Tags::TimeStepId>`\n *   - `subcell::Tags::ActiveGrid`\n *   - `System::variables_tag`\n * - Adds: nothing\n * - Removes: nothing\n * - Modifies:\n *   - `subcell::Tags::NeighborDataForReconstructionAndRdmpTci<Dim>`\n */\ntemplate <size_t Dim, typename GhostDataMutator>\nstruct SendDataForReconstruction {\n  using inbox_tags = tmpl::list<\n      evolution::dg::Tags::BoundaryCorrectionAndGhostCellsInbox<Dim>>;\n\n  template <typename DbTags, typename... InboxTags, typename ArrayIndex,\n            typename ActionList, typename ParallelComponent,\n            typename Metavariables>\n  static std::tuple<db::DataBox<DbTags>&&> apply(\n      db::DataBox<DbTags>& box, tuples::TaggedTuple<InboxTags...>& /*inboxes*/,\n      Parallel::GlobalCache<Metavariables>& cache,\n      const ArrayIndex& /*array_index*/, const ActionList /*meta*/,\n      const ParallelComponent* const /*meta*/) {\n    using variables_tag = typename Metavariables::system::variables_tag;\n\n    ASSERT(db::get<Tags::ActiveGrid>(box) == ActiveGrid::Subcell,\n           \"The SendDataForReconstruction action can only be called when \"\n           \"Subcell is the active scheme.\");\n\n    db::mutate<Tags::NeighborDataForReconstructionAndRdmpTci<Dim>>(\n        make_not_null(&box),\n        [](const auto neighbor_data_ptr, const auto& active_vars) {\n          auto [max_of_vars, min_of_vars] =\n              rdmp_max_min(active_vars, {}, false);\n\n          // Clear the previous neighbor data and add current local data\n          neighbor_data_ptr->clear();\n          (*neighbor_data_ptr)[std::pair{\n              Direction<Dim>::lower_xi(),\n              ElementId<Dim>::external_boundary_id()}] =\n              NeighborData{{}, std::move(max_of_vars), std::move(min_of_vars)};\n        },\n        db::get<variables_tag>(box));\n\n    const Mesh<Dim>& dg_mesh = db::get<::domain::Tags::Mesh<Dim>>(box);\n    const Mesh<Dim>& subcell_mesh = db::get<Tags::Mesh<Dim>>(box);\n    const Element<Dim>& element = db::get<::domain::Tags::Element<Dim>>(box);\n    const size_t ghost_zone_size =\n        Metavariables::SubcellOptions::ghost_zone_size(box);\n    DirectionMap<Dim, bool> directions_to_slice{};\n    for (const auto& direction_neighbors : element.neighbors()) {\n      if (direction_neighbors.second.size() == 0) {\n        directions_to_slice[direction_neighbors.first] = false;\n      } else {\n        directions_to_slice[direction_neighbors.first] = true;\n      }\n    }\n    // Optimization note: could save a copy+allocation if we moved\n    // all_sliced_data when possible before sending.\n    const DirectionMap<Dim, std::vector<double>> all_sliced_data = slice_data(\n        db::mutate_apply(GhostDataMutator{}, make_not_null(&box)),\n        subcell_mesh.extents(), ghost_zone_size, directions_to_slice);\n\n    auto& receiver_proxy =\n        Parallel::get_parallel_component<ParallelComponent>(cache);\n    const NeighborData& local_neighbor_data =\n        db::get<Tags::NeighborDataForReconstructionAndRdmpTci<Dim>>(box).at(\n            std::pair{Direction<Dim>::lower_xi(),\n                      ElementId<Dim>::external_boundary_id()});\n    const TimeStepId& time_step_id = db::get<::Tags::TimeStepId>(box);\n    const TimeStepId& next_time_step_id = [&box]() {\n      if (Metavariables::local_time_stepping) {\n        return db::get<::Tags::Next<::Tags::TimeStepId>>(box);\n      } else {\n        return db::get<::Tags::TimeStepId>(box);\n      }\n    }();\n\n    // Compute and send actual variables\n    for (const auto& [direction, neighbors_in_direction] :\n         element.neighbors()) {\n      const auto& orientation = neighbors_in_direction.orientation();\n      const auto direction_from_neighbor = orientation(direction.opposite());\n      ASSERT(neighbors_in_direction.size() == 1,\n             \"AMR is not yet supported when using DG-subcell. Note that this \"\n             \"condition could be relaxed to support AMR only where the \"\n             \"evolution is using DG without any changes to subcell.\");\n\n      for (const ElementId<Dim>& neighbor : neighbors_in_direction) {\n        std::vector<double> subcell_data_to_send{};\n        if (not orientation.is_aligned()) {\n          std::array<size_t, Dim> slice_extents{};\n          for (size_t d = 0; d < Dim; ++d) {\n            gsl::at(slice_extents, d) = subcell_mesh.extents(d);\n          }\n          gsl::at(slice_extents, direction.dimension()) = ghost_zone_size;\n\n          subcell_data_to_send =\n              orient_variables(all_sliced_data.at(direction),\n                               Index<Dim>{slice_extents}, orientation);\n        } else {\n          subcell_data_to_send = all_sliced_data.at(direction);\n        }\n        subcell_data_to_send.insert(\n            subcell_data_to_send.end(),\n            local_neighbor_data.max_variables_values.cbegin(),\n            local_neighbor_data.max_variables_values.cend());\n        subcell_data_to_send.insert(\n            subcell_data_to_send.end(),\n            local_neighbor_data.min_variables_values.cbegin(),\n            local_neighbor_data.min_variables_values.cend());\n\n        std::tuple<Mesh<Dim - 1>, std::optional<std::vector<double>>,\n                   std::optional<std::vector<double>>, ::TimeStepId>\n            data{dg_mesh.slice_away(direction.dimension()),\n                 std::move(subcell_data_to_send), std::nullopt,\n                 next_time_step_id};\n\n        Parallel::receive_data<\n            evolution::dg::Tags::BoundaryCorrectionAndGhostCellsInbox<Dim>>(\n            receiver_proxy[neighbor], time_step_id,\n            std::pair{std::pair{direction_from_neighbor, element.id()},\n                      std::move(data)});\n      }\n    }\n    return {std::move(box)};\n  }\n};\n\n/*!\n * \\brief Receive the subcell data from our neighbor, and accumulate the data\n * from the relaxed discrete maximum principle troubled-cell indicator.\n *\n * Note:\n * - Since we only care about the min/max over all neighbors and ourself at the\n *   past time, we accumulate all data immediately into the self `NeighborData`.\n * - If the neighbor is using DG and therefore sends boundary correction data\n *   then that is added into the `evolution::dg::Tags::MortarData` tag\n * - The next `TimeStepId` is recorded, but we do not yet support local time\n *   stepping.\n * - This action will never care about what variables are sent for\n *   reconstruction. It is only responsible for receiving the data and storing\n *   it in the `NeighborData`.\n *\n * GlobalCache:\n * -Uses: nothing\n *\n * DataBox:\n * - Uses:\n *   - `domain::Tags::Element<Dim>`\n *   - `Tags::TimeStepId`\n *   - `domain::Tags::Mesh<Dim>`\n *   - `subcell::Tags::Mesh<Dim>`\n *   - `domain::Tags::Element<Dim>`\n *   - `Tags::Next<Tags::TimeStepId>`\n *   - `subcell::Tags::ActiveGrid`\n *   - `System::variables_tag`\n * - Adds: nothing\n * - Removes: nothing\n * - Modifies:\n *   - `subcell::Tags::NeighborDataForReconstructionAndRdmpTci<Dim>`\n *   - `evolution::dg::Tags::MortarData`\n *   - `evolution::dg::Tags::MortarNextTemporalId`\n */\ntemplate <size_t Dim>\nstruct ReceiveDataForReconstruction {\n  template <typename DbTags, typename... InboxTags, typename ArrayIndex,\n            typename ActionList, typename ParallelComponent,\n            typename Metavariables>\n  static std::tuple<db::DataBox<DbTags>&&, Parallel::AlgorithmExecution> apply(\n      db::DataBox<DbTags>& box, tuples::TaggedTuple<InboxTags...>& inboxes,\n      const Parallel::GlobalCache<Metavariables>& /*cache*/,\n      const ArrayIndex& /*array_index*/, const ActionList /*meta*/,\n      const ParallelComponent* const /*meta*/) {\n    static_assert(\n        not Metavariables::local_time_stepping,\n        \"DG-subcell does not yet support local time stepping. The \"\n        \"reconstruction data must be sent using dense output sometimes, and \"\n        \"not at all other times. However, the data for the RDMP TCI should be \"\n        \"sent along with the data for reconstruction each time.\");\n    const Element<Dim>& element = db::get<::domain::Tags::Element<Dim>>(box);\n    const auto number_of_expected_messages = element.neighbors().size();\n    if (UNLIKELY(number_of_expected_messages == 0)) {\n      // We have no neighbors, so just continue without doing any work\n      return {std::move(box), Parallel::AlgorithmExecution::Continue};\n    }\n\n    using ::operator<<;\n    using Key = std::pair<Direction<Dim>, ElementId<Dim>>;\n    const auto& current_time_step_id = db::get<::Tags::TimeStepId>(box);\n    std::map<TimeStepId,\n             FixedHashMap<\n                 maximum_number_of_neighbors(Dim), Key,\n                 std::tuple<Mesh<Dim - 1>, std::optional<std::vector<double>>,\n                            std::optional<std::vector<double>>, ::TimeStepId>,\n                 boost::hash<Key>>>& inbox =\n        tuples::get<evolution::dg::Tags::BoundaryCorrectionAndGhostCellsInbox<\n            Metavariables::volume_dim>>(inboxes);\n    const auto& received = inbox.find(current_time_step_id);\n    // Check we have at least some data from correct time, and then check that\n    // we have received all data\n    if (received == inbox.end() or\n        received->second.size() != number_of_expected_messages) {\n      return {std::move(box), Parallel::AlgorithmExecution::Retry};\n    }\n\n    // Now that we have received all the data, copy it over as needed.\n    FixedHashMap<maximum_number_of_neighbors(Dim), Key,\n                 std::tuple<Mesh<Dim - 1>, std::optional<std::vector<double>>,\n                            std::optional<std::vector<double>>, ::TimeStepId>,\n                 boost::hash<Key>>\n        received_data = std::move(inbox[current_time_step_id]);\n    inbox.erase(current_time_step_id);\n    db::mutate<Tags::NeighborDataForReconstructionAndRdmpTci<Dim>,\n               evolution::dg::Tags::MortarData<Dim>,\n               evolution::dg::Tags::MortarNextTemporalId<Dim>>(\n        make_not_null(&box),\n        [&current_time_step_id, &element, &received_data](\n            const gsl::not_null<FixedHashMap<\n                maximum_number_of_neighbors(Dim) + 1,\n                std::pair<Direction<Dim>, ElementId<Dim>>, NeighborData,\n                boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>*>\n                neighbor_data_ptr,\n            const gsl::not_null<std::unordered_map<\n                Key, evolution::dg::MortarData<Dim>, boost::hash<Key>>*>\n                mortar_data,\n            const gsl::not_null<\n                std::unordered_map<Key, TimeStepId, boost::hash<Key>>*>\n                mortar_next_time_step_id) {\n          // Get the next time step id, and also the fluxes data if the neighbor\n          // is doing DG.\n          for (auto& received_mortar_data : received_data) {\n            const auto& mortar_id = received_mortar_data.first;\n            try {\n              mortar_next_time_step_id->at(mortar_id) =\n                  std::get<3>(received_mortar_data.second);\n            } catch (std::exception& e) {\n              ERROR(\"Failed retrieving the MortarId: (\"\n                    << mortar_id.first << ',' << mortar_id.second\n                    << \") from the mortar_next_time_step_id. Got exception: \"\n                    << e.what());\n            }\n            if (std::get<2>(received_mortar_data.second).has_value()) {\n              mortar_data->at(mortar_id).insert_neighbor_mortar_data(\n                  current_time_step_id,\n                  std::get<0>(received_mortar_data.second),\n                  std::move(*std::get<2>(received_mortar_data.second)));\n            }\n          }\n\n          ASSERT(neighbor_data_ptr->size() == 1,\n                 \"Should only have one element in the neighbor data when \"\n                 \"receiving neighbor data\");\n          ASSERT(\n              neighbor_data_ptr->count(\n                  std::pair{Direction<Dim>::lower_xi(),\n                            element.id().external_boundary_id()}) == 1,\n              \"The self data for the RDMP TCI should have been inserted but it \"\n              \"wasn't, despite there being one entry in the neighbor data.\");\n          NeighborData& self_neighbor_data = (*neighbor_data_ptr)[std::pair{\n              Direction<Dim>::lower_xi(),\n              ElementId<Dim>::external_boundary_id()}];\n          const size_t number_of_evolved_vars =\n              self_neighbor_data.max_variables_values.size();\n          ASSERT(self_neighbor_data.min_variables_values.size() ==\n                     number_of_evolved_vars,\n                 \"The number of evolved variables for which we have a maximum \"\n                 \"and minimum should be the same, but we have \"\n                     << number_of_evolved_vars << \" for the max and \"\n                     << self_neighbor_data.min_variables_values.size()\n                     << \" for the min.\");\n\n          for (const auto& [direction, neighbors_in_direction] :\n               element.neighbors()) {\n            for (const auto& neighbor : neighbors_in_direction) {\n              std::pair directional_element_id{direction, neighbor};\n              ASSERT(neighbor_data_ptr->count(directional_element_id) == 0,\n                     \"Found neighbor already inserted in direction \"\n                         << direction << \" with ElementId \" << neighbor);\n              ASSERT(std::get<1>(received_data[directional_element_id])\n                         .has_value(),\n                     \"Received subcell data message that does not contain any \"\n                     \"actual subcell data for reconstruction.\");\n              // Collect the max/min of u(t^n) for the RDMP as we receive data.\n              // This reduces the memory footprint.\n              std::vector<double>& received_neighbor_subcell_data =\n                  *std::get<1>(received_data[directional_element_id]);\n              const size_t max_offset = received_neighbor_subcell_data.size() -\n                                        2 * number_of_evolved_vars;\n              const size_t min_offset = received_neighbor_subcell_data.size() -\n                                        number_of_evolved_vars;\n              for (size_t var_index = 0; var_index < number_of_evolved_vars;\n                   ++var_index) {\n                self_neighbor_data.max_variables_values[var_index] = std::max(\n                    self_neighbor_data.max_variables_values[var_index],\n                    received_neighbor_subcell_data[max_offset + var_index]);\n                self_neighbor_data.min_variables_values[var_index] = std::min(\n                    self_neighbor_data.min_variables_values[var_index],\n                    received_neighbor_subcell_data[min_offset + var_index]);\n              }\n              // Copy over the ghost cell data for subcell reconstruction.\n              [[maybe_unused]] const auto insert_result =\n                  neighbor_data_ptr->insert(std::pair{\n                      directional_element_id,\n                      NeighborData{std::vector<double>{\n                          received_neighbor_subcell_data.begin(),\n                          std::prev(\n                              received_neighbor_subcell_data.end(),\n                              2 * static_cast<typename std::iterator_traits<\n                                      typename std::vector<double>::iterator>::\n                                                  difference_type>(\n                                      number_of_evolved_vars))}}});\n              ASSERT(insert_result.second,\n                     \"Failed to insert the neighbor data in direction \"\n                         << direction << \" from neighbor \" << neighbor);\n            }\n          }\n        });\n    return {std::move(box), Parallel::AlgorithmExecution::Continue};\n  }\n};\n}  // namespace evolution::dg::subcell::Actions\n", "meta": {"hexsha": "92c17e4961deb7b7a36334dd82238ffaa23d707f", "size": 18598, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DgSubcell/Actions/ReconstructionCommunication.hpp", "max_stars_repo_name": "kidder/spectre", "max_stars_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-02T16:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T16:49:35.000Z", "max_issues_repo_path": "src/Evolution/DgSubcell/Actions/ReconstructionCommunication.hpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-02-27T22:13:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T16:21:08.000Z", "max_forks_repo_path": "src/Evolution/DgSubcell/Actions/ReconstructionCommunication.hpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "max_forks_repo_licenses": ["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.1488833747, "max_line_length": 80, "alphanum_fraction": 0.6368964405, "num_tokens": 4158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416749665475, "lm_q2_score": 0.025957354937269386, "lm_q1q2_score": 0.007892117672828566}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <algorithm>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/SliceIterator.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Evolution/DgSubcell/Projection.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/MortarData.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace evolution::dg::subcell {\n/*!\n * \\brief Project the DG package data to the subcells. Data received from a\n * neighboring element doing DG is always projected, while the data we sent to\n * our neighbors before doing a rollback from DG to subcell is only projected if\n * `OverwriteInternalMortarData` is `true`.\n *\n * In order for the hybrid DG-FD/FV scheme to be conservative between elements\n * using DG and elements using subcell, the boundary terms must be the same on\n * both elements. In practice this means the boundary corrections \\f$G+D\\f$ must\n * be computed on the same grid. Consider the element doing subcell which\n * receives data from an element doing DG. In this case the DG element's\n * ingredients going into \\f$G+D\\f$ are projected to the subcells and then\n * \\f$G+D\\f$ are computed on the subcells. Similarly, for strict conservation\n * the element doing DG must first project the data it sent to the neighbor to\n * the subcells, then compute \\f$G+D\\f$ on the subcells, and finally reconstrct\n * \\f$G+D\\f$ back to the DG grid before lifting \\f$G+D\\f$ to the volume.\n *\n * This function updates the `packaged_data` (ingredients into \\f$G+D\\f$)\n * received by an element doing subcell by projecting the neighbor's DG data\n * onto the subcells. Note that this is only half of what is required for strict\n * conservation, the DG element must also compute \\f$G+D\\f$ on the subcells.\n * Note that we currently do not perform the other half of the correction\n * needed to be strictly conservative.\n *\n * If we are retaking a time step after the DG step failed then maintaining\n * conservation requires additional care. If `OverwriteInternalMortarData` is\n * `true` then the local (the element switching from DG to subcell) ingredients\n * into \\f$G+D\\f$ are projected and overwrite the data computed from\n * the FD reconstruction to the interface. However, even this is insufficient to\n * guarantee conservation. To guarantee conservation (which we do not currently\n * do) the correction \\f$G+D\\f$ must be computed on the DG grid and then\n * projected to the subcells.\n *\n * Note that our practical experience shows that since the DG-subcell hybrid\n * scheme switches to the subcell solver _before_ the local solution contains\n * discontinuities, strict conservation is not necessary between DG and FD/FV\n * regions. This was also observed with a block-adaptive finite difference AMR\n * code \\cite CHEN2016604\n */\ntemplate <bool OverwriteInternalMortarData, size_t Dim,\n          typename DgPackageFieldTags>\nvoid correct_package_data(\n    const gsl::not_null<Variables<DgPackageFieldTags>*> lower_packaged_data,\n    const gsl::not_null<Variables<DgPackageFieldTags>*> upper_packaged_data,\n    const size_t logical_dimension_to_operate_in, const Element<Dim>& element,\n    const Mesh<Dim>& subcell_volume_mesh,\n    const std::unordered_map<\n        std::pair<Direction<Dim>, ElementId<Dim>>,\n        evolution::dg::MortarData<Dim>,\n        boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>& mortar_data) {\n  const Direction<Dim> upper_direction{logical_dimension_to_operate_in,\n                                       Side::Upper};\n  const Direction<Dim> lower_direction{logical_dimension_to_operate_in,\n                                       Side::Lower};\n  const bool has_upper_neighbor = element.neighbors().contains(upper_direction);\n  const bool has_lower_neighbor = element.neighbors().contains(lower_direction);\n  const std::pair upper_mortar_id =\n      has_upper_neighbor\n          ? std::pair{upper_direction,\n                      *element.neighbors().at(upper_direction).begin()}\n          : std::pair<Direction<Dim>, ElementId<Dim>>{};\n  const std::pair lower_mortar_id =\n      has_lower_neighbor\n          ? std::pair{lower_direction,\n                      *element.neighbors().at(lower_direction).begin()}\n          : std::pair<Direction<Dim>, ElementId<Dim>>{};\n\n  Index<Dim> subcell_extents_with_faces = subcell_volume_mesh.extents();\n  ++subcell_extents_with_faces[logical_dimension_to_operate_in];\n  const Mesh<Dim - 1>& subcell_face_mesh =\n      subcell_volume_mesh.slice_away(logical_dimension_to_operate_in);\n\n  const auto project_dg_data_to_subcells =\n      [logical_dimension_to_operate_in, &subcell_extents_with_faces,\n       &subcell_face_mesh](const gsl::not_null<Variables<DgPackageFieldTags>*>\n                               subcell_packaged_data,\n                           const size_t subcell_index,\n                           const Mesh<Dim - 1>& neighbor_face_mesh,\n                           const std::vector<double>& neighbor_data) {\n        const double* slice_data = neighbor_data.data();\n        // Warning: projected_data can't be inside the `if constexpr` since that\n        // would lead to a dangling pointer.\n        std::vector<double> projected_data{};\n        if constexpr (Dim > 1) {\n          projected_data.resize(\n              Variables<DgPackageFieldTags>::number_of_independent_components *\n              subcell_face_mesh.number_of_grid_points());\n          evolution::dg::subcell::fd::detail::project_impl(\n              gsl::make_span(projected_data.data(), projected_data.size()),\n              gsl::make_span(neighbor_data.data(), neighbor_data.size()),\n              neighbor_face_mesh, subcell_face_mesh.extents());\n          slice_data = projected_data.data();\n        } else {\n          (void)subcell_face_mesh;\n          (void)projected_data;\n        }\n        const size_t volume_grid_points = subcell_extents_with_faces.product();\n        const size_t slice_grid_points =\n            subcell_extents_with_faces\n                .slice_away(logical_dimension_to_operate_in)\n                .product();\n        double* const volume_data = subcell_packaged_data->data();\n        for (SliceIterator si(subcell_extents_with_faces,\n                              logical_dimension_to_operate_in, subcell_index);\n             si; ++si) {\n          for (size_t i = 0;\n               i <\n               Variables<DgPackageFieldTags>::number_of_independent_components;\n               ++i) {\n            // clang-tidy: do not use pointer arithmetic\n            volume_data[si.volume_offset() +\n                        i * volume_grid_points] =  // NOLINT\n                slice_data[si.slice_offset() +\n                           i * slice_grid_points];  // NOLINT\n          }\n        }\n      };\n\n  // Project DG data to the subcells\n  if (auto neighbor_mortar_data_it = mortar_data.find(upper_mortar_id);\n      has_upper_neighbor and neighbor_mortar_data_it != mortar_data.end()) {\n    if (neighbor_mortar_data_it->second.neighbor_mortar_data().has_value()) {\n      project_dg_data_to_subcells(\n          upper_packaged_data,\n          subcell_extents_with_faces[logical_dimension_to_operate_in] - 1,\n          neighbor_mortar_data_it->second.neighbor_mortar_data()->first,\n          neighbor_mortar_data_it->second.neighbor_mortar_data()->second);\n    }\n    if constexpr (OverwriteInternalMortarData) {\n      if (neighbor_mortar_data_it->second.local_mortar_data().has_value()) {\n        project_dg_data_to_subcells(\n            lower_packaged_data,\n            subcell_extents_with_faces[logical_dimension_to_operate_in] - 1,\n            neighbor_mortar_data_it->second.local_mortar_data()->first,\n            neighbor_mortar_data_it->second.local_mortar_data()->second);\n      }\n    }\n  }\n  if (auto neighbor_mortar_data_it = mortar_data.find(lower_mortar_id);\n      has_lower_neighbor and neighbor_mortar_data_it != mortar_data.end()) {\n    if (neighbor_mortar_data_it->second.neighbor_mortar_data().has_value()) {\n      project_dg_data_to_subcells(\n          lower_packaged_data, 0,\n          neighbor_mortar_data_it->second.neighbor_mortar_data()->first,\n          neighbor_mortar_data_it->second.neighbor_mortar_data()->second);\n    }\n    if constexpr (OverwriteInternalMortarData) {\n      if (neighbor_mortar_data_it->second.local_mortar_data().has_value()) {\n        project_dg_data_to_subcells(\n            upper_packaged_data, 0,\n            neighbor_mortar_data_it->second.local_mortar_data()->first,\n            neighbor_mortar_data_it->second.local_mortar_data()->second);\n      }\n    }\n  }\n}\n}  // namespace evolution::dg::subcell\n", "meta": {"hexsha": "c82971bddc85c316a9e62bd8ff764ddd9cc7640c", "size": 9018, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DgSubcell/CorrectPackagedData.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/Evolution/DgSubcell/CorrectPackagedData.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/Evolution/DgSubcell/CorrectPackagedData.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": 48.7459459459, "max_line_length": 80, "alphanum_fraction": 0.6993790197, "num_tokens": 2088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.027585284625072475, "lm_q1q2_score": 0.007850110073778714}}
{"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#ifndef GRIDMANAGER_HH_\n#define GRIDMANAGER_HH_\n\n#include <ctime>\n#include <iostream>\n#include <utility>\n\n#include <boost/signals2.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/timer/timer.hpp>\n\n#ifdef MULTITHREAD\n#include <boost/thread.hpp>\n#endif\n\n#include <dune/grid/common/capabilities.hh>\n#include <dune/grid/common/gridview.hh>\n#include <dune/grid/io/file/dgfparser/gridptr.hh>\n\n#ifdef MULTITHREAD\n#include \"utilities/threadpool/threadpool-0_2_5-src/threadpool/boost/threadpool.hpp\"\n#endif\n\n#include \"utilities/threading.hh\"\n\nnamespace Kaskade\n{\n  template<class G, class T> class CellData;\n\n  /**\n   * \\ingroup grid\n   * \\brief A class that provides access to signals that are emitted from the grid manager on various occasions.\n   */\n  struct GridSignals\n  {\n    /**\n     * \\ingroup grid\n     * Signal group names for use with the informAboutRefinement\n     * signal. Freeing resources should occur before allocating new\n     * resources.\n     */\n    enum { freeResources=0, allocResources=1 };\n\n    /**\n     * \\ingroup grid\n     * \\brief The argument type of the signal that is emitted before and after grid adaptation.\n     */\n    enum Status { BeforeRefinement, AfterRefinement, TransferCompleted };\n\n\n    /**\n     * \\ingroup grid\n     * \\brief A signal that is emitted thrice on grid modifications, once before\n     * adaptation takes place and twice after it is completed.\n     * \n     * The current state of grid refinement and FE coefficient transfer is signaled by the status argument.\n     */\n    boost::signals2::signal<void (Status)> informAboutRefinement;\n  };\n  \n\n  /**\n   * \\ingroup grid\n   * \\brief A class storing cell ranges of roughly equal size for multithreaded mesh traversal.\n   */\n  template <class GridView>\n  class CellRanges\n  {\n  public:\n    /**\n     * \\brief The type of iterator to step through the cells of the given view.\n     */\n    typedef typename GridView::template Codim<0>::Iterator CellIterator;\n    \n    /**\n     * \\brief Default constructor.\n     * This creates a pretty useless empty cell ranges object.\n     */\n    CellRanges() = default;\n    \n    /**\n     * \\brief Constructs cell ranges.\n     * \\param nmax Compute and store cell ranges for up to nmax groups\n     * \\param gridView the grid view to use (usually a leaf view). The iterators returned by the grid view\n     *                 have to be valid for the lifetime of the CellRanges object - usually this means the \n     *                 grid shall not be modified/adapted.\n     */\n    CellRanges(int nmax, GridView const& gridView): cellRanges(nmax+1)\n    {\n      // We know how many iterators we will insert - allocate space beforehand. \n      for (int n=1; n<=nmax; ++n)\n        cellRanges[n].reserve(n+1);\n      \n      // number of cells\n      size_t const size = gridView.size(0);\n      \n      // Step through all cells, storing the iterator in case it is at a boundary of cell ranges.\n      // The iteration through the cells is monotone, hence the ranges we construct cannot overlap. If few\n      // cells exist, some ranges may be empty, however. \n      // The following postconditions hold: \n      // (i) cellRanges[n].size() <= n. \n      // Proof: Assume cellRanges[n].size()==n. Then there is no cell with j >= size (it is at most size-1), where a further push_back could happen.\n      // (ii) cellRanges[n][0] == begin. \n      // Proof: In the first iterations j==0 and cellRanges[n].size()==0 holds, such that 0>=0 evaluates true and triggers the push_back(begin).\n      // (iii) any range contains less than size/n + 1 cells.\n      // Proof: Assume a range [r,s[. Then there is k with r>=k*size/n and t<(k+1)*size/n for all t<s. Thus s-1-r < ((k+1)-k)*size/n = size/n,\n      // such that the length is s-r < size/n + 1.\n      size_t j = 0; // cell counter\n      for (CellIterator i=gridView.template begin<0>(); i!=gridView.template end<0>(); ++i, ++j)\n        for (int n=1; n<=nmax; ++n)\n          if (j >= cellRanges[n].size()*size/n)\n            cellRanges[n].push_back(i);\n\n      // Now we have to make sure that every range vector contains the number of ranges it's supposed to hold. Add empty ranges as needed.\n      // As up to here the size of cellRanges[n] is at most n (not n+1), we automatically take care of terminating the last range with \n      // the end iterator.\n      for (int n=1; n<=nmax; ++n)\n        while (cellRanges[n].size()<n+1)\n          cellRanges[n].push_back(gridView.template end<0>());\n    }\n    \n    /**\n     * \\brief Obtain cell range.\n     * \\param n the number of cell ranges (1<=n<=maxRanges())\n     * \\param k the k-th range will be returned (0<=k<n)\n     */\n    boost::iterator_range<CellIterator> range(int n, int k) const\n    {\n      assert(1<=n && n<cellRanges.size());\n      assert(0<=k && k<n);\n      return boost::iterator_range<CellIterator>(cellRanges[n][k],cellRanges[n][k+1]);\n    }\n    \n    /**\n     * \\brief Obtain the maximum number of ranges.\n     * Default constructed \"empty\" cell ranges return a negative value.\n     */\n    int maxRanges() const\n    {\n      return static_cast<int>(cellRanges.size())-1;\n    }\n    \n  private:\n    std::vector<std::vector<CellIterator>> cellRanges;\n  };\n  \n  //----------------------------------------------------------------------------------------\n  \n  /**\n   * \\ingroup grid\n   * \\brief Basic functionality for managing grids and their refinement.\n   */\n  template<class Grd>\n  class GridManagerBase\n  {\n    typedef Grd Grid;\n  public:    \n    \n    typedef GridManagerBase<Grid> Self;\n    \n    GridManagerBase(Dune::GridPtr<Grid> grid_, bool verbose_, bool enforceConcurrentReads = false)\n    : GridManagerBase(grid_.release(),verbose_,enforceConcurrentReads)\n    {}\n\n    GridManagerBase(std::unique_ptr<Grid>&& grid_, bool verbose_, bool enforceConcurrentReads = false)\n    : GridManagerBase(grid_.release(),verbose_,enforceConcurrentReads)\n    {}\n\n    GridManagerBase(Grid*&& grid_, bool verbose_, bool enforceConcurrentReads = false):\n      markedAny(false), gridptr(grid_), measureTime(false),\n      gridIsThreadSafe_(Dune::Capabilities::viewThreadSafe<Grid>::v), enforceConcurrentReads_(enforceConcurrentReads),\n      levelRanges(gridptr->maxLevel()+1), verbose(verbose_)\n    {}\n\n    virtual ~GridManagerBase() {};\n\n    /// Returns a const reference on the owned grid\n    Grid const& grid() const\n    {\n      return *gridptr;\n    }\n    \n    /// Returns a non-const reference on the owned grid\n    Grid& grid_non_const()\n    {\n      return *gridptr;\n    }\n\n    /**\n     * \\brief Provides shared ownership management. \n     * \n     * Note that only an immutable grid is provided, such that the responsibility for \n     * grid modifications remains with the GridManager object. This is necessary for the \n     * GridManager to trigger prolongation/interpolation on grid modification.\n     */\n    std::shared_ptr<Grid const> gridShared() const\n    {\n      return gridptr;\n    }\n\n\n    bool adaptAtOnce()\n    {\n      this->preAdapt();\n      bool result = adapt();\n#if !defined(NDEBUG)\n      if(!result) std::cout << \"GRIDMANAGER: Nothing has been refined!\" << std::endl;\n#endif\n      this->postAdapt();\n      return result;\n    }\n\n    // will be removed after 2014-10-31\n    /// Calls grid.mark(...): Marks an Entity T by an integer refCount\n    bool mark(int refCount, typename Grid::template Codim<0>::EntityPointer e) __attribute((deprecated)) \n    {\n      if(refCount != 0)\n      {\n        markedAny = true;\n        return gridptr->mark(refCount,*e);\n      }\n      return false;\n    }\n\n    /// Calls grid.mark(...): Marks an Entity T by an integer refCount\n    bool mark(int refCount, typename Grid::template Codim<0>::Entity const& e) \n    {\n      if(refCount != 0)\n      {\n        markedAny = true;\n        return gridptr->mark(refCount,e);\n      }\n      return false;\n    }\n\n    /// Marks all Entities of a grid according to the corresponding entries in a CellData\n    template<class S>\n    void mark(CellData<Grid,S> const& cellData)\n    {\n      this->flushMarks();\n      typename CellData<Grid,S>::CellDataVector::const_iterator imark;\n      typename CellData<Grid,S>::CellDataVector::const_iterator imark_end = cellData.end();\n      for(imark=cellData.begin(); imark != imark_end; ++imark)\n        if(!this->mark(imark->first,imark->second) && imark->first!=0) \n          std::cout << \"GRIDMANAGER: Warning: Cannot mark element!\" << std::endl;\n      this->markedAny = true;\n    }\n\n    /**\n     * \\brief Marks a cell by its index.\n     * \n     * \\warning The computational complexity of this method is the number of cells in the grid, i.e., calling this\n     *          is dead slow.\n     */\n    void markByIndex(int refCount, int index)\n    {\n      auto cend = gridptr->leafIndexSet().template end<0, Dune::All_Partition>();\n      for (auto ci=gridptr->leafIndexSet().template begin<0,Dune::All_Partition>(); ci!=cend; ++ci) {\n        if(gridptr->leafIndexSet().index(*ci)==index) \n          mark(refCount,ci);\n      }\n    }\n\n    /**\n     * \\brief Reports the number of marked elements.\n     * \n     * Elements may be marked for multiple refinement. This is reflected in the sum. The exact \n     * number returned is \\f[ \\sum_i r_i, \\f] where \\f$ r_i \\f$ is the refinement count for \n     * cell \\f$ i \\f$.\n     */\n    size_t countMarked() const\n    {\n      size_t marks(0);\n      auto cend = gridptr->template leafend<0>();\n      for (auto ci=gridptr->template leafbegin<0>(); ci!=cend; ++ci) \n        marks += abs(gridptr->getMark(*ci));\n      std::cout << \"GRIDMANAGER: \" << marks << \" marked elements!\" << std::endl;\n      return marks;\n    }\n\n    /// Calls grid.preAdapt().\n    bool preAdapt() { \n      if(markedAny) \n        return gridptr->preAdapt(); \n      else \n        return false; \n    };\n\n    /// Calls grid.postAdapt().\n    void postAdapt()\n    {\n      gridptr->postAdapt();\n\n      if(verbose)\n        std::cout << \"after refinement: \" << gridptr->size(0) << \" cells, \" << gridptr->size(Grid::dimension) << \" vertices.\" << std::endl;\n    };\n\n\n    /// Remove all marks from the grid\n    void flushMarks()\n    {\n      auto lend = gridptr->template leafend<0>();\n      for(auto li=gridptr->template leafbegin<0>(); li !=lend; ++li) \n        mark(0,*li);\n      markedAny = false;\n    }\n\n    /**\n     * \\brief Tells the grid manager that concurrent reads of the grid are safe.\n     */\n    Self& enforceConcurrentReads(bool enforceConcurrentReads) \n    { \n      enforceConcurrentReads_ = enforceConcurrentReads; \n      return *this; \n    }\n\n    /**\n     * \\brief Tells the grid manager whether to report timing statistics to standard output.\n     */\n    Self& setMeasureTime(bool measureTime_) { measureTime = measureTime_; return *this; }\n\n    /**\n     * \\brief sets the verbosity level of the grid manager\n     *\n     * The grid manager prints status and progress information to std::cout. The amount of\n     * information depends on the verbosity:\n     * - 0: no messages are printed\n     * - 1: mesh size change on refinement is reported\n     */\n    Self& setVerbosity(const bool verbosity) { verbose = verbosity; return *this; }\n\n    /**\n     * \\brief Returns true if concurrent read accesses to the grid do not lead to data races.\n     * \n     * This is either the case if the grid implementation itself reports that it's thread-safe, or if the \n     * user has explicitly stated that concurrent reads are safe (using enforceConcurrentReads).\n     * \n     * The thread-safety reported by this method is used e.g. by the assembler to decide how many threads \n     * to use during assembly.\n     */\n    bool gridIsThreadSafe() const\n    {\n#ifdef NDEBUG\n      return gridIsThreadSafe_ || enforceConcurrentReads_;\n#else\n      std::cout << \"GRIDMANAGER: No Multithreading in DEBUG mode!\" << std::endl;\n      return false;\n#endif\n    }\n\n    template<class TM, class FSE>\n    struct TransFSE\n    {\n      TransFSE(TM const& mat_, FSE& fse_) : mat(mat_), fse(fse_) {}\n\n      void operator()()\n      {\n        fse.transfer(mat);\n      }\n\n      TM const& mat;\n      FSE& fse;\n    };\n\n\n    template<class TM, class FSE>\n    void transferFSE(TM const& mat, FSE& fse) const\n    {\n#ifdef MULTITHREAD\n      pool->schedule(TransFSE<TM, FSE>(mat,fse));\n#else\n      fse.transfer(mat);\n#endif\n    }\n\n    template<class TD, class Space>\n    struct TransBefore\n    {\n      TransBefore(TD* td_, Space const& space_) : td(td_), space(space_) {}\n\n      void operator()()\n      {\n        td = new TD(space);\n      }\n\n      TD* td;\n      Space const& space;\n    };\n\n\n\n\n    template<class TransferD, class Space>\n    void getTransferData(TransferD*& result, Space const& space)\n    {\n#ifdef MULTITHREAD\n      pool->schedule(TransBefore<TransferD, Space>(result,space));\n#else\n      result = (new TransferD(space));\n#endif\n    }\n\n\n    template<class TD, class TM, class Space>\n    struct TransAfter\n    {\n      TransAfter(TD* td_, TM* result_, Space const& space_, GridManagerBase<Grd>const & gm_) : td(td_), result(result_), space(space_), gm(gm_) {}\n\n      void operator()()\n      {\n        result=td->transferMatrix().release();\n        space.requestToRefine(*result,gm);\n      }\n\n      TD* td;\n      TM* result;\n      Space const& space;\n      GridManagerBase<Grd> const& gm;\n    };\n\n    template<class TransferD, class Space>\n    void getTransferMatrix(TransferD* transferData, typename TransferD::TransferMatrix*& result, Space const& space)\n    {\n#ifdef MULTITHREAD\n      pool->schedule(TransAfter<TransferD,typename TransferD::TransferMatrix, Space>(transferData,result,space,*this));\n#else\n      result = transferData->transferMatrix().release();\n      space.requestToRefine(*result,*this);\n#endif\n    }\n\n    // TODO: docme\n    bool adapt()\n    {\n      bool result;\n      if(this->markedAny) {\n\n        boost::timer::cpu_timer timer;\n        if(measureTime) std::cout << \"GRIDMANAGER: Preref.:\" << std::flush;\n        this->beforeRefinement();\n        if(measureTime) std::cout << boost::timer::format(timer.elapsed()) << std::endl;\n\n        if (verbose)  std::cout << std::endl << \"GRIDMANAGER: mesh is refined from \" << this->gridptr->size(0) << \" cells \" << std::flush;\n\n        timer.start();\n        if(measureTime) std::cout << \"GRIDMANAGER: Refinement: \" << std::flush;\n        result = adaptGrid();\n        update();\n        if(measureTime) std::cout << boost::timer::format(timer.elapsed()) << std::endl;\n\n        if(verbose) std::cout << \"to \" << this->gridptr->size(0) << \" cells\" << std::endl;\n\n#if !defined(NDEBUG)\n        if(!result) std::cout << \"GRIDMANAGER: Warning: no refinement made!\" << std::endl;\n#endif\n\n        timer.start();\n        if(measureTime) std::cout << \"GRIDMANAGER: Postref.: \" << std::flush;\n        this->afterRefinement();\n        if(measureTime) std::cout << boost::timer::format(timer.elapsed()) << std::endl;\n\n        this->markedAny = false;\n      } else\n        result = false;\n      return result;\n    }\n\n    /// Refines the grid and transfers the data\n    /** Calls grid.globalRefine(...) and performs the transfer of data\n     * between the old and the new grid. If measureTime is true, then some\n     * output on time needed the for the steps is given.\n     */\n    void globalRefine(int refCount) {\n      if(refCount==0) return;\n      if(refCount == -1) refCount=0;\n\n      boost::timer::cpu_timer timer;\n      if(measureTime) std::cout << \"GRIDMANAGER: Preref.:\" << std::flush;\n      this->beforeRefinement();\n      if(measureTime) std::cout << boost::timer::format(timer.elapsed()) << std::endl;\n\n      timer.start();\n      if(measureTime) std::cout << \"GRIDMANAGER: Refinement: \" << std::flush;\n      refineGrid(refCount);\n      update();\n      if(measureTime) std::cout << boost::timer::format(timer.elapsed()) << std::endl;\n\n      timer.start();\n      if(measureTime) std::cout << \"GRIDMANAGER: Postref.: \" << std::flush;\n      this->afterRefinement();\n      if(measureTime) std::cout << boost::timer::format(timer.elapsed()) << std::endl;\n\n      this->markedAny=false;\n    };\n\n    /**\n     * \\brief Must be overloaded by derived classes to adjust internal state immediately after mesh refinement.\n     */\n    virtual void update() = 0;\n    \n    /**\n     * \\brief DEPRECATED, use cellRanges(gridView) instead\n     */\n    CellRanges<typename Grid::LeafGridView> const& leafCellRanges() const\n    {\n      if (!leafRanges)\n        leafRanges.reset(new CellRanges<typename Grid::LeafGridView>(NumaThreadPool::instance().cpus(),grid().leafGridView()));\n      return *leafRanges;\n    }\n    \n    /**\n     * \\brief Returns a CellRanges object for the given grid view.\n     * The cell ranges are created on demand. The reference is valid up to the next mesh modification. This method is *not* thread-safe.\n     * \\todo implement locking just to make sure\n     */\n    CellRanges<typename Grid::LeafGridView> const& cellRanges(typename Grid::LeafGridView const&) const\n    {\n      if (!leafRanges)\n        leafRanges.reset(new CellRanges<typename Grid::LeafGridView>(2*NumaThreadPool::instance().cpus(),grid().leafGridView()));\n      return *leafRanges;\n    }\n    \n    /**\n     * \\brief Returns a CellRanges object for the given grid view.\n     * \\param gridView a level grid view of the grid managed by this grid manager\n     * \n     * The cell ranges are created on demand. The reference is valid up to the next mesh modification. This method is *not* thread-safe.\n     * \\todo implement locking just to make sure\n     */\n    CellRanges<typename Grid::LevelGridView> const& cellRanges(typename Grid::LevelGridView const& gridView) const\n    {\n      int const level = gridView.template begin<0>()->level(); // cells have the level of their level view (inferred from the Dune tutorial)\n      assert(level<=grid().maxLevel());\n      \n      if (levelRanges[level].maxRanges()<0)\n        levelRanges[level] = CellRanges<typename Grid::LevelGridView>(2*NumaThreadPool::instance().cpus(),grid().levelGridView(level));\n        // we could have used gridView directly here. But can we make sure this is a level view of the grid we keep?\n      return levelRanges[level];\n    }\n    \n    \n    // TODO: docme\n    bool markedAny;\n\n  private:\n    // TODO: docme!\n    virtual void refineGrid(int refcount) = 0;\n    virtual bool adaptGrid() = 0;\n\n  protected:\n    void beforeRefinement()\n    {\n      // trigger creation of transfer data structures\n#ifdef MULTITHREAD\n      pool.reset(new boost::threadpool::pool(16));\n#endif\n      signals.informAboutRefinement(GridSignals::BeforeRefinement);\n#ifdef MULTITHREAD\n      pool->wait(0);\n#endif\n      \n      // invalidate the cell range data structures\n      leafRanges.reset();\n      levelRanges.clear();\n    }\n\n    void afterRefinement()\n    {\n      levelRanges.resize(grid().maxLevel()+1);\n#ifdef MULTITHREAD\n      std::cout << \"multithreading enabled\" << std::endl;\n#endif\n      signals.informAboutRefinement(GridSignals::AfterRefinement);\n#ifdef MULTITHREAD\n      pool->wait(0);\n#endif\n      signals.informAboutRefinement(GridSignals::TransferCompleted);\n#ifdef MULTITHREAD\n      pool->wait(0);\n      pool.reset();\n#endif\n    }\n\n    template<class LocalToGlobalMapper> friend class FEFunctionSpace;\n    template<class GridMan, class ErrEst> friend class AdaptiveGrid;\n\n    /**\n     * \\brief The grid itself.\n     */\n    std::shared_ptr<Grid> gridptr;\n    \n#ifdef MULTITHREAD\n    std::unique_ptr<boost::threadpool::pool> pool;\n#endif\n\n  public:\n    GridSignals signals;\n\n  private:\n    /// true: Print timing information, false: don't\n    bool measureTime;\n\n    const bool gridIsThreadSafe_;\n    \n    /// enforce concurrent reads for grids that possibly do not support concurrency\n    bool enforceConcurrentReads_;\n    \n    // cell ranges are constructed on demand\n    mutable std::unique_ptr<CellRanges<typename Grid::LeafGridView>> leafRanges;\n    mutable std::vector<CellRanges<typename Grid::LevelGridView>> levelRanges;\n\n  protected:\n    bool verbose;\n  };\n\n  // -------------------------------------------------------------------\n  \n  /** \n   * \\ingroup grid\n   * \\brief Class that takes care of the transfer of data (of each FunctionSpaceElement) after modification of the grid\n   *\n   * Class that owns a grid. It takes care that all grid functions stay\n   * consistent, when the grid is refined. A Gridmanager<Grid> is constructed with a\n   * GridPointer<Grid>,  a std::unique_ptr<Grid>&& or an r-value reference on a Grid*. After this, all\n   * modifications on the grid have to be done via the GridManager, in\n   * particular refinement. If the grid is refined, the GridManager sends a\n   * boost::signal to each FEFunctionSpace, which themselves send a\n   * boost::signal to each FunctionSpaceElement, such that their transfer\n   * from one grid to the other is organized.\n   * \n   * The grid manager can print status and progress information to std::cout, see \\ref setVerbosity.\n\n   * <b> Examples for usage </b>\n\n - Construction\n\n \\verbatim\n Dune::GridPtr<Grid> gridptr(\"MyDomain.dgf\");\n GridManager<Grid> gm(gridptr);\n \\endverbatim\n\n - Alternative construction\n\n \\verbatim\n std::unique_ptr<Grid> gridptr(new ...);\n GridManager<Grid> gm(gridptr);\n \\endverbatim\n\n - Construction of FEFunctionSpaces with GridManager:\n\n \\verbatim\n MySpace mySpace(gm,gm.grid().leafIndexSet(),order) //instead of: MySpace mySpace(grid,grid().leafIndexSet(),order)\n \\endverbatim\n\n - Uniform Refinement:\n\n \\verbatim\n gm.globalRefine(nTimes) //instead of: grid.globalRefine(nTimes)\n \\endverbatim\n\n - Adaptivity\n\n Cf. detailed description of averaging_errorest.hh\n   */\n  template <class Grd>\n  class GridManager : public GridManagerBase<Grd>{\n  public:\n    typedef Grd Grid;\n    /// Construction from a GridPtr<Grid>\n    /** Construct a GridManager<Grid> from a GridPointer<Grid>. The\n     * ownership of the grid is transferred to the GridManager. Afterwards\n     * the grid can only be modified via the GridManager.\n     */\n    explicit GridManager(Dune::GridPtr<Grid> grid_, bool verbose=false) : GridManagerBase<Grid>(grid_,verbose)\n    {}\n\n    /// Construction from an unique_ptr<Grid>\n    /** Construct a GridManager<Grid> from a std::unique_ptr<Grid>. The\n     * ownership of the grid is transferred to the GridManager. Afterwards\n     * the grid can only be modified via the GridManager.\n     */\n    explicit GridManager(std::unique_ptr<Grid>&& grid_, bool verbose=false) : GridManagerBase<Grid>( std::move(grid_),verbose)\n    {}\n\n    /// Construction from a Grid*\n    /** Construct a GridManager<Grid> from a std::unique_ptr<Grid>. The\n     * ownership of the grid is transferred to the GridManager. Afterwards\n     * the grid can only be modified via the GridManager.\n     */\n    explicit GridManager(Grid*&& grid_, bool verbose=false) : GridManagerBase<Grid>( std::move(grid_),verbose)\n    {}\n\n\n    virtual void update() {}\n\n  private:\n    virtual void refineGrid(int refCount)\n    {\n      this->gridptr->globalRefine(refCount);\n    };\n\n\n    virtual bool adaptGrid()\n    {\n      return this->gridptr->adapt();\n    };\n  };\n\n\n  //---------------------------------------------------------------------\n\n  /**\n   * \\ingroup grid\n   * \\brief A convenience routine that refines all cells incident to a boundary face. \n   * \n   * This is useful to create a priori boundary-refined meshes.\n   */\n  template <class Grid>\n  void refineAtBoundary(GridManager<Grid>& gridManager)\n  {\n    auto lend = gridManager.grid().template leafend<0>();\n    for (auto i=gridManager.grid().template leafbegin<0>(); i!=lend; ++i)\n      if (i->hasBoundaryIntersections())\n        gridManager.mark(1,i);\n    gridManager.adaptAtOnce();\n  }\n}\n\n#endif /* GRIDMANAGER_HH_ */\n", "meta": {"hexsha": "f1501311793beefa490566ceb872deb9e3ee9904", "size": 24435, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/gridmanager.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/gridmanager.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/gridmanager.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 32.975708502, "max_line_length": 148, "alphanum_fraction": 0.6254962144, "num_tokens": 6020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1778108694780496, "lm_q2_score": 0.0440186461006112, "lm_q1q2_score": 0.007826993736396236}}
{"text": "// Copyright (C) 2003-2011 Anders Logg\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// Modified by Garth N. Wells 2005-2010\n// Modified by Martin Sandve Alnes 2008\n// Modified by Andre Massing 2009\n//\n// First added:  2003-11-28\n// Last changed: 2011-11-14\n\n#include <algorithm>\n#include <map>\n#include <utility>\n#include <vector>\n#include <boost/assign/list_of.hpp>\n\n#include <dolfin/adaptivity/Extrapolation.h>\n#include <dolfin/common/utils.h>\n#include <dolfin/common/Array.h>\n#include <dolfin/common/NoDeleter.h>\n#include <dolfin/fem/FiniteElement.h>\n#include <dolfin/fem/GenericDofMap.h>\n#include <dolfin/fem/DirichletBC.h>\n#include <dolfin/fem/UFC.h>\n#include <dolfin/io/File.h>\n#include <dolfin/io/XMLFile.h>\n#include <dolfin/la/GenericVector.h>\n#include <dolfin/la/DefaultFactory.h>\n#include <dolfin/log/log.h>\n#include <dolfin/mesh/Mesh.h>\n#include <dolfin/mesh/Vertex.h>\n#include <dolfin/mesh/ParallelData.h>\n#include <dolfin/mesh/Point.h>\n#include <dolfin/parameter/GlobalParameters.h>\n#include \"Expression.h\"\n#include \"FunctionSpace.h\"\n#include \"Function.h\"\n\nusing namespace dolfin;\n\n//-----------------------------------------------------------------------------\nFunction::Function(const FunctionSpace& V)\n  : Hierarchical<Function>(*this),\n    _function_space(reference_to_no_delete_pointer(V)),\n    allow_extrapolation(dolfin::parameters[\"allow_extrapolation\"])\n{\n  // Check that we don't have a subspace\n  if (V.component().size() > 0)\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"create function\",\n                 \"Cannot be created from subspace. Consider collapsing the function space\");\n  }\n\n  // Initialize vector\n  init_vector();\n}\n//-----------------------------------------------------------------------------\nFunction::Function(boost::shared_ptr<const FunctionSpace> V)\n  : Hierarchical<Function>(*this), _function_space(V),\n    allow_extrapolation(dolfin::parameters[\"allow_extrapolation\"])\n{\n  // Check that we don't have a subspace\n  if (V->component().size() > 0)\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"create function\",\n                 \"Cannot be created from subspace. Consider collapsing the function space\");\n  }\n\n  // Initialize vector\n  init_vector();\n}\n//-----------------------------------------------------------------------------\nFunction::Function(boost::shared_ptr<const FunctionSpace> V,\n                   boost::shared_ptr<GenericVector> x)\n  : Hierarchical<Function>(*this), _function_space(V), _vector(x),\n    allow_extrapolation(dolfin::parameters[\"allow_extrapolation\"])\n{\n  // We do not check for a subspace since this constructor is used for creating\n  // subfunctions\n\n  // Assertion uses '<=' to deal with sub-functions\n  dolfin_assert(V->dofmap());\n  dolfin_assert(V->dofmap()->global_dimension() <= x->size());\n}\n//-----------------------------------------------------------------------------\nFunction::Function(const FunctionSpace& V, std::string filename)\n  : Hierarchical<Function>(*this),\n    _function_space(reference_to_no_delete_pointer(V)),\n    allow_extrapolation(dolfin::parameters[\"allow_extrapolation\"])\n{\n  // Check that we don't have a subspace\n  if (V.component().size() > 0)\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"create function\",\n                 \"Cannot be created from subspace. Consider collapsing the function space\");\n  }\n\n  // Initialize vector\n  init_vector();\n\n  // Check size of vector\n  if (_vector->size() != _function_space->dim())\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"read function from file\",\n                 \"The number of degrees of freedom (%d) does not match dimension of function space (%d)\",\n                 _vector->size(), _function_space->dim());\n  }\n\n  // Read function data from file\n  File file(filename);\n  file >> *this;\n}\n//-----------------------------------------------------------------------------\nFunction::Function(boost::shared_ptr<const FunctionSpace> V,\n                   std::string filename)\n  : Hierarchical<Function>(*this), _function_space(V),\n    allow_extrapolation(dolfin::parameters[\"allow_extrapolation\"])\n{\n  // Check that we don't have a subspace\n  if (V->component().size() > 0)\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"create function\",\n                 \"Cannot be created from subspace. Consider collapsing the function space\");\n  }\n\n  // Initialize vector\n  init_vector();\n\n  // Check size of vector\n  if (_vector->size() != _function_space->dim())\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"read function from file\",\n                 \"The number of degrees of freedom (%d) does not match dimension of function space (%d)\",\n                 _vector->size(), _function_space->dim());\n  }\n\n  // Read function data from file\n  File file(filename);\n  file >> *this;\n}\n//-----------------------------------------------------------------------------\nFunction::Function(const Function& v)\n  : Hierarchical<Function>(*this),\n    allow_extrapolation(dolfin::parameters[\"allow_extrapolation\"])\n{\n  // Assign data\n  *this = v;\n}\n//-----------------------------------------------------------------------------\nFunction::Function(const Function& v, uint i)\n  : Hierarchical<Function>(*this),\n    allow_extrapolation(dolfin::parameters[\"allow_extrapolation\"])\n{\n  // Copy function space pointer\n  this->_function_space = v[i]._function_space;\n\n  // Copy vector pointer\n  this->_vector = v[i]._vector;\n}\n//-----------------------------------------------------------------------------\nFunction::~Function()\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nconst Function& Function::operator= (const Function& v)\n{\n  dolfin_assert(v._vector);\n\n  // Make a copy of all the data, or if v is a sub-function, then we collapse\n  // the dof map and copy only the relevant entries from the vector of v.\n  if (v._vector->size() == v._function_space->dim())\n  {\n    // Copy function space\n    _function_space = v._function_space;\n\n    // Copy vector\n    _vector.reset(v._vector->copy());\n\n    // Clear subfunction cache\n    sub_functions.clear();\n  }\n  else\n  {\n    // Create new collapsed FunctionSpace\n    boost::unordered_map<uint, uint> collapsed_map;\n    _function_space = v._function_space->collapse(collapsed_map);\n\n    // FIXME: This dolfin_assertion doesn't work in parallel\n    //dolfin_assert(collapsed_map.size() == _function_space->dofmap()->global_dimension());\n    //dolfin_assert(collapsed_map.size() == _function_space->dofmap()->local_dimension());\n\n    // Get row indices of original and new vectors\n    boost::unordered_map<uint, uint>::const_iterator entry;\n    std::vector<uint> new_rows(collapsed_map.size());\n    Array<uint> old_rows(collapsed_map.size());\n    uint i = 0;\n    for (entry = collapsed_map.begin(); entry != collapsed_map.end(); ++entry)\n    {\n      new_rows[i]   = entry->first;\n      old_rows[i++] = entry->second;\n    }\n\n    // Gather values into an Array\n    Array<double> gathered_values;\n    dolfin_assert(v.vector());\n    v.vector()->gather(gathered_values, old_rows);\n\n    // Initial new vector (global)\n    init_vector();\n    dolfin_assert(_function_space->dofmap());\n    dolfin_assert(_vector->size() == _function_space->dofmap()->global_dimension());\n\n    // Set values in vector\n    this->_vector->set(&gathered_values[0], collapsed_map.size(), &new_rows[0]);\n    this->_vector->apply(\"insert\");\n  }\n\n  // Call assignment operator for base class\n  Hierarchical<Function>::operator=(v);\n\n  return *this;\n}\n//-----------------------------------------------------------------------------\nconst Function& Function::operator= (const Expression& v)\n{\n  interpolate(v);\n  return *this;\n}\n//-----------------------------------------------------------------------------\nFunction& Function::operator[] (uint i) const\n{\n  // Check if sub-Function is in the cache, otherwise create and add to cache\n  boost::ptr_map<uint, Function>::iterator sub_function = sub_functions.find(i);\n  if (sub_function != sub_functions.end())\n    return *(sub_function->second);\n  else\n  {\n    // Extract function subspace\n    std::vector<uint> component = boost::assign::list_of(i);\n    boost::shared_ptr<const FunctionSpace> sub_space(_function_space->extract_sub_space(component));\n\n    // Insert sub-Function into map and return reference\n    sub_functions.insert(i, new Function(sub_space, _vector));\n    return *(sub_functions.find(i)->second);\n  }\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const FunctionSpace> Function::function_space() const\n{\n  dolfin_assert(_function_space);\n  return _function_space;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<GenericVector> Function::vector()\n{\n  dolfin_assert(_vector);\n  dolfin_assert(_function_space->dofmap());\n\n  // Check that this is not a sub function.\n  if (_vector->size() != _function_space->dofmap()->global_dimension())\n  {\n    cout << \"Size of vector: \" << _vector->size() << endl;\n    cout << \"Size of function space: \" << _function_space->dofmap()->global_dimension() << endl;\n    dolfin_error(\"Function.cpp\",\n                 \"access vector of degrees of freedom fro function\",\n                 \"Cannot access a non-const vector from a subfunction\");\n  }\n  return _vector;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const GenericVector> Function::vector() const\n{\n  dolfin_assert(_vector);\n  return _vector;\n}\n//-----------------------------------------------------------------------------\nbool Function::in(const FunctionSpace& V) const\n{\n  dolfin_assert(_function_space);\n  return *_function_space == V;\n}\n//-----------------------------------------------------------------------------\ndolfin::uint Function::geometric_dimension() const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->mesh());\n  return _function_space->mesh()->geometry().dim();\n}\n//-----------------------------------------------------------------------------\nvoid Function::eval(Array<double>& values, const Array<double>& x) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->mesh());\n  const Mesh& mesh = *_function_space->mesh();\n\n  // Find the cell that contains x\n  const double* _x = x.data().get();\n  const Point point(mesh.geometry().dim(), _x);\n  int id = mesh.intersected_cell(point);\n\n  // If not found, use the closest cell\n  if (id == -1)\n  {\n    if (allow_extrapolation)\n    {\n      id = mesh.closest_cell(point);\n      cout << \"Extrapolating function value at x = \" << point << \" (not inside domain).\" << endl;\n    }\n    else\n    {\n      cout << \"Evaluating at x = \" << point << endl;\n      dolfin_error(\"Function.cpp\",\n                   \"evaluate function at point\",\n                   \"The point is not inside the domain. Consider setting \\\"allow_extrapolation\\\" to allow extrapolation\");\n    }\n  }\n\n  // Create cell that contains point\n  const Cell cell(mesh, id);\n  const UFCCell ufc_cell(cell, false);\n\n  // Call evaluate function\n  eval(values, x, cell, ufc_cell);\n}\n//-----------------------------------------------------------------------------\nvoid Function::eval(Array<double>& values,\n                    const Array<double>& x,\n                    const Cell& dolfin_cell,\n                    const ufc::cell& ufc_cell) const\n{\n  // Developer note: work arrays/vectors are re-created each time this function\n  //                 is called for thread-safety\n\n  dolfin_assert(_function_space->element());\n  const FiniteElement& element = *_function_space->element();\n\n  // FIXME: Rather than computing num_tensor_entries, we could just use\n  //        values.size()\n\n  // Compute in tensor (one for scalar function, . . .)\n  uint num_tensor_entries = 1;\n  for (uint i = 0; i < element.value_rank(); i++)\n    num_tensor_entries *= element.value_dimension(i);\n\n  dolfin_assert(values.size() == num_tensor_entries);\n\n  // Create work vector for expansion coefficients\n  std::vector<double> coefficients(element.space_dimension());\n\n  // Restrict function to cell\n  restrict(&coefficients[0], element, dolfin_cell, ufc_cell);\n\n  // Create work vector for basis\n  std::vector<double> basis(num_tensor_entries);\n\n  // Initialise values\n  for (uint j = 0; j < num_tensor_entries; ++j)\n    values[j] = 0.0;\n\n  // Compute linear combination\n  for (uint i = 0; i < element.space_dimension(); ++i)\n  {\n    element.evaluate_basis(i, &basis[0], &x[0], ufc_cell);\n    for (uint j = 0; j < num_tensor_entries; ++j)\n      values[j] += coefficients[i]*basis[j];\n  }\n}\n//-----------------------------------------------------------------------------\nvoid Function::interpolate(const GenericFunction& v)\n{\n  // Gather off-process dofs\n  v.gather();\n\n  // Initialise vector\n  init_vector();\n\n  // Interpolate\n  dolfin_assert(_function_space);\n  _function_space->interpolate(*_vector, v);\n}\n//-----------------------------------------------------------------------------\nvoid Function::extrapolate(const Function& v)\n{\n  Extrapolation::extrapolate(*this, v);\n}\n//-----------------------------------------------------------------------------\ndolfin::uint Function::value_rank() const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->element());\n  return _function_space->element()->value_rank();\n}\n//-----------------------------------------------------------------------------\ndolfin::uint Function::value_dimension(uint i) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->element());\n  return _function_space->element()->value_dimension(i);\n}\n//-----------------------------------------------------------------------------\nvoid Function::eval(Array<double>& values, const Array<double>& x,\n                    const ufc::cell& ufc_cell) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->mesh());\n  const Mesh& mesh = *_function_space->mesh();\n\n  // Check if UFC cell comes from mesh, otherwise redirect to\n  // evaluate on non-matching cell\n  if (ufc_cell.mesh_identifier == (int) mesh.id())\n  {\n    const Cell cell(mesh, ufc_cell.index);\n    eval(values, x, cell, ufc_cell);\n  }\n  else\n    non_matching_eval(values, x, ufc_cell);\n}\n//-----------------------------------------------------------------------------\nvoid Function::non_matching_eval(Array<double>& values,\n                                 const Array<double>& x,\n                                 const ufc::cell& ufc_cell) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->mesh());\n  const Mesh& mesh = *_function_space->mesh();\n\n  const double* _x = x.data().get();\n  const uint dim = mesh.geometry().dim();\n  const Point point(dim, _x);\n\n  // Alternative 1: Find cell that point (x) intersects\n  int id = mesh.intersected_cell(point);\n\n  if (id == -1 && !allow_extrapolation)\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"evaluate function at point\",\n                 \"The point is not inside the domain. Consider setting \\\"allow_extrapolation\\\" to allow extrapolation\");\n  }\n\n  // Alternative 2: Compute closest cell to point (x)\n  if (id == -1 && allow_extrapolation && dim == 2)\n    id = mesh.closest_cell(point);\n\n  // Alternative 3: Compute cell that contains barycenter of ufc_cell\n  // NB: This is slightly heuristic, but should work well for\n  // evaluation of points on refined meshes\n  if (id == -1 && allow_extrapolation)\n  {\n    // Extract vertices of ufc_cell\n    const double * const * vertices = ufc_cell.coordinates;\n\n    Point barycenter;\n    for (uint i = 0; i <= dim; i++)\n    {\n      Point vertex(dim, vertices[i]);\n      barycenter += vertex;\n    }\n    barycenter /= (dim + 1);\n    id = mesh.intersected_cell(barycenter);\n  }\n\n  // Throw error if all alternatives failed.\n  if (id == -1)\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"evaluate function at point\",\n                 \"No matching cell found\");\n  }\n\n  // Create cell that contains point\n  const Cell cell(mesh, id);\n  const UFCCell new_ufc_cell(cell, false);\n\n  // Call evaluate function\n  eval(values, x, cell, new_ufc_cell);\n}\n//-----------------------------------------------------------------------------\nvoid Function::restrict(double* w,\n                        const FiniteElement& element,\n                        const Cell& dolfin_cell,\n                        const ufc::cell& ufc_cell) const\n{\n  dolfin_assert(w);\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->dofmap());\n\n  // Check if we are restricting to an element of this function space\n  if (_function_space->has_element(element)\n      && _function_space->has_cell(dolfin_cell))\n  {\n    // Get dofmap for cell\n    const GenericDofMap& dofmap = *_function_space->dofmap();\n    const std::vector<uint>& dofs = dofmap.cell_dofs(dolfin_cell.index());\n\n    // Pick values from vector(s)\n    _vector->get_local(w, dofs.size(), &dofs[0]);\n  }\n  else\n  {\n    // Restrict as UFC function (by calling eval)\n    restrict_as_ufc_function(w, element, dolfin_cell, ufc_cell);\n  }\n}\n//-----------------------------------------------------------------------------\nvoid Function::compute_vertex_values(Array<double>& vertex_values,\n                                     const Mesh& mesh) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->mesh());\n\n  // Check that the mesh matches\n  if (&mesh != _function_space->mesh().get())\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"interpolate function values at vertices\",\n                 \"Non-matching mesh\");\n  }\n\n  // Gather ghosts dofs\n  gather();\n\n  // Get finite element\n  dolfin_assert(_function_space->element());\n  const FiniteElement& element = *_function_space->element();\n\n  // Local data for interpolation on each cell\n  const uint num_cell_vertices = mesh.type().num_vertices(mesh.topology().dim());\n\n  // Compute in tensor (one for scalar function, . . .)\n  uint num_tensor_entries = 1;\n  for (uint i = 0; i < element.value_rank(); i++)\n    num_tensor_entries *= element.value_dimension(i);\n\n  // Resize Array for holding vertex values\n  vertex_values.resize(num_tensor_entries*(_function_space->mesh()->num_vertices()));\n\n  // Create vector to hold cell vertex values\n  std::vector<double> cell_vertex_values(num_tensor_entries*num_cell_vertices);\n\n  // Create vector for expansion coefficients\n  std::vector<double> coefficients(element.space_dimension());\n\n  // Interpolate vertex values on each cell (using last computed value if not\n  // continuous, e.g. discontinuous Galerkin methods)\n  UFCCell ufc_cell(mesh, false);\n  for (CellIterator cell(mesh); !cell.end(); ++cell)\n  {\n    // Update to current cell\n    ufc_cell.update(*cell);\n\n    // Pick values from global vector\n    restrict(&coefficients[0], element, *cell, ufc_cell);\n\n    // Interpolate values at the vertices\n    element.interpolate_vertex_values(&cell_vertex_values[0],\n                                      &coefficients[0], ufc_cell);\n\n    // Copy values to array of vertex values\n    for (VertexIterator vertex(*cell); !vertex.end(); ++vertex)\n    {\n      for (uint i = 0; i < num_tensor_entries; ++i)\n      {\n        const uint local_index  = vertex.pos()*num_tensor_entries + i;\n        const uint global_index = i*mesh.num_vertices() + vertex->index();\n        vertex_values[global_index] = cell_vertex_values[local_index];\n      }\n    }\n  }\n}\n//-----------------------------------------------------------------------------\nvoid Function::gather() const\n{\n  if (MPI::num_processes() > 1)\n    _vector->update_ghost_values();\n}\n//-----------------------------------------------------------------------------\nvoid Function::init_vector()\n{\n  // Check that function space is not a subspace (view)\n  dolfin_assert(_function_space);\n  if (_function_space->dofmap()->is_view())\n  {\n    dolfin_error(\"Function.cpp\",\n                 \"initialize vector of degrees of freedom for function\",\n                 \"Cannot be created from subspace. Consider collapsing the function space\");\n  }\n\n  // Get global size\n  const uint N = _function_space->dofmap()->global_dimension();\n\n  // Get local range\n  const std::pair<uint, uint> range = _function_space->dofmap()->ownership_range();\n  const uint local_size = range.second - range.first;\n\n  // Determine ghost vertices if dof map is distributed\n  std::vector<uint> ghost_indices;\n  if (N  > local_size)\n    compute_ghost_indices(range, ghost_indices);\n\n  // Create vector of dofs\n  if (!_vector)\n  {\n    DefaultFactory factory;\n    _vector.reset(factory.create_vector());\n  }\n  dolfin_assert(_vector);\n\n  // Initialize vector of dofs\n  _vector->resize(range, ghost_indices);\n  _vector->zero();\n}\n//-----------------------------------------------------------------------------\nvoid Function::compute_ghost_indices(std::pair<uint, uint> range,\n                                     std::vector<uint>& ghost_indices) const\n{\n  // Clear data\n  ghost_indices.clear();\n\n  // Get mesh\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->mesh());\n  const Mesh& mesh = *_function_space->mesh();\n\n  // Get dof map\n  dolfin_assert(_function_space->dofmap());\n  const GenericDofMap& dofmap = *_function_space->dofmap();\n\n  // Dofs per cell\n  dolfin_assert(_function_space->element());\n  const uint num_dofs_per_cell = _function_space->element()->space_dimension();\n\n  // Get local range\n  const uint n0 = range.first;\n  const uint n1 = range.second;\n\n  // Iterate over local mesh and check which dofs are needed\n  for (CellIterator cell(mesh); !cell.end(); ++cell)\n  {\n    // Get dofs on cell\n    const std::vector<uint>& dofs = dofmap.cell_dofs(cell->index());\n\n    for (uint d = 0; d < num_dofs_per_cell; ++d)\n    {\n      const uint dof = dofs[d];\n      if (dof < n0 || dof >= n1)\n      {\n        // FIXME: Could we use dolfin::Set here? Or unordered_set?\n        if (std::find(ghost_indices.begin(), ghost_indices.end(), dof) == ghost_indices.end())\n          ghost_indices.push_back(dof);\n      }\n    }\n  }\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "d9990de4e906b8fad549faa8662b8259bf4e9d52", "size": 22692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/function/Function.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/function/Function.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/function/Function.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.5184638109, "max_line_length": 122, "alphanum_fraction": 0.6013573065, "num_tokens": 5072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127868852725, "lm_q2_score": 0.031143833906973895, "lm_q1q2_score": 0.007814386159890866}}
{"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#ifndef MUTABLEVERTEXMESH_HPP_\n#define MUTABLEVERTEXMESH_HPP_\n\n// Forward declaration prevents circular include chain\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nclass VertexMeshWriter;\n\n#include <iostream>\n#include <map>\n#include <algorithm>\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/base_object.hpp>\n#include <boost/serialization/split_member.hpp>\n\n#include \"VertexMesh.hpp\"\n#include \"RandomNumberGenerator.hpp\"\n\n/**\n * A mutable vertex-based mesh class, which inherits from VertexMesh and allows for local\n * remeshing. This is implemented through simple operations including node merging, neighbour\n * exchange (\"T1 swap\"), node/edge merging in the case of intersections (\"T3 swap\") and\n * removal of small triangular elements (\"T2 swap\").\n *\n * MutableVertexMesh is used as a member of the VertexBasedCellPopulation class to represent\n * the junctional network of cells that forms the basis of simulations of off-lattice\n * vertex-based models.\n */\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nclass MutableVertexMesh : public VertexMesh<ELEMENT_DIM, SPACE_DIM>\n{\n    friend class TestMutableVertexMesh;\n    friend class TestMutableVertexMeshReMesh;\n    friend class TestMutableVertexMeshRosetteMethods;\n\nprotected:\n\n    /** The minimum distance apart that two nodes in the mesh can be without causing element rearrangement. */\n    double mCellRearrangementThreshold;\n\n    /**\n     * The ratio between the minimum distance apart that two nodes in the mesh can be without causing element\n     * rearrangement and their separation after remeshing.\n     */\n    double mCellRearrangementRatio;\n\n    /** The area threshold at which T2 swaps occur in an apoptotic, triangular cell/element. */\n    double mT2Threshold;\n\n    /** The probability that, instead of a T1 swap, the relevant nodes merge to form a protorosette */\n    double mProtorosetteFormationProbability;\n\n    /** The probability that, in a given timestep, a protorosette node resolves into two rank-3 nodes */\n    double mProtorosetteResolutionProbabilityPerTimestep;\n\n    /** The probability that, in a given timestep, a rosette node resolves into two lower-rank nodes */\n    double mRosetteResolutionProbabilityPerTimestep;\n\n    /** Whether to check for edges intersections (true) or not (false). */\n    bool mCheckForInternalIntersections;\n\n    /** Indices of nodes that have been deleted. These indices can be reused when adding new elements/nodes. */\n    std::vector<unsigned> mDeletedNodeIndices;\n\n    /** Indices of elements that have been deleted. These indices can be reused when adding new elements. */\n    std::vector<unsigned> mDeletedElementIndices;\n\n    /**\n     * Distance for T3 swap checking. At each time step we check for each boundary node whether\n     * it intersects with any boundary elements (cells) whose centroids lie within this distance\n     * to the node. Note that T3 swaps may not be resolved correctly if this distance is chosen\n     * too small, while large values for mDistanceForT3SwapChecking may slow down the simulation.\n     */\n    double mDistanceForT3SwapChecking;\n\n    /**\n     * Locations of T1 swaps (the mid point of the moving nodes), stored so they can be accessed and output by the cell population.\n     * The locations are stored until they are cleared by ClearLocationsOfT1Swaps().\n     */\n    std::vector< c_vector<double, SPACE_DIM> > mLocationsOfT1Swaps;\n\n    /**\n     * The location of the last T2 swap (the centre of the removed triangle), stored so it can be accessed by the T2SwapCellKiller.\n     */\n    c_vector<double, SPACE_DIM> mLastT2SwapLocation;\n\n    /**\n     * Locations of T3 swaps (the location of the intersection with the edge), stored so they can be accessed and output by the cell population.\n     * The locations are stored until they are cleared by ClearLocationsOfT3Swaps().\n     */\n    std::vector< c_vector<double, SPACE_DIM> > mLocationsOfT3Swaps;\n\n    /**\n     * Locations of intersection swaps (the mid point of the switching nodes), stored so they can be accessed and output by the cell population.\n     * The locations are stored until they are cleared by ClearLocationsOfIntersectionSwaps().\n     */\n    std::vector< c_vector<double, SPACE_DIM> > mLocationsOfIntersectionSwaps;\n\n    /**\n     * Divide an element along the axis passing through two of its nodes.\n     *\n     * \\todo This method currently assumes SPACE_DIM = 2 (see #866)\n     *\n     * @param pElement the element to divide\n     * @param nodeAIndex the local index of one node within this element\n     * @param nodeBIndex the local index of another node within this element\n     * @param placeOriginalElementBelow whether to place the original element below (in the y direction) the new element (defaults to false)\n     *\n     * @return the index of the new element\n     */\n    unsigned DivideElement(VertexElement<ELEMENT_DIM,SPACE_DIM>* pElement,\n                           unsigned nodeAIndex,\n                           unsigned nodeBIndex,\n                           bool placeOriginalElementBelow=false);\n\n    /**\n     * Helper method for ReMesh().\n     *\n     * Check if any neighbouring nodes in an element are closer than the mCellRearrangementThreshold\n     * and are not contained in any triangular elements. If any such pair of nodes are found, then\n     * call IdentifySwapType(), which in turn implements the appropriate local remeshing operation\n     * (a T1 swap, void removal, or node merge).\n     *\n     * @return whether we need to check for, and implement, any further local remeshing operations\n     *                   (true if any swaps are performed).\n     */\n    virtual bool CheckForSwapsFromShortEdges();\n\n    /**\n     * Helper method for ReMesh().\n     *\n     * Check if any elements have become intersected and correct this by implementing the appropriate\n     * local remeshing operation (a T3 swap or node merge).\n     *\n     * @return whether to recheck the mesh again\n     */\n    bool CheckForIntersections();\n\n    /**\n     * Helper method for ReMesh(), called by CheckForSwapsFromShortEdges() when\n     * neighbouring nodes in an element have been found to be closer than the mCellRearrangementThreshold\n     * and do not share any triangular elements.\n     *\n     * Identify the type of local remeshing operation required (T1 swap, void removal, or node merge).\n     *\n     * @param pNodeA one of the nodes to perform the swap with\n     * @param pNodeB the other node to perform the swap\n     */\n    virtual void IdentifySwapType(Node<SPACE_DIM>* pNodeA, Node<SPACE_DIM>* pNodeB);\n\n    /**\n     * Helper method for ReMesh(), called by IdentifySwapType().\n     *\n     * Merge two given nodes in the mesh and update node/element ownership, by replacing\n     * the node contained in the least number of elements with the other node. The merged\n     * node is moved to the centre between the two old node positions.\n     *\n     * @param pNodeA one of the nodes to perform the merge with\n     * @param pNodeB the other node to perform the merge with\n     */\n    void PerformNodeMerge(Node<SPACE_DIM>* pNodeA, Node<SPACE_DIM>* pNodeB);\n\n    /**\n     * Helper method for ReMesh(), called by IdentifySwapType().\n     *\n     * Perform a T1 swap on two given nodes contained in a given set of elements.\n     * This involves replacing the two nodes with two new nodes placed on either\n     * side of the previous shared edge, such that the edge formed by the two new nodes\n     * is the perpendicular bisector of the previous shared edge, and 'just larger' (by a\n     * factor mCellRearrangementRatio) than mThresholdDistance.\n     *\n     * @param pNodeA one of the nodes to perform the swap with\n     * @param pNodeB the other node to perform the swap\n     * @param rElementsContainingNodes set of common elements\n     */\n    void PerformT1Swap(Node<SPACE_DIM>* pNodeA, Node<SPACE_DIM>* pNodeB, std::set<unsigned>& rElementsContainingNodes);\n\n    /**\n     * Helper method for ReMesh(), called by CheckForIntersections().\n     *\n     * Perform an element swap to resolve the situation where a given node\n     * has been found to overlap a given element not containing it.\n     *\n     * @param pNode pointer to the node\n     * @param elementIndex global index of the element in the mesh\n     */\n    void PerformIntersectionSwap(Node<SPACE_DIM>* pNode, unsigned elementIndex);\n\n    /**\n     * Helper method for ReMesh(), called by CheckForT2Swaps().\n     *\n     * Perform a T2 swap on a given triangular element whose area is smaller than mT2Threshold\n     * by replacing it with a new node located at the centroid of the former element and updating\n     * node/element ownership.\n     *\n     * @param rElement the element to remove\n     */\n    void PerformT2Swap(VertexElement<ELEMENT_DIM,SPACE_DIM>& rElement);\n\n    /**\n     * Helper method for ReMesh(), called by CheckForIntersections().\n     *\n     * Perform a T3 swap on a given node that has been found to overlap a given element\n     * by moving the node back onto the edge of that element, associating it with the\n     * element and adding new nodes to maintain three elements per node.\n     *\n     * @param pNode pointer to the node\n     * @param elementIndex global index of the element in the mesh\n     */\n    void PerformT3Swap(Node<SPACE_DIM>* pNode, unsigned elementIndex);\n\n    /**\n     * Helper method for ReMesh(), called by IdentifySwapType().\n     *\n     * Remove a triangular void bounded by three given nodes, in which one of the edges is\n     * less than mCellRearrangementThreshold, through calls to PerformNodeMerge().\n     *\n     * @param pNodeA one of the nodes on the short edge\n     * @param pNodeB the other node on the short edge\n     * @param pNodeC the other node in the triangular void\n     */\n    void PerformVoidRemoval(Node<SPACE_DIM>* pNodeA, Node<SPACE_DIM>* pNodeB, Node<SPACE_DIM>* pNodeC);\n\n    /**\n     * Helper method for ReMesh(), called by IdentifySwapType().\n     *\n     * Handles the case where a swap involves a junction with more than three adjacent elements.\n     * This is implemented in a separate method to allow child classes to override this behaviour\n     * and implement junction remodelling with high-order nodes (see #2664).\n     *\n     * @param pNodeA one of the nodes to perform the swap with\n     * @param pNodeB the other node to perform the swap\n     */\n    virtual void HandleHighOrderJunctions(Node<SPACE_DIM>* pNodeA, Node<SPACE_DIM>* pNodeB);\n\n    /**\n     * Helper method for ReMesh(), called by HandleHighOrderJunctions().\n     *\n     * Merge a node of a non-rosette cell with the central node\n     * of a rosette, by replacing the node in the non-rosette\n     * cell with that of the rosette centre, keeping the rosette\n     * centre in the same position.\n     *\n     * @param pNodeA one of the nodes to perform the merge with\n     * @param pNodeB the other node to perform the merge with\n     */\n    void PerformRosetteRankIncrease(Node<SPACE_DIM>* pNodeA, Node<SPACE_DIM>* pNodeB);\n\n    /**\n     * Helper method for ReMesh(), called by CheckForRosettes().\n     *\n     * Split protorosette in random direction.\n     * Create new node and redistribute nodes along line joining\n     * centres of randomly selected cell and cell opposite it.\n     *\n     * @param pProtorosetteNode node at centre of protorosette\n     */\n    void PerformProtorosetteResolution(Node<SPACE_DIM>* pProtorosetteNode);\n\n    /**\n     * Helper method for ReMesh(), called by CheckForRosettes().\n     *\n     * Split rosette by removing one cell at random.\n     * Create new node positioned along line joining\n     * rosette node and centre of randomly selected cell.\n     * Rosette node will remain unmoved.\n     *\n     * @param pRosetteNode node at centre of rosette\n     */\n    void PerformRosetteRankDecrease(Node<SPACE_DIM>* pRosetteNode);\n\n    /**\n     * Helper method for ReMesh().\n     *\n     * Check whether the mesh contains rosettes or protorosettes, and implement resolution events\n     * if necessary.\n     */\n    void CheckForRosettes();\n\n    /**\n     * Helper method for ReMesh(), called by PerformT3Swap(). During T3 swaps nodes are merged onto edges. This\n     * method checks if the edge is too short and moves its vertices apart if necessary in order to prevent T1 swaps\n     * from happening right away. The method also checks that the location where the merged node is going to end up at\n     * is not too close to one of the neighbouring vertices and moves it if necessary to prevent T1 swaps.\n     *\n     * @param indexA  index of one of the nodes on the short edge\n     * @param indexB  index of the other node on the short edge\n     * @param intersection  the intersection location, i.e. the location where we are planning to put the merged node\n     *\n     * @return intersection, the corrected location of where we are planning to put the merged node\n     */\n    c_vector<double, 2> WidenEdgeOrCorrectIntersectionLocationIfNecessary(unsigned indexA, unsigned indexB, c_vector<double,2> intersection);\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n\n    /**\n     * Serialize the mesh.\n     *\n     * Note that if you are calling this method (from subclasses) you should archive your\n     * member variables FIRST. So that this method can call a ReMesh\n     * (to convert from TrianglesMeshReader input format into your native format).\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        // NOTE - Subclasses must archive their member variables BEFORE calling this method.\n        archive & mCellRearrangementThreshold;\n        archive & mCellRearrangementRatio;\n        archive & mT2Threshold;\n        archive & mProtorosetteFormationProbability;\n        archive & mProtorosetteResolutionProbabilityPerTimestep;\n        archive & mRosetteResolutionProbabilityPerTimestep;\n        archive & mCheckForInternalIntersections;\n        archive & mDeletedNodeIndices;\n        archive & mDeletedElementIndices;\n        archive & mDistanceForT3SwapChecking;\n        ///\\todo: maybe we should archive the mLocationsOfT1Swaps and mDeletedNodeIndices etc. as well?\n\n        archive & boost::serialization::base_object<VertexMesh<ELEMENT_DIM, SPACE_DIM> >(*this);\n    }\n\npublic:\n\n    /**\n     * Default constructor.\n     *\n     * @param nodes vector of pointers to nodes\n     * @param vertexElements vector of pointers to VertexElements\n     * @param cellRearrangementThreshold the minimum threshold distance for element rearrangement (defaults to 0.01)\n     * @param t2Threshold the maximum threshold distance for Type 2 swaps (defaults to 0.001)\n     * @param cellRearrangementRatio ratio between the minimum threshold distance for element\n     *                                rearrangement node separation after remeshing (defaults to 1.5)\n     * @param protorosetteFormationProbability the probability of a protorosette formation event happening instead of\n     *                                a T1 swap\n     * @param protorosetteResolutionProbabilityPerTimestep the probability that, in a given timestep, a protorosette\n     *                                will resolve (similar to the completion of a T1 swap)\n     * @param rosetteResolutionProbabilityPerTimestep the probability that, in a given timestep, a rosette will\n     *                                resolve (reduce the number of cells sharing a common vertex by 1)\n     */\n    MutableVertexMesh(std::vector<Node<SPACE_DIM>*> nodes,\n                      std::vector<VertexElement<ELEMENT_DIM, SPACE_DIM>*> vertexElements,\n                      double cellRearrangementThreshold=0.01,\n                      double t2Threshold=0.001,\n                      double cellRearrangementRatio=1.5,\n                      double protorosetteFormationProbability=0.0,\n                      double protorosetteResolutionProbabilityPerTimestep=0.0,\n                      double rosetteResolutionProbabilityPerTimestep=0.0);\n\n    /**\n     * Default constructor for use by serializer.\n     */\n    MutableVertexMesh();\n\n    /**\n     * Destructor.\n     */\n    virtual ~MutableVertexMesh();\n\n    /**\n     * Set method for mCellRearrangementThreshold.\n     *\n     * @param cellRearrangementThreshold\n     */\n    void SetCellRearrangementThreshold(double cellRearrangementThreshold);\n\n    /**\n     * Set method for mT2Threshold.\n     *\n     * @param t2Threshold\n     */\n    void SetT2Threshold(double t2Threshold);\n\n    /**\n     * Set method for mCellRearrangementRatio.\n     *\n     * @param cellRearrangementRatio\n     */\n    void SetCellRearrangementRatio(double cellRearrangementRatio);\n\n    /**\n     * Set method for mProtoRosetteFormationProbability.\n     *\n     * @param protorosetteFormationProbability the new value of mProtoRosetteFormationProbability\n     */\n    void SetProtorosetteFormationProbability(double protorosetteFormationProbability);\n\n    /**\n     * Set method for mProtoRosetteResolutionProbabilityPerTimestep.\n     *\n     * @param protorosetteResolutionProbabilityPerTimestep the new value of mProtoRosetteResolutionProbabilityPerTimestep\n     */\n    void SetProtorosetteResolutionProbabilityPerTimestep(double protorosetteResolutionProbabilityPerTimestep);\n\n    /**\n     * Set method for mRosetteResolutionProbabilityPerTimestep.\n     *\n     * @param rosetteResolutionProbabilityPerTimestep the new value of mRosetteResolutionProbabilityPerTimestep\n     */\n    void SetRosetteResolutionProbabilityPerTimestep(double rosetteResolutionProbabilityPerTimestep);\n\n    /**\n     * Move the node with a particular index to a new point in space.\n     *\n     * @param nodeIndex the index of the node to be moved\n     * @param point the new target location of the node\n     */\n    virtual void SetNode(unsigned nodeIndex, ChastePoint<SPACE_DIM> point);\n\n    /**\n     * Set method for mCheckForInternalIntersections.\n     *\n     * @param checkForInternalIntersections\n     */\n    void SetCheckForInternalIntersections(bool checkForInternalIntersections);\n\n    /**\n     * @return mCellRearrangementThreshold\n     */\n    double GetCellRearrangementThreshold() const;\n\n    /**\n     * @return mT2Threshold\n     */\n    double GetT2Threshold() const;\n\n    /**\n     * @return mCellRearrangementRatio\n     */\n    double GetCellRearrangementRatio() const;\n\n    /**\n     * Get method for mProtoRosetteFormationProbability.\n     *\n     * @return mProtoRosetteFormationProbability\n     */\n    double GetProtorosetteFormationProbability() const;\n\n    /**\n     * Get method for mProtoRosetteResolutionProbabilityPerTimestep.\n     *\n     * @return mProtoRosetteResolutionProbabilityPerTimestep\n     */\n    double GetProtorosetteResolutionProbabilityPerTimestep() const;\n\n    /**\n     * Get method for mRosetteResolutionProbabilityPerTimestep.\n     *\n     * @return mRosetteResolutionProbabilityPerTimestep\n     */\n    double GetRosetteResolutionProbabilityPerTimestep() const;\n\n    /**\n     * Set distance for T3 swap checking. At each time step we check for each boundary node whether\n     * it intersects with any boundary elements (cells) whose centroids lie within this distance\n     * to the node. Note that T3 swaps may not be resolved correctly if this distance is chosen\n     * too small, while large values for mDistanceForT3SwapChecking may slow down the simulation.\n     *\n     * @param distanceForT3SwapChecking\n     */\n    void SetDistanceForT3SwapChecking( double distanceForT3SwapChecking );\n\n    /**\n     * Get Distance for T3 swap checking.\n     *\n     * @return mDistanceForT3SwapChecking\n     */\n    double GetDistanceForT3SwapChecking() const;\n\n    /**\n     * @return the number of Nodes in the mesh.\n     */\n    unsigned GetNumNodes() const;\n\n    /**\n     * @return the number of VertexElements in the mesh.\n     */\n    unsigned GetNumElements() const;\n\n    /**\n     * @return mCheckForInternalIntersections, either to check for edges intersections or not.\n     */\n    bool GetCheckForInternalIntersections() const;\n\n    /**\n     * @return the locations of the T1 swaps\n     */\n    std::vector< c_vector<double, SPACE_DIM> > GetLocationsOfT1Swaps();\n\n    /**\n     * @return the location of the last T2 swap\n     */\n    c_vector<double, SPACE_DIM> GetLastT2SwapLocation();\n\n    /**\n     * @return the locations of the T3 swaps\n     */\n    std::vector< c_vector<double, SPACE_DIM> > GetLocationsOfT3Swaps();\n\n    /**\n     * @return the locations of the intersection swaps\n     */\n    std::vector< c_vector<double, SPACE_DIM> > GetLocationsOfIntersectionSwaps();\n\n    /**\n     * Helper method to clear the stored T1 swaps\n     */\n    void ClearLocationsOfT1Swaps();\n\n    /**\n     * Helper method to clear the stored T3 swaps\n     */\n    void ClearLocationsOfT3Swaps();\n\n    /**\n     * Helper method to clear the stored intersection swaps\n     */\n    void ClearLocationsOfIntersectionSwaps();\n\n    /**\n     * Add a node to the mesh.\n     *\n     * Note: After calling this one or more times, you must then call ReMesh.\n     *\n     * @param pNewNode pointer to the new node\n     * @return the global index of the new node in the mesh.\n     */\n    unsigned AddNode(Node<SPACE_DIM>* pNewNode);\n\n    /**\n     * Mark an element as deleted. Note that it DOES NOT deal with the associated\n     * nodes and therefore should only be called immediately prior to a ReMesh()\n     * being called.\n     *\n     * @param index  the global index of a specified vertex element\n     */\n    void DeleteElementPriorToReMesh(unsigned index);\n\n    /**\n     * Mark a given node as deleted. Note that this method DOES NOT deal with the\n     * associated elements and therefore should only be called immediately prior\n     * to a ReMesh() being called.\n     *\n     * @param index The index of the node to delete\n     */\n    void DeleteNodePriorToReMesh(unsigned index);\n\n    /**\n     * Divide an element along its short axis.\n     *\n     * @param pElement the element to divide\n     * @param placeOriginalElementBelow whether to place the original element below (in the y direction) the new element (defaults to false)\n     *\n     * @return the index of the new element\n     */\n    unsigned DivideElementAlongShortAxis(VertexElement<ELEMENT_DIM,SPACE_DIM>* pElement,\n                                         bool placeOriginalElementBelow=false);\n\n    /**\n     * Divide an element along a specified axis.\n     *\n     * If the new nodes (intersections of axis with element) are within\n     * mCellRearrangementThreshold of existing nodes then they are\n     * moved 2*mCellRearrangementThreshold away.\n     *\n     * @param pElement the element to divide\n     * @param axisOfDivision axis to divide the element by\n     * @param placeOriginalElementBelow whether to place the original element below (in the y direction) the new element (defaults to false)\n     *\n     * @return the index of the new element\n     */\n    unsigned DivideElementAlongGivenAxis(VertexElement<ELEMENT_DIM,SPACE_DIM>* pElement,\n                                         c_vector<double, SPACE_DIM> axisOfDivision,\n                                         bool placeOriginalElementBelow=false);\n\n    /**\n     * Add an element to the mesh.\n     *\n     * @param pNewElement the new element\n     *\n     * @return the index of the new element in the mesh\n     */\n    unsigned AddElement(VertexElement<ELEMENT_DIM, SPACE_DIM>* pNewElement);\n\n    /**\n     * Helper method for ReMesh().\n     *\n     * Check for any triangular element whose area is smaller than mT2Threshold\n     * and call PerformT2Swap() on any such element.\n     *\n     * @param rElementMap a VertexElementMap which associates the indices of VertexElements in the old mesh\n     *                   with indices of VertexElements in the new mesh.  This should be created\n     *                   with the correct size, GetNumElements()\n     *\n     * @return whether we need to check for, and implement, any further local remeshing operations\n     */\n    bool CheckForT2Swaps(VertexElementMap& rElementMap);\n\n    /**\n     * Delete mNodes and mElements.\n     */\n    void Clear();\n\n    /**\n     * Add a node on the edge between two nodes.\n     *\n     * @param pNodeA a pointer to one node\n     * @param pNodeB a pointer to the other nodes\n     */\n    void DivideEdge(Node<SPACE_DIM>* pNodeA, Node<SPACE_DIM>* pNodeB);\n\n    /**\n     * Helper method for ReMesh(). Removes the deleted nodes and elements from the mesh and updates the\n     * rElementMap accordingly.\n     *\n     * @param rElementMap a VertexElementMap which associates the indices of VertexElements in the old mesh\n     *                   with indices of VertexElements in the new mesh.  This should be created\n     *                   with the correct size, GetNumElements()\n     */\n    void RemoveDeletedNodesAndElements(VertexElementMap& rElementMap);\n\n    /**\n     * Helper method for ReMesh(). Removes the deleted nodes from the mesh and relabels the node indices.\n     */\n    void RemoveDeletedNodes();\n\n    /**\n     * Update the state of the mesh by implementing any local remeshing operations (node merging,\n     * or T1, T2 or T3 swaps) that are required, and store any changes in element indices using\n     * the given VertexElementMap.\n     *\n     * This method calls several other methods, in particular CheckForT2Swaps(), CheckForSwapsFromShortEdges()\n     * and CheckForIntersections().\n     *\n     * @param rElementMap a VertexElementMap which associates the indices of VertexElements in the old mesh\n     *                   with indices of VertexElements in the new mesh.  This should be created\n     *                   with the correct size, GetNumElements()\n     */\n    virtual void ReMesh(VertexElementMap& rElementMap);\n\n    /**\n     * Alternative version of ReMesh which takes no parameters and does not require a VertexElementMap.\n     * Note: inherited classes should overload ReMesh(VertexElementMap&).\n     *\n     * \\todo This method seems to be redundant; remove it? (#2401)\n     */\n    void ReMesh();\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_ALL_DIMS(MutableVertexMesh)\n\n#endif /*MUTABLEVERTEXMESH_HPP_*/\n", "meta": {"hexsha": "284dbd03d3be06c1e1b72292c0be8adcba6698d8", "size": 27923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mesh/src/vertex/MutableVertexMesh.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mesh/src/vertex/MutableVertexMesh.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mesh/src/vertex/MutableVertexMesh.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3511560694, "max_line_length": 144, "alphanum_fraction": 0.6984564696, "num_tokens": 6246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.02405355429364403, "lm_q1q2_score": 0.007799014087443884}}
{"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_REDUCER_HPP\n#define AMA_TENSOR_MUL_MUL_REDUCER_HPP 1\n\n#include <ama/tensor/detail/tensor_base.hpp>\n#include <ama/tensor/mul/mul_calculator.hpp>\n#include <ama/tensor/mul/mul_temporary.hpp>\n#include <ama/tensor/iexp/iexp_copy.hpp>\n#include <ama/tensor/iexp/indices.hpp>\n#include <ama/tensor/iexp/sum.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/size.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* forward declaration */\n    template <typename LEFT, typename RIGHT> class mul_reducer;\n\n\n    /* specialization of traits */\n    template <typename LEFT, typename RIGHT>\n    struct tensor_traits< mul_reducer<LEFT, RIGHT> >\n    {\n      typedef typename LEFT::value_type value_type;\n\n      typedef typename LEFT::dimension_type dimension_type;\n\n      typedef mpl::size<typename iexp_reduce<\n            typename mul_index<LEFT, RIGHT>::tensor_type\n          , typename mul_index<LEFT, RIGHT>::index_list\n          >::controvariant> controvariant_type;\n      typedef mpl::size<typename iexp_reduce<\n            typename mul_index<LEFT, RIGHT>::tensor_type\n          , typename mul_index<LEFT, RIGHT>::index_list\n          >::covariant> covariant_type;\n\n      typedef ::boost::mpl::false_ is_assignable;\n      typedef ::boost::mpl::true_ is_temporary;\n    };\n\n\n    /* class declaration */\n    template <typename LEFT, typename RIGHT>\n    class mul_reducer:\n          public tensor_base< mul_reducer<LEFT, RIGHT> >\n    {\n    protected:\n      typedef tensor_base< mul_reducer<LEFT, RIGHT> > base_type;\n      typedef mul_reducer<LEFT, RIGHT> derived_type;\n\n      typedef LEFT left_operand;\n      typedef RIGHT right_operand;\n\n      typedef mul_temporary<left_operand, right_operand> iexp_type;\n\n    public:\n      /* constructor */\n      mul_reducer(left_operand const & left,\n                  right_operand const & right)\n          : m_iexp(left, right) { }\n\n    public:\n      typedef typename base_type::value_type value_type;\n      typedef typename base_type::dimension_type dimension_type;\n\n      template <typename ILIST>\n      value_type at() const\n      {\n        namespace mpl = ::boost::mpl;\n\n        typedef typename iexp_reduce<\n              typename mul_index<LEFT, RIGHT>::tensor_type\n            , typename mul_index<LEFT, RIGHT>::index_list\n            >::index_list index_list; /* other indices */\n        typedef typename iexp_reduce<\n              typename mul_index<LEFT, RIGHT>::tensor_type\n            , typename mul_index<LEFT, RIGHT>::index_list\n            >::reduce_list sum_indices; /* index of sum */\n\n        BOOST_MPL_ASSERT_MSG(\n              (mpl::equal_to< mpl::size<ILIST> , mpl::size<index_list> >::value)\n            , THE_INDICES_LIST_MUST_HAVE_THE_SAME_SIZE\n            , (ILIST));\n\n        /* indeces (not for sum) */\n        typedef typename make_imap<index_list, ILIST>::type imap;\n        typedef typename mpl::size<sum_indices>::type order;\n\n        return sum<dimension_type, order>::template apply<imap, sum_indices>(m_iexp);\n      }\n\n    protected:\n      iexp_type const m_iexp;\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_MUL_MUL_REDUCER_HPP */\n", "meta": {"hexsha": "3110c8f3d93f2b5734830a70a49b20bde0b6d8ba", "size": 4813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/mul/mul_reducer.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_reducer.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_reducer.hpp", "max_forks_repo_name": "mattiapenati/amanita", "max_forks_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4621212121, "max_line_length": 85, "alphanum_fraction": 0.6964471224, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.020645931228825517, "lm_q1q2_score": 0.007794678684091303}}
{"text": "/*!\n  \\file gpp_python_knowledge_gradient.cpp\n  \\rst\n  This file has the logic to invoke C++ functions pertaining to knowledge gradient from Python.\n  The data flow follows the basic 4 step from gpp_python_common.hpp.\n\n  .. NoteL: several internal functions of this source file are only called from ``Export*()`` functions,\n  so their description, inputs, outputs, etc. comments have been moved. These comments exist in\n  ``Export*()`` as Python docstrings, so we saw no need to repeat ourselves.\n\\endrst*/\n// This include violates the Google Style Guide by placing an \"other\" system header ahead of C and C++ system headers.  However,\n// it needs to be at the top, otherwise compilation fails on some systems with some versions of python: OS X, python 2.7.3.\n// Putting this include first prevents pyport from doing something illegal in C++; reference: http://bugs.python.org/issue10910\n#include \"Python.h\"  // NOLINT(build/include)\n\n#include \"gpp_python_knowledge_gradient.hpp\"\n\n// NOLINT-ing the C, C++ header includes as well; otherwise cpplint gets confused\n#include <string>  // NOLINT(build/include_order)\n#include <vector>  // NOLINT(build/include_order)\n\n#include <boost/python/bases.hpp>  // NOLINT(build/include_order)\n#include <boost/python/class.hpp>  // NOLINT(build/include_order)\n#include <boost/python/def.hpp>  // NOLINT(build/include_order)\n#include <boost/python/dict.hpp>  // NOLINT(build/include_order)\n#include <boost/python/extract.hpp>  // NOLINT(build/include_order)\n#include <boost/python/list.hpp>  // NOLINT(build/include_order)\n#include <boost/python/object.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_knowledge_gradient_optimization.hpp\"\n#include \"gpp_geometry.hpp\"\n#include \"gpp_math.hpp\"\n#include \"gpp_optimization.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_python_common.hpp\"\n\nnamespace optimal_learning {\n\nnamespace {\n\ndouble ComputePosteriorMeanWrapper(const GaussianProcess& gaussian_process,\n                                   const int num_fidelity,\n                                   const boost::python::list& points_to_sample) {\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container(points_to_sample, gradients, gaussian_process.dim()-num_fidelity, 1, num_derivatives_input);\n\n  bool configure_for_gradients = false;\n  PosteriorMeanEvaluator ps_evaluator(gaussian_process);\n  PosteriorMeanEvaluator::StateType ps_state(ps_evaluator, num_fidelity, input_container.points_to_sample.data(), configure_for_gradients);\n\n  return ps_evaluator.ComputePosteriorMean(&ps_state);\n}\n\nboost::python::list ComputeGradPosteriorMeanWrapper(const GaussianProcess& gaussian_process,\n                                                    const int num_fidelity,\n                                                    const boost::python::list& points_to_sample) {\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container(points_to_sample, gradients, gaussian_process.dim()-num_fidelity, 1, num_derivatives_input);\n\n  std::vector<double> grad_PS(input_container.dim);\n  bool configure_for_gradients = true;\n\n  PosteriorMeanEvaluator ps_evaluator(gaussian_process);\n  PosteriorMeanEvaluator::StateType ps_state(ps_evaluator, num_fidelity, input_container.points_to_sample.data(), configure_for_gradients);\n\n  ps_evaluator.ComputeGradPosteriorMean(&ps_state, grad_PS.data());\n  return VectorToPylist(grad_PS);\n}\n\ndouble ComputeKnowledgeGradientWrapper(const GaussianProcess& gaussian_process,\n                                       const int num_fidelity,\n                                       const boost::python::object& optimizer_parameters,\n                                       const boost::python::list& domain_bounds,\n                                       const boost::python::list& discrete_pts,\n                                       const boost::python::list& points_to_sample,\n                                       const boost::python::list& points_being_sampled,\n                                       int num_pts, int num_to_sample, int num_being_sampled,\n                                       int max_int_steps, double best_so_far, RandomnessSourceContainer& randomness_source) {\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container_discrete(discrete_pts, gradients, gaussian_process.dim()-num_fidelity, num_pts, num_derivatives_input);\n  PythonInterfaceInputContainer input_container(points_to_sample, points_being_sampled, gradients, gaussian_process.dim(),\n                                                num_to_sample, num_being_sampled, num_derivatives_input);\n\n  bool configure_for_gradients = false;\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim-num_fidelity);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim-num_fidelity, domain_bounds_C);\n  //TensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n  TensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim-num_fidelity);\n\n  const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n\n  KnowledgeGradientEvaluator<TensorProductDomain> kg_evaluator(gaussian_process, num_fidelity, input_container_discrete.points_to_sample.data(),\n                                                               num_pts, max_int_steps, inner_domain, gradient_descent_parameters, best_so_far);\n  KnowledgeGradientEvaluator<TensorProductDomain>::StateType kg_state(kg_evaluator, input_container.points_to_sample.data(),\n                                                                      input_container.points_being_sampled.data(),\n                                                                      input_container.num_to_sample,\n                                                                      input_container.num_being_sampled,\n                                                                      input_container_discrete.num_to_sample,\n                                                                      gaussian_process.derivatives().data(), gaussian_process.num_derivatives(),\n                                                                      configure_for_gradients,\n                                                                      randomness_source.normal_rng_vec.data());\n  return kg_evaluator.ComputeKnowledgeGradient(&kg_state);\n}\n\nboost::python::list ComputeGradKnowledgeGradientWrapper(const GaussianProcess& gaussian_process,\n                                                        const int num_fidelity,\n                                                        const boost::python::object& optimizer_parameters,\n                                                        const boost::python::list& domain_bounds,\n                                                        const boost::python::list& discrete_pts,\n                                                        const boost::python::list& points_to_sample,\n                                                        const boost::python::list& points_being_sampled,\n                                                        int num_pts, int num_to_sample, int num_being_sampled,\n                                                        int max_int_steps, double best_so_far, RandomnessSourceContainer& randomness_source) {\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container_discrete(discrete_pts, gradients, gaussian_process.dim()-num_fidelity, num_pts, num_derivatives_input);\n\n  PythonInterfaceInputContainer input_container(points_to_sample, points_being_sampled, gradients, gaussian_process.dim(),\n                                                num_to_sample, num_being_sampled, num_derivatives_input);\n\n  std::vector<double> grad_KG(num_to_sample*input_container.dim);\n  bool configure_for_gradients = true;\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim-num_fidelity);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim-num_fidelity, domain_bounds_C);\n  //TensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n  TensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim- num_fidelity);\n\n  const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n\n  KnowledgeGradientEvaluator<TensorProductDomain> kg_evaluator(gaussian_process, num_fidelity, input_container_discrete.points_to_sample.data(),\n                                                               num_pts, max_int_steps, inner_domain, gradient_descent_parameters, best_so_far);\n  KnowledgeGradientEvaluator<TensorProductDomain>::StateType kg_state(kg_evaluator, input_container.points_to_sample.data(),\n                                                                      input_container.points_being_sampled.data(),\n                                                                      input_container.num_to_sample,\n                                                                      input_container.num_being_sampled,\n                                                                      input_container_discrete.num_to_sample,\n                                                                      gaussian_process.derivatives().data(), gaussian_process.num_derivatives(),\n                                                                      configure_for_gradients, randomness_source.normal_rng_vec.data());\n  kg_evaluator.ComputeGradKnowledgeGradient(&kg_state, grad_KG.data());\n\n  return VectorToPylist(grad_KG);\n}\n\n/*!\\rst\n  Utility that dispatches KG optimization based on optimizer type and num_to_sample.\n  This is just used to reduce copy-pasted code.\n\n  \\param\n    :optimizer_parameters: python/cpp_wrappers/optimization._CppOptimizerParameters\n      Python object containing the DomainTypes domain_type and OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton).\n      See comments on the python interface for multistart_expected_improvement_optimization_wrapper\n    :gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities) that describes the\n      underlying GP\n    :input_container: PythonInterfaceInputContainer object containing data about points_being_sampled\n    :domain: object specifying the domain to optimize over (see gpp_domain.hpp)\n    :optimizer_type: type of optimization to use (e.g., null, gradient descent)\n    :num_to_sample: how many simultaneous experiments you would like to run (i.e., the q in q,p-KG)\n    :best_so_far: value of the best sample so far (must be min(points_sampled_value))\n    :max_int_steps: maximum number of MC iterations\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :randomness_source: object containing randomness sources (sufficient for multithreading) used in KG computation\n    :status: pydict object; cannot be None\n  \\output\n    :randomness_source: PRNG internal states modified\n    :status: modified on exit to describe whether convergence occurred\n    :best_points_to_sample[num_to_sample][dim]: next set of points to evaluate\n\\endrst*/\n\ntemplate <typename DomainType>\nvoid DispatchKnowledgeGradientOptimization(const boost::python::object& optimizer_parameters,\n                                           const boost::python::object& optimizer_parameters_inner,\n                                           const GaussianProcess& gaussian_process, const int num_fidelity,\n                                           const PythonInterfaceInputContainer& input_container_discrete,\n                                           const PythonInterfaceInputContainer& input_container,\n                                           const DomainType& domain, const DomainType& inner_domain,\n                                           OptimizerTypes optimizer_type, int num_to_sample, double best_so_far,\n                                           int max_int_steps, int max_num_threads,\n                                           RandomnessSourceContainer& randomness_source,\n                                           boost::python::dict& status,\n                                           double * restrict best_points_to_sample) {\n\n  bool found_flag = false;\n  switch (optimizer_type) {\n    case OptimizerTypes::kNull: {\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_static);\n      // optimizer_parameters must contain an int num_random_samples field, extract it\n      const GradientDescentParameters& gradient_descent_parameters_inner = boost::python::extract<GradientDescentParameters&>(optimizer_parameters_inner.attr(\"optimizer_parameters\"));\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      ComputeKGOptimalPointsToSampleViaLatinHypercubeSearch(gaussian_process, num_fidelity, gradient_descent_parameters_inner, domain, inner_domain,\n                                                            thread_schedule, input_container.points_being_sampled.data(),\n                                                            input_container_discrete.points_to_sample.data(),\n                                                            num_random_samples, num_to_sample,\n                                                            input_container.num_being_sampled,\n                                                            input_container_discrete.num_to_sample,\n                                                            best_so_far, max_int_steps,\n                                                            &found_flag, &randomness_source.uniform_generator,\n                                                            randomness_source.normal_rng_vec.data(),\n                                                            best_points_to_sample);\n      status[std::string(\"lhc_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kNull optimizer_type\n    case OptimizerTypes::kGradientDescent: {\n      // optimizer_parameters must contain a optimizer_parameters field\n      // of type GradientDescentParameters. extract it\n      const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n      const GradientDescentParameters& gradient_descent_parameters_inner = boost::python::extract<GradientDescentParameters&>(optimizer_parameters_inner.attr(\"optimizer_parameters\"));\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_dynamic);\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      bool random_search_only = false;\n      ComputeKGOptimalPointsToSample(gaussian_process, num_fidelity, gradient_descent_parameters, gradient_descent_parameters_inner, domain, inner_domain, thread_schedule,\n                                     input_container.points_being_sampled.data(), input_container_discrete.points_to_sample.data(),\n                                     num_to_sample, input_container.num_being_sampled, input_container_discrete.num_to_sample,\n                                     best_so_far, max_int_steps, random_search_only, num_random_samples, &found_flag,\n                                     &randomness_source.uniform_generator,\n                                     randomness_source.normal_rng_vec.data(), best_points_to_sample);\n\n      status[std::string(\"gradient_descent_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kGradientDescent optimizer_type\n    default: {\n      std::fill(best_points_to_sample, best_points_to_sample + input_container.dim*num_to_sample, 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid optimizer choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over optimizer_type\n}\n\nboost::python::list MultistartKnowledgeGradientOptimizationWrapper(const boost::python::object& optimizer_parameters,\n                                                                   const boost::python::object& optimizer_parameters_inner,\n                                                                   const GaussianProcess& gaussian_process, const int num_fidelity,\n                                                                   const boost::python::list& domain_bounds,\n                                                                   const boost::python::list& discrete_pts,\n                                                                   const boost::python::list& points_being_sampled,\n                                                                   int num_pts, int num_to_sample, int num_being_sampled,\n                                                                   double best_so_far, int max_int_steps, int max_num_threads,\n                                                                   RandomnessSourceContainer& randomness_source,\n                                                                   boost::python::dict& status) {\n  // TODO(GH-131): make domain objects constructible from python; and pass them in through\n  // the optimizer_parameters python object\n\n  // abort if we do not have enough sources of randomness to run with max_num_threads\n  if (unlikely(max_num_threads > static_cast<int>(randomness_source.normal_rng_vec.size()))) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"Fewer randomness_sources than max_num_threads.\", randomness_source.normal_rng_vec.size(), max_num_threads);\n  }\n\n  int num_to_sample_input = 0;  // No points to sample; we are generating these via KG optimization\n  const boost::python::list points_to_sample_dummy;\n\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container_discrete(discrete_pts, gradients, gaussian_process.dim()-num_fidelity, num_pts, num_derivatives_input);\n  PythonInterfaceInputContainer input_container(points_to_sample_dummy, points_being_sampled, gradients, gaussian_process.dim(),\n                                                num_to_sample_input, num_being_sampled, num_derivatives_input);\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim, domain_bounds_C);\n\n  std::vector<double> best_points_to_sample_C(input_container.dim*num_to_sample);\n\n  DomainTypes domain_type = boost::python::extract<DomainTypes>(optimizer_parameters.attr(\"domain_type\"));\n  OptimizerTypes optimizer_type = boost::python::extract<OptimizerTypes>(optimizer_parameters.attr(\"optimizer_type\"));\n  switch (domain_type) {\n    case DomainTypes::kTensorProduct: {\n      TensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n      TensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim- num_fidelity);\n\n      DispatchKnowledgeGradientOptimization(optimizer_parameters, optimizer_parameters_inner, gaussian_process, num_fidelity, input_container_discrete,\n                                            input_container, domain, inner_domain, optimizer_type, num_to_sample, best_so_far,\n                                            max_int_steps, max_num_threads, randomness_source, status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kTensorProduct\n    case DomainTypes::kSimplex: {\n      SimplexIntersectTensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n      SimplexIntersectTensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim- num_fidelity);\n\n      DispatchKnowledgeGradientOptimization(optimizer_parameters, optimizer_parameters_inner, gaussian_process, num_fidelity, input_container_discrete,\n                                            input_container, domain, inner_domain, optimizer_type, num_to_sample, best_so_far,\n                                            max_int_steps, max_num_threads, randomness_source, status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kSimplex\n    default: {\n      std::fill(best_points_to_sample_C.begin(), best_points_to_sample_C.end(), 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid domain choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over domain_type\n  return VectorToPylist(best_points_to_sample_C);\n}\n\nboost::python::list ComputeOptimalPosteriorMeanWrapper(const GaussianProcess& gaussian_process, const int num_fidelity,\n                                                       const boost::python::object& optimizer_parameters,\n                                                       const boost::python::list& domain_bounds,\n                                                       const boost::python::list& initial_guess,\n                                                       boost::python::dict& status) {\n    int dim = gaussian_process.dim();\n\n    int num_derivatives_input = 0;\n    const boost::python::list gradients;\n\n    PythonInterfaceInputContainer input_container(initial_guess, gradients, gaussian_process.dim()-num_fidelity, 1, num_derivatives_input);\n\n    std::vector<ClosedInterval> domain_bounds_C(dim-num_fidelity);\n    CopyPylistToClosedIntervalVector(domain_bounds, dim-num_fidelity, domain_bounds_C);\n\n    std::vector<double> best_points_to_sample_C(dim-num_fidelity);\n\n    bool found_flag = false;\n    const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n\n    DomainTypes domain_type = boost::python::extract<DomainTypes>(optimizer_parameters.attr(\"domain_type\"));\n    switch (domain_type) {\n      case DomainTypes::kTensorProduct: {\n        TensorProductDomain inner_domain(domain_bounds_C.data(), dim - num_fidelity);\n\n        ComputeOptimalPosteriorMean(gaussian_process, num_fidelity, gradient_descent_parameters, inner_domain, input_container.points_to_sample.data(),\n                                    &found_flag, best_points_to_sample_C.data());\n        break;\n      }  // end case OptimizerTypes::kTensorProduct\n      case DomainTypes::kSimplex: {\n        SimplexIntersectTensorProductDomain inner_domain(domain_bounds_C.data(), dim - num_fidelity);\n\n        ComputeOptimalPosteriorMean(gaussian_process, num_fidelity, gradient_descent_parameters, inner_domain, input_container.points_to_sample.data(),\n                                    &found_flag, best_points_to_sample_C.data());\n        break;\n      }  // end case OptimizerTypes::kSimplex\n      default: {\n        std::fill(best_points_to_sample_C.begin(), best_points_to_sample_C.end(), 0.0);\n        OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid domain choice. Setting all coordinates to 0.0.\");\n        break;\n      }\n    }  // end switch over domain_type\n    return VectorToPylist(best_points_to_sample_C);\n}\n\nboost::python::list EvaluateKGAtPointListWrapper(const GaussianProcess& gaussian_process,\n                                                 const int num_fidelity, const boost::python::object& optimizer_parameters,\n                                                 const boost::python::list& domain_bounds,\n                                                 const boost::python::list& discrete_being_sampled,\n                                                 const boost::python::list& initial_guesses,\n                                                 int num_multistarts, int num_pts, int num_to_sample,\n                                                 int num_being_sampled, double best_so_far,\n                                                 int max_int_steps, int max_num_threads,\n                                                 RandomnessSourceContainer& randomness_source,\n                                                 boost::python::dict& status) {\n  // abort if we do not have enough sources of randomness to run with max_num_threads\n  if (unlikely(max_num_threads > static_cast<int>(randomness_source.normal_rng_vec.size()))) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"Fewer randomness_sources than max_num_threads.\", randomness_source.normal_rng_vec.size(), max_num_threads);\n  }\n\n  int num_derivatives_input = 0;\n  const boost::python::list gradients;\n\n  PythonInterfaceInputContainer input_container(discrete_being_sampled, gradients, gaussian_process.dim(), num_pts+num_being_sampled, num_derivatives_input);\n\n  std::vector<double> result_point_C(input_container.dim);  // not used\n  std::vector<double> result_function_values_C(num_multistarts);\n  std::vector<double> initial_guesses_C(input_container.dim * num_multistarts);\n\n  CopyPylistToVector(initial_guesses, input_container.dim * num_multistarts, initial_guesses_C);\n\n  ThreadSchedule thread_schedule(max_num_threads, omp_sched_static);\n  bool found_flag = false;\n\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim, domain_bounds_C);\n  TensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n  TensorProductDomain inner_domain(domain_bounds_C.data(), input_container.dim- num_fidelity);\n\n  const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n\n  EvaluateKGAtPointList(gaussian_process, num_fidelity, gradient_descent_parameters, domain, inner_domain, thread_schedule, initial_guesses_C.data(),\n                        input_container.points_to_sample.data() + input_container.dim*num_pts, input_container.points_to_sample.data(),\n                        num_multistarts, num_to_sample, num_being_sampled,\n                        num_pts, best_so_far, max_int_steps, &found_flag, randomness_source.normal_rng_vec.data(),\n                        result_function_values_C.data(), result_point_C.data());\n\n  status[\"evaluate_KG_at_point_list\"] = found_flag;\n\n  return VectorToPylist(result_function_values_C);\n}\n}  // end unnamed namespace\n\nvoid ExportKnowldegeGradientFunctions() {\n  boost::python::def(\"compute_posterior_mean\", ComputePosteriorMeanWrapper, R\"%%(\n    Compute knowledge gradient.\n    If ``num_to_sample == 1`` and ``num_being_sampled == 0`` AND ``force_monte_carlo is false``, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based KG computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: computed EI\n    :rtype: float64 >= 0.0\n    )%%\");\n\n  boost::python::def(\"compute_grad_posterior_mean\", ComputeGradPosteriorMeanWrapper, R\"%%(\n    Compute the gradient of knowledge gradient evaluated at points_to_sample.\n    If num_to_sample = 1 and num_being_sampled = 0 AND force_monte_carlo is false, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based KG computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: gradient of EI (computed at points_to_sample + points_being_sampled, wrt points_to_sample)\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"compute_knowledge_gradient\", ComputeKnowledgeGradientWrapper, R\"%%(\n    Compute knowledge gradient.\n    If ``num_to_sample == 1`` and ``num_being_sampled == 0`` AND ``force_monte_carlo is false``, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based KG computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: computed EI\n    :rtype: float64 >= 0.0\n    )%%\");\n\n  boost::python::def(\"compute_grad_knowledge_gradient\", ComputeGradKnowledgeGradientWrapper, R\"%%(\n    Compute the gradient of knowledge gradient evaluated at points_to_sample.\n    If num_to_sample = 1 and num_being_sampled = 0 AND force_monte_carlo is false, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based KG computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: gradient of EI (computed at points_to_sample + points_being_sampled, wrt points_to_sample)\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"multistart_knowledge_gradient_optimization\", MultistartKnowledgeGradientOptimizationWrapper, R\"%%(\n    Optimize expected improvement (i.e., solve q,p-EI) over the specified domain using the specified optimization method.\n    Can optimize for num_to_sample new points to sample (i.e., aka \"q\", experiments to run) simultaneously.\n    Allows the user to specify num_being_sampled (aka \"p\") ongoing/concurrent experiments.\n\n    The _CppOptimizerParameters object is a python class defined in:\n    python/cpp_wrappers/optimization._CppOptimizerParameters\n    See that class definition for more details.\n\n    This function expects it to have the fields:\n\n    * domain_type (DomainTypes enum from this file)\n    * optimizer_type (OptimizerTypes enum from this file)\n    * num_random_samples (int, number of samples to 'dumb' search over, if 'dumb' search is being used.\n      e.g., if optimizer = kNull or if to_sample > 1)\n    * optimizer_parameters (*Parameters struct (gpp_optimizer_parameters.hpp) where * matches optimizer_type\n      unused if optimizer_type == kNull)\n\n    This function also has the option of using GPU to compute general q,p-EI via MC simulation. To enable it,\n    make sure you have installed GPU components of MOE, otherwise, it will throw Runtime excpetion.\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n    :param optimizer_parameters: python object containing the DomainTypes domain_type and\n      OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton)\n    :type optimizer_parameters: _CppOptimizerParameters\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param domain: [lower, upper] bound pairs for each dimension\n    :type domain: list of float64 with shape (dim, 2)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param use_gpu: set to 1 if user wants to use GPU for MC computation\n    :type use_gpu: bool\n    :param which_gpu: GPU device ID\n    :type which_gpu: int >= 0\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: next set of points to eval\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"posterior_mean_optimization\", ComputeOptimalPosteriorMeanWrapper, R\"%%(\n    Optimize expected improvement (i.e., solve q,p-EI) over the specified domain using the specified optimization method.\n    Can optimize for num_to_sample new points to sample (i.e., aka \"q\", experiments to run) simultaneously.\n    Allows the user to specify num_being_sampled (aka \"p\") ongoing/concurrent experiments.\n\n    The _CppOptimizerParameters object is a python class defined in:\n    python/cpp_wrappers/optimization._CppOptimizerParameters\n    See that class definition for more details.\n\n    This function expects it to have the fields:\n\n    * domain_type (DomainTypes enum from this file)\n    * optimizer_type (OptimizerTypes enum from this file)\n    * num_random_samples (int, number of samples to 'dumb' search over, if 'dumb' search is being used.\n      e.g., if optimizer = kNull or if to_sample > 1)\n    * optimizer_parameters (*Parameters struct (gpp_optimizer_parameters.hpp) where * matches optimizer_type\n      unused if optimizer_type == kNull)\n\n    This function also has the option of using GPU to compute general q,p-EI via MC simulation. To enable it,\n    make sure you have installed GPU components of MOE, otherwise, it will throw Runtime excpetion.\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n    :param optimizer_parameters: python object containing the DomainTypes domain_type and\n      OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton)\n    :type optimizer_parameters: _CppOptimizerParameters\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param domain: [lower, upper] bound pairs for each dimension\n    :type domain: list of float64 with shape (dim, 2)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param use_gpu: set to 1 if user wants to use GPU for MC computation\n    :type use_gpu: bool\n    :param which_gpu: GPU device ID\n    :type which_gpu: int >= 0\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: next set of points to eval\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"evaluate_KG_at_point_list\", EvaluateKGAtPointListWrapper, R\"%%(\n    Evaluates the expected improvement at each point in initial_guesses; can handle q,p-EI.\n    Useful for plotting.\n\n    Equivalent to::\n\n      result = []\n      for point in initial_guesses:\n          result.append(compute_expected_improvement(point, ...))\n\n    But this method is substantially faster (loop in C++ and multithreaded).\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param initial_guesses: points at which to evaluate EI\n    :type initial_guesses: list of flaot64 with shape (num_multistarts, num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_multistarts: number of points at which to evaluate EI\n    :type num_multistarts: int > 0\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: EI values at each point of the initial_guesses list, in the same order\n    :rtype: list of float64 with shape (num_multistarts, )\n    )%%\");\n}\n\n}  // end namespace optimal_learning\n", "meta": {"hexsha": "db7865a0199d24b10f227495be2fd0e200c16141", "size": 43237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_python_knowledge_gradient.cpp", "max_stars_repo_name": "AliBaheri/Cornell-MOE", "max_stars_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_python_knowledge_gradient.cpp", "max_issues_repo_name": "AliBaheri/Cornell-MOE", "max_issues_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_python_knowledge_gradient.cpp", "max_forks_repo_name": "AliBaheri/Cornell-MOE", "max_forks_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T14:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T14:48:26.000Z", "avg_line_length": 64.2451708767, "max_line_length": 183, "alphanum_fraction": 0.698036404, "num_tokens": 8916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861804086755836, "lm_q2_score": 0.020023440119862953, "lm_q1q2_score": 0.007781470070810008}}
{"text": "/*\n\n\n\tThis file is part of PEST++.\n\n\tPEST++ is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tPEST++ is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with PEST++.  If not, see<http://www.gnu.org/licenses/>.\n*/\n\n#include \"RunManagerPanther.h\" //needs to be first because it includes winsock2.h\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iomanip>\n#include \"config_os.h\"\n#include \"MorrisMethod.h\"\n#include \"sobol.h\"\n//#include \"TornadoPlot.h\"\n#include \"Pest.h\"\n#include \"Transformable.h\"\n#include \"Transformation.h\"\n#include \"ParamTransformSeq.h\"\n#include \"utilities.h\"\n#include \"pest_error.h\"\n#include \"ModelRunPP.h\"\n#include \"FileManager.h\"\n#include \"RunManagerSerial.h\"\n#include \"OutputFileWriter.h\"\n#include \"PantherAgent.h\"\n#include \"Serialization.h\"\n#include \"system_variables.h\"\n\n\n\nusing namespace std;\nusing namespace pest_utils;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n\nint main(int argc, char* argv[])\n{\n#ifndef _DEBUG\n\ttry\n\t{\n#endif\n\tstring version = PESTPP_VERSION;\n\tcout << endl << endl;\n\tcout << \"             pestpp-sen: a tool for global sensitivity analysis\" << endl << endl;\n\tcout << \"                       by The PEST++ Development Team\" << endl;\n\tcout << endl << endl << \"version: \" << version << endl;\n\tcout << \"binary compiled on \" << __DATE__ << \" at \" << __TIME__ << endl << endl;\n\t\n\tCmdLine cmdline(argc, argv);\n\tFileManager file_manager;\n\tstring pathname = \".\";\n\tfile_manager.initialize_path(get_filename_without_ext(cmdline.ctl_file_name), pathname);\n\n\tif (cmdline.runmanagertype == CmdLine::RunManagerType::PANTHER_WORKER)\n\t{\n\t\t// This is a PANTHER worker, start PEST++ as a PANTHER worker\n\t\ttry\n\t\t{\n\t\t\tofstream frec(\"panther_worker.rec\");\n\t\t\tif (frec.bad())\n\t\t\t\tthrow runtime_error(\"error opening 'panther_worker.rec'\");\n\t\t\tPANTHERAgent yam_agent(frec);\n\t\t\tstring ctl_file = \"\";\n\t\t\ttry {\n\t\t\t\t// process traditional PEST control file\n\t\t\t\tctl_file = file_manager.build_filename(\"pst\");\n\t\t\t\tyam_agent.process_ctl_file(ctl_file);\n\t\t\t\t\n\t\t\t}\n\t\t\tcatch (PestError e)\n\t\t\t{\n\t\t\t\tcerr << \"Error prococessing control file: \" << ctl_file << endl << endl;\n\t\t\t\tcerr << e.what() << endl << endl;\n\t\t\t\tthrow(e);\n\t\t\t}\n\n\t\t\tyam_agent.start(cmdline.panther_host_name,cmdline.panther_port);\n\t\t}\n\t\tcatch (PestError &perr)\n\t\t{\n\t\t\tcerr << perr.what();\n\t\t\tthrow(perr);\n\t\t}\n\t\tcout << endl << \"Work Done...\" << endl;\n\t\texit(0);\n\t}\n\t\n\t\n\tif (cmdline.runmanagertype == CmdLine::RunManagerType::GENIE)\n\t{\n\t\tcerr << \"Genie run manager ('/g') no longer supported, please use PANTHER instead\" << endl;\n\t\texit(1);\n\n\t}\n\tif (cmdline.runmanagertype == CmdLine::RunManagerType::EXTERNAL)\n\t{\n\t\tcerr << \"external run manager ('/e') no longer supported, please use PANTHER instead\" << endl;\n\t\texit(1);\n\n\t}\n\n\tofstream &fout_rec = file_manager.open_ofile_ext(\"rec\");\n\tfout_rec << \"             pestpp-sen: a tool for global sensitivity analysis\" << endl << endl;\n\tfout_rec << \"                         by The PEST++ Development Team\" << endl << endl;\n\tfout_rec << endl << endl << \"version: \" << version << endl;\n\tfout_rec << \"binary compiled on \" << __DATE__ << \" at \" << __TIME__ << endl << endl;\n\tfout_rec << \"using control file: \\\"\" << cmdline.ctl_file_name << \"\\\"\" << endl;\n\tfout_rec << \"in directory: \\\"\" << OperSys::getcwd() << \"\\\"\" << endl;\n\tfout_rec << \"on host: \\\"\" << w_get_hostname() << \"\\\"\" << endl << endl;\n\n\tcout << endl;\n\tcout << \"using control file: \\\"\" << cmdline.ctl_file_name << \"\\\"\" << endl;\n\tcout << \"in directory: \\\"\" << OperSys::getcwd() << \"\\\"\" << endl;\n\tcout << \"on host: \\\"\" << w_get_hostname() << \"\\\"\" << endl << endl;\n\n\t// create pest run and process control file to initialize it\n\tPest pest_scenario;\n\tpest_scenario.set_defaults();\n\ttry \n\t{\n\t\tpest_scenario.process_ctl_file(file_manager.open_ifile_ext(\"pst\"), file_manager.build_filename(\"pst\"),fout_rec);\n\t\tfile_manager.close_file(\"pst\");\n\t\t//pest_scenario.check_inputs(fout_rec);\n\t}\n\tcatch(PestError e)\n\t{\n\t\tcerr << \"Error prococessing control file: \" << cmdline.ctl_file_name << endl << endl;\n\t\tcerr << e.what() << endl << endl;\n\t\tfout_rec << \"Error prococessing control file: \" << cmdline.ctl_file_name << endl << endl;\n\t\tfout_rec << e.what() << endl;\n\t\tfout_rec.close();\n\t\t//throw(e);\n\t\treturn 1;\n\t}\n\tpest_scenario.check_inputs(fout_rec);\n\t//OutputFileWriter(FileManager &_file_manager, Pest &_pest_scenario, bool restart_flag = false, bool _save_rei = true, int _eigenwrite = 0);\n\t\n\tOutputFileWriter ofw(file_manager,pest_scenario,false,false,0);\n\t//ofw.scenario_report(fout_rec, false);\n\n\tif (pest_scenario.get_pestpp_options().get_debug_parse_only())\n\t{\n\t\tcout << endl << endl << \"DEBUG_PARSE_ONLY is true, exiting...\" << endl << endl;\n\t\texit(0);\n\t}\n\n\n\tRunManagerAbstract *run_manager_ptr;\n\tif (cmdline.runmanagertype == CmdLine::RunManagerType::PANTHER_MASTER)\n\t{\n\t\tconst ModelExecInfo &exi = pest_scenario.get_model_exec_info();\n\t\trun_manager_ptr = new RunManagerPanther (\n\t\t\tfile_manager.build_filename(\"rns\"), cmdline.panther_port,\n\t\t\tfile_manager.open_ofile_ext(\"rmr\"),\n\t\t\tpest_scenario.get_pestpp_options().get_max_run_fail(),\n\t\t\tpest_scenario.get_pestpp_options().get_overdue_reched_fac(),\n\t\t\tpest_scenario.get_pestpp_options().get_overdue_giveup_fac(),\n\t\t\tpest_scenario.get_pestpp_options().get_overdue_giveup_minutes(),\n\t\t\tpest_scenario.get_pestpp_options().get_panther_echo());\n\t}\n\telse\n\t{\n\t\tconst ModelExecInfo &exi = pest_scenario.get_model_exec_info();\n\t\trun_manager_ptr = new RunManagerSerial(exi.comline_vec,\n\t\t\texi.tplfile_vec, exi.inpfile_vec, exi.insfile_vec, exi.outfile_vec,\n\t\t\tfile_manager.build_filename(\"rns\"), pathname,\n\t\t\tpest_scenario.get_pestpp_options().get_max_run_fail(),\n\t\t\tpest_scenario.get_pestpp_options().get_fill_tpl_zeros(),\n\t\t\tpest_scenario.get_pestpp_options().get_additional_ins_delimiters(),\n\t\t\tpest_scenario.get_pestpp_options().get_num_tpl_ins_threads());\n\t}\n\n\tcout << endl;\n\tfout_rec << endl;\n\tcout << \"using control file: \\\"\" <<  cmdline.ctl_file_name << \"\\\"\" << endl;\n\tfout_rec << \"using control file: \\\"\" <<  cmdline.ctl_file_name << \"\\\"\" << endl;\n\n\n\tenum class GSA_RESTART { NONE, RESTART };\n\tGSA_RESTART gsa_restart = GSA_RESTART::NONE;\n\t//process restart and  reuse jacibian directives\n\tif (cmdline.jac_restart)\n\t{\n\t\tcerr << \"jacobian restart ('/j') not supported in PESTPP-SEN\";\n\t\texit(1);\n\t}\n\tif (cmdline.restart)\n\t{\n\t\tgsa_restart = GSA_RESTART::RESTART;\n\t}\n\telse\n\t{\n\t\tgsa_restart = GSA_RESTART::NONE;\n\t}\n\t//OutputFileWriter(FileManager &_file_manager, Pest &_pest_scenario, bool restart_flag = false, bool _save_rei = true, int _eigenwrite = 0);\n\tOutputFileWriter output_writer(file_manager, pest_scenario, false, false);\n\tofstream &frec = file_manager.rec_ofstream();\n\toutput_writer.scenario_report(frec);\n\t//output_writer.scenario_io_report(frec);\n\t//output_writer.scenario_par_report(frec);\n\t//output_writer.scenario_obs_report(frec);\n\n\tpest_scenario.check_inputs(frec);\n\tpest_scenario.check_io(frec);\n\n\t//map<string, string> gsa_opt_map;\n\t//process .gsa file\n\tstring gsa_filename = file_manager.get_base_filename() + \".gsa\";\n\t\n\tif (check_exist_in(gsa_filename))\n\t{\n\t\tcout << \"WARNING: use of .gsa files is deprecated - .gsa file '\" << gsa_filename << \"' is being ignored, please use '++' args\";\n\t\treturn 1;\n\t}\n\n\tPestppOptions *pp_ptr = pest_scenario.get_pestpp_options_ptr();\n\tmap<string, string> gsa_opt_map = pp_ptr->get_arg_map();\n\t\n\t//Build Transformation with ctl_2_numberic\n\tParamTransformSeq base_partran_seq(pest_scenario.get_base_par_tran_seq());\n\tParameters ctl_par = pest_scenario.get_ctl_parameters();\n\n\n\t//Build Transformation with ctl_2_numberic\n\tObjectiveFunc obj_func(&(pest_scenario.get_ctl_observations()), &(pest_scenario.get_ctl_observation_info()), &(pest_scenario.get_prior_info()));\n\tModelRun model_run(&obj_func, pest_scenario.get_ctl_observations());\n\tconst set<string> &log_trans_pars = base_partran_seq.get_log10_ptr()->get_items();\n\tauto method = gsa_opt_map.find(\"GSA_METHOD\");\n\n\tGsaAbstractBase* gsa_method = nullptr;\n\tif (method == gsa_opt_map.end() || method->second == \"MORRIS\")\n\t{\n\t\tint morris_r = 4;\n\t\tint morris_p = 4;\n\n\t\tdouble morris_delta = .666;\n\t\tbool default_delta = true;\n\t\tbool calc_pooled_obs = false;\n\t\tbool calc_morris_obs_sen = true;\n\t\tauto morris_r_it = gsa_opt_map.find(\"GSA_MORRIS_R\");\n\t\tif (morris_r_it != gsa_opt_map.end())\n\t\t{\n\t\t\tconvert_ip(morris_r_it->second, morris_r);\n\t\t}\n\t\tauto morris_p_it = gsa_opt_map.find(\"GSA_MORRIS_P\");\n\t\tif (morris_p_it != gsa_opt_map.end())\n\t\t{\n\t\t\tconvert_ip(morris_p_it->second, morris_p);\n\t\t}\n\t\tauto morris_d_it = gsa_opt_map.find(\"GSA_MORRIS_DELTA\");\n\t\tif (morris_d_it != gsa_opt_map.end())\n\t\t{\n\t\t\t\n\t\t\tconvert_ip(morris_d_it->second, morris_delta);\n\t\t\tdefault_delta = false;\n\t\t}\n\t\tauto morris_pool_it = gsa_opt_map.find(\"GSA_MORRIS_POOLED_OBS\");\n\t\tif (morris_pool_it != gsa_opt_map.end())\n\t\t{\n\t\t\tstring pooled_obs_flag = morris_pool_it->second;\n\t\t\tupper_ip(pooled_obs_flag);\n\t\t\tif (pooled_obs_flag == \"TRUE\") calc_pooled_obs = true;\n\t\t}\n\n\t\tauto morris_obs_sen_it = gsa_opt_map.find(\"GSA_MORRIS_OBS_SEN\");\n\t\tif (morris_obs_sen_it != gsa_opt_map.end())\n\t\t{\n\t\t\tstring obs_sen_flag = morris_obs_sen_it->second;\n\t\t\tupper_ip(obs_sen_flag);\n\t\t\tif (obs_sen_flag == \"FALSE\") calc_morris_obs_sen = false;\n\t\t}\n\n\t\tif (default_delta) morris_delta = morris_p / (2.0 * (morris_p - 1));\n\n\t\tMorrisMethod *m_ptr = new MorrisMethod(pest_scenario, file_manager, &obj_func,\n\t\t\tbase_partran_seq, morris_p, morris_r, morris_delta, calc_pooled_obs,\n\t\t\tcalc_morris_obs_sen, GsaAbstractBase::PARAM_DIST::uniform, 1.0);\n\t\tgsa_method = m_ptr;\n\t\tm_ptr->process_pooled_var_file();\n\t\t\n\t\tfrec << endl << endl << endl << \"Method of Morris settings:\" << endl;\n\n\t\tfrec << scientific << left << setw(30) << \" morris_r \" << morris_r << endl;\n\t\tfrec << scientific << left << setw(30) << \" morris_p \" << morris_p << endl;\n\t\tfrec << scientific << left << setw(30) << \" morris_delta \" << morris_delta << endl << endl;\n\t\t\n\n\t}\n\t\n\telse if (method != gsa_opt_map.end() && method->second == \"SOBOL\")\n\t{\n\t\tGsaAbstractBase::PARAM_DIST par_dist = GsaAbstractBase::PARAM_DIST::uniform;\n\t\tstring par_dist_str = \"UNIFORM\";\n\t\tint n_sample = 100;\n\t\tauto sob_n_sam_it = gsa_opt_map.find(\"GSA_SOBOL_SAMPLES\");\n\t\tif (sob_n_sam_it != gsa_opt_map.end())\n\t\t{\n\t\t\tconvert_ip(sob_n_sam_it->second, n_sample);\n\t\t}\n\t\tauto sob_p_dist_it = gsa_opt_map.find(\"GSA_SOBOL_PAR_DIST\");\n\t\tif (sob_p_dist_it != gsa_opt_map.end())\n\t\t{\n\t\t\tpar_dist_str = sob_p_dist_it->second;\n\t\t\tupper_ip(par_dist_str);\n\t\t\tif (par_dist_str == \"NORM\") par_dist = GsaAbstractBase::PARAM_DIST::normal;\n\t\t\telse if (par_dist_str == \"UNIF\") par_dist = GsaAbstractBase::PARAM_DIST::uniform;\n\t\t\telse\n\t\t\t{\n\t\t\t\tostringstream str;\n\t\t\t\tstr << \"SOBOL_PAR_DIST(\" << par_dist_str << \"):  \\\"\" << par_dist_str << \"\\\" is an invalid distribuation type\";\n\t\t\t\tthrow PestError(str.str());\n\t\t\t}\n\t\t}\n\n\t\tgsa_method = new Sobol(pest_scenario, file_manager, &obj_func,\n\t\t\tbase_partran_seq, n_sample, par_dist, 1.0);\n\n\t\tfrec << endl << endl << endl << \"Method of Sobol settings:\" << endl;\n\n\t\tfrec << scientific << left << setw(30) << \" n_sample \" << n_sample << endl;\n\t\tfrec << scientific << left << setw(30) << \" sobol par dist \" <<par_dist_str << endl;\n\t\t\n\t}\n\telse\n\t{\n\t\tthrow PestError(\"A valid method for computing the sensitivity must be specified in the control file\");\n\t}\n\n\tauto morris_r_it = gsa_opt_map.find(\"RAND_SEED\");\n\tif (morris_r_it != gsa_opt_map.end())\n\t{\n\t\tunsigned int seed = convert_cp<unsigned int>(morris_r_it->second);\n\t\tgsa_method->set_seed(seed);\n\t}\n\t//gsa_method->set_seed(2);\n\tfrec << scientific << left << setw(30) << \" gsa random seed \" << gsa_method->get_seed() << endl;\n\t// make model runs\n\tif (gsa_restart == GSA_RESTART::NONE)\n\t{\n\t\t//Allocates Space for Run Manager.  This initializes the model parameter names and observations names.\n\t\t//Neither of these will change over the course of the simulation\n\t\tcout << endl;\n\t\tcout << \"Building model run parameter sets...\" << endl;\n\t\trun_manager_ptr->initialize(base_partran_seq.ctl2model_cp(ctl_par), pest_scenario.get_ctl_observations());\n\n\t\tParameters model_pars = base_partran_seq.ctl2model_cp(ctl_par);\n\t\trun_manager_ptr->reinitialize();\n\t\tgsa_method->assemble_runs(*run_manager_ptr);\n\t}\n\telse\n\t{\n\t\trun_manager_ptr->initialize_restart(file_manager.build_filename(\"rns\"));\n\t}\n\tcout << endl;\n\tcout << \"Performing model runs...\" << endl;\n\trun_manager_ptr->run();\n\n\tcout << \"Calculating sensitivities...\" << endl;\n\tgsa_method->calc_sen(*run_manager_ptr, model_run);\n\tfile_manager.close_file(\"srw\");\n\tfile_manager.close_file(\"msn\");\n\tfile_manager.close_file(\"orw\");\n\tdelete run_manager_ptr;\n\n\tstring case_name = file_manager.get_base_filename();\n\tfile_manager.close_file(\"rst\");\n\tpest_utils::try_clean_up_run_storage_files(case_name);\n\n\tcout << endl << endl << \"PESTPP-SEN Analysis Complete...\" << endl;\n\treturn 0;\n\t//cout << endl << \"Simulation Complete - Press RETURN to close window\" << endl;\n\t//char buf[256];\n\t//OperSys::gets_s(buf, sizeof(buf));\n#ifndef _DEBUG\n\t}\n\tcatch (exception &e)\n\t{\n\t\tcout << \"Error condition prevents further execution: \" << endl << e.what() << endl;\n\t\t//cout << \"press enter to continue\" << endl;\n\t\t//char buf[256];\n\t\t//OperSys::gets_s(buf, sizeof(buf));\n\t\treturn 1;\n\t}\n\tcatch (...)\n\t{\n\t\tcout << \"Error condition prevents further execution\" << endl;\n\t\treturn 1;\n\t}\n\n#endif\n}\n", "meta": {"hexsha": "bcb4886aa0628effcc89435e0178b235acdd4b3e", "size": 13665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/PEST++/src/programs/gsa/main.cpp", "max_stars_repo_name": "usgs/neversink_workflow", "max_stars_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "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": "source/PEST++/src/programs/gsa/main.cpp", "max_issues_repo_name": "usgs/neversink_workflow", "max_issues_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "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": "source/PEST++/src/programs/gsa/main.cpp", "max_forks_repo_name": "usgs/neversink_workflow", "max_forks_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4926470588, "max_line_length": 145, "alphanum_fraction": 0.7028905964, "num_tokens": 3802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.026355352989510358, "lm_q1q2_score": 0.007754139446154532}}
{"text": "/*\n * modules/cmoea/mp_cmoea_nsga2_mpi.hpp\n *\n *  Created on: Mar 10, 2017\n *      Author: Joost Huizinga\n *\n * This is the file for the massively parallel version of C-MOEA.\n * The main idea behind MP C-MOEA, is that there is no longer a master and a set of workers.\n * Instead, each worker will create its own population, and occasionally exchange part of the,\n * population with other workers.\n */\n\n#ifndef MODULES_CMOEA_CMOEA_NSGA2_MPI_HPP_\n#define MODULES_CMOEA_CMOEA_NSGA2_MPI_HPP_\n\n// Standard includes\n#include <algorithm>\n#include <limits>\n\n// Boost includes\n#include <boost/foreach.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/array.hpp>\n#include <boost/fusion/algorithm/iteration/for_each.hpp>\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/spirit/include/karma.hpp>\n#include <boost/mpi.hpp>\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/detail/point_to_point.hpp>\n\n// Sferes includes\n#include <sferes/stc.hpp>\n#include <sferes/ea/ea.hpp>\n#include <sferes/fit/fitness.hpp>\n#include <sferes/dbg/dbg.hpp>\n#include <sferes/ea/dom_sort_basic.hpp>\n#include <sferes/ea/common.hpp>\n#include <sferes/ea/crowd.hpp>\n\n// Module includes\n#include <modules/misc/common_compare.hpp>\n#include <modules/debugext/dbgext.hpp>\n\n// Local includes\n#include \"mpi_util.hpp\"\n#include \"nsga_util.hpp\"\n\nnamespace karma = boost::spirit::karma;\n\n// Debug statements become a bit too long without this statement\nusing namespace dbg;\nusing namespace dbgext;\n#define DBO dbo(\"ea\") << \"[\"<< _world->rank() << \"] \"\n#define DBOF dbo(\"eafit\") << \"[\"<< _world->rank() << \"] \"\n#define DBOO dbo(\"eaobj\") << \"[\"<< _world->rank() << \"] \"\n#define DBO_MPI dbo(\"mpi\") << \"[\"<< _world->rank() << \"] \"\n\nnamespace sferes\n{\nnamespace ea\n{\n\n\n/**\n * This is the main class for massively parallel C-MOEA.\n *\n * Usually, this part is only executed by the master.\n */\nSFERES_EA(MPCmoeaNsga2Mpi, Ea){\npublic:\n    /** PARAMETERS **/\n\n    // The type of Pareto domination sort to use.\n    // Currently available types are:\n    // - sferes::ea::dom_sort_basic_f\n\t//   (defined in sferes/ea/dom_sort_basic.hpp)\n    //   Sorts according to pareto dominance and will add individuals from the\n\t//   highest to the lowest layer, with crowding as a tie-breaker in the last\n\t//   layer to be added.\n    // - sferes::ea::dom_sort_no_duplicates_f\n\t//   (defined in sferes/ea/dom_sort_no_duplicates.hpp)\n    //   Same as dom_sort_basic, accept that, for each front, only one\n\t//   individual per pareto location is added. Other individuals at the same\n\t//   location will be bumped to the next layer.\n    typedef typename Params::ea::dom_sort_f dom_sort_f;\n\n    // The type non dominated comparator to use\n    // Currently available types are:\n    // - sferes::ea::_dom_sort_basic::non_dominated_f\n    //   (defined in sferes/ea/dom_sort_basic.hpp)\n    //   Regular comparisons based on dominance\n    // - sferes::ea::cmoea_nsga::prob_dom_f<Params>\n    //   Comparisons based on probabilistic sorting, where some objectives can\n    //   be stronger than others.\n    typedef typename Params::cmoea_nsga::non_dom_f non_dom_f;\n\n    // The index used to temporarily store the category\n    // This index should hold a dummy value, as it will be overwritten\n    // constantly. The default would be 0.\n    static const size_t obj_index = Params::cmoea::obj_index;\n\n    // The number of objectives (bins) used in the map\n    size_t nr_of_bins;\n\n    // The size of each bin\n    static const size_t bin_size = Params::cmoea::bin_size;\n\n    // The number of individuals initially generated to fill the archive\n    // If equal to the bin_size, every initially generated individual is added\n    // to every bin of every category.\n    // The init_size has to be greater than or equal to the bin_size\n    static const size_t init_size = Params::pop::init_size;\n\n    // Very large initial populations may cause CMOEA to run out of memory.\n    // To avoid this, you can add the initial populations in init_batch batches\n    // of init_size.\n    //static const size_t init_batch = Params::pop::init_batch;\n\n    // Max batch size to avoid memory issues\n    static const size_t max_batch_size = Params::pop::max_batch_size;\n\n    // Individuals generated each epoch per bin (needs to be divisible by 2)\n    static const size_t offspring_per_generation = Params::pop::select_size;\n\n    // The number of replicates for each bin\n    static const int replicates = Params::cmoea::replicates;\n\n    // Due to memory limitations, you may not always be able to send the entire\n    // population at once. max_send_size determines the maximum size of the\n    // population to send at once.\n    static const size_t max_send_size = Params::cmoea::max_send_size;\n\n    // The total number of bins, including replicates\n    int bins_total;\n\n\n    /** TYPE DEFINITIONS **/\n\n    // The type of the phenotype\n    typedef Phen phen_t;\n\n    // A smart pointer to the phenotype\n    typedef boost::shared_ptr<Phen> phen_ptr_t;\n    typedef phen_ptr_t indiv_t;\n\n    // The population type\n    typedef typename std::vector<phen_ptr_t> pop_t;\n\n    // Iterator for the population\n    typedef typename std::vector<phen_ptr_t>::iterator pop_it_t;\n\n    // The type of the Pareto front\n    typedef typename std::vector<pop_t> front_t;\n\n    // The type of a collections of bins\n    typedef typename std::vector<pop_t> bins_t;\n\n    // The type of the mpi environment\n    typedef typename boost::mpi::environment mpi_env_t;\n\n    // The type of the mpi communicator\n    typedef typename boost::mpi::communicator mpi_com_t;\n\n    // The type of serialization archive for sending\n    typedef typename boost::mpi::packed_oarchive mpi_oarchive_t;\n\n    // The type of serialization archive for receiving\n    typedef typename boost::mpi::packed_iarchive mpi_iarchive_t;\n\n    // The exact type of non-dominated sort function to use\n    typedef fill_dom_sort_f<phen_ptr_t, dom_sort_f, non_dom_f> sort_f;\n\n    // Maps MPI instances to bin indices\n    typedef std::map<int, std::vector<int> > inst_bin_map_t;\n\n    // Friend declaration required for Sferes\n    SFERES_EA_FRIEND(MPCmoeaNsga2Mpi);\n\n    /**\n     * Constructor for MP-CMOEA.\n     *\n     * Initializes the MPI environment, and calculates some relevant statistics\n     * for this run.\n     */\n    MPCmoeaNsga2Mpi(){\n        dbg::trace trace(\"ea\", DBG_HERE);\n\n        // Initialize MPI\n\t\tstatic char* argv[] = {(char*)\"sferes2\", 0x0};\n\t\tchar** argv2 = (char**) malloc(sizeof(char*) * 2);\n\t\tint argc = 1;\n\t\targv2[0] = argv[0];\n\t\targv2[1] = argv[1];\n\t\tdbg::out(dbg::info, \"mpi\") << \"Initializing MPI...\" << std::endl;\n\t\t_env = boost::shared_ptr<mpi_env_t>(new mpi_env_t(argc, argv2, true));\n\t\tdbg::out(dbg::info, \"mpi\") << \"MPI initialized\" << std::endl;\n\t\t_world = boost::shared_ptr<mpi_com_t>(new mpi_com_t());\n\n\t\tnr_of_bins = Params::cmoea::nb_of_bins;\n\t\tbins_total = nr_of_bins * replicates;\n\n\t\t// Lower bound on the number of bins per instance\n\t\t_min_bins_inst = bins_total / _world->size();\n\n\t\t// Upper bound on the number of bins per instance\n\t\t_max_bins_inst = _min_bins_inst + 1;\n\n\t\t// The number of bins remaining after each instance is assigned its\n\t\t// bins_per_instance\n\t\t_overfull_inst = bins_total % _world->size();\n\n\t\t// The total number of bins assigned to over-full instances\n\t\t_overfull_bins = _max_bins_inst * _overfull_inst;\n\n\t\t// The number of bins this instance has to handle\n\t\tint my_nr_bins;\n\t\tif(_world->rank() < _overfull_inst){\n\t\t\tmy_nr_bins = _max_bins_inst;\n\t\t\t_first_bin_id = _world->rank() * _max_bins_inst;\n\t\t} else {\n\t\t\tmy_nr_bins = _min_bins_inst;\n\t\t\tint other_instances = (_world->rank()-_overfull_inst);\n\t\t\tint other_bins = other_instances * _min_bins_inst;\n\t\t\t_first_bin_id = _overfull_bins + other_bins;\n\t\t}\n\n\t\t// Create the necessary bins\n\t\tfor( size_t i=0; i<my_nr_bins; ++i){\n\t\t\t_bins.push_back(pop_t());\n\t\t}\n\n\t\t// Print parameters\n\t\tDBO << \"Objectives: \" << nr_of_bins << dbe;\n\t\tDBO << \"Min bins per instance: \" << _min_bins_inst << dbe;\n\t\tDBO << \"Max bins per instance: \" << _max_bins_inst << dbe;\n\t\tDBO << \"Over-full instances: \" << _overfull_inst << dbe;\n\t\tDBO << \"Over-full bins: \" << _overfull_bins << dbe;\n\t\tDBO << \"First bin id: \" << _first_bin_id << dbe;\n\t\tDBO << \"My bins: \" << _bins.size() << dbe;\n    }\n\n    int get_rank(){\n    \treturn _world->rank();\n    }\n\n    /**\n     * Creates a random initial population.\n     *\n     * The number of generated individuals is determined by\n     * init_batch * init_size, but the final population size is determined by\n     * bin_size.\n     */\n    void random_pop(){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        parallel::init();\n\n        // Clear the population\n        this->_pop.clear();\n\n        // Define bins\n        pop_t send_pop;\n        pop_t recv_pop;\n        bins_t new_indiv_bins (_bins.size());\n\n        // Calculate the number of batches\n        unsigned nr_of_batches = (init_size / max_batch_size);\n        unsigned remainder = init_size % max_batch_size;\n        if(remainder) ++nr_of_batches;\n\n        // Generate and evaluate new random individuals\n        for(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n        \tDBO << \"Pop for bin: \" << bin_i << dbe;\n        \tfor(unsigned j=0; j<nr_of_batches; ++j){\n        \t\t// Calculate batch size\n            \tunsigned batch_size = max_batch_size;\n            \tif(j==(nr_of_batches-1) && remainder > 0){\n            \t\tbatch_size = remainder;\n            \t}\n\n        \t\t// Generate the new random individuals\n        \t\tnew_indiv_bins[bin_i].resize(batch_size);\n        \t\tint i = 0;\n        \t\tBOOST_FOREACH(phen_ptr_t& indiv, new_indiv_bins[bin_i]){\n        \t\t\tDBO << \"Random indiv: \" << i++ << dbe;\n        \t\t\tindiv = phen_ptr_t(new phen_t());\n        \t\t\tindiv->random();\n        \t\t}\n\n            \t// Evaluate the new individuals\n        \t\tDBO << \"Evaluating pop\" << std::endl;\n            \t_evaluate(new_indiv_bins[bin_i]);\n        \t}\n        }\n\n        // Exchange individuals\n        for(size_t offset=0; offset<bin_size; offset+=max_send_size){\n        \tsend_pop.clear();\n        \trecv_pop.clear();\n        \tfor(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n        \t\tpop_it_t it_slice_begin = new_indiv_bins[bin_i].begin();\n        \t\tpop_it_t it_end = new_indiv_bins[bin_i].end();\n        \t\tstd::advance (it_slice_begin, offset);\n        \t\tpop_it_t it_slice_end = it_slice_begin;\n        \t\tfor(size_t i=0; i<max_send_size && it_slice_end != it_end; ++i){\n        \t\t\t++it_slice_end;\n        \t\t}\n        \t\tsend_pop.insert(send_pop.end(), it_slice_begin, it_slice_end);\n        \t}\n\n        \tg_exchange_v(_world, send_pop, recv_pop);\n\n        \t// Add all individuals to the same population and perform selection\n        \tfor(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n        \t\tthis->_pop.clear();\n\n            \t// Copy the current individuals to the population for processing\n            \tcompare::merge(this->_pop, _bins[bin_i]);\n\n        \t\t// Copy the new individuals to the population for processing\n        \t\tcompare::merge(this->_pop, send_pop);\n\n        \t\t// Add the received individuals to the population for processing\n        \t\tcompare::merge(this->_pop, recv_pop);\n\n        \t\t// Perform selection on the current population\n        \t\t_survivor_selection(bin_i);\n\n        \t\t// Copy the current population back to the appropriate bin\n        \t\t_copy_to_bin(bin_i, this->_pop);\n        \t}\n        }\n\n        // Copy everything back to the current population for serialization\n        _copy_all_to_pop(this->_pop);\n    }\n\n    /**\n     * Runs one epoch of our evolutionary algorithm.\n     */\n    void epoch(){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        DBO << \"Starting epoch: \" << this->_gen << dbe;\n\n        // Clear the population\n        this->_pop.clear();\n\n        // Define bins\n        pop_t send_pop;\n        pop_t recv_pop;\n        bins_t new_indiv_bins (_bins.size());\n\n        // Generate and evaluate new individuals\n        for(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n        \tfor (size_t i = 0; i < (offspring_per_generation/2); ++i){\n        \t\tDBO << \"New indiv: \" << i << dbe;\n        \t\tphen_ptr_t p1 = selection(_bins[bin_i]);\n        \t\tphen_ptr_t p2 = selection(_bins[bin_i]);\n        \t\tphen_ptr_t i1, i2;\n        \t\tp1->cross(p2, i1, i2);\n        \t\ti1->mutate();\n        \t\ti2->mutate();\n        \t\tnew_indiv_bins[bin_i].push_back(i1);\n        \t\tnew_indiv_bins[bin_i].push_back(i2);\n        \t}\n\n        \t// Evaluate the new individuals\n        \t_evaluate(new_indiv_bins[bin_i]);\n        }\n\n#ifdef EA_EVAL_ALL\n        for(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n        \t_evaluate(_bins[bin_i]);\n        }\n#endif\n\n\n//        // Decide which individuals to send\n//        for(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n//\n//        \t// Send the current (old) population\n//        \t//compare::merge(send_bins[bin_i], _bins[bin_i]);\n//\n//        \t// Send the newly created individuals\n//        \tcompare::merge(send_bins[bin_i], new_indiv_bins[bin_i]);\n//        }\n\n\n        /** OLD MP-CMOEA EXCHANGE START **/\n//        // Get the set of all partners that we need to interact with\n//        std::set<int> partners;\n//        std::map<int, std::vector<int> > recv_bin_map;\n//        std::map<int, std::vector<int> > send_bin_map;\n//        std::map<int, int> recv_map;\n//        for(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n//        \t_get_partners(bin_i, partners, recv_bin_map, send_bin_map, recv_map);\n//        }\n//\n//#if defined(DBG_ENABLED)\n//        {\n//        \tDBO_MPI << \"Partners of instance: \" << _world->rank() << dbe;\n//        \tstd::set<int>::iterator it;\n//        \tfor (it = partners.begin(); it != partners.end(); ++it){\n//        \t\tDBO_MPI << \"  partner: \" << *it << dbe;\n//        \t}\n//        }\n//#endif\n//        {\n//        \tstd::set<int>::iterator it;\n//        \tfor (it = partners.begin(); it != partners.end(); ++it){\n//        \t\t_exchange_send(*it, recv_bin_map, send_bin_map, send_bins, recv_bins, recv_map);\n//        \t}\n//        \tfor (it = partners.begin(); it != partners.end(); ++it){\n//        \t\t_exchange_recv(*it, recv_bin_map, send_bin_map, send_bins, recv_bins, recv_map);\n//        \t}\n//        }\n//        _wait_all();\n\t\t/** OLD MP-CMOEA EXCHANGE END **/\n\n//        // Exchange individuals with partners in the correct order\n//        while(!partners.empty()){\n//        \tint partner = *partners.begin();\n//        \tpartners.erase(partner);\n//        \t_exchange(partner, recv_bin_map, send_bin_map, send_bins, recv_bins, recv_map);\n//        }\n\n\n        // Exchange individuals\n        for(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n        \tcompare::merge(send_pop, new_indiv_bins[bin_i]);\n        }\n\n        g_exchange_v(_world, send_pop, recv_pop);\n\n        // Add all individuals to the same population and perform selection\n        for(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n        \tthis->_pop.clear();\n\n        \t// Copy the current individuals to the population for processing\n        \tcompare::merge(this->_pop, _bins[bin_i]);\n\n        \t// Copy the new individuals to the population for processing\n        \tcompare::merge(this->_pop, send_pop);\n\n        \t// Add the received individuals to the population for processing\n        \tcompare::merge(this->_pop, recv_pop);\n\n        \t// Perform selection on the current population\n        \t_survivor_selection(bin_i);\n\n        \t// Copy the current population back to the appropriate bin\n        \t_copy_to_bin(bin_i, this->_pop);\n        }\n\n        // Copy everything back to the current population for serialization\n        _copy_all_to_pop(this->_pop);\n\n        DBO << \"Epoch \" << this->_gen << \" complete.\" << dbe;\n    }\n\n    void barrier(){\n    \t_world->barrier();\n    }\n\nprotected:\n    // Pointer to the MPI environment\n    boost::shared_ptr<mpi_env_t> _env;\n\n    // Pointer to the MPI world\n    boost::shared_ptr<mpi_com_t> _world;\n\n    std::vector<boost::mpi::packed_oarchive*> _send_buffer;\n    std::vector<size_t*> _send_buffer_sizes;\n    std::vector<MPI_Request*> _outstanding_requests;\n\n    // Vector of bins stores all bins governed by this instance.\n    bins_t _bins;\n\n    // The global index of the first bin this instance is responsible for\n    int _first_bin_id;\n\n    // The lower bound on the number of bins handled by any one instance\n    int _min_bins_inst;\n\n    // The upper bound on the number of bins handled by any one instance\n    // Because bins are distributed as evenly over instances as possible, will\n    // always be _min_bins_inst + 1\n    int _max_bins_inst;\n\n    // The number of \"over-full instances\" (MPI instances responsible for\n    // _max_bins_inst bins).\n    int _overfull_inst;\n\n    // The total number of bins allocated to \"over-full instances\"\n    int _overfull_bins;\n\n    /**\n     * Evaluates all individuals in the provided population.\n     *\n     * @param pop: The population to evaluate.\n     */\n    void _evaluate(pop_t& pop){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tthis->_eval.eval(pop, 0, pop.size(), this->_fit_proto);\n#if defined(DBG_ENABLED)\n    \tfor(size_t i=0; i<pop.size(); ++i){\n    \t\tDBOF << \"Fit indiv: \" << i << dbe;\n    \t\tfor(size_t j=0; j<nr_of_bins; ++j){\n    \t\t\tDBOF << \"  bin \" << j <<\n    \t\t\t\t\t\": \" << pop[i]->fit().getBinFitness(j) << dbe;\n    \t\t}\n    \t}\n#endif\n    }\n\n    /**\n     * Performs survivor selection on the bin at the provided index.\n     *\n     * @param bin_i: The local bin index of the bin to evaluate.\n     */\n    void _survivor_selection(size_t bin_i){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n\n    \t// Determine the type of bin that we govern based on our rank\n    \tsize_t bin_obj = (_first_bin_id + bin_i) % nr_of_bins;\n    \tDBO << \"Performing selection for bin: \" << bin_obj << dbe;\n    \t_cat_to_obj(this->_pop, bin_obj);\n\n    \t// Apply modifiers\n    \tDBO << \"  Applying modifiers\" << dbe;\n    \tthis->apply_modifier();\n\n#if defined(DBG_ENABLED)\n    \tfor(size_t i=0; i<this->_pop.size(); ++i){\n    \t\tDBOO << \"  Pop before selection: \" << i << dbe;\n    \t\tfor(size_t j=0; j<this->_pop[i]->fit().objs().size(); ++j){\n    \t\t\tDBOO << \"    obj \" << j <<\n    \t\t\t\t\t\": \" << this->_pop[i]->fit().objs()[j] << dbe;\n    \t\t}\n    \t}\n#endif\n\n    \t// Perform selection\n    \tDBO << \"  Performing selection\" << dbe;\n    \tpop_t ptmp;\n    \tsort_f()(this->_pop, ptmp, bin_size);\n    \tthis->_pop = ptmp;\n\n#if defined(DBG_ENABLED)\n    \tfor(size_t i=0; i<this->_pop.size(); ++i){\n    \t\tDBOO << \"  Pop after selection: \" << i << dbe;\n    \t\tfor(size_t j=0; j<this->_pop[i]->fit().objs().size(); ++j){\n    \t\t\tDBOO << \"    obj \" << j <<\n    \t\t\t\t\t\": \" << this->_pop[i]->fit().objs()[j] << dbe;\n    \t\t}\n    \t}\n#endif\n\n    }\n\n\n    /**\n     * Initialize the current bins given a population.\n     *\n     * @param pop: The population with which to initialize the current bins.\n     */\n    void _set_pop(const pop_t& pop) {\n        dbg::trace trace(\"ea\", DBG_HERE);\n        size_t size_expected = _bins.size()*bin_size;\n        DBO << \"Pop size from archive: \" << pop.size() << dbe;\n        DBO << \"Pop size expected: \" << size_expected << dbe;\n        dbg::assertion(DBG_ASSERTION(pop.size() == size_expected));\n        size_t k=0;\n        for(size_t i=0; i<_bins.size(); ++i){\n        \tfor(size_t j=0; j<bin_size; ++j){\n        \t\t_bins[i].push_back(pop[k]);\n        \t\t++k;\n        \t}\n        }\n    }\n\n    /**\n     * Copy all individuals from the provided population to the bin at the\n     * provided bin index.\n     *\n     * @param bin_i: The local bin index of the bin to copy to.\n     * @param pop: The population of individuals to copy to that bin.\n     */\n    void _copy_to_bin(size_t bin_i, const pop_t& pop){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \t_bins[bin_i].clear();\n    \tcompare::merge(_bins[bin_i], pop);\n    }\n\n    /**\n     * Copy all individuals of all bins to the provided population.\n     *\n     * @param pop (out): The population to which to copy the current bins.\n     */\n    void _copy_all_to_pop(pop_t& pop){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tpop.clear();\n    \tfor(size_t bin_i=0; bin_i<_bins.size(); ++bin_i){\n    \t\tcompare::merge(pop, _bins[bin_i]);\n    \t}\n    }\n\n\n    /**\n     * Copy the performance on the task associated with the provided bin index\n     * to one of the current objectives of the all individuals of the provided\n     * population.\n     *\n     * @param pop: The population of individuals for which to copy task\n     *     performance.\n     * @param bin_i: The global bin index of the task performance that needs to\n     *     be copied.\n     */\n    void _cat_to_obj(pop_t& pop, size_t bin_i){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        for(size_t i=0; i<pop.size(); ++i){\n        \tpop[i]->fit().set_obj(obj_index, pop[i]->fit().getBinFitness(bin_i));\n        }\n    }\n\n    /**\n     * Calculates which other MPI instances we need to communicate with, and\n     * what data needs to be exchanged.\n     *\n     * @param local_bin_i: The local bin index for which we want to exchange\n     *     information.\n     * @param partners (out): Reference to the set of partners (mpi instances)\n     *     with whom we need to communicate.\n     * @param recv_bin_map (out): Reference to a map mapping instance rank to\n     *     a vector of global bin indices of bins that we will receive from that\n     *     instance.\n     * @param send_bin_map (out): Reference to a map mapping instance rank to a\n     *     vector of global bin indices that we will send to that instance.\n     * @param recv_map (out): Map indicating which of the received bins should\n     *     be added to which of the bins governed by this instance.\n     */\n    void _get_partners(int local_bin_i,\n    \t\tstd::set<int>& partners,\n\t\t\tinst_bin_map_t& recv_bin_map,\n\t\t\tinst_bin_map_t& send_bin_map,\n\t\t\tstd::map<int, int>& recv_map){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n\n    \t// Determine with which bins to exchange individuals\n    \tint global_bin_i = _get_global_bin_i(local_bin_i);\n    \tint offset = (this->_gen % (bins_total-1)) + 1;\n    \tint bin_id1 =  compare::mod(global_bin_i + offset, bins_total);\n    \tint bin_id2 =  compare::mod(global_bin_i - offset, bins_total);\n    \tint inst1 = _get_instance_from_bin(bin_id1);\n    \tint inst2 = _get_instance_from_bin(bin_id2);\n\n    \tsend_bin_map[inst1].push_back(global_bin_i);\n    \tsend_bin_map[inst2].push_back(global_bin_i);\n    \trecv_bin_map[inst1].push_back(bin_id1);\n    \trecv_bin_map[inst2].push_back(bin_id2);\n    \trecv_map[bin_id1] = global_bin_i;\n    \trecv_map[bin_id2] = global_bin_i;\n\n    \tpartners.insert(inst1);\n    \tpartners.insert(inst2);\n    }\n\n    /**\n     * Exchange all necessary bins with the indicated partner.\n     *\n     * @param partner: Rank of the MPI instance with whom to exchange data.\n     * @param recv_bin_map: The map of MPI instances and bins to receive.\n     * @param send_bin_map: The map on MPI instances and bins to send.\n     * @param send_bins: Vector containing the actual bins to send.\n     * @param recv_bins (out): Vector for storing received bins.\n     * @param recv_map: Map indicating which received bins should be added to\n     *     which of the local bins (in global bin ids).\n     */\n    void _exchange(int partner,\n    \t\tinst_bin_map_t& recv_bin_map,\n\t\t\tinst_bin_map_t& send_bin_map,\n\t\t\tconst bins_t& send_bins,\n\t\t\tbins_t& recv_bins,\n\t\t\tconst std::map<int, int>& recv_map){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tDBO_MPI << \"Exchanging with partner: \" << partner << dbe;\n\n    \t// These are the bins I am going to send, and in the order in which I\n    \t// will send them\n    \tstd::vector<int> bins_to_send = send_bin_map[partner];\n    \tcompare::sort(bins_to_send);\n\n    \t// These are the bins I am going to receive, and in the order in which\n    \t// I will receive them\n    \tstd::vector<int> bins_to_receive = recv_bin_map[partner];\n    \tcompare::sort(bins_to_receive);\n\n    \tif(_world->rank() == partner){\n    \t\tDBO_MPI << \"Performing local exchange\" << dbe;\n    \t\tfor(size_t i=0; i<bins_to_send.size(); ++i){\n    \t\t\tint send_bin_i = _get_local_bin_i(bins_to_send[i]);\n    \t\t\tint recv_bin_i = _get_local_bin_i(bins_to_receive[i]);\n    \t\t\trecv_bins[recv_bin_i] = send_bins[send_bin_i];\n    \t\t}\n    \t} else if(_world->rank() < partner){\n    \t\tDBO_MPI << \"My rank is lower, sending first\" << dbe;\n    \t\tfor(size_t i=0; i<bins_to_send.size(); ++i){\n    \t\t\tDBO_MPI << \"Sending bin: \" << bins_to_send[i] << dbe;\n    \t\t\tint local_bin_i = _get_local_bin_i(bins_to_send[i]);\n    \t\t\tDBO_MPI << \"Local bin index: \" << local_bin_i << dbe;\n    \t\t\t_send(partner, send_bins[local_bin_i]);\n    \t\t}\n    \t\tfor(size_t i=0; i<bins_to_receive.size(); ++i){\n    \t\t\tDBO_MPI << \"Receiving bin: \" << bins_to_receive[i] << dbe;\n    \t\t\tint global_bin_i = recv_map.at(bins_to_receive[i]);\n    \t\t\tDBO_MPI << \"Adding it to bin: \" << global_bin_i << dbe;\n    \t\t\tint local_bin_i = _get_local_bin_i(global_bin_i);\n    \t\t\tDBO_MPI << \"Local bin index: \" << local_bin_i << dbe;\n    \t\t\t_recv(partner, recv_bins[local_bin_i]);\n    \t\t}\n    \t} else {\n    \t\tDBO_MPI << \"My rank is higher, receiving first\" << dbe;\n    \t\tfor(size_t i=0; i<bins_to_receive.size(); ++i){\n    \t\t\tDBO_MPI << \"Receiving bin: \" << bins_to_receive[i] << dbe;\n    \t\t\tint global_bin_i = recv_map.at(bins_to_receive[i]);\n    \t\t\tDBO_MPI << \"Adding it to bin: \" << global_bin_i << dbe;\n    \t\t\tint local_bin_i = _get_local_bin_i(global_bin_i);\n    \t\t\tDBO_MPI << \"Local bin index: \" << local_bin_i << dbe;\n    \t\t\t_recv(partner, recv_bins[local_bin_i]);\n    \t\t}\n    \t\tfor(size_t i=0; i<bins_to_send.size(); ++i){\n    \t\t\tDBO_MPI << \"Sending bin: \" << bins_to_send[i] << dbe;\n    \t\t\tint local_bin_i = _get_local_bin_i(bins_to_send[i]);\n    \t\t\tDBO_MPI << \"Local bin index: \" << local_bin_i << dbe;\n    \t\t\t_send(partner, send_bins[local_bin_i]);\n    \t\t}\n    \t}\n    }\n\n    /**\n     * Exchange all necessary bins with the indicated partner.\n     *\n     * @param partner: Rank of the MPI instance with whom to exchange data.\n     * @param recv_bin_map: The map of MPI instances and bins to receive.\n     * @param send_bin_map: The map on MPI instances and bins to send.\n     * @param send_bins: Vector containing the actual bins to send.\n     * @param recv_bins (out): Vector for storing received bins.\n     * @param recv_map: Map indicating which received bins should be added to\n     *     which of the local bins (in global bin ids).\n     */\n    void _exchange_send(int partner,\n    \t\tinst_bin_map_t& recv_bin_map,\n\t\t\tinst_bin_map_t& send_bin_map,\n\t\t\tconst bins_t& send_bins,\n\t\t\tbins_t& recv_bins,\n\t\t\tconst std::map<int, int>& recv_map){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tDBO_MPI << \"Sending to partner: \" << partner << dbe;\n\n    \t// These are the bins I am going to send, and in the order in which I\n    \t// will send them\n    \tstd::vector<int> bins_to_send = send_bin_map[partner];\n    \tcompare::sort(bins_to_send);\n\n    \t// These are the bins I am going to receive, and in the order in which\n    \t// I will receive them\n    \tstd::vector<int> bins_to_receive = recv_bin_map[partner];\n    \tcompare::sort(bins_to_receive);\n\n    \tif(_world->rank() == partner){\n    \t\tDBO_MPI << \"Performing local exchange\" << dbe;\n    \t\tfor(size_t i=0; i<bins_to_send.size(); ++i){\n    \t\t\tint send_bin_i = _get_local_bin_i(bins_to_send[i]);\n    \t\t\tint recv_bin_i = _get_local_bin_i(bins_to_receive[i]);\n    \t\t\trecv_bins[recv_bin_i] = send_bins[send_bin_i];\n    \t\t}\n    \t} else {\n    \t\tDBO_MPI << \"Sending:\" << dbe;\n    \t\tfor(size_t i=0; i<bins_to_send.size(); ++i){\n    \t\t\tDBO_MPI << \"Sending bin: \" << bins_to_send[i] << dbe;\n    \t\t\tint local_bin_i = _get_local_bin_i(bins_to_send[i]);\n    \t\t\tDBO_MPI << \"Local bin index: \" << local_bin_i << dbe;\n    \t\t\t_sendi(partner, send_bins[local_bin_i], int(i));\n    \t\t}\n    \t}\n    }\n\n    /**\n     * Exchange all necessary bins with the indicated partner.\n     *\n     * @param partner: Rank of the MPI instance with whom to exchange data.\n     * @param recv_bin_map: The map of MPI instances and bins to receive.\n     * @param send_bin_map: The map on MPI instances and bins to send.\n     * @param send_bins: Vector containing the actual bins to send.\n     * @param recv_bins (out): Vector for storing received bins.\n     * @param recv_map: Map indicating which received bins should be added to\n     *     which of the local bins (in global bin ids).\n     */\n    void _exchange_recv(int partner,\n    \t\tinst_bin_map_t& recv_bin_map,\n\t\t\tinst_bin_map_t& send_bin_map,\n\t\t\tconst bins_t& send_bins,\n\t\t\tbins_t& recv_bins,\n\t\t\tconst std::map<int, int>& recv_map){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tDBO_MPI << \"Receiving from partner: \" << partner << dbe;\n\n    \t// These are the bins I am going to send, and in the order in which I\n    \t// will send them\n    \tstd::vector<int> bins_to_send = send_bin_map[partner];\n    \tcompare::sort(bins_to_send);\n\n    \t// These are the bins I am going to receive, and in the order in which\n    \t// I will receive them\n    \tstd::vector<int> bins_to_receive = recv_bin_map[partner];\n    \tcompare::sort(bins_to_receive);\n\n\n    \tif(_world->rank() == partner){\n    \t\tDBO_MPI << \"Partner is local: exchange already completed\" << dbe;\n    \t} else {\n    \t\tDBO_MPI << \"Receiving\" << dbe;\n    \t\tfor(size_t i=0; i<bins_to_receive.size(); ++i){\n    \t\t\tDBO_MPI << \"Receiving bin: \" << bins_to_receive[i] << dbe;\n    \t\t\tint global_bin_i = recv_map.at(bins_to_receive[i]);\n    \t\t\tDBO_MPI << \"Adding it to bin: \" << global_bin_i << dbe;\n    \t\t\tint local_bin_i = _get_local_bin_i(global_bin_i);\n    \t\t\tDBO_MPI << \"Local bin index: \" << local_bin_i << dbe;\n    \t\t\t_recv(partner, recv_bins[local_bin_i], int(i));\n    \t\t}\n    \t}\n    }\n\n    /**\n     * Send the supplied population to the indicated MPI instance.\n     *\n     * @param partner: The rank of the MPI instance to send to.\n     * @param pop: The population to send.\n     */\n    void _sendi(int partner, const pop_t& pop, int tag=1){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tMPI_Request* req1 = new MPI_Request();\n    \tMPI_Request* req2 = new MPI_Request();\n    \t_outstanding_requests.push_back(req1);\n    \t_outstanding_requests.push_back(req2);\n        std::vector<MPI_Request> req(2);\n        DBO_MPI << \"sending to rank: \" << partner << std::endl;\n\n        // Serializing population\n\n        boost::mpi::packed_oarchive* oa = new boost::mpi::packed_oarchive (*_world);\n        _send_buffer.push_back(oa);\n\n\t\t//boost::mpi::packed_oarchive oa(*_world);\n        (*oa) << pop;\n        //_outstanding_requests.push_back(MPI_Request());\n        size_t* size_p = new size_t((*oa).size());\n        _send_buffer_sizes.push_back(size_p);\n\n        // Send the the number of individuals that will be send\n        const void* size_1 = size_p;\n        BOOST_MPI_CHECK_RESULT(MPI_Isend,\n                (const_cast<void*>(size_1), 1,\n                 boost::mpi::get_mpi_datatype<std::size_t>(*size_p),\n\t\t\t\t partner, tag, *_world, req1));\n\n        // Actually send the individuals\n        BOOST_MPI_CHECK_RESULT(MPI_Isend,\n                (const_cast<void*>((*oa).address()),\n                (*oa).size(),\n                 MPI_PACKED,\n\t\t\t\t partner, tag, *_world, req2));\n\n        // Wait until everything is send successfully\n        //BOOST_MPI_CHECK_RESULT(MPI_Waitall, (req.siz(), &req[0], MPI_STATUSES_IGNORE));\n    }\n\n    /**\n     * Send the supplied population to the indicated MPI instance.\n@@ -640,29 +748,53 @@ protected:\n     */\n    void _send(int partner, const pop_t& pop){\n       dbg::trace trace(\"ea\", DBG_HERE);\n        std::vector<MPI_Request> req(2);\n        DBO_MPI << \"sending to rank: \" << partner << std::endl;\n        int tag = 1;\n\n        // Serializing population\n        boost::mpi::packed_oarchive oa(*_world);\n        oa << pop;\n\n        // Send the the number of individuals that will be send\n        const void* size_1 = &oa.size();\n\n        BOOST_MPI_CHECK_RESULT(MPI_Isend,\n                (const_cast<void*>(size_1), 1,\n                 boost::mpi::get_mpi_datatype<std::size_t>(oa.size()),\n                                partner, tag, *_world, &req[0]));\n\n        // Actually send the individuals\n        BOOST_MPI_CHECK_RESULT(MPI_Isend,\n                (const_cast<void*>(oa.address()), oa.size(),\n                 MPI_PACKED, partner, tag, *_world, &req[1]));\n\n\n        // Wait until everything is send successfully\n        BOOST_MPI_CHECK_RESULT(MPI_Waitall, (2, &req[0], MPI_STATUSES_IGNORE));\n    }\n\n    void _wait_all(){\n    \tstd::vector<MPI_Request> requests;\n    \tfor(size_t i=0; i<_outstanding_requests.size(); ++i){\n    \t\trequests.push_back(*(_outstanding_requests[i]));\n    \t}\n    \tBOOST_MPI_CHECK_RESULT(MPI_Waitall, (requests.size(), &requests[0], MPI_STATUSES_IGNORE));\n    \tfor(size_t i=0; i<_outstanding_requests.size(); ++i){\n    \t\tdelete _outstanding_requests[i];\n    \t}\n    \t_outstanding_requests.clear();\n    \tfor(size_t i=0; i<_send_buffer_sizes.size(); ++i){\n    \t\tdelete _send_buffer_sizes[i];\n    \t}\n    \t_send_buffer_sizes.clear();\n    \tfor(size_t i=0; i<_send_buffer.size(); ++i){\n    \t\tdelete _send_buffer[i];\n    \t}\n    \t_send_buffer.clear();\n    }\n\n\n    /**\n     * Receive individuals from the indicated MPI instance.\n     *\n     * @param partner: The rank of the MPI instance to receive from.\n     * @param pop (out): Reference to a population in which to store the\n     *     received individuals.\n     */\n    void _recv(int partner, pop_t& pop, int tag = 1){\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n        // Receive data from the root.\n        MPI_Status stat;\n        std::size_t count;\n        int recv = 0;\n        using namespace boost::mpi;\n\n        DBO_MPI << \"receiving from rank: \" << partner << dbe;\n\n        BOOST_MPI_CHECK_RESULT(MPI_Recv,\n                (&count, 1,  get_mpi_datatype<std::size_t>(count),\n                partner, tag, *_world, &stat));\n        MPI_Get_count(&stat,  get_mpi_datatype<std::size_t>(count), &recv);\n        DBO_MPI  <<\n\t\t\t\t\" received size_t of size: \" << recv <<\n\t\t\t\t\" from \" << stat.MPI_SOURCE <<\n\t\t\t\t\" with tag \" << stat.MPI_TAG << std::endl;\n\n        // Prepare input buffer and receive the message\n        mpi_iarchive_t ia(*_world);\n        ia.resize(count);\n        BOOST_MPI_CHECK_RESULT(MPI_Recv,\n                (ia.address(), ia.size(), MPI_PACKED,\n                partner, tag,\n                 *_world, &stat));\n        MPI_Get_count(&stat, MPI_PACKED, &recv);\n        DBO_MPI <<\n\t\t\t\t\" received archive of size: \" << recv <<\n\t\t\t\t\" from \" << stat.MPI_SOURCE <<\n\t\t\t\t\" with tag \" << stat.MPI_TAG << std::endl;\n\n        // De-serializing population\n        ia >> pop;\n    }\n\n\n    /**\n     * Takes a global bin index and returns the local bin index.\n     *\n     * @param global_bin_i: The global bin index to convert.\n     * @return: The local bin index.\n     */\n    inline int _get_local_bin_i(int global_bin_i) const{\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tdbg::assertion(DBG_ASSERTION(global_bin_i >= 0));\n    \tdbg::assertion(DBG_ASSERTION(global_bin_i < bins_total));\n    \tint result = global_bin_i - _first_bin_id;\n    \tdbg::assertion(DBG_ASSERTION(result >= 0));\n    \tdbg::assertion(DBG_ASSERTION(result < _bins.size()));\n    \treturn result;\n    }\n\n    /**\n     * Takes a local bin index and returns its global bin index.\n     *\n     * @param local_bin_i: The local bin index to convert.\n     * @return: The global bin index.\n     */\n    inline int _get_global_bin_i(int local_bin_i) const{\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tdbg::assertion(DBG_ASSERTION(local_bin_i >= 0));\n    \tdbg::assertion(DBG_ASSERTION(local_bin_i < _bins.size()));\n    \tint result = local_bin_i + _first_bin_id;\n    \tdbg::assertion(DBG_ASSERTION(result >= 0));\n    \tdbg::assertion(DBG_ASSERTION(result < bins_total));\n    \treturn result;\n    }\n\n\n    /**\n     * Returns the rank of the instance associated with the supplied bin_id.\n     *\n     * @param bin_id: The global bin index for which we want to retrieve the MPI\n     *     instance.\n     * @return: The rank of the MPI instance responsible for the provided bin\n     *     index.\n     */\n    inline int _get_instance_from_bin(int bin_id) const{\n    \tdbg::trace trace(\"ea\", DBG_HERE);\n    \tint instance_rank;\n\n\t\tif(bin_id < _overfull_bins){\n\t\t\t// The instance we are looking for is one of the over-full instances\n\t\t\tinstance_rank = bin_id / _max_bins_inst;\n\t\t} else{\n\t\t\t// The instance we are looking for is one of the other instances\n\t\t\tint other_bins = (bin_id - _overfull_bins);\n\t\t\tint other_instances = other_bins / _min_bins_inst;\n\t\t\tinstance_rank = _overfull_inst + other_instances;\n\t\t}\n\n\t\treturn instance_rank;\n    }\n};\n}\n}\n\n#undef DBO\n#undef DBO_MPI\n#undef DBOF\n#undef DBOO\n\n#endif /* MODULES_CMOEA_CMOEA_NSGA2_MPI_HPP_ */\n", "meta": {"hexsha": "8810f010e467cb1217354a551969e2b550acbf4a", "size": 36470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mp_cmoea_nsga2_mpi.hpp", "max_stars_repo_name": "Evolving-AI-Lab/cmoea", "max_stars_repo_head_hexsha": "6f3c3d8e1ba23bb9c786f2335bccfa26dbc25cfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-07-14T22:02:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T11:03:27.000Z", "max_issues_repo_path": "mp_cmoea_nsga2_mpi.hpp", "max_issues_repo_name": "Evolving-AI-Lab/cmoea", "max_issues_repo_head_hexsha": "6f3c3d8e1ba23bb9c786f2335bccfa26dbc25cfb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mp_cmoea_nsga2_mpi.hpp", "max_forks_repo_name": "Evolving-AI-Lab/cmoea", "max_forks_repo_head_hexsha": "6f3c3d8e1ba23bb9c786f2335bccfa26dbc25cfb", "max_forks_repo_licenses": ["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.0336215178, "max_line_length": 95, "alphanum_fraction": 0.6293666027, "num_tokens": 9630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.02976009437622677, "lm_q1q2_score": 0.007732435507082203}}
{"text": "\n// MIT License\n//\n// Copyright (c) 2018 degski\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#pragma once\n\n#include <cstdint>\n#include <cstdlib>\n#include <cmath>\n\n#include <iostream>\n#include <random>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/container/static_vector.hpp>\n\n#include <cereal/cereal.hpp>\n#include <cereal/types/unordered_map.hpp>\n#include <cereal/archives/binary.hpp>\n\n#include \"owningptr.hpp\"\n#include \"pool_allocator.hpp\"\n\n#include \"autotimer.hpp\"\n\n#include \"Typedefs.hpp\"\n#include \"player.hpp\"\n#include \"flat_search_tree.hpp\"\n\n\nnamespace mcts {\n\n    template<typename T>\n    class Stack {\n\n        std::vector<T> m_data;\n\n    public:\n\n        explicit Stack ( const T & v_ ) noexcept {\n            m_data.push_back ( v_ );\n        }\n\n        [[ nodiscard ]] T pop ( ) noexcept {\n            const T v { m_data.back ( ) };\n            m_data.pop_back ( );\n            return v;\n        }\n\n        void push ( const T & v_ ) noexcept {\n            m_data.push_back ( v_ );\n        }\n\n        [[ nodiscard ]] bool not_empty ( ) const noexcept {\n            return m_data.size ( );\n        }\n    };\n\n\n    template<typename T>\n    class Queue {\n\n        boost::container::deque<T> m_data;\n\n    public:\n\n        explicit Queue ( const T & v_ ) noexcept {\n            m_data.push_back ( v_ );\n        }\n\n        [[ nodiscard ]] const T pop ( ) noexcept {\n            const T v = m_data.front ( );\n            m_data.pop_front ( );\n            return v;\n        }\n\n        void push ( const T & v_ ) noexcept {\n            m_data.push_back ( v_ );\n        }\n\n        [[ nodiscard ]] bool not_empty ( ) const noexcept {\n            return m_data.size ( );\n        }\n    };\n\n\n\n    template<typename State>\n    struct ArcData { // 1 bytes.\n\n        using state_type = State;\n        // float m_score = 0.0f; // 4 bytes.\n        // std::int32_t m_visits = 0; // 4 bytes.\n        typename State::Move m_move = State::Move::invalid; // 1 bytes.\n\n        ArcData ( ) noexcept {\n            // std::cout << \"arcdata default constructed\\n\";\n        }\n        ArcData ( const State & state_ ) noexcept {\n            // std::cout << \"arcdata constructed from state\\n\";\n            m_move = state_.lastMove ( );\n        }\n        ArcData ( const ArcData & ad_ ) noexcept {\n            // std::cout << \"arcdata copy constructed\\n\";\n            // m_score = nd_.m_score;\n            // m_visits = nd_.m_visits;\n            m_move = ad_.m_move;\n        }\n        ArcData ( ArcData && ad_ ) noexcept {\n            // std::cout << \"arcdata move constructed\\n\";\n            // m_score = std::move ( ad_.m_score );\n            // m_visits = std::move ( ad_.m_visits );\n            m_move = std::move ( ad_.m_move );\n        }\n\n        ~ArcData ( ) noexcept {\n        }\n\n        [[ maybe_unused ]] ArcData & operator += ( const ArcData & rhs_ ) noexcept {\n            // m_score += rhs_.m_score;\n            // m_visits += rhs_.m_visits;\n            return * this;\n        }\n\n        [[ maybe_unused ]] ArcData & operator = ( const ArcData & ad_ ) noexcept {\n            // std::cout << \"arcdata copy assigned\\n\";\n            // m_score = nd_.m_score;\n            // m_visits = nd_.m_visits;\n            m_move = ad_.m_move;\n            return * this;\n        }\n\n        [[ maybe_unused ]] ArcData & operator = ( ArcData && ad_ ) noexcept {\n            // std::cout << \"arcdata move assigned\\n\";\n            // m_score = std::move ( ad_.m_score );\n            // m_visits = std::move ( ad_.m_visits );\n            m_move = std::move ( ad_.m_move );\n            return * this;\n        }\n\n    private:\n\n        friend class cereal::access;\n\n        template < class Archive >\n        void serialize ( Archive & ar_ ) {\n            ar_ ( m_move );\n        }\n    };\n\n\n\n    template<typename State>\n    struct NodeData { // 17 bytes.\n\n        using state_type = State;\n        using Moves = typename State::Moves;\n        using Move = typename State::Moves::value_type;\n        using MovesPool = pa::pool_allocator<Moves>;\n        using MovesPoolPtr = llvm::OwningPtr<MovesPool>;\n\n        Moves * m_moves = nullptr;  // 8 bytes.\n        float m_score = 0.0f; // 4 bytes.\n        std::int32_t m_visits = 0; // 4 bytes.\n        Player m_player_just_moved = Player::Type::invalid; // 1 byte.\n\n        // Constructors.\n\n        NodeData ( ) noexcept {\n            // std::cout << \"nodedata default constructed\\n\";\n        }\n        NodeData ( const State & state_ ) noexcept {\n            // std::cout << \"nodedata constructed from state\\n\";\n            m_moves = m_moves_pool->new_element ( );\n            if ( not ( state_.moves ( m_moves ) ) ) {\n                m_moves_pool->delete_element ( m_moves );\n                m_moves = nullptr;\n            }\n            m_player_just_moved = state_.playerJustMoved ( );\n        }\n        NodeData ( const NodeData & nd_ ) noexcept {\n            // std::cout << \"nodedata copy constructed\\n\";\n            if ( nd_.m_moves != nullptr ) {\n                m_moves = m_moves_pool->new_element ( * nd_.m_moves );\n            }\n            m_score = nd_.m_score;\n            m_visits = nd_.m_visits;\n            m_player_just_moved = nd_.m_player_just_moved;\n        }\n        NodeData ( NodeData && nd_ ) noexcept {\n            // std::cout << \"nodedata move constructed\\n\";\n            std::swap ( m_moves, nd_.m_moves );\n            m_score = std::move ( nd_.m_score );\n            m_visits = std::move ( nd_.m_visits );\n            m_player_just_moved = std::move ( nd_.m_player_just_moved );\n        }\n\n        ~NodeData ( ) noexcept {\n            m_moves_pool->delete_element ( m_moves ); // Checked for nullptr in delete_element ( ... ).\n        }\n\n        [[ nodiscard ]] Move getUntriedMove ( ) noexcept {\n            if ( 1 == m_moves->size ( ) ) {\n                // 1 move left, so destroy memory and return that 1 move.\n                const Move move = m_moves->front ( );\n                m_moves_pool->delete_element ( m_moves );\n                m_moves = nullptr;\n                return move;\n            }\n            return m_moves->draw ( );\n        }\n\n        [[ maybe_unused ]] NodeData & operator += ( const NodeData & rhs_ ) noexcept {\n            m_score += rhs_.m_score;\n            m_visits += rhs_.m_visits;\n            return * this;\n        }\n\n        [[ maybe_unused ]] NodeData & operator = ( const NodeData & nd_ ) noexcept {\n            // std::cout << \"nodedata copy assigned\\n\";\n            if ( nullptr != nd_.m_moves ) {\n                m_moves = m_moves_pool->new_element ( * nd_.m_moves );\n            }\n            m_score = nd_.m_score;\n            m_visits = nd_.m_visits;\n            m_player_just_moved = nd_.m_player_just_moved;\n            return * this;\n        }\n\n        [[ maybe_unused ]] NodeData & operator = ( NodeData && nd_ ) noexcept {\n            // std::cout << \"nodedata move assigned\\n\";\n            std::swap ( m_moves, nd_.m_moves );\n            m_score = std::move ( nd_.m_score );\n            m_visits = std::move ( nd_.m_visits );\n            m_player_just_moved = std::move ( nd_.m_player_just_moved );\n            return * this;\n        }\n\n        static MovesPoolPtr m_moves_pool;\n\n    private:\n\n        friend class cereal::access;\n\n        template < class Archive >\n        void save ( Archive & ar_ ) const noexcept {\n            if ( nullptr != m_moves ) {\n                const std::int8_t tmp = 2;\n                ar_ ( tmp );\n                m_moves->serialize ( ar_ );\n            }\n            else {\n                const std::int8_t tmp = 1;\n                ar_ ( tmp );\n            }\n            ar_ ( m_score, m_visits, m_player_just_moved );\n        }\n\n        template < class Archive >\n        void load ( Archive & ar_ ) noexcept {\n            std::int8_t tmp = -1;\n            ar_ ( tmp );\n            if ( 2 == tmp ) {\n                m_moves = m_moves_pool->new_element ( );\n                m_moves->serialize ( ar_ );\n            }\n            ar_ ( m_score, m_visits, m_player_just_moved );\n        }\n    };\n\n    template<typename State>\n    typename NodeData<State>::MovesPoolPtr NodeData<State>::m_moves_pool ( new MovesPool ( ) );\n\n\n    template <typename State>\n    using Tree = fst::SearchTree<ArcData<State>, NodeData<State>>;\n\n    template<typename State>\n    using NodeID = typename Tree<State>::NodeID;\n\n    template<typename State>\n    using ArcID = typename Tree<State>::ArcID;\n\n\n    template < typename State >\n    class Mcts {\n\n    public:\n\n        using Tree = Tree<State>;\n\n        using ArcID = typename Tree::ArcID;\n        using NodeID = typename Tree::NodeID;\n\n        using ArcData = ArcData<State>;\n        using NodeData = NodeData<State>;\n\n        using InIt = typename Tree::in_iterator;\n        using OutIt = typename Tree::out_iterator;\n\n        using cInIt = typename Tree::const_in_iterator;\n        using cOutIt = typename Tree::const_out_iterator;\n\n        using Move = typename State::Move;\n        using Moves = typename State::Moves;\n\n        using Player = typename State::Player;\n\n        using Link = typename Tree::Link;\n        using Path = typename Tree::Path;\n\n        using TranspositionTable = std::unordered_map<ZobristHash, NodeID>;\n        using InverseTranspositionTable = std::vector < ZobristHash >;\n        using TranspositionTablePtr = llvm::OwningPtr<TranspositionTable>;\n\n        // The data.\n\n        Tree m_tree;\n        TranspositionTablePtr m_transposition_table;\n\n        bool m_not_initialized = true;\n\n        // The purpose of the m_path is to maintain the path with updates\n        // (of the visits/scores) all the way to the original root (start\n        // of the game). It's also used as a scrath-pad for the updates\n        // after play-out. Each move and players' move gets added to this\n        // path.\n\n        Path m_path;\n        index_t m_path_size;\n\n        // Init.\n\n        void initialize ( const State & state_ ) noexcept {\n            if ( m_transposition_table.get ( ) == nullptr ) {\n                m_transposition_table.reset ( new TranspositionTable ( ) );\n            }\n            // Set root_node data.\n            m_tree [ m_tree.root_node ] = NodeData { state_ };\n            // Add root_node to transposition_table.\n            m_transposition_table->emplace ( state_.zobrist ( ), m_tree.root_node );\n            // Has been initialized.\n            m_not_initialized = false;\n            m_path.reset ( Tree::ArcID::invalid, m_tree.root_node );\n            m_path_size = 1;\n        }\n\n\n        [[ nodiscard ]] Link addArc ( const NodeID parent_, const NodeID child_, const State & state_ ) noexcept {\n            return { m_tree.addArc ( parent_, child_, state_ ), child_ };\n        }\n\n        [[ nodiscard ]] Link addNode ( const NodeID parent_, const State & state_ ) noexcept {\n            const Link link_to_child { addArc ( parent_, m_tree.addNode ( state_ ), state_ ) };\n            m_transposition_table->emplace ( state_.zobrist ( ), link_to_child.target );\n            return link_to_child;\n        }\n\n\n        void printMoves ( const NodeID n_ ) const noexcept {\n            std::cout << \"moves of \" << ( int ) n_ << \": \";\n            for ( OutIt a ( m_tree, n_ ); a != OutIt::end ( ); ++a ) {\n                std::cout << \"[\" << ( int ) a.get ( ) << \", \" << ( int ) m_tree [ a ].m_move.m_loc << \"]\";\n            }\n            putchar ( '\\n' );\n        }\n\n\n        [[ nodiscard ]] Move getMove ( const ArcID arc_ ) const noexcept {\n            return m_tree [ arc_ ].m_move;\n        }\n\n        [[ nodiscard ]] NodeID getNode ( const ZobristHash zobrist_ ) const noexcept {\n            const auto it = m_transposition_table->find ( zobrist_ );\n            return it == m_transposition_table->cend ( ) ? Tree::NodeID::invalid : it->second;\n        }\n\n\n        [[ nodiscard ]] bool hasChildren ( const NodeID node_ ) const noexcept {\n            return m_tree.isInternal ( node_ );\n        }\n\n\n        // Moves.\n\n        [[ nodiscard ]] bool hasNoUntriedMoves ( const NodeID node_ ) const noexcept {\n            return m_tree [ node_ ].m_moves == nullptr;\n        }\n\n        [[ nodiscard ]] bool hasUntriedMoves ( const NodeID node_ ) const noexcept {\n            return m_tree [ node_ ].m_moves != nullptr;\n        }\n\n        [[ nodiscard ]] Move getUntriedMove ( const NodeID node_ ) noexcept {\n            return m_tree [ node_ ].getUntriedMove ( );\n        }\n\n\n        // Data.\n\n        [[ nodiscard ]] std::int32_t getVisits ( const NodeID node_ ) const noexcept {\n            std::int32_t visits = 0;\n            for ( InIt a { m_tree, node_ }; a.is_valid ( ); ++a ) {\n                visits += m_tree [ a ].m_visits;\n            }\n            return visits;\n        }\n\n\n        [[ nodiscard ]] float getUCTFromArcs ( const NodeID parent_, const NodeID child_ ) const noexcept {\n            ArcData child_data;\n            for ( InIt a { m_tree, child_ }; a.is_valid ( ); ++a ) {\n                child_data += m_tree [ a ];\n            }\n            std::int32_t visits = 1;\n            for ( InIt a { m_tree, parent_ }; a.is_valid ( ); ++a ) {\n                visits += m_tree [ a ].m_visits;\n            }\n            //                              Exploitation                                                             Exploration\n            // Exploitation is the task to select the move that leads to the best results so far.\n            // Exploration deals with less promising moves that still have to be examined, due to the uncertainty of the evaluation.\n            return ( float ) child_data.m_score / ( float ) child_data.m_visits + sqrtf ( 3.0f * logf ( ( float ) visits ) / ( float ) child_data.m_visits );\n        }\n\n\n        [[ nodiscard ]] float getUCTFromNode ( const NodeID parent_, const NodeID child_ ) const noexcept {\n            //                              Exploitation                                                             Exploration\n            // Exploitation is the task to select the move that leads to the best results so far.\n            // Exploration deals with less promising moves that still have to be examined, due to the uncertainty of the evaluation.\n            return ( float ) m_tree [ child_ ].m_score / ( float ) m_tree [ child_ ].m_visits + sqrtf ( 4.0f * logf ( ( float ) ( m_tree [ parent_ ].m_visits + 1 ) ) / ( float ) m_tree [ child_ ].m_visits );\n        }\n\n\n        [[ nodiscard ]] Link selectChildRandom ( const NodeID parent_ ) const noexcept {\n            boost::container::static_vector<Link, State::max_no_moves> children;\n            for ( OutIt a ( m_tree, parent_ ); a.is_valid ( ); ++a ) {\n                children.emplace_back ( a.id ( ), a->target );\n            }\n            return children [ std::uniform_int_distribution<ptrdiff_t> ( 0, children.size ( ) - 1 ) ( g_rng ) ];\n        }\n\n\n        [[ nodiscard ]] Link selectChildUCT ( const NodeID parent_ ) const noexcept {\n            cOutIt a = m_tree.cbeginOut ( parent_ );\n            boost::container::static_vector < Link, State::max_no_moves > best_children ( 1, m_tree.link ( a ) );\n            float best_UCT_score = getUCTFromNode ( parent_, best_children.back ( ).target );\n            ++a;\n            for ( ; a.is_valid ( ); ++a ) {\n                const Link child = m_tree.link ( a );\n                const float UCT_score = getUCTFromNode ( parent_, child.target );\n                if ( UCT_score > best_UCT_score ) {\n                    best_children.resize ( 1 );\n                    best_children.back ( ) = child;\n                    best_UCT_score = UCT_score;\n                }\n                else if ( UCT_score == best_UCT_score ) {\n                    best_children.push_back ( child );\n                }\n            }\n            // Ties are broken by fair coin flips.\n            return best_children.size ( ) == 1 ? best_children.back ( ) : best_children [ std::uniform_int_distribution < ptrdiff_t > ( 0, best_children.size ( ) - 1 ) ( g_rng ) ];\n        }\n\n\n        // State is updated to reflect move.\n        [[ nodiscard ]] Link addChild ( const NodeID parent_, const State & state_ ) noexcept {\n            const NodeID child = getNode ( state_.zobrist ( ) );\n            return Tree::NodeID::invalid == child ? addNode ( parent_, state_ ) : addArc ( parent_, child, state_ );\n        }\n\n\n        void updateData ( const Link & link_, const State & state_ ) noexcept {\n            const float result = state_.result ( m_tree [ link_.target ].m_player_just_moved );\n            // ++m_tree [ link_.arc ].m_visits;\n            // m_tree [ link_.arc ].m_score += result;\n            ++m_tree [ link_.target ].m_visits;\n            m_tree [ link_.target ].m_score += result;\n        }\n\n\n        // Find the node (the most robust) with the most visits.\n        [[ nodiscard ]] Move getBestMove ( ) noexcept {\n            std::int32_t best_child_visits = INT_MIN;\n            Move best_child_move = State::Move::none;\n            m_path.push ( Tree::ArcID::invalid, Tree::NodeID::invalid );\n            ++m_path_size;\n            for ( cOutIt a ( m_tree.cbeginOut ( m_tree.root_node ) ); a.is_valid ( ); ++a ) {\n                const Link child ( m_tree.link ( a ) );\n                const std::int32_t child_visits ( m_tree [ child.target ].m_visits );\n                if ( child_visits > best_child_visits ) {\n                    best_child_visits = child_visits;\n                    best_child_move = m_tree [ child.arc ].m_move;\n                    m_path.back ( ) = child;\n                }\n            }\n            return best_child_move;\n        }\n\n\n        // Adding the move of the opponent to the path (and possibly to the tree).\n        void connectStatesPath ( const State & state_ ) noexcept {\n            const NodeID parent = m_path.back ( ).target; NodeID child = getNode ( state_.zobrist ( ) );\n            if ( Tree::NodeID::invalid == child ) {\n                child = addNode ( parent, state_ ).target;\n            }\n            m_path.push ( m_tree.link ( parent, child ) );\n            ++m_path_size;\n        }\n\n\n        [[ nodiscard ]] Move compute ( const State & state_, index_t max_iterations_ ) noexcept {\n\n            // constexpr std::int32_t threshold = 5;\n\n            if ( m_not_initialized ) {\n                initialize ( state_ );\n            }\n            else {\n                connectStatesPath ( state_ );\n            }\n\n            // const Player player = state_.playerToMove ( );\n            // if ( player == Player::Type::agent ) {\n                // m_path.print ( );\n            // }\n\n            // max_iterations_ -= m_tree.nodeNum ( );\n\n            while ( max_iterations_-- > 0 ) {\n                NodeID node = m_tree.root_node;\n                State state ( state_ );\n                // Select a path through the tree to a leaf node.\n                while ( hasNoUntriedMoves ( node ) and hasChildren ( node ) ) {\n                    // UCT is only applied in nodes of which the visit count\n                    // is higher than a certain threshold T\n                    Link child = selectChildUCT ( node );\n                    state.move_hash ( m_tree [ child.arc ].m_move );\n                    m_path.push ( child );\n                    node = child.target;\n                }\n\n                /*\n\n                static int cnt = 0;\n\n                if ( state != m_tree [ node ].m_state ) {\n                    state.print ( );\n                    m_tree [ node ].m_state.print ( );\n                    ++cnt;\n                    if ( cnt == 100 ) exit ( 0 );\n                }\n\n                */\n\n                // If we are not already at the final state, expand the tree with a new\n                // node and move there.\n\n                // In addition to expanding one node per simulated game, we also expand all the\n                // children of a node when a node's visit count equals T\n\n                if ( hasUntriedMoves ( node ) ) {\n                    // if ( player == Player::Type::agent and m_tree [ node ].m_visits < threshold )\n                    state.move_hash_winner ( getUntriedMove ( node ) ); // State update.\n                    m_path.push ( addChild ( node, state ) );\n                }\n\n                // The player in back of path is player ( the player to move ).We now play\n                // randomly until the game ends.\n\n                // if ( player == Player::Type::human ) {\n                    // state.simulate ( );\n                    // for ( Link & link : m_path ) {\n                        // We have now reached a final state. Backpropagate the result up the\n                        // tree to the root node.\n                        // updateData ( link, state );\n                    // }\n                // }\n\n                // else {\n\n                for ( index_t i = 0; i < 3; ++i ) {\n                    State sim_state ( state );\n                    sim_state.simulate ( );\n                    // We have now reached a final state. Backpropagate the result up the\n                    // tree to the root node.\n                    for ( Link & link : m_path ) {\n                        updateData ( link, sim_state );\n                    }\n                }\n                // }\n                m_path.resize ( m_path_size );\n            }\n            return getBestMove ( );\n        }\n\n        private:\n\n        void prune_impl ( Mcts * new_mcts_, const State & state_ ) noexcept {\n            using Visited = typename Tree::Visited; // New m_nodes by old_index.\n            using Stack = typename Tree::Stack;\n            // Prune Tree.\n            const NodeID old_node = getNode ( state_.zobrist ( ) );\n            Tree & new_tree = new_mcts_->m_tree;\n            new_tree [ new_tree.root_node ] = std::move ( m_tree [ old_node ] );\n            // The Visited-vector stores the new NodeID's indexed by old NodeID's,\n            // old NodeID's not present in the new tree have a value of NodeID::invalid.\n            static Visited visited;\n            visited.clear ( );\n            visited.resize ( m_tree.nodesSize ( ), Tree::NodeID::invalid );\n            visited [ old_node.value ] = new_tree.root_node;\n            static Stack stack;\n            stack.clear ( );\n            stack.push_back ( old_node );\n            while ( stack.size ( ) ) {\n                const NodeID parent = stack.back ( ); stack.pop_back ( );\n                for ( OutIt a { m_tree, parent }; a.is_valid ( ); ++a ) {\n                    const NodeID child { a->target };\n                    if ( Tree::NodeID::invalid == visited [ child.value ] ) { // Not visited yet.\n                        visited [ child.value ] = new_tree.addNode ( std::move ( m_tree [ child ] ) );\n                        stack.push_back ( child );\n                    }\n                    new_tree.addArc ( visited [ parent.value ], visited [ child.value ], std::move ( m_tree [ a.id ( ) ] ) );\n                }\n            }\n            // Purge TransitionTable.\n            auto it = m_transposition_table->begin ( );\n            const auto it_cend = m_transposition_table->cend ( );\n            while ( it != it_cend ) {\n                const auto tmp_it = it;\n                ++it;\n                const NodeID new_node = visited [ tmp_it->second.value ];\n                if ( Tree::NodeID::invalid == new_node ) {\n                    m_transposition_table->erase ( tmp_it );\n                }\n                else {\n                    tmp_it->second = new_node;\n                }\n            }\n            // Transfer TranspositionTable.\n            new_mcts_->m_transposition_table.reset ( m_transposition_table.take ( ) );\n            // Has been initialized.\n            new_mcts_->m_not_initialized = false;\n            // Reset path.\n            new_mcts_->m_path.reset ( new_tree.root_arc, new_tree.root_node );\n            new_mcts_->m_path_size = 1;\n        }\n\n        public:\n\n        static void prune ( Mcts * & mcts_, const State & state_ ) noexcept {\n            Mcts * pruned_mcts = new Mcts ( );\n            if ( not ( mcts_->m_not_initialized ) and Mcts::Tree::NodeID::invalid != mcts_->getNode ( state_.zobrist ( ) ) ) {\n                // The state exists in the tree and it's not the current\n                // root_node, i.e. now prune.\n                mcts_->prune_impl ( pruned_mcts, state_ );\n            }\n            else {\n                mcts_->initialize ( state_ );\n            }\n            std::swap ( mcts_, pruned_mcts );\n            delete pruned_mcts;\n        }\n\n\n        static void reset ( Mcts * & mcts_, const State & state_ ) noexcept {\n            if ( not ( mcts_->m_not_initialized ) ) {\n                const Mcts::NodeID new_root_node = mcts_->getNode ( state_.zobrist ( ) );\n                if ( Mcts::Tree::NodeID::invalid != new_root_node ) {\n                    // The state exists in the tree and it's not the current\n                    // root_node, i.e. re-hang the tree.\n                    mcts_->m_tree.root_node = new_root_node;\n                }\n                else {\n                    std::cout << \"new tree\\n\";\n                    Mcts * new_mcts = new Mcts ( );\n                    new_mcts->initialize ( state_ );\n                    std::swap ( mcts_, new_mcts );\n                    delete new_mcts;\n                }\n            }\n        }\n\n\n        [[ nodiscard ]] InverseTranspositionTable invertTranspositionTable ( ) const noexcept {\n            InverseTranspositionTable itt ( m_transposition_table->size ( ) );\n            for ( auto & e : * m_transposition_table ) {\n                itt [ e.second.value ] = e.first;\n            }\n            return itt;\n        }\n\n\n        static void merge ( Mcts * & t_mcts_, Mcts * & s_mcts_ ) {\n            // Same pointer, do nothing.\n            if ( t_mcts_ == s_mcts_ ) {\n                return;\n            }\n            // t_mcts_ (target) becomes the largest tree, we're merging the smaller tree (source) into the larger tree.\n            if ( t_mcts_->m_tree.nodeNum ( ) < s_mcts_->m_tree.nodeNum ( ) ) {\n                std::swap ( t_mcts_, s_mcts_ );\n            }\n            // Avoid some levels of indirection and make things clearer.\n            Tree & t_t = t_mcts_->m_tree, & s_t = s_mcts_->m_tree; // target tree, source tree.\n            TranspositionTable & t_tt = * t_mcts_->m_transposition_table; // target transposition table.\n            InverseTranspositionTable s_itt { s_mcts_->invertTranspositionTable ( ) }; // source inverse transposition table.\n            // bfs help structures.\n            using Visited = boost::dynamic_bitset<>;\n            using Queue = Queue<NodeID>;\n            Visited s_visited { s_t.nodeNum ( ) };\n            Queue s_queue { { s_t.root_node } };\n            s_visited [ s_t.root_node.value ] = true;\n            // Walk the tree, breadth first.\n            while ( s_queue.not_empty ( ) ) {\n                // The t_source (target parent) does always exist, as we are going at it breadth first.\n                const NodeID s_source = s_queue.pop ( ), t_source = t_tt.find ( s_itt [ s_source.value ] )->second;\n                // Iterate over children (targets) of the parent (source).\n                for ( OutIt soi { s_t, s_source }; soi.is_valid ( ); ++soi ) { // Source Out Iterator (soi).\n                    const Link s_link = s_t.link ( soi );\n                    if ( not ( s_visited [ s_link.target.value ] ) ) {\n                        s_visited [ s_link.target.value ] = true;\n                        s_queue.push ( s_link.target );\n                        // Now do something. If child in s_mcts_ doesn't exist in t_mcts_, add child.\n                        const auto t_it = t_tt.find ( s_itt [ s_link.target.value ] );\n                        if ( t_it != t_tt.cend ( ) ) { // Child exists. The arc does or does not exist.\n                            // NodeID t_it->second corresponds to NodeID target child.\n                            const Link t_link ( t_t.link ( t_source, t_it->second ) );\n                            if ( Tree::ArcID::invalid != t_link.arc ) { // The arc does exist.\n                                t_t [ t_link.arc.value ] += s_t [ s_link.arc.value ];\n                            }\n                            else { // The arc does not exist.\n                                t_t [ t_t.addArc ( t_source, t_link.target ).arc.value ] = std::move ( s_t [ s_link.arc.value ] );\n                            }\n                            // Update the values of the target.\n                            t_t [ t_link.target.value ] += s_t [ s_link.target.value ];\n                        }\n                        else { // Child does not exist.\n                            const Link t_link = t_t.addNode ( t_source );\n                            // m_tree.\n                            t_t [ t_link.arc.value    ] = std::move ( s_t [ s_link.arc.value    ] );\n                            t_t [ t_link.target.value ] = std::move ( s_t [ s_link.target.value ] );\n                            // m_transposition_table.\n                            t_tt.emplace ( s_itt [ s_link.target.value ], t_link.target );\n                        }\n                    }\n                }\n            }\n            t_mcts_->m_path.resize ( 1 );\n            t_mcts_->m_path_size = 1;\n            delete s_mcts_; // Destruct the smaller tree.\n            s_mcts_ = nullptr;\n        }\n\n\n        std::size_t numTranspositions ( ) const noexcept {\n            std::size_t nt = 0;\n            using Visited = boost::dynamic_bitset<>;\n            using Stack = Stack<NodeID>;\n            Visited visited { m_tree.nodeNum ( ) };\n            Stack stack { m_tree.root_node };\n            visited [ m_tree.root_node.value ] = true;\n            while ( stack.not_empty ( ) ) {\n                const NodeID parent = stack.pop ( );\n                for ( OutIt a { m_tree, parent }; a.is_valid ( ); ++a ) {\n                    const NodeID child = a->target;\n                    if ( not ( visited [ child.value ] ) ) {\n                        visited [ child.value ] = true;\n                        stack.push ( child );\n                        if ( m_tree.inArcNum ( child ) > 1 ) {\n                            ++nt;\n                        }\n                    }\n                }\n            }\n            return nt;\n        }\n\n    private:\n\n        friend class cereal::access;\n\n        template < class Archive >\n        void save ( Archive & ar_ ) const noexcept {\n            ar_ ( m_tree, * m_transposition_table, m_not_initialized );\n        }\n\n        template < class Archive >\n        void load ( Archive & ar_ ) noexcept {\n            m_tree.clearUnsafe ( );\n            if ( m_transposition_table.get ( ) == nullptr ) {\n                m_transposition_table.reset ( new TranspositionTable ( ) );\n            }\n            else {\n                m_transposition_table->clear ( );\n            }\n            ar_ ( m_tree, * m_transposition_table, m_not_initialized );\n            m_path.reset ( m_tree.root_arc, m_tree.root_node );\n            m_path_size = 1;\n        }\n    };\n\n\n    template<typename State>\n    void compute ( State & state_, index_t max_iterations_ ) noexcept {\n        Mcts<State> * mcts = new Mcts<State> ( );\n        state_.move_hash_winner ( mcts->compute ( state_, max_iterations_ ) );\n        delete mcts;\n    }\n}\n", "meta": {"hexsha": "bac5b33aed246894e68accdc38a62391c54b3f86", "size": 32373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mcts/mcts.hpp", "max_stars_repo_name": "degski/MCTSConnectFour", "max_stars_repo_head_hexsha": "cf84afd4053b04239836f74d43341fb287ce1938", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mcts/mcts.hpp", "max_issues_repo_name": "degski/MCTSConnectFour", "max_issues_repo_head_hexsha": "cf84afd4053b04239836f74d43341fb287ce1938", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcts/mcts.hpp", "max_forks_repo_name": "degski/MCTSConnectFour", "max_forks_repo_head_hexsha": "cf84afd4053b04239836f74d43341fb287ce1938", "max_forks_repo_licenses": ["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.0036144578, "max_line_length": 207, "alphanum_fraction": 0.51774627, "num_tokens": 7277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370636758849891, "lm_q2_score": 0.033085978627057866, "lm_q1q2_score": 0.007732403883040404}}
{"text": "/*\nDeterministic Bayesian Sparse Linear Mixed Model (DBSLMM)\nCopyright (C) 2019  Sheng Yang and Xiang Zhou\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <map>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <bitset>\n#include <numeric>\n#include <time.h>\n#include <math.h>\n#include <sys/time.h>\n#include <cctype>\n#include <boost/math/distributions/students_t.hpp>\n\n#include <armadillo>\n\n#include \"../include/dtpr.hpp\"\n\nusing namespace std;\nusing namespace arma;\n// input block information\nint IO::readBlock(string infile, char *separator, vector <BLOCK> &block){\n\n\tint block_num = getRow(infile);\n\tblock.resize(block_num);\n\tstring oneblock, element;\n\tifstream file_stream(infile.c_str());\n\tint block_count = 0; \n\twhile (getline(file_stream, oneblock)) {\n\t\tvector<string> block_str;\n\t\tstringstream oneblock_stream(oneblock);\n\t\twhile (getline(oneblock_stream, element, *separator))\n\t\t\tblock_str.push_back(element);\n\t\tblock[block_count].chr = block_str[0]; \n\t\tblock[block_count].start = atol(block_str[1].c_str());\n\t\tblock[block_count].end = atol(block_str[2].c_str()); \n\t\tblock_count++;\n\t}\n\tfile_stream.close();\n\treturn 0;\n}\n\n// get row number\nint IO::getRow(string infile){\n\t\n\tint n_row = 0;\n\tstring row;\n\tifstream file_stream(infile.c_str());\n\twhile (getline(file_stream, row))\n\t\tn_row++;\n\tfile_stream.close();\n\treturn n_row;\n}\n\n// input bim data\nint IO::readBim(int n_ref, string ref_str, char *separator, map<string, ALLELE> &bim, bool constr){\n\t\n\tstring bed_str = ref_str + \".bed\", bim_str = ref_str + \".bim\";\n\tifstream bim_stream(bim_str.c_str());\n\tint n_snp = getRow(bim_str);\n\tvec maf = zeros<vec>(n_snp); \n\tif (constr == true){\n\t\tifstream bed_stream(bed_str);\n\t\tcout << \"Calculating MAF of reference panel ...\" << endl;\n\t\tvector<int> idv(n_ref); \n\t\tfor (int i = 0; i < n_ref; i++) idv[i] = 1; \n\t\tfor (int i = 0; i < n_snp; i++){\n\t\t\tvec geno = zeros<vec>(n_ref); \n\t\t\treadSNPIm(i, n_ref, idv, bed_stream, geno, maf(i));\n\t\t}\n\t\tbed_stream.close();\n\t} else {\n\t\tcout << \"[WARNING] Do not consider the difference between reference panel and summary data ...\" << endl;\n\t}\n\t\n\tstring snp, elem;\n\tint count = 0;\n\twhile (getline(bim_stream, snp)) {\n\t\tvector<string> snp_vec;\n\t\tALLELE allele; \n\t\tstringstream snp_stream(snp);\n\t\twhile (getline(snp_stream, elem, *separator)) snp_vec.push_back(elem);\n\t\tallele.pos = count; \n\t\tallele.a1 = snp_vec[4];\n\t\tallele.a2 = snp_vec[5];\n\t\tallele.maf = maf(count);\n\t\tbim.insert(pair<string, ALLELE>(snp_vec[1], allele));\n\t\tcount++; \n\t}\n\tbim_stream.close();\n\treturn 0;\n}\n\n// input bim data\nint IO::readBim(int n_ref, string ref_str, char *separator, map<string, ALLELEB> &bim, bool constr){\n\t\n\tstring bed_str = ref_str + \".bed\", bim_str = ref_str + \".bim\";\n\tifstream bim_stream(bim_str.c_str());\n\tint n_snp = getRow(bim_str); \n\tvec maf = zeros<vec>(n_snp);\n\tif (constr == true){\n\t\tifstream bed_stream(bed_str);\n\t\tcout << \"Calculating MAF of reference panel ...\" << endl;\n\t\tvector<int> idv(n_ref); \n\t\tfor (int i = 0; i < n_ref; i++) idv[i] = 1; \n\t\tfor (int i = 0; i < n_snp; i++){\n\t\t\tvec geno = zeros<vec>(n_ref); \n\t\t\treadSNPIm(i, n_ref, idv, bed_stream, geno, maf(i));\n\t\t}\n\t\tbed_stream.close();\n\t} else {\n\t\tcout << \"[WARNING] Do not consider the difference between reference panel and external summary data ...\" << endl;\n\t}\n\tstring snp, elem;\n\tint count = 0;\n\twhile (getline(bim_stream, snp)) {\n\t\tvector<string> snp_vec;\n\t\tALLELEB alleleb; \n\t\tstringstream snp_stream(snp);\n\t\twhile (getline(snp_stream, elem, *separator)) snp_vec.push_back(elem);\n\t\talleleb.pos = count; \n\t\talleleb.ps = atoi(snp_vec[3].c_str());\n\t\talleleb.a1 = snp_vec[4];\n\t\talleleb.a2 = snp_vec[5];\n\t\talleleb.maf = maf(count);\n\t\tbim.insert(pair<string, ALLELEB>(snp_vec[1], alleleb));\n\t\tcount++; \n\t}\n\tbim_stream.close();\n\treturn 0;\n}\n\n// calculate P value from GEMMA output\ndouble IO::calP(double beta, double se, int sampleSize){\n\tdouble t = beta / se;\n\tboost::math::students_t tDis(sampleSize);\n\tdouble p = 2 * cdf(complement(tDis, fabs(t)));\n\treturn p;\n}\n\n\n// input summary data\nint IO::readSumm(string summ_str, char *separator, vector<SUMM > &summ){\n\n\tstring snp, element, chr_str;\n\tifstream summ_stream(summ_str.c_str());\n\n\tint num = getRow(summ_str);\n\t// read the summary data of specific chromosome\n\tsumm.resize(num);\n\tint summ_count = 0; \n\twhile (getline(summ_stream, snp)){\n\t\tvector<string> snp_summ;\n\t\tstringstream summ_stream(snp);\n\t\twhile (getline(summ_stream, element, *separator)) \n\t\t\tsnp_summ.push_back(element);\n\t\tdouble P = atof(snp_summ[10].c_str()); \n\t\tdouble se, sei;\n\t\tif (isdigit(snp_summ[9].c_str()[0])){\n\t\t\tse = atof(snp_summ[9].c_str());\n\t\t\tif (se - 0.0 > 1e-20){\n\t\t\t\tsumm[summ_count].z = atof(snp_summ[8].c_str()) / se;\n\t\t\t\tsumm[summ_count].P = calP(atof(snp_summ[8].c_str()), se, atoi(snp_summ[4].c_str()));\n\t\t\t} else {\n\t\t\t\tsumm[summ_count].z = 0; \n\t\t\t\tsumm[summ_count].P = 1;\n\t\t\t}\n\t\t} else {\n\t\t\tsumm[summ_count].z = 0; \n\t\t\tsumm[summ_count].P = 1;\n\t\t}\n\t\tsumm[summ_count].chr = atoi(snp_summ[0].c_str());\n\t\tsumm[summ_count].snp = snp_summ[1];\n\t\tsumm[summ_count].ps = atol(snp_summ[2].c_str());\n\t\tsumm[summ_count].a1 = snp_summ[5].c_str();\n\t\tsumm[summ_count].a2 = snp_summ[6].c_str();\n\t\tdouble af = atof(snp_summ[7].c_str());\n\t\tsumm[summ_count].maf = min(af, 1.0 - af);\n\t\tsumm_count++; \n\t\n\t}\n\tsumm_stream.close();\n\t\n\treturn summ_count;\n}\n\n// input DBSLMM result\nint IO::readDBSLMM(string summ_str, char *separator, vector<SUMMS> &summ){\n\n\tstring snp, element, chr_str;\n\tifstream summ_stream(summ_str.c_str());\n\n\tint num = getRow(summ_str);\n\t// read the summary data of specific chromosome\n\tsumm.resize(num);\n\tint summ_count = 0; \n\twhile (getline(summ_stream, snp)){\n\t\tvector<string> snp_summ;\n\t\tstringstream summ_stream(snp);\n\t\twhile (getline(summ_stream, element, *separator)) \n\t\t\tsnp_summ.push_back(element);\n\t\tsumm[summ_count].snp = snp_summ[0];\n\t\tsumm[summ_count].a1 = snp_summ[1].c_str();\n\t\tsumm[summ_count].z = atof(snp_summ[2].c_str());\n\t\tsumm_count++; \n\t}\n\tsumm_stream.close();\n\t\n\treturn summ_count;\n}\n\n// input external result (summary statistics)\nint IO::readExt(string summ_str, char *separator, map<string, SUMMS> &summ){\n\n\tstring snp, element, chr_str;\n\tifstream summ_stream(summ_str.c_str());\n\n\t// read the summary data of specific chromosome\n\tint summ_count = 0; \n\twhile (getline(summ_stream, snp)){\n\t\tvector<string> snp_summ;\n\t\tSUMMS summs; \n\t\tstringstream summ_stream(snp);\n\t\twhile (getline(summ_stream, element, *separator)) \n\t\t\tsnp_summ.push_back(element); \n\t\tsumms.snp = snp_summ[0]; \n\t\tsumms.a1 = snp_summ[1]; \n\t\tsumms.maf = atof(snp_summ[2].c_str()); \n\t\tsumms.z = atof(snp_summ[3].c_str()); \n\t\tsumm.insert(pair<string, SUMMS>(snp_summ[0], summs)); \n\t}\n\tsumm_stream.close();\n\t\n\treturn summ_count;\n}\n\n// input genotype data\n// modify from GEMMA, Xiang Zhou et al.\nvoid IO::readSNPIm(const int pos, int ni_test, const vector<int> &indicator_idv, ifstream &infile, vec &geno, double &maf) {\n\n\t// debug_msg(\"entered\");\n\tsize_t ni_total = indicator_idv.size(), n_bit;\n\tif (ni_total % 4 == 0) {\n\t\tn_bit = ni_total / 4;\n\t}\n\telse {\n\t\tn_bit = ni_total / 4 + 1;\n\t}\n\n\t// n_bit, and 3 is the number of magic numbers.\n\tinfile.seekg(pos * n_bit + 3);\n\n\t// Read genotypes.\n\tchar ch[1];\n\tbitset<8> b;\n\t\n\tdouble geno_mean = 0.0;\n\tsize_t c = 0, c_idv = 0;\n\tvector<size_t> geno_miss;\n\tint freq[3];\n\tfreq[0] = freq[1] = freq[2] = 0;\n\tfor (size_t i = 0; i < n_bit; ++i) {\n\t\tinfile.read(ch, 1);\n\t\tb = ch[0];\n\n\t\t// Minor allele homozygous: 2.0; major: 0.0.\n\t\tfor (size_t j = 0; j < 4; ++j) {\n\t\t\tif ((i == (n_bit - 1)) && c == ni_total) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (indicator_idv[c] == 0) {\n\t\t\t\tc++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tc++;\n\n\t\t\tif (b[2 * j] == 0) {\n\t\t\t\tif (b[2 * j + 1] == 0) {\n\t\t\t\t\tgeno(c_idv) = 2.0;\n\t\t\t\t\tgeno_mean += 2.0;\n\t\t\t\t\tfreq[2]++;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tgeno(c_idv) = 1.0;\n\t\t\t\t\tgeno_mean += 1.0;\n\t\t\t\t\tfreq[1]++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (b[2 * j + 1] == 1) {\n\t\t\t\t\tgeno(c_idv) = 0.0;\n\t\t\t\t\tgeno_mean += 0.0;\n\t\t\t\t\tfreq[0]++; \n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tgeno_miss.push_back(c_idv);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc_idv++;\n\t\t}\n\t}\n\t// max imputation\n\t// int imp_val = distance(freq, max_element(freq, freq + 3));\n\t// mean imputation\n\tgeno_mean /= (double)(c_idv - geno_miss.size());\n\tfor (size_t i = 0; i < geno_miss.size(); ++i) \n\t\tgeno(geno_miss[i]) = geno_mean;\n\tdouble af = 0.5 * sum(geno) / geno.n_elem; \n\tmaf = min(af, 1.0 - af);\n\treturn ;\n}\n\ndouble IO::getWalltime(){\n    struct timeval time;\n    if (gettimeofday(&time,NULL)){\n        //  Handle error\n        return 0;\n    }\n    return (double)time.tv_sec + (double)time.tv_usec * .000001;\n}\n\nvoid SNPPROC::nomalizeVec(vec &x) {\n\t\n\tx -= mean(x); \n\tx /= stddev(x);\n\treturn;\n}\n\n// match summary result and reference panel\nint SNPPROC::matchRef(vector<SUMM> summ, map<string, ALLELE> bim, vector<POS> &inter_snp, double mafMax, bool *badsnp_bool) {\n\t\n\tint dis_count = 0, maf_count = 0; \n\tfor (size_t i = 0; i < summ.size(); ++i) {\n\t\tbool a1_bool = bim[summ[i].snp].a1 == summ[i].a1; \n\t\tbool a2_bool = bim[summ[i].snp].a2 == summ[i].a2; \n\t\tbool maf_bool = fabs(bim[summ[i].snp].maf - summ[i].maf) < mafMax; \n\t\tif (a1_bool == false || a2_bool == false) dis_count++; \n\t\tif (maf_bool == false) maf_count++;\n\t\tif (a1_bool == true && a2_bool == true && maf_bool == true && bim.find(summ[i].snp) != bim.end()){\n\t\t\tPOS s_summ; \n\t\t\ts_summ.snp = summ[i].snp; \n\t\t\ts_summ.ps = summ[i].ps; \n\t\t\ts_summ.pos = bim[summ[i].snp].pos; \n\t\t\ts_summ.a1 = summ[i].a1; \n\t\t\ts_summ.maf = summ[i].maf; \n\t\t\ts_summ.z = summ[i].z; \n\t\t\ts_summ.P = summ[i].P;\n\t\t\tinter_snp.push_back(s_summ);\n\t\t\tbadsnp_bool[i] = true;\n\t\t}\n\t}\n\tcout << \"Number of allele discrepency: \" << dis_count << endl;\n\tcout << \"Number of maf discrepency:    \" << maf_count << endl;\n\treturn 0;\n}\n\n// match external summary statistics to DBSLMM result\nint SNPPROC::matchSumm(vector<SUMMS> summ, map<string, SUMMS> summE, vector<SUMMC> &summC) {\n\t\n\tint dis_count = 0; \n\tfor (size_t i = 0; i < summ.size(); ++i) {\n\t\tif (summE.find(summ[i].snp) != summE.end()){\n\t\t\tSUMMC summc; \n\t\t\tsummc.snp = summE[summ[i].snp].snp;\n\t\t\tsummc.a1 = summ[i].a1; \n\t\t\tsummc.maf = summE[summ[i].snp].maf;\n\t\t\tsummc.z1 = summ[i].z; \n\t\t\tbool a1_bool = summE[summ[i].snp].a1 == summ[i].a1;\n\t\t\tif (a1_bool == false) dis_count++; \n\t\t\tif (a1_bool == true){\n\t\t\t\tsummc.z2 = summE[summ[i].snp].z; \n\t\t\t} else {\n\t\t\t\tsummc.z2 = -summE[summ[i].snp].z; \n\t\t\t}\n\t\t\tsummC.push_back(summc); \n\t\t}\n\t}\n\tcout << \"Number of allele discrepency: \" << dis_count << endl;\n\treturn 0; \n}\n\n// match DBSLMM result, external summary statistics and bim file\nint SNPPROC::matchAll(vector <SUMMC> summI, map<string, ALLELEB> bim, double mafMax, vector <SUMMP> &summO) {\n\t\n\tfor (size_t i = 0; i < summI.size(); ++i) {\n\t\tbool a1_bool = bim[summI[i].snp].a1 == summI[i].a1;\n\t\tbool maf_bool = fabs(bim[summI[i].snp].maf - summI[i].maf) < mafMax; \n\t\tif (a1_bool == true && maf_bool == true && bim.find(summI[i].snp) != bim.end()){\n\t\t\tSUMMP summp; \n\t\t\tsummp.ps = bim[summI[i].snp].ps; \n\t\t\tsummp.pos = bim[summI[i].snp].pos; \n\t\t\tsummp.snp = summI[i].snp; \n\t\t\tsummp.z1 = summI[i].z1; \n\t\t\tsummp.z2 = summI[i].z2; \n\t\t\tsummO.push_back(summp); \n\t\t}\n\t}\n\tsort(summO.begin(), summO.end(), sortPS);\n\treturn 0; \n}\n\nint SNPPROC::addBlock(vector<POS> summ, vector <BLOCK> block, vector<INFO> &pos_block){\n\t\n\tint num_block = block.size();\n\tint count = 0; \n\tpos_block.resize(summ.size());\n\tfor (int i = 0; i < num_block; i++){\n\t\tint start = block[i].start;\n\t\tint end = block[i].end;\n\t\t// cout << i << \" \" << begin << \" \" << end << endl;\n\t\tfor (size_t j = count; j < summ.size(); j++){\n\t\t\tif (summ[j].ps >= start && summ[j].ps < end) { \n\t\t\t\tpos_block[j].snp = summ[j].snp;\n\t\t\t\tpos_block[j].block = i; \n\t\t\t\tpos_block[j].ps = summ[j].ps; // snp position\n\t\t\t\tpos_block[j].pos = summ[j].pos; // bim file position\n\t\t\t\tpos_block[j].a1 = summ[j].a1;\n\t\t\t\tpos_block[j].maf = summ[j].maf;\n\t\t\t\tpos_block[j].P = summ[j].P;\n\t\t\t\tpos_block[j].z = summ[j].z;\n\t\t\t\tcount++;\n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn num_block; \n}\n\nbool sortP(const INFO &snpinfo1, const INFO &snpinfo2){\n\treturn snpinfo1.P < snpinfo2.P;\n}\n\nbool sortPOS(const INFO &snpinfo1, const INFO &snpinfo2){\n\treturn snpinfo1.pos < snpinfo2.pos;\n}\n\nbool sortPS(const SUMMP &summp1, const SUMMP &summp2)\n{\n\treturn summp1.ps < summp2.ps;\n}\n\n\nvoid printProgBar(int percent) {\n\tstring bar;\n\tfor (int i = 0; i < 50; i++) {\n\t\tif (i < (percent / 2)) {\n\t\t\tbar.replace(i, 1, \"=\");\n\t\t}\n\t\telse if (i == (percent / 2)) {\n\t\t\tbar.replace(i, 1, \">\");\n\t\t}\n\t\telse {\n\t\t\tbar.replace(i, 1, \" \");\n\t\t}\n\t}\n\n\tcout << \"\\r\" \"[\" << bar << \"] \";\n\tcout.width(3);\n\tcout << percent << \"%     \" << std::flush;\n}\n\n\n\n", "meta": {"hexsha": "85d947f006968482b498d4346ef2cf5b9a927d5f", "size": 13100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dtpr.cpp", "max_stars_repo_name": "fboehm/DBSLMMread", "max_stars_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dtpr.cpp", "max_issues_repo_name": "fboehm/DBSLMMread", "max_issues_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dtpr.cpp", "max_forks_repo_name": "fboehm/DBSLMMread", "max_forks_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_forks_repo_licenses": ["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.0103092784, "max_line_length": 125, "alphanum_fraction": 0.6395419847, "num_tokens": 4434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208212878370535, "lm_q2_score": 0.024053552588347283, "lm_q1q2_score": 0.0077168917184498665}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <fstream>\n#include <conio.h>\n#include <boost/program_options.hpp>\n#include \"input_data.h\"\n\nnamespace po = boost::program_options;\nusing namespace std;\n\nstruct ParamIsNotSet {\n    std::string param;\n    ParamIsNotSet (std::string param)\n        : param(param)\n    {}\n};\n\nstruct ParamIsNotPositive {\n    std::string param;\n    ParamIsNotPositive (std::string param)\n        : param(param)\n    {}\n};\n\nvoid print_error (const string msg)\n{\n    cerr << msg << \"\\n\";\n    getch();\n    exit(1);\n}\n\nvoid get_double_param (const po::variables_map& vm, const char* param,\n    double& val)\n{\n    if (vm.count(param))\n        val = vm[param].as<double>();\n    else\n        throw ParamIsNotSet(param);\n}\n\nvoid get_pos_double_param (po::variables_map& vm, const char* param,\n    double& val)\n{\n    if (vm.count(param)) {\n        val = vm[param].as<double>();\n        if (val < 0)\n            throw ParamIsNotPositive(param);\n    }\n    else\n        throw ParamIsNotSet(param);\n}\n\nvoid get_int_param (const po::variables_map& vm, const char* param, int& val)\n{\n    if (vm.count(param)) {\n        val = vm[param].as<int>();\n        if (val < 0)\n            throw ParamIsNotPositive(param);\n    }\n    else\n        throw ParamIsNotSet(param);\n}\n\nvoid get_string_param (const po::variables_map& vm, const char* param,\n    string& val)\n{\n    if (vm.count(param))\n        val = vm[param].as<string>();\n    else\n        throw ParamIsNotSet(param);\n}\n\ntemplate <typename T>\nstd::string toString (T val)\n{\n    std::ostringstream oss;\n    oss << val;\n    return oss.str();\n}\n\nextern \"C\" FILE* popen(const char* command, const char* mode);\nextern \"C\" int pclose(FILE* stream);\n\n// call program cmd with arguments len num arg\n// len - length of the interval, (num + 1) - number of grid points\n// ans - values of the function in the grid points\nvoid calc_fun (string cmd, string arg, double len, int num, vector<double>& ans)\n{\n    string arg1 = toString(len) + \" \" + toString(num);\n    string full_cmd = cmd + \" \" + arg1 + \" \" + arg;\n    cout << full_cmd << endl;\n    FILE* pf = popen(full_cmd.c_str(), \"r\");\n    ans.resize(num + 1);\n    for (int i = 0; i <= num; ++i)\n        fscanf(pf, \"%lf\", &ans[i]);\n    pclose(pf);\n}\n\nInputData::InputData (string input_file_name)\n{\n    try {\n        po::options_description desc(\"Input data\");\n        desc.add_options()\n            (\"L\", po::value<double>(), \"Length of the space interval\")\n            (\"T\", po::value<double>(), \"Length of the time interval\")\n            (\"a\", po::value<double>(), \"Diffusion coefficient a\")\n            (\"alpha\", po::value<double>(), \"Diffusion coefficient alpha\")\n            (\"kappa_a\", po::value<double>(), \"Coefficient kappa_a\")\n            (\"b\", po::value<double>(), \"Coefficient b\")\n            (\"beta\", po::value<double>(), \"Coefficient beta (in BC)\")\n            (\"gamma\", po::value<double>(), \"Coefficient gamma (in BC)\")\n            (\"theta_b1\", po::value<double>(), \"Boundary temperature theta_b1\")\n            (\"theta_b2\", po::value<double>(), \"Boundary temperature theta_b2\")\n            (\"mode\", po::value<string>(),\n                \"Mode: whether q(t) or r(t) is given (given_q or given_r)\")\n            (\"q_init_guess\", po::value<double>(),\n                \"Initial guess in the bisection method\")\n            (\"q_init_len\", po::value<double>(),\n                \"Initial length of the interval in the bisection method\")\n            (\"q_tol\", po::value<double>(), \"Tolerance in the bisection method\")\n            (\"verify_monotonicity\", po::value<string>(),\n                \"Verify monotonicity (on or off)\")\n            (\"monot_ver_q_1\", po::value<double>(),\n                \"Left bound of the range of the monotonicity verification\")\n            (\"monot_ver_q_2\", po::value<double>(),\n                \"Right bound of the range of the monotonicity verification\")\n            (\"monot_ver_q_step\", po::value<double>(),\n                \"Step of the monotonicity verification\")\n            (\"N\", po::value<int>(), \"Number of space grid points\")\n            (\"M\", po::value<int>(), \"Number of time grid points\")\n            (\"theta_0_fun_cmd\", po::value<string>(), \"Command theta_0\")\n            (\"theta_0_fun_arg\", po::value<string>(), \"Arguments of theta_0\")\n            (\"f_fun_cmd\", po::value<string>(), \"Command f\")\n            (\"f_fun_arg\", po::value<string>(), \"Arguments of f\")\n            (\"g_fun_cmd\", po::value<string>(), \"Command g\")\n            (\"g_fun_arg\", po::value<string>(), \"Arguments of g\")\n            (\"q_fun_cmd\", po::value<string>(), \"Command q\")\n            (\"q_fun_arg\", po::value<string>(), \"Arguments of q\")\n            (\"r_fun_cmd\", po::value<string>(), \"Command r\")\n            (\"r_fun_arg\", po::value<string>(), \"Arguments of r\")\n            (\"fd_scheme\", po::value<string>(),\n                \"Finite difference scheme (E - Euler or CN - Crank-Nicolson)\")\n            (\"linear_sys_sol_method\", po::value<string>(),\n                \"Linear system solution method (m - MTL or u - UMFPACK)\")\n            (\"Newton_tol\", po::value<double>(), \"Tolerance in Newton's method\")\n            (\"linear_sys_tol\", po::value<double>(),\n                \"Tolerance in the linear system solution method\")\n            (\"divided_start_steps\", po::value<int>(),\n                \"Number of start time steps which are to be divided\")\n            (\"start_substeps\", po::value<int>(),\n                \"Number of substeps in the start time steps\")\n        ;\n        po::variables_map vm;\n        ifstream ifs(input_file_name.c_str());\n        if (!ifs)\n            print_error(\"Can not open input file: \" + input_file_name);\n        else {\n            po::store(parse_config_file(ifs, desc), vm);\n            po::notify(vm);\n        }\n        get_pos_double_param(vm, \"L\", L);\n        get_pos_double_param(vm, \"T\", T);\n        get_pos_double_param(vm, \"a\", a);\n        get_pos_double_param(vm, \"alpha\", alpha);\n        get_pos_double_param(vm, \"kappa_a\", kappa_a);\n        get_pos_double_param(vm, \"b\", b);\n        get_pos_double_param(vm, \"beta\", beta);\n        get_pos_double_param(vm, \"gamma\", gamma);\n        get_pos_double_param(vm, \"theta_b1\", theta_b1);\n        get_pos_double_param(vm, \"theta_b2\", theta_b2);\n        string s;\n        get_string_param(vm, \"mode\", s);\n        if (s == \"given_q\")\n            mode = MODE_GIVEN_Q;\n        else if (s == \"given_r\")\n            mode = MODE_GIVEN_R;\n        else\n            print_error(\"mode doesn't equal either given_q or given_r\");\n        get_double_param(vm, \"q_init_guess\", q_init_guess);\n        get_pos_double_param(vm, \"q_init_len\", q_init_len);\n        get_pos_double_param(vm, \"q_tol\", q_tol);\n        get_string_param(vm, \"verify_monotonicity\", s);\n        if (s == \"on\")\n            verify_monotonicity = true;\n        else if (s == \"off\")\n            verify_monotonicity = false;\n        else {\n            print_error(\n                \"verify_monotonicity doesn't equal either on or off\");\n        }\n        if (verify_monotonicity) {\n            get_double_param(vm, \"monot_ver_q_1\", monot_ver_q_1);\n            get_double_param(vm, \"monot_ver_q_2\", monot_ver_q_2);\n            get_pos_double_param(vm, \"monot_ver_q_step\", monot_ver_q_step);\n            if (monot_ver_q_1 >= monot_ver_q_2)\n                print_error(\"monot_ver_q_1 >= monot_ver_q_2\");\n        }\n        get_int_param(vm, \"N\", N);\n        get_int_param(vm, \"M\", M);\n        get_pos_double_param(vm, \"Newton_tol\", Newton_tol);\n        get_string_param(vm, \"fd_scheme\", s);\n        if (s == \"E\")\n            fd_scheme = FD_SCHEME_IMPLICIT_EULER;\n        else if (s == \"CN\")\n            fd_scheme = FD_SCHEME_CRANK_NICOLSON;\n        else\n            print_error(\"fd_scheme doesn't equal either E or CN\");\n        get_string_param(vm, \"linear_sys_sol_method\", s);\n        if (s == \"m\")\n            linear_sys_sol_method = SOL_METHOD_MTL;\n        else if (s == \"u\")\n            linear_sys_sol_method = SOL_METHOD_UMFPACK;\n        else {\n            print_error(\n                \"linear_sys_sol_method doesn't equal either m or u\");\n        }\n        if (linear_sys_sol_method == SOL_METHOD_MTL)\n            get_pos_double_param(vm, \"linear_sys_tol\", linear_sys_tol);\n        get_int_param(vm, \"divided_start_steps\", divided_start_steps);\n        if (divided_start_steps > 0)\n            get_int_param(vm, \"start_substeps\", start_substeps);\n\n        string theta_0_fun_cmd, theta_0_fun_arg, f_fun_cmd, f_fun_arg,\n            g_fun_cmd, g_fun_arg, q_fun_cmd, q_fun_arg, r_fun_cmd, r_fun_arg;\n        get_string_param(vm, \"theta_0_fun_cmd\", theta_0_fun_cmd);\n        get_string_param(vm, \"theta_0_fun_arg\", theta_0_fun_arg);\n        calc_fun(theta_0_fun_cmd, theta_0_fun_arg, L, N, theta_0);\n        get_string_param(vm, \"f_fun_cmd\", f_fun_cmd);\n        get_string_param(vm, \"f_fun_arg\", f_fun_arg);\n        calc_fun(f_fun_cmd, f_fun_arg, L, N, f);\n        get_string_param(vm, \"g_fun_cmd\", g_fun_cmd);\n        get_string_param(vm, \"g_fun_arg\", g_fun_arg);\n        calc_fun(g_fun_cmd, g_fun_arg, L, N, g);\n        if (mode == MODE_GIVEN_Q) {\n            get_string_param(vm, \"q_fun_cmd\", q_fun_cmd);\n            get_string_param(vm, \"q_fun_arg\", q_fun_arg);\n            calc_fun(q_fun_cmd, q_fun_arg, T, M, q);\n        }\n        else {  // mode == MODE_GIVEN_R\n            get_string_param(vm, \"r_fun_cmd\", r_fun_cmd);\n            get_string_param(vm, \"r_fun_arg\", r_fun_arg);\n            calc_fun(r_fun_cmd, r_fun_arg, T, M, r);\n        }\n    }\n    catch (ParamIsNotSet e) {\n        print_error(\"Parameter \\\"\" + e.param + \"\\\" is not specified\");\n    }\n    catch (ParamIsNotPositive e) {\n        print_error(\"Parameter \\\"\" + e.param + \"\\\" is not positive\");\n    }\n    catch (std::exception& e) {\n        print_error(std::string(\"error: \") + e.what());\n    }\n    catch (...) {\n        print_error(\"Exception of unknown type!\");\n    }\n    // increase the upper bound a little bit\n    // so that the for loop works correctly\n    if (monot_ver_q_2 > 0)\n        monot_ver_q_2 *= 1 + 1e-5;\n    else\n        monot_ver_q_2 *= 1 - 1e-5;\n}\n", "meta": {"hexsha": "690c51833bfebc6eb13d224904b0fd16aa9869d6", "size": 10070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "input_data.cpp", "max_stars_repo_name": "grenkin/inverse_heat", "max_stars_repo_head_hexsha": "730ee30ec00743b2e580ddf14fd9c7cd12140d68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-19T08:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T08:52:09.000Z", "max_issues_repo_path": "input_data.cpp", "max_issues_repo_name": "grenkin/inverse_heat", "max_issues_repo_head_hexsha": "730ee30ec00743b2e580ddf14fd9c7cd12140d68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "input_data.cpp", "max_forks_repo_name": "grenkin/inverse_heat", "max_forks_repo_head_hexsha": "730ee30ec00743b2e580ddf14fd9c7cd12140d68", "max_forks_repo_licenses": ["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.1439393939, "max_line_length": 80, "alphanum_fraction": 0.5820258193, "num_tokens": 2560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1801066816898922, "lm_q2_score": 0.042722193890012965, "lm_q1q2_score": 0.007694552576042422}}
{"text": "﻿/*\n * fcsp.cpp\n *\n *  Created on: Dec 16, 2013\n *      Author: dmitry\n */\n#include <algorithm>\n#include <numeric>\n#include <iomanip>\n#include <set>\n#include <boost/graph/vf2_sub_graph_iso.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/visitors.hpp>\n\n#include \"conv.hpp\"\n#include \"ctab.hpp\"\n#include \"descriptors.hpp\"\n#include \"fcsp.hpp\"\n#include \"log.hpp\"\n\nenum { NON_PASSABLE = 10000 };\nusing namespace std;\nusing namespace boost;\n\nvoid printJsArray(vector<int>& v, ostream& out)\n{\n    out << \"[\";\n    sort(v.begin(), v.end());\n    v.erase(unique(v.begin(), v.end()), v.end());\n    for(size_t i=0;i<v.size();i++)\n    {\n        if(i != 0) out << \", \";\n        out << v[i];\n    }\n    out << \"]\";\n}\n\nbool is_exclusive_dc(int dc)\n{\n    return dc == 45 || dc == 46; // these are impassable if one is part of chain\n}\n\n// Select 1-s from bool matrix so that \n// there is at least one selected per row\n// and no more then one per column\n// Input:\n// matrix - bool matrix\n// selections : row idx --> col idx\n// cur - number of currently matching row\nbool pickChoices(const vector<bool>& matrix, size_t rows, size_t cols, vector<size_t>& selections, size_t cur=0)\n{\n    if(cur == rows)\n        return true;\n    for(size_t i=0; i<cols; i++)\n    {\n        if(matrix[cur*cols + i])\n        {\n            selections[cur] = i;\n            auto end = selections.begin()+cur;\n            // not chosen before\n            if(find(selections.begin(), selections.begin()+cur, i) == end)\n            {\n                if(pickChoices(matrix, rows, cols, selections, cur+1))\n                    return true;\n                else\n                    selections[cur] = -1; // reset and continue\n            }\n        }\n    }\n    return false;\n}\n\nstruct TrackPath: public default_bfs_visitor {\n    ChemGraph& g;\n    vector<pair<vd, int>>& dcs;\n    ChemGraph::vertex_descriptor start, tgt;\n    bool pass_4546;\n    TrackPath(ChemGraph& graph, ChemGraph::vertex_descriptor s, ChemGraph::vertex_descriptor t, \n        vector<pair<vd, int>>& dcsArr) :\n        g(graph), dcs(dcsArr), start(s), tgt(t)\n    {\n        auto sdc = *find_if(dcs.begin(), dcs.end(), [&](pair<vd,int> p){\n            return p.first == start;\n        });\n        auto edc = *find_if(dcs.begin(), dcs.end(), [&](pair<vd,int> p){\n            return p.first == tgt;\n        });\n        pass_4546 = sdc.second != 45 && sdc.second != 46 && edc.second != 45 && edc.second != 46;\n        LOG(TRACE) << (pass_4546 ? \"Passing\" :\"Not passing\") <<\" DC 45-46 while going \"\n            << sdc.second << \"-->\"<< edc.second << endline; \n    }\n\n    template<typename Vertex>\n    void initialize_vertex(Vertex v, const ChemGraph&) const\n    {\n        g[v].path = 0;\n    }\n\n    template<typename Edge>\n    void tree_edge(Edge e, const ChemGraph&) const\n    {\n        auto d = target(e, g);\n        auto s = source(e, g);\n        //cout << s << \"-->\" << d << endline;\n        if (g[d].inAromaCycle && d != tgt) //all paths  of aromatic cycle  are inpassable\n            g[d].path = NON_PASSABLE;\n        else if (g[d].inAromaCycle && g[s].inAromaCycle)\n            g[d].path = NON_PASSABLE;\n        else if (g[d].code != C && d != tgt)\n            g[d].path = NON_PASSABLE;\n        else if(d != tgt && !pass_4546 && g[d].code == C)\n        {\n            bool hit4546 = find_if(dcs.begin(), dcs.end(), [d](pair<vd,int> p){\n                return p.first == d && (p.second == 45 || p.second == 46);\n            }) != dcs.end();\n\n            if(hit4546)\n            {\n                auto sdc = *find_if(dcs.begin(), dcs.end(), [&](pair<vd,int> p){\n                    return p.first == start;\n                });\n                auto edc = *find_if(dcs.begin(), dcs.end(), [&](pair<vd,int> p){\n                    return p.first == tgt;\n                });\n                LOG(DEBUG) << \"Hit non-passable DC 45/46 while going \" \n                    << sdc.second << \"-->\" << edc.second << endline;\n                g[d].path = NON_PASSABLE;\n            }\n            else\n                g[d].path = g[s].path + 1;\n        }\n        else\n            g[d].path = g[s].path + 1;\n    }\n};\n\n// callback for VF2 algorithm\nstruct CollectAsVectors{\n    ChemGraph& pattern;\n    vector<vector<size_t>>& mappings; // mapped atoms in the bigger graph\n\n    \n    CollectAsVectors(ChemGraph& pat, vector<vector<size_t>>& _mappings):pattern(pat), mappings(_mappings){}\n    template <typename CorrespondenceMap1To2,\n          typename CorrespondenceMap2To1>\n    bool operator()(CorrespondenceMap1To2 f, CorrespondenceMap2To1 g) const\n    {\n        auto vtx = vertices(pattern);\n        vector<size_t> in_big;\n        for(auto p=vtx.first; p != vtx.second; p++)\n        {\n            in_big.push_back(get(f, *p));\n        }\n        using std::move;\n        mappings.push_back(move(in_big));\n        return true;\n    }\n};\n\nint singleCount(ChemGraph& graph, ChemGraph::vertex_descriptor vertex)\n{\n    auto edges = out_edges(vertex, graph);\n    int cnt = 0;\n    for (auto p = edges.first; p != edges.second; p++)\n    {\n        if (graph[*p].type == 1)\n            cnt++;        \n    }\n    return cnt;\n}\n\npair<int,int> multiCount(ChemGraph& graph, ChemGraph::vertex_descriptor vertex)\n{\n    auto edges = out_edges(vertex, graph);\n    int dual = 0, tripple = 0;\n    for (auto p = edges.first; p != edges.second; p++)\n    {\n        if (graph[*p].type == 2)\n            dual++;\n        else if (graph[*p].type == 3)\n            tripple++;\n    }\n    return make_pair(dual, tripple);\n}\n\nstruct FCSP::Impl{\n    Impl(FCSPOptions opts) :\n        order1(std::move(opts.first)), order2(std::move(opts.second)), \n        repls(std::move(opts.replacements)),\n        long41(opts.long41), format(opts.format){}\n\n    void load(istream& inp)\n    {\n        CTab tab = readMol(inp);\n        graph = toGraph(tab);\n        auto comp = connectedComponents(graph);\n    }\n    // Очистить все переменные состояния кодировщика\n    void clear()\n    {\n        outPieces.clear();\n        outPiecesCycle.clear();\n        dcs.clear();\n        dcsAtoms.clear();\n        reserved_dcs.clear();\n        cycles.clear();\n    }\n\n    void sortDCs()\n    {\n        // filter out things that got reserved\n        auto before = dcs.size();\n        dcs.erase(remove_if(dcs.begin(), dcs.end(), [&](const pair<vd, int>& a){\n            auto p = reserved_dcs.find(a.first);\n            // LOG(FATAL) << \"> \" << (p != reserved_dcs.end()) << endline;\n            return p != reserved_dcs.end() && p->second != a.second;\n        }), dcs.end());\n        LOG(INFO) << \"Filtered \" << before - dcs.size() << \" DCs in favor of monolithic patterns.\"<< endline;\n        sort(dcs.begin(), dcs.end(), [](const pair<vd, int>& a, const pair<vd, int>& b){\n            return a.second < b.second;\n        });\n        LOG(INFO) << \"Found DCs:\" << endline;\n        for (auto& dc : dcs)\n        {\n            LOG(INFO) << dc.first << \" -DC-> \" << dc.second << endline;\n        }\n        LOG(INFO) << endline;\n    }\n\n    void process(ostream& out, string filename)\n    {\n        clear(); // clear state\n        addHydrogen(graph);\n        locatePiElectrons();\n        locateCycles(); //adds cyclic DCs\n        locateDCs(false);\n        locateIrregular();\n        sortDCs();\n        cyclic(out);\n        linear(out);\n        locateDCs(true); // REPL-only DCs - 44 so far\n        sortDCs();\n        replacement(out);\n        outputWhole(out, filename);\n    }\n\n    void dumpGraph(ostream& out)\n    {\n        ::dumpGraph(graph, out);\n    }\n\n    void outputPieceCycle(string code, vector<int>& atoms)\n    {\n        outputPiece_(code, atoms, true);\n    }\n\n    void outputPiece(string code, vector<int>& atoms)\n    {\n        outputPiece_(code, atoms, false);\n    }\n\n    void outputPiece_(string code, vector<int>& atoms, bool cycle)\n    {\n        if(format == FCSPFMT::JSON)\n        {\n            stringstream s;\n            s << \"{\" << \"\\\"code\\\" : \\\"\"<<code<<\"\\\",\";\n            s << \"\\\"place\\\": \";\n            printJsArray(atoms, s); \n            s << \"}\";\n            if(cycle)\n                outPiecesCycle.push_back(s.str());\n            else\n                outPieces.push_back(s.str());\n        }\n        else if(format == FCSPFMT::CSV || format == FCSPFMT::TXT)\n        {\n            if(cycle)\n                outPiecesCycle.push_back(code);\n            else\n                outPieces.push_back(code);\n        }\n    }\n\n    void outputWhole(ostream& out, string filename)\n    {\n        sort(outPiecesCycle.begin(), outPiecesCycle.end());\n        sort(outPieces.begin(), outPieces.end());\n        outPieces.insert(outPieces.begin(), outPiecesCycle.begin(), outPiecesCycle.end());\n        if(format == FCSPFMT::JSON)\n        {\n            out << \"[\";\n            for(size_t i=0; i<outPieces.size();i++)\n            {\n                if(i != 0)\n                    out << \", \";\n                out << outPieces[i];\n            }\n            out << \"]\";\n            out << endline;\n        }\n        else if(format == FCSPFMT::CSV || format == FCSPFMT::TXT)\n        {\n            if(format == FCSPFMT::CSV)\n                out << filename << ';';\n            for(size_t i=0; i<outPieces.size();i++)\n            {\n                if(i != 0)\n                    out << \" \";\n                out << outPieces[i];\n            }\n            out << endline;\n        }\n    }\n\n    void locatePiElectrons()\n    {\n        auto vrtx = vertices(graph);\n        for (auto i = vrtx.first; i != vrtx.second; i++)\n        {\n            //pre-calculate per-atom properties\n            int valency = getValence(graph, *i);\n            graph[*i].valence = valency;\n            auto dual_tripple = multiCount(graph, *i);\n            int piE = countPiElectrons(graph[*i].code, valency, dual_tripple.first, dual_tripple.second);\n            graph[*i].piE = piE > 0 ? piE : 0;\n        }\n    }\n\n    void locateDCs(bool replOnly)\n    {\n        auto vrtx = vertices(graph);\n        for (auto i = vrtx.first; i != vrtx.second; i++)\n        {\n            int valency = graph[*i].valence;\n            auto edges = out_edges(*i, graph);\n            LevelOne t{graph[*i].code, valency, 0};\n            auto range = equal_range(order1.begin(), order1.end(), t);\n            if(!replOnly) // skip level-1 DCs and 45-46 for repl-only DCs\n            {\n                for (auto j = range.first; j != range.second; ++j)\n                {\n                    dcs.emplace_back(*i, j->dc);\n                }\n                if(graph[*i].code == C && !graph[*i].inAromaCycle)\n                {\n                    // check for 45 & 46\n                    for (auto p = edges.first; p != edges.second; p++)\n                    {\n                        auto tgt = target(*p, graph);\n                        if (graph[*p].type == 2 && graph[tgt].code == C && !graph[tgt].inAromaCycle)\n                        {\n                            auto tgt_edges = out_edges(tgt, graph);\n                            auto cnt = count_if(tgt_edges.first, tgt_edges.second, [&](ed edge){\n                                if(graph[edge].type == 2){\n                                    auto t2 = target(edge, graph);\n                                    if(graph[t2].code == C && !graph[t2].inAromaCycle)\n                                        return true;\n                                }\n                                return false;\n                            });\n                            if(cnt == 2) // 2 double links both with C - 45 DC\n                            { \n                                dcs.emplace_back(*i, 45);\n                            }\n                            else // only one double link\n                            {\n                                dcs.emplace_back(*i, 46);\n                            }\n                        }\n                        else if (graph[*p].type == 3 && graph[tgt].code == C && !graph[tgt].inAromaCycle)\n                        {\n                            dcs.emplace_back(*i, 45);\n                        }\n                    }\n                }\n            }\n            // select a range of DCs pattern with center matching this atom\n            auto range2 = make_pair(order2.begin(), order2.end());\n            for (auto j = range2.first; j != range2.second; j++)\n            {\n                if(j->replOnly != replOnly) // can't use during this stage\n                    continue;\n                if (edges.second - edges.first < (int)j->bonds.size())\n                    continue;\n                if (!j->center.matches(graph[*i].code))\n                    continue;\n                if (j->valence != valency)\n                    continue;\n                LOG(TRACE) << \"Candidate DC \"<< j->dc <<\" CENTER \" << j->center.symbol() << \" VALENCE \"<< valency << endline;\n\n                vector<int> atoms; // atoms in this center\n                size_t cand_bnds = edges.second - edges.first;\n                size_t smpl_bnds = j->bonds.size();\n                // Put ones for combinations that match. A row per edge in a DC pattern (sample).\n                // Then we need to pick one in each row, if at least one row is all zeros - no match\n                // Same DC may happen twice in the same atom, but we don't accomodate for that (for now)\n                vector<bool> mappings(cand_bnds*smpl_bnds); \n                LOG(TRACE) << \"MAPPING:\" <<endline;\n                LOG(TRACE) << \"  \";\n                for(size_t k=0; k<cand_bnds; k++)\n                {\n                    auto e = (edges.first+k);\n                    auto t = target(*e, graph);\n                    LOG(TRACE) << setw(2) << graph[t].code.symbol();\n                }\n                for(size_t p=0; p<smpl_bnds; p++)\n                {\n                    LOG(TRACE) << endline << setw(2) << j->bonds[p].atom.symbol();\n                    for(size_t q=0; q<cand_bnds; q++)\n                    {\n                        auto e = edges.first + q;\n                        if(graph[*e].type == j->bonds[p].bondType)\n                        {\n                            auto t = target(*e, graph);\n                            if(j->bonds[p].atom.matches(graph[t].code))\n                                mappings[p*cand_bnds + q] = true;\n                        }\n                        LOG(TRACE) << setw(2) << mappings[p*cand_bnds + q];\n                    }\n                }\n                LOG(TRACE) << endline;\n                vector<size_t> found_mapping(smpl_bnds); // sample idx --> candidate idx\n                if(pickChoices(mappings, smpl_bnds, cand_bnds, found_mapping))\n                {\n                    for(auto idx : found_mapping)\n                    {\n                        // get atom by index of edge around this atom\n                        auto t = target(*(edges.first + idx), graph);\n                        atoms.push_back(t);\n                    }\n                    dcs.emplace_back(*i, j->dc);\n                    dcsAtoms.insert(make_pair(*i, atoms));\n                    // only assign DCs to reserve once\n                    if(j->monolith && reserved_dcs.find(*i) == reserved_dcs.end())\n                    { \n                        LOG(DEBUG) << \"Reserved for DC \"<< j->dc << \" \"<< atoms.size() + 1 <<\" atoms\"<<endline;\n                        //reserve atoms that belong to this DC\n                        reserved_dcs[*i] = j->dc;\n                        for(auto v : atoms)\n                        {\n                            if(graph[v].code != C) //FIXME: should be more sensible\n                                reserved_dcs[v] = j->dc;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    template<class T>\n    static const T& chainAt(const vector<T>& chain, int idx)\n    {\n        while (idx < 0)\n            idx += (int)chain.size();\n        while (idx >= (int)chain.size())\n            idx -= (int)chain.size();\n        return chain[idx];\n    }\n\n    static string keyatom(ChemGraph& g, vd v)\n    {\n        //numbers mean at least x links of given type\n        //val == 0 - do not care\n        struct Entry {\n            char symbol;\n            Code code;\n            int valence;\n            int singleLinks;\n            int dualLinks;\n            int trippleLinks;\n        };\n        Entry table[] = {\n            { 'M', N, 0, 1, 1, 0 },\n            { 'N', N, 0, 2, 0, 0 },\n            { 'Q', O, 2, 0, 0, 0 },\n            { 'R', O, 3, 0, 0, 0 },\n            { 'T', S, 0, 1, 1, 0 },\n            { 'S', S, 2, 2, 0, 0 }\n        };\n        for (auto& e : table)\n        {\n            if (g[v].code == e.code)\n            {\n                if (e.valence && g[v].valence != e.valence)\n                    continue;\n                auto dt = multiCount(g, v);\n                auto s = singleCount(g, v);\n                if (e.singleLinks && e.singleLinks > s)\n                    continue; //not enough links\n                if (e.dualLinks && e.dualLinks > dt.first)\n                    continue;\n                if (e.trippleLinks && e.trippleLinks > dt.second)\n                    continue;\n                return string(1, e.symbol);\n            }\n        }\n        if (heteroatom(g[v]))\n            return g[v].code.symbol();\n        else\n            return string();\n    }\n\n    static bool heteroatom(const AtomVertex& atom)\n    {\n        return !atom.code.matches(C) && !atom.code.matches(H);\n    }\n\n    \n    void locateCycles()\n    {\n        cycles = minimalCycleBasis(graph);\n        for (auto& ic : cycles)\n        {\n            auto& vc = ic.chain;\n            ic.markAromatic(graph);\n            if(ic.aromatic()) // aromatic specific DCs\n            {\n                for(auto n : vc)\n                {\n                    //any atom in aromatic cycle\n                    dcs.emplace_back(n, 33);\n                    //hetero-atom in aromatic cycle - DC 34\n                    if (!graph[n].code.matches(C))\n                        dcs.emplace_back(n, 34);\n                    auto idx = find(vc.begin(), vc.end(), n) - vc.begin();\n                    assert(idx != (int)vc.size());\n                    if (heteroatom(graph[chainAt(vc, idx - 1)])\n                        || heteroatom(graph[chainAt(vc, idx + 1)]))\n                    {\n                        dcs.emplace_back(n, 35);\n                    }\n                    else if (heteroatom(graph[chainAt(vc, idx - 2)])\n                        || heteroatom(graph[chainAt(vc, idx + 2)]))\n                    {\n                        dcs.emplace_back(n, 36);\n                    }\n                    else if (heteroatom(graph[chainAt(vc, idx - 3)])\n                        || heteroatom(graph[chainAt(vc, idx + 3)]))\n                    {\n                        dcs.emplace_back(n, 37);\n                    }\n                    //TODO: DC 40 - need to handle charges carefully to test charged atoms\n                }\n            }\n        }\n    }\n\n    void locateIrregular() //  TODO: rewrite\n    {\n        /*for (auto& r : irregularTempl)\n        {\n            vector<vector<pair<size_t, size_t>>> mappings;\n            auto& g = graph;\n            ullmann_all(r.piece, graph, [&r, &g](ChemGraph::vertex_descriptor a, ChemGraph::vertex_descriptor b){\n                return r.piece[a].code == g[b].code;\n            }, [&r, &g](ChemGraph::edge_descriptor a, ChemGraph::edge_descriptor b){\n                return r.piece[a].type == g[b].type;\n            }, mappings);\n        }*/\n    }\n\n    void addDescriptorAtoms(vector<int>& fragment, vd dc)\n    {\n        if(dcsAtoms.find(dc) != dcsAtoms.end()){\n            fragment.insert(fragment.end(), dcsAtoms[dc].begin(), dcsAtoms[dc].end());\n        }\n    }\n\n    template<class Fn>\n    void applyPath(vd start, vd end, Fn&& fn)\n    {\n        vd current = end;\n        fn(current);\n        while (current != start)\n        {\n            //cout << graph[current].path << \" -->\" << endline;\n            auto nearby = adjacent_vertices(current, graph);\n            auto i = nearby.first;\n            for (; i != nearby.second; i++)\n            {\n                //cout << graph[*i].path << \"..\" ;\n                if (graph[*i].path == graph[current].path - 1)\n                {\n                    current = *i;\n                    fn(current);\n                    break;\n                }\n            }\n            if (i == nearby.second)\n                break;\n        }\n    }\n\n    void linear(ostream& out)\n    {\n        queue<vd> buf;\n        // DCs are sorted as a[0] < .. < a[n-1]\n        for (size_t i = 0; i < dcs.size(); i++)\n        for (size_t j = i  + 1; j < dcs.size(); j++)\n        {\n            vd start = dcs[i].first;\n            vd end = dcs[j].first;\n            int start_dc = dcs[i].second;\n            int end_dc = dcs[j].second;\n            breadth_first_search(graph, start, buf,\n                TrackPath(graph, start, end, dcs), get(&AtomVertex::color, graph));\n            if (graph[end].path && graph[end].path < NON_PASSABLE)\n            {\n                bool coupled = true; //0-length path is therefore coupled (FIXME: check PI el-s too)\n                auto &g = graph;\n                vector<int> fragment;\n                if(start_dc == 41) // check only the first \n                {\n                    bool check = true;\n                    applyPath(start, end, [g, end, &check, &coupled, &fragment](vd v){\n                        if(check)\n                        {\n                            if (v != end && g[v].code.matches(C) && g[v].piE == 0)\n                                coupled = false;\n                            check = false;\n                        }\n                        fragment.push_back((int)v);\n                    });\n                }\n                else\n                {\n                    applyPath(start, end, [g, end, &coupled, &fragment](vd v){\n                        if (v != end && g[v].code.matches(C) && g[v].piE == 0)\n                            coupled = false;\n                        fragment.push_back((int)v);\n                    });\n                }\n                int len = graph[end].path - 1;\n                //SPECIAL CASE - TODO verifiy correctness\n                if(len == 0)\n                    coupled = true;\n                if (len == 0 && is_exclusive_dc(start_dc) && start_dc == end_dc)\n                {\n                    if(g[edge(start, end, g).first].type > 1) // connected with non-single link\n                    {\n                        continue; // skip output - this is self-referental\n                    }\n                }\n                // SPECIAL CASE - \"The long 41\" rule\n                if(start_dc == 41 && long41)\n                    len += 1;\n                if(end_dc == 41 && long41)\n                    len += 1;\n                stringstream buffer;\n                buffer << setfill('0') << setw(2) << start_dc\n                    << setfill('0') << setw(2) << len\n                    << setfill('0') << setw(2) << end_dc\n                    << (coupled ? 1 : 0);\n                addDescriptorAtoms(fragment, dcs[i].first);\n                addDescriptorAtoms(fragment, dcs[j].first);\n                outputPiece(buffer.str(), fragment);\n            }\n        }\n    }\n\n    struct Edge{\n        pair<vd, vd> e;\n        int cycNum; //e принадлежит циклу cycles[cycNum]\n        Edge(pair<vd, vd> e_, int cyc) :\n            e(e_), cycNum(cyc){}\n        bool operator<(const Edge& rhs)const\n        {\n            return e < rhs.e;\n        }\n    };\n\n    //Строим запись \"головы\" двигаясь по огибающей (common) в обе стороны \n    string encodeHead(int firstCycle, vector<vd>& commonCh, vector<Edge>& common, int totalCycles)\n    {\n        //Выбор опорного атома из стартового цикла\n        auto& firstChain = cycles[firstCycle].chain;\n        auto firstIdx = find_if(commonCh.begin(), commonCh.end(), [&firstChain](int v){\n            return find(firstChain.begin(), firstChain.end(), v) != firstChain.end();\n        });\n        auto fIdx = firstIdx - commonCh.begin();\n        // обход вперед/назад\n        auto fwd = encodeCycle(1, commonCh, fIdx, firstCycle, common, totalCycles);\n        auto bwd = encodeCycle(-1, commonCh, fIdx, firstCycle, common, totalCycles);\n        return fwd < bwd ? fwd : bwd;\n    }\n\n    string encodeCycle(int dir, vector<vd>& commonCh, int fIdx, int cycNum, vector<Edge>& common, int totalCycles)\n    {\n        stringstream cyclic_out;\n        int edgeNum = 0; // on the most recent cycle\n        int prevEdgeNum = 0; //edge count tracked on previous cycle\n        size_t cycCount = 0; //first 2 are output as is, 3rd, 4th and so on need prefixes\n        //for (auto& p : common)\n        //    cout << p.e.first << \":\" << p.e.second << endline;\n        auto v1 = chainAt(commonCh, fIdx);\n        for (int j = dir; ; j+= dir)\n        {\n            auto v2 = chainAt(commonCh, fIdx + j);\n            auto edge = v1 < v2 ? make_pair(v1, v2) : make_pair(v2, v1);\n            v1 = v2;\n            auto p = equal_range(common.begin(), common.end(), Edge(edge, 0));\n            assert(p.first != p.second);\n            //cout << \"Go with \" << p.first->e.first << \":\" << p.first->e.second << endline;\n            edgeNum++;\n            if (cycNum != p.first->cycNum)\n            {\n                //cout << \"Cycle!\" << endline;\n                static string tab = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n                cycCount++;\n                if (cycCount > 2)\n                {\n                    assert(prevEdgeNum > 0 && prevEdgeNum < 20); //TODO: error on this\n                    cyclic_out << setw(1) << tab[prevEdgeNum-1]\n                        << setw(1) << cycles[cycNum].edges.size();\n                }\n                else\n                    cyclic_out << setw(1) << cycles[cycNum].edges.size();\n                cycNum = p.first->cycNum;\n                prevEdgeNum = edgeNum;\n                edgeNum = 0;\n                if (cycCount == totalCycles) // all encoded\n                    break;\n            }\n        }\n        return cyclic_out.str();\n    }\n\n    int pickNonKeyAtom(int dir, int fChain, int firstCycle, vector<vd>& commonCh, vector<Edge>& common)\n    {\n        for (int k = 0, j = fChain; k < (int)commonCh.size(); k++, j += dir)\n        {\n            auto v = chainAt(commonCh, j);\n            auto v2 = chainAt(commonCh, j + dir);\n            auto p = v < v2 ? make_pair(v, v2) : make_pair(v2, v);\n            auto e = Edge(p, 0);\n            auto r = equal_range(common.begin(), common.end(), e);\n            assert(r.first != r.second);\n            if (r.first->cycNum != firstCycle)\n            {\n                return j - dir;//step back \n            }\n        }\n        assert(false);\n        return 0;\n    }\n\n    string encodeHeteroAtoms(int dir, int start, vector<vd>& commonCh)\n    {\n        stringstream s;\n        for (int i = 0, j = start; i < commonCh.size(); i++, j += dir)\n        {\n            auto v = chainAt(commonCh, j);\n            string k = keyatom(graph, v);\n            if (!k.empty())\n            {\n                s << k << i + 1;\n            }\n        }\n        return s.str();\n    }\n\n    //Строим запись \"хвоста\" по стартовому циклу, двигаясь по огибающей (common) в обе стороны\n    string encodeTail(int firstCycle, vector<vd>& commonCh, vector<Edge>& common, int totalCycles)\n    {\n        auto& firstChain = cycles[firstCycle].chain;\n        auto firstIdx = find_if(commonCh.begin(), commonCh.end(), [&firstChain](int v){\n            return find(firstChain.begin(), firstChain.end(), v) != firstChain.end();\n        });\n        auto fi = firstIdx - commonCh.begin();\n        //Идем в обе стороны и находим последние элементы в нашем цикле\n        int firstV, secondV;\n        //Правило: ключевые атомы (принадлежащие нескольким циклам) должны иметь наибольший номер\n        firstV = pickNonKeyAtom(1, fi, firstCycle, commonCh, common);\n        secondV = pickNonKeyAtom(-1, fi, firstCycle, commonCh, common);\n        string variant[2];\n        //firstV первый неключевой атом в \"+\" сторону, значит нумеруем в обратную\n        variant[0] = encodeHeteroAtoms(-1, firstV, commonCh);\n        //тоже для secondV\n        variant[1] = encodeHeteroAtoms(1, secondV, commonCh);\n        sort(variant, variant + 2);\n        return variant[0];\n    }\n\n    //копирует ccv, тк будет не однакратно сортирован\n    void encodeOnePolyCycle(vector<int> ccv)\n    {\n        //элементарные циклы кодируются отдельно\n        if (ccv.size() == 1)\n            return;\n        vector<int> intercounts(cycles.size()); //кол-во пересечний с другими циклами\n        for (auto n : ccv)\n        {\n            int c = 0;\n            for (auto n2 : ccv)\n            {\n                if (intermap[n*cycles.size() + n2])\n                    c++;\n            }\n            intercounts[n] = c;\n        }\n        //Выбираем стартовый цикл - минимальный по числу пересечений (крайний), минимальный по числу элементов\n        //ищем сразу 2 стартовых цикла, на случай, где они одинково хорошо подходят\n        auto& cys = cycles;\n        partial_sort(ccv.begin(), ccv.begin() + 2, ccv.end(), [&intercounts, &cys](int a, int b){\n            int ia = intercounts[a];\n            int ib = intercounts[b];\n            return ia < ib || (ia == ib && cys[a].edges.size() < cys[b].edges.size());\n        });\n        auto start = ccv.begin();\n        //Строим огибающий цикл (ребра)\n        //в огибающей записывается номер цикла, которому принадлежит ребро\n        vector<Edge> common;\n        vector<size_t> idxs(ccv.size()); //idxs[i] --> cycles[ccv[i]][*]\n        //алгоритм объединения N множест ребер\n        //с исключением по предикату \"принадлежит более чем одному множеству\"\n        for (;;)\n        {\n            //which edge to pick\n            pair<vd, vd> m_edge(-1, -1);\n            size_t smallestCCV = 0; //number of ccv entry having the smalles edge so far\n            for (size_t i = 0; i < idxs.size(); i++)\n            {\n                auto n_edge = idxs[i];\n                if (n_edge >= cys[ccv[i]].edges.size())\n                    continue;\n                auto edge = cys[ccv[i]].edges[n_edge];\n                if (m_edge.first == (size_t)-1 || edge < m_edge)\n                {\n                    m_edge = edge;\n                    smallestCCV = i;\n                }\n            }\n            if (m_edge.first == (size_t)-1)\n                break;\n            auto i = idxs[smallestCCV];\n            auto& c = cys[ccv[smallestCCV]];\n            idxs[smallestCCV]++;\n            //проверка - c[i] должен принадлежать только одному эл. циклу\n            int matches = 0;\n            for (auto x : ccv)\n            {\n                auto er = equal_range(cys[x].edges.begin(), cys[x].edges.end(), c.edges[i]);\n                if (er.first != er.second)\n                    matches++;\n            }\n            if (matches == 1 && (common.empty() || common.back().e != c.edges[i]))\n                common.push_back(Edge(c.edges[i], ccv[smallestCCV]));\n            assert(is_sorted(common.begin(), common.end()));\n        }\n        LOG(DEBUG) << \"COMMON EDGE SET:\";\n        for(auto e : common)\n            LOG(DEBUG) << e.e << \" \";\n        LOG(DEBUG) << endline;\n        auto commonCh = cycleToChain(common, [](const Edge& e){ return e.e; });\n        string head = encodeHead(*start, commonCh, common, ccv.size());\n        string head2 = head;\n        // еще один стартовый цикл (если одинакового размера)\n        if (cycles[*start].edges.size() == cycles[*(start + 1)].edges.size())\n        {\n            head2 = encodeHead(*(start + 1), commonCh, common, ccv.size());\n        }\n        head = head < head2 ? head : head2;\n        //Суммируем Пи электроны по огибающей\n        auto range = vertices(graph);\n        auto sz = range.second - range.first;\n        vector<bool> visited(sz);\n        int piE = 0;\n        for (int v : commonCh)\n        {\n            piE += graph[v].piE;\n        }\n        bool aromatic = (piE - 2) % 4 == 0;\n        //Кодируем \"хвост\"\n        //Выбираем новый цикл - минимальный по числу пересечений (крайний), _максимальный_ по числу элементов\n        partial_sort(ccv.begin(), ccv.begin() + 2, ccv.end(), [&intercounts, &cys](int a, int b){\n            int ia = intercounts[a];\n            int ib = intercounts[b];\n            return ia < ib || (ia == ib && cys[a].edges.size() > cys[b].edges.size());\n        });\n        start = ccv.begin();\n        string tail = encodeTail(*start, commonCh, common, ccv.size());\n        string tail2 = tail;\n        // еще один стартовый цикл (если одинакового размера)\n        if (cycles[*start].edges.size() == cycles[*(start + 1)].edges.size())\n            tail2 = encodeTail(*(start + 1), commonCh, common, ccv.size());\n        if (tail > tail2)\n            tail = tail2;\n        stringstream buffer;\n        vector<int> fragment;\n\n        buffer << head;\n        buffer << \",\" << setfill('0') << setw(2) << (aromatic ? piE : 0);\n        buffer << tail;\n        for(auto cc : ccv){\n            fragment.insert(fragment.end(), cycles[cc].chain.begin(), cycles[cc].chain.end());\n        }\n        outputPieceCycle(buffer.str(), fragment);\n    }\n\n    void recursePoly(vector<int>& poly, map<int, vector<int>>& adj_list, set<vector<int>>& used)\n    {\n        auto e = poly.back();\n        for (auto x : adj_list[e])\n        {\n            {\n                if (find(poly.begin(), poly.end(), x) != poly.end())\n                    continue;\n                assert(intermap[x + e*cycles.size()]);\n                poly.push_back(x);\n                if (poly.size() > 1)\n                {\n                    auto cp = poly;\n                    sort(cp.begin(), cp.end());\n                    if (used.find(cp) == used.end())\n                    {\n                        encodeOnePolyCycle(cp);\n                        using std::move;\n                        used.insert(move(cp));\n                    }\n                }\n                //добавить еще один цикл\n                if (poly.size() < adj_list.size())\n                    recursePoly(poly, adj_list, used);\n                poly.pop_back();\n            }\n        }\n    }\n\n    void encodePolyCycles(vector<int>& ccv)\n    {\n        map<int, vector<int>> adj_list; //ccv[i] --> adj_list[i]\n        for (auto x : ccv)\n        {\n            vector<int> neib;\n            for (auto y : ccv)\n            {\n                if (y != x && intermap[y*cycles.size() + x])\n                {\n                    neib.push_back(y);\n                }\n            }\n            using std::move;\n            adj_list.insert(make_pair(x, move(neib)));\n        }\n        vector<int> poly;\n        set<vector<int>> used;\n        for (auto x : ccv)\n        {\n            poly.push_back(x);\n            recursePoly(poly, adj_list, used);\n            poly.pop_back();\n            assert(poly.size() == 0);\n        }\n    }\n\n    void cyclic(ostream& out)\n    {\n        // Кодирование простых циклов\n        for (auto cyc : cycles)\n        {\n            auto& ch = cyc.chain;\n            int piE = 0;\n            // NEW RULE - always output piE for singleton cycles and coupling linked systems\n            for (vd v : ch)\n                piE += graph[v].piE;\n            vector<pair<string, vd>> hatoms;\n            for (vd v : ch)\n            {\n                string s = keyatom(graph, v);\n                if (!s.empty())\n                {\n                    hatoms.emplace_back(s, v);\n                }\n            }\n            auto pivot = min_element(hatoms.begin(), hatoms.end(), [](const pair<string, int> & lhs, const pair<string, int> &rhs){\n                return lhs.first < rhs.first;\n            });\n            stringstream buffer;\n            vector<int> fragment;\n            fragment.insert(fragment.end(), ch.begin(), ch.end());\n            buffer << setfill('0') << setw(1) << cyc.edges.size()\n                << \",\"\n                << setfill('0') << setw(2) << piE;\n            bool heterocycle = pivot != hatoms.end();\n            if (heterocycle)\n            {\n                string left_descr, right_descr;\n                auto idx = pivot - hatoms.begin();\n                for (int k = 0; k < (int)hatoms.size(); k++)\n                {\n                    auto& nextL = chainAt(hatoms, idx + k);\n                    auto& nextR = chainAt(hatoms, idx - k);\n                    auto number = to<string>(k + 1);\n                    left_descr += nextL.first + number;\n                    right_descr += nextR.first + number;\n                }\n                buffer << (left_descr < right_descr ? left_descr : right_descr);\n            }\n            outputPieceCycle(buffer.str(), fragment);\n        }\n        //make a map of intersections\n        intermap.resize(cycles.size()*cycles.size());\n        intermap.clear();\n        for (size_t i = 0; i < cycles.size(); i++)\n        for (size_t j = i + 1; j < cycles.size(); j++)\n        {\n            auto& c1 = cycles[i];\n            auto& c2 = cycles[j];\n            bool intersection = c1.intersects(c2);\n            intermap[i*cycles.size() + j] = intersection;\n            intermap[j*cycles.size() + i] = intersection;\n        }/*\n        for (size_t i = 0; i < cycles.size(); i++)\n        {\n            for (size_t j = 0; j < cycles.size(); j++)\n            {\n                cout << intermap[i*cycles.size() + j];\n            }\n            cout << endline;\n        }*/\n        //\n        vector<int> ccv; //chain - indices of cycles\n        vector<bool> used(cycles.size());\n        do\n        {\n            ccv.clear();\n            for (size_t i = 0; i < cycles.size();)\n            {\n                if (used[i])\n                {\n                    i++;\n                    continue;\n                }\n                if (ccv.empty())\n                {\n                    used[i] = true;\n                    ccv.push_back(i);\n                    i++; // первый непроверенный, нет нужды начинать с 0\n                    continue;\n                }\n                //then must interesect some other cycle in this chain\n                bool found = false;\n                for (auto j : ccv)\n                {\n                    if (intermap[i*cycles.size() + j])\n                    {\n                        found = true;\n                        break;\n                    }\n                }\n                if (found)\n                {\n                    used[i] = true;\n                    ccv.push_back(i);\n                    i = 0; //нужно перепроверить циклы\n                    continue;\n                }\n                i++;\n            }\n            if (ccv.size() > 1) //элементарные циклы уже учтены\n            {\n                encodePolyCycles(ccv);\n            }\n        } while (!ccv.empty());\n    }\n\n    // return all descriptors at dcV vertex\n    vector<int> mapDCs(size_t dcV)\n    {\n        vector<int> dc_nums;\n        for(auto p : dcs){\n            if(p.first == dcV)\n                dc_nums.push_back(p.second);\n        }\n        return dc_nums;\n    }\n\n    void replacement(ostream& out)\n    {\n        //cout << \"REPLACEMENTS!\" << endline;\n        for (auto& r : repls)\n        {\n            vector<vector<size_t>> mappings;\n            auto& g = graph;\n            \n            vf2_subgraph_iso(r.piece, g, CollectAsVectors(g, mappings), vertex_order_by_mult(r.piece),\n                vertices_equivalent([&](ChemGraph::vertex_descriptor a, ChemGraph::vertex_descriptor b){                \n                    if(!r.piece[a].code.matches(g[b].code))\n                        return false;\n                    if(a == r.a1 || a == r.a2){\n                        if(g[b].inAromaCycle) // none of replacemnt dc are in aroma cycle (e.g. DC 41 is CH3)\n                            return false;\n                        return find_if(dcs.begin(), dcs.end(), [&](pair<vd,size_t> dcp){\n                            return dcp.first == b;\n                        }) != dcs.end();\n                    }\n                    else\n                        return true;\n                }).edges_equivalent(\n                [&r, &g](ChemGraph::edge_descriptor a, ChemGraph::edge_descriptor b){\n                    return r.piece[a].type == g[b].type;\n                })\n            );\n            vector<pair<pair<int, int>, pair<int, int>>> used_pairs;\n            for (auto& m : mappings)\n            {\n                int fV = m[r.a1];\n                int sV = m[r.a2];                \n                // check if this pair of vertex-DC pairs was used before\n                auto fdc = mapDCs(fV);\n                if (fdc.size() == 0)\n                    continue;\n                auto sdc = mapDCs(sV);\n                if (sdc.size() == 0)\n                    continue;\n                for(auto f : fdc)\n                for(auto s : sdc)\n                {\n                    auto firstDC = f;\n                    auto secondDC = s;\n                    auto firstV = fV;\n                    auto secondV = sV;\n                    // the usual rule of smaller DC first\n                    if(firstDC > secondDC)\n                    {\n                        swap(firstDC, secondDC);\n                        swap(firstV, secondV);\n                    }\n                    auto check_val = make_pair(make_pair(firstV, firstDC), make_pair(secondV,secondDC));\n                    if (find(used_pairs.begin(), used_pairs.end(),check_val) != used_pairs.end())\n                            continue;\n                    used_pairs.emplace_back(make_pair(firstV, firstDC), make_pair(secondV,secondDC));\n                    \n                    stringstream buffer;\n                    vector<int> fragment;\n                    for(auto& p : m)\n                        fragment.push_back(p);\n                    addDescriptorAtoms(fragment, fV);\n                    addDescriptorAtoms(fragment, sV);\n\n                    buffer << setfill('0') << setw(2) << firstDC\n                        << setfill('0') << setw(2) << r.dc\n                        << setfill('0') << setw(2) << secondDC\n                        << r.coupling;\n                    outputPiece(buffer.str(), fragment);\n                }\n            }\n        }\n    }\n\nprivate:\n    std::vector<LevelOne> order1;        // patterns for first-order DCs\n    std::vector<LevelTwo> order2;        // patterns for second-order DCs\n    std::vector<Replacement> repls; // patterns for replacement decsriptors (not DCs)\n    bool long41;                                        // if true - DC #41 adds +1 to the length of chain\n    FCSPFMT format;                                     // controls output format\n    ChemGraph graph;                                // mol graph\n    //location of DCs in 'graph' and their numeric value\n    vector<pair<vd, int>> dcs;            // sorted by vertex array of vertex->dc mappings\n    std::unordered_map<vd, vector<int>> dcsAtoms;  // extra atoms that belong to each DC  \n    std::unordered_map<vd, int> reserved_dcs; // atoms reserved by specific monolithic DC\n    // unassembled output chunks, assembly depends on format variable\n    vector<string> outPiecesCycle; // cycle descriptors go first on assembly\n    vector<string> outPieces;\n    //sorted arrays of edges - basic cycles\n    //vector<vector<pair<int, int>>> cycles;\n    //same basic cycles represented as chains of vertices\n    //vector<vector<int>> chains;\n    vector<Cycle> cycles;\n    //map of intersection between cycles\n    vector<bool> intermap;\n};\n\nFCSP::FCSP(FCSPOptions opts) :\n    pimpl(new FCSP::Impl(std::move(opts))){}\n\nvoid FCSP::load(std::istream& inp)\n{\n    pimpl->load(inp);\n}\n\n\nvoid FCSP::dumpGraph(std::ostream& dot)\n{\n    pimpl->dumpGraph(dot);\n}\n\nvoid FCSP::process(std::ostream& out, string filename)\n{\n    pimpl->process(out, filename);\n}\n\nFCSP::~FCSP(){}\n", "meta": {"hexsha": "92e243171791f89b2c2675e2469a18147b3df2ad", "size": 43707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fcsp.cpp", "max_stars_repo_name": "DmitryOlshansky/fcsp", "max_stars_repo_head_hexsha": "27301f475947c961501aa24a9537ca583a7d65c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fcsp.cpp", "max_issues_repo_name": "DmitryOlshansky/fcsp", "max_issues_repo_head_hexsha": "27301f475947c961501aa24a9537ca583a7d65c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fcsp.cpp", "max_forks_repo_name": "DmitryOlshansky/fcsp", "max_forks_repo_head_hexsha": "27301f475947c961501aa24a9537ca583a7d65c0", "max_forks_repo_licenses": ["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.5443143813, "max_line_length": 131, "alphanum_fraction": 0.460955911, "num_tokens": 10610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.019419346479940012, "lm_q1q2_score": 0.007691384673682229}}
{"text": "﻿#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <fstream>\r\n#include <boost/foreach.hpp>\r\n\r\nusing namespace std;\r\n\r\nclass HDB3Parser\r\n{\r\npublic:\r\n\t//public entry point for encode\r\n\tvector<string> Encode(vector<string> data)\r\n\t{\r\n\t\tfor each (auto item in data)\r\n\t\t\tthis->_convertedData.push_back(EncodeToHDB3(item));\r\n\r\n\t\treturn this->_convertedData;\r\n\t}\r\n\r\n\t//public entry point for decode\r\n\tvector<string> Decode(string readFilename, string writeFilename)\r\n\t{\r\n\t\tReadWrite(readFilename, true);\r\n\r\n\t\tfor each (auto item in this->_data)\r\n\t\t\tthis->_convertedData.push_back(DecodeFromHDB3(item));\r\n\r\n\t\tReadWrite(writeFilename, false);\r\n\r\n\t\treturn this->_convertedData;\r\n\t}\r\n\r\nprivate:\r\n\tvector<string> _data;\r\n\tvector<string> _convertedData;\r\n\r\n\t//reads or writes to a file\r\n\tvoid ReadWrite(string filename, bool read)\r\n\t{\r\n\t\tfstream stream;\r\n\t\tstring lineIn;\r\n\t\tstring temp;\r\n\r\n\t\tstream.open(filename);\r\n\r\n\t\tif (stream.good())\r\n\t\t{\r\n\t\t\tif (read)\r\n\t\t\t{\r\n\t\t\t\tcout << \"Reading contents of \" << filename << \"...\" << endl;\r\n\t\t\t\twhile (stream.good())\r\n\t\t\t\t{\r\n\t\t\t\t\tgetline(stream, lineIn);\r\n\r\n\t\t\t\t\tthis->_data.push_back(lineIn);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tcout << \"Saving data to \" << filename << \"...\" << endl;\r\n\r\n\t\t\t\tfor each (auto str in this->_convertedData)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (str != \"\")\r\n\t\t\t\t\t\tstream << str << endl;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tstream.close();\r\n\t\t}\r\n\t\telse\r\n\t\t\tcout << \"ERROR: Could not open file: \" << filename << endl;\r\n\t}\r\n\r\n\t//encodes given string to HDB3\r\n\tstring EncodeToHDB3(string item)\r\n\t{\r\n\t\tint numZeroes = 0;\r\n\t\tint numPulseCharacters = 0;\r\n\t\tbool prevPulseWasPositive = false;\r\n\t\tbool isAfterFirstViolation = false;\r\n\t\tbool tempPulseBool;\r\n\t\titem = ConvertToAMI(item, false);\r\n\r\n\t\tfor (int i = 0; i < item.length(); i++)\r\n\t\t{\r\n\t\t\tif (item[i] == '+')\r\n\t\t\t{\r\n\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t\tnumPulseCharacters++;\r\n\t\t\t}\r\n\t\t\telse if (item[i] == '-')\r\n\t\t\t{\r\n\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\t\tnumPulseCharacters++;\r\n\t\t\t}\r\n\r\n\t\t\tif (item[i] == '0' && item.length() - i >= 4 && item.substr(i, 4) == \"0000\")\r\n\t\t\t{\r\n\t\t\t\tif (!isAfterFirstViolation)\r\n\t\t\t\t\tisAfterFirstViolation = true;\r\n\r\n\t\t\t\tif (isOdd(numPulseCharacters))\r\n\t\t\t\t{\r\n\t\t\t\t\tif (prevPulseWasPositive)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\titem.replace(i, 4, \"-00-\");\r\n\t\t\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\titem.replace(i, 4, \"+00+\");\r\n\t\t\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tnumPulseCharacters = 1;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif (prevPulseWasPositive)\r\n\t\t\t\t\t\titem.replace(i, 4, \"000+\");\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\titem.replace(i, 4, \"000-\");\r\n\r\n\t\t\t\t\tnumPulseCharacters = 1;\r\n\t\t\t\t}\r\n\r\n\t\t\t\ti += 3;\r\n\t\t\t\ttempPulseBool = prevPulseWasPositive;\r\n\t\t\t\titem = CheckForAMIViolations(item, i, prevPulseWasPositive);\r\n\r\n\t\t\t\tprevPulseWasPositive = tempPulseBool;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn item;\r\n\t}\r\n\r\n\t//converts given string to AMI\r\n\tstring ConvertToAMI(string binaryStr, bool prevPulseWasPositive)\r\n\t{\r\n\t\tfor (int i = 0; i < binaryStr.length(); i++)\r\n\t\t{\r\n\t\t\tif (binaryStr[i] == '1' && !prevPulseWasPositive)\r\n\t\t\t{\r\n\t\t\t\tbinaryStr[i] = '+';\r\n\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t}\r\n\t\t\telse if (binaryStr[i] == '1' && prevPulseWasPositive)\r\n\t\t\t{\r\n\t\t\t\tbinaryStr[i] = '-';\r\n\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn binaryStr;\r\n\t}\r\n\r\n\t//checks for AMI violations in given string and corrects them\r\n\tstring CheckForAMIViolations(string item, int currentIndex, bool prevPulseWasPositive)\r\n\t{\r\n\t\tint first = currentIndex + 1;\r\n\t\tbool tempPulseBool = prevPulseWasPositive;\r\n\t\tint numAmiViolations = 0;\r\n\r\n\t\tfor (first; first < item.length(); first++)\r\n\t\t{\r\n\t\t\tif (prevPulseWasPositive && item[first] == '+')\r\n\t\t\t{\r\n\t\t\t\titem[first] = '-';\r\n\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\t\tnumAmiViolations++;\r\n\t\t\t}\r\n\t\t\telse if (!prevPulseWasPositive && item[first] == '-')\r\n\t\t\t{\r\n\t\t\t\titem[first] = '+';\r\n\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t\tnumAmiViolations++;\r\n\t\t\t}\r\n\t\t\telse if (prevPulseWasPositive && item[first] == '-')\r\n\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\telse if (!prevPulseWasPositive && item[first] == '+')\r\n\t\t\t\tprevPulseWasPositive = true;\r\n\t\t}\r\n\t\treturn item;\r\n\t}\r\n\r\n\t//determines if given number is odd\r\n\tbool isOdd(int num)\r\n\t{\r\n\t\tif (num % 2 == 1)\r\n\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t//decodes given string from HDB3 to binary string\r\n\tstring DecodeFromHDB3(string item)\r\n\t{\r\n\t\tbool prevPulseWasPositive = false;\r\n\r\n\t\tfor (int i = 0; i < item.length(); i++)\r\n\t\t{\r\n\t\t\tif (i == 0 && item.length() >= 4 && item.substr(i, 4) == \"000+\")\r\n\t\t\t{\r\n\t\t\t\titem[i + 3] = '1';\r\n\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (item[i] == '+')\r\n\t\t\t{\r\n\t\t\t\tif (item.substr(i, 4) != \"+00+\")\r\n\t\t\t\t\titem[i] = '1';\r\n\t\t\t\telse if (item.length() - i >= 4 && (item[i] == '+' && item.substr(i, 4) == \"+00+\"))\r\n\t\t\t\t{\r\n\t\t\t\t\titem.replace(i, 4, \"0000\");\r\n\t\t\t\t\ti += 3;\r\n\t\t\t\t}\r\n\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t}\r\n\t\t\telse if (item[i] == '-')\r\n\t\t\t{\r\n\t\t\t\tif (item.substr(i, 4) != \"-00-\")\r\n\t\t\t\t\titem[i] = '1';\r\n\t\t\t\telse if (item.length() - i >= 4 && (item[i] == '-' && item.substr(i, 4) == \"-00-\"))\r\n\t\t\t\t{\r\n\t\t\t\t\titem.replace(i, 4, \"0000\");\r\n\t\t\t\t\ti += 3;\r\n\t\t\t\t}\r\n\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\t}\r\n\t\t\telse if (item[i] == '0' && item.length() - i >= 4)\r\n\t\t\t{\r\n\t\t\t\tif (prevPulseWasPositive && item.substr(i, 4) == \"000+\")\r\n\t\t\t\t{\r\n\t\t\t\t\titem.replace(i, 4, \"0000\");\r\n\t\t\t\t\ti += 3;\r\n\t\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t\t}\r\n\t\t\t\telse if (!prevPulseWasPositive && item.substr(i, 4) == \"000-\")\r\n\t\t\t\t{\r\n\t\t\t\t\titem.replace(i, 4, \"0000\");\r\n\t\t\t\t\ti += 3;\r\n\t\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\t\t}\r\n\t\t\t\telse if (!prevPulseWasPositive && item.substr(i, 4) == \"000+\")\r\n\t\t\t\t{\r\n\t\t\t\t\titem.replace(i, 4, \"0001\");\r\n\t\t\t\t\ti += 3;\r\n\t\t\t\t\tprevPulseWasPositive = true;\r\n\t\t\t\t}\r\n\t\t\t\telse if (prevPulseWasPositive && item.substr(i, 4) == \"000-\")\r\n\t\t\t\t{\r\n\t\t\t\t\titem.replace(i, 4, \"0001\");\r\n\t\t\t\t\ti += 3;\r\n\t\t\t\t\tprevPulseWasPositive = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn item;\r\n\t}\r\n};", "meta": {"hexsha": "a4624459cec79cb6de2b26730646924e88892344", "size": 5846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Server/HDB3Parser.cpp", "max_stars_repo_name": "dsilva609/Client-Server", "max_stars_repo_head_hexsha": "0fd0b3e94517434404f0527da7e7fcb97ee6521f", "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": "Server/HDB3Parser.cpp", "max_issues_repo_name": "dsilva609/Client-Server", "max_issues_repo_head_hexsha": "0fd0b3e94517434404f0527da7e7fcb97ee6521f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Server/HDB3Parser.cpp", "max_forks_repo_name": "dsilva609/Client-Server", "max_forks_repo_head_hexsha": "0fd0b3e94517434404f0527da7e7fcb97ee6521f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6589147287, "max_line_length": 88, "alphanum_fraction": 0.5612384536, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.03410042399448255, "lm_q1q2_score": 0.0076868021753775054}}
{"text": "// This file is part of sibilla : inference in epidemics with Belief Propagation\n// Author: Alfredo Braunstein\n\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl_bind.h>\n#include <pybind11/stl.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pytypes.h>\n#include <pybind11/iostream.h>\n#include <string>\n#include <sstream>\n#include <numeric>\n#include <boost/lexical_cast.hpp>\n#include <iterator>\n#include <exception>\n#include \"bp.h\"\n#include \"mf.h\"\n\n\n\ntypedef NodeType<BPMes> Node;\ntypedef NeighType<BPMes> Neigh;\n\nPYBIND11_MAKE_OPAQUE(std::valarray<real_t>);\nPYBIND11_MAKE_OPAQUE(std::vector<real_t>);\nPYBIND11_MAKE_OPAQUE(std::vector<int>);\nPYBIND11_MAKE_OPAQUE(std::vector<Node>);\n\nnamespace py = pybind11;\nusing namespace std;\nusing boost::lexical_cast;\n\n\n\n\n\nvector<real_t> make_vector(py::list & l)\n{\n    vector<real_t> v(l.size());\n    int i = 0;\n    for (py::handle o : l) {\n        v[i++] = py::cast<real_t>(o);\n    }\n    return v;\n}\n\nmap<int, vector<times_t> >\nget_times(BPGraph const & f) {\n        map<int, vector<times_t> > times;\n        for (int i = 0; i < int(f.nodes.size()); ++i) {\n            times[i] = f.nodes[i].times;\n            times[i].pop_back();\n        }\n        return times;\n}\n\nvector<tuple<real_t, real_t, real_t>>\nget_marginal(Node const & n)\n{\n        vector<real_t> rbt(n.bt.size());\n        vector<real_t> lbg(n.bg.size());\n        int const T = n.bt.size() - 1;\n        lbg[0] = n.bg[0];\n        rbt[T] = n.bt[T];\n        for (int t = 1; t <= T; ++t) {\n            lbg[t] = lbg[t-1] + n.bg[t];\n            rbt[T - t] = rbt[T - t + 1] + n.bt[T - t];\n        }\n        auto marg = vector<tuple<real_t, real_t, real_t>>(T-1);\n        for (int t = 1; t < T; ++t)\n            marg[t-1] = make_tuple(rbt[t], 1-rbt[t]-lbg[t-1], lbg[t-1]);\n        return marg;\n}\n\ntuple<real_t, real_t, real_t> get_marginal_index(Node const & n, int t)\n{\n        if (t < 0 || t >= int(n.bt.size()) - 2)\n            throw py::key_error(\"Time out of range\");\n        return get_marginal(n)[t];\n}\n\n\n\nvoid check_index(BPGraph const & G, int i)\n{\n        if (i < 0 || i >= int(G.nodes.size()))\n                throw invalid_argument(\"unexistent index\");\n\n}\n\n\ntemplate<int i>\nreal_t mygetter(Proba & p)\n{\n    return p.theta[i];\n}\n\ntemplate<int i>\nvoid mysetter(Proba & p, real_t x)\n{\n    p.theta[i] = x;\n}\n\ntemplate<class TMes>\nvoid init_factorgraph(py::module & m)\n{\n    py::class_<FactorGraph<TMes>>(m, FactorGraph<TMes>::name(), \"SIB class representing the graphical model of the epidemics\")\n        .def(py::init<Params const &,\n                vector<tuple<int,int,times_t,real_t>>,\n                vector<tuple<int,int,times_t>>,\n                vector<tuple<int,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>>>\n                >(),\n                py::arg(\"params\") = Params(shared_ptr<Proba>(new Uniform(1.0)), shared_ptr<Proba>(new Exponential(0.5)), 0.1, 0.45, 0.0, 0.0, 0.0, 0.0),\n                py::arg(\"contacts\") = vector<tuple<int,int,times_t,real_t>>(),\n                py::arg(\"observations\") = vector<tuple<int,int,times_t>>(),\n                py::arg(\"individuals\") = vector<tuple<int,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>,shared_ptr<Proba>>>())\n        .def(\"update\", &FactorGraph<TMes>::iteration,\n                py::arg(\"damping\") = 0.0,\n                py::arg(\"learn\") = false,\n                \"perform one iteration\")\n        .def(\"loglikelihood\", &FactorGraph<TMes>::loglikelihood, \"compute the bethe log-likelihood\")\n        .def(\"__repr__\", &lexical_cast<string, FactorGraph<TMes>>)\n        .def(\"append_contact\", (void (FactorGraph<TMes>::*)(int,int,times_t,real_t,real_t)) &FactorGraph<TMes>::append_contact,\n                py::arg(\"i\"),\n                py::arg(\"j\"),\n                py::arg(\"t\"),\n                py::arg(\"lambdaij\"),\n                py::arg(\"lambdaji\") = real_t(FactorGraph<TMes>::DO_NOT_OVERWRITE),\n                \"appends a new contact from i to j at time t with transmission probabilities lambdaij, lambdaji\")\n        .def(\"reset_observations\", &FactorGraph<TMes>::reset_observations,\n                py::arg(\"obs\"),\n                \"resets all observations\")\n        .def(\"append_observation\", &FactorGraph<TMes>::append_observation,\n                py::arg(\"i\"),\n                py::arg(\"s\"),\n                py::arg(\"t\"),\n                \"appends a new observation with state s to node i at time t\")\n        .def(\"show\", &FactorGraph<TMes>::show_graph)\n        .def(\"drop_contacts\", &FactorGraph<TMes>::drop_contacts, \"drop contacts at time t (first time)\")\n        .def(\"drop_time\", &drop_time<BPMes>, \"drop time t (first time)\")\n        .def(\"showmsg\", [](FactorGraph<TMes> & f){f.show_msg(std::cout);}, \"show messages for debugging\")\n        .def_readonly(\"nodes\", &FactorGraph<TMes>::nodes, \"all nodes in this FactorGraph<TMes>\")\n        .def_readonly(\"params\", &FactorGraph<TMes>::params, \"parameters\");\n\n    py::class_<NodeType<TMes>>(m, NodeType<TMes>::name(), \"SIB class representing an individual\")\n        .def(\"marginal\", &get_marginal, \"compute marginal probabilities (pS,pI,pR) corresponding to times n.times[1:]\")\n        .def(\"marginal_index\", &get_marginal_index, \"marginal at a given time (excluding time -1)\")\n        .def_readwrite(\"ht\", &NodeType<TMes>::ht, \"external prior on ti\")\n        .def_readwrite(\"hg\", &NodeType<TMes>::hg, \"external prior on gi\")\n        .def_readonly(\"bt\", &NodeType<TMes>::bt, \"belief on ti\")\n        .def_readonly(\"bg\", &NodeType<TMes>::bg, \"belief on gi\")\n        .def_readonly(\"err\", &NodeType<TMes>::err_, \"error on update\")\n        .def_readonly(\"df_i\", &NodeType<TMes>::df_i, \"gradient on prior_i params\")\n        .def_readonly(\"df_r\", &NodeType<TMes>::df_r, \"gradient on prior_r params\")\n        .def_readonly(\"times\", &NodeType<TMes>::times, \"event times of this node\")\n        .def_readonly(\"index\", &NodeType<TMes>::index, \"node index (deprecated, do not use)\")\n        .def_readonly(\"prob_i\", &NodeType<TMes>::prob_i, \"probability of infection as function of t-ti\")\n        .def_readonly(\"prob_r\", &NodeType<TMes>::prob_r, \"cumulative probability of recovery P(tr>t)\")\n        .def_readonly(\"prob_i0\", &NodeType<TMes>::prob_i0, \"probability of infection as function of t-ti for ti=0\")\n        .def_readonly(\"prob_r0\", &NodeType<TMes>::prob_r0, \"cumulative probability of recovery P(tr>t) for ti=0\");\n\n}\n\nvoid init_realparams(py::module & m)\n{\n    py::class_<RealParams>(m, \"RealParams\", py::buffer_protocol())\n        .def(py::init([](py::buffer const b) {\n                py::buffer_info info = b.request();\n                if (info.format != py::format_descriptor<real_t>::format() || info.ndim != 1)\n                throw std::runtime_error(\"Incompatible buffer format!\");\n\n                auto v = new RealParams(info.shape[0]);\n                memcpy(&(*v)[0], info.ptr, sizeof(real_t) * (size_t) (v->size()));\n                return v;\n                }))\n        .def(py::init([](vector<real_t> const & p)->RealParams {return RealParams(&p[0], p.size());}))\n        .def(py::init([](py::list & l)->RealParams {auto v = make_vector(l); return RealParams(&v[0], v.size());}))\n        .def_buffer([](RealParams &p) -> py::buffer_info {\n            return py::buffer_info(\n                &p[0],                               /* Pointer to buffer */\n                sizeof(real_t),                          /* Size of one scalar */\n                py::format_descriptor<real_t>::format(), /* Python struct-style format descriptor */\n                1,                                      /* Number of dimensions */\n                { p.size() },                 /* Buffer dimensions */\n                { sizeof(real_t) }             /* Strides (in bytes) for each index */\n                );\n        })\n        .def(\"__add__\", [](RealParams & p, RealParams & q)->RealParams { return p + q; })\n        .def(\"__getitem__\", [](const RealParams &p, ssize_t i) {\n                if (i > int(p.size()))\n                    throw py::index_error();\n                return p[i];\n                })\n        .def(\"__setitem__\", [](RealParams &p, ssize_t i, real_t v) {\n                if (i > int(p.size()))\n                    throw py::index_error();\n                p[i] = v;\n                })\n        .def(\"__repr__\", [](RealParams &p) {\n                    string s = \"RealParams([\";\n                    for (size_t i = 0; i < p.size(); ++i)\n                        s += (i ? \",\":\"\") + lexical_cast<string>(p[i]);\n                    s+=\"])\";\n                    return s;\n                });\n}\n\nvoid init_proba(py::module & m)\n{\n    py::class_<Proba, shared_ptr<Proba>>(m, \"Proba\")\n        .def(\"__call__\", [](Proba const & p, real_t d) { return p(d); } )\n        .def(\"grad\", [](Proba const & p, real_t d) { RealParams dtheta(0.0, p.theta.size()); p.grad(dtheta, d); return dtheta;} )\n        .def(\"__repr__\", &lexical_cast<string, Proba>)\n        .def_readwrite(\"theta\", &Proba::theta);\n\n    py::class_<Uniform, Proba, shared_ptr<Uniform>>(m, \"Uniform\")\n        .def(py::init<real_t>(), py::arg(\"p\") = 1.0)\n        .def_property(\"p\", &mygetter<0>, &mysetter<0>);\n\n    py::class_<Exponential, Proba, shared_ptr<Exponential>>(m, \"Exponential\")\n        .def(py::init<real_t>(), py::arg(\"mu\") = 0.1)\n        .def_property(\"mu\", &mygetter<0>, &mysetter<0>);\n\n    py::class_<Gamma, Proba, shared_ptr<Gamma>>(m, \"Gamma\")\n        .def(py::init<real_t, real_t>(), py::arg(\"k\") = 1.0, py::arg(\"mu\") = 0.1)\n        .def_property(\"k\", &mygetter<0>, &mysetter<0>)\n        .def_property(\"mu\", &mygetter<1>, &mysetter<1>);\n\n    py::class_<UnnormalizedGammaPDF, Proba, shared_ptr<UnnormalizedGammaPDF>>(m, \"UnnormalizedGammaPDF\")\n        .def(py::init<real_t, real_t>(), py::arg(\"k\") = 1.0, py::arg(\"mu\") = 0.1)\n        .def_property(\"k\", &mygetter<0>, &mysetter<0>)\n        .def_property(\"mu\", &mygetter<1>, &mysetter<1>);\n    py::class_<PiecewiseLinear, Proba, shared_ptr<PiecewiseLinear>>(m, \"PiecewiseLinear\")\n        .def(py::init<RealParams const &, real_t>(), py::arg(\"theta\"), py::arg(\"step\") = 1.0)\n        .def(py::init<Proba const &, int, real_t>(), py::arg(\"prob\"), py::arg(\"num\"), py::arg(\"step\") = 1.0);\n\n    py::class_<Cached, Proba, shared_ptr<Cached>>(m, \"Cached\")\n        .def(py::init<std::shared_ptr<Proba> const &, int>(), py::arg(\"prob\"), py::arg(\"T\"))\n        .def_property(\"theta\", &Cached::get_theta, &Cached::set_theta);\n\n    py::class_<Scaled, Proba, shared_ptr<Scaled>>(m, \"Scaled\")\n        .def(py::init<std::shared_ptr<Proba> const &, real_t>(), py::arg(\"prob\"), py::arg(\"scale\") = 1.0);\n\n    py::class_<PDF, Proba, shared_ptr<PDF>>(m, \"PDF\")\n        .def(py::init<std::shared_ptr<Proba> const &>());\n\n}\n\nvoid init_params(py::module & m)\n{\n    py::class_<Params>(m, \"Params\")\n        .def(py::init<shared_ptr<Proba> const &, shared_ptr<Proba> const &, real_t, real_t, real_t, real_t, real_t, real_t>(),\n                \"SIB Params class. prob_i and prob_r parameters are defaults.\",\n                py::arg(\"prob_i\") = *new Uniform(1.0),\n                py::arg(\"prob_r\") = *new Exponential(0.1),\n                py::arg(\"pseed\") = 0.01,\n                py::arg(\"psus\") = 0.5,\n                py::arg(\"fp_rate\") = 0.0,\n                py::arg(\"fn_rate\") = 0.0,\n                py::arg(\"pautoinf\") = 0.0,\n                py::arg(\"learn_rate\") = 0.0)\n\n        .def_readwrite(\"prob_r\", &Params::prob_r)\n        .def_readwrite(\"prob_i\", &Params::prob_i)\n        .def_readwrite(\"pseed\", &Params::pseed)\n        .def_readwrite(\"psus\", &Params::psus)\n        .def_readwrite(\"fp_rate\", &Params::fp_rate)\n        .def_readwrite(\"fn_rate\", &Params::fn_rate)\n        .def_readwrite(\"pautoinf\", &Params::pautoinf)\n        .def_readwrite(\"learn_rate\", &Params::learn_rate)\n        .def(\"__repr__\", &lexical_cast<string, Params>);\n}\n\n\nPYBIND11_MODULE(_sib, m) {\n    init_realparams(m);\n    init_proba(m);\n    // py::add_ostream_redirect(m, \"ostream_redirect\");\n    py::bind_vector<std::vector<int>>(m, \"VectorInt\");\n    py::bind_vector<std::vector<real_t>>(m, \"VectorReal\");\n    py::bind_vector<std::vector<Node>>(m, \"VectorNode\");\n\n    init_params(m);\n    init_factorgraph<BPMes>(m);\n    init_factorgraph<MFMes>(m);\n\n    m.def(\"set_num_threads\", &omp_set_num_threads, \"sets the maximum number of simultaneous cpu threads\");\n    m.def(\"version\", [](){return VERSION;}, \"compiled version of sib\");\n}\n", "meta": {"hexsha": "973aa2e49d82201e5d3b54e102aabd0b5cf40e14", "size": 12368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pysib.cpp", "max_stars_repo_name": "abraunst/sib", "max_stars_repo_head_hexsha": "bf08edb829e9419c6bdfc353dd7141b11f956d74", "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": "pysib.cpp", "max_issues_repo_name": "abraunst/sib", "max_issues_repo_head_hexsha": "bf08edb829e9419c6bdfc353dd7141b11f956d74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pysib.cpp", "max_forks_repo_name": "abraunst/sib", "max_forks_repo_head_hexsha": "bf08edb829e9419c6bdfc353dd7141b11f956d74", "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.5017182131, "max_line_length": 152, "alphanum_fraction": 0.5685640362, "num_tokens": 3529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.023689470093140645, "lm_q1q2_score": 0.007680964787296797}}
{"text": "// **************************************************************************************************\n//\n// The MIT License (MIT)\n// \n// Copyright (c) 2017 Pierre Lebreton\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and \n// associated documentation files (the \"Software\"), to deal in the Software without restriction, including \n// without limitation the rights 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 furnished to do so, subject to the \n// following conditions:\n// \n// The above copyright notice and this permission notice shall be included in all copies or substantial \n// portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT \n// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n// IN NO EVENT SHALL THE 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 CONNECTION WITH THE \n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// **************************************************************************************************\n\n\n\n\n#include \"GBVS360.h\"\n\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <iostream>\n#include <limits>\n#include <set>\n#include <boost/thread.hpp>\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <stdlib.h>  \n#include <time.h>\n\n#include <HMDSim.h>\n#include <VPD.h>\n\n#include \"Projection.h\"\n#include \"Options.h\"\n#include \"CSVReader.h\"\n\n#define STUDY_FIX_PREDICTION 1\n\nGBVS360::GBVS360(boost::shared_ptr<Projection> projection) {\n\tm_Projection = projection;\n\n\tblurfrac\t\t= 0.02f;\n\tsalmapmaxsize \t= 60;\n\tfeatureScaling\t= 1.0f;\n\thmdMode = false;\n}\n\n\nvoid GBVS360::compute(const cv::Mat& input, cv::Mat &output, bool normalize) {\n\n\tassert(input.channels() == 3 && input.type() == CV_8UC3);\n\n\tnbThreads = std::max<int>(2, static_cast<int>(Option::threads / 3.f));\n\n\t// reset the framework.... \n\tm_ProjectedFrames.clear();\n\tfeatureDone.clear();\n\tm_GBVSWorkers.clear();\n\tclear(); \t\t\t\t\t// reset GBVS features and keep init done. \n\n\tm_InputImage = input;\n\t\n\t// Let's start the analysis\n\tm_EquirectangularFrameSize = input.size();\n\t\n\n\tstd::cout << \"[I] Init graph framework -- scheduled\" << std::endl;\n\tboost::thread_group group;\n\tgroup.create_thread(boost::bind(&GBVS360::initGBVS, this, boost::ref(input)));\n\n\tstd::cout << \"[I] Getting rectilinear frames\" << std::endl;\n\tgetRectilinearFrames(input);\n\n\t// get feature maps for each equililnear frame\n\tstd::cout << \"[I] Getting features per frame\" << std::endl;\n\tgetRectilinearFeatures();\n\n\t// back project feature maps to equirectangular coordinate\n\tstd::cout << \"[I] Getting back-projected features\" << std::endl;\n\tgetEquirectangularFeatures();\n\n\n\tstd::cout << \"[I] Waiting graph initialization to finish\" << std::endl;\n\tgroup.join_all();\n\n\t\n\tstd::cout << \"[I] Applying GBVS Activation, Normalization & Pooling\" << std::endl;\n\n\t// GBVS regular flow\n\tgbvsActivation(input, output, normalize);\n\n\n\tif(equatorialPrior) {\n\t\tapplyEquatorialPrior(output, input);\n\n\t\tif(normalize) {\n\t\t\tdouble mn, mx;\n\t\t\tcv::minMaxLoc(output, &mn, &mx);\n\t\t\toutput = (output - mn) / (mx - mn);\n\t\t}\n\t\t\n\t}\n\t\n\n\tif (Option::exportRawFeatures) {\n\t\tfor (std::list<FeatureMap>::const_iterator it = allmaps.begin(); it != allmaps.end(); ++it) {\n\t\t\tFILE *f = fopen((Option::prefix + \"_\" + boost::lexical_cast<std::string>(it->channel) + \"_\" + boost::lexical_cast<std::string>(it->level) + \"_\" + boost::lexical_cast<std::string>(it->type) + \".csv\").c_str(), \"w\");\n\t\t\tif (f == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < it->map.rows; ++i) {\n\t\t\t\tfor (int j = 0; j < it->map.cols-1; ++j) {\n\t\t\t\t\tfprintf(f, \"%20.20lf, \", it->map.at<double>(i, j));\n\t\t\t\t}\n\t\t\t\tfprintf(f, \"%20.20lf\\n\", it->map.at<double>(i, it->map.cols - 1));\n\t\t\t}\n\n\t\t\tfclose(f);\n\t\t}\n\t}\n\n}\n\n\n\n\n\nstruct FixationOptionComparison {\n\tbool operator()(const FixationOption &a, const FixationOption &b) const {\n\t\tif(std::abs(a.value - b.value) < 0.000000001f) {\n\t\t\tif (std::abs(a.probability - b.probability) < 0.000000001f) {\n\t\t\t\tif(a.x == b.x) {\n\t\t\t\t\treturn a.y < b.y;\n\t\t\t\t} else {\n\t\t\t\t\treturn a.x < b.x;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn (a.probability < b.probability);\n\t\t\t}\n\t\t}\n\t\treturn a.value < b.value;\n\t}\n};\n\n\nstruct FixationOptionComparison2 {\n\tbool operator()(const FixationOption &a, const FixationOption &b) const {\n\t\tif (std::abs(a.probability - b.probability) < 0.000000001f) {\n\t\t\tif(std::abs(a.value - b.value) < 0.000000001f) {\n\t\t\t\tif(a.x == b.x) {\n\t\t\t\t\treturn a.y < b.y;\n\t\t\t\t} else {\n\t\t\t\t\treturn a.x < b.x;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn a.value < b.value;\n\t\t\t}\n\t\t}\n\t\treturn (a.probability < b.probability);\n\t\t\n\t}\n};\n\n\ntypedef std::set<FixationOption, FixationOptionComparison2> TFixationsSet;\n\n\nvoid GBVS360::scanPath(const cv::Mat& imgBGR, cv::Mat &out, bool inputSaliencyMap) {\n\n\t// -------------------------------------------------------------------------------------------\n\t// First, we need the saliency map\n\n\n\t// if the input provided is not already a saliency map, then compute it using the GBVS360 framework\n\tif(!inputSaliencyMap) {\n\t\tcv::Mat saliency;\n\t\tcompute(imgBGR, saliency);\n\t}\n\n\n\t// Check if the GBVS360 framework was initialized (it is the case if it computed the saliency map, it was provided as input the initialization is required)\n\tif(!initDone)\n\t\tinitGBVS(imgBGR);\n\n\n\tCSVReader<float> csv;\n\tif(!Option::scanPath.empty()) {\n\t\tif(!csv.open(Option::scanPath)) {\n\t\t\tstd::cout << \"[I] cannot open csv file: \" << Option::scanPath << std::endl;\n\t\t}\n\t}\n\n\tstd::vector<FixationOption> groundTruthFixations;\n\tif(csv.getCols() > 0) {\n\t\tint obsIdx = -1;\n\t\tfor(size_t i = 0 ; i < csv[0].size() ; ++i) {\n\t\t\tif(csv[0][i] == 1) {\n\t\t\t\t++obsIdx;\n\t\t\t}\n\n\t\t\tif(obsIdx == Option::scanPathUserIdx) {\n\t\t\t\tFixationOption f;\n\t\t\t\tf.x = static_cast<int>(csv[2][i]);\n\t\t\t\tf.y = static_cast<int>(csv[3][i]);\n\t\t\t\tf.value = csv[0][i];\n\t\t\t\tf.probability = csv[1][i];\n\n\t\t\t\tgroundTruthFixations.push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// Check the input: if a saliency map was provided, it can be in BGR or gayscale. \n\tcv::Mat saliency;\n\tif(inputSaliencyMap) {\n\t\tsaliency = imgBGR.clone();\n\t\tif(imgBGR.channels() == 3 && imgBGR.type() == CV_8UC3) {\n\t\t\tcv::cvtColor(saliency, saliency, cv::COLOR_BGR2GRAY);\n\t\t\tsaliency.convertTo(saliency, CV_64FC1);\n\t\t\tsaliency /= 255;\n\t\t} else {\n\t\t\tsaliency.convertTo(saliency, CV_64FC1);\n\t\t}\n\t\t\n\n\t\tcv::resize(saliency, master_map, cv::Size(salmapmaxsize_v[1], salmapmaxsize_v[0]), 0, 0, cv::INTER_AREA);\n\t}\n\n#ifdef STUDY_FIX_PREDICTION\n\n\tcv::resize(saliency, saliency, saliency.size()/5, 0, 0, cv::INTER_AREA);\n\n#endif\n\n\t// -------------------------------------------------------------------------------------------\n\t// prepare the state transition matrix\n\n\tconst cv::Mat &lx = grframe.lx;\n\n\t// form a multiresolution pyramid of feature maps according to multilevels\n\tstd::vector<cv::Mat> apyr;\n\tstd::vector< std::pair<int, int> > dims;\n\tformMapPyramid(master_map, grframe.multilevels, apyr, dims);\n\n\t// assign a linear index to each node\n\tstd::vector<double> AL;\n\tarrangeLinear(apyr , dims, AL);\n\n\t// create the state transition matrix between nodes\n\tcv::Mat mm(lx.rows, lx.rows, CV_64FC1, cv::Scalar(0.f)); \n\n\t// assign edge weights based on distances between nodes and algtype\n\t\n\tfor(int c = 0 ; c < static_cast<int>(AL.size()) ; ++c) {\n\t\tfor(int r = 0 ; r < static_cast<int>(AL.size()) ; ++r) {\n\t\t\tmm.at<double>(r,c) =  std::abs( AL[r] - AL[c] );\n\t\t}\n\t}\n\n\t// make it a markov matrix (so each column sums to 1)\n\tcolumnNormalize(mm);\n\n\t// inverse the weight, as we want to convert normalized distance to probability of transition\n\t// two elements with a distance of 0 should have a high chance to be connected \n\tmm = 1 - mm;\n\n\t\n\t// -------------------------------------------------------------------------------------------\n\t// Use the state transition matrix to predict scan path\n\t\n\tsrand(time(NULL));\n\n#ifdef STUDY_FIX_PREDICTION\n\n\tsaliency.convertTo(saliency, CV_32FC3);\n\n#endif\n\t\n\tout = cv::Mat(Option::numberFixations * Option::experimentRepppetition, 4, CV_32FC1, cv::Scalar(0.f));\n\tfor(int i = 0 ; i < Option::experimentRepppetition ; ++i) {\n\t\tint initPosition = static_cast<int>((i * static_cast<float>(master_map.cols) / static_cast<float>(Option::experimentRepppetition)) * master_map.rows + master_map.rows / 2);\n\t\tcv::Mat result = runScanPath(saliency, imgBGR, groundTruthFixations, lx, mm, initPosition);\n\n\t\tfor(int ii = 0 ; ii < result.rows ; ++ii) {\n\t\t\tfor(int jj = 0 ; jj < result.cols ; ++jj) {\n\t\t\t\tout.at<float>(i*Option::numberFixations + ii, jj) = result.at<float>(ii,jj);\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\n\n\nvoid GBVS360::getTransitionMatrix(const cv::Mat &lx, const cv::Mat &mm, cv::Mat &distanceMatrix, int position, float scaling) const {\n\tdouble sig = sigma_frac_act * static_cast<double>(master_map.cols + master_map.rows)/2.f;\n\n\tfor(int l = 0 ; l < lx.rows ; ++l) {\n\t\tdistanceMatrix.at<float>(l % master_map.rows, l / master_map.rows) = static_cast<float>(mm.at<double>(l, position)); //\n\t}\n\n\tdouble mx, mn;\n\tcv::minMaxLoc(distanceMatrix, &mn, &mx);\n\n\tdistanceMatrix = (distanceMatrix - mn) / (mx - mn);\n\n\tfor(int l = 0 ; l < lx.rows ; ++l) {\n\n\t\tfloat distX = static_cast<float>(std::min( std::abs((l / master_map.rows)  -  (position / master_map.rows)) , std::abs( std::abs((l / master_map.rows)  -  (position / master_map.rows)) - master_map.cols ) ));\n\t\tfloat distY = static_cast<float>(std::min( std::abs((l % master_map.rows)  -  (position % master_map.rows)) , std::abs( std::abs((l % master_map.rows)  -  (position % master_map.rows)) - master_map.rows ) ));\n\t\tfloat dist = (distX*distX + distY*distY);\n\n\t\tdistanceMatrix.at<float>(l % master_map.rows, l / master_map.rows) = static_cast<float>(std::exp( -1 *( dist / scaling ) / (2 * sig*sig)) * distanceMatrix.at<float>(l % master_map.rows, l / master_map.rows)); //\n\t}\n\n\tdistanceMatrix = distanceMatrix * (mx - mn) + mn;\n}\n\n\n#ifdef STUDY_FIX_PREDICTION\ncv::Mat GBVS360::runScanPath(const cv::Mat& saliency, const cv::Mat& imgBGR, const std::vector<FixationOption>& groundTruthFixations, const cv::Mat &lx, const cv::Mat &mm, int initPosition) {\n#else\ncv::Mat GBVS360::runScanPath(const cv::Mat& , const cv::Mat& imgBGR, const std::vector<FixationOption>& , const cv::Mat &lx, const cv::Mat &mm, int initPosition) {\n#endif\n\n\tcv::Mat out = cv::Mat(Option::numberFixations, 4, CV_32FC1, cv::Scalar(0.f));\n\n\t// start from the center\n\tint position = initPosition;\n\n\n#ifdef STUDY_FIX_PREDICTION\n\n\tfloat scaling = static_cast<float>(saliency.cols / master_map.cols);\n\n\n\tcv::Mat saliency2 = saliency.clone();\n\n#endif\n\n\t// if start from a non salient area, find one.\n\tif(master_map.at<double>(position % master_map.rows, position / master_map.rows) < 0.7) {\n\t\tfloat localMax = 0;\n\t\tint pos_x = position % master_map.cols;\n\n\t\tfor(int ii = master_map.rows/3 ; ii < master_map.rows - master_map.rows/3 ; ++ii) {\n\t\t\tfor(int jj = std::max(0, pos_x-master_map.cols/6) ; jj < std::min(master_map.cols/6, pos_x+master_map.cols/6) ; ++jj) {\n\t\t\t\t\n\t\t\t\tif(master_map.at<double>(ii,jj) > localMax) {\n\t\t\t\t\tposition = jj * master_map.rows + ii;\n\t\t\t\t\tlocalMax = static_cast<float>(master_map.at<double>(ii,jj));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif((pos_x-master_map.cols/6) < 0) {\n\t\t\t\tfor(int jj = master_map.cols + (pos_x-master_map.cols/6) ; jj < master_map.cols ; ++jj) {\n\t\t\t\t\n\t\t\t\t\tif(master_map.at<double>(ii,jj) > localMax) {\n\t\t\t\t\t\tposition = jj * master_map.rows + ii;\n\t\t\t\t\t\tlocalMax = static_cast<float>(master_map.at<double>(ii,jj));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif((pos_x+master_map.cols/6) > master_map.cols) {\n\t\t\t\tfor(int jj = 0 ; jj < (pos_x+master_map.cols/6) - master_map.cols ; ++jj) {\n\t\t\t\t\n\t\t\t\t\tif(master_map.at<double>(ii,jj) > localMax) {\n\t\t\t\t\t\tposition = jj * master_map.rows + ii;\n\t\t\t\t\t\tlocalMax = static_cast<float>(master_map.at<double>(ii,jj));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t}\n\t}\n\t\t\n\t// find local maxiam\n\t{\n\t\tint lx = position / master_map.rows;\n\t\tint ly = position % master_map.rows;\n\n\t\tint plx = -1;\n\t\tint ply = -1;\n\t\twhile(plx != lx && ply != ly) {\n\t\t\tplx = lx; ply = ly;\n\t\t\tif((lx + 1 < master_map.cols) && master_map.at<double>(ly, lx+1) > master_map.at<double>(ly, lx)) {\n\t\t\t\t++lx;\n\t\t\t}\n\t\t\tif((lx - 1 > 0) && master_map.at<double>(ly, lx-1) > master_map.at<double>(ly, lx)) {\n\t\t\t\t--lx;\n\t\t\t}\n\t\t\tif((ly + 1 < master_map.rows) && master_map.at<double>(ly+1, lx) > master_map.at<double>(ly, lx)) {\n\t\t\t\t++ly;\n\t\t\t}\n\t\t\tif((ly - 1 > 0) && master_map.at<double>(ly-1, lx) > master_map.at<double>(ly, lx)) {\n\t\t\t\t--ly;\n\t\t\t}\n\t\t}\n\n\t\tposition = lx * master_map.rows + ly;\n\t}\n\n\n\n\n\tdouble smx, smn;\n\tcv::minMaxLoc(master_map, &smn, &smx);\n\n\n\tstd::list<cv::Point2i> fixationHistory;\n\tfixationHistory.push_back(cv::Point2i(position / master_map.rows, position % master_map.rows));\n\n\tcv::Mat distanceMatrix(master_map.size(), CV_32FC1, cv::Scalar(0));\n\tfor(int i = 0 ; i < Option::numberFixations ; ++i) {\n\t\t// lookup the transition probability for all other points\n\n\n\t\tgetTransitionMatrix(lx, mm, distanceMatrix, position, 1);\n\n\t\tdouble mx, mn;\n\t\tcv::minMaxLoc(distanceMatrix, &mn, &mx);\n\n\t\tdouble localThreshold = mn + (mx - mn) * 0.9;\n\n\t\tint nextX = 0;\n\t\tint nextY = 0;\n\t\tTFixationsSet fixations;\n\t\tint nbIter = 0;\n\t\tint nbIter2 = 0;\n\t\tfloat salRequired = static_cast<float>(0.7 * smx);\n\t\twhile(fixations.empty() && nbIter != 15 && nbIter2 < 10) {\n\t\t\t\n\t\t\tfor(int ii = 0 ; ii < distanceMatrix.rows ; ++ii) {\n\t\t\t\tfor(int jj = 0 ; jj < distanceMatrix.cols ; ++jj) {\n\t\t\t\t\t\n\t\t\t\t\tif(distanceMatrix.at<float>(ii,jj) > localThreshold) {\n\n\t\t\t\t\t\tbool keep = true;\n\n\t\t\t\t\t\tint nbPrevious = 0;\n\t\t\t\t\t\tfor(std::list<cv::Point2i>::reverse_iterator it = fixationHistory.rbegin() ; it != fixationHistory.rend() && keep && nbPrevious < 20; ++it) {\n\t\t\t\t\t\t\tif(it->x == jj && it->y == ii) {\n\t\t\t\t\t\t\t\tkeep = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t++nbPrevious;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(master_map.at<double>(ii,jj) < salRequired) keep = false;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(keep) {\n\t\t\t\t\t\t\tFixationOption f;\n\t\t\t\t\t\t\tf.x \t\t\t= jj;\n\t\t\t\t\t\t\tf.y \t\t\t= ii;\n\t\t\t\t\t\t\tf.value \t\t= static_cast<float>(master_map.at<double>(ii,jj));\n\t\t\t\t\t\t\tf.probability \t= distanceMatrix.at<float>(ii,jj);\n\n\t\t\t\t\t\t\tfixations.insert(f);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(fixations.empty()) {\n\t\t\t\tif(nbIter == 14) {\n\t\t\t\t\tsalRequired = static_cast<float>(0.1 * smx); // relax constrain, if we cannot find a suitable position\n\t\t\t\t\t++nbIter2; \t\t\t\t // make sure it will end.\n\t\t\t\t\tnbIter = 0;\n\t\t\t\t} else {\n\t\t\t\t\tsalRequired = static_cast<float>(0.5 * smx);\n\t\t\t\t}\n\t\t\t\t++nbIter;\n\t\t\t\tgetTransitionMatrix(lx, mm, distanceMatrix, position, 10.f * nbIter);\n\t\t\t}\n\t\t}\n\t\t\n\n\t\tint next_idx = rand() % 4;\n\n\t\t// if no fixation could be found, go to the most salient point nearby... \n\t\tif(fixations.empty()) {\n\t\t\tfloat localMax = 0;\n\t\t\tfor(int ii = 0 ; ii < distanceMatrix.rows ; ++ii) {\n\t\t\t\tfor(int jj = 0 ; jj < distanceMatrix.cols ; ++jj) {\n\t\t\t\t\t\n\t\t\t\t\tif(distanceMatrix.at<float>(ii,jj) > localMax) {\n\t\t\t\t\t\tif(!fixationHistory.empty() && fixationHistory.back().x == jj && fixationHistory.back().y == ii) continue;\n\t\t\t\t\t\tnextX = jj;\n\t\t\t\t\t\tnextY = ii;\n\t\t\t\t\t\tlocalMax = distanceMatrix.at<float>(ii,jj);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tFixationOption f;\n\t\t\tf.x \t\t\t= nextX;\n\t\t\tf.y \t\t\t= nextY;\n\t\t\tf.value \t\t= static_cast<float>(master_map.at<double>(nextY,nextX));\n\t\t\tf.probability \t= distanceMatrix.at<float>(nextY,nextX);\n\n\t\t\tfixations.insert(f);\n\t\t\t\n\t\t}\n\n\t\tTFixationsSet::reverse_iterator it = fixations.rbegin();\n\t\tif(next_idx == 0) {\n\t\t\tnextX = it->x;\n\t\t\tnextY = it->y;\n\t\t} else {\n\t\t\tTFixationsSet::reverse_iterator prev_it = it;\n\t\t\t++it;\n\n\t\t\tfor(int ii = 0 ; ii < next_idx && it != fixations.rend() ; ++ii) {\n\t\t\t\tprev_it = it;\n\t\t\t\t++it;\n\t\t\t}\n\n\t\t\tif(it != fixations.rend()) {\n\t\t\t\tnextX = it->x;\n\t\t\t\tnextY = it->y;\n\t\t\t} else {\n\t\t\t\tnextX = prev_it->x;\n\t\t\t\tnextY = prev_it->y;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfixationHistory.push_back(cv::Point2i(nextX, nextY));\n\n\t\tposition = nextX * distanceMatrix.rows + nextY;\n\n#ifdef STUDY_FIX_PREDICTION\n\n\t\tcv::circle(saliency2, cv::Point2i(scaling * nextX, scaling * nextY), 6, cv::Scalar(1,1,0));\n\n\t\tif(i < static_cast<int>(groundTruthFixations.size()))\n\t\t\tcv::circle(saliency2, cv::Point2i(saliency2.cols * groundTruthFixations[i].x / static_cast<float>(imgBGR.cols), saliency2.rows * groundTruthFixations[i].y / static_cast<float>(imgBGR.rows)), 3, cv::Scalar(1,1,0));\n\t\t\n\n\t\tcv::imshow(\"saliency\", saliency2);\n\t\tcv::waitKey();\n\n\t\tsaliency2 = saliency.clone();\n\n#endif\n\n\t\tout.at<float>(i, 2) = static_cast<float>(static_cast<int>(nextX * static_cast<float>(imgBGR.cols) / static_cast<float>(master_map.cols)));\n\t\tout.at<float>(i, 3) = static_cast<float>(static_cast<int>(nextY * static_cast<float>(imgBGR.cols) / static_cast<float>(master_map.cols)));\n\t\tout.at<float>(i, 1) = fixations.rbegin()->value;\n\t\tout.at<float>(i, 0) = static_cast<float>(i);\n\t}\n\n\tfloat sumProb = 0;\n\tfor(int i = 1 ; i < out.rows ; ++i) {\n\t\tsumProb += out.at<float>(i, 1);\n\t}\n\n\tout.at<float>(0, 1) = 0;\n\tfor(int i = 1 ; i < out.rows ; ++i) {\n\t\tout.at<float>(i, 1) = out.at<float>(i-1, 1) + Option::experimentLength * out.at<float>(i, 1) / sumProb;\n\t}\n\n\treturn out;\n}\n\n\n\n// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\nvoid GBVS360::getRectilinearFrames(const cv::Mat &inputImage) {\n\tif(!m_Projection) {\n\t\tstd::logic_error(std::string(\"Saliency360::getEquilinarFrames: The projection model was not allocated. Quit\"));;\n\t\treturn;\n\t}\n\n\n\tif(m_Projection->nreWidth == 0 || m_Projection->nreHeight == 0) {\n\t\tm_Projection->nreWidth = inputImage.cols;\n\t\tm_Projection->nreHeight = inputImage.rows;\n\t}\n\n\n\tfloat scaling_x = 2;\n\tfloat scaling_y = 1;\n\n\n\tint nb_projections_w = static_cast<int>(std::ceil(360.f / static_cast<float>(m_Projection->nrApper/scaling_x)));\n\tint nb_projections_h = static_cast<int>(std::ceil(180.f / static_cast<float>(m_Projection->nrApper/scaling_y)));\n\n\n\t// prepare all the projections: what needs to be done.\n\tfor(int j = -nb_projections_h / 2 ; j <= nb_projections_h/2 ; ++j) { // for(int j = -nb_projections_h / 2 -1 ; j <= nb_projections_h/2 + 1; ++j) {\n\t\tfor(int i = 0 ; i < nb_projections_w ; ++i) {\n\n\t\t\tm_ProjectedFrames.push_back(ProjectedFrame());\n\t\t\tProjectedFrame &frame = m_ProjectedFrames.back();\n\n\t\t\tframe.rectilinearFrame = cv::Mat(m_Projection->nrrHeight, m_Projection->nrrWidth, CV_8UC3, inputImage.channels());\n\t\t\tif(frame.rectilinearFrame.empty()) {\n\t\t\t\tthrow std::logic_error(std::string(\"Saliency360::getRectilinearFrames bad alloc...\"));\n\t\t\t\treturn ;\n\t\t\t}\n\n\t\t\t// frame.nrElev = static_cast<int>(j * m_Projection->nrApper/scaling_x);\n\t\t\t// frame.nrAzim = static_cast<int>(i * m_Projection->nrApper/scaling_y);\n\t\t\tframe.nrAzim = static_cast<int>(i * m_Projection->nrApper/scaling_x);\n\t\t\tframe.nrElev = static_cast<int>(j * m_Projection->nrApper/scaling_y);\n\t\t\tframe.taskDone = false;\n\t\t}\n\t}\n\n\n\t// Run `Option::threads` threads to do all the projections.\n\tboost::thread_group group;\n\tfor(size_t i = 0 ; i < Option::threads ; ++i) {\n\t\tgroup.create_thread(boost::bind(&GBVS360::getRectilinearFramesJob, this, boost::ref(inputImage)));\n\t}\n\tgroup.join_all();\n\n\n\t// reset all task flags, to be ready for the next task\n\tfor(std::list<ProjectedFrame>::iterator it = m_ProjectedFrames.begin() ; it != m_ProjectedFrames.end() ; ++it) {\n\t\tit->taskDone = false;\n\t}\n\n}\n\n\n\nvoid GBVS360::getRectilinearFramesJob(const cv::Mat &inputImage) {\n\n\tbool taskFound = true;\n\n\twhile(taskFound) {\n\t\ttaskFound = false;\n\t\tProjectedFrame *projectedFrame = NULL;\n\t\tm_mutex.lock();\n\t\tint taskId = 0;\n\t\tfor(std::list<ProjectedFrame>::iterator it = m_ProjectedFrames.begin() ; it != m_ProjectedFrames.end() ; ++it) {\n\t\t\tif(!it->taskDone) {\n\t\t\t\ttaskFound = true;\n\t\t\t\tprojectedFrame = &(*it);\n\n\t\t\t\tit->taskDone = true;\t\t// marked the currently processed frame as estimated\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++taskId;\n\t\t}\n\n\t\tm_mutex.unlock();\n\n\n\t\t// if there is still something to do, do the job\n\t\tif(taskFound) {\n\t\t\tm_Projection->equirectangularToRectilinear(inputImage, projectedFrame->rectilinearFrame, static_cast<float>(projectedFrame->nrAzim), static_cast<float>(projectedFrame->nrElev));\n\n\t\t\tif(hmdMode) {\n\t\t\t\tHMDSim simulator;\n\t\t\t\tcv::Mat result;\n    \t\t\tsimulator.applyFilter(projectedFrame->rectilinearFrame, result);\n    \t\t\tresult = 255*result;\n    \t\t\tresult.convertTo(projectedFrame->rectilinearFrame, CV_8UC3);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- \n\n\nvoid GBVS360::getRectilinearFeatures\t() {\n\tif(m_ProjectedFrames.empty()) return;\n\n\tint maxLevel = 0;\n\tfor(size_t i = 0 ; i < levels.size() ; ++i) {\n\t\tif(levels[i] > maxLevel)\n\t\t\tmaxLevel = levels[i];\n\t}\n\n\tif(maxLevel == 0) return;\n\n\tmaxcomputelevel = maxLevel;\n\tint height = static_cast<int>(m_ProjectedFrames.front().rectilinearFrame.rows / (maxLevel*featureScaling));\n\tint width = static_cast<int>(m_ProjectedFrames.front().rectilinearFrame.cols  / (maxLevel*featureScaling));\n\n\n\tbool faceDetection = false;\n\tbool segmentation = false;\n\tbool linPerspective = false;\n\tstd::string workChannels; // forward the requested channels to the workers. Unfortunately, Haarcascades classifiers does not seems to like multithreading. So, it will be needed to that in the main threads. \n\tfor(size_t i = 0 ; i < channels.size() ; ++i) {\n\t\tif(channels[i] != 'F' &&  channels[i] != 'S'  &&  channels[i] != 'P') \n\t\t\tworkChannels += channels[i];\n\t\telse {\n\t\t\tif(channels[i] == 'F')\n\t\t\t\tfaceDetection = true;\n\n\t\t\tif(channels[i] =='S')\n\t\t\t\tsegmentation = true;\n\n\t\t\tif(channels[i] == 'P') \n\t\t\t\tlinPerspective = true;\n\t\t}\n\t\t\t\n\t}\n\n\tchannels = workChannels + (linPerspective ? \"P\" : \"\") + (faceDetection ? \"F\" : \"\") + (segmentation ? \"S\" : \"\");\t// make sure that F, S, P are in the last channel. \n\n\tfor(size_t i = m_GBVSWorkers.size() ; i < Option::threads ; ++i) {\t\t// instantiate all the workers;\n\t\tm_GBVSWorkers.push_back(boost::shared_ptr<GBVS>(new GBVS()));\t\n\t\tm_GBVSWorkers.back()->useCSF = false;\n\t\tm_GBVSWorkers.back()->initDone = true;\t\t// the workers will not generate saliency maps, no need to initialize the graph\n\t\tm_GBVSWorkers.back()->maxcomputelevel = maxLevel; // we need to know what the deepest level. Normally this is estimated by initGBVS()\n\t\tm_GBVSWorkers.back()->makeGaborFilters();\t// we need the Gabor filter \n\t\tm_GBVSWorkers.back()->salmapmaxsize_v.clear();\n\t\tm_GBVSWorkers.back()->salmapmaxsize_v.push_back(height);\t\n\t\tm_GBVSWorkers.back()->salmapmaxsize_v.push_back(width);\n\t\tm_GBVSWorkers.back()->channels = workChannels;\t\n\n\t}\n\n\n\tboost::thread_group group;\n\tfor(int i = 0 ; i < static_cast<int>(m_GBVSWorkers.size()) ; ++i) {\n\t\tgroup.create_thread(boost::bind(&GBVS360::getRectilinearFeaturesJob, this, i));\n\t}\n\tgroup.join_all();\n\n\n\t// Face detection was requested, we now do it in the main thread.\n\tif(faceDetection) {\n\t\tgetFaceDetectionFeature(height, width);\n\t}\n\n\t\t\n}\n\n\nvoid GBVS360::getRectilinearFeaturesJob(int workerID) {\n\tboost::shared_ptr<GBVS> &saliency = m_GBVSWorkers[workerID];\n\n\n\t// look for a frame which need to be processed\n\tbool taskFound = true;\n\n\twhile(taskFound) {\n\t\ttaskFound = false;\n\t\tProjectedFrame *projectedFrame = NULL;\n\t\tm_mutex.lock();\n\t\tfor(std::list<ProjectedFrame>::iterator it = m_ProjectedFrames.begin() ; it != m_ProjectedFrames.end() ; ++it) {\n\t\t\tif(!it->taskDone) {\n\t\t\t\ttaskFound = true;\n\t\t\t\tprojectedFrame = &(*it);\n\n\t\t\t\tit->taskDone = true;\t\t// marked the currently processed frame as estimated\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tm_mutex.unlock();\n\n\n\t\t// if there is still something to do, do the job\n\t\tif(taskFound) {\n\t\t\tsaliency->computeFeatures(projectedFrame->rectilinearFrame);\n\t\t\tprojectedFrame->features = saliency->features;\n\t\t} \n\t}\n}\n\n\n// Do the face detection in the mean thread as the haarcascades classifiers does not like multi-threading... \nvoid GBVS360::getFaceDetectionFeature(int height, int width) {\n\n\tfor(std::list<ProjectedFrame>::iterator it = m_ProjectedFrames.begin() ; it != m_ProjectedFrames.end() ; ++it) {\n\t\tit->taskDone = true;\t\t// marked the currently processed frame as estimated\n\n\t\tProjectedFrame *projectedFrame = &(*it);\n\n\t\tint channelNumber = 0;\n\t\tfor(size_t i = 0 ; i < channels.size() ; ++i) {\n\t\t\tif(channels[i] == 'F') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++channelNumber;\n\t\t}\n\n\t\tFeature f;\n\t\tf.description = \"Face detector\";\n\t\tf.weight = faceFeatureWeight;\n\t\tf.channel = channelNumber;\n\n\t\tcv::Mat featureMap = faceFeaturesDectection(projectedFrame->rectilinearFrame);\n\n\t\t\n\t\tif(!featureMap.empty()) {\n\t\t\tFeatureMap fm;\n\t\t\tfm.type  = 0;\n\t\t\tfm.level = 0;\n\t\t\tfm.channel = static_cast<int>(channels.size())-1;\n\n\t\t\tcv::resize(featureMap, fm.map, cv::Size(width, height), 0, 0, cv::INTER_AREA);\n\t\t\tf.maps.push_back(fm);\n\n\t\t\tprojectedFrame->features.push_back(f);\n\t\t}\n\t}\n}\n\nvoid GBVS360::getSegmentationFeature(const cv::Mat &inputImage, Feature &segFeature) {\n\tcv::Mat input = inputImage.clone();\n\tinput.convertTo(input, CV_64FC3);\n\tinput /= 255;\n\tsegFeature = segmentationFeature(input);\n\n\tint featureIndex = 0;\n\tfor(size_t i = 0 ; i < channels.size() ; ++i) {\n\t\tif(channels[i] == 'S') {\n\t\t\tfeatureIndex = static_cast<int>(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tsegFeature.channel = featureIndex;\n\tfor(std::list<FeatureMap>::iterator it = segFeature.maps.begin() ; it !=  segFeature.maps.end() ; ++it) {\n\t\tit->channel = featureIndex;\n\t}\n}\n\nvoid GBVS360::getLinPerFeature(const cv::Mat &inputImage, Feature &linPerFeature) {\n\tcv::Mat image;\n\tcv::resize(inputImage, image, cv::Size(1200, static_cast<int>((1000.f/inputImage.cols) * inputImage.rows)));\n\n\tstd::vector<double> reliability(4);\n    std::vector<cv::Mat> outputs(4);\n    for(size_t i = 0 ; i < outputs.size() ; ++i) {\n\t\toutputs[i] = vanishingLineFeatureMap(image, &reliability[i]);\n    }\n\n    for(size_t i = 1 ; i < outputs.size() ; ++i) {\n        outputs[0] += outputs[i];\n        reliability[0] += reliability[i];\n    }\n    outputs[0] /= static_cast<double>(outputs.size());\n    reliability[0] /= static_cast<double>(outputs.size());\n\n\tFeatureMap fm;\n\tfm.type  = 0;\n\tfm.level = 0;\n\tfor(size_t i = 0 ; i < channels.size() ; ++i) {\n\t\tif(channels[i] == 'P') {\n\t\t\tfm.channel = static_cast<int>(i);\n\t\t}\n\t}\n\n\tif(reliability[0] < 0.0015) {\t// 0.0038 if the feature map does not contains much information, drop it.\n\t\tfm.map = cv::Mat(cv::Size(salmapmaxsize_v[1], salmapmaxsize_v[0]), CV_64FC1, cv::Scalar(0.f));\n\t} else {\n\t\tcv::resize(outputs[0], fm.map, cv::Size(salmapmaxsize_v[1], salmapmaxsize_v[0]), 0, 0, cv::INTER_AREA);\n\t}\n\n\tlinPerFeature.maps.push_back(fm);\n\tlinPerFeature.description = \"Linear perspective\";\n\tif(reliability[0] >= 0.0038)\n\t\tlinPerFeature.weight = std::min(100.f, std::max(0.f, static_cast<float>(-2.824f + 3.105f * exp(662.373f * reliability[0])))) / 10.f; //30 / 70\n\telse\n\t\tlinPerFeature.weight = std::min(100.f, std::max(0.f, static_cast<float>(-3.276f + 2.936f * exp(689.485f * reliability[0])))) / 140.f; //100\n\n\tlinPerFeature.channel = fm.channel;\n}\n\nvoid GBVS360::getEquirectangularFeatures() {\n\n\tif(m_ProjectedFrames.empty()) { std::cout << \"[I] No projected frames... \" << std::endl; return; } \t\t\t\t\t// If there are no frames available, stop.\n\tProjectedFrame &frame = *m_ProjectedFrames.begin(); \t\n\tif(frame.features.empty()) { std::cout << \"[I] No features\" << std::endl; return; };\t\t\t\t\t\t// If there are no features computed, stop.\n\n\tint mxType = 0;\n\tint mxLevel = 0;\n\tint mxChannel = 0;\n\t// allocate enough memory for all features in equirectangular domain.\n\tfor(std::list<Feature>::iterator it = frame.features.begin() ; it != frame.features.end() ; ++it) {\n\t\tfeatures.push_back(Feature());\n\t\tfeatures.back().weight \t\t= it->weight;\n\t\tfeatures.back().channel \t= it->channel;\n\t\tfeatures.back().description = it->description;\n\n\t\tfor(std::list< FeatureMap >::iterator mapIt = it->maps.begin() ; mapIt != it->maps.end() ; ++mapIt) {\n\t\t\tfeatures.back().maps.push_back(FeatureMap());\n\t\t\tfeatures.back().maps.back().type \t= mapIt->type;\n\t\t\tfeatures.back().maps.back().level \t= mapIt->level;\n\t\t\tfeatures.back().maps.back().channel = mapIt->channel;\n\n\t\t\t// the interpolation in the projection function needs an image in with a power of 2.\n\t\t\tint rows = 4 * (static_cast<int>(m_EquirectangularFrameSize.height / (maxcomputelevel*featureScaling)) / 4); // 0\n\t\t\tint cols = 4 * (static_cast<int>(m_EquirectangularFrameSize.width / (maxcomputelevel*featureScaling)) / 4); // 1\n\n\t\t\tfeatures.back().maps.back().map = cv::Mat(rows, cols, CV_64FC1, cv::Scalar(0));\n\n\t\t\tmxType = std::max(mxType, mapIt->type);\n\t\t\tmxLevel = std::max(mxLevel, mapIt->level);\n\t\t\tmxChannel = std::max(mxChannel, mapIt->channel);\n\t\t}\n\t}\n\n\n\t// add flags to know if a feature was projected to equirectangular domain.\n\t// order is : featureDone[CHANNEL][LEVEL][TYPE]\n\tfeatureDone.clear();\n\t++mxChannel; ++mxLevel; ++mxType;\n\tfeatureDone.resize(mxChannel);\n\tfor(int i = 0 ; i < mxChannel ; ++i) {\n\t\tfeatureDone[i].resize(mxLevel);\n\t\tfor(int j = 0 ; j < mxLevel ; ++j) {\n\t\t\tfeatureDone[i][j].resize(mxType, false);\n\t\t}\n\t}\n\n\t// Run `Option::threads` threads to do all the projections.\n\tboost::thread_group group;\n\tfor(size_t i = 0 ; i < Option::threads ; ++i) {\n\t\tgroup.create_thread(boost::bind(&GBVS360::getEquirectangularFeaturesJob, this));\n\t}\n\n\n\t// if the feature S is requested, we compute it directly in equirectangular domain.\n\tbool doSegmentation = false;\n\tFeature segFeature;\n\tfor(size_t i = 0 ; i < channels.size() && !doSegmentation ; ++i) {\n\t\tif(channels[i] == 'S') {\n\t\t\tgroup.create_thread(boost::bind(&GBVS360::getSegmentationFeature, this, boost::ref(m_InputImage), boost::ref(segFeature)));\n\t\t\tdoSegmentation = true;\n\t\t}\n\t}\n\n\t// if the feature S is requested, we compute it directly in equirectangular domain.\n\tbool doPerspective = false;\n\tFeature linPerFeature;\n\tfor(size_t i = 0 ; i < channels.size() && !doPerspective ; ++i) {\n\t\tif(channels[i] == 'P') {\n\t\t\t//getLinPerFeature(m_InputImage, linPerFeature);\n\t\t\tgroup.create_thread(boost::bind(&GBVS360::getLinPerFeature, this, boost::ref(m_InputImage), boost::ref(linPerFeature)));\n\t\t\tdoPerspective = true;\n\t\t}\n\t}\n\n\n\tgroup.join_all();\n\n\t// add the segmentation feature maps which was estimated in parallel.\n\tif(doSegmentation) {\n\t\tfeatures.push_back(segFeature);\n\t}\n\n\tif(doPerspective) {\n\t\tdouble mx, mn;\n\t\tcv::minMaxLoc(linPerFeature.maps.back().map, &mn, &mx);\n\t\tif(mx > 0.1) {\n\t\t\tfeatures.push_back(linPerFeature);\n\t\t\t// allmaps.push_back(linPerFeature.maps.front());\n\t\t}\n\t}\n\n}\n\n\nvoid GBVS360::getEquirectangularFeaturesJob() {\n\n\tbool taskFound = true;\n\twhile(taskFound) {\n\t\ttaskFound = false;\n\n\t\t// algo v1, easy, without packing of multiple features with the same resolution to save computational costs...\n\t\tif(m_ProjectedFrames.empty()) break; \t\t\t\t\t// If there are no frames available, stop.\n\t\tProjectedFrame &frame = *m_ProjectedFrames.begin(); \t\n\t\tif(frame.features.empty()) break;\t\t\t\t\t\t// If there are no features computed, stop.\n\n\n\n\t\tint channel = 0;\n\t\tint level = 0;\n\t\tint type = 0;\n\n\t\t// ----------------------------------------------------------------------------------\n\t\t// identify what task need to be done\n\n\n\t\tm_mutex.lock();\n\t\t\n\t\t// iterate each feature channel\n\t\tfor(std::list<Feature>::iterator it = frame.features.begin() ; it != frame.features.end() && !taskFound ; ++it) {\n\t\t\t// iterate each feature map\n\t\t\tfor(std::list< FeatureMap >::iterator mapIt = it->maps.begin() ; mapIt != it->maps.end()  && !taskFound ; ++mapIt) {\n\t\t\t\tif(!featureDone[mapIt->channel][mapIt->level][mapIt->type]) {\n\n\t\t\t\t\t// we found one feature map which needs to be back projected. \n\t\t\t\t\tchannel = mapIt->channel;\n\t\t\t\t\tlevel = mapIt->level;\n\t\t\t\t\ttype = mapIt->type;\n\n\t\t\t\t\t// we mark it as `done`, e.g. in progress...\n\t\t\t\t\tfeatureDone[mapIt->channel][mapIt->level][mapIt->type] = true;\n\n\t\t\t\t\t// a task was found.\n\t\t\t\t\ttaskFound = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm_mutex.unlock();\n\n\t\t// if nothing to do, then close the thread.\n\t\tif(!taskFound) {\n\t\t\treturn;\n\t\t}\n\n\t\t// ----------------------------------------------------------------------------------\n\t\t// back-project the identified feature map.\n\n\n\n\t\t// Find the feature map between the equirectilinear maps\n\t\tfor(std::list<Feature>::iterator featureItEquirect = features.begin() ; featureItEquirect != features.end() ; ++featureItEquirect) {\n\t\t\tif(featureItEquirect->channel != channel) continue; // if we are not on the right channel, no need to check the maps\n\n\t\t\t// iterate each feature map\n\t\t\tfor(std::list< FeatureMap >::iterator mapItEquirectilinear = featureItEquirect->maps.begin() ; mapItEquirectilinear != featureItEquirect->maps.end() ; ++mapItEquirectilinear) {\n\t\t\t\tif(mapItEquirectilinear->level == level && mapItEquirectilinear->type == type && mapItEquirectilinear->channel == channel) {\n\n\n\t\t\t\t\tcv::Mat nbProj(mapItEquirectilinear->map.rows, mapItEquirectilinear->map.cols, CV_8UC1, cv::Scalar(0));\n\n\t\t\t\t\tfor(std::list< ProjectedFrame >::iterator projIt = m_ProjectedFrames.begin() ; projIt != m_ProjectedFrames.end() ; ++projIt) {\n\t\t\t\t\t\t\n\n\n\n\t\t\t\t\t\t// Find the feature map between the equilinear maps\n\t\t\t\t\t\tfor(std::list<Feature>::iterator featureIt = projIt->features.begin() ; featureIt != projIt->features.end() ; ++featureIt) {\n\n\t\t\t\t\t\t\tif(featureIt->channel != channel) continue; // if we are not on the right channel, no need to check the maps\n\n\t\t\t\t\t\t\t// iterate each feature map\n\t\t\t\t\t\t\tfor(std::list< FeatureMap >::iterator mapItEquilinear = featureIt->maps.begin() ; mapItEquilinear != featureIt->maps.end() ; ++mapItEquilinear) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif((mapItEquilinear->level == level && mapItEquilinear->type == type && mapItEquilinear->channel == channel)) {\n\n\t\t\t\t\t\t\t\t\tcv::Mat tempEquirect(mapItEquirectilinear->map.rows, mapItEquirectilinear->map.cols, CV_32FC3, cv::Scalar(0.f,0.f,0.f));\n\t\t\t\t\t\t\t\t\tcv::Mat floatFeature(mapItEquilinear->map.rows, mapItEquilinear->map.cols, CV_32FC3, cv::Scalar(0.f,0.f,0.f));\n\n\t\t\t\t\t\t\t\t\tfor(int i = 0 ; i < mapItEquilinear->map.rows ; ++i) {\n\t\t\t\t\t\t\t\t\t\tfor(int j = 0 ; j < mapItEquilinear->map.cols ; ++j) {\n\t\t\t\t\t\t\t\t\t\t\tcv::Point3_<float> &dst = floatFeature.at< cv::Point3_<float> >(i,j);\n\t\t\t\t\t\t\t\t\t\t\tdst.x = static_cast<float>(mapItEquilinear->map.at<double>(i,j));\n\t\t\t\t\t\t\t\t\t\t\tdst.y = 1;\n\t\t\t\t\t\t\t\t\t\t\tdst.z = 0;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\t\tm_Projection->rectilinearToEquirectangularFC3(floatFeature, tempEquirect, static_cast<float>(projIt->nrAzim), static_cast<float>(projIt->nrElev));\n\n\t\t\t\t\t\t\t\t\tfor(int i = 0 ; i < tempEquirect.rows ; ++i) {\n\t\t\t\t\t\t\t\t\t\tfor(int j = 0 ; j < tempEquirect.cols ; ++j) {\n\t\t\t\t\t\t\t\t\t\t\tcv::Point3_<float> &src = tempEquirect.at< cv::Point3_<float> >(i,j);\n\n\t\t\t\t\t\t\t\t\t\t\t// if that is not part of the feature, skip\n\t\t\t\t\t\t\t\t\t\t\tif(src.y < 0.999f) continue;\n\n\t\t\t\t\t\t\t\t\t\t\tdouble v = mapItEquirectilinear->map.at<double>(i,j);\n\n\t\t\t\t\t\t\t\t\t\t\tv += src.x;\n\n\t\t\t\t\t\t\t\t\t\t\t++nbProj.at<unsigned char>(i,j);\n\n\t\t\t\t\t\t\t\t\t\t\tmapItEquirectilinear->map.at<double>(i,j) = v;\n\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\n\t\t\t\t\t} // end loop projIt\n\n\n\t\t\t\t\tfor(int i = 0 ; i < mapItEquirectilinear->map.rows ; ++i) {\n\t\t\t\t\t\tfor(int j = 0 ; j < mapItEquirectilinear->map.cols ; ++j) {\n\t\t\t\t\t\t\tmapItEquirectilinear->map.at<double>(i,j) /= nbProj.at<unsigned char>(i,j);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcv::Mat tmp;\n\t\t\t\t\tcv::resize(mapItEquirectilinear->map, tmp, cv::Size(salmapmaxsize_v[1], salmapmaxsize_v[0]), 0, 0, cv::INTER_AREA);\n\t\t\t\t\tmapItEquirectilinear->map = tmp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\n\t} // end while task\n\n\n}\n\n\n// ----------------------------------------------------------------------------------------------------------------------------------------------------\n// redefine GBVS functions \n\ncv::Mat GBVS360::simpledistance\t(const std::pair<int, int>& dim, int ) const {\n\n\treturn Option::distScaling * GBVS::simpledistance(dim, 0);\n\t\n\tint N = dim.first*dim.second;\n\tcv::Mat d(N, N, CV_64FC1, cv::Scalar(0.f));\n\n\tdouble l0 = static_cast<float>(dim.second)/2;\n\tdouble p0 = static_cast<float>(dim.first)/2;\n\n\t#define idx(mi,mj) ((mj)*dim.first+(mi))\n\n\t#ifndef PI\n\t#define PI 3.14159265358979116f\n\t#endif\n\n\tfor(int i = 0 ; i < dim.second ; ++i) {\n\t\tfor(int j = 0 ; j < dim.first ; ++j) {\n\t\t\tfor(int ii = 0 ; ii < dim.second ; ++ii) {\n\t\t\t\tfor(int jj = 0 ; jj < dim.first ; ++jj) {\n\n\t\t\t\t\t// replace the distance by the haversine distance to account for the non-linearity of the grid in equirectangular domain. \n\t\t\t\t\tif(d.at<double>(idx(j,i), idx(jj,ii)) == 0) {\n\n\t\t\t\t\t\tdouble haversine = 0;\n\n\t\t\t\t\t\t// TO CHECK:\n\t\t\t\t\t\t// shall this be \" - p0 \" & \"/ dim.first\" as j loop between [0-dim.first] ? \n\t\t\t\t\t\t// I think that mistake added an equatorial prior which is a positive thing... \n                        double phy1   = PI*(j + .5  - p0) / static_cast<double>(dim.first);\n                        double phy2   = PI*(jj + .5 - p0) / static_cast<double>(dim.first);\n                        double lambda1 =  PI*(i + .5 - l0) / static_cast<double>(dim.second)/2;\n                        double lambda2 =  PI*(ii + .5 - l0) / static_cast<double>(dim.second)/2;\n\n\n                        double sn1 = std::sin((phy2-phy1)/2);\n                        double sn2 = std::sin((lambda2-lambda1)/2);\n\n                        haversine = sqrt(sn1*sn1 + std::cos(phy1)*std::cos(phy2)*sn2*sn2);\n                        if(haversine > 1.0)  haversine = 1.0;\t// this can happens due to rounding error... \n                        if(haversine < -1.0) haversine = -1.0;\n\n                        // haversine = m_Projection->nrrWidth*dim.first*std::asin(haversine); //dim.first*\n\t\t\t\t\t\thaversine = Option::distScaling * dim.first*std::asin(haversine); //dim.first*\n\t\t\t\t\t\t// haversine = dim.first*std::asin(haversine);\n\n\t\t\t\t\t\t// haversine = dim.first * 2 * std::atan2(std::sqrt(haversine), std::sqrt(1-haversine));\n\t\t\t\t\t\t\n\n\t\t\t\t\t\td.at<double>(idx(j,i), idx(jj,ii)) = haversine;\n\t\t\t\t\t\td.at<double>(idx(jj,ii), idx(j,i)) = haversine;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t#undef idx\n\n\treturn d;\n}\n\n\nvoid GBVS360::attenuateBordersGBVS(cv::Mat &, int ) const {\n\t// do nothing -- remove central prior\n\n\t// if(size == 4) return;\n\n\t// if(size == 13) GBVS::attenuateBordersGBVS(image, 5);\n}\n\n\n\nconst cv::Mat * GBVS360::findMap(char channel, int level, int type) const {\n\tint channelId = -1;\n\tfor(int i = 0 ; i < static_cast<int>(channels.size()) ; ++i) {\n\t\tif(channels[i] == channel) {\n\t\t\tchannelId = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(channelId == -1) return NULL;\n\n\tfor(std::list<FeatureMap>::const_iterator it = allmaps.begin() ; it != allmaps.end() ; ++it) {\n\t\tif(it->channel == channelId && it->type == type && it->level == level) \n\t\t\treturn &it->map;\n\t}\n\n\treturn NULL;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "f88ab92c71f44e8da12eff2772cf8114ac0cea0f", "size": 38497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libgbvs360/GBVS360.cpp", "max_stars_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_stars_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-01-23T14:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T13:53:41.000Z", "max_issues_repo_path": "libgbvs360/GBVS360.cpp", "max_issues_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_issues_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-09-05T23:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T18:52:18.000Z", "max_forks_repo_path": "libgbvs360/GBVS360.cpp", "max_forks_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_forks_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T00:35:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T16:55:07.000Z", "avg_line_length": 31.4004893964, "max_line_length": 216, "alphanum_fraction": 0.6292957893, "num_tokens": 11262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.026355353897650872, "lm_q1q2_score": 0.007668903706538869}}
{"text": "// Copyright Maarten L. Hekkelman, Radboud University 2008-2011.\n//   Distributed under the Boost Software License, Version 1.0.\n//       (See accompanying file LICENSE_1_0.txt or copy at    \n//             http://www.boost.org/LICENSE_1_0.txt)      \n\n#include \"mas.h\"\n\n#if defined(_MSC_VER)\n#include <conio.h>\n#include <ctype.h>\n#endif\n\n#include <iostream>\n\n#include <boost/format.hpp>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n#include <boost/bind.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/date_clock_device.hpp>\n\n#include \"dssp.h\"\n#include \"structure.h\"\n\nusing namespace std;\n\nstring ResidueToDSSPLine(const MResidue& residue)\n{\n/*   \n\tThis is the header line for the residue lines in a DSSP file:\n\n  #  RESIDUE AA STRUCTURE BP1 BP2  ACC     N-H-->O    O-->H-N    N-H-->O    O-->H-N    TCO  KAPPA ALPHA  PHI   PSI    X-CA   Y-CA   Z-CA \n\n */\n\tboost::format kDSSPResidueLine(\n\t\"%5.5d%5.5d%1.1s%1.1s %c  %c %c%c%c%c%c%c%c%4.4d%4.4d%c%4.4d %11s%11s%11s%11s  %6.3f%6.1f%6.1f%6.1f%6.1f %6.1f %6.1f %6.1f\");\n\t\n\tconst MAtom& ca = residue.GetCAlpha();\n\t\n\tchar code = kResidueInfo[residue.GetType()].code;\n\tif (residue.GetType() == kCysteine and residue.GetSSBridgeNr() != 0)\n\t\tcode = 'a' + ((residue.GetSSBridgeNr() - 1) % 26);\n\n\tchar ss;\n\tswitch (residue.GetSecondaryStructure())\n\t{\n\t\tcase alphahelix:\tss = 'H'; break;\n\t\tcase betabridge:\tss = 'B'; break;\n\t\tcase strand:\t\tss = 'E'; break;\n\t\tcase helix_3:\t\tss = 'G'; break;\n\t\tcase helix_5:\t\tss = 'I'; break;\n\t\tcase turn:\t\t\tss = 'T'; break;\n\t\tcase bend:\t\t\tss = 'S'; break;\n\t\tcase loop:\t\t\tss = ' '; break;\n\t}\n\t\n\tchar helix[3];\n\tfor (uint32 stride = 3; stride <= 5; ++stride)\n\t{\n\t\tswitch (residue.GetHelixFlag(stride))\n\t\t{\n\t\t\tcase helixNone:\t\t\thelix[stride - 3] = ' '; break;\n\t\t\tcase helixStart:\t\thelix[stride - 3] = '>'; break;\n\t\t\tcase helixEnd:\t\t\thelix[stride - 3] = '<'; break;\n\t\t\tcase helixStartAndEnd:\thelix[stride - 3] = 'X'; break;\n\t\t\tcase helixMiddle:\t\thelix[stride - 3] = '0' + stride; break;\n\t\t}\n\t}\n\t\n\tchar bend = ' ';\n\tif (residue.IsBend())\n\t\tbend = 'S';\n\n\tdouble alpha;\n\tchar chirality;\n\ttr1::tie(alpha,chirality) = residue.Alpha();\n\t\n\tuint32 bp[2] = {};\n\tchar bridgelabel[2] = { ' ', ' ' };\n\tfor (uint32 i = 0; i < 2; ++i)\n\t{\n\t\tMBridgeParner p = residue.GetBetaPartner(i);\n\t\tif (p.residue != nullptr)\n\t\t{\n\t\t\tbp[i] = p.residue->GetNumber();\n\t\t\tbp[i] %= 10000;\t// won't fit otherwise...\n\t\t\tbridgelabel[i] = 'A' + p.ladder % 26;\n\t\t\tif (p.parallel)\n\t\t\t\tbridgelabel[i] = tolower(bridgelabel[i]);\n\t\t}\n\t}\n\t\n\tchar sheet = ' ';\n\tif (residue.GetSheet() != 0)\n\t\tsheet = 'A' + (residue.GetSheet() - 1) % 26;\n\t\n\tstring NHO[2], ONH[2];\n\tconst HBond* acceptors = residue.Acceptor();\n\tconst HBond* donors = residue.Donor();\n\tfor (uint32 i = 0; i < 2; ++i)\n\t{\n\t\tNHO[i] = ONH[i] = \"0, 0.0\";\n\t\t\n\t\tif (acceptors[i].residue != nullptr)\n\t\t{\n\t\t\tint32 d = acceptors[i].residue->GetNumber() - residue.GetNumber();\n\t\t\tNHO[i] = (boost::format(\"%d,%3.1f\") % d % acceptors[i].energy).str();\n\t\t}\n\t\n\t\tif (donors[i].residue != nullptr)\n\t\t{\n\t\t\tint32 d = donors[i].residue->GetNumber() - residue.GetNumber();\n\t\t\tONH[i] = (boost::format(\"%d,%3.1f\") % d % donors[i].energy).str();\n\t\t}\n\t}\n\t\n\treturn (kDSSPResidueLine % residue.GetNumber() % ca.mResSeq % ca.mICode % ca.mChainID % code %\n\t\tss % helix[0] % helix[1] % helix[2] % bend % chirality % bridgelabel[0] % bridgelabel[1] %\n\t\tbp[0] % bp[1] % sheet % floor(residue.Accessibility() + 0.5) %\n\t\tNHO[0] % ONH[0] % NHO[1] % ONH[1] %\n\t\tresidue.TCO() % residue.Kappa() % alpha % residue.Phi() % residue.Psi() %\n\t\tca.mLoc.mX % ca.mLoc.mY % ca.mLoc.mZ).str();\n}\n\nvoid WriteDSSP(MProtein& protein, ostream& os)\n{\n\tconst string kFirstLine(\"==== Secondary Structure Definition by the program DSSP, CMBI version by M.L. Hekkelman/2010-10-21 ==== \");\n\tboost::format kHeaderLine(\"%1% %|127t|%2%\");\n\t\n\tusing namespace boost::gregorian;\n\t\n\tuint32 nrOfResidues, nrOfChains, nrOfSSBridges, nrOfIntraChainSSBridges, nrOfHBonds;\n\tuint32 nrOfHBondsPerDistance[11] = {};\n\t\n\tprotein.GetStatistics(nrOfResidues, nrOfChains, nrOfSSBridges, nrOfIntraChainSSBridges, nrOfHBonds, nrOfHBondsPerDistance);\n\t\n\tdate today = day_clock::local_day();\n\n\tos << kHeaderLine % (kFirstLine + \"DATE=\" + to_iso_extended_string(today)) % '.' << endl;\n\tos << kHeaderLine % \"REFERENCE W. KABSCH AND C.SANDER, BIOPOLYMERS 22 (1983) 2577-2637\" % '.' << endl;\n\tos << kHeaderLine % protein.GetHeader() % '.' << endl;\n\tif (not protein.GetCompound().empty())\n\t\tos << kHeaderLine % protein.GetCompound() % '.' << endl;\n\tif (not protein.GetSource().empty())\n\t\tos << kHeaderLine % protein.GetSource() % '.' << endl;\n\tif (not protein.GetAuthor().empty())\n\t\tos << kHeaderLine % protein.GetAuthor() % '.' << endl;\n\n\tdouble accessibleSurface = 0;\t// calculate accessibility as \n\tforeach (const MChain* chain, protein.GetChains())\n\t{\n\t\tforeach (const MResidue* residue, chain->GetResidues())\n\t\t\taccessibleSurface += residue->Accessibility();\n\t}\n\n\tos << boost::format(\"%5.5d%3.3d%3.3d%3.3d%3.3d TOTAL NUMBER OF RESIDUES, NUMBER OF CHAINS, NUMBER OF SS-BRIDGES(TOTAL,INTRACHAIN,INTERCHAIN) %|127t|%c\") %\n   \t\tnrOfResidues % nrOfChains % nrOfSSBridges % nrOfIntraChainSSBridges % (nrOfSSBridges - nrOfIntraChainSSBridges) % '.' << endl;\n   \tos << kHeaderLine % (boost::format(\"%8.1f   ACCESSIBLE SURFACE OF PROTEIN (ANGSTROM**2)\") % accessibleSurface) % '.' << endl;\n\n\t// hydrogenbond summary\n\t\n\tos << kHeaderLine % (\n\t\tboost::format(\"%5.5d%5.1f   TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(J)  , SAME NUMBER PER 100 RESIDUES\")\n\t\t\t% nrOfHBonds % (nrOfHBonds * 100.0 / nrOfResidues)) % '.' << endl;\n\n\tuint32 nrOfHBondsInParallelBridges = protein.GetNrOfHBondsInParallelBridges();\n\tos << kHeaderLine % (\n\t\tboost::format(\"%5.5d%5.1f   TOTAL NUMBER OF HYDROGEN BONDS IN     PARALLEL BRIDGES, SAME NUMBER PER 100 RESIDUES\")\n\t\t\t% nrOfHBondsInParallelBridges % (nrOfHBondsInParallelBridges * 100.0 / nrOfResidues)) % '.' << endl;\n\n\tuint32 nrOfHBondsInAntiparallelBridges = protein.GetNrOfHBondsInAntiparallelBridges();\n\tos << kHeaderLine % (\n\t\tboost::format(\"%5.5d%5.1f   TOTAL NUMBER OF HYDROGEN BONDS IN ANTIPARALLEL BRIDGES, SAME NUMBER PER 100 RESIDUES\")\n\t\t\t% nrOfHBondsInAntiparallelBridges % (nrOfHBondsInAntiparallelBridges * 100.0 / nrOfResidues)) % '.' << endl;\n\t\n\tboost::format kHBondsLine(\"%5.5d%5.1f   TOTAL NUMBER OF HYDROGEN BONDS OF TYPE O(I)-->H-N(I%c%1.1d), SAME NUMBER PER 100 RESIDUES\");\n   \tfor (int32 k = 0; k < 11; ++k)\n\t{\n\t\tos << kHeaderLine % (kHBondsLine % nrOfHBondsPerDistance[k] % (nrOfHBondsPerDistance[k] * 100.0 / nrOfResidues) % (k - 5 < 0 ? '-' : '+') % abs(k - 5)) % '.' << endl;\n\t}\n\n\t// histograms...\n\t\n\tuint32 histogram[kHistogramSize];\n\tos << \"  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30     *** HISTOGRAMS OF ***           .\" << endl;\n\n\tprotein.GetResiduesPerAlphaHelixHistogram(histogram);\n\tfor (uint32 i = 0; i < kHistogramSize; ++i)\n\t\tos << boost::format(\"%3.3d\") % histogram[i];\n\tos << \"    RESIDUES PER ALPHA HELIX         .\" << endl;\n\n\tprotein.GetParallelBridgesPerLadderHistogram(histogram);\n\tfor (uint32 i = 0; i < kHistogramSize; ++i)\n\t\tos << boost::format(\"%3.3d\") % histogram[i];\n\tos << \"    PARALLEL BRIDGES PER LADDER      .\" << endl;\n\n\tprotein.GetAntiparallelBridgesPerLadderHistogram(histogram);\n\tfor (uint32 i = 0; i < kHistogramSize; ++i)\n\t\tos << boost::format(\"%3.3d\") % histogram[i];\n\tos << \"    ANTIPARALLEL BRIDGES PER LADDER  .\" << endl;\n\n\tprotein.GetLaddersPerSheetHistogram(histogram);\n\tfor (uint32 i = 0; i < kHistogramSize; ++i)\n\t\tos << boost::format(\"%3.3d\") % histogram[i];\n\tos << \"    LADDERS PER SHEET                .\" << endl;\n\n\t// per residue information\n\n\tos << \"  #  RESIDUE AA STRUCTURE BP1 BP2  ACC     N-H-->O    O-->H-N    N-H-->O    O-->H-N    TCO  KAPPA ALPHA  PHI   PSI    X-CA   Y-CA   Z-CA \" << endl;\n\tboost::format kDSSPResidueLine(\n\t\t\"%5.5d        !%c             0   0    0      0, 0.0     0, 0.0     0, 0.0     0, 0.0   0.000 360.0 360.0 360.0 360.0    0.0    0.0    0.0\");\n\n\tvector<const MResidue*> residues;\n\n\tforeach (const MChain* chain, protein.GetChains())\n\t{\n\t\tforeach (const MResidue* residue, chain->GetResidues())\n\t\t\tresidues.push_back(residue);\n\t}\n\t\n\t// keep residues sorted by residue number as assigned during reading the PDB file\n\tsort(residues.begin(), residues.end(), boost::bind(&MResidue::GetNumber, _1) < boost::bind(&MResidue::GetNumber, _2));\n\n\tconst MResidue* last = nullptr;\n\tforeach (const MResidue* residue, residues)\n\t{\n\t\t// insert a break line whenever we detect missing residues\n\t\t// can be the transition to a different chain, or missing residues in the current chain\n\t\tif (last != nullptr and last->GetNumber() + 1 != residue->GetNumber())\n\t\t{\n\t\t\tchar breaktype = ' ';\n\t\t\tif (last->GetChainID() != residue->GetChainID())\n\t\t\t\tbreaktype = '*';\n\t\t\tos << (kDSSPResidueLine % (last->GetNumber() + 1) % breaktype) << endl;\n\t\t}\n\t\tos << ResidueToDSSPLine(*residue) << endl;\n\t\tlast = residue;\n\t}\n}\n", "meta": {"hexsha": "6d8ebe13b80306553f93b78fd1c114c1c043aec8", "size": 8918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rd_party/hhsuite-2.1.0/dependencies/dssp-2.2.1/src/dssp.cpp", "max_stars_repo_name": "genomecuration/JAMp", "max_stars_repo_head_hexsha": "962985df85ce84a7afe2bcb975081426e6c42079", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-07-12T19:26:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T03:18:09.000Z", "max_issues_repo_path": "3rd_party/hhsuite-2.1.0/dependencies/dssp-2.2.1/src/dssp.cpp", "max_issues_repo_name": "genomecuration/JAMp", "max_issues_repo_head_hexsha": "962985df85ce84a7afe2bcb975081426e6c42079", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-06-23T02:35:23.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-02T22:22:17.000Z", "max_forks_repo_path": "3rd_party/hhsuite-2.1.0/dependencies/dssp-2.2.1/src/dssp.cpp", "max_forks_repo_name": "genomecuration/JAMp", "max_forks_repo_head_hexsha": "962985df85ce84a7afe2bcb975081426e6c42079", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T23:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T03:18:11.000Z", "avg_line_length": 37.1583333333, "max_line_length": 168, "alphanum_fraction": 0.640390222, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.019124035493046376, "lm_q1q2_score": 0.007646012008040946}}
{"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#include <photk/Common.h>\n#include <photk/config.h>\n#include <vw/Math/BBox.h>\n#include <vw/config.h>\n#include <boost/filesystem/path.hpp>\nusing namespace vw;\n\nnamespace photk {\n\n  BaseOptions::BaseOptions() {\n#if defined(VW_HAS_BIGTIFF) && VW_HAS_BIGTIFF == 1\n    gdal_options[\"COMPRESS\"] = \"LZW\";\n#else\n    gdal_options[\"COMPRESS\"] = \"NONE\";\n    gdal_options[\"BIGTIFF\"] = \"NO\";\n#endif\n    raster_tile_size =\n      vw::Vector2i(vw::vw_settings().default_tile_size(),\n                   vw::vw_settings().default_tile_size());\n  }\n\n  BaseOptionsDescription::BaseOptionsDescription( BaseOptions& opt ) {\n    namespace po = boost::program_options;\n    (*this).add_options()\n      (\"threads\", po::value(&opt.num_threads)->default_value(0),\n       \"Select the number of processors (threads) to use.\")\n      (\"no-bigtiff\", \"Tell GDAL to not create bigtiffs.\")\n      (\"version,v\", \"Display the version of software.\")\n      (\"help,h\", \"Display this help message\");\n  }\n\n  boost::program_options::variables_map\n  check_command_line( int argc, char *argv[], BaseOptions& opt,\n                      boost::program_options::options_description const& public_options,\n                      boost::program_options::options_description const& hidden_options,\n                      boost::program_options::positional_options_description const& positional,\n                      std::string const& help ) {\n    namespace po = boost::program_options;\n    po::variables_map vm;\n    try {\n      po::options_description all_options;\n      all_options.add(public_options).add(hidden_options);\n      po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional).run(), vm );\n      po::notify( vm );\n    } catch (po::error const& e) {\n      vw::vw_throw( vw::ArgumentErr() << \"Error parsing input:\\n\"\n                    << e.what() << \"\\n\" << help << \"\\n\" << public_options );\n    }\n    // We really don't want to use BIGTIFF unless we have to. It's\n    // hard to find viewers for bigtiff.\n    if ( vm.count(\"no-bigtiff\") ) {\n      opt.gdal_options[\"BIGTIFF\"] = \"NO\";\n    } else {\n      opt.gdal_options[\"BIGTIFF\"] = \"IF_SAFER\";\n    }\n    if ( vm.count(\"help\") )\n      vw::vw_throw( vw::ArgumentErr() << help << \"\\n\" << public_options );\n    if ( vm.count(\"version\") )\n      vw::vw_throw( vw::ArgumentErr() << PHOTK_PACKAGE_STRING << \"\\n\\n\"\n                    << \"Built against:\\n  \" << VW_PACKAGE_STRING << \"\\n  BOOST \"\n                    << PHOTK_BOOST_VERSION << \"\\n\");\n    if ( opt.num_threads != 0 ) {\n      vw::vw_out() << \"\\t--> Setting number of processing threads to: \"\n                   << opt.num_threads << std::endl;\n      vw::vw_settings().set_default_num_threads(opt.num_threads);\n    }\n\n    return vm;\n  }\n\n  bool has_cam_extension( std::string input ) {\n    boost::filesystem::path ipath( input );\n    std::string ext = ipath.extension();\n    if ( ext == \".cahvor\" || ext == \".cahv\" ||\n         ext == \".pin\" || ext == \".pinhole\" ||\n         ext == \".tsai\" || ext == \".cmod\" ||\n         ext == \".cahvore\" )\n      return true;\n    return false;\n  }\n\n  // This algorithm is lifted from, \"Cutting circles and squares into\n  // equal pieces\" by Bose et. al.\n  std::vector<vw::BBox2i>\n  split_square_to_equal_area( int32 const& side_length,\n                              size_t const& k ) {\n    using namespace vw;\n    std::vector<BBox2i> result;\n    result.reserve( k );\n\n    VW_ASSERT( uint64(side_length)*uint64(side_length) >= uint64(k),\n               ArgumentErr() << \"Requesting more regions then are pixels in square. K = \" << k << \", Side Length = \" << side_length );\n    VW_ASSERT( side_length >= k,\n               ArgumentErr() << \"K must be smaller or equal to side_length.\" );\n\n    int32 a = int32(floor(sqrt(float(k))));\n    int32 r = k - a*a;\n    int32 r_p_h_num = 0, r_pp_h_num = 0;\n    if ( 0 <= r && r <= a ) {\n      r_p_h_num = r;\n      r_pp_h_num = a - r;\n    } else if ( a + 1 <= r && r <= 2*a ) {\n      r_p_h_num = r - a;\n      r_pp_h_num = 2*a - r + 1;\n    } else {\n      vw_throw( LogicErr() << \"Split square has hit undiscovered error.\" );\n    }\n    int32 region_split =\n      int32(float(side_length * (a+1) * r_p_h_num)/float(k));\n    int32 r_p_h = r_p_h_num == 0 ? 0 : ceil(float(region_split) / float(r_p_h_num));\n    int32 r_pp_h = r_pp_h_num == 0 ? 0 : int32(ceil(float(side_length - region_split) / float(r_pp_h_num)));\n    int32 r_p_v = int32(ceil(float(side_length)/float(a + 1)));\n    int32 r_pp_v = int32(ceil(float(side_length)/float(a)));\n\n    int32 x,y;\n    if ( r_p_h != 0 ) {\n      // Adding boxes in the R' region\n      for (y = 0; y < side_length - r_p_v; y += r_p_v) {\n        for (x = 0; x < region_split - r_p_h; x += r_p_h)\n          result.push_back(BBox2i(x,y,r_p_h,r_p_v));\n        result.push_back(BBox2i(x,y,region_split-x,r_p_v));\n      }\n      for (x = 0; x < region_split - r_p_h; x += r_p_h )\n        result.push_back(BBox2i(x,y,r_p_h,side_length-y));\n      result.push_back(BBox2i(x,y,region_split-x,side_length-y));\n    }\n\n    // Adding boxes in the R'' region\n    if ( r_pp_h != 0 ) {\n      for (y = 0; y < side_length - r_pp_v; y += r_pp_v) {\n        for (x = region_split; x < side_length-r_pp_h; x += r_pp_h)\n          result.push_back(BBox2i(x,y,r_pp_h,r_pp_v));\n        result.push_back(BBox2i(x,y,side_length-x,r_pp_v));\n      }\n      for (x = region_split; x < side_length-r_pp_h; x += r_pp_h)\n        result.push_back(BBox2i(x,y,r_pp_h,side_length-y));\n      result.push_back(BBox2i(x,y,side_length-x,side_length-y));\n    }\n\n    return result;\n  }\n\n}\n", "meta": {"hexsha": "e843636f1f9a3ef2fde8fb24a2dd522c1e73ab9e", "size": 5752, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src_plate_old/photk/Common.cc", "max_stars_repo_name": "NeoGeographyToolkit/PhotometryTK", "max_stars_repo_head_hexsha": "edbfc3fa05ff5dd1c2905843f8f67e8f8f8bffe9", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-13T22:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:09:25.000Z", "max_issues_repo_path": "src_plate_old/photk/Common.cc", "max_issues_repo_name": "NeoGeographyToolkit/PhotometryTK", "max_issues_repo_head_hexsha": "edbfc3fa05ff5dd1c2905843f8f67e8f8f8bffe9", "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_plate_old/photk/Common.cc", "max_forks_repo_name": "NeoGeographyToolkit/PhotometryTK", "max_forks_repo_head_hexsha": "edbfc3fa05ff5dd1c2905843f8f67e8f8f8bffe9", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T12:36:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T01:04:32.000Z", "avg_line_length": 38.3466666667, "max_line_length": 134, "alphanum_fraction": 0.6015299026, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2568319970758679, "lm_q2_score": 0.02976009523675189, "lm_q1q2_score": 0.0076433446928230115}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Tensor/EagerMath/Magnitude.hpp\"\n#include \"Domain/FaceNormal.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Domain/Tags.hpp\"\n#include \"Domain/Tags/FaceNormal.hpp\"\n#include \"Domain/Tags/Faces.hpp\"\n#include \"Domain/Tags/SurfaceJacobian.hpp\"\n#include \"Elliptic/BoundaryConditions/ApplyBoundaryCondition.hpp\"\n#include \"Elliptic/DiscontinuousGalerkin/DgOperator.hpp\"\n#include \"Elliptic/DiscontinuousGalerkin/Initialization.hpp\"\n#include \"Elliptic/DiscontinuousGalerkin/Tags.hpp\"\n#include \"Elliptic/Systems/GetSourcesComputer.hpp\"\n#include \"Elliptic/Utilities/ApplyAt.hpp\"\n#include \"NumericalAlgorithms/DiscontinuousGalerkin/HasReceivedFromAllMortars.hpp\"\n#include \"NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.hpp\"\n#include \"NumericalAlgorithms/DiscontinuousGalerkin/Tags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Parallel/AlgorithmMetafunctions.hpp\"\n#include \"Parallel/GlobalCache.hpp\"\n#include \"Parallel/InboxInserters.hpp\"\n#include \"Parallel/Invoke.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/GetOutput.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/Literals.hpp\"\n#include \"Utilities/TMPL.hpp\"\n#include \"Utilities/TaggedTuple.hpp\"\n\n/// Actions related to elliptic discontinuous Galerkin schemes\nnamespace elliptic::dg::Actions {\n// The individual actions in this namespace are not exposed publicly because\n// they don't work on their own. Instead, the public interface (defined below)\n// exposes them in action lists.\nnamespace detail {\n\n// This tag is used to communicate mortar data across neighbors\ntemplate <size_t Dim, typename TemporalIdTag, typename PrimalFields,\n          typename PrimalFluxes>\nstruct MortarDataInboxTag\n    : public Parallel::InboxInserters::Map<\n          MortarDataInboxTag<Dim, TemporalIdTag, PrimalFields, PrimalFluxes>> {\n  using temporal_id = typename TemporalIdTag::type;\n  using type = std::map<\n      temporal_id,\n      FixedHashMap<maximum_number_of_neighbors(Dim), ::dg::MortarId<Dim>,\n                   elliptic::dg::BoundaryData<PrimalFields, PrimalFluxes>,\n                   boost::hash<::dg::MortarId<Dim>>>>;\n};\n\n// Initializes all quantities the DG operator needs on internal and external\n// faces, as well as the mortars between neighboring elements. Also initializes\n// the variable-independent background fields in the PDEs.\ntemplate <typename System, typename BackgroundTag>\nstruct InitializeFacesMortarsAndBackground {\n private:\n  static constexpr size_t Dim = System::volume_dim;\n  static constexpr bool has_background_fields =\n      not std::is_same_v<typename System::background_fields, tmpl::list<>>;\n  static_assert(\n      not(has_background_fields and std::is_same_v<BackgroundTag, void>),\n      \"The system has background fields that need initialization. Supply a \"\n      \"'BackgroundTag' to 'elliptic::dg::Actions::initialize_operator'.\");\n\n  using InitializeFacesAndMortars =\n      elliptic::dg::InitializeFacesAndMortars<Dim,\n                                              typename System::inv_metric_tag>;\n  using InitializeBackground =\n      elliptic::dg::InitializeBackground<Dim,\n                                         typename System::background_fields>;\n\n public:\n  using simple_tags = tmpl::append<\n      typename InitializeFacesAndMortars::return_tags,\n      tmpl::conditional_t<has_background_fields,\n                          typename InitializeBackground::return_tags,\n                          tmpl::list<>>>;\n  using compute_tags = tmpl::list<>;\n\n  template <typename DbTagsList, typename... InboxTags, typename Metavariables,\n            typename ArrayIndex, typename ActionList,\n            typename ParallelComponent>\n  static std::tuple<db::DataBox<DbTagsList>&&> apply(\n      db::DataBox<DbTagsList>& box,\n      const tuples::TaggedTuple<InboxTags...>& /*inboxes*/,\n      const Parallel::GlobalCache<Metavariables>& /*cache*/,\n      const ArrayIndex& /*array_index*/, ActionList /*meta*/,\n      const ParallelComponent* const /*meta*/) {\n    if constexpr (has_background_fields) {\n      const auto& background = db::get<BackgroundTag>(box);\n      using background_classes =\n          tmpl::at<typename Metavariables::factory_creation::factory_classes,\n                   std::decay_t<decltype(background)>>;\n      // Initialize faces and mortars\n      db::mutate_apply<typename InitializeFacesAndMortars::return_tags,\n                       typename InitializeFacesAndMortars::argument_tags>(\n          InitializeFacesAndMortars{}, make_not_null(&box),\n          db::get<domain::Tags::InitialExtents<Dim>>(box), background,\n          background_classes{});\n      // Initialize background fields\n      db::mutate_apply<typename InitializeBackground::return_tags,\n                       typename InitializeBackground::argument_tags>(\n          InitializeBackground{}, make_not_null(&box), background,\n          background_classes{});\n    } else {\n      // Initialize faces and mortars\n      db::mutate_apply<typename InitializeFacesAndMortars::return_tags,\n                       typename InitializeFacesAndMortars::argument_tags>(\n          InitializeFacesAndMortars{}, make_not_null(&box),\n          db::get<domain::Tags::InitialExtents<Dim>>(box));\n    }\n    return {std::move(box)};\n  }\n};\n\n// Compute auxiliary variables and fluxes from the primal variables, prepare the\n// local side of all mortars and send the local mortar data to neighbors. Also\n// handle boundary conditions by preparing the exterior (\"ghost\") side of\n// external mortars.\ntemplate <typename System, bool Linearized, typename TemporalIdTag,\n          typename PrimalFieldsTag, typename PrimalFluxesTag,\n          typename OperatorAppliedToFieldsTag, typename PrimalMortarFieldsTag,\n          typename PrimalMortarFluxesTag,\n          typename FluxesArgsTags =\n              typename System::fluxes_computer::argument_tags,\n          typename SourcesArgsTags = typename elliptic::get_sources_computer<\n              System, Linearized>::argument_tags>\nstruct PrepareAndSendMortarData;\n\ntemplate <typename System, bool Linearized, typename TemporalIdTag,\n          typename PrimalFieldsTag, typename PrimalFluxesTag,\n          typename OperatorAppliedToFieldsTag, typename PrimalMortarFieldsTag,\n          typename PrimalMortarFluxesTag, typename... FluxesArgsTags,\n          typename... SourcesArgsTags>\nstruct PrepareAndSendMortarData<\n    System, Linearized, TemporalIdTag, PrimalFieldsTag, PrimalFluxesTag,\n    OperatorAppliedToFieldsTag, PrimalMortarFieldsTag, PrimalMortarFluxesTag,\n    tmpl::list<FluxesArgsTags...>, tmpl::list<SourcesArgsTags...>> {\n private:\n  static constexpr size_t Dim = System::volume_dim;\n  using all_mortar_data_tag = ::Tags::Mortars<\n      elliptic::dg::Tags::MortarData<typename TemporalIdTag::type,\n                                     typename PrimalMortarFieldsTag::tags_list,\n                                     typename PrimalMortarFluxesTag::tags_list>,\n      Dim>;\n  using mortar_data_inbox_tag =\n      MortarDataInboxTag<Dim, TemporalIdTag,\n                         typename PrimalMortarFieldsTag::tags_list,\n                         typename PrimalMortarFluxesTag::tags_list>;\n  using BoundaryConditionsBase = typename System::boundary_conditions_base;\n\n public:\n  // Request these tags be added to the DataBox by the `SetupDataBox` action. We\n  // don't actually need to initialize them, because the `TemporalIdTag` and the\n  // `PrimalFieldsTag` will be set by other actions before applying the operator\n  // and the remaining tags hold output of the operator.\n  using simple_tags =\n      tmpl::list<TemporalIdTag, PrimalFieldsTag, PrimalFluxesTag,\n                 OperatorAppliedToFieldsTag, all_mortar_data_tag>;\n  using compute_tags = tmpl::list<>;\n\n  template <typename DbTagsList, typename... InboxTags, typename Metavariables,\n            typename ActionList, typename ParallelComponent>\n  static std::tuple<db::DataBox<DbTagsList>&&> apply(\n      db::DataBox<DbTagsList>& box,\n      const tuples::TaggedTuple<InboxTags...>& /*inboxes*/,\n      Parallel::GlobalCache<Metavariables>& cache,\n      const ElementId<Dim>& element_id, const ActionList /*meta*/,\n      const ParallelComponent* const /*meta*/) {\n    // Used to retrieve items out of the DataBox to forward to functions\n    const auto get_items = [](const auto&... args) {\n      return std::forward_as_tuple(args...);\n    };\n    const auto& temporal_id = db::get<TemporalIdTag>(box);\n    const auto& element = db::get<domain::Tags::Element<Dim>>(box);\n    const auto& mesh = db::get<domain::Tags::Mesh<Dim>>(box);\n    const size_t num_points = mesh.number_of_grid_points();\n    const auto& mortar_meshes =\n        db::get<::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>>(box);\n    const auto& domain = db::get<domain::Tags::Domain<Dim>>(box);\n    const auto& boundary_conditions = domain.blocks()\n                                          .at(element_id.block_id())\n                                          .external_boundary_conditions();\n    const auto apply_boundary_condition =\n        [&box, &boundary_conditions, &element_id](\n            const Direction<Dim>& direction, const auto... fields_and_fluxes) {\n          ASSERT(\n              boundary_conditions.contains(direction),\n              \"No boundary condition is available in block \"\n                  << element_id.block_id() << \" in direction \" << direction\n                  << \". Make sure you are setting up boundary conditions when \"\n                     \"creating the domain.\");\n          ASSERT(dynamic_cast<const BoundaryConditionsBase*>(\n                     boundary_conditions.at(direction).get()) != nullptr,\n                 \"The boundary condition in block \"\n                     << element_id.block_id() << \" in direction \" << direction\n                     << \" has an unexpected type. Make sure it derives off the \"\n                        \"'boundary_conditions_base' class set in the system.\");\n          const auto& boundary_condition =\n              dynamic_cast<const BoundaryConditionsBase&>(\n                  *boundary_conditions.at(direction));\n          elliptic::apply_boundary_condition<Linearized>(\n              boundary_condition, box, direction, fields_and_fluxes...);\n        };\n\n    // Can't `db::get` the arguments for the boundary conditions within\n    // `db::mutate`, so we extract the data to mutate and move it back in when\n    // we're done.\n    typename PrimalFluxesTag::type primal_fluxes;\n    typename all_mortar_data_tag::type all_mortar_data;\n    db::mutate<PrimalFluxesTag, all_mortar_data_tag>(\n        make_not_null(&box),\n        [&primal_fluxes, &all_mortar_data](const auto local_primal_fluxes,\n                                           const auto local_all_mortar_data) {\n          primal_fluxes = std::move(*local_primal_fluxes);\n          all_mortar_data = std::move(*local_all_mortar_data);\n        });\n\n    // Prepare mortar data\n    //\n    // These memory buffers will be discarded when the action returns so we\n    // don't inflate the memory usage of the simulation when the element is\n    // inactive.\n    Variables<typename System::auxiliary_fields> auxiliary_fields_buffer{\n        num_points};\n    Variables<typename System::auxiliary_fluxes> auxiliary_fluxes_buffer{\n        num_points};\n    using fluxes_args_tags = typename System::fluxes_computer::argument_tags;\n    using fluxes_args_volume_tags =\n        typename System::fluxes_computer::volume_tags;\n    DirectionMap<Dim, std::tuple<decltype(db::get<FluxesArgsTags>(box))...>>\n        fluxes_args_on_faces{};\n    for (const auto& direction : Direction<Dim>::all_directions()) {\n      fluxes_args_on_faces.emplace(\n          direction, elliptic::util::apply_at<\n                         domain::make_faces_tags<Dim, fluxes_args_tags,\n                                                 fluxes_args_volume_tags>,\n                         fluxes_args_volume_tags>(get_items, box, direction));\n    }\n    elliptic::dg::prepare_mortar_data<System, Linearized>(\n        make_not_null(&auxiliary_fields_buffer),\n        make_not_null(&auxiliary_fluxes_buffer), make_not_null(&primal_fluxes),\n        make_not_null(&all_mortar_data), db::get<PrimalFieldsTag>(box), element,\n        db::get<domain::Tags::Mesh<Dim>>(box),\n        db::get<domain::Tags::InverseJacobian<Dim, Frame::ElementLogical,\n                                              Frame::Inertial>>(box),\n        db::get<domain::Tags::Faces<Dim, domain::Tags::FaceNormal<Dim>>>(box),\n        db::get<domain::Tags::Faces<\n            Dim, domain::Tags::UnnormalizedFaceNormalMagnitude<Dim>>>(box),\n        mortar_meshes,\n        db::get<::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>>(box),\n        temporal_id, apply_boundary_condition,\n        std::forward_as_tuple(db::get<FluxesArgsTags>(box)...),\n        std::forward_as_tuple(db::get<SourcesArgsTags>(box)...),\n        fluxes_args_on_faces);\n\n    // Move the mutated data back into the DataBox\n    db::mutate<PrimalFluxesTag, all_mortar_data_tag>(\n        make_not_null(&box),\n        [&primal_fluxes, &all_mortar_data](const auto local_primal_fluxes,\n                                           const auto local_all_mortar_data) {\n          *local_primal_fluxes = std::move(primal_fluxes);\n          *local_all_mortar_data = std::move(all_mortar_data);\n        });\n\n    // Send mortar data to neighbors\n    auto& receiver_proxy =\n        Parallel::get_parallel_component<ParallelComponent>(cache);\n    for (const auto& [direction, neighbors] : element.neighbors()) {\n      const size_t dimension = direction.dimension();\n      const auto& orientation = neighbors.orientation();\n      const auto direction_from_neighbor = orientation(direction.opposite());\n      for (const auto& neighbor_id : neighbors) {\n        const ::dg::MortarId<Dim> mortar_id{direction, neighbor_id};\n        // Make a copy of the local boundary data on the mortar to send to the\n        // neighbor\n        auto remote_boundary_data_on_mortar =\n            get<all_mortar_data_tag>(box).at(mortar_id).local_data(\n                temporal_id);\n        // Reorient the data to the neighbor orientation if necessary\n        if (not orientation.is_aligned()) {\n          remote_boundary_data_on_mortar.orient_on_slice(\n              mortar_meshes.at(mortar_id).extents(), dimension, orientation);\n        }\n        // Send remote data to neighbor\n        Parallel::receive_data<mortar_data_inbox_tag>(\n            receiver_proxy[neighbor_id], temporal_id,\n            std::make_pair(\n                ::dg::MortarId<Dim>{direction_from_neighbor, element.id()},\n                std::move(remote_boundary_data_on_mortar)));\n      }  // loop over neighbors in direction\n    }    // loop over directions\n\n    return {std::move(box)};\n  }\n};\n\n// Wait until all mortar data from neighbors is available. Then add boundary\n// corrections to the primal fluxes, compute their derivatives (i.e. the second\n// derivatives of the primal variables) and add boundary corrections to the\n// result.\ntemplate <typename System, bool Linearized, typename TemporalIdTag,\n          typename PrimalFieldsTag, typename PrimalFluxesTag,\n          typename OperatorAppliedToFieldsTag, typename PrimalMortarFieldsTag,\n          typename PrimalMortarFluxesTag,\n          typename FluxesArgsTags =\n              typename System::fluxes_computer::argument_tags,\n          typename SourcesArgsTags = typename elliptic::get_sources_computer<\n              System, Linearized>::argument_tags>\nstruct ReceiveMortarDataAndApplyOperator;\n\ntemplate <typename System, bool Linearized, typename TemporalIdTag,\n          typename PrimalFieldsTag, typename PrimalFluxesTag,\n          typename OperatorAppliedToFieldsTag, typename PrimalMortarFieldsTag,\n          typename PrimalMortarFluxesTag, typename... FluxesArgsTags,\n          typename... SourcesArgsTags>\nstruct ReceiveMortarDataAndApplyOperator<\n    System, Linearized, TemporalIdTag, PrimalFieldsTag, PrimalFluxesTag,\n    OperatorAppliedToFieldsTag, PrimalMortarFieldsTag, PrimalMortarFluxesTag,\n    tmpl::list<FluxesArgsTags...>, tmpl::list<SourcesArgsTags...>> {\n private:\n  static constexpr size_t Dim = System::volume_dim;\n  using all_mortar_data_tag = ::Tags::Mortars<\n      elliptic::dg::Tags::MortarData<typename TemporalIdTag::type,\n                                     typename PrimalMortarFieldsTag::tags_list,\n                                     typename PrimalMortarFluxesTag::tags_list>,\n      Dim>;\n  using mortar_data_inbox_tag =\n      MortarDataInboxTag<Dim, TemporalIdTag,\n                         typename PrimalMortarFieldsTag::tags_list,\n                         typename PrimalMortarFluxesTag::tags_list>;\n\n public:\n  using const_global_cache_tags =\n      tmpl::list<elliptic::dg::Tags::PenaltyParameter,\n                 elliptic::dg::Tags::Massive>;\n  using inbox_tags = tmpl::list<mortar_data_inbox_tag>;\n\n  template <typename DbTags, typename... InboxTags, typename Metavariables,\n            typename ArrayIndex, typename ActionList,\n            typename ParallelComponent>\n  static std::tuple<db::DataBox<DbTags>&&, Parallel::AlgorithmExecution> apply(\n      db::DataBox<DbTags>& box, tuples::TaggedTuple<InboxTags...>& inboxes,\n      const Parallel::GlobalCache<Metavariables>& /*cache*/,\n      const ArrayIndex& /*array_index*/, const ActionList /*meta*/,\n      const ParallelComponent* const /*meta*/) {\n    const auto& temporal_id = get<TemporalIdTag>(box);\n    const auto& element = get<domain::Tags::Element<Dim>>(box);\n\n    if (not ::dg::has_received_from_all_mortars<mortar_data_inbox_tag>(\n            temporal_id, element, inboxes)) {\n      return {std::move(box), Parallel::AlgorithmExecution::Retry};\n    }\n\n    // Move received \"remote\" mortar data into the DataBox\n    if (LIKELY(element.number_of_neighbors() > 0)) {\n      auto received_mortar_data =\n          std::move(tuples::get<mortar_data_inbox_tag>(inboxes)\n                        .extract(temporal_id)\n                        .mapped());\n      db::mutate<all_mortar_data_tag>(\n          make_not_null(&box),\n          [&received_mortar_data, &temporal_id](const auto all_mortar_data) {\n            for (auto& [mortar_id, mortar_data] : received_mortar_data) {\n              all_mortar_data->at(mortar_id).remote_insert(\n                  temporal_id, std::move(mortar_data));\n            }\n          });\n    }\n\n    // Apply DG operator\n    db::mutate<OperatorAppliedToFieldsTag, all_mortar_data_tag>(\n        make_not_null(&box),\n        [](const auto&... args) {\n          elliptic::dg::apply_operator<System, Linearized>(args...);\n        },\n        db::get<PrimalFieldsTag>(box), db::get<PrimalFluxesTag>(box), element,\n        db::get<domain::Tags::Mesh<Dim>>(box),\n        db::get<domain::Tags::InverseJacobian<Dim, Frame::ElementLogical,\n                                              Frame::Inertial>>(box),\n        db::get<domain::Tags::DetInvJacobian<Frame::ElementLogical,\n                                             Frame::Inertial>>(box),\n        db::get<domain::Tags::Faces<\n            Dim, domain::Tags::UnnormalizedFaceNormalMagnitude<Dim>>>(box),\n        db::get<domain::Tags::Faces<\n            Dim, domain::Tags::DetSurfaceJacobian<Frame::ElementLogical,\n                                                  Frame::Inertial>>>(box),\n        db::get<::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>>(box),\n        db::get<::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>>(box),\n        db::get<::Tags::Mortars<domain::Tags::DetSurfaceJacobian<\n                                    Frame::ElementLogical, Frame::Inertial>,\n                                Dim>>(box),\n        db::get<elliptic::dg::Tags::PenaltyParameter>(box),\n        db::get<elliptic::dg::Tags::Massive>(box), temporal_id,\n        std::forward_as_tuple(db::get<SourcesArgsTags>(box)...));\n\n    return {std::move(box), Parallel::AlgorithmExecution::Continue};\n  }\n};\n\n}  // namespace detail\n\n/*!\n * \\brief Initialize geometric and background quantities for the elliptic DG\n * operator\n *\n * The geometric and background quantities are initialized together because the\n * geometry depends on the background metric through the normalization of face\n * normals. Other examples for background fields are curvature quantities\n * associated with the background metric, or matter sources such as a\n * mass-density in the XCTS equations. All `System::background_fields` are\n * retrieved from the `BackgroundTag` together, to enable re-using cached\n * temporary quantities in the computations. The `variables` function is invoked\n * on the `BackgroundTag` with the inertial coordinates, the element's `Mesh`\n * and the element's inverse Jacobian. These arguments allow computing numeric\n * derivatives, if necessary. The `BackgroundTag` can be set to `void` (default)\n * if the `System` has no background fields.\n *\n * DataBox:\n * - Uses:\n *   - `domain::Tags::InitialExtents<Dim>`\n *   - `BackgroundTag`\n * - Adds:\n *   - `::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>`\n *   - `::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>`\n *   - `::Tags::Variables<background_fields>`\n * - Adds on internal and external faces:\n *   - `domain::Tags::Coordinates<Dim, Frame::Inertial>`\n *   - `::Tags::Normalized<domain::Tags::UnnormalizedFaceNormal<Dim>>`\n *   - `::Tags::Magnitude<domain::Tags::UnnormalizedFaceNormal<Dim>>`\n *   - `::Tags::Variables<background_fields>`\n *\n * \\note This action relies on the `SetupDataBox` aggregated initialization\n * mechanism, so `Actions::SetupDataBox` must be present in the `Initialization`\n * phase action list prior to this action.\n *\n * \\see elliptic::dg::Actions::apply_operator\n */\ntemplate <typename System, typename BackgroundTag = void>\nusing initialize_operator = tmpl::list<\n    detail::InitializeFacesMortarsAndBackground<System, BackgroundTag>>;\n\n/*!\n * \\brief Apply the DG operator to the `PrimalFieldsTag` and write the result to\n * the `OperatorAppliedToFieldsTag`\n *\n * Add this list to the action list of a parallel component to compute the\n * elliptic DG operator or its linearization. The operator involves a\n * communication between nearest-neighbor elements. See `elliptic::dg` for\n * details on the elliptic DG operator. Make sure to add\n * `elliptic::dg::Actions::initialize_operator` to the initialization phase of\n * your parallel component so the required DataBox tags are set up before\n * applying the operator.\n *\n * The result of the computation is written to the `OperatorAppliedToFieldsTag`.\n * Additionally, the primal fluxes are written to the `PrimalFluxesTag` as an\n * intermediate result. The auxiliary fields and fluxes are discarded to avoid\n * inflating the memory usage.\n *\n * You can specify the `PrimalMortarFieldsTag` and the `PrimalMortarFluxesTag`\n * to re-use mortar-data memory buffers from other operator applications, for\n * example when applying the nonlinear and linearized operator. They default to\n * the `PrimalFieldsTag` and the `PrimalFluxesTag`, meaning memory buffers\n * corresponding to these tags are set up in the DataBox.\n */\ntemplate <typename System, bool Linearized, typename TemporalIdTag,\n          typename PrimalFieldsTag, typename PrimalFluxesTag,\n          typename OperatorAppliedToFieldsTag,\n          typename PrimalMortarFieldsTag = PrimalFieldsTag,\n          typename PrimalMortarFluxesTag = PrimalFluxesTag>\nusing apply_operator =\n    tmpl::list<detail::PrepareAndSendMortarData<\n                   System, Linearized, TemporalIdTag, PrimalFieldsTag,\n                   PrimalFluxesTag, OperatorAppliedToFieldsTag,\n                   PrimalMortarFieldsTag, PrimalMortarFluxesTag>,\n               detail::ReceiveMortarDataAndApplyOperator<\n                   System, Linearized, TemporalIdTag, PrimalFieldsTag,\n                   PrimalFluxesTag, OperatorAppliedToFieldsTag,\n                   PrimalMortarFieldsTag, PrimalMortarFluxesTag>>;\n\n/*!\n * \\brief For linear systems, impose inhomogeneous boundary conditions as\n * contributions to the fixed sources (i.e. the RHS of the equations).\n *\n * \\see elliptic::dg::impose_inhomogeneous_boundary_conditions_on_source\n */\ntemplate <\n    typename System, typename FixedSourcesTag,\n    typename FluxesArgsTags = typename System::fluxes_computer::argument_tags,\n    typename SourcesArgsTags = typename System::sources_computer::argument_tags>\nstruct ImposeInhomogeneousBoundaryConditionsOnSource;\n\n/// \\cond\ntemplate <typename System, typename FixedSourcesTag, typename... FluxesArgsTags,\n          typename... SourcesArgsTags>\nstruct ImposeInhomogeneousBoundaryConditionsOnSource<\n    System, FixedSourcesTag, tmpl::list<FluxesArgsTags...>,\n    tmpl::list<SourcesArgsTags...>> {\n private:\n  static constexpr size_t Dim = System::volume_dim;\n  using BoundaryConditionsBase = typename System::boundary_conditions_base;\n\n public:\n  using const_global_cache_tags =\n      tmpl::list<elliptic::dg::Tags::PenaltyParameter,\n                 elliptic::dg::Tags::Massive>;\n\n  template <typename DbTags, typename... InboxTags, typename Metavariables,\n            typename ActionList, typename ParallelComponent>\n  static std::tuple<db::DataBox<DbTags>&&> apply(\n      db::DataBox<DbTags>& box,\n      const tuples::TaggedTuple<InboxTags...>& /*inboxes*/,\n      const Parallel::GlobalCache<Metavariables>& /*cache*/,\n      const ElementId<Dim>& element_id, const ActionList /*meta*/,\n      const ParallelComponent* const /*meta*/) {\n    // Used to retrieve items out of the DataBox to forward to functions\n    const auto get_items = [](const auto&... args) {\n      return std::forward_as_tuple(args...);\n    };\n    const auto& domain = db::get<domain::Tags::Domain<Dim>>(box);\n    const auto& boundary_conditions = domain.blocks()\n                                          .at(element_id.block_id())\n                                          .external_boundary_conditions();\n    const auto apply_boundary_condition =\n        [&box, &boundary_conditions, &element_id](\n            const Direction<Dim>& direction, const auto... fields_and_fluxes) {\n          ASSERT(\n              boundary_conditions.contains(direction),\n              \"No boundary condition is available in block \"\n                  << element_id.block_id() << \" in direction \" << direction\n                  << \". Make sure you are setting up boundary conditions when \"\n                     \"creating the domain.\");\n          ASSERT(dynamic_cast<const BoundaryConditionsBase*>(\n                     boundary_conditions.at(direction).get()) != nullptr,\n                 \"The boundary condition in block \"\n                     << element_id.block_id() << \" in direction \" << direction\n                     << \" has an unexpected type. Make sure it derives off the \"\n                        \"'boundary_conditions_base' class set in the system.\");\n          const auto& boundary_condition =\n              dynamic_cast<const BoundaryConditionsBase&>(\n                  *boundary_conditions.at(direction));\n          elliptic::apply_boundary_condition<false>(\n              boundary_condition, box, direction, fields_and_fluxes...);\n        };\n\n    // Can't `db::get` the arguments for the boundary conditions within\n    // `db::mutate`, so we extract the data to mutate and move it back in when\n    // we're done.\n    typename FixedSourcesTag::type fixed_sources;\n    db::mutate<FixedSourcesTag>(\n        make_not_null(&box), [&fixed_sources](const auto local_fixed_sources) {\n          fixed_sources = std::move(*local_fixed_sources);\n        });\n\n    using fluxes_args_tags = typename System::fluxes_computer::argument_tags;\n    using fluxes_args_volume_tags =\n        typename System::fluxes_computer::volume_tags;\n    DirectionMap<Dim, std::tuple<decltype(db::get<FluxesArgsTags>(box))...>>\n        fluxes_args_on_faces{};\n    for (const auto& direction : Direction<Dim>::all_directions()) {\n      fluxes_args_on_faces.emplace(\n          direction, elliptic::util::apply_at<\n                         domain::make_faces_tags<Dim, fluxes_args_tags,\n                                                 fluxes_args_volume_tags>,\n                         fluxes_args_volume_tags>(get_items, box, direction));\n    }\n\n    elliptic::dg::impose_inhomogeneous_boundary_conditions_on_source<System>(\n        make_not_null(&fixed_sources), db::get<domain::Tags::Element<Dim>>(box),\n        db::get<domain::Tags::Mesh<Dim>>(box),\n        db::get<domain::Tags::InverseJacobian<Dim, Frame::ElementLogical,\n                                              Frame::Inertial>>(box),\n        db::get<domain::Tags::DetInvJacobian<Frame::ElementLogical,\n                                             Frame::Inertial>>(box),\n        db::get<domain::Tags::Faces<Dim, domain::Tags::FaceNormal<Dim>>>(box),\n        db::get<domain::Tags::Faces<\n            Dim, domain::Tags::UnnormalizedFaceNormalMagnitude<Dim>>>(box),\n        db::get<::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>>(box),\n        db::get<::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>>(box),\n        db::get<elliptic::dg::Tags::PenaltyParameter>(box),\n        db::get<elliptic::dg::Tags::Massive>(box), apply_boundary_condition,\n        std::forward_as_tuple(db::get<FluxesArgsTags>(box)...),\n        std::forward_as_tuple(db::get<SourcesArgsTags>(box)...),\n        fluxes_args_on_faces);\n\n    // Move the mutated data back into the DataBox\n    db::mutate<FixedSourcesTag>(\n        make_not_null(&box), [&fixed_sources](const auto local_fixed_sources) {\n          *local_fixed_sources = std::move(fixed_sources);\n        });\n    return {std::move(box)};\n  }\n};\n/// \\endcond\n\n}  // namespace elliptic::dg::Actions\n", "meta": {"hexsha": "a7db027f7f196fc6f7f112089f95f7cd78fa3b66", "size": 30035, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Elliptic/DiscontinuousGalerkin/Actions/ApplyOperator.hpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T00:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:17:33.000Z", "max_issues_repo_path": "src/Elliptic/DiscontinuousGalerkin/Actions/ApplyOperator.hpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Elliptic/DiscontinuousGalerkin/Actions/ApplyOperator.hpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9967373573, "max_line_length": 82, "alphanum_fraction": 0.6741135342, "num_tokens": 6910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.017442481831261, "lm_q1q2_score": 0.0076367284285985835}}
{"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_DETAIL_STRXOR_HPP\n#define CRYPTO3_DETAIL_STRXOR_HPP\n\n#include <iterator>\n\n#include <boost/concept/assert.hpp>\n#include <boost/assert.hpp>\n#include <boost/range/concepts.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n            template<typename InputIterator1, typename InputIterator2, typename OutputIterator>\n            constexpr inline typename std::enable_if<\n                std::is_same<typename std::iterator_traits<InputIterator1>::value_type,\n                             typename std::iterator_traits<InputIterator2>::value_type>::value &&\n                    std::is_same<typename std::iterator_traits<InputIterator1>::value_type,\n                                 typename std::iterator_traits<OutputIterator>::value_type>::value,\n                OutputIterator>::type\n                strxor(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2,\n                       OutputIterator out) {\n                BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<InputIterator1>));\n                BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<InputIterator2>));\n                BOOST_CONCEPT_ASSERT(\n                    (boost::OutputIteratorConcept<OutputIterator,\n                                                  typename std::iterator_traits<OutputIterator>::value_type>));\n\n                assert(std::distance(first1, last1) == std::distance(first2, last2));\n\n                for (; first1 != last1 && first2 != last2; first1++, first2++, out++) {\n                    *out = *first1 ^ *first2;\n                }\n\n                return out;\n            }\n\n            template<typename InputRange1, typename InputRange2, typename OutputIterator>\n            constexpr inline OutputIterator strxor(const InputRange1 &in1, const InputRange2 &in2, OutputIterator out) {\n                BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<InputRange1>));\n                BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<InputRange2>));\n\n                return strxor(in1.cbegin(), in1.cend(), in2.cbegin(), in2.cend(), out);\n            }\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_DETAIL_STRXOR_HPP\n", "meta": {"hexsha": "64b4ae37e74832a6e5669472eee12edfbc0bdf11", "size": 3649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/strxor.hpp", "max_stars_repo_name": "JasonCoombs/crypto3-hash", "max_stars_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_stars_repo_licenses": ["MIT"], "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/detail/strxor.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-hash", "max_issues_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "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/strxor.hpp", "max_forks_repo_name": "JasonCoombs/crypto3-hash", "max_forks_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "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": 49.3108108108, "max_line_length": 120, "alphanum_fraction": 0.6377089614, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070997458932, "lm_q2_score": 0.0346188415781891, "lm_q1q2_score": 0.007616390932179923}}
{"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#define BOOST_PYTHON_MAX_ARITY 17\n\n#include \"PyImathMatrix.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathDecorators.h\"\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include <boost/python/tuple.hpp>\n#include <boost/python/dict.hpp>\n#include <boost/python/raw_function.hpp>\n#include \"PyImath.h\"\n#include \"PyImathVec.h\"\n#include \"PyImathMathExc.h\"\n#include <ImathVec.h>\n#include <ImathMatrixAlgo.h>\n#include <Iex.h>\n\nnamespace PyImath {\n\ntemplate<> const char *PyImath::M33fArray::name() { return \"M33fArray\"; }\ntemplate<> const char *PyImath::M33dArray::name() { return \"M33dArray\"; }\n\nusing namespace boost::python;\nusing namespace IMATH_NAMESPACE;\n\ntemplate <class T, int len>\nstruct MatrixRow {\n    explicit MatrixRow(T *data) : _data(data) {}\n    T & operator [] (int i) { return _data[i]; }\n    T *_data;\n\n    static const char *name;\n    static void register_class()\n    {\n        typedef PyImath::StaticFixedArray<MatrixRow,T,len> MatrixRow_helper;\n        class_<MatrixRow> matrixRow_class(name,no_init);\n        matrixRow_class\n            .def(\"__len__\", MatrixRow_helper::len)\n            .def(\"__getitem__\", MatrixRow_helper::getitem,return_value_policy<copy_non_const_reference>())\n            .def(\"__setitem__\", MatrixRow_helper::setitem)\n            ;\n    }\n};\n\ntemplate <> const char *MatrixRow<float,3>::name = \"M33fRow\";\ntemplate <> const char *MatrixRow<double,3>::name = \"M33dRow\";\n\n\ntemplate <class Container, class Data, int len>\nstruct IndexAccessMatrixRow {\n    typedef MatrixRow<Data,len> result_type;\n    static MatrixRow<Data,len> apply(Container &c, int i) { return MatrixRow<Data,len>(c[i]); }\n};\n\ntemplate <class T> struct Matrix33Name { static const char *value; };\ntemplate<> const char *Matrix33Name<float>::value  = \"M33f\";\ntemplate<> const char *Matrix33Name<double>::value = \"M33d\";\n\ntemplate <class T>\nstatic std::string Matrix33_str(const Matrix33<T> &v)\n{\n    std::stringstream stream;\n    stream << Matrix33Name<T>::value << \"(\";\n    for (int row = 0; row < 3; row++)\n    {\n        stream << \"(\";\n\tfor (int col = 0; col < 3; col++)\n\t{\n\t    stream << v[row][col];\n            stream << (col != 2 ? \", \" : \"\");\n\t}\n        stream << \")\" << (row != 2 ? \", \" : \"\");\n    }\n    stream << \")\";\n    return stream.str();\n}\n\n// Non-specialized repr is same as str\ntemplate <class T>\nstatic std::string Matrix33_repr(const Matrix33<T> &v)\n{\n    return Matrix33_str(v);\n}\n\n// Specialization for float to full precision\ntemplate <>\nstd::string Matrix33_repr(const Matrix33<float> &v)\n{\n    return (boost::format(\"%s((%.9g, %.9g, %.9g), (%.9g, %.9g, %.9g), (%.9g, %.9g, %.9g))\")\n                        % Matrix33Name<float>::value\n                        % v[0][0] % v[0][1] % v[0][2]\n                        % v[1][0] % v[1][1] % v[1][2]\n                        % v[2][0] % v[2][1] % v[2][2]).str();\n}\n\n// Specialization for double to full precision\ntemplate <>\nstd::string Matrix33_repr(const Matrix33<double> &v)\n{\n    return (boost::format(\"%s((%.17g, %.17g, %.17g), (%.17g, %.17g, %.17g), (%.17g, %.17g, %.17g))\")\n                        % Matrix33Name<double>::value\n                        % v[0][0] % v[0][1] % v[0][2]\n                        % v[1][0] % v[1][1] % v[1][2]\n                        % v[2][0] % v[2][1] % v[2][2]).str();\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\ninvert33 (Matrix33<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.invert(singExc);\n}\n\ntemplate <class T>\nstatic Matrix33<T>\ninverse33 (Matrix33<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.inverse(singExc);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\ngjInvert33 (Matrix33<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.gjInvert(singExc);\n}\n\ntemplate <class T>\nstatic Matrix33<T>\ngjInverse33 (Matrix33<T> &m, bool singExc = true)\n{\n    MATH_EXC_ON;\n    return m.gjInverse(singExc);\n}\n\ntemplate <class T, class U>\nstatic const Matrix33<T> &\niadd33(Matrix33<T> &m, const Matrix33<U> &m2)\n{\n    MATH_EXC_ON;\n    Matrix33<T> m3;\n    m3.setValue (m2);\n    return m += m3;\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\niadd33T(Matrix33<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    return mat += a;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nadd33(Matrix33<T> &m, const Matrix33<T> &m2)\n{\n    MATH_EXC_ON;\n    return m + m2;\n}\n\ntemplate <class T, class U>\nstatic const Matrix33<T> &\nisub33(Matrix33<T> &m, const Matrix33<U> &m2)\n{\n    MATH_EXC_ON;\n    Matrix33<T> m3;\n    m3.setValue (m2);\n    return m -= m3;\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nisub33T(Matrix33<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    return mat -= a;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nsub33(Matrix33<T> &m, const Matrix33<T> &m2)\n{\n    MATH_EXC_ON;\n    return m - m2;\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nnegate33 (Matrix33<T> &m)\n{\n    MATH_EXC_ON;\n    return m.negate();\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nneg33 (Matrix33<T> &m)\n{\n    MATH_EXC_ON;\n    return -m;\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nimul33T(Matrix33<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m *= t;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nmul33T(Matrix33<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m * t;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nrmul33T(Matrix33<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return t * m;\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nidiv33T(Matrix33<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m /= t;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\ndiv33T(Matrix33<T> &m, const T &t)\n{\n    MATH_EXC_ON;\n    return m / t;\n}\n\ntemplate <class T>\nstatic void \nextractAndRemoveScalingAndShear33(Matrix33<T> &mat, IMATH_NAMESPACE::Vec2<T> &dstScl, IMATH_NAMESPACE::Vec2<T> &dstShr, int exc = 1)\n{\n    MATH_EXC_ON;\n    T dstShrTmp;\n    IMATH_NAMESPACE::extractAndRemoveScalingAndShear(mat, dstScl, dstShrTmp, exc);\n\n    dstShr.setValue(dstShrTmp, T (0));\n}\n\ntemplate <class T>\nstatic void\nextractEuler(Matrix33<T> &mat, Vec2<T> &dstObj)\n{\n    MATH_EXC_ON;\n    T dst;\n    IMATH_NAMESPACE::extractEuler(mat, dst);\n    dstObj.setValue(dst, T (0));\n}\n\ntemplate <class T>\nstatic int\nextractSHRT33(Matrix33<T> &mat, Vec2<T> &s, Vec2<T> &h, Vec2<T> &r, Vec2<T> &t, int exc = 1)\n{\n    MATH_EXC_ON;\n    T hTmp, rTmp;\n    \n    int b = IMATH_NAMESPACE::extractSHRT(mat, s, hTmp, rTmp, t, exc);\n    \n    h.setValue(hTmp, T (0));\n    r.setValue(rTmp, T (0));\n    \n    return b;\n}\n\ntemplate <class T>\nstatic void\nextractScaling33(Matrix33<T> &mat, Vec2<T> &dst, int exc = 1)\n{\n    MATH_EXC_ON;\n    IMATH_NAMESPACE::extractScaling(mat, dst, exc);\n}\n\ntemplate <class T>\nvoid\nouterProduct33(Matrix33<T> &mat, const Vec3<T> &a, const Vec3<T> &b)\n{\n    MATH_EXC_ON;\n    mat = IMATH_NAMESPACE::outerProduct(a,b);\n}\n\ntemplate <class T>\nstatic void\nextractScalingAndShear33(Matrix33<T> &mat, Vec2<T> &dstScl, Vec2<T> &dstShr, int exc = 1)\n{\n    MATH_EXC_ON;\n    T dstShrTmp;\n    IMATH_NAMESPACE::extractScalingAndShear(mat, dstScl, dstShrTmp, exc);\n    \n    dstShr.setValue(dstShrTmp, T (0));\n}\n\ntemplate <class TV,class TM>\nstatic void\nmultDirMatrix33(Matrix33<TM> &mat, const Vec2<TV> &src, Vec2<TV> &dst)\n{\n    MATH_EXC_ON;\n    mat.multDirMatrix(src, dst);    \n}\n\ntemplate <class TV,class TM>\nstatic Vec2<TV>\nmultDirMatrix33_return_value(Matrix33<TM> &mat, const Vec2<TV> &src)\n{\n    MATH_EXC_ON;\n    Vec2<TV> dst;\n    mat.multDirMatrix(src, dst);    \n    return dst;\n}\n\ntemplate <class TV,class TM>\nstatic FixedArray<Vec2<TV> >\nmultDirMatrix33_array(Matrix33<TM> &mat, const FixedArray<Vec2<TV> >&src)\n{\n    MATH_EXC_ON;\n    size_t len = src.len();\n    FixedArray<Vec2<TV> > dst(len);\n    for (size_t i=0; i<len; ++i) mat.multDirMatrix(src[i], dst[i]);    \n    return dst;\n}\n\ntemplate <class TV,class TM>\nstatic void\nmultVecMatrix33(Matrix33<TM> &mat, const Vec2<TV> &src, Vec2<TV> &dst)\n{\n    MATH_EXC_ON;\n    mat.multVecMatrix(src, dst);    \n}\n\ntemplate <class TV,class TM>\nstatic Vec2<TV>\nmultVecMatrix33_return_value(Matrix33<TM> &mat, const Vec2<TV> &src)\n{\n    MATH_EXC_ON;\n    Vec2<TV> dst;\n    mat.multVecMatrix(src, dst);    \n    return dst;\n}\n\ntemplate <class TV,class TM>\nstatic FixedArray<Vec2<TV> >\nmultVecMatrix33_array(Matrix33<TM> &mat, const FixedArray<Vec2<TV> >&src)\n{\n    MATH_EXC_ON;\n    size_t len = src.len();\n    FixedArray<Vec2<TV> > dst(len);\n    for (size_t i=0; i<len; ++i) mat.multVecMatrix(src[i], dst[i]);    \n    return dst;\n}\n\ntemplate <class T>\nstatic int\nremoveScaling33(Matrix33<T> &mat, int exc = 1)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::removeScaling(mat, exc);\n}\n\n\ntemplate <class T>\nstatic int\nremoveScalingAndShear33(Matrix33<T> &mat, int exc = 1)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::removeScalingAndShear(mat, exc);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nrotate33(Matrix33<T> &mat, const T &r)\n{\n    MATH_EXC_ON;\n    return mat.rotate(r);    \n}\n\n\ntemplate <class T>\nstatic Matrix33<T>\nsansScaling33(const Matrix33<T> &mat, bool exc = true)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::sansScaling(mat, exc);\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nsansScalingAndShear33(const Matrix33<T> &mat, bool exc = true)\n{\n    MATH_EXC_ON;\n    return IMATH_NAMESPACE::sansScalingAndShear(mat, exc);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nscaleSc33(Matrix33<T> &mat, const T &s)\n{\n    MATH_EXC_ON;\n    Vec2<T> sVec(s, s);\n    return mat.scale(sVec);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nscaleV33(Matrix33<T> &mat, const Vec2<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.scale(s);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nscale33Tuple(Matrix33<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        \n        return mat.scale(s);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.scale needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetRotation33(Matrix33<T> &mat, const T &r)\n{\n    MATH_EXC_ON;\n    return mat.setRotation(r);    \n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetScaleSc33(Matrix33<T> &mat, const T &s)\n{\n    MATH_EXC_ON;\n    Vec2<T> sVec(s, s);\n    return mat.setScale(sVec);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetScaleV33(Matrix33<T> &mat, const Vec2<T> &s)\n{\n    MATH_EXC_ON;\n    return mat.setScale(s);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetScale33Tuple(Matrix33<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> s;\n        s.x = extract<T>(t[0]);\n        s.y = extract<T>(t[1]);\n        \n        return mat.setScale(s);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.setScale needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetShearSc33(Matrix33<T> &mat, const T &h)\n{\n    MATH_EXC_ON;\n    Vec2<T> hVec(h, T(0));    \n    return mat.setShear(hVec);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetShearV33(Matrix33<T> &mat, const Vec2<T> &h)\n{\n    MATH_EXC_ON;\n    return mat.setShear(h);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetShear33Tuple(Matrix33<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> h;\n        h.x = extract<T>(t[0]);\n        h.y = extract<T>(t[1]);\n        \n        return mat.setShear(h);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.shear needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetTranslation33(Matrix33<T> &mat, const Vec2<T> &t)\n{\n    MATH_EXC_ON;\n    return mat.setTranslation(t);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetTranslation33Tuple(Matrix33<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> trans;\n        trans.x = extract<T>(t[0]);\n        trans.y = extract<T>(t[1]);\n        \n        return mat.setTranslation(trans);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.translate needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nsetTranslation33Obj(Matrix33<T> &mat, const object &o)\n{\n    MATH_EXC_ON;\n    Vec2<T> v;\n    if (PyImath::V2<T>::convert (o.ptr(), &v))\n    {\n        return mat.setTranslation(v);\n    }\n    else\n    {\n        THROW(IEX_NAMESPACE::ArgExc, \"m.setTranslation expected V2 argument\");\n        return mat;\n    }   \n}\n\ntemplate <class T>\nstatic void\nsetValue33(Matrix33<T> &mat, const Matrix33<T> &value)\n{\n    MATH_EXC_ON;\n    mat.setValue(value);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nshearSc33(Matrix33<T> &mat, const T &h)\n{\n    MATH_EXC_ON;\n    Vec2<T> hVec(h, T (0));\n    \n    return mat.shear(hVec);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nshearV33(Matrix33<T> &mat, const Vec2<T> &h)\n{\n    MATH_EXC_ON;\n    return mat.shear(h);\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\nshear33Tuple(Matrix33<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> h;\n        h.x = extract<T>(t[0]);\n        h.y = extract<T>(t[1]);\n        \n        return mat.shear(h);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.shear needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\ntranslate33(Matrix33<T> &mat, const object &t)\n{\n    MATH_EXC_ON;\n    Vec2<T> v;\n    if (PyImath::V2<T>::convert (t.ptr(), &v))\n    {\n        return mat.translate(v);\n    }\n    else\n    {\n        THROW(IEX_NAMESPACE::ArgExc, \"m.translate expected V2 argument\");\n        return mat;\n    }   \n}\n\ntemplate <class T>\nstatic const Matrix33<T> &\ntranslate33Tuple(Matrix33<T> &mat, const tuple &t)\n{\n    MATH_EXC_ON;\n    if(t.attr(\"__len__\")() == 2)\n    {\n        Vec2<T> trans;\n        trans.x = extract<T>(t[0]);\n        trans.y = extract<T>(t[1]);\n        \n        return mat.translate(trans);\n    }\n    else\n        THROW(IEX_NAMESPACE::LogicExc, \"m.translate needs tuple of length 2\");\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nsubtractTL33(Matrix33<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix33<T> m(mat.x);\n    for(int i = 0; i < 3; ++i)\n        for(int j = 0; j < 3; ++j)\n            m.x[i][j] -= a;\n    \n    return m;\n}\n\ntemplate <class T>\nstatic Matrix33<T>\nsubtractTR33(Matrix33<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix33<T> m(mat.x);\n    for(int i = 0; i < 3; ++i)\n        for(int j = 0; j < 3; ++j)\n            m.x[i][j] = a - m.x[i][j];\n    \n    return m;\n}\n\n\ntemplate <class T>\nstatic Matrix33<T>\nadd33T(Matrix33<T> &mat, T a)\n{\n    MATH_EXC_ON;\n    Matrix33<T> m(mat.x);\n    for(int i = 0; i < 3; ++i)\n        for(int j = 0; j < 3; ++j)\n            m.x[i][j] += a;\n    \n    return m;\n}\n\ntemplate <class S, class T>\nstatic Matrix33<T>\nmul33(Matrix33<T> &mat1, Matrix33<S> &mat2)\n{\n    MATH_EXC_ON;\n    Matrix33<T> mat2T;\n    mat2T.setValue (mat2);\n    return mat1 * mat2T;\n}\n\ntemplate <class S, class T>\nstatic Matrix33<T>\nrmul33(Matrix33<T> &mat2, Matrix33<S> &mat1)\n{\n    MATH_EXC_ON;\n    Matrix33<T> mat1T;\n    mat1T.setValue (mat1);\n    return mat1T * mat2;\n}\n\ntemplate <class S, class T>\nstatic const Matrix33<T> &\nimul33(Matrix33<T> &mat1, Matrix33<S> &mat2)\n{\n    MATH_EXC_ON;\n    Matrix33<T> mat2T;\n    mat2T.setValue (mat2);\n    return mat1 *= mat2T;\n}\n\ntemplate <class T>\nstatic bool\nlessThan33(Matrix33<T> &mat1, const Matrix33<T> &mat2)\n{\n    for(int i = 0; i < 3; ++i){\n        for(int j = 0; j < 3; ++j){\n            if(mat1[i][j] > mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return (mat1 != mat2);            \n}\n\ntemplate <class T>\nstatic bool\nlessThanEqual33(Matrix33<T> &mat1, const Matrix33<T> &mat2)\n{\n    for(int i = 0; i < 3; ++i){\n        for(int j = 0; j < 3; ++j){\n            if(mat1[i][j] > mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return true;            \n}\n\ntemplate <class T>\nstatic bool\ngreaterThan33(Matrix33<T> &mat1, const Matrix33<T> &mat2)\n{\n    for(int i = 0; i < 3; ++i){\n        for(int j = 0; j < 3; ++j){\n            if(mat1[i][j] < mat2[i][j]){\n                std::cout << mat1[i][j] << \" \" << mat2[i][j] << std::endl;\n                return false;\n            }\n        }\n    }\n    \n    return (mat1 != mat2);            \n}\n\ntemplate <class T>\nstatic bool\ngreaterThanEqual33(Matrix33<T> &mat1, const Matrix33<T> &mat2)\n{\n    for(int i = 0; i < 3; ++i){\n        for(int j = 0; j < 3; ++j){\n            if(mat1[i][j] < mat2[i][j]){\n                return false;\n            }\n        }\n    }\n    \n    return true;            \n}\n\ntemplate <class T>\nstatic tuple\nsingularValueDecomposition33(const Matrix33<T>& m, bool forcePositiveDeterminant = false)\n{\n    IMATH_NAMESPACE::Matrix33<T> U, V;\n    IMATH_NAMESPACE::Vec3<T> S;\n    IMATH_NAMESPACE::jacobiSVD (m, U, S, V, IMATH_NAMESPACE::limits<T>::epsilon(), forcePositiveDeterminant);\n    return make_tuple (U, S, V);\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(invert33_overloads, invert33, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(inverse33_overloads, inverse33, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(gjInvert33_overloads, gjInvert33, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(gjInverse33_overloads, gjInverse33, 1, 2);\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractAndRemoveScalingAndShear33_overloads, extractAndRemoveScalingAndShear33, 3, 4)\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractSHRT33_overloads, extractSHRT33, 5, 6)\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractScaling33_overloads, extractScaling33, 2, 3)\nBOOST_PYTHON_FUNCTION_OVERLOADS(extractScalingAndShear33_overloads, extractScalingAndShear33, 3, 4)\nBOOST_PYTHON_FUNCTION_OVERLOADS(removeScaling33_overloads, removeScaling33, 1, 2)\nBOOST_PYTHON_FUNCTION_OVERLOADS(removeScalingAndShear33_overloads, removeScalingAndShear33, 1, 2)\nBOOST_PYTHON_FUNCTION_OVERLOADS(sansScaling33_overloads, sansScaling33, 1, 2)\nBOOST_PYTHON_FUNCTION_OVERLOADS(sansScalingAndShear33_overloads, sansScalingAndShear33, 1, 2)\nBOOST_PYTHON_FUNCTION_OVERLOADS(outerProduct33_overloads, outerProduct33, 3, 3);\n\ntemplate <class T>\nstatic Matrix33<T> * Matrix3_tuple_constructor(const tuple &t0, const tuple &t1, const tuple &t2)\n{\n  if(t0.attr(\"__len__\")() == 3 && t1.attr(\"__len__\")() == 3 && t2.attr(\"__len__\")() == 3)\n  {\n      return new Matrix33<T>(extract<T>(t0[0]),  extract<T>(t0[1]),  extract<T>(t0[2]),\n                             extract<T>(t1[0]),  extract<T>(t1[1]),  extract<T>(t1[2]),\n                             extract<T>(t2[0]),  extract<T>(t2[1]),  extract<T>(t2[2]));\n  }\n  else\n      THROW(IEX_NAMESPACE::LogicExc, \"Matrix33 takes 3 tuples of length 3\");\n}\n\ntemplate <class T, class S>\nstatic Matrix33<T> *Matrix3_matrix_constructor(const Matrix33<S> &mat)\n{\n    Matrix33<T> *m = new Matrix33<T>;\n    \n    for(int i = 0; i < 3; ++i)\n        for(int j = 0; j < 3; ++j)\n            m->x[i][j] = T (mat.x[i][j]);\n    \n    return m;\n}\n\ntemplate <class T>\nclass_<Matrix33<T> >\nregister_Matrix33()\n{\n    typedef PyImath::StaticFixedArray<Matrix33<T>,T,3,IndexAccessMatrixRow<Matrix33<T>,T,3> > Matrix33_helper;\n\n    MatrixRow<T,3>::register_class();\n    class_<Matrix33<T> > matrix33_class(Matrix33Name<T>::value, Matrix33Name<T>::value,init<Matrix33<T> >(\"copy construction\"));\n    matrix33_class\n        .def(init<>(\"initialize to identity\"))\n        .def(init<T>(\"initialize all entries to a single value\"))\n        .def(init<T,T,T,T,T,T,T,T,T>(\"make from components\"))\n        .def(\"__init__\", make_constructor(Matrix3_tuple_constructor<T>))\n        .def(\"__init__\", make_constructor(Matrix3_matrix_constructor<T,float>))\n        .def(\"__init__\", make_constructor(Matrix3_matrix_constructor<T,double>))\n        \n\t//.def_readwrite(\"x00\", &Matrix33<T>::x[0][0])\n\t//.def_readwrite(\"x01\", &Matrix33<T>::x[0][1])\n\t//.def_readwrite(\"x02\", &Matrix33<T>::x[0][2])\n\t//.def_readwrite(\"x10\", &Matrix33<T>::x[1][0])\n\t//.def_readwrite(\"x11\", &Matrix33<T>::x[1][1])\n\t//.def_readwrite(\"x12\", &Matrix33<T>::x[1][2])\n\t//.def_readwrite(\"x20\", &Matrix33<T>::x[2][0])\n\t//.def_readwrite(\"x21\", &Matrix33<T>::x[2][1])\n\t//.def_readwrite(\"x22\", &Matrix33<T>::x[2][2])\n        .def(\"baseTypeEpsilon\", &Matrix33<T>::baseTypeEpsilon,\"baseTypeEpsilon() epsilon value of the base type of the vector\")\n        .staticmethod(\"baseTypeEpsilon\")\n        .def(\"baseTypeMax\", &Matrix33<T>::baseTypeMax,\"baseTypeMax() max value of the base type of the vector\")\n        .staticmethod(\"baseTypeMax\")\n        .def(\"baseTypeMin\", &Matrix33<T>::baseTypeMin,\"baseTypeMin() min value of the base type of the vector\")\n        .staticmethod(\"baseTypeMin\")\n        .def(\"baseTypeSmallest\", &Matrix33<T>::baseTypeSmallest,\"baseTypeSmallest() smallest value of the base type of the vector\")\n        .staticmethod(\"baseTypeSmallest\")\n        .def(\"equalWithAbsError\", &Matrix33<T>::equalWithAbsError,\"m1.equalWithAbsError(m2,e) true if the elements \"\n             \"of v1 and v2 are the same with an absolute error of no more than e, \"\n             \"i.e., abs(m1[i] - m2[i]) <= e\")\n        .def(\"equalWithRelError\", &Matrix33<T>::equalWithRelError,\"m1.equalWithAbsError(m2,e) true if the elements \"\n             \"of m1 and m2 are the same with an absolute error of no more than e, \"\n             \"i.e., abs(m1[i] - m2[i]) <= e * abs(m1[i])\")\n        // need a different version for matrix data access\n        .def(\"__len__\", Matrix33_helper::len)\n        .def(\"__getitem__\", Matrix33_helper::getitem)\n\t//.def(\"__setitem__\", Matrix33_helper::setitem)\n        .def(\"makeIdentity\",&Matrix33<T>::makeIdentity,\"makeIdentity() make this matrix the identity matrix\")\n        .def(\"transpose\",&Matrix33<T>::transpose,return_internal_reference<>(),\"transpose() transpose this matrix\")\n        .def(\"transposed\",&Matrix33<T>::transposed,\"transposed() return a transposed copy of this matrix\")\n        .def(\"invert\",&invert33<T>,invert33_overloads(\"invert() invert this matrix\")[return_internal_reference<>()])\n        .def(\"inverse\",&inverse33<T>,inverse33_overloads(\"inverse() return an inverted copy of this matrix\"))\n        .def(\"gjInvert\",&gjInvert33<T>,gjInvert33_overloads(\"gjInvert() invert this matrix\")[return_internal_reference<>()])\n        .def(\"gjInverse\",&gjInverse33<T>,gjInverse33_overloads(\"gjInverse() return an inverted copy of this matrix\"))\n        .def(\"minorOf\",&Matrix33<T>::minorOf,\"minorOf() return the matrix minor of the (row,col) element of this matrix\")\n        .def(\"fastMinor\",&Matrix33<T>::fastMinor,\"fastMinor() return the matrix minor using the specified rows and columns of this matrix\")\n        .def(\"determinant\",&Matrix33<T>::determinant,\"determinant() return the determinant of this matrix\")\n        .def(self == self) // NOSONAR - suppress SonarCloud bug report.\n        .def(self != self) // NOSONAR - suppress SonarCloud bug report.\n        .def(\"__iadd__\", &iadd33<T, float>,return_internal_reference<>())\n        .def(\"__iadd__\", &iadd33<T, double>,return_internal_reference<>())\n        .def(\"__iadd__\", &iadd33T<T>,return_internal_reference<>())\n        .def(\"__add__\", &add33<T>)\n        .def(\"__isub__\", &isub33<T, float>,return_internal_reference<>())\n        .def(\"__isub__\", &isub33<T, double>,return_internal_reference<>())\n        .def(\"__isub__\", &isub33T<T>,return_internal_reference<>())\n        .def(\"__sub__\", &sub33<T>)\n        .def(\"negate\",&negate33<T>,return_internal_reference<>(),\"negate() negate all entries in this matrix\")\n        .def(\"__neg__\", &neg33<T>)\n        .def(\"__imul__\", &imul33T<T>,return_internal_reference<>())\n        .def(\"__mul__\", &mul33T<T>)\n        .def(\"__rmul__\", &rmul33T<T>)\n        .def(\"__idiv__\", &idiv33T<T>,return_internal_reference<>())\n        .def(\"__itruediv__\", &idiv33T<T>,return_internal_reference<>())\n        .def(\"__div__\", &div33T<T>)\n        .def(\"__truediv__\", &div33T<T>)\n        .def(\"__add__\", &add33T<T>)\n        .def(\"__radd__\", &add33T<T>)\n        .def(\"__sub__\", &subtractTL33<T>)\n        .def(\"__rsub__\", &subtractTR33<T>)\n        .def(\"__mul__\", &mul33<float, T>)\n        .def(\"__mul__\", &mul33<double, T>)\n        .def(\"__rmul__\", &rmul33<float, T>)\n        .def(\"__rmul__\", &rmul33<double, T>)\n        .def(\"__imul__\", &imul33<float, T>,return_internal_reference<>())\n        .def(\"__imul__\", &imul33<double, T>,return_internal_reference<>())\n        .def(\"__lt__\", &lessThan33<T>)\n        .def(\"__le__\", &lessThanEqual33<T>)\n        .def(\"__gt__\", &greaterThan33<T>)\n        .def(\"__ge__\", &greaterThanEqual33<T>)\n\t//.def(self_ns::str(self))\n        .def(\"__str__\",&Matrix33_str<T>)\n        .def(\"__repr__\",&Matrix33_repr<T>)\n        .def(\"extractAndRemoveScalingAndShear\", &extractAndRemoveScalingAndShear33<T>, \n              extractAndRemoveScalingAndShear33_overloads(\n              \"M.extractAndRemoveScalingAndShear(scl, shr, \"\n              \"[exc]) -- extracts the scaling component of \"\n              \"M into scl and the shearing component of M \"\n              \"into shr.  Also removes the scaling and \"\n              \"shearing components from M.  \"\n              \"Returns 1 unless the scaling component is \"\n              \"nearly 0, in which case 0 is returned. \"\n              \"If optional arg. exc == 1, then if the \"\n              \"scaling component is nearly 0, then MathExc \"\n              \"is thrown. \"))\n             \n         .def(\"extractEuler\", &extractEuler<T>, \t\t\t\t\n              \"M.extractEulerZYX(r) -- extracts the \"\n\t\t\t  \"rotation component of M into r. \"\n              \"Assumes that M contains no shear or \"\n              \"non-uniform scaling; results are \"\n              \"meaningless if it does.\")\n              \n         .def(\"extractSHRT\", &extractSHRT33<T>, extractSHRT33_overloads(\t\t\t\t\n              \"M.extractSHRT(Vs, Vh, Vr, Vt, [exc]) -- \"\n\t          \"extracts the scaling component of M into Vs, \"\n\t\t\t  \"the shearing component of M in Vh (as XY, \"\n\t          \"XZ, YZ shear factors), the rotation of M \"\n\t          \"into Vr (as Euler angles in the order XYZ), \"\n\t          \"and the translaation of M into Vt. \"\n\t\t\t  \"If optional arg. exc == 1, then if the \"\n\t\t\t  \"scaling component is nearly 0, then MathExc \"\n\t\t\t  \"is thrown. \"))\n              \n         .def(\"extractScaling\", &extractScaling33<T>, extractScaling33_overloads(\"extract scaling\"))\n         .def(\"outerProduct\", &outerProduct33<T>, outerProduct33_overloads(\n              \"M.outerProduct(Va,Vb) -- \"\n                  \"Performs the outer product, or tensor product, of two 3D vectors, Va and Vb\"))\n\n         .def(\"extractScalingAndShear\", &extractScalingAndShear33<T>, extractScalingAndShear33_overloads(\"extract scaling\"))\n        .def(\"singularValueDecomposition\", &singularValueDecomposition33<T>, \n             \"Decomposes the matrix using the singular value decomposition (SVD) into three\\n\"\n             \"matrices U, S, and V which have the following properties: \\n\"\n             \"  1. U and V are both orthonormal matrices, \\n\"\n             \"  2. S is the diagonal matrix of singular values, \\n\"\n             \"  3. U * S * V.transposed() gives back the original matrix.\\n\"\n             \"The result is returned as a tuple [U, S, V].  Note that since S is diagonal we\\n\"\n             \"don't need to return the entire matrix, so we return it as a three-vector.  \\n\"\n             \"\\n\"\n             \"The 'forcePositiveDeterminant' argument can be used to force the U and V^T to\\n\"\n             \"have positive determinant (that is, to be proper rotation matrices); if\\n\"\n             \"forcePositiveDeterminant is False, then the singular values are guaranteed to\\n\"\n             \"be nonnegative but the U and V matrices might contain negative scale along one\\n\"\n             \"of the axes; if forcePositiveDeterminant is True, then U and V cannot contain\\n\"\n             \"negative scale but S[2] might be negative.  \\n\"\n             \"\\n\"\n             \"Our SVD implementation uses two-sided Jacobi rotations to iteratively\\n\"\n             \"diagonalize the matrix, which should be quite robust and significantly faster\\n\"\n             \"than the more general SVD solver in LAPACK.  \\n\",\n             args(\"matrix\", \"forcePositiveDeterminant\"))\n        .def(\"symmetricEigensolve\", &PyImath::jacobiEigensolve<IMATH_NAMESPACE::Matrix33<T> >, \n             \"Decomposes the matrix A using a symmetric eigensolver into matrices Q and S \\n\"\n             \"which have the following properties: \\n\"\n             \"  1. Q is the orthonormal matrix of eigenvectors, \\n\"\n             \"  2. S is the diagonal matrix of eigenvalues, \\n\"\n             \"  3. Q * S * Q.transposed() gives back the original matrix.\\n\"\n             \"\\n\"\n             \"IMPORTANT: It is vital that the passed-in matrix be symmetric, or the result \\n\"\n             \"won't make any sense.  This function will return an error if passed an \\n\"\n             \"unsymmetric matrix.\\n\"\n             \"\\n\"\n             \"The result is returned as a tuple [Q, S].  Note that since S is diagonal \\n\"\n             \"we don't need to return the entire matrix, so we return it as a three-vector. \\n\"\n             \"\\n\"\n             \"Our eigensolver implementation uses one-sided Jacobi rotations to iteratively \\n\"\n             \"diagonalize the matrix, which should be quite robust and significantly faster \\n\"\n             \"than the more general symmetric eigenvalue solver in LAPACK.  \\n\")\n         .def(\"multDirMatrix\", &multDirMatrix33<double,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix33_return_value<double,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix33_array<double,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix33<float,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix33_return_value<float,T>, \"mult matrix\")\n         .def(\"multDirMatrix\", &multDirMatrix33_array<float,T>, \"mult matrix\")\n         .def(\"multVecMatrix\", &multVecMatrix33<double,T>, \"mult matrix\")\n         .def(\"multVecMatrix\", &multVecMatrix33_return_value<double,T>, \"mult matrix\")\n         .def(\"multVecMatrix\", &multVecMatrix33_array<double,T>, \"mult matrix\")\n         .def(\"multVecMatrix\", &multVecMatrix33<float,T>, \"mult matrix\")\n         .def(\"multVecMatrix\", &multVecMatrix33_return_value<float,T>, \"mult matrix\")\n         .def(\"multVecMatrix\", &multVecMatrix33_array<float,T>, \"mult matrix\")\n         .def(\"removeScaling\", &removeScaling33<T>, removeScaling33_overloads(\"remove scaling\"))\n\n         .def(\"removeScalingAndShear\", &removeScalingAndShear33<T>, removeScalingAndShear33_overloads(\"remove scaling\"))\n         .def(\"sansScaling\", &sansScaling33<T>, sansScaling33_overloads(\"sans scaling\"))\n         .def(\"rotate\", &rotate33<T>, return_internal_reference<>(),\"rotate matrix\")\n\n         .def(\"sansScalingAndShear\", &sansScalingAndShear33<T>, sansScalingAndShear33_overloads(\"sans scaling and shear\"))\n         .def(\"scale\", &scaleSc33<T>, return_internal_reference<>(),\"scale matrix\")\n         .def(\"scale\", &scaleV33<T>, return_internal_reference<>(),\"scale matrix\")\n         .def(\"scale\", &scale33Tuple<T>, return_internal_reference<>(),\"scale matrix\")\n\n         .def(\"setRotation\", &setRotation33<T>, return_internal_reference<>(),\"setRotation()\")\n         .def(\"setScale\", &setScaleSc33<T>, return_internal_reference<>(),\"setScale()\")\n         .def(\"setScale\", &setScaleV33<T>, return_internal_reference<>(),\"setScale()\")\n         .def(\"setScale\", &setScale33Tuple<T>, return_internal_reference<>(),\"setScale()\")\n\n         .def(\"setShear\", &setShearSc33<T>, return_internal_reference<>(),\"setShear()\")\n         .def(\"setShear\", &setShearV33<T>, return_internal_reference<>(),\"setShear()\")\n         .def(\"setShear\", &setShear33Tuple<T>, return_internal_reference<>(),\"setShear()\")\n         \n         .def(\"setTranslation\", &setTranslation33<T>, return_internal_reference<>(),\"setTranslation()\")\n         .def(\"setTranslation\", &setTranslation33Tuple<T>, return_internal_reference<>(),\"setTranslation()\")\n         .def(\"setTranslation\", &setTranslation33Obj<T>, return_internal_reference<>(),\"setTranslation()\")\n         .def(\"setValue\", &setValue33<T>, \"setValue()\")\n         .def(\"shear\", &shearSc33<T>, return_internal_reference<>(),\"shear()\")\n         .def(\"shear\", &shearV33<T>, return_internal_reference<>(),\"shear()\")\n         .def(\"shear\", &shear33Tuple<T>, return_internal_reference<>(),\"shear()\")\n         .def(\"translate\", &translate33<T>, return_internal_reference<>(),\"translate()\")\n         .def(\"translate\", &translate33Tuple<T>, return_internal_reference<>(),\"translate()\")\n         .def(\"translation\", &Matrix33<T>::translation, \"translation()\")\n         ;\n\n    decoratecopy(matrix33_class);\n\n    return matrix33_class;\n/*\n    const Matrix33 &\toperator = (const Matrix33 &v);\n    const Matrix33 &\toperator = (T a);\n    T *\t\t\tgetValue ();\n    const T *\t\tgetValue () const;\n    template <class S> void getValue (Matrix33<S> &v) const;\n    template <class S> Matrix33 & setValue (const Matrix33<S> &v);\n    template <class S> Matrix33 & setTheMatrix (const Matrix33<S> &v);\n    template <class S> void multVecMatrix(const Vec2<S> &src, Vec2<S> &dst) const;\n    template <class S> void multDirMatrix(const Vec2<S> &src, Vec2<S> &dst) const;\n    template <class S> const Matrix33 &\tsetRotation (S r);\n    template <class S> const Matrix33 &\trotate (S r);\n    const Matrix33 &\tsetScale (T s);\n    template <class S> const Matrix33 &\tsetScale (const Vec2<S> &s);\n    template <class S> const Matrix33 &\tscale (const Vec2<S> &s);\n    template <class S> const Matrix33 &\tsetTranslation (const Vec2<S> &t);\n    Vec2<T>\t\ttranslation () const;\n    template <class S> const Matrix33 &\ttranslate (const Vec2<S> &t);\n    template <class S> const Matrix33 &\tsetShear (const S &h);\n    template <class S> const Matrix33 &\tsetShear (const Vec2<S> &h);\n    template <class S> const Matrix33 &\tshear (const S &xy);\n    template <class S> const Matrix33 &\tshear (const Vec2<S> &h);\n*/\n}\n\ntemplate <class T>\nstatic void\nsetM33ArrayItem(FixedArray<IMATH_NAMESPACE::Matrix33<T> > &ma,\n                Py_ssize_t index,\n                const IMATH_NAMESPACE::Matrix33<T> &m)\n{\n    ma[ma.canonical_index(index)] = m;\n}\n\ntemplate <class T>\nclass_<FixedArray<IMATH_NAMESPACE::Matrix33<T> > >\nregister_M33Array()\n{\n    class_<FixedArray<IMATH_NAMESPACE::Matrix33<T> > > matrixArray_class = FixedArray<IMATH_NAMESPACE::Matrix33<T> >::register_(\"Fixed length array of IMATH_NAMESPACE::Matrix33\");\n    matrixArray_class\n         .def(\"__setitem__\", &setM33ArrayItem<T>)\n        ;\n    return matrixArray_class;\n}\n\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Matrix33<float> > register_Matrix33<float>();\ntemplate PYIMATH_EXPORT class_<IMATH_NAMESPACE::Matrix33<double> > register_Matrix33<double>();\n\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Matrix33<float> > > register_M33Array<float>();\ntemplate PYIMATH_EXPORT class_<FixedArray<IMATH_NAMESPACE::Matrix33<double> > > register_M33Array<double>();\n\n\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Matrix33<float> FixedArrayDefaultValue<IMATH_NAMESPACE::Matrix33<float> >::value() { return IMATH_NAMESPACE::Matrix33<float>(); }\ntemplate<> PYIMATH_EXPORT IMATH_NAMESPACE::Matrix33<double> FixedArrayDefaultValue<IMATH_NAMESPACE::Matrix33<double> >::value() { return IMATH_NAMESPACE::Matrix33<double>(); }\n}\n", "meta": {"hexsha": "edc2c146041be80c65e092985c9b38bbb931e8e2", "size": 36828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PyIlmBase/PyImath/PyImathMatrix33.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/PyImathMatrix33.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/PyImathMatrix33.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": 32.8235294118, "max_line_length": 179, "alphanum_fraction": 0.6357934181, "num_tokens": 10604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197264277872, "lm_q2_score": 0.022977367401108627, "lm_q1q2_score": 0.007608259607885844}}
{"text": "/*\n For more information, please see: http://software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n\n Author : Spencer Frisby, Moritz Dannhauer\n Date   : May 2014\n*/\n\n#include <iostream>\n\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Algorithms/BrainStimulator/SetConductivitiesToTetMeshAlgorithm.h>\n#include <Core/GeometryPrimitives/Vector.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/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Datatypes/Legacy/Field/VField.h>\n#include <Core/Datatypes/Legacy/Field/FieldInformation.h>\n#include <Core/GeometryPrimitives/Vector.h>\n\n#include <Core/Logging/Log.h>\n\n#include <boost/assign.hpp>\n\nusing namespace boost::assign;\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::BrainStimulator;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Logging;\n\nALGORITHM_PARAMETER_DEF(BrainStimulator, Skin);\nALGORITHM_PARAMETER_DEF(BrainStimulator, SoftBone);\nALGORITHM_PARAMETER_DEF(BrainStimulator, HardBone);\nALGORITHM_PARAMETER_DEF(BrainStimulator, CSF);\nALGORITHM_PARAMETER_DEF(BrainStimulator, GM);\nALGORITHM_PARAMETER_DEF(BrainStimulator, WM);\nALGORITHM_PARAMETER_DEF(BrainStimulator, Electrode);\nALGORITHM_PARAMETER_DEF(BrainStimulator, InternalAir);\n\nAlgorithmInputName  SetConductivitiesToMeshAlgorithm::InputField(\"InputField\");\nAlgorithmOutputName SetConductivitiesToMeshAlgorithm::OutputField(\"OutputField\");\n\nSetConductivitiesToMeshAlgorithm::SetConductivitiesToMeshAlgorithm()\n{\n  ElemLabelLookup += 1,2,3,4,5,6,7,8;\n\n  using namespace Parameters;\n  /// electrical conductivities (isotropic) default values based on the literature\n  addParameter(Skin,         0.43);\n  addParameter(SoftBone,     0.02856);\n  addParameter(HardBone,     0.00640);\n  addParameter(CSF,          1.79);\n  addParameter(GM,           0.33);\n  addParameter(WM,           0.142);\n  addParameter(Electrode,    1.4);\n  addParameter(InternalAir,  1e-6);\n}\n\nAlgorithmOutput SetConductivitiesToMeshAlgorithm::run(const AlgorithmInput& input) const\n{\n  auto mesh  = input.get<Field>(InputField);\n\n  AlgorithmOutput output;\n\n  FieldHandle output_field = run(mesh);\n\n  output[OutputField] = output_field;\n\n  return output;\n}\n\nFieldHandle SetConductivitiesToMeshAlgorithm::run(FieldHandle fh) const\n{\n  // making sure the field is not null\n  if (!fh)\n    THROW_ALGORITHM_INPUT_ERROR(\"Field supplied is empty \");\n\n  /// making sure the data is on the elem and not the nodes\n  FieldInformation fi(fh);\n  if (!fi.is_constantdata())\n    THROW_ALGORITHM_INPUT_ERROR(\"This function requires the data to be on the elements \");\n\n  /// making sure the field contains data\n  VField* vfield = fh->vfield();\n  if (vfield->is_nodata())\n    THROW_ALGORITHM_INPUT_ERROR(\"Field supplied contained no data \");\n\n  /// making sure the field is not in vector or tensor format\n  if (!vfield->is_scalar())\n    THROW_ALGORITHM_INPUT_ERROR(\"Function only supports scalar labels. \");\n\n  using namespace Parameters;\n\n  LOG_DEBUG(\"SetConductivitiesToTetMeshAlgorithm parameters:\\n\\tSkin = {}\\n\\tSoftBone = {}\\n\\tHardBone = {}\"\n    \"\\n\\tCSF = {}\\n\\tGM = {}\\n\\tWM = {}\\n\\tElectrode = {}\\n\\tInternalAir = {}\",\n    get(Skin).toDouble(), get(SoftBone).toDouble(), get(HardBone).toDouble(),\n    get(CSF).toDouble(), get(GM).toDouble(), get(WM).toDouble(), get(Electrode).toDouble(),\n    get(InternalAir).toDouble());\n\n  /// array holding conductivities\n  /// @todo: enable when VS2013 is supported\n//  std::vector<double> conductivities = {get(Skin).toDouble(), get(SoftBone).toDouble(), get(HardBone).toDouble(),\n//  get(CSF).toDouble(), get(GM).toDouble(), get(WM).toDouble(), get(Electrode).toDouble(), get(InternalAir).toDouble()};\n\n  // stopgap measure until VS2013 is supported\n  std::vector<double> conductivities;\n  conductivities += get(Skin).toDouble(), get(SoftBone).toDouble(), get(HardBone).toDouble(),\n  get(CSF).toDouble(), get(GM).toDouble(), get(WM).toDouble(), get(Electrode).toDouble(), get(InternalAir).toDouble();\n\n  // check if defined conductivities and lookup table are consistent\n  if (conductivities.size() != ElemLabelLookup.size())\n    THROW_ALGORITHM_INPUT_ERROR(\"Defined conductivities and lookup table are inconsistent! \");\n\n  /// replacing field value with conductivity value\n  FieldHandle output = CreateField(fi, fh->mesh());\n  VField* ofield = output->vfield();\n  int val = 0;\n  int cnt = 0;\n\n  for (VMesh::Elem::index_type i = 0; i < vfield->vmesh()->num_elems(); i++) // loop over all tetrahedral elements\n  {\n    vfield->get_value(val, i);  //get the data value stored on the current element\n\n    bool found = false; // boolean that indicates if element label was found in lookup\n\n     // loop over lookup table and check if the current element has one of the desired labels, if not error\n    for (size_t j = 0; j < ElemLabelLookup.size(); ++j)\n    {\n      if (val == ElemLabelLookup[j])\n      {\n        ofield->set_value(conductivities[j], i); // if so, set it to the isotropic conductivity value\n        found = true;\n        break;\n      }\n    }\n\n    if (!found)\n    {\n      THROW_ALGORITHM_INPUT_ERROR(\"Tetrahedral element label could not be found in lookup table. \");\n    }\n\n    cnt++;\n    if (cnt == 500)\n    {\n      cnt = 0;\n      update_progress_max(i,vfield->vmesh()->num_elems());\n    }\n  }\n\n  return output;\n}\n", "meta": {"hexsha": "f8254c330ac39c6c33afa46c38ba9d06cc9615f5", "size": 6670, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/BrainStimulator/SetConductivitiesToTetMeshAlgorithm.cc", "max_stars_repo_name": "Nahusa/SCIRun", "max_stars_repo_head_hexsha": "c54e714d4c7e956d053597cf194e07616e28a498", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T06:00:15.000Z", "max_issues_repo_path": "src/Core/Algorithms/BrainStimulator/SetConductivitiesToTetMeshAlgorithm.cc", "max_issues_repo_name": "manual123/SCIRun", "max_issues_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/BrainStimulator/SetConductivitiesToTetMeshAlgorithm.cc", "max_forks_repo_name": "manual123/SCIRun", "max_forks_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4719101124, "max_line_length": 121, "alphanum_fraction": 0.7370314843, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.02556521480489875, "lm_q1q2_score": 0.007604882662245198}}
{"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//\r\n//\r\n// Revision History:\r\n//   04 April 2001: Added named parameter variant. (Jeremy Siek)\r\n//   01 April 2001: Modified to use new <boost/limits.hpp> header. (JMaddock)\r\n//\r\n#ifndef BOOST_GRAPH_DIJKSTRA_HPP\r\n#define BOOST_GRAPH_DIJKSTRA_HPP\r\n\r\n#include <functional>\r\n#include <boost/limits.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/graph/breadth_first_search.hpp>\r\n#include <boost/graph/relax.hpp>\r\n#include <boost/pending/indirect_cmp.hpp>\r\n#include <boost/graph/exception.hpp>\r\n#include <boost/graph/overloading.hpp>\r\n#include <boost/smart_ptr.hpp>\r\n#include <boost/graph/detail/d_ary_heap.hpp>\r\n#include <boost/graph/two_bit_color_map.hpp>\r\n#include <boost/graph/detail/mpi_include.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/property_map/vector_property_map.hpp>\r\n#include <boost/type_traits.hpp>\r\n#include <boost/concept/assert.hpp>\r\n\r\n#ifdef BOOST_GRAPH_DIJKSTRA_TESTING\r\n#include <boost/pending/mutable_queue.hpp>\r\n#endif // BOOST_GRAPH_DIJKSTRA_TESTING\r\n\r\nnamespace boost\r\n{\r\n\r\n/**\r\n * @brief Updates a particular value in a queue used by Dijkstra's\r\n * algorithm.\r\n *\r\n * This routine is called by Dijkstra's algorithm after it has\r\n * decreased the distance from the source vertex to the given @p\r\n * vertex. By default, this routine will just call @c\r\n * Q.update(vertex). However, other queues may provide more\r\n * specialized versions of this routine.\r\n *\r\n * @param Q             the queue that will be updated.\r\n * @param vertex        the vertex whose distance has been updated\r\n * @param old_distance  the previous distance to @p vertex\r\n */\r\ntemplate < typename Buffer, typename Vertex, typename DistanceType >\r\ninline void dijkstra_queue_update(\r\n    Buffer& Q, Vertex vertex, DistanceType old_distance)\r\n{\r\n    (void)old_distance;\r\n    Q.update(vertex);\r\n}\r\n\r\ntemplate < class Visitor, class Graph > struct DijkstraVisitorConcept\r\n{\r\n    void constraints()\r\n    {\r\n        BOOST_CONCEPT_ASSERT((CopyConstructibleConcept< Visitor >));\r\n        vis.initialize_vertex(u, g);\r\n        vis.discover_vertex(u, g);\r\n        vis.examine_vertex(u, g);\r\n        vis.examine_edge(e, g);\r\n        vis.edge_relaxed(e, g);\r\n        vis.edge_not_relaxed(e, g);\r\n        vis.finish_vertex(u, g);\r\n    }\r\n    Visitor vis;\r\n    Graph g;\r\n    typename graph_traits< Graph >::vertex_descriptor u;\r\n    typename graph_traits< Graph >::edge_descriptor e;\r\n};\r\n\r\ntemplate < class Visitors = null_visitor >\r\nclass dijkstra_visitor : public bfs_visitor< Visitors >\r\n{\r\npublic:\r\n    dijkstra_visitor() {}\r\n    dijkstra_visitor(Visitors vis) : bfs_visitor< Visitors >(vis) {}\r\n\r\n    template < class Edge, class Graph > void edge_relaxed(Edge e, Graph& g)\r\n    {\r\n        invoke_visitors(this->m_vis, e, g, on_edge_relaxed());\r\n    }\r\n    template < class Edge, class Graph > void edge_not_relaxed(Edge e, Graph& g)\r\n    {\r\n        invoke_visitors(this->m_vis, e, g, on_edge_not_relaxed());\r\n    }\r\n\r\nprivate:\r\n    template < class Edge, class Graph > void tree_edge(Edge u, Graph& g) {}\r\n};\r\ntemplate < class Visitors >\r\ndijkstra_visitor< Visitors > make_dijkstra_visitor(Visitors vis)\r\n{\r\n    return dijkstra_visitor< Visitors >(vis);\r\n}\r\ntypedef dijkstra_visitor<> default_dijkstra_visitor;\r\n\r\nnamespace detail\r\n{\r\n\r\n    template < class UniformCostVisitor, class UpdatableQueue, class WeightMap,\r\n        class PredecessorMap, class DistanceMap, class BinaryFunction,\r\n        class BinaryPredicate >\r\n    struct dijkstra_bfs_visitor\r\n    {\r\n        typedef typename property_traits< DistanceMap >::value_type D;\r\n        typedef typename property_traits< WeightMap >::value_type W;\r\n\r\n        dijkstra_bfs_visitor(UniformCostVisitor vis, UpdatableQueue& Q,\r\n            WeightMap w, PredecessorMap p, DistanceMap d,\r\n            BinaryFunction combine, BinaryPredicate compare, D zero)\r\n        : m_vis(vis)\r\n        , m_Q(Q)\r\n        , m_weight(w)\r\n        , m_predecessor(p)\r\n        , m_distance(d)\r\n        , m_combine(combine)\r\n        , m_compare(compare)\r\n        , m_zero(zero)\r\n        {\r\n        }\r\n\r\n        template < class Edge, class Graph > void tree_edge(Edge e, Graph& g)\r\n        {\r\n            bool decreased = relax_target(e, g, m_weight, m_predecessor,\r\n                m_distance, m_combine, m_compare);\r\n            if (decreased)\r\n                m_vis.edge_relaxed(e, g);\r\n            else\r\n                m_vis.edge_not_relaxed(e, g);\r\n        }\r\n        template < class Edge, class Graph > void gray_target(Edge e, Graph& g)\r\n        {\r\n            D old_distance = get(m_distance, target(e, g));\r\n\r\n            bool decreased = relax_target(e, g, m_weight, m_predecessor,\r\n                m_distance, m_combine, m_compare);\r\n            if (decreased)\r\n            {\r\n                dijkstra_queue_update(m_Q, target(e, g), old_distance);\r\n                m_vis.edge_relaxed(e, g);\r\n            }\r\n            else\r\n                m_vis.edge_not_relaxed(e, g);\r\n        }\r\n\r\n        template < class Vertex, class Graph >\r\n        void initialize_vertex(Vertex u, Graph& g)\r\n        {\r\n            m_vis.initialize_vertex(u, g);\r\n        }\r\n        template < class Edge, class Graph > void non_tree_edge(Edge, Graph&) {}\r\n        template < class Vertex, class Graph >\r\n        void discover_vertex(Vertex u, Graph& g)\r\n        {\r\n            m_vis.discover_vertex(u, g);\r\n        }\r\n        template < class Vertex, class Graph >\r\n        void examine_vertex(Vertex u, Graph& g)\r\n        {\r\n            m_vis.examine_vertex(u, g);\r\n        }\r\n        template < class Edge, class Graph > void examine_edge(Edge e, Graph& g)\r\n        {\r\n            // Test for negative-weight edges:\r\n            //\r\n            // Reasons that other comparisons do not work:\r\n            //\r\n            // m_compare(e_weight, D(0)):\r\n            //    m_compare only needs to work on distances, not weights, and\r\n            //    those types do not need to be the same (bug 8398,\r\n            //    https://svn.boost.org/trac/boost/ticket/8398).\r\n            // m_compare(m_combine(source_dist, e_weight), source_dist):\r\n            //    if m_combine is project2nd (as in prim_minimum_spanning_tree),\r\n            //    this test will claim that the edge weight is negative whenever\r\n            //    the edge weight is less than source_dist, even if both of\r\n            //    those are positive (bug 9012,\r\n            //    https://svn.boost.org/trac/boost/ticket/9012).\r\n            // m_compare(m_combine(e_weight, source_dist), source_dist):\r\n            //    would fix project2nd issue, but documentation only requires\r\n            //    that m_combine be able to take a distance and a weight (in\r\n            //    that order) and return a distance.\r\n\r\n            // W e_weight = get(m_weight, e);\r\n            // sd_plus_ew = source_dist + e_weight.\r\n            // D sd_plus_ew = m_combine(source_dist, e_weight);\r\n            // sd_plus_2ew = source_dist + 2 * e_weight.\r\n            // D sd_plus_2ew = m_combine(sd_plus_ew, e_weight);\r\n            // The test here is equivalent to e_weight < 0 if m_combine has a\r\n            // cancellation law, but always returns false when m_combine is a\r\n            // projection operator.\r\n            if (m_compare(m_combine(m_zero, get(m_weight, e)), m_zero))\r\n                boost::throw_exception(negative_edge());\r\n            // End of test for negative-weight edges.\r\n\r\n            m_vis.examine_edge(e, g);\r\n        }\r\n        template < class Edge, class Graph > void black_target(Edge, Graph&) {}\r\n        template < class Vertex, class Graph >\r\n        void finish_vertex(Vertex u, Graph& g)\r\n        {\r\n            m_vis.finish_vertex(u, g);\r\n        }\r\n\r\n        UniformCostVisitor m_vis;\r\n        UpdatableQueue& m_Q;\r\n        WeightMap m_weight;\r\n        PredecessorMap m_predecessor;\r\n        DistanceMap m_distance;\r\n        BinaryFunction m_combine;\r\n        BinaryPredicate m_compare;\r\n        D m_zero;\r\n    };\r\n\r\n} // namespace detail\r\n\r\nnamespace detail\r\n{\r\n    template < class Graph, class IndexMap, class Value, bool KnownNumVertices >\r\n    struct vertex_property_map_generator_helper\r\n    {\r\n    };\r\n\r\n    template < class Graph, class IndexMap, class Value >\r\n    struct vertex_property_map_generator_helper< Graph, IndexMap, Value, true >\r\n    {\r\n        typedef boost::iterator_property_map< Value*, IndexMap > type;\r\n        static type build(const Graph& g, const IndexMap& index,\r\n            boost::scoped_array< Value >& array_holder)\r\n        {\r\n            array_holder.reset(new Value[num_vertices(g)]);\r\n            std::fill(array_holder.get(), array_holder.get() + num_vertices(g),\r\n                Value());\r\n            return make_iterator_property_map(array_holder.get(), index);\r\n        }\r\n    };\r\n\r\n    template < class Graph, class IndexMap, class Value >\r\n    struct vertex_property_map_generator_helper< Graph, IndexMap, Value, false >\r\n    {\r\n        typedef boost::vector_property_map< Value, IndexMap > type;\r\n        static type build(const Graph& g, const IndexMap& index,\r\n            boost::scoped_array< Value >& array_holder)\r\n        {\r\n            return boost::make_vector_property_map< Value >(index);\r\n        }\r\n    };\r\n\r\n    template < class Graph, class IndexMap, class Value >\r\n    struct vertex_property_map_generator\r\n    {\r\n        typedef boost::is_base_and_derived< boost::vertex_list_graph_tag,\r\n            typename boost::graph_traits< Graph >::traversal_category >\r\n            known_num_vertices;\r\n        typedef vertex_property_map_generator_helper< Graph, IndexMap, Value,\r\n            known_num_vertices::value >\r\n            helper;\r\n        typedef typename helper::type type;\r\n        static type build(const Graph& g, const IndexMap& index,\r\n            boost::scoped_array< Value >& array_holder)\r\n        {\r\n            return helper::build(g, index, array_holder);\r\n        }\r\n    };\r\n}\r\n\r\nnamespace detail\r\n{\r\n    template < class Graph, class IndexMap, bool KnownNumVertices >\r\n    struct default_color_map_generator_helper\r\n    {\r\n    };\r\n\r\n    template < class Graph, class IndexMap >\r\n    struct default_color_map_generator_helper< Graph, IndexMap, true >\r\n    {\r\n        typedef boost::two_bit_color_map< IndexMap > type;\r\n        static type build(const Graph& g, const IndexMap& index)\r\n        {\r\n            size_t nv = num_vertices(g);\r\n            return boost::two_bit_color_map< IndexMap >(nv, index);\r\n        }\r\n    };\r\n\r\n    template < class Graph, class IndexMap >\r\n    struct default_color_map_generator_helper< Graph, IndexMap, false >\r\n    {\r\n        typedef boost::vector_property_map< boost::two_bit_color_type,\r\n            IndexMap >\r\n            type;\r\n        static type build(const Graph& g, const IndexMap& index)\r\n        {\r\n            return boost::make_vector_property_map< boost::two_bit_color_type >(\r\n                index);\r\n        }\r\n    };\r\n\r\n    template < class Graph, class IndexMap > struct default_color_map_generator\r\n    {\r\n        typedef boost::is_base_and_derived< boost::vertex_list_graph_tag,\r\n            typename boost::graph_traits< Graph >::traversal_category >\r\n            known_num_vertices;\r\n        typedef default_color_map_generator_helper< Graph, IndexMap,\r\n            known_num_vertices::value >\r\n            helper;\r\n        typedef typename helper::type type;\r\n        static type build(const Graph& g, const IndexMap& index)\r\n        {\r\n            return helper::build(g, index);\r\n        }\r\n    };\r\n}\r\n\r\n// Call breadth first search with default color map.\r\ntemplate < class Graph, class SourceInputIter, class DijkstraVisitor,\r\n    class PredecessorMap, class DistanceMap, class WeightMap, class IndexMap,\r\n    class Compare, class Combine, class DistZero >\r\ninline void dijkstra_shortest_paths_no_init(const Graph& g,\r\n    SourceInputIter s_begin, SourceInputIter s_end, PredecessorMap predecessor,\r\n    DistanceMap distance, WeightMap weight, IndexMap index_map, Compare compare,\r\n    Combine combine, DistZero zero, DijkstraVisitor vis)\r\n{\r\n    typedef detail::default_color_map_generator< Graph, IndexMap >\r\n        ColorMapHelper;\r\n    typedef typename ColorMapHelper::type ColorMap;\r\n    ColorMap color = ColorMapHelper::build(g, index_map);\r\n    dijkstra_shortest_paths_no_init(g, s_begin, s_end, predecessor, distance,\r\n        weight, index_map, compare, combine, zero, vis, color);\r\n}\r\n\r\n// Call breadth first search with default color map.\r\ntemplate < class Graph, class DijkstraVisitor, class PredecessorMap,\r\n    class DistanceMap, class WeightMap, class IndexMap, class Compare,\r\n    class Combine, class DistZero >\r\ninline void dijkstra_shortest_paths_no_init(const Graph& g,\r\n    typename graph_traits< Graph >::vertex_descriptor s,\r\n    PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\r\n    IndexMap index_map, Compare compare, Combine combine, DistZero zero,\r\n    DijkstraVisitor vis)\r\n{\r\n    dijkstra_shortest_paths_no_init(g, &s, &s + 1, predecessor, distance,\r\n        weight, index_map, compare, combine, zero, vis);\r\n}\r\n\r\n// Call breadth first search\r\ntemplate < class Graph, class SourceInputIter, class DijkstraVisitor,\r\n    class PredecessorMap, class DistanceMap, class WeightMap, class IndexMap,\r\n    class Compare, class Combine, class DistZero, class ColorMap >\r\ninline void dijkstra_shortest_paths_no_init(const Graph& g,\r\n    SourceInputIter s_begin, SourceInputIter s_end, PredecessorMap predecessor,\r\n    DistanceMap distance, WeightMap weight, IndexMap index_map, Compare compare,\r\n    Combine combine, DistZero zero, DijkstraVisitor vis, ColorMap color)\r\n{\r\n    typedef indirect_cmp< DistanceMap, Compare > IndirectCmp;\r\n    IndirectCmp icmp(distance, compare);\r\n\r\n    typedef typename graph_traits< Graph >::vertex_descriptor Vertex;\r\n\r\n    // Now the default: use a d-ary heap\r\n    boost::scoped_array< std::size_t > index_in_heap_map_holder;\r\n    typedef detail::vertex_property_map_generator< Graph, IndexMap,\r\n        std::size_t >\r\n        IndexInHeapMapHelper;\r\n    typedef typename IndexInHeapMapHelper::type IndexInHeapMap;\r\n    IndexInHeapMap index_in_heap\r\n        = IndexInHeapMapHelper::build(g, index_map, index_in_heap_map_holder);\r\n    typedef d_ary_heap_indirect< Vertex, 4, IndexInHeapMap, DistanceMap,\r\n        Compare >\r\n        MutableQueue;\r\n    MutableQueue Q(distance, index_in_heap, compare);\r\n\r\n    detail::dijkstra_bfs_visitor< DijkstraVisitor, MutableQueue, WeightMap,\r\n        PredecessorMap, DistanceMap, Combine, Compare >\r\n        bfs_vis(vis, Q, weight, predecessor, distance, combine, compare, zero);\r\n\r\n    breadth_first_visit(g, s_begin, s_end, Q, bfs_vis, color);\r\n}\r\n\r\n// Call breadth first search\r\ntemplate < class Graph, class DijkstraVisitor, class PredecessorMap,\r\n    class DistanceMap, class WeightMap, class IndexMap, class Compare,\r\n    class Combine, class DistZero, class ColorMap >\r\ninline void dijkstra_shortest_paths_no_init(const Graph& g,\r\n    typename graph_traits< Graph >::vertex_descriptor s,\r\n    PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\r\n    IndexMap index_map, Compare compare, Combine combine, DistZero zero,\r\n    DijkstraVisitor vis, ColorMap color)\r\n{\r\n    dijkstra_shortest_paths_no_init(g, &s, &s + 1, predecessor, distance,\r\n        weight, index_map, compare, combine, zero, vis, color);\r\n}\r\n\r\n// Initialize distances and call breadth first search with default color map\r\ntemplate < class VertexListGraph, class SourceInputIter, class DijkstraVisitor,\r\n    class PredecessorMap, class DistanceMap, class WeightMap, class IndexMap,\r\n    class Compare, class Combine, class DistInf, class DistZero, typename T,\r\n    typename Tag, typename Base >\r\ninline void dijkstra_shortest_paths(const VertexListGraph& g,\r\n    SourceInputIter s_begin, SourceInputIter s_end, PredecessorMap predecessor,\r\n    DistanceMap distance, WeightMap weight, IndexMap index_map, Compare compare,\r\n    Combine combine, DistInf inf, DistZero zero, DijkstraVisitor vis,\r\n    const bgl_named_params< T, Tag, Base >& BOOST_GRAPH_ENABLE_IF_MODELS_PARM(\r\n        VertexListGraph, vertex_list_graph_tag))\r\n{\r\n    boost::two_bit_color_map< IndexMap > color(num_vertices(g), index_map);\r\n    dijkstra_shortest_paths(g, s_begin, s_end, predecessor, distance, weight,\r\n        index_map, compare, combine, inf, zero, vis, color);\r\n}\r\n\r\n// Initialize distances and call breadth first search with default color map\r\ntemplate < class VertexListGraph, class DijkstraVisitor, class PredecessorMap,\r\n    class DistanceMap, class WeightMap, class IndexMap, class Compare,\r\n    class Combine, class DistInf, class DistZero, typename T, typename Tag,\r\n    typename Base >\r\ninline void dijkstra_shortest_paths(const VertexListGraph& g,\r\n    typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n    PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\r\n    IndexMap index_map, Compare compare, Combine combine, DistInf inf,\r\n    DistZero zero, DijkstraVisitor vis,\r\n    const bgl_named_params< T, Tag, Base >& BOOST_GRAPH_ENABLE_IF_MODELS_PARM(\r\n        VertexListGraph, vertex_list_graph_tag))\r\n{\r\n    dijkstra_shortest_paths(g, &s, &s + 1, predecessor, distance, weight,\r\n        index_map, compare, combine, inf, zero, vis);\r\n}\r\n\r\n// Initialize distances and call breadth first search\r\ntemplate < class VertexListGraph, class SourceInputIter, class DijkstraVisitor,\r\n    class PredecessorMap, class DistanceMap, class WeightMap, class IndexMap,\r\n    class Compare, class Combine, class DistInf, class DistZero,\r\n    class ColorMap >\r\ninline void dijkstra_shortest_paths(const VertexListGraph& g,\r\n    SourceInputIter s_begin, SourceInputIter s_end, PredecessorMap predecessor,\r\n    DistanceMap distance, WeightMap weight, IndexMap index_map, Compare compare,\r\n    Combine combine, DistInf inf, DistZero zero, DijkstraVisitor vis,\r\n    ColorMap color)\r\n{\r\n    typedef typename property_traits< ColorMap >::value_type ColorValue;\r\n    typedef color_traits< ColorValue > Color;\r\n    typename graph_traits< VertexListGraph >::vertex_iterator ui, ui_end;\r\n    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)\r\n    {\r\n        vis.initialize_vertex(*ui, g);\r\n        put(distance, *ui, inf);\r\n        put(predecessor, *ui, *ui);\r\n        put(color, *ui, Color::white());\r\n    }\r\n    for (SourceInputIter it = s_begin; it != s_end; ++it)\r\n    {\r\n        put(distance, *it, zero);\r\n    }\r\n\r\n    dijkstra_shortest_paths_no_init(g, s_begin, s_end, predecessor, distance,\r\n        weight, index_map, compare, combine, zero, vis, color);\r\n}\r\n\r\n// Initialize distances and call breadth first search\r\ntemplate < class VertexListGraph, class DijkstraVisitor, class PredecessorMap,\r\n    class DistanceMap, class WeightMap, class IndexMap, class Compare,\r\n    class Combine, class DistInf, class DistZero, class ColorMap >\r\ninline void dijkstra_shortest_paths(const VertexListGraph& g,\r\n    typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n    PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\r\n    IndexMap index_map, Compare compare, Combine combine, DistInf inf,\r\n    DistZero zero, DijkstraVisitor vis, ColorMap color)\r\n{\r\n    dijkstra_shortest_paths(g, &s, &s + 1, predecessor, distance, weight,\r\n        index_map, compare, combine, inf, zero, vis, color);\r\n}\r\n\r\n// Initialize distances and call breadth first search\r\ntemplate < class VertexListGraph, class SourceInputIter, class DijkstraVisitor,\r\n    class PredecessorMap, class DistanceMap, class WeightMap, class IndexMap,\r\n    class Compare, class Combine, class DistInf, class DistZero >\r\ninline void dijkstra_shortest_paths(const VertexListGraph& g,\r\n    SourceInputIter s_begin, SourceInputIter s_end, PredecessorMap predecessor,\r\n    DistanceMap distance, WeightMap weight, IndexMap index_map, Compare compare,\r\n    Combine combine, DistInf inf, DistZero zero, DijkstraVisitor vis)\r\n{\r\n    dijkstra_shortest_paths(g, s_begin, s_end, predecessor, distance, weight,\r\n        index_map, compare, combine, inf, zero, vis, no_named_parameters());\r\n}\r\n\r\n// Initialize distances and call breadth first search\r\ntemplate < class VertexListGraph, class DijkstraVisitor, class PredecessorMap,\r\n    class DistanceMap, class WeightMap, class IndexMap, class Compare,\r\n    class Combine, class DistInf, class DistZero >\r\ninline void dijkstra_shortest_paths(const VertexListGraph& g,\r\n    typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n    PredecessorMap predecessor, DistanceMap distance, WeightMap weight,\r\n    IndexMap index_map, Compare compare, Combine combine, DistInf inf,\r\n    DistZero zero, DijkstraVisitor vis)\r\n{\r\n    dijkstra_shortest_paths(g, &s, &s + 1, predecessor, distance, weight,\r\n        index_map, compare, combine, inf, zero, vis);\r\n}\r\n\r\nnamespace detail\r\n{\r\n\r\n    // Handle defaults for PredecessorMap and\r\n    // Distance Compare, Combine, Inf and Zero\r\n    template < class VertexListGraph, class DistanceMap, class WeightMap,\r\n        class IndexMap, class Params >\r\n    inline void dijkstra_dispatch2(const VertexListGraph& g,\r\n        typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n        DistanceMap distance, WeightMap weight, IndexMap index_map,\r\n        const Params& params)\r\n    {\r\n        // Default for predecessor map\r\n        dummy_property_map p_map;\r\n\r\n        typedef typename property_traits< DistanceMap >::value_type D;\r\n        D inf = choose_param(get_param(params, distance_inf_t()),\r\n            (std::numeric_limits< D >::max)());\r\n\r\n        dijkstra_shortest_paths(g, s,\r\n            choose_param(get_param(params, vertex_predecessor), p_map),\r\n            distance, weight, index_map,\r\n            choose_param(\r\n                get_param(params, distance_compare_t()), std::less< D >()),\r\n            choose_param(\r\n                get_param(params, distance_combine_t()), std::plus< D >()),\r\n            inf, choose_param(get_param(params, distance_zero_t()), D()),\r\n            choose_param(get_param(params, graph_visitor),\r\n                make_dijkstra_visitor(null_visitor())),\r\n            params);\r\n    }\r\n\r\n    template < class VertexListGraph, class DistanceMap, class WeightMap,\r\n        class IndexMap, class Params >\r\n    inline void dijkstra_dispatch1(const VertexListGraph& g,\r\n        typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n        DistanceMap distance, WeightMap weight, IndexMap index_map,\r\n        const Params& params)\r\n    {\r\n        // Default for distance map\r\n        typedef typename property_traits< WeightMap >::value_type D;\r\n        typename std::vector< D >::size_type n\r\n            = is_default_param(distance) ? num_vertices(g) : 1;\r\n        std::vector< D > distance_map(n);\r\n\r\n        detail::dijkstra_dispatch2(g, s,\r\n            choose_param(distance,\r\n                make_iterator_property_map(\r\n                    distance_map.begin(), index_map, distance_map[0])),\r\n            weight, index_map, params);\r\n    }\r\n} // namespace detail\r\n\r\n// Named Parameter Variant\r\ntemplate < class VertexListGraph, class Param, class Tag, class Rest >\r\ninline void dijkstra_shortest_paths(const VertexListGraph& g,\r\n    typename graph_traits< VertexListGraph >::vertex_descriptor s,\r\n    const bgl_named_params< Param, Tag, Rest >& params)\r\n{\r\n    // Default for edge weight and vertex index map is to ask for them\r\n    // from the graph.  Default for the visitor is null_visitor.\r\n    detail::dijkstra_dispatch1(g, s, get_param(params, vertex_distance),\r\n        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),\r\n        choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n        params);\r\n}\r\n\r\n} // namespace boost\r\n\r\n#include BOOST_GRAPH_MPI_INCLUDE(< boost / graph / distributed / dijkstra_shortest_paths.hpp >)\r\n\r\n#endif // BOOST_GRAPH_DIJKSTRA_HPP\r\n", "meta": {"hexsha": "053c5fddc931b30a1d8ce7268a69018817154dfa", "size": 24275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/dijkstra_shortest_paths.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/dijkstra_shortest_paths.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/dijkstra_shortest_paths.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.7814113597, "max_line_length": 96, "alphanum_fraction": 0.6689186406, "num_tokens": 5392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.025565213366451192, "lm_q1q2_score": 0.007604882552797567}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Cell class declared in the\n    swp_cell.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_cell.h\"\n#include \"swp_particle_model.h\"\n#include \"swp_birth_process.h\"\n#include \"swp_death_process.h\"\n#include \"swp_sprog_idealgas_wrapper.h\"\n#include \"swp_fixed_mixture.h\"\n\n#include <stdexcept>\n\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n\nusing namespace std;\n\nnamespace Sweep {\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (public).\nCell::Cell(const Sweep::ParticleModel &model, const bool const_gas)\n: m_ensemble(), m_model(&model),\n  m_smpvol(1.0), m_fixed_chem(false),\n  m_constv(false), m_particle_density(0.0), m_adiabatic_flag(false)\n{\n    if(const_gas)\n        m_gas = new Sweep::FixedMixture(fvector(7 + model.Species()->size()), *model.Species());\n    else\n        m_gas = new Sweep::SprogIdealGasWrapper(*model.Species());\n\n    assert(isValid());\n}\n\n// Copy constructor.\nCell::Cell(const Cell &copy)\n: m_gas(copy.m_gas->Clone())\n{\n    *this = copy;\n\tassert(isValid());\n}\n\n// Stream-reading constructor.\nCell::Cell(std::istream &in, const Sweep::ParticleModel &model)\n: m_model(&model), m_gas(new Sweep::SprogIdealGasWrapper(*model.Species()))\n{\n    Deserialize(in, model);\n\tassert(isValid());\n}\n\n// Default destructor.\nCell::~Cell(void)\n{\n\tassert(isValid());\n    delete m_gas;\n}\n\n\n// OPERATOR OVERLOADS.\n\n// Assignment operator.\nCell &Cell::operator=(const Sweep::Cell &rhs)\n{\n    if (this != &rhs) {\n\t//assert(rhs.isValid());\n        delete m_gas;\n        m_gas        = rhs.m_gas->Clone();\n        m_ensemble   = rhs.m_ensemble;\n        m_model      = rhs.m_model;\n        m_smpvol     = rhs.m_smpvol;\n        m_fixed_chem = rhs.m_fixed_chem;\n        m_inflow     = rhs.m_inflow;\n        m_outflow    = rhs.m_outflow;\n        m_adiabatic_flag = rhs.m_adiabatic_flag;          // flag for adiabatic operation\n        m_bulk_heat_capacity = rhs.m_bulk_heat_capacity;  // temperature update variables\n\tm_particle_heat_capacity = rhs.m_particle_heat_capacity;\n        m_particle_density = rhs.m_particle_density;\n        m_enthalpies = rhs.m_enthalpies;\n\tm_constv = rhs.m_constv;                          // flag for constant volume operation\n    }\n    assert(isValid());\n    return *this;\n}\n\n/*!\n * @param os    Output stream\n * @param net   Cell object to print\n * @return      Output stream\n */\nstd::ostream& operator<<(\n        std::ostream &os,\n        const Sweep::Cell &c)\n{\n  os << \"[Sweep::Cell]\\n\";\n  if (&(c.Particles()) != NULL) os << \" with \" << c.Particles();\n  os << \" with [EnvInterface],\" <<\n          \" T=\" << c.GasPhase().Temperature() <<\n          \" P=\" << c.GasPhase().Pressure() <<\n          \" SP0=\" << c.GasPhase().SpeciesConcentration(0) <<\n          \" \\n\";\n  assert(c.isValid());\n  return os;\n}\n\n\n// THE PARTICLE ENSEMBLE.\n\n// Returns the particle ensemble.\nEnsemble &Cell::Particles(void) {return m_ensemble;}\nconst Ensemble &Cell::Particles(void) const {return m_ensemble;}\n\n// Returns the particle count.\nunsigned int Cell::ParticleCount(void) const\n{\n    assert(isValid());\n    return m_ensemble.Count();\n}\n\n// Returns the particle statistical weight.\ndouble Cell::ParticleWeightSum(void) const\n{\n\treturn m_ensemble.GetSum(iW);\n}\n\n/**\n * Initialise the ensemble to hold particles of the type specified\n * by the model and containing the particular particles contained\n * in the range [particle_list_begin, particle_list_end) and set\n * the sample volume to achieve the statistical weight.\n *\n *\n *@param[in]        particle_list_begin     Iterator to first in range of particle pointers to insert\n *@param[in]        particle_list_end       Iterator to one past end of range of particle pointers to insert\n *@param[in]        statistical_weight      Number of physical particles represented by each computational particle\n *@param[in,out]    rng                     Random number generator\n */\nvoid Cell::SetParticles(\n        std::list<Particle*>::iterator particle_list_begin,\n        std::list<Particle*>::iterator particle_list_end,\n        double statistical_weight, rng_type &rng)\n{\n    assert(statistical_weight > 0);\n    // This puts the particles into the ensemble and clears any scaling\n    // stored inside the ensemble\n    m_ensemble.SetParticles(particle_list_begin, particle_list_end, rng);\n\n    m_smpvol = 1.0 / statistical_weight;\n    assert(isValid());\n}\n\n/**\n * Initialise the ensemble to hold particles of the type specified\n * by the model and containing the particular particles contained\n * in the range [particle_list_begin, particle_list_end) and set\n * the sample volume to achieve the statistical weight.\n *\n *\n *@param[in]        particle_list_begin     Iterator to first in range of particle pointers to insert\n *@param[in]        particle_list_end       Iterator to one past end of range of particle pointers to insert\n *@param[in]        statistical_weight      Number of physical particles represented by each computational particle\n *\n *@pre  The length of the input sequence is at most m_ensemble.capacity()\n */\nvoid Cell::SetParticles(\n        std::list<Particle*>::iterator particle_list_begin,\n        std::list<Particle*>::iterator particle_list_end,\n        double statistical_weight)\n{\n    assert(statistical_weight > 0);\n    // This puts the particles into the ensemble and clears any scaling\n    // stored inside the ensemble\n    if(std::distance(particle_list_begin, particle_list_end) > m_ensemble.Capacity())\n        throw std::runtime_error(\"Attempt to set too many particles in Sweep::Cell::SetParticles\");\n\n    // The rng will not be used, so just provide a default constructed object\n    rng_type rng;\n    const rng_type rngCopy(rng);\n    m_ensemble.SetParticles(particle_list_begin, particle_list_end, rng);\n    assert(rngCopy == rng);\n\n    m_smpvol = 1.0 / statistical_weight;\n    assert(isValid());\n}\n\n// Returns particle statistics.\nvoid Cell::GetVitalStats(Stats::EnsembleStats &stats) const\n{\n    stats.Calculate(m_ensemble, 1.0/SampleVolume());\n}\n\n\n// SCALING ROUTINES INCL. SAMPLE VOLUME.\n\n// Returns the double system to stochastic system scaling factor.\ndouble Cell::SampleVolume() const\n{\n    return m_smpvol * m_ensemble.Scaling();\n}\n\n/*!\n * Set the number density which the ensemble represents including the\n * effects of ensemble doublings and contractions.\n *\n *@param[in]    scale_factor    Ratio of new to old sample volumes\n *\n *@pre      scale_factor > 0\n */\nvoid Cell::AdjustSampleVolume(double scale_factor)\n{\n    assert(scale_factor > 0);\n    assert(scale_factor <= std::numeric_limits<double>::max());\n    m_smpvol = SampleVolume() * scale_factor;\n\n    // The effects of ensemble rescalings are now incorporated in this sample\n    // volume.\n    m_ensemble.ResetScaling();\n    assert(isValid());\n}\n\nunsigned int Cell::NumOfStartingSpecies(const int index) const \n{\n    // figure out how many starting PAHs are supposed in the particle ensemble\n    // N = NA*Vsmpl*molar density*volume fraction of starting PAH.\n    unsigned int m_amount = NA * SampleVolume() * GasPhase().SpeciesConcentration(index);\n    return m_amount;\n}\n\n/**\n * Clear any particles and set the sample volume so that a full ensemble\n * (of m_ensemble.Capacity() particles) has the specified m0.\n *\n *@param[in]    m0              Particle number density for full ensemble (units \\f$\\mathrm{m}^{-3}\\f$)\n */\nvoid Cell::Reset(const double m0)\n{\n    assert(m0 > 0.0);\n    m_ensemble.Clear();\n    m_ensemble.ResetScaling();\n\n    if ((m_ensemble.Capacity() > 0) && (m0 > 0.0)) {\n        m_smpvol = m_ensemble.Capacity() / m0;\n    }\n    else {\n        // The ensemble has not yet been initialised\n        m_smpvol = 1.0;\n    }\n    assert(isValid());\n\n}\n\n\n// FIXED/VARIABLE CHEMISTRY.\n\n// Returns whether or not the chemical conditions are fixed.\nbool Cell::FixedChem() const {return m_fixed_chem;}\n\n// Sets whether or not the chemical conditions are fixed.\nvoid Cell::SetFixedChem(bool fixed) {m_fixed_chem = fixed;}\n\n// Set the chemical conditions to be variable.\nvoid Cell::SetVariableChem(bool vari) {m_fixed_chem = !vari;}\n\n\n// PARTICLE INFLOW PROCESSES.\n\n// Returns the number of inflow processes defined\n// for this Cell.\nunsigned int Cell::InflowCount(void) const {return m_inflow.size();}\n\n// Returns the vector of particle inflow processes.\nconst Processes::BirthPtrVector &Cell::Inflows(void) const {return m_inflow;}\n\n// Returns the ith particle inflow process.\nProcesses::BirthProcess *const Cell::Inflows(unsigned int i) const\n{\n    if (i < m_inflow.size()) {\n        return m_inflow[i];\n    } else {\n        return NULL;\n    }\n}\n\n// Add an inflow process to the Cell. The process is copied.\nvoid Cell::AddInflow(Processes::BirthProcess &inf)\n{\n    m_inflow.push_back(inf.Clone());\n}\n\n\n// PARTICLE OUTFLOW PROCESSES.\n\n// Returns the number of outflow processes defined\n// for this Cell.\nunsigned int Cell::OutflowCount(void) const {return m_outflow.size();}\n\n// Returns the vector of particle outflow processes.\nconst Processes::DeathPtrVector &Cell::Outflows(void) const {return m_outflow;}\n\n// Returns the ith particle outflow process.\nProcesses::DeathProcess *const Cell::Outflows(unsigned int i) const\n{\n    if (i < m_outflow.size()) {\n        return m_outflow[i];\n    } else {\n        return NULL;\n    }\n}\n\n\n// Add an outflow process to the Cell. The process is copied.\nvoid Cell::AddOutflow(Processes::DeathProcess &out)\n{\n    m_outflow.push_back(out.Clone());\n}\n\n// Add an outflow process with the given rate to the Cell.\nvoid Cell::AddOutflow(double rate, const Sweep::Mechanism &mech)\n{\n    Processes::DeathProcess *death = new Processes::DeathProcess(mech);\n    death->SetA(rate);\n    m_outflow.push_back(death);\n}\n\n// Store temperature properties to be used in particle step\nvoid Cell::setGasPhaseProperties(double C_bulk, double C_particle, double rhop, fvector enthalpies)\n{\n    m_bulk_heat_capacity = C_bulk;\n    m_particle_heat_capacity = C_particle;\n    m_particle_density = rhop;\n    m_enthalpies = enthalpies;\n}\n\n// READ/WRITE/COPY.\n\n/*!\n * Writes the object to a binary stream.\n *\n *@param[in,out]    out     output stream\n */\nvoid Cell::Serialize(std::ostream &out) const\n{\n    assert(isValid());\n    if (out.good()) {\n        // Output the gas mixture\n        // First check how the mixture is stored\n        const SprogIdealGasWrapper *pSprogWrapper = dynamic_cast<const SprogIdealGasWrapper*>(m_gas);\n        const FixedMixture *pFixedMix = dynamic_cast<const FixedMixture*>(m_gas);\n\n        // Now serialise with a label to say what type of object has been serialised\n        // so that it can be correctly deserialised.\n        if(NULL != pSprogWrapper) {\n            const int sprogWrapperID = 1;\n            out.write(reinterpret_cast<const char *>(&sprogWrapperID), sizeof(sprogWrapperID));\n            pSprogWrapper->Serialize(out);\n        }\n        else if(NULL != pFixedMix) {\n            const int FixedMixID = 2;\n            out.write(reinterpret_cast<const char *>(&FixedMixID), sizeof(FixedMixID));\n            throw std::logic_error(\"Serialisation of Sweep::FixedMixture not supported in Sweep::Cell::Serialize\");\n        }\n        else {\n            throw std::logic_error(\"Unsupported gas phase mixture type in Sweep::Cell::Serialize\");\n        }\n\n        // Output the sample volume.\n        double v = (double)m_smpvol;\n        out.write((char*)&v, sizeof(v));\n\n        // Output if fixed chem.\n        out.write((char*)&m_fixed_chem, sizeof(m_fixed_chem));\n\n\n\t\t// Output if constant volume. \n\t\tout.write((char*)&m_constv, sizeof(m_constv));\n\n\n\t\t// Output if fully adiabatic.\n\t\tout.write((char*)&m_adiabatic_flag, sizeof(m_adiabatic_flag));\n\n        // Output the ensemble.\n        m_ensemble.Serialize(out);\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, Cell::Serialize).\");\n    }\n}\n\n/*!\n * Read object state from a binary stream.\n *\n *@param[in,out]        in      Stream from which to read\n *@param[in]            model   Model for interpreting the particles in the cell\n *\n *@pre  m_gas is initialised\n */\nvoid Cell::Deserialize(std::istream &in, const Sweep::ParticleModel &model)\n{\n    if (in.good()) {\n\n        // Find out what kind of mixture to read, see Serialize() method for possible values\n        int mixID;\n        in.read(reinterpret_cast<char *>(&mixID), sizeof(mixID));\n\n        switch(mixID) {\n            case 1:\n            {\n                //SprogIdealGasWrapper\n                Sweep::SprogIdealGasWrapper *pGas = new Sweep::SprogIdealGasWrapper(*model.Species());\n                pGas->Implementation()->Deserialize(in);\n                // Set the species, because the pointer gets reset in Sprog::Mixture::Deserialize\n                pGas->Implementation()->SetSpecies(*model.Species());\n                m_gas = pGas;\n                break;\n            }\n            case 2:\n                // FixedMixture - not currently supported\n                throw std::logic_error(\"Deserialisation of Sweep::FixedMixture not supported in Sweep::Cell::Deserialize\");\n                break;\n            default:\n                throw std::logic_error(\"Unrecognised gas-phase mixture type in Sweep::Cell::Deserialize\");\n                break;\n        }\n\n        // Read the sample volume.\n        in.read(reinterpret_cast<char*>(&m_smpvol), sizeof(m_smpvol));\n\n        // Read if fixed chem.\n        in.read(reinterpret_cast<char*>(&m_fixed_chem), sizeof(m_fixed_chem));\n\n\t\t// Read if constant volume.\n\t\tin.read(reinterpret_cast<char*>(&m_constv), sizeof(m_constv));\n\n\t\t// Read if fully adiabatic.\n\t\tin.read(reinterpret_cast<char*>(&m_adiabatic_flag), sizeof(m_adiabatic_flag));\n\n        // Read the ensemble.\n        m_ensemble.Deserialize(in, model);\n\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, Cell::Deserialize).\");\n    }\n}\n\n// Check cell consistency, ensure gas phase mixture pointers are never null \nbool Cell::isValid() const {\n    return m_gas != NULL; \n}\n\n} // Sweep namespace\n", "meta": {"hexsha": "43b3b7b89c28df435defcd070f07365b13a4df53", "size": 15257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_cell.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_cell.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_cell.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 31.0101626016, "max_line_length": 123, "alphanum_fraction": 0.671167333, "num_tokens": 3626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968626535545, "lm_q2_score": 0.03622005391432915, "lm_q1q2_score": 0.007587003329948786}}
{"text": "/*\n * Copyright (c) 2009-2021, Albertas Vyšniauskas\n * All rights reserved.\n *\n * Redistribution 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 software author nor the names of its contributors may be used 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 WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 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\n#include \"Color.h\"\n#include <cmath>\n#include <string>\n#include <tuple>\n#include <stdexcept>\n#include <boost/math/special_functions/relative_difference.hpp>\n\n// Constant used for lab->xyz transform. Should be calculated with maximum accuracy possible.\nconst double Epsilon = 216.0 / 24389.0;\nconst double Kk = 24389.0 / 27.0;\nconst Color Color::white = { 1.0f, 1.0f, 1.0f };\nconst Color Color::black = { 0.0f, 0.0f, 0.0f };\nstatic Color::Matrix3d sRGBTransformation;\nstatic Color::Matrix3d sRGBTransformationInverted;\nstatic Color::Matrix3d d65d50AdaptationMatrixValue;\nstatic Color::Matrix3d d50d65AdaptationMatrixValue;\nconst Color::Matrix3d &Color::sRGBMatrix = sRGBTransformation;\nconst Color::Matrix3d &Color::sRGBInvertedMatrix = sRGBTransformationInverted;\nconst Color::Matrix3d &Color::d65d50AdaptationMatrix = d65d50AdaptationMatrixValue;\nconst Color::Matrix3d &Color::d50d65AdaptationMatrix = d50d65AdaptationMatrixValue;\nstatic Color::Vector3f references[][2] = {\n\t{ { 109.850f, 100.000f, 35.585f }, { 111.144f, 100.000f, 35.200f } },\n\t{ { 98.074f, 100.000f, 118.232f }, { 97.285f, 100.000f, 116.145f } },\n\t{ { 96.422f, 100.000f, 82.521f }, { 96.720f, 100.000f, 81.427f } },\n\t{ { 95.682f, 100.000f, 92.149f }, { 95.799f, 100.000f, 90.926f } },\n\t{ { 95.047f, 100.000f, 108.883f }, { 94.811f, 100.000f, 107.304f } },\n\t{ { 94.972f, 100.000f, 122.638f }, { 94.416f, 100.000f, 120.641f } },\n\t{ { 99.187f, 100.000f, 67.395f }, { 103.280f, 100.000f, 69.026f } },\n\t{ { 95.044f, 100.000f, 108.755f }, { 95.792f, 100.000f, 107.687f } },\n\t{ { 100.966f, 100.000f, 64.370f }, { 103.866f, 100.000f, 65.627f } },\n};\nvoid Color::initialize() {\n\t// constants used below are sRGB working space red, green and blue primaries for D65 reference white\n\tsRGBTransformation = getWorkingSpaceMatrix(0.6400f, 0.3300f, 0.3000f, 0.6000f, 0.1500f, 0.0600f, getReference(ReferenceIlluminant::D65, ReferenceObserver::_2));\n\tsRGBTransformationInverted = sRGBTransformation.inverse().value();\n\td65d50AdaptationMatrixValue = getChromaticAdaptationMatrix(getReference(ReferenceIlluminant::D65, ReferenceObserver::_2), getReference(ReferenceIlluminant::D50, ReferenceObserver::_2));\n\td50d65AdaptationMatrixValue = getChromaticAdaptationMatrix(getReference(ReferenceIlluminant::D50, ReferenceObserver::_2), getReference(ReferenceIlluminant::D65, ReferenceObserver::_2));\n}\nnamespace util {\ntemplate<typename T>\ninline void copy(const T *source, T *destination, size_t count = 1) {\n\tfor (size_t i = 0; i < count; i++) {\n\t\tdestination[i] = source[i];\n\t}\n}\ntemplate<typename T, typename TSource>\ninline void castCopy(const TSource *source, T *destination, size_t count = 1) {\n\tfor (size_t i = 0; i < count; i++) {\n\t\tdestination[i] = static_cast<T>(source[i]);\n\t}\n}\ntemplate<typename T>\ninline void fill(T *destination, T value, size_t count = 1) {\n\tfor (size_t i = 0; i < count; i++) {\n\t\tdestination[i] = value;\n\t}\n}\n}\nstatic Color::Vector3d xyzToLab(const Color::Vector3d &xyzVector, const Color::Vector3f &referenceWhite);\nstatic Color::Vector3d labToXyz(const Color::Vector3d &labVector, const Color::Vector3f &referenceWhite);\nstatic Color::Vector3d xyzChromaticAdaptation(Color::Vector3d xyzVector, const Color::Matrix3d &adaptation);\nColor &Color::zero() {\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tdata[i] = 0;\n\treturn *this;\n}\nColor Color::zero() const {\n\treturn Color();\n}\nColor::Color() {\n\tutil::fill(data, 0.0f, ChannelCount);\n}\nColor::Color(float value) {\n\tutil::fill(data, value, ChannelCount);\n}\nColor::Color(int value) {\n\tutil::fill(data, value / 255.0f, ChannelCount);\n}\nColor::Color(float red, float green, float blue) {\n\trgb.red = red;\n\trgb.green = green;\n\trgb.blue = blue;\n\tutil::fill(data + 3, 0.0f, ChannelCount - 3);\n}\nColor::Color(float value1, float value2, float value3, float value4) {\n\tdata[0] = value1;\n\tdata[1] = value2;\n\tdata[2] = value3;\n\tdata[3] = value4;\n}\nColor::Color(int red, int green, int blue) {\n\trgb.red = static_cast<float>(red / 255.0f);\n\trgb.green = static_cast<float>(green / 255.0f);\n\trgb.blue = static_cast<float>(blue / 255.0f);\n\tutil::fill(data + 3, 0.0f, ChannelCount - 3);\n}\nColor::Color(const Color &color) {\n\tutil::copy(color.data, data, MemberCount);\n}\nColor::Color(const Vector3f &value) {\n\tutil::copy(value.data, data, 3);\n\tutil::fill(data + 3, 0.0f, ChannelCount - 3);\n}\nColor::Color(const Vector3d &value) {\n\tutil::castCopy(value.data, data, 3);\n\tutil::fill(data + 3, 0.0f, ChannelCount - 3);\n}\ntemplate<>\nColor::Vector3f Color::rgbVector() const {\n\treturn Vector3f(rgb.red, rgb.green, rgb.blue);\n}\ntemplate<>\nColor::Vector3d Color::rgbVector() const {\n\treturn Vector3d(rgb.red, rgb.green, rgb.blue);\n}\nColor Color::rgbToHsv() const {\n\tfloat min, max;\n\tstd::tie(min, max) = math::minMax(rgb.red, rgb.green, rgb.blue);\n\tfloat delta = max - min;\n\tColor result;\n\tresult.hsv.value = max;\n\tif (max != 0.0f)\n\t\tresult.hsv.saturation = delta / max;\n\telse\n\t\tresult.hsv.saturation = 0.0f;\n\tif (result.hsv.saturation == 0.0f) {\n\t\tresult.hsv.hue = 0.0f;\n\t} else {\n\t\tif (rgb.red == max)\n\t\t\tresult.hsv.hue = (rgb.green - rgb.blue) / delta;\n\t\telse if (rgb.green == max)\n\t\t\tresult.hsv.hue = 2.0f + (rgb.blue - rgb.red) / delta;\n\t\telse if (rgb.blue == max)\n\t\t\tresult.hsv.hue = 4.0f + (rgb.red - rgb.green) / delta;\n\t\tresult.hsv.hue /= 6.0f;\n\t\tresult.hsv.hue = math::wrap(result.hsv.hue);\n\t}\n\treturn result;\n}\nColor Color::hsvToRgb() const {\n\tfloat v = hsv.value;\n\tColor result;\n\tif (hsv.saturation == 0.0f) {\n\t\tresult.rgb.red = result.rgb.green = result.rgb.blue = hsv.value;\n\t} else {\n\t\tfloat h, f, x, y, z;\n\t\th = (hsv.hue - std::floor(hsv.hue)) * 6.0f;\n\t\tint i = int(h);\n\t\tf = h - std::floor(h);\n\t\tx = v * (1.0f - hsv.saturation);\n\t\ty = v * (1.0f - (hsv.saturation * f));\n\t\tz = v * (1.0f - (hsv.saturation * (1.0f - f)));\n\t\tif (i == 0) {\n\t\t\tresult.rgb.red = v;\n\t\t\tresult.rgb.green = z;\n\t\t\tresult.rgb.blue = x;\n\t\t} else if (i == 1) {\n\t\t\tresult.rgb.red = y;\n\t\t\tresult.rgb.green = v;\n\t\t\tresult.rgb.blue = x;\n\t\t} else if (i == 2) {\n\t\t\tresult.rgb.red = x;\n\t\t\tresult.rgb.green = v;\n\t\t\tresult.rgb.blue = z;\n\t\t} else if (i == 3) {\n\t\t\tresult.rgb.red = x;\n\t\t\tresult.rgb.green = y;\n\t\t\tresult.rgb.blue = v;\n\t\t} else if (i == 4) {\n\t\t\tresult.rgb.red = z;\n\t\t\tresult.rgb.green = x;\n\t\t\tresult.rgb.blue = v;\n\t\t} else {\n\t\t\tresult.rgb.red = v;\n\t\t\tresult.rgb.green = x;\n\t\t\tresult.rgb.blue = y;\n\t\t}\n\t}\n\treturn result;\n}\nColor Color::rgbToHsl() const {\n\tfloat min, max;\n\tstd::tie(min, max) = math::minMax(rgb.red, rgb.green, rgb.blue);\n\tfloat delta = max - min;\n\tColor result;\n\tresult.hsl.lightness = (max + min) / 2;\n\tif (delta == 0) {\n\t\tresult.hsl.hue = 0;\n\t\tresult.hsl.saturation = 0;\n\t} else {\n\t\tif (result.hsl.lightness < 0.5f) {\n\t\t\tresult.hsl.saturation = delta / (max + min);\n\t\t} else {\n\t\t\tresult.hsl.saturation = delta / (2 - max - min);\n\t\t}\n\t\tif (rgb.red == max)\n\t\t\tresult.hsl.hue = (rgb.green - rgb.blue) / delta;\n\t\telse if (rgb.green == max)\n\t\t\tresult.hsl.hue = 2.0f + (rgb.blue - rgb.red) / delta;\n\t\telse if (rgb.blue == max)\n\t\t\tresult.hsl.hue = 4.0f + (rgb.red - rgb.green) / delta;\n\t\tresult.hsl.hue /= 6.0f;\n\t\tresult.hsl.hue = math::wrap(result.hsl.hue);\n\t}\n\treturn result;\n}\nColor Color::hslToRgb() const {\n\tColor result;\n\tif (hsl.saturation == 0) {\n\t\tresult.rgb.red = result.rgb.green = result.rgb.blue = hsl.lightness;\n\t} else {\n\t\tfloat q;\n\t\tif (hsl.lightness < 0.5f)\n\t\t\tq = hsl.lightness * (1.0f + hsl.saturation);\n\t\telse\n\t\t\tq = hsl.lightness + hsl.saturation - hsl.lightness * hsl.saturation;\n\t\tfloat p = 2 * hsl.lightness - q;\n\t\tfloat R = hsl.hue + 1 / 3.0f;\n\t\tfloat G = hsl.hue;\n\t\tfloat B = hsl.hue - 1 / 3.0f;\n\t\tif (R > 1) R -= 1;\n\t\tif (B < 0) B += 1;\n\t\tif (6.0f * R < 1)\n\t\t\tresult.rgb.red = p + (q - p) * 6.0f * R;\n\t\telse if (2.0 * R < 1)\n\t\t\tresult.rgb.red = q;\n\t\telse if (3.0 * R < 2)\n\t\t\tresult.rgb.red = p + (q - p) * ((2.0f / 3.0f) - R) * 6.0f;\n\t\telse\n\t\t\tresult.rgb.red = p;\n\t\tif (6.0f * G < 1)\n\t\t\tresult.rgb.green = p + (q - p) * 6.0f * G;\n\t\telse if (2.0f * G < 1)\n\t\t\tresult.rgb.green = q;\n\t\telse if (3.0f * G < 2)\n\t\t\tresult.rgb.green = p + (q - p) * ((2.0f / 3.0f) - G) * 6.0f;\n\t\telse\n\t\t\tresult.rgb.green = p;\n\t\tif (6.0f * B < 1)\n\t\t\tresult.rgb.blue = p + (q - p) * 6.0f * B;\n\t\telse if (2.0f * B < 1)\n\t\t\tresult.rgb.blue = q;\n\t\telse if (3.0f * B < 2)\n\t\t\tresult.rgb.blue = p + (q - p) * ((2.0f / 3.0f) - B) * 6.0f;\n\t\telse\n\t\t\tresult.rgb.blue = p;\n\t}\n\treturn result;\n}\nColor Color::rgbToXyz(const Matrix3d &transformation) const {\n\treturn transformation * linearRgb().rgbVector<double>();\n}\nstatic Color::Vector3d rgbToXyz(const Color::Vector3d &rgbVector, const Color::Matrix3d &transformation) {\n\treturn transformation * rgbVector;\n}\nColor Color::xyzToRgb(const Matrix3d &transformationInverted) const {\n\treturn Color(transformationInverted * rgbVector<double>()).nonLinearRgbInplace();\n}\nstatic Color::Vector3d xyzToRgb(const Color::Vector3d &xyzVector, const Color::Matrix3d &transformationInverted) {\n\treturn transformationInverted * xyzVector;\n}\nColor Color::rgbToLab(const Vector3f &referenceWhite, const Matrix3d &transformation, const Matrix3d &adaptationMatrix) const {\n\treturn ::xyzToLab(::xyzChromaticAdaptation(::rgbToXyz(linearRgb().rgbVector<double>(), transformation), adaptationMatrix), referenceWhite);\n}\nColor Color::labToRgb(const Vector3f &referenceWhite, const Matrix3d &transformationInverted, const Matrix3d &adaptationMatrixInverted) const {\n\treturn Color(::xyzToRgb(::xyzChromaticAdaptation(::labToXyz(rgbVector<double>(), referenceWhite), adaptationMatrixInverted), transformationInverted)).nonLinearRgbInplace();\n}\nColor Color::labToLch() const {\n\tdouble H;\n\tif (lab.a == 0 && lab.b == 0) {\n\t\tH = 0;\n\t} else {\n\t\tH = std::atan2(lab.b, lab.a);\n\t}\n\tH *= 180.0f / math::PI;\n\tif (H < 0) H += 360;\n\tif (H >= 360) H -= 360;\n\treturn Color(lab.L, static_cast<float>(std::sqrt(lab.a * lab.a + lab.b * lab.b)), static_cast<float>(H));\n}\nColor Color::lchToLab() const {\n\treturn Color(lch.L, static_cast<float>(lch.C * std::cos(lch.h * math::PI / 180.0f)), static_cast<float>(lch.C * std::sin(lch.h * math::PI / 180.0f)));\n}\nColor Color::hslToHsv() const {\n\tfloat l = hsl.lightness * 2.0f;\n\tfloat s = hsl.saturation * ((l <= 1.0f) ? (l) : (2.0f - l));\n\tColor result;\n\tresult.hsv.hue = hsl.hue;\n\tif (l + s == 0) {\n\t\tresult.hsv.value = 0;\n\t\tresult.hsv.saturation = 1;\n\t} else {\n\t\tresult.hsv.value = (l + s) / 2.0f;\n\t\tresult.hsv.saturation = (2.0f * s) / (l + s);\n\t}\n\treturn result;\n}\nColor Color::hsvToHsl() const {\n\tfloat l = (2.0f - hsv.saturation) * hsv.value;\n\tfloat s = (hsv.saturation * hsv.value) / ((l <= 1.0f) ? (l) : (2 - l));\n\tif (l == 0) s = 0;\n\treturn Color(hsv.hue, s, l / 2.0f);\n}\nColor &Color::linearRgbInplace() {\n\tif (rgb.red > 0.04045f)\n\t\trgb.red = std::pow((rgb.red + 0.055f) / 1.055f, 2.4f);\n\telse\n\t\trgb.red = rgb.red / 12.92f;\n\tif (rgb.green > 0.04045f)\n\t\trgb.green = std::pow((rgb.green + 0.055f) / 1.055f, 2.4f);\n\telse\n\t\trgb.green = rgb.green / 12.92f;\n\tif (rgb.blue > 0.04045f)\n\t\trgb.blue = std::pow((rgb.blue + 0.055f) / 1.055f, 2.4f);\n\telse\n\t\trgb.blue = rgb.blue / 12.92f;\n\treturn *this;\n}\nColor Color::linearRgb() const {\n\tColor result;\n\tif (rgb.red > 0.04045f)\n\t\tresult.rgb.red = std::pow((rgb.red + 0.055f) / 1.055f, 2.4f);\n\telse\n\t\tresult.rgb.red = rgb.red / 12.92f;\n\tif (rgb.green > 0.04045f)\n\t\tresult.rgb.green = std::pow((rgb.green + 0.055f) / 1.055f, 2.4f);\n\telse\n\t\tresult.rgb.green = rgb.green / 12.92f;\n\tif (rgb.blue > 0.04045f)\n\t\tresult.rgb.blue = std::pow((rgb.blue + 0.055f) / 1.055f, 2.4f);\n\telse\n\t\tresult.rgb.blue = rgb.blue / 12.92f;\n\treturn result;\n}\nColor Color::nonLinearRgb() const {\n\tColor result;\n\tif (rgb.red > 0.0031308f)\n\t\tresult.rgb.red = (1.055f * std::pow(rgb.red, 1.0f / 2.4f)) - 0.055f;\n\telse\n\t\tresult.rgb.red = rgb.red * 12.92f;\n\tif (rgb.green > 0.0031308f)\n\t\tresult.rgb.green = (1.055f * std::pow(rgb.green, 1.0f / 2.4f)) - 0.055f;\n\telse\n\t\tresult.rgb.green = rgb.green * 12.92f;\n\tif (rgb.blue > 0.0031308f)\n\t\tresult.rgb.blue = (1.055f * std::pow(rgb.blue, 1.0f / 2.4f)) - 0.055f;\n\telse\n\t\tresult.rgb.blue = rgb.blue * 12.92f;\n\treturn result;\n}\nColor &Color::nonLinearRgbInplace() {\n\tif (rgb.red > 0.0031308f)\n\t\trgb.red = (1.055f * std::pow(rgb.red, 1.0f / 2.4f)) - 0.055f;\n\telse\n\t\trgb.red = rgb.red * 12.92f;\n\tif (rgb.green > 0.0031308f)\n\t\trgb.green = (1.055f * std::pow(rgb.green, 1.0f / 2.4f)) - 0.055f;\n\telse\n\t\trgb.green = rgb.green * 12.92f;\n\tif (rgb.blue > 0.0031308f)\n\t\trgb.blue = (1.055f * std::pow(rgb.blue, 1.0f / 2.4f)) - 0.055f;\n\telse\n\t\trgb.blue = rgb.blue * 12.92f;\n\treturn *this;\n}\nColor Color::rgbToLch(const Vector3f &referenceWhite, const Matrix3d &transformation, const Matrix3d &adaptationMatrix) const {\n\treturn rgbToLab(referenceWhite, transformation, adaptationMatrix).labToLch();\n}\nColor Color::lchToRgb(const Vector3f &referenceWhite, const Matrix3d &transformationInverted, const Matrix3d &adaptationMatrixInverted) const {\n\treturn lchToLab().labToRgb(referenceWhite, transformationInverted, adaptationMatrixInverted);\n}\nColor Color::rgbToLchD50() const {\n\treturn rgbToLab(getReference(ReferenceIlluminant::D50, ReferenceObserver::_2), sRGBMatrix, d65d50AdaptationMatrix).labToLch();\n}\nColor Color::lchToRgbD50() const {\n\treturn lchToLab().labToRgb(getReference(ReferenceIlluminant::D50, ReferenceObserver::_2), sRGBInvertedMatrix, d50d65AdaptationMatrix);\n}\nColor Color::rgbToLabD50() const {\n\treturn rgbToLab(getReference(ReferenceIlluminant::D50, ReferenceObserver::_2), sRGBMatrix, d65d50AdaptationMatrix);\n}\nColor Color::labToRgbD50() const {\n\treturn labToRgb(getReference(ReferenceIlluminant::D50, ReferenceObserver::_2), sRGBInvertedMatrix, d50d65AdaptationMatrix);\n}\nColor Color::rgbToCmy() const {\n\treturn Color(1 - rgb.red, 1 - rgb.green, 1 - rgb.blue);\n}\nColor Color::cmyToRgb() const {\n\treturn Color(1 - cmy.c, 1 - cmy.m, 1 - cmy.y);\n}\nColor Color::cmyToCmyk() const {\n\tfloat k = 1;\n\tif (cmy.c < k) k = cmy.c;\n\tif (cmy.m < k) k = cmy.m;\n\tif (cmy.y < k) k = cmy.y;\n\tColor result;\n\tif (k == 1) {\n\t\tresult.cmyk.c = result.cmyk.m = result.cmyk.y = 0;\n\t} else {\n\t\tresult.cmyk.c = (cmy.c - k) / (1 - k);\n\t\tresult.cmyk.m = (cmy.m - k) / (1 - k);\n\t\tresult.cmyk.y = (cmy.y - k) / (1 - k);\n\t}\n\tresult.cmyk.k = k;\n\treturn result;\n}\nColor Color::cmykToCmy() const {\n\treturn Color(cmyk.c * (1 - cmyk.k) + cmyk.k, cmyk.m * (1 - cmyk.k) + cmyk.k, cmyk.y * (1 - cmyk.k) + cmyk.k);\n}\nColor Color::rgbToCmyk() const {\n\treturn rgbToCmy().cmyToCmyk();\n}\nColor Color::cmykToRgb() const {\n\treturn cmykToCmy().cmyToRgb();\n}\nColor Color::xyzToLab(const Vector3f &referenceWhite) const {\n\tfloat X = xyz.x / referenceWhite.x;\n\tfloat Y = xyz.y / referenceWhite.y;\n\tfloat Z = xyz.z / referenceWhite.z;\n\tif (X > Epsilon) {\n\t\tX = static_cast<float>(std::pow(X, 1.0f / 3.0f));\n\t} else {\n\t\tX = static_cast<float>((Kk * X + 16.0f) / 116.0f);\n\t}\n\tif (Y > Epsilon) {\n\t\tY = static_cast<float>(std::pow(Y, 1.0f / 3.0f));\n\t} else {\n\t\tY = static_cast<float>((Kk * Y + 16.0f) / 116.0f);\n\t}\n\tif (Z > Epsilon) {\n\t\tZ = static_cast<float>(std::pow(Z, 1.0f / 3.0f));\n\t} else {\n\t\tZ = static_cast<float>((Kk * Z + 16.0f) / 116.0f);\n\t}\n\treturn Color((116 * Y) - 16, 500 * (X - Y), 200 * (Y - Z));\n}\nstatic Color::Vector3d xyzToLab(const Color::Vector3d &xyzVector, const Color::Vector3f &referenceWhite) {\n\tdouble X = xyzVector.x / referenceWhite.x;\n\tdouble Y = xyzVector.y / referenceWhite.y;\n\tdouble Z = xyzVector.z / referenceWhite.z;\n\tif (X > Epsilon) {\n\t\tX = std::pow(X, 1.0 / 3.0);\n\t} else {\n\t\tX = (Kk * X + 16.0) / 116.0;\n\t}\n\tif (Y > Epsilon) {\n\t\tY = std::pow(Y, 1.0 / 3.0);\n\t} else {\n\t\tY = (Kk * Y + 16.0) / 116.0;\n\t}\n\tif (Z > Epsilon) {\n\t\tZ = std::pow(Z, 1.0 / 3.0);\n\t} else {\n\t\tZ = (Kk * Z + 16.0) / 116.0;\n\t}\n\treturn Color::Vector3d((116 * Y) - 16, 500 * (X - Y), 200 * (Y - Z));\n}\nColor Color::labToXyz(const Vector3f &referenceWhite) const {\n\tfloat x, y, z;\n\tfloat fy = (lab.L + 16) / 116;\n\tfloat fx = lab.a / 500 + fy;\n\tfloat fz = fy - lab.b / 200;\n\tconst double K = (24389.0 / 27.0);\n\tif (std::pow(fx, 3) > Epsilon) {\n\t\tx = static_cast<float>(std::pow(fx, 3));\n\t} else {\n\t\tx = static_cast<float>((116 * fx - 16) / K);\n\t}\n\tif (lab.L > K * Epsilon) {\n\t\ty = static_cast<float>(std::pow((lab.L + 16) / 116, 3));\n\t} else {\n\t\ty = static_cast<float>(lab.L / K);\n\t}\n\tif (std::pow(fz, 3) > Epsilon) {\n\t\tz = static_cast<float>(std::pow(fz, 3));\n\t} else {\n\t\tz = static_cast<float>((116 * fz - 16) / K);\n\t}\n\treturn Color(x * referenceWhite.x, y * referenceWhite.y, z * referenceWhite.z);\n}\nstatic Color::Vector3d labToXyz(const Color::Vector3d &labVector, const Color::Vector3f &referenceWhite) {\n\tdouble x, y, z;\n\tdouble fy = (labVector.x + 16) / 116;\n\tdouble fx = labVector.y / 500 + fy;\n\tdouble fz = fy - labVector.z / 200;\n\tconst double K = (24389.0 / 27.0);\n\tif (std::pow(fx, 3) > Epsilon) {\n\t\tx = std::pow(fx, 3);\n\t} else {\n\t\tx = (116 * fx - 16) / K;\n\t}\n\tif (labVector.x > K * Epsilon) {\n\t\ty = std::pow((labVector.x + 16) / 116, 3);\n\t} else {\n\t\ty = labVector.x / K;\n\t}\n\tif (std::pow(fz, 3) > Epsilon) {\n\t\tz = std::pow(fz, 3);\n\t} else {\n\t\tz = (116 * fz - 16) / K;\n\t}\n\treturn Color::Vector3d(x * referenceWhite.x, y * referenceWhite.y, z * referenceWhite.z);\n}\nColor::Matrix3d Color::getWorkingSpaceMatrix(float xr, float yr, float xg, float yg, float xb, float yb, const Vector3f &referenceWhite) {\n\tfloat Xr = xr / yr;\n\tfloat Yr = 1;\n\tfloat Zr = (1 - xr - yr) / yr;\n\tfloat Xg = xg / yg;\n\tfloat Yg = 1;\n\tfloat Zg = (1 - xg - yg) / yg;\n\tfloat Xb = xb / yb;\n\tfloat Yb = 1;\n\tfloat Zb = (1 - xb - yb) / yb;\n\tauto s = Matrix3d { Xr, Xg, Xb, Yr, Yg, Yb, Zr, Zg, Zb }.inverse().value() * math::vectorCast<double>(referenceWhite);\n\treturn Matrix3d { Xr * s.r, Xg * s.g, Xb * s.b, Yr * s.r, Yg * s.g, Yb * s.b, Zr * s.r, Zg * s.g, Zb * s.b };\n}\nColor::Matrix3d Color::getChromaticAdaptationMatrix(const Vector3f &sourceReferenceWhite, const Vector3f &destinationReferenceWhite) {\n\tconst Matrix3d bradfordMatrix { 0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296 };\n\tconst Matrix3d bradfordInvertedMatrix = *bradfordMatrix.inverse();\n\tauto source = bradfordMatrix * math::vectorCast<double>(sourceReferenceWhite);\n\tauto destination = bradfordMatrix * math::vectorCast<double>(destinationReferenceWhite);\n\tMatrix3d matrix;\n\tmatrix[0] = destination.x / source.x;\n\tmatrix[4] = destination.y / source.y;\n\tmatrix[8] = destination.z / source.z;\n\treturn bradfordMatrix * matrix * bradfordInvertedMatrix;\n}\nColor Color::xyzChromaticAdaptation(const Matrix3d &adaptation) const {\n\treturn adaptation * rgbVector<double>();\n}\nstatic Color::Vector3d xyzChromaticAdaptation(Color::Vector3d xyzVector, const Color::Matrix3d &adaptation) {\n\treturn adaptation * xyzVector;\n}\nconst Color::Vector3f &Color::getReference(ReferenceIlluminant illuminant, ReferenceObserver observer) {\n\treturn references[static_cast<uint8_t>(illuminant)][static_cast<uint8_t>(observer)];\n}\nReferenceIlluminant Color::getIlluminant(const std::string &illuminant) {\n\tconst struct {\n\t\tconst char *label;\n\t\tReferenceIlluminant illuminant;\n\t} illuminants[] = {\n\t\t{ \"A\", ReferenceIlluminant::A },\n\t\t{ \"C\", ReferenceIlluminant::C },\n\t\t{ \"D50\", ReferenceIlluminant::D50 },\n\t\t{ \"D55\", ReferenceIlluminant::D55 },\n\t\t{ \"D65\", ReferenceIlluminant::D65 },\n\t\t{ \"D75\", ReferenceIlluminant::D75 },\n\t\t{ \"F2\", ReferenceIlluminant::F2 },\n\t\t{ \"F7\", ReferenceIlluminant::F7 },\n\t\t{ \"F11\", ReferenceIlluminant::F11 },\n\t\t{ nullptr, ReferenceIlluminant::D50 },\n\t};\n\tfor (int i = 0; illuminants[i].label; i++) {\n\t\tif (illuminant == illuminants[i].label) {\n\t\t\treturn illuminants[i].illuminant;\n\t\t}\n\t}\n\treturn ReferenceIlluminant::D50;\n};\nReferenceObserver Color::getObserver(const std::string &observer) {\n\tconst struct {\n\t\tconst char *label;\n\t\tReferenceObserver observer;\n\t} observers[] = {\n\t\t{ \"2\", ReferenceObserver::_2 },\n\t\t{ \"10\", ReferenceObserver::_10 },\n\t\t{ nullptr, ReferenceObserver::_2 },\n\t};\n\tfor (int i = 0; observers[i].label; i++) {\n\t\tif (observer == observers[i].label) {\n\t\t\treturn observers[i].observer;\n\t\t}\n\t}\n\treturn ReferenceObserver::_2;\n}\nbool Color::isOutOfRgbGamut() const {\n\tif (rgb.red < 0 || rgb.red > 1)\n\t\treturn true;\n\tif (rgb.green < 0 || rgb.green > 1)\n\t\treturn true;\n\tif (rgb.blue < 0 || rgb.blue > 1)\n\t\treturn true;\n\treturn false;\n}\nfloat Color::distance(const Color &a, const Color &b) {\n\tauto al = a.linearRgb();\n\tauto bl = b.linearRgb();\n\treturn static_cast<float>(std::sqrt(\n\t\tstd::pow(bl.rgb.red - al.rgb.red, 2) +\n\t\tstd::pow(bl.rgb.green - al.rgb.green, 2) +\n\t\tstd::pow(bl.rgb.blue - al.rgb.blue, 2)));\n}\nfloat Color::distanceLch(const Color &a, const Color &b) {\n\tauto al = a.labToLch();\n\tauto bl = b.labToLch();\n\treturn static_cast<float>(std::sqrt(\n\t\tstd::pow((bl.lch.L - al.lch.L) / 1, 2) +\n\t\tstd::pow((bl.lch.C - al.lch.C) / (1 + 0.045 * al.lch.C), 2) +\n\t\tstd::pow((std::pow(a.lab.a - b.lab.a, 2) + std::pow(a.lab.b - b.lab.b, 2) - (bl.lch.C - al.lch.C)) / (1 + 0.015 * al.lch.C), 2)));\n}\nColor mix(const Color &a, const Color &b, float ratio) {\n\treturn (a.linearRgb() * (1.0f - ratio) + b.linearRgb() * ratio).nonLinearRgb();\n}\nbool Color::operator==(const Color &color) const {\n\tfor (auto i = 0; i < MemberCount; i++) {\n\t\tif (data[i] == 0.0f || color.data[i] == 0.0f) {\n\t\t\tif (math::abs(data[i] - color.data[i]) > 1e-10)\n\t\t\t\treturn false;\n\t\t} else if (boost::math::epsilon_difference(data[i], color.data[i]) > 50.0f)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\nbool Color::operator!=(const Color &color) const {\n\tfor (auto i = 0; i < MemberCount; i++) {\n\t\tif (data[i] == 0.0f || color.data[i] == 0.0f) {\n\t\t\tif (math::abs(data[i] - color.data[i]) > 1e-10)\n\t\t\t\treturn false;\n\t\t} else if (boost::math::epsilon_difference(data[i], color.data[i]) > 50.0f)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\nColor Color::operator*(float value) const {\n\treturn Color(data[0] * value, data[1] * value, data[2] * value, data[3] * value);\n}\nColor Color::operator/(float value) const {\n\treturn Color(data[0] / value, data[1] / value, data[2] / value, data[3] / value);\n}\nColor Color::operator+(const Color &color) const {\n\tColor result;\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tresult.data[i] = data[i] + color.data[i];\n\treturn result;\n}\nColor Color::operator-(const Color &color) const {\n\tColor result;\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tresult.data[i] = data[i] - color.data[i];\n\treturn result;\n}\nColor Color::operator*(const Color &color) const {\n\tColor result;\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tresult.data[i] = data[i] * color.data[i];\n\treturn result;\n}\nColor &Color::operator*=(const Color &color) {\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tdata[i] *= color.data[i];\n\treturn *this;\n}\nColor &Color::operator+=(const Color &color) {\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tdata[i] += color.data[i];\n\treturn *this;\n}\nfloat &Color::operator[](int index) {\n\tif (index < 0 || index >= MemberCount)\n\t\tthrow std::invalid_argument(\"index\");\n\treturn data[index];\n}\nfloat Color::operator[](int index) const {\n\tif (index < 0 || index >= MemberCount)\n\t\tthrow std::invalid_argument(\"index\");\n\treturn data[index];\n}\nColor Color::normalizeRgb() const {\n\tColor result(*this);\n\tresult.rgb.red = math::clamp(rgb.red, 0.0f, 1.0f);\n\tresult.rgb.green = math::clamp(rgb.green, 0.0f, 1.0f);\n\tresult.rgb.blue = math::clamp(rgb.blue, 0.0f, 1.0f);\n\treturn result;\n}\nColor &Color::normalizeRgbInplace() {\n\trgb.red = math::clamp(rgb.red, 0.0f, 1.0f);\n\trgb.green = math::clamp(rgb.green, 0.0f, 1.0f);\n\trgb.blue = math::clamp(rgb.blue, 0.0f, 1.0f);\n\treturn *this;\n}\nColor Color::absolute() const {\n\tColor result(*this);\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tresult.data[i] = math::abs(data[i]);\n\treturn result;\n}\nColor &Color::absoluteInplace() {\n\tfor (auto i = 0; i < Color::MemberCount; i++)\n\t\tdata[i] = math::abs(data[i]);\n\treturn *this;\n}\nconst Color &Color::getContrasting() const {\n\tauto t = rgbToLab(getReference(ReferenceIlluminant::D50, ReferenceObserver::_2), sRGBMatrix, d65d50AdaptationMatrix);\n\treturn t.lab.L > 50 ? black : white;\n}\n", "meta": {"hexsha": "45a1ecc0a4adb2afe15975775e22db64733e22ea", "size": 25285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Color.cpp", "max_stars_repo_name": "ericonr/gpick", "max_stars_repo_head_hexsha": "ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 311.0, "max_stars_repo_stars_event_min_datetime": "2015-03-26T18:38:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T07:39:30.000Z", "max_issues_repo_path": "source/Color.cpp", "max_issues_repo_name": "ericonr/gpick", "max_issues_repo_head_hexsha": "ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2015-03-27T06:05:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T23:04:30.000Z", "max_forks_repo_path": "source/Color.cpp", "max_forks_repo_name": "ericonr/gpick", "max_forks_repo_head_hexsha": "ff0a3c0c797d3d06d1b8ab257cb2e9dcca389908", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T16:40:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T22:36:47.000Z", "avg_line_length": 35.5126404494, "max_line_length": 211, "alphanum_fraction": 0.6565552699, "num_tokens": 8731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.01912403710028962, "lm_q1q2_score": 0.0075744225787260115}}
{"text": "#ifndef DART_NEURAL_DIFF_CONSTRAINT_HPP_\n#define DART_NEURAL_DIFF_CONSTRAINT_HPP_\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/collision/Contact.hpp\"\n#include \"dart/neural/NeuralConstants.hpp\"\n#include \"dart/neural/NeuralUtils.hpp\"\n#include \"dart/simulation/World.hpp\"\n\nnamespace dart {\n\nnamespace constraint {\nclass ConstrainedGroup;\nclass ConstraintBase;\nclass ContactConstraint;\n} // namespace constraint\n\nnamespace dynamics {\nclass Skeleton;\n}\n\nnamespace simulation {\nclass World;\n}\n\nnamespace neural {\nclass BackpropSnapshot;\n\nenum DofContactType\n{\n  UNSUPPORTED = 0,\n  NONE = 1,\n  VERTEX = 2,\n  FACE = 3,\n  EDGE_A = 4,\n  EDGE_B = 5,\n  SELF_COLLISION = 7,\n  SPHERE_TO_BOX = 8,\n  BOX_TO_SPHERE = 9,\n  SPHERE_A = 10,\n  SPHERE_B = 11,\n  SPHERE_TO_FACE = 12,\n  FACE_TO_SPHERE = 13,\n  SPHERE_TO_EDGE = 14,\n  EDGE_TO_SPHERE = 15,\n  SPHERE_TO_VERTEX = 16,\n  VERTEX_TO_SPHERE = 17,\n  PIPE_TO_SPHERE = 18,\n  SPHERE_TO_PIPE = 19,\n  PIPE_A = 20,\n  PIPE_B = 21,\n  PIPE_TO_VERTEX = 22,\n  VERTEX_TO_PIPE = 23,\n  PIPE_TO_EDGE = 24,\n  EDGE_TO_PIPE = 25\n};\n\nstruct EdgeData\n{\n  Eigen::Vector3s edgeAPos;\n  Eigen::Vector3s edgeADir;\n  Eigen::Vector3s edgeBPos;\n  Eigen::Vector3s edgeBDir;\n};\n\nclass DifferentiableContactConstraint\n{\n\npublic:\n  DifferentiableContactConstraint(\n      std::shared_ptr<constraint::ConstraintBase> constraint,\n      int index,\n      s_t constraintForce);\n\n  Eigen::Vector3s getContactWorldPosition();\n\n  /// This returns the normal of the contact, pointing from A to B. This IS NOT\n  /// NECESSARILY THE DIRECTION OF FORCE! If this contact constraint is a\n  /// friction constraint, then this returns the normal of the contact, and\n  /// getContactWorldForceDirection() returns the direction of the force.\n  Eigen::Vector3s getContactWorldNormal();\n\n  Eigen::Vector3s getContactWorldForceDirection();\n\n  /// This computes the force, in world space exponential coordinates, that this\n  /// contact generates\n  Eigen::Vector6s getWorldForce();\n\n  /// This returns the nature of the contact, whether it's a face-vertex, or a\n  /// vertex-face, or an edge-edge, or something else. This is relevant because\n  /// we need to know in order to accurately estimate how the contact position\n  /// and normal will change as we perturb skeletons by small amounts.\n  collision::ContactType getContactType();\n\n  collision::Contact& getContact();\n\n  /// This figures out what type of contact this skeleton is involved in.\n  DofContactType getDofContactType(dynamics::DegreeOfFreedom* dof);\n\n  /// This analytically computes a column of the A_c matrix just for this\n  /// skeleton.\n  Eigen::VectorXs getConstraintForces(std::shared_ptr<dynamics::Skeleton> skel);\n\n  /// This analytically computes a column of the A_c matrix for this set of\n  /// skeletons.\n  Eigen::VectorXs getConstraintForces(\n      simulation::World* world, std::vector<std::string> skelNames);\n\n  /// This analytically computes a column of the A_c matrix, for this contact\n  /// constraint, across the whole world by concatenating the result for each\n  /// skeleton together into a single vector.\n  Eigen::VectorXs getConstraintForces(simulation::World* world);\n\n  /// Returns the gradient of the contact position with respect to the\n  /// specified dof of this skeleton\n  Eigen::Vector3s getContactPositionGradient(dynamics::DegreeOfFreedom* dof);\n\n  /// Returns the gradient of the contact normal with respect to the\n  /// specified dof of this skeleton\n  Eigen::Vector3s getContactNormalGradient(dynamics::DegreeOfFreedom* dof);\n\n  /// Returns the gradient of the contact force with respect to the\n  /// specified dof of this skeleton\n  Eigen::Vector3s getContactForceGradient(dynamics::DegreeOfFreedom* dof);\n\n  /// Returns the gradient of the full 6d twist force\n  Eigen::Vector6s getContactWorldForceGradient(dynamics::DegreeOfFreedom* dof);\n\n  /// Returns the gradient of the screw axis with respect to the rotate dof\n  Eigen::Vector6s getScrewAxisForPositionGradient(\n      dynamics::DegreeOfFreedom* screwDof,\n      dynamics::DegreeOfFreedom* rotateDof);\n\n  /// Returns the gradient of the screw axis with respect to the rotate dof\n  Eigen::Vector6s getScrewAxisForForceGradient(\n      dynamics::DegreeOfFreedom* screwDof,\n      dynamics::DegreeOfFreedom* rotateDof);\n\n  /// Returns the gradient of the screw axis with respect to the rotate dof\n  ///\n  /// Unlike its sibling, getScrewAxisForForceGradient(), this allows passing\n  /// in values that are otherwise repeatedly computed.\n  Eigen::Vector6s getScrewAxisForForceGradient_Optimized(\n      dynamics::DegreeOfFreedom* screwDof,\n      dynamics::DegreeOfFreedom* rotateDof,\n      const Eigen::Vector6s& axisWorldTwist);\n\n  /// This is the analytical Jacobian for the contact position\n  math::LinearJacobian getContactPositionJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// This is the analytical Jacobian for the contact position\n  math::LinearJacobian getContactPositionJacobian(\n      std::shared_ptr<dynamics::Skeleton> skel);\n\n  /// This is the analytical Jacobian for the contact normal\n  math::LinearJacobian getContactForceDirectionJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// This is the analytical Jacobian for the contact normal\n  math::LinearJacobian getContactForceDirectionJacobian(\n      std::shared_ptr<dynamics::Skeleton> skel);\n\n  /// This is the analytical Jacobian for the force (in exponential coordinates,\n  /// in the world frame) generated by this contact. This is measuring how the\n  /// force (in world space) changes as a result of moving the contact position\n  /// and normal as a result of moving the joints of the skeletons in the world.\n  math::Jacobian getContactForceJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// This is the analytical Jacobian for the force (in exponential coordinates,\n  /// in the world frame) generated by this contact. This is measuring how the\n  /// force (in world space) changes as a result of moving the contact position\n  /// and normal as a result of moving the joints of the skeletons passed in.\n  math::Jacobian getContactForceJacobian(\n      std::shared_ptr<dynamics::Skeleton> skel);\n\n  /// This gets the constraint force for a given DOF\n  s_t getConstraintForce(dynamics::DegreeOfFreedom* dof);\n\n  /// This gets the gradient of constraint force at this joint with respect to\n  /// another joint\n  s_t getConstraintForceDerivative(\n      dynamics::DegreeOfFreedom* dof, dynamics::DegreeOfFreedom* wrt);\n\n  /// This returns an analytical Jacobian relating the skeletons that this\n  /// contact touches.\n  const Eigen::MatrixXs& getConstraintForcesJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// This computes and returns the analytical Jacobian relating how changes in\n  /// the positions of wrt's DOFs changes the constraint forces on skel.\n  Eigen::MatrixXs getConstraintForcesJacobian(\n      std::shared_ptr<dynamics::Skeleton> skel,\n      std::shared_ptr<dynamics::Skeleton> wrt);\n\n  /// This computes and returns the analytical Jacobian relating how changes in\n  /// the positions of wrt's DOFs changes the constraint forces on all the\n  /// skels.\n  Eigen::MatrixXs getConstraintForcesJacobian(\n      std::vector<std::shared_ptr<dynamics::Skeleton>> skels,\n      std::shared_ptr<dynamics::Skeleton> wrt);\n\n  /// This computes and returns the analytical Jacobian relating how changes in\n  /// the positions of any of the DOFs changes the constraint forces on all the\n  /// skels.\n  Eigen::MatrixXs getConstraintForcesJacobian(\n      std::shared_ptr<simulation::World> world,\n      std::vector<std::shared_ptr<dynamics::Skeleton>> skels);\n\n  /// This returns the skeletons that this contact constraint interacts with.\n  const std::vector<std::shared_ptr<dynamics::Skeleton>>& getSkeletons();\n\n  /////////////////////////////////////////////////////////////////////////////////////\n  // Testing\n  /////////////////////////////////////////////////////////////////////////////////////\n\n  /// The linear Jacobian for the contact position\n  math::LinearJacobian bruteForceContactPositionJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// The linear Jacobian for the contact normal\n  math::LinearJacobian bruteForceContactForceDirectionJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// This is the brute force version of getWorldForceJacobian()\n  math::Jacobian bruteForceContactForceJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// This is the brute force version of getConstraintForcesJacobian()\n  Eigen::MatrixXs bruteForceConstraintForcesJacobian(\n      std::shared_ptr<simulation::World> world);\n\n  /// Just for testing: This analytically estimates the way the contact position\n  /// will change if we perturb the `dofIndex`'th DOF of `skel` by `eps`.\n  Eigen::Vector3s estimatePerturbedContactPosition(\n      std::shared_ptr<dynamics::Skeleton> skel, int dofIndex, s_t eps);\n\n  /// Just for testing: This analytically estimates the way the contact normal\n  /// will change if we perturb the `dofIndex`'th DOF of `skel` by `eps`.\n  Eigen::Vector3s estimatePerturbedContactNormal(\n      std::shared_ptr<dynamics::Skeleton> skel, int dofIndex, s_t eps);\n\n  /// Just for testing: This analytically estimates the way the contact normal\n  /// will change if we perturb the `dofIndex`'th DOF of `skel` by `eps`.\n  Eigen::Vector3s estimatePerturbedContactForceDirection(\n      std::shared_ptr<dynamics::Skeleton> skel, int dofIndex, s_t eps);\n\n  /// Just for testing: This analytically estimates how edges will move under a\n  /// perturbation\n  EdgeData estimatePerturbedEdges(\n      std::shared_ptr<dynamics::Skeleton> skel, int dofIndex, s_t eps);\n\n  /// Just for testing: returns the edges, if this is an edge-edge collision,\n  /// otherwise 0s\n  EdgeData getEdges();\n\n  /// Just for testing: Returns the gradient of the edge data for this collision\n  /// (0s if this isn't an edge-edge collision)\n  EdgeData getEdgeGradient(dynamics::DegreeOfFreedom* dof);\n\n  /// Just for testing: This analytically estimates how a screw axis will move\n  /// when rotated by another screw.\n  Eigen::Vector6s estimatePerturbedScrewAxisForPosition(\n      dynamics::DegreeOfFreedom* axis,\n      dynamics::DegreeOfFreedom* rotate,\n      s_t eps);\n\n  /// Just for testing: This analytically estimates how a screw axis will move\n  /// when rotated by another screw.\n  Eigen::Vector6s estimatePerturbedScrewAxisForForce(\n      dynamics::DegreeOfFreedom* axis,\n      dynamics::DegreeOfFreedom* rotate,\n      s_t eps);\n\n  /// Just for testing: This lets the world record what index this\n  /// constraint is at, so that we can recover the analagous constraint from\n  /// another forward pass for finite-differencing.\n  void setOffsetIntoWorld(int offset, bool isUpperBoundConstraint);\n\n  /// Just for testing: This runs a full timestep to get the way the contact\n  /// position will change if we perturb the `dofIndex`'th DOF of `skel` by\n  /// `eps`.\n  Eigen::Vector3s bruteForcePerturbedContactPosition(\n      std::shared_ptr<simulation::World> world,\n      std::shared_ptr<dynamics::Skeleton> skel,\n      int dofIndex,\n      s_t eps);\n\n  /// Just for testing: This runs a full timestep to get the way the contact\n  /// normal will change if we perturb the `dofIndex`'th DOF of `skel` by\n  /// `eps`.\n  Eigen::Vector3s bruteForcePerturbedContactNormal(\n      std::shared_ptr<simulation::World> world,\n      std::shared_ptr<dynamics::Skeleton> skel,\n      int dofIndex,\n      s_t eps);\n\n  /// Just for testing: This runs a full timestep to get the way the contact\n  /// force direction will change if we perturb the `dofIndex`'th DOF of `skel`\n  /// by `eps`.\n  Eigen::Vector3s bruteForcePerturbedContactForceDirection(\n      std::shared_ptr<simulation::World> world,\n      std::shared_ptr<dynamics::Skeleton> skel,\n      int dofIndex,\n      s_t eps);\n\n  /// Just for testing: This perturbs the world position of a skeleton to read a\n  /// screw axis will move when rotated by another screw.\n  Eigen::Vector6s bruteForceScrewAxisForPosition(\n      dynamics::DegreeOfFreedom* axis,\n      dynamics::DegreeOfFreedom* rotate,\n      s_t eps);\n\n  /// Just for testing: This perturbs the world position of a skeleton to read a\n  /// screw axis will move when rotated by another screw.\n  Eigen::Vector6s bruteForceScrewAxisForForce(\n      dynamics::DegreeOfFreedom* axis,\n      dynamics::DegreeOfFreedom* rotate,\n      s_t eps);\n\n  /// Just for testing: This perturbs the world position of a skeleton  to read\n  /// how edges will move.\n  EdgeData bruteForceEdges(\n      std::shared_ptr<simulation::World> world,\n      std::shared_ptr<dynamics::Skeleton> skel,\n      int dofIndex,\n      s_t eps);\n\n  /// Return the index into the contact that this constraint represents. If it's\n  /// >0, then this is a frictional constraint.\n  int getIndexInConstraint();\n\n  /// This returns the axis for the specified dof index\n  static Eigen::Vector6s getWorldScrewAxisForPosition(\n      std::shared_ptr<dynamics::Skeleton> skel, int dofIndex);\n\n  /// This returns the axis for the specified dof index\n  static Eigen::Vector6s getWorldScrewAxisForPosition(\n      dynamics::DegreeOfFreedom* dof);\n\n  /// This returns the axis for the specified dof index which, when dotted with\n  /// force, calculates the torque on this joint. THIS IS NOT THE SAME AS\n  /// getWorldScrewAxisForPosition(), because of FreeJoints and BallJoints.\n  static Eigen::Vector6s getWorldScrewAxisForForce(\n      std::shared_ptr<dynamics::Skeleton> skel, int dofIndex);\n\n  /// This returns the axis for the specified dof index which, when dotted with\n  /// force, calculates the torque on this joint. THIS IS NOT THE SAME AS\n  /// getWorldScrewAxisForPosition(), because of FreeJoints and BallJoints.\n  static Eigen::Vector6s getWorldScrewAxisForForce(\n      dynamics::DegreeOfFreedom* dof);\n\n  /// This returns the constraint that's at our same location in the snapshot.\n  /// This assumes that `mOffsetIntoWorld` and `mIsUpperBoundConstraint` are\n  /// set.\n  std::shared_ptr<DifferentiableContactConstraint> getPeerConstraint(\n      std::shared_ptr<neural::BackpropSnapshot> snapshot);\n\n  /// This returns 1.0 by default, 0.0 if this constraint doesn't effect the\n  /// specified DOF, and -1.0 if the constraint effects this dof negatively.\n  /// Pretty much only public for testing\n  s_t getControlForceMultiple(dynamics::DegreeOfFreedom* dof);\n\npublic:\n  /// Returns true if this dof moves this body node\n  bool isParent(\n      const dynamics::DegreeOfFreedom* dof, const dynamics::BodyNode* node);\n\n  /// Returns true if this dof moves the other dof's screw axis\n  bool isParent(\n      const dynamics::DegreeOfFreedom* parent,\n      const dynamics::DegreeOfFreedom* child);\n\n  friend class BackpropSnapshot;\n\nprotected:\n  std::shared_ptr<constraint::ConstraintBase> mConstraint;\n  std::shared_ptr<constraint::ContactConstraint> mContactConstraint;\n  std::shared_ptr<collision::Contact> mContact;\n  std::vector<std::string> mSkeletons;\n  std::vector<Eigen::VectorXs> mSkeletonOriginalPositions;\n  s_t mConstraintForce;\n\n  bool mWorldConstraintJacCacheDirty;\n  Eigen::MatrixXs mWorldConstraintJacCache;\n\n  int mIndex;\n\n  /// This allows us to locate this constraint in the world arrays. This value\n  /// is not guaranteed to be set, but must be set before calling any of the\n  /// brute force methods!\n  int mOffsetIntoWorld;\n  /// This allows us to locate this constraint in the world arrays. If true,\n  /// we're in the upper bound array. Otherwise, we're clamping. This value\n  /// is not guaranteed to be set, but must be set before calling any of the\n  /// brute force methods!\n  bool mIsUpperBoundConstraint;\n};\n} // namespace neural\n} // namespace dart\n\n#endif", "meta": {"hexsha": "bb72782317e750f3c72d9777cca00a5ea8abdc8b", "size": 15796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/neural/DifferentiableContactConstraint.hpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "dart/neural/DifferentiableContactConstraint.hpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/neural/DifferentiableContactConstraint.hpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 38.6210268949, "max_line_length": 87, "alphanum_fraction": 0.7324006077, "num_tokens": 3877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.01615283470373692, "lm_q1q2_score": 0.007572297502554967}}
{"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 NSGA2_HPP_\n#define NSGA2_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.hpp>\n#include <sferes/ea/common.hpp>\n#include <sferes/ea/crowd.hpp>\n\nnamespace sferes {\n  namespace ea {\n    // Main class\n    SFERES_EA(Nsga2, Ea) {\n    public:\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      void random_pop() {\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()),\n                        random<crowd::Indiv<Phen> >(init_pop));\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      void epoch() {\n        this->_pop.clear();\n        _pareto_front.clear();\n        _selection (_parent_pop, _child_pop);\n        parallel::p_for(parallel::range_t(0, _child_pop.size()),\n                        mutate<crowd::Indiv<Phen> >(_child_pop));\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        _apply_modifier(_mixed_pop);\n#ifndef NDEBUG\n        BOOST_FOREACH(indiv_t& ind, _mixed_pop)\n        for (size_t i = 0; i < ind->fit().objs().size(); ++i) {\n          assert(!std::isnan(ind->fit().objs()[i]));\n        }\n#endif\n        _fill_nondominated_sort(_mixed_pop, _parent_pop);\n        _mixed_pop.clear();\n        _child_pop.clear();\n\n        _convert_pop(_parent_pop, this->_pop);\n\n        assert(_parent_pop.size() == Params::pop::size);\n        assert(_pareto_front.size() <= Params::pop::size * 2);\n        assert(_mixed_pop.size() == 0);\n        //\tassert(_child_pop.size() == 0);\n        assert(this->_pop.size() == Params::pop::size);\n      }\n      const std::vector<boost::shared_ptr<Phen> >& pareto_front() const {\n        return _pareto_front;\n      }\n      const pop_t& mixed_pop() {\n        return _mixed_pop;\n      }\n      const pop_t& parent_pop() {\n        return _parent_pop;\n      }\n      const pop_t& child_pop() {\n        return _child_pop;\n      }\n    protected:\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 _update_pareto_front(const front_t& fronts) {\n        _convert_pop(fronts.front(), _pareto_front);\n      }\n\n      void _convert_pop(const pop_t& pop1,\n                        std::vector<boost::shared_ptr<Phen> > & pop2) {\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        this->_eval.eval(pop, 0, pop.size());\n      }\n\n      void _apply_modifier(pop_t& pop) {\n        _convert_pop(pop, this->_pop);\n        this->apply_modifier();\n      }\n      void _fill_nondominated_sort(pop_t& mixed_pop, pop_t& new_pop) {\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          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          std::sort(fronts[i].begin(), fronts[i].end(), crowd::compare_crowd());\n          for (size_t k = 0; k < size ; ++k) {\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        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        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          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        // if (i1->rank() < i2->rank())\n        //   return i1;\n        // else if (i2->rank() > i1->rank())\n        //   return i2;\n        // else if (misc::flip_coin())\n        //   return i1;\n        // else\n        //   return i2;\n\n        int flag = fit::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\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        }\n#endif\n        dom_sort(pop, fronts, 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      void _assign_rank(pop_t& pop) {\n        int rank = 0;\n        fit::compare_pareto comp;\n        assert(pop.size());\n        std::sort(pop.begin(), pop.end(), comp);\n        pop[0]->set_rank(0);\n        for (unsigned i = 1; i < pop.size(); ++i) {\n          assert(comp(pop[i-1], pop[i]) || comp.eq(pop[i -1], pop[i]));\n          if (comp(pop[i-1], pop[i]))\n            ++rank;\n          pop[i]->set_rank(rank);\n        }\n      }\n\n    };\n  }\n}\n#endif\n\n\n", "meta": {"hexsha": "738302155ba3ec1b4dce742d109c4fceebec3f76", "size": 9277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sferes/sferes/ea/nsga2.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/ea/nsga2.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/ea/nsga2.hpp", "max_forks_repo_name": "Evolving-AI-Lab/innovation-engine", "max_forks_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-11-15T01:52:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-11T23:42:58.000Z", "avg_line_length": 33.6123188406, "max_line_length": 82, "alphanum_fraction": 0.585857497, "num_tokens": 2498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.028436031501050025, "lm_q1q2_score": 0.007560585508580478}}
{"text": "// \n//  Copyright © 2015 Claus Christmann <hcc |ä| gatech.edu>.\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 \"vroniinterface.h\"\n\n/* VRONI header files\n *   These header files are part of the VRONI source code\n *   NOTE: The order of inlcusion does matter!\n */\n#include <vroni.h>\n\n#include <boost/geometry/algorithms/envelope.hpp> \n#include <boost/geometry/algorithms/reverse.hpp> \n#include <QtCore/QHash>\n#include <QtCore/QDebug>\n\n#include <unordered_map>\n\n#include \"Graphics/arrowitem.h\"\n\nVroniInterface::VroniInterface()\n{\n  // from VRONI docu:\n  // call this routine once prior calling any other routine of VRONI\n  VRONI::API_InitializeProgram();\n  \n  VRONI::quiet = true; // suppress printfs\n}\n\nVroniInterface::~VroniInterface()\n{\n  // from VRONI docu:\n  // call this routine to release all memory allocated by VRONI\n  VRONI::API_TerminateProgram();\n}\n\nvoid VroniInterface::resetAll(void )\n{\n  // call VRONI's API funtion\n  VRONI::API_ResetAll();\n  \n  // mark the (now erased) VD/DT data as not current\n  m_vdIsCurrent = false;\n  m_isPointSite = true;\n}\n\n\nvoid VroniInterface::setVroniSiteData(const Geometry::Polygon_2D& complexPolygon)\n{\n  resetAll(); // reset VRONI's data...\n  m_isPointSite = false;\n  \n  namespace bg = boost::geometry;\n  \n  // get the containing box of the polygon\n  bg::model::box<Geometry::Point_2D> box;\n  bg::envelope(complexPolygon,box);\n  \n  // set the scaling box from that\n  auto x_min = box.min_corner().get<0>();\n  auto y_min = box.min_corner().get<1>();\n  auto x_max = box.max_corner().get<0>();\n  auto y_max = box.max_corner().get<1>();\n \n  m_scalingBox = ScalingBox(x_min,y_min,x_max,y_max); //NOTE: Warning, this could include an implicit conversion to double!\n  \n \n  // add the outer polygon\n  addElementToSite( complexPolygon.outer());\n  \n  // add the inner holes, i.e. the obstacles\n  auto obstacleList =  complexPolygon.inners();\n  for(Geometry::Polygon_2D::ring_type const & ring : obstacleList)\n  {\n    addElementToSite(ring);\n  }\n  \n  \n  boundingBox();\n}\n\nvoid VroniInterface::setVroniSiteData(const Geometry::Polygon_2D& boundary, const std::unordered_map<ElementId, Obstacle >& obstacleData)\n{\n  resetAll(); // reset VRONI's data...\n  m_isPointSite = false;\n  \n//   qDebug() << \"ENTERING setVroniSiteData\";\n//   printVroniSiteData();\n  \n  namespace bg = boost::geometry;\n  \n  // get the containing box of the polygon\n  bg::model::box<Geometry::Point_2D> box;\n  bg::envelope(boundary,box);\n  \n  // set the scaling box from that\n  auto x_min = box.min_corner().get<0>();\n  auto y_min = box.min_corner().get<1>();\n  auto x_max = box.max_corner().get<0>();\n  auto y_max = box.max_corner().get<1>();\n \n  m_scalingBox = ScalingBox(x_min,y_min,x_max,y_max); //NOTE: Warning, this could include an implicit conversion to double!\n  \n \n  // add the outer boundary to the site and add the shape identifier \"0\"\n  int index = 0;\n  \n  Geometry::Point_2D centroid;\n  boost::geometry::centroid(boundary.outer(),centroid);\n  shapeCentroidMap.clear();\n  shapeCentroidMap[index] = centroid;\n  \n  addElementToSite( boundary.outer(), index++);\n  \n  // add the obstacles to the site_file\n  for( auto& pair : obstacleData  ) \n  {\n    Obstacle const& obstacle = pair.second;\n    \n    //NOTE: we need to make a copy of the outer obstacle shape so that  we can \n    // use bg::reverse. This is important so that the boundary and the obstacle \n    // shapes have different orientations so that VRONI can correctly determined\n    // \"holes\" and the \"inside\" of the arena.\n    Geometry::Polygon_2D::ring_type tempRing;\n    bg::assign(tempRing,obstacle.shape().outer());\n    bg::reverse(tempRing);\n    \n    Geometry::Point_2D centroid;\n    boost::geometry::centroid(tempRing,centroid);\n    shapeCentroidMap[index] = centroid;\n\n    addElementToSite( tempRing, index++ );\n  }\n  \n  \n  // update the bounding box\n  boundingBox();\n  \n}\n\nvoid VroniInterface::setVroniSiteData(const Geometry::MultiPoint_2D& mulitPoint)\n{\n  resetAll(); // reste VRONI's internal site data\n  m_isPointSite = true;\n  \n  namespace bg = boost::geometry;\n  \n  // get the containing box of the point set\n  boost::geometry::model::box<Geometry::Point_2D> box;\n  boost::geometry::envelope(mulitPoint,box);\n\n  // set the scaling box from that\n  auto x_min = box.min_corner().get<0>();\n  auto y_min = box.min_corner().get<1>();\n  auto x_max = box.max_corner().get<0>();\n  auto y_max = box.max_corner().get<1>();\n \n  m_scalingBox = ScalingBox(x_min,y_min,x_max,y_max); //NOTE: Warning, this could include an implicit conversion to double!\n  \n  // add the points to the internal VRONI site data set\n  addElementToSite(mulitPoint);\n\n  boundingBox();\n  \n}\n\n\nvoid VroniInterface::addElementToSite(const Geometry::Polygon_2D::ring_type& ring, VRONI::eas_type data)\n{\n  using namespace VRONI;\n  \n  m_isPointSite = false; //NOTE: this function adds non-points to the VRONI site\n  \n  // get the number of edges of the geometry\n  std::size_t num_edges = boost::geometry::num_points(ring) - 1; // this assumes that the ring is closed!\n  \n  // preallocate a VRONI in_segs array to hold the edges' data\n  in_segs* edges = new in_segs[num_edges];\n  \n  // populate the edges array\n  int i=0;\n  for( auto it_point=ring.begin() ; it_point !=--(ring.end()); /* no action */)\n  {\n    edges[i].x1 = boost::geometry::get<0>(*it_point); //NOTE: Warning: this could cause an implicit conversion\n    edges[i].y1 = boost::geometry::get<1>(*it_point); //NOTE: Warning: this could cause an implicit conversion\n    ++it_point;\n    edges[i].x2 = boost::geometry::get<0>(*it_point); //NOTE: Warning: this could cause an implicit conversion\n    edges[i].y2 = boost::geometry::get<1>(*it_point); //NOTE: Warning: this could cause an implicit conversion\n    \n    edges[i].ext_appl = data;\n    ++i;\n  }\n\n  // store whether or not VRONI determined the API input to be new or not\n  boolean new_input = false; \n\n  // Call the VRONI API to add the edge segments representing the QPolygon\n  API_ArrayInput(\n    0,nullptr,   // not adding any points\n    num_edges, edges,   // adding num_edges segments, stored in/at edges\n    0,nullptr,     // not adding any arcs\n    &new_input    // check if VRONI determines this is a new input\n  );\n  \n  if( new_input )\n  {\n    // reset the Voronoi diagram tracker\n    m_vdIsCurrent = false;\n  }\n  \n  // free the allocated memory temporarily holding the edges.\n  // VRONIs API_ArrayInput performs an internal copy-by-value, hence this is \n  // safe\n  delete[] edges;\n}\n\nvoid VroniInterface::addElementToSite(const Geometry::Point_2D& point)\n{\n  using namespace VRONI;\n  \n  // get/set the number of points to add\n  int num_points = 1;\n\n  // preallocate a VRONI in_pnts array to hold the points' data\n  in_pnts * points = new in_pnts[num_points];\n  \n  // populate the points array\n  int i = 0;\n  {\n    points[i].x1 =  boost::geometry::get<0>(point);\n    points[i].y1 =  boost::geometry::get<1>(point);\n  }\n  \n  \n  // store whether or not VRONI determined the API input to be new or not\n  boolean new_input = false; \n  \n  // Call the VRONI API to add the edge segments representing the QPolygon\n  API_ArrayInput(\n    num_points, points,   // adding num_points elements, stored in/at points\n    0,nullptr,   // not adding any edges\n    0,nullptr,     // not adding any arcs\n    &new_input    // check if VRONI determines this is a new input\n  );\n  \n  if( new_input )\n  {\n    // reset the Voronoi diagram tracker\n    m_vdIsCurrent = false;\n  }\n  \n  // free the allocated memory temporarily holding the edges.\n  // VRONIs API_ArrayInput performs an internal copy-by-value, hence this is \n  // safe\n  delete[] points;\n  \n}\n\nvoid VroniInterface::addElementToSite(const Geometry::MultiPoint_2D& mulitPoint)\n{\n  using namespace VRONI;\n  \n  // get/set the number of points to add\n  int num_points = boost::geometry::num_geometries(mulitPoint);\n\n  // preallocate a VRONI in_pnts array to hold the points' data\n  in_pnts * points = new in_pnts[num_points];\n  \n  // populate the points array\n  int i = 0;\n  for( auto & point : mulitPoint )\n  {\n    points[i].x1 =  boost::geometry::get<0>(point);\n    points[i].y1 =  boost::geometry::get<1>(point);\n    ++i;\n  }\n  \n  \n  // store whether or not VRONI determined the API input to be new or not\n  boolean new_input = false; \n  \n  // Call the VRONI API to add the edge segments representing the QPolygon\n  API_ArrayInput(\n    num_points, points,   // adding num_points elements, stored in/at points\n    0,nullptr,   // not adding any edges\n    0,nullptr,     // not adding any arcs\n    &new_input    // check if VRONI determines this is a new input\n  );\n  \n  if( new_input )\n  {\n    // reset the Voronoi diagram tracker\n    m_vdIsCurrent = false;\n  }\n  \n  // free the allocated memory temporarily holding the edges.\n  // VRONIs API_ArrayInput performs an internal copy-by-value, hence this is \n  // safe\n  delete[] points;\n}\n\n#ifdef WITH_GRAPHICS\n\nQGraphicsItemGroup* VroniInterface::getSiteGraphics()\n{\n  auto group = new QGraphicsItemGroup;\n  \n  QColor pntColor = Qt::red;    /// PNT site color\n  QColor segColor = Qt::blue;   /// SEG site color\n  QColor arcColor = Qt::green;  /// ARC site color\n  \n//   using LineGraphics = QGraphicsLineItem;\n  using LineGraphics = Graphics_2D::Arrow;\n  QPen segPen = QPen(segColor);\n    \n  using ArcGraphics = QGraphicsEllipseItem;\n  QPen arcPen = QPen(arcColor);\n  const bool approxArcsByLines = true;\n  const bool drawArcCenter = true;\n    \n  using VertexGraphics = QGraphicsEllipseItem;\n  QPen pntPen = QPen(pntColor);\n  constexpr qreal radius = 4.0;\n\n  // add segments\n  for( int i = 0; i<VRONI::num_segs; ++i)\n  {\n    VRONI::seg* vr_seg  = VRONI::segs+i;\n    \n    Geometry::Point_2D tail;\n    get_pnt_coords(tail,vr_seg->i1);\n    \n    Geometry::Point_2D head;\n    get_pnt_coords(head,vr_seg->i2);\n   \n    auto line = new LineGraphics(tail.x(), tail.y(),\n                                 head.x(), head.y());  \n    \n    line->setPen(segPen);\n    group->addToGroup(line);\n  }\n  \n  // add arcs\n  for(int i = 0; i<VRONI::num_arcs; ++i)\n  {\n    VRONI::arc* vr_arc = VRONI::arcs+i; \n    \n    if( approxArcsByLines )\n    {\n      Geometry::Point_2D tail;\n      get_pnt_coords(tail,vr_arc->i1);\n      \n      Geometry::Point_2D head;\n      get_pnt_coords(head,vr_arc->i2);\n    \n      \n      if( boost::geometry::distance(tail,head) > ZERO )\n      {\n        auto line = new LineGraphics(tail.x(), tail.y(),\n                                  head.x(), head.y());  \n        group->addToGroup(line);     \n      }\n    }\n    \n    if( drawArcCenter )\n    {\n      Geometry::Point_2D center(vr_arc->c.x, vr_arc->c.y);\n      if(VRONI::scale_data)\n      { center = unScale(center); }\n        \n      auto point = new VertexGraphics(center.x()-radius/2, center.y()-radius/2,\n                                      radius,radius);\n    }\n    \n  }\n     \n  // add points  \n  for( int i = 0; i<VRONI::num_pnts; ++i )\n  {\n    Geometry::Point_2D point;\n    get_pnt_coords(point, i);\n    \n    auto vertex = new VertexGraphics(point.x()-radius/2, point.y()-radius/2,\n                                      radius,radius);\n    vertex->setPen(pntPen);\n    group->addToGroup(vertex);\n  }\n      \n  printVroniSiteData();\n      \n  return group;\n}\n\nQGraphicsItemGroup* VroniInterface::getNodeGraphics()\n{\n  auto group = new QGraphicsItemGroup;\n  \n  QColor nodeColor = Qt::darkRed;    \n  \n  int num_nodes = VRONI::GetNumberOfNodes();\n  \n  \n  using VertexGraphics = QGraphicsEllipseItem;\n  QPen nodePen = QPen(nodeColor);\n  constexpr qreal radius = 4.0;\n  \n  // add nodes\n  for( int i = 0; i<num_nodes; ++i )\n  {\n    Geometry::Point_2D node;\n    get_node_coords(node,i);\n   \n    auto vertex = new VertexGraphics(node.x()-radius/2, node.y()-radius/2,\n                                      radius,radius);\n    vertex->setPen(nodePen);\n    group->addToGroup(vertex);\n   \n  }\n  \n  return group;\n}\n\nQGraphicsItemGroup* VroniInterface::getEdgeGraphics()\n{\n  auto group = new QGraphicsItemGroup;\n  \n  QColor edgeColor = Qt::darkGreen;\n  \n  int num_edges = VRONI::GetNumberOfEdges();\n  \n    \n  using LineGraphics = Graphics_2D::Arrow;\n//   using LineGraphics = QGraphicsLineItem;\n  QPen edgePen = QPen(edgeColor);\n  edgePen.setWidthF(0);\n  \n  // add edges\n  for( int i=0; i< num_edges; ++i)\n  {\n    VRONI::edge* vr_edge  = VRONI::edges+i;\n    \n    Geometry::Point_2D tail;\n    get_node_coords(tail,vr_edge->n1);\n    \n    Geometry::Point_2D head;\n    get_node_coords(head,vr_edge->n2);\n   \n    \n    if( boost::geometry::distance(tail,head) > ZERO ) // NOTE: ZERO is a VRONI #define\n    {\n      auto line = new LineGraphics(tail.x(), tail.y(),\n                                  head.x(), head.y());  \n      \n      line->setPen(edgePen);\n      group->addToGroup(line);\n    }\n  }\n  \n  return group;\n}\n\n#endif // WITH_GRAPHICS\n\n\nSimple2dGraph::Graph VroniInterface::createSiteShapeAssociationGraph()\n{\n  using Graph = Simple2dGraph::Graph;\n  Graph graph;\n  \n  if( !m_vdIsCurrent )\n  { \n    qDebug() << \"Thr Voronoi diagram is not current. Can't create the site-to-shape association graph.\";\n    return graph;\n  }\n  \n  \n  auto vIndexMap  = boost::get(boost::vertex_index,graph); ///< Vertex_Index_Map\n  auto vPosMap    = boost::get(boost::vertex_position_2D, graph); ///< Vertex_Position2d_Map \n \n  QHash<int,Graph::vertex_descriptor> shapeVertexHash;\n  \n  // create the vertices representing the shapes (as they won't be itner connected)\n  for( int i=0; i<shapeCentroidMap.size(); ++i)\n  {\n    Graph::vertex_descriptor shapeVertex = boost::add_vertex(graph);\n        shapeVertexHash[i]=shapeVertex;\n  \n    vPosMap[shapeVertex] = shapeCentroidMap[i];\n  }\n  \n  QHash<int,Graph::vertex_descriptor> segSiteHash;\n  \n  // create the vertices representing the SEG sites \n  for( int i=0; i<VRONI::num_segs; ++i)\n  {\n    Graph::vertex_descriptor segVertex = boost::add_vertex(graph);\n    segSiteHash[i]=segVertex;\n    \n    VRONI::seg* vr_seg = VRONI::segs+i;\n    \n    Geometry::Point_2D tail;\n    get_pnt_coords(tail,vr_seg->i1);\n    \n    Geometry::Point_2D head;\n    get_pnt_coords(head,vr_seg->i2);\n    \n    vPosMap[segVertex] = Geometry::midpoint(head,tail);\n    \n    boost::add_edge(segVertex,shapeVertexHash[vr_seg->ext_appl],graph);\n    \n  }\n    \n  \n  // get the PNT-to-shape map \n  QHash<int,int> pntShapeMap  = getPntToShapeMap();\n    \n  QHash<int,Graph::vertex_descriptor> pntSiteHash;  \n  \n  // create the vertices representing the PNT sites \n  for( int i=0; i<VRONI::num_pnts;++i )\n  {\n    Graph::vertex_descriptor pntVertex = boost::add_vertex(graph);\n    pntSiteHash[i]=pntVertex;\n    \n    Geometry::Point_2D point;\n    get_pnt_coords(point,i);\n    \n    vPosMap[pntVertex] = point;\n    \n    boost::add_edge(pntVertex,shapeVertexHash[pntShapeMap[i]],graph);\n  }\n  \n  return graph;\n    \n}\n\nSimple2dGraph::Graph VroniInterface::createEdgeSiteAssociationGraph()\n{\n  using Graph = Simple2dGraph::Graph;\n  Graph graph;\n  \n  auto vIndexMap  = boost::get(boost::vertex_index,graph); ///< Vertex_Index_Map\n  auto vPosMap    = boost::get(boost::vertex_position_2D, graph); ///< Vertex_Position2d_Map \n \n  QHash<int,Graph::vertex_descriptor> pntSiteHash;\n  QHash<int,Graph::vertex_descriptor> segSiteHash;\n  QHash<int,Graph::vertex_descriptor> arcSiteHash;\n  QHash<int,Graph::vertex_descriptor> vdEdgeHash;\n  \n  // first, create the vertices representing the sites (as they won't be connected)\n  \n  for( int i=0; i<VRONI::num_pnts;++i )\n  {\n    Graph::vertex_descriptor vertex = boost::add_vertex(graph);\n    pntSiteHash[i]=vertex;\n    \n    Geometry::Point_2D point;\n    get_pnt_coords(point,i);\n    \n    vPosMap[vertex] = point;\n  }\n  \n  for( int i=0; i<VRONI::num_segs; ++i)\n  {\n    Graph::vertex_descriptor vertex = boost::add_vertex(graph);\n    segSiteHash[i]=vertex;\n    \n    VRONI::seg* vr_seg = VRONI::segs+i;\n    \n    Geometry::Point_2D tail;\n    get_pnt_coords(tail,vr_seg->i1);\n    \n    Geometry::Point_2D head;\n    get_pnt_coords(head,vr_seg->i2);\n    \n    vPosMap[vertex] = Geometry::midpoint(head,tail);\n  }\n  \n  for( int i=0; i<VRONI::num_arcs; ++i)\n  {\n    Graph::vertex_descriptor vertex = boost::add_vertex(graph);\n    arcSiteHash[i]=vertex;\n    \n    VRONI::arc* vr_arc = VRONI::arcs+i;\n    \n    Geometry::Point_2D tail;\n    get_pnt_coords(tail,vr_arc->i1);\n    \n    Geometry::Point_2D head;\n    get_pnt_coords(head,vr_arc->i2);\n    \n    vPosMap[vertex] = Geometry::midpoint(head,tail);\n  }\n  \n  auto inclusion_check = always_true;\n  \n  // second, create the vertices representing the edges and connect the resp. \n  // vertices\n  for( int i=0; i<VRONI::GetNumberOfEdges(); ++i)\n  {\n    VRONI::edge* vr_edge = VRONI::edges+i;\n    \n    if( inclusion_check(vr_edge))\n    {\n      Graph::vertex_descriptor vertex = boost::add_vertex(graph);\n      vdEdgeHash[i] = vertex;\n      \n      \n      Geometry::Point_2D tail;\n      get_node_coords(tail,vr_edge->n1);\n      \n      Geometry::Point_2D head;\n      get_node_coords(head,vr_edge->n2);\n      \n      vPosMap[vertex] = Geometry::midpoint(head,tail);\n      \n      // get left site vertex\n      \n      Graph::vertex_descriptor left;\n      switch(vr_edge->ltype)\n      {\n        case VRONI::PNT : left = pntSiteHash[vr_edge->lft]; break;\n        case VRONI::SEG : left = segSiteHash[vr_edge->lft]; break;\n        case VRONI::ARC : left = arcSiteHash[vr_edge->lft]; break;\n        default: ;  // this shouldn't happen\n      }\n      boost::add_edge(left,vertex,graph);\n      \n      Graph::vertex_descriptor right;\n      switch(vr_edge->rtype)\n      {\n        case VRONI::PNT : right = pntSiteHash[vr_edge->rgt]; break;\n        case VRONI::SEG : right = segSiteHash[vr_edge->rgt]; break;\n        case VRONI::ARC : right = arcSiteHash[vr_edge->rgt]; break;\n        default: ;  // this shouldn't happen\n      }\n      boost::add_edge(right,vertex,graph);\n    }\n    \n  }\n  \n  return graph;\n  \n}\n\nSimple2dGraph::Graph VroniInterface::createEdgeShapeAssociationGraph()\n{\n  using Graph = Simple2dGraph::Graph;\n  Graph graph;\n  \n  if( !m_vdIsCurrent )\n  { \n    qDebug() << \"Thr Voronoi diagram is not current. Can't create the edge-to-shape association graph.\";\n    return graph;\n  }\n  \n  auto vIndexMap  = boost::get(boost::vertex_index,graph); ///< Vertex_Index_Map\n  auto vPosMap    = boost::get(boost::vertex_position_2D, graph); ///< Vertex_Position2d_Map \n \n  QHash<int,Graph::vertex_descriptor> shapeHash;\n  QHash<int,Graph::vertex_descriptor> vdEdgeHash;\n  \n    \n  // create the vertices representing the shapes (as they won't be connected)\n  for( int i=0; i<shapeCentroidMap.size(); ++i)\n  {\n    Graph::vertex_descriptor shapeVertex = boost::add_vertex(graph);\n    shapeHash[i]=shapeVertex;\n  \n    vPosMap[shapeVertex] = shapeCentroidMap[i];\n  }\n  \n  // get the SITE-to-shape maps \n  QHash<int,int> pntToShapeMap  = getPntToShapeMap();\n  QHash<int,int> segToShapeMap  = getSegToShapeMap();\n  \n  printVroniSiteData();\n  qDebug() << \"PNT-to-Shape Map:\\n\" <<  pntToShapeMap;\n  qDebug() << \"SEG-to-Shape Map:\\n\" <<  segToShapeMap;\n\n  auto inclusion_check = in_w_mat;\n  \n  // third, create the vertices representing the edges and connect the resp. \n  // vertices\n  for( int i_vr_edge=0; i_vr_edge<VRONI::GetNumberOfEdges(); ++i_vr_edge)\n  {\n    VRONI::edge* vr_edge = VRONI::edges+i_vr_edge;\n    \n    // check whether the current edge should be included in this extraction\n    if( inclusion_check(vr_edge ) )\n    {\n//       QString edgeString = QString(\"Edge %1 :\").arg(i_vr_edge,2);\n      \n      Graph::vertex_descriptor edgeVertex = boost::add_vertex(graph);\n      vdEdgeHash[i_vr_edge] = edgeVertex;\n      \n      \n      Geometry::Point_2D tail;\n      get_node_coords(tail,vr_edge->n1);\n      \n      Geometry::Point_2D head;\n      get_node_coords(head,vr_edge->n2);\n      \n      vPosMap[edgeVertex] = Geometry::midpoint(head,tail);\n      \n      // get left site index\n            \n      int leftShapeIndex = NIL;\n      switch(vr_edge->ltype)\n      {\n        case VRONI::PNT : \n          // NOTE: the .contains check is necessary as operator[] default \n          // constructs an entry in case the key isn't present -- and that default\n          // constucted int is not VRONI::NIL.\n          if( pntToShapeMap.contains(vr_edge->lft) )\n          { leftShapeIndex = pntToShapeMap[vr_edge->lft]; }\n//           edgeString.append(QString(\"PNT %1\").arg(vr_edge->lft,2));\n          break;\n        case VRONI::SEG :\n          if( segToShapeMap.contains(vr_edge->lft) )\n          { leftShapeIndex = segToShapeMap[vr_edge->lft]; }\n//           edgeString.append(QString(\"SEG %1\").arg(vr_edge->lft,2));\n          break;\n        default: ; // this shouldn' happen\n      }\n      \n      if( leftShapeIndex != NIL )\n      {\n        Graph::vertex_descriptor leftShape = shapeHash[leftShapeIndex];\n        if( leftShapeIndex!=0 ) // don't add edges to the boundary\n        { boost::add_edge(leftShape,edgeVertex,graph); }\n//         edgeString.append(QString(\" (# %1)\").arg(leftShapeIndex,2));\n      }\n//       else\n//       { edgeString.append(QString(\"       \")); } // space for the alignment\n      \n      int rightShapeIndex = NIL;\n      switch(vr_edge->rtype)\n      {\n        case VRONI::PNT : \n          // NOTE: the .contains check is necessary as operator[] default \n          // constructs an entry in case the key isn't present -- and that default\n          // constucted int is not VRONI::NIL.\n          if( pntToShapeMap.contains(vr_edge->rgt) )\n          { rightShapeIndex = pntToShapeMap[vr_edge->rgt]; }\n//           edgeString.append(QString(\"PNT %1\").arg(vr_edge->rgt,2));\n          break;\n        case VRONI::SEG :\n          if( segToShapeMap.contains(vr_edge->rgt) )\n          { rightShapeIndex = segToShapeMap[vr_edge->rgt]; }\n//           edgeString.append(QString(\"SEG %1\").arg(vr_edge->rgt,2));\n          break;\n        default: ; // this shouldn' happen\n      }\n      \n      \n      if( rightShapeIndex != NIL )\n      {\n        Graph::vertex_descriptor rightShape = shapeHash[rightShapeIndex];\n        if( rightShapeIndex != 0 ) // don't add edges to the boundary\n        { boost::add_edge(rightShape,edgeVertex,graph); }\n//         edgeString.append(QString(\" (# %1)\").arg(rightShapeIndex,2));\n      }\n//       else\n//       { edgeString.append(QString(\"       \")); } // space for the alignment\n        \n//       qDebug() << edgeString;\n    }\n  }\n  \n  return graph;\n}\n\nSimple2dGraph::Graph VroniInterface::createEdgeShapeAssociationGraph(\n  QHash<int,int> shapeToEdgeMap\n)\n{\n  using Graph = Simple2dGraph::Graph;\n  Graph graph;\n  \n//   auto vIndexMap  = boost::get(boost::vertex_index,graph); ///< Vertex_Index_Map\n  auto vPosMap    = boost::get(boost::vertex_position_2D, graph); ///< Vertex_Position2d_Map \n  \n  QHash<int,Graph::vertex_descriptor> vdEdgeHash;\n  auto inclusion_check = in_w_mat;\n  \n  // create the vertices representing the edges \n  for( int i_vr_edge=0; i_vr_edge<VRONI::GetNumberOfEdges(); ++i_vr_edge)\n  {\n    VRONI::edge* vr_edge = VRONI::edges+i_vr_edge;\n    \n    // check whether the current edge should be included in this extraction\n    if( inclusion_check(vr_edge ) )\n    {\n      Graph::vertex_descriptor edgeVertex = boost::add_vertex(graph);\n      vdEdgeHash[i_vr_edge] = edgeVertex;\n      \n      \n      Geometry::Point_2D tail;\n      get_node_coords(tail,vr_edge->n1);\n      \n      Geometry::Point_2D head;\n      get_node_coords(head,vr_edge->n2);\n      \n      vPosMap[edgeVertex] = Geometry::midpoint(head,tail);\n    }\n  }\n \n  QHash<int,Graph::vertex_descriptor> shapeHash;\n  \n  // create the vertices representing the shapes and connect them to the edges\n  for( int i=0; i<shapeCentroidMap.size(); ++i)\n  {\n    \n    // create vertex\n    \n    Graph::vertex_descriptor shapeVertex = boost::add_vertex(graph);\n    shapeHash[i]=shapeVertex;\n  \n    vPosMap[shapeVertex] = shapeCentroidMap[i];\n    \n    // connect to edge(s)\n    \n    auto connectedEdges = shapeToEdgeMap.values(i);\n    \n    for( auto edge : connectedEdges)\n    { \n      if( vdEdgeHash.contains(edge) )\n      { boost::add_edge(shapeVertex,vdEdgeHash[edge],graph); }\n    }\n    \n  }\n  \n  return graph;\n}\n\nvoid VroniInterface::computeVD(const VroniInterface::VDDTParameter& params) \n{\n  // VRONI is not const correct, hence some const casting is necessary\n  auto output_file = const_cast<char*>( params.site_file.c_str() );\n  auto vd_dt_file  = const_cast<char*>( params.points_VDDT_file.c_str() );\n  \n  // call the VRONI function computing the Voronoi diagram and the Delaunay \n  // triangulation\n  VRONI::API_ComputeVD(\n    params.save_input, params.new_data, params.timing, params.bound, \n    params.sample,params.approx, output_file, params.check_for_duplicates, \n    params.recover_arcs, params.apx_absolute, params.apx_relative, \n    params.auto_apx, params.points_only, params.save_point_output, vd_dt_file, \n    params.clean_data\n  );\n  \n  // mark the current VD/DT data as current\n  m_vdIsCurrent = true;\n}\n\n/** \\todo Maybe introduce an exception to indicate the out-of-dateness of the\n *    VD/DT data instead of implicitely calling computeVD()? This could \n *    improve the const-correctness of the overall interface.\n */\nvoid VroniInterface::computeWMAT(double WMAT_distance, double WMAT_angle, bool auto_WMAT, bool left, bool right, bool timing)\n{\n  // check if the VD/DT data is current. If not, update the VD/DT data\n  if( !m_vdIsCurrent )\n  { computeVD(); }\n  \n  // call VRONI's API function\n  // NOTE: technically the function prototype calls for VRONI:boolean as bool\n  //   input types. But since those are just typdef'ed to bool this should work.\n  VRONI::API_ComputeWMAT(auto_WMAT, WMAT_angle,WMAT_distance,timing,left,right);\n}\n\nvoid VroniInterface::computeWMAT(const VroniInterface::WMATParameter& params) \n{\n  // check if the VD/DT data is current. If not, update the VD/DT data\n  if( !m_vdIsCurrent )\n  { computeVD(); }\n  \n  // call VRONI's API function\n  // NOTE: technically the function prototype calls for VRONI:boolean as bool\n  //   input types. But since those are just typdef'ed to bool this should work.\n  VRONI::API_ComputeWMAT(\n    params.auto_WMAT, params.WMAT_angle, params.WMAT_distance, params.timing, \n    params.left, params.right\n  );\n}\n\n\nVroniGraph::Graph VroniInterface::extractVdGraph(std::function< bool (VRONI::edge*)> inclusion_check) const\n{\n  using Graph = VroniGraph::Graph;\n  Graph graph; ///< a new boost graph to hold the VD graph.\n    \n  auto vIndexMap  = boost::get(boost::vertex_index,graph); ///< Vertex_Index_Map\n  auto vPosMap    = boost::get(boost::vertex_position_2D, graph); ///< Vertex_Position2d_Map \n  auto vVroniMap  = boost::get(boost::vertex_vroniIndex, graph); ///< Vertex_VroniIndex_Map \n  auto vDataMap   = boost::get(boost::vertex_vroniNodeData, graph); ///<  Vertex_VroniNodeData_Map \n  auto eWeightMap = boost::get(boost::edge_weight, graph); ///<  Edge_Weight_Map   \n  auto eVroniMap  = boost::get(boost::edge_vroniIndex, graph); ///<  Edge_VroniIndex_Map \n  auto eDataMap   = boost::get(boost::edge_vroniEdgeData, graph); ///<  Edge_VroniEdgeData_Map\n\n\n  \n  // A hash to relate VRONI node indices to the corresponding boost vertices\n  QHash<int,Graph::vertex_descriptor> vroniIndexVertexHash;\n  // A hash to relate VRONI edge indices to the corresponding boost edges\n  QHash<int,Graph::edge_descriptor>   vroniIndexEdgeHash;\n\n  // A counter to assign consecutive indices to the vertices (which will\n  // differ from the VRONI indices stored in vVroniMap!)\n  unsigned int vertexCounter = 0;\n  \n  \n  auto get_vertex_descriptor = [&](Graph::vertex_descriptor & vertex, int vroniNodeIndex)\n  {\n    if( !vroniIndexVertexHash.contains(vroniNodeIndex) )\n    { //no. add a new vertex.\n      vertex = boost::add_vertex(graph);\n      vroniIndexVertexHash[vroniNodeIndex]=vertex;\n          \n      { // populate the vertex properties\n      \n        vIndexMap[vertex]=vertexCounter++;\n        vVroniMap[vertex]=vroniNodeIndex;\n        \n        VRONI::node* vroniNode = VRONI::nodes+vroniNodeIndex;\n        vDataMap[vertex]=*vroniNode;\n        \n        Geometry::Point_2D position(vroniNode->p.x,vroniNode->p.y);\n        if( VRONI::scale_data)\n        { position = unScale(position); }\n        vPosMap[vertex]=position;\n        \n        \n\n      }\n    }\n    else\n    { //yes. recover it.\n      vertex = vroniIndexVertexHash.value(vroniNodeIndex);\n    }\n  };\n\n    \n  //\n  // process the VRONI data and copy them over to the boost graph\n  // ============================================================\n  //\n  \n  \n  // The total number of edges in VRONI's internal data. This includes VD/DT and\n  // WMAT edges, but no data from the input site.\n  int number_of_edges = VRONI::GetNumberOfEdges();\n\n  // the index for the currently processed VRONI edge\n  for(  int i_vr_edge = 4; // NOTE: I have NO IDEA why it has to start on 4, but this is a straight copy from VRONI::AddWMATToBuffer().\n        i_vr_edge < number_of_edges;\n        ++i_vr_edge)\n  { // loop over all edges in the VRONI data, i.e. WMAT and VD/DT:\n    \n    // get a pointer to the currently processed edge\n    VRONI::edge* vr_edge = VRONI::edges+i_vr_edge;\n    \n    // check whether the current edge should be included in this extraction\n    if( inclusion_check(vr_edge ) )\n    {\n      Graph::vertex_descriptor tail;\n            get_vertex_descriptor( tail, vr_edge->n1 );\n\n      Graph::vertex_descriptor head;\n            get_vertex_descriptor( head, vr_edge->n2 );\n      \n      {/* connect the head and the tail in the boost graph and compute the edge\n        * length\n        */\n        using namespace boost;\n        \n        bool success= false;\n        Graph::edge_descriptor edge;\n        boost::tie(edge,success) = boost::add_edge(tail, head, graph);\n        \n        if(success)\n        {\n          eVroniMap[edge]   = i_vr_edge;\n          eDataMap[edge]    = *vr_edge;\n          eWeightMap[edge]  = geometry::distance(vPosMap[head],vPosMap[tail]);\n          vroniIndexEdgeHash[i_vr_edge] = edge;\n        }\n      }\n      \n    }\n  }\n  \n  // Initialize the interior edge index\n  auto eIndexMap  = boost::get(boost::edge_index, graph); ///<  Edge_Index_Map \n  boost::graph_traits<Graph>::edges_size_type edge_count = 0;\n  boost::graph_traits<Graph>::edge_iterator ei, ei_end;\n  for(boost::tie(ei, ei_end) = boost::edges(graph); ei != ei_end; ++ei)\n  { eIndexMap[*ei] = edge_count++; }\n\n  \n  \n  \n  \n  \n  // done\n  return graph;  \n}\n\n\n\nVroniGraph::Graph VroniInterface::extractDtGraph(void ) const\n{\n  using Graph = VroniGraph::Graph;\n  \n  if( !m_isPointSite )\n  { \n    qDebug() << \"The VRONI site isn't a pure point site. Cannot extract Delaunay triangulation and/or graph.\";\n    return Graph();\n  }\n  \n  Graph graph; ///< a new boost graph to hold the DT graph.\n  \n  auto vIndexMap  = boost::get(boost::vertex_index,graph); ///< Vertex_Index_Map\n  auto vPosMap    = boost::get(boost::vertex_position_2D, graph); ///< Vertex_Position2d_Map \n  auto vVroniMap  = boost::get(boost::vertex_vroniIndex, graph); ///< Vertex_VroniIndex_Map \n  auto vDataMap   = boost::get(boost::vertex_vroniNodeData, graph); ///<  Vertex_VroniNodeData_Map \n  auto eWeightMap = boost::get(boost::edge_weight, graph); ///<  Edge_Weight_Map   \n  \n  //NOTE: There is no VRONI data associated with these edges, as VRONI doesn't\n  // explicitely compute them.\n  //   auto eVroniMap  = boost::get(boost::edge_vroniIndex, graph); ///<  Edge_VroniIndex_Map \n  //   auto eDataMap   = boost::get(boost::edge_vroniEdgeData, graph); ///<  Edge_VroniEdgeData_Map\n \n  // A hash to relate VRONI node indices to the corresponding boost vertices\n  QHash<int,Graph::vertex_descriptor> vroniIndexHash;\n\n  // A counter to assigne consecutive indices to the vertices (which will\n  // differ from the VRONI indices stored in vVroniMap!)\n  unsigned int vertexCounter = 0;\n  \n  // lambda to check if any of those VRONI nodes already is in the index hash\n  auto get_site_vertex = [&](Graph::vertex_descriptor & vertex, int vroniNodeIndex)\n  {\n    if( !vroniIndexHash.contains(vroniNodeIndex) )\n    { //no. add a new vertex.\n      vertex = boost::add_vertex(graph);\n      vroniIndexHash[vroniNodeIndex]=vertex;\n          \n      { // populate the vertex properties\n      \n        vIndexMap[vertex]=vertexCounter++;\n        vVroniMap[vertex]=vroniNodeIndex;\n        \n        VRONI::node* vroniNode = VRONI::nodes+vroniNodeIndex;\n        vDataMap[vertex]=*vroniNode;\n        \n        Geometry::Point_2D position(VRONI::pnts[vroniNodeIndex+2].p.x/*NOTE: this is different from vroniNode->p.x*/,\n                                    VRONI::pnts[vroniNodeIndex+2].p.y/*NOTE: this is different from vroniNode->p.y*/);\n        if( VRONI::scale_data)\n        { position = unScale(position); }\n        vPosMap[vertex]=position;\n\n      }\n    }\n    else\n    { //yes. recover it.\n      vertex = vroniIndexHash.value(vroniNodeIndex);\n    }\n  };\n  \n  // get the Delaunay triangulation from VRONI\n  std::vector<VRONI::d_triangle> dtTriangles = VRONI::GetDelaunayTriangles();\n    \n  for( VRONI::d_triangle& triangle : dtTriangles )\n  {\n    // get the involved nodes\n    Graph::vertex_descriptor n1;\n        get_site_vertex(n1,triangle.n1);\n    Graph::vertex_descriptor n2;\n        get_site_vertex(n2,triangle.n2);\n    Graph::vertex_descriptor n3;\n        get_site_vertex(n3,triangle.n3);\n\n    // connect them in the boost graph and compute the edge lengths\n    {\n     \n      bool success= false;\n      Graph::edge_descriptor edge;\n      \n      boost::tie(edge,success) = boost::add_edge(n1, n2, graph);\n      if(success)\n      { \n        \n        eWeightMap[edge] = boost::geometry::distance(vPosMap[n1],vPosMap[n2]); \n      }\n\n      boost::tie(edge,success) = boost::add_edge(n2, n3, graph);\n      if(success)\n      { \n        \n        eWeightMap[edge] = boost::geometry::distance(vPosMap[n2],vPosMap[n3]);\n      }\n      \n      boost::tie(edge,success) = boost::add_edge(n3, n1, graph);\n      if(success)\n      { \n        \n        eWeightMap[edge] = boost::geometry::distance(vPosMap[n3],vPosMap[n1]);\n      }\n      \n    }\n   \n  }\n  \n//   VRONI::WriteVDDT(\"vddt.out\");\n  \n  return graph;\n  \n}\n\n\n\n\n\nVroniGraph::Graph VroniInterface::extractVdGraph(void ) const\n{\n  return extractVdGraph(always_true);\n}\nVroniGraph::Graph VroniInterface::extractWmatGraph(void ) const\n{\n  return extractVdGraph(in_w_mat);\n}\nVroniGraph::Graph VroniInterface::extractNonWmatGraph(void ) const\n{\n  return extractVdGraph(in_vddt);\n}\n \n\n\n\nQHash< int, int > VroniInterface::determineVoronoiCells()\n{\n  QHash<int,int> shapeToEdgeMap;\n  \n  if( !m_vdIsCurrent )\n  { \n    qDebug() << \"Thr Voronoi diagram is not current. Can't determine the Voronoi cells.\";\n    return shapeToEdgeMap;\n  }\n  \n  // get the SITE-to-shape maps \n  QHash<int,int> pntToShapeMap  = getPntToShapeMap();\n  QHash<int,int> segToShapeMap  = getSegToShapeMap();\n  \n  auto inclusion_check = in_w_mat;\n  \n  // third, create the vertices representing the edges and connect the resp. \n  // vertices\n  for( int i_vr_edge=0; i_vr_edge<VRONI::GetNumberOfEdges(); ++i_vr_edge)\n  {\n    VRONI::edge* vr_edge = VRONI::edges+i_vr_edge;\n    \n    // check whether the current edge should be included in this extraction\n    if( inclusion_check(vr_edge ) )\n    {\n            \n      int leftShapeIndex = NIL;\n      switch(vr_edge->ltype)\n      {\n        case VRONI::PNT : \n          // NOTE: the .contains check is necessary as operator[] default \n          // constructs an entry in case the key isn't present -- and that default\n          // constucted int is not VRONI::NIL.\n          if( pntToShapeMap.contains(vr_edge->lft) )\n          { leftShapeIndex = pntToShapeMap[vr_edge->lft]; }\n          break;\n        case VRONI::SEG :\n          if( segToShapeMap.contains(vr_edge->lft) )\n          { leftShapeIndex = segToShapeMap[vr_edge->lft]; }\n          break;\n        default: ; // this shouldn' happen\n      }\n      \n      if( leftShapeIndex != NIL )\n      { shapeToEdgeMap.insertMulti(leftShapeIndex,i_vr_edge); }\n      \n      int rightShapeIndex = NIL;\n      switch(vr_edge->rtype)\n      {\n        case VRONI::PNT : \n          // NOTE: the .contains check is necessary as operator[] default \n          // constructs an entry in case the key isn't present -- and that default\n          // constucted int is not VRONI::NIL.\n          if( pntToShapeMap.contains(vr_edge->rgt) )\n          { rightShapeIndex = pntToShapeMap[vr_edge->rgt]; }\n          break;\n        case VRONI::SEG :\n          if( segToShapeMap.contains(vr_edge->rgt) )\n          { rightShapeIndex = segToShapeMap[vr_edge->rgt]; }\n          break;\n        default: ; // this shouldn' happen\n      }\n      \n      if( rightShapeIndex != NIL and rightShapeIndex != 0)\n      { shapeToEdgeMap.insertMulti(rightShapeIndex,i_vr_edge); }\n\n    }\n  }\n  \n  return shapeToEdgeMap;\n}\n\n// QHash< int, Geometry::Polygon_2D > VroniInterface::extractVoronoiCellGeometries() const\n// {\n//   QHash<int, Geometry::Polygon_2D> geometries;\n//   \n//   if( !m_vdIsCurrent )\n//   {\n//     qDebug() << \"The VD is not current, cannot extract Voronoi cell geometries.\";\n//     return geometries;\n//   }\n//   \n//   QHash<int,int>  shapeToEdgeMap = determineVoronoiCells;\n//   QList<int>      shapeIndices = shapeToEdgeMap.uniqueKeys;\n//   \n//   for( auto shape_i : shapeIndices)\n//   {\n//     Geometry::MultiPoint_2D cellCorners;\n//     \n//     // get a list of all edges associacted with that shape.\n//     QList<int> edgeIndices = shapeToEdgeMap.values(shape_i);\n//     \n//     for( auto edge_i : edgeIndices)\n//     {\n//       VRONI::edge* vr_edge = VRONI::edges+edge_i;\n//       \n//       Geometry::Point_2D tail;\n//       get_node_coords(tail,vr_edge->n1);\n//       boost::geometry::append(cellCorners,tail);\n//       \n//       Geometry::Point_2D head;\n//       get_node_coords(tail,vr_edge->n2);\n//       boost::geometry::append(cellCorners,head);\n//     }\n//     \n//     Geometry::Polygon_2D cellGeometry;\n//     boost::geometry::convex_hull(cellCorners,cellGeometry);\n//     geometries[shape_i] = cellGeometry;\n//   }\n//   \n//   return geometries;\n// }\n\n\nGeometry::Box_2D VroniInterface::boundingBox() const\n{ \n  using namespace VRONI;\n  \n  if (!bbox_added) //NOTE: the bbox gets added in VRONI::AddDummyCorners(int bound)\n    SetBoundingBox();\n  \n  if( data_scaled )\n  {\n    Geometry::Point_2D minCorner((bb_min.x/scale_factor)+shift.x,\n                                 (bb_min.y/scale_factor)+shift.y);\n    Geometry::Point_2D maxCorner((bb_max.x/scale_factor)+shift.x,\n                                 (bb_max.y/scale_factor)+shift.y);\n    \n    return Geometry::Box_2D(minCorner,maxCorner);\n  }\n  else\n  {\n    Geometry::Point_2D minCorner((bb_min.x),\n                                 (bb_min.y));\n    Geometry::Point_2D maxCorner((bb_max.x),\n                                 (bb_max.y));\n    \n    return Geometry::Box_2D(minCorner,maxCorner);\n    \n  }\n}\n\nGeometry::Point_2D VroniInterface::unScale(const Geometry::Point_2D& point) const\n{\n  if( VRONI::data_scaled )\n    return Geometry::Point_2D(point.get<0>()/VRONI::scale_factor+VRONI::shift.x,\n                              point.get<1>()/VRONI::scale_factor+VRONI::shift.y);\n  else\n    return point;\n}\n\n\nvoid VroniInterface::get_pnt_coords(Geometry::Point_2D& point, const int& pntIndex) const\n{\n  VRONI::pnt* vr_pnt = VRONI::pnts+pntIndex;\n  point.set_x(vr_pnt->p.x);\n  point.set_y(vr_pnt->p.y);\n  if(VRONI::scale_data)\n  { point = unScale(point); }\n};\n\nvoid VroniInterface::get_node_coords(Geometry::Point_2D& point, const int& nodeIndex) const\n{\n  VRONI::node* vr_node = VRONI::nodes+nodeIndex;\n  point.set_x(vr_node->p.x);\n  point.set_y(vr_node->p.y);\n  if(VRONI::scale_data)\n  { point = unScale(point); }\n}\n\n\n// void VroniInterface::unScale(Geometry::Point_2D& point) const\n// {\n//   point.get<0>() /= VRONI::scale_factor;\n//   point.get<0>() += VRONI::shift.x;\n//   point.get<1>() /= VRONI::scale_factor;\n//   point.get<1>() += VRONI::shift.y;\n// }\n\n\n\nvoid VroniInterface::printVroniSiteData()\n{\n  qDebug() <<\"VRONI Site Data:\" \n    <<\"\\nNumber of PNTs :\" << VRONI::num_pnts\n    <<\"\\nNumber of SEGs :\" << VRONI::num_segs\n    <<\"\\nNumber or ARCs :\" << VRONI::num_arcs;\n    \n  qDebug() << \"VRONI PNT Data :\";\n  for( int i=0; i<VRONI::num_pnts; ++i)\n  { \n    Geometry::Point_2D p;\n    get_pnt_coords(p,i);\n    qDebug() << QString(\"PNT %1:(%2,%3)\").arg(i,2).arg(p.x()).arg(p.y());\n  }\n  \n  qDebug() << \"VRONI SEG Data :\";\n  for( int i=0; i<VRONI::num_segs; ++i)\n  { \n    \n    Geometry::Point_2D tail,head;\n    VRONI::seg* vr_seg = VRONI::segs+i;\n    get_pnt_coords(tail,vr_seg->i1);\n    get_pnt_coords(head,vr_seg->i2);\n    \n//     qDebug() << QString(\"SEG %1: PNT %2 -> PNT %3 : (%4,%5) -> (%6,%7)\")\n//     .arg(i,2)\n//     .arg(vr_seg->i1,2)\n//     .arg(vr_seg->i2,2)\n//     .arg(tail.x(),8,'f',2).arg(tail.y(),8,'f',2)\n//     .arg(head.x(),8,'f',2).arg(head.y(),8,'f',2) ;\n    qDebug() << QString(\"SEG %1 (%2): PNT %3 -> PNT %4 \")\n    .arg(i,2)\n    .arg(vr_seg->ext_appl,2)\n    .arg(vr_seg->i1,2)\n    .arg(vr_seg->i2,2);\n  }\n  \n  \n  \n}\n\nQHash< int, int > VroniInterface::getSegToShapeMap() const\n{\n  QHash<int,int> segToShapeMap;\n  \n  for(int i=0; i<VRONI::num_segs; ++i)\n  {\n    VRONI::seg* vr_seg = VRONI::segs+i;\n    segToShapeMap[i] = vr_seg->ext_appl;\n  }\n  \n  return segToShapeMap;\n}\n\n\n\nQHash< int, int > VroniInterface::getPntToShapeMap() const\n{\n  QHash<int,int> pntShapeMap;\n  \n  // loop over all segments, grab the end points and the assoc. shape and\n  // put it in the pntShapeMap\n  for( int i=0; i< VRONI::num_segs; ++i)\n  {\n    VRONI::seg* vr_seg = VRONI::segs+i;\n    \n    pntShapeMap[vr_seg->i1] = vr_seg->ext_appl; // tail\n    pntShapeMap[vr_seg->i2] = vr_seg->ext_appl; // head\n    \n  }\n  \n  return pntShapeMap;\n}\n\n\nbool VroniInterface::isVdCurrent() const\n{\n  return m_vdIsCurrent;\n}\n\n\n\n", "meta": {"hexsha": "fb648b77f2b7a5802ced354019af38b7954862de", "size": 42081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/vroniinterface.cpp", "max_stars_repo_name": "mvsframework/mvs", "max_stars_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "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/core/vroniinterface.cpp", "max_issues_repo_name": "mvsframework/mvs", "max_issues_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/vroniinterface.cpp", "max_forks_repo_name": "mvsframework/mvs", "max_forks_repo_head_hexsha": "4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81", "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.6763046544, "max_line_length": 137, "alphanum_fraction": 0.6466814002, "num_tokens": 11987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.025565213644860394, "lm_q1q2_score": 0.007521668620863463}}
{"text": "//#include <boost/serialization/export.hpp>\n#include \"TCell.h\"\n\n//BOOST_CLASS_EXPORT_IMPLEMENT(TCell)\n#include \"../../core/GlobalUtilities.h\"\n#include \"../compartment/Tumor.h\"\n\n\n#include <boost/math/tools/roots.hpp>\n\nnamespace SP_QSP_IO{\nnamespace SP_QSP_NSCLC{\n\n//#define IFNG_ID 0\n\nusing std::string;\nusing std::stringstream;\n\nstatic int TCellSize = 1;\n\nTCell::TCell()\n\t: _count_neighbor_cancer(0)\n\t, _count_neighbor_Treg(0)\n\t, _count_neighbor_all(0)\n\t, _max_neighbor_PDL1(0)\n{\n}\n\nTCell::TCell(SpatialCompartment* c)\n\t:Cell_Tumor(c)\n\t, _divide_flag(false)\n\t, _divide_cd(0)\n\t, _divide_limit(params.getVal(PARAM_T_DIV_LIMIT))\n\t, _IL2_exposure(0)\n\t, _IL2_release_remain(params.getVal(PARAM_IL_2_RELEASE_TIME))\n\t, _IFN_release_remain(params.getVal(PARAM_IFN_RELEASE_TIME))\n\t, _source_IFNg(NULL)\n\t, _source_IL_2(NULL)\n\t, _count_neighbor_cancer(0)\n\t, _count_neighbor_Treg(0)\n\t, _count_neighbor_all(0)\n\t, _max_neighbor_PDL1(0)\n{\n\t_state = AgentStateEnum::T_CELL_EFF;\n\t_life = TCell::getTCellLife();\n\t//cout << getID() << \", \" << getType() << endl;\n}\n\n\nTCell::TCell( const TCell & c)\n\t:Cell_Tumor(c)\n\t, _divide_flag(c._divide_flag)\n\t, _divide_cd(c._divide_cd)\n\t, _divide_limit(c._divide_limit)\n\t, _IL2_exposure(c._IL2_exposure)\n\t, _IL2_release_remain(c._IL2_release_remain)\n\t, _IFN_release_remain(c._IFN_release_remain)\n\t, _source_IFNg(NULL)\n\t, _source_IL_2(NULL)\n\t, _count_neighbor_cancer(0)\n\t, _count_neighbor_Treg(0)\n\t, _count_neighbor_all(0)\n\t, _max_neighbor_PDL1(0)\n{\n\t_state = c._state;\n\t//cout << getID() << \", \" << getType() << endl;\n\t_life = TCell::getTCellLife();\n\t//std::cout << \"Teff copy life: \" << _life << std::endl;\n\tif (_state == AgentStateEnum::T_CELL_CYT)\n\t{\n\t\tsetup_chem_source(_source_IFNg, CHEM_IFN, params.getVal(PARAM_IFN_G_RELEASE));\n\t\tsetup_chem_source(_source_IL_2, CHEM_IL_2, params.getVal(PARAM_IL_2_RELEASE));\n\t}\n}\n\n\nTCell::~TCell()\n{\n}\nstring TCell::toString()const{\n\tstringstream ss;\n\tss << CellAgent::toString();\n\tss << \"division flag: \" << _divide_flag << \", division cool down: \" \n\t\t<< _divide_cd  << std::endl;\n\treturn ss.str();\n}\n\nbool TCell::agent_movement_step(double t, double dt, Coord& c){\n\tbool move = false;\n\tif (rng.get_unif_01() < params.getVal(PARAM_T_CELL_MOVE_PROB))\n\t{\n\t\t// move\n\t\tint idx;\n\t\tconst auto shape = getCellShape();\n\t\tif (_compartment->getOneOpenVoxel(shape->getMoveDestinationVoxels(), \n\t\t\tshape->getMoveDirectionAnchor(), _coord, getType(), idx, rng))\n\t\t{\n\t\t\tmove = true;\n\t\t\tc = getCellShape()->getMoveDirectionAnchor()[idx] + _coord;\n\t\t}\n\t}\n\treturn move;\n\n}\n\n/*! Scan neighborhood and count neighbor cell type\n\tnumber of Teff neighbor for Cancer cell; \n\tnumber of Cancer cell neighbor for Teff; \n\tnumber of Treg neighbor for Teff; \n*/\nvoid TCell::agent_state_scan(void){\n\n\tconst auto shape = getCellShape();\n\tif (_state == AgentStateEnum::T_CELL_CYT){\n\t\t/**/\n\t\t// scan cancer cells\n\t\t//std::cout << \"T cell at: \"<< _coord << std::endl;\n\t\t//int nr_cancer_neighbor = 0;\n\t\t_compartment->for_each_neighbor_ag(shape->getEnvironmentLocations(),\n\t\t\t_coord, [&](BaseAgent* ag){\n\t\t\t_count_neighbor_all++;\n\t\t\tauto pCell = dynamic_cast<Cell_Tumor*>(ag);\n\t\t\tupdate_neighbor_PDL1(pCell->get_PDL1());\n\t\t\tif (ag->getType() == AgentTypeEnum::CELL_TYPE_CANCER){\n\t\t\t\tauto pCancer = dynamic_cast<CancerCell*>(ag);\n\t\t\t\tinc_neighbor_cancer();\n\t\t\t\tpCancer->inc_neighbor_Teff(); \n\t\t\t\t//nr_cancer_neighbor += 1;\n\t\t\t}\n\t\t\telse if (ag->getType() == AgentTypeEnum::CELL_TYPE_TREG){\n\t\t\t\tinc_neighbor_Treg();\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n\t\t//std::cout << \"T cell neighbor PDL1: \"<< _max_neighbor_PDL1 << std::endl;\n\t\t//std::cout << \"T cell neighbor Cancer: \"<< nr_cancer_neighbor << std::endl;\n\t}\n\treturn;\n}\n\nbool TCell::agent_state_step(double t, double dt, Coord& c){\n\tbool divide = false;\n\tif (!isDead())\n\t{\n\t\t_life--;\n\t\tif (_life <= 0)\n\t\t{\n\t\t\tsetDead();\n\t\t\t// remove source when cell die\n\t\t\treturn divide;\n\t\t}\n\t}\n\t//std::cout << \"Teff life: \" << _life << std::endl;\n\n\tconst auto shape = getCellShape();\n\n\tCell_Tumor::agent_state_step(t, dt, c);\n\n\tauto tumor = dynamic_cast<Tumor*>(_compartment);\n\n\tdouble IL2 = get_tumor().get_chem(_coord, CHEM_IL_2);\n\t_IL2_exposure += params.getVal(PARAM_SEC_PER_TIME_SLICE) * IL2;\n\n\t// effector cells to proliferate on IL2 exposure\n\tif (_IL2_exposure > params.getVal(PARAM_IL_2_PROLIF_TH))\n\t{\n\t\t_divide_flag = true;\n\t}\n\n\t// Look for tumor Ag\n\tif (_state == AgentStateEnum::T_CELL_EFF)\n\t{\n\t\tbool cancer_found = _compartment->hasTypeStateInTarget(shape->getEnvironmentLocations(), \n\t\t\t_coord, AgentTypeEnum::CELL_TYPE_CANCER, AgentStateEnum::CANCER_PROGENITOR);\n\t\tif (cancer_found)\n\t\t{\n\t\t\t_state = AgentStateEnum::T_CELL_CYT;\n\t\t\t_divide_flag = true;\n\t\t\tsetup_chem_source(_source_IFNg, CHEM_IFN, params.getVal(PARAM_IFN_G_RELEASE));\n\t\t\tsetup_chem_source(_source_IL_2, CHEM_IL_2, params.getVal(PARAM_IL_2_RELEASE));\n\t\t}\n\t}\n\n\tif (_state == AgentStateEnum::T_CELL_CYT){\n\t\t/**/\n\t\tdouble nivo = tumor->get_Nivo();\n\n\t\t// kill one cancer cell\n\t\t// now handled from cancer cells\n\n\t\t// IL-2 release time limit\n\t\tif (_IL2_release_remain > 0)\n\t\t{\n\t\t\t_IL2_release_remain -= params.getVal(PARAM_SEC_PER_TIME_SLICE);\n\t\t}\n\t\telse{\n\t\t\t// set IL-2 source to 0\n\t\t\tupdate_chem_source(_source_IL_2, 0.0);\n\t\t}\n\t\t// IFNg release time limit\n\t\tif (_IFN_release_remain > 0)\n\t\t{\n\t\t\t_IFN_release_remain -= params.getVal(PARAM_SEC_PER_TIME_SLICE);\n\t\t}\n\t\telse{\n\t\t\t// set IL-2 source to 0\n\t\t\tupdate_chem_source(_source_IFNg, 0.0);\n\t\t}\n\t\t\n\t\t// exhaustion\n\t\tif (_count_neighbor_Treg > 0)// suppresion by Treg\n\t\t{\n\t\t\tdouble bond = get_PD1_PDL1(_max_neighbor_PDL1, nivo);\n\t\t\tdouble supp = get_PD1_supp(bond, params.getVal(PARAM_N_PD1_PDL1));\n\t\t\tdouble q = double(_count_neighbor_Treg) / _count_neighbor_all;\n\t\t\tdouble p_exhaust = get_exhaust_prob_Treg(supp, q);\n\t\t\tif (rng.get_unif_01() < p_exhaust)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\tstd::cout << \"RNG check: ID=\" << getID() <<\n\t\t\t\t\"(Teff exhaust by Treg): \" << rng.get_unif_01() << std::endl;\n\t\t\t\t*/\n\t\t\t\tset_suppressed();\n\t\t\t}\n\t\t}\n\t\telse if (_count_neighbor_all > 0)// suppresion by PDL1 \n\t\t{\n\t\t\tdouble bond = get_PD1_PDL1(_max_neighbor_PDL1, nivo);\n\t\t\tdouble supp = get_PD1_supp(bond, 1);\n\t\t\tdouble p_exhaust = get_exhaust_prob_PDL1(supp, 1.0);\n\t\t\t/*\n\t\t\tstd::cout << \"suppression prob: \" << p_exhaust << std::endl;\n\t\t\t*/\n\t\t\tif (rng.get_unif_01() < p_exhaust)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\tstd::cout << \"RNG check: ID=\" << getID() <<\n\t\t\t\t\" (Teff exhaust by PDL1): \" << rng.get_unif_01() << std::endl;\n\t\t\t\t*/\n\t\t\t\tset_suppressed();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (_divide_cd > 0)\n\t{\n\t\t_divide_cd--;\n\t}\n\t\n\tif (_divide_limit > 0 && _divide_flag && _divide_cd == 0)\n\t{\n\t\tint idx;\n\t\tif (_compartment->getOneOpenVoxel(shape->getProlifDestinationVoxels(), \n\t\t\tshape->getProlifDestinationAnchor(), _coord, getType(), idx, rng))\n\t\t{\n\t\t\tdivide = true;\n\t\t\t//cout << \"idx: \" << idx << \", \" << getCellShape()->getProlif()[idx] << endl;\n\t\t\tc = getCellShape()->getProlifDestinationAnchor()[idx] + _coord;\n\n\t\t\t_divide_flag = true;\n\t\t\t_divide_limit -= 1;\n\t\t\t_divide_cd = params.getVal(PARAM_T_DIV_INTERVAL);\n\t\t}\n\n\t}\n\n\t_count_neighbor_cancer = 0;\n\t_count_neighbor_Treg = 0;\n\t_count_neighbor_all = 0;\n\t_max_neighbor_PDL1 = 0;\n\treturn divide;\n}\n\n/*! set to suppressed state\n*/\nvoid TCell::set_suppressed(void){\n\t_divide_flag = false;\n\t_divide_limit = 0;\n\t_state = AgentStateEnum::T_CELL_SUPP;\n\tremove_source_sink(_source_IFNg);\n\tremove_source_sink(_source_IL_2);\n\treturn;\n}\n\n//! move sources (IFN and IL2)\nvoid TCell::move_all_source_sink(void)const{\n\t//std::cout << \"moving sources: \" << _coord << std::endl;\n\tmove_source_sink(_source_IFNg);\n\tmove_source_sink(_source_IL_2);\n\treturn;\n}\n\n//! remove sources (IFN and IL2)\nvoid TCell::remove_all_source_sink(void){\n\tremove_source_sink(_source_IFNg);\n\tremove_source_sink(_source_IL_2);\n\treturn;\n}\n\nvoid TCell::update_neighbor_PDL1(double PDL1){\n\tif (PDL1 > _max_neighbor_PDL1)\n\t{\n\t\t_max_neighbor_PDL1 = PDL1;\n\t}\n\treturn;\n}\n\n//! PD1_PDL1 bond in synapse, newton_raphson method\ndouble TCell::get_PD1_PDL1(double PDL1, double Nivo){\n\tusing namespace boost::math::tools;\n\tdouble guess = 0;\n\tdouble xmin = 0;\n\tdouble xmax = 1;\n\tint digits = static_cast<int>(std::numeric_limits<double>::digits);\n\tboost::uintmax_t maxit = 20;\n\n\tstatic double T1 = params.getVal(PARAM_PD1_SYN);\n\tdouble T2 = PDL1;\n\tstatic double k1 = params.getVal(PARAM_PDL1_K1);\n\tstatic double k2 = params.getVal(PARAM_PDL1_K2);\n\tstatic double k3 = params.getVal(PARAM_PDL1_K3);\n\n\t// 0 if no T2\n\tif (T2 == 0){\n\t\treturn 0;\n\t}\n\t// f(x)\n\tdouble a, b, c, d;\n\ta = 1;\n\tb = -(T1 / T2 + 2 + 1 / T2 / k1 + Nivo*k2 / T2 / k1*(1 - 2 * k3 / k1));\n\tc = 2 * T1 / T2 + 1 + 1 / T2 / k1 + Nivo*k2 / T2 / k1;\n\td = -T1 / T2;\n\t// f'(x)\n\tdouble a1, b1, c1;\n\ta1 = 3;\n\tb1 = -2 * (T1 / T2 + 2 + 1 / T2 / k1 + Nivo*k2 / T2 / k1*(1 - 2 * k3 / k1));\n\tc1 = 1 + 1 / k1 / T2 + Nivo*k2 / k1 / T2 + 2 * T1 / T2;\n\n\tdouble root = newton_raphson_iterate(\n\t\t// lambda function:\n\t\t[a, b, c, d, a1, b1, c1](const double g){ return std::make_pair(\n\t\ta * g * g * g + b * g * g + c * g + d,\n\t\ta1 * g * g + b1 * g + c1); },\n\t\tguess, xmin, xmax, digits, maxit);\n\n\tdouble bond = T2*root;\n\treturn bond;\n}\n\n//! PD1_PDL1 bond in synapse\n/*\ndouble TCell::get_PD1_PDL1(double PDL1, double Nivo){\n\n\tstatic double T1 = params.getVal(PARAM_PD1_SYN);\n\tdouble T2 = PDL1;\n\tstatic double k1 = params.getVal(PARAM_PDL1_K1);\n\tstatic double k2 = params.getVal(PARAM_PDL1_K2);\n\tstatic double k3 = params.getVal(PARAM_PDL1_K3);\n\n\tdouble a = 1;\n\tdouble b = (Nivo*k2/k1*(2*k3/k1-1) - 2*T2 - T1 - 1/k1)/T2;\n\tdouble c = (Nivo*k2/k1 + 1/k1  +T2 + 2*T1 )/T2;\n\tdouble d = -T1/T2;\n\n\n\t//Newton_Raphson_root\n\tint max_iter = 20;\n\tdouble tol_rel = 1E-5;\n\tdouble root = 0;\n\tdouble res, root_new, f, f1;\n\tint i = 0;\n\twhile (i < max_iter){\n\t\tf = a*std::pow(root, 3) + b*std::pow(root, 2)+ c*root + d;\n\t\tf1 = 3.0*a*std::pow(root, 2) + 2.0*b*root + c;\n\t\troot_new = root - f/f1;\n\t\tres = std::abs(root_new - root) / root_new;\n\t\tif (res > tol_rel){\n\t\t\ti++;\n\t\t\troot = root_new;\n\t\t}\n\t\telse{\n\t\t\tbreak;\n\t\t}\n\t}\n\tdouble bond = T2*root;\n\treturn bond;\n}*/\n\n\n//! get suppression from PD1_PDL1 bond\ndouble TCell::get_PD1_supp(double bond, double n) {\n\tdouble k50 = params.getVal(PARAM_PD1_PDL1_HALF);\n\treturn get_Hill_equation(bond, k50, n);\n}\n\nint TCell::getTCellLife(){\n\tdouble lifeMean = params.getVal(PARAM_T_CELL_LIFE_MEAN_SLICE);\n\tdouble lifeSd = params.getVal(PARAM_T_CELL_LIFE_SD_SLICE);\n\tdouble tLifeD = lifeMean + rng.get_norm_std() * lifeSd;\n\t/*\n\tdouble tLifeD = rng.get_exponential(lifeMean);\n\t*/\n\n\tint tLife = int(tLifeD + 0.5);\n\ttLife = tLife > 0 ? tLife : 0;\n\t//std::cout << \"random T cell life: \" << tLife << std::endl;\n\treturn tLife;\n}\n\n/*! probability of Cancer cell getting killed by Teff\n\t\\param[in] supp: suppression\n\tp_kill = 1 - B_esc^((1-supp)*q),\n\twhere B_esc = exp(-tstep * k_C_death_by_T)\n*/\ndouble TCell::get_kill_prob(double supp, double q){\n\treturn 1 - std::pow(params.getVal(PARAM_ESCAPE_BASE), q*(1-supp));\n}\n\n/*! probability of turning exhausted from PDL1-PD1 interaction\n\tp_exhaust_PDL1 = 1 - B^(supp*q)\n*/\ndouble TCell::get_exhaust_prob_PDL1(double supp, double q){\n\treturn 1 - std::pow(params.getVal(PARAM_EXHUAST_BASE_PDL1), q*supp);\n}\n\n/*! probability of turning exhausted from Treg\n\tp_exhaust_Treg = 1 - B^((1 + supp)*q)\n*/\ndouble TCell::get_exhaust_prob_Treg(double supp, double q){\n\treturn 1 - std::pow(params.getVal(PARAM_EXHUAST_BASE_TREG), q*(1 + supp));\n}\n\n\n};\n};\n", "meta": {"hexsha": "4d03572279c6511d35c2bf282be421c5e9fbeb12", "size": 11240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPQSP_IO/NSCLC/SP_QSP_NSCLC/abm/agent/TCell.cpp", "max_stars_repo_name": "popellab/SPQSP_IO", "max_stars_repo_head_hexsha": "eca3ea55ec2f75b0db5d58da09500ddffabc001d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SPQSP_IO/NSCLC/SP_QSP_NSCLC/abm/agent/TCell.cpp", "max_issues_repo_name": "popellab/SPQSP_IO", "max_issues_repo_head_hexsha": "eca3ea55ec2f75b0db5d58da09500ddffabc001d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SPQSP_IO/NSCLC/SP_QSP_NSCLC/abm/agent/TCell.cpp", "max_forks_repo_name": "popellab/SPQSP_IO", "max_forks_repo_head_hexsha": "eca3ea55ec2f75b0db5d58da09500ddffabc001d", "max_forks_repo_licenses": ["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.7798165138, "max_line_length": 91, "alphanum_fraction": 0.678113879, "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.02556521137118536, "lm_q1q2_score": 0.007521667951914226}}
{"text": "/***\n第三节 完美转发\n（1）完美转发的概念和步骤演绎\na)直接调用：  funcLast();\nb)转发： 通过funcMiddle()间接调用funcLast。funcMiddle相当于一个跳板函数。如果有参数，那么参数也需要通过funcMiddle中转传递给funcLast()\nc)完美转发：const,左值，右值。实参的属性完全不丢失，原原本本的通过funcMiddle转发给funcLast，这种转发就是完美转发。\n\n万能引用：实参的所有信息都会传递到万能引用当中去从而让编译器推导出来函数模板最终的形参类型 (引用折叠)。\n完美转发：就是让开发者可以书写接受任意实参的函数模板（funcMiddle_Temp），并将其转发到目标函数（funcLast2)，目标函数会接收到与\n转发函数（funcMiddle_Temp）所接收的完全相同（当然包括类型相同比如保持参数的左值、右值特性）的参数。\n要实现完美转发，就要用到std::forward了。\n***/\n\n#include <iostream>\n\n//#include <boost/type_index.hpp>\nusing namespace std;\n//#pragma warning(disable : 4996) \n\n\n//函数模板\n//template <typename T>\n//void myfunc(T  tmprv)\n//{\n//\tcout << \"--------------------------------begin----------------\" << endl;\n//\tusing boost::typeindex::type_id_with_cvr;\n//\tcout << \"T=\" << type_id_with_cvr<T>().pretty_name() << endl; //显示T的类型\n//\tcout << \"tmprv=\" << type_id_with_cvr<decltype(tmprv)>().pretty_name() << endl; //显示tmprv的类型\n//\tcout << \"--------------------------------end------------------\" << endl;\n//}\n\nnamespace _nmsp1\n{\n\t//void funcLast(int v1, int v2)\n\tvoid funcLast(int v1, int& v2)\n\t{\n\t\t++v2; //改变v2的值，让其自增1\n\t\tcout << v1 + v2 << endl;\n\t}\n\n\tvoid funcLast2(int&& v1, int& v2)\n\t{\n\t\tcout << v1 << endl;\n\t\tcout << v2 << endl;\n\t}\n\n\t//函数模板（跳板函数）：把收到的参数以及这些参数相对应的类型不变的转发给其他函数（完美转发）\n\ttemplate<typename F, typename T1,typename T2>\n\t//void funcMiddle_Temp(F f, T1 t1, T2 t2) //f:函数指针类型void(*)(int,int)，而funcLast是函数类型void(int,int)\n\tvoid funcMiddle_Temp(F f, T1&& t1, T2&& t2)\n\t{\n\t\tf(t1, t2);\n\t}\n}\n\nint main()\n{ \n\t/*\n\tint i = 50;\n\t_nmsp1::funcLast(41, i);                           //变量i自加1后 + 50 = 92\n\t*/\n\n\t/*\n\tint j = 70;\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast, 20, j);  //变量j自加1后 + 20 = 91\n\t*/\n\n\t/*\n\tint k = 50;\n\t_nmsp1::funcLast(41, k);                          //直接调用，92,执行完k=51         \n\t*/\n\n\t/*\n\tint l = 70;\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast, 20, l); //91,执行完本函数，l = 71？70呢？ = 70\n\t                                                  //当前情况下l被funcMiddle_Temp推断成了int而不是int&\n\t                                                  //void funcMiddle_Temp(void(*f)(int,int &),int t1,int t2){...}\n\t*/\n\n\t/*\n\tint m = 70;\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast, 20, m);  //91,T1=int, t1 = int &&，      T2 = int & , t2 = int &\n\t\t                                               //m = 71;\n\t*/\n\t\n\tint n = 70;\n\t//_nmsp1::funcLast2(20, n); //20,70\n\t_nmsp1::funcMiddle_Temp(_nmsp1::funcLast2, 20, n);\n\t                                                 //20->t1(int &&)，但是t1本身是左值。\n\n\t/*int&& abc = 1;\n\tabc = 15;*/\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "94eb5f00d83bd4c4e86e352e7b96f36c8721a453", "size": 2492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/3/304.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/3/304.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/3/304.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 25.6907216495, "max_line_length": 113, "alphanum_fraction": 0.5597913323, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11596071214366646, "lm_q2_score": 0.06465348880678598, "lm_q1q2_score": 0.007497264604607471}}
{"text": "// Copyright (c) 2021-2022, The iTw3 Project\n//\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other\n//    materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n//    used to endorse or promote products derived from this software without specific\n//    prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"multisig_account.h\"\n\n#include \"crypto/crypto.h\"\n#include \"cryptonote_config.h\"\n#include \"include_base_utils.h\"\n#include \"multisig.h\"\n#include \"multisig_kex_msg.h\"\n#include \"ringct/rctOps.h\"\n\n#include <boost/math/special_functions/binomial.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <limits>\n#include <memory>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n\n#undef MONERO_DEFAULT_LOG_CATEGORY\n#define MONERO_DEFAULT_LOG_CATEGORY \"multisig\"\n\nnamespace multisig\n{\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  * \n  * brief: check_multisig_config - validate multisig configuration details\n  * param: round - the round of the message that should be produced\n  * param: threshold - threshold for multisig (M in M-of-N)\n  * param: num_signers - number of participants in multisig (N)\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static void check_multisig_config(const std::uint32_t round,\n    const std::uint32_t threshold,\n    const std::uint32_t num_signers)\n  {\n    CHECK_AND_ASSERT_THROW_MES(num_signers > 1, \"Must be at least one other multisig signer.\");\n    CHECK_AND_ASSERT_THROW_MES(num_signers <= config::MULTISIG_MAX_SIGNERS,\n      \"Too many multisig signers specified (limit = 16 to prevent dangerous combinatorial explosion during key exchange).\");\n    CHECK_AND_ASSERT_THROW_MES(num_signers >= threshold,\n      \"Multisig threshold may not be larger than number of signers.\");\n    CHECK_AND_ASSERT_THROW_MES(threshold > 0, \"Multisig threshold must be > 0.\");\n    CHECK_AND_ASSERT_THROW_MES(round > 0, \"Multisig kex round must be > 0.\");\n    CHECK_AND_ASSERT_THROW_MES(round <= multisig_kex_rounds_required(num_signers, threshold) + 1,\n      \"Trying to process multisig kex for an invalid round.\");\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  * \n  * brief: calculate_multisig_keypair_from_derivation - wrapper on calculate_multisig_keypair() for an input public key\n  *    Converts an input public key into a crypto private key (type cast, does not change serialization),\n  *    then passes it to get_multisig_blinded_secret_key().\n  * \n  *    Result:\n  *      - privkey = H(derivation)\n  *      - pubkey = privkey * G\n  * param: derivation - a curve point\n  * outparam: derived_pubkey_out - public key of the resulting privkey\n  * return: multisig private key\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static crypto::secret_key calculate_multisig_keypair_from_derivation(const crypto::public_key_memsafe &derivation,\n    crypto::public_key &derived_pubkey_out)\n  {\n    crypto::secret_key blinded_skey = get_multisig_blinded_secret_key(rct::rct2sk(rct::pk2rct(derivation)));\n    CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(blinded_skey, derived_pubkey_out), \"Failed to derive public key\");\n\n    return blinded_skey;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: make_multisig_common_privkey - Create the 'common' multisig privkey, owned by all multisig participants.\n  *    - common privkey = H(sorted base common privkeys)\n  * param: participant_base_common_privkeys - Base common privkeys contributed by multisig participants.\n  * outparam: common_privkey_out - result\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static void make_multisig_common_privkey(std::vector<crypto::secret_key> participant_base_common_privkeys,\n    crypto::secret_key &common_privkey_out)\n  {\n    // sort the privkeys for consistency\n    //TODO: need a constant-time operator< for sorting secret keys\n    std::sort(participant_base_common_privkeys.begin(), participant_base_common_privkeys.end(),\n        [](const crypto::secret_key &key1, const crypto::secret_key &key2) -> bool\n        {\n          return memcmp(&key1, &key2, sizeof(crypto::secret_key)) < 0;\n        }\n      );\n\n    // privkey = H(sorted ancillary base privkeys)\n    crypto::hash_to_scalar(participant_base_common_privkeys.data(),\n      participant_base_common_privkeys.size()*sizeof(crypto::secret_key),\n      common_privkey_out);\n\n    CHECK_AND_ASSERT_THROW_MES(common_privkey_out != crypto::null_skey, \"Unexpected null secret key (danger!).\");\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  * \n  * brief: compute_multisig_aggregation_coefficient - creates aggregation coefficient for a specific public key in a set\n  *    of public keys\n  *    \n  *    WARNING: The coefficient will only be deterministic if...\n  *      1) input keys are pre-sorted\n  *         - tested here\n  *      2) input keys are in canonical form (compressed points in the prime-order subgroup of Ed25519)\n  *         - untested here for performance\n  * param: sorted_keys - set of component public keys that will be merged into a multisig public spend key\n  * param: aggregation_key - one of the component public keys\n  * return: aggregation coefficient\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static rct::key compute_multisig_aggregation_coefficient(const std::vector<crypto::public_key> &sorted_keys,\n    const crypto::public_key &aggregation_key)\n  {\n    CHECK_AND_ASSERT_THROW_MES(std::is_sorted(sorted_keys.begin(), sorted_keys.end()),\n      \"Keys for aggregation coefficient aren't sorted.\");\n\n    // aggregation key must be in sorted_keys\n    CHECK_AND_ASSERT_THROW_MES(std::find(sorted_keys.begin(), sorted_keys.end(), aggregation_key) != sorted_keys.end(),\n      \"Aggregation key expected to be in input keyset.\");\n\n    // aggregation coefficient salt\n    rct::key salt = rct::zero();\n    static_assert(sizeof(rct::key) >= sizeof(config::HASH_KEY_MULTISIG_KEY_AGGREGATION), \"Hash domain separator is too big.\");\n    memcpy(salt.bytes, config::HASH_KEY_MULTISIG_KEY_AGGREGATION, sizeof(config::HASH_KEY_MULTISIG_KEY_AGGREGATION));\n\n    // coeff = H(aggregation_key, sorted_keys, domain-sep)\n    rct::keyV data;\n    data.reserve(sorted_keys.size() + 2);\n    data.push_back(rct::pk2rct(aggregation_key));\n    for (const auto &key : sorted_keys)\n      data.push_back(rct::pk2rct(key));\n    data.push_back(salt);\n\n    // note: coefficient is considered public knowledge, no need to memwipe data\n    return rct::hash_to_scalar(data);\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  * \n  * brief: generate_multisig_aggregate_key - generates a multisig public spend key via key aggregation\n  *    Key aggregation via aggregation coefficients prevents key cancellation attacks.\n  *    See: https://www.getmonero.org/resources/research-lab/pubs/MRL-0009.pdf\n  * param: final_keys - address components (public keys) obtained from other participants (not shared with local)\n  * param: privkeys_inout - private keys of address components known by local; each key will be multiplied by an aggregation coefficient (return by reference)\n  * return: final multisig public spend key for the account\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static crypto::public_key generate_multisig_aggregate_key(std::vector<crypto::public_key> final_keys,\n    std::vector<crypto::secret_key> &privkeys_inout)\n  {\n    // collect all public keys that will go into the spend key (these don't need to be memsafe)\n    final_keys.reserve(final_keys.size() + privkeys_inout.size());\n\n    // 1. convert local multisig private keys to pub keys\n    // 2. insert to final keyset if not there yet\n    // 3. save the corresponding index of input priv key set for later reference\n    std::unordered_map<crypto::public_key, std::size_t> own_keys_mapping;\n\n    for (std::size_t multisig_keys_index{0}; multisig_keys_index < privkeys_inout.size(); ++multisig_keys_index)\n    {\n      crypto::public_key pubkey;\n      CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(privkeys_inout[multisig_keys_index], pubkey), \"Failed to derive public key\");\n\n      own_keys_mapping[pubkey] = multisig_keys_index;\n\n      final_keys.push_back(pubkey);\n    }\n\n    // sort input final keys for computing aggregation coefficients (lowest to highest)\n    // note: input should be sanitized (no duplicates)\n    std::sort(final_keys.begin(), final_keys.end());\n    CHECK_AND_ASSERT_THROW_MES(std::adjacent_find(final_keys.begin(), final_keys.end()) == final_keys.end(),\n        \"Unexpected duplicate found in input list.\");\n\n    // key aggregation\n    rct::key aggregate_key = rct::identity();\n\n    for (const crypto::public_key &key : final_keys)\n    {\n      // get aggregation coefficient\n      rct::key coeff = compute_multisig_aggregation_coefficient(final_keys, key);\n\n      // convert private key if possible\n      // note: retain original priv key index in input list, in case order matters upstream\n      auto found_key = own_keys_mapping.find(key);\n      if (found_key != own_keys_mapping.end())\n      {\n        // k_agg = coeff*k_base\n        sc_mul((unsigned char*)&(privkeys_inout[found_key->second]),\n          coeff.bytes,\n          (const unsigned char*)&(privkeys_inout[found_key->second]));\n\n        CHECK_AND_ASSERT_THROW_MES(privkeys_inout[found_key->second] != crypto::null_skey,\n          \"Multisig privkey with aggregation coefficient unexpectedly null.\");\n      }\n\n      // convert public key (pre-merge operation)\n      // K_agg = coeff*K_base\n      rct::key converted_pubkey = rct::scalarmultKey(rct::pk2rct(key), coeff);\n\n      // build aggregate key (merge operation)\n      rct::addKeys(aggregate_key, aggregate_key, converted_pubkey);\n    }\n\n    return rct::rct2pk(aggregate_key);\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: multisig_kex_make_round_keys - Makes a kex round's keys.\n  *    - Involves DH exchanges with pubkeys provided by other participants.\n  *    - Conserves mapping [pubkey -> DH derivation] : [origin keys of participants that share this secret with you].\n  * param: base_privkey - account's base private key, for performing DH exchanges and signing messages\n  * param: pubkey_origins_map - map between pubkeys to produce DH derivations with and identity keys of\n  *    participants who will share each derivation with you\n  * outparam: derivation_origins_map_out - map between DH derivations (shared secrets) and identity keys\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static void multisig_kex_make_round_keys(const crypto::secret_key &base_privkey,\n    multisig_keyset_map_memsafe_t pubkey_origins_map,\n    multisig_keyset_map_memsafe_t &derivation_origins_map_out)\n  {\n    // make shared secrets with input pubkeys\n    derivation_origins_map_out.clear();\n\n    for (auto &pubkey_and_origins : pubkey_origins_map)\n    {\n      // D = 8 * k_base * K_pubkey\n      // note: must be mul8 (cofactor), otherwise it is possible to leak to a malicious participant if the local\n      //       base_privkey is a multiple of 8 or not\n      // note2: avoid making temporaries that won't be memwiped\n      rct::key derivation_rct;\n      auto a_wiper = epee::misc_utils::create_scope_leave_handler([&]{\n        memwipe(&derivation_rct, sizeof(rct::key));\n      });\n\n      rct::scalarmultKey(derivation_rct, rct::pk2rct(pubkey_and_origins.first), rct::sk2rct(base_privkey));\n      rct::scalarmultKey(derivation_rct, derivation_rct, rct::EIGHT);\n\n      // retain mapping between pubkey's origins and the DH derivation\n      // note: if working on last kex round, then caller must know how to handle these derivations properly\n      derivation_origins_map_out[rct::rct2pk(derivation_rct)] = std::move(pubkey_and_origins.second);\n    }\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: check_messages_round - Check that a set of messages have an expected round number.\n  * param: expanded_msgs - set of multisig kex messages to process\n  * param: expected_round - round number the kex messages should have\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static void check_messages_round(const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::uint32_t expected_round)\n  {\n    CHECK_AND_ASSERT_THROW_MES(expanded_msgs.size() > 0, \"At least one input message expected.\");\n    const std::uint32_t round{expanded_msgs[0].get_round()};\n    CHECK_AND_ASSERT_THROW_MES(round == expected_round, \"Messages don't have the expected kex round number.\");\n\n    for (const auto &expanded_msg : expanded_msgs)\n      CHECK_AND_ASSERT_THROW_MES(expanded_msg.get_round() == round, \"All messages must have the same kex round number.\");\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: multisig_kex_msgs_sanitize_pubkeys - Sanitize multisig kex messages.\n  *    - Removes duplicates from msg pubkeys, ignores pubkeys equal to the local account's signing key,\n  *      ignores messages signed by the local account, ignores keys found in input 'exclusion set',\n  *      constructs map of pubkey:origins.\n  *    - Requires that all input msgs have the same round number.\n  *\n  *    origins = all the signing pubkeys that recommended a given pubkey found in input msgs\n  *\n  *    - If the messages' round numbers are all '1', then only the message signing pubkey is considered\n  *      'recommended'. Furthermore, the 'exclusion set' is ignored.\n  * param: own_pubkey - local account's signing key (key used to sign multisig messages)\n  * param: expanded_msgs - set of multisig kex messages to process\n  * param: exclude_pubkeys - pubkeys to exclude from output set\n  * outparam: sanitized_pubkeys_out - processed pubkeys obtained from msgs, mapped to their origins\n  * return: round number shared by all input msgs\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static std::uint32_t multisig_kex_msgs_sanitize_pubkeys(const crypto::public_key &own_pubkey,\n    const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::vector<crypto::public_key> &exclude_pubkeys,\n    multisig_keyset_map_memsafe_t &sanitized_pubkeys_out)\n  {\n    // all messages should have the same round (redundant sanity check)\n    CHECK_AND_ASSERT_THROW_MES(expanded_msgs.size() > 0, \"At least one input message expected.\");\n    const std::uint32_t round{expanded_msgs[0].get_round()};\n    check_messages_round(expanded_msgs, round);\n\n    sanitized_pubkeys_out.clear();\n\n    // get all pubkeys from input messages, add them to pubkey:origins map\n    // - origins = all the signing pubkeys that recommended a given msg pubkey\n    for (const auto &expanded_msg : expanded_msgs)\n    {\n      // ignore messages from self\n      if (expanded_msg.get_signing_pubkey() == own_pubkey)\n        continue;\n\n      // in round 1, only the signing pubkey is treated as a msg pubkey\n      if (round == 1)\n      {\n        // note: ignores duplicates\n        sanitized_pubkeys_out[expanded_msg.get_signing_pubkey()].insert(expanded_msg.get_signing_pubkey());\n      }\n      // in other rounds, only the msg pubkeys are treated as msg pubkeys\n      else\n      {\n        // copy all pubkeys from message into list\n        for (const auto &pubkey : expanded_msg.get_msg_pubkeys())\n        {\n          // ignore own pubkey\n          if (pubkey == own_pubkey)\n            continue;\n\n          // ignore pubkeys in 'ignore' set\n          if (std::find(exclude_pubkeys.begin(), exclude_pubkeys.end(), pubkey) != exclude_pubkeys.end())\n            continue;\n\n          // note: ignores duplicates\n          sanitized_pubkeys_out[pubkey].insert(expanded_msg.get_signing_pubkey());\n        }\n      }\n    }\n\n    return round;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: evaluate_multisig_kex_round_msgs - Evaluate pubkeys from a kex round in order to prepare for the next round.\n  *    - Sanitizes input msgs.\n  *    - Require uniqueness in: 'exclude_pubkeys'.\n  *    - Requires each input pubkey be recommended by 'num_recommendations = expected_round' msg signers.\n  *      - For a final multisig key to be truly 'M-of-N', each of the the private key's components must be\n  *        shared by (N - M + 1) signers.\n  *    - Requires that msgs are signed by only keys in 'signers'.\n  *    - Requires that each key in 'signers' recommends [num_signers - 2 CHOOSE (expected_round - 1)] pubkeys.\n  *      - These should be derivations each signer recommends for round 'expected_round', excluding derivations shared\n  *        with the local account.\n  *    - Requires that 'exclude_pubkeys' has [num_signers - 1 CHOOSE (expected_round - 1)] pubkeys.\n  *      - These should be derivations the local account has corresponding to round 'expected_round'.\n  * param: base_pubkey - multisig account's base public key\n  * param: expected_round - expected kex round of input messages\n  * param: signers - expected participants in multisig kex\n  * param: expanded_msgs - set of multisig kex messages to process\n  * param: exclude_pubkeys - derivations held by the local account corresponding to round 'expected_round'\n  * return: fully sanitized and validated pubkey:origins map for building the account's next kex round message\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static multisig_keyset_map_memsafe_t evaluate_multisig_kex_round_msgs(\n    const crypto::public_key &base_pubkey,\n    const std::uint32_t expected_round,\n    const std::vector<crypto::public_key> &signers,\n    const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::vector<crypto::public_key> &exclude_pubkeys)\n  {\n    // exclude_pubkeys should all be unique\n    for (auto it = exclude_pubkeys.begin(); it != exclude_pubkeys.end(); ++it)\n    {\n      CHECK_AND_ASSERT_THROW_MES(std::find(exclude_pubkeys.begin(), it, *it) == it,\n        \"Found duplicate pubkeys for exclusion unexpectedly.\");\n    }\n\n    // sanitize input messages\n    multisig_keyset_map_memsafe_t pubkey_origins_map;\n    const std::uint32_t round = multisig_kex_msgs_sanitize_pubkeys(base_pubkey, expanded_msgs, exclude_pubkeys, pubkey_origins_map);\n    CHECK_AND_ASSERT_THROW_MES(round == expected_round,\n      \"Kex messages were for round [\" << round << \"], but expected round is [\" << expected_round << \"]\");\n\n    // evaluate pubkeys collected\n    std::unordered_map<crypto::public_key, std::unordered_set<crypto::public_key>> origin_pubkeys_map;\n\n    // 1. each pubkey should be recommended by a precise number of signers\n    for (const auto &pubkey_and_origins : pubkey_origins_map)\n    {\n      // expected amount = round_num\n      // With each successive round, pubkeys are shared by incrementally larger groups,\n      //  starting at 1 in round 1 (i.e. the local multisig key to start kex with).\n      CHECK_AND_ASSERT_THROW_MES(pubkey_and_origins.second.size() == round,\n        \"A pubkey recommended by multisig kex messages had an unexpected number of recommendations.\");\n\n      // map (sanitized) pubkeys back to origins\n      for (const auto &origin : pubkey_and_origins.second)\n        origin_pubkeys_map[origin].insert(pubkey_and_origins.first);\n    }\n\n    // 2. the number of unique signers recommending pubkeys should equal the number of signers passed in (minus the local signer)\n    CHECK_AND_ASSERT_THROW_MES(origin_pubkeys_map.size() == signers.size() - 1,\n      \"Number of unique other signers does not equal number of other signers that recommended pubkeys.\");\n\n    // 3. each origin should recommend a precise number of pubkeys\n\n    // TODO: move to a 'math' library, with unit tests\n    auto n_choose_k_f =\n      [](const std::uint32_t n, const std::uint32_t k) -> std::uint32_t\n      {\n        static_assert(std::numeric_limits<std::int32_t>::digits <= std::numeric_limits<double>::digits,\n          \"n_choose_k requires no rounding issues when converting between int32 <-> double.\");\n\n        if (n < k)\n          return 0;\n\n        double fp_result = boost::math::binomial_coefficient<double>(n, k);\n\n        if (fp_result < 0)\n          return 0;\n\n        if (fp_result > std::numeric_limits<std::int32_t>::max())  // note: std::round() returns std::int32_t\n          return 0;\n\n        return static_cast<std::uint32_t>(std::round(fp_result));\n      };\n\n    // other signers: (N - 2) choose (msg_round_num - 1)\n      // - Each signer recommends keys they share with other signers.\n      // - In each round, a signer shares a key with 'round num - 1' other signers.\n      // - Since 'origins pubkey map' excludes keys shared with the local account,\n      //   only keys shared with participants 'other than local and self' will be in the map (e.g. N - 2 signers).\n      // - So other signers will recommend (N - 2) choose (msg_round_num - 1) pubkeys (after removing keys shared with local).\n      // - Each origin should have a shared key with each group of size 'round - 1'.\n      // Note: Keys shared with local are ignored to facilitate kex round boosting, where one or more signers may\n      //       have boosted the local signer (implying they didn't have access to the local signer's previous round msg).\n    const std::uint32_t expected_recommendations_others = n_choose_k_f(signers.size() - 2, round - 1);\n\n    // local: (N - 1) choose (msg_round_num - 1)\n    const std::uint32_t expected_recommendations_self = n_choose_k_f(signers.size() - 1, round - 1);\n\n    // note: expected_recommendations_others would be 0 in the last round of 1-of-N, but we return early for that case\n    CHECK_AND_ASSERT_THROW_MES(expected_recommendations_self > 0 && expected_recommendations_others > 0,\n      \"Bad num signers or round num (possibly numerical limits exceeded).\");\n\n    // check that local account recommends expected number of keys\n    CHECK_AND_ASSERT_THROW_MES(exclude_pubkeys.size() == expected_recommendations_self,\n      \"Local account did not recommend expected number of multisig keys.\");\n\n    // check that other signers recommend expected number of keys\n    for (const auto &origin_and_pubkeys : origin_pubkeys_map)\n    {\n      CHECK_AND_ASSERT_THROW_MES(origin_and_pubkeys.second.size() == expected_recommendations_others,\n        \"A pubkey recommended by multisig kex messages had an unexpected number of recommendations.\");\n\n      // 2 (continued). only expected signers should be recommending keys\n      CHECK_AND_ASSERT_THROW_MES(std::find(signers.begin(), signers.end(), origin_and_pubkeys.first) != signers.end(),\n        \"Multisig kex message with unexpected signer encountered.\");\n    }\n\n    // note: above tests implicitly detect if the total number of recommended keys is correct or not\n    return pubkey_origins_map;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: evaluate_multisig_post_kex_round_msgs - Evaluate messages for the post-kex verification round.\n  *    - Sanitizes input msgs.\n  *    - Requires that only one pubkey is recommended.\n  *    - Requires that all signers (other than self) recommend that one pubkey.\n  * param: base_pubkey - multisig account's base public key\n  * param: expected_round - expected kex round of input messages\n  * param: signers - expected participants in multisig kex\n  * param: expanded_msgs - set of multisig kex messages to process\n  * return: sanitized and validated pubkey:origins map\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static multisig_keyset_map_memsafe_t evaluate_multisig_post_kex_round_msgs(\n    const crypto::public_key &base_pubkey,\n    const std::uint32_t expected_round,\n    const std::vector<crypto::public_key> &signers,\n    const std::vector<multisig_kex_msg> &expanded_msgs)\n  {\n    // sanitize input messages\n    const std::vector<crypto::public_key> dummy;\n    multisig_keyset_map_memsafe_t pubkey_origins_map;\n    const std::uint32_t round = multisig_kex_msgs_sanitize_pubkeys(base_pubkey, expanded_msgs, dummy, pubkey_origins_map);\n    CHECK_AND_ASSERT_THROW_MES(round == expected_round,\n      \"Kex messages were for round [\" << round << \"], but expected round is [\" << expected_round << \"]\");\n\n    // evaluate pubkeys collected\n\n    // 1) there should only be two pubkeys\n    CHECK_AND_ASSERT_THROW_MES(pubkey_origins_map.size() == 2,\n      \"Multisig post-kex round messages from other signers did not all contain two pubkeys.\");\n\n    // 2) both keys should be recommended by the same set of signers\n    CHECK_AND_ASSERT_THROW_MES(pubkey_origins_map.begin()->second == (++(pubkey_origins_map.begin()))->second,\n      \"Multisig post-kex round messages from other signers did not all recommend the same pubkey pair.\");\n\n    // 3) all signers should be present in the recommendation list\n    auto origins = pubkey_origins_map.begin()->second;\n    origins.insert(base_pubkey);  //add self\n\n    CHECK_AND_ASSERT_THROW_MES(origins.size() == signers.size(),\n      \"Multisig post-kex round message origins don't line up with multisig signer set.\");\n\n    for (const crypto::public_key &signer : signers)\n    {\n      CHECK_AND_ASSERT_THROW_MES(origins.find(signer) != origins.end(),\n        \"Could not find an expected signer in multisig post-kex round messages (all signers expected).\");\n    }\n\n    return pubkey_origins_map;\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  /**\n  * INTERNAL\n  *\n  * brief: multisig_kex_process_round_msgs - Process kex messages for the active kex round.\n  *    - A wrapper around evaluate_multisig_kex_round_msgs() -> multisig_kex_make_next_msg().\n  *      - In other words, evaluate the input messages and try to make a message for the next round.\n  *    - Note: Must be called on the final round's msgs to evaluate the final key components\n  *            recommended by other participants.\n  * param: base_privkey - multisig account's base private key\n  * param: current_round - round of kex the input messages should be designed for\n  * param: threshold - threshold for multisig (M in M-of-N)\n  * param: signers - expected participants in multisig kex\n  * param: expanded_msgs - set of multisig kex messages to process\n  * param: exclude_pubkeys - keys held by the local account corresponding to round 'current_round'\n  *    - If 'current_round' is the final round, these are the local account's shares of the final aggregate key.\n  * outparam: keys_to_origins_map_out - map between round keys and identity keys\n  *    - If in the final round, these are key shares recommended by other signers for the final aggregate key.\n  *    - Otherwise, these are the local account's DH derivations for the next round.\n  *      - See multisig_kex_make_next_msg() for an explanation.\n  * return: multisig kex message for next round, or empty message if 'current_round' is the final round\n  */\n  //----------------------------------------------------------------------------------------------------------------------\n  static void multisig_kex_process_round_msgs(const crypto::secret_key &base_privkey,\n    const crypto::public_key &base_pubkey,\n    const std::uint32_t current_round,\n    const std::uint32_t threshold,\n    const std::vector<crypto::public_key> &signers,\n    const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::vector<crypto::public_key> &exclude_pubkeys,\n    multisig_keyset_map_memsafe_t &keys_to_origins_map_out)\n  {\n    check_multisig_config(current_round, threshold, signers.size());\n    const std::uint32_t kex_rounds_required{multisig_kex_rounds_required(signers.size(), threshold)};\n\n    // process messages into a [pubkey : {origins}] map\n    multisig_keyset_map_memsafe_t evaluated_pubkeys;\n\n    if (threshold == 1 && current_round == kex_rounds_required)\n    {\n      // in the last main kex round of 1-of-N, all signers share a key so the local signer doesn't care about evaluating\n      // recommendations from other signers\n    }\n    else if (current_round <= kex_rounds_required)\n    {\n      // for normal kex rounds, fully evaluate kex round messages\n      evaluated_pubkeys = evaluate_multisig_kex_round_msgs(base_pubkey,\n        current_round,\n        signers,\n        expanded_msgs,\n        exclude_pubkeys);\n    }\n    else //(current_round == kex_rounds_required + 1)\n    {\n      // for the post-kex verification round, validate the last kex round's messages\n      evaluated_pubkeys = evaluate_multisig_post_kex_round_msgs(base_pubkey,\n        current_round,\n        signers,\n        expanded_msgs);\n    }\n\n    // prepare keys-to-origins map for updating the multisig account\n    if (current_round < kex_rounds_required)\n    {\n      // normal kex round: make new keys\n      multisig_kex_make_round_keys(base_privkey, std::move(evaluated_pubkeys), keys_to_origins_map_out);\n    }\n    else if (current_round >= kex_rounds_required)\n    {\n      // last kex round: collect the key shares recommended by other signers for the final aggregate key\n      // post-kex verification round: save the keys found in input messages\n      keys_to_origins_map_out = std::move(evaluated_pubkeys);\n    }\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_account: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_account::initialize_kex_update(const std::vector<multisig_kex_msg> &expanded_msgs,\n    const std::uint32_t kex_rounds_required,\n    std::vector<crypto::public_key> &exclude_pubkeys_out)\n  {\n    if (m_kex_rounds_complete == 0)\n    {\n      // the first round of kex msgs will contain each participant's base pubkeys and ancillary privkeys\n\n      // collect participants' base common privkey shares\n      // note: duplicate privkeys are acceptable, and duplicates due to duplicate signers\n      //       will be blocked by duplicate-signer errors after this function is called\n      std::vector<crypto::secret_key> participant_base_common_privkeys;\n      participant_base_common_privkeys.reserve(expanded_msgs.size() + 1);\n\n      // add local ancillary base privkey\n      participant_base_common_privkeys.emplace_back(m_base_common_privkey);\n\n      // add other signers' base common privkeys\n      for (const auto &expanded_msg : expanded_msgs)\n      {\n        if (expanded_msg.get_signing_pubkey() != m_base_pubkey)\n        {\n          participant_base_common_privkeys.emplace_back(expanded_msg.get_msg_privkey());\n        }\n      }\n\n      // make common privkey\n      make_multisig_common_privkey(std::move(participant_base_common_privkeys), m_common_privkey);\n\n      // set common pubkey\n      CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(m_common_privkey, m_common_pubkey),\n        \"Failed to derive public key\");\n\n      // if N-of-N, then the base privkey will be used directly to make the account's share of the final key\n      if (kex_rounds_required == 1)\n      {\n        m_multisig_privkeys.clear();\n        m_multisig_privkeys.emplace_back(m_base_privkey);\n      }\n\n      // exclude all keys the local account recommends\n      // - in the first round, only the local pubkey is recommended by the local signer\n      exclude_pubkeys_out.emplace_back(m_base_pubkey);\n    }\n    else\n    {\n      // in other rounds, kex msgs will contain participants' shared keys\n\n      // ignore shared keys the account helped create for this round\n      for (const auto &shared_key_with_origins : m_kex_keys_to_origins_map)\n      {\n        exclude_pubkeys_out.emplace_back(shared_key_with_origins.first);\n      }\n    }\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_account: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_account::finalize_kex_update(const std::uint32_t kex_rounds_required,\n    multisig_keyset_map_memsafe_t result_keys_to_origins_map)\n  {\n    std::vector<crypto::public_key> next_msg_keys;\n\n    // prepare for next round (or complete the multisig account fully)\n    if (m_kex_rounds_complete == kex_rounds_required)\n    {\n      // post-kex verification round: check that the multisig pubkey and common pubkey were recommended by other signers\n      CHECK_AND_ASSERT_THROW_MES(result_keys_to_origins_map.count(m_multisig_pubkey) > 0,\n        \"Multisig post-kex round: expected multisig pubkey wasn't found in other signers' messages.\");\n      CHECK_AND_ASSERT_THROW_MES(result_keys_to_origins_map.count(m_common_pubkey) > 0,\n        \"Multisig post-kex round: expected common pubkey wasn't found in other signers' messages.\");\n\n      // save keys that should be recommended to other signers\n      // - for convenience, re-recommend the post-kex verification message once an account is complete\n      next_msg_keys.reserve(2);\n      next_msg_keys.push_back(m_multisig_pubkey);\n      next_msg_keys.push_back(m_common_pubkey);\n    }\n    else if (m_kex_rounds_complete + 1 == kex_rounds_required)\n    {\n      // finished with main kex rounds (have set of msgs to complete address)\n\n      // when 'completing the final round', result keys are other signers' shares of the final key\n      std::vector<crypto::public_key> result_keys;\n      result_keys.reserve(result_keys_to_origins_map.size());\n\n      for (const auto &result_key_and_origins : result_keys_to_origins_map)\n      {\n        result_keys.emplace_back(result_key_and_origins.first);\n      }\n\n      // compute final aggregate key, update local multisig privkeys with aggregation coefficients applied\n      m_multisig_pubkey = generate_multisig_aggregate_key(std::move(result_keys), m_multisig_privkeys);\n\n      // no longer need the account's pubkeys saved for this round (they were only used to build exclude_pubkeys)\n      // TODO: record [pre-aggregation pubkeys : origins] map for aggregation-style signing\n      m_kex_keys_to_origins_map.clear();\n\n      // save keys that should be recommended to other signers\n      // - for post-kex verification, recommend the multisig pubkeys to notify other signers that the local signer is done\n      next_msg_keys.reserve(2);\n      next_msg_keys.push_back(m_multisig_pubkey);\n      next_msg_keys.push_back(m_common_pubkey);\n    }\n    else if (m_kex_rounds_complete + 2 == kex_rounds_required)\n    {\n      // one more round (must send/receive one more set of kex msgs)\n      // - at this point, have local signer's pre-aggregation private key shares of the final address\n\n      // result keys are the local signer's DH derivations for the next round\n\n      // derivations are shared secrets between each group of N - M + 1 signers of which the local account is a member\n      // - convert them to private keys: multisig_key = H(derivation)\n      // - note: shared key = multisig_key[i]*G is recorded in the kex msg for sending to other participants\n      //   instead of the original 'derivation' value (which MUST be kept secret!)\n      m_multisig_privkeys.clear();\n      m_multisig_privkeys.reserve(result_keys_to_origins_map.size());\n\n      m_kex_keys_to_origins_map.clear();\n      next_msg_keys.reserve(result_keys_to_origins_map.size());\n\n      for (const auto &derivation_and_origins : result_keys_to_origins_map)\n      {\n        // multisig_privkey = H(derivation)\n        // derived pubkey = multisig_key * G\n        crypto::public_key_memsafe derived_pubkey;\n        m_multisig_privkeys.push_back(\n          calculate_multisig_keypair_from_derivation(derivation_and_origins.first, derived_pubkey));\n\n        // save the account's kex key mappings for this round [derived pubkey : other signers who will have the same key]\n        m_kex_keys_to_origins_map[derived_pubkey] = std::move(derivation_and_origins.second);\n\n        // save keys that should be recommended to other signers\n        // - The keys multisig_key*G are sent to other participants in the message, so they can be used to produce the final\n        //   multisig key via generate_multisig_spend_public_key().\n        next_msg_keys.push_back(derived_pubkey);\n      }\n    }\n    else  //(m_kex_rounds_complete + 3 <= kex_rounds_required)\n    {\n      // next round is an 'intermediate' key exchange round, so there is nothing special to do here\n\n      // save keys that should be recommended to other signers\n      // - Send this round's DH derivations to other participants, who will make more DH derivations for the following round.\n      next_msg_keys.reserve(result_keys_to_origins_map.size());\n\n      for (const auto &derivation_and_origins : result_keys_to_origins_map)\n        next_msg_keys.push_back(derivation_and_origins.first);\n\n      // save the account's kex keys for this round [DH derivation : other signers who should have the same derivation]\n      m_kex_keys_to_origins_map = std::move(result_keys_to_origins_map);\n    }\n\n    // a full set of msgs has been collected and processed, so the 'round is complete'\n    ++m_kex_rounds_complete;\n\n    // make next round's message (or reproduce the post-kex verification round if kex is complete)\n    m_next_round_kex_message = multisig_kex_msg{\n      (m_kex_rounds_complete > kex_rounds_required ? kex_rounds_required : m_kex_rounds_complete) + 1,\n      m_base_privkey,\n      std::move(next_msg_keys)}.get_msg();\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n  // multisig_account: INTERNAL\n  //----------------------------------------------------------------------------------------------------------------------\n  void multisig_account::kex_update_impl(const std::vector<multisig_kex_msg> &expanded_msgs)\n  {\n    // check messages are for the expected kex round\n    check_messages_round(expanded_msgs, m_kex_rounds_complete + 1);\n\n    // check kex round count\n    const std::uint32_t kex_rounds_required{multisig_kex_rounds_required(m_signers.size(), m_threshold)};\n\n    CHECK_AND_ASSERT_THROW_MES(kex_rounds_required > 0, \"Multisig kex rounds required unexpectedly 0.\");\n    CHECK_AND_ASSERT_THROW_MES(m_kex_rounds_complete < kex_rounds_required + 1,\n      \"Multisig kex has already completed all required rounds (including post-kex verification).\");\n\n    // initialize account update\n    std::vector<crypto::public_key> exclude_pubkeys;\n    initialize_kex_update(expanded_msgs, kex_rounds_required, exclude_pubkeys);\n\n    // process messages into a [pubkey : {origins}] map\n    multisig_keyset_map_memsafe_t result_keys_to_origins_map;\n    multisig_kex_process_round_msgs(\n      m_base_privkey,\n      m_base_pubkey,\n      m_kex_rounds_complete + 1,\n      m_threshold,\n      m_signers,\n      expanded_msgs,\n      exclude_pubkeys,\n      result_keys_to_origins_map);\n\n    // finish account update\n    finalize_kex_update(kex_rounds_required, std::move(result_keys_to_origins_map));\n  }\n  //----------------------------------------------------------------------------------------------------------------------\n} //namespace multisig\n", "meta": {"hexsha": "bf6aa274a78ace5ab4db139f2dc82a75b49bc473", "size": 41727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multisig/multisig_account_kex_impl.cpp", "max_stars_repo_name": "Snider/blockchain", "max_stars_repo_head_hexsha": "64a856edc03f2e0b52a1c4475f16f60b5e20acc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multisig/multisig_account_kex_impl.cpp", "max_issues_repo_name": "Snider/blockchain", "max_issues_repo_head_hexsha": "64a856edc03f2e0b52a1c4475f16f60b5e20acc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multisig/multisig_account_kex_impl.cpp", "max_forks_repo_name": "Snider/blockchain", "max_forks_repo_head_hexsha": "64a856edc03f2e0b52a1c4475f16f60b5e20acc9", "max_forks_repo_licenses": ["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.5169491525, "max_line_length": 158, "alphanum_fraction": 0.6629280801, "num_tokens": 9376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.017712296370081107, "lm_q1q2_score": 0.007483527567155325}}
{"text": "//\n// Created by veyry_p on 7/11/15.\n//\n\n#include <iostream>\n#include <chrono>\n#include <numeric>\n#include <SFML/Graphics/Sprite.hpp>\n#include <SFML/Graphics/Texture.hpp>\n#include <SFML/Graphics/RectangleShape.hpp>\n#include <SFML/Graphics/RenderTexture.hpp>\n#include <tbb/tbb.h>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n#include \"strong-classifier.h\"\n#include \"../features/four-rectangles-feature.h\"\n#include \"../features/three-horizontal-rectangles-feature.h\"\n#include \"../config.h\"\n#include \"../features/two-vertical-rectangles-feature.h\"\n#include \"../features/two-horizontal-rectangles-feature.h\"\n#include \"../features/three-vertical-rectangles-feature.h\"\n\nstatic tbb::mutex mutex;\nnamespace violajones\n{\n  StrongClassifier::StrongClassifier(std::vector<WeakClassifier> classifiers)\n          : classifiers_{classifiers}\n  {\n    long double galpha = 0;\n    for (auto& classifier : classifiers)\n      galpha += classifier.alpha_;\n\n    global_alpha_ = galpha;\n  }\n\n  bool StrongClassifier::check(Window win, std::shared_ptr<IntegralImage> image)\n  {\n    long double sumvalues = 0.0;\n    for (auto& weakclass : classifiers_)\n      sumvalues += weakclass.get_value(win, image);\n\n    bool tmp = sumvalues >= (global_alpha_ / 2.0);\n    if (Config::debug_classifier_check)\n      std::cout << \"StrongClassifier::check \" << tmp\n      << \" - sumvalues: \" << sumvalues\n      << \" global_alpha: \" << global_alpha_ << std::endl;\n\n    return tmp;\n  }\n\n  void StrongClassifier::save(std::string path)\n  {\n    std::ofstream fs;\n    fs.open(path);\n    for (auto& classif : classifiers_)\n      fs << classif.alpha_ << \" \"\n      << classif.threshold_ << \" \"\n      << (int)classif.parity_ << \" \"\n      << classif.feature_->get_type() << \" \"\n      << classif.feature_->frame.top_left.x << \" \"\n      << classif.feature_->frame.top_left.y << \" \"\n      << classif.feature_->frame.width << \" \"\n      << classif.feature_->frame.height << std::endl;\n    fs.close();\n  }\n\n  StrongClassifier StrongClassifier::load_from_file(std::string path)\n  {\n    std::function<WeakClassifier(std::string&)> restore_classifier =\n            [](std::string& s) {\n              std::vector<std::string> tokens;\n              boost::split(tokens, s, boost::is_any_of(\" ;\"));\n              double alpha = std::stod(tokens[0]);\n              int threshold = std::stoi(tokens[1]);\n              char parity = (char) std::stoi(tokens[2]);\n              std::string feature_type = tokens[3];\n\n              int featurex = std::stoi(tokens[4]);\n              int featurey = std::stoi(tokens[5]);\n              int featurewidth = std::stoi(tokens[6]);\n              int featureheight = std::stoi(tokens[7]);\n\n              Rectangle feature_frame(Point(featurex, featurey), featurewidth, featureheight);\n              if (feature_type == \"FourRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity, std::make_shared<FourRectanglesFeature>(feature_frame));\n              else if (feature_type == \"ThreeHorizontalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<ThreeHorizontalRectanglesFeature>(feature_frame));\n              else if (feature_type == \"ThreeVerticalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<ThreeVerticalRectanglesFeature>(feature_frame));\n              else if (feature_type == \"TwoHorizontalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<TwoHorizontalRectanglesFeature>(feature_frame));\n              else if (feature_type == \"TwoVerticalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<TwoVerticalRectanglesFeature>(feature_frame));\n\n              std::cerr << \"Fatal Error: feature_type \" << feature_type << std::endl;\n              return WeakClassifier(alpha, threshold, parity, std::make_shared<FourRectanglesFeature>(feature_frame));\n            };\n\n    std::ifstream infile(path);\n    std::string line;\n    std::vector<WeakClassifier> classifiers;\n    while (std::getline(infile, line))\n      classifiers.push_back(restore_classifier(line));\n    return StrongClassifier(classifiers);\n  }\n\n  StrongClassifier StrongClassifier::train(std::string tests_dir)\n  {\n    std::cout << \"Initializing Trainer ...\\n\"\n    << \"Loading trainer tests ...\" << std::endl;\n    auto start = std::chrono::steady_clock::now();\n    auto tests_set = load_tests_set(tests_dir);\n    auto& tests = tests_set.first;\n    auto& features_values = tests_set.second;\n\n\n    tbb::atomic<unsigned long> ncached_features = 0;\n\n\n    if (Config::parallelized)\n      tbb::parallel_for_each(features_values.begin(), features_values.end(),\n                             [&ncached_features](FeatureValues& ftvalues) {\n                               if (ftvalues.values_.size())\n                                 ++ncached_features;\n                             });\n    else\n      for (FeatureValues& ftvalues : features_values)\n        if (ftvalues.values_.size())\n          ++ncached_features;\n\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double> diff = end - start;\n    std::cout << \"Tests loaded in \" << diff.count() << \" seconds (\"\n    << ncached_features * 100 / features_values.size()\n    << \"% cached)\\n Launching training...\" << std::endl;\n\n    std::vector<WeakClassifier> classifiers;\n    unsigned ipass = 1;\n    auto global_start = std::chrono::steady_clock::now();\n    while (ipass <= Config::learn_pass)\n    {\n      start = std::chrono::steady_clock::now();\n      std::cout << ipass << \"/\" << Config::learn_pass << \" trainer pass...\" << std::endl;\n      double weightsum = std::accumulate(tests.begin(), tests.end(), 0.0,\n                                         [](double acc, TestImage& t) { return t.weight_ + acc; });\n\n      double validweight = 0.0;\n      for (size_t i = 0; i < tests.size(); ++i)\n      {\n        tests[i].weight_ = tests[i].weight_ / weightsum;\n        if (tests[i].valid_)\n          validweight += tests[i].weight_;\n      }\n\n\n      TestWeakClassifier best(features_values[0], 0, 1, std::numeric_limits<double>::max());\n      if (Config::parallelized)\n      {\n        tbb::parallel_for_each(features_values.begin(), features_values.end(),\n                               [&](FeatureValues& fv) {\n                                 auto new_classifier = TestWeakClassifier::train(tests, validweight, fv);\n                                 tbb::mutex::scoped_lock lock;\n                                 lock.acquire(mutex);\n                                 if (best.errors_ > new_classifier.errors_)\n                                   best = new_classifier;\n                                 lock.release();\n                               });\n      }\n      else\n        std::for_each(features_values.begin(), features_values.end(),\n                      [&](FeatureValues& fv) {\n                        auto new_classifier = TestWeakClassifier::train(tests, validweight, fv);\n                        if (best.errors_ > new_classifier.errors_)\n                          best = new_classifier;\n                      });\n\n      end = std::chrono::steady_clock::now();\n      diff = end - start;\n\n      std::cout << \"New weak classifier selected in \" << diff.count() << \" seconds (error score : \"\n      << best.errors_ << \")\\n\"\n      << \"X: \" << best.feature_.feature_->frame.top_left.x\n      << \" Y: \" << best.feature_.feature_->frame.top_left.y\n      << \" - Width: \" << best.feature_.feature_->frame.width\n      << \" Height: \" << best.feature_.feature_->frame.height << std::endl;\n\n      double beta = best.errors_ / (1.0 - best.errors_);\n      if (beta < 1.0 / 100000000)\n        beta = 1.0 / 100000000;\n\n      for (FeatureValue& featurevalue : best.feature_.values_)\n        if (best.check(featurevalue.value_) == tests[featurevalue.test_index_].valid_)\n          tests[featurevalue.test_index_].weight_ *= beta;\n\n      auto alpha = std::log(1.0 / beta);\n      classifiers.push_back(best.get_classifier(alpha));\n      ++ipass;\n    }\n\n    auto global_end = std::chrono::steady_clock::now();\n    diff = global_end - global_start;\n    std::cout << \"Training finished in \" << diff.count()\n    << \" secs.\" << std::endl;\n    return StrongClassifier(classifiers);\n  }\n\n  std::pair<std::vector<TestImage>,\n          std::vector<FeatureValues> > StrongClassifier::load_tests_set(std::string tests_dir)\n  {\n    std::string gooddir = tests_dir + \"/good\";\n    std::string baddir = tests_dir + \"/bad\";\n    auto good = load_images(gooddir);\n    auto bad = load_images(baddir);\n\n    double goodweight = 1.0 / (2 * good.size());\n    double badweight = 1.0 / (2 * bad.size());\n\n    std::vector<TestImage> tests;\n    for (size_t i = 0; i < good.size(); ++i)\n      tests.push_back(TestImage(*good[i], goodweight, true));\n\n    for (auto i = good.size(); i < good.size() + bad.size(); ++i)\n      tests.push_back(TestImage(*bad[i - good.size()], badweight, false));\n\n    auto features_values = compute_features_values(tests);\n    return std::pair<std::vector<TestImage>, std::vector<FeatureValues>>(tests, features_values);\n  }\n\n  std::vector<FeatureValues> StrongClassifier::compute_features_values(std::vector<TestImage> tests)\n  {\n    std::vector<std::shared_ptr<Feature> > features = Window::list_features();\n    std::vector<FeatureValues> features_values;\n    for (size_t i = 0; i < features.size(); ++i)\n    {\n      auto values = FeatureValue::compute_all_values_sorted(tests, *features[i]);\n      features_values.push_back(FeatureValues(features[i], values));\n    }\n    return features_values;\n  }\n\n  std::shared_ptr<GreyImage> StrongClassifier::load_image(std::string imagepath)\n  {\n    sf::Image sfimage;\n    sfimage.loadFromFile(imagepath);\n    if (sfimage.getSize().x != Config::window_width || sfimage.getSize().y != Config::window_height)\n    {\n      std::cerr << \"Invalid image size (must be \"\n      << Config::window_width << \"*\"\n      << Config::window_height << \"): \"\n      << imagepath << std::endl;\n      exit(1);\n    }\n    return std::make_shared<GreyImage>(GreyImage(sfimage));\n  }\n\n  tbb::concurrent_vector<std::shared_ptr<GreyImage>> StrongClassifier::load_images(std::string dir)\n  {\n    namespace fs = boost::filesystem;\n    fs::path path(dir);\n    fs::directory_iterator end_itr;\n    tbb::concurrent_vector<std::shared_ptr<GreyImage>> images;\n\n    size_t number_loaded = 0;\n    if (Config::parallelized)\n    {\n      std::vector<std::string> strings;\n      for (fs::directory_iterator iter(path);\n           iter != end_itr && (number_loaded < Config::number_load || !Config::number_load);\n           ++iter, ++number_loaded)\n        if (fs::is_regular_file(iter->status()))\n          strings.push_back(iter->path().string());\n\n      tbb::parallel_for_each(strings.begin(), strings.end(),\n                             [&](std::string string) {\n                               images.push_back(load_image(string));\n                             });\n    }\n    else if (fs::exists(path) && fs::is_directory(path))\n      for (fs::directory_iterator iter(path);\n           iter != end_itr && (number_loaded < Config::number_load || !Config::number_load);\n           ++iter, ++number_loaded)\n        if (fs::is_regular_file(iter->status()))\n          images.push_back(load_image(iter->path().string()));\n\n    std::cout << \"Loaded \" << images.size() << \" in \" << dir << std::endl;\n    if (!images.size())\n    {\n      std::cerr << \"Error: no images has been loaded from: \" << dir << std::endl;\n      exit(0);\n    }\n\n    return images;\n  }\n}", "meta": {"hexsha": "4e085457c90663881e4660f88b8a702fe8d8b245", "size": 11747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trainer/strong-classifier.cpp", "max_stars_repo_name": "hasB4K/FaceDetection", "max_stars_repo_head_hexsha": "77067dfb100c3bcd63d196002efc6ed41c4cf69f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-05-10T14:14:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-17T04:18:14.000Z", "max_issues_repo_path": "src/trainer/strong-classifier.cpp", "max_issues_repo_name": "hasB4K/FaceDetection", "max_issues_repo_head_hexsha": "77067dfb100c3bcd63d196002efc6ed41c4cf69f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/trainer/strong-classifier.cpp", "max_forks_repo_name": "hasB4K/FaceDetection", "max_forks_repo_head_hexsha": "77067dfb100c3bcd63d196002efc6ed41c4cf69f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T08:10:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T08:10:01.000Z", "avg_line_length": 39.4194630872, "max_line_length": 120, "alphanum_fraction": 0.5999829744, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.016914915465848824, "lm_q1q2_score": 0.0074708615543645105}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_ALGEBRA_TYPE_TRAITS_HPP\n#define CRYPTO3_ALGEBRA_TYPE_TRAITS_HPP\n\n#include <complex>\n\n#include <boost/type_traits.hpp>\n#include <boost/tti/tti.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/type_traits/is_same.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace algebra {\n\n            using namespace boost::mpl::placeholders;\n\n            BOOST_TTI_HAS_TYPE(iterator)\n            BOOST_TTI_HAS_TYPE(const_iterator)\n\n            BOOST_TTI_HAS_TYPE(extension_policy)\n            BOOST_TTI_HAS_TYPE(curve_type)\n            BOOST_TTI_HAS_TYPE(field_type)\n            BOOST_TTI_HAS_TYPE(value_type)\n            BOOST_TTI_HAS_TYPE(integral_type)\n            BOOST_TTI_HAS_TYPE(base_field_type)\n            BOOST_TTI_HAS_TYPE(modular_type)\n            BOOST_TTI_HAS_TYPE(scalar_field_type)\n            BOOST_TTI_HAS_TYPE(g1_type)\n            BOOST_TTI_HAS_TYPE(g2_type)\n            BOOST_TTI_HAS_TYPE(gt_type)\n\n            BOOST_TTI_HAS_TYPE(group_type)\n\n            BOOST_TTI_HAS_STATIC_MEMBER_DATA(value_bits)\n            BOOST_TTI_HAS_STATIC_MEMBER_DATA(modulus_bits)\n            BOOST_TTI_HAS_STATIC_MEMBER_DATA(base_field_modulus)\n            BOOST_TTI_HAS_STATIC_MEMBER_DATA(scalar_field_modulus)\n            BOOST_TTI_HAS_STATIC_MEMBER_DATA(arity)\n            BOOST_TTI_HAS_STATIC_MEMBER_DATA(p)\n            BOOST_TTI_HAS_STATIC_MEMBER_DATA(q)\n\n            BOOST_TTI_HAS_FUNCTION(to_affine)\n            BOOST_TTI_HAS_FUNCTION(to_special)\n            BOOST_TTI_HAS_FUNCTION(is_special)\n\n            BOOST_TTI_HAS_STATIC_MEMBER_FUNCTION(zero)\n            BOOST_TTI_HAS_STATIC_MEMBER_FUNCTION(one)\n            BOOST_TTI_HAS_FUNCTION(is_zero)\n            BOOST_TTI_HAS_FUNCTION(is_well_formed)\n            BOOST_TTI_HAS_FUNCTION(doubled)\n\n            template<typename T>\n            struct is_curve {\n                static const bool value = has_type_base_field_type<T>::value && has_type_scalar_field_type<T>::value &&\n                                          has_type_g1_type<T>::value && has_type_g2_type<T>::value &&\n                                          has_type_gt_type<T>::value;\n                typedef T type;\n            };\n\n            // TODO: we should add some other params to curve group policy to identify it more clearly\n            template<typename T>\n            struct is_curve_group {\n                static const bool value = has_type_value_type<T>::value && has_type_field_type<T>::value &&\n                                          has_static_member_data_value_bits<T, const std::size_t>::value &&\n                                          has_type_curve_type<T>::value;\n                typedef T type;\n            };\n\n            template<typename T>\n            struct is_field {\n                static const bool value =\n                    has_type_value_type<T>::value && has_static_member_data_value_bits<T, const std::size_t>::value &&\n                    has_type_integral_type<T>::value &&\n                    has_static_member_data_modulus_bits<T, const std::size_t>::value &&\n                    has_type_modular_type<T>::value && has_static_member_data_arity<T, const std::size_t>::value;\n                typedef T type;\n            };\n\n            template<typename T>\n            struct is_extended_field {\n                static const bool value = has_type_value_type<T>::value &&\n                                          has_static_member_data_value_bits<T, const std::size_t>::value &&\n                                          has_type_integral_type<T>::value &&\n                                          has_static_member_data_modulus_bits<T, const std::size_t>::value &&\n                                          has_type_modular_type<T>::value &&\n                                          has_static_member_data_modulus_bits<T, const std::size_t>::value &&\n                                          has_type_extension_policy<T>::value;\n                typedef T type;\n            };\n\n            template<typename T>\n            struct is_group_element{\n                static const bool value = has_type_field_type<T>::value && \n                                          has_type_group_type<T>::value &&\n                                          has_static_member_function_zero<T, T>::value && \n                                          has_static_member_function_one<T, T>::value && \n                                          has_function_is_zero<T, bool>::value && \n                                          has_function_is_well_formed<T, bool>::value && \n                                          has_function_doubled<T, T>::value;\n            };\n\n            template<typename T>\n            struct is_g1_group_element {\n                static const bool value =\n                    boost::is_same<typename T::group_type::curve_type::template g1_type<typename T::coordinates,\n                        typename T::form>, typename T::group_type>::value;\n            };\n\n            template<typename T>\n            struct is_g2_group_element {\n                static const bool value =\n                    boost::is_same<typename T::group_type::curve_type::template g2_type<typename T::coordinates,\n                        typename T::form>, typename T::group_type>::value;\n            };\n\n            template<typename T>\n            struct is_complex : std::false_type { };\n            template<typename T>\n            struct is_complex<std::complex<T>> : std::true_type { };\n            template<typename T>\n            constexpr bool is_complex_v = is_complex<T>::value;\n\n            template<typename T>\n            struct remove_complex {\n                using type = T;\n            };\n            template<typename T>\n            struct remove_complex<std::complex<T>> {\n                using type = T;\n            };\n            template<typename T>\n            using remove_complex_t = typename remove_complex<T>::type;\n        }    // namespace algebra\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ALGEBRA_TYPE_TRAITS_HPP\n", "meta": {"hexsha": "161096f7cfd21f431b8b806d1db16b503a8c4649", "size": 7442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/algebra/include/nil/crypto3/algebra/type_traits.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/algebra/include/nil/crypto3/algebra/type_traits.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/algebra/include/nil/crypto3/algebra/type_traits.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": 45.6564417178, "max_line_length": 119, "alphanum_fraction": 0.5804891158, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.017176712376886664, "lm_q1q2_score": 0.0074543747978365275}}
{"text": "#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/serialization/string.hpp>\n#include <boost/serialization/base_object.hpp>\n\n#include \"ProgramBddContext.hpp\"\n\n#include \"glog/logging.h\"\n#include \"buddy/fdd.h\"\n\n#include <cstdlib>\n#include <ctime>\n\n#include <boost/lexical_cast.hpp>\n\nusing namespace std;\nusing namespace  wali::domains::binrel;\n\n// ////////////////////////////////////////\n//     TRASH IN --- TRASH OUT            //\n// ////////////////////////////////////////\n\nusing namespace wali::domains::binrel;\n\nnamespace wali\n{\n  namespace domains\n  {\n    namespace binrel\n    {\n      extern RevBddContext idx2Name;\n    }\n  }\n}\n\n\nnamespace details\n{\n  void\n  interleave_all_fdds()\n  {\n    vector<int> new_order;\n\n    for (int bit_num=0; bit_num<bdd_varnum(); ++bit_num) {\n      for (int fdd_num=0; fdd_num<fdd_domainnum(); ++fdd_num) {\n        if (bit_num < fdd_varnum(fdd_num)) {\n          int * vars = fdd_vars(fdd_num);\n          new_order.push_back(vars[bit_num]);\n        }\n      }\n    }\n\n    assert(new_order.size() == static_cast<size_t>(bdd_varnum()));\n\n    bdd_setvarorder(&new_order[0]);\n  }\n\n  \n  std::map<int, std::string>\n  get_partial_mapping_for_fdd(std::string const & basename, int fdd_no)\n  {\n    int num_bits = fdd_varnum(fdd_no);\n    int * var_nums = fdd_vars(fdd_no); // [0] = lsb\n    std::map<int, std::string> ret;\n\n    for (int i=0; i<num_bits; ++i) {\n      ret[var_nums[i]] =\n        basename + \"_\" + boost::lexical_cast<std::string>(i)\n        + \"(\" + boost::lexical_cast<std::string>(var_nums[i]) + \")\";\n    }\n\n    return ret;\n  }\n\n\n  void accumulate(std::map<int, std::string> & out,\n                  std::map<int, std::string> const & more)\n  {\n    for (std::map<int, std::string>::const_iterator iter = more.begin();\n         iter != more.end(); ++iter)\n    {\n      bool added = out.insert(*iter).second;\n      assert(added);\n    }\n  }\n\n  \n  std::map<int, std::string>\n  get_partial_mapping_for_var(std::string const & name, BddInfo const & info)\n  {\n    std::map<int, std::string> vars;\n    accumulate(vars, get_partial_mapping_for_fdd(name, info.baseLhs));\n    accumulate(vars, get_partial_mapping_for_fdd(name + \"\\'\", info.baseRhs));\n    accumulate(vars, get_partial_mapping_for_fdd(name + \"\\'\\'\", info.baseExtra));\n    accumulate(vars, get_partial_mapping_for_fdd(name + \"_t1\", info.tensor1Lhs));\n    accumulate(vars, get_partial_mapping_for_fdd(name + \"_t1\\'\", info.tensor1Rhs));\n    accumulate(vars, get_partial_mapping_for_fdd(name + \"_t1\\'\\'\", info.tensor1Extra));\n    accumulate(vars, get_partial_mapping_for_fdd(name + \"_t2\", info.tensor2Lhs));\n    accumulate(vars, get_partial_mapping_for_fdd(name + \"_t2\\'\", info.tensor2Rhs));    \n    accumulate(vars, get_partial_mapping_for_fdd(name + \"_t2\\'\\'\", info.tensor2Extra));\n    return vars;\n  }\n\n  \n  std::map<int, std::string>\n  get_mapping()\n  {\n    std::map<int, std::string> mapping;\n    for (RevBddContext::const_iterator iter = idx2Name.begin(); iter != idx2Name.end(); ++iter)\n    {\n      accumulate(mapping, get_partial_mapping_for_fdd(iter->second, iter->first));\n    }\n    return mapping;\n  }\n  \n  \n  void\n  print_bdd_variable_order(std::ostream & os)\n  {\n    std::map<int, std::string> var_num_to_name = get_mapping();\n\n    int num = bdd_varnum();\n    for (int i=0; i<num; ++i) {\n      os << \"  \" << i << \": \" << var_num_to_name[bdd_level2var(i)] << \"\\n\";\n    }\n    os << \"\\n\";\n  }\n\n  \n  bdd make_bdd_high_bits_zero(int fdd_no, int fdd_vars[], int start_at_bit)\n  {\n    int total_bits = fdd_varnum(fdd_no);\n\n    bdd ret = bddtrue;\n    for (int bit = start_at_bit; bit < total_bits; ++bit) {\n      int result_var = fdd_vars[bit];\n      ret = ret & bdd_nithvar(result_var);\n    }\n    return ret;\n  }\n\n\n  bdd make_adder_box(int in1_varno, int in2_varno, int out_varno,\n                     bdd t0, bdd t1, bdd t2, bool inv)\n  {\n    bdd a = bdd_ithvar(in1_varno);\n    bdd b = bdd_ithvar(in2_varno);\n    bdd c = bdd_ithvar(out_varno);\n\n    if (inv) {\n      // If there's a carry in, then the result is the opposite of what it\n      // \"should\" be.\n      c = !c;\n\n      // Furthermore, if a+b=1, we carry to the next bit.\n      t1 = t2;\n    }\n\n    // The following is a truth-table for a 1-bit adder, which also conjoins\n    // in the appropriate box from the next level.\n    return ((   a  &   b  & (!c) & t2)\n            |(  a  & (!b) &   c  & t1)\n            |((!a) &   b  &   c  & t1)\n            |((!a) & (!b) & (!c) & t0));\n  }\n\n  \n  bdd make_adder(int fdd_lhs, int fdd_rhs, int fdd_result, int num_bits)\n  {\n    //int num_bits = fdd_varnum(fdd_lhs);\n    //assert(num_bits == fdd_varnum(fdd_rhs));\n    //assert(num_bits == fdd_varnum(fdd_result));\n\n    //std::cerr << \"  make_adder: num_bits is \" << num_bits << \"\\n\";\n    //std::cerr << \"              lhs fdd has \" << fdd_varnum(fdd_lhs) << \" vars\\n\";\n    //std::cerr << \"              rhs fdd has \" << fdd_varnum(fdd_rhs) << \" vars\\n\";\n    //std::cerr << \"              result fdd has \" << fdd_varnum(fdd_result) << \" vars\\n\";    \n\n    int * lhs_vars = fdd_vars(fdd_lhs);\n    int * rhs_vars = fdd_vars(fdd_rhs);\n    int * result_vars = fdd_vars(fdd_result);\n\n    bdd left_box = bddtrue;\n    bdd right_box = bddtrue;\n\n    for (int level=0; level<num_bits; ++level) {\n      // IMPORTANT: level counts from 0=msb to num_bits-1=lsb. However,\n      // *_vars have index 0 as the lsb.\n      int lhs_var = lhs_vars[num_bits-1 - level];\n      int rhs_var = rhs_vars[num_bits-1 - level];\n      int result_var = result_vars[num_bits-1 - level];\n\n      bdd new_left_box = make_adder_box(lhs_var, rhs_var, result_var,\n                                        left_box, left_box, right_box, false);\n      bdd new_right_box = make_adder_box(lhs_var, rhs_var, result_var,\n                                         left_box, right_box, right_box, true);\n\n      left_box = new_left_box;\n      right_box = new_right_box;\n    }\n\n    bdd high_bits_zero = make_bdd_high_bits_zero(fdd_lhs, lhs_vars, num_bits)\n                         & make_bdd_high_bits_zero(fdd_rhs, rhs_vars, num_bits)\n                         & make_bdd_high_bits_zero(fdd_result, result_vars, num_bits);\n\n    return left_box & high_bits_zero;\n  }\n\n  \n  // http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/\n  bool is_power_of_two(unsigned x)\n  {\n    return ((x != 0) && ((x & (~x + 1)) == x));\n  }\n\n  \n  int log2_ceiling(unsigned x)\n  {\n    int num_shifts = 0;\n    while ((1u << num_shifts) <= x) {\n      ++num_shifts;\n    }\n    return num_shifts;\n  }\n}\n\n\n// ////////////////////////////////////////////////////////////////////////////\n// The interface assumes that the google logging library is initialized before\n// calling any of its functions.\n\nProgramBddContext::~ProgramBddContext()\n{\n  regAInfo = regBInfo = NULL;\n  baseId = bddtrue;\n  BinRel::reset();\n}\n\nvoid ProgramBddContext::addBoolVar(std::string name)\n{\n  addIntVar(name,2);\n}\n\nvoid ProgramBddContext::setIntVars(const std::map<std::string, int>& inflatvars)\n{\n  // copy inflatvars because we mess with it.\n  std::map<std::string, int> flatvars = inflatvars;\n  \n  // Remember creation history\n  CreationCall cc;\n  cc.cf = SET_INT_MAP;\n  cc.arg.push_back(flatvars);\n  creationHistory.push_back(cc);\n  \n  // Add extra variables at the end of the variables passed in.\n  unsigned size = 0;\n  for(std::map<std::string, int>::const_iterator ci = flatvars.begin(); ci != flatvars.end(); ++ci)\n    size = ((unsigned) ci->second) > size ? ci->second : size;\n  size = size < 2 ? 2 : size; // The least size handled is 2. There must be at least one bool variable.\n  maxSize = size;\n  flatvars[\"__regA\"] = size;\n  flatvars[\"__regB\"] = size;\n  flatvars[\"__regSize\"] = size + 1; //only baseLhs will be used. Rest of the levels will be wasted. Ah, what the hell!\n\n  std::vector<std::map<std::string, int> > vars;\n  vars.push_back(flatvars);\n\n  createIntVars(vars);\n\n  //createExtraVars(); <-- not needed.\n  // Now extract the information about extra variables.\n  regAInfo = (*this)[\"__regA\"];\n  regBInfo = (*this)[\"__regB\"];\n  bddinfo_t regSizeInfo = (*this)[\"__regSize\"];\n  sizeInfo = regSizeInfo->baseLhs;\n  // Now delete entries for these extra variables from the vocabulary.\n  this->erase(this->find(\"__regA\"));\n  this->erase(this->find(\"__regB\"));\n  this->erase(this->find(\"__regSize\")); //will get deleted because no one references it anymore.\n\n  //details::interleave_all_fdds(); //speeds up ProgramBddContext operations.\n  BddContext::setupCachedBdds();\n  setupCachedBdds();\n}\n\n\nvoid ProgramBddContext::setIntVars(const std::vector<std::map<std::string, int> >& vars)\n{\n  //Remember Creation history\n  CreationCall cc;\n  cc.cf = SET_INT_VECT;\n  for(vector< map< string, int > >::const_iterator cit = vars.begin(); cit != vars.end(); ++cit)\n    cc.arg.push_back(*cit);\n  creationHistory.push_back(cc);\n\n  createIntVars(vars);\n  createExtraVars();\n  BddContext::setupCachedBdds();\n  setupCachedBdds();\n}\n\nvoid ProgramBddContext::createExtraVars()\n{\n  // Compute the size of register needed.\n  unsigned size = 0;\n  for(std::map<const std::string, bddinfo_t>::const_iterator ci = this->begin(); ci != this->end(); ++ci)\n    size = ci->second->maxVal > size ? ci->second->maxVal : size;\n  size = size < 2 ? 2 : size; // The least size handled is 2. There must be at least one bool variable.\n  maxSize = size;\n\n  // Now create some buddy levels for scratchpad\n  int isize = (int) size;\n  int domains[7] = {isize + 1, isize, isize, isize, isize, isize, isize};\n  int base = fdd_extdomain(domains,7);\n\n  // Now create the corresponding bddinfo\n  sizeInfo = (unsigned) base++;\n  regAInfo = new BddInfo();\n  regAInfo->baseLhs = (unsigned) base++;\n  regAInfo->baseRhs = (unsigned) base++;\n  regAInfo->baseExtra = (unsigned) base++;\n\n  regBInfo = new BddInfo();\n  regBInfo->baseLhs = (unsigned) base++;\n  regBInfo->baseRhs = (unsigned) base++;\n  regBInfo->baseExtra = (unsigned) base++;\n  \n  //To pretty print during testing, we add some names for this extra register\n  //Currently, idx2Name is a global variable in wali::domains::binrel\n  idx2Name[sizeInfo] = \"__regSize\";\n  idx2Name[regAInfo->baseLhs] = \"__regA\";\n  idx2Name[regAInfo->baseRhs] = \"__regA'\";\n  idx2Name[regAInfo->baseExtra] = \"__regA''\";\n  idx2Name[regBInfo->baseLhs] = \"__regB\";\n  idx2Name[regBInfo->baseRhs] = \"__regB'\";\n  idx2Name[regBInfo->baseExtra] = \"__regB''\";\n}\n\nvoid ProgramBddContext::setupCachedBdds()\n{\n  // Create cached identity\n  baseId = bddtrue;\n  int * baseLhs = new int[this->size()];\n  int * baseRhs = new int[this->size()];\n  int vari = 0;\n  for(BddContextIter varIter = this->begin(); varIter != this->end();  ++varIter){\n    bddinfo_t varInfo = (*varIter).second;\n    baseId = baseId & fdd_equals(varInfo->baseLhs, varInfo->baseRhs);\n    baseLhs[vari] = varInfo->baseLhs;\n    baseRhs[vari] = varInfo->baseRhs;\n    ++vari;\n  }\n  fdd_setpairs(baseLhs2Rhs.get(), baseLhs, baseRhs, this->size());\n  delete [] baseLhs;\n  delete [] baseRhs;\n}\n\nvoid ProgramBddContext::addIntVar(std::string name, unsigned siz)\n{\n  //Remember Creation history\n  CreationCall cc;\n  cc.cf = ADD_INT;\n  map< string, int > m;\n  m[name] = siz;\n  cc.arg.push_back(m);\n  creationHistory.push_back(cc);\n\n  BddContext::addIntVar(name,siz);\n  if(siz > maxSize){\n    if(maxSize == 0){\n      //This is when we *create* the extra levels needed\n      int domains[1] = {(int)siz+1};\n      int retSizeInfo = fdd_extdomain(domains,1);\n      if(retSizeInfo < 0)\n        LOG(FATAL) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(retSizeInfo) << \"\\\"\" << endl\n          << \"    Aborting.\" << endl;\n      else\n        sizeInfo = (unsigned) retSizeInfo;\n      //To pretty print during testing, we add some names for this regsiter size fdd level.\n      idx2Name[sizeInfo] = \"__regSize\";\n      //Now create two extra bdd levels, and the corresponding BddInfo entries to be used for manipulation\n      //inside ProgramBddContext.\n      //We will create indices such that we get a default variable ordering where\n      //baseLhs, baseRhs, baseExtra are mixed.\n      {\n        int domains2[3] = {(int)siz, (int)siz, (int)siz};\n        regAInfo = new BddInfo();\n        //Create fdds for base\n        int base = fdd_extdomain(domains2,3);\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n\n        regAInfo->baseLhs = (unsigned) base;\n        regAInfo->baseRhs = (unsigned) base + 1;\n        regAInfo->baseExtra = (unsigned) base + 2;\n\n        //To pretty print during testing, we add some names for this extra register\n        //Currently, idx2Name is a global variable in wali::domains::binrel\n        idx2Name[regAInfo->baseLhs] = \"__regA\";\n        idx2Name[regAInfo->baseRhs] = \"__regA'\";\n        idx2Name[regAInfo->baseExtra] = \"__regA''\";\n      }\n      {\n        int domains2[3] = {(int)siz, (int)siz, (int)siz};\n        regBInfo = new BddInfo();\n        //Create fdds for base\n        int base = fdd_extdomain(domains2,3);\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        regBInfo->baseLhs = (unsigned) base;\n        regBInfo->baseRhs = (unsigned )base + 1;\n        regBInfo->baseExtra = (unsigned) base + 2;\n\n        //To pretty print during testing, we add some names for this extra register\n        //Currently, idx2Name is a global variable in wali::domains::binrel\n        idx2Name[regBInfo->baseLhs] = \"__regB\";\n        idx2Name[regBInfo->baseRhs] = \"__regB'\";\n        idx2Name[regBInfo->baseExtra] = \"__regB''\";\n      }\n    }else{\n      //This is when we *enlarge* the extra levels needed\n      int maxVal = siz - maxSize;\n\n      int domains[1] = {maxVal};\n      int retSizeInfo = fdd_extdomain(domains,1);\n      if(retSizeInfo < 0)\n        LOG(FATAL) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(retSizeInfo) << \"\\\"\" << endl\n          << \"    Aborting.\" << endl;\n      retSizeInfo = fdd_overlapdomain(sizeInfo,retSizeInfo);\n      if(retSizeInfo < 0)\n        LOG(FATAL) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(retSizeInfo) << \"\\\"\" << endl\n          << \"    Aborting.\" << endl;\n      sizeInfo = retSizeInfo;\n\n      //To pretty print during testing, we add some names for this regsiter size fdd level.\n      idx2Name[sizeInfo] = \"__regSize\";\n      //Now create two extra bdd levels, and the corresponding BddInfo entries to be used for manipulation\n      //inside ProgramBddContext.\n      //We will create indices such that we get a default variable ordering where\n      //baseLhs, baseRhs, baseExtra are mixed.\n      {\n        int domains2[3] = {maxVal, maxVal, maxVal};\n        //Create fdds for base\n        int base = fdd_extdomain(domains2,3);\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        int retbase;\n        retbase = fdd_overlapdomain(regAInfo->baseLhs,base);\n        regAInfo->baseLhs = retbase;\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        retbase = fdd_overlapdomain(regAInfo->baseRhs,base+1);\n        regAInfo->baseRhs = retbase;\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        retbase = fdd_overlapdomain(regAInfo->baseExtra,base+2);\n        regAInfo->baseExtra = retbase;\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        //To pretty print during testing, we add some names for this extra register\n        //Currently, idx2Name is a global variable in wali::domains::binrel\n        idx2Name[regAInfo->baseLhs] = \"__regA\";\n        idx2Name[regAInfo->baseRhs] = \"__regA'\";\n        idx2Name[regAInfo->baseExtra] = \"__regA''\";\n      }\n      {\n        int domains2[3] = {maxVal, maxVal, maxVal};\n        //Create fdds for base\n        int base = fdd_extdomain(domains2,3);\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        int retbase;\n        retbase = fdd_overlapdomain(regBInfo->baseLhs,base);\n        regBInfo->baseLhs = retbase;\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        retbase = fdd_overlapdomain(regBInfo->baseRhs,base+1);\n        regBInfo->baseRhs = retbase;\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        retbase = fdd_overlapdomain(regBInfo->baseExtra,base+2);\n        regBInfo->baseExtra = retbase;\n        if (base < 0)\n          LOG(ERROR) << \"[ERROR-BuDDy initialization] \\\"\" << bdd_errstring(base) << \"\\\"\" << endl\n            << \"    Aborting.\" << endl;\n        //To pretty print during testing, we add some names for this extra register\n        //Currently, idx2Name is a global variable in wali::domains::binrel\n        idx2Name[regBInfo->baseLhs] = \"__regB\";\n        idx2Name[regBInfo->baseRhs] = \"__regB'\";\n        idx2Name[regBInfo->baseExtra] = \"__regB''\";\n      }\n    }\n    maxSize = siz;\n  }\n\n    //update cached identity and base pair\n    bddinfo_t varInfo = this->find(name)->second;\n    baseId = baseId & fdd_equals(varInfo->baseLhs, varInfo->baseRhs);\n    fdd_setpair(baseLhs2Rhs.get(), varInfo->baseLhs, varInfo->baseRhs);\n}\n\nProgramBddContext::ProgramBddContext(int bddMemSize, int cacheSize) :\n  BddContext(bddMemSize, cacheSize),\n  sizeInfo(0),\n  maxSize(0),\n  regAInfo(NULL),\n  regBInfo(NULL),\n  baseId(bddtrue),\n  baseLhs2Rhs(BddPairPtr(bdd_newpair()))\n{}\n\nProgramBddContext::ProgramBddContext(const ProgramBddContext& other) :\n  BddContext(other),\n  sizeInfo(other.sizeInfo),\n  maxSize(other.maxSize),\n  regAInfo(other.regAInfo),\n  regBInfo(other.regBInfo),\n  baseId(other.baseId),\n  baseLhs2Rhs(other.baseLhs2Rhs)\n{}\n\nProgramBddContext& ProgramBddContext::operator = (const ProgramBddContext& other)\n{\n  if(this != &other){\n    BddContext::operator=(other);\n    sizeInfo=other.sizeInfo;\n    maxSize=other.maxSize;\n    regAInfo=other.regAInfo;\n    regBInfo=other.regBInfo;\n  }\n  return *this;\n}\n\n\nProgramBddContext::ProgramBddContext(const std::map<std::string, int>& vars, int bddMemSize, int cacheSize) :\n  BddContext(bddMemSize, cacheSize),\n  sizeInfo(0),\n  maxSize(0),\n  regAInfo(NULL),\n  regBInfo(NULL),\n  baseId(bddtrue),\n  baseLhs2Rhs(BddPairPtr(bdd_newpair()))\n{\n  setIntVars(vars);\n}\n\nProgramBddContext::ProgramBddContext(const std::vector<std::map<std::string, int> >& vars, int bddMemSize, int cacheSize) :\n  BddContext(bddMemSize, cacheSize),\n  sizeInfo(0),\n  maxSize(0),\n  regAInfo(NULL),\n  regBInfo(NULL),\n  baseId(bddtrue),\n  baseLhs2Rhs(BddPairPtr(bdd_newpair()))\n{\n  setIntVars(vars);\n}\n\n\nstd::ostream& ProgramBddContext::print(std::ostream& o) const\n{\n  o << \"ProgramBddContext dump:\" << std::endl;\n  o << \"sizeInfo: \" << sizeInfo << std::endl;\n  o << \"maxSize: \" << maxSize << std::endl;\n  regAInfo->print(o << \"regAInfo: \") << std::endl;\n  regBInfo->print(o << \"regBInfo: \") << std::endl;\n  return o;\n}\n\nbdd ProgramBddContext::From(std::string var) const\n{\n  bdd ret = bddfalse;\n  ProgramBddContext::const_iterator iter = (this->find(var));\n  if(iter == this->end())\n    LOG(FATAL) << \"attempted from () on \\\"\" << var << \"\\\". i don't recognize this name\\n\";\n  const bddinfo_t bi = iter->second;\n  for(unsigned i = 0; i < bi->maxVal; ++i)\n    ret = ret | (fdd_ithvar(bi->baseLhs, i) & fdd_ithvar(regAInfo->baseRhs, i));\n  ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  ret = ret & fdd_ithvar(sizeInfo, bi->maxVal);\n  return ret;\n}\n\nbdd ProgramBddContext::True() const\n{\n  return fdd_ithvar(regAInfo->baseRhs,1) & fdd_ithvar(sizeInfo, 2);\n}\n\nbdd ProgramBddContext::False() const\n{\n  return fdd_ithvar(regAInfo->baseRhs,0) & fdd_ithvar(sizeInfo, 2);\n}\n\nbdd ProgramBddContext::Const(unsigned val) const\n{\n  if(val >= maxSize){\n    LOG(ERROR) << \"[Const] Attempted to create a constant value larger \"\n      << \"than maxVal\";\n    assert(0);\n  }\n  return fdd_ithvar(regAInfo->baseRhs, val) & fdd_ithvar(sizeInfo, maxSize);\n}\n\nbdd ProgramBddContext::NonDet() const\n{\n  bdd ret = bddtrue;\n  //ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  ret = ret & fdd_ithvar(sizeInfo, maxSize);\n  return ret;\n}\n\nbdd ProgramBddContext::applyBinOp(bdd lexpr, bdd rexpr, bdd op) const\n{ \n  unsigned old1Size = getRegSize(lexpr);\n  unsigned old2Size = getRegSize(rexpr);\n  // If the sizes are different, we don't want that part of\n  // the bdd interfering in actual operation.\n  if(old1Size != old2Size){\n    lexpr = bdd_exist(lexpr, fdd_ithset(sizeInfo));\n    rexpr = bdd_exist(rexpr, fdd_ithset(sizeInfo));\n  }\n  bddPair *regA2regB = bdd_newpair();\n  fdd_setpair(regA2regB, regAInfo->baseRhs, regBInfo->baseRhs);\n  rexpr = bdd_replace(rexpr, regA2regB);\n  bdd_freepair(regA2regB);\n\n  lexpr = lexpr & rexpr;\n\n  //IMP: fddsets are unioned by & of the representing bdds (Not | as I had\n  //earlier expected.\n  lexpr = bdd_relprod(\n      lexpr,\n      op, \n      fdd_ithset(regAInfo->baseRhs) & fdd_ithset(regBInfo->baseRhs)\n      );\n\n  bddPair *regAExtra2Rhs = bdd_newpair();\n  fdd_setpair(regAExtra2Rhs, regAInfo->baseExtra, regAInfo->baseRhs);\n  lexpr = bdd_replace(lexpr, regAExtra2Rhs);\n  bdd_freepair(regAExtra2Rhs);\n\n  //update the regsize\n  if(old1Size != old2Size){\n    unsigned minSize = (old1Size < old2Size)? old1Size : old2Size;\n    lexpr = lexpr & fdd_ithvar(sizeInfo, minSize);\n    getRegSize(lexpr);\n  }\n  return lexpr;\n}\n\nbdd ProgramBddContext::applyUnOp(bdd expr, bdd op) const\n{\n  expr = bdd_relprod(\n      expr,\n      op,\n      fdd_ithset(regAInfo->baseRhs)\n      );\n\n  bddPair *regAExtra2Rhs = bdd_newpair();\n  fdd_setpair(regAExtra2Rhs, regAInfo->baseExtra, regAInfo->baseRhs);\n  expr = bdd_replace(expr, regAExtra2Rhs);\n  bdd_freepair(regAExtra2Rhs);\n\n  return expr;\n}\n\nbdd ProgramBddContext::And(bdd lexpr, bdd rexpr) const\n{\n  return applyBinOp(lexpr, rexpr, bddAnd());      \n}\n\nbdd ProgramBddContext::Or(bdd lexpr, bdd rexpr) const\n{\n  return applyBinOp(lexpr, rexpr, bddOr());\n}\n\nbdd ProgramBddContext::Not(bdd expr) const\n{\n  return applyUnOp(expr, bddNot());      \n}\n\nbdd ProgramBddContext::Plus(bdd lexpr, bdd rexpr) const \n{\n  unsigned in1 = getRegSize(lexpr);\n  unsigned in2 = getRegSize(rexpr);\n  return applyBinOp(lexpr, rexpr, bddPlus(in1,in2));\n}\n\n#ifdef BINREL_I_WANT_MINUS_TIMES_AND_DIV_EVEN_THOUGH_THEY_CAN_BE_EXPONENTIALLY_SLOW\nbdd ProgramBddContext::Minus(bdd lexpr, bdd rexpr) const\n{\n  unsigned in1 = getRegSize(lexpr);\n  unsigned in2 = getRegSize(rexpr);\n  return applyBinOp(lexpr, rexpr, bddMinus(in1,in2));\n}\n\nbdd ProgramBddContext::Times(bdd lexpr, bdd rexpr) const\n{\n  unsigned in1 = getRegSize(lexpr);\n  unsigned in2 = getRegSize(rexpr);\n  return applyBinOp(lexpr, rexpr, bddTimes(in1,in2));\n}\n\nbdd ProgramBddContext::Div(bdd lexpr, bdd rexpr) const\n{\n  unsigned in1 = getRegSize(lexpr);\n  unsigned in2 = getRegSize(rexpr);\n  return applyBinOp(lexpr, rexpr, bddDiv(in1,in2));\n}\n#endif\n\nbdd ProgramBddContext::setPre(std::string var) const\n{\n  bdd ret;\n  ProgramBddContext::const_iterator iter = (this->find(var));\n  if(iter == this->end())\n    LOG(FATAL) << \"attempted setPre () on \\\"\" << var << \"\\\". i don't recognize this name\\n\";\n  const bddinfo_t bi = iter->second;\n  assert(bi->maxVal == 2);\n  ret = fdd_ithvar(bi->baseLhs, 1);\n  ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  return ret;\n}\n\nbdd ProgramBddContext::unsetPre(std::string var) const\n{\n  bdd ret;\n  ProgramBddContext::const_iterator iter = (this->find(var));\n  if(iter == this->end())\n    LOG(FATAL) << \"attempted unsetPre () on \\\"\" << var << \"\\\". i don't recognize this name\\n\";\n  const bddinfo_t bi = iter->second;\n  assert(bi->maxVal == 2);\n  ret = fdd_ithvar(bi->baseLhs, 0);\n  ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  return ret;\n}\nbdd ProgramBddContext::setPre(std::string var, unsigned val) const\n{\n  bdd ret;\n  ProgramBddContext::const_iterator iter = (this->find(var));\n  if(iter == this->end())\n    LOG(FATAL) << \"attempted setPre () on \\\"\" << var << \"\\\". i don't recognize this name\\n\";\n  const bddinfo_t bi = iter->second;\n  if(val >= bi->maxVal)\n    LOG(FATAL) << \"setPre: val too large\\n\";\n  ret = fdd_ithvar(bi->baseLhs, val);\n  ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  return ret;\n}\nbdd ProgramBddContext::setPost(std::string var) const\n{\n  bdd ret;\n  ProgramBddContext::const_iterator iter = (this->find(var));\n  if(iter == this->end())\n    LOG(FATAL) << \"attempted setPoist () on \\\"\" << var << \"\\\". i don't recognize this name\\n\";\n  const bddinfo_t bi = iter->second;\n  assert(bi->maxVal == 2);\n  ret = fdd_ithvar(bi->baseRhs, 1);\n  ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  return ret;\n}\nbdd ProgramBddContext::unsetPost(std::string var) const\n{\n  bdd ret;\n  ProgramBddContext::const_iterator iter = (this->find(var));\n  if(iter == this->end())\n    LOG(FATAL) << \"attempted unsetPost () on \\\"\" << var << \"\\\". i don't recognize this name\\n\";\n  const bddinfo_t bi = iter->second;\n  assert(bi->maxVal == 2);\n  ret = fdd_ithvar(bi->baseRhs, 0);\n  ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  return ret;\n}\nbdd ProgramBddContext::setPost(std::string var, unsigned val) const\n{\n  bdd ret;\n  ProgramBddContext::const_iterator iter = (this->find(var));\n  if(iter == this->end())\n    LOG(FATAL) << \"attempted setPost () on \\\"\" << var << \"\\\". i don't recognize this name\\n\";\n  const bddinfo_t bi = iter->second;\n  if(val >= bi->maxVal)\n    LOG(FATAL) << \"setPost: val too large\\n\";\n  ret = fdd_ithvar(bi->baseLhs, val);\n  ret = bdd_exist(ret, fdd_ithset(sizeInfo));\n  return ret;\n}\n\nbdd ProgramBddContext::bddAnd() const\n{\n  bdd ret =\n    (fdd_ithvar(regAInfo->baseRhs,1) & \n     fdd_ithvar(regBInfo->baseRhs,1) &\n     fdd_ithvar(regAInfo->baseExtra,1))\n    |\n    (fdd_ithvar(regAInfo->baseRhs,1) & \n     fdd_ithvar(regBInfo->baseRhs,0) &\n     fdd_ithvar(regAInfo->baseExtra,0))\n    |\n    (fdd_ithvar(regAInfo->baseRhs,0) & \n     fdd_ithvar(regBInfo->baseRhs,1) &\n     fdd_ithvar(regAInfo->baseExtra,0))\n    |\n    (fdd_ithvar(regAInfo->baseRhs,0) & \n     fdd_ithvar(regBInfo->baseRhs,0) &\n     fdd_ithvar(regAInfo->baseExtra,0));\n  ret = ret & fdd_ithvar(sizeInfo, 2);\n  return ret;\n}\n\nbdd ProgramBddContext::bddOr() const\n{\n  bdd ret = \n    (fdd_ithvar(regAInfo->baseRhs,1) & \n     fdd_ithvar(regBInfo->baseRhs,1) &\n     fdd_ithvar(regAInfo->baseExtra,1))\n    |\n    (fdd_ithvar(regAInfo->baseRhs,1) & \n     fdd_ithvar(regBInfo->baseRhs,0) &\n     fdd_ithvar(regAInfo->baseExtra,1))\n    |\n    (fdd_ithvar(regAInfo->baseRhs,0) & \n     fdd_ithvar(regBInfo->baseRhs,1) &\n     fdd_ithvar(regAInfo->baseExtra,1))\n    |\n    (fdd_ithvar(regAInfo->baseRhs,0) & \n     fdd_ithvar(regBInfo->baseRhs,0) &\n     fdd_ithvar(regAInfo->baseExtra,0));\n  ret = ret & fdd_ithvar(sizeInfo, 2);\n  return ret;\n}\n\nbdd ProgramBddContext::bddNot() const\n{\n  bdd ret =\n    (fdd_ithvar(regAInfo->baseRhs,1) & \n     fdd_ithvar(regAInfo->baseExtra,0))\n    |\n    (fdd_ithvar(regAInfo->baseRhs,0) & \n     fdd_ithvar(regAInfo->baseExtra,1));\n  ret = ret & fdd_ithvar(sizeInfo, 2);\n  return ret;\n}\n\nbdd ProgramBddContext::bddPlus(unsigned in1Size, unsigned in2Size) const\n{\n  //std::cerr << \"bddPlus(\" << in1Size << \", \" << in2Size << \"):\\n\";\n  if(in1Size != in2Size){\n    LOG(WARNING) << \n      \"[ProgramBddContext::bddPlus] Different sizes of registers in operation.\" \n      << \" Longer register / constant will be clipped.\\n\";\n    if(in1Size < in2Size)\n      in2Size = in1Size;\n    else\n      in1Size = in2Size;\n  }\n  unsigned outSize = in1Size;\n  int num_bits = ::details::log2_ceiling(outSize - 1);\n\n  // Not really fast and slow, but fast and slow to construct.\n  bdd fast_adder, slow_adder;\n\n  // Build fast adder then maybe build slow adder\n  if (::details::is_power_of_two(outSize)) {\n    //std::cerr << \"  Building slow adder because \" << outSize << \" is\"\n    //          << (details::is_power_of_two(outSize) ? \" \" : \" not \")\n    //          << \"a power of two\\n\";\n    assert(in1Size <= (unsigned)fdd_domainsize(regAInfo->baseRhs));\n    fast_adder = ::details::make_adder(regAInfo->baseRhs, regBInfo->baseRhs, regAInfo->baseExtra, num_bits);\n    fast_adder = fast_adder & fdd_ithvar(sizeInfo, outSize);\n  }\n\n#ifndef BINREL_ALWAYS_BUILD_SLOW_ADDER\n#error \"You must define BINREL_ALWAYS_BUILD_SLOW_ADDER to 0 or 1\"\n#endif\n  \n  if (BINREL_ALWAYS_BUILD_SLOW_ADDER\n      || (BINREL_ALLOW_BUILD_SLOW_ADDER &&\n          !::details::is_power_of_two(outSize)))\n  {\n    //std::cerr << \"  Building slow adder because\"\n    //          << (BINREL_ALWAYS_BUILD_SLOW_ADDER ? \" we always do;\" : \"\")\n    //          << (details::is_power_of_two(outSize) ? \"\" : \"outsize is not a power of two\")\n    //          << \"\\n\";\n    \n    slow_adder = bddfalse;\n    for(unsigned i=0; i<in1Size; ++i){\n      for(unsigned j=0; j<in2Size; ++j){\n        int k = (i + j) % outSize;\n        slow_adder = slow_adder  |\n          (fdd_ithvar(regAInfo->baseRhs,i) &\n           fdd_ithvar(regBInfo->baseRhs,j) &\n           fdd_ithvar(regAInfo->baseExtra,k));\n      }\n    }\n    slow_adder = slow_adder & fdd_ithvar(sizeInfo, outSize);\n  }\n\n  // If we built both, check they are the same\n  if (fast_adder.id() != 0\n      && slow_adder.id() != 0\n      && fast_adder != slow_adder)\n  {\n    std::cerr << \"WARNING: the two methods of creating a plus BDD differ\\n\";\n    std::cerr << \"   in1size: \" << in1Size << \"\\n\";\n    std::cerr << \"   in2size: \" << in2Size << \"\\n\";\n    bdd_fnprintdot((char*)\"slow_plus.dot\", slow_adder);\n    bdd_fnprintdot((char*)\"fast_plus.dot\", fast_adder);\n    assert(fast_adder == slow_adder);  \n  }\n\n\n  if (fast_adder.id() != 0) {\n    assert(BINREL_ALWAYS_BUILD_SLOW_ADDER || slow_adder.id() == 0);\n    return fast_adder;\n  }\n  else {\n    assert(slow_adder.id() != 0);\n    return slow_adder;\n  }\n}\n\n#ifdef BINREL_I_WANT_MINUS_TIMES_AND_DIV_EVEN_THOUGH_THEY_CAN_BE_EXPONENTIALLY_SLOW\nbdd ProgramBddContext::bddMinus(unsigned in1Size, unsigned in2Size) const\n{\n  if(in1Size != in2Size){\n    LOG(WARNING) << \n      \"[ProgramBddContext::bddPlus] Different sizes of registers in operation.\" \n      << \" Longer register / constant will be clipped.\\n\";\n    if(in1Size < in2Size)\n      in2Size = in1Size;\n    else\n      in1Size = in2Size;\n  }\n  unsigned outSize = in1Size;\n  bdd ret = bddfalse;\n  for(unsigned i=0; i<in1Size; ++i){\n    for(unsigned j=0; j<in2Size; ++j){\n      int k = (i - j + outSize) % outSize;\n      ret = ret  |\n        (fdd_ithvar(regAInfo->baseRhs,i) &\n         fdd_ithvar(regBInfo->baseRhs,j) &\n         fdd_ithvar(regAInfo->baseExtra,k));\n    }\n  }\n  ret = ret & fdd_ithvar(sizeInfo, outSize);\n  return ret;\n}\n\nbdd ProgramBddContext::bddTimes(unsigned in1Size, unsigned in2Size) const\n{\n  if(in1Size != in2Size){\n    LOG(WARNING) << \n      \"[ProgramBddContext::bddPlus] Different sizes of registers in operation.\" \n      << \" Longer register / constant will be clipped.\\n\";\n    if(in1Size < in2Size)\n      in2Size = in1Size;\n    else\n      in1Size = in2Size;\n  }\n  unsigned outSize = in1Size;\n  bdd ret = bddfalse;\n  for(unsigned i=0; i<in1Size; ++i){\n    for(unsigned j=0; j<in2Size; ++j){\n      int k = (i * j) % outSize;\n      ret = ret  |\n        (fdd_ithvar(regAInfo->baseRhs,i) &\n         fdd_ithvar(regBInfo->baseRhs,j) &\n         fdd_ithvar(regAInfo->baseExtra,k));\n    }\n  }\n  ret = ret & fdd_ithvar(sizeInfo, outSize);\n  return ret;\n}\n\nbdd ProgramBddContext::bddDiv(unsigned in1Size, unsigned in2Size) const\n{\n  if(in1Size != in2Size){\n    LOG(WARNING) << \n      \"[ProgramBddContext::bddPlus] Different sizes of registers in operation.\" \n      << \" Longer register / constant will be clipped.\\n\";\n    if(in1Size < in2Size)\n      in2Size = in1Size;\n    else\n      in1Size = in2Size;\n  }\n  unsigned outSize = in1Size;\n  bdd ret = bddfalse;\n  for(unsigned i=0; i<in1Size; ++i){\n    for(unsigned j=0; j<in2Size; ++j){\n      int k;\n      if(j == 0)\n        //arbitrary\n        k = 0;\n      else\n        k = (int) i / j;\n      ret = ret |\n        (fdd_ithvar(regAInfo->baseRhs,i) &\n         fdd_ithvar(regBInfo->baseRhs,j) &\n         fdd_ithvar(regAInfo->baseExtra,k));\n    }\n  }\n  ret = ret & fdd_ithvar(sizeInfo, outSize);\n  return ret;\n}\n#endif\n\nunsigned ProgramBddContext::getRegSize(bdd forThis) const\n{\n  //Inefficient!!!\n  for(unsigned i = 0; i <= maxSize; ++i){\n    bdd tmp = fdd_ithvar(sizeInfo, i);\n    if((tmp & forThis) != bddfalse)\n      return i;\n  }\n  LOG(FATAL) << \"[ProgramBddContext::getRegSize] bdd does not have a recognizable regSize\\n\";\n  return 0;\n}\n\nbdd ProgramBddContext::Assign(std::string var, bdd expr) const\n{\n  bddinfo_t bi;\n  if(this->find(var) == this->end()){\n    LOG(WARNING) << \"[ProgramBddContext::Assign] Unknown Variable: \" << var;\n    //This is a safe result. We assume that anything can be assigned to anything!\n    return bddtrue;\n  }else{\n    bi = this->find(var)->second;\n  }\n\n  unsigned rvalsize = getRegSize(expr);\n  //if(rvalsize > bi->maxVal){\n  //  LOG(WARNING) << \"[ProgramBddContext::Assign] The register size of rhs is greater than what the variable can hold\";\n  //  return bddfalse;\n  //}\n\n  // If rhs max size is smaller, only copy the relevant bits.\n  unsigned copysize = bi->maxVal;\n  copysize = (rvalsize < copysize) ? rvalsize : copysize;\n\n  //redundant?\n  bddPair *regARhs2Extra = bdd_newpair();\n  fdd_setpair(\n      regARhs2Extra,\n      regAInfo->baseRhs,\n      regAInfo->baseExtra\n      );\n  expr = bdd_replace(expr,regARhs2Extra);\n  bdd_freepair(regARhs2Extra);\n  //up to here.\n\n  bdd regA2var = bddfalse;\n  for(unsigned i = 0; i < copysize; ++i)\n    regA2var = regA2var |\n      (fdd_ithvar(regAInfo->baseExtra,i) & fdd_ithvar(bi->baseRhs,i));\n  expr = bdd_relprod(expr,regA2var,fdd_ithset(regAInfo->baseExtra));\n\n  // All transformers are slight perturbations of identity.\n  bdd c = baseId;\n  c = bdd_exist(c, fdd_ithset(bi->baseLhs));\n  c = bdd_exist(c, fdd_ithset(bi->baseRhs));\n  return bdd_exist(expr & c, fdd_ithset(sizeInfo));\n}\n\nbdd ProgramBddContext::Assume(bdd expr1, bdd expr2) const\n{\n\n  bddPair *regARhs2Extra = bdd_newpair();\n  fdd_setpair(\n      regARhs2Extra,\n      regAInfo->baseRhs,\n      regAInfo->baseExtra\n      );\n  expr1 = bdd_replace(expr1, regARhs2Extra);\n  bdd_freepair(regARhs2Extra);\n\n  bddPair *regARhs2BExtra = bdd_newpair();\n  fdd_setpair(\n      regARhs2BExtra,\n      regAInfo->baseRhs,\n      regBInfo->baseExtra\n      );\n  expr2 = bdd_replace(expr2, regARhs2BExtra);\n  bdd_freepair(regARhs2BExtra);\n\n  expr2 = bdd_replace(expr2, baseLhs2Rhs.get());\n\n  bdd equate = baseId &\n    fdd_equals(\n        regAInfo->baseExtra,\n        regBInfo->baseExtra\n        );\n\n  // expr1 and expr2 can have different regSize.\n  // In that case, only the smaller number of bits are constrainted.\n  expr1 = bdd_exist(expr1, fdd_ithset(sizeInfo));\n  expr2 = bdd_exist(expr2, fdd_ithset(sizeInfo));\n\n  bdd ret = expr1 & expr2 & equate;\n\n  ret = bdd_exist(ret, fdd_ithset(regAInfo->baseExtra));\n  ret = bdd_exist(ret, fdd_ithset(regBInfo->baseExtra));\n\n  return ret;\n}\n\nbdd ProgramBddContext::tGetRandomTransformer(bool isTensored, unsigned seed) const\n{\n  if(seed != 0)\n    srand(seed);\n  bdd ret = bddfalse;\n  int numRounds = rand() % 10 + 1;\n  for(int c=0; c < numRounds; ++c){\n    bdd inbdd = rand()%2?bddfalse:bddtrue;\n    for(BddContext::const_iterator iter = this->begin(); \n        iter != this->end();\n        ++iter){\n      int siz = iter->second->maxVal;\n      int n;\n      if(!isTensored){\n        n = rand() % 4;\n        if(n==0)\n          inbdd = inbdd & fdd_ithvar(iter->second->baseLhs,rand()%siz);\n        if(n==1)    \n          inbdd = inbdd | fdd_ithvar(iter->second->baseLhs,rand()%siz);\n        n = rand() % 4;\n        if(n==0)\n          inbdd = inbdd & fdd_ithvar(iter->second->baseRhs,rand()%siz);\n        if(n==1)    \n          inbdd = inbdd | fdd_ithvar(iter->second->baseRhs,rand()%siz);\n      }else{\n        n = rand() % 4;\n        if(n==0)\n          inbdd = inbdd & fdd_ithvar(iter->second->tensor1Lhs,rand()%siz);\n        if(n==1)    \n          inbdd = inbdd | fdd_ithvar(iter->second->tensor1Lhs,rand()%siz);\n        n = rand() % 4;\n        if(n==0)\n          inbdd = inbdd & fdd_ithvar(iter->second->tensor1Rhs,rand()%siz);\n        if(n==1)    \n          inbdd = inbdd | fdd_ithvar(iter->second->tensor1Rhs,rand()%siz);\n        n = rand() % 4;\n        if(n==0)\n          inbdd = inbdd & fdd_ithvar(iter->second->tensor2Lhs,rand()%siz);\n        if(n==1)    \n          inbdd = inbdd | fdd_ithvar(iter->second->tensor2Lhs,rand()%siz);\n        n = rand() % 4;\n        if(n==0)\n          inbdd = inbdd & fdd_ithvar(iter->second->tensor2Rhs,rand()%siz);\n        if(n==1)    \n          inbdd = inbdd | fdd_ithvar(iter->second->tensor2Rhs,rand()%siz);\n      }\n    }\n    ret = rand() % 2 ? ret & inbdd : ret | inbdd;\n  }\n  return ret;\n}\n\nvoid ProgramBddContext::printHistory(std::ostream& o) const\n{\n  boost::archive::text_oarchive oa(o);\n  oa << creationHistory;\n}\n\nProgramBddContext * ProgramBddContext::buildFromHistory(std::istream& in)\n{\n  CreationHistory ch;\n  boost::archive::text_iarchive ia(in);\n  ia >> ch;\n\n  ProgramBddContext * con = new ProgramBddContext();\n  for(CreationHistory::const_iterator ci = ch.begin(); ci != ch.end(); ++ci){\n    CreationCall cc = *ci;\n    switch(cc.cf){\n      case SET_INT_VECT:\n        con->setIntVars(cc.arg);\n        break;\n      case SET_INT_MAP:\n        con->setIntVars(cc.arg[0]);\n        break;\n      case ADD_INT:        \n        {\n          map< string, int >::iterator m = cc.arg[0].begin();\n          con->addIntVar(m->first, m->second);\n        }\n        break;\n      case ADD_BOOL:\n      default:\n        assert(0);\n    }\n  }\n  return con;\n}\n\ntemplate<class Archive>\nvoid ProgramBddContext::CreationCall::serialize(Archive &ar, const unsigned int)\n{\n  //ignore file_version\n  ar & cf;\n  ar & arg;\n}\n\nostream& ProgramBddContext::CreationCall::print(ostream& o) const\n{\n  switch(cf){\n    case SET_INT_VECT:\n      o << \"SET_INT_VECT\";\n      break;\n    case SET_INT_MAP:\n      o << \"SET_INT_MAP\";\n      break;\n    case ADD_INT:\n      o << \"ADD_INT\";\n      break;\n    case ADD_BOOL:\n      o << \"ADD_BOOL\";\n      break;\n    default:\n      o << \"UNKNOWN\";\n  }\n  o << \": \";\n  for(vector< map< string, int > >::const_iterator cvi = arg.begin(); cvi != arg.end(); ++cvi){\n    o << \"{\";\n    bool first = true;\n    for(map< string, int >::const_iterator cmi = cvi->begin(); cmi != cvi->end(); ++cmi){\n      if(!first)\n        o << \", \";\n      o << cmi->first << \": \" << cmi->second;\n      first = false;\n    }\n    o << \"}\";\n  }\n  o << endl;\n  return o;\n}\n// Yo, Emacs!\n// Local Variables:\n//   c-file-style: \"ellemtel\"\n//   c-basic-offset: 2\n// End:\n", "meta": {"hexsha": "093484995b728cf3b17bb6155336c5b4f0177338", "size": 39004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AddOns/Domains/Source/wali/domains/binrel/ProgramBddContext.cpp", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "AddOns/Domains/Source/wali/domains/binrel/ProgramBddContext.cpp", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "AddOns/Domains/Source/wali/domains/binrel/ProgramBddContext.cpp", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 31.1782573941, "max_line_length": 123, "alphanum_fraction": 0.627909958, "num_tokens": 12165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.01971912789131383, "lm_q1q2_score": 0.007444773008414782}}
{"text": "/* tsne_python.cc\n   Jeremy Barnes, 20 January 2010\n   Copyright (c) 2010 Jeremy Barnes.  All rights reserved.\n\n   Python wrapper for TSNE.\n*/\n\n#include <Python.h>\n#include <numpy/arrayobject.h>\n#include \"tsne.h\"\n#include <iostream>\n#include \"jml/arch/exception.h\"\n#include \"jml/utils/unnamed_bool.h\"\n#include \"jml/arch/demangle.h\"\n#include <cxxabi.h>\n#include <typeinfo>\n#include <boost/bind.hpp>\n\n\nusing namespace std;\nusing namespace ML;\n\n// For the following: /usr/include/python2.6/numpy/__multiarray_api.h:958: error: ‘int _import_array()’ defined but not used\nint (*fn) () = &_import_array;\n\ntemplate<class Object>\nstruct PyRef {\n    PyRef(Object * obj)\n        : obj(obj)\n    {\n    }\n\n    template<class Other>\n    PyRef(Other * obj)\n        : obj(reinterpret_cast<Object *>(obj))\n    {\n    }\n\n    Object * obj;\n\n    JML_IMPLEMENT_OPERATOR_BOOL(obj);\n\n    template<class ObjectOut>\n    operator ObjectOut * () const { return reinterpret_cast<ObjectOut *>(obj); }\n\n    Object * release()\n    {\n        Object * result = obj;\n        obj = 0;\n        return result;\n    }\n\n    template<class ObjectOut>\n    ObjectOut * release()\n    {\n        ObjectOut * result = *this;\n        obj = 0;\n        return result;\n    }\n\n    ~PyRef()\n    {\n        if (obj) Py_DECREF(obj);\n    }\n};\n\nstruct Interrupt_Exception : public Exception {\n    Interrupt_Exception()\n        : Exception(\"Keyboard Interrupt\")\n    {\n    }\n};\n\ntypedef PyRef<PyObject> PyObjectRef;\ntypedef PyRef<PyArrayObject> PyArrayRef;\n\nPyObject * to_python_exception(const std::type_info * exc_type,\n                               const char * what = 0)\n{\n    if (*exc_type == typeid(Interrupt_Exception)) {\n        PyErr_SetString(PyExc_KeyboardInterrupt, \"JML processing interrupted\");\n        return NULL;\n    }\n\n    std::string message;\n    if (what)\n        message = format(\"JML Exception of type %s caught: %s\",\n                         demangle(exc_type->name()).c_str(),\n                         what);\n    else\n        message = format(\"JML Exception of type %s caught\",\n                         demangle(exc_type->name()).c_str());\n\n    PyErr_SetString(PyExc_RuntimeError, message.c_str());\n    \n    return NULL;\n}\n\nPyObject * to_python_exception(const std::exception & exc)\n{\n    return to_python_exception(&typeid(exc), exc.what());\n}\n\nPyObject * to_python_exception()\n{\n    const std::type_info * exc_type = abi::__cxa_current_exception_type();\n    if (!exc_type) {\n        cerr << \"exception type was null\" << endl;\n        abort();\n    }\n\n    return to_python_exception(exc_type);\n}\n\nenum BlockOp {\n    UNBLOCK,\n    BLOCK\n};\n\nvolatile int num_signals_received = 0;\n\nvoid handle_sigint(int action)\n{\n    PyErr_SetInterrupt();\n    ++num_signals_received;\n}\n\nstruct PyThreads {\n    PyThreads(BlockOp op = UNBLOCK)\n        : _save(0), old_sigint(0)\n    {\n        if (op == UNBLOCK)\n            unblock();\n    }\n\n    ~PyThreads()\n    {\n        if (_save)\n            block();\n    }\n\n    PyThreadState *_save;\n    PyOS_sighandler_t old_sigint;\n    int signals_before;\n\n    void unblock()\n    {\n        if (_save) {\n            cerr << \"threads were already unblocked; pairing error\"\n                 << endl;\n            abort();\n        }\n        \n        old_sigint = PyOS_setsig(SIGINT, handle_sigint);\n        signals_before = num_signals_received;\n        Py_UNBLOCK_THREADS;\n    }\n\n    void block()\n    {\n        if (!_save) {\n            cerr << \"threads were already unblocked; pairing error\"\n                 << endl;\n            abort();\n        }\n            \n        Py_BLOCK_THREADS;\n        PyOS_setsig(SIGINT, old_sigint);\n    }\n\n    bool interrupted()\n    {\n        return num_signals_received > signals_before;\n    }\n};\n\nstatic PyObject *\ntsne_vectors_to_distances(PyObject *self, PyObject *args)\n{\n    PyObject * in_array;\n\n    int args_ok = PyArg_ParseTuple(args, \"O!\", &PyArray_Type, &in_array);\n    if (!args_ok)\n        return NULL;\n    \n    /* Convert the argument to a float array. */\n    PyArrayRef input_as_float32\n        = PyArray_FromAny(in_array,\n                          PyArray_DescrFromType(NPY_FLOAT32),\n                          2, 2,\n                          NPY_C_CONTIGUOUS | NPY_FORCECAST | NPY_ALIGNED,\n                          0);\n    if (!input_as_float32)\n        return NULL;\n    \n    // TODO: inc reference?\n\n    int n = PyArray_DIM(input_as_float32, 0);\n    int d = PyArray_DIM(input_as_float32, 1);\n\n    npy_intp npy_shape[2] = { n, n };\n\n    /* Allocate an object (in memory) for the result */\n    PyArrayRef result_array\n        = PyArray_SimpleNew(2 /* num dims */,\n                            npy_shape,\n                            NPY_FLOAT);\n    if (!result_array)\n        return NULL;\n\n    // TODO: inc reference?\n\n    try {\n        PyThreads threads(UNBLOCK);\n\n        /* Copy into a boost multi array (TODO: avoid this copy) */\n        boost::multi_array<float, 2> array(boost::extents[n][d]);\n\n        const float * data_in = (const float *)PyArray_DATA(input_as_float32);\n\n        std::copy(data_in, data_in + (n * d), array.data());\n\n        input_as_float32.release();\n\n        boost::multi_array<float, 2> result\n            = ML::vectors_to_distances(array);\n\n        if (result.shape()[0] != n || result.shape()[1] != n)\n            throw Exception(\"wrong shapes\");\n\n        float * data_out = (float *)PyArray_DATA(result_array);\n\n        std::copy(result.data(), result.data() + n * n, data_out);\n    } catch (const std::exception & exc) {\n        return to_python_exception(exc);\n    } catch (...) {\n        return to_python_exception();\n    }\n\n    return result_array.release<PyObject>();\n}\n\nstatic PyObject *\ntsne_distances_to_probabilities(PyObject *self, PyObject *args)\n{\n    PyObject * in_array;\n    double tolerance;\n    double perplexity;\n\n    int args_ok = PyArg_ParseTuple(args, \"O!dd\", &PyArray_Type, &in_array,\n                                   &tolerance, &perplexity);\n    if (!args_ok)\n        return NULL;\n\n    /* Convert the argument to a float array. */\n    PyArrayRef input_as_float32\n        = PyArray_FromAny(in_array,\n                          PyArray_DescrFromType(NPY_FLOAT32),\n                          2, 2,\n                          NPY_C_CONTIGUOUS | NPY_FORCECAST | NPY_ALIGNED,\n                          0);\n    if (!input_as_float32)\n        return NULL;\n    \n    int n = PyArray_DIM(input_as_float32, 0);\n    int n2 = PyArray_DIM(input_as_float32, 1);\n\n    if (n != n2) {\n        PyErr_SetString(PyExc_RuntimeError, \"array must be square\");\n        return NULL;\n    }\n\n    /* Allocate an object (in memory) for the result */\n    npy_intp npy_shape[2] = { n, n };\n    PyArrayRef result_array\n        = PyArray_SimpleNew(2 /* num dims */,\n                            npy_shape,\n                            NPY_FLOAT);\n    if (!result_array)\n        return NULL;\n\n    try {\n        PyThreads threads(UNBLOCK);\n\n        /* Copy into a boost multi array (TODO: avoid this copy) */\n        boost::multi_array<float, 2> array(boost::extents[n][n]);\n\n        const float * data_in = (const float *)PyArray_DATA(input_as_float32);\n\n        std::copy(data_in, data_in + (n * n), array.data());\n\n        input_as_float32.release();\n\n        boost::multi_array<float, 2> result\n            = distances_to_probabilities(array,\n                                         tolerance,\n                                         perplexity);\n        \n        if (result.shape()[0] != n || result.shape()[1] != n)\n            throw Exception(\"wrong shapes\");\n\n        float * data_out = (float *)PyArray_DATA(result_array);\n\n        std::copy(result.data(), result.data() + n * n, data_out);\n    } catch (const std::exception & exc) {\n        return to_python_exception(exc);\n    } catch (...) {\n        return to_python_exception();\n    }\n\n    return result_array.release<PyObject>();\n}\n\nbool tsne_callback(int signals_before, int, float, const char *)\n{\n    return signals_before == num_signals_received;\n}\n\nstatic PyObject *\ntsne_tsne(PyObject *self, PyObject *args, PyObject * kwds)\n{\n    PyObject * in_array;\n    TSNE_Params params;\n\n    int num_dims = 2;\n\n    static const char * const kwlist[] =\n        { \"array\", \"num_dims\", \"max_iter\", \"initial_momentum\", \"final_momentum\",\n          \"eta\", \"min_gain\", \"min_prob\", NULL };\n\n    if (!PyArg_ParseTupleAndKeywords(args, kwds,\n                                     \"O!|iiddddd\", (char **)kwlist,\n                                     &PyArray_Type, &in_array,\n                                     &num_dims,\n                                     &params.max_iter,\n                                     &params.initial_momentum,\n                                     &params.final_momentum,\n                                     &params.eta,\n                                     &params.min_gain,\n                                     &params.min_prob))\n        return NULL;\n\n    /* Convert the input array to a float array. */\n    PyArrayRef input_as_float32\n        = PyArray_FromAny(in_array,\n                          PyArray_DescrFromType(NPY_FLOAT32),\n                          2, 2,\n                          NPY_C_CONTIGUOUS | NPY_FORCECAST | NPY_ALIGNED,\n                          0);\n    if (!input_as_float32)\n        return NULL;\n    \n    int n = PyArray_DIM(input_as_float32, 0);\n    int n2 = PyArray_DIM(input_as_float32, 1);\n\n    if (n != n2) {\n        PyErr_SetString(PyExc_RuntimeError, \"array must be square\");\n        return NULL;\n    }\n\n    /* Allocate an object (in memory) for the result */\n    npy_intp npy_shape[2] = { n, num_dims };\n    PyArrayRef result_array\n        = PyArray_SimpleNew(2 /* num dims */,\n                            npy_shape,\n                            NPY_FLOAT);\n    if (!result_array)\n        return NULL;\n    \n    try {\n        PyThreads threads(UNBLOCK);\n\n        /* Copy into a boost multi array (TODO: avoid this copy) */\n        boost::multi_array<float, 2> array(boost::extents[n][n]);\n\n        const float * data_in = (const float *)PyArray_DATA(input_as_float32);\n\n        std::copy(data_in, data_in + (n * n), array.data());\n\n        input_as_float32.release();\n\n        boost::multi_array<float, 2> result\n            = tsne(array, num_dims, params,\n                   boost::bind(tsne_callback,\n                               threads.signals_before,\n                               _1, _2, _3));\n        \n        if (threads.interrupted())\n            throw Interrupt_Exception();\n\n        if (result.shape()[0] != n || result.shape()[1] != num_dims)\n            throw Exception(\"wrong shapes\");\n        \n        float * data_out = (float *)PyArray_DATA(result_array);\n        \n        std::copy(result.data(), result.data() + n * num_dims, data_out);\n    } catch (const std::exception & exc) {\n        return to_python_exception(exc);\n    } catch (...) {\n        return to_python_exception();\n    }\n\n    return result_array.release<PyObject>();\n}\n\nstatic PyMethodDef TsneMethods[] = {\n    {\"vectors_to_distances\",  tsne_vectors_to_distances, METH_VARARGS,\n     \"Convert an array of vectors in a coordinate space to a symmetric square\"\n     \"matrix of distances between them.\"},\n    {\"distances_to_probabilities\",  tsne_distances_to_probabilities, METH_VARARGS,\n     \"Convert an array of distances between points to an array of joint \"\n     \"probabilities by modelling as gaussians.\"},\n    {\"tsne\",  (PyCFunction)tsne_tsne, METH_VARARGS | METH_KEYWORDS,\n     \"reduce the (n x d) matrix to a (n x num_dims) matrix using t-SNE.\"},\n    {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\nextern \"C\" {\n\nPyMODINIT_FUNC\ninit_tsne(void)\n{\n    import_array();\n\n    PyObject *m;\n\n    m = Py_InitModule(\"_tsne\", TsneMethods);\n    if (m == NULL)\n        return;\n\n#if 0\n    TsneError = PyErr_NewException(\"tsne.error\", NULL, NULL);\n    Py_INCREF(TsneError);\n    PyModule_AddObject(m, \"error\", TsneError);\n#endif\n}\n\n} // extern \"C\"\n", "meta": {"hexsha": "49a422a1662e538cb94d095a470eaf4b8b20003a", "size": 11872, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jml/tsne/tsne_python.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/tsne/tsne_python.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/tsne/tsne_python.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.0432801822, "max_line_length": 124, "alphanum_fraction": 0.5658692722, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2909808539178129, "lm_q2_score": 0.02556521615054331, "lm_q1q2_score": 0.007438988426078554}}
{"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_IEXP_IEXP_CALCULATOR_HPP\n#define AMA_TENSOR_IEXP_IEXP_CALCULATOR_HPP 1\n\n#include <ama/common/size_t.hpp>\n#include <ama/tensor/iexp/indices.hpp>\n#include <boost/mpl/advance.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <boost/mpl/contains.hpp>\n#include <boost/mpl/count.hpp>\n#include <boost/mpl/empty.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/logical.hpp>\n#include <boost/mpl/max.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/vector/vector0.hpp>\n\n/* forward declaration */\nnamespace ama\n{\n  template <typename T, size_t D, size_t CT, size_t CO> class tensor;\n\n  namespace tensor_\n  {\n    template <typename TENSOR, typename CTLIST, typename COLIST> class iexp_constant;\n    template <typename TENSOR, typename CTLIST, typename COLIST> class iexp_mutable;\n    template <typename TENSOR, typename CTLIST, typename COLIST> class iexp_temporary;\n  }\n}\n\n\n\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    namespace mpl = ::boost::mpl;\n\n    /* check if the list contains repeated indices */\n    template <typename ILIST>\n    struct has_repeated_indices:\n        mpl::fold<\n              ILIST\n            , mpl::false_\n            , mpl::or_<\n                  mpl::_1\n                , mpl::greater<\n                        mpl::count<ILIST, mpl::_2>\n                      , mpl::size_t<1>\n                      >\n                >\n            >::type { };\n\n\n\n\n    /* check if all indices are repeated */\n    template <typename ILIST>\n    struct all_repeated_indices:\n        mpl::fold<\n              ILIST\n            , mpl::true_\n            , mpl::and_<\n                  mpl::_1\n                , mpl::greater<\n                        mpl::count<ILIST, mpl::_2>\n                      , mpl::size_t<1>\n                      >\n                >\n            >::type { };\n\n\n\n\n    /* compute the return type of an iexp expression */\n    template <typename TENSOR, typename ILIST, typename CONST>\n    struct iexp_calculator:\n        mpl::if_<\n              has_repeated_indices<ILIST>\n            , typename mpl::if_<\n                    all_repeated_indices<ILIST>\n                  , typename TENSOR::value_type\n                  , iexp_temporary<\n                          typename iexp_reduce<TENSOR, ILIST>::tensor_type\n                        , typename iexp_reduce<TENSOR, ILIST>::controvariant\n                        , typename iexp_reduce<TENSOR, ILIST>::covariant\n                        >\n                  >::type\n            , typename mpl::if_<\n                    CONST\n                  , iexp_constant<\n                          TENSOR\n                        , typename controvariant<TENSOR,ILIST>::type\n                        , typename covariant<TENSOR,ILIST>::type\n                        >\n                  , iexp_mutable<\n                          TENSOR\n                        , typename controvariant<TENSOR,ILIST>::type\n                        , typename covariant<TENSOR,ILIST>::type\n                        >\n                  >::type\n            >\n    {\n      typedef typename mpl::fold<\n            ILIST\n          , mpl::size_t<0>\n          , mpl::max<\n                  mpl::_1\n                , mpl::count<ILIST, mpl::_1>\n                >\n          >::type max_;\n\n      /* check if the indeces are repeated at most twice */\n      BOOST_MPL_ASSERT_MSG(\n            (mpl::less_equal< max_, mpl::size_t<2> >::type::value)\n          , AN_INDEX_COULD_BE_REPEATED_AT_MOST_TWICE\n          , (TENSOR, ILIST));\n\n      typedef typename controvariant<TENSOR,ILIST>::type controvariant_;\n      typedef typename covariant<TENSOR,ILIST>::type covariant_;\n\n      typedef typename mpl::not_< has_repeated_indices<controvariant_> >::type bct_;\n      typedef typename mpl::not_< has_repeated_indices<covariant_> > bco_;\n\n      /* check for reduced indeces */\n      BOOST_MPL_ASSERT_MSG(\n            (mpl::and_<bct_,bco_>::type::value)\n          , YOU_CANNOT_REDUCE_TWO_INDICES_OF_SAME_TYPE\n          , (TENSOR, ILIST));\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_IEXP_IEXP_CALCULATOR_HPP */\n", "meta": {"hexsha": "7bc4bc3b6e34125af20fc378c9e1c3ec070f3da2", "size": 5808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/iexp/iexp_calculator.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/iexp/iexp_calculator.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/iexp/iexp_calculator.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.3668639053, "max_line_length": 86, "alphanum_fraction": 0.606577135, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.024423089033355595, "lm_q1q2_score": 0.007425636897558551}}
{"text": "#include \"MaterialProperties.h\"\n#include <cc_CommonUtilities.h>\n#include <string>\n#include <stdlib.h>\n#include <locale>\n#include <iostream>\n#include <ostream>\n#include <sstream>\n\n#include <boost\\filesystem.hpp>\n#include <boost\\property_tree\\ptree.hpp>\n#include <boost\\property_tree\\json_parser.hpp>\n#include <boost\\foreach.hpp>\n#include <boost\\algorithm\\string.hpp>\n#include <sstream>\n\n#include <fstream>\n#include <iterator>\n#include <boost/regex.hpp>\n#include <stdlib.h>\n#include \"cc_LoggerBoost.h\"\n\n\nnamespace isis\n{\n\n\tconst double PASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR = 1.0 / 1000000.0;\n\tconst double CONVERSION_FACTOR_ONE = 1.0;\n\tconst double M_CUBED_TO_MM_CUBED = 1000.0 * 1000.0 * 1000.0;\n\tconst double M_CUBED_TO_MM_CUBED_RECIPROCAL = 1.0 / M_CUBED_TO_MM_CUBED;\n\tconst double M_TO_MM_RECIPROCAL = 1.0  / 1000.0;\n/*\n\tstd::string ConvertToUpperCase(const std::string &in_String)\n\t{\n\t\tstd::string temp_string(in_String);\n\t\tstd::locale loc;\n\t\tfor (std::string::iterator p = temp_string.begin(); temp_string.end() != p; ++p)    *p = toupper(*p, loc);\n\t\treturn temp_string;\n\t}\n\n*/\n\n\nvoid stream_AnalysisMaterialProperties( const AnalysisMaterialProperties &in_CADAnalyses, std::ostream &out_Stream )\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n{\n\tout_Stream << std::endl << \"Material Name: \" << in_CADAnalyses.materialName;\n\tout_Stream << std::endl << \"Material Type: \" << isis::MaterialType_string(in_CADAnalyses.materialType);\n\t\n\tout_Stream << std::endl << \"   ModulusOfElasticity\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.modulusOfElasticityDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.modulusOfElasticity;\n\n\tout_Stream << std::endl << \"   PoissonsRatio\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.poissonsRatioDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.poissonsRatio;\n\n\tout_Stream << std::endl << \"   TensileYieldStrength\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.tensileYieldStrengthDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.tensileYieldStrength;\n\n\tout_Stream << std::endl << \"   TensileUltimateStrength\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.tensileUltimateStrengthDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.tensileUltimateStrength;\n\n\tout_Stream << std::endl << \"   ShearStrength\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.shearStrengthDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.shearStrength;\n\n\tout_Stream << std::endl << \"   BearingYieldStrength\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.bearingYieldStrengthDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.bearingYieldStrength;\n\n\tout_Stream << std::endl << \"   BearingUltimateStrength\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.bearingUltimateStrengthDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.bearingUltimateStrength;\n\n\tout_Stream << std::endl << \"   FatigueStrength\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.fatigueStrengthDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.fatigueStrength;\n\n\tout_Stream << std::endl << \"   fatigueNumberOfCycles\";\n\tout_Stream << std::endl << \"      Defined: \" << in_CADAnalyses.fatigueNumberOfCyclesDefined;\n\tout_Stream << std::endl << \"      Value: \"   << in_CADAnalyses.fatigueNumberOfCycles;\n\n};\n\nvoid stream_AnalysisMaterialProperties_Allowables( const AnalysisMaterialProperties_Allowables\t&in_AnalysisMaterialProperties, std::ostream &out_Stream )\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n{\n\tout_Stream << std::endl << \"Material Name: \" << in_AnalysisMaterialProperties.materialName;\n\tout_Stream << std::endl << \"Material Type: \" << isis::MaterialType_string(in_AnalysisMaterialProperties.materialType);\n\n\tout_Stream << std::endl << \"   TensileStrength\";\n\tout_Stream << std::endl << \"      Value: \"   << in_AnalysisMaterialProperties.tensileStrength;\n\n\tout_Stream << std::endl << \"   ShearStrength\";\n\tout_Stream << std::endl << \"      Value: \"   << in_AnalysisMaterialProperties.shearStrength;\n\n\tout_Stream << std::endl << \"   BearingStrength\";\n\tout_Stream << std::endl << \"      Value: \"   << in_AnalysisMaterialProperties.bearingStrength;\n\n\tout_Stream << std::endl << \"   NumberOfCycles\";\n\tout_Stream << std::endl << \"      Value: \"   << in_AnalysisMaterialProperties.numberOfCycles;\n\n};\n\n///////////////////////////////////////////////////////////////////////////////////////////////\nbool \tStressValueComputed(\tbool\tin_Value_1_Defined,\n\t\t\t\t\t\t\t\tdouble\tin_Value_1,\t\n\t\t\t\t\t\t\t\tbool\tin_Value_2_Defined,\n\t\t\t\t\t\t\t\tdouble\tin_Value_2,\n\t\t\t\t\t\t\t\tdouble\tin_ReferenceValue,\n\t\t\t\t\t\t\t\tdouble  &out_ComputedValue )\n{\n\n\t\tif ( in_Value_1_Defined && in_Value_2_Defined  )\n\t\t{\n\t\t\tout_ComputedValue =  (in_ReferenceValue / in_Value_1 ) * in_Value_2;\n\t\t\t//std::cout << std::endl << \"BEGIN StressValueComputed\";\n\t\t\t//std::cout << std::endl << \"  in_Value_1_Defined: \"\t<< in_Value_1_Defined;\n\t\t\t//std::cout << std::endl << \"  in_Value_1: \"\t\t\t<< in_Value_1;\n\t\t\t//std::cout << std::endl << \"  in_Value_2_Defined: \"\t<< in_Value_1_Defined;\n\t\t\t//std::cout << std::endl << \"  in_Value_2: \"\t\t\t<< in_Value_2;\n\t\t\t//std::cout << std::endl << \"  in_ReferenceValue:  \"\t<< in_ReferenceValue;\n\t\t\t//std::cout << std::endl << \"  out_ComputedValue:  \"\t<< out_ComputedValue;\n\t\t\t//std::cout << std::endl << \"END StressValueComputed\";\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t} \n}\n/////////////////////////////////////////////////////////////////////////////////////////////////\n\n// General Rules:\n//\t1)\tIf in_NumberOfCycles == 0 assume infinite number of cycles\n//\t2)\tConsider 500,000,000 (5M) cycles to be infinite cycles \n//\t3)  Consider less than 1,000 cycles to be equivalent to 1 cycle for determining the allowable stress levels. \n//\t3)\tAluminum must have in_AnalysisMaterialProperties.fatigueStrength and fatigueNumberOfCycles set.\n//\t4)\tFor Steel, if in_AnalysisMaterialProperties.fatigueStrength is not set, assume that it is \n//\t\t50% of in_AnalysisMaterialProperties.tensileUltimateStrength\n//\t5)\tTBD For cycle values between 1,000 and 500,000,000, we need a graph of X-Number Cycles, and Y-Stress.  These\n//\t\tare usually log base 10 graphs. \n//\t\t\n//\tMaterial  \t\tFatigue\t\tNumber \t\tTensile\t\t\t\t\t\t\tBearing\t\t\t\t\t\t\tShear\n//\t\t\t\t\tGiven\t\tCycles\t\tStrength\t\t\t\t\t\tStrength\t\t\t\t\t\tStrength\n//\t-----------\t\t--------\t-------\t\t--------------\t\t\t\t\t-----------\t\t\t\t\t\t---------------\n//\tSteel/Aluminum\tYes\t\t\tN < 1000\ttensileYieldStrength\t\t\tbearingYieldStrength\t\t\tshearStrength\n//\tStee/Aluminum\tYes\t\t\t1000 < N \tfatigueStrength\t\t\t\t\tSF * bearingUltimateStrength\tSF * shearStrength\n//\tSteel\t\t\tNo\t\t\t1000 < N \t.5 * tensileUltimateStrength\tSF  * bearingYieldStrength\t\tSF  * shearStrength\n//\tAluminum\t\tNo\t\t\t(Not Allowed, throw exception)\n//\n// SF - Scale Factor = fatigueStrength / tensileUltimateStrength; \n\nvoid ComputeAllowableStressLevels(\tint\t\t\t\t\t\t\t\t\t\tin_NumberOfCycles,\n\t\t\t\t\t\t\t\t\tconst AnalysisMaterialProperties\t\t&in_AnalysisMaterialProperties,\n\t\t\t\t\t\t\t\t    AnalysisMaterialProperties_Allowables\t&out_AnalysisMaterialProperties )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow (isis::application_exception)\n{\n\t///////////////////////////////////////////////\n\t// zero out values\n\t///////////////////////////////////////////////\n\tout_AnalysisMaterialProperties.materialName = \"\";\n\tout_AnalysisMaterialProperties.tensileStrength\t= 0;\n\tout_AnalysisMaterialProperties.bearingStrength\t= 0;\n\tout_AnalysisMaterialProperties.shearStrength\t= 0;\n\tout_AnalysisMaterialProperties.numberOfCycles\t= 0;\n\n\t///////////////////////////////////////////////\n\t// Only Aluminum and Steel Currently Supported\n\t///////////////////////////////////////////////\n\tif ( ( in_AnalysisMaterialProperties.materialType != MATERIAL_ALUMINUM ) &&\n\t\t ( in_AnalysisMaterialProperties.materialType != MATERIAL_STEEL ) )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t{\n\t\t// zzz fix this to use the common functions\n\t\tstd::string tempMaterialType = \"Unknown\";\n\t\tif (in_AnalysisMaterialProperties.materialType == MATERIAL_CERAMIC )tempMaterialType = \"Ceramic\";\n\t\tif (in_AnalysisMaterialProperties.materialType == MATERIAL_PLASTIC )tempMaterialType = \"Plastic\";\n\n\t\tstd::string TempError = \"Function ComputeAllowableStressLevels(...) for material \" + in_AnalysisMaterialProperties.materialName + \n\t\t\" was passed: \" + tempMaterialType + \n\t\t\".  Currently only Steel and Aluminum are supported. Plastic and Ceramic will be supported in future releases.\";   \n\t\tthrow isis::application_exception(TempError.c_str());\n\t}\n\n\t///////////////////////////////////////////////////////\n\t// Fatigue strength must be given defined for Aluminum\n\t///////////////////////////////////////////////////////\n\tif ( ( in_AnalysisMaterialProperties.materialType == MATERIAL_ALUMINUM ) &&\n\t\t ( !in_AnalysisMaterialProperties.fatigueStrengthDefined ) )\n\t{\n\t\tstd::string TempError = \"Function ComputeAllowableStressLevels(...) for material \" + in_AnalysisMaterialProperties.materialName + \n\t\t\" does not have a fatigue strength defined.  Aluminum must have fatigue strength defined.\";   \n\t\tthrow isis::application_exception(TempError.c_str());\t\t\n\t}\n\n\t////////////////////////////////////////\n\t// Tensile yield strength must be given\n\t////////////////////////////////////////\n\tif ( !in_AnalysisMaterialProperties.tensileYieldStrengthDefined )\n\t{\n\t\tstd::string TempError = \"Function ComputeAllowableStressLevels(...) for material \" + in_AnalysisMaterialProperties.materialName + \n\t\t\" does not have a tensile yield strength defined.  All material must have tensile yield strength defined.\";   \n\t\tthrow isis::application_exception(TempError.c_str());\t\t\n\t}\n\n\t////////////////////////////////////////\n\t// Tensile Ultimate strength must be given\n\t////////////////////////////////////////\n\tif ( !in_AnalysisMaterialProperties.tensileUltimateStrengthDefined )\n\t{\n\t\tstd::string TempError = \"Function ComputeAllowableStressLevels(...) for material \" + in_AnalysisMaterialProperties.materialName + \n\t\t\" does not have a tensile ultimate strength defined.  All material must have tensile ultimate strength defined.\";   \n\t\tthrow isis::application_exception(TempError.c_str());\t\t\n\t}\n\n\n\t//////////////////////////////////////////////\n\t// Shear Strength must be given for Aluminum\n\t/////////////////////////////////////////////\n\tif ( !in_AnalysisMaterialProperties.shearStrengthDefined &&  in_AnalysisMaterialProperties.materialType == MATERIAL_ALUMINUM  )\n\t{\n\t\tstd::string TempError = \"Function ComputeAllowableStressLevels(...) for material \" + in_AnalysisMaterialProperties.materialName + \n\t\t\" does not have a shear strength defined.  Aluminum must have shear strength defined.\";   \n\t\tthrow isis::application_exception(TempError.c_str());\t\t\n\t}\n\n\t////////////////////////////////////////\n\t// Set Material Name and Type\n\t////////////////////////////////////////\n\tout_AnalysisMaterialProperties.materialName = in_AnalysisMaterialProperties.materialName;\n\tout_AnalysisMaterialProperties.materialType = in_AnalysisMaterialProperties.materialType;\n\n\t////////////////////////////////////////\n\t// Set Number of cycles\n\t////////////////////////////////////////\n\tout_AnalysisMaterialProperties.numberOfCycles = in_NumberOfCycles;\n\n\t////////////////////////////////////////\n\t// Compute tempShearStrength\n\t////////////////////////////////////////\n\tdouble tempShearStrength;\n\tif ( in_AnalysisMaterialProperties.shearStrengthDefined )\n\t{\n\t\ttempShearStrength = in_AnalysisMaterialProperties.shearStrength;\n\t}\n\telse \n\t{\n\t\t// Case for steel when shear strength is not defined, use rule of thumb\n\t\ttempShearStrength = .58 * in_AnalysisMaterialProperties.tensileYieldStrength;\n\t}\n\n\t////////////////////////////////////////\n\t// No Fatigue Case\n\t////////////////////////////////////////\n\tif ( ( in_NumberOfCycles != 0 ) && ( in_NumberOfCycles < 1000 ) )\n\t{\n\t\tout_AnalysisMaterialProperties.tensileStrength = in_AnalysisMaterialProperties.tensileYieldStrength;\n\t\tout_AnalysisMaterialProperties.shearStrength   = tempShearStrength;\n\t\t\n\t\tif (in_AnalysisMaterialProperties.bearingYieldStrengthDefined )\n\t\t\tout_AnalysisMaterialProperties.bearingStrength = in_AnalysisMaterialProperties.bearingYieldStrength;\n\t\telse\n\t\t\tout_AnalysisMaterialProperties.bearingStrength = in_AnalysisMaterialProperties.tensileYieldStrength;\n\t\t\n\t}\n\telse\n\t{\n\t\t/////////////////////////////////////////\n\t\t// Fatigue Case - Steel and Aluminum\n\t\t////////////////////////////////////////\n\n\t\t// Note fatigue strength would be defined for aluminum as checked above, maybe not for steel.\n\t\tdouble tempFatigueStrength;\n\n\t\tif ( in_AnalysisMaterialProperties.fatigueStrengthDefined )\n\t\t\ttempFatigueStrength = in_AnalysisMaterialProperties.fatigueStrength;\n\t\telse\n\t\t\ttempFatigueStrength = .5 * in_AnalysisMaterialProperties.tensileUltimateStrength;\n\n\t\t// Tensile\n\t\tout_AnalysisMaterialProperties.tensileStrength = tempFatigueStrength;\t\t\n\n\t\t// Bearing\n\t\tbool stressComputed = false;\n\t\tstressComputed = StressValueComputed(\t\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileUltimateStrengthDefined,\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileUltimateStrength,\t\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.bearingUltimateStrengthDefined,\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.bearingUltimateStrength,\n\t\t\t\t\t\t\ttempFatigueStrength,\n\t\t\t\t\t\t\tout_AnalysisMaterialProperties.bearingStrength );\n\n\t\t\n\t\tif ( !stressComputed )\n\t\t   stressComputed = StressValueComputed(\t\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileYieldStrengthDefined,\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileYieldStrength,\t\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.bearingYieldStrengthDefined,\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.bearingYieldStrength,\n\t\t\t\t\t\t\ttempFatigueStrength,\n\t\t\t\t\t\t\tout_AnalysisMaterialProperties.bearingStrength );\n\n\t\tif ( !stressComputed )\n\t\t\tout_AnalysisMaterialProperties.bearingStrength = tempFatigueStrength;\n\n\t\t// Shear\n\t\tstressComputed = StressValueComputed(\t\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileUltimateStrengthDefined,\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileUltimateStrength,\t\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\ttempShearStrength, \n\t\t\t\t\t\t\ttempFatigueStrength,\n\t\t\t\t\t\t\tout_AnalysisMaterialProperties.shearStrength );\n\n\t\tif ( !stressComputed )\n\t\t\tstressComputed = StressValueComputed(\t\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileYieldStrengthDefined,\n\t\t\t\t\t\t\tin_AnalysisMaterialProperties.tensileYieldStrength,\t\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\ttempShearStrength, \n\t\t\t\t\t\t\ttempFatigueStrength,\n\t\t\t\t\t\t\tout_AnalysisMaterialProperties.shearStrength );\n\t\tif ( !stressComputed )\n\t\t\tout_AnalysisMaterialProperties.shearStrength =  .5 * in_AnalysisMaterialProperties.shearStrength;\n\n\t}\n\n\t///////////////////////////////////////////////\n\t//\tAt this point, the strength properties \n\t//\tshould be set.  It would be a programming\n\t//\terror if this was not the case. Throw\n\t//\tand exception if the strength properties \n\t//\tare not set.\n\t///////////////////////////////////////////////\n\n\tif ( out_AnalysisMaterialProperties.tensileStrength\t== 0 ||\n\t\t out_AnalysisMaterialProperties.bearingStrength\t== 0 ||\n\t     out_AnalysisMaterialProperties.shearStrength\t== 0 )\n\t{\n\t\tstd::ostringstream tensileStrength_str;\n\t\tstd::ostringstream bearingStrength_str;\n\t\tstd::ostringstream shearStrength_str;\n\n\t\ttensileStrength_str << out_AnalysisMaterialProperties.tensileStrength;\n\t\tbearingStrength_str << out_AnalysisMaterialProperties.bearingStrength;\n\t\tshearStrength_str   << out_AnalysisMaterialProperties.shearStrength;\n\n\t\tstd::string TempError = \"Function ComputeAllowableStressLevels(...) for material \" + in_AnalysisMaterialProperties.materialName + \n\t\t\" failed to compute the all of the strength material properties.  Computed properties are: Tensile Strength: \" +\n\t\ttensileStrength_str.str() + \", Bearing Strength: \" + bearingStrength_str.str() + \", Shear Strength: \" + shearStrength_str.str() + \".\";   \n\t\tthrow isis::application_exception(TempError.c_str());\t\t\n\t}\n}\n\nenum e_UnitType\n{\n\tUNIT_MPA,\n\tUNIT_GPA,\n\tUNIT_NA\n};\n\n\ne_UnitType RetrieveUnitType(\tconst std::string &in_MaterialName,\n\t\t\t\t\t\t\t\tconst std::string &in_Units )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow (isis::application_exception)\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tstd::string units = isis::ConvertToUpperCase(in_Units);\t\n\n\tif ( strcmp(units.c_str(), \"MPA\") == 0  )\t\t\n\t\treturn UNIT_MPA;\n\telse \n\t\tif ( strcmp(units.c_str(), \"GPA\")  == 0  ) \n\t\t\treturn UNIT_GPA;\n\t\telse \n\t\t\tif ( strcmp(units.c_str(), \"N/A\")  == 0  ) \n\t\t\t\treturn UNIT_NA;\n\n\t// No known type found.\n\tstd::string TempError = \"Function RetrieveUnitType(...) for material \" + in_MaterialName + \n\t\t\" was passed: \" + in_Units + \n\t\t\".  Acceptable types (case insensitive) are: MPA, GPA, and N/A.\";   \n\tthrow isis::application_exception(TempError.c_str());\n}\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Description:\n//\t\tThis function converts string representations of material properties\n//\t\t(i.e. in_MaterialMetrics_map[in_MaterialPropertyName] ) to doubles and stores \n//\t\tthe results in out_Property.\n//\t\t\n//\t\tNote -\tAll units stored in out_Property will be in MPa except for unit-less values\n//\t\t\t\tsuch as PoissonsRatio.\n//\t\t\n// Pre-Conditions:\n//\t\tif in_MaterialPropertyName[in_MaterialPropertyName] exists\n//\t\t\tin_MaterialPropertyName[in_MaterialPropertyName].units must be MPa, GPa, or N/A\n//\n// Post-Conditions:\n//\t\tif in_MaterialPropertyName[in_MaterialPropertyName] not exists\n//\t\t\treturn (no action taken)\n//\t\telse\n//\t\t\tif in_MaterialPropertyName[in_MaterialPropertyName].units != MPa, GPa, or N/A\n//\t\t\t\tthrow isis::application_exception\n//\t\t\telse\n//\t\t\t\tout_Property =  in_MaterialPropertyName[in_MaterialPropertyName].value\n//\t\t\t\tout_PropertyDefnied = true\n//\t\t\t\tif in_MaterialPropertyName[in_MaterialPropertyName].units == GPa\n//\t\t\t\t\tscale out_Property to be in MPA\n//\t\t\t\t\nvoid SetSingleAnalysisMaterialProperty(  \n\t\t\t\t\tconst std::string\t\t\t\t\t\t&in_MaterialPropertyName,\n\t\t\t\t\tconst std::map<std::string, MaterialMetrics> &in_MaterialMetrics_map,\n\t\t\t\t\tdouble\t\t\t\t\t\t\t\t\t&out_Property,\n\t\t\t\t\tbool\t\t\t\t\t\t\t\t\t&out_PropertyDefnied) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow (isis::application_exception)\n{\n\tstd::map<std::string, MaterialMetrics>::const_iterator itr = in_MaterialMetrics_map.find(in_MaterialPropertyName);\n\n\tif (itr != in_MaterialMetrics_map.end() )\n\t{\n\t\t// Note Poissoin's ration could be zero.  Since we will analyze metals, this should not be a problem.\n\t\tif ( itr->second.value == 0 )  \n\t\t{\n\t\t\tout_PropertyDefnied = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tout_Property = itr->second.value;\n\t\t\tout_PropertyDefnied = true;\n\t\t\tif( RetrieveUnitType(in_MaterialPropertyName,itr->second.units ) == UNIT_GPA ) out_Property *= 1000;\n\t\t}\n\t}\n}\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// This funcdtion will convert integer values.  The only integer value is FatigueNumberOfCycles\n// which has no units.\nvoid SetSingleAnalysisMaterialProperty(  \n\t\t\t\t\tconst std::string\t\t\t\t\t\t&in_MaterialPropertyName,\n\t\t\t\t\tconst std::map<std::string, MaterialMetrics> &in_MaterialMetrics_map,\n\t\t\t\t\tlong\t\t\t\t\t\t\t\t\t&out_Property,\n\t\t\t\t\tbool\t\t\t\t\t\t\t\t\t&out_PropertyDefnied)\n{\n\tstd::map<std::string, MaterialMetrics>::const_iterator itr = in_MaterialMetrics_map.find(in_MaterialPropertyName);\n\n\tif (itr != in_MaterialMetrics_map.end() )\n\t{\n\t\t//out_Property = strtol(itr->second.value.c_str(), NULL,10 );\n\t\tout_Property = itr->second.value;\n\n\t\tout_PropertyDefnied = true;\n\t}\n}\n////////////////////////////////////////////////////////////////////////////////////////////////////\nvoid PopulateAnalysisMaterialStruct( const Material\t\t\t\t &in_Material, \n\t\t\t\t\t\t\t\t\t AnalysisMaterialProperties  &out_AnalysisMaterialProperties_struct )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow (isis::application_exception)\n{\n\tout_AnalysisMaterialProperties_struct.materialType = in_Material.materialType;\n\tout_AnalysisMaterialProperties_struct.materialName = in_Material.materialName;\n\n\t//std::map<std::string, MaterialMetrics> i;\n\n\tSetSingleAnalysisMaterialProperty(\t\"ModulusOfElasticity\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.modulusOfElasticity,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.modulusOfElasticityDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"PoissonsRatio\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.poissonsRatio,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.poissonsRatioDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"TensileYieldStrength\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.tensileYieldStrength,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.tensileYieldStrengthDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"TensileUltimateStrength\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.tensileUltimateStrength,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.tensileUltimateStrengthDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"ShearStrength\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.shearStrength,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.shearStrengthDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"BearingYieldStrength\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.bearingYieldStrength,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.bearingYieldStrengthDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"BearingUltimateStrength\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.bearingUltimateStrength,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.bearingUltimateStrengthDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"FatigueStrength\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.fatigueStrength,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.fatigueStrengthDefined);\n\n\tSetSingleAnalysisMaterialProperty(\t\"FatigueNumberOfCycles\", \n\t\t\t\t\t\t\t\t\t\tin_Material.materialMetrics_map, \n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.fatigueNumberOfCycles,\n\t\t\t\t\t\t\t\t\t\tout_AnalysisMaterialProperties_struct.fatigueNumberOfCyclesDefined);\n\n} \n\n\t////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\t// in_UnitsConversionFactor should equal to 1.0 if no conversion.\n\tbool MaterialPropertyFound_RetrieveValue( \n\t\t\t\t\t\tconst boost::property_tree::ptree::value_type\t&in_Material_pt,\n\t\t\t\t\t\tconst std::string\t    &in_MaterialName,\n\t\t\t\t\t\tconst std::string\t\t&in_MaterialLibPropertyName, // e.g. strength_tensile_ultimate\n\t\t\t\t\t\tconst\t\t\t\t\tstd::string in_MaterialLibRequiredUnit,  // e.g. Pa\n\t\t\t\t\t\tdouble\t\t\t\t\tin_UnitsConversionFactor,  // e.g. PASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR\n\t\t\t\t\t\tconst std::string\t\t&in_ConvertToUnit,\n\t\t\t\t\t\tdouble\t\t\t\t\t&out_Value)\n\t{\n\n\t\t//std::clog << std::endl << \"   \" << in_Material_pt.first.data();\n\n\t\tbool materialFound = false;\n\n\t\t// Case insensitive check.\n\t\tif ( isis::ConvertToUpperCase(std::string(in_Material_pt.first.data())) == isis::ConvertToUpperCase(in_MaterialLibPropertyName) )\n\t\t{\n\t\t\tstd::string unit;\n\t\t\tif ( in_MaterialLibRequiredUnit.size() == 0 )\n\t\t\t{\n\t\t\t\tunit = \"None\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tunit = in_Material_pt.second.get<std::string>(\"unit\");\n\t\t\t\t}\n\t\t\t\tcatch (...)  // Could not get the unit, but units are required.  Assume the property is not defined\n\t\t\t\t{\n\t\t\t\t\t\n\n\t\t\t\t\tisis_LOG(lg, isis_CONSOLE_FILE, isis_ERROR) << \"Material units not defined for: \" << isis_EOL <<\n\t\t\t\t\t\t\t\t\t\t\t  \"   Material Name:     \" << in_MaterialName << isis_EOL <<\n\t\t\t\t\t\t\t\t\t\t\t  \"   Material Property: \" << in_MaterialLibPropertyName << isis_EOL <<\n\t\t\t\t\t\t\t\t\t\t\t  \"   Note:              Without units, this material property cannot be used.\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmaterialFound = true;\n\t\t\tif ( in_MaterialLibRequiredUnit.size() > 0 )\n\t\t\t{\n\t\t\t\t// Must verify units.  \n\t\t\t\tif ( isis::ConvertToUpperCase(in_MaterialLibRequiredUnit) != isis::ConvertToUpperCase(unit) )\n\t\t\t\t{\n\t\t\t\t\tstd::stringstream errorString;\n\t\t\t\t\t\t\t\terrorString <<\n\t\t\t\t\t\t\t\t\t\t\"Material:          \" <<  in_MaterialName << std::endl <<\n\t\t\t\t\t\t\t\t\t\t\"Material Property: \" <<  in_MaterialLibPropertyName << std::endl <<\n\t\t\t\t\t\t\t\t\t\t\"Material Unit:\t    \" <<  unit  << std::endl <<\n\t\t\t\t\t\t\t\t\t\t\"Required Unit:     \" << in_MaterialLibRequiredUnit << std::endl <<\n\t\t\t\t\t\t\t\t\t\t\"The units in the material library are incompatible with the required units.\";\n\t\t\t\t\tthrow isis::application_exception(errorString.str());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::string value_string =  in_Material_pt.second.get<std::string>(\"value\");\n\n\t\t\tif ( isis::ConvertToUpperCase(value_string) == \"NONE\") return false;\n\n\t\t\tout_Value =  atof(value_string.c_str()) * in_UnitsConversionFactor;\n\t\t\t// Alternate conversion approach, should consider.\n\t\t\t// boost::optional<float> v = pt.get_optional<float>(\"a.path.to.float.value\");\n\t\t\t// http://www.boost.org/doc/libs/1_43_0/doc/html/boost_propertytree/accessing.html\n\n\t\t\tif ( out_Value == 0 )\n\t\t\t{\n\t\t\t\tstd::stringstream errorString;\n\t\t\t\terrorString <<\n\t\t\t\t\t\"Material:          \" <<  in_MaterialName << std::endl <<\n\t\t\t\t\t\"Material Property: \" <<  in_MaterialLibPropertyName << std::endl <<\n\t\t\t\t\t\"Material Unit:\t    \" <<  unit  << std::endl <<\n\t\t\t\t\t\"Value:             \" << value_string << std::endl <<\n\t\t\t\t\t\"A zero value is not allowed.\";\n\t\t\t\tthrow isis::application_exception(errorString.str());\n\t\t\t}\n\t\t\t\n\n\t\t\tisis_LOG(lg, isis_FILE, isis_INFO) <<\n\t\t\t\t\t\"Material:                \" <<  in_MaterialName << isis_EOL <<\n\t\t\t\t\t\"Material Property:       \" <<  in_MaterialLibPropertyName << isis_EOL <<\n\t\t\t\t\t\"Material Unit:\t          \" <<  unit  << isis_EOL <<\n\t\t\t\t\t\"Material Library Value:  \" <<  value_string << isis_EOL <<\n\t\t\t\t\t\"Unit Conversion Factor:  \" <<  in_UnitsConversionFactor << isis_EOL <<\n\t\t\t\t\t\"Convert to Unit:         \" << in_ConvertToUnit << isis_EOL <<\n\t\t\t\t\t\"Converted Value\t\t  \" << out_Value;\n\t\t}\n\n\t\treturn materialFound;\n\t}\n\t////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\t// Throw an exception if:\n\t// a) All the meterials in in_MaterialNames are not found in n_MaterialLibrary_PathAndFileName\n\t// b) Material properties are not in Pa or kg/m3. \n\t//\n\t//  Note - this function converts :\n\t//\t\t\t\tPa to MPa\n\t//\t\t\t\tkg/m3 to kg/mm3 \n\t//\t\t\t\tW/(m*K) to W/(mm*K)\n\t//\t\t\t\tand stores the converted values\n\t//         in out_Materials\n\t//\n\n\tvoid ReadMaterialsLibrary(  \tconst std::string &in_MaterialLibrary_PathAndFileName,\n\t\t\t\t\t\t\t\t\tconst std::set<std::string> &in_MaterialNames,\n\t\t\t\t\t\t\t\t\tstd::map<std::string, Material> &out_Materials ) \n\t\t\t\t\t\t\t\t\t\t\t\t\t throw (isis::application_exception)\n\t{\n\t\tusing boost::property_tree::ptree;\n\n\t\tstd::string currentMaterialName;\n\t\tstd::string currentMaterialProperty;\n\n\t\ttry\n\t\t{\n\t\t\t// Create a set of material names.  When a material is found remove it from the set.\n\t\t\t// If the set is not empty at the end of the program, throw and exception.\n\t\t\tstd::set<std::string>  notFound_MaterialNames_set;\n\t\t\tfor each ( std::string i in in_MaterialNames) notFound_MaterialNames_set.insert(i);\n\n\t\t\tboost::filesystem::path p(in_MaterialLibrary_PathAndFileName);\n\t\t\tif (boost::filesystem::exists(p))\n\t\t\t{\n\t\t\t\tif (boost::filesystem::is_regular_file(p))\n\t\t\t\t{\n\t\t\t\t\tptree pt;\n\t\t\t\t\tboost::property_tree::read_json(p.make_preferred().string(), pt);\n\t\t\t\t\tBOOST_FOREACH(ptree::value_type& materialLib_pt, pt.get_child(\"Material library\")) \n\t\t\t\t\t{\n\t\t\t\t\t\t//if (materialLib_pt.size() != 1 )\n\t\t\t\t\t\t//{\n\t\t\t\t\t\t//\tstd::stringstream errorString;\n\t\t\t\t\t\t//\t\terrorString <<\n\t\t\t\t\t\t//\t\t\t\t\"Function:         ReadMaterialsLibrary\" << endl <<\n\t\t\t\t\t\t//\t\t\t\t\"Material Library: \"  << in_MaterialLibrary_PathAndFileName << endl <<\n\t\t\t\t\t\t//\t\t\t\t\"Number of \\\"Material library\\\" tags: \" << pt.size() << endl <<\n\t\t\t\t\t\t//\t\t\t\t\"The material library must contain one and only one \\\"Material library\\\" tag.\";\n\t\t\t\t\t\t//\t\tthrow isis::application_exception(errorString.str());\n\t\t\t\t\t\t//}\n\n\t\t\t\t\t\t//std::clog << std::endl << materialLib_pt.first.data();\n\t\t\t\t\t\tfor each ( const std::string materialName in in_MaterialNames )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurrentMaterialName = materialName;\n\t\t\t\t\t\t\tif ( isis::ConvertToUpperCase(std::string(materialLib_pt.first.data())) == isis::ConvertToUpperCase(materialName) )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnotFound_MaterialNames_set.erase(materialName);\n\t\t\t\t\t\t\t\tout_Materials[materialName].materialName = materialName;\n\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.materialName = materialName;\n\n\t\t\t\t\t\t\t\t//std::cout << std::endl << materialLib_pt.first.data();\n\t\t\t\t\t\t\t\tBOOST_FOREACH(const ptree::value_type& material_pt, materialLib_pt.second)\n\t\t\t\t\t\t\t\t{\t\t\n\t\t\t\t\t\t\t\t\tdouble materialPropertyValue;\n\n\t\t\t\t\t\t\t\t\tif ( isis::ConvertToUpperCase(material_pt.first) ==  \"MATERIAL_CATEGORY\" )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tstd::string materialType =  material_pt.second.get<std::string>(\"value\");\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].materialType = MaterialType_enum(materialType);\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.materialType = MaterialType_enum(materialType);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__modulus_elastic\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Pa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"MPa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.modulusOfElasticityDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.modulusOfElasticity = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.modulusOfElasticityUnit = CADUnitsPressure_enum(\"MPa\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__ratio_poissons\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\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\t1.0,\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\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.poissonsRatioDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.poissonsRatio = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__strength_tensile_yield\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Pa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"MPa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.tensileYieldStrengthDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.tensileYieldStrength = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.tensileYieldStrengthUnit = CADUnitsPressure_enum(\"MPa\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__strength_tensile_ultimate\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Pa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"MPa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.tensileUltimateStrengthDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.tensileUltimateStrength = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.tensileUltimateStrengthUnit = CADUnitsPressure_enum(\"MPa\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__strength_shear\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Pa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"MPa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.shearStrengthDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.shearStrength = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.shearStrengthUnit = CADUnitsPressure_enum(\"MPa\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__strength_fatigue\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Pa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"MPa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.fatigueStrengthDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.fatigueStrength = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.fatigueStrengthUnit = CADUnitsPressure_enum(\"MPa\");\n\t\t\t\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__strength_bearing_yield\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Pa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"MPa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.bearingYieldStrengthDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.bearingYieldStrength = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.bearingYieldStrengthUnit = CADUnitsPressure_enum(\"MPa\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"mechanical__strength_bearing_ultimate\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Pa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPASCAL_TO_MEGA_PASCAL_CONVERSION_FACTOR,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"MPa\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.bearingUltimateStrengthDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.bearingUltimateStrength = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.bearingUltimateStrengthUnit = CADUnitsPressure_enum(\"MPa\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"density\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\"kg/m3\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"kg/m^3\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tM_CUBED_TO_MM_CUBED_RECIPROCAL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"kg/mm3\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.denstiyDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.density= materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.densityUnit = CADUnitsDensity_enum(\"kg/mm3\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"thermal__conductivity\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"W/(m*K)\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tM_TO_MM_RECIPROCAL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"w/mmk\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.thermalConductivityDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.thermalConductivity = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.thermalConductivityUnit = CADUnitsThermalConductivity_enum(\"w/mmk\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentMaterialProperty = \"thermal__capacity_specific_heat\";\n\n\t\t\t\t\t\t\t\t\tif ( MaterialPropertyFound_RetrieveValue( material_pt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMaterialProperty,\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"J/(kg-K)\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t1.0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"j/kgk\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaterialPropertyValue ) )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.heatCapacityDefined = true;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.heatCapacity = materialPropertyValue;\n\t\t\t\t\t\t\t\t\t\tout_Materials[materialName].analysisMaterialProperties.heatCapacityUnit = CADUnitsHeatCapacity_enum(\"j/kgk\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}  // END BOOST_FOREACH(const ptree::value_type& material_pt, materialLib_pt.second)\t\t\t\t\t\n\t\t\t\t\t\t\t}  // END if ( isis::ConvertToUpperCase(std::string(materialLib_pt.first.data())) == isis::ConvertToUpperCase(materialName) )\n\t\t\t\t\t\t}  // END for each ( const std::string i in in_MaterialNames )\n\t\t\t\t\t} // END BOOST_FOREACH(ptree::value_type& materialLib_pt, pt.get_child(\"Material library\")) \n\t\t\t\t} // END if (boost::filesystem::is_regular_file(p))\n\t\t\t} // END if (boost::filesystem::exists(p))\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::stringstream errorString;\n\t\t\t\terrorString << \"Material library input file not found: \" << in_MaterialLibrary_PathAndFileName;\n\t\t\t\tthrow isis::application_exception(errorString.str());\n\t\t\t}\n\n\t\t\tif ( notFound_MaterialNames_set.size() != 0 )\n\t\t\t{\n\t\t\t\tstd::stringstream errorString;\n\t\t\t\terrorString << \"Material(s) not found in the material library: \" << in_MaterialLibrary_PathAndFileName << std::endl <<\n\t\t\t\t\t\t\t\t\"Material(s):\" << std::endl;\n\t\t\t\tfor each (std::string i in notFound_MaterialNames_set) errorString << i << std::endl;\n\t\t\t\tthrow isis::application_exception(errorString.str());\n\n\t\t\t}\n\n\t\t}\n\t\tcatch(const boost::property_tree::ptree_error &exc)\n\t\t{\t\t\n\t\t\tstd::stringstream errorString;\n\t\t\terrorString << \"Input file processing error: \" << in_MaterialLibrary_PathAndFileName <<  std::endl <<\n\t\t\t\t\t\t\t\"   Material Name:     \" << currentMaterialName <<  std::endl <<\n\t\t\t\t\t\t\t\"   Material Property: \" << currentMaterialProperty <<  std::endl <<\n\t\t\t\t\t\t\t\"   Error: \" << exc.what();\n\t\t\tthrow isis::application_exception(errorString.str());\n\t\t}\n\n\t\tcatch(const isis::application_exception &exc)\n\t\t{\t\t\n\t\t\tstd::stringstream errorString;\n\t\t\terrorString << \"Input file processing error: \" << in_MaterialLibrary_PathAndFileName <<  std::endl <<\n\t\t\t\t\t\t\t\"   Material Name:     \" << currentMaterialName <<  std::endl <<\n\t\t\t\t\t\t\t\"   Material Property: \" << currentMaterialProperty <<  std::endl <<\n\t\t\t\t\t\t\t\"   Error: \" << exc.what();\n\t\t\tthrow isis::application_exception(errorString.str());\n\t\t}\n\n\t} // END ReadMaterialsLibrary\n\n\n} // namespace isis", "meta": {"hexsha": "d252a59421a96b199980eb6ae2b850d25ed24192", "size": 38521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CADAssembler/CADCreoParametricCreateAssemblyFunctions/MaterialProperties.cpp", "max_stars_repo_name": "lefevre-fraser/openmeta-mms", "max_stars_repo_head_hexsha": "08f3115e76498df1f8d70641d71f5c52cab4ce5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CADAssembler/CADCreoParametricCreateAssemblyFunctions/MaterialProperties.cpp", "max_issues_repo_name": "lefevre-fraser/openmeta-mms", "max_issues_repo_head_hexsha": "08f3115e76498df1f8d70641d71f5c52cab4ce5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CADAssembler/CADCreoParametricCreateAssemblyFunctions/MaterialProperties.cpp", "max_forks_repo_name": "lefevre-fraser/openmeta-mms", "max_forks_repo_head_hexsha": "08f3115e76498df1f8d70641d71f5c52cab4ce5f", "max_forks_repo_licenses": ["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.2820224719, "max_line_length": 170, "alphanum_fraction": 0.6670647179, "num_tokens": 9031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.016657039643116853, "lm_q1q2_score": 0.0074212031273335815}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n//\n// Comparison operators for cpp_int_backend:\n//\n#ifndef BOOST_MP_CPP_INT_COMPARISON_HPP\n#define BOOST_MP_CPP_INT_COMPARISON_HPP\n\n#include <boost/multiprecision/detail/constexpr.hpp>\n#include <boost/type_traits/make_unsigned.hpp>\n\nnamespace boost {\nnamespace multiprecision {\nnamespace backends {\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable : 4018 4389 4996)\n#endif\n\n//\n// Start with non-trivial cpp_int's:\n//\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_integer_type SignType,\n          cpp_int_check_type Checked, class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<\n        cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>>::value,\n    bool>::type\neval_eq(\n    const cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> &a,\n    const cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator> &b)\n    BOOST_NOEXCEPT {\n  return (a.sign() == b.sign()) && (a.size() == b.size()) &&\n         std_constexpr::equal(a.limbs(), a.limbs() + a.size(), b.limbs());\n}\ntemplate <unsigned MinBits1, unsigned MaxBits1, cpp_integer_type SignType1,\n          cpp_int_check_type Checked1, class Allocator1, unsigned MinBits2,\n          unsigned MaxBits2, cpp_integer_type SignType2,\n          cpp_int_check_type Checked2, class Allocator2>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1,\n                                        Allocator1>>::value &&\n        !is_trivial_cpp_int<cpp_int_backend<MinBits2, MaxBits2, SignType2,\n                                            Checked2, Allocator2>>::value,\n    bool>::type\neval_eq(const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1,\n                              Allocator1> &a,\n        const cpp_int_backend<MinBits2, MaxBits2, SignType2, Checked2,\n                              Allocator2> &b) BOOST_NOEXCEPT {\n  return (a.sign() == b.sign()) && (a.size() == b.size()) &&\n         std_constexpr::equal(a.limbs(), a.limbs() + a.size(), b.limbs());\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_eq(const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked,\n                              Allocator> &a,\n        limb_type b) BOOST_NOEXCEPT {\n  return (a.sign() == false) && (a.size() == 1) && (*a.limbs() == b);\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_eq(const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked,\n                              Allocator> &a,\n        signed_limb_type b) BOOST_NOEXCEPT {\n  return (a.sign() == (b < 0)) && (a.size() == 1) &&\n         (*a.limbs() == boost::multiprecision::detail::unsigned_abs(b));\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_eq(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              Allocator> &a,\n        limb_type b) BOOST_NOEXCEPT {\n  return (a.size() == 1) && (*a.limbs() == b);\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_eq(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              Allocator> &a,\n        signed_limb_type b) BOOST_NOEXCEPT {\n  return (b < 0)\n             ? eval_eq(a, cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                          Checked, Allocator>(b))\n             : eval_eq(a, static_cast<limb_type>(\n                              b)); // Use bit pattern of b for comparison\n}\n\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_lt(const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked,\n                              Allocator> &a,\n        limb_type b) BOOST_NOEXCEPT {\n  if (a.sign())\n    return true;\n  if (a.size() > 1)\n    return false;\n  return *a.limbs() < b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\ninline BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_lt(const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked,\n                              Allocator> &a,\n        signed_limb_type b) BOOST_NOEXCEPT {\n  if ((b == 0) || (a.sign() != (b < 0)))\n    return a.sign();\n  if (a.sign()) {\n    if (a.size() > 1)\n      return true;\n    return *a.limbs() > boost::multiprecision::detail::unsigned_abs(b);\n  } else {\n    if (a.size() > 1)\n      return false;\n    return *a.limbs() < boost::multiprecision::detail::unsigned_abs(b);\n  }\n}\n\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_lt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              Allocator> &a,\n        limb_type b) BOOST_NOEXCEPT {\n  if (a.size() > 1)\n    return false;\n  return *a.limbs() < b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_lt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              Allocator> &a,\n        signed_limb_type b) BOOST_NOEXCEPT {\n  return (b < 0) ? a.compare(b) < 0\n                 : eval_lt(a, static_cast<limb_type>(\n                                  b)); // Use bit pattern of b for comparison\n}\n\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_gt(const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked,\n                              Allocator> &a,\n        limb_type b) BOOST_NOEXCEPT {\n  if (a.sign())\n    return false;\n  if (a.size() > 1)\n    return true;\n  return *a.limbs() > b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\ninline BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_gt(const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked,\n                              Allocator> &a,\n        signed_limb_type b) BOOST_NOEXCEPT {\n  if (b == 0)\n    return !a.sign() && ((a.size() > 1) || *a.limbs());\n  if (a.sign() != (b < 0))\n    return !a.sign();\n  if (a.sign()) {\n    if (a.size() > 1)\n      return false;\n    return *a.limbs() < boost::multiprecision::detail::unsigned_abs(b);\n  } else {\n    if (a.size() > 1)\n      return true;\n    return *a.limbs() > boost::multiprecision::detail::unsigned_abs(b);\n  }\n}\n\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_gt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              Allocator> &a,\n        limb_type b) BOOST_NOEXCEPT {\n  if (a.size() > 1)\n    return true;\n  return *a.limbs() > b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class Allocator>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    !is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                        Checked, Allocator>>::value,\n    bool>::type\neval_gt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              Allocator> &a,\n        signed_limb_type b) BOOST_NOEXCEPT {\n  return (b < 0) ? a.compare(b) > 0\n                 : eval_gt(a, static_cast<limb_type>(\n                                  b)); // Use bit pattern of b for comparison.\n}\n//\n// And again for trivial cpp_ints:\n//\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                       Checked, void>>::value,\n    bool>::value\neval_eq(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &b)\n    BOOST_NOEXCEPT {\n  return (a.sign() == b.sign()) && (*a.limbs() == *b.limbs());\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                       Checked, void>>::value,\n    bool>::value\neval_eq(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &b) BOOST_NOEXCEPT {\n  return *a.limbs() == *b.limbs();\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class U>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_unsigned<U>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_eq(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    U b) BOOST_NOEXCEPT {\n  return !a.sign() && (*a.limbs() == b);\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class S>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_signed<S>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_eq(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    S b) BOOST_NOEXCEPT {\n  return (a.sign() == (b < 0)) &&\n         (*a.limbs() == boost::multiprecision::detail::unsigned_abs(b));\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class U>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_unsigned<U>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_eq(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        U b) BOOST_NOEXCEPT {\n  return *a.limbs() == b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class S>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_signed<S>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_eq(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        S b) BOOST_NOEXCEPT {\n  typedef typename make_unsigned<S>::type ui_type;\n  if (b < 0) {\n    cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked, void> t(b);\n    return *a.limbs() == *t.limbs();\n  } else {\n    return *a.limbs() == static_cast<ui_type>(b);\n  }\n}\n\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                       Checked, void>>::value,\n    bool>::type\neval_lt(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked, void>\n        &b) BOOST_NOEXCEPT {\n  if (a.sign() != b.sign())\n    return a.sign();\n  return a.sign() ? *a.limbs() > *b.limbs() : *a.limbs() < *b.limbs();\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                       Checked, void>>::value,\n    bool>::type\neval_lt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &b) BOOST_NOEXCEPT {\n  return *a.limbs() < *b.limbs();\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class U>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_unsigned<U>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_lt(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    U b) BOOST_NOEXCEPT {\n  if (a.sign())\n    return true;\n  return *a.limbs() < b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class S>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_signed<S>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_lt(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    S b) BOOST_NOEXCEPT {\n  if (a.sign() != (b < 0))\n    return a.sign();\n  return a.sign()\n             ? (*a.limbs() > boost::multiprecision::detail::unsigned_abs(b))\n             : (*a.limbs() < boost::multiprecision::detail::unsigned_abs(b));\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class U>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_unsigned<U>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_lt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        U b) BOOST_NOEXCEPT {\n  return *a.limbs() < b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class S>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_signed<S>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_lt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        S b) BOOST_NOEXCEPT {\n  typedef typename make_unsigned<S>::type ui_type;\n  if (b < 0) {\n    cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked, void> t(b);\n    return *a.limbs() < *t.limbs();\n  } else {\n    return *a.limbs() < static_cast<ui_type>(b);\n  }\n}\n\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                       Checked, void>>::value,\n    bool>::type\neval_gt(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &b)\n    BOOST_NOEXCEPT {\n  if (a.sign() != b.sign())\n    return !a.sign();\n  return a.sign() ? *a.limbs() < *b.limbs() : *a.limbs() > *b.limbs();\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                       Checked, void>>::value,\n    bool>::type\neval_gt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &b) BOOST_NOEXCEPT {\n  return *a.limbs() > *b.limbs();\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class U>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_unsigned<U>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_gt(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    U b) BOOST_NOEXCEPT {\n  if (a.sign())\n    return false;\n  return *a.limbs() > b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class S>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_signed<S>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, signed_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_gt(\n    const cpp_int_backend<MinBits, MaxBits, signed_magnitude, Checked, void> &a,\n    S b) BOOST_NOEXCEPT {\n  if (a.sign() != (b < 0))\n    return !a.sign();\n  return a.sign()\n             ? (*a.limbs() < boost::multiprecision::detail::unsigned_abs(b))\n             : (*a.limbs() > boost::multiprecision::detail::unsigned_abs(b));\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class U>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_unsigned<U>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_gt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        U b) BOOST_NOEXCEPT {\n  return *a.limbs() > b;\n}\ntemplate <unsigned MinBits, unsigned MaxBits, cpp_int_check_type Checked,\n          class S>\nBOOST_MP_FORCEINLINE BOOST_MP_CXX14_CONSTEXPR typename enable_if_c<\n    is_signed<S>::value &&\n        is_trivial_cpp_int<cpp_int_backend<MinBits, MaxBits, unsigned_magnitude,\n                                           Checked, void>>::value,\n    bool>::type\neval_gt(const cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked,\n                              void> &a,\n        S b) BOOST_NOEXCEPT {\n  typedef typename make_unsigned<S>::type ui_type;\n  if (b < 0) {\n    cpp_int_backend<MinBits, MaxBits, unsigned_magnitude, Checked, void> t(b);\n    return *a.limbs() > *t.limbs();\n  } else {\n    return *a.limbs() > static_cast<ui_type>(b);\n  }\n}\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n} // namespace backends\n} // namespace multiprecision\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "0239a1a1c7d34f0d0f1bd4207d9330510bf4de8c", "size": 21228, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/multiprecision/cpp_int/comparison.hpp", "max_stars_repo_name": "henrywarhurst/matrix", "max_stars_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/boost_1_72_0/boost/multiprecision/cpp_int/comparison.hpp", "max_issues_repo_name": "henrywarhurst/matrix", "max_issues_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/boost_1_72_0/boost/multiprecision/cpp_int/comparison.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": 42.8848484848, "max_line_length": 80, "alphanum_fraction": 0.6481062747, "num_tokens": 5213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761018, "lm_q2_score": 0.026355352846119756, "lm_q1q2_score": 0.00741654375900957}}
{"text": "/// @file DeconvolverBase.tcc\n/// @brief Base class for a deconvolver\n/// @details This interface class defines a deconvolver used to estimate an\n/// image from a dirty image, psf optionally using a mask and a weights image.\n/// @ingroup Deconvolver\n///\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Tim Cornwell <tim.cornwell@csiro.au>\n///\n\n#include <string>\n\n#include <casacore/casa/aips.h>\n#include <boost/shared_ptr.hpp>\n#include <casacore/casa/Arrays/Array.h>\n#include <casacore/casa/Arrays/ArrayMath.h>\n#include <fft/FFTWrapper.h>\n#include <askap/AskapLogging.h>\nASKAP_LOGGER(decbaselogger, \".deconvolution.base\");\n\n#include <deconvolution/DeconvolverBase.h>\n#include <deconvolution/DeconvolverState.h>\n\nnamespace askap {\n\n    namespace synthesis {\n\n        template<class T, class FT>\n        DeconvolverBase<T, FT>::~DeconvolverBase()\n        {\n            auditAllMemory();\n        };\n\n        template<class T, class FT>\n        DeconvolverBase<T, FT>::DeconvolverBase(Vector<Array<T> >& dirty, Vector<Array<T> >& psf) :\n                itsBMaj(0.0), itsBMin(0.0), itsBPa(0.0)\n        {\n            init(dirty, psf);\n        }\n\n        template<class T, class FT>\n        DeconvolverBase<T, FT>::DeconvolverBase(Array<T>& dirty, Array<T>& psf) :\n                itsBMaj(0.0), itsBMin(0.0), itsBPa(0.0)\n        {\n            Vector<Array<T> > dirtyVec(1);\n            dirtyVec(0) = dirty.nonDegenerate();\n            Vector<Array<T> > psfVec(1);\n            psfVec(0) = psf.nonDegenerate();\n            init(dirtyVec, psfVec);\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::init(Vector<Array<T> >& dirtyVec, Vector<Array<T> >& psfVec)\n        {\n\n            ASKAPCHECK(psfVec.nelements() == dirtyVec.nelements(),\n                       \"Vectors of dirty images and PSF's not same length\");\n\n            itsNumberTerms = dirtyVec.nelements();\n\n            itsDirty.resize(itsNumberTerms);\n            itsPsf.resize(itsNumberTerms);\n            itsModel.resize(itsNumberTerms);\n            itsWeight.resize(itsNumberTerms);\n\n            ASKAPLOG_INFO_STR(decbaselogger, \"There are \" << itsNumberTerms << \" dirty images\");\n\n            for (uInt term = 0; term < itsNumberTerms; term++) {\n\n                ASKAPASSERT(dirtyVec(term).nonDegenerate().shape().nelements() == 2);\n                ASKAPASSERT(psfVec(term).nonDegenerate().shape().nelements() == 2);\n\n                this->itsDirty(term) = dirtyVec(term).nonDegenerate().copy();\n                this->itsPsf(term) = psfVec(term).nonDegenerate().copy();\n\n                ASKAPASSERT(this->itsPsf(term).shape().conform(this->itsDirty(term).shape()));\n\n                ASKAPLOG_INFO_STR(decbaselogger, \"Dirty image(\" << term << \") has shape: \"\n                                      << this->dirty(term).shape());\n\n                this->model(term).resize(this->dirty(term).shape());\n                this->model(term).set(T(0.0));\n            }\n\n            casa::IPosition minPos;\n            casa::IPosition maxPos;\n            T minVal, maxVal;\n            ASKAPLOG_INFO_STR(decbaselogger, \"Validating PSF\");\n            casa::minMax(minVal, maxVal, minPos, maxPos, this->psf(0));\n\n            const Int nx(this->psf(0).shape()(0));\n            const Int ny(this->psf(0).shape()(1));\n\n            ASKAPLOG_INFO_STR(decbaselogger, \"Maximum of PSF(0) = \" << maxVal << \" at \" << maxPos);\n            ASKAPLOG_INFO_STR(decbaselogger, \"Minimum of PSF(0) = \" << minVal << \" at \" << minPos);\n\n            if ((maxPos(0) != nx / 2) || (maxPos(1) != ny / 2)) {\n                ASKAPTHROW(AskapError, \"Peak of PSF(0) is at \" << maxPos << \": not at centre pixel: [\" << nx / 2 << \",\" << ny / 2 << \"]\");\n            }\n\n            this->itsPeakPSFVal = maxVal;\n            this->itsPeakPSFPos = maxPos;\n\n            itsDS = boost::shared_ptr<DeconvolverState<T> >(new DeconvolverState<T>());\n            ASKAPASSERT(itsDS);\n            itsDC = boost::shared_ptr<DeconvolverControl<T> >(new DeconvolverControl<T>());\n            ASKAPASSERT(itsDC);\n            itsDM = boost::shared_ptr<DeconvolverMonitor<T> >(new DeconvolverMonitor<T>());\n            ASKAPASSERT(itsDM);\n\n            this->validateShapes();\n\n            auditAllMemory();\n\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::configure(const LOFAR::ParameterSet& parset)\n        {\n            this->itsDC->configure(parset);\n            this->itsDM->configure(parset);\n\n            // Get the beam information\n            const casa::Vector<float> beam = parset.getFloatVector(\"beam\");\n            ASKAPCHECK(beam.size() == 3, \"Need three elements for beam. You have \" << beam);\n            ASKAPLOG_INFO_STR(logger, \"Restore solver will convolve with the 2D gaussian: \" << beam(0) <<\n                              \" x \" << beam(1) << \" pixels at position angle \" << beam(2) << \" degrees\");\n            itsBMaj = beam(0);\n            itsBMin = beam(1);\n            itsBPa = beam(2);\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::setModel(const Array<T> model, const uInt term)\n        {\n            ASKAPCHECK(term < itsNumberTerms, \"Term \" << term << \" greater than allowed \" << itsNumberTerms);\n            this->itsModel(term) = model.nonDegenerate().copy();\n            this->validateShapes();\n        }\n\n        template<class T, class FT>\n        Array<T> & DeconvolverBase<T, FT>::model(const uInt term)\n        {\n            ASKAPCHECK(term < itsNumberTerms, \"Term \" << term << \" greater than allowed \" << itsNumberTerms);\n            return itsModel(term);\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::updateDirty(Array<T>& dirty, const uInt term)\n        {\n            ASKAPCHECK(term < itsNumberTerms, \"Term \" << term << \" greater than allowed \" << itsNumberTerms);\n            if (!dirty.shape().nonDegenerate().conform(this->dirty(term).shape())) {\n                throw(AskapError(\"Updated dirty image has different shape\"));\n            }\n            this->itsDirty(term) = dirty.nonDegenerate().copy();\n            this->validateShapes();\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::updateDirty(Vector<Array<T> >& dirtyVec)\n        {\n            if (dirtyVec.nelements() != this->itsDirty.nelements()) {\n                throw(AskapError(\"Updated dirty image has different shape\"));\n            }\n            this->itsDirty.resize(dirtyVec.nelements());\n            for (uInt term = 0; term < dirtyVec.nelements(); term++) {\n                if (!dirtyVec(term).nonDegenerate().shape().conform(this->itsDirty(term).nonDegenerate().shape())) {\n                    throw(AskapError(\"Updated dirty image has different shape from original\"));\n                }\n                this->itsDirty(term) = dirtyVec(term).nonDegenerate().copy();\n            }\n            this->validateShapes();\n        }\n\n        template<class T, class FT>\n        bool DeconvolverBase<T, FT>::deconvolve()\n        {\n            throw(AskapError(\"Called base class deconvolver\"));\n        }\n\n        template<class T, class FT>\n        Array<T> & DeconvolverBase<T, FT>::dirty(const uInt term)\n        {\n            ASKAPCHECK(term < itsNumberTerms, \"Term \" << term << \" greater than allowed \" << itsNumberTerms);\n            return itsDirty(term);\n        }\n\n        template<class T, class FT>\n        Array<T> & DeconvolverBase<T, FT>::psf(const uInt term)\n        {\n            ASKAPCHECK(term < itsNumberTerms, \"Term \" << term << \" greater than allowed \" << itsNumberTerms);\n            return itsPsf(term);\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::setWeight(Array<T> weight, const uInt term)\n        {\n            ASKAPCHECK(term < itsNumberTerms, \"Term \" << term << \" greater than allowed \" << itsNumberTerms);\n            this->itsWeight(term) = weight.nonDegenerate().copy();\n        }\n\n        template<class T, class FT>\n        Array<T> & DeconvolverBase<T, FT>::weight(const uInt term)\n        {\n            ASKAPCHECK(term < itsNumberTerms, \"Term \" << term << \" greater than allowed \" << itsNumberTerms);\n            return itsWeight(term);\n        }\n\n        template<class T, class FT>\n        boost::shared_ptr<DeconvolverControl<T> > DeconvolverBase<T, FT>::control() const\n        {\n            ASKAPASSERT(itsDC);\n            return itsDC;\n        }\n\n        template<class T, class FT>\n        bool DeconvolverBase<T, FT>::setControl(boost::shared_ptr<DeconvolverControl<T> > DC)\n        {\n            itsDC = DC;\n            ASKAPASSERT(itsDC);\n            return True;\n        }\n\n        template<class T, class FT>\n        boost::shared_ptr<DeconvolverMonitor<T> > DeconvolverBase<T, FT>::monitor() const\n        {\n            ASKAPASSERT(itsDM);\n            return itsDM;\n        }\n\n        template<class T, class FT>\n        bool DeconvolverBase<T, FT>::setMonitor(boost::shared_ptr<DeconvolverMonitor<T> > DM)\n        {\n            itsDM = DM;\n            ASKAPASSERT(itsDM);\n            return True;\n        }\n\n        template<class T, class FT>\n        boost::shared_ptr<DeconvolverState<T> > DeconvolverBase<T, FT>::state() const\n        {\n            ASKAPASSERT(itsDS);\n            return itsDS;\n        }\n\n        template<class T, class FT>\n        bool DeconvolverBase<T, FT>::setState(boost::shared_ptr<DeconvolverState<T> > DS)\n        {\n            itsDS = DS;\n            ASKAPASSERT(itsDS);\n            return True;\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::validateShapes()\n        {\n            casa::IPosition minPos;\n            casa::IPosition maxPos;\n            T minVal, maxVal;\n            casa::minMax(minVal, maxVal, minPos, maxPos, this->psf(0));\n            const Int nx(this->psf(0).shape()(0));\n            const Int ny(this->psf(0).shape()(1));\n            if ((maxPos(0) != nx / 2) || (maxPos(1) != ny / 2)) {\n                ASKAPTHROW(AskapError, \"Peak of PSF(0) is at \" << maxPos << \": not at centre pixel: [\" << nx / 2 << \",\" << ny / 2 << \"]\");\n            }\n\n            for (uInt term = 0; term < itsNumberTerms; term++) {\n                if (!(this->dirty(term).shape().size())) {\n                    ASKAPTHROW(AskapError, \"Dirty image has zero size\");\n                }\n                if (!(this->psf(term).shape().size())) {\n                    ASKAPTHROW(AskapError, \"PSF image has zero size\");\n                }\n                if (!(this->psf(term).shape()[0] == this->dirty().shape()[0]) || !(this->psf(term).shape()[1] == this->dirty().shape()[1])) {\n                    ASKAPTHROW(AskapError, \"PSF has different shape from dirty image\");\n                }\n\n                // The model and dirty image shapes only need to agree on the\n                // first two axes\n                if (!(this->model(term).shape().size())) {\n                    ASKAPTHROW(AskapError, \"Model has zero size\");\n                }\n                if (!(this->model(term).shape()[0] == this->dirty().shape()[0]) || !(this->model(term).shape()[1] == this->dirty().shape()[1])) {\n                    ASKAPTHROW(AskapError, \"Model has different shape from dirty image\");\n                }\n            }\n            if (!this->itsPeakPSFPos.size()) {\n                ASKAPTHROW(AskapError, \"Position of PSF peak not defined \" << this->itsPeakPSFPos);\n            }\n            if (this->itsPeakPSFVal == 0.0) {\n                ASKAPTHROW(AskapError, \"PSF peak is zero\");\n            }\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::initialise()\n        {\n            ASKAPLOG_INFO_STR(decbaselogger, \"Initialising weight images\");\n\n            // Always check shapes on initialise\n            this->validateShapes();\n\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::finalise()\n        {\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::updateResiduals(Vector<Array<T> >& model)\n        {\n            ASKAPCHECK(model.shape() == itsNumberTerms, \"Number of terms in model \" << model.shape()\n                           << \" not same as number of terms specified \"\n                           << itsNumberTerms);\n\n            for (uInt term = 0; term < itsNumberTerms; term++) {\n                Array<FT> xfr;\n                xfr.resize(psf(term).shape());\n                casa::setReal(xfr, psf(term));\n                scimath::fft2d(xfr, true);\n                Array<FT> work;\n                // Find residuals for current model model\n                work.resize(model(term).shape());\n                work.set(FT(0.0));\n                casa::setReal(work, model(term));\n                scimath::fft2d(work, true);\n                work = xfr * work;\n                scimath::fft2d(work, false);\n                this->dirty(term) = this->dirty(term) - real(work);\n            }\n        }\n\n        template<class T, class FT>\n        bool DeconvolverBase<T, FT>::restore(Vector<Array<T> >& restored)\n        {\n            return restore(restored, itsModel);\n        }\n\n        template<class T, class FT>\n        bool DeconvolverBase<T, FT>::restore(Vector<Array<T> >& restored, Vector<Array<T> >& model)\n        {\n            if (itsBMaj <= 0.0) {\n                ASKAPLOG_INFO_STR(decbaselogger, \"Beam not specified - no restoration\");\n                return false;\n            }\n\n            ASKAPCHECK(model.shape() == itsNumberTerms, \"Number of terms in model \" << model.shape()\n                           << \" not same as number of terms specified \"\n                           << itsNumberTerms);\n\n            ASKAPCHECK(restored.shape() == itsNumberTerms, \"Number of terms in restored image \" << restored.shape()\n                           << \" not same as number of terms specified \"\n                           << itsNumberTerms);\n\n            const int nx(model(0).shape()(0));\n            const int ny(model(0).shape()(1));\n            const IPosition centre(2, nx / 2, ny / 2);\n            Matrix<FT> gaussian(nx, ny);\n            gaussian.set(0.0);\n\n            const float scalex(sqrt(4.0*log(2.0)) / itsBMaj);\n            const float scaley(sqrt(4.0*log(2.0)) / itsBMin);\n            const float theta(itsBPa*C::pi / 180.0);\n            const float cs(cos(theta));\n            const float sn(sin(theta));\n            for (int y = 0; y < nx; y++) {\n                const float dy = (y - ny / 2) * scaley;\n                for (int x = 0; x < nx; x++) {\n                    const float dx = (x - nx / 2) * scalex;\n                    const float rsq = pow((dx * cs + dy * sn), 2) + pow((-dx * sn + dy * cs), 2);\n                    if (rsq < 20.0) {\n                        gaussian(x, y) = exp(-rsq);\n                    }\n                }\n            }\n            const float volume(sum(real(gaussian)));\n\n            scimath::fft2d(gaussian, true);\n\n            ASKAPLOG_INFO_STR(logger, \"Volume of PSF = \" << volume << \" pixels\");\n\n            for (uInt term = 0; term < itsNumberTerms; term++) {\n                Array<FT> vis(model(term).shape());\n                vis.set(FT(0.0));\n                casa::setReal(vis, model(term));\n                scimath::fft2d(vis, true);\n                vis = vis * gaussian;\n                scimath::fft2d(vis, false);\n                restored(term).resize(model(term).shape());\n                restored(term) = this->dirty(term) + real(vis);\n            }\n            return true;\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::updateResiduals(Array<T> & model)\n        {\n            Vector<Array<T> > modelVec(1);\n            modelVec(0) = model;\n            updateResiduals(modelVec);\n        }\n\n        template<class T, class FT>\n        uInt DeconvolverBase<T, FT>::auditMemory(Vector<casa::Array<T> >& vecArray)\n        {\n            uInt memory = 0;\n            for (uInt term = 0; term < vecArray.nelements(); term++) {\n                memory += sizeof(T) * vecArray(term).nelements();\n            }\n            return memory;\n        }\n\n        template<class T, class FT>\n        uInt DeconvolverBase<T, FT>::auditMemory(Vector<casa::Array<FT> >& vecArray)\n        {\n            uInt memory = 0;\n            for (uInt term = 0; term < vecArray.nelements(); term++) {\n                memory += sizeof(FT) * vecArray(term).nelements();\n            }\n            return memory;\n        }\n\n        template<class T, class FT>\n        void DeconvolverBase<T, FT>::auditAllMemory()\n        {\n            ASKAPLOG_DEBUG_STR(decbaselogger, \"Dirty images  \" << auditMemory(itsDirty));\n            ASKAPLOG_DEBUG_STR(decbaselogger, \"PSFs          \" << auditMemory(itsPsf));\n            ASKAPLOG_DEBUG_STR(decbaselogger, \"Models        \" << auditMemory(itsModel));\n            ASKAPLOG_DEBUG_STR(decbaselogger, \"Weight images \" << auditMemory(itsWeight));\n        }\n\n        template<class T, class FT>\n        IPosition DeconvolverBase<T, FT>::findSubPsfShape()\n        {\n            IPosition subPsfShape(2, this->model().shape()(0), this->model().shape()(1));\n            // Only use the specified psfWidth if it makes sense\n            // Also make sure it is even, otherwise the fft of the PSF is incorrect and the clean diverges\n            if (this->control()->psfWidth() > 1) {\n                uInt psfWidth = (this->control()->psfWidth()/2)*2;\n                if ((psfWidth < uInt(this->model().shape()(0))) && (psfWidth < uInt(this->model().shape()(1)))) {\n                    subPsfShape(0) = psfWidth;\n                    subPsfShape(1) = psfWidth;\n                }\n            }\n            return subPsfShape;\n        }\n    } // namespace synthesis\n\n} // namespace askap\n", "meta": {"hexsha": "bcbe809ab59b1709952f2b257426d647e42e8182", "size": 18718, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverBase.tcc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverBase.tcc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverBase.tcc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5729386892, "max_line_length": 145, "alphanum_fraction": 0.538465648, "num_tokens": 4649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237174, "lm_q2_score": 0.03021458422930661, "lm_q1q2_score": 0.007405141772628763}}
{"text": "/*\n  Copyright 2008 Intel Corporation\n\n  Use, modification and distribution are subject to the Boost Software License,\n  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n  http://www.boost.org/LICENSE_1_0.txt).\n*/\n\n#ifndef BOOST_POLYGON_ISOTROPY_HPP\n#define BOOST_POLYGON_ISOTROPY_HPP\n\n//external\n#include <cmath>\n#include <cstddef>\n#include <cstdlib>\n#include <vector>\n#include <deque>\n#include <map>\n#include <set>\n#include <list>\n//#include <iostream>\n#include <algorithm>\n#include <limits>\n#include <iterator>\n#include <string>\n\n#ifndef BOOST_POLYGON_NO_DEPS\n\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n#define BOOST_POLYGON_MSVC\n#endif\n#ifdef BOOST_INTEL\n#define BOOST_POLYGON_ICC\n#endif\n#ifdef BOOST_HAS_LONG_LONG\n#define BOOST_POLYGON_USE_LONG_LONG\ntypedef boost::long_long_type polygon_long_long_type;\ntypedef boost::ulong_long_type polygon_ulong_long_type;\n//typedef long long polygon_long_long_type;\n//typedef unsigned long long polygon_ulong_long_type;\n#endif\n#else\n\n#ifdef _WIN32\n#define BOOST_POLYGON_MSVC\n#endif\n#ifdef __ICC\n#define BOOST_POLYGON_ICC\n#endif\n#define BOOST_POLYGON_USE_LONG_LONG\ntypedef long long polygon_long_long_type;\ntypedef unsigned long long polygon_ulong_long_type;\n#endif\n\nnamespace boost { namespace polygon{\n\n  enum GEOMETRY_CONCEPT_ID {\n    COORDINATE_CONCEPT,\n    INTERVAL_CONCEPT,\n    POINT_CONCEPT,\n    POINT_3D_CONCEPT,\n    RECTANGLE_CONCEPT,\n    POLYGON_90_CONCEPT,\n    POLYGON_90_WITH_HOLES_CONCEPT,\n    POLYGON_45_CONCEPT,\n    POLYGON_45_WITH_HOLES_CONCEPT,\n    POLYGON_CONCEPT,\n    POLYGON_WITH_HOLES_CONCEPT,\n    POLYGON_90_SET_CONCEPT,\n    POLYGON_45_SET_CONCEPT,\n    POLYGON_SET_CONCEPT\n  };\n\n  struct undefined_concept {};\n\n  template <typename T>\n  struct geometry_concept { typedef undefined_concept type; };\n\n  template <typename GCT, typename T>\n  struct view_of {};\n\n  template <typename T1, typename T2>\n  view_of<T1, T2> view_as(const T2& obj) { return view_of<T1, T2>(obj); }\n\n  template <typename T, bool /*enable*/ = true>\n  struct coordinate_traits {};\n\n  //used to override long double with an infinite precision datatype\n  template <typename T>\n  struct high_precision_type {\n    typedef long double type;\n  };\n\n  template <typename T>\n  T convert_high_precision_type(const typename high_precision_type<T>::type& v) {\n    return T(v);\n  }\n\n  //used to override std::sort with an alternative (parallel) algorithm\n  template <typename iter_type>\n  void polygon_sort(iter_type _b_, iter_type _e_);\n\n  template <typename iter_type, typename pred_type>\n  void polygon_sort(iter_type _b_, iter_type _e_, const pred_type& _pred_);\n\n\n  template <>\n  struct coordinate_traits<int> {\n    typedef int coordinate_type;\n    typedef long double area_type;\n#ifdef BOOST_POLYGON_USE_LONG_LONG\n    typedef polygon_long_long_type manhattan_area_type;\n    typedef polygon_ulong_long_type unsigned_area_type;\n    typedef polygon_long_long_type coordinate_difference;\n#else\n    typedef long manhattan_area_type;\n    typedef unsigned long unsigned_area_type;\n    typedef long coordinate_difference;\n#endif\n    typedef long double coordinate_distance;\n  };\n\n  template<>\n  struct coordinate_traits<long, sizeof(long) == sizeof(int)> {\n    typedef coordinate_traits<int> cT_;\n    typedef cT_::coordinate_type coordinate_type;\n    typedef cT_::area_type area_type;\n    typedef cT_::manhattan_area_type manhattan_area_type;\n    typedef cT_::unsigned_area_type unsigned_area_type;\n    typedef cT_::coordinate_difference coordinate_difference;\n    typedef cT_::coordinate_distance coordinate_distance;\n  };\n\n#ifdef BOOST_POLYGON_USE_LONG_LONG\n  template <>\n  struct coordinate_traits<polygon_long_long_type> {\n    typedef polygon_long_long_type coordinate_type;\n    typedef long double area_type;\n    typedef polygon_long_long_type manhattan_area_type;\n    typedef polygon_ulong_long_type unsigned_area_type;\n    typedef polygon_long_long_type coordinate_difference;\n    typedef long double coordinate_distance;\n  };\n\n  template<>\n  struct coordinate_traits<long, sizeof(long) == sizeof(polygon_long_long_type)> {\n    typedef coordinate_traits<polygon_long_long_type> cT_;\n    typedef cT_::coordinate_type coordinate_type;\n    typedef cT_::area_type area_type;\n    typedef cT_::manhattan_area_type manhattan_area_type;\n    typedef cT_::unsigned_area_type unsigned_area_type;\n    typedef cT_::coordinate_difference coordinate_difference;\n    typedef cT_::coordinate_distance coordinate_distance;\n  };\n#endif\n\n  template <>\n  struct coordinate_traits<float> {\n    typedef float coordinate_type;\n    typedef float area_type;\n    typedef float manhattan_area_type;\n    typedef float unsigned_area_type;\n    typedef float coordinate_difference;\n    typedef float coordinate_distance;\n  };\n\n  template <>\n  struct coordinate_traits<double> {\n    typedef double coordinate_type;\n    typedef double area_type;\n    typedef double manhattan_area_type;\n    typedef double unsigned_area_type;\n    typedef double coordinate_difference;\n    typedef double coordinate_distance;\n  };\n\n  template <>\n  struct coordinate_traits<long double> {\n    typedef long double coordinate_type;\n    typedef long double area_type;\n    typedef long double manhattan_area_type;\n    typedef long double unsigned_area_type;\n    typedef long double coordinate_difference;\n    typedef long double coordinate_distance;\n  };\n\n  template <typename T>\n  struct scaling_policy {\n    template <typename T2>\n    static inline T round(T2 t2) {\n      return (T)std::floor(t2+0.5);\n    }\n\n    static inline T round(T t2) {\n      return t2;\n    }\n  };\n\n  struct coordinate_concept {};\n\n  template <>\n  struct geometry_concept<int> { typedef coordinate_concept type; };\n#ifdef BOOST_POLYGON_USE_LONG_LONG\n  template <>\n  struct geometry_concept<polygon_long_long_type> { typedef coordinate_concept type; };\n#endif\n  template <>\n  struct geometry_concept<float> { typedef coordinate_concept type; };\n  template <>\n  struct geometry_concept<double> { typedef coordinate_concept type; };\n  template <>\n  struct geometry_concept<long double> { typedef coordinate_concept type; };\n\n  struct gtl_no { static const bool value = false; };\n  struct gtl_yes { typedef gtl_yes type;\n    static const bool value = true; };\n\n  template <bool T, bool T2>\n  struct gtl_and_c { typedef gtl_no type; };\n  template <>\n  struct gtl_and_c<true, true> { typedef gtl_yes type; };\n\n  template <typename T, typename T2>\n  struct gtl_and : gtl_and_c<T::value, T2::value> {};\n  template <typename T, typename T2, typename T3>\n  struct gtl_and_3 { typedef typename gtl_and<\n                       T, typename gtl_and<T2, T3>::type>::type type; };\n\n  template <typename T, typename T2, typename T3, typename T4>\n  struct gtl_and_4 { typedef typename gtl_and_3<\n                       T, T2, typename gtl_and<T3, T4>::type>::type type; };\n  template <typename T, typename T2>\n  struct gtl_or { typedef gtl_yes type; };\n  template <typename T>\n  struct gtl_or<T, T> { typedef T type; };\n\n  template <typename T, typename T2, typename T3>\n  struct gtl_or_3 { typedef typename gtl_or<\n                      T, typename gtl_or<T2, T3>::type>::type type; };\n\n  template <typename T, typename T2, typename T3, typename T4>\n  struct gtl_or_4 { typedef typename gtl_or<\n                      T, typename gtl_or_3<T2, T3, T4>::type>::type type; };\n\n  template <typename T>\n  struct gtl_not { typedef gtl_no type; };\n  template <>\n  struct gtl_not<gtl_no> { typedef gtl_yes type; };\n\n  template <typename T>\n  struct gtl_if {\n#ifdef BOOST_POLYGON_MSVC\n    typedef gtl_no type;\n#endif\n  };\n  template <>\n  struct gtl_if<gtl_yes> { typedef gtl_yes type; };\n\n  template <typename T, typename T2>\n  struct gtl_same_type { typedef gtl_no type; };\n  template <typename T>\n  struct gtl_same_type<T, T> { typedef gtl_yes type; };\n  template <typename T, typename T2>\n  struct gtl_different_type { typedef typename gtl_not<typename gtl_same_type<T, T2>::type>::type type; };\n\n  struct manhattan_domain {};\n  struct forty_five_domain {};\n  struct general_domain {};\n\n  template <typename T>\n  struct geometry_domain { typedef general_domain type; };\n\n  template <typename domain_type, typename coordinate_type>\n  struct area_type_by_domain { typedef typename coordinate_traits<coordinate_type>::area_type type; };\n  template <typename coordinate_type>\n  struct area_type_by_domain<manhattan_domain, coordinate_type> {\n    typedef typename coordinate_traits<coordinate_type>::manhattan_area_type type; };\n\n  template<bool E, class R = void>\n  struct enable_if_ {\n      typedef R type;\n  };\n\n  template<class R>\n  struct enable_if_<false, R> { };\n\n  template<class E, class R = void>\n  struct enable_if\n      : enable_if_<E::value, R> { };\n\n  struct y_c_edist : gtl_yes {};\n\n  template <typename coordinate_type_1, typename coordinate_type_2>\n    typename enable_if<\n    typename gtl_and_3<y_c_edist, typename gtl_same_type<typename geometry_concept<coordinate_type_1>::type, coordinate_concept>::type,\n                       typename gtl_same_type<typename geometry_concept<coordinate_type_1>::type, coordinate_concept>::type>::type,\n    typename coordinate_traits<coordinate_type_1>::coordinate_difference>::type\n  euclidean_distance(const coordinate_type_1& lvalue, const coordinate_type_2& rvalue) {\n    typedef typename coordinate_traits<coordinate_type_1>::coordinate_difference Unit;\n    return (lvalue < rvalue) ? (Unit)rvalue - (Unit)lvalue : (Unit)lvalue - (Unit)rvalue;\n  }\n\n\n\n  // predicated_swap swaps a and b if pred is true\n\n  // predicated_swap is guarenteed to behave the same as\n  // if(pred){\n  //   T tmp = a;\n  //   a = b;\n  //   b = tmp;\n  // }\n  // but will not generate a branch instruction.\n  // predicated_swap always creates a temp copy of a, but does not\n  // create more than one temp copy of an input.\n  // predicated_swap can be used to optimize away branch instructions in C++\n  template <class T>\n  inline bool predicated_swap(const bool& pred,\n                              T& a,\n                              T& b) {\n    const T tmp = a;\n    const T* input[2] = {&b, &tmp};\n    a = *input[!pred];\n    b = *input[pred];\n    return pred;\n  }\n\n  enum direction_1d_enum { LOW = 0, HIGH = 1,\n                           LEFT = 0, RIGHT = 1,\n                           CLOCKWISE = 0, COUNTERCLOCKWISE = 1,\n                           REVERSE = 0, FORWARD = 1,\n                           NEGATIVE = 0, POSITIVE = 1 };\n  enum orientation_2d_enum { HORIZONTAL = 0, VERTICAL = 1 };\n  enum direction_2d_enum { WEST = 0, EAST = 1, SOUTH = 2, NORTH = 3 };\n  enum orientation_3d_enum { PROXIMAL = 2 };\n  enum direction_3d_enum { DOWN = 4, UP = 5 };\n  enum winding_direction {\n    clockwise_winding = 0,\n    counterclockwise_winding = 1,\n    unknown_winding = 2\n  };\n\n  class direction_2d;\n  class direction_3d;\n  class orientation_2d;\n\n  class direction_1d {\n  private:\n    unsigned int val_;\n    explicit direction_1d(int d);\n  public:\n    inline direction_1d() : val_(LOW) {}\n    inline direction_1d(const direction_1d& that) : val_(that.val_) {}\n    inline direction_1d(const direction_1d_enum val) : val_(val) {}\n    explicit inline direction_1d(const direction_2d& that);\n    explicit inline direction_1d(const direction_3d& that);\n    inline direction_1d& operator = (const direction_1d& d) {\n      val_ = d.val_; return * this; }\n    inline bool operator==(direction_1d d) const { return (val_ == d.val_); }\n    inline bool operator!=(direction_1d d) const { return !((*this) == d); }\n    inline unsigned int to_int(void) const { return val_; }\n    inline direction_1d& backward() { val_ ^= 1; return *this; }\n    inline int get_sign() const { return val_ * 2 - 1; }\n  };\n\n  class direction_2d;\n\n  class orientation_2d {\n  private:\n    unsigned int val_;\n    explicit inline orientation_2d(int o);\n  public:\n    inline orientation_2d() : val_(HORIZONTAL) {}\n    inline orientation_2d(const orientation_2d& ori) : val_(ori.val_) {}\n    inline orientation_2d(const orientation_2d_enum val) : val_(val) {}\n    explicit inline orientation_2d(const direction_2d& that);\n    inline orientation_2d& operator=(const orientation_2d& ori) {\n      val_ = ori.val_; return * this; }\n    inline bool operator==(orientation_2d that) const { return (val_ == that.val_); }\n    inline bool operator!=(orientation_2d that) const { return (val_ != that.val_); }\n    inline unsigned int to_int() const { return (val_); }\n    inline void turn_90() { val_ = val_^ 1; }\n    inline orientation_2d get_perpendicular() const {\n      orientation_2d retval = *this;\n      retval.turn_90();\n      return retval;\n    }\n    inline direction_2d get_direction(direction_1d dir) const;\n  };\n\n  class direction_2d {\n  private:\n    int val_;\n\n  public:\n\n    inline direction_2d() : val_(WEST) {}\n\n    inline direction_2d(const direction_2d& that) : val_(that.val_) {}\n\n    inline direction_2d(const direction_2d_enum val) : val_(val) {}\n\n    inline direction_2d& operator=(const direction_2d& d) {\n      val_ = d.val_;\n      return * this;\n    }\n\n    inline ~direction_2d() { }\n\n    inline bool operator==(direction_2d d) const { return (val_ == d.val_); }\n    inline bool operator!=(direction_2d d) const { return !((*this) == d); }\n    inline bool operator< (direction_2d d) const { return (val_ < d.val_); }\n    inline bool operator<=(direction_2d d) const { return (val_ <= d.val_); }\n    inline bool operator> (direction_2d d) const { return (val_ > d.val_); }\n    inline bool operator>=(direction_2d d) const { return (val_ >= d.val_); }\n\n    // Casting to int\n    inline unsigned int to_int(void) const { return val_; }\n\n    inline direction_2d backward() const {\n      // flip the LSB, toggles 0 - 1   and 2 - 3\n      return direction_2d(direction_2d_enum(val_ ^ 1));\n    }\n\n    // Returns a direction 90 degree left (LOW) or right(HIGH) to this one\n    inline direction_2d turn(direction_1d t) const {\n      return direction_2d(direction_2d_enum(val_ ^ 3 ^ (val_ >> 1) ^ t.to_int()));\n    }\n\n    // Returns a direction 90 degree left to this one\n    inline direction_2d left() const {return turn(HIGH);}\n\n    // Returns a direction 90 degree right to this one\n    inline direction_2d right() const {return turn(LOW);}\n\n    // N, E are positive, S, W are negative\n    inline bool is_positive() const {return (val_ & 1);}\n    inline bool is_negative() const {return !is_positive();}\n    inline int get_sign() const {return ((is_positive()) << 1) -1;}\n\n  };\n\n  direction_1d::direction_1d(const direction_2d& that) : val_(that.to_int() & 1) {}\n\n  orientation_2d::orientation_2d(const direction_2d& that) : val_(that.to_int() >> 1) {}\n\n  direction_2d orientation_2d::get_direction(direction_1d dir) const {\n    return direction_2d(direction_2d_enum((val_ << 1) + dir.to_int()));\n  }\n\n  class orientation_3d {\n  private:\n    unsigned int val_;\n    explicit inline orientation_3d(int o);\n  public:\n    inline orientation_3d() : val_((int)HORIZONTAL) {}\n    inline orientation_3d(const orientation_3d& ori) : val_(ori.val_) {}\n    inline orientation_3d(orientation_2d ori) : val_(ori.to_int()) {}\n    inline orientation_3d(const orientation_3d_enum val) : val_(val) {}\n    explicit inline orientation_3d(const direction_2d& that);\n    explicit inline orientation_3d(const direction_3d& that);\n    inline ~orientation_3d() {  }\n    inline orientation_3d& operator=(const orientation_3d& ori) {\n      val_ = ori.val_; return * this; }\n    inline bool operator==(orientation_3d that) const { return (val_ == that.val_); }\n    inline bool operator!=(orientation_3d that) const { return (val_ != that.val_); }\n    inline unsigned int to_int() const { return (val_); }\n    inline direction_3d get_direction(direction_1d dir) const;\n  };\n\n  class direction_3d {\n  private:\n    int val_;\n\n  public:\n\n    inline direction_3d() : val_(WEST) {}\n\n    inline direction_3d(direction_2d that) : val_(that.to_int()) {}\n    inline direction_3d(const direction_3d& that) : val_(that.val_) {}\n\n    inline direction_3d(const direction_2d_enum val) : val_(val) {}\n    inline direction_3d(const direction_3d_enum val) : val_(val) {}\n\n    inline direction_3d& operator=(direction_3d d) {\n      val_ = d.val_;\n      return * this;\n    }\n\n    inline ~direction_3d() { }\n\n    inline bool operator==(direction_3d d) const { return (val_ == d.val_); }\n    inline bool operator!=(direction_3d d) const { return !((*this) == d); }\n    inline bool operator< (direction_3d d) const { return (val_ < d.val_); }\n    inline bool operator<=(direction_3d d) const { return (val_ <= d.val_); }\n    inline bool operator> (direction_3d d) const { return (val_ > d.val_); }\n    inline bool operator>=(direction_3d d) const { return (val_ >= d.val_); }\n\n    // Casting to int\n    inline unsigned int to_int(void) const { return val_; }\n\n    inline direction_3d backward() const {\n      // flip the LSB, toggles 0 - 1   and 2 - 3 and 4 - 5\n      return direction_2d(direction_2d_enum(val_ ^ 1));\n    }\n\n    // N, E, U are positive, S, W, D are negative\n    inline bool is_positive() const {return (val_ & 1);}\n    inline bool is_negative() const {return !is_positive();}\n    inline int get_sign() const {return ((is_positive()) << 1) -1;}\n\n  };\n\n  direction_1d::direction_1d(const direction_3d& that) : val_(that.to_int() & 1) {}\n  orientation_3d::orientation_3d(const direction_3d& that) : val_(that.to_int() >> 1) {}\n  orientation_3d::orientation_3d(const direction_2d& that) : val_(that.to_int() >> 1) {}\n\n  direction_3d orientation_3d::get_direction(direction_1d dir) const {\n    return direction_3d(direction_3d_enum((val_ << 1) + dir.to_int()));\n  }\n\n}\n}\n#endif\n", "meta": {"hexsha": "615ae399dd8fa0264d45cdc6376779b1deb04d4f", "size": 17571, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/polygon/isotropy.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/polygon/isotropy.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/polygon/isotropy.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": 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.4049429658, "max_line_length": 135, "alphanum_fraction": 0.7046269421, "num_tokens": 4608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.018264274611223024, "lm_q1q2_score": 0.007370855840610158}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n#include \"NDDODipoleMomentCalculator.h\"\n#include \"NDDODipoleMatrixCalculator.h\"\n#include <Sparrow/Implementations/Nddo/Am1/AM1Method.h>\n#include <Sparrow/Implementations/Nddo/Mndo/MNDOMethod.h>\n#include <Sparrow/Implementations/Nddo/Pm6/PM6Method.h>\n#include <Sparrow/Implementations/Nddo/Utils/IntegralsEvaluationUtils/multipoleTypes.h>\n#include <Sparrow/Implementations/Nddo/Utils/NDDOInitializer.h>\n#include <Sparrow/Implementations/Nddo/Utils/ParameterUtils/PrincipalQuantumNumbers.h>\n#include <Utils/DataStructures/AtomsOrbitalsIndexes.h>\n#include <Utils/Geometry.h>\n#include <Eigen/Eigenvalues>\n\nnamespace Scine {\nnamespace Sparrow {\n\ntemplate<class NDDOMethod>\nNDDODipoleMomentCalculator<NDDOMethod>::~NDDODipoleMomentCalculator() = default;\n\ntemplate<class NDDOMethod>\nNDDODipoleMomentCalculator<NDDOMethod>::NDDODipoleMomentCalculator(NDDOMethod& method, DipoleMatrixCalculator& dipoleMatrixCalculator)\n  : method_(method), dipoleMatrixCalculator_(dipoleMatrixCalculator) {\n}\n\ntemplate<class NDDOMethod>\nstd::unique_ptr<NDDODipoleMomentCalculator<NDDOMethod>>\nNDDODipoleMomentCalculator<NDDOMethod>::create(NDDOMethod& method, DipoleMatrixCalculator& dipoleMatrixCalculator) {\n  NDDODipoleMomentCalculator<NDDOMethod> instance(method, dipoleMatrixCalculator);\n  return std::make_unique<NDDODipoleMomentCalculator<NDDOMethod>>(std::move(instance));\n}\n\ntemplate<class NDDOMethod>\nEigen::RowVector3d NDDODipoleMomentCalculator<NDDOMethod>::calculate() const {\n  auto atomicCharges = method_.getAtomicCharges();\n  auto coreCharges = method_.getInitializer().getCoreCharges();\n  auto densityMatrix = method_.getDensityMatrix().restrictedMatrix();\n  auto positions = method_.getPositions();\n\n  if (useNDDOApproximation_) {\n    auto elements = method_.getElementTypes();\n    std::vector<int> nrAOs(positions.rows());\n    std::vector<double> chargeSeparationSP(nrAOs.size());\n    std::vector<double> chargeSeparationPD(nrAOs.size());\n\n    for (int el = 0; el < nrAOs.size(); ++el) {\n      nrAOs[el] = method_.getAtomsOrbitalsIndexesHolder().getNOrbitals(el);\n      chargeSeparationSP[el] =\n          method_.getInitializer().getElementParameters().get(elements[el]).chargeSeparations().get(nddo::multipole::sp1);\n      chargeSeparationPD[el] =\n          method_.getInitializer().getElementParameters().get(elements[el]).chargeSeparations().get(nddo::multipole::pd1);\n    }\n    return calculateWithNDDOApproximation(std::move(atomicCharges), std::move(positions), std::move(densityMatrix),\n                                          std::move(elements), std::move(nrAOs), std::move(chargeSeparationSP),\n                                          std::move(chargeSeparationPD));\n  }\n  else {\n    auto overlapMatrix = method_.getOverlapMatrix();\n    Eigen::RowVector3d evaluationCoordinate = Utils::Position::Zero();\n    if (!dipoleMatrixCalculator_.isValid()) {\n      dipoleMatrixCalculator_.fillDipoleMatrix(evaluationCoordinate);\n    }\n    return calculateWithDipoleMatrix(std::move(coreCharges), std::move(positions), std::move(densityMatrix),\n                                     dipoleMatrixCalculator_.getAODipoleMatrix(), std::move(overlapMatrix),\n                                     std::move(evaluationCoordinate));\n  }\n}\n\ntemplate<class NDDOMethod>\nEigen::RowVector3d NDDODipoleMomentCalculator<NDDOMethod>::calculateWithNDDOApproximation(\n    std::vector<double> atomicCharges, Utils::PositionCollection positions, Eigen::MatrixXd densityMatrix,\n    Utils::ElementTypeCollection elements, std::vector<int> nrAOs, std::vector<double> chargeSeparationSP,\n    std::vector<double> chargeSeparationPD) const {\n  Eigen::MatrixX3d atomicDipoles(positions.rows(), 3);\n\n  Eigen::RowVector3d totalDipole = Utils::Dipole::Zero(3);\n\n  int currentdensityMatrixOrbital = 0;\n  // Put center of mass at the origin\n  auto centerOfMass = Utils::Geometry::getCenterOfMass(positions, Utils::Geometry::getMasses(elements));\n  positions.rowwise() -= centerOfMass;\n  for (unsigned atom = 0; atom < atomicDipoles.rows(); ++atom) {\n    // Mullikan charges dipole contribution\n    atomicDipoles.row(atom) = atomicCharges[atom] * positions.row(atom);\n\n    // SP hybridization\n    if (chargeSeparationSP[atom] != 0) {\n      const double HybrSP = 2.0 * chargeSeparationSP[atom];\n      for (int pOrbComponent = 0; pOrbComponent < 3; ++pOrbComponent) {\n        atomicDipoles.row(atom)(pOrbComponent) -=\n            HybrSP * densityMatrix(currentdensityMatrixOrbital, currentdensityMatrixOrbital + 1 + pOrbComponent);\n      }\n    }\n    // PD hybridization\n    //                                  0  1   2   3   4         5      6      7      8\n    // d orbitals are ordered this way: s, px, py, pz, d(x2-y2), d(xz), d(z2), d(yz), d(xy)\n    // where 0 corresponds to currentdensityMatrixOrbital\n    // See generalTypes.h for details.\n    if (chargeSeparationPD[atom] != 0) {\n      const double HybrPD = 2.0 * chargeSeparationPD[atom];\n      const double OneOverSqrt3 = 1.0 / std::sqrt(3);\n\n      const double DensMatComponentsX =\n          densityMatrix(currentdensityMatrixOrbital + 1, currentdensityMatrixOrbital + 4) -\n          densityMatrix(currentdensityMatrixOrbital + 1, currentdensityMatrixOrbital + 6) * OneOverSqrt3 +\n          densityMatrix(currentdensityMatrixOrbital + 2, currentdensityMatrixOrbital + 8) +\n          densityMatrix(currentdensityMatrixOrbital + 3, currentdensityMatrixOrbital + 5);\n\n      atomicDipoles.row(atom)(0) -= DensMatComponentsX * HybrPD;\n\n      const double DensMatComponentsY =\n          densityMatrix(currentdensityMatrixOrbital + 1, currentdensityMatrixOrbital + 8) -\n          densityMatrix(currentdensityMatrixOrbital + 2, currentdensityMatrixOrbital + 4) -\n          densityMatrix(currentdensityMatrixOrbital + 2, currentdensityMatrixOrbital + 6) * OneOverSqrt3 +\n          densityMatrix(currentdensityMatrixOrbital + 3, currentdensityMatrixOrbital + 7);\n\n      atomicDipoles.row(atom)(1) -= DensMatComponentsY * HybrPD;\n\n      const double DensMatComponentsZ =\n          densityMatrix(currentdensityMatrixOrbital + 1, currentdensityMatrixOrbital + 5) +\n          densityMatrix(currentdensityMatrixOrbital + 2, currentdensityMatrixOrbital + 7) +\n          densityMatrix(currentdensityMatrixOrbital + 3, currentdensityMatrixOrbital + 6) * 2.0 * OneOverSqrt3;\n\n      atomicDipoles.row(atom)(2) -= DensMatComponentsZ * HybrPD;\n    }\n\n    currentdensityMatrixOrbital += nrAOs[atom];\n  }\n\n  totalDipole += atomicDipoles.colwise().sum();\n  return totalDipole;\n}\n\ntemplate<class NDDOMethod>\nvoid NDDODipoleMomentCalculator<NDDOMethod>::useNDDOApproximation(bool useNDDOApprox) {\n  useNDDOApproximation_ = useNDDOApprox;\n}\n\ntemplate<class NDDOMethod>\nEigen::RowVector3d NDDODipoleMomentCalculator<NDDOMethod>::calculateWithDipoleMatrix(\n    std::vector<double> coreCharges, Utils::PositionCollection positions, Eigen::MatrixXd densityMatrix,\n    Utils::DipoleMatrix dipoleMatrix, Eigen::MatrixXd overlapMatrix, Eigen::RowVector3d dipoleEvaluationCoordinate) const {\n  auto const nAtoms = coreCharges.size();\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(overlapMatrix);\n  Eigen::MatrixXd sqrtS = es.operatorInverseSqrt();\n  Eigen::MatrixXd nonOrthogonalDensityMatrix =\n      sqrtS.selfadjointView<Eigen::Upper>() * densityMatrix * sqrtS.selfadjointView<Eigen::Upper>();\n  Eigen::RowVector3d dipole;\n  dipole.setZero();\n\n  positions.rowwise() -= dipoleEvaluationCoordinate;\n\n  const auto atomicOrbitalsNumber = dipoleMatrix.x().get<Utils::derivOrder::zero>().cols();\n  // Classical Core charge component\n  for (int atom = 0; atom < nAtoms; ++atom) {\n    dipole += coreCharges[atom] * positions.row(atom);\n  }\n\n  // electronic component (diagonal)\n  for (int AO = 0; AO < atomicOrbitalsNumber; ++AO) {\n    dipole.x() -= nonOrthogonalDensityMatrix(AO, AO) * dipoleMatrix.x().get<Utils::derivOrder::zero>()(AO, AO);\n    dipole.y() -= nonOrthogonalDensityMatrix(AO, AO) * dipoleMatrix.y().get<Utils::derivOrder::zero>()(AO, AO);\n    dipole.z() -= nonOrthogonalDensityMatrix(AO, AO) * dipoleMatrix.z().get<Utils::derivOrder::zero>()(AO, AO);\n  }\n  // electronic component(off-diagonal)\n  for (int nu = 0; nu < atomicOrbitalsNumber; ++nu) {\n    for (int mu = nu + 1; mu < atomicOrbitalsNumber; ++mu) {\n      dipole.x() -= 2 * nonOrthogonalDensityMatrix(nu, mu) * dipoleMatrix.x().get<Utils::derivOrder::zero>()(nu, mu);\n      dipole.y() -= 2 * nonOrthogonalDensityMatrix(nu, mu) * dipoleMatrix.y().get<Utils::derivOrder::zero>()(nu, mu);\n      dipole.z() -= 2 * nonOrthogonalDensityMatrix(nu, mu) * dipoleMatrix.z().get<Utils::derivOrder::zero>()(nu, mu);\n    }\n  }\n  return dipole;\n}\n\ntemplate class NDDODipoleMomentCalculator<nddo::PM6Method>;\ntemplate class NDDODipoleMomentCalculator<nddo::AM1Method>;\ntemplate class NDDODipoleMomentCalculator<nddo::MNDOMethod>;\n} // namespace Sparrow\n} // namespace Scine\n", "meta": {"hexsha": "5bf6fb72da9afef26fe108578c257bcf5f242258", "size": 9041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Sparrow/Sparrow/Implementations/Nddo/Utils/DipoleUtils/NDDODipoleMomentCalculator.cpp", "max_stars_repo_name": "DockBio/sparrow", "max_stars_repo_head_hexsha": "f82cf86584e9edfc6f2c78af4896dc6f2ee8a455", "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/Sparrow/Sparrow/Implementations/Nddo/Utils/DipoleUtils/NDDODipoleMomentCalculator.cpp", "max_issues_repo_name": "DockBio/sparrow", "max_issues_repo_head_hexsha": "f82cf86584e9edfc6f2c78af4896dc6f2ee8a455", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Sparrow/Sparrow/Implementations/Nddo/Utils/DipoleUtils/NDDODipoleMomentCalculator.cpp", "max_forks_repo_name": "DockBio/sparrow", "max_forks_repo_head_hexsha": "f82cf86584e9edfc6f2c78af4896dc6f2ee8a455", "max_forks_repo_licenses": ["BSD-3-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.8702702703, "max_line_length": 134, "alphanum_fraction": 0.7246985953, "num_tokens": 2486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.017442481097044375, "lm_q1q2_score": 0.007369529106160116}}
{"text": "#include \"decon.h\"\n#include \"defines.h\"\n#include \"utils.h\"\n#include \"reader.h\"\n#include \"resampler.h\"\n#include \"math_local.h\"\n#include \"writer.h\"\n#include <algorithm>\n#include <boost/program_options.hpp>\n\nnamespace po = boost::program_options;\n\nint main(int argc, char** argv) {\n  // parameters\n  float xy_res = UNSET_FLOAT;\n  float kernel_zstep = UNSET_FLOAT;\n  float img_zstep = UNSET_FLOAT;\n  float subtract_constant = UNSET_FLOAT;\n  unsigned int iterations = UNSET_UNSIGNED_INT;\n  unsigned int bit_depth = UNSET_UNSIGNED_INT;\n  bool overwrite = UNSET_BOOL;\n  bool verbose = UNSET_BOOL;\n\n  // declare the supported options\n  po::options_description visible_opts(\"usage: decon [options] path\\n\\nAllowed options\");\n  visible_opts.add_options()\n      (\"help,h\", \"display this help message\")\n      (\"kernel,k\", po::value<std::string>()->required(),\"kernel file path\")\n      (\"iterations,n\", po::value<unsigned int>(&iterations)->required(),\"deconvolution iterations\")\n      (\"xy-rez,x\", po::value<float>(&xy_res)->default_value(0.104f), \"x/y resolution (um/px)\")\n      (\"kernel-spacing,p\", po::value<float>(&kernel_zstep)->default_value(1.0f),\"z-step size of kernel\")\n      (\"image-spacing,q\", po::value<float>(&img_zstep)->default_value(1.0f),\"z-step size of input image\")\n      (\"subtract-constant,s\", po::value<float>(&subtract_constant)->default_value(0.0f),\"constant intensity value to subtract from input image\")\n      (\"output,o\", po::value<std::string>()->required(),\"output file path\")\n      (\"bit-depth,b\", po::value<unsigned int>(&bit_depth)->default_value(16),\"bit depth (8, 16, or 32) of output image\")\n      (\"overwrite,w\", po::value<bool>(&overwrite)->default_value(false)->implicit_value(true)->zero_tokens(), \"overwrite output if it exists\")\n      (\"verbose,v\", po::value<bool>(&verbose)->default_value(false)->implicit_value(true)->zero_tokens(), \"display progress and debug information\")\n      (\"version\", \"display the version number\")\n  ;\n\n  po::options_description hidden_opts;\n  hidden_opts.add_options()\n    (\"input\", po::value<std::string>()->required(), \"input file path\")\n  ;\n\n  po::positional_options_description positional_opts; \n  positional_opts.add(\"input\", 1);\n\n  po::options_description all_opts;\n  all_opts.add(visible_opts).add(hidden_opts);\n\n  // parse options\n  po::variables_map varsmap;\n  try {\n    po::store(po::command_line_parser(argc, argv).options(all_opts).positional(positional_opts).run(), varsmap);\n\n    // print help message\n    if (varsmap.count(\"help\") || (argc == 1)) {\n      std::cerr << \"decon: deconvolves an image with a PSF or PSF parameters\\n\";\n      std::cerr << visible_opts << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    // print version number\n    if (varsmap.count(\"version\")) {\n      std::cerr << DECON_VERSION << std::endl;\n      return EXIT_FAILURE;\n    }\n    \n    // check options\n    po::notify(varsmap);\n\n  } catch (po::error& e) {\n    std::cerr << \"decon: \" << e.what() << \"\\n\\n\";\n    std::cerr << visible_opts << std::endl;\n    return EXIT_FAILURE;\n  } catch (...) {\n    std::cerr << \"decon: unknown error during command line parsing\\n\\n\";\n    std::cerr << visible_opts << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // check files\n  const char* in_path = varsmap[\"input\"].as<std::string>().c_str();\n  if (!IsFile(in_path)) {\n    std::cerr << \"decon: input path is not a file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  const char* kernel_path = varsmap[\"kernel\"].as<std::string>().c_str();\n  if (!IsFile(kernel_path)) {\n    std::cerr << \"decon: kernel path is not a file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  const char* out_path = varsmap[\"output\"].as<std::string>().c_str();\n  if (IsFile(out_path)) {\n    if (!overwrite) {\n      std::cerr << \"decon: output path already exists\" << std::endl;\n      return EXIT_FAILURE;\n    } else if (verbose) {\n        std::cout << \"overwriting: \" << out_path << std::endl;\n    }\n  }\n\n  // check bit depth\n  unsigned int bits[] = {8, 16, 32};\n  unsigned int* p = std::find(std::begin(bits), std::end(bits), bit_depth);\n  if (p == std::end(bits)) {\n    std::cerr << \"decon: bit depth must be 8, 16, or 32\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // print parameters\n  if (verbose) {\n    std::cout << \"\\nInput Parameters\\n\";\n    std::cout << \"Iterations = \" << iterations << \"\\n\";\n    std::cout << \"Input Path = \" << in_path << \"\\n\";\n    std::cout << \"Kernel Path = \" << kernel_path << \"\\n\";\n    std::cout << \"Output Path = \" << out_path << \"\\n\";\n    std::cout << \"Overwrite = \" << overwrite << \"\\n\";\n    std::cout << \"Bit Depth = \" << bit_depth << std::endl;\n  }\n\n  // read data\n  kImageType::Pointer img = ReadImageFile<kImageType>(in_path);\n  kImageType::Pointer kernel = ReadImageFile<kImageType>(kernel_path);\n\n  // set spacing\n  kImageType::SpacingType img_spacing;\n\n  img_spacing[0] = xy_res;\n  img_spacing[1] = xy_res;\n  img_spacing[2] = img_zstep;\n  img->SetSpacing(img_spacing);\n\n  kImageType::SpacingType kernel_spacing;\n\n  kernel_spacing[0] = xy_res;\n  kernel_spacing[1] = xy_res;\n  kernel_spacing[2] = kernel_zstep;\n  kernel->SetSpacing(kernel_spacing);\n\n  // resample kernel\n  if (img_zstep != kernel_zstep)\n  {\n    kernel = Resampler(kernel, img_spacing, verbose);\n  }\n\n  // subtract constant\n  if (subtract_constant != 0.0)\n  {\n    img = SubtractConstantClamped(img, (kPixelType) subtract_constant/std::numeric_limits<unsigned short>::max()); // TODO: scale subtraction by input type\n\n  }\n\n  // decon\n  kImageType::Pointer decon_img = RichardsonLucy(img, kernel, iterations, verbose);\n\n  // write file\n  if (bit_depth == 8) {\n    using PixelTypeOut = unsigned char;\n    using ImageTypeOut = itk::Image<PixelTypeOut, kDimensions>;\n    WriteImageFile<kImageType,ImageTypeOut>(decon_img, out_path);\n  } else if (bit_depth == 16) {\n    using PixelTypeOut = unsigned short;\n    using ImageTypeOut = itk::Image<PixelTypeOut, kDimensions>;\n    WriteImageFile<kImageType,ImageTypeOut>(decon_img, out_path);\n  } else if (bit_depth == 32) {\n    using PixelTypeOut = float;\n    using ImageTypeOut = itk::Image<PixelTypeOut, kDimensions>;\n    WriteImageFile<kImageType,ImageTypeOut>(decon_img, out_path);\n  } else {\n    std::cerr << \"decon: unknown bit depth\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  return EXIT_SUCCESS;\n}", "meta": {"hexsha": "aa7d4aae0dcd3a8a2714e841ce6a61f751ae6a7f", "size": 6257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/c/decon/decon.cpp", "max_stars_repo_name": "JaneliaSciComp/LLSM", "max_stars_repo_head_hexsha": "d0f5fba1fd0bfe116876e99046c6e3a7b235be5f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-27T22:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-14T07:09:18.000Z", "max_issues_repo_path": "src/c/decon/decon.cpp", "max_issues_repo_name": "JaneliaSciComp/LLSM", "max_issues_repo_head_hexsha": "d0f5fba1fd0bfe116876e99046c6e3a7b235be5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T15:31:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T17:46:37.000Z", "max_forks_repo_path": "src/c/decon/decon.cpp", "max_forks_repo_name": "JaneliaSciComp/LLSM", "max_forks_repo_head_hexsha": "d0f5fba1fd0bfe116876e99046c6e3a7b235be5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-04T13:37:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T13:37:21.000Z", "avg_line_length": 35.3502824859, "max_line_length": 155, "alphanum_fraction": 0.661179479, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.021615332762647654, "lm_q1q2_score": 0.0073076495379413185}}
{"text": "/*\n    Copyright (c) 2011-2014 University of Zurich\n    \n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n    \n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n    \n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n*/\n\n#ifndef PLLL_INCLUDE_GUARD__ENUMIMPL_PARALLELSERIAL_ENUM_CPP\n#define PLLL_INCLUDE_GUARD__ENUMIMPL_PARALLELSERIAL_ENUM_CPP\n\n#include <boost/thread.hpp>\n\nnamespace plll\n{\n    template<class RealTypeContext, class IntTypeContext, class JobManager>\n    /*\n      The JobManager class must have a method\n          void addJob(unsigned dim,\n                      const linalg::math_rowvector<typename IntTypeContext::Integer> & x_end,\n                      const typename RealTypeContext::Real & ell,\n                      const typename RealTypeContext::Real & bound,\n                      bool iszero);\n    */\n    class JobData;\n    \n    template<class RealTypeContext, class IntTypeContext, class JobManager>\n    class ThreadData\n    // Stores per thread data, like certain arrays\n    {\n        friend class JobData<RealTypeContext, IntTypeContext, JobManager>;\n        \n    private:\n        Lattice<RealTypeContext, IntTypeContext> * d_lattice;\n        JobManager & d_jm;\n        Updater<RealTypeContext, IntTypeContext> & d_update;\n        unsigned d_begin;\n        unsigned d_end;\n        unsigned d_dim;\n        \n        volatile bool d_need_to_setup;\n        volatile unsigned d_need_to_setup_begin;\n        volatile unsigned d_need_to_setup_end;\n        volatile Lattice<RealTypeContext, IntTypeContext> * d_need_to_setup_lattice;\n        \n        linalg::math_rowvector<typename IntTypeContext::Integer> d_result;\n        linalg::math_rowvector<typename IntTypeContext::Integer> d_x;\n        linalg::math_rowvector<typename RealTypeContext::Real> d_x_real;\n        linalg::base_rowvector<long> d_delta;\n        linalg::base_rowvector<int> d_delta2;\n        linalg::math_rowvector<int> d_r; /* Used for improvement sketched in Appendix B of Gama,\n        Nguyen, Regev: \"Lattice Enumeration Using Extreme Pruning\", EUROCRYPT 2010. Stores\n        information on how much of the cache in d_sigma can be used. */\n        linalg::math_matrix<typename RealTypeContext::Real> d_sigma; /* used for improvement\n        sketched in Appendix B of Gama, Nguyen, Regev: \"Lattice Enumeration Using Extreme Pruning\",\n        EUROCRYPT 2010. The i-th row caches intermediate values used during the computation of\n        d_c[i]. */\n        linalg::math_rowvector<typename RealTypeContext::Real> d_c;\n        linalg::math_rowvector<typename RealTypeContext::Real> d_ell;\n        linalg::math_rowvector<typename RealTypeContext::Real> d_bounds; /* For pruning. This is\n        updated by JobData, not by ThreadData, and any relation to d_bound is managed by JobData. */\n        std::vector<bool> d_iszero;\n        \n        std::list<JobData<RealTypeContext, IntTypeContext, JobManager> > d_job_list;\n        \n        boost::mutex d_bound_update_mutex;\n        volatile bool d_bound_updated;\n        typename RealTypeContext::Real d_bound;\n        \n        volatile bool d_split;\n        volatile bool d_stop;\n        \n    public:\n        ThreadData(JobManager & jm, Updater<RealTypeContext, IntTypeContext> & update)\n            : d_lattice(NULL), d_jm(jm), d_update(update), d_begin(0), d_end(0), d_dim(0),\n              d_need_to_setup(false), d_need_to_setup_begin(0), d_need_to_setup_end(0),\n              d_need_to_setup_lattice(NULL), d_bound_updated(false), d_split(false),\n              d_stop(false)\n        {\n        }\n        \n        void setup(Lattice<RealTypeContext, IntTypeContext> & lattice, unsigned begin, unsigned end)\n        // Called at beginning of specific enumerate\n        {\n            d_need_to_setup = false;\n            d_lattice = &lattice;\n            d_begin = begin;\n            d_end = end;\n            d_dim = d_end - d_begin + 1;\n            // The updater functions rely on the size of d_result and d_x, hence always resize them!\n            d_result.resize(d_dim);\n            d_x.resize(d_dim);\n            // Only resize the others when necessary\n            if (d_x_real.size() < d_dim)\n            {\n                d_x_real.resize(d_dim, linalg::Initialize(lattice.rc()));\n                d_delta.resize(d_dim);\n                d_delta2.resize(d_dim);\n                d_r.resize(d_dim + 1);\n                d_sigma.resize(d_dim, d_dim, linalg::Initialize(lattice.rc()));\n                d_c.resize(d_dim, linalg::Initialize(lattice.rc()));\n                d_ell.resize(d_dim + 1, linalg::Initialize(lattice.rc()));\n                d_bounds.resize(d_dim, linalg::Initialize(lattice.rc()));\n                d_iszero.resize(d_dim + 1);\n            }\n            for (unsigned i = 0; i < d_dim; ++i)\n            {\n                setZero(d_x_real[i]);\n                setZero(d_c[i]);\n                setZero(d_ell[i]);\n                setZero(d_bounds[i]);\n//            for (unsigned j = 0; j < d_dim; ++j)\n//                setZero(d_sigma(i, j));\n            }\n            setZero(d_ell[d_dim]);\n            d_bound_updated = false;\n            setZero(d_bound);\n            d_split = false;\n            d_stop = false;\n            updateContext();\n        }\n        \n        void updateContext()\n        {\n            RealTypeContext & rc = d_lattice->rc();\n            for (unsigned i = 0; i < d_sigma.rows(); ++i)\n                for (unsigned j = 0; j < d_sigma.cols(); ++j)\n                    d_sigma(i, j).setContext(rc);\n            for (unsigned i = 0; i < d_x_real.size(); ++i)\n                d_x_real[i].setContext(rc);\n            for (unsigned i = 0; i < d_c.size(); ++i)\n                d_c[i].setContext(rc);\n            for (unsigned i = 0; i < d_ell.size(); ++i)\n                d_ell[i].setContext(rc);\n            for (unsigned i = 0; i < d_bounds.size(); ++i)\n                d_bounds[i].setContext(rc);\n            d_bound.setContext(rc);\n        }\n        \n        inline void flagToSetup(Lattice<RealTypeContext, IntTypeContext> & lattice, unsigned begin, unsigned end)\n        {\n            d_need_to_setup_lattice = &lattice;\n            d_need_to_setup_begin = begin;\n            d_need_to_setup_end = end;\n            d_need_to_setup = true;\n        }\n        \n        inline void doSetup()\n        {\n            if (d_need_to_setup)\n            {\n                setup((Lattice<RealTypeContext, IntTypeContext>&)*d_need_to_setup_lattice, d_need_to_setup_begin, d_need_to_setup_end);\n                d_need_to_setup = false;\n            }\n        }\n        \n        inline void setUpdatedBound(const typename RealTypeContext::Real & bound)\n        {\n            boost::lock_guard<boost::mutex> guard(d_bound_update_mutex);\n            d_bound_updated = true;\n            d_bound = bound;\n        }\n        \n        inline bool hasUpdatedBound() const\n        {\n            return d_bound_updated;\n        }\n        \n        inline bool updateBound(typename RealTypeContext::Real & bound)\n        {\n            bool updated = false;\n            if (d_bound_updated)\n            {\n                boost::lock_guard<boost::mutex> guard(d_bound_update_mutex);\n                if (d_bound_updated)\n                {\n                    d_bound_updated = false;\n                    bound = d_bound;\n                    updated = true;\n                }\n            }\n            return updated;\n        }\n        \n        inline void flagToStop()\n        {\n            d_stop = true;\n        }\n        \n        inline bool shouldIStop()\n        {\n            return d_stop;\n        }\n        \n        inline void flagToSplit()\n        {\n            d_split = true;\n        }\n        \n        inline bool shouldISplit()\n        {\n            if (d_split)\n            {\n                d_split = false;\n                return true;\n            }\n            else\n                return false;\n        }\n    };\n    \n    template<class RealTypeContext, class IntTypeContext, class JobManager>\n    class JobData\n    // The job itself. Contains info on job parameters, local parameters while running, as well as contains result\n    {\n    private:\n        linalg::math_rowvector<typename IntTypeContext::Integer> d_x_end; // td.d_dim - d_x_end.size() is the dimension which is\n        // still to be enumerated\n        typename RealTypeContext::Real d_ell;\n        bool d_iszero;\n        \n    public:\n        linalg::math_rowvector<typename IntTypeContext::Integer> d_result; // is zero vector (of no length) until a solution was found\n        typename RealTypeContext::Real d_bound;\n        \n    private:\n        void propagate_new_bound(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td)\n        {\n            td.d_jm.d_pruninghelper.computeBounds(td.d_bounds, td.d_dim, d_bound);\n        }\n        \n        inline void run_init(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td, unsigned realdim, unsigned enumbegin, unsigned enumdim)\n        {\n            // Fill in x, delta, delta2, ell\n            for (unsigned i = 0; i < d_x_end.size(); ++i)\n            {\n                td.d_x[enumdim + i] = d_x_end[i];\n                arithmetic::convert(td.d_x_real[enumdim + i], d_x_end[i], td.d_lattice->rc());\n            }\n            td.d_ell[enumdim] = d_ell;\n            td.d_iszero[enumdim] = d_iszero;\n            \n            // Prepare enumeration\n            for (unsigned i = 0; i < enumdim; ++i)\n            {\n                td.d_r[i] = realdim - 1;\n                setZero(td.d_sigma(i, realdim - 1));\n            }\n            typename RealTypeContext::Real tmp(td.d_lattice->rc());\n            \n            for (unsigned j = td.d_r[enumdim - 1]; j >= enumdim; --j) // this is the summation order considered in Pujol-Stehle\n            {\n                tmp = td.d_x_real[j] * td.d_lattice->getCoeff(enumbegin + j, enumbegin + enumdim - 1);\n                td.d_sigma(enumdim - 1, j - 1) = td.d_sigma(enumdim - 1, j) + tmp;\n            }\n            td.d_c[enumdim - 1] = -td.d_sigma(enumdim - 1, enumdim - 1);\n            bool ru;\n            arithmetic::convert_round(td.d_x[enumdim - 1], td.d_c[enumdim - 1], ru, td.d_lattice->ic());\n            arithmetic::convert(td.d_x_real[enumdim - 1], td.d_x[enumdim - 1], td.d_lattice->rc());\n            td.d_iszero[enumdim - 1] = td.d_iszero[enumdim] && isZero(td.d_x[enumdim - 1]);\n            td.d_delta[enumdim - 1] = 0;\n            td.d_delta2[enumdim - 1] = ru ? 1 : -1;\n            propagate_new_bound(td);\n        }\n        \n        class CallUpdater\n        {\n        public:\n            inline bool operator() (ThreadData<RealTypeContext, IntTypeContext, JobManager> & td, JobData & jd,\n                                    unsigned realdim, unsigned enumbegin, unsigned enumdim, unsigned stage, bool & noSolutionYet,\n                                    typename RealTypeContext::Real & tmp) const\n            {\n                if (td.d_update(*td.d_lattice, td.d_begin, td.d_end, jd.d_result, jd.d_bound, td.d_x, td.d_ell[0], noSolutionYet))\n                    jd.propagate_new_bound(td);\n                return true;\n            }\n        };\n        \n        class CallUpdaterNotify\n        {\n        private:\n            mutable bool d_was_updated;\n            \n        public:\n            inline CallUpdaterNotify()\n                : d_was_updated(false)\n            {\n            }\n            \n            inline bool wasUpdated() const\n            {\n                return d_was_updated;\n            }\n            \n            inline bool operator() (ThreadData<RealTypeContext, IntTypeContext, JobManager> & td, JobData & jd,\n                                    unsigned realdim, unsigned enumbegin, unsigned enumdim, unsigned stage, bool & noSolutionYet,\n                                    typename RealTypeContext::Real & tmp) const\n            {\n                if (td.d_update(*td.d_lattice, td.d_begin, td.d_end, jd.d_result, jd.d_bound, td.d_x, td.d_ell[0], noSolutionYet))\n                {\n                    jd.propagate_new_bound(td);\n                    d_was_updated = true;\n                }\n                return true;\n            }\n        };\n        \n        class CallRefiner\n        {\n        public:\n            inline bool operator() (ThreadData<RealTypeContext, IntTypeContext, JobManager> & td, JobData & jd,\n                                    unsigned realdim, unsigned enumbegin, unsigned enumdim, unsigned stage, bool & noSolutionYet,\n                                    typename RealTypeContext::Real & tmp) const\n            {\n                td.d_jm.addJob(realdim, td.d_x, td.d_ell[0], jd.d_bound, td.d_iszero[0]);\n                // update bound (improves pruning)\n                if (td.d_jm.isBoundUpdated())\n                {\n                    jd.d_bound = td.d_jm.getUpdatedBound();\n                    jd.propagate_new_bound(td);\n                }\n                return true;\n            }\n        };\n        \n        class CallRunner;\n        friend class CallRunner;\n        \n        class CallRunner\n        {\n        private:\n            static void enqueue(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td, JobData & jd,\n                                unsigned realdim, unsigned enumbegin, unsigned enumdim, unsigned stage,\n                                typename RealTypeContext::Real & tmp)\n            {\n                while (true)\n                {\n                    tmp = td.d_x_real[stage] - td.d_c[stage];\n                    square(td.d_ell[stage], tmp);\n                    td.d_ell[stage] *= td.d_lattice->getNormSq(enumbegin + stage);\n                    td.d_ell[stage] += td.d_ell[stage + 1];\n                    if (td.d_ell[stage] <= td.d_bounds[stage])\n                        td.d_job_list.push_back(JobData(td.d_dim - stage, td.d_x, td.d_ell[stage], jd.d_bound, td.d_iszero[stage], stage));\n                    else\n                    {\n                        if (++stage >= enumdim)\n                            break;\n                    }\n                    // Modify d_x[stage]\n                    if (td.d_iszero[stage + 1])\n                    {\n                        ++td.d_x[stage];\n                    }\n                    else\n                    {\n                        td.d_delta2[stage] = -td.d_delta2[stage];\n                        td.d_delta[stage] = -td.d_delta[stage] + td.d_delta2[stage];\n                        td.d_x[stage] += arithmetic::convert(td.d_delta[stage], td.d_lattice->ic());\n                    }\n                    arithmetic::convert(td.d_x_real[stage], td.d_x[stage], td.d_lattice->rc());\n                    td.d_iszero[stage] = false;\n                }\n                \n                td.d_jm.addJobs(td.d_job_list.begin(), td.d_job_list.end());\n                td.d_job_list.clear();\n            }\n            \n        public:\n            inline bool operator() (ThreadData<RealTypeContext, IntTypeContext, JobManager> & td, JobData & jd,\n                                    unsigned realdim, unsigned enumbegin, unsigned enumdim, unsigned stage, bool & noSolutionYet,\n                                    typename RealTypeContext::Real & tmp) const\n            {\n                if (td.shouldIStop())\n                    return false;\n                if (td.shouldISplit())\n                {\n                    enqueue(td, jd, realdim, enumbegin, enumdim, stage, tmp);\n                    return false;\n                }\n                if (td.updateBound(jd.d_bound)) // update bound\n                    jd.propagate_new_bound(td);\n                jd.go_stage_down<false>(td, realdim, enumbegin, enumdim, stage - 1, 0, tmp);\n                CallUpdaterNotify caller;\n                jd.do_the_run<true, true>(td, realdim, enumbegin, stage, stage - 1, noSolutionYet, caller, 0);\n                if (caller.wasUpdated())\n                {\n                    // Inform other threads about update\n                    td.d_jm.tryToUpdateBound(jd.d_result, jd.d_bound);\n                }\n                return true;\n            }\n        };\n        \n        template<bool avoid_bottom>\n        static inline void go_stage_down(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td,\n                                  unsigned realdim, unsigned enumbegin, unsigned enumdim, unsigned stage, unsigned zerostage,\n                                  typename RealTypeContext::Real & tmp)\n        {\n            if (stage > 0)\n            {\n                if (td.d_r[stage - 1] < td.d_r[stage])\n                    td.d_r[stage - 1] = td.d_r[stage];\n            }\n            for (unsigned j = td.d_r[stage]; j > stage; --j) // this is the summation order considered in Pujol-Stehle\n            {\n                tmp = td.d_x_real[j] * td.d_lattice->getCoeff(enumbegin + j, enumbegin + stage);\n                td.d_sigma(stage, j - 1) = td.d_sigma(stage, j) + tmp;\n            }\n            td.d_c[stage] = -td.d_sigma(stage, stage);\n            bool ru;\n            arithmetic::convert_round(td.d_x[stage], td.d_c[stage], ru, td.d_lattice->ic());\n            td.d_iszero[stage] = td.d_iszero[stage + 1] && isZero(td.d_x[stage]);\n            if (avoid_bottom && (stage == zerostage) && td.d_iszero[stage])\n                // fuck it. this should _not_ be zero! (in case avoidbottom is set!)\n                ++td.d_x[stage];\n            arithmetic::convert(td.d_x_real[stage], td.d_x[stage], td.d_lattice->rc());\n            td.d_delta[stage] = 0;\n            td.d_delta2[stage] = ru ? 1 : -1;\n        }\n        \n        template<bool avoid_bottom, bool inc_stage_after_call, class Caller>\n        inline bool do_the_run(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td,\n                               unsigned realdim, unsigned enumbegin, unsigned enumdim, unsigned stage,\n                               bool & noSolutionYet, const Caller & caller, unsigned zerostage = 0)\n        {\n            typename RealTypeContext::Real tmp(td.d_lattice->rc());\n            \n            while (true)\n            {\n                tmp = td.d_x_real[stage] - td.d_c[stage];\n                square(td.d_ell[stage], tmp);\n                td.d_ell[stage] *= td.d_lattice->getNormSq(enumbegin + stage);\n                td.d_ell[stage] += td.d_ell[stage + 1];\n                if (td.d_ell[stage] <= td.d_bounds[stage])\n                {\n                    if (stage == zerostage)\n                    {\n                        if (!caller(td, *this, realdim, enumbegin, enumdim, stage, noSolutionYet, tmp))\n                            return false;\n                        if (inc_stage_after_call)\n                        {\n                            if (++stage >= enumdim)\n                                break;\n                            // Update r for the lower stage\n                            td.d_r[stage - 1] = stage;\n                        }\n                    }\n                    else\n                    {\n                        --stage;\n                        go_stage_down<avoid_bottom>(td, realdim, enumbegin, enumdim, stage, zerostage, tmp);\n                        continue;\n                    }\n                }\n                else\n                {\n                    if (++stage >= enumdim)\n                        break;\n                    // Update r for the lower stage\n                    td.d_r[stage - 1] = stage;\n                }\n                // Modify d_x[stage]\n                if (td.d_iszero[stage + 1])\n                {\n                    ++td.d_x[stage];\n                }\n                else\n                {\n                    td.d_delta2[stage] = -td.d_delta2[stage];\n                    td.d_delta[stage] = -td.d_delta[stage] + td.d_delta2[stage];\n                    td.d_x[stage] += arithmetic::convert(td.d_delta[stage], td.d_lattice->ic());\n                }\n                arithmetic::convert(td.d_x_real[stage], td.d_x[stage], td.d_lattice->rc());\n                td.d_iszero[stage] = false;\n            }\n            return true;\n        }\n        \n        bool d_done;\n        \n    public:\n        JobData(unsigned dim, const linalg::math_rowvector<typename IntTypeContext::Integer> & x_end,\n                const typename RealTypeContext::Real & ell,\n                const typename RealTypeContext::Real & bound,\n                bool iszero, unsigned ofs = 0)\n            : d_x_end(dim), d_ell(ell), d_iszero(iszero), d_bound(bound), d_done(false)\n        {\n            for (unsigned i = 0; i < dim; ++i)\n                d_x_end[i] = x_end[ofs + i];\n        }\n        \n        void markDone()\n        {\n            d_done = true;\n        }\n        \n        bool isDone() const\n        {\n            return d_done;\n        }\n        \n        const typename RealTypeContext::Real & ell() const\n        {\n            return d_ell;\n        }\n        \n        unsigned dimension() const\n        {\n            return d_x_end.size();\n        }\n        \n        bool update(typename RealTypeContext::Real & bound)\n        // Returns false if job is superfluous\n        {\n            d_bound = bound;\n            return d_ell <= d_bound;\n        }\n        \n        unsigned leftoverDims(const ThreadData<RealTypeContext, IntTypeContext, JobManager> & td) const\n        {\n            return td.d_dim - d_x_end.size();\n        }\n        \n        void print()\n        {\n            for (unsigned i = 0; i < d_x_end.size(); ++i)\n                std::cout << \" \" << d_x_end[i];\n            std::cout << \" -- \" << d_ell << \" -- \" << d_bound << \" -- \" << (d_iszero ? \"true\" : \"false\") << \"\\n\";\n        }\n        \n        void run(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td)\n        {\n            // Prepare enumeration\n            td.doSetup();\n            unsigned enumdim = td.d_dim - d_x_end.size(); // td.d_enumdim;\n            bool noSolutionYet = true;\n            run_init(td, td.d_dim, td.d_begin, enumdim);\n            // Do enumeration\n            CallUpdater caller;\n            do_the_run<true, true>(td, td.d_dim, td.d_begin, enumdim, enumdim - 1, noSolutionYet, caller, 0);\n        }\n        \n        void run2(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td)\n        {\n            enum { THRESHOLD = 40 };\n            \n            // Prepare enumeration\n            td.doSetup();\n            unsigned enumdim = td.d_dim - d_x_end.size(); // td.d_enumdim;\n            bool noSolutionYet = true;\n            run_init(td, td.d_dim, td.d_begin, enumdim);\n            if (enumdim > THRESHOLD)\n            {\n                // Do enumeration in two (main) stages\n                CallRunner caller;\n                do_the_run<false, false>(td, td.d_dim, td.d_begin, enumdim, enumdim - 1, noSolutionYet, caller, THRESHOLD);\n            }\n            else\n            {\n                // Do enumeration\n                CallUpdater caller;\n                do_the_run<true, true>(td, td.d_dim, td.d_begin, enumdim, enumdim - 1, noSolutionYet, caller, 0);\n            }\n        }\n        \n        void refine(ThreadData<RealTypeContext, IntTypeContext, JobManager> & td, unsigned dim)\n        // Computes the next dim dimensions. We must have dim < leftoverDims(td).\n        {\n            // Prepare refinement\n            td.doSetup();\n            assert(dim < leftoverDims(td));\n            unsigned realdim = dim + d_x_end.size();\n            bool noSolutionYet; // not needed\n            unsigned enumbegin = td.d_begin + td.d_dim - realdim;\n            run_init(td, realdim, enumbegin, dim);\n            \n            // Do refinement\n            CallRefiner caller;\n            do_the_run<false, false>(td, realdim, enumbegin, dim, dim - 1, noSolutionYet, caller, 0);\n        }\n    };\n}\n\n#endif\n", "meta": {"hexsha": "8d67592f954364819773c25f8ab7ef1660c0910a", "size": 24607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plll/src/lattices/enumimpl-parallelserial-enum.cpp", "max_stars_repo_name": "KudrinMatvey/myfplll", "max_stars_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plll/src/lattices/enumimpl-parallelserial-enum.cpp", "max_issues_repo_name": "KudrinMatvey/myfplll", "max_issues_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plll/src/lattices/enumimpl-parallelserial-enum.cpp", "max_forks_repo_name": "KudrinMatvey/myfplll", "max_forks_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0801335559, "max_line_length": 146, "alphanum_fraction": 0.5207461292, "num_tokens": 5554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.017712302138592775, "lm_q1q2_score": 0.007281719928299663}}
{"text": "#include <fstream>\n#include <cmath>\n#include <iostream>\n#include <sstream>\n#include <cstdlib>\n#include <vector>\n#include <string.h>\n#include <netcdfcpp.h>\n#include <gsl/gsl_cdf.h>\n#include <boost/random.hpp>\n#include <boost/math/distributions/inverse_gaussian.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/program_options.hpp>\n#include <WilcoxonTest.h>\nnamespace po = boost::program_options;\nusing namespace std;\n\nconst string help = \"help\";\nconst string dataFileName = \"dataFile\";\nconst string configFileName = \"configFile\";\n\nint dataYsize;\nint dataXsize;\n\nvoid commandConfigMessage()\n{\n        cout << \"Alternatively, instead of config file, you can write configuration arguments directly to the command line, \";\n        cout << \"overwriting some or all the arguments. \" << endl;\n        cout << \"Note! testIndexes and ontrolIndexes must be a Comma separated integer list _WITHOUT_ spaces!\" << endl << endl;\n        cout << \"Example: WilcoxonTest --\" << dataFileName << \" data.nc \";\n        cout << \"--DataName data \" << \"--xDimension  n \" << \" --yDimension m \";\n        cout << \"--testIndexes  0,2,4,6 \" << \" --controlIndexes 1,3,5,7\" << endl<< endl;\n        cout << \"Note that if both Command line config parameters and Config file is given, then the command line parameters will be used\" << endl<< endl;\n}\n\nbool validateCommandLine(po::variables_map * vm, po::options_description * commandArgs)\n{\n    if(!vm->count(dataFileName)){\n        cout << \"Invalid parameters.\" << endl;\n        cout << *commandArgs << endl;\n        cout << \"Example: WilcoxonTest --\" << dataFileName << \" data.nc --\" << configFileName << \" conf.cfg\" << endl<< endl;\n\n        commandConfigMessage();\n        return false;\n    }\n    return true;\n}\n\nbool validateConfiguration(po::variables_map * vm, po::options_description * configuration)\n{\n    if(!vm->count(\"DataName\") || !vm->count(\"xDimension\") || !vm->count(\"yDimension\")\n            || !vm->count(\"testIndexes\") || !vm->count(\"controlIndexes\")){\n\n        cout << \"Configuration file has missing options\" << endl;\n        cout << *configuration << endl;\n        cout << \"Example: conf.cfg:\" << endl;\n        cout << \"DataName = data\" << endl;\n        cout << \"xDimension = n\" << endl;\n        cout << \"yDimension = m\" << endl;\n        cout << \"testIndexes = 0, 2, 4, 6\" << endl;\n        cout << \"controlIndexes = 1, 3, 5, 7\" << endl<< endl;\n\n        commandConfigMessage();\n        return false;\n    }\n    return true;\n}\n\nfloat * readNetCdfFile(string fileName, string dataName, string xDimension, string yDimension)\n{\n    NcFile file(fileName.c_str(), NcFile::ReadOnly);\n    if (!file.is_valid())\n    {\n        cout << \"Couldn't open file!\\n\";\n        throw;\n    }\n\n    NcVar *experimentData = file.get_var(dataName.c_str());\n\n    dataYsize = file.get_dim(yDimension.c_str())->size();\n    dataXsize = file.get_dim(xDimension.c_str())->size();\n\n    float * data = new float[dataYsize * dataXsize];;\n\n\n    experimentData->get(&data[0], dataYsize, dataXsize);\n    return data;\n}\n\n//TODO optimize this thing\nvoid writeResultsFile(string dataFileName, string yDimension, vector<double> * pValues)\n{\n    NcFile file(dataFileName.c_str(), NcFile::ReadOnly);\n    NcVar *geneNames = file.get_var(\"gene\");\n    int dataYsize = file.get_dim(yDimension.c_str())->size();\n\n    FILE * pFile;\n    pFile = fopen (\"results.txt\",\"w\");\n\n    cout << \"Writing results to file..\" << endl;\n\n    int percentage = dataYsize / 10;\n    int percentageCount = 10;\n    for(int i = 0; i < dataYsize; i++){\n        char * c = geneNames->as_string(i*28);\n        std::string str;\n        if(pValues->at(i) > 0.05){\n            std::ostringstream strs;\n            strs << pValues->at(i);\n            str = strs.str();\n        }else{\n            str = \"NA\";\n        }\n        fprintf (pFile, \"%-20s-%20s\", c, str.c_str());\n        fprintf (pFile, \"\\n\");\n        if(i == percentage)\n        {\n            cout <<  percentageCount << \"% complete\" << endl;\n            percentageCount += 10;\n            percentage += dataYsize / 10;\n        }\n        delete c;\n    }\n    fclose(pFile);\n}\n\nint main(int argc, char* argv[])\n{\n    po::options_description commandArgs(\"Command line arguments\");\n    commandArgs.add_options()\n        (help.c_str(), \"produce help message\")\n        (dataFileName.c_str(), po::value< string > (), \"A NetCDF file containing the data that tests will be run on\")\n        (configFileName.c_str(), po::value< string > (), \"A configuration INI file containing all the specified options under 'Configuration'\")\n    ;\n\n    po::options_description config(\"Configuration\");\n    config.add_options()\n        (\"DataName\", po::value<string>(), \"Name of the data variable in NetCDF file - string\")\n        (\"xDimension\", po::value<string>(), \"Name of the Y dimension of the data matrix - string\")\n        (\"yDimension\", po::value<string>(), \"Name of the X dimension of the data matrix - string\")\n        (\"testIndexes\", po::value<string>(), \"Test group column indexes - comma separated int array\")\n        (\"controlIndexes\", po::value<string>(), \"Control group column indexes - comma separated int array\")\n        ;\n    commandArgs.add(config);\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, commandArgs), vm);\n    po::notify(vm);\n\n    if (!vm[help].empty()) {\n        cout << commandArgs << endl;\n        cout << config << endl;\n        return 1;\n    }\n    else if (validateCommandLine(&vm, &commandArgs)) {\n\n        //This doesnt overwrite command line parameters\n        if(vm.count(configFileName)){\n            std::ifstream file;\n            file.open(vm[configFileName].as<string>().c_str());\n            if (!file.is_open())\n            {\n                cerr << \"Config file does not exist! \" << endl;\n                throw;\n            }\n\n            po::store(po::parse_config_file(file, config), vm);\n            po::notify(vm);\n        }\n\n        if(validateConfiguration(&vm, &config)){\n            string dataFileName = vm.at(\"dataFile\").as<string>();\n            string testIndexes = vm.at(\"testIndexes\").as<string>();\n            string controlIndexes = vm.at(\"controlIndexes\").as<string>();\n            string dataName = vm.at(\"DataName\").as<string>();\n            string xDimension = vm.at(\"xDimension\").as<string>();\n            string yDimension = vm.at(\"yDimension\").as<string>();\n            float * data = readNetCdfFile(dataFileName, dataName, xDimension, yDimension);\n            WilcoxonTest wilx(data, dataXsize, dataYsize, testIndexes, controlIndexes);\n            vector<double> * pValues = wilx.test();\n            writeResultsFile(dataFileName, yDimension, pValues);\n        }\n    }\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "65e32eeedb2cd5e0679a78bd032c4852506c6598", "size": 6705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TerminalWilcoxonTest/src/WilcoxonTestLoader.cpp", "max_stars_repo_name": "stenver/wilcoxon-test", "max_stars_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-04-05T09:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T14:35:01.000Z", "max_issues_repo_path": "TerminalWilcoxonTest/src/WilcoxonTestLoader.cpp", "max_issues_repo_name": "stenver/wilcoxon-test", "max_issues_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TerminalWilcoxonTest/src/WilcoxonTestLoader.cpp", "max_forks_repo_name": "stenver/wilcoxon-test", "max_forks_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-01T07:57:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T09:45:52.000Z", "avg_line_length": 36.0483870968, "max_line_length": 154, "alphanum_fraction": 0.608650261, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233684437737093, "lm_q2_score": 0.01854656661422524, "lm_q1q2_score": 0.007276501419459832}}
{"text": "// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye\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 ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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// Copyright (c) 2011-2013, Paul Furgale and others.\n// All rights reserved.\n//\n// Unlike otherwise stated in source files, the code in this repository is\n// published under the Revised BSD (New BSD) license.\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 <organization> 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 <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#pragma once\n\n#include <vector>\n#include <Eigen/Core>\n#include <ze/common/types.hpp>\n#include <ze/common/matrix.hpp>\n\nnamespace ze {\n// imported from Schweizer-Messer Kinematics. Not intended to be used outside\n// of the spline package.\nnamespace sm {\n\ninline Matrix4 boxPlus(const Vector6 & dt)\n{\n  Matrix4 Bp;\n  Bp <<   0.0,  -dt[5],   dt[4],  -dt[0],\n          dt[5],     0.0,  -dt[3],  -dt[1],\n         -dt[4],   dt[3],     0.0,  -dt[2],\n          0.0,     0.0,     0.0,     0.0;\n  return Bp;\n}\n\ninline Matrix46 boxMinus(const Vector4 & p)\n{\n  Matrix46 Bm;\n  Bm <<    p[3],     0.0,     0.0,     0.0,     -p[2],     p[1],\n           0.0,    p[3],     0.0,    p[2],       0.0,    -p[0],\n           0.0,     0.0,    p[3],   -p[1],      p[0],      0.0,\n           0.0,     0.0,     0.0,     0.0,       0.0,      0.0;\n  return Bm;\n}\n\ninline Matrix6 boxTimes(Matrix4 const & T_ba)\n{\n  Matrix6 Tbp = Matrix6::Zero();\n\n  Tbp.topLeftCorner<3, 3>() = T_ba.topLeftCorner<3, 3>();\n  Tbp.bottomRightCorner<3, 3>() = T_ba.topLeftCorner<3, 3>();\n  Tbp.topRightCorner<3, 3>() = -skewSymmetric(T_ba(0, 3), T_ba(1, 3), T_ba(2, 3))\n                               * T_ba.topLeftCorner<3, 3>();\n\n  return Tbp;\n}\n\n} // namespace kinematics\n} // namespace ze\n", "meta": {"hexsha": "cacd94a2d65af269664ee54040f8cd5ac2267787", "size": 4598, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ze_splines/include/ze/splines/operators.hpp", "max_stars_repo_name": "rockenbf/ze_oss", "max_stars_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-09-27T07:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T20:44:28.000Z", "max_issues_repo_path": "ze_splines/include/ze/splines/operators.hpp", "max_issues_repo_name": "rockenbf/ze_oss", "max_issues_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-18T15:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-21T03:10:06.000Z", "max_forks_repo_path": "ze_splines/include/ze/splines/operators.hpp", "max_forks_repo_name": "rockenbf/ze_oss", "max_forks_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-11-05T07:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T02:26:08.000Z", "avg_line_length": 45.98, "max_line_length": 86, "alphanum_fraction": 0.689430187, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.021287351638224167, "lm_q1q2_score": 0.007271386493643273}}
{"text": "/**\n *\n *\n *                               Heu-MCHC\n *\n * A fast and accurate heuristic algorithm for the haplotype inference\n * problem on pedigree data with recombinations and mutations\n *\n * Copyright (C) 2009,2010,2011  Yuri PIROLA\n *\n * Distributed under the terms of the GNU General Public License (GPL)\n *\n *\n * This file is part of Heu-MCHC.\n *\n * Heu-MCHC 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 * Heu-MCHC 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 Heu-MCHC.  If not, see <http://www.gnu.org/licenses/>.\n *\n **/\n#include <string>\n#include <iostream>\n#include <fstream>\n\n#include <map>\n\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/graphviz.hpp>\n\n#include <cstdio>\n\n#include \"locus-graph.hpp\"\n#include \"irregular_mat.hpp\"\n#include \"belief-propagation.hpp\"\n#include \"util.h\"\n#include \"log.h\"\n#include <m4ri/m4ri.h>\n\nusing namespace boost;\nusing namespace ped;\n\n#define MZD_INIT( r, c ) mzd_init( r<32?32:r, c<32?32:c )\n\ntemplate <typename T>\nclass TLN_t {\npublic:\n  TLN_t<T>* const pred;\n  T data;\n  TLN_t(TLN_t<T>* const _pred, T _data)\n\t\t:pred(_pred), data(_data) {}\n\n};\n\ntypedef TLN_t<ped::h_variable_t> tln_h_t;\ntypedef TLN_t<ped::e_variable_t> tln_e_t;\n\n\nstatic bool\nis_indiv_homoz_at_locus(const pindiv i, const int l) {\n  return i!=NULL && i->g[l]!=GEN2;\n}\n\nclass ped_lg_label_writer {\nprivate:\n  LocusGraph& g;\n  int l;\npublic:\n  ped_lg_label_writer(LocusGraph& _lg, int _l)\n\t\t:g(_lg), l(_l)\n  {}\n\n  void operator()(std::ostream& out, const LG_Vertex& v) {\n\t out << \"[label=\\\"I\" << g[v].individ->id <<\n\t\t\"^\"<< l <<\" (ls=\" << ped::locus_abbrv_status_names[g[v].ls] << \", p~=\" << g[v].ptilde <<\")\\\"]\";\n  }\n\n  void operator()(std::ostream& out, const LG_Edge& e) {\n\t out << \"[label=\\\"d=\" << g[e].d << \"\\\"]\";\n  }\n};\n\nclass general_locus_graph_visitor: public boost::default_dfs_visitor {\nprivate:\n  LocusGraph& lg;\n\npublic:\n  general_locus_graph_visitor(LocusGraph& _lg)\n\t\t:lg(_lg)\n  {}\n\n  void initialize_vertex(LG_Vertex v, const LocusGraph& g) {\n\t lg[v].pred_vertex= v;\n  }\n\n  void tree_edge(LG_Edge e, const LocusGraph& g) {\n\t DEBUG(\"Edge \" ST_FMT \"-\" ST_FMT \" is in the spanning forest.\",\n\t\t\t source(e, lg), target(e, lg));\n\t lg[e].in_spanning_forest= true;\n\t lg[target(e, lg)].pred_vertex= source(e, lg);\n\t lg[target(e, lg)].pred_edge= e;\n  }\n};\n\n\nstatic LocusGraph *\nbuild_locus_graph_from_pedigree(pgenped gp,\n\t\t\t\t\t\t\t\t\t\t  const unsigned int l) {\n  my_assert(gp!=NULL);\n  assert_ulim(l, gp->n_loci);\n  DEBUG(\"Building locus graph of locus %d\", l);\n\n  LocusGraph * plg= new LocusGraph(gp->n_indiv, l);\n  LocusGraph& lg= *plg;\n\n  int index= 0;\n  BGL_FORALL_VERTICES(v, lg, LocusGraph) {\n\t pindiv i= gp->individuals[index];\n\t ++index;\n\t lg[v].individ= i;\n\t lg[v].ptilde= -1;\n\t lg[v].ls= ped::LS_UNDETERMINED;\n// Set the status of the locus\n\t if (is_indiv_homoz_at_locus(i, l)) {\n\t\tlg[v].ls= ped::LS_IMMUTABLE;\n\t\tlg[v].ptilde= i->g[l];\n\t } else {\n// Individual heterozygous\n\t\tif (is_indiv_homoz_at_locus(i->f, l)) {\n// Father homozygous\n\t\t  if (is_indiv_homoz_at_locus(i->m, l)) {\n// Both parents homozygous\n\t\t\t if (i->f->g[l]==i->m->g[l]) {\n// Same homozygousity -> Ambiguous\n\t\t\t\tlg[v].ls= ped::LS_PRED_AMBIGUOUS;\n\t\t\t\tlg[v].ptilde= i->f->g[l];\n\t\t\t } else {\n// Different homozygousity -> Doubly predetermined\n\t\t\t\tlg[v].ls= ped::LS_PRED_DOUBLE;\n\t\t\t\tlg[v].ptilde= i->f->g[l];\n\t\t\t }\n\t\t  } else {\n// Only father homozygous\n\t\t\t lg[v].ls= ped::LS_PRED_SINGLE_FATHER;\n\t\t\t lg[v].ptilde= i->f->g[l];\n\t\t  }\n\t\t} else if (is_indiv_homoz_at_locus(i->m, l)) {\n// Only mother homozygous\n\t\t  lg[v].ls= ped::LS_PRED_SINGLE_MOTHER;\n\t\t  lg[v].ptilde= (i->m->g[l]+1)%2;\n\t\t}\n\t }\n\n\t my_assert(lg[v].ptilde!=-1 || lg[v].ls==ped::LS_UNDETERMINED);\n\n  }\n\n  index= 0;\n  BGL_FORALL_VERTICES(v, lg, LocusGraph) {\n\t pindiv i= gp->individuals[index];\n\t if (i->f!=NULL && i->f->g[l]==GEN2) {\n\t\tDEBUG(\"Adding edge %d %d\", i->id, i->fi);\n\t\tLocusGraph::edge_descriptor ed= add_edge(i->id, i->fi, lg).first;\n\t\tlg[ed].d= 0;\n\t }\n\t if (i->m!=NULL && i->m->g[l]==GEN2) {\n\t\tDEBUG(\"Adding edge %d %d\", i->id, i->mi);\n\t\tLocusGraph::edge_descriptor ed= add_edge(i->id, i->mi, lg).first;\n\t\tlg[ed].d= (gp->individuals[index]->g[l]==GEN2)?1:0;\n\t }\n\t ++index;\n  }\n  general_locus_graph_visitor vis(lg);\n  depth_first_search(lg, visitor(vis));\n\n\n#ifdef LOG_GRAPHS\n  write_graphviz(std::cout, lg,\n\t\t\t\t\t  ped_lg_label_writer(lg, l),\n\t\t\t\t\t  ped_lg_label_writer(lg, l));\n#endif\n\n  return plg;\n}\n\nstatic LocusGraph**\nbuild_all_locus_graphs_from_pedigree(pgenped gp) {\n  my_assert(gp!=NULL);\n  LocusGraph** lgs= NPALLOC(LocusGraph*, gp->n_loci);\n\n  for(unsigned int i= 0; i<gp->n_loci; ++i) {\n\t lgs[i]= build_locus_graph_from_pedigree(gp, i);\n  }\n\n  return lgs;\n}\n\nstatic LocusGraph*\nbuild_general_locus_graph_from_pedigree(pgenped gp) {\n// Build a general locus graph (w/o checking homozygousity)\n  my_assert(gp!=NULL);\n  DEBUG(\"Building general locus graph\");\n  LocusGraph* const plg= new LocusGraph(gp->n_indiv, -1);\n  LocusGraph& lg= *plg;\n  int index= 0;\n  BGL_FORALL_VERTICES(v, lg, LocusGraph) {\n\t pindiv i= gp->individuals[index];\n\t ++index;\n\t lg[v].individ= i;\n  }\n\n  index= 0;\n  BGL_FORALL_VERTICES(v, lg, LocusGraph) {\n\t pindiv i= gp->individuals[index];\n\t if (i->f!=NULL) {\n\t\tLocusGraph::edge_descriptor ed= add_edge(i->id, i->fi, lg).first;\n\t }\n\t if (i->m!=NULL) {\n\t\tLocusGraph::edge_descriptor ed= add_edge(i->id, i->mi, lg).first;\n\t }\n\t ++index;\n  }\n\n  general_locus_graph_visitor vis(lg);\n  depth_first_search(lg, visitor(vis));\n\n#ifdef LOG_GRAPHS\n  write_graphviz(std::cout, lg,\n\t\t\t\t\t  ped_lg_label_writer(lg, -1),\n\t\t\t\t\t  ped_lg_label_writer(lg, -1));\n#endif\n\n  return plg;\n}\n\nstatic ped::e_variable_t\nget_m_variable_from_edge(const LocusGraph& lg,\n\t\t\t\t\t\t\t\t const int u,\n\t\t\t\t\t\t\t\t const int v,\n\t\t\t\t\t\t\t\t const int l) {\n// Determino chi e' il genitore\n  bool u_child_of_v= (lg[u].individ->fi==v) ||\n\t (lg[u].individ->mi==v);\n\n  my_assert(u_child_of_v || (lg[v].individ->fi==u) ||\n\t\t\t\t(lg[v].individ->mi==u));\n\n  if (u_child_of_v)\n\t return ped::e_variable_t(ped::e_variable_t::MUT,\n\t\t\t\t\t\t\t\t\t  u, l, lg[u].individ->fi==v?0:1);\n  else\n\t return ped::e_variable_t(ped::e_variable_t::MUT,\n\t\t\t\t\t\t\t\t\t  v, l, lg[v].individ->fi==u?0:1);\n}\n\nstatic ped::h_variable_t\nget_h_variable_from_edge(const LocusGraph& lg,\n\t\t\t\t\t\t\t\t const int u,\n\t\t\t\t\t\t\t\t const int v,\n\t\t\t\t\t\t\t\t const int l) {\n// Determino chi e' il genitore\n  bool u_child_of_v= (lg[u].individ->fi==v) ||\n\t (lg[u].individ->mi==v);\n\n  my_assert(u_child_of_v || (lg[v].individ->fi==u) ||\n\t\t\t\t(lg[v].individ->mi==u));\n\n  if (u_child_of_v)\n\t return ped::h_variable_t(u, lg[u].individ->fi==v?0:1);\n  else\n\t return ped::h_variable_t(v, lg[v].individ->fi==u?0:1);\n}\n\nstatic void\nget_rec_variables_from_edge_to_tln(const LocusGraph& lg,\n\t\t\t\t\t\t\t\t\t\t\t  const int u,\n\t\t\t\t\t\t\t\t\t\t\t  const int v,\n\t\t\t\t\t\t\t\t\t\t\t  const int l,\n\t\t\t\t\t\t\t\t\t\t\t  tln_e_t*& evars,\n\t\t\t\t\t\t\t\t\t\t\t  int & cont) {\n#ifndef NO_RECOMBINATIONS\n// Determino chi e' il genitore\n  bool u_child_of_v= (lg[u].individ->fi==v) ||\n\t (lg[u].individ->mi==v);\n\n  my_assert(u_child_of_v || (lg[v].individ->fi==u) ||\n\t\t\t\t(lg[v].individ->mi==u));\n  const int p= (u_child_of_v)?v:u;\n  const int c= (u_child_of_v)?u:v;\n  const int parenthood= lg[c].individ->fi==p?0:1;\n\n  for (int i= 1; i<=l; ++i) {\n\t if (lg[p].individ->g[i]==GEN2) {\n\t\tevars= new tln_e_t(evars,\n\t\t\t\t\t\t\t\t ped::e_variable_t(ped::e_variable_t::REC,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t c, i, parenthood));\n\t\t++cont;\n\t }\n  }\n#endif\n}\n\nstatic void\nget_rec_variables_from_edge_to_set(const LocusGraph& lg,\n\t\t\t\t\t\t\t\t\t\t\t  const int u,\n\t\t\t\t\t\t\t\t\t\t\t  const int v,\n\t\t\t\t\t\t\t\t\t\t\t  const int l,\n\t\t\t\t\t\t\t\t\t\t\t  ped::e_vars_t& evars) {\n#ifndef NO_RECOMBINATIONS\n// Determino chi e' il genitore\n  bool u_child_of_v= (lg[u].individ->fi==v) ||\n\t (lg[u].individ->mi==v);\n\n  my_assert(u_child_of_v || (lg[v].individ->fi==u) ||\n\t\t\t\t(lg[v].individ->mi==u));\n  const int p= (u_child_of_v)?v:u;\n  const int c= (u_child_of_v)?u:v;\n  const int parenthood= lg[c].individ->fi==p?0:1;\n\n  for (int i= 1; i<=l; ++i) {\n\t if (lg[p].individ->g[i]==GEN2) {\n\t\tevars.insert(ped::e_variable_t(ped::e_variable_t::REC,\n\t\t\t\t\t\t\t\t\t\t\t\t c, i, parenthood));\n\t }\n  }\n#endif\n}\n\nstatic ped::e_variable_t\nget_extremal_m_var(const ped::locus_status ls,\n\t\t\t\t\t\t const int v,\n\t\t\t\t\t\t const int locus) {\n  switch (ls) {\n\t case ped::LS_UNDETERMINED:\n\t\tfail();\n\t\tbreak;\n\t case ped::LS_IMMUTABLE:\n// none to add\n\t\treturn ped::e_variable_t();\n\t\tbreak;\n\t case ped::LS_PRED_SINGLE_FATHER:\n\t\treturn ped::e_variable_t(ped::e_variable_t::MUT, v, locus, 0);\n\t\tbreak;\n\t case ped::LS_PRED_SINGLE_MOTHER:\n\t\treturn ped::e_variable_t(ped::e_variable_t::MUT, v, locus, 1);\n\t\tbreak;\n\t case ped::LS_PRED_DOUBLE:\n\t\treturn ped::e_variable_t(ped::e_variable_t::MUT, v, locus, 0);\n\t\tbreak;\n\t case ped::LS_PRED_AMBIGUOUS:\n\t\treturn ped::e_variable_t(ped::e_variable_t::MUT, v, locus, 0);\n\t\tbreak;\n  }\n  fail();\n  return ped::e_variable_t();\n}\n\ntemplate <typename T>\nclass to_visit_t {\nprivate:\n  std::list<T> datas;\n\npublic:\n  void push(const T& el) {\n\t datas.push_front(el);\n  }\n\n  T pop(void) {\n\t T el= datas.front();\n\t datas.pop_front();\n\t return el;\n  }\n\n  bool empty(void) const {\n\t return datas.empty();\n  }\n};\n\ntemplate <typename SET>\nstatic void\nread_tree_path_events(tln_e_t* const n, SET& set) {\n  tln_e_t* tmp= n;\n  while (tmp->pred!=NULL) {\n#ifdef NO_RECOMBINATIONS\n\t if (tmp->data.kind() != ped::e_variable_t::REC)\n#endif\n#ifdef NO_MUTATIONS\n\t if (tmp->data.kind() != ped::e_variable_t::MUT)\n#endif\n\t\tset.insert(tmp->data);\n\t tmp= tmp->pred;\n  }\n}\n\ntemplate <typename SET>\nstatic void\nread_tree_path_hvars(tln_h_t* const n, SET& set) {\n  tln_h_t* tmp= n;\n  while (tmp->pred!=NULL) {\n\t set.insert(tmp->data);\n\t tmp= tmp->pred;\n  }\n}\n\nstatic void\nadd_constraints_from_v_in_locus(const LocusGraph& lg,\n\t\t\t\t\t\t\t\t\t\t  const LG_Vertex root,\n\t\t\t\t\t\t\t\t\t\t  cycle_constraints_t& ccv,\n\t\t\t\t\t\t\t\t\t\t  const int locus,\n\t\t\t\t\t\t\t\t\t\t  const int n_indiv,\n\t\t\t\t\t\t\t\t\t\t  std::vector<bool>& visited) {\n  my_assert(lg[root].ls != ped::LS_UNDETERMINED);\n  FINETRACE(\"Adding constraints from predetermined vertex %d.\", root);\n\n  to_visit_t< LG_Vertex > to_visit;\n  to_visit_t< tln_h_t* > tv_h;\n  to_visit_t< tln_e_t* > tv_e;\n  to_visit_t< int > tv_ne;\n  std::vector< int > sum(n_indiv, -1);\n\n  std::list< tln_h_t* > td_h;\n  std::list< tln_e_t* > td_e;\n  std::list< int > td_ne;\n\n  ped::e_vars_t::iterator it;\n  ped::e_variable_t m;\n  ped::h_variable_t h;\n\n  tln_e_t* const root_e= new tln_e_t(NULL, e_variable_t());\n  tln_h_t* const root_h= new tln_h_t(NULL, h_variable_t());\n\n  sum[root]= lg[root].ptilde;\n\n  int cont= 1;\n  m= get_extremal_m_var(lg[root].ls, root, locus);\n  if (m.i>=0) {\n\t tln_e_t* n= new tln_e_t(root_e, m);\n\t tv_e.push(n);\n\t cont= 2;\n  } else {\n\t tv_e.push(root_e);\n  }\n  tv_ne.push(cont);\n  tv_h.push(root_h);\n  to_visit.push(root);\n\n  while (!to_visit.empty()) {\n\t LG_Vertex v= to_visit.pop();\n\t tln_h_t* hvars= tv_h.pop();\n\t tln_e_t* evars= tv_e.pop();\n\t int ne= tv_ne.pop();\n\t td_h.push_front(hvars);\n\t td_e.push_front(evars);\n\t td_ne.push_front(ne);\n// Iterates over its out edges\n\t graph_traits<LocusGraph>::out_edge_iterator e, e_end, next;\n\t tie(e, e_end) = out_edges(v, lg);\n\t for (; e != e_end; ++e) {\n\t\tif (!lg[*e].in_spanning_forest)\n\t\t  continue;\n\t\tconst LG_Vertex u= target(*e, lg);\n\t\tif (sum[u]==-1) {\n\t\t  FINETRACE(\"Considering edge %d-%d\", v, u);\n\t\t  sum[u]= sum[v]+lg[*e].d;\n\t\t  m= get_m_variable_from_edge(lg, u, v, locus);\n\t\t  tln_e_t* new_evars= new tln_e_t(evars, m);\n\t\t  cont= 1;\n\t\t  get_rec_variables_from_edge_to_tln(lg, u, v, locus, new_evars, cont);\n\t\t  h= get_h_variable_from_edge(lg, u, v, locus);\n\t\t  tln_h_t* new_hvars= new tln_h_t(hvars, h);\n\t\t  to_visit.push(u);\n\t\t  tv_e.push(new_evars);\n\t\t  tv_ne.push(cont);\n\t\t  tv_h.push(new_hvars);\n\t\t  if (lg[u].ls != ped::LS_UNDETERMINED) {\n\t\t\t DEBUG(\"Constraint detected between vertex \" ST_FMT \" and vertex \" ST_FMT \".\", root, u);\n\t\t\t visited[u]= true;\n\t\t\t cycle_constraint_t* cc= new cycle_constraint_t;\n\t\t\t ccv.push_back(cc);\n\t\t\t cc->constant= (sum[u]+lg[u].ptilde)%2==1;\n\t\t\t m= get_extremal_m_var(lg[u].ls, u, locus);\n\t\t\t if (m.i>=0) {\n\t\t\t\tnew_evars= new tln_e_t(new_evars, m);\n\t\t\t\t++cont;\n\t\t\t }\n\t\t\t read_tree_path_hvars(new_hvars, cc->h_vars);\n\t\t\t read_tree_path_events(new_evars, cc->events);\n\t\t  }\n// Free memory\n//\t\t\t delete new_hvars;\n//\t\t\t for (int i= 0; i<cont; ++i) {\n//\t\t\t\ttln_e_t* tmp= new_evars;\n//\t\t\t\tnew_evars= new_evars->pred;\n//\t\t\t\tdelete tmp;\n//\t\t\t }\n//\t\t  }\n\t\t}\n\t }\n  }\n\n  while (!td_h.empty()) {\n\t delete td_h.front();\n\t td_h.pop_front();\n  }\n  while (!td_e.empty()) {\n\t int ne= td_ne.front();\n\t tln_e_t* evars= td_e.front();\n\t for (int i= 0; i<ne; ++i) {\n\t\ttln_e_t* tmp= evars;\n\t\tevars= evars->pred;\n\t\tdelete tmp;\n\t }\n\t td_ne.pop_front();\n\t td_e.pop_front();\n  }\n}\n\nstatic void\nadd_immutable_immutable_constraints\n  (pgenped pg,\n\tped::e_vars_t& m_vars_univ,\n\tped::cycle_constraints_t& cycle_constraints)\n{\n  for (unsigned int i= 0; i<pg->n_indiv; ++i) {\n\t if (pg->individuals[i]->fi==-1) {\n\t\tmy_assert(pg->individuals[i]->mi==-1);\n\t } else {\n\t\tpindiv const ii= pg->individuals[i];\n\t\tfor (unsigned int j= 0; j<pg->n_loci; ++j) {\n\t\t  if (ii->g[j]!=GEN2 && ii->f->g[j]!=GEN2) {\n\t\t\t if (ii->g[j]!=ii->f->g[j]) {\n\t\t\t\tped::e_variable_t mv(ped::e_variable_t::MUT, i, j, 0);\n\t\t\t\tm_vars_univ.insert(mv);\n\t\t\t\tped::cycle_constraint_t* cc= new ped::cycle_constraint_t;\n\t\t\t\tcc->events.insert(mv);\n\t\t\t\tcc->constant= true;\n\t\t\t\tcycle_constraints.push_back(cc);\n\t\t\t\tDEBUG(\"Added immutable constraint for indiv. %d at locus %d\"\n\t\t\t\t\t\t\" because he and his father are homozygous and they have\"\n\t\t\t\t\t\t\" different alleles.\",\n\t\t\t\t\t\tmv.i, mv.l);\n\t\t\t }\n\t\t  }\n\t\t  if (ii->g[j]!=GEN2 && ii->m->g[j]!=GEN2) {\n\t\t\t if (ii->g[j]!=ii->m->g[j]) {\n\t\t\t\tped::e_variable_t mv(ped::e_variable_t::MUT, i, j, 1);\n\t\t\t\tm_vars_univ.insert(mv);\n\t\t\t\tped::cycle_constraint_t* cc= new ped::cycle_constraint_t;\n\t\t\t\tcc->events.insert(mv);\n\t\t\t\tcc->constant= true;\n\t\t\t\tcycle_constraints.push_back(cc);\n\t\t\t\tDEBUG(\"Added immutable constraint for indiv. %d at locus %d\"\n\t\t\t\t\t\t\" because he and his mother are homozygous and they have\"\n\t\t\t\t\t\t\" different alleles.\",\n\t\t\t\t\t\tmv.i, mv.l);\n\t\t\t }\n\t\t  }\n\t\t  if ((ii->g[j]==GEN2) &&\n\t\t\t\t(ii->f->g[j] == ii->m->g[j]) &&\n\t\t\t\t(ii->f->g[j]!=GEN2)) {\n\t\t\t ped::e_variable_t mv0(ped::e_variable_t::MUT, i, j, 0);\n\t\t\t if (m_vars_univ.find(mv0)==m_vars_univ.end()) {\n\t\t\t\tm_vars_univ.insert(mv0);\n\t\t\t\tped::e_variable_t mv1(ped::e_variable_t::MUT, i, j, 1);\n\t\t\t\tm_vars_univ.insert(mv1);\n\t\t\t\tped::cycle_constraint_t* cc= new ped::cycle_constraint_t;\n\t\t\t\tcc->events.insert(mv0);\n\t\t\t\tcc->events.insert(mv1);\n\t\t\t\tcc->constant= true;\n\t\t\t\tcycle_constraints.push_back(cc);\n\t\t\t\tDEBUG(\"Added special constraint for indiv. %d at locus %d\"\n\t\t\t\t\t\t\" because he is ambiguously predetermined.\",\n\t\t\t\t\t\ti, j);\n\t\t\t }\n\t\t  }\n\t\t}\n\t }\n  }\n}\n\n\n// Compute the tree path between u and v on lg\nstatic void\ntree_path(const LocusGraph& lg,\n\t\t\t const LG_Vertex& u,\n\t\t\t const LG_Vertex& v,\n\t\t\t std::list< LG_Vertex >& path_u_v) {\n  list<LG_Edge> path_v_root;\n  LG_Vertex tmp= v;\n  while (lg[tmp].pred_vertex != tmp) {\n\t path_v_root.push_front(lg[tmp].pred_edge);\n\t tmp= lg[tmp].pred_vertex;\n  }\n  list<LG_Edge> path_u_root;\n  tmp= u;\n  while (lg[tmp].pred_vertex != tmp) {\n\t path_u_root.push_front(lg[tmp].pred_edge);\n\t tmp= lg[tmp].pred_vertex;\n  }\n  while (!path_u_root.empty() && !path_v_root.empty()\n\t\t\t&& (path_u_root.front()==path_v_root.front())) {\n\t path_u_root.pop_front();\n\t path_v_root.pop_front();\n  }\n  tmp= u;\n  path_u_v.push_front(u);\n  while (!path_u_root.empty()) {\n\t LG_Edge e= path_u_root.back();\n\t if (source(e, lg)==tmp) {\n\t\ttmp= target(e, lg);\n\t } else if (target(e, lg)==tmp) {\n\t\ttmp= source(e, lg);\n\t } else {\n\t\tERROR(\"Error in determining the tree path from \" ST_FMT \" to \" ST_FMT \".\", u, v);\n\t\tfail();\n\t }\n\t path_u_v.push_back(tmp);\n\t path_u_root.pop_back();\n  }\n  tmp= path_u_v.back();\n  while (!path_v_root.empty()) {\n\t LG_Edge e= path_v_root.front();\n\t if (source(e, lg)==tmp) {\n\t\ttmp= target(e, lg);\n\t } else if (target(e, lg)==tmp) {\n\t\ttmp= source(e, lg);\n\t } else {\n\t\tERROR(\"Error in determining the tree path from \" ST_FMT \" to \" ST_FMT \".\", u, v);\n\t\tfail();\n\t }\n\t path_u_v.push_back(tmp);\n\t path_v_root.pop_front();\n  }\n#ifdef LOG_DEBUG_ENABLED\n  DEBUG_NOTN(\"The foundamental cycle of edge (\" ST_FMTL(4) \" -\" ST_FMTL(4) \" ) \"\n\t\t\t\t \"contains the path {\", u, v);\n  for (std::list< LG_Vertex >::const_iterator it= path_u_v.begin();\n\t\t it != path_u_v.end(); ++it) {\n\t if (it!=path_u_v.begin())\n\t\tDEBUG_MSG(\"%s\",\", \");\n\t DEBUG_MSG(\"\" ST_FMTL(4) \" \", *it);\n  }\n  DEBUG_MSG(\"%s\",\"}\\n\");\n#endif\n}\n\nstatic void\nadd_non_tree_constraints(const LocusGraph& glg,\n\t\t\t\t\t\t\t\t const LocusGraph& lg,\n\t\t\t\t\t\t\t\t cycle_constraints_t& ccv,\n\t\t\t\t\t\t\t\t const int locus) {\n  BGL_FORALL_EDGES(e, lg, LocusGraph) {\n\t if (lg[e].in_spanning_forest)\n\t\tcontinue;\n\t const LG_Vertex u= source(e, lg);\n\t const LG_Vertex v= target(e, lg);\n\t DEBUG(\"Adding constraints for non-tree edge \" ST_FMT \"-\" ST_FMT \".\", u, v);\n\t std::list< LG_Vertex > cycle_e;\n\t tree_path(lg, u, v, cycle_e);\n\n\t unsigned int predet_vertices= 0;\n\t for (std::list< LG_Vertex >::const_iterator it= cycle_e.begin();\n\t\t\tit != cycle_e.end(); ++it) {\n\t\tif (lg[*it].ls!=ped::LS_UNDETERMINED)\n\t\t  ++predet_vertices;\n\t }\n\t DEBUG(\"The foundamental cycle of (\" ST_FMT \"-\" ST_FMT \") has %u predetermined vertices.\",\n\t\t\t u, v, predet_vertices);\n\t if (predet_vertices<=1) {\n\t\tDEBUG(\"The foundamental cycle exists in the locus graph %d.\", locus);\n\t\tDEBUG(\"Adding NON-tree constraint.\");\n\t\tped::cycle_constraint_t* c= new cycle_constraint_t;\n\t\tccv.push_back(c);\n\t\tLG_Vertex prev= v;\n\t\tc->constant= false;\n\t\tfor (std::list< LG_Vertex >::const_iterator it= cycle_e.begin();\n\t\t\t  it != cycle_e.end(); ++it) {\n\t\t  bool found= false;\n\t\t  LG_Edge lge;\n\t\t  tie(lge, found)= edge(prev, *it, lg);\n\t\t  my_assert(found);\n\t\t  c->constant ^= (lg[lge].d==1);\n#ifndef NO_MUTATIONS\n\t\t  c->events.insert(get_m_variable_from_edge(lg, prev, *it, locus));\n#endif\n#ifndef NO_RECOMBINATIONS\n\t\t  get_rec_variables_from_edge_to_set(lg, prev, *it, locus, c->events);\n#endif\n\t\t  c->h_vars.insert(get_h_variable_from_edge(lg, prev, *it, locus));\n\t\t  prev= *it;\n\t\t}\n\t } else {\n// Compute the predetermined endpoints of the path\n\t\tDEBUG(\"The foundamental cycle does not exist in the locus graph %d.\",\n\t\t\t\tlocus);\n\t\tDEBUG(\"Adding tree constraint.\");\n\t\tLG_Vertex x= u;\n\t\tfor (std::list< LG_Vertex >::const_iterator it= cycle_e.begin();\n\t\t\t  (it != cycle_e.end()) && (lg[x].ls==ped::LS_UNDETERMINED);\n\t\t\t  ++it) {\n\t\t  x= *it;\n\t\t}\n\t\tmy_assert(lg[x].ls!=ped::LS_UNDETERMINED);\n\t\tLG_Vertex y= v;\n\t\tfor (std::list< LG_Vertex >::const_reverse_iterator it= cycle_e.rbegin();\n\t\t\t  (it != cycle_e.rend()) && (lg[y].ls==ped::LS_UNDETERMINED);\n\t\t\t  ++it) {\n\t\t  y= *it;\n\t\t}\n\t\tmy_assert(lg[y].ls!=ped::LS_UNDETERMINED);\n\t\tmy_assert(x!=y);\n\t\tDEBUG(\"Endpoints of the constraint \" ST_FMT \"-\" ST_FMT \".\", x, y);\n\t\tped::cycle_constraint_t* c= new cycle_constraint_t;\n\t\tccv.push_back(c);\n\t\tLG_Vertex prev= v;\n\t\tc->constant= false;\n\t\tbool avoid= false;\n\t\tfor (std::list< LG_Vertex >::const_iterator it= cycle_e.begin();\n\t\t\t  it != cycle_e.end(); ++it) {\n\t\t  if (!avoid) {\n\t\t\t bool found= false;\n\t\t\t LG_Edge lge;\n\t\t\t DEBUG(\"\" ST_FMT \" \" ST_FMT \"\", prev, *it);\n\t\t\t tie(lge, found)= edge(prev, *it, lg);\n\t\t\t my_assert(found);\n\t\t\t c->constant ^= (lg[lge].d==1);\n#ifndef NO_MUTATIONS\n\t\t\t c->events.insert(get_m_variable_from_edge(lg, prev, *it, locus));\n#endif\n#ifndef NO_RECOMBINATIONS\n\t\t\t get_rec_variables_from_edge_to_set(lg, prev, *it, locus, c->events);\n#endif\n\t\t\t c->h_vars.insert(get_h_variable_from_edge(lg, prev, *it, locus));\n\t\t  }\n\t\t  prev= *it;\n\t\t  if (*it==y)\n\t\t\t avoid= false;\n\t\t  if (*it==x)\n\t\t\t avoid= true;\n\t\t}\n#ifndef NO_MUTATIONS\n// Add extremal m variables\n\t\tped::e_variable_t m= get_extremal_m_var(lg[x].ls, x, locus);\n\t\tif (m.i>=0) {\n\t\t  c->events.insert(m);\n\t\t}\n\t\tm= get_extremal_m_var(lg[y].ls, y, locus);\n\t\tif (m.i>=0) {\n\t\t  c->events.insert(m);\n\t\t}\n#endif\n// Add predetermined phases\n\t\tc->constant ^= ((lg[x].ptilde+lg[y].ptilde)%2)==1;\n\t }\n  }\n}\n\n\nstatic void\nadd_special_constraints(ped::e_vars_t& m_vars_univ,\n\t\t\t\t\t\t\t\tLocusGraph** lgs,\n\t\t\t\t\t\t\t\tped::cycle_constraints_t& cycle_constraints)\n{\n  ped::e_vars_t new_vars;\n  ped::e_vars_t::iterator iMVU= m_vars_univ.begin();\n  const ped::e_vars_t::iterator& iMVUend= m_vars_univ.end();\n  for (; iMVU!=iMVUend; ++iMVU) {\n\t const ped::e_variable_t& mv= *iMVU;\n\t if (mv.kind()==ped::e_variable_t::MUT && mv.p==0 && (*lgs[mv.l])[mv.i].ls>=ped::LS_PRED_DOUBLE) {\n\t\tped::cycle_constraint_t* cc= new ped::cycle_constraint_t;\n\t\tcc->events.insert(mv);\n\t\tped::e_variable_t mv1= mv;\n\t\tmv1.p= 1;\n\t\tcc->events.insert(mv1);\n\t\tcc->constant= (*lgs[mv.l])[mv.i].ls==ped::LS_PRED_AMBIGUOUS;\n\t\tcycle_constraints.push_back(cc);\n\t\tm_vars_univ.insert(iMVU, mv1);\n\t\tnew_vars.insert(mv1);\n\t\tDEBUG(\"Added special constraint for indiv. %d at locus %d because he is %s.\",\n\t\t\t\tmv.i, mv.l, ped::locus_status_names[(*lgs[mv.l])[mv.i].ls]);\n\t }\n  }\n}\n\n\n\nstatic void\nbuild_basic_constraints(LocusGraph* const glg,\n\t\t\t\t\t\t\t\tLocusGraph* const * const lgs,\n\t\t\t\t\t\t\t\tpgenped gp,\n\t\t\t\t\t\t\t\tped::cycle_constraints_t& constraints) {\n/*********************************************************\n *\n * Per ogni locus graph Gl\n *   Per ogni vertice v\n *     if v is predetermined then\n *       visita il grafo a partire da v e aggiungi i vincoli\n *\n *********************************************************/\n  for (unsigned int l= 0; l<gp->n_loci; ++l) {\n\t DEBUG(\"Starting analysis of constraints of locus %d.\", l);\n\t LocusGraph& lg= *(lgs[l]);\n\t std::vector<bool> visited(gp->n_indiv, false);\n\t for (unsigned int v= 0; v<gp->n_indiv; ++v) {\n\t\tif (lg[v].ls!=ped::LS_UNDETERMINED && !visited[v]) {\n\t\t  visited[v]= true;\n\t\t  TRACE(\"Vertex %d is predetermined.\", v);\n\t\t  add_constraints_from_v_in_locus(lg, v, constraints,\n\t\t\t\t\t\t\t\t\t\t\t\t\t l, gp->n_indiv, visited);\n\t\t}\n\t }\n\t add_non_tree_constraints(*glg, lg, constraints, l);\n  }\n}\n\nvoid\nbuild_constraints_from_pedigree(pgenped gp,\n\t\t\t\t\t\t\t\t\t\t  ped::cycle_constraints_t& final_ct,\n\t\t\t\t\t\t\t\t\t\t  ped::e_vars_t& e_vars_univ) {\n\n#if (defined NO_RECOMBINATIONS) && (defined NO_MUTATIONS)\n#error \"Both Recombinations and Mutations are excluded. Impossible to continue.\"\n#endif\n#ifdef NO_MUTATIONS\n#warning \"Only RECOMBINATIONS are considered.\"\n  WARN(\"Only RECOMBINATIONS are considered.\");\n#endif\n#ifdef NO_RECOMBINATIONS\n#warning \"Only MUTATIONS are considered.\"\n  WARN(\"Only MUTATIONS are considered.\");\n#endif\n  my_assert(gp!=NULL);\n// Build the locus graphs\n  LocusGraph* glg= build_general_locus_graph_from_pedigree(gp);\n  LocusGraph** lgs= build_all_locus_graphs_from_pedigree(gp);\n\n// Build the basic constraints\n  ped::cycle_constraints_t basic_ct;\n  build_basic_constraints(glg, lgs, gp, basic_ct);\n#ifdef LOG_DEBUG_ENABLED\n  {\n\t DEBUG(\"Basic constraints:\");\n\t int _cont= 0;\n\t for (cycle_constraints_t::iterator it= basic_ct.begin();\n\t\t\tit!=basic_ct.end();\n\t\t\t++it, ++_cont) {\n\t\tDEBUG(\"Constraint %4d.\", _cont);\n\t\tDEBUG(\"h_vars: %s\", to_c_str((*it)->h_vars));\n\t\tDEBUG(\"events: %s\", to_c_str((*it)->events));\n\t\tDEBUG(\"constant: %d\", ((*it)->constant)?1:0);\n\t }\n  }\n#endif\n\n// Build the basis of the null-space of the vector space spanned by\n// the set of h-variable subsets\n\n// 1- build the map h-variable <->position\n  ped::h_vars_t h_vars;\n  unsigned int i= 0;\n  for (ped::cycle_constraints_t::const_iterator cit= basic_ct.begin();\n\t\t cit!=basic_ct.end(); ++cit) {\n\t for (ped::h_vars_t::const_iterator hit= (*cit)->h_vars.begin();\n\t\t\thit!= (*cit)->h_vars.end(); ++hit){\n\t\th_vars.insert(*hit);\n\t }\n\t ++i;\n  }\n\n  const size_t N_BASIC_CT= i;\n  const size_t N_H_VARS= h_vars.size();\n#ifdef LOG_STATS_ENABLED\n  static bool first= true;\n  STATS_IF(first, \"# basic constraints \" ST_FMT \"\", N_BASIC_CT);\n  STATS_IF(first, \"# h-variables \" ST_FMT \"\", N_H_VARS);\n#endif\n\n  if (N_BASIC_CT>0) {\n\t DEBUG(\"There are \" ST_FMTL(4) \"  basic constraints and \" ST_FMTL(4) \"  h-variables.\",\n\t\t\t N_BASIC_CT, N_H_VARS);\n\n\t std::map<h_variable_t, unsigned int> h_to_pos;\n\t std::vector<h_variable_t> pos_to_h(N_H_VARS);\n\t i= 0;\n\t for (ped::h_vars_t::const_iterator hit= h_vars.begin();\n\t\t\thit!= h_vars.end(); ++hit, ++i) {\n\t\th_to_pos[*hit]= i;\n\t\tpos_to_h.push_back(*hit);\n\t }\n\n// 2- build the binary matrix\n\t mzd_t *bm= MZD_INIT(N_H_VARS, N_BASIC_CT);\n\t i= 0;\n\t for (ped::cycle_constraints_t::const_iterator cit= basic_ct.begin();\n\t\t\tcit!=basic_ct.end(); ++cit) {\n\t\tfor (size_t j= 0; j<N_H_VARS; ++j)\n\t\t  mzd_write_bit(bm, j, i, 0);\n\t\tfor (ped::h_vars_t::const_iterator hit= (*cit)->h_vars.begin();\n\t\t\t  hit!= (*cit)->h_vars.end(); ++hit){\n\t\t  mzd_write_bit(bm, h_to_pos[*hit], i, 1);\n\t\t}\n\t\t++i;\n\t }\n\t const size_t rank_bm= mzd_echelonize_m4ri(bm, 0, 0);\n\t STATS_IF(first, \"rank basic constraints \" ST_FMT \"\", rank_bm);\n//\t DEBUG(\"The rank of the basic constraint matrix is %4d.\", rank_bm);\n/**\n * 3- reorder column so that the first rank_bm are independent\n * */\n\t std::vector<int> col_perm;\n\t mzd_t *bm_re= MZD_INIT(rank_bm, N_BASIC_CT);\n\t size_t pos= 0;\n\t for (i= 0; i<rank_bm; ++i) {\n\t\twhile (mzd_read_bit(bm, i, pos)==0) {\n\t\t  ++pos;\n\t\t}\n// Independent column\n\t\tfor (size_t j= 0; j<=i; ++j)\n\t\t  mzd_write_bit(bm_re, j, i, mzd_read_bit(bm, j, pos));\n\t\tcol_perm.push_back(pos);\n\t\t++pos;\n\t }\n\t size_t second_part= rank_bm;\n\t i= 0;\n\t pos= 0;\n\t while ((second_part<N_BASIC_CT) && (i<N_H_VARS)) {\n\t\twhile ((pos<N_BASIC_CT) && (mzd_read_bit(bm, i, pos) == 0)) {\n// Move column pos to second_part\n\t\t  for (size_t j= 0; j<i; ++j)\n\t\t\t mzd_write_bit(bm_re, j, second_part, mzd_read_bit(bm, j, pos));\n\t\t  col_perm.push_back(pos);\n\t\t  ++second_part;\n\t\t  ++pos;\n\t\t}\n\t\t++i;\n\t\t++pos;\n\t }\n// Move remaining columns to second_part\n\t while (second_part<N_BASIC_CT) {\n\t\tfor (size_t j= 0; j<N_H_VARS; ++j)\n\t\t  mzd_write_bit(bm_re, j, second_part, mzd_read_bit(bm, j, pos));\n\t\tcol_perm.push_back(pos);\n\t\t++second_part;\n\t\t++pos;\n\t }\n\n// Transform the independent columns into a identity matrix\n\t for (i= rank_bm-1; i>0; --i) {\n\t\tfor (size_t j= 0; j<i; ++j) {\n\t\t  if (mzd_read_bit(bm_re, j, i)==1) {\n\t\t\t mzd_row_add(bm_re, i, j);\n\t\t  }\n\t\t}\n\t }\n\n// The last N_BASIC_CT - rank_bm columns contain the null-space\n\n// Generate cycle-constraints\n\t for (i= rank_bm; i<N_BASIC_CT; ++i) {\n\t\tDEBUG(\"Generating cycle constraint \" ST_FMTL(4) \" .\", i+1-rank_bm);\n\t\tped::cycle_constraint_t* cc= new ped::cycle_constraint_t;\n\t\tcc->events= basic_ct[col_perm[i]]->events;\n\t\tcc->constant= basic_ct[col_perm[i]]->constant;\n\t\tDEBUG(\"Dependent constraint %d\", col_perm[i]);\n\t\tfor (size_t j= 0; j<rank_bm; ++j) {\n\t\t  if (mzd_read_bit(bm_re, j, i)==1) {\n\t\t\t DEBUG(\"+ constraint %d\", col_perm[j]);\n\t\t\t inplace_symmetric_difference(cc->events, basic_ct[col_perm[j]]->events);\n\t\t\t cc->constant= cc->constant != basic_ct[col_perm[j]]->constant;\n\t\t  }\n\t\t}\n\t\tinplace_union(e_vars_univ, cc->events);\n\t\tfinal_ct.push_back(cc);\n\t }\n\t mzd_free(bm);\n\t mzd_free(bm_re);\n  } else {\n\t INFO(\"There are no basic constraints.\");\n  }\n\n\n  add_special_constraints(e_vars_univ, lgs, final_ct);\n\n  add_immutable_immutable_constraints(gp, e_vars_univ, final_ct);\n\n  for (ped::cycle_constraints_t::const_iterator cit= basic_ct.begin();\n\t\t cit!=basic_ct.end(); ++cit) {\n\t delete *cit;\n  }\n  for (unsigned int l= 0; l<gp->n_loci; ++l)\n\t delete (lgs[l]);\n  delete glg;\n  pfree(lgs);\n#ifdef LOG_STATS_ENABLED\n  STATS_IF(first, \"# initial cycle constraints \" ST_FMT \"\", final_ct.size());\n  STATS_IF(first, \"# initial events variables \" ST_FMT \"\", e_vars_univ.size());\n  first= false;\n#endif\n}\n\n\n", "meta": {"hexsha": "b9ec722656c76e5b3f6562074a38a9d553a739d6", "size": 27765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/locus-graph.cpp", "max_stars_repo_name": "yp/Heu-MCHC", "max_stars_repo_head_hexsha": "30c4a5e189c7ab67d82357d2c8a98833a556345a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-30T04:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-30T04:39:34.000Z", "max_issues_repo_path": "src/locus-graph.cpp", "max_issues_repo_name": "yp/Heu-MCHC", "max_issues_repo_head_hexsha": "30c4a5e189c7ab67d82357d2c8a98833a556345a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/locus-graph.cpp", "max_forks_repo_name": "yp/Heu-MCHC", "max_forks_repo_head_hexsha": "30c4a5e189c7ab67d82357d2c8a98833a556345a", "max_forks_repo_licenses": ["BSD-3-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.4629080119, "max_line_length": 99, "alphanum_fraction": 0.6405906717, "num_tokens": 9090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.02442308961030215, "lm_q1q2_score": 0.007265135368829004}}
{"text": "#ifndef GEODB_INTERVAL_SET_HPP\n#define GEODB_INTERVAL_SET_HPP\n\n#include \"geodb/algorithm.hpp\"\n#include \"geodb/common.hpp\"\n#include \"geodb/interval.hpp\"\n#include \"geodb/type_traits.hpp\"\n\n#include <boost/range/adaptor/indirected.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/algorithm/equal.hpp>\n#include <boost/range/algorithm_ext/push_back.hpp>\n#include <boost/range/concepts.hpp>\n#include <boost/range/counting_range.hpp>\n#include <boost/range/empty.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/sub_range.hpp>\n#include <boost/range/metafunctions.hpp>\n#include <boost/range/numeric.hpp>\n#include <tpie/serialization2.h>\n\n#include <algorithm>\n#include <ostream>\n#include <queue>\n#include <vector>\n\n/// \\file\n/// Implements a compact set based on sorted, non-overlapping intervals.\n\nnamespace geodb {\n\nnamespace detail {\n    /// Represents the start or end point of some interval.\n    template<typename T>\n    struct interval_event {\n        enum kind_t {\n            open = 1, close = 2\n        };\n\n        kind_t kind;\n        T point;\n\n        // Ordered by point. Open events come before close events on the same point.\n        bool operator<(const interval_event& other) const {\n            return point < other.point || (point == other.point && kind < other.kind);\n        }\n\n        bool operator==(const interval_event& other) const {\n            return kind == other.kind && point == other.point;\n        }\n    };\n\n    /// Takes a range of interval-ranges and invokes the provided callback\n    /// for every interval event (open or close) in sorted ascernding order.\n    /// Each individual interval range must be in sorted order (ascending)\n    /// with no overlapping intervals.\n    /// Intervals from different ranges may overlap.\n    ///\n    /// This function serves as a building block for plane-sweep algorithms over\n    /// a series of interval sets.\n    ///\n    /// Runtime complexity: O(N log M) where N is the total number of intervals\n    /// and M is the number of nested ranges.\n    template<typename Range, typename Callback>\n    void interval_events(const Range& rng, Callback&& cb) {\n        using nested_range_type = typename boost::range_value<const Range>::type;\n\n        using nested_iterator_type = typename boost::range_iterator<\n            typename boost::range_value<const Range>::type\n        >::type;\n\n        using interval_type = typename boost::range_value<nested_range_type>::type;\n\n        using point_type = typename interval_type::value_type;\n\n        using event_type = interval_event<point_type>;\n\n        static_assert(is_specialization_of<interval, interval_type>::value,\n                      \"nested ranges must contain intervals\");\n        static_assert(std::is_lvalue_reference<typename boost::range_reference<const Range>::type>::value,\n                      \"nested ranges must be lvalues (i.e. no temporaries).\");\n\n        BOOST_CONCEPT_ASSERT(( boost::ForwardRangeConcept<const Range> ));\n        BOOST_CONCEPT_ASSERT(( boost::ForwardRangeConcept<const nested_range_type> ));\n\n        // A cursor tracks the iterator position within one of the subranges.\n        // Every interval is visited twice, once for the start and once for the end point.\n        struct cursor_t {\n        private:\n            typename event_type::kind_t kind;\n            nested_iterator_type pos;\n            nested_iterator_type end;\n\n        public:\n            cursor_t(nested_iterator_type pos, nested_iterator_type end)\n                : kind(event_type::open)\n                , pos(pos), end(end)\n            {}\n\n            bool at_end() const { return pos == end; }\n\n            event_type event() const {\n                geodb_assert(pos != end, \"not at end\");\n                return kind == event_type::open\n                          ? event_type{kind, pos->begin()}\n                          : event_type{kind, pos->end()};\n            }\n\n            void advance() {\n                geodb_assert(pos != end, \"not at end\");\n                if (kind == event_type::open) {\n                    kind = event_type::close;\n                    return;\n                }\n\n                ++pos;\n                kind = event_type::open;\n            }\n\n            bool operator<(const cursor_t& other) const { return event() < other.event(); }\n            bool operator>(const cursor_t& other) const { return other < *this; }\n        };\n\n        // A min heap that keeps track of the closest cursor.\n        std::priority_queue<cursor_t, std::vector<cursor_t>, std::greater<cursor_t>> queue;\n        for (auto&& nested_range : rng) {\n            cursor_t c(boost::begin(nested_range), boost::end(nested_range));\n            if (!c.at_end()) {\n                queue.push(std::move(c));\n            }\n        }\n\n        while (!queue.empty()) {\n            // Pop the closest cursor and get one event from it. Reinsert the\n            // cursor if there are more elements.\n            cursor_t c = std::move(queue.top());\n            queue.pop();\n\n            cb(c.event());\n\n            c.advance();\n            if (!c.at_end()) {\n                queue.push(std::move(c));\n            }\n        }\n    }\n\n    /// Takes a vector of intervals and a range of iterators into that vector.\n    /// Every iterator in `gaps` gives the position after which a new merged interval begins.\n    /// \\pre `gaps` must be sorted.\n    /// \\warning `gaps` must not contain the last iterator.\n    template<typename T, typename IteratorRange>\n    void merge_positions(std::vector<interval<T>>& intervals, const IteratorRange& gaps) {\n        using iterator = typename std::vector<interval<T>>::iterator;\n\n        auto gaps_pos = boost::begin(gaps);\n        auto gaps_end = boost::end(gaps);\n\n        if (intervals.empty()) {\n            return;\n        }\n\n        auto write_merged = [](iterator out, iterator a, iterator b) {\n            geodb_assert(a <= b, \"iterator ordering violated\");\n            T begin = a->begin();\n            T end = b->end();\n            *out = interval<T>(begin, end);\n        };\n\n        // Merge intervals until a new gap is encountered, at which point a new interval begins.\n        iterator in = intervals.begin();\n        iterator out = in;\n        iterator last = intervals.end();\n        while (gaps_pos != gaps_end) {\n            // Note: in != last because there are valid iterators in gaps remaining.\n            iterator gap = *gaps_pos++;\n            geodb_assert(gap != last - 1, \"the last interval has no successor.\");\n\n            write_merged(out, in, gap);\n            ++out;\n            in = gap + 1;\n        }\n\n        // The interval after the last gap.\n        write_merged(out, in, last - 1);\n        ++out;\n        intervals.erase(out, last);\n    }\n\n    /// Merges adjacent intervals until there are no more than\n    /// `capacity` intervals in total. Chooses the intervals with the\n    /// smallest gaps in between.\n    /// The interval vector is modified in-place.\n    template<typename T>\n    void merge_intervals(std::vector<interval<T>>& intervals, size_t capacity) {\n        using iterator = typename std::vector<interval<T>>::iterator;\n\n        geodb_assert(capacity > 0, \"invalid capacity\");\n\n        const size_t size = intervals.size();\n        if (size <= capacity) {\n            return;\n        }\n\n        // Compute the `capacity - 1` largest gaps.\n        // We will keep these gaps and merge all other intervals between them.\n        // Then, the size of the new set will have the size `capacity`.\n        const size_t k = capacity - 1;\n        std::vector<iterator> gaps(k);\n        k_smallest(boost::counting_range(intervals.begin(), intervals.end() - 1), k, gaps,\n            // Compare the distances between the interval pairs.\n            [](const iterator& pos1, const iterator& pos2) {\n                geodb_assert(pos1[1].begin() > pos1[0].end(), \"intervals must be ordered\");\n                geodb_assert(pos2[1].begin() > pos2[0].end(), \"intervals must be ordered\");\n                // \">\": compute largest instead of k_smallest.\n                return pos1[1].begin() - pos1[0].end() > pos2[1].begin() - pos2[0].end();\n            }\n        );\n\n        // Intervals are ordered by merge cost, now sort them in positional order.\n        std::sort(gaps.begin(), gaps.end());\n\n        // Close the gaps in place.\n        return merge_positions(intervals, gaps);\n    }\n\n} // namespace detail\n\n/// Represents a set of integers as intervals.\n/// Points can be inserted as intervals of size 1.\n/// Using \\ref trim(), one can reduce the size of the set\n/// by merging neighboring intervals, thus introducing some error.\n///\n/// Efficient algorithms for computing the union / intersection of an\n/// arbitrary number of interval_sets are provided.\n///\n/// Note: This class is backed by a sorted vector. Insert performance could\n/// be improved by using a balanced search tree instead.\n/// Intervals are sorted and do not overlap, so a \"normal\" 1-D tree\n/// would be sufficient.\ntemplate<typename T>\nclass interval_set {\n    using storage_type = std::vector<interval<T>>;\n\npublic:\n    using iterator = typename storage_type::const_iterator;\n    using const_iterator = iterator;\n\n    using interval_type = interval<T>;\n    using point_type = T;\n\npublic:\n    /// Takes a range of interval_sets and computes their union.\n    ///\n    /// Runtime complexity: O(N log M) where N is the total number of intervals across all ranges\n    /// and M is the number of ranges.\n    template<typename Range>\n    static interval_set set_union(Range&& rng)\n    {\n        using detail::interval_events;\n\n        // Sweep over the plane and keep track of open intervals.\n        // Whenever the open counter reaches zero, an element of the union has been found.\n        std::vector<interval_type> result;\n        point_type begin;   // Start of the earliest still active interval.\n        size_t open = 0;    // Number of open intervals.\n        interval_events(rng, [&](const auto& event) {\n            if (event.kind == event.open) {\n                if (++open == 1) {\n                    begin = event.point;\n                }\n            } else {\n                if (open-- == 1) {\n                    result.push_back(interval_type(begin, event.point));\n                }\n            }\n        });\n        return interval_set(std::move(result));\n    }\n\n    /// Takes a range of interval_sets and return their intersection.\n    ///\n    /// Runtime complexity: O(N log M) where N is the total number of intervals across all ranges\n    /// and M is the number of ranges.\n    template<typename Range>\n    static interval_set set_intersection(Range&& rng) {\n        using detail::interval_events;\n\n        // Sweep over the plane and keep track of open intervals.\n        // When a close event is encountered and the count of open intervals\n        // equals the number of sets in `rng`, then the closing interval\n        // is a member of the intersection.\n        // Note: Intervals in individual sets do not overlap, thus the count\n        // of open intervals can never be greater than `size`.\n        std::vector<interval_type> result;\n        size_t size = boost::size(rng);\n        point_type begin = 0;   // Start of the intersection interval.\n        size_t open = 0;        // Number of open intervals.\n        interval_events(rng, [&](const auto& event) {\n            geodb_assert(open <= size, \"too many active intervals\");\n\n            if (event.kind == event.open) {\n                if (++open == size) {\n                    begin = event.point;\n                }\n            } else {\n                if (open-- == size) {\n                    result.push_back(interval_type(begin, event.point));\n                }\n            }\n        });\n        return interval_set(std::move(result));\n    }\n\npublic:\n    /// Creates an empty interval set.\n    /// \\post `size() == 0`.\n    interval_set() {}\n\n    /// Creates a new interval set from the given list of intervals.\n    /// The list must be sorted (by start coordinate, ascending) and\n    /// adjacent intervals must not overlap.\n    interval_set(std::initializer_list<interval_type> list):\n        interval_set(list.begin(), list.end()) {}\n\n    /// \\copydoc interval_set(std::initializer_list<interval_type>)\n    template<typename FwdIterator>\n    interval_set(FwdIterator first, FwdIterator last)\n        : m_intervals(first, last)\n    {\n        assert_invariant();\n    }\n\nprivate:\n    interval_set(storage_type&& vec): m_intervals(std::move(vec)) {}\n\npublic:\n    /// Returns the iterator to the first element.\n    /// The itervals are disjoint and sorted.\n    iterator begin() const { return m_intervals.begin(); }\n\n    /// Returns the past-the-end iterator.\n    iterator end() const { return m_intervals.end(); }\n\n    /// Returns the interval at the given index.\n    /// \\pre `index < size()`.\n    const interval_type& operator[](size_t index) const {\n        geodb_assert(index < size(), \"index out of bounds\");\n        return *(begin() + index);\n    }\n\n    /// Returns true iff `size() == 0`.\n    bool empty() const { return size() == 0; }\n\n    /// Returns the size (the number of intervals) of this set.\n    size_t size() const { return m_intervals.size(); }\n\n    /// Assign a new set of intervals. Reuses existing capacity.\n    template<typename FwdIterator>\n    void assign(FwdIterator first, FwdIterator last) {\n        m_intervals.assign(first, last);\n        assert_invariant();\n    }\n\n    /// Adds a point to this set.\n    ///\n    ///     - If some interval already contains this point, nothing needs to be done.\n    ///     - Otherwise, insert a new point-like interval at the appropriate position.\n    ///\n    /// Runtime complexity: O(size()).\n    ///\n    /// \\post `contains(point)`.\n    /// \\return Returns true iff adding the point caused the set to change, i.e. when\n    ///         the point was not already represented by one of the intervals.\n    bool add(point_type point) {\n        const auto begin = mut_begin();\n        const auto end = mut_end();\n        const auto pos = interval_before(point);\n        geodb_assert(pos == end || point >= pos->begin(), \"\");\n\n        if (pos != end && pos->contains(point)) {\n            // Point already represented.\n            return false;\n        }\n\n        geodb_assert(pos == end || point > pos->end(),\n                     \"point must lie to the right of the found interval\");\n        m_intervals.insert(pos != end ? pos + 1 : begin, interval_type(point));\n\n        geodb_assert(contains(point), \"postcondition violated\");\n        return true;\n    }\n\n    /// Returns true if this set contains the given point.\n    /// Runtime complexity: O(log(size)).\n    bool contains(point_type point) const {\n        const auto pos = interval_before(point);\n        if (pos == end()) {\n            return false;\n        }\n\n        geodb_assert(pos->begin() <= point, \"interval to the left\");\n        return pos->contains(point);\n    }\n\n    /// Trims this set to fit the new size.\n    /// Excess intervals will be merged.\n    /// \\pre `size > 0`.\n    /// \\post `this->size() <= size`.\n    void trim(size_t size) {\n        detail::merge_intervals(m_intervals, size);\n        geodb_assert(m_intervals.size() <= size, \"postcondition failure.\");\n    }\n\n    /// Resets this instance.\n    void clear() {\n        m_intervals.clear();\n    }\n\n    /// Returns the union of \\p *this and \\p other.\n    interval_set union_with(const interval_set& other) const {\n        std::array<const interval_set*, 2> args{this, &other};\n        return interval_set::set_union(args | boost::adaptors::indirected);\n    }\n\n    /// Returns the intersection of \\p *this and \\p other.\n    interval_set intersection_with(const interval_set& other) const {\n        std::array<const interval_set*, 2> args{this, &other};\n        return interval_set::set_intersection(args | boost::adaptors::indirected);\n    }\n\nprivate:\n    using mut_iter = typename storage_type::iterator;\n\n    // mutable iterators not exposed to users.\n    mut_iter mut_begin() { return m_intervals.begin(); }\n    mut_iter mut_end() { return m_intervals.end(); }\n\n    /// Finds the last interval i thats begin before `point`,\n    /// i.e. i.begin() <= point.\n    mut_iter interval_before(point_type point) {\n        const auto compare = [](point_type p, const interval_type& i) {\n            return p < i.begin();\n        };\n\n        // pos is the first interval with i.begin() > point.\n        const auto pos = std::upper_bound(mut_begin(), mut_end(), point, compare);\n        if (pos != begin()) {\n            // The predecessor is the interval we're looking for.\n            return pos - 1;\n        }\n        // There is no such interval.\n        return mut_end();\n    }\n\n    /// \\copydoc interval_before()\n    iterator interval_before(point_type point) const {\n        return static_cast<iterator>(\n                    const_cast<interval_set*>(this)->interval_before(point));\n    }\n\n    /// Iterate over the intervals, but merge adjacent intervals\n    /// that do not have a gap between them (for cleaner display functionality).\n    template<typename Func>\n    void adjacent_merged(Func&& f) const {\n        for (auto i = begin(), e = end(); i != e; ) {\n            interval_type c = *i;\n            while (++i != e && i->begin() == c.end() + 1) {\n                c = interval_type(c.begin(), i->end());\n            }\n            f(c);\n        }\n    }\n\n    friend std::ostream& operator<<(std::ostream& o, const interval_set& set) {\n        o << \"{\";\n        set.adjacent_merged([&](const interval_type& i) {\n            o << i;\n        });\n        o << \"}\";\n        return o;\n    }\n\n    void assert_invariant() {\n#ifdef GEODB_DEBUG\n        if (empty()) {\n            return;\n        }\n\n        auto last = m_intervals.end();\n        auto iter = m_intervals.begin();\n        auto prev = iter++;\n        for (; iter != last; ++iter, ++prev) {\n            geodb_assert(!iter->overlaps(*prev), \"Intervals must not overlap\");\n            geodb_assert(iter->begin() >= prev->end(), \"intervals must be sorted\");\n        }\n#endif\n    }\n\n    template<typename Dest>\n    friend void serialize(Dest& dst, const interval_set& set) {\n        using tpie::serialize;\n        serialize(dst, set.m_intervals);\n    }\n\n    template<typename Src>\n    friend void unserialize(Src& src, interval_set& set) {\n        using tpie::unserialize;\n        unserialize(src, set.m_intervals);\n        set.assert_invariant();\n    }\n\nprivate:\n    storage_type m_intervals;\n};\n\n/// A variant of \\ref interval_set that automatically enforces a capacity.\n/// The number of elements within a `static_interval_set` will always be\n/// lesser than or equal to `Capacity`.\n/// Intervals are merged as neccessary in order to keep this invariant.\ntemplate<typename T, size_t Capacity>\nclass static_interval_set {\n    using inner_t = interval_set<T>;\n\n    static_assert(Capacity > 0, \"Capacity must not be zero\");\n\npublic:\n    using iterator = typename inner_t::iterator;\n    using const_iterator = typename inner_t::const_iterator;\n\n    using point_type = typename inner_t::point_type;\n    using interval_type = typename inner_t::interval_type;\n\npublic:\n    template<typename Range>\n    static static_interval_set set_union(Range&& r) {\n        inner_t set = inner_t::set_union(std::forward<Range>(r));\n        return static_interval_set(std::move(set));\n    }\n\n    template<typename Range>\n    static static_interval_set set_intersection(Range&& r) {\n        inner_t set = inner_t::set_intersection(std::forward<Range>(r));\n        return static_interval_set(std::move(set));\n    }\n\n    static constexpr size_t capacity() { return Capacity; }\n\npublic:\n    static_interval_set() {}\n\n    static_interval_set(std::initializer_list<interval_type> list)\n        : inner(list)\n    {\n        trim();\n    }\n\n    template<typename FwdIter>\n    static_interval_set(FwdIter begin, FwdIter end)\n        : inner(begin, end)\n    {\n        trim();\n    }\n\n    explicit static_interval_set(interval_set<T> set)\n        : inner(std::move(set))\n    {\n        trim();\n    }\n\n    iterator begin() const { return inner.begin(); }\n    iterator end() const { return inner.end(); }\n\n    /// \\copydoc interval_set<T>::operator[]\n    const interval_type& operator[](size_t index) const { return inner[index]; }\n\n    /// \\copydoc interval_set<T>::empty\n    bool empty() const { return inner.empty(); }\n\n    /// \\copydoc interval_set<T>::size\n    size_t size() const { return inner.size(); }\n\n    /// Assign a new set of intervals, merging them if neccessary.\n    template<typename FwdIter>\n    void assign(FwdIter first, FwdIter last) {\n        inner.assign(first, last);\n        trim();\n    }\n\n    /// Adds the point to the set, merging intervals if the set becomes full.\n    ///\n    /// \\sa interval_set::add\n    bool add(point_type point) {\n        bool changed = inner.add(point);\n        trim();\n        return changed;\n    }\n\n    /// \\copydoc interval_set<T>::trim\n    bool contains(point_type point) const { return inner.contains(point); }\n\n    /// \\copydoc interval_set<T>::trim\n    void trim(size_t size) { inner.trim(size); }\n\n    /// Equivalent to `trim(capacity())`.\n    void trim() { trim(capacity()); }\n\n    /// \\copydoc interval_set<T>::clear\n    void clear() { inner.clear(); }\n\n    /// Returns the union of `*this` and `other`, adjusted for capacity.\n    static_interval_set union_with(const static_interval_set& other) const {\n        return static_interval_set(inner.union_with(other.inner));\n    }\n\n    /// Returns the intersection of `*this` and `other`, adjusted for capacity.\n    static_interval_set intersection_with(const static_interval_set& other) const {\n        return static_interval_set(inner.intersection_with(other.inner));\n    }\n\n    /// Returns a const view to the dynamic interval data.\n    operator const interval_set<T>& () const { return inner; }\n\nprivate:\n    friend std::ostream& operator<<(std::ostream& o, const static_interval_set& set) {\n        return o << set.inner;\n    }\n\n    template<typename Dest>\n    friend void serialize(Dest& dst, const static_interval_set& set) {\n        using tpie::serialize;\n        serialize(dst, set.inner);\n    }\n\n    template<typename Src>\n    friend void unserialize(Src& src, static_interval_set& set) {\n        using tpie::unserialize;\n        unserialize(src, set.inner);\n    }\n\nprivate:\n    inner_t inner;\n};\n\n} // namespace geodb\n\n#endif // GEODB_INTERVAL_SET_HPP\n", "meta": {"hexsha": "8b7d3dd2bee39db41717d873c5480e41f6b820cb", "size": 22448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/geodb/interval_set.hpp", "max_stars_repo_name": "mbeckem/msc", "max_stars_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_stars_repo_licenses": ["MIT"], "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/geodb/interval_set.hpp", "max_issues_repo_name": "mbeckem/msc", "max_issues_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_issues_repo_licenses": ["MIT"], "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/geodb/interval_set.hpp", "max_forks_repo_name": "mbeckem/msc", "max_forks_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_forks_repo_licenses": ["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.6419753086, "max_line_length": 106, "alphanum_fraction": 0.6106111903, "num_tokens": 4917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.02262920262840714, "lm_q1q2_score": 0.007259930223869195}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <initializer_list>\n\n#include <ROOT/RDataFrame.hxx>\n#include <TCanvas.h>\n#include <TRatioPlot.h>\n#include <yaml-cpp/yaml.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n\n#include <FileInPath.h>\n#include <Options.h>\n#include <Utils.h>\nusing namespace ROOT;\nnamespace po = boost::program_options;\n\nvoid drawHist(RDF::RNode df_ll, RDF::RNode df_photon, TString obs, RDF::TH1DModel model){\n  auto h_ll = (TH1F*) df_ll.Histo1D(model, obs).GetValue().Clone();\n  auto h_photon = (TH1F*) df_photon.Histo1D(model, obs, \"pt_weight\").GetValue().Clone();\n  auto c1 = new TCanvas(\"c1\",\"c1\",1200,1200);\n  c1->SetLogy();\n  h_ll->SetLineColor(kBlue+1);\n  h_photon->SetLineColor(kRed);\n  h_ll->Draw();\n  h_photon->Draw(\"Same\");\n  auto rp_inc = new TRatioPlot(h_ll, h_photon);\n  c1->SetTicks(0,1);\n  rp_inc->Draw();\n  rp_inc->GetLowerRefYaxis()->SetTitle(\"ratio\");\n  rp_inc->GetLowerRefGraph()->SetMinimum(0);\n  rp_inc->GetLowerRefGraph()->SetMaximum(3);\n  c1->Print(\"mc_closure_\" + obs + \".png\");\n}\n\nTH1F * GetWeightHisto(TH1F * h_ll, TH1F * h_gamma,  TString obs) {\n\n  h_ll->Scale(1/h_ll->Integral());\n  h_gamma->Scale(1/h_gamma->Integral());\n  auto h_weight = (TH1F*) h_ll->Clone();\n  h_weight->Divide(h_gamma);\n  h_weight->SetName(obs + \"_weight\");\n  h_weight->SetTitle(obs + \"_weight\");\n  if (obs.EqualTo(\"nvtx\")){\n  auto h_nvtx_weight_smooth = utils::SmoothenHisto(h_weight);\n  return h_nvtx_weight_smooth;\n  }\n  else\n    return h_weight;\n}\n\nfloat applyWeight(TH1F * h_weight, float boson_eta) {\n    //auto h_weight = (TH1F*) gROOT->Get(\"eta_weight\");\n    auto const bin = h_weight->FindFixBin(boson_eta);\n    return h_weight->GetBinContent(bin);\n    //std::cout << h_weight->GetBinContent(bin) <<std::endl;\n}\n\nRDF::RNode applyCutsCommon(RDF::RNode df){\n  std::function<bool(int)> nGoodJet = [](int ngood_jets) { return ngood_jets >= 2; };\n  std::function<bool(int)> nGoodbJet = [](int ngood_bjets) { return ngood_bjets == 0; };\n  std::function<bool(int)> nTaus = [](int ntau) { return ntau == 0; };\n  std::function<bool(float)> zpt = [](float Z_pt) { return Z_pt > 55.; };\n  std::function<bool(float)> met = [](float met) { return met < 60.; };\n  std::function<bool(float)> delta_phi_j_met = [](float delta_phi_j_met) { return abs(delta_phi_j_met) > 0.5; };\n  std::function<bool(float)> delta_phi_ZMet_bst = [](float delta_phi_ZMet_bst) { return abs(delta_phi_ZMet_bst) > 1.0; };\n  std::function<bool(float)> Jet_etas_multiplied = [](float Jet_etas_multiplied) { return Jet_etas_multiplied < 0.; };\n  std::function<bool(float)> dijet_Mjj = [](float dijet_Mjj) { return dijet_Mjj > 400.; };\n  std::function<bool(float)> dijet_abs_dEta = [](float dijet_abs_dEta) { return dijet_abs_dEta > 2.4; };\n  auto tmp = df.\n                     Filter(nGoodJet, {\"ngood_jets\"}, \"2-jets\").\n                     Filter(nGoodbJet, {\"ngood_bjets\"}, \"bveto\").\n                     Filter(nTaus, {\"nhad_taus\"}, \"tau-veto\").\n                     Filter(delta_phi_j_met, {\"delta_phi_j_met\"}, \"delta_phi_j_met\").\n                     //Filter(delta_phi_ZMet_bst, {\"delta_phi_ZMet_bst\"}).\n                     Filter(Jet_etas_multiplied, {\"Jet_etas_multiplied\"}, \"opposite_jet_eta\").\n                     Filter(dijet_Mjj, {\"dijet_Mjj\"}, \"dijet_Mjj<400\").\n                     Filter(dijet_abs_dEta, {\"dijet_abs_dEta\"}, \"dijet_abs_eta<2.4\").\n                     Filter(zpt, {\"Z_pt\"}, \"boson_pt>55\");\n  return tmp;\n}\n\nRDF::RNode applyCutsLL(RDF::RNode df){\n  std::function<bool(int)> lep_cat = [](int lep_category) { return lep_category == 1 || lep_category == 3; };\n  std::function<bool(float)> deltaR_ll = [](float delta_R_ll) { return delta_R_ll < 2.5; };\n  auto tmp = df.Filter(lep_cat, {\"lep_category\"}).\n                Filter(deltaR_ll, {\"delta_R_ll\"});\n  return tmp;\n}\n\nRDF::RNode applyCutsMET(RDF::RNode df){\n  std::function<bool(float)> met = [](float met) { return met < 60.; };\n  auto tmp = df.Filter(met, {\"met_pt\"}, \"MET<60\");\n  return tmp;\n}\n\nRDF::RNode applyCutsPhoton(RDF::RNode df){\n  std::function<bool(float)> boson_eta = [](float Z_eta) { return abs(Z_eta) < 2.4; };\n  std::function<bool(int)> nextra_leptons = [](int nextra_leptons) { return nextra_leptons == 0; };\n  std::function<bool(int)> ngood_leptons = [](int ngood_leptons) { return ngood_leptons == 0; };\n  std::function<bool(int)> nextra_photons = [](int nloose_photons) { return nloose_photons == 1; };\n\n  auto tmp = df.\n             Filter(nextra_leptons,{\"nextra_leptons\"}, \"No_nextra_leptons\").\n             Filter(ngood_leptons,{\"ngood_leptons\"}, \"No_good_leptons\").\n             //Filter(nextra_photons,{\"nloose_photons\"}, \"No_extra_photons\").\n             Filter(boson_eta, {\"Z_eta\"});\n  return tmp;\n}\n\nint main(int argc, char **argv){\n\n  Options options(argc, argv);\n  YAML::Node const config = options.GetConfig();\n  std::string tree = Options::NodeAs<std::string>(config, {\"tree_name\"});\n // std::string dilepton_filename = Options::NodeAs<std::string>(config, {\"dilepton_files\"});\n  std::vector<std::string> dilepton_filenames = Options::GetStrings(config, {\"dilepton_files\"});\n  std::vector<std::string> photon_filenames = Options::GetStrings(config, {\"photon_files\"});\n  //std::string photon_filename = Options::NodeAs<std::string>(config, {\"photon_files\"});\n  bool isMC = Options::NodeAs<bool>(config, {\"isMC\"});\n  std::vector<std::string> dilepton_files;\n  std::vector<std::string> photon_files;\n  for (auto &dilepton_filename : dilepton_filenames)\n    FileInPath::GetFilenames(FileInPath::Resolve(dilepton_filename), dilepton_files);\n  for (auto &photon_filename : photon_filenames)\n    FileInPath::GetFilenames(FileInPath::Resolve(photon_filename), photon_files);\n  //std::string photonPath = FileInPath::Resolve(photon_filename);\n  RDataFrame::ColumnNames_t varibles = {\"nJet\",\"Muon_pt\" \"Jet_pt_nom\", \n      \"lead_jet_pt\", \"lead_jet_phi\", \"trail_jet_pt\", \"trail_jet_eta\",\n      \"trail_jet_phi\", \"lep_category\", \"ngood_jets\", \"ngood_bjets\",\n      \"nhad_taus\", \"met_pt\", \"met_phi\", \"delta_R_ll\", \"delta_phi_j_met\",\n      \"Jet_etas_multiplied\", \"dijet_Mjj\", \"dijet_abs_dEta\", \n      \"Z_pt\", \"Z_eta\", \"Z_phi\", \"Z_mass\",\n      \"nPhoton\", \"nMuon\", \"nElectron\", \"Pileup_nPU\",\n      \"ngood_leptons\", \"nextra_leptons\",\n      \"deltaPhiClosestJetMet\", \"deltaPhiFarthestJetMet\",\n      //\"delta_phi_ZMet_bst\",\n      \"nloose_photons\",\n       \"delta_phi_ZMet\"};\n  RDataFrame::ColumnNames_t storeBranches = {\"boson_pt\", \"boson_eta\", \"Pileup_nPU\", \"met_pt\"};\n  if (isMC) {\n    //varibles.insert(0, RDataFrame::ColumnNames_t{\"weight\"});\n    for (auto &br : RDataFrame::ColumnNames_t{\"weight\", \"puWeight\", \"w_muon_SF\", \"w_electron_SF\",\n        \"PrefireWeight\", \"nvtxWeight\", \"TriggerSFWeight\", \"btagEventWeight\", \"Jet_partonFlavour\",\n        \"Jet_qgl\"})\n      varibles.push_back(br);\n  }\n  // enabling Multi-Thread\n  ROOT::EnableImplicitMT();\n  // data-frame initializing\n  RDataFrame df_dilepton(tree, dilepton_files, varibles);\n  RDataFrame df_photon(tree, photon_files, varibles);\n  // apply common selections\n  auto df_ll_filtered_tmp = applyCutsCommon(df_dilepton);\n  auto df_gamma_filtered_tmp = applyCutsCommon(df_photon);\n  // apply dilepton & photon selections separately\n  auto df_ll_filtered_noMET = applyCutsLL(df_ll_filtered_tmp);\n  auto df_gamma_filtered_noMET = applyCutsPhoton(df_gamma_filtered_tmp);\n  // apply MET cut, (we will need the ones without MET cut to draw control plots)\n  auto df_ll_filtered = applyCutsMET(df_ll_filtered_noMET);\n  auto df_gamma_filtered = applyCutsMET(df_gamma_filtered_noMET);\n\n  auto df_ll_aug = df_ll_filtered.\n                  Define(\"boson_pt\", \"Z_pt\").\n                  Define(\"boson_eta\", \"abs(Z_eta)\").\n                  Define(\"nvtx\", \"Pileup_nPU\").\n                  Define(\"ptmiss\", \"met_pt\").\n                  Define(\"corr\", \"weight\");\n\n  auto df_gamma_aug = df_gamma_filtered.\n                  Define(\"boson_pt\", \"Z_pt\").\n                  Define(\"boson_eta\", \"abs(Z_eta)\").\n                  Define(\"nvtx\", \"Pileup_nPU\").\n                  Define(\"ptmiss\", \"met_pt\").\n                  Define(\"corr\", \"weight\");\n  // fill histograms in binning of nvtx and abseta\n  auto h_nvtx_ll = (TH1F*)df_ll_aug.Histo1D({\"nvtx_ll\",\"nvtx_ll\",100,0,100},\"nvtx\", \"corr\").GetValue().Clone();\n  auto h_nvtx_gamma = (TH1F*)df_gamma_aug.Histo1D({\"nvtx_gamma\",\"nvtx_gamma\",100,0,100},\"nvtx\", \"corr\").GetValue().Clone();\n  auto h_eta_ll = (TH1F*)df_ll_aug.Histo1D({\"eta_ll\",\"eta_ll\",24,0,2.4},\"boson_eta\", \"corr\").GetValue().Clone();\n  auto h_eta_gamma = (TH1F*)df_gamma_aug.Histo1D({\"eta_gamma\",\"eta_gamma\",24,0,2.4},\"boson_eta\", \"corr\").GetValue().Clone();\n  auto h_nvtx_weight = GetWeightHisto(h_nvtx_ll, h_nvtx_gamma, \"nvtx\");\n  auto h_eta_weight = GetWeightHisto(h_eta_ll, h_eta_gamma, \"eta\");\n  // define a lambda function for applying weights in the Data-Frame\n  auto applyEtaWeight = [] (float boson_eta) {\n    TH1F * h_weight = (TH1F *)gROOT->Get(\"eta_weight\");\n    auto const bin = h_weight->FindFixBin(boson_eta);\n    return h_weight->GetBinContent(bin);\n  };\n  auto df_gamma_eta_weighted_tmp = df_gamma_aug.Define(\"eta_weight\", applyEtaWeight, {\"boson_eta\"});\n  auto df_gamma_eta_weighted = df_gamma_eta_weighted_tmp.Define(\"corr_eta\", \"corr * eta_weight\");\n  const float  binning[] = {55,75,100,150,200,250,1500};\n  RDF::TH1DModel pt_model(\"pt_ll\",\"pt_ll\",6, binning);\n  RDF::TH1DModel pt_model_gamma(\"pt_gamma\",\"pt_gamma\",6, binning);\n  auto h_pt_ll = (TH1F*)df_ll_aug.Histo1D(pt_model,\"boson_pt\", \"corr\").GetValue().Clone();\n  auto h_pt_gamma = (TH1F*)df_gamma_eta_weighted.Histo1D(pt_model_gamma,\"boson_pt\", \"corr_eta\").GetValue().Clone();\n  auto h_pt_weight = GetWeightHisto(h_pt_ll, h_pt_gamma, \"pt\");\n  \n  // define a lambda function for applying weights in the Data-Frame\n  auto applyPtWeight = [] (float boson_pt) {\n    TH1F * h_weight = (TH1F *)gROOT->Get(\"pt_weight\");\n    auto const bin = h_weight->FindFixBin(boson_pt);\n    return h_weight->GetBinContent(bin);\n  };\n  auto df_gamma_eta_pt_weighted = df_gamma_eta_weighted.Define(\"pt_weight\", applyPtWeight, {\"boson_pt\"});\n  auto df_photon_weighted = df_gamma_filtered_noMET.Define(\"pt_weight\", applyPtWeight, {\"Z_pt\"});\n  std::cout << \"All stats:\" << std::endl;\n  auto allCutsReport = df_gamma_filtered.Report();\n  std::cout << \"Name\\tAll\\tPass\\tEfficiency\" << std::endl;\n   for (auto &&cutInfo : allCutsReport) {\n      std::cout << cutInfo.GetName() << \"\\t\" << cutInfo.GetAll() << \"\\t\" << cutInfo.GetPass() << \"\\t\"\n                << cutInfo.GetEff() << \" %\" << std::endl;\n   }\n  const float  met_binning[] = {0,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,160,170,180,190,200,250,300,350,400,450,500,600,900,1500};\n  RDF::TH1DModel met_model(\"\",\"\",sizeof(met_binning)/sizeof(float) - 1, met_binning);\n  drawHist(df_ll_filtered_noMET, df_photon_weighted, \"met_pt\", met_model);\n\n  RDataFrame::ColumnNames_t toBeStored_ll = { \"met_pt\",\n                                          }; \n  RDataFrame::ColumnNames_t toBeStored_photon = toBeStored_ll;\n  toBeStored_photon.push_back(\"pt_weight\");\n   \n  df_photon_weighted.Snapshot(\"Events\",\"photon.root\", toBeStored_photon);\n  df_ll_filtered_noMET.Snapshot(\"Events\",\"ll.root\", toBeStored_ll);\n  auto f1 = new TFile(\"weights.root\", \"RECREATE\");\n  h_nvtx_weight->Write();\n  h_eta_weight->Write();\n  h_pt_weight->Write();\n  h_pt_gamma->Write();\n  h_pt_ll->Write();\n  f1->Close();\n  return 0;\n}\n\n", "meta": {"hexsha": "03a3f21aa379552a5f2a27dc983dc70486b61c31", "size": 11418, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/analyzer.cc", "max_stars_repo_name": "Allen319/photonCR", "max_stars_repo_head_hexsha": "354fabe2ea910d1fd80588d6e6d2b89645c302c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analyzer.cc", "max_issues_repo_name": "Allen319/photonCR", "max_issues_repo_head_hexsha": "354fabe2ea910d1fd80588d6e6d2b89645c302c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analyzer.cc", "max_forks_repo_name": "Allen319/photonCR", "max_forks_repo_head_hexsha": "354fabe2ea910d1fd80588d6e6d2b89645c302c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5872340426, "max_line_length": 163, "alphanum_fraction": 0.6732352426, "num_tokens": 3438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052844289766, "lm_q2_score": 0.020964241200430604, "lm_q1q2_score": 0.007234870422312273}}
{"text": "/*! \\file Peridigm_Material.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//@HEADER\n\n#include \"Peridigm_Material.hpp\"\n#include \"Peridigm_Field.hpp\"\n#include <Teuchos_Assert.hpp>\n#include <Epetra_SerialComm.h>\n//#include \"material_utilities.h\"\n#include <boost/math/special_functions/fpclassify.hpp>\n\nusing namespace std;\n\nvoid PeridigmNS::Material::computeJacobian(const double dt,\n                                           const int numOwnedPoints,\n                                           const int* ownedIDs,\n                                           const int* neighborhoodList,\n                                           PeridigmNS::DataManager& dataManager,\n                                           PeridigmNS::SerialMatrix& jacobian,\n                                           PeridigmNS::Material::JacobianType jacobianType) const\n{\n  // Compute a finite-difference Jacobian using either FORWARD_DIFFERENCE or CENTRAL_DIFFERENCE\n  computeFiniteDifferenceJacobian(dt, numOwnedPoints, ownedIDs, neighborhoodList, dataManager, jacobian, CENTRAL_DIFFERENCE, jacobianType);\n}\n\nvoid PeridigmNS::Material::computeFiniteDifferenceJacobian(const double dt,\n                                                           const int numOwnedPoints,\n                                                           const int* ownedIDs,\n                                                           const int* neighborhoodList,\n                                                           PeridigmNS::DataManager& dataManager,\n                                                           PeridigmNS::SerialMatrix& jacobian,\n                                                           FiniteDifferenceScheme finiteDifferenceScheme,\n                                                           PeridigmNS::Material::JacobianType jacobianType) const\n{\n  // The Jacobian is of the form:\n  //\n  // dF_0x/dx_0  dF_0x/dy_0  dF_0x/dz_0  dF_0x/dx_1  dF_0x/dy_1  dF_0x/dz_1  ...  dF_0x/dx_n  dF_0x/dy_n  dF_0x/dz_n  \n  // dF_0y/dx_0  dF_0y/dy_0  dF_0y/dz_0  dF_0y/dx_1  dF_0y/dy_1  dF_0y/dz_1  ...  dF_0y/dx_n  dF_0y/dy_n  dF_0y/dz_n  \n  // dF_0z/dx_0  dF_0z/dy_0  dF_0z/dz_0  dF_0z/dx_1  dF_0z/dy_1  dF_0z/dz_1  ...  dF_0z/dx_n  dF_0z/dy_n  dF_0z/dz_n  \n  // dF_1x/dx_0  dF_1x/dy_0  dF_1x/dz_0  dF_1x/dx_1  dF_1x/dy_1  dF_1x/dz_1  ...  dF_1x/dx_n  dF_1x/dy_n  dF_1x/dz_n  \n  // dF_1y/dx_0  dF_1y/dy_0  dF_1y/dz_0  dF_1y/dx_1  dF_1y/dy_1  dF_1y/dz_1  ...  dF_1y/dx_n  dF_1y/dy_n  dF_1y/dz_n  \n  // dF_1z/dx_0  dF_1z/dy_0  dF_1z/dz_0  dF_1z/dx_1  dF_1z/dy_1  dF_1z/dz_1  ...  dF_1z/dx_n  dF_1z/dy_n  dF_1z/dz_n  \n  //     .           .           .           .           .           .                .           .           .\n  //     .           .           .           .           .           .                .           .           .\n  //     .           .           .           .           .           .                .           .           .\n  // dF_nx/dx_0  dF_nx/dy_0  dF_nx/dz_0  dF_nx/dx_1  dF_nx/dy_1  dF_nx/dz_1  ...  dF_nx/dx_n  dF_nx/dy_n  dF_nx/dz_n  \n  // dF_ny/dx_0  dF_ny/dy_0  dF_ny/dz_0  dF_ny/dx_1  dF_ny/dy_1  dF_ny/dz_1  ...  dF_ny/dx_n  dF_ny/dy_n  dF_ny/dz_n  \n  // dF_nz/dx_0  dF_nz/dy_0  dF_nz/dz_0  dF_nz/dx_1  dF_nz/dy_1  dF_nz/dz_1  ...  dF_nz/dx_n  dF_nz/dy_n  dF_nz/dz_n  \n\n  // Each entry is computed by finite difference:\n  //\n  // Forward difference:\n  // dF_0x/dx_0 = ( F_0x(perturbed x_0) - F_0x(unperturbed) ) / epsilon\n  //\n  // Central difference:\n  // dF_0x/dx_0 = ( F_0x(positive perturbed x_0) - F_0x(negative perturbed x_0) ) / ( 2.0*epsilon )\n\n  TEUCHOS_TEST_FOR_EXCEPT_MSG(m_finiteDifferenceProbeLength == DBL_MAX, \"**** Finite-difference Jacobian requires that the \\\"Finite Difference Probe Length\\\" parameter be set.\\n\");\n  double epsilon = m_finiteDifferenceProbeLength;\n\n  // Get field ids for all relevant data\n  PeridigmNS::FieldManager& fieldManager = PeridigmNS::FieldManager::self();\n  int volumeFId = fieldManager.getFieldId(\"Volume\");\n  int coordinatesFId = fieldManager.getFieldId(\"Coordinates\");\n  int velocityFId = fieldManager.getFieldId(\"Velocity\");\n  int forceDensityFId = fieldManager.getFieldId(\"Force_Density\");\n\n  // Loop over all points.\n  int neighborhoodListIndex = 0;\n  for(int iID=0 ; iID<numOwnedPoints ; ++iID){\n\n    // Create a temporary neighborhood consisting of a single point and its neighbors.\n    int numNeighbors = neighborhoodList[neighborhoodListIndex++];\n    vector<int> tempMyGlobalIDs(numNeighbors+1);\n    // Put the node at the center of the neighborhood at the beginning of the list.\n    tempMyGlobalIDs[0] = dataManager.getOwnedScalarPointMap()->GID(iID);\n    vector<int> tempNeighborhoodList(numNeighbors+1); \n    tempNeighborhoodList[0] = numNeighbors;\n    for(int iNID=0 ; iNID<numNeighbors ; ++iNID){\n      int neighborID = neighborhoodList[neighborhoodListIndex++];\n      tempMyGlobalIDs[iNID+1] = dataManager.getOverlapScalarPointMap()->GID(neighborID);\n      tempNeighborhoodList[iNID+1] = iNID+1;\n    }\n\n    Epetra_SerialComm serialComm;\n    Teuchos::RCP<Epetra_BlockMap> tempOneDimensionalMap = Teuchos::rcp(new Epetra_BlockMap(numNeighbors+1, numNeighbors+1, &tempMyGlobalIDs[0], 1, 0, serialComm));\n    Teuchos::RCP<Epetra_BlockMap> tempThreeDimensionalMap = Teuchos::rcp(new Epetra_BlockMap(numNeighbors+1, numNeighbors+1, &tempMyGlobalIDs[0], 3, 0, serialComm));\n    Teuchos::RCP<Epetra_BlockMap> tempBondMap = Teuchos::rcp(new Epetra_BlockMap(1, 1, &tempMyGlobalIDs[0], numNeighbors, 0, serialComm));\n\n    // Create a temporary DataManager containing data for this point and its neighborhood.\n    PeridigmNS::DataManager tempDataManager;\n    tempDataManager.setMaps(Teuchos::RCP<const Epetra_BlockMap>(),\n                            tempOneDimensionalMap,\n                            Teuchos::RCP<const Epetra_BlockMap>(),\n                            tempThreeDimensionalMap,\n                            tempBondMap);\n\n    // The temporary data manager will have the same fields and data as the real data manager.\n    vector<int> fieldIds = dataManager.getFieldIds();\n    tempDataManager.allocateData(fieldIds);\n    tempDataManager.copyLocallyOwnedDataFromDataManager(dataManager);\n\n    // Set up numOwnedPoints and ownedIDs.\n    // There is only one owned ID, and it has local ID zero in the tempDataManager.\n    int tempNumOwnedPoints = 1;\n    vector<int> tempOwnedIDs(1);\n    tempOwnedIDs[0] = 0;\n\n    // Extract pointers to the underlying data in the constitutiveData array.\n    double *volume, *y, *v, *force;\n    tempDataManager.getData(volumeFId, PeridigmField::STEP_NONE)->ExtractView(&volume);\n    tempDataManager.getData(coordinatesFId, PeridigmField::STEP_NP1)->ExtractView(&y);\n    tempDataManager.getData(velocityFId, PeridigmField::STEP_NP1)->ExtractView(&v);\n    tempDataManager.getData(forceDensityFId, PeridigmField::STEP_NP1)->ExtractView(&force);\n\n    // Create a temporary vector for storing force\n    Teuchos::RCP<Epetra_Vector> forceVector = tempDataManager.getData(forceDensityFId, PeridigmField::STEP_NP1);\n    Teuchos::RCP<Epetra_Vector> tempForceVector = Teuchos::rcp(new Epetra_Vector(*forceVector));\n    double* tempForce;\n    tempForceVector->ExtractView(&tempForce);\n\n    // Use the scratchMatrix as sub-matrix for storing tangent values prior to loading them into the global tangent matrix.\n    // Resize scratchMatrix if necessary\n    if(scratchMatrix.Dimension() < 3*(numNeighbors+1))\n      scratchMatrix.Resize(3*(numNeighbors+1));\n\n    // Create a list of global indices for the rows/columns in the scratch matrix.\n    vector<int> globalIndices(3*(numNeighbors+1));\n    for(int i=0 ; i<numNeighbors+1 ; ++i){\n      int globalID = tempOneDimensionalMap->GID(i);\n      for(int j=0 ; j<3 ; ++j)\n        globalIndices[3*i+j] = 3*globalID+j;\n    }\n\n    if(finiteDifferenceScheme == FORWARD_DIFFERENCE){\n      // Compute and store the unperturbed force.\n      computeForce(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n      for(int i=0 ; i<forceVector->MyLength() ; ++i)\n        tempForce[i] = force[i];\n    }\n\n    // Perturb one dof in the neighborhood at a time and compute the force.\n    // The point itself plus each of its neighbors must be perturbed.\n    for(int iNID=0 ; iNID<numNeighbors+1 ; ++iNID){\n\n      int perturbID;\n      if(iNID < numNeighbors)\n        perturbID = tempNeighborhoodList[iNID+1];\n      else\n        perturbID = 0;\n\n      for(int dof=0 ; dof<3 ; ++dof){\n\n        // Perturb a dof and compute the forces.\n        double oldY = y[3*perturbID+dof];\n        double oldV = v[3*perturbID+dof];\n\n        if(finiteDifferenceScheme == CENTRAL_DIFFERENCE){\n          // Compute and store the negatively perturbed force.\n          y[3*perturbID+dof] -= epsilon;\n          v[3*perturbID+dof] -= epsilon/dt;\n          computeForce(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n          y[3*perturbID+dof] = oldY;\n          v[3*perturbID+dof] = oldV;\n          for(int i=0 ; i<forceVector->MyLength() ; ++i)\n            tempForce[i] = force[i];\n        }\n\n\n        // Compute the purturbed force\n        y[3*perturbID+dof] += epsilon;\n        v[3*perturbID+dof] += epsilon/dt;\n        computeForce(dt, tempNumOwnedPoints, &tempOwnedIDs[0], &tempNeighborhoodList[0], tempDataManager);\n        y[3*perturbID+dof] = oldY;\n        v[3*perturbID+dof] = oldV;\n\n        for(int i=0 ; i<numNeighbors+1 ; ++i){\n          int forceID;\n          if(i < numNeighbors)\n            forceID = tempNeighborhoodList[i+1];\n          else\n            forceID = 0;\n\n          for(int d=0 ; d<3 ; ++d){\n            double value = ( force[3*forceID+d] - tempForce[3*forceID+d] ) / epsilon;\n            if(finiteDifferenceScheme == CENTRAL_DIFFERENCE)\n              value *= 0.5;\n            scratchMatrix(3*forceID+d, 3*perturbID+dof) = value;\n          }\n        }\n      }\n    }\n\n    // Convert force density to force\n    // \\todo Create utility function for this in ScratchMatrix\n    for(unsigned int row=0 ; row<globalIndices.size() ; ++row){\n      for(unsigned int col=0 ; col<globalIndices.size() ; ++col){\n        scratchMatrix(row, col) *= volume[row/3];\n      }\n    }\n\n    // Check for NaNs\n    for(unsigned int row=0 ; row<globalIndices.size() ; ++row){\n      for(unsigned int col=0 ; col<globalIndices.size() ; ++col){\n        TEUCHOS_TEST_FOR_EXCEPT_MSG(!boost::math::isfinite(scratchMatrix(row, col)), \"**** NaN detected in finite-difference Jacobian.\\n\");\n      }\n    }\n\n    // Sum the values into the global tangent matrix (this is expensive).\n    if (jacobianType == PeridigmNS::Material::FULL_MATRIX)\n      jacobian.addValues((int)globalIndices.size(), &globalIndices[0], scratchMatrix.Data());\n    else if (jacobianType == PeridigmNS::Material::BLOCK_DIAGONAL) {\n      jacobian.addBlockDiagonalValues((int)globalIndices.size(), &globalIndices[0], scratchMatrix.Data());\n    }\n    else // unknown jacobian type\n      TEUCHOS_TEST_FOR_EXCEPT_MSG(true, \"**** Unknown Jacobian Type\\n\");\n  }\n}\n\ndouble PeridigmNS::Material::calculateBulkModulus(const Teuchos::ParameterList & params) const\n{\n  bool bulkModulusDefined(false), shearModulusDefined(false), youngsModulusDefined(false), poissonsRatioDefined(false);\n  double bulkModulus(0.0), shearModulus(0.0), youngsModulus(0.0), poissonsRatio(0.0);\n  double computedValue;\n\n  if( params.isParameter(\"Bulk Modulus\") ){\n    bulkModulusDefined = true;\n    bulkModulus = params.get<double>(\"Bulk Modulus\");\n  }\n  if( params.isParameter(\"Shear Modulus\") ){\n    shearModulus = params.get<double>(\"Shear Modulus\");\n    shearModulusDefined = true;\n  }\n  if( params.isParameter(\"Young's Modulus\") ){\n    youngsModulus = params.get<double>(\"Young's Modulus\");\n    youngsModulusDefined = true;\n  }\n  if( params.isParameter(\"Poisson's Ratio\") ){\n    poissonsRatio = params.get<double>(\"Poisson's Ratio\");\n    poissonsRatioDefined = true;\n  }\n\n  int numDefinedConstants = static_cast<int>(bulkModulusDefined) + \n    static_cast<int>(shearModulusDefined) + \n    static_cast<int>(youngsModulusDefined) + \n    static_cast<int>(poissonsRatioDefined);\n\n  TEUCHOS_TEST_FOR_EXCEPT_MSG(numDefinedConstants != 2, \"**** Error:  Exactly two elastic constants must be provided.  Allowable constants are \\\"Bulk Modulus\\\", \\\"Shear Modulus\\\", \\\"Young's Modulus\\\", \\\"Poisson's Ratio\\\".\\n\");\n\n  if(bulkModulusDefined)\n    computedValue = bulkModulus;\n  else if(youngsModulusDefined && shearModulusDefined)\n    computedValue = (youngsModulus * shearModulus) / (3.0*(3.0*shearModulus - youngsModulus));\n  else if(youngsModulusDefined && poissonsRatioDefined)\n    computedValue = youngsModulus / (3.0*(1.0 - 2.0*poissonsRatio));\n  else if(shearModulusDefined && poissonsRatioDefined)\n    computedValue = (2.0*shearModulus*(1.0 + poissonsRatio)) / (3.0*(1.0 - 2.0*poissonsRatio));\n  else\n    TEUCHOS_TEST_FOR_EXCEPT_MSG(true, \"**** Error:  Exactly two elastic constants must be provided.  Allowable constants are \\\"Bulk Modulus\\\", \\\"Shear Modulus\\\", \\\"Young's Modulus\\\", \\\"Poisson's Ratio\\\".\\n\");\n\n  return computedValue;\n}\n\n\ndouble PeridigmNS::Material::calculateShearModulus(const Teuchos::ParameterList & params) const\n{\n  bool bulkModulusDefined(false), shearModulusDefined(false), youngsModulusDefined(false), poissonsRatioDefined(false);\n  double bulkModulus(0.0), shearModulus(0.0), youngsModulus(0.0), poissonsRatio(0.0);\n  double computedValue;\n\n  if( params.isParameter(\"Bulk Modulus\") ){\n    bulkModulusDefined = true;\n    bulkModulus = params.get<double>(\"Bulk Modulus\");\n  }\n  if( params.isParameter(\"Shear Modulus\") ){\n    shearModulus = params.get<double>(\"Shear Modulus\");\n    shearModulusDefined = true;\n  }\n  if( params.isParameter(\"Young's Modulus\") ){\n    youngsModulus = params.get<double>(\"Young's Modulus\");\n    youngsModulusDefined = true;\n  }\n  if( params.isParameter(\"Poisson's Ratio\") ){\n    poissonsRatio = params.get<double>(\"Poisson's Ratio\");\n    poissonsRatioDefined = true;\n  }\n\n  int numDefinedConstants = static_cast<int>(bulkModulusDefined) + \n    static_cast<int>(shearModulusDefined) + \n    static_cast<int>(youngsModulusDefined) + \n    static_cast<int>(poissonsRatioDefined);\n\n  TEUCHOS_TEST_FOR_EXCEPT_MSG(numDefinedConstants != 2, \"**** Error:  Exactly two elastic constants must be provided.  Allowable constants are \\\"Bulk Modulus\\\", \\\"Shear Modulus\\\", \\\"Young's Modulus\\\", \\\"Poisson's Ratio\\\".\\n\");\n\n  if(shearModulusDefined)\n    computedValue = shearModulus;\n  else if(bulkModulusDefined && youngsModulusDefined)\n    computedValue = (3.0*bulkModulus*youngsModulus) / (9.0*bulkModulus - youngsModulus);\n  else if(bulkModulusDefined & poissonsRatioDefined)\n    computedValue = (3.0*bulkModulus*(1.0 - 2.0*poissonsRatio)) / (2.0*(1.0 + poissonsRatio));\n  else if(youngsModulusDefined && poissonsRatioDefined)\n    computedValue = youngsModulus / (2.0*(1.0 + poissonsRatio));\n  else\n    TEUCHOS_TEST_FOR_EXCEPT_MSG(true, \"**** Error:  Exactly two elastic constants must be provided.  Allowable constants are \\\"Bulk Modulus\\\", \\\"Shear Modulus\\\", \\\"Young's Modulus\\\", \\\"Poisson's Ratio\\\".\\n\");\n\n  return computedValue;\n}\n\n\nvoid\nPeridigmNS::Material::computeDilatation(\n        const int numOwnedPoints,\n        const int* ownedIDs,\n        const int* neighborhoodList,\n        const double BM,\n        const double SM,\n        PeridigmNS::DataManager& dataManager) const {\n            \n          \n    //////////////////////////////////////////////////////////////////////////////////////    \n    // Routine developed for Peridigm by DLR.\n    // Dilatation has to be updated before the damage routine. Therefore, this routine has been added\n    // to the model evaluator. The dilatation is needed to calculate the energy at both bonds (12 and 21) \n    // for the correct time step, prior to the calculation of the internal forces. The bonds with critical\n    // energy are deleted and the internal loads calculation will be done.\n    //////////////////////////////////////////////////////////////////////////////////////    \n    // Questions?\n    // Christian Willberg  christian.willberg@dlr.de\n    // Martin Raedel       martin.raedel@dlr.de\n    //////////////////////////////////////////////////////////////////////////////////////   \n     \n    PeridigmNS::FieldManager& fieldManager = PeridigmNS::FieldManager::self();\n    //double m_horizon = params.get<double>(\"Horizon\");\n    //////////////////////////////////////////////////////////////////////////////////////\n    // ALL IDS will be initialized in the material routine \"Peridigm_ElasticMaterial.cpp\"\n    // carefull if changed from Peridigm_ElasticMaterial.cpp to something else\n    //////////////////////////////////////////////////////////////////////////////////////    \n    \n    int m_modelCoordinatesFieldId = fieldManager.getFieldId(PeridigmField::NODE, PeridigmField::VECTOR, PeridigmField::CONSTANT, \"Model_Coordinates\");\n    int m_coordinatesFieldId = fieldManager.getFieldId(PeridigmField::NODE, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Coordinates\");\n    int m_volumeFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Volume\");\n    int m_weightedVolumeFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Weighted_Volume\");\n    int m_dilatationFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Dilatation\");\n\tint m_bondDamageFieldId = fieldManager.getFieldId(PeridigmField::BOND, PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Bond_Damage\");\n    int m_horizonFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Horizon\");\n    int m_damageModelFieldId = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Damage_Model_Data\");\n   \n    ///////////////////////////////////////////////////////////////////////////////\n    PeridigmNS::InfluenceFunction::functionPointer OMEGA;\n    OMEGA = PeridigmNS::InfluenceFunction::self().getInfluenceFunction();\n    double *x, *y, *bondDamage, *horizon;\n    double *Volume, *weightedVolume, *damageModel, *theta;\n    ///////////////////////////////////////////////////////////////////////////////\n    dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n    dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume);\n    dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&Volume);\n\tdataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);   \n    dataManager.getData(m_dilatationFieldId, PeridigmField::STEP_NP1)->ExtractView(&theta);\n\tdataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n    \n    dataManager.getData(m_damageModelFieldId, PeridigmField::STEP_NP1)->ExtractView(&damageModel);\n\n    \n\t*(dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)) = *(dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_N));\n    dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n    double m_alpha = 0.0; // to be adapted for temperature\n    double *deltaTemperature = NULL; \n\tconst double *xOwned = x;\n\tconst double *yOwned = y;\n\tconst double *deltaT = deltaTemperature;\n\tconst double *m = weightedVolume;\n\tconst double *v = Volume;\n\tdouble cellVolume;\n\t\n\tconst int *neighPtr = neighborhoodList;\n\t\n\t\n\tfor(int p=0; p<numOwnedPoints;p++, xOwned+=3, yOwned+=3, horizon++, deltaT++, m++, theta++){\n\t\tint numNeigh = *neighPtr; neighPtr++;\n\t\tconst double *X = xOwned;\n\t\tconst double *Y = yOwned;\n\t\t*theta = 0.0;\n\t\tfor(int n=0;n<numNeigh;n++,neighPtr++,bondDamage++){\n\t\t\tint localId = *neighPtr;\n\t\t\tcellVolume = v[localId];\n\t\t\tconst double *XP = &x[3*localId];\n\t\t\tconst double *YP = &y[3*localId];\n\t\t\tdouble X_dx = XP[0]-X[0];\n\t\t\tdouble X_dy = XP[1]-X[1];\n\t\t\tdouble X_dz = XP[2]-X[2];\n\t\t\tdouble zetaSquared = X_dx*X_dx+X_dy*X_dy+X_dz*X_dz;\n\t\t\tdouble Y_dx = YP[0]-Y[0];\n\t\t\tdouble Y_dy = YP[1]-Y[1];\n\t\t\tdouble Y_dz = YP[2]-Y[2];\n\t\t\tdouble dY = Y_dx*Y_dx+Y_dy*Y_dy+Y_dz*Y_dz;\n\t\t\tdouble d = sqrt(zetaSquared);\n\t\t\tdouble e = sqrt(dY);\n\t\t\te -= d;\n\t\t\t//if(deltaTemperature)\n\t\t\t//  e -= thermalExpansionCoefficient*(*deltaT)*d;\n\t\t\tdouble omega = OMEGA(d,*horizon);\n\t\t\t*theta += 3.0*omega*(1.0-*bondDamage)*d*e*cellVolume/(*m);\n\t\t}\n        // variable is needed to determine the accurate energy in the energy based damage criterion\n\t\tdamageModel[3*p] = *theta;\n\t\tdamageModel[3*p+1] = BM / (*m);\n\t\tdamageModel[3*p+2] = SM / (*m) ;\n\t\t*theta = 0.0;\n\n\t}\n}\t\t\n\n", "meta": {"hexsha": "d90345ddf12e7a6e4f964f466567c956cf433353", "size": 22631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Peridigm/Code/Energy_damage_criterion/src/materials/Peridigm_Material.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/materials/Peridigm_Material.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/materials/Peridigm_Material.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": 49.6293859649, "max_line_length": 226, "alphanum_fraction": 0.6541911537, "num_tokens": 6273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.022286186553878713, "lm_q1q2_score": 0.007225970298008038}}
{"text": "/// \\file   price_setter.cpp\n///\n/// \\brief\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2018-07-19\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#include <esl/economics/markets/walras/price_setter.hpp>\n\n#include <algorithm>\n#include <type_traits>\n#include <map>\nusing std::map;\n\n#include <esl/economics/markets/walras/quote_message.hpp>\n#include <esl/economics/markets/walras/tatonnement.hpp>\nusing esl::law::property;\n\n#include <esl/economics/finance/securities_lending_contract.hpp>\n\n\n\ntemplate <class... T>\nstruct always_false\n: std::false_type\n{\n\n};\n\ntemplate <> struct always_false<>\n: std::true_type\n{\n\n};\n\nnamespace esl::economics::markets::walras {\n    price_setter::price_setter()\n    : price_setter(identity<price_setter>())\n    {\n\n    }\n\n    ///\n    /// \\brief\n    ///\n    /// \\details    Initialises the differentiable variable context to 1.0 times\n    ///             the initial quotes. In essence, the\n    ///             solver starts at 1.0 times the initial quote\n    /// \\param i\n    /// \\param traded_assets\n    price_setter::price_setter(const identity<price_setter> &i,\n                               law::property_map<quote> traded_properties)\n\n    : agent(i)\n    , market(i, traded_properties)\n    , state(sending_quotes)\n    {\n        output_clearing_prices_ =\n            create_output<std::vector<price>>(\"clearing_prices\");\n\n        this->register_callback<walras::differentiable_order_message>(\n            [this](auto msg, simulation::time_interval ti,\n                   std::seed_seq &seed) {\n                (void)msg;\n                (void)seed;\n                return ti.upper;\n            });\n    }\n\n    simulation::time_point\n    price_setter::act(simulation::time_interval step, std::seed_seq &seed)\n    {\n        (void)seed;\n        simulation::time_point next_ = step.upper;\n        std::vector<quote> quotes_;\n\n\n        if(state == sending_quotes) {\n            // send out initial quotes and wait for orders,\n            // scheduled in the same time step\n            next_ = step.lower;\n            for(const auto &[k, v] : traded_properties) {\n                (void)k;\n                quotes_.push_back(v);\n            }\n        }else{\n            std::unordered_map< identity<agent>,\n                                std::shared_ptr<walras::differentiable_order_message>>\n                orders_;\n            for(const auto &[k, message_]: inbox) {\n                (void)k;\n                if(walras::differentiable_order_message::code == message_->type) {\n                    auto order_ = std::dynamic_pointer_cast<\n                        walras::differentiable_order_message>(message_);\n\n\n                    if(message_->sent < step.lower){\n                        next_ = step.lower;\n                        break;\n                    }\n\n                    orders_.insert({order_->sender, order_});\n\n\n                }\n            }\n\n            if(!orders_.empty()) {\n                // there is at least one order so we clear the market\n                auto scalars_ = clear_market(orders_, step);\n                std::vector<price> prices_;\n                for(auto &[k, v]: traded_properties){\n                    (void)v;\n                    //auto price_ =\n                    //    cash(currencies::USD).value(scalars_[k->identifier]);\n                    //traded_properties.insert(\n                    //    std::make_pair(k, quote(price_)));  // overwrite\n                    prices_.emplace_back(std::get<price>(v.type));\n                    quotes_.emplace_back(quote(v));\n                }\n                //output_clearing_prices_->put(step.lower, prices_);\n                latest = step.lower;\n            } else { // restore previous prices\n                for(const auto &[k, v]: traded_properties) {\n                    (void)k;\n                    quotes_.push_back(v);\n                }\n            }\n        }\n\n        law::property_map<quote> quote_map_;\n        {\n            size_t sequence_ = 0;\n            for(const auto &[k, v] : traded_properties) {\n                quote_map_.insert({k, quotes_[sequence_]});\n                ++sequence_;\n            }\n        }\n\n        for(const auto &p : participants) {\n            auto m = this->template create_message<walras::quote_message>(\n                p, step.lower + 1, this->identifier, p, quote_map_);\n        }\n        state = clearing_market;\n\n        return next_;\n    }\n\n    ///\n    /// \\brief  Clear market using tatonnement. It is assumed the price_setter\n    ///         has received at least one excess demand function for each\n    ///         property from market participants, otherwise\n    ///         it will return the previous price for the property with no\n    ///         excess demand curve.\n    ///\n    ///\n    std::map<identity<law::property>, double> price_setter::clear_market(const std::unordered_map<identity<agent>, std::shared_ptr<walras::differentiable_order_message>> &orders, const simulation::time_interval &step)\n    {\n        law::property_map<quote> old_quotes_ = this->traded_properties;\n\n        std::map<identity<law::property>, quote> quotes_;\n        for(const auto &[k, v] : traded_properties) {\n            (void)k;\n            quotes_.emplace(k->identifier, v);\n        }\n\n        tatonnement::excess_demand_model model_(quotes_);\n        for(auto [key, function_] : orders) {\n            (void)key;\n            model_.excess_demand_functions_.push_back(function_);\n        }\n        auto result1_ = model_.do_compute();\n\n        // if finding a price failed, return previous price vector\n        if(!result1_.has_value()) {\n            std::map<identity<law::property>, double> previous_;\n            for(const auto &[k, v] : traded_properties) {\n                (void)k;\n                previous_.insert({k->identifier, 1.0 * double(v)});\n            }\n            return previous_;\n        }\n\n        auto result_ = result1_.value();\n\n\n\n        ////////////////////////////////////////////////////////////////////////\n        // round to the nearest valid price\n        std::map<identity<law::property>, std::tuple<quote, double>> solution_;\n        for(auto [p, q] : this->traded_properties) {\n            double scalar_ = result_.find(p->identifier)->second;\n            std::tuple<quote, double> part_ = std::make_tuple(q, scalar_);\n            solution_.emplace(p->identifier, part_);\n\n            std::visit([this, result_, p = p](auto &quote) {\n                    using type_ = std::decay_t<decltype(quote)>;\n                    if constexpr(std::is_same_v<type_, price>) {\n                        std::get<price>(traded_properties[p].type).value =\n                            int64_t(\n                                quote.value\n                                * result_.find(p->identifier)->second);\n\n                    }else if constexpr(std::is_same_v<type_, exchange_rate>) {\n                        quote =\n                            exchange_rate(uint64_t(\n                                quote.numerator()\n                                * result_.find(p->identifier)->second), quote.denominator());\n                        traded_properties[p].type = quote;\n                    }else{\n                         static_assert(always_false<type_>::value,\n                                       \"non-exhaustive handling of quotes\");\n                    }\n                }, q.type);\n        }\n\n\n        ////////////////////////////////////////////////////////////////////////\n        // recompute demand for solution\n        ////////////////////////////////////////////////////////////////////////\n        map<identity<property>, double> volumes_;\n        map<identity<property>, map<identity<agent>, std::tuple<double, quantity, quantity> >> orders_;\n        for(const auto &[participant, order_]: orders) {\n            auto demand_ = order_->excess_demand_m(solution_);\n            for(const auto &[k, v]: demand_) {\n                if(v == 0) {\n                    continue;\n                }\n                auto i = volumes_.find(k);\n                if(volumes_.end() == i) {\n                    i = volumes_.emplace(k, 0).first;\n                    orders_.emplace(k, map<identity<agent>, std::tuple<double, quantity, quantity>>());\n                }\n                i->second += abs(v);\n\n                auto j = order_->supply.find(k);\n                if(order_->supply.end() == j){\n                    orders_.find(k)->second.emplace(participant,\n                                                    std::make_tuple(v\n                                                            ,quantity(0,1)\n                                                            , quantity(0,1)));\n                }else{\n                    orders_.find(k)->second.emplace(participant,\n                                                    std::make_tuple(v\n                                                            ,std::get<0>(j->second)\n                                                            , std::get<1>(j->second)));\n                }\n            }\n        }\n\n\n        ////////////////////////////////////////////////////////////////////////\n        // compute transfers in terms of the primary property\n        map<identity<property>, map<identity<agent>, int64_t>> transfers_;\n        for(const auto &[property_, data_]: traded_properties){\n            auto i = volumes_.find(property_->identifier);\n            if(volumes_.end() == i){\n                continue;   // no agents expressed interest\n            }\n            int64_t accumulator_ = 0;\n            std::vector<std::tuple<identity<agent>, int64_t>> allocations_;\n            for(auto [p,a]: orders_.find(property_->identifier)->second){\n                auto alloc_ = int64_t(std::get<0>(a));// / i->second);\n                accumulator_ += alloc_;\n                allocations_.push_back(std::make_tuple(p, alloc_ ));\n            }\n            std::sort(allocations_.begin(), allocations_.end(),\n                      [](const auto &a, const auto &b) -> bool\n                      {\n                          return std::abs(std::get<1>(a))\n                                 < std::abs(std::get<1>(b));\n                      });\n            //\n             int64_t error_ = accumulator_;\n            if(error_ < 0){ // assigned too many\n\n                if(allocations_.size() < -error_){\n                    LOG(notice) << \"clearing price beyond rounding error\" << std::endl;\n                }\n\n                for(size_t ii = 0; ii < uint64_t(-error_); ++ii){\n                    std::get<1>(allocations_[ii%allocations_.size()]) += 1;\n                }\n            }else{\n                //assert(allocations_.size() >= uint64_t(error_));\n                if(allocations_.size() < uint64_t(error_)){\n                    LOG(notice) << \"clearing price beyond rounding error\" << std::endl;\n                }\n\n                for(size_t ii = 0; ii < uint64_t(error_); ++ii){\n                    std::get<1>(allocations_[ii%allocations_.size()]) -= 1;\n                }\n            }\n            auto pair_ = transfers_.emplace(property_->identifier, map<identity<agent>, int64_t>());\n\n            for(auto [p,a]: allocations_) {\n                 pair_.first->second.emplace(p, a);\n            }\n        }\n        LOG(trace) << transfers_ << std::endl;\n\n        //\n        //  send_: we, the market maker, send items to participant\n        //  receive_: we, the market maker, receive items from participant\n        //\n        map<identity<agent>,  accounting::inventory_filter<law::property> > send_, receive_;\n\n        auto usd_ = std::make_shared<cash>(currencies::USD);\n\n\n        for(const auto &[property_, data_]: traded_properties) {\n            for(auto &[p, v]: transfers_.find(*property_)->second){\n                if(v == 0){\n                    continue;\n                }\n\n                auto i = orders.find(p)->second->supply.find(*property_);\n                if(orders.find(p)->second->supply.end() == i){\n                    continue;\n                }\n                uint64_t &long_amount_ = std::get<0>(i->second).amount;\n                uint64_t &short_amount_ = std::get<1>(i->second).amount;\n\n                if(v > 0){ // send properties to this agent, or receive shorts\n                    if(long_amount_ > 0){ // they had long pos\n                        //  purchase\n                        accounting::inventory_filter<law::property> purchased_;\n                        purchased_.insert(property_, quantity(uint64_t(v), 1));\n                        send_.emplace(p, purchased_);\n                        //  payment\n                        // they should send cash for the purchase\n                        auto j = receive_.find(p);\n                        if(receive_.end() == j){\n                            auto [jj, succes_] = receive_.emplace(p, accounting::inventory_filter<law::property>());\n                            j = jj;\n                        }\n                        auto q__ = usd_->amount(v * double(std::get<price>(data_.type)) / data_.lot);\n                        j->second.insert(usd_, q__);\n                    }else if(short_amount_ > 0){// there was a short position\n                        if(uint64_t(v) >= short_amount_){// cancel all\n                            // 1 cancel short, by transferring shorts back to market agent\n                            // cancel the short, by receiving their short contracts\n                            std::map<identity<property>, esl::quantity> basket_;\n                            basket_.emplace(property_->identifier, quantity(1,1));\n                            auto short_contract_ = std::make_shared<finance::securities_lending_contract>(identifier, p, basket_);\n                            auto r = receive_.find(p);\n                            if(receive_.end() == r){\n                                auto [rr, b_] = receive_.emplace(p, accounting::inventory_filter<law::property>());\n                                r = rr;\n                            }\n                            r->second.insert(short_contract_, quantity(short_amount_,1));\n                            // we pay back the collateral amount\n                            auto s = send_.find(p);\n                            if(send_.end() == s){\n                                auto [ss, success_] = send_.emplace(p, accounting::inventory_filter<law::property>());\n                                s = ss;\n                            }\n\n                            auto o = old_quotes_.find(property_);\n                            auto collateral_ =\n                                usd_->amount((short_amount_ * double(std::get<price>(o->second.type))) / o->second.lot);\n                            s->second.insert(usd_, collateral_);\n\n                            ////////////////////////////////////////////////////\n                            //\n\n                            v -=  short_amount_;\n\n                            if(v > 0){\n                                // this is all copy pasted from above\n                                accounting::inventory_filter<law::property> purchased_;\n                                purchased_.insert(property_, quantity(uint64_t(v), 1));\n                                send_.emplace(p, purchased_);\n\n                                ////////////////////////////////////////////////////////\n                                //  payment\n                                // they should send cash for the purchase\n                                auto j = receive_.find(p);\n                                if(receive_.end() == j){\n                                    auto [jj, succes_] = receive_.emplace(p, accounting::inventory_filter<law::property>());\n                                    j=jj;\n                                }\n                                j->second.insert(usd_, usd_->amount(v * double(std::get<price>(data_.type)) / data_.lot));\n                            }\n\n                        }else{// cancel in part\n\n                            auto amount_to_cancel = v;\n\n                            std::map<identity<property>, esl::quantity> basket_;\n                            basket_.emplace(property_->identifier, quantity(1,1));\n                            auto short_contract_ = std::make_shared<finance::securities_lending_contract>(identifier, p, basket_);\n                            auto r = receive_.find(p);\n                            if(receive_.end() == r){\n                                auto [rr, b_] = receive_.emplace(p, accounting::inventory_filter<law::property>());\n                                r=rr;\n                            }\n                            r->second.insert(short_contract_, quantity(amount_to_cancel,1));\n                            // we pay back the collateral amount\n                            auto s = send_.find(p);\n                            if(send_.end() == s){\n                                auto [ss, success_] = send_.emplace(p, accounting::inventory_filter<law::property>());\n                                s=ss;\n                            }\n\n                            auto o = old_quotes_.find(property_);\n                            auto collateral_ =\n                                usd_->amount((amount_to_cancel * double(std::get<price>(o->second.type))) / o->second.lot);\n                            s->second.insert(usd_, collateral_);\n                        }\n                    }\n                }else{ // participant wants to sell/short///////////////////////////////////////////////////////////////////////////\n                    if(long_amount_ > 0 || short_amount_ == 0) {  // they had long pos/had nothing\n\n                        if(-v >= long_amount_){// cancel all\n                            // 1 cancel long, by transferring stocks back to market agent\n                            auto r = receive_.find(p);\n                            if(receive_.end() == r){\n                                auto [rr, b_] = receive_.emplace(p, accounting::inventory_filter<law::property>());\n                                r = rr;\n                            }\n                            r->second.insert(property_, quantity(long_amount_,1));\n\n                            auto s = send_.find(p);\n                            if(send_.end() == s){\n                                auto [ss, success_] = send_.emplace(p, accounting::inventory_filter<law::property>());\n                                s = ss;\n                            }\n                            auto proceeds_ =\n                                usd_->amount((long_amount_ * double(std::get<price>(data_.type))) / data_.lot);\n                            s->second.insert(usd_, proceeds_);\n\n\n                            ////////////////////////////////////////////////////\n                            //\n\n                            v +=  long_amount_;\n                            if(v < 0){\n                                std::map<identity<property>, esl::quantity> basket_;\n                                basket_.emplace(property_->identifier, quantity(1,1));\n                                auto short_contract_ = std::make_shared<finance::securities_lending_contract>(identifier, p, basket_);\n\n                                auto j = send_.find(p);\n                                if(send_.end() == j){\n                                    auto [jj, succes_] = send_.emplace(p, accounting::inventory_filter<law::property>());\n                                    j=jj;\n                                }\n\n                                j->second.insert(short_contract_, quantity(uint64_t(-v), 1));\n                                j->second.insert(usd_, usd_->amount(-v * double(std::get<price>(data_.type)) / data_.lot));\n                            }\n\n                        }else{// cancel in part\n\n                            auto amount_to_cancel = -v;\n                            auto r = receive_.find(p);\n                            if(receive_.end() == r){\n                                auto [rr, b_] = receive_.emplace(p, accounting::inventory_filter<law::property>());\n                                r = rr;\n                            }\n                            r->second.insert(property_, quantity(amount_to_cancel,1));\n\n\n                            // we pay back the collateral amount\n                            auto s = send_.find(p);\n                            if(send_.end() == s){\n                                auto [ss, success_] = send_.emplace(p, accounting::inventory_filter<law::property>());\n                                s = ss;\n                            }\n                            auto proceeds_ =\n                                usd_->amount((amount_to_cancel * double(std::get<price>(data_.type))) / data_.lot);\n                            s->second.insert(usd_, proceeds_);\n                        }\n                    }else{\n                        //extend the short position\n                        auto amount_to_extend = -v;\n\n                        std::map<identity<property>, esl::quantity> basket_;\n                        basket_.emplace(property_->identifier, quantity(1,1));\n                        auto short_contract_ = std::make_shared<finance::securities_lending_contract>(identifier, p, basket_);\n                        auto s = send_.find(p);\n                        if(send_.end() == s){\n                            auto [ss, b_] = receive_.emplace(p, accounting::inventory_filter<law::property>());\n                            s=ss;\n                        }\n\n                        auto sale_ =\n                            usd_->amount((amount_to_extend * double(std::get<price>(data_.type))) / data_.lot);\n                        s->second.insert(usd_, sale_);\n                        s->second.insert(short_contract_, quantity(amount_to_extend,1));\n                    }\n                }\n            }\n        }\n\n        for(auto [p,i]: send_){\n            LOG(trace) << \"market sends to \" << p << \" items \" << i << std::endl;\n            this->template create_message<interaction::transfer>( p\n                                                                , step.lower\n                                                                , identifier\n                                                                 , p\n                                                                 , reinterpret_identity_cast<law::owner<law::property>>(identifier)\n                                                                 , reinterpret_identity_cast<law::owner<law::property>>(p)\n                                                                 , i\n                                                                );\n        }\n\n        for(auto [p,i]: receive_){\n            LOG(trace) << \"market receives from \" << p << \" items \" << i << std::endl;\n            this->template create_message<interaction::transfer>( p\n                , step.lower\n                , p\n                , identifier\n                , reinterpret_identity_cast<law::owner<law::property>>(p)\n                , reinterpret_identity_cast<law::owner<law::property>>(identifier)\n                , i\n            );\n        }\n\n        return result_;\n    }\n\n}  // namespace esl::economics::markets::walras\n\n\n#include <boost/serialization/export.hpp>\n\n#include <esl/data/serialization.hpp>\n\n\nBOOST_CLASS_EXPORT(std::vector<esl::economics::price>);\ntypedef std::tuple<esl::simulation::time_point,\n                   std::vector<esl::economics::price>>\n    tuple_time_point_price_vector;\nBOOST_CLASS_EXPORT(tuple_time_point_price_vector);\ntypedef std::vector<\n    std::tuple<esl::simulation::time_point, std::vector<esl::economics::price>>>\n    time_series_price_vector;\nBOOST_CLASS_EXPORT(time_series_price_vector);\nBOOST_CLASS_EXPORT(esl::data::output<std::vector<esl::economics::price>>);", "meta": {"hexsha": "b0830bac961d5da991980165938004c9bccb1dbf", "size": 24740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "esl/economics/markets/walras/price_setter.cpp", "max_stars_repo_name": "fagan2888/ESL", "max_stars_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-17T18:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T18:18:08.000Z", "max_issues_repo_path": "esl/economics/markets/walras/price_setter.cpp", "max_issues_repo_name": "fagan2888/ESL", "max_issues_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/economics/markets/walras/price_setter.cpp", "max_forks_repo_name": "fagan2888/ESL", "max_forks_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "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.4165170557, "max_line_length": 217, "alphanum_fraction": 0.4539207761, "num_tokens": 4660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.018833129718340783, "lm_q1q2_score": 0.007179557277673891}}
{"text": "\n#include \"decaf.h\"\n\n#include <boost/range/combine.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <fmt/format.h>\n#include <llvm/ADT/SmallString.h>\n#include <llvm/IR/Instructions.h>\n#include <llvm/Support/raw_ostream.h>\n\n#include <iostream>\n#include <optional>\n#include <stdexcept>\n\nnamespace decaf {\n/************************************************\n * Executor                                     *\n ************************************************/\nvoid Executor::add_context(Context &&ctx) {\n  contexts.push_back(ctx);\n}\n\nContext Executor::next_context() {\n  DECAF_ASSERT(has_next());\n\n  Context ctx = std::move(contexts.back());\n  contexts.pop_back();\n  return ctx;\n}\n\nbool Executor::has_next() const {\n  return !contexts.empty();\n}\n\n/************************************************\n * StackFrame                                   *\n ************************************************/\nStackFrame::StackFrame(llvm::Function *function)\n    : function(function), current_block(&function->getEntryBlock()), prev_block(nullptr),\n      current(current_block->begin()) {}\n\nvoid StackFrame::jump_to(llvm::BasicBlock *block) {\n  prev_block = current_block;\n  current_block = block;\n  current = block->begin();\n}\n\nvoid StackFrame::insert(llvm::Value *value, const z3::expr &expr) {\n  variables.insert_or_assign(value, expr);\n}\n\nz3::expr StackFrame::lookup(llvm::Value *value, z3::context &ctx) const {\n  if (auto *constant = llvm::dyn_cast_or_null<llvm::Constant>(value))\n    return evaluate_constant(ctx, constant);\n\n  auto it = variables.find(value);\n  DECAF_ASSERT(it != variables.end(), \"Tried to access unknown variable\");\n  return it->second;\n}\n\n/************************************************\n * Context                                      *\n ************************************************/\n\nContext::Context(z3::context &z3, llvm::Function *function)\n    : solver(z3::tactic(z3, \"default\").mk_solver()) {\n  stack.emplace_back(function);\n  StackFrame &frame = stack_top();\n\n  int argnum = 0;\n  for (auto &arg : function->args()) {\n    z3::sort sort = sort_for_type(z3, arg.getType());\n    z3::symbol symbol = z3.int_symbol(argnum);\n\n    frame.variables.insert({&arg, z3.constant(symbol, sort)});\n    argnum += 1;\n  }\n}\nContext::Context(const Context &ctx, z3::solver &&solver)\n    : stack(ctx.stack), solver(std::move(solver)) {}\n\nStackFrame &Context::stack_top() {\n  DECAF_ASSERT(!stack.empty());\n  return stack.back();\n}\n\nz3::check_result Context::check(const z3::expr &expr) {\n  auto cond = normalize_to_bool(expr);\n  DECAF_ASSERT(cond.is_bool());\n  return solver.check(1, &cond);\n}\nz3::check_result Context::check() {\n  return solver.check();\n}\n\nvoid Context::add(const z3::expr &assertion) {\n  DECAF_ASSERT(assertion.is_bool(), \"assertions must be booleans\");\n  solver.add(assertion);\n}\n\nContext Context::fork() const {\n  z3::solver new_solver = z3::tactic(solver.ctx(), \"default\").mk_solver();\n\n  for (const auto &assertion : solver.assertions()) {\n    new_solver.add(assertion);\n  }\n\n  return Context(*this, std::move(new_solver));\n}\n\n/************************************************\n * Interpreter                                  *\n ************************************************/\nInterpreter::Interpreter(Context *ctx, Executor *queue, z3::context *z3, FailureTracker *tracker)\n    : ctx(ctx), queue(queue), z3(z3), tracker(tracker) {}\n\nvoid Interpreter::execute() {\n  ExecutionResult exec;\n\n  do {\n    StackFrame &frame = ctx->stack_top();\n\n    DECAF_ASSERT(frame.current != frame.current_block->end(),\n                 \"Instruction pointer ran off end of block.\");\n\n    llvm::Instruction &inst = *frame.current;\n\n    // Note: Need to increment the iterator before actually doing\n    //       anything with the instruction since instructions can\n    //       modify the current position (e.g. branch, call, etc.)\n    ++frame.current;\n\n    exec = visit(inst);\n  } while (exec == ExecutionResult::Continue);\n}\n\nExecutionResult Interpreter::visitAdd(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, lhs + rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitSub(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, lhs - rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitMul(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, lhs * rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitICmpInst(llvm::ICmpInst &icmp) {\n  using llvm::ICmpInst;\n\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(icmp.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(icmp.getOperand(1), *z3));\n\n  switch (icmp.getPredicate()) {\n  case ICmpInst::ICMP_EQ:\n    frame.insert(&icmp, lhs == rhs);\n    break;\n  case ICmpInst::ICMP_NE:\n    frame.insert(&icmp, lhs != rhs);\n    break;\n  case ICmpInst::ICMP_UGT:\n    frame.insert(&icmp, z3::ugt(lhs, rhs));\n    break;\n  case ICmpInst::ICMP_UGE:\n    frame.insert(&icmp, z3::uge(lhs, rhs));\n    break;\n  case ICmpInst::ICMP_ULT:\n    frame.insert(&icmp, z3::ult(lhs, rhs));\n    break;\n  case ICmpInst::ICMP_ULE:\n    frame.insert(&icmp, z3::ule(lhs, rhs));\n    break;\n  case ICmpInst::ICMP_SGT:\n    frame.insert(&icmp, lhs > rhs);\n    break;\n  case ICmpInst::ICMP_SGE:\n    frame.insert(&icmp, lhs >= rhs);\n    break;\n  case ICmpInst::ICMP_SLT:\n    frame.insert(&icmp, lhs < rhs);\n    break;\n  case ICmpInst::ICMP_SLE:\n    frame.insert(&icmp, lhs <= rhs);\n    break;\n  default:\n    DECAF_UNREACHABLE();\n  }\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitSDiv(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  if (ctx->check(rhs == 0 || !z3::bvsdiv_no_overflow(lhs, rhs)) == z3::sat) {\n    tracker->add_failure(*ctx, ctx->solver.get_model());\n  }\n  ctx->add(rhs != 0);\n  ctx->add(z3::bvsdiv_no_overflow(lhs, rhs));\n\n  frame.insert(&op, lhs / rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitUDiv(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  if (ctx->check(rhs == 0) == z3::sat) {\n    tracker->add_failure(*ctx, ctx->solver.get_model());\n  }\n  ctx->add(rhs != 0);\n\n  frame.insert(&op, z3::udiv(lhs, rhs));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitSRem(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  if (ctx->check(rhs == 0 || !z3::bvsdiv_no_overflow(lhs, rhs)) == z3::sat) {\n    tracker->add_failure(*ctx, ctx->solver.get_model());\n  }\n  ctx->add(rhs != 0);\n  ctx->add(z3::bvsdiv_no_overflow(lhs, rhs));\n\n  frame.insert(&op, lhs % rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitURem(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  if (ctx->check(rhs == 0) == z3::sat) {\n    tracker->add_failure(*ctx, ctx->solver.get_model());\n  }\n  ctx->add(rhs != 0);\n\n  frame.insert(&op, z3::urem(lhs, rhs));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitShl(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, z3::shl(lhs, rhs));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitAShr(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, z3::ashr(lhs, rhs));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitLShr(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, z3::lshr(lhs, rhs));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitAnd(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, lhs & rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitOr(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, lhs | rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitXor(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto lhs = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n  auto rhs = normalize_to_int(frame.lookup(op.getOperand(1), *z3));\n\n  frame.insert(&op, lhs ^ rhs);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitNot(llvm::BinaryOperator &op) {\n  StackFrame &frame = ctx->stack_top();\n\n  auto expr = normalize_to_int(frame.lookup(op.getOperand(0), *z3));\n\n  frame.insert(&op, ~expr);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitTrunc(llvm::TruncInst &trunc) {\n  auto &frame = ctx->stack_top();\n\n  auto src = normalize_to_int(frame.lookup(trunc.getOperand(0), *z3));\n  auto dst_ty = trunc.getDestTy();\n\n  DECAF_ASSERT(dst_ty->isIntegerTy());\n  DECAF_ASSERT(dst_ty->getIntegerBitWidth() <= src.get_sort().bv_size());\n\n  frame.insert(&trunc, src.extract(dst_ty->getIntegerBitWidth() - 1, 0));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitBranchInst(llvm::BranchInst &inst) {\n  if (!inst.isConditional()) {\n    ctx->stack_top().jump_to(inst.getSuccessor(0));\n    return ExecutionResult::Continue;\n  }\n\n  auto &frame = ctx->stack_top();\n  auto cond = normalize_to_bool(frame.lookup(inst.getCondition(), *z3));\n\n  auto is_t = ctx->check(cond);\n  auto is_f = ctx->check(!cond);\n\n  // Note: For the purposes of branching we consider unknown to be\n  //       equivalent to sat. Maybe future branches will bring the\n  //       equation back to being solvable.\n  if (is_t != z3::unsat && is_f != z3::unsat) {\n    auto fork = ctx->fork();\n\n    // In cases where both conditions are possible we follow the\n    // false path. This should be enough to get us out of most loops\n    // and actually exploring the rest of the program.\n    fork.add(cond);\n    ctx->add(!cond);\n\n    fork.stack_top().jump_to(inst.getSuccessor(0));\n    ctx->stack_top().jump_to(inst.getSuccessor(1));\n\n    queue->add_context(std::move(fork));\n    return ExecutionResult::Continue;\n  } else if (is_t != z3::unsat) {\n    ctx->add(cond);\n    ctx->stack_top().jump_to(inst.getSuccessor(0));\n    return ExecutionResult::Continue;\n  } else if (is_f != z3::unsat) {\n    ctx->add(!cond);\n    ctx->stack_top().jump_to(inst.getSuccessor(1));\n    return ExecutionResult::Continue;\n  } else {\n    return ExecutionResult::Stop;\n  }\n}\n\nExecutionResult Interpreter::visitReturnInst(llvm::ReturnInst &inst) {\n  auto &frame = ctx->stack_top();\n\n  std::optional<z3::expr> result;\n  if (inst.getNumOperands() != 0)\n    result = frame.lookup(inst.getOperand(0), *z3);\n\n  ctx->stack.pop_back();\n\n  // Reached end of function, nothing left to do.\n  if (ctx->stack.empty())\n    return ExecutionResult::Stop;\n\n  if (result.has_value()) {\n    auto &parent = ctx->stack_top();\n    auto &caller = *std::prev(parent.current);\n\n    parent.insert(&caller, *result);\n  }\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitPHINode(llvm::PHINode &node) {\n  auto &frame = ctx->stack_top();\n\n  // PHI nodes in the entry block is invalid.\n  DECAF_ASSERT(frame.prev_block != nullptr);\n\n  auto value = frame.lookup(node.getIncomingValueForBlock(frame.prev_block), *z3);\n  frame.insert(&node, value);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitCallInst(llvm::CallInst &call) {\n  auto func = call.getCalledFunction();\n\n  if (func->isIntrinsic()) {\n    DECAF_ABORT(fmt::format(\"Intrinsic function '{}' not supported\", func->getName().str()));\n  }\n\n  DECAF_ASSERT(!call.isIndirectCall(), \"Indirect functions are not implemented yet\");\n\n  if (func->empty())\n    return visitExternFunc(call);\n\n  StackFrame callee{func};\n  auto &frame = ctx->stack_top();\n\n  for (auto arg_pair :\n       boost::combine(boost::make_iterator_range(func->arg_begin(), func->arg_end()),\n                      boost::make_iterator_range(call.arg_begin(), call.arg_end()))) {\n    callee.insert(&boost::get<0>(arg_pair), frame.lookup(boost::get<1>(arg_pair).get(), *z3));\n  }\n\n  ctx->stack.push_back(std::move(callee));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitSelectInst(llvm::SelectInst &inst) {\n  auto &frame = ctx->stack_top();\n\n  auto cond = normalize_to_bool(frame.lookup(inst.getCondition(), *z3));\n  auto t_val = normalize_to_int(frame.lookup(inst.getTrueValue(), *z3));\n  auto f_val = normalize_to_int(frame.lookup(inst.getFalseValue(), *z3));\n\n  frame.insert(&inst, z3::ite(cond, t_val, f_val));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitSExtInst(llvm::SExtInst &sext) {\n  auto &frame = ctx->stack_top();\n\n  auto src = normalize_to_int(frame.lookup(sext.getOperand(0), *z3));\n  auto dst_ty = sext.getDestTy();\n\n  DECAF_ASSERT(dst_ty->isIntegerTy());\n  DECAF_ASSERT(dst_ty->getIntegerBitWidth() > src.get_sort().bv_size());\n\n  auto size_difference = dst_ty->getIntegerBitWidth() - src.get_sort().bv_size();\n  frame.insert(&sext, z3::sext(src, size_difference));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitZExtInst(llvm::ZExtInst &zext) {\n  auto &frame = ctx->stack_top();\n\n  auto src = normalize_to_int(frame.lookup(zext.getOperand(0), *z3));\n  auto dst_ty = zext.getDestTy();\n\n  DECAF_ASSERT(dst_ty->isIntegerTy());\n  DECAF_ASSERT(dst_ty->getIntegerBitWidth() > src.get_sort().bv_size());\n\n  auto size_difference = dst_ty->getIntegerBitWidth() - src.get_sort().bv_size();\n  frame.insert(&zext, z3::zext(src, size_difference));\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitExternFunc(llvm::CallInst &call) {\n  auto func = call.getCalledFunction();\n  auto name = func->getName();\n\n  DECAF_ASSERT(func->empty(), \"visitExternFunc called with non-external function\");\n\n  if (name == \"decaf_assert\")\n    return visitAssert(call);\n  if (name == \"decaf_assume\")\n    return visitAssume(call);\n\n  DECAF_ABORT(fmt::format(\"external function '{}' not implemented\", name.str()));\n}\n\nExecutionResult Interpreter::visitAssume(llvm::CallInst &call) {\n  DECAF_ASSERT(call.getNumArgOperands() == 1);\n\n  auto &frame = ctx->stack_top();\n  ctx->add(normalize_to_bool(frame.lookup(call.getArgOperand(0), *z3)));\n\n  // Don't check whether adding the assumption causes this path to become\n  // dead since assumptions are rare, solver calls are expensive, and it'll\n  // get caught at the next conditional branch anyway.\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitAssert(llvm::CallInst &call) {\n  DECAF_ASSERT(call.getNumArgOperands() == 1);\n\n  auto &frame = ctx->stack_top();\n  auto assertion = normalize_to_bool(frame.lookup(call.getArgOperand(0), *z3));\n\n  DECAF_ASSERT(assertion.is_bool(),\n               fmt::format(\"Called decaf_assert with invalid type, found: {}, expected bool\",\n                           assertion.get_sort().to_string()));\n\n  if (ctx->check(!assertion) == z3::sat) {\n    tracker->add_failure(*ctx, ctx->solver.get_model());\n  }\n  ctx->add(assertion);\n\n  return ExecutionResult::Continue;\n}\n\nExecutionResult Interpreter::visitInstruction(llvm::Instruction &inst) {\n  DECAF_ABORT(fmt::format(\"Instruction '{}' not implemented!\", inst.getOpcodeName()));\n}\n\n/************************************************\n * PrintingFailureTracker                       *\n ************************************************/\nvoid PrintingFailureTracker::add_failure(Context &, const z3::model &model) {\n  std::cout << \"Found failed model! Inputs: \\n\" << model << std::endl;\n}\n\nFailureTracker *PrintingFailureTracker::default_instance() {\n  static PrintingFailureTracker instance;\n\n  return &instance;\n}\n\n/************************************************\n * Free Functions                               *\n ************************************************/\nz3::sort sort_for_type(z3::context &ctx, llvm::Type *type) {\n  if (type->isIntegerTy()) {\n    return ctx.bv_sort(type->getIntegerBitWidth());\n  }\n\n  std::string message;\n  llvm::raw_string_ostream os{message};\n  os << \"Unsupported LLVM type: \";\n  type->print(os);\n\n  DECAF_ABORT(message);\n}\n\nvoid execute_symbolic(llvm::Function *function, FailureTracker *tracker) {\n  z3::config cfg;\n\n  // We want Z3 to generate models\n  cfg.set(\"model\", true);\n  // Automatically select and configure the solver\n  cfg.set(\"auto_config\", true);\n\n  z3::context z3{cfg};\n  Executor exec;\n\n  exec.add_context(Context(z3, function));\n\n  while (exec.has_next()) {\n    Context ctx = exec.next_context();\n    Interpreter interp{&ctx, &exec, &z3, tracker};\n\n    interp.execute();\n  }\n}\n\nz3::expr evaluate_constant(z3::context &ctx, llvm::Constant *constant) {\n  if (auto *intconst = llvm::dyn_cast<llvm::ConstantInt>(constant)) {\n    const llvm::APInt &value = intconst->getValue();\n\n    if (value.getBitWidth() <= 64) {\n      return ctx.bv_val(value.getLimitedValue(), value.getBitWidth());\n    }\n\n    // This isn't particularly efficient. Unfortunately, when it comes\n    // to integers larger than uint64_t there's no efficient way to get\n    // them into Z3. The options are either\n    //  - Convert to base-10 string and use that\n    //  - Put every single bit into a separate boolean then load that\n    // I've opted to go the string route since it's easier here. Maybe\n    // in the future we can get an API for doing this more efficiently\n    // added to Z3.\n    llvm::SmallString<64> str;\n    value.toStringUnsigned(str, 10);\n\n    return ctx.bv_val(str.c_str(), value.getBitWidth());\n  }\n\n  // We only implement integers at the moment\n  DECAF_UNIMPLEMENTED();\n}\n\nz3::expr normalize_to_bool(const z3::expr &expr) {\n  auto sort = expr.get_sort();\n\n  if (sort.is_bv() && sort.bv_size() == 1)\n    return expr == 1;\n\n  return expr;\n}\n\nz3::expr normalize_to_int(const z3::expr &expr) {\n  auto sort = expr.get_sort();\n\n  if (sort.is_bool()) {\n    auto &ctx = expr.ctx();\n    return z3::ite(expr, ctx.bv_val(1, 1), ctx.bv_val(0, 1));\n  }\n\n  return expr;\n}\n} // namespace decaf\n", "meta": {"hexsha": "64e0709aae165679c61b849aa77d0050aa654520", "size": 19507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/decaf.cpp", "max_stars_repo_name": "mishazharov/decaf", "max_stars_repo_head_hexsha": "b4f568bbdd3d56f021f421685b2262c586d84a7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/decaf.cpp", "max_issues_repo_name": "mishazharov/decaf", "max_issues_repo_head_hexsha": "b4f568bbdd3d56f021f421685b2262c586d84a7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-10-02T20:36:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-28T16:34:03.000Z", "max_forks_repo_path": "src/decaf.cpp", "max_forks_repo_name": "mishazharov/decaf", "max_forks_repo_head_hexsha": "b4f568bbdd3d56f021f421685b2262c586d84a7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-02T21:41:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T23:07:53.000Z", "avg_line_length": 29.5113464448, "max_line_length": 97, "alphanum_fraction": 0.6620187625, "num_tokens": 5003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.023330770378873742, "lm_q1q2_score": 0.007170899611637757}}
{"text": "// Copyright (C) 2007-2011 Anders Logg and Garth N. Wells\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// Modified by Kristian Oelgaard, 2008\n// Modified by Martin Sandve Alnes, 2008\n// Modified by Johan Hake, 2009\n//\n// First added:  2007-04-10\n// Last changed: 2011-09-19\n\n#include <map>\n#include <utility>\n#include <boost/assign/list_of.hpp>\n\n#include <dolfin/common/constants.h>\n#include <dolfin/common/Array.h>\n#include <dolfin/common/NoDeleter.h>\n#include <dolfin/function/GenericFunction.h>\n#include <dolfin/function/FunctionSpace.h>\n#include <dolfin/function/Constant.h>\n#include <dolfin/log/log.h>\n#include <dolfin/mesh/Mesh.h>\n#include <dolfin/mesh/MeshData.h>\n#include <dolfin/mesh/MeshDomains.h>\n#include <dolfin/mesh/MeshFunction.h>\n#include <dolfin/mesh/MeshValueCollection.h>\n#include <dolfin/mesh/Vertex.h>\n#include <dolfin/mesh/Cell.h>\n#include <dolfin/mesh/Facet.h>\n#include <dolfin/mesh/Point.h>\n#include <dolfin/mesh/SubDomain.h>\n#include <dolfin/la/GenericMatrix.h>\n#include <dolfin/la/GenericVector.h>\n#include <dolfin/la/LinearAlgebraFactory.h>\n#include \"GenericDofMap.h\"\n#include \"FiniteElement.h\"\n#include \"UFCMesh.h\"\n#include \"UFCCell.h\"\n#include \"DirichletBC.h\"\n\nusing namespace dolfin;\n\nconst std::set<std::string> DirichletBC::methods\n            = boost::assign::list_of(\"topological\")(\"geometric\")(\"pointwise\");\n\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(const FunctionSpace& V, const GenericFunction& g,\n                         const SubDomain& sub_domain, std::string method)\n  : BoundaryCondition(V),\n    Hierarchical<DirichletBC>(*this),\n    g(reference_to_no_delete_pointer(g)),\n    _method(method), _user_sub_domain(reference_to_no_delete_pointer(sub_domain))\n{\n  check();\n  parameters = default_parameters();\n  init_from_sub_domain(_user_sub_domain);\n}\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(boost::shared_ptr<const FunctionSpace> V,\n                         boost::shared_ptr<const GenericFunction> g,\n                         boost::shared_ptr<const SubDomain> sub_domain,\n                         std::string method)\n  : BoundaryCondition(V),\n    Hierarchical<DirichletBC>(*this),\n    g(g), _method(method), _user_sub_domain(sub_domain)\n{\n  check();\n  parameters = default_parameters();\n  init_from_sub_domain(_user_sub_domain);\n}\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(const FunctionSpace& V, const GenericFunction& g,\n                         const MeshFunction<uint>& sub_domains,\n                         uint sub_domain, std::string method)\n  : BoundaryCondition(V),\n    Hierarchical<DirichletBC>(*this),\n    g(reference_to_no_delete_pointer(g)),\n    _method(method)\n{\n  check();\n  parameters = default_parameters();\n  init_from_mesh_function(sub_domains, sub_domain);\n}\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(boost::shared_ptr<const FunctionSpace> V,\n                         boost::shared_ptr<const GenericFunction> g,\n                         boost::shared_ptr<const MeshFunction<uint> > sub_domains,\n                         uint sub_domain,\n                         std::string method)\n  : BoundaryCondition(V),\n    Hierarchical<DirichletBC>(*this),\n    g(g), _method(method)\n{\n  check();\n  parameters = default_parameters();\n  init_from_mesh_function(*sub_domains, sub_domain);\n}\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(const FunctionSpace& V, const GenericFunction& g,\n                         uint sub_domain, std::string method)\n  : BoundaryCondition(V),\n    Hierarchical<DirichletBC>(*this),\n    g(reference_to_no_delete_pointer(g)), _method(method)\n{\n  check();\n  parameters = default_parameters();\n  init_from_mesh(sub_domain);\n}\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(boost::shared_ptr<const FunctionSpace> V,\n                         boost::shared_ptr<const GenericFunction> g,\n                         uint sub_domain, std::string method)\n  : BoundaryCondition(V),\n    Hierarchical<DirichletBC>(*this),\n    g(g), _method(method)\n{\n  check();\n  parameters = default_parameters();\n  init_from_mesh(sub_domain);\n}\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(boost::shared_ptr<const FunctionSpace> V,\n                         boost::shared_ptr<const GenericFunction> g,\n                         const std::vector<std::pair<uint, uint> >& markers,\n                         std::string method)\n  : BoundaryCondition(V),\n    Hierarchical<DirichletBC>(*this),\n    g(g), _method(method), facets(markers)\n{\n  check();\n  parameters = default_parameters();\n}\n//-----------------------------------------------------------------------------\nDirichletBC::DirichletBC(const DirichletBC& bc)\n  : BoundaryCondition(bc._function_space),\n    Hierarchical<DirichletBC>(*this)\n{\n  // Set default parameters\n  parameters = default_parameters();\n\n  *this = bc;\n}\n//-----------------------------------------------------------------------------\nDirichletBC::~DirichletBC()\n{\n  // Do nothing\n}\n//-----------------------------------------------------------------------------\nconst DirichletBC& DirichletBC::operator= (const DirichletBC& bc)\n{\n  _function_space = bc._function_space;\n  g = bc.g;\n  _method = bc._method;\n  _user_sub_domain = bc._user_sub_domain;\n  facets = bc.facets;\n\n  // Call assignment operator for base class\n  Hierarchical<DirichletBC>::operator=(bc);\n\n  return *this;\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::apply(GenericMatrix& A) const\n{\n  apply(&A, 0, 0);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::apply(GenericVector& b) const\n{\n  apply(0, &b, 0);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::apply(GenericMatrix& A, GenericVector& b) const\n{\n  apply(&A, &b, 0);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::apply(GenericVector& b, const GenericVector& x) const\n{\n  apply(0, &b, &x);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::apply(GenericMatrix& A,\n                        GenericVector& b,\n                        const GenericVector& x) const\n{\n  apply(&A, &b, &x);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::get_boundary_values(Map& boundary_values,\n                         std::string method) const\n{\n  // Create local data\n  BoundaryCondition::LocalData data(*_function_space);\n\n  // Compute dofs and values\n  compute_bc(boundary_values, data, method);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::zero(GenericMatrix& A) const\n{\n  // A map to hold the mapping from boundary dofs to boundary values\n  Map boundary_values;\n\n  // Create local data for application of boundary conditions\n  BoundaryCondition::LocalData data(*_function_space);\n\n  // Compute dofs and values\n  compute_bc(boundary_values, data, _method);\n\n  // Copy boundary value data to arrays\n  std::vector<uint> dofs(boundary_values.size());\n  Map::const_iterator bv;\n  uint i = 0;\n  for (bv = boundary_values.begin(); bv != boundary_values.end(); ++bv)\n    dofs[i++] = bv->first;\n\n  // Modify linear system (A_ii = 1)\n  A.zero(boundary_values.size(), &dofs[0]);\n\n  // Finalise changes to A\n  A.apply(\"insert\");\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::zero_columns(GenericMatrix& A,\n                               GenericVector& b,\n                               double diag_val) const\n{\n  Map bv_map;\n  get_boundary_values(bv_map, _method);\n\n  // Create lookup table of dofs\n  //const uint nrows = A.size(0); // should be equal to b.size()\n  const uint ncols = A.size(1); // should be equal to max possible dof+1\n\n  std::pair<uint,uint> rows = A.local_range(0);\n  //std::pair<uint,uint> cols = A.local_range(1);\n\n  std::vector<char> is_bc_dof(ncols);\n  std::vector<double> bc_dof_val(ncols);\n  for (Map::const_iterator bv = bv_map.begin();  bv != bv_map.end();  ++bv)\n  {\n    is_bc_dof[bv->first] = 1;\n    bc_dof_val[bv->first] = bv->second;\n  }\n\n  // Scan through all columns of all rows, setting to zero if is_bc_dof[column]\n  // At the same time, we collect corrections to the RHS\n\n  std::vector<uint>   cols;\n  std::vector<double> vals;\n  std::vector<double> b_vals;\n  std::vector<uint>   b_rows;\n\n  for (uint row=rows.first; row<rows.second; row++)\n  {\n    // If diag_val is nonzero, the matrix is a diagonal block (nrows==ncols),\n    // and we can set the whole BC row\n    if (diag_val != 0.0 && is_bc_dof[row])\n    {\n      A.getrow(row, cols, vals);\n      for (uint j=0; j<cols.size(); j++)\n        vals[j] = (cols[j]==row) * diag_val;\n      A.setrow(row, cols, vals);\n      A.apply(\"insert\");\n      b.setitem(row, bc_dof_val[row]*diag_val);\n    }\n    else // Otherwise, we scan the row for BC columns\n    {\n      A.getrow(row, cols, vals);\n      bool row_changed=false;\n      for (uint j=0; j<cols.size(); j++)\n      {\n        const uint col = cols[j];\n\n        // Skip columns that aren't BC, and entries that are zero\n        if (!is_bc_dof[col] || vals[j] == 0.0)\n          continue;\n\n        // We're going to change the row, so make room for it\n        if (!row_changed)\n        {\n          row_changed = true;\n          b_rows.push_back(row);\n          b_vals.push_back(0.0);\n        }\n\n        b_vals.back() -= bc_dof_val[col]*vals[j];\n        vals[j] = 0.0;\n      }\n      if (row_changed)\n      {\n        A.setrow(row, cols, vals);\n        A.apply(\"insert\");\n      }\n    }\n  }\n\n  b.add(&b_vals.front(), b_rows.size(), &b_rows.front());\n  b.apply(\"add\");\n}\n//-----------------------------------------------------------------------------\nconst std::vector<std::pair<dolfin::uint, dolfin::uint> >& DirichletBC::markers() const\n{\n  return facets;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const GenericFunction> DirichletBC::value() const\n{\n  return g;\n}\n//-----------------------------------------------------------------------------\nboost::shared_ptr<const SubDomain> DirichletBC::user_sub_domain() const\n{\n  return _user_sub_domain;\n}\n//-----------------------------------------------------------------------------\nbool DirichletBC::is_compatible(GenericFunction& v) const\n{\n  // This function only checks the values at vertices when it should\n  // really check that the dof functionals agree. The check here is\n  // neither necessary nor sufficient to guarantee compatible boundary\n  // boundary conditions but a more robust test requires access to the\n  // function space.\n\n  dolfin_error(\"DirichletBC.cpp\",\n               \"call is_compatible\",\n               \"This function has not been updated for the new Function class interface\");\n\n  /*\n  // Compute value size\n  uint size = 1;\n  const uint rank = g->function_space().element()->value_rank();\n  for (uint i = 0; i < rank ; i++)\n    size *= g->function_space().element()->value_dimension(i);\n  double* g_values = new double[size];\n  double* v_values = new double[size];\n\n  // Get mesh\n  const Mesh& mesh = _function_space->mesh();\n\n  // Iterate over facets\n  for (uint f = 0; f < facets.size(); f++)\n  {\n    // Create cell and facet\n    uint cell_number  = facets[f].first;\n    uint facet_number = facets[f].second;\n    Cell cell(mesh, cell_number);\n    Facet facet(mesh, facet_number);\n\n    // Make cell and facet available to user-defined function\n    dolfin_error(\"DirichletBC.cpp\",\n                 \"add proper message here\",\n                 \"Does the new GenericFunction class need an 'update' function?\");\n    //g->update(cell, facet_number);\n    //v.update(cell, facet_number);\n\n    // Iterate over facet vertices\n    for (VertexIterator vertex(facet); !vertex.end(); ++vertex)\n    {\n      // Evaluate g and v at vertex\n      g->eval(g_values, vertex->x());\n      v.eval(v_values, vertex->x());\n\n      // Check values\n      for (uint i = 0; i < size; i++)\n      {\n        if (std::abs(g_values[i] - v_values[i]) > DOLFIN_EPS)\n        {\n          Point p(mesh.geometry().dim(), vertex->x());\n          cout << \"Incompatible function value \" << v_values[i] << \" at x = \" << p << \", should be \" << g_values[i] << \".\" << endl;\n          delete [] g_values;\n          delete [] v_values;\n          return false;\n        }\n      }\n    }\n  }\n\n  delete [] g_values;\n  delete [] v_values;\n  */\n\n  return true;\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::set_value(const GenericFunction& g)\n{\n  this->g = reference_to_no_delete_pointer(g);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::homogenize()\n{\n  const uint value_rank = g->value_rank();\n  if (!value_rank)\n  {\n    boost::shared_ptr<Constant> zero(new Constant(0.0));\n    set_value(zero);\n  } else if (value_rank == 1)\n  {\n    const uint value_dim = g->value_dimension(0);\n    std::vector<double> values(value_dim, 0.0);\n    boost::shared_ptr<Constant> zero(new Constant(values));\n    set_value(zero);\n  } else\n  {\n    std::vector<uint> value_shape;\n    for (uint i = 0; i < value_rank; i++)\n      value_shape.push_back(g->value_dimension(i));\n    std::vector<double> values(g->value_size(), 0.0);\n    boost::shared_ptr<Constant> zero(new Constant(value_shape, values));\n    set_value(zero);\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::set_value(boost::shared_ptr<const GenericFunction> g)\n{\n  this->g = g;\n}\n//-----------------------------------------------------------------------------\nstd::string DirichletBC::method() const\n{\n  return _method;\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::apply(GenericMatrix* A,\n                        GenericVector* b,\n                        const GenericVector* x) const\n{\n  // Check arguments\n  check_arguments(A, b, x);\n\n  // A map to hold the mapping from boundary dofs to boundary values\n  Map boundary_values;\n\n  // Create local data for application of boundary conditions\n  BoundaryCondition::LocalData data(*_function_space);\n\n  // Compute dofs and values\n  compute_bc(boundary_values, data, _method);\n\n  // Copy boundary value data to arrays\n  const uint size = boundary_values.size();\n  std::vector<uint> dofs(size);\n  std::vector<double> values(size);\n  Map::const_iterator bv;\n  uint i = 0;\n  for (bv = boundary_values.begin(); bv != boundary_values.end(); ++bv)\n  {\n    dofs[i]     = bv->first;\n    values[i++] = bv->second;\n  }\n\n  // Modify boundary values for nonlinear problems\n  if (x)\n  {\n    // Get values (these must reside in local portion (including ghost\n    // values) of the vector\n    std::vector<double> x_values(size);\n    x->get_local(&x_values[0], dofs.size(), &dofs[0]);\n\n    // Modify RHS entries\n    for (uint i = 0; i < size; i++)\n      values[i] = x_values[i] - values[i];\n  }\n\n  log(PROGRESS, \"Applying boundary conditions to linear system.\");\n\n  // Modify RHS vector (b[i] = value) and apply changes\n  if (b)\n  {\n    b->set(&values[0], size, &dofs[0]);\n    b->apply(\"insert\");\n  }\n\n  // Modify linear system (A_ii = 1) and apply changes\n  if (A)\n  {\n    const bool use_ident = parameters[\"use_ident\"];\n    if (use_ident)\n      A->ident(size, &dofs[0]);\n    else\n    {\n      for (uint i = 0; i < size; i++)\n      {\n        std::pair<uint, uint> ij(dofs[i], dofs[i]);\n        A->setitem(ij, 1.0);\n      }\n    }\n\n    // Apply changes\n    A->apply(\"add\");\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::check() const\n{\n  dolfin_assert(g);\n  dolfin_assert(_function_space->element());\n\n  // Check for common errors, message below might be cryptic\n  if (g->value_rank() == 0 && _function_space->element()->value_rank() == 1)\n  {\n    dolfin_error(\"DirichletBC.cpp\",\n                 \"create Dirichlet boundary condition\",\n                 \"Expecting a vector-valued boundary value but given function is scalar\");\n  }\n  if (g->value_rank() == 1 && _function_space->element()->value_rank() == 0)\n  {\n    dolfin_error(\"DirichletBC.cpp\",\n                 \"create Dirichlet boundary condition\",\n                 \"Expecting a scalar boundary value but given function is vector-valued\");\n  }\n\n  // Check that value shape of boundary value\n  if (g->value_rank() != _function_space->element()->value_rank())\n  {\n    dolfin_error(\"DirichletBC.cpp\",\n                 \"create Dirichlet boundary condition\",\n                 \"Illegal value rank (%d), expecting (%d)\",\n                 g->value_rank(), _function_space->element()->value_rank());\n  }\n  for (uint i = 0; i < g->value_rank(); i++)\n  {\n    if (g->value_dimension(i) != _function_space->element()->value_dimension(i))\n    {\n      dolfin_error(\"DirichletBC.cpp\",\n                   \"create Dirichlet boundary condition\",\n                   \"Illegal value dimension (%d), expecting (%d)\",\n                   g->value_dimension(i),\n                   _function_space->element()->value_dimension(i));\n    }\n  }\n\n  // Check that boundary condition method is known\n  if (methods.count(_method) == 0)\n  {\n    dolfin_error(\"DirichletBC.cpp\",\n                 \"create Dirichlet boundary condition\",\n                 \"unknown method (\\\"%s\\\")\", _method.c_str());\n  }\n\n  // Check that the mesh is ordered\n  dolfin_assert(_function_space->mesh());\n  if (!_function_space->mesh()->ordered())\n  {\n    dolfin_error(\"DirichletBC.cpp\",\n                 \"create Dirichlet boundary condition\",\n                 \"Mesh is not ordered according to the UFC numbering convention. Consider calling mesh.order()\");\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::init_from_sub_domain(boost::shared_ptr<const SubDomain> sub_domain)\n{\n  dolfin_assert(facets.size() == 0);\n\n  // FIXME: This can be made more efficient, we should be able to\n  // FIXME: extract the facets without first creating a MeshFunction on\n  // FIXME: the entire mesh and then extracting the subset. This is done\n  // FIXME: mainly for convenience (we may reuse mark() in SubDomain).\n\n  dolfin_assert(_function_space->mesh());\n  const Mesh& mesh = *_function_space->mesh();\n\n  // Create mesh function for sub domain markers on facets\n  const uint dim = mesh.topology().dim();\n  _function_space->mesh()->init(dim - 1);\n  MeshFunction<uint> sub_domains(mesh, dim - 1);\n\n  // Set geometric dimension (needed for SWIG interface)\n  sub_domain->_geometric_dimension = mesh.geometry().dim();\n\n  // Mark everything as sub domain 1\n  sub_domains = 1;\n\n  // Mark the sub domain as sub domain 0\n  sub_domain->mark(sub_domains, 0);\n\n  // Initialize from mesh function\n  init_from_mesh_function(sub_domains, 0);\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::init_from_mesh_function(const MeshFunction<uint>& sub_domains,\n                                          uint sub_domain)\n{\n  dolfin_assert(facets.size() == 0);\n\n  dolfin_assert(_function_space->mesh());\n  const Mesh& mesh = *_function_space->mesh();\n\n  // Make sure we have the facet - cell connectivity\n  const uint dim = mesh.topology().dim();\n  mesh.init(dim - 1, dim);\n\n  // Build set of boundary facets\n  for (FacetIterator facet(mesh); !facet.end(); ++facet)\n  {\n    // Skip facets not on this boundary\n    if (sub_domains[*facet] != sub_domain)\n      continue;\n\n    // Get cell to which facet belongs (there may be two, but pick first)\n    const Cell cell(mesh, facet->entities(dim)[0]);\n\n    // Get local index of facet with respect to the cell\n    const uint facet_number = cell.index(*facet);\n\n    // Copy data\n    facets.push_back(std::pair<uint, uint>(cell.index(), facet_number));\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::init_from_mesh(uint sub_domain)\n{\n  dolfin_assert(facets.size() == 0);\n\n  // For this to work, the mesh *needs* to be ordered according to\n  // the UFC ordering before it gets here. So reordering the mesh\n  // here will either have no effect (if the mesh is already ordered\n  // or it won't do anything good (since the markers are wrong anyway).\n  // In conclusion: we don't need to order the mesh here.\n\n  dolfin_assert(_function_space->mesh());\n  const Mesh& mesh = *_function_space->mesh();\n\n  // Assign domain numbers for each facet\n  const uint D = mesh.topology().dim();\n  const std::map<std::pair<uint, uint>, uint>&\n    markers = mesh.domains().markers(D - 1).values();\n  std::map<std::pair<uint, uint>, uint>::const_iterator mark;\n  for (mark = markers.begin(); mark != markers.end(); ++mark)\n  {\n    if (mark->second == sub_domain)\n      facets.push_back(mark->first);\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::compute_bc(Map& boundary_values,\n                             BoundaryCondition::LocalData& data,\n                             std::string method) const\n{\n  // Set method if dafault\n  if (method == \"default\")\n    method = _method;\n\n  // Choose strategy\n  if (method == \"topological\")\n    compute_bc_topological(boundary_values, data);\n  else if (method == \"geometric\")\n    compute_bc_geometric(boundary_values, data);\n  else if (method == \"pointwise\")\n    compute_bc_pointwise(boundary_values, data);\n  else\n  {\n    dolfin_error(\"DirichletBC.cpp\",\n                 \"compute boundary conditions\",\n                 \"Unknown method for application of boundary conditions\");\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::compute_bc_topological(Map& boundary_values,\n                                         BoundaryCondition::LocalData& data) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(g);\n\n  // Special case\n  if (facets.size() == 0)\n  {\n    if (MPI::num_processes() == 1)\n      warning(\"Found no facets matching domain for boundary condition.\");\n    return;\n  }\n\n  // Get mesh and dofmap\n  dolfin_assert(_function_space->mesh());\n  dolfin_assert(_function_space->dofmap());\n  const Mesh& mesh = *_function_space->mesh();\n  const GenericDofMap& dofmap = *_function_space->dofmap();\n\n  // Create UFC cell object\n  UFCCell ufc_cell(mesh);\n\n  // Iterate over facets\n  dolfin_assert(_function_space->element());\n  Progress p(\"Computing Dirichlet boundary values, topological search\", facets.size());\n  for (uint f = 0; f < facets.size(); ++f)\n  {\n    // Get cell number and local facet number\n    const uint cell_number  = facets[f].first;\n    const uint facet_number = facets[f].second;\n\n    // Create cell\n    Cell cell(mesh, cell_number);\n    ufc_cell.update(cell, facet_number);\n\n    // Restrict coefficient to cell\n    g->restrict(&data.w[0], *_function_space->element(), cell, ufc_cell);\n\n    // Tabulate dofs on cell\n    dofmap.tabulate_dofs(&data.cell_dofs[0], cell);\n\n    // Tabulate which dofs are on the facet\n    dofmap.tabulate_facet_dofs(&data.facet_dofs[0], facet_number);\n\n    // Pick values for facet\n    for (uint i = 0; i < dofmap.num_facet_dofs(); i++)\n    {\n      const uint global_dof = data.cell_dofs[data.facet_dofs[i]];\n      const double value = data.w[data.facet_dofs[i]];\n      boundary_values[global_dof] = value;\n    }\n\n    p++;\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::compute_bc_geometric(Map& boundary_values,\n                                      BoundaryCondition::LocalData& data) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->element());\n  dolfin_assert(g);\n\n  // Special case\n  if (facets.size() == 0)\n  {\n    if (MPI::num_processes() == 1)\n      warning(\"Found no facets matching domain for boundary condition.\");\n    return;\n  }\n\n  // Get mesh and dofmap\n  dolfin_assert(_function_space->mesh());\n  dolfin_assert(_function_space->dofmap());\n  const Mesh& mesh = *_function_space->mesh();\n  const GenericDofMap& dofmap = *_function_space->dofmap();\n\n  // Initialize facets, needed for geometric search\n  log(TRACE, \"Computing facets, needed for geometric application of boundary conditions.\");\n  mesh.init(mesh.topology().dim() - 1);\n\n  // Iterate over facets\n  Progress p(\"Computing Dirichlet boundary values, geometric search\", facets.size());\n  for (uint f = 0; f < facets.size(); ++f)\n  {\n    // Get cell number and local facet number\n    const uint cell_number = facets[f].first;\n    const uint facet_number = facets[f].second;\n\n    // Create facet\n    Cell cell(mesh, cell_number);\n    Facet facet(mesh, cell.entities(mesh.topology().dim() - 1)[facet_number]);\n\n    // Create UFC cell object\n    UFCCell ufc_cell(mesh);\n\n    // Loop the vertices associated with the facet\n    for (VertexIterator vertex(facet); !vertex.end(); ++vertex)\n    {\n      // Loop the cells associated with the vertex\n      for (CellIterator c(*vertex); !c.end(); ++c)\n      {\n        ufc_cell.update(*c, facet_number);\n\n        bool interpolated = false;\n\n        // Tabulate coordinates of dofs on cell\n        dofmap.tabulate_coordinates(data.coordinates, ufc_cell);\n\n        // Loop over all dofs on cell\n        for (uint i = 0; i < dofmap.cell_dimension(c->index()); ++i)\n        {\n          // Check if the coordinates are on current facet and thus on boundary\n          if (!on_facet(&(data.coordinates[i][0]), facet))\n            continue;\n\n          if (!interpolated)\n          {\n            // Tabulate dofs on cell\n            dofmap.tabulate_dofs(&data.cell_dofs[0], *c);\n\n            // Restrict coefficient to cell\n            g->restrict(&data.w[0], *_function_space->element(), cell, ufc_cell);\n          }\n\n          // Set boundary value\n          const uint global_dof = data.cell_dofs[i];\n          const double value = data.w[i];\n          boundary_values[global_dof] = value;\n        }\n      }\n    }\n  }\n}\n//-----------------------------------------------------------------------------\nvoid DirichletBC::compute_bc_pointwise(Map& boundary_values,\n                                      BoundaryCondition::LocalData& data) const\n{\n  dolfin_assert(_function_space);\n  dolfin_assert(_function_space->element());\n  dolfin_assert(g);\n  dolfin_assert(_user_sub_domain);\n\n  // Get mesh and dofmap\n  dolfin_assert(_function_space->mesh());\n  dolfin_assert(_function_space->dofmap());\n  const Mesh& mesh = *_function_space->mesh();\n  const GenericDofMap& dofmap = *_function_space->dofmap();\n\n  // Geometric dim\n  const uint gdim = mesh.geometry().dim();\n\n  // Create UFC cell object\n  UFCCell ufc_cell(mesh);\n\n  // Iterate over cells\n  Progress p(\"Computing Dirichlet boundary values, pointwise search\", mesh.num_cells());\n  Array<double> x(gdim);\n  for (CellIterator cell(mesh); !cell.end(); ++cell)\n  {\n    // Update UFC cell\n    ufc_cell.update(*cell);\n\n    // Tabulate coordinates of dofs on cell\n    dofmap.tabulate_coordinates(data.coordinates, ufc_cell);\n\n    // Interpolate function only once and only on cells where necessary\n    bool already_interpolated = false;\n\n    // Loop all dofs on cell\n    for (uint i = 0; i < dofmap.cell_dimension(cell->index()); ++i)\n    {\n      // Check if the coordinates are part of the sub domain (calls user-defined 'indside' function)\n      for (uint j = 0; j < gdim; ++j)\n        x[j] = data.coordinates[i][j];\n      if (!_user_sub_domain->inside(x, false))\n        continue;\n\n      if (!already_interpolated)\n      {\n        already_interpolated = true;\n\n        // Tabulate dofs on cell\n        dofmap.tabulate_dofs(&data.cell_dofs[0], *cell);\n\n        // Restrict coefficient to cell\n        g->restrict(&data.w[0], *_function_space->element(), *cell, ufc_cell);\n      }\n\n      // Set boundary value\n      const uint global_dof = data.cell_dofs[i];\n      const double value = data.w[i];\n      boundary_values[global_dof] = value;\n    }\n\n    p++;\n  }\n}\n//-----------------------------------------------------------------------------\nbool DirichletBC::on_facet(double* coordinates, Facet& facet) const\n{\n  // Check if the coordinates are on the same line as the line segment\n  if (facet.dim() == 1)\n  {\n    // Create points\n    Point p(coordinates[0], coordinates[1]);\n    const Point v0 = Vertex(facet.mesh(), facet.entities(0)[0]).point();\n    const Point v1 = Vertex(facet.mesh(), facet.entities(0)[1]).point();\n\n    // Create vectors\n    const Point v01 = v1 - v0;\n    const Point vp0 = v0 - p;\n    const Point vp1 = v1 - p;\n\n    // Check if the length of the sum of the two line segments vp0 and vp1 is\n    // equal to the total length of the facet\n    if ( std::abs(v01.norm() - vp0.norm() - vp1.norm()) < DOLFIN_EPS )\n      return true;\n    else\n      return false;\n  }\n  // Check if the coordinates are in the same plane as the triangular facet\n  else if (facet.dim() == 2)\n  {\n    // Create points\n    const Point p(coordinates[0], coordinates[1], coordinates[2]);\n    const Point v0 = Vertex(facet.mesh(), facet.entities(0)[0]).point();\n    const Point v1 = Vertex(facet.mesh(), facet.entities(0)[1]).point();\n    const Point v2 = Vertex(facet.mesh(), facet.entities(0)[2]).point();\n\n    // Create vectors\n    const Point v01 = v1 - v0;\n    const Point v02 = v2 - v0;\n    const Point vp0 = v0 - p;\n    const Point vp1 = v1 - p;\n    const Point vp2 = v2 - p;\n\n    // Check if the sum of the area of the sub triangles is equal to the total\n    // area of the facet\n    if (std::abs(v01.cross(v02).norm() - vp0.cross(vp1).norm() - vp1.cross(vp2).norm()\n        - vp2.cross(vp0).norm()) < DOLFIN_EPS)\n      return true;\n    else\n      return false;\n  }\n\n  dolfin_error(\"DirichletBC.cpp\",\n               \"determine if given point is on facet\",\n               \"Not implemented for given facet dimension\");\n\n  return false;\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "bb9d84a3b681a276671cfb69a4583b5182ac2292", "size": 30798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/fem/DirichletBC.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/fem/DirichletBC.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/fem/DirichletBC.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.1517761033, "max_line_length": 131, "alphanum_fraction": 0.5834469771, "num_tokens": 7239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651623644570757, "lm_q2_score": 0.03021458412014941, "lm_q1q2_score": 0.007146239721869979}}
{"text": "/*\n * Copyright (c) 2014, Stanislav Vorobiov\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#include \"HermitePath.h\"\n#include \"Settings.h\"\n#include <boost/make_shared.hpp>\n#include <cmath>\n\nnamespace af\n{\n    HermitePathIterator::HermitePathIterator(const HermitePath* path, int i, float pos)\n    : path_(path),\n      i_(i),\n      pos_(pos)\n    {\n        if (path_->lengths_.empty()) {\n            return;\n        }\n\n        if (i < 0) {\n            i = 0;\n            pos = 0.0f;\n        }\n\n        if (static_cast<size_t>(i) >= path_->lengths_.size()) {\n            i = path_->lengths_.size() - 1;\n            pos = path_->lengths_[i];\n        }\n\n        float t = pos / path_->lengths_[i];\n        point_ = path_->samples_[i] + t * (path_->samples_[i + 1] - path_->samples_[i]);\n    }\n\n    HermitePathIterator::~HermitePathIterator()\n    {\n    }\n\n    PathIteratorPtr HermitePathIterator::clone() const\n    {\n        return boost::make_shared<HermitePathIterator>(path_, i_, pos_);\n    }\n\n    const b2Vec2& HermitePathIterator::current() const\n    {\n        return point_;\n    }\n\n    bool HermitePathIterator::less(const PathIteratorPtr& other) const\n    {\n        const HermitePathIteratorPtr& r =\n            boost::static_pointer_cast<HermitePathIterator>(other);\n\n        return less(*r);\n    }\n\n    bool HermitePathIterator::eq(const PathIteratorPtr& other) const\n    {\n        const HermitePathIteratorPtr& r =\n            boost::static_pointer_cast<HermitePathIterator>(other);\n\n        return eq(*r);\n    }\n\n    void HermitePathIterator::step(float length)\n    {\n        if ((length == 0.0f) || path_->lengths_.empty()) {\n            return;\n        }\n\n        if (i_ < 0) {\n            if (length > 0.0f) {\n                i_ = 0;\n                pos_ = 0.0f;\n            } else {\n                return;\n            }\n        }\n\n        if (static_cast<size_t>(i_) >= path_->lengths_.size()) {\n            if (length > 0.0f) {\n                return;\n            } else {\n                i_ = path_->lengths_.size() - 1;\n                pos_ = path_->lengths_[i_];\n            }\n        }\n\n        if (length > 0.0f) {\n            stepForward(length);\n        } else {\n            stepBack(-length);\n        }\n    }\n\n    void HermitePathIterator::stepForward(float length)\n    {\n        if (length > path_->length_) {\n            if (loop()) {\n                length = std::fmod(length, path_->length_);\n                if (length == 0.0f) {\n                    return;\n                }\n            } else {\n                i_ = path_->lengths_.size();\n                pos_ = 0.0f;\n                point_ = path_->samples_[i_];\n                return;\n            }\n        }\n\n        if (loop()) {\n            float l = 0.0f;\n            float tmpPos = pos_ + length;\n            size_t k = i_;\n\n            while (true) {\n                if (tmpPos <= (l + path_->lengths_[k])) {\n                    i_ = k;\n                    pos_ = tmpPos - l;\n\n                    float t = pos_ / path_->lengths_[i_];\n                    point_ = path_->samples_[i_] + t * (path_->samples_[i_ + 1] - path_->samples_[i_]);\n\n                    return;\n                }\n                l += path_->lengths_[k];\n\n                ++k;\n                k %= path_->lengths_.size();\n            }\n        } else {\n            float l = 0.0f;\n            float tmpPos = pos_ + length;\n\n            for (size_t k = i_; k < path_->lengths_.size(); ++k) {\n                if (tmpPos <= (l + path_->lengths_[k])) {\n                    i_ = k;\n                    pos_ = tmpPos - l;\n\n                    float t = pos_ / path_->lengths_[i_];\n                    point_ = path_->samples_[i_] + t * (path_->samples_[i_ + 1] - path_->samples_[i_]);\n\n                    return;\n                }\n                l += path_->lengths_[k];\n            }\n\n            i_ = path_->lengths_.size();\n            pos_ = 0.0f;\n            point_ = path_->samples_[i_];\n        }\n    }\n\n    void HermitePathIterator::stepBack(float length)\n    {\n        if (length > path_->length_) {\n            if (loop()) {\n                length = std::fmod(length, path_->length_);\n                if (length == 0.0f) {\n                    return;\n                }\n            } else {\n                i_ = -1;\n                pos_ = 0.0f;\n                point_ = path_->samples_[0];\n                return;\n            }\n        }\n\n        if (loop()) {\n            float l = 0.0f;\n            float tmpPos = path_->lengths_[i_] + length - pos_;\n            size_t k = i_;\n\n            while (true) {\n                l += path_->lengths_[k];\n                if (tmpPos < l) {\n                    i_ = k;\n                    pos_ = l - tmpPos;\n\n                    float t = pos_ / path_->lengths_[i_];\n                    point_ = path_->samples_[i_] + t * (path_->samples_[i_ + 1] - path_->samples_[i_]);\n\n                    return;\n                }\n\n                if (k-- == 0) {\n                    k = path_->lengths_.size() - 1;\n                }\n            }\n        } else {\n            float l = 0.0f;\n            float tmpPos = path_->lengths_[i_] + length - pos_;\n\n            for (int k = i_; k >= 0; --k) {\n                l += path_->lengths_[k];\n                if (tmpPos < l) {\n                    i_ = k;\n                    pos_ = l - tmpPos;\n\n                    float t = pos_ / path_->lengths_[i_];\n                    point_ = path_->samples_[i_] + t * (path_->samples_[i_ + 1] - path_->samples_[i_]);\n\n                    return;\n                }\n            }\n\n            i_ = -1;\n            pos_ = 0.0f;\n            point_ = path_->samples_[0];\n        }\n    }\n\n    HermitePath::HermitePath(int numIterations, float c)\n    : step_(1.0f / numIterations),\n      c_(c),\n      length_(0.0f)\n    {\n        if (numIterations <= 0) {\n            step_ = 1.0f;\n        }\n    }\n\n    HermitePath::HermitePath(float c)\n    : step_(1.0f / settings.hermitePath.numIterations),\n      c_(c),\n      length_(0.0f)\n    {\n    }\n\n    HermitePath::~HermitePath()\n    {\n    }\n\n    void HermitePath::add(const b2Vec2& point)\n    {\n        p_.push_back(point);\n\n        if (p_.size() >= 3) {\n            const b2Vec2& p2 = p_[p_.size() - 1];\n            const b2Vec2& p0 = p_[p_.size() - 3];\n            m_.push_back((1.0f - c_) * 0.5f * (p2 - p0));\n        }\n\n        if (p_.size() >= 4) {\n            b2Vec2 prev = at(p_.size() - 4, 0.0f);\n\n            if (p_.size() == 4) {\n                samples_.push_back(prev);\n            }\n\n            for (float t = step_; t <= (1.0f - step_); t += step_) {\n                b2Vec2 cur = at(p_.size() - 4, t);\n                samples_.push_back(cur);\n\n                lengths_.push_back(b2Distance(prev, cur));\n                length_ += lengths_.back();\n\n                prev = cur;\n            }\n\n            b2Vec2 cur = at(p_.size() - 4, 1.0f);\n            samples_.push_back(cur);\n\n            lengths_.push_back(b2Distance(prev, cur));\n            length_ += lengths_.back();\n        }\n    }\n\n    void HermitePath::add(const b2Vec2* points, size_t numPoints)\n    {\n        for (size_t i = 0; i < numPoints; ++i) {\n            add(points[i]);\n        }\n    }\n\n    void HermitePath::addFront(const b2Vec2& point)\n    {\n        p_.insert(p_.begin(), point);\n\n        if (p_.size() >= 3) {\n            const b2Vec2& p2 = p_[2];\n            const b2Vec2& p0 = p_[0];\n            m_.insert(m_.begin(), (1.0f - c_) * 0.5f * (p2 - p0));\n        }\n\n        if (p_.size() >= 4) {\n            b2Vec2 prev = at(0, 0.0f);\n\n            std::vector<float> tmpLengths;\n            Points tmpSamples;\n\n            if (p_.size() == 4) {\n                tmpSamples.push_back(prev);\n            }\n\n            for (float t = step_; t <= (1.0f - step_); t += step_) {\n                b2Vec2 cur = at(0, t);\n                tmpSamples.push_back(cur);\n\n                tmpLengths.push_back(b2Distance(prev, cur));\n                length_ += tmpLengths.back();\n\n                prev = cur;\n            }\n\n            b2Vec2 cur = at(0, 1.0f);\n            tmpSamples.push_back(cur);\n\n            tmpLengths.push_back(b2Distance(prev, cur));\n            length_ += tmpLengths.back();\n\n            samples_.insert(samples_.begin(), tmpSamples.begin(), tmpSamples.end());\n            lengths_.insert(lengths_.begin(), tmpLengths.begin(), tmpLengths.end());\n        }\n    }\n\n    void HermitePath::addFront(const b2Vec2* points, size_t numPoints)\n    {\n        for (size_t i = 0; i < numPoints; ++i) {\n            addFront(points[i]);\n        }\n    }\n\n    PathPtr HermitePath::clone() const\n    {\n        HermitePathPtr p = boost::make_shared<HermitePath>(1.0f, 0.0f);\n\n        /*\n         * FIXME: hack.\n         */\n        p->step_ = step_;\n        p->c_ = c_;\n        p->p_ = p_;\n        p->m_ = m_;\n        p->length_ = length_;\n        p->lengths_ = lengths_;\n        p->samples_ = samples_;\n\n        return p;\n    }\n\n    const Points& HermitePath::points() const\n    {\n        return p_;\n    }\n\n    float HermitePath::length() const\n    {\n        return length_;\n    }\n\n    PathIteratorPtr HermitePath::first() const\n    {\n        return boost::make_shared<HermitePathIterator>(this, 0, 0.0f);\n    }\n\n    PathIteratorPtr HermitePath::last() const\n    {\n        if (lengths_.empty()) {\n            return boost::make_shared<HermitePathIterator>(this, 0, 0.0f);\n        } else {\n            return boost::make_shared<HermitePathIterator>(this, lengths_.size() - 1, lengths_.back());\n        }\n    }\n\n    PathIteratorPtr HermitePath::end() const\n    {\n        if (lengths_.empty()) {\n            return boost::make_shared<HermitePathIterator>(this, 0, 0.0f);\n        } else {\n            return boost::make_shared<HermitePathIterator>(this, lengths_.size(), 0.0f);\n        }\n    }\n\n    PathIteratorPtr HermitePath::rend() const\n    {\n        if (lengths_.empty()) {\n            return boost::make_shared<HermitePathIterator>(this, 0, 0.0f);\n        } else {\n            return boost::make_shared<HermitePathIterator>(this, -1, 0.0f);\n        }\n    }\n\n    PathIteratorPtr HermitePath::find(float pos) const\n    {\n        if (lengths_.empty()) {\n            return boost::make_shared<HermitePathIterator>(this, 0, 0.0f);\n        }\n\n        if (pos < 0.0f) {\n            return boost::make_shared<HermitePathIterator>(this, -1, 0.0f);\n        }\n\n        float l = 0.0f;\n\n        for (size_t i = 0; i < lengths_.size(); ++i) {\n            if (pos <= (l + lengths_[i])) {\n                return boost::make_shared<HermitePathIterator>(this, i, pos - l);\n            }\n            l += lengths_[i];\n        }\n\n        return boost::make_shared<HermitePathIterator>(this, lengths_.size(), 0.0f);\n    }\n\n    HermitePathIterator HermitePath::firstIt() const\n    {\n        return HermitePathIterator(this, 0, 0.0f);\n    }\n\n    HermitePathIterator HermitePath::lastIt() const\n    {\n        if (lengths_.empty()) {\n            return HermitePathIterator(this, 0, 0.0f);\n        } else {\n            return HermitePathIterator(this, lengths_.size() - 1, lengths_.back());\n        }\n    }\n\n    HermitePathIterator HermitePath::findIt(float pos) const\n    {\n        if (lengths_.empty()) {\n            return HermitePathIterator(this, 0, 0.0f);\n        }\n\n        if (pos < 0.0f) {\n            return HermitePathIterator(this, -1, 0.0f);\n        }\n\n        float l = 0.0f;\n\n        for (size_t i = 0; i < lengths_.size(); ++i) {\n            if (pos <= (l + lengths_[i])) {\n                return HermitePathIterator(this, i, pos - l);\n            }\n            l += lengths_[i];\n        }\n\n        return HermitePathIterator(this, lengths_.size(), 0.0f);\n    }\n\n    HermitePathIterator HermitePath::endIt() const\n    {\n        if (lengths_.empty()) {\n            return HermitePathIterator(this, 0, 0.0f);\n        } else {\n            return HermitePathIterator(this, lengths_.size(), 0.0f);\n        }\n    }\n\n    HermitePathIterator HermitePath::rendIt() const\n    {\n        if (lengths_.empty()) {\n            return HermitePathIterator(this, 0, 0.0f);\n        } else {\n            return HermitePathIterator(this, -1, 0.0f);\n        }\n    }\n\n    void HermitePath::clear()\n    {\n        p_.clear();\n        m_.clear();\n        length_ = 0.0f;\n        lengths_.clear();\n        samples_.clear();\n    }\n\n    b2Vec2 HermitePath::at(int i, float t) const\n    {\n        float h00 = 2 * t * t * t - 3 * t * t + 1;\n        float h10 = t * t * t - 2 * t * t + t;\n        float h01 = - 2 * t * t * t + 3 * t * t;\n        float h11 = t * t * t - t * t;\n\n        const b2Vec2& p0 = p_[i + 1];\n        const b2Vec2& p1 = p_[i + 2];\n\n        const b2Vec2& m0 = m_[i];\n        const b2Vec2& m1 = m_[i + 1];\n\n        return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1;\n    }\n}\n", "meta": {"hexsha": "dee61fcb2ca5f1439d3fc2fa285476d10a618d62", "size": 14031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "game/HermitePath.cpp", "max_stars_repo_name": "Sheph/TriggerTime", "max_stars_repo_head_hexsha": "9265dee6a178e43bf7365e3aa2f7f2ca22df074f", "max_stars_repo_licenses": ["BSD-2-Clause"], "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": "game/HermitePath.cpp", "max_issues_repo_name": "Sheph/TriggerTime", "max_issues_repo_head_hexsha": "9265dee6a178e43bf7365e3aa2f7f2ca22df074f", "max_issues_repo_licenses": ["BSD-2-Clause"], "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": "game/HermitePath.cpp", "max_forks_repo_name": "Sheph/TriggerTime", "max_forks_repo_head_hexsha": "9265dee6a178e43bf7365e3aa2f7f2ca22df074f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-02-28T11:33:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T20:11:45.000Z", "avg_line_length": 27.6200787402, "max_line_length": 103, "alphanum_fraction": 0.489558834, "num_tokens": 3798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.01854656264734432, "lm_q1q2_score": 0.007138797201394921}}
{"text": "#include <stdgl/ShaderProgram.hpp>\n#include <stdgl/VoxelData.hpp>\n#include <stdgl/Texture3D.hpp>\n#include <csgframework/CsgTree.hpp>\n#include <csgframework/CsgLoader.hpp>\n\n#include <stdio.h>\n#include <iostream>\n#include <memory>\n\n#include <imgui/imgui.h>\n#include <imgui/imgui_impl_glfw.h>\n#include <GLFW/glfw3.h>\n\n#include <Eigen/Geometry>\n\n#define TO_STRING(x) #x\n\n#define SHADER_PREFIX \\\n  \"#version 120\\n\" \\\n  \"#define MAXFLOAT 1.0e15f\\n\"\n\nconst char* vs_str = SHADER_PREFIX TO_STRING\n(\n  //! Normalized pixel coordinates.\n  varying vec2 vPixel;\n\n  void main (void)\n  {\n    vPixel = gl_Vertex.xy;\n\n    gl_Position = gl_Vertex;\n  }\n);\n\nconst char* fs_str = SHADER_PREFIX TO_STRING\n(\n  //! Normalized pixel coordinates.\n  varying vec2 vPixel;\n\n  uniform vec3 iResolution;\n  uniform float iGlobalTime;\n  uniform float iCameraAngle;\n  uniform float iCameraDistance;\n\n  uniform float iSceneRadius;\n\n  //! Scene epsilon to prevent self-intersections.\n  uniform float iSceneEpsilon;\n\n  uniform sampler3D iDistanceTexture;\n\n  uniform vec3 iBoundsMin;\n  uniform vec3 iBoundsMax;\n\n  float sdPlane (vec3 p)\n  {\n    return p.y;\n  }\n\n  //----------------------------------------------------------------------\n\n  vec2 opU (vec2 d1, vec2 d2)\n  {\n    return (d1.x < d2.x) ? d1 : d2;\n  }\n\n  //----------------------------------------------------------------------\n\n  float distanceField (in vec3 thePoint)\n  {\n    vec3 aTexCoord = (thePoint - iBoundsMin) / (iBoundsMax - iBoundsMin);\n\n    return texture3D (iDistanceTexture, aTexCoord).r;\n  }\n\n\n  vec2 map (in vec3 thePos)\n  {\n    vec2 res = vec2 (distanceField (thePos), 46.9);\n    res = opU (vec2 (sdPlane (thePos - vec3( 0.0, iBoundsMin.y, 0.0)), 1.0), res);\n\n    return res;\n  }\n\n  vec2 castRayTexture (in vec3 ro, in vec3 rd, in vec2 theRange)\n  {\n    float tmin = theRange.x;\n    float tmax = theRange.y;\n\n    float precis = iSceneEpsilon;\n    float t = tmin;\n    float m = -1.0;\n\n    for (int i = 0; i < 100; i++)\n    {\n      vec3 aPos = ro + rd * t;\n      vec2 res = map (aPos);\n\n      if (res.x < precis || t > tmax)\n      {\n        break;\n      }\n\n      t += res.x;\n      m = res.y;\n    }\n\n    if (t > tmax)\n    {\n      m = -1.0;\n    }\n\n    return vec2 (t, m);\n  }\n\n  float softshadow (in vec3 ro, in vec3 rd, in float mint, in float tmax)\n  {\n    float res = 1.0;\n    float t = mint;\n\n    for (int i = 0; i < 16; i++)\n    {\n      float h = map (ro + rd * t).x;\n      res = min (res, 8.0 * h / t);\n      t += clamp (h, 0.02, 0.10);\n\n      if (h < iSceneEpsilon || t > tmax)\n      {\n        break;\n      }\n    }\n\n    return clamp (res, 0.0, 1.0);\n  }\n\n  vec3 calcNormal (in vec3 pos)\n  {\n    vec3 eps = vec3 (iSceneEpsilon, 0.0, 0.0);\n    vec3 nor = vec3 ( map (pos + eps.xyy).x - map (pos - eps.xyy).x,\n                      map (pos + eps.yxy).x - map (pos - eps.yxy).x,\n                      map (pos + eps.yyx).x - map (pos - eps.yyx).x);\n    return normalize (nor);\n  }\n\n  float calcAO (in vec3 pos, in vec3 nor)\n  {\n    float occ = 0.0;\n    float sca = 1.0;\n\n    for (int i = 0; i < 5; i++)\n    {\n      float hr = 0.01 + 0.12 * float (i) / 4.0;\n      vec3 aopos =  nor * hr + pos;\n      float dd = map (aopos).x;\n      occ += - (dd - hr) * sca;\n      sca *= 0.95;\n    }\n\n    return clamp (1.0 - 3.0 * occ, 0.0, 1.0);\n  }\n\n  vec3 render (in vec3 ro, in vec3 rd, in vec2 theRange)\n  {\n    vec3 col = vec3 (0.7, 0.9, 1.0) + rd.y * 0.8;\n\n    if (theRange.x == MAXFLOAT)\n    {\n      return col;\n    }\n\n    vec2 res = castRayTexture (ro, rd, theRange);\n\n    float t = res.x;\n    float m = res.y;\n\n    if (m > -0.5)\n    {\n      vec3 pos = ro + t * rd;\n      vec3 nor = calcNormal (pos);\n      vec3 ref = reflect (rd, nor);\n\n      // col = abs(nor);\n      // return col;\n\n      // material\n      col = 0.45 + 0.3 * sin (vec3 (0.05, 0.08, 0.10) * (m - 1.0));\n\n      if (m < 1.5)\n      {\n        float f = mod (floor (5.0 * pos.z) + floor (5.0 * pos.x), 2.0);\n        col = 0.4 + 0.1 * f * vec3 (1.0);\n      }\n\n      // lighitng\n      float occ = calcAO (pos, nor);\n      vec3  lig = normalize (vec3 (-0.6, 0.7, -0.5));\n      float amb = clamp (0.5 + 0.5 * nor.y, 0.0, 1.0);\n      float dif = clamp (dot (nor, lig), 0.0, 1.0);\n      float bac = clamp (dot (nor, normalize (vec3 (-lig.x, 0.0, -lig.z))), 0.0, 1.0) * clamp (1.0 - pos.y, 0.0, 1.0);\n      float dom = smoothstep (-0.1, 0.1, ref.y);\n      float fre = pow (clamp (1.0 + dot (nor, rd), 0.0, 1.0), 2.0);\n      float spe = pow (clamp (dot (ref, lig), 0.0, 1.0), 16.0);\n\n      // dif *= softshadow (pos, lig, 0.02, 2.5);\n      // dom *= softshadow( pos, ref, 0.02, 2.5 );\n\n      vec3 lin = vec3 (0.0);\n      lin += 1.20 * dif * vec3 (1.00, 0.85, 0.55);\n      lin += 1.20 * spe * vec3 (1.00, 0.85, 0.55) * dif;\n      lin += 0.20 * amb * vec3 (0.50, 0.70, 1.00) * occ;\n      lin += 0.30 * dom * vec3 (0.50, 0.70, 1.00) * occ;\n      lin += 0.30 * bac * vec3 (0.25, 0.25, 0.25) * occ;\n      lin += 0.40 * fre * vec3 (1.00, 1.00, 1.00) * occ;\n      col = col * lin;\n    }\n\n    return vec3 (clamp (col, 0.0, 1.0));\n  }\n\n  mat3 setCamera (in vec3 ro, in vec3 ta, float cr)\n  {\n    vec3 cw = normalize (ta - ro);\n    vec3 cp = vec3 (sin (cr), cos (cr), 0.0);\n    vec3 cu = normalize (cross (cw, cp));\n    vec3 cv = normalize (cross (cu, cw));\n    return mat3 (cu, cv, cw);\n  }\n\n  vec2 intersectBox (in vec3 theOrigin, in vec3 theDirect, in vec3 theMinPnt, in vec3 theMaxPnt)\n  {\n    vec3 aTimeBoxMin = (theMinPnt - theOrigin) * (1.f / theDirect);\n    vec3 aTimeBoxMax = (theMaxPnt - theOrigin) * (1.f / theDirect);\n\n    vec3 aTimeMax = max (aTimeBoxMin, aTimeBoxMax);\n    vec3 aTimeMin = min (aTimeBoxMin, aTimeBoxMax);\n\n    float aTime1 = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));\n    float aTime2 = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));\n\n    return aTime1 > aTime2 || aTime2 < 0.f ?\n           vec2 (MAXFLOAT) : vec2 (max (aTime1, 0.f), aTime2);\n  }\n\n  void main()\n  {\n\n    vec2 p = vPixel;\n    p.x *= iResolution.x / iResolution.y;\n\n    float time = 15.0f + iGlobalTime;\n\n    // camera\n    vec3 ta = (iBoundsMin + iBoundsMax) * 0.5f;\n    float R = iCameraDistance;\n    vec3 ro = ta + vec3 (R * cos (0.1f * time + iCameraAngle),\n                         R * 0.5f,\n                         R * sin (0.1f * time + iCameraAngle));\n\n    // camera-to-world transformation\n    mat3 ca = setCamera (ro, ta, 0.0f);\n\n    // ray direction\n    vec3 rd = ca * normalize (vec3 (p.xy, 2.0f));\n\n    vec2 aRange = intersectBox (ro, rd, iBoundsMin, iBoundsMax);\n\n    // render\n    vec3 col = render (ro, rd, aRange);\n\n    col = pow (col, vec3 (0.4545f));\n\n    gl_FragColor = vec4 (col, 1.0f);\n  }\n\n);\n\n#define MAXFLOAT 1.0e15f\n\nnamespace\n{\n  float evalPrimitiveDistance (const Vec4f& thePos, CsgPrimitiveNode* theNode)\n  {\n    float aDistance = MAXFLOAT;\n    Vec3f aScaling;\n\n    Mat4f aMatWithoutScale = theNode->Transform();\n    for (int i = 0; i < 3; ++i)\n    {\n      float aScaleI = aMatWithoutScale.col (i).head<3>().norm();\n      aScaling[i] = aScaleI;\n      aMatWithoutScale.col (i).head<3>() *= 1.f / aScaleI;\n    }\n\n    Vec4f aTransformedPos = aMatWithoutScale.inverse() * thePos;\n    aTransformedPos /= aTransformedPos.w();\n    const Vec3f& aPoint = aTransformedPos.head<3>();\n\n    switch (theNode->TypeID())\n    {\n      case CSG_SPHERE:\n      {\n        aDistance = aPoint.norm() - aScaling.x(); // only uniform scaling for spheres\n        break;\n      }\n      case CSG_BOX:\n      {\n        Vec3f d = aPoint.cwiseAbs() - aScaling;\n        aDistance = std::min (std::max (d.x(), std::max (d.y(), d.z())), 0.f)\n                      + (d.cwiseMax (Vec3f (0.f, 0.f, 0.f))).norm();\n        break;\n      }\n    }\n\n    return aDistance;\n  }\n\n  float evalDistance (const Vec4f& thePos, CsgNode* theNode)\n  {\n    if (theNode->IsLeaf())\n    {\n      return evalPrimitiveDistance (thePos, static_cast<CsgPrimitiveNode*> (theNode));\n    }\n\n    float aDistance = MAXFLOAT;\n    CsgOperationNode* anOpNode = static_cast<CsgOperationNode*> (theNode);\n\n    switch (theNode->TypeID())\n    {\n      case CSG_OP_UNION:\n      {\n        aDistance = std::min (evalDistance (thePos, anOpNode->Child<0>()),\n                              evalDistance (thePos, anOpNode->Child<1>()));\n        break;\n      }\n      case CSG_OP_INTER:\n      {\n        aDistance = std::max (evalDistance (thePos, anOpNode->Child<0>()),\n                              evalDistance (thePos, anOpNode->Child<1>()));\n        break;\n      }\n      case CSG_OP_MINUS:\n      {\n        aDistance = std::max ( evalDistance (thePos, anOpNode->Child<0>()),\n                              -evalDistance (thePos, anOpNode->Child<1>()));\n        break;\n      }\n    }\n\n    return aDistance;\n  }\n\n  static const GLfloat aQuadVertices[] = { -1.f, -1.f,  0.f,\n                                           -1.f,  1.f,  0.f,\n                                            1.f,  1.f,  0.f,\n                                            1.f,  1.f,  0.f,\n                                            1.f, -1.f,  0.f,\n                                           -1.f, -1.f,  0.f\n                                         };\n\n  static void errorCallback (int error, const char* description)\n  {\n    fprintf (stderr, \"Error %d: %s\\n\", error, description);\n  }\n}\n\nint main (int, char**)\n{\n  // Setup window\n  glfwSetErrorCallback (errorCallback);\n\n  if (!glfwInit())\n  {\n    return 1;\n  }\n\n  // Load CSG-tree\n  auto aExtTrsf = Eigen::Scaling (1.0f) * Eigen::AngleAxisf (M_PI * 0.5f, Vec3f (1.f, 0.f, 0.f));\n  Eigen::Affine3f aSphereTransform = aExtTrsf * Eigen::Translation3f (0.f, 0.4f, 0.f) * Eigen::Scaling (0.35f);\n  Eigen::Affine3f aBoxTransform;\n  aBoxTransform = aExtTrsf * Eigen::Translation3f (0.f, -0.1f, 0.f) * Eigen::Scaling (0.5f, 0.2f, 0.4f);\n\n  // std::unique_ptr<CsgNode> aTree (new CsgOperationNode (CSG_OP_UNION,\n  //   new CsgPrimitiveNode (CSG_SPHERE, aSphereTransform.matrix()),\n  //   new CsgPrimitiveNode (CSG_BOX, aBoxTransform.matrix())));\n\n  json11::Json aData = csg::Parser::parse (\"sample_cubes.csg\");\n\n  std::unique_ptr<CsgNode> aTree (CsgLoader::LoadTree (aData));\n\n  aTree->InitializeBounds();\n\n  // Init distance field\n  VoxelData aDistanceFiled (84, 84, 84,\n                            aTree->Bounds().CornerMin(),\n                            aTree->Bounds().CornerMax());\n\n  const float aMinPointX = aDistanceFiled.MinCorner.x() + 0.5f * aDistanceFiled.CellSize.x();\n  const float aMinPointY = aDistanceFiled.MinCorner.y() + 0.5f * aDistanceFiled.CellSize.y();\n  const float aMinPointZ = aDistanceFiled.MinCorner.z() + 0.5f * aDistanceFiled.CellSize.z();\n\n  std::cout << aDistanceFiled.MinCorner.transpose() << std::endl;\n  std::cout << aDistanceFiled.MaxCorner.transpose() << std::endl;\n\n  Vec4f aQuery (0.f, 0.f, 0.f, 1.f);\n\n  for (int aX = 0; aX < aDistanceFiled.SizeX; ++aX)\n  {\n    aQuery[0] = aMinPointX + aX * aDistanceFiled.CellSize.x();\n\n    for (int aY = 0; aY < aDistanceFiled.SizeY; ++aY)\n    {\n      aQuery[1] = aMinPointY + aY * aDistanceFiled.CellSize.y();\n\n      for (int aZ = 0; aZ < aDistanceFiled.SizeZ; ++aZ)\n      {\n        aQuery[2] = aMinPointZ + aZ * aDistanceFiled.CellSize.z();\n\n        aDistanceFiled.Value (aX, aY, aZ) = evalDistance (aQuery, aTree.get());\n      }\n    }\n  }\n\n  // Setup window\n  GLFWwindow* aWindow = glfwCreateWindow (1280, 720, \"csgviewer\", NULL, NULL);\n  glfwMakeContextCurrent (aWindow);\n\n  // Setup ImGui\n  ImGui_ImplGlfw_Init (aWindow, true);\n\n  bool show_test_window = false;\n  ImVec4 clear_color = ImColor (114, 144, 154);\n\n  ShaderProgram aProgram (vs_str, fs_str);\n\n  if (!aProgram.infoLog().empty())\n  {\n    std::cout << aProgram.infoLog() << std::endl;\n  }\n\n  // Init 1-component 3D texture\n  Texture3D aDistFieldTexture (1);\n\n  aDistFieldTexture.SetFiltering (TextureFilterMode (GL_LINEAR, GL_LINEAR));\n\n  if (!aDistFieldTexture.Init (aDistanceFiled.SizeX,\n                               aDistanceFiled.SizeY,\n                               aDistanceFiled.SizeZ,\n                               aDistanceFiled.Data))\n  {\n    return 1;\n  }\n\n  const float aSceneRadius = (aDistanceFiled.MaxCorner - aDistanceFiled.MinCorner).norm();\n  float aSceneEpsilon = aSceneRadius * 1e-3f;\n  float aCameraAngle = 0.f;\n  float aCameraDistance = aSceneRadius;\n  float aCamDistFactor = 1.f;\n  double aLastMouseX = -1.0, aLastMouseY = -1.0;\n\n  // Setup screen-quad VBO\n  GLuint aScreenQuadVbo;\n  glGenBuffers (1, &aScreenQuadVbo);\n  glBindBuffer (GL_ARRAY_BUFFER, aScreenQuadVbo);\n  glBufferData (GL_ARRAY_BUFFER, sizeof (GLfloat) * 3 * 6, aQuadVertices, GL_STATIC_DRAW);\n  glBindBuffer (GL_ARRAY_BUFFER, 0);\n\n  // Main loop\n  while (!glfwWindowShouldClose (aWindow))\n  {\n    glfwPollEvents();\n    ImGui_ImplGlfw_NewFrame();\n\n    ImGuiIO& io = ImGui::GetIO();\n\n    if (!io.WantCaptureMouse)\n    {\n      if (io.MouseDown[0])\n      {\n        double aMouseX, aMouseY;\n        glfwGetCursorPos (aWindow, &aMouseX, &aMouseY);\n\n        if (aLastMouseX >= 0.0)\n        {\n          aCameraAngle += (aMouseX - aLastMouseX) * 0.03f;\n        }\n\n        aLastMouseX = aMouseX;\n        aLastMouseY = aMouseY;\n      }\n      else\n      {\n        aLastMouseX = -1.0;\n      }\n    }\n\n    {\n      if (ImGui::Button (\"Test Window\"))\n      {\n        show_test_window ^= 1;\n      }\n\n      ImGui::DragFloat (\"Scene epsilon\", &aSceneEpsilon, 1e-4f);\n\n      // Camera angle slider\n      ImGui::DragFloat (\"Camera angle\", &aCameraAngle, 0.0f, 3.141592f);\n\n      ImGui::SliderFloat (\"Camera zoom\", &aCamDistFactor, 0.1f, 3.f);\n      ImGui::Text (\"Camera distance: %f\", aCameraDistance * aCamDistFactor);\n\n      ImGui::Text (\"Application average %.3f ms/frame (%.1f FPS)\", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n    }\n\n    if (show_test_window)\n    {\n      ImGui::SetNextWindowPos (ImVec2 (650, 20), ImGuiSetCond_FirstUseEver);\n      ImGui::ShowTestWindow (&show_test_window);\n    }\n\n    // Rendering\n    int aDisplayWidth, aDisplayHeight;\n    glfwGetFramebufferSize (aWindow, &aDisplayWidth, &aDisplayHeight);\n    glViewport (0, 0, aDisplayWidth, aDisplayHeight);\n    glClear (GL_COLOR_BUFFER_BIT);\n\n    // Draw screen quad\n    glUseProgram (aProgram.programId());\n\n    // Set uniforms\n    glUniform3f (glGetUniformLocation (aProgram.programId(), \"iResolution\"), aDisplayWidth, aDisplayHeight, 0.f);\n    glUniform1f (glGetUniformLocation (aProgram.programId(), \"iGlobalTime\"), glfwGetTime());\n    glUniform1f (glGetUniformLocation (aProgram.programId(), \"iCameraAngle\"), aCameraAngle);\n    glUniform1f (glGetUniformLocation (aProgram.programId(), \"iCameraDistance\"), aCameraDistance * aCamDistFactor);\n    glUniform1ui (glGetUniformLocation (aProgram.programId(), \"iDistanceTexture\"), 0u);\n    glUniform3fv (glGetUniformLocation (aProgram.programId(), \"iBoundsMin\"), 1, reinterpret_cast<GLfloat*> (&aDistanceFiled.MinCorner));\n    glUniform3fv (glGetUniformLocation (aProgram.programId(), \"iBoundsMax\"), 1, reinterpret_cast<GLfloat*> (&aDistanceFiled.MaxCorner));\n    glUniform1f (glGetUniformLocation (aProgram.programId(), \"iSceneRadius\"), aSceneRadius);\n    glUniform1f (glGetUniformLocation (aProgram.programId(), \"iSceneEpsilon\"), aSceneEpsilon);\n\n    aDistFieldTexture.Bind (GL_TEXTURE0);\n    glBindBuffer (GL_ARRAY_BUFFER, aScreenQuadVbo);\n    glEnableClientState (GL_VERTEX_ARRAY);\n    glVertexPointer (3, GL_FLOAT, 0, NULL);\n    glDrawArrays (GL_TRIANGLES, 0, 6);\n    glDisableClientState (GL_VERTEX_ARRAY);\n    glBindBuffer (GL_ARRAY_BUFFER, 0);\n    aDistFieldTexture.Unbind (GL_TEXTURE0);\n    glUseProgram (0);\n\n    // Draw ImGui stuff\n    glActiveTexture (GL_TEXTURE0);\n    ImGui::Render();\n    glfwSwapBuffers (aWindow);\n  }\n\n  glDeleteBuffers (1, &aScreenQuadVbo);\n\n  // Cleanup\n  ImGui_ImplGlfw_Shutdown();\n  glfwTerminate();\n\n  return 0;\n}\n", "meta": {"hexsha": "dcbbc5d4f3c50ae91de2f5cfc49ab281d3fc1bcf", "size": 15640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/csgviewer.cpp", "max_stars_repo_name": "hb3p8/csg-tools", "max_stars_repo_head_hexsha": "d6b2734620ec7c381c2c7fd36fdb6393d6ec3663", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-10T13:44:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-01T08:45:23.000Z", "max_issues_repo_path": "src/csgviewer.cpp", "max_issues_repo_name": "hb3p8/csg-tools", "max_issues_repo_head_hexsha": "d6b2734620ec7c381c2c7fd36fdb6393d6ec3663", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-10-15T16:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-15T16:04:04.000Z", "max_forks_repo_path": "src/csgviewer.cpp", "max_forks_repo_name": "megaton/csg-tools", "max_forks_repo_head_hexsha": "d6b2734620ec7c381c2c7fd36fdb6393d6ec3663", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-02T04:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-02T04:48:13.000Z", "avg_line_length": 27.7304964539, "max_line_length": 136, "alphanum_fraction": 0.5808823529, "num_tokens": 5042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.017986210981971562, "lm_q1q2_score": 0.007123765601847507}}
{"text": "/*\n\nCopyright (c) 2005-2017, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef STOCHASTICWNTCELLCYCLEMODEL_HPP_\n#define STOCHASTICWNTCELLCYCLEMODEL_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"WntCellCycleModel.hpp\"\n#include \"RandomNumberGenerator.hpp\"\n\n/**\n * Wnt-dependent cell-cycle model with a stochastic G2 duration.\n *\n * Note that this class uses C++'s default copying semantics, and so\n * doesn't implement a copy constructor or operator=.\n */\nclass StochasticWntCellCycleModel : public WntCellCycleModel\n{\nprivate:\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive the object 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<WntCellCycleModel>(*this);\n\n        // Make sure the random number generator is also archived\n        SerializableSingleton<RandomNumberGenerator>* p_rng_wrapper = RandomNumberGenerator::Instance()->GetSerializationWrapper();\n        archive & p_rng_wrapper;\n\n        archive & mStochasticG2Duration;\n    }\n\n    /** The duration of the G2 phase, set stochastically. */\n    double mStochasticG2Duration;\n\n    /**\n     * This method introduces the stochastic element of this class.\n     *\n     * We allow the duration of the G2 phase of the cell cycle to\n     * vary as a normal random deviate with a mean of its deterministic\n     * duration, a standard deviation of 0.9 hours, and a cutoff to\n     * ensure that it is greater than some minimum value.\n     *\n     */\n    void GenerateStochasticG2Duration();\n\nprotected:\n\n    /**\n     * Protected copy-constructor for use by CreateCellCycleModel.\n     * The only way for external code to create a copy of a cell cycle model\n     * is by calling that method, to ensure that a model of the correct subclass is created.\n     * This copy-constructor helps subclasses to ensure that all member variables are correctly copied when this happens.\n     *\n     * This method is called by child classes to set member variables for a daughter cell upon cell division.\n     * Note that the parent cell cycle model will have had ResetForDivision() called just before CreateCellCycleModel() is called,\n     * so performing an exact copy of the parent is suitable behaviour. Any daughter-cell-specific initialisation\n     * can be done in InitialiseDaughterCell().\n     *\n     * @param rModel the cell cycle model to copy.\n     */\n    StochasticWntCellCycleModel(const StochasticWntCellCycleModel& rModel);\n\npublic:\n    /**\n     * The standard constructor called in tests.\n     *\n     * @param pOdeSolver An optional pointer to a cell-cycle model ODE solver object (allows the use of different ODE solvers)\n     */\n    StochasticWntCellCycleModel(boost::shared_ptr<AbstractCellCycleModelOdeSolver> pOdeSolver = boost::shared_ptr<AbstractCellCycleModelOdeSolver>());\n\n    /** Empty virtual destructor so archiving works with static libraries. */\n    virtual ~StochasticWntCellCycleModel();\n\n    /**\n     * Overridden builder method to create new copies of\n     * this cell-cycle model.\n     *\n     * @return the new cell-cycle model\n     */\n    AbstractCellCycleModel* CreateCellCycleModel();\n\n    /**\n     * Set the duration of the G2 phase for the daughter cell.\n     */\n    void InitialiseDaughterCell();\n\n    /**\n     * Initialise the cell-cycle model at the start of a simulation.\n     *\n     * This overridden method sets up a new WntCellCycleOdeSystem,\n     * sets the cell type according to the current beta catenin level\n     * and sets a random G2 duration.\n     */\n    void Initialise();\n\n    /**\n     * Reset cell-cycle model by calling AbstractOdeBasedPhaseBasedCellCycleModel::ResetForDivision()\n     * and setting a new random G2 duration.\n     */\n    void ResetForDivision();\n\n    /**\n     * @return the duration of the G2 phase.\n     */\n    double GetG2Duration() const;\n\n    /**\n     * Overridden OutputCellCycleModelParameters() method.\n     *\n     * @param rParamsFile the file stream to which the parameters are output\n     */\n    virtual void OutputCellCycleModelParameters(out_stream& rParamsFile);\n};\n\n// Declare identifier for the serializer\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(StochasticWntCellCycleModel)\n#include \"CellCycleModelOdeSolverExportWrapper.hpp\"\nEXPORT_CELL_CYCLE_MODEL_ODE_SOLVER(StochasticWntCellCycleModel)\n\n#endif /*STOCHASTICWNTCELLCYCLEMODEL_HPP_*/\n", "meta": {"hexsha": "cd5f9f22a14faeb55b432e665abe723d886a688e", "size": 6280, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crypt/src/cell/cycle/StochasticWntCellCycleModel.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "crypt/src/cell/cycle/StochasticWntCellCycleModel.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crypt/src/cell/cycle/StochasticWntCellCycleModel.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0606060606, "max_line_length": 150, "alphanum_fraction": 0.7417197452, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.01941934995589521, "lm_q1q2_score": 0.007118934379879371}}
{"text": "/*\n * The MIT License\n *\n * Copyright (c) 2012-2018 The University of Utah\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\n#include \"ConvectiveInterpolationMethods.h\"\n\n#include <boost/bimap.hpp>\n\n#include <stdexcept>\n#include <sstream>\n\nnamespace WasatchCore {\n\n  typedef boost::bimap<std::string,ConvInterpMethods> ConvInterpStringMap;\n  static ConvInterpStringMap validConvInterpStrings;\n\n  void set_conv_interp_string_map()\n  {\n    if( !validConvInterpStrings.empty() ) return;\n    typedef ConvInterpStringMap::left_value_type LVT;\n    validConvInterpStrings.left.insert( LVT(\"CENTRAL\" , CENTRAL ) );\n    validConvInterpStrings.left.insert( LVT(\"UPWIND\"  , UPWIND  ) );\n    validConvInterpStrings.left.insert( LVT(\"SUPERBEE\", SUPERBEE) );\n    validConvInterpStrings.left.insert( LVT(\"CHARM\"   , CHARM   ) );\n    validConvInterpStrings.left.insert( LVT(\"KOREN\"   , KOREN   ) );\n    validConvInterpStrings.left.insert( LVT(\"MC\"      , MC      ) );\n    validConvInterpStrings.left.insert( LVT(\"OSPRE\"   , OSPRE   ) );\n    validConvInterpStrings.left.insert( LVT(\"SMART\"   , SMART   ) );\n    validConvInterpStrings.left.insert( LVT(\"VANLEER\" , VANLEER ) );\n    validConvInterpStrings.left.insert( LVT(\"HCUS\"    , HCUS    ) );\n    validConvInterpStrings.left.insert( LVT(\"MINMOD\"  , MINMOD  ) );\n    validConvInterpStrings.left.insert( LVT(\"HQUICK\"  , HQUICK  ) );\n  }\n\n  //------------------------------------------------------------------\n\n  ConvInterpMethods get_conv_interp_method( std::string key )\n  {\n    set_conv_interp_string_map();\n    std::transform( key.begin(), key.end(), key.begin(), ::toupper );\n    ConvInterpStringMap::left_const_iterator ii = validConvInterpStrings.left.find(key);\n    if( ii == validConvInterpStrings.left.end() ){\n      std::ostringstream msg;\n      msg << __FILE__ << \" : \" << __LINE__ << std::endl\n          << \"No matching upwind method for '\" << key << \"'\" << std::endl;\n    }\n    return ii->second;\n  }\n\n  std::string get_conv_interp_method( const ConvInterpMethods key )\n  {\n    set_conv_interp_string_map();\n    return validConvInterpStrings.right.find(key)->second;\n  }\n\n} // namespace WasatchCore\n", "meta": {"hexsha": "dab6cce6b96889b739622ca1c6437445535bc207", "size": 3174, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/CCA/Components/Wasatch/ConvectiveInterpolationMethods.cc", "max_stars_repo_name": "damu1000/Uintah", "max_stars_repo_head_hexsha": "0c768664c1fe0a80eff2bbbd9b837e27f281f0a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T08:21:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T18:33:16.000Z", "max_issues_repo_path": "src/CCA/Components/Wasatch/ConvectiveInterpolationMethods.cc", "max_issues_repo_name": "damu1000/Uintah", "max_issues_repo_head_hexsha": "0c768664c1fe0a80eff2bbbd9b837e27f281f0a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CCA/Components/Wasatch/ConvectiveInterpolationMethods.cc", "max_forks_repo_name": "damu1000/Uintah", "max_forks_repo_head_hexsha": "0c768664c1fe0a80eff2bbbd9b837e27f281f0a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-30T05:48:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-12T16:24:16.000Z", "avg_line_length": 41.2207792208, "max_line_length": 88, "alphanum_fraction": 0.6994328922, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993079883920791, "lm_q2_score": 0.035678552543951185, "lm_q1q2_score": 0.007111020536276007}}
{"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\nnamespace boost\r\n{\r\n\r\nnamespace detail\r\n{\r\n    enum planar_canonical_ordering_state\r\n    {\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\r\ntemplate < typename Graph, typename PlanarEmbedding, typename OutputIterator,\r\n    typename VertexIndexMap >\r\nvoid planar_canonical_ordering(const Graph& g, PlanarEmbedding embedding,\r\n    OutputIterator ordering, 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\r\n        typename graph_traits< Graph >::adjacency_iterator adjacency_iterator_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< typename std::vector< vertex_t >::iterator,\r\n        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(\r\n        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 = first_vertex;\r\n    adjacency_iterator_t ai, ai_end;\r\n    for (boost::tie(ai, ai_end) = adjacent_vertices(first_vertex, g);\r\n         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\r\n            && 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\r\n                = 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)\r\n                : source(*prior_edge_itr, g);\r\n            vertex_t next_vertex = source(*next_edge_itr, g) == u\r\n                ? target(*next_edge_itr, g)\r\n                : 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\r\n                    : boost::next(next_edge_itr);\r\n                next_vertex = source(*next_edge_itr, g) == u\r\n                    ? target(*next_edge_itr, g)\r\n                    : source(*next_edge_itr, g);\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                    || (prior_vertex == x\r\n                        && !(first_vertex == x && second_vertex == u)))\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            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        status[u] = detail::PCO_PROCESSED;\r\n        *ordering = u;\r\n        ++ordering;\r\n    }\r\n}\r\n\r\ntemplate < typename Graph, typename PlanarEmbedding, typename OutputIterator >\r\nvoid planar_canonical_ordering(\r\n    const Graph& g, PlanarEmbedding embedding, OutputIterator ordering)\r\n{\r\n    planar_canonical_ordering(g, embedding, ordering, get(vertex_index, g));\r\n}\r\n\r\n} // namespace boost\r\n\r\n#endif //__PLANAR_CANONICAL_ORDERING_HPP__\r\n", "meta": {"hexsha": "151726d7e3aa39ce1e0a21c3aa65ba0cbd9f5b47", "size": 7407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/planar_canonical_ordering.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/planar_canonical_ordering.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/planar_canonical_ordering.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.1317073171, "max_line_length": 81, "alphanum_fraction": 0.566491157, "num_tokens": 1593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220561778540017, "lm_q2_score": 0.029312230857352094, "lm_q1q2_score": 0.007099586983473234}}
{"text": "#ifndef STAN_MATH_TORSTEN_EVENT_HISTORY_HPP\n#define STAN_MATH_TORSTEN_EVENT_HISTORY_HPP\n\n#include <iomanip>\n#include <stan/math/torsten/return_type.hpp>\n#include <stan/math/prim/scal/err/check_greater_or_equal.hpp>\n#include <stan/math/torsten/PKModel/functions.hpp>\n#include <stan/math/torsten/pk_nsys.hpp>\n#include <Eigen/Dense>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\nnamespace torsten {\n\n  /**\n   * The EventHistory class defines objects that contain a vector of Events,\n   * along with a series of functions that operate on them.\n   */\n  template<typename T0, typename T1, typename T2, typename T3, typename T4_container, typename T5, typename T6>\n  struct EventHistory {\n    using T4 = typename stan::math::value_type<T4_container>::type;\n    using T_scalar = typename torsten::return_t<T0, T1, T2, T3, T4, T5, T6>::type;\n    using T_time = typename torsten::return_t<T0, T1, T3, T6, T2>::type;\n    using T_rate = typename torsten::return_t<T2, T5>::type;\n    using T_amt = typename torsten::return_t<T1, T5>::type;\n    using Param = std::pair<double, std::array<int, 3> >;\n    using rate_t = std::pair<double, std::vector<T2> >;\n\n    const std::vector<T0>& time_;\n    const std::vector<T1>& amt_;\n    const std::vector<T2>& rate_;\n    const std::vector<T3>& ii_;\n    const std::vector<int>& evid_;\n    const std::vector<int>& cmt_;\n    const std::vector<int>& addl_;\n    const std::vector<int>& ss_;\n\n    std::vector<Param> param_index;\n    const std::vector<T4_container>& theta_;\n    const std::vector<std::vector<T5> >& biovar_;\n    const std::vector<std::vector<T6> >& tlag_;\n\n    // internally generated events\n    const size_t num_event_times;\n    std::vector<T_time> gen_time;\n    std::vector<T1> gen_amt;\n    std::vector<T2> gen_rate;\n    std::vector<T3> gen_ii;\n    std::vector<int> gen_cmt;\n    std::vector<int> gen_addl;\n    std::vector<int> gen_ss;\n\n    using IDVec = std::array<int, 7>;\n    // 0: original(0)/generated(1)\n    // 1: index in original/generated arrays\n    // 2: evid\n    // 3: is new?(0/1)\n    // 4: theta id\n    // 5: biovar id\n    // 6: tlag id\n    std::vector<IDVec> index;\n\n    // rate at distinct time\n    std::vector<rate_t> rates;\n    std::vector<int> rate_index;\n\n    inline bool keep(const IDVec& id)  const { return id[0] == 0; }\n    inline bool isnew(const IDVec& id) const { return id[3] == 1; }\n    inline int evid (const IDVec& id) const { return id[2] ; }\n\n    inline bool keep(int i)  const { return keep(index[i]); }\n    inline bool isnew(int i) const { return isnew(index[i]); }\n    inline int evid (int i) const { return evid(index[i]); }\n\n    /*\n     * for a population with data in ragged array form, we\n     * form the events history using the population data and\n     * the location of the individual in the ragged arrays.\n     * In this constructor we assume @c p_ii.size() > 1 and\n     * @c p_ss.size() > 1.\n     */\n    EventHistory(int ncmt, int ibegin, int isize,\n                 const std::vector<T0>& p_time, const std::vector<T1>& p_amt,\n                 const std::vector<T2>& p_rate, const std::vector<T3>& p_ii,\n                 const std::vector<int>& p_evid, const std::vector<int>& p_cmt,\n                 const std::vector<int>& p_addl, const std::vector<int>& p_ss,\n                 int ibegin_theta, int isize_theta,\n                 const std::vector<T4_container>& theta,\n                 int ibegin_biovar, int isize_biovar,\n                 const std::vector<std::vector<T5> >& biovar,\n                 int ibegin_tlag, int isize_tlag,\n                 const std::vector<std::vector<T6> >& tlag) :\n      time_(p_time),\n      amt_(p_amt),\n      rate_(p_rate),\n      ii_(p_ii),\n      evid_(p_evid),\n      cmt_(p_cmt),\n      addl_(p_addl),\n      ss_(p_ss),\n      param_index(isize),\n      theta_(theta),\n      biovar_(biovar),\n      tlag_(tlag),\n      num_event_times(isize),\n      index(isize, {0, 0, 0, 0, ibegin_theta, ibegin_biovar, ibegin_tlag})\n    {\n      const int iend = ibegin + isize;\n      using stan::math::check_greater_or_equal;\n      static const char* caller = \"EventHistory::EventHistory\";\n      check_greater_or_equal(caller, \"isize\", isize , 1);\n      check_greater_or_equal(caller, \"time size\", p_time.size() , size_t(iend));\n      check_greater_or_equal(caller, \"amt size\", p_amt.size()   , size_t(iend));\n      check_greater_or_equal(caller, \"rate size\", p_rate.size() , size_t(iend));\n      check_greater_or_equal(caller, \"ii size\", p_ii.size()     , size_t(iend));\n      check_greater_or_equal(caller, \"evid size\", p_evid.size() , size_t(iend));\n      check_greater_or_equal(caller, \"cmt size\", p_cmt.size()   , size_t(iend));\n      check_greater_or_equal(caller, \"addl size\", p_addl.size() , size_t(iend));\n      check_greater_or_equal(caller, \"ss size\", p_ss.size()     , size_t(iend));\n      for (size_t i = 0; i < isize; ++i) {\n        index[i][1] = ibegin + i;\n        index[i][2] = evid_[ibegin + i];\n        index[i][4] = isize_theta   > 1 ? ibegin_theta  + i : ibegin_theta;\n        index[i][5] = isize_biovar  > 1 ? ibegin_biovar + i : ibegin_biovar;\n        index[i][6] = isize_tlag    > 1 ? ibegin_tlag   + i : ibegin_tlag;\n      }\n      insert_addl_dose();\n      sort_state_time();\n\n      for (int i = 0; i < isize; ++i) {\n        int j = isize_theta   > 1 ? ibegin_theta  + i : ibegin_theta;\n        int k = isize_biovar  > 1 ? ibegin_biovar + i : ibegin_biovar;\n        int l = isize_tlag    > 1 ? ibegin_tlag   + i : ibegin_tlag;\n        param_index[i] = std::make_pair<double, std::array<int, 3> >(stan::math::value_of(time_[ibegin + i]), {j, k, l });\n      }\n      param_sort();\n\n      attach_event_parameters();\n      insert_lag_dose();\n      generate_rates(ncmt);\n      attach_event_parameters();\n    }\n\n    EventHistory(int ncmt,\n                 const std::vector<T0>& p_time, const std::vector<T1>& p_amt,\n                 const std::vector<T2>& p_rate, const std::vector<T3>& p_ii,\n                 const std::vector<int>& p_evid, const std::vector<int>& p_cmt,\n                 const std::vector<int>& p_addl, const std::vector<int>& p_ss,\n                 const std::vector<T4_container>& theta,\n                 const std::vector<std::vector<T5> >& biovar,\n                 const std::vector<std::vector<T6> >& tlag)\n    : EventHistory(ncmt,\n                   0, p_time.size(), p_time, p_amt, p_rate, p_ii, p_evid, p_cmt, p_addl, p_ss,\n                   0, theta.size(), theta,\n                   0, biovar.size(), biovar,\n                   0, tlag.size(), tlag)\n    {}\n\n    void attach_event_parameters() {\n      int nEvent = num_state_times();\n      assert(nEvent > 0);\n      int len_Parameters = param_index.size();  // numbers of events for which parameters are determined\n      assert(len_Parameters > 0);\n\n      if (!param_check()) param_sort();\n      param_index.resize(nEvent);\n\n      int iEvent = 0;\n      for (int i = 0; i < len_Parameters - 1; i++) {\n        while (isnew(iEvent)) iEvent++;  // skip new events\n        assert(std::get<0>(param_index[i]) == time(iEvent));  // compare time of \"old' events to time of parameters.\n        iEvent++;\n      }\n\n      if (len_Parameters == 1)  {\n        for (int i = 0; i < nEvent; i++) {\n          param_index[i] = std::make_pair<double, std::array<int, 3> >(stan::math::value_of(time(i)) , std::array<int,3>(std::get<1>(param_index[0])));\n          index[i][3] = 0;\n        }\n      } else {  // parameters are event dependent.\n        std::vector<double> times(nEvent, 0);\n        for (int i = 0; i < nEvent; i++) times[i] = param_index[i].first;\n        iEvent = 0;\n\n        Param newParameter;\n        int j = 0;\n        std::vector<Param>::const_iterator lower = param_index.begin();\n        std::vector<Param>::const_iterator it_param_end = param_index.begin() + len_Parameters;\n        for (int iEvent = 0; iEvent < nEvent; ++iEvent) {\n          if (isnew(iEvent)) {\n            // Find the index corresponding to the time of the new event in the\n            // times vector.\n            const double t = stan::math::value_of(time(iEvent));\n            lower = std::lower_bound(lower, it_param_end, t,\n                                     [](const Param& t1, const double& t2) {return t1.first < t2;});\n            newParameter = lower == (it_param_end) ? param_index[len_Parameters-1] : *lower;\n            newParameter.first = t;\n            param_index[len_Parameters + j] = newParameter;\n            index[iEvent][3] = 0;\n            j++;\n          }\n        }\n      }\n      param_sort();\n    }\n\n    bool is_reset(int i) const {\n      return evid(i) == 3 || evid(i) == 4;\n    }\n\n    bool is_reset_event(const IDVec& id) {\n      return evid(id) == 3 || evid(id) == 4;\n    }\n\n    bool is_dosing(int i) const {\n      return evid(i) == 1 || evid(i) == 4;\n    }\n    \n    bool is_log_sum_exp_dosing(int i) const {\n      return evid(i) == 11;\n    }\n\n    /*\n     * if an event is steady-state dosing event.\n     */\n    bool is_ss_dosing(int i) const {\n      return (is_dosing(i) && (ss(i) == 1 || ss(i) == 2)) || ss(i) == 3;\n    }\n\n    static bool is_dosing(const std::vector<int>& event_id, int i) {\n      return event_id[i] == 1 || event_id[i] == 4;\n    }\n\n    bool is_bolus_dosing(int i) const {\n      const double eps = 1.0E-12;\n      return is_dosing(i) && rate(i) < eps;\n    }\n\n    /*\n     * use current event #i as template to @c push_back to\n     * another event.\n     */\n    void insert_event(int i) {\n      index.push_back({1, int(gen_time.size()), index[i][2], 1, index[i][4], index[i][5], index[i][6]});\n      gen_time. push_back(time (i));\n      gen_amt.  push_back(amt  (i));\n      gen_rate. push_back(rate (i));\n      gen_ii.   push_back(ii   (i));\n      gen_cmt.  push_back(cmt  (i));\n      gen_addl. push_back(addl (i));\n      gen_ss.   push_back(ss   (i));\n    }\n\n    /**\n     * Add events to EventHistory object, corresponding to additional dosing,\n     * administered at specified inter-dose interval. This information is stored\n     * in the addl and ii members of the EventHistory object.\n     *\n     * Events is sorted at the end of the procedure.\n     */\n    void insert_addl_dose() {\n      for (int i = 0; i < num_state_times(); i++) {\n        if (is_dosing(i) && ((addl(i) > 0) && (ii(i) > 0))) {\n          for (int j = 1; j <= addl(i); j++) {\n            insert_event(i);\n            gen_time.back() += j * ii(i);\n            gen_ii.back() = 0;\n            gen_addl.back() = 0;\n            gen_ss.back() = 0;\n          }\n        }\n      }\n    }\n\n    /*\n     * sort PMX events and nonevents times\n     */\n    void sort_state_time() { std::stable_sort(index.begin(), index.end(),\n                                              [this](const IDVec &a, const IDVec &b) {\n                                                using stan::math::value_of;\n                                                double ta = keep(a) ? value_of(time_[a[1]]) : value_of(gen_time[a[1]]);\n                                                double tb = keep(b) ? value_of(time_[b[1]]) : value_of(gen_time[b[1]]);\n                                                return ta < tb;\n                                              });\n    }\n\n    /*\n     * return if an event is a \"reset\" event(evid=3 or 4)\n     */\n    void param_sort() {\n      std::sort(param_index.begin(), param_index.end(),\n                [](const Param& a, const Param& b)\n                { return a.first < b.first; });\n    }\n\n    bool param_check() {\n      // check that elements are in chronological order.\n      int i = param_index.size() - 1;\n      bool ordered = true;\n\n      while (i > 0 && ordered) {\n        ordered = (param_index[i].first >= param_index[i-1].first);\n        i--;\n      }\n      return ordered;\n    }\n\n    void generate_rates(int nCmt) {\n      using std::vector;\n      using stan::math::value_of;\n\n      const int n = num_state_times();\n      for (size_t i = 0; i < n; ++i) {\n        if ((is_dosing(i)) && (rate(i) > 0 && amt(i) > 0)) {\n          insert_event(i);\n          index.back()[2] = 2;    // reset evid\n          gen_time. back() += amt(i)/rate(i);\n          gen_amt.  back() = 0;\n          gen_rate. back() = 0;\n          gen_ii.   back() = 0;\n          gen_addl. back() = 0;\n          gen_ss.   back() = 0;\n        }\n      }\n      sort_state_time();\n\n      rate_t newRate{0.0, std::vector<T2>(nCmt, 0.0)};\n      // unique_times is sorted\n      std::vector<int> ut(unique_times());\n      for (auto i : ut) {\n        newRate.first = value_of(time(i));\n        rates.push_back(newRate);\n      }\n      // check sorted?\n      std::sort(rates.begin(), rates.end(), [](rate_t const &a, rate_t const &b) {\n          return a.first < b.first;\n        });\n\n      for (size_t i = 0; i < num_state_times(); ++i) {\n        if ((is_dosing(i)) && (rate(i) > 0 && amt(i) > 0)) {\n          double t0 = value_of(time(i));\n          double t1 = t0 + value_of(amt(i)/rate(i));\n          for (auto&& r : rates) {\n            if (r.first > t0 && r.first <= t1) {\n              r.second[cmt(i) - 1] += rate(i);\n            }\n          }\n        }\n      }\n\n      /*\n       * rate index points to the rates for each state time,\n       * since there is one rates vector per time, not per event.\n       */\n      rate_index.resize(index.size());\n      int iRate = 0;\n      for (size_t i = 0; i < index.size(); ++i) {\n        if (rates[iRate].first != time(i)) iRate++;\n        rate_index[i] = iRate;\n      }\n    }\n\n    // Access functions\n    inline T_time time (const IDVec& id) const { return keep(id) ? time_[id[1]] : gen_time[id[1]] ; }\n    inline const T1& amt      (const IDVec& id) const { return keep(id) ? amt_[id[1]] : gen_amt[id[1]] ; }\n    inline const T2& rate     (const IDVec& id) const { return keep(id) ? rate_[id[1]] : gen_rate[id[1]] ; }\n    inline const T3& ii       (const IDVec& id) const { return keep(id) ? ii_[id[1]] : gen_ii[id[1]] ; }\n    inline int cmt     (const IDVec& id) const { return keep(id) ? cmt_[id[1]] : gen_cmt[id[1]] ; }\n    inline int addl    (const IDVec& id) const { return keep(id) ? addl_[id[1]] : gen_addl[id[1]] ; }\n    inline int ss      (const IDVec& id) const { return keep(id) ? ss_[id[1]] : gen_ss[id[1]] ; }\n\n    inline T_time time (int i) const { return time(index[i]); }\n    inline const T1& amt      (int i) const { return amt (index[i]); }\n    inline const T2& rate     (int i) const { return rate(index[i]); }\n    inline const T3& ii       (int i) const { return ii  (index[i]); }\n    inline int cmt     (int i) const { return cmt (index[i]); }\n    inline int addl    (int i) const { return addl(index[i]); }\n    inline int ss      (int i) const { return ss  (index[i]); }\n\n    inline size_t num_state_times() const { return index.size(); }\n\n    inline std::vector<T_rate> fractioned_rates(int i) const {\n      const int n = rates[0].second.size();\n      const std::vector<T2>& r = rates[rate_index[i]].second;\n      std::vector<T_rate> res(r.size());\n      for (size_t j = 0; j < r.size(); ++j) {\n        res[j] = r[j] * bioavailability(i, j);\n      }\n      return res;\n    }\n\n    inline T_amt fractioned_amt(int i) const {\n      return bioavailability(i, cmt(i) - 1) * amt(i);\n    }\n\n    std::vector<int> unique_times() {\n      std::vector<int> t(index.size());\n      std::iota(t.begin(), t.end(), 0);\n      auto last = std::unique(t.begin(), t.end(),\n                              [this](const int& i, const int& j) {return time(i) == time(j);});\n      t.erase(last, t.end());\n      return t;\n    }\n\n    /**\n     * Implement absorption lag times by modifying the times of the dosing events.\n     * Two cases: parameters are either constant or vary with each event.\n     * Function sorts events at the end of the procedure.\n     *\n     * @tparam T_parameters type of scalar model parameters\n     * @return - modified events that account for absorption lag times\n     */\n    void insert_lag_dose() {\n      // reverse loop so we don't process same lagged events twice\n      int nEvent = num_state_times();\n      int iEvent = nEvent - 1;\n      while (iEvent >= 0) {\n        if (is_dosing(iEvent)) {\n          if (GetValueTlag(iEvent, cmt(iEvent) - 1) != 0) {\n            insert_event(iEvent);\n            gen_time.back() += GetValueTlag(iEvent, cmt(iEvent) - 1);\n\n            // Events[iEvent].evid = 2;  // Check\n            index[iEvent][2] = 2;\n            // The above statement changes events so that CleanEvents does\n            // not return an object identical to the original. - CHECK\n          }\n        }\n        iEvent--;\n      }\n      sort_state_time();\n    }\n\n    inline const T4_container& model_param(int i) const {\n      return theta_[param_index[i].second[0]];\n    }\n\n    inline const T4& GetValue(int iEvent, int iParameter) const {\n      return theta_[std::get<1>(param_index[iEvent])[0]][iParameter];\n    }\n\n    inline const T5& bioavailability(int iEvent, int iParameter) const {\n      return biovar_[std::get<1>(param_index[iEvent])[1]][iParameter];\n    }\n\n    inline const T6& GetValueTlag(int iEvent, int iParameter) const {\n      return tlag_[std::get<1>(param_index[iEvent])[2]][iParameter];\n    }\n\n    /*\n     * Overloading the << Operator\n     */\n    friend std::ostream& operator<<(std::ostream& os, const EventHistory& ev) {\n      const int w = 6;\n      os << \"\\n\";\n      os << std::setw(w) << \"time\" <<\n        std::setw(w) << \"amt\" <<\n        std::setw(w) << \"rate\" <<\n        std::setw(w) << \"ii\" <<\n        std::setw(w) << \"evid\" <<\n        std::setw(w) << \"cmt\" <<\n        std::setw(w) << \"addl\" <<\n        std::setw(w) << \"ss\" <<\n        std::setw(w) << \"keep\" <<\n        std::setw(w) << \"isnew\" << \"\\n\";\n      for (size_t i = 0; i < ev.size(); ++i) {\n        os <<\n          std::setw(w)   << ev.time(i) << \" \" <<\n          std::setw(w-1) << ev.amt(i) << \" \" <<\n          std::setw(w-1) << ev.rate(i) << \" \" <<\n          std::setw(w-1) << ev.ii(i) << \" \" <<\n          std::setw(w-1) << ev.evid(i) << \" \" <<\n          std::setw(w-1) << ev.cmt(i) << \" \" <<\n          std::setw(w-1) << ev.addl(i) << \" \" <<\n          std::setw(w-1) << ev.ss(i) << \" \" <<\n          std::setw(w-1) << ev.keep(i) << \" \" <<\n          std::setw(w-1) << ev.isnew(i) << \"\\n\";\n      }\n      return os;\n    }\n  };\n\n}    // torsten namespace\n#endif\n", "meta": {"hexsha": "b6749dfc64f6fcdbb3216ab01bebd162fb3fdcda", "size": 18189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/event_history.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/event_history.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/event_history.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": 37.4259259259, "max_line_length": 151, "alphanum_fraction": 0.5499477706, "num_tokens": 5182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081161995, "lm_q2_score": 0.020964240397594095, "lm_q1q2_score": 0.007087529823978859}}
{"text": "#ifndef HPENFACAG_HPP_INCLUDED\n#define HPENFACAG_HPP_INCLUDED\n\n#include <vector>\n#include <string>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/deque.hpp>\n#include <caffe/util/math_functions.hpp>\n\n#include \"arch/AACAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include \"bib/OrnsteinUhlenbeckNoise.hpp\"\n#include \"bib/MetropolisHasting.hpp\"\n#include \"bib/XMLEngine.hpp\"\n#include \"bib/IniParser.hpp\"\n#include \"bib/OnlineNormalizer.hpp\"\n#include \"nn/MLP.hpp\"\n\n#ifdef PARALLEL_INTERACTION\n#include <mpi.h>\n#include <boost/mpi.hpp>\n#endif\n\n#ifndef SAASRG_SAMPLE\n#define SAASRG_SAMPLE\ntypedef struct _sample {\n  std::vector<double> s;\n  std::vector<double> goal_achieved;\n  std::vector<double> goal_achieved_unnormed;\n  std::vector<double> pure_a;\n  std::vector<double> a;\n  std::vector<double> next_s;\n  std::vector<double> next_goal_achieved_unnormed;\n  double r;\n  bool goal_reached;\n  double prob;\n  bool artificial;\n  bool interest;\n  \n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar& BOOST_SERIALIZATION_NVP(s);\n    ar& BOOST_SERIALIZATION_NVP(goal_achieved);\n    ar& BOOST_SERIALIZATION_NVP(goal_achieved_unnormed);\n    ar& BOOST_SERIALIZATION_NVP(pure_a);\n    ar& BOOST_SERIALIZATION_NVP(a);\n    ar& BOOST_SERIALIZATION_NVP(next_s);\n    ar& BOOST_SERIALIZATION_NVP(next_goal_achieved_unnormed);\n    ar& BOOST_SERIALIZATION_NVP(r);\n    ar& BOOST_SERIALIZATION_NVP(goal_reached);\n    ar& BOOST_SERIALIZATION_NVP(prob);\n    ar& BOOST_SERIALIZATION_NVP(artificial);\n    ar& BOOST_SERIALIZATION_NVP(interest);\n  }\n} sample;\n#endif\n\ntemplate<typename NN = MLP>\nclass OfflineCaclaAg : public arch::AACAgent<NN, arch::AgentGPUProgOptions> {\n public:\n  typedef NN PolicyImpl;\n\n  OfflineCaclaAg(unsigned int _nb_motors, unsigned int _nb_sensors, uint _goal_size, uint _goal_start)\n      : arch::AACAgent<NN, arch::AgentGPUProgOptions>(_nb_motors, _nb_sensors-_goal_size), nb_sensors(_nb_sensors-_goal_size), empty_action(), \n      last_state(_nb_sensors-_goal_size, 0.f), last_goal_achieved(_goal_size, 0.f), goal_size(_goal_size), goal_start(_goal_start-_goal_size),\n      normalizer(nb_sensors) {\n\n        LOG_DEBUG(\"goal size \" << goal_size);\n        LOG_DEBUG(\"goal start \" << goal_start);\n  }\n\n  virtual ~OfflineCaclaAg() {\n    if(vnn != nullptr)\n      delete vnn;\n    delete ann;\n    delete ann_noblob;\n\n    delete hidden_unit_v;\n    delete hidden_unit_a;\n    \n    if(oun == nullptr)\n      delete oun;\n  }\n\n  const std::vector<double>& _run(double reward, const std::vector<double>& sensors,\n                                  const std::vector<double>& goal_achieved, bool learning, bool as, bool) override {\n    std::vector<double> normed_sensors(nb_sensors);\n    normalizer.transform_with_double_clip(normed_sensors, sensors, false);\n    \n    // protect batch norm from testing data and poor data\n    vector<double>* next_action = ann_noblob->computeOut(normed_sensors);\n    if (last_action.get() != nullptr && learning) {\n      double prob = bib::Proba<double>::truncatedGaussianDensity(*last_action, *last_pure_action, noise);\n      bool gr = reward >= -0.0000001;\n      trajectory.push_back( {last_state, last_goal_achieved, last_goal_achieved, *last_pure_action, *last_action, sensors, goal_achieved, reward, gr, prob, false, true});\n      if (gr)\n        trajectory_end_points.push_back(trajectory.size());\n      \n//      auto sa = trajectory.back();\n//      double nr = dense_reward(sa.goal_achieved_unnormed, sa.s,\n//                                                    sa.next_goal_achieved_unnormed, sa.next_s,\n//                                                    sa.s, sa.next_s);\n//      LOG_DEBUG(reward << \" \" << nr);\n    }\n\n    last_pure_action.reset(new std::vector<double>(*next_action));\n    if(learning) {\n      if(gaussian_policy == 1) {\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(gaussian_policy == 2) {\n        oun->step(*next_action);\n      } else if(gaussian_policy == 3 && bib::Utils::rand01() < noise2) {\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(gaussian_policy == 4) {\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise * pow(noise2, noise3 - ((double) step)));\n        delete next_action;\n        next_action = randomized_action;\n      } else if(gaussian_policy == 5) {\n        if (bib::Utils::rand01() < noise2){\n          for (uint i = 0; i < next_action->size(); i++)\n            next_action->at(i) = bib::Utils::randin(-1.f, 1.f);\n        } else {\n          vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);\n          delete next_action;\n          next_action = randomized_action;\n        }\n      } else if(bib::Utils::rand01() < noise) { //e-greedy\n        for (uint i = 0; i < next_action->size(); i++)\n          next_action->at(i) = bib::Utils::randin(-1.f, 1.f);\n      }\n    }\n    last_action.reset(next_action);\n\n    std::copy(sensors.begin(), sensors.end(), last_state.begin());\n    std::copy(goal_achieved.begin(), goal_achieved.end(), last_goal_achieved.begin());\n    step++;\n    \n    return *next_action;\n  }\n\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map* command_args) override {\n//     bib::Seed::setFixedSeedUTest();\n    hidden_unit_v           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_v\"));\n    hidden_unit_a           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_a\"));\n    noise                   = pt->get<double>(\"agent.noise\");\n    gaussian_policy         = pt->get<uint>(\"agent.gaussian_policy\");\n    number_fitted_iteration = pt->get<uint>(\"agent.number_fitted_iteration\");\n    stoch_iter_actor        = pt->get<uint>(\"agent.stoch_iter_actor\");\n    stoch_iter_critic       = pt->get<uint>(\"agent.stoch_iter_critic\");\n    actor_output_layer_type = pt->get<uint>(\"agent.actor_output_layer_type\");\n    hidden_layer_type       = pt->get<uint>(\"agent.hidden_layer_type\");\n    alpha_a                 = pt->get<double>(\"agent.alpha_a\");\n    alpha_v                 = pt->get<double>(\"agent.alpha_v\");\n    lambda                  = pt->get<double>(\"agent.lambda\");\n    momentum                = pt->get<uint>(\"agent.momentum\");\n    beta_target             = pt->get<double>(\"agent.beta_target\");\n    ignore_poss_ac          = pt->get<bool>(\"agent.ignore_poss_ac\");\n    conserve_beta           = pt->get<bool>(\"agent.conserve_beta\");\n    disable_trust_region = pt->get<bool>(\"agent.disable_trust_region\");\n    disable_cac                 = pt->get<bool>(\"agent.disable_cac\");\n    hindsight_nb_destination = pt->get<uint>(\"agent.hindsight_nb_destination\");\n    gae                     = false;\n    update_each_episode = 1;\n    \n    if(gaussian_policy == 2) {\n      double oun_theta = pt->get<double>(\"agent.noise2\");\n      double oun_dt = pt->get<double>(\"agent.noise3\");\n      oun = new bib::OrnsteinUhlenbeckNoise<double>(this->nb_motors, noise, oun_theta, oun_dt);\n    } else if (gaussian_policy == 3 || gaussian_policy == 5){\n      noise2 = pt->get<double>(\"agent.noise2\");\n    } else if (gaussian_policy == 4){\n      noise2 = pt->get<double>(\"agent.noise2\");\n      noise3 = pt->get<double>(\"agent.noise3\");\n    }\n    \n    try {\n      update_each_episode     = pt->get<uint>(\"agent.update_each_episode\");\n#ifdef PARALLEL_INTERACTION\n      if (update_each_episode % (world.size() - 1) != 0) {\n        LOG_ERROR(\"update_each_episode must be a multiple of (number of worker - 1)\");\n        exit(1);\n      }\n      update_each_episode = update_each_episode / (world.size() - 1);\n#endif\n    } catch(boost::exception const& ) {\n    }\n    \n    if(lambda >= 0.)\n      gae = pt->get<bool>(\"agent.gae\");\n\n#ifdef CAFFE_CPU_ONLY\n    LOG_INFO(\"CPU mode\");\n    (void) command_args;\n#else\n    \n    if(command_args->count(\"gpu\") == 0 || command_args->count(\"cpu\") > 0\n#ifdef PARALLEL_INTERACTION\n      || world.rank() != 0\n#endif\n     )\n    { \n      caffe::Caffe::set_mode(caffe::Caffe::Brew::CPU);\n      LOG_INFO(\"CPU mode\");\n    } else {\n      caffe::Caffe::set_mode(caffe::Caffe::Brew::GPU);\n      caffe::Caffe::SetDevice((*command_args)[\"gpu\"].as<uint>());\n      LOG_INFO(\"GPU mode\");\n    }   \n#endif\n  \n    LOG_INFO(\"dimensionality of NN \" << nb_sensors << \" (in) \" << this->nb_motors << \" (out).\");\n    ann = new NN(nb_sensors, *hidden_unit_a, this->nb_motors, alpha_a, 1, hidden_layer_type, actor_output_layer_type, 0, true, momentum);\n    ann_noblob = new NN(*ann, false, ::caffe::Phase::TEST);\n\n#ifdef PARALLEL_INTERACTION\n    std::vector<double> weights(ann->number_of_parameters(false), 0.f);\n    if (world.rank() == 0)\n      ann->copyWeightsTo(weights.data(), false);\n\n    broadcast(world, weights, 0);\n    if (world.rank() != 0)\n      ann->copyWeightsFrom(weights.data(), false);\n#endif\n\n#ifdef PARALLEL_INTERACTION\n    if (world.rank() == 0)\n      vnn = new NN(nb_sensors, nb_sensors, *hidden_unit_v, alpha_v, 1, -1, hidden_layer_type, 0, false, momentum);\n#else\n    vnn = new NN(nb_sensors, nb_sensors, *hidden_unit_v, alpha_v, 1, -1, hidden_layer_type, 0, false, momentum);\n#endif\n    bestever_score = std::numeric_limits<double>::lowest();\n  }\n\n  void _start_episode(const std::vector<double>& sensors, bool) override {\n    std::copy(sensors.begin(), sensors.end(), last_state.begin());\n\n    last_action = nullptr;\n    last_pure_action = nullptr;\n    \n    step = 0;\n    if(gaussian_policy == 2)\n      oun->reset();\n\n    double* weights = new double[ann->number_of_parameters(false)];\n    ann->copyWeightsTo(weights, false);\n    ann_noblob->copyWeightsFrom(weights, false);\n    delete[] weights;\n  }\n\n  void update_critic(const caffe::Blob<double>& all_states, const caffe::Blob<double>& all_next_states,\n    const caffe::Blob<double>& r_gamma_coef) {\n    \n    if (trajectory.size() > 0) {\n      caffe::Blob<double> v_target(trajectory.size(), 1, 1, 1);\n\n      //remove trace of old policy\n      auto iter = [&]() {\n        auto all_nextV = vnn->computeOutVFBlob(all_next_states, empty_action);\n        auto all_V = vnn->computeOutVFBlob(all_states, empty_action);\n        //all_V must be computed after all_nextV to use learn_blob_no_full_forward\n\n//#ifdef CAFFE_CPU_ONLY\n        caffe::caffe_mul(trajectory.size(), r_gamma_coef.cpu_diff(), all_nextV->cpu_data(), v_target.mutable_cpu_data());\n        caffe::caffe_add(trajectory.size(), r_gamma_coef.cpu_data(), v_target.cpu_data(), v_target.mutable_cpu_data());\n\n        double *pv_target = v_target.mutable_cpu_data();\n        double min_ = - (1.f/(1.f-this->gamma));\n        for(int i=0;i<trajectory.size();i++){\n            if(pv_target[i] > 0.0)\n                pv_target[i] = 0.f;\n            else if (pv_target[i] < min_)\n                pv_target[i] = min_;\n        }\n\n        caffe::caffe_sub(trajectory.size(), v_target.cpu_data(), all_V->cpu_data(), v_target.mutable_cpu_data());\n//#else\n//      switch (caffe::Caffe::mode()) {\n//      case caffe::Caffe::CPU:\n//        caffe::caffe_mul(trajectory.size(), r_gamma_coef.cpu_diff(), all_nextV->cpu_data(), v_target.mutable_cpu_data());\n//        caffe::caffe_add(trajectory.size(), r_gamma_coef.cpu_data(), v_target.cpu_data(), v_target.mutable_cpu_data());\n//        caffe::caffe_sub(trajectory.size(), v_target.cpu_data(), all_V->cpu_data(), v_target.mutable_cpu_data());\n//        break;\n//      case caffe::Caffe::GPU:\n//        caffe::caffe_gpu_mul(trajectory.size(), r_gamma_coef.gpu_diff(), all_nextV->gpu_data(), v_target.mutable_gpu_data());\n//        caffe::caffe_gpu_add(trajectory.size(), r_gamma_coef.gpu_data(), v_target.gpu_data(), v_target.mutable_gpu_data());\n//        caffe::caffe_gpu_sub(trajectory.size(), v_target.gpu_data(), all_V->gpu_data(), v_target.mutable_gpu_data());\n//        break;\n//      }\n//#endif\n        \n//     Simple computation for lambda return\n//    move v_target from GPU to CPU\n        double* pdiff = v_target.mutable_cpu_diff();\n        const double* pvtarget = v_target.cpu_data();\n        int li=trajectory.size() - 1;\n        double prev_delta = 0.;\n        int index_ep = trajectory_end_points.size() - 1;\n        for (auto it = trajectory.rbegin(); it != trajectory.rend(); it++) {\n          if (index_ep >= 0 && trajectory_end_points[index_ep] - 1 == li){\n              prev_delta = 0.;\n              index_ep--;\n          }\n//          if(pvtarget[li] + all_V->cpu_data()[li] > 0.0001f || pvtarget[li] + all_V->cpu_data()[li] < -50.0001f)\n//            LOG_DEBUG(\"MIGHT BE PROBLEMATIC \" << (pvtarget[li]+all_V->cpu_data()[li]) << \" \" << r_gamma_coef.cpu_diff()[li] << \" \" << all_nextV->cpu_data()[li] << \" \" << r_gamma_coef.cpu_data()[li]);\n          \n          if (it->artificial) {\n            pdiff[li] = pvtarget[li] * std::min(it->prob, pbar) + prev_delta * std::min(it->prob, cbar);\n            prev_delta = this->gamma * lambda * pdiff[li];\n          } else {\n            pdiff[li] = pvtarget[li] + prev_delta;\n            prev_delta = this->gamma * lambda * pdiff[li];\n          }\n          --li;\n        }\n//        ASSERT(pdiff[trajectory.size() -1] == pvtarget[trajectory.size() -1] * std::min(trajectory[trajectory.size() - 1].prob, pbar), \"pb lambda\");\n        \n//         move diff to GPU\n#ifdef CAFFE_CPU_ONLY\n        caffe::caffe_add(trajectory.size(), v_target.cpu_diff(), all_V->cpu_data(), v_target.mutable_cpu_data());\n#else\n      switch (caffe::Caffe::mode()) {\n      case caffe::Caffe::CPU:\n        caffe::caffe_add(trajectory.size(), v_target.cpu_diff(), all_V->cpu_data(), v_target.mutable_cpu_data());\n        break;\n      case caffe::Caffe::GPU:\n        caffe::caffe_gpu_add(trajectory.size(), v_target.gpu_diff(), all_V->gpu_data(), v_target.mutable_gpu_data());\n        break;\n      }\n#endif\n        if (stoch_iter_critic == 1)\n          vnn->learn_blob_no_full_forward(all_states, empty_action, v_target);\n        else\n          vnn->learn_blob(all_states, empty_action, v_target, stoch_iter_critic);\n\n        delete all_V;\n        delete all_nextV;\n      };\n\n      for(uint i=0; i<number_fitted_iteration; i++)\n        iter();\n    }\n  }\n\n  void end_episode(bool learning) override {\n//     LOG_FILE(\"policy_exploration\", ann->hash());\n    if(!learning){\n      return;\n    }\n    \n    //learning phase\n    if (trajectory_end_points.size() == 0 || trajectory_end_points.back() != trajectory.size())\n      trajectory_end_points.push_back(trajectory.size());\n    if (episode % update_each_episode != 0)\n      return;\n\n//     \n// Remove junk data\n// \n    std::deque<double> varsums(trajectory_end_points.size(), 0.f);\n    for (int traj = trajectory_end_points.size() - 1 ; traj >= 0 ; traj--) {\n      int beg = traj == 0 ? 0 : trajectory_end_points[traj-1];\n      int end = trajectory_end_points[traj];\n      if (end - beg > 1) {\n        for (int goal_dim=0; goal_dim < goal_size; goal_dim++) {\n          std::function<double(const sample&)> get = [goal_dim](const sample&  s) {\n            return s.goal_achieved_unnormed[goal_dim];\n          };\n          varsums[traj] += bib::Utils::variance<>(trajectory.cbegin() + beg, trajectory.cbegin() + end, get);\n        }\n      }\n      \n      //goal_achieved hasn't change at all during the trajectory\n      if (varsums[traj] <= 1e-8) {\n        // tag already achieved task where actor won't be update\n        if (trajectory[beg].r >= -0.0001) {\n          for (auto it = trajectory.begin() + beg; it != trajectory.begin() + end; it++)\n              it->interest=false;\n\t\t}\n      }\n    }\n \n#ifdef PARALLEL_INTERACTION\n    if (world.rank() == 0) {\n      trajectory_end_points.clear();\n      varsums.clear();\n      \n      std::vector<std::deque<sample>> all_traj;\n      std::vector<std::deque<int>> all_traj_ep;\n      std::vector<std::deque<double>> all_varsums;\n      gather(world, trajectory, all_traj, 0);\n      gather(world, trajectory_end_points, all_traj_ep, 0);\n      gather(world, varsums, all_varsums, 0);\n\n      ASSERT(all_traj.size() == all_traj_ep.size(), \"pb\");\n      for (auto it : all_varsums)\n        for (auto it2 : it)\n            varsums.push_back(it2);\n      for (int i=0; i < all_traj.size() ; i++) {\n        for (auto d2 : all_traj_ep[i])\n          trajectory_end_points.push_back(trajectory.size() + d2);\n        \n        trajectory.insert(trajectory.end(), all_traj[i].begin(), all_traj[i].end());\n      }\n    } else {\n      gather(world, trajectory, 0);\n      gather(world, trajectory_end_points, 0);\n      gather(world, varsums, 0);\n    }\n    \n    if (world.rank() == 0) {\n#endif\n    \n//     LOG_DEBUG(\"#############\");\n//     for (int i=0;i<trajectory.size(); i++) {\n//       bib::Logger::PRINT_ELEMENTS(trajectory[i].goal_achieved);\n//       LOG_DEBUG(trajectory[i].r << \" \" <<i);\n//     }\n//     bib::Logger::PRINT_ELEMENTS(trajectory_end_points);\n//     LOG_DEBUG(\"#############\");\n//     LOG_DEBUG(\"#############\");\n    \n//     \n//    update norm on batch\n//     \n    for (int i=0;i<trajectory.size(); i++) {\n      normalizer.update_batch_clip_before(trajectory[i].s, goal_size);//ignore fixed goal in update\n      normalizer.update_batch_clip_before(trajectory[i].goal_achieved);\n    }\n    \n#ifdef PARALLEL_INTERACTION\n    }\n    \n//     synchronize normalizer\n    bib::OnlineNormalizer on(this->nb_sensors);\n    if (world.rank() == 0)\n      on.copyFrom(normalizer);\n    \n    broadcast(world, on, 0);\n    \n    if (world.rank() != 0)\n      normalizer.copyFrom(on);\n    \n    if (world.rank() == 0) {\n#endif\n   \n    if (trajectory.size() == 0) {\n      LOG_INFO(\"no data left\");\n      nb_sample_update = 0;\n      ASSERT(trajectory_end_points.size() == 0, \"\");\n      return;\n    }\n    \n//     LOG_DEBUG(\"#############\");\n//     for (int i=0;i<trajectory.size(); i++) {\n//       bib::Logger::PRINT_ELEMENTS(trajectory[i].goal_achieved);\n//       LOG_DEBUG(trajectory[i].r << \" \" <<i);\n// //       if(trajectory[i].r >= 0 ){\n// //         bib::Logger::PRINT_ELEMENTS(trajectory[i].goal_achieved, (\"HERE \"+std::to_string(i)+\" \").c_str());\n// //       }\n//     }\n// //     bib::Logger::PRINT_ELEMENTS(trajectory_end_points);\n// //     exit(1);\n    \n//     \n//  perform norm on batch\n// \n     for (int i=0;i<trajectory.size(); i++) {\n       std::vector<double> normed_sensors(nb_sensors);\n       std::vector<double> normed_goal_size(goal_size);\n       std::vector<double> normed_next_s(nb_sensors);\n       normalizer.transform_with_double_clip(normed_sensors, trajectory[i].s, false);\n       normalizer.transform_with_double_clip(normed_goal_size, trajectory[i].goal_achieved, false);\n       normalizer.transform_with_double_clip(normed_next_s, trajectory[i].next_s, false);\n       \n       std::copy(normed_sensors.begin(), normed_sensors.end(), trajectory[i].s.begin());\n       std::copy(normed_goal_size.begin(), normed_goal_size.end(), trajectory[i].goal_achieved.begin());\n       std::copy(normed_next_s.begin(), normed_next_s.end(), trajectory[i].next_s.begin());\n     }\n    \n//     LOG_DEBUG(\"#############\");\n//     for (int i=0;i<trajectory.size(); i++) {\n//       bib::Logger::PRINT_ELEMENTS(trajectory[i].s);\n//       bib::Logger::PRINT_ELEMENTS(trajectory[i].goal_achieved);\n//       LOG_DEBUG(trajectory[i].r << \" \" <<i);\n//     }\n//     exit(1);\n    \n// \n// data augmentation part\n//\n   int saved_trajsize=trajectory.size();\n   int saved_trajend_point=trajectory_end_points.size();\n \n   for(int i=0;i < saved_trajend_point; i++) {\n//      don't generate trajectory where goal achieved hasn't changed\n     if (varsums[i] <= 1e-8)\n       continue;\n       \n      int min_index=0;\n      if(i>0)\n        min_index=trajectory_end_points[i-1];\n\n\t  if(trajectory_end_points[i]-1 == min_index)\n\t\tcontinue;\n\n      for(int j=0;j<hindsight_nb_destination;j++) {\n          uint destination = bib::Seed::unifRandInt(min_index, trajectory_end_points[i]-1);\n\n          for(int k=min_index;k<=destination;k++) {\n            sample sa = trajectory[k];\n            trajectory.push_back(sa);\n            trajectory.back().artificial = true;\n            std::copy(trajectory[destination].goal_achieved.begin(), \n                  trajectory[destination].goal_achieved.end(), \n                  trajectory.back().s.begin() + goal_start);\n            std::copy(trajectory[destination].goal_achieved.begin(), \n                  trajectory[destination].goal_achieved.end(), \n                  trajectory.back().next_s.begin() + goal_start);\n            \n //         sparse reward\n            if ( sparse_reward(sa.goal_achieved_unnormed, trajectory[destination].goal_achieved_unnormed)) {\n              trajectory.back().r = 0.f;\n              trajectory.back().goal_reached = true;\n              trajectory_end_points.push_back(trajectory.size());\n            }\n //         --\n\n//          dense reward\n//          trajectory.back().r = dense_reward(sa.goal_achieved_unnormed, trajectory[destination].goal_achieved_unnormed,\n//                                                  sa.next_goal_achieved_unnormed, trajectory[destination].next_goal_achieved_unnormed,\n//                                                  sa.s, sa.next_s);\n//          if ( trajectory.back().r >= -0.0000001 ) {\n//              trajectory_end_points.push_back(trajectory.size());\n//              trajectory.back().goal_reached = true;\n//          }\n//        --\n\n            //should remove junk data after data\n          }\n     \t  if (trajectory_end_points.back() != trajectory.size())\n          \ttrajectory_end_points.push_back(trajectory.size());\n      }\n   }\n//\n// tag artificial junk data\n//\n    for (int traj = trajectory_end_points.size() - 1 ; traj >= saved_trajend_point ; traj--) {\n      int beg = traj == 0 ? 0 : trajectory_end_points[traj-1];\n      int end = trajectory_end_points[traj];\n\t  double varsum = 0.f;\n      if (end - beg > 1) {\n        for (int goal_dim=0; goal_dim < goal_size; goal_dim++) {\n          std::function<double(const sample&)> get = [goal_dim](const sample&  s) {\n            return s.goal_achieved_unnormed[goal_dim];\n          };\n          varsum += bib::Utils::variance<>(trajectory.cbegin() + beg, trajectory.cbegin() + end, get);\n        }\n      }\n      \n      //goal_achieved hasn't change at all during the trajectory\n      if (varsum <= 1e-8 && trajectory[beg].r >= -0.0001) {\n        for (auto it = trajectory.begin() + beg; it != trajectory.begin() + end; it++){\n            it->interest=false;\n\t\t}\n      }\n    }\n \n// \n//  compute importance sampling ratio on artificial data\n// \n    int artificial_data_size = trajectory.size() - saved_trajsize;\n    if (artificial_data_size > 0) {\n      caffe::Blob<double> all_states(artificial_data_size, nb_sensors, 1, 1);\n      double* pall_states = all_states.mutable_cpu_data();\n      \n      int li=0;\n      for (int i = saved_trajsize; i < trajectory.size(); i++) {\n        std::copy(trajectory[i].s.begin(), trajectory[i].s.end(), pall_states + li * nb_sensors);\n        li++;\n      }\n      \n      ann->increase_batchsize(artificial_data_size);\n      auto ac_out = ann->computeOutBlob(all_states);\n      li=0;\n      for (int i = saved_trajsize; i < trajectory.size(); i++) {\n        trajectory[i].prob = bib::Proba<double>::truncatedGaussianDensity(trajectory[i].a, ac_out->cpu_data(), noise, li * this->nb_motors) / trajectory[i].prob;\n        li++;\n      }\n      delete ac_out;\n    }\n    \n//     LOG_DEBUG(\"#############\");\n//     for (int i=0;i<trajectory.size(); i++){\n//       bib::Logger::PRINT_ELEMENTS(trajectory[i].s, trajectory[i].artificial ? \"arti \" : \"real \");\n//       bib::Logger::PRINT_ELEMENTS(trajectory[i].goal_achieved);\n//       LOG_DEBUG(trajectory[i].r << \" \" <<i);\n//     }\n//     LOG_DEBUG(\"#############\");\n//     LOG_DEBUG(\"#############\");\n//     LOG_DEBUG(\"#############\");\n//     exit(1);\n        \n    if(trajectory.size() > 0)\n      vnn->increase_batchsize(trajectory.size());\n    \n    caffe::Blob<double> all_states(trajectory.size(), nb_sensors, 1, 1);\n    caffe::Blob<double> all_next_states(trajectory.size(), nb_sensors, 1, 1);\n    //store reward in data and gamma coef in diff\n    caffe::Blob<double> r_gamma_coef(trajectory.size(), 1, 1, 1);\n    \n    double* pall_states = all_states.mutable_cpu_data();\n    double* pall_states_next = all_next_states.mutable_cpu_data();\n    double* pr_all = r_gamma_coef.mutable_cpu_data();\n    double* pgamma_coef = r_gamma_coef.mutable_cpu_diff();\n\n    int li=0;\n    for (auto it : trajectory) {\n      std::copy(it.s.begin(), it.s.end(), pall_states + li * nb_sensors);\n      std::copy(it.next_s.begin(), it.next_s.end(), pall_states_next + li * nb_sensors);\n      pr_all[li]=it.r;\n      pgamma_coef[li]= it.goal_reached ? 0.000f : this->gamma;\n      li++;\n    }\n\n    update_critic(all_states, all_next_states, r_gamma_coef);\n\n    if (trajectory.size() > 0) {\n      const std::vector<double> disable_back_ac(this->nb_motors, 0.00f);\n      caffe::Blob<double> deltas(trajectory.size(), 1, 1, 1);\n\n      auto all_nextV = vnn->computeOutVFBlob(all_next_states, empty_action);\n      auto all_mine = vnn->computeOutVFBlob(all_states, empty_action);\n     \n//#ifdef CAFFE_CPU_ONLY\n      caffe::caffe_mul(trajectory.size(), r_gamma_coef.cpu_diff(), all_nextV->cpu_data(), deltas.mutable_cpu_data());\n      caffe::caffe_add(trajectory.size(), r_gamma_coef.cpu_data(), deltas.cpu_data(), deltas.mutable_cpu_data());\n\n      double *pv_target = deltas.mutable_cpu_data();\n     double min_ = - (1.f/(1.f-this->gamma));\n     for(int i=0;i<trajectory.size();i++){\n         if(pv_target[i] > 0.0)\n             pv_target[i] = 0.f;\n         else if (pv_target[i] < min_)\n             pv_target[i] = min_;\n     }\n\n\n      caffe::caffe_sub(trajectory.size(), deltas.cpu_data(), all_mine->cpu_data(), deltas.mutable_cpu_data());\n//#else\n//      switch (caffe::Caffe::mode()) {\n//      case caffe::Caffe::CPU:\n//        caffe::caffe_mul(trajectory.size(), r_gamma_coef.cpu_diff(), all_nextV->cpu_data(), deltas.mutable_cpu_data());\n//        caffe::caffe_add(trajectory.size(), r_gamma_coef.cpu_data(), deltas.cpu_data(), deltas.mutable_cpu_data());\n//        caffe::caffe_sub(trajectory.size(), deltas.cpu_data(), all_mine->cpu_data(), deltas.mutable_cpu_data());\n//        break;\n//      case caffe::Caffe::GPU:\n//        caffe::caffe_gpu_mul(trajectory.size(), r_gamma_coef.gpu_diff(), all_nextV->gpu_data(), deltas.mutable_gpu_data());\n//        caffe::caffe_gpu_add(trajectory.size(), r_gamma_coef.gpu_data(), deltas.gpu_data(), deltas.mutable_gpu_data());\n//        caffe::caffe_gpu_sub(trajectory.size(), deltas.gpu_data(), all_mine->gpu_data(), deltas.mutable_gpu_data());\n//        break;\n//      }\n//#endif\n \n      if(gae){\n        //        Simple computation for lambda return\n        //        move deltas from GPU to CPU\n        double * diff = deltas.mutable_cpu_diff();\n        const double* pdeltas = deltas.cpu_data();\n        int li=trajectory.size() - 1;\n        double prev_delta = 0.;\n        int index_ep = trajectory_end_points.size() - 1;\n        for (auto it = trajectory.rbegin(); it != trajectory.rend(); it++) {\n          if (index_ep >= 0 && trajectory_end_points[index_ep] - 1 == li){\n              prev_delta = 0.;\n              index_ep--;\n          }\n          \n          if(it->artificial) {\n            diff[li] = pdeltas[li] * std::min(it->prob, pbar) + prev_delta * std::min(it->prob, cbar);\n            prev_delta = this->gamma * lambda * diff[li];\n          } else {\n            diff[li] = pdeltas[li] + prev_delta;\n            prev_delta = this->gamma * lambda * diff[li];\n          }\n          --li;\n        }\n//        ASSERT(diff[trajectory.size() -1] == pdeltas[trajectory.size() -1] * std::min(trajectory[trajectory.size() - 1].prob, pbar), \"pb lambda\");\n\n        caffe::caffe_copy(trajectory.size(), deltas.cpu_diff(), deltas.mutable_cpu_data());\n      }\n      \n      uint n=0;\n      posdelta_mean=0.f;\n      //store target in data, and disable in diff\n      caffe::Blob<double> target_cac(trajectory.size(), this->nb_motors, 1, 1);\n      caffe::Blob<double> target_treg(trajectory.size(), this->nb_motors, 1, 1);\n      caffe::caffe_set(target_cac.count(), static_cast<double>(1.f), target_cac.mutable_cpu_diff());\n      caffe::caffe_set(target_treg.count(), static_cast<double>(1.f), target_treg.mutable_cpu_diff());\n      caffe::Blob<double> deltas_blob(trajectory.size(), this->nb_motors, 1, 1);\n      caffe::caffe_set(deltas_blob.count(), static_cast<double>(1.f), deltas_blob.mutable_cpu_data());\n\n      double* pdisable_back_cac = target_cac.mutable_cpu_diff();\n      double* pdisable_back_treg = target_treg.mutable_cpu_diff();\n      double* pdeltas_blob = deltas_blob.mutable_cpu_data();\n      double* ptarget_cac = target_cac.mutable_cpu_data();\n      double* ptarget_treg = target_treg.mutable_cpu_data();\n      const double* pdeltas = deltas.cpu_data();\n      li=0;\n      //cacla cost\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        std::copy(it->a.begin(), it->a.end(), ptarget_cac + li * this->nb_motors);\n        if(pdeltas[li] > 0. && it->interest) {\n          posdelta_mean += pdeltas[li];\n          n++;\n        } else {\n          std::copy(disable_back_ac.begin(), disable_back_ac.end(), pdisable_back_cac + li * this->nb_motors);\n        }\n        if(!disable_cac)\n            std::fill(pdeltas_blob + li * this->nb_motors, pdeltas_blob + (li+1) * this->nb_motors, pdeltas[li]);\n        li++;\n      }\n      //penalty cost\n      li=0;\n      int number_non_artificial_sample = 0;\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        std::copy(it->pure_a.begin(), it->pure_a.end(), ptarget_treg + li * this->nb_motors);\n        if(ignore_poss_ac && pdeltas[li] > 0. || it->artificial) {\n            std::copy(disable_back_ac.begin(), disable_back_ac.end(), pdisable_back_treg + li * this->nb_motors);\n        }\n        if (! it->artificial)\n          number_non_artificial_sample++;\n        li++;\n      }\n\n      ratio_valid_advantage = ((float)n) / ((float) trajectory.size());\n      posdelta_mean = posdelta_mean / ((float) trajectory.size());\n      int size_cost_cacla=trajectory.size()*this->nb_motors;\n      \n      double beta=0.0001f;\n      mean_beta=0.f;\n      if(conserve_beta)\n        beta=conserved_beta;\n      mean_beta += beta;\n      \n      if(n > 0) {\n        ann->increase_batchsize(trajectory.size());\n        for(uint sia = 0; sia < stoch_iter_actor; sia++){\n          //learn BN\n          auto ac_out = ann->computeOutBlob(all_states);\n          ann->ZeroGradParameters();\n          \n          number_effective_actor_update = sia;\n          if(disable_trust_region)\n              beta=0.f;\n          else if (sia > 0) {\n            //compute deter distance(pi, pi_old)\n            caffe::Blob<double> diff_treg(trajectory.size(), this->nb_motors, 1, 1);\n            double l2distance = 0.f;\n#ifdef CAFFE_CPU_ONLY\n            caffe::caffe_sub(size_cost_cacla, target_treg.cpu_data(), ac_out->cpu_data(), diff_treg.mutable_cpu_data());\n            caffe::caffe_mul(size_cost_cacla, target_treg.cpu_diff(), diff_treg.cpu_data(), diff_treg.mutable_cpu_data());\n            caffe::caffe_mul(size_cost_cacla, diff_treg.cpu_data(), diff_treg.cpu_data(), diff_treg.mutable_cpu_data());\n            l2distance = caffe::caffe_cpu_asum(size_cost_cacla, diff_treg.cpu_data());\n#else\n          switch (caffe::Caffe::mode()) {\n          case caffe::Caffe::CPU:\n            caffe::caffe_sub(size_cost_cacla, target_treg.cpu_data(), ac_out->cpu_data(), diff_treg.mutable_cpu_data());\n            caffe::caffe_mul(size_cost_cacla, target_treg.cpu_diff(), diff_treg.cpu_data(), diff_treg.mutable_cpu_data());\n            caffe::caffe_mul(size_cost_cacla, diff_treg.cpu_data(), diff_treg.cpu_data(), diff_treg.mutable_cpu_data());\n            l2distance = caffe::caffe_cpu_asum(size_cost_cacla, diff_treg.cpu_data());\n            break;\n          case caffe::Caffe::GPU:\n            caffe::caffe_gpu_sub(size_cost_cacla, target_treg.gpu_data(), ac_out->gpu_data(), diff_treg.mutable_gpu_data());\n            caffe::caffe_gpu_mul(size_cost_cacla, target_treg.gpu_diff(), diff_treg.gpu_data(), diff_treg.mutable_gpu_data());\n            caffe::caffe_gpu_mul(size_cost_cacla, diff_treg.gpu_data(), diff_treg.gpu_data(), diff_treg.mutable_gpu_data());\n            caffe::caffe_gpu_asum(size_cost_cacla, diff_treg.gpu_data(), &l2distance);\n            break;\n          }\n#endif\n            l2distance = std::sqrt(l2distance/((double) number_non_artificial_sample*this->nb_motors));\n\n            if (l2distance < beta_target/1.5)\n                beta = beta/2.;\n            else if (l2distance > beta_target*1.5)\n                beta = beta*2.;\n\n            beta=std::max(std::min((double)20.f, beta), (double) 0.01f);\n            mean_beta += beta;\n            conserved_l2dist = l2distance;\n            //LOG_DEBUG(std::setprecision(7) << l2distance << \" \" << beta << \" \" << beta_target << \" \" << sia);\n          }\n          \n          const auto actor_actions_blob = ann->getNN()->blob_by_name(MLP::actions_blob_name);\n          \n          caffe::Blob<double> diff_cac(trajectory.size(), this->nb_motors, 1, 1);\n          caffe::Blob<double> diff_treg(trajectory.size(), this->nb_motors, 1, 1);\n          double * ac_diff = nullptr;\n#ifdef CAFFE_CPU_ONLY\n          ac_diff = actor_actions_blob->mutable_cpu_diff();\n          caffe::caffe_sub(size_cost_cacla, target_cac.cpu_data(), ac_out->cpu_data(), diff_cac.mutable_cpu_data());\n          caffe::caffe_mul(size_cost_cacla, diff_cac.cpu_data(), deltas_blob.cpu_data(), diff_cac.mutable_cpu_data());\n          caffe::caffe_mul(size_cost_cacla, target_cac.cpu_diff(), diff_cac.cpu_data(), diff_cac.mutable_cpu_data());\n          \n          caffe::caffe_sub(size_cost_cacla, target_treg.cpu_data(), ac_out->cpu_data(), diff_treg.mutable_cpu_data());\n          caffe::caffe_scal(size_cost_cacla, beta, diff_treg.mutable_cpu_data());\n          caffe::caffe_mul(size_cost_cacla, target_treg.cpu_diff(), diff_treg.cpu_data(), diff_treg.mutable_cpu_data());\n          \n          caffe::caffe_add(size_cost_cacla, diff_cac.cpu_data(), diff_treg.cpu_data(), ac_diff);\n          caffe::caffe_scal(size_cost_cacla, (double) -1.f, ac_diff);\n#else\n          switch (caffe::Caffe::mode()) {\n          case caffe::Caffe::CPU:\n            ac_diff = actor_actions_blob->mutable_cpu_diff();\n            caffe::caffe_sub(size_cost_cacla, target_cac.cpu_data(), ac_out->cpu_data(), diff_cac.mutable_cpu_data());\n            caffe::caffe_mul(size_cost_cacla, diff_cac.cpu_data(), deltas_blob.cpu_data(), diff_cac.mutable_cpu_data());\n            caffe::caffe_mul(size_cost_cacla, target_cac.cpu_diff(), diff_cac.cpu_data(), diff_cac.mutable_cpu_data());\n            \n            caffe::caffe_sub(size_cost_cacla, target_treg.cpu_data(), ac_out->cpu_data(), diff_treg.mutable_cpu_data());\n            caffe::caffe_scal(size_cost_cacla, beta, diff_treg.mutable_cpu_data());\n            caffe::caffe_mul(size_cost_cacla, target_treg.cpu_diff(), diff_treg.cpu_data(), diff_treg.mutable_cpu_data());\n            \n            caffe::caffe_add(size_cost_cacla, diff_cac.cpu_data(), diff_treg.cpu_data(), ac_diff);\n            caffe::caffe_scal(size_cost_cacla, (double) -1.f, ac_diff);\n            break;\n          case caffe::Caffe::GPU:\n            ac_diff = actor_actions_blob->mutable_gpu_diff();\n            caffe::caffe_gpu_sub(size_cost_cacla, target_cac.gpu_data(), ac_out->gpu_data(), diff_cac.mutable_gpu_data());\n            caffe::caffe_gpu_mul(size_cost_cacla, diff_cac.gpu_data(), deltas_blob.gpu_data(), diff_cac.mutable_gpu_data());\n            caffe::caffe_gpu_mul(size_cost_cacla, target_cac.gpu_diff(), diff_cac.gpu_data(), diff_cac.mutable_gpu_data());\n            \n            caffe::caffe_gpu_sub(size_cost_cacla, target_treg.gpu_data(), ac_out->gpu_data(), diff_treg.mutable_gpu_data());\n            caffe::caffe_gpu_scal(size_cost_cacla, beta, diff_treg.mutable_gpu_data());\n            caffe::caffe_gpu_mul(size_cost_cacla, target_treg.gpu_diff(), diff_treg.gpu_data(), diff_treg.mutable_gpu_data());\n            \n            caffe::caffe_gpu_add(size_cost_cacla, diff_cac.gpu_data(), diff_treg.gpu_data(), ac_diff);\n            caffe::caffe_gpu_scal(size_cost_cacla, (double) -1.f, ac_diff);\n            break;\n          }\n#endif\n\n          ann->actor_backward();\n          ann->updateFisher(n);\n          ann->regularize();\n          ann->getSolver()->ApplyUpdate();\n          ann->getSolver()->set_iter(ann->getSolver()->iter() + 1);\n          delete ac_out;\n        }\n      }\n      \n      conserved_beta = beta;\n      if (number_effective_actor_update != 0)\n        mean_beta /= (double) number_effective_actor_update;\n\n      delete all_nextV;\n      delete all_mine;\n    }\n    \n#ifdef PARALLEL_INTERACTION\n    }\n    std::vector<double> weights(ann->number_of_parameters(false), 0.f);\n    if (world.rank() == 0)\n        ann->copyWeightsTo(weights.data(), false);\n\n    broadcast(world, weights, 0);\n    if (world.rank() != 0)\n        ann->copyWeightsFrom(weights.data(), false);\n#endif\n    nb_sample_update = trajectory.size();\n    trajectory.clear();\n    trajectory_end_points.clear();\n  }\n\n  void end_instance(bool learning) override {\n    if(learning)\n      episode++;\n  }\n\n  void save(const std::string& path, bool savebest, bool learning) override {\n    if(savebest) {\n      if(!learning && this->sum_weighted_reward >= bestever_score) {\n        bestever_score = this->sum_weighted_reward;\n        ann->save(path+\".actor\");\n      }\n    } else {\n#ifdef PARALLEL_INTERACTION\n      if(world.rank() == 0 ) {\n#endif\n        ann->save(path+\".actor\");\n        vnn->save(path+\".critic\");\n        bib::XMLEngine::save<>(normalizer, \"normalizer\", path+\".normalizer.data\");\n#ifdef PARALLEL_INTERACTION\n      }\n#endif\n    } \n  }\n  \n  void save_run() override {\n    ann->save(\"continue.actor\");\n    vnn->save(\"continue.critic\");\n    struct algo_state st = {episode};\n    bib::XMLEngine::save(st, \"algo_state\", \"continue.algo_state.data\");\n  }\n\n  void load(const std::string& path) override {\n    ann->load(path+\".actor\");\n#ifndef PARALLEL_INTERACTION\n    vnn->load(path+\".critic\");\n#else\n    if (world.rank() == 0)\n      vnn->load(path+\".critic\");\n#endif\n    bib::XMLEngine::load<>(normalizer, \"normalizer\", path+\".normalizer.data\");\n  }\n  \n  void load_previous_run() override {\n    ann->load(\"continue.actor\");\n    vnn->load(\"continue.critic\");\n    auto p3 = bib::XMLEngine::load<struct algo_state>(\"algo_state\", \"continue.algo_state.data\");\n    episode = p3->episode;\n    delete p3;\n  }\n\n  double criticEval(const std::vector<double>&, const std::vector<double>&) override {\n    LOG_INFO(\"not implemented\");\n    return 0;\n  }\n\n  arch::Policy<NN>* getCopyCurrentPolicy() override {\n//         return new arch::Policy<MLP>(new MLP(*ann) , gaussian_policy ? arch::policy_type::GAUSSIAN : arch::policy_type::GREEDY, noise, decision_each);\n    return nullptr;\n  }\n  \n  uint getGoalSize(){\n    return goal_size;\n  }\n\n  bool sparse_reward(const std::vector<double>&  a, const std::vector<double>&  b) {\n    double sum = 0.f;\n    for (int i=0;i<a.size();i++){\n      double diff = a[i] - b[i];\n      sum += diff*diff;\n    }\n    sum = std::sqrt(sum);\n    return sum < 0.05f;\n  };\n \n  double dense_reward(const std::vector<double>&  goal_achieved, const std::vector<double>&  desired_goal, \n                               const std::vector<double>&  next_goal_achieved, const std::vector<double>&  next_desired_goal, \n                               const std::vector<double>&  observation, const std::vector<double>&  next_observation) {\n     \n     if (sparse_reward(goal_achieved, desired_goal))\n        return 0.f;\n\n     std::vector<double> mid_goal(3, 0.f);\n     mid_goal[0] = next_goal_achieved[0] - (next_desired_goal[0] - next_goal_achieved[0] > 0.f ? 1.f : -1.f)*0.04f;\n     mid_goal[1] = next_goal_achieved[1] - (next_desired_goal[1] - next_goal_achieved[1] > 0.f ? 1.f : -1.f)*0.04f;\n     mid_goal[2] = next_goal_achieved[2] + 0.07f;\n     \n     double dist_obj_hand;\n     {\n       std::vector<double> diff(3, 0.f);\n       std::transform(mid_goal.begin(), mid_goal.end(), observation.begin() + 3, diff.begin(), std::minus<double>());\n       dist_obj_hand = bib::Utils::euclidien_dist_ref(diff, 0.f)*3.f;\n     }\n     {\n       std::vector<double> diff(3, 0.f);\n       std::transform(mid_goal.begin(), mid_goal.end(), next_observation.begin() + 3, diff.begin(), std::minus<double>());\n       dist_obj_hand -= bib::Utils::euclidien_dist_ref(diff, 0.f)*3.f;\n     }\n \n     double dist_goal;\n     {\n       std::vector<double> diff(3, 0.f);\n       std::transform(goal_achieved.begin(), goal_achieved.end(), desired_goal.begin(), diff.begin(), std::minus<double>());\n       dist_goal = bib::Utils::euclidien_dist_ref(diff, 0.f)*3.f;\n     }\n     {\n       std::vector<double> diff(3, 0.f);\n       std::transform(next_goal_achieved.begin(), next_goal_achieved.end(), next_desired_goal.begin(), diff.begin(), std::minus<double>());\n       dist_goal -= bib::Utils::euclidien_dist_ref(diff, 0.f)*3.f;\n     }\n     if(dist_goal < 0.00005 and dist_goal >= 0.000000001)\n        dist_goal = 0.f;\n\n     double r = dist_obj_hand + 100*dist_goal;\n     if (r > 0.5)\n        r = 0.5;\n     else if (r < -0.5)\n        r = -0.5;\n\n     return -1. + 0.5 + r;\n   }\n \n\n#ifdef PARALLEL_INTERACTION\n  int getMPIrank() {\n    return world.rank();\n  }\n#endif\n\n protected:\n#ifndef PARALLEL_INTERACTION\n  void _display(std::ostream& out) const override {\n    out << std::setw(12) << std::fixed << std::setprecision(10) << this->sum_weighted_reward/this->gamma << \" \" << this->sum_reward << \n        \" \" << std::setw(8) << std::fixed << std::setprecision(5) << vnn->error() << \" \" << noise << \" \" << nb_sample_update <<\n          \" \" << std::setprecision(3) << ratio_valid_advantage << \" \" << vnn->weight_l1_norm() << \" \" << ann->weight_l1_norm(true);\n  }\n\n//clear all; close all; wndw = 10; X=load('0.learning.data'); X=filter(ones(wndw,1)/wndw, 1, X); startx=0; starty=800; width=350; height=350; figure('position',[startx,starty,width,height]); plot(X(:,3), \"linewidth\", 2); xlabel('learning episode', \"fontsize\", 16); ylabel('sum rewards', \"fontsize\", 16); startx+=width; figure('position',[startx,starty,width,height]); plot(X(:,9), \"linewidth\", 2); xlabel('learning episode', \"fontsize\", 16); ylabel('beta', \"fontsize\", 16); startx+=width; figure('position',[startx,starty,width,height]) ; plot(X(:,8), \"linewidth\", 2); xlabel('learning episode', \"fontsize\", 16); ylabel('valid adv', \"fontsize\", 16); ylim([0, 1]); startx+=width; figure('position',[startx,starty,width,height]) ; plot(X(:,11), \"linewidth\", 2); hold on; plot(X(:,12), \"linewidth\", 2, \"color\", \"red\"); legend(\"critic\", \"actor\"); xlabel('learning episode', \"fontsize\", 16); ylabel('||\\theta||_1', \"fontsize\", 16); startx+=width; figure('position',[startx,starty,width,height]) ; plot(X(:,10), \"linewidth\", 2); xlabel('learning episode', \"fontsize\", 16); ylabel('||\\mu_{old}-\\mu||_2', \"fontsize\", 16); startx+=width; figure('position',[startx,starty,width,height]) ; plot(X(:,14), \"linewidth\", 2); xlabel('learning episode', \"fontsize\", 16); ylabel('effective actor. upd.', \"fontsize\", 16); \n\n  void _dump(std::ostream& out) const override {\n    out << std::setw(25) << std::fixed << std::setprecision(22) << this->sum_weighted_reward/this->gamma << \" \" << \n    this->sum_reward << \" \" << std::setw(8) << std::fixed << std::setprecision(5) << vnn->error() << \" \" << \n    nb_sample_update << \" \" << std::setprecision(3) << ratio_valid_advantage << \" \" << std::setprecision(10) << \n    mean_beta << \" \" << conserved_l2dist << \" \" << std::setprecision(3) << vnn->weight_l1_norm() << \" \" << \n    ann->weight_l1_norm(true) << \" \" << std::setprecision(6)  << posdelta_mean << \" \" << number_effective_actor_update;\n  }\n#else\n  void _dump(std::ostream& out) const override {\n    out << std::setw(25) << std::fixed << std::setprecision(22) << this->sum_weighted_reward/this->gamma << \" \" << \n    this->sum_reward << \" \" << std::setw(8) << std::fixed << std::setprecision(5) << (world.rank() == 0 ? vnn->error() : 0) << \" \" << \n    nb_sample_update << \" \" << std::setprecision(3) << ratio_valid_advantage << \" \" << std::setprecision(10) << \n    mean_beta << \" \" << conserved_l2dist << \" \" << std::setprecision(3) << (world.rank() == 0 ?  vnn->weight_l1_norm() : 0) << \" \" << \n    ann->weight_l1_norm(true) << \" \" << std::setprecision(6)  << posdelta_mean << \" \" << number_effective_actor_update;\n  }\n  \n  void _display(std::ostream& out) const override {\n    out << std::setw(12) << std::fixed << std::setprecision(10) << this->sum_weighted_reward/this->gamma << \" \" << this->sum_reward << \n        \" \" << std::setw(8) << std::fixed << std::setprecision(5) << (world.rank() == 0 ? vnn->error() : 0) << \" \" << noise << \" \" << nb_sample_update <<\n          \" \" << std::setprecision(3) << ratio_valid_advantage << \" \" << (world.rank() == 0 ?  vnn->weight_l1_norm() : 0) << \" \" << ann->weight_l1_norm(true);\n  }\n#endif\n  \n private:\n  uint nb_sensors;\n  uint episode = 1;\n  uint step = 0;\n\n  double noise, noise2, noise3;\n  uint gaussian_policy;\n  bool gae, ignore_poss_ac, conserve_beta, disable_trust_region, disable_cac;\n  uint number_fitted_iteration, stoch_iter_actor, stoch_iter_critic;\n  uint actor_output_layer_type, hidden_layer_type, momentum;\n  double lambda, beta_target;\n  double conserved_beta= 0.0001f;\n  double mean_beta= 0.f;\n  double conserved_l2dist= 0.f;\n  int number_effective_actor_update = 0;\n\n  std::shared_ptr<std::vector<double>> last_action;\n  std::shared_ptr<std::vector<double>> last_pure_action;\n  std::vector<double> last_state;\n  std::vector<double> last_goal_achieved;\n  double alpha_v, alpha_a;\n\n  std::deque<sample> trajectory;\n  std::deque<int> trajectory_end_points;\n\n  NN* ann;\n  NN* ann_noblob;\n  NN* vnn = nullptr;\n\n  std::vector<uint>* hidden_unit_v;\n  std::vector<uint>* hidden_unit_a;\n  caffe::Blob<double> empty_action; //dummy action cause c++ cannot accept null reference\n  double bestever_score;\n  int update_each_episode;\n  bib::OrnsteinUhlenbeckNoise<double>* oun = nullptr;\n  float ratio_valid_advantage=0;\n  int nb_sample_update = 0;\n  double posdelta_mean = 0;\n  \n  //hindsight\n  uint goal_size;\n  uint goal_start;\n  uint hindsight_nb_destination;\n  \n  //v trace\n  double pbar = 1;\n  double cbar = 1;\n  \n  bib::OnlineNormalizer normalizer;\n\n#ifdef PARALLEL_INTERACTION\n  boost::mpi::communicator world;\n#endif\n  \n  struct algo_state {\n    uint episode;\n    \n    friend class boost::serialization::access;\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int) {\n      ar& BOOST_SERIALIZATION_NVP(episode);\n    }\n  };\n};\n\n#endif\n\n", "meta": {"hexsha": "037b859947bba1705eaab977f7c2828778b9efa3", "size": 47034, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/cacla/include/HPeNFACAg.hpp", "max_stars_repo_name": "matthieu637/ddrl", "max_stars_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T09:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T13:50:23.000Z", "max_issues_repo_path": "agent/cacla/include/HPeNFACAg.hpp", "max_issues_repo_name": "matthieu637/ddrl", "max_issues_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-10-09T14:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T15:01:00.000Z", "max_forks_repo_path": "agent/cacla/include/HPeNFACAg.hpp", "max_forks_repo_name": "matthieu637/ddrl", "max_forks_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T09:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T14:35:40.000Z", "avg_line_length": 42.372972973, "max_line_length": 1303, "alphanum_fraction": 0.6250797296, "num_tokens": 12430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.02161533520491613, "lm_q1q2_score": 0.007082660158265025}}
{"text": "//=============================================================================================================\n/**\n* @file     minimumnorm.cpp\n* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     February, 2013\n*\n* @section  LICENSE\n*\n* Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Implementation of the MinimumNorm Class.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"minimumnorm.h\"\n\n#include <mne/mne_sourceestimate.h>\n#include <fiff/fiff_evoked.h>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// STL INCLUDES\n//=============================================================================================================\n\n#include <iostream>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Core>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace MNELIB;\nusing namespace INVERSELIB;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nMinimumNorm::MinimumNorm(const MNEInverseOperator &p_inverseOperator, float lambda, const QString method)\n: m_inverseOperator(p_inverseOperator)\n, inverseSetup(false)\n{\n    this->setRegularization(lambda);\n    this->setMethod(method);\n}\n\n//*************************************************************************************************************\n\nMinimumNorm::MinimumNorm(const MNEInverseOperator &p_inverseOperator, float lambda, bool dSPM, bool sLORETA)\n: m_inverseOperator(p_inverseOperator)\n, inverseSetup(false)\n{\n    this->setRegularization(lambda);\n    this->setMethod(dSPM, sLORETA);\n}\n\n\n//*************************************************************************************************************\n\nMNESourceEstimate MinimumNorm::calculateInverse(const FiffEvoked &p_fiffEvoked, bool pick_normal)\n{\n    //\n    //   Set up the inverse according to the parameters\n    //\n    qint32 nave = p_fiffEvoked.nave;\n\n    if(!m_inverseOperator.check_ch_names(p_fiffEvoked.info))\n    {\n        qWarning(\"Channel name check failed.\");\n        return MNESourceEstimate();\n    }\n\n    doInverseSetup(nave,pick_normal);\n\n    //\n    //   Pick the correct channels from the data\n    //\n    FiffEvoked t_fiffEvoked = p_fiffEvoked.pick_channels(inv.noise_cov->names);\n\n    printf(\"Picked %d channels from the data\\n\",t_fiffEvoked.info.nchan);\n\n    //Results\n    float tmin = ((float)t_fiffEvoked.first) / t_fiffEvoked.info.sfreq;\n    float tstep = 1/t_fiffEvoked.info.sfreq;\n\n    return calculateInverse(t_fiffEvoked.data, tmin, tstep);\n\n//    //\n//    //   Set up the inverse according to the parameters\n//    //\n//    qint32 nave = p_fiffEvoked.nave;\n\n//    if(!m_inverseOperator.check_ch_names(p_fiffEvoked.info))\n//    {\n//        qWarning(\"Channel name check failed.\");\n//        return SourceEstimate();\n//    }\n\n//    //ToDo his could be heavily accelerated for real time calculation -> ToDo calculate inverse RT\n//    MNEInverseOperator inv = m_inverseOperator.prepare_inverse_operator(nave, m_fLambda, m_bdSPM, m_bsLORETA);\n//    //\n//    //   Pick the correct channels from the data\n//    //\n//    FiffEvoked t_fiffEvoked = p_fiffEvoked.pick_channels(inv.noise_cov->names);\n\n//    printf(\"Picked %d channels from the data\\n\",t_fiffEvoked.info.nchan);\n//    printf(\"Computing inverse...\");\n\n//    MatrixXd K;\n//    SparseMatrix<double> noise_norm;\n//    QList<VectorXi> vertno;\n//    Label label;\n//    inv.assemble_kernel(label, m_sMethod, pick_normal, K, noise_norm, vertno);\n\n//    MatrixXd sol = K * t_fiffEvoked.data; //apply imaging kernel\n\n//    if (inv.source_ori == FIFFV_MNE_FREE_ORI)\n//    {\n//        printf(\"combining the current components...\");\n//        MatrixXd sol1(sol.rows()/3,sol.cols());\n//        for(qint32 i = 0; i < sol.cols(); ++i)\n//        {\n//            VectorXd* tmp = MNEMath::combine_xyz(sol.block(0,i,sol.rows(),1));\n//            sol1.block(0,i,sol.rows()/3,1) = tmp->cwiseSqrt();\n//            delete tmp;\n//        }\n//        sol.resize(sol1.rows(),sol1.cols());\n//        sol = sol1;\n//    }\n\n//    if (m_bdSPM)\n//    {\n//        printf(\"(dSPM)...\");\n//        sol = inv.noisenorm*sol;\n//    }\n//    else if (m_bsLORETA)\n//    {\n//        printf(\"(sLORETA)...\");\n//        sol = inv.noisenorm*sol;\n//    }\n//    printf(\"[done]\\n\");\n\n//    //Results\n//    float tmin = ((float)t_fiffEvoked.first) / t_fiffEvoked.info.sfreq;\n//    float tstep = 1/t_fiffEvoked.info.sfreq;\n\n//    QList<VectorXi> t_qListVertices;\n//    for(qint32 h = 0; h < inv.src.size(); ++h)\n//        t_qListVertices.push_back(inv.src[h].vertno);\n\n//    return SourceEstimate(sol, t_qListVertices, tmin, tstep);\n}\n\n\n//*************************************************************************************************************\n\nMNESourceEstimate MinimumNorm::calculateInverse(const MatrixXd &data, float tmin, float tstep) const\n{\n    if(!inverseSetup)\n    {\n        qWarning(\"Inverse not setup -> call doInverseSetup first!\");\n        return MNESourceEstimate();\n    }\n\n    MatrixXd sol = K * data; //apply imaging kernel\n\n    if (inv.source_ori == FIFFV_MNE_FREE_ORI)\n    {\n        printf(\"combining the current components...\");\n        MatrixXd sol1(sol.rows()/3,sol.cols());\n        for(qint32 i = 0; i < sol.cols(); ++i)\n        {\n            VectorXd* tmp = MNEMath::combine_xyz(sol.block(0,i,sol.rows(),1));\n            sol1.block(0,i,sol.rows()/3,1) = tmp->cwiseSqrt();\n            delete tmp;\n        }\n        sol.resize(sol1.rows(),sol1.cols());\n        sol = sol1;\n    }\n\n    if (m_bdSPM)\n    {\n        printf(\"(dSPM)...\");\n        sol = inv.noisenorm*sol;\n    }\n    else if (m_bsLORETA)\n    {\n        printf(\"(sLORETA)...\");\n        sol = inv.noisenorm*sol;\n    }\n    printf(\"[done]\\n\");\n\n    //Results\n    VectorXi p_vecVertices(inv.src[0].vertno.size() + inv.src[1].vertno.size());\n    p_vecVertices << inv.src[0].vertno, inv.src[1].vertno;\n\n//    VectorXi p_vecVertices();\n//    for(qint32 h = 0; h < inv.src.size(); ++h)\n//        t_qListVertices.push_back(inv.src[h].vertno);\n\n    return MNESourceEstimate(sol, p_vecVertices, tmin, tstep);\n\n}\n\n\n//*************************************************************************************************************\n\nvoid MinimumNorm::doInverseSetup(qint32 nave, bool pick_normal)\n{\n    //\n    //   Set up the inverse according to the parameters\n    //\n    inv = m_inverseOperator.prepare_inverse_operator(nave, m_fLambda, m_bdSPM, m_bsLORETA);\n\n    printf(\"Computing inverse...\");\n    inv.assemble_kernel(label, m_sMethod, pick_normal, K, noise_norm, vertno);\n\n    std::cout << \"K \" << K.rows() << \" x \" << K.cols() << std::endl;\n\n    inverseSetup = true;\n}\n\n\n//*************************************************************************************************************\n\nconst char* MinimumNorm::getName() const\n{\n    return \"Minimum Norm Estimate\";\n}\n\n\n//*************************************************************************************************************\n\nconst MNESourceSpace& MinimumNorm::getSourceSpace() const\n{\n    return m_inverseOperator.src;\n}\n\n//*************************************************************************************************************\n\nvoid MinimumNorm::setMethod(QString method)\n{\n    if(method.compare(\"MNE\") == 0)\n        setMethod(false, false);\n    else if(method.compare(\"dSPM\") == 0)\n        setMethod(true, false);\n    else if(method.compare(\"sLORETA\") == 0)\n        setMethod(false, true);\n    else\n    {\n        qWarning(\"Method not recognized!\");\n        method = \"dSPM\";\n        setMethod(true, false);\n    }\n\n    printf(\"\\tSet minimum norm method to %s.\\n\", method.toUtf8().constData());\n}\n\n\n//*************************************************************************************************************\n\nvoid MinimumNorm::setMethod(bool dSPM, bool sLORETA)\n{\n    if(dSPM && sLORETA)\n    {\n        qWarning(\"Cant activate dSPM and sLORETA at the same time! - Activating dSPM\");\n        m_bdSPM = true;\n        m_bsLORETA = false;\n    }\n    else\n    {\n        m_bdSPM = dSPM;\n        m_bsLORETA = sLORETA;\n        if(dSPM)\n            m_sMethod = QString(\"dSPM\");\n        else if(sLORETA)\n            m_sMethod = QString(\"sLORETA\");\n        else\n            m_sMethod = QString(\"MNE\");\n\n    }\n}\n\n\n//*************************************************************************************************************\n\nvoid MinimumNorm::setRegularization(float lambda)\n{\n    m_fLambda = lambda;\n}\n", "meta": {"hexsha": "e7b8a62eea47df38ecf5e8a193a227c5d98f4991", "size": 11353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/inverse/minimumNorm/minimumnorm.cpp", "max_stars_repo_name": "13grife37/mne-cpp-swpold", "max_stars_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T20:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-26T16:30:25.000Z", "max_issues_repo_path": "MNE/inverse/minimumNorm/minimumnorm.cpp", "max_issues_repo_name": "13grife37/mne-cpp-swpold", "max_issues_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/inverse/minimumNorm/minimumnorm.cpp", "max_forks_repo_name": "13grife37/mne-cpp-swpold", "max_forks_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T15:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-23T15:55:31.000Z", "avg_line_length": 34.403030303, "max_line_length": 116, "alphanum_fraction": 0.4921166212, "num_tokens": 2364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.020023443409341448, "lm_q1q2_score": 0.007052292723806715}}
{"text": "//  Copyright John Maddock 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_MATH_POLICY_HPP\n#define BOOST_MATH_POLICY_HPP\n\n#include <boost/mpl/list.hpp>\n#include <boost/mpl/contains.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/find_if.hpp>\n#include <boost/mpl/remove_if.hpp>\n#include <boost/mpl/vector.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/at.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/assert.hpp>\n#include <boost/math/tools/config.hpp>\n#include <limits>\n// Sadly we do need the .h versions of these to be sure of getting\n// FLT_MANT_DIG etc.\n#include <limits.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <math.h>\n\nnamespace boost{ namespace math{ \n\nnamespace tools{\n\ntemplate <class T>\nint digits(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T));\ntemplate <class T>\nT epsilon(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T));\n\n}\n\nnamespace policies{\n\n//\n// Define macros for our default policies, if they're not defined already:\n//\n#ifndef BOOST_MATH_DOMAIN_ERROR_POLICY\n#define BOOST_MATH_DOMAIN_ERROR_POLICY throw_on_error\n#endif\n#ifndef BOOST_MATH_POLE_ERROR_POLICY\n#define BOOST_MATH_POLE_ERROR_POLICY throw_on_error\n#endif\n#ifndef BOOST_MATH_OVERFLOW_ERROR_POLICY\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY throw_on_error\n#endif\n#ifndef BOOST_MATH_EVALUATION_ERROR_POLICY\n#define BOOST_MATH_EVALUATION_ERROR_POLICY throw_on_error\n#endif\n#ifndef BOOST_MATH_ROUNDING_ERROR_POLICY\n#define BOOST_MATH_ROUNDING_ERROR_POLICY throw_on_error\n#endif\n#ifndef BOOST_MATH_UNDERFLOW_ERROR_POLICY\n#define BOOST_MATH_UNDERFLOW_ERROR_POLICY ignore_error\n#endif\n#ifndef BOOST_MATH_DENORM_ERROR_POLICY\n#define BOOST_MATH_DENORM_ERROR_POLICY ignore_error\n#endif\n#ifndef BOOST_MATH_INDETERMINATE_RESULT_ERROR_POLICY\n#define BOOST_MATH_INDETERMINATE_RESULT_ERROR_POLICY ignore_error\n#endif\n#ifndef BOOST_MATH_DIGITS10_POLICY\n#define BOOST_MATH_DIGITS10_POLICY 0\n#endif\n#ifndef BOOST_MATH_PROMOTE_FLOAT_POLICY\n#define BOOST_MATH_PROMOTE_FLOAT_POLICY true\n#endif\n#ifndef BOOST_MATH_PROMOTE_DOUBLE_POLICY\n#ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#define BOOST_MATH_PROMOTE_DOUBLE_POLICY false\n#else\n#define BOOST_MATH_PROMOTE_DOUBLE_POLICY true\n#endif\n#endif\n#ifndef BOOST_MATH_DISCRETE_QUANTILE_POLICY\n#define BOOST_MATH_DISCRETE_QUANTILE_POLICY integer_round_outwards\n#endif\n#ifndef BOOST_MATH_ASSERT_UNDEFINED_POLICY\n#define BOOST_MATH_ASSERT_UNDEFINED_POLICY true\n#endif\n#ifndef BOOST_MATH_MAX_SERIES_ITERATION_POLICY\n#define BOOST_MATH_MAX_SERIES_ITERATION_POLICY 1000000\n#endif\n#ifndef BOOST_MATH_MAX_ROOT_ITERATION_POLICY\n#define BOOST_MATH_MAX_ROOT_ITERATION_POLICY 200\n#endif\n\n#if !defined(__BORLANDC__)\n#define BOOST_MATH_META_INT(type, name, Default)\\\n   template <type N = Default> struct name : public boost::mpl::int_<N>{};\\\n   namespace detail{\\\n   template <type N>\\\n   char test_is_valid_arg(const name<N>*);\\\n   char test_is_default_arg(const name<Default>*);\\\n   template <class T> struct is_##name##_imp\\\n   {\\\n      template <type N> static char test(const name<N>*);\\\n      static double test(...);\\\n      BOOST_STATIC_CONSTANT(bool, value = sizeof(test(static_cast<T*>(0))) == 1);\\\n   };\\\n   }\\\n   template <class T> struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp<T>::value>{};\n\n#define BOOST_MATH_META_BOOL(name, Default)\\\n   template <bool N = Default> struct name : public boost::mpl::bool_<N>{};\\\n   namespace detail{\\\n   template <bool N>\\\n   char test_is_valid_arg(const name<N>*);\\\n   char test_is_default_arg(const name<Default>*);\\\n   template <class T> struct is_##name##_imp\\\n   {\\\n      template <bool N> static char test(const name<N>*);\\\n      static double test(...);\\\n      BOOST_STATIC_CONSTANT(bool, value = sizeof(test(static_cast<T*>(0))) == 1);\\\n   };\\\n   }\\\n   template <class T> struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp<T>::value>{};\n#else\n#define BOOST_MATH_META_INT(Type, name, Default)\\\n   template <Type N = Default> struct name : public boost::mpl::int_<N>{};\\\n   namespace detail{\\\n   template <Type N>\\\n   char test_is_valid_arg(const name<N>*);\\\n   char test_is_default_arg(const name<Default>*);\\\n   template <class T> struct is_##name##_tester\\\n   {\\\n      template <Type N> static char test(const name<N>&);\\\n      static double test(...);\\\n   };\\\n   template <class T> struct is_##name##_imp\\\n   {\\\n      static T inst;\\\n      BOOST_STATIC_CONSTANT(bool, value = sizeof( ::boost::math::policies::detail::is_##name##_tester<T>::test(inst)) == 1);\\\n   };\\\n   }\\\n   template <class T> struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp<T>::value>\\\n   {\\\n      template <class U> struct apply{ typedef is_##name<U> type; };\\\n   };\n\n#define BOOST_MATH_META_BOOL(name, Default)\\\n   template <bool N = Default> struct name : public boost::mpl::bool_<N>{};\\\n   namespace detail{\\\n   template <bool N>\\\n   char test_is_valid_arg(const name<N>*);\\\n   char test_is_default_arg(const name<Default>*);\\\n   template <class T> struct is_##name##_tester\\\n   {\\\n      template <bool N> static char test(const name<N>&);\\\n      static double test(...);\\\n   };\\\n   template <class T> struct is_##name##_imp\\\n   {\\\n      static T inst;\\\n      BOOST_STATIC_CONSTANT(bool, value = sizeof( ::boost::math::policies::detail::is_##name##_tester<T>::test(inst)) == 1);\\\n   };\\\n   }\\\n   template <class T> struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp<T>::value>\\\n   {\\\n      template <class U> struct apply{ typedef is_##name<U> type;  };\\\n   };\n#endif\n//\n// Begin by defining policy types for error handling:\n//\nenum error_policy_type\n{\n   throw_on_error = 0,\n   errno_on_error = 1,\n   ignore_error = 2,\n   user_error = 3\n};\n\nBOOST_MATH_META_INT(error_policy_type, domain_error, BOOST_MATH_DOMAIN_ERROR_POLICY)\nBOOST_MATH_META_INT(error_policy_type, pole_error, BOOST_MATH_POLE_ERROR_POLICY)\nBOOST_MATH_META_INT(error_policy_type, overflow_error, BOOST_MATH_OVERFLOW_ERROR_POLICY)\nBOOST_MATH_META_INT(error_policy_type, underflow_error, BOOST_MATH_UNDERFLOW_ERROR_POLICY)\nBOOST_MATH_META_INT(error_policy_type, denorm_error, BOOST_MATH_DENORM_ERROR_POLICY)\nBOOST_MATH_META_INT(error_policy_type, evaluation_error, BOOST_MATH_EVALUATION_ERROR_POLICY)\nBOOST_MATH_META_INT(error_policy_type, rounding_error, BOOST_MATH_ROUNDING_ERROR_POLICY)\nBOOST_MATH_META_INT(error_policy_type, indeterminate_result_error, BOOST_MATH_INDETERMINATE_RESULT_ERROR_POLICY)\n\n//\n// Policy types for internal promotion:\n//\nBOOST_MATH_META_BOOL(promote_float, BOOST_MATH_PROMOTE_FLOAT_POLICY)\nBOOST_MATH_META_BOOL(promote_double, BOOST_MATH_PROMOTE_DOUBLE_POLICY)\nBOOST_MATH_META_BOOL(assert_undefined, BOOST_MATH_ASSERT_UNDEFINED_POLICY)\n//\n// Policy types for discrete quantiles:\n//\nenum discrete_quantile_policy_type\n{\n   real,\n   integer_round_outwards,\n   integer_round_inwards,\n   integer_round_down,\n   integer_round_up,\n   integer_round_nearest\n};\n\nBOOST_MATH_META_INT(discrete_quantile_policy_type, discrete_quantile, BOOST_MATH_DISCRETE_QUANTILE_POLICY)\n//\n// Precision:\n//\nBOOST_MATH_META_INT(int, digits10, BOOST_MATH_DIGITS10_POLICY)\nBOOST_MATH_META_INT(int, digits2, 0)\n//\n// Iterations:\n//\nBOOST_MATH_META_INT(unsigned long, max_series_iterations, BOOST_MATH_MAX_SERIES_ITERATION_POLICY)\nBOOST_MATH_META_INT(unsigned long, max_root_iterations, BOOST_MATH_MAX_ROOT_ITERATION_POLICY)\n//\n// Define the names for each possible policy:\n//\n#define BOOST_MATH_PARAMETER(name)\\\n   BOOST_PARAMETER_TEMPLATE_KEYWORD(name##_name)\\\n   BOOST_PARAMETER_NAME(name##_name)\n\nstruct default_policy{};\n\nnamespace detail{\n//\n// Trait to work out bits precision from digits10 and digits2:\n//\ntemplate <class Digits10, class Digits2>\nstruct precision\n{\n   //\n   // Now work out the precision:\n   //\n   typedef typename mpl::if_c<\n      (Digits10::value == 0),\n      digits2<0>,\n      digits2<((Digits10::value + 1) * 1000L) / 301L>\n   >::type digits2_type;\npublic:\n#ifdef __BORLANDC__\n   typedef typename mpl::if_c<\n      (Digits2::value > ::boost::math::policies::detail::precision<Digits10,Digits2>::digits2_type::value),\n      Digits2, digits2_type>::type type;\n#else\n   typedef typename mpl::if_c<\n      (Digits2::value > digits2_type::value),\n      Digits2, digits2_type>::type type;\n#endif\n};\n\ntemplate <class A, class B, bool b>\nstruct select_result\n{\n   typedef A type;\n};\ntemplate <class A, class B>\nstruct select_result<A, B, false>\n{\n   typedef typename mpl::deref<B>::type type;\n};\n\ntemplate <class Seq, class Pred, class DefaultType>\nstruct find_arg\n{\nprivate:\n   typedef typename mpl::find_if<Seq, Pred>::type iter;\n   typedef typename mpl::end<Seq>::type end_type;\npublic:\n   typedef typename select_result<\n      DefaultType, iter,\n      ::boost::is_same<iter, end_type>::value>::type type;\n};\n\ndouble test_is_valid_arg(...);\ndouble test_is_default_arg(...);\nchar test_is_valid_arg(const default_policy*);\nchar test_is_default_arg(const default_policy*);\n\ntemplate <class T>\nstruct is_valid_policy_imp \n{\n   BOOST_STATIC_CONSTANT(bool, value = sizeof(::boost::math::policies::detail::test_is_valid_arg(static_cast<T*>(0))) == 1);\n};\n\ntemplate <class T>\nstruct is_default_policy_imp\n{\n   BOOST_STATIC_CONSTANT(bool, value = sizeof(::boost::math::policies::detail::test_is_default_arg(static_cast<T*>(0))) == 1);\n};\n\ntemplate <class T> struct is_valid_policy \n: public mpl::bool_< \n   ::boost::math::policies::detail::is_valid_policy_imp<T>::value>\n{};\n\ntemplate <class T> struct is_default_policy \n: public mpl::bool_< \n   ::boost::math::policies::detail::is_default_policy_imp<T>::value>\n{\n   template <class U>\n   struct apply\n   {\n      typedef is_default_policy<U> type;\n   };\n};\n\ntemplate <class Seq, class T, int N>\nstruct append_N\n{\n   typedef typename mpl::push_back<Seq, T>::type new_seq;\n   typedef typename append_N<new_seq, T, N-1>::type type;\n};\n\ntemplate <class Seq, class T>\nstruct append_N<Seq, T, 0>\n{\n   typedef Seq type;\n};\n\n//\n// Traits class to work out what template parameters our default\n// policy<> class will have when modified for forwarding:\n//\ntemplate <bool f, bool d>\nstruct default_args\n{\n   typedef promote_float<false> arg1;\n   typedef promote_double<false> arg2;\n};\n\ntemplate <>\nstruct default_args<false, false>\n{\n   typedef default_policy arg1;\n   typedef default_policy arg2;\n};\n\ntemplate <>\nstruct default_args<true, false>\n{\n   typedef promote_float<false> arg1;\n   typedef default_policy arg2;\n};\n\ntemplate <>\nstruct default_args<false, true>\n{\n   typedef promote_double<false> arg1;\n   typedef default_policy arg2;\n};\n\ntypedef default_args<BOOST_MATH_PROMOTE_FLOAT_POLICY, BOOST_MATH_PROMOTE_DOUBLE_POLICY>::arg1 forwarding_arg1;\ntypedef default_args<BOOST_MATH_PROMOTE_FLOAT_POLICY, BOOST_MATH_PROMOTE_DOUBLE_POLICY>::arg2 forwarding_arg2;\n\n} // detail\n//\n// Now define the policy type with enough arguments to handle all\n// the policies:\n//\ntemplate <class A1 = default_policy, \n          class A2 = default_policy, \n          class A3 = default_policy,\n          class A4 = default_policy,\n          class A5 = default_policy,\n          class A6 = default_policy,\n          class A7 = default_policy,\n          class A8 = default_policy,\n          class A9 = default_policy,\n          class A10 = default_policy,\n          class A11 = default_policy,\n          class A12 = default_policy,\n          class A13 = default_policy>\nstruct policy\n{\nprivate:\n   //\n   // Validate all our arguments:\n   //\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A1>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A2>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A3>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A4>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A5>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A6>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A7>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A8>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A9>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A10>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A11>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A12>::value);\n   BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy<A13>::value);\n   //\n   // Typelist of the arguments:\n   //\n   typedef mpl::list<A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13> arg_list;\n\npublic:\n   typedef typename detail::find_arg<arg_list, is_domain_error<mpl::_1>, domain_error<> >::type domain_error_type;\n   typedef typename detail::find_arg<arg_list, is_pole_error<mpl::_1>, pole_error<> >::type pole_error_type;\n   typedef typename detail::find_arg<arg_list, is_overflow_error<mpl::_1>, overflow_error<> >::type overflow_error_type;\n   typedef typename detail::find_arg<arg_list, is_underflow_error<mpl::_1>, underflow_error<> >::type underflow_error_type;\n   typedef typename detail::find_arg<arg_list, is_denorm_error<mpl::_1>, denorm_error<> >::type denorm_error_type;\n   typedef typename detail::find_arg<arg_list, is_evaluation_error<mpl::_1>, evaluation_error<> >::type evaluation_error_type;\n   typedef typename detail::find_arg<arg_list, is_rounding_error<mpl::_1>, rounding_error<> >::type rounding_error_type;\n   typedef typename detail::find_arg<arg_list, is_indeterminate_result_error<mpl::_1>, indeterminate_result_error<> >::type indeterminate_result_error_type;\nprivate:\n   //\n   // Now work out the precision:\n   //\n   typedef typename detail::find_arg<arg_list, is_digits10<mpl::_1>, digits10<> >::type digits10_type;\n   typedef typename detail::find_arg<arg_list, is_digits2<mpl::_1>, digits2<> >::type bits_precision_type;\npublic:\n   typedef typename detail::precision<digits10_type, bits_precision_type>::type precision_type;\n   //\n   // Internal promotion:\n   //\n   typedef typename detail::find_arg<arg_list, is_promote_float<mpl::_1>, promote_float<> >::type promote_float_type;\n   typedef typename detail::find_arg<arg_list, is_promote_double<mpl::_1>, promote_double<> >::type promote_double_type;\n   //\n   // Discrete quantiles:\n   //\n   typedef typename detail::find_arg<arg_list, is_discrete_quantile<mpl::_1>, discrete_quantile<> >::type discrete_quantile_type;\n   //\n   // Mathematically undefined properties:\n   //\n   typedef typename detail::find_arg<arg_list, is_assert_undefined<mpl::_1>, assert_undefined<> >::type assert_undefined_type;\n   //\n   // Max iterations:\n   //\n   typedef typename detail::find_arg<arg_list, is_max_series_iterations<mpl::_1>, max_series_iterations<> >::type max_series_iterations_type;\n   typedef typename detail::find_arg<arg_list, is_max_root_iterations<mpl::_1>, max_root_iterations<> >::type max_root_iterations_type;\n};\n//\n// These full specializations are defined to reduce the amount of\n// template instantiations that have to take place when using the default\n// policies, they have quite a large impact on compile times:\n//\ntemplate <>\nstruct policy<default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy>\n{\npublic:\n   typedef domain_error<> domain_error_type;\n   typedef pole_error<> pole_error_type;\n   typedef overflow_error<> overflow_error_type;\n   typedef underflow_error<> underflow_error_type;\n   typedef denorm_error<> denorm_error_type;\n   typedef evaluation_error<> evaluation_error_type;\n   typedef rounding_error<> rounding_error_type;\n   typedef indeterminate_result_error<> indeterminate_result_error_type;\n#if BOOST_MATH_DIGITS10_POLICY == 0\n   typedef digits2<> precision_type;\n#else\n   typedef detail::precision<digits10<>, digits2<> >::type precision_type;\n#endif\n   typedef promote_float<> promote_float_type;\n   typedef promote_double<> promote_double_type;\n   typedef discrete_quantile<> discrete_quantile_type;\n   typedef assert_undefined<> assert_undefined_type;\n   typedef max_series_iterations<> max_series_iterations_type;\n   typedef max_root_iterations<> max_root_iterations_type;\n};\n\ntemplate <>\nstruct policy<detail::forwarding_arg1, detail::forwarding_arg2, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy, default_policy>\n{\npublic:\n   typedef domain_error<> domain_error_type;\n   typedef pole_error<> pole_error_type;\n   typedef overflow_error<> overflow_error_type;\n   typedef underflow_error<> underflow_error_type;\n   typedef denorm_error<> denorm_error_type;\n   typedef evaluation_error<> evaluation_error_type;\n   typedef rounding_error<> rounding_error_type;\n   typedef indeterminate_result_error<> indeterminate_result_error_type;\n#if BOOST_MATH_DIGITS10_POLICY == 0\n   typedef digits2<> precision_type;\n#else\n   typedef detail::precision<digits10<>, digits2<> >::type precision_type;\n#endif\n   typedef promote_float<false> promote_float_type;\n   typedef promote_double<false> promote_double_type;\n   typedef discrete_quantile<> discrete_quantile_type;\n   typedef assert_undefined<> assert_undefined_type;\n   typedef max_series_iterations<> max_series_iterations_type;\n   typedef max_root_iterations<> max_root_iterations_type;\n};\n\ntemplate <class Policy, \n          class A1 = default_policy, \n          class A2 = default_policy, \n          class A3 = default_policy,\n          class A4 = default_policy,\n          class A5 = default_policy,\n          class A6 = default_policy,\n          class A7 = default_policy,\n          class A8 = default_policy,\n          class A9 = default_policy,\n          class A10 = default_policy,\n          class A11 = default_policy,\n          class A12 = default_policy,\n          class A13 = default_policy>\nstruct normalise\n{\nprivate:\n   typedef mpl::list<A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13> arg_list;\n   typedef typename detail::find_arg<arg_list, is_domain_error<mpl::_1>, typename Policy::domain_error_type >::type domain_error_type;\n   typedef typename detail::find_arg<arg_list, is_pole_error<mpl::_1>, typename Policy::pole_error_type >::type pole_error_type;\n   typedef typename detail::find_arg<arg_list, is_overflow_error<mpl::_1>, typename Policy::overflow_error_type >::type overflow_error_type;\n   typedef typename detail::find_arg<arg_list, is_underflow_error<mpl::_1>, typename Policy::underflow_error_type >::type underflow_error_type;\n   typedef typename detail::find_arg<arg_list, is_denorm_error<mpl::_1>, typename Policy::denorm_error_type >::type denorm_error_type;\n   typedef typename detail::find_arg<arg_list, is_evaluation_error<mpl::_1>, typename Policy::evaluation_error_type >::type evaluation_error_type;\n   typedef typename detail::find_arg<arg_list, is_rounding_error<mpl::_1>, typename Policy::rounding_error_type >::type rounding_error_type;\n   typedef typename detail::find_arg<arg_list, is_indeterminate_result_error<mpl::_1>, typename Policy::indeterminate_result_error_type >::type indeterminate_result_error_type;\n   //\n   // Now work out the precision:\n   //\n   typedef typename detail::find_arg<arg_list, is_digits10<mpl::_1>, digits10<> >::type digits10_type;\n   typedef typename detail::find_arg<arg_list, is_digits2<mpl::_1>, typename Policy::precision_type >::type bits_precision_type;\n   typedef typename detail::precision<digits10_type, bits_precision_type>::type precision_type;\n   //\n   // Internal promotion:\n   //\n   typedef typename detail::find_arg<arg_list, is_promote_float<mpl::_1>, typename Policy::promote_float_type >::type promote_float_type;\n   typedef typename detail::find_arg<arg_list, is_promote_double<mpl::_1>, typename Policy::promote_double_type >::type promote_double_type;\n   //\n   // Discrete quantiles:\n   //\n   typedef typename detail::find_arg<arg_list, is_discrete_quantile<mpl::_1>, typename Policy::discrete_quantile_type >::type discrete_quantile_type;\n   //\n   // Mathematically undefined properties:\n   //\n   typedef typename detail::find_arg<arg_list, is_assert_undefined<mpl::_1>, typename Policy::assert_undefined_type >::type assert_undefined_type;\n   //\n   // Max iterations:\n   //\n   typedef typename detail::find_arg<arg_list, is_max_series_iterations<mpl::_1>, typename Policy::max_series_iterations_type>::type max_series_iterations_type;\n   typedef typename detail::find_arg<arg_list, is_max_root_iterations<mpl::_1>, typename Policy::max_root_iterations_type>::type max_root_iterations_type;\n   //\n   // Define a typelist of the policies:\n   //\n   typedef mpl::vector<\n      domain_error_type,\n      pole_error_type,\n      overflow_error_type,\n      underflow_error_type,\n      denorm_error_type,\n      evaluation_error_type,\n      rounding_error_type,\n      indeterminate_result_error_type,\n      precision_type,\n      promote_float_type,\n      promote_double_type,\n      discrete_quantile_type,\n      assert_undefined_type,\n      max_series_iterations_type,\n      max_root_iterations_type> result_list;\n   //\n   // Remove all the policies that are the same as the default:\n   //\n   typedef typename mpl::remove_if<result_list, detail::is_default_policy<mpl::_> >::type reduced_list;\n   //\n   // Pad out the list with defaults:\n   //\n   typedef typename detail::append_N<reduced_list, default_policy, (14 - ::boost::mpl::size<reduced_list>::value)>::type result_type;\npublic:\n   typedef policy<\n      typename mpl::at<result_type, mpl::int_<0> >::type,\n      typename mpl::at<result_type, mpl::int_<1> >::type,\n      typename mpl::at<result_type, mpl::int_<2> >::type,\n      typename mpl::at<result_type, mpl::int_<3> >::type,\n      typename mpl::at<result_type, mpl::int_<4> >::type,\n      typename mpl::at<result_type, mpl::int_<5> >::type,\n      typename mpl::at<result_type, mpl::int_<6> >::type,\n      typename mpl::at<result_type, mpl::int_<7> >::type,\n      typename mpl::at<result_type, mpl::int_<8> >::type,\n      typename mpl::at<result_type, mpl::int_<9> >::type,\n      typename mpl::at<result_type, mpl::int_<10> >::type,\n      typename mpl::at<result_type, mpl::int_<11> >::type,\n      typename mpl::at<result_type, mpl::int_<12> >::type > type;\n};\n//\n// Full specialisation to speed up compilation of the common case:\n//\ntemplate <>\nstruct normalise<policy<>, \n          promote_float<false>, \n          promote_double<false>, \n          discrete_quantile<>,\n          assert_undefined<>,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy>\n{\n   typedef policy<detail::forwarding_arg1, detail::forwarding_arg2> type;\n};\n\ntemplate <>\nstruct normalise<policy<detail::forwarding_arg1, detail::forwarding_arg2>,\n          promote_float<false>,\n          promote_double<false>,\n          discrete_quantile<>,\n          assert_undefined<>,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy,\n          default_policy>\n{\n   typedef policy<detail::forwarding_arg1, detail::forwarding_arg2> type;\n};\n\ninline policy<> make_policy()\n{ return policy<>(); }\n\ntemplate <class A1>\ninline typename normalise<policy<>, A1>::type make_policy(const A1&)\n{ \n   typedef typename normalise<policy<>, A1>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2>\ninline typename normalise<policy<>, A1, A2>::type make_policy(const A1&, const A2&)\n{ \n   typedef typename normalise<policy<>, A1, A2>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3>\ninline typename normalise<policy<>, A1, A2, A3>::type make_policy(const A1&, const A2&, const A3&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4>\ninline typename normalise<policy<>, A1, A2, A3, A4>::type make_policy(const A1&, const A2&, const A3&, const A4&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3, A4>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4, class A5>\ninline typename normalise<policy<>, A1, A2, A3, A4, A5>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3, A4, A5>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4, class A5, class A6>\ninline typename normalise<policy<>, A1, A2, A3, A4, A5, A6>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4, class A5, class A6, class A7>\ninline typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8>\ninline typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9>\ninline typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8, A9>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&, const A9&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8, A9>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10>\ninline typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&, const A9&, const A10&)\n{ \n   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>::type result_type;\n   return result_type(); \n}\n\ntemplate <class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11>\ninline typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&, const A9&, const A10&, const A11&)\n{\n   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11>::type result_type;\n   return result_type();\n}\n\n//\n// Traits class to handle internal promotion:\n//\ntemplate <class Real, class Policy>\nstruct evaluation\n{\n   typedef Real type;\n};\n\ntemplate <class Policy>\nstruct evaluation<float, Policy>\n{\n   typedef typename mpl::if_<typename Policy::promote_float_type, double, float>::type type;\n};\n\ntemplate <class Policy>\nstruct evaluation<double, Policy>\n{\n   typedef typename mpl::if_<typename Policy::promote_double_type, long double, double>::type type;\n};\n\n#ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n\ntemplate <class Real>\nstruct basic_digits : public mpl::int_<0>{ };\ntemplate <>\nstruct basic_digits<float> : public mpl::int_<FLT_MANT_DIG>{ };\ntemplate <>\nstruct basic_digits<double> : public mpl::int_<DBL_MANT_DIG>{ };\ntemplate <>\nstruct basic_digits<long double> : public mpl::int_<LDBL_MANT_DIG>{ };\n\ntemplate <class Real, class Policy>\nstruct precision\n{\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<Real>::radix == 2);\n   typedef typename Policy::precision_type precision_type;\n   typedef basic_digits<Real> digits_t;\n   typedef typename mpl::if_<\n      mpl::equal_to<digits_t, mpl::int_<0> >,\n      // Possibly unknown precision:\n      precision_type,\n      typename mpl::if_<\n         mpl::or_<mpl::less_equal<digits_t, precision_type>, mpl::less_equal<precision_type, mpl::int_<0> > >,\n         // Default case, full precision for RealType:\n         digits2< ::std::numeric_limits<Real>::digits>,\n         // User customised precision:\n         precision_type\n      >::type\n   >::type type;\n};\n\ntemplate <class Policy>\nstruct precision<float, Policy>\n{\n   typedef digits2<FLT_MANT_DIG> type;\n};\ntemplate <class Policy>\nstruct precision<double, Policy>\n{\n   typedef digits2<DBL_MANT_DIG> type;\n};\ntemplate <class Policy>\nstruct precision<long double, Policy>\n{\n   typedef digits2<LDBL_MANT_DIG> type;\n};\n\n#else\n\ntemplate <class Real, class Policy>\nstruct precision\n{\n   BOOST_STATIC_ASSERT((::std::numeric_limits<Real>::radix == 2) || ((::std::numeric_limits<Real>::is_specialized == 0) || (::std::numeric_limits<Real>::digits == 0)));\n#ifndef __BORLANDC__\n   typedef typename Policy::precision_type precision_type;\n   typedef typename mpl::if_c<\n      ((::std::numeric_limits<Real>::is_specialized == 0) || (::std::numeric_limits<Real>::digits == 0)),\n      // Possibly unknown precision:\n      precision_type,\n      typename mpl::if_c<\n         ((::std::numeric_limits<Real>::digits <= precision_type::value) \n         || (Policy::precision_type::value <= 0)),\n         // Default case, full precision for RealType:\n         digits2< ::std::numeric_limits<Real>::digits>,\n         // User customised precision:\n         precision_type\n      >::type\n   >::type type;\n#else\n   typedef typename Policy::precision_type precision_type;\n   typedef mpl::int_< ::std::numeric_limits<Real>::digits> digits_t;\n   typedef mpl::bool_< ::std::numeric_limits<Real>::is_specialized> spec_t;\n   typedef typename mpl::if_<\n      mpl::or_<mpl::equal_to<spec_t, mpl::false_>, mpl::equal_to<digits_t, mpl::int_<0> > >,\n      // Possibly unknown precision:\n      precision_type,\n      typename mpl::if_<\n         mpl::or_<mpl::less_equal<digits_t, precision_type>, mpl::less_equal<precision_type, mpl::int_<0> > >,\n         // Default case, full precision for RealType:\n         digits2< ::std::numeric_limits<Real>::digits>,\n         // User customised precision:\n         precision_type\n      >::type\n   >::type type;\n#endif\n};\n\n#endif\n\n#ifdef BOOST_MATH_USE_FLOAT128\n\ntemplate <class Policy>\nstruct precision<__float128, Policy>\n{\n   typedef mpl::int_<113> type;\n};\n\n#endif\n\nnamespace detail{\n\ntemplate <class T, class Policy>\ninline int digits_imp(mpl::true_ const&)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<T>::is_specialized);\n#else\n   BOOST_ASSERT(::std::numeric_limits<T>::is_specialized);\n#endif\n   typedef typename boost::math::policies::precision<T, Policy>::type p_t;\n   return p_t::value;\n}\n\ntemplate <class T, class Policy>\ninline int digits_imp(mpl::false_ const&)\n{\n   return tools::digits<T>();\n}\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline int digits(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T))\n{\n   typedef mpl::bool_< std::numeric_limits<T>::is_specialized > tag_type;\n   return detail::digits_imp<T, Policy>(tag_type());\n}\n\ntemplate <class Policy>\ninline unsigned long get_max_series_iterations()\n{\n   typedef typename Policy::max_series_iterations_type iter_type;\n   return iter_type::value;\n}\n\ntemplate <class Policy>\ninline unsigned long get_max_root_iterations()\n{\n   typedef typename Policy::max_root_iterations_type iter_type;\n   return iter_type::value;\n}\n\nnamespace detail{\n\ntemplate <class T, class Digits, class Small, class Default>\nstruct series_factor_calc\n{\n   static T get()\n   {\n      return ldexp(T(1.0), 1 - Digits::value);\n   }\n};\n\ntemplate <class T, class Digits>\nstruct series_factor_calc<T, Digits, mpl::true_, mpl::true_>\n{\n   static T get()\n   {\n      return boost::math::tools::epsilon<T>();\n   }\n};\ntemplate <class T, class Digits>\nstruct series_factor_calc<T, Digits, mpl::true_, mpl::false_>\n{\n   static T get()\n   {\n      static const boost::uintmax_t v = static_cast<boost::uintmax_t>(1u) << (Digits::value - 1);\n      return 1 / static_cast<T>(v);\n   }\n};\ntemplate <class T, class Digits>\nstruct series_factor_calc<T, Digits, mpl::false_, mpl::true_>\n{\n   static T get()\n   {\n      return boost::math::tools::epsilon<T>();\n   }\n};\n\ntemplate <class T, class Policy>\ninline T get_epsilon_imp(mpl::true_ const&)\n{\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<T>::is_specialized);\n   BOOST_STATIC_ASSERT( ::std::numeric_limits<T>::radix == 2);\n#else\n   BOOST_ASSERT(::std::numeric_limits<T>::is_specialized);\n   BOOST_ASSERT(::std::numeric_limits<T>::radix == 2);\n#endif\n   typedef typename boost::math::policies::precision<T, Policy>::type p_t;\n   typedef mpl::bool_<p_t::value <= std::numeric_limits<boost::uintmax_t>::digits> is_small_int;\n   typedef mpl::bool_<p_t::value >= std::numeric_limits<T>::digits> is_default_value;\n   return series_factor_calc<T, p_t, is_small_int, is_default_value>::get();\n}\n\ntemplate <class T, class Policy>\ninline T get_epsilon_imp(mpl::false_ const&)\n{\n   return tools::epsilon<T>();\n}\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline T get_epsilon(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T))\n{\n   typedef mpl::bool_< (std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::radix == 2)) > tag_type;\n   return detail::get_epsilon_imp<T, Policy>(tag_type());\n}\n\nnamespace detail{\n\ntemplate <class A1, \n          class A2, \n          class A3,\n          class A4,\n          class A5,\n          class A6,\n          class A7,\n          class A8,\n          class A9,\n          class A10,\n          class A11>\nchar test_is_policy(const policy<A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11>*);\ndouble test_is_policy(...);\n\ntemplate <class P>\nstruct is_policy_imp\n{\n   BOOST_STATIC_CONSTANT(bool, value = (sizeof(::boost::math::policies::detail::test_is_policy(static_cast<P*>(0))) == 1));\n};\n\n}\n\ntemplate <class P>\nstruct is_policy : public mpl::bool_< ::boost::math::policies::detail::is_policy_imp<P>::value> {};\n\n//\n// Helper traits class for distribution error handling:\n//\ntemplate <class Policy>\nstruct constructor_error_check\n{\n   typedef typename Policy::domain_error_type domain_error_type;\n   typedef typename mpl::if_c<\n      (domain_error_type::value == throw_on_error) || (domain_error_type::value == user_error),\n      mpl::true_,\n      mpl::false_>::type type;\n};\n\ntemplate <class Policy>\nstruct method_error_check\n{\n   typedef typename Policy::domain_error_type domain_error_type;\n   typedef typename mpl::if_c<\n      (domain_error_type::value == throw_on_error) && (domain_error_type::value != user_error),\n      mpl::false_,\n      mpl::true_>::type type;\n};\n\n}}} // namespaces\n\n#endif // BOOST_MATH_POLICY_HPP\n\n\n\n", "meta": {"hexsha": "c8ad26d28f0e438ef0d32caa4fc5b0224f36def2", "size": 35177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/policies/policy.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/math/policies/policy.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/math/policies/policy.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 35.4606854839, "max_line_length": 222, "alphanum_fraction": 0.7261278676, "num_tokens": 8924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.028436035206176487, "lm_q1q2_score": 0.0070517791832555}}
{"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_BASE_HPP\n#define AMA_TENSOR_DETAIL_TENSOR_BASE_HPP 1\n\n#include <boost/mpl/plus.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* this class is needed to retrieve the information of DERIVED type */\n    template <typename T> struct tensor_traits;\n\n    /*\n     * This class is the base for every class that represent a tensor, it uses\n     * the CRTP to implement the static polymorphism. The previous traits need\n     * to access to the property of tensor:\n     *   - value_type, the scalar type used to represent the numbers\n     *   - dimension, the dimension of tensor\n     *   - order, the order (or rank) of tensor\n     *\n     * Moreover this class is only for internal purpose, the developers can use\n     * that class to implement new tensors. The end user can ignore this class.\n     */\n    template <typename DERIVED>\n    class tensor_base\n    {\n    public:\n      /* the type retrieved through the tensor_traits */\n      typedef typename tensor_traits<DERIVED>::value_type value_type;\n\n      typedef typename tensor_traits<DERIVED>::dimension_type dimension_type;\n\n      typedef typename tensor_traits<DERIVED>::controvariant_type controvariant_type;\n      typedef typename tensor_traits<DERIVED>::covariant_type covariant_type;\n      typedef typename ::boost::mpl::plus<controvariant_type,covariant_type>::type order_type;\n\n      typedef typename tensor_traits<DERIVED>::is_assignable is_assignable;\n      typedef typename tensor_traits<DERIVED>::is_temporary is_temporary;\n\n    private:\n      /* the foundamental types for CRTP */\n      typedef tensor_base<DERIVED> base_type;\n      typedef DERIVED derived_type;\n\n    public:\n      /* cast the object to the base class */\n      base_type & base() { return *static_cast<base_type *>(this); }\n      base_type const & base() const { return *static_cast<base_type const *>(this); }\n\n    public:\n      /* cast the object to the derived class */\n      derived_type & derived() { return *static_cast<derived_type *>(this); }\n      derived_type const & derived() const { return *static_cast<derived_type const *>(this); }\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_DETAIL_TENSOR_BASE_HPP */\n", "meta": {"hexsha": "b510533b6d8a5871cdd275e3792109a8e3ed6767", "size": 3804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/detail/tensor_base.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_base.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_base.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": 42.7415730337, "max_line_length": 95, "alphanum_fraction": 0.7284437434, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436780168531517, "lm_q2_score": 0.036220052613898816, "lm_q1q2_score": 0.007040012003489966}}
{"text": "/*********************************************************************\n\nCopyright (c) 2000-2007, Stanford University,\nRensselaer Polytechnic Institute, Kenneth E. Jansen,\nCharles A. Taylor (see SimVascular Acknowledgements file\nfor additional contributors to the source code).\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\nRedistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and/or other materials provided with the distribution.\nNeither the name of the Stanford University or Rensselaer Polytechnic\nInstitute nor the names of its contributors may be used to endorse or\npromote products derived from this software without specific prior\nwritten 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\nFOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\nOF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\nAND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\nTHE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\nDAMAGE.\n\n**********************************************************************/\n\n#include \"cmd.h\"\n#include \"cvSolverIO.h\"\n\n#ifdef USE_ZLIB\n#include \"zlib.h\"\n#else\n#include <stdlib.h>\n#define gzopen fopen\n#define gzprintf fprintf\n#define gzFile FILE*\n#define gzclose fclose\n#define gzgets fgets\n#define gzeof feof\n#endif\n#include <time.h>\n#include <fstream>\nusing namespace std;\n\n// added std::vector\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <array>\n#include <boost/config.hpp>\n\n\n\n// =========\n//   Cross\n// =========\ninline\nvoid Cross(double ax, double ay, double az,\ndouble bx, double by, double bz,\ndouble *prodx, double *prody, double *prodz)\n{\n    (*prodx) = ay * bz - az * by;\n    (*prody) = -(ax * bz - az * bx);\n    (*prodz) = ax * by - ay * bx;\n    return;\n}\n\n\n// =======\n//   Dot\n// =======\n\ninline\ndouble Dot(double ax, double ay, double az,\ndouble bx, double by, double bz)\n{\n    double product;\n\n    product = ax * bx + ay * by + az * bz;\n    return product;\n}\n\n//\n// some helpful global variables\n//\nextern const char* oformat;\n\nextern int numNodes_;\nextern int numElements_;\nextern int numMeshEdges_;\nextern int numMeshFaces_;\nextern int numSolnVars_;\nextern int numBoundaryFaces_;\nextern int** boundaryElements_;\nextern double* nodes_;\nextern int* elements_;\nextern int* boundaryElementsIds_;\nextern std::unordered_map<int, std::vector<int>> boundaryElementIdToIndicesMap_;\nextern int* xadj_;\nextern int xadjSize_;\nextern int* adjncy_;\nextern int adjncySize_;\nextern int* iBC_;\nextern int* iBCB_;\nextern double* BCB_;\nextern int   DisplacementNumElements_;\nextern int*  DisplacementConn_[3];\nextern int   DisplacementNumNodes_;\nextern int*  DisplacementNodeMap_;\nextern int* ndsurfg_;\n\nint writeGEOMBCDAT(char* filename);\n\ngzFile fp_ = NULL;\nchar buffer_[MAXCMDLINELENGTH];\n\nint NWopenFile(char* filename) {\n\n    if (fp_ != NULL) {\n        fprintf(stderr, \"ERROR: Apparently a file is already open! (opening %s)\\n\", filename);\n        return CV_ERROR;\n    }\n\n    fp_ = NULL;\n    fp_ = gzopen(filename, \"rb\");\n    if (fp_ == NULL) {\n        fprintf(stderr, \"ERROR: could not open file (%s)\\n\", filename);\n        return CV_ERROR;\n    }\n\n    return CV_OK;\n}\n\n\nint NWcloseFile() {\n    if (fp_ == NULL) {\n        fprintf(stderr, \"Closing a file already closed!\\n\");\n        return CV_OK;\n    }\n    gzclose(fp_);\n    fp_ = NULL;\n    return CV_OK;\n}\n\n\nint NWgetNextLine(int *eof) {\n    for (int i = 0; i < MAXCMDLINELENGTH; i++) {\n        buffer_[i] = '\\0';\n    }\n#ifdef USE_ZLIB\n    gzgets(fp_,buffer_,MAXCMDLINELENGTH);\n#else\n    fgets(buffer_, MAXCMDLINELENGTH, fp_);\n#endif\n\n    *eof = gzeof(fp_);\n\n    return CV_OK;\n}\n\n\nint NWgetNextNonBlankLine(int *eof) {\n    NWgetNextLine(eof);\n    for (int i = 0; i < MAXCMDLINELENGTH; i++) {\n        if (buffer_[i] == '\\0') break;\n        if (buffer_[i] == '\\n') break;\n        if (buffer_[i] != ' ') return CV_OK;\n    }\n    return CV_ERROR;\n}\n\n\nint parseCmdStr(char *cmd, char *mystr) {\n    // parse command string\n    int n = 0;\n    int end = 0;\n    char ignored[MAXSTRINGLENGTH];\n    ignored[0] = '\\0';\n    cmd_token_get(&n, cmd, ignored, &end);\n    mystr[0] = '\\0';\n    cmd_token_get(&n, cmd, mystr, &end);\n    return CV_OK;\n}\n\n\nint parseNum(char *cmd, int *num) {\n\n    // parse command string\n    char mystr[MAXSTRINGLENGTH];\n    parseCmdStr(cmd, mystr);\n\n    // do work\n    *num = 0;\n    if (sscanf(mystr, \"%i\", num) != 1) {\n        fprintf(stderr, \"error parsing num!\\n\");\n        return CV_ERROR;\n    }\n\n    return CV_OK;\n\n}\n\n\nint parseNum2(char *cmd, int *num) {\n\n    // parse command string\n    int n = 0;\n    int end = 0;\n    char ignored[MAXSTRINGLENGTH];\n    ignored[0] = '\\0';\n    cmd_token_get(&n, cmd, ignored, &end);\n    char infile[MAXPATHLEN];\n    infile[0] = '\\0';\n    cmd_token_get(&n, cmd, infile, &end);\n    char surfidstr[MAXSTRINGLENGTH];\n    surfidstr[0] = '\\0';\n    cmd_token_get(&n, cmd, surfidstr, &end);\n\n    // do work\n\n    *num = 0;\n\n    int surfID = 0;\n    if (sscanf(surfidstr, \"%i\", &surfID) != 1) {\n        fprintf(stderr, \"error parsing num!\\n\");\n        return CV_ERROR;\n    }\n\n    *num = surfID;\n\n    return CV_OK;\n\n}\n\n\nint parseDouble(char *cmd, double *num) {\n\n    // parse command string\n    char mystr[MAXSTRINGLENGTH];\n    parseCmdStr(cmd, mystr);\n\n    // do work\n    *num = 0.0;\n    if (sscanf(mystr, \"%lf\", num) != 1) {\n        fprintf(stderr, \"error parsing double!\\n\");\n        return CV_ERROR;\n    }\n\n    return CV_OK;\n\n}\n\n\nint parseDouble2(char *cmd, double *num) {\n\n    // parse command string\n\n    int n = 0;\n    int end = 0;\n    char ignored[MAXSTRINGLENGTH];\n    ignored[0] = '\\0';\n    cmd_token_get(&n, cmd, ignored, &end);\n    ignored[0] = '\\0';\n    cmd_token_get(&n, cmd, ignored, &end);\n\n    char mystr[MAXSTRINGLENGTH];\n    mystr[0] = '\\0';\n    cmd_token_get(&n, cmd, mystr, &end);\n\n\n    // do work\n    *num = 0.0;\n    if (sscanf(mystr, \"%lf\", num) != 1) {\n        fprintf(stderr, \"error parsing double!\\n\");\n        return CV_ERROR;\n    }\n\n    return CV_OK;\n\n}\n\n\nint parseDouble3(char *cmd, double *v1, double *v2, double *v3) {\n\n    // parse command string\n    int n = 0;\n    int end = 0;\n    char ignored[MAXSTRINGLENGTH];\n    ignored[0] = '\\0';\n    cmd_token_get(&n, cmd, ignored, &end);\n    char str1[MAXPATHLEN];\n    str1[0] = '\\0';\n    cmd_token_get(&n, cmd, str1, &end);\n    char str2[MAXSTRINGLENGTH];\n    str2[0] = '\\0';\n    cmd_token_get(&n, cmd, str2, &end);\n    char str3[MAXSTRINGLENGTH];\n    str3[0] = '\\0';\n    cmd_token_get(&n, cmd, str3, &end);\n\n    // do work\n    *v1 = 0.0;\n    if (sscanf(str1, \"%lf\", v1) != 1) {\n        fprintf(stderr, \"error parsing double!\\n\");\n        return CV_ERROR;\n    }\n    *v2 = 0.0;\n    if (sscanf(str2, \"%lf\", v2) != 1) {\n        fprintf(stderr, \"error parsing double!\\n\");\n        return CV_ERROR;\n    }\n    *v3 = 0.0;\n    if (sscanf(str3, \"%lf\", v3) != 1) {\n        fprintf(stderr, \"error parsing double!\\n\");\n        return CV_ERROR;\n    }\n\n    return CV_OK;\n\n}\n\n\nint parseFile(char *cmd) {\n\n    // parse command string\n    char infile[MAXPATHLEN];\n    parseCmdStr(cmd, infile);\n\n    // do work\n    return NWopenFile(infile);\n\n}\n\nint setNodesWithCode(char *cmd, int val) {\n\n    // enter\n    debugprint(stddbg, \"Entering setNodesWithCode.\\n\");\n\n    // do work\n    if (numNodes_ == 0) {\n        fprintf(stderr, \"ERROR:  Must specify number of nodes before you read them in!\\n\");\n        return CV_ERROR;\n    }\n\n    if (parseFile(cmd) == CV_ERROR) {\n        return CV_ERROR;\n    }\n\n    if (iBC_ == NULL) {\n        iBC_ = new int[numNodes_]();\n    }\n\n    int eof = 0;\n    int nodeId = 0;\n\n    while (NWgetNextNonBlankLine(&eof) == CV_OK) {\n        if (sscanf(buffer_, \"%i\", &nodeId) != 1) {\n            fprintf(stderr, \"WARNING:  line not of correct format (%s)\\n\", buffer_);\n        }\n        else {\n            // this should be a bit set instead of an int!!\n            iBC_[nodeId - 1] = val;\n        }\n    }\n    if (eof == 0) return CV_ERROR;\n    NWcloseFile();\n\n    // cleanup\n    debugprint(stddbg, \"Exiting setNodesWithCode.\\n\");\n    return CV_OK;\n\n}\n\n\nint check_node_order(int n0, int n1, int n2, int n3, int elementId,\n    int *k0, int *k1, int *k2, int *k3) {\n\n    int i, j0, j1, j2, j3;\n\n    if (n3 >= 0) {\n\n        if (phasta_node_order_ == 0) {\n            // Not necessary if using phasta-conn\n            // flip the middle to vertexes because we used a value of 1\n            // for node ordering in meshsim and scorec used the value of 0\n            j0 = n0;\n            j1 = n2;\n            j2 = n1;\n            j3 = n3;\n        }\n        else {\n            j0 = n0;\n            j1 = n1;\n            j2 = n2;\n            j3 = n3;\n        }\n\n    }\n    else {\n\n        j0 = n0;\n        j1 = n1;\n        j2 = n2;\n        j3 = -1;\n\n        for (i = 0; i < 4; i++) {\n            if (elements_[i*numElements_ + (elementId - 1)] != j0 &&\n                elements_[i*numElements_ + (elementId - 1)] != j1 &&\n                elements_[i*numElements_ + (elementId - 1)] != j2) {\n                j3 = elements_[i*numElements_ + (elementId - 1)];\n                break;\n            }\n        }\n        if (j3 < 0) {\n            //gzclose(fp);\n            fprintf(stderr, \"ERROR:  could not find nodes in element (%i %i %i %i)\\n\",\n                elementId, n0, n1, n2);\n            return CV_ERROR;\n        }\n\n    }\n\n    double a[3];\n    double b[3];\n    double c[3];\n    double norm0, norm1, norm2;\n\n    a[0] = nodes_[0 * numNodes_ + j1 - 1] - nodes_[0 * numNodes_ + j0 - 1];\n    a[1] = nodes_[1 * numNodes_ + j1 - 1] - nodes_[1 * numNodes_ + j0 - 1];\n    a[2] = nodes_[2 * numNodes_ + j1 - 1] - nodes_[2 * numNodes_ + j0 - 1];\n    b[0] = nodes_[0 * numNodes_ + j2 - 1] - nodes_[0 * numNodes_ + j0 - 1];\n    b[1] = nodes_[1 * numNodes_ + j2 - 1] - nodes_[1 * numNodes_ + j0 - 1];\n    b[2] = nodes_[2 * numNodes_ + j2 - 1] - nodes_[2 * numNodes_ + j0 - 1];\n    c[0] = nodes_[0 * numNodes_ + j3 - 1] - nodes_[0 * numNodes_ + j0 - 1];\n    c[1] = nodes_[1 * numNodes_ + j3 - 1] - nodes_[1 * numNodes_ + j0 - 1];\n    c[2] = nodes_[2 * numNodes_ + j3 - 1] - nodes_[2 * numNodes_ + j0 - 1];\n\n    Cross(a[0], a[1], a[2], b[0], b[1], b[2], &norm0, &norm1, &norm2);\n    double mydot = Dot(norm0, norm1, norm2, c[0], c[1], c[2]);\n\n    if (mydot > 0) {\n        int tmpj = j0;\n        j0 = j2;\n        j2 = j1;\n        j1 = tmpj;\n        debugprint(stdout, \"elementId %i : %i %i %i %i   (flipped) %lf\\n\", elementId, j0, j1, j2, j3, mydot);\n    }\n    else {\n        //debugprint(stdout,\"elementId %i : %i %i %i %i  %lf\\n\",elementId,j0,j1,j2,j3,mydot);\n    }\n\n    *k0 = j0; *k1 = j1; *k2 = j2; *k3 = j3;\n\n    return CV_OK;\n}\n\nint setBoundaryFacesWithCode(char* cmd, int setSurfID, int surfID, int setCode, int code, double value)\n{\n\n    // enter\n    debugprint(stddbg, \"Entering setBoundaryFacesWithCode.\\n\");\n\n    int i;\n\n    // parse command string\n    if (parseFile(cmd) == CV_ERROR) {\n        return CV_ERROR;\n    }\n\n    if (iBCB_ == NULL) {\n        iBCB_ = new int[2 * numBoundaryFaces_]();\n        BCB_ = new double[numBoundaryFaces_ * 6]();\n    }\n\n    if (ndsurfg_ == NULL) {\n        ndsurfg_ = new int[numNodes_]();\n    }\n\n    int elementId, matId;\n\n    int eof = 0;\n\n    vector<vector<int>> elem_edge; // vector of element edges - stored as node pairs [n1,n2] *** added by KDL 07/02/14\n    vector<vector<int>> surf_data; // vector of surface elements -stored as  [ids,n1,n2,n3]  *** added by KDL 07/02/14\n\n    while (NWgetNextNonBlankLine(&eof) == CV_OK) {\n\n        int n0, n1, n2;\n        if (sscanf(buffer_, \"%i %i %i %i %i\", &elementId, &matId, &n0, &n1, &n2) != 5) {\n            fprintf(stderr, \"WARNING:  line not of correct format (%s)\\n\", buffer_);\n            NWcloseFile();\n            return CV_ERROR;\n        }\n\n        /*\n         * store node pairings for each element *** added by KDL 07/02/14\n         */\n        /*\n         if (setSurfID) {\n\n         // arrange each edge's node pair - lowest index first\n         vector <int> node_pair;\n\n         // check and add n0 & n1\n         if (n0 < n1) {\n         node_pair.push_back(int(n0));\n         node_pair.push_back(int(n1));\n         } else {\n         node_pair.push_back(int(n1));\n         node_pair.push_back(int(n0));\n         }\n\n         elem_edge.push_back(node_pair);\n         node_pair.clear();\n\n         // check and add n1 & n2\n         if (n1 < n2) {\n         node_pair.push_back(int(n1));\n         node_pair.push_back(int(n2));\n         } else {\n         node_pair.push_back(int(n2));\n         node_pair.push_back(int(n1));\n         }\n\n         elem_edge.push_back(node_pair);\n         node_pair.clear();\n\n         // check and add n2 & n0\n         if (n0 < n2) {\n         node_pair.push_back(int(n0));\n         node_pair.push_back(int(n2));\n         } else {\n         node_pair.push_back(int(n2));\n         node_pair.push_back(int(n0));\n         }\n\n         elem_edge.push_back(node_pair);\n         node_pair.clear();\n         }\n         */\n\n        int j0 = n0;\n        int j1 = n1;\n        int j2 = n2;\n        int j3 = -1;\n\n        for (i = 0; i < 4; i++) {\n            if (elements_[i * numElements_ + (elementId - 1)] != j0 && elements_[i * numElements_ + (elementId - 1)] != j1 &&\n                elements_[i * numElements_ + (elementId - 1)] != j2) {\n                j3 = elements_[i * numElements_ + (elementId - 1)];\n                break;\n            }\n        }\n        if (j3 < 0) {\n            NWcloseFile();\n            fprintf(stderr, \"ERROR:  could not find nodes in element (%i %i %i %i)\\n\", elementId, n0, n1, n2);\n            return CV_ERROR;\n        }\n\n        double a[3];\n        double b[3];\n        double c[3];\n        double norm0, norm1, norm2;\n\n        a[0] = nodes_[0 * numNodes_ + j1 - 1] - nodes_[0 * numNodes_ + j0 - 1];\n        a[1] = nodes_[1 * numNodes_ + j1 - 1] - nodes_[1 * numNodes_ + j0 - 1];\n        a[2] = nodes_[2 * numNodes_ + j1 - 1] - nodes_[2 * numNodes_ + j0 - 1];\n        b[0] = nodes_[0 * numNodes_ + j2 - 1] - nodes_[0 * numNodes_ + j0 - 1];\n        b[1] = nodes_[1 * numNodes_ + j2 - 1] - nodes_[1 * numNodes_ + j0 - 1];\n        b[2] = nodes_[2 * numNodes_ + j2 - 1] - nodes_[2 * numNodes_ + j0 - 1];\n        c[0] = nodes_[0 * numNodes_ + j3 - 1] - nodes_[0 * numNodes_ + j0 - 1];\n        c[1] = nodes_[1 * numNodes_ + j3 - 1] - nodes_[1 * numNodes_ + j0 - 1];\n        c[2] = nodes_[2 * numNodes_ + j3 - 1] - nodes_[2 * numNodes_ + j0 - 1];\n\n        Cross(a[0], a[1], a[2], b[0], b[1], b[2], &norm0, &norm1, &norm2);\n        double mydot = Dot(norm0, norm1, norm2, c[0], c[1], c[2]);\n\n        if (mydot > 0) {\n            std::swap(j0, j1);\n            /*\n            int tmpj = j0;\n            j0 = j2;\n            j2 = j1;\n            j1 = tmpj;\n            */\n            fprintf(stdout, \"elementId %i : %i %i %i %i   (flipped0) %lf\\n\", elementId, j0, j1, j2, j3, mydot);\n        }\n        else {\n            // fprintf(stdout,\"elementId %i : %i %i %i %i  %lf\\n\",elementId,j0,j1,j2,j3,mydot);\n        }\n\n        // find matching element already read in\n        auto iter = boundaryElementIdToIndicesMap_.find(elementId - 1);\n\n        if (iter == boundaryElementIdToIndicesMap_.end()) {\n            fprintf(stderr, \"ERROR: could not find pressure face in boundary faces!\\n\");\n            return CV_ERROR;\n        }\n\n        for (int i : iter->second) {\n            std::array<int, 4> elementNodeIds{\n                { boundaryElements_[0][i], boundaryElements_[1][i], boundaryElements_[2][i], boundaryElements_[3][i] } };\n\n            if (std::find(elementNodeIds.begin(), elementNodeIds.end(), j0) != elementNodeIds.end() &&\n                std::find(elementNodeIds.begin(), elementNodeIds.end(), j1) != elementNodeIds.end() &&\n                std::find(elementNodeIds.begin(), elementNodeIds.end(), j2) != elementNodeIds.end() && elementNodeIds[3] == j3) {\n                if (setCode) {\n                    iBCB_[i] = code;\n                    BCB_[1 * numBoundaryFaces_ + i] = value;\n                }\n                if (setSurfID) {\n                    iBCB_[numBoundaryFaces_ + i] = surfID;\n                    //                    // add surf ID to global ndsurfl\n                    //                    ndsurfg_[j0-1] = surfID;\n                    //                    ndsurfg_[j1-1] = surfID;\n                    //                    ndsurfg_[j2-1] = surfID;\n\n                    // first time we hit a node it is 0\n                    // if it then set to 1 it is left alone\n\n                    if (ndsurfg_[j0 - 1] != 1) {\n                        ndsurfg_[j0 - 1] = surfID;\n                        // fprintf(stdout,\"surfID %i\\n\",surfID);\n                    }\n\n                    if (ndsurfg_[j1 - 1] != 1) {\n                        ndsurfg_[j1 - 1] = surfID;\n                    }\n\n                    if (ndsurfg_[j2 - 1] != 1) {\n                        ndsurfg_[j2 - 1] = surfID;\n                    }\n\n                    if (surfID != 1) {\n\n                        if (ndsurfg_[j0 - 1] != 0) {\n                            ndsurfg_[j0 - 1] = surfID;\n                            // fprintf(stdout,\"surfID %i\\n\",surfID);\n                        }\n                        if (ndsurfg_[j1 - 1] != 0) {\n                            ndsurfg_[j1 - 1] = surfID;\n                        }\n\n                        if (ndsurfg_[j2 - 1] != 0) {\n                            ndsurfg_[j2 - 1] = surfID;\n                        }\n                    }\n\n                    vector<int> elem_data;\n                    elem_data.push_back(elementId);\n                    elem_data.push_back(boundaryElements_[0][i]);\n                    elem_data.push_back(boundaryElements_[1][i]);\n                    elem_data.push_back(boundaryElements_[2][i]);\n                    surf_data.push_back(elem_data);\n                }\n                break;\n            }\n        }\n    }\n\n    NWcloseFile();\n\n    vector<vector<double>> edge_coords; // vector of edges node coordinates\n    vector<vector<double>> surf_coords; // vector of surface node coordinates\n\n    /*\n     * Calculate radius to each node\n     * Added by KDL 07/02/14\n     */\n    /*\n    if (setSurfID) {\n\n    int count[elem_edge.size()];\n    vector<double> xyz;\n    double x,y,z;\n\n    // count frequency\n    for (int j=0; j<elem_edge.size(); j++) {\n    count[j] = 0;\n    for (int k=0; k<elem_edge.size(); k++) {\n    if (elem_edge.at(j).at(0) == elem_edge.at(k).at(0) &&\n    elem_edge.at(j).at(1) == elem_edge.at(k).at(1) ) {\n    count[j] += 1;\n    }\n    }\n    }\n\n    // if count == 1 it is unique\n    for (int j=0; j<elem_edge.size(); j++) {\n    if (count[j] == 1) {\n\n    x = nodes_[0*numNodes_ + elem_edge.at(j).at(0) - 1 ];\n    y = nodes_[1*numNodes_ + elem_edge.at(j).at(0) - 1 ];\n    z = nodes_[2*numNodes_ + elem_edge.at(j).at(0) - 1 ];\n    xyz.push_back(x);\n    xyz.push_back(y);\n    xyz.push_back(z);\n    edge_coords.push_back(xyz);\n    xyz.clear();\n\n    x = nodes_[0*numNodes_ + elem_edge.at(j).at(1) - 1 ];\n    y = nodes_[1*numNodes_ + elem_edge.at(j).at(1) - 1 ];\n    z = nodes_[2*numNodes_ + elem_edge.at(j).at(1) - 1 ];\n    xyz.push_back(x);\n    xyz.push_back(y);\n    xyz.push_back(z);\n    edge_coords.push_back(xyz);\n    xyz.clear();\n\n    }\n    }\n\n    for (int j=0; j<surf_data.size(); j++) {\n    int id,n[3];\n\n    id = surf_data[j].at(0);\n    n[0] = surf_data[j].at(1);\n    n[1] = surf_data[j].at(2);\n    n[2] = surf_data[j].at(3);\n\n    printf(\"%8i %8i %8i %8i\\n\",id, n[0], n[1], n[2]);\n\n    for (int l=0; l<3; l++) {\n    double x = nodes_[0*numNodes_ + n[l] - 1 ];\n    double y = nodes_[1*numNodes_ + n[l] - 1 ];\n    double z = nodes_[2*numNodes_ + n[l] - 1 ];\n    printf(\"%12.3e %12.3e %12.3e\\n\",x,y,z);\n    }\n\n    }\n\n\n\n\n    }\n    */\n\n    // cleanup\n    debugprint(stddbg, \"Exiting setBoundaryFacesWithCode.\\n\");\n    return CV_OK;\n}\n\nint fixFreeEdgeNodes(char *cmd) {\n\n    // enter\n    debugprint(stddbg, \"Entering fixFreeEdgeNodes.\\n\");\n\n    // parse command string\n    if (parseFile(cmd) == CV_ERROR) {\n        return CV_ERROR;\n    }\n\n    if (iBC_ == NULL) {\n        iBC_ = new int[numNodes_]();\n    }\n\n    // count lines in file\n    int eof = 0;\n    int numLinesInFile = 0;\n    while (NWgetNextNonBlankLine(&eof) == CV_OK) {\n        numLinesInFile++;\n    }\n    NWcloseFile();\n\n    debugprint(stddbg, \"Number of lines in file: %i\\n\", numLinesInFile);\n\n    if (numLinesInFile == 0) {\n        return CV_ERROR;\n    }\n\n    struct EdgeHasher {\n        std::size_t operator()(const std::array<int, 2>& e) const\n        {\n            return std::hash<int>{}(e[0]) * 31 + std::hash<int>{}(e[1]);\n        }\n    };\n\n    std::unordered_set<std::array<int, 2>, EdgeHasher> edges;\n\n    if (parseFile(cmd) == CV_ERROR) {\n        return CV_ERROR;\n    }\n\n\n    eof = 0;\n\n    while (NWgetNextNonBlankLine(&eof) == CV_OK) {\n\n        int n0, n1, n2;\n        int elementId, matId;\n        if (sscanf(buffer_, \"%i %i %i %i %i\", &elementId, &matId, &n0, &n1, &n2) != 5) {\n            fprintf(stderr, \"WARNING:  line not of correct format (%s)\\n\", buffer_);\n            NWcloseFile();\n            return CV_ERROR;\n        }\n\n        auto add_or_remove_edge = [&edges](int n0, int n1)\n        {\n            #ifdef BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX\n            std::array<int, 2> toInsert{{ std::min(n0, n1), std::max(n0, n1) }};\n            auto iterBoolPair = edges.insert(toInsert);\n            #else\n            auto iterBoolPair = edges.insert({ std::min(n0, n1), std::max(n0, n1) });\n            #endif\n            if (!iterBoolPair.second) {\n                // Remove duplicate if already present in set\n                edges.erase(iterBoolPair.first);\n            }\n        };\n\n        add_or_remove_edge(n0, n1);\n        add_or_remove_edge(n1, n2);\n        add_or_remove_edge(n0, n2);\n    }\n\n    NWcloseFile();\n\n    for (const auto& edge : edges) {\n        debugprint(stddbg, \"  Fixing Node: %i\\n\", edge[0]);\n        debugprint(stddbg, \"  Fixing Node: %i\\n\", edge[1]);\n        // no slip code\n        // this should be a bit set instead of an int!!\n        iBC_[edge[0] - 1] = 56;\n        iBC_[edge[1] - 1] = 56;\n    }\n\n    // cleanup\n\n    debugprint(stddbg, \"Exiting fixFreeEdgeNodes.\\n\");\n    return CV_OK;\n}\n\n\nint createMeshForDispCalc(char *cmd) {\n\n    // enter\n    debugprint(stddbg, \"Entering createMeshForDispCalc.\\n\");\n\n    // parse command string\n    if (parseFile(cmd) == CV_ERROR) {\n        return CV_ERROR;\n    }\n\n    // count lines in file\n    int eof = 0;\n    int numLinesInFile = 0;\n    while (NWgetNextNonBlankLine(&eof) == CV_OK) {\n        numLinesInFile++;\n    }\n    NWcloseFile();\n\n    debugprint(stddbg, \"Number of lines in file: %i\\n\", numLinesInFile);\n\n    if (numLinesInFile == 0) {\n        return CV_ERROR;\n    }\n\n    std::vector<std::array<int, 3>> ids;\n    ids.reserve(numLinesInFile);\n\n    if (parseFile(cmd) == CV_ERROR) {\n        return CV_ERROR;\n    }\n\n\n    eof = 0;\n    int numElements = 0;\n    while (NWgetNextNonBlankLine(&eof) == CV_OK) {\n        int n0, n1, n2;\n        int elementId, matId;\n\n        if (sscanf(buffer_, \"%i %i %i %i %i\", &elementId, &matId, &n0, &n1, &n2) != 5) {\n            fprintf(stderr, \"WARNING:  line not of correct format (%s)\\n\", buffer_);\n            NWcloseFile();\n            return CV_ERROR;\n        }\n\n        #ifdef BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX\n        {\n            std::array<int, 3> toPushBack{ { n0, numElements, 0 } };\n            ids.push_back(toPushBack);\n        }\n        {\n            std::array<int, 3> toPushBack{ { n1, numElements, 1 } };\n            ids.push_back(toPushBack);\n        }\n        {\n            std::array<int, 3> toPushBack{ { n2, numElements, 2 } };\n            ids.push_back(toPushBack);\n        }\n        #else\n        ids.push_back({ { n0, numElements, 0 } });\n        ids.push_back({ { n1, numElements, 1 } });\n        ids.push_back({ { n2, numElements, 2 } });\n        #endif\n\n        numElements++;\n    }\n\n    NWcloseFile();\n\n    // sort node ids so we can find duplicates\n    std::sort(ids.begin(), ids.end());\n\n    // count the number of unique nodes\n    int numUniqueNodes = 1;\n    int index0 = ids[0][0];\n    for (int i = 0; i < ids.size(); i++) {\n        if (ids[i][0] != index0) {\n            numUniqueNodes++;\n            index0 = ids[i][0];\n        }\n    }\n    debugprint(stddbg, \"  Number of Unique Nodes Found: %i\\n\", numUniqueNodes);\n\n    // create renumbered connectivity for initial disp. calc.\n\n    int* conn[3];\n    conn[0] = new int[numElements];\n    conn[1] = new int[numElements];\n    conn[2] = new int[numElements];\n\n    int* map = new int[numUniqueNodes];\n\n    index0 = -1;\n    int j = 0;\n\n    ofstream mapping(\"mapping.dat\");\n    mapping << \"i\\t\\tmap[i]\" << endl;\n    for (int i = 0; i < ids.size(); i++) {\n        if (ids[i][0] != index0) {\n            map[j] = ids[i][0];\n            //debugprint(stddbg,\"  map[%i] %i\\n\",j,map[j]);\n            mapping << j + 1 << \"\\t\\t\" << map[j] << endl;\n            index0 = ids[i][0];\n            j++;\n        }\n        conn[ids[i][2]][ids[i][1]] = j - 1;\n    }\n    mapping.close();\n    debugprint(stddbg, \"  Number of Unique Nodes Found: %i\\n\", j);\n\n    // set global variables\n    DisplacementNumElements_ = numElements;\n    DisplacementConn_[0] = conn[0];\n    DisplacementConn_[1] = conn[1];\n    DisplacementConn_[2] = conn[2];\n    DisplacementNumNodes_ = numUniqueNodes;\n    DisplacementNodeMap_ = map;\n\n    debugprint(stddbg, \"Exiting createMeshForDispCalc.\\n\");\n    return CV_OK;\n    return 0;\n}\n\n", "meta": {"hexsha": "cf9d05ea6b4dc325e8cd9769f2e9b5a3b39c588c", "size": 26153, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Presolver/helpers.cxx", "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": "Presolver/helpers.cxx", "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": "Presolver/helpers.cxx", "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": 26.9896800826, "max_line_length": 129, "alphanum_fraction": 0.5390203801, "num_tokens": 7787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.016657042877108286, "lm_q1q2_score": 0.007037677817876911}}
{"text": "// -*- C++ -*-\n// Implementation of class xFOOx\n//\n// Copyright (C) 2009-2010 by John Weiss\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the Artistic License, included as the file\n// \"LICENSE\" in the source code archive.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n//\n// You should have received a copy of the file \"LICENSE\", containing\n// the License John Weiss originally placed this program under.\n//\nstatic const char* const\nxFOOx_cc__=\"RCS $Id: statistics.cc 1887 2009-10-13 20:05:57Z candide $\";\n\n\n// Includes\n//\n#include <iostream>\n#include <sys/types.h>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <vector>\n#include <string>\n#include <stdexcept>\n#include <sstream>\n#include <algorithm>\n#include <boost/static_assert.hpp>\n\n#include \"jpw_nld.h\"\n#include \"Matrix.h\"\n#include \"Manips.h\"\n#include \"MathTools.h\"\n#include \"statistics.h\"\n\n#include \"details/Matrix.tcc\"\n\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::flush;\nusing std::scientific;\nusing std::setprecision;\nusing std::vector;\nusing outManips::reset;\nusing jpw_nld::index_t;\n\nusing namespace jpw_math;\nusing namespace jpw_math::statistics;\n\n\n//\n// Static variables\n//\n\n\nnamespace {\n static bool g__pRNG_Initialized(false);\n};\n\n\n//\n// Typedefs\n//\n\n\ntypedef unsigned short seed48v_t[3];\n\n\n/////////////////////////\n\n//\n// Inline Template Function Definitions\n//\n\n\ntemplate<unsigned SZ> inline void\nl__remap_seed__(time_t, seed48v_t&)\n{\n    BOOST_STATIC_ASSERT(false && SZ);\n}\n\n\n// Specialization for 64-bit time_t\ntemplate<> inline void\nl__remap_seed__<8>(time_t rawSeedVal, seed48v_t& elSeed)\n{\n    // 64-bit time_t:  Ignore the upper 2 bytes, which change far more slowly\n    //                 than the rest.\n    // Layout:\n    //    ........ ........ ........ ........ ........ ........\n    // 48       40       32       24       16        8        0\n    //           5        4        3        2        1        0\n\n    // Bytes 0 and 5\n    elSeed[0] = ( ((rawSeedVal & 0xFF) << 8)\n                  | ((rawSeedVal >> 40) & 0xFF) );\n    // Bytes 2 and 3\n    elSeed[1] = ( ((rawSeedVal >> 8) & 0xFF00)\n                  | ((rawSeedVal >> 24) & 0xFF) );\n    // Bytes 4 and 1\n    elSeed[2] = ( ((rawSeedVal >> 24) & 0xFF00)\n                  | ((rawSeedVal >> 8) & 0xFF) );\n}\n\n\n// Specialization for 32-bit time_t\ntemplate<> inline void\nl__remap_seed__<4>(time_t rawSeedVal, seed48v_t& elSeed)\n{\n    // 32-bit time_t:  Split into two 6-bit segments, and four 5-bit\n    //                 segments.\n    //\n    // Layout - The Input:\n    //   ........ ........ ........ ........\n    //  |     |      |     |    |     |    |\n    // 32    26     20    15   10     5    0\n    //          3        2        1        0\n    //\n    // Layout - The Output:\n    //    ......00 0.....00 .....000 00.....0 000..... 00......\n    // 48       40       32       24       16        8        0\n    //           5        4        3        2        1        0\n\n    // Bits 0-4 and 26-31\n    // Map 26-31 to the LSB, and 0-4 to the bit-0 of the upper byte.\n    elSeed[0] = ( ((rawSeedVal & 0x1F) << 8)\n                  | ((rawSeedVal >> 26) & 0x3F) );\n    // Bits 10-14 and 15-19\n    // Map 15-19 to the bit-1 of the lower byte, and 10-14 to the bit-3 of\n    // the upper byte.\n    elSeed[1] = ( ((rawSeedVal << 1) & 0xF800)\n                  | ((rawSeedVal >> 14) & 0x3E) );\n    // Bits 20-25 and 5-9\n    // Map 5-9 to the bit-2 of the lower byte, and 20-25 to the bit-2 of\n    // the upper byte.\n    elSeed[2] = ( ((rawSeedVal >> 10) & 0x7C00)\n                  | ((rawSeedVal >> 3) & 0x7C) );\n}\n\n\n/////////////////////////\n\n//\n// namespace statistics Function Definitions\n//\n\n\n// REFACTOR:  Use template functions & inline-functors to define the pRNG\n// functions.\n// Hmmm... use classes.  Design so that we can refactor the implementation at\n// a later stage (like, say, the very last!)\n//\n// When refactoring the actual generators [like gaussian()], do some more\n// performance tests.  See how well they inline.\n\n\nvoid jpw_math::statistics::parseSeed(std::string& seedStr,\n                                     unsigned& seedLo, unsigned& seedHi)\n{\n    // FIXME:  This is now part of 'jpwTools::RandomDataSrc'.\n    using namespace std;\n\n    if(seedStr.empty()) {\n        return;\n    }\n\n    // Make sure there's a leading \"0x\" prefix, or you'll get parsing errors.\n    if( (seedStr[0] & 0x5F) == 'X' ) {\n        seedStr.insert(0, 1, '0');\n    } else if( (seedStr.size() > 1) &&\n               !( (seedStr[0] == '0') && ((seedStr[1] & 0x5F) == 'X') )\n               ) {\n        seedStr.insert(0, \"0x\");\n    }\n\n    unsigned long long seedVal(0);\n    istringstream hex_iss(seedStr);\n    hex_iss >> hex >> seedVal;\n    if(!hex_iss.good() && !hex_iss.eof()) {\n        string err(\"Not a valid format hex string:  \\\"\");\n        err += seedStr;\n        err += '\"';\n        seedStr.clear();\n        throw runtime_error(err);\n    }\n\n    seedHi = static_cast<unsigned>(seedVal >> 32);\n    seedLo = static_cast<unsigned>(seedVal & 0xFFFFFFFF);\n}\n\n\nvoid jpw_math::statistics::init_rand(bool verbose)\n{\n    seed48v_t elseed;\n    // get time/date to use as a seed\n    l__remap_seed__<sizeof(time_t)>(time(static_cast<time_t*>(0)), elseed);\n    if (verbose) {\n        cout << std::hex\n             << \"\\t\\t[Random seed=0x\"\n             << elseed[2] << elseed[1] << elseed[0]\n             << \"]\" << endl;\n    }\n    seed48(elseed);\n    g__pRNG_Initialized = true;\n}\n\n\nvoid jpw_math::statistics::init_rand_firstTimeOnly(bool verbose)\n{\n    if(!g__pRNG_Initialized) {\n        init_rand(verbose);\n    }\n}\n\n\nvoid jpw_math::statistics::init_rand(unsigned s1, unsigned s2, bool verbose)\n{\n    seed48v_t elseed;\n\n    elseed[2] = static_cast<unsigned short>(s1 & 0xFFFF);\n    elseed[1] = static_cast<unsigned short>((s2 & 0xFFFF0000) >> 16);\n    elseed[0] = static_cast<unsigned short>(s2 & 0xFFFF);\n    if (verbose) {\n        cout << std::hex << \"\\t\\t[Specified seed=0x\"\n             << elseed[2] << elseed[1] << elseed[0]\n             << \"]\" << endl;\n    }\n    seed48(elseed);\n    g__pRNG_Initialized = true;\n}\n\n\ndouble jpw_math::statistics::gaussrand(void)\n{\n    static int iset=1;\n    register double u,v,rsq;\n    double fac;\n    static double gset=0.0;\n\n\n    if(iset)\n    {\n        // Pick two uniform random #'s on the unit circle.\n        do\n        {\n            u = 2.0*drand48() - 1.0;\n            v = 2.0*drand48() - 1.0;\n            rsq = u*u + v*v + jpw_math::TINY;\n        }\n        while(rsq >= 1.0);\n\n        // Now calculate the pair of normal random #'s.\n        fac = sqrt(-2.0*log(rsq)/rsq);\n        gset = v*fac;\n        iset = 0;\n\n        return(u*fac);\n    }\n    else\n    {\n        iset = 1;\n        return(gset);\n    }\n}\n\n\ndouble jpw_math::statistics::std_dev(const dvector_t& values)\n{\n    double mean(0);\n    double sum_sq(0);\n    double total(values.size());\n\n    dvector_t::const_iterator values_end = values.end();\n    for(dvector_t::const_iterator\n            vi = values.begin(); vi != values_end; ++vi) {\n        mean += *vi;\n    }\n    mean /= total;\n\n    for(dvector_t::const_iterator\n            vi = values.begin(); vi != values_end; ++vi) {\n        sum_sq += jpw_math::SQR((*vi) - mean);\n    }\n\n    return(sqrt(sum_sq/(total-1)));\n}\n\n\ndouble jpw_math::statistics::signif_del_chisq_tg(double& siglevel)\n{\n    static double sigvals[]={.5,\n                             .68268949,\n                             .8,\n                             .9,\n                             .95,\n                             .95449974,\n                             .96,\n                             .98,\n                             .99,\n                             .99730020,\n                             .9999};\n    static double del_chisq_vals[]={0.45493642,\n                                    1.0,\n                                    1.6423744,\n                                    2.7055435,\n                                    3.8414588,\n                                    4.0,\n                                    4.2178846,\n                                    5.4118944,\n                                    6.6348966,\n                                    9.0,\n                                    15.136705};\n    static index_t nsigs=sizeof(sigvals)/sizeof(double);  // Should be 11.\n    index_t i, sigidx;\n\n    // Assumes errors obey Gaussian statistics and uses theory for finding the\n    // significance of a value of DeltaChi^2 for 1 parameter.\n    if(siglevel < sigvals[0])\n    {\n        sigidx = 0;\n    }\n    else if(siglevel >= sigvals[nsigs-1])\n    {\n        sigidx = nsigs-1;\n    }\n    else\n    {\n        i=1;\n        sigidx=-1;\n        while(i<nsigs)\n        {\n            if( (sigvals[i-1] <= siglevel) && (siglevel < sigvals[i]) )\n            {\n                sigidx = i-1;\n            }\n            ++i;\n        }\n    }\n\n    siglevel = sigvals[sigidx];\n    return(del_chisq_vals[sigidx]);\n}\n\n\ndouble jpw_math::statistics::confidence_tg(double del_chisq_sig,\n                                           const dmatrix_t& inv_curv_m,\n                                           index_t parmidx, bool verbose)\n{\n    double inval;\n\n\n    // At the minimum, we should ALWAYS be positive definite.\n    inval = inv_curv_m[parmidx][parmidx];\n    if(jpw_math::NEAR_ZERO(inval, -jpw_math::DBL_PREC, jpw_math::DBL_PREC))\n    {\n        inval = 0.0;\n    }\n\n    if(inval <= 0.0)\n    {\n        if( (inval == 0.0) && verbose )\n        {\n            cerr << \"confidence_tg():  null value at param #\" << parmidx\n                 << endl;\n        }\n        else if(inval < 0.0)\n        {\n            cerr << scientific << setprecision(2)\n                 << \"confidence_tg():  negative value, inv[\"\n                 << parmidx << \"][\" << parmidx\n                 << \"]=\" << inval\n                 << \"  Minimization Failure?\"\n                 << reset << endl;\n        }\n        return(jpw_math::HUGE);\n    }\n\n    return(sqrt(del_chisq_sig*inval));\n}\n\n\nlong jpw_math::statistics::nearest_multiple(double val,\n                                            double nearfac,\n                                            bool use_larger)\n{\n    double yy_l, yy_u, nufac_l, nufac_u;\n    double iy_l, iy_u;\n    double aval, udiff, ldiff;\n\n    // Make sure our input values are nonzero integers.\n    val = rint(val);\n    aval = jpw_math::ABS(val);\n    nearfac = rint(nearfac);\n    if(jpw_math::ABS(nearfac) >= aval)\n    {\n        // Note that this includes the case val==0.0.\n        return(static_cast<long>(nearfac));\n    }\n    else if(nearfac == 0.0)\n    {\n        return(1L); // 1 is the closest multiple to 0 of any number.\n    }\n\n    yy_l = val/nearfac;\n    iy_l = rint(yy_l);\n    // Is nearfac actually a multiple of val?\n    if(yy_l == iy_l)\n    {\n        return(static_cast<long>(nearfac));\n    }\n\n    yy_u = yy_l;\n    iy_u = iy_l;\n    nufac_l = nufac_u = nearfac;\n    // Find multiple just above nearfac.\n    while( (yy_u != iy_u) && (jpw_math::ABS(nufac_u) < aval) )\n    {\n        ++nufac_u;\n        yy_u = val/nufac_u;\n        iy_u = rint(yy_u);\n    }\n    // Find multiple just below nearfac.\n    while( (yy_l != iy_l) && (jpw_math::ABS(nufac_l) > 1.0) )\n    {\n        --nufac_l;\n        yy_l = val/nufac_l;\n        iy_l = rint(yy_l);\n    }\n    udiff = jpw_math::ABS(nufac_u-nearfac);\n    ldiff = jpw_math::ABS(nearfac-nufac_l);\n\n    // Now choose the one which is nearest to 'nearfac'.\n    if(udiff > ldiff)\n    {\n        return(static_cast<long>(nufac_l));\n    }\n    else if(udiff < ldiff)\n    {\n        return(static_cast<long>(nufac_u));\n    }\n    else\n    {\n        // When it's equally spaced, flip up or down depending on the value of\n        // the flag \"use_larger\"\n        if(use_larger) {\n            return(static_cast<long>(nufac_u));\n        }\n        else\n        {\n            return(static_cast<long>(nufac_l));\n        }\n    }\n}\n\n\n/////////////////////////\n//\n// End\n", "meta": {"hexsha": "8ec64740ac0cb46e25b0141ac679cfe78578e973", "size": 12053, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libs/utils/statistics.cc", "max_stars_repo_name": "jpweiss/code-sample.nl-fit", "max_stars_repo_head_hexsha": "230a3728effe8b1f5bfb8332a26fc229dd39667b", "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/libs/utils/statistics.cc", "max_issues_repo_name": "jpweiss/code-sample.nl-fit", "max_issues_repo_head_hexsha": "230a3728effe8b1f5bfb8332a26fc229dd39667b", "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/libs/utils/statistics.cc", "max_forks_repo_name": "jpweiss/code-sample.nl-fit", "max_forks_repo_head_hexsha": "230a3728effe8b1f5bfb8332a26fc229dd39667b", "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": 25.9204301075, "max_line_length": 78, "alphanum_fraction": 0.5120716834, "num_tokens": 3393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.033085974694221476, "lm_q1q2_score": 0.007016503094392993}}
{"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#ifndef _ABSTRACTONESTEPIVPODESOLVER_HPP_\n#define _ABSTRACTONESTEPIVPODESOLVER_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include \"ClassIsAbstract.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractIvpOdeSolver.hpp\"\n\n/**\n * Abstract one-step initial value problem ODE solver class. Sets up variables and functions\n * for all the ODE solvers that only have one timestep.\n*/\nclass AbstractOneStepIvpOdeSolver : public AbstractIvpOdeSolver\n{\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<AbstractIvpOdeSolver>(*this);\n    }\n\n    /**\n     * Working memory\n     */\n    std::vector<double> mWorkingMemory;\n\nprotected:\n\n    /**\n     * Method that actually performs the solving on behalf of the public Solve methods.\n     *\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param rCurrentYValues  the current (initial) state; results will also be returned\n     *                         in here\n     * @param rWorkingMemory  working memory; same size as rCurrentYValues\n     * @param startTime  initial time\n     * @param endTime  time to solve to\n     * @param timeStep  dt\n     */\n    virtual void InternalSolve(AbstractOdeSystem* pAbstractOdeSystem,\n                               std::vector<double>& rCurrentYValues,\n                               std::vector<double>& rWorkingMemory,\n                               double startTime,\n                               double endTime,\n                               double timeStep);\n\n    /**\n     * Calculate the solution to the ODE system at the next timestep.\n     * Concrete subclasses should provide this method.\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    virtual void CalculateNextYValue(AbstractOdeSystem* pAbstractOdeSystem,\n                                     double timeStep,\n                                     double time,\n                                     std::vector<double>& rCurrentYValues,\n                                     std::vector<double>& rNextYValues)=0;\n\npublic:\n\n    /**\n     * Solves a system of ODEs using a specified one-step ODE solver and returns\n     * the solution as an OdeSolution object.\n     *\n     * An example, which returns the solution every 0.1 seconds using dt=0.01:\n     *\n     *     MyOdeSystem ode;\n     *     std::vector<double> init_cond = ode_system.GetInitialConditions();\n     *     OdeSolution solution = solver.Solve(&ode, init_cond, 0, 1, 0.01, 0.1);\n     *\n     *\n     * @param pAbstractOdeSystem  pointer to the concrete ODE system to be solved\n     * @param rYValues  a standard vector specifying the intial condition of each\n     *                  solution variable in the system (this can be the initial\n     *                  conditions vector stored in the ODE system)\n     * @param startTime  the time at which the initial conditions are specified\n     * @param endTime  the time to which the system should be solved and the solution\n     *                 returned\n     * @param timeStep  the time interval to be used by the solver\n     * @param timeSampling  the interval at which to sample the solution to the ODE system\n     *\n     * @return OdeSolution is an object containing an integer of the number of\n     * equations, a stdAbstractOdeSystem::vector of times and a std::vector of std::vectors where\n     * each of those vectors contains the solution for one variable of the ODE\n     * system at those times.\n     */\n    virtual OdeSolution Solve(AbstractOdeSystem* pAbstractOdeSystem,\n                              std::vector<double>& rYValues,\n                              double startTime,\n                              double endTime,\n                              double timeStep,\n                              double timeSampling);\n\n    /**\n     * Second version of Solve. Solves a system of ODEs using a specified one-step\n     * ODE solver. This method does not return the solution and therefore does not\n     * take in a sampling time. Instead, the mStateVariables component in the ODE\n     * system object is updated.\n     *\n     * An example:\n     *\n     *     std::vector<double> init_cond = ode_system.GetInitialConditions();\n     *     solver.Solve(&ode, init_cond, 0, 1, 0.01);\n     *     state_variables = ode_system.rGetStateVariables(); // solution at t=1 found here\n     *\n     *\n     * @param pAbstractOdeSystem  pointer to the concrete ODE system to be solved\n     * @param rYValues  a standard vector specifying the intial condition of each\n     *                  solution variable in the system (this can be the initial\n     *                  conditions vector stored in the ODE system)\n     * @param startTime  the time at which the initial conditions are specified\n     * @param endTime  the time to which the system should be solved and the solution\n     *                 returned\n     * @param timeStep  the time interval to be used by the solver\n     */\n    virtual void Solve(AbstractOdeSystem* pAbstractOdeSystem,\n                       std::vector<double>& rYValues,\n                       double startTime,\n                       double endTime,\n                       double timeStep);\n\n    /**\n     * Virtual destructor since we have virtual methods.\n     */\n    virtual ~AbstractOneStepIvpOdeSolver()\n    {}\n};\n\nCLASS_IS_ABSTRACT(AbstractOneStepIvpOdeSolver)\n\n#endif //_ABSTRACTONESTEPIVPODESOLVER_HPP_\n", "meta": {"hexsha": "7315d0b6cae4c9067b00df87a939e0bb142ffe09", "size": 7681, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ode/src/solver/AbstractOneStepIvpOdeSolver.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": "ode/src/solver/AbstractOneStepIvpOdeSolver.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": "ode/src/solver/AbstractOneStepIvpOdeSolver.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": 41.9726775956, "max_line_length": 97, "alphanum_fraction": 0.6655383414, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.02405355145148285, "lm_q1q2_score": 0.006999123236897308}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\r\r\n\r\r\n//Distributed under the Boost Software License, Version 1.0. (See accompanying\r\r\n//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\r\n\r\r\n#include <boost/qvm/operations.hpp>\r\r\n#include <boost/qvm/quat.hpp>\r\r\n#include <boost/qvm/vec.hpp>\r\r\n#include <boost/qvm/mat.hpp>\r\r\n\r\r\nnamespace\r\r\nmy_stuff\r\r\n    {\r\r\n    struct\r\r\n    mat\r\r\n        {\r\r\n        float a[3][3];\r\r\n        };\r\r\n\r\r\n    struct\r\r\n    vec\r\r\n        {\r\r\n        float a[3];\r\r\n        };\r\r\n\r\r\n    struct\r\r\n    quat\r\r\n        {\r\r\n        float a[4];\r\r\n        };\r\r\n    }\r\r\n\r\r\nnamespace\r\r\nboost\r\r\n    {\r\r\n    namespace\r\r\n    qvm\r\r\n        {\r\r\n        template <>\r\r\n        struct\r\r\n        mat_traits<my_stuff::mat>\r\r\n            {\r\r\n            typedef float scalar_type;\r\r\n            static int const rows=3;\r\r\n            static int const cols=3;\r\r\n\r\r\n            template <int R,int C>\r\r\n            static\r\r\n            scalar_type &\r\r\n            write_element( my_stuff::mat & m )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(R>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(R<rows);\r\r\n                BOOST_QVM_STATIC_ASSERT(C>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(C<cols);\r\r\n                return m.a[R][C];\r\r\n                }\r\r\n\r\r\n            template <int R,int C>\r\r\n            static\r\r\n            scalar_type\r\r\n            read_element( my_stuff::mat const & m )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(R>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(R<rows);\r\r\n                BOOST_QVM_STATIC_ASSERT(C>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(C<cols);\r\r\n                return m.a[R][C];\r\r\n                }\r\r\n\r\r\n            static\r\r\n            inline\r\r\n            scalar_type &\r\r\n            write_element_idx( int r, int c, my_stuff::mat & m )\r\r\n                {\r\r\n                BOOST_QVM_ASSERT(r>=0);\r\r\n                BOOST_QVM_ASSERT(r<rows);\r\r\n                BOOST_QVM_ASSERT(c>=0);\r\r\n                BOOST_QVM_ASSERT(c<cols);\r\r\n                return m.a[r][c];\r\r\n                }\r\r\n\r\r\n            static\r\r\n            inline\r\r\n            scalar_type\r\r\n            read_element_idx( int r, int c, my_stuff::mat const & m )\r\r\n                {\r\r\n                BOOST_QVM_ASSERT(r>=0);\r\r\n                BOOST_QVM_ASSERT(r<rows);\r\r\n                BOOST_QVM_ASSERT(c>=0);\r\r\n                BOOST_QVM_ASSERT(c<cols);\r\r\n                return m.a[r][c];\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <>\r\r\n        struct\r\r\n        vec_traits<my_stuff::vec>\r\r\n            {\r\r\n            static int const dim=3;\r\r\n            typedef float scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            scalar_type &\r\r\n            write_element( my_stuff::vec & m )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\r\n                return m.a[I];\r\r\n                }\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            scalar_type\r\r\n            read_element( my_stuff::vec const & m )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\r\n                return m.a[I];\r\r\n                }\r\r\n\r\r\n            static\r\r\n            inline\r\r\n            scalar_type &\r\r\n            write_element_idx( int i, my_stuff::vec & m )\r\r\n                {\r\r\n                BOOST_QVM_ASSERT(i>=0);\r\r\n                BOOST_QVM_ASSERT(i<dim);\r\r\n                return m.a[i];\r\r\n                }\r\r\n\r\r\n            static\r\r\n            inline\r\r\n            scalar_type\r\r\n            read_element_idx( int i, my_stuff::vec const & m )\r\r\n                {\r\r\n                BOOST_QVM_ASSERT(i>=0);\r\r\n                BOOST_QVM_ASSERT(i<dim);\r\r\n                return m.a[i];\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <>\r\r\n        struct\r\r\n        quat_traits<my_stuff::quat>\r\r\n            {\r\r\n            typedef float scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            scalar_type &\r\r\n            write_element( my_stuff::quat & m )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return m.a[I];\r\r\n                }\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            scalar_type\r\r\n            read_element( my_stuff::quat const & m )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return m.a[I];\r\r\n                }\r\r\n            };\r\r\n        }\r\r\n    }\r\r\n\r\r\nnamespace\r\r\nmy_stuff\r\r\n    {\r\r\n    mat &\r\r\n    operator/=( mat & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator/=(x,y);\r\r\n        }\r\r\n\r\r\n    vec &\r\r\n    operator/=( vec & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator/=(x,y);\r\r\n        }\r\r\n\r\r\n    quat &\r\r\n    operator/=( quat & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator/=(x,y);\r\r\n        }\r\r\n\r\r\n    mat &\r\r\n    operator*=( mat & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator*=(x,y);\r\r\n        }\r\r\n\r\r\n    vec &\r\r\n    operator*=( vec & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator*=(x,y);\r\r\n        }\r\r\n\r\r\n    quat &\r\r\n    operator*=( quat & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator*=(x,y);\r\r\n        }\r\r\n\r\r\n    mat\r\r\n    operator/( mat const & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator/(x,y);\r\r\n        }\r\r\n\r\r\n    vec\r\r\n    operator/( vec const & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator/(x,y);\r\r\n        }\r\r\n\r\r\n    quat\r\r\n    operator/( quat const & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator/(x,y);\r\r\n        }\r\r\n\r\r\n    mat\r\r\n    operator*( mat const & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator*(x,y);\r\r\n        }\r\r\n\r\r\n    vec\r\r\n    operator*( vec const & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator*(x,y);\r\r\n        }\r\r\n\r\r\n    quat\r\r\n    operator*( quat const & x, float y )\r\r\n        {\r\r\n        return boost::qvm::operator*(x,y);\r\r\n        }\r\r\n\r\r\n    mat &\r\r\n    operator*=( mat & x, mat const & y )\r\r\n        {\r\r\n        return boost::qvm::operator*=(x,y);\r\r\n        }\r\r\n\r\r\n    mat\r\r\n    operator*=( mat const & x, mat const & y )\r\r\n        {\r\r\n        return boost::qvm::operator*(x,y);\r\r\n        }\r\r\n\r\r\n    vec\r\r\n    operator*( mat const & x, vec const & y )\r\r\n        {\r\r\n        return boost::qvm::operator*(x,y);\r\r\n        }\r\r\n\r\r\n    vec\r\r\n    operator*( quat const & x, vec const & y )\r\r\n        {\r\r\n        return boost::qvm::operator*(x,y);\r\r\n        }\r\r\n\r\r\n    vec\r\r\n    operator*( vec const & x, mat const & y )\r\r\n        {\r\r\n        return boost::qvm::operator*(x,y);\r\r\n        }\r\r\n\r\r\n    bool\r\r\n    operator==( mat const & x, mat const & y )\r\r\n        {\r\r\n        return boost::qvm::operator==(x,y);\r\r\n        }\r\r\n\r\r\n    bool\r\r\n    operator!=( mat const & x, mat const & y )\r\r\n        {\r\r\n        return boost::qvm::operator!=(x,y);\r\r\n        }\r\r\n\r\r\n    bool\r\r\n    operator==( vec const & x, vec const & y )\r\r\n        {\r\r\n        return boost::qvm::operator==(x,y);\r\r\n        }\r\r\n\r\r\n    bool\r\r\n    operator!=( vec const & x, vec const & y )\r\r\n        {\r\r\n        return boost::qvm::operator!=(x,y);\r\r\n        }\r\r\n\r\r\n    bool\r\r\n    operator==( quat const & x, quat const & y )\r\r\n        {\r\r\n        return boost::qvm::operator==(x,y);\r\r\n        }\r\r\n\r\r\n    bool\r\r\n    operator!=( quat const & x, quat const & y )\r\r\n        {\r\r\n        return boost::qvm::operator!=(x,y);\r\r\n        }\r\r\n    }\r\r\n\r\r\nint\r\r\nmain()\r\r\n    {\r\r\n    using namespace boost::qvm::sfinae;\r\r\n    using namespace my_stuff;\r\r\n    typedef boost::qvm::mat<double,3,3> mat2;\r\r\n    typedef boost::qvm::vec<double,3> vec2;\r\r\n    typedef boost::qvm::quat<double> quat2;\r\r\n\r\r\n    mat ma1, mb1; set_zero(ma1); set_zero(mb1);\r\r\n    vec va1, vb1; set_zero(va1); set_zero(vb1);\r\r\n    quat qa1, qb1; set_zero(qa1); set_zero(qb1);\r\r\n    mat2 ma2, mb2; set_zero(ma2); set_zero(mb2);\r\r\n    vec2 va2, vb2; set_zero(va2); set_zero(vb2);\r\r\n    quat2 qa2, qb2; set_zero(qa2); set_zero(qb2);\r\r\n\r\r\n    set_zero(ma1);\r\r\n    set_zero(mb1);\r\r\n    set_zero(va1);\r\r\n    set_zero(vb1);\r\r\n    set_zero(qa1);\r\r\n    set_zero(qb1);\r\r\n    set_zero(ma2);\r\r\n    set_zero(mb2);\r\r\n    set_zero(va2);\r\r\n    set_zero(vb2);\r\r\n    set_zero(qa2);\r\r\n    set_zero(qb2);\r\r\n\r\r\n    ma1/=2;\r\r\n    va1/=2;\r\r\n    qa1/=2;\r\r\n    ma2/=2;\r\r\n    va2/=2;\r\r\n    qa2/=2;\r\r\n\r\r\n    ma1*=2;\r\r\n    va1*=2;\r\r\n    qa1*=2;\r\r\n    ma2*=2;\r\r\n    va2*=2;\r\r\n    qa2*=2;\r\r\n\r\r\n    mb1=ma1/2;\r\r\n    vb1=va1/2;\r\r\n    qb1=qb1/2;\r\r\n    mb2=convert_to<mat2>(ma1/2);\r\r\n    vb2=convert_to<vec2>(va1/2);\r\r\n    qb2=convert_to<quat2>(qa1/2);\r\r\n    mb1=scalar_cast<float>(ma2/2);\r\r\n    vb1=scalar_cast<float>(va2/2);\r\r\n    qb1=scalar_cast<float>(qa2/2);\r\r\n\r\r\n    mb1=ma1*2;\r\r\n    vb1=va1*2;\r\r\n    qb1=qa1*2;\r\r\n    mb2=convert_to<mat2>(ma1*2);\r\r\n    vb2=convert_to<vec2>(va1*2);\r\r\n    qb2=convert_to<quat2>(qa1*2);\r\r\n    mb1=scalar_cast<float>(ma2*2);\r\r\n    vb1=scalar_cast<float>(va2*2);\r\r\n    qb1=scalar_cast<float>(qa2*2);\r\r\n\r\r\n    ma1*=mb1;\r\r\n    ma1*=scalar_cast<float>(ma2);\r\r\n    ma2*=ma1;\r\r\n\r\r\n    va1=ma1*va1;\r\r\n    va1=qa1*va1;\r\r\n    va1=scalar_cast<float>(ma2*va1);\r\r\n    va1=scalar_cast<float>(ma1*va2);\r\r\n    va1=scalar_cast<float>(ma2*va2);\r\r\n    va1=scalar_cast<float>(qa2*va1);\r\r\n    va1=scalar_cast<float>(qa1*va2);\r\r\n    va1=scalar_cast<float>(qa2*va2);\r\r\n\r\r\n    va2=convert_to<vec2>(ma1*va1);\r\r\n    va2=convert_to<vec2>(qa1*va1);\r\r\n    va2=ma2*va1;\r\r\n    va2=ma1*va2;\r\r\n    va2=ma2*va2;\r\r\n    va2=qa2*va1;\r\r\n    va2=qa1*va2;\r\r\n    va2=qa2*va2;\r\r\n\r\r\n    va1=va1*ma1;\r\r\n    va1=scalar_cast<float>(va1*ma2);\r\r\n    va1=scalar_cast<float>(va2*ma1);\r\r\n    va1=scalar_cast<float>(va2*ma2);\r\r\n\r\r\n    va2=convert_to<vec2>(va1*ma1);\r\r\n    va2=va1*ma2;\r\r\n    va2=va2*ma1;\r\r\n    va2=va2*ma2;\r\r\n\r\r\n    (void) (ma1==mb1);\r\r\n    (void) (ma1==ma2);\r\r\n    (void) (ma2==ma1);\r\r\n\r\r\n    (void) (ma1!=mb1);\r\r\n    (void) (ma1!=ma2);\r\r\n    (void) (ma2!=ma1);\r\r\n\r\r\n    (void) (va1==vb1);\r\r\n    (void) (va1==va2);\r\r\n    (void) (va2==va1);\r\r\n\r\r\n    (void) (va1!=vb1);\r\r\n    (void) (va1!=va2);\r\r\n    (void) (va2!=va1);\r\r\n\r\r\n    (void) (qa1==qb1);\r\r\n    (void) (qa1==qa2);\r\r\n    (void) (qa2==qa1);\r\r\n\r\r\n    (void) (qa1!=qb1);\r\r\n    (void) (qa1!=qa2);\r\r\n    (void) (qa2!=qa1);\r\r\n\r\r\n    return 0;\r\r\n    }\r\r\n", "meta": {"hexsha": "e53f4ebb9667f4b33a3c54465a04a80271a01676", "size": 10462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost_1_63_0/libs/qvm/test/interop_test.cpp", "max_stars_repo_name": "newtondev/drachtio-server", "max_stars_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/boost_1_63_0/libs/qvm/test/interop_test.cpp", "max_issues_repo_name": "newtondev/drachtio-server", "max_issues_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/boost_1_63_0/libs/qvm/test/interop_test.cpp", "max_forks_repo_name": "newtondev/drachtio-server", "max_forks_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_forks_repo_licenses": ["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.995412844, "max_line_length": 80, "alphanum_fraction": 0.4346205314, "num_tokens": 2847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709194, "lm_q2_score": 0.014063629522651349, "lm_q1q2_score": 0.006976879826152386}}
{"text": "#include <ctime>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <stdexcept>\n#include <sys/stat.h>\n#include <algorithm>\n#include \"qm_qchem.hpp\"\n#include \"properties.hpp\"\n#include \"util.hpp\"\n#include <armadillo>\n#include <unordered_map>\n#include <chrono>\n#include <functional>\n\nConfigBlockReader\nQM_QChem::qchem_reader() {\n  using types = ConfigBlockReader::types;\n  ConfigBlockReader reader{\"qchem\"};\n  reader.add_entry(\"qc_scratch\", \"DEFAULT\");\n  reader.add_entry(\"basis\", types::STRING);\n  reader.add_entry(\"exchange\", types::STRING);\n  reader.add_entry(\"scf_algorithm\", \"DIIS\");\n  reader.add_entry(\"boys_states\", std::vector<int> {}); // sentinel value\n  // FIXME: add scf_guess and default to read\n  reader.add_entry(\"nthreads\", 1);\n  reader.add_entry(\"buffer_states\", 0);\n\n  reader.add_entry(\"sing_thresh\", 1.2); // for state tracking\n\n  // FIXME: ConfigReader should support bool\n  reader.add_entry(\"singlets\", 1);\n  reader.add_entry(\"triplets\", 0);\n  reader.add_entry(\"state_analysis\", 0);\n  reader.add_entry(\"spin_flip\", 0);\n  reader.add_entry(\"save_nacvector\", 0);\n  reader.add_entry(\"record_spectrum\", 0);\n  reader.add_entry(\"track_states\", 0);\n  reader.add_entry(\"dump_qc_output\", 0);\n  reader.add_entry(\"dump_qc_input\", 0);\n  reader.add_entry(\"externalcharges_hack\", 0);\n  reader.add_entry(\"time_properties\", 0);\n\n  return reader;\n}\n\n\n/*\n  Recall that Q-Chem can decide to change the number of excited states\n  it computes! Usually this will be to a larger number of states. --Y.S.\n\n  Happens in setman; to see where, search for \"NRoots was altered as:\"\n\n  On subsequent invocation (as during AIMD), setman_init.F will reset\n  the number requested to the original number.\n\n  This is fixed by setting set_roots_orig and makeing sure we have\n  headroom on our hopping states.\n*/\nQM_QChem::QM_QChem(FileHandle& fh, \n                   const arma::uvec& in_qmids, \n\t\t   arma::mat& in_qm_crd, \n\t\t   arma::mat& in_mm_crd, \n\t\t   arma::vec& in_mm_chg, \n\t\t   const int charge, \n\t\t   const int mult,\n\t\t   const int excited_states_in,\n                   const int min_state_in):\n  QMInterface(in_qmids, in_qm_crd, in_mm_crd, in_mm_chg, charge, mult, excited_states_in, min_state_in)\n{\n  ConfigBlockReader reader = qchem_reader();\n  reader.parse(fh);\n\n  reader.get_data(\"basis\", basis_set);\n  reader.get_data(\"exchange\", exchange_method);\n  reader.get_data(\"scf_algorithm\", scf_algorithm);\n  reader.get_data(\"sing_thresh\", sing_thresh);\n\n  {\n    int in;\n    reader.get_data(\"singlets\", in);\n    singlets = in;\n    reader.get_data(\"triplets\", in);\n    triplets = in;\n    reader.get_data(\"state_analysis\", in);\n    state_analysis = in;\n    reader.get_data(\"spin_flip\", in);\n    spin_flip = in;\n    reader.get_data(\"save_nacvector\", in);\n    save_nacvector = in;\n    reader.get_data(\"record_spectrum\", in);\n    record_spectrum = in;\n    reader.get_data(\"track_states\", in);\n    track_states = in;\n    reader.get_data(\"dump_qc_output\", in);\n    dump_qc_output = in;\n    reader.get_data(\"dump_qc_input\", in);\n    dump_qc_input = in;\n    reader.get_data(\"externalcharges_hack\", in);\n    externalcharges_hack = in;\n    reader.get_data(\"time_properties\", in);\n    time_properties = in;\n\n  }\n\n  // shstates must be set before buffer states or are added or min_state is changed for spin_flip\n  shstates = excited_states + 1 - min_state;\n\n  if(spin_flip){\n    qm_multiplicity = 3;\n    min_state += 1; // since the ground state is the first excited state\n    excited_states += 1;\n  }\n\n  bool valid_options = true;\n\n  if (min_state < 1){\n    std::cerr << \"min_state=\" << min_state << std::endl;\n    std::cerr << \"Minimum states smaller than 1 not supported in QChem!\" << std::endl;\n    valid_options = false;\n  }\n\n  {\n    int buffer_states;\n    reader.get_data(\"buffer_states\", buffer_states);\n\n    if (buffer_states < 0){\n      valid_options = false;\n      std::cerr << \"Buffer_states must be non-negative\" << std::endl;\n    }\n    else{\n      excited_states += buffer_states;\n    }\n  }\n\n  reader.get_data(\"boys_states\", boys_states);\n  if (boys_states.size() > 1){\n    //FIXME: when we have capacity for diabatic dynamics, will need to expand control\n    boys_diabatization = true;\n\n    for (auto s: boys_states){\n      if ((s < 0 ) || ((size_t) s > excited_states)){\n        valid_options = false;\n        std::cerr << \"Boys states must be within the excited states!\" << std::endl;\n      }\n    }\n  }\n\n  if(spin_flip && excited_states < 1){\n    valid_options = false;\n    std::cerr << \"Must compute excited states with spin-flip; try increasing buffer_states.\" << std::endl;\n  }\n\n  if(spin_flip && !track_states){\n    //valid_options = false;\n    std::cerr << \"WARNING: Selecting spin-flip without state tracking nearly guaranteed to produce incorrect results\" << std::endl;\n  }\n\n  if (singlets && triplets && !track_states){\n    valid_options = false;\n    std::cerr << \"Selecting singlets and triplets without state tracking nearly guaranteed to produce incorrect results!\" << std::endl;\n  }\n\n  // FIXME: implement triplet tracking\n  if (track_states && !singlets){\n    valid_options = false;\n    std::cerr << \"State tracking for triplets not (yet << std::endl implemented!\" << std::endl;\n  }\n\n  if (!valid_options){\n    throw std::runtime_error(\"Invalid options; see above!\");\n  }\n  \n  /*\n    The environmental variables $QCSCRATCH, $QCTHREADS shall take\n    precedence over anything set in the config.\n  */\n\n  std::string conf_scratch;\n  reader.get_data(\"qc_scratch\", conf_scratch);\n  qc_scratch_directory = get_qcscratch(conf_scratch);\n  \n  /*\n    Setting $QCTHREADS seems sufficient on the Subotnik cluster, but\n    perhaps this is unique to our setup. Need to check with Evgeny to\n    be sure. Changes to $OMP_NUM_THREADS seem to have no effect.\n  */\n  int conf_threads;\n  reader.get_data(\"nthreads\", conf_threads);\n  if (conf_threads > 1){\n    setenv(\"QCTHREADS\", std::to_string(conf_threads).c_str(), 0);\n  }\n  // FIXME: should include MPI support\n\n  qc_executable = get_qcprog();\n}\n\n\nvoid QM_QChem::get_properties(PropMap &props){\n  if(track_states){\n    state_tracker(props);\n  }\n\n  for (QMProperty p: props.keys()){\n    auto time_start = std::chrono::steady_clock::now();\n\n    switch(p){\n    case QMProperty::wfoverlap:{\n      get_wf_overlap(props.get(p));\n      break;\n    }\n\n    case QMProperty::diabatic_rot_mat:\n      get_diabatic_rot_mat(props.get(p));\n      break;\n\n    case QMProperty::nacvector_imag:\n      throw std::invalid_argument(\"Imaginary NAC not implemented!\");\n      break;\n\n    case QMProperty::nacvector:{\n      const arma::uvec &idx = *props.get_idx(p);\n      size_t A = idx[0]; size_t B = idx[1];\n      get_nac_vector(props.get(p), A, B);\n      break;\n    }\n\n    case QMProperty::mmgradient:\n      break; // if we need mm, then we will do qm, which catches both\n    case QMProperty::qmgradient:{\n      arma::mat &g_qm = props.get(QMProperty::qmgradient);\n\n      arma::uword surface = 0; //assume ground state\n      if (props.has_idx(QMProperty::qmgradient)){\n\tsurface = (*props.get_idx(QMProperty::qmgradient))[0];\n      }\n\n      if (props.has(QMProperty::mmgradient)){\n\tarma::mat &g_mm = props.get(QMProperty::mmgradient);\n\tget_gradient(g_qm, g_mm, surface);\n      }\n      else{\n\tget_gradient(g_qm, surface);\n      }\n      break;\n    }\n\n    case QMProperty::mmgradient_multi:\n      break; // if we need mm, then we will do qm, which catches both\n    case QMProperty::qmgradient_multi:{\n      arma::cube &g_qm = props.get(QMProperty::qmgradient_multi);\n\n      if (!props.has_idx(QMProperty::qmgradient_multi)){\n        throw std::logic_error(\"Cannot request gradient_multi without specifying states!\");\n      }\n      arma::uvec surfaces = *props.get_idx(QMProperty::qmgradient_multi);\n\n      if (g_qm.n_slices != surfaces.n_elem){\n\tthrow std::range_error(\"Insufficient space for requested gradients!\");\n      }\n      \n      for(arma::uword i = 0; i < surfaces.n_elem; i++){\n\tif (props.has(QMProperty::mmgradient_multi)){\n\t  arma::cube &g_mm = props.get(QMProperty::mmgradient_multi);\n\t  get_gradient(g_qm.slice(i), g_mm.slice(i), surfaces(i));\n\t}\n\telse{\n\t  get_gradient(g_qm.slice(i), surfaces(i));\n\t}\n      }\n      break;\n    }\n      \n    case QMProperty::energies:{\n      arma::vec & energies = props.get(p);\n      if (props.has_idx(p)){\n        arma::uvec idx = *props.get_idx(p);\n        if (energies.n_elem != idx.n_elem){\n          throw std::logic_error(\"energy array of incorrect size\");\n        }\n\n        arma::vec e_temp(excited_states + 1, arma::fill::zeros);\n        get_all_energies(e_temp);\n        energies = e_temp(idx);\n      }\n      else{\n        get_ground_energy(energies); // FIXME: combine ground/excited calls\n      }\n      break;\n    }\n\n    default: // Compile with the default case commented out and the compiler will detect neglected properties\n      std::cerr << \"You requested QMProperty \" << p << std::endl;\n      throw std::invalid_argument(\"Unknown QMProperty!\");\n      break;\n    }\n    auto time_stop = std::chrono::steady_clock::now();\n    if (time_properties){\n      std::cout << p << \" required \" <<\n        std::chrono::duration_cast<std::chrono::milliseconds>(time_stop - time_start).count()/1e3 << \"s\" << std::endl;\n    }\n  }\n\n  // everything here will be called exactly once per call to update()\n  if (!called(Q::once)){\n    auto time_start = std::chrono::steady_clock::now();\n    if (state_analysis){\n      do_state_analysis();\n    }\n\n    if (record_spectrum){\n      do_record_spectrum();\n    }\n\n    if (boys_diabatization){\n      do_boys_diabatization();\n    }\n\n    auto time_stop = std::chrono::steady_clock::now();\n    if (time_properties){\n      std::cout << \"once calls required \" <<\n        std::chrono::duration_cast<std::chrono::milliseconds>(time_stop - time_start).count() / 1e3 << \"s\" << std::endl;\n    }\n  }\n}\n\n\n// modifies all properties requesting state k to request k' where k' is the (k+1)th *singlet*\nvoid QM_QChem::state_tracker(PropMap &props){\n  arma::vec S2(excited_states + 1);\n  {\n    get_all_energies(S2); // a dummy call to generate FILE_CIS_S2; incidentally will also cache results for us\n    S2.set_size(excited_states);\n    readQFMan(QCFILE::FILE_CIS_S2, S2);\n  }\n\n  /* 1.2 is the default for REM_CIS_S2_THRESH; If we want to change,\n     we can specify our threshold via sing_thresh, which is synced\n     with the rem section.\n  */\n\n  // if S^2 is larger than sing_thresh, we consider the state a triplet\n\n  arma::uvec statei(excited_states + 1, arma::fill::zeros);\n\n  // FIXME: once BOMD doens't know anything about excited states or\n  // min_state (and idx{0} means the first comptued singlet, then we\n  // can ditch these hacks. rather could be: n_singlets = 0;\n  // statei(n_singlets++) = i; And we will need to test the ground\n  // state too.\n  arma::uword n_singlets = qm_multiplicity == 1 ? 1 : 0;\n\n  for (arma::uword i = 0; i < excited_states; i++){\n    if (S2(i) < sing_thresh){\n      statei(n_singlets++) = i+1; // the ground state is state 0\n    }\n  }\n  statei.resize(n_singlets);\n\n  for (QMProperty p: props.keys()){\n    if (props.has_idx(p)){\n      arma::uvec & idxs = props.get_writable_idx(p);\n      for (arma::uword & i: idxs){\n        if (i >= n_singlets){\n          std::cerr << \"Requested \" << p << \"(\" << i << \"); have \" << n_singlets-1 << \".\" << std::endl;\n          throw std::runtime_error(\"The requested state is not within those states computed!\");\n        }\n        else{\n          i = statei(i);\n        }\n      }\n    }\n  }\n}\n\n\nvoid QM_QChem::do_boys_diabatization(void){\n  REMKeys keys = {{\"jobtype\",\"sp\"},\n                  {\"boys_cis_numstate\", std::to_string(boys_states.size())},\n                  {\"sts_mom\", \"1\"}};\n\n  REMKeys ex = excited_rem();\n  keys.insert(ex.begin(), ex.end());\n\n  std::ofstream input = get_input_handle();\n  write_rem_section(input, keys);  \n  write_molecule_section(input);\n\n  { // write boys section\n    input << \"$localized_diabatization\" << std::endl;\n    input << \"Comment: states we mix\" << std::endl;\n    for (const auto& s: boys_states){\n      input << s << \" \";\n    }\n    input << std::endl << \"$end\" << std::endl;\n  }\n  input.close();\n\n  exec_qchem();\n\n  // FIXME: write the relevant boys quantities in a better fashion\n  {\n    std::string src = get_qcwdir() + \"/\" + qc_log_file;\n    std::string dest = get_qcwdir() + \"/\" +\n      \"boys.\" + std::to_string(call_idx()) + \".out\";\n\n    std::string cmd = \"cp -a \" + src + \" \" + dest; \n    int status = std::system(cmd.c_str());\n\n    if(status){\n      std::cerr << \"Warning: unable to write \" + dest << std::endl;\n    }\n  }\n}\n\nstd::string QM_QChem::qc_log_file_idx(void){\n  const int idx = call_idx();\n  static int last_idx = idx;\n  static int call = 0; // will be incremented on first run\n\n  if (idx == last_idx){\n    call++;\n  }\n  else{\n    call = 1;\n  }\n\n  last_idx = idx;\n  return \"QCHEM.\" + std::to_string(idx) + \".\" + std::to_string(call) + \".out\";\n}\n\n\nvoid QM_QChem::do_record_spectrum(void){\n  arma::vec e;\n  // dummy call to make sure the transition dipoles and energies are written\n  e.set_size(excited_states + 1);\n  get_all_energies(e);\n\n  e.set_size(excited_states);\n  readQFMan(QCFILE::FILE_SET_ENERGY, e);\n  \n  // for mu, the first row is the oscillator strength\n  arma::mat mu(4, excited_states);\n  readQFMan(QCFILE::FILE_TRANS_DIP_MOM, mu);\n\n  //write spectrum to file as [excitation energy] [strength]\n  {\n    if (e[0] < 0){ // the true ground state is the first excited state\n      e = e - e[0];\n    }\n    \n    arma::mat spec(excited_states,2);\n    spec.col(0) = e;\n    spec.col(1) = mu.row(0).t();\n    arma::vec osc = spec.col(1);\n\n    osc.save(arma::hdf5_name(\"gifs.hdf5\",\n                             \"/oscillator/\" + std::to_string(call_idx()),\n                             arma::hdf5_opts::replace));\n\n    std::string specf = get_qcwdir() + \"/\" + \"spectrum.dat\";\n    std::ofstream stream;\n    stream.open(specf, std::ios::out | std::ios::app | std::ios::binary);\n    if (!stream){\n      throw std::runtime_error(\"Cannot open spectrum file, \" + specf);\n    }\n    else{\n      spec.save(stream, arma::raw_ascii);\n    }\n  }\n\n}\n\n\nvoid QM_QChem::do_state_analysis(void){\n  REMKeys keys = {{\"jobtype\",\"sp\"},\n                  {\"make_cube_files\", \"false\"},\n                  {\"gui\", \"2\"},\n                  {\"state_analysis\", \"true\"},\n                  {\"molden_format\", \"true\"}};\n\n  REMKeys ex = excited_rem();\n  keys.insert(ex.begin(), ex.end());\n\n  std::ofstream input = get_input_handle();\n  write_rem_section(input, keys);  \n  write_molecule_section(input);\n  input.close();\n\n  {\n    std::string guifile = get_qcwdir() + \"/\" +\n      std::to_string(call_idx()) + \".fchk\";\n    setenv(\"GUIFILE\", guifile.c_str(), 1);\n  }\n  \n  exec_qchem();\n}\n\n\n//FIXME: Use another REM variable to save PREV_GEO\nvoid QM_QChem::get_wf_overlap(arma::mat &U){\n  static bool first_wfoverlap = true;\n\n  if (U.n_elem != shstates * shstates){\n    throw std::logic_error(\"WF overlap is of wrong size!\");\n  }\n  \n  REMKeys keys = excited_rem();\n  keys.insert({{\"jobtype\",\"sp\"},\n      //{\"namd_lowestsurface\", std::to_string(min_state)},\n               {\"wf_overlap_minsurf\", std::to_string(min_state)},\n               {\"wf_overlap_nsurf\", std::to_string(shstates)},\n               {\"dump_wf_overlap\", std::to_string(first_wfoverlap ? 1 : 2)}});\n    \n  std::ofstream input = get_input_handle();\n  write_rem_section(input, keys);\n  write_molecule_section(input);\n  input.close();\n  exec_qchem();\n\n  /*\n    If this is the first call, don't actually read from $QC; there\n    will be no overlap to read. It is *required*, however, that the\n    above call be made as it saves the relevant overlap quantities for\n    the next call.\n  */\n  if (first_wfoverlap){\n    U.eye();\n  }\n  else{\n    readQFMan(QCFILE::FILE_WF_OVERLAP, U);\n  }\n\n  first_wfoverlap = false;\n}\n\n\n/*\n  FIXME: Need to recitfy min_state or choose which states to mix\n  FIXME: Want to choose between ER and Boys and ...\n  FIXME: Want to pick separate spin states (rem_boys_cis_spin_separate)\n  FIXME: May want to increase REM_CIS_CONVERGENCE to 7 (from default 6)\n  FIXME: Do we need to include $localised_diabatization section?\n*/\nvoid QM_QChem::get_diabatic_rot_mat(arma::mat &U){\n  REMKeys k = excited_rem();\n  k.insert({\n      {\"jobtype\",\"sp\"},\n      {\"boys_cis_numstate\", std::to_string(excited_states)}\n    });\n\n  std::ofstream input = get_input_handle();\n  write_rem_section(input, k);\n  write_molecule_section(input);\n  input.close();\n  exec_qchem();\n\n  readQFMan(QCFILE::FILE_DIAB_ROT_MAT, U);\n}\n\n\nvoid QM_QChem::get_ground_energy(arma::vec & e){\n  // Build job if we need to\n  if (! called(Q::scfman)){\n    std::ofstream input = get_input_handle();\n    write_rem_section(input, {{\"jobtype\",\"sp\"}});\n    write_molecule_section(input);\n    input.close();\n    exec_qchem();\n  }\n\n  parse_energies(e);\n}\n\n\n// ground + excited states\nvoid QM_QChem::get_all_energies(arma::vec & e){\n  if (! called(Q::setman)){\n    REMKeys k = excited_rem(false);\n    k.insert({\n        {\"jobtype\",\"sp\"},\n        {\"cis_rlx_dns\", \"1\"}}\n      );\n    \n    std::ofstream input = get_input_handle();\n    write_rem_section(input, k);\n    write_molecule_section(input);\n    input.close();\n    called(Q::scfman); // because it will be after this execution\n    exec_qchem();\n  }\n\n  parse_energies(e);\n}\n\n\nvoid QM_QChem::get_gradient(arma::mat &g_qm, arma::mat &g_mm, arma::uword surface){\n  get_gradient(g_qm, surface);\n  if (NMM > 0){\n    parse_mm_gradient(g_mm);\n  }\n}\n\n\nvoid QM_QChem::get_gradient(arma::mat &g_qm, arma::uword surface){\n  if (surface > excited_states){\n    throw std::invalid_argument(\"Requested surface not computed!\");\n  }\n\n  std::ofstream input = get_input_handle();\n  REMKeys keys = {{\"jobtype\",\"force\"}};\n\n  if (surface != 0){\n    REMKeys ex = excited_rem();\n    keys.insert(ex.begin(), ex.end());\n    keys.insert({{\"cis_state_deriv\", std::to_string(surface)}});\n  }\n  else{\n    called(Q::scfman);\n  }\n  \n  write_rem_section(input, keys);  \n  write_molecule_section(input);\n  input.close();\n\n  exec_qchem();\n\n  readQFMan(QCFILE::FILE_NUCLEAR_GRADIENT, g_qm);\n}\n\n\nvoid QM_QChem::get_nac_vector(arma::mat & nac, size_t A, size_t B){\n  /*\n    cannot skip setman for nac; no need to skip scfman because it will\n    be so quick\n  */\n  REMKeys keys = excited_rem(false);\n\n  /*\n    relaxed density should be computed automatically, but we set it\n    explictily here since we're setting scf- and setman as called()\n  */\n  called(Q::scfman); called(Q::setman);\n  keys.insert({\n      {\"jobtype\",\"sp\"},\n      {\"calc_nac\", \"true\"},\n      {\"cis_der_numstate\", \"2\"}, // Always, in our case, between 2 states\n      {\"cis_rlx_dns\", \"1\"}\n    });\n\n  if (NMM > 0){\n    keys.insert({{\"nac_pointcharge\", \"1\"},\n                 {\"qm_mm\", \"true\"}});\n  }\n  \n  std::ofstream input = get_input_handle();\n  write_rem_section(input, keys);\n\n  /*\n    Section format:\n    $derivative_coupling\n      comment line\n      A B ...\n    $end\n    where A, B, ... are the states between which to compute the\n    derivative coupling. The $rem section must include\n    cis_der_numstates equal to the total number of states\n    specified. The ground state is 0.\n\n  */\n  input << \"$derivative_coupling\" << std::endl;\n  input << \"comment\" << std::endl;\n  input << A << \" \" << B << std::endl;\n  input << \"$end\" << std::endl;\n  \n  write_molecule_section(input);\n  input.close();\n\n  exec_qchem();\n\n  readQFMan(QCFILE::FILE_DERCOUP, nac);\n\n  if (save_nacvector){\n    std::string nacf = get_qcwdir() + \"/\" +\n      \"nacvector.\" + std::to_string(call_idx()) + \".arma\";\n\n    // FIXME: should save better than this\n    nac.save(arma::hdf5_name(\"gifs.hdf5\",\n                             \"/nac/\" + std::to_string(call_idx()),\n                             arma::hdf5_opts::replace));\n  }\n}\n\n\nvoid QM_QChem::parse_energies(arma::vec &e){\n  readQFMan(QCFILE::FILE_ENERGY, e.memptr(), 1, POS_CRNT_TOTAL_ENERGY);\n\n  if (excited_states > 0 && e.n_elem > 1){\n    double e_ground = e[0];\n\n    if (!(e.n_elem >= excited_states + 1)){\n      throw std::range_error(\"Insufficient space for all excited states in vec e!\");\n    }\n\n    size_t count = readQFMan(QCFILE::FILE_SET_ENERGY, e.memptr() + 1, excited_states, POS_BEGIN);\n    if (count != excited_states){\n      throw std::runtime_error(\"Unable to parse energies!\");\n    }\n\n    // Energies for higher states given in terms of exitations so we\n    // must add in the ground.\n    e += e_ground;\n    e[0] = e_ground;\n  }\n  e.save(arma::hdf5_name(\"gifs.hdf5\",\n                         \"/energies/\" + std::to_string(call_idx()),\n                         arma::hdf5_opts::replace));\n}\n\n\nvoid QM_QChem::parse_mm_gradient(arma::mat &g_mm){\n  /* Size of g_mm updated above in GifsImpl::update_gradient() */\n  readQFMan(QCFILE::FILE_EFIELD, g_mm);\n\n  for (size_t i = 0; i < NMM; i++){\n    const double q = chg_mm[i];\n    // FILE_EFIELD really contains the *field* so we need a negative to get the gradient.\n    g_mm.col(i) *= -1.0 * q;\n  }\n  /*\n    FIXME: prevent efield.dat from being written with REM_QMMM_EXT_GIFS set\n\n    This method replaced parsing efield.dat, which has the following\n    format:\n\n    Ex(mm1) Ey(mm1) Ez(mm1)\n    ...\n    Ex(mmN) Ey(mmN) Ez(mmN)\n    Ex(qm1) Ey(qm1) Ez(qm1)\n    ...\n    Ex(qmN) Ey(qmN) Ez(qmN)\n\n    where Ea(u) is the component of the electric field in the a\n    direction at u and mmi and qmi are the coordinates of the ith mm\n    and qm atoms respectively. N.N. The product of the field and the\n    charge is a force rather than the gradient.\n  */\n}\n\n\nconst std::string QM_QChem::get_qcprog(void){\n  char * qc_str = std::getenv(\"QC\");\n  std::string default_path = \"qcprog.exe\";\n  if (nullptr == qc_str){\n    std::cerr << \"Warning, $QC not set; using \" << default_path << std::endl;\n    return default_path;\n  }\n  else{\n    return std::string(qc_str) + \"/exe/qcprog.exe\";\n  }\n}\n\n\nconst std::string QM_QChem::get_qcwdir(void){\n  char * pwd = std::getenv(\"PWD\");\n  std::string qcwdir = std::string(pwd) + \"/GQSH\";\n\n  static bool create = true;\n\n  if (create){\n    struct stat st = {};\n    if (-1 == stat(qcwdir.c_str(), &st)){\n      mkdir(qcwdir.c_str(), 0700);\n    }\n    create = false;\n  }\n\n  return qcwdir;\n}\n\n\n/*\n  In order of preference:\n  1)               If $QCSCRATCH is set and an absolute path use it\n  2) Failing that, if conf_dir   is set and an absolute path use it\n  3) Failing that, use our default path\n\n  The above are set in reverse.\n*/\nconst std::string QM_QChem::get_qcscratch(std::string conf_dir){\n  char * pwd = std::getenv(\"PWD\");\n  std::string scratch_path = std::string(pwd) + \"/GQSH.sav\";\n\n  // if the config directory is valid, take it as the default\n  if (conf_dir[0] == '/'){\n    scratch_path = conf_dir;\n  }\n  \n  char * qc_str = std::getenv(\"QCSCRATCH\");\n  if (nullptr == qc_str){\n    std::cerr << \"Warning, $QCSCRATCH not set; using \" << scratch_path << std::endl;\n  }\n  else if (qc_str[0] != '/'){\n    std::cerr << \"Warning, $QCSCRATCH is not an absolute path; instead using \" << scratch_path << std::endl;\n  }\n  else{\n    scratch_path = std::string(qc_str);\n    // If using a global scratch path, make it unique\n    // FIXME: could still collide if QCSCRATCH is on a network device\n    std::srand(getpid());\n    scratch_path += \"/GIFS_\" + std::to_string(std::time(nullptr)) + \"_\" + std::to_string(rand());\n  }\n\n  /* Make sure the directory exists; create otherwise */\n  struct stat st = {};\n  if (-1 == stat(scratch_path.c_str(), &st)){\n    mkdir(scratch_path.c_str(), 0700);\n  }\n\n  /*\n    Set $QCSCRATCH to whatever we're using. Incidentally, this fixes a\n    corner case where Q-Chem will crash if QCSCRATCH=\"\"; set, but to\n    the empty string.\n  */\n  setenv(\"QCSCRATCH\", scratch_path.c_str(), true);\n  std::cerr << \"taking scratch path to be: \" << scratch_path << std::endl;\n\n  return scratch_path;\n}\n\nvoid QM_QChem::exec_qchem(void){\n  if (dump_qc_output){\n    qc_log_file = qc_log_file_idx();\n  }\n\n  std::string cmd = \"cd \" + get_qcwdir() + \"; \" + // change to  target WD\n    qc_executable + \" \" +\n    qc_scratch_directory + \"/\" + qc_input_file + \" \" +\n    qc_scratch_directory + \" >\" + qc_log_file + \" 2>&1\";\n  int status = std::system(cmd.c_str());\n  if (status){\n    throw std::runtime_error(\"Q-Chem could not be called or exited abnormally; see \" + get_qcwdir() + \"/\" + qc_log_file);\n  }\n  first_call = false;\n}\n\n\n/* Consistent formatting and file name */\nstd::ofstream QM_QChem::get_input_handle(){\n  std::ofstream os(qc_scratch_directory + \"/\" + qc_input_file);\n  os.setf(std::ios_base::fixed, std::ios_base::floatfield);\n  os.precision(std::numeric_limits<double>::digits10);\n\n  return os;\n}\n\n/*\n  detectQinks must be false if in constructing your job and before\n  calling exec_qchem() you:\n  - call called() at all\n  - call excited_rem() more than once\n*/\nREMKeys QM_QChem::excited_rem(bool detectQinks){\n  REMKeys keys\n    {\n      {\"cis_n_roots\", std::to_string(excited_states)},\n      {\"set_roots_orig\", std::to_string(excited_states)}, // make sure we always use the same number of states\n      {\"max_cis_cycles\", \"500\"}, // same as set_iter\n      {\"cis_singlets\", std::to_string(singlets)},  \n      {\"cis_triplets\", std::to_string(triplets)} \n    };\n\n  if (detectQinks){\n    bool skip_scfman = called(Q::scfman);  // called() updates internal state so we\n    bool skip_setman = called(Q::setman);  // need to make sure both are touched.\n    if (skip_scfman){\n      keys.insert({{\"skip_scfman\", \"1\"}});\n      if (skip_setman){\n        keys.insert({{\"skip_setman\", \"1\"}});\n      }\n    }\n    else{\n      keys.insert({{\"cis_rlx_dns\", \"1\"}});\n    }\n  }\n\n  return keys;\n}\n\n\nvoid QM_QChem::write_rem_section(std::ostream &os, const REMKeys &options){\n  // Default options \n  REMKeys rem_keys\n    {\n      {\"method\",         exchange_method},\n      {\"basis\",          basis_set},\n      {\"scf_algorithm\",  scf_algorithm},\n      {\"thresh_diis_switch\", \"7\"},  // control change-over to GDM if\n      {\"max_diis_cycles\", \"50\"},    // scf_alg is DIIS_GDM\n      {\"sym_ignore\",     \"true\"},\n      {\"qm_mm\",          \"true\"},\n      {\"max_scf_cycles\", \"500\"},\n      {\"skip_charge_self_interact\", \"1\"}, // since the MD driver will compute MM-MM interaction\n      {\"cis_s2_thresh\",  std::to_string(int(sing_thresh * 100))},\n      {\"print_input\",    std::to_string(dump_qc_input)},\n      {\"input_bohr\",     \"true\"} // .../libgen/PointCharges.C works for MM charges\n    };\n\n  if (spin_flip){\n    rem_keys.emplace(\"spin_flip\", \"1\");\n    rem_keys.emplace(\"sts_mom\", \"1\");\n  }\n  if (first_call){\n    rem_keys.emplace(\"qmmm_ext_gifs\", \"1\");\n  }\n  else{\n    rem_keys.emplace(\"qmmm_ext_gifs\", \"2\");\n    rem_keys.emplace(\"scf_guess\",     \"read\");\n  }  \n\n  /*\n    Make sure passed options take precedence?  Could do this by\n    inserting the defaults into the passed options rather than the\n    other way around.\n  */\n  \n  // merge in options; usually will include jobtype \n  rem_keys.insert(options.begin(), options.end());\n  \n  os << \"$rem\" << std::endl;\n  for (const auto& e: rem_keys){\n    os << e.first << \" \" << e.second << std::endl;\n  }\n  os << \"$end\" << std::endl;  \n}\n\n\n/*\n  FIXME: should do better formatting with std::right << std::fixed <<\n  std::setprecision(precision) << std::setw(precision+5) and friends\n*/\nvoid QM_QChem::write_molecule_section(std::ostream &os){\n  /*\n    format of $molecule & $externall_charges sections:\n    $molecule\n    [charge] [multiplicity]\n    [atomic-number] [x-coord] [y-coord] [x-coord]\n    ...\n    $end\n\n    $external_charges\n    [x-coord] [y-coord] [x-coord] [charge]\n    ...\n    $end\n  */  \n  os << \"$molecule\" << std::endl;\n  os << qm_charge << \" \" << qm_multiplicity << std::endl;\n\n  for (size_t i = 0; i < NQM; i++){\n    os << atomids[i]      << \" \";        // id\n    os << crd_qm[i*3 + 0] << \" \";        // x\n    os << crd_qm[i*3 + 1] << \" \";        // y\n    os << crd_qm[i*3 + 2] << std::endl;  // x\n  }\n  os <<  \"$end\" << std::endl;\n\n  if (NMM > 0){\n    if(externalcharges_hack){\n      std::string extfname = \"external_charges.in\";\n      os << std::endl << \"$external_charges\" << std::endl;\n      os << extfname << std::endl;\n      os << \"$end\" << std::endl;\n\n      std::ofstream osext(get_qcwdir() + \"/\" + extfname);\n      osext.setf(std::ios_base::fixed, std::ios_base::floatfield);\n      osext.precision(std::numeric_limits<double>::digits10);\n      write_external_charges_section(osext);\n      osext.close();\n    }\n    else{\n      write_external_charges_section(os);\n    }\n  }\n}\n\nvoid QM_QChem::write_external_charges_section(std::ostream &os){\n  os << std::endl << \"$external_charges\" << std::endl;\n  for (size_t i = 0; i < NMM; i++){\n    os << crd_mm[i*3 + 0] << \" \";        // x\n    os << crd_mm[i*3 + 1] << \" \";        // y\n    os << crd_mm[i*3 + 2] << \" \";        // z\n    os << chg_mm[i]       << std::endl;  // charge\n  }\n  os << \"$end\" << std::endl;\n}\n\n/*\n  Sentinel system to track whether the respective q-chem qink has been\n  called since the last call to update(). See/update the protected\n  nested enum class Q (as in sentinel) for the list of relevant qinks\n*/\nbool QM_QChem::called(Q q){\n  static std::unordered_map<Q, int> calls;\n  if(call_idx() == calls[q]){\n    return true;\n  }\n  else{\n    calls[q] = call_idx();\n    return false;\n  }\n}\n\n\n/*\n  Given a q-qchem file number (see qm_qchem.hpp for examples), read N\n  elements from the file (in the scratch directory) starting from the\n  offset into memptr, which must point to a block of memory with space\n  for at least N doubles.\n*/\nsize_t QM_QChem::readQFMan(QCFILE filenum, double * memptr, size_t N, size_t offset){\n  std::string path = qc_scratch_directory + \"/\" + std::to_string((int) filenum) + \".0\";\n  std::ifstream ifile;\n  ifile.open(path, std::ios::in | std::ios::binary);\n\n  if (!ifile.is_open()){\n    throw std::ios_base::failure(\"Error: cannot read from \" + path);\n  }\n\n  char buffer[sizeof(double)];\n  size_t i = 0;\n  size_t count = 0;\n  while(ifile.read(buffer, sizeof(double))){\n    if ((i >= offset) && (i < offset + N)){\n      double * d = (double *) buffer;\n      *(memptr + count++) = *d;\n    }\n    i++;\n  }\n  ifile.close();\n\n  return count;\n}\n\nstd::string QM_QChem::to_string(const QCFILE f){\n  std::string name;\n  switch (f){\n  case QCFILE::FILE_SET_ENERGY:\n    name = \"FILE_SET_ENERGY, 72.0\";\n    break;\n  case QCFILE::FILE_ENERGY:\n    name = \"FILE_ENERGY, 99.0\";\n    break;\n  case QCFILE::FILE_NUCLEAR_GRADIENT:\n    name = \"FILE_NUCLEAR_GRADIENT, 131.0\";\n    break;\n  case QCFILE::FILE_EFIELD:\n    name = \"FILE_EFIELD, 329.0\";\n    break;\n  case QCFILE::FILE_DERCOUP:\n    name = \"FILE_DERCOUP, 967.0\";\n    break;\n  case QCFILE::FILE_WF_OVERLAP:\n    name = \"FILE_WF_OVERLAP, 398.0\";\n    break;\n  case QCFILE::FILE_DIAB_ROT_MAT:\n    name = \"FILE_DIAB_ROT_MAT, 941.0\";\n    break;\n  case QCFILE::FILE_TRANS_DIP_MOM:\n    name = \"FILE_TRANS_DIP_MOM, 942.0\";\n    break;\n  case QCFILE::FILE_CIS_S2:\n    name = \"FILE_CIS_S2, 1200.0\";\n    break;\n  }\n  return name;\n}\n", "meta": {"hexsha": "ca173ce602293b5b48bce7550ebc5198211bbbfe", "size": 30850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gifs_src/qm_qchem.cpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T19:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T19:48:20.000Z", "max_issues_repo_path": "gifs_src/qm_qchem.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/qm_qchem.cpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 28.5912882298, "max_line_length": 135, "alphanum_fraction": 0.631636953, "num_tokens": 8764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000708951749934, "lm_q2_score": 0.031618770234328894, "lm_q1q2_score": 0.006956353613377241}}
{"text": "/*\n\n   Copyright (c) 2006+6010, The Scripps Research Institute\n   Copyright (c) 2015, The University of Georgia\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+6.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   Modifications for Vina-Carb 1.0 By: Anita K. Nivedha <nivedha@uga.edu>\n                                       The Woods' Lab\n                                       Complex Carbohydrate Research Center\n                                       The University of Georgia\n\n*/\n\n#include \"model.h\"\n#include \"file.h\"\n#include \"curl.h\"\n#include \"parse_pdbqt.h\"\n#include <boost/thread/mutex.hpp>\nnamespace\n\t{\n\tboost::mutex cout_mutex;\n\t}\n\n\n\ntemplate<typename T>\natom_range get_atom_range(const T& t) {\n\tatom_range tmp = t.node;\n\tVINA_FOR_IN(i, t.children) {\n\t\tatom_range r = get_atom_range(t.children[i]);\n\t\tif(tmp.begin > r.begin) tmp.begin = r.begin;\n\t\tif(tmp.end   < r.end  ) tmp.end   = r.end;\n\t}\n\treturn tmp;\n}\n\nstruct branch_metrics {\n\tsz length;\n\tsz corner2corner;\n\tbranch_metrics() : length(0), corner2corner(0) {}\n};\n\ntemplate<typename T>\nbranch_metrics get_branch_metrics(const T& t) {\n\tbranch_metrics tmp;\n\tif(!t.children.empty()) {\n\t\tsz corner2corner_max = 0;\n\t\tszv lengths;\n\t\tVINA_FOR_IN(i, t.children) {\n\t\t\tbranch_metrics res = get_branch_metrics(t.children[i]);\n\t\t\tif(corner2corner_max < res.corner2corner)\n\t\t\t\tcorner2corner_max = res.corner2corner;\n\t\t\tlengths.push_back(res.length + 1); // FIXME? weird compiler warning (sz -> unsigned)\n\t\t}\n\t\tstd::sort(lengths.begin(), lengths.end());\n\n\t\ttmp.length = lengths.back();\n\n\t\ttmp.corner2corner = tmp.length;\n\t\tif(lengths.size() >= 2)\n\t\t\ttmp.corner2corner += lengths[lengths.size() - 1];\n\n\t\tif(tmp.corner2corner < corner2corner_max)\n\t\t\ttmp.corner2corner = corner2corner_max;\n\t}\n\treturn tmp;\n}\n\nsz model::ligand_longest_branch(sz ligand_number) const {\n\treturn get_branch_metrics(ligands[ligand_number]).length;\n}\n\nsz model::ligand_length(sz ligand_number) const {\n\treturn get_branch_metrics(ligands[ligand_number]).corner2corner;\n}\n\nvoid ligand::set_range() {\n\tatom_range tmp = get_atom_range(*this);\n\tbegin = tmp.begin;\n\tend   = tmp.end;\n}\n\n/////////////////// begin MODEL::APPEND /////////////////////////\n\n// FIXME hairy code - needs to be extensively commented, asserted, reviewed and tested\n\nstruct appender_info {\n\tsz grid_atoms_size;\n\tsz m_num_movable_atoms;\n\tsz atoms_size;\n\n\tappender_info(const model& m) : grid_atoms_size(m.grid_atoms.size()), m_num_movable_atoms(m.m_num_movable_atoms), atoms_size(m.atoms.size()) {}\n};\n\nclass appender {\n\tappender_info a_info;\n\tappender_info b_info;\n\tsz new_grid_index(sz x) const {\n\t\treturn (is_a ? x : (a_info.grid_atoms_size + x)); // a-grid_atoms spliced before b-grid_atoms\n\t}\npublic:\n\tbool is_a;\n\n\tappender(const model& a, const model& b) : a_info(a), b_info(b), is_a(true) {}\n\n\tsz operator()(sz x) const { // transform coord index\n\t\tif(is_a) {\n\t\t\tif(x < a_info.m_num_movable_atoms)  return x; // a-movable unchanged\n\t\t\telse                                return x + b_info.m_num_movable_atoms; // b-movable spliced before a-inflex\n\t\t}\n\t\telse {\n\t\t\tif(x < b_info.m_num_movable_atoms)  return x + a_info.m_num_movable_atoms; // a-movable spliced before b-movable\n\t\t\telse                                return x + a_info.atoms_size; // all a's spliced before b-inflex\n\t\t}\n\t}\n\tatom_index operator()(const atom_index& x) const { // transform atom_index\n\t\tatom_index tmp(x);\n\t\tif(tmp.in_grid) tmp.i = new_grid_index(tmp.i);\n\t\telse            tmp.i = operator()(tmp.i);\n\t\t\treturn tmp;\n\t}\n\n\t// type-directed old -> new transformations\n\tvoid update(interacting_pair& ip) const {\n\t\tip.a = operator()(ip.a);\n\t\tip.b = operator()(ip.b);\n\t}\n\tvoid update(vec& v) const { // coordinates & forces - do nothing\n\t}\n\tvoid update(ligand& lig) const {\n\t\tlig.transform(*this); // ligand as an atom_range subclass\n\t\ttransform_ranges(lig, *this);\n\t\tVINA_FOR_IN(i, lig.pairs)\n\t\t\tthis->update(lig.pairs[i]);\n\t\tVINA_FOR_IN(i, lig.cont)\n\t\t\tthis->update(lig.cont[i]); // parsed_line update, below\n\t}\n\tvoid update(residue_vc& r) const {\n\t\ttransform_ranges(r, *this);\n\t}\n\tvoid update(parsed_line& p) const {\n\t\tif(p.second)\n\t\t\tp.second = operator()(p.second.get());\n\t}\n\tvoid update(atom_vc& a) const {\n\t\tVINA_FOR_IN(i, a.bonds) {\n\t\t\tbond_vc& b = a.bonds[i];\n\t\t\tb.connected_atom_index = operator()(b.connected_atom_index); // atom_index transformation, above\n\t\t}\n\t}\n\n\t// ligands, flex, flex_context, atoms; also used for other_pairs\n\ttemplate<typename T>\n\tvoid append(std::vector<T>& a, const std::vector<T>& b) { // first arg becomes aaaaaaaabbbbbbbbbbbbbbb\n\t\tsz a_sz = a.size();\n\t\tvector_append(a, b);\n\n\t\tis_a = true;\n\t\tVINA_FOR(i, a_sz)\n\t\t\tupdate(a[i]);\n\n\t\tis_a = false;\n\t\tVINA_RANGE(i, a_sz, a.size())\n\t\t\tupdate(a[i]);\n\t}\n\n\t// internal_coords, coords, minus_forces, atoms\n\ttemplate<typename T>\n\tvoid coords_append(std::vector<T>& a, const std::vector<T>& b) { // first arg becomes aaaaaaaabbbbbbbbbaab\n\t\tstd::vector<T> b_copy(b); // more straightforward to make a copy of b and transform that than to do piecewise transformations of the result\n\n\t\tis_a = true;\n\t\tVINA_FOR_IN(i, a)\n\t\t\tupdate(a[i]);\n\n\t\tis_a = false;\n\t\tVINA_FOR_IN(i, b_copy)\n\t\t\tupdate(b_copy[i]);\n\n\t\t// interleave \n\t\ttypedef typename std::vector<T>::const_iterator const cci;\n\t\tcci b1 = b_copy.begin();\n\t\tcci b2 = b_copy.begin() + b_info.m_num_movable_atoms;\n\t\tcci b3 = b_copy.end();\n\n\t\ta.insert(a.begin() + a_info.m_num_movable_atoms , b1 , b2);\n\t\ta.insert(a.end()                                , b2 , b3);\n\t}\n};\n\nvoid model::append(const model& m) {\n\tVINA_CHECK(atom_typing_used() == m.atom_typing_used());\n\n\tappender t(*this, m);\n\n\tt.append(other_pairs, m.other_pairs);\n\n\tVINA_FOR_IN(i, atoms)\n\t\tVINA_FOR_IN(j, m.atoms) {\n\t\t\tif(i >= m_num_movable_atoms && j >= m.m_num_movable_atoms) continue; // no need for inflex-inflex interactions\n\n\t\t\tconst atom_vc& a =   atoms[i];\n\t\t\tconst atom_vc& b = m.atoms[j];\n\n\t\t\tsz t1 = a.get(atom_typing_used());\n\t\t\tsz t2 = b.get(atom_typing_used());\n\t\t\tsz n = num_atom_types(atom_typing_used());\n\n\t\t\tif(t1 < n && t2 < n) {\n\t\t\t\tt.is_a =  true;\n\t\t\t\tsz new_i = t(i);\n\t\t\t\tt.is_a = false;\n\t\t\t\tsz new_j = t(j);\n\t\t\t\tsz type_pair_index = triangular_matrix_index_permissive(n, t1, t2);\n\t\t\t\tother_pairs.push_back(interacting_pair(type_pair_index, new_i, new_j));\n\t\t\t}\n\t\t}\n\n\tVINA_CHECK(  minus_forces.size() ==   coords.size());\n\tVINA_CHECK(m.minus_forces.size() == m.coords.size());\n\n\tt.coords_append(internal_coords, m.internal_coords);\n\tt.coords_append(         coords, m         .coords);\n\tt.coords_append(   minus_forces, m   .minus_forces); // for now, minus_forces.size() == coords.size() (includes inflex)\n\n\tt.append(ligands,         m.ligands);\n\tt.append(flex,            m.flex);\n\tt.append(flex_context,    m.flex_context);\n\n\tt       .append(grid_atoms, m.grid_atoms);\n\tt.coords_append(     atoms, m     .atoms);\n\n\tm_num_movable_atoms += m.m_num_movable_atoms;\n}\n\n///////////////////  end  MODEL::APPEND /////////////////////////\n\n\n/////////////////// begin MODEL::INITIALIZE /////////////////////////\n\natom_index model::sz_to_atom_index(sz i) const {\n\tif(i < grid_atoms.size()) return atom_index(i                    ,  true);\n\telse                      return atom_index(i - grid_atoms.size(), false);\n}\n\ndistance_type model::distance_type_between(const distance_type_matrix& mobility, const atom_index& i, const atom_index& j) const {\n\tif(i.in_grid && j.in_grid) return DISTANCE_FIXED;\n\tif(i.in_grid) return (j.i < m_num_movable_atoms) ? DISTANCE_VARIABLE : DISTANCE_FIXED;\n\tif(j.in_grid) return (i.i < m_num_movable_atoms) ? DISTANCE_VARIABLE : DISTANCE_FIXED;\n\tassert(!i.in_grid);\n\tassert(!j.in_grid);\n\tassert(i.i < atoms.size());\n\tassert(j.i < atoms.size());\n\tsz a = i.i;\n\tsz b = j.i;\n\tif(a == b) return DISTANCE_FIXED;\n\treturn (a < b) ? mobility(a, b) : mobility(b, a);\n}\n\nconst vec& model::atom_coords(const atom_index& i) const {\n\treturn i.in_grid ? grid_atoms[i.i].coords : coords[i.i];\n}\n\nfl model::distance_sqr_between(const atom_index& a, const atom_index& b) const {\n\treturn vec_distance_sqr(atom_coords(a), atom_coords(b));\n}\n\nstruct bond_less { // FIXME rm!?\n\tbool operator()(const bond_vc& a, const bond_vc& b) const {\n\t\treturn a.connected_atom_index.i < b.connected_atom_index.i;\n\t}\n};\n\n\nbool model::atom_exists_between(const distance_type_matrix& mobility, const atom_index& a, const atom_index& b, const szv& relevant_atoms) const { // there is an atom closer to both a and b then they are to each other and immobile relative to them\n\tfl r2 = distance_sqr_between(a, b);\n\tVINA_FOR_IN(relevant_atoms_i, relevant_atoms) {\n\t\tsz i = relevant_atoms[relevant_atoms_i];\n\t\tatom_index c = sz_to_atom_index(i);\n\t\tif(a == c || b == c) continue;\n\t\tdistance_type ac = distance_type_between(mobility, a, c);\n\t\tdistance_type bc = distance_type_between(mobility, b, c);\n\t\tif(ac != DISTANCE_VARIABLE &&\n\t\t   bc != DISTANCE_VARIABLE &&\n\t\t   distance_sqr_between(a, c) < r2 &&\n\t\t   distance_sqr_between(b, c) < r2)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nstruct beads {\n\tfl radius_sqr;\n\tstd::vector<std::pair<vec, szv> > data;\n\tbeads(sz reserve_size, fl radius_sqr_) : radius_sqr(radius_sqr_) { data.reserve(reserve_size); }\n\tvoid add(sz index, const vec& coords) {\n\t\tVINA_FOR_IN(i, data) {\n\t\t\tif(vec_distance_sqr(coords, data[i].first) < radius_sqr) {\n\t\t\t\tdata[i].second.push_back(index);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// not found\n\t\tstd::pair<vec, szv> tmp;\n\t\ttmp.first = coords;\n\t\ttmp.second.push_back(index);\n\t\tdata.push_back(tmp);\n\t}\n};\n\nvoid model::assign_bonds(const distance_type_matrix& mobility) { // assign bonds based on relative mobility, distance and covalent length\n\tconst fl bond_length_allowance_factor = 1.1;\n\tsz n = grid_atoms.size() + atoms.size();\n\n\t// construct beads\n\tconst fl bead_radius = 15;\n\tbeads beads_instance(n, sqr(bead_radius));\n\tVINA_FOR(i, n) {\n\t\tatom_index i_atom_index = sz_to_atom_index(i);\n\t\tbeads_instance.add(i, atom_coords(i_atom_index));\n\t}\n\t// assign bonds\n\tVINA_FOR(i, n) {\n\t\tatom_index i_atom_index = sz_to_atom_index(i);\n\t\tconst vec& i_atom_coords = atom_coords(i_atom_index);\n\t\tatom_vc& i_atom = get_atom(i_atom_index);\n\n\t\tconst fl max_covalent_r = max_covalent_radius(); // FIXME mv to atom_constants\n\t\tfl i_atom_covalent_radius = max_covalent_r;\n\t\tif(i_atom.ad < AD_TYPE_SIZE)\n\t\t\ti_atom_covalent_radius = ad_type_property(i_atom.ad).covalent_radius;\n\n\t\t//find relevant atoms\n\t\tszv relevant_atoms;\n\t\tconst fl bead_cutoff_sqr = sqr(bead_radius + bond_length_allowance_factor * (i_atom_covalent_radius + max_covalent_r));\n\t\tVINA_FOR_IN(b, beads_instance.data) {\n\t\t\tif(vec_distance_sqr(beads_instance.data[b].first, i_atom_coords) > bead_cutoff_sqr) continue;\n\t\t\tconst szv& bead_elements = beads_instance.data[b].second;\n\t\t\tVINA_FOR_IN(bead_elements_i, bead_elements) {\n\t\t\t\tsz j = bead_elements[bead_elements_i];\n\t\t\t\tatom_index j_atom_index = sz_to_atom_index(j);\n\t\t\t\tatom_vc& j_atom = get_atom(j_atom_index);\n\t\t\t\tconst fl bond_length = i_atom.optimal_covalent_bond_length(j_atom);\n\t\t\t\tdistance_type dt = distance_type_between(mobility, i_atom_index, j_atom_index);\n\t\t\t\tif(dt != DISTANCE_VARIABLE && i != j) {\n\t\t\t\t\tfl r2 = distance_sqr_between(i_atom_index, j_atom_index);\n\t\t\t\t\t//if(r2 < sqr(bond_length_allowance_factor * bond_length))\n\t\t\t\t\tif(r2 < sqr(bond_length_allowance_factor * (i_atom_covalent_radius + max_covalent_r)))\n\t\t\t\t\t\trelevant_atoms.push_back(j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// find bonded atoms\n\t\tVINA_FOR_IN(relevant_atoms_i, relevant_atoms) {\n\t\t\tsz j = relevant_atoms[relevant_atoms_i];\n\t\t\tif(j <= i) continue; // already considered\n\t\t\tatom_index j_atom_index = sz_to_atom_index(j);\n\t\t\tatom_vc& j_atom = get_atom(j_atom_index);\n\t\t\tconst fl bond_length = i_atom.optimal_covalent_bond_length(j_atom);\n\t\t\tdistance_type dt = distance_type_between(mobility, i_atom_index, j_atom_index);\n\t\t\tfl r2 = distance_sqr_between(i_atom_index, j_atom_index);\n\t\t\tif(r2 < sqr(bond_length_allowance_factor * bond_length) && !atom_exists_between(mobility, i_atom_index, j_atom_index, relevant_atoms)) {\n\t\t\t\tbool rotatable = (dt == DISTANCE_ROTOR);\n\t\t\t\tfl length = std::sqrt(r2);\n\t\t\t\ti_atom.bonds.push_back(bond_vc(j_atom_index, length, rotatable));\n\t\t\t\tj_atom.bonds.push_back(bond_vc(i_atom_index, length, rotatable));\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nbool model::bonded_to_HD(const atom_vc& a) const {\n\tVINA_FOR_IN(i, a.bonds) {\n\t\tconst bond_vc& b = a.bonds[i];\n\t\tif(get_atom(b.connected_atom_index).ad == AD_TYPE_HD) \n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool model::bonded_to_heteroatom(const atom_vc& a) const {\n\tVINA_FOR_IN(i, a.bonds) {\n\t\tconst bond_vc& b = a.bonds[i];\n\t\tif(get_atom(b.connected_atom_index).is_heteroatom())\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid model::assign_types() {\n\tVINA_FOR(i, grid_atoms.size() + atoms.size()) {\n\t\tconst atom_index ai = sz_to_atom_index(i);\n\t\tatom_vc& a = get_atom(ai);\n\t\ta.assign_el();\n\t\tsz& x = a.xs;\n\n\t\tbool acceptor   = (a.ad == AD_TYPE_OA || a.ad == AD_TYPE_NA); // X-Score forumaltion apparently ignores SA\n\t\tbool donor_NorO = (a.el == EL_TYPE_Met || bonded_to_HD(a));\n\n\t\tswitch(a.el) {\n\t\t\tcase EL_TYPE_H    : break;\n\t\t\tcase EL_TYPE_C    : x = bonded_to_heteroatom(a) ? XS_TYPE_C_P : XS_TYPE_C_H; break;\n\t\t\tcase EL_TYPE_N    : x = (acceptor && donor_NorO) ? XS_TYPE_N_DA : (acceptor ? XS_TYPE_N_A : (donor_NorO ? XS_TYPE_N_D : XS_TYPE_N_P)); break;\n\t\t\tcase EL_TYPE_O    : x = (acceptor && donor_NorO) ? XS_TYPE_O_DA : (acceptor ? XS_TYPE_O_A : (donor_NorO ? XS_TYPE_O_D : XS_TYPE_O_P)); break;\n\t\t\tcase EL_TYPE_S    : x = XS_TYPE_S_P; break;\n\t\t\tcase EL_TYPE_P    : x = XS_TYPE_P_P; break;\n\t\t\tcase EL_TYPE_F    : x = XS_TYPE_F_H; break;\n\t\t\tcase EL_TYPE_Cl   : x = XS_TYPE_Cl_H; break;\n\t\t\tcase EL_TYPE_Br   : x = XS_TYPE_Br_H; break;\n\t\t\tcase EL_TYPE_I    : x = XS_TYPE_I_H; break;\n\t\t\tcase EL_TYPE_Met  : x = XS_TYPE_Met_D; break;\n\t\t\tcase EL_TYPE_SIZE : break;\n\t\t\tdefault: VINA_CHECK(false);\n\t\t}\n\t}\n}\n\nsz model::find_ligand(sz a) const {\n\tVINA_FOR_IN(i, ligands)\n\t\tif(a >= ligands[i].begin && a < ligands[i].end)\n\t\t\treturn i;\n\treturn ligands.size();\n}\n\nvoid model::bonded_to(sz a, sz n, szv& out) const {\n\tif(!has(out, a)) { // not found\n\t\tout.push_back(a);\n\t\tif(n > 0) \n\t\t\tVINA_FOR_IN(i, atoms[a].bonds) {\n\t\t\t\tconst bond_vc& b = atoms[a].bonds[i];\n\t\t\t\tif(!b.connected_atom_index.in_grid)\n\t\t\t\t\tbonded_to(b.connected_atom_index.i, n-1, out);\n\t\t\t}\n\t}\n}\n\nszv model::bonded_to(sz a, sz n) const {\n\tszv tmp;\n\tbonded_to(a, n, tmp);\n\treturn tmp;\n}\n\n\nvoid model::initialize_pairs(const distance_type_matrix& mobility) {\n\tVINA_FOR_IN(i, atoms) {\n\t\tsz i_lig = find_ligand(i);\n\t\tszv bonded_atoms = bonded_to(i, 3);\n\t\tVINA_RANGE(j, i+1, atoms.size()) {\n\t\t\tif(i >= m_num_movable_atoms && j >= m_num_movable_atoms) continue; // exclude inflex-inflex\n\t\t\tif(mobility(i, j) == DISTANCE_VARIABLE && !has(bonded_atoms, j)) {\n\t\t\t\tsz t1 = atoms[i].get  (atom_typing_used());\n\t\t\t\tsz t2 = atoms[j].get  (atom_typing_used());\n\t\t\t\tsz n  = num_atom_types(atom_typing_used());\n\t\t\t\tif(t1 < n && t2 < n) { // exclude, say, Hydrogens\n\t\t\t\t\tsz type_pair_index = triangular_matrix_index_permissive(n, t1, t2);\n\t\t\t\t\tinteracting_pair ip(type_pair_index, i, j);\n\t\t\t\t\tif(i_lig < ligands.size() && find_ligand(j) == i_lig)\n\t\t\t\t\t\tligands[i_lig].pairs.push_back(ip);\n\t\t\t\t\telse\n\t\t\t\t\t\tother_pairs.push_back(ip);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid model::initialize(const distance_type_matrix& mobility) {\n\tVINA_FOR_IN(i, ligands)\n\t\tligands[i].set_range();\n\tassign_bonds(mobility);\n\tassign_types();\n\tinitialize_pairs(mobility);\n}\n\n///////////////////  end  MODEL::INITIALIZE /////////////////////////\n\n\nsz model::num_internal_pairs() const {\n\tsz tmp = 0;\n\tVINA_FOR_IN(i, ligands)\n\t\ttmp += ligands[i].pairs.size();\n\treturn tmp;\n}\n\nszv model::get_movable_atom_types(atom_type::t atom_typing_used_) const {\n\tszv tmp;\n\tsz n = num_atom_types(atom_typing_used_);\n\tVINA_FOR(i, m_num_movable_atoms) {\n\t\tconst atom_vc& a = atoms[i];\n\t\tsz t = a.get(atom_typing_used_);\n\t\tif(t < n && !has(tmp, t))\n\t\t\ttmp.push_back(t);\n\t}\n\treturn tmp;\n}\n\nconf_size model::get_size() const {\n\tconf_size tmp;\n\ttmp.ligands = ligands.count_torsions();\n\ttmp.flex    = flex   .count_torsions();\n\treturn tmp;\n}\n\nconf model::get_initial_conf() const { // torsions = 0, orientations = identity, ligand positions = current\n\tconf_size cs = get_size();\n\tconf tmp(cs);\n\ttmp.set_to_null();\n\tVINA_FOR_IN(i, ligands)\n\t\ttmp.ligands[i].rigid.position = ligands[i].node.get_origin();\n\treturn tmp;\n}\n\ngrid_dims model::movable_atoms_box(fl add_to_each_dimension, fl granularity) const {\n\tvec corner1(0, 0, 0), corner2(0, 0, 0);\n\tVINA_FOR(i, num_movable_atoms()) {\n\t\tconst vec& v = movable_coords(i);\n\t\tVINA_FOR_IN(j, v) {\n\t\t\tif(i == 0 || v[j] < corner1[j]) corner1[j] = v[j];\n\t\t\tif(i == 0 || v[j] > corner2[j]) corner2[j] = v[j];\n\t\t}\n\t}\n\tcorner1 -= add_to_each_dimension / 2;\n\tcorner2 += add_to_each_dimension / 2;\n\n\tgrid_dims gd;\n\t{ // always doing this now FIXME ?\n\t\tvec center; center = 0.5 * (corner2 + corner1);\n\t\tVINA_FOR_IN(i, gd) {\n\t\t\tgd[i].n = sz(std::ceil((corner2[i] - corner1[i]) / granularity));\n\t\t\tfl real_span = granularity * gd[i].n;\n\t\t\tgd[i].begin = center[i] - real_span/2;\n\t\t\tgd[i].end = gd[i].begin + real_span;\n\t\t}\n\t}\n\treturn gd;\n}\n\nvoid string_write_coord(sz i, fl x, std::string& str) {\n\tVINA_CHECK(i > 0);\n\t--i;\n\tstd::ostringstream out;\n\tout.setf(std::ios::fixed, std::ios::floatfield);\n\tout.setf(std::ios::showpoint);\n\tout << std::setw(8) << std::setprecision(3) << x;\n\tVINA_CHECK(out.str().size() == 8); \n\tVINA_CHECK(str.size() > i + 8);\n\tVINA_FOR(j, 8)\n\t\tstr[i+j] = out.str()[j];\n}\nstd::string coords_to_pdbqt_string(const vec& coords, const std::string& str) { \n\tstd::string tmp(str);\n\tstring_write_coord(31, coords[0], tmp);\n\tstring_write_coord(39, coords[1], tmp);\n\tstring_write_coord(47, coords[2], tmp);\n\treturn tmp;\n}\n\nvoid model::write_context(const context& c, ofile& out) const {\n\tverify_bond_lengths();\n\tVINA_FOR_IN(i, c) {\n\t\tconst std::string& str = c[i].first;\n\t\tif(c[i].second) {\n\t\t\tout << coords_to_pdbqt_string(coords[c[i].second.get()], str) << '\\n';\n\t\t}\n\t\telse\n\t\t\tout << str << '\\n';\n\t}\n}\n\nvoid model::seti(const conf& c) {\n\tligands.set_conf(atoms, internal_coords, c.ligands);\n}\n\nvoid model::sete(const conf& c) {\n\tVINA_FOR_IN(i, ligands)\n\t\tc.ligands[i].rigid.apply(internal_coords, coords, ligands[i].begin, ligands[i].end);\n\tflex.set_conf(atoms, coords, c.flex);\n}\n\nvoid model::set         (const conf& c) {\n\tligands.set_conf(atoms, coords, c.ligands);\n\tflex   .set_conf(atoms, coords, c.flex);\n}\n\nfl model::gyration_radius(sz ligand_number) const {\n\tVINA_CHECK(ligand_number < ligands.size());\n\tconst ligand& lig = ligands[ligand_number];\n\tfl acc = 0;\n\tunsigned counter = 0;\n\tVINA_RANGE(i, lig.begin, lig.end) {\n\t\tif(atoms[i].el != EL_TYPE_H) { // only heavy atoms are used\n\t\t\tacc += vec_distance_sqr(coords[i], lig.node.get_origin()); // FIXME? check!\n\t\t\t++counter;\n\t\t}\n\t}\n\treturn (counter > 0) ? std::sqrt(acc/counter) : 0;\n}\n\n\nfl eval_interacting_pairs(const precalculate& p, fl v, const interacting_pairs& pairs, const vecv& coords) { // clean up\n\tconst fl cutoff_sqr = p.cutoff_sqr();\n\tfl e = 0;\n\tVINA_FOR_IN(i, pairs) {\n\t\tconst interacting_pair& ip = pairs[i];\n\t\tfl r2 = vec_distance_sqr(coords[ip.a], coords[ip.b]);\n\t\tif(r2 < cutoff_sqr) {\n\t\t\tfl tmp = p.eval_fast(ip.type_pair_index, r2);\n\t\t\tcurl(tmp, v);\n\t\t\te += tmp;\n\t\t}\n\t}\n\treturn e;\n}\n\nfl eval_interacting_pairs_deriv(const precalculate& p, fl v, const interacting_pairs& pairs, const vecv& coords, vecv& forces) { // adds to forces  // clean up\n\tconst fl cutoff_sqr = p.cutoff_sqr();\n\tfl e = 0;\n\tint count=0; \n\tVINA_FOR_IN(i, pairs) {\n\t\tcount++;\n\t\tconst interacting_pair& ip = pairs[i];  \n\t\tvec r; r = coords[ip.b] - coords[ip.a]; // a -> b\n\t\tfl r2 = sqr(r);\n\t\tif(r2 < cutoff_sqr) {\n\t\t\tpr tmp = p.eval_deriv(ip.type_pair_index, r2);\n\t\t\tvec force; force = tmp.second * r;\n\t\t\tcurl(tmp.first, force, v);\n\t\t\te += tmp.first;\n\t\t\t// FIXME inefficient, if using hard curl\n\t\t\tforces[ip.a] -= force; // we could omit forces on inflex here\n\t\t\tforces[ip.b] += force;\n\t\t}\n\t}\n\treturn e;\n}\n\nfl model::evali(const precalculate& p,                                  const vec& v                          ) const { // clean up\n\tfl e = 0;\n\tVINA_FOR_IN(i, ligands) \n\t\te += eval_interacting_pairs(p, v[0], ligands[i].pairs, internal_coords); // probably might was well use coords here\n\treturn e;\n}\n\nfl model::evale(const precalculate& p, const igrid& ig, const vec& v                          ) const { // clean up\n\tfl e = ig.eval(*this, v[1]);\n\te += eval_interacting_pairs(p, v[2], other_pairs, coords);\n\treturn e;\n}\n\ndouble model::phi_alpha_energy(double phi_angle)\n{\ndouble LH = 2.97696467271672, Lc = -199.494365163839, LW = 677.808323900125, RH = 102.253303636096, Rc = 170.599580473404, RW = 1696.78443699429, aH = 10.7448005875571, ac = -105.313553566706, aW = 4724.58364072706, bH = 3.67344580413578, bc = 6.20116671874232, bW = 1347.72056251564, cH = 2.06094652655659, cc = 91.6553021324274, cW = 1500.02002601097, Off = 1.00501e-30, dH = 6.19388683252667, dc = -22.9786969888816, dW = 2122.27783139301, eH = -2.11153017593601, ec = 83.6019123356148, eW = 1254.13371108961, fH = -98.0013005657107, fc = 170.012289132741, fW = 1598.73272567307, Leftx, Rightx, ax, bx, cx, dx, ex, fx, x, Totx;\nx=phi_angle;\nLeftx = LH * exp(-pow((x-(Lc)),2.0)/LW);\nRightx = RH * exp(-pow((x-(Rc)),2.0)/RW);\nax = aH * exp(-pow((x-(ac)),2.0)/aW);\nbx = bH * exp(-pow((x-(bc)),2.0)/bW);\ncx = cH * exp(-pow((x-(cc)),2.0)/cW);\ndx = dH * exp(-pow((x-(dc)),2.0)/dW);\nex = eH * exp(-pow((x-(ec)),2.0)/eW);\nfx = fH * exp(-pow((x-(fc)),2.0)/fW);\nTotx = Rightx + Leftx + ax + bx + cx + dx + ex + fx;\nreturn Totx;\n}\n\n\n\ndouble model::phi_beta_energy(double phi_angle)\n{\ndouble Lc = -330.769995527134, aH = 5.93533323829663, ac = -152.080139620062, aW = 6049.77220005964, bH = 22.467372096061, bc = -23.5159916173247, bW = 606.89715970453, cH = 10.0360057033439, cc = 120.962836525241, cW = 4037.89330459304, LH = 450.540038600828, LW = 4449.7622241787, RH = 23.7118506901333, Rc = 304.624980492529, RW = 8375.1929028027, /*Off = -2.27829251796721,*/ Off = -2.1283, dH = -18.1406478565247, dc = -24.2677756921736, dW = 543.050986049266, eH = 5.88226333077368, ec = 19.6321032903376, eW = 897.92664572344, Leftx, Rightx, ax, bx, cx, dx, ex, x, Totx;\nx=phi_angle;\nLeftx = LH * exp(-pow((x-(Lc)),2.0)/LW);\nRightx = RH * exp(-pow((x-(Rc)),2.0)/RW);\nax = aH * exp(-pow((x-(ac)),2.0)/aW);\nbx = bH * exp(-pow((x-(bc)),2.0)/bW);\ncx = cH * exp(-pow((x-(cc)),2.0)/cW);\ndx = dH * exp(-pow((x-(dc)),2.0)/dW);\nex = eH * exp(-pow((x-(ec)),2.0)/eW);\nTotx = Rightx + Leftx + ax + bx + cx + dx + ex + Off;\nreturn Totx;\n}\n\ndouble model::psi_2A3E_energy(double psi_angle)\n{\ndouble LH = 4.62366277694845, Lc = 5.045583934308, LW = 5005.75236060956, RH = 4.61387450239844, Rc = 362.487847702007, RW = 2090.63190217702, aH = 4.94191727813274, ac = 121.202321824468, aW = 2093.75214491931, bH = 0.402901504292045, bc = 241.428583877882, bW = 456.828754790442, cH = 0.798876573705798, cc = 68.425080241155, cW = 678.807178379645, Off = -0.125645118474882, dc = 192.925748017071, dW = 347.244734136509, dH = 0.222992242737354, Leftx, Rightx, ax, bx, cx, dx, x, Totx;\nif(psi_angle<0)\n{\npsi_angle=360+psi_angle;}\nx=psi_angle;\nLeftx = LH * exp(-pow((x-(Lc)),2.0)/LW);\nRightx = RH * exp(-pow((x-(Rc)),2.0)/RW);\nax = aH * exp(-pow((x-(ac)),2.0)/aW);\nbx = bH * exp(-pow((x-(bc)),2.0)/bW);\ncx = cH * exp(-pow((x-(cc)),2.0)/cW);\ndx = dH * exp(-pow((x-(dc)),2.0)/dW);\nTotx = Rightx + Leftx + ax + bx + cx + dx + Off;\nreturn Totx;\n}\n\ndouble model::psi_2E3A_energy(double psi_angle)\n{\ndouble LH = 4.46811874171788, Lc = 1e-30, LW = 1279.58772056199, RH = 4.38204018882823, Rc = 357.770654336205, RW = 6050.14162479438, aH = 284.944948778136, ac = 146.644068129462, aW = 1551.75673776163, bH = 4.76134025362478, bc = 220.683118921686, bW = 5892.94143218231, cH = -169.197666368856, cc = 147.370828680332, cW = 1742.47541063603, Off = 1.0219924486158, dc = 146.05660843428, dW = 1359.82873591396, dH = -118.440552792375, Leftx, Rightx, ax, bx, cx, dx, x, Totx;\nif(psi_angle<0){\npsi_angle=360+psi_angle;}\nx=psi_angle;\nLeftx = LH * exp(-pow((x-(Lc)),2.0)/LW);\nRightx = RH * exp(-pow((x-(Rc)),2.0)/RW);\nax = aH * exp(-pow((x-(ac)),2.0)/aW);\nbx = bH * exp(-pow((x-(bc)),2.0)/bW);\ncx = cH * exp(-pow((x-(cc)),2.0)/cW);\ndx = dH * exp(-pow((x-(dc)),2.0)/dW);\nTotx = Rightx + Leftx + ax + bx + cx + dx + Off;\nreturn Totx;\n}\n\ndouble model::psi_6A_energy(double psi_angle)\n{\ndouble aH = 67.9431348410598, ac = -59.5393395706705, aW = 993.323581145538, bH = 6.13421142432396, bc = 10.4786088782815, bW = 945.770771330812, cH = 3.27628727235978, cc = 54.2960678151208, cW = 851.528141801851, dH = 0.727486729062442, dc = 131.067737803489, dW = 1037.41211378392, eH = 2.57362265878937, ec = 245.102891425541, eW = 2012.99451568206, fH = 5.75995973448166, fc = 359.999988549478, fW = 1153.3974275673, gH = 3.47492643928157, gc = 321.677942414686, gW = 2080.97053159226, hH = -0.741000462200939, hc = 199.106903524814, hW = 522.180434119001, ax, bx, cx, dx, ex, fx, gx, hx, x, Totx;\n\nif(psi_angle<0)\n{\npsi_angle=360+psi_angle;\n}\nx=psi_angle;\nax = aH * exp(-pow((x-(ac)),2.0)/aW);\nbx = bH * exp(-pow((x-(bc)),2.0)/bW);\ncx = cH * exp(-pow((x-(cc)),2.0)/cW);\ndx = dH * exp(-pow((x-(dc)),2.0)/dW);\nex = eH * exp(-pow((x-(ec)),2.0)/eW);\nfx = fH * exp(-pow((x-(fc)),2.0)/fW);\ngx = gH * exp(-pow((x-(gc)),2.0)/gW);\nhx = hH * exp(-pow((x-(hc)),2.0)/hW);\nTotx = ax + bx + cx + dx + ex + fx + gx + hx;\nreturn Totx;\n}\n\ndouble model::psi_6E_energy(double psi_angle)\n{\ndouble aH = 7.24858655753829, ac = 3.60600554520403, aW = 2459.23916629141, bH = 1.9, bc = 96.5930821702371, bW = 2683.88656516991, cH = 0.741022592342903, cc = 141.663521919709, cW = 1150.04756181103, dH = 0.2, dc = 162, dW = 400, eH = 0.287090039932611, ec = 228.171314273305, eW = 272.201363844744, fH = 1.22591971967808, fc = 292.206221787048, fW = 1134.52455512381, gH = 7.41063235334191, gc = 369.867701147817, gW = 3499.15994772992, hH = -0.61489499584011, hc = 271.319024293053, hW = 532.437194483944, iH = -0.35, ic = 183, iW = 100, ax, bx, cx, dx, ex, fx, gx, hx, ix, x, Totx;\n\nif(psi_angle<0)\n{\npsi_angle=360+psi_angle;\n}\nx=psi_angle;\nax = aH * exp(-pow((x-(ac)),2.0)/aW);\nbx = bH * exp(-pow((x-(bc)),2.0)/bW);\ncx = cH * exp(-pow((x-(cc)),2.0)/cW);\ndx = dH * exp(-pow((x-(dc)),2.0)/dW);\nex = eH * exp(-pow((x-(ec)),2.0)/eW);\nfx = fH * exp(-pow((x-(fc)),2.0)/fW);\ngx = gH * exp(-pow((x-(gc)),2.0)/gW);\nhx = hH * exp(-pow((x-(hc)),2.0)/hW);\nix = iH * exp(-pow((x-(ic)),2.0)/iW);\nTotx = ax + bx + cx + dx + ex + fx + gx + hx + ix;\nreturn Totx;\n}\n\ndouble model::omega_6A_energy(double omega_angle)\n{\ndouble x, energy, b, k=0.0025;\n        if(omega_angle<0)\n        {\n        x=360+omega_angle;\n        }\n        else\n        {\n        x=omega_angle;\n        }\n        if((x>=0.0 && x<120.0)||(x>=360.0 && x<120.0))\n        {\n        b=0.0;\n        energy=k*pow((x-60),2)+b;\n        }\n        else if(x>=120.0 && x<240.0)\n        {\n        b=0.3;\n        energy=k*pow((x-180),2)+b;\n        }\n        else if(x>=240.0 && x<360.0)\n        {\n        b=1.0;\n        energy=k*pow((x-300),2)+b;\n        }\nreturn energy;\n}\n\n\ndouble model::omega_6E_energy(double omega_angle)\n{\ndouble x, energy, b, k=0.0025;\n        if(omega_angle<0)\n        {\n        x=360+omega_angle;\n        }\n        else\n        {\n        x=omega_angle;\n        }\n        if((x>=0.0 && x<120.0)||(x>=360.0 && x<120.0))\n        {\n        b=0.21;\n        energy=k*pow((x-60),2)+b;\n        }\n        else if(x>=120.0 && x<240.0)\n        {\n        b=1.39;\n        energy=k*pow((x-180),2)+b;\n        }\n        else if(x>=240.0 && x<360.0)\n        {\n        b=0.0;\n        energy=k*pow((x-300),2)+b;\n        }\nreturn energy;\n}\n\n\n\nfl model::eval         (const precalculate& p, const igrid& ig, const vec& v, const conf& c           ) { // clean up\n\tset(c);\n\tfl e = evale(p, ig, v);\n\tVINA_FOR_IN(i, ligands) \n\t\te += eval_interacting_pairs(p, v[0], ligands[i].pairs, coords); // coords instead of internal coords\n\treturn e;\n}\n\ndouble model::get_torsion_coords_vecs_list(vec A, vec B, vec C, vec D)\n{\ndouble angle=0.0;\nvec AB, BC, CD, ABCcross, BCDcross;\ndouble ABC_BCD_dot, AB_BCD_dot, BCscalar_AB_BCD_dot;\nAB=B-A;\nBC=C-B;\nCD=D-C;\nABCcross=cross_product(AB,BC);\nBCDcross=cross_product(BC,CD);\nABC_BCD_dot=dot_product(ABCcross,BCDcross);\nAB_BCD_dot=dot_product(AB,BCDcross);\nBCscalar_AB_BCD_dot=magnitude(BC)*AB_BCD_dot;                        \nangle=atan2(BCscalar_AB_BCD_dot,ABC_BCD_dot)*57.2957795; //angle in degrees\nreturn angle;           \n}                       \n\nvecv model::get_flexible_coords(){\nreturn coords;\n}\n\n\nfl model::eval_chi(const fl chi_coeff, const fl chi_cutoff)\n{\nfl e=0.0;\nif(chi_coeff!=0){\n\tdouble phi_energy=0.0, psi_energy=0.0,omega_energy=0.0, phi=0.0, psi=0.0, omega=0.0, total=0.0,current_energy=0.0;\n\tstd::vector< std::vector<size_t*> > glyco_info=glycan_info_func();\n\tVINA_FOR(i,glyco_info.size())\n\t{\n\tif(glyco_info[i][10][0]!=0){\n\tphi=get_torsion_coords_vecs_list(coords[glyco_info[i][0][0]],coords[glyco_info[i][1][0]],coords[glyco_info[i][2][0]],coords[glyco_info[i][3][0]]);\n\t\tif(glyco_info[i][5][0]==0)\n\t\t{//Alpha\n\t\t\tif(glyco_info[i][10][0]==1)\n\t\t\t{//D sugar (Alpha)\n\t\t\tcurrent_energy=phi_alpha_energy(phi);\n\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\tphi_energy+=current_energy;\n\t\t\t\tcurrent_energy=0.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(glyco_info[i][10][0]==2)\n\t\t\t{//L-Sugar (Alpha)\n\t\t\tcurrent_energy=phi_alpha_energy(-phi);\n\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\tphi_energy+=current_energy;\n                                current_energy=0.0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{//Beta\n\t\t\tif(glyco_info[i][10][0]==1)\n\t\t\t{//D sugar (Beta)\n\t\t\tcurrent_energy=phi_beta_energy(phi);\n\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\tphi_energy+=current_energy;\n\t\t\t\tcurrent_energy=0.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(glyco_info[i][10][0]==2)\n\t\t\t{//L Sugar (Beta)\n\t\t\tcurrent_energy=phi_beta_energy(-phi);\n\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\tphi_energy+=current_energy;\n\t\t\t\tcurrent_energy=0.0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif(glyco_info[i][11][0]!=0){\n\tpsi=get_torsion_coords_vecs_list(coords[glyco_info[i][1][0]],coords[glyco_info[i][2][0]],coords[glyco_info[i][3][0]],coords[glyco_info[i][4][0]]);\n\tomega=get_torsion_coords_vecs_list(coords[glyco_info[i][2][0]],coords[glyco_info[i][3][0]],coords[glyco_info[i][4][0]],coords[glyco_info[i][9][0]]);\n\t\tif(glyco_info[i][7][0]==2 || glyco_info[i][7][0]==4)\n\t\t{//2 or 4 linkage\n\t\t\tif(glyco_info[i][6][0]==0)\n\t\t\t{//Axial attachment\n\t\t\t\tif(glyco_info[i][11][0]==2)\n\t\t\t\t{//L sugar\n\t\t\t\tcurrent_energy=psi_2A3E_energy(-psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n\t\t\t\t\tcurrent_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(glyco_info[i][11][0]==1)\n\t\t\t\t{//D sugar\n\t\t\t\tcurrent_energy=psi_2A3E_energy(psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n                                        current_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{//Equatorial attachment\n\t\t\t\tif(glyco_info[i][11][0]==2)\n\t\t\t\t{//L sugar\n\t\t\t\tcurrent_energy=psi_2E3A_energy(-psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n\t\t\t\t\tcurrent_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(glyco_info[i][11][0]==1)\n\t\t\t\t{//D sugar\n\t\t\t\tcurrent_energy=psi_2E3A_energy(psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n                                        current_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t}\n\t\telse if(glyco_info[i][7][0]==3)\n\t\t{//3 linkage\n\t\t\tif(glyco_info[i][6][0]==0)\n\t\t\t{//Axial attachment\n\t\t\t\n\t\t\t\tif(glyco_info[i][11][0]==2)\n\t\t\t\t{//L sugar\n\t\t\t\tcurrent_energy=psi_2E3A_energy(-psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n                                        current_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(glyco_info[i][11][0]==1)\n\t\t\t\t{//D sugar\n                                current_energy=psi_2E3A_energy(psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n                                        current_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{//Equatorial attachment\n\t\t\t\tif(glyco_info[i][11][0]==2)\n\t\t\t\t{//L sugar\n                                current_energy=psi_2A3E_energy(-psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n                                        current_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(glyco_info[i][11][0]==1)\n\t\t\t\t{//D sugar\n\t\t\t\tcurrent_energy=psi_2A3E_energy(psi);\n\t\t\t\t\tif(current_energy>chi_cutoff){\n\t\t\t\t\tpsi_energy+=current_energy;\n                                        current_energy=0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t}\n\telse if(glyco_info[i][7][0]==6)\n                {//6 linkage\n                        if(glyco_info[i][8][0]==0)\n                                {\n                                current_energy=psi_6A_energy(psi);\n                                        if(current_energy>chi_cutoff){\n                                        psi_energy+=current_energy;\n                                        current_energy=0.0;\n                                        }\n                                current_energy=omega_6A_energy(omega);\n                                        if(current_energy>chi_cutoff){\n                                        omega_energy+=current_energy;\n                                        current_energy=0.0;\n                                        }\n                                }\n                        else if(glyco_info[i][8][0]==1)\n                                {\n                                current_energy=psi_6E_energy(psi);\n                                        if(current_energy>chi_cutoff){\n                                        psi_energy+=current_energy;\n                                        current_energy=0.0;\n                                        }\n                                current_energy=omega_6E_energy(omega);\n                                        if(current_energy>chi_cutoff){\n                                        omega_energy+=current_energy;\n                                        current_energy=0.0;\n                                        }\n                                }\n                }\n\t}\n\t\n\t}\n\ttotal=phi_energy+psi_energy+omega_energy;\n\ttotal=total*chi_coeff; \n\tdouble combined_score=total+e;\n\te=combined_score;\n\t}\n\telse\n\te=0.0;\nreturn e;\n}\n\n\nfl  model::eval_deriv  (const precalculate& p, const igrid& ig, const vec& v, const conf& c, change& g/*, std::vector< std::vector<int> > glyco_info*/,const fl chi_coeff, const fl chi_cutoff ) { // clean up\n\tset(c);\n\tfl chi_energy = 0.0;\n\tchi_energy=eval_chi(chi_coeff,chi_cutoff);\n\tfl e = ig.eval_deriv(*this, v[1]); // sets minus_forces, except inflex\n        e += eval_interacting_pairs_deriv(p, v[2], other_pairs, coords, minus_forces); // adds to minus_forces\n        VINA_FOR_IN(i, ligands){\n                e += eval_interacting_pairs_deriv(p, v[0], ligands[i].pairs, coords, minus_forces); // adds to minus_forces\n}\n        ligands.derivative(coords, minus_forces, g.ligands);\n\tflex.derivative(coords, minus_forces, g.flex); // inflex forces are ignored\n\treturn (e+chi_energy);\n}\n\n\nfl model::eval_intramolecular(const precalculate& p, const vec& v, const conf& c) {\n\tset(c);\n\tfl e = 0;\n\n\t// internal for each ligand\n\tVINA_FOR_IN(i, ligands)\n\t\te += eval_interacting_pairs(p, v[0], ligands[i].pairs, coords); // coords instead of internal coords\n\n\tsz nat = num_atom_types(atom_typing_used());\n\tconst fl cutoff_sqr = p.cutoff_sqr();\n\n\t// flex-rigid\n\tVINA_FOR(i, num_movable_atoms()) {\n\t\tif(find_ligand(i) < ligands.size()) continue; // we only want flex-rigid interaction\n\t\tconst atom_vc& a = atoms[i];\n\t\tsz t1 = a.get(atom_typing_used());\n\t\tif(t1 >= nat) continue;\n\t\tVINA_FOR_IN(j, grid_atoms) {\n\t\t\tconst atom_vc& b = grid_atoms[j];\n\t\t\tsz t2 = b.get(atom_typing_used());\n\t\t\tif(t2 >= nat) continue;\n\t\t\tfl r2 = vec_distance_sqr(coords[i], b.coords);\n\t\t\tif(r2 < cutoff_sqr) {\n\t\t\t\tsz type_pair_index = triangular_matrix_index_permissive(nat, t1, t2);\n\t\t\t\tfl this_e = p.eval_fast(type_pair_index, r2);\n\t\t\t\tcurl(this_e, v[1]);\n\t\t\t\te += this_e;\n\t\t\t}\n\t\t}\n\t}\n\n\t// flex-flex\n\tVINA_FOR_IN(i, other_pairs) {\n\t\tconst interacting_pair& pair = other_pairs[i];\n\t\tif(find_ligand(pair.a) < ligands.size() || find_ligand(pair.b) < ligands.size()) continue; // we only need flex-flex\n\t\tfl r2 = vec_distance_sqr(coords[pair.a], coords[pair.b]);\n\t\tif(r2 < cutoff_sqr) {\n\t\t\tfl this_e = p.eval_fast(pair.type_pair_index, r2);\n\t\t\tcurl(this_e, v[2]);\n\t\t\te += this_e;\n\t\t}\n\t}\n\treturn e;\n}\n\n\nfl model::eval_adjusted      (const scoring_function& sf, const precalculate& p, const igrid& ig, const vec& v, const conf& c, fl intramolecular_energy) {\n\tfl e = eval(p, ig, v, c); // sets c\n\treturn sf.conf_independent(*this, e - intramolecular_energy);\n}\n\nfl model::rmsd_lower_bound_asymmetric(const model& x, const model& y) const { // actually static\n\tsz n = x.m_num_movable_atoms; \n\tVINA_CHECK(n == y.m_num_movable_atoms);\n\tfl sum = 0;\n\tunsigned counter = 0;\n\tVINA_FOR(i, n) {\n\t\tconst atom_vc& a =   x.atoms[i];\n\t\tif(a.el != EL_TYPE_H) {\n\t\t\tfl r2 = max_fl;\n\t\t\tVINA_FOR(j, n) {\n\t\t\t\tconst atom_vc& b = y.atoms[j];\n\t\t\t\tif(a.same_element(b) && !b.is_hydrogen()) {\n\t\t\t\t\tfl this_r2 = vec_distance_sqr(x.coords[i], \n\t\t\t\t\t                              y.coords[j]);\n\t\t\t\t\tif(this_r2 < r2)\n\t\t\t\t\t\tr2 = this_r2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(not_max(r2));\n\t\t\tsum += r2;\n\t\t\t++counter;\n\t\t}\n\t}\n\treturn (counter == 0) ? 0 : std::sqrt(sum / counter);\n}\n\nfl model::rmsd_lower_bound(const model& m) const {\n\treturn (std::max)(rmsd_lower_bound_asymmetric(*this,     m),\n\t\t            rmsd_lower_bound_asymmetric(    m, *this));\n}\n\nfl model::rmsd_upper_bound(const model& m) const {\n\tVINA_CHECK(m_num_movable_atoms == m.m_num_movable_atoms);\n\tfl sum = 0;\n\tunsigned counter = 0;\n\tVINA_FOR(i, m_num_movable_atoms) {\n\t\tconst atom_vc& a =   atoms[i];\n\t\tconst atom_vc& b = m.atoms[i];\n\t\tassert(a.ad == b.ad);\n\t\tassert(a.xs == b.xs);\n\t\tif(a.el != EL_TYPE_H) {\n\t\t\tsum += vec_distance_sqr(coords[i], m.coords[i]);\n\t\t\t++counter;\n\t\t}\n\t}\n\treturn (counter == 0) ? 0 : std::sqrt(sum / counter);\n}\n\nfl model::rmsd_ligands_upper_bound(const model& m) const {\n\tVINA_CHECK(ligands.size() == m.ligands.size());\n\tfl sum = 0;\n\tunsigned counter = 0;\n\tVINA_FOR_IN(ligand_i, ligands) {\n\t\tconst ligand&   lig =   ligands[ligand_i];\n\t\tconst ligand& m_lig = m.ligands[ligand_i];\n\t\tVINA_CHECK(lig.begin == m_lig.begin);\n\t\tVINA_CHECK(lig.end   == m_lig.end);\n\t\tVINA_RANGE(i, lig.begin, lig.end) {\n\t\t\tconst atom_vc& a =   atoms[i];\n\t\t\tconst atom_vc& b = m.atoms[i];\n\t\t\tassert(a.ad == b.ad);\n\t\t\tassert(a.xs == b.xs);\n\t\t\tif(a.el != EL_TYPE_H) {\n\t\t\t\tsum += vec_distance_sqr(coords[i], m.coords[i]);\n\t\t\t\t++counter;\n\t\t\t}\n\t\t}\n\t}\n\treturn (counter == 0) ? 0 : std::sqrt(sum / counter);\n}\n\n\nvoid model::verify_bond_lengths() const {\n\tVINA_FOR(i, grid_atoms.size() + atoms.size()) {\n\t\tconst atom_index ai = sz_to_atom_index(i);\n\t\tconst atom_vc& a = get_atom(ai);\n\t\tVINA_FOR_IN(j, a.bonds) {\n\t\t\tconst bond_vc& b = a.bonds[j];\n\t\t\tfl d = std::sqrt(distance_sqr_between(ai, b.connected_atom_index));\n\t\t\tbool ok = eq(d, b.length);\n\t\t\tif(!ok) {\n\t\t\t\tVINA_SHOW(d);\n\t\t\t\tVINA_SHOW(b.length);\n\t\t\t}\n\t\t\tVINA_CHECK(ok);\n\t\t}\n\t}\n}\n\nvoid model::check_internal_pairs() const {\n\tVINA_FOR_IN(i, ligands) {\n\t\tconst ligand& lig = ligands[i];\n\t\tconst interacting_pairs& pairs = lig.pairs;\n\t\tVINA_FOR_IN(j, pairs) {\n\t\t\tconst interacting_pair& ip = pairs[j];\n\t\t\tVINA_CHECK(ip.a >= lig.begin);\n\t\t\tVINA_CHECK(ip.b  < lig.end);\n\t\t}\n\t}\n}\n\nvoid model::about() const {\n\tVINA_SHOW(atom_typing_used());\n\tVINA_SHOW(num_movable_atoms());\n\tVINA_SHOW(num_internal_pairs());\n\tVINA_SHOW(num_other_pairs());\n\tVINA_SHOW(num_ligands());\n\tVINA_SHOW(num_flex());\n}\n\nvoid model::print_stuff() const {\n\tstd::cout << \"coords:\\n\";\n\tVINA_FOR_IN(i, coords)\n\t\tprintnl(coords[i]);\n\n\tstd::cout << \"internal_coords:\\n\";\n\tVINA_FOR_IN(i, internal_coords)\n\t\tprintnl(internal_coords[i]);\n\n\tstd::cout << \"atoms:\\n\";\n\tVINA_FOR_IN(i, atoms) {\n\t\tconst atom_vc& a = atoms[i];\n\t\tstd::cout << a.el << \" \" << a.ad << \" \" << a.xs << \" \" << a.sy << \"    \" << a.charge << '\\n';\n\t\tstd::cout << a.bonds.size() << \"  \"; printnl(a.coords);\n\t}\n\n\tstd::cout << \"grid_atoms:\\n\";\n\tVINA_FOR_IN(i, grid_atoms) {\n\t\tconst atom_vc& a = grid_atoms[i];\n\t\tstd::cout << a.el << \" \" << a.ad << \" \" << a.xs << \" \" << a.sy << \"    \" << a.charge << '\\n';\n\t\tstd::cout << a.bonds.size() << \"  \"; printnl(a.coords);\n\t}\n\tabout();\n}\n\nfl pairwise_clash_penalty(fl r, fl covalent_r) {\n\t// r = 0          -> max_penalty \n\t// r = covalent_r -> 1\n\t// elsewhere      -> hyperbolic function\n\tassert(r >= 0);\n\tassert(covalent_r > epsilon_fl);\n\tconst fl x = r / covalent_r;\n\tif(x > 2) return 0;\n\treturn 1-x*x/4;\n}\n\nfl model::clash_penalty_aux(const interacting_pairs& pairs) const {\n\tfl e = 0;\n\tVINA_FOR_IN(i, pairs) {\n\t\tconst interacting_pair& ip = pairs[i];\n\t\tconst fl r = std::sqrt(vec_distance_sqr(coords[ip.a], coords[ip.b]));\n\t\tconst fl covalent_r = atoms[ip.a].covalent_radius() + atoms[ip.b].covalent_radius();\n\t\te += pairwise_clash_penalty(r, covalent_r);\n\t}\n\treturn e;\n}\n\nfl model::clash_penalty() const {\n\tfl e = 0;\n\tVINA_FOR_IN(i, ligands) \n\t\te += clash_penalty_aux(ligands[i].pairs);\n\te += clash_penalty_aux(other_pairs);\n\treturn e;}\n", "meta": {"hexsha": "731e972e9fd9b200680b835a282089ddd64d6870", "size": 41447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/model.cpp", "max_stars_repo_name": "Alicecomma/VinaCarb", "max_stars_repo_head_hexsha": "baf0759bfce46cd31fff03aa73edf4ab7fd929b3", "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/lib/model.cpp", "max_issues_repo_name": "Alicecomma/VinaCarb", "max_issues_repo_head_hexsha": "baf0759bfce46cd31fff03aa73edf4ab7fd929b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/model.cpp", "max_forks_repo_name": "Alicecomma/VinaCarb", "max_forks_repo_head_hexsha": "baf0759bfce46cd31fff03aa73edf4ab7fd929b3", "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.5074509804, "max_line_length": 630, "alphanum_fraction": 0.6324462567, "num_tokens": 13256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.02262920015662629, "lm_q1q2_score": 0.006955266083387774}}
{"text": "// -*- mode: c++; indent-tabs-mode: nil; -*-\n//\n// Copyright (c) 2010-2015 Illumina, Inc.\n// All rights reserved.\n\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n\n// 1. Redistributions of source code must retain the above copyright notice, this\n//    list of conditions and the following disclaimer.\n\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n\n// 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\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// OR TORT INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/**\n *  \\brief Read a spacer-separated file and compute a ROC curve\n *\n *\n * \\file roc.cpp\n * \\author Peter Krusche\n * \\email pkrusche@illumina.com\n *\n */\n\n#include <boost/program_options.hpp>\n\n#include \"Version.hh\"\n#include \"helpers/StringUtil.hh\"\n\n#include <iostream>\n#include <limits>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <cstdlib>\n#include <map>\n#include <set>\n#include <boost/algorithm/string.hpp>\n\n#include \"Error.hh\"\n\nenum class tag_t { tp, fp, fn };\n\nstruct RocData {\n    void add(double value, tag_t tag)\n    {\n        if(reverse) value = -value;\n        data.push_back(std::make_pair(value, tag));\n    }\n\n    void print_roc(std::ostream & out) {\n        if(data.empty())\n        {\n            return;\n        }\n        // pair gets sorted by first element, then second\n        std::sort(data.begin(), data.end());\n        int total_tp = 0;\n        int total_fp = 0;\n        int total_fn = 0;\n        for (auto r : data) {\n            switch(r.second)\n            {\n                case tag_t::tp: ++total_tp; break;\n                case tag_t::fp: ++total_fp; break;\n                case tag_t::fn: ++total_fn; break;\n                default: break;\n            }\n        }\n\n        out << label << \"\\t\" << \"tp\" << \"\\t\" << \"fp\" << \"\\t\" << \"fn\" << \"\\t\" << \"precision\" << \"\\t\" << \"recall\" << \"\\n\";\n        double current_value = data[0].first - 1;\n        double tp = total_tp;\n        double fp = total_fp;\n        double fn = total_fn;\n        for (auto r : data) {\n            if(r.first > current_value)\n            {\n                current_value = r.first;\n                double precision = 1.0;\n                double recall = 0;\n                if(tp + fp > 0)\n                {\n                    precision = tp / (tp + fp);\n                }\n                if(tp + fn > 0)\n                {\n                    recall = tp / (tp + fn);\n                }\n\n                out << (reverse ? -current_value : current_value) << \"\\t\" << tp << \"\\t\" << fp << \"\\t\" << fn << \"\\t\" << precision << \"\\t\" << recall << \"\\n\";\n            }\n\n            switch(r.second)\n            {\n                case tag_t::fn:\n                    break;\n                case tag_t::tp:\n                    --tp;\n                    ++fn;\n                    break;\n                case tag_t::fp:\n                    --fp;\n                    break;\n            }\n        }\n    }\n\n    std::vector<std::pair<double, tag_t> > data;\n    std::string label = \"value\";\n\n    bool reverse = false;\n};\n\n\nint main(int argc, char* argv[]) {\n    namespace po = boost::program_options;\n\n    std::vector<std::string> files;\n    std::string output = \"-\";\n    std::string sep = \"\\t\";\n    int header_lines = 1;\n    std::string value = \"\";\n    int value_column = 0;\n    std::string tag = \"\";\n    int tag_column = 1;\n    std::string filter = \"\";\n    int filter_column = -1;\n    std::string filter_name = \"\";\n\n    bool verbose = false;\n    bool reverse = false;\n\n    try\n    {\n        // Declare the supported options.\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()\n            (\"help,h\", \"produce help message\")\n            (\"version\", \"show version\")\n            (\"verbose\", \"show verbose information (to stderr)\")\n            (\"input-file\", po::value<std::vector< std::string> >(), \"The input files\")\n            (\"output-file,o\", po::value<std::string>(), \"Output file name, defaults to - / write to stdout\")\n            (\"separator,s\", po::value<std::string>(), \"separator character (default: '\\\\t' for reading tsv)\")\n            (\"header-lines,H\", po::value<int>(), \"lines to skip before starting to read\")\n            (\"value,v\", po::value<std::string>(), \"value column name\")\n            (\"value-column\", po::value<int>(), \"value column number\")\n            (\"reverse,R\", po::value<bool>(), \"Reverse counting for score (default: higher scores are better)\")\n            (\"tag,t\", po::value<std::string>(), \"tag column name\")\n            (\"tag-column\", po::value<int>(), \"tag column number. Tags must be TP/FP/FN, lines with different tags will be ignored\")\n            (\"filter,f\", po::value<std::string>(), \"filter column name\")\n            (\"filter-column\", po::value<int>(), \"filter column number. This is used if we the value we are varying is a threshold for a certain filter.\")\n            (\"filter-name,n\", po::value<std::string>(), \"filter name if value is threshold for this filter\")\n        ;\n\n        po::positional_options_description popts;\n        popts.add(\"input-file\", -1);\n\n        po::options_description cmdline_options;\n        cmdline_options\n            .add(desc)\n        ;\n\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).\n                  options(cmdline_options).positional(popts).run(), vm);\n        po::notify(vm);\n\n        if (vm.count(\"version\"))\n        {\n            std::cout << \"roc version \" << HAPLOTYPES_VERSION << \"\\n\";\n            return 0;\n        }\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << desc << \"\\n\";\n            return 1;\n        }\n\n        if (vm.count(\"verbose\"))\n        {\n            std::cerr << \"Verbose mode enabled\" << \"\\n\";\n            verbose = true;\n        }\n\n        if (vm.count(\"input-file\"))\n        {\n            files = vm[\"input-file\"].as< std::vector<std::string> >();\n        }\n\n        if (vm.count(\"output-file\"))\n        {\n            output = vm[\"output-file\"].as<std::string>();\n        }\n\n        if (vm.count(\"separator\"))\n        {\n            sep = vm[\"separator\"].as< std::string >();\n        }\n\n        if (vm.count(\"header-lines\"))\n        {\n            header_lines = vm[\"header-lines\"].as<int>();\n        }\n\n        if (vm.count(\"value-column\"))\n        {\n            value_column = vm[\"value-column\"].as<int>() - 1;\n        }\n        if (vm.count(\"value\"))\n        {\n            value = vm[\"value\"].as<std::string>();\n        }\n        if (vm.count(\"reverse\"))\n        {\n            reverse = vm[\"reverse\"].as<bool>();\n        }\n\n        if (vm.count(\"tag-column\"))\n        {\n            tag_column = vm[\"tag-column\"].as<int>() - 1;\n        }\n        if (vm.count(\"tag\"))\n        {\n            tag = vm[\"tag\"].as<std::string>();\n        }\n\n        if (vm.count(\"filter-column\"))\n        {\n            filter_column = vm[\"filter-column\"].as<int>() - 1;\n        }\n        if (vm.count(\"filter\"))\n        {\n            filter = vm[\"filter\"].as<std::string>();\n        }\n        if (vm.count(\"filter-name\"))\n        {\n            filter_name = vm[\"filter-name\"].as<std::string>();\n        }\n    }\n    catch (po::error & e)\n    {\n        std::cerr << e.what() << \"\\n\";\n        return 1;\n    }\n\n\n    RocData data;\n    data.reverse = reverse;\n    if(!value.empty())\n    {\n        data.label = value;\n    }\n\n    if(files.size() == 0) {\n        files.push_back(\"-\");\n    }\n\n    int total_tp = 0;\n    int total_fp = 0;\n    int total_fn = 0;\n    int total_filtered = 0;\n    int total_ignored = 0;\n    std::map<std::string, int> filter_stats;\n    std::map<std::string, int> filter_stats_tp;\n    std::map<std::string, int> filter_stats_fp;\n    std::map<std::string, int> filter_stats_fn;\n\n    for (auto i : files) {\n        std::istream * in = NULL;\n        bool deleteme = false;\n        if(i == \"-\") {\n            in = &std::cin;\n        } else {\n            in = new std::ifstream(i.c_str());\n            deleteme = true;\n        }\n\n        // read input data\n        int min_columns = std::max(value_column, tag_column);\n        min_columns = std::max(filter_column, min_columns);\n\n        int hc = header_lines;\n        while(in->good()) {\n            std::string line;\n            std::getline(*in, line);\n            std::vector<std::string> v;\n            stringutil::split(line, v, sep, true);\n\n            if(hc > 0) {\n                if (!value.empty() || !tag.empty() || !filter.empty())\n                {\n                    for (size_t i = 0; i < v.size(); ++i)\n                    {\n                        v[i] = stringutil::replaceAll(v[i], \"\\r\", \"\");\n                        if(!v[i].empty() && v[i] == value) {\n                            value_column = i;\n                        }\n                        if(!v[i].empty() && v[i] == tag) {\n                            tag_column = i;\n                        }\n                        if(!v[i].empty() && v[i] == filter) {\n                            filter_column = i;\n                        }\n                    }\n                }\n                min_columns = std::max(value_column, tag_column);\n                min_columns = std::max(filter_column, min_columns);\n                --hc;\n                continue;\n            }\n\n            if(((int)v.size()) < min_columns + 1) {\n                ++total_ignored;\n                continue;\n            }\n\n            std::string & ltag = v[tag_column];\n            boost::algorithm::to_lower(ltag);\n\n            // true if filtered by other filter than the one we're looking at. These go to the beginning.\n            bool filtered_other = false;\n\n            if (filter_column >= 0)\n            {\n                std::vector<std::string> filters;\n                std::string fcol = v[filter_column];\n                if(fcol == \".\" || fcol == \"PASS\") {\n                    fcol = \"\";\n                }\n                stringutil::split(fcol, filters, \";,\");\n                for (auto f : filters)\n                {\n                    auto q = filter_stats.find(f);\n                    if(q != filter_stats.end()) {\n                        q->second++;\n                    } else {\n                        filter_stats[f] = 1;\n                    }\n                    if (ltag == \"tp\")\n                    {\n                        auto q = filter_stats_tp.find(f);\n                        if(q != filter_stats_tp.end()) {\n                            q->second++;\n                        } else {\n                            filter_stats_tp[f] = 1;\n                        }\n                    } else if (ltag == \"fp\") {\n                        auto q = filter_stats_fp.find(f);\n                        if(q != filter_stats_fp.end()) {\n                            q->second++;\n                        } else {\n                            filter_stats_fp[f] = 1;\n                        }\n                    } else if (ltag == \"fn\") {\n                        auto q = filter_stats_fn.find(f);\n                        if(q != filter_stats_fn.end()) {\n                            q->second++;\n                        } else {\n                            filter_stats_fn[f] = 1;\n                        }\n                    }\n                }\n\n                if(!filter_name.empty())\n                {\n                    auto it = filters.begin();\n                    std::vector<std::string> _filters_to_remove;\n                    stringutil::split(filter_name, _filters_to_remove, \";,\");\n                    std::set<std::string> filters_to_remove;\n                    for (auto f : _filters_to_remove) {\n                        filters_to_remove.insert(f);\n                        if(f == \"*\")\n                        {\n                            filters.clear();\n                            break;\n                        }\n                    }\n                    while(it != filters.end())\n                    {\n                        if(filters_to_remove.count(*it) > 0) {\n                            filters.erase(it);\n                            it = filters.begin();\n                        } else {\n                            ++it;\n                        }\n                    }\n                }\n                if (!filters.empty())\n                {\n                    ++total_filtered;\n                    filtered_other = true;\n                }\n            }\n\n            tag_t ttag = tag_t::fn;\n\n            if(ltag.substr(0, 2) == \"tp\") {\n                ttag = tag_t::tp;\n                ++total_tp;\n            } else if(ltag.substr(0, 2) == \"fp\") {\n                ttag = tag_t::fp;\n                ++total_fp;\n            } else if(ltag.substr(0, 2) == \"fn\") {\n                ttag = tag_t::fn;\n                ++total_fn;\n            } else {\n                ++total_ignored;\n                continue;\n            }\n\n            double xvalue = atof(v[value_column].c_str());\n            if(v[value_column] == \"\")\n            {\n                xvalue = 0;\n            }\n            if (filtered_other)\n            {\n                xvalue = std::numeric_limits<double>::min();\n            }\n            data.add(xvalue, ttag);\n        }\n        if (deleteme)\n        {\n            delete in;\n        }\n    }\n    if(verbose) {\n        std::cerr << \"tp: \" << total_tp << \" fp: \" << total_fp << \" fn: \" << total_fn\n                  << \" filtered: \" << total_filtered << \" ignored: \" << total_ignored << \"\\n\";\n        for (auto i : filter_stats) {\n            int f_tp = 0;\n            if (filter_stats_tp.find(i.first) != filter_stats_tp.end())\n            {\n                f_tp = filter_stats_tp[i.first];\n            }\n            int f_fp = 0;\n            if (filter_stats_fp.find(i.first) != filter_stats_fp.end())\n            {\n                f_fp = filter_stats_fp[i.first];\n            }\n            std::cerr << \"F:\" << i.first << \" : \" << i.second\n                      << \" -- tp: \" << f_tp\n                      << \" fp: \" << f_fp\n                      << \"\\n\";\n        }\n    }\n    if(output == \"-\") {\n        data.print_roc(std::cout);\n    } else {\n        std::ofstream o(output);\n        data.print_roc(o);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "13263acd887ab30b188cd1b3a008abb7f289a492", "size": 14990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/c++/main/roc.cpp", "max_stars_repo_name": "nh13/hap.py", "max_stars_repo_head_hexsha": "fd67904f7a68981e76c12301aa2add2718b30120", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 315.0, "max_stars_repo_stars_event_min_datetime": "2015-07-21T13:53:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T02:01:19.000Z", "max_issues_repo_path": "src/c++/main/roc.cpp", "max_issues_repo_name": "nh13/hap.py", "max_issues_repo_head_hexsha": "fd67904f7a68981e76c12301aa2add2718b30120", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 147.0, "max_issues_repo_issues_event_min_datetime": "2015-11-26T03:06:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T18:22:33.000Z", "max_forks_repo_path": "src/c++/main/roc.cpp", "max_forks_repo_name": "nh13/hap.py", "max_forks_repo_head_hexsha": "fd67904f7a68981e76c12301aa2add2718b30120", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 124.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T13:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:34:31.000Z", "avg_line_length": 31.8936170213, "max_line_length": 155, "alphanum_fraction": 0.4482321548, "num_tokens": 3281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.01771230116637158, "lm_q1q2_score": 0.006949188094579403}}
{"text": "// [[Rcpp::depends(BH)]]\n// [[Rcpp::depends(RcppEigen)]]\n\n#include \"distribution.h\"\n#include <boost/math/distributions/logistic.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/cauchy.hpp>\n#include <boost/math/distributions/extreme_value.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\n\nusing namespace boost::math;\nusing namespace std;\nusing namespace Rcpp ;\n\ndistribution::distribution(void) {\n  // Rcout << \"Distribution is being created\" << endl;\n}\n\nstd::string distribution::concatenate(std::string x, std::string level)\n{\n  return (x + \" \" +level);\n}\n\n// ORDINAL DATA SELECTION\n\nDataFrame my_transpose(DataFrame dat_in){\n  Environment base_base(\"package:base\");\n  Function my_transpose1 = base_base[\"t\"];\n  DataFrame data_out = my_transpose1(dat_in);\n  return data_out;\n}\n\nNumericMatrix to_dummy1(NumericVector A, CharacterVector levels)\n{\n  NumericVector cha_to_fact = A;\n  CharacterVector levs1 = levels;\n  int var_lev = levs1.length();\n\n  // Rcout << var_lev << std::endl;\n\n  NumericMatrix B_Ma(cha_to_fact.length(), var_lev);\n  for (int i_1 = 0; i_1 < cha_to_fact.length(); ++i_1){\n    int col_ind = cha_to_fact[i_1] - 1;\n    B_Ma(i_1, col_ind) = 1;\n  }\n\n  // print(B_Ma);\n\n  B_Ma = B_Ma( _ , Range(0,var_lev-2) );\n\n  // if (var_lev != 2){\n  //   B_Ma = B_Ma( _ , Range(0,var_lev-2) );\n  // } else {\n  //   B_Ma = B_Ma( _ , Range(1,var_lev-1) );\n  // }\n  return B_Ma;\n}\n\nList Model_Matrix_or(DataFrame data, Formula formula) {\n  Environment stats_env(\"package:stats\");\n  Function model_frame = stats_env[\"model.frame\"];\n  Function model_matrix = stats_env[\"model.matrix\"];\n  DataFrame df_new1 = model_frame(Rcpp::_[\"formula\"] = formula, _[\"data\"] = data);\n  SEXP Response = df_new1[0];\n  NumericMatrix df_new = model_matrix(df_new1, _[\"data\"] = data);\n\n  return List::create(\n    Named(\"df_new\") = df_new,\n    Named(\"Response\") = Response\n  );\n\n}\n\n\nList Cat_ref_order(CharacterVector categories_order, SEXP response_categories){\n  // Environment base_env(\"package:base\");\n  // Function my_unique = base_env[\"unique\"];\n\n  CharacterVector response_categories1 = response_categories;\n  // CharacterVector levels = my_unique(response_categories1);\n\n  IntegerVector num_categories_order = seq_len(categories_order.length());\n\n  DataFrame response_neworder = DataFrame::create(  _[\"num_categories_order\"] = num_categories_order );\n\n  response_neworder = my_transpose(response_neworder);\n  response_neworder.names() = categories_order;\n\n  String a1;\n  CharacterVector a2;\n  for(int i = 0; i <response_categories1.length(); i++){\n    a1 = response_categories1[i];\n    a2 = response_neworder[a1];\n    response_categories1[i] = a2[0];\n  }\n\n  // print(response_categories1);\n\n  return List::create(\n    Named(\"response_neworder\") = response_neworder,\n    Named(\"response_categories2\") = response_categories1,\n    Named(\"levels\") = categories_order\n  );\n}\n\n\n\nList distribution::All_pre_data_or(Formula formula, DataFrame input_data,\n                                   CharacterVector categories_order,\n                                   CharacterVector proportional_effect,\n                                   std::string threshold){\n\n  Environment base_env(\"package:base\");\n  Function my_asnumeric = base_env[\"as.numeric\"];\n  Function my_cbind = base_env[\"cbind\"];\n  Function my_order = base_env[\"order\"];\n\n  List M_matrix = Model_Matrix_or(input_data, formula);\n  List Cat_ref_or_L = Cat_ref_order(categories_order, M_matrix[\"Response\"]);\n  NumericMatrix Design = M_matrix[\"df_new\"];\n\n  CharacterVector a1 = Cat_ref_or_L[\"response_categories2\"];\n\n  NumericVector Num_res = my_asnumeric(a1);\n\n  Design = my_cbind(Num_res, Design);\n\n  // Now order dataset with respect to the repsonse variables in the given order\n  DataFrame df_tans = my_transpose(Design);\n  DataFrame df_tans_2 = Design ;\n  NumericVector order_var_sel = my_order(df_tans_2[0]);\n  order_var_sel = order_var_sel - 1 ;\n  df_tans = df_tans[order_var_sel];\n\n  df_tans_2 = my_transpose(df_tans);\n\n  CharacterVector Levels = Cat_ref_or_L[\"levels\"];\n\n\n  int N_cats = Levels.length();\n\n  LogicalVector any_alternative_specific = !is_na(proportional_effect); // TRUE IF THERE ARE\n  CharacterVector colnames_final_m = df_tans_2.names();\n\n  NumericVector x(colnames_final_m.length());\n  if (any_alternative_specific[0]) {\n    // x(colnames_final_m.length());\n    for(int indi = 0 ; indi < proportional_effect.length(); indi++){\n      String var_1 = proportional_effect[indi];\n      int indi_var = df_tans_2.findName(var_1);\n      x[indi_var] = indi_var;\n    }\n    colnames_final_m = colnames_final_m[x==0]; // Case where there no proportional effects\n  }\n\n  // Now extend\n  // Y EXTEND\n  NumericVector Response = df_tans_2[0];\n  NumericMatrix Response_EXT = to_dummy1(Response, Levels);\n\n  // X EXTEND\n\n  // X COMPLETE\n\n  DataFrame DF_complete_effect = df_tans_2[colnames_final_m];\n  NumericMatrix Pre_Design1 = internal::convert_using_rfunction(DF_complete_effect, \"as.matrix\");\n  Eigen::Map<Eigen::MatrixXd> Pre_Design = as<Eigen::Map<Eigen::MatrixXd> >(Pre_Design1);\n  Eigen::MatrixXd Iden_Q1 = Eigen::MatrixXd::Identity(N_cats-1,N_cats-1);\n\n  Eigen::MatrixXd X_EXT_COMPLETE;\n\n  if (threshold == \"equidistant\"){ // eRASE THE LAST TWO COLUMNS ONE CORRESPONDING TO DR AND OTHER TO THE INTERCEPT\n    X_EXT_COMPLETE = Eigen::kroneckerProduct(Pre_Design.rightCols(DF_complete_effect.cols() - 2), Iden_Q1).eval();\n    colnames_final_m.erase(0);\n    colnames_final_m.erase(0);\n  } else {\n    X_EXT_COMPLETE = Eigen::kroneckerProduct(Pre_Design.rightCols(DF_complete_effect.cols() - 1), Iden_Q1).eval();\n    colnames_final_m.erase(0);\n  }\n\n  Eigen::MatrixXd Design_Matrix;\n\n  if (any_alternative_specific[0]) {\n\n    // PONER ESA PARTE ACA\n\n    DataFrame DF_proportional_effect = df_tans_2[proportional_effect];\n    NumericMatrix Pre_DF_proportional1 = internal::convert_using_rfunction(DF_proportional_effect, \"as.matrix\");\n    Eigen::Map<Eigen::MatrixXd> Pre_DF_proportional2 = as<Eigen::Map<Eigen::MatrixXd> >(Pre_DF_proportional1);\n\n    Eigen::MatrixXd Pre_DF_proportional = Pre_DF_proportional2;\n\n    Eigen::VectorXd Ones = Eigen::VectorXd::Ones(N_cats-1);\n    Eigen::MatrixXd X_EXT_PROPORTIONAL = Eigen::kroneckerProduct(Pre_DF_proportional, Ones).eval();\n\n    // TENGO QUE PONER EL IF ACA\n\n    if (threshold == \"equidistant\"){\n      NumericMatrix tJac = my_cbind(1, seq_len(categories_order.length() -1 )-1 );\n      Eigen::Map<Eigen::MatrixXd> tJac2 = as<Eigen::Map<Eigen::MatrixXd> >(tJac);\n      Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(Response_EXT.rows());\n      Eigen::MatrixXd Threshold_M = Eigen::kroneckerProduct(Ones1, tJac2).eval();\n      X_EXT_PROPORTIONAL.conservativeResize(X_EXT_PROPORTIONAL.rows(),X_EXT_PROPORTIONAL.cols()+2);\n      X_EXT_PROPORTIONAL.block(0,X_EXT_PROPORTIONAL.cols()-2, X_EXT_PROPORTIONAL.rows(),2) = Threshold_M;\n    }\n\n\n    Design_Matrix.conservativeResize(X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()+X_EXT_PROPORTIONAL.cols());\n    Design_Matrix.block(0,0,X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()) = X_EXT_COMPLETE;\n    Design_Matrix.block(0,X_EXT_COMPLETE.cols(),X_EXT_COMPLETE.rows(),X_EXT_PROPORTIONAL.cols()) = X_EXT_PROPORTIONAL;\n\n  }else{Design_Matrix = X_EXT_COMPLETE;}\n\n\n\n  return List::create(\n    Named(\"Design_Matrix\") = Design_Matrix,\n    Named(\"Response_EXT\") = Response_EXT,\n    Named(\"Levels\") = Levels,\n    Named(\"Complete_effects\") = colnames_final_m,\n    Named(\"N_cats\") = N_cats\n  );\n}\n\n\n\n\n// [[Rcpp::export]]\nList All_pre_data_or2(Formula formula, DataFrame input_data,\n                      CharacterVector categories_order,\n                      CharacterVector proportional_effect){\n\n  Environment base_env(\"package:base\");\n  Function my_asnumeric = base_env[\"as.numeric\"];\n  Function my_cbind = base_env[\"cbind\"];\n  Function my_order = base_env[\"order\"];\n\n  List M_matrix = Model_Matrix_or(input_data, formula);\n  List Cat_ref_or_L = Cat_ref_order(categories_order, M_matrix[\"Response\"]);\n  NumericMatrix Design = M_matrix[\"df_new\"];\n\n  CharacterVector a1 = Cat_ref_or_L[\"response_categories2\"];\n  NumericVector Num_res = my_asnumeric(a1);\n\n  Design = my_cbind(Num_res, Design);\n\n  // Now order dataset with respect to the repsonse variables in the given order\n  DataFrame df_tans = my_transpose(Design);\n  DataFrame df_tans_2 = Design ;\n  NumericVector order_var_sel = my_order(df_tans_2[0]);\n  order_var_sel = order_var_sel - 1 ;\n  df_tans = df_tans[order_var_sel];\n\n  df_tans_2 = my_transpose(df_tans);\n\n  CharacterVector Levels = Cat_ref_or_L[\"levels\"];\n  int N_cats = Levels.length();\n\n  LogicalVector any_alternative_specific = !is_na(proportional_effect); // TRUE IF THERE ARE\n  CharacterVector colnames_final_m = df_tans_2.names();\n\n  NumericVector x(colnames_final_m.length());\n  if (any_alternative_specific[0]) {\n    // x(colnames_final_m.length());\n    for(int indi = 0 ; indi < proportional_effect.length(); indi++){\n      String var_1 = proportional_effect[indi];\n      int indi_var = df_tans_2.findName(var_1);\n      x[indi_var] = indi_var;\n    }\n    colnames_final_m = colnames_final_m[x==0]; // Case where there no proportional effects\n  }\n\n  // Now extend\n\n  // X COMPLETE\n  DataFrame DF_complete_effect = df_tans_2[colnames_final_m];\n  NumericMatrix Pre_Design1 = internal::convert_using_rfunction(DF_complete_effect, \"as.matrix\");\n  Eigen::Map<Eigen::MatrixXd> Pre_Design = as<Eigen::Map<Eigen::MatrixXd> >(Pre_Design1);\n  Eigen::MatrixXd Iden_Q1 = Eigen::MatrixXd::Identity(N_cats-1,N_cats-1);\n  Eigen::MatrixXd X_EXT_COMPLETE = Eigen::kroneckerProduct(Pre_Design.rightCols(DF_complete_effect.cols() - 1), Iden_Q1).eval();\n\n  // X PROPOTIONAL\n\n  Eigen::MatrixXd Design_Matrix;\n\n  // Y EXTEND\n  NumericVector Response = df_tans_2[0];\n  NumericMatrix Response_EXT = to_dummy1(Response, Levels);\n\n  NumericMatrix tJac = my_cbind(1, seq_len(categories_order.length() -1 )-1 );\n  Rcout << tJac << endl;\n\n  NumericMatrix Response_EXT1 = internal::convert_using_rfunction(Response_EXT, \"as.matrix\");\n  NumericMatrix tJac1 = internal::convert_using_rfunction(tJac, \"as.matrix\");\n\n  Eigen::Map<Eigen::MatrixXd> Response_EXT2 = as<Eigen::Map<Eigen::MatrixXd> >(Response_EXT1);\n  Eigen::Map<Eigen::MatrixXd> tJac2 = as<Eigen::Map<Eigen::MatrixXd> >(tJac1);\n\n\n  // Eigen::MatrixXd MAR = Response_EXT2 * tJac2;\n\n  Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(Response_EXT2.rows());\n  Eigen::MatrixXd MAR = Eigen::kroneckerProduct(Ones1, tJac2).eval();\n\n\n  if (any_alternative_specific[0]) {\n\n    DataFrame DF_proportional_effect = df_tans_2[proportional_effect];\n    NumericMatrix Pre_DF_proportional1 = internal::convert_using_rfunction(DF_proportional_effect, \"as.matrix\");\n    Eigen::Map<Eigen::MatrixXd> Pre_DF_proportional2 = as<Eigen::Map<Eigen::MatrixXd> >(Pre_DF_proportional1);\n\n    Eigen::MatrixXd Pre_DF_proportional = Pre_DF_proportional2;\n\n    // Pre_DF_proportional.conservativeResize(Pre_DF_proportional.rows(),Pre_DF_proportional.cols()+2);\n    // Pre_DF_proportional.block(0,Pre_DF_proportional2.cols(),Pre_DF_proportional.rows(),2) = MAR;\n\n\n    Eigen::VectorXd Ones = Eigen::VectorXd::Ones(N_cats-1);\n    Eigen::MatrixXd X_EXT_PROPORTIONAL = Eigen::kroneckerProduct(Pre_DF_proportional, Ones).eval();\n\n    X_EXT_PROPORTIONAL.conservativeResize(X_EXT_PROPORTIONAL.rows(),X_EXT_PROPORTIONAL.cols()+2);\n    X_EXT_PROPORTIONAL.block(0,X_EXT_PROPORTIONAL.cols()-2,X_EXT_PROPORTIONAL.rows(),2) = MAR;\n\n    Design_Matrix.conservativeResize(X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()+X_EXT_PROPORTIONAL.cols());\n    Design_Matrix.block(0,0,X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()) = X_EXT_COMPLETE;\n    Design_Matrix.block(0,X_EXT_COMPLETE.cols(),X_EXT_COMPLETE.rows(),X_EXT_PROPORTIONAL.cols()) = X_EXT_PROPORTIONAL;\n\n  }else{Design_Matrix = X_EXT_COMPLETE;}\n\n\n\n  colnames_final_m.erase(0);\n\n  return List::create(\n    Named(\"Design_Matrix\") = Design_Matrix,\n    Named(\"Response_EXT\") = Response_EXT,\n    Named(\"Levels\") = Levels,\n    Named(\"Complete_effects\") = colnames_final_m,\n    Named(\"MAR2\") = MAR,\n    Named(\"N_cats\") = N_cats\n  );\n}\n\n\nList distribution::All_pre_data_NEWDATA(Formula formula,\n                                        DataFrame NEWDATA,\n                                        CharacterVector categories_order,\n                                        CharacterVector proportional_effect,\n                                        int N_cats){\n\n  Environment base_env(\"package:base\");\n  Function my_asnumeric = base_env[\"as.numeric\"];\n  Function my_cbind = base_env[\"cbind\"];\n  Function my_order = base_env[\"order\"];\n\n  List M_matrix = Model_Matrix_or(NEWDATA, formula);\n  // List Cat_ref_or_L = Cat_ref_order(categories_order, M_matrix[\"Response\"]);\n  NumericMatrix Design = M_matrix[\"df_new\"];\n\n  // CharacterVector a1 = Cat_ref_or_L[\"response_categories2\"];\n  // NumericVector Num_res = my_asnumeric(a1);\n  //\n  // Design = my_cbind(Num_res, Design);\n\n  // Now order dataset with respect to the repsonse variables in the given order\n  // DataFrame df_tans = my_transpose(Design);\n  DataFrame df_tans_2 = Design ;\n\n\n  // NumericVector order_var_sel = my_order(df_tans_2[0]);\n  // order_var_sel = order_var_sel - 1 ;\n  // df_tans = df_tans[order_var_sel];\n\n  // df_tans_2 = my_transpose(df_tans);\n\n  // CharacterVector Levels = Cat_ref_or_L[\"levels\"];\n  // int N_cats = Levels.length();\n\n  LogicalVector any_alternative_specific = !is_na(proportional_effect); // TRUE IF THERE ARE\n  CharacterVector colnames_final_m = df_tans_2.names();\n\n\n  NumericVector x(colnames_final_m.length());\n  if (any_alternative_specific[0]) {\n    // x(colnames_final_m.length());\n    for(int indi = 0 ; indi < proportional_effect.length(); indi++){\n      String var_1 = proportional_effect[indi];\n      int indi_var = df_tans_2.findName(var_1);\n      x[indi_var] = indi_var;\n    }\n    colnames_final_m = colnames_final_m[x==0]; // Case where there no proportional effects\n  }\n\n\n  // X EXTEND\n\n  // X COMPLETE\n\n  DataFrame DF_complete_effect = df_tans_2[colnames_final_m];\n\n  NumericMatrix Pre_Design1 = internal::convert_using_rfunction(DF_complete_effect, \"as.matrix\");\n  Eigen::Map<Eigen::MatrixXd> Pre_Design = as<Eigen::Map<Eigen::MatrixXd> >(Pre_Design1);\n  Eigen::MatrixXd Iden_Q1 = Eigen::MatrixXd::Identity(N_cats-1,N_cats-1);\n\n  Eigen::MatrixXd X_EXT_COMPLETE;\n\n  // if (threshold == \"equidistant\"){ // eRASE THE LAST TWO COLUMNS ONE CORRESPONDING TO DR AND OTHER TO THE INTERCEPT\n  //   X_EXT_COMPLETE = Eigen::kroneckerProduct(Pre_Design.rightCols(DF_complete_effect.cols() - 2), Iden_Q1).eval();\n  //   colnames_final_m.erase(0);\n  //   colnames_final_m.erase(0);\n  // } else {\n  X_EXT_COMPLETE = Eigen::kroneckerProduct(Pre_Design, Iden_Q1).eval();\n\n\n  // colnames_final_m.erase(0);\n  // }\n\n  Eigen::MatrixXd Design_Matrix;\n\n  if (any_alternative_specific[0]) {\n\n    // PONER ESA PARTE ACA\n\n    DataFrame DF_proportional_effect = df_tans_2[proportional_effect];\n    NumericMatrix Pre_DF_proportional1 = internal::convert_using_rfunction(DF_proportional_effect, \"as.matrix\");\n    Eigen::Map<Eigen::MatrixXd> Pre_DF_proportional2 = as<Eigen::Map<Eigen::MatrixXd> >(Pre_DF_proportional1);\n\n    Eigen::MatrixXd Pre_DF_proportional = Pre_DF_proportional2;\n\n    Eigen::VectorXd Ones = Eigen::VectorXd::Ones(N_cats-1);\n    Eigen::MatrixXd X_EXT_PROPORTIONAL = Eigen::kroneckerProduct(Pre_DF_proportional, Ones).eval();\n\n    // TENGO QUE PONER EL IF ACA\n    //\n    // if (threshold == \"equidistant\"){\n    //   NumericMatrix tJac = my_cbind(1, seq_len(categories_order.length() -1 )-1 );\n    //   Eigen::Map<Eigen::MatrixXd> tJac2 = as<Eigen::Map<Eigen::MatrixXd> >(tJac);\n    //   Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(Response_EXT.rows());\n    //   Eigen::MatrixXd Threshold_M = Eigen::kroneckerProduct(Ones1, tJac2).eval();\n    //   X_EXT_PROPORTIONAL.conservativeResize(X_EXT_PROPORTIONAL.rows(),X_EXT_PROPORTIONAL.cols()+2);\n    //   X_EXT_PROPORTIONAL.block(0,X_EXT_PROPORTIONAL.cols()-2, X_EXT_PROPORTIONAL.rows(),2) = Threshold_M;\n    // }\n\n\n    Design_Matrix.conservativeResize(X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()+X_EXT_PROPORTIONAL.cols());\n    Design_Matrix.block(0,0,X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()) = X_EXT_COMPLETE;\n    Design_Matrix.block(0,X_EXT_COMPLETE.cols(),X_EXT_COMPLETE.rows(),X_EXT_PROPORTIONAL.cols()) = X_EXT_PROPORTIONAL;\n\n  }else{Design_Matrix = X_EXT_COMPLETE;}\n\n  // Now extend\n\n\n  // // X COMPLETE\n  // DataFrame DF_complete_effect = df_tans_2[colnames_final_m];\n  // NumericMatrix Pre_Design1 = internal::convert_using_rfunction(DF_complete_effect, \"as.matrix\");\n  // Eigen::Map<Eigen::MatrixXd> Pre_Design = as<Eigen::Map<Eigen::MatrixXd> >(Pre_Design1);\n  // // print(colnames_final_m);\n  // Eigen::MatrixXd Iden_Q1 = Eigen::MatrixXd::Identity(N_cats-1,N_cats-1);\n  //\n  // Eigen::MatrixXd X_EXT_COMPLETE = Eigen::kroneckerProduct(Pre_Design.rightCols(DF_complete_effect.cols() - 1), Iden_Q1).eval();\n  //\n  // // X PROPOTIONAL\n  //\n  // Eigen::MatrixXd Design_Matrix;\n  //\n  // if (any_alternative_specific[0]) {\n  //\n  //   DataFrame DF_proportional_effect = df_tans_2[proportional_effect];\n  //   NumericMatrix Pre_DF_proportional1 = internal::convert_using_rfunction(DF_proportional_effect, \"as.matrix\");\n  //   Eigen::Map<Eigen::MatrixXd> Pre_DF_proportional = as<Eigen::Map<Eigen::MatrixXd> >(Pre_DF_proportional1);\n  //   Eigen::VectorXd Ones = Eigen::VectorXd::Ones(N_cats-1);\n  //   Eigen::MatrixXd X_EXT_PROPORTIONAL = Eigen::kroneckerProduct(Pre_DF_proportional, Ones).eval();\n  //\n  //   Design_Matrix.conservativeResize(X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()+X_EXT_PROPORTIONAL.cols());\n  //   Design_Matrix.block(0,0,X_EXT_COMPLETE.rows(),X_EXT_COMPLETE.cols()) = X_EXT_COMPLETE;\n  //   Design_Matrix.block(0,X_EXT_COMPLETE.cols(),X_EXT_COMPLETE.rows(),X_EXT_PROPORTIONAL.cols()) = X_EXT_PROPORTIONAL;\n  //\n  // }else{Design_Matrix = X_EXT_COMPLETE;}\n\n  return List::create(\n    Named(\"Design\") = Design,\n    Named(\"Design_Matrix\") = Design_Matrix\n  );\n}\n\n\nCharacterVector Var_Not_In(DataFrame final_matrix, CharacterVector alternative_specific){\n\n  LogicalVector any_alternative_specific = !is_na(alternative_specific);\n\n  CharacterVector colnames_final_m = final_matrix.names();\n\n  if (any_alternative_specific[0]) {\n    NumericVector x(colnames_final_m.length());\n    for(int indi = 0 ; indi < alternative_specific.length(); indi++){\n      String var_1 = alternative_specific[indi];\n      int indi_var = final_matrix.findName(var_1);\n      x[indi_var] = indi_var;\n    }\n    colnames_final_m = colnames_final_m[x==0]; // Case where there no alternative specific variables\n  }\n  colnames_final_m.erase(0, 4); // Eliminate the first 4 information variables\n\n  return colnames_final_m;\n}\n\nList formula_entry(Formula formula1){\n  Environment base_base(\"package:base\");\n  Function my_strsplit = base_base[\"strsplit\"];\n  Function my_format = base_base[\"format\"];\n  Function my_paste = base_base[\"paste\"];\n  Function my_sub = base_base[\"sub\"];\n  Function my_rev = base_base[\"rev\"];\n  Function my_trimws = base_base[\"trimws\"];\n\n  Environment base_stats(\"package:stats\");\n  Function my_as_formula = base_stats[\"as.formula\"];\n\n  CharacterVector st1 = my_format(formula1);\n  String str_for = my_paste(st1,  _[\"collapse\"] = \"\");\n  List list1 = (my_strsplit(str_for, \"~\"));\n  CharacterVector vars = list1[0];\n  String vars_string = vars[1];\n  String res1 = vars[0];\n  String res = my_trimws(res1);\n  List list_vars = my_strsplit(vars_string, \"[+]\");\n  CharacterVector char_vars = list_vars(0);\n\n  String vars_for = my_paste(my_sub(\"\\\\[[^()]*\\\\]\", \"\", char_vars),  _[\"collapse\"] = \" + \");\n  CharacterVector form = my_paste(res, vars_for, _[\"sep\"] = \"~\");\n  Formula formula2 = my_as_formula(form);\n\n  String firs_col;\n  List list_no_spaces, list_var_rev, list_cat_rev;\n  StringVector Vars(char_vars.length()), Alternatives(char_vars.length());\n\n  for (int i = 0; i < char_vars.length() ; i++) {\n    firs_col = char_vars[i];\n    String no_spaces = my_trimws(firs_col);\n    list_no_spaces = my_strsplit(no_spaces, \"\");\n    String rev_string = my_paste(my_rev(list_no_spaces[0]), _[\"collapse\"] = \"\");\n\n    String var = my_sub(\".*\\\\[\", \"\", rev_string);\n    list_var_rev = my_strsplit(var, \"\");\n    String var1 = my_paste(my_rev(list_var_rev[0]), _[\"collapse\"] = \"\");\n\n    String cat = my_sub(\".*\\\\]\", \"\", my_sub(\"\\\\[.*\", \"\", rev_string));\n    list_cat_rev = my_strsplit(cat, \"\");\n    String cat1 = my_paste(my_rev(list_cat_rev[0]), _[\"collapse\"] = \"\");\n\n    if (var1 != cat1){ Alternatives[i] = cat1; }\n    if (var1 == \"1\"){ var1 = \"(Intercept)\"; }\n    Vars[i] = var1;\n  }\n\n  DataFrame Var_alt = DataFrame::create(Named(\"Alternatives\") = Alternatives);\n  Var_alt = my_transpose(Var_alt);\n  Var_alt.names() = Vars;\n\n  DataFrame Var_alt1 = Var_alt;\n\n  return List::create(\n    Named(\"Var_alt\") = Var_alt,\n    Named(\"Response\") = res,\n    Named(\"formula_model\") = formula2\n  );\n}\n\nNumericVector Cat_ref(CharacterVector alternatives, String Ref_cat){\n  NumericVector Ref_vec(alternatives.length());\n  for (int i = 0; i < alternatives.length(); i++){\n    if(alternatives(i) == Ref_cat){\n      Ref_vec(i) = 1;\n    }else{Ref_vec(i) = 0;}\n  }\n  return Ref_vec;\n}\n\nDataFrame Sort_DataFrame(DataFrame ModelMatrix,\n                         DataFrame InputData,\n                         CharacterVector names,\n                         String Choice_vec,\n                         String Ref_cat) {\n  // Order DATAFRAME ACCORDING TO VARIABLES GIVEN IN VECTOR NAMES\n  // CBIND OF DATA SETS AND THEN ORDER ACCORDING TO VARIABLES\n  Environment base_env(\"package:base\");\n  Function my_order = base_env[\"order\"];\n  Function my_cbind = base_env[\"cbind\"];\n  Function my_asnumeric = base_env[\"as.numeric\"];\n\n  String alt = names[0];\n  String id_case_0 = names[2];\n\n  NumericVector Cat_ref_vec = Cat_ref(InputData[alt], Ref_cat);\n\n  DataFrame A2 = my_cbind( _[\"alternatives\"] = InputData[alt],\n                           _[\"Cat_ref_vec\"] = Cat_ref_vec,\n                           _[\"id_case\"] = InputData[id_case_0],\n                                                   _[\"choice\"] = my_asnumeric(InputData[Choice_vec]),\n                                                   ModelMatrix);\n\n  CharacterVector names1 = {\"alternatives\", \"Cat_ref_vec\", \"id_case\"};\n\n  DataFrame df_tans = my_transpose(A2);\n  DataFrame df_tans_2 = A2 ;\n\n  for (int i = 0; i < names1.length() ; i++) {\n    String var = names1(i);\n    NumericVector order_var_sel = my_order(df_tans_2[var]);\n    order_var_sel = order_var_sel - 1 ;\n    df_tans = df_tans[order_var_sel];\n    df_tans_2 = my_transpose(df_tans);\n  }\n  return  df_tans_2;\n}\n\n\nDataFrame my_AsNumericMatrix(DataFrame dat_in){\n  Environment base_env(\"package:base\");\n  Function my_asnumeric = base_env[\"as.numeric\"];\n  Function my_ascharacter = base_env[\"as.character\"];\n  Function my_cbind = base_env[\"cbind\"];\n  DataFrame data_out = dat_in ;\n\n  for (int i = 4; i < dat_in.length() ; i++) {\n    NumericVector vec = my_asnumeric(my_ascharacter(dat_in[i]));\n    data_out[i] = vec;\n  }\n  return data_out;\n}\n\nNumericMatrix Model_Matrix(DataFrame data, Formula formula) {\n  Environment stats_env(\"package:stats\");\n  Function model_frame = stats_env[\"model.frame\"];\n  Function model_matrix = stats_env[\"model.matrix\"];\n  DataFrame df_new1 = model_frame(Rcpp::_[\"formula\"] = formula, _[\"data\"] = data);\n  NumericMatrix df_new = model_matrix(df_new1, _[\"data\"] = data);\n  return  df_new;\n}\n\nDataFrame All_pre_data(Formula formula, DataFrame input_data, CharacterVector var_informatives, String choice, String Ref_cat){\n  DataFrame data_output = my_AsNumericMatrix(Sort_DataFrame(\n    Model_Matrix(input_data,\n                 formula_entry(formula)[\"formula_model\"]),\n                 input_data,\n                 var_informatives,\n                 choice,\n                 Ref_cat));\n  return data_output;\n}\n\nEigen::MatrixXd Extend_alt_specific(DataFrame alt_specific, int N_cats, int N_ind, CharacterVector var_alt_specific){\n  // cat_index = 1;\n\n  Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(N_cats-1);\n  Eigen::MatrixXd Iden_Q = Eigen::MatrixXd::Identity(N_cats,N_cats);\n  Iden_Q.conservativeResize(Iden_Q.rows() - 1, Iden_Q.cols());\n  Iden_Q.col(N_cats-1) = -Ones1;\n  NumericMatrix alt_specific_num = internal::convert_using_rfunction(alt_specific[var_alt_specific], \"as.matrix\");\n  Eigen::Map<Eigen::MatrixXd> M_alt_specific = as<Eigen::Map<Eigen::MatrixXd> >(alt_specific_num);\n  Eigen::MatrixXd Matrix_trans((N_cats-1)*N_ind,var_alt_specific.length());\n  for(int indi = 1 ; indi <= N_ind ; indi++)\n  {\n    Eigen::MatrixXd Block_ind =  M_alt_specific.block((indi-1) * N_cats, 0, N_cats, var_alt_specific.length());\n    Eigen::MatrixXd Block_RES = Block_ind.transpose() * Iden_Q.transpose();\n    Matrix_trans.block((indi-1) * (N_cats-1), 0, N_cats-1, var_alt_specific.length()) = Block_RES.transpose();\n  }\n\n  return Matrix_trans;\n}\n\nEigen::MatrixXd Extend_case_specific(DataFrame case_specific, int N_cats, int N_ind,\n                                     CharacterVector var_alt_specific,  DataFrame Var_alt){\n\n  CharacterVector var_case_specific = Var_Not_In(case_specific, var_alt_specific);\n  DataFrame effect_specific_for1 = Var_alt[var_case_specific];\n  effect_specific_for1 = my_transpose(effect_specific_for1);\n  CharacterVector effect_specific_for2 = effect_specific_for1[0];\n\n  Eigen::MatrixXd Iden_Q1 = Eigen::MatrixXd::Identity(N_cats-1,N_cats-1);\n  NumericMatrix case_specific_num = internal::convert_using_rfunction(case_specific[var_case_specific], \"as.matrix\");\n  Eigen::Map<Eigen::MatrixXd> M_case_specific = as<Eigen::Map<Eigen::MatrixXd> >(case_specific_num);\n\n  Eigen::MatrixXd Matrix_trans((N_cats-1)*N_ind,(N_cats-1)*var_case_specific.length());\n\n  for(int indi = 1 ; indi <= N_ind ; indi++)\n  {\n    Eigen::MatrixXd Block_ind =  M_case_specific.block((indi-1) * N_cats, 0, 1, var_case_specific.length());\n    Eigen::MatrixXd Block_RES = Eigen::kroneckerProduct(Block_ind, Iden_Q1).eval();\n    Matrix_trans.block((indi-1) * (N_cats-1), 0, N_cats-1, (N_cats-1)*var_case_specific.length()) = Block_RES;\n  }\n  // Rcout << Matrix_trans << std::endl;\n  // Create vector relation between category and order in dataset\n  CharacterVector ordered_cat = case_specific[\"alternatives\"];\n  String cat_1 = ordered_cat[0];\n  NumericVector cat_index = NumericVector::create(Named(cat_1 , 0));\n\n  for(int j_1 = 1; j_1 < N_cats ; j_1++){\n    cat_1 = ordered_cat[j_1];\n    cat_index.push_back(j_1, cat_1);\n  }\n  int count_re_var = 0;\n  for(int ind_b_var = 0; ind_b_var < var_case_specific.length() ; ind_b_var++){\n\n    Eigen::MatrixXd Block_cat = Matrix_trans.block(0,ind_b_var*(N_cats-1),Matrix_trans.rows(), N_cats-1);\n\n    if( effect_specific_for2[ind_b_var] != \"\" ){\n      String cat_loop = effect_specific_for2[ind_b_var];\n      int Var_to_keep = cat_index[cat_loop];\n      Matrix_trans.block(0,count_re_var,Matrix_trans.rows(), 1) = Block_cat.block(0, Var_to_keep, Matrix_trans.rows(),1);\n      count_re_var = count_re_var+1;\n\n    }else{\n\n      Matrix_trans.block(0,count_re_var,Matrix_trans.rows(), N_cats-1) = Block_cat;\n      count_re_var = count_re_var+N_cats-1;\n\n    }\n  }\n  Eigen::MatrixXd Matrix_trans1 = Matrix_trans.block(0,0,Matrix_trans.rows(), count_re_var);\n  return Matrix_trans1;\n}\n\nEigen::MatrixXd Extend_All_design(DataFrame Final_mat, DataFrame Var_alt, CharacterVector var_alt_specific,\n                                  int N_ind, int N_cats){\n\n  LogicalVector any_alternative_specific = !is_na(var_alt_specific); // TRUE IF ANY\n\n  CharacterVector var_case_specific = Var_Not_In(Final_mat, var_alt_specific);\n  Eigen::MatrixXd Ex_case_M = Extend_case_specific(Final_mat, N_cats, N_ind, var_alt_specific, Var_alt );\n\n  Eigen::MatrixXd Design_Matrix;\n\n  if (any_alternative_specific[0]) {\n    Eigen::MatrixXd Ex_alt_M = Extend_alt_specific(Final_mat, N_cats, N_ind, var_alt_specific);\n    int rows_t = Ex_case_M.rows();\n    Design_Matrix.conservativeResize(rows_t,Ex_case_M.cols()+Ex_alt_M.cols());\n    Design_Matrix.block(0,0,rows_t,Ex_case_M.cols()) = Ex_case_M;\n    Design_Matrix.block(0,Ex_case_M.cols(),rows_t,Ex_alt_M.cols()) = Ex_alt_M;\n  }else{Design_Matrix = Ex_case_M;}\n\n  return Design_Matrix;\n}\n\nList Extend_Response(DataFrame Final_mat ){\n\n  Environment base_env(\"package:base\");\n  Function my_unique = base_env[\"unique\"];\n  Function my_length = base_env[\"length\"];\n  Function my_matrix = base_env[\"matrix\"];\n  Function my_asnumeric = base_env[\"as.numeric\"];\n\n  SEXP N_cat_1 = my_length(my_unique(Final_mat[\"alternatives\"]));\n  int N_cat = Rcpp::as<int>(N_cat_1);\n\n  NumericVector y11 = my_asnumeric(Final_mat[\"choice\"]) ;\n  DataFrame Y_Ext = my_transpose(my_matrix(y11 ,  _[\"nrow\"] = N_cat));\n  NumericMatrix Y_Ext1 = internal::convert_using_rfunction(Y_Ext, \"as.matrix\");\n\n  Eigen::MatrixXd Y_n2 = as<Eigen::Map<Eigen::MatrixXd> >(Y_Ext1-1);\n  Y_n2.conservativeResize(Y_n2.rows(), Y_n2.cols() - 1);\n\n  return List::create(\n    Named(\"N_cat\") = N_cat,\n    Named(\"Y_Ext\") = Y_n2\n  );\n}\n\nList distribution::select_data_nested(Formula formula,\n                                      String individuals,\n                                      String Alternatives,\n                                      SEXP ref_cat,\n                                      CharacterVector var_alt_specific,\n                                      DataFrame input_data\n) {\n\n  List Formula_l = formula_entry(formula);\n  SEXP Var_spe_alt1 = Formula_l[\"Var_alt\"];\n  String Response = Formula_l[\"Response\"];\n  DataFrame Var_spe_alt = Rcpp::as<DataFrame>(Var_spe_alt1);\n\n  CharacterVector var_informatives = {\"Alternatives\", \"Cat_ref_vec\", \"individuals\"};\n  var_informatives[0] = Alternatives;\n  var_informatives[2] = individuals;\n\n  DataFrame Final_mat1 = All_pre_data(Formula_l[\"formula_model\"],\n                                      input_data,\n                                      var_informatives,\n                                      Response,\n                                      ref_cat);\n\n  List Response_L = Extend_Response(Final_mat1);\n  Eigen::MatrixXd Response_M = Response_L[\"Y_Ext\"];\n\n  Eigen::MatrixXd Design_Matrix = Extend_All_design(Final_mat1,\n                                                    Var_spe_alt,\n                                                    var_alt_specific,\n                                                    Response_M.rows(),\n                                                    Response_L[\"N_cat\"]);\n\n\n  return List::create(\n    _[\"Design_Matrix\"] = Design_Matrix,\n    _[\"Response_M\"] = Response_M\n  );\n}\n\nEigen::VectorXd Logistic::in_open_corner(const Eigen::VectorXd& p) const\n{\n  Eigen::VectorXd pi = p;\n  int J = pi.size() + 1;\n  for(int j=0; j<J-1; ++j)\n  { pi[j] = std::max(_epsilon_0, std::min(pi[j], 1-_epsilon_1)); }\n  double sum = pi.sum();\n  if(sum > 1-_epsilon_1)\n  {\n    for(int j=0; j<J-1; ++j)\n    { pi[j] *= (1.-_epsilon_1)/sum;  }\n  }\n  return pi;\n}\n\nLogistic::Logistic(void) {\n}\ndouble Logistic::cdf_logit(const double& value) const\n{\n  boost::math::logistic dist(0., 1.);\n  return boost::math::cdf(dist, value);\n}\ndouble Logistic::pdf_logit(const double& value) const\n{\n  boost::math::logistic dist(0., 1.);\n  return boost::math::pdf(dist, value);\n}\nEigen::VectorXd Logistic::InverseLinkQuantileFunction(Eigen::VectorXd vector ){\n  boost::math::logistic dist(0., 1.);\n  for (int i = 0; i<=vector.size()-1; i++)\n    vector(i) = quantile(dist, vector(i));\n  return vector;\n}\n\n\nNormal::Normal(void) {\n}\ndouble Normal::cdf_normal(const double& value) const\n{\n  boost::math::normal norm;\n  return boost::math::cdf(norm, value);\n}\ndouble Normal::pdf_normal(const double& value) const\n{\n  boost::math::normal norm;\n  return boost::math::pdf(norm, value);\n}\nEigen::VectorXd Normal::InverseLinkQuantileFunction(Eigen::VectorXd vector ){\n  boost::math::normal norm;\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = quantile(norm, vector(i));\n  return vector;\n}\n\nCauchit::Cauchit(void) {\n}\n\ndouble Cauchit::cdf_cauchit(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  return cdf(extreme_value, value);\n}\ndouble Cauchit::pdf_cauchit(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  return pdf(extreme_value, value);\n}\nEigen::VectorXd Cauchit::InverseLinkQuantileFunction(Eigen::VectorXd vector ){\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::cauchy_distribution<> extreme_value(_location, _scale);\n  for (int i = 0; i<=vector.rows()-1; i++)\n    vector(i) = quantile(extreme_value, vector(i));\n  return vector;\n}\n\nStudent::Student(void) {\n}\n\ndouble Student::cdf_student(const double& value, const double& freedom_degrees) const\n{\n  double z;\n  if(freedom_degrees < 2 * pow(value, 2) )\n  { z = boost::math::ibeta(freedom_degrees * 0.5, 0.5, freedom_degrees / (freedom_degrees + pow(value, 2))) * 0.5; }\n  else\n  { z = boost::math::ibetac(0.5, freedom_degrees * 0.5, pow(value, 2) / (freedom_degrees + pow(value, 2))) * 0.5; }\n  if(value > 0)\n  { return 1-z; }\n  else\n  {return z; }\n}\n\ndouble Student::pdf_student(const double& value, const double& freedom_degrees) const\n{ return pow( freedom_degrees/(freedom_degrees + pow(value, 2)) , (1+freedom_degrees) * 0.5 ) / ( pow(freedom_degrees,0.5) * boost::math::beta(freedom_degrees*0.5, 0.5) ); }\n\nGumbel::Gumbel(void) {\n  // Rcout << \"Gumbel is being created\" << endl;\n}\ndouble Gumbel::cdf_gumbel(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  return cdf(extreme_value, value);\n}\ndouble Gumbel::pdf_gumbel(const double& value) const\n{\n  double _location = 0.0;\n  double _scale =1.0;\n  boost::math::extreme_value_distribution<> extreme_value(_location, _scale);\n  return pdf(extreme_value, value);\n}\n\nGompertz::Gompertz(void) {\n  // Rcout << \"Gompertz is being created\" << endl;\n}\n\ndouble Gompertz::pdf_gompertz(const double& value) const\n{ double _mu = 0.0;\n  double _sigma = 1.0;\n\n  return (exp((value - _mu)/ _sigma) *  exp( - exp ((value - _mu)/ _sigma) ) ) / _sigma ; }\n\ndouble Gompertz::cdf_gompertz(const double& value) const\n{ double _mu = 0.0;\n  double _sigma = 1.0;\n  return  1 - exp( - exp((value - _mu) / _sigma) ); }\n\n\nRCPP_MODULE(exportmod){\n  using namespace Rcpp ;\n  class_<distribution>(\"distribution\")\n    .constructor()\n  ;\n  class_<Student>(\"Student\")\n    .derives<distribution>(\"distribution\")\n    .constructor()\n    .method( \"cdf_student\", &Student::cdf_student )\n    .method( \"pdf_student\", &Student::pdf_student )\n  ;\n}\n\n// RCPP_MODULE(exportmoddev){\n//   using namespace Rcpp ;\n//   class_<distribution>(\"distribution\")\n//     .constructor()\n//   ;\n//   class_<Logistic>(\"Logistic\")\n//     .derives<distribution>(\"distribution\")\n//     .constructor()\n//     .method( \"InverseLinkCumulativeFunction\", &Logistic::InverseLinkCumulativeFunction )\n//   ;\n// }\n\n", "meta": {"hexsha": "589a9ca7669d3737f14ba2a36dfdaf6b05d57871", "size": 34900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distribution.cpp", "max_stars_repo_name": "ylleonv/pack", "max_stars_repo_head_hexsha": "cb3416a8e230cfbee5a95273c9c6a15184d2458b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distribution.cpp", "max_issues_repo_name": "ylleonv/pack", "max_issues_repo_head_hexsha": "cb3416a8e230cfbee5a95273c9c6a15184d2458b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distribution.cpp", "max_forks_repo_name": "ylleonv/pack", "max_forks_repo_head_hexsha": "cb3416a8e230cfbee5a95273c9c6a15184d2458b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0537190083, "max_line_length": 173, "alphanum_fraction": 0.6944985673, "num_tokens": 9366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.019719129763597815, "lm_q1q2_score": 0.0069451123750095545}}
{"text": "//\n//  E_step.cpp\n//  synthetic_data_helper\n//\n//  Created by Cristián Garay on 11/16/16.\n//  Copyright © 2016 Cristian Garay. All rights reserved.\n//\n\n#define NPY_NO_DEPRECATED_API NPY_1_11_API_VERSION\n\n#include <iostream>\n#include <stdint.h>\n#include <alloca.h>\n#include <Eigen/Core>\n#include <omp.h>\n#include <boost/python.hpp>\n#include <boost/python/numeric.hpp>\n#include <boost/python/ptr.hpp>\n#include <Python.h>\n#include <numpy/ndarrayobject.h>\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace boost::python;\n\n#if PY_VERSION_HEX >= 0x03000000\nvoid *\n#else\nvoid\n#endif\ninit_numpy(){\n    //Py_Initialize;\n    import_array();\n}\n\n//original comment:\n//\"TODO if we aren't outputting gamma, don't need to write it to memory (just\n//need t and t+1), so we can save the stack array for each HMM at the cost of\n//a branch\"\n\n/*struct double_to_python_float\n{\n    static PyObject* convert(double const& d)\n      {\n        return boost::python::incref(\n          boost::python::object(d).ptr());\n      }\n};*/\n\n//numpy scalar converters.\ntemplate <typename T, NPY_TYPES NumPyScalarType>\nstruct enable_numpy_scalar_converter\n{\n  enable_numpy_scalar_converter()\n  {\n    // Required NumPy call in order to use the NumPy C API within another\n    // extension module.\n    // import_array();\n    init_numpy();\n\n    boost::python::converter::registry::push_back(\n      &convertible,\n      &construct,\n      boost::python::type_id<T>());\n  }\n\n  static void* convertible(PyObject* object)\n  {\n    // The object is convertible if all of the following are true:\n    // - is a valid object.\n    // - is a numpy array scalar.\n    // - its descriptor type matches the type for this converter.\n    return (\n      object &&                                                    // Valid\n      PyArray_CheckScalar(object) &&                               // Scalar\n      PyArray_DescrFromScalar(object)->type_num == NumPyScalarType // Match\n    )\n      ? object // The Python object can be converted.\n      : NULL;\n  }\n\n  static void construct(\n    PyObject* object,\n    boost::python::converter::rvalue_from_python_stage1_data* data)\n  {\n    // Obtain a handle to the memory block that the converter has allocated\n    // for the C++ type.\n    namespace python = boost::python;\n    typedef python::converter::rvalue_from_python_storage<T> storage_type;\n    void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;\n\n    // Extract the array scalar type directly into the storage.\n    PyArray_ScalarAsCtype(object, storage);\n\n    // Set convertible to indicate success.\n    data->convertible = storage;\n  }\n};\n\n//dict create_synthetic_data(dict& model, numeric::array& starts, numeric::array& lengths, numeric::array& resources)\ndict run(dict& data, dict& model, numeric::array& trans_softcounts, numeric::array& emission_softcounts, numeric::array& init_softcounts, int num_outputs){\n    //TODO: check if parameters are null.\n    //TODO: check that dicts have the required members.\n    //TODO: check that all parameters have the right sizes.\n    //TODO: i'm not sending any error messages.\n\n    IOFormat CleanFmt(4, 0, \", \", \"\\n\", \"[\", \"]\");\n\n    numeric::array alldata = extract<numeric::array>(data[\"data\"]); //multidimensional array, so i need to keep extracting arrays.\n    int bigT = len(alldata[0]); //this should be the number of columns in the alldata object. i'm assuming is 2d array.\n    int num_subparts = len(alldata);\n\n    numeric::array allresources = extract<numeric::array>(data[\"resources\"]);\n\n    numeric::array starts = extract<numeric::array>(data[\"starts\"]);\n\n    int num_sequences = len(starts);\n\n    numeric::array lengths = extract<numeric::array>(data[\"lengths\"]);\n\n    numeric::array learns = extract<numeric::array>(model[\"learns\"]);\n    int num_resources = len(learns);\n\n    numeric::array forgets = extract<numeric::array>(model[\"forgets\"]);\n\n    numeric::array guesses = extract<numeric::array>(model[\"guesses\"]);\n\n    numeric::array slips = extract<numeric::array>(model[\"slips\"]);\n\n    double prior = extract<double>(model[\"prior\"]);\n\n    bool normalizeLengths = false;\n    //then the original code goes to find the optional parameters.\n\n    Array2d initial_distn;\n    initial_distn << 1-prior, prior;\n\n    MatrixXd As(2,2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        double learn = extract<double>(learns[n]);\n        double forget = extract<double>(forgets[n]);\n        As.col(2*n) << 1-learn, learn;\n        As.col(2*n+1) << forget, 1-forget;\n    }\n\n    Array2Xd Bn(2,2*num_subparts);\n    for (int n=0; n<num_subparts; n++) {\n        double guess = extract<double>(guesses[n]);\n        double slip = extract<double>(slips[n]);\n        Bn.col(2*n) << 1-guess, slip; // incorrect\n        Bn.col(2*n+1) << guess, 1-slip; // correct\n    }\n\n    //// outputs\n\n    //TODO: NEED TO FIX THIS I'M CREATING NEW ARRAYS AND I NEED TO USE THE ARGUMENTS!!!\n    //TODO: FIX THIS!!!\n    /*Map<ArrayXXd,Aligned> all_trans_softcounts(trans_softcounts,2,2*num_resources);\n    all_trans_softcounts.setZero();\n    Map<Array2Xd,Aligned> all_emission_softcounts(emission_softcounts,2,2*num_subparts);\n    all_emission_softcounts.setZero();\n    Map<Array2d,Aligned> all_initial_softcounts(init_softcounts);\n    all_initial_softcounts.setZero();*/\n    //TODO: I replaced the pointers to the arguments for new Eigen arrays.\n    /*ArrayXXd all_trans_softcounts(2,2*num_resources);\n    all_trans_softcounts.setZero(); //why is he setting all these to zero???\n    Array2Xd all_emission_softcounts(2,2*num_subparts);\n    all_emission_softcounts.setZero();\n    Array2d all_initial_softcounts(2, 1); //should i use these dimensions? the same as the original vector??\n    all_initial_softcounts.setZero();*/\n    //cout << \"all_trans_softcounts\" << all_trans_softcounts << endl;\n    //cout << \"all_emission_softcounts\" << all_emission_softcounts << endl;\n    //cout << \"all_initial_softcounts\" << all_initial_softcounts << endl;\n    double r_trans_softcounts[2*2*num_resources];\n    double r_emission_softcounts[2*2*num_subparts];\n    double r_init_softcounts[2*1];\n    Map<ArrayXXd,Aligned> all_trans_softcounts(r_trans_softcounts,2,2*num_resources);\n    all_trans_softcounts.setZero();\n    Map<Array2Xd,Aligned> all_emission_softcounts(r_emission_softcounts,2,2*num_subparts);\n    all_emission_softcounts.setZero();\n    Map<Array2d,Aligned> all_initial_softcounts(r_init_softcounts);\n    all_initial_softcounts.setZero();\n\n    //TODO: FIX THIS!!! I'll replace all these weird arrays for zeroes ones.\n    //Array2Xd likelihoods_out(2,bigT);\n    //likelihoods_out.setZero();\n    //Array2Xd gamma_out(2,bigT);\n    //gamma_out.setZero();\n    //Array2Xd alpha_out(2,bigT);\n    //alpha_out.setZero();\n    Map<Array2Xd,Aligned> likelihoods_out(NULL,2,bigT);\n    Map<Array2Xd,Aligned> gamma_out(NULL,2,bigT);\n    Map<Array2Xd,Aligned> alpha_out(NULL,2,bigT);\n    double s_total_loglike = 0;\n    double *total_loglike = &s_total_loglike;\n    //cout << \"likelihoods_out\" << likelihoods_out << endl;\n    //cout << \"gamma_out\" << gamma_out << endl;\n    //cout << \"alpha_out\" << alpha_out << endl;\n    //cout << \"s_total_loglike \" << s_total_loglike << endl;\n    //cout << \"total_loglike \" << total_loglike << endl;\n\n    //TODO: FIX THIS!!! why is he doing this??\n    /* switch (num_outputs)\n    {\n        case 4:\n            plhs[3] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&likelihoods_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[3]),2,bigT);\n        case 3:\n            plhs[2] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&gamma_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[2]),2,bigT);\n        case 2:\n            plhs[1] = mxCreateDoubleMatrix(2,bigT,mxREAL);\n            new (&alpha_out) Map<Array2Xd,Aligned>(mxGetPr(plhs[1]),2,bigT);\n        case 1:\n            plhs[0] = mxCreateDoubleScalar(0.);\n            total_loglike = mxGetPr(plhs[0]);\n    }*/\n    double r_likelihoods_out[2*bigT];\n    double r_gamma_out[2*bigT];\n    double r_alpha_out[2*bigT];\n\n    new (&likelihoods_out) Map<Array2Xd,Aligned>(r_likelihoods_out,2,bigT);\n    new (&gamma_out) Map<Array2Xd,Aligned>(r_gamma_out,2,bigT);\n    new (&alpha_out) Map<Array2Xd,Aligned>(r_alpha_out,2,bigT);\n\n\n    /* COMPUTATION */\n    Eigen::initParallel();\n    /* omp_set_dynamic(0); */\n    /* omp_set_num_threads(6); */\n    #pragma omp parallel\n    {\n        double s_trans_softcounts[2*2*num_resources] __attribute__((aligned(16)));\n        double s_emission_softcounts[2*2*num_subparts] __attribute__((aligned(16)));\n        Map<ArrayXXd,Aligned> trans_softcounts_temp(s_trans_softcounts,2,2*num_resources);\n        Map<ArrayXXd,Aligned> emission_softcounts_temp(s_emission_softcounts,2,2*num_subparts);\n        Array2d init_softcounts_temp;\n        double loglike;\n\n        trans_softcounts_temp.setZero();\n        emission_softcounts_temp.setZero();\n        init_softcounts_temp.setZero();\n        loglike = 0;\n        int num_threads = omp_get_num_threads();\n        int blocklen = 1 + ((num_sequences - 1) / num_threads);\n        int sequence_idx_start = blocklen * omp_get_thread_num();\n        int sequence_idx_end = min(sequence_idx_start+blocklen,num_sequences);\n        //mexPrintf(\"start:%d   end:%d\\n\", sequence_idx_start, sequence_idx_end);\n        //cout << \"start: \" << sequence_idx_start << \" end: \" << sequence_idx_end << endl;\n\n        for (int sequence_index=sequence_idx_start; sequence_index < sequence_idx_end; sequence_index++) {\n\n            // NOTE: -1 because Matlab indexing starts at 1\n            int64_t sequence_start = extract<int64_t>(starts[sequence_index]) - 1;\n\n            int64_t T = extract<int64_t>(lengths[sequence_index]);\n\n            //// likelihoods\n            double s_likelihoods[2*T];\n            Map<Array2Xd,Aligned> likelihoods(s_likelihoods,2,T);\n\n            likelihoods.setOnes();\n             for (int t=0; t<T; t++) {\n                 for (int n=0; n<num_subparts; n++) {\n                    int32_t data_temp = extract<int32_t>(alldata[n][sequence_start+t]);\n                     if (data_temp != 0) {\n                         likelihoods.col(t) *= Bn.col(2*n + (data_temp == 2));\n                     }\n                 }\n             }\n\n            //// forward messages\n            double norm;\n            double s_alpha[2*T] __attribute__((aligned(16)));\n            double contribution;\n            Map<MatrixXd,Aligned> alpha(s_alpha,2,T);\n            alpha.col(0) = initial_distn * likelihoods.col(0);\n            norm = alpha.col(0).sum();\n            //cout << \"norm: \" << norm << endl;\n            alpha.col(0) /= norm;\n            contribution = log(norm);\n            //cout << \"contribution \" << contribution << endl;\n            if(normalizeLengths) {\n                contribution = contribution / T;\n            }\n            loglike += contribution;\n            //cout << \"loglike2 \" << loglike << endl;\n\n            for (int t=0; t<T-1; t++) {\n                int64_t resources_temp = extract<int64_t>(allresources[sequence_start+t]);\n                alpha.col(t+1) = (As.block(0,2*(resources_temp-1),2,2) * alpha.col(t)).array()\n                    * likelihoods.col(t+1);\n                //cout << \"likelihoods.col(t+1) \" << likelihoods.col(t+1) << endl;\n                norm = alpha.col(t+1).sum();\n                //cout << \"norm: \" << norm << endl;\n                alpha.col(t+1) /= norm;\n                contribution = log(norm);\n                //cout << \"contribution: \" << contribution << endl;\n                if(normalizeLengths) {\n                    contribution = contribution / T;\n                }\n                loglike += contribution;\n                //cout << \"loglike \" << loglike << endl;\n            }\n\n            //// backward messages and statistic counting\n\n            double s_gamma[2*T] __attribute__((aligned(16)));\n            Map<Array2Xd,Aligned> gamma(s_gamma,2,T);\n            gamma.col(T-1) = alpha.col(T-1);\n            for (int n=0; n<num_subparts; n++) {\n                int32_t data_temp = extract<int32_t>(alldata[n][sequence_start+(T-1)]);\n                if (data_temp != 0) {\n                    emission_softcounts_temp.col(2*n + (data_temp == 2)) += gamma.col(T-1);\n                }\n            }\n\n            for (int t=T-2; t>=0; t--) {\n\n\t\t\t\tint64_t resources_temp = extract<int64_t>(allresources[sequence_start+t]);\n                Matrix2d A = As.block(0,2*(resources_temp-1),2,2);\n                Array22d pair = A.array();\n                pair.rowwise() *= alpha.col(t).transpose().array();\n                pair.colwise() *= gamma.col(t+1);\n                pair.colwise() /= (A*alpha.col(t)).array();\n                pair = (pair != pair).select(0.,pair); // NOTE: replace NaNs\n                trans_softcounts_temp.block(0,2*(resources_temp-1),2,2) += pair;\n\n                gamma.col(t) = pair.colwise().sum().transpose();\n                // NOTE: we have to touch the data again here\n                for (int n=0; n<num_subparts; n++) {\n                    int32_t data_temp = extract<int32_t>(alldata[n][sequence_start+t]);\n                    if (data_temp != 0) {\n                        emission_softcounts_temp.col(2*n + (data_temp == 2)) += gamma.col(t);\n                    }\n                }\n            }\n            init_softcounts_temp += gamma.col(0);\n\n            //TODO: FIX THIS!!!\n            /* switch (nlhs)\n            {\n                case 4:\n                    likelihoods_out.block(0,sequence_start,2,T) = likelihoods;\n                case 3:\n                    gamma_out.block(0,sequence_start,2,T) = gamma;\n                case 2:\n                    alpha_out.block(0,sequence_start,2,T) = alpha;\n            } */\n            likelihoods_out.block(0,sequence_start,2,T) = likelihoods;\n            gamma_out.block(0,sequence_start,2,T) = gamma;\n            alpha_out.block(0,sequence_start,2,T) = alpha;\n        }\n\n        #pragma omp critical\n        {\n            all_trans_softcounts += trans_softcounts_temp;\n            all_emission_softcounts += emission_softcounts_temp;\n            all_initial_softcounts += init_softcounts_temp;\n            //cout << \"loglike \" << loglike << endl;\n            *total_loglike += loglike;\n        }\n    }\n\n    dict result;\n    result[\"total_loglike\"] = *total_loglike;\n\n    //cout << \"r_trans_softcounts \" << r_trans_softcounts << endl;\n\n    npy_intp all_trans_softcounts_dims[3] = {num_resources,2,2}; //TODO: just put directly this array into the PyArray_SimpleNewFromData function?\n    PyObject * all_trans_softcounts_pyObj = PyArray_New(&PyArray_Type, 3, all_trans_softcounts_dims, NPY_DOUBLE, NULL, &r_trans_softcounts, 0, NPY_ARRAY_CARRAY, NULL);\n    boost::python::handle<> all_trans_softcounts_handle( all_trans_softcounts_pyObj );\n    boost::python::numeric::array all_trans_softcounts_arr( all_trans_softcounts_handle );\n    result[\"all_trans_softcounts\"] = all_trans_softcounts_arr;\n\n    npy_intp all_emission_softcounts_dims[3] = {num_subparts,2,2}; //TODO: just put directly this array into the PyArray_SimpleNewFromData function?\n    PyObject * all_emission_softcounts_pyObj = PyArray_New(&PyArray_Type, 3, all_emission_softcounts_dims, NPY_DOUBLE, NULL, &r_emission_softcounts, 0, NPY_ARRAY_CARRAY, NULL);\n    boost::python::handle<> all_emission_softcounts_handle( all_emission_softcounts_pyObj );\n    boost::python::numeric::array all_emission_softcounts_arr( all_emission_softcounts_handle );\n    result[\"all_emission_softcounts\"] = all_emission_softcounts_arr;\n\n    npy_intp all_initial_softcounts_dims[2] = {2,1}; //TODO: just put directly this array into the PyArray_SimpleNewFromData function?\n    PyObject * all_initial_softcounts_pyObj = PyArray_New(&PyArray_Type, 2, all_initial_softcounts_dims, NPY_DOUBLE, NULL, &r_init_softcounts, 0, NPY_ARRAY_CARRAY, NULL);\n    boost::python::handle<> all_initial_softcounts_handle( all_initial_softcounts_pyObj );\n    boost::python::numeric::array all_initial_softcounts_arr( all_initial_softcounts_handle );\n    result[\"all_initial_softcounts\"] = all_initial_softcounts_arr;\n\n    npy_intp alpha_out_dims[2] = {2,bigT}; //TODO: just put directly this array into the PyArray_SimpleNewFromData function?\n    PyObject * alpha_out_pyObj = PyArray_New(&PyArray_Type, 2, alpha_out_dims, NPY_DOUBLE, NULL, &r_alpha_out, 0, NPY_ARRAY_CARRAY, NULL);\n    boost::python::handle<> alpha_out_handle( alpha_out_pyObj );\n    boost::python::numeric::array alpha_out_arr( alpha_out_handle );\n    result[\"alpha\"] = alpha_out_arr;\n\n    return(result);\n}\n\n\nBOOST_PYTHON_MODULE(E_step){\n    //import_array();\n    init_numpy();\n    numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n    //to_python_converter<double, double_to_python_float>();\n    enable_numpy_scalar_converter<boost::int8_t, NPY_INT8>();\n    enable_numpy_scalar_converter<boost::int16_t, NPY_INT16>();\n    enable_numpy_scalar_converter<boost::int32_t, NPY_INT32>();\n    enable_numpy_scalar_converter<boost::int64_t, NPY_INT64>();\n\n    def(\"run\", run);\n\n}\n", "meta": {"hexsha": "9716135118bc935757e99eccc71f8433d4b91b4e", "size": 16963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fit/E_step.cpp", "max_stars_repo_name": "rachelcusack/pyBKT", "max_stars_repo_head_hexsha": "af10442bcffcdd2dcbdd9ee7e437b81a002a55f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fit/E_step.cpp", "max_issues_repo_name": "rachelcusack/pyBKT", "max_issues_repo_head_hexsha": "af10442bcffcdd2dcbdd9ee7e437b81a002a55f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fit/E_step.cpp", "max_forks_repo_name": "rachelcusack/pyBKT", "max_forks_repo_head_hexsha": "af10442bcffcdd2dcbdd9ee7e437b81a002a55f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2725060827, "max_line_length": 176, "alphanum_fraction": 0.6385662913, "num_tokens": 4303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.01971912803533567, "lm_q1q2_score": 0.006945112034475724}}
{"text": "/*\n\nCopyright (c) 2005-2017, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n#ifndef LINEARPARABOLICPDESYSTEMWITHCOUPLEDODESYSTEMSOLVER_HPP_\n#define LINEARPARABOLICPDESYSTEMWITHCOUPLEDODESYSTEMSOLVER_HPP_\n\n#include \"AbstractAssemblerSolverHybrid.hpp\"\n#include \"AbstractDynamicLinearPdeSolver.hpp\"\n#include \"AbstractLinearParabolicPdeSystemForCoupledOdeSystem.hpp\"\n#include \"TetrahedralMesh.hpp\"\n#include \"BoundaryConditionsContainer.hpp\"\n#include \"AbstractOdeSystemForCoupledPdeSystem.hpp\"\n#include \"CvodeAdaptor.hpp\"\n#include \"BackwardEulerIvpOdeSolver.hpp\"\n#include \"Warnings.hpp\"\n#include \"VtkMeshWriter.hpp\"\n\n#include <boost/shared_ptr.hpp>\n\n/**\n * A class for solving systems of parabolic PDEs and ODEs, which may be coupled\n * via their source terms:\n *\n * d/dt (u_i) = div (D(x) grad (u_i)) + f_i (x, u_1, ..., u_p, v_1, ..., v_q),  i=1,...,p,\n * d/dt (v_j) = g_j(x, u_1, ..., u_p, v_1, ..., v_q),  j=1,...,q.\n *\n * The solver class is templated over spatial dimension and PDE problem dimension (p).\n */\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM=ELEMENT_DIM, unsigned PROBLEM_DIM=1>\nclass LinearParabolicPdeSystemWithCoupledOdeSystemSolver\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    AbstractLinearParabolicPdeSystemForCoupledOdeSystem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* mpPdeSystem;\n\n    /** Vector of pointers to ODE systems, defined at nodes. */\n    std::vector<AbstractOdeSystemForCoupledPdeSystem*> 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 solver. */\n    boost::shared_ptr<AbstractIvpOdeSolver> mpOdeSolver;\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     * 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    LinearParabolicPdeSystemWithCoupledOdeSystemSolver(TetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh,\n                                                       AbstractLinearParabolicPdeSystemForCoupledOdeSystem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pPdeSystem,\n                                                       BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pBoundaryConditions,\n                                                       std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystemsAtNodes=std::vector<AbstractOdeSystemForCoupledPdeSystem*>(),\n                                                       boost::shared_ptr<AbstractIvpOdeSolver> pOdeSolver=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    ~LinearParabolicPdeSystemWithCoupledOdeSystemSolver();\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\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)> LinearParabolicPdeSystemWithCoupledOdeSystemSolver<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    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        c_matrix<double, SPACE_DIM, SPACE_DIM> this_pde_diffusion_term = mpPdeSystem->ComputeDiffusionTerm(rX, pde_index, pElement);\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    return matrix_term;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nc_vector<double, PROBLEM_DIM*(ELEMENT_DIM+1)> LinearParabolicPdeSystemWithCoupledOdeSystemSolver<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    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        double this_dudt_coefficient = mpPdeSystem->ComputeDuDtCoefficientFunction(rX, pde_index);\n        double this_source_term = mpPdeSystem->ComputeSourceTerm(rX, rU, mInterpolatedOdeStateVariables, pde_index);\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\n    return vector_term;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid LinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ResetInterpolatedQuantities()\n{\n    mInterpolatedOdeStateVariables.clear();\n\n    if (mOdeSystemsPresent)\n    {\n        unsigned num_state_variables = mOdeSystemsAtNodes[0]->GetNumberOfStateVariables();\n        mInterpolatedOdeStateVariables.resize(num_state_variables, 0.0);\n    }\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid LinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::IncrementInterpolatedQuantities(double phiI, const Node<SPACE_DIM>* pNode)\n{\n    if (mOdeSystemsPresent)\n    {\n        unsigned num_state_variables = mOdeSystemsAtNodes[0]->GetNumberOfStateVariables();\n\n        for (unsigned i=0; i<num_state_variables; i++)\n        {\n            mInterpolatedOdeStateVariables[i] += phiI * mOdeSystemsAtNodes[pNode->GetIndex()]->rGetStateVariables()[i];\n        }\n    }\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid LinearParabolicPdeSystemWithCoupledOdeSystemSolver<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 LinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetupLinearSystem(Vec currentSolution, bool computeMatrix)\n{\n    this->SetupGivenLinearSystem(currentSolution, computeMatrix, this->mpLinearSystem);\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nLinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::LinearParabolicPdeSystemWithCoupledOdeSystemSolver(\n        TetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh,\n        AbstractLinearParabolicPdeSystemForCoupledOdeSystem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pPdeSystem,\n        BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* pBoundaryConditions,\n        std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystemsAtNodes,\n        boost::shared_ptr<AbstractIvpOdeSolver> pOdeSolver)\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      mpOdeSolver(pOdeSolver),\n      mSamplingTimeStep(DOUBLE_UNSET),\n      mOdeSystemsPresent(false),\n      mClearOutputDirectory(false)\n{\n    this->mpBoundaryConditions = pBoundaryConditions;\n\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 (!mpOdeSolver)\n        {\n#ifdef CHASTE_CVODE\n            mpOdeSolver.reset(new CvodeAdaptor);\n#else\n            mpOdeSolver.reset(new BackwardEulerIvpOdeSolver(mOdeSystemsAtNodes[0]->GetNumberOfStateVariables()));\n#endif //CHASTE_CVODE\n        }\n    }\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nLinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::~LinearParabolicPdeSystemWithCoupledOdeSystemSolver()\n{\n    if (mOdeSystemsPresent)\n    {\n        for (unsigned i=0; i<mOdeSystemsAtNodes.size(); i++)\n        {\n            delete mOdeSystemsAtNodes[i];\n        }\n    }\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid LinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::PrepareForSetupLinearSystem(Vec currentPdeSolution)\n{\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                current_soln_this_node[pde_index] = current_soln_this_pde_this_node;\n            }\n\n            // Pass it into the ODE system at this node\n            mOdeSystemsAtNodes[node_index]->SetPdeSolution(current_soln_this_node);\n\n            // Solve ODE system at this node\n            mpOdeSolver->SolveAndUpdateStateVariable(mOdeSystemsAtNodes[node_index], time, next_time, dt);\n        }\n    }\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid LinearParabolicPdeSystemWithCoupledOdeSystemSolver<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 LinearParabolicPdeSystemWithCoupledOdeSystemSolver<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 LinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SolveAndWriteResultsToFile()\n{\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    // Create a .pvd output file\n    OutputFileHandler output_file_handler(this->mOutputDirectory, mClearOutputDirectory);\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    // Write initial condition to VTK\n    Vec initial_condition = this->mInitialCondition;\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    // Main time loop\n    while (!stepper.IsTimeAtEnd())\n    {\n        // Reset start and end times\n        this->SetTimes(stepper.GetTime(), stepper.GetNextTime());\n\n        // Solve the system up to the new end time\n        Vec soln = this->Solve();\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        // Write solution to VTK\n        WriteVtkResultsToFile(soln, stepper.GetTotalTimeStepsTaken());\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}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid LinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::WriteVtkResultsToFile(Vec solution, unsigned numTimeStepsElapsed)\n{\n#ifdef CHASTE_VTK\n\n    // Create a new VTK file for this time step\n    std::stringstream time;\n    time << numTimeStepsElapsed;\n    VtkMeshWriter<ELEMENT_DIM, SPACE_DIM> mesh_writer(this->mOutputDirectory, \"results_\"+time.str(), false);\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    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 \" << 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        std::vector<std::vector<double> > ode_data;\n        unsigned num_odes = mOdeSystemsAtNodes[0]->rGetStateVariables().size();\n        ode_data.resize(num_odes);\n        for (unsigned ode_index=0; ode_index<num_odes; ode_index++)\n        {\n            ode_data[ode_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            for (unsigned i=0; i<num_odes; i++)\n            {\n                ode_data[i][node_index] = all_odes_this_node[i];\n            }\n        }\n\n        for (unsigned ode_index=0; ode_index<num_odes; ode_index++)\n        {\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 \" << 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\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nAbstractOdeSystemForCoupledPdeSystem* LinearParabolicPdeSystemWithCoupledOdeSystemSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetOdeSystemAtNode(unsigned index)\n{\n    return mOdeSystemsAtNodes[index];\n}\n\n#endif /*LINEARPARABOLICPDESYSTEMWITHCOUPLEDODESYSTEMSOLVER_HPP_*/\n", "meta": {"hexsha": "aa54830bdc2e8217f91e7d0bd1d97f1252b22734", "size": 26506, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pde/src/solver/LinearParabolicPdeSystemWithCoupledOdeSystemSolver.hpp", "max_stars_repo_name": "gonayl/Chaste", "max_stars_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pde/src/solver/LinearParabolicPdeSystemWithCoupledOdeSystemSolver.hpp", "max_issues_repo_name": "gonayl/Chaste", "max_issues_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pde/src/solver/LinearParabolicPdeSystemWithCoupledOdeSystemSolver.hpp", "max_forks_repo_name": "gonayl/Chaste", "max_forks_repo_head_hexsha": "498c48489a38a8f4c5fa7c01e691cc82df3d2e6b", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6106750392, "max_line_length": 182, "alphanum_fraction": 0.7049724591, "num_tokens": 6517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.021615334023173283, "lm_q1q2_score": 0.006934659579072839}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <iostream>\n#include <string>\n#include <complex>\n#include <vector>\n#include <limits>\n#include <time.h>\n#include <unistd.h>\n#include <proj_api.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n#include <boost/filesystem/operations.hpp>\nnamespace fs = boost::filesystem;\n\n#include <vw/Core.h>\n#include <vw/Image.h>\n#include <vw/FileIO.h>\n#include <vw/Cartography.h>\n#include <vw/Math.h>\nusing namespace vw;\nusing namespace vw::cartography;\n\n#include <vw/Photometry/Reconstruct.h>\n#include <vw/Photometry/Misc.h>\n#include <vw/Photometry/Shape.h>\nusing namespace vw::photometry;\n\n\n//upsamples a geo referenced tiff image by four- used in sfs\n\nvoid upsample_image(std::string output_file, std::string input_file, int upsampleFactor) {\n  GeoReference geo;\n  read_georeference(geo, input_file);\n  DiskImageView<PixelGray<float> >   image(input_file);\n\n  int cols = (image.cols())*upsampleFactor, rows = (image.rows())*upsampleFactor;\n  ImageView<PixelGray<float> >  tm_image(cols, rows);\n\n  ImageViewRef<PixelGray<float> >   interp = interpolate(edge_extend(image.impl(),\n                                                                     ConstantEdgeExtension()),\n                                                         BilinearInterpolation());\n\n  int x, y;\n\n  for (x=0; x<cols; ++x){\n    for (y=0; y<rows; ++y){\n      //if ( is_valid(image(2*x,2*y)) || is_valid(image(2*x+1,2*y)) || is_valid(image(2*x,2*y+1)) || is_valid(image(2*x+1,2*y+1)) ) {\n      //if (is_valid(image(2*x,2*y)) && is_valid(image(2*x+1,2*y)) && is_valid(image(2*x,2*y+1)) && is_valid(image(2*x+1,2*y+1)) ) {\n      float xx = x/upsampleFactor;\n      float yy = y/upsampleFactor;\n\n      if ( interp(x, y) != -10000 ){\n           tm_image(x,y) = interp(x, y);\n      }\n      else{\n           tm_image(x,y) = -10000;\n      }\n    }\n  }\n\n  Matrix<double> H = geo.transform();\n  H(0,0) /= upsampleFactor;\n  H(1,1) /= upsampleFactor;\n  geo.set_transform(H);\n\n  write_georeferenced_image(output_file, tm_image, geo, TerminalProgressCallback(\"photometry\",\"Processing:\"));\n}\n\n\n//subsamples a geo referenced tiff image by two\nvoid subsample_image(std::string output_file, std::string input_file) {\n  GeoReference geo;\n  read_georeference(geo, input_file);\n  DiskImageView<PixelMask<PixelGray<uint8> > >  image(input_file);\n  int cols = (image.cols()+1)/2, rows = (image.rows()+1)/2;\n  ImageView<PixelMask<PixelGray<uint8> > > tm_image(cols, rows);\n\n\n  ImageViewRef<PixelMask<PixelGray<uint8> > >  interp = interpolate(edge_extend(image.impl(),\n                                                                                ConstantEdgeExtension()),\n                                                                    BilinearInterpolation());\n\n  int x, y;\n\n  for (x=0; x<cols; ++x){\n    for (y=0; y<rows; ++y){\n      //if ( is_valid(image(2*x,2*y)) || is_valid(image(2*x+1,2*y)) || is_valid(image(2*x,2*y+1)) || is_valid(image(2*x+1,2*y+1)) ) {\n      //if (is_valid(image(2*x,2*y)) && is_valid(image(2*x+1,2*y)) && is_valid(image(2*x,2*y+1)) && is_valid(image(2*x+1,2*y+1)) ) {\n      if ( is_valid(interp(2*x+0.5, 2*y+0.5)) ){\n        tm_image(x,y) = interp(2*x+0.5, 2*y+0.5);\n      }\n      else{\n        tm_image(x,y).invalidate();\n      }\n    }\n  }\n\n  Matrix<double> H = geo.transform();\n  H(0,0) *= 2;\n  H(1,1) *= 2;\n  geo.set_transform(H);\n\n  write_georeferenced_image(output_file, tm_image, geo, TerminalProgressCallback(\"photometry\",\"Processing:\"));\n}\n\n\n// Given two images and two georeferences, this function picks a set\n// of matching pixel samples between the two images.  It rejects\n// pixels that are not valid, and it should probably also reject\n// pixels that are near saturation (though it does not yet!).\ntemplate <class ViewT>\nstd::vector<Vector4> sample_images(ImageViewBase<ViewT> const& image1,\n                                   ImageViewBase<ViewT> const& image2,\n                                   GeoReference const& geo1,\n                                   GeoReference const& geo2,\n                                   int num_samples,\n                                   std::string const& DEM_file,\n                                   std::vector<Vector3> *normalArray,\n                                   std::vector<Vector3> *xyzArray ) {\n  int sample = 0;\n  int numtries = 0;\n  std::vector<Vector4> result;\n\n  // Random numbers\n  srandom((unsigned int) clock());\n\n  ImageViewRef<typename ViewT::pixel_type> interp_image1 = interpolate(edge_extend(image1.impl(),\n                                                                       ConstantEdgeExtension()),\n                                                                       BilinearInterpolation());\n  ImageViewRef<typename ViewT::pixel_type> interp_image2 = interpolate(edge_extend(image2.impl(),\n                                                                       ConstantEdgeExtension()),\n                                                                       BilinearInterpolation());\n\n  // This block of code samples the images comprehensively, adding a\n  // sample pair for every valid pixel in interp_image1.\n  // for (unsigned j=0; j < interp_image1.rows(); ++j) {\n  //   for (unsigned i=0; i < interp_image1.cols(); ++i) {\n  //     Vector2 sample_pix1(i,j);\n  //     Vector2 sample_pix2 = geo2.lonlat_to_pixel(geo1.pixel_to_lonlat(sample_pix1));\n\n  //     // Check to see whether these pixels are valid\n  //     typename ViewT::pixel_type pix1 = interp_image1(sample_pix1[0], sample_pix1[1]);\n  //     typename ViewT::pixel_type pix2 = interp_image2(sample_pix2[0], sample_pix2[1]);\n  //     if ( is_valid(pix1) && is_valid(pix2) &&\n  //          pix1[0] > 10 && pix1[0] < 245 &&\n  //          pix2[0] > 10 && pix2[0] < 245 ) {\n  //       result.push_back(Vector2(pix1[0],pix2[0]));\n  //       ++sample;\n  //       //        std::cout << result[result.size()-1][0] << \" \" << result[result.size()-1][1] << \"\\n\";\n  //     }\n  //     ++numtries;\n  //   }\n  // }\n\n\n  //added by Ara to support DEMs - START\n  DiskImageView<PixelGray<float> >  dem_image(DEM_file);\n  GeoReference GR;\n  read_georeference(GR, DEM_file);\n  //added by Ara to support DEMs - END\n\n  // This block of code samples the images randomly, gathering up to\n  // num_samples samples from the images.\n  while (sample < num_samples && numtries < num_samples*10) {\n\n    Vector2 sample_pix1(float(random())/RAND_MAX * image1.impl().cols(),\n                        float(random())/RAND_MAX * image1.impl().rows());\n    Vector2 sample_pix2 = geo2.lonlat_to_pixel(geo1.pixel_to_lonlat(sample_pix1));\n\n    Vector2 sample_pix_dem = GR.lonlat_to_pixel(geo1.pixel_to_lonlat(sample_pix1));\n\n    Vector2 lonlat = geo1.pixel_to_lonlat(sample_pix1);\n\n    // Check to see whether these pixels are valid\n    typename ViewT::pixel_type pix1 = interp_image1(sample_pix1[0], sample_pix1[1]);\n    typename ViewT::pixel_type pix2 = interp_image2(sample_pix2[0], sample_pix2[1]);\n    if ( is_valid(pix1) && is_valid(pix2) ) {\n\n       //result.push_back(Vector4(pix1[0],pix2[0],lonlat[0],lonlat[1]));\n\n       int x = (int)sample_pix_dem[0];\n       int y = (int)sample_pix_dem[1];\n\n       if (x < 0){\n           x = 0;\n       }\n       if (x > dem_image.cols()-1){\n           x = dem_image.cols()-1;\n       }\n       if (y < 0){\n           y = 0;\n       }\n       if (y > dem_image.rows()-1){\n           y = dem_image.rows()-1;\n       }\n\n       Vector3 longlat3(lonlat(0),lonlat(1),(dem_image)(x, y));\n       Vector3 xyz = geo1.datum().geodetic_to_cartesian(longlat3);\n\n       Vector2 sample_pix_dem_left;\n       sample_pix_dem_left(0) = x-1;\n       if (sample_pix_dem_left(0) < 0){\n          sample_pix_dem_left(0) = 0;\n          //break;\n       }\n       sample_pix_dem_left(1) = y;\n       lonlat = GR.pixel_to_lonlat(sample_pix_dem_left);\n\n       Vector3 longlat3_left(lonlat(0),lonlat(1),(dem_image)(sample_pix_dem_left(0), sample_pix_dem_left(1)));\n       Vector3 xyz_left = geo1.datum().geodetic_to_cartesian(longlat3_left);\n\n       Vector2 sample_pix_dem_top;\n       sample_pix_dem_top(0) = x;\n       sample_pix_dem_top(1) = y-1;\n       if (sample_pix_dem_top(1) < 0){\n         sample_pix_dem_top(1) = 0;\n         //break;\n       }\n\n       lonlat = GR.pixel_to_lonlat(sample_pix_dem_top);\n       Vector3 longlat3_top(lonlat(0),lonlat(1),(dem_image)(sample_pix_dem_top(0), sample_pix_dem_top(1)));\n       Vector3 xyz_top = geo1.datum().geodetic_to_cartesian(longlat3_top);\n\n\n\n       Vector3 normal = computeNormalFrom3DPoints(xyz, xyz_left, xyz_top);\n\n       //printf(\"normal:%f %f %f\\n\", normal(0), normal(1), normal(2));\n       //printf(\"%f %f %f\\n\", loc_longlat3(0), loc_longlat3(1), loc_longlat3(2));\n\n       result.push_back(Vector4(pix1[0],pix2[0],lonlat[0],lonlat[1]));\n\n       normalArray->push_back(normal);\n       xyzArray->push_back(xyz);\n\n       ++sample;\n       //      std::cout << result[result.size()-1][0] << \" \" << result[result.size()-1][1] << \"\\n\";\n    }\n    ++numtries;\n  }\n  return result;\n}\n/*\n/// Erases a file suffix if one exists and returns the base string\nstatic std::string prefix_from_filename(std::string const& filename) {\n        std::string result = filename;\n        int index = result.rfind(\".\");\n        if (index != -1)\n                result.erase(index, result.size());\n        return result;\n}\n\n/// Erases a file suffix if one exists and returns the base string less3 characters\nstatic std::string prefix_less3_from_filename(std::string const& filename) {\n  std::string result = filename;\n  int index = result.rfind(\".\");\n  if (index != -1)\n    result.erase(index-3, result.size()+3);\n  return result;\n}\n\n/// Erases a file suffix if one exists and returns the base string less3 characters\nstatic std::string sufix_from_filename(std::string const& filename) {\n  std::string result = filename;\n  int index = result.rfind(\"/\");\n  if (index != -1)\n    result.erase(0, index);\n  return result;\n}\n*/\n\n//reads the tiff DEM into a 3D coordinate\n//pos is a Vector2 of pixel coordinates, GR is georeference\ntemplate <class ViewT>\nVector3 pixel_to_cart (Vector2 pos, ImageViewBase<ViewT> const& img,  GeoReference GR) {\n    Vector2 loc_longlat2=GR.point_to_lonlat(GR.pixel_to_point(pos));\n    Vector3 loc_longlat3(loc_longlat2(0),loc_longlat2(1),img((int)pos[0],(int)pos[1]));\n    Vector3 loc_cartesian=GR.datum().geodetic_to_cartesian(loc_longlat3);\n    return loc_cartesian;\n}\n\n\n// Create the output, index, and radiance file names\n\nstd::vector<std::string> parse_command_arguments(int argc, char *argv[] ) {\n        int num_matches;\n        std::vector<std::string> input_files;\n\n        po::options_description general_options(\"Options\");\n        general_options.add_options()\n        (\"help\", \"Display this help message\")\n        (\"num-matches,m\", po::value<int>(&num_matches)->default_value(1000), \"Number of points to match for linear regression.\");\n\n        po::options_description hidden_options(\"\");\n        hidden_options.add_options()\n        (\"input-files\", po::value<std::vector<std::string> >(&input_files));\n\n        po::options_description options(\"Allowed Options\");\n        options.add(general_options).add(hidden_options);\n\n        po::positional_options_description p;\n        p.add(\"input-files\", -1);\n\n        po::variables_map vm;\n        po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );\n        po::notify( vm );\n\n        std::ostringstream usage;\n        usage << \"Description: tonematches several images\" << std::endl << std::endl;\n        usage << \"Usage: histeq [options] <filename1> <filename2> ...\" << std::endl << std::endl;\n        usage << general_options << std::endl;\n\n        if( vm.count(\"help\") ) {\n                std::cerr << usage.str() << std::endl;\n                exit(1);\n        }\n\n        if( vm.count(\"input-files\")<1 ) {\n                std::cerr << \"Error: Must specify at least one input file!\" << std::endl << std::endl;\n                std::cerr << usage.str();\n                exit(1);\n        }\n\n        return input_files;\n}\n\n\n\n", "meta": {"hexsha": "8e214b734d5be736b80204747ee75f0d74fa046f", "size": 12246, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Photometry/Misc.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Photometry/Misc.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Photometry/Misc.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 36.2307692308, "max_line_length": 133, "alphanum_fraction": 0.6045239262, "num_tokens": 3219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.022629200609786092, "lm_q1q2_score": 0.00688022005655338}}
{"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_HASH_STREAM_POSTPROCESSOR_HPP\n#define CRYPTO3_HASH_STREAM_POSTPROCESSOR_HPP\n\n#include <array>\n\n#include <boost/assert.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/range/concepts.hpp>\n#include <boost/array.hpp>\n\n#include <nil/crypto3/detail/pack.hpp>\n\n#include <nil/crypto3/hash/accumulators/hash.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<typename HashAccumulatorSet>\n                struct ref_hash_impl {\n                    typedef HashAccumulatorSet accumulator_set_type;\n                    typedef\n                        typename boost::mpl::front<typename accumulator_set_type::features_type>::type accumulator_type;\n\n                    typedef typename accumulator_type::hash_type hash_type;\n\n                    ref_hash_impl(accumulator_set_type &&stream_hash) : accumulator_set(stream_hash) {\n                    }\n\n                    accumulator_set_type &accumulator_set;\n                };\n\n                template<typename HashAccumulatorSet>\n                struct value_hash_impl {\n                    typedef HashAccumulatorSet accumulator_set_type;\n                    typedef\n                        typename boost::mpl::front<typename accumulator_set_type::features_type>::type accumulator_type;\n\n                    typedef typename accumulator_type::hash_type hash_type;\n\n                    value_hash_impl(accumulator_set_type &&stream_hash) :\n                        accumulator_set(std::forward<accumulator_set_type>(stream_hash)) {\n                    }\n\n                    mutable accumulator_set_type accumulator_set;\n                };\n\n                template<typename HashStateImpl>\n                struct range_hash_impl : public HashStateImpl {\n                    typedef HashStateImpl hash_state_impl_type;\n\n                    typedef typename hash_state_impl_type::accumulator_type accumulator_type;\n                    typedef typename hash_state_impl_type::accumulator_set_type accumulator_set_type;\n\n                    typedef typename hash_state_impl_type::hash_type hash_type;\n\n                    typedef typename boost::mpl::apply<accumulator_set_type, accumulator_type>::type::result_type\n                        result_type;\n\n                    template<typename SinglePassRange>\n                    range_hash_impl(const SinglePassRange &range, accumulator_set_type &&ise) :\n                        HashStateImpl(std::forward<accumulator_set_type>(ise)) {\n                        BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const SinglePassRange>));\n\n                        typedef\n                            typename std::iterator_traits<typename SinglePassRange::iterator>::value_type value_type;\n                        BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);\n                        typedef typename hash_type::template stream_processor<\n                            accumulator_set_type,\n                            std::numeric_limits<value_type>::digits + std::numeric_limits<value_type>::is_signed>::type\n                            stream_processor;\n\n                        stream_processor(this->accumulator_set)(range.begin(), range.end());\n                    }\n\n                    template<typename InputIterator>\n                    range_hash_impl(InputIterator first, InputIterator last, accumulator_set_type &&ise) :\n                        HashStateImpl(std::forward<accumulator_set_type>(ise)) {\n                        BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<InputIterator>));\n\n                        typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n                        BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);\n                        typedef typename hash_type::template stream_processor<\n                            accumulator_set_type,\n                            std::numeric_limits<value_type>::digits + std::numeric_limits<value_type>::is_signed>::type\n                            stream_processor;\n\n                        stream_processor(this->accumulator_set)(first, last);\n                    }\n\n                    template<typename T, std::size_t Size>\n                    inline operator std::array<T, Size>() const {\n                        result_type result =\n                            boost::accumulators::extract_result<accumulator_type>(this->accumulator_set);\n                        std::array<T, Size> out;\n                        std::copy(result.begin(), result.end(), out.end());\n                        return out;\n                    }\n\n                    template<typename T, std::size_t Size>\n                    inline operator boost::array<T, Size>() const {\n                        result_type result =\n                            boost::accumulators::extract_result<accumulator_type>(this->accumulator_set);\n                        boost::array<T, Size> out;\n                        std::copy(result.begin(), result.end(), out.end());\n                        return out;\n                    }\n\n                    template<typename OutputRange>\n                    inline operator OutputRange() const {\n                        result_type result =\n                            boost::accumulators::extract_result<accumulator_type>(this->accumulator_set);\n                        return OutputRange(result.begin(), result.end());\n                    }\n\n                    inline operator result_type() const {\n                        return boost::accumulators::extract_result<accumulator_type>(this->accumulator_set);\n                    }\n\n                    inline operator accumulator_set_type &() const {\n                        return this->accumulator_set;\n                    }\n\n                    template<typename Integral,\n                             typename = typename std::enable_if<std::is_integral<Integral>::value &&\n                                                                hash_type::digest_bits <=\n                                                                    std::numeric_limits<Integral>::digits>::type>\n                    inline operator Integral() const {\n                        std::array<Integral, 1> out;\n                        result_type res = boost::accumulators::extract_result<accumulator_type>(this->accumulator_set);\n                        ::nil::crypto3::detail::pack_to<stream_endian::little_octet_big_bit>(res, out);\n                        return out[0];\n                    }\n\n#ifndef CRYPTO3_RAW_HASH_STRING_OUTPUT\n\n                    template<typename Char, typename CharTraits, typename Alloc>\n                    inline operator std::basic_string<Char, CharTraits, Alloc>() const {\n                        return std::to_string(\n                            boost::accumulators::extract_result<accumulator_type>(this->accumulator_set));\n                    }\n\n#endif\n                };\n\n                template<typename HashStateImpl, typename OutputIterator>\n                struct itr_hash_impl : public HashStateImpl {\n                private:\n                    mutable OutputIterator out;\n\n                public:\n                    typedef HashStateImpl hash_state_impl_type;\n\n                    typedef typename hash_state_impl_type::accumulator_type accumulator_type;\n                    typedef typename hash_state_impl_type::accumulator_set_type accumulator_set_type;\n\n                    typedef typename hash_state_impl_type::hash_type hash_type;\n\n                    typedef typename boost::mpl::apply<accumulator_set_type, accumulator_type>::type::result_type\n                        result_type;\n\n                    template<typename SinglePassRange>\n                    itr_hash_impl(const SinglePassRange &range, OutputIterator out, accumulator_set_type &&ise) :\n                        HashStateImpl(std::forward<accumulator_set_type>(ise)), out(std::move(out)) {\n                        BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const SinglePassRange>));\n\n                        typedef\n                            typename std::iterator_traits<typename SinglePassRange::iterator>::value_type value_type;\n                        BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);\n                        typedef typename hash_type::template stream_processor<\n                            accumulator_set_type,\n                            std::numeric_limits<value_type>::digits + std::numeric_limits<value_type>::is_signed>::type\n                            stream_processor;\n\n                        stream_processor(this->accumulator_set)(range.begin(), range.end());\n                    }\n\n                    template<typename InputIterator>\n                    itr_hash_impl(InputIterator first, InputIterator last, OutputIterator out,\n                                  accumulator_set_type &&ise) :\n                        HashStateImpl(std::forward<accumulator_set_type>(ise)),\n                        out(std::move(out)) {\n                        BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<InputIterator>));\n\n                        typedef typename std::iterator_traits<InputIterator>::value_type value_type;\n                        BOOST_STATIC_ASSERT(std::numeric_limits<value_type>::is_specialized);\n                        typedef typename hash_type::template stream_processor<\n                            accumulator_set_type,\n                            std::numeric_limits<value_type>::digits + std::numeric_limits<value_type>::is_signed>::type\n                            stream_processor;\n\n                        stream_processor(this->accumulator_set)(first, last);\n                    }\n\n                    inline operator accumulator_set_type &() const {\n                        return this->accumulator_set;\n                    }\n\n                    inline operator OutputIterator() const {\n                        result_type result =\n                            boost::accumulators::extract_result<accumulator_type>(this->accumulator_set);\n                        return std::move(result.cbegin(), result.cend(), out);\n                    }\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "f2e940a586af7e4bc197c78e0affcab1726f9d4b", "size": 11717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/hash/hash_value.hpp", "max_stars_repo_name": "JasonCoombs/crypto3-hash", "max_stars_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "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/hash/hash_value.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-hash", "max_issues_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "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/hash/hash_value.hpp", "max_forks_repo_name": "JasonCoombs/crypto3-hash", "max_forks_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "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": 49.6483050847, "max_line_length": 120, "alphanum_fraction": 0.5651617308, "num_tokens": 1879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.019719126127046394, "lm_q1q2_score": 0.00687497713031866}}
{"text": "/**\n * Copyright (c) 2018, University Osnabrück\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 University Osnabrück 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 University Osnabrück 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#ifndef __ClSurface_H\n#define __ClSurface_H\n\n#include <lvr2/reconstruction/QueryPoint.hpp>\n#include <lvr2/reconstruction/LBKdTree.hpp>\n#include <lvr2/geometry/BaseVector.hpp>\n#include <lvr2/geometry/LBPointArray.hpp>\n\n#include <boost/filesystem.hpp>\n#include <boost/shared_array.hpp>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define CL_HPP_TARGET_OPENCL_VERSION 120\n#define CL_USE_DEPRECATED_OPENCL_1_2_APIS\n#define __CL_ENABLE_EXCEPTIONS\n\n#if defined(__APPLE__) || defined(__MACOSX)\n    #include <OpenCL/opencl.h>\n#else\n    #include <CL/cl.h>\n#endif\n#include <lvr2/reconstruction/opencl/cl_helper.h>\n\n#define MAX_SOURCE_SIZE (0x1024)\n\nnamespace lvr2\n{\n\ntypedef boost::shared_array<float> floatArr;\n\nusing Vec = BaseVector<float>;\ntypedef QueryPoint<Vec> QueryPointC;\n\nclass ClSurface {\npublic:\n    ClSurface(floatArr& points, size_t num_points, int device = 0);\n    ~ClSurface();\n\n    /**\n    * @brief Starts calculation the normals on GPU\n    *\n    */\n    void calculateNormals();\n\n    /**\n     * @brief Get the resulting normals of the normal calculation. After calling \"start\".\n     *\n     * @param output_normals     PointArray as return value\n     */\n    void getNormals(floatArr output_normals);\n\n    /**\n     * @brief Set the number of k nearest neighbors\n     *        k-neighborhood\n     *\n     * @param k             The size of the used k-neighborhood\n     *\n     */\n    void setKn(int kn);\n\n    /**\n     * @brief Set the number of k nearest neighbors\n     *        k-neighborhood for interpolation\n     *\n     * @param k             The size of the used k-neighborhood\n     *\n     */\n    void setKi(int ki);\n\n    /**\n     * @brief Set the number of k nearest neighbors\n     *        k-neighborhood for distance\n     *\n     * @param k             The size of the used k-neighborhood\n     *\n     */\n    void setKd(int kd);\n\n    /**\n     * @brief Set the viewpoint to orientate the normals\n     *\n     * @param v_x     Coordinate X axis\n     * @param v_y     Coordinate Y axis\n     * @param v_z     Coordinate Z axis\n     *\n     */\n    void setFlippoint(float v_x, float v_y, float v_z);\n\n    /**\n     * @brief Set Method for normal calculation\n     *\n     * @param method   \"PCA\",\"RANSAC\"\n     *\n     */\n    void setMethod(std::string method);\n\n    /**\n    * Reconstuction Mode:\n    * Points stay in gpu until reconstruction is finished\n    */\n    void setReconstructionMode(bool mode = true);\n\n    /**\n    * TODO:\n    *    Implement\n    */\n    void distances(std::vector<QueryPoint<Vec> >& query_points, float voxel_size);\n\n    void freeGPU();\n\nprivate:\n\n    void init();\n\n    const char *getErrorString(cl_int error);\n\n    void initKdTree();\n\n    void getDeviceInformation(int platform_id=0, int device_id=0);\n\n    void loadEstimationKernel();\n\n    void loadInterpolationKernel();\n\n    void initCl();\n\n    void finalizeCl();\n\n    // V->points and normals\n    LBPointArray<float> V;\n    LBPointArray<float>* kd_tree_values;\n    LBPointArray<unsigned char>* kd_tree_splits;\n\n    LBPointArray<float> Result_Normals;\n    boost::shared_ptr<LBKdTree> kd_tree_gen;\n\n    float m_vx, m_vy, m_vz;\n    int m_k, m_ki, m_kd;\n\n\n    int m_calc_method;\n    bool m_reconstruction_mode;\n\n    // Device Information\n    cl_platform_id m_platform_id;\n    cl_device_id m_device_id;\n    cl_uint m_mps;\n    cl_uint m_threads_per_block;\n    cl_ulong m_device_global_memory;\n    cl_int m_ret;\n    cl_context m_context;\n    cl_command_queue m_command_queue;\n    cl_program m_program_es;\n    cl_program m_program_in;\n    cl_kernel m_kernel_normal_estimation;\n    cl_kernel m_kernel_normal_interpolation;\n\n    cl_mem D_V;\n    cl_mem D_kd_tree_values;\n    cl_mem D_kd_tree_splits;\n    cl_mem D_Normals;\n\n\nconst char *NORMAL_ESTIMATION_KERNEL_STRING = \"\\n\"\n\"unsigned int GetKdTreePosition(__global const float* D_kd_tree_values,\"\n\"const unsigned int num_values,__global const unsigned char* D_kd_tree_splits,\"\n\"const unsigned int num_splits, float x, float y, float z) \\n\"\n\"{ \\n\"\n\"    unsigned int pos = 0; \\n\"\n\"    unsigned int current_dim = 0; \\n\"\n\"    while(pos < num_splits) \\n\"\n\"    { \\n\"\n\"        current_dim = (unsigned int)(D_kd_tree_splits[pos]); \\n\"\n\"        if(current_dim == 0) \\n\"\n\"        { \\n\"\n\"            if(x <= D_kd_tree_values[pos] ) \\n\"\n\"            { \\n\"\n\"                pos = pos*2+1; \\n\"\n\"            } else { \\n\"\n\"                pos = pos*2+2; \\n\"\n\"            } \\n\"\n\"        } else if(current_dim == 1) { \\n\"\n\"            if(y <= D_kd_tree_values[pos] ){ \\n\"\n\"                pos = pos*2+1; \\n\"\n\"            }else{ \\n\"\n\"                pos = pos*2+2; \\n\"\n\"            } \\n\"\n\"        } else { \\n\"\n\"            if(z <= D_kd_tree_values[pos] ){ \\n\"\n\"                pos = pos*2+1; \\n\"\n\"            }else{ \\n\"\n\"                pos = pos*2+2; \\n\"\n\"            } \\n\"\n\"        } \\n\"\n\"    } \\n\"\n\"    return pos; \\n\"\n\"} \\n\"\n\" \\n\"\n\"__kernel void NormalEstimationKernel(__global const float* D_V, const unsigned int num_points,\"\n\"__global const float* D_kd_tree_values, const unsigned int num_values,\"\n\"__global const unsigned char* D_kd_tree_splits , const unsigned int num_splits,\"\n\"__global float* D_Normals, const unsigned int num_pointnormals,const unsigned int k,\"\n\"const float flip_x, const float flip_y, const float flip_z) \\n\"\n\"{ \\n\"\n\"    unsigned int loc_id = get_local_id(0); \\n\"\n\"    unsigned int loc_size = get_local_size(0); \\n\"\n\"    unsigned int glob_id = get_global_id(0); \\n\"\n\"    unsigned int glob_size = get_global_size(0); \\n\"\n\"    unsigned int group_id = get_group_id(0); \\n\"\n\"    unsigned int group_size = get_num_groups(0); \\n\"\n\"    unsigned int tid = glob_id; \\n\"\n\"    const unsigned int offset = glob_size; \\n\"\n\"    for(;tid < num_points; tid += offset) \\n\"\n\"    { \\n\"\n\"        unsigned int pos = GetKdTreePosition(D_kd_tree_values, \"\n\"num_values,D_kd_tree_splits, num_splits,D_V[tid * 3], D_V[tid * 3 + 1], D_V[tid * 3 +2] ); \\n\"\n\"        unsigned int vertex_index = (unsigned int)(D_kd_tree_values[pos]+ 0.5); \\n\"\n\"        if(vertex_index < num_points) \\n\"\n\"        { \\n\"\n\"            float vertex_x = D_V[ vertex_index * 3 + 0 ]; \\n\"\n\"            float vertex_y = D_V[ vertex_index * 3 + 1 ]; \\n\"\n\"            float vertex_z = D_V[ vertex_index * 3 + 2 ]; \\n\"\n\"            unsigned int nearest_index; \\n\"\n\"            int start = pos-(k/2); \\n\"\n\"            int end = pos+((k+1)/2); \\n\"\n\"            int correct = 0; \\n\"\n\"            if(start < num_splits) \\n\"\n\"            { \\n\"\n\"                correct = num_splits - start; \\n\"\n\"            }else if(end > num_values) \\n\"\n\"            { \\n\"\n\"                correct = num_values - end; \\n\"\n\"            } \\n\"\n\"            start += correct; \\n\"\n\"            end += correct; \\n\"\n\"            float result_x = 0.0; \\n\"\n\"            float result_y = 0.0; \\n\"\n\"            float result_z = 0.0; \\n\"\n\"            float xx = 0.0; \\n\"\n\"            float xy = 0.0; \\n\"\n\"            float xz = 0.0; \\n\"\n\"            float yy = 0.0; \\n\"\n\"            float yz = 0.0; \\n\"\n\"            float zz = 0.0; \\n\"\n\"            for(unsigned int i = start; i < end && i<num_values; i++ ) \\n\"\n\"            { \\n\"\n\"                if(i != pos) \\n\"\n\"                { \\n\"\n\"                    nearest_index = (unsigned int)(D_kd_tree_values[i]+ 0.5); \\n\"\n\"                    if(nearest_index < num_points) \\n\"\n\"                    { \\n\"\n\"                        float rx = D_V[ nearest_index * 3 + 0 ] - vertex_x; \\n\"\n\"                        float ry = D_V[ nearest_index * 3 + 1 ] - vertex_y; \\n\"\n\"                        float rz = D_V[ nearest_index * 3 + 2 ] - vertex_z; \\n\"\n\"                        xx += rx * rx; \\n\"\n\"                        xy += rx * ry; \\n\"\n\"                        xz += rx * rz; \\n\"\n\"                        yy += ry * ry; \\n\"\n\"                        yz += ry * rz; \\n\"\n\"                        zz += rz * rz; \\n\"\n\"                    } \\n\"\n\"                } \\n\"\n\"            } \\n\"\n\"            float det_x = yy * zz - yz * yz; \\n\"\n\"            float det_y = xx * zz - xz * xz; \\n\"\n\"            float det_z = xx * yy - xy * xy; \\n\"\n\"            float dir_x; \\n\"\n\"            float dir_y; \\n\"\n\"            float dir_z; \\n\"\n\"            if( det_x >= det_y && det_x >= det_z) \\n\"\n\"            { \\n\"\n\"                dir_x = 1.0; \\n\"\n\"                dir_y = (xz * yz - xy * zz) / det_x; \\n\"\n\"                dir_z = (xy * yz - xz * yy) / det_x; \\n\"\n\"            } \\n\"\n\"            else if( det_y >= det_x && det_y >= det_z) \\n\"\n\"            { \\n\"\n\"                dir_x = (yz * xz - xy * zz) / det_y; \\n\"\n\"                dir_y = 1.0; \\n\"\n\"                dir_z = (xy * xz - yz * xx) / det_y; \\n\"\n\"            } \\n\"\n\"            else{ \\n\"\n\"                dir_x = (yz * xy - xz * yy ) / det_z; \\n\"\n\"                dir_y = (xz * xy - yz * xx ) / det_z; \\n\"\n\"                dir_z = 1.0; \\n\"\n\"            } \\n\"\n\"            float invnorm = 1/sqrt( dir_x * dir_x + dir_y * dir_y + dir_z * dir_z ); \\n\"\n\"            result_x = dir_x * invnorm; \\n\"\n\"            result_y = dir_y * invnorm; \\n\"\n\"            result_z = dir_z * invnorm; \\n\"\n\"            float x_dir = flip_x - vertex_x; \\n\"\n\"            float y_dir = flip_y - vertex_y; \\n\"\n\"            float z_dir = flip_z - vertex_z; \\n\"\n\"            float scalar = x_dir * result_x + y_dir * result_y + z_dir * result_z; \\n\"\n\"            if(scalar < 0) \\n\"\n\"            { \\n\"\n\"                result_x = -result_x; \\n\"\n\"                result_y = -result_y; \\n\"\n\"                result_z = -result_z; \\n\"\n\"            } \\n\"\n\"            D_Normals[tid * 3 ] = result_x; \\n\"\n\"            D_Normals[tid * 3 + 1 ] = result_y; \\n\"\n\"            D_Normals[tid * 3 + 2 ] = result_z; \\n\"\n\"        } \\n\"\n\"    } \\n\"\n\"} \\n\";\n\nconst char *NORMAL_INTERPOLATION_KERNEL_STRING = \"\\n\"\n\"float getGaussianFactor(const unsigned int index, const unsigned int middle_i, \"\n\"const unsigned int ki, const float norm) \\n\"\n\"{ \\n\"\n\"    float val = (float)(index); \\n\"\n\"    float middle = (float)(middle_i); \\n\"\n\"    float ki_2 = (float)(ki)/2.0; \\n\"\n\"    if(val > middle) \\n\"\n\"    { \\n\"\n\"        val = val - middle; \\n\"\n\"    }else{ \\n\"\n\"        val = middle - val; \\n\"\n\"    } \\n\"\n\"    if(val > ki_2) \\n\"\n\"    { \\n\"\n\"        return 0.0; \\n\"\n\"    }else{ \\n\"\n\"        float border_val = 0.2; \\n\"\n\"        float gaussian = 1.0 - pow((float)val/ki_2, (float)2.0) * (1.0-border_val); \\n\"\n\"        return gaussian * norm; \\n\"\n\"    } \\n\"\n\"} \\n\"\n\" \\n\"\n\"__kernel void NormalInterpolationKernel(__global float* D_kd_tree_values,\"\n\"const unsigned int num_values, __global float* D_kd_tree_splits, \"\n\"const unsigned int num_splits, __global float* D_Normals, \"\n\"const unsigned int num_pointnormals, const unsigned int ki) \\n\"\n\"{ \\n\"\n\"    unsigned int loc_id = get_local_id(0); \\n\"\n\"    unsigned int loc_size = get_local_size(0); \\n\"\n\"    unsigned int glob_id = get_global_id(0); \\n\"\n\"    unsigned int glob_size = get_global_size(0); \\n\"\n\"    unsigned int group_id = get_group_id(0); \\n\"\n\"    unsigned int group_size = get_num_groups(0); \\n\"\n\"    unsigned int tid = glob_id; \\n\"\n\"    const unsigned int offset = glob_size; \\n\"\n\"    for(;tid < num_pointnormals; tid += offset) \\n\"\n\"    { \\n\"\n\"        int c = 0; \\n\"\n\"        unsigned int offset = num_splits; \\n\"\n\"        unsigned int query_index = (unsigned int)(D_kd_tree_values[offset + tid]+ 0.5); \\n\"\n\"        unsigned int nearest_index; \\n\"\n\"        float gaussian = 5.0; \\n\"\n\"        if(query_index < num_pointnormals) \\n\"\n\"        { \\n\"\n\"            float n_x = D_Normals[query_index * 3 + 0]; \\n\"\n\"            float n_y = D_Normals[query_index * 3 + 1]; \\n\"\n\"            float n_z = D_Normals[query_index * 3 + 2]; \\n\"\n\"            if(tid > 1) \\n\"\n\"            { \\n\"\n\"                for(unsigned int i = tid-1; i > 0 && c < ki/2; i--,c++ ) \\n\"\n\"                { \\n\"\n\"                    nearest_index = (unsigned int)(D_kd_tree_values[i + offset]+ 0.5); \\n\"\n\"                    if(nearest_index < num_pointnormals) \\n\"\n\"                    { \\n\"\n\"                        gaussian = getGaussianFactor(i, tid, ki, 5.0); \\n\"\n\"                        n_x += gaussian * D_Normals[nearest_index * 3 + 0]; \\n\"\n\"                        n_y += gaussian * D_Normals[nearest_index * 3 + 1]; \\n\"\n\"                        n_z += gaussian * D_Normals[nearest_index * 3 + 2]; \\n\"\n\"                    } \\n\"\n\"                } \\n\"\n\"            } \\n\"\n\"            if(tid < num_pointnormals-1) \\n\"\n\"            { \\n\"\n\"                for(unsigned int i = tid+1; i < num_pointnormals && c < ki; i++,c++ ) \\n\"\n\"                { \\n\"\n\"                    nearest_index = (unsigned int)(D_kd_tree_values[i + offset]+ 0.5); \\n\"\n\"                    if(nearest_index < num_pointnormals) \\n\"\n\"                    { \\n\"\n\"                        gaussian = getGaussianFactor(i, tid, ki, 5.0); \\n\"\n\"                        n_x += gaussian * D_Normals[nearest_index * 3 + 0]; \\n\"\n\"                        n_y += gaussian * D_Normals[nearest_index * 3 + 1]; \\n\"\n\"                        n_z += gaussian * D_Normals[nearest_index * 3 + 2]; \\n\"\n\"                    } \\n\"\n\"                } \\n\"\n\"            } \\n\"\n\"            float norm = sqrt(pow(n_x,2) + pow(n_y,2) + pow(n_z,2)); \\n\"\n\"            n_x = n_x/norm; \\n\"\n\"            n_y = n_y/norm; \\n\"\n\"            n_z = n_z/norm; \\n\"\n\"            D_Normals[query_index * 3 + 0] = n_x; \\n\"\n\"            D_Normals[query_index * 3 + 1] = n_y; \\n\"\n\"            D_Normals[query_index * 3 + 2] = n_z; \\n\"\n\"        } \\n\"\n\"    } \\n\"\n\"} \\n\";\n\n};\n\n} /* namespace lvr2 */\n\n#endif // !__ClSurface_H\n", "meta": {"hexsha": "a629a37ed0064824fb0dd03f430d05dd9194b78d", "size": 15069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lvr2/reconstruction/opencl/ClSurface.hpp", "max_stars_repo_name": "jtpils/lvr2", "max_stars_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-07T03:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-07T03:55:27.000Z", "max_issues_repo_path": "include/lvr2/reconstruction/opencl/ClSurface.hpp", "max_issues_repo_name": "jtpils/lvr2", "max_issues_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/lvr2/reconstruction/opencl/ClSurface.hpp", "max_forks_repo_name": "jtpils/lvr2", "max_forks_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_forks_repo_licenses": ["BSD-3-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.1258741259, "max_line_length": 96, "alphanum_fraction": 0.5411772513, "num_tokens": 4404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.020023442057000223, "lm_q1q2_score": 0.00683965711676787}}
{"text": "#ifdef COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4;autowrap:nil;-*-\necho $X\n[ ! -d build.$X ] && (mkdir build.$X && cd build.$X && cmake ..)\ncd build.$X && make -j && ctest -j --output-on-failure\nexit\n#endif\n// $CXXX $CXXFLAGS $0 -o $0.$X&&$0.$X&&rm $0.$X;exit\n//  © Alfredo A. Correa 2018-2019\n\n#ifndef BOOST_MULTI_ARRAY_HPP \n#define BOOST_MULTI_ARRAY_HPP\n\n#include \"./array_ref.hpp\"\n#include \"./config/NO_UNIQUE_ADDRESS.hpp\"\n\n#include \"./memory/allocator.hpp\"\n#include \"./detail/memory.hpp\"\n#include \"./detail/adl.hpp\"\n\n#include<memory>\n\nnamespace boost{\nnamespace multi{\n\ntemplate<class Allocator> struct array_allocator{\n\tusing allocator_type = Allocator;\nprotected:\n\tMULTI_NO_UNIQUE_ADDRESS allocator_type alloc_;\n\tallocator_type& alloc(){return alloc_;}\n\tarray_allocator(allocator_type const& a = {}) : alloc_{a}{}\n\ttypename std::allocator_traits<allocator_type>::pointer \n\tallocate(typename std::allocator_traits<allocator_type>::size_type n){\n\t\treturn n?std::allocator_traits<allocator_type>::allocate(alloc_, n):nullptr;\n\t}\n\ttypename std::allocator_traits<allocator_type>::pointer \n\tallocate(typename std::allocator_traits<allocator_type>::size_type n, typename std::allocator_traits<allocator_type>::const_void_pointer hint){\n\t\treturn n?std::allocator_traits<allocator_type>::allocate(alloc_, n, hint):nullptr;\n\t}\n\tauto uninitialized_fill_n(typename std::allocator_traits<allocator_type>::pointer base, typename std::allocator_traits<allocator_type>::size_type num_elements, typename std::allocator_traits<allocator_type>::value_type e){\n\t\treturn adl_alloc_uninitialized_fill_n(alloc_, base, num_elements, e);\n\t}\n\ttemplate<typename It> \n\tauto uninitialized_copy_n(It first, size_type n, typename std::allocator_traits<allocator_type>::pointer data){\n\t\treturn adl_alloc_uninitialized_copy_n(alloc_, first, n, data);\n\t}\n\ttemplate<typename It> \n\tauto destroy_n(It first, size_type n){\n\t\treturn adl_alloc_destroy_n(this->alloc(), first, n);\n\t}\npublic:\n\tallocator_type get_allocator() const{return alloc_;}\n\tfriend allocator_type get_allocator(array_allocator const& s){return s.get_allocator();}\n};\n\ntemplate<class T, class Ptr = T*> struct move_ptr : std::move_iterator<Ptr>{\n\tusing std::move_iterator<Ptr>::move_iterator;\n\texplicit operator Ptr() const{return std::move_iterator<Ptr>::base();}\n};\n\n// static_array is not a value type because it doesn't define assignment for static_arrays of different extensions\ntemplate<class T, dimensionality_type D, class Alloc = std::allocator<T>>\nstruct static_array : \n\tprotected array_allocator<Alloc>,\n\tpublic array_ref<T, D, typename std::allocator_traits<typename array_allocator<Alloc>::allocator_type>::pointer>\n{\nprivate:\n\tusing array_alloc = array_allocator<Alloc>;\npublic:\t\n\tstatic_assert( std::is_same<typename std::allocator_traits<Alloc>::value_type, typename static_array::element>{}, \n\t\t\"allocator value type must match array value type\");\n\tstatic_assert( std::is_same<typename std::allocator_traits<Alloc>::pointer, typename static_array::element_ptr>{}, \n\t\t\"allocator pointer type must match array pointer type\");\n\tusing array_alloc::get_allocator;\n\tusing typename array_allocator<Alloc>::allocator_type;\n//\tusing allocator_type = typename static_array::allocator_type;\n\tusing decay_type = array<T, D, Alloc>;\nprotected:\n\tusing alloc_traits = typename std::allocator_traits<typename static_array::allocator_type>;\n\tusing ref = array_ref<T, D, typename std::allocator_traits<typename std::allocator_traits<Alloc>::template rebind_alloc<T>>::pointer>;\n\tauto uninitialized_value_construct(){\n\t\treturn adl_alloc_uninitialized_value_construct_n(static_array::alloc(), this->base_, this->num_elements());\n\t}\n\tauto uninitialized_default_construct(){\n\t//\treturn std::uninitialized_default_construct_n(this->base_, this->num_elements());\n\t\treturn adl_alloc_uninitialized_default_construct_n(static_array::alloc(), this->base_, this->num_elements());\n\t}\n\ttemplate<typename It> auto uninitialized_copy_elements(It first){\n\t\treturn array_alloc::uninitialized_copy_n(first, this->num_elements(), this->data_elements());\n\t}\n\tvoid destroy_aux(std::false_type){array_alloc::destroy_n(this->data_elements(), this->num_elements());}\n\tvoid destroy_aux(std::true_type ){}\n\tvoid destroy(){destroy_aux(std::is_trivially_destructible<typename static_array::element>{});}\n\tvoid allocate(){this->base_ = array_alloc::allocate(static_array::num_elements());}\npublic:\n\tusing value_type = typename std::conditional<\n\t\t(static_array::dimensionality>1),\n\t\tarray<typename static_array::element, static_array::dimensionality-1, allocator_type>, \n\t\ttypename std::conditional<\n\t\t\tstatic_array::dimensionality == 1,\n\t\t\ttypename static_array::element,\n\t\t\ttypename static_array::element // TODO or void?\n\t\t>::type\n\t>::type;\n\n\tusing typename ref::size_type;\n\tusing typename ref::difference_type;\n\texplicit static_array(typename static_array::allocator_type const& a) : array_alloc{a}{}\nprotected:\n\tstatic_array(static_array&& other, typename static_array::allocator_type const& a) noexcept     //6b\n\t:\tarray_alloc{a},\n\t\tref{other.base_, other.extensions()}\n\t{\n\t\tother.ref::layout_t::operator=({});\n\t\tother.base_ = nullptr;\n\t}\npublic:\n\t// cppcheck-suppress noExplicitConstructor ; because argument can be well-represented\n\tstatic_array(\n\t\tbasic_array<typename static_array::element, static_array::dimensionality, multi::move_ptr<typename static_array::element, typename static_array::element_ptr>>&& other, \n\t\ttypename static_array::allocator_type const& a = {}\n\t) noexcept : \n\t\tarray_alloc{a},\n\t\tref{\n\t\t\tother.layout()==typename static_array::layout_t(other.extensions())?\n\t\t\t\tother.base_.base():\n\t\t\t\tarray_alloc::allocate(other.num_elements())\n\t\t\t,\n\t\t\tother.extensions()\n\t\t}\n\t{\n\t\tif(other.base_.base() != static_array::base_)\n\t\t\trecursive<D>::alloc_uninitialized_copy(static_array::alloc(), \n\t\t\t\tother.template static_array_cast<typename static_array::element, typename static_array::element_ptr>().begin(), \n\t\t\t\tother.template static_array_cast<typename static_array::element, typename static_array::element_ptr>().end()  , \n\t\t\t\tthis->begin()\n\t\t\t);\n\t}\n//\ttemplate<class Array>//, std::enable_if_t<std::is_same<Array, basic_array>{}, int> =0> \n//\tauto operator==(Array&& o) const&\n//\t->decltype(std::move(modify(*this)).ref::operator==(std::forward<Array>(o))){\n//\t\treturn std::move(modify(*this)).ref::operator==(std::forward<Array>(o));}\n\n//\tauto operator==(static_array const& o) const&{return std::move(modify(*this)).ref::operator==(std::move(modify(o)));}\n\n\ttemplate<class TT, class... Args>\n\tbool operator==(basic_array<TT, D, Args...> const& other) const{\n\t\treturn ref::operator==(other);\n\t}\n\n\ttemplate<class It, class=typename std::iterator_traits<std::decay_t<It>>::difference_type>//edecltype(std::distance(std::declval<It>(), std::declval<It>()), *std::declval<It>())>      \n\t// analogous to std::vector::vector (5) https://en.cppreference.com/w/cpp/container/vector/vector\n\tstatic_array(It first, It last, typename static_array::allocator_type const& a = {}) : \n\t\tarray_alloc{a},\n\t\tref{\n\t\t\tarray_alloc::allocate(typename static_array::layout_t{index_extension(adl_distance(first, last))*multi::extensions(*first)}.num_elements()), \n\t\t\tindex_extension(adl_distance(first, last))*multi::extensions(*first)\n\t\t}\n\t{\n//\t\trecursive<D>::alloc_uninitialized_copy(static_array::alloc(), first, last, this->begin());\n\t\tadl_alloc_uninitialized_copy(static_array::alloc(), first, last, ref::begin());\n//\t\tadl::uninitialized_copy(first, last, ref::begin());\n\t}\n\n\ttemplate<\n\t\tclass Range, class=std::enable_if_t<not std::is_base_of<static_array, std::decay_t<Range>>{}>, \n\t\tclass=decltype(/*static_array*/(std::declval<Range&&>().begin(), std::declval<Range&&>().end())), // instantiation of static_array here gives a compiler error in 11.0\n\t\tclass=std::enable_if_t<not is_basic_array<Range&&>{}>// TODO add is_assignable<value_type> check\n\t> \n\t// cppcheck-suppress noExplicitConstructor ; because I want to use equal for lazy assigments form range-expressions\n\tstatic_array(Range&& rng) : static_array(std::forward<Range>(rng).begin(), std::forward<Range>(rng).end()){}\n\n\ttemplate<class TT> \n\tauto uninitialized_fill_elements(TT const& value){\n\t\treturn array_alloc::uninitialized_fill_n(this->data_elements(), this->num_elements(), value);\n\t}\n\n\ttemplate<class TT, class... As> \n\t// cppcheck-suppress noExplicitConstructor ; because argument can be well-represented\n\tstatic_array(array_ref<TT, D, As...> const& other, typename static_array::allocator_type const& a = {}) :\n\t\tarray_alloc{a},\n\t\tref{array_alloc::allocate(other.num_elements()), other.extensions()}\n\t{\n\t\tadl_alloc_uninitialized_copy_n(static_array::alloc(), other.data_elements(), other.num_elements(), this->data_elements());\n\t}\n\n\tstatic_array(typename static_array::extensions_type x, typename static_array::element const& e, typename static_array::allocator_type const& a) : //2\n\t\tarray_alloc{a}, \n\t\tref(array_alloc::allocate(typename static_array::layout_t{x}.num_elements()), x)\n\t{\n\t\tarray_alloc::uninitialized_fill_n(this->data_elements(), this->num_elements(), e);\n\t}\n\ttemplate<class Element, std::enable_if_t<std::is_convertible<Element, typename static_array::element>{} and D==0, int> = 0>\n\texplicit static_array(Element const& e, typename static_array::allocator_type const& a) :\n\t\tstatic_array(typename static_array::extensions_type{}, e, a){}\n\n\tstatic_array(typename static_array::extensions_type x, typename static_array::element const& e) : //2\n\t\tarray_alloc{}, ref(array_alloc::allocate(typename static_array::layout_t{x}.num_elements()), x)\n\t{\n\t\tarray_alloc::uninitialized_fill_n(this->base(), this->num_elements(), e);\n\t}\n\texplicit static_array(typename static_array::extensions_type x, typename std::allocator_traits<Alloc>::const_void_pointer hint) :\n\t\tarray_alloc{}, ref(array_alloc::allocate(typename static_array::layout_t{x}.num_elements(), hint), x)\n\t{}\n//\ttemplate<class Elem, typename = std::enable_if_t<std::is_convertible<Elem, typename static_array::element>{} and D==0>>\n//\tstatic_array(Elem const& e)  //2\n//\t:\tstatic_array(multi::iextensions<D>{}, e){}\n\n//\texplicit static_array(typename static_array::index n, typename static_array::value_type const& v, typename static_array::allocator_type const& a = {})\n//\t: \tstatic_array(typename static_array::index_extension(n), v, a){}\n\ttemplate<class ValueType, typename = std::enable_if_t<std::is_same<ValueType, typename static_array::value_type>{}>>\n\texplicit static_array(typename static_array::index_extension const& e, ValueType const& v, typename static_array::allocator_type const& a = {}) //3\n\t= delete;\n//\t: static_array(e*extensions(v), a) {\n//\t\tadl::fill(this->begin(), this->end(), v); // TODO this should be alloc_unintialized_fill\n//\t}\n//\ttemplate<class Allocator, typename = std::enable_if_t<std::is_same<Allocator, allocator_type>{}> >\n//\texplicit \n// analgous to std::vector::vector ((4)) https://en.cppreference.com/w/cpp/container/vector/vector\n\texplicit static_array(typename static_array::extensions_type x, typename static_array::allocator_type const& a = typename static_array::allocator_type{}) :\n\t\tarray_alloc{a}, ref{array_alloc::allocate(typename static_array::layout_t{x}.num_elements()), x}\n\t{\n\t\tif(not std::is_trivially_default_constructible<typename static_array::element_type>{})\n\t\t\tuninitialized_default_construct();\n\t}\n\ttemplate<class TT, class... Args, \n\t\tclass=std::enable_if_t<std::is_assignable<typename ref::element_ref, typename multi::basic_array<TT, D, Args...>::element>{}>,\n\t\tclass=decltype(adl_copy(std::declval<multi::basic_array<TT, D, Args...> const&>().begin(), std::declval<multi::basic_array<TT, D, Args...> const&>().end(), std::declval<typename static_array::iterator>()))\n\t>\n\t// cppcheck-suppress noExplicitConstructor ; because argument can be well-represented\n\tstatic_array(multi::basic_array<TT, D, Args...> const& o, typename static_array::allocator_type const& a = {})\n\t: static_array(o.extensions(), a) // TODO: should be uninitialized_copy\n\t{\n\t\tadl_copy(o.begin(), o.end(), this->begin()); // TODO: should be uninitialized_copy, and recursive\n\t}\n\n\ttemplate<class TT, class... Args>\n\t// cppcheck-suppress noExplicitConstructor ; because argument can be well-represented\n\tstatic_array(array_ref<TT, D, Args...>&& o)\n\t: array_alloc{}, ref{array_alloc::allocate(o.num_elements()), o.extensions()}{\n\t\tstatic_array::uninitialized_copy_elements(std::move(o).data_elements());\n\t}\n\tstatic_array(static_array const& o, typename static_array::allocator_type const& a) //5b\n\t: array_alloc{a}, ref{static_array::allocate(num_elements(o)), extensions(o)}{\n\t\tuninitialized_copy_from(data(o));\n\t}\n\tstatic_array(static_array const& o)                                  //5b\n\t: array_alloc{o.get_allocator()}, ref{array_alloc::allocate(num_elements(o)), extensions(o)}{\n\t\tuninitialized_copy_elements(o.data_elements());\n\t}\n//\tTODO static_array(static_array&& o)                                  //5b'\n//\t: array_alloc{o.get_allocator()}, ref{array_alloc::allocate(num_elements(o)), extensions(o)}{\n//\t\tarray_alloc::uninitialized_move_elements(data_elements(o));\n//\t}\n\t// cppcheck-suppress noExplicitConstructor ; to allow assigment-like construction of nested arrays\n\tconstexpr static_array(std::initializer_list<typename static_array<T, D>::value_type> mil) : \n\t\tstatic_array(static_array<T, D>(mil.begin(), mil.end()))\n\t{}\n\tstatic_array(\n\t\tstd::initializer_list<typename static_array<T, D>::value_type> mil, \n\t\ttypename static_array::allocator_type const& a\n\t) : static_array(static_array<T, D>(mil.begin(), mil.end()), a){}\n\ttemplate<class TT, std::size_t N> \n\t// cppcheck-suppress noExplicitConstructor ; to allow assigment-like construction from c-arrays\n\tconstexpr static_array(TT(&array)[N]) : static_array(std::begin(array), std::end(array)){}\n\ttemplate<class It> static auto distance(It a, It b){using std::distance; return distance(a, b);}\nprotected:\n\tvoid deallocate(){\n\t\tif(this->num_elements()) alloc_traits::deallocate(this->alloc(), this->base_, static_cast<typename alloc_traits::size_type>(this->num_elements()));\n\t}\n\tvoid clear() noexcept{\n\t\tthis->destroy();\n\t\tdeallocate();\n\t\tlayout_t<D>::operator=({});\n\t}\n\ttemplate<class... Ts>\n\tconstexpr static_array&& reindex(Ts... a)&&{\n\t\tstatic_array::layout_t::reindex(a...);\n\t\treturn std::move(*this);\n\t}\n\ttemplate<class... Ts>\n\tconstexpr static_array& reindex(Ts... a)&{\n\t\tstatic_array::layout_t::reindex(a...);\n\t\treturn *this;\n\t}\npublic:\n\tstatic_array() = default;\n\t~static_array() noexcept{destroy(); deallocate();}\n\tusing element_const_ptr = typename std::pointer_traits<typename static_array::element_ptr>::template rebind<typename static_array::element const>;\n\tusing element_move_ptr  = std::move_iterator<typename static_array::element_ptr>;\n\tusing reference = typename std::conditional<\n\t\t(static_array::dimensionality > 1), \n\t\tbasic_array<typename static_array::element, static_array::dimensionality-1, typename static_array::element_ptr>, \n\t\ttypename std::conditional<\n\t\t\tstatic_array::dimensionality == 1,\n\t\t\ttypename std::iterator_traits<typename static_array::element_ptr>::reference,\n\t\t\tvoid\n\t\t>::type\n\t//\ttypename pointer_traits<typename static_array::element_ptr>::element_type&\n\t>::type;\n\tusing const_reference = typename std::conditional<\n\t\t(static_array::dimensionality > 1), \n\t\tbasic_array<typename static_array::element, static_array::dimensionality-1, typename static_array::element_const_ptr>, // TODO should be const_reference, but doesn't work witn rangev3\n\t\ttypename std::conditional<\n\t\t\tstatic_array::dimensionality == 1,\n\t\t\tdecltype(*std::declval<typename static_array::element_const_ptr>()),\n\t\t//\ttypename std::iterator_traits<typename static_array::element_const_ptr>::reference,\n\t\t\tvoid\n\t\t>::type\n\t//\ttypename pointer_traits<typename static_array::element_ptr>::element_type const&\n\t>::type;\n\tusing       iterator = multi::array_iterator<T, static_array::dimensionality, typename static_array::element_ptr      >;//, reference>;\n\tusing const_iterator = multi::array_iterator<T, static_array::dimensionality, typename static_array::element_const_ptr>;//, const_reference>;\n//\treference\n//\t      reference operator[](index i)     &&{return std::move(*this).ref::operator[](i);}\n//\t      reference operator[](index i)      &{return ref::operator[](i);}\n//\tconst_reference operator[](index i) const&{return ref::operator[](i);}\n//\ttypename static_array::allocator_type get_allocator() const{return static_cast<typename static_array::allocator_type const&>(*this);}\n\tfriend typename static_array::allocator_type get_allocator(static_array const& self){return self.get_allocator();}\n\n//\t[[deprecated(\"use ::data_elements()\")]] typename static_array::element_ptr data()       {return ref::data_elements();}\n//\t[[deprecated(\"use ::data_elements()\")]] constexpr auto data() const{return typename static_array::element_const_ptr{ref::data_elements()};}\n//#ifndef __NVCC__ // deprecated friend doesn't work in nvcc\n//\t[[deprecated(\"use data_elements()\")]] \n//#else\n//\t__attribute__((deprecated))\n//#endif\n//\tfriend typename static_array::element_ptr       data(static_array&       s){return s.data_elements();}\n//#ifndef __NVCC__ // deprecated friend doesn't work in nvcc\n//\t[[deprecated(\"use data_elements()\")]] \n//#else\n//\t__attribute__((deprecated))\n//#endif\n//\tfriend typename static_array::element_const_ptr data(static_array const& s){return s.data_elements();}\n\n\telement_const_ptr                   data_elements() const&{return this->base_;}\n\ttypename static_array::element_ptr  data_elements()      &{return this->base_;}\n\tstatic_array::element_move_ptr      data_elements()     &&{return std::make_move_iterator(this->base_);}\n\n\tfriend auto data_elements(static_array const& s){return           s .data_elements();}\n\tfriend auto data_elements(static_array      & s){return           s .data_elements();}\n\tfriend auto data_elements(static_array     && s){return std::move(s).data_elements();}\n\n\tconstexpr typename static_array::element_ptr       base()      {return ref::base();}\n\tconstexpr typename static_array::element_const_ptr base() const{return typename static_array::element_const_ptr{ref::base()};}\n\tfriend typename static_array::element_ptr       base(static_array&       s){return s.base();}\n\tfriend typename static_array::element_const_ptr base(static_array const& s){return s.base();}\n\n\ttypename static_array::element_ptr       origin()      {return ref::origin();}\n\ttypename static_array::element_const_ptr origin() const{return ref::origin();}\n\tfriend typename static_array::element_ptr       origin(static_array&       s){return s.origin();}\n\tfriend typename static_array::element_const_ptr origin(static_array const& s){return s.origin();}\n\n//\ttemplate<class... Args> decltype(auto) operator()(Args const&... args)&{return ref::operator()(args...);}\n//\ttemplate<class... Args> decltype(auto) operator()(Args const&... args) const&{return ref::operator()(args...);}\n//\tusing ref::operator();\n\n//\tbasic_array<T, D, typename static_array::element_ptr> \n//\tdecltype(auto) operator()() &{\n//\t\tthis->template static_array_cast<typename static_array::element_type>();\n\t//\treturn static_array_cast<typename static_array::element_type>(*this);//(std::forward<Ts>(t)...);\n\t//\treturn ref::operator()();\n\t//\treturn *this;\n//\t}\n//\tbasic_array<T, D, typename static_array::element_const_ptr> operator()() const&{\n//\t\tthis->template static_array_cast<typename static_array::element_type>();\n\t//\treturn static_array_cast<typename static_array::element_type const>(*this);\n\t//\treturn basic_array<T, D, typename static_array::element_const_ptr>{this->layout(), this->base_};\n//\t}\n//\ttemplate<class... Ts> decltype(auto) operator()(Ts&&... t) &     {assert(0); return ref::operator()(std::forward<Ts>(t)...);}\n//\ttemplate<class... Ts> decltype(auto) operator()(Ts&&... t) &&    {return std::move(*this).ref::operator()(std::forward<Ts>(t)...);}\n//\ttemplate<class... Ts> decltype(auto) operator()(Ts&&... t) const&{return ref::operator()(std::forward<Ts>(t)...);}\n\n//\ttemplate<class... Ts> decltype(auto) operator()(Ts&&... t) const{return static_array_cast<typename static_array::element_type const>(*this)(std::forward<Ts>(t)...);}\n\n#if 0\n\ttemplate<class... As> decltype(auto) paren(index a, As... as) &     {return ref::paren(a, std::forward<As>(as)...);}\n\ttemplate<class... As> decltype(auto) paren(index a, As... as) && = delete;//{return ref::operator()(a, std::forward<As>(as)...);}\n\ttemplate<class... As> decltype(auto) paren(index a, As... as) const&{return ref::paren(a, std::forward<As>(as)...);}\n\n\ttemplate<class... As> decltype(auto) paren(index_range a, As... as) &{return ref::paren(a, std::forward<As>(as)...);}\n\ttemplate<class... As> decltype(auto) paren(index_range a, As... as) && = delete;//{return ref::operator()(a, std::forward<As>(as)...);}\n\ttemplate<class... As> decltype(auto) paren(index_range a, As... as) const&{return ref::paren(a, std::forward<As>(as)...);}\n\n\tdecltype(auto) operator()(index i) & {return operator[](i);}\n\tdecltype(auto) operator()(index i) && {return std::move(*this).operator[](i);}\n\tdecltype(auto) operator()(index i) const& {return operator[](i);}\n//#define SARRAY1(A1) auto operator()(A1 a1) const{return operator()<>(a1);}\n#define SARRAY2(A1, A2)\t\\\n\tauto operator()(A1 a1, A2 a2) const& JUSTRETURN(paren<A2>(a1, a2)) \\\n\tauto operator()(A1 a1, A2 a2) && = delete;/*     JUSTRETURN(std::move(*this).static_array::template paren<A2>(a1, a2))*/ \\\n\tauto operator()(A1 a1, A2 a2) &      JUSTRETURN(paren<A2>(a1, a2))  \n\tSARRAY2(index, index ); SARRAY2(irange, index );\n\tSARRAY2(index, irange); SARRAY2(irange, irange);\n#undef SARRAY2\n#if 0\n#define SARRAY3(A1, A2, A3) auto operator()(A1 a1, A2 a2, A3 a3) const{return operator()<A2, A3>(a1, a2, a3);} auto operator()(A1 a1, A2 a2, A3 a3){return operator()<A2, A3>(a1, a2, a3);}\n\tSARRAY3(index, index , index ); SARRAY3(irange, index , index );\n\tSARRAY3(index, index , irange); SARRAY3(irange, index , irange);\n\tSARRAY3(index, irange, index ); SARRAY3(irange, irange, index );\n\tSARRAY3(index, irange, irange); SARRAY3(irange, irange, irange);\n#undef SARRAY3\n#define SARRAY4(A1, A2, A3, A4) auto operator()(A1 a1, A2 a2, A3 a3, A4 a4) const{return operator()<A2, A3, A4>(a1, a2, a3, a4);} auto operator()(A1 a1, A2 a2, A3 a3, A4 a4) {return operator()<A2, A3, A4>(a1, a2, a3, a4);}\n\tSARRAY4(index, index, index , index ); SARRAY4(index, irange, index , index );\n\tSARRAY4(index, index, index , irange); SARRAY4(index, irange, index , irange);\n\tSARRAY4(index, index, irange, index ); SARRAY4(index, irange, irange, index );\n\tSARRAY4(index, index, irange, irange); SARRAY4(index, irange, irange, irange);\n\tSARRAY4(irange, index, index , index ); SARRAY4(irange, irange, index , index );\n\tSARRAY4(irange, index, index , irange); SARRAY4(irange, irange, index , irange);\n\tSARRAY4(irange, index, irange, index ); SARRAY4(irange, irange, irange, index );\n\tSARRAY4(irange, index, irange, irange); SARRAY4(irange, irange, irange, irange);\n#undef SARRAY4\n#endif\n#endif\n//\tusing const_reverse_iterator = basic_reverse_iterator<const_iterator>;\n\tconstexpr auto rotated(dimensionality_type d = 1) const&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.rotate(d);\n\t\treturn basic_array<T, D, typename static_array::element_const_ptr>{new_layout, this->base_};\n\t}\n\tconstexpr auto rotated(dimensionality_type d = 1)&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.rotate(d);\n\t\treturn basic_array<T, D, typename static_array::element_ptr>{new_layout, this->base_};\n\t}\n\tconstexpr auto rotated(dimensionality_type d = 1)&&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.rotate(d);\n\t\treturn basic_array<T, D, typename static_array::element_ptr>{new_layout, this->base_};\n\t}\n//\tfriend decltype(auto) rotated(static_array const& self){return self.rotated();}\n//\ttemplate<class Array, typename = std::enable_if_t<std::is_same<static_array, std::decay_t<Array>>{}> > \n\tfriend constexpr decltype(auto) rotated(static_array&       s){return s.rotated();}\n\tfriend constexpr decltype(auto) rotated(static_array const& s){return s.rotated();}\n\n\tconstexpr auto unrotated(dimensionality_type d = 1) const&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.unrotate(d);\n\t\treturn basic_array<T, D, typename static_array::element_const_ptr>{new_layout, this->base_};\n\t}\n\tconstexpr auto unrotated(dimensionality_type d = 1)&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.unrotate(d);\n\t\treturn basic_array<T, D, typename static_array::element_ptr>{new_layout, this->base_};\n\t}\n\tfriend constexpr decltype(auto) unrotated(static_array& self){return self.unrotated();}\n\tfriend constexpr decltype(auto) unrotated(static_array const& self){return self.unrotated();}\n\n\tconstexpr decltype(auto) operator<<(dimensionality_type d)      {return   rotated(d);}\n\tconstexpr decltype(auto) operator>>(dimensionality_type d)      {return unrotated(d);}\n\tconstexpr decltype(auto) operator<<(dimensionality_type d) const{return   rotated(d);}\n\tconstexpr decltype(auto) operator>>(dimensionality_type d) const{return unrotated(d);}\n\n\tstatic_array& operator=(static_array const& other) &{\n\t\tassert( extensions(other) == static_array::extensions() );\n\t\tadl_copy_n(other.data_elements(), other.num_elements(), this->data_elements());\n\t\treturn *this;\n\t}\n\ttemplate<class TT, class... As>\n\tstatic_array& operator=(static_array<TT, static_array::dimensionality, As...> const& other)&{assert( extensions(other) == static_array::extensions() );\n\t\tadl_copy_n(other.data_elements(), other.num_elements(), this->data_elements());\n\t\treturn *this;\n\t}\n//\ttemplate<class... As>\n//\tstatic_array operator=(static_array<static_array::value_type, static_array::dimensionality, As...> const& o){assert( extensions(o) == static_array::extensions() );\n//\t\treturn adl::copy_elements(o.data_elements()), *this;\n//\t}\n\tconstexpr operator basic_array<typename static_array::value_type, static_array::dimensionality, typename static_array::element_const_ptr, typename static_array::layout_t>()&{\n\t\treturn this->template static_array_cast<typename static_array::value_type, typename static_array::element_const_ptr>(*this);\n//\t\treturn static_array_cast<typename static_array::value_type, typename static_array::element_const_ptr>(*this);\n\t}\n};\n\ntemplate<class T, class Alloc>\nstruct static_array<T, dimensionality_type{0}, Alloc> : \n\tprotected array_allocator<Alloc>,\n\tpublic array_ref<T, 0, typename std::allocator_traits<typename array_allocator<Alloc>::allocator_type>::pointer>\n{\nprivate:\n\tusing array_alloc = array_allocator<Alloc>;\npublic:\t\n\tstatic_assert( std::is_same<typename std::allocator_traits<Alloc>::value_type, typename static_array::element>{}, \n\t\t\"allocator value type must match array value type\");\n\tusing array_alloc::get_allocator;\n\tusing allocator_type = typename static_array::allocator_type;\nprotected:\n\tusing alloc_traits = typename std::allocator_traits<allocator_type>;\n\tusing ref = array_ref<T, 0, typename std::allocator_traits<typename std::allocator_traits<Alloc>::template rebind_alloc<T>>::pointer>;\n\tauto uninitialized_value_construct(){return adl_alloc_uninitialized_value_construct_n(static_array::alloc(), this->base_, this->num_elements());}\n\ttemplate<typename It> auto uninitialized_copy(It first){return adl_alloc_uninitialized_copy_n(this->alloc(), first, this->num_elements(), this->data_elements());}\n\ttemplate<typename It>\n\tauto uninitialized_move(It first){\n\t\treturn adl_alloc_uninitialized_move_n(this->alloc(), first, this->num_elements(), this->data_elements());\n\t}\n\tvoid destroy(){array_alloc::destroy_n(this->data_elements(), this->num_elements());}\npublic:\n\tusing typename ref::value_type;\n\tusing typename ref::size_type;\n\tusing typename ref::difference_type;\n\tconstexpr explicit static_array(allocator_type const& a) : array_alloc{a}{}\nprotected:\n\tconstexpr static_array(static_array&& other, allocator_type const& a)                           //6b\n\t:\tarray_alloc{a},\n\t\tref{other.base_, other.extensions()}\n\t{\n\t\tother.ref::layout_t::operator=({});\n\t}\npublic:\n\tusing ref::operator==;\n\tusing ref::operator!=;\n\t\n\ttemplate<class TT, \n\t\tstd::enable_if_t<std::is_constructible<T, TT>{}, int>* = nullptr, \n\t\tclass = decltype(adl_uninitialized_copy_n(&std::declval<TT&>(), 1, std::declval<typename static_array::element_ptr&>()))\n\t>\n\t// cppcheck-suppress noExplicitConstructor ; because I want to use equal for lazy assigments form range-expressions\n\tstatic_array(TT&& tt) : ref(static_array::allocate(typename static_array::layout_t{}.num_elements()), {}){\n\t\tadl_uninitialized_copy_n(&tt, 1, this->base());\n\t}\n//\ttemplate<class Range0, \n//\t\tstd::enable_if_t<std::is_constructible<typename static_array::element, typename Range0::element>{}, int>* = nullptr, \n//\t\tclass = decltype(adl_uninitialized_copy_n(&std::declval<Range0&>(), 1, std::declval<typename static_array::element_ptr&>()))\n//\t>\n////\ttemplate<class Range0, class = decltype(adl_uninitialized_copy_n(&std::declval<Range0&>(), 1, std::declval<typename static_array::element_ptr&>()))>\n//\t// cppcheck-suppress noExplicitConstructor ; because I want to use equal for lazy assigments form range-expressions\n//\tstatic_array(Range0&& r) : ref(static_array::allocate(typename static_array::layout_t{}.num_elements()), {}){\n//\t\tadl_uninitialized_copy_n(&r, 1, this->base());\n//\t}\n\tstatic_array(typename static_array::extensions_type x, typename static_array::element const& e, allocator_type const& a) : //2\n\t\tarray_alloc{a}, \n\t\tref(static_array::allocate(typename static_array::layout_t{x}.num_elements()), x)\n\t{\n\t\tuninitialized_fill(e);\n\t}\n\tstatic_array(typename static_array::element_type const& e, allocator_type const& a)\n\t\t: static_array(typename static_array::extensions_type{}, e, a){}\n\tauto uninitialized_fill(typename static_array::element const& e){array_alloc::uninitialized_fill_n(this->base_, this->num_elements(), e);}\n\tstatic_array(typename static_array::extensions_type const& x, typename static_array::element const& e)  //2\n\t\t: array_alloc{}, ref(static_array::allocate(typename static_array::layout_t{x}.num_elements()), x)\n\t{\n\t\tuninitialized_fill(e);\n\t}\n\n\tstatic_array() : static_array(multi::iextensions<0>{}){}\n\n\texplicit static_array(typename static_array::element const& e)  //2\n\t\t: static_array(multi::iextensions<0>{}, e)\n\t{}\n\n\ttemplate<class ValueType, typename = std::enable_if_t<std::is_same<ValueType, typename static_array::value_type>{}>> \n\texplicit static_array(typename static_array::index_extension const& e, ValueType const& v, allocator_type const& a = {}) //3\n\t\t: static_array(e*extensions(v), a)\n\t{\n\t\tusing std::fill; fill(this->begin(), this->end(), v);\n\t}\n\n\texplicit static_array(typename static_array::extensions_type const& x, allocator_type const& a = {}) //3\n\t: array_alloc{a}, ref{static_array::allocate(typename static_array::layout_t{x}.num_elements()), x}{\n\t\tif(not std::is_trivially_default_constructible<typename static_array::element>{}) uninitialized_value_construct();\n\t}\n\ttemplate<class TT, class... Args> \n\t// cppcheck-suppress noExplicitConstructor ; because argument can be well-represented\n\tstatic_array(multi::basic_array<TT, 0, Args...> const& other, allocator_type const& a = {})\n\t\t: array_alloc{a}, ref(static_array::allocate(other.num_elements()), extensions(other))\n\t{\n\t\tusing std::copy; copy(other.begin(), other.end(), this->begin());\n\t}\n\ttemplate<class TT, class... Args> \n\t// cppcheck-suppress noExplicitConstructor ; because argument can be well-represented\n\tstatic_array(array_ref<TT, 0, Args...> const& other)\n\t:\tarray_alloc{}, ref{static_array::allocate(other.num_elements()), extensions(other)}{\n\t\tuninitialized_copy_(other.data_elements());\n\t}\n\tstatic_array(static_array const& other, allocator_type const& a)                      //5b\n\t:\tarray_alloc{a}, ref{static_array::allocate(other.num_elements()), extensions(other)}{\n\t//\tassert(0);\n\t\tuninitialized_copy_(other.data_elements());\n\t}\n\tstatic_array(static_array const& o) :                                  //5b\n\t\tarray_alloc{o.get_allocator()}, \n\t\tref{static_array::allocate(o.num_elements()), o.extensions()}\n\t{\n\t\tuninitialized_copy(o.data_elements());\n\t}\n\tstatic_array(static_array&& o) :       // it is private because it is a valid operation for derived classes //5b\n\t\tarray_alloc{o.get_allocator()}, \n\t\tref{static_array::allocate(o.num_elements()), o.extensions()}\n\t{\n\t\tuninitialized_move(o.data_elements()); // TODO: uninitialized_move?\n\t}\n\ttemplate<class It> static auto distance(It a, It b){using std::distance; return distance(a, b);}\nprotected:\n\tvoid deallocate(){ // TODO move this to array_allocator\n\t\tif(this->num_elements()) alloc_traits::deallocate(this->alloc(), this->base_, static_cast<typename alloc_traits::size_type>(this->num_elements()));\n\t}\n\tvoid clear() noexcept{\n\t\tthis->destroy();\n\t\tdeallocate();\n\t\tlayout_t<0>::operator=({});\n\t}\npublic:\n//\tstatic_array() = default;\n\t~static_array() noexcept{\n\t\tthis->destroy();\n\t\tdeallocate();\n\t}\n\tusing element_const_ptr = typename std::pointer_traits<typename static_array::element_ptr>::template rebind<typename static_array::element const>;\n\tfriend allocator_type get_allocator(static_array const& self){return self.get_allocator();}\n\n//\t[[deprecated(\"use data_elements() instead of data()\")]]\n//\tconstexpr typename static_array::element_ptr       data()      {return ref::data_elements();}\n//\t[[deprecated(\"use data_elements() instead of data()\")]]\n//\tconstexpr auto data() const{return typename static_array::element_const_ptr{ref::data_elements()};}\n\n\t// TODO find how to use `deprecated` with nvcc\n//\tfriend constexpr typename static_array::element_ptr       data(static_array&       s)\n//\t{return s.data_elements();}\n//\tfriend constexpr typename static_array::element_const_ptr data(static_array const& s)\n//\t{return s.data_elements();}\n\n\t       constexpr typename static_array::element_ptr       base()                 &   {return ref::base();}\n\t       constexpr typename static_array::element_const_ptr base()            const&   {return ref::base();}\n\tfriend constexpr typename static_array::element_ptr       base(static_array&       s){return s.base();}\n\tfriend constexpr typename static_array::element_const_ptr base(static_array const& s){return s.base();}\n\n\tconstexpr typename static_array::element_ptr       origin()      {return ref::origin();}\n\tconstexpr typename static_array::element_const_ptr origin() const{return ref::origin();}\n\tfriend constexpr typename static_array::element_ptr       origin(static_array&       s){return s.origin();}\n\tfriend constexpr typename static_array::element_const_ptr origin(static_array const& s){return s.origin();}\n\n//\ttemplate<class... Args> decltype(auto) operator()(Args const&... args)&{return ref::operator()(args...);}\n//\ttemplate<class... Args> decltype(auto) operator()(Args const&... args) const&{return ref::operator()(args...);}\n\n//\tusing ref::operator typename static_array::element_ref;//{return *(this->base_);}\n//\toperator decltype(auto)(){return *(this->base_);}\n//\toperator decltype(auto)() const{return *(this->base_);}\n//\toperator typename static_array::element_type() const{return *(this->base_);}\n//\tusing ref::operator();\t\n//\toperator typename static_array::element_ref() const& = delete;//{return *(this->base_);}\n\tconstexpr operator typename std::iterator_traits<typename static_array::element_const_ptr>::reference() const&{\n\t\treturn *(this->base_);\n\t}\n\tconstexpr operator typename std::add_rvalue_reference<typename std::iterator_traits<typename static_array::element_ptr>::reference>::type()&&{\n\t\treturn *(this->base_);\n\t}\n\tconstexpr operator typename std::iterator_traits<typename static_array::element_ptr>::reference()&{\n\t\treturn *(this->base_);\n\t}\n\tconstexpr explicit operator typename std::iterator_traits<typename static_array::element_const_ptr>::value_type(){\n\t\treturn *(this->base_);\n\t}\n//\tbasic_array<T, D, typename static_array::element_ptr> \n//\tdecltype(auto) operator()()&{\n//\t\treturn ref::operator()();\n\t//\treturn *this;\n//\t}\n//\tbasic_array<T, 0, typename static_array::element_const_ptr> operator()() const&{\n//\t\treturn basic_array<T, 0, typename static_array::element_const_ptr>{this->layout(), this->base_};\n//\t}\n\n//\ttypename std::iterator_traits<typename static_array::element_const_ptr>::reference operator()() const&{\n//\t\treturn *(this->base_);\n//\t}\n\n\n//\tusing const_reverse_iterator = basic_reverse_iterator<const_iterator>;\n\tconstexpr auto rotated(dimensionality_type d = 1) const&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.rotate(d);\n\t\treturn basic_array<T, 0, typename static_array::element_const_ptr>{new_layout, this->base_};\n\t}\n\tconstexpr auto rotated(dimensionality_type d = 1)&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.rotate(d);\n\t\treturn basic_array<T, 0, typename static_array::element_ptr>{new_layout, this->base_};\n\t}\n\tconstexpr auto rotated(dimensionality_type d = 1)&&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.rotate(d);\n\t\treturn basic_array<T, 0, typename static_array::element_ptr>{new_layout, this->base_};\n\t}\n//\tfriend decltype(auto) rotated(static_array const& self){return self.rotated();}\n//\ttemplate<class Array, typename = std::enable_if_t<std::is_same<static_array, std::decay_t<Array>>{}> > \n\tfriend constexpr decltype(auto) rotated(static_array&       s){return s.rotated();}\n\tfriend constexpr decltype(auto) rotated(static_array const& s){return s.rotated();}\n\n\tconstexpr auto unrotated(dimensionality_type d = 1) const&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.unrotate(d);\n\t\treturn basic_array<T, 0, typename static_array::element_const_ptr>{new_layout, this->base_};\n\t}\n\tconstexpr auto unrotated(dimensionality_type d = 1)&{\n\t\ttypename static_array::layout_t new_layout = *this;\n\t\tnew_layout.unrotate(d);\n\t\treturn basic_array<T, 0, typename static_array::element_ptr>{new_layout, this->base_};\n\t}\n\tfriend constexpr decltype(auto) unrotated(static_array& self){return self.unrotated();}\n\tfriend constexpr decltype(auto) unrotated(static_array const& self){return self.unrotated();}\n\n\tconstexpr decltype(auto) operator<<(dimensionality_type d){return rotated(d);}\n\tconstexpr decltype(auto) operator>>(dimensionality_type d){return unrotated(d);}\n\tconstexpr decltype(auto) operator<<(dimensionality_type d) const{return rotated(d);}\n\tconstexpr decltype(auto) operator>>(dimensionality_type d) const{return unrotated(d);}\n\n\tstatic_array& operator=(static_array const& other){assert( extensions(other) == static_array::extensions() );\n\t\tadl_copy_n(other.data_elements(), other.num_elements(), this->data_elements());\n\t\treturn *this;\n\t}\n\ttemplate<class TT, class... As>\n\tconstexpr static_array& operator=(static_array<TT, static_array::dimensionality, As...> const& other)&{assert( extensions(other) == static_array::extensions() );\n\t\tadl_copy_n(other.data_elements(), other.num_elements(), this->data_elements());\n\t\treturn *this;\n\t}\n\n\tconstexpr operator basic_array<typename static_array::value_type, static_array::dimensionality, typename static_array::element_const_ptr, typename static_array::layout_t>()&{\n\t\treturn this->template static_array_cast<typename static_array::value_type, typename static_array::element_const_ptr>();\n\t//\treturn static_array_cast<typename static_array::value_type, typename static_array::element_const_ptr>(*this);\n\t}\n\t\n\ttemplate<class Archive>\n\tauto serialize(Archive& ar, const unsigned int version){\n//\t\tauto extensions = this->extensions();\n//\t\tusing boost::serialization::make_nvp;\n//\t\tar & make_nvp(\"extensions\", extensions);\n//\t\tif(extensions != this->extensions()){clear(); this->reextent(extensions);}\n//\t\tassert(extensions == this->extensions());\n\t\tstd::move(*this).ref::serialize(ar, version);\n\t}\n};\n\ntemplate<typename T, class Alloc>\nstruct array<T, dimensionality_type{0}, Alloc>\n\t: static_array<T, 0, Alloc>\n{\n\tusing static_ = static_array<T, 0, Alloc>;\n\tusing static_::static_;\n\tvoid reextent(typename array::extensions_type const&){}\n};\n\ntemplate<class T, dimensionality_type D, class Alloc>\nstruct array : static_array<T, D, Alloc>,\n\tboost::multi::random_iterable<array<T, D, Alloc> >\n{\n\tusing static_ = static_array<T, D, Alloc>;\n\tstatic_assert(std::is_same<typename array::alloc_traits::value_type, T>{} or std::is_same<typename array::alloc_traits::value_type, void>{}, \"!\");\npublic:\n//\tarray_ptr<T, D, typename array::element_const_ptr> operator&() const&{return {this->base(), this->extensions()};}\n//\tarray_ptr<T, D, typename array::element_ptr> operator&() &{return {this->base(), this->extensions()};}\n//\tarray_ptr<T, D, typename array::element_ptr> operator&() && = delete;\n\ttemplate<class Archive>\n\tauto serialize(Archive& ar, const unsigned int version){\n\t\tauto extensions = this->extensions();\n\t\tar & multi::archive_traits<Archive>::make_nvp(\"extensions\", extensions);\n\t\tif(extensions != this->extensions()){clear(); this->reextent(extensions);}\n\t\tassert(extensions == this->extensions());\n\t\tstatic_::serialize(ar, version);\n\t}\n\tusing static_::static_;\n\tusing typename static_::value_type;\n\tarray() = default;\n\tarray(array const&) = default;\n\tarray& reshape(typename array::extensions_type x) &{\n\t\ttypename array::layout_t new_layout{x};\n\t\tassert( new_layout.num_elements() == this->num_elements() );\n\t\tstatic_cast<typename array::layout_t&>(*this)=new_layout;\n\t\treturn *this;\n\t}\n\tusing static_::clear;\n\tfriend void clear(array& self) noexcept{self.clear();}\n\n\tfriend auto data_elements(array const& self){return self.data_elements();}\n\tfriend auto data_elements(array      & self){return self.data_elements();}\n\tfriend auto data_elements(array     && self){return std::move(self).data_elements();}\n\t\n\tbasic_array<typename array::element, array::dimensionality, multi::move_ptr<typename array::element> >\n\tmove() &{\n\t\tbasic_array<typename array::element, array::dimensionality, multi::move_ptr<typename array::element> >\n\t\tret = multi::static_array_cast<typename array::element, multi::move_ptr<typename array::element>>(*this);\n\t\tlayout_t<array::dimensionality>::operator=({});\n\t\treturn ret;\n\t}\n\tfriend \t\n\tbasic_array<typename array::element, array::dimensionality, multi::move_ptr<typename array::element> >\n\tmove(array& self){return self.move();}\n\n//\texplicit\t\n//\tarray(array const& other)                                              // 5a\n//\t:\tallocator_type{other}, ref{allocate(other.num_elements()), extensions(other)}{\n//\t\tuninitialized_copy_(other.data());\n//\t}\n//\texplicit\n//s\tusing static_::static_array;\n//\ttemplate<class Array> array(Array const& arr) : static_{arr}{}\n//\tusing static_::static_;\n//\ttemplate<class... As>\n//\tarray(typename array::extensions_type x, As&&... as) : static_{x, std::forward<As>(as)...}{} //2\n//\tarray(array const& other) : static_{static_cast<static_ const&>(other)}{}\n\tarray(array&& o, typename array::allocator_type const& a) noexcept : static_{std::move(o), a}{}\n\tarray(array&& o) noexcept : array{std::move(o), o.get_allocator()}{}\n\tfriend typename array::allocator_type get_allocator(array const& self){return self.get_allocator();}\n#if 0\n\ttemplate<class A//, typename = std::enable_if_t<not std::is_base_of<array, std::decay_t<A>>{}>,\n//\t\ttypename = std::enable_if_t<not std::is_convertible<std::decay_t<A>, typename array::element_type>{}>\n\t>\n\tarray& operator=(A&& a){\n\t\tauto ext = extensions(a);\n\t\tif(ext==array::extensions()){\n\t\t//\tconst_cast<array const&>\n\t\t\tstd::move(*this).static_::ref::operator=(std::forward<A>(a));\n\t\t}else{\n\t\t\tthis->clear(); //\tthis->ref::layout_t::operator=(layout_t<D>{extensions(a)}); //\t\t\tthis->base_ = allocate(this->num_elements());\n\t\t\tthis->base_ = this->allocate(static_cast<typename array::alloc_traits::size_type>(this->static_::ref::layout_t::operator=(layout_t<D>{extensions(a)}).num_elements()));\n\t\t\tusing std::begin; using std::end;\n\t\t//\talloc_uninitialized_copy(this->alloc(), begin(std::forward<A>(a)), end(std::forward<A>(a)), array::begin()); //\trecursive_uninitialized_copy<D>(alloc(), begin(std::forward<A>(a)), end(std::forward<A>(a)), array::begin());\n\t\t\tadl::alloc_uninitialized_copy(this->alloc(), begin(std::forward<A>(a)), end(std::forward<A>(a)), array::begin()); //\trecursive_uninitialized_copy<D>(alloc(), begin(std::forward<A>(a)), end(std::forward<A>(a)), array::begin());\n\t\t}\n\t\treturn *this;\n\t}\n#endif\n#if 0\n\ttemplate<class... As>\n\tarray& operator=(array<array::value_type, array::dimensionality, As...> const& o){\n\t\tif(o.extensions()==array::extensions()) return static_::operator=(o);\n\t\treturn operator=(array{o});\n\t/*\n\t\telse{\n\t\t\tarray::destroy();\n\t\t\tarray::deallocate();\n\t\t\tthis->static_::ref::layout_t::operator=(layout_t<D>{extensions(o)});\n\t\t\tarray::allocate();//array::num_elements());\n\t\t\tarray::uninitialized_copy_elements(data_elements(o));//adl::alloc_uninitialized_copy_n(data_elements(o), num_elements(o), array::data_elements());\n\t\t}*/\n\t//\treturn *this;\n\t}\n\ttemplate<class OtherT, class... As>\n\tauto operator=(array<OtherT, array::dimensionality, As...> const& o) &{\n\t\tif(extensions(o)==array::extensions()){\n\t\t\tstatic_::operator=(o);\n\t\t}else{\n\t\t\tarray::destroy(); array::deallocate();\n\t\t\tthis->static_::ref::layout_t::operator=(layout_t<D>{extensions(o)});\n\t\t\tarray::allocate(); array::uninitialized_copy_elements(data_elements(o));\n\t\t}\n\t\treturn *this;\n\t}\n//\tarray& operator=(array other) noexcept{swap(other);} //TODO consider this\n#endif\n\tvoid swap(array& other) noexcept{\n\t\tusing std::swap;\n\t\tswap(this->alloc(), other.alloc());\n\t\tswap(this->base_, other.base_);\n\t\tswap(\n\t\t\tstatic_cast<typename array::layout_t&>(*this), \n\t\t\tstatic_cast<typename array::layout_t&>(other)\n\t\t);\n\t}\n#ifndef NOEXCEPT_ASSIGNMENT\n\tarray& operator=(array&& other) noexcept{\n\t\tusing std::exchange;\n\t\tclear();\n\t\tthis->base_ = exchange(other.base_, nullptr);\n\t\tthis->alloc() = std::move(other.alloc());\n\t\tstatic_cast<typename array::layout_t&>(*this) = exchange(static_cast<typename array::layout_t&>(other), {});\n\t\treturn *this;\n\t}\n\tarray& operator=(array const& o){\n\t\tif(array::extensions() == o.extensions()) static_::operator=(o);\n\t\telse operator=(array{o});\n\t\treturn *this;\n\t}\n#else\n\tarray& operator=(array o) noexcept{return swap(o), *this;}\n#endif\n\ttemplate<class Range, class=std::enable_if_t<not std::is_base_of<array, std::decay_t<Range>>{}> >\n\tauto operator=(Range&& o) // check that LHS is not read-only\n\t->decltype(                                         static_::operator=(o)                     , std::declval<array&>()){\n\t\treturn ((array::extensions() == o.extensions())?static_::operator=(o):operator=(array(o))), *this                 ;}\n\n\tarray& operator=(basic_array<T, D, multi::move_ptr<typename array::element, typename array::element_ptr>>& other){\n\t\tif(other.layout() != this->layout()) return array::operator=(other.template static_array_cast<typename array::element, typename array::element_ptr>());\n\t\tif(this->base_ != other.base_) other.base_ = nullptr;\n\t\treturn *this;\n\t}\n\tfriend void swap(array& a, array& b){a.swap(b);}\n\tvoid assign(typename array::extensions_type x, typename array::element const& e){\n\t\tif(array::extensions()==x){\n\t\t\tfill_n(this->base_, this->num_elements(), e);\n\t\t}else{\n\t\t\tthis->clear();\n\t\t\tthis->layout_t<D>::operator=(layout_t<D>{x});\n\t\t\tthis->base_ = this->allocate();\n\t\t\tuninitialized_fill_n(e);\n\t\t//\trecursive_uninitialized_fill<dimensionality>(alloc(), begin(), end(), e);\n\t\t}\n\t}\n//\ttemplate<class It, class Size> It assign_n(It first, Size n){\n//\t\tif(n == array::size() and multi::extensions(*first) == multi::extensions(*array::begin())){\n//\t\t\treturn static_::ref::assign(first);\n//\t\t}\n//\t\tthis->\n//\t}\n\ttemplate<class It>\n\tarray& assign(It first, It last){using std::next; using std::all_of;\n\t//\tauto const s = adl::distance(first, last);\n\t\tif(adl_distance(first, last) == array::size()){// and multi::extensions(*first) == multi::extensions(*array::begin())){\n\t\t\tstatic_::ref::assign(first);\n\t\t}else{\n\t\t\tthis->operator=(array(first, last));\n\t\t/*\n\t\t\tthis->clear();\n\t\t\tthis->layout_t<D>::operator=(layout_t<D>{std::tuple_cat(std::make_tuple(index_extension{array::extension().front(), array::extension().front() + distance(first, last)}), multi::extensions(*first))});\n\t\t\tusing std::next;\n\t\t\tusing std::all_of;\n\t\t\tif(first!=last) assert( all_of(next(first), last, [x=multi::extensions(*first)](auto& e){return extensions(e)==x;}) );\n\t\t\tthis->base_ = this->allocate();\n\t\t\tmulti::uninitialized_copy<D>(first, last, array::begin());\n\t\t*/\n\t\t}\n\t\treturn *this;\n\t}\n\tvoid assign(std::initializer_list<typename array::value_type> il){assign(il.begin(), il.end());}\n\ttemplate<class Range> auto assign(Range&& r) &\n\t->decltype(assign(adl_begin(r), adl_end(r))){\n\t\treturn assign(adl_begin(r), adl_end(r));}\n\tarray& operator=(std::initializer_list<typename array::value_type> il){assign(il.begin(), il.end()); return *this;}\n\n\ttemplate<class TT, class... Args>\n\tbool operator==(basic_array<TT, D, Args...> const& other) const{\n\t\treturn static_::operator==(other);\n\t}\n\n\tvoid reextent(typename array::extensions_type const& x){\n\t\tif(x == this->extensions()) return;\n\t\tarray tmp(x, this->get_allocator());\n\t\tauto const is = intersection(this->extensions(), x);\n\t\ttmp.apply(is) = this->apply(is);\n\t\tswap(tmp);\n\t}\n\tvoid reextent(typename array::extensions_type const& x, typename array::element const& e){\n\t\tif(x == this->extensions()) return;\n\t\tarray tmp(x, e, this->get_allocator());\n\t\tauto const is = intersection(this->extensions(), x);\n\t\ttmp.apply(is) = this->apply(is);\n\t\tswap(tmp);\n\t}\n\ttemplate<class... Ts> constexpr array&& reindex(Ts... a)&&{array::layout_t::reindex(a...); return std::move(*this);}\n\ttemplate<class... Ts> constexpr array&  reindex(Ts... a)& {array::layout_t::reindex(a...); return           *this ;}\n\t~array() noexcept = default;\n};\n\n#if defined(__cpp_deduction_guides)\n// clang cannot recognize templated-using, so don't replace IL<IL<T>> by IL2<T>, etc\n//#ifndef __clang__\n//template<class T, dimensionality_type D, class A=std::allocator<T>> static_array(multi::initializer_list_t<T, D>, A={})->static_array<T, D, A>;\n//template<class T, dimensionality_type D, class A=std::allocator<T>> array(multi::initializer_list_t<T, D>, A={})->array<T, D, A>;\n//#else\n#define IL std::initializer_list\n\ttemplate<class T, class A=std::allocator<T>> static_array(IL<T>                , A={})->static_array<T,1,A>; \n\ttemplate<class T, class A=std::allocator<T>> static_array(IL<IL<T>>            , A={})->static_array<T,2,A>;\n\ttemplate<class T, class A=std::allocator<T>> static_array(IL<IL<IL<T>>>        , A={})->static_array<T,3,A>; \n\ttemplate<class T, class A=std::allocator<T>> static_array(IL<IL<IL<IL<T>>>>    , A={})->static_array<T,4,A>; \n\ttemplate<class T, class A=std::allocator<T>> static_array(IL<IL<IL<IL<IL<T>>>>>, A={})->static_array<T,5,A>;\n\n//\ttemplate<class T, class A=std::allocator<T>> array(IL<T>                , A={})->array<T,1,A>; \n\ttemplate<class T, class A=std::allocator<T>> array(IL<IL<T>>            , A={})->array<T,2,A>;\n\ttemplate<class T, class A=std::allocator<T>> array(IL<IL<IL<T>>>        , A={})->array<T,3,A>; \n\ttemplate<class T, class A=std::allocator<T>> array(IL<IL<IL<IL<T>>>>    , A={})->array<T,4,A>; \n\ttemplate<class T, class A=std::allocator<T>> array(IL<IL<IL<IL<IL<T>>>>>, A={})->array<T,5,A>;\n\n\n\ttemplate<class T> array(std::initializer_list<T>)->array<T, 1>; \n#undef IL\n//#endif\n\ntemplate<class T, class A=std::allocator<T>> array(T[]                  , A={})->array<T,1,A>;\n\n//template<class Array, class E = typename multi::array_traits<Array>::element, class A=std::allocator<E>, class=std::enable_if_t<is_allocator<A>{}>> array(Array            , A={})->array<typename multi::array_traits<Array>::element, 1, A>;\n\ntemplate<dimensionality_type D, class T, class=std::enable_if_t<not is_allocator<T>{}> > array(iextensions<D>, T)->array<T, D, std::allocator<T>>;\n\ttemplate<class T, class=std::enable_if_t<not is_allocator<T>{}> > array(iextensions<0>, T)->array<T,0, std::allocator<T>>;\n\ttemplate<class T, class=std::enable_if_t<not is_allocator<T>{}> > array(iextensions<1>, T)->array<T,1, std::allocator<T>>;\n\ttemplate<class T, class=std::enable_if_t<not is_allocator<T>{}> > array(iextensions<2>, T)->array<T,2, std::allocator<T>>;\n\ttemplate<class T, class=std::enable_if_t<not is_allocator<T>{}> > array(iextensions<3>, T)->array<T,3, std::allocator<T>>;\n\ttemplate<class T, class=std::enable_if_t<not is_allocator<T>{}> > array(iextensions<4>, T)->array<T,4, std::allocator<T>>;\n\ttemplate<class T, class=std::enable_if_t<not is_allocator<T>{}> > array(iextensions<5>, T)->array<T,5, std::allocator<T>>;\n\ntemplate<dimensionality_type D, class T, class A, typename = std::enable_if_t<std::is_same<typename std::allocator_traits<A>::value_type, T>{}> > static_array(iextensions<D>, T, A)->static_array<T, D, A>;\n\ttemplate<class T, class A, typename = std::enable_if_t<std::is_same<typename std::allocator_traits<A>::value_type, T>{}>> static_array(T, A)->static_array<T, 0, A>;\n//\ttemplate<class T, class A, typename = std::enable_if_t<not is_allocator<T>{}> > static_array(iextensions<1>, T, A = {})->static_array<T, 1, A>;\n\ntemplate<dimensionality_type D, class A, class=std::enable_if_t<is_allocator<A>{}>, typename T = typename std::allocator_traits<A>::value_type> array(iextensions<D>, A)->array<T, D, A>;\n\ttemplate<class A, class=std::enable_if_t<is_allocator<A>{}>, typename T = typename std::allocator_traits<A>::value_type> array(iextensions<0>, A)->array<T, 0, A>;\n\ttemplate<class A, class=std::enable_if_t<is_allocator<A>{}>, typename T = typename std::allocator_traits<A>::value_type> array(iextensions<1>, A)->array<T, 1, A>;\n\ttemplate<class A, class=std::enable_if_t<is_allocator<A>{}>, typename T = typename std::allocator_traits<A>::value_type> array(iextensions<2>, A)->array<T, 2, A>;\n\ttemplate<class A, class=std::enable_if_t<is_allocator<A>{}>, typename T = typename std::allocator_traits<A>::value_type> array(iextensions<3>, A)->array<T, 3, A>;\n\ttemplate<class A, class=std::enable_if_t<is_allocator<A>{}>, typename T = typename std::allocator_traits<A>::value_type> array(iextensions<4>, A)->array<T, 4, A>;\n\ttemplate<class A, class=std::enable_if_t<is_allocator<A>{}>, typename T = typename std::allocator_traits<A>::value_type> array(iextensions<5>, A)->array<T, 5, A>;\n\n\ttemplate<class T> array(iextensions<0>, T)->array<T, 0>;\n\ttemplate<class T> array(iextensions<1>, T)->array<T, 1>; template<class T> array(multi::size_type, T)->array<T, 1>;\n\ttemplate<class T> array(iextensions<2>, T)->array<T, 2>;\n\ttemplate<class T> array(iextensions<3>, T)->array<T, 3>;\n\ntemplate<class T, class MR, class A=memory::allocator<T, MR>> array(iextensions<1>, T, MR*)->array<T, 1, A>;\ntemplate<class T, class MR, class A=memory::allocator<T, MR>> array(iextensions<2>, T, MR*)->array<T, 2, A>;\ntemplate<class T, class MR, class A=memory::allocator<T, MR>> array(iextensions<3>, T, MR*)->array<T, 3, A>;\ntemplate<class T, class MR, class A=memory::allocator<T, MR>> array(iextensions<4>, T, MR*)->array<T, 4, A>;\ntemplate<class T, class MR, class A=memory::allocator<T, MR>> array(iextensions<5>, T, MR*)->array<T, 5, A>;\n\ntemplate<class MatrixRef, class DT = typename MatrixRef::decay_type, class T = typename DT::element, dimensionality_type D = DT::dimensionality, class Alloc = typename DT::allocator_type>\narray(MatrixRef)->array<T, D, Alloc>;\n\ntemplate<typename T, dimensionality_type D, typename P> array(basic_array<T, D, P>)->array<T, D>;\n#endif\n\ntemplate <class T, std::size_t N>\nmulti::array<typename std::remove_all_extents<T[N]>::type, std::rank<T[N]>{}> \ndecay(const T(&t)[N]) noexcept{\n\treturn multi::array_cref<typename std::remove_all_extents<T[N]>::type, std::rank<T[N]>{}>(data_elements(t), extensions(t));\n}\n\ntemplate<class T, size_t N>\nstruct array_traits<T[N], void, void>{\n\tusing reference = T&;\n\tusing element = std::remove_all_extents_t<T[N]>;\n\tusing decay_type = multi::array<T, 1>;\n};\n\n}}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#if defined(__INCLUDE_LEVEL__) and not __INCLUDE_LEVEL__\n\n#include<cassert>\n#include<numeric> // iota\n#include<iostream>\n#include<algorithm>\n#include<vector>\n\n#include <random>\n#include <boost/timer/timer.hpp>\n#include<boost/multi_array.hpp>\n\nusing std::cout;\nnamespace multi = boost::multi;\n\n#if 1\ntemplate<class Matrix, class Vector>\nvoid solve(Matrix& m, Vector& y){\n//\tusing std::size; // assert(size(m) == std::ptrdiff_t(size(y)));\n\tstd::ptrdiff_t msize = size(m); \n\tfor(auto r = 0; r != msize; ++r){ //\tauto mr = m[r]; //  auto const mrr = mr[r];// assert( mrr != 0 ); // m[r][r] = 1;\n\t\tauto mr = m[r];\n\t\tauto mrr = mr[r];\n\t\tfor(auto c = r + 1; c != msize; ++c) mr[c] /= mrr;\n\t\tauto yr = (y[r] /= mrr);\n\t\tfor(auto r2 = r + 1; r2 != msize; ++r2){ //\tauto mr2 = m[r2]; //\tauto const mr2r = mr2[r]; // m[r2][r] = 0;\n\t\t\tauto mr2 = m[r2];\n\t\t\tauto const& mr2r = mr2[r];\n\t\t\tauto const& mr_cr = m[r];\n\t\t\tfor(auto c = r + 1; c != msize; ++c) mr2[c] -= mr2r*mr_cr[c];\n\t\t\ty[r2] -= mr2r*yr;\n\t\t}\n\t}\n\tfor(auto r = msize - 1; r > 0; --r){ //\tauto mtr = m.rotated(1)[r];\n\t\tauto const& yr = y[r];\n\t\tfor(auto r2 = r-1; r2 >=0; --r2)\n\t\t\ty[r2] -= yr*m[r2][r];\n\t}\n}\n#endif\n\nvoid f(boost::multi::array<double, 4> const& A){\n\tA[1][2];\n\tauto&& a = A[1][2]; (void)a; // careful, a is a reference here, don't use auto, \n\tauto const& b = A[1][2]; (void)b; // use auto const& if possible\n//\tA[1][2][3][4] = 5; // fail, element is read-only\n}\n\ntemplate<class C>\nvoid set_99(C&& c){\n\tfor(auto j : c.extension(0))\n\t\tfor(auto k : c.extension(1))\n\t\t\t\tc[j][k] = 99.;\n}\n\nnamespace multi = boost::multi;\n\ntemplate<class T> void fun(T const& t){\n\tstd::cout << typeid(t).name() << std::endl;\n}\n\ntemplate<class T> struct extension{};\ntemplate<class T> void gun(extension<T>){\n\tstd::cout << typeid(T).name() << std::endl;\n}\n\ntypedef double a1010[10][10];\n\nstruct A{\n\tdouble const* p;\n\tA(std::initializer_list<double> il){ p = &*(il.begin() + 1); };\n};\n\ntemplate<class T> void what(T&&) = delete;\n\nint main(){\n\n{\n\tmulti::array<double, 1> A1 = {1.,2.,3.}; \n\tassert( A1.dimensionality==1 and A1.num_elements()==3 );\n\n\tmulti::array<double, 2> A2 {\n\t\t {1.,2.,3.},\n\t\t {4.,5.,6.}\n\t};\n\t*A2.begin()->begin() = 99;\n\tassert(A2[0][0] == 99 );\n}\n{\n\tdouble A[2][3] = {{1.,2.,3.}, {4.,5.,6.}};\n\tusing multi::decay;\n\tauto A_copy = decay(A);\n}\n\t{\n\t\tmulti::array<double, 2> A = {\n\t\t\t{1},\n\t\t\t{2},\n\t\t\t{3}\n\t\t};\n\t\tassert( size(A) == 3 );\n\t\tassert( size(rotated(A)) == 1 );\n\t\tassert( stride(A) == 1 );\n\t\tassert( stride(rotated(A)) == 1 );\n\t\tassert( A.extensions() );\n\t}\n\t{\n\t\tmulti::array<double, 1> A = {1};\n\t\tassert( size(A) == 1 );\n\t\tassert( stride(A) == 1 );\n\t}\n\t{\n\t\tmulti::array<double, 0> A = 3.;\n\t//\tassert( stride(A) == 1 );\n\t}\n\t{\n\t\tdouble D3[3] = {0, 1, 2};\n\t\tmulti::array<double, 1> A(D3);\n\t\tassert( A[1] == 1 );\n\t}\n}\n#endif\n#endif\n\n", "meta": {"hexsha": "d4357a31c8bf4c175867f92b2f60bb617aabf5d3", "size": 58952, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_codes/boost_multi/multi/array.hpp", "max_stars_repo_name": "eugeneswalker/qmcpack", "max_stars_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external_codes/boost_multi/multi/array.hpp", "max_issues_repo_name": "eugeneswalker/qmcpack", "max_issues_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "external_codes/boost_multi/multi/array.hpp", "max_forks_repo_name": "mmorale3/qmcpack", "max_forks_repo_head_hexsha": "b1a358d8aeb63a96bccabafea5d899afa4520d13", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.8645383952, "max_line_length": 240, "alphanum_fraction": 0.7077283213, "num_tokens": 15101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.02716923163414444, "lm_q1q2_score": 0.006817107626854687}}
{"text": "/// \\file   price_setter.cpp\n///\n/// \\brief\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2018-07-19\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#include <esl/economics/markets/walras/price_setter.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <type_traits>\nusing std::map;\n\n#include <esl/economics/markets/walras/quote_message.hpp>\n#include <esl/economics/markets/walras/tatonnement.hpp>\nusing esl::law::property;\nusing esl::economics::finance::securities_lending_contract;\n\n#include <esl/economics/finance/securities_lending_contract.hpp>\n\n\ntemplate<class... T>\nstruct always_false : std::false_type\n{ };\n\ntemplate<>\nstruct always_false<> : std::true_type\n{ };\n\nnamespace esl::economics::markets::walras {\n    price_setter::price_setter()\n        : price_setter(identity<price_setter>())\n    {\n\n    }\n\n    ///\n    /// \\brief\n    ///\n    /// \\details    Initialises the differentiable variable context to 1.0 times\n    ///             the initial quotes. In essence, the\n    ///             solver starts at 1.0 times the initial quote\n    /// \\param i\n    /// \\param traded_assets\n    price_setter::price_setter(const identity<price_setter> &i,\n                               law::property_map<quote>\n                               traded_properties)\n    : agent(i)\n    , market(i)\n    , state(sending_quotes)\n    , traded_properties(traded_properties)\n    {\n\n        output_clearing_prices_ =\n            create_output<std::vector<price>>(\"clearing_prices\");\n\n\n        output_volumes_ =\n            create_output<std::vector<uint64_t>>(\"volumes\");\n\n\n        register_callback<walras::differentiable_order_message>(\n            [this](auto msg, simulation::time_interval ti,\n                   std::seed_seq &seed) {\n                (void)msg;\n                (void)seed;\n                return ti.upper;\n            });\n    }\n\n    ///\n    /// \\brief\n    ///\n    /// \\param step\n    /// \\param seed\n    /// \\return\n    simulation::time_point price_setter::act(simulation::time_interval step, std::seed_seq &seed)\n    {\n        (void)seed;\n        simulation::time_point next_ = step.upper;\n        std::vector<quote> quotes_;\n\n        if(state == sending_quotes){\n            // send out initial quotes and wait for orders,\n            // scheduled in the same time step\n            next_ = step.lower;\n            for(const auto &[k, v]: traded_properties) {\n                (void)k;\n                quotes_.push_back(v);\n            }\n        }else{\n            std::unordered_map<\n                identity<agent>,\n                std::shared_ptr<walras::differentiable_order_message>>\n                orders_;\n            for(const auto &[k, message_]: inbox) {\n                (void)k;\n                if(walras::differentiable_order_message::code == message_->type) {\n                    auto order_ = std::dynamic_pointer_cast<\n                        walras::differentiable_order_message>(message_);\n\n                    if(message_->sent < step.lower) {\n                        next_ = step.lower;\n                        break;\n                    }\n                    orders_.emplace(order_->sender, order_);\n                }\n            }\n\n            if(!orders_.empty()) {\n                // there is at least one order so we clear the market\n                auto before_ = std::chrono::high_resolution_clock::now();\n                auto scalars_ = clear_market(orders_, step);\n                LOG(notice) << \"clearing market took \" << (double((std::chrono::high_resolution_clock::now()-before_).count()) / 1e+6) <<  \" milliseconds\" << std::endl;\n\n                std::vector<price> prices_;\n                for(auto &[k, v]: traded_properties){\n                    (void)v;\n                    // TODO: generalise to all types of quotes\n                    prices_.emplace_back(std::get<price>(v.type));\n                    quotes_.emplace_back(quote(v));\n                }\n\n                LOG(notice) << \"quotes: \" << quotes_ << std::endl;\n\n                output_clearing_prices_->put(step.lower, prices_);\n\n            }else{  // restore previous prices\n                for(const auto &[k, v]: traded_properties){\n                    (void)k;\n                    quotes_.push_back(v);\n                }\n                if(step.lower > 1){\n                    next_ = step.lower;\n                }\n            }\n        }\n\n        law::property_map<quote> quote_map_;\n        {\n            size_t sequence_ = 0;\n            for(const auto &[k, v]: traded_properties) {\n                quote_map_.insert({k, quotes_[sequence_]});\n                ++sequence_;\n            }\n        }\n        LOG(trace) << describe() << \" \" << identifier << \" time \" << step.lower <<  \" clearing prices \" << quote_map_ << std::endl;\n\n        for(const auto &p : participants) {\n            auto m = this->template create_message<walras::quote_message>(\n                p, step.lower + 1, identifier, p, quote_map_);\n        }\n        state = clearing_market;\n        return next_;\n    }\n\n\n    ///\n    /// \\brief  Applies a solution of quotes to the currently stored traded_properties\n    ///\n    /// \\param result_\n    /// \\param traded_properties\n    /// \\return\n    std::map<identity<law::property>, std::tuple<quote, double>> apply_results(\n        std::map<identity<law::property>, double> result_\n        , law::property_map<quote> &traded_properties\n    )\n    {\n        std::map<identity<law::property>, std::tuple<quote, double>> solution_;\n        for(auto [p, q]: traded_properties) {\n            double scalar_ = result_.find(p->identifier)->second;\n            std::tuple<quote, double> part_ = std::make_tuple(q, scalar_);\n            solution_.emplace(p->identifier, part_);\n\n            std::visit(\n                [&, result_, p = p](auto &quote) {\n                    using type_ = std::decay_t<decltype(quote)>;\n                    if constexpr(std::is_same_v<type_, price>) {\n                        auto value_ = int64_t(quote.value\n                                              * result_.find(p->identifier)->second);\n                        if(0 == value_){//} && POSITIVE){\n                            value_ = 1;\n                        }\n                        std::get<price>(traded_properties[p].type).value =value_\n                            ;\n\n                    } else if constexpr(std::is_same_v<type_, exchange_rate>) {\n                        quote = exchange_rate(\n                            uint64_t(quote.numerator()\n                                     * result_.find(p->identifier)->second),\n                            quote.denominator());\n                        traded_properties[p].type = quote;\n                    } else {\n                        static_assert(always_false<type_>::value,\n                                      \"non-exhaustive handling of quote types\");\n                    }\n                },\n                q.type);\n        }\n        return solution_;\n    }\n\n\n    ///\n    /// \\brief  Computes the transfers from and to the market agent\n    ///\n    /// \\param traded_properties\n    /// \\param volumes_\n    /// \\param orders_\n    /// \\return\n    map<identity<property>, map<identity<agent>, int64_t>> price_setter::compute_transfers\n        ( const law::property_map<quote> &traded_properties\n            , const map<identity<property>, double> &volumes_\n            , const map<identity<property>, map<identity<agent>, std::tuple<double, quantity, quantity>>> &orders_\n        )\n    {\n        map<identity<property>, map<identity<agent>, int64_t>> transfers_;\n        for(const auto &[property_, data_]: traded_properties) {\n            auto i = volumes_.find(property_->identifier);\n            if(volumes_.end() == i) {\n                continue;  // no agents expressed interest\n            }\n            int64_t error_ = 0;\n            std::vector<std::tuple<identity<agent>, int64_t>> allocations_;\n            for(auto [p, a]: orders_.find(property_->identifier)->second) {\n                auto alloc_ = int64_t(std::get<0>(a));\n                error_ += alloc_;\n                allocations_.emplace_back(p, alloc_);\n            }\n            std::sort(allocations_.begin(), allocations_.end(),\n                      [](const auto &a, const auto &b) -> bool {\n                          return std::abs(std::get<1>(a))\n                                 < std::abs(std::get<1>(b));\n                      });\n\n            if(error_ < 0){  // assigned too many\n                if(allocations_.size() < uint64_t(-error_)) {\n                    LOG(notice) << \"clearing price beyond rounding error\" << std::endl;\n                }\n\n                for(size_t ii = 0; ii < uint64_t(-error_); ++ii) {\n                    std::get<1>(allocations_[ii % allocations_.size()]) += 1;\n                }\n            }else{\n                if(allocations_.size() < uint64_t(error_)) {\n                    LOG(notice) << \"clearing price beyond rounding error\" << std::endl;\n                }\n\n                for(size_t ii = 0; ii < uint64_t(error_); ++ii) {\n                    std::get<1>(allocations_[ii % allocations_.size()]) -= 1;\n                }\n            }\n            auto pair_ = transfers_.emplace(property_->identifier, map<identity<agent>, int64_t>());\n\n            for(auto [p, a]: allocations_) {\n                pair_.first->second.emplace(p, a);\n            }\n        }\n        //if(transfers_.size()){\n        //    LOG(trace) << transfers_ << std::endl;\n        //}\n        return transfers_;\n    }\n\n\n\n    ///\n    /// \\brief  Clear market using tatonnement. It is assumed the price_setter\n    ///         has received at least one excess demand function for each\n    ///         property from market participants, otherwise\n    ///         it will return the previous price for the property with no\n    ///         excess demand curve.\n    ///\n    ///\n    std::map<identity<law::property>, double> price_setter::clear_market(\n        const std::unordered_map<\n            identity<agent>,\n            std::shared_ptr<walras::differentiable_order_message>> &orders,\n        const simulation::time_interval &step)\n    {\n        law::property_map<quote> old_quotes_ = traded_properties;\n\n        tatonnement::excess_demand_model model_(traded_properties);\n        for(auto [key, function_] : orders) {\n            (void)key;\n            model_.excess_demand_functions_.push_back(function_);\n        }\n        auto result1_ = model_.compute_clearing_quotes();\n\n        // if finding a price failed, return previous price vector\n        if(!result1_.has_value()){\n            std::map<identity<law::property>, double> previous_;\n            for(const auto &[k, v] : traded_properties) {\n                (void)k;\n                previous_.insert({k->identifier, 1.0 * double(v)});\n            }\n            return previous_;\n        }\n\n        auto solution_ = apply_results(result1_.value(), traded_properties);\n\n        ////////////////////////////////////////////////////////////////////////\n        map<identity<property>, double> volumes_;\n        map<identity<property>, map<identity<agent>, std::tuple<double, quantity, quantity>>> orders_;\n\n        //  this is to normalize positive demand, so that we dont create\n        //  naked short positions by inventing new property\n        map<identity<property>, double> scales_;\n\n        map<identity<property>, double> existingdemand_;\n\n        // total supply is the maximum number of properties\n        map<identity<property>, double> total_supply_;\n\n\n        for(const auto &[participant, order_] : orders) {\n            auto demand_ = order_->excess_demand(solution_);\n            for(const auto &[property_, excess_] : demand_) {\n                auto i = scales_.emplace(property_, 0.).first;\n                auto j = total_supply_.emplace(property_, 0.).first;\n                auto h = existingdemand_.emplace(property_, 0.).first;\n\n                // TODO: the minimum transfer amount should be derived from the quote\n                constexpr double minimum_transfer_amount = 0.00001;\n                if(excess_ > -minimum_transfer_amount && excess_ < minimum_transfer_amount) {\n                    continue;\n                }\n                auto quote_ = solution_.find(property_)->second;\n                auto units_ = excess_ / (double(std::get<0>(quote_)) * std::get<1>(quote_));\n                auto units_with_existing_ = units_;\n\n                auto k = order_->supply.find(property_);\n                if(order_->supply.end() != k){\n                    // TODO: there is the excess, and this is the reserve\n                    units_with_existing_ -= double(std::get<0>(k->second));\n                    units_with_existing_ -= double(std::get<1>(k->second));\n\n                    j->second += double(std::get<0>(k->second)) - double(std::get<1>(k->second)) ;\n                }\n\n                if(units_with_existing_ > 0.) {\n                    h->second += units_with_existing_;\n                }\n\n                if(units_ > 0.){\n                    i->second += units_;\n                }\n            }\n        }\n\n        // TODO: check to make sure we use supply properly\n        //std::cout << \" total_supply_ = \" << total_supply_ << std::endl;\n        //std::cout << \" existing_demand_ = \" << existingdemand_ << std::endl;\n        //std::cout << \" demand(scale) = \" << scales_ << std::endl;\n\n        for(const auto &[participant, order_]: orders) {\n            auto demand_ = order_->excess_demand(solution_);\n            for(const auto &[property_, excess_]: demand_) {\n                if(excess_ >= -0.00001 && excess_ <= 0.00001) {\n                    continue;\n                }\n\n                auto quote_ = solution_.find(property_)->second;\n\n                auto units_ = (excess_ ) / (double(std::get<0>(quote_)) * std::get<1>(quote_));\n\n                auto i = volumes_.find(property_);\n                if(volumes_.end() == i){\n                    i = volumes_.emplace(property_, 0).first;\n                    orders_.emplace( property_\n                        , map<identity<agent>, std::tuple<double, quantity, quantity>>()\n                    );\n                }\n                i->second += abs(units_);\n\n                auto j = order_->supply.find(property_);\n                if(order_->supply.end() == j){\n                    orders_.find(property_)->second.emplace( participant, std::make_tuple(units_, 0, 0));\n\n                    //LOG(trace) << participant << \" demands {\" << property_ << \", \"\n                    //           << units_ << \"}\" << std::endl;\n                }else{\n                    //LOG(trace) << participant << \" demands {\" << property_ << \", \"\n                    //           << std::setprecision(5) << units_\n                    //           << \"}\" << std::endl;\n\n                    orders_.find(property_)->second.emplace(participant, std::make_tuple(units_, std::get<0>(j->second), std::get<1>(j->second)));\n                }\n            }\n        }\n\n        ////////////////////////////////////////////////////////////////////////\n        auto transfers_ = compute_transfers(traded_properties, volumes_, orders_);\n        output_volumes_->put(step.lower, { std::uint64_t(volumes_.begin()->second )} );\n\n\n        //  send_: we, the market maker, send items to participant\n        //  receive_: we, the market maker, receive items from participant\n        map<identity<agent>, accounting::inventory_filter<law::property>> send_, receive_;\n\n        auto usd_ = std::make_shared<cash>(currencies::USD);\n\n        for(const auto &[property_, data_] : traded_properties) {\n            // if no agents expressed interest, transfers_ might be empty\n            if(transfers_.end() == transfers_.find(*property_)) {\n                continue;\n            }\n            for(auto &[p, v] : transfers_.find(*property_)->second) {\n                if(v == 0) {\n                    continue;\n                }\n\n                auto i = orders.find(p)->second->supply.find(*property_);\n                if(orders.find(p)->second->supply.end() == i) {\n                    auto [ii,b] = orders.find(p)->second->supply.insert({property_->identifier\n                                                                            , std::make_tuple(quantity(0)\n                            ,quantity(0))});\n                    i = ii;\n                }\n                uint64_t &long_  = std::get<0>(i->second).amount;\n                uint64_t &short_ = std::get<1>(i->second).amount;\n\n                if(v > 0) {  // send properties to this agent, or receive shorts\n                    if(short_ > 0) {  // there was a short position\n                        assert(long_ == 0);\n\n                        uint64_t cancel_ = std::min(uint64_t(v), short_);\n                        //LOG(trace) << \"cancel the short position of \" << p <<\" by \" << cancel_ << std::endl;\n\n\n                        auto short_contract_ = std::make_shared<securities_lending_contract>(identifier, p, property_->identifier, quantity(1));\n                        auto r = receive_.emplace(p, accounting::inventory_filter<law::property>()).first;\n                        r->second.insert(short_contract_, quantity(cancel_));\n\n                        // ???\n                        // auto s = send_.emplace(p, accounting::inventory_filter<law::property>()).first;\n                        //\n                        auto s = receive_.emplace(p, accounting::inventory_filter<law::property>()).first;\n                        auto o = old_quotes_.find(property_);\n                        auto collateral_ = usd_->amount(cancel_ * double(std::get<price>(o->second.type)) / o->second.lot);\n\n                        s->second.insert(usd_, collateral_);\n                        v -= cancel_;\n                    }\n\n                    if(uint64_t(v) > 0){\n                        //LOG(trace) << p << \" purchased additional \" << v << std::endl;\n                        accounting::inventory_filter<law::property> purchased_;\n                        purchased_.insert(property_, quantity(uint64_t(v)));\n                        send_.emplace(p, purchased_);\n\n                        // they should send cash for the purchase\n                        auto r = receive_.emplace(p, accounting::inventory_filter<law::property>()).first;\n                        r->second.insert(usd_, usd_->amount(v * double(std::get<price>(data_.type)) / data_.lot));\n                    }\n                }else{  // v < 0 so participant wants to sell/short\n\n                    if(long_ > 0){\n\n                        uint64_t cancel_ = std::min(uint64_t(-v), long_);\n                        //LOG(trace) << \"cancel the long position of \" << p <<\" by \" << cancel_ << std::endl;\n\n                        auto r = receive_.emplace( p, accounting::inventory_filter<law::property>()).first;\n                        r->second.insert(property_, quantity(cancel_));\n\n                        auto s = send_.emplace(p, accounting::inventory_filter<law::property>()).first;\n                        auto proceeds_ = usd_->amount(cancel_ * double(std::get<price>(data_.type)) / data_.lot);\n                        s->second.insert(usd_, proceeds_);\n                        v += cancel_;\n                    }\n\n                    if(v <  0){ // is still smaller than zero\n                        // extend the short position\n                        auto amount_to_extend = uint64_t(-v);\n                        //LOG(trace) << \"extend the short position of \" << p <<\" by \" << amount_to_extend << std::endl;\n\n                        auto short_contract_ = std::make_shared<securities_lending_contract>(identifier, p, property_->identifier, quantity(1));\n                        auto s = send_.emplace( p, accounting::inventory_filter<law::property>()).first;\n\n                        auto sale_ = usd_->amount(amount_to_extend * double(std::get<price>(data_.type)) / data_.lot);\n\n                        s->second.insert(usd_, sale_);\n                        s->second.insert(short_contract_, quantity(amount_to_extend));\n                    }\n                }\n            }\n        }\n\n        // apply netting\n        for(auto &[p, i_r] : receive_) {\n            auto offset_ = send_.find(p);\n            if(send_.end() == offset_) {\n                continue;\n            }\n\n            for(auto &[k, v] : i_r.items) {\n                if(0 == v.amount){\n                    //i_r.items.erase(k);\n                    continue;\n                }\n\n                auto property_ = offset_->second.items.find(k);\n                if(offset_->second.items.end() == property_) {\n                    continue;\n                }\n                // receiving more than sending\n                if(v > property_->second) {\n                    auto diff_ = v - property_->second;\n                    v          = diff_;\n                    offset_->second.items.erase(property_);\n                } else if(v < property_->second) {  // sending more than recv\n                    auto diff_        = property_->second - v;\n                    property_->second = diff_;\n                    //i_r.items.erase(k);\n                } else {  // sending and rececing same amount\n                    //i_r.items.erase(k);\n                    offset_->second.items.erase(property_);\n                }\n            }\n            if(i_r.items.empty()){\n                receive_.erase(p);\n            }\n        }\n\n\n        for(auto [p, i] : send_) {\n            LOG(trace) << \"market sends to \" << p << \" items \" << i\n                       << std::endl;\n            this->template create_message<interaction::transfer>(\n                p, step.lower, identifier, p,\n                reinterpret_identity_cast<law::owner<law::property>>(\n                    identifier),\n                reinterpret_identity_cast<law::owner<law::property>>(p), i);\n        }\n\n        for(auto [p, i]: receive_) {\n            LOG(trace) << \"market receives from \" << p << \" items \" << i\n                       << std::endl;\n            this->template create_message<interaction::transfer>(\n                p, step.lower, p, identifier,\n                reinterpret_identity_cast<law::owner<law::property>>(p),\n                reinterpret_identity_cast<law::owner<law::property>>(\n                    identifier),\n                i);\n        }\n\n        return result1_.value();\n    }\n\n}  // namespace esl::economics::markets::walras\n\n\n#include <boost/serialization/export.hpp>\n\n#include <esl/data/serialization.hpp>\n\n\nBOOST_CLASS_EXPORT(std::vector<esl::economics::price>);\ntypedef std::tuple<esl::simulation::time_point,\n    std::vector<esl::economics::price>>\n    tuple_time_point_price_vector;\nBOOST_CLASS_EXPORT(tuple_time_point_price_vector);\ntypedef std::vector<\n    std::tuple<esl::simulation::time_point, std::vector<esl::economics::price>>>\n    time_series_price_vector;\nBOOST_CLASS_EXPORT(time_series_price_vector);\nBOOST_CLASS_EXPORT(esl::data::output<std::vector<esl::economics::price>>);", "meta": {"hexsha": "dc83277989ff8942b5db02c19b2ad5cc7b624de2", "size": 23881, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "esl/economics/markets/walras/price_setter.cpp", "max_stars_repo_name": "rht/ESL", "max_stars_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "esl/economics/markets/walras/price_setter.cpp", "max_issues_repo_name": "rht/ESL", "max_issues_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/economics/markets/walras/price_setter.cpp", "max_forks_repo_name": "rht/ESL", "max_forks_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-27T12:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T12:11:48.000Z", "avg_line_length": 40.752559727, "max_line_length": 168, "alphanum_fraction": 0.5111594992, "num_tokens": 5028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.02033235430730904, "lm_q1q2_score": 0.006802991067044342}}
{"text": "#include <algorithm>\n#include <chrono>\n#include <functional>\n#include <map>\n#include <memory>\n#include <regex>\n#include <set>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <nlohmann/json.hpp>\n#include <pybind11/operators.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/pytypes.h>\n#include <pybind11/stl.h>\n\n#include \"arch_graph.hpp\"\n#include \"arch_graph_automorphisms.hpp\"\n#include \"arch_graph_cluster.hpp\"\n#include \"arch_graph_system.hpp\"\n#include \"arch_uniform_super_graph.hpp\"\n#include \"nauty_graph.hpp\"\n#include \"parse.hpp\"\n#include \"perm.hpp\"\n#include \"perm_group.hpp\"\n#include \"perm_set.hpp\"\n#include \"task_mapping.hpp\"\n#include \"task_mapping_orbit.hpp\"\n#include \"timeout.hpp\"\n#include \"util.hpp\"\n\nnamespace mp = boost::multiprecision;\n\nnamespace py = pybind11;\n\nusing namespace py::literals;\n\nusing json = nlohmann::json;\n\nusing mpsym::ArchGraph;\nusing mpsym::ArchGraphCluster;\nusing mpsym::ArchGraphSystem;\nusing mpsym::ArchUniformSuperGraph;\nusing mpsym::ReprOptions;\nusing mpsym::TaskMapping;\nusing mpsym::TMO;\nusing mpsym::TMORs;\n\nusing mpsym::internal::ArchGraphAutomorphisms;\nusing mpsym::internal::BSGS;\nusing mpsym::internal::NautyGraph;\nusing mpsym::internal::Perm;\nusing mpsym::internal::PermGroup;\nusing mpsym::internal::PermSet;\n\nusing mpsym::util::IteratorAdaptor;\nusing mpsym::util::parse_perm;\nusing mpsym::util::stream;\n\nusing mpsym::internal::timeout::flag;\nusing mpsym::internal::timeout::run_abortable_with_timeout;\nusing mpsym::internal::timeout::TimeoutError;\n\nnamespace\n{\n\ntemplate<typename T = unsigned>\nusing Sequence = std::vector<T>;\n\ntemplate<typename T>\nusing contained_type =\n  typename std::remove_reference<decltype(*std::declval<T>().begin())>::type;\n\ntemplate<typename T>\nSequence<contained_type<T>> to_sequence(T const &obj)\n{ return Sequence<contained_type<T>>(obj.begin(), obj.end()); }\n\ntemplate<typename T = unsigned>\nSequence<T> to_sequence(py::iterator it)\n{\n  Sequence<T> seq;\n\n  while (it != py::iterator::sentinel()) {\n    try {\n      seq.push_back(it->cast<T>());\n    } catch (py::cast_error const &) {\n      throw std::runtime_error(\"failed to convert iterable to matching sequence\");\n    }\n\n    ++it;\n  }\n\n  return seq;\n}\n\ntemplate<typename T>\npy::tuple sequence_to_tuple(Sequence<T> const &seq)\n{\n  py::tuple t = py::cast(seq);\n  return t;\n}\n\ntemplate<typename T>\npy::tuple to_tuple(T const &obj)\n{ return sequence_to_tuple(to_sequence(obj)); }\n\nReprOptions str_to_repr_options(std::string const &method)\n{\n  ReprOptions options;\n\n  if (method == \"auto\") {\n    options.method = ReprOptions::Method::AUTO;\n  } else if (method == \"iterate\") {\n    options.method = ReprOptions::Method::ITERATE;\n  } else if (method == \"orbit\") {\n    options.method = ReprOptions::Method::ORBITS;\n  } else if (method == \"local_search_bfs\") {\n    options.method = ReprOptions::Method::LOCAL_SEARCH;\n    options.variant = ReprOptions::Variant::LOCAL_SEARCH_BFS;\n  } else if (method == \"local_search_dfs\") {\n    options.method = ReprOptions::Method::LOCAL_SEARCH;\n    options.variant = ReprOptions::Variant::LOCAL_SEARCH_DFS;\n  } else {\n    throw std::invalid_argument(\"invalid 'method'\");\n  }\n\n  return options;\n}\n\nPerm str_to_perm(unsigned degree, std::string cycles)\n{\n  static std::regex re_perm(R\"((\\(\\)|(\\(( *\\d+,)+ *\\d+ *\\))+))\");\n\n  cycles.erase(std::remove(cycles.begin(), cycles.end(), ' ' ), cycles.end());\n\n  if (!std::regex_match(cycles, re_perm))\n    throw std::invalid_argument(\"invalid permutation string\");\n\n  return parse_perm(degree, cycles);\n}\n\ntemplate<typename T>\nT arch_graph_json_cast(ArchGraphSystem const &self, std::string const &key)\n{\n  auto j(json::parse(self.to_json()));\n  T ret = j[\"graph\"][key];\n  return ret;\n}\n\ntemplate<typename FUNC, typename ...ARGS>\ntypename std::result_of<FUNC(ArchGraphSystem *, ARGS..., flag)>::type\narch_graph_timeout(std::string const &what,\n                   double timeout,\n                   ArchGraphSystem &self,\n                   FUNC f,\n                   ARGS &&...args)\n{\n  return run_abortable_with_timeout(\n    what,\n    std::chrono::duration<double>(timeout),\n    [&](flag aborted)\n    { return (self.*f)(std::forward<ARGS>(args)..., aborted); });\n}\n\n} // anonymous namespace\n\nnamespace pybind11\n{\n\nnamespace detail\n{\n\ntemplate <>\nstruct type_caster<mp::cpp_int> {\n  PYBIND11_TYPE_CASTER(mp::cpp_int, _(\"cpp_int\"));\n\n  static handle cast(mp::cpp_int const &src, return_value_policy, handle)\n  { return PyLong_FromString(stream(src).c_str(), nullptr, 10); }\n};\n\n} // namespace detail\n\n} // namespace pybind11\n\n#define PYBIND11_MODULE_(name, m) PYBIND11_MODULE(name, m)\n\nPYBIND11_MODULE_(PYTHON_MODULE_INTERNAL, m)\n{\n  m.attr(\"__version__\") = PYTHON_VERSION;\n  m.doc() = PYTHON_DESCRIPTION;\n\n  // ArchGraphSystem\n  py::class_<ArchGraphSystem,\n             std::shared_ptr<ArchGraphSystem>>(m, \"ArchGraphSystem\")\n    .def(\"__repr__\", &ArchGraphSystem::to_json)\n    .def_static(\"from_lua\", &ArchGraphSystem::from_lua,\n                \"lua\"_a, \"args\"_a = std::vector<std::string>())\n    .def_static(\"from_lua_file\", &ArchGraphSystem::from_lua_file,\n                \"lua_file\"_a, \"args\"_a = std::vector<std::string>())\n    .def_static(\"from_nauty\",\n                [](int vertices,\n                   std::map<int, std::vector<int>> const &adjacencies,\n                   int vertices_reduced,\n                   bool directed,\n                   std::vector<std::set<int>> const &coloring)\n                {\n                  // validate number of vertices\n                  if (vertices <= 0)\n                    throw std::invalid_argument(\"number of vertices must be non-negative\");\n\n                  // validate adjacencies\n                  std::set<std::pair<int, int>> edges;\n                  std::set<std::pair<int, int>> edge_parities;\n\n                  for (auto const &p : adjacencies) {\n                    int from = p.first;\n\n                    if (from >= vertices)\n                      throw std::invalid_argument(\"vertex index out of range\");\n\n                    for (int to : p.second) {\n                      if (to >= vertices)\n                        throw std::invalid_argument(\"vertex index out of range\");\n\n                      auto edge(std::make_pair(from, to));\n                      auto reverse_edge(std::make_pair(to, from));\n\n                      if (!edges.insert(edge).second)\n                        throw std::invalid_argument(\"duplicate edges\");\n                    }\n                  }\n\n                  // validate coloring\n                  if (!coloring.empty()) {\n                    std::set<int> tmp;\n                    for (auto const &p : coloring)\n                      tmp.insert(p.begin(), p.end());\n\n                    if (static_cast<int>(tmp.size()) != vertices\n                        || *tmp.begin() != 0\n                        || *tmp.rbegin() != vertices - 1) {\n\n                      throw std::invalid_argument(\"invalid coloring\");\n                    }\n                  }\n\n                  // construct graph\n                  if (vertices_reduced == 0)\n                    vertices_reduced = vertices;\n\n                  NautyGraph g{vertices, directed};\n\n                  g.add_edges(adjacencies);\n\n                  if (!coloring.empty()) {\n                    std::vector<std::vector<int>> coloring_;\n                    for (auto const &c : coloring)\n                      coloring_.emplace_back(c.begin(), c.end());\n\n                    g.set_partition(coloring_);\n                  }\n\n                  // extract automorphisms\n                  return std::make_shared<ArchGraphAutomorphisms>(\n                    PermGroup(vertices_reduced, g.automorphism_generators()));\n                },\n                \"vertices\"_a,\n                \"adjacencies\"_a,\n                \"vertices_reduced\"_a = 0,\n                \"directed\"_a = true,\n                \"coloring\"_a = std::vector<int>())\n    .def_static(\"from_json\", &ArchGraphSystem::from_json,\n                \"json\"_a)\n    .def_static(\"from_json_file\", &ArchGraphSystem::from_json_file,\n                \"json_file\"_a)\n    .def(\"to_json\", &ArchGraphSystem::to_json)\n    .def(\"processor_types\",\n         [](ArchGraphSystem const &self)\n         {\n           using T = std::vector<std::string>;\n           return arch_graph_json_cast<T>(self, \"processor_types\");\n         })\n    .def(\"channel_types\",\n         [](ArchGraphSystem const &self)\n         {\n           using T = std::vector<std::string>;\n           return arch_graph_json_cast<T>(self, \"channel_types\");\n         })\n    .def(\"processors\",\n         [](ArchGraphSystem const &self)\n         {\n           using T = std::pair<unsigned, std::string>;\n           using U = std::vector<T>;\n           return arch_graph_json_cast<U>(self, \"processors\");\n         })\n    .def(\"channels\",\n         [](ArchGraphSystem const &self)\n         {\n           using T = std::pair<unsigned, std::string>;\n           using U = std::map<unsigned, std::vector<T>>;\n           return arch_graph_json_cast<U>(self, \"channels\");\n         })\n    .def(\"num_processors\", &ArchGraphSystem::num_processors)\n    .def(\"num_channels\", &ArchGraphSystem::num_channels)\n    .def(\"initialize\",\n         [&](ArchGraphSystem &self, double timeout)\n         {\n           arch_graph_timeout(\"initialize\",\n                              timeout,\n                              self,\n                              &ArchGraphSystem::init_repr,\n                              nullptr);\n         },\n         \"timeout\"_a = 0.0)\n    .def(\"num_automorphisms\",\n         [](ArchGraphSystem &self, double timeout)\n         {\n           return arch_graph_timeout(\"num_automorphisms\",\n                                     timeout,\n                                     self,\n                                     &ArchGraphSystem::num_automorphisms,\n                                     nullptr);\n         },\n         \"timeout\"_a = 0.0)\n    .def(\"automorphisms_generators\",\n         [](ArchGraphSystem &self, double timeout)\n         {\n           auto generators(arch_graph_timeout(\n             \"automorphisms_generators\",\n             timeout,\n             self,\n             &ArchGraphSystem::automorphisms_generators,\n             nullptr));\n\n           return Sequence<Perm>(generators.begin(), generators.end());\n         },\n         \"timeout\"_a = 0.0)\n    .def(\"automorphisms\",\n         [](ArchGraphSystem &self, double timeout)\n         {\n           return arch_graph_timeout(\"automorphisms\",\n                                     timeout,\n                                     self,\n                                     &ArchGraphSystem::automorphisms,\n                                     nullptr);\n         },\n         \"timeout\"_a = 0.0)\n    .def(\"expand_automorphisms\", &ArchGraphSystem::expand_automorphisms)\n    .def(\"orbit\",\n         [&](ArchGraphSystem &self,\n             Sequence<> const &mapping,\n             double timeout)\n         {\n           for (unsigned task : mapping) {\n             if (task >= self.automorphisms_degree())\n               throw std::invalid_argument(\"task index out of range\");\n           }\n\n           return arch_graph_timeout(\"orbit\",\n                                     timeout,\n                                     self,\n                                     &ArchGraphSystem::automorphisms_orbit,\n                                     mapping,\n                                     nullptr);\n         },\n         \"mapping\"_a, \"timeout\"_a = 0.0)\n    .def(\"representative\",\n         [&](ArchGraphSystem &self,\n             Sequence<> const &mapping,\n             std::string const &method,\n             double timeout)\n         {\n           using T = TaskMapping(ArchGraphSystem::*)(TaskMapping const &,\n                                                     ReprOptions const *,\n                                                     flag);\n\n           auto options(str_to_repr_options(method));\n\n           auto repr(arch_graph_timeout(\"representative\",\n                                        timeout,\n                                        self,\n                                        (T)&ArchGraphSystem::repr,\n                                        mapping,\n                                        &options));\n\n           return to_tuple(repr);\n         },\n         \"mapping\"_a, \"method\"_a = \"auto\", \"timeout\"_a = 0.0)\n    .def(\"representative\",\n         [&](ArchGraphSystem &self,\n             Sequence<> const &mapping,\n             TMORs &representatives,\n             std::string const &method,\n             double timeout)\n         {\n           using T = std::tuple<TaskMapping, bool, unsigned>\n                     (ArchGraphSystem::*)(TaskMapping const &,\n                                          TMORs &,\n                                          ReprOptions const *,\n                                          flag);\n\n\n           auto options(str_to_repr_options(method));\n\n           TaskMapping repr;\n           bool orbit_new;\n           unsigned orbit_index;\n\n           std::tie(repr, orbit_new, orbit_index) =\n             arch_graph_timeout(\"representative\",\n                                timeout,\n                                self,\n                                (T)&ArchGraphSystem::repr,\n                                mapping,\n                                representatives,\n                                &options);\n\n           return std::make_tuple(to_tuple(repr),\n                                  orbit_new,\n                                  orbit_index);\n         },\n         \"mapping\"_a, \"representatives\"_a, \"method\"_a = \"auto\", \"timeout\"_a = 0.0);\n\n  // ArchGraphAutomorphisms\n  py::class_<ArchGraphAutomorphisms,\n             ArchGraphSystem,\n             std::shared_ptr<ArchGraphAutomorphisms>>(m, \"ArchGraphAutomorphisms\")\n    .def(py::init<PermGroup>(), \"automorphisms\"_a)\n    .def(py::pickle(\n        [](ArchGraphAutomorphisms &self)\n        { return self.to_json(); },\n        [](std::string const &json)\n        {\n          return std::dynamic_pointer_cast<ArchGraphAutomorphisms>(\n            ArchGraphSystem::from_json(json));\n        }));\n\n  // ArchGraph\n  py::class_<ArchGraph,\n             ArchGraphSystem,\n             std::shared_ptr<ArchGraph>>(m, \"ArchGraph\")\n    .def(py::init<bool>(), \"directed\"_a = true)\n    .def(py::pickle(\n        [](ArchGraph &self)\n        { return self.to_json(); },\n        [](std::string const &json)\n        {\n          return std::dynamic_pointer_cast<ArchGraph>(\n            ArchGraphSystem::from_json(json));\n        }))\n    .def(\"directed\", &ArchGraph::directed)\n    .def(\"add_processor\",\n         (unsigned(ArchGraph::*)(std::string const &))\n         &ArchGraph::add_processor,\n         \"pl\"_a)\n    .def(\"add_processors\",\n         (unsigned(ArchGraph::*)(unsigned, std::string const &))\n         &ArchGraph::add_processors,\n         \"n\"_a, \"pl\"_a)\n    .def(\"add_channel\",\n         [](ArchGraph &self, unsigned pe1, unsigned pe2, std::string const &cl)\n         {\n           if (pe1 >= self.num_processors() || pe2 >= self.num_processors())\n             throw std::out_of_range(\"processor index out of range\");\n\n           self.add_channel(pe1, pe2, cl);\n         },\n         \"pe1\"_a, \"pe2\"_a, \"cl\"_a)\n    .def(\"add_channels\",\n         [](ArchGraph &self, ArchGraph::ChannelDict<std::string> const &cm)\n         {\n           for (auto const &tmp : cm) {\n             unsigned pe1 = tmp.first;\n             if (pe1 >= self.num_processors())\n               throw std::out_of_range(\"processor index out of range\");\n\n             for (auto const &edge : tmp.second) {\n               unsigned pe2 = edge.first;\n               if (pe2 >= self.num_processors())\n                 throw std::out_of_range(\"processor index out of range\");\n             }\n           }\n\n           self.add_channels<std::string>(cm);\n         },\n         \"channels\"_a)\n    .def(\"add_channels\",\n         [](ArchGraph &self,\n            ArchGraph::ChannelDict<> const &cm,\n            std::string const &ct)\n         {\n           for (auto const &tmp : cm) {\n             unsigned pe1 = tmp.first;\n             if (pe1 >= self.num_processors())\n               throw std::out_of_range(\"processor index out of range\");\n\n             for (unsigned pe2 : tmp.second) {\n               if (pe2 >= self.num_processors())\n                 throw std::out_of_range(\"processor index out of range\");\n             }\n           }\n\n           self.add_channels(cm, ct);\n         },\n         \"channels\"_a, \"ct\"_a)\n    .def(\"fully_connect\",\n         (void(ArchGraph::*)(std::string const &))\n         &ArchGraph::fully_connect,\n         \"cl\"_a)\n    .def(\"fully_connect\",\n         (void(ArchGraph::*)(std::string const &, std::string const &))\n         &ArchGraph::fully_connect,\n         \"pl\"_a, \"cl\"_a)\n    .def(\"fully_connect\",\n         [](ArchGraph &self, py::iterable it, std::string const &cl)\n         {\n           auto processors(to_sequence<>(py::make_iterator(it)));\n\n           for (unsigned pe1 : processors) {\n             for (unsigned pe2 : processors) {\n               if (pe1 != pe2)\n                 self.add_channel(pe1, pe2, cl);\n             }\n           }\n         },\n         \"processors\"_a, \"cl\"_a)\n    .def(\"self_connect\",\n         (void(ArchGraph::*)(std::string const &))\n         &ArchGraph::self_connect,\n         \"cl\"_a)\n    .def(\"self_connect\",\n         (void(ArchGraph::*)(std::string const &, std::string const &))\n         &ArchGraph::self_connect,\n         \"pl\"_a, \"cl\"_a)\n    .def(\"self_connect\",\n         [](ArchGraph &self, py::iterator it, std::string const &cl)\n         {\n           auto processors(to_sequence<>(it));\n\n           for (unsigned pe : processors)\n             self.add_channel(pe, pe, cl);\n         },\n         \"processors\"_a, \"cl\"_a);\n\n  // ArchGraphCluster\n  py::class_<ArchGraphCluster,\n             ArchGraphSystem,\n             std::shared_ptr<ArchGraphCluster>>(m, \"ArchGraphCluster\")\n    .def(py::init<>())\n    .def(py::pickle(\n        [](ArchGraphCluster &self)\n        { return self.to_json(); },\n        [](std::string const &json)\n        {\n          return std::dynamic_pointer_cast<ArchGraphCluster>(\n            ArchGraphSystem::from_json(json));\n        }))\n    .def(\"add_subsystem\", &ArchGraphCluster::add_subsystem, \"subsystem\"_a)\n    .def(\"num_subsystems\", &ArchGraphCluster::num_subsystems);\n\n  // ArchUniformSuperGraph\n  py::class_<ArchUniformSuperGraph,\n             ArchGraphSystem,\n             std::shared_ptr<ArchUniformSuperGraph>>(m, \"ArchUniformSuperGraph\")\n    .def(py::init<std::shared_ptr<ArchGraphSystem>,\n                  std::shared_ptr<ArchGraphSystem>>(),\n         \"super_graph\"_a, \"proto\"_a)\n    .def(py::pickle(\n        [](ArchUniformSuperGraph &self)\n        { return self.to_json(); },\n        [](std::string const &json)\n        {\n          return std::dynamic_pointer_cast<ArchUniformSuperGraph>(\n            ArchGraphSystem::from_json(json));\n        }));\n\n  // TMO\n  py::class_<TMO>(m, \"Orbit\")\n    .def(\"__iter__\",\n         [](TMO &orbit)\n         {\n           IteratorAdaptor<TMO, py::tuple> adaptor(orbit, to_tuple<TaskMapping>);\n\n           return py::make_iterator<py::return_value_policy::copy>(adaptor.begin(),\n                                                                   adaptor.end());\n         }, py::keep_alive<0, 1>());\n\n  // TMORs\n  py::class_<TMORs>(m, \"Representatives\")\n    .def(py::init<>())\n    .def(py::self == py::self)\n    .def(py::self != py::self)\n    .def(\"__len__\", &TMORs::num_orbits)\n    .def(\"__iter__\",\n         [](TMORs const &orbits)\n         { return py::make_iterator(orbits.begin(), orbits.end()); },\n         py::keep_alive<0, 1>())\n    .def(\"__contains__\",\n         [](TMORs const &orbits, Sequence<> const &mapping)\n         { return orbits.is_repr(mapping); },\n         \"mapping\"_a);\n\n  // Perm\n  py::class_<Perm>(m, \"Perm\")\n    .def(py::init<unsigned>(), \"degree\"_a = 1)\n    .def(py::init(\n           [](Sequence<> const &v)\n           {\n             if (v.empty())\n                throw std::invalid_argument(\"invalid permutation\");\n\n             auto max = *std::max_element(v.begin(), v.end());\n             if (v.size() != max + 1)\n               throw std::invalid_argument(\"invalid permutation\");\n\n             std::set<unsigned> s(v.begin(), v.end());\n             if (s.size() != max + 1 || *s.begin() != 0)\n               throw std::invalid_argument(\"invalid permutation\");\n\n             return Perm(v);\n           }),\n         \"perm\"_a)\n    .def(py::init(\n           [](unsigned degree, Sequence<Sequence<>> const &cycles)\n           {\n             std::unordered_set<unsigned> cycles_flattened;\n\n             for (auto const &cycle : cycles) {\n                for (unsigned x : cycle) {\n                  if (x > degree || !cycles_flattened.insert(x).second)\n                    throw std::invalid_argument(\"invalid permutation\");\n                }\n             }\n\n             return Perm(degree, cycles);\n           }),\n           \"degree\"_a, \"cycles\"_a)\n    .def(py::init(\n           [](unsigned degree, std::string cycles)\n           { return str_to_perm(degree, cycles); }),\n           \"degree\"_a, \"cycles\"_a)\n    .def(\"__eq__\",\n         [](Perm const &self, Perm const &other)\n         {\n           if (self.degree() != other.degree())\n             throw std::invalid_argument(\"can only compare permutations of equal degree\");\n\n           return self == other;\n         })\n    .def(\"__ne__\",\n         [](Perm const &self, Perm const &other)\n         {\n           if (self.degree() != other.degree())\n             throw std::invalid_argument(\"can only compare permutations of equal degree\");\n\n           return self != other;\n         })\n    .def(hash(py::self))\n    .def(\"__getitem__\",\n         [](Perm const &self, unsigned x)\n         {\n           if (x > self.degree() - 1)\n             throw std::out_of_range(\"not in domain\");\n\n           return self[x];\n         },\n         \"x\"_a)\n    .def(\"__invert__\", &Perm::operator~)\n    .def(\"__mul__\",\n         [](Perm const &self, Perm const &other)\n         {\n           if (self.degree() != other.degree())\n             throw std::invalid_argument(\"permutation degrees do not match\");\n\n           return self * other;\n         },\n         \"other\"_a)\n    .def(\"__rmul__\",\n         [](Perm const &self, Perm const &other)\n         {\n           if (self.degree() != other.degree())\n             throw std::invalid_argument(\"permutation degrees do not match\");\n\n           return other * self;\n         },\n         \"other\"_a)\n    .def(\"__bool__\",\n         [](Perm const &self)\n         { return !self.id(); })\n    .def(\"__repr__\",\n         [](Perm const &self)\n         { return stream(self); })\n    .def(\"degree\", &Perm::degree);\n\n  py::implicitly_convertible<Sequence<>, Perm>();\n\n  // PermGroup\n  py::class_<PermGroup>(m, \"PermGroup\")\n    .def(py::init<unsigned>(), \"degree\"_a = 1)\n    .def(py::init(\n           [](Sequence<Perm> const &generators_)\n           {\n             if (generators_.empty())\n               throw std::invalid_argument(\"generating set must not be empty\");\n\n             unsigned degree = generators_[0].degree();\n             for (std::size_t i = 1; i < generators_.size(); ++i) {\n                if (generators_[i].degree() != degree)\n                  throw std::invalid_argument(\"mismatched generator degrees\");\n             }\n\n             PermSet generators(generators_.begin(), generators_.end());\n\n             return PermGroup(degree, generators);\n           }),\n         \"generators\"_a)\n    .def(py::init(\n           [](unsigned degree, Sequence<std::string> const &generators_)\n           {\n             PermSet generators;\n             for (auto const &gen : generators_)\n               generators.insert(str_to_perm(degree, gen));\n\n             return PermGroup(degree, generators);\n           }),\n         \"degree\"_a, \"generators\"_a)\n    .def_static(\"symmetric\", PermGroup::symmetric, \"degree\"_a)\n    .def_static(\"cyclic\", PermGroup::cyclic, \"degree\"_a)\n    .def_static(\"dihedral\", PermGroup::dihedral, \"degree\"_a)\n    .def_static(\"direct_product\",\n                [](py::iterable it)\n                {\n                  auto groups(to_sequence<PermGroup>(py::make_iterator(it)));\n\n                  return PermGroup::direct_product(groups.begin(), groups.end());\n                },\n                \"groups\"_a)\n    .def_static(\"wreath_product\",\n                [](PermGroup const &lhs, PermGroup const &rhs)\n                { return PermGroup::wreath_product(lhs, rhs); },\n                \"lhs\"_a, \"rhs\"_a)\n    .def(\"__eq__\",\n         [](PermGroup const &self, PermGroup const &other)\n         {\n           if (self.degree() != other.degree())\n             throw std::invalid_argument(\"can only compare permutation groups of equal degree\");\n\n           return self == other;\n         })\n    .def(\"__ne__\",\n         [](PermGroup const &self, PermGroup const &other)\n         {\n           if (self.degree() != other.degree())\n             throw std::invalid_argument(\"can only compare permutation groups of equal degree\");\n\n           return self != other;\n         })\n    .def(\"__len__\", &PermGroup::order)\n    .def(\"__iter__\",\n         [](PermGroup const &self)\n         { return py::make_iterator<py::return_value_policy::copy>(self.begin(), self.end()); },\n         py::keep_alive<0, 1>())\n    .def(\"__contains__\",\n         [](PermGroup const &self, Perm const &p)\n         {\n           if (p.degree() != self.degree())\n             throw std::invalid_argument(\"mismatched degrees\");\n\n           return self.contains_element(p);\n         },\n         \"perm\"_a)\n    .def(\"__contains__\",\n         [](PermGroup const &self, std::string const &p)\n         { return self.contains_element(str_to_perm(self.degree(), p)); },\n         \"perm\"_a)\n    .def(\"__bool__\",\n         [](PermGroup const &self)\n         { return !self.is_trivial(); })\n    .def(\"__repr__\",\n         [](PermGroup const &self)\n         { return stream(self.generators()); })\n    .def(\"degree\", &PermGroup::degree)\n    .def(\"bsgs\",\n         [&](PermGroup const &self)\n         {\n           auto bsgs(self.bsgs());\n\n           return std::make_pair<BSGS::Base, Sequence<Perm>>(\n             bsgs.base(),\n             to_sequence(bsgs.strong_generators()));\n         })\n    .def(\"generators\",\n         [&](PermGroup const &self, bool sorted)\n         {\n           auto generators(self.generators());\n\n           if (sorted)\n             std::sort(generators.begin(), generators.end());\n\n           return to_sequence(generators);\n         },\n         \"sorted\"_a = true)\n    .def(\"is_symmetric\", &PermGroup::is_symmetric)\n    .def(\"is_transitive\", &PermGroup::is_transitive);\n\n  py::implicitly_convertible<Sequence<Perm>, PermGroup>();\n}\n", "meta": {"hexsha": "c112112a0ca5df8c5ebaf7eb8daa14639b589722", "size": 26845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/source/_mpsym.cpp", "max_stars_repo_name": "goens/TUD_computational_group_theory", "max_stars_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/source/_mpsym.cpp", "max_issues_repo_name": "goens/TUD_computational_group_theory", "max_issues_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-22T09:40:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-23T11:03:30.000Z", "max_forks_repo_path": "python/source/_mpsym.cpp", "max_forks_repo_name": "goens/TUD_computational_group_theory", "max_forks_repo_head_hexsha": "3f4703cae1ac049089db23eafc321e8daca2d99d", "max_forks_repo_licenses": ["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.8982843137, "max_line_length": 96, "alphanum_fraction": 0.5333954181, "num_tokens": 6040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098087851200094, "lm_q2_score": 0.023330770888190494, "lm_q1q2_score": 0.006788808209407886}}
{"text": "/*\n * modules/cmoea/cmoea_nsga2_mpi.hpp\n *\n *  Created on: Mar 12, 2015\n *      Author: Joost Huizinga\n */\n\n#ifndef MODULES_CMOEA_CMOEA_NSGA2_MPI_HPP_\n#define MODULES_CMOEA_CMOEA_NSGA2_MPI_HPP_\n\n// Standard includes\n#include <algorithm>\n#include <limits>\n\n// Boost includes\n#include <boost/foreach.hpp>\n#include <boost/multi_array.hpp>\n#include <boost/array.hpp>\n#include <boost/fusion/algorithm/iteration/for_each.hpp>\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/spirit/include/karma.hpp>\n#include <boost/mpi.hpp>\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/detail/point_to_point.hpp>\n\n// Sferes includes\n#include <sferes/stc.hpp>\n#include <sferes/ea/ea.hpp>\n#include <sferes/fit/fitness.hpp>\n#include <sferes/dbg/dbg.hpp>\n#include <sferes/ea/dom_sort_basic.hpp>\n#include <sferes/ea/common.hpp>\n#include <sferes/ea/crowd.hpp>\n\n// Module includes\n#include <modules/datatools/common_compare.hpp>\n#include <modules/debugext/dbgext.hpp>\n\n// Local includes\n#include \"cmoea_nsga2.hpp\"\n#include \"mpi_util.hpp\"\n#include \"nsga_util.hpp\"\n\n// Debug defines\n#define DBOW dbg::out(dbg::info, \"mpi\") << \"Worker \" << _world->rank()\n#define DBOM dbg::out(dbg::info, \"mpi\") << \"Master \" << this->eval().world()->rank()\n#define DBOE dbg::out(dbg::info, \"ea\")\n\nnamespace karma = boost::spirit::karma;\n\nnamespace sferes\n{\nnamespace ea\n{\n\ntemplate<typename Phen, typename FitModifier, typename Params>                                                       \\\nclass ArchiveTask{\npublic:\n    //Params\n    typedef ArchiveTask<Phen, FitModifier, Params> this_t;\n\n    //The type of Pareto domination sort to use.\n    //Currently available types are:\n    // - sferes::ea::dom_sort_basic_f  (defined in sferes/ea/dom_sort_basic.hpp)\n    //   Sorts according to pareto dominance and will add individuals from the\n    //   highest to the lowest layer, with crowding as a tie-breaker in the last\n    //   layer to be added.\n    // - sferes::ea::dom_sort_no_duplicates_f\n    //   (defined in sferes/ea/dom_sort_no_duplicates.hpp)\n    //   Same as dom_sort_basic, accept that, for each front, only one\n    //   individual per pareto location is added. Other individuals at the same\n    //   location will be bumped to the next layer.\n    typedef typename Params::ea::dom_sort_f dom_sort_f;\n\n    //The type non dominated comparator to use\n    //Currently available types are:\n    // - sferes::ea::_dom_sort_basic::non_dominated_f\n    //   (defined in sferes/ea/dom_sort_basic.hpp)\n    //   Regular comparisons based on dominance\n    // - sferes::ea::cmoea_nsga::prob_dom_f<Params>\n    //   Comparisons based on probabilistic sorting, where some objectives can\n    //   be stronger than others.\n    typedef typename Params::cmoea_nsga::non_dom_f non_dom_f;\n\n    //The index used to temporarily store the category\n    //This index should hold a dummy value, as it will be overwritten\n    //constantly.\n    //The default would be 0.\n    static const size_t obj_index = Params::cmoea::obj_index;\n\n    //The number of objectives (bins) used in the map\n    size_t nr_of_bins;\n\n    //The size of each bin\n    static const size_t bin_size = Params::cmoea::bin_size;\n\n    //The number of individuals initially generated to fill the archive\n    //If equal to the bin_size, every initially generated individual is added\n    //to every bin of every category.\n    //The init_size has to be greater than or equal to the bin_size\n    static const size_t init_size = Params::pop::init_size;\n\n    //Not actually the size of the standing population\n    //(which is bin_size*nr_of_bins)\n    //but the number of individuals that are generated each epoch.\n    //Because individuals are always produced in pairs,\n    //pop_size has to be divisible by 2.\n    static const size_t indiv_per_gen = Params::pop::select_size;\n\n    //Modifier for calculating distance\n    typedef typename boost::mpl::if_<boost::fusion::traits::is_sequence<FitModifier>,\n                     FitModifier,\n                     boost::fusion::vector<FitModifier> >::type modifier_t;\n\n    typedef Phen phen_t;\n    typedef crowd::Indiv<phen_t> crowd_t;\n    typedef boost::shared_ptr<crowd_t> indiv_t;\n    typedef typename std::vector<indiv_t> pop_t;\n    typedef typename std::vector<boost::shared_ptr<phen_t> > ea_pop_t;\n    typedef typename std::vector<std::vector<indiv_t> > front_t;\n\n    modifier_t _fit_modifier;\n    ea_pop_t _pop;\n\n    ArchiveTask(){\n    \tnr_of_bins = Params::cmoea::nb_of_bins;\n    }\n\n    void run(boost::shared_ptr<boost::mpi::communicator> _world,\n    \t\tboost::mpi::status s,\n\t\t\tboost::shared_ptr<boost::mpi::environment> env)\n    {\n        dbg::trace trace(\"ea\", DBG_HERE);\n        pop_t pop;\n        pop_t archive;\n        pop_t new_bin;\n        indiv_t temp;\n\n\n        DBOW << \" receiving broadcast from world: \" << _world << std::endl;\n        better_broadcast(_world, pop);\n        DBOW << \" received pop of size: \" << pop.size() << std::endl;\n\n        while(true){\n        \tDBOW << \" waiting for message in cmoea_nsga2_mpi.hpp\" << std::endl;\n            s = _world->probe();\n            DBOW << \" receveived message in cmoea_nsga2_mpi.hpp tag: \" <<\n            \t\ts.tag() << \" source: \" << s.source()  << std::endl;\n            if (s.tag() == env->max_tag()){\n                break;\n            }\n\n            DBOW << \" receiving archive.\" << std::endl;\n            _world->recv(0, s.tag(), archive);\n            DBOW << \" archive received.\" << std::endl;\n\n            for(size_t j = 0; j < pop.size(); ++j){\n                archive.push_back(pop[j]);\n            }\n            DBOW << \" applying modifier\" << std::endl;\n            _apply_modifier(archive);\n            _cat_to_obj(archive, s.tag());\n            DBOW << \" sorting\" << std::endl;\n            _fill_nondominated_sort(archive, new_bin);\n            DBOW << \" sending bin: \" << s.tag() <<\n            \t\t\" size: \" << new_bin.size() << std::endl;\n            _world->send(0, s.tag(), new_bin);\n        }\n    }\n\n    // modifiers\n   void apply_modifier()\n   { boost::fusion::for_each(_fit_modifier, ApplyModifier_f<this_t>(*this)); }\n\n   const ea_pop_t& pop() const { return _pop; };\n   ea_pop_t& pop() { return _pop; };\n\nprotected:\n    /**\n     * Converts a population from array individuals to regular individuals.\n     */\n    void _convert_pop(const pop_t& pop1, ea_pop_t& pop2){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        pop2.resize(pop1.size());\n        for (size_t i = 0; i < pop1.size(); ++i){\n            pop2[i] = pop1[i];\n        }\n    }\n\n    /**\n     * Converts a population from regular individuals to crowd individuals.\n     */\n    void _convert_pop(const ea_pop_t& pop1, pop_t& pop2){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        pop2.resize(pop1.size());\n        for (size_t i = 0; i < pop1.size(); ++i){\n            pop2[i] = boost::shared_ptr<crowd_t>(new crowd_t(*pop1[i]));\n        }\n    }\n\n    /**\n     * Does not actually convert anything, merely copies the content from one\n     * pop to the other pop.\n     */\n    void _convert_pop(const pop_t& pop1, pop_t& pop2){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        pop2.resize(pop1.size());\n        for (size_t i = 0; i < pop1.size(); ++i){\n            pop2[i] = pop1[i];\n        }\n    }\n \n\n    /**\n     * Applies the modifier to the supplied population (vector of individuals).\n     *\n     * Note that this overwrites the this->_pop population.\n     */\n    void _apply_modifier(pop_t pop){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        _convert_pop(pop, this->_pop);\n        apply_modifier();\n    }\n\n    /**\n     * Selects a random individual from the supplied population.\n     */\n    indiv_t _selection(const pop_t& pop){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        int x1 = misc::rand< int > (0, pop.size());\n        dbg::check_bounds(dbg::error, 0, x1, pop.size(), DBG_HERE);\n        return pop[x1];\n    }\n\n    /**\n     * Takes a mixed population, sorts it according to Pareto dominance, and\n     * generates a new population depending on the bin size.\n     *\n     * @Param mixed_pop The mixed population from which to select.\n     *                  The mixed population must be larger than the bin_size\n     *                  for selection to occur.\n     * @Param new_pop   Output parameter. After execution, should contain a\n     * \t\t\t\t\tnumber of individuals equal to the bin_size, selected\n     * \t\t\t\t\tbased on Pareto dominance first, crowding second.\n     */\n    void _fill_nondominated_sort(pop_t& mixed_pop, pop_t& new_pop)\n    {\n        dbg::trace trace(\"ea\", DBG_HERE);\n        dbg::out(dbg::info, \"ea\") << \"Mixed pop size: \" << mixed_pop.size() <<\n        \t\t\" bin size: \" << bin_size << std::endl;\n        dbg::assertion(DBG_ASSERTION(mixed_pop.size()));\n        dbg::assertion(DBG_ASSERTION(mixed_pop.size() >= bin_size));\n\n        //Rank the population according to Pareto fronts\n        front_t fronts;\n        _rank_crowd(mixed_pop, fronts);\n\n        //Add Pareto layers to the new population until the current layer no\n        //longer fits\n        new_pop.clear();\n        size_t front_index = 0;\n        while(fronts[front_index].size() + new_pop.size() < bin_size){\n            new_pop.insert(new_pop.end(), fronts[front_index].begin(),\n            \t\tfronts[front_index].end());\n            ++front_index;\n        }\n\n        // sort the last layer\n        size_t size_remaining = bin_size - new_pop.size();\n        if (size_remaining > 0){\n            dbg::assertion(DBG_ASSERTION(front_index < fronts.size()));\n            std::sort(fronts[front_index].begin(), fronts[front_index].end(),\n            \t\tcrowd::compare_crowd());\n            for (size_t k = 0; k < size_remaining; ++k){\n                new_pop.push_back(fronts[front_index][k]);\n            }\n        }\n        dbg::assertion(DBG_ASSERTION(new_pop.size() == bin_size));\n    }\n\n    // --- rank & crowd ---\n\n    /**\n     * Ranks and crowds a population.\n     *\n     * Takes a population and divides it based on objectives.\n     *\n     * @param pop    The population to be ranked.\n     * @param fronts The resulting Pareto fronts will be stored here.\n     */\n    void _rank_crowd(pop_t& pop, front_t& fronts)\n    {\n        dbg::trace trace(\"ea\", DBG_HERE);\n        //Execute ranking based on dominance\n        std::vector<size_t> ranks;\n        dom_sort_f()(pop, fronts, non_dom_f(), ranks);\n\n        //Why are we assigning a crowd score to every individual?\n        parallel::p_for(parallel::range_t(0, fronts.size()),\n        \t\tcrowd::assign_crowd<indiv_t >(fronts));\n    }\n\n\n    /**\n     * For the specified category and array, copies the category score to the\n     * obj_index (usually 1).\n     */\n    void _cat_to_obj(pop_t& bin, size_t bin_i){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        for(size_t i=0; i<bin.size(); ++i){\n        \tfloat fit = bin[i]->fit().getBinFitness(bin_i);\n            bin[i]->fit().set_obj(obj_index, fit);\n        }\n    }\n\n    /**\n     * Copies the stored diversity back to the relevant objective.\n     *\n     * Does nothing when DIV is not defined\n     */\n    void _div_to_obj(pop_t& bin, size_t category){\n        dbg::trace trace(\"ea\", DBG_HERE);\n#if defined(DIV)\n        for(size_t i=0; i<bin.size(); ++i){\n            size_t div_index = bin[i]->fit().objs().size() - 1;\n            float div = bin[i]->fit().getBinDiversity(category);\n            bin[i]->fit().set_obj(div_index, div);\n        }\n#endif\n    }\n\n    /**\n     * Copies the calculated diversity to the individuals diversity array.\n     *\n     * Does nothing when DIV is not defined\n     */\n    void _obj_to_div(pop_t& bin, size_t category){\n        dbg::trace trace(\"ea\", DBG_HERE);\n#if defined(DIV)\n        for(size_t j = 0; j < bin.size(); ++j){\n            bin[j]->fit().initDiv();\n            size_t div_index = bin[j]->fit().objs().size() - 1;\n            bin[j]->fit().setDiv(category, bin[j]->fit().obj(div_index));\n        }\n#endif\n    }\n};\n\n\n// Main class\nSFERES_EA(CmoeaNsga2Mpi, CmoeaNsga2){\npublic:\n    //Params\n\n    //The type of Pareto domination sort to use.\n    //Currently available types are:\n    // - sferes::ea::dom_sort_basic_f\n\t//   (defined in sferes/ea/dom_sort_basic.hpp)\n    //   Sorts according to pareto dominance and will add individuals from the\n\t//   highest to the lowest layer, with crowding as a tie-breaker in the last\n\t//   layer to be added.\n    // - sferes::ea::dom_sort_no_duplicates_f\n\t//   (defined in sferes/ea/dom_sort_no_duplicates.hpp)\n    //   Same as dom_sort_basic, accept that, for each front, only one\n\t//   individual per pareto location is added. Other individuals at the same\n\t//   location will be bumped to the next layer.\n    typedef typename Params::ea::dom_sort_f dom_sort_f;\n\n    //The type non dominated comparator to use\n    //Currently available types are:\n    // - sferes::ea::_dom_sort_basic::non_dominated_f\n    //   (defined in sferes/ea/dom_sort_basic.hpp)\n    //   Regular comparisons based on dominance\n    // - sferes::ea::cmoea_nsga::prob_dom_f<Params>\n    //   Comparisons based on probabilistic sorting, where some objectives can\n    //   be stronger than others.\n    typedef typename Params::cmoea_nsga::non_dom_f non_dom_f;\n\n    //The index used to temporarily store the category\n    //This index should hold a dummy value, as it will be overwritten\n    //constantly. The default would be 0.\n    static const size_t obj_index = Params::cmoea::obj_index;\n\n    //The number of objectives (bins) used in the map\n    size_t nr_of_bins;\n\n    //The size of each bin\n    static const size_t bin_size = Params::cmoea::bin_size;\n\n    //The number of individuals initially generated to fill the archive\n    //If equal to the bin_size, every initially generated individual is added\n    //to every bin of every category.\n    //The init_size has to be greater than or equal to the bin_size\n    static const size_t init_size = Params::pop::init_size;\n\n    // Very large initial populations may cause CMOEA to run out of memory.\n    // To avoid this, you can add the initial populations in init_batch batches\n    // of init_size.\n//    static const size_t init_batch = Params::pop::init_batch;\n\n    //Not actually the size of the standing population\n    //(which is bin_size*nr_of_bins)\n    //but the number of individuals that are generated each epoch.\n    //Because individuals are always produced in pairs,\n    //pop_size has to be divisible by 2.\n    static const size_t indiv_per_gen = Params::pop::select_size;\n\n    typedef Phen phen_t;\n    typedef crowd::Indiv<phen_t> crowd_t;\n    typedef boost::shared_ptr<crowd_t> indiv_t;\n    typedef std::vector<indiv_t> pop_t;\n    typedef boost::shared_ptr<phen_t> raw_indiv_t;\n    typedef std::vector<raw_indiv_t> raw_pop_t;\n    typedef typename std::vector<pop_t> front_t;\n    typedef std::vector<pop_t> array_t;\n    SFERES_EA_FRIEND(CmoeaNsga2Mpi);\n\n    CmoeaNsga2Mpi()\n    {\n        dbg::trace trace(\"ea\", DBG_HERE);\n        //dbg::compile_assertion<pop_size%2 == 0>(\"Population size has to be\n        //divisible by 2.\");\n        DBOE << \"Objectives: \" << nr_of_bins << std::endl;\n        nr_of_bins = Params::cmoea::nb_of_bins;\n        this->_array.resize(nr_of_bins);\n    }\n\n//    void random_pop()\n//    {\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        DBOE << \"Generating random pop\" << std::endl;\n//        //Create and evaluate the initial random population\n//        parallel::init();\n//        for(unsigned j=0; j<init_batch; ++j){\n//            pop_t pop;\n//            pop.resize(init_size);\n//            int i = 0;\n//            BOOST_FOREACH(indiv_t& indiv, pop)\n//            {\n//            \tDBOE << \"Creating random individual: \" << i++ << std::endl;\n//                indiv = indiv_t(new crowd_t());\n//                indiv->random();\n//            }\n//            DBOE << \"Evaluating population\" << std::endl;\n//            this->_eval.eval(pop, 0, pop.size(), this->_fit_proto);\n//\n//            DBOE << \"Applying modifier\" << std::endl;\n//            _apply_modifier(pop);\n//\n//            DBOE << \"Adding to archive\" << std::endl;\n//            _add_to_archive(pop);\n//        }\n//        DBOE << \"Generating random pop done\" << std::endl;\n//\n//        DBG_CONDITIONAL(dbg::info, \"archive\", this->_init_debug_array());\n//    }\n//\n//    void epoch(){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//\n//        //We are creating and selecting a number of individuals equal to the\n//        //population size. A simpler variant would only select and mutate one\n//        //individual\n//        pop_t ptmp;\n//        for(size_t i=0; i<_array.size(); ++i){\n//            if(_array[i].size() != bin_size){\n//                std::cout << \"Before reproduction: bin \" << i <<\n//                \t\t\" contains only \" << _array[i].size() <<\n//\t\t\t\t\t\t\" indiv.\" <<std::endl;\n//            }\n//        }\n//        for (size_t i = 0; i < (indiv_per_gen/2); ++i)\n//        {\n//        \tDBOE << \"Creating individual: \" << i <<std::endl;\n//            indiv_t p1 = _selection(_array);\n//            indiv_t p2 = _selection(_array);\n//            indiv_t i1, i2;\n//\n//            p1->cross(p2, i1, i2);\n//            i1->mutate();\n//            i2->mutate();\n//            ptmp.push_back(i1);\n//            ptmp.push_back(i2);\n//        }\n//        this->_eval.eval(ptmp, 0, ptmp.size(), this->_fit_proto);\n//        _add_to_archive(ptmp);\n//\n//        for(size_t i=0; i<_array.size(); ++i){\n//            if(_array[i].size() != bin_size){\n//                std::cout << \"After reproduction: bin \" << i <<\n//                \t\t\" contains only \" << _array[i].size() <<\n//\t\t\t\t\t\t\" indiv.\" <<std::endl;\n//            }\n//        }\n//\n//        //For writing statistics only from the first bin:\n//        _convert_pop(_array, this->_pop);\n//\n//        DBG_CONDITIONAL(dbg::info, \"archive\", this->_print_archive());\n//    }\n//\n//    const array_t& archive() const { return _array; }\n\n\n    /**\n     * Adds the new `population' (vector of individuals) to the archive by\n     * adding every individual to every bin, and then running NSGA 2 (or pNSGA)\n     * selection on every bin.\n     */\n    void add_to_archive(pop_t& pop){\n        dbg::trace trace(\"ea\", DBG_HERE);\n        //Add everyone to the archive\n\n        //Set new task\n        for (size_t i = 1; i < this->eval().world()->size(); ++i){\n            this->eval().world()->send(i, this->eval().env()->max_tag(), 1);\n        }\n\n\n        //Broadcast the new individuals to all workers\n        DBOM << \"Broadcasting population of size: \" <<\n        \t\tpop.size() << \" to world: \" << this->eval().world() <<\n\t\t\t\tstd::endl;\n        better_broadcast(this->eval().world(), pop);\n\n\n        size_t current = 0;\n        std::vector<bool> done(nr_of_bins);\n        std::fill(done.begin(), done.end(), false); // @suppress(\"Ambiguous problem\")\n//        std::fill<std::vector<bool>::iterator>(done.begin(), done.end(), false);\n\n        // first round\n        size_t world_size = this->eval().world()->size();\n        for (size_t i = 1; i < world_size && current < nr_of_bins; ++i) {\n        \tDBOM << \"Sending bin: \" << current  <<\n        \t\t\t\" to worker \" << i << std::endl;\n            this->eval().world()->send(i, current, this->_array[current]);\n            ++current;\n        }\n\n        // Subsequent rounds\n        while (current < nr_of_bins){\n            boost::mpi::status s = this->eval().world()->probe();\n            DBOM << \"Receiving bin: \" << s.tag() << std::endl;\n            this->eval().world()->recv(s.source(), s.tag(), this->_array[s.tag()]);\n            DBOM << \"Received bin: \" << s.tag() <<\n            \t\t\" size: \" << this->_array[s.tag()].size()  << std::endl;\n            done[s.tag()] = true;\n            DBOM << \"Sending bin: \" << current << std::endl;\n            this->eval().world()->send(s.source(), current, this->_array[current]);\n            ++current;\n        }\n\n        // Join\n        bool all_done = true;\n        do{\n        \tDBOM << \"joining...\"<<std::endl;\n            all_done = true;\n            for (size_t i = 0; i < nr_of_bins; ++i){\n                if (!done[i]){\n                    boost::mpi::status s = this->eval().world()->probe();\n                    DBOM << \"Receiving bin: \" << s.tag() << std::endl;\n                    this->eval().world()->recv(s.source(), s.tag(),\n                    \t\tthis->_array[s.tag()]);\n                    DBOM << \"Received bin: \" << s.tag() <<\n                    \t\t\" size: \" << this->_array[s.tag()].size()  << std::endl;\n                    done[s.tag()] = true;\n                    all_done = false;\n                }\n            }\n        }\n        while (!all_done);\n    }\n\nprotected:\n//    array_t _array;\n//\n//    /**\n//     * Converts a population from array individuals to regular individuals.\n//     */\n//    void _convert_pop(const pop_t& pop1, raw_pop_t& pop2){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        pop2.resize(pop1.size());\n//        for (size_t i = 0; i < pop1.size(); ++i){\n//            pop2[i] = pop1[i];\n//        }\n//    }\n//\n//    /**\n//     * Converts the entire array of individuals to regular individuals.\n//     */\n//    void _convert_pop(const array_t& array, raw_pop_t& pop2){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        pop2.resize(array.size() * bin_size);\n//        size_t k=0;\n//        for (size_t i = 0; i < array.size(); ++i){\n//          for (size_t j = 0; j < bin_size; ++j){\n//            pop2[k++] = array[i][j];\n//          }\n//        }\n//    }\n//\n//    /**\n//     * Converts a population from regular individuals to crowd individuals.\n//     */\n//    void _convert_pop(const raw_pop_t& pop1, pop_t& pop2){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        pop2.resize(pop1.size());\n//        for (size_t i = 0; i < pop1.size(); ++i){\n//            pop2[i] = boost::shared_ptr<crowd_t>(new crowd_t(*pop1[i]));\n//        }\n//    }\n//\n//    /**\n//     * Initialize the archive give a population.\n//     */\n//    void _set_pop(const raw_pop_t& pop) {\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        pop_t converted_pop;\n//        this->_convert_pop(pop, converted_pop);\n//\n//        dbg::out(dbg::info, \"continue\") << \"Adding: \" << converted_pop.size()\n//                << \" to archive: \" << this-> _array.size()\n//                << \" by \" << this->bin_size << std::endl;\n//        dbg::assertion(DBG_ASSERTION(pop.size() == converted_pop.size()));\n//        dbg::assertion(DBG_ASSERTION(converted_pop.size() ==\n//        \t\tthis->_array.size()*this->bin_size));\n//\n//        //Add everyone to the archive in the appropriate place\n//        size_t pop_index = 0;\n//        for(size_t i=0; i<this->_array.size(); ++i){\n//            for(size_t j=0; j<this->bin_size; ++j){\n//                this->_array[i].push_back(converted_pop[pop_index]);\n//                ++pop_index;\n//            }\n//        }\n//\n//        DBG_CONDITIONAL(dbg::info, \"archive\", this->_init_debug_array());\n//    }\n//\n//    /**\n//     * Applies the modifier to the supplied population (vector of individuals).\n//     *\n//     * Note that this overwrites the this->_pop population.\n//     */\n//    void _apply_modifier(pop_t pop){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        _convert_pop(pop, this->_pop);\n//        this->apply_modifier();\n//    }\n//\n//\n//\n//    /**\n//     * Selects a random individual from the supplied population.\n//     */\n//    indiv_t _selection(const pop_t& pop){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        int x1 = misc::rand< int > (0, pop.size());\n//        dbg::check_bounds(dbg::error, 0, x1, pop.size(), DBG_HERE);\n//        return pop[x1];\n//    }\n//\n//    /**\n//     * Selects a random individual from the supplied archive\n//     */\n//    indiv_t _selection(const array_t& archive){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        size_t category = misc::rand< size_t > (0, archive.size());\n//        dbg::check_bounds(dbg::error, 0, category, archive.size(), DBG_HERE);\n//        size_t size = archive[category].size();\n//        size_t indiv_i = misc::rand< size_t > (0, size);\n//        dbg::check_bounds(dbg::error, 0, indiv_i, size, DBG_HERE);\n//        return archive[category][indiv_i];\n//    }\n//\n//    /**\n//     * Takes a mixed population, sorts it according to Pareto dominance, and\n//     * generates a new population depending on the bin size.\n//     *\n//     * @Param mixed_pop The mixed population from which to select.\n//     *                  The mixed population must be larger than the bin_size\n//     *                  for selection to occur.\n//     * @Param new_pop   Output parameter. After execution, should contain a\n//     * \t\t\t\t\tnumber of individuals equal to the bin_size, selected\n//     * \t\t\t\t\tbased on Pareto dominance first, crowding second.\n//     */\n//    void _fill_nondominated_sort(pop_t& mixed_pop, pop_t& new_pop)\n//    {\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        dbg::assertion(DBG_ASSERTION(mixed_pop.size()));\n//\n//        //Rank the population according to Pareto fronts\n//        front_t fronts;\n//        _rank_crowd(mixed_pop, fronts);\n//\n//        //Add Pareto layers to the new population until the current layer no\n//        //longer fits\n//        new_pop.clear();\n//        size_t front_index = 0;\n//        while(fronts[front_index].size() + new_pop.size() < bin_size){\n//            new_pop.insert(new_pop.end(), fronts[front_index].begin(),\n//            \t\tfronts[front_index].end());\n//            ++front_index;\n//        }\n//\n//        // sort the last layer\n//        size_t size_remaining = bin_size - new_pop.size();\n//        if (size_remaining > 0){\n//            dbg::assertion(DBG_ASSERTION(front_index < fronts.size()));\n//            std::sort(fronts[front_index].begin(), fronts[front_index].end(),\n//            \t\tcrowd::compare_crowd());\n//            for (size_t k = 0; k < size_remaining; ++k){\n//                new_pop.push_back(fronts[front_index][k]);\n//            }\n//        }\n//        dbg::assertion(DBG_ASSERTION(new_pop.size() == bin_size));\n//    }\n//\n//    // --- rank & crowd ---\n//\n//    /**\n//     * Ranks and crowds a population.\n//     *\n//     * Takes a population and divides it based on objectives.\n//     *\n//     * @param pop    The population to be ranked.\n//     * @param fronts The resulting Pareto fronts will be stored here.\n//     */\n//    void _rank_crowd(pop_t& pop, front_t& fronts)\n//    {\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        //Execute ranking based on dominance\n//        std::vector<size_t> ranks;\n//        dom_sort_f()(pop, fronts, non_dom_f(), ranks);\n//\n//        //Why are we assigning a crowd score to every individual?\n//        parallel::p_for(parallel::range_t(0, fronts.size()),\n//        \t\tcrowd::assign_crowd<indiv_t >(fronts));\n//    }\n//\n//\n//    /**\n//     * For the specified category and array, copies the category score to the\n//     * obj_index (usually 1).\n//     */\n//    void _cat_to_obj(array_t& array, size_t category){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        dbg::check_bounds(dbg::error, 0, category, array.size(), DBG_HERE);\n//        for(size_t i=0; i<array[category].size(); ++i){\n//            array[category][i]->fit().set_obj(obj_index,\n//            \t\tarray[category][i]->fit().getBinFitness(category));\n//        }\n//    }\n//\n//    /**\n//     * Copies the stored diversity back to the relevant objective.\n//     *\n//     * Does nothing when DIV is not defined\n//     */\n//    void _div_to_obj(array_t& array, size_t category){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//#if defined(DIV)\n//        for(size_t i=0; i<bin_size; ++i){\n//            size_t div_index = _array[category][i]->fit().objs().size() - 1;\n//            array[category][i]->fit().set_obj(div_index,\n//            \t\tarray[category][i]->fit().getBinDiversity(category));\n//        }\n//#endif\n//    }\n//\n//    /**\n//     * Copies the calculated diversity to the individuals diversity array.\n//     *\n//     * Does nothing when DIV is not defined\n//     */\n//    void _obj_to_div(array_t& array, size_t category){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//#if defined(DIV)\n//        for(size_t j = 0; j < array[category].size(); ++j){\n//            array[category][j]->fit().initDiv();\n//            size_t div_index = array[category][j]->fit().objs().size() - 1;\n//            array[category][j]->fit().setDiv(category,\n//            \t\tarray[category][j]->fit().obj(div_index));\n//        }\n//#endif\n//    }\n//\n//    //Debug functions\n//#ifdef DBG_ENABLED\n//    array_t _debug_array;\n//\n//    enum array_type{\n//        current_array,\n//        debug_array\n//    };\n//\n//    /**\n//     * Prints the fitness and closest distance values for each position in the\n//     * archive.\n//     *\n//     * Note: requires the _debug_array to be set, otherwise it will throw a\n//     * segmentation fault\n//     */\n//    void _print_archive(){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        std::cout << \"Old archive:\" << std::endl;\n//        _print_array(current_array);\n//        std::cout << \"New archive:\" << std::endl;\n//        _print_array(debug_array);\n//        _init_debug_array();\n//    }\n//\n//    /**\n//     * Print the debug array.\n//     */\n//    void _print_array(array_type type){\n//    \tusing namespace karma;\n//        for(size_t i=0; i<nr_of_bins; ++i){\n//            _cat_to_obj(_array, i);\n//            _div_to_obj(_array, i);\n//            _cat_to_obj(_debug_array, i);\n//            _div_to_obj(_debug_array, i);\n//\n//            pop_t temp_current = _array[i];\n//            pop_t temp_debug = _debug_array[i];\n//\n//            compare::sort(temp_current, compare::pareto_objs().descending());\n//            compare::sort(temp_debug, compare::pareto_objs().descending());\n//\n//            for(size_t j=0; j<bin_size; ++j){\n//                std::cout << \"(\";\n//                for(size_t k=0; k<temp_current[j]->fit().objs().size(); ++k){\n//                \tfloat obj_old = temp_debug[j]->fit().obj(k);\n//                \tfloat obj_new = temp_current[j]->fit().obj(k);\n//                    bool better = obj_old < obj_new;\n//                    bool worse = obj_old > obj_new;\n//                    if(better) std::cout << COL_GREEN;\n//                    if(worse) std::cout << COL_MAGENTA;\n//                    float value = temp_current[j]->fit().obj(k);;\n//                    if(type == debug_array) value = temp_debug[j]->fit().obj(k);\n//                    std::cout << format(\n//                    \t\tleft_align(5, '0')[maxwidth(5)[double_]],\n//                    \t\tvalue);\n//                    std::cout << END_COLOR;\n//                    if(k+1 != _array[i][j]->fit().objs().size()) std::cout << \":\";\n//                }\n//                std::cout << \") \";\n//            }\n//            std::cout << std::endl;\n//        }\n//    }\n//\n//    /**\n//     * Sets the debug array.\n//     *\n//     * Required for debugging at the end of the random pop and load population\n//     * functions.\n//     */\n//    void _init_debug_array(){\n//        dbg::trace trace(\"ea\", DBG_HERE);\n//        for(size_t i=0; i<nr_of_bins; ++i){\n//            _debug_array[i].resize(bin_size);\n//            for(size_t j=0; j<bin_size; ++j){\n//                _debug_array[i][j] = indiv_t(new crowd_t(*_array[i][j]));\n//            }\n//        }\n//    }\n//\n//#endif //DBG_ENABLED\n};\n}\n}\n\n// Undefine everything\n#undef DBOM\n#undef DBOW\n#undef DBOE\n\n#endif /* MODULES_CMOEA_CMOEA_NSGA2_MPI_HPP_ */\n", "meta": {"hexsha": "20837ee02f14e2338a8e72be8cb5d1d01c0714f2", "size": 31328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmoea_nsga2_mpi.hpp", "max_stars_repo_name": "JoostHuizinga/cmoea", "max_stars_repo_head_hexsha": "13bfb90e4f90cf7e184b6e369bd06bde3725cd21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmoea_nsga2_mpi.hpp", "max_issues_repo_name": "JoostHuizinga/cmoea", "max_issues_repo_head_hexsha": "13bfb90e4f90cf7e184b6e369bd06bde3725cd21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmoea_nsga2_mpi.hpp", "max_forks_repo_name": "JoostHuizinga/cmoea", "max_forks_repo_head_hexsha": "13bfb90e4f90cf7e184b6e369bd06bde3725cd21", "max_forks_repo_licenses": ["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.5595913734, "max_line_length": 118, "alphanum_fraction": 0.5689798264, "num_tokens": 8096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.0233307675776318, "lm_q1q2_score": 0.006788806959197963}}
{"text": "/*\nThe MIT License\n\nCopyright (c) 2013 Radhika S. Saksena radhika.saksena@gmail.com,\n                   Kosuke Imai kimai@princeton.edu\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 conditions:\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\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#include \"Analytics.h\"\n#include \"ZeroTradeModelIO.h\"\n#include <numeric>\n#include <algorithm>\n#include <sstream>\n#include <iostream>\n#include <boost/random.hpp>\n#include <time.h>\n\nusing namespace std;\nusing namespace boost;\n\n/* \n * using namespace Rcpp;\n*/\n\nbool sortFunc(pair<int, long double> p1, pair<int, long double> p2);\n\n// [[Rcpp::export]]                                                                                                                                                                         \nint ztm(int nsim, int maxiter, long double eps, int numModelsM, long double nu, long double OP_w_ij_inp, \n         string inputYears, int numThreads, int total_mc_trials, string q_filename, string mu_filename,\n\tstring sigmasq_filename, string pi_filename, string zeta_filename, int seedOffset) {\n\n  // int numCountries, numProductsK, numModelsM;                                                                                                                                           \n  // long double nu;\n  // long double OP_w_ij_inp;\n  //long double nu, bayes_beta, bayes_alpha, bayes_tau;                                                                                                                                   \n  // string tmpString;\n  vector<int> nemptyIdx;\n  // int success=0;\n  // int numThreads=8;\n  // int numModelsM;\n  // int  maxiter;\n  // int nsim, total_mc_trials \n  int mc_trials;\n  // bool successFlag = 0;\n  bool resetFlag = 0;\n  //string inputFilename;                                                                                                                                                                 \n  // string inputYears;\n  ofstream logFile;\n  // ifstream configFile;\n  long double max_ll_new;\n  int max_sim;\n  // long double eps;\n  bool checkpointFlag = 0;\n  vector<pair<int, long double> > simDF;\n  bool* isSuccess;\n  // string q_filename,mu_filename,sigmasq_filename,pi_filename,zeta_filename;\n  // int np \n  int rank=0;\n  long double** all_TFProportions;\n  // double start_time, end_time;\n\n     cout<<\"read in: nsim = \"<<nsim<<endl;\n     cout<<\"read in: maxiter = \"<<maxiter<<endl;\n     cout<<\"read in: eps = \"<<eps<<endl; \n     cout<<\"read in: Z = \"<<numModelsM<<endl;\n     cout<<\"read in: nu = \"<<nu<<endl;\n     cout<<\"read in: OP_w_ij_inp = \"<<OP_w_ij_inp<<endl;\n     cout<<\"read in: q checkpoint file = \"<<q_filename<<endl;\n     cout<<\"read in: mu checkpoint file = \"<<mu_filename<<endl;\n     cout<<\"read in: sigmasq checkpoint file = \"<<sigmasq_filename<<endl;\n     cout<<\"read in: pi checkpoint file = \"<<pi_filename<<endl;\n     cout<<\"read in: zeta checkpoint file = \"<<zeta_filename<<endl;\n     //cout<<\"read in: input file = \"<<inputFilename<<endl;\n     cout<<\"read in: input years = \"<<inputYears<<endl;\n     cout<<\"read in: number of threads = \"<<numThreads<<endl;\n\n     cout<<\"input: random seed = \"<<seedOffset<<endl;\n\n     isSuccess = (bool *)malloc(sizeof(bool)*nsim); \n\n     omp_set_num_threads(numThreads);\n     cout<<\"Before call to ZeroTradeModel constructor.\"<<endl;\n\t //ZeroTradeModelIO trade1(numModelsM,nu,OP_w_ij_inp,inputFilename,numThreads); \n\t ZeroTradeModelIO trade1(numModelsM,nu,OP_w_ij_inp,inputYears,maxiter,numThreads); \n\n     cout<<\"After call to ZeroTradeModel constructor.\"<<endl;\n     logFile.open(\"ZeroTradeModel.log\");\n\n#if EXITONZEROVARIANCE\n     cout<<\"Algorithm exits when it encounters zero variance.\"<<endl;\n     logFile<<\"Algorithm exits when it encounters zero variance.\"<<endl;\n#endif\n#if FLIPDYADPAIRS\n     cout<<\"Dyad pairs may be flipped.\"<<endl;\n     logFile<<\"Dyad pairs may be flipped.\"<<endl;\n#endif\n#if PRIOR_OP\n     cout<<\"Prior is applied.\"<<endl;\n     logFile<<\"Prior is applied.\"<<endl;\n     logFile<<\"Executing: ZeroTradeModel with the following parameters: \";\n#endif\n#ifndef PRIOR_OP\n     logFile<<\"Prior is not applied.\"<<endl;\n     logFile<<\"Executing: ZeroTradeModel with the following parameters: \";\n#endif\n     logFile<<\"read in: maxiter = \"<<maxiter<<endl;\n     logFile<<\"read in: eps = \"<<eps<<endl;\n     logFile<<\"read in: Z = \"<<numModelsM<<endl;\n     logFile<<\"read in: nu = \"<<nu<<endl;\n     //logFile<<\"read in: input file = \"<<inputFilename<<endl;\n     logFile<<\"read in: input years = \"<<inputYears<<endl;\n     logFile<<\"read in: number of threads = \"<<numThreads<<endl;\n\n\n     max_ll_new = -9999999999;\n     max_sim = 0;\n\n     for(int isim = 0; isim  < nsim; isim++){\n\n         //int numThreads;\n\t long double ll_new = 0.0;\n         // long double ll_old = -9999999999999999;\n         // double elapsed_time;\n         time_t seed;\n         // ofstream* clusterFiles = new ofstream[trade1.numModelsM];\n         checkpointFlag = 0;\n\n         cout<<endl<<endl<<\"Running Simulation \"<<isim<<\"....\"<<endl<<endl;;\n         logFile<<endl<<endl<<\"Running Simulation \"<<isim<<\"....\"<<endl<<endl;;\n\n         //seed = time(0);\n         seed = isim;\n         seed = seed + seedOffset;\n         cout<<\"Using seed = \"<<seed<<\" seedOffset = \"<<seedOffset<<endl;\n         //seed = 1377336905;\n         //max for Y90\n\n         //cout<<\"Modified.\"<<endl;\n         //logFile<<\"Modified.\"<<endl;\n\n         logFile<<\"Using seed = \"<<seed<<endl;\n\n         //TODO: uncomment\n        trade1.initializeModel(seed);\n         //0-th iteration was done above\n         //trade1.calcMu();\n\n         for(int iter=1; iter < maxiter; iter++){\n             cout<<\"Running iteration: \"<<iter<<endl;\n             trade1.expectationTh(iter,logFile);\n             cout<<\"iter = \"<<iter<<\": After expectation.\"<<endl;\n             trade1.maximizationTh(0,resetFlag,logFile);\n             cout<<\"iter = \"<<iter<<\": After maximization.\"<<endl;\n             //long double ll_new = trade1.logLikelihoodTh(iter);\n             //double start_time = omp_get_wtime();\n             //long double ll_new = trade1.obsLogPosterior(iter);\n             //double end_time = omp_get_wtime();\n             cout<<\"After ll = \"<<ll_new<<endl;\n         }//end of iter loop\n\n        trade1.chkpClusters(isim,logFile);\n        trade1.chkpModelParams(isim,logFile);\n\n     }//end of isim loop\n\n     omp_set_num_threads(numThreads);\n\n     //mc_trials = (total_mc_trials/np)*np;\n     mc_trials = total_mc_trials;\n     cout<<\"Before call to Analytics constructor.\"<<endl;\n     Analytics mc1(mc_trials,numThreads,numModelsM,trade1.ntimes,trade1.numProdsK,q_filename,\n                     mu_filename,sigmasq_filename,pi_filename,zeta_filename);\n     cout<<\"After call to Analytics constructor.\"<<endl;\n\n     mc1.analytics(rank);\n\n#pragma omp parallel for\n     for(int ith = 0; ith < numThreads; ith++){\n        for(int z = 0; z < numModelsM; z++){\n            int tmpSum = 0;\n            for(int t = 0; t < mc1.ntimes; t++)\n            {\n                tmpSum += mc1.clusterOcc[t][z].size();\n            }\n            if(!tmpSum) continue;\n            mc1.doMC(z,rank);\n        }\n    }\n\n     all_TFProportions = (long double**)malloc(numModelsM*sizeof(long double*));\n     for(int z = 0; z < numModelsM; z++){\n          all_TFProportions[z] = (long double*)malloc(2*trade1.numProdsK*sizeof(long double));\n          for(int k = 0; k < 2*trade1.numProdsK; k++){\n              all_TFProportions[z][k] = 0.0;\n          }\n     }\n\n     for(int z = 0; z < numModelsM; z++){\n         for(int k = 0; k < 2*trade1.numProdsK; k++){\n             for(int ith = 0; ith < numThreads; ith++){\n                all_TFProportions[z][k] += mc1.prodProportion[ith][z][k];\n             }\n         }\n     }\n\n     for(int z = 0; z < numModelsM; z++){\n        for(int k = 0; k < 2*trade1.numProdsK; k++){\n            all_TFProportions[z][k] /= (long double)numThreads;\n        }\n     }\n\n    ostringstream outfileName;\n    outfileName<<\"TF_\"<<rand()<<\".txt\";\n    ofstream fout;\n    fout.open(outfileName.str().c_str());\n\n    //print header with product codes, where available\n    fout<<\"\\\"ClusterID\\\"\"<<\"\\t\";\n    for(int k = 0; k < 2*trade1.numProdsK-1; k++){\n        string currProd = mc1.prodNames[k];\n        fout<<\"\\\"\"<<currProd<<\"\\\"\"<<\"\\t\";\n    }\n    string currProd = mc1.prodNames[2*trade1.numProdsK-1];\n    fout<<\"\\\"\"<<currProd<<\"\\\"\"<<endl;\n\n    for(int z = 0; z < numModelsM; z++){\n        // long double *max_element_ptr = max_element(all_TFProportions[z],all_TFProportions[z]+2*trade1.numProdsK);\n        int tmpSum = 0;\n        for(int t = 0; t < trade1.ntimes; t++)\n        {\n            tmpSum += mc1.clusterOcc[t][z].size();\n            cout<<\"writing TF: t = \"<<t<<\" z = \"<<z<<\" tmpSum = \"<<tmpSum<<endl;\n        }\n        if(!tmpSum) continue;\n        fout<<z<<\"\\t\";\n        for(int k = 0; k < 2*trade1.numProdsK-1; k++){\n            if(isnan(all_TFProportions[z][k])){\n                cout<<\"Found nan in TF proportions = \"<<all_TFProportions[z][k]<<endl;\n                exit(-1);\n            }\n                fout<<all_TFProportions[z][k]<<\"\\t\";\n        }\n        if(isnan(all_TFProportions[z][2*trade1.numProdsK-1])){\n            cout<<\"Found nan in TF proportions = \"<<all_TFProportions[z][2*trade1.numProdsK-1]<<endl;\n            exit(-1);\n        }\n        fout<<all_TFProportions[z][2*trade1.numProdsK-1]<<endl;\n    }\n\n    fout.close();\n\n    logFile.close();\n\n    // HJ: return 1;\n    cout << \"It is all done!\" << endl;\n    return 0;\n }\n\n bool sortFunc(pair<int, long double> p1, pair<int, long double> p2){\n     return(p1.second > p2.second);\n } \n\n// [[Rcpp::export]]\nint mainRcpp(string configTxt, int randomSeed) {\n\n     long double nu;\n     long double OP_w_ij_inp;\n     string tmpString;\n     int numThreads=8;\n     int numModelsM;\n     int maxiter;\n     int nsim, total_mc_trials;\n     string inputYears;\n     ofstream logFile;\n     ifstream configFile;\n     long double eps;\n     string q_filename,mu_filename,sigmasq_filename,pi_filename,zeta_filename;\n\n     configFile.open(&configTxt[0u]);  \n     int seedOffset = randomSeed;\n\n     if(!configFile){\n         cout<<\"Could not open config file.\"<<endl;\n         exit(-1);\n     }\n     \n    cout<<\"configFile is \"<< \"./config.txt\" <<endl; \n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> nsim;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> maxiter;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> eps;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> numModelsM;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> nu;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> OP_w_ij_inp;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> inputYears;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> numThreads;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> total_mc_trials;   //total MC trials \n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> q_filename;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> mu_filename;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> sigmasq_filename;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> pi_filename;\n\n     configFile >> tmpString;\n     configFile >> tmpString;\n     configFile >> zeta_filename;\n\n     configFile.close();\n\n     return ztm(nsim, maxiter, eps, numModelsM, nu, OP_w_ij_inp, inputYears, numThreads, total_mc_trials, \n                q_filename, mu_filename, sigmasq_filename, pi_filename, zeta_filename, seedOffset);\n}\n\n\n\n#include <Rcpp.h>\n// ztm\nint ztm(int nsim, int maxiter, long double eps, int numModelsM, long double nu, long double OP_w_ij_inp, string inputYears, int numThreads, int total_mc_trials, string q_filename, string mu_filename, string sigmasq_filename, string pi_filename, string zeta_filename, int seedOffset);\nRcppExport SEXP dynCluster_ztm(SEXP nsimSEXP, SEXP maxiterSEXP, SEXP epsSEXP, SEXP numModelsMSEXP, SEXP nuSEXP, SEXP OP_w_ij_inpSEXP, SEXP inputYearsSEXP, SEXP numThreadsSEXP, SEXP total_mc_trialsSEXP, SEXP q_filenameSEXP, SEXP mu_filenameSEXP, SEXP sigmasq_filenameSEXP, SEXP pi_filenameSEXP, SEXP zeta_filenameSEXP, SEXP seedOffsetSEXP) {\nBEGIN_RCPP\n    Rcpp::RObject __result;\n    Rcpp::RNGScope __rngScope;\n    Rcpp::traits::input_parameter< int >::type nsim(nsimSEXP);\n    Rcpp::traits::input_parameter< int >::type maxiter(maxiterSEXP);\n    Rcpp::traits::input_parameter< long double >::type eps(epsSEXP);\n    Rcpp::traits::input_parameter< int >::type numModelsM(numModelsMSEXP);\n    Rcpp::traits::input_parameter< long double >::type nu(nuSEXP);\n    Rcpp::traits::input_parameter< long double >::type OP_w_ij_inp(OP_w_ij_inpSEXP);\n    Rcpp::traits::input_parameter< string >::type inputYears(inputYearsSEXP);\n    Rcpp::traits::input_parameter< int >::type numThreads(numThreadsSEXP);\n    Rcpp::traits::input_parameter< int >::type total_mc_trials(total_mc_trialsSEXP);\n    Rcpp::traits::input_parameter< string >::type q_filename(q_filenameSEXP);\n    Rcpp::traits::input_parameter< string >::type mu_filename(mu_filenameSEXP);\n    Rcpp::traits::input_parameter< string >::type sigmasq_filename(sigmasq_filenameSEXP);\n    Rcpp::traits::input_parameter< string >::type pi_filename(pi_filenameSEXP);\n    Rcpp::traits::input_parameter< string >::type zeta_filename(zeta_filenameSEXP);\n    Rcpp::traits::input_parameter< int >::type seedOffset(seedOffsetSEXP);\n    __result = Rcpp::wrap(ztm(nsim, maxiter, eps, numModelsM, nu, OP_w_ij_inp, inputYears, numThreads, total_mc_trials, q_filename, mu_filename, sigmasq_filename, pi_filename, zeta_filename, seedOffset));\n    return __result;\nEND_RCPP\n}\n// mainRcpp\nint mainRcpp(string configTxt, int randomSeed);\nRcppExport SEXP dynCluster_mainRcpp(SEXP configTxtSEXP, SEXP randomSeedSEXP) {\nBEGIN_RCPP\n    Rcpp::RObject __result;\n    Rcpp::RNGScope __rngScope;\n    Rcpp::traits::input_parameter< string >::type configTxt(configTxtSEXP);\n    Rcpp::traits::input_parameter< int >::type randomSeed(randomSeedSEXP);\n    __result = Rcpp::wrap(mainRcpp(configTxt, randomSeed));\n    return __result;\nEND_RCPP\n}\n", "meta": {"hexsha": "ecd8bbda47635ec3035c9f92d2e665f85f8be28a", "size": 15234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mainRcpp.cpp", "max_stars_repo_name": "kosukeimai/dynCluster", "max_stars_repo_head_hexsha": "8a64afcebd8dd457e8a1a88022a1495812e30f5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T12:20:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T07:34:58.000Z", "max_issues_repo_path": "src/mainRcpp.cpp", "max_issues_repo_name": "kosukeimai/dynCluster", "max_issues_repo_head_hexsha": "8a64afcebd8dd457e8a1a88022a1495812e30f5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mainRcpp.cpp", "max_forks_repo_name": "kosukeimai/dynCluster", "max_forks_repo_head_hexsha": "8a64afcebd8dd457e8a1a88022a1495812e30f5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-11T22:06:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T01:23:08.000Z", "avg_line_length": 37.2469437653, "max_line_length": 340, "alphanum_fraction": 0.624130235, "num_tokens": 3876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.01826428212589028, "lm_q1q2_score": 0.00676190127435909}}
{"text": "#ifndef STAN_MODEL_MODEL_BASE_HPP\n#define STAN_MODEL_MODEL_BASE_HPP\n\n#include <stan/io/var_context.hpp>\n#include <stan/math/rev/core.hpp>\n#include <stan/model/prob_grad.hpp>\n#include <boost/random/additive_combine.hpp>\n#include <ostream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace stan {\nnamespace model {\n\n/**\n * The base class for models defining all virtual methods required for\n * services.  Any class extending this class and defining all of its\n * virtual methods can be used with any of the Stan services for\n * sampling, optimization, or variational inference.\n *\n * <p><i>Implementation Details:</i> The reason there are so many\n * overloads of the `log_prob` and `write_array` methods is that\n * template methods cannot be declared virtual.  This class extends\n * `stan::model::prob_grad` in order to define sizing for the number\n * of unconstrained parameters;  thus it is not a pure virtual base\n * class.\n *\n *<p>The approach to defining models used by the Stan language code\n * generator is use the curiously recursive template base class defined\n * in the extension `stan::model::model_base_crtp`.\n */\nclass model_base : public prob_grad {\n public:\n  /**\n   * Construct a model with the specified number of real valued\n   * unconstrained parameters.\n   *\n   * @param[in] num_params_r number of real-valued, unconstrained\n   * parameters\n   */\n  explicit model_base(size_t num_params_r) : prob_grad(num_params_r) {}\n\n  /**\n   * Destructor.  This class has a no-op destructor.\n   */\n  virtual ~model_base() {}\n\n  /**\n   * Return the name of the model.\n   *\n   * @return model name\n   */\n  virtual std::string model_name() const = 0;\n\n  /**\n   * Returns the compile information of the model:\n   * stanc version and stanc flags used to compile the model.\n   *\n   * @return model name\n   */\n  virtual std::vector<std::string> model_compile_info() const = 0;\n\n  /**\n   * Set the specified argument to sequence of parameters, transformed\n   * parameters, and generated quantities in the order in which they\n   * were declared.  The input sequence is cleared and resized.\n   *\n   * @param[in,out] names sequence of names parameters, transformed\n   * parameters, and generated quantities\n   */\n  virtual void get_param_names(std::vector<std::string>& names) const = 0;\n\n  /**\n   * Set the dimensionalities of constrained parameters, transformed\n   * parameters, and generated quantities.  The input sequence is\n   * cleared and resized.  The dimensions of each parameter\n   * dimensionality is represented by a sequence of sizes.  Scalar\n   * real and integer parameters are represented as an empty sequence\n   * of dimensions.\n   *\n   * <p>Indexes are output in the order they are used in indexing. For\n   * example, a 2 x 3 x 4 array will have dimensionality\n   * `std::vector<size_t>{ 2, 3, 4 }`, whereas a 2-dimensional array\n   * of 3-vectors will have dimensionality `std::vector<size_t>{ 2, 3\n   * }`, and a 2-dimensional array of 3 x 4 matrices will have\n   * dimensionality `std::vector<size_t>{2, 3, 4}`.\n   *\n   * @param[in,out] dimss sequence of dimensions specifications to set\n   */\n  virtual void get_dims(std::vector<std::vector<size_t> >& dimss) const = 0;\n\n  /**\n   *  Set the specified sequence to the indexed, scalar, constrained\n   *  parameter names.  Each variable is output with a\n   *  period-separated list of indexes as a suffix, indexing from 1.\n   *\n   * <p>A real parameter `alpha` will produce output `alpha` with no\n   * indexes.\n   *\n   * <p>A 3-dimensional vector (row vector, simplex, etc.)\n   * `theta` will produce output `theta.1`, `theta.2`, `theta.3`.  The\n   * dimensions are the constrained dimensions.\n   *\n   * <p>Matrices are output column major to match their internal\n   * representation in the Stan math library, so that a 2 x 3 matrix\n   * `X` will produce output `X.1.1, X.2.1, X.1.2, X.2.2, X.1.3,\n   * X.2.3`.\n   *\n   * <p>Arrays are handled in natural C++ order, 2 x 3 x 4 array `a`\n   * will produce output `a.1.1.1`, `a.1.1.2`, `a.1.1.3`, `a.1.1.4`,\n   * `a.1.2.1`, `a.1.2.2`, `a.1.2.3`, `a.1.2.4`, `a.1.3.1`, `a.1.3.2`,\n   * `a.1.3.3`, `a.1.3.4`, `a.2.1.1`, `a.2.1.2`, `a.2.1.3`, `a.2.1.4`,\n   * `a.2.2.1`, `a.2.2.2`, `a.2.2.3`, `a.2.2.4`, `a.2.3.1`, `a.2.3.2`,\n   * `a.2.3.3`, `a.2.3.4`.\n   *\n   * <p>Arrays of vectors are handled as expected, so that a\n   * 2-dimensional array of 3-vectors is output as `B.1.1`, `B.2.1`,\n   * `B.1.2`, `B.2.2`, `B.1.3`, `B.2.3`.\n\n   * <p>Arrays of matrices are generated in row-major order for the\n   * array components and column-major order for the matrix component.\n   * Thus a 2-dimensional array of 3 by 4 matrices `B` will be of\n   * dimensionality 2 x 3 x 4 (indexes `B[1:2, 1:3, 1:4]`) and will be output\n   * as `B.1.1.1`, `B.2.1.1`, `B.1.2.1`, `B.2.2.1`, `B.1.3.1`,\n   * `B.2.3.1`, `B.1.1.2`, `B.2.1.2`, `B.1.2.2`, `B.2.2.2`, `B.1.3.2`,\n   * `B.2.3.2`, `B.1.1.3`, `B.2.1.3`, `B.1.2.3`, `B.2.2.3`, `B.1.3.3`,\n   * `B.2.3.3`, `B.1.1.4`, `B.2.1.4`, `B.1.2.4`, `B.2.2.4`, `B.1.3.4`,\n   * `B.2.3.4`\n   */\n  virtual void constrained_param_names(std::vector<std::string>& param_names,\n                                       bool include_tparams = true,\n                                       bool include_gqs = true) const = 0;\n\n  /**\n   * Set the specified sequence of parameter names to the\n   * unconstrained parameter names.  Each unconstrained parameter is\n   * represented as a simple one-dimensional sequence of values.  The\n   * actual transforms are documented in the reference manual.\n   *\n   * <p>The sizes will not be the declared sizes for types such as\n   * simplexes, correlation, and covariance matrices.  A simplex of\n   * size `N` has `N - 1` unconstrained parameters, an `N` by `N`\n   * correlation matrix (or Cholesky factor thereof) has `N` choose 2\n   * unconstrained parameters, and a covariance matrix (or Cholesky\n   * factor thereof) has `N` choose 2 plus `N` unconstrained\n   * parameters.\n   *\n   * <p>Full details of the transforms and their underlying\n   * representations as sequences are detailed in the Stan reference\n   * manual.  This also provides details of the order of each\n   * parameter type.\n   *\n   * @param[in,out] param_names sequence of names to set\n   * @param[in] include_tparams true if transformed parameters should\n   * be included\n   * @param[in] include_gqs true if generated quantities should be\n   * included\n   */\n  virtual void unconstrained_param_names(std::vector<std::string>& param_names,\n                                         bool include_tparams = true,\n                                         bool include_gqs = true) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian and with normalizing constants for\n   * probability functions.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob(Eigen::VectorXd& params_r,\n                          std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian and with normalizing constants for\n   * probability functions.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob(Eigen::Matrix<math::var, -1, 1>& params_r,\n                             std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and with\n   * normalizing constants for probability functions.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob_jacobian(Eigen::VectorXd& params_r,\n                                   std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and with\n   * normalizing constants for probability functions.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob_jacobian(Eigen::Matrix<math::var, -1, 1>& params_r,\n                                      std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian correction for constraints and\n   * dropping normalizing constants.\n   *\n   * <p>This method is for completeness as `double`-based inputs are\n   * always constant and will thus cause all probability functions to\n   * be dropped from the result.  To get the value of this\n   * calculation, use the overload for `math::var`.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob_propto(Eigen::VectorXd& params_r,\n                                 std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian correction for constraints and\n   * dropping normalizing constants.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob_propto(Eigen::Matrix<math::var, -1, 1>& params_r,\n                                    std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and dropping\n   * normalizing constants.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * <p>This method is for completeness as `double`-based inputs are\n   * always constant and will thus cause all probability functions to\n   * be dropped from the result.  To get the value of this\n   * calculation, use the overload for `math::var`.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob_propto_jacobian(Eigen::VectorXd& params_r,\n                                          std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and dropping\n   * normalizing constants.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob_propto_jacobian(\n      Eigen::Matrix<math::var, -1, 1>& params_r, std::ostream* msgs) const = 0;\n\n  /**\n   * Convenience template function returning the log density for the\n   * specified unconstrained parameters, with Jacobian and normalizing\n   * constant inclusion controlled by the template parameters.\n   *\n   * <p>This non-virtual template method delegates to the appropriate\n   * overloaded virtual function.  This allows external interfaces to\n   * call the convenient template methods rather than the individual\n   * virtual functions.\n   *\n   * @tparam propto `true` if normalizing constants should be dropped\n   * and result returned up to an additive constant\n   * @tparam jacobian `true` if the log Jacobian adjustment is\n   * included for the change of variables from unconstrained to\n   * constrained parameters\n   * @tparam T type of scalars in the vector of parameters\n   * @param[in] params_r unconstrained parameters\n   * @param[in,out] msgs stream to which messages are written\n   * @return log density with normalizing constants and Jacobian\n   * included as specified by the template parameters\n   */\n  template <bool propto, bool jacobian, typename T>\n  inline T log_prob(Eigen::Matrix<T, -1, 1>& params_r,\n                    std::ostream* msgs) const {\n    if (propto && jacobian)\n      return log_prob_propto_jacobian(params_r, msgs);\n    else if (propto && !jacobian)\n      return log_prob_propto(params_r, msgs);\n    else if (!propto && jacobian)\n      return log_prob_jacobian(params_r, msgs);\n    else  // if (!propto && !jacobian)\n      return log_prob(params_r, msgs);\n  }\n\n  /**\n   * Read constrained parameter values from the specified context,\n   * unconstrain them, then concatenate the unconstrained sequences\n   * into the specified parameter sequence.  Output messages go to the\n   * specified stream.\n   *\n   * @param[in] context definitions of variable values\n   * @param[in,out] params_r unconstrained parameter values produced\n   * @param[in,out] msgs stream to which messages are written\n   */\n  virtual void transform_inits(const io::var_context& context,\n                               Eigen::VectorXd& params_r,\n                               std::ostream* msgs) const = 0;\n\n  /**\n   * Convert the specified sequence of unconstrained parameters to a\n   * sequence of constrained parameters, optionally including\n   * transformed parameters and including generated quantities.  The\n   * generated quantities may use the random number generator.  Any\n   * messages are written to the specified stream.  The output\n   * parameter sequence will be resized if necessary to match the\n   * number of constrained scalar parameters.\n   *\n   * @param base_rng RNG to use for generated quantities\n   * @param[in] params_r unconstrained parameters input\n   * @param[in,out] params_constrained_r constrained parameters produced\n   * @param[in] include_tparams true if transformed parameters are\n   * included in output\n   * @param[in] include_gqs true if generated quantities are included\n   * in output\n   * @param[in,out] msgs msgs stream to which messages are written\n   */\n  virtual void write_array(boost::ecuyer1988& base_rng,\n                           Eigen::VectorXd& params_r,\n                           Eigen::VectorXd& params_constrained_r,\n                           bool include_tparams = true, bool include_gqs = true,\n                           std::ostream* msgs = 0) const = 0;\n\n  // TODO(carpenter): cut redundant std::vector versions from here ===\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian and with normalizing constants for\n   * probability functions.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob(std::vector<double>& params_r,\n                          std::vector<int>& params_i,\n                          std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian and with normalizing constants for\n   * probability functions.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob(std::vector<math::var>& params_r,\n                             std::vector<int>& params_i,\n                             std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and with\n   * normalizing constants for probability functions.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob_jacobian(std::vector<double>& params_r,\n                                   std::vector<int>& params_i,\n                                   std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and with\n   * normalizing constants for probability functions.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob_jacobian(std::vector<math::var>& params_r,\n                                      std::vector<int>& params_i,\n                                      std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian correction for constraints and\n   * dropping normalizing constants.\n   *\n   * <p>This method is for completeness as `double`-based inputs are\n   * always constant and will thus cause all probability functions to\n   * be dropped from the result.  To get the value of this\n   * calculation, use the overload for `math::var`.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob_propto(std::vector<double>& params_r,\n                                 std::vector<int>& params_i,\n                                 std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, without Jacobian correction for constraints and\n   * dropping normalizing constants.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob_propto(std::vector<math::var>& params_r,\n                                    std::vector<int>& params_i,\n                                    std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and dropping\n   * normalizing constants.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * <p>This method is for completeness as `double`-based inputs are\n   * always constant and will thus cause all probability functions to\n   * be dropped from the result.  To get the value of this\n   * calculation, use the overload for `math::var`.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual double log_prob_propto_jacobian(std::vector<double>& params_r,\n                                          std::vector<int>& params_i,\n                                          std::ostream* msgs) const = 0;\n\n  /**\n   * Return the log density for the specified unconstrained\n   * parameters, with Jacobian correction for constraints and dropping\n   * normalizing constants.\n   *\n   * <p>The Jacobian is of the inverse transform from unconstrained\n   * parameters to constrained parameters; full details for Stan\n   * language types can be found in the language reference manual.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs message stream\n   * @return log density for specified parameters\n   */\n  virtual math::var log_prob_propto_jacobian(std::vector<math::var>& params_r,\n                                             std::vector<int>& params_i,\n                                             std::ostream* msgs) const = 0;\n\n  /**\n   * Convenience template function returning the log density for the\n   * specified unconstrained parameters, with Jacobian and normalizing\n   * constant inclusion controlled by the template parameters.\n   *\n   * <p>This non-virtual template method delegates to the appropriate\n   * overloaded virtual function.  This allows external interfaces to\n   * call the convenient template methods rather than the individual\n   * virtual functions.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @tparam propto `true` if normalizing constants should be dropped\n   * and result returned up to an additive constant\n   * @tparam jacobian `true` if the log Jacobian adjustment is\n   * included for the change of variables from unconstrained to\n   * constrained parameters.\n   * @tparam T type of scalars in the vector of parameters\n   * @param[in] params_r unconstrained parameters\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] msgs stream to which messages are written\n   * @return log density with normalizing constants and Jacobian\n   * included as specified by the template parameters\n   */\n  template <bool propto, bool jacobian, typename T>\n  inline T log_prob(std::vector<T>& params_r, std::vector<int>& params_i,\n                    std::ostream* msgs) const {\n    if (propto && jacobian)\n      return log_prob_propto_jacobian(params_r, params_i, msgs);\n    else if (propto && !jacobian)\n      return log_prob_propto(params_r, params_i, msgs);\n    else if (!propto && jacobian)\n      return log_prob_jacobian(params_r, params_i, msgs);\n    else  // if (!propto && !jacobian)\n      return log_prob(params_r, params_i, msgs);\n  }\n\n  /**\n   * Read constrained parameter values from the specified context,\n   * unconstrain them, then concatenate the unconstrained sequences\n   * into the specified parameter sequence.  Output messages go to the\n   * specified stream.\n   *\n   * \\deprecated Use Eigen vector versions\n   *\n   * @param[in] context definitions of variable values\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] params_r unconstrained parameter values produced\n   * @param[in,out] msgs stream to which messages are written\n   */\n  virtual void transform_inits(const io::var_context& context,\n                               std::vector<int>& params_i,\n                               std::vector<double>& params_r,\n                               std::ostream* msgs) const = 0;\n\n  /**\n   * Convert the specified sequence of unconstrained parameters to a\n   * sequence of constrained parameters, optionally including\n   * transformed parameters and including generated quantities.  The\n   * generated quantities may use the random number generator.  Any\n   * messages are written to the specified stream.  The output\n   * parameter sequence will be resized if necessary to match the\n   * number of constrained scalar parameters.\n   *\n   * @param base_rng RNG to use for generated quantities\n   * @param[in] params_r unconstrained parameters input\n   * @param[in] params_i integer parameters (ignored)\n   * @param[in,out] params_r_constrained constrained parameters produced\n   * @param[in] include_tparams true if transformed parameters are\n   * included in output\n   * @param[in] include_gqs true if generated quantities are included\n   * in output\n   * @param[in,out] msgs msgs stream to which messages are written\n   */\n  virtual void write_array(boost::ecuyer1988& base_rng,\n                           std::vector<double>& params_r,\n                           std::vector<int>& params_i,\n                           std::vector<double>& params_r_constrained,\n                           bool include_tparams = true, bool include_gqs = true,\n                           std::ostream* msgs = 0) const = 0;\n\n  /**\n   * Return as json string the unconstrained size types\n   */\n  virtual std::string get_unconstrained_sizedtypes() const = 0;\n};\n\n}  // namespace model\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "fef716d2f910fdb1520a467fc92c0760469ce1d9", "size": 25261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/model/model_base.hpp", "max_stars_repo_name": "clamped-params/stan", "max_stars_repo_head_hexsha": "8ea4ac747d6f6d4d229eb64d3a1b62253e0a8855", "max_stars_repo_licenses": ["CC-BY-3.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": "src/stan/model/model_base.hpp", "max_issues_repo_name": "clamped-params/stan", "max_issues_repo_head_hexsha": "8ea4ac747d6f6d4d229eb64d3a1b62253e0a8855", "max_issues_repo_licenses": ["CC-BY-3.0", "BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-03-17T20:26:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T06:22:25.000Z", "max_forks_repo_path": "src/stan/model/model_base.hpp", "max_forks_repo_name": "clamped-params/stan", "max_forks_repo_head_hexsha": "8ea4ac747d6f6d4d229eb64d3a1b62253e0a8855", "max_forks_repo_licenses": ["CC-BY-3.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": 41.8228476821, "max_line_length": 80, "alphanum_fraction": 0.6723803492, "num_tokens": 6107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781087383497524, "lm_q2_score": 0.037892427308664316, "lm_q1q2_score": 0.006737685611481881}}
{"text": "#include <utility>\n\n#include <utility>\n\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <H5Cpp.h>\n#include \"../include/def.h\"\n#include \"../include/utils.h\"\n#include \"../include/state_type.h\"\n#include \"../include/observer_type.h\"\n#include \"../include/solver_type.h\"\n#include \"../include/herring_func.hpp\"\n\n\nclass HerringSolverType: public RBCSystem::SolverType {\npublic:\n    explicit HerringSolverType(const Real &Prandtl_number = 1.0, const Real &Rayleigh_number = 1000.0,\n                               const Real &wave_number = 1.0, const Real &start_time = 0.0, const Real &end_time = 1.0,\n                               const String &in_h5file_name = static_cast<String>(\"in_data.h5\"),\n                               const String &in_h5dset_name = static_cast<String>(\"/group/state\"),\n                               const String &out_h5file_name = static_cast<String>(\"out_data.h5\"),\n                               const String &out_h5group_name = static_cast<String>(\"/group/state\"));\n\n    HerringSolverType(const HerringSolverType &rhs);\n\n    HerringSolverType &operator=(const HerringSolverType &rhs);\n\n    ~HerringSolverType(void);\n\n    const String &in_h5file_name(void) const;\n\n    void in_h5file_name(const String &in_h5file_name);\n\n    const String &in_h5dset_name(void) const;\n\n    void in_h5dset_name(const String &in_h5dset_name);\n\n    const String &out_h5file_name(void) const;\n\n    void out_h5file_name(const String &out_h5file_name);\n\n    const String &out_h5group_name(void) const;\n\n    void out_h5group_name(const String &out_h5group_name);\n\n    void operator()(const RBCSystem::StateType &f, RBCSystem::StateType &dfdt, const Real &t) const override;\n\n    void parseArgv(int argc, char *argv[]);\n\nprivate:\n    String inf_name, ind_name, outf_name, outg_name;\n};\n\n\nint main(int argc, char* argv[])\n{\n    HerringSolverType solver;\n    H5::H5File inf, outf;\n\n    solver.parseArgv(argc, argv);\n    //inf = H5::H5File(mysolver.in_h5file_name, H5F_ACC_RDONLY);\n    //initial_state.loadFile(inf, mysolver.in_h5obj_name);\n    //inf.close();\n    //solver.initial_state(initial_state);\n    solver.evaluate();\n    outf = H5::H5File(solver.out_h5file_name(), H5F_ACC_TRUNC);\n    solver.saveFile(outf, solver.out_h5group_name());\n    outf.close();\n\n    return 0;\n}\n\nHerringSolverType::HerringSolverType(const Real &Prandtl_number, const Real &Rayleigh_number, const Real &wave_number,\n        const Real &start_time, const Real &end_time,\n        const String &in_h5file_name, const String &in_h5dset_name,\n        const String &out_h5file_name, const String &out_h5group_name):\n        RBCSystem::SolverType(Prandtl_number, Rayleigh_number, wave_number, RBCSystem::StateType::TrivialState(), start_time, end_time),\n        inf_name(in_h5file_name), ind_name(in_h5dset_name),\n        outf_name(out_h5file_name), outg_name(out_h5group_name) { return; }\n\nHerringSolverType::HerringSolverType(const HerringSolverType &rhs):\n        RBCSystem::SolverType(rhs),\n        inf_name(rhs.inf_name), ind_name(rhs.ind_name),\n        outf_name(rhs.inf_name), outg_name(rhs.outg_name) { return; }\n\nHerringSolverType &HerringSolverType::operator=(const HerringSolverType &rhs)\n{\n    RBCSystem::SolverType::operator=(rhs);\n    inf_name = rhs.inf_name;\n    ind_name = rhs.ind_name;\n    outf_name = rhs.outf_name;\n    outg_name = rhs.outg_name;\n\n    return *this;\n}\n\nHerringSolverType::~HerringSolverType(void) { return; }\n\ninline const String &HerringSolverType::in_h5file_name(void) const { return inf_name; }\n\ninline void HerringSolverType::in_h5file_name(const String &in_h5file_name) { inf_name = in_h5file_name; return; }\n\ninline const String &HerringSolverType::in_h5dset_name(void) const { return ind_name; }\n\ninline void HerringSolverType::in_h5dset_name(const String &in_h5dset_name) { ind_name = in_h5dset_name; return; }\n\ninline const String &HerringSolverType::out_h5file_name(void) const { return outf_name; }\n\ninline void HerringSolverType::out_h5file_name(const String &out_h5file_name) { outf_name = out_h5file_name; return; }\n\ninline const String &HerringSolverType::out_h5group_name(void) const { return outg_name; }\n\ninline void HerringSolverType::out_h5group_name(const String &out_h5group_name) { outg_name = out_h5group_name; return; }\n\nvoid HerringSolverType::operator()(const RBCSystem::StateType &f, RBCSystem::StateType &dfdt, const Real &t) const\n{\n    func(f, dfdt, t, Prandtl_number(), Rayleigh_number(), wave_number());\n\n    return;\n}\n\nvoid HerringSolverType::parseArgv(int argc, char *argv[])\n{\n    using namespace boost::program_options;\n\n    options_description desc(\"**This program is used to simulate HerringSolver's model.**\\nUsages:\");\n    desc.add_options()\n            (\"help,h\", \"display usages;\")\n            (\"Prandtl_number\", value<Real>()->default_value(1.0), \"Prandl_number;\")\n            (\"Rayleigh_number\", value<Real>()->default_value(1000.0), \"Rayleigh_number;\")\n            (\"wave_number\", value<Real>()->default_value(0.5), \"wave_number;\")\n            (\"start_time\", value<Real>()->default_value(0.0), \"start_time\")\n            (\"end_time\", value<Real>()->default_value(1.0), \"end_time\")\n            (\"input_h5file\", value<String>()->default_value(static_cast<String>(\"in_data.h5\")), \"input h5file's name;\")\n            (\"input_h5obj\", value<String>()->default_value(static_cast<String>(\"/group/state\")), \"input h5obj's name;\")\n            (\"output_h5file\", value<String>()->default_value(static_cast<String>(\"out_data.h5\")), \"output h5file's name;\")\n            (\"output_h5obj\", value<String>()->default_value(static_cast<String>(\"/group\")), \"output h5obj's name.\");\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n    if(vm.count(\"help\") ){\n        std::cout << desc << std::endl;\n        std::exit(1);\n    }\n    Prandtl_number(vm[\"Prandtl_number\"].as<Real>());\n    Rayleigh_number(vm[\"Rayleigh_number\"].as<Real>());\n    wave_number(vm[\"wave_number\"].as<Real>());\n    start_time(vm[\"start_time\"].as<Real>());\n    end_time(vm[\"end_time\"].as<Real>());\n    in_h5file_name(vm[\"input_h5file\"].as<String>());\n    in_h5dset_name(vm[\"input_h5obj\"].as<String>());\n    out_h5file_name(vm[\"output_h5file\"].as<String>());\n    out_h5group_name(vm[\"output_h5obj\"].as<String>());\n\n    return;\n}\n", "meta": {"hexsha": "6f4463f9d3187689fb6b667dddefcb9d6ec76852", "size": 6285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/programs/herring_model.cpp", "max_stars_repo_name": "lhc12/Rayleigh-Benard-Convection", "max_stars_repo_head_hexsha": "97f922ec50597c2cff10d50ca44b2414daf4a4cc", "max_stars_repo_licenses": ["MIT"], "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/programs/herring_model.cpp", "max_issues_repo_name": "lhc12/Rayleigh-Benard-Convection", "max_issues_repo_head_hexsha": "97f922ec50597c2cff10d50ca44b2414daf4a4cc", "max_issues_repo_licenses": ["MIT"], "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/programs/herring_model.cpp", "max_forks_repo_name": "lhc12/Rayleigh-Benard-Convection", "max_forks_repo_head_hexsha": "97f922ec50597c2cff10d50ca44b2414daf4a4cc", "max_forks_repo_licenses": ["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.7784810127, "max_line_length": 136, "alphanum_fraction": 0.6940334129, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2365162364457076, "lm_q2_score": 0.028436036132458178, "lm_q1q2_score": 0.006725584245483163}}
{"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/*\n  Author: Melonee Wise\n  Contributors: Dave Coleman, Jonathan Bohren, Bob Holmberg, Wim Meeussen\n  Desc: Implements a standard proportional-integral-derivative controller\n*/\n\n#include <control_toolbox/pid.h>\n#include <tinyxml.h>\n\n#include <boost/algorithm/clamp.hpp>\n#include <boost/algorithm/minmax.hpp>\n\nnamespace control_toolbox {\n\nstatic const std::string DEFAULT_NAMESPACE = \"pid\"; // \\todo better default prefix?\n\nPid::Pid(double p, double i, double d, double i_max, double i_min, bool antiwindup)\n  : dynamic_reconfig_initialized_(false)\n{\n  setGains(p,i,d,i_max,i_min,antiwindup);\n\n  reset();\n}\n\nPid::Pid(const Pid &source)\n   : dynamic_reconfig_initialized_(false)\n{\n  // Copy the realtime buffer to then new PID class\n  gains_buffer_ = source.gains_buffer_;\n\n  // Reset the state of this PID controller\n  reset();\n}\n\nPid::~Pid()\n{\n}\n\nvoid Pid::initPid(double p, double i, double d, double i_max, double i_min,\n  const ros::NodeHandle& /*node*/)\n{\n  initPid(p, i, d, i_max, i_min);\n\n  // Create node handle for dynamic reconfigure\n  ros::NodeHandle nh(DEFAULT_NAMESPACE);\n  initDynamicReconfig(nh);\n}\n\nvoid Pid::initPid(double p, double i, double d, double i_max, double i_min, bool antiwindup,\n  const ros::NodeHandle& /*node*/)\n{\n  initPid(p, i, d, i_max, i_min, antiwindup);\n\n  // Create node handle for dynamic reconfigure\n  ros::NodeHandle nh(DEFAULT_NAMESPACE);\n  initDynamicReconfig(nh);\n}\n\nvoid Pid::initPid(double p, double i, double d, double i_max, double i_min, bool antiwindup)\n{\n  setGains(p,i,d,i_max,i_min, antiwindup);\n\n  reset();\n}\n\nbool Pid::initParam(const std::string& prefix, const bool quiet)\n{\n  ros::NodeHandle nh(prefix);\n  return init(nh, quiet);\n}\n\nbool Pid::init(const ros::NodeHandle &node, const bool quiet)\n{\n  ros::NodeHandle nh(node);\n\n  Gains gains;\n\n  // Load PID gains from parameter server\n  if (!nh.getParam(\"p\", gains.p_gain_))\n  {\n    if (!quiet) {\n      ROS_ERROR(\"No p gain specified for pid.  Namespace: %s\", nh.getNamespace().c_str());\n    }\n    return false;\n  }\n  // Only the P gain is required, the I and D gains are optional and default to 0:\n  nh.param(\"i\", gains.i_gain_, 0.0);\n  nh.param(\"d\", gains.d_gain_, 0.0);\n\n  // Load integral clamp from param server or default to 0\n  double i_clamp;\n  nh.param(\"i_clamp\", i_clamp, 0.0);\n  gains.i_max_ = std::abs(i_clamp);\n  gains.i_min_ = -std::abs(i_clamp);\n  if(nh.hasParam(\"i_clamp_min\"))\n  {\n    nh.param(\"i_clamp_min\", gains.i_min_, gains.i_min_); // use i_clamp_min parameter, otherwise keep -i_clamp\n    gains.i_min_ = -std::abs(gains.i_min_); // make sure the value is <= 0\n  }\n  if(nh.hasParam(\"i_clamp_max\"))\n  {\n    nh.param(\"i_clamp_max\", gains.i_max_, gains.i_max_); // use i_clamp_max parameter, otherwise keep i_clamp\n    gains.i_max_ = std::abs(gains.i_max_); // make sure the value is >= 0\n  }\n  nh.param(\"antiwindup\", gains.antiwindup_, false);\n\n  nh.param(\"publish_state\", publish_state_, false);\n\n  if(publish_state_)\n  {\n    state_publisher_.reset(new realtime_tools::RealtimePublisher<control_msgs::PidState>());\n    state_publisher_->init(nh, \"state\", 1);\n  }\n\n  setGains(gains);\n\n  reset();\n  initDynamicReconfig(nh);\n\n  return true;\n}\n\nbool Pid::initXml(TiXmlElement *config)\n{\n  // Create node handle for dynamic reconfigure\n  ros::NodeHandle nh(DEFAULT_NAMESPACE);\n\n  double i_clamp;\n  i_clamp = config->Attribute(\"iClamp\") ? atof(config->Attribute(\"iClamp\")) : 0.0;\n\n  setGains(\n    config->Attribute(\"p\") ? atof(config->Attribute(\"p\")) : 0.0,\n    config->Attribute(\"i\") ? atof(config->Attribute(\"i\")) : 0.0,\n    config->Attribute(\"d\") ? atof(config->Attribute(\"d\")) : 0.0,\n    std::abs(i_clamp),\n    -std::abs(i_clamp),\n    config->Attribute(\"antiwindup\") ? atof(config->Attribute(\"antiwindup\")) : false\n  );\n\n  reset();\n  initDynamicReconfig(nh);\n\n  return true;\n}\n\nvoid Pid::initDynamicReconfig(ros::NodeHandle &node)\n{\n  ROS_DEBUG_STREAM_NAMED(\"pid\",\"Initializing dynamic reconfigure in namespace \"\n    << node.getNamespace());\n\n  // Start dynamic reconfigure server\n  param_reconfig_server_.reset(new DynamicReconfigServer(param_reconfig_mutex_, node));\n  dynamic_reconfig_initialized_ = true;\n\n  // Set Dynamic Reconfigure's gains to Pid's values\n  updateDynamicReconfig();\n\n  // Set callback\n  param_reconfig_callback_ = boost::bind(&Pid::dynamicReconfigCallback, this, _1, _2);\n  param_reconfig_server_->setCallback(param_reconfig_callback_);\n}\n\nvoid Pid::reset()\n{\n  p_error_last_ = 0.0;\n  p_error_ = 0.0;\n  i_error_ = 0.0;\n  d_error_ = 0.0;\n  cmd_ = 0.0;\n}\n\nvoid Pid::getGains(double &p, double &i, double &d, double &i_max, double &i_min)\n{\n  bool antiwindup;\n  getGains(p, i, d, i_max, i_min, antiwindup);\n}\n\nvoid Pid::getGains(double &p, double &i, double &d, double &i_max, double &i_min, bool &antiwindup)\n{\n  Gains gains = *gains_buffer_.readFromRT();\n\n  p     = gains.p_gain_;\n  i     = gains.i_gain_;\n  d     = gains.d_gain_;\n  i_max = gains.i_max_;\n  i_min = gains.i_min_;\n  antiwindup = gains.antiwindup_;\n}\n\nPid::Gains Pid::getGains()\n{\n  return *gains_buffer_.readFromRT();\n}\n\nvoid Pid::setGains(double p, double i, double d, double i_max, double i_min, bool antiwindup)\n{\n  Gains gains(p,i,d,i_max,i_min, antiwindup);\n\n  setGains(gains);\n}\n\nvoid Pid::setGains(const Gains &gains)\n{\n  gains_buffer_.writeFromNonRT(gains);\n\n  // Update dynamic reconfigure with the new gains\n  updateDynamicReconfig(gains);\n}\n\nvoid Pid::updateDynamicReconfig()\n{\n  // Make sure dynamic reconfigure is initialized\n  if(!dynamic_reconfig_initialized_)\n    return;\n\n  // Get starting values\n  control_toolbox::ParametersConfig config;\n\n  // Get starting values\n  getGains(config.p, config.i, config.d, config.i_clamp_max, config.i_clamp_min, config.antiwindup);\n\n  updateDynamicReconfig(config);\n}\n\nvoid Pid::updateDynamicReconfig(Gains gains_config)\n{\n  // Make sure dynamic reconfigure is initialized\n  if(!dynamic_reconfig_initialized_)\n    return;\n\n  control_toolbox::ParametersConfig config;\n\n  // Convert to dynamic reconfigure format\n  config.p = gains_config.p_gain_;\n  config.i = gains_config.i_gain_;\n  config.d = gains_config.d_gain_;\n  config.i_clamp_max = gains_config.i_max_;\n  config.i_clamp_min = gains_config.i_min_;\n  config.antiwindup = gains_config.antiwindup_;\n\n  updateDynamicReconfig(config);\n}\n\nvoid Pid::updateDynamicReconfig(control_toolbox::ParametersConfig config)\n{\n  // Make sure dynamic reconfigure is initialized\n  if(!dynamic_reconfig_initialized_)\n    return;\n\n  // Set starting values, using a shared mutex with dynamic reconfig\n  param_reconfig_mutex_.lock();\n  param_reconfig_server_->updateConfig(config);\n  param_reconfig_mutex_.unlock();\n}\n\nvoid Pid::dynamicReconfigCallback(control_toolbox::ParametersConfig &config, uint32_t /*level*/)\n{\n  ROS_DEBUG_STREAM_NAMED(\"pid\",\"Dynamics reconfigure callback recieved.\");\n\n  // Set the gains\n  setGains(config.p, config.i, config.d, config.i_clamp_max, config.i_clamp_min, config.antiwindup);\n}\n\ndouble Pid::computeCommand(double error, ros::Duration dt)\n{\n\n  if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n    return 0.0;\n\n  double error_dot = d_error_;\n\n  // Calculate the derivative error\n  if (dt.toSec() > 0.0)\n  {\n    error_dot = (error - p_error_last_) / dt.toSec();\n    p_error_last_ = error;\n  }\n\n  return computeCommand(error, error_dot, dt);\n}\n\ndouble Pid::updatePid(double error, ros::Duration dt)\n{\n  return -computeCommand(error, dt);\n}\n\ndouble Pid::computeCommand(double error, double error_dot, ros::Duration dt)\n{\n  // Get the gain parameters from the realtime buffer\n  Gains gains = *gains_buffer_.readFromRT();\n\n  double p_term, d_term, i_term;\n  p_error_ = error; // this is error = target - state\n  d_error_ = error_dot;\n\n  if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n    return 0.0;\n\n  // Calculate proportional contribution to command\n  p_term = gains.p_gain_ * p_error_;\n\n  // Calculate the integral of the position error\n  i_error_ += dt.toSec() * p_error_;\n\n  if(gains.antiwindup_ && gains.i_gain_!=0)\n  {\n    // Prevent i_error_ from climbing higher than permitted by i_max_/i_min_\n    boost::tuple<double, double> bounds = boost::minmax<double>(gains.i_min_ / gains.i_gain_, gains.i_max_ / gains.i_gain_);\n    i_error_ = boost::algorithm::clamp(i_error_, bounds.get<0>(), bounds.get<1>());\n  }\n\n  // Calculate integral contribution to command\n  i_term = gains.i_gain_ * i_error_;\n\n  if(!gains.antiwindup_)\n  {\n    // Limit i_term so that the limit is meaningful in the output\n    i_term = boost::algorithm::clamp(i_term, gains.i_min_, gains.i_max_);\n  }\n\n  // Calculate derivative contribution to command\n  d_term = gains.d_gain_ * d_error_;\n\n  // Compute the command\n  cmd_ = p_term + i_term + d_term;\n\n  // Publish controller state if configured\n  if (publish_state_ && state_publisher_)\n  {\n    if (state_publisher_->trylock())\n    {\n      state_publisher_->msg_.header.stamp = ros::Time::now();\n      state_publisher_->msg_.timestep = dt;\n      state_publisher_->msg_.error = error;\n      state_publisher_->msg_.error_dot = error_dot;\n      state_publisher_->msg_.p_error = p_error_;\n      state_publisher_->msg_.i_error = i_error_;\n      state_publisher_->msg_.d_error = d_error_;\n      state_publisher_->msg_.p_term = p_term;\n      state_publisher_->msg_.i_term = i_term;\n      state_publisher_->msg_.d_term = d_term;\n      state_publisher_->msg_.i_max = gains.i_max_;\n      state_publisher_->msg_.i_min = gains.i_min_;\n      state_publisher_->msg_.output = cmd_;\n      state_publisher_->unlockAndPublish();\n    }\n  }\n\n  return cmd_;\n}\n\ndouble Pid::updatePid(double error, double error_dot, ros::Duration dt)\n{\n  return -computeCommand(error, error_dot, dt);\n}\n\nvoid Pid::setCurrentCmd(double cmd)\n{\n  cmd_ = cmd;\n}\n\ndouble Pid::getCurrentCmd()\n{\n  return cmd_;\n}\n\nvoid Pid::getCurrentPIDErrors(double *pe, double *ie, double *de)\n{\n  // Get the gain parameters from the realtime buffer\n  Gains gains = *gains_buffer_.readFromRT();\n\n  *pe = p_error_;\n  *ie = i_error_;\n  *de = d_error_;\n}\n\nvoid Pid::printValues()\n{\n  Gains gains = getGains();\n\n  ROS_INFO_STREAM_NAMED(\"pid\",\"Current Values of PID Class:\\n\"\n    << \"  P Gain: \" << gains.p_gain_ << \"\\n\"\n    << \"  I Gain: \" << gains.i_gain_ << \"\\n\"\n    << \"  D Gain: \" << gains.d_gain_ << \"\\n\"\n    << \"  I_Max:  \" << gains.i_max_  << \"\\n\"\n    << \"  I_Min:  \" << gains.i_min_  << \"\\n\"\n    << \"  Antiwindup:  \" << gains.antiwindup_  << \"\\n\"\n    << \"  P_Error_Last: \" << p_error_last_  << \"\\n\"\n    << \"  P_Error:      \" << p_error_  << \"\\n\"\n    << \"  I_Error:       \" << i_error_  << \"\\n\"\n    << \"  D_Error:      \" << d_error_  << \"\\n\"\n    << \"  Command:      \" << cmd_\n  );\n\n}\n\n} // namespace\n", "meta": {"hexsha": "175f9ba113b192356450a1e61893c85d42a6a1fd", "size": 12499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "melodic/src/control_toolbox/src/pid.cpp", "max_stars_repo_name": "disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA", "max_stars_repo_head_hexsha": "3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T12:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T07:14:13.000Z", "max_issues_repo_path": "src/control_toolbox/src/pid.cpp", "max_issues_repo_name": "xsgauthier/ros-robot-control", "max_issues_repo_head_hexsha": "1ce67586f29185fd046e2febea9db479fb8a8d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control_toolbox/src/pid.cpp", "max_forks_repo_name": "xsgauthier/ros-robot-control", "max_forks_repo_head_hexsha": "1ce67586f29185fd046e2febea9db479fb8a8d8b", "max_forks_repo_licenses": ["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.9328703704, "max_line_length": 124, "alphanum_fraction": 0.6913353068, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.026759285222833183, "lm_q1q2_score": 0.006714246830318963}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <boost/assert.hpp>\n\n#include <fstream>\n#include <iostream>\n\n\ntemplate <typename T>\nEigen::Block<const T>\nftcut(const Eigen::DenseBase<T> &m, int rows, int cols)\n{\n  int this_rows = m.rows();\n  int this_cols = m.cols();\n\n  int row_offset = this_rows / 2 - rows / 2;\n  int col_offset = this_cols / 2 - cols / 2;\n  assert(row_offset >= 0);\n  assert(col_offset >= 0);\n  return m.block(row_offset, col_offset, rows, cols);\n}\n\ntemplate <typename T>\nEigen::Block<T>\nftcut(Eigen::DenseBase<T> &m, int rows, int cols)\n{\n  int this_rows = m.rows();\n  int this_cols = m.cols();\n\n  int row_offset = this_rows / 2 - rows / 2;\n  int col_offset = this_cols / 2 - cols / 2;\n  assert(row_offset >= 0);\n  assert(col_offset >= 0);\n  return m.block(row_offset, col_offset, rows, cols);\n}\n\ntemplate <typename T>\nEigen::Block<const T>\nftcut(const Eigen::SparseMatrixBase<T> &m, int rows, int cols)\n{\n  int this_rows = m.rows();\n  int this_cols = m.cols();\n\n  int row_offset = this_rows / 2 - rows / 2;\n  int col_offset = this_cols / 2 - cols / 2;\n  assert(row_offset >= 0);\n  assert(col_offset >= 0);\n  return m.block(row_offset, col_offset, rows, cols);\n}\n\ntemplate <typename T>\nEigen::Block<T>\nftcut(Eigen::DenseBase<T> &&m, int rows, int cols)\n{\n  (void)m;\n  (void)rows;\n  (void)cols;\n  static_assert(sizeof(T) == -1, \"invalid instantiation\");\n}\n\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nftpad(Eigen::SparseMatrixBase<DERIVED1> &dst,\n      const Eigen::SparseMatrixBase<DERIVED2> &src,\n      int nrows,\n      int ncols)\n{\n  BOOST_VERIFY(nrows >= src.rows() && ncols >= src.cols());\n\n  // new row and column offsets\n  auto offset = [](int nnew, int nold) {\n    if ((nnew % 2) == (nold % 2)) {\n      /*  (even,even) or (odd, odd) */\n      return (nnew - nold) / 2;\n    } else if (nnew % 2 == 0 && nold % 2 == 1) {\n      /*  (even, odd)  */\n      return (nnew - nold + 1) / 2;\n    } else if (nnew % 2 == 1 && nold % 2 == 0) {\n      /* (odd, even)  */\n      return (nnew - nold) / 2;\n    } else {\n      assert(false);\n    }\n  };\n\n  int row_offset = offset(nrows, src.rows());\n  int col_offset = offset(ncols, src.cols());\n\n  // todo: this could be implemented (on-the-fly) as a transformation returning\n  // an iterator\n  std::vector<Eigen::Triplet<double, int>> triplets(src.derived().nonZeros());\n  int count = 0;\n  for (int ii = 0; ii < src.outerSize(); ++ii) {\n    for (typename DERIVED2::InnerIterator it(src.derived(), ii); it; ++it) {\n      triplets[count++] =\n          Eigen::Triplet<double, int>(it.row() + row_offset, it.col() + col_offset, it.value());\n    }\n  }\n  BOOST_VERIFY(count == src.derived().nonZeros());\n  dst.derived().resize(nrows, ncols);\n  dst.derived().setFromTriplets(triplets.begin(), triplets.end());\n}\n\ntemplate <typename DERIVED1, typename DERIVED2>\nvoid\nftpad(Eigen::SparseMatrixBase<DERIVED2> &src, int nrows, int ncols)\n{\n  BOOST_VERIFY(nrows >= src.rows() && ncols >= src.cols());\n\n  // new row and column offsets\n  auto offset = [](int nnew, int nold) {\n    if ((nnew % 2) == (nold % 2)) {\n      /*  (even,even) or (odd, odd) */\n      return (nnew - nold) / 2;\n    } else if (nnew % 2 == 0 && nold % 2 == 1) {\n      /*  (even, odd)  */\n      return (nnew - nold + 1) / 2;\n    } else if (nnew % 2 == 1 && nold % 2 == 0) {\n      /* (odd, even)  */\n      return (nnew - nold) / 2;\n    } else {\n      assert(false);\n    }\n  };\n\n  int row_offset = offset(nrows, src.rows());\n  int col_offset = offset(ncols, src.cols());\n\n  // todo: this could be implemented (on-the-fly) as a transformation returning\n  // an iterator\n  std::vector<Eigen::Triplet<double, int>> triplets(src.nonZeros());\n  int count = 0;\n  for (int ii = 0; ii < src.outerSize(); ++ii) {\n    for (typename DERIVED2::InnerIterator it(src.derived(), ii); it; ++it) {\n      triplets[count++] =\n          Eigen::Triplet<double, int>(it.row() + row_offset, it.col() + col_offset, it.value());\n    }\n  }\n  BOOST_VERIFY(count == src.derived().nonZeros());\n  src.derived().resize(nrows, ncols);\n  src.derived().setFromTriplets(triplets.begin(), triplets.end());\n}\n\n/**\n *  @brief set maximal negative frequency coefficients to zero\n *\n *\n *  @param Y Fourier coefficients in zero-centered frequency storage\n */\ntemplate <typename DERIVED>\nvoid\nhf_zero(Eigen::DenseBase<DERIVED> &Y)\n{\n  Y.derived().col(0).setZero();\n  Y.derived().row(0).setZero();\n}\n", "meta": {"hexsha": "9eb0e4b0fcd3adb6984f6eac29d45c6787595cc8", "size": 4403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fft/ft_grid_helpers_impl/ftcut.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "fft/ft_grid_helpers_impl/ftcut.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft/ft_grid_helpers_impl/ftcut.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": 27.6918238994, "max_line_length": 96, "alphanum_fraction": 0.6138996139, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262224883771, "lm_q2_score": 0.03410042730743849, "lm_q1q2_score": 0.006711858292162618}}
{"text": "//\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2016  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 <stdio.h>\n#include <cstdlib>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <cstring>\n#include <cmath>\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <boost/concept_check.hpp>\n\n#include \"Antenna.h\"\n#include \"Application.h\"\n#include \"Debug.h\"\n#include \"GPS.h\"\n#include \"HexBin.h\"\n#include \"Ublox.h\"\n#include \"ReceiverMeasurement.h\"\n#include \"SVMeasurement.h\"\n\nextern ostream *debugStream;\nextern Application *app;\n\n#define CLIGHT 299792458.0\n#define ICD_PI 3.1415926535898\n\n#define MAX_CHANNELS 16 // max channels per constellation\n#define SLOPPINESS 0.1\n#define CLOCKSTEP  0.001\n#define MAX_GAP    3   // maximum permissible gap in observation sequence before ambiguity resolution is triggered\n// types used by ublox receivers     \ntypedef signed char    I1;\ntypedef unsigned char  U1;\ntypedef unsigned char  X1;\ntypedef unsigned short U2;\ntypedef short          I2;\ntypedef int            I4;\ntypedef unsigned int   U4;\ntypedef float          R4;\ntypedef double         R8;\n\n// messages that are parsed\n#define MSG0121 0x01\n#define MSG0122 0x02\n#define MSG0215 0x04\n#define MSG0D01 0x08\n\n\nUblox::Ublox(Antenna *ant,string m):Receiver(ant)\n{\n\tmodelName=m;\n\tmanufacturer=\"ublox\";\n\tswversion=\"0.1\";\n\tconstellations=GNSSSystem::GPS;\n\tcodes=GNSSSystem::C1;\n\tchannels=32;\n\tif (modelName == \"LEA8MT\"){\n\t\t// For the future\n\t}\n\telse if (modelName == \"NEO8MT\"){\n\t}\n\telse{\n\t\tapp->logMessage(\"Unknown receiver model: \" + modelName);\n\t\tapp->logMessage(\"Assuming NEO8MT\");\n\t}\n}\n\nUblox::~Ublox()\n{\n}\n\nbool Ublox::readLog(string fname,int mjd,int startTime,int stopTime,int rinexObsInterval)\n{\n\tDBGMSG(debugStream,INFO,\"reading \" << fname);\t\n\t\n\tifstream infile (fname.c_str());\n\tstring line;\n\tint linecount=0;\n\t\n\tstring msgid,currpctime,pctime,msg,gpstime;\n\t\n\tI4 sawtooth;\n\tI4 clockBias;\n\tR8 measTOW;\n\tU2 measGPSWN;\n\tI1 measLeapSecs;\n\t\n\tU2 UTCyear;\n\tU1 UTCmon,UTCday,UTChour,UTCmin,UTCsec,UTCvalid;\n\t\n\tU1 u1buf;\n\tI2 i2buf;\n\tI4 i4buf;\n\tU4 u4buf;\n\tR4 r4buf;\n\tR8 r8buf;\n\t\n\tfloat rxTimeOffset; // single\n\t\n\tvector<SVMeasurement *> svmeas;\n\t\n\tgotUTCdata=false;\n\tgotIonoData=false;\n\t\n\tunsigned int currentMsgs=0;\n\tunsigned int reqdMsgs =  MSG0121 | MSG0122 | MSG0215 | MSG0D01 ;\n\n  if (infile.is_open()){\n    while ( getline (infile,line) ){\n\t\t\tlinecount++;\n\t\t\t\n\t\t\tif (line.size()==0) continue; // skip empty line\n\t\t\tif ('#' == line.at(0)) continue; // skip comments\n\t\t\tif ('%' == line.at(0)) continue;\n\t\t\tif ('@' == line.at(0)) continue;\n\t\t\t\n\t\t\tstringstream sstr(line);\n\t\t\tsstr >> msgid >> currpctime >> msg;\n\t\t\tif (sstr.fail()){\n\t\t\t\tDBGMSG(debugStream,WARNING,\" bad data at line \" << linecount);\n\t\t\t\tcurrentMsgs=0;\n\t\t\t\tdeleteMeasurements(svmeas);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// The 0x0215 message starts each second\n\t\t\tif(msgid == \"0215\"){ // raw measurements \n\t\t\t\t\n\t\t\t\tif (currentMsgs == reqdMsgs){ // save the measurements from the previous second\n\t\t\t\t\tif (svmeas.size() > 0){\n\t\t\t\t\t\tReceiverMeasurement *rmeas = new ReceiverMeasurement();\n\t\t\t\t\t\tmeasurements.push_back(rmeas);\n\t\t\t\t\t\t\n\t\t\t\t\t\trmeas->sawtooth=sawtooth*1.0E-12; // units are ps, must be added to TIC measurement\n\t\t\t\t\t\trmeas->timeOffset=clockBias*1.0E-9; // units are ns WARNING no sign convention defined yet ...\n\t\t\t\t\t\t\n\t\t\t\t\t\tint pchh,pcmm,pcss;\n\t\t\t\t\t\tif ((3==sscanf(pctime.c_str(),\"%d:%d:%d\",&pchh,&pcmm,&pcss))){\n\t\t\t\t\t\t\trmeas->pchh=pchh;\n\t\t\t\t\t\t\trmeas->pcmm=pcmm;\n\t\t\t\t\t\t\trmeas->pcss=pcss;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t// GPSTOW is used for pseudorange estimations\n\t\t\t\t\t\t// note: this is rounded because measurements are interpolated on a 1s grid\n\t\t\t\t\t\trmeas->gpstow=rint(measTOW);  \n\t\t\t\t\t\trmeas->gpswn=measGPSWN % 1024; // Converted to truncated WN. Not currently used \n\t\t\t\t\t\t\n\t\t\t\t\t\t// UTC time of measurement\n\t\t\t\t\t\t// We could use other time information to calculate this eg gpstow,gpswn and leap seconds\n\t\t\t\t\t\trmeas->tmUTC.tm_sec=UTCsec;\n\t\t\t\t\t\trmeas->tmUTC.tm_min=UTCmin;\n\t\t\t\t\t\trmeas->tmUTC.tm_hour=UTChour;\n\t\t\t\t\t\trmeas->tmUTC.tm_mday=UTCday;\n\t\t\t\t\t\trmeas->tmUTC.tm_mon=UTCmon-1;\n\t\t\t\t\t\trmeas->tmUTC.tm_year=UTCyear-1900;\n\t\t\t\t\t\trmeas->tmUTC.tm_isdst=0;\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Calculate GPS time of measurement \n\t\t\t\t\t\t// FIXME why do this ? why not just convert from UTC ? and full WN is known anyway\n\t\t\t\t\t\ttime_t tgps = GPS::GPStoUnix(rmeas->gpstow,rmeas->gpswn);\n\t\t\t\t\t\tstruct tm *tmGPS = gmtime(&tgps);\n\t\t\t\t\t\trmeas->tmGPS=*tmGPS;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//rmeas->tmfracs = measTOW - (int)(measTOW); \n\t\t\t\t\t\t//if (rmeas->tmfracs > 0.5) rmeas->tmfracs -= 1.0; // place in the previous second\n\t\t\t\t\t\t\n\t\t\t\t\t\trmeas->tmfracs=0.0;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (constellations & GNSSSystem::GPS){\n\t\t\t\t\t\t\tfor (unsigned int sv=0;sv<svmeas.size();sv++){\n\t\t\t\t\t\t\t\tsvmeas.at(sv)->dbuf3 = svmeas.at(sv)->meas; // save for debugging\n\t\t\t\t\t\t\t\tsvmeas.at(sv)->meas -= clockBias*1.0E-9; // evidently it is subtracted\n\t\t\t\t\t\t\t\t// Now subtract the ms part so that ms ambiguity resolution works\n\t\t\t\t\t\t\t\tsvmeas.at(sv)->meas -= 1.0E-3*floor(svmeas.at(sv)->meas/1.0E-3);\n\t\t\t\t\t\t\t\tsvmeas.at(sv)->rm=rmeas;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trmeas->meas=svmeas;\n\t\t\t\t\t\t\tsvmeas.clear(); // don't delete - we only made a shallow copy!\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t// KEEP THIS it's useful for debugging measurement-time related problems\n\t\t\t\t\t//fprintf(stderr,\"PC=%02d:%02d:%02d tmUTC=%02d:%02d:%02d tmGPS=%4d %02d:%02d:%02d gpstow=%d gpswn=%d measTOW=%.12lf tmfracs=%g clockbias=%g\\n\",\n\t\t\t\t\t//\tpchh,pcmm,pcss,UTChour,UTCmin,UTCsec, rmeas->tmGPS.tm_year+1900,rmeas->tmGPS.tm_hour, rmeas->tmGPS.tm_min,rmeas->tmGPS.tm_sec,\n\t\t\t\t\t//\t(int) rmeas->gpstow,(int) rmeas->gpswn,measTOW,rmeas->tmfracs,clockBias*1.0E-9  );\n\t\t\t\t\t\n\t\t\t\t\t//fprintf(stderr,\"%02d:%02d:%02d %02d:%02d:%02d %02d:%02d:%02d %d %d %.12lf %g %g\\n\",\n\t\t\t\t\t//pchh,pcmm,pcss,UTChour,UTCmin,UTCsec, rmeas->tmGPS.tm_hour, rmeas->tmGPS.tm_min,rmeas->tmGPS.tm_sec,\n\t\t\t\t\t//(int) rmeas->gpstow,(int) rmeas->gpswn,measTOW,rmeas->tmfracs,clockBias*1.0E-9  );\n\t\t\t\t\t\t\n\t\t\t\t\t}// if (gpsmeas.size() > 0)\n\t\t\t\t} \n\t\t\t\telse{\n\t\t\t\t\tDBGMSG(debugStream,TRACE,pctime << \" reqd message missing, flags = \" << currentMsgs);\n\t\t\t\t\tdeleteMeasurements(svmeas);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpctime=currpctime;\n\t\t\t\tcurrentMsgs = 0;\n\t\t\t\t\n\t\t\t\tif (msg.size()-2*2-16*2 > 0){ // don't know the expected message size yet but if we've got the header ...\n\t\t\t\t\tHexToBin((char *) msg.substr(11*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &u1buf);\n\t\t\t\t\tunsigned int nmeas=u1buf;\n\t\t\t\t\tif (msg.size() == (2+16+nmeas*32)*2){\n\t\t\t\t\t\tHexToBin((char *) msg.substr(0*2,2*sizeof(R8)).c_str(),sizeof(R8),(unsigned char *) &measTOW); //measurement TOW (s)\n\t\t\t\t\t\tHexToBin((char *) msg.substr(8*2,2*sizeof(U2)).c_str(),sizeof(U2),(unsigned char *) &measGPSWN); // full WN\n\t\t\t\t\t\tHexToBin((char *) msg.substr(10*2,2*sizeof(I1)).c_str(),sizeof(I1),(unsigned char *) &measLeapSecs);\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,currpctime << \" meas tow=\" << measTOW << setprecision(12) << \" gps wn=\" << (int) measGPSWN << \" leap=\" << (int) measLeapSecs);\n\t\t\t\t\t\t//DBGMSG(debugStream,TRACE,nmeas);\n\t\t\t\t\t\tfor (unsigned int m=0;m<nmeas;m++){\n\t\t\t\t\t\t\tHexToBin((char *) msg.substr((36+32*m)*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &u1buf); //GNSS id\n\t\t\t\t\t\t\tint gnssSys = 0;\n\t\t\t\t\t\t\tswitch (u1buf){\n\t\t\t\t\t\t\t\tcase 0: gnssSys=GNSSSystem::GPS; break;\n\t\t\t\t\t\t\t\tcase 1:case 4: case 5: break;\n\t\t\t\t\t\t\t\tcase 2: gnssSys=GNSSSystem::GALILEO; break;\n\t\t\t\t\t\t\t\tcase 3: gnssSys=GNSSSystem::BEIDOU; break;\n\t\t\t\t\t\t\t\tcase 6: gnssSys=GNSSSystem::GLONASS; break;\n\t\t\t\t\t\t\t\tdefault: break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//DBGMSG(debugStream,TRACE,gnssSys);\n\t\t\t\t\t\t\tif (gnssSys & constellations ){\n\t\t\t\t\t\t\t\t// Since we get all the measurements in one message (which starts each second) there's no need to check for multiple measurement messages\n\t\t\t\t\t\t\t\t// like with eg the Resolution T\n\t\t\t\t\t\t\t\tHexToBin((char *) msg.substr((16+32*m)*2,2*sizeof(R8)).c_str(),sizeof(R8),(unsigned char *) &r8buf); //pseudorange (m)\n\t\t\t\t\t\t\t\tHexToBin((char *) msg.substr((37+32*m)*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &u1buf); //svid\n\t\t\t\t\t\t\t\tint svID=u1buf;\n\t\t\t\t\t\t\t\tHexToBin((char *) msg.substr((46+32*m)*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &u1buf);\n\t\t\t\t\t\t\t\tint prStdDev= u1buf & 0x0f;\n\t\t\t\t\t\t\t\tHexToBin((char *) msg.substr((46+32*m)*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &u1buf);\n\t\t\t\t\t\t\t\tint trkStat=u1buf;\n\t\t\t\t\t\t\t\t// When PR is reported, trkStat is always 1 but .\n\t\t\t\t\t\t\t\tif (trkStat > 0 && r8buf/CLIGHT < 1.0){\n\t\t\t\t\t\t\t\t\tSVMeasurement *svm = new SVMeasurement(svID,gnssSys,GNSSSystem::C1,r8buf/CLIGHT,NULL);\n\t\t\t\t\t\t\t\t\t//svm->dbuf1=0.01*pow(2.0,prStdDev); \n\t\t\t\t\t\t\t\t\tsvmeas.push_back(svm);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\"SYS \" <<gnssSys << \" SV\" << svID << \" pr=\" << r8buf/CLIGHT << setprecision(8) << \" trkStat= \" << (int) trkStat);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentMsgs |= MSG0215;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad 0215 message size\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\"empty/malformed 0215 message\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t} // raw measurements\n\t\t\t\n\t\t\t// 0x0D01 Timepulse time data (sawtooth correction)\n\t\t\tif(msgid == \"0d01\"){\n\t\t\t\t\n\t\t\t\tif (msg.size()==(16+2)*2){\n\t\t\t\t\tX1 TPflags,TPrefInfo;\n\t\t\t\t\tU4 TPTOW;\n\t\t\t\t\tHexToBin((char *) msg.substr(0*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &TPTOW); // (ms)\n\t\t\t\t\tHexToBin((char *) msg.substr(8*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &sawtooth); // (ps)\n\t\t\t\t\tHexToBin((char *) msg.substr(14*2,2*sizeof(X1)).c_str(),sizeof(X1),(unsigned char *) &TPflags);\n\t\t\t\t\tHexToBin((char *) msg.substr(15*2,2*sizeof(X1)).c_str(),sizeof(X1),(unsigned char *) &TPrefInfo);\n\t\t\t\t\tDBGMSG(debugStream,TRACE,currpctime << \" tow= \" << (int) TPTOW << \" sawtooth=\" << sawtooth << \" ps\" << std::hex << \" flags=0x\" << (unsigned int) TPflags << \n\t\t\t\t\t\t\" ref=0x\" << (unsigned int) TPrefInfo << std::dec);\n\t\t\t\t\tcurrentMsgs |= MSG0D01;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad 0d01 message size\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t// 0x0135 UBX-NAV-SAT satellite information\n\t\t\t\n\t\t\t// 0x0121 UBX-NAV-TIME-UTC UTC time solution\n\t\t\tif(msgid == \"0121\"){\n\t\t\t\tif (msg.size()==(20+2)*2){\n\t\t\t\t\tHexToBin((char *) msg.substr(12*2,2*sizeof(U2)).c_str(),sizeof(U2),(unsigned char *) &UTCyear);\n\t\t\t\t\tHexToBin((char *) msg.substr(14*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &UTCmon);\n\t\t\t\t\tHexToBin((char *) msg.substr(15*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &UTCday);\n\t\t\t\t\tHexToBin((char *) msg.substr(16*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &UTChour);\n\t\t\t\t\tHexToBin((char *) msg.substr(17*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &UTCmin);\n\t\t\t\t\tHexToBin((char *) msg.substr(18*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &UTCsec);\n\t\t\t\t\tHexToBin((char *) msg.substr(19*2,2*sizeof(X1)).c_str(),sizeof(X1),(unsigned char *) &UTCvalid);\n\t\t\t\t\tDBGMSG(debugStream,TRACE,currpctime << \" UTC:\" << UTCyear << \" \" << (int) UTCmon << \" \" << (int) UTCday << \" \"\n\t\t\t\t\t\t<< (int) UTChour << \":\" << (int) UTCmin << \":\" << (int) UTCsec << \" valid=\" << (unsigned int) UTCvalid);\n\t\t\t\t\tif (UTCvalid & 0x04)\n\t\t\t\t\t\tcurrentMsgs |= MSG0121;\n\t\t\t\t\telse{\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"UTC not valid yet\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad 0121 message size\");\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// 0x0122 UBX-NAV-CLOCK clock solution  (clock bias)\n\t\t\tif(msgid == \"0122\"){\n\t\t\t\tif (msg.size()==(20+2)*2){\n\t\t\t\t\t\tHexToBin((char *) msg.substr(0*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf); // GPS tow of navigation epoch (ms)\n\t\t\t\t\t\tHexToBin((char *) msg.substr(4*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &clockBias); // in ns\n\t\t\t\t\t\t\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\"GPS tow=\" << u4buf << \"ms\" << \" clock bias=\" << clockBias << \" ns\");\n\t\t\t\t\t\tcurrentMsgs |= MSG0122;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad 0122 message size\");\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t//\n\t\t\t// Messages needed to contruct the RINEX navigation file\n\t\t\t//\n\t\t\t\n\t\t\t// Ionosphere parameters, UTC parameters \n\t\t\tif (!gotUTCdata){\n\t\t\t\tif(msgid == \"0b02\"){\n\t\t\t\t\tif (msg.size()==(72+2)*2){\n\t\t\t\t\t\tHexToBin((char *) msg.substr(4*2,2*sizeof(R8)).c_str(),sizeof(R8),(unsigned char *) &(gps.UTCdata.A0)); \n\t\t\t\t\t\tHexToBin((char *) msg.substr(12*2,2*sizeof(R8)).c_str(),sizeof(R8),(unsigned char *) &r8buf);\n\t\t\t\t\t\tgps.UTCdata.A1=r8buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(20*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &i4buf);\n\t\t\t\t\t\tgps.UTCdata.t_ot = i4buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(24*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &i2buf);\n\t\t\t\t\t\tgps.UTCdata.WN_t=i2buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(26*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &i2buf);\n\t\t\t\t\t\tleapsecs = i2buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(28*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &i2buf);\n\t\t\t\t\t\tgps.UTCdata.WN_LSF=i2buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(30*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &i2buf);\n\t\t\t\t\t\tgps.UTCdata.DN=i2buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(32*2,2*sizeof(I4)).c_str(),sizeof(I4),(unsigned char *) &i2buf);\n\t\t\t\t\t\tgps.UTCdata.dt_LSF=i2buf;\n\t\t\t\t\t\t\n\t\t\t\t\t\tHexToBin((char *) msg.substr(36*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.a0));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(40*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.a1));\n\t\t\t\t\t\t//gps.ionoData.a1 /= ICD_PI;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(44*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.a2));\n\t\t\t\t\t\t//gps.ionoData.a2 /= (ICD_PI*ICD_PI);\n\t\t\t\t\t\tHexToBin((char *) msg.substr(48*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.a3));\n\t\t\t\t\t\t//gps.ionoData.a3 /= (ICD_PI*ICD_PI*ICD_PI);\n\t\t\t\t\t\t\n\t\t\t\t\t\tHexToBin((char *) msg.substr(52*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.B0));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(56*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.B1));\n\t\t\t\t\t\t//gps.ionoData.B1 /= ICD_PI;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(60*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.B2));\n\t\t\t\t\t\t//gps.ionoData.B2 /= (ICD_PI*ICD_PI);\n\t\t\t\t\t\tHexToBin((char *) msg.substr(64*2,2*sizeof(R4)).c_str(),sizeof(R4),(unsigned char *) &(gps.ionoData.B3));\n\t\t\t\t\t\t//gps.ionoData.B3 /= (ICD_PI*ICD_PI*ICD_PI);\n\t\t\t\t\t\t\n\t\t\t\t\t\tgotUTCdata=true;\n\t\t\t\t\t\tgotIonoData=true;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad 0b02 message size\");\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\t// Ephemeris\n\t\t\tif(msgid == \"0b31\"){\n\t\t\t\tif (msg.size()==(8+2)*2){\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Empty ephemeris\");\n\t\t\t\t}\n\t\t\t\telse if (msg.size()==(104+2)*2){\n\t\t\t\t\tGPS::EphemerisData *ed = decodeGPSEphemeris(msg);\n\t\t\t\t\tint pchh,pcmm,pcss;\n\t\t\t\t\t\tif ((3==sscanf(pctime.c_str(),\"%d:%d:%d\",&pchh,&pcmm,&pcss)))\n\t\t\t\t\t\t\ted->tLogged = pchh*3600 + pcmm*60 + pcss; \n\t\t\t\t\t\telse\n\t\t\t\t\t\t\ted->tLogged = -1;\n\t\t\t\t\tgps.addEphemeris(ed);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad 0b31 message size\");\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t} // ephemeris\n\t\t}\n\t} // infile is open\n\telse{\n\t\tapp->logMessage(\" unable to open \" + fname);\n\t\treturn false;\n\t}\n\tinfile.close();\n\n\t\n\tif (!gotUTCdata){\n\t\tapp->logMessage(\"failed to find ionosphere/UTC parameters - no 0b02 messages\");\n\t\t//return false; // FIXME temporary\n\t}\n\t\n\tif (measurements.size() == 0){\n\t\tapp->logMessage(\" no measurements available in \" + fname);\n\t\treturn false;\n\t}\n\t\n\t// Pass through the data to realign the sawtooth correction.\n\t// This could be done in the main loop but it's more flexible this way.\n\t// For the ublox, the sawtooth correction applies to the next second\n\t// If we're missing the sawtooth correction because of eg a gap in the data\n\t// then we'll just use the current sawtooth. \n\t\n\tDBGMSG(debugStream,TRACE,\"Fixing sawtooth\");\n\tdouble prevSawtooth=measurements.at(0)->sawtooth;\n\ttime_t    tPrevSawtooth=mktime(&(measurements.at(0)->tmUTC));\n\tint nBadSawtoothCorrections =1; // first is bad !\n\t// First point is untouched\n\tfor (unsigned int i=1;i<measurements.size();i++){\n\t\tdouble sawTmp = measurements.at(i)->sawtooth;\n\t\ttime_t tTmp= mktime(&(measurements.at(i)->tmUTC));\n\t\tif (tTmp - tPrevSawtooth == 1){\n\t\t\tmeasurements.at(i)->sawtooth = prevSawtooth;\n\t\t}\n\t\telse{\n\t\t\t// do nothing - the current value is the best guess\n\t\t\tnBadSawtoothCorrections++;\n\t\t}\n\t\tprevSawtooth=sawTmp;\n\t\ttPrevSawtooth=tTmp;\n\t}\n\t\n\t// The Ublox sometime reports what appears to be an incorrect pseudorange after picking up an SV\n\t// If you wanted to filter these out, this is where you should do it\n\t\n\t// Fix 1 ms ambiguities/steps in the pseudorange\n\t// Do this initially and then every time a step is detected\n\t\n\tDBGMSG(debugStream,TRACE,\"Fixing ms ambiguities\");\n\tint nDropped;\n\tfor (int g=GNSSSystem::GPS;g<=GNSSSystem::GALILEO;(g <<= 1)){\n\t\tif (!(g & constellations)) continue;\n\t\tGNSSSystem *gnss;\n\t\tswitch (g){\n\t\t\tcase GNSSSystem::BEIDOU:gnss=&beidou;break;\n\t\t\tcase GNSSSystem::GALILEO:gnss=&galileo;break;\n\t\t\tcase GNSSSystem::GLONASS:gnss=&glonass;break;\n\t\t\tcase GNSSSystem::GPS:gnss=&gps;break;\n\t\t\tdefault:break;\n\t\t}\n\t\tfor (int svn=1;svn<=gnss->nsats();svn++){\n\t\t\tunsigned int lasttow=99999999,currtow=99999999;\n\t\t\tdouble lastmeas=0,currmeas;\n\t\t\tdouble corr=0.0;\n\t\t\tbool first=true;\n\t\t\tbool ok=false;\n\t\t\tfor (unsigned int i=0;i<measurements.size();i++){\n\t\t\t\tunsigned int m=0;\n\t\t\t\twhile (m < measurements[i]->meas.size()){\n\t\t\t\t\tif ((svn==measurements[i]->meas[m]->svn) && (measurements[i]->meas[m]->code == GNSSSystem::C1)){\n\t\t\t\t\t\tlasttow=currtow;\n\t\t\t\t\t\tlastmeas=currmeas;\n\t\t\t\t\t\tcurrmeas=measurements[i]->meas[m]->meas;\n\t\t\t\t\t\tcurrtow=measurements[i]->gpstow;\n\t\t\t\t\t\t\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,svn << \" \" << currtow << \" \" << currmeas << \" \");\n\t\t\t\t\t\tif (first){\n\t\t\t\t\t\t\tok = gnss->resolveMsAmbiguity(antenna,measurements[i],measurements[i]->meas[m],&corr);\n\t\t\t\t\t\t\tif (ok){\n\t\t\t\t\t\t\t\tfirst=false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (currtow - lasttow > MAX_GAP){\n\t\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\"gap \" << svn << \" \" << lasttow << \",\" << lastmeas << \"->\" << currtow << \",\" << currmeas);\n\t\t\t\t\t\t\tok = gnss->resolveMsAmbiguity(antenna,measurements[i],measurements[i]->meas[m],&corr);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (currtow > lasttow){\n\t\t\t\t\t\t\tif (fabs(currmeas-lastmeas) > CLOCKSTEP*SLOPPINESS){\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\"first/step \" << svn << \" \" << lasttow << \",\" << lastmeas << \"->\" << currtow << \",\" << currmeas);\n\t\t\t\t\t\t\t\tok = gnss->resolveMsAmbiguity(antenna,measurements[i],measurements[i]->meas[m],&corr);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (ok){ \n\t\t\t\t\t\t\tmeasurements[i]->meas[m]->meas += corr;\n\t\t\t\t\t\t\tm++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{ // ambiguity correction failed, so drop the measurement\n\t\t\t\t\t\t\tnDropped++;\n\t\t\t\t\t\t\tmeasurements[i]->meas.erase(measurements[i]->meas.begin()+m); // FIXME memory leak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tm++;\n\t\t\t\t\t\n\t\t\t\t} // \n\t\t\t} // for (unsigned int i=0;i<measurements.size();i++){\n\t\t}\n\t}\n\t\n\tDBGMSG(debugStream,INFO,\"done: read \" << linecount << \" lines\");\n\tDBGMSG(debugStream,INFO,measurements.size() << \" measurements read\");\n\tDBGMSG(debugStream,INFO,gps.ephemeris.size() << \" GPS ephemeris entries read\");\n\tDBGMSG(debugStream,INFO,nBadSawtoothCorrections << \" bad sawtooth corrections\");\n\tDBGMSG(debugStream,INFO,\"dropped \" << nDropped << \" SV measurements (ms ambiguity failure)\"); \n\t\n\treturn true;\n\t\n}\n\nGPS::EphemerisData* Ublox::decodeGPSEphemeris(string msg)\n{\n\tU4 u4buf;\n\tHexToBin((char *) msg.substr(0*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tGPS::EphemerisData* ed= new GPS::EphemerisData();\n\ted->SVN=u4buf;\n\tDBGMSG(debugStream,TRACE,\"Ephemeris for SV\" << (int) ed->SVN);\n\t\n\t// cerr << \"EPH\" << endl;\n\n\t// To use the MID macro, LSB is bit 0, m is first bit, n is last bit\n\t#define LAST(k,n) ((k) & ((1<<(n))-1))\n\t#define MID(k,m,n) LAST((k)>>(m),((n)-(m)+1)) \n\t\n\t// Data is in bits 0-23, parity bits are discarded by ublox\n\t// To translate from ICD numbering b24 (ICD) -> b0 (ublox)\n\t// subframe 1\n\t// word 3\n\tHexToBin((char *) msg.substr(8*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\t\n\ted->week_number = MID(u4buf,14,23);\n\ted->SV_accuracy_raw=MID(u4buf,8,11); \n\ted->SV_accuracy = GPS::URA[ed->SV_accuracy_raw];\n\ted->SV_health=MID(u4buf,2,7);\n\t// IODC b23-b24 (upper bits)\n\tunsigned int hibits=MID(u4buf,0,1);\n\thibits = hibits << 8;\n\t\n\t//fprintf(stderr,\"%i %08x %i %i %i\\n\",(int) ed->SVN,u4buf, (int) ed->week_number,\n\t//\t(int) ed->SV_accuracy, ed->SV_health);\n\t\n\t// word 7 \n\tHexToBin((char *) msg.substr(24*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\t//Tgd b17-b24 (ICD) CHECKED\n\tsigned char tGD = MID(u4buf,0,7); // signed, scaled by 2^-31\n\ted->t_GD =  (double) tGD / (double) pow(2,31);\n\t\n\t//fprintf(stderr,\"%08x %.12e\\n\",u4buf,ed->t_GD);\n\t\n\t// word 8\n\tHexToBin((char *) msg.substr(28*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\t// IODC b1-b8 (lower bits) // CHECKED\n\tunsigned int lobits = MID(u4buf,16,23);\n\ted->IODC = hibits | lobits;\n\t// t_OC b9-b24 (ICD)\n\ted->t_OC = 16*MID(u4buf,0,15);\n\t//fprintf(stderr,\"%08x %e %i\\n\",u4buf,ed->t_OC,(int) ed->IODC);\n\t\n\t// word 9 a_f2 b1-b8, a_f1 b9-b24 // CHECKED a_f1\n\tHexToBin((char *) msg.substr(32*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tsigned char af2 = MID(u4buf,16,23);\n\ted->a_f2 = af2/pow(2,55);\n\tsigned short af1= MID(u4buf,0,15);\n\ted->a_f1 = (double) af1/(double) pow(2,43);\n\t\n\t//fprintf(stderr,\"%08x %.12e %.12e\\n\",u4buf,ed->a_f1,ed->a_f2);\n\tif (ed->a_f2 != 0.0) fprintf(stderr,\"BING!\\n\");\n\n\t// word 10 a_f0 b1-b22 // CHECKED\n\tHexToBin((char *) msg.substr(36*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tint tmp = (MID(u4buf,2,23) << 10);\n\ttmp = tmp >> 10;\n\ted->a_f0 = (double) tmp /(double) pow(2,31); // signed, scaled by 2^-31\n\t//fprintf(stderr,\"%08x %.12e\\n\",u4buf,ed->a_f0);\n\t\n\t// data frame 2\n\t// word 3\n\t// IODE b1-b8 // CHECKED\n\tHexToBin((char *) msg.substr(40*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\ted->IODE = MID(u4buf,16,23);\n\t// C_rs b9-b24 // CHECKED\n\tsigned short Crs= MID(u4buf,0,15);\n\ted->C_rs= (double) Crs/ (double) 32.0;\n\t//fprintf(stderr,\"%08x %i %.12e\\n\",u4buf,ed->IODE,ed->C_rs);\n\t\n\t// word 4\n\t// deltaN b1-b16 // CHECKED nb this is a SINGLE so differences in 7 or 8th digit in RINEX files\n\tHexToBin((char *) msg.substr(44*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tsigned short deltaN=MID(u4buf,8,23);\n\ted->delta_N = ICD_PI*(double) deltaN/(double) pow(2,43); // GPS units are semi-circles/s, RINEX units are rad/s\n\t// M_0 (upper 8 bits) b17-b24\n\thibits =  MID(u4buf,0,7) << 24;\n\t\n\t// word 5\n\t// M_0 (lower 24 bits) b1-b24 // CHECKED\n\tHexToBin((char *) msg.substr(48*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tlobits = MID(u4buf,0,23);\n\t\n\ted->M_0 = ICD_PI * ((double) ((int) (hibits | lobits)))/ (double) pow(2,31);\n\t//fprintf(stderr,\"%08x %.12e %.12e\\n\",u4buf,ed->delta_N, ed->M_0);\n\t\n\t// word 6\n\t// C_uc b1-b16 // CHECKED\n\tHexToBin((char *) msg.substr(52*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tsigned short Cuc=MID(u4buf,8,23);\n\ted->C_uc = (double) Cuc/(double) pow(2,29);\n\t// e b17-b24 (upper 8 bits)\n\thibits =  MID(u4buf,0,7) << 24;\n\t\n\t// word 7\n\t// e b1-b24 (lower 24 bits) // CHECKED\n\tHexToBin((char *) msg.substr(56*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tlobits = MID(u4buf,0,23);\n\ted->e = ((double) (unsigned int)((hibits | lobits)))/ (double) pow(2,33);\n\t//fprintf(stderr,\"%08x %.12e %.12e \\n\",u4buf,ed->C_uc,ed->e);\n\t\n\t// word 8\n\t// C_us b1-b16 // CHECKED\n\tHexToBin((char *) msg.substr(60*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tsigned short Cus=MID(u4buf,8,23);\n\ted->C_us = (double) Cus/(double) pow(2,29);\n\t// sqrtA b1-b8 (upper bits)\n\thibits =  MID(u4buf,0,7) << 24;\n\t\n\t// word 9\n\t//sqrtA b1-b24 (lower bits) // CHECKED\n\tHexToBin((char *) msg.substr(64*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tlobits = MID(u4buf,0,23);\n\ted->sqrtA = ((double) (unsigned int)((hibits | lobits)))/ (double) pow(2,19);\n\t//fprintf(stderr,\"%08x %.12e %.12e\\n\",u4buf,ed->C_us,ed->sqrtA);\n\t\n\t// word 10\n\t// t_OE b1-b16 // CHECKED\n\tHexToBin((char *) msg.substr(68*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tunsigned short toe=MID(u4buf,8,23);\n\ted->t_oe = toe * 16;\n\t//fprintf(stderr,\"%08x %.12e \\n\",u4buf,ed->t_oe);\n\t\n\t// data frame 3\n\t// word 3\n\t// C_ic b1-b16 // CHECKED\n\tHexToBin((char *) msg.substr(72*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tsigned short Cic=MID(u4buf,8,23);\n\ted->C_ic = (double) Cic/(double) pow(2,29);\n\t// OMEGA_0 b17-b24 (upper bits)\n\thibits =  MID(u4buf,0,7) << 24;\n\t\n\t// word 4\n\t// OMEGA_0 b1-b24 lower bits // CHECKED\n\tHexToBin((char *) msg.substr(76*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tlobits = MID(u4buf,0,23);\n\ted->OMEGA_0 = ICD_PI * ((double) (signed int)((hibits | lobits)))/ (double) pow(2,31);\n\t//fprintf(stderr,\"%08x %.12e %.12e\\n\",u4buf,ed->C_ic,ed->OMEGA_0);\n\t\n\t// word 5\n\t// C_is b1-b16 // CHECKED\n\tHexToBin((char *) msg.substr(80*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tsigned short Cis=MID(u4buf,8,23);\n\ted->C_is= (double) Cis/(double) pow(2,29);\n\t// i_0 b17-b24 (upper bits)\n\thibits =  MID(u4buf,0,7) << 24;\n\t\n\t// word 6\n\t// i_0 b1-b24 (lower bits) // CHECKED\n\tHexToBin((char *) msg.substr(84*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tlobits = MID(u4buf,0,23);\n\ted->i_0 = ICD_PI * ((double) (signed int)((hibits | lobits)))/ (double) pow(2,31);\n\t//fprintf(stderr,\"%08x %.12e %.12e\\n\",u4buf,ed->C_is,ed->i_0);\n\t\n\t// word 7\n\t// C_rc b1-b16 // CHECKED\n\tHexToBin((char *) msg.substr(88*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tsigned short Crc=MID(u4buf,8,23);\n\ted->C_rc= (double) Crc/32.0;\n\t// OMEGA b17-b24 (upper bits)\n\thibits =  MID(u4buf,0,7) << 24;\n\t\n\t// word 8\n\t// OMEGA b1-b24 (lower bits) // CHECKED\n\tHexToBin((char *) msg.substr(92*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tlobits = MID(u4buf,0,23);\n\ted->OMEGA = ICD_PI * ((double) (signed int)((hibits | lobits)))/ (double) pow(2,31);\n\t//fprintf(stderr,\"%08x %.12e %.12e\\n\",u4buf,ed->C_rc,ed->OMEGA);\n\t\n\t\n\t// word 9\n\t// OMEGA_DOT b1-b24 // CHECKED\n\tHexToBin((char *) msg.substr(96*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tint odot = (MID(u4buf,0,23)) << 8;\n\todot = odot >> 8;\t\n\ted->OMEGADOT = ICD_PI * (double) (odot)/ (double) pow(2,43);\n\t//fprintf(stderr,\"%08x %.12e\\n\",u4buf,ed->OMEGADOT);\n\n\t// word 10\n\t// IODE b1-b8 (repeated to facilitate checking for data cutovers) ... but which one should I use ???\n\t// IDOT b9-b22 // CHECKED\n\tHexToBin((char *) msg.substr(100*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\tint idot = (MID(u4buf,2,15)) << 18;\n\tidot = idot >> 18;\n\ted->IDOT = ICD_PI * (double) (idot)/ (double) pow(2,43);\n\t//fprintf(stderr,\"%08x %.12e\\n\",u4buf,ed->IDOT);\n\t\n\treturn ed;\n}\n", "meta": {"hexsha": "5e622cceda6ae1532b35986741a7ea4fce4a76a8", "size": 27768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/gpscv/common/process/mktimetx/Ublox.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/Ublox.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/Ublox.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": 38.1428571429, "max_line_length": 161, "alphanum_fraction": 0.6312662057, "num_tokens": 9675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682621306573767, "lm_q2_score": 0.034100423135568096, "lm_q1q2_score": 0.006711857149713136}}
{"text": "/*\n * Copyright (c) 2020-2021 Adrian Georg Herrmann\n * \n * This contains code for the HEMS data types and structures.\n */\n\n#include <algorithm>\n#include <map>\n#include <string>\n#include <cmath>\n\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include \"hems/common/types.h\"\n\nnamespace hems { namespace types {\n\n    bool operator==(const settings_t& lhs, const settings_t& rhs) {\n        if (lhs.longitude == rhs.longitude && lhs.latitude == rhs.latitude &&\n            lhs.timezone == rhs.timezone && lhs.pv_uri == rhs.pv_uri &&\n            lhs.station_intervals == rhs.station_intervals && lhs.station_uris == rhs.station_uris &&\n            lhs.interval_energy_production == rhs.interval_energy_production &&\n            lhs.interval_energy_consumption == rhs.interval_energy_consumption &&\n            lhs.interval_automation == rhs.interval_automation) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    bool operator!=(const settings_t& lhs, const settings_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const settings_t& entry) {\n        std::string str = \"(\"\n            \"longitude: \" + std::to_string(entry.longitude) + \", \" +\n            \"latitude: \" + std::to_string(entry.latitude) + \", \" +\n            \"timezone: \" + std::to_string(entry.timezone) + \", \" +\n            \"pv_uri: '\" + entry.pv_uri + \"', \" +\n            \"station_intervals: (\";\n        if (entry.station_intervals.empty()) {\n            str += \"None\";\n        } else {\n            for (const auto& station_interval : entry.station_intervals) {\n                str +=\n                    std::to_string(station_interval.first) + \" -> \" +\n                    std::to_string(station_interval.second) + \", \";\n            }\n            str.pop_back();\n            str.pop_back();\n        }\n        str += \"), station_uris: (\";\n        if (entry.station_uris.empty()) {\n            str += \"None\";\n        } else {\n            for (const auto& station_uris : entry.station_uris) {\n                str +=\n                    std::to_string(station_uris.first) + \" -> \" +\n                    \"'\" + station_uris.second + \"', \";\n            }\n            str.pop_back();\n            str.pop_back();\n        }\n        str += \"), \";\n        str +=\n            \"interval_energy_production: \" + std::to_string(entry.interval_energy_production) + \", \" +\n            \"interval_energy_consumption: \" + std::to_string(entry.interval_energy_consumption) + \", \" +\n            \"interval_automation: \" + std::to_string(entry.interval_automation);\n        str += \")\";\n        return str;\n    }\n\n    const settings_t settings_undefined;\n\n    bool is_undefined(const settings_t& entry) {\n        return entry.longitude == 0 && entry.latitude == 0 && entry.timezone == 0;\n    }\n\n\n    bool operator==(const appliance_t& lhs, const appliance_t& rhs) {\n        if (lhs.name != rhs.name || lhs.uri != rhs.uri || lhs.rating != rhs.rating ||\n            lhs.duty_cycle != rhs.duty_cycle || lhs.schedules_per_week != rhs.schedules_per_week ||\n            lhs.tasks.size() != rhs.tasks.size() || lhs.auto_profiles.size() != rhs.auto_profiles.size()) {\n            return false;\n        } else if (!std::is_permutation(lhs.tasks.begin(), lhs.tasks.end(), rhs.tasks.begin())) {\n            return false;\n        } else if (\n            !std::is_permutation(lhs.auto_profiles.begin(), lhs.auto_profiles.end(), rhs.auto_profiles.begin())\n        ) {\n            return false;\n        } else {\n            return true;\n        }\n    }\n\n    bool operator!=(const appliance_t& lhs, const appliance_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const appliance_t& entry) {\n        std::string str = \"(\"\n            \"id: \" + std::to_string(entry.id) + \", \"\n            \"name: '\" + entry.name + \"', \"\n            \"uri: '\" + entry.uri + \"', \"\n            \"rating: \" + std::to_string(entry.rating) + \", \"\n            \"duty_cycle: \" + std::to_string(entry.duty_cycle) + \", \"\n            \"schedules_per_week: \" + std::to_string(entry.schedules_per_week) + \", \"\n            \"tasks: (\";\n        if (entry.tasks.empty()) {\n            str += \"None\";\n        } else {\n            for (const auto& task : entry.tasks) {\n                str += std::to_string(task) + \", \";\n            }\n            str.pop_back();\n            str.pop_back();\n        }\n        str += \"), auto_profiles: (\";\n        if (entry.auto_profiles.empty()) {\n            str += \"None\";\n        } else {\n            for (const auto& auto_profile : entry.auto_profiles) {\n                str += std::to_string(auto_profile) + \", \";\n            }\n            str.pop_back();\n            str.pop_back();\n        }\n        str += \"))\";\n        return str;\n    }\n\n\n    bool operator==(const task_t& lhs, const task_t& rhs) {\n        if (lhs.name != rhs.name || lhs.start_time != rhs.start_time || lhs.end_time != rhs.end_time ||\n            lhs.auto_profile != rhs.auto_profile || lhs.is_user_declared != rhs.is_user_declared ||\n            lhs.appliances.size() != rhs.appliances.size()) {\n            return false;\n        } else if (!std::is_permutation(lhs.appliances.begin(), lhs.appliances.end(), rhs.appliances.begin())) {\n            return false;\n        } else {\n            return true;\n        }\n    }\n\n    bool operator!=(const task_t& lhs, const task_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const task_t& entry) {\n        std::string str = \"(\"\n            \"id: \" + std::to_string(entry.id) + \", \"\n            \"name: '\" + entry.name + \"', \"\n            \"start_time: \" + boost::posix_time::to_simple_string(entry.start_time) + \", \"\n            \"end_time: \" + boost::posix_time::to_simple_string(entry.end_time) + \", \"\n            \"auto_profile: \" + std::to_string(entry.auto_profile) + \", \"\n            \"is_user_declared: \" + (entry.is_user_declared ? \"true\" : \"false\") + \", \"\n            \"appliances: (\";\n        if (entry.appliances.empty()) {\n            str += \"None\";\n        } else {\n            for (const auto& appliance : entry.appliances) {\n                str += std::to_string(appliance) + \", \";\n            }\n            str.pop_back();\n            str.pop_back();\n        }\n        str += \"))\";\n        return str;\n    }\n\n\n    bool operator==(const auto_profile_t& lhs, const auto_profile_t& rhs) {\n        if (lhs.name != rhs.name || lhs.profile != rhs.profile ||\n            lhs.appliances.size() != rhs.appliances.size() || lhs.tasks.size() != rhs.tasks.size()) {\n            return false;\n        } else if (!std::is_permutation(lhs.appliances.begin(), lhs.appliances.end(), rhs.appliances.begin())) {\n            return false;\n        } else if (!std::is_permutation(lhs.tasks.begin(), lhs.tasks.end(), rhs.tasks.begin())) {\n            return false;\n        } else {\n            return true;\n        }\n    }\n\n    bool operator!=(const auto_profile_t& lhs, const auto_profile_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const auto_profile_t& entry) {\n        std::string str = \"(\"\n            \"id: \" + std::to_string(entry.id) + \", \"\n            \"name: '\" + entry.name + \"', \"\n            \"profile: '\" + entry.profile + \"', \"\n            \"appliances: (\";\n        if (entry.appliances.empty()) {\n            str += \"None\";\n        } else {\n            for (const auto& appliance : entry.appliances) {\n                str += std::to_string(appliance) + \", \";\n            }\n            str.pop_back();\n            str.pop_back();\n        }\n        str += \"), tasks: (\";\n        if (entry.tasks.empty()) {\n            str += \"None\";\n        } else {\n            for (const auto& task : entry.tasks) {\n                str += std::to_string(task) + \", \";\n            }\n            str.pop_back();\n            str.pop_back();\n        }\n        str += \"))\";\n        return str;\n    }\n\n\n    bool operator==(const energy_consumption_t& lhs, const energy_consumption_t& rhs) {\n        if (lhs.time == rhs.time && lhs.appliance_id == rhs.appliance_id && lhs.energy == rhs.energy) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    bool operator!=(const energy_consumption_t& lhs, const energy_consumption_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const energy_consumption_t& entry) {\n        std::string str = \"(\"\n            \"time: \" + boost::posix_time::to_simple_string(entry.time) + \", \"\n            \"appliance_id: \" + std::to_string(entry.appliance_id) + \", \"\n            \"energy: \" + std::to_string(entry.energy) +\n        \")\";\n        return str;\n    }\n\n\n    bool operator==(const energy_production_t& lhs, const energy_production_t& rhs) {\n        if (lhs.time == rhs.time && lhs.energy == rhs.energy) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    bool operator!=(const energy_production_t& lhs, const energy_production_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const energy_production_t& entry) {\n        std::string str = \"(\"\n            \"time: \" + boost::posix_time::to_simple_string(entry.time) + \", \"\n            \"energy: \" + std::to_string(entry.energy) +\n        \")\";\n        return str;\n    }\n\n\n    bool operator==(const weather_t& lhs, const weather_t& rhs) {\n        if (lhs.time == rhs.time && lhs.station == rhs.station && lhs.temperature == rhs.temperature &&\n            lhs.humidity == rhs.humidity && lhs.pressure == rhs.pressure &&\n            lhs.cloud_cover == rhs.cloud_cover && lhs.radiation == rhs.radiation) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    bool operator!=(const weather_t& lhs, const weather_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const weather_t& entry) {\n        std::string str = \"(\"\n            \"time: \" + boost::posix_time::to_simple_string(entry.time) + \", \"\n            \"temperature: \" + std::to_string(entry.temperature) + \", \"\n            \"humidity: \" + std::to_string(entry.humidity) + \", \"\n            \"pressure: \" + std::to_string(entry.pressure) + \", \"\n            \"cloud cover: \" + std::to_string(entry.cloud_cover) + \", \"\n            \"radiation: \" + std::to_string(entry.radiation) +\n        \")\";\n        return str;\n    }\n\n\n    bool operator==(const sunlight_t& lhs, const sunlight_t& rhs) {\n        if (lhs.time == rhs.time && lhs.angle == rhs.angle) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    bool operator!=(const sunlight_t& lhs, const sunlight_t& rhs) {\n        return !(lhs == rhs);\n    }\n\n    std::string to_string(const sunlight_t& entry) {\n        std::string str = \"(\"\n            \"time: \" + boost::posix_time::to_simple_string(entry.time) + \", \"\n            \"angle: \" + std::to_string(entry.angle) +\n        \")\";\n        return str;\n    }\n\n    sunlight_t get_angle(ptime time, double latitude, double longitude) {\n        auto get_radians = [](double degrees) {\n            return (degrees * M_PI) / 180;\n        };\n\n        auto get_degrees = [](double radians) {\n            return (radians * 180) / M_PI;\n        };\n\n        auto get_julian_day = [](ptime time) {\n            auto y = 0;\n            auto m = 0;\n            if (time.date().month() > 2) {\n                y = time.date().year();\n                m = time.date().month();\n            } else {\n                y = time.date().year() - 1;\n                m = time.date().month() + 12;\n            }\n            auto d =\n                time.date().day() + time.time_of_day().hours() / 24.0 +\n                time.time_of_day().minutes() / 1440.0 + time.time_of_day().seconds() / 86400.0;\n            auto b = 2 - std::floor(y / 100) + std::floor(y / 400);\n\n            auto jd = std::floor(365.25 * (y + 4716)) + std::floor(30.6001 * (m + 1)) + d + b - 1524.5;\n            return jd;\n        };\n\n\n        /* Source: https://de.wikipedia.org/wiki/Sonnenstand#Genauere_Ermittlung_des_Sonnenstandes_f%C3%BCr_einen_Zeitpunkt */\n\n        /* 1. Eclipctical coordinates of the sun */\n\n        /* Julian day */\n        auto jd = get_julian_day(time);\n\n        auto n = jd - 2451545;\n\n        /* Median ecliptic longitude of the sun */\n        auto l = std::fmod(280.46 + 0.9856474 * n, 360);\n\n        /* Median anomaly */\n        auto g = std::fmod(357.528 + 0.9856003 * n, 360);\n\n        /* Ecliptic longitude of the sun */\n        auto lbd = l + 1.915 * std::sin(get_radians(g)) + 0.01997 * std::sin(get_radians(2*g));\n\n\n        /* 2. Equatorial coordinates of the sun */\n\n        /* Ecliptic */\n        auto eps = 23.439 - 0.0000004 * n;\n\n        /* Right ascension */\n        auto alpha = get_degrees(std::atan(std::cos(get_radians(eps)) * std::tan(get_radians(lbd))));\n        if (std::cos(get_radians(lbd)) < 0) {\n            alpha += 180;\n        }\n\n        /* Declination */\n        auto delta = get_degrees(std::asin(std::sin(get_radians(eps)) * std::sin(get_radians(lbd))));\n\n\n        /* 3. Horizontal coordinates of the sun */\n\n        ptime time_(time.date(), boost::posix_time::time_duration(0, 0, 0));\n        auto t0 = (get_julian_day(time_) - 2451545) / 36525;\n\n        /* Median sidereal time */\n        auto theta_hg = std::fmod(\n            6.697376 + 2400.05134 * t0 + 1.002738 * (time.time_of_day().hours() + time.time_of_day().minutes() / 60.0),\n            24\n        );\n\n        auto theta_g = theta_hg * 15;\n        auto theta = theta_g + longitude;\n\n        /* Hour angle of the sun */\n        auto tau = theta - alpha;\n\n        /* Elevation angle */\n        auto h = std::cos(get_radians(delta)) * std::cos(get_radians(tau)) * std::cos(get_radians(latitude));\n        h += std::sin(get_radians(delta)) * std::sin(get_radians(latitude));\n        h = get_degrees(std::asin(h));\n\n        sunlight_t angle = {\n            time    : time,\n            angle   : h > 0 ? h : 0\n        };\n        return angle;\n    }\n\n}}\n", "meta": {"hexsha": "628617328a4e9580a36d2d1f84c74a3954f0262c", "size": 13913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hems/common/types.cpp", "max_stars_repo_name": "adrianghc/HEMS", "max_stars_repo_head_hexsha": "94ffd85a050211efc6ef785b873ee39e906a8b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-06-05T22:32:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T11:05:13.000Z", "max_issues_repo_path": "src/hems/common/types.cpp", "max_issues_repo_name": "adrianghc/HEMS", "max_issues_repo_head_hexsha": "94ffd85a050211efc6ef785b873ee39e906a8b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-06-06T10:23:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-06T10:42:24.000Z", "max_forks_repo_path": "src/hems/common/types.cpp", "max_forks_repo_name": "adrianghc/HEMS", "max_forks_repo_head_hexsha": "94ffd85a050211efc6ef785b873ee39e906a8b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-25T13:20:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T13:20:34.000Z", "avg_line_length": 34.523573201, "max_line_length": 126, "alphanum_fraction": 0.5182922447, "num_tokens": 3368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2393493473227117, "lm_q2_score": 0.028007521417299727, "lm_q1q2_score": 0.006703581971357559}}
{"text": "/**\n* This file is part of Intrinsic3D.\n*\n* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n* Copyright (c) 2019, Technical University of Munich. 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*    * 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 <nv/mesh/util.h>\n\n#include <iostream>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n\n\nnamespace nv\n{\nnamespace MeshUtil\n{\n\n    void removeLooseComponents(Mesh* mesh)\n    {\n        const std::vector<Vec3f> &verts = mesh->vertices;\n        std::vector<Vec3i> &face_indices = mesh->face_vertices;\n        size_t num_faces = face_indices.size();\n\n        // collapse vertices that have the same 3D location and store their connected faces\n        typedef boost::tuple<float, float, float> vec3;\n        std::map<vec3, std::vector<size_t> > verts_collapsed;\n        for (size_t i = 0; i < num_faces; ++i)\n        {\n            for (size_t j = 0; j < 3; ++j)\n            {\n                Vec3f v = verts[face_indices[i][j]];\n                vec3 p = boost::tuples::make_tuple(v[0], v[1], v[2]);\n                verts_collapsed[p].push_back(i);\n            }\n        }\n\n        // build graph\n        typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS> Graph;\n        Graph G;\n        for (std::map<vec3, std::vector<size_t> >::iterator itr = verts_collapsed.begin(); itr != verts_collapsed.end(); ++itr)\n        {\n            std::vector<size_t> &face_list = itr->second;\n            for (size_t j = 0; j < face_list.size(); ++j)\n            {\n                boost::add_edge(face_list[j], face_list[(j + 1) % face_list.size()], G);\n            }\n        }\n\n        // compute connected components\n        std::vector<int> components(boost::num_vertices(G));\n        int num_components = boost::connected_components(G, &components[0]);\n        std::vector<int> component_sizes;\n        component_sizes.resize(num_components, 0);\n        //std::cout << \"Total number of components: \" << numComponents << std::endl;\n        for (size_t i = 0; i != components.size(); ++i)\n            component_sizes[components[i]]++;\n        size_t largest = std::max_element(component_sizes.begin(), component_sizes.end()) - component_sizes.begin();\n        //std::cout << \"largest is \" << largest << \" with \" << component_sizes[largest] << \" out of \" << num_faces << \" triangles\" << std::endl;\n\n        // store old face indices and clear output\n        std::vector<Vec3i> face_indices_old(face_indices);\n        face_indices.clear();\n\n        // only add faces from largest component to new output faces\n        for (int i = 0; i < num_faces; ++i)\n            if (components[i] == largest)\n                face_indices.push_back(face_indices_old[i]);\n        //std::cout << \"triangles before: \" << face_indices_old.size() << \"; triangles after: \" << face_indices.size() << std::endl;\n\n        // remove unused vertices\n        removeUnusedVertices(mesh);\n    }\n\n\n    void removeUnusedVertices(Mesh* mesh)\n    {\n        std::vector<Vec3f> &verts = mesh->vertices;\n        std::vector<Vec3b> &colors = mesh->colors;\n        std::vector<Vec3i> &face_indices = mesh->face_vertices;\n        bool has_colors = !colors.empty();\n        //std::cout << \"Vertices before removing unused: \" << verts.size() << std::endl;\n\n        // detect used vertices\n        std::vector<bool> verts_used;\n        verts_used.resize(verts.size(), false);\n        for (size_t i = 0; i < face_indices.size(); i++)\n        {\n            for (size_t t = 0; t < 3; ++t)\n            {\n                unsigned int v_idx = static_cast<unsigned int>(face_indices[i][t]);\n                verts_used[v_idx] = true;\n            }\n        }\n\n        // count unused vertices\n        size_t num_unused = 0;\n        for (size_t i = 0; i < verts_used.size(); ++i)\n            if (!verts_used[i])\n                ++num_unused;\n        //std::cout << \"Unused vertices: \" << num_unused << std::endl;\n        if (num_unused == 0)\n            return;\n\n        // remove unused vertices\n        std::vector<Vec3f> verts_new;\n        std::vector<Vec3b> colors_new;\n        unsigned int idx = 0;\n        std::vector<unsigned int> vert_indices;\n        vert_indices.resize(verts.size());\n        for (size_t i = 0; i < verts.size(); ++i)\n        {\n            if (verts_used[i])\n            {\n                verts_new.push_back(verts[i]);\n                if (has_colors)\n                    colors_new.push_back(colors[i]);\n                vert_indices[i] = idx;\n                ++idx;\n            }\n        }\n        // set updated vertices\n        mesh->vertices.clear();\n        mesh->colors.clear();\n        for (size_t i = 0; i < verts_new.size(); ++i)\n        {\n            mesh->vertices.push_back(verts_new[i]);\n            if (has_colors)\n                mesh->colors.push_back(colors_new[i]);\n        }\n\n        // update face indices (indices may have shifted)\n        for (size_t i = 0; i < face_indices.size(); ++i)\n        {\n            for (size_t t = 0; t < 3; ++t)\n            {\n                unsigned int vIdx = static_cast<unsigned int>(face_indices[i][t]);\n                face_indices[i][t] = vert_indices[vIdx];\n            }\n        }\n\n        //std::cout << \"Vertices after removing unused: \" << mesh->vertices.size() << std::endl;\n    }\n\n\n    bool removeDegenerateFaces(Mesh* mesh)\n    {\n        if (!mesh)\n            return false;\n\n        // remove degenerate faces\n        const std::vector<Vec3f> &verts = mesh->vertices;\n        std::vector<Vec3i> faces = mesh->face_vertices;\n        mesh->face_vertices.clear();\n        for (size_t i = 0; i < faces.size(); ++i)\n        {\n            int v0 = faces[i][0];\n            int v1 = faces[i][1];\n            int v2 = faces[i][2];\n            // check if two vertices have the same indices\n            if ((v0 == v1) || (v0 == v2) || (v1 == v2))\n                continue;\n            // check if triangle area is zero\n            Vec3f e0 = verts[v2] - verts[v0];\n            Vec3f e1 = verts[v2] - verts[v1];\n            double area = static_cast<double>((e0.cross(e1)).norm());\n            if (area == 0.0 || std::isnan(area) || std::isinf(area))\n                continue;\n            mesh->face_vertices.push_back(Vec3i(v0, v1, v2));\n        }\n        return true;\n    }\n\n} // namespace MeshUtil\n} // namespace nv\n", "meta": {"hexsha": "07bd82458334774d6a2c5c7fdbe82fad8a7546b2", "size": 7850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libintrinsic3d/src/mesh/util.cpp", "max_stars_repo_name": "dazinovic/intrinsic3d", "max_stars_repo_head_hexsha": "4e5ea3b3d81b4174f33765e1d3dd0b24c2716c06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 370.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T23:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T12:40:03.000Z", "max_issues_repo_path": "libintrinsic3d/src/mesh/util.cpp", "max_issues_repo_name": "jtpils/intrinsic3d", "max_issues_repo_head_hexsha": "3f94bc59dba6d77981aad1c8f38531706e51078f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2019-02-13T10:15:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T10:22:47.000Z", "max_forks_repo_path": "libintrinsic3d/src/mesh/util.cpp", "max_forks_repo_name": "jtpils/intrinsic3d", "max_forks_repo_head_hexsha": "3f94bc59dba6d77981aad1c8f38531706e51078f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2019-02-28T06:19:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:06:35.000Z", "avg_line_length": 38.4803921569, "max_line_length": 144, "alphanum_fraction": 0.5877707006, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.018264277516894006, "lm_q1q2_score": 0.006695496679032926}}
{"text": "#ifndef KA_PARSE_HPP\n#define KA_PARSE_HPP\n#pragma once\n\n#include \"macroregular.hpp\"\n#include \"utility.hpp\"\n#include \"typetraits.hpp\"\n#include \"indexed.hpp\"\n#include \"opt.hpp\"\n#include \"functional.hpp\"\n#include \"zero.hpp\"\n#include \"functor.hpp\"\n\n#include <boost/variant/variant.hpp>\n#include <boost/variant/get.hpp>\n#include <boost/variant/apply_visitor.hpp>\n\n#include <vector>\n#include <utility>\n#include <initializer_list>\n\nnamespace ka {\nnamespace parse {\n/// Semantics is provided through 'meaning' expressions, of the form\n/// 'meaning(<C++ construct>) = <denotation>'. A denotation is an entity that is\n/// the *interpretation* of a C++ construct.\n///\n/// See formal specification `spec:/sbre/framework/2020/d`.\n\n/// The result of some parsing operation.\n///\n/// It is an optional parsed element (if parsing succeeded), paired with the\n/// string that remains to parse. Two sets are therefore involved: the\n/// \"parsed set\" and the \"symbol set\" (aka \"character set\").\n///\n/// meaning(std::iterator_traits<I>::value_type) = C\n///   C is the 'character' or 'symbol' set, whom strings are parsed.\n///\n/// meaning(pair<res_t<A, I>, I>) = R(A, C)\n///   `res_t` contains only the iterator until the parser succeeded to parse.\n///   Therefore, the *string* C^* that remains to parse is represented by the\n///   bounded range whose `res_t`'s iterator is the beginning and the end\n///   iterator is known from the context.\n///\n/// ForwardIterator I\ntemplate<typename A, typename I>\nstruct res_t {\n  using value_type = A;\n  using iterator_type = I;\n\n  opt_t<A> value;\n  I iter;\n\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_2(res_t, value, iter)\n\n// Readable:\n  auto operator*() const& noexcept -> decltype(*value) {\n    return *value;\n  }\n\n// Mutable:\n  auto operator*() & noexcept -> decltype(*value) {\n    return *value;\n  }\n  auto operator*() && noexcept -> decltype(*mv(value)) {\n    return *mv(value);\n  }\n\n// EmptyMutable:\n  constexpr\n  auto empty() const noexcept -> bool {\n    return value.empty();\n  }\n\n  template<typename F, typename V>\n  using ValueOfResultOfFmap = typename Decay<CodomainFor<fmap_fn_t, F, V>>::value_type;\n\n// Functor:\n  /// Function<U (A)> F\n  template<typename F>\n  auto fmap(F&& f) const&\n    -> res_t<ValueOfResultOfFmap<F, const opt_t<A>&>, I> {\n    return { ka::fmap(fwd<F>(f), value), iter };\n  }\n\n  /// Function<U (A)> F\n  template<typename F>\n  auto fmap(F&& f) &&\n    -> res_t<ValueOfResultOfFmap<F, opt_t<A>&&>, I> {\n    return { ka::fmap(fwd<F>(f), mv(value)), mv(iter) };\n  }\n};\n\n/// Convenience function to construct a result in success, deducing argument types.\n///\n/// meaning(ok(a, i)) = (a, s), where s = meaning(pair{i, end})\nstruct ok_fn_t {\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_0(ok_fn_t)\n// Function:\n  /// ForwardIterator I\n  template<typename A, typename I> constexpr\n  auto operator()(A&& a, I&& i) const noexcept -> res_t<Decay<A>, Decay<I>> {\n    return {ka::opt(fwd<A>(a)), fwd<I>(i)};\n  }\n};\n\nstatic constexpr auto const& ok = static_const_t<ok_fn_t>::value;\n\n/// Convenience function to construct a result in error, deducing argument types.\n///\n/// meaning(err(t, i)) = (none, s), where s = meaning(pair{i, end})\n///\n/// ForwardIterator I\nstruct err_fn_t {\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_0(err_fn_t)\n// Function:\n  template<typename A, typename I> constexpr\n  auto operator()(type_t<A>, I i) const noexcept -> res_t<A, I> {\n    return {opt_t<A>{}, mv(i)};\n  }\n};\n\nstatic constexpr auto const& err = static_const_t<err_fn_t>::value;\n\n/// Convenience function to construct a result, deducing argument types.\n///\n/// meaning(res(a, i)) = (a, s), where s = meaning(pair{i, end})\n///\n/// ForwardIterator I\ntemplate<typename A, typename I> constexpr\nauto res(opt_t<A> opt_val, I i) noexcept -> res_t<A, I> {\n  return {mv(opt_val), mv(i)};\n}\n\n/// The result iterator up to which the parsing was successful.\n///\n/// meaning(iter(res(a, i))) = s, where s = meaning(pair{i, end})\n///\n/// ForwardIterator I\ntemplate<typename A, typename I> constexpr\nauto iter(res_t<A, I> const& r) noexcept -> I const& {\n  return r.iter;\n}\n\n/// Overload for non-const references.\ntemplate<typename A, typename I> constexpr\nauto iter(res_t<A, I>& r) noexcept -> I& {\n  return r.iter;\n}\n\n/// Overload for rvalue-references.\ntemplate<typename A, typename I> constexpr\nauto iter(res_t<A, I>&& r) noexcept -> I {\n  return mv(r.iter);\n}\n\n/// The optional value of the result.\n///\n/// invariant: ka::empty(r) == ka::empty(to_opt(r))\n///         && ka::src(r) == ka::src(to_opt(r))\n///\n/// meaning(to_opt)(a, s) = a\n///\n/// ForwardIterator I\ntemplate<typename A, typename I> constexpr\nauto to_opt(res_t<A, I> const& r) noexcept -> ka::opt_t<A> const& {\n  return r.value;\n}\n\n/// Overload for non-const references.\ntemplate<typename A, typename I> constexpr\nauto to_opt(res_t<A, I>& r) noexcept -> ka::opt_t<A>& {\n  return r.value;\n}\n\n/// Overload for rvalue-references.\ntemplate<typename A, typename I> constexpr\nauto to_opt(res_t<A, I>&& r) noexcept -> ka::opt_t<A> {\n  return mv(r.value);\n}\n\n/// Derives the implementation of the functor part of a parser type.\n#define KA_PARSER_DERIVE_FUNCTOR()                                 \\\n  /* Procedure<B (A)> PDFF */                                      \\\n  template<typename PDFF> constexpr                                \\\n  auto fmap(PDFF&& f) const & noexcept                             \\\n    -> ka::parse::fmapped_t<Decay<PDFF>, Decay<decltype(*this)>> { \\\n    return { fwd<PDFF>(f), *this };                                \\\n  }                                                                \\\n  template<typename PDFF>                                          \\\n  auto fmap(PDFF&& f) && noexcept                                  \\\n    -> ka::parse::fmapped_t<Decay<PDFF>, Decay<decltype(*this)>> { \\\n    return { fwd<PDFF>(f), std::move(*this) };                     \\\n  }\n\n/// meaning(ResultOf<PA, I>) = R(A, C^*), where C = meaning(I::value_type)\n///\n/// Parser<A> PA\n/// ForwardIterator I\ntemplate<typename PA, typename I>\nusing ResultOf = Decay<CodomainFor<PA, I, I>>;\n\n/// meaning(ValueOf<PA, I>) = A\n///\n/// Parser<A> PA\n/// ForwardIterator I\ntemplate<typename PA, typename I>\nusing ValueOf = typename ResultOf<PA, I>::value_type;\n\n/// Mapping of a procedure through the parser functor.\n///\n/// I.e. new parser whose result is obtained by mapping the function to the\n/// original parser's result.\n///\n/// meaning(fmap) = P: B^A → (PB)^(PA) // function-part of the functor\n///\n/// Procedure<B (A)> F\n/// Parser PA\ntemplate<typename F, typename PA>\nstruct fmapped_t {\n  F f;\n  PA pa;\n\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_2(fmapped_t, f, pa)\n\n// Functor (up to isomorphism):\n  KA_PARSER_DERIVE_FUNCTOR()\n\n// Parser<A>:\n  /// @pre readable_bounded_range(b, e)\n  template<typename I> constexpr\n  auto operator()(I b, I e) const -> decltype(pa(b, e).fmap(f)) {\n    // Workaround MSVC:\n    // Using `ka::fmap()` does not instantiate the right `fmap_dispatch` function.\n    // This seems to be a compiler bug.\n    return pa(b, e).fmap(f);\n  }\n};\n\n/// Parser of a single element.\n///\n/// meaning(symbol_t<I>) = PC, where C = meaning(I::value_type)\n/// (C is the 'character' or 'symbol' set)\nstruct symbol_t {\n  template<typename I>\n  using Value = typename std::iterator_traits<I>::value_type;\n\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_0(symbol_t)\n\n// Functor (up to isomorphism):\n  KA_PARSER_DERIVE_FUNCTOR()\n\n// Parser<C>:\n  /// @pre readable_bounded_range(b, e)\n  template<typename I> constexpr\n  auto operator()(I b, I e) const -> res_t<Value<I>, I> {\n    return (b == e) ? err(type_t<Value<I>>{}, b) : ok(*b, std::next(b));\n  }\n};\n\nstatic constexpr auto const& symbol = static_const_t<symbol_t>::value;\n\n/// Combines multiple parsers into one, which returns the product of all results.\n/// Succeeds if all parsers succeed.\n///\n/// meaning(product_t) = ⊗\n///\n/// Parser<A>... PA\ntemplate<typename... PA>\nstruct product_t {\n  ka::product_t<PA...> pa;\n\n  template<typename I>\n  using Value = ka::product_t<ValueOf<PA, I>...>;\n\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_1(product_t, pa)\n\n// Functor (up to isomorphism):\n  KA_PARSER_DERIVE_FUNCTOR()\n\n// Parser<ka::product_t<A...>>:\n  /// @pre readable_bounded_range(b, e)\n  template<typename I>\n  auto operator()(I b, I e) const -> res_t<Value<I>, I> {\n    return impl(index_sequence_for<PA...>{}, b, e);\n  }\n\nprivate:\n  template<std::size_t Idx, typename I>\n  auto do_one_at(ka::product_t<opt_t<ResultOf<PA, I>>...>& res, I b, I e) const\n    -> std::pair<bool, I> {\n    auto& opt_res_at = std::get<Idx>(res);\n    opt_res_at.emplace_front(std::get<Idx>(pa)(b, e));\n    auto& res_at = opt_res_at.front();\n    return { !res_at.empty(), iter(res_at) };\n  }\n\n  template<std::size_t... Idx, typename I>\n  auto impl(index_sequence<Idx...>, I b, I e) const -> res_t<Value<I>, I> {\n    auto success = true;\n    auto it = b;\n    auto opt_res = ka::product_t<opt_t<ResultOf<PA, I>>...>{};\n    // The following use of `std::initializer_list` is a C++11 hack to\n    // repeatedly apply a function on arguments of heterogeneous types, avoiding\n    // function recursion.\n    // TODO: Factorize in a named function, and replace in C++17 or above.\n\n    // Ignore unused variables (happens with product_t<>).\n    (void) e; (void) opt_res;\n    (void) std::initializer_list<bool>{ (\n      success = success && (\n          std::tie(success, it) = do_one_at<Idx>(opt_res, it, e),\n          success\n        )\n      )... };\n\n    if (!success) {\n      return err(type_t<Value<I>>{}, b);\n    }\n\n    auto values = ka::product(mv(**std::get<Idx>(opt_res))...);\n    return ok(mv(values), it);\n  }\n};\n\n/// Constructs a product of parsers, performing argument type deduction.\n///\n/// Parser<A>... PA\nstruct product_fn_t {\n  template<typename... PA> constexpr\n  auto operator()(PA&&... pa) const noexcept -> product_t<Decay<PA>...> {\n    return { ka::product(fwd<PA>(pa)...) };\n  }\n};\nstatic constexpr auto const& product = static_const_t<product_fn_t>::value;\n\n/// Parser that always succeeds, returning unit and the string as-is.\n///\n/// meaning(unit_t) = 1\nusing unit_t = product_t<>;\nstatic constexpr auto const& unit = static_const_t<unit_t>::value;\n\nnamespace detail {\n  // `product_t` is `parse::product_t`, by opposition to `ka::product_t` (tuple\n  // construction).\n  template<typename PA> constexpr\n  auto unwrap_product(PA&& pa) noexcept -> ka::product_t<PA&&> {\n    return ka::product_t<PA&&>{ fwd<PA>(pa) };\n  }\n\n  template<typename... PA> constexpr\n  auto unwrap_product(product_t<PA...> const& prod) noexcept ->\n  ka::product_t<PA...> const& {\n    return prod.pa;\n  }\n\n  template<typename... PA> constexpr\n  auto unwrap_product(product_t<PA...>&& prod) noexcept -> ka::product_t<PA...>&& {\n    return mv(prod.pa);\n  }\n\n  constexpr\n  auto unwrap_product(product_t<> prod) noexcept -> ka::product_t<> {\n    return {};\n  }\n} // namespace detail\n\n/// Constructs a product of parsers, flattening any product of product in the\n/// result and performing argument type deduction.\n///\n/// Parser<A>... PA\ntemplate<typename... PA> constexpr\nauto flat_product(PA&&... pa) noexcept\n  -> decltype(apply(product, std::tuple_cat(detail::unwrap_product(fwd<PA>(pa))...))) {\n  return apply(product, std::tuple_cat(detail::unwrap_product(fwd<PA>(pa))...));\n}\n\n/// Convenience type for the value type of the result of a sum of parsers.\ntemplate<typename... A>\nusing SumValue = ApplyIndexed<boost::variant, A...>;\n\n/// Combines multiple parsers into one, which returns the result of the first\n/// parser that succeeds, in the order of declaration. Succeeds if any parser\n/// succeeds.\n///\n/// meaning(sum_t) = ⊕\n///\n/// Parser<A>... PA\ntemplate<typename... PA>\nstruct sum_t {\n  ka::product_t<PA...> pa;\n\n  template<typename I>\n  using Value = SumValue<ValueOf<PA, I>...>;\n\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_1(sum_t, pa)\n\n// Functor (up to isomorphism):\n  KA_PARSER_DERIVE_FUNCTOR()\n\n// Parser<SumValue<A>>:\n  /// @pre readable_bounded_range(b, e)\n  template<typename I>\n  auto operator()(I b, I e) const -> res_t<Value<I>, I> {\n    return impl(index_sequence_for<PA...>{}, b, e);\n  }\n\nprivate:\n  template<std::size_t Idx, typename I>\n  auto do_one_at(opt_t<Value<I>>& opt_val, I b, I e) const -> std::pair<bool, I> {\n    auto res = std::get<Idx>(pa)(b, e);\n    auto const ok = !res.empty();\n    if (ok) {\n      opt_val.emplace_front(indexed<Idx>(*mv(res)));\n    }\n    // Ok to use `res` here even after move, since we're not accessing the moved\n    // part.\n    return { ok, iter(res) };\n  }\n\n  template<std::size_t... Idx, typename I>\n  auto impl(index_sequence<Idx...>, I b, I e) const -> res_t<Value<I>, I> {\n    auto success = false;\n    auto it = b;\n    auto opt_val = opt_t<Value<I>>{};\n\n    // The following use of `std::initializer_list` is a C++11 hack to\n    // repeatedly apply a function on arguments of heterogeneous types, avoiding\n    // function recursion.\n    // TODO: Factorize in a named function, and replace in C++17 or above.\n    (void) std::initializer_list<bool>{(\n      success = success || (\n          std::tie(success, it) = do_one_at<Idx>(opt_val, it, e),\n          success\n        )\n      )...};\n\n    if (!success) {\n      return err(type_t<Value<I>>{}, b);\n    }\n    assert(!opt_val.empty());\n    return ok(*mv(opt_val), it);\n  }\n};\n\n/// Parser that always fails to return an element of the empty set 0 (since\n/// there's none).\n///\n/// meaning(sum_t<>) = 0\n// TODO: Remove this specialization when having a `ka::sum_t` type that can be empty.\ntemplate<>\nstruct sum_t<> {\n  using Value = ka::zero_t;\n  ka::product_t<> pa;\n\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_0(sum_t)\n\n// Functor (up to isomorphism):\n  KA_PARSER_DERIVE_FUNCTOR()\n\n// Parser<>:\n  /// @pre readable_bounded_range(b, e)\n  template<typename I> constexpr\n  auto operator()(I b, I) const noexcept -> res_t<Value, I> {\n    return err(type_t<Value>{}, b);\n  }\n};\nusing zero_t = sum_t<>;\nstatic constexpr auto const& zero = static_const_t<zero_t>::value;\n\n/// Constructs a sum of parsers, performing argument type deduction.\n///\n/// Parser<A>... PA\nstruct sum_fn_t {\n  template<typename... PA> constexpr\n  auto operator()(PA&&... pa) const noexcept -> sum_t<Decay<PA>...> {\n    return { ka::product(fwd<PA>(pa)...) };\n  }\n};\nstatic constexpr auto const& sum = static_const_t<sum_fn_t>::value;\n\nnamespace detail {\n  template<typename PA> constexpr\n  auto unwrap_sum(PA&& pa) noexcept -> ka::product_t<PA&&> {\n    return ka::product_t<PA&&>{ fwd<PA>(pa) };\n  }\n\n  template<typename... PA> constexpr\n  auto unwrap_sum(sum_t<PA...> const& s) noexcept -> ka::product_t<PA...> const& {\n    return s.pa;\n  }\n\n  template<typename... PA> constexpr\n  auto unwrap_sum(sum_t<PA...>&& s) noexcept -> ka::product_t<PA...>&& {\n    return mv(s.pa);\n  }\n} // namespace detail\n\n/// Constructs a sum of parsers, flattening any sum of sum in the result and\n/// performing argument type deduction.\n///\n/// Parser<A>... PA\ntemplate<typename... PA> constexpr\nauto flat_sum(PA&&... pa) noexcept\n  -> decltype(apply(sum, std::tuple_cat(detail::unwrap_sum(fwd<PA>(pa))...))) {\n  return apply(sum, std::tuple_cat(detail::unwrap_sum(fwd<PA>(pa))...));\n}\n\nnamespace detail {\n  /// Visitor for `boost::variant` that contains either `indexed_t<T>` or\n  /// indexed_t<ka::unit_t>` and converts it into an `opt_t<T>`.\n  struct to_opt_t {\n    template<typename V, typename... A>\n    struct visitor_t : boost::static_visitor<opt_t<V>> {\n      template<std::size_t I, typename U>\n      auto operator()(indexed_t<I, U> const& u) const -> ka::opt_t<V> {\n        return ka::opt(V(src(u)));\n      }\n      template<std::size_t I>\n      auto operator()(indexed_t<I, ka::unit_t>) const -> ka::opt_t<V> {\n        return {};\n      }\n    };\n\n    template<typename A> constexpr\n    auto operator()(boost::variant<indexed_t<0, A>, indexed_t<1, ka::unit_t>> const& v) const\n      -> opt_t<A> {\n      return boost::apply_visitor(visitor_t<A>{}, v);\n    }\n  };\n} // namespace detail\n\n/// Convenience function to construct a parser of optional that always succeeds,\n/// producing an optional value.\n///\n/// meaning(opt(pa)) = pa ⊕ 1\n///\n/// Parser<A> PA\ntemplate<typename PA> constexpr\nauto opt(PA&& pa) noexcept\n  -> decltype(sum(pa, unit).fmap(detail::to_opt_t{})) {\n  return sum(pa, unit).fmap(detail::to_opt_t{});\n}\n\n/// Parser that applies another one between min and max times (included). Its\n/// result is a list of `A` containing between min and max (included) elements.\n///\n/// meaning(quantify_t) = quantify\n///\n/// Parser<A> PA\ntemplate<typename PA>\nstruct quantify_t {\n  PA pa;\n  std::size_t min;\n  ka::opt_t<std::size_t> max; // Precondition: max.empty() || min <= src(max)\n\n  template<typename I>\n  using Value = std::vector<ValueOf<PA, I>>;\n\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_3(quantify_t, pa, min, max)\n\n// Functor (up to isomorphism):\n  KA_PARSER_DERIVE_FUNCTOR()\n\n// Parser<std::vector<A>>:\n  /// @pre readable_bounded_range(b, e)\n  template<typename I>\n  auto operator()(I b, I e) const -> res_t<Value<I>, I> {\n    auto b0 = b;\n    auto values = Value<I>{};\n    if (max.empty()) {\n      while (parse_one(pa, b, e, values)); // unbounded\n    } else {\n      auto const m = src(max);\n      for (std::size_t i = 0; i != m && parse_one(pa, b, e, values); ++i);\n    }\n    return min <= values.size()\n      ? ok(mv(values), mv(b))\n      : err(type_t<Value<I>>{}, mv(b0));\n  }\nprivate:\n  template<typename I, typename V> static\n  auto parse_one(PA const& pa, I& b, I const& e, V& values) -> bool {\n    auto res = pa(b, e);\n    if (res.empty()) return false;\n    b = iter(res);\n    values.push_back(*mv(res));\n    return true;\n  }\n};\n\n/// Constructs a quantified parser, performing argument type deduction.\n/// Omitting or passing an empty maximum means there is no upper bound.\nstruct quantify_fn_t {\n// Regular:\n  KA_GENERATE_FRIEND_REGULAR_OPS_0(quantify_fn_t)\n// Function:\n  /// Precondition: max.empty() || min <= src(max)\n  /// Parser<A> PA\n  template<typename PA>\n  auto operator()(PA&& pa, std::size_t min, ka::opt_t<std::size_t> max) const noexcept -> quantify_t<Decay<PA>> {\n    return {fwd<PA>(pa), min, mv(max)};\n  }\n  /// Precondition: min <= max\n  /// Parser<A> PA\n  template<typename PA>\n  auto operator()(PA&& pa, std::size_t min, std::size_t max) const noexcept -> quantify_t<Decay<PA>> {\n    return {fwd<PA>(pa), min, ka::opt(max)};\n  }\n  /// Parser<A> PA\n  template<typename PA>\n  auto operator()(PA&& pa, std::size_t min) const noexcept -> quantify_t<Decay<PA>> {\n    return {fwd<PA>(pa), min, ka::opt_t<std::size_t>{}};\n  }\n};\n\nstatic constexpr auto const& quantify = static_const_t<quantify_fn_t>::value;\n\n/// Parser that applies another one as much as possible and always succeeds. Its\n/// result is a list of `A`.\n///\n/// meaning(list) = ^* = quantify(_, 0, ∞)\n///\n/// Parser<A> PA\ntemplate<typename PA> constexpr\nauto list(PA&& pa) noexcept -> quantify_t<Decay<PA>> {\n  return quantify(fwd<PA>(pa), 0);\n}\n\nnamespace detail {\n  template<typename PA> constexpr\n  auto unwrap_quantify(PA&& pa) noexcept -> PA&& {\n    return fwd<PA>(pa);\n  }\n\n  template<typename PA> constexpr\n  auto unwrap_quantify(quantify_t<PA> const& l) noexcept -> PA const& {\n    return l.pa;\n  }\n\n  template<typename PA> constexpr\n  auto unwrap_quantify(quantify_t<PA>&& l) noexcept -> PA&& {\n    return mv(l.pa);\n  }\n} // namespace detail\n\n/// Constructs a list of a parser, flattening the result if the argument is\n/// already a list and performing argument type deduction.\n///\n/// Parser<A> PA\ntemplate<typename PA> constexpr\nauto flat_list(PA&& pa) noexcept\n  -> decltype(list(detail::unwrap_quantify(fwd<PA>(pa)))) {\n  return list(detail::unwrap_quantify(fwd<PA>(pa)));\n}\n\n// TODO: Complete list monoid with concatenation and empty list.\n// TODO: Add literal, filter and bounded quantification parsers (see\n//  `spec:/sbre/framework/2020/d`)\n\nnamespace ops {\n  /// Operator for flat product of parsers.\n  ///\n  /// Parser<A> PA\n  /// Parser<B> PB\n  template<typename PA, typename PB> constexpr\n  auto operator*(PA&& pa, PB&& pb) noexcept\n    -> decltype(flat_product(fwd<PA>(pa), fwd<PB>(pb))) {\n    return flat_product(fwd<PA>(pa), fwd<PB>(pb));\n  }\n\n  /// Operator for flat sum of parsers.\n  ///\n  /// Parser<A> PA\n  /// Parser<B> PB\n  template<typename PA, typename PB> constexpr\n  auto operator+(PA&& pa, PB&& pb) noexcept\n    -> decltype(flat_sum(fwd<PA>(pa), fwd<PB>(pb))) {\n    return flat_sum(fwd<PA>(pa), fwd<PB>(pb));\n  }\n\n  /// Operator for flat list (repetition) of parsers.\n  ///\n  /// Parser<A> PA\n  /// Parser<B> PB\n  template<typename PA> constexpr\n  auto operator*(PA&& pa) noexcept\n    -> decltype(flat_list(fwd<PA>(pa))) {\n    return flat_list(fwd<PA>(pa));\n  }\n} // namespace ops\n\n} // namespace parse\n} // namespace ka\n\n#endif // KA_PARSE_HPP\n", "meta": {"hexsha": "d593ecd168582c72172e7168afcf716a527f8c8b", "size": 20764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ka/parse.hpp", "max_stars_repo_name": "arntanguy/libqi", "max_stars_repo_head_hexsha": "7f3e1394cb26126b26fa7ff54d2de1371a1c9f96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:05:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T16:47:47.000Z", "max_issues_repo_path": "ka/parse.hpp", "max_issues_repo_name": "arntanguy/libqi", "max_issues_repo_head_hexsha": "7f3e1394cb26126b26fa7ff54d2de1371a1c9f96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2015-04-06T21:41:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T13:24:51.000Z", "max_forks_repo_path": "ka/parse.hpp", "max_forks_repo_name": "arntanguy/libqi", "max_forks_repo_head_hexsha": "7f3e1394cb26126b26fa7ff54d2de1371a1c9f96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T20:01:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T13:31:20.000Z", "avg_line_length": 29.4107648725, "max_line_length": 113, "alphanum_fraction": 0.6413022539, "num_tokens": 5714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.02716923153568105, "lm_q1q2_score": 0.006658771467718838}}
{"text": "#include \"Quad.h\"\n#include <memory>\n#include <cassert>\n#include <iostream>\n#include \"ofVboMesh.h\"\n#include <exception>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\nusing namespace ofx;\n\n// Convert two vertex indices into edge key by returning pair of\n// vertex indices where first index in pair is greater than second.\nEdgeKey makeEdgeKey(VertexID v0, VertexID v1)\n{\n    if (v0 == -1 || v1 == -1) {\n        return {-1, -1};\n    }\n\n    if (v0 > v1) {\n        auto temp = v0;\n        v0 = v1;\n        v1 = temp;\n    }\n\n    return {v0, v1};\n}\n\nQuad::Quad() : _redrawMesh(true)\n{\n\n}\n\nQuad::Quad(string objFilename) : _redrawMesh(true)\n{\n    load(objFilename);\n}\n\n// Load mesh data from OBJ file.\n// Mesh in OBJ file is restricted to 4 sided polygons.\nvoid Quad::load(std::string objFilename)\n{\n    ifstream input(\"./bin/\" + objFilename);\n\n    vector<VertexID> vertexIDs;\n\n    string line;\n    vector<string> tokens;\n    while (getline(input, line)) {\n        tokens.clear();\n        boost::split(tokens, line, boost::is_any_of(\" \"));\n        if (tokens.size() == 4 && tokens[0] == \"v\") {\n            auto vID = addVertex({stof(tokens[1]), stof(tokens[2]), stof(tokens[3])});\n            vertexIDs.push_back(vID);\n        }\n        else if (tokens.size() == 5 && tokens[0] == \"f\") {\n            auto v0 = vertexIDs[stoi(tokens[1]) - 1];\n            auto v1 = vertexIDs[stoi(tokens[2]) - 1];\n            auto v2 = vertexIDs[stoi(tokens[3]) - 1];\n            auto v3 = vertexIDs[stoi(tokens[4]) - 1];\n            addFace(v0, v1, v2, v3);\n        }\n    }\n\n    _redrawMesh = true;\n}\n\n// Given vertex position, add new vertex to mesh\n// and return vertex ID of new vertex\nVertexID Quad::addVertex(ofVec3f vertex)\n{\n    // Initialize normal of vertex to all zeros. This will be calculated later.\n    // Initialize new vertex ID to -1. This is used internally when doing\n    // subdivision surface calculations.\n    _vertices.push_back({vertex, {0.0, 0.0, 0.0}, -1});\n    _redrawMesh = true;\n    return _vertices.size() - 1;\n}\n\n// Given four valid vertex IDs, add new face to mesh\n// and return face ID of new face\nFaceID Quad::addFace(VertexID v0, VertexID v1, VertexID v2, VertexID v3)\n{\n    _edges.push_back({v0, -1, -1, -1, -1});\n    EdgeID edge0 = _edges.size() - 1;\n\n    _edges.push_back({v1, -1, -1, -1, -1});\n    EdgeID edge1 = _edges.size() - 1;\n    \n    _edges.push_back({v2, -1, -1, -1, -1});\n    EdgeID edge2 = _edges.size() - 1;\n    \n    _edges.push_back({v3, -1, -1, -1, -1});\n    EdgeID edge3 = _edges.size() - 1;\n\n    _edges[edge0].next = edge1;\n    _edges[edge1].next = edge2;\n    _edges[edge2].next = edge3;\n    _edges[edge3].next = edge0;\n\n    // function for attaching an edge to an adjacent edge, if exists.\n    // Given two vertex IDs, search for existing edge with those vertices\n    // as endpoints.\n    auto attachEdge = [this](EdgeID edge, VertexID a, VertexID b) {\n        auto neighborEdge = findEdge(a, b);\n        if (neighborEdge == -1) {\n            _edgeMap[makeEdgeKey(a, b)] = edge;\n        }\n        else {\n            _edges[neighborEdge].opposite = edge;\n            _edges[edge].opposite = neighborEdge;\n        }\n    };\n\n    // Attach each edge to an adjacent edge with same endpoints, if it exists\n    attachEdge(edge0, v0, v1);\n    attachEdge(edge1, v1, v2);\n    attachEdge(edge2, v2, v3);\n    attachEdge(edge3, v3, v0);\n\n    _faces.push_back({edge0, edge1, edge2, edge3, -1});\n    FaceID face = _faces.size() - 1;\n\n    _edges[edge0].face = face;\n    _edges[edge1].face = face;\n    _edges[edge2].face = face;\n    _edges[edge3].face = face;\n\n    _redrawMesh = true;\n    return face;\n}\n\n// Draw mesh using either flat shading or smooth shading\nvoid Quad::draw(bool smoothShading)\n{\n    // If mesh has changed, build OpenFrameworks tri mesh out of quad mesh\n    // and draw tri mesh\n    if (_redrawMesh) {\n        _mesh.clear();\n        calculateNormals();\n\n        for (auto &f: _faces) {\n            auto v0 = _vertices[_edges[f.edges[0]].vertex];\n            auto v1 = _vertices[_edges[f.edges[1]].vertex];\n            auto v2 = _vertices[_edges[f.edges[2]].vertex];\n            auto v3 = _vertices[_edges[f.edges[3]].vertex];\n\n            _mesh.addVertex(v0.position);\n            _mesh.addVertex(v1.position);\n            _mesh.addVertex(v2.position);\n\n            _mesh.addVertex(v0.position);\n            _mesh.addVertex(v2.position);\n            _mesh.addVertex(v3.position);\n            \n            if (smoothShading) {\n                _mesh.addNormal(v0.normal);\n                _mesh.addNormal(v1.normal);\n                _mesh.addNormal(v2.normal);\n                _mesh.addNormal(v0.normal);\n                _mesh.addNormal(v2.normal);\n                _mesh.addNormal(v3.normal);\n            } else {\n                _mesh.addNormal(f.normal);\n                _mesh.addNormal(f.normal);\n                _mesh.addNormal(f.normal);\n                _mesh.addNormal(f.normal);\n                _mesh.addNormal(f.normal);\n                _mesh.addNormal(f.normal);\n            }\n        }\n\n        _redrawMesh = false;\n    }\n    _mesh.draw();\n}\n\nvoid Quad::drawWireframe()\n{\n    for (auto &f: _faces) {\n        auto v0 = _vertices[_edges[f.edges[0]].vertex];\n        auto v1 = _vertices[_edges[f.edges[1]].vertex];\n        auto v2 = _vertices[_edges[f.edges[2]].vertex];\n        auto v3 = _vertices[_edges[f.edges[3]].vertex];\n        ofLine(v0.position, v1.position);\n        ofLine(v1.position, v2.position);\n        ofLine(v2.position, v3.position);\n        ofLine(v3.position, v0.position);\n    }\n}\n\nEdgeID Quad::findEdge(VertexID v0, VertexID v1)\n{\n    auto key = makeEdgeKey(v0, v1);\n    auto result = _edgeMap.find(key);\n    if (result == _edgeMap.end()) {\n        return -1;\n    }\n    return result->second;\n}\n\n// Catmull-Clark subdivision surface algorithm\nQuad Quad::subdivide(int level)\n{\n    if (level == 0) {\n        return *this;\n    }\n\n    for (auto &v: _vertices) {\n        v.newVertex = -1;\n    }\n    \n    vector<ofVec3f> newVertices;\n        \n    // Divide existing face into four new faces, using the four existing face\n    // vertices and a new vertex at the center of existing face. Calculate new\n    // vertex in center of existing face by averaging four corner vertices\n    // of face.\n    for (auto &f: _faces) {\n        newVertices.push_back((_vertices[_edges[f.edges[0]].vertex].position +\n                               _vertices[_edges[f.edges[1]].vertex].position +\n                               _vertices[_edges[f.edges[2]].vertex].position +\n                               _vertices[_edges[f.edges[3]].vertex].position) / 4.0f);\n        f.center = newVertices.size() - 1;\n    }\n\n    // Divide existing edge into two new edges, using edge endpoints and new\n    // vertex around the midpoint of edge. Calculate new vertex on existing\n    // edge by averaging the endpoints of edge and the centers of the two\n    // adjacent faces.\n    auto newMidpoint = [this, &newVertices](EdgeID edge, VertexID a, VertexID b) {\n        // Check to see if new midpoint has already been calculated for\n        // opposite edge\n        if (_edges[_edges[edge].opposite].midpoint == -1) {\n            auto newVertex = (_vertices[a].position +\n                              _vertices[b].position +\n                              newVertices[_faces[_edges[edge].face].center] +\n                              newVertices[_faces[_edges[_edges[edge].opposite].face].center]) / 4.0f;\n            newVertices.push_back(newVertex);\n            _edges[edge].midpoint = newVertices.size() - 1;\n            _edges[_edges[edge].opposite].midpoint = newVertices.size() - 1;\n        }\n        else {\n            // We've already calculated the new midpoint vertex for the\n            // opposite edge; no need to calculate again.\n            _edges[edge].midpoint = _edges[_edges[edge].opposite].midpoint;\n        }\n    };\n\n    for (auto &f: _faces) {\n        newMidpoint(f.edges[0], _edges[f.edges[0]].vertex, _edges[f.edges[1]].vertex);\n        newMidpoint(f.edges[1], _edges[f.edges[1]].vertex, _edges[f.edges[2]].vertex);\n        newMidpoint(f.edges[2], _edges[f.edges[2]].vertex, _edges[f.edges[3]].vertex);\n        newMidpoint(f.edges[3], _edges[f.edges[3]].vertex, _edges[f.edges[0]].vertex);\n    }\n\n    // Calculate new position of each existing vertex, using the midpoints of\n    // connected edges, centers of connected faces, and current position.\n    // Valence value is the number of connected edges.\n    auto getNewVertex = [this, &newVertices](EdgeID edge) {\n        int valence = 0;\n        ofVec3f  sumMidpoints = {0.0, 0.0, 0.0};\n        ofVec3f sumCenters = {0.0, 0.0, 0.0};\n\n        // Loop through each connected edge of vertex\n        auto e = _edges[edge].opposite;\n        do {\n            sumMidpoints += (_vertices[_edges[e].vertex].position +\n                             _vertices[_edges[_edges[e].opposite].vertex].position) / 2.0f;\n            sumCenters += newVertices[_faces[_edges[e].face].center];\n            valence++;\n            e = _edges[_edges[e].next].opposite;\n        } while (_edges[e].opposite != edge);\n\n        // Formulate for calculating new vertex position\n        auto newVertex = ((sumCenters / valence) +\n                          ((sumMidpoints / valence) * 2) +\n                          (_vertices[_edges[edge].vertex].position * (valence - 3))) / valence;\n\n        newVertices.push_back(newVertex);\n        return newVertices.size() - 1;\n    };\n    \n    for (auto &f: _faces) {\n        auto v0 = _edges[f.edges[0]].vertex;\n        auto v1 = _edges[f.edges[1]].vertex;\n        auto v2 = _edges[f.edges[2]].vertex;\n        auto v3 = _edges[f.edges[3]].vertex;\n        _vertices[v0].newVertex = getNewVertex(f.edges[0]);\n        _vertices[v1].newVertex = getNewVertex(f.edges[1]);\n        _vertices[v2].newVertex = getNewVertex(f.edges[2]);\n        _vertices[v3].newVertex = getNewVertex(f.edges[3]);\n    }\n    \n    // Build new quad\n    Quad newQuad;\n    for (auto &v: newVertices) {\n        newQuad.addVertex(v);\n    }\n\n    for (auto &f: _faces) {\n        auto e0 = _edges[f.edges[0]];\n        auto e1 = _edges[f.edges[1]];\n        auto e2 = _edges[f.edges[2]];\n        auto e3 = _edges[f.edges[3]];\n\n        auto v0 = _vertices[e0.vertex].newVertex;\n        auto v1 = _vertices[e1.vertex].newVertex;\n        auto v2 = _vertices[e2.vertex].newVertex;\n        auto v3 = _vertices[e3.vertex].newVertex;\n\n        auto mp0 = e0.midpoint;\n        auto mp1 = e1.midpoint;\n        auto mp2 = e2.midpoint;\n        auto mp3 = e3.midpoint;\n\n        auto center = f.center;\n\n        newQuad.addFace(v0, mp0, center, mp3);\n        newQuad.addFace(v1, mp1, center, mp0);\n        newQuad.addFace(v2, mp2, center, mp1);\n        newQuad.addFace(v3, mp3, center, mp2);\n    }\n\n    if (level > 1) {\n        return newQuad.subdivide(level - 1);\n    }\n    return newQuad;\n}\n\n// Calculate smooth normals for each vertex by averaging normal of each face\n// that vertex is a part of\nvoid Quad::calculateNormals()\n{\n    // Calculate normal for each pair of edges in face, and average together\n    // to get face normal. I ~think~ this should work for slightly coplanar\n    // faces.\n    for (auto &f: _faces) {\n        auto v0 = &_vertices[_edges[f.edges[0]].vertex];\n        auto v1 = &_vertices[_edges[f.edges[1]].vertex];\n        auto v2 = &_vertices[_edges[f.edges[2]].vertex];\n        auto v3 = &_vertices[_edges[f.edges[3]].vertex];\n        auto n0 = ((v0->position - v1->position).getCrossed(v0->position - v3->position)).getNormalized();\n        auto n1 = ((v2->position - v3->position).getCrossed(v2->position - v1->position)).getNormalized();\n        f.normal = (n0 + n1) / 2.0;\n    }\n    \n    // Calculate smoothed normal for each vertex\n    for (auto &edge: _edges) {\n        int numNormals = 0;\n        ofVec3f sumNormals = {0.0, 0.0, 0.0};\n        auto e = edge;\n        do {\n            sumNormals += _faces[e.face].normal;\n            numNormals++;\n            e = _edges[_edges[e.opposite].next];\n        } while (e.face != edge.face);\n        _vertices[edge.vertex].normal = sumNormals / numNormals;\n    }\n}\n", "meta": {"hexsha": "80fddd33b70f66fd6b165296c1acffc37ae7de69", "size": 12105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Quad.cpp", "max_stars_repo_name": "jayvius/ofxQuad", "max_stars_repo_head_hexsha": "ae5f0c15454314f3f335a203b12dbcade4f519c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-12-02T08:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T03:38:35.000Z", "max_issues_repo_path": "src/Quad.cpp", "max_issues_repo_name": "jayvius/ofxQuad", "max_issues_repo_head_hexsha": "ae5f0c15454314f3f335a203b12dbcade4f519c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-10T08:34:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-22T11:05:20.000Z", "max_forks_repo_path": "src/Quad.cpp", "max_forks_repo_name": "jayvius/ofxQuad", "max_forks_repo_head_hexsha": "ae5f0c15454314f3f335a203b12dbcade4f519c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T03:09:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T03:09:22.000Z", "avg_line_length": 33.5318559557, "max_line_length": 106, "alphanum_fraction": 0.5843040066, "num_tokens": 3278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149845400438, "lm_q2_score": 0.022629199497484775, "lm_q1q2_score": 0.00665784958030605}}
{"text": "/*=========================================================================\n *\n *  Copyright 2011-2013 The University of North Carolina at Chapel Hill\n *  All rights reserved.\n *\n *  Licensed under the MADAI Software License. You may obtain a copy of\n *  this license at\n *\n *         https://madai-public.cs.unc.edu/visualization/software-license/\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*/\n\n#include <cassert>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n\n#include \"ApplicationUtilities.h\"\n#include \"Defaults.h\"\n#include \"ExternalModel.h\"\n#include \"MetropolisHastingsSampler.h\"\n#include \"GaussianProcessEmulator.h\"\n#include \"GaussianProcessEmulatorDirectoryFormatIO.h\"\n#include \"GaussianProcessEmulatedModel.h\"\n#include \"Paths.h\"\n#include \"PercentileGridSampler.h\"\n#include \"RuntimeParameterFileReader.h\"\n#include \"SamplerCSVWriter.h\"\n\n#include \"madaisys/SystemTools.hxx\"\n\n\nint main(int argc, char ** argv) {\n\n  if (argc < 3) {\n    std::cerr\n      << \"Usage:\\n\"\n      << \"    \" << argv[0] << \" <StatisticsDirectory> <OutputFileName>\\n\"\n      << \"\\n\"\n      << \"This program produces a Markov Chain Monte Carlo trace by either \\n\"\n      << \"evaluating a model defined in an external process or evaluating a \\n\"\n      << \"trained emulator. The program madai_pca_decompose must have been \\n\"\n      << \"run on <StatisticsDirectory> prior to running this program and if \\n\"\n      << \"no EXTERNAL_MODEL_EXECUTABLE is specified in the settings file, \\n\"\n      << \"madai_train_emulator must have been run as well.\\n\"\n      << \"\\n\"\n      << \"<StatisticsDirectory> is the directory in which all \\n\"\n      << \"statistics data are stored. It contains the parameter file \"\n      << madai::Paths::RUNTIME_PARAMETER_FILE << \"\\n\"\n      << \"\\n\"\n      << \"<OutputFileName> is the name of the comma-separated value-format \\n\"\n      << \"file in which the trace will be written. This file will be \\n\"\n      << \"written in the directory <StatisticsDirectory>/trace/.\\n\"\n      << \"\\n\"\n      << \"Format of entries in \" << madai::Paths::RUNTIME_PARAMETER_FILE\n      << \":\\n\\n\"\n      << \"MODEL_OUTPUT_DIRECTORY <value> (default: \"\n      << madai::Defaults::MODEL_OUTPUT_DIRECTORY << \")\\n\"\n      << \"EXPERIMENTAL_RESULTS_FILE <value> (default: \"\n      << madai::Defaults::EXPERIMENTAL_RESULTS_FILE << \")\\n\"\n      << \"SAMPLER <value> (default: \"\n      << madai::Defaults::SAMPLER << \")\\n\"\n      << \"SAMPLER_NUMBER_OF_SAMPLES <value> (default: \"\n      << madai::Defaults::SAMPLER_NUMBER_OF_SAMPLES << \")\\n\"\n      << \"SAMPLER_INACTIVE_PARAMETERS_FILE <value> (default: \"\n      << madai::Defaults::SAMPLER_INACTIVE_PARAMETERS_FILE << \")\\n\"\n      << \"MCMC_NUMBER_OF_BURN_IN_SAMPLES <value> (default: \"\n      << madai::Defaults::MCMC_NUMBER_OF_BURN_IN_SAMPLES << \")\\n\"\n      << \"MCMC_USE_MODEL_ERROR <value> (default: \"\n      << madai::Defaults::MCMC_USE_MODEL_ERROR << \")\\n\"\n      << \"MCMC_STEP_SIZE <value> (default: \"\n      << madai::Defaults::MCMC_STEP_SIZE << \")\\n\"\n      << \"EXTERNAL_MODEL_EXECUTABLE <value> (default: \\\"\"\n      << madai::Defaults::EXTERNAL_MODEL_EXECUTABLE << \"\\\")\\n\"\n      << \"EXTERNAL_MODEL_ARGUMENTS <Argument1> <Argument2> ... <LastArgument>\\n\"\n      << \"VERBOSE <value> (default: \"\n      << madai::Defaults::VERBOSE << \")\\n\";\n\n    return EXIT_FAILURE;\n  }\n  std::string statisticsDirectory( argv[1] );\n  madai::EnsurePathSeparatorAtEnd( statisticsDirectory );\n\n  madai::RuntimeParameterFileReader settings;\n  std::string settingsFile = statisticsDirectory + madai::Paths::RUNTIME_PARAMETER_FILE;\n  if ( !settings.ParseFile( settingsFile ) ) {\n    std::cerr << \"Could not open runtime parameter file '\" << settingsFile << \"'\\n\";\n    return EXIT_FAILURE;\n  }\n\n  std::string modelOutputDirectory =\n    madai::GetModelOutputDirectory( statisticsDirectory, settings );\n  std::string experimentalResultsFile =\n    madai::GetExperimentalResultsFile( statisticsDirectory, settings );\n\n  std::string samplerType = settings.GetOption( \"SAMPLER\", madai::Defaults::SAMPLER );\n\n  int numberOfSamples = settings.GetOptionAsInt(\n      \"SAMPLER_NUMBER_OF_SAMPLES\",\n      madai::Defaults::SAMPLER_NUMBER_OF_SAMPLES);\n\n  int numberOfBurnInSamples = settings.GetOptionAsInt(\n      \"MCMC_NUMBER_OF_BURN_IN_SAMPLES\",\n      madai::Defaults::MCMC_NUMBER_OF_BURN_IN_SAMPLES);\n\n  bool useModelError = settings.GetOptionAsBool(\n      \"MCMC_USE_MODEL_ERROR\",\n      madai::Defaults::MCMC_USE_MODEL_ERROR);\n\n  double stepSize = settings.GetOptionAsDouble(\n      \"MCMC_STEP_SIZE\", madai::Defaults::MCMC_STEP_SIZE);\n\n  std::string executable = settings.GetOption(\n      \"EXTERNAL_MODEL_EXECUTABLE\",\n      madai::Defaults::EXTERNAL_MODEL_EXECUTABLE);\n\n  bool verbose = settings.GetOptionAsBool( \"VERBOSE\", madai::Defaults::VERBOSE );\n\n  bool writeLogLikelihoodGradients = settings.GetOptionAsBool(\n      \"WRITE_LOGLIKELIHOOD_GRADIENTS\", \n      madai::Defaults::WRITE_LOGLIKELIHOOD_GRADIENTS );\n\n  bool compressed = settings.GetOptionAsBool( \"COMPRESS_TRACE\", madai::Defaults::COMPRESS_TRACE );\n\n  madai::ExternalModel externalModel;\n  madai::GaussianProcessEmulatedModel gpem;\n\n  madai::Model * model;\n  if ( executable == \"\" ) { // Use emulator\n    bool useModelError = settings.GetOptionAsBool(\n        \"PCA_USE_MODEL_ERROR\", madai::Defaults::PCA_USE_MODEL_ERROR );\n    madai::GaussianProcessEmulator gpe(useModelError);\n    madai::GaussianProcessEmulatorDirectoryFormatIO directoryReader;\n    if ( !directoryReader.LoadTrainingData( &gpe,\n                                            modelOutputDirectory,\n                                            statisticsDirectory,\n                                            experimentalResultsFile ) ) {\n      std::cerr << \"Error loading training data from the directory structure.\\n\";\n      return EXIT_FAILURE;\n    }\n    if ( !directoryReader.LoadPCA( &gpe, statisticsDirectory ) ) {\n      std::cerr << \"Error loading the PCA decomposition data. Did you \"\n                << \"run madai_pca_decompose?\\n\";\n      return EXIT_FAILURE;\n    }\n    if ( !directoryReader.LoadEmulator( &gpe, statisticsDirectory ) ) {\n      std::cerr << \"Error loading emulator data. Did you run \"\n                << \"madai_train_emulator?\\n\";\n      return EXIT_FAILURE;\n    }\n\n    gpem.SetGaussianProcessEmulator( gpe );\n\n    model = &gpem;\n\n    if ( verbose ) {\n      std::cout << \"Using emulator to generate trace.\\n\";\n    }\n  } else { // Use external model\n\n    // Split arguments into vector of strings\n    std::vector< std::string > arguments;\n    if ( settings.HasOption( \"EXTERNAL_MODEL_ARGUMENTS\" ) ) {\n      std::string argumentsString =\n        settings.GetOption( \"EXTERNAL_MODEL_ARGUMENTS\" );\n      arguments = madai::SplitString( argumentsString, ' ' );\n    }\n\n    if ( verbose ) {\n      std::cout << \"Using external model executable '\" << executable << \"'.\\n\";\n    }\n\n    externalModel.StartProcess( executable, arguments );\n    if (! externalModel.IsReady()) {\n      std::cerr << \"Something is wrong with the external model\\n\";\n      return EXIT_FAILURE;\n    }\n\n    model = &externalModel;\n  }\n\n  std::ifstream experimentalResults(experimentalResultsFile.c_str());\n  if ( madai::Model::NO_ERROR !=\n       madai::LoadObservations( model, experimentalResults ) ) {\n    std::cerr << \"Error loading observations.\\n\";\n    externalModel.StopProcess();\n    return EXIT_FAILURE;\n  }\n  experimentalResults.close();\n\n  madai::Sampler * sampler;\n\n  madai::PercentileGridSampler pgs;\n  madai::MetropolisHastingsSampler mhs;\n  if ( samplerType == \"PercentileGrid\" ) {\n    pgs.SetModel( model );\n\n    // Burn-in samples don't exist for a percentile grid sampling\n    numberOfBurnInSamples = 0;\n\n    sampler = &pgs;\n\n    if ( verbose ) {\n      std::cout << \"Using PercentileGridSampler for sampling\\n\";\n    }\n  } else { // Default to Metropolis Hastings\n    mhs.SetModel( model );\n    mhs.SetStepSize( stepSize );\n\n    sampler = &mhs;\n\n    if ( verbose ) {\n      std::cout << \"Using MetropolisHastingsSampler for sampling\\n\";\n    }\n  }\n\n  // Potentially set some parameters to inactive\n  std::string samplerInactiveParametersFile =\n    madai::GetInactiveParametersFile( statisticsDirectory, settings );\n  if ( samplerInactiveParametersFile != \"\" ) {\n    if ( ! madai::SetInactiveParameters( samplerInactiveParametersFile,\n                                         *sampler, verbose ) ) {\n      std::cerr << \"Error when setting inactive parameters from file '\"\n                << samplerInactiveParametersFile << \"'.\\n\";\n      return EXIT_FAILURE;\n    }\n  }\n\n  if ( samplerType == \"PercentileGrid\" ) {\n    assert( pgs.GetModel() != NULL );\n    pgs.SetNumberOfSamples(numberOfSamples);\n    numberOfSamples = pgs.GetNumberOfSamples();\n    if ( verbose ) {\n      std::cout << \"Number of grid samples: \" << numberOfSamples << \"\\n\";\n    }\n  }\n\n  std::string outputFilePath( argv[2] );\n  std::ofstream outFile(outputFilePath.c_str(), std::ios_base::out | std::ios_base::binary);\n  if ( !outFile.good() ) {\n    std::cerr << \"Could not open trace file '\" << outputFilePath << \"' for writing.\\n\";\n    return EXIT_FAILURE;\n  }\n  boost::iostreams::filtering_streambuf<boost::iostreams::output> outbuf;\n  if( compressed ) {\n      outbuf.push(boost::iostreams::gzip_compressor());\n  }\n  outbuf.push(outFile);\n  std::ostream outFileStream(&outbuf);\n\n  std::ostream * progressStream = verbose ? (& std::cerr) : NULL;\n  int returnCode = madai::SamplerCSVWriter::GenerateSamplesAndSaveToFile(\n      *sampler,\n      *model,\n      outFileStream,\n      numberOfSamples,\n      numberOfBurnInSamples,\n      useModelError,\n      writeLogLikelihoodGradients,\n      progressStream);\n\n  if ( verbose ) {\n    if ( returnCode == EXIT_SUCCESS ) {\n      std::cout << \"Succeeded writing trace file '\" << outputFilePath << \"'.\\n\";\n    } else {\n      std::cerr << \"Could not write trace file '\" << outputFilePath << \"'.\\n\";\n    }\n  }\n\n  return returnCode;\n}\n", "meta": {"hexsha": "f06e862fc2712230a500384216297989c6b17860", "size": 10340, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "applications/madai_generate_trace.cxx", "max_stars_repo_name": "scottedwardpratt/MADAI", "max_stars_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-28T20:14:23.000Z", "max_issues_repo_path": "applications/madai_generate_trace.cxx", "max_issues_repo_name": "scottedwardpratt/MADAI", "max_issues_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/madai_generate_trace.cxx", "max_forks_repo_name": "scottedwardpratt/MADAI", "max_forks_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-08-20T14:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-28T20:15:23.000Z", "avg_line_length": 36.5371024735, "max_line_length": 98, "alphanum_fraction": 0.6579303675, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070997458932, "lm_q2_score": 0.030214585539193057, "lm_q1q2_score": 0.006647423334502069}}
{"text": "/*ckwg +29\n * Copyright 2014-2016 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 kwiver::arrows::transform functions to apply\n * similarity transformations\n */\n\n#include \"transform.h\"\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n\nnamespace kwiver {\nnamespace arrows {\n\n\n/// Transform the camera by applying a similarity transformation in place\nvoid\ntransform_inplace(const vital::similarity_d& xform,\n                  vital::simple_camera_perspective& cam)\n{\n  cam.set_center( xform * cam.get_center() );\n  cam.set_rotation( cam.get_rotation() * xform.rotation().inverse() );\n  cam.set_center_covar( transform(cam.get_center_covar(), xform) );\n}\n\n\n/// Transform the landmark by applying a similarity transformation in place\ntemplate <typename T>\nvoid\ntransform_inplace(const vital::similarity_<T>& xform,\n                  vital::landmark_<T>& lm)\n{\n  lm.set_loc( xform * lm.get_loc() );\n  lm.set_scale( lm.get_scale() * xform.scale() );\n  lm.set_covar( transform(lm.get_covar(), xform) );\n}\n\n\n/// Transform a 3D covariance matrix with a similarity transformation\ntemplate <typename T>\nvital::covariance_<3,T> transform(const vital::covariance_<3,T>& covar,\n                                  const vital::similarity_<T>& xform)\n{\n  // TODO trasform covariance parameters directly\n  // instead of converting to matrix form and back\n  Eigen::Matrix<T,3,3> C(covar.matrix());\n  Eigen::Matrix<T,3,3> sR(xform.rotation().matrix());\n  sR /= xform.scale();\n  C = sR * C * sR.transpose();\n  return vital::covariance_<3,T>(C);\n}\n\n\n/// construct a transformed camera by applying a similarity transformation\nvital::camera_perspective_sptr transform(vital::camera_perspective_sptr cam,\n                                         const vital::similarity_d& xform)\n{\n  cam = std::dynamic_pointer_cast<vital::camera_perspective>(cam->clone());\n  if( vital::simple_camera_perspective* vcam =\n      dynamic_cast<vital::simple_camera_perspective*>(cam.get()) )\n  {\n    transform_inplace(xform, *vcam);\n  }\n  else\n  {\n    vital::simple_camera_perspective* new_cam =\n        new vital::simple_camera_perspective( xform * cam->center(),\n                                  cam->rotation() * xform.rotation().inverse(),\n                                  cam->intrinsics() );\n    new_cam->set_center_covar( transform(cam->center_covar(), xform) );\n    cam = vital::camera_perspective_sptr( new_cam );\n  }\n  return cam;\n}\n\n\n/// construct a transformed map of cameras by applying a similarity transformation\nvital::camera_map_sptr transform(vital::camera_map_sptr cameras,\n                                 const vital::similarity_d& xform)\n{\n  vital::camera_map::map_camera_t cam_map = cameras->cameras();\n  for(vital::camera_map::map_camera_t::value_type& p : cam_map)\n  {\n    auto cam_ptr = std::dynamic_pointer_cast<vital::camera_perspective>(p.second);\n    p.second = transform(cam_ptr, xform);\n  }\n  return vital::camera_map_sptr(new vital::simple_camera_map(cam_map));\n}\n\n\n/// construct a transformed landmark by applying a similarity transformation\nvital::landmark_sptr transform(vital::landmark_sptr lm,\n                               const vital::similarity_d& xform)\n{\n  if (!lm)\n  {\n    return vital::landmark_sptr();\n  }\n  lm = lm->clone();\n  if( vital::landmark_d* vlm = dynamic_cast<vital::landmark_d*>(lm.get()) )\n  {\n    transform_inplace(xform, *vlm);\n  }\n  else if( vital::landmark_f* vlm = dynamic_cast<vital::landmark_f*>(lm.get()) )\n  {\n    transform_inplace(vital::similarity_f(xform), *vlm);\n  }\n  else\n  {\n    auto new_lm = std::make_shared<vital::landmark_d>( *lm );\n    new_lm->set_loc( xform * lm->loc() );\n    new_lm->set_scale( lm->scale() * xform.scale() );\n    new_lm->set_covar( transform(lm->covar(), xform) );\n    lm = new_lm;\n  }\n  return lm;\n}\n\n\n/// construct a transformed map of landmarks by applying a similarity transformation\nvital::landmark_map_sptr transform(vital::landmark_map_sptr landmarks,\n                                   const vital::similarity_d& xform)\n{\n  vital::landmark_map::map_landmark_t lm_map = landmarks->landmarks();\n  for(vital::landmark_map::map_landmark_t::value_type& p : lm_map)\n  {\n    p.second = transform(p.second, xform);\n  }\n  return vital::landmark_map_sptr(new vital::simple_landmark_map(lm_map));\n}\n\n\n/// Compute an approximate Necker reversal of cameras and landmarks\nvoid\nnecker_reverse(vital::camera_map_sptr& cameras,\n               vital::landmark_map_sptr& landmarks)\n{\n  typedef vital::landmark_map::map_landmark_t lm_map_t;\n  typedef vital::camera_map::map_camera_t cam_map_t;\n\n  cam_map_t cams = cameras->cameras();\n  lm_map_t lms = landmarks->landmarks();\n\n  // compute the landmark location mean and covariance\n  vital::vector_3d lc(0.0, 0.0, 0.0);\n  vital::matrix_3x3d covar = vital::matrix_3x3d::Zero();\n  for(const lm_map_t::value_type& p : lms)\n  {\n    vital::vector_3d pt = p.second->loc();\n    lc += pt;\n    covar += pt * pt.transpose();\n  }\n  const double num_lm = static_cast<double>(lms.size());\n  lc /= num_lm;\n  covar /= num_lm;\n  covar -= lc * lc.transpose();\n\n  // the mirroring plane will pass through the landmark centeroid (lc)\n  // and have a normal vector aligned with the smallest eigenvector of covar\n  Eigen::JacobiSVD<vital::matrix_3x3d> svd(covar, Eigen::ComputeFullV);\n  vital::vector_3d axis = svd.matrixV().col(2);\n\n  // flip cameras around\n  vital::rotation_d Ra180(vital::vector_4d(axis.x(), axis.y(), axis.z(), 0.0));\n  vital::rotation_d Rz180(vital::vector_4d(0.0, 0.0, 1.0, 0.0));\n  for(cam_map_t::value_type& p : cams)\n  {\n    auto flipped = std::make_shared<vital::simple_camera_perspective>(\n      dynamic_cast<vital::simple_camera_perspective&>(*p.second));\n    // extract the camera center\n    const vital::vector_3d cc = flipped->center();\n    // extract the camera principal axis\n    vital::vector_3d pa = flipped->rotation().matrix().row(2);\n    // compute the distance from cc along pa until intersection with\n    // the mirroring plane of the points\n    const double dist = (lc - cc).dot(axis) / pa.dot(axis);\n    // compute the ground point where the principal axis\n    // intersects the mirroring plane\n    vital::vector_3d gp = cc + dist * pa;\n    // rotate the camera center 180 degrees about the mirroring plane normal\n    // axis centered at gp, also rotate the camera 180 about its principal axis\n    flipped->set_center(Ra180 * (flipped->center() - gp) + gp);\n    flipped->set_rotation(Rz180 * flipped->rotation() * Ra180);\n    p.second = vital::camera_perspective_sptr(flipped);\n  }\n\n  // mirror landmark locations about the mirroring plane\n  for(lm_map_t::value_type& p : lms)\n  {\n    vital::vector_3d v = p.second->loc();\n    v -= 2.0 * (v - lc).dot(axis) * axis;\n    auto new_lm = std::make_shared<vital::landmark_d>(*p.second);\n    new_lm->set_loc(v);\n    p.second = new_lm;\n  }\n\n  cameras = vital::camera_map_sptr(new vital::simple_camera_map(cams));\n  landmarks = vital::landmark_map_sptr(new vital::simple_landmark_map(lms));\n}\n\n\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_TRANSFORM(T) \\\ntemplate KWIVER_ALGO_CORE_EXPORT vital::covariance_<3,T> \\\ntransform(const vital::covariance_<3,T>& covar, \\\n          const vital::similarity_<T>& xform); \\\ntemplate KWIVER_ALGO_CORE_EXPORT void \\\ntransform_inplace(const vital::similarity_<T>& xform, \\\n                  vital::landmark_<T>& cam);\n\nINSTANTIATE_TRANSFORM(double);\nINSTANTIATE_TRANSFORM(float);\n\n#undef INSTANTIATE_TRANSFORM\n/// \\endcond\n\n\n} // end namespace arrows\n} // end namespace kwiver\n", "meta": {"hexsha": "a9f64284544b9fc80961b0d6e80998946868a0f4", "size": 9004, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "arrows/core/transform.cxx", "max_stars_repo_name": "judajake/kwiver", "max_stars_repo_head_hexsha": "303a11ebb43c020ab8e48b6ef70407b460dba46b", "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": "arrows/core/transform.cxx", "max_issues_repo_name": "judajake/kwiver", "max_issues_repo_head_hexsha": "303a11ebb43c020ab8e48b6ef70407b460dba46b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/core/transform.cxx", "max_forks_repo_name": "judajake/kwiver", "max_forks_repo_head_hexsha": "303a11ebb43c020ab8e48b6ef70407b460dba46b", "max_forks_repo_licenses": ["BSD-3-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.016, "max_line_length": 84, "alphanum_fraction": 0.6964682363, "num_tokens": 2279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.02228618663505097, "lm_q1q2_score": 0.006629470936811174}}
{"text": "/*-\n * SPDX-License-Identifier: BSD-2-Clause\n * \n * Copyright (c) 2020 NKI/AVL, Netherlands Cancer Institute\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// Calculate DSSP-like secondary structure information\n\n#include <numeric>\n#include <iomanip>\n#include <thread>\n\n#include <boost/algorithm/string.hpp>\n\n#include \"cif++/Structure.hpp\"\n#include \"cif++/Secondary.hpp\"\n\nnamespace ba = boost::algorithm;\n\n// --------------------------------------------------------------------\n\nnamespace mmcif\n{\n\nstruct Res;\n\nenum ResidueType\n{\n\tkUnknownResidue,\n\t\n\t//\n\tkAlanine,\t\t\t\t// A\tala\n\tkArginine,\t\t\t\t// R\targ\n\tkAsparagine,\t\t\t// N\tasn\n\tkAsparticAcid,\t\t\t// D\tasp\n\tkCysteine,\t\t\t\t// C\tcys\n\tkGlutamicAcid,\t\t\t// E\tglu\n\tkGlutamine,\t\t\t\t// Q\tgln\n\tkGlycine,\t\t\t\t// G\tgly\n\tkHistidine,\t\t\t\t// H\this\n\tkIsoleucine,\t\t\t// I\tile\n\tkLeucine,\t\t\t\t// L\tleu\n\tkLysine,\t\t\t\t// K\tlys\n\tkMethionine,\t\t\t// M\tmet\n\tkPhenylalanine,\t\t\t// F\tphe\n\tkProline,\t\t\t\t// P\tpro\n\tkSerine,\t\t\t\t// S\tser\n\tkThreonine,\t\t\t\t// T\tthr\n\tkTryptophan,\t\t\t// W\ttrp\n\tkTyrosine,\t\t\t\t// Y\ttyr\n\tkValine,\t\t\t\t// V\tval\n\t\n\tkResidueTypeCount\n};\n\nstruct ResidueInfo\n{\n\tResidueType\t\ttype;\n\tchar\t\t\tcode;\n\tchar\t\t\tname[4];\n};\n\nconst ResidueInfo kResidueInfo[] = {\n\t{ kUnknownResidue,\t'X', \"UNK\" },\n\t{ kAlanine,\t\t\t'A', \"ALA\" },\n\t{ kArginine,\t\t'R', \"ARG\" },\n\t{ kAsparagine,\t\t'N', \"ASN\" },\n\t{ kAsparticAcid,\t'D', \"ASP\" },\n\t{ kCysteine,\t\t'C', \"CYS\" },\n\t{ kGlutamicAcid,\t'E', \"GLU\" },\n\t{ kGlutamine,\t\t'Q', \"GLN\" },\n\t{ kGlycine,\t\t\t'G', \"GLY\" },\n\t{ kHistidine,\t\t'H', \"HIS\" },\n\t{ kIsoleucine,\t\t'I', \"ILE\" },\n\t{ kLeucine,\t\t\t'L', \"LEU\" },\n\t{ kLysine,\t\t\t'K', \"LYS\" },\n\t{ kMethionine,\t\t'M', \"MET\" },\n\t{ kPhenylalanine,\t'F', \"PHE\" },\n\t{ kProline,\t\t\t'P', \"PRO\" },\n\t{ kSerine,\t\t\t'S', \"SER\" },\n\t{ kThreonine,\t\t'T', \"THR\" },\n\t{ kTryptophan,\t\t'W', \"TRP\" },\n\t{ kTyrosine,\t\t'Y', \"TYR\" },\n\t{ kValine,\t\t\t'V', \"VAL\" }\n};\n\nResidueType MapResidue(std::string inName)\n{\n\tba::trim(inName);\n\n\tResidueType result = kUnknownResidue;\n\t\n\tfor (auto& ri: kResidueInfo)\n\t{\n\t\tif (inName == ri.name)\n\t\t{\n\t\t\tresult = ri.type;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn result;\n}\n\nstruct HBond\n{\n\tRes*\tresidue;\n\tdouble\tenergy;\n};\n\nenum BridgeType\n{\n\tbtNoBridge, btParallel, btAntiParallel\n};\n\nstruct Bridge\n{\n\tBridgeType\t\t\t\ttype;\n\tuint32_t\t\t\t\tsheet, ladder;\n\tstd::set<Bridge*>\t\tlink;\n\tstd::deque<uint32_t>\ti, j;\n\tstd::string\t\t\t\tchainI, chainJ;\n\t\n\tbool\t\t\toperator<(const Bridge& b) const\t\t{ return chainI < b.chainI or (chainI == b.chainI and i.front() < b.i.front()); }\n};\n\nstruct BridgeParner\n{\n\tRes*\t\tresidue;\n\tuint32_t\tladder;\n\tbool\t\tparallel;\n};\n\n// --------------------------------------------------------------------\n\nconst float\n\t// kSSBridgeDistance = 3.0f,\n\tkMinimalDistance = 0.5f,\n\tkMinimalCADistance = 9.0f,\n\tkMinHBondEnergy = -9.9f,\n\tkMaxHBondEnergy = -0.5f,\n\tkCouplingConstant = -27.888f,\t//\t= -332 * 0.42 * 0.2\n\tkMaxPeptideBondLength = 2.5f;\n\nconst float\n\tkRadiusN = 1.65f,\n\tkRadiusCA = 1.87f,\n\tkRadiusC = 1.76f,\n\tkRadiusO = 1.4f,\n\tkRadiusSideAtom = 1.8f,\n\tkRadiusWater = 1.4f;\n\nstruct Res\n{\n\tRes(const Monomer& m, int nr, ChainBreak brk)\n\t\t: mM(m), mNumber(nr)\n\t\t, mType(MapResidue(m.compoundID()))\n\t\t, mChainBreak(brk)\n\t{\n\t\t// update the box containing all atoms\n\t\tmBox[0].mX = mBox[0].mY = mBox[0].mZ =  std::numeric_limits<float>::max();\n\t\tmBox[1].mX = mBox[1].mY = mBox[1].mZ = -std::numeric_limits<float>::max();\n\n\t\tmH = mmcif::Point{ std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max() };\n\n\t\tfor (auto& a: mM.unique_atoms())\n\t\t{\n\t\t\tif (a.labelAtomID() == \"CA\")\n\t\t\t{\n\t\t\t\tmCAlpha = a.location();\n\t\t\t\tExtendBox(mCAlpha, kRadiusCA + 2 * kRadiusWater);\n\t\t\t}\n\t\t\telse if (a.labelAtomID() == \"C\")\n\t\t\t{\n\t\t\t\tmC = a.location();\n\t\t\t\tExtendBox(mC, kRadiusC + 2 * kRadiusWater);\n\t\t\t}\n\t\t\telse if (a.labelAtomID() == \"N\")\n\t\t\t{\n\t\t\t\tmH = mN = a.location();\n\t\t\t\tExtendBox(mN, kRadiusN + 2 * kRadiusWater);\n\t\t\t}\n\t\t\telse if (a.labelAtomID() == \"O\")\n\t\t\t{\n\t\t\t\tmO = a.location();\n\t\t\t\tExtendBox(mO, kRadiusO + 2 * kRadiusWater);\n\t\t\t}\n\t\t\telse if (a.type() != AtomType::H)\n\t\t\t{\n\t\t\t\tmSideChain.push_back(a.location());\n\t\t\t\tExtendBox(a.location(), kRadiusSideAtom + 2 * kRadiusWater);\n\t\t\t}\n\t\t}\n\n\t\tmRadius = mBox[1].mX - mBox[0].mX;\n\t\tif (mRadius < mBox[1].mY - mBox[0].mY)\n\t\t\tmRadius = mBox[1].mY - mBox[0].mY;\n\t\tif (mRadius < mBox[1].mZ - mBox[0].mZ)\n\t\t\tmRadius = mBox[1].mZ - mBox[0].mZ;\n\n\t\tmCenter.mX = (mBox[0].mX + mBox[1].mX) / 2;\n\t\tmCenter.mY = (mBox[0].mY + mBox[1].mY) / 2;\n\t\tmCenter.mZ = (mBox[0].mZ + mBox[1].mZ) / 2;\n\t}\n\n\tvoid assignHydrogen()\n\t{\n\t\t// assign the Hydrogen\n\t\tmH = mN;\n\t\t\n\t\tif (mType != kProline and mPrev != nullptr)\n\t\t{\n\t\t\tauto pc = mPrev->mC;\n\t\t\tauto po = mPrev->mO;\n\t\t\t\n\t\t\tfloat CODistance = static_cast<float>(Distance(pc, po));\n\t\t\t\n\t\t\tmH.mX += (pc.mX - po.mX) / CODistance; \n\t\t\tmH.mY += (pc.mY - po.mY) / CODistance; \n\t\t\tmH.mZ += (pc.mZ - po.mZ) / CODistance; \n\t\t}\n\t}\n\n\tvoid SetSecondaryStructure(SecondaryStructureType inSS)\t{ mSecondaryStructure = inSS; }\n\tSecondaryStructureType GetSecondaryStructure() const\t{ return mSecondaryStructure; }\n\t\n\tvoid SetBetaPartner(uint32_t n, Res& inResidue, uint32_t inLadder, bool inParallel)\n\t{\n\t\tassert(n == 0 or n == 1);\n\t\t\n\t\tmBetaPartner[n].residue = &inResidue;\n\t\tmBetaPartner[n].ladder = inLadder;\n\t\tmBetaPartner[n].parallel = inParallel;\n\t}\n\t\n\tBridgeParner GetBetaPartner(uint32_t n) const\n\t{\n\t\tassert(n == 0 or n == 1);\n\t\treturn mBetaPartner[n];\n\t}\n\t\t\t\t\t\t\n\tvoid SetSheet(uint32_t inSheet)\t\t\t\t\t\t{ mSheet = inSheet; }\n\tuint32_t GetSheet() const\t\t\t\t\t\t\t{ return mSheet; }\n\t\n\tbool IsBend() const\t\t\t\t\t\t\t\t\t{ return mBend; }\n\tvoid SetBend(bool inBend)\t\t\t\t\t\t\t{ mBend = inBend; }\n\t\n\tHelix GetHelixFlag(HelixType helixType) const\n\t{\n\t\tsize_t stride = static_cast<size_t>(helixType);\n\t\tassert(stride < 4);\n\t\treturn mHelixFlags[stride];\n\t}\n\n\tbool IsHelixStart(HelixType helixType) const\n\t{\n\t\tsize_t stride = static_cast<size_t>(helixType);\n\t\tassert(stride < 4);\n\t\treturn mHelixFlags[stride] == Helix::Start or mHelixFlags[stride] == Helix::StartAndEnd;\n\t}\n\n\tvoid SetHelixFlag(HelixType helixType, Helix inHelixFlag)\n\t{\n\t\tsize_t stride = static_cast<size_t>(helixType);\n\t\tassert(stride < 4);\n\t\tmHelixFlags[stride] = inHelixFlag;\n\t}\n\n\tvoid SetSSBridgeNr(uint8_t inBridgeNr)\n\t{\n\t\tif (mType != kCysteine)\n\t\t\tthrow std::runtime_error(\"Only cysteine residues can form sulphur bridges\");\n\t\tmSSBridgeNr = inBridgeNr;\n\t}\n\t\n\tuint8_t GetSSBridgeNr() const\n\t{\n\t\tif (mType != kCysteine)\n\t\t\tthrow std::runtime_error(\"Only cysteine residues can form sulphur bridges\");\n\t\treturn mSSBridgeNr;\n\t}\n\n\tdouble CalculateSurface(const std::vector<Res>& inResidues);\n\tdouble CalculateSurface(const Point& inAtom, float inRadius, const std::vector<Res*>& inNeighbours);\n\n\tbool AtomIntersectsBox(const Point& atom, float inRadius) const\n\t{\n\t\treturn\n\t\t\tatom.mX + inRadius >= mBox[0].mX and\n\t\t\tatom.mX - inRadius <= mBox[1].mX and\n\t\t\tatom.mY + inRadius >= mBox[0].mY and\n\t\t\tatom.mY - inRadius <= mBox[1].mY and\n\t\t\tatom.mZ + inRadius >= mBox[0].mZ and\n\t\t\tatom.mZ - inRadius <= mBox[1].mZ;\n\t}\n\n\tvoid ExtendBox(const Point& atom, float inRadius)\n\t{\n\t\tif (mBox[0].mX > atom.mX - inRadius)\n\t\t\tmBox[0].mX = atom.mX - inRadius;\n\t\tif (mBox[0].mY > atom.mY - inRadius)\n\t\t\tmBox[0].mY = atom.mY - inRadius;\n\t\tif (mBox[0].mZ > atom.mZ - inRadius)\n\t\t\tmBox[0].mZ = atom.mZ - inRadius;\n\t\tif (mBox[1].mX < atom.mX + inRadius)\n\t\t\tmBox[1].mX = atom.mX + inRadius;\n\t\tif (mBox[1].mY < atom.mY + inRadius)\n\t\t\tmBox[1].mY = atom.mY + inRadius;\n\t\tif (mBox[1].mZ < atom.mZ + inRadius)\n\t\t\tmBox[1].mZ = atom.mZ + inRadius;\n\t}\n\n\tRes* mNext = nullptr;\n\tRes* mPrev = nullptr;\n\n\tconst Monomer& mM;\n\tstd::string mAltID;\n\n\tint mNumber;\n\n\tPoint mCAlpha, mC, mN, mO, mH;\n\tPoint mBox[2] = {};\n\tfloat mRadius;\n\tPoint mCenter;\n\tstd::vector<Point> mSideChain;\n\tdouble mAccessibility = 0;\n\t\n\tResidueType mType;\n\tuint8_t mSSBridgeNr = 0;\n\tSecondaryStructureType mSecondaryStructure = ssLoop;\n\tHBond mHBondDonor[2] = {}, mHBondAcceptor[2] = {};\n\tBridgeParner mBetaPartner[2] = {};\n\tuint32_t mSheet = 0;\n\tHelix mHelixFlags[4] = { Helix::None, Helix::None, Helix::None, Helix::None };\t//\n\tbool mBend = false;\n\tChainBreak mChainBreak = ChainBreak::None;\n};\n\n// --------------------------------------------------------------------\n\nclass Accumulator\n{\n\tpublic:\n\n\tstruct candidate\n\t{\n\t\tPoint\tlocation;\n\t\tdouble\tradius;\n\t\tdouble\tdistance;\n\n\t\tbool operator<(const candidate& rhs) const\n\t\t\t\t{ return distance < rhs.distance; }\n\t};\n\n\tvoid operator()(const Point& a, const Point& b, double d, double r)\n\t{\n\t\tdouble distance = DistanceSquared(a, b);\n\n\t\td += kRadiusWater;\n\t\tr += kRadiusWater;\n\n\t\tdouble test = d + r;\n\t\ttest *= test;\n\n\t\tif (distance < test and distance > 0.0001)\n\t\t{\n\t\t\tcandidate c = { b - a, r * r, distance };\n\n\t\t\tm_x.push_back(c);\n\t\t\tpush_heap(m_x.begin(), m_x.end());\n\t\t}\n\t}\n\n\tvoid sort()\n\t{\n\t\tsort_heap(m_x.begin(), m_x.end());\n\t}\n\n\tstd::vector<candidate>  m_x;\n};\n\n// we use a fibonacci sphere to calculate the even distribution of the dots\nclass MSurfaceDots\n{\n  public:\n\n\tstatic MSurfaceDots&  Instance();\n\n\tsize_t size() const\t\t\t\t\t\t\t{ return mPoints.size(); }\n\tconst Point& operator[](size_t inIx) const\t{ return mPoints[inIx]; }\n\tdouble weight() const\t\t\t\t\t\t{ return mWeight; }\n\n  private:\n\tMSurfaceDots(int32_t inN);\n\n\tstd::vector<Point> mPoints;\n\tdouble mWeight;\n};\n\nMSurfaceDots& MSurfaceDots::Instance()\n{\n\tconst int32_t kN = 200;\n\n\tstatic MSurfaceDots sInstance(kN);\n\treturn sInstance;\n}\n\nMSurfaceDots::MSurfaceDots(int32_t N)\n{\n\tauto P = 2 * N + 1;\n\n\tconst float kGoldenRatio = (1 + std::sqrt(5.0f)) / 2;\n\n\tmWeight = (4 * kPI) / P;\n\n\tfor (auto i = -N; i <= N; ++i)\n\t{\n\t\tfloat lat = std::asin((2.0f * i) / P);\n\t\tfloat lon = static_cast<float>(std::fmod(i, kGoldenRatio) * 2 * kPI / kGoldenRatio);\n\n\t\tmPoints.emplace_back(std::sin(lon) * std::cos(lat), std::cos(lon) * std::cos(lat), std::sin(lat));\n\t}\n}\n\ndouble Res::CalculateSurface(const Point& inAtom, float inRadius, const std::vector<Res*>& inNeighbours)\n{\n\tAccumulator accumulate;\n\n\tfor (auto r: inNeighbours)\n\t{\n\t\tif (r->AtomIntersectsBox(inAtom, inRadius))\n\t\t{\n\t\t\taccumulate(inAtom, r->mN, inRadius, kRadiusN);\n\t\t\taccumulate(inAtom, r->mCAlpha, inRadius, kRadiusCA);\n\t\t\taccumulate(inAtom, r->mC, inRadius, kRadiusC);\n\t\t\taccumulate(inAtom, r->mO, inRadius, kRadiusO);\n\n\t\t\tfor (auto& atom: r->mSideChain)\n\t\t\t\taccumulate(inAtom, atom, inRadius, kRadiusSideAtom);\n\t\t}\n\t}\n\n\taccumulate.sort();\n\n\tfloat radius = inRadius + kRadiusWater;\n\tdouble surface = 0;\n\n\tMSurfaceDots& surfaceDots = MSurfaceDots::Instance();\n\n\tfor (size_t i = 0; i < surfaceDots.size(); ++i)\n\t{\n\t\tPoint xx = surfaceDots[i] * radius;\n\n\t\tbool free = true;\n\t\tfor (size_t k = 0; free and k < accumulate.m_x.size(); ++k)\n\t\t\tfree = accumulate.m_x[k].radius < DistanceSquared(xx, accumulate.m_x[k].location);\n\n\t\tif (free)\n\t\t\tsurface += surfaceDots.weight();\n\t}\n\n\treturn surface * radius * radius;\n}\n\ndouble Res::CalculateSurface(const std::vector<Res>& inResidues)\n{\n\tstd::vector<Res*> neighbours;\n\n\tfor (auto& r: inResidues)\n\t{\n\t\tPoint center = r.mCenter;\n\t\tdouble radius = r.mRadius;\n\n\t\tif (Distance(mCenter, center) < mRadius + radius)\n\t\t\tneighbours.push_back(const_cast<Res*>(&r));\n\t}\n\n\tmAccessibility = CalculateSurface(mN, kRadiusN, neighbours) +\n\t\t\t\t\t CalculateSurface(mCAlpha, kRadiusCA, neighbours) +\n\t\t\t\t\t CalculateSurface(mC, kRadiusC, neighbours) +\n\t\t\t\t\t CalculateSurface(mO, kRadiusO, neighbours);\n\n\tfor (auto& atom: mSideChain)\n\t\tmAccessibility += CalculateSurface(atom, kRadiusSideAtom, neighbours);\n\t\n\treturn mAccessibility;\n}\n\nvoid CalculateAccessibilities(std::vector<Res>& inResidues, DSSP_Statistics& stats)\n{\n\tstats.accessibleSurface = 0;\n\tfor (auto& residue: inResidues)\n\t\tstats.accessibleSurface += residue.CalculateSurface(inResidues);\n}\n\n// --------------------------------------------------------------------\n// TODO: use the angle to improve bond energy calculation.\n\ndouble CalculateHBondEnergy(Res& inDonor, Res& inAcceptor)\n{\n\tdouble result = 0;\n\t\n\tif (inDonor.mType != kProline)\n\t{\n\t\tdouble distanceHO = Distance(inDonor.mH, inAcceptor.mO);\n\t\tdouble distanceHC = Distance(inDonor.mH, inAcceptor.mC);\n\t\tdouble distanceNC = Distance(inDonor.mN, inAcceptor.mC);\n\t\tdouble distanceNO = Distance(inDonor.mN, inAcceptor.mO);\n\t\t\n\t\tif (distanceHO < kMinimalDistance or distanceHC < kMinimalDistance or distanceNC < kMinimalDistance or distanceNO < kMinimalDistance)\n\t\t\tresult = kMinHBondEnergy;\n\t\telse\n\t\t\tresult = kCouplingConstant / distanceHO - kCouplingConstant / distanceHC + kCouplingConstant / distanceNC - kCouplingConstant / distanceNO;\n\n\t\t// DSSP compatibility mode:\n\t\tresult = round(result * 1000) / 1000;\n\n\t\tif (result < kMinHBondEnergy)\n\t\t\tresult = kMinHBondEnergy;\n\t}\n\n\t// update donor\n\tif (result < inDonor.mHBondAcceptor[0].energy)\n\t{\n\t\tinDonor.mHBondAcceptor[1] = inDonor.mHBondAcceptor[0];\n\t\tinDonor.mHBondAcceptor[0].residue = &inAcceptor;\n\t\tinDonor.mHBondAcceptor[0].energy = result;\n\t}\n\telse if (result < inDonor.mHBondAcceptor[1].energy)\n\t{\n\t\tinDonor.mHBondAcceptor[1].residue = &inAcceptor;\n\t\tinDonor.mHBondAcceptor[1].energy = result;\n\t}\t\t\n\n\t// and acceptor\n\tif (result < inAcceptor.mHBondDonor[0].energy)\n\t{\n\t\tinAcceptor.mHBondDonor[1] = inAcceptor.mHBondDonor[0];\n\t\tinAcceptor.mHBondDonor[0].residue = &inDonor;\n\t\tinAcceptor.mHBondDonor[0].energy = result;\n\t}\n\telse if (result < inAcceptor.mHBondDonor[1].energy)\n\t{\n\t\tinAcceptor.mHBondDonor[1].residue = &inDonor;\n\t\tinAcceptor.mHBondDonor[1].energy = result;\n\t}\t\t\n\t\n\treturn result;\n}\n\n\n// --------------------------------------------------------------------\n\nvoid CalculateHBondEnergies(std::vector<Res>& inResidues)\n{\n\t// Calculate the HBond energies\n\tfor (uint32_t i = 0; i + 1 < inResidues.size(); ++i)\n\t{\n\t\tauto& ri = inResidues[i];\n\t\t\n\t\tfor (uint32_t j = i + 1; j < inResidues.size(); ++j)\n\t\t{\n\t\t\tauto& rj = inResidues[j];\n\t\t\t\n\t\t\tif (Distance(ri.mCAlpha, rj.mCAlpha) < kMinimalCADistance)\n\t\t\t{\n\t\t\t\tCalculateHBondEnergy(ri, rj);\n\t\t\t\tif (j != i + 1)\n\t\t\t\t\tCalculateHBondEnergy(rj, ri);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// --------------------------------------------------------------------\n\nbool NoChainBreak(const Res* a, const Res* b)\n{\n\tbool result = a->mM.asymID() == b->mM.asymID();\n\tfor (auto r = a; result and r != b; r = r->mNext)\n\t{\n\t\tauto next = r->mNext;\n\t\tif (next == nullptr)\n\t\t\tresult = false;\n\t\telse\n\t\t\tresult = next->mNumber == r->mNumber + 1;\n\t}\n\treturn result;\n}\n\nbool NoChainBreak(const Res& a, const Res& b)\n{\n\treturn NoChainBreak(&a, &b);\n}\n\n// --------------------------------------------------------------------\n\nbool TestBond(const Res* a, const Res* b)\n{\n\treturn\n\t\t(a->mHBondAcceptor[0].residue == b and a->mHBondAcceptor[0].energy < kMaxHBondEnergy) or\n\t\t(a->mHBondAcceptor[1].residue == b and a->mHBondAcceptor[1].energy < kMaxHBondEnergy);\n}\n\n// --------------------------------------------------------------------\n\nBridgeType TestBridge(const Res& r1, const Res& r2)\n{\t\t\t\t\t\t\t\t\t\t// I.\ta\td\tII.\ta\td\t\tparallel    \n\tauto a = r1.mPrev;\t\t\t\t\t//\t\t  \\\t\t\t  /\n\tauto b = &r1;\t\t\t\t\t\t//\t\tb\te\t\tb\te\n\tauto c = r1.mNext;\t\t\t\t\t// \t\t  /\t\t\t  \\                      ..\n\tauto d = r2.mPrev;\t\t\t\t\t//\t\tc\tf\t\tc\tf\n\tauto e = &r2;\t\t\t\t\t\t//\n\tauto f = r2.mNext;\t\t\t\t\t// III.\ta <- f\tIV. a\t  f\t\tantiparallel\n\t\t\t\t\t\t\t\t\t\t//\t\t                                   \n\tBridgeType result = btNoBridge;\t\t//\t\tb\t e      b <-> e                  \n\t\t\t\t\t\t\t\t\t\t//                                          \n\t\t\t\t\t\t\t\t\t\t//\t\tc -> d\t\tc     d\n\t\t\t\t\t\t\t\t\t\t\n\tif (a and c and NoChainBreak(a, c) and d and f and NoChainBreak(d, f))\n\t{\n\t\tif ((TestBond(c, e) and TestBond(e, a)) or (TestBond(f, b) and TestBond(b, d)))\n\t\t\tresult = btParallel;\n\t\telse if ((TestBond(c, d) and TestBond(f, a)) or (TestBond(e, b) and TestBond(b, e)))\n\t\t\tresult = btAntiParallel;\n\t}\n\t\n\treturn result;\n}\n\n// --------------------------------------------------------------------\n// return true if any of the residues in bridge a is identical to any of the residues in bridge b\nbool Linked(const Bridge& a, const Bridge& b)\n{\n\treturn\n\t\tfind_first_of(a.i.begin(), a.i.end(), b.i.begin(), b.i.end()) != a.i.end() or\n\t\tfind_first_of(a.i.begin(), a.i.end(), b.j.begin(), b.j.end()) != a.i.end() or\n\t\tfind_first_of(a.j.begin(), a.j.end(), b.i.begin(), b.i.end()) != a.j.end() or\n\t\tfind_first_of(a.j.begin(), a.j.end(), b.j.begin(), b.j.end()) != a.j.end();\n}\n\n// --------------------------------------------------------------------\n\nvoid CalculateBetaSheets(std::vector<Res>& inResidues, DSSP_Statistics& stats)\n{\n\t// Calculate Bridges\n\tstd::vector<Bridge> bridges;\n\tif (inResidues.size() > 4)\n\t{\n\t\tfor (uint32_t i = 1; i + 4 < inResidues.size(); ++i)\n\t\t{\n\t\t\tauto& ri = inResidues[i];\n\t\t\t\n\t\t\tfor (uint32_t j = i + 3; j + 1 < inResidues.size(); ++j)\n\t\t\t{\n\t\t\t\tauto& rj = inResidues[j];\n\t\t\t\t\n\t\t\t\tBridgeType type = TestBridge(ri, rj);\n\t\t\t\tif (type == btNoBridge)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tbool found = false;\n\t\t\t\tfor (Bridge& bridge : bridges)\n\t\t\t\t{\n\t\t\t\t\tif (type != bridge.type or i != bridge.i.back() + 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\n\t\t\t\t\tif (type == btParallel and bridge.j.back() + 1 == j)\n\t\t\t\t\t{\n\t\t\t\t\t\tbridge.i.push_back(i);\n\t\t\t\t\t\tbridge.j.push_back(j);\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (type == btAntiParallel and bridge.j.front() - 1 == j)\n\t\t\t\t\t{\n\t\t\t\t\t\tbridge.i.push_back(i);\n\t\t\t\t\t\tbridge.j.push_front(j);\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (not found)\n\t\t\t\t{\n\t\t\t\t\tBridge bridge = {};\n\t\t\t\t\t\n\t\t\t\t\tbridge.type = type;\n\t\t\t\t\tbridge.i.push_back(i);\n\t\t\t\t\tbridge.chainI = ri.mM.asymID();\n\t\t\t\t\tbridge.j.push_back(j);\n\t\t\t\t\tbridge.chainJ = rj.mM.asymID();\n\t\t\t\t\t\n\t\t\t\t\tbridges.push_back(bridge);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// extend ladders\n\tstd::sort(bridges.begin(), bridges.end());\n\t\n\tfor (uint32_t i = 0; i < bridges.size(); ++i)\n\t{\n\t\tfor (uint32_t j = i + 1; j < bridges.size(); ++j)\n\t\t{\n\t\t\tuint32_t ibi = bridges[i].i.front();\n\t\t\tuint32_t iei = bridges[i].i.back();\n\t\t\tuint32_t jbi = bridges[i].j.front();\n\t\t\tuint32_t jei = bridges[i].j.back();\n\t\t\tuint32_t ibj = bridges[j].i.front();\n\t\t\tuint32_t iej = bridges[j].i.back();\n\t\t\tuint32_t jbj = bridges[j].j.front();\n\t\t\tuint32_t jej = bridges[j].j.back();\n\n\t\t\tif (bridges[i].type != bridges[j].type or\n\t\t\t\tNoChainBreak(inResidues[std::min(ibi, ibj)], inResidues[std::max(iei, iej)]) == false or\n\t\t\t\tNoChainBreak(inResidues[std::min(jbi, jbj)], inResidues[std::max(jei, jej)]) == false or\n\t\t\t\tibj - iei >= 6 or\n\t\t\t\t(iei >= ibj and ibi <= iej))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tbool bulge;\n\t\t\tif (bridges[i].type == btParallel)\n\t\t\t\tbulge = ((jbj - jei < 6 and ibj - iei < 3) or (jbj - jei < 3));\n\t\t\telse\n\t\t\t\tbulge = ((jbi - jej < 6 and ibj - iei < 3) or (jbi - jej < 3));\n\n\t\t\tif (bulge)\n\t\t\t{\n\t\t\t\tbridges[i].i.insert(bridges[i].i.end(), bridges[j].i.begin(), bridges[j].i.end());\n\t\t\t\tif (bridges[i].type == btParallel)\n\t\t\t\t\tbridges[i].j.insert(bridges[i].j.end(), bridges[j].j.begin(), bridges[j].j.end());\n\t\t\t\telse\n\t\t\t\t\tbridges[i].j.insert(bridges[i].j.begin(), bridges[j].j.begin(), bridges[j].j.end());\n\t\t\t\tbridges.erase(bridges.begin() + j);\n\t\t\t\t--j;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sheet\n\tstd::set<Bridge*> ladderset;\n\tfor (Bridge& bridge : bridges)\n\t{\n\t\tladderset.insert(&bridge);\n\t\t\n\t\tsize_t n = bridge.i.size();\n\t\tif (n > kHistogramSize)\n\t\t\tn = kHistogramSize;\n\t\t\n\t\tif (bridge.type == btParallel)\n\t\t\tstats.parallelBridgesPerLadderHistogram[n - 1] += 1;\n\t\telse\n\t\t\tstats.antiparallelBridgesPerLadderHistogram[n - 1] += 1;\n\t}\n\t\n\tuint32_t sheet = 1, ladder = 0;\n\twhile (not ladderset.empty())\n\t{\n\t\tstd::set<Bridge*> sheetset;\n\t\tsheetset.insert(*ladderset.begin());\n\t\tladderset.erase(ladderset.begin());\n\n\t\tbool done = false;\n\t\twhile (not done)\n\t\t{\n\t\t\tdone = true;\n\t\t\tfor (Bridge* a : sheetset)\n\t\t\t{\n\t\t\t\tfor (Bridge* b : ladderset)\n\t\t\t\t{\n\t\t\t\t\tif (Linked(*a, *b))\n\t\t\t\t\t{\n\t\t\t\t\t\tsheetset.insert(b);\n\t\t\t\t\t\tladderset.erase(b);\n\t\t\t\t\t\tdone = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (not done)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tfor (Bridge* bridge : sheetset)\n\t\t{\n\t\t\tbridge->ladder = ladder;\n\t\t\tbridge->sheet = sheet;\n\t\t\tbridge->link = sheetset;\n\t\t\t\n\t\t\t++ladder;\n\t\t}\n\t\t\n\t\tsize_t nrOfLaddersPerSheet = sheetset.size();\n\t\tif (nrOfLaddersPerSheet > kHistogramSize)\n\t\t\tnrOfLaddersPerSheet = kHistogramSize;\n\t\tif (nrOfLaddersPerSheet == 1 and (*sheetset.begin())->i.size() > 1)\n\t\t\tstats.laddersPerSheetHistogram[0] += 1;\n\t\telse if (nrOfLaddersPerSheet > 1)\n\t\t\tstats.laddersPerSheetHistogram[nrOfLaddersPerSheet - 1] += 1;\n\t\t\n\t\t++sheet;\n\t}\n\n\tfor (Bridge& bridge : bridges)\n\t{\n\t\t// find out if any of the i and j set members already have\n\t\t// a bridge assigned, if so, we're assigning bridge 2\n\t\t\n\t\tuint32_t betai = 0, betaj = 0;\n\t\t\n\t\tfor (uint32_t l : bridge.i)\n\t\t{\n\t\t\tif (inResidues[l].GetBetaPartner(0).residue != nullptr)\n\t\t\t{\n\t\t\t\tbetai = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tfor (uint32_t l : bridge.j)\n\t\t{\n\t\t\tif (inResidues[l].GetBetaPartner(0).residue != nullptr)\n\t\t\t{\n\t\t\t\tbetaj = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tSecondaryStructureType ss = ssBetabridge;\n\t\tif (bridge.i.size() > 1)\n\t\t\tss = ssStrand;\n\t\t\n\t\tif (bridge.type == btParallel)\n\t\t{\n\t\t\tstats.nrOfHBondsInParallelBridges += bridge.i.back() - bridge.i.front() + 2;\n\t\t\t\n\t\t\tstd::deque<uint32_t>::iterator j = bridge.j.begin();\n\t\t\tfor (uint32_t i : bridge.i)\n\t\t\t\tinResidues[i].SetBetaPartner(betai, inResidues[*j++], bridge.ladder, true);\n\n\t\t\tj = bridge.i.begin();\n\t\t\tfor (uint32_t i : bridge.j)\n\t\t\t\tinResidues[i].SetBetaPartner(betaj, inResidues[*j++], bridge.ladder, true);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstats.nrOfHBondsInAntiparallelBridges += bridge.i.back() - bridge.i.front() + 2;\n\n\t\t\tstd::deque<uint32_t>::reverse_iterator j = bridge.j.rbegin();\n\t\t\tfor (uint32_t i : bridge.i)\n\t\t\t\tinResidues[i].SetBetaPartner(betai, inResidues[*j++], bridge.ladder, false);\n\n\t\t\tj = bridge.i.rbegin();\n\t\t\tfor (uint32_t i : bridge.j)\n\t\t\t\tinResidues[i].SetBetaPartner(betaj, inResidues[*j++], bridge.ladder, false);\n\t\t}\n\n\t\tfor (uint32_t i = bridge.i.front(); i <= bridge.i.back(); ++i)\n\t\t{\n\t\t\tif (inResidues[i].GetSecondaryStructure() != ssStrand)\n\t\t\t\tinResidues[i].SetSecondaryStructure(ss);\n\t\t\tinResidues[i].SetSheet(bridge.sheet);\n\t\t}\n\n\t\tfor (uint32_t i = bridge.j.front(); i <= bridge.j.back(); ++i)\n\t\t{\n\t\t\tif (inResidues[i].GetSecondaryStructure() != ssStrand)\n\t\t\t\tinResidues[i].SetSecondaryStructure(ss);\n\t\t\tinResidues[i].SetSheet(bridge.sheet);\n\t\t}\n\t}\n}\n\n// --------------------------------------------------------------------\n// TODO: improve alpha helix calculation by better recognizing pi-helices \n\nvoid CalculateAlphaHelices(std::vector<Res>& inResidues, DSSP_Statistics& stats, bool inPreferPiHelices = true)\n{\n\t// Helix and Turn\n\tfor (HelixType helixType: { HelixType::rh_3_10, HelixType::rh_alpha, HelixType::rh_pi })\n\t{\n\t\tuint32_t stride = static_cast<uint32_t>(helixType) + 3;\n\n\t\tfor (uint32_t i = 0; i + stride < inResidues.size(); ++i)\n\t\t{\n\t\t\tif (NoChainBreak(inResidues[i], inResidues[i + stride]) and TestBond(&inResidues[i + stride], &inResidues[i]))\n\t\t\t{\n\t\t\t\tinResidues[i + stride].SetHelixFlag(helixType, Helix::End);\n\t\t\t\tfor (uint32_t j = i + 1; j < i + stride; ++j)\n\t\t\t\t{\n\t\t\t\t\tif (inResidues[j].GetHelixFlag(helixType) == Helix::None)\n\t\t\t\t\t\tinResidues[j].SetHelixFlag(helixType, Helix::Middle);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (inResidues[i].GetHelixFlag(helixType) == Helix::End)\n\t\t\t\t\tinResidues[i].SetHelixFlag(helixType, Helix::StartAndEnd);\n\t\t\t\telse\n\t\t\t\t\tinResidues[i].SetHelixFlag(helixType, Helix::Start);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (auto& r : inResidues)\n\t{\n\t\tdouble kappa = r.mM.kappa();\n\t\tr.SetBend(kappa != 360 and kappa > 70);\n\t}\n\n\tfor (uint32_t i = 1; i + 4 < inResidues.size(); ++i)\n\t{\n\t\tif (inResidues[i].IsHelixStart(HelixType::rh_alpha) and inResidues[i - 1].IsHelixStart(HelixType::rh_alpha))\n\t\t{\n\t\t\tfor (uint32_t j = i; j <= i + 3; ++j)\n\t\t\t\tinResidues[j].SetSecondaryStructure(ssAlphahelix);\n\t\t}\n\t}\n\n\tfor (uint32_t i = 1; i + 3 < inResidues.size(); ++i)\n\t{\n\t\tif (inResidues[i].IsHelixStart(HelixType::rh_3_10) and inResidues[i - 1].IsHelixStart(HelixType::rh_3_10))\n\t\t{\n\t\t\tbool empty = true;\n\t\t\tfor (uint32_t j = i; empty and j <= i + 2; ++j)\n\t\t\t\tempty = inResidues[j].GetSecondaryStructure() == ssLoop or inResidues[j].GetSecondaryStructure() == ssHelix_3;\n\t\t\tif (empty)\n\t\t\t{\n\t\t\t\tfor (uint32_t j = i; j <= i + 2; ++j)\n\t\t\t\t\tinResidues[j].SetSecondaryStructure(ssHelix_3);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (uint32_t i = 1; i + 5 < inResidues.size(); ++i)\n\t{\n\t\tif (inResidues[i].IsHelixStart(HelixType::rh_pi) and inResidues[i - 1].IsHelixStart(HelixType::rh_pi))\n\t\t{\n\t\t\tbool empty = true;\n\t\t\tfor (uint32_t j = i; empty and j <= i + 4; ++j)\n\t\t\t\tempty = inResidues[j].GetSecondaryStructure() == ssLoop or inResidues[j].GetSecondaryStructure() == ssHelix_5 or\n\t\t\t\t\t\t\t(inPreferPiHelices and inResidues[j].GetSecondaryStructure() == ssAlphahelix);\n\t\t\tif (empty)\n\t\t\t{\n\t\t\t\tfor (uint32_t j = i; j <= i + 4; ++j)\n\t\t\t\t\tinResidues[j].SetSecondaryStructure(ssHelix_5);\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\n\tfor (uint32_t i = 1; i + 1 < inResidues.size(); ++i)\n\t{\n\t\tif (inResidues[i].GetSecondaryStructure() == ssLoop)\n\t\t{\n\t\t\tbool isTurn = false;\n\t\t\tfor (HelixType helixType: { HelixType::rh_3_10, HelixType::rh_alpha, HelixType::rh_pi })\n\t\t\t{\n\t\t\t\tuint32_t stride = 3 + static_cast<uint32_t>(helixType);\n\t\t\t\tfor (uint32_t k = 1; k < stride and not isTurn; ++k)\n\t\t\t\t\tisTurn = (i >= k) and inResidues[i - k].IsHelixStart(helixType);\n\t\t\t}\n\t\t\t\n\t\t\tif (isTurn)\n\t\t\t\tinResidues[i].SetSecondaryStructure(ssTurn);\n\t\t\telse if (inResidues[i].IsBend())\n\t\t\t\tinResidues[i].SetSecondaryStructure(ssBend);\n\t\t}\n\t}\n\n\tstd::string asym;\n\tsize_t helixLength = 0;\n\tfor (auto r: inResidues)\n\t{\n\t\tif (r.mM.asymID() != asym)\n\t\t{\n\t\t\thelixLength = 0;\n\t\t\tasym = r.mM.asymID();\n\t\t}\n\n\t\tif (r.GetSecondaryStructure() == ssAlphahelix)\n\t\t\t++helixLength;\n\t\telse if (helixLength > 0)\n\t\t{\n\t\t\tif (helixLength > kHistogramSize)\n\t\t\t\thelixLength = kHistogramSize;\n\n\t\t\tstats.residuesPerAlphaHelixHistogram[helixLength - 1] += 1;\n\t\t\thelixLength = 0;\n\t\t}\n\t}\n}\n\n// --------------------------------------------------------------------\n\nvoid CalculatePPHelices(std::vector<Res>& inResidues, DSSP_Statistics& stats, int stretch_length)\n{\n\tsize_t N = inResidues.size();\n\n\tconst float epsilon = 29;\n\tconst float phi_min = -75 - epsilon;\n\tconst float phi_max = -75 + epsilon;\n\tconst float psi_min = 145 - epsilon;\n\tconst float psi_max = 145 + epsilon;\n\n\tstd::vector<float> phi(N), psi(N);\n\n\tfor (uint32_t i = 1; i + 1 < inResidues.size(); ++i)\n\t{\n\t\tphi[i] = inResidues[i].mM.phi();\n\t\tpsi[i] = inResidues[i].mM.psi();\n\t}\n\n\tfor (uint32_t i = 1; i + 3 < inResidues.size(); ++i)\n\t{\n\t\tswitch (stretch_length)\n\t\t{\n\t\t\tcase 2:\n\t\t\t{\n\t\t\t\tif (phi_min > phi[i + 0] or phi[i + 0] > phi_max or\n\t\t\t\t\tphi_min > phi[i + 1] or phi[i + 1] > phi_max)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (psi_min > psi[i + 0] or psi[i + 0] > psi_max or\n\t\t\t\t\tpsi_min > psi[i + 1] or psi[i + 1] > psi_max)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// auto phi_avg = (phi[i + 0] + phi[i + 1]) / 2;\n\t\t\t\t// auto phi_sq = (phi[i + 0] - phi_avg) * (phi[i + 0] - phi_avg) +\n\t\t\t\t// \t\t\t  (phi[i + 1] - phi_avg) * (phi[i + 1] - phi_avg);\n\t\t\t\t\n\t\t\t\t// if (phi_sq >= 200)\n\t\t\t\t// \tcontinue;\n\n\t\t\t\t// auto psi_avg = (psi[i + 0] + psi[i + 1]) / 2;\n\t\t\t\t// auto psi_sq = (psi[i + 0] - psi_avg) * (psi[i + 0] - psi_avg) +\n\t\t\t\t// \t\t\t  (psi[i + 1] - psi_avg) * (psi[i + 1] - psi_avg);\n\n\t\t\t\t// if (psi_sq >= 200)\n\t\t\t\t// \tcontinue;\n\n\t\t\t\tswitch (inResidues[i].GetHelixFlag(HelixType::rh_pp))\n\t\t\t\t{\n\t\t\t\t\tcase Helix::None:\n\t\t\t\t\t\tinResidues[i].SetHelixFlag(HelixType::rh_pp, Helix::Start);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\t\tcase Helix::End:\n\t\t\t\t\t\tinResidues[i].SetHelixFlag(HelixType::rh_pp, Helix::Middle);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tinResidues[i + 1].SetHelixFlag(HelixType::rh_pp, Helix::End);\n\n\t\t\t\tif (inResidues[i].GetSecondaryStructure() == SecondaryStructureType::ssLoop)\n\t\t\t\t\tinResidues[i].SetSecondaryStructure(SecondaryStructureType::ssHelix_PPII);\n\t\t\t\tif (inResidues[i + 1].GetSecondaryStructure() == SecondaryStructureType::ssLoop)\n\t\t\t\t\tinResidues[i + 1].SetSecondaryStructure(SecondaryStructureType::ssHelix_PPII);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase 3:\n\t\t\t{\n\t\t\t\tif (phi_min > phi[i + 0] or phi[i + 0] > phi_max or\n\t\t\t\t\tphi_min > phi[i + 1] or phi[i + 1] > phi_max or\n\t\t\t\t\tphi_min > phi[i + 2] or phi[i + 2] > phi_max)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (psi_min > psi[i + 0] or psi[i + 0] > psi_max or\n\t\t\t\t\tpsi_min > psi[i + 1] or psi[i + 1] > psi_max or\n\t\t\t\t\tpsi_min > psi[i + 2] or psi[i + 2] > psi_max)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// auto phi_avg = (phi[i + 0] + phi[i + 1] + phi[i + 2]) / 3;\n\t\t\t\t// auto phi_sq = (phi[i + 0] - phi_avg) * (phi[i + 0] - phi_avg) +\n\t\t\t\t// \t\t\t  (phi[i + 1] - phi_avg) * (phi[i + 1] - phi_avg) +\n\t\t\t\t// \t\t\t  (phi[i + 2] - phi_avg) * (phi[i + 2] - phi_avg);\n\t\t\t\t\n\t\t\t\t// if (phi_sq >= 300)\n\t\t\t\t// \tcontinue;\n\n\t\t\t\t// auto psi_avg = (psi[i + 0] + psi[i + 1] + psi[i + 2]) / 3;\n\t\t\t\t// auto psi_sq = (psi[i + 0] - psi_avg) * (psi[i + 0] - psi_avg) +\n\t\t\t\t// \t\t\t  (psi[i + 1] - psi_avg) * (psi[i + 1] - psi_avg) +\n\t\t\t\t// \t\t\t  (psi[i + 2] - psi_avg) * (psi[i + 2] - psi_avg);\n\n\t\t\t\t// if (psi_sq >= 300)\n\t\t\t\t// \tcontinue;\n\n\t\t\t\tswitch (inResidues[i].GetHelixFlag(HelixType::rh_pp))\n\t\t\t\t{\n\t\t\t\t\tcase Helix::None:\n\t\t\t\t\t\tinResidues[i].SetHelixFlag(HelixType::rh_pp, Helix::Start);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\t\tcase Helix::End:\n\t\t\t\t\t\tinResidues[i].SetHelixFlag(HelixType::rh_pp, Helix::StartAndEnd);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tinResidues[i + 1].SetHelixFlag(HelixType::rh_pp, Helix::Middle);\n\t\t\t\tinResidues[i + 2].SetHelixFlag(HelixType::rh_pp, Helix::End);\n\n\t\t\t\tif (inResidues[i + 0].GetSecondaryStructure() == SecondaryStructureType::ssLoop)\n\t\t\t\t\tinResidues[i + 0].SetSecondaryStructure(SecondaryStructureType::ssHelix_PPII);\n\n\t\t\t\tif (inResidues[i + 1].GetSecondaryStructure() == SecondaryStructureType::ssLoop)\n\t\t\t\t\tinResidues[i + 1].SetSecondaryStructure(SecondaryStructureType::ssHelix_PPII);\n\t\t\t\t\n\t\t\t\tif (inResidues[i + 2].GetSecondaryStructure() == SecondaryStructureType::ssLoop)\n\t\t\t\t\tinResidues[i + 2].SetSecondaryStructure(SecondaryStructureType::ssHelix_PPII);\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tthrow std::runtime_error(\"Unsupported stretch length\");\n\t\t}\n\t}\n}\n\n// --------------------------------------------------------------------\n\nstruct DSSPImpl\n{\n\tDSSPImpl(const Structure& s, int min_poly_proline_stretch_length);\n\t\n\tconst Structure&\t\t\tmStructure;\n\tconst std::list<Polymer>&\tmPolymers;\n\tstd::vector<Res>\t\t\tmResidues;\n\tstd::vector<std::pair<Res*,Res*>> mSSBonds;\n\n\tint m_min_poly_proline_stretch_length;\n\n\tauto findRes(const std::string& asymID, int seqID)\n\t{\n\t\treturn std::find_if(mResidues.begin(), mResidues.end(), [&](auto& r) { return r.mM.asymID() == asymID and r.mM.seqID() == seqID; });\n\t}\n\n\tvoid calculateSurface();\n\tvoid calculateSecondaryStructure();\n\n\tDSSP_Statistics\t\t\t\tmStats = {};\n};\n\n// --------------------------------------------------------------------\n\nDSSPImpl::DSSPImpl(const Structure& s, int min_poly_proline_stretch_length)\n\t: mStructure(s)\n\t, mPolymers(mStructure.polymers())\n\t, m_min_poly_proline_stretch_length(min_poly_proline_stretch_length)\n{\n\tsize_t nRes = accumulate(mPolymers.begin(), mPolymers.end(),\n\t\t0ULL, [](size_t s, auto& p) { return s + p.size(); });\n\n\tmStats.nrOfChains = static_cast<uint32_t>(mPolymers.size());\n\n\tmResidues.reserve(nRes);\n\tint resNumber = 0;\n\t\n\tfor (auto& p: mPolymers)\n\t{\n\t\tChainBreak brk = ChainBreak::NewChain;\n\n\t\tfor (auto& m: p)\n\t\t{\n\t\t\tif (not m.isComplete())\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\t++resNumber;\n\n\t\t\tif (not mResidues.empty() and\n\t\t\t\tDistance(mResidues.back().mC, m.atomByID(\"N\").location()) > kMaxPeptideBondLength)\n\t\t\t{\n\t\t\t\tif (mResidues.back().mM.asymID() == m.asymID())\n\t\t\t\t{\n\t\t\t\t\t++mStats.nrOfChains;\n\t\t\t\t\tbrk = ChainBreak::Gap;\n\t\t\t\t}\n\t\t\t\t++resNumber;\n\t\t\t}\n\n\t\t\tmResidues.emplace_back(m, resNumber, brk);\n\n\t\t\tbrk = ChainBreak::None;\n\t\t}\n\t}\n\n\tmStats.nrOfResidues = static_cast<uint32_t>(mResidues.size());\n\n\tfor (size_t i = 0; i + 1 < mResidues.size(); ++i)\n\t{\n\t\tmResidues[i].mNext = &mResidues[i + 1];\n\t\tmResidues[i + 1].mPrev = &mResidues[i];\n\t\t\n\t\tmResidues[i + 1].assignHydrogen();\n\t}\n}\n\nvoid DSSPImpl::calculateSecondaryStructure()\n{\n\tauto& db = mStructure.getFile().data();\n\tfor (auto r: db[\"struct_conn\"].find(cif::Key(\"conn_type_id\") == \"disulf\"))\n\t{\n\t\tstd::string asym1, asym2;\n\t\tint seq1, seq2;\n\t\tcif::tie(asym1, seq1, asym2, seq2) = r.get(\"ptnr1_label_asym_id\", \"ptnr1_label_seq_id\", \"ptnr2_label_asym_id\", \"ptnr2_label_seq_id\");\n\n\t\tauto r1 = findRes(asym1, seq1);\n\t\tif (r1 == mResidues.end())\n\t\t{\n\t\t\tif (cif::VERBOSE)\n\t\t\t\tstd::cerr << \"Missing (incomplete?) residue for SS bond when trying to find \" << asym1 << '/' << seq1 << std::endl;\n\t\t\tcontinue;\n\t\t\t// throw std::runtime_error(\"Invalid file, missing residue for SS bond\");\n\t\t}\n\n\t\tauto r2 = findRes(asym2, seq2);\n\t\tif (r2 == mResidues.end())\n\t\t{\n\t\t\tif (cif::VERBOSE)\n\t\t\t\tstd::cerr << \"Missing (incomplete?) residue for SS bond when trying to find \" << asym2 << '/' << seq2 << std::endl;\n\t\t\tcontinue;\n\t\t\t// throw std::runtime_error(\"Invalid file, missing residue for SS bond\");\n\t\t}\n\n\t\tmSSBonds.emplace_back(&*r1, &*r2);\n\t}\n\n\tCalculateHBondEnergies(mResidues);\n\tCalculateBetaSheets(mResidues, mStats);\n\tCalculateAlphaHelices(mResidues, mStats);\n\tCalculatePPHelices(mResidues, mStats, m_min_poly_proline_stretch_length);\n\n\tif (cif::VERBOSE > 1)\n\t{\n\t\tfor (auto& r: mResidues)\n\t\t{\n\t\t\tauto& m = r.mM;\n\t\t\t\n\t\t\tchar helix[5] = { };\n\t\t\tfor (HelixType helixType: { HelixType::rh_3_10, HelixType::rh_alpha, HelixType::rh_pi, HelixType::rh_pp\t})\n\t\t\t{\n\t\t\t\tswitch (r.GetHelixFlag(helixType))\n\t\t\t\t{\n\t\t\t\t\tcase Helix::Start:\t\t\thelix[static_cast<int>(helixType)] = '>'; break;\n\t\t\t\t\tcase Helix::Middle:\t\t\thelix[static_cast<int>(helixType)] = helixType == HelixType::rh_pp ? 'P' : '3' + static_cast<char>(helixType); break;\n\t\t\t\t\tcase Helix::StartAndEnd:\thelix[static_cast<int>(helixType)] = 'X'; break;\n\t\t\t\t\tcase Helix::End:\t\t\thelix[static_cast<int>(helixType)] = '<'; break;\n\t\t\t\t\tcase Helix::None:\t\t\thelix[static_cast<int>(helixType)] = ' '; break;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tauto id = m.asymID() + ':' + std::to_string(m.seqID()) + '/' + m.compoundID();\n\t\t\t\n\t\t\tstd::cerr << id << std::string(12 - id.length(), ' ')\n\t\t\t\t\t<< char(r.mSecondaryStructure) << ' '\n\t\t\t\t\t<< helix\n\t\t\t\t\t<< std::endl;\n\t\t}\n\t}\n\n\t// finish statistics\n\tmStats.nrOfSSBridges = static_cast<uint32_t>(mSSBonds.size());\n\n\tmStats.nrOfIntraChainSSBridges = 0;\n\tuint8_t ssBondNr = 0;\n\tfor (const auto& [a, b]: mSSBonds)\n\t{\n\t\tif (a == b)\n\t\t{\n\t\t\tif (cif::VERBOSE)\n\t\t\t\tstd::cerr << \"In the SS bonds list, the residue \" << a->mM << \" is bonded to itself\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (a->mM.asymID() == b->mM.asymID() and NoChainBreak(a, b))\n\t\t\t++mStats.nrOfIntraChainSSBridges;\n\n\t\ta->mSSBridgeNr = b->mSSBridgeNr = ++ssBondNr;\n\t}\n\n\tmStats.nrOfHBonds = 0;\n\tfor (auto& r: mResidues)\n\t{\n\t\tauto donor = r.mHBondDonor;\n\n\t\tfor (int i = 0; i < 2; ++i)\n\t\t{\n\t\t\tif (donor[i].residue != nullptr and donor[i].energy < kMaxHBondEnergy)\n\t\t\t{\n\t\t\t\t++mStats.nrOfHBonds;\n\t\t\t\tauto k = donor[i].residue->mNumber - r.mNumber;\n\t\t\t\tif (k >= -5 and k <= 5)\n\t\t\t\t\tmStats.nrOfHBondsPerDistance[k + 5] += 1;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid DSSPImpl::calculateSurface()\n{\n\tCalculateAccessibilities(mResidues, mStats);\n}\n\n// --------------------------------------------------------------------\n\nconst Monomer& DSSP::ResidueInfo::residue() const\n{\n\treturn mImpl->mM;\n}\n\nstd::string DSSP::ResidueInfo::alt_id() const\n{\n\treturn mImpl->mAltID;\n}\n\nChainBreak DSSP::ResidueInfo::chainBreak() const\n{\n\treturn mImpl->mChainBreak;\n}\n\nint DSSP::ResidueInfo::nr() const\n{\n\treturn mImpl->mNumber;\n}\n\nSecondaryStructureType DSSP::ResidueInfo::ss() const\n{\n\treturn mImpl->mSecondaryStructure;\n}\n\nint DSSP::ResidueInfo::ssBridgeNr() const\n{\n\treturn mImpl->mSSBridgeNr;\n}\n\nHelix DSSP::ResidueInfo::helix(HelixType helixType) const\n{\n\treturn mImpl->GetHelixFlag(helixType);\n}\n\nbool DSSP::ResidueInfo::bend() const\n{\n\treturn mImpl->IsBend();\n}\n\ndouble DSSP::ResidueInfo::accessibility() const\n{\n\treturn mImpl->mAccessibility;\n}\n\nstd::tuple<DSSP::ResidueInfo,int,bool> DSSP::ResidueInfo::bridgePartner(int i) const\n{\n\tauto bp = mImpl->GetBetaPartner(i);\n\n\tResidueInfo ri(bp.residue);\n\n\treturn std::make_tuple(std::move(ri), bp.ladder, bp.parallel);\n}\n\nint DSSP::ResidueInfo::sheet() const\n{\n\treturn mImpl->GetSheet();\n}\n\nstd::tuple<DSSP::ResidueInfo,double> DSSP::ResidueInfo::acceptor(int i) const\n{\n\tauto& a = mImpl->mHBondAcceptor[i];\n\treturn { ResidueInfo(a.residue), a.energy };\n}\n\nstd::tuple<DSSP::ResidueInfo,double> DSSP::ResidueInfo::donor(int i) const\n{\n\tauto& d = mImpl->mHBondDonor[i];\n\treturn { ResidueInfo(d.residue), d.energy };\n}\n\n// --------------------------------------------------------------------\n\nDSSP::iterator::iterator(Res* res)\n\t: mCurrent(res)\n{\n}\n\nDSSP::iterator::iterator(const iterator& i)\n\t: mCurrent(i.mCurrent)\n{\n}\n\nDSSP::iterator& DSSP::iterator::operator=(const iterator& i)\n{\n\tmCurrent = i.mCurrent;\n\treturn *this;\n}\n\nDSSP::iterator& DSSP::iterator::operator++()\n{\n\t++mCurrent.mImpl;\n\treturn *this;\n}\n\n// --------------------------------------------------------------------\n\nDSSP::DSSP(const Structure& s, int min_poly_proline_stretch, bool calculateSurfaceAccessibility)\n\t: mImpl(new DSSPImpl(s, min_poly_proline_stretch))\n{\n\tif (calculateSurfaceAccessibility)\n\t{\n\t\tstd::thread t(std::bind(&DSSPImpl::calculateSurface, mImpl));\n\t\tmImpl->calculateSecondaryStructure();\n\t\tt.join();\n\t}\n\telse\n\t\tmImpl->calculateSecondaryStructure();\n}\n\nDSSP::~DSSP()\n{\n\tdelete mImpl;\n}\n\nDSSP::iterator DSSP::begin() const\n{\n\treturn iterator(mImpl->mResidues.empty() ? nullptr : mImpl->mResidues.data());\n}\n\nDSSP::iterator DSSP::end() const\n{\n\t// careful now, MSVC is picky when it comes to dereferencing iterators that are at the end.\n\tRes* res = nullptr;\n\tif (not mImpl->mResidues.empty())\n\t{\n\t\tres = mImpl->mResidues.data();\n\t\tres += mImpl->mResidues.size();\n\t}\n\n\treturn iterator(res);\n}\n\nSecondaryStructureType DSSP::operator()(const std::string& inAsymID, int inSeqID) const\n{\n\tSecondaryStructureType result = ssLoop;\n\tauto i = find_if(mImpl->mResidues.begin(), mImpl->mResidues.end(),\n\t\t[&](auto& r) { return r.mM.asymID() == inAsymID and r.mM.seqID() == inSeqID; });\n\tif (i != mImpl->mResidues.end())\n\t\tresult = i->mSecondaryStructure;\n\telse if (cif::VERBOSE)\n\t\tstd::cerr << \"Could not find secondary structure for \" << inAsymID << ':' << inSeqID << std::endl;\n\treturn result;\n}\n\nSecondaryStructureType DSSP::operator()(const Monomer& m) const\n{\n\treturn operator()(m.asymID(), m.seqID());\n}\n\ndouble DSSP::accessibility(const std::string& inAsymID, int inSeqID) const\n{\n\tSecondaryStructureType result = ssLoop;\n\tauto i = find_if(mImpl->mResidues.begin(), mImpl->mResidues.end(),\n\t\t[&](auto& r) { return r.mM.asymID() == inAsymID and r.mM.seqID() == inSeqID; });\n\tif (i != mImpl->mResidues.end())\n\t\tresult = i->mSecondaryStructure;\n\telse if (cif::VERBOSE)\n\t\tstd::cerr << \"Could not find secondary structure for \" << inAsymID << ':' << inSeqID << std::endl;\n\treturn result;\n}\n\ndouble DSSP::accessibility(const Monomer& m) const\n{\n\treturn accessibility(m.asymID(), m.seqID());\n}\n\nbool DSSP::isAlphaHelixEndBeforeStart(const Monomer& m) const\n{\n\treturn isAlphaHelixEndBeforeStart(m.asymID(), m.seqID());\n}\n\nbool DSSP::isAlphaHelixEndBeforeStart(const std::string& inAsymID, int inSeqID) const\n{\n\tauto i = find_if(mImpl->mResidues.begin(), mImpl->mResidues.end(),\n\t\t[&](auto& r) { return r.mM.asymID() == inAsymID and r.mM.seqID() == inSeqID; });\n\n\tbool result = false;\n\n\tif (i != mImpl->mResidues.end() and i + 1 != mImpl->mResidues.end())\n\t\tresult = i->GetHelixFlag(HelixType::rh_alpha) == Helix::End and (i + 1)->GetHelixFlag(HelixType::rh_alpha) == Helix::Start;\n\telse if (cif::VERBOSE)\n\t\tstd::cerr << \"Could not find secondary structure for \" << inAsymID << ':' << inSeqID << std::endl;\n\n\treturn result;\n}\n\nDSSP_Statistics DSSP::GetStatistics() const\n{\n\treturn mImpl->mStats;\n}\n\n}\n", "meta": {"hexsha": "dd1907eeb5e1b69b4365905619eef2451db62a5c", "size": 40538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Secondary.cpp", "max_stars_repo_name": "PDB-REDO/libcifpp", "max_stars_repo_head_hexsha": "f97e742daa7c1cfd0670ad00d3aef004708a3461", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-01-12T07:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:44:14.000Z", "max_issues_repo_path": "src/Secondary.cpp", "max_issues_repo_name": "PDB-REDO/libcifpp", "max_issues_repo_head_hexsha": "f97e742daa7c1cfd0670ad00d3aef004708a3461", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-03-11T17:53:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T15:06:04.000Z", "max_forks_repo_path": "src/Secondary.cpp", "max_forks_repo_name": "PDB-REDO/libcifpp", "max_forks_repo_head_hexsha": "f97e742daa7c1cfd0670ad00d3aef004708a3461", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-02-08T00:45:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T22:37:22.000Z", "avg_line_length": 26.5127534336, "max_line_length": 144, "alphanum_fraction": 0.6206028911, "num_tokens": 13524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624720889433, "lm_q2_score": 0.02800752030174629, "lm_q1q2_score": 0.006624233595395952}}
{"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\n#define BOOST_PYTHON_MAX_ARITY 40\n#include <boost/python.hpp>\n#include <cmath>\n#include <iostream>\n\n#include \"numpy_bind.hh\"\n\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n#include \"graph_filtering.hh\"\n\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_properties.hh\"\n#include \"graph_util.hh\"\n\n#include \"random.hh\"\n\n#include \"config.h\"\n#include \"graph_blockmodel.hh\"\n#include \"graph_blockmodel_overlap.hh\"\n\n\nusing namespace boost;\nusing namespace graph_tool;\n\nnamespace graph_tool\n{\ntemplate <class Eprop, class Vprop, class VEprop>\nstruct move_sweep_overlap_dispatch\n{\n    move_sweep_overlap_dispatch(Eprop eweight, Vprop vweight,\n                                boost::any egroups, VEprop esrcpos,\n                                VEprop etgtpos, Vprop label, vector<int>& vlist,\n                                bool deg_corr, bool dense, bool multigraph,\n                                bool parallel_edges, double beta,\n                                bool sequential, bool parallel,\n                                bool random_move, double c, bool node_coherent,\n                                bool verbose, size_t max_edge_index,\n                                size_t nmerges, size_t niter, Vprop merge_map,\n                                overlap_stats_t& overlap_stats,\n                                overlap_partition_stats_t& partition_stats,\n                                rng_t& rng, double& S, size_t& nmoves,\n                                GraphInterface& bgi)\n\n        : eweight(eweight), vweight(vweight), oegroups(egroups), esrcpos(esrcpos),\n          etgtpos(etgtpos), label(label), vlist(vlist),\n          deg_corr(deg_corr), dense(dense), multigraph(multigraph),\n          parallel_edges(parallel_edges), beta(beta), sequential(sequential),\n          parallel(parallel), random_move(random_move), c(c),\n          node_coherent(node_coherent), verbose(verbose),\n          max_edge_index(max_edge_index), nmerges(nmerges),\n          niter(niter), merge_map(merge_map), overlap_stats(overlap_stats),\n          partition_stats(partition_stats), rng(rng), S(S), nmoves(nmoves), bgi(bgi)\n    {}\n\n    Eprop eweight;\n    Vprop vweight;\n    boost::any oegroups;\n    VEprop esrcpos;\n    VEprop etgtpos;\n    Vprop label;\n    size_t n;\n    vector<int>& vlist;\n    bool deg_corr;\n    bool dense;\n    bool multigraph;\n    bool parallel_edges;\n    double beta;\n    bool sequential;\n    bool parallel;\n    bool random_move;\n    double c;\n    bool node_coherent;\n    bool verbose;\n    size_t max_edge_index;\n    size_t nmerges;\n    size_t niter;\n    Vprop merge_map;\n    overlap_stats_t& overlap_stats;\n    overlap_partition_stats_t& partition_stats;\n    rng_t& rng;\n    double& S;\n    size_t& nmoves;\n    GraphInterface& bgi;\n\n    template <class Graph>\n    void operator()(Eprop mrs, Vprop mrp, Vprop mrm, Vprop wr, Vprop b,\n                    Graph& g, boost::any& emat, boost::any sampler,\n                    boost::any cavity_sampler, bool weighted) const\n    {\n        if (is_directed::apply<Graph>::type::value)\n        {\n            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, cavity_sampler,\n                     bgi.GetGraph(), weighted);\n        }\n        else\n        {\n            UndirectedAdaptor<GraphInterface::multigraph_t> ug(bgi.GetGraph());\n            dispatch(mrs, mrp, mrm, wr, b, g, emat, sampler, cavity_sampler, ug,\n                     weighted);\n        }\n    }\n\n    template <class Graph, class BGraph>\n    void dispatch(Eprop& mrs, Vprop& mrp, Vprop& mrm, Vprop& wr, Vprop& b,\n                  Graph& g, boost::any& aemat, boost::any asampler,\n                  boost::any& cavity_sampler, BGraph& bg, bool weighted) const\n    {\n        if (weighted)\n        {\n            typedef typename property_map_type::apply<DynamicSampler<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,\n                                                      GraphInterface::vertex_index_map_t>::type vemap_t;\n            vemap_t egroups = any_cast<vemap_t>(oegroups);\n            dispatch(mrs, mrp, mrm, wr, b, g, aemat, asampler, cavity_sampler,\n                     bg, egroups);\n        }\n        else\n        {\n            typedef typename property_map_type::apply<vector<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,\n                                                      GraphInterface::vertex_index_map_t>::type vemap_t;\n            vemap_t egroups = any_cast<vemap_t>(oegroups);\n            dispatch(mrs, mrp, mrm, wr, b, g, aemat, asampler, cavity_sampler,\n                     bg, egroups);\n        }\n    }\n\n    template <class Graph, class BGraph, class Egroups>\n    void dispatch(Eprop& mrs, Vprop& mrp, Vprop& mrm, Vprop& wr, Vprop& b,\n                  Graph& g, boost::any& aemat, boost::any& asampler,\n                  boost::any& acavity_sampler, BGraph& bg, Egroups& egroups) const\n    {\n        try\n        {\n            typedef typename get_emat_t::apply<BGraph>::type emat_t;\n            emat_t& emat = any_cast<emat_t&>(aemat);\n            size_t B = num_vertices(bg);\n            size_t max_BE = is_directed::apply<Graph>::type::value ?\n                B * B : (B * (B + 1)) / 2;\n            dispatch(mrs.get_unchecked(max_BE), mrp, mrm, wr, b, g,\n                     asampler, acavity_sampler, bg, egroups, emat);\n        }\n        catch (bad_any_cast&)\n        {\n            typedef typename get_ehash_t::apply<BGraph>::type emat_t;\n            emat_t& emat = any_cast<emat_t&>(aemat);\n            dispatch(mrs, mrp, mrm, wr, b, g, asampler, acavity_sampler,\n                     bg, egroups, emat);\n        }\n    }\n\n    template <class Graph, class BGraph, class Egroups, class Emat, class MEprop>\n    void dispatch(MEprop mrs, Vprop& mrp, Vprop& mrm, Vprop& wr, Vprop& b,\n                  Graph& g, boost::any& asampler, boost::any& acavity_sampler,\n                  BGraph& bg, Egroups& egroups, Emat& emat) const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n\n        size_t eidx = random_move ? 1 : max_edge_index;\n\n        typedef typename property_map<Graph, vertex_index_t>::type vindex_map_t;\n        typedef typename property_map_type::apply<Sampler<vertex_t, boost::mpl::false_>,\n                                                  vindex_map_t>::type::unchecked_t\n            sampler_map_t;\n        sampler_map_t sampler = any_cast<sampler_map_t>(asampler);\n        sampler_map_t cavity_sampler = any_cast<sampler_map_t>(acavity_sampler);\n\n        ConstantPropertyMap<int, typename graph_traits<Graph>::edge_descriptor> ce(0);\n        ConstantPropertyMap<std::array<int, 1>, typename graph_traits<Graph>::vertex_descriptor> cv({-1});\n        IdentityArrayPropertyMap<typename graph_traits<Graph>::vertex_descriptor> vmap;\n        boost::typed_identity_property_map<int> identity;\n\n        vector<size_t> free_blocks;\n        auto state = make_block_state(g,\n                                      eweight.get_unchecked(max_edge_index),\n                                      vweight.get_unchecked(num_vertices(g)),\n                                      b.get_unchecked(num_vertices(g)),\n                                      bg, emat, mrs,\n                                      mrp.get_unchecked(num_vertices(bg)),\n                                      mrm.get_unchecked(num_vertices(bg)),\n                                      wr.get_unchecked(num_vertices(bg)),\n                                      egroups.get_unchecked(num_vertices(bg)),\n                                      esrcpos.get_unchecked(eidx),\n                                      etgtpos.get_unchecked(eidx),\n                                      sampler, cavity_sampler,\n                                      partition_stats, overlap_stats,\n                                      identity, identity, free_blocks,\n                                      false, false, true);\n\n        vector<decltype(state)> states = {state};\n        vector<SingleEntrySet<Graph>> m_entries(1);\n\n        if (nmerges == 0)\n        {\n            if (!node_coherent)\n            {\n                move_sweep_overlap(states, m_entries, overlap_stats,\n                                   wr.get_unchecked(num_vertices(bg)),\n                                   b.get_unchecked(num_vertices(g)), cv,\n                                   vmap, label.get_unchecked(num_vertices(bg)),\n                                   vlist, deg_corr, dense, multigraph, beta,\n                                   vweight.get_unchecked(num_vertices(g)), g,\n                                   sequential, parallel, random_move, c, niter,\n                                   num_vertices(bg), verbose, rng, S, nmoves);\n            }\n            else\n            {\n                vector<EntrySet<Graph>> m_entries(1, EntrySet<Graph>(num_vertices(bg)));\n                coherent_move_sweep_overlap(states, m_entries, overlap_stats,\n                                            wr.get_unchecked(num_vertices(bg)),\n                                            b.get_unchecked(num_vertices(g)), cv,\n                                            vmap, label.get_unchecked(num_vertices(bg)),\n                                            vlist, deg_corr, dense, multigraph, beta,\n                                            vweight.get_unchecked(num_vertices(g)), g,\n                                            sequential,  random_move, c,\n                                            false, niter,\n                                            num_vertices(bg), rng, S, nmoves);\n            }\n        }\n        else\n        {\n            merge_sweep_overlap(states, m_entries, overlap_stats,\n                                wr.get_unchecked(num_vertices(bg)),\n                                b.get_unchecked(num_vertices(g)), ce, cv, vmap,\n                                label.get_unchecked(num_vertices(bg)), vlist,\n                                deg_corr, dense, multigraph, g, random_move,\n                                false, nmerges, niter,\n                                num_vertices(bg), rng, S, nmoves);\n        }\n    }\n};\n\n\nboost::python::object\ndo_move_sweep_overlap(GraphInterface& gi, GraphInterface& bgi, boost::any& emat,\n                      boost::any sampler, boost::any cavity_sampler,\n                      boost::any omrs, boost::any omrp, boost::any omrm,\n                      boost::any owr, boost::any ob, boost::any olabel,\n                      vector<int>& vlist, bool deg_corr, bool dense,\n                      bool multigraph, bool parallel_edges, boost::any oeweight,\n                      boost::any ovweight, boost::any oegroups,\n                      boost::any oesrcpos, boost::any oetgtpos, double beta,\n                      bool sequential, bool parallel, bool random_move,\n                      double c, bool node_coherent, bool weighted,\n                      size_t nmerges, boost::any omerge_map, size_t niter,\n                      overlap_stats_t& overlap_stats,\n                      overlap_partition_stats_t& partition_stats, bool verbose,\n                      rng_t& rng)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        vemap_t;\n    emap_t mrs = any_cast<emap_t>(omrs);\n    vmap_t mrp = any_cast<vmap_t>(omrp);\n    vmap_t mrm = any_cast<vmap_t>(omrm);\n    vmap_t wr = any_cast<vmap_t>(owr);\n    vmap_t b = any_cast<vmap_t>(ob);\n    vmap_t label = any_cast<vmap_t>(olabel);\n    emap_t eweight = any_cast<emap_t>(oeweight);\n    vmap_t vweight = any_cast<vmap_t>(ovweight);\n\n    vemap_t esrcpos = any_cast<vemap_t>(oesrcpos);\n    vemap_t etgtpos = any_cast<vemap_t>(oetgtpos);\n\n    double S = 0;\n    size_t nmoves = 0;\n\n    vmap_t merge_map = any_cast<vmap_t>(omerge_map);\n\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind(move_sweep_overlap_dispatch<emap_t, vmap_t, vemap_t>\n                       (eweight, vweight, oegroups, esrcpos, etgtpos,\n                        label, vlist, deg_corr, dense, multigraph, parallel_edges,\n                        beta, sequential, parallel, random_move, c, node_coherent,\n                        verbose, gi.GetMaxEdgeIndex(), nmerges,\n                        niter, merge_map, overlap_stats, partition_stats, rng, S,\n                        nmoves, bgi),\n                       mrs, mrp, mrm, wr, b, placeholders::_1,\n                       std::ref(emat), sampler, cavity_sampler, weighted))();\n    return boost::python::make_tuple(S, nmoves);\n}\n\nstruct get_overlap_stats\n{\n    template <class Graph, class Vprop, class VIprop, class VVprop>\n    void operator()(Graph& g, Vprop b, VVprop half_edges, VIprop node_index,\n                    size_t B, overlap_stats_t& overlap_stats) const\n    {\n        overlap_stats = overlap_stats_t(g, b.get_unchecked(num_vertices(g)),\n                                        half_edges,\n                                        node_index.get_unchecked(num_vertices(g)), B);\n    }\n};\n\noverlap_stats_t\ndo_get_overlap_stats(GraphInterface& gi, boost::any ob,\n                     boost::any ohalf_edges, boost::any onode_index,\n                     size_t NN, size_t B)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vimap_t;\n    typedef property_map_type::apply<vector<int64_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n\n    overlap_stats_t overlap_stats;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    vvmap_t half_edges = any_cast<vvmap_t>(ohalf_edges);\n    vimap_t node_index = any_cast<vimap_t>(onode_index);\n\n    run_action<>()(gi, std::bind(get_overlap_stats(), placeholders::_1, b,\n                                 half_edges.get_unchecked(NN), node_index, B,\n                                 std::ref(overlap_stats)))();\n    return overlap_stats;\n}\n\nstruct get_overlap_partition_stats\n{\n    template <class Graph, class Vprop, class Eprop>\n    void operator()(Graph& g, Vprop b, Eprop eweight, size_t N, size_t B,\n                    bool edges_dl, overlap_stats_t& overlap_stats,\n                    overlap_partition_stats_t& partition_stats) const\n    {\n        partition_stats = overlap_partition_stats_t(g, b, overlap_stats,\n                                                    eweight, N, B, edges_dl);\n    }\n};\n\noverlap_partition_stats_t\ndo_get_overlap_partition_stats(GraphInterface& gi, boost::any ob,\n                               boost::any aeweight, size_t N, size_t B,\n                               bool edges_dl, overlap_stats_t& overlap_stats)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n\n    overlap_partition_stats_t partition_stats;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    emap_t eweight = any_cast<emap_t>(aeweight);\n\n    run_action<>()(gi, std::bind(get_overlap_partition_stats(),\n                                 placeholders::_1, b, eweight, N, B, edges_dl,\n                                 std::ref(overlap_stats),\n                                 std::ref(partition_stats)))();\n\n    return partition_stats;\n}\n\ndouble do_get_overlap_parallel_entropy(GraphInterface& gi,\n                                       overlap_stats_t& overlap_stats)\n{\n    double S = 0;\n    run_action<>()\n        (gi, std::bind(entropy_parallel_edges_overlap(),\n                       placeholders::_1, std::ref(overlap_stats),\n                       std::ref(S)))();\n    return S;\n}\n\n\nstruct get_eg_overlap\n{\n    template <class Graph, class EGraph, class EVprop, class VProp,\n              class VIProp, class VVProp, class EProp>\n    void operator()(Graph& g, EGraph& eg, EVprop be, VProp b, VIProp node_index,\n                    VVProp half_edges, EProp egindex) const\n    {\n        auto eindex = get(edge_index, g);\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n        for (auto e : edges_range(g))\n        {\n            vertex_t s = get_source(e, g);\n            vertex_t t = get_target(e, g);\n            vertex_t u = add_vertex(eg);\n            vertex_t v = add_vertex(eg);\n            auto ne = add_edge(u, v, eg).first;\n            egindex[ne] = eindex[e];\n            if (be[e].size() != 2)\n                throw GraphException(\"Edge block property map must have two values per edge\");\n            b[u] = be[e][0];\n            b[v] = be[e][1];\n            node_index[u] = s;\n            node_index[v] = t;\n            half_edges[s].push_back(u);\n            half_edges[t].push_back(v);\n        }\n    }\n};\n\nvoid do_get_eg_overlap(GraphInterface& gi, GraphInterface& egi, boost::any obe,\n                       boost::any ob, boost::any onode_index,\n                       boost::any ohalf_edges, boost::any oeindex)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vimap_t;\n    typedef property_map_type::apply<vector<int64_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::edge_index_map_t>::type\n        evmap_t;\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    evmap_t be = any_cast<evmap_t>(obe);\n    vimap_t node_index = any_cast<vimap_t>(onode_index);\n    vvmap_t half_edges = any_cast<vvmap_t>(ohalf_edges);\n    emap_t eindex = any_cast<emap_t>(oeindex);\n\n    run_action<>()(gi, std::bind(get_eg_overlap(), placeholders::_1,\n                                 std::ref(egi.GetGraph()), be, b, node_index,\n                                 half_edges, eindex))();\n}\n\nstruct get_be_overlap\n{\n    template <class Graph, class EGraph, class EVprop, class VProp, class VIProp>\n    void operator()(Graph& g, EGraph& eg, EVprop be, VProp b, VIProp node_index)\n        const\n    {\n        for (auto ei : edges_range(eg))\n        {\n            auto u = source(ei, eg);\n            auto v = target(ei, eg);\n\n            auto s = vertex(node_index[u], g);\n            auto t = vertex(node_index[v], g);\n\n            for (auto e : out_edges_range(s, g))\n            {\n                if (!be[e].empty() || target(e, g) != t)\n                    continue;\n                if (is_directed::apply<Graph>::type::value || s < target(e, g))\n                    be[e] = {b[u], b[v]};\n                else\n                    be[e] = {b[v], b[u]};\n                break;\n            }\n\n            for (auto e : in_edges_range(t, g))\n            {\n                if (!be[e].empty() || source(e, g) != s)\n                    continue;\n                be[e] = {b[u], b[v]};\n                break;\n            }\n        }\n    }\n};\n\nvoid do_get_be_overlap(GraphInterface& gi, GraphInterface& egi, boost::any obe,\n                       boost::any ob, boost::any onode_index)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vimap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::edge_index_map_t>::type\n        evmap_t;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    evmap_t be = any_cast<evmap_t>(obe);\n    vimap_t node_index = any_cast<vimap_t>(onode_index);\n\n    run_action<>()(gi, std::bind(get_be_overlap(), placeholders::_1,\n                                 std::ref(egi.GetGraph()), be, b,\n                                 node_index))();\n}\n\n\nstruct get_be_from_b_overlap\n{\n    template <class Graph, class EVprop, class VProp>\n    void operator()(Graph& g, EVprop be, VProp b)\n        const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n        typename graph_traits<Graph>::edge_iterator ei, ei_end;\n        for (auto e : edges_range(g))\n        {\n            vertex_t s = get_source(e, g);\n            vertex_t t = get_target(e, g);\n            be[e] = {b[s], b[t]};\n        }\n    }\n};\n\nvoid do_get_be_from_b_overlap(GraphInterface& gi, boost::any obe, boost::any ob)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::edge_index_map_t>::type\n        evmap_t;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    evmap_t be = any_cast<evmap_t>(obe);\n\n    run_action<>()(gi, std::bind(get_be_from_b_overlap(), placeholders::_1,\n                                 be, b))();\n}\n\n\nstruct get_bv_overlap\n{\n    template <class Graph, class VProp, class VIProp, class VVProp>\n    void operator()(Graph& g, VProp b, VIProp node_index, VVProp bv,\n                    VVProp bc_in, VVProp bc_out, VVProp bc_total) const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n\n        typedef unordered_map<int, int> map_t;\n        vector<map_t> hist_in;\n        vector<map_t> hist_out;\n\n        for (auto v : vertices_range(g))\n        {\n            if (out_degree(v, g) > 0)\n            {\n                vertex_t s = node_index[v];\n                if (s >= hist_out.size())\n                    hist_out.resize(s + 1);\n                hist_out[s][b[v]]++;\n            }\n\n            if (in_degreeS()(v, g) > 0)\n            {\n                vertex_t t = node_index[v];\n                if (t >= hist_in.size())\n                    hist_in.resize(t + 1);\n                hist_in[t][b[v]]++;\n            }\n        }\n\n        size_t N = max(hist_in.size(), hist_out.size());\n        hist_in.resize(N);\n        hist_out.resize(N);\n\n        set<size_t> rs;\n        for (size_t i = 0; i < N; ++i)\n        {\n            rs.clear();\n            for (auto iter = hist_out[i].begin(); iter != hist_out[i].end(); ++iter)\n                rs.insert(iter->first);\n            for (auto iter = hist_in[i].begin(); iter != hist_in[i].end(); ++iter)\n                rs.insert(iter->first);\n            // if (rs.empty())\n            //     throw GraphException(\"Cannot have empty overlapping block membership!\");\n            for (size_t r : rs)\n            {\n                bv[i].push_back(r);\n\n                auto iter_in = hist_in[i].find(r);\n                if (iter_in != hist_in[i].end())\n                    bc_in[i].push_back(iter_in->second);\n                else\n                    bc_in[i].push_back(0);\n\n                auto iter_out = hist_out[i].find(r);\n                if (iter_out != hist_out[i].end())\n                    bc_out[i].push_back(iter_out->second);\n                else\n                    bc_out[i].push_back(0);\n\n                bc_total[i].push_back(bc_in[i].back() +\n                                      bc_out[i].back());\n            }\n        }\n    }\n};\n\nvoid do_get_bv_overlap(GraphInterface& gi, boost::any ob,  boost::any onode_index,\n                       boost::any obv, boost::any obc_in, boost::any obc_out,\n                       boost::any obc_total)\n{\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vimap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    vimap_t node_index = any_cast<vimap_t>(onode_index);\n    vvmap_t bv = any_cast<vvmap_t>(obv);\n    vvmap_t bc_in = any_cast<vvmap_t>(obc_in);\n    vvmap_t bc_out = any_cast<vvmap_t>(obc_out);\n    vvmap_t bc_total = any_cast<vvmap_t>(obc_total);\n\n    run_action<>()(gi, std::bind(get_bv_overlap(), placeholders::_1, b,\n                                 node_index, bv, bc_in, bc_out, bc_total))();\n }\n\nstruct get_wr_overlap\n{\n    template <class Graph, class VProp, class VVProp>\n    void operator()(Graph& g, VVProp bv, VProp wr) const\n    {\n        for (auto v : vertices_range(g))\n        {\n            for (size_t i = 0; i < bv[v].size(); ++i)\n                wr[bv[v][i]]++;\n        }\n    }\n};\n\nvoid do_get_wr_overlap(GraphInterface& gi, boost::any obv,\n                       boost::any owr)\n{\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n\n    vvmap_t bv = any_cast<vvmap_t>(obv);\n    vmap_t wr = any_cast<vmap_t>(owr);\n\n    run_action<>()(gi, std::bind(get_wr_overlap(), placeholders::_1, bv, wr))();\n}\n\nstruct get_nodeset_overlap\n{\n    template <class Graph, class VProp, class VVProp>\n    void operator()(Graph& g, VProp node_index, VVProp half_edges)\n        const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n        for (auto e : edges_range(g))\n        {\n            vertex_t s = get_source(e, g);\n            vertex_t t = get_target(e, g);\n            half_edges[node_index[s]].push_back(s);\n            half_edges[node_index[t]].push_back(t);\n        }\n    }\n};\n\nvoid do_get_nodeset_overlap(GraphInterface& gi, boost::any onode_index,\n                            boost::any ohalf_edges)\n{\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int64_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n\n    vmap_t node_index = any_cast<vmap_t>(onode_index);\n    vvmap_t half_edges = any_cast<vvmap_t>(ohalf_edges);\n\n    run_action<>()(gi, std::bind(get_nodeset_overlap(), placeholders::_1,\n                                 node_index, half_edges))();\n}\n\nstruct get_augmented_overlap\n{\n    template <class Graph, class VProp, class VIProp>\n    void operator()(Graph& g, VProp b, VIProp node_index, VProp br_map,\n                    vector<int32_t>& br_b, vector<int32_t>& br_ni) const\n    {\n        unordered_map<std::tuple<int, int>, size_t> idx_map;\n        vector<std::tuple<int, int>> idx_rmap;\n        size_t pos = 0;\n\n        for (auto v : vertices_range(g))\n        {\n            size_t vi = node_index[v];\n            auto br = std::make_tuple(b[v], vi);\n            size_t idx;\n            auto iter = idx_map.find(br);\n            if (iter != idx_map.end())\n            {\n                idx = iter->second;\n            }\n            else\n            {\n                idx = pos;\n                idx_map[br] = pos++;\n                idx_rmap.push_back(br);\n            }\n            br_map[v] = idx;\n        }\n\n        for (size_t i = 0; i < idx_rmap.size(); ++i)\n        {\n            auto& br = idx_rmap[i];\n            br_b.push_back(get<0>(br));\n            br_ni.push_back(get<1>(br));\n        }\n    }\n};\n\nvoid do_get_augmented_overlap(GraphInterface& gi, boost::any ob,\n                              boost::any onode_index, boost::any obr_map,\n                              vector<int32_t>& br_b, vector<int32_t>& br_ni)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int64_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vimap_t;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    vimap_t node_index = any_cast<vimap_t>(onode_index);\n    vmap_t br_map = any_cast<vmap_t>(obr_map);\n\n    run_action<>()(gi, std::bind(get_augmented_overlap(), placeholders::_1,\n                                 b, node_index, br_map, std::ref(br_b),\n                                 std::ref(br_ni)))();\n}\n\n\nstruct get_overlap_split\n{\n    template <class Graph, class VVProp, class VProp>\n    void operator()(Graph& g, VVProp bv, VProp b) const\n    {\n        unordered_map<vector<int>, size_t> bvset;\n\n        for (auto v : vertices_range(g))\n        {\n            auto r = bv[v];\n            auto iter = bvset.find(r);\n            if (iter == bvset.end())\n                iter = bvset.insert(make_pair(r, bvset.size())).first;\n            b[v] = iter->second;\n        }\n    }\n};\n\nvoid do_get_overlap_split(GraphInterface& gi, boost::any obv, boost::any ob)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n\n    vvmap_t bv = any_cast<vvmap_t>(obv);\n    vmap_t b = any_cast<vmap_t>(ob);\n\n    run_action<>()(gi, std::bind(get_overlap_split(),\n                                 placeholders::_1, bv, b))();\n}\n\n\nstruct get_maj_overlap\n{\n    template <class Graph, class VProp, class VVProp>\n    void operator()(Graph& g, VVProp bv, VVProp bc_total, VProp b) const\n    {\n        for (auto v : vertices_range(g))\n        {\n            if (bv[v].empty())\n            {\n                b[v] = numeric_limits<int32_t>::max();\n                continue;\n            }\n\n            auto& c = bc_total[v];\n            auto pos = std::max_element(c.begin(), c.end());\n            auto r = *(bv[v].begin() + (pos - c.begin()));\n            b[v] = r;\n        }\n    }\n};\n\nvoid do_get_maj_overlap(GraphInterface& gi, boost::any obv,\n                        boost::any obc_total, boost::any ob)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n\n    vmap_t b = any_cast<vmap_t>(ob);\n    vvmap_t bv = any_cast<vvmap_t>(obv);\n    vvmap_t bc_total = any_cast<vvmap_t>(obc_total);\n\n    run_action<>()(gi, std::bind(get_maj_overlap(), placeholders::_1, bv,\n                                 bc_total, b))();\n}\n\n\n} // namespace graph_tool\n\n\nvoid export_blockmodel_overlap()\n{\n    using namespace boost::python;\n\n    class_<overlap_stats_t>(\"overlap_stats\")\n        .def(\"is_enabled\", &overlap_stats_t::is_enabled);\n    class_<overlap_partition_stats_t>(\"overlap_partition_stats\")\n        .def(\"is_enabled\", &overlap_partition_stats_t::is_enabled)\n        .def(\"get_partition_dl\", &overlap_partition_stats_t::get_partition_dl)\n        .def(\"get_deg_dl\", &overlap_partition_stats_t::get_deg_dl);\n\n    def(\"move_sweep_overlap\", do_move_sweep_overlap);\n    def(\"init_overlap_stats\", do_get_overlap_stats);\n    def(\"init_overlap_partition_stats\", do_get_overlap_partition_stats);\n\n    def(\"overlap_parallel_entropy\", do_get_overlap_parallel_entropy);\n\n    // def(\"get_overlap_proj\", do_get_overlap_proj);\n\n    def(\"get_eg_overlap\", do_get_eg_overlap);\n    def(\"get_be_overlap\", do_get_be_overlap);\n    def(\"get_be_from_b_overlap\", do_get_be_from_b_overlap);\n    def(\"get_bv_overlap\", do_get_bv_overlap);\n    def(\"get_wr_overlap\", do_get_wr_overlap);\n    def(\"get_nodeset_overlap\", do_get_nodeset_overlap);\n    def(\"get_augmented_overlap\", do_get_augmented_overlap);\n    def(\"get_overlap_split\", do_get_overlap_split);\n    def(\"get_maj_overlap\", do_get_maj_overlap);\n}\n", "meta": {"hexsha": "0a2f814c323281d600a0465371ca4648a5e5493e", "size": 33131, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/community/graph_blockmodel_overlap.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/community/graph_blockmodel_overlap.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/community/graph_blockmodel_overlap.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": 38.0378874856, "max_line_length": 135, "alphanum_fraction": 0.5531979113, "num_tokens": 7617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.01640303020216949, "lm_q1q2_score": 0.0066197192904158654}}
{"text": "//=======================================================================\n// Copyright (C) 2012 Flavio De Lorenzi (fdlorenzi@gmail.com)\n// Copyright (C) 2013 Jakob Lykke Andersen, University of Southern Denmark (jlandersen@imada.sdu.dk)\n//\n// The algorithm implemented here is derived from original ideas by \n// Pasquale Foggia and colaborators. For further information see \n// e.g. Cordella et al. 2001, 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\n// Revision History:\n//   8 April 2013: Fixed a typo in vf2_print_callback. (Flavio De Lorenzi) \n\n#ifndef BOOST_VF2_SUB_GRAPH_ISO_HPP\n#define BOOST_VF2_SUB_GRAPH_ISO_HPP\n\n#include <iostream>\n#include <iomanip>\n#include <iterator>\n#include <vector>\n#include <utility>\n\n#include <boost/assert.hpp>\n#include <boost/concept/assert.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/mcgregor_common_subgraphs.hpp> // for always_equivalent\n#include <boost/graph/named_function_params.hpp>\n#include <boost/type_traits/has_less.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/range/algorithm/sort.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/utility/enable_if.hpp>\n\n#ifndef BOOST_GRAPH_ITERATION_MACROS_HPP\n#define BOOST_ISO_INCLUDED_ITER_MACROS // local macro, see bottom of file\n#include <boost/graph/iteration_macros.hpp>\n#endif\n\nnamespace boost {\n  \n  // Default print_callback\n  template <typename Graph1,\n            typename Graph2>\n  struct vf2_print_callback {\n    \n    vf2_print_callback(const Graph1& graph1, const Graph2& graph2) \n      : graph1_(graph1), graph2_(graph2) {}\n    \n    template <typename CorrespondenceMap1To2,\n              typename CorrespondenceMap2To1>\n    bool operator()(CorrespondenceMap1To2 f, CorrespondenceMap2To1) const {\n      \n      // Print (sub)graph isomorphism map\n      BGL_FORALL_VERTICES_T(v, graph1_, Graph1) \n        std::cout << '(' << get(vertex_index_t(), graph1_, v) << \", \" \n                  << get(vertex_index_t(), graph2_, get(f, v)) << \") \";\n      \n      std::cout << std::endl;\n      \n      return true;\n    }\n    \n  private:\n    const Graph1& graph1_;\n    const Graph2& graph2_;\n  };\n  \n  namespace detail {\n    \n    // State associated with a single graph (graph_this)\n    template<typename GraphThis,\n             typename GraphOther,\n             typename IndexMapThis,\n             typename IndexMapOther>\n    class base_state {\n      \n      typedef typename graph_traits<GraphThis>::vertex_descriptor vertex_this_type;\n      typedef typename graph_traits<GraphOther>::vertex_descriptor vertex_other_type;\n      \n      typedef typename graph_traits<GraphThis>::vertices_size_type size_type;\n      \n      const GraphThis& graph_this_;\n      const GraphOther& graph_other_;\n      \n      IndexMapThis index_map_this_;\n      IndexMapOther index_map_other_;\n      \n      std::vector<vertex_other_type> core_vec_;\n      typedef iterator_property_map<typename std::vector<vertex_other_type>::iterator,\n                                    IndexMapThis, vertex_other_type, \n                                    vertex_other_type&> core_map_type;\n      core_map_type core_;\n    \n      std::vector<size_type> in_vec_, out_vec_;\n      typedef iterator_property_map<typename std::vector<size_type>::iterator,\n                                    IndexMapThis, size_type, size_type&> in_out_map_type;\n      in_out_map_type in_, out_;\n\n      size_type term_in_count_, term_out_count_, term_both_count_, core_count_;\n\n      // Forbidden \n      base_state(const base_state&);\n      base_state& operator=(const base_state&);\n\n    public:\n\n      base_state(const GraphThis& graph_this, const GraphOther& graph_other,\n                 IndexMapThis index_map_this, IndexMapOther index_map_other)\n        : graph_this_(graph_this), graph_other_(graph_other), \n          index_map_this_(index_map_this), index_map_other_(index_map_other), \n          term_in_count_(0), term_out_count_(0), term_both_count_(0), core_count_(0) {\n\n        core_vec_.resize(num_vertices(graph_this_), graph_traits<GraphOther>::null_vertex());\n        core_ = make_iterator_property_map(core_vec_.begin(), index_map_this_);\n\n        in_vec_.resize(num_vertices(graph_this_), 0);\n        in_ = make_iterator_property_map(in_vec_.begin(), index_map_this_);\n\n        out_vec_.resize(num_vertices(graph_this_), 0);\n        out_ = make_iterator_property_map(out_vec_.begin(), index_map_this_);\n      }\n\n      // Adds a vertex pair to the state of graph graph_this\n      void push(const vertex_this_type& v_this, const vertex_other_type& v_other) {\n\n        ++core_count_;\n\n        put(core_, v_this, v_other);\n\n        if (!get(in_, v_this)) {   \n          put(in_, v_this, core_count_);\n          ++term_in_count_;\n          if (get(out_, v_this))\n            ++term_both_count_;\n        }\n\n        if (!get(out_, v_this)) {   \n          put(out_, v_this, core_count_);\n          ++term_out_count_;\n          if (get(in_, v_this))\n            ++term_both_count_;\n        }\n\n        BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis) {\n          vertex_this_type w = source(e, graph_this_);\n          if (!get(in_, w)) {\n            put(in_, w, core_count_);\n            ++term_in_count_;\n            if (get(out_, w))\n              ++term_both_count_;\n          }\n        }\n        \n        BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis) {\n          vertex_this_type w = target(e, graph_this_);\n          if (!get(out_, w)) {\n            put(out_, w, core_count_);\n            ++term_out_count_;\n            if (get(in_, w))\n              ++term_both_count_;                        \n          }\n        }\n        \n      }\n\n      // Removes vertex pair from state of graph_this\n      void pop(const vertex_this_type& v_this, const vertex_other_type&) {\n        \n        if (!core_count_) return;\n        \n        if (get(in_, v_this) == core_count_) {\n          put(in_, v_this, 0);\n          --term_in_count_;\n          if (get(out_, v_this))\n            --term_both_count_;\n        }\n\n        BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis) {\n          vertex_this_type w = source(e, graph_this_);\n          if (get(in_, w) == core_count_) {\n            put(in_, w, 0);\n            --term_in_count_;\n            if (get(out_, w))\n              --term_both_count_;\n          }\n        }\n\n        if (get(out_, v_this) == core_count_) {\n          put(out_, v_this, 0);\n          --term_out_count_;\n          if (get(in_, v_this))\n            --term_both_count_;\n        }\n\n        BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis) {\n          vertex_this_type w = target(e, graph_this_);\n          if (get(out_, w) == core_count_) {\n            put(out_, w, 0);\n            --term_out_count_;\n            if (get(in_, w))\n              --term_both_count_;\n          }\n        }\n        put(core_, v_this, graph_traits<GraphOther>::null_vertex());\n\n        --core_count_;\n        \n      }\n            \n      // Returns true if the in-terminal set is not empty  \n      bool term_in() const {\n        return core_count_ < term_in_count_ ;\n      }\n\n      // Returns true if vertex belongs to the in-terminal set\n      bool term_in(const vertex_this_type& v) const {\n        return (get(in_, v) > 0) &&\n               (get(core_, v) == graph_traits<GraphOther>::null_vertex());\n      }\n            \n      // Returns true if the out-terminal set is not empty  \n      bool term_out() const {\n        return core_count_ < term_out_count_;\n      }\n\n      // Returns true if vertex belongs to the out-terminal set\n      bool term_out(const vertex_this_type& v) const {\n        return (get(out_, v) > 0) && \n               (get(core_, v) == graph_traits<GraphOther>::null_vertex());\n      }\n\n      // Returns true of both (in- and out-terminal) sets are not empty\n      bool term_both() const {\n        return core_count_ < term_both_count_;\n      }\n\n      // Returns true if vertex belongs to both (in- and out-terminal) sets\n      bool term_both(const vertex_this_type& v) const {\n        return (get(in_, v) > 0) && (get(out_, v) > 0) && \n               (get(core_, v) == graph_traits<GraphOther>::null_vertex());\n      }\n\n      // Returns true if vertex belongs to the core map, i.e. it is in the \n      // present mapping\n      bool in_core(const vertex_this_type& v) const {\n        return get(core_, v) != graph_traits<GraphOther>::null_vertex();\n      }\n\n      // Returns the number of vertices in the mapping\n      size_type count() const {\n        return core_count_;\n      }            \n\n      // Returns the image (in graph_other) of vertex v (in graph_this)\n      vertex_other_type core(const vertex_this_type& v) const {\n        return get(core_, v);\n      }\n\n      // Returns the mapping\n      core_map_type get_map() const {\n        return core_;\n      }\n\n      // Returns the \"time\" (or depth) when vertex was added to the in-terminal set\n      size_type in_depth(const vertex_this_type& v) const {\n        return get(in_, v);\n      }\n\n      // Returns the \"time\" (or depth) when vertex was added to the out-terminal set\n      size_type out_depth(const vertex_this_type& v) const {\n        return get(out_, v);\n      }            \n\n      // Returns the terminal set counts\n      boost::tuple<size_type, size_type, size_type>\n      term_set() const {\n        return boost::make_tuple(term_in_count_, term_out_count_, \n                                 term_both_count_);\n      }\n      \n    };\n\n\n    // Function object that checks whether a valid edge\n    // exists. For multi-graphs matched edges are excluded  \n    template <typename Graph, typename Enable = void>\n    struct equivalent_edge_exists {\n      typedef typename boost::graph_traits<Graph>::edge_descriptor edge_type;\n\n      BOOST_CONCEPT_ASSERT(( LessThanComparable<edge_type> ));\n\n      template<typename EdgePredicate>\n      bool operator()(typename graph_traits<Graph>::vertex_descriptor s,\n                      typename graph_traits<Graph>::vertex_descriptor t, \n                      EdgePredicate is_valid_edge, const Graph& g) {\n        \n        BGL_FORALL_OUTEDGES_T(s, e, g, Graph) {\n          if ((target(e, g) == t) && is_valid_edge(e) && \n              (matched_edges_.find(e) == matched_edges_.end())) {\n            matched_edges_.insert(e);\n            return true;\n          }\n        }\n\n        return false;\n      }\n\n    private:\n      \n      std::set<edge_type> matched_edges_;\n    };\n    \n    template <typename Graph>\n    struct equivalent_edge_exists<Graph, typename boost::disable_if<is_multigraph<Graph> >::type> {\n      template<typename EdgePredicate>\n      bool operator()(typename graph_traits<Graph>::vertex_descriptor s,\n                      typename graph_traits<Graph>::vertex_descriptor t, \n                      EdgePredicate is_valid_edge, const Graph& g) {\n        \n        typename graph_traits<Graph>::edge_descriptor e;\n        bool found;\n        boost::tie(e, found) = edge(s, t, g);\n        if (!found)\n          return false;\n        else if (is_valid_edge(e))\n          return true;\n        \n        return false;\n      }\n      \n    };\n\n\n    // Generates a predicate for edge e1 given  a binary predicate and a \n    // fixed edge e2\n    template <typename Graph1,\n              typename Graph2,\n              typename EdgeEquivalencePredicate>\n    struct edge1_predicate {\n      \n      edge1_predicate(EdgeEquivalencePredicate edge_comp, \n                      typename graph_traits<Graph2>::edge_descriptor e2)\n        : edge_comp_(edge_comp), e2_(e2) {}\n      \n      bool operator()(typename graph_traits<Graph1>::edge_descriptor e1) {\n        return edge_comp_(e1, e2_);\n      }\n\n      EdgeEquivalencePredicate edge_comp_;\n      typename graph_traits<Graph2>::edge_descriptor e2_;\n    };\n\n\n    // Generates a predicate for edge e2 given given a binary predicate and a\n    // fixed edge e1\n    template <typename Graph1,\n              typename Graph2,\n              typename EdgeEquivalencePredicate>\n    struct edge2_predicate {\n      \n      edge2_predicate(EdgeEquivalencePredicate edge_comp, \n                      typename graph_traits<Graph1>::edge_descriptor e1)\n        : edge_comp_(edge_comp), e1_(e1) {}\n\n      bool operator()(typename graph_traits<Graph2>::edge_descriptor e2) {\n        return edge_comp_(e1_, e2);\n      }\n\n      EdgeEquivalencePredicate edge_comp_;\n      typename graph_traits<Graph1>::edge_descriptor e1_;\n    };\n\n\n    enum problem_selector {subgraph_mono, subgraph_iso, isomorphism };\n    \n    // The actual state associated with both graphs\n    template<typename Graph1,\n             typename Graph2,\n             typename IndexMap1,\n             typename IndexMap2,\n             typename EdgeEquivalencePredicate,\n             typename VertexEquivalencePredicate,\n             typename SubGraphIsoMapCallback,\n             problem_selector problem_selection>\n    class state {\n\n      typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_type;\n      typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_type;\n\n      typedef typename graph_traits<Graph1>::edge_descriptor edge1_type;\n      typedef typename graph_traits<Graph2>::edge_descriptor edge2_type;\n\n      typedef typename graph_traits<Graph1>::vertices_size_type graph1_size_type;\n      typedef typename graph_traits<Graph2>::vertices_size_type graph2_size_type;\n\n      const Graph1& graph1_;\n      const Graph2& graph2_;\n      \n      IndexMap1 index_map1_;\n      \n      EdgeEquivalencePredicate edge_comp_;\n      VertexEquivalencePredicate vertex_comp_;\n                \n      base_state<Graph1, Graph2, IndexMap1, IndexMap2> state1_;\n      base_state<Graph2, Graph1, IndexMap2, IndexMap1> state2_;\n\n      // Three helper functions used in Feasibility and Valid functions to test\n      // terminal set counts when testing for:\n      // - graph sub-graph monomorphism, or\n      inline bool comp_term_sets(graph1_size_type a, \n                                 graph2_size_type b,\n                                 boost::mpl::int_<subgraph_mono>) const {\n        return a <= b;\n      }\n\n      // - graph sub-graph isomorphism, or\n      inline bool comp_term_sets(graph1_size_type a, \n                                 graph2_size_type b,\n                                 boost::mpl::int_<subgraph_iso>) const {\n        return a <= b;\n      }\n\n      // - graph isomorphism\n      inline bool comp_term_sets(graph1_size_type a, \n                                 graph2_size_type b,\n                                 boost::mpl::int_<isomorphism>) const {\n        return a == b;\n      }\n      \n      // Forbidden \n      state(const state&);\n      state& operator=(const state&);\n\n    public:\n\n      state(const Graph1& graph1, const Graph2& graph2, \n            IndexMap1 index_map1, IndexMap2 index_map2, \n            EdgeEquivalencePredicate edge_comp,\n            VertexEquivalencePredicate vertex_comp)\n        : graph1_(graph1), graph2_(graph2), \n          index_map1_(index_map1), \n          edge_comp_(edge_comp), vertex_comp_(vertex_comp),\n          state1_(graph1, graph2, index_map1, index_map2), \n          state2_(graph2, graph1, index_map2, index_map1) {}\n      \n            // Add vertex pair to the state\n      void push(const vertex1_type& v, const vertex2_type& w) {\n        state1_.push(v, w);\n        state2_.push(w, v);\n      }\n      \n      // Remove vertex pair from state\n      void pop(const vertex1_type& v, const vertex2_type&) {\n        vertex2_type w = state1_.core(v);\n        state1_.pop(v, w);\n        state2_.pop(w, v);\n      }\n           \n      // Checks the feasibility of a new vertex pair\n      bool feasible(const vertex1_type& v_new, const vertex2_type& w_new) {\n        \n        if (!vertex_comp_(v_new, w_new)) return false;\n        \n        // graph1\n        graph1_size_type term_in1_count = 0, term_out1_count = 0, rest1_count = 0;\n        \n        {\n          equivalent_edge_exists<Graph2> edge2_exists;\n          \n          BGL_FORALL_INEDGES_T(v_new, e1, graph1_, Graph1) {\n            vertex1_type v = source(e1, graph1_);\n            \n            if (state1_.in_core(v) || (v == v_new)) {\n              vertex2_type w = w_new;\n              if (v != v_new)\n                w = state1_.core(v);\n              if (!edge2_exists(w, w_new,\n                                edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e1), \n                                graph2_))\n                return false;\n              \n            } else {\n              if (0 < state1_.in_depth(v))\n                ++term_in1_count;\n              if (0 < state1_.out_depth(v))\n                ++term_out1_count;\n              if ((state1_.in_depth(v) == 0) && (state1_.out_depth(v) == 0))\n                ++rest1_count;\n            }\n          }\n        }\n        \n        {\n          equivalent_edge_exists<Graph2> edge2_exists;\n          \n          BGL_FORALL_OUTEDGES_T(v_new, e1, graph1_, Graph1) {\n            vertex1_type v = target(e1, graph1_);\n            if (state1_.in_core(v) || (v == v_new)) {\n              vertex2_type w = w_new;\n              if (v != v_new)\n                w = state1_.core(v);\n              \n              if (!edge2_exists(w_new, w,\n                                edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e1), \n                                graph2_))\n                return false;\n              \n            } else {\n              if (0 < state1_.in_depth(v))\n                ++term_in1_count;\n              if (0 < state1_.out_depth(v))\n                ++term_out1_count;\n              if ((state1_.in_depth(v) == 0) && (state1_.out_depth(v) == 0))\n                ++rest1_count;\n            }\n          }\n        }\n        \n        // graph2\n        graph2_size_type term_out2_count = 0, term_in2_count = 0, rest2_count = 0;\n        \n        {\n          equivalent_edge_exists<Graph1> edge1_exists;\n          \n          BGL_FORALL_INEDGES_T(w_new, e2, graph2_, Graph2) {\n            vertex2_type w = source(e2, graph2_);\n            if (state2_.in_core(w) || (w == w_new)) {\n              if (problem_selection != subgraph_mono) {\n                vertex1_type v = v_new;\n                if (w != w_new)\n                  v = state2_.core(w);\n              \n                if (!edge1_exists(v, v_new,\n                                  edge1_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e2), \n                                  graph1_))\n                  return false;\n              }\n            } else {\n              if (0 < state2_.in_depth(w))\n                ++term_in2_count;\n              if (0 < state2_.out_depth(w))\n                ++term_out2_count;\n              if ((state2_.in_depth(w) == 0) && (state2_.out_depth(w) == 0))\n                ++rest2_count;\n            }\n          }\n        }\n\n        {\n          equivalent_edge_exists<Graph1> edge1_exists;\n          \n          BGL_FORALL_OUTEDGES_T(w_new, e2, graph2_, Graph2) {\n            vertex2_type w = target(e2, graph2_);\n            if (state2_.in_core(w) || (w == w_new)) {\n              if (problem_selection != subgraph_mono) {\n                vertex1_type v = v_new;\n                if (w != w_new)\n                  v = state2_.core(w);\n              \n                if (!edge1_exists(v_new, v,\n                                  edge1_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e2), \n                                  graph1_))\n                  return false;\n              }\n            } else {\n              if (0 < state2_.in_depth(w))\n                ++term_in2_count;\n              if (0 < state2_.out_depth(w))\n                ++term_out2_count;\n              if ((state2_.in_depth(w) == 0) && (state2_.out_depth(w) == 0))\n                ++rest2_count;\n            }\n          }\n        }\n\n        if (problem_selection != subgraph_mono) { // subgraph_iso and isomorphism\n          return comp_term_sets(term_in1_count, term_in2_count,\n                                boost::mpl::int_<problem_selection>()) &&\n                 comp_term_sets(term_out1_count, term_out2_count, \n                                boost::mpl::int_<problem_selection>()) &&\n                 comp_term_sets(rest1_count, rest2_count, \n                                boost::mpl::int_<problem_selection>());\n        } else { // subgraph_mono\n          return comp_term_sets(term_in1_count, term_in2_count,\n                                boost::mpl::int_<problem_selection>()) &&\n                 comp_term_sets(term_out1_count, term_out2_count, \n                                boost::mpl::int_<problem_selection>()) &&\n                 comp_term_sets(term_in1_count + term_out1_count + rest1_count,\n                                term_in2_count + term_out2_count + rest2_count, \n                                boost::mpl::int_<problem_selection>());\n        }\n      }\n      \n      // Returns true if vertex v in graph1 is a possible candidate to\n      // be added to the current state\n      bool possible_candidate1(const vertex1_type& v) const {\n        if (state1_.term_both() && state2_.term_both()) \n          return state1_.term_both(v);\n        else if (state1_.term_out() && state2_.term_out())\n          return state1_.term_out(v);\n        else if (state1_.term_in() && state2_.term_in())\n          return state1_.term_in(v);\n        else\n          return !state1_.in_core(v);\n      }\n\n      // Returns true if vertex w in graph2 is a possible candidate to\n      // be added to the current state\n      bool possible_candidate2(const vertex2_type& w) const {\n        if (state1_.term_both() && state2_.term_both()) \n          return state2_.term_both(w);\n        else if (state1_.term_out() && state2_.term_out())\n          return state2_.term_out(w);\n        else if (state1_.term_in() && state2_.term_in())\n          return state2_.term_in(w);\n        else\n          return !state2_.in_core(w);\n      }\n\n      // Returns true if a mapping was found\n      bool success() const {\n        return state1_.count() == num_vertices(graph1_);\n      }\n \n      // Returns true if a state is valid\n      bool valid() const {\n        boost::tuple<graph1_size_type, graph1_size_type, graph1_size_type> term1;\n        boost::tuple<graph2_size_type, graph2_size_type, graph2_size_type> term2;\n        \n        term1 = state1_.term_set();\n        term2 = state2_.term_set();\n        \n        return comp_term_sets(boost::get<0>(term1), boost::get<0>(term2),\n                              boost::mpl::int_<problem_selection>()) &&\n               comp_term_sets(boost::get<1>(term1), boost::get<1>(term2),\n                              boost::mpl::int_<problem_selection>()) &&\n               comp_term_sets(boost::get<2>(term1), boost::get<2>(term2),\n                              boost::mpl::int_<problem_selection>()); \n      }\n      \n      // Calls the user_callback with a graph (sub)graph mapping \n      bool call_back(SubGraphIsoMapCallback user_callback) const {\n        return user_callback(state1_.get_map(), state2_.get_map());\n      }\n      \n    };\n\n    \n    // Data structure to keep info used for back tracking during\n    // matching process\n    template<typename Graph1,\n             typename Graph2,\n             typename VertexOrder1>\n    struct vf2_match_continuation {\n      typename VertexOrder1::const_iterator graph1_verts_iter;\n      typename graph_traits<Graph2>::vertex_iterator graph2_verts_iter;\n    };\n\n    // Non-recursive method that explores state space using a depth-first\n    // search strategy.  At each depth possible pairs candidate are compute\n    // and tested for feasibility to extend the mapping. If a complete\n    // mapping is found, the mapping is output to user_callback in the form\n    // of a correspondence map (graph1 to graph2). Returning false from the\n    // user_callback will terminate the search. Function match will return\n    // true if the entire search space was explored.\n    template<typename Graph1,\n             typename Graph2,\n             typename IndexMap1,\n             typename IndexMap2,\n             typename VertexOrder1,\n             typename EdgeEquivalencePredicate,\n             typename VertexEquivalencePredicate, \n             typename SubGraphIsoMapCallback,\n             problem_selector problem_selection>\n    bool match(const Graph1& graph1, const Graph2& graph2, \n               SubGraphIsoMapCallback user_callback, const VertexOrder1& vertex_order1, \n               state<Graph1, Graph2, IndexMap1, IndexMap2,\n               EdgeEquivalencePredicate, VertexEquivalencePredicate,\n               SubGraphIsoMapCallback, problem_selection>& s) {\n      \n      typename VertexOrder1::const_iterator graph1_verts_iter;\n\n      typedef typename graph_traits<Graph2>::vertex_iterator vertex2_iterator_type;\n      vertex2_iterator_type graph2_verts_iter, graph2_verts_iter_end;\n    \n      typedef vf2_match_continuation<Graph1, Graph2, VertexOrder1> match_continuation_type;\n      std::vector<match_continuation_type> k;\n  \n      recur:\n      if (s.success()) {\n        if (!s.call_back(user_callback)) \n          return false;\n\n        goto back_track;\n      }\n \n      if (!s.valid())\n        goto back_track;\n\n      graph1_verts_iter = vertex_order1.begin();\n      while (graph1_verts_iter != vertex_order1.end() && \n             !s.possible_candidate1(*graph1_verts_iter)) {\n        ++graph1_verts_iter;\n      }\n\n      boost::tie(graph2_verts_iter, graph2_verts_iter_end) = vertices(graph2);\n      while (graph2_verts_iter != graph2_verts_iter_end) {\n        if (s.possible_candidate2(*graph2_verts_iter)) {\n          if (s.feasible(*graph1_verts_iter, *graph2_verts_iter)) {\n            match_continuation_type kk;\n            kk.graph1_verts_iter = graph1_verts_iter;\n            kk.graph2_verts_iter = graph2_verts_iter;\n            k.push_back(kk);\n            \n            s.push(*graph1_verts_iter, *graph2_verts_iter);\n            goto recur;\n          }\n        }\n        graph2_loop: ++graph2_verts_iter;\n      }\n\n      back_track:\n      if (k.empty()) \n        return true;    \n      \n      const match_continuation_type kk = k.back();\n      graph1_verts_iter = kk.graph1_verts_iter;\n      graph2_verts_iter = kk.graph2_verts_iter;\n      k.pop_back();\n      \n      s.pop(*graph1_verts_iter, *graph2_verts_iter);\n      \n      goto graph2_loop;\n    }\n\n\n    // Used to sort nodes by in/out degrees\n    template<typename Graph>\n    struct vertex_in_out_degree_cmp {\n      typedef typename graph_traits<Graph>::vertex_descriptor vertex_type;\n\n      vertex_in_out_degree_cmp(const Graph& graph)\n        : graph_(graph) {}\n\n      bool operator()(const vertex_type& v, const vertex_type& w) const {\n        // lexicographical comparison\n        return std::make_pair(in_degree(v, graph_), out_degree(v, graph_)) <\n               std::make_pair(in_degree(w, graph_), out_degree(w, graph_));\n      }\n\n      const Graph& graph_;\n    };\n\n\n    // Used to sort nodes by multiplicity of in/out degrees\n    template<typename Graph,\n             typename FrequencyMap>\n    struct vertex_frequency_degree_cmp {\n      typedef typename graph_traits<Graph>::vertex_descriptor vertex_type;\n      \n      vertex_frequency_degree_cmp(const Graph& graph, FrequencyMap freq)\n        : graph_(graph), freq_(freq) {}\n      \n      bool operator()(const vertex_type& v, const vertex_type& w) const {\n        // lexicographical comparison\n        return std::make_pair(freq_[v], in_degree(v, graph_)+out_degree(v, graph_)) <\n               std::make_pair(freq_[w], in_degree(w, graph_)+out_degree(w, graph_));\n      }\n\n      const Graph& graph_;\n      FrequencyMap freq_;\n    };\n\n    \n    // Sorts vertices of a graph by multiplicity of in/out degrees \n    template<typename Graph,\n             typename IndexMap,\n             typename VertexOrder>\n    void sort_vertices(const Graph& graph, IndexMap index_map, VertexOrder& order) {\n      typedef typename graph_traits<Graph>::vertices_size_type size_type;\n\n      boost::range::sort(order, vertex_in_out_degree_cmp<Graph>(graph));\n\n      std::vector<size_type> freq_vec(num_vertices(graph), 0);\n      typedef iterator_property_map<typename std::vector<size_type>::iterator,\n                                    IndexMap, size_type, size_type&> frequency_map_type;\n                \n      frequency_map_type freq = make_iterator_property_map(freq_vec.begin(), index_map);\n\n      typedef typename VertexOrder::iterator order_iterator;\n\n      for (order_iterator order_iter = order.begin(); order_iter != order.end(); ) {\n        size_type count = 0;\n        for (order_iterator count_iter = order_iter;\n             (count_iter != order.end()) &&\n             (in_degree(*order_iter, graph) == in_degree(*count_iter, graph)) &&\n             (out_degree(*order_iter, graph) == out_degree(*count_iter, graph)); \n             ++count_iter)\n          ++count;\n      \n        for (size_type i = 0; i < count; ++i) {\n          freq[*order_iter] = count;\n          ++order_iter;\n        }\n      }\n\n      boost::range::sort(order, vertex_frequency_degree_cmp<Graph, frequency_map_type>(graph, freq));\n\n    }\n\n    // Enumerates all graph sub-graph mono-/iso-morphism mappings between graphs\n    // graph_small and graph_large. Continues until user_callback returns true or the\n    // search space has been fully explored.\n    template <problem_selector problem_selection,\n              typename GraphSmall,\n              typename GraphLarge,\n              typename IndexMapSmall,\n              typename IndexMapLarge,\n              typename VertexOrderSmall,\n              typename EdgeEquivalencePredicate,\n              typename VertexEquivalencePredicate,\n              typename SubGraphIsoMapCallback>\n    bool vf2_subgraph_morphism(const GraphSmall& graph_small, const GraphLarge& graph_large,\n                          SubGraphIsoMapCallback user_callback,\n                          IndexMapSmall index_map_small, IndexMapLarge index_map_large, \n                          const VertexOrderSmall& vertex_order_small,\n                          EdgeEquivalencePredicate edge_comp,\n                          VertexEquivalencePredicate vertex_comp) {\n\n      // Graph requirements\n      BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<GraphSmall> ));\n      BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<GraphSmall> ));\n      BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<GraphSmall> ));\n      BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<GraphSmall> ));\n\n      BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<GraphLarge> ));\n      BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<GraphLarge> ));\n      BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<GraphLarge> ));\n      BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<GraphLarge> ));\n\n      typedef typename graph_traits<GraphSmall>::vertex_descriptor vertex_small_type;\n      typedef typename graph_traits<GraphLarge>::vertex_descriptor vertex_large_type;\n\n      typedef typename graph_traits<GraphSmall>::vertices_size_type size_type_small;\n      typedef typename graph_traits<GraphLarge>::vertices_size_type size_type_large;\n        \n      // Property map requirements\n      BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMapSmall, vertex_small_type> ));\n      typedef typename property_traits<IndexMapSmall>::value_type IndexMapSmallValue;\n      BOOST_STATIC_ASSERT(( is_convertible<IndexMapSmallValue, size_type_small>::value ));\n        \n      BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMapLarge, vertex_large_type> ));\n      typedef typename property_traits<IndexMapLarge>::value_type IndexMapLargeValue;\n      BOOST_STATIC_ASSERT(( is_convertible<IndexMapLargeValue, size_type_large>::value ));\n\n      // Edge & vertex requirements\n      typedef typename graph_traits<GraphSmall>::edge_descriptor edge_small_type;\n      typedef typename graph_traits<GraphLarge>::edge_descriptor edge_large_type;\n\n      BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<EdgeEquivalencePredicate, \n                             edge_small_type, edge_large_type> ));\n\n      BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<VertexEquivalencePredicate, \n                             vertex_small_type, vertex_large_type> ));\n\n      // Vertex order requirements\n      BOOST_CONCEPT_ASSERT(( ContainerConcept<VertexOrderSmall> )); \n      typedef typename VertexOrderSmall::value_type order_value_type;\n      BOOST_STATIC_ASSERT(( is_same<vertex_small_type, order_value_type>::value ));\n      BOOST_ASSERT( num_vertices(graph_small) == vertex_order_small.size() );\n\n      if (num_vertices(graph_small) > num_vertices(graph_large))\n        return false;\n\n      typename graph_traits<GraphSmall>::edges_size_type num_edges_small = num_edges(graph_small);\n      typename graph_traits<GraphLarge>::edges_size_type num_edges_large = num_edges(graph_large);\n\n      // Double the number of edges for undirected graphs: each edge counts as\n      // in-edge and out-edge\n      if (is_undirected(graph_small)) num_edges_small *= 2;\n      if (is_undirected(graph_large)) num_edges_large *= 2;\n      if (num_edges_small > num_edges_large)\n        return false;\n    \n      if ((num_vertices(graph_small) == 0) && (num_vertices(graph_large) == 0))\n        return true;\n\n      detail::state<GraphSmall, GraphLarge, IndexMapSmall, IndexMapLarge,\n                    EdgeEquivalencePredicate, VertexEquivalencePredicate,\n                    SubGraphIsoMapCallback, problem_selection> \n        s(graph_small, graph_large, index_map_small, index_map_large, edge_comp, vertex_comp);\n\n      return detail::match(graph_small, graph_large, user_callback, vertex_order_small, s);\n    }\n\n  } // namespace detail\n\n\n  // Returns vertex order (vertices sorted by multiplicity of in/out degrees)\n  template<typename Graph>\n  std::vector<typename graph_traits<Graph>::vertex_descriptor> \n    vertex_order_by_mult(const Graph& graph) {\n\n    std::vector<typename graph_traits<Graph>::vertex_descriptor> vertex_order;\n    std::copy(vertices(graph).first, vertices(graph).second, std::back_inserter(vertex_order));\n\n    detail::sort_vertices(graph, get(vertex_index, graph), vertex_order);\n    return vertex_order;\n  }\n\n\n  // Enumerates all graph sub-graph monomorphism mappings between graphs\n  // graph_small and graph_large. Continues until user_callback returns true or the\n  // search space has been fully explored.\n  template <typename GraphSmall,\n            typename GraphLarge,\n            typename IndexMapSmall,\n            typename IndexMapLarge,\n            typename VertexOrderSmall,\n            typename EdgeEquivalencePredicate,\n            typename VertexEquivalencePredicate,\n            typename SubGraphIsoMapCallback>\n  bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large,\n                         SubGraphIsoMapCallback user_callback,\n                         IndexMapSmall index_map_small, IndexMapLarge index_map_large, \n                         const VertexOrderSmall& vertex_order_small,\n                         EdgeEquivalencePredicate edge_comp,\n                         VertexEquivalencePredicate vertex_comp) {\n    return detail::vf2_subgraph_morphism<detail::subgraph_mono>\n                                        (graph_small, graph_large,\n                                         user_callback,\n                                         index_map_small, index_map_large,\n                                         vertex_order_small,\n                                         edge_comp,\n                                         vertex_comp);\n  }\n\n\n  // All default interface for vf2_subgraph_iso\n  template <typename GraphSmall,\n            typename GraphLarge,\n            typename SubGraphIsoMapCallback>\n  bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large, \n                         SubGraphIsoMapCallback user_callback) {\n    return vf2_subgraph_mono(graph_small, graph_large, user_callback, \n                             get(vertex_index, graph_small), get(vertex_index, graph_large),\n                             vertex_order_by_mult(graph_small),\n                             always_equivalent(), always_equivalent());\n  }\n\n\n  // Named parameter interface of vf2_subgraph_iso\n  template <typename GraphSmall,\n            typename GraphLarge,\n            typename VertexOrderSmall,\n            typename SubGraphIsoMapCallback,\n            typename Param,\n            typename Tag,\n            typename Rest>\n  bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large,\n                         SubGraphIsoMapCallback user_callback,\n                         const VertexOrderSmall& vertex_order_small,\n                         const bgl_named_params<Param, Tag, Rest>& params) {\n    return vf2_subgraph_mono(graph_small, graph_large, user_callback,\n                             choose_const_pmap(get_param(params, vertex_index1),\n                                               graph_small, vertex_index),\n                             choose_const_pmap(get_param(params, vertex_index2),\n                                               graph_large, vertex_index),\n                             vertex_order_small,\n                             choose_param(get_param(params, edges_equivalent_t()),\n                                          always_equivalent()),\n                             choose_param(get_param(params, vertices_equivalent_t()),\n                                          always_equivalent())\n                             );\n  }\n  \n  \n  // Enumerates all graph sub-graph isomorphism mappings between graphs\n  // graph_small and graph_large. Continues until user_callback returns true or the\n  // search space has been fully explored.\n  template <typename GraphSmall,\n            typename GraphLarge,\n            typename IndexMapSmall,\n            typename IndexMapLarge,\n            typename VertexOrderSmall,\n            typename EdgeEquivalencePredicate,\n            typename VertexEquivalencePredicate,\n            typename SubGraphIsoMapCallback>\n  bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large,\n                        SubGraphIsoMapCallback user_callback,\n                        IndexMapSmall index_map_small, IndexMapLarge index_map_large, \n                        const VertexOrderSmall& vertex_order_small,\n                        EdgeEquivalencePredicate edge_comp,\n                        VertexEquivalencePredicate vertex_comp) {\n    return detail::vf2_subgraph_morphism<detail::subgraph_iso>\n                                        (graph_small, graph_large,\n                                         user_callback,\n                                         index_map_small, index_map_large,\n                                         vertex_order_small,\n                                         edge_comp,\n                                         vertex_comp);\n  }\n\n\n  // All default interface for vf2_subgraph_iso\n  template <typename GraphSmall,\n            typename GraphLarge,\n            typename SubGraphIsoMapCallback>\n  bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large, \n                        SubGraphIsoMapCallback user_callback) {\n\n    typedef typename graph_traits<GraphSmall>::vertex_descriptor vertex_small_type;\n    \n    return vf2_subgraph_iso(graph_small, graph_large, user_callback, \n                            get(vertex_index, graph_small), get(vertex_index, graph_large),\n                            vertex_order_by_mult(graph_small),\n                            always_equivalent(), always_equivalent());\n  }\n\n\n  // Named parameter interface of vf2_subgraph_iso\n  template <typename GraphSmall,\n            typename GraphLarge,\n            typename VertexOrderSmall,\n            typename SubGraphIsoMapCallback,\n            typename Param,\n            typename Tag,\n            typename Rest>\n  bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large,\n                        SubGraphIsoMapCallback user_callback,\n                        const VertexOrderSmall& vertex_order_small,\n                        const bgl_named_params<Param, Tag, Rest>& params) {\n    \n    return vf2_subgraph_iso(graph_small, graph_large, user_callback,\n                            choose_const_pmap(get_param(params, vertex_index1),\n                                              graph_small, vertex_index),\n                            choose_const_pmap(get_param(params, vertex_index2),\n                                              graph_large, vertex_index),\n                            vertex_order_small,\n                            choose_param(get_param(params, edges_equivalent_t()),\n                                         always_equivalent()),\n                            choose_param(get_param(params, vertices_equivalent_t()),\n                                         always_equivalent())\n                            );\n\n  }\n\n\n  // Enumerates all isomorphism mappings between graphs graph1_ and graph2_.\n  // Continues until user_callback returns true or the search space has been\n  // fully explored.\n  template <typename Graph1,\n            typename Graph2,\n            typename IndexMap1,\n            typename IndexMap2,\n            typename VertexOrder1,\n            typename EdgeEquivalencePredicate,\n            typename VertexEquivalencePredicate,\n            typename GraphIsoMapCallback>\n  bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,\n                     GraphIsoMapCallback user_callback,\n                     IndexMap1 index_map1, IndexMap2 index_map2, \n                     const VertexOrder1& vertex_order1,\n                     EdgeEquivalencePredicate edge_comp,\n                     VertexEquivalencePredicate vertex_comp) {\n\n    // Graph requirements\n    BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph1> ));\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph1> ));\n    BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> ));\n    BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph1> ));\n\n    BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph2> ));\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph2> ));\n    BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph2> ));\n    BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph2> ));\n \n        \n    typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_type;\n    typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_type;\n    \n    typedef typename graph_traits<Graph1>::vertices_size_type size_type1;\n    typedef typename graph_traits<Graph2>::vertices_size_type size_type2;\n        \n    // Property map requirements\n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap1, vertex1_type> ));\n    typedef typename property_traits<IndexMap1>::value_type IndexMap1Value;\n    BOOST_STATIC_ASSERT(( is_convertible<IndexMap1Value, size_type1>::value ));\n        \n    BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap2, vertex2_type> ));\n    typedef typename property_traits<IndexMap2>::value_type IndexMap2Value;\n    BOOST_STATIC_ASSERT(( is_convertible<IndexMap2Value, size_type2>::value ));\n\n    // Edge & vertex requirements\n    typedef typename graph_traits<Graph1>::edge_descriptor edge1_type;\n    typedef typename graph_traits<Graph2>::edge_descriptor edge2_type;\n\n    BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<EdgeEquivalencePredicate, \n                           edge1_type, edge2_type> ));\n\n    BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<VertexEquivalencePredicate, \n                           vertex1_type, vertex2_type> ));\n    \n    // Vertex order requirements\n    BOOST_CONCEPT_ASSERT(( ContainerConcept<VertexOrder1> )); \n    typedef typename VertexOrder1::value_type order_value_type;\n    BOOST_STATIC_ASSERT(( is_same<vertex1_type, order_value_type>::value ));\n    BOOST_ASSERT( num_vertices(graph1) == vertex_order1.size() );\n\n    if (num_vertices(graph1) != num_vertices(graph2))\n      return false;\n\n    typename graph_traits<Graph1>::edges_size_type num_edges1 = num_edges(graph1);\n    typename graph_traits<Graph2>::edges_size_type num_edges2 = num_edges(graph2);\n\n    // Double the number of edges for undirected graphs: each edge counts as\n    // in-edge and out-edge\n    if (is_undirected(graph1)) num_edges1 *= 2;\n    if (is_undirected(graph2)) num_edges2 *= 2;\n    if (num_edges1 != num_edges2)\n      return false;\n\n    if ((num_vertices(graph1) == 0) && (num_vertices(graph2) == 0))\n      return true;\n        \n    detail::state<Graph1, Graph2, IndexMap1, IndexMap2,\n                  EdgeEquivalencePredicate, VertexEquivalencePredicate,\n                  GraphIsoMapCallback, detail::isomorphism> \n      s(graph1, graph2, index_map1, index_map2, edge_comp, vertex_comp);\n\n    return detail::match(graph1, graph2, user_callback, vertex_order1, s);\n  }\n\n\n  // All default interface for vf2_graph_iso\n  template <typename Graph1,\n            typename Graph2,\n            typename GraphIsoMapCallback>\n  bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2, \n                     GraphIsoMapCallback user_callback) {\n    \n    typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_type;\n\n    return vf2_graph_iso(graph1, graph2, user_callback, \n                         get(vertex_index, graph1), get(vertex_index, graph2),\n                         vertex_order_by_mult(graph1),\n                         always_equivalent(), always_equivalent());\n  }\n\n\n  // Named parameter interface of vf2_graph_iso\n  template <typename Graph1,\n            typename Graph2,\n            typename VertexOrder1,\n            typename GraphIsoMapCallback,\n            typename Param,\n            typename Tag,\n            typename Rest>\n  bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,\n                     GraphIsoMapCallback user_callback,\n                     const VertexOrder1& vertex_order1,\n                     const bgl_named_params<Param, Tag, Rest>& params) {\n    \n    return vf2_graph_iso(graph1, graph2, user_callback,\n                         choose_const_pmap(get_param(params, vertex_index1),\n                                           graph1, vertex_index),\n                         choose_const_pmap(get_param(params, vertex_index2),\n                                           graph2, vertex_index),\n                         vertex_order1,\n                         choose_param(get_param(params, edges_equivalent_t()),\n                                always_equivalent()),\n                         choose_param(get_param(params, vertices_equivalent_t()),\n                                      always_equivalent())\n                         );\n\n  }\n\n\n  // Verifies a graph (sub)graph isomorphism map \n  template<typename Graph1,\n           typename Graph2,\n           typename CorresponenceMap1To2,\n           typename EdgeEquivalencePredicate,\n           typename VertexEquivalencePredicate>\n  inline bool verify_vf2_subgraph_iso(const Graph1& graph1, const Graph2& graph2, \n                                      const CorresponenceMap1To2 f,\n                                      EdgeEquivalencePredicate edge_comp, \n                                      VertexEquivalencePredicate vertex_comp) {\n        \n    BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> ));\n    BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph2> ));\n\n    detail::equivalent_edge_exists<Graph2> edge2_exists;\n\n    BGL_FORALL_EDGES_T(e1, graph1, Graph1) {\n      typename graph_traits<Graph1>::vertex_descriptor s1, t1;\n      typename graph_traits<Graph2>::vertex_descriptor s2, t2;\n      \n      s1 = source(e1, graph1); t1 = target(e1, graph1);\n      s2 = get(f, s1); t2 = get(f, t1);\n      \n      if (!vertex_comp(s1, s2) || !vertex_comp(t1, t2))\n        return false;\n\n      typename graph_traits<Graph2>::edge_descriptor e2;\n      \n      if (!edge2_exists(s2, t2,\n                        detail::edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp, e1), \n                        graph2))\n        return false;\n      \n    }\n  \n    return true;\n  }\n\n  // Variant of verify_subgraph_iso with all default parameters\n  template<typename Graph1,\n           typename Graph2,\n           typename CorresponenceMap1To2>\n  inline bool verify_vf2_subgraph_iso(const Graph1& graph1, const Graph2& graph2, \n                                      const CorresponenceMap1To2 f) {\n    return verify_vf2_subgraph_iso(graph1, graph2, f, \n                                   always_equivalent(), always_equivalent());\n  }\n\n\n\n} // namespace boost\n\n#ifdef BOOST_ISO_INCLUDED_ITER_MACROS\n#undef BOOST_ISO_INCLUDED_ITER_MACROS\n#include <boost/graph/iteration_macros_undef.hpp>\n#endif\n\n#endif // BOOST_VF2_SUB_GRAPH_ISO_HPP\n", "meta": {"hexsha": "a316f78139d88db44f68fda3c999f990a88226ba", "size": 48871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extlibs/miniBoost/boost/graph/vf2_sub_graph_iso.hpp", "max_stars_repo_name": "sofa-framework/issofa", "max_stars_repo_head_hexsha": "94855f488465bc3ed41223cbde987581dfca5389", "max_stars_repo_licenses": ["OML"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-12-05T19:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T09:07:09.000Z", "max_issues_repo_path": "boost/graph/vf2_sub_graph_iso.hpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_issues_repo_licenses": ["BSL-1.0"], "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/graph/vf2_sub_graph_iso.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T00:09:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T10:47:11.000Z", "avg_line_length": 39.3486312399, "max_line_length": 109, "alphanum_fraction": 0.6098299605, "num_tokens": 10433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2254166158350767, "lm_q2_score": 0.029312233083263438, "lm_q1q2_score": 0.00660746438419822}}
{"text": "/*\n  Author(s):      Robert Patterson and Markus Sander\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the PAHInception class declared in the\n    swp_PAHInception.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Prof Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_pah_inception.h\"\n#include \"swp_mechanism.h\"\n\n#include \"local_geometry1d.h\"\n\n#include <boost/random/uniform_01.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::Processes;\nusing namespace std;\n\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (protected).\nPAHInception::PAHInception(void)\n: Inception()\n{\n    m_name = \"PAHInception\";\n}\n\n// Initialising constructor.\nPAHInception::PAHInception(const Sweep::Mechanism &mech,\n                          const EnvironmentInterface::PropertyIndex pah_index)\n: Inception(mech)\n, mPAHFormationIndex(pah_index)\n{\n    m_name = \"PAHInception\";\n}\n\n// Copy constructor.\nPAHInception::PAHInception(const PAHInception &copy)\n{\n    *this = copy;\n}\n\n// Stream-reading constructor.\nPAHInception::PAHInception(std::istream &in, const Sweep::Mechanism &mech)\n{\n    Deserialize(in, mech);\n}\n\n// Default destructor.\nPAHInception::~PAHInception(void)\n{\n}\n\n// OPERATOR OVERLOADS.\n\n// Assignment operator.\nPAHInception &PAHInception::operator =(const PAHInception &rhs)\n{\n    if (this != &rhs) {\n        Inception::operator =(rhs);\n\n    }\n    return *this;\n}\n\n\n/*!\n * Create a new particle and add it to the ensemble with position uniformly\n * distributed over the grid cell, if it is of positive size.\n *\n * The iterm parameter is included because it will be needed for many process\n * types and this function is meant to have a general signature.\n *\n * \\param[in]       t           Time\n * \\param[in,out]   sys         System to update\n * \\param[in]       local_geom  Details of local phsyical layout\n * \\param[in]       iterm       Process term responsible for this event\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      0 on success, otherwise negative.\n */\nint PAHInception::Perform(const double t, Cell &sys,\n                          const Geometry::LocalGeometry1d &local_geom,\n                          const unsigned int iterm,\n                          rng_type &rng) const {\n\n\tParticle *sp = NULL;\n\n\t//If using weighted PAHs...\n\tif (sys.ParticleModel()->Components(0)->WeightedPAHs()){\n\t//Check to see if a particle that matches that of the incepted PAHs already exists in the emsemble\n\t\tint j = sys.Particles().NumOfInceptedPAH(m_mech->AggModel(), 0);\n\t\tif (j > 0) {\n\t\t\t//There is already an inception PAH in the ensemble (should only be 1). \n\t\t\t//Just update it's statistical weight\n\t\t\tint Pindex = sys.Particles().IndexOfInceptedPAH(m_mech->AggModel(), 0);\n\t\t\tsp = sys.Particles().At(Pindex);\n\t\t\tint StatWeight = sp->getStatisticalWeight();\n\t\t\tsp->setStatisticalWeight(StatWeight + 1.0);\n\t\t\tsys.Particles().Update(Pindex);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t// Get the cell vertices\n\tfvector vertices = local_geom.cellVertices();\n\n\t// Sample a uniformly distributed position, note that this method\n\t// works whether the vertices come in increasing or decreasing order,\n\t// but 1d is assumed for now.\n\tdouble posn = vertices.front();\n\n\tconst double width = vertices.back() - posn;\n\n\tif (width > 0) {\n\t\tboost::uniform_01<rng_type&, double> uniformGenerator(rng);\n\t\t// There is some double spatial detail\n\t\tposn += width * uniformGenerator();\n\t\tsp = m_mech->CreateParticle(t, posn);\n\t}\n\telse {\n\t\t// Ignore all questions of position\n\t\tsp = m_mech->CreateParticle(t, 0);\n\t\t//This means creating the first PAH in the inception list. Not tested gl413\n\t}\n\n\tsp->UpdateCache();\n\n\t// Add particle to main ensemble.\n\tif (sys.ParticleCount() < sys.Particles().Capacity()){\n\t\tsys.Particles().Add(*sp, rng);\n\t}\n\telse\n\t{\n\t\tstd::cout << \"No room in ensemble after PAH inception\" << std::endl;\n\t\tsys.Particles().Add(*sp, rng);\n\t}\n\n\t// Update gas-phase chemistry of system.\n\tadjustGas(sys, sp->getStatisticalWeight());\n\n\n    return 0;\n}\n\n/*!\n * Ensure the number of InceptedPAHs in the particle ensemble is consistent with that in the gas phase\n * If the number of InceptedPAHs (i.e. A1, A2 or A4) in the particle ensemble is less than that in the gas phase, new InceptedPAHs will be created (transfer from gas phase) and added to the ensemble. In contrast, if the number of InceptedPAHs in the particle ensemble are more than that in the gas phase, the redundant InceptedPAH will be removed accordingly.\n * This function is only used for PAH-PP model currently\n * The mass form gas phase will be transfered to particle ensemble by using this function\n *\n * \\param[in]       i           number of pyrene supposed in the ensemble\n * \\param[in]\t\tk \t\t\tIndex of PAH in inception list to incept\n * \\param[in]       t           Time\n * \\param[in,out]   sys         System to update\n * \\param[in]       iterm       Process term responsible for this event\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      0 on success, otherwise negative.\n */\nint PAHInception::AddInceptedPAH(const int i, const int k, const double t, Cell &sys,rng_type &rng) const {\n\n    Particle *sp = NULL;\n\n    // return current number of pyrene in the emsemble\n    int j = sys.Particles().NumOfInceptedPAH(m_mech->AggModel(), k);\n\n\tif (i > j)\n\t{\n\t\tif (sys.ParticleModel()->Components(0)->WeightedPAHs()){\n\t\t\tif (j > 0) {\n\t\t\t\t//There is already an inception PAH in the ensemble (should only be 1). \n\t\t\t\t//Just update it's statistical weight\n\t\t\t\tint Pindex = sys.Particles().IndexOfInceptedPAH(m_mech->AggModel(), k);\n\t\t\t\tsp = sys.Particles().At(Pindex);\n\t\t\t\tint StatWeight = sp->getStatisticalWeight();\n\t\t\t\tsp->setStatisticalWeight(StatWeight + i - j);\n\t\t\t\tsys.Particles().Update(Pindex);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tsp = m_mech->CreateParticle(t, k);\n\t\t\t\tsp->setStatisticalWeight(i);\n\t\t\t\tsp->UpdateCache();\n\t\t\t\t// Add particle to main ensemble.\n\t\t\t\tsys.Particles().Add(*sp, rng);\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\twhile (i > j)\n\t\t\t{\n\n\t\t\t\t// Ignore all questions of position\n\t\t\t\tsp = m_mech->CreateParticle(t, k);\n\t\t\t\tsp->UpdateCache();\n\t\t\t\t// Add particle to main ensemble.\n\t\t\t\tsys.Particles().Add(*sp, rng);\n\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n    }\n    else if (i<j){\n\t\tif (sys.ParticleModel()->Components(0)->WeightedPAHs()){\n\t\t\tint Pindex = sys.Particles().IndexOfInceptedPAH(m_mech->AggModel(), k);\n\t\t\tsp = sys.Particles().At(Pindex);\n\t\t\tint StatWeight = sp->getStatisticalWeight();\n\t\t\tsp->setStatisticalWeight(StatWeight + i - j);\n\t\t\tsys.Particles().Update(Pindex);\n\t\t}\n\t\telse{\n\t\t\twhile (i < j)\n\t\t\t{\n\t\t\t\tint Pindex = sys.Particles().IndexOfInceptedPAH(m_mech->AggModel(), k);\n\t\t\t\tif (Pindex < 0)\n\t\t\t\t\tthrow runtime_error(\"There are no InceptedPAH in the ensemble, and all the InceptedPAH molecules are consumed due to unknown reason(Mops, Sweep::PAHInception::Perform).\");\n\t\t\t\tsys.Particles().Remove(Pindex);\n\t\t\t\t//std::cout<<\"j-i is \"<<j-i<<std::endl;\n\t\t\t\tj--;\n\t\t\t}\n\t\t}\n    }\n    //i==j do nothong\n    else return 0;\n    return 0;\n}\n\n// TOTAL RATE CALCULATIONS.\n\n// Returns rate of the process for the given system.\ndouble PAHInception::Rate(double t, const Cell &sys,\n                        const Geometry::LocalGeometry1d &local_geom) const\n{\n    const double rate = NA * sys.GasPhase().PropertyValue(mPAHFormationIndex) * A(); \n\n    // PAHFormation rate may be negative which means no inception\n    if(rate < 0.0)\n        return 0.0;\n\n    return rate *  sys.SampleVolume();\n}\n\n\n// RATE TERM CALCULATIONS.\n\n// Returns the number of rate terms for this process (one).\nunsigned int PAHInception::TermCount(void) const {return 1;}\n\n// Calculates the rate terms given an iterator to a double vector. The\n// iterator is advanced to the position after the last term for this\n// process.  Returns the sum of all terms.\ndouble PAHInception::RateTerms(const double t, const Cell &sys,\n                             const Geometry::LocalGeometry1d &local_geom,\n                             fvector::iterator &iterm) const\n{\n    // Calculate the single rate term and advance iterator.\n    *iterm = Rate(t, sys, local_geom);\n    return *(iterm++);\n}\n\n\n// READ/WRITE/COPY.\n\n// Creates a copy of the inception.\nPAHInception *const PAHInception::Clone(void) const {return new PAHInception(*this);}\n\n// Returns the process type.  Used to identify different\n// processes and for serialisation.\nProcessType PAHInception::ID(void) const {return PAH_Inception_ID;}\n\n// Writes the object to a binary stream.\nvoid PAHInception::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Serialize base class.\n        Inception::Serialize(out);\n\n        out.write(reinterpret_cast<const char*>(&mPAHFormationIndex), sizeof(mPAHFormationIndex));\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, PAHInception::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid PAHInception::Deserialize(std::istream &in, const Sweep::Mechanism &mech)\n{\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        switch (version) {\n            case 0:\n                // Deserialize base class.\n                Inception::Deserialize(in, mech);\n\n                in.read(reinterpret_cast<char*>(&mPAHFormationIndex), sizeof(mPAHFormationIndex));\n                 break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, PAHInception::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, PAHInception::Deserialize).\");\n    }\n}\n", "meta": {"hexsha": "fa98a00310d879d57ac931c7459500ffd8604914", "size": 11028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_pah_inception.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_pah_inception.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_pah_inception.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 31.4188034188, "max_line_length": 359, "alphanum_fraction": 0.664127675, "num_tokens": 2831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206879937726764, "lm_q2_score": 0.031143830647184973, "lm_q1q2_score": 0.006604634773357469}}
{"text": "//\r\n// $Id$\r\n//\r\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.\r\n//\r\n// The Original Code is the IDPicker project.\r\n//\r\n// The Initial Developer of the Original Code is Matt Chambers.\r\n//\r\n// Copyright 2017 Vanderbilt University\r\n//\r\n// Contributor(s):\r\n//\r\n\n#define PWIZ_SOURCE\n\n#include \"pwiz/utility/misc/Std.hpp\"\n#include \"pwiz/utility/chemistry/Chemistry.hpp\"\r\n#include \"IdpSqlExtensions.hpp\"\r\n#include \"boost/crc.hpp\"\r\n#include \"boost/range/algorithm/sort.hpp\"\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/framework/accumulator_set.hpp>\r\n#include \"../../freicore/percentile.hpp\"\r\n#include \"sqlite3ext.h\" /* Do not use <sqlite3.h>! */\r\n#include \"sqlite3pp.h\"\r\nSQLITE_EXTENSION_INIT1\r\n\r\nusing namespace pwiz::util;\r\nnamespace sqlite = sqlite3pp;\r\nnamespace accs = boost::accumulators;\r\n\r\n\r\nnamespace {\r\n\r\n    struct DistinctDoubleArraySum\r\n    {\r\n        typedef DistinctDoubleArraySum MyType;\r\n        set<int> arrayIds;\r\n        vector<double> result;\r\n        boost::crc_32_type crc32;\r\n\r\n        DistinctDoubleArraySum(int arrayLength) : result((size_t)arrayLength, 0.0) {}\r\n\r\n        static void Step(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n        {\r\n            void* aggContext = sqlite3_aggregate_context(context, sizeof(MyType*));\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            MyType** ppThis = static_cast<MyType**>(aggContext);\r\n            MyType*& pThis = *ppThis;\r\n\r\n            if (numValues > 1 || values[0] == NULL)\r\n                return;\r\n\r\n            int arrayByteCount = sqlite3_value_bytes(values[0]);\r\n            int arrayLength = arrayByteCount / 8;\r\n            const char* arrayBytes = static_cast<const char*>(sqlite3_value_blob(values[0]));\r\n            if (arrayBytes == NULL)\r\n                return;\r\n\r\n            if (arrayByteCount % 8 > 0)\r\n                throw runtime_error(\"distinct_double_array_sum only works with BLOBs of double precision floats\");\r\n\r\n            if (pThis == NULL)\r\n                pThis = new DistinctDoubleArraySum(arrayLength);\r\n            else\r\n                pThis->crc32.reset();\r\n\r\n            // if the arrayId was already in the set, ignore its values\r\n            pThis->crc32.process_bytes(arrayBytes, arrayByteCount);\r\n            int arrayId = pThis->crc32.checksum();\r\n            if (!pThis->arrayIds.insert(arrayId).second)\r\n                return;\r\n\r\n            const double* arrayValues = reinterpret_cast<const double*>(arrayBytes);\r\n\r\n            for (int i = 0; i < arrayLength; ++i)\r\n                pThis->result[i] += arrayValues[i];\r\n        }\r\n\r\n        static void Final(sqlite3_context* context)\r\n        {\r\n            void* aggContext = sqlite3_aggregate_context(context, 0);\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            MyType** ppThis = static_cast<MyType**>(aggContext);\r\n            MyType*& pThis = *ppThis;\r\n\r\n            if (pThis == NULL)\r\n                pThis = new DistinctDoubleArraySum(0);\r\n\r\n            sqlite3_result_blob(context, pThis->result.empty() ? NULL : &pThis->result[0], pThis->result.size() * sizeof(double), SQLITE_TRANSIENT);\r\n\r\n            delete pThis;\r\n        }\r\n    };\r\n\r\n\r\n    struct DistinctDoubleArrayMean\r\n    {\r\n        typedef DistinctDoubleArrayMean MyType;\r\n        set<int> arrayIds;\r\n        vector<double> result;\r\n        boost::crc_32_type crc32;\r\n\r\n        DistinctDoubleArrayMean(int arrayLength) : result((size_t)arrayLength, 0.0) {}\r\n\r\n        static void Step(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n        {\r\n            DistinctDoubleArraySum::Step(context, numValues, values);\r\n        }\r\n\r\n        static void Final(sqlite3_context* context)\r\n        {\r\n            void* aggContext = sqlite3_aggregate_context(context, 0);\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            MyType** ppThis = static_cast<MyType**>(aggContext);\r\n            MyType*& pThis = *ppThis;\r\n\r\n            if (pThis == NULL)\r\n                pThis = new DistinctDoubleArrayMean(0);\r\n\r\n            // divide sum by number of elements\r\n            if (!pThis->result.empty())\r\n                for (auto& r : pThis->result)\r\n                    r /= pThis->arrayIds.size();\r\n\r\n            sqlite3_result_blob(context, pThis->result.empty() ? NULL : &pThis->result[0], pThis->result.size() * sizeof(double), SQLITE_TRANSIENT);\r\n\r\n            delete pThis;\r\n        }\r\n    };\r\n\r\n    struct DistinctDoubleArrayMedian\r\n    {\r\n        typedef DistinctDoubleArrayMedian MyType;\r\n        typedef accs::accumulator_set<double, accs::stats<accs::tag::percentile> > MedianAccumulator;\r\n        set<int> arrayIds;\r\n        vector<MedianAccumulator> medianAccumulators;\r\n        boost::crc_32_type crc32;\r\n\r\n        DistinctDoubleArrayMedian(int arrayLength) : medianAccumulators((size_t)arrayLength) {}\r\n\r\n        static void Step(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n        {\r\n            void* aggContext = sqlite3_aggregate_context(context, sizeof(MyType*));\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            MyType** ppThis = static_cast<MyType**>(aggContext);\r\n            MyType*& pThis = *ppThis;\r\n\r\n            if (numValues > 1 || values[0] == NULL)\r\n                return;\r\n\r\n            int arrayByteCount = sqlite3_value_bytes(values[0]);\r\n            int arrayLength = arrayByteCount / 8;\r\n            const char* arrayBytes = static_cast<const char*>(sqlite3_value_blob(values[0]));\r\n            if (arrayBytes == NULL)\r\n                return;\r\n\r\n            if (arrayByteCount % 8 > 0)\r\n                throw runtime_error(\"distinct_double_array_sum only works with BLOBs of double precision floats\");\r\n\r\n            if (pThis == NULL)\r\n                pThis = new DistinctDoubleArrayMedian(arrayLength);\r\n            else\r\n                pThis->crc32.reset();\r\n\r\n            // if the arrayId was already in the set, ignore its values\r\n            pThis->crc32.process_bytes(arrayBytes, arrayByteCount);\r\n            int arrayId = pThis->crc32.checksum();\r\n            if (!pThis->arrayIds.insert(arrayId).second)\r\n                return;\r\n\r\n            const double* arrayValues = reinterpret_cast<const double*>(arrayBytes);\r\n\r\n            for (int i = 0; i < arrayLength; ++i)\r\n                (pThis->medianAccumulators[i])(arrayValues[i]);\r\n        }\r\n\r\n        static void Final(sqlite3_context* context)\r\n        {\r\n            void* aggContext = sqlite3_aggregate_context(context, 0);\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            MyType** ppThis = static_cast<MyType**>(aggContext);\r\n            MyType*& pThis = *ppThis;\r\n\r\n            if (pThis == NULL)\r\n                pThis = new DistinctDoubleArrayMedian(0);\r\n\r\n            // divide sum by number of elements\r\n            vector<double> result;\r\n            result.reserve(pThis->medianAccumulators.size());\r\n            if (!pThis->medianAccumulators.empty())\r\n                for (auto& acc : pThis->medianAccumulators)\r\n                    result.push_back(accs::percentile(acc, accs::percentile_number = 50));\r\n\r\n            sqlite3_result_blob(context, result.empty() ? NULL : &result[0], result.size() * sizeof(double), SQLITE_TRANSIENT);\r\n\r\n            delete pThis;\r\n        }\r\n    };\r\n\r\n    struct DistinctTukeyBiweightAverage\r\n    {\r\n        typedef DistinctTukeyBiweightAverage MyType;\r\n        set<int> arrayIds;\r\n        vector<double> result;\r\n        vector<vector<double> > tukeyBuffer;\r\n        boost::crc_32_type crc32;\r\n\r\n        DistinctTukeyBiweightAverage(int arrayLength) : result((size_t)arrayLength, 0.0), tukeyBuffer(arrayLength) {}\r\n\r\n        static void Step(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n        {\r\n            void* aggContext = sqlite3_aggregate_context(context, sizeof(MyType*));\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            MyType** ppThis = static_cast<MyType**>(aggContext);\r\n            MyType*& pThis = *ppThis;\r\n\r\n            if (numValues > 1 || values[0] == NULL)\r\n                return;\r\n\r\n            int arrayByteCount = sqlite3_value_bytes(values[0]);\r\n            int arrayLength = arrayByteCount / 8;\r\n            const char* arrayBytes = static_cast<const char*>(sqlite3_value_blob(values[0]));\r\n            if (arrayBytes == NULL)\r\n                return;\r\n\r\n            if (arrayByteCount % 8 > 0)\r\n                throw runtime_error(\"distinct_double_array_sum only works with BLOBs of double precision floats\");\r\n\r\n            if (pThis == NULL)\r\n                pThis = new DistinctTukeyBiweightAverage(arrayLength);\r\n            else\r\n                pThis->crc32.reset();\r\n\r\n            // if the arrayId was already in the set, ignore its values\r\n            pThis->crc32.process_bytes(arrayBytes, arrayByteCount);\r\n            int arrayId = pThis->crc32.checksum();\r\n            if (!pThis->arrayIds.insert(arrayId).second)\r\n                return;\r\n\r\n            const double* arrayValues = reinterpret_cast<const double*>(arrayBytes);\r\n\r\n            for (int i = 0; i < arrayLength; ++i)\r\n                pThis->tukeyBuffer[i].push_back(arrayValues[i]);\r\n        }\r\n\r\n        static inline double weight_bisquare(double x)\r\n        {\r\n            return fabs(x) <= 1.0 ? (1 - x*x) * (1 - x*x) : 0;\r\n        }\r\n\r\n        static inline double safe_log(double x)\r\n        {\r\n            return x > 1 ? std::log(x) : 0.0;\r\n        }\r\n\r\n        static void Final(sqlite3_context* context) { Final(context, false); }\r\n\r\n        static void FinalLog(sqlite3_context* context){ Final(context, true); }\r\n\r\n        static void Final(sqlite3_context* context, bool logValues)\r\n        {\r\n            void* aggContext = sqlite3_aggregate_context(context, 0);\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            MyType** ppThis = static_cast<MyType**>(aggContext);\r\n            MyType*& pThis = *ppThis;\r\n\r\n            if (pThis == NULL)\r\n                pThis = new DistinctTukeyBiweightAverage(0);\r\n            else\r\n            {\r\n                double c = 5.0;\r\n                double epsilon = 0.0001;\r\n\r\n                vector<double> medians(pThis->tukeyBuffer[0].size());\r\n                auto length = pThis->tukeyBuffer[0].size();\r\n                for (int column = 0; column < pThis->tukeyBuffer.size(); ++column)\r\n                {\r\n                    vector<double>& values = pThis->tukeyBuffer[column];\r\n                    if (logValues)\r\n                        std::transform(values.begin(), values.end(), values.begin(), static_cast<double(*)(double)>(safe_log));\r\n\r\n                    medians = values;\r\n                    boost::range::sort(medians);\r\n\r\n                    double median = (length % 2 == 0) ? (medians[length / 2 - 1] + medians[length / 2]) / 2.0 : medians[length / 2];\r\n\r\n                    for (size_t i = 0; i < length; ++i)\r\n                        medians[i] = fabs(values[i] - median);\r\n                    boost::range::sort(medians);\r\n\r\n                    double S = (length % 2 == 0) ? (medians[length / 2 - 1] + medians[length / 2]) / 2.0 : medians[length / 2];\r\n\r\n                    for (size_t i = 0; i < length; ++i)\r\n                        medians[i] = (values[i] - median) / (c*S + epsilon);\r\n\r\n                    double sum = 0.0;\r\n                    double sumw = 0.0;\r\n                    for (size_t i = 0; i < length; ++i)\r\n                    {\r\n                        sum += weight_bisquare(medians[i]) * values[i];\r\n                        sumw += weight_bisquare(medians[i]);\r\n                    }\r\n\r\n                    pThis->result[column] = sum / sumw;\r\n                }\r\n            }\r\n\r\n            sqlite3_result_blob(context, pThis->result.empty() ? NULL : &pThis->result[0], pThis->result.size() * sizeof(double), SQLITE_TRANSIENT);\r\n\r\n            delete pThis;\r\n        }\r\n    };\r\n\r\n    void PrintDoubleArray(sqlite3_context* context, int numValues, sqlite3_value** values)\n    {\r\n        if (numValues != 1)\r\n        {\r\n            sqlite3_result_error(context, \"[PRINT_DOUBLE_ARRAY] requires 1 double array argument\", -1);\r\n            return;\r\n        }\n\n        if (values[0] == NULL)\n        {\n            sqlite3_result_null(context);\n            return;\n        }\n\r\n        const void* blob = sqlite3_value_blob(values[0]);\n        int size = sqlite3_value_bytes(values[0]) / sizeof(double);\n\n        char* str;\n        int strSize;\n        if (blob == NULL)\n        {\n            strSize = size * 2; // all 0s with commas between plus a null terminator\n            str = (char*)sqlite3_malloc(strSize); // all 0s with commas between plus a null terminator\n            for (size_t i = 0; i < size; ++i)\n                str[i*2] = '0', str[i*2 + 1] = ',';\n            str[size * 2 - 1] = 0;\n        }\n        else\n        {\n            strSize = size * 30;\n            str = (char*)sqlite3_malloc(strSize);\n\n            const double* blobArray = reinterpret_cast<const double*>(blob);\n\n            int offset = 0;\n            for (size_t i = 0; i < size; ++i)\n                offset += sprintf(&str[offset], \"%.5f,\", blobArray[i]);\n        }\n\n        sqlite3_result_text(context, str, strSize, sqlite3_free);\n    }\r\n\r\n    struct GroupConcatEx\r\n    {\n        static void Step(sqlite3_context *context, int argc, sqlite3_value **argv)\n        {\n            const char *zVal;\n            const char *zSep;\n            int nVal, nSep;\n            assert(argc == 1 || argc == 2);\n            if (sqlite3_value_type(argv[0]) == SQLITE_NULL) return;\r\n\r\n            void* aggContext = sqlite3_aggregate_context(context, sizeof(string*));\r\n            if (aggContext == NULL)\r\n                throw runtime_error(sqlite3_errmsg(sqlite3_context_db_handle(context)));\r\n\r\n            string** ppAccum = static_cast<string**>(aggContext);\r\n            string*& pAccum = *ppAccum;\n\n            if (!pAccum)\r\n                pAccum = new string();\n\n            int firstTerm = pAccum->empty();\n            if (!firstTerm){\n                if (argc == 2){\n                    zSep = (char*)sqlite3_value_text(argv[1]);\n                    nSep = sqlite3_value_bytes(argv[1]);\n                }\n                else{\n                    zSep = separator_.c_str();\n                    nSep = separator_.length();\n                }\n                if (zSep) pAccum->append(zSep, zSep + nSep);\n            }\n            zVal = (char*)sqlite3_value_text(argv[0]);\n            nVal = sqlite3_value_bytes(argv[0]);\n            if (zVal) pAccum->append(zVal, zVal + nVal);\n        }\n\n        static void Final(sqlite3_context *context)\n        {\n            string **pAccum = (string**)sqlite3_aggregate_context(context, 0);\n            if (pAccum && *pAccum)\n            {\n                sqlite3_result_text(context, (*pAccum)->c_str(), (*pAccum)->length(), SQLITE_TRANSIENT);\n                delete *pAccum;\n            }\n        }\n\n        static string separator_;\r\n    };\r\n\r\n    string GroupConcatEx::separator_ = \",\";\r\n\r\n    void SortUnmappedLast(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n    {\r\n        if (numValues != 1)\r\n        {\r\n            sqlite3_result_error(context, \"[SORT_UNMAPPED_LAST] requires 1 text argument\", -1);\r\n            return;\r\n        }\n\n        if (values[0] == NULL)\n        {\n            sqlite3_result_null(context);\n            return;\n        }\r\n\r\n        const unsigned char* text = sqlite3_value_text(values[0]);\r\n        auto textRange = boost::make_iterator_range(text, text + sqlite3_value_bytes(values[0]));\r\n\r\n        if (textRange.size() < 3 || std::find(textRange.begin(), textRange.end(), GroupConcatEx::separator_[0]) == textRange.end())\r\n        {\n            sqlite3_result_text(context, (const char*) text, textRange.size(), NULL);\r\n            return;\r\n        }\r\n\r\n        vector<string> tokens;\r\n        bal::split(tokens, textRange, bal::is_any_of(GroupConcatEx::separator_));\r\n\r\n        std::sort(tokens.begin(), tokens.end(), [&](const string& lhs, const string& rhs)\n        {\n            bool lhsUnmapped = bal::starts_with(lhs, \"Unmapped_\");\n            bool rhsUnmapped = bal::starts_with(rhs, \"Unmapped_\");\n            if (lhsUnmapped && rhsUnmapped)\n                return lhs < rhs;\n            if (lhsUnmapped)\n                return false;\n            if (rhsUnmapped)\n                return true;\n            return lhs < rhs;\n        });\n\n        char* result = (char*)sqlite3_malloc(textRange.size()+1);\n        size_t offset = 0;\n        for (const string& token : tokens)\n        {\n            std::copy(token.begin(), token.end(), result + offset);\n            offset += token.length() + 1;\n            result[offset-1] = GroupConcatEx::separator_[0];\n        }\n        result[textRange.size()] = 0;\n\n        sqlite3_result_text(context, result, textRange.size()+1, sqlite3_free);\r\n    };\r\n\r\n    /// Automatically choose monoisotopic or average mass error based on the following logic:\r\n    /// if the absolute value of monoisotopic error is less than absolute value of average error\r\n    /// or if the monoisotopic error is nearly a multiple of a neutron mass,\r\n    /// then return the monoisotopic error.\r\n    void GetSmallerMassError(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n    {\r\n        if (numValues != 2 || values[0] == NULL || values[1] == NULL)\r\n        {\r\n            sqlite3_result_error(context, \"[GET_SMALLER_MASS_ERROR] requires 2 numeric arguments\", -1);\r\n            return;\r\n        }\r\n\r\n        double mono = sqlite3_value_double(values[0]);\r\n        double avg = sqlite3_value_double(values[1]);\r\n\r\n        bool monoisotopic = fabs(mono) < fabs(avg) || fmod(fabs(mono), pwiz::chemistry::Neutron) < fabs(avg);\r\n        sqlite3_result_double(context, monoisotopic ? mono : avg);\r\n    }\r\n\r\n    /// Same as GetSmallerMassError(), but when monoisotopic error is used because it is nearly a multiple of a neutron mass,\r\n    /// the returned error is adjusted to factor out the neutron contribution; the result is the true monoisotopic error.\r\n    void GetSmallerMassErrorAdjusted(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n    {\r\n        if (numValues != 2 || values[0] == NULL || values[1] == NULL)\r\n        {\r\n            sqlite3_result_error(context, \"[GET_SMALLER_MASS_ERROR_ADJUSTED] requires 2 numeric arguments\", -1);\r\n            return;\r\n        }\r\n\r\n        double mono = sqlite3_value_double(values[0]);\r\n        double avg = sqlite3_value_double(values[1]);\r\n\r\n        if (fabs(mono) < fabs(avg))\r\n            sqlite3_result_double(context, mono);\r\n        else\r\n        {\r\n            double monoModNeutron = fmod(mono, pwiz::chemistry::Neutron);\r\n            bool monoisotopic = fabs(monoModNeutron) < fabs(avg);\r\n            sqlite3_result_double(context, monoisotopic ? monoModNeutron : avg);\r\n        }\r\n    }\r\n\r\n    // WITHIN_MASS_TOLERANCE_MZ(observed, expected, tolerance)\r\n    void WithinMassToleranceMZ(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n    {\r\n        if (numValues != 3 || values[0] == NULL || values[1] == NULL || values[2] == NULL)\r\n        {\r\n            sqlite3_result_error(context, \"[WITHIN_MASS_TOLERANCE_MZ] requires 3 numeric arguments\", -1);\r\n            return;\r\n        }\r\n\r\n        double observed = sqlite3_value_double(values[0]);\r\n        double expected = sqlite3_value_double(values[1]);\r\n        double tolerance = sqlite3_value_double(values[2]);\r\n        double lower_bound = expected - tolerance;\r\n        double upper_bound = expected + tolerance;\r\n\r\n        sqlite3_result_int(context, (observed > lower_bound && observed < upper_bound) ? 1 : 0);\r\n    }\r\n\r\n    // WITHIN_MASS_TOLERANCE_PPM(observed, expected, tolerance)\r\n    void WithinMassTolerancePPM(sqlite3_context* context, int numValues, sqlite3_value** values)\r\n    {\r\n        if (numValues != 3 || values[0] == NULL || values[1] == NULL || values[2] == NULL)\r\n        {\r\n            sqlite3_result_error(context, \"[WITHIN_MASS_TOLERANCE_PPM] requires 3 numeric arguments\", -1);\r\n            return;\r\n        }\r\n\r\n        double observed = sqlite3_value_double(values[0]);\r\n        double expected = sqlite3_value_double(values[1]);\r\n        double tolerance = sqlite3_value_double(values[2]);\r\n        double ppmDelta = fabs(expected) * tolerance * 1e-6;\r\n        double lower_bound = expected - ppmDelta;\r\n        double upper_bound = expected + ppmDelta;\r\n\r\n        sqlite3_result_int(context, (observed > lower_bound && observed < upper_bound) ? 1 : 0);\r\n    }\r\n\r\n} // namespace\r\n\n\n// no need to rename IDPicker namespace for these global functions\nnamespace IDPicker {\n\r\nPWIZ_API_DECL void setGroupConcatSeparator(const std::string& separator) { GroupConcatEx::separator_ = separator; }\r\n\r\nPWIZ_API_DECL const std::string& getGroupConcatSeparator() { return GroupConcatEx::separator_; }\r\n\r\n} // IDPicker\r\n\r\n\r\nextern \"C\" {\r\n\r\nPWIZ_API_DECL int sqlite3_idpsqlextensions_init(sqlite3 *idpDbConnection, char **pzErrMsg, const sqlite3_api_routines *pApi)\r\n{\r\n    int rc = SQLITE_OK;\r\n    SQLITE_EXTENSION_INIT2(pApi);\r\n\n    rc += sqlite3_create_function(idpDbConnection, \"distinct_double_array_sum\", -1, SQLITE_ANY, 0, NULL, &DistinctDoubleArraySum::Step, &DistinctDoubleArraySum::Final);\n    rc += sqlite3_create_function(idpDbConnection, \"distinct_double_array_mean\", -1, SQLITE_ANY, 0, NULL, &DistinctDoubleArrayMean::Step, &DistinctDoubleArrayMean::Final);\n    rc += sqlite3_create_function(idpDbConnection, \"distinct_double_array_median\", -1, SQLITE_ANY, 0, NULL, &DistinctDoubleArrayMedian::Step, &DistinctDoubleArrayMedian::Final);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"distinct_double_array_tukey_biweight_average\", -1, SQLITE_ANY, 0, NULL, &DistinctTukeyBiweightAverage::Step, &DistinctTukeyBiweightAverage::Final);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"distinct_double_array_tukey_biweight_log_average\", -1, SQLITE_ANY, 0, NULL, &DistinctTukeyBiweightAverage::Step, &DistinctTukeyBiweightAverage::FinalLog);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"print_double_array\", 1, SQLITE_ANY, 0, &PrintDoubleArray, NULL, NULL);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"group_concat\", -1, SQLITE_ANY, 0, NULL, &GroupConcatEx::Step, &GroupConcatEx::Final);\r\n    rc += sqlite3_create_function(idpDbConnection, \"group_concat_ex\", -1, SQLITE_ANY, 0, NULL, &GroupConcatEx::Step, &GroupConcatEx::Final);\r\n    \r\n    rc += sqlite3_create_function(idpDbConnection, \"sort_unmapped_last\", 1, SQLITE_ANY, 0, &SortUnmappedLast, NULL, NULL);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"get_smaller_mass_error\", 2, SQLITE_ANY, 0, &GetSmallerMassError, NULL, NULL);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"get_smaller_mass_error_adjusted\", 2, SQLITE_ANY, 0, &GetSmallerMassErrorAdjusted, NULL, NULL);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"within_mass_tolerance_mz\", 3, SQLITE_ANY, 0, &WithinMassToleranceMZ, NULL, NULL);\r\n\r\n    rc += sqlite3_create_function(idpDbConnection, \"within_mass_tolerance_ppm\", 3, SQLITE_ANY, 0, &WithinMassTolerancePPM, NULL, NULL);\r\n\r\n    return rc;\r\n}\r\n\r\n} // extern C\r\n", "meta": {"hexsha": "feee1480e76368dae945de5f44d03161ee7afab0", "size": 24228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz_tools/Bumbershoot/idpicker/Qonverter/IdpSqlExtensions.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz_tools/Bumbershoot/idpicker/Qonverter/IdpSqlExtensions.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz_tools/Bumbershoot/idpicker/Qonverter/IdpSqlExtensions.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5882352941, "max_line_length": 207, "alphanum_fraction": 0.5911754994, "num_tokens": 5690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.01744248384237626, "lm_q1q2_score": 0.006585247015351579}}
{"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/// Detection and representation of allowed three-phonon processes.\n\n#include <cstddef>\n#include <cmath>\n#include <array>\n#include <vector>\n#include <functional>\n#include <boost/mpi.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/serialization/array.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/unique_ptr.hpp>\n#include <structures.hpp>\n#include <qpoint_grid.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\n\nnamespace alma {\n/// Process type (emission or absorption).\nenum class threeph_type { emission = -1, absorption = 1 };\n/// Representation of a three-phonon process.\nclass Threeph_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    /// Has the phase space of the process been computed yet?\n    bool gaussian_computed;\n    /// Gaussian factor of the process, coming from the\n    /// regularized Dirac delta.\n    double gaussian;\n    /// Has the matrix element of the process been computed yet?\n    bool vp2_computed;\n    /// Modulus squared of the matrix element of the process.\n    double vp2;\n    /// Serialize non-const members of the class.\n    ///\n\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_computed;\n        ar & this->gaussian;\n        ar & this->vp2_computed;\n        ar & this->vp2;\n        ar & this->c;\n        ar & this->q;\n        ar & this->alpha;\n        ar & this->type;\n    }\n\n\npublic:\n    /// Equivalence class of the first phonon.\n    std::size_t c;\n    /// q point indices of each of the three phonons involved.\n    std::array<std::size_t, 3> q;\n    /// Mode indices of the three phonons involved.\n    std::array<std::size_t, 3> alpha;\n    /// Type of process.\n    threeph_type type;\n    /// Default constructor this is to comply with DefaultConstructible required\n    /// by boost for serialization maps with values of this class\n    Threeph_process(){};\n    /// Basic constructor.\n    Threeph_process(std::size_t _c,\n                    const std::array<std::size_t, 3>& _q,\n                    const std::array<std::size_t, 3>& _alpha,\n                    threeph_type _type,\n                    double _domega,\n                    double _sigma)\n        : domega(_domega), sigma(_sigma), gaussian_computed(false),\n          vp2_computed(false), c(_c), q(std::move(_q)),\n          alpha(std::move(_alpha)), type(_type) {\n    }\n\n    /// Copy constructor.\n    Threeph_process(const Threeph_process& original)\n        : domega(original.domega), sigma(original.sigma),\n          gaussian_computed(original.gaussian_computed),\n          gaussian(original.gaussian), vp2_computed(original.vp2_computed),\n          vp2(original.vp2), c(original.c), q(original.q),\n          alpha(original.alpha), type(original.type) {\n    }\n\n    /// Copy assignament operator:\n    Threeph_process& operator=(const Threeph_process& rhs) {\n        this->domega = rhs.domega;\n        this->sigma = rhs.sigma;\n        this->gaussian_computed = rhs.gaussian_computed;\n        this->gaussian = rhs.gaussian;\n        this->vp2_computed = rhs.vp2_computed;\n        this->vp2 = rhs.vp2;\n        this->c = rhs.c;\n        this->q = {rhs.q[0], rhs.q[1], rhs.q[2]};\n        this->alpha = rhs.alpha;\n        this->type = rhs.type;\n        return *this;\n    }\n\n\n    /// Move constructor\n    Threeph_process(Threeph_process&& rhs) {\n        using std::swap;\n        swap(this->domega, rhs.domega);\n        swap(this->sigma, rhs.sigma);\n        swap(this->gaussian_computed, rhs.gaussian_computed);\n        swap(this->gaussian, rhs.gaussian);\n        swap(this->vp2_computed, rhs.vp2_computed);\n        swap(this->vp2, rhs.vp2);\n        swap(this->c, rhs.c);\n        swap(this->q, rhs.q);\n        swap(this->alpha, rhs.alpha);\n        swap(this->type, rhs.type);\n    }\n\n    /// Swap function\n    /// It is required by sorting algorithms\n    void swap(Threeph_process& lhs, Threeph_process& rhs) {\n        using std::swap;\n        swap(lhs.domega, rhs.domega);\n        swap(lhs.sigma, rhs.sigma);\n        swap(lhs.gaussian_computed, rhs.gaussian_computed);\n        swap(lhs.gaussian, rhs.gaussian);\n        swap(lhs.vp2_computed, rhs.vp2_computed);\n        swap(lhs.vp2, rhs.vp2);\n        swap(lhs.c, rhs.c);\n        swap(lhs.q, rhs.q);\n        swap(lhs.alpha, rhs.alpha);\n        swap(lhs.type, rhs.type);\n    }\n\n    /// Move assignament operator:\n    Threeph_process& operator=(Threeph_process&& rhs) {\n        using std::swap;\n        swap(this->domega, rhs.domega);\n        swap(this->sigma, rhs.sigma);\n        swap(this->gaussian_computed, rhs.gaussian_computed);\n        swap(this->gaussian, rhs.gaussian);\n        swap(this->vp2_computed, rhs.vp2_computed);\n        swap(this->vp2, rhs.vp2);\n        swap(this->c, rhs.c);\n        swap(this->q, rhs.q);\n        swap(this->alpha, rhs.alpha);\n        swap(this->type, rhs.type);\n        return *this;\n    }\n\n\n    /// Comparison operator\n    /// It is built in top of tuples as they have the by construction the\n    /// desired ordering\n    bool operator<(const Threeph_process& rhs) const {\n        return std::tuple<std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          int>(this->q[0],\n                               this->q[1],\n                               this->q[2],\n                               this->alpha[0],\n                               this->alpha[1],\n                               this->alpha[2],\n                               static_cast<int>(this->type)) <\n               std::tuple<std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          std::size_t,\n                          int>(rhs.q[0],\n                               rhs.q[1],\n                               rhs.q[2],\n                               rhs.alpha[0],\n                               rhs.alpha[1],\n                               rhs.alpha[2],\n                               static_cast<int>(rhs.type));\n    }\n\n\n    /// Compute and return the Gaussian factor of the process,\n    /// i.e., the amplitude of the regularized delta.\n    ///\n    /// The result is cached. It can be used to obtain the phase\n    /// space volume of three-phonon processes.\n    /// @return the Gaussian factor of the process\n    double compute_gaussian() {\n        if (!this->gaussian_computed) {\n            auto distr = boost::math::normal(0., this->sigma);\n            this->gaussian = boost::math::pdf(distr, this->domega);\n            this->gaussian_computed = true;\n        }\n        return this->gaussian;\n    }\n\n\n    /// Compute and return a weighted version of the Gaussian factor\n    /// of the process, containing essentially the same ingredients as\n    /// the scattering rate except for the matrix element and some\n    /// constants.\n    ///\n    /// The result can be used to obtain the weighted phase\n    /// space volume of three-phonon processes. The Gaussian factor\n    /// is cached.\n    /// @param[in] grid - regular grid with phonon spectrum\n    /// @param[in] T - temperature in K\n    /// @return the Bose-Einstein weighted Gaussian factor of the process at the\n    /// given temperature.\n    double compute_weighted_gaussian(const Gamma_grid& grid, double T);\n\n\n    /// Compute, return and store the modulus squared of the matrix\n    /// element of the process.\n    ///\n    /// @param[in] cell - description of the unit cell\n    /// @param[in] grid - regular grid with phonon spectrum\n    /// @param[in] thirdorder - third-order ifcs\n    /// @return the modulus squared of the matrix element\n    /// of the process\n    double compute_vp2(const Crystal_structure& cell,\n                       const Gamma_grid& grid,\n                       const std::vector<Thirdorder_ifcs>& thirdorder);\n\n    /// Return the modulus squared of the matrix element of the\n    /// process or throw an exception if it has not been calculated.\n    ///\n    /// @return the modulus squared of the matrix element\n    /// of the process\n    inline double get_vp2() const {\n        if (!this->vp2_computed)\n            throw exception(\"vp2 is not available\");\n        return this->vp2;\n    }\n\n    /// Return the modulus squared of the matrix element of the\n    /// process or throw an exception if it has not been calculated.\n    ///\n    /// @return None\n    inline void set_vp2(double A) {\n        this->vp2_computed = true;\n        this->vp2 = A;\n    }\n\n\n    /// @return the value of vp2_computed.\n    inline bool is_vp2_computed() const {\n        return this->vp2_computed;\n    }\n\n\n    /// Get the \"partial scattering rate\" Gamma for this process.\n    ///\n    /// vp2 must have been precomputed.\n    /// @param[in] grid - regular grid with phonon spectrum\n    /// @param[in] T - temperature in K\n    //  @param[in] compact - bool indicating if vp2 is already multiplied by\n    //  gaussian\n    /// @return Gamma, the partial scattering rate\n    double compute_gamma(const Gamma_grid& grid,\n                         double T,\n                         bool compact = false);\n\n    /// Get the reduced \"partial scattering rate\", meaning Gamma\n    /// without the scaling factor involving the BE occupations.\n    ///\n    /// vp2 must have been precomputed.\n    /// @param[in] grid - regular grid with phonon spectrum\n    /// @param[in] T - temperature in K\n    /// @return Gamma, the partial scattering rate\n    double compute_gamma_reduced(const Gamma_grid& grid, double T);\n\n    /// Get the coefficients of the three contributions to the\n    /// linearized scattering operator from this process.\n    ///\n    /// vp2 must have been precomputed.\n    /// @param[in] grid - regular grid with phonon spectrum\n    /// @param[in] n0 - precomputed Bose-Einstein distribution\n    /// @return an array with the three coefficients\n    Eigen::ArrayXd compute_collision(const Gamma_grid& grid,\n                                     const Eigen::ArrayXXd& n0);\n};\n/// Look for allowed three-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 three-phonon processes involving one\n/// phonon from that part and two other phonons from anywhere\n/// 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 Threeph_process objects\nstd::vector<Threeph_process> find_allowed_threeph(\n    const Gamma_grid& grid,\n    const boost::mpi::communicator& communicator,\n    double scalebroad = 1.0);\n\n/// Compute and store the three-phonon contribution to the RTA\n/// scattering rates for all vibrational modes on a grid.\n///\n/// @param[in] grid - phonon spectrum on a regular grid\n/// @param[in] processes - a vector of allowed\n/// three-phonon processes\n/// @param[in] T - the temperature in K\n/// @param[in] comm - an mpi communicator\nEigen::ArrayXXd calc_w0_threeph(const alma::Gamma_grid& grid,\n                                std::vector<alma::Threeph_process>& processes,\n                                double T,\n                                const boost::mpi::communicator& comm);\n\n/// Compute and store the three-phonon contribution to the RTA\n/// scattering rates for all vibrational modes on a grid. Take into\n/// account only those processes fullfilling a criterion.\n///\n/// @param[in] grid - phonon spectrum on a regular grid\n/// @param[in] processes - a vector of allowed\n/// three-phonon processes\n/// @param[in] T - the temperature in K\n/// @param[in] filter - boolean function returning true if a process must\n///                     be taken into account\n/// @param[in] comm - an mpi communicator\nEigen::ArrayXXd calc_w0_threeph(\n    const alma::Gamma_grid& grid,\n    std::vector<alma::Threeph_process>& processes,\n    double T,\n    std::function<bool(const Threeph_process&)> filter,\n    const boost::mpi::communicator& comm);\n} // namespace alma\n", "meta": {"hexsha": "b2e6204130830c6106e4dc0fcc383d628a90f484", "size": 14177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/processes.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/processes.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/processes.hpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8053333333, "max_line_length": 80, "alphanum_fraction": 0.6075333286, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416749665474, "lm_q2_score": 0.021615334653436125, "lm_q1q2_score": 0.0065719625529931745}}
{"text": "/**\n * Copyright (c) 2018, University Osnabrück\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 University Osnabrück 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 University Osnabrück 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 * AdaptiveKSearchSurface.cpp\n *\n *  Created on: 07.02.2011\n *      Author: Thomas Wiemann\n *   co-Author: Dominik Feldschnieders (dofeldsc@uos.de)\n */\n\n\n// External libraries in lvr source tree\n#include <Eigen/Dense>\n\n// boost libraries\n#include <boost/filesystem.hpp>\n\n#include <fstream>\n#include <set>\n#include <random>\n#include <algorithm>\n\n#include <lvr2/util/Factories.hpp>\n#include <lvr2/io/Progress.hpp>\n\nnamespace lvr2\n{\n\ntemplate<typename BaseVecT>\nAdaptiveKSearchSurface<BaseVecT>::AdaptiveKSearchSurface()\n    : m_calcMethod(0)\n{\n    this->setKi(10);\n    this->setKn(10);\n    this->setKd(10);\n}\n\ntemplate<typename BaseVecT>\nAdaptiveKSearchSurface<BaseVecT>::AdaptiveKSearchSurface(\n    PointBufferPtr buffer,\n    std::string searchTreeName,\n    int kn,\n    int ki,\n    int kd,\n    int calcMethod,\n    string posefile\n) :\n    PointsetSurface<BaseVecT>(buffer),\n    m_searchTreeName(searchTreeName),\n    m_calcMethod(calcMethod)\n{\n    this->setKi(ki);\n    this->setKn(kn);\n    this->setKd(kd);\n\n    init();\n\n\n    this->m_searchTree = getSearchTree<BaseVecT>(m_searchTreeName, buffer);\n\n    if(!this->m_searchTree)\n    {\n       this->m_searchTree = getSearchTree<BaseVecT>(\"flann\", buffer);\n       cout << timestamp.getElapsedTime() << \"No valid search tree specified (\" << searchTreeName << \").\" << endl;\n       cout << timestamp.getElapsedTime() << \"Maybe you did not install the required library.\" << endl;\n       cout << timestamp.getElapsedTime() << \"Defaulting to flann.\" << endl;\n    }\n\n    if(posefile != \"\")\n    {\n        //panic_unimplemented(\"posefile handling\");\n        parseScanPoses(posefile);\n    }\n\n}\n\n template<typename BaseVecT>\n void AdaptiveKSearchSurface<BaseVecT>::parseScanPoses(string posefile)\n {\n     cout << timestamp << \"Parsing scan poses.\" << endl;\n     std::ifstream in(posefile.c_str());\n     if(!in.good())\n     {\n         cout << timestamp << \"Unable to open scan pose file \" << posefile << endl;\n         return;\n     }\n\n     // Read vertex information\n     float x, y, z;\n     std::vector<BaseVecT> v;\n     while(in.good())\n     {\n         in >> x >> y >> z;\n         v.push_back(BaseVecT(x, y, z));\n     }\n\n     if(v.size() > 0)\n     {\n         PointBufferPtr loader (new PointBuffer);\n         floatArr points(new float[3 * v.size()]);\n         for(size_t i = 0; i < v.size(); i++)\n         {\n             points[3 * i]       = v[i][0];\n             points[3 * i + 1]   = v[i][1];\n             points[3 * i + 2]   = v[i][2];\n         }\n\n         loader->setPointArray(points, v.size());\n         size_t n = v.size();\n\n         cout << timestamp << \"Creating pose search tree(\" << m_searchTreeName << \") with \"\n              << n << \" poses.\" << endl;\n\n\n\n         this->m_poseTree = getSearchTree<BaseVecT>(m_searchTreeName, loader);\n\n\n         if( !this->m_poseTree )\n         {\n             cout << timestamp << \"No Valid Searchtree class specified!\" << endl;\n             cout << timestamp << \"Class: \" << m_searchTreeName << endl;\n         }\n     }\n }\n\ntemplate<typename BaseVecT>\nvoid AdaptiveKSearchSurface<BaseVecT>::init()\n{\n    cout << timestamp.getElapsedTime() << \"##### Dataset statatistics: ##### \" << endl << endl;\n    cout << timestamp << \"Num points \\t: \" << this->m_pointBuffer->numPoints() << endl;\n    cout << timestamp << this->m_boundingBox << endl;\n    cout << endl;\n    this->m_centroid = BaseVecT(0.0, 0.0, 0.0);\n}\n\n\n\ntemplate<typename BaseVecT>\nvoid AdaptiveKSearchSurface<BaseVecT>::calculateSurfaceNormals()\n{\n    int k_0 = this->m_kn;\n    size_t numPoints = this->m_pointBuffer->numPoints();\n    FloatChannel pts = *(this->m_pointBuffer->getFloatChannel(\"points\"));\n\n    cout << timestamp.getElapsedTime() << \"Initializing normal array...\" << endl;\n\n    floatArr normals = floatArr( new float[numPoints * 3] );\n    this->m_pointBuffer->setNormalArray(normals, numPoints);\n\n    // Create a progress counter\n    string comment = timestamp.getElapsedTime() + \"Estimating normals \";\n    lvr2::ProgressBar progress(numPoints, comment);\n\n    #pragma omp parallel for schedule(static)\n    for(size_t i = 0; i < numPoints; i++) {\n        // We have to fit these vector to have the\n        // correct return values when performing the\n        // search on the stann kd tree. So we don't use\n        // the template parameter T for di\n        vector<size_t> id;\n        vector<float> di;\n\n        int n = 0;\n        size_t k = k_0;\n\n        while(n < 5)\n        {\n            n++;\n            /**\n             *  @todo Maybe this should be done at the end of the loop\n             *        after the bounding box check\n             */\n            k = k * 2;\n\n            //T* point = this->m_points[i];\n\n            id.clear();\n            di.clear();\n\n            this->m_searchTree->kSearch(pts[i], k, id, di);\n\n            float min_x = 1e15f;\n            float min_y = 1e15f;\n            float min_z = 1e15f;\n            float max_x = - min_x;\n            float max_y = - min_y;\n            float max_z = - min_z;\n\n            float dx, dy, dz;\n            dx = dy = dz = 0;\n\n            // Calculate the bounding box of found point set\n            /**\n             * @todo Use the bounding box object from the old model3d\n             *       library for bounding box calculation...\n             */\n            for(size_t j = 0; j < k; j++) {\n                min_x = std::min(min_x, pts[id[j]][0]);\n                min_y = std::min(min_y, pts[id[j]][1]);\n                min_z = std::min(min_z, pts[id[j]][2]);\n\n                max_x = std::max(max_x, pts[id[j]][0]);\n                max_y = std::max(max_y, pts[id[j]][1]);\n                max_z = std::max(max_z, pts[id[j]][2]);\n\n                dx = max_x - min_x;\n                dy = max_y - min_y;\n                dz = max_z - min_z;\n            }\n\n            if(boundingBoxOK(dx, dy, dz))\n            {\n                break;\n            }\n        }\n\n        // Create a query point for the current point\n        auto queryPoint = pts[i];\n\n        // Interpolate a plane based on the k-neighborhood\n        Plane<BaseVecT> p;\n        bool ransac_ok;\n\n        if(m_calcMethod == 1)\n        {\n            p = calcPlaneRANSAC(queryPoint, k, id, ransac_ok);\n            // Fallback if RANSAC failed\n            if(!ransac_ok)\n            {\n                // compare speed\n                p = calcPlane(queryPoint, k, id);\n            }\n        }\n        else if(m_calcMethod == 2)\n        {\n            p = calcPlaneIterative(queryPoint, k, id);\n        }\n        else\n        {\n            p = calcPlane(queryPoint, k, id);\n        }\n        // Get the mean distance to the tangent plane\n        //mean_distance = meanDistance(p, id, k);\n        Normal<typename BaseVecT::CoordType> normal(0, 0, 1);\n        normal = p.normal;\n\n        // Flip normals towards the center of the scene or nearest scan pose\n        if(m_poseTree)\n        {\n            vector<size_t> nearestPoseIds;\n            m_poseTree->kSearch(queryPoint, 1, nearestPoseIds);\n            if(nearestPoseIds.size() == 1)\n            {\n                BaseVecT nearest = pts[nearestPoseIds[0]];\n                Normal<typename BaseVecT::CoordType> dir(queryPoint - nearest);\n                if(normal.dot(dir) > 0)\n                {\n                    normal = -normal;\n                }\n            }\n            else\n            {\n                cout << timestamp.getElapsedTime() << \"Could not get nearest scan pose. Defaulting to centroid.\" << endl;\n                Normal<typename BaseVecT::CoordType> dir(queryPoint - m_centroid);\n                if(normal.dot(dir) > 0)\n                {\n                    normal = -normal;\n                }\n            }\n        }\n        else\n        {\n            Normal<typename BaseVecT::CoordType> dir(queryPoint - m_centroid);\n            if(normal.dot(dir) > 0)\n            {\n                normal = -normal;\n            }\n        }\n\n        // Save result in normal array\n        normals[i*3 + 0] = normal.x;\n        normals[i*3 + 1] = normal.y;\n        normals[i*3 + 2] = normal.z;\n\n        ++progress;\n    }\n    cout << endl;\n\n    if(this->m_ki)\n    {\n        interpolateSurfaceNormals();\n    }\n}\n\n\ntemplate<typename BaseVecT>\nvoid AdaptiveKSearchSurface<BaseVecT>::interpolateSurfaceNormals()\n{\n    size_t numPoints     = this->m_pointBuffer->numPoints();\n    FloatChannel pts     = *(this->m_pointBuffer->getFloatChannel(\"points\"));\n    FloatChannel normals = *(this->m_pointBuffer->getFloatChannel(\"normals\"));\n    // Create a temporal normal array for the\n    vector<Normal<typename BaseVecT::CoordType>> tmp(\n        numPoints,\n        Normal<typename BaseVecT::CoordType>(0, 0, 1)\n    );\n\n    // Create progress output\n    string comment = timestamp.getElapsedTime() + \"Interpolating normals \";\n    lvr2::ProgressBar progress(numPoints, comment);\n\n    // Interpolate normals\n    #pragma omp parallel for schedule(static)\n    for( int i = 0; i < (int)numPoints; i++){\n\n        vector<size_t> id;\n        vector<float> di;\n\n        this->m_searchTree->kSearch(pts[i], this->m_ki, id, di);\n\n        BaseVecT mean;\n\n        for(int j = 0; j < this->m_ki; j++)\n        {\n            mean += normals[id[j]];\n        }\n        auto mean_normal = mean.normalized();\n\n        tmp[i] = mean_normal;\n\n        ///todo Try to remove this code. Should improve the results at all.\n        for(int j = 0; j < this->m_ki; j++)\n        {\n            Normal<typename BaseVecT::CoordType> n = normals[id[j]];\n\n            // Only override existing normals if the interpolated\n            // normals is significantly different from the initial\n            // estimation. This helps to avoid a too smooth normal\n            // field\n            if(fabs(n.dot(mean_normal)) > 0.2 )\n            {\n                normals[id[j]] = mean_normal;\n            }\n        }\n        ++progress;\n    }\n    cout << endl;\n    cout << timestamp.getElapsedTime() << \"Copying normals...\" << endl;\n\n    for(size_t i = 0; i < numPoints; i++){\n        normals[i] = tmp[i];\n    }\n}\n\ntemplate<typename BaseVecT>\nbool AdaptiveKSearchSurface<BaseVecT>::boundingBoxOK(float dx, float dy, float dz)\n{\n    /**\n     * @todo Replace magic number here.\n     */\n    float e = 0.05f;\n    if(dx < e * dy) return false;\n    else if(dx < e * dz) return false;\n    else if(dy < e * dx) return false;\n    else if(dy < e * dz) return false;\n    else if(dz < e * dx) return false;\n    else if(dz < e * dy) return false;\n    return true;\n}\n\n// template<typename BaseVecT>\n// void AdaptiveKSearchSurface<BaseVecT>::getkClosestVertices(const VertexT &v,\n//         const size_t &k, vector<VertexT> &nb)\n// {\n//     vector<int> id;\n\n//     //Allocate ANN point\n//     {\n//         coord<float> p;\n//         p[0] = v[0];\n//         p[1] = v[1];\n//         p[2] = v[2];\n\n//         //Find nearest tangent plane\n//         // m_pointTree.ksearch( p, k, id, 0 );\n//         this->m_searchTree->kSearch( p, k, id );\n//     }\n\n//     //parse result\n//     if ( this->m_colors )\n//     {\n//         for ( size_t i = 0; i < k; i++ )\n//         {\n//             VertexT tmp;\n//             nb.push_back( tmp );\n//             nb[i].x = this->m_points[id[i]][0];\n//             nb[i].y = this->m_points[id[i]][1];\n//             nb[i].z = this->m_points[id[i]][2];\n//     /*      nb[i].r = this->m_colors[id[i]][0];\n//             nb[i].g = this->m_colors[id[i]][1];\n//             nb[i].b = this->m_colors[id[i]][2]; */\n//         }\n//     }\n//     else\n//     {\n//         for ( size_t i = 0; i < k; i++ )\n//         {\n//             VertexT tmp( this->m_points[id[i]][0], this->m_points[id[i]][1],\n//                     this->m_points[id[i]][2] );\n//             nb.push_back( tmp );\n//         }\n//     }\n// }\n\n// template<typename BaseVecT>\n// float AdaptiveKSearchSurface<BaseVecT>::meanDistance(const Plane<BaseVecT> &p,\n//         const vector<unsigned long> &id, const int &k)\n// {\n//     float sum = 0;\n//     for(int i = 0; i < k; i++){\n//         sum += distance(fromID(id[i]), p);\n//     }\n//     sum = sum / k;\n//     return sum;\n// }\n\n// template<typename BaseVecT>\n// float AdaptiveKSearchSurface<BaseVecT>::distance(VertexT v, Plane<BaseVecT> p)\n// {\n//     return fabs((v - p.p) * p.n);\n// }\n\ntemplate<typename BaseVecT>\npair<typename BaseVecT::CoordType, typename BaseVecT::CoordType>\n    AdaptiveKSearchSurface<BaseVecT>::distance(BaseVecT p) const\n{\n\n    FloatChannel pts     = *(this->m_pointBuffer->getFloatChannel(\"points\"));\n    FloatChannel normals = *(this->m_pointBuffer->getFloatChannel(\"normals\"));\n    size_t numPoints     = pts.numElements();\n    int k = this->m_kd;\n\n    vector<size_t> id;\n    vector<float> di;\n\n    //Allocate ANN point\n    {\n        // Find nearest tangent plane\n        this->m_searchTree->kSearch( p, k, id, di );\n    }\n\n    BaseVecT nearest;\n    BaseVecT avg_normal;\n\n    for ( int i = 0; i < k; i++ )\n    {\n        //Get nearest tangent plane\n        auto vq = pts[id[i]];\n\n        //Get normal\n        auto n = normals[id[i]];\n\n        nearest += vq;\n        avg_normal += n;\n    }\n\n    avg_normal /= k;\n    nearest /= k;\n    auto normal = avg_normal.normalized();\n\n    //Calculate distance\n    auto projectedDistance = (p - BaseVecT(nearest)).dot(normal);\n    auto euklideanDistance = (p - BaseVecT(nearest)).length();\n\n    return std::make_pair(projectedDistance, euklideanDistance);\n    // return make_pair(euklideanDistance, projectedDistance);\n}\n\n// template<typename BaseVecT>\n// VertexT AdaptiveKSearchSurface<BaseVecT>::fromID(int i){\n//     return VertexT(\n//             this->m_points[i][0],\n//             this->m_points[i][1],\n//             this->m_points[i][2]);\n// }\n\ntemplate<typename BaseVecT>\nPlane<BaseVecT> AdaptiveKSearchSurface<BaseVecT>::calcPlane(\n    const BaseVecT &queryPoint,\n    int k,\n    const vector<size_t> &id\n)\n{\n    FloatChannel pts     = *(this->m_pointBuffer->getFloatChannel(\"points\"));\n    size_t numPoints     = pts.numElements();\n\n    /**\n     * @todo Think of a better way to code this magic number.\n     */\n    const float epsilon = 100.0;\n\n    // Calculate a least sqaures fit to the given points\n    Eigen::Vector3f C;\n    Eigen::VectorXf F(k);\n    Eigen::MatrixXf B(k, 3);\n\n    for(int j = 0; j < k; j++) {\n        BaseVecT p = pts[id[j]];\n        F(j)    = p.y;\n        B(j, 0) = 1.0f;\n        B(j, 1) = p.x;\n        B(j, 2) = p.z;\n    }\n\n    C = B.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(F);\n\n    // Calculate to vectors in the fitted plane\n    auto z1 = C(0) + C(1) * (queryPoint.x + epsilon) + C(2) * queryPoint.z;\n    auto z2 = C(0) + C(1) * queryPoint.x + C(2) * (queryPoint.z + epsilon);\n\n    // Calculcate the plane's normal via the cross product\n    auto diff1 = BaseVecT(queryPoint.x + epsilon, z1, queryPoint.z) - queryPoint;\n    auto diff2 = BaseVecT(queryPoint.x, z2, queryPoint.z + epsilon) - queryPoint;\n\n    auto normal = diff1.cross(diff2).normalized();\n\n    if(isnan(normal.getX()) || isnan(normal.getY()) || isnan(normal.getZ()))\n    {\n        cout << \"Warning: Nan-coordinate in plane normal.\" << endl;\n    }\n\n    // Create a plane representation and return the result\n    Plane<BaseVecT> p;\n    // p.a = C(0);\n    // p.b = C(1);\n    // p.c = C(2);\n    p.normal = normal;\n    p.pos = queryPoint;\n\n    return p;\n}\n\ntemplate<typename BaseVecT>\nPlane<BaseVecT> AdaptiveKSearchSurface<BaseVecT>::calcPlaneIterative(\n    const BaseVecT &queryPoint,\n    int k,\n    const vector<size_t> &id\n)\n{\n\n    FloatChannel pts     = *(this->m_pointBuffer->getFloatChannel(\"points\"));\n    FloatChannel normals = *(this->m_pointBuffer->getFloatChannel(\"normals\"));\n    size_t numPoints     = pts.numElements();\n\n    Plane<BaseVecT> p;\n    BaseVecT normal;\n\n\n    //x\n    float xx = 0.0;\n    float xy = 0.0;\n    float xz = 0.0;\n\n    //y\n    float yy = 0.0;\n    float yz = 0.0;\n\n    //z\n    float zz = 0.0;\n\n    for(int j = 0; j < k; j++) {\n        auto p = pts[id[j]];\n\n        auto r = p - queryPoint;\n\n        xx += r.x * r.x;\n        xy += r.x * r.y;\n        xz += r.x * r.z;\n        yy += r.y * r.y;\n        yz += r.y * r.z;\n        zz += r.z * r.z;\n\n    }\n\n    //determinante\n    float det_x = yy * zz - yz * yz;\n    float det_y = xx * zz - xz * xz;\n    float det_z = xx * yy - xy * xy;\n\n    float dir_x;\n    float dir_y;\n    float dir_z;\n    // det X biggest\n    if( det_x >= det_y && det_x >= det_z){\n\n        if(det_x <= 0.0){\n            //not a plane\n        }\n\n        dir_x = 1.0;\n        dir_y = (xz * yz - xy * zz) / det_x;\n        dir_z = (xy * yz - xz * yy) / det_x;\n    } //det Y biggest\n    else if( det_y >= det_x && det_y >= det_z){\n\n        if(det_y <= 0.0){\n            // not a plane\n        }\n\n        dir_x = (yz * xz - xy * zz) / det_y;\n        dir_y = 1.0;\n        dir_z = (xy * xz - yz * xx) / det_y;\n    } // det Z biggest\n    else{\n        if(det_z <= 0.0){\n            // not a plane\n        }\n\n        dir_x = (yz * xy - xz * yy ) / det_z;\n        dir_y = (xz * xy - yz * xx ) / det_z;\n        dir_z = 1.0;\n    }\n\n    float invnorm = 1/sqrtf( dir_x * dir_x + dir_y * dir_y + dir_z * dir_z );\n\n    normal.x = dir_x * invnorm;\n    normal.y = dir_y * invnorm;\n    normal.z = dir_z * invnorm;\n\n\n    p.normal = normal;\n    p.pos = queryPoint;\n\n    return p;\n}\n\n// template<typename BaseVecT>\n// const VertexT AdaptiveKSearchSurface<BaseVecT>::operator[]( const size_t& index ) const\n// {\n//     return VertexT(\n//             m_points[index].x, m_points[index].y, m_points[index].z,\n//             m_colors[index].r, m_colors[index].g, m_colors[index].b );\n// }\n\n//    template<typename BaseVecT>\n// size_t AdaptiveKSearchSurface<BaseVecT>::getNumPoints()\n// {\n//     return m_numPoints;\n// }\n\ntemplate<typename BaseVecT>\nPlane<BaseVecT> AdaptiveKSearchSurface<BaseVecT>::calcPlaneRANSAC(\n    const BaseVecT &queryPoint,\n    int k,\n    const vector<size_t> &id,\n    bool &ok\n)\n{\n    FloatChannel pts     = *(this->m_pointBuffer->getFloatChannel(\"points\"));\n    FloatChannel normals = *(this->m_pointBuffer->getFloatChannel(\"normals\"));\n    size_t numPoints     = pts.numElements();\n\n   Plane<BaseVecT> p;\n\n   //representation of best regression plane by point and normal\n   BaseVecT bestPoint;\n   Normal<typename BaseVecT::CoordType> bestNorm(0, 0, 1);\n\n   float bestdist = numeric_limits<float>::max();\n   float dist     = 0;\n\n   int iterations              = 0;\n   int nonimproving_iterations = 0;\n\n   //  int max_nonimproving = max(5, k / 2);\n   int max_interations  = 10;\n\n   while((nonimproving_iterations < 5) && (iterations < max_interations))\n   {\n       // randomly choose 3 disjoint points\n       int c = 0;\n\n       std::set<unsigned long> ids;\n       std::default_random_engine generator;\n       std::uniform_int_distribution<unsigned long> distribution(0, id.size() - 1);\n       auto number = std::bind(distribution, generator);\n       do\n       {\n           ids.insert(number());\n           c++;\n           if (c == 20) cout << \"Deadlock\" << endl;\n       }\n       while (ids.size() < 3 && c <= 20);\n\n       vector<unsigned long> sample_ids(ids.size());\n       std::copy(ids.begin(), ids.end(), sample_ids.begin());\n\n       BaseVecT point1 = pts[sample_ids[0]];\n       BaseVecT point2 = pts[sample_ids[1]];\n       BaseVecT point3 = pts[sample_ids[2]];\n\n       auto n0 = (point1 - point2).cross(point1 - point3).normalized();\n\n       //compute error to at most 50 other randomly chosen points\n       dist = 0;\n       int n = std::min(50, k);\n       for(int i = 0; i < n; i++)\n       {\n           int index = id[rand() % k];\n           BaseVecT refpoint = pts[index];\n           dist += fabs(refpoint.dot(n0) - point1.dot(n0));\n       }\n       if(n != 0) dist /= n;\n\n       //a new optimum is found\n       if(dist < bestdist)\n       {\n           bestdist = dist;\n\n           bestPoint = point1;\n           bestNorm = n0;\n\n           nonimproving_iterations = 0;\n       }\n       else\n       {\n           nonimproving_iterations++;\n       }\n\n       iterations++;\n   }\n\n   // Save plane parameters\n   // p.a = 0;\n   // p.b = 0;\n   // p.c = 0;\n   p.normal = bestNorm;\n   p.pos = bestPoint;\n\n\n   return p;\n}\n\n\n// template<typename BaseVecT>\n// Plane<BaseVecT> AdaptiveKSearchSurface<BaseVecT>::calcPlaneRANSACfromPoints(const VertexT &queryPoint,\n//         const int &k,\n//         const vector<VertexT> points,\n//         Normal<typename BaseVecT::CoordType> c_normal,\n//         bool &ok)\n// {\n//     // the resulting plane\n//     Plane<BaseVecT> p;\n\n//     VertexT point1;\n//     VertexT point2;\n//     VertexT point3;\n\n//     //representation of best regression plane by point and normal\n//     VertexT bestpoint;\n//     Normal<typename BaseVecT::CoordType> bestNorm;\n\n//     float bestdist = numeric_limits<float>::max();\n//     float dist     = 0;\n\n//     int iterations              = 0;\n//     int nonimproving_iterations = 0;\n\n//     int max_interations = max(10, k / 2);\n//     //int max_interations  = 10;\n\n//     bool first_it = true;\n//     while((nonimproving_iterations < 5) && (iterations < max_interations))\n//     {\n//         Normal<typename BaseVecT::CoordType> n0;\n//         //randomly choose 3 disjoint points\n//         int c = 0;\n//         do{\n//             int index[3];\n//             for(int i = 0; i < 3; i++)\n//             {\n//                 float f = 1.0 * rand() / RAND_MAX;\n//                 int r = (int)(f * points.size() - 1);\n//                 index[i] = r;\n//             }\n\n//             point1 = VertexT(this->m_points[index[0]][0],this->m_points[index[0]][1], this->m_points[index[0]][2]);\n//             point2 = VertexT(this->m_points[index[1]][0],this->m_points[index[1]][1], this->m_points[index[1]][2]);\n//             point3 = VertexT(this->m_points[index[2]][0],this->m_points[index[2]][1], this->m_points[index[2]][2]);\n\n//             //compute normal of the plane given by the 3 points (look at the end)\n//             n0 = (point1 - point2).cross(point1 - point3);\n//             n0.normalize();\n//             c++;\n\n//             // check if the three points are disjoint\n//             if( (point1 != point2) && (point2 != point3) && (point3 != point1) )\n//             {\n//                 // at first, use interpolated normal\n//                 Normal<typename BaseVecT::CoordType> check(0.0, 0.0, 0.0);\n//                 if(first_it && !(check == c_normal))\n//                 {\n//                     n0 = c_normal;\n//                     n0.normalize();\n//                     first_it = false;\n//                 }\n//                 break;\n//             }\n//             // Check for deadlock\n//             if(c > 50)\n//             {\n//                 cout << \"DL \" << k << endl;\n//                 ok = false;\n//                 return p;\n//             }\n//         }\n//         while(true);\n\n//         //compute error to at most 10 other randomly chosen points\n//         dist = 0;\n//         int n = min(10,k);\n//         for(int i = 0; i < n; i++)\n//         {\n//             int index = rand() % points.size();\n//             VertexT refpoint = VertexT(points[index][0], points[index][1] ,points[index][2]);\n//             dist += fabs(refpoint * n0 - point1 * n0);\n//         }\n//         if(n != 0) dist /= n;\n\n//         //a new optimum is found\n//         if(dist < bestdist)\n//         {\n//             bestdist = dist;\n//             bestpoint = point1;\n//             bestNorm = n0;\n\n//             nonimproving_iterations = 0;\n//         }\n//         else\n//         {\n//             nonimproving_iterations++;\n//         }\n\n//         iterations++;\n//     } // end while\n\n//     // Save plane parameters\n//     p.a = 0;\n//     p.b = 0;\n//     p.c = 0;\n//     p.n = bestNorm;\n//     p.p = bestpoint;\n\n//     return p;\n// }\n\n// template<typename BaseVecT>\n// void AdaptiveKSearchSurface<BaseVecT>::colorizePointCloud(\n//       typename AdaptiveKSearchSurface<BaseVecT>::Ptr pcm, const float& sqrtMaxDist,\n//       const unsigned char* blankColor)\n// {\n// //    if( !m_colors )\n// //    {\n// //        m_colors = color3bArr( new color<uchar>[ m_numPoints ] );\n// //    }\n// //\n// //#pragma omp parallel for schedule(dynamic)\n// //    for( size_t i = 0; i < m_numPoints; i++ )\n// //    {\n// //        std::vector< VertexT > nearestPoint( 1 );\n// //\n// //        VertexT p( this->getPoint( i ) );\n// //        pcm->getkClosestVertices( p, 1, nearestPoint );\n// //        if(nearestPoint.size() )\n// //        {\n// //            if( p.sqrDistance( nearestPoint[0] ) < sqrtMaxDist )\n// //            {\n// //                m_colors[i][0] = nearestPoint[0].r;\n// //                m_colors[i][1] = nearestPoint[0].g;\n// //                m_colors[i][2] = nearestPoint[0].b;\n// //            }\n// //            else if( blankColor )\n// //            {\n// //                m_colors[i][0] = blankColor[0];\n// //                m_colors[i][1] = blankColor[1];\n// //                m_colors[i][2] = blankColor[2];\n// //            }\n// //        }\n// //    }\n// }\n\n\n\n\n} // namespace lvr2\n", "meta": {"hexsha": "2f94c42d84d5a83ea318c5890b5146122ab305db", "size": 26503, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "include/lvr2/reconstruction/AdaptiveKSearchSurface.tcc", "max_stars_repo_name": "jtpils/lvr2", "max_stars_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-07T03:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-07T03:55:27.000Z", "max_issues_repo_path": "include/lvr2/reconstruction/AdaptiveKSearchSurface.tcc", "max_issues_repo_name": "jtpils/lvr2", "max_issues_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/lvr2/reconstruction/AdaptiveKSearchSurface.tcc", "max_forks_repo_name": "jtpils/lvr2", "max_forks_repo_head_hexsha": "b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce", "max_forks_repo_licenses": ["BSD-3-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.7451193059, "max_line_length": 121, "alphanum_fraction": 0.5408444327, "num_tokens": 7064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.020964240932818432, "lm_q1q2_score": 0.006513471906183328}}
{"text": "/*\n * BSD 2-Clause License\n *\n * Copyright (c) 2021, Christoph Neuhauser\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 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <boost/algorithm/string/case_conv.hpp>\n\n#include <Utils/File/Logfile.hpp>\n#include <Utils/File/FileLoader.hpp>\n#include <Utils/StringUtils.hpp>\n#include <Utils/Convert.hpp>\n\n#include \"../StreamlineTracingDefines.hpp\"\n#include \"../StreamlineTracingGrid.hpp\"\n#include \"GridLoader.hpp\"\n#include \"StructuredGridVtkLoader.hpp\"\n\nvoid StructuredGridVtkLoader::_readLines(\n        ReadMode readMode, int numObjects, float* fieldData,\n        size_t& charPtr, size_t& length, const char* fileBuffer) {\n    int lineNum = 0;\n    std::string lineBuffer;\n    std::vector<std::string> splitLineString;\n    while (charPtr < length && lineNum < numObjects) {\n        lineBuffer.clear();\n        while (charPtr < length) {\n            char currentChar = fileBuffer[charPtr];\n            if (currentChar == '\\n' || currentChar == '\\r') {\n                charPtr++;\n                break;\n            }\n            lineBuffer.push_back(currentChar);\n            charPtr++;\n        }\n\n        if (lineBuffer.empty()) {\n            sgl::Logfile::get()->throwError(\n                    \"Error in RbcBinFileLoader::_readLines: Encountered an empty line.\");\n        }\n\n        if (readMode == ReadMode::SCALAR) {\n            fieldData[lineNum] = sgl::fromString<float>(lineBuffer);\n        } else if (readMode == ReadMode::VECTOR) {\n            splitLineString.clear();\n            sgl::splitStringWhitespace(lineBuffer, splitLineString);\n            if (splitLineString.size() != 3) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::_readLines: Vector mode, but line contains less than three \"\n                        \"items.\");\n            }\n            fieldData[lineNum * 3] = sgl::fromString<float>(splitLineString.at(0));\n            fieldData[lineNum * 3 + 1] = sgl::fromString<float>(splitLineString.at(1));\n            fieldData[lineNum * 3 + 2] = sgl::fromString<float>(splitLineString.at(2));\n        }\n\n        lineNum++;\n    }\n\n    if (lineNum < numObjects) {\n        sgl::Logfile::get()->throwError(\n                \"Error in RbcBinFileLoader::_readLines: The file has ended before all values could be read.\");\n    }\n}\n\nvoid StructuredGridVtkLoader::_convertScalarFieldCellToPointMode(\n        const float* scalarFieldCell, float* scalarFieldPoint, int xs, int ys, int zs) {\n    #pragma omp parallel for shared(xs, ys, zs, scalarFieldCell, scalarFieldPoint)  default(none)\n    for (int z = 0; z < zs; z++) {\n        for (int y = 0; y < ys; y++) {\n            for (int x = 0; x < xs; x++) {\n                int numNeighboringCells = 0;\n                float valueSum = 0.0f;\n                for (int zc = z - 1; zc <= z; zc++) {\n                    for (int yc = y - 1; yc <= y; yc++) {\n                        for (int xc = x - 1; xc <= x; xc++) {\n                            if (xc >= 0 && yc >= 0 && zc >= 0 && xc < xs - 1 && yc < ys - 1 && zc < zs - 1) {\n                                numNeighboringCells++;\n                                valueSum += scalarFieldCell[IDXS_C(xc, yc, zc)];\n                            }\n                        }\n                    }\n                }\n                scalarFieldPoint[IDXS(x, y, z)] = valueSum / float(numNeighboringCells);\n            }\n        }\n    }\n}\n\nvoid StructuredGridVtkLoader::load(const std::string& dataSourceFilename, StreamlineTracingGrid* grid) {\n    int xs = 0, ys = 0, zs = 0;\n\n    uint8_t* buffer = nullptr;\n    size_t length = 0;\n    bool loaded = sgl::loadFileFromSource(dataSourceFilename, buffer, length, false);\n    if (!loaded) {\n        sgl::Logfile::get()->throwError(\n                \"Error in RbcBinFileLoader::load: Couldn't open file \\\"\" + dataSourceFilename + \"\\\".\");\n    }\n    char* fileBuffer = reinterpret_cast<char*>(buffer);\n\n    std::string lineBuffer;\n    std::string stringBuffer;\n    std::vector<std::string> splitLineString;\n    bool isBinaryMode = false;\n    bool pointDataMode = true; //< Point data or cell data.\n    std::string scalarFieldName;\n    bool ignoreNextScalarData = false; //< For ignoring everything that is not of type float.\n    int nextScalarDataBytesPerElement = 4; //< For ignoring everything that is not of type float.\n    int numPoints = 0;\n    int numCells = 0;\n\n    glm::vec3* gridPoints = nullptr;\n    float* points = nullptr;\n    std::map<std::string, float*> vectorFields;\n    std::map<std::string, float*> scalarFields;\n\n    for (size_t charPtr = 0; charPtr < length; ) {\n        lineBuffer.clear();\n        while (charPtr < length) {\n            char currentChar = fileBuffer[charPtr];\n            if (currentChar == '\\n' || currentChar == '\\r') {\n                charPtr++;\n                break;\n            }\n            lineBuffer.push_back(currentChar);\n            charPtr++;\n        }\n\n        if (lineBuffer.empty()) {\n            continue;\n        }\n\n        splitLineString.clear();\n        sgl::splitStringWhitespace(lineBuffer, splitLineString);\n        if (splitLineString.empty()) {\n            continue;\n        }\n\n        if (splitLineString.front() == \"BINARY\") {\n            isBinaryMode = true;\n        } else if (splitLineString.front() == \"ASCII\") {\n            isBinaryMode = false;\n        } else if (splitLineString.front() == \"DATASET\") {\n            if (splitLineString.size() != 2 || splitLineString.at(1) != \"STRUCTURED_GRID\") {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid DATASET mode in file \\\"\"\n                        + dataSourceFilename + \"\\\".\");\n            }\n        } else if (splitLineString.front() == \"DIMENSIONS\") {\n            if (splitLineString.size() != 4) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid DIMENSIONS string in file \\\"\"\n                        + dataSourceFilename + \"\\\".\");\n            }\n            xs = sgl::fromString<int>(splitLineString.at(1));\n            ys = sgl::fromString<int>(splitLineString.at(2));\n            zs = sgl::fromString<int>(splitLineString.at(3));\n            numPoints = xs * ys * zs;\n            numCells = (xs - 1) * (ys - 1) * (zs - 1);\n        } else if (splitLineString.front() == \"POINTS\") {\n            if (splitLineString.size() != 3) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid POINTS string in file \\\"\"\n                        + dataSourceFilename + \"\\\".\");\n            }\n            if (splitLineString.at(2) != \"float\") {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid POINTS string in file \\\"\"\n                        + dataSourceFilename + \"\\\". The loader only supports float data.\");\n            }\n            int numPointsLocal = sgl::fromString<int>(splitLineString.at(1));\n            if (numPointsLocal != numPoints) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid POINTS string in file \\\"\"\n                        + dataSourceFilename + \"\\\". The number of points does not match the dimensions.\");\n            }\n            if (gridPoints) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: The file \\\"\"\n                        + dataSourceFilename + \"\\\" contains more than one POINTS statement.\");\n            }\n\n            gridPoints = new glm::vec3[numPoints];\n            points = reinterpret_cast<float*>(gridPoints);\n            if (isBinaryMode) {\n                size_t numBytes = sizeof(float) * numPoints * 3;\n                if (charPtr + numBytes > length) {\n                    sgl::Logfile::get()->throwError(\n                            \"Error in RbcBinFileLoader::load: The file \\\"\" + dataSourceFilename\n                            + \"\\\" ended before all data from a POINTS statement could be read.\");\n                }\n                memcpy(points, fileBuffer + charPtr, sizeof(float) * numPoints * 3);\n                swapEndianness(points, numPoints * 3);\n                charPtr += sizeof(float) * numPoints * 3;\n            } else {\n                _readLines(ReadMode::VECTOR, numPoints, points, charPtr, length, fileBuffer);\n            }\n        } else if (splitLineString.front() == \"POINT_DATA\") {\n            if (splitLineString.size() != 2) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid POINT_DATA string in file \\\"\"\n                        + dataSourceFilename + \"\\\".\");\n            }\n            int numPointsLocal = sgl::fromString<int>(splitLineString.at(1));\n            if (numPointsLocal != numPoints) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid POINT_DATA string in file \\\"\"\n                        + dataSourceFilename + \"\\\". The number of points does not match the dimensions.\");\n            }\n\n            pointDataMode = true;\n        } else if (splitLineString.front() == \"CELL_DATA\") {\n            if (splitLineString.size() != 2) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid CELL_DATA string in file \\\"\"\n                        + dataSourceFilename + \"\\\".\");\n            }\n            int numCellsLocal = sgl::fromString<int>(splitLineString.at(1));\n            if (numCellsLocal != numCells) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid CELL_DATA string in file \\\"\"\n                        + dataSourceFilename + \"\\\". The number of points does not match the dimensions.\");\n            }\n\n            pointDataMode = false;\n        } else if (splitLineString.front() == \"VECTORS\") {\n            if (splitLineString.size() != 3) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid VECTORS string in file \\\"\"\n                        + dataSourceFilename + \"\\\".\");\n            }\n            if (splitLineString.at(2) != \"float\") {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid VECTORS string in file \\\"\"\n                        + dataSourceFilename + \"\\\". The loader only supports float data.\");\n            }\n\n            std::string vectorFieldName = splitLineString.at(1);\n\n            int numVectors = pointDataMode ? numPoints : numCells;\n            auto* vectorField = new float[numVectors * 3];\n            if (isBinaryMode) {\n                size_t numBytes = sizeof(float) * numVectors * 3;\n                if (charPtr + numBytes > length) {\n                    sgl::Logfile::get()->throwError(\n                            \"Error in RbcBinFileLoader::load: The file \\\"\" + dataSourceFilename\n                            + \"\\\" ended before all data from a POINTS statement could be read.\");\n                }\n                memcpy(vectorField, fileBuffer + charPtr, sizeof(float) * numVectors * 3);\n                swapEndianness(vectorField, numVectors * 3);\n                charPtr += sizeof(float) * numVectors * 3;\n            } else {\n                _readLines(\n                        ReadMode::VECTOR, numVectors, vectorField,\n                        charPtr, length, fileBuffer);\n            }\n\n            if (vectorFields.find(vectorFieldName) != vectorFields.end()) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: The vector field \\\"\" + vectorFieldName\n                        + \"\\\" exists more than one time in the file \\\"\" + dataSourceFilename + \"\\\".\");\n            }\n\n            if (pointDataMode) {\n                vectorFields.insert(std::make_pair(vectorFieldName, vectorField));\n            } else {\n                // Ignoring cell data for now.\n                delete[] vectorField;\n            }\n        } else if (splitLineString.front() == \"SCALARS\") {\n            if (splitLineString.size() != 4) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid SCALARS string in file \\\"\"\n                        + dataSourceFilename + \"\\\".\");\n            }\n            if (splitLineString.at(2) != \"float\" && splitLineString.at(2) != \"unsigned_char\") {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid SCALARS string in file \\\"\" + dataSourceFilename +\n                        \"\\\". The loader only supports float data. Additionally, unsigned_char data can be ignored.\");\n            }\n            if (splitLineString.at(3) != \"1\") {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Invalid SCALARS string in file \\\"\"\n                        + dataSourceFilename + \"\\\". The loader only supports scalars with one value.\");\n            }\n            if (!scalarFieldName.empty()) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Encountered another SCALARS string in file \\\"\"\n                        + dataSourceFilename + \"\\\" even though no LOOKUP_TABLE statement was given.\");\n            }\n\n            scalarFieldName = splitLineString.at(1);\n            ignoreNextScalarData = splitLineString.at(2) != \"float\";\n            if (splitLineString.at(2) == \"float\") {\n                nextScalarDataBytesPerElement = 4;\n            } else if (splitLineString.at(2) == \"unsigned_char\") {\n                nextScalarDataBytesPerElement = 1;\n            }\n        } else if (splitLineString.front() == \"LOOKUP_TABLE\") {\n            if (scalarFieldName.empty()) {\n                sgl::Logfile::get()->throwError(\n                        \"Error in RbcBinFileLoader::load: Encountered a LOOKUP_TABLE string in file \\\"\"\n                        + dataSourceFilename + \"\\\" before a SCALARS string.\");\n            }\n\n            int numScalars = pointDataMode ? numPoints : numCells;\n\n            if (!ignoreNextScalarData) {\n                auto* scalarField = new float[numScalars];\n                if (isBinaryMode) {\n                    size_t numBytes = sizeof(float) * numScalars;\n                    if (charPtr + numBytes > length) {\n                        sgl::Logfile::get()->throwError(\n                                \"Error in RbcBinFileLoader::load: The file \\\"\" + dataSourceFilename\n                                + \"\\\" ended before all data from a SCALARS statement could be read.\");\n                    }\n                    memcpy(scalarField, fileBuffer + charPtr, sizeof(float) * numScalars);\n                    swapEndianness(scalarField, numScalars);\n                    charPtr += sizeof(float) * numScalars;\n                } else {\n                    _readLines(\n                            ReadMode::SCALAR, numScalars, scalarField,\n                            charPtr, length, fileBuffer);\n                }\n\n                if (scalarFields.find(scalarFieldName) != scalarFields.end()) {\n                    sgl::Logfile::get()->throwError(\n                            \"Error in RbcBinFileLoader::load: The scalar field \\\"\" + scalarFieldName\n                            + \"\\\" exists more than one time in the file \\\"\" + dataSourceFilename + \"\\\".\");\n                }\n                if (pointDataMode) {\n                    scalarFields.insert(std::make_pair(scalarFieldName, scalarField));\n                } else {\n                    // Convert cell data to point data.\n                    auto* scalarFieldPoint = new float[numPoints];\n                    _convertScalarFieldCellToPointMode(scalarField, scalarFieldPoint, xs, ys, zs);\n                    scalarFields.insert(std::make_pair(scalarFieldName, scalarFieldPoint));\n                    delete[] scalarField;\n                }\n            } else {\n                if (isBinaryMode) {\n                    size_t numBytes = nextScalarDataBytesPerElement * numScalars;\n                    if (charPtr + numBytes > length) {\n                        sgl::Logfile::get()->throwError(\n                                \"Error in RbcBinFileLoader::load: The file \\\"\" + dataSourceFilename\n                                + \"\\\" ended before all data from a SCALARS statement could be read.\");\n                    }\n                    charPtr += sizeof(float) * numScalars;\n                } else {\n                    _readLines(\n                            ReadMode::SKIP, numScalars, nullptr,\n                            charPtr, length, fileBuffer);\n                }\n            }\n            scalarFieldName.clear();\n        }\n    }\n\n    if (!gridPoints) {\n        sgl::Logfile::get()->throwError(\n                \"Error in RbcBinFileLoader::load: The file \\\"\" + dataSourceFilename\n                + \"\\\" does not contain a POINTS statement.\");\n    }\n\n    /*sgl::AABB3 domainExtents;\n    for (int i = 0; i < numPoints; i++) {\n        domainExtents.combine(gridPoints[i]);\n    }\n\n    glm::vec3 dimensions = domainExtents.getDimensions();\n    float maxDimension = std::max(dimensions.x, std::max(dimensions.y, dimensions.z));\n    float cellStep = 1.0f / maxDimension;*/\n\n    float maxDimension = float(std::max(xs - 1, std::max(ys - 1, zs - 1)));\n    float cellStep = 1.0f / maxDimension;\n\n    auto itVelocity = vectorFields.find(\"velocity\");\n    if (itVelocity == vectorFields.end()) {\n        sgl::Logfile::get()->throwError(\n                \"Error in RbcBinFileLoader::load: The file \\\"\" + dataSourceFilename\n                + \"\\\" does not contain a vector field called 'velocity'.\");\n    }\n    float* velocityField = itVelocity->second;\n\n    grid->setGridMetadata(xs, ys, zs, cellStep, cellStep, cellStep);\n\n    if (scalarFields.find(\"velocityMagnitude\") == scalarFields.end()) {\n        auto* velocityMagnitudeField = new float[numPoints];\n        computeVectorMagnitudeField(velocityField, velocityMagnitudeField, xs, ys, zs);\n        scalarFields.insert(std::make_pair(\"Velocity Magnitude\", velocityMagnitudeField));\n    }\n\n    if (vectorFields.find(\"vorticity\") == vectorFields.end()\n            || scalarFields.find(\"vorticityMagnitude\") == scalarFields.end()\n            || scalarFields.find(\"helicity\") == scalarFields.end()) {\n        float* vorticityField;\n        auto it = vectorFields.find(\"vorticity\");\n        if (it == vectorFields.end()) {\n            vorticityField = new float[numPoints * 3];\n            computeVorticityField(velocityField, vorticityField, xs, ys, zs, cellStep, cellStep, cellStep);\n            vectorFields.insert(std::make_pair(\"Vorticity\", vorticityField));\n        } else {\n            vorticityField = it->second;\n        }\n        if (scalarFields.find(\"vorticityMagnitude\") == scalarFields.end()) {\n            auto* vorticityMagnitudeField = new float[numPoints];\n            computeVectorMagnitudeField(vorticityField, vorticityMagnitudeField, xs, ys, zs);\n            scalarFields.insert(std::make_pair(\"Vorticity Magnitude\", vorticityMagnitudeField));\n        }\n        if (scalarFields.find(\"helicity\") == scalarFields.end()) {\n            auto* helicityField = new float[numPoints];\n            computeHelicityField(velocityField, vorticityField, helicityField, xs, ys, zs);\n            scalarFields.insert(std::make_pair(\"Helicity\", helicityField));\n        }\n    }\n\n    for (auto& it : vectorFields) {\n        // Convert first letter to upper case.\n        std::string vectorDisplayName;\n        vectorDisplayName = boost::to_upper_copy(it.first.substr(0, 1)) + it.first.substr(1);\n        grid->addVectorField(it.second, vectorDisplayName);\n    }\n\n    for (auto& it : scalarFields) {\n        // Convert first letter to upper case.\n        std::string scalarDisplayName;\n        scalarDisplayName = boost::to_upper_copy(it.first.substr(0, 1)) + it.first.substr(1);\n        std::string::size_type magnitudePos = scalarDisplayName.find(\"Magnitude\");\n        if (scalarDisplayName.find(\" Magnitude\") == std::string::npos\n                && magnitudePos != std::string::npos && magnitudePos > 0) {\n            scalarDisplayName =\n                    scalarDisplayName.substr(0, magnitudePos) + \" \" + scalarDisplayName.substr(magnitudePos);\n        }\n        grid->addScalarField(it.second, scalarDisplayName);\n    }\n\n    delete[] gridPoints;\n    delete[] buffer;\n    buffer = nullptr;\n}\n", "meta": {"hexsha": "b8d92b91133b06d8051980e9e4436146a05f3d82", "size": 21800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LineData/Flow/Loader/StructuredGridVtkLoader.cpp", "max_stars_repo_name": "chrismile/StressLineVis", "max_stars_repo_head_hexsha": "bb81322496cf5447c19699de9185a5c86666110c", "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/LineData/Flow/Loader/StructuredGridVtkLoader.cpp", "max_issues_repo_name": "chrismile/StressLineVis", "max_issues_repo_head_hexsha": "bb81322496cf5447c19699de9185a5c86666110c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LineData/Flow/Loader/StructuredGridVtkLoader.cpp", "max_forks_repo_name": "chrismile/StressLineVis", "max_forks_repo_head_hexsha": "bb81322496cf5447c19699de9185a5c86666110c", "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.9827586207, "max_line_length": 117, "alphanum_fraction": 0.5530275229, "num_tokens": 4852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776780354463427, "lm_q2_score": 0.022629202298836342, "lm_q1q2_score": 0.006511955841503323}}
{"text": "//\n// Created by Markus on 19.01.17.\n//\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <boost/variant.hpp>\n#include <map>\n\n#include \"LCFRS.h\"\n#include \"LCFRS_Parser.h\"\n#include \"LCFRS_util.h\"\n#include \"../Names.h\"\n\nusing namespace std;\nnamespace LCFR {\n\n    void manual_parse(const LCFRS<string, string> &grammar, const vector<string> &word);\n\n\n    int main() {\n        LCFRS<string, string> grammar(\"S\", \"Test\");\n\n//    grammar.add_rule(construct_rule(\"S\", vector<string>{\"a a x{0,0}\"}, \"S\"));\n//    grammar.add_rule(construct_rule(\"S\", vector<string>{\"a\"}, \"\"));\n//    vector<string> word{\"a\", \"a\", \"a\", \"a\"};\n//    manual_parse(grammar, word);\n\n//    grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0} x{0,1}\"}, \"A\"));\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"A\"));\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\", \"b\"}, \"A\"));\n//    vector<string> word;\n//    tokenize<vector<string>>(\"a a a b b b\", word);\n\n\n//    grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0} x{0,1}\"}, \"A\"));\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"A\"));\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\", \"b\"}, \"\"));\n//    vector<string> word;\n//    tokenize<vector<string>>(\"a a a a a a a a a b b b b b b b b b\", word);\n\n//    grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0} x{1,0} x{0,1} x{1,1}\"}, \"A B\"));\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"A\"));\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\", \"b\"}, \"\"));\n//    grammar.add_rule(construct_rule(\"B\", vector<string>{\"a\", \"b\"}, \"\"));\n//    grammar.add_rule(construct_rule(\"B\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"B\"));\n//    vector<string> word;\n//    tokenize<vector<string>>(\"a a a a b b b b\", word);\n\n        grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,1} x{1,1} x{0,0} x{1,0}\"}, \"A B\", 0));\n        grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"A\", 1));\n        grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\", \"b\"}, \"\", 2));\n        grammar.add_rule(construct_rule(\"B\", vector<string>{\"\", \"\"}, \"\", 3)); // ε-rule\n        grammar.add_rule(construct_rule(\"B\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"B\", 4));\n        vector<string> word;\n        tokenize<vector<string>>(\"b b b b b a a a a a\", word);\n\n//        // grammar that contains a chain rule\n//        grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0} x{0,1}\"}, \"A\", 0));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"A\", 1));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\", \"b\"}, \"\", 2));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0}\", \"x{0,1}\"}, \"A\", 3));\n//        vector<string> word;\n//        tokenize<vector<string>>(\"a b\", word);\n\n//        // grammar that contains chain rules\n//        grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,1} x{1,1} x{0,0} x{1,0}\"}, \"A B\", 0));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"A\", 1));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\", \"b\"}, \"\", 2));\n//        grammar.add_rule(construct_rule(\"B\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"B\", 3));\n//        grammar.add_rule(construct_rule(\"B\", vector<string>{\"a\", \"b\"}, \"\", 2));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0}\", \"x{0,1}\"}, \"B\", 4));\n//        grammar.add_rule(construct_rule(\"B\", vector<string>{\"x{0,0}\", \"x{0,1}\"}, \"A\", 5));\n//        grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0}\"}, \"S\", 6));\n//        vector<string> word;\n//        tokenize<vector<string>>(\"b b b a a a\", word);\n\n\n//        // chain rules in upper position\n//        grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0}\"}, \"A\", 0));\n//        grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0}\"}, \"S\", 1));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\"}, \"A\", 2));\n//        grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\"}, \"\", 3));\n//        vector<string> word;\n//        tokenize<vector<string>>(\"a\", word);\n\n\n//    grammar.add_rule(construct_rule(\"S\", vector<string>{\"x{0,0} x{1,0}\"}, \"A B\")); // deleting rule\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"x{0,0} a\", \"x{0,1} b\"}, \"A\")); // as many a's as b's\n//    grammar.add_rule(construct_rule(\"A\", vector<string>{\"a\", \"b\"}, \"\"));\n//    grammar.add_rule(construct_rule(\"B\", vector<string>{\"\", \"\"}, \"\")); // ε-rule\n//    grammar.add_rule(construct_rule(\"B\", vector<string>{\"x{0,0} b b\"}, \"B\")); // an even number of b's\n//    vector<string> word;\n//    tokenize<vector<string>>(\"a a a a a a b b b b b b\", word);\n\n\n        clog << grammar << endl;\n\n\n        LCFRS_Parser<string, string> parser(grammar, word);\n        parser.do_parse();\n\n\n        if(parser.recognized()) {\n\n            std::clog << \"Recognizing finished successfully!\" << std::endl;\n\n            map<PassiveItem<string>, TraceItem<string, string>> trace = parser.get_trace();\n//            clog << \"Parses:\" << endl;\n\n//        print_top_trace(grammar, trace, word);\n\n            std::vector<std::string> nodeLabels {\"S\", \"A\", \"B\", \"C\"};\n            auto const nodeLabelsPtr = std::make_shared<const std::vector<string>>(nodeLabels);\n            std::vector<EdgeLabelT> edgeLabels {0, 1, 2, 3, 4, 5, 6};\n            auto const edgeLabelsPtr = std::make_shared<const std::vector<EdgeLabelT>>(edgeLabels);\n\n            parser.prune_trace();\n\n            std::clog << \"Trace was pruned.\" << std::endl;\n\n\n            auto hg{\n                    parser.convert_trace_to_hypergraph(\n                            nodeLabelsPtr\n                            , edgeLabelsPtr\n                    )};\n\n            std::clog << std::endl;\n            std::clog << \"Nodes and outgoing egdes in the pruned trace: \" << std::endl;\n            std::clog << \"Initial node: \" << hg.second << std::endl;\n            for (auto const& element : *(hg.first)) {\n                std::clog << element << \": \";\n                for(auto const& edge : (hg.first)->get_incoming_edges(element)) {\n                    for (auto const &source : edge->get_sources())\n                        std::clog << source << \" \";\n                    std::clog << \";  \";\n                }\n                std::clog << std::endl;\n            }\n        } else { // parser.recognized() is false\n            std::clog << \"There was no succesfull parse!\" << std::endl;\n        }\n        return 0;\n    }\n}\n\nint main(){\n        return LCFR::main();\n}", "meta": {"hexsha": "27bdad89fe596951c779cb347e7a6344a9cc0c28", "size": 6649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LCFR/main_lcfrs.cpp", "max_stars_repo_name": "kilian-gebhardt/panda-parser-backend", "max_stars_repo_head_hexsha": "b9877ba6df4d49456fe234d10427e60b4cc1f252", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-12T12:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-12T12:07:26.000Z", "max_issues_repo_path": "LCFR/main_lcfrs.cpp", "max_issues_repo_name": "kilian-gebhardt/panda-parser-backend", "max_issues_repo_head_hexsha": "b9877ba6df4d49456fe234d10427e60b4cc1f252", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LCFR/main_lcfrs.cpp", "max_forks_repo_name": "kilian-gebhardt/panda-parser-backend", "max_forks_repo_head_hexsha": "b9877ba6df4d49456fe234d10427e60b4cc1f252", "max_forks_repo_licenses": ["BSD-3-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.3266666667, "max_line_length": 111, "alphanum_fraction": 0.5477515416, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.025565214340883397, "lm_q1q2_score": 0.006490011055961342}}
{"text": "//=============================================================================================================\n/**\n * @file     fiff_coord_trans_old.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\n *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n *           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>\n * @since    0.1.0\n * @date     January, 2017\n *\n * @section  LICENSE\n *\n * Copyright (C) 2017, Lorenz Esch, Matti Hamalainen, Christoph Dinh. 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 the FiffCoordTransOld Class.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"fiff_coord_trans_old.h\"\n\n#include <fiff/fiff_tag.h>\n\n#include <QFile>\n\n#include <Eigen/Dense>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace FIFFLIB;\nusing namespace FIFFLIB;\n\n#ifndef TRUE\n#define TRUE 1\n#endif\n\n#ifndef FALSE\n#define FALSE 0\n#endif\n\n#ifndef FAIL\n#define FAIL -1\n#endif\n\n#ifndef OK\n#define OK 0\n#endif\n\n#define X_20 0\n#define Y_20 1\n#define Z_20 2\n\n#define FREE_20(x) if ((char *)(x) != NULL) free((char *)(x))\n\n#define MALLOC_20(x,t) (t *)malloc((x)*sizeof(t))\n\nstatic void matrix_error_20(int kind, int nr, int nc)\n\n{\n    if (kind == 1)\n        printf(\"Failed to allocate memory pointers for a %d x %d matrix\\n\",nr,nc);\n    else if (kind == 2)\n        printf(\"Failed to allocate memory for a %d x %d matrix\\n\",nr,nc);\n    else\n        printf(\"Allocation error for a %d x %d matrix\\n\",nr,nc);\n    if (sizeof(void *) == 4) {\n        printf(\"This is probably because you seem to be using a computer with 32-bit architecture.\\n\");\n        printf(\"Please consider moving to a 64-bit platform.\");\n    }\n    printf(\"Cannot continue. Sorry.\\n\");\n    exit(1);\n}\n\nfloat **mne_cmatrix_20(int nr,int nc)\n\n{\n    int i;\n    float **m;\n    float *whole;\n\n    m = MALLOC_20(nr,float *);\n    if (!m) matrix_error_20(1,nr,nc);\n    whole = MALLOC_20(nr*nc,float);\n    if (!whole) matrix_error_20(2,nr,nc);\n\n    for(i=0;i<nr;i++)\n        m[i] = whole + i*nc;\n    return m;\n}\n\n#define VEC_DIFF_20(from,to,diff) {\\\n    (diff)[X_20] = (to)[X_20] - (from)[X_20];\\\n    (diff)[Y_20] = (to)[Y_20] - (from)[Y_20];\\\n    (diff)[Z_20] = (to)[Z_20] - (from)[Z_20];\\\n    }\n\n#define ALLOC_CMATRIX_20(x,y) mne_cmatrix_20((x),(y))\n\n#define MAXWORD 1000\n\n#define VEC_DOT_20(x,y) ((x)[X_20]*(y)[X_20] + (x)[Y_20]*(y)[Y_20] + (x)[Z_20]*(y)[Z_20])\n\n#define VEC_LEN_20(x) sqrt(VEC_DOT_20(x,x))\n\n#define CROSS_PRODUCT_20(x,y,xy) {\\\n    (xy)[X_20] =   (x)[Y_20]*(y)[Z_20]-(y)[Y_20]*(x)[Z_20];\\\n    (xy)[Y_20] = -((x)[X_20]*(y)[Z_20]-(y)[X_20]*(x)[Z_20]);\\\n    (xy)[Z_20] =   (x)[X_20]*(y)[Y_20]-(y)[X_20]*(x)[Y_20];\\\n    }\n\n#define FREE_CMATRIX_20(m) mne_free_cmatrix_20((m))\n\nvoid mne_free_cmatrix_20(float **m)\n{\n    if (m) {\n        FREE_20(*m);\n        FREE_20(m);\n    }\n}\n\n#define MIN_20(a,b) ((a) < (b) ? (a) : (b))\n\n//float\nEigen::MatrixXf toFloatEigenMatrix_20(float **mat, const int m, const int n)\n{\n    Eigen::MatrixXf eigen_mat(m,n);\n\n    for ( int i = 0; i < m; ++i)\n        for ( int j = 0; j < n; ++j)\n            eigen_mat(i,j) = mat[i][j];\n\n    return eigen_mat;\n}\n\nvoid fromFloatEigenVector_20(const Eigen::VectorXf& from_vec, float *to_vec, const int n)\n{\n    for ( int i = 0; i < n; ++i)\n        to_vec[i] = from_vec[i];\n}\n\nvoid fromFloatEigenMatrix_20(const Eigen::MatrixXf& from_mat, float **& to_mat, const int m, const int n)\n{\n    for ( int i = 0; i < m; ++i)\n        for ( int j = 0; j < n; ++j)\n            to_mat[i][j] = from_mat(i,j);\n}\n\nint mne_svd_20(float **mat,\t/* The matrix */\n            int   m,int n,\t/* m rows n columns */\n            float *sing,\t/* Singular values (must have size\n                             * MIN(m,n)+1 */\n            float **uu,\t\t/* Left eigenvectors */\n            float **vv)\t\t/* Right eigenvectors */\n/*\n      * Compute the SVD of mat.\n      * The singular vector calculations depend on whether\n      * or not u and v are given.\n      *\n      * The allocations should be done as follows\n      *\n      * mat = ALLOC_CMATRIX_3(m,n);\n      * vv  = ALLOC_CMATRIX_3(MIN(m,n),n);\n      * uu  = ALLOC_CMATRIX_3(MIN(m,n),m);\n      * sing = MALLOC_3(MIN(m,n),float);\n      *\n      * mat is modified by this operation\n      *\n      * This simply allocates the workspace and calls the\n      * LAPACK Fortran routine\n      */\n\n{\n    int    udim = MIN_20(m,n);\n\n    Eigen::MatrixXf eigen_mat = toFloatEigenMatrix_20(mat, m, n);\n\n    //ToDo Optimize computation depending of whether uu or vv are defined\n    Eigen::JacobiSVD< Eigen::MatrixXf > svd(eigen_mat ,Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    fromFloatEigenVector_20(svd.singularValues(), sing, svd.singularValues().size());\n\n    if (uu != NULL)\n        fromFloatEigenMatrix_20(svd.matrixU().transpose(), uu, udim, m);\n\n    if (vv != NULL)\n        fromFloatEigenMatrix_20(svd.matrixV().transpose(), vv, m, n);\n\n    return 0;\n    //  return info;\n}\n\nvoid mne_matt_mat_mult2_20 (float **m1,float **m2,float **result,\n                         int d1,int d2,int d3)\n     /* Matrix multiplication\n      * result(d1 x d3) = m1(d2 x d1)^T * m2(d2 x d3) */\n\n{\n    #ifdef BLAS\n    char  *transa = \"N\";\n    char  *transb = \"T\";\n    float zero = 0.0;\n    float one  = 1.0;\n\n    sgemm (transa,transb,&d3,&d1,&d2,\n            &one,m2[0],&d3,m1[0],&d1,&zero,result[0],&d3);\n\n    return;\n    #else\n    int j,k,p;\n    float sum;\n    int  one = 1;\n\n    for (j = 0; j < d1; j++)\n        for (k = 0; k < d3; k++) {\n            sum = 0.0;\n        for (p = 0; p < d2; p++)\n            sum = sum + m1[p][j]*m2[p][k];\n        result[j][k] = sum;\n    }\n    return;\n    #endif\n}\n\nfloat **mne_matt_mat_mult_20 (float **m1,float **m2,int d1,int d2,int d3)\n\n{\n  float **result = ALLOC_CMATRIX_20(d1,d3);\n  mne_matt_mat_mult2_20(m1,m2,result,d1,d2,d3);\n  return result;\n}\n\nstatic void skip_comments(FILE *in)\n\n{\n    int c;\n\n    while (1) {\n        c = fgetc(in);\n        if (c == '#') {\n            for (c = fgetc(in); c != EOF && c != '\\n'; c = fgetc(in))\n                ;\n        }\n        else {\n            ungetc(c,in);\n            return;\n        }\n    }\n}\n\nstatic int whitespace(int c)\n\n{\n    if (c == '\\t' || c == '\\n' || c == ' ')\n        return TRUE;\n    else\n        return FALSE;\n}\n\nstatic int whitespace_quote(int c, int inquote)\n\n{\n    if (inquote)\n        return (c == '\"');\n    else\n        return (c == '\\t' || c == '\\n' || c == ' ');\n}\n\nstatic char *next_word_20(FILE *in)\n\n{\n    char *next = MALLOC_20(MAXWORD,char);\n    int c;\n    int  p,k;\n    int  inquote;\n\n    skip_comments(in);\n\n    inquote = FALSE;\n    for (k = 0, p = 0, c = fgetc(in); c != EOF && !whitespace_quote(c,inquote) ; c = fgetc(in), k++) {\n        if (k == 0 && c == '\"')\n            inquote = TRUE;\n        else\n            next[p++] = c;\n    }\n    if (c == EOF && k == 0) {\n        FREE_20(next);\n        return NULL;\n    }\n    else\n        next[p] = '\\0';\n    if (c != EOF) {\n        for (k = 0, c = fgetc(in); whitespace(c) ; c = fgetc(in), k++)\n            ;\n        if (c != EOF)\n            ungetc(c,in);\n    }\n#ifdef DEBUG\n    if (next)\n        printf(\"<%s>\\n\",next);\n#endif\n    return next;\n}\n\nstatic int get_fval_20(FILE *in, float *fval)\n{\n    char *next = next_word_20(in);\n    if (next == NULL) {\n        qWarning(\"bad integer\");\n        return FAIL;\n    }\n    else if (sscanf(next,\"%g\",fval) != 1) {\n        qWarning(\"bad floating point number : %s\",next);\n        FREE_20(next);\n        return FAIL;\n    }\n    FREE_20(next);\n    return OK;\n}\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nFiffCoordTransOld::FiffCoordTransOld()\n{\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld::FiffCoordTransOld(const FiffCoordTransOld &p_FiffCoordTransOld)\n{\n    this->from = p_FiffCoordTransOld.from;\n    this->to = p_FiffCoordTransOld.to;\n\n    for (int j = 0; j < 3; j++) {\n        this->move[j] = p_FiffCoordTransOld.move[j];\n        this->invmove[j] = p_FiffCoordTransOld.invmove[j];\n        for (int k = 0; k < 3; k++) {\n            this->rot(j,k) = p_FiffCoordTransOld.rot(j,k);\n            this->invrot(j,k) = p_FiffCoordTransOld.invrot(j,k);\n        }\n    }\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::catenate(FiffCoordTransOld *t1, FiffCoordTransOld *t2)\n{\n    FiffCoordTransOld* t = new FiffCoordTransOld;\n    int j,k,p;\n\n    t->to   = t1->to;\n    t->from = t2->from;\n\n    for (j = 0; j < 3; j++) {\n        t->move[j] = t1->move[j];\n        for (k = 0; k < 3; k++) {\n            t->rot(j,k) = 0.0;\n            t->move[j] += t1->rot(j,k)*t2->move[k];\n            for (p = 0; p < 3; p++)\n                t->rot(j,k) += t1->rot(j,p)*t2->rot(p,k);\n        }\n    }\n    add_inverse(t);\n    return (t);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld::FiffCoordTransOld(int from, int to, float rot[3][3], float move[3])\n{\n    this->from = from;\n    this->to   = to;\n\n    for (int j = 0; j < 3; j++) {\n        this->move[j] = move[j];\n        for (int k = 0; k < 3; k++)\n            this->rot(j,k) = rot[j][k];\n    }\n    add_inverse(this);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld::~FiffCoordTransOld()\n{\n}\n\n//=============================================================================================================\n\nFiffCoordTrans FiffCoordTransOld::toNew()\n{\n    FiffCoordTrans t = *new FiffCoordTrans;\n    MatrixXf trans = MatrixXf::Identity(4,4);\n    trans.block(0,0,3,3) = this->rot;\n    trans.block(0,3,3,1) = this->move;\n    t.to = this->to;\n    t.from = this->from;\n    t.trans = trans;\n    t.addInverse(t);\n    return t;\n}\n\n//=============================================================================================================\n\nint FiffCoordTransOld::add_inverse(FiffCoordTransOld *t)\n{\n    Matrix4f m = Matrix4f::Identity(4,4);\n\n    m.block(0,0,3,3) = t->rot;\n    m.block(0,3,3,1) = t->move;\n\n    m = m.inverse().eval();\n\n    t->invrot = m.block(0,0,3,3);\n    t->invmove = m.block(0,3,3,1);\n\n    return OK;\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::fiff_invert_transform() const\n{\n    FiffCoordTransOld* ti = new FiffCoordTransOld;\n    ti->move = this->invmove;\n    ti->invmove = this ->move;\n    ti->rot = this->invrot;\n    ti->invrot = this ->rot;\n    ti->from = this->to;\n    ti->to   = this->from;\n    return (ti);\n}\n\n//=============================================================================================================\n\nvoid FiffCoordTransOld::fiff_coord_trans(float r[], const FiffCoordTransOld *t, int do_move)\n/*\n * Apply coordinate transformation\n */\n{\n    int j,k;\n    float res[3];\n\n    for (j = 0; j < 3; j++) {\n        res[j] = (do_move ? t->move[j] :  0.0);\n        for (k = 0; k < 3; k++)\n            res[j] += t->rot(j,k)*r[k];\n    }\n    for (j = 0; j < 3; j++)\n        r[j] = res[j];\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::fiff_combine_transforms(int from, int to, FiffCoordTransOld *t1, FiffCoordTransOld *t2)\n/*\n * Combine two coordinate transformations\n * to yield a transform from 'from' system\n * to 'to' system.\n *\n * Return NULL if this fails\n *\n */\n{\n    FiffCoordTransOld* t = NULL;\n    int swapped = 0;\n    FiffCoordTransOld* temp;\n    /*\n       * We have a total of eight possibilities:\n       * four without swapping and four with\n       */\n    while (1) {\n        if (t1->to == to && t2->from == from) {\n            t1 = new FiffCoordTransOld(*t1);\n            t2 = new FiffCoordTransOld(*t2);\n            break;\n        }\n        else if (t1->from == to && t2->from == from) {\n            FiffCoordTransOld* tmp_t1 = t1;\n            t1 = tmp_t1->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t1;\n            t2 = new FiffCoordTransOld(*t2);\n            break;\n        }\n        else if (t1->to == to && t2->to == from) {\n            t1 = new FiffCoordTransOld(*t1);\n            FiffCoordTransOld* tmp_t2 = t2;\n            t2 = tmp_t2->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t2;\n            break;\n        }\n        else if (t1->from == to && t2->to == from) {\n            FiffCoordTransOld* tmp_t1 = t1;\n            t1 = tmp_t1->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t1;\n            FiffCoordTransOld* tmp_t2 = t2;\n            t2 = tmp_t2->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t2;\n            break;\n        }\n        if (swapped) {  /* Already swapped and not found */\n            qCritical(\"Cannot combine coordinate transforms\");\n            return (t);\n        }\n        temp = t1;      /* Try it swapped as well */\n        t1 = t2;\n        t2 = temp;\n        swapped = 1;\n    }\n    if (t1->from  != t2->to)    /* Transforms must match on the other side as well */\n        qCritical (\"Cannot combine coordinate transforms\");\n    else                        /* We can do it directly */\n        t = catenate(t1,t2);\n    FREE_20(t1); FREE_20(t2);\n    return (t);\n}\n\n//=============================================================================================================\n\nvoid FiffCoordTransOld::fiff_coord_trans_inv(float r[], FiffCoordTransOld *t, int do_move)\n/*\n * Apply inverse coordinate transformation\n */\n{\n    int j,k;\n    float res[3];\n\n    for (j = 0; j < 3; j++) {\n        res[j] = (do_move ? t->invmove[j] :  0.0);\n        for (k = 0; k < 3; k++)\n            res[j] += t->invrot(j,k)*r[k];\n    }\n    for (j = 0; j < 3; j++)\n        r[j] = res[j];\n}\n\n//=============================================================================================================\n\ntypedef struct {\n    int frame;\n    const char *name;\n} frameNameRec;\n\nconst char *FiffCoordTransOld::mne_coord_frame_name(int frame)\n{\n    static frameNameRec frames[] = {\n        {FIFFV_COORD_UNKNOWN,\"unknown\"},\n        {FIFFV_COORD_DEVICE,\"MEG device\"},\n        {FIFFV_COORD_ISOTRAK,\"isotrak\"},\n        {FIFFV_COORD_HPI,\"hpi\"},\n        {FIFFV_COORD_HEAD,\"head\"},\n        {FIFFV_COORD_MRI,\"MRI (surface RAS)\"},\n        {FIFFV_MNE_COORD_MRI_VOXEL, \"MRI voxel\"},\n        {FIFFV_COORD_MRI_SLICE,\"MRI slice\"},\n        {FIFFV_COORD_MRI_DISPLAY,\"MRI display\"},\n        {FIFFV_MNE_COORD_CTF_DEVICE,\"CTF MEG device\"},\n        {FIFFV_MNE_COORD_CTF_HEAD,\"CTF/4D/KIT head\"},\n        {FIFFV_MNE_COORD_RAS,\"RAS (non-zero origin)\"},\n        {FIFFV_MNE_COORD_MNI_TAL,\"MNI Talairach\"},\n        {FIFFV_MNE_COORD_FS_TAL_GTZ,\"Talairach (MNI z > 0)\"},\n        {FIFFV_MNE_COORD_FS_TAL_LTZ,\"Talairach (MNI z < 0)\"},\n        {-1,\"unknown\"}\n    };\n    int k;\n    for (k = 0; frames[k].frame != -1; k++) {\n        if (frame == frames[k].frame)\n            return frames[k].name;\n    }\n    return frames[k].name;\n}\n\n//=============================================================================================================\n\nvoid FiffCoordTransOld::mne_print_coord_transform_label(FILE *log, char *label, FiffCoordTransOld *t)\n{\n    int k,p;\n    int frame;\n    if (!label || strlen(label) == 0)\n        fprintf(log,\"Coordinate transformation: \");\n    else\n        fprintf(log,\"%s\",label);\n    for (frame = t->from, k = 0; k < 2; k++) {\n        if (k == 0) {\n            fprintf(log,\"%s -> \",mne_coord_frame_name(frame));\n            frame = t->to;\n        }\n        else {\n            fprintf(log,\"%s\\n\",mne_coord_frame_name(frame));\n            for (p = 0; p < 3; p++)\n                fprintf(log,\"\\t% 8.6f % 8.6f % 8.6f\\t% 7.2f mm\\n\",\n                        t->rot(p,X_20),t->rot(p,Y_20),t->rot(p,Z_20),1000*t->move[p]);\n            fprintf(log,\"\\t% 8.6f % 8.6f % 8.6f  % 7.2f\\n\",0.0,0.0,0.0,1.0);\n        }\n    }\n}\n\n//=============================================================================================================\n\nvoid FiffCoordTransOld::mne_print_coord_transform(FILE *log, FiffCoordTransOld *t)\n{\n    mne_print_coord_transform_label(log,NULL,t);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_transform(const QString &name, int from, int to)\n/*\n          * Read the specified coordinate transformation\n          */\n{\n    QFile file(name);\n    FiffStream::SPtr stream(new FiffStream(&file));\n\n    FiffCoordTransOld* res = NULL;\n    //    fiffFile       in = NULL;\n    FiffTag::SPtr t_pTag;\n    //    fiffTagRec     tag;\n    //    fiffDirEntry   dir;\n    fiff_int_t kind, pos;\n    int k;\n\n    //    tag.data = NULL;\n    //    if ((in = fiff_open(name.toUtf8().data())) == NULL)\n    //        goto out;\n    if(!stream->open())\n        goto out;\n\n    for (k = 0; k < stream->dir().size(); k++) {\n        kind = stream->dir()[k]->kind;\n        pos  = stream->dir()[k]->pos;\n        if (kind == FIFF_COORD_TRANS) {\n            //            if (fiff_read_this_tag (in->fd,dir->pos,&tag) == FIFF_FAIL)\n            //                goto out;\n            //            res = (fiffCoordTrans)tag.data;\n            if (!stream->read_tag(t_pTag,pos))\n                goto out;\n\n            res = FiffCoordTransOld::read_helper( t_pTag );\n            if (res->from == from && res->to == to) {\n                //                tag.data = NULL;\n                goto out;\n            }\n            else if (res->from == to && res->to == from) {\n                FiffCoordTransOld* tmp_res = res;\n                res = tmp_res->fiff_invert_transform();//Memory leak here!!\n                delete tmp_res;\n                goto out;\n            }\n            res = NULL;\n        }\n    }\n    qCritical(\"No suitable coordinate transformation found in %s.\",name.toUtf8().data());\n    goto out;\n\nout : {\n        //        FREE(tag.data);\n        //        fiff_close(in);\n        stream->close();\n        return res;\n    }\n\n    return res;\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_transform_from_node(FiffStream::SPtr &stream, const FiffDirNode::SPtr &node, int from, int to)\n/*\n * Read the specified coordinate transformation\n */\n{\n    FiffCoordTransOld* res = NULL;\n    FiffTag::SPtr t_pTag;\n    //    fiffTagRec     tag;\n    //    fiffDirEntry   dir;\n    fiff_int_t kind, pos;\n    int k;\n\n    //    tag.data = NULL;\n    for (k = 0; k < node->nent(); k++)\n        kind = node->dir[k]->kind;\n    pos  = node->dir[k]->pos;\n    if (kind == FIFF_COORD_TRANS) {\n        //            if (fiff_read_this_tag (in->fd,dir->pos,&tag) == FIFF_FAIL)\n        //                goto out;\n        //            res = (fiffCoordTrans)tag.data;\n        if (!stream->read_tag(t_pTag,pos))\n            goto out;\n        res = FiffCoordTransOld::read_helper( t_pTag );\n        if (res->from == from && res->to == to) {\n            //                tag.data = NULL;\n            goto out;\n        }\n        else if (res->from == to && res->to == from) {\n            FiffCoordTransOld* tmp_res = res;\n            res = tmp_res->fiff_invert_transform();//Memory leak here!!\n            delete tmp_res;\n            goto out;\n        }\n        res = NULL;\n    }\n    printf(\"No suitable coordinate transformation found\");\n    goto out;\n\nout : {\n        //        FREE(tag.data);\n        return res;\n    }\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_mri_transform(const QString &name)\n/*\n          * Read the MRI -> HEAD coordinate transformation\n          */\n{\n    return mne_read_transform(name,FIFFV_COORD_MRI,FIFFV_COORD_HEAD);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_meas_transform(const QString &name)\n/*\n * Read the MEG device -> HEAD coordinate transformation\n */\n{\n    return mne_read_transform(name,FIFFV_COORD_DEVICE,FIFFV_COORD_HEAD);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_transform_ascii(char *name, int from, int to)\n/*\n * Read the Neuromag -> FreeSurfer transformation matrix\n */\n{\n    FILE *in = NULL;\n    FiffCoordTransOld* t = NULL;\n    float rot[3][3];\n    float move[3];\n    int   k;\n    float dum;\n\n    if ((in = fopen(name,\"r\")) == NULL) {\n        qCritical(name);\n        goto bad;\n    }\n    for (k = 0; k < 3; k++) {\n        if (get_fval_20(in,rot[k]+X_20) == FAIL)\n            goto noread;\n        if (get_fval_20(in,rot[k]+Y_20) == FAIL)\n            goto noread;\n        if (get_fval_20(in,rot[k]+Z_20) == FAIL)\n            goto noread;\n        if (get_fval_20(in,move+k) == FAIL)\n            goto noread;\n    }\n    for (k = 0; k < 4; k++) {\n        if (get_fval_20(in,&dum) == FAIL)\n            goto noread;\n    }\n    fclose(in);\n    for (k = 0; k < 3; k++)\n        move[k] = move[k]/1000.0;\n    t  = new FiffCoordTransOld(from, to, rot, move );\n    return t;\n\nnoread : {\n        qCritical(\"Cannot read the coordinate transformation\");\n        goto bad;\n    }\n\nbad : {\n        if(t)\n            delete t;\n        if (in != NULL)\n            fclose(in);\n        return NULL;\n    }\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_FShead2mri_transform(char *name)\n{\n    return mne_read_transform_ascii(name,FIFFV_COORD_HEAD,FIFFV_COORD_MRI);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::mne_identity_transform(int from, int to)\n{\n    float rot[3][3] = { { 1.0, 0.0, 0.0 },\n                        { 0.0, 1.0, 0.0 },\n                        { 0.0, 0.0, 1.0 } };\n    float move[] = { 0.0, 0.0, 0.0 };\n    return new FiffCoordTransOld(from,to,rot,move);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld * FiffCoordTransOld::fiff_make_transform_card (int from,int to,\n                                                                 float *rL,\n                                                                 float *rN,\n                                                                 float *rR)\n/* 'from' coordinate system\n * cardinal points expressed in\n * the 'to' system */\n\n{\n    FiffCoordTransOld* t = new FiffCoordTransOld();\n    float ex[3],ey[3],ez[3];\t/* The unit vectors */\n    float alpha,alpha1,len;\n    float diff1[3],diff2[3];\n    int   k;\n    float r0[3];\n\n    t->from = from;\n    t->to   = to;\n    for (k = 0; k < 3; k++) {\n        diff1[k] = rN[k] - rL[k];\n        diff2[k] = rR[k] - rL[k];\n    }\n    alpha = VEC_DOT_20(diff1,diff2)/VEC_DOT_20(diff2,diff2);\n    len = VEC_LEN_20(diff2);\n    alpha1 = 1.0 - alpha;\n\n    for (k = 0; k < 3; k++) {\n        r0[k] = alpha1*rL[k] + alpha*rR[k];\n        ex[k] = diff2[k]/len;\n        ey[k] = rN[k] - r0[k];\n        t->move[k] = r0[k];\n    }\n\n    len = VEC_LEN_20(ey);\n\n    for (k = 0; k < 3; k++)\n        ey[k] = ey[k]/len;\n\n    CROSS_PRODUCT_20 (ex,ey,ez);\n\n    for (k = 0; k < 3; k++) {\n        t->rot(k,X_20) = ex[k];\n        t->rot(k,Y_20) = ey[k];\n        t->rot(k,Z_20) = ez[k];\n    }\n\n    add_inverse (t);\n\n    return (t);\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld* FiffCoordTransOld::procrustes_align(int   from_frame,  /* The coordinate frames */\n                       int   to_frame,\n                       float **fromp,     /* Point locations in these two coordinate frames */\n                       float **top,\n                       float *w,\t  /* Optional weights */\n                       int   np,\t  /* How many points */\n                       float max_diff)\t  /* Maximum allowed difference */\n/*\n * Perform an alignment using the the solution of the orthogonal (weighted) Procrustes problem\n */\n{\n    float **from = ALLOC_CMATRIX_20(np,3);\n    float **to   = ALLOC_CMATRIX_20(np,3);\n    float from0[3],to0[3],rr[3],diff[3];\n    int   j,k,c,p;\n    float rot[3][3];\n    float move[3];\n\n    /*\n     * Calculate the centroids and subtract;\n     */\n    for (c = 0; c < 3; c++)\n        from0[c] = to0[c] = 0.0;\n    for (j = 0; j < np; j++) {\n        for (c = 0; c < 3; c++) {\n            from0[c] += fromp[j][c];\n            to0[c] += top[j][c];\n        }\n    }\n    for (c = 0; c < 3; c++) {\n        from0[c] = from0[c]/np;\n        to0[c] = to0[c]/np;\n    }\n    for (j = 0; j < np; j++) {\n        for (c = 0; c < 3; c++) {\n            from[j][c] = fromp[j][c] - from0[c];\n            to[j][c]   = top[j][c]    - to0[c];\n        }\n    }\n    /*\n     * Compute the solution of the orthogonal Proscrustes problem\n     */\n    {\n        float **S;\n        float **uu = ALLOC_CMATRIX_20(3,3);\n        float **vv = ALLOC_CMATRIX_20(3,3);\n        float **R = NULL;\n        float sing[3];\n\n        if (w) {\n            /*\n            * This is the weighted version which allows multiplicity of points\n            */\n            S = ALLOC_CMATRIX_20(3,3);\n            for (j = 0; j < 3; j++) {\n                for (k = 0; k < 3; k++) {\n                    S[j][k] = 0.0;\n                    for (p = 0; p < np; p++)\n                        S[j][k] += w[p]*from[p][j]*to[p][k];\n                }\n            }\n        }\n        else\n            S = mne_matt_mat_mult_20(from,to,3,np,3);\n        if (mne_svd_20(S,3,3,sing,uu,vv) != 0) {\n            FREE_CMATRIX_20(S);\n            FREE_CMATRIX_20(uu);\n            FREE_CMATRIX_20(vv);\n            goto bad;\n        }\n        R = mne_matt_mat_mult_20(vv,uu,3,3,3);\n        for (j = 0; j < 3; j++)\n            for (k = 0; k < 3; k++)\n                rot[j][k] = R[j][k];\n        FREE_CMATRIX_20(R);\n        FREE_CMATRIX_20(S);\n        FREE_CMATRIX_20(uu);\n        FREE_CMATRIX_20(vv);\n    }\n    /*\n     * Now we need to generate a transformed translation vector\n     */\n    for (j = 0; j < 3; j++) {\n        move[j] = to0[j];\n        for (k = 0; k < 3; k++)\n            move[j] = move[j] - rot[j][k]*from0[k];\n    }\n    /*\n     * Test the transformation and print the results\n     */\n    #ifdef DEBUG\n    fprintf(stderr,\"Procrustes matching (desired vs. transformed) :\\n\");\n    #endif\n    for (p = 0; p < np; p++) {\n        for (j = 0; j < 3; j++) {\n            rr[j] = move[j];\n        for (k = 0; k < 3; k++)\n            rr[j] += rot[j][k]*fromp[p][k];\n        }\n        VEC_DIFF_20(top[p],rr,diff);\n        #ifdef DEBUG\n        fprintf(stderr,\"\\t%7.2f %7.2f %7.2f mm <-> %7.2f %7.2f %7.2f mm diff = %8.3f mm\\n\",\n        1000*top[p][0],1000*top[p][1],1000*top[p][2],\n        1000*rr[0],1000*rr[1],1000*rr[2],1000*VEC_LEN(diff));\n        #endif\n        if (VEC_LEN_20(diff) > max_diff) {\n            printf(\"To large difference in matching : %7.1f > %7.1f mm\", 1000*VEC_LEN_20(diff),1000*max_diff);\n            goto bad;\n        }\n    }\n    #ifdef DEBUG\n    fprintf(stderr,\"\\n\");\n    #endif\n\n    FREE_CMATRIX_20(from);\n    FREE_CMATRIX_20(to);\n\n    return new FiffCoordTransOld(from_frame,to_frame,rot,move);\n\n    bad : {\n        FREE_CMATRIX_20(from);\n        FREE_CMATRIX_20(to);\n        return NULL;\n    }\n}\n\n//=============================================================================================================\n\nFiffCoordTransOld *FiffCoordTransOld::read_helper( FIFFLIB::FiffTag::SPtr& tag)\n{\n    FiffCoordTransOld* p_FiffCoordTrans = NULL;\n    if(tag->isMatrix() || tag->getType() != FIFFT_COORD_TRANS_STRUCT || tag->data() == NULL)\n        return p_FiffCoordTrans;\n    else\n    {\n        p_FiffCoordTrans = new FiffCoordTransOld;\n        qint32* t_pInt32 = (qint32*)tag->data();\n        p_FiffCoordTrans->from = t_pInt32[0];\n        p_FiffCoordTrans->to = t_pInt32[1];\n\n        float* t_pFloat = (float*)tag->data();\n        int count = 0;\n        int r, c;\n        for (r = 0; r < 3; ++r) {\n            p_FiffCoordTrans->move[r] = t_pFloat[11+r];\n            for (c = 0; c < 3; ++c) {\n                p_FiffCoordTrans->rot(r,c) = t_pFloat[2+count];\n                ++count;\n            }\n        }\n\n        count = 0;\n        for (r = 0; r < 3; ++r) {\n            p_FiffCoordTrans->invmove[r] = t_pFloat[23+r];\n            for (c = 0; c < 3; ++c) {\n                p_FiffCoordTrans->invrot(r,c) = t_pFloat[14+count];\n                ++count;\n            }\n        }\n\n        return p_FiffCoordTrans;\n    }\n}\n", "meta": {"hexsha": "116a609fbe6b9e6b68cc5fc5402c1e9e8cc24512", "size": 30874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fiff/c/fiff_coord_trans_old.cpp", "max_stars_repo_name": "svdecomposer/mne-cpp", "max_stars_repo_head_hexsha": "dad9a6da135a46cd4985d99881e6f6a569b66e5a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T20:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-29T20:17:57.000Z", "max_issues_repo_path": "libraries/fiff/c/fiff_coord_trans_old.cpp", "max_issues_repo_name": "svdecomposer/mne-cpp", "max_issues_repo_head_hexsha": "dad9a6da135a46cd4985d99881e6f6a569b66e5a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/fiff/c/fiff_coord_trans_old.cpp", "max_forks_repo_name": "svdecomposer/mne-cpp", "max_forks_repo_head_hexsha": "dad9a6da135a46cd4985d99881e6f6a569b66e5a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-15T17:46:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T17:46:25.000Z", "avg_line_length": 29.5727969349, "max_line_length": 141, "alphanum_fraction": 0.4770680832, "num_tokens": 8647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.01854656383401801, "lm_q1q2_score": 0.006466169257890873}}
{"text": "/* This file is part of VoltDB.\n * Copyright (C) 2008-2020 VoltDB Inc.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * 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 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 VoltDB.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <memory>\n#include <sstream>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/foreach.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n\n#include \"common/ValueFactory.hpp\"\n#include \"expressions/geofunctions.h\"\n\nnamespace voltdb {\n\nstatic const int POINT = FUNC_VOLT_POINTFROMTEXT;\nstatic const int POLY = FUNC_VOLT_POLYGONFROMTEXT;\n\nstatic const double SPHERICAL_EARTH_MEAN_RADIUS_M = 6371008.8; // mean radius in meteres\nstatic const double RADIUS_SQ_M = SPHERICAL_EARTH_MEAN_RADIUS_M * SPHERICAL_EARTH_MEAN_RADIUS_M;\n\ntypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\n\nstatic bool isMultiPolygon(const Polygon &poly, std::stringstream *msg);\nstatic void throwInvalidWktPoint(const std::string& input) {\n    std::ostringstream oss;\n    oss << \"Invalid input to POINTFROMTEXT: \";\n    oss << \"'\" << input << \"', \";\n    oss << \"expected input of the form 'POINT(<lng> <lat>)'\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\nstatic void throwInvalidWktPoly(const std::string& reason) {\n    std::ostringstream oss;\n    oss << \"Invalid input to POLYGONFROMTEXT: \" << reason << \".  \";\n    oss << \"Expected input of the form 'POLYGON((<lng> <lat>, ...), ...)'\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\nstatic void throwInvalidMakeValidPoly(const std::string& reason) {\n    std::ostringstream oss;\n    oss << \"Invalid input to MAKE_VALID_POLYGON: \" << reason << \".\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\nstatic void throwInvalidPointLatitude(const std::string& input) {\n    std::ostringstream oss;\n    oss << \"Invalid input to POINTFROMTEXT: '\" << input << \"'\";\n    oss << \".  Latitude must be in the range [-90,90].\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\nstatic void throwInvalidPointLongitude(const std::string& input) {\n    std::ostringstream oss;\n    oss << \"Invalid input to POINTFROMTEXT: '\" << input << \"'\";\n    oss << \".  Longitude must be in the range [-180,180].\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\nstatic void throwInvalidPolygonLatitude(const std::string& input) {\n    std::ostringstream oss;\n    oss << \"Invalid input to POLYGONFROMTEXT: '\" << input << \"'\";\n    oss << \".  Latitude must be in the range [-90,90].\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\nstatic void throwInvalidPolygonLongitude(const std::string& input) {\n    std::ostringstream oss;\n    oss << \"Invalid input to POLYGONFROMTEXT: '\" << input << \"'\";\n    oss << \".  Longitude must be in the range [-180,180].\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\nstatic void throwInvalidDistanceDWithin(const std::string& msg) {\n    std::ostringstream oss;\n    oss << \"Invalid input to DWITHIN function: '\" << msg << \"'.\";\n    throw SQLException(SQLException::data_exception_invalid_parameter,\n                       oss.str().c_str());\n}\n\n\nstatic GeographyPointValue::Coord stringToCoord(int pointOrPoly,\n        const std::string& input, const std::string& val) {\n    GeographyPointValue::Coord coord = 0.0;\n    try {\n        coord = boost::lexical_cast<GeographyPointValue::Coord>(val);\n    } catch (const boost::bad_lexical_cast&) {\n        if (pointOrPoly == POLY) {\n            throwInvalidWktPoly(\"expected a number but found '\" + val + \"'\");\n        } else {\n            throwInvalidWktPoint(input);\n        }\n    }\n\n    return coord;\n}\n\n\n// function computes distance between two non-null points\n// function computes distance using Haversine formula\nstatic double getDistance(const GeographyPointValue &point1,\n                          const GeographyPointValue &point2) {\n    vassert(!point1.isNull());\n    vassert(!point2.isNull());\n\n    const S2LatLng latLng1 = S2LatLng(point1.toS2Point()).Normalized();\n    const S2LatLng latLng2 = S2LatLng(point2.toS2Point()).Normalized();\n    S1Angle distance = latLng1.GetDistance(latLng2);\n    return distance.radians() * SPHERICAL_EARTH_MEAN_RADIUS_M;\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POINTFROMTEXT>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tPOINT);\n    }\n\n    int32_t textLength;\n    const char* textData = getObject_withoutNull(textLength);\n    std::string wkt(textData, textLength);\n\n    // Discard whitespace, but return commas or parentheses as tokens\n    Tokenizer tokens(wkt, boost::char_separator<char>(\" \\f\\n\\r\\t\\v\", \",()\"));\n    Tokenizer::iterator it = tokens.begin();\n    Tokenizer::iterator end = tokens.end();\n\n    if (! boost::iequals(*it, \"point\")) {\n        throwInvalidWktPoint(wkt);\n    }\n    ++it;\n\n    if (! boost::iequals(*it, \"(\")) {\n        throwInvalidWktPoint(wkt);\n    }\n    ++it;\n\n\n    GeographyPointValue::Coord lng = stringToCoord(POINT, wkt, *it);\n    ++it;\n\n    GeographyPointValue::Coord lat = stringToCoord(POINT, wkt, *it);\n    ++it;\n\n    if ( lng < -180.0 || lng > 180.0) {\n        throwInvalidPointLongitude(wkt);\n    } else if (lat < -90.0 || lat > 90.0 ) {\n        throwInvalidPointLatitude(wkt);\n    }\n\n    if (! boost::iequals(*it, \")\")) {\n        throwInvalidWktPoint(wkt);\n    }\n    ++it;\n\n    if (it != end) {\n        throwInvalidWktPoint(wkt);\n    }\n\n    NValue returnValue(ValueType::tPOINT);\n    returnValue.getGeographyPointValue() = GeographyPointValue(lng, lat);\n\n    return returnValue;\n}\n\n#undef DEBUG_POLYGONS\n\n#if defined(DEBUG_POLYGONS)\nstatic void printLoop(int lidx, bool is_shell, S2Loop *loop) {\n    std::cout << \"Loop \" << lidx << \": \";\n    std::cout << (is_shell ? \"\" : \"not \") << \"a shell, \";\n    std::cout << \"depth = \" << loop->depth();\n    std::cout << \", is_hole = \" << loop->is_hole();\n    std::cout << \", points: \";\n    std::string sep(\"\");\n    for (int idx = 0; idx < loop->num_vertices(); idx += 1) {\n        S2LatLng ll(loop->vertex(idx));\n        std::cout << sep << \"(\" << ll.lng().degrees() << \", \" << ll.lat().degrees() << \")\";\n        sep = \", \";\n    }\n    std::cout << \"\\n\";\n}\n\nstatic void printPolygon(const std::string &label, const S2Polygon *poly) {\n    std::cout << label << \":\\n\";\n    std::cout << (poly->has_holes() ? \"Has holes\" : \"Has no holes\") << std::endl;\n    for (int lidx = 0; lidx < poly->num_loops(); lidx += 1) {\n        S2Loop *loop = poly->loop(lidx);\n        printLoop(lidx, !loop->is_hole(), loop);\n    }\n    std::cout << std::flush;\n}\n#else\n#define printLoop(lidx, is_shell, loop)\n#define printPolygon(label, poly)\n#endif\n\nstatic void readLoop(bool is_shell,\n        const std::string &wkt,\n        Tokenizer::iterator &it,\n        const Tokenizer::iterator &end,\n        S2Loop *loop) {\n    if (! boost::iequals(*it, \"(\")) {\n        throwInvalidWktPoly(\"expected left parenthesis to start a ring\");\n    }\n    ++it;\n\n    std::vector<S2Point> points;\n    while (it != end && *it != \")\") {\n        GeographyPointValue::Coord lng = stringToCoord(POLY, wkt, *it);\n\n        if (lng < -180 || lng > 180) {\n            throwInvalidPolygonLongitude(*it);\n        }\n        ++it;\n        GeographyPointValue::Coord lat = stringToCoord(POLY, wkt, *it);\n        if (lat < -90 || lat > 90) {\n            throwInvalidPolygonLatitude(*it);\n        }\n        ++it;\n\n        // Note: This is S2.  It takes latitude, longitude, not\n        //       longitude, latitude.\n        points.push_back(S2LatLng::FromDegrees(lat, lng).ToPoint());\n\n        if (*it == \",\") {\n            ++it;\n            // continue to next lat long pair\n        } else if (*it != \")\") {\n            throwInvalidWktPoly(\"unexpected token: '\" + (*it) + \"'\");\n        }\n    }\n\n    if (it == end) {\n        // we hit the end of input before the closing parenthesis\n        throwInvalidWktPoly(\"unexpected end of input\");\n    }\n\n    vassert(*it == \")\");\n\n    // Advance iterator to next token\n    ++it;\n\n    if (points.size() < 4) {\n        throwInvalidWktPoly(\"A polygon ring must contain at least 4 points (including repeated closing vertex)\");\n    }\n\n    const S2Point& first = points.at(0);\n    const S2Point& last = points.at(points.size() - 1);\n\n    if (first != last) {\n        throwInvalidWktPoly(\"A polygon ring's first vertex must be equal to its last vertex\");\n    }\n\n    // S2 format considers the closing vertex in a loop to be\n    // implicit, while in WKT it is explicit.  Remove the closing\n    // vertex here to reflect this.\n    points.pop_back();\n    // The first is a shell.  All others are holes.  We need to reverse\n    // the order of the vertices for holes.\n    if (!is_shell) {\n        // Don't touch the first point.  We don't want to\n        // cycle the vertices.\n        std::reverse(++(points.begin()), points.end());\n    }\n    loop->Init(points);\n}\n\nstatic NValue polygonFromText(const std::string &wkt, bool doRepairs) {\n    // Discard whitespace, but return commas or parentheses as tokens\n    Tokenizer tokens(wkt, boost::char_separator<char>(\" \\f\\n\\r\\t\\v\", \",()\"));\n    Tokenizer::iterator it = tokens.begin();\n    Tokenizer::iterator end = tokens.end();\n\n    if (! boost::iequals(*it, \"polygon\")) {\n        throwInvalidWktPoly(\"does not start with POLYGON keyword\");\n    }\n    ++it;\n\n    if (! boost::iequals(*it, \"(\")) {\n        throwInvalidWktPoly(\"missing left parenthesis after POLYGON keyword\");\n    }\n    ++it;\n\n    bool is_shell = true;\n    // This is the length of the polygon when serialized.\n    // We could get this with Polygon::serializedLenth.  But\n    // that would require traversing the loops twice, and\n    // who has time for that?\n    std::size_t length = Polygon::serializedLengthNoLoops();\n    std::vector<std::unique_ptr<S2Loop> > loops;\n    while (it != end) {\n        loops.push_back(std::unique_ptr<S2Loop>(new S2Loop()));\n        readLoop(is_shell, wkt, it, end, loops.back().get());\n        // Only the first loop is a shell.\n        is_shell = false;\n        length += Loop::serializedLength(loops.back()->num_vertices());\n        if (*it == \",\") {\n            ++it;\n        } else if (*it == \")\") {\n            ++it;\n            break;\n        } else {\n            throwInvalidWktPoly(\"unexpected token: '\" + (*it) + \"'\");\n        }\n    }\n\n    if (it != end) {\n        // extra stuff after input\n        throwInvalidWktPoly(\"unrecognized input after WKT: '\" + (*it) + \"'\");\n    }\n\n    NValue nval = ValueFactory::getUninitializedTempGeographyValue(length);\n    char* storage = const_cast<char*>(ValuePeeker::peekObjectValue(nval));\n\n    Polygon poly;\n    poly.init(&loops, doRepairs); // polygon takes ownership of loops here.\n    if (doRepairs) {\n        std::stringstream validReason;\n        if (!poly.IsValid(&validReason) || isMultiPolygon(poly, &validReason)) {\n            throwInvalidWktPoly(validReason.str());\n        }\n    }\n    SimpleOutputSerializer output(storage, length);\n    poly.saveToBuffer(output);\n    return nval;\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POLYGONFROMTEXT>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tGEOGRAPHY);\n    }\n\n    int32_t textLength;\n    const char* textData = getObject_withoutNull(textLength);\n    const std::string wkt(textData, textLength);\n\n    return polygonFromText(wkt, false);\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_VALIDPOLYGONFROMTEXT>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tGEOGRAPHY);\n    }\n\n    int32_t textLength;\n    const char* textData = getObject_withoutNull(textLength);\n    const std::string wkt(textData, textLength);\n\n    return polygonFromText(wkt, true);\n}\n\ntemplate<> NValue NValue::call<FUNC_VOLT_CONTAINS>(const std::vector<NValue>& arguments) {\n    if (arguments[0].isNull() || arguments[1].isNull())\n        return NValue::getNullValue(ValueType::tBOOLEAN);\n\n    Polygon poly;\n    poly.initFromGeography(arguments[0].getGeographyValue());\n    S2Point pt = arguments[1].getGeographyPointValue().toS2Point();\n    return ValueFactory::getBooleanValue(poly.Contains(pt));\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POLYGON_NUM_INTERIOR_RINGS>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tINTEGER);\n    }\n\n    Polygon poly;\n    poly.initFromGeography(getGeographyValue());\n\n    NValue retVal(ValueType::tINTEGER);\n    // exclude exterior ring\n    retVal.getInteger() = poly.num_loops() - 1;\n    return retVal;\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POLYGON_NUM_POINTS>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tINTEGER);\n    }\n\n    Polygon poly;\n    poly.initFromGeography(getGeographyValue());\n\n    // the OGC spec suggests that the number of vertices should\n    // include the repeated closing vertex which is implicit in S2's\n    // representation.  So add an extra vertex for each loop.\n    int32_t numPoints = poly.num_vertices() + poly.num_loops();\n\n    NValue retVal(ValueType::tINTEGER);\n    retVal.getInteger() = numPoints;\n    return retVal;\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POINT_LATITUDE>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tDOUBLE);\n    }\n    const GeographyPointValue point = getGeographyPointValue();\n    NValue retVal(ValueType::tDOUBLE);\n    retVal.getDouble() = point.getLatitude();\n    return retVal;\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POINT_LONGITUDE>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tDOUBLE);\n    }\n    const GeographyPointValue point = getGeographyPointValue();\n    NValue retVal(ValueType::tDOUBLE);\n    retVal.getDouble() = point.getLongitude();\n    return retVal;\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POLYGON_CENTROID>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tPOINT);\n    }\n\n    Polygon polygon;\n    polygon.initFromGeography(getGeographyValue());\n    const GeographyPointValue point(polygon.GetCentroid());\n    NValue retVal(ValueType::tPOINT);\n    retVal.getGeographyPointValue() = point;\n    return retVal;\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POLYGON_AREA>() const {\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tDOUBLE);\n    }\n\n    Polygon polygon;\n    polygon.initFromGeography(getGeographyValue());\n\n    NValue retVal(ValueType::tDOUBLE);\n    // area is in steradians which is a solid angle. Earth in the calculation is treated as sphere\n    // and area of sphere can be calculated as steradians * radius^2\n    retVal.getDouble() = polygon.GetArea() * RADIUS_SQ_M;\n    return retVal;\n}\n\ntemplate<> NValue NValue::call<FUNC_VOLT_DISTANCE_POLYGON_POINT>(const std::vector<NValue>& arguments) {\n    vassert(arguments[0].getValueType() == ValueType::tGEOGRAPHY);\n    vassert(arguments[1].getValueType() == ValueType::tPOINT);\n\n    if (arguments[0].isNull() || arguments[1].isNull()) {\n        return NValue::getNullValue(ValueType::tDOUBLE);\n    }\n\n    Polygon polygon;\n    polygon.initFromGeography(arguments[0].getGeographyValue());\n    GeographyPointValue point = arguments[1].getGeographyPointValue();\n    NValue retVal(ValueType::tDOUBLE);\n    // distance is in radians, so convert it to meters\n    retVal.getDouble() = polygon.getDistance(point) * SPHERICAL_EARTH_MEAN_RADIUS_M;\n    return retVal;\n}\n\ntemplate<> NValue NValue::call<FUNC_VOLT_DISTANCE_POINT_POINT>(const std::vector<NValue>& arguments) {\n    vassert(arguments[0].getValueType() == ValueType::tPOINT);\n    vassert(arguments[1].getValueType() == ValueType::tPOINT);\n\n    if (arguments[0].isNull() || arguments[1].isNull()) {\n        return NValue::getNullValue(ValueType::tDOUBLE);\n    } else {\n        NValue retVal(ValueType::tDOUBLE);\n        retVal.getDouble() = getDistance(arguments[0].getGeographyPointValue(), arguments[1].getGeographyPointValue());\n        return retVal;\n    }\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_ASTEXT_GEOGRAPHY_POINT>() const {\n    vassert(getValueType() == ValueType::tPOINT);\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tVARCHAR);\n    } else {\n        const std::string pointAsText = getGeographyPointValue().toWKT();\n        return getTempStringValue(pointAsText.c_str(), pointAsText.length());\n    }\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_ASTEXT_GEOGRAPHY>() const {\n    vassert(getValueType() == ValueType::tGEOGRAPHY);\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tVARCHAR);\n    } else {\n        const std::string polygonAsText = getGeographyValue().toWKT();\n        return getTempStringValue(polygonAsText.c_str(), polygonAsText.length());\n    }\n}\n\n//\n// Return true if poly has more than one shell, or has shells\n// inside holes.\n//\nstatic bool isMultiPolygon(const Polygon &poly, std::stringstream *msg) {\n    auto nloops = poly.num_loops();\n    int nouters = 0;\n    for (int idx = 0; idx < nloops; idx += 1) {\n        S2Loop *loop = poly.loop(idx);\n        switch (loop->depth()) {\n            case 0:\n                nouters += 1;\n                break;\n            case 1:\n                break;\n            default:\n                if (msg != NULL) {\n                    (*msg) << \"Polygons can only be shells or holes\";\n                } else {\n                    VOLT_TRACE(\"Polygons can only be shells or holes.\");\n                }\n                return true;\n        }\n        if (!loop->IsNormalized(msg)) {\n            return true;\n        }\n    }\n    if (nouters != 1) {\n        if (msg != NULL) {\n            (*msg) << \"Polygons can have only one shell, not \" << nouters;\n        } else {\n            VOLT_TRACE(\"Polygons can have only one shell, not %d.\", nouters);\n        }\n        return true;\n    } else {\n        return false;\n    }\n}\n\n/*\n * This and FUNC_VOLT_POLYGON_INVALID_REASON are suspiciously\n * close to the same thing.  Maybe they could be unified?\n */\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_IS_VALID_POLYGON>() const {\n    vassert(getValueType() == ValueType::tGEOGRAPHY);\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tBOOLEAN);\n    }\n    // Be optimistic.\n    bool returnval = true;\n    // Extract the polygon and check its validity.\n    Polygon poly;\n    poly.initFromGeography(getGeographyValue());\n    if (!poly.IsValid() || isMultiPolygon(poly, NULL)) {\n        returnval = false;\n    }\n    return ValueFactory::getBooleanValue(returnval);\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_POLYGON_INVALID_REASON>() const {\n    vassert(getValueType() == ValueType::tGEOGRAPHY);\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tVARCHAR);\n    }\n    // Extract the polygon and check its validity.\n    std::stringstream msg;\n    Polygon poly;\n    poly.initFromGeography(getGeographyValue());\n    if (poly.IsValid(&msg)) {\n        isMultiPolygon(poly, &msg);\n    }\n    std::string res (msg.str());\n    if (res.size() == 0) {\n        res = std::string(\"Valid Polygon\");\n    }\n    return getTempStringValue(res.c_str(),res.length());\n}\n\ntemplate<> NValue NValue::callUnary<FUNC_VOLT_MAKE_VALID_POLYGON>() const {\n    vassert(getValueType() == ValueType::tGEOGRAPHY);\n    if (isNull()) {\n        return NValue::getNullValue(ValueType::tGEOGRAPHY);\n    }\n    // Extract the polygon and check its validity.\n    std::stringstream msg;\n    Polygon poly;\n    poly.initFromGeography(getGeographyValue(), true);\n    for (int idx = 0; idx < poly.num_loops(); idx += 1) {\n        S2Loop *loop = poly.loop(idx);\n        if ( ! loop->IsNormalized() ) {\n            std::cout << \"Not normalized loop in make_valid_polygon: \" << idx << \"\\n\";\n        }\n    }\n    if ( ! poly.IsValid(&msg)) {\n        std::string res (msg.str());\n        vassert(res.size() > 0);\n        throwInvalidMakeValidPoly(res);\n        // No return from here.\n    }\n    else if ( isMultiPolygon(poly, &msg)) {\n        std::string res (msg.str());\n        vassert(res.size() > 0);\n        throwInvalidMakeValidPoly(res);\n        // No return from here.\n    }\n    // Ok, so the polygon either was valid before or else\n    // we repaired it, and it is not a multi polygon.\n    // So, msg will not be the empty string, and we can package\n    // this polygon up.\n    //\n    vassert(msg.str().size() == 0);\n    int length = poly.serializedLength();\n    NValue nval = ValueFactory::getUninitializedTempGeographyValue(length);\n    char* storage = const_cast<char*>(ValuePeeker::peekObjectValue(nval));\n    SimpleOutputSerializer output(storage, length);\n    poly.saveToBuffer(output);\n    return nval;\n}\n\ntemplate<> NValue NValue::call<FUNC_VOLT_DWITHIN_POLYGON_POINT>(const std::vector<NValue>& arguments) {\n    vassert(arguments[0].getValueType() == ValueType::tGEOGRAPHY);\n    vassert(arguments[1].getValueType() == ValueType::tPOINT);\n    vassert(isNumeric(arguments[2].getValueType()));\n\n    if (arguments[0].isNull() || arguments[1].isNull() || arguments[2].isNull()) {\n        return NValue::getNullValue(ValueType::tBOOLEAN);\n    }\n\n    Polygon polygon;\n    polygon.initFromGeography(arguments[0].getGeographyValue());\n    GeographyPointValue point = arguments[1].getGeographyPointValue();\n    double withinDistanceOf = arguments[2].castAsDoubleAndGetValue();\n    if (withinDistanceOf < 0) {\n        throwInvalidDistanceDWithin(\"Value of DISTANCE argument must be non-negative\");\n    }\n    double polygonToPointDistance = polygon.getDistance(point) * SPHERICAL_EARTH_MEAN_RADIUS_M;\n    return ValueFactory::getBooleanValue(polygonToPointDistance <= withinDistanceOf);\n}\n\ntemplate<> NValue NValue::call<FUNC_VOLT_DWITHIN_POINT_POINT>(const std::vector<NValue>& arguments) {\n    vassert(arguments[0].getValueType() == ValueType::tPOINT);\n    vassert(arguments[1].getValueType() == ValueType::tPOINT);\n    vassert(isNumeric(arguments[2].getValueType()));\n\n    if (arguments[0].isNull() || arguments[1].isNull() || arguments[2].isNull()) {\n        return NValue::getNullValue(ValueType::tBOOLEAN);\n    }\n\n    double withinDistanceOf = arguments[2].castAsDoubleAndGetValue();\n    if (withinDistanceOf < 0) {\n        throwInvalidDistanceDWithin(\"Value of DISTANCE argument must be non-negative\");\n    }\n    double pointToPointDistance = getDistance(arguments[0].getGeographyPointValue(), arguments[1].getGeographyPointValue());\n    return ValueFactory::getBooleanValue(pointToPointDistance <= withinDistanceOf);\n}\n} // end namespace voltdb\n", "meta": {"hexsha": "8ee79ad1f3bf8feb0e5f434aada035511a14ae4d", "size": 23243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/app/voltdb/voltdb_src/src/ee/expressions/geofunctions.cpp", "max_stars_repo_name": "OpenMPDK/SMDK", "max_stars_repo_head_hexsha": "8f19d32d999731242cb1ab116a4cb445d9993b15", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2022-03-16T08:32:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:02:35.000Z", "max_issues_repo_path": "src/app/voltdb/voltdb_src/src/ee/expressions/geofunctions.cpp", "max_issues_repo_name": "H2O0Lee/SMDK", "max_issues_repo_head_hexsha": "eff49bc17a55a83ea968112feb2e2f2ea18c4ff5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-29T02:30:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:40:46.000Z", "max_forks_repo_path": "src/app/voltdb/voltdb_src/src/ee/expressions/geofunctions.cpp", "max_forks_repo_name": "H2O0Lee/SMDK", "max_forks_repo_head_hexsha": "eff49bc17a55a83ea968112feb2e2f2ea18c4ff5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T04:41:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:32:12.000Z", "avg_line_length": 34.7428998505, "max_line_length": 124, "alphanum_fraction": 0.6461300176, "num_tokens": 5759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.01450357758814871, "lm_q1q2_score": 0.006461772179258262}}
{"text": "// Copyright (C) 2007-2018 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: Thejaka Kanewala\n//           Nicholas Edmonds\n//           Douglas Gregor\n//           Andrew Lumsdaine\n\n#ifndef BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_NUMA_HPP\n#define BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_NUMA_HPP\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <am++/counter_coalesced_message_type.hpp>\n#include <am++/detail/thread_support.hpp>\n\n#include <boost/graph/distributed/priority_q_defs.hpp>\n#include <boost/parallel/append_buffer.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/parallel/algorithm.hpp> // for all_reduce\n#include <boost/graph/parallel/thread_support.hpp> // for compare_and_swap\n#include <algorithm> // for std::min, std::max\n#include <boost/format.hpp>\n#include <iostream>\n#include <atomic>\n\nnamespace boost { namespace graph { namespace distributed {\n\ntemplate<typename Graph, \n         typename DistanceMap, \n         typename EdgeWeightMap, \n       \t typename WorkStats,\n\t typename PriorityQueueGenerator = thread_priority_queue_gen,\n         typename MessageGenerator = \n           amplusplus::simple_generator<amplusplus::counter_coalesced_message_type_gen> >\nclass delta_stepping_shortest_paths_numa {\n  typedef delta_stepping_shortest_paths_numa<Graph, DistanceMap, EdgeWeightMap, PriorityQueueGenerator> \n    self_type;\n\n  typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap;\n\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef typename graph_traits<Graph>::degree_size_type Degree;\n  typedef typename property_traits<EdgeWeightMap>::value_type Dist;\n  typedef std::pair<Vertex, Dist> vertex_distance_data;\n\n  // Constructing bucket type ...\n  struct default_comparer {\n    bool operator()(const vertex_distance_data& vd1, const vertex_distance_data& vd2) {\n      return vd1.second > vd2.second;\n    }\n  };\n\n  typedef typename PriorityQueueGenerator::template queue<vertex_distance_data, \n\t\t\t\t\t\t\t  default_comparer>::type Bucket;\n\n  // Bucket is an ordering container\n  //  typedef typename PriorityQueueType Bucket;\n\n  typedef typename std::vector<Bucket*>::size_type BucketIndex;\n\n  struct vertex_distance_handler;\n\n  typedef typename MessageGenerator::template call_result<vertex_distance_data, vertex_distance_handler, \n\t\t\t\t     vertex_distance_owner<OwnerMap, vertex_distance_data>,\n\t\t\t\t     amplusplus::idempotent_combination_t<boost::parallel::minimum<Dist>,\n\t\t\t\t\t\t\t\t\t  Dist> >::type\n    RelaxMessage;\n\n\npublic:\n\n  delta_stepping_shortest_paths_numa(Graph& g,\n\t\t\t\t     DistanceMap distance, \n\t\t\t\t     EdgeWeightMap weight,\n\t\t\t\t     amplusplus::transport &t,\n\t\t\t\t     Dist delta,\n\t\t\t\t     int offs,\n                                     WorkStats& stats,\n\t\t\t\t     int freq,\n\t\t\t\t     MessageGenerator message_gen = \n\t\t\t\t     MessageGenerator(amplusplus::counter_coalesced_message_type_gen(1 << 12)))\n    : dummy_first_member_for_init_order((amplusplus::register_mpi_datatype<vertex_distance_data>(), 0)),\n      g(g), transport(t), distance(distance), weight(weight), delta(delta), \n      core_offset(offs),\n      work_stats(stats),\n      owner(get(vertex_owner, g)), \n      level_sync(false), current_level(0), buckets_processed(0), current_bucket(0),\n      relax_msg(message_gen, transport, vertex_distance_owner<OwnerMap, vertex_distance_data>(owner),\n\t\tamplusplus::idempotent_combination(boost::parallel::minimum<Dist>(), std::numeric_limits<Dist>::max())),\n      flushFrequency(freq)\n  {\n    initialize();\n  }\n\n#ifdef AMPLUSPLUS_PRINT_HIT_RATES\n  typedef std::pair<unsigned long long, unsigned long long> cache_stats;\n  cache_stats\n  get_cache_stats() {\n    cache_stats stats(0, 0);\n    for(size_t i = 0; i < relax_msg.counters.hits.size(); ++i) {\n      stats.first += relax_msg.counters.hits[i];\n      stats.second += relax_msg.counters.tests[i];\n    }\n    return stats;\n  }\n#endif // AMPLUSPLUS_PRINT_HIT_RATES\n\n  void set_source(Vertex s) { source = s; } // for threaded execution\n  void set_level_sync() { level_sync = true; } // force level-synchronized exploration\n  void operator() (int tid) { run(source, tid); }\n\n  void run(Vertex s, int tid = 0);\n\n  void initialize_threaded_buckets(int tid);\n  void allocate_pqs();\n\n  BucketIndex get_num_levels() { return buckets_processed; }\n  time_type get_start_time() { return start_time; }\n\nprotected:\n  void initialize();\n  \n  // Relax the edge (u, v), creating a new best path of distance x.\n  void relax(const vertex_distance_data& vd);\n\n  void find_next_bucket();\n\n  const int dummy_first_member_for_init_order; // Unused\n\n  const Graph& g;\n  amplusplus::transport& transport;\n  DistanceMap distance;\n  EdgeWeightMap weight;\n  Dist delta;\n  int core_offset;\n  WorkStats& work_stats;\n  OwnerMap owner;\n  Vertex source;\n  bool level_sync;\n\n  // Bucket data structure. The ith bucket contains all local vertices\n  // with (tentative) distance in the range [i*delta,\n  // (i+1)*delta). \n  std::vector<shared_ptr<Bucket> > buckets;\n\n  // Bucket to hold vertices deleted at each level\n  shared_ptr<Bucket> deleted_vertices;\n  BucketIndex current_level; // How many buckets have we processed?\n  BucketIndex buckets_processed; // Stats tracking\n  BucketIndex num_buckets;\n\n  // Shared thread state to make sure we're all on the same page\n  BucketIndex current_bucket;\n  shared_ptr<amplusplus::detail::barrier> t_bar;\n  RelaxMessage relax_msg;\n  time_type start_time;\n  int flushFrequency;\n};\n\n#define DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS                                   \\\n      typename Graph, typename DistanceMap, typename EdgeWeightMap, typename WorkStats, typename PriorityQueueGenerator, typename MessageGenerator\n\n#define DELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE                                    \\\n      delta_stepping_shortest_paths_numa<Graph, DistanceMap, EdgeWeightMap, WorkStats, PriorityQueueGenerator, MessageGenerator>\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE::initialize()\n{\n  int nthreads = transport.get_nthreads();\n\n  relax_msg.set_handler(vertex_distance_handler(*this));\n\n  // Setup distance map\n  distance.set_consistency_model(0);\n  set_property_map_role(vertex_distance, distance);\n\n  using boost::parallel::all_reduce;\n  using boost::parallel::maximum;\n  using std::max;\n\n  // Compute the maximum edge weight\n  Dist max_edge_weight = 0;\n\n  BGL_FORALL_VERTICES_T(u, g, Graph) {\n    BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\n      max_edge_weight = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_edge_weight, get(weight, e));\n  }\n\n  all_reduce<Dist, maximum<Dist> > r(transport, maximum<Dist>());\n  max_edge_weight = r(max_edge_weight);\n\n  // If delta wasn't supplied in the ctor initialize it\n  if (delta == 0) {\n\n    // Compute the maximum edge degree\n    Degree max_degree = 0;\n    BGL_FORALL_VERTICES_T(u, g, Graph) {\n      max_degree = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_degree, out_degree(u, g));\n    }\n    // max_degree = all_reduce(process_group(g), max_degree, maximum<Degree>());\n    all_reduce<Degree, maximum<Degree> > r(transport, maximum<Degree>());\n    max_degree = r(max_degree);\n    \n    // Take a guess at delta, based on what works well for random\n    // graphs.\n    delta = max_edge_weight / max_degree;\n    if (delta == 0)\n      delta = 1;\n  }\n\n  //\n  // Initialize buckets data structure\n  //\n\n  // Extra bucket is so we don't try to insert into the bucket we're processing\n  // when the index wraps\n  num_buckets = max_edge_weight / delta;\n  num_buckets += (num_buckets * delta < (BucketIndex)max_edge_weight) ? 2 : 1;\n\n  // + 1 is for deleted_vertices bucket\n  unsigned long capacity_per_bucket = (DEFAULT_HEAP_SIZE / (num_buckets + 1));\n\n  // Declare bucket data structure and index variable\n  buckets.resize(num_buckets);\n  for (BucketIndex i = 0 ; i < buckets.size() ; ++i) {\n    //    shared_ptr<Bucket> p(new Bucket(nthreads));\n    //buckets[i].swap(p);\n    buckets[i].reset(new Bucket(nthreads, capacity_per_bucket));\n  }\n\n  //shared_ptr<Bucket> p(new Bucket(nthreads));\n  //deleted_vertices.swap(p);\n  deleted_vertices.reset(new Bucket(nthreads, capacity_per_bucket));\n\n  // Initialize distance labels\n  BGL_FORALL_VERTICES_T(v, g, Graph) { \n    put(distance, v, (std::numeric_limits<Dist>::max)()); \n  }\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE::allocate_pqs() {\n  for (BucketIndex i = 0 ; i < buckets.size() ; ++i) {\n    buckets[i]->allocate_pqs();\n  }\n\n  deleted_vertices->allocate_pqs();\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE::initialize_threaded_buckets(int tid) {\n  for (BucketIndex i = 0 ; i < buckets.size() ; ++i) {\n    buckets[i]->initialize(tid, false);\n  }\n\n  deleted_vertices->initialize(tid, false);\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE::run(Vertex s, int tid) {\n  /**\n   *  NOTE: We never remove a vertex from a higher bucket when\n   *  placing it in a lower one because thread-safe insertion is\n   *  cheap as long as we don't have to handle removal\n   *  simultaneously, this will result in additional work and higher\n   *  memory consumption, but the alternative is locking which is\n   *  sure to be slow.\n   */\n  int doFlushCounter = 0;\n  int count_epoch = 0 ; \n  AMPLUSPLUS_WITH_THREAD_ID(tid) {\n    int nthreads = transport.get_nthreads();\n\n    if (tid == 0)\n      t_bar.reset(new amplusplus::detail::barrier(nthreads));\n    \n    // This barrier acts as a temporary barrier until we can be sure t_bar is initialized \n    { amplusplus::scoped_epoch epoch(transport); } \n\n    // wait till all threads are pinned\n    t_bar->wait();\n\n    // if two processes are running on the same node, core_offset\n    // is important to achieve thread affinity\n    if (pin(tid+core_offset) != 0) {\n      std::cerr << \"[ERROR] Unable to pin current thread to \"\n\t\t<< \"core : \" << tid << std::endl;\n      assert(false);\n    }\n\n    // wait till all threads are pinned\n    t_bar->wait();\n    { amplusplus::scoped_epoch epoch(transport); }\n\n    validate_thread_core_relation();\n\n#ifdef LIB_CDS\n    // Attach thread to CDS; main thread is already attached\n    if (tid != 0)\n      cds::threading::Manager::attachThread();\n#endif\n\n    // For each thread initialize buckets\n    initialize_threaded_buckets(tid);\n    t_bar->wait(); // wait till all threads initialize buckets\n\n    // if thread id is 0 \n    // go through all the buckets\n    // and allocate priority queues\n    // cos we need to new them in the main thread in cds\n    //if (tid == 0) {\n    //  allocate_pqs();\n    //}\n\n    //t_bar->wait(); // wait till tid=0 allocate priority queues\n    start_time = get_time();\n\n    // Push the source onto the queue\n    { \n      amplusplus::scoped_epoch epoch(transport); \n\n      if (get(owner, s) == transport.rank() && tid == 0)\n        relax(vertex_distance_data(s, 0));\n    }    \n\n    t_bar->wait();\n\n    while(current_bucket != (std::numeric_limits<BucketIndex>::max)()) { // do for all buckets\n\n      //std::cout << transport.rank() \n      //\t<< \" processing bucket \" << current_bucket << std::endl;\n\n      unsigned long all_process_bucket_empty = 1;\n      unsigned long p_bucket_full = 0; \n      count_epoch = 0;\n      // process current bucket\n      while(all_process_bucket_empty != 0) {\n\n\t// wait till all threads reach here\n\t// before checking whether queue is empty we need to make sure\n\t// none of the threads are pushing elements to the queue.\n\t// Therefore make sure all threads reach here before checking whether queue is\n\t// empty\n\tt_bar->wait();\n\n\tif (!buckets[current_bucket]->empty(tid))\n\t  p_bucket_full = 1;\n\telse\n\t  p_bucket_full = 0;\n\n\t//t_bar->wait(); // TODO Not sure whether we really need this\n\n\t{\n\t  //\t  std::cout << \"p_bucket_not_empty : \" << p_bucket_not_empty << std::endl;\n\t  amplusplus::scoped_epoch_value epoch(transport, \n\t\t\t\t\t       p_bucket_full, \n\t\t\t\t\t       all_process_bucket_empty);\n\n \t  //std::cout << transport.rank() \n\t  //    << \" all_process_bucket_empty : \" \n\t  //    << all_process_bucket_empty << std::endl;\n\n\t  vertex_distance_data vd;\n\t  while(buckets[current_bucket]->pop(vd, tid)) { // extract an item from the current bucket\n\t    \n\t    assert(all_process_bucket_empty != 0);\n\t    // process light edges\n#ifdef PRINT_DEBUG\n\t    if (tid == 0)\n\t      std::cerr << transport.rank() << \": processing light edges in bucket \"\n\t\t\t<< current_bucket << std::endl;\n#endif\n\t    Vertex v = vd.first;\n\t    Dist dv = get(distance, v);\n\n\t    // v is updated with a better distance ! we do not need to relax\n\t    if (dv < delta * (Dist)current_level) {\n\t      continue;\n            }\n\n\t    // Add v to set of deleted vertices\n\t    deleted_vertices->put(vd, tid);\n\t      \n\t    // Relax light edges\n\t    BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t      Vertex u = target(e, g);\n\t      Dist we = get(weight, e);\n\t      if (we <= delta) {// light edge\n\t\trelax_msg.send(vertex_distance_data(u, dv + we));\n#ifdef PRINT_DEBUG\n\t\tstd::cerr << \"  Relax \" << get(get(vertex_local, g), v) << \"@\" \n\t\t\t  << get(get(vertex_owner, g), v) << \"->\"\n\t\t\t  << get(get(vertex_local, g), u) << \"@\" \n\t\t\t  << get(get(vertex_owner, g), u) << \"  weight = \"\n\t\t\t  << we << std::endl;\n#endif\n\t      }\n\t    } // end of BGL for\n\n    \t    doFlushCounter++;\n\t    if(doFlushCounter == flushFrequency) {\n\t      doFlushCounter = 0;\n\t      transport.get_scheduler().run_one();\n\t    }\n\t  } // end of while (bucket)\n\t  // TODO need to add if (level_sync) break; code; not sure still valid\n\t} // end of scoped epoch      \n\tcount_epoch += 1;\n      } // all processors should be done with current bucket\n\n      assert(buckets[current_bucket]->empty(tid));\n\n      // If all processes are done with the current bucket:\n      //   1. clear the current bucket\n      //   2. process heavy edges\n      //   3. find the next bucket to work on \n      buckets[current_bucket]->clear(tid);\n      t_bar->wait();\n\t  \n      // Process heavy edges\n      // TODO: If we had a separate transport here we could do single-level termination detection\n      {\n\tamplusplus::scoped_epoch epoch(transport);\n\t    \n\tvertex_distance_data deleted_vd;\n\twhile(deleted_vertices->pop(deleted_vd, tid)) {\n\t  Vertex v = deleted_vd.first;\n\t  Dist dv = get(distance, v);\n\t  BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t    Vertex u = target(e, g);\n\t    Dist we = get(weight, e);\n\t    if (we > delta) // heavy edge\n\t      relax_msg.send(vertex_distance_data(u, dv + we));\n\t  } // end BGL for\n\n\t  doFlushCounter++;\n\t  if(doFlushCounter == flushFrequency) {\n\t    doFlushCounter = 0;\n\t    transport.get_scheduler().run_one();\n\t  }\n\n\t} // end while\n      } // end_epoch does a thread barrier\n\t  \n#ifdef PRINT_DEBUG\n      std::cerr << tid << \"@\" << transport.rank() << \": Current bucket \" << current_bucket\n\t\t<< \" size \" << buckets[current_bucket]->size() << std::endl;\n#endif\n      assert(buckets[current_bucket]->size(tid) == 0);\n\n      deleted_vertices->clear(tid);\n          \n      // find next bucket with work and update current_level \n      BucketIndex old_bucket = current_bucket;\n          \n      t_bar->wait();\n      if (tid == 0) {\n\tfind_next_bucket();\n\n\tif (current_bucket != (std::numeric_limits<BucketIndex>::max)()) {\n\t  current_level += current_bucket - old_bucket;\n\t  ++buckets_processed;\n\t}\n      }\n      t_bar->wait();\n    } // end of while global bucket check \n\n#ifdef LIB_CDS\n    if (tid != 0)\n      cds::threading::Manager::detachThread();\n#endif\n\n  } // end of AMPP THREAD ID\n} //end of run\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE::relax(const vertex_distance_data& vd) {\n  Vertex v = vd.first;\n  Dist d = vd.second;\n  using boost::parallel::val_compare_and_swap;\n\n  int tid = amplusplus::detail::get_thread_id();\n  Dist old_dist = get(distance, v), last_old_dist;\n  while (d < old_dist) {\n    last_old_dist = old_dist;\n    old_dist = val_compare_and_swap(&distance[v], old_dist, d);\n    if (last_old_dist == old_dist) {\n#ifdef PBGL2_PRINT_WORK_STATS\n      if(old_dist < std::numeric_limits<Dist>::max()) { \n\twork_stats.increment_invalidated(tid);\n      } else {\n\twork_stats.increment_useful(tid);\n      }\n#endif\n      // Insert vertex into new bucket, note we don't remove it from any other\n      // buckets it might be in \n      BucketIndex new_index = \n        static_cast<BucketIndex>((d - (current_level * delta)) / delta);\n\n      //\n      // If new_index == 0, relax all light edges and add it to deleted_vertices\n      //\n      if (new_index == 0) { // This vertex is bound for the current bucket \n\tBGL_FORALL_OUTEDGES_T(v, e, g, Graph) {\n\t  Vertex u = target(e, g);\n\t  Dist we = get(weight, e);\n\t  if (we <= delta) // light edge\n\t    relax_msg.send(vertex_distance_data(u, d + we));\n\t}\n\t\n\tdeleted_vertices->put(vd, tid);\n\n        break; // No need to insert into current bucket now\n      }\n\n      new_index = (current_bucket + new_index) % num_buckets;\n      buckets[new_index]->put(vd, tid);\n\n      // new_distance now == get(distance, v) so we exit automatically\n      // but this saves us the conditional test\n      break;\n    }\n  }\n\n#ifdef PBGL2_PRINT_WORK_STATS\n  work_stats.increment_rejected(tid);\n#endif\n\n  return;\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS>\nvoid\nDELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE::find_next_bucket()\n{\n  using boost::parallel::all_reduce;\n  using boost::parallel::minimum;\n\n  BucketIndex old_bucket = current_bucket;\n  BucketIndex max_bucket = (std::numeric_limits<BucketIndex>::max)();\n\n  current_bucket = (current_bucket + 1) % buckets.size();\n  while (current_bucket != old_bucket && buckets[current_bucket]->empty())\n    current_bucket = (current_bucket + 1) % buckets.size();\n  \n  if (current_bucket == old_bucket) \n    current_bucket = max_bucket;\n  \n  // If we wrapped, project index past end of buckets to use min()\n  if (current_bucket < old_bucket) current_bucket += buckets.size();\n  \n  all_reduce<BucketIndex, minimum<BucketIndex> > r(transport, minimum<BucketIndex>());\n  current_bucket = r(current_bucket);\n  \n  // Map index back into range of buckets\n  if (current_bucket != max_bucket) \n    current_bucket %= buckets.size();\n}\n\ntemplate<DELTA_STEPPING_SHORTEST_PATHS_NUMA_PARMS>\nstruct DELTA_STEPPING_SHORTEST_PATHS_NUMA_TYPE::\nvertex_distance_handler {\n  \n  vertex_distance_handler() : self(NULL) {}\n  vertex_distance_handler(delta_stepping_shortest_paths_numa& self) : self(&self) {}\n  \n  void operator() (const vertex_distance_data& data) const {\n\n    self->work_stats.increment_edges(amplusplus::detail::get_thread_id());\n\n    if (data.second < get(self->distance, data.first))\n      self->relax(data);\n#ifdef PBGL2_PRINT_WORK_STATS\n    else\n      self->work_stats.increment_rejected(amplusplus::detail::get_thread_id());\n#endif\n  }\n\nprotected:\n  delta_stepping_shortest_paths_numa* self;\n};\n\n\n} } } // end namespace boost::graph::distributed\n\n#endif // BOOST_GRAPH_DELTA_STEPPING_SHORTEST_PATHS_HPP\n", "meta": {"hexsha": "c02dee31c3936d84fb2abbf1e541422483c44375", "size": 19316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/distributed/delta_stepping_shortest_paths_numa.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": "boost/graph/distributed/delta_stepping_shortest_paths_numa.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": "boost/graph/distributed/delta_stepping_shortest_paths_numa.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": 32.1933333333, "max_line_length": 146, "alphanum_fraction": 0.6899979292, "num_tokens": 4825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850131323717, "lm_q2_score": 0.02635535169899494, "lm_q1q2_score": 0.006459301717256449}}
{"text": "//\n// Created by senbaikang on 14.05.21.\n//\n\n#include <cfloat>\n#include <iostream>\n#include <regex>\n\n#include <dlib/global_optimization.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n\n#include \"process_data.h\"\n#include \"probabilities.h\"\n\nvoid process_data(Config &config)\n{\n  // Build a thread pool.\n  ThreadPool threadPool(config.getThreads());\n\n  // Get pointers to data files.\n  auto filePtrs(std::move(getReadCountsFiles(config)));\n\n  // Object storing output data.\n  Data data;\n\n  // Mutex for data synchronization.\n  std::mutex dataMutex;\n\n  // Read the cellular information.\n  std::vector<u_int32_t> tumorCellPos;\n  std::vector<u_int32_t> normalCellPos;\n  u_int32_t tumorBulkPos;\n  u_int32_t normalBulkPos;\n  readCellInformation(\n      tumorCellPos,\n      normalCellPos,\n      tumorBulkPos,\n      normalBulkPos,\n      config,\n      data\n      );\n\n  // Get the number of tumor cells.\n  const u_int32_t tumorCellNum = tumorCellPos.size();\n  config.setTumorCellNum(tumorCellNum);\n\n  // Get sites to skip.\n  std::set<std::pair<ChromosomeLabel, u_int32_t>> exMap;\n  if (!config.getExcludedSitesFileName().empty())\n    readExclusionList(config.getExcludedSitesFileName(), exMap);\n\n  // Get mutated sites to skip during the error rate estimation.\n  std::set<std::pair<ChromosomeLabel, u_int32_t>> exMuMap;\n  if (!config.getExcludedMutatedSitesFileName().empty())\n    readExclusionList(config.getExcludedMutatedSitesFileName(), exMuMap);\n\n  // Get sites to keep.\n  std::set<std::tuple<ChromosomeLabel, u_int32_t, char, std::vector<char>>> incMap;\n  if (!config.getIncludedSitesFileName().empty())\n    readInclusionVCF(config.getIncludedSitesFileName(), incMap);\n\n  // Estimate effective error rate if necessary using multithreading.\n  if (config.isEstimateErrRate())\n  {\n    // <error, cov>\n    u_int32_t _error = 0;\n    u_int32_t _cov = 0;\n    std::vector<std::future<std::pair<u_int32_t, u_int32_t>>> collection{};\n\n    for (auto &i : filePtrs)\n      collection.emplace_back(\n          threadPool.addTask(\n              estimateSeqErrorRate,\n              std::ref(config),\n              std::ref(i),\n              std::ref(exMap),\n              std::ref(exMuMap),\n              std::ref(tumorCellPos),\n              std::ref(normalCellPos)\n              )\n          );\n\n    for (auto &&i : collection) {\n      const auto &j = i.get();\n\n      _error += std::get<0>(j);\n      _cov += std::get<1>(j);\n    }\n\n    config.setEffectiveSeqErrRate(\n        static_cast<double>(_error) / static_cast<double>(_cov)\n        );\n  }\n\n  // Multithreading.\n  for (auto &i : filePtrs)\n    threadPool.addTask(\n        process_single_file,\n        std::ref(config),\n        std::ref(i),\n        std::ref(tumorCellNum),\n        std::ref(tumorCellPos),\n        std::ref(normalCellPos),\n        std::ref(tumorBulkPos),\n        std::ref(normalBulkPos),\n        std::ref(exMap),\n        std::ref(incMap),\n        std::ref(dataMutex),\n        std::ref(data)\n    );\n\n  std::cout << threadPool.waitUntilFinished() << \" files processed.\" << std::endl;\n\n  // Write to output file.\n  data.createNoiseCounts();\n  data.sortEntries();\n\n  try\n  {\n    writeAltNucInfo(data, config);\n  }\n  catch (const std::exception &e)\n  {\n    std::cerr << e.what() << std::endl;\n  }\n\n  closeReadCountsFile(filePtrs);\n}\n\n/**\n * Get indices of different cells / cell groups.\n *\n * @param config        configuration object\n * @param data          object storing output data\n */\nvoid readCellInformation(\n    std::vector<u_int32_t> &tumorCellPos,\n    std::vector<u_int32_t> &normalCellPos,\n    u_int32_t &tumorBulkPos,\n    u_int32_t &normalBulkPos,\n    const Config &config,\n    Data &data\n    )\n{\n  std::cout << \"> Reading cell names... \";\n\n  readCellNames(config, data);\n\n  tumorBulkPos = UINT_MAX;\n  normalBulkPos = UINT_MAX;\n\n  std::ifstream inputStream(config.getCellNamesFileName());\n\n  std::vector<std::string> splitVec;\n  u_int32_t counter = 0;\n  std::string currLine;\n\n  while(getline(inputStream, currLine))\n  {\n    if (!currLine.empty())\n    {\n      boost::split(splitVec, currLine, boost::is_any_of(\"\\t\"));\n\n      if (splitVec[1] == \"BN\")\n      {\n        if (normalBulkPos != UINT_MAX)\n          std::cout << \"WARNING: Multiple bulk control files provided. Only using the first one!\";\n        else\n          normalBulkPos = counter;\n      }\n\n      // TODO:\n      if (splitVec[1] == \"BT\")\n      {\n      }\n\n      if (splitVec[1] == \"CN\")\n        normalCellPos.emplace_back(counter);\n\n      if (splitVec[1] == \"CT\")\n        tumorCellPos.emplace_back(counter);\n\n      ++counter;\n    }\n  }\n\n  std::cout << \"Done.\" << std::endl;\n}\n\n/**\n * Get names of cancer cells.\n *\n * @param config configuration object\n * @param data   object storing output data\n */\nvoid readCellNames(const Config & config, Data & data)\n{\n  std::ifstream inputStream(config.getCellNamesFileName());\n  std::vector<std::string> splitVec;\n  std::vector<std::string> splitVecEntry;\n\n  std::string currLine;\n\n  while(getline(inputStream, currLine))\n  {\n    if (!currLine.empty())\n    {\n      boost::split(splitVec, currLine, boost::is_any_of(\"\\t\"));\n\n      if (splitVec[1] == \"CT\")\n      {\n        boost::split(splitVecEntry, splitVec[0], boost::is_any_of(\"/\"));\n\n        std::string name = splitVecEntry.back();\n        std::regex suf(config.getCellNameSuffix());\n\n        if (std::regex_search(name, suf))\n          name = std::regex_replace(name, suf, \"\");\n\n        data.addCellName(std::move(name));\n      }\n    }\n  }\n}\n\n/**\n * Get sites which will be excluded.\n */\nvoid readExclusionList(\n    const std::string &v,\n    std::set<std::pair<ChromosomeLabel, u_int32_t>> &_map\n    )\n{\n  std::cout << \"> Reading sites to be excluded... \";\n\n  std::ifstream inputStream(v);\n  if (!inputStream)\n    throw std::runtime_error(\"Error: Could not open \" + v);\n\n  std::string currLine;\n  std::vector<std::string> splitVec;\n\n  while (std::getline(inputStream, currLine))\n  {\n    if (currLine[0] != '#')\n    {\n      boost::split(splitVec, currLine, boost::is_any_of(\"\\t\"));\n\n      _map.emplace(\n          std::make_pair(\n              std::move(ChromosomeLabel(std::move(splitVec[0]))),\n              std::stoi(splitVec[1])\n              )\n          );\n    }\n  }\n\n  std::cout << \"Done. \" << _map.size() << \" sites will be excluded.\" << std::endl;\n}\n\n/**\n * Get sites which will be included.\n */\nvoid readInclusionVCF(\n    const std::string &v,\n    std::set<std::tuple<ChromosomeLabel, u_int32_t, char, std::vector<char>>> &_map\n)\n{\n  std::cout << \"> Reading sites to be included... \";\n\n  std::ifstream inputStream(v);\n  if (!inputStream)\n    throw std::runtime_error(\"Error: Could not open \" + v);\n\n  std::string currLine;\n  std::vector<std::string> splitVec;\n\n  while (std::getline(inputStream, currLine))\n  {\n    if (currLine[0] != '#')\n    {\n      boost::split(splitVec, currLine, boost::is_any_of(\"\\t\"));\n\n      if (splitVec[3].size() != 1)\n        throw std::runtime_error(\"Error: Illegal format of reference nucleotide: \" + splitVec[3]);\n\n      _map.emplace(\n          std::make_tuple(\n              std::move(ChromosomeLabel(std::move(splitVec[0]))),\n              std::stoi(splitVec[1]),\n              splitVec[3][0],\n              std::move(std::vector<char>(splitVec[4].begin(), splitVec[4].end()))\n              )\n          );\n    }\n  }\n\n  std::cout << \"Done. \" << _map.size() << \" sites will be included.\" << std::endl;\n}\n\nstd::vector<std::unique_ptr<ReadCountsFile>> getReadCountsFiles(const Config &config)\n{\n  const std::regex name(GZ_FILE_PATTERN);\n\n  std::vector<std::unique_ptr<ReadCountsFile>> ret;\n\n  for (const std::string &i : config.getInputFileNames())\n  {\n    if (std::regex_match(i, name))\n      ret.emplace_back(std::unique_ptr<ReadCountsFile>(new GZFile(i, config.getReadLength())));\n    else\n      ret.emplace_back(std::unique_ptr<ReadCountsFile>(new MPileupFile(i)));\n  }\n\n  return ret;\n}\n\nvoid closeReadCountsFile(std::vector<std::unique_ptr<ReadCountsFile>> &files)\n{\n  for (auto &i : files)\n    i.reset();\n}\n\n// This function is used to collect the sequencing information of all cells.\nvoid extractSeqInformation(\n    std::vector<std::array<u_int32_t, 5>> &counts,\n    const std::vector<std::string> &splitVec,\n    const std::vector<u_int32_t> &positions\n)\n{\n  // loop over the cells\n  for (size_t i = 0; i < positions.size(); ++i)\n    extractSeqInformation(counts[i], splitVec, positions[i]);\n}\n\n// This functions is used to extract information about\n// sequencing errors. Only if a single cell shows a mutation\n// the error rates will be collected.\nvoid updateSeqErrorStats(\n    u_int32_t &seqErrors,\n    u_int32_t &seqErrorsCombCov,\n    const std::vector<std::array<u_int32_t, 5>> &counts\n    )\n{\n  for (size_t j = 0; j < 4; ++j) // loop over the nucleotides\n    for (const auto & count : counts) // loop over all cells\n      seqErrors += count[j];\n\n  for (const auto & count : counts) // update the coverage\n    seqErrorsCombCov += count[4];\n}\n\nstd::pair<u_int32_t, u_int32_t> estimateSeqErrorRate(\n    const Config &config,\n    std::unique_ptr<ReadCountsFile> &filePtr,\n    const std::set<std::pair<ChromosomeLabel, u_int32_t>> &exMap,\n    const std::set<std::pair<ChromosomeLabel, u_int32_t>> &errExMap,\n    const std::vector<u_int32_t> &tumorCellPos,\n    const std::vector<u_int32_t> &normalCellPos\n    )\n{\n  u_int32_t maxEstLoop = config.getErrRateEstLoops();\n\n  std::string currLine;\n  std::vector<std::string> splitVec;\n  std::vector<std::array<u_int32_t, 5>> tumor_counts(tumorCellPos.size(), {{0,0,0,0,0}});\n  std::vector<std::array<u_int32_t, 5>> normal_counts(normalCellPos.size(), {{0,0,0,0,0}});\n\n  u_int32_t seqErrors = 0;\n  u_int32_t seqErrorsCombCov = 0;\n\n  for (size_t lineNumber = 0; lineNumber < maxEstLoop && filePtr->getLine(currLine); lineNumber++)\n  {\n    if (currLine.empty())\n    {\n      lineNumber--;\n      continue;\n    }\n\n    boost::split(splitVec, currLine, boost::is_any_of(\"\\t\"));\n\n    if (!isRefKnown(splitVec[2]))\n    {\n      lineNumber--;\n      continue;\n    }\n\n    const auto &tmp = std::make_pair(\n        std::move(ChromosomeLabel(splitVec[0])),\n        std::stoi(splitVec[1])\n        );\n    auto itEx = exMap.find(tmp);\n    auto itErrEx = errExMap.find(tmp);\n\n    if (itEx == exMap.end() && itErrEx == errExMap.end())\n    {\n      extractSeqInformation(tumor_counts, splitVec, tumorCellPos);\n      updateSeqErrorStats(seqErrors, seqErrorsCombCov, tumor_counts);\n\n      extractSeqInformation(normal_counts, splitVec, normalCellPos);\n      updateSeqErrorStats(seqErrors, seqErrorsCombCov, normal_counts);\n    }\n    else\n      lineNumber--;\n  }\n\n  // add pseudo counts\n  seqErrors++;\n\n  filePtr->rewind();\n\n  return std::make_pair(seqErrors, seqErrorsCombCov);\n}\n\n// Check if the reference base is known.\nbool isRefKnown(const std::string & n)\n{\n  if (n[0] == 'n' || n[0] == 'N')\n    return false;\n\n  return true;\n}\n\n// This function is used to collect the sequencing information of all cells.\nvoid extractSeqInformation(\n    std::array<u_int32_t, 5> &count,\n    const std::vector<std::string> &splitVec,\n    u_int32_t position\n    )\n{\n  count = {{0,0,0,0,0}}; // (a,c,g,t, coverage)\n  count[4] = std::stoi(splitVec[position * 3 + 3]);\n  extractCellNucCountInformation(count, splitVec[position * 3 + 4]);\n}\n\nvoid extractCellNucCountInformation(\n    std::array<u_int32_t, 5> &counts,\n    const std::string &nucleotides\n    )\n{\n  //counts = {{0, 0, 0, 0, 0}}; // (a,c,g,t, coverage)\n  for (size_t j = 0; j < nucleotides.size(); ++j) // loop over the nucleotides of a cell in the pileup\n  {\n    u_int16_t index = charToIndex(nucleotides[j]);\n    if (index < 4)\n      ++counts[index];\n    else if (index == 9)\n      --counts[4];\n    else if (index == 4)\n      j = skipIndels(nucleotides, j);\n    else if (index == 5)\n      ++j;\n    else if (index == 6)\n      continue;\n  }\n}\n\nu_int16_t charToIndex(char c)\n{\n  switch (std::toupper(c))\n  {\n  case('A'):\n    return 0;\n  case('C'):\n    return 1;\n  case('G'):\n    return 2;\n  case('T'):\n    return 3;\n  case('-'):\n  case('+'):\n    return 4;\n  case('^'):\n    return 5;\n  case('$'):\n    return 6;\n  case('.'):\n  case(','):\n    return 7;\n  case('*'):\n    return 8;\n  }\n\n  if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))\n  {\n    return 9;\n  }\n\n  std::cerr << \"Unknown character \\\"\" << c << \"\\\" in pileup sequence!\" << std::endl;\n  std::exit(EXIT_FAILURE);\n\n  return 10;\n}\n\n// This function is used to skip indels in the pileup.\nu_int32_t skipIndels(\n    const std::string &nucleotides,\n    u_int32_t currentPos\n    )\n{\n  if(nucleotides[currentPos] != '-' && nucleotides[currentPos] != '+')\n    return currentPos;\n\n  u_int32_t numIndels = 0;\n  u_int32_t i = currentPos + 1; // skip the '-' or '+'\n\n  for (; i < nucleotides.size(); ++i)\n  {\n    if (nucleotides[i] >= '0' && nucleotides[i] <= '9')\n    {\n      numIndels *= 10;\n      numIndels += static_cast<int32_t>(nucleotides[i]) - 48;\n    }\n    else\n      break;\n  }\n  return i + (numIndels - 1);\n}\n\nbool passNormalFilter(\n    const std::array<u_int32_t , 5> &normalCounts,\n    const Config &config\n    )\n{\n  if (normalCounts[4] >= config.getMinCovInBulk())\n  {\n    for (size_t i = 0; i < 4; ++i)\n      if (normalCounts[i] >= config.getMaxSupInBulk())\n        return false;\n\n    return true;\n  }\n\n  return false;\n}\n\nbool passNormalCellCoverage(\n    const std::vector<std::array<u_int32_t, 5>> &normalCellCounts,\n    const Config &config\n    )\n{\n  u_int32_t maxCov = 0;\n\n  for (const auto &normalCellCount : normalCellCounts)\n    if (normalCellCount[4] > maxCov)\n      maxCov = normalCellCount[4];\n\n  if(maxCov < config.getMinCovNormalCell())\n    return false;\n\n  return true;\n}\n\nvoid applyCoverageFilterPerCell(\n    std::vector<std::array<u_int32_t , 5>> &counts,\n    const Config &config\n    )\n{\n  for (auto &count : counts)\n    if(count[4] < config.getMinCov())\n      for (size_t j = 0; j < 5; ++j)\n        count[j] = 0;\n}\n\nbool applyFilterAcrossCells(\n    const std::vector<std::array<u_int32_t, 5>> &counts,\n    const Config &config,\n    u_int32_t nucId\n    )\n{\n  u_int32_t numCellsAboveThresh = 0;\n  for (auto &count : counts)\n  {\n    if (passCovFilter(count[4], config.getMinCov()) &&\n        passFreqFilter(count[nucId],count[4], config.getMinFreq()) &&\n        passSuppFilter(count[nucId], config.getMinSup()))\n    {\n      ++numCellsAboveThresh;\n\n      if(numCellsAboveThresh >= config.getMinTumorCellsToPass())\n        return true;\n    }\n  }\n\n  return false;\n}\n\nbool passSuppFilter(\n    u_int32_t altCount,\n    u_int32_t minSupport\n    )\n{\n  if (altCount >= minSupport)\n    return true;\n\n  return false;\n}\n\nbool passFreqFilter(\n    double altCount,\n    double coverage,\n    double minFreq\n    )\n{\n  if (altCount/coverage >= minFreq)\n    return true;\n\n  return false;\n}\n\nbool passCovFilter(\n    u_int32_t coverage,\n    u_int32_t minCov\n    )\n{\n  if (coverage >= minCov)\n    return true;\n\n  return false;\n}\n\nbool passNormalCellFilter(\n    const std::vector<std::array<u_int32_t, 5>> &normalCellCounts,\n    u_int16_t j,\n    const Config &config\n    )\n{\n  u_int32_t numMutated = 0;\n\n  for (const auto &normalCellCount : normalCellCounts)\n  {\n    const auto homoRef = computeRawWildLogScore(config, normalCellCount[j], normalCellCount[4]);\n    const auto heteroMu = computeRawHeteroMutLogScore(config, normalCellCount[j], normalCellCount[4]);\n    const auto homoMu = computeRawHomoMutLogScore(config, normalCellCount[4] - normalCellCount[j], normalCellCount[4]);\n\n    if (homoRef < heteroMu || homoRef < homoMu)\n      ++numMutated;\n  }\n\n  if (numMutated > config.getMaxNormalCellsToMutate())\n    return false;\n\n  return true;\n}\n\ndouble updateLogH1Temp(\n    double logH1Temp,\n    u_int32_t numCells,\n    u_int32_t numMuts,\n    bool tumorCells,\n    double dropOut\n    )\n{\n  if (tumorCells)\n    return logH1Temp + 2 * logNChooseK(numCells, numMuts) - std::log(2*numMuts - 1) - logNChooseK(2*numCells, 2*numMuts);\n\n  return logH1Temp + logNChooseK(numCells, numMuts) + std::log(std::pow(1.0 - dropOut, numMuts)) + std::log(std::pow(dropOut, numCells - numMuts)) - (1.0 - std::pow(dropOut, numCells));\n}\n\nbool mustH0Win(\n    double &logH1Max,\n    double logH1Temp,\n    double logNumCells,\n    double logH0\n    )\n{\n  if (logH1Temp >= logH1Max)\n  {\n    logH1Max = logH1Temp;\n    return false;\n  }\n  else\n  {\n    if (logH1Max + logNumCells < logH0)\n      return true;\n  }\n\n  return false;\n}\n\nbool computeProbCellsAreMutated(\n    const Config &config,\n    std::vector<long double> &logProbs,\n    std::vector<long double> &tempLogProbs,\n    std::vector<double> &logProbTempValues,\n    std::vector<std::array<u_int32_t, 5>> &filteredCounts,\n    std::vector<double> &cellsNotMutated,\n    std::vector<double> &cellsMutated,\n    u_int32_t currentChar,\n    bool tumorCells\n    )\n{\n  u_int32_t numCells = filteredCounts.size();\n  double logNumCells = log(numCells);\n\n  tempLogProbs[0] = 0.0;\n  for (size_t i = 1; i < filteredCounts.size() + 1; ++i)\n  {\n    cellsNotMutated[i - 1] = computeRawWildLogScore(config, filteredCounts[i - 1][currentChar], filteredCounts[i - 1][4]);\n    cellsMutated[i - 1] = logSumExp(computeRawHeteroMutLogScore(config, filteredCounts[i - 1][currentChar], filteredCounts[i - 1][4]), computeRawHomoMutLogScore(config, filteredCounts[i - 1][4] - filteredCounts[i - 1][currentChar], filteredCounts[i - 1][4]));\n//    cellsMutated[i - 1] = computeRawHeteroMutLogScore(config, filteredCounts[i - 1][currentChar], filteredCounts[i - 1][4]);\n    tempLogProbs[i] = tempLogProbs[i - 1] + cellsNotMutated[i - 1];\n  }\n\n  swap(logProbs, tempLogProbs);\n\n  const double prior = tumorCells ? config.getMuRatePrior() : config.getGermlineRatePrior();\n\n  const double logH0 = logProbs.back() + log(1.0 - prior);\n\n  logProbTempValues[0] = logH0;\n\n  // compute the probabilitues of observing 1, 2, 3, ... mutations\n  double logH1Max = -DBL_MAX; // the current best alternative score\n  long double logNOverK = 0;  // helper to efficiently compute nChooseK\n  size_t numMut = 1;          // number of mutations currently computet\n\n  for (; numMut <= numCells; ++numMut)\n  {\n    double logProbAllPrevCellsMutated = logProbs[numMut - 1];\n    double currentCellMutated = cellsMutated[numMut - 1];\n    tempLogProbs[numMut] = logProbAllPrevCellsMutated + currentCellMutated;\n    for (size_t i = numMut + 1; i < filteredCounts.size() + 1; ++i)\n    {\n      double previousCellNotMutated = logProbs[i - 1];\n      currentCellMutated = cellsMutated[i - 1];\n      double previousCellMutated = tempLogProbs[i -1];\n      double currentCellNotMutated = cellsNotMutated[i - 1];\n      tempLogProbs[i] = addLogProb(\n          previousCellNotMutated + currentCellMutated,\n          previousCellMutated + currentCellNotMutated\n          );\n\n    }\n    swap(logProbs, tempLogProbs);\n    logNOverK = logNChooseK(numCells, numMut, logNOverK);\n    double logH1Temp = logProbs.back() + log(prior) - logNOverK;\n    logH1Temp = updateLogH1Temp(logH1Temp, numCells, numMut, tumorCells, config.getAdoRatePrior() / 2.0);\n\n    // check whether the alternative hypothesis can win\n    bool h0Wins = mustH0Win(logH1Max, logH1Temp, logNumCells, logH0);\n    logProbTempValues[numMut] = logH1Temp;\n    if (h0Wins)\n      return true;\n  }\n\n  return false;\n}\n\ndouble sumValuesInLogSpace(\n    std::vector<double>::const_iterator itBegin,\n    std::vector<double>::const_iterator itEnd\n    )\n{\n  auto it = itBegin;\n  double maxLogValue = *it;\n  ++it;\n\n  for (;it != itEnd; ++it)\n    if (maxLogValue < *it)\n      maxLogValue = *it;\n\n  it = itBegin;\n  double h1 = 0;\n\n  for (;it != itEnd; ++it)\n    h1 += exp(*it - maxLogValue);\n\n  return log(h1) + maxLogValue;\n}\n\nchar indexToChar(u_int16_t index)\n{\n  switch (index)\n  {\n  case(0):\n    return 'A';\n  case(1):\n    return 'C';\n  case(2):\n    return 'G';\n  case(3):\n    return 'T';\n  default:\n    return 'N';\n  }\n}\n\nvoid writeAltNucInfo(\n    const Data &data,\n    const Config &config\n) {\n  if (config.getOutputFileName().has_parent_path()) {\n    std::string mkdir =\n        \"mkdir -p \" +\n        static_cast<std::string>(config.getOutputFileName().parent_path());\n    std::system(mkdir.c_str());\n  }\n\n  std::ofstream out;\n  out.open(config.getOutputFileName());\n\n  out << \"=numSamples=\" << \"\\n\";\n  out << config.getTumorCellNum() << \"\\n\";\n\n  out << \"=numCandidateMutatedSites=\" << \"\\n\";\n  out << data.getCandidateMutatedSitesNum() << \"\\n\";\n\n  if (data.getBackgroundSitesNum() % static_cast<u_int64_t>(config.getTumorCellNum()) != 0)\n    std::cerr << \"WARNING! Read counts data of some cells for background sites are missing. Make sure your mpileups are generated correctly.\\n\";\n\n  out << \"=numBackgroundSites=\" << \"\\n\";\n  out << std::fixed;\n  out.precision(0);\n  out << std::floor(data.getBackgroundSitesNum() / static_cast<u_int64_t>(config.getTumorCellNum())) << \"\\n\";\n\n  out << \"=mutations=\" << \"\\n\";\n  for (const auto & i : data.getCandidateMutatedReadCounts()) {\n    // chrom\n    out << std::get<0>(std::get<0>(i)) << \"\\t\";\n\n    // pos\n    out << std::get<1>(std::get<0>(i)) << \"\\t\";\n\n    // ref nuc\n    out << std::get<2>(std::get<0>(i)) << \"\\t\";\n\n    // significant alt nucs\n    if (std::get<3>(std::get<0>(i)).empty())\n      out << \"N\";\n    else\n    {\n      for (size_t j = 0; j < std::get<3>(std::get<0>(i)).size(); j++)\n      {\n        out << std::get<3>(std::get<0>(i))[j];\n\n        if (j < std::get<3>(std::get<0>(i)).size() - 1)\n          out << ',';\n      }\n    }\n\n    // each cell\n    for (size_t j = 0 ; j < config.getTumorCellNum(); j++)\n      out << \"\\t\" << std::get<1>(i)[j];\n\n    out << \"\\n\";\n  }\n\n  out << \"=background=\" << \"\\n\";\n  out << data.getBackgroundSitesReadCounts();\n\n  out.close();\n}\n\nvoid process_single_file(\n    const Config &config,\n    std::unique_ptr<ReadCountsFile> &filePtr,\n    const u_int32_t &tumorCellNum,\n    const std::vector<u_int32_t> &tumorCellPos,\n    const std::vector<u_int32_t> &normalCellPos,\n    const u_int32_t &tumorBulkPos,\n    const u_int32_t &normalBulkPos,\n    const std::set<std::pair<ChromosomeLabel, u_int32_t>> &exMap,\n    const std::set<std::tuple<ChromosomeLabel, u_int32_t, char, std::vector<char>>> &incMap,\n    std::mutex &_mutex,\n    Data &data\n    )\n{\n  const std::thread::id _id(std::this_thread::get_id());\n  std::cout << \"> [\" << _id << \"] Processing \" + filePtr->getFileName() + \"... \" << std::endl;\n\n  TData _data;\n  std::vector<CellReadCounts> cellReadCounts{};\n  cellReadCounts.reserve(tumorCellNum);\n  SignificantAltNucs significantAltNucs{};\n  std::array<u_int16_t, 3> altNucs{};\n  u_int16_t altNucIdx{};\n  ContinuousNoiseCounts continuousNoiseCounts{};\n  bool hasSignificantAltNucs;\n\n  std::array<u_int32_t, 5> normalBulkCounts{};\n\n  // vector to hold the nucleotide information {a,c,g,t,coverage}\n  std::vector<std::array<u_int32_t, 5>> counts(tumorCellNum, {{0,0,0,0,0}});\n\n  // vector to hold the nucleotide information {a,c,g,t,coverage}\n  std::vector<std::array<u_int32_t, 5>> countsNormal(normalCellPos.size(), {{0,0,0,0,0}});\n\n  // vector to hold the filtered nucleotide information {a,c,g,t,coverage}\n  std::vector<std::array<u_int32_t, 5>> filteredCounts(tumorCellNum, {{0,0,0,0,0}});\n\n  // probabilities of observing 0, 1, 2, 3, 4 ... mutations\n  std::vector<long double> logProbsNormal(normalCellPos.size() + 1, 0);\n\n  // helper array for probabilities of observing 0, 1, 2, 3, 4 ... mutations\n  std::vector<long double> tempLogProbsNormal(normalCellPos.size() + 1, 0);\n\n  std::vector<double> logProbTempValuesNormal(normalCellPos.size() + 1);\n\n  // probabilities of observing 0, 1, 2, 3, 4 ... mutations\n  std::vector<long double> logProbs(tumorCellNum + 1, 0);\n\n  std::vector<double> logProbTempValues(tumorCellNum + 1);\n\n  // helper array for probabilities of observing 0, 1, 2, 3, 4 ... mutations\n  std::vector<long double> tempLogProbs(tumorCellNum + 1, 0);\n\n  std::vector<double> cellsNotMutated(tumorCellNum);\n  std::vector<double> cellsNotMutatedNormal(normalCellPos.size());\n  std::vector<double> cellsMutated(tumorCellNum);\n  std::vector<double> cellsMutatedNormal(normalCellPos.size());\n\n  std::string currentLine;\n  std::vector<std::string> splitVec;\n\n  filePtr->setClearCache(true);\n\n  while (filePtr->getLine(currentLine)) {\n    if (currentLine.empty())\n      continue;\n\n    significantAltNucs.resetSigAltNucs();\n    altNucIdx = 0;\n    hasSignificantAltNucs = false;\n    cellReadCounts.clear();\n\n    // split the current line into easily accessible chunks\n    boost::split(splitVec, currentLine, boost::is_any_of(\"\\t\"));\n\n    if (!isRefKnown(splitVec[2]))\n      continue;\n\n    // check if the current pos is to be excluded\n    auto it = exMap.find(\n        std::make_pair(\n            std::move(ChromosomeLabel(splitVec[0])),\n            std::stoi(splitVec[1])\n            )\n        );\n\n    if (it == exMap.end())\n    {\n      if (normalBulkPos != UINT_MAX)\n      {\n        extractSeqInformation(normalBulkCounts, splitVec, normalBulkPos);\n\n        if (!passNormalFilter(normalBulkCounts, config))\n          continue;\n      }\n\n      if (!normalCellPos.empty())\n      {\n        extractSeqInformation(countsNormal, splitVec, normalCellPos);\n        if (!passNormalCellCoverage(countsNormal, config))\n          continue;\n      }\n\n      extractSeqInformation(counts, splitVec, tumorCellPos);\n\n      filteredCounts = counts;\n      applyCoverageFilterPerCell(filteredCounts, config);\n\n      bool positionMutated = false;\n      for (size_t altAlleleIdx = 0; altAlleleIdx < 4; ++altAlleleIdx) {\n        if (altAlleleIdx == charToIndex(splitVec[2][0]))\n          continue;\n\n        altNucs[altNucIdx++] = altAlleleIdx;\n        bool h0Wins = !applyFilterAcrossCells(filteredCounts, config, altAlleleIdx);\n\n        if (!normalCellPos.empty())\n        {\n          // use the normal cell filter\n          if (config.getNormalCellFilterMode() == 1)\n          {\n            if (!passNormalCellFilter(countsNormal, altAlleleIdx, config))\n            {\n              positionMutated = true;\n              h0Wins = true;\n              continue;\n            }\n          }\n          else if (config.getNormalCellFilterMode() == 2)\n          {\n            bool h0WinsNormal = computeProbCellsAreMutated(\n                config,\n                logProbsNormal,\n                tempLogProbsNormal,\n                logProbTempValuesNormal,\n                countsNormal,\n                cellsNotMutatedNormal,\n                cellsMutatedNormal,\n                altAlleleIdx,\n                false\n                );\n\n            if (!h0WinsNormal)\n            {\n              double logH0Normal = sumValuesInLogSpace(\n                  logProbTempValuesNormal.begin(),\n                  logProbTempValuesNormal.begin() +\n                      config.getMaxNormalCellsToMutate() + 1);\n\n              double logH1Normal = sumValuesInLogSpace(\n                  logProbTempValuesNormal.begin() +\n                      config.getMaxNormalCellsToMutate() + 1,\n                  logProbTempValuesNormal.end());\n\n              if (logH0Normal < logH1Normal)\n              {\n                positionMutated = true;\n                h0Wins = true;\n                continue;\n              }\n            }\n          }\n        }\n\n        double logH0 = -DBL_MAX;\n        double logH1 = -DBL_MAX;\n        if (!h0Wins)\n          h0Wins = computeProbCellsAreMutated(\n              config, logProbs, tempLogProbs, logProbTempValues,\n              filteredCounts, cellsNotMutated, cellsMutated, altAlleleIdx,\n              true);\n\n        if (h0Wins)\n        {\n          logH1 = -DBL_MAX;\n          logH0 = DBL_MAX;\n        } else {\n          logH0 =\n              sumValuesInLogSpace(\n                  logProbTempValues.begin(),\n                  logProbTempValues.begin() + config.getMinTumorCellsToCallMu()\n                  );\n          logH1 = sumValuesInLogSpace(\n              logProbTempValues.begin() + config.getMinTumorCellsToCallMu(),\n              logProbTempValues.end()\n              );\n        }\n\n        if (logH1 > logH0 ||\n            incMap.count(\n                std::make_tuple(\n                    std::move(ChromosomeLabel(splitVec[0])),\n                    std::stoi(splitVec[1]), splitVec[2][0],\n                    std::move(std::vector<char>(indexToChar(altAlleleIdx)))\n                    )\n                ) != 0\n            )\n        {\n          positionMutated = true;\n\n          std::vector<std::pair<u_int32_t, u_int32_t>> testCounts;\n          for (size_t cell = 0; cell < counts.size(); ++cell)\n            if (cellsNotMutated[cell] < cellsMutated[cell])\n              testCounts.emplace_back(counts[cell][altAlleleIdx], counts[cell][4]);\n\n          dlib::matrix<double, 0, 1> startingPointMeanOverDis = {0.05, 5.0};\n          dlib::matrix<double, 0, 1> dLibMinMeanOverDis = {0.001, 0.1};\n          dlib::matrix<double, 0, 1> dLibMaxMeanOverDis = {0.999, 10000.0};\n          OptimizeBetaBinMeanOverDis optBetaBinMeanOverDis(testCounts);\n          OptimizeBetaBinMeanOverDisDerivates optBetaBinDerMeanOverDis(\n              testCounts);\n          double resultMeanOverDis = dlib::find_max_box_constrained(\n              dlib::bfgs_search_strategy(), // Use BFGS search algorithm\n              dlib::objective_delta_stop_strategy(\n                  1e-7), // Stop when the change in rosen() is less than 1e-7\n              optBetaBinMeanOverDis, optBetaBinDerMeanOverDis,\n              startingPointMeanOverDis, dLibMinMeanOverDis,\n              dLibMaxMeanOverDis);\n\n          dlib::matrix<double, 0, 1> startingPointOverDis = {2.0};\n          dlib::matrix<double, 0, 1> dLibMinOverDis = {0.1};\n          dlib::matrix<double, 0, 1> dLibMaxOverDis = {10000.0};\n          OptimizeBetaBinOverDis optBetaBinOverDis(\n              testCounts, config.getMeanFreqSite());\n          OptimizeBetaBinOverDisDerivates optBetaBinDerOverDis(\n              testCounts, config.getMeanFreqSite());\n          double resultOverDis = dlib::find_max_box_constrained(\n              dlib::bfgs_search_strategy(), // Use BFGS search algorithm\n              dlib::objective_delta_stop_strategy(\n                  1e-7), // Stop when the change in rosen() is less than 1e-7\n              optBetaBinOverDis, optBetaBinDerOverDis, startingPointOverDis,\n              dLibMinOverDis, dLibMaxOverDis);\n\n          double pValue;\n          if (resultOverDis >\n              resultMeanOverDis) // if true the results are within the optimization limit\n            pValue = 1;\n          else\n          {\n            double testStat = -2 * (resultOverDis - resultMeanOverDis);\n            boost::math::chi_squared mydist(1);\n            pValue = 1 - boost::math::cdf(mydist, testStat);\n          }\n\n          if (pValue > 0.05 ||\n              startingPointMeanOverDis(0) >= config.getMeanFreqSite() ||\n              incMap.count(\n                  std::make_tuple(std::move(ChromosomeLabel(splitVec[0])),\n                                  std::stoi(splitVec[1]), splitVec[2][0],\n                                  std::move(std::vector<char>(\n                                      indexToChar(altAlleleIdx))))) != 0)\n          {\n            hasSignificantAltNucs = true;\n            significantAltNucs.addSigAltNuc(SignificantAltNuc(\n                altAlleleIdx, startingPointMeanOverDis(0), pValue));\n          }\n        }\n      }\n\n      if (!positionMutated)\n        for (size_t cell = 0; cell < tumorCellNum; cell++)\n          continuousNoiseCounts.add(std::array<u_int32_t, 4>{\n              counts[cell][altNucs[0]], counts[cell][altNucs[1]],\n              counts[cell][altNucs[2]], counts[cell][4]});\n\n      // only treat the site as a candidate snv if it contains significant alternative nucleotides\n      if (hasSignificantAltNucs)\n      {\n        // sort significant alternative nucleotides\n        significantAltNucs.getOrderedSigAltNucs();\n\n        // collect read counts for each alternative nucleotide in each cell\n        for (size_t cell = 0; cell < tumorCellNum; cell++)\n        {\n          cellReadCounts.emplace_back(CellReadCounts(\n              AltNucReadCount(altNucs[0], indexToChar(altNucs[0]),\n                              counts[cell][altNucs[0]], significantAltNucs),\n              AltNucReadCount(altNucs[1], indexToChar(altNucs[1]),\n                              counts[cell][altNucs[1]], significantAltNucs),\n              AltNucReadCount(altNucs[2], indexToChar(altNucs[2]),\n                              counts[cell][altNucs[2]], significantAltNucs),\n              counts[cell][4]));\n\n          cellReadCounts[cell].sortAltNucReadCounts();\n        }\n\n        // save the data\n        _data.emplace_back(std::move(TDataEntry(\n            std::move(\n                TPosInfo(std::move(ChromosomeLabel(std::move(splitVec[0]))),\n                         std::stoi(splitVec[1]), splitVec[2][0],\n                         std::move(significantAltNucs.convertAltNucsType(\n                             indexToChar)))),\n            std::move(cellReadCounts))));\n      }\n    }\n  }\n\n  {\n    std::lock_guard<std::mutex> lock(_mutex);\n    data.addReadCounts(std::move(_data));\n    data.addContinuousNoiseCounts(continuousNoiseCounts);\n  }\n\n  std::cout << \"> [\" << _id << \"] Done.\" << std::endl;\n}\n", "meta": {"hexsha": "20d539e96799c31177072554c05e9ab331cd93cf", "size": 33001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/process_data.cpp", "max_stars_repo_name": "senbaikang/DataFilter", "max_stars_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/process_data.cpp", "max_issues_repo_name": "senbaikang/DataFilter", "max_issues_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/process_data.cpp", "max_forks_repo_name": "senbaikang/DataFilter", "max_forks_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.400172117, "max_line_length": 259, "alphanum_fraction": 0.6155571043, "num_tokens": 9245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.020332354121799366, "lm_q1q2_score": 0.006454023239488961}}
{"text": "/** accuracy.cc\n    Jeremy Barnes, 16 December 2014\n    Copyright (c) 2014 mldb.ai inc.  All rights reserved.\n\n    This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n    Implementation of an ACCURACY algorithm for embedding of a dataset.\n*/\n\n#include \"accuracy.h\"\n#include \"mldb/builtin/matrix.h\"\n#include \"mldb/core/mldb_engine.h\"\n#include \"mldb/core/dataset.h\"\n#include \"mldb/core/bound_queries.h\"\n#include \"mldb/sql/sql_expression.h\"\n#include \"mldb/utils/distribution.h\"\n#include <boost/multi_array.hpp>\n#include \"mldb/base/scope.h\"\n#include \"mldb/base/parallel.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/arch/timers.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"mldb/utils/vector_utils.h\"\n#include \"mldb/types/basic_value_descriptions.h\"\n#include \"mldb/plugins/jml/value_descriptions.h\"\n#include \"mldb/plugins/jml/separation_stats.h\"\n#include \"mldb/core/analytics.h\"\n#include \"mldb/types/any_impl.h\"\n#include \"mldb/base/per_thread_accumulator.h\"\n#include \"mldb/types/optional_description.h\"\n#include \"mldb/types/annotated_exception.h\"\n#include \"mldb/builtin/sql_config_validator.h\"\n#include \"mldb/builtin/sql_expression_extractors.h\"\n#include \"mldb/base/parallel_merge_sort.h\"\n#include \"mldb/utils/log.h\"\n#include \"mldb/utils/possibly_dynamic_buffer.h\"\n\n#define NO_DATA_ERR_MSG \"Cannot run classifier.test procedure on empty test set\"\n\nusing namespace std;\n\n\n\nnamespace MLDB {\n\ntypedef std::vector<std::pair<RowPath, std::vector<std::tuple<ColumnPath, CellValue, Date> > > > Rows;\n\nDEFINE_STRUCTURE_DESCRIPTION(AccuracyConfig);\n\n\nAccuracyConfigDescription::\nAccuracyConfigDescription()\n{\n    Optional<PolyConfigT<Dataset> > optionalOutputDataset;\n    optionalOutputDataset.emplace(PolyConfigT<Dataset>().\n                                  withType(AccuracyConfig::defaultOutputDatasetType));\n\n    addField(\"mode\", &AccuracyConfig::mode,\n             \"Model mode: `boolean`, `regression` or `categorical`. \"\n             \"Controls how the label is interpreted and what is the output of the classifier. \"\n             \"This must match what was used during training.\", CM_BOOLEAN);\n    addField(\"testingData\", &AccuracyConfig::testingData,\n             \"SQL query which specifies the scores, labels and optional weights for evaluation. \"\n             \"The query is usually of the form: \"\n             \"`select classifier_function({features: {f1, f2}})[score] as score, x as label from ds`.\\n\\n\"\n             \"The select expression must contain these two columns: \\n\\n\"\n             \"  * `score`: one scalar expression which evaluates to the score a classifier \"\n             \"has assigned to the given row, and \\n\"\n             \"  * `label`: one scalar expression to identify the row's label, and whose type \"\n             \"must match that of the classifier mode. Rows with null labels will be ignored. \\n\"\n             \"     * `boolean` mode: a boolean (0 or 1)\\n\"\n             \"     * `regression` mode: a real number\\n\"\n             \"     * `categorical` mode: any combination of numbers and strings for\\n\\n\"\n             \"The select expression can contain an optional `weight` column. The weight \"\n             \"allows the relative importance of examples to be set. It must \"\n             \"be a real number. If the `weight` is not specified each row will have \"\n             \"a weight of 1. Rows with a null weight will cause a training error. \\n\\n\"\n             \"The query must not contain `GROUP BY` or `HAVING` clauses. \");\n    addField(\"outputDataset\", &AccuracyConfig::outputDataset,\n             \"Output dataset for scored examples. The score for the test \"\n             \"example will be written to this dataset. Examples get grouped when \"\n              \"they have the same score when `mode` is `boolean`. Specifying a \"\n             \"dataset is optional.\", optionalOutputDataset);\n    addField(\"uniqueScoresOnly\", &AccuracyConfig::uniqueScoresOnly,\n              \"If `outputDataset` is set and `mode` is set to `boolean`, setting this parameter \"\n              \"to `true` will output a single row per unique score. This is useful if the \"\n              \"test set is very large and aggregate statistics for each unique score is \"\n              \"sufficient, for instance to generate a ROC curve. This has no effect \"\n              \"for other values of `mode`.\", false);\n    addField(\"recallOverN\", &AccuracyConfig::accuracyOverN,\n              \"Calculate a recall score over the top scoring labels.\"\n              \"Does not apply to boolean or regression modes.\");\n    \n    addParent<ProcedureConfig>();\n\n    onPostValidate = validateQuery(&AccuracyConfig::testingData,\n                                   NoGroupByHaving(),\n                                   PlainColumnSelect(),\n                                   ScoreLabelSelect(),\n                                   MustContainFrom());\n\n}\n\n\n/*****************************************************************************/\n/* ACCURACY PROCEDURE                                                         */\n/*****************************************************************************/\n\nAccuracyProcedure::\nAccuracyProcedure(MldbEngine * owner,\n                 PolyConfig config,\n                 const std::function<bool (const Json::Value &)> & onProgress)\n    : Procedure(owner)\n{\n    this->accuracyConfig = config.params.convert<AccuracyConfig>();\n    if (!accuracyConfig.testingData.stm)\n        throw AnnotatedException(400, \"Classifier testing procedure requires 'testingData' to be set\",\n                                  \"config\", this->accuracyConfig);\n}\n\nAny\nAccuracyProcedure::\ngetStatus() const\n{\n    return Any();\n}\n\nRunOutput\nrunBoolean(AccuracyConfig & runAccuracyConf,\n           BoundSelectQuery & selectQuery,\n           std::shared_ptr<Dataset> output)\n{\n\n    PerThreadAccumulator<ScoredStats> accum;\n    auto logger = MLDB::getMldbLog<AccuracyProcedure>();\n\n    auto processor = [&] (NamedRowValue & row,\n                          const std::vector<ExpressionValue> & scoreLabelWeight)\n        {\n            double score = scoreLabelWeight[0].toDouble();\n            bool label = scoreLabelWeight[1].asBool();\n            double weight = scoreLabelWeight[2].toDouble();\n\n            TRACE_MSG(logger) << \"score=\" << score << \"; label=\" << label << \"; weight=\" << weight;\n\n            accum.get().update(label, score, weight, row.rowName);\n\n            return true;\n        };\n\n    selectQuery.execute({processor,true/*processInParallel*/}, runAccuracyConf.testingData.stm->offset,\n             runAccuracyConf.testingData.stm->limit,\n             nullptr /* progress */);\n\n    // Now merge out stats together\n    ScoredStats stats;\n    bool gotStuff = false;\n\n    accum.forEach([&] (ScoredStats * thrStats)\n                  {\n                      gotStuff = true;\n                      thrStats->sort();\n                      stats.add(*thrStats);\n                  });\n\n    if (!gotStuff) {\n        throw MLDB::Exception(NO_DATA_ERR_MSG);\n    }\n\n    //stats.sort();\n    stats.calculate();\n    if(output) {\n        const Date recordDate = Date::now();\n\n        int prevIncludedPop = 0;\n\n        std::vector<std::pair<RowPath, std::vector<std::tuple<ColumnPath, CellValue, Date> > > > rows;\n\n        auto recordRow = [&] (unsigned i, const BinaryStats & bstats, ScoredStats::ScoredEntry & entry)\n        {\n            std::vector<std::tuple<RowPath, CellValue, Date> > row;\n\n            row.emplace_back(ColumnPath(\"index\"), i, recordDate);\n            row.emplace_back(ColumnPath(\"label\"), entry.label, recordDate);\n            row.emplace_back(ColumnPath(\"score\"), entry.score, recordDate);\n            row.emplace_back(ColumnPath(\"weight\"), entry.weight, recordDate);\n            row.emplace_back(ColumnPath(\"truePositives\"), bstats.truePositives(), recordDate);\n            row.emplace_back(ColumnPath(\"falsePositives\"), bstats.falsePositives(), recordDate);\n            row.emplace_back(ColumnPath(\"trueNegatives\"), bstats.trueNegatives(), recordDate);\n            row.emplace_back(ColumnPath(\"falseNegatives\"), bstats.falseNegatives(), recordDate);\n            row.emplace_back(ColumnPath(\"accuracy\"), bstats.accuracy(), recordDate);\n            row.emplace_back(ColumnPath(\"precision\"), bstats.precision(), recordDate);\n            row.emplace_back(ColumnPath(\"recall\"), bstats.recall(), recordDate);\n            row.emplace_back(ColumnPath(\"truePositiveRate\"), bstats.truePositiveRate(), recordDate);\n            row.emplace_back(ColumnPath(\"falsePositiveRate\"), bstats.falsePositiveRate(), recordDate);\n\n            rows.emplace_back(std::any_cast<RowPath>(entry.key), std::move(row));\n            if (rows.size() > 10000) {\n                output->recordRows(rows);\n                rows.clear();\n            }\n        };\n\n        for (unsigned i = 1, j = 0;  i < stats.stats.size();  ++i) {\n            auto & bstats = stats.stats[i];\n            auto & entry = stats.entries[j];\n\n            // the difference between included population of the current versus\n            // last stats.stats represents the number of exemples included in the stats.\n            // examples get grouped when they have the same score. use the unweighted\n            // scores because we care about the actual number of examples, whatever\n            // what their training weight was\n            unsigned next_j = j + (bstats.includedPopulation(false) - prevIncludedPop);\n            prevIncludedPop = bstats.includedPopulation(false);\n\n            if(runAccuracyConf.uniqueScoresOnly) {\n                j = next_j;\n                ExcAssertEqual(bstats.threshold, entry.score);\n                recordRow(i, bstats, entry);\n            }\n            else {\n                for(; j<next_j; j++) {\n                    entry = stats.entries[j];\n                    ExcAssertEqual(bstats.threshold, entry.score);\n                    recordRow(i, bstats, entry);\n                }\n            }\n        }\n\n        output->recordRows(rows);\n\n        output->commit();\n    }\n\n    DEBUG_MSG(logger) << \"stats are \";\n\n    DEBUG_MSG(logger) << stats.toJson();\n\n    DEBUG_MSG(logger) << stats.atPercentile(0.50).toJson();\n    DEBUG_MSG(logger) << stats.atPercentile(0.20).toJson();\n    DEBUG_MSG(logger) << stats.atPercentile(0.10).toJson();\n    DEBUG_MSG(logger) << stats.atPercentile(0.05).toJson();\n    DEBUG_MSG(logger) << stats.atPercentile(0.01).toJson();\n\n    return Any(stats.toJson());\n}\n\nRunOutput\nrunCategorical(AccuracyConfig & runAccuracyConf,\n               BoundSelectQuery & selectQuery,\n               std::shared_ptr<Dataset> output,\n               const std::vector<size_t>& accuracyOverN)\n{\n    typedef vector<std::tuple<CellValue, CellValue, double>> AccumBucket;\n    typedef vector<std::tuple<CellValue, CellValue, std::vector<CellValue>, std::vector<double>,  double>> AccumBucketWithBestLabels;\n\n    //We use one or the other\n    PerThreadAccumulator<AccumBucket> accum;\n    PerThreadAccumulator<AccumBucketWithBestLabels> accumWithBestLabels;\n\n    PerThreadAccumulator<Rows> rowsAccum;\n    Date recordDate = Date::now();\n    bool computeTopN = accuracyOverN.size() > 0;\n    size_t maxTopN = 1;\n    for (auto& v : accuracyOverN) {\n        maxTopN = std::max(maxTopN, v);\n    }\n\n    auto processor = [&] (NamedRowValue & row,\n                           const std::vector<ExpressionValue> & scoreLabelWeight)\n        {\n            CellValue maxLabel;\n            double maxLabelScore = -INFINITY;\n\n            std::vector<std::tuple<RowPath, CellValue, Date> > outputRow;\n\n            static const ColumnPath score(\"score\");\n\n            PossiblyDynamicBuffer<std::pair<double, CellValue>> bestlabelsCandidates(scoreLabelWeight[0].getAtomCount());            \n            size_t labelCount = 0;\n            auto onAtom = [&] (const Path & columnName,\n                               const Path & prefix,\n                               const CellValue & val,\n                               Date ts)\n                {\n                    auto v = val.toDouble();\n\n                    if (std::isnan(v))\n                        throw MLDB::Exception(MLDB::format(\"Classifier returned a NaN score \",\n                        columnName.toSimpleName().rawString().c_str()));\n\n                    if(v > maxLabelScore) {\n                        maxLabelScore = v;\n                        maxLabel = jsonDecodeStr<CellValue>(columnName.toSimpleName());\n                    }\n\n                    if(output) {\n                        outputRow.emplace_back(score + columnName, v, recordDate);\n                    }\n\n                    if (computeTopN) {\n                        bestlabelsCandidates[labelCount] = std::pair<double, CellValue>(v, jsonDecodeStr<CellValue>(columnName.toSimpleName()));\n                        ++labelCount;\n                    }\n\n                    return true;\n                };\n            scoreLabelWeight[0].forEachAtom(onAtom);\n\n            if (computeTopN) {\n                //We cannot do a partial sort in case there are ties\n                std::sort(bestlabelsCandidates.data(), \n                          bestlabelsCandidates.data() + bestlabelsCandidates.size(), \n                          std::greater<std::pair<double, CellValue>>());\n            }\n\n            size_t numBest = std::min(maxTopN, bestlabelsCandidates.size());\n\n            //check for ties\n            while (numBest > 0 && numBest < bestlabelsCandidates.size()) {\n                if (bestlabelsCandidates[numBest - 1].second != bestlabelsCandidates[numBest].second)\n                    break;\n\n                numBest++;\n            }\n\n            PossiblyDynamicBuffer<CellValue> bestlabels(numBest);\n            PossiblyDynamicBuffer<double> bestscores(numBest);\n            for (size_t i = 0; i < numBest; ++i) {\n                bestlabels[i] = bestlabelsCandidates[i].second;\n                bestscores[i] = bestlabelsCandidates[i].first;\n            }\n\n            CellValue label = scoreLabelWeight[1].getAtom();\n            double weight = scoreLabelWeight[2].toDouble();\n\n            if (computeTopN) {                \n                accumWithBestLabels.get().emplace_back(label, \n                                                       maxLabel, \n                                                       std::vector<CellValue>(bestlabels.data(), bestlabels.data()+numBest), \n                                                       std::vector<double>(bestscores.data(), bestscores.data()+numBest), \n                                                       weight);\n            }\n            else \n                accum.get().emplace_back(label, maxLabel, weight);\n\n            if(output) {\n                outputRow.emplace_back(ColumnPath(\"maxLabel\"), maxLabel, recordDate);\n                outputRow.emplace_back(ColumnPath(\"label\"), label, recordDate);\n                outputRow.emplace_back(ColumnPath(\"weight\"), weight, recordDate);\n\n                rowsAccum.get().emplace_back(row.rowName, std::move(outputRow));\n                if(rowsAccum.get().size() > 1000) {\n                    output->recordRows(rowsAccum.get());\n                    rowsAccum.get().clear();\n                }\n            }\n\n            return true;\n        };\n\n    selectQuery.execute({processor,true/*processInParallel*/},\n            runAccuracyConf.testingData.stm->offset,\n            runAccuracyConf.testingData.stm->limit,\n            nullptr /* progress */);\n\n\n    if(output) {\n        rowsAccum.forEach([&] (Rows * thrRow)\n            {\n                output->recordRows(*thrRow);\n            });\n        output->commit();\n    }\n\n\n    // Create confusion matrix (actual / predicted)\n    std::string recallString = \"recallOverTopN\";\n    map<CellValue, map<CellValue, double>> confusion_matrix;\n    map<CellValue, double> predicted_sums;\n    map<CellValue, double> real_sums;\n    map<std::pair<CellValue, int>, double> predicted_topn_sums;\n    double conf_mat_sum = 0;\n    bool gotStuff = false;\n    if (computeTopN) {\n        accumWithBestLabels.forEach([&] (AccumBucketWithBestLabels * thrBucket)\n        {\n            gotStuff = true;\n            for(auto & elem : *thrBucket) {\n                const CellValue & label = std::get<0>(elem);\n                const CellValue & predicted = std::get<1>(elem);\n                const std::vector<CellValue>& topPredicted = std::get<2>(elem);\n                const std::vector<double>& topPredictedScores = std::get<3>(elem);\n                const double & weight = std::get<4>(elem);\n                confusion_matrix[label][predicted] += weight;\n                real_sums[label] += weight;\n                predicted_sums[predicted] += weight;\n                conf_mat_sum += weight;\n                auto it = std::find(topPredicted.begin(), topPredicted.end(), label);\n                if (it != topPredicted.end()){\n\n                    size_t rank = it - topPredicted.begin();\n                    double score = topPredictedScores[rank];\n                    size_t earliestRank = std::find(topPredictedScores.begin(), topPredictedScores.end(), score) - topPredictedScores.begin();\n                    size_t ties = std::count(topPredictedScores.begin(), topPredictedScores.end(), score);\n                    ExcAssert(ties > 0);\n\n                    for (int i = 0; i < accuracyOverN.size(); ++i) {\n                        auto limit = accuracyOverN[i];\n\n                        if (earliestRank < limit)\n                        {\n                            //do we share last rank?\n                            size_t lastRank = earliestRank + (ties-1);\n                            if (ties > 1 && lastRank >= limit) {\n                                //how many \"last positions\" are there?\n                                size_t numPos = (limit - earliestRank);\n                                ExcAssert(numPos < ties);\n                                double correctedWeight = (weight * numPos) / ties;\n                                predicted_topn_sums[{label, i}] += correctedWeight;\n                            }\n                            else {\n                                predicted_topn_sums[{label, i}] += weight;\n                            }\n                        }                        \n                    }                    \n                }\n            }\n        });\n    }\n    else {\n        accum.forEach([&] (AccumBucket * thrBucket)\n        {\n            gotStuff = true;\n            for(auto & elem : *thrBucket) {\n                const CellValue & label = std::get<0>(elem);\n                const CellValue & predicted = std::get<1>(elem);\n                const double & weight = std::get<2>(elem);\n                confusion_matrix[label][predicted] += weight;\n                real_sums[label] += weight;\n                predicted_sums[predicted] += weight;\n                conf_mat_sum += weight;\n            }\n        });\n    }    \n\n    if (!gotStuff) {\n        throw MLDB::Exception(NO_DATA_ERR_MSG);\n    }\n    // Create per-class statistics\n    Json::Value results;\n    results[\"labelStatistics\"] = Json::Value();\n    if (computeTopN)\n        results[\"recallOverN\"] = jsonEncode(accuracyOverN);\n\n    double total_accuracy = 0;\n    double total_precision = 0;\n    std::vector<double> total_recall_topn(accuracyOverN.size(), 0);\n    double total_recall = 0; // i'll be back!\n    double total_f1 = 0;\n    double total_support = 0;\n\n    int nb_predicted_no_label = 0;\n\n    auto logger = MLDB::getMldbLog<AccuracyProcedure>();\n    results[\"confusionMatrix\"] = Json::Value(Json::arrayValue);\n    for(const auto & actual_it : confusion_matrix) {\n\n        for(const auto & predicted_it : actual_it.second) {\n            Json::Value conf_mat_elem;\n            conf_mat_elem[\"predicted\"] = jsonEncode(predicted_it.first);\n            conf_mat_elem[\"actual\"] = jsonEncode(actual_it.first);\n            conf_mat_elem[\"count\"] = predicted_it.second;\n            results[\"confusionMatrix\"].append(conf_mat_elem);\n        }\n\n        double tp = confusion_matrix[actual_it.first][actual_it.first];\n        double fp = predicted_sums[actual_it.first] - tp;\n        double fn = real_sums[actual_it.first] - tp;\n        double tn = conf_mat_sum - fn - fp - tp;\n\n        DEBUG_MSG(logger) << \"label: \" << actual_it.first;\n        DEBUG_MSG(logger) << \"TP: \" << tp;\n        DEBUG_MSG(logger) << \"FP: \" << fp;\n        DEBUG_MSG(logger) << \"TN: \" << tn;\n        DEBUG_MSG(logger) << \"FN: \" << fn;\n\n        // if our class was (wrongfully) predicted (fp) but was never actually\n        // there (tp + fn == 0), then this is strange\n        if (tp + fn == 0 && fp > 0) {\n            nb_predicted_no_label++;\n            DEBUG_MSG(logger)\n                << \"WARNING!! Label '\" << actual_it.first\n                << \"' was predicted but not in known labels!\";\n        }\n\n        Json::Value class_stats;\n\n        double accuracy = MLDB::xdiv(tp + tn, conf_mat_sum);\n        double precision = MLDB::xdiv(tp, tp + fp);\n        double support = tp + fn;\n        double recall = MLDB::xdiv(tp, support);\n        class_stats[\"accuracy\"] = accuracy;\n        class_stats[\"precision\"] = precision;\n        class_stats[\"recall\"] = recall;\n        class_stats[\"f1Score\"] = 2 * MLDB::xdiv(precision * recall,\n                                        precision + recall);\n        class_stats[\"support\"] = support;\n        for (int i = 0; i < accuracyOverN.size(); ++i) {\n            auto tptopn = predicted_topn_sums[{actual_it.first,i}];\n            total_recall_topn[i] += tptopn;\n            class_stats[recallString][i] = MLDB::xdiv(tptopn, real_sums[actual_it.first]);\n        }\n\n        results[\"labelStatistics\"][actual_it.first.toUtf8String()] = class_stats;\n\n        total_accuracy += accuracy * support;\n        total_precision += precision * support;\n        total_recall += recall * support;\n        total_f1 += class_stats[\"f1Score\"].asDouble() * support;\n        total_support += support;\n    }\n\n    // Create weighted statistics\n    Json::Value weighted_stats;\n    weighted_stats[\"accuracy\"] = total_accuracy / total_support;\n    weighted_stats[\"precision\"] = total_precision / total_support;\n    weighted_stats[\"recall\"] = total_recall / total_support;\n    weighted_stats[\"f1Score\"] = total_f1 / total_support;\n    weighted_stats[\"support\"] = total_support;\n\n    for (int i = 0; i < accuracyOverN.size(); ++i) {\n        weighted_stats[recallString][i] = total_recall_topn[i] / total_support;\n    }\n\n    results[\"weightedStatistics\"] = weighted_stats;\n\n\n    // TODO maybe this should always return an error? The problem is it is not impossible that because\n    // of the way the dataset is split, it is a normal situation. But it can also point to\n    // misalignment in the way columns are named\n    \n    // throw if precision is zero and at least one predicted value wasn't even\n    // in the labels\n    if (weighted_stats[\"precision\"].asDouble() == 0\n        && nb_predicted_no_label > 0) {\n        throw MLDB::Exception(MLDB::format(\"Weighted precision is 0 and %i\"\n                \"labels were predicted but not in true labels! \"\n                \"Are the columns of the predicted labels named properly?\",\n                nb_predicted_no_label));\n    }\n    \n    // cout << results.toStyledString() << endl;\n\n    return Any(results);\n}\n\nRunOutput\nrunMultilabel(AccuracyConfig & runAccuracyConf,\n               BoundSelectQuery & selectQuery,\n               std::shared_ptr<Dataset> output,\n               const std::vector<size_t>& accuracyOverN)\n{\n    //labels, bestlabels, weight\n    typedef vector<std::tuple<std::vector<CellValue>, std::vector<CellValue>, std::vector<double>, double>> AccumBucket;\n    PerThreadAccumulator<AccumBucket> accum;\n\n    PerThreadAccumulator<Rows> rowsAccum;\n    Date recordDate = Date::now();\n\n    auto processor = [&] (NamedRowValue & row,\n                           const std::vector<ExpressionValue> & scoreLabelWeight)\n        {\n            std::vector<CellValue> bestlabels;\n            std::vector<double> bestlabelsScores;\n            std::vector<std::pair<double, CellValue>> bestlabelsCandidates;\n\n            bestlabels.reserve(scoreLabelWeight[0].getAtomCount());\n            bestlabelsScores.reserve(scoreLabelWeight[0].getAtomCount());\n\n            std::vector<std::tuple<RowPath, CellValue, Date> > outputRow;\n\n            static const ColumnPath score(\"score\");\n\n            auto onAtom = [&] (const Path & columnName,\n                               const Path & prefix,\n                               const CellValue & val,\n                               Date ts)\n                {\n                    auto v = val.toDouble();\n\n                    if (std::isnan(v))\n                        throw MLDB::Exception(MLDB::format(\"Classifier returned a NaN score \",\n                        columnName.toSimpleName().rawString().c_str()));\n\n                    CellValue scoreLabel = jsonDecodeStr<CellValue>(columnName.toSimpleName());\n                    bestlabelsCandidates.push_back({v,scoreLabel});\n\n                    if(output) {\n                        outputRow.emplace_back(score + columnName, v, recordDate);\n                    }\n\n                    return true;\n                };\n\n                scoreLabelWeight[0].forEachAtom(onAtom);\n\n                std::sort(bestlabelsCandidates.begin(), \n                          bestlabelsCandidates.end(), \n                          std::greater<std::pair<double, CellValue>>());\n\n            for (const auto& pair : bestlabelsCandidates) {\n                bestlabels.push_back(pair.second);\n                bestlabelsScores.push_back(pair.first);\n            }\n\n            std::vector<CellValue> labels;\n            std::function<bool (const PathElement & columnName,\n                                const ExpressionValue & val)> randomStrategy = [&] (const PathElement & columnName,\n                                                                              const ExpressionValue & val) ->bool\n                {\n                    if (!val.empty()) {\n                        labels.push_back(columnName.toUtf8String());\n                    }\n\n                    return true;\n                };\n\n            scoreLabelWeight[1].forEachColumn(randomStrategy);\n\n            if (labels.size() == 0)\n                return true;\n\n            double weight = scoreLabelWeight[2].toDouble();\n            accum.get().emplace_back(labels, bestlabels, bestlabelsScores, weight);\n\n            if(output) {\n                for (int i = 0; i < labels.size(); ++i) {\n                    outputRow.emplace_back(ColumnPath(\"label\") + ColumnPath(i), labels[i], recordDate);\n                }\n\n                outputRow.emplace_back(ColumnPath(\"weight\"), weight, recordDate);\n\n                rowsAccum.get().emplace_back(row.rowName, std::move(outputRow));\n                if(rowsAccum.get().size() > 1000) {\n                    output->recordRows(rowsAccum.get());\n                    rowsAccum.get().clear();\n                }\n            }\n\n            return true;\n        };\n\n    selectQuery.execute({processor,true/*processInParallel*/},\n            runAccuracyConf.testingData.stm->offset,\n            runAccuracyConf.testingData.stm->limit,\n            nullptr /* progress */);\n\n\n    if(output) {\n        rowsAccum.forEach([&] (Rows * thrRow)\n            {\n                output->recordRows(*thrRow);\n            });\n        output->commit();\n    }\n\n    map<std::pair<CellValue, int>, double> recallsums;\n    map<CellValue, double> labelsums;\n\n    double totalWeight = 0;\n    std::vector<double> totalAccurateWeight(accuracyOverN.size(),0);\n    double totalCoverageError = 0;\n\n    accum.forEach([&] (AccumBucket * thrBucket)\n            {\n               // gotStuff = true;\n                for(auto & elem : *thrBucket) {\n\n                    const std::vector<CellValue> & labels = std::get<0>(elem);\n                    const std::vector<CellValue> & topPredicted = std::get<1>(elem);\n                    const std::vector<double> & topPredictedScores = std::get<2>(elem);\n                    const double & weight = std::get<3>(elem);\n\n                    if (weight == 0)\n                        continue;\n\n                    double maxRank = 0;\n                    double totalExampleWeight = 0;\n\n                    for (auto& label : labels) {\n                        auto labelScoreIt = std::find(topPredicted.begin(), topPredicted.end(), label);\n                        size_t rank = topPredicted.size();\n                        double averageRank = (double)rank;\n                        if ( labelScoreIt != topPredicted.end()) {\n                            rank = labelScoreIt - topPredicted.begin();\n                            double score = topPredictedScores[rank];\n                            size_t earliestRank = std::find(topPredictedScores.begin(), topPredictedScores.end(), score) - topPredictedScores.begin();\n                            size_t ties = std::count(topPredictedScores.begin(), topPredictedScores.end(), score);\n                            ExcAssert(ties > 0);\n                            averageRank = (2.f * earliestRank + (ties - 1)) / 2.0f;\n\n                            for (int i = 0; i < accuracyOverN.size(); ++i) {\n\n                                size_t limit = accuracyOverN[i];\n\n                                if (earliestRank < limit) {\n\n                                    //do we share last rank?\n                                    size_t lastRank = earliestRank + (ties-1);\n                                    if (ties > 1 && lastRank >= limit) {\n\n                                        //how many \"last positions\" are there?\n                                        size_t numPos = (limit - earliestRank);\n                                        ExcAssert(numPos < ties);\n                                        double correctedWeight = (weight * numPos) / ties;\n                                        recallsums[{label, i}] += correctedWeight;\n                                        totalAccurateWeight[i] += correctedWeight;\n                                    }\n                                    else {\n                                        recallsums[{label, i}] += weight;\n                                        totalAccurateWeight[i] += weight;\n                                    }\n                                }\n\n                            }                            \n                        }\n\n                        maxRank = std::max(maxRank, averageRank);\n                        labelsums[label] += weight;\n                        totalWeight += weight;\n                        totalExampleWeight += weight;\n                    }\n\n                    totalCoverageError += (1+maxRank)*totalExampleWeight;\n                }\n            });\n\n    // Create per-class statistics\n    Json::Value results;\n    results[\"labelStatistics\"] = Json::Value();\n    results[\"recallOverN\"] = jsonEncode(accuracyOverN);\n\n    std::string recallString = \"recallOverTopN\";\n\n    for(const auto & actual_it : labelsums) {\n        Json::Value class_stats;\n        for (int i = 0; i < accuracyOverN.size(); ++i) {\n            double recallSum = 0;\n            auto recall_it = recallsums.find({actual_it.first, i});\n            if (recall_it != recallsums.end())\n                recallSum = recall_it->second;\n            \n            class_stats[recallString][i] = recallSum / actual_it.second;            \n        }\n\n        results[\"labelStatistics\"][actual_it.first.toUtf8String()] = class_stats;\n    }\n\n    // Create weighted statistics\n    Json::Value weighted_stats;\n    for (int i = 0; i < accuracyOverN.size(); ++i)\n        weighted_stats[recallString][i] = totalAccurateWeight[i] / totalWeight;\n    weighted_stats[\"coverageError\"] = totalCoverageError / totalWeight;\n    results[\"weightedStatistics\"] = weighted_stats;\n\n    return Any(results);\n}\n\nRunOutput\nrunRegression(AccuracyConfig & runAccuracyConf,\n               BoundSelectQuery & selectQuery,\n               std::shared_ptr<Dataset> output)\n{\n    /* Calculate the r-squared. */\n    struct ThreadStats {\n        ThreadStats() :\n            mse_sum(0), totalWeight(0)\n        {}\n\n        void increment(double v, double l, double w) {\n            if (!std::isfinite(v)) return;\n\n            mse_sum += pow(v-l, 2) * w;\n            absolute_percentage.push_back(abs( (v-l)/l ));\n\n            labelsWeights.emplace_back(l,w);\n            totalWeight += w;\n        }\n\n        static void merge(ThreadStats & t1, ThreadStats & t2)\n        {\n            size_t split = t1.absolute_percentage.size();\n\n            t1.absolute_percentage.insert(t1.absolute_percentage.end(),\n                          std::make_move_iterator(t2.absolute_percentage.begin()),\n                          std::make_move_iterator(t2.absolute_percentage.end()));\n            t2.absolute_percentage.clear();\n\n            std::inplace_merge(t1.absolute_percentage.begin(),\n                               t1.absolute_percentage.begin() + split,\n                               t1.absolute_percentage.end());\n        }\n\n        double mse_sum;\n        double totalWeight;\n        distribution<double> absolute_percentage;\n        vector<pair<double, double>> labelsWeights;\n    };\n\n    PerThreadAccumulator<ThreadStats> accum;\n\n    PerThreadAccumulator<Rows> rowsAccum;\n    Date recordDate = Date::now();\n\n    auto processor = [&] (NamedRowValue & row,\n                          const std::vector<ExpressionValue> & scoreLabelWeight)\n        {\n            double score = scoreLabelWeight[0].toDouble();\n            double label = scoreLabelWeight[1].toDouble();\n            double weight = scoreLabelWeight[2].toDouble();\n\n            accum.get().increment(score, label, weight);\n\n            if(output) {\n                std::vector<std::tuple<RowPath, CellValue, Date> > outputRow;\n\n                outputRow.emplace_back(ColumnPath(\"score\"), score, recordDate);\n                outputRow.emplace_back(ColumnPath(\"label\"), label, recordDate);\n                outputRow.emplace_back(ColumnPath(\"weight\"), weight, recordDate);\n\n                rowsAccum.get().emplace_back(row.rowName, outputRow);\n                if(rowsAccum.get().size() > 1000) {\n                    output->recordRows(rowsAccum.get());\n                    rowsAccum.get().clear();\n                }\n            }\n\n            return true;\n        };\n\n    selectQuery.execute({processor,true/*processInParallel*/},\n             runAccuracyConf.testingData.stm->offset,\n             runAccuracyConf.testingData.stm->limit,\n             nullptr /* progress */);\n\n\n    if(output) {\n        rowsAccum.forEach([&] (Rows * thrRow)\n            {\n                output->recordRows(*thrRow);\n            });\n        output->commit();\n    }\n\n\n    double totalWeight = 0, mse_sum = 0;\n    vector<vector<pair<double,double>> > allThreadLabelsWeights;\n    accum.forEach([&] (ThreadStats * thrStats)\n                  {\n                        totalWeight += thrStats->totalWeight;\n                        mse_sum += thrStats->mse_sum;\n                        allThreadLabelsWeights.emplace_back(std::move(thrStats->labelsWeights));\n                  });\n\n    if(totalWeight == 0) {\n        throw MLDB::Exception(NO_DATA_ERR_MSG);\n    }\n\n    std::mutex mergeAccumsLock;\n\n    double meanOfLabel = 0;\n    auto doThreadMeanLbl = [&] (int threadNum) -> bool\n    {\n        double averageAccum = 0;\n        for(auto & labelWeight : allThreadLabelsWeights[threadNum])\n            averageAccum += labelWeight.first * labelWeight.second / totalWeight;\n\n        std::unique_lock<std::mutex> guard(mergeAccumsLock);\n        meanOfLabel += averageAccum;\n        return true;\n    };\n    parallelMap(0, allThreadLabelsWeights.size(), doThreadMeanLbl);\n\n    double totalSumSquares = 0;\n    auto doThreadSS = [&] (int threadNum) -> bool\n    {\n        double ssAccum = 0;\n        for(auto & labelWeight : allThreadLabelsWeights[threadNum])\n            ssAccum += pow(labelWeight.first - meanOfLabel, 2) * labelWeight.second;\n\n        std::unique_lock<std::mutex> guard(mergeAccumsLock);\n        totalSumSquares += ssAccum;\n        return true;\n    };\n    parallelMap(0, allThreadLabelsWeights.size(), doThreadSS);\n\n\n    // calculate the r2 while catching the edge cases\n    double r_squared;\n    if      (mse_sum == 0)          r_squared = 1;\n    else if (totalSumSquares == 0)  r_squared = 0;\n    else                            r_squared = 1 - (mse_sum / totalSumSquares);\n\n    // prepare absolute_percentage distribution\n    distribution<double> absolute_percentage;\n\n    parallelMergeSortRecursive(accum.threads, 0, accum.threads.size(),\n                               [] (const std::shared_ptr<ThreadStats> & t)\n                               {\n                                   std::sort(t->absolute_percentage.begin(),\n                                             t->absolute_percentage.end());\n                               },\n                               [] (const std::shared_ptr<ThreadStats> & t1,\n                                   const std::shared_ptr<ThreadStats> & t2)\n                               {\n                                   ThreadStats::merge(*t1, *t2);\n                               },\n                               [] (const std::shared_ptr<ThreadStats> & t)\n                               {\n                                   return t->absolute_percentage.size();\n                               },\n                               10000 /* thread threshold */);\n    if (!accum.threads.empty()) {\n        absolute_percentage = std::move(accum.threads[0]->absolute_percentage);\n    }\n\n    // create return object\n    Json::Value results;\n    results[\"r2\"] = r_squared;\n//     results[\"b\"] = b;\n//     results[\"bd\"] = bd;\n    results[\"mse\"] = mse_sum / totalWeight;\n\n    Json::Value quantile_errors;\n    if(absolute_percentage.size() > 0) {\n        size_t size = absolute_percentage.size() - 1;\n        quantile_errors[\"0.25\"] = absolute_percentage[(int)(size*0.25)];\n        quantile_errors[\"0.5\"] = absolute_percentage[(int)(size*0.5)];\n        quantile_errors[\"0.75\"] = absolute_percentage[(int)(size*0.75)];\n        quantile_errors[\"0.9\"] = absolute_percentage[(int)(size*0.9)];\n    }\n    results[\"quantileErrors\"] = quantile_errors;\n\n    return Any(results);\n}\n\nRunOutput\nAccuracyProcedure::\nrun(const ProcedureRunConfig & run,\n    const std::function<bool (const Json::Value &)> & onProgress) const\n{\n    auto runAccuracyConf = applyRunConfOverProcConf(accuracyConfig, run);\n\n    // 1.  Get the input dataset\n    SqlExpressionMldbScope context(engine);\n\n    ConvertProgressToJson convertProgressToJson(onProgress);\n    auto dataset = runAccuracyConf.testingData.stm->from->bind(context, convertProgressToJson).dataset;\n\n    // prepare output dataset\n    std::shared_ptr<Dataset> output;\n    if(runAccuracyConf.outputDataset) {\n        PolyConfigT<Dataset> outputDataset = *runAccuracyConf.outputDataset;\n        if (outputDataset.type.empty())\n            outputDataset.type = AccuracyConfig::defaultOutputDatasetType;\n\n        output = createDataset(engine, outputDataset, nullptr, true /*overwrite*/);\n    }\n\n    // 5.  Run it\n    auto score = extractNamedSubSelect(\"score\", runAccuracyConf.testingData.stm->select)->expression;\n    auto label = extractNamedSubSelect(\"label\", runAccuracyConf.testingData.stm->select)->expression;\n    auto weightSubSelect = extractNamedSubSelect(\"weight\", runAccuracyConf.testingData.stm->select);\n    shared_ptr<SqlExpression> weight = weightSubSelect ? weightSubSelect->expression : SqlExpression::ONE;\n\n    std::vector<std::shared_ptr<SqlExpression> > calc = {\n        score,\n        label,\n        weight\n    };\n\n    auto boundQuery =\n        BoundSelectQuery({} /* select */, *dataset, \"\" /* table alias */,\n                     runAccuracyConf.testingData.stm->when,\n                     *runAccuracyConf.testingData.stm->where,\n                     runAccuracyConf.testingData.stm->orderBy,\n                     calc);\n\n    if(runAccuracyConf.mode == CM_BOOLEAN)\n        return runBoolean(runAccuracyConf, boundQuery, output);\n    if(runAccuracyConf.mode == CM_CATEGORICAL)\n        return runCategorical(runAccuracyConf, boundQuery, output, runAccuracyConf.accuracyOverN);\n    if(runAccuracyConf.mode == CM_REGRESSION)\n        return runRegression(runAccuracyConf, boundQuery, output);\n    if(runAccuracyConf.mode == CM_MULTILABEL)\n        return runMultilabel(runAccuracyConf, boundQuery, output, runAccuracyConf.accuracyOverN);\n\n    throw MLDB::Exception(\"Classification mode '%d' not implemented\", runAccuracyConf.mode);\n}\n\nnamespace {\n\nRegisterProcedureType<AccuracyProcedure, AccuracyConfig>\nregAccuracy(builtinPackage(),\n            \"Calculate the accuracy of a classifier on held-out data\",\n            \"procedures/Accuracy.md.html\");\n\n} // file scope\n\n} // namespace MLDB\n\n", "meta": {"hexsha": "b747f4493e9984a8c8853015b36aafb979098147", "size": 40786, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/accuracy.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/accuracy.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/accuracy.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": 40.2625863771, "max_line_length": 150, "alphanum_fraction": 0.5594076399, "num_tokens": 8543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.01771230226822227, "lm_q1q2_score": 0.006429020282219944}}
{"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/// @author vsevolod vlaskine\n\n#ifdef WIN32\n#include <stdio.h>\n#include <fcntl.h>\n#include <io.h>\n#endif\n\n#include <comma/application/signal_flag.h>\n#include <comma/base/exception.h>\n#include <comma/csv/stream.h>\n#include <comma/csv/impl/program_options.h>\n#include <comma/math/compare.h>\n#include <comma/visiting/traits.h>\n#include <snark/visiting/eigen.h>\n\n// #include <boost/random/mersenne_twister.hpp>\n// #include <boost/random/uniform_real.hpp>\n// #include <boost/random/variate_generator.hpp>\n// #include <Eigen/Geometry>\n// boost::mt19937 generator;\n// boost::uniform_real< double > distribution( 0, 1 );\n// boost::variate_generator< boost::mt19937&, boost::uniform_real< double > > r( generator, distribution );\n\nint main( int argc, char** argv )\n{\n//     for( unsigned int i = 0; i < boost::lexical_cast< unsigned int >( argv[1] ); ++i )\n//     {\n//         double x = r() * 20 - 10;\n//         double y = r() * 20 - 10;\n//         double z = r() * 20 - 10;\n//         std::cout << x << ',' << y << ',' << z << ',' << int( std::max( std::abs( x ), std::max( std::abs( y ), std::abs( z ) ) ) ) << std::endl;\n//     }\n//     return 0;\n\n    try\n    {\n        std::string normal_string;\n        std::string points_string;\n        std::string point_outside;\n        boost::program_options::options_description description( \"options\" );\n        description.add_options()\n            ( \"help,h\", \"display help message\" )\n            ( \"points,p\", boost::program_options::value< std::string >( &points_string )->default_value( \"0,0,0\" ), \"point(s) belonging to the plane, either 3 points, or 1 point, if --normal defined\" )\n            ( \"point-outside\", boost::program_options::value< std::string >( &point_outside ), \"point on the side of the plane where the normal would point, a convenience option; 3 points are enough\" )\n            ( \"normal,n\", boost::program_options::value< std::string >( &normal_string ), \"normal to the plane\" )\n            ( \"intersections\", \"assume the input represents a trajectory, find all its intersections with the plane\")\n            ( \"threshold\", boost::program_options::value< double >(), \"if --intersections present, any separation between contiguous points of trajectory greater than threshold will be treated as a gap in the trajectory (no intersections will lie in the gaps)\");\n        description.add( comma::csv::program_options::description( \"x,y,z\" ) );\n        boost::program_options::variables_map vm;\n        boost::program_options::store( boost::program_options::parse_command_line( argc, argv, description), vm );\n        boost::program_options::notify( vm );\n        if ( vm.count( \"help\" ) )\n        {\n            std::cerr << std::endl;\n            std::cerr << \"take points on stdin, append distance from a given plane\" << std::endl;\n            std::cerr << std::endl;\n            std::cerr << \"if --intersections is specified, assume the input represents a trajectory, find its intersections with the plane,\" << std::endl;\n            std::cerr << \"for each intersection, output adjacent points between which it occurs, the intersection point, and the direction of intersection (-1,0,+1),\" << std::endl;\n            std::cerr << \"where 0 indicates that both adjacent points are in the plane\" << std::endl;\n            std::cerr << std::endl;\n            std::cerr << \"usage: \" << std::endl;\n            std::cerr << \"    cat points.csv | points-slice [options] > points_with_distance.csv\" << std::endl;\n            std::cerr << \"    cat trajectory.csv | points-slice [options] --intersections > intersections.csv\" << std::endl;\n            std::cerr << std::endl;\n            std::cerr << description << std::endl;\n            std::cerr << std::endl;\n            std::cerr << \"defining the plane\" << std::endl;\n            std::cerr << \"    --points x1,y1,z1,x2,y2,z2,x3,y3,x3\" << std::endl;\n            std::cerr << \"    --points x1,y1,z1,x2,y2,z2,x3,y3,x3 --point-outside x4,y4,z4\" << std::endl;\n            std::cerr << \"    --points x,y,z --normal n1,n2,n3\" << std::endl;\n            std::cerr << \"    --normal n1,n2,n3    (the plane passes through 0,0,0)\" << std::endl;\n            std::cerr << std::endl;\n            std::cerr << \"output\" << std::endl;\n            std::cerr << \"    default: \" << std::endl;\n            std::cerr << \"        x,y,z,distance, where distance is signed distance to the plane\" << std::endl;\n            std::cerr << std::endl;\n            std::cerr << \"    if --intersections is specified:\" << std::endl;\n            std::cerr << \"        x1,y1,z1,x2,y2,z2,p1,p2,p3,i, where x1,y1,z1,x2,y2,z2 are the adjacent points, p1,p2,p3 is the intersection, and i is the direction\" << std::endl;\n            std::cerr << std::endl;\n            std::cerr << \"examples:\" << std::endl;\n            std::cerr << \"   echo -e \\\"0,0,-1\\\\n0,0,0\\\\n0,0,1\\\" | points-slice --points 0,0,0,0,1,0,1,0,0\" << std::endl;\n            std::cerr << \"   echo -e \\\"0,0,-1\\\\n0,0,0\\\\n0,0,1\\\" | points-slice --points 0,0,0,0,1,0,1,0,0 --point-outside 0,0,1\" << std::endl;\n            std::cerr << \"   echo -e \\\"0,0,-1\\\\n0,0,0\\\\n0,0,1\\\" | points-slice --points 0,0,0 --normal 0,0,1\" << std::endl;\n            std::cerr << \"   echo -e \\\"0,0,-1\\\\n0,0,0\\\\n0,0,1\\\" | points-slice --normal 0,0,1\" << std::endl;\n            std::cerr << \"   echo -e \\\"0,0,-1\\\\n0,0,0\\\\n0,0,1\\\" | points-slice --normal 0,0,1 --intersections\" << std::endl;\n            std::cerr << \"   echo -e \\\"0,0,-1\\\\n0,0,-0.5\\\\n0,0,0\\\\n0,0,1\\\\n0,0,1.5\\\" | points-slice --normal 0,0,1 --intersections --threshold=0.5\" << std::endl;\n            std::cerr << std::endl;\n            return 1;\n        }\n        if( vm.count( \"points\" ) == 0 ) { std::cerr << \"points-slice: please specify --points\" << std::endl; return 1; }\n        comma::csv::options csv = comma::csv::program_options::get( vm );\n        Eigen::Vector3d normal;\n        Eigen::Vector3d point;\n        if( vm.count( \"normal\" ) )\n        {\n            normal = comma::csv::ascii< Eigen::Vector3d >( \"x,y,z\", ',' ).get( normal_string );\n            point = comma::csv::ascii< Eigen::Vector3d >( \"x,y,z\", ',' ).get( points_string );\n        }\n        else\n        {\n            boost::array< Eigen::Vector3d, 3 > points; // quick and dirty\n            std::vector< std::string > v = comma::split( points_string, ',' );\n            if( v.size() != 9 ) { std::cerr << \"points-slice: expected 3 points, got: \\\"\" << points_string << \"\\\"\" << std::endl; return 1; }\n            point = comma::csv::ascii< Eigen::Vector3d >( \"x,y,z\", ',' ).get( v[0] + ',' + v[1] + ',' + v[2] ); // quick and dirty\n            Eigen::Vector3d a = comma::csv::ascii< Eigen::Vector3d >( \"x,y,z\", ',' ).get( v[3] + ',' + v[4] + ',' + v[5] ); // quick and dirty\n            Eigen::Vector3d b = comma::csv::ascii< Eigen::Vector3d >( \"x,y,z\", ',' ).get( v[6] + ',' + v[7] + ',' + v[8] ); // quick and dirty\n            a -= point;\n            b -= point;\n            if( comma::math::equal( std::abs( a.dot( b ) ), a.norm() * b.norm() ) ) { std::cerr << \"points-slice: given points are not corners or a triangle: \\\"\" << points_string << \"\\\"\" << std::endl; }\n            normal = a.cross( b );\n            if( vm.count( \"point-outside\" ) )\n            {\n                Eigen::Vector3d p = comma::csv::ascii< Eigen::Vector3d >( \"x,y,z\", ',' ).get( point_outside );\n                if( comma::math::equal( ( p - point ).dot( normal ), 0 ) ) { std::cerr << \"points-slice: expected a point outside of the plane, got: \" << point_outside << \", which belongs to the plane\" << std::endl; return 1; }\n                normal *= normal.dot( p - point ) > 0 ? 1 : -1;\n            }\n        }\n        normal.normalize();\n        #ifdef WIN32\n            _setmode( _fileno( stdout ), _O_BINARY ); /// @todo move to a library\n        #endif\n        comma::csv::input_stream< Eigen::Vector3d > istream( std::cin, csv );\n        comma::signal_flag is_shutdown;\n        comma::csv::ascii< Eigen::Vector3d > ascii( \"x,y,z\", csv.delimiter );\n        comma::csv::binary< Eigen::Vector3d > binary( \"3d\", \"x,y,z\" );\n        if( vm.count(\"intersections\") )\n        {\n            Eigen::Hyperplane< double, 3 > plane( normal, point );\n            boost::optional< Eigen::Vector3d > last;\n            double d_last = 0;\n            boost::optional< double > threshold;\n            if( vm.count(\"threshold\") ) { threshold.reset( vm[\"threshold\"].as< double >() ); }\n            while( !is_shutdown && ( istream.ready() || ( !std::cin.eof() && std::cin.good() ) ) )\n            {\n                const Eigen::Vector3d* p = istream.read();\n                if( !p ) { break; }\n                double d = ( *p - point ).dot( normal );\n                bool valid_intersection = false;\n                if( last )\n                {\n                    bool intersects = d * d_last <= 0;\n                    bool interval_within_threshold = !threshold || ( threshold && ( *p - *last ).norm() <= *threshold );\n                    valid_intersection = intersects && interval_within_threshold;\n                }\n                if( valid_intersection )\n                {\n                    Eigen::Vector3d intersection_point;\n                    BOOST_STATIC_ASSERT( sizeof( Eigen::Vector3d ) == sizeof( double ) * 3 );\n                    bool lies_on_plane = ( d == 0 && d_last == 0 );\n                    if( lies_on_plane )\n                    {\n                        intersection_point = *last; \n                    }\n                    else\n                    {\n                        Eigen::ParametrizedLine< double, 3 > line = Eigen::ParametrizedLine< double, 3 >::Through( *last, *p );\n                        intersection_point = line.intersectionPoint( plane );\n                    }\n                    comma::int32 direction;\n                    if( d_last != 0 ) { direction = ( d_last > 0 ) ? 1 : -1; }\n                    else if( d != 0 ) { direction = ( d < 0 ) ? 1 : -1; }\n                    else { direction = 0; }\n                    if( csv.binary() )\n                    {\n                        std::cout.write( reinterpret_cast< const char* >( &( *last ) ), sizeof( double ) * 3 );\n                        std::cout.write( istream.binary().last(), istream.binary().binary().format().size() );\n                        std::cout.write( reinterpret_cast< const char* >( &intersection_point ), sizeof( double ) * 3 );\n                        std::cout.write( reinterpret_cast< const char* >( &direction ), sizeof( comma::int32 ) );\n                    }\n                    else\n                    {\n                        std::cout << ascii.put( *last ) << csv.delimiter << comma::join( istream.ascii().last(), csv.delimiter ) << csv.delimiter\n                                    << ascii.put( intersection_point ) << csv.delimiter << direction << std::endl;\n                    }\n                }\n                last.reset( *p );\n                d_last = d;\n            }\n        }\n        else\n        {\n            while( !is_shutdown && ( istream.ready() || ( !std::cin.eof() && std::cin.good() ) ) )\n            {\n                const Eigen::Vector3d* p = istream.read();\n                if( !p ) { break; }\n                double d = ( *p - point ).dot( normal );\n                if( csv.binary() )\n                {\n                    std::cout.write( istream.binary().last(), istream.binary().binary().format().size() );\n                    std::cout.write( reinterpret_cast< const char* >( &d ), sizeof( double ) );\n                }\n                else\n                {\n                    std::cout << comma::join( istream.ascii().last(), csv.delimiter ) << csv.delimiter << d << std::endl;\n                }\n            }\n        }\n        return 0;\n    }\n    catch( std::exception& ex )\n    {\n        std::cerr << \"points-slice: \" << ex.what() << std::endl;\n    }\n    catch( ... )\n    {\n        std::cerr << \"points-slice: unknown exception\" << std::endl;\n    }\n    return 1;\n}\n", "meta": {"hexsha": "6d529b2507bc5d466a999ac9d13ecc00df7efaeb", "size": 13706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "point_cloud/applications/points-slice.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": "point_cloud/applications/points-slice.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": "point_cloud/applications/points-slice.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": 57.1083333333, "max_line_length": 262, "alphanum_fraction": 0.5456734277, "num_tokens": 3560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455664065234, "lm_q2_score": 0.02128734934862768, "lm_q1q2_score": 0.006402075937146568}}
{"text": "#pragma once\n\n#include <set>\n#include <queue>\n#include <vector>\n#include <string>\n#include <memory>\n#include <random>\n#include <algorithm>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <chrono>\n\n#include \"prx/utilities/defs.hpp\"\n#include \"prx/utilities/data_structures/gnn.hpp\"\n#include \"prx/utilities/data_structures/undirected_graph.hpp\"\n// #include \"prx/utilities/data_structures/tree.hpp\"\n#include \"prx/simulation/playback/trajectory.hpp\"\n#include \"prx/planning/planner_functions/planner_functions.hpp\"\n\n// #define z_obstacle std::complex<double>(std::numeric_limits<double>::max(),std::numeric_limits<double>::max())\n#define MA_DEBUG(i,j,iL,jL,str) if (i == iL && j == jL) std::cout << str << std::endl;\n#define EXPAND_CMP(cmp) cmp.real(), cmp.imag()\n\nnamespace prx\n{\n\ttypedef std::function<void(int,int,space_point_t)> mapping_f;\n\ttypedef std::complex<double> ma_pt;\n\t/**\n\t * Compute the medial axis and vector field for a 2D map\n\t */\n\t// static std::function<bool(std::complex<double>,std::complex<double>)> cmpx_comp = [] (std::complex<double> a, std::complex<double> b)\n\t// \t{\n\t// \t\treturn std::abs(a) < std::abs(b);\n\t// \t};\n\n\tstruct cmpx_comp {\n    \tbool operator()(const std::complex<int> a, const std::complex<int> b) const \n    \t{ \n        \treturn std::abs(a) < std::abs(b);\n    \t}\n\t};\n\tclass ma_map_t;\n\tclass medial_axis_t;\n\n\tclass ma_cell\n\t{\n\tprivate:\n\t\tbool is_edge; \n\t\tbool is_node;\n\t\tedge_index_t edge_id;\n\t\tnode_index_t node_id;\n\t\tdouble dist_to_ma;\n\t\tdouble dist_to_obs;\n\t\tstd::complex<double> close;\n\t\tstd::complex<double> far;\n\t\tstd::complex<double> integrated;\n\t\tstd::complex<double> to_ma;\n\t\tint close_count;\n\t\t// static int next_edge_id;\n\t\t// static int next_node_id;\n\n\tpublic:\n\t\tstatic constexpr std::complex<double> z_obstacle = std::complex<double>(std::numeric_limits<double>::max(),std::numeric_limits<double>::max());\n\t\tma_cell()\n\t\t{\n\t\t\tis_node = false;\n\t\t\tis_edge = false;\n\t\t\tclose = std::complex<double>(0,0);\n\t\t\tfar = std::complex<double>(0,0);\n\t\t\tintegrated = std::complex<double>(0,0);\n\t\t\tto_ma = std::complex<double>(0,0);\n\t\t\tdist_to_obs = std::numeric_limits<double>::infinity();\n\t\t\tdist_to_ma = std::numeric_limits<double>::infinity();\n\t\t\tedge_id = -1;\n\t\t\tnode_id = -1;\n\t\t\tclose_count = 0;\n\t\t};\n\t\t~ma_cell() = default;\n\t\tbool is_obstacle()\n\t\t{\n\t\t\treturn close == z_obstacle || far == z_obstacle || integrated == z_obstacle;\n\t\t}\n\t\tfriend class medial_axis_t;\n\t};\n\n\tclass medial_axis_t\n\t{\n\tprivate:\n\t\t/**\n\t\t * The computation of the vector field has the following flowchart:\n\t\t * \n\t\t * \t\t\t\t\t\t   Construction\n\t\t * \t\t\t\t\t\t\t\t|\n\t\t *         \t\t\t\t\t   init\n\t\t *         \t\t\t\t\t    |\n\t\t *          --------------------+---------------------------\n\t\t *          |\t\t\t\t\t\t\t\t\t\t\t\t|\n\t\t * \t\t set_map\t\t\t\t\t\t\t\tset_close_vf_from_file\n\t\t *   \t\t|\t\t\t\t\t\t\t\t\t\t\t\t|\t\n\t\t *   compute_close_VF \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+------------+----------------------------------+\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 set_goal\t\t\t\t\t\tset_far_vf_from_file\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|\n\t\t *          \t|\t\t\t\t  |\t\t\t\t\t\t\t|\n\t\t * \t\t\tset_sknw \t\tcompute_sknw\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|\n\t\t *    \t\t\t\t\t |\t\t\t\t\t\t\t\t\t|\n\t\t * \t\t\t   \t   prepare_graph\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\t|\n\t\t *                    \t |\t\t\t\t   \t\t\t\t\t|\n\t\t * \t               compute_far_VF\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\t\t\t|\t\n\t\t *           \t\t\t +-----------+----------------------+\n\t\t * \t\t\t\t\t            \t |\n\t\t * \t\t\t\t\t     +-------(Queries)*\n\t\t *           \t\t     |\t\t\t |\n\t\t *                 \t     |\t\t\t |\n\t\t * \t\t\t\t\t     |\t  (Save to files)*\n\t\t *        \t\t\t     |\t\t\t |\n\t\t *               \t     +-----------+\n\t\t * \n\t\t * Queries: integrated_vector_at, close_vector_at, far_vector_at\n\t\t *\n\t\t * Save to files: integrated_vf_to_file, close_vf_to_file, far_vf_to_file, grap_vertices_to_file, gnn_to_file\n\t\t * \n\t\t */\n\t\tenum Stage { instatiated, init_done, map_set, close_ready, goal_set, sknw_set, graph_ready, far_ready};\n\t\tint next_edge_id = 0;\n\t\tint next_node_id = 0;\n\t\tspace_t* state_space;\n\t\t// Eigen::Matrix <std::complex<double>, Eigen::Dynamic, Eigen::Dynamic> close;\n\t\t// Eigen::Matrix <std::complex<double>, Eigen::Dynamic, Eigen::Dynamic> map_close;\n\t\t// Eigen::Matrix <std::complex<double>, Eigen::Dynamic, Eigen::Dynamic> map_far;\n\t\t// ma_map_t* ma_map;\n\t\tundirected_graph_t graph;\n\t\tundirected_graph_t obstacles_graph;\n\t\t// undirected_graph_t graph_obstacles;\n\t\tgraph_nearest_neighbors_t* metric_close;\n\t\tgraph_nearest_neighbors_t* metric_obstacles;\n\t\tstd::vector<double*> state_memory;\n\t\ttrajectory_t* aux_traj;\n\t\tstd::complex<double> v_zero;//(0,0);\n\t\tstd::complex<double> v_not_computed;//(0,0);\n\t\t// std::complex<double> z_obstacle;\n\t\tnode_index_t goal_index;\n\t\tspace_point_t goal;\n\n\t\tStage stage;\n\n\t\t// Auxiliary variables for different functions\n\t\tdouble h,w;\n\t\tspace_point_t pt;\n\t\tspace_point_t pt_cl1, pt_cl2;\n\t\t// space_point_t space_point;\n\t\t// Eigen::Vector2d v1, v2, v3;\n\t\tma_pt v1, v2, v3;\n\n\t\tstd::string map_file_name;\n\n\t\t// Line of Sight clearance\n\t\tdouble los_clearance;\n\n\t\tint height;\n\t\tint width;\n\t\tstd::vector<std::vector<ma_cell>> ma_map;\n\t\tstd::queue<std::pair<int,int>> ma_queue;\n\t\tstd::unordered_map<int, std::pair<int, int>> nodes_edges;\n\n\t\t// key: node_index\n\t\t// value: vector of edges_index\n\t\tstd::unordered_map<int, std::vector<int>> edges_list;\n\n\t\t// std::random_device rd;\n    \t// std::mt19937 rd_mt19937(std::random_device());\n\t\t// ------------\n\t\t// | 7 | 0 | 1 |\n\t\t// | 6 | p | 2 |\n\t\t// | 5 | 4 | 3 |\n\t\t// ------------\n\t\tstd::vector<std::pair<ma_pt,double>> dirs = {\t\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+1,+0), std::abs(std::complex<double>(+1,+0))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+1,+1), std::abs(std::complex<double>(+1,+1))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+0,+1), std::abs(std::complex<double>(+0,+1))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(-1,+1), std::abs(std::complex<double>(-1,+1))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(-1,+0), std::abs(std::complex<double>(-1,+0))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(-1,-1), std::abs(std::complex<double>(-1,-1))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+0,-1), std::abs(std::complex<double>(+0,-1))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+1,-1), std::abs(std::complex<double>(+1,-1)))\n\t\t\t\t\t};\n\t\t\n\t\tstd::vector<std::pair<ma_pt,double>> dir4 = {\t\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+1,+0), std::abs(std::complex<double>(+1,+0))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+0,+1), std::abs(std::complex<double>(+0,+1))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(-1,+0), std::abs(std::complex<double>(-1,+0))),\n\t\t\t\t\t\tstd::pair<ma_pt,double>(std::complex<double>(+0,-1), std::abs(std::complex<double>(+0,-1))),\n\t\t\t\t\t};\n\t\t// std::set<std::complex<int>, cmpx_comp> edges_set;\n\t\t// ma_map related functions\n\t\tvoid init_ma_map()\n\t\t{\n\t\t\tfor (int i = 0; i < height; ++i)\n\t\t\t{\t\n\t\t\t\tstd::vector<ma_cell> row;\n\t\t\t\tfor (int j = 0; j < width; ++j)\n\t\t\t\t{\n\t\t\t\t\trow.push_back(ma_cell());\n\t\t\t\t}\n\t\t\t\tma_map.push_back(row);\n\t\t\t}\n\t\t}\n\n\t\tvoid set_obstacle(int i, int j, bool obst)\n\t\t{\n\t\t\tif (obst)\n\t\t\t{\n\t\t\t\tma_map[i][j].far = ma_cell::z_obstacle;\n\t\t\t\tma_map[i][j].close = ma_cell::z_obstacle;\n\t\t\t\tma_map[i][j].integrated = ma_cell::z_obstacle;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tma_map[i][j].far = v_not_computed;\n\t\t\t\tma_map[i][j].close = v_not_computed;\n\t\t\t\tma_map[i][j].integrated = v_not_computed;\t\n\t\t\t}\n\t\t}\n\n\t\tstd::complex<double>& map_far(int i, int j)\n\t\t{\n\t\t\treturn ma_map[i][j].far;\n\t\t}\n\t\tconst std::complex<double> map_far(int i, int j) const\n\t\t{\n\t\t\treturn ma_map[i][j].far;\n\t\t}\n\n\t\tstd::complex<double>& map_close(int i, int j)\n\t\t{\n\t\t\treturn ma_map[i][j].close;\n\t\t}\n\t\tconst std::complex<double> map_close(int i, int j) const\n\t\t{\n\t\t\treturn ma_map[i][j].close;\n\t\t}\n\t\tstd::complex<double>& to_ma(int i, int j)\n\t\t{\n\t\t\t// printf(\"(%d, %d)\\n\", i, j);\n\t\t\ti = std::max(0, std::min(i, height - 1));\n\t\t\tj = std::max(0, std::min(j, width  - 1));\n\t\t\treturn ma_map[i][j].to_ma;\n\t\t}\n\t\tconst std::complex<double> to_ma(int i, int j) const\n\t\t{\n\t\t\ti = std::max(0, std::min(i, height - 1));\n\t\t\tj = std::max(0, std::min(j, width  - 1));\n\t\t\treturn ma_map[i][j].to_ma;\n\t\t}\n\n\t\tinline int rows(){return height;}\n\t\tinline int cols(){return width;}\n\n\t\tvoid set_as_edge(int i, int j)\n\t\t{\n\t\t\t// if (ma_map[i][j].close == ma_cell::z_obstacle) return;\n\t\t\t// if (ma_map[i][j].is_node) return;\n\t\t\tma_map[i][j].is_edge = true;\n\t\t\t// ma_map[i][j].dist_to_ma = 0;\n\t\t}\n\n\t\tvoid set_as_edge(int i, int j, int edge_id)\n\t\t{\n\t\t\tif (ma_map[i][j].close == ma_cell::z_obstacle) return;\n\t\t\tif (ma_map[i][j].is_node) return;\n\t\t\tma_map[i][j].is_edge = true;\n\t\t\tma_map[i][j].dist_to_ma = 0;\n\t\t\tma_map[i][j].edge_id = edge_id;\n\t\t\tnext_edge_id = std::max(next_edge_id, edge_id+1);\n\t\t\tma_queue.push(std::make_pair(i,j));\n\n\t\t}\n\n\t\tvoid unset_edge(int i, int j)\n\t\t{\n\t\t\tma_map[i][j].is_edge = false;\n\t\t\tma_map[i][j].edge_id = -1;\n\n\t\t}\n\n\t\tdouble get_dist_to_ma(int i, int j)\n\t\t{\n\t\t\treturn ma_map[i][j].dist_to_ma;\n\t\t}\n\n\t\tinline void set_as_node(ma_pt v, int node_id)\n\t\t{\n\t\t\tset_as_node(v.real(), v.imag(), node_id);\n\t\t}\n\t\tinline void set_as_node(int i, int j, int node_id)\n\t\t{\n\t\t\ti = std::max(0, std::min(i, height - 1));\n\t\t\tj = std::max(0, std::min(j, width  - 1));\n\t\t\tma_map[i][j].is_node = true;\n\t\t\tma_map[i][j].dist_to_ma = 0;\n\t\t\tma_map[i][j].node_id = node_id;\n\t\t\tnext_node_id = std::max(next_node_id, node_id+1);\n\t\t\tma_queue.push(std::make_pair(i,j));\n\t\t}\n\t\tinline void set_node_as(int i, int j, bool val)\n\t\t{\n\t\t\tma_map[i][j].is_node = val;\n\t\t}\n\t\t// bool surrounded_by_obstacles(int i, int j);\n\t\t\n\t\tinline bool is_edge(std::complex<double> v)\n\t\t{\n\t\t\treturn is_edge(v.real(), v.imag());\n\t\t}\n\t\tinline bool is_edge(int i, int j)\n\t\t{\n\t\t\tif (i < 0 || i >= rows()) return false;\n\t\t\tif (j < 0 || j >= cols()) return false;\n\t\t\treturn ma_map[i][j].is_edge;\n\t\t}\n\n\t\tint get_edge_id(int i, int j)\n\t\t{\n\t\t\treturn ma_map[i][j].edge_id;\n\t\t}\n\n\t\tbool is_node(ma_pt v)\n\t\t{\n\t\t\tif (v.real() < 0 || v.real() >= rows()) return false;\n\t\t\tif (v.imag() < 0 || v.imag() >= cols()) return false;\n\t\t\t\n\t\t\treturn  ma_map[v.real()][v.imag()].is_node;\n\t\t}\n\t\tbool is_node(int i, int j)\n\t\t{\n\t\t\tif (i < 0 || i >= rows()) return false;\n\t\t\tif (j < 0 || j >= cols()) return false;\n\t\t\treturn ma_map[i][j].is_node;\n\t\t}\n\n\t\tbool is_goal(double i, double j)\n\t\t{\n\t\t\tif (i < 0 || i >= rows()) return false;\n\t\t\tif (j < 0 || j >= cols()) return false;\n\t\t\tauto id1 = ma_map[std::floor(i)][std::floor(j)].node_id;\n\t\t\tauto id2 = ma_map[std::ceil(i)][std::ceil(j)].node_id;\n\t\t\tif (id1 == goal_index || id2 == goal_index) printf(\"GOAL!\\n\");\n\t\t\treturn id1 == goal_index || id2 == goal_index;\t\t\t\n\t\t}\n\n\t\tinline node_index_t get_node_id(int i, int j)\n\t\t{\n\t\t\treturn ma_map[i][j].node_id;\n\t\t}\n\t\tinline edge_index_t get_node_id(ma_pt v)\n\t\t{\n\t\t\treturn get_node_id(v.real(), v.imag());\n\t\t}\n\t\tinline const double dist_to_obstacle(ma_pt v) const\n\t\t{\n\t\t\treturn ma_map[v.real()][v.imag()].dist_to_obs;\n\t\t}\n\t\tinline double& dist_to_obstacle(ma_pt v)\n\t\t{\n\t\t\treturn ma_map[v.real()][v.imag()].dist_to_obs;\n\t\t}\n\t\tinline bool is_obstacle(int i, int j)\n\t\t{\n\t\t\t// Lets say the bounds are obstacles...\n\t\t\t// if (i < 0 || i >= rows()) return true;\n\t\t\t// if (j < 0 || j >= cols()) return true;\n\t\t\treturn \t(i < 0 || i >= rows()) ||\n\t\t\t \t\t(j < 0 || j >= cols()) || \n\t\t\t \t\tma_map[i][j].is_obstacle();\n\t\t}\n\n\t\tinline bool in_bounds(int i, int j)\n\t\t{\n\t\t\treturn 0 <= i && 0 <= j && i <  cols() && j <  rows();\n\t\t}\n\n\t\tvoid compute_distances_to_ma();\n\n\t\t/**\n\t\t * Check if there are no obstacles in a straigh line from init to end\n\t\t * @param  init Point where to start the line segment\n\t\t * @param  end  Point where the line segment ends\n\t\t * @return      True if no obstacles are found, false otherwise\n\t\t */\n\t\t// bool has_direct_line_of_sight(space_point_t init, space_point_t end);\n\t\tbool has_direct_line_of_sight(space_point_t init, space_point_t end, double clearance = 0.0);\n\n\t\tvoid add_goal_to_graph();\n\n\t\t// read a vector field from file. \n\t\t// If close_far == 0 ==> close\n\t\t// If close_far == 1 ==> far\n\t\t// Each line of the file has to be in the form:\n\t\t// i j u v\n\t\t// Where map(i,j) = (u,v).\n\t\tvoid vector_field_from_file(std::string file_name, int close_far);\n\n\t\tvoid add_obstacles_to_graph();\n\n\tpublic:\t\n\t\t// valid_trajectory_t valid_check;\n\t\t//distance function to the medial axis\n\t\tdistance_function_t df_ma; \n\t\t// distance function: pixel to medial axis to goal\n\t\tmedial_axis_t()\n\t\t{\t\n\t\t\t// valid_check = nullptr;\n\t\t\tdf_ma = nullptr;\n\t\t\tgoal = nullptr;\n\t\t\tv_zero = std::complex<double>(0,0);\n\t\t\tv_not_computed = std::complex<double>(std::numeric_limits<double>::min(),std::numeric_limits<double>::min());\n     \t\t\n\n\t\t\tstate_memory = {&h, &w};\n\t\t\tstate_space = new space_t(\"EE\",state_memory,\"HW\");\n\t\t\tstate_space -> set_bounds(\t{-std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()},\n\t\t\t\t\t\t\t\t\t\t{ std::numeric_limits<double>::max(),  std::numeric_limits<double>::max()});\n\n\t\t\taux_traj = new trajectory_t(state_space);\n    \t\tdf_ma = [](const space_point_t& p1, const space_point_t& p2)\n\t\t\t{\n\t\t\t\tdouble cost = 0;\n\t\t\t\tfor (int i = 0; i < p1 -> get_dim(); ++i)\n\t\t\t\t{\n\t\t\t\t\tcost += std::pow(p1 -> at(i) - p2 -> at(i), 2);\n\t\t\t\t}\n\t\t\t\treturn std::sqrt(cost);\n\t\t\t};\n\t\t\t// pt =  state_space -> make_point();\n\t\t\tpt =  state_space -> make_point();\n\t\t\tpt_cl1 =  state_space -> make_point();\n\t\t\tpt_cl2 =  state_space -> make_point();\n\n\t\t\tlos_clearance = 5;\n\t\t\tstage = instatiated;\n\n\t\t};\n\n\t\tvoid init()\n\t\t{\t\n\t\t\tprx_assert(df_ma != nullptr, \"distance_function not set for medial_axis_t!\");\n\t\t\tmetric_close = new graph_nearest_neighbors_t(df_ma);\n\t\t\tmetric_obstacles = new graph_nearest_neighbors_t(df_ma);\n\t\t\tgraph.clear();\n\t\t\tgraph.allocate_memory<undirected_node_t,undirected_edge_t>(1000);\n\t\t\tobstacles_graph.clear();\n\t\t\tobstacles_graph.allocate_memory<undirected_node_t,undirected_edge_t>(1000);\n\t\t\tmetric_close -> clear();\n\t\t\tmetric_obstacles -> clear();\n\t\t\tstage = init_done;\n\t\t}\n\n\t\tvoid set_goal(std::vector<double> _goal)\n\t\t{\n\t\t\tprx_assert(stage >= close_ready, \"Close VF has not been set/computed.\");\n\n\t\t\tgoal = state_space -> make_point();\n\t\t\tstate_space -> copy_point_from_vector(goal, _goal);\n\t\t\t// std::cout << state_space -> print_point(goal, 2) << std::endl;\n\t\t\tstage = goal_set;\n\t\t}\n\n\t\tvoid set_map(const std::string map_file);\n\n\t\tvoid set_sknw(const std::string nodes_file, const std::string sknw_file, const std::string edges_file); // Should get skeletonization within c++\n\n\t\tvoid cost_to_go_to_file(std::string file_name);\n\n\t\tvoid integrated_vf_to_file(std::string file_name);\n\n\t\tvoid close_vf_to_file(std::string file_name, bool normalized = true);\n\n\t\tvoid far_vf_to_file(std::string file_name, bool normalized = true);\n\n\t\tvoid grap_vertices_to_file(std::string file_name);\n\n\t\tvoid gnn_to_file(std::string file_name);\n\n\t\tvoid set_close_vf_from_file(std::string file_name);\n\t\n\t\tvoid set_far_vf_from_file(std::string file_name);\n\n\t\tvoid prepare_graph();\n\n\t\t/**\n\t\t * Compute the close vector at (i, j) \n\t\t * @param i Compute the element of the ith row\n\t\t * @param j Compute the element of the jth column\n\t\t */\n\t\tvoid compute_close_vector(int i, int j);\n\n\t\t/**\n\t\t * Compute the far vector at (i, j) \n\t\t * @param i Compute the element of the ith row\n\t\t * @param j Compute the element of the jth column\n\t\t */\n\t\tvoid compute_far_vector(int i, int j);\n\n\t\t/**\n\t\t * Compute the full close vector field\n\t\t */\n\t\tvoid compute_close_vector_field();\n\n\t\t/**\n\t\t * Compute the full far vector field\n\t\t */\n\t\tvoid compute_far_vector_field();\n\n\t\t/**\n\t\t * Compute both vector fields at the same time. \n\t\t * This method is more efficient than computing \n\t\t * both vector fields by they own.\n\t\t */\n\t\tvoid compute_vector_fields();\n\n\t\tvoid edges_to_file(std::string file_name);\n\n\t\tvoid nodes_to_file(std::string file_name);\n\t\t\n\t\tstd::complex<double> compute_integrated_vector(int i, int j);\n\t\t\n\t\tstd::vector<std::complex<double>> blossom(int i, int j, int n, double max_magnitud = std::numeric_limits<double>::max(), double min_magnitud = 0.0, bool avg_if_obstacle = false);\n\n\t\t/**\n\t\t * Compute the integrated vector at (i,j)\n\t\t * The magnitud m of the output vector is such that: m \\in [min_magnitud, max_magnitud]\n\t\t * The default values are [0, \\inf]\n\t\t * Notice that if 0 < min_magnitud the resulting vector could be in collision.\n\t\t */\n\t\tstd::complex<double> integrated_vector_at(int i, int j, double max_magnitud = std::numeric_limits<double>::max(), double min_magnitud = 0.0, bool avg_if_obstacle = false);\n\n\t\tstd::complex<double> close_vector_at(int i, int j, bool normalized = true);\n\n\t\tstd::complex<double> far_vector_at(int i, int j, bool normalized = true);\n\n\t\tvoid blossom_to_file(std::string file_name);\n\n\t\tvoid compute_sknw_and_save_to_files(std::string nodes_file, std::string edges_file, std::string sknw_file,\n\t\t\t\t\tstd::string py_sknw = lib_path + \"/scripts/medial_axis.py\", std::string py_cmd = \"python3\");\n\n\t\tvoid gradient_vector_at(int i, int j);\n\n\t\t// @Aravind: I had to include this line to get this file to compile.\n\t\ttypedef std::function<void (int,int,space_point_t)> mapping_f;\n\n\t\tvoid set_map(int x_grid, int y_grid, valid_state_t& valid_state, mapping_f f,\n\t\t\tspace_t* state_space, std::string _map_name = lib_path + \"/out/ma_custom.map\");\n\n\t\tvoid find_medial_axis();\n\n\t\tdouble cost_to_go(int i, int j);\n\n\n\n\n\t};\n}\n", "meta": {"hexsha": "fd552aaf3a88e8037d00b39368a56f26a82213b9", "size": 17383, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/prx/utilities/heuristics/medial_axis.hpp", "max_stars_repo_name": "aravindsiv/ML4KP", "max_stars_repo_head_hexsha": "064015a7545e1713cbcad3e79807b5cec0849f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-05-31T11:28:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T13:49:30.000Z", "max_issues_repo_path": "src/prx/utilities/heuristics/medial_axis.hpp", "max_issues_repo_name": "aravindsiv/ML4KP", "max_issues_repo_head_hexsha": "064015a7545e1713cbcad3e79807b5cec0849f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T09:39:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-10T22:17:56.000Z", "max_forks_repo_path": "src/prx/utilities/heuristics/medial_axis.hpp", "max_forks_repo_name": "aravindsiv/ML4KP", "max_forks_repo_head_hexsha": "064015a7545e1713cbcad3e79807b5cec0849f54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-03T09:17:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T15:52:58.000Z", "avg_line_length": 30.3368237347, "max_line_length": 180, "alphanum_fraction": 0.6139331531, "num_tokens": 5300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.01542455377907998, "lm_q1q2_score": 0.006399629559870473}}
{"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\n#include <votca/xtp/qmmachine.h>\n#include <sys/stat.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <votca/xtp/elements.h>\n#include <votca/tools/linalg.h>\n#include <votca/xtp/espfit.h>\n\n\nusing boost::format;\n\nnamespace votca {\n    namespace xtp {\n\n        template<class QMPackage>\n        QMMachine<QMPackage>::QMMachine(ctp::XJob *job, ctp::XInductor *xind, QMPackage *qmpack,\n                Property *opt, string sfx, int nst, bool mav)\n        : _job(job), _xind(xind), _qmpack(qmpack), _subthreads(nst),\n        _isConverged(false) {\n\n            string key = sfx + \".qmmmconvg\";\n\n            _crit_dR = opt->ifExistsReturnElseReturnDefault<double>(key + \".dR\", 0.01); //nm\n            _crit_dQ = opt->ifExistsReturnElseReturnDefault<double>(key + \".dQ\", 0.01); //e\n            _crit_dE_QM = opt->ifExistsReturnElseReturnDefault<double>(key + \".dQdE_QM\", 0.001); //eV\n            _crit_dE_MM = opt->ifExistsReturnElseReturnDefault<double>(key + \".dE_MM\", _crit_dE_QM); //eV\n            _maxIter = opt->ifExistsReturnElseReturnDefault<int>(key + \".max_iter\", 32);\n\n\n            key = sfx;\n            bool split_dpl = opt->ifExistsReturnElseReturnDefault<bool>(key + \".split_dpl\", true);\n            double dpl_spacing = opt->ifExistsReturnElseReturnDefault<double>(key + \".dpl_spacing\", 1e-3);\n            qminterface.setMultipoleSplitting(split_dpl, dpl_spacing);\n\n            // check for archiving\n            std::string _archiving_string = opt->ifExistsReturnElseReturnDefault<std::string>(key + \".archiving\", \"\");\n            if (_archiving_string.find(\"iterations\") != std::string::npos) {\n                _do_archive = true;\n            } else {\n                _do_archive = false;\n            }\n\n            // check for static or polarized qmmm\n            key = sfx + \".tholemodel\";\n            _static_qmmm = true;\n            if (opt->exists(key + \".induce\")) {\n                int induce = opt->get(key + \".induce\").as< int >();\n                _static_qmmm = (induce == 1) ? false : true;\n            }\n\n\n            // GDMA options\n            key = sfx + \".gdma\";\n            if (opt->exists(key)) {\n                _do_gdma = true;\n                string _gdma_xml = opt->get(key).as<string> ();\n                //cout << endl << \"... ... Parsing \" << _package_xml << endl ;\n                load_property_from_xml(_gdma_options, _gdma_xml.c_str());\n            } else {\n                _do_gdma = false;\n            }\n\n\n            // GWBSE options\n            key = sfx + \".gwbse\";\n            if (opt->exists(key)) {\n                _do_gwbse = true;\n\n            // PUT IN some useful type definitions for excited state\n            // - singlet -> singlet exciton\n            // - triplet -> triplet exciton\n            // - quasiparticle -> GW quasiparticle (diagqp)\n            // - kohn-sham -> DFT MO\n        \n                string _gwbse_xml = opt->get(key + \".gwbse_options\").as<string> ();\n                //cout << endl << \"... ... Parsing \" << _package_xml << endl ;\n                load_property_from_xml(_gwbse_options, _gwbse_xml.c_str());\n                _state = opt->get(key + \".state\").as< int >();\n                _type = opt->get(key + \".type\").as< string >();\n                if (_type != \"singlet\" && _type != \"triplet\" && _type != \"quasiparticle\") {\n                    throw runtime_error(\" Invalid excited state type! \" + _type);\n                }\n\n                key = sfx + \".gwbse.filter\";\n                if (opt->exists(key + \".oscillator_strength\") && _type != \"triplet\") {\n                    _has_osc_filter = true;\n                    _osc_threshold = opt->get(key + \".oscillator_strength\").as<double> ();\n                }\n                if (opt->exists(key + \".overlap\")) {\n                    _has_overlap_filter = true;\n                    // _osc_threshold = opt->get(key + \".oscillator_strength\").as<double> ();\n                }\n                if (opt->exists(key + \".localisation\")) {\n                    _has_loc_filter = true;\n                    \n                    string temp = opt->get(key + \".localisation\").as<string> ();\n                    Tokenizer tok_cleanup(temp, \", \\n\\t\");\n                    std::vector <std::string> strings_vec;\n                    tok_cleanup.ToVector(strings_vec);\n                    if (strings_vec.size()!=2){\n                        throw runtime_error(\"qmmmachine: Fragment and localisation threshold are not separated\");\n                    }\n                    if(strings_vec[0]==\"a\" || strings_vec[0]==\"A\"){\n                        _localiseonA=true;\n                    }else if(strings_vec[0]==\"b\" || strings_vec[0]==\"B\"){\n                         _localiseonA=false;\n                    }else{\n                        throw runtime_error(\"qmmmachine: Fragment label not known, either A or B\");\n                    }\n                    _loc_threshold=boost::lexical_cast<double>(strings_vec[1]);\n                } \n\n                if (opt->exists(key + \".charge_transfer\")) {\n                    _has_dQ_filter = true;\n                    _dQ_threshold = opt->get(key + \".charge_transfer\").as<double> ();\n                } \n                if(_has_dQ_filter && _has_loc_filter){\n                    throw runtime_error(\"Cannot use localisation and charge_transfer filter at the same time.\");\n                }\n            } else {\n                _do_gwbse = false;\n            }\n\n            return;\n        }\n\n        template<class QMPackage>\n        QMMachine<QMPackage>::~QMMachine() {\n\n            std::vector<QMMIter*> ::iterator qit;\n            for (qit = _iters.begin(); qit < _iters.end(); ++qit) {\n                delete *qit;\n            }\n            _iters.clear();\n        }\n\n        template<class QMPackage>\n        int QMMachine<QMPackage>::Evaluate(ctp::XJob *job) {\n\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... dR %1$1.4f dQ %2$1.4f QM %3$1.4f MM %4$1.4f IT %5$d\")\n                    % _crit_dR % _crit_dQ % _crit_dE_QM % _crit_dE_MM % _maxIter << flush;\n\n            // FIGURE OUT CHARGE + MULTIPLICITY\n            double dQ = 0.0;\n            for (unsigned int i = 0; i < _job->getPolarTop()->QM0().size(); ++i) {\n                dQ += _job->getPolarTop()->QM0()[i]->CalcTotQ();\n            }\n            int chrg = round(dQ);\n            int spin = ((chrg < 0) ? -chrg : chrg) % 2 + 1;\n            CTP_LOG(ctp::logINFO, *_log) << \"... Q = \" << chrg << \", 2S+1 = \" << spin << flush;\n\n\n            // PREPARE JOB DIRECTORY\n            string jobFolder = \"xjob_\" + boost::lexical_cast<string>(_job->getId())\n                    + \"_\" + _job->getTag();\n            bool created = boost::filesystem::create_directory(jobFolder);\n            if (created) {\n                CTP_LOG(ctp::logINFO, *_log) << \"Created directory \" << jobFolder << flush;\n            }\n\n\n            // SET ITERATION-TIME CONSTANTS\n            // TO ADJUST\n\n            _qmpack->setCharge(chrg);\n            _qmpack->setSpin(spin);\n\n\n            int iterCnt = 0;\n            int iterMax = _maxIter;\n            for (; iterCnt < iterMax; ++iterCnt) {\n\n                // check for polarized QM/MM convergence\n            int info= Iterate(jobFolder, iterCnt);\n            if(info!=0){\n                 CTP_LOG(ctp::logERROR, *_log)\n                        << format(\"Iterating job failed!\")<<flush;\n                 return 1;\n            }\n                if (_static_qmmm) {\n                    _isConverged = true;\n                    break;\n                } else if (hasConverged()) {\n                    break;\n                }\n\n            }\n\n            if (iterCnt == iterMax - 1 && !_isConverged) {\n                CTP_LOG(ctp::logWARNING, *_log)\n                        << format(\"Not converged within %1$d iterations.\") % iterMax;\n                return 2;\n            }\n\n            return 0;\n        }\n\n        template<class QMPackage>\n        bool QMMachine<QMPackage>::Iterate(string jobFolder, int iterCnt) {\n\n            // CREATE ITERATION OBJECT & SETUP RUN DIRECTORY\n            QMMIter *thisIter = this->CreateNewIter();\n            int iter = iterCnt;\n            string runFolder = jobFolder + \"/iter_\" + boost::lexical_cast<string>(iter);\n\n            bool created = boost::filesystem::create_directory(runFolder);\n            if (created)\n                CTP_LOG(ctp::logDEBUG, *_log) << \"Created directory \" << runFolder << flush;\n            else\n                CTP_LOG(ctp::logWARNING, *_log) << \"Could not create directory \" << runFolder << flush;\n\n\n            // RUN CLASSICAL INDUCTION & SAVE\n            _job->getPolarTop()->PrintPDB(runFolder + \"/QM0_MM1_MM2.pdb\");\n            _xind->Evaluate(_job);\n\n\n\n            assert(_xind->hasConverged());\n            thisIter->setE_FM(_job->getEF00(), _job->getEF01(), _job->getEF02(),\n                    _job->getEF11(), _job->getEF12(), _job->getEM0(),\n                    _job->getEM1(), _job->getEM2(), _job->getETOT());\n\n\n            std::vector<ctp::Segment*> empty;\n            /* Translate atoms in QM0() to QMAtoms in orbitals object\n             * to be used in writing the QM input files for the\n             * external QMPackages or directly in internal DFT engine.\n             * DRAWBACK: QMAtom positions are fixed for all iterations\n             *           unless the UPDATE function at the end of the\n             *           iteration updates orb_iter_input (TO BE TESTED)\n             */\n            if (iterCnt == 0) qminterface.GenerateQMAtomsFromPolarSegs(_job->getPolarTop(), orb_iter_input);\n\n            /* Generate list of polar segments in the MM1() and MM2()\n             * region to be used in writing the background multipoles\n             * in the external QMPackages or in the direct evaluation\n             * in the internal DFT engine.\n             */\n            std::vector<ctp::PolarSeg*> MultipolesBackground = qminterface.GenerateMultipoleList( _job->getPolarTop() );\n\n            // if XTP DFT is used, pass this list of polar segments\n            if ( _qmpack->getPackageName() == \"xtp\" )  _qmpack->setMultipoleBackground( MultipolesBackground );\n\n            // setting RUNDIR for the external QMPackages, dummy for internal\n            _qmpack->setRunDir(runFolder);\n\n            /* Call to WriteInputFile writes the appropriate input files\n             * for the respective external QMPackages. For the internal\n             * DFT engine, this function sets logger and runs DFTENGINE's\n             * Prepare() function. ONLY the first iteration, this will\n             * initialize the atoms, basissets, ecps, etc. In all\n             * subsequent iterations it will recalculate all the \"static\"\n             * AOmatrices (overlap, kinetic energy, nuc/ecp) which is\n             * strictly unnecessary but at the same time also those\n             * for external point charges, dipoles, and quadrupoles.\n             * Since in polarized calculations, the dipoles can change\n             * this recalculation is required. Should be split off the\n             * Prepare() function for efficiency.\n             */\n            CTP_LOG(ctp::logDEBUG, *_log) << \"Writing input file \" << runFolder << flush;\n            _qmpack->WriteInputFile(empty, &orb_iter_input, MultipolesBackground);\n\n\n            FILE *out;\n            out = fopen((runFolder + \"/system.pdb\").c_str(), \"w\");\n            orb_iter_input.WritePDB(out);\n            fclose(out);\n\n            /* Runs the external QMPackage or the self-consistent part of\n             * DFTENGINE\n             */\n            _qmpack->Run( &orb_iter_input );\n\n            /* Parse information from the LOGFILE into orbitals, if\n             * external QMPackage is run. Dummy for internal DFTENGINE.\n             * The QMPackage's MOcoefficients are not automatically\n             * parsed in DFT-only calculations and ESP fits for\n             * polarized QMMM are expected in the LOGFILE.\n             * IF the internal ESPFITs should be used, the MOcoefficients\n             * need to be parsed too.\n             */\n            bool success=_qmpack->ParseLogFile(&orb_iter_input);\n            if(!success){\n                return 1;\n            }\n\n            ub::matrix<double> DMAT_tot;\n            // GW-BSE starts here\n            double energy___ex = 0.0;\n            std::vector<int> _state_index;\n\n            if (_do_gwbse) {\n\n                /* Parses the MOcoefficients from the external QMPackages\n                 * for GW-BSE. Internal DFTENGINE has stored coefficients\n                 * into orb_iter_input already, so this is a dummy for that.\n                 */\n                _qmpack->ParseOrbitalsFile(&orb_iter_input);\n                orb_iter_input.setDFTbasis(_qmpack->getBasisSetName());\n\n                // Get a GWBSE object\n                GWBSE _gwbse = GWBSE(&orb_iter_input);\n                // define own logger for GW-BSE that is written into a runFolder logfile\n                ctp::Logger gwbse_logger(ctp::logDEBUG);\n                gwbse_logger.setMultithreading(false);\n                _gwbse.setLogger(&gwbse_logger);\n                gwbse_logger.setPreface(ctp::logINFO, (format(\"\\nGWBSE INF ...\")).str());\n                gwbse_logger.setPreface(ctp::logERROR, (format(\"\\nGWBSE ERR ...\")).str());\n                gwbse_logger.setPreface(ctp::logWARNING, (format(\"\\nGWBSE WAR ...\")).str());\n                gwbse_logger.setPreface(ctp::logDEBUG, (format(\"\\nGWBSE DBG ...\")).str());\n\n                // Initialize with options\n                _gwbse.Initialize(&_gwbse_options);\n\n                /* Only execute GWBSE if excited state is requested. This is a bit\n                 * weird construction to have ground state calculation treated in\n                 * exactly the same way for polarized QMMM.\n                 */\n                if (_state > 0) {\n                    CTP_LOG(ctp::logDEBUG, *_log) << \"Excited state via GWBSE: \" << flush;\n                    CTP_LOG(ctp::logDEBUG, *_log) << \"  --- type:              \" << _type << flush;\n                    CTP_LOG(ctp::logDEBUG, *_log) << \"  --- state:             \" << _state << flush;\n                    if (_has_overlap_filter) {\n                        CTP_LOG(ctp::logDEBUG, *_log) << \"  --- filter: overlap  \" <<  flush;\n                    }\n                    if (_has_osc_filter) {\n                        CTP_LOG(ctp::logDEBUG, *_log) << \"  --- filter: osc.str. > \" << _osc_threshold << flush;\n                    }\n                    if (_has_dQ_filter) {\n                        CTP_LOG(ctp::logDEBUG, *_log) << \"  --- filter: crg.trs. > \" << _dQ_threshold << flush;\n                    }\n                    if (_has_loc_filter){\n                        if (_localiseonA){\n                         CTP_LOG(ctp::logDEBUG, *_log) << \"  --- filter: localisation on A > \" << _loc_threshold << flush;\n                        }else{\n                            CTP_LOG(ctp::logDEBUG, *_log) << \"  --- filter: localisation on B > \" << _loc_threshold << flush;\n                        }\n                    }\n\n                    if (_has_osc_filter && _has_dQ_filter) {\n                        CTP_LOG(ctp::logDEBUG, *_log) << \"  --- WARNING: filtering for optically active CT transition - might not make sense... \" << flush;\n                    }\n\n                    // actual GW-BSE run\n                    _gwbse.Evaluate();\n\n                    // write logger to log file\n                    ofstream ofs;\n                    string gwbse_logfile = runFolder + \"/gwbse.log\";\n                    ofs.open(gwbse_logfile.c_str(), ofstream::out);\n                    if (!ofs.is_open()) {\n                        throw runtime_error(\"Bad file handle: \" + gwbse_logfile);\n                    }\n                    ofs << gwbse_logger << endl;\n                    ofs.close();\n\n                    // PROCESSING the GW-BSE result\n                    // - find the excited state of interest\n                    // oscillator strength filter\n\n                    // quasiparticle filter\n                    if (_has_overlap_filter) {\n                        if (iter == 0) {\n\n                            // One - to - One LIST in 0th iteration\n                            for (unsigned _i = 0; _i < orb_iter_input.QPdiagEnergies().size(); _i++) {\n                                _state_index.push_back(_i);\n                            }\n\n                        } else {\n                            // get AO overlap matrix\n                            AOOverlap _dftoverlap;\n                            // load dft  basis set (element-wise information) from xml file\n                            BasisSet dftbs;\n                            dftbs.LoadBasisSet(orb_iter_input.getDFTbasis());\n                            CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Loaded DFT Basis Set \" << orb_iter_input.getDFTbasis() << flush;\n\n                            // fill auxiliary GW AO basis by going through all atoms\n                            AOBasis dftbasis;\n                            dftbasis.AOBasisFill(&dftbs, orb_iter_input.QMAtoms());\n                            CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Filled DFT Basis of size \" << dftbasis.AOBasisSize() << flush;\n\n                            // Fill overlap\n                            _dftoverlap.Fill(dftbasis);\n                            CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Filled DFT Overlap matrix of dimension: \" << _dftoverlap.Matrix().size1() << flush;\n\n\n                            // 'LAMBDA' matrix of the present iteration                \n                            ub::matrix<real_gwbse> lambda_N = orb_iter_input.LambdaMatrixQuasiParticle();\n\n                            // 'LAMBDA' matrix of the previous iteration\n                            string runFolder_N_1 = jobFolder + \"/iter_\" + boost::lexical_cast<string>(iter - 1);\n                            string orbfile_N_1 = runFolder_N_1 + \"/system.orb\";\n                            Orbitals _orbitals_N_1;\n                            // load the QM data from serialized orbitals object\n                            std::ifstream ifs((orbfile_N_1).c_str());\n                            CTP_LOG(ctp::logDEBUG, *_log) << \" Loading QM data from \" << orbfile_N_1 << flush;\n                            boost::archive::binary_iarchive ia(ifs);\n                            ia >> _orbitals_N_1;\n                            ifs.close();\n\n\n                            ub::matrix<real_gwbse> lambda_N_1 = _orbitals_N_1.LambdaMatrixQuasiParticle();\n                            // calculate QP overlaps\n                            ub::matrix<real_gwbse> qptemp = ub::prod(_dftoverlap.Matrix(), ub::trans(lambda_N_1));\n                            ub::matrix<real_gwbse> qpoverlaps = ub::prod(lambda_N, qptemp);\n\n                            // test output\n                            if (tools::globals::verbose) {\n                                for (unsigned i = 0; i < qpoverlaps.size1(); i++) {\n                                    for (unsigned j = 0; j < qpoverlaps.size2(); j++) {\n                                        CTP_LOG(ctp::logDEBUG, *_log) << \" [\" << i << \" , \" << j << \"]: \" << qpoverlaps(i, j) << flush;\n                                    }\n                                }\n                            }\n\n\n                            // filter for max absolute value (hopefully close to 1)\n                            for (unsigned _j = 0; _j < qpoverlaps.size2(); _j++) {\n                                int maxi = 0;\n                                for (unsigned _i = 0; _i < qpoverlaps.size1(); _i++) {\n                                    if (std::abs(qpoverlaps(_i, _j)) > std::abs(qpoverlaps(maxi, _j))) {\n                                        maxi = _i;\n                                    }\n                                }\n                                _state_index.push_back(maxi);\n                                CTP_LOG(ctp::logDEBUG, *_log) << \" [\" << maxi << \" , \" << _j << \"]: \" << qpoverlaps(maxi, _j) << flush;\n                            }\n\n                        }\n\n                    }\n                    \n                    if (_has_osc_filter) {\n\n                        // go through list of singlets\n                        const std::vector<double>oscs = orb_iter_input.Oscillatorstrengths();\n                        for (unsigned _i = 0; _i < oscs.size(); _i++) {\n\n                            double osc = oscs[_i];\n                            if (osc > _osc_threshold) _state_index.push_back(_i);\n                        }\n\n                    } else {\n                        const ub::vector<real_gwbse>& energies = (_type==\"singlet\") \n                        ? orb_iter_input.BSESingletEnergies() : orb_iter_input.BSETripletEnergies();\n                       \n                        for (unsigned _i = 0; _i < energies.size(); _i++) {\n                            _state_index.push_back(_i);\n                        }     \n                    }\n\n\n                    // filter according to charge transfer, go through list of excitations in _state_index\n                    if (_has_dQ_filter) {\n                        std::vector<int> _state_index_copy;\n                        const std::vector< ub::vector<double> >& dQ_frag= (_type==\"singlet\") \n                        ? orb_iter_input.getFragmentChargesSingEXC():orb_iter_input.getFragmentChargesTripEXC();\n                        for (unsigned _i = 0; _i < _state_index.size(); _i++) {\n                            if (std::abs(dQ_frag[_state_index[_i]](0)) > _dQ_threshold) {\n                                _state_index_copy.push_back(_state_index[_i]);\n                            }\n                        }\n                        _state_index = _state_index_copy;\n                    }\n                    else if (_has_loc_filter) {\n                        std::vector<int> _state_index_copy;\n                        const std::vector< ub::vector<double> >& popE= (_type==\"singlet\") \n                        ? orb_iter_input.getFragment_E_localisation_singlet():orb_iter_input.getFragment_E_localisation_triplet();\n                        const std::vector< ub::vector<double> >& popH= (_type==\"singlet\") \n                        ? orb_iter_input.getFragment_H_localisation_singlet():orb_iter_input.getFragment_H_localisation_triplet();\n                        if(_localiseonA){\n                            for (unsigned _i = 0; _i < _state_index.size(); _i++) {\n                                if (popE[_state_index[_i]](0) > _loc_threshold && popH[_state_index[_i]](0) > _loc_threshold ) {\n                                    _state_index_copy.push_back(_state_index[_i]);\n                                }\n                            }\n                        }else{\n                            for (unsigned _i = 0; _i < _state_index.size(); _i++) {\n                                if (popE[_state_index[_i]](1) > _loc_threshold && popH[_state_index[_i]](1) > _loc_threshold ) {\n                                    _state_index_copy.push_back(_state_index[_i]);\n                                }\n                            }\n                        }\n                        _state_index = _state_index_copy;\n                    }\n\n\n                    if (_state_index.size() < 1) {\n                        CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" WARNING: FILTER yielded no state. Taking lowest excitation\" << flush;\n                        _state_index.push_back(0);\n                    }else{\n                        if ( _type == \"quasiparticle\" ){\n                            CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Filter yielded QP index: \"<<_state_index[_state - 1 - orb_iter_input.getGWAmin()]<< flush;\n                        }else {\n                            CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Filter yielded state\"<<_type<<\":\"<<_state_index[_state - 1]+1<< flush;\n                        }\n                    }\n                    // - output its energy\n                    if (_type == \"singlet\") {\n                        energy___ex = orb_iter_input.BSESingletEnergies()[_state_index[_state - 1]] * tools::conv::hrt2ev; // to eV\n                    } else if (_type == \"triplet\") {\n                        energy___ex = orb_iter_input.BSETripletEnergies()[_state_index[_state - 1]] * tools::conv::hrt2ev; // to eV\n                    } else if (_type == \"quasiparticle\") {\n                        if ( _state > orb_iter_input.getNumberOfElectrons()  ) {\n                            // unoccupied QPs: E_a = E_0 + eps_l\n                            energy___ex = orb_iter_input.QPdiagEnergies()[_state_index[_state - 1 - orb_iter_input.getGWAmin()]] * tools::conv::hrt2ev; // to eV\n                        } else {\n                            // occupied QPs: E_c = E_0 - eps_h\n                            energy___ex = -1.0*orb_iter_input.QPdiagEnergies()[_state_index[_state - 1 - orb_iter_input.getGWAmin()]] * tools::conv::hrt2ev; // to eV\n                        }\n                    }\n\n                } // only if state >0\n\n                if (!_static_qmmm) {\n                    Density2Charges(&_gwbse,_state_index);\n                } // for polarized QMMM\n\n            } //_do_gwbse\n\n\n            /* new ESP fit only required for\n             * - polarizable QMMM\n             * AND\n             * - GWBSE or DFT with internal DFTENGINE\n             */\n            if (!_static_qmmm && _qmpack->getPackageName() == \"xtp\" && !_do_gwbse) {\n                Density2Charges();\n            } // for polarized QMMM\n\n            // Test: go via GDMA instead of point charges, only for DFT with Gaussian!\n            GDMA _gdma;\n            if (_do_gdma) {\n                if (_qmpack->getPackageName() != \"gaussian\" || _qmpack->getExecutable() != \"g03\") {\n\n                    throw runtime_error(\" Invalid QMPackage! \" + _type + \" Gaussian 03 only!\");\n\n                } else {\n                    // get a GDMA object\n                    _gdma.Initialize(&_gdma_options);\n                    _gdma.setLog(_log);\n                    _gdma.SetRunDir(runFolder);\n\n                    CTP_LOG(ctp::logINFO, *_log) << \"Running GDMA \" << flush;\n                    // prepare a GDMA input file\n                    _gdma.WriteInputFile();\n\n                    // run GDMA external\n                    _gdma.RunExternal();\n\n                    // parse output of gdma and update multipoles_full\n                    _gdma.ParseOutputFile();\n\n                } // use gdma\n            } // _do_gdma\n\n\n            out = fopen((runFolder + \"/InputConfig.pdb\").c_str(), \"w\");\n            orb_iter_input.WritePDB(out);\n            fclose(out);\n\n            assert(orb_iter_input.hasSelfEnergy());\n            assert(orb_iter_input.hasQMEnergy());\n\n            // EXTRACT & SAVE QM ENERGIES\n            double energy___sf = orb_iter_input.getSelfEnergy();\n            double energy_qmsf = orb_iter_input.getQMEnergy();\n            double energy_qm__ = energy_qmsf - energy___sf;\n            thisIter->setQMSF(energy_qm__, energy___sf, energy___ex);\n            _job->setEnergy_QMMM(thisIter->getQMEnergy(), thisIter->getGWBSEEnergy(), thisIter->getSFEnergy(),\n                    thisIter->getQMMMEnergy());\n\n            // EXTRACT & SAVE QMATOM DATA\n            std::vector< ctp::QMAtom* > &atoms = orb_iter_input.QMAtoms();\n\n            thisIter->UpdatePosChrgFromQMAtoms(atoms, _job->getPolarTop()->QM0());\n\n            if (_do_gdma) {\n\n                // update PolarTop\n                thisIter->UpdateMPSFromGDMA(_gdma.GetMultipoles(), _job->getPolarTop()->QM0());\n\n            }\n            \n            // Update state variable\n            if (_type == \"quasiparticle\" || _has_overlap_filter ){\n                \n                _state = _state_index[ _state -1 - orb_iter_input.getGWAmin() ] + 1 + orb_iter_input.getGWAmin();\n                \n            }\n\n            unsigned qmsize = 0;\n            std::vector< ctp::QMAtom* > ::iterator ait;\n            for (ait = atoms.begin(); ait < atoms.end(); ++ait) {\n\n                if ( !(*ait)->from_environment ) qmsize++;\n                //CTP_LOG(ctp::logINFO, *_log) << (*ait)->type << \" \" << (*ait)->x << \" \"  << (*ait)->y << \" \" << (*ait)->z << flush;\n\n            }\n            // serialize this iteration\n            if (_do_archive) {\n                // save orbitals\n                std::string ORB_FILE = runFolder + \"/system.orb\";\n                CTP_LOG(ctp::logDEBUG, *_log) << \"Archiving data to \" << ORB_FILE << flush;\n                orb_iter_input.Save(ORB_FILE);\n            }\n\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"Summary - iteration %1$d:\") % (iterCnt + 1) << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... QM Size  = %1$d atoms\") % int(qmsize) << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... E(QM)    = %1$+4.9e\") % thisIter->getQMEnergy() << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... E(GWBSE) = %1$+4.9e\") % thisIter->getGWBSEEnergy() << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... E(SF)    = %1$+4.9e\") % thisIter->getSFEnergy() << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... E(FM)    = %1$+4.9e\") % thisIter->getFMEnergy() << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... E(MM)    = %1$+4.9e\") % thisIter->getMMEnergy() << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... E(QMMM)  = %1$+4.9e\") % thisIter->getQMMMEnergy() << flush;\n            if (!_static_qmmm) {\n                CTP_LOG(ctp::logINFO, *_log)\n                        << format(\"... RMS(dR)  = %1$+4.9e\") % thisIter->getRMSdR() << flush;\n                CTP_LOG(ctp::logINFO, *_log)\n                        << format(\"... RMS(dQ)  = %1$+4.9e\") % thisIter->getRMSdQ() << flush;\n                CTP_LOG(ctp::logINFO, *_log)\n                        << format(\"... SUM(dQ)  = %1$+4.9e\") % thisIter->getSUMdQ() << flush;\n            }\n            // CLEAN DIRECTORY\n            _qmpack->CleanUp();\n\n\n            return 0;\n        }\n\n\n        template<class QMPackage>\n        void QMMachine<QMPackage>::Density2Charges( GWBSE* _gwbse, std::vector<int> _state_index ){\n\n                   \n                    // load DFT basis set (element-wise information) from xml file\n                    BasisSet dftbs;\n                    if (orb_iter_input.getDFTbasis() != \"\") {\n                        dftbs.LoadBasisSet(orb_iter_input.getDFTbasis());\n                        CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Loaded DFT Basis Set \" << orb_iter_input.getDFTbasis() << flush;\n                    } else {\n                        //dftbs.LoadBasisSet(_gwbse->get_dftbasis_name());\n                        //CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Loaded DFT Basis Set \" << _gwbse.get_dftbasis_name() << flush;\n                    }\n\n                    // fill DFT AO basis by going through all atoms\n                    AOBasis dftbasis;\n                    dftbasis.AOBasisFill(&dftbs, orb_iter_input.QMAtoms());\n                    \n                    ub::matrix<double> DMATGS = orb_iter_input.DensityMatrixGroundState();\n\n                    ub::matrix<double> DMAT_tot = DMATGS; // Ground state + hole_contribution + electron contribution\n\n                    if (_state > 0 ) {\n                        \n                        if ( _type == \"singlet\" && _type == \"triplet\"){\n                        \n                            std::vector<ub::matrix<double> > DMAT = orb_iter_input.DensityMatrixExcitedState(_type, _state_index[_state - 1]);\n                            DMAT_tot = DMAT_tot - DMAT[0] + DMAT[1]; // Ground state + hole_contribution + electron contribution\n                        } else if ( _type == \"quasiparticle\"){\n                            \n                            ub::matrix<double> DMATQP = orb_iter_input.DensityMatrixQuasiParticle(  _state_index[_state - 1 - orb_iter_input.getGWAmin()]);\n\n                            if ( _state > orb_iter_input.getNumberOfElectrons() ) {\n                                DMAT_tot = DMAT_tot + DMATQP;\n                            } else {\n                                DMAT_tot = DMAT_tot - DMATQP;\n                            }\n                        }\n                    }\n\n                    // fill DFT AO basis by going through all atoms\n                    std::vector< ctp::QMAtom* >& Atomlist = orb_iter_input.QMAtoms();\n\n                    Espfit esp = Espfit(_log);\n                    if (_qmpack->ECPRequested()) {\n                        esp.setUseECPs(true);\n                    }\n                    esp.Fit2Density(Atomlist, DMAT_tot, dftbasis, dftbs, \"medium\");\n\n\n\n\n            return;\n        }\n\n\n\n        template<class QMPackage>\n        QMMIter *QMMachine<QMPackage>::CreateNewIter() {\n\n            QMMIter *newIter = new QMMIter(_iters.size());\n            this->_iters.push_back(newIter);\n            return newIter;\n        }\n\n        template<class QMPackage>\n        bool QMMachine<QMPackage>::hasConverged() {\n\n            _convg_dR = false;\n            _convg_dQ = false;\n            _convg_dE_QM = false;\n            _convg_dE_MM = false;\n\n            if (_iters.size() > 1) {\n\n                QMMIter *iter_0 = _iters[_iters.size() - 2];\n                QMMIter *iter_1 = _iters[_iters.size() - 1];\n\n                double dR = iter_1->getRMSdR();\n                double dQ = iter_1->getRMSdQ();\n                double dE_QM = iter_1->getQMEnergy() - iter_0->getQMEnergy();\n                double dE_MM = iter_1->getMMEnergy() - iter_0->getMMEnergy();\n\n                CTP_LOG(ctp::logINFO, *_log)\n                        << format(\"... dE_QM  = %1$+4.9e\") % dE_QM << flush;\n                CTP_LOG(ctp::logINFO, *_log)\n                        << format(\"... dE_MM  = %1$+4.9e\") % dE_MM << flush;\n\n                if (dR <= _crit_dR) _convg_dR = true;\n                if (dQ <= _crit_dQ) _convg_dQ = true;\n                if (dE_QM * dE_QM <= _crit_dE_QM * _crit_dE_QM) _convg_dE_QM = true;\n                if (dE_MM * dE_MM <= _crit_dE_MM * _crit_dE_MM) _convg_dE_MM = true;\n            }\n\n            _isConverged = ((_convg_dR && _convg_dQ) && (_convg_dE_QM && _convg_dE_MM));\n\n\n\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... Convg dR = %s\") % (_convg_dR ? \"true\" : \"false\") << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... Convg dQ = %s\") % (_convg_dQ ? \"true\" : \"false\") << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... Convg QM = %s\") % (_convg_dE_QM ? \"true\" : \"false\") << flush;\n            CTP_LOG(ctp::logINFO, *_log)\n                    << format(\"... Convg MM = %s\") % (_convg_dE_MM ? \"true\" : \"false\") << flush;\n\n            return _isConverged;\n        }\n\n\n\n        // REGISTER QM PACKAGES\n        template class QMMachine<QMPackage>;\n\n\n\n    }\n}\n", "meta": {"hexsha": "75b177efb6bc9090fea3bb8a67e6b9f793316edb", "size": 35973, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/qmmachine.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/qmmachine.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/qmmachine.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": 45.825477707, "max_line_length": 173, "alphanum_fraction": 0.4863925722, "num_tokens": 8574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894279828469, "lm_q2_score": 0.019124035458106307, "lm_q1q2_score": 0.006398700084651471}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2016 John Maddock. 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_MP_MIN_MAX_HPP\r\n#define BOOST_MP_MIN_MAX_HPP\r\n\r\n#include <boost/multiprecision/traits/is_backend.hpp>\r\n\r\nnamespace boost { namespace multiprecision {\r\n\r\n//\r\n// Expression template overloads for (min) and (max):\r\n//\r\n// Introduced in response to https://svn.boost.org/trac/boost/ticket/11149\r\n// note that these can not legally be injected into namespace std, and that doing so\r\n// may break future enhancements to the standard.  None the less adding\r\n// namespace std{ using boost::multiprecision::(min); using boost::multiprecision::(max); }\r\n// to your code may get some generic code working that wouldn't work otherwise.\r\n//\r\n// The use of enable_if on the return type is to avoid poisoning std::min/max,\r\n// otherwise attempting to make an explicit call to min<long>(a, b) when these and std\r\n// versions are in scope, will cause the compiler to try to instantiate the signatures\r\n// for our versions as well as the std ones, which in turn instantiates number<long>\r\n// which fails to compile as \"long\" is not a valid backend type.\r\n//\r\ntemplate <class Backend>\r\ninline typename boost::enable_if_c<boost::multiprecision::detail::is_backend<Backend>::value, const number<Backend, et_on>&>::type(min)(const number<Backend, et_on>& a, const number<Backend, et_on>& b)\r\n{\r\n   return a < b ? a : b;\r\n}\r\ntemplate <class Backend, class tag, class A1, class A2, class A3, class A4>\r\ninline typename boost::enable_if_c<boost::multiprecision::detail::is_backend<Backend>::value, const number<Backend, et_on> >::type(min)(const number<Backend, et_on>& a, const detail::expression<tag, A1, A2, A3, A4>& b)\r\n{\r\n   number<Backend, et_on> t(b);\r\n   if (a < t)\r\n      return a;\r\n   return BOOST_MP_MOVE(t);\r\n}\r\ntemplate <class tag, class A1, class A2, class A3, class A4, class Backend>\r\ninline typename boost::enable_if_c<boost::multiprecision::detail::is_backend<Backend>::value, const number<Backend, et_on> >::type(min)(const detail::expression<tag, A1, A2, A3, A4>& a, const number<Backend, et_on>& b)\r\n{\r\n   number<Backend, et_on> t(a);\r\n   if (t < b)\r\n      return BOOST_MP_MOVE(t);\r\n   return b;\r\n}\r\ntemplate <class tag, class A1, class A2, class A3, class A4, class tagb, class A1b, class A2b, class A3b, class A4b>\r\ninline typename detail::expression<tag, A1, A2, A3, A4>::result_type(min)(const detail::expression<tag, A1, A2, A3, A4>& a, const detail::expression<tagb, A1b, A2b, A3b, A4b>& b)\r\n{\r\n   typename detail::expression<tag, A1, A2, A3, A4>::result_type t1(a), t2(b);\r\n   if (t1 < t2)\r\n      return BOOST_MP_MOVE(t1);\r\n   return BOOST_MP_MOVE(t2);\r\n}\r\ntemplate <class tag, class A1, class A2, class A3, class A4>\r\ninline typename detail::expression<tag, A1, A2, A3, A4>::result_type(min)(const detail::expression<tag, A1, A2, A3, A4>& a, const detail::expression<tag, A1, A2, A3, A4>& b)\r\n{\r\n   typename detail::expression<tag, A1, A2, A3, A4>::result_type t1(a), t2(b);\r\n   if (t1 < t2)\r\n      return BOOST_MP_MOVE(t1);\r\n   return BOOST_MP_MOVE(t2);\r\n}\r\n\r\ntemplate <class Backend>\r\ninline typename boost::enable_if_c<boost::multiprecision::detail::is_backend<Backend>::value, const number<Backend, et_on>&>::type(max)(const number<Backend, et_on>& a, const number<Backend, et_on>& b)\r\n{\r\n   return a > b ? a : b;\r\n}\r\ntemplate <class Backend, class tag, class A1, class A2, class A3, class A4>\r\ninline typename boost::enable_if_c<boost::multiprecision::detail::is_backend<Backend>::value, const number<Backend, et_on> >::type(max)(const number<Backend, et_on>& a, const detail::expression<tag, A1, A2, A3, A4>& b)\r\n{\r\n   number<Backend, et_on> t(b);\r\n   if (a > t)\r\n      return a;\r\n   return BOOST_MP_MOVE(t);\r\n}\r\ntemplate <class tag, class A1, class A2, class A3, class A4, class Backend>\r\ninline typename boost::enable_if_c<boost::multiprecision::detail::is_backend<Backend>::value, const number<Backend, et_on> >::type(max)(const detail::expression<tag, A1, A2, A3, A4>& a, const number<Backend, et_on>& b)\r\n{\r\n   number<Backend, et_on> t(a);\r\n   if (t > b)\r\n      return BOOST_MP_MOVE(t);\r\n   return b;\r\n}\r\ntemplate <class tag, class A1, class A2, class A3, class A4, class tagb, class A1b, class A2b, class A3b, class A4b>\r\ninline typename detail::expression<tag, A1, A2, A3, A4>::result_type(max)(const detail::expression<tag, A1, A2, A3, A4>& a, const detail::expression<tagb, A1b, A2b, A3b, A4b>& b)\r\n{\r\n   typename detail::expression<tag, A1, A2, A3, A4>::result_type t1(a), t2(b);\r\n   if (t1 > t2)\r\n      return BOOST_MP_MOVE(t1);\r\n   return BOOST_MP_MOVE(t2);\r\n}\r\ntemplate <class tag, class A1, class A2, class A3, class A4>\r\ninline typename detail::expression<tag, A1, A2, A3, A4>::result_type(max)(const detail::expression<tag, A1, A2, A3, A4>& a, const detail::expression<tag, A1, A2, A3, A4>& b)\r\n{\r\n   typename detail::expression<tag, A1, A2, A3, A4>::result_type t1(a), t2(b);\r\n   if (t1 > t2)\r\n      return BOOST_MP_MOVE(t1);\r\n   return BOOST_MP_MOVE(t2);\r\n}\r\n\r\n}} // namespace boost::multiprecision\r\n\r\n#endif\r\n", "meta": {"hexsha": "883e834692b3ee66939adb394b6eaacf9d7eda60", "size": 5226, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/multiprecision/detail/min_max.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/multiprecision/detail/min_max.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/multiprecision/detail/min_max.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": 48.8411214953, "max_line_length": 219, "alphanum_fraction": 0.6825487945, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2018132126589859, "lm_q2_score": 0.03161876738271023, "lm_q1q2_score": 0.006381085025821907}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2017.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Timo Sachsenberg $\n// $Authors: $\n// --------------------------------------------------------------------------\n//\n\n#include <OpenMS/TRANSFORMATIONS/RAW2PEAK/OptimizePeakDeconvolution.h>\n#include <boost/math/special_functions/acosh.hpp>\n\n\n#ifdef DEBUG_DECONV\n#include <iostream>\n#include <fstream>\n#endif\n\nnamespace OpenMS\n{\n\n\n  const double OptimizePeakDeconvolution::dist_ = 1.003;\n\n  //TODO: the operator() and the df function need heavy refactoring!!!\n  struct OPDFunctor\n  {\n    int inputs() const { return m_inputs; }\n    int values() const { return m_values; }\n\n    OPDFunctor(unsigned dimensions, unsigned numDataPoints, const OptimizePeakDeconvolution::Data* data) :\n      m_inputs(dimensions), m_values(numDataPoints), m_data(data){}\n\n    int operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec)\n    {\n      //TODO: holding the parameters to be optimized and additional values in the same vector is\n      //      most likely not the best idea. should be split in two vectors.\n      //\n      // x contains the parameters to be optimized.\n      // The first two entries are the left and right width, respectively.They are equal\n      // for all peaks. Then the height and position of all peaks are stored.\n      //\n      // m_data might contain any additional parameters. We handle these using class members\n      // instead.\n      // The vector f is supposed to contain the result when we return from this function.\n      const std::vector<double>& signal = m_data->signal;\n      const std::vector<double>& positions = m_data->positions;\n      const std::vector<PeakShape>& peaks = m_data->peaks;\n      const OptimizationFunctions::PenaltyFactorsIntensity& penalties = m_data->penalties;\n      Int charge = m_data->charge;\n      double leftwidth = x(0);\n      double rightwidth = x(1);\n      //double posP1 = x(2);\n\n      // iterate over all points of the signal\n      for (Size current_point = 0; current_point < positions.size(); current_point++)\n      {\n        double computed_signal = 0.;\n        double current_position = positions[current_point];\n        double experimental_signal = signal[current_point];\n\n        //iterate over all peaks\n        for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n        {\n          //Store the current parameters for this peak\n          double p_height = x(2 + 2 * current_peak);\n          double p_position = x(2 + 2 * current_peak + 1);\n          double p_width = (current_position <= p_position) ? leftwidth : rightwidth;\n\n          //is it a Lorentz or a Sech - Peak?\n          if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n          {\n            computed_signal += p_height / (1. + pow(p_width * (current_position - p_position), 2));\n          }\n          else // It's a Sech - Peak\n          {\n            computed_signal += p_height / pow(cosh(p_width * (current_position - p_position)), 2);\n          }\n        }\n        fvec(current_point) = computed_signal - experimental_signal;\n      }\n\n      // penalties : especially negative heights have to be penalised\n      double penalty = 0.;\n\n      double penalty_pos = penalties.pos;\n      double penalty_lwidth = penalties.lWidth;\n      double penalty_rwidth = penalties.rWidth;\n      double penalty_intensity = penalties.height;\n\n\n      //iterate over all peaks again to compute the penalties\n      for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n        double p_position = x(2 + 2 * current_peak + 1);\n        if (current_peak < peaks.size() - 1)\n        {\n\n          double next_p_position  = x(2 + 2 * current_peak + 3);\n          // if distance between peaks does not match the peptide mass rule\n          if (fabs(fabs(p_position - next_p_position) - 1.003 / charge) > 0.05)\n          {\n            // penalize it\n            penalty +=  penalty_pos * 10000\n                       * pow(fabs(fabs(p_position - next_p_position) - 1.003 / charge), 2);\n          }\n        }\n        double old_position = peaks[current_peak].mz_position;\n        double old_width_l  = peaks[current_peak].left_width;\n        double old_width_r = peaks[current_peak].right_width;\n        double old_height = peaks[current_peak].height;\n\n        double p_width_l = x(0);\n        double p_width_r = x(1);\n        double p_height = x(2 + 2 * current_peak);\n\n        if (p_height <  1)\n        {\n          penalty += 100000* penalty_intensity* pow(fabs(p_height - old_height), 2);\n\n        }\n        if (p_width_l < 0)\n        {\n          penalty += penalty_lwidth * peaks.size() * 10000 * pow(fabs(p_width_l - old_width_l), 2);\n        }\n        else if (p_width_l < 1.5)\n          penalty += 10000 * pow(fabs(p_width_l - old_width_l), 2);\n        if (p_width_r < 0)\n        {\n          penalty += penalty_rwidth * peaks.size() * 10000 * pow(fabs(p_width_r - old_width_r), 2);\n        }\n        else if (p_width_r < 1.5)\n          penalty += 10000 * pow(fabs(p_width_r - old_width_r), 2);\n        if (fabs(old_position - p_position) > 0.1)\n        {\n          penalty += 10000* penalty_pos* pow(fabs(old_position - p_position), 2);\n        }\n      }\n      fvec(fvec.size() - 1) = penalty;\n\n      return 0;\n    }\n\n    // compute Jacobian matrix for the different parameters\n    int df(const Eigen::VectorXd& x, Eigen::MatrixXd& J)\n    {\n      // For the conventions on x and params c.f. the commentary in residual()\n      //\n      // The matrix J is supposed to contain the result when we return from this function.\n      // Note: Jacobian is expected as follows:\n      //                    - each row corresponds to one data point\n      //                    - each column corresponds to one parameter\n      const std::vector<double>& positions = m_data->positions;\n      const std::vector<PeakShape>& peaks = m_data->peaks;\n      const OptimizationFunctions::PenaltyFactorsIntensity& penalties = m_data->penalties;\n      Int charge = m_data->charge;\n\n      double leftwidth = x(0);\n      double rightwidth = x(1);\n\n      //TODO: is the reset needed?\n      J.setZero();\n\n      // iterate over all points of the signal\n      for (Size current_point = 0; current_point < positions.size(); current_point++)\n      {\n        double current_position = positions[current_point];\n\n        // iterate over all peaks\n        for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n        {\n          //Store the current parameters for this peak\n          double p_height = x(2 + 2 * current_peak);\n          double p_position = x(2 + 2 * current_peak + 1);\n          double p_width = (current_position <= p_position) ? leftwidth : rightwidth;\n\n          //is it a Lorentz or a Sech - Peak?\n          if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n          {\n            double diff = current_position - p_position;\n            double denom_inv = 1. / (1. + pow(p_width * diff, 2));\n\n            double ddl_left\n              = (current_position <= p_position) ? -2* p_height* pow(diff, 2) * p_width * pow(denom_inv, 2) : 0;\n\n            double ddl_right\n              = (current_position  > p_position) ? -2* p_height* pow(diff, 2) * p_width * pow(denom_inv, 2) : 0;\n\n            // left and right width are the same for all peaks,\n            // the sums of the derivations over all peaks are stored in the first two columns\n            J(current_point, 0) = J(current_point, 0) + ddl_left;\n            J(current_point, 1) = J(current_point, 1) + ddl_right;\n\n            double ddx0    = 2* p_height* pow(p_width, 2) * diff * pow(denom_inv, 2);\n\n            // partial derivation with respect to intensity\n            J(current_point, 2 + 2 * current_peak) = denom_inv;\n\n            // partial derivation with respect to the mz-position\n            J(current_point, 2 + 2 * current_peak + 1) = ddx0;\n          }\n          else // It's a Sech - Peak\n          {\n            double diff      = current_position - p_position;\n            double denom_inv = 1. / cosh(p_width * diff);\n\n            // The remaining computations are not stable if denom_inv == 0. In that case, we are far away from the peak\n            // and can assume that all derivatives vanish\n            double sinh_term = (fabs(denom_inv) < 1e-6) ? 0.0 : sinh(p_width * diff);\n\n\n            double ddl_left  = (current_position <= p_position)\n                               ? -2* p_height* sinh_term* diff* pow(denom_inv, 3) :\n                               0;\n            double ddl_right = (current_position  > p_position)\n                               ? -2* p_height* sinh_term* diff* pow(denom_inv, 3) :\n                               0;\n\n            J(current_point, 0) = J(current_point, 0) + ddl_left;\n            J(current_point, 1) = J(current_point, 1) + ddl_right;\n\n            double ddx0      = 2* p_height* p_width* sinh_term* pow(denom_inv, 3);\n\n            J(current_point, 2 + 2 * current_peak) = pow(denom_inv, 2);\n            J(current_point, 2 + 2 * current_peak + 1) = ddx0;\n          }\n        }\n      }\n\n      /** Now iterate over all peaks again to compute the\n       *  penalties.\n       */\n      for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n\n\n        double penalty_p = 0;\n        double p_position = x(2 + 2 * current_peak + 1);\n        if (current_peak < peaks.size() - 1)\n        {\n\n          double next_p_position  = x(2 + 2 * current_peak + 3);\n          // if distance between peaks does not match the peptide mass rule\n          if (fabs(fabs(p_position - next_p_position) - 1.003 / charge) > 0.05)\n          {\n            // penalize it\n            penalty_p += penalties.pos * 20000\n                         * fabs(fabs(p_position - next_p_position) - 1.003 / charge);\n\n          }\n        }\n        std::cout << \"Eigen penalty_p \" << penalty_p << std::endl;\n        double p_width_left = x(0);\n        double p_width_right = x(1);\n        double p_height = x(2 + 2 * current_peak);\n\n        double old_position = peaks[current_peak].mz_position;\n        double old_width_left  = peaks[current_peak].left_width;\n        double old_width_right = peaks[current_peak].right_width;\n        double old_height = peaks[current_peak].height;\n\n        double penalty_h = 0., penalty_l = 0., penalty_r = 0.;\n        if (p_height < 1)\n        {\n          penalty_h += 100000 * 2 * penalties.height * (fabs(p_height) - fabs(old_height));\n        }\n\n        if (p_width_left < 0)\n        {\n          penalty_l += peaks.size() * 2 * penalties.lWidth * 10000 * (fabs(p_width_left - old_width_left));\n        }\n        else if (p_width_left < 1.5)\n          penalty_l += 2 * penalties.lWidth * 10000 * pow(fabs(p_width_left - old_width_left), 2);\n        if (p_width_right < 0)\n        {\n          penalty_r += peaks.size() * 2 * penalties.rWidth * 10000 * (fabs(p_width_right - old_width_right));\n        }\n        else if (p_width_right < 1.5)\n          penalty_r += 2 * penalties.rWidth * 10000 * pow(fabs(p_width_right - old_width_right), 2);\n        if (fabs(old_position - p_position) > 0.1)\n        {\n          penalty_p += 10000 * penalties.pos * 2 * fabs(old_position - p_position);\n        }\n\n        J(positions.size(), 2 + 2 * current_peak) = 100 * penalty_h;\n        J(positions.size(), 0) = 100 * penalty_l;\n        J(positions.size(), 1) = 100 * penalty_r;\n        J(positions.size(), 2 + 2 * current_peak + 1) = 100 * penalty_p;\n      }\n      for (int i = 0; i < J.rows(); ++i)\n      {\n        for (int j = 0; j < J.cols(); ++j)\n          std::cout << J(i, j) << \" \";\n        std::cout << std::endl;\n      }\n      std::cout << std::endl;\n      return 0;\n    }\n\n    const int m_inputs, m_values;\n    const OptimizePeakDeconvolution::Data* m_data;\n  };\n\n\n\n  OptimizePeakDeconvolution::OptimizePeakDeconvolution() :\n    DefaultParamHandler(\"OptimizePeakDeconvolution\"), charge_(1)\n  {\n\n    defaults_.setValue(\"max_iteration\", 10, \"maximal number of iterations for the fitting step\");\n    defaults_.setValue(\"eps_abs\", 1e-04, \"if the absolute error gets smaller than this value the fitting is stopped\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"eps_rel\", 1e-04, \"if the relative error gets smaller than this value the fitting is stopped\", ListUtils::create<String>(\"advanced\"));\n\n    defaults_.setValue(\"penalties:left_width\", 0.0, \"penalty term for the fitting of the left width:\" \\\n                                                    \"If the left width gets too broad or negative during the fitting it can be penalized.\");\n    defaults_.setValue(\"penalties:right_width\", 0.0, \"penalty term for the fitting of the right width:\" \\\n                                                     \"If the right width gets too broad or negative during the fitting it can be penalized.\");\n    defaults_.setValue(\"penalties:height\", 0.0, \"penalty term for the fitting of the intensity:\" \\\n                                                \"If it gets negative during the fitting it can be penalized.\");\n    defaults_.setValue(\"penalties:position\", 0.0, \"penalty term for the fitting of the peak position:\" \\\n                                                  \"If the position changes more than 0.5Da during the fitting it can be penalized as well as \" \\\n                                                  \"discrepancies of the peptide mass rule.\");\n\n    defaults_.setValue(\"fwhm_threshold\", 1.0, \"If a peaks is broader than fwhm_threshold, it is assumed that it contains another peaks and an additional peak is added.\");\n\n    defaultsToParam_();\n  }\n\n  void OptimizePeakDeconvolution::updateMembers_()\n  {\n    penalties_.rWidth = (float)param_.getValue(\"penalties:right_width\");\n    penalties_.lWidth = (float)param_.getValue(\"penalties:left_width\");\n    penalties_.height = (float)param_.getValue(\"penalties:height\");\n    penalties_.pos    = (float)param_.getValue(\"penalties:position\");\n\n  }\n\n  bool OptimizePeakDeconvolution::optimize(std::vector<PeakShape>& peaks, Data& data)\n  {\n\n    if (peaks.empty())\n      return true;\n\n\n#ifdef DEBUG_DECONV\n    std::cout << \"peaksanzahl:\" << peaks.size();\n    std::cout << \"\\tpeaks[0].mz_position:\" << peaks[0].mz_position << std::endl;\n\n    for (Size j = 0; j < peaks.size(); ++j)\n    {\n      std::cout << \"\\tpeaks[j].mz_position:\" << peaks[j].mz_position;\n      std::cout << \"\\tpeaks[j].height:\" << peaks[j].height << std::endl;\n      std::cout << \"\\tpeaks[j].left_width:\" << peaks[j].left_width;\n      std::cout << \"\\tpeaks[j].right_width:\" << peaks[j].right_width << std::endl << std::endl;\n    }\n\n    for (Size j = 0; j < data.positions.size(); ++j)\n    {\n      std::cout << \"positions[\" << j << \"]=\" << data.positions[j] << std::endl;\n    }\n\n#endif\n\n    // the input peaks are stored in a temporary vector\n    std::vector<PeakShape> temp_shapes = peaks;\n\n    Size global_peak_number = 0;\n\n    double min(std::numeric_limits<double>::max());\n    Int bestCharge = 0;\n    Size bestNumPeaks = 0;\n    Eigen::VectorXd bestResult(2 + 2 * data.peaks.size());\n    bestResult.setZero();\n\n    // try three different charge states : charge-1, charge, charge +1\n    // take the best solution\n    Int chargeState = (charge_ - 1 > 1) ? charge_ - 1 : charge_;\n    Int firstChargeState = chargeState;\n#ifdef DEBUG_DECONV\n    std::cout << \"charge \" << chargeState << \" max_charge\" << charge_ + 1\n              << \"\\tpeaks.size() \" << peaks.size() << std::endl;\n#endif\n    bestCharge = chargeState;\n    bestNumPeaks = peaks.size();\n    for (; chargeState < charge_ + 2; ++chargeState)\n    {\n\n      setNumberOfPeaks_(data, temp_shapes, chargeState);\n      Eigen::VectorXd x_init(2 + 2 * data.peaks.size());\n      for (Size i = 0; i < data.peaks.size(); i++)\n      {\n        x_init(2 + 2 * i) = data.peaks[i].height;\n        x_init(3 + 2 * i) = data.peaks[i].mz_position;\n      }\n      // Initialize the parameters for the optimization\n      // all peaks shall have the same width\n      double wl = data.peaks[0].left_width;\n      double wr = data.peaks[0].right_width;\n      if (boost::math::isnan(wl))\n      {\n        for (Size i = 0; i < data.peaks.size(); ++i)\n        {\n          data.peaks[i].left_width = 1;\n        }\n        wl = 1.;\n      }\n      if (boost::math::isnan(wr))\n      {\n        for (Size i = 0; i < data.peaks.size(); ++i)\n        {\n          data.peaks[i].right_width = 1;\n        }\n        wr = 1.;\n      }\n      x_init(0) = wl;\n      x_init(1) = wr;\n      data.penalties = penalties_;\n      data.charge = chargeState;\n      unsigned numDataPoints = std::max(data.positions.size() + 1, 2 + 2 * data.peaks.size());\n      OPDFunctor functor(2, numDataPoints, &data);\n      Eigen::LevenbergMarquardt<OPDFunctor> lmSolver(functor);\n      Eigen::LevenbergMarquardt<OPDFunctor>::Parameters config;\n      config.maxfev = (Int)param_.getValue(\"max_iteration\");\n      lmSolver.parameters = config;\n      Eigen::LevenbergMarquardtSpace::Status status = lmSolver.minimize(x_init);\n\n      //the states are poorly documented. after checking the source, we believe that\n      //all states except NotStarted, Running and ImproperInputParameters are good\n      //termination states.\n      if (status <= Eigen::LevenbergMarquardtSpace::ImproperInputParameters)\n      {\n        throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"UnableToFit-OptimizePeakDeconvolution\", \"Could not fit the curve to the data: Error \" + String(status));\n      }\n      double chi = lmSolver.fnorm;\n      if ((chargeState == firstChargeState) || (chi < min))\n      {\n\n        bestResult = x_init;\n        min = chi;\n        bestCharge = chargeState;\n        bestNumPeaks = data.peaks.size();\n      }\n    }\n    global_peak_number += bestNumPeaks;\n    // iterate over all peaks and store the optimized values in peaks\n    if (bestNumPeaks > 0)\n    {\n      peaks.resize(bestNumPeaks);\n      for (Size current_peak = 0; current_peak < bestNumPeaks; current_peak++)\n      {\n\n        // Store the current parameters for this peak\n\n        peaks[current_peak].left_width  = bestResult(0);\n        peaks[current_peak].right_width = bestResult(1);\n\n        peaks[current_peak].height = bestResult(2 + 2 * current_peak);\n        peaks[current_peak].mz_position = bestResult(2 + 2 * current_peak + 1);\n\n\n\n        // compute the area\n        // is it a Lorentz or a Sech - Peak?\n        if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n        {\n          PeakShape p = peaks[current_peak];\n          double x_left_endpoint = p.mz_position + 1 / p.left_width * sqrt(p.height / 1 - 1);\n          double x_right_endpoint = p.mz_position + 1 / p.right_width * sqrt(p.height / 1 - 1);\n#ifdef DEBUG_DECONV\n          std::cout << \"x_left_endpoint \" << x_left_endpoint << \" x_right_endpoint \" << x_right_endpoint << std::endl;\n          std::cout << \"p.height\" << p.height << std::endl;\n#endif\n          double area_left = -p.height / p.left_width * atan(p.left_width * (x_left_endpoint - p.mz_position));\n          double area_right = -p.height / p.right_width * atan(p.right_width * (p.mz_position - x_right_endpoint));\n          peaks[current_peak].area = area_left + area_right;\n\n        }\n        else                   //It's a Sech - Peak\n        {\n          PeakShape p = peaks[current_peak];\n          double x_left_endpoint = p.mz_position + 1 / p.left_width * boost::math::acosh(sqrt(p.height / 0.001));\n          double x_right_endpoint = p.mz_position + 1 / p.right_width * boost::math::acosh(sqrt(p.height / 0.001));\n#ifdef DEBUG_DECONV\n          std::cout << \"x_left_endpoint \" << x_left_endpoint << \" x_right_endpoint \" << x_right_endpoint << std::endl;\n          std::cout << \"p.height\" << p.height << std::endl;\n#endif\n          double area_left = -p.height / p.left_width * (sinh(p.left_width * (p.mz_position - x_left_endpoint))\n                                                         / cosh(p.left_width * (p.mz_position - x_left_endpoint)));\n          double area_right = -p.height / p.right_width * (sinh(p.right_width * (p.mz_position - x_right_endpoint))\n                                                           / cosh(p.right_width * (p.mz_position - x_right_endpoint)));\n          peaks[current_peak].area = area_left + area_right;\n\n        }\n\n      }\n    }\n    charge_ = bestCharge;\n\n    return true;\n  }\n\n  Size OptimizePeakDeconvolution::getNumberOfPeaks_(Int charge, std::vector<PeakShape>& temp_shapes, Data& data)\n  {\n    double dist = dist_ / charge;\n\n    data.peaks.clear();\n\n    Size shape = 0;\n#ifdef DEBUG_DECONV\n    std::cout << \"temp_shapes[0].mz_position \" << temp_shapes[0].mz_position\n              << \"\\t dist \" << dist << \"\\tp_index \" << shape << std::endl;\n#endif\n    // while the peak's position is smaller than the last considered position\n    // take the peak for optimization\n    while ((temp_shapes[0].mz_position + shape * dist <\n            data.positions[data.positions.size() - 1]) &&\n           (shape < temp_shapes.size()))\n    {\n      data.peaks.push_back(temp_shapes[shape]);\n#ifdef DEBUG_DECONV\n      std::cout << \"temp_shapes[0].mz_position + p_index*dist = \" << temp_shapes[0].mz_position + shape * dist << std::endl;\n#endif\n      ++shape;\n    }\n\n    return shape;\n\n  }\n\n  void OptimizePeakDeconvolution::setNumberOfPeaks_(Data& data, const std::vector<PeakShape>& temp_shapes, Int charge)\n  {\n    double dist = dist_ / charge;\n\n    data.peaks.clear();\n#ifdef DEBUG_DECONV\n    std::cout << \"temp_shapes[0].mz_position \" << temp_shapes[0].mz_position\n              << \"\\t dist \" << dist << \"\\tp_index \" << shape << std::endl;\n#endif\n    // while the peak's position is smaller than the last considered position\n    // take the peak for optimization\n    Size shape = 0;\n    while ((temp_shapes[0].mz_position + shape * dist <\n            data.positions[data.positions.size() - 1]) &&\n           (shape < temp_shapes.size()))\n    {\n      data.peaks.push_back(temp_shapes[shape]);\n#ifdef DEBUG_DECONV\n      std::cout << \"temp_shapes[0].mz_position + p_index*dist = \" << temp_shapes[0].mz_position + shape * dist << std::endl;\n#endif\n      shape++;\n    }\n  }\n\n}\n", "meta": {"hexsha": "0f41386ce7de6638990e7ebf87d5c72e988c685c", "size": 23972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePeakDeconvolution.cpp", "max_stars_repo_name": "raghav17083/OpenMS", "max_stars_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePeakDeconvolution.cpp", "max_issues_repo_name": "raghav17083/OpenMS", "max_issues_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePeakDeconvolution.cpp", "max_forks_repo_name": "raghav17083/OpenMS", "max_forks_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2598967298, "max_line_length": 186, "alphanum_fraction": 0.6019522777, "num_tokens": 5951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326705, "lm_q2_score": 0.01406362898028128, "lm_q1q2_score": 0.006320091485001082}}
{"text": "/*\n * Copyright (c) 2016, Vanderbilt University\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: Addisu Z. Taddese\n */\n\n#include <boost/bind.hpp>\n#include <boost/thread.hpp>\n#include <boost/thread/mutex.hpp>\n\n#include <ros/callback_queue.h>\n#include <ros/advertise_options.h>\n#include <ros/ros.h>\n\n#include <iostream>\n#include <vector>\n#include <cstdint>\n\n#include \"storm_gazebo_ros_magnet/dipole_magnet.h\"\n\nnamespace gazebo {\n\nDipoleMagnet::DipoleMagnet(): ModelPlugin() {\n  this->connect_count = 0;\n}\n\nDipoleMagnet::~DipoleMagnet() {\n  event::Events::DisconnectWorldUpdateBegin(this->update_connection);\n  if (this->should_publish) {\n    this->queue.clear();\n    this->queue.disable();\n    this->rosnode->shutdown();\n    this->callback_queue_thread.join();\n    delete this->rosnode;\n  }\n  if (this->mag){\n    DipoleMagnetContainer::Get().Remove(this->mag);\n  }\n}\n\nvoid DipoleMagnet::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) {\n  // Store the pointer to the model\n  this->model = _parent;\n  this->world = _parent->GetWorld();\n  gzdbg << \"Loading DipoleMagnet plugin\" << std::endl;\n\n  this->mag = std::make_shared<DipoleMagnetContainer::Magnet>();\n\n  // load parameters\n  this->robot_namespace = \"\";\n  if (_sdf->HasElement(\"robotNamespace\"))\n    this->robot_namespace = _sdf->GetElement(\"robotNamespace\")->Get<std::string>() + \"/\";\n\n  if(!_sdf->HasElement(\"bodyName\")) {\n    gzerr << \"DipoleMagnet plugin missing <bodyName>, cannot proceed\" << std::endl;\n    return;\n  }else {\n    this->link_name = _sdf->GetElement(\"bodyName\")->Get<std::string>();\n  }\n\n  this->link = this->model->GetLink(this->link_name);\n  if(!this->link){\n    gzerr << \"Error: link named \" << this->link_name << \" does not exist\" << std::endl;\n    return;\n  }\n\n  this->should_publish = false;\n  if (_sdf->HasElement(\"shouldPublish\"))\n  {\n    this->should_publish = _sdf->GetElement(\"shouldPublish\")->Get<bool>();\n  }\n\n  if (!_sdf->HasElement(\"updateRate\"))\n  {\n    gzmsg << \"DipoleMagnet plugin missing <updateRate>, defaults to 0.0\"\n        \" (as fast as possible)\" << std::endl;\n    this->update_rate = 0;\n  }\n  else\n    this->update_rate = _sdf->GetElement(\"updateRate\")->Get<double>();\n\n  if (_sdf->HasElement(\"calculate\")){\n    this->mag->calculate = _sdf->Get<bool>(\"calculate\");\n  } else\n    this->mag->calculate = true;\n\n  if (_sdf->HasElement(\"dipole_moment\")){\n    this->mag->moment = _sdf->Get<math::Vector3>(\"dipole_moment\");\n  }\n\n  if (_sdf->HasElement(\"xyzOffset\")){\n    this->mag->offset.pos = _sdf->Get<math::Vector3>(\"xyzOffset\");\n  }\n\n  if (_sdf->HasElement(\"rpyOffset\")){\n    math::Vector3 rpy_offset = _sdf->Get<math::Vector3>(\"rpyOffset\");\n    this->mag->offset.rot = math::Quaternion(rpy_offset);\n  }\n\n  if (this->should_publish) {\n    if (!_sdf->HasElement(\"topicNs\"))\n    {\n      gzmsg << \"DipoleMagnet plugin missing <topicNs>,\" \n          \"will publish on namespace \" << this->link_name << std::endl;\n    }\n    else {\n      this->topic_ns = _sdf->GetElement(\"topicNs\")->Get<std::string>();\n    }\n\n    if (!ros::isInitialized())\n    {\n      gzerr << \"A ROS node for Gazebo has not been initialized, unable to load \"\n        \"plugin. Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in \"\n        \"the gazebo_ros package. If you want to use this plugin without ROS, \"\n        \"set <shouldPublish> to false\" << std::endl;\n      return;\n    }\n\n    this->rosnode = new ros::NodeHandle(this->robot_namespace);\n    this->rosnode->setCallbackQueue(&this->queue);\n\n    this->wrench_pub = this->rosnode->advertise<geometry_msgs::WrenchStamped>(\n        this->topic_ns + \"/wrench\", 1,\n        boost::bind( &DipoleMagnet::Connect,this),\n        boost::bind( &DipoleMagnet::Disconnect,this), ros::VoidPtr(), &this->queue);\n    this->mfs_pub = this->rosnode->advertise<sensor_msgs::MagneticField>(\n        this->topic_ns + \"/mfs\", 1,\n        boost::bind( &DipoleMagnet::Connect,this),\n        boost::bind( &DipoleMagnet::Disconnect,this), ros::VoidPtr(), &this->queue);\n\n    // Custom Callback Queue\n    this->callback_queue_thread = boost::thread( boost::bind( &DipoleMagnet::QueueThread,this ) );\n  }\n\n  this->mag->model_id = this->model->GetId();\n\n  gzmsg << \"Loaded Gazebo dipole magnet plugin on \" << this->model->GetName() << std::endl;\n\n  DipoleMagnetContainer::Get().Add(this->mag);\n\n  // Listen to the update event. This event is broadcast every\n  // simulation iteration.\n  this->update_connection = event::Events::ConnectWorldUpdateBegin(\n      boost::bind(&DipoleMagnet::OnUpdate, this, _1));\n}\n\nvoid DipoleMagnet::Connect() {\n  this->connect_count++;\n}\n\nvoid DipoleMagnet::Disconnect() {\n  this->connect_count--;\n}\n\nvoid DipoleMagnet::QueueThread() {\n  static const double timeout = 0.01;\n\n  while (this->rosnode->ok())\n  {\n    this->queue.callAvailable(ros::WallDuration(timeout));\n  }\n}\n\n// Called by the world update start event\nvoid DipoleMagnet::OnUpdate(const common::UpdateInfo & /*_info*/) {\n\n  // Calculate the force from all other magnets\n  math::Pose p_self = this->link->GetWorldPose();\n  p_self.pos += -p_self.rot.RotateVector(this->mag->offset.pos);\n  p_self.rot *= this->mag->offset.rot.GetInverse();\n\n  this->mag->pose = p_self;\n\n  if (!this->mag->calculate)\n    return;\n\n  DipoleMagnetContainer& dp = DipoleMagnetContainer::Get();\n\n\n  math::Vector3 moment_world = p_self.rot.RotateVector(this->mag->moment);\n\n  math::Vector3 force(0, 0, 0);\n  math::Vector3 torque(0, 0, 0);\n  math::Vector3 mfs(0, 0, 0);\n  for(DipoleMagnetContainer::MagnetPtrV::iterator it = dp.magnets.begin(); it < dp.magnets.end(); it++){\n    std::shared_ptr<DipoleMagnetContainer::Magnet> mag_other = *it;\n    if (mag_other->model_id != this->mag->model_id) {\n      math::Pose p_other = mag_other->pose;\n      math::Vector3 m_other = p_other.rot.RotateVector(mag_other->moment);\n\n      math::Vector3 force_tmp;\n      math::Vector3 torque_tmp;\n      GetForceTorque(p_self, moment_world, p_other, m_other, force_tmp, torque_tmp);\n\n      force += force_tmp;\n      torque += torque_tmp;\n\n      math::Vector3 mfs_tmp;\n      GetMFS(p_self, p_other, m_other, mfs_tmp);\n\n      mfs += mfs_tmp;\n\n      this->link->AddForce(force_tmp);\n      this->link->AddTorque(torque_tmp);\n    }\n  }\n\n  this->PublishData(force, torque, mfs);\n}\n\nvoid DipoleMagnet::PublishData(\n    const math::Vector3& force,\n    const math::Vector3& torque,\n    const math::Vector3& mfs){\n  if(this->should_publish && this->connect_count > 0) {\n    // Rate control\n    common::Time cur_time = this->world->GetSimTime();\n    if (this->update_rate > 0 &&\n        (cur_time-this->last_time).Double() < (1.0/this->update_rate))\n      return;\n\n    this->lock.lock();\n    // copy data into wrench message\n    this->wrench_msg.header.frame_id = \"world\";\n    this->wrench_msg.header.stamp.sec = cur_time.sec;\n    this->wrench_msg.header.stamp.nsec = cur_time.nsec;\n\n    this->wrench_msg.wrench.force.x    = force.x;\n    this->wrench_msg.wrench.force.y    = force.y;\n    this->wrench_msg.wrench.force.z    = force.z;\n    this->wrench_msg.wrench.torque.x   = torque.x;\n    this->wrench_msg.wrench.torque.y   = torque.y;\n    this->wrench_msg.wrench.torque.z   = torque.z;\n\n\n    // now mfs\n    this->mfs_msg.header.frame_id = this->link_name;\n    this->mfs_msg.header.stamp.sec = cur_time.sec;\n    this->mfs_msg.header.stamp.nsec = cur_time.nsec;\n\n    this->mfs_msg.magnetic_field.x = mfs.x;\n    this->mfs_msg.magnetic_field.y = mfs.y;\n    this->mfs_msg.magnetic_field.z = mfs.z;\n\n\n    this->wrench_pub.publish(this->wrench_msg);\n    this->mfs_pub.publish(this->mfs_msg);\n\n    this->lock.unlock();\n  }\n}\n\n\nvoid DipoleMagnet::GetForceTorque(const math::Pose& p_self,\n    const math::Vector3& m_self,\n    const math::Pose& p_other,\n    const math::Vector3& m_other,\n    math::Vector3& force,\n    math::Vector3& torque) {\n\n  bool debug = false;\n  math::Vector3 p = p_self.pos - p_other.pos;\n  math::Vector3 p_unit = p/p.GetLength();\n\n  math::Vector3 m1 = m_other;\n  math::Vector3 m2 = m_self;\n  if (debug)\n    std::cout << \"p: \" << p << \" m1: \" << m1 << \" m2: \" << m2 << std::endl;\n\n  double K = 3.0*1e-7/pow(p.GetLength(), 4);\n  force = K * (m2 * (m1.Dot(p_unit)) +  m1 * (m2.Dot(p_unit)) +\n      p_unit*(m1.Dot(m2)) - 5*p_unit*(m1.Dot(p_unit))*(m2.Dot(p_unit)));\n\n  double Ktorque = 1e-7/pow(p.GetLength(), 3);\n  math::Vector3 B1 = Ktorque*(3*(m1.Dot(p_unit))*p_unit - m1);\n  torque = m2.Cross(B1);\n  if (debug)\n    std::cout << \"B: \" << B1 << \" K: \" << Ktorque << \" t: \" << torque << std::endl;\n}\n\nvoid DipoleMagnet::GetMFS(const math::Pose& p_self,\n    const math::Pose& p_other,\n    const math::Vector3& m_other,\n    math::Vector3& mfs) {\n\n  // sensor location\n  math::Vector3 p = p_self.pos - p_other.pos;\n  math::Vector3 p_unit = p/p.GetLength();\n\n  // Get the field at the sensor location\n  double K = 1e-7/pow(p.GetLength(), 3);\n  math::Vector3 B = K*(3*(m_other.Dot(p_unit))*p_unit - m_other);\n\n  // Rotate the B vector into the capsule/body frame\n  math::Vector3 B_body = p_self.rot.RotateVectorReverse(B);\n\n  // Assign vector\n  mfs.x = B_body[0];\n  mfs.y = B_body[1];\n  mfs.z = B_body[2];\n}\n\n// Register this plugin with the simulator\nGZ_REGISTER_MODEL_PLUGIN(DipoleMagnet)\n\n}\n", "meta": {"hexsha": "535c6c078904c620667bd6ddc2d62ee43e897f84", "size": 9663, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dipole_magnet.cc", "max_stars_repo_name": "mkrizmancic/storm_gazebo_ros_magnet", "max_stars_repo_head_hexsha": "1f6f5ab4e6d6983c717019b1383e5c8feade0421", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-07-23T20:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T04:02:02.000Z", "max_issues_repo_path": "src/dipole_magnet.cc", "max_issues_repo_name": "mkrizmancic/storm_gazebo_ros_magnet", "max_issues_repo_head_hexsha": "1f6f5ab4e6d6983c717019b1383e5c8feade0421", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-06-30T15:28:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T11:35:36.000Z", "max_forks_repo_path": "src/dipole_magnet.cc", "max_forks_repo_name": "mkrizmancic/storm_gazebo_ros_magnet", "max_forks_repo_head_hexsha": "1f6f5ab4e6d6983c717019b1383e5c8feade0421", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-11T11:30:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T07:55:20.000Z", "avg_line_length": 30.2915360502, "max_line_length": 104, "alphanum_fraction": 0.6586981269, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710537, "lm_q2_score": 0.02976009502162061, "lm_q1q2_score": 0.006311187768788926}}
{"text": "#ifndef STAN_IO_DUMP_HPP\n#define STAN_IO_DUMP_HPP\n\n#include <stan/io/validate_zero_buf.hpp>\n#include <stan/io/var_context.hpp>\n#include <stan/math/prim.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/throw_exception.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/type_traits/is_arithmetic.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n#include <cctype>\n\nnamespace stan {\nnamespace io {\n\nusing Eigen::Dynamic;\n/**\n * Reads data from S-plus dump format.\n *\n * A <code>dump_reader</code> parses data from the S-plus dump\n * format, a human-readable ASCII representation of arbitrarily\n * dimensioned arrays of integers and arrays of floating point\n * values.\n *\n * <p>Stan's dump reader is limited to reading\n * integers, scalars and arrays of arbitrary dimensionality of\n * integers and scalars.  It is able to read from a file\n * consisting of a sequence of dumped variables.\n *\n * <p>There cannot be any <code>NA</code>\n * (i.e., undefined) values, because these cannot be\n * represented as <code>double</code> values.\n *\n * <p>The dump reader class follows a standard scanner pattern.\n * The method <code>next()</code> is called to scan the next\n * input.  The type, dimensions, and values of the input is then\n * available through method calls.  Here, the type is either\n * double or integer, and the values are the name of the variable\n * and its array of values.  If there is a single value, the\n * dimension array is empty.  For a list, the dimension\n * array contains a single entry for the number of values.\n * For an array, the dimensions are the dimensions of the array.\n *\n * <p>Reads are performed in an \"S-compatible\" mode whereby\n * a string such as \"1\" or \"-127\" denotes and integer, whereas\n * a string such as \"1.\" or \"0.9e-5\" represents a floating\n * point value.\n *\n * <p>The dump reader treats \"integer(x)\" as an array of zeros\n * (type being integer and length x), where x any non-negative\n * integers and x can be omitted to indicate zero-length.\n * So the following are all legitimate: * \"x <- integer()\",\n * \"x <- integer(0) \", and \"x <- integer(3)\". For array of zeros\n * of type double, we can replace the above \"integer\" with \"double\".\n * This is mainly for the purpose of supporting zero-size arrays\n * such as \"x <- structure(integer(0), .Dim = c(2, 0))\".\n *\n * <p>For dumping, arrays are indexed in last-index major fashion,\n * which corresponds to column-major order for matrices\n * represented as two-dimensional arrays.  As a result, the first\n * indices change fastest.  For instance, if there is an\n * three-dimensional array <code>x</code> with dimensions\n * <code>[2,2,2]</code>, then there are 8 values, provided in the\n * order\n *\n * <p><code>[0,0,0]</code>,\n * <code>[1,0,0]</code>,\n * <code>[0,1,0]</code>,\n * <code>[1,1,0]</code>,\n * <code>[0,0,1]</code>,\n * <code>[1,0,1]</code>,\n * <code>[0,1,1]</code>,\n * <code>[1,1,1]</code>.\n *\n * definitions ::= definition+\n *\n * definition ::= name (\"<-\" | '=') value optional_semicolon\n *\n * name ::= char*\n *        | ''' char* '''\n *        | '\"' char* '\"'\n *\n * value ::= value<int> | value<double>\n *\n * value<T> ::= T\n *            | seq<T>\n *            | zero_array<T>\n *            | \"structure\" '(' seq<T> ',' \".Dim\" '=' seq<int> ')'\n *            | \"structure\" '(' zero_array<T> ',' \".Dim\" '=' seq<int> ')'\n *\n * seq<int> ::= int ':' int\n *            | cseq<int>\n *\n * seq<double> ::= cseq<double>\n *\n * cseq<T> ::= 'c' '(' vseq<T> ')'\n *\n * vseq<T> ::= T\n *           | T ',' vseq<T>\n *\n * zero_array<integer> ::= \"integer\"<non negative int?>\n *\n * zero_array<double> ::= \"double\"<non negative int?>\n *\n */\nclass dump_reader {\n private:\n  std::string buf_;\n  std::string name_;\n  std::vector<int> stack_i_;\n  std::vector<double> stack_r_;\n  std::vector<size_t> dims_;\n  std::istream& in_;\n\n  bool scan_single_char(char c_expected) {\n    int c = in_.peek();\n    if (in_.fail())\n      return false;\n    if (c != c_expected)\n      return false;\n    char c_skip;\n    in_.get(c_skip);\n    return true;\n  }\n\n  bool scan_optional_long() {\n    if (scan_single_char('l'))\n      return true;\n    else if (scan_single_char('L'))\n      return true;\n    else\n      return false;\n  }\n\n  bool scan_char(char c_expected) {\n    char c;\n    in_ >> c;\n    if (in_.fail())\n      return false;\n    if (c != c_expected) {\n      in_.putback(c);\n      return false;\n    }\n    return true;\n  }\n\n  bool scan_name_unquoted() {\n    char c;\n    in_ >> c;\n    if (in_.fail())\n      return false;\n    if (!std::isalpha(c))\n      return false;\n    name_.push_back(c);\n    while (in_.get(c)) {  // get turns off auto space skip\n      if (std::isalpha(c) || std::isdigit(c) || c == '_' || c == '.') {\n        name_.push_back(c);\n      } else {\n        in_.putback(c);\n        return true;\n      }\n    }\n    return true;  // but hit eos\n  }\n\n  bool scan_name() {\n    if (scan_char('\"')) {\n      if (!scan_name_unquoted())\n        return false;\n      if (!scan_char('\"'))\n        return false;\n    } else if (scan_char('\\'')) {\n      if (!scan_name_unquoted())\n        return false;\n      if (!scan_char('\\''))\n        return false;\n    } else {\n      if (!scan_name_unquoted())\n        return false;\n    }\n    return true;\n  }\n\n  bool scan_chars(const char* s, bool case_sensitive = true) {\n    for (size_t i = 0; s[i]; ++i) {\n      char c;\n      if (!(in_ >> c)) {\n        for (size_t j = 1; j < i; ++j)\n          in_.putback(s[i - j]);\n        return false;\n      }\n      // all ASCII, so toupper is OK\n      if ((case_sensitive && c != s[i])\n          || (!case_sensitive && ::toupper(c) != ::toupper(s[i]))) {\n        in_.putback(c);\n        for (size_t j = 1; j < i; ++j)\n          in_.putback(s[i - j]);\n        return false;\n      }\n    }\n    return true;\n  }\n\n  bool scan_chars(std::string s, bool case_sensitive = true) {\n    for (size_t i = 0; i < s.size(); ++i) {\n      char c;\n      if (!(in_ >> c)) {\n        for (size_t j = 1; j < i; ++j)\n          in_.putback(s[i - j]);\n        return false;\n      }\n      // all ASCII, so toupper is OK\n      if ((case_sensitive && c != s[i])\n          || (!case_sensitive && ::toupper(c) != ::toupper(s[i]))) {\n        in_.putback(c);\n        for (size_t j = 1; j < i; ++j)\n          in_.putback(s[i - j]);\n        return false;\n      }\n    }\n    return true;\n  }\n\n  size_t scan_dim() {\n    char c;\n    buf_.clear();\n    while (in_.get(c)) {\n      if (std::isspace(c))\n        continue;\n      if (std::isdigit(c)) {\n        buf_.push_back(c);\n      } else {\n        in_.putback(c);\n        break;\n      }\n    }\n    scan_optional_long();\n    size_t d = 0;\n    try {\n      d = boost::lexical_cast<size_t>(buf_);\n    } catch (const boost::bad_lexical_cast& exc) {\n      std::string msg = \"value \" + buf_ + \" beyond array dimension range\";\n      BOOST_THROW_EXCEPTION(std::invalid_argument(msg));\n    }\n    return d;\n  }\n\n  int scan_int() {\n    char c;\n    buf_.clear();\n    while (in_.get(c)) {\n      if (std::isspace(c))\n        continue;\n      if (std::isdigit(c)) {\n        buf_.push_back(c);\n      } else {\n        in_.putback(c);\n        break;\n      }\n    }\n    return (get_int());\n  }\n\n  int get_int() {\n    int n = 0;\n    try {\n      n = boost::lexical_cast<int>(buf_);\n    } catch (const boost::bad_lexical_cast& exc) {\n      std::string msg = \"value \" + buf_ + \" beyond int range\";\n      BOOST_THROW_EXCEPTION(std::invalid_argument(msg));\n    }\n    return n;\n  }\n\n  double scan_double() {\n    double x = 0;\n    try {\n      x = boost::lexical_cast<double>(buf_);\n      if (x == 0)\n        validate_zero_buf(buf_);\n    } catch (const boost::bad_lexical_cast& exc) {\n      std::string msg = \"value \" + buf_ + \" beyond numeric range\";\n      BOOST_THROW_EXCEPTION(std::invalid_argument(msg));\n    }\n    return x;\n  }\n\n  // scan number stores number or throws bad lexical cast exception\n  void scan_number(bool negate_val) {\n    // must take longest first!\n    if (scan_chars(\"Inf\")) {\n      scan_chars(\"inity\");  // read past if there\n      stack_r_.push_back(negate_val ? -std::numeric_limits<double>::infinity()\n                                    : std::numeric_limits<double>::infinity());\n      return;\n    }\n    if (scan_chars(\"NaN\", false)) {\n      stack_r_.push_back(std::numeric_limits<double>::quiet_NaN());\n      return;\n    }\n\n    char c;\n    bool is_double = false;\n    buf_.clear();\n    while (in_.get(c)) {\n      if (std::isdigit(c)) {  // before pre-scan || c == '-' || c == '+') {\n        buf_.push_back(c);\n      } else if (c == '.' || c == 'e' || c == 'E' || c == '-' || c == '+') {\n        is_double = true;\n        buf_.push_back(c);\n      } else {\n        in_.putback(c);\n        break;\n      }\n    }\n    if (!is_double && stack_r_.size() == 0) {\n      int n = get_int();\n      stack_i_.push_back(negate_val ? -n : n);\n      scan_optional_long();\n    } else {\n      for (size_t j = 0; j < stack_i_.size(); ++j)\n        stack_r_.push_back(static_cast<double>(stack_i_[j]));\n      stack_i_.clear();\n      double x = scan_double();\n      stack_r_.push_back(negate_val ? -x : x);\n    }\n  }\n\n  void scan_number() {\n    char c;\n    while (in_.get(c)) {\n      if (std::isspace(c))\n        continue;\n      in_.putback(c);\n      break;\n    }\n    bool negate_val = scan_char('-');\n    if (!negate_val)\n      scan_char('+');  // flush leading +\n    return scan_number(negate_val);\n  }\n\n  bool scan_zero_integers() {\n    if (!scan_char('('))\n      return false;\n    if (scan_char(')')) {\n      dims_.push_back(0U);\n      return true;\n    }\n    int s = scan_int();\n    if (s < 0)\n      return false;\n    for (int i = 0; i < s; ++i) {\n      stack_i_.push_back(0);\n    }\n    if (!scan_char(')'))\n      return false;\n    dims_.push_back(s);\n    return true;\n  }\n\n  bool scan_zero_doubles() {\n    if (!scan_char('('))\n      return false;\n    if (scan_char(')')) {\n      dims_.push_back(0U);\n      return true;\n    }\n    int s = scan_int();\n    if (s < 0)\n      return false;\n    for (int i = 0; i < s; ++i) {\n      stack_r_.push_back(0);\n    }\n    if (!scan_char(')'))\n      return false;\n    dims_.push_back(s);\n    return true;\n  }\n\n  bool scan_seq_value() {\n    if (!scan_char('('))\n      return false;\n    if (scan_char(')')) {\n      dims_.push_back(0U);\n      return true;\n    }\n    scan_number();  // first entry\n    while (scan_char(',')) {\n      scan_number();\n    }\n    dims_.push_back(stack_r_.size() + stack_i_.size());\n    return scan_char(')');\n  }\n\n  bool scan_struct_value() {\n    if (!scan_char('('))\n      return false;\n    if (scan_chars(\"integer\")) {\n      scan_zero_integers();\n    } else if (scan_chars(\"double\")) {\n      scan_zero_doubles();\n    } else if (scan_char('c')) {\n      scan_seq_value();\n    } else {\n      int start = scan_int();\n      if (!scan_char(':'))\n        return false;\n      int end = scan_int();\n      if (start <= end) {\n        for (int i = start; i <= end; ++i)\n          stack_i_.push_back(i);\n      } else {\n        for (int i = start; i >= end; --i)\n          stack_i_.push_back(i);\n      }\n    }\n    dims_.clear();\n    if (!scan_char(','))\n      return false;\n    if (!scan_char('.'))\n      return false;\n    if (!scan_chars(\"Dim\"))\n      return false;\n    if (!scan_char('='))\n      return false;\n    if (scan_char('c')) {\n      if (!scan_char('('))\n        return false;\n      size_t dim = scan_dim();\n      dims_.push_back(dim);\n      while (scan_char(',')) {\n        dim = scan_dim();\n        dims_.push_back(dim);\n      }\n      if (!scan_char(')'))\n        return false;\n    } else {\n      size_t start = scan_dim();\n      if (!scan_char(':'))\n        return false;\n      size_t end = scan_dim();\n      if (start < end) {\n        for (size_t i = start; i <= end; ++i)\n          dims_.push_back(i);\n      } else {\n        for (size_t i = start; i >= end; --i)\n          dims_.push_back(i);\n      }\n    }\n    if (!scan_char(')'))\n      return false;\n    return true;\n  }\n\n  bool scan_value() {\n    if (scan_char('c'))\n      return scan_seq_value();\n    if (scan_chars(\"integer\"))\n      return scan_zero_integers();\n    if (scan_chars(\"double\"))\n      return scan_zero_doubles();\n    if (scan_chars(\"structure\"))\n      return scan_struct_value();\n    scan_number();\n    if (!scan_char(':'))\n      return true;\n    if (stack_i_.size() != 1)\n      return false;\n    scan_number();\n    if (stack_i_.size() != 2)\n      return false;\n    int start = stack_i_[0];\n    int end = stack_i_[1];\n    stack_i_.clear();\n    if (start <= end) {\n      for (int i = start; i <= end; ++i)\n        stack_i_.push_back(i);\n    } else {\n      for (int i = start; i >= end; --i)\n        stack_i_.push_back(i);\n    }\n    dims_.push_back(stack_i_.size());\n    return true;\n  }\n\n public:\n  /**\n   * Construct a reader for the specified input stream.\n   *\n   * @param in Input stream reference from which to read.\n   */\n  explicit dump_reader(std::istream& in) : in_(in) {}\n\n  /**\n   * Destroy this reader.\n   */\n  ~dump_reader() {}\n\n  /**\n   * Return the name of the most recently read variable.\n   *\n   * @return Name of most recently read variable.\n   */\n  std::string name() { return name_; }\n\n  /**\n   * Return the dimensions of the most recently\n   * read variable.\n   *\n   * @return Last dimensions.\n   */\n  std::vector<size_t> dims() { return dims_; }\n\n  /**\n   * Checks if the last item read is integer.\n   *\n   * Return <code>true</code> if the value(s) in the most recently\n   * read item are integer values and <code>false</code> if\n   * they are floating point.\n   */\n  bool is_int() {\n    // return stack_i_.size() > 0;\n    return stack_r_.size() == 0;\n  }\n\n  /**\n   * Returns the integer values from the last item if the\n   * last item read was an integer and the empty vector otherwise.\n   *\n   * @return Integer values of last item.\n   */\n  std::vector<int> int_values() { return stack_i_; }\n\n  /**\n   * Returns the floating point values from the last item if the\n   * last item read contained floating point values and the empty\n   * vector otherwise.\n   *\n   * @return Floating point values of last item.\n   */\n  std::vector<double> double_values() { return stack_r_; }\n\n  /**\n   * Read the next value from the input stream, returning\n   * <code>true</code> if successful and <code>false</code> if no\n   * further input may be read.\n   *\n   * @return Return <code>true</code> if a fresh variable was read.\n   * @throws bad_cast if bad number values encountered.\n   */\n  bool next() {\n    stack_r_.clear();\n    stack_i_.clear();\n    dims_.clear();\n    name_.erase();\n    if (!scan_name())  // set name\n      return false;\n    if (!scan_char('<'))  // set <-\n      return false;\n    if (!scan_char('-'))\n      return false;\n    try {\n      bool okSyntax = scan_value();  // set stack_r_, stack_i_, dims_\n      if (!okSyntax) {\n        std::string msg = \"syntax error\";\n        BOOST_THROW_EXCEPTION(std::invalid_argument(msg));\n      }\n    } catch (const std::invalid_argument& e) {\n      std::string msg = \"data \" + name_ + \" \" + e.what();\n      BOOST_THROW_EXCEPTION(std::invalid_argument(msg));\n    }\n    return true;\n  }\n};\n\n/**\n * Represents named arrays with dimensions.\n *\n * A dump object represents a dump of named arrays with dimensions.\n * The arrays may have any dimensionality.  The values for an array\n * are typed to double or int.\n *\n * <p>See <code>dump_reader</code> for more information on the format.\n *\n * <p>Dump objects are created from reading dump files from an\n * input stream.\n *\n * <p>The dimensions and values of variables\n * may be accessed by name.\n */\nclass dump : public stan::io::var_context {\n private:\n  std::map<std::string, std::pair<std::vector<double>, std::vector<size_t> > >\n      vars_r_;\n  std::map<std::string, std::pair<std::vector<int>, std::vector<size_t> > >\n      vars_i_;\n  std::vector<double> const empty_vec_r_;\n  std::vector<int> const empty_vec_i_;\n  std::vector<size_t> const empty_vec_ui_;\n  /**\n   * Return <code>true</code> if this dump contains the specified\n   * variable name is defined in the real values. This method\n   * returns <code>false</code> if the values are all integers.\n   *\n   * @param name Variable name to test.\n   * @return <code>true</code> if the variable exists in the\n   * real values of the dump.\n   */\n  bool contains_r_only(const std::string& name) const {\n    return vars_r_.find(name) != vars_r_.end();\n  }\n\n public:\n  /**\n   * Construct a dump object from the specified input stream.\n   *\n   * <b>Warning:</b> This method does not close the input stream.\n   *\n   * @param in Input stream from which to read.\n   */\n  explicit dump(std::istream& in) {\n    dump_reader reader(in);\n    while (reader.next()) {\n      if (reader.is_int()) {\n        vars_i_[reader.name()]\n            = std::pair<std::vector<int>, std::vector<size_t> >(\n                reader.int_values(), reader.dims());\n\n      } else {\n        vars_r_[reader.name()]\n            = std::pair<std::vector<double>, std::vector<size_t> >(\n                reader.double_values(), reader.dims());\n      }\n    }\n  }\n\n  /**\n   * Return <code>true</code> if this dump contains the specified\n   * variable name is defined. This method returns <code>true</code>\n   * even if the values are all integers.\n   *\n   * @param name Variable name to test.\n   * @return <code>true</code> if the variable exists.\n   */\n  bool contains_r(const std::string& name) const {\n    return contains_r_only(name) || contains_i(name);\n  }\n\n  /**\n   * Return <code>true</code> if this dump contains an integer\n   * valued array with the specified name.\n   *\n   * @param name Variable name to test.\n   * @return <code>true</code> if the variable name has an integer\n   * array value.\n   */\n  bool contains_i(const std::string& name) const {\n    return vars_i_.find(name) != vars_i_.end();\n  }\n\n  /**\n   * Return the double values for the variable with the specified\n   * name or null.\n   *\n   * @param name Name of variable.\n   * @return Values of variable.\n   */\n  std::vector<double> vals_r(const std::string& name) const {\n    if (contains_r_only(name)) {\n      return (vars_r_.find(name)->second).first;\n    } else if (contains_i(name)) {\n      std::vector<int> vec_int = (vars_i_.find(name)->second).first;\n      std::vector<double> vec_r(vec_int.size());\n      for (size_t ii = 0; ii < vec_int.size(); ii++) {\n        vec_r[ii] = vec_int[ii];\n      }\n      return vec_r;\n    }\n    return empty_vec_r_;\n  }\n\n  /**\n   * Return the dimensions for the double variable with the specified\n   * name.\n   *\n   * @param name Name of variable.\n   * @return Dimensions of variable.\n   */\n  std::vector<size_t> dims_r(const std::string& name) const {\n    if (contains_r_only(name)) {\n      return (vars_r_.find(name)->second).second;\n    } else if (contains_i(name)) {\n      return (vars_i_.find(name)->second).second;\n    }\n    return empty_vec_ui_;\n  }\n\n  /**\n   * Return the integer values for the variable with the specified\n   * name.\n   *\n   * @param name Name of variable.\n   * @return Values.\n   */\n  std::vector<int> vals_i(const std::string& name) const {\n    if (contains_i(name)) {\n      return (vars_i_.find(name)->second).first;\n    }\n    return empty_vec_i_;\n  }\n\n  /**\n   * Return the dimensions for the integer variable with the specified\n   * name.\n   *\n   * @param name Name of variable.\n   * @return Dimensions of variable.\n   */\n  std::vector<size_t> dims_i(const std::string& name) const {\n    if (contains_i(name)) {\n      return (vars_i_.find(name)->second).second;\n    }\n    return empty_vec_ui_;\n  }\n\n  /**\n   * Return a list of the names of the floating point variables in\n   * the dump.\n   *\n   * @param names Vector to store the list of names in.\n   */\n  virtual void names_r(std::vector<std::string>& names) const {\n    names.resize(0);\n    for (std::map<std::string, std::pair<std::vector<double>,\n                                         std::vector<size_t> > >::const_iterator\n             it\n         = vars_r_.begin();\n         it != vars_r_.end(); ++it)\n      names.push_back((*it).first);\n  }\n\n  /**\n   * Return a list of the names of the integer variables in\n   * the dump.\n   *\n   * @param names Vector to store the list of names in.\n   */\n  virtual void names_i(std::vector<std::string>& names) const {\n    names.resize(0);\n    for (std::map<std::string, std::pair<std::vector<int>,\n                                         std::vector<size_t> > >::const_iterator\n             it\n         = vars_i_.begin();\n         it != vars_i_.end(); ++it)\n      names.push_back((*it).first);\n  }\n\n  /**\n   * Check variable dimensions against variable declaration.\n   *\n   * @param stage stan program processing stage\n   * @param name variable name\n   * @param base_type declared stan variable type\n   * @param dims variable dimensions\n   * @throw std::runtime_error if mismatch between declared\n   *        dimensions and dimensions found in context.\n   */\n  void validate_dims(const std::string& stage, const std::string& name,\n                     const std::string& base_type,\n                     const std::vector<size_t>& dims_declared) const {\n    bool is_int_type = base_type == \"int\";\n    if (is_int_type) {\n      if (!contains_i(name)) {\n        std::stringstream msg;\n        msg << (contains_r(name) ? \"int variable contained non-int values\"\n                                 : \"variable does not exist\")\n            << \"; processing stage=\" << stage << \"; variable name=\" << name\n            << \"; base type=\" << base_type;\n        throw std::runtime_error(msg.str());\n      }\n    } else {\n      if (!contains_r(name)) {\n        std::stringstream msg;\n        msg << \"variable does not exist\"\n            << \"; processing stage=\" << stage << \"; variable name=\" << name\n            << \"; base type=\" << base_type;\n        throw std::runtime_error(msg.str());\n      }\n    }\n    std::vector<size_t> dims = dims_r(name);\n    if (dims.size() != dims_declared.size()) {\n      std::stringstream msg;\n      msg << \"mismatch in number dimensions declared and found in context\"\n          << \"; processing stage=\" << stage << \"; variable name=\" << name\n          << \"; dims declared=\";\n      dims_msg(msg, dims_declared);\n      msg << \"; dims found=\";\n      dims_msg(msg, dims);\n      throw std::runtime_error(msg.str());\n    }\n    for (size_t i = 0; i < dims.size(); ++i) {\n      if (dims_declared[i] != dims[i]) {\n        std::stringstream msg;\n        msg << \"mismatch in dimension declared and found in context\"\n            << \"; processing stage=\" << stage << \"; variable name=\" << name\n            << \"; position=\" << i << \"; dims declared=\";\n        dims_msg(msg, dims_declared);\n        msg << \"; dims found=\";\n        dims_msg(msg, dims);\n        throw std::runtime_error(msg.str());\n      }\n    }\n  }\n\n  /**\n   * Remove variable from the object.\n   *\n   * @param name Name of the variable to remove.\n   * @return If variable is removed returns <code>true</code>, else\n   *   returns <code>false</code>.\n   */\n  bool remove(const std::string& name) {\n    return (vars_i_.erase(name) > 0) || (vars_r_.erase(name) > 0);\n  }\n};\n\n}  // namespace io\n\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "81c0bf2805860892f26e4a02b4e87cd0d4771a79", "size": 23213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/io/dump.hpp", "max_stars_repo_name": "sidkapoor97/stan", "max_stars_repo_head_hexsha": "70b2b23f2312320b1008d776fdf44461ae2f52ba", "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/io/dump.hpp", "max_issues_repo_name": "sidkapoor97/stan", "max_issues_repo_head_hexsha": "70b2b23f2312320b1008d776fdf44461ae2f52ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/io/dump.hpp", "max_forks_repo_name": "sidkapoor97/stan", "max_forks_repo_head_hexsha": "70b2b23f2312320b1008d776fdf44461ae2f52ba", "max_forks_repo_licenses": ["BSD-3-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.5688836105, "max_line_length": 80, "alphanum_fraction": 0.575625727, "num_tokens": 6140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592736, "lm_q2_score": 0.028870908617445887, "lm_q1q2_score": 0.006274732002010204}}
{"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 propagator for a given material at given temperature and timestep\n#define TBB_PREVIEW_GLOBAL_CONTROL true\n#include <iostream>\n#include <fstream>\n#include <boost/filesystem.hpp>\n#include <boost/mpi.hpp>\n#include <cmakevars.hpp>\n#include <constants.hpp>\n#include <utilities.hpp>\n#include <structures.hpp>\n#include <bulk_hdf5.hpp>\n#include <io_utils.hpp>\n#include <collision_operator.hpp>\n#include <vasp_io.hpp>\n#include <tbb/global_control.h>\n#include <chrono>\n\nint main(int argc, char** argv) {\n    boost::mpi::environment env;\n    boost::mpi::communicator world;\n\n    /// Record start time\n    auto begin = std::chrono::high_resolution_clock::now();\n\n    /// MPI info\n    std::size_t master = 0;\n    std::size_t my_id = world.rank();\n    std::size_t nprocs = world.size();\n\n    // Temperature at which calculate the propagator\n    double Tambient = -42.0;\n    // Time step for the propagator P = exp(dt*B) where B is the collision\n    // operator in energy\n    double dt = -1.0;\n\n    std::size_t nthreadsTBB = 1;\n\n    // Path to the HDF5 file.\n    std::string h5filename, anhIFCfile;\n\n    if (!(argc == 6 or argc == 5)) {\n        std::cout << \"USAGE 0: PropagatorBuilder <inputfile.hdf5>  \"\n                     \"FORCE_CONSTANTS_3RD Temperature[Kelvin] time_step[ps] \"\n                     \"nthreads[optional]\"\n                  << std::endl;\n        world.abort(1);\n    }\n\n    else {\n        h5filename = argv[1];\n        anhIFCfile = argv[2];\n        Tambient = atof(argv[3]);\n        dt = atof(argv[4]);\n        if (Tambient <= 0.0) {\n            std::cerr << \"ERROR: Tambient must be positive (\" << Tambient\n                      << \" provided).\" << std::endl;\n            world.abort(1);\n        }\n        if (dt <= 0.0) {\n            std::cerr << \"ERROR: dt must be positive (\" << dt << \" provided).\"\n                      << std::endl;\n            world.abort(1);\n        }\n    }\n\n    if (argc == 6) {\n        nthreadsTBB = boost::lexical_cast<std::size_t>(argv[5]);\n        if (nthreadsTBB < 1) {\n            std::cerr << \"ERROR: nthreads must be positive (\" << nthreadsTBB\n                      << \" provided).\" << std::endl;\n            world.abort(1);\n        }\n    }\n\n    /// Init TBB threads with user defined number of threads or single one as\n    /// default.\n    tbb::global_control control(tbb::global_control::max_allowed_parallelism,\n                                nthreadsTBB);\n\n    if (my_id == master) {\n        std::cout << \"***********************************\" << std::endl;\n        std::cout << \"This is ALMA/PropagatorBuilder version \"\n                  << ALMA_VERSION_MAJOR << \".\" << ALMA_VERSION_MINOR\n                  << std::endl;\n        std::cout << \"***********************************\" << std::endl;\n        std::cout << \"#input variables:\\n\"\n                  << \"-h5filename: \" << h5filename << \"\\n-3rdIFC: \" << anhIFCfile\n                  << \"\\n-Tambient: \" << Tambient << \" K\\n-dt: \" << dt << \" ps\"\n                  << std::endl;\n        std::cout << \"#MPI procs:\\n\" << nprocs << std::endl;\n        std::cout << \"#TBB processes\\n\" << nthreadsTBB << std::endl;\n    }\n    // Create name of outputfile\n    boost::filesystem::path hdf5_path{h5filename};\n    std::stringstream output_file_builder;\n    output_file_builder << hdf5_path.stem().string() << \"_\" << Tambient << \"K_\"\n                        << dt << \"ps\";\n    std::string output_file = output_file_builder.str();\n\n    // Obtain phonon data and anharmonic force constants\n    if (my_id == master)\n        std::cout << \"Reading \" << h5filename << std::endl;\n\n    if (!(boost::filesystem::exists(hdf5_path))) {\n        std::cout << \"ERROR:\" << std::endl;\n        std::cout << \"HDF5 file \" << hdf5_path << \" does not exist.\"\n                  << std::endl;\n        world.abort(1);\n    }\n\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n\n    auto hdf5_data = alma::load_bulk_hdf5(hdf5_path.string().c_str(), world);\n    auto poscar = std::move(std::get<1>(hdf5_data));\n    auto syms = std::move(std::get<2>(hdf5_data));\n    auto grid = std::move(std::get<3>(hdf5_data));\n    auto processes = std::move(std::get<4>(hdf5_data));\n    \n    processes.release(); \n   \n    if (my_id == master)\n        std::cout << \"Reading \" << anhIFCfile << std::endl;\n    auto anhIFC = alma::load_FORCE_CONSTANTS_3RD(anhIFCfile.c_str(), *poscar);\n\n    auto t2 = std::chrono::high_resolution_clock::now();\n\n    if (my_id == master)\n        std::cout << std::endl << \"Generating scattering operator\" << std::endl;\n\n    /// We are building B matrix (liniarized collision operator in energy\n    /// formulation) from almaBTE database and extending it to fullBZ using\n    /// symmetry and permutation. B is a huge matrix (it can be dozens of GBs)\n    auto B =\n        get_collision_operator_dense(*grid, *poscar, *anhIFC, Tambient, world);\n    alma::save_P(output_file + \".B.eigen.bin\",B,world);    \n    auto t3 = std::chrono::high_resolution_clock::now();\n\n    if (my_id == master)\n        std::cout << std::endl << \"Getting propagator\" << std::endl;\n    /// Propagator calculation; this is done through krylov subspace\n    Eigen::MatrixXd P;\n    alma::build_P(B, P, dt, world);\n\n    auto t4 = std::chrono::high_resolution_clock::now();\n\n    if (my_id == master)\n        std::cout << std::endl << \"Storing propagator\" << std::endl;\n\n    alma::save_P(output_file + \".P.eigen.bin\", P, world);\n\n    world.barrier();\n\n    auto end = std::chrono::high_resolution_clock::now();\n\n    if (my_id == master) {\n        std::cout << std::endl << \"[DONE.]\" << std::endl;\n        std::cout << \"###############\\nGLOBAL TIMING\\n###############\\n\";\n        auto begin_c = std::chrono::system_clock::to_time_t(begin);\n        std::cout << \"#\" << std::endl\n                  << \"Started at \"\n                  << std::put_time(std::localtime(&begin_c), \"%c\") << std::endl;\n        auto end_c = std::chrono::system_clock::to_time_t(end);\n        std::cout << \"#\" << std::endl\n                  << \"Ended at \" << std::put_time(std::localtime(&end_c), \"%c\")\n                  << std::endl;\n        std::cout\n            << \"#\" << std::endl\n            << \"Total elapsed time: \"\n            << (static_cast<std::chrono::duration<double>>(end - begin)).count()\n            << \" s\\n\";\n        std::cout\n            << \"###############\\nTIME CONSUMED BY EACH TASK\\n###############\\n\";\n        std::cout\n            << \"#HDF5 and 3rdIFC processing:         : \"\n            << (static_cast<std::chrono::duration<double>>(t2 - t1)).count()\n            << \" s\\n\";\n        std::cout\n            << \"#Scattering operator generation      : \"\n            << (static_cast<std::chrono::duration<double>>(t3 - t2)).count()\n            << \" s\\n\";\n        std::cout\n            << \"#Calculating propagator (matrix exp) : \"\n            << (static_cast<std::chrono::duration<double>>(t4 - t3)).count()\n            << \" s\\n\";\n        std::cout\n            << \"#Storing propagator                  : \"\n            << (static_cast<std::chrono::duration<double>>(end - t4)).count()\n            << \" s\\n\";\n    }\n    world.barrier();\n    return 0;\n}\n", "meta": {"hexsha": "ae4530a804c9769942c7325673305f997c680f7d", "size": 7710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PropagatorBuilder.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/PropagatorBuilder.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/PropagatorBuilder.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.8899521531, "max_line_length": 81, "alphanum_fraction": 0.5538261997, "num_tokens": 2001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091976292927183, "lm_q2_score": 0.02716923005873027, "lm_q1q2_score": 0.00627391216413284}}
{"text": "#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n\n#include <pgsql/libpq-fe.h>\n\n#include \"PJMCoords.h\"\n\n#define HTMfunc_Pr 3.1415926535897932385E0 / 180.0\n\nstruct db_entry {\n  std::string schema_name;\n  std::string table_name;\n  std::string owner;\n  std::string host;\n  int port;\n\n  db_entry(std::string _schema_name, std::string _table_name,\n           std::string _owner, std::string _host, int _port) {\n    schema_name = _schema_name;\n    table_name = _table_name;\n    owner = _owner;\n    host = _host;\n    port = _port;\n  }\n};\n\nstd::unordered_map<int, std::shared_ptr<struct db_entry>> db_index;\nvoid make_gaia_db(int hpx, std::shared_ptr<struct db_entry> entry);\n\nvoid load_db_index(std::string filename) {\n  std::ifstream index_file(filename);\n\n  for (std::string line; getline(index_file, line);) {\n    // std::cout << line << std::endl;\n\n    std::vector<std::string> columns;\n    boost::split(columns, line, [](char c) { return c == '|'; });\n\n    // extract the database connection info based on the healpix index\n    if (columns.size() == 6) {\n      int hpx;\n\n      sscanf(columns[1].c_str(), \"gaia_source_%d\", &hpx);\n\n      std::shared_ptr<struct db_entry> entry(\n          new db_entry(columns[0], columns[1], columns[3], columns[4],\n                       std::stoi(columns[5])));\n\n      db_index.insert(std::make_pair(hpx, entry));\n    }\n  }\n\n  std::cout << \"PostgreSQL HEALPix index contains \" << db_index.size()\n            << \" entries.\" << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n  // load the db healpix index file\n  load_db_index(\"gaiadr2-table.dat\");\n\n// go through the GAIA db once and make a cache\n#pragma omp parallel\n  {\n#pragma omp single\n    {\n      for (auto &it : db_index) {\n#pragma omp task\n        {\n          int hpx = it.first;\n          auto entry = it.second;\n          make_gaia_db(hpx, entry);\n        }\n      }\n    }\n  }\n}\n\nvoid make_gaia_db(int hpx, std::shared_ptr<struct db_entry> entry) {\n  OmniCoords coords;\n  coords.change_sol_pos(8.3, 0.027);\n\n  std::cout << \"schema.table: \" << entry->schema_name << \".\"\n            << entry->table_name << \" owner: \" << entry->owner\n            << \" host:port: \" << entry->host << \":\" << entry->port << std::endl;\n\n  std::string conn_str = \"dbname=gaiadr2 host=\" + entry->host +\n                         \" port=\" + std::to_string(entry->port) +\n                         \" user=\" + entry->owner + \" password=jvo!\";\n\n  PGconn *gaia_db = PQconnectdb(conn_str.c_str());\n  uint64_t count = 0;\n  uint64_t no_samples = 0;\n\n  if (PQstatus(gaia_db) != CONNECTION_OK) {\n    fprintf(stderr, \"PostgreSQL connection failed: %s\\n\",\n            PQerrorMessage(gaia_db));\n\n    PQfinish(gaia_db);\n    gaia_db = NULL;\n    return;\n  } else\n    printf(\"PostgreSQL connection successful.\\n\");\n\n  // alter table add column\n  std::string sql = \"alter table \" + entry->schema_name + \".\" +\n                    entry->table_name +\n                    \" add column _x real,\"\n                    \" add column _y real,\"\n                    \" add column _z real,\"\n                    \" add column _r real,\"\n                    \" add column _phi real,\"\n                    \" add column _m_g real;\";\n\n  PGresult *res = PQexec(gaia_db, sql.c_str());\n  ExecStatusType stat = PQresultStatus(res);\n\n  if (stat != PGRES_COMMAND_OK)\n    std::cout << sql << \" : \" << PQresStatus(stat) << std::endl;\n\n  if (res != NULL)\n    PQclear(res);\n\n  // create search indices\n  std::string columns[6] = {\"_x\", \"_y\", \"_z\", \"_r\", \"_phi\", \"_m_g\"};\n\n  for (int i = 0; i < 6; i++) {\n    std::string column = columns[i];\n\n    // sql = \"create index on \" + entry->schema_name + \".\" + entry->table_name +\n    // \" (\" + column + \");\";\n    sql = \"create index \" + entry->table_name + \"_\" + column + \"_idx on \" +\n          entry->schema_name + \".\" + entry->table_name + \" (\" + column + \");\";\n\n    res = PQexec(gaia_db, sql.c_str());\n    ExecStatusType stat = PQresultStatus(res);\n\n    if (stat != PGRES_COMMAND_OK)\n      std::cout << sql << \" : \" << PQresStatus(stat) << std::endl;\n\n    if (res != NULL)\n      PQclear(res);\n  }\n\n  // iterate through all the rows\n  sql = \"select \"\n        \"ra,dec,phot_g_mean_mag,bp_rp,parallax,pmra,pmdec,radial_\"\n        \"velocity,source_id from \" +\n        entry->schema_name + \".\" + entry->table_name +\n        \" where parallax > 0 and ra is not null and dec is not \"\n        \"null and phot_g_mean_mag is not null and bp_rp is not \"\n        \"null and pmra is not null and pmdec is not null and \"\n        \"radial_velocity is not null;\";\n\n  // group update statements;\n  std::vector<std::string> batch;\n\n  if (PQsendQuery(gaia_db, sql.c_str())) {\n    if (PQsetSingleRowMode(gaia_db)) {\n      PGresult *res = NULL;\n\n      while ((res = PQgetResult(gaia_db)) != NULL) {\n        if (PQresultStatus(res) == PGRES_SINGLE_TUPLE) {\n          count++;\n\n          std::stringstream res_str;\n          res_str << count << \":\\t\";\n\n          int nRows = PQntuples(res);\n          int nFields = PQnfields(res);\n\n          for (int i = 0; i < nRows; i++) {\n            if (nFields >= 8) {\n              /*char *e;\n              errno = 0;*/\n\n              std::size_t pos;\n              long long source_id;\n              double ra, dec, phot_g_mean_mag, bp_rp, parallax, pmra, pmdec,\n                  radial_velocity;\n\n              bool valid_data = true;\n\n              try {\n                ra = std::stod(std::string(PQgetvalue(res, i, 0)), &pos);\n\n                dec = std::stod(std::string(PQgetvalue(res, i, 1)), &pos);\n\n                phot_g_mean_mag =\n                    std::stod(std::string(PQgetvalue(res, i, 2)), &pos);\n\n                bp_rp = std::stod(std::string(PQgetvalue(res, i, 3)), &pos);\n\n                parallax = std::stod(std::string(PQgetvalue(res, i, 4)), &pos);\n\n                pmra = std::stod(std::string(PQgetvalue(res, i, 5)), &pos);\n\n                pmdec = std::stod(std::string(PQgetvalue(res, i, 6)), &pos);\n\n                radial_velocity =\n                    std::stod(std::string(PQgetvalue(res, i, 7)), &pos);\n\n                source_id =\n                    std::stoll(std::string(PQgetvalue(res, i, 8)), &pos);\n              } catch (const std::out_of_range &err) {\n                printf(\"(%s) (%s) (%s) (%s) (%s) (%s) (%s) (%s) (%s)\\n\",\n                       PQgetvalue(res, i, 0), PQgetvalue(res, i, 1),\n                       PQgetvalue(res, i, 2), PQgetvalue(res, i, 3),\n                       PQgetvalue(res, i, 4), PQgetvalue(res, i, 5),\n                       PQgetvalue(res, i, 6), PQgetvalue(res, i, 7),\n                       PQgetvalue(res, i, 8));\n                valid_data = false;\n              } catch (const std::invalid_argument &err) {\n                printf(\"(%s) (%s) (%s) (%s) (%s) (%s) (%s) (%s) (%s)\\n\",\n                       PQgetvalue(res, i, 0), PQgetvalue(res, i, 1),\n                       PQgetvalue(res, i, 2), PQgetvalue(res, i, 3),\n                       PQgetvalue(res, i, 4), PQgetvalue(res, i, 5),\n                       PQgetvalue(res, i, 6), PQgetvalue(res, i, 7),\n                       PQgetvalue(res, i, 7));\n                valid_data = false;\n              }\n\n              if (valid_data) {\n                no_samples++;\n                // std::cout << source_id << \"\\t\";\n                double M_G =\n                    phot_g_mean_mag + 5.0 + 5.0 * log10(parallax / 1000.0);\n\n                double alpha = ra * HTMfunc_Pr;  //[rad]\n                double delta = dec * HTMfunc_Pr; //[rad]\n                double d = 1000.0 / parallax;    // distance [parsec, pc]\n\n                vec6 sHEQ, sGCA, sGCY;\n                sHEQ[0] = d / 1000.0;      //[kpc]\n                sHEQ[1] = ra;              //[deg]\n                sHEQ[2] = dec;             //[deg]\n                sHEQ[3] = radial_velocity; //[km/s]\n                sHEQ[4] = pmra;\n                sHEQ[5] = pmdec;\n\n                sGCA = coords.GCAfromHEQ(sHEQ);\n                sGCY = coords.GCYfromHEQ(sHEQ);\n\n                double X = sGCA[0]; //[kpc]\n                double Y = sGCA[1]; //[kpc]\n                double Z = sGCA[2]; //[kpc]\n\n                double R = sGCY[0];    //[kpc]\n                double Phi = sGCY[2];  //[rad]\n                double VR = sGCY[3];   //[km/s]\n                double VZ = sGCY[4];   //[km/s]\n                double VPhi = sGCY[5]; //[km/s]\n\n                // update the db row\n                sql = \"update \" + entry->schema_name + \".\" + entry->table_name +\n                      \" set\" + \" _x = \" + std::to_string(X) +\n                      \",\"\n                      \" _y = \" +\n                      std::to_string(Y) +\n                      \",\"\n                      \" _z = \" +\n                      std::to_string(Z) +\n                      \",\"\n                      \" _r = \" +\n                      std::to_string(R) +\n                      \",\"\n                      \" _phi = \" +\n                      std::to_string(Phi) +\n                      \",\"\n                      \" _m_g = \" +\n                      std::to_string(M_G) +\n                      \" where source_id = \" + std::to_string(source_id) + \";\";\n                // std::cout << sql << std::endl;\n                batch.push_back(std::string(sql));\n              }\n            }\n          }\n        };\n\n        PQclear(res);\n      };\n    } else\n      std::cout << \"error setting PQsetSingleRowMode.\\n\";\n  } else\n    std::cout << \"PQsendQuery error.\\n\";\n\n  std::cout << \"processed \" << no_samples << \"/\" << count << \" valid records.\"\n            << std::endl;\n\n  // batch update\n  count = 0;\n  for (auto &_sql : batch) {\n    PGresult *_res = PQexec(gaia_db, _sql.c_str());\n    ExecStatusType _stat = PQresultStatus(_res);\n\n    if (_stat != PGRES_COMMAND_OK)\n      std::cout << _sql << \" : \" << PQresStatus(_stat) << std::endl;\n    else\n      count++;\n\n    if (_res != NULL)\n      PQclear(_res);\n  }\n\n  std::cout << \"updated \" << count << \" records.\" << std::endl;\n\n  // clean up the db connection\n  if (gaia_db != NULL)\n    PQfinish(gaia_db);\n}", "meta": {"hexsha": "0d87eaa898df1c0ac7491b03388b7a460d5b01c5", "size": 10075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/makeDBcache.cpp", "max_stars_repo_name": "jvo203/GAIAWebQL", "max_stars_repo_head_hexsha": "492e9b0c41ee95437d3fb6023be5169ee5755747", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/makeDBcache.cpp", "max_issues_repo_name": "jvo203/GAIAWebQL", "max_issues_repo_head_hexsha": "492e9b0c41ee95437d3fb6023be5169ee5755747", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/makeDBcache.cpp", "max_forks_repo_name": "jvo203/GAIAWebQL", "max_forks_repo_head_hexsha": "492e9b0c41ee95437d3fb6023be5169ee5755747", "max_forks_repo_licenses": ["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.0859872611, "max_line_length": 80, "alphanum_fraction": 0.4929032258, "num_tokens": 2768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056074291438, "lm_q2_score": 0.022286183550505313, "lm_q1q2_score": 0.00627145701930734}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Xin Wang\n *\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the copyright holder(s) nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * Author : Xin Wang\n * Email  : ericrussell@zju.edu.cn\n *\n */\n\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <math.h>\n#include <Eigen/Core>\n#include \"LagrangeTensorWorker.h\"\n#include \"globaldef.h\"\n#include \"dataLibrary.h\"\n\nusing namespace std;\n\nbool LagrangeTensorWorker::is_para_satisfying(QString &message){\n    if(dataLibrary::Fracture_Triangles.size() > 0){\n        this->setParaSize(7);\n        if(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters.size()>=this->getParaSize()){\n            this->setStriationsFileName(QString::fromUtf8(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[0].c_str()));\n            this->setStepsFileName(QString::fromUtf8(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[1].c_str()));\n            this->setSizeFileName(QString::fromUtf8(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[2].c_str()));\n            this->setTensorFileName(QString::fromUtf8(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[3].c_str()));\n            string size_th_string = dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[4];\n\t\t\ttransform(size_th_string.begin(), size_th_string.end(), size_th_string.begin(), ::tolower);\n            if(size_th_string == \"allsize\"){\n                this->setSizeThMode(false);\n                this->setSizeTh(0.0);\n            }\n            else{\n                double SizeTh;\n                stringstream ss_SizeTh(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[4]);\n\t\t\t    ss_SizeTh >> SizeTh;\n                this->setSizeThMode(true);\n                this->setSizeTh(SizeTh);\n            }\n            double AngleTh;\n            stringstream ss_AngleTh(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[5]);\n\t\t\tss_AngleTh >> AngleTh;\n            this->setAngleTh(AngleTh);\n            string K_string = dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[6];\n            transform(K_string.begin(), K_string.end(), K_string.begin(), ::tolower);\n            if(K_string == \"realk\"){\n                this->setKfixedMode(false);\n            }\n            else{\n                double K;\n                stringstream ss_K(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[6]);\n\t\t\t    ss_K >> K;\n                this->setKfixedMode(true);\n                this->setK(K);\n            }\n            this->setStriationsMTh(0.05);\n            this->setStepsMTh(0.0);\n            this->setParaIndex(this->getParaSize());\n            return true;\n        }\n        else{\n            message = QString(\"lagrangetensor: No (or not enough) Parameter Given.\");\n            return false;\n        }\n    }\n    else{\n        message = QString(\"lagrangetensor: Please Perform Fracture Triangulation or Open Triangulation Data First.\");\n\t\treturn false;\n    }\n}\n\nvoid LagrangeTensorWorker::prepare(){\n\tthis->setUnmute();\n\tthis->setWriteLog();\n\tthis->check_mute_nolog();\n}\n\nbool readStriationsOrSteps(const string &filename, vector<Eigen::Vector3f> &dir, vector<float> &M, string err_message){\n\tifstream fs;\n    fs.open (filename.c_str());\n    if (!fs.is_open() || fs.fail()){\n\t\terr_message = \"Could not open file \" + filename + \" !\";\n        fs.close();\n        return false;\n    }\n    \n    string line;\n    vector<string> st;\n    \n    while (!fs.eof()){\n        getline(fs, line);\n        // Ignore empty lines\n        if (line == \"\")\n            continue;\n        \n        // Tokenize the line\n        boost::trim(line);\n        boost::split(st, line, boost::is_any_of(\",\\t\\r \"), boost::token_compress_on);\n        \n        if (st.size() < 5)\n            continue;\n        \n        Eigen::Vector3f temp_dir;\n        temp_dir<<stof(st[0]),stof(st[1]),stof(st[2]);\n        dir.push_back(temp_dir);\n        M.push_back(stof(st[4]));\n    }\n    fs.close();\n    return true;\n}\n\nbool readSize(const string &filename, vector<int> &f_size, string err_message){\n\tifstream fs;\n    fs.open (filename.c_str());\n    if (!fs.is_open() || fs.fail()){\n\t\terr_message = \"Could not open file \" + filename + \" !\";\n        fs.close();\n        return false;\n    }\n    \n    string line;\n    \n    while (!fs.eof()){\n        getline(fs, line);\n        // Ignore empty lines\n        if (line == \"\")\n            continue;\n        \n        boost::trim(line);\n        \n        f_size.push_back(stoi(line));\n    }\n    fs.close();\n    return true;\n}\n\nvoid LagrangeTensorWorker::doWork(){\n\tbool is_success(false);\n\n    QByteArray baStriations = this->getStriationsFileName().toLocal8Bit();\n\tstring* strStriationsfilename = new string(baStriations.data());\n    QByteArray baSteps = this->getStepsFileName().toLocal8Bit();\n\tstring* strStepsfilename = new string(baSteps.data());\n    QByteArray baSize = this->getSizeFileName().toLocal8Bit();\n\tstring* strSizefilename = new string(baSize.data());\n    QByteArray baTensor = this->getTensorFileName().toLocal8Bit();\n\tstring* strTensorfilename = new string(baTensor.data());\n    \n    dataLibrary::Status = STATUS_LAGRANGETENSOR;\n\n    this->timer_start();\n\n\t//begin of processing\n    vector<Eigen::Vector3f> striations_dir;\n    vector<float> striations_M;\n    vector<Eigen::Vector3f> steps_dir;\n    vector<float> steps_M;\n    vector<int> f_size;\n\tstring error_msg = \"\";\n\tif(!readStriationsOrSteps(*strStriationsfilename, striations_dir, striations_M, error_msg)){\n\t\temit showErrors(QString(error_msg.c_str()));\n\t}\n    else{\n        if(!readStriationsOrSteps(*strStepsfilename, steps_dir, steps_M, error_msg)){\n            emit showErrors(QString(error_msg.c_str()));\n        }\n        else{\n            if(!readSize(*strSizefilename, f_size, error_msg)){\n                emit showErrors(QString(error_msg.c_str()));\n            }\n            else{\n                ofstream fout(strTensorfilename->c_str());\n                for(int i=0; i<dataLibrary::Fracture_Triangles.size(); i++){\n                    if((this->getSizeThMode() == false)||((this->getSizeThMode() == true)&&(f_size[i] >= this->getSizeTh()))){\n                        if((striations_dir[i].norm() != 0)&&(steps_dir[i].norm() != 0)){\n                            if((striations_M[i] >= this->getStriationsMTh())&&(steps_M[i] >= this->getStepsMTh())){\n                                Eigen::Vector3f shear_dir;\n                                double angle = acos(striations_dir[i].dot(steps_dir[i])/(striations_dir[i].norm()*steps_dir[i].norm()));\n                                double angle_th = this->getAngleTh()*TWOPI/360.0;\n                                if((angle<=angle_th)||((TWOPI/2-angle)<=angle_th)){\n                                    if(angle < TWOPI/4){\n                                        shear_dir = striations_dir[i];\n                                    }\n                                    else if(angle > TWOPI/4){\n                                        shear_dir = -striations_dir[i];\n                                    }\n                                    else{\n                                        continue;\n                                    }\n                                    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_ptr(new pcl::PointCloud<pcl::PointXYZ>);\n                                    pcl::fromROSMsg(dataLibrary::Fracture_Triangles[i]->cloud, *cloud_ptr);\n                                    Eigen::Vector4f plane_normal_param = dataLibrary::fitPlaneManually(*cloud_ptr);\n                                    Eigen::Vector3f fracture_normal;\n                                    fracture_normal << plane_normal_param(0), plane_normal_param(1), plane_normal_param(2);\n                                    Eigen::Vector3f e1 = shear_dir/shear_dir.norm();\n                                    Eigen::Vector3f e2 = fracture_normal/fracture_normal.norm();\n                                    Eigen::Vector3f e3 = e1.cross(e2);\n                                    Eigen::Vector3f e_prime1, e_prime2, e_prime3;\n                                    e_prime1<<1,0,0;\n                                    e_prime2<<0,1,0;\n                                    e_prime3<<0,0,1;\n                                    double K;\n                                    double M2Kpara = 0.2;\n                                    if(this->getKfixedMode()){\n                                        K = this->getK();\n                                    }\n                                    else{\n                                        K = (striations_M[i] + steps_M[i])*M2Kpara;\n                                    }\n                                    Eigen::Matrix3f E_star;\n                                    E_star << 0, K/2, 0,\n                                            K/2, K*K/2, 0,\n                                            0, 0, 0;\n                                    Eigen::Matrix3f T;\n                                    T << e1.dot(e_prime1), e1.dot(e_prime2), e1.dot(e_prime3),\n                                        e2.dot(e_prime1), e2.dot(e_prime2), e2.dot(e_prime3),\n                                        e3.dot(e_prime1), e3.dot(e_prime2), e3.dot(e_prime3);\n                                    Eigen::Matrix3f E_star_prime = T.transpose()*E_star*T;\n                                    fout<<i<<'\\t'\n                                            <<E_star_prime(0,0)<<'\\t'<<E_star_prime(0,1)<<'\\t'<<E_star_prime(0,2)<<'\\t'\n                                            <<E_star_prime(1,0)<<'\\t'<<E_star_prime(1,1)<<'\\t'<<E_star_prime(1,2)<<'\\t'\n                                            <<E_star_prime(2,0)<<'\\t'<<E_star_prime(2,1)<<'\\t'<<E_star_prime(2,2)<<'\\n';\n                                }\n                            }\n                        }\n                    }\n                }\n                fout.close();\n                is_success = true;\n            }\n        }\n    }\n\t//end of processing\n\n    this->timer_stop();\n\n    if(this->getWriteLogMode()&&is_success){\n        string log_text = \"\\tLagrange Tensor costs: \";\n        ostringstream strs;\n        strs << this->getTimer_sec();\n        log_text += (strs.str() +\" seconds.\");\n        dataLibrary::write_text_to_log_file(log_text);\n    }\n\n\tdataLibrary::Status = STATUS_READY;\n    emit showReadyStatus();\n\tdelete strStriationsfilename;\n    delete strStepsfilename;\n    delete strSizefilename;\n    delete strTensorfilename;\n\tif(this->getWorkFlowMode()&&is_success){\n\t\tthis->Sleep(1000);\n\t\temit GoWorkFlow();\n\t}\n}", "meta": {"hexsha": "80b90823cd7744fa398c8085f45981f7001c73a0", "size": 12122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LagrangeTensorWorker.cpp", "max_stars_repo_name": "EricAlex/structrock", "max_stars_repo_head_hexsha": "754d8c481d22a48ea7eb4e055eb16c64c44055ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-05-10T07:07:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T02:57:14.000Z", "max_issues_repo_path": "LagrangeTensorWorker.cpp", "max_issues_repo_name": "liuxinren456852/structrock", "max_issues_repo_head_hexsha": "1a5e660bdbb5f80fb2ab479b7398c072e2573fd1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LagrangeTensorWorker.cpp", "max_forks_repo_name": "liuxinren456852/structrock", "max_forks_repo_head_hexsha": "1a5e660bdbb5f80fb2ab479b7398c072e2573fd1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-03-25T01:24:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-04T23:40:06.000Z", "avg_line_length": 42.0902777778, "max_line_length": 141, "alphanum_fraction": 0.5498267613, "num_tokens": 2628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.01640303579181684, "lm_q1q2_score": 0.0062531584204706765}}
{"text": "/* \n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/xtp/qmstate.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/regex.hpp>\n#include <regex>\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n\nnamespace votca {\n    namespace xtp {\n\n    int QMStateType::ToCTPIndex()const {\n      if (_type == QMStateType::Singlet) {\n        return 2;\n      } else if (_type == QMStateType::Triplet) {\n        return 3;\n      } else if (_type == QMStateType::Hole) {\n        return 1;\n      } else if (_type == QMStateType::Electron) {\n        return -1;\n      } else if (_type == QMStateType::Gstate) {\n        return 0;\n      } else {\n        throw std::runtime_error(\"For state \" + this->ToString() + \" no conversion to ctp exists\");\n      }\n      return 0;\n    }\n\n    std::string QMStateType::ToString() const{\n      std::string identifier=\"\";\n      switch (_type) {\n        case QMStateType::Singlet: identifier = \"s\";\n          break;\n        case QMStateType::Triplet: identifier = \"t\";\n          break;\n        case QMStateType::PQPstate: identifier = \"pqp\";\n          break;\n        case QMStateType::DQPstate: identifier = \"dqp\";\n          break;\n        case QMStateType::KSstate: identifier = \"ks\";\n          break;\n        case QMStateType::Gstate: identifier = \"n\";\n          break;\n        case QMStateType::Hole: identifier = \"h\";\n          break;\n        case QMStateType::Electron: identifier = \"e\";\n          break;\n      }\n      return identifier;\n    }\n    \n    std::string QMStateType::ToLongString() const{\n      std::string identifier=\"\";\n      switch (_type) {\n        case QMStateType::Singlet: identifier = \"singlet\";\n          break;\n        case QMStateType::Triplet: identifier = \"triplet\";\n          break;\n        case QMStateType::PQPstate: identifier = \"pert-qparticle\";\n          break;\n        case QMStateType::DQPstate: identifier = \"diag-qparticle\";\n          break;\n        case QMStateType::KSstate: identifier = \"Kohn-Sham-orbital\";\n          break;\n        case QMStateType::Gstate: identifier = \"groundstate\";\n          break;\n          case QMStateType::Hole: identifier = \"hole\";\n          break;\n        case QMStateType::Electron: identifier = \"electron\";\n          break;\n      }\n      return identifier;\n    }\n    \n    void QMStateType::FromString(const std::string& statetypestring){\n      std::string lower = boost::algorithm::to_lower_copy(statetypestring);\n      boost::trim(lower);\n      if(lower==\"s\" || lower==\"singlet\"){\n        _type=QMStateType::Singlet;\n      }else if(lower==\"t\" || lower==\"triplet\" ){\n        _type=QMStateType::Triplet;\n      }else if(lower==\"pqp\" || lower==\"pert-qparticle\"){\n        _type=QMStateType::PQPstate;\n      }else if(lower==\"dqp\" || lower==\"diag-qparticle\" || lower==\"qpdiag\"){\n        _type=QMStateType::DQPstate;\n      }else if(lower==\"ks\" || lower==\"kohn-sham-orbital\"){\n        _type=QMStateType::KSstate;\n      }else if(lower==\"n\" || lower==\"groundstate\" || lower==\"gs\"){\n        _type=QMStateType::Gstate;\n       }else if(lower==\"h\" || lower==\"hole\" ){\n        _type=QMStateType::Hole;\n       }else if(lower==\"e\" || lower==\"electron\"){\n        _type=QMStateType::Electron;\n      }else{\n        throw std::runtime_error(\"Statetype:\"+statetypestring+\" not recognized\");\n      }\n    }\n    \n    std::string QMState::ToLongString()const{\n      int index=_index;\n      if(_type==QMStateType::Singlet || _type==QMStateType::Triplet){\n        index++;\n      }else if(_type==QMStateType::Gstate || _type==QMStateType::Electron || _type==QMStateType::Hole){\n        return _type.ToLongString();\n      }\n      std::string result=_type.ToLongString()+(boost::format(\" %i\") % index ).str();\n      if(_transition){\n        result=\"Groundstate to \"+result;\n      }\n      return result;\n    }\n    \n    std::string QMState::ToString()const{\n      int index=_index;\n      if(_type==QMStateType::Singlet || _type==QMStateType::Triplet){\n        index++;\n      }else if(_type==QMStateType::Gstate || _type==QMStateType::Electron || _type==QMStateType::Hole){\n        return _type.ToString();\n      }\n      std::string result=_type.ToString()+(boost::format(\"%i\") % index ).str();\n      if(_transition){\n        result=\"N2\"+result;\n      }\n      return result;\n    }\n    \n    \n    int QMState::DetermineIndex(const std::string& statestring){\n     \n      std::smatch search;\n      std::regex reg(\"[0-9]+\");\n      \n      bool found_integer=std::regex_search(statestring,search,reg);\n      if(!found_integer){\n        throw std::runtime_error(\"Found no index in string: \"+statestring);\n      }\n      if(search.size()>1){\n        throw std::runtime_error(\"Found more than 1 index in string: \"+statestring);\n      }\n      \n      int index=boost::lexical_cast<int>(search.str(0));\n        if(_type.isExciton() || _type==QMStateType::Electron || _type==QMStateType::Hole){\n        index--;\n      }\n      return index;\n    }\n    \n    \n    QMStateType QMState::DetermineType(const std::string& statestring){\n         std::regex reg(\"[^0-9]+\");\n         std::smatch search;\n         \n       bool found_typestring=std::regex_search(statestring,search,reg);\n      if(!found_typestring){\n        throw std::runtime_error(\"Found no type in string: \"+statestring);\n      }\n      if(search.size()>1){\n        throw std::runtime_error(\"Found more than one type in string: \"+statestring);\n      }\n        QMStateType type;\n        type.FromString(search.str(0));\n        \n        return type;\n    }\n\n    void QMState::FromString(const std::string& statestring){\n      std::string lower = boost::algorithm::to_lower_copy(statestring);\n      boost::trim(lower);\n      std::string rest;\n      if (boost::starts_with(lower, \"n2\")){\n        _transition=true;\n        rest=lower.substr(2);\n      }else if(boost::starts_with(lower, \"groundstate to\")){\n        _transition=true;\n        rest=lower.substr(14);\n      }else{\n        rest=lower;\n        _transition=false;\n      }\n      boost::trim(rest);\n      \n      _type=DetermineType(rest);\n      if(_type!=QMStateType::Singlet && _transition==true){\n          throw std::runtime_error(\"Transition states only exist for singlets.\");\n      }\n      if(_type!=QMStateType::Gstate && _type!=QMStateType::Electron && _type!=QMStateType::Hole){\n        _index=DetermineIndex(rest);\n     }else{\n        _index=-1;\n     }\n    }\n  \n\n    }\n}\n", "meta": {"hexsha": "03d5677b49dcaef3e1ecd36cfc639d84d98f9a3c", "size": 7015, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/qmstate.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/qmstate.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/qmstate.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6279069767, "max_line_length": 103, "alphanum_fraction": 0.5940128297, "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781087819190097, "lm_q2_score": 0.03514484652711669, "lm_q1q2_score": 0.0062491360249062}}
{"text": "#ifndef INHOMOGENOUSCOUPLEDPDEODECOUPLEDCELLSOLVER_HPP_\n#define INHOMOGENOUSCOUPLEDPDEODECOUPLEDCELLSOLVER_HPP_\n\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 \"AbstractOdeSystemForCoupledPdeSystem.hpp\"\n#include \"CvodeAdaptor.hpp\"\n#include \"BackwardEulerIvpOdeSolver.hpp\"\n#include \"Warnings.hpp\"\n#include \"VtkMeshWriter.hpp\"\n#include \"StateVariableRegister.hpp\"\n#include \"InhomogenousCoupledPdeOdeSolver_templated.hpp\"\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=2>\nclass InhomogenousCoupledPdeOdeCoupledCellSolver\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>* mpFeMesh;\n\n    /** The PDE system to be solved. */ \n    //CellSourceInhomogenousParabolicPdeOdeSystem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>* mpPdeSystem;\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    bool mCellTransportOdeSystemsPresent;\n\n    bool mCellMembraneOdeSystemsPresent;\n\n    bool mConditionsInterpolated=false;\n\n    AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& mrCellPopulation;\n\n    ChastePoint<SPACE_DIM> mX;\n\n    c_vector<double,PROBLEM_DIM> mU;\n\n    unsigned mInterpolationCount=0;\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     * 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    InhomogenousCoupledPdeOdeCoupledCellSolver(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                                    AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation,\n                                    std::vector<AbstractInhomogenousOdeSystemForCoupledPdeSystem*> odeSystemsAtNodes=std::vector<AbstractInhomogenousOdeSystemForCoupledPdeSystem*>(),\n                                    std::vector<boost::shared_ptr<AbstractIvpOdeSolver>> pOdeSolvers=std::vector<boost::shared_ptr<AbstractIvpOdeSolver>>(),\n                                    bool conditionsInterpolated =false,\n                                    ChastePoint<SPACE_DIM> point = ChastePoint<SPACE_DIM>(),\n                                    c_vector<double,PROBLEM_DIM> stateVector = zero_vector<double>(PROBLEM_DIM));\n\n    /**\n     * Destructor.\n     * If an ODE system is present, the pointers to the ODE system objects are deleted here.\n     */\n    ~InhomogenousCoupledPdeOdeCoupledCellSolver();\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 mpFeMesh\n     * @return mOdeSystemsAtNodes[index]\n     */\n    AbstractOdeSystemForCoupledPdeSystem* GetOdeSystemAtNode(unsigned index);\n\n    void SetInterpolationPoint(ChastePoint<SPACE_DIM> );\n\n    void SetCurrentStateVector(c_vector<double,PROBLEM_DIM>);\n\n    bool CheckChastePointsForEquality(ChastePoint<SPACE_DIM>,ChastePoint<SPACE_DIM>);\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)> InhomogenousCoupledPdeOdeCoupledCellSolver<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<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - ComputeMatrixTerm\"<<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\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<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - ComputeMatrixTerm - end\"<<std::endl;\n    return matrix_term;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nc_vector<double, PROBLEM_DIM*(ELEMENT_DIM+1)> InhomogenousCoupledPdeOdeCoupledCellSolver<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{   //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - 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   \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        double this_constant_source_term =0.0;\n\n        // check whether adding cell contribution\n        if(mCellTransportOdeSystemsPresent || mCellMembraneOdeSystemsPresent)\n        {  \n          \n            // at least one of the cells has the transport property and can run an transport ode system which needs to be considered\n            // check whether point rX is associated with a cell\n            bool isContributed=false;\n            unsigned cell_count=0;\n            for (AbstractCellPopulation<2>::Iterator cell_iter = mrCellPopulation.Begin();\n             cell_iter != mrCellPopulation.End();\n             ++cell_iter)\n            {   \n\n                unsigned cell_location_index = mrCellPopulation.GetLocationIndexUsingCell(*cell_iter);\n                const ChastePoint<SPACE_DIM>& cellCentrePoint = mrCellPopulation.GetLocationOfCellCentre(*cell_iter);\n                \n                if (cell_iter->HasCellProperty<TransportCellProperty>())\n                {\n                   \n                    boost::shared_ptr<TransportCellProperty> transport_cell_property = boost::static_pointer_cast<TransportCellProperty>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<TransportCellProperty>().GetProperty());\n \n                    if(cell_iter->HasCellProperty<ExtendedCellProperty<SPACE_DIM>>())\n                    {\n                        boost::shared_ptr<ExtendedCellProperty<SPACE_DIM>> extended_cell_property = boost::static_pointer_cast<ExtendedCellProperty<SPACE_DIM>>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<ExtendedCellProperty<SPACE_DIM>>().GetProperty());\n\n                        if(extended_cell_property -> IsPointInCell(cellCentrePoint, rX))\n                        {\n                            // point is in cell, test if it is a cell boundary point\n                            if(extended_cell_property -> CheckCellBoundary(cellCentrePoint, rX))\n                            {\n                                // if so then add the transport contribution\n                                std::string name_of_pde_index = mpPdeSystem->GetStateVariableRegister()->RetrieveStateVariableName(pde_index);\n                                \n\n                                // if cell is on boundary add the result of the transport Ode system\n                                this_constant_source_term = extended_cell_property ->RetrieveBoundarySourceByStateName(name_of_pde_index,mX);\n\n                                if(!transport_cell_property ->GetIncludeOdeInterpolationOnBoundary())\n                                {\n                                    // override the ode source term\n                                    //this_source_term =0.0;\n                                }\n                            }\n                            else\n                            {\n                                // point rX is in cell\n                                std::string name_of_pde_index = mpPdeSystem->GetStateVariableRegister()->RetrieveStateVariableName(pde_index);\n              //                  this_constant_source_term += (extended_cell_property->RetrieveInternalCellSourceByStateName(name_of_pde_index)/(double)(ELEMENT_DIM+1));\n                                if(!extended_cell_property -> GetIncludeOdeInterpolationInCell())\n                                {\n                                    // source is null\n                                    //this_source_term = 0.0;\n                                }\n                                // else source term is the ode term is present; see above\n                            }\n                            // point rX can only be associated with one cell at a time, so here it has been found so break\n                            break;\n                        }\n                    \n                    }\n                    else\n                    {\n                        // for case that cell has no extended property, can check that rX is close to cell_location\n                        // then use the concentrations, bulk and cell, with the transport property\n                        if(CheckChastePointsForEquality(cellCentrePoint,rX))\n                        {\n                            // if so then add the transport contribution\n                            std::string name_of_pde_index = mpPdeSystem->GetStateVariableRegister()->RetrieveStateVariableName(pde_index);\n         \n                            // if cell is on boundary add the result of the transport Ode system\n                            // scale the constant source term to remove the additive affect of the multiple element nodes \n                            //this_constant_source_term += (transport_cell_property ->RetrieveBoundarySourceByStateName(name_of_pde_index)/(double)(ELEMENT_DIM+1));\n                            \n                            this_constant_source_term += (transport_cell_property ->RetrieveChangeBoundarySourceByStateName(name_of_pde_index)/(double)(ELEMENT_DIM+1));\n                            \n                            if(!transport_cell_property ->GetIncludeOdeInterpolationOnBoundary())\n                            {\n                                // override the ode source term\n                                //this_source_term =0.0;\n                            }\n                            isContributed =true; // as already found the only possible cell which may act as a source\n                        }\n                        // else not this cell\n                    }\n                } \n                \n                // check for membrane system\n                if (cell_iter->HasCellProperty<MembraneCellProperty>())\n                {\n                   \n                    boost::shared_ptr<MembraneCellProperty> membrane_cell_property = boost::static_pointer_cast<MembraneCellProperty>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<MembraneCellProperty>().GetProperty());\n                    // check that rX is close to cell_location\n                    // then use the concentrations, bulk and cell, with the membrane property\n                    if(CheckChastePointsForEquality(cellCentrePoint,rX))\n                    {\n                        // if so then add the membrane contribution\n                        std::string name_of_pde_index = mpPdeSystem->GetStateVariableRegister()->RetrieveStateVariableName(pde_index);\n                  \n                        // if cell is on boundary add the result of the membrane Ode system\n                        // scale the constant source term to remove the additive affect of the multiple element nodes \n                        this_constant_source_term += (membrane_cell_property ->RetrieveChangeBoundarySourceByStateName(name_of_pde_index)/(double)(ELEMENT_DIM+1));\n\n                        if(!membrane_cell_property ->GetIncludeMembraneOdeInterpolationOnBoundary())\n                        {\n                            // override the ode source term\n                            //this_source_term =0.0;\n                        }\n                        isContributed =true; // as already found the only possible cell which may act as a source\n                    }\n                    // else not this cell\n                }\n                \n                if(isContributed)\n                {\n                    // only one cell may contribute at a single point\n                    //std::cout<<this_constant_source_term<<std::endl;\n                    break;\n                }\n                // else ignore cell; the cell has no transport property\n                cell_count++;\n            }\n        }\n\n\n        // include the cell contribution alongside the interpolated ode contribution\n        c_vector<double, ELEMENT_DIM+1> this_vector_term;\n        \n        this_vector_term = (this_source_term + this_constant_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<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - ComputeVectorTerm - end\"<<std::endl;\n    return vector_term;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::ResetInterpolatedQuantities()                \n{   //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - ResetInterpolatedQuantities\"<<std::endl;\n    mInterpolatedOdeStateVariables.clear();\n\n    if (mOdeSystemsPresent)\n    {\n        unsigned num_state_variables = mpPdeSystem->GetStateVariableRegister()->GetNumberOfStateVariables();\n        \n        mInterpolatedOdeStateVariables.resize(num_state_variables, 0.0);\n    }\n\n    if(mCellTransportOdeSystemsPresent)\n    {\n        // reset the point and current state vector\n        ChastePoint<SPACE_DIM> x(0,0,0);\n\n        SetInterpolationPoint(x);\n\n        c_vector<double,PROBLEM_DIM> u = zero_vector<double>(PROBLEM_DIM);\n\n        SetCurrentStateVector(u);\n\n        mInterpolationCount=0;\n        for (AbstractCellPopulation<2>::Iterator cell_iter = mrCellPopulation.Begin();\n        cell_iter != mrCellPopulation.End();\n        ++cell_iter)\n        {\n            if (cell_iter->HasCellProperty<ExtendedCellProperty<SPACE_DIM>>())\n            {\n                boost::shared_ptr<ExtendedCellProperty<SPACE_DIM>> extended_cell_property = boost::static_pointer_cast<ExtendedCellProperty<SPACE_DIM>>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<ExtendedCellProperty<SPACE_DIM>>().GetProperty());\n\n                extended_cell_property -> ResetVectorOfBoundaryStateVariables();\n                extended_cell_property -> ResetVectorOfInternalBoundaryStateVariables();\n                extended_cell_property -> ResetVectorOfBoundaryLocations();\n\n            }\n            // if cell has only the transport property then there is nothing needed to be reset\n        }\n\n    }\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - ResetInterpolatedQuantities - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::IncrementInterpolatedQuantities(double phiI, const Node<SPACE_DIM>* pNode)\n{   //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - IncrementInterpolatedQuantities\"<<std::endl;\n    // interploates a quantity from a node location to point x through the basis function phi associated with the node \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 state variable 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            else\n            {\n                // if the state variable isn't a part of the ODE then interpolated the pde solution at the node\n                mInterpolatedOdeStateVariables[i] += phiI * 0.0;\n\n            }\n                                \n        }\n\n    }\n\n    // check whether adding cell contribution\n    if(mCellTransportOdeSystemsPresent || mCellMembraneOdeSystemsPresent)\n    {\n\n        // interpolate mX and mU\n        mX.rGetLocation() += phiI*pNode->rGetLocation();\n        for(unsigned prob_dim=0; prob_dim<PROBLEM_DIM; prob_dim++)\n        {\n            mU(prob_dim) += phiI*this->GetCurrentSolutionOrGuessValue(pNode->GetIndex(), prob_dim);\n        }\n        \n        // store mX and mU over the interpolation; assume ELEMENT_DIM + 1 nodes for interpolation\n        //std::cout<<\"mInterpolationCount = \"<<mInterpolationCount<<std::endl;\n        if(mInterpolationCount==2)\n        {\n            // the mX and mU are fully interpolated\n            //std::cout<<\"hit interpolation\"<<std::endl;\n            // check whether point mX is associated with a cell\n            bool this_point_found = false;\n            for (AbstractCellPopulation<2>::Iterator cell_iter = mrCellPopulation.Begin();\n            cell_iter != mrCellPopulation.End();\n            ++cell_iter)\n            {\n\n                if(cell_iter->HasCellProperty<TransportCellProperty>())\n                {\n                    //std::cout<<\"transport\"<<std::endl;\n                    const ChastePoint<SPACE_DIM>& cellCentrePoint = mrCellPopulation.GetLocationOfCellCentre(*cell_iter);\n\n                    //ChastePoint<SPACE_DIM> cellCentrePoint(cell_location);\n\n                    if (cell_iter->HasCellProperty<ExtendedCellProperty<SPACE_DIM>>())\n                    {\n\n                        boost::shared_ptr<ExtendedCellProperty<SPACE_DIM>> extended_cell_property = boost::static_pointer_cast<ExtendedCellProperty<SPACE_DIM>>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<ExtendedCellProperty<SPACE_DIM>>().GetProperty());\n\n                        if(extended_cell_property -> IsPointInCell(cellCentrePoint, mX))\n                        {\n                            // ignore point if it is in the cell and not on boundary for time being. The internal cell points are handled differently.\n                            if(extended_cell_property -> IsPointOnCellBoundary(cellCentrePoint, mX))\n                            {\n                                // need mU as std::vector<double>\n                                std::vector<double> mUstd(PROBLEM_DIM,0.0);\n                                for(unsigned i=0; i<PROBLEM_DIM;i++)\n                                {\n                                    mUstd[i] = mU[i];\n                                }\n                                extended_cell_property -> RecordLocationAndStateVariable(mX,mUstd);\n                                mUstd.clear();\n                            }\n                            this_point_found = true; // found where the point rX is associated\n                        }\n                    }\n                    else\n                    {\n                        boost::shared_ptr<TransportCellProperty> transport_cell_property = boost::static_pointer_cast<TransportCellProperty>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<TransportCellProperty>().GetProperty());\n\n                        // check whether the interpolated point is on the cell centre\n                        //std::cout<<\"Check for equality\"<<std::endl;\n                        if(CheckChastePointsForEquality(cellCentrePoint, mX))\n                        {\n                            //std::cout<<\"IncrementInterpolatedQuantities - CheckChastePointsForEquality \"<<std::endl;\n                            // set the value for rU as the mBulkBoundaryConcentrationVector\n                            // need mU as std::vector<double>\n                            std::vector<double> mUstd(PROBLEM_DIM,0.0);\n                            for(unsigned i=0; i<PROBLEM_DIM;i++)\n                            {\n                                mUstd[i] = mU[i];\n                               \n                            }\n                            transport_cell_property -> SetBulkBoundaryConcentrationVector(mUstd);\n                            transport_cell_property -> SetInitBulkBoundaryConcentrationVector(mUstd); //15/10/2020\n                            transport_cell_property -> ResetReactionCalls();\n                            mUstd.clear();\n\n                            this_point_found = true; // as have found the cell associated with the point interpolated\n                        }\n\n                    }\n                    \n                }\n\n                if(cell_iter->HasCellProperty<MembraneCellProperty>())\n                {\n\n                    const ChastePoint<SPACE_DIM>& cellCentrePoint = mrCellPopulation.GetLocationOfCellCentre(*cell_iter);\n\n                    boost::shared_ptr<MembraneCellProperty> membrane_cell_property = boost::static_pointer_cast<MembraneCellProperty>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<MembraneCellProperty>().GetProperty());\n\n                    // check whether the interpolated point is on the cell centre\n\n                    if(CheckChastePointsForEquality(cellCentrePoint, mX))\n                    {\n\n                        // set the value for rU as the mBulkBoundaryConcentrationVector\n                        // need mU as std::vector<double>\n                        std::vector<double> mUstd(PROBLEM_DIM,0.0);\n                        for(unsigned i=0; i<PROBLEM_DIM;i++)\n                        {\n                            mUstd[i] = mU[i];\n                            \n                        }\n                        membrane_cell_property -> SetBulkBoundaryConcentrationVector(mUstd);\n                        membrane_cell_property -> SetInitBulkBoundaryConcentrationVector(mUstd); //15/10/2020\n                        membrane_cell_property -> ResetReactionCalls();\n                        mUstd.clear();\n\n                        this_point_found = true; // as have found the cell associated with the point interpolated\n                    } \n                }\n                if(this_point_found)\n                {\n                    break;\n                }\n            }\n            // reset the interpolation count\n            mInterpolationCount=0;\n        }\n        else\n        {\n            // not fully interpolated the point and state vector yet\n            mInterpolationCount +=1;\n        }\n    }\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - IncrementInterpolatedQuantities - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::InitialiseForSolve(Vec initialSolution)\n{   //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - InitialiseForSolve\"<<std::endl;\n    if (this->mpLinearSystem == NULL)\n    {\n        unsigned preallocation = mpFeMesh->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    // set up each of the cells\n    if(mCellTransportOdeSystemsPresent)\n    {\n       \n        // reset the point and current state vector\n        ChastePoint<SPACE_DIM> x(0,0,0);\n\n        SetInterpolationPoint(x);\n\n        c_vector<double,PROBLEM_DIM> u = zero_vector<double>(PROBLEM_DIM);\n\n        SetCurrentStateVector(u);\n     \n        for (AbstractCellPopulation<2>::Iterator cell_iter = mrCellPopulation.Begin();\n        cell_iter != mrCellPopulation.End();\n        ++cell_iter)\n        {   \n            if (cell_iter->HasCellProperty<ExtendedCellProperty<SPACE_DIM>>())\n            {\n                boost::shared_ptr<ExtendedCellProperty<SPACE_DIM>> extended_cell_property = boost::static_pointer_cast<ExtendedCellProperty<SPACE_DIM>>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<ExtendedCellProperty<SPACE_DIM>>().GetProperty());\n\n                unsigned num_voxels = extended_cell_property->GetTotalNumberMeshVoxels();\n                if(num_voxels == 0)\n                {\n                    num_voxels=1;\n                }\n                std::vector<double> initialCellConcentration = extended_cell_property->GetCellConcentrationVector();\n\n                for(unsigned state=0; state<initialCellConcentration.size(); state++)\n                {\n                    // scale by the number of voxels\n                    initialCellConcentration[state] /= num_voxels;\n                }\n\n                extended_cell_property -> ResetVectorOfBoundaryStateVariables();\n                extended_cell_property -> ResetVectorOfInternalBoundaryStateVariables();\n                extended_cell_property -> ResetVectorOfBoundaryLocations();\n                extended_cell_property -> ResetNextTimestepConcentrationVector(PROBLEM_DIM);\n\n                for(unsigned boundary_index=0; boundary_index<extended_cell_property->GetNumberMeshVoxelsOnBoundary(); boundary_index++)\n                {\n                    extended_cell_property -> RecordLocationAndStateVariable(x,initialCellConcentration);\n\n                }\n            }\n        }\n\n    }\n\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - InitialiseForSolve -end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetupLinearSystem(Vec currentSolution, bool computeMatrix)\n{   //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - SetupLinearSystem\"<<std::endl;\n    this->SetupGivenLinearSystem(currentSolution, computeMatrix, this->mpLinearSystem);\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - SetupLinearSystem -end\"<<std::endl;\n}\n\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nInhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::InhomogenousCoupledPdeOdeCoupledCellSolver(\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        AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation,\n        std::vector<AbstractInhomogenousOdeSystemForCoupledPdeSystem*> odeSystemsAtNodes,\n        std::vector<boost::shared_ptr<AbstractIvpOdeSolver>> pOdeSolvers,\n        bool conditionsInterpolated,\n        ChastePoint<SPACE_DIM> point,\n        c_vector<double,PROBLEM_DIM> stateVector\n        )\n    : AbstractAssemblerSolverHybrid<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM, NORMAL>(pMesh, pBoundaryConditions),\n      AbstractDynamicLinearPdeSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>(pMesh),\n      mpFeMesh(pMesh),\n      mpPdeSystem(pPdeSystem),\n      mrCellPopulation(rCellPopulation),\n      mOdeSystemsAtNodes(odeSystemsAtNodes),\n      mpOdeSolvers(pOdeSolvers),\n      mConditionsInterpolated(conditionsInterpolated),\n      mX(point),\n      mU(stateVector),\n      mSamplingTimeStep(DOUBLE_UNSET),\n      mOdeSystemsPresent(false),\n      mCellTransportOdeSystemsPresent(false),\n      mCellMembraneOdeSystemsPresent(false),\n      mClearOutputDirectory(false)\n{   //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - InhomogenousCoupledPdeOdeCoupledCellSolver - start\"<<std::endl;\n    this->mpBoundaryConditions = pBoundaryConditions;\n\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() == mpFeMesh->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    // run through the cell popualtion for the occurance of a cell with the transport property defined\n    for (AbstractCellPopulation<2>::Iterator cell_iter = mrCellPopulation.Begin();\n        cell_iter != mrCellPopulation.End();\n        ++cell_iter)\n    {\n\n        if (cell_iter->HasCellProperty<TransportCellProperty>())\n        {\n            // if there exists at least one cell with the transport property then solve transport odes\n            mCellTransportOdeSystemsPresent=true;\n            break;\n        }\n    }\n\n    // run through the cell popualtion for the occurance of a cell with the membrane property defined\n    for (AbstractCellPopulation<2>::Iterator cell_iter = mrCellPopulation.Begin();\n        cell_iter != mrCellPopulation.End();\n        ++cell_iter)\n    {\n\n        if (cell_iter->HasCellProperty<MembraneCellProperty>())\n        {\n            // if there exists at least one cell with the membrane property then solve transport odes\n            mCellMembraneOdeSystemsPresent=true;\n            break;\n        }\n    }\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - InhomogenousCoupledPdeOdeCoupledCellSolver - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nInhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::~InhomogenousCoupledPdeOdeCoupledCellSolver()\n{\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - ~InhomogenousCoupledPdeOdeCoupledCellSolver\"<<std::endl;\n\n    /*  don't delete as solver will be called multiple times on same odes, assume that the ode FeMesh remains unchanged\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 InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::PrepareForSetupLinearSystem(Vec currentPdeSolution)\n{   \n //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - PrepareForSetupLinearSystem - strat\"<<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<mpFeMesh->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\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\n    // run cell transport chemical ode\n\n    if (mConditionsInterpolated && (mCellTransportOdeSystemsPresent||mCellMembraneOdeSystemsPresent))\n    {\n        //std::cout<<\"run cell transport\"<<std::endl;\n        double time = PdeSimulationTime::GetTime();\n        double next_time = PdeSimulationTime::GetNextTime();\n        double dt = PdeSimulationTime::GetPdeTimeStep();\n        //std::cout<<\"Here - 4 -time: \"<<time<<std::endl;\n        for (AbstractCellPopulation<2>::Iterator cell_iter = mrCellPopulation.Begin();\n             cell_iter != mrCellPopulation.End();\n             ++cell_iter)\n        {\n             //std::cout<<\"for cell:\"<<std::endl;\n            if (cell_iter->HasCellProperty<TransportCellProperty>())\n            {\n                \n                boost::shared_ptr<TransportCellProperty> transport_property = boost::static_pointer_cast<TransportCellProperty>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<TransportCellProperty>().GetProperty());\n\n                if(cell_iter->HasCellProperty<ExtendedCellProperty<SPACE_DIM>>())\n                {\n                    boost::shared_ptr<ExtendedCellProperty<SPACE_DIM>> extended_cell_property = boost::static_pointer_cast<ExtendedCellProperty<SPACE_DIM>>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<ExtendedCellProperty<SPACE_DIM>>().GetProperty());\n    \n                    for(unsigned boundary_index=0; boundary_index<extended_cell_property->GetNumberMeshVoxelsOnBoundary(); boundary_index++)\n                    {\n                        // rY for bulk state variables at the location specified by the boundary_index\n                        std::vector<double> rY = extended_cell_property -> GetVectorOfBoundaryStateVariablesByLocationIndex(boundary_index);\n                        \n                        // append the cell state variables\n                        extended_cell_property -> AppendInternalCellBoundaryConcentrations(rY,boundary_index);\n                        \n                        // rY needs to be both bulk and cell state variables\n                        transport_property->GetTransportOdeSolver()->Solve(transport_property->GetTransportOdeSystem(), rY, time, next_time, dt);\n\n                        extended_cell_property -> ReplaceBoundaryStateVariables(boundary_index, rY);\n                    }\n                }\n                else\n                {   \n                    // cell is not exetended and as such the cell state variables are not stored in the extended cell property \n                    // no voxels to iterate over\n                    //std::cout<<\"transport get external\"<<std::endl;\n                    // rY for bulk state variables at the location specified by the boundary_index\n                    std::vector<double> rY = transport_property -> GetExternalCellBoundaryConcentrationVector();\n                    //std::cout<<\"transport append internal\"<<std::endl;\n                    // append the cell state variables\n                    transport_property -> AppendInternalCellBoundaryConcentrations(rY);\n\n                    // need to combine the outer nad inner values of concentrations either side of the cell into one rY vector\n                    std::vector<double> rDY(rY.size(),0.0);\n                    // whether we need to solve the ode or just perform the reaction system\n                    //transport_property->GetTransportOdeSolver()->Solve(transport_property->GetTransportOdeSystem(), rY, time, next_time, dt);\n                    transport_property->GetTransportOdeSystem()->SetPdeStateRegister(mpPdeSystem->GetStateVariableRegister());\n                    //std::cout<<\"transport evalualte\"<<std::endl;\n                    transport_property->GetTransportOdeSystem()->EvaluateYDerivatives(time, rY, rDY);\n                    for(unsigned i=0; i<rDY.size(); i++)\n                    {\n                        rDY[i] = rDY[i]*dt;\n                    }\n                    \n                    transport_property -> ReplaceBoundaryStateVariables(rY);\n                    transport_property -> ReplaceChangeBoundaryStateVariables(rDY);\n                }\n            }\n   \n            if (cell_iter->HasCellProperty<MembraneCellProperty>())\n            {\n                    \n                boost::shared_ptr<MembraneCellProperty> membrane_property = boost::static_pointer_cast<MembraneCellProperty>(cell_iter->rGetCellPropertyCollection().GetPropertiesType<MembraneCellProperty>().GetProperty());\n                // rY for bulk state variables at the location specified by the boundary_index\n                std::vector<double> rY = membrane_property -> GetExternalCellBoundaryConcentrationVector();\n \n                membrane_property -> AppendInternalCellBoundaryConcentrations(rY);\n                std::vector<double> rDY(rY.size(),0.0);\n                membrane_property->GetMembraneOdeSystem()->SetPdeStateRegister(mpPdeSystem->GetStateVariableRegister());\n      \n                membrane_property->GetMembraneOdeSystem()->EvaluateYDerivatives(time, rY, rDY);\n         \n                for(unsigned i=0; i<rDY.size(); i++)\n                {\n                    rDY[i] = rDY[i]*dt;\n                }\n\n                membrane_property -> ReplaceBoundaryStateVariables(rY);\n\n                membrane_property -> ReplaceChangeBoundaryStateVariables(rDY);\n            }\n        }\n    }\n//std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - PrepareForSetupLinearSystem - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeCoupledCellSolver<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 InhomogenousCoupledPdeOdeCoupledCellSolver<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 InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SolveAndWriteResultsToFile()\n{\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - SolveAndWriteResultsToFile - start\"<<std::endl;\n   \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    // Create a .pvd output file\n\n    OutputFileHandler output_file_handler(this->mOutputDirectory, mClearOutputDirectory);\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    \n\n    // Write initial condition to VTK\n    Vec initial_condition = this->mInitialCondition;\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    // Main time loop\n    while (!stepper.IsTimeAtEnd())\n    {\n        // Reset start and end times\n        this->SetTimes(stepper.GetTime(), stepper.GetNextTime());\n\n        // Solve the system up to the new end time\n        Vec soln = this->Solve();\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        // Write solution to VTK\n        WriteVtkResultsToFile(soln, stepper.GetTotalTimeStepsTaken());\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\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - SolveAndWriteResultsToFile - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::WriteVtkResultsToFile(Vec solution, unsigned numTimeStepsElapsed)\n{\n    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - WriteVtkResultsToFile - start\"<<std::endl;\n#ifdef CHASTE_VTK\n\n\n    // Create a new VTK file for this time step\n    std::stringstream time;\n    time << numTimeStepsElapsed;\n    VtkMeshWriter<ELEMENT_DIM, SPACE_DIM> mesh_writer(this->mOutputDirectory, \"results_\"+time.str(), false);\n    // need to ensure StateVariableRegister is defined\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    unsigned num_nodes = mpFeMesh->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            // do we need to use the rPDEsolution for the other nodes or is 0 the correct (current) choice?\n            //---------------------------------------------------------------------------------\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(*mpFeMesh);\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    //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - SolveAndWriteResultsToFile - end\"<<std::endl;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nAbstractOdeSystemForCoupledPdeSystem* InhomogenousCoupledPdeOdeCoupledCellSolver<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 InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetInterpolationPoint(ChastePoint<SPACE_DIM> point)\n{\n    mX = point;\n}\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nvoid InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetCurrentStateVector(c_vector<double,PROBLEM_DIM> stateVector)\n{\n    mU = stateVector;\n}\n\n\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>\nbool InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::CheckChastePointsForEquality(ChastePoint<SPACE_DIM> rX1,ChastePoint<SPACE_DIM> rX2)\n{   //std::cout<<\"InhomogenousCoupledPdeOdeCoupledCellSolver - CheckChastePointsForEquality\"<<std::endl;\n    // function to check whether two chaste points are congruent\n    // use half the scale dimension as an error\n\n    // half of the voxel dimensions of the tetrahedral mesh, a value to which a point should be congruent\n    std::vector<double> mesh_single_voxel_dimensions(SPACE_DIM,0.4); \n\n    bool equality=true;\n\n    for(unsigned i=0; i<SPACE_DIM; i++)\n    {\n        if(rX1[i] < rX2[i] + mesh_single_voxel_dimensions[i] && rX1[i] >= rX2[i] - mesh_single_voxel_dimensions[i])\n        {\n            // both points are congruent within 0.5 of mesh scale in the ith dimension\n            equality=true;\n        }\n        else\n        {\n            // as soon as a dimension where the points are disaparate is found end the function return false\n            equality=false;\n            break;\n        }\n        \n    }\n    return equality;\n}\n\n\n#endif", "meta": {"hexsha": "49d417e65d29aa6882847d670f9d78c2cefbf3a3", "size": 56871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/InhomogenousCoupledPdeOdeCoupledCellSolver.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/InhomogenousCoupledPdeOdeCoupledCellSolver.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/InhomogenousCoupledPdeOdeCoupledCellSolver.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": 46.8459637562, "max_line_length": 268, "alphanum_fraction": 0.6443178421, "num_tokens": 12541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.015663646442881745, "lm_q1q2_score": 0.006203871723797089}}
{"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#ifndef VERTEXMESH_HPP_\n#define VERTEXMESH_HPP_\n\n// Forward declaration prevents circular include chain\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nclass VertexMeshWriter;\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n\n#include <boost/serialization/base_object.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/vector.hpp>\n#include \"ChasteSerialization.hpp\"\n\n#include \"AbstractMesh.hpp\"\n#include \"ArchiveLocationInfo.hpp\"\n#include \"TetrahedralMesh.hpp\"\n#include \"VertexElement.hpp\"\n#include \"VertexElementMap.hpp\"\n#include \"VertexMeshReader.hpp\"\n#include \"VertexMeshWriter.hpp\"\n\n/**\n * A vertex-based mesh class, in which elements may contain different numbers of nodes.\n * This is facilitated by the VertexElement class.\n *\n * This class has two applications in the cell_based code.\n *\n * First, VertexMesh is used as a member of the MeshBasedCellPopulation class to represent\n * a Voronoi tessellation, the dual to a Delaunay mesh, which allows the shapes of cells\n * to be visualised in simulations of a class of off-lattice cell centre-based models.\n *\n * Second, VertexMesh serves as a parent class for MutableVertexMesh, which is used as a\n * member of the VertexBasedCellPopulation class to represent the junctional network of\n * cells that forms the basis of simulations of off-lattice vertex-based models.\n */\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nclass VertexMesh : public AbstractMesh<ELEMENT_DIM, SPACE_DIM>\n{\n    friend class TestVertexMesh;\n\nprotected:\n    /** Vector of pointers to VertexElements. */\n    std::vector<VertexElement<ELEMENT_DIM, SPACE_DIM>*> mElements;\n\n    /** Vector of pointers to VertexElements. */\n    std::vector<VertexElement<ELEMENT_DIM - 1, SPACE_DIM>*> mFaces;\n\n    /**\n     * Map that is used only when the vertex mesh is used to represent\n     * a Voronoi tessellation, the dual to a Delaunay tetrahedral mesh.\n     * The map consists of pairs (index1, index2), where index1 denotes\n     * the global index of a node in the Delaunay mesh and index2 denotes\n     * the global index of the corresponding element in the Voronoi mesh.\n     */\n    std::map<unsigned, unsigned> mVoronoiElementIndexMap;\n\n    /**\n     * Delaunay tetrahedral mesh that is used only when the vertex mesh\n     * is used to represent a Voronoi tessellation. A pointer to the\n     * Delaunay mesh is required in this case because the Delaunay mesh\n     * may be a subclass of TetrahedralMesh, which overrides methods such as\n     * GetVectorFromAtoB().\n     */\n    TetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* mpDelaunayMesh;\n\n    /**\n     * Solve node mapping method. This overridden method is required\n     * as it is pure virtual in the base class.\n     *\n     * @param index the global index of the node\n     * @return local index\n     */\n    unsigned SolveNodeMapping(unsigned index) const;\n\n    /**\n     * Solve element mapping method. This overridden method is required\n     * as it is pure virtual in the base class.\n     *\n     * @param index the global index of the element\n     * @return local index\n     */\n    unsigned SolveElementMapping(unsigned index) const;\n\n    /**\n     * Solve boundary element mapping method. This overridden method is required\n     * as it is pure virtual in the base class.\n     *\n     * @param index the global index of the boundary element\n     * @return local index\n     */\n    unsigned SolveBoundaryElementMapping(unsigned index) const;\n\n    /**\n     * Populate mNodes with locations corresponding to the element\n     * circumcentres of a given TetrahedralMesh. Used by 'Voronoi'\n     * constructors.\n     *\n     * @param rMesh a tetrahedral mesh\n     */\n    void GenerateVerticesFromElementCircumcentres(TetrahedralMesh<ELEMENT_DIM, SPACE_DIM>& rMesh);\n\n    /**\n     * Test whether a given point lies inside a given element.\n     *\n     * We use a winding number test, which counts the number of times the\n     * polygon associated with the element winds around the given point.\n     * The point is outside only when this \"winding number\" vanishes;\n     * otherwise, the point is inside.\n     *\n     * One must decide whether a point on the polygon's boundary is inside\n     * or outside: we adopt the standard convention that a point on a left\n     * or bottom edge is inside, and a point on a right or top edge is outside.\n     * This way, if two distinct polygons share a common boundary segment,\n     * then a point on that segment will be in one polygon or the other, but\n     * not both at the same time.\n     *\n     * @param rTestPoint the point to test\n     * @param elementIndex global index of the element in the mesh\n     *\n     * @return if the point is included in the element.\n     */\n    bool ElementIncludesPoint(const c_vector<double, SPACE_DIM>& rTestPoint, unsigned elementIndex);\n\n    /**\n     * Get the local index of a given element which is the start vertex of the edge\n     * of the element that the overlapping point rTestPoint is closest to.\n     *\n     * @param rTestPoint the point to test\n     * @param elementIndex global index of the element in the mesh\n     *\n     * @return the local index\n     */\n    unsigned GetLocalIndexForElementEdgeClosestToPoint(const c_vector<double, SPACE_DIM>& rTestPoint, unsigned elementIndex);\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n\n    /**\n     * Archive the VertexMesh and its member variables. Note that this will\n     * write out a VertexMeshWriter file to wherever ArchiveLocationInfo has specified.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template <class Archive>\n    void save(Archive& archive, const unsigned int version) const\n    {\n        archive& boost::serialization::base_object<AbstractMesh<ELEMENT_DIM, SPACE_DIM> >(*this);\n\n        // Create a mesh writer pointing to the correct file and directory\n        VertexMeshWriter<ELEMENT_DIM, SPACE_DIM> mesh_writer(ArchiveLocationInfo::GetArchiveRelativePath(),\n                                                             ArchiveLocationInfo::GetMeshFilename(),\n                                                             false);\n        mesh_writer.WriteFilesUsingMesh(*(const_cast<VertexMesh<ELEMENT_DIM, SPACE_DIM>*>(this)));\n    }\n\n    /**\n     * Load a mesh by using VertexMeshReader and the location in ArchiveLocationInfo.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template <class Archive>\n    void load(Archive& archive, const unsigned int version)\n    {\n        archive& boost::serialization::base_object<AbstractMesh<ELEMENT_DIM, SPACE_DIM> >(*this);\n\n        VertexMeshReader<ELEMENT_DIM, SPACE_DIM> mesh_reader(ArchiveLocationInfo::GetArchiveDirectory() + ArchiveLocationInfo::GetMeshFilename());\n        this->ConstructFromMeshReader(mesh_reader);\n    }\n    BOOST_SERIALIZATION_SPLIT_MEMBER()\n\npublic:\n    /** Forward declaration of element iterator. */\n    class VertexElementIterator;\n\n    /**\n     * @return an iterator to the first element in the mesh.\n     *\n     * @param skipDeletedElements whether to include deleted element\n     */\n    inline VertexElementIterator GetElementIteratorBegin(bool skipDeletedElements = true);\n\n    /**\n     * @return an iterator to one past the last element in the mesh.\n     */\n    inline VertexElementIterator GetElementIteratorEnd();\n\n    /**\n     * Default constructor.\n     *\n     * @param nodes vector of pointers to nodes\n     * @param vertexElements vector of pointers to VertexElements\n     */\n    VertexMesh(std::vector<Node<SPACE_DIM>*> nodes,\n               std::vector<VertexElement<ELEMENT_DIM, SPACE_DIM>*> vertexElements);\n\n    /**\n     * Constructor.\n     *\n     * @param nodes vector of pointers to nodes\n     * @param faces vector of pointer to VertexElements\n     * @param vertexElements vector of pointers to VertexElement<3,3>s\n     */\n    VertexMesh(std::vector<Node<SPACE_DIM>*> nodes,\n               std::vector<VertexElement<ELEMENT_DIM - 1, SPACE_DIM>*> faces,\n               std::vector<VertexElement<ELEMENT_DIM, SPACE_DIM>*> vertexElements);\n\n    /**\n     * @brief  Alternative 2D 'Voronoi' constructor.\n     *\n     * This VertexMesh constructor is currently only defined for 2D meshes.\n     *\n     * Creates a Voronoi tessellation of a given tetrahedral mesh,\n     * which must be Delaunay (see TetrahedralMesh::CheckIsVoronoi).\n     *\n     * \\todo Merge with 3D Voronoi constructor? (see #1075)\n     *\n     * @param rMesh a tetrahedral mesh\n     * @param isPeriodic a boolean that indicates whether the mesh is periodic or not\n     */\n    VertexMesh(TetrahedralMesh<2, 2>& rMesh, bool isPeriodic = false);\n\n    /**\n     * Alternative 3D 'Voronoi' constructor. Creates a Voronoi tessellation of a given tetrahedral mesh,\n     * which must be Delaunay (see TetrahedralMesh::CheckIsVoronoi).\n     *\n     * \\todo Merge with 2D Voronoi constructor? (see #1075)\n     *\n     * @param rMesh a tetrahedral mesh\n     */\n    VertexMesh(TetrahedralMesh<3, 3>& rMesh);\n\n    /**\n     * Default constructor for use by serializer.\n     */\n    VertexMesh();\n\n    /**\n     * Destructor.\n     */\n    virtual ~VertexMesh();\n\n    /**\n     * @return the number of Nodes in the mesh.\n     */\n    virtual unsigned GetNumNodes() const;\n\n    /**\n     * @return the number of VertexElements in the mesh.\n     */\n    virtual unsigned GetNumElements() const;\n\n    /**\n     * @return the number of VertexElements in the mesh, including those marked as deleted.\n     */\n    unsigned GetNumAllElements() const;\n\n    /**\n     * @return the number of Faces in the mesh.\n     */\n    virtual unsigned GetNumFaces() const;\n\n    /**\n     * @param index  the global index of a specified vertex element.\n     *\n     * @return a pointer to the vertex element\n     */\n    VertexElement<ELEMENT_DIM, SPACE_DIM>* GetElement(unsigned index) const;\n\n    /**\n     * @param index  the global index of a specified face.\n     *\n     * @return a pointer to the face\n     */\n    VertexElement<ELEMENT_DIM - 1, SPACE_DIM>* GetFace(unsigned index) const;\n\n    /**\n     * Compute the centroid of an element.\n     *\n     * A formula for the centroid of a plane polygon may be found e.g. in the following reference:\n     *\n     * Mechanics of Materials\n     * James M. Gere (Author), Barry J. Goodno.\n     * Cengage Learning; 8th edition (January 1, 2012)\n     *\n     * This needs to be overridden in daughter classes for non-Euclidean metrics.\n     *\n     * @param index  the global index of a specified vertex element\n     *\n     * @return (centroid_x, centroid_y).\n     */\n    virtual c_vector<double, SPACE_DIM> GetCentroidOfElement(unsigned index);\n\n    /**\n     * Construct the mesh using a MeshReader.\n     *\n     * @param rMeshReader the mesh reader\n     */\n    void ConstructFromMeshReader(AbstractMeshReader<ELEMENT_DIM, SPACE_DIM>& rMeshReader);\n\n    /**\n     * Delete mNodes, mFaces and mElements.\n     */\n    virtual void Clear();\n\n    /**\n     * @return the global index of the corresponding element in the Delaunay mesh,\n     * given the global index of an element in the Voronoi mesh.\n     * @param elementIndex global index of an element in the Voronoi mesh\n     */\n    unsigned GetDelaunayNodeIndexCorrespondingToVoronoiElementIndex(unsigned elementIndex);\n\n    /**\n     * @return the global index of the corresponding element in the Voronoi\n     * mesh given the global index of a node in the Delaunay mesh,  or\n     * throws an exception if this does not exist.\n     *\n     * @param nodeIndex global index of a node in the Delaunay mesh\n     */\n    unsigned GetVoronoiElementIndexCorrespondingToDelaunayNodeIndex(unsigned nodeIndex);\n\n    /**\n     * Get the \"rosette rank\" of an element.\n     *\n     * This is defined as the maximum number of elements shared by any node in the specified element.\n     *\n     * @param index  the global index of a specified vertex element\n     *\n     * @return the rosette rank of the element\n     */\n    unsigned GetRosetteRankOfElement(unsigned index);\n\n    /**\n     * Overridden GetVectorFromAtoB() method. Returns a vector between two points in space.\n     *\n     * If the mesh is being used to represent a Voronoi tessellation, and mpDelaunayMesh\n     * is not NULL, then use that to compute GetVectorFromAtoB.\n     *\n     * @param rLocationA a c_vector of coordinates\n     * @param rLocationB a c_vector of coordinates\n     *\n     * @return c_vector from location A to location B.\n     */\n    virtual c_vector<double, SPACE_DIM> GetVectorFromAtoB(const c_vector<double, SPACE_DIM>& rLocationA,\n                                                          const c_vector<double, SPACE_DIM>& rLocationB);\n\n    /**\n     * Get the volume (or area in 2D, or length in 1D) of an element.\n     *\n     * This needs to be overridden in daughter classes for non-Euclidean metrics.\n     *\n     * @param index  the global index of a specified vertex element\n     *\n     * @return the volume of the element\n     */\n    virtual double GetVolumeOfElement(unsigned index);\n\n    /**\n     * Compute the surface area (or perimeter in 2D) of an element.\n     *\n     * This needs to be overridden in daughter classes for non-Euclidean metrics.\n     *\n     * @param index  the global index of a specified vertex element\n     *\n     * @return the surfacearea of the element\n     */\n    virtual double GetSurfaceAreaOfElement(unsigned index);\n\n    /**\n     * Compute the area gradient of a 2D element at one of its nodes.\n     *\n     * N.B. This calls GetVectorFromAtoB(), which can be overridden\n     * in daughter classes for non-Euclidean metrics.\n     *\n     * @param pElement  pointer to a specified vertex element\n     * @param localIndex  local index of a node in this element\n     *\n     * @return the gradient of the area of the element, evaluated at this node.\n     */\n    c_vector<double, SPACE_DIM> GetAreaGradientOfElementAtNode(VertexElement<ELEMENT_DIM, SPACE_DIM>* pElement, unsigned localIndex);\n\n    /**\n     * Compute the gradient of the edge of a 2D element ending at its nodes.\n     *\n     * N.B. This calls GetVectorFromAtoB(), which can be overridden\n     * in daughter classes for non-Euclidean metrics.\n     *\n     * @param pElement  pointer to a specified vertex element\n     * @param localIndex  local index of a node in this element\n     *\n     * @return the gradient of the edge of the element that ends at this node.\n     */\n    c_vector<double, SPACE_DIM> GetPreviousEdgeGradientOfElementAtNode(VertexElement<ELEMENT_DIM, SPACE_DIM>* pElement, unsigned localIndex);\n\n    /**\n     * Compute the gradient of the edge of a 2D element starting at its nodes.\n     *\n     * N.B. This calls GetVectorFromAtoB(), which can be overridden\n     * in daughter classes for non-Euclidean metrics.\n     *\n     * @param pElement  pointer to a specified vertex element\n     * @param localIndex  local index of a node in this element\n     *\n     * @return the gradient of the edge of the element that starts at this node.\n     */\n    c_vector<double, SPACE_DIM> GetNextEdgeGradientOfElementAtNode(VertexElement<ELEMENT_DIM, SPACE_DIM>* pElement, unsigned localIndex);\n\n    /**\n     * Compute the gradient of the perimeter of a 2D element at its nodes.\n     * This returns the sum of GetPreviousEdgeGradientAtNode() and GetNextEdgeGradientAtNode().\n     *\n     * @param pElement  pointer to a specified vertex element\n     * @param localIndex  local index of a node in this element\n     *\n     * @return the gradient of the perimeter of the element, evaluated at this node.\n     */\n    c_vector<double, SPACE_DIM> GetPerimeterGradientOfElementAtNode(VertexElement<ELEMENT_DIM, SPACE_DIM>* pElement, unsigned localIndex);\n\n    /**\n     * Compute the second moments and product moment of area for a given 2D element\n     * about its centroid. These are:\n     *\n     * I_xx, the second moment of area about an axis through the centroid of the\n     * element parallel to the x-axis;\n     *\n     * I_yy, the second moment of area about an axis through the centroid of the\n     * element parallel to the y-axis;\n     *\n     * and I_xy, product moment of area through the centroid of the element.\n     *\n     * Formulae for these quantities may be found e.g. in the following reference:\n     *\n     * Mechanics of Materials\n     * James M. Gere (Author), Barry J. Goodno.\n     * Cengage Learning; 8th edition (January 1, 2012)\n     *\n     * This method is used within GetShortAxisOfElement() to compute the direction\n     * of the shortest principal axis passing through the centroid, or 'short axis',\n     * of the element.\n     *\n     * Note that by definition, the second moments of area must be non-negative,\n     * while the product moment of area may not be.\n     *\n     * @param index  the global index of a specified vertex element\n     *\n     * @return (Ixx,Iyy,Ixy).\n     */\n    virtual c_vector<double, 3> CalculateMomentsOfElement(unsigned index);\n\n    /**\n     * @return the length of the edge separating two given elements in 2D.\n     *\n     * @param elementIndex1 index of an element in the mesh\n     * @param elementIndex2 index of an element in the mesh\n     */\n    double GetEdgeLength(unsigned elementIndex1, unsigned elementIndex2);\n\n    /**\n     * Get the elongation shape factor of a given element.\n     * This is defined as the square root of the ratio of\n     * the two second moments of the element around its\n     * principal axes.\n     *\n     * @param elementIndex index of an element in the mesh\n     *\n     * @return the elongation shape factor of the element.\n     */\n    double GetElongationShapeFactorOfElement(unsigned elementIndex);\n\n    /**\n     * Compute the unit normal vector to a given face in 3D. This is achieved by calculating scaled normal,\n     * which is the effective sum of signed areas of triangle forming the face.\n     * Note: this may return the outward or inward normal, depending\n     * on the face chirality.\n     *\n     * @param pFace a face in the mesh\n     * @param rNormal vector in which to return the unit normal\n     *\n     * @return the area\n     */\n    double CalculateUnitNormalToFaceWithArea(VertexElement<ELEMENT_DIM - 1, SPACE_DIM>* pFace, c_vector<double, SPACE_DIM>& rNormal);\n\n    /**\n     * Get the area of a given face in 3D.  Uses CalculateUnitNormalToFaceWithArea\n     *\n     * This needs to be overridden in daughter classes for non-Euclidean metrics.\n     *\n     * @param pFace a face in the mesh\n     *\n     * @return the area\n     */\n    virtual double CalculateAreaOfFace(VertexElement<ELEMENT_DIM - 1, SPACE_DIM>* pFace);\n\n    /**\n     * Compute the direction of the shortest principal axis passing through the centroid,\n     * or 'short axis', of a given element. This is the eigenvector associated with the\n     * eigenvalue of largest magnitude of the inertia matrix\n     *\n     * J = (  I_xx  -I_xy )\n     *     ( -I_xy   I_yy )\n     *\n     * whose entries are computed by calling the method CalculateMomentsOfElement().\n     *\n     * Note that if the nodes owned by the element are supplied in clockwise rather than\n     * anticlockwise manner, or if this arises when any periodicity is enforced, then the\n     * sign of each moment may be incorrect change. This means that we need to consider the eigenvalue\n     * of largest magnitude rather than largest value when computing the short axis of the\n     * element.\n     *\n     * If the element is a regular polygon then the eigenvalues of the inertia tensor are\n     * equal: in this case we return a random unit vector.\n     *\n     * This method is only implemented in 2D at present.\n     *\n     * @param index  the global index of a specified vertex element\n     *\n     * @return a unit vector giving the direction of the short axis\n     */\n    c_vector<double, SPACE_DIM> GetShortAxisOfElement(unsigned index);\n\n    /**\n     * Given a node, find a set containing the indices of its neighbouring nodes.\n     *\n     * @param nodeIndex global index of the node\n     * @return its neighbouring node indices\n     */\n    std::set<unsigned> GetNeighbouringNodeIndices(unsigned nodeIndex);\n\n    /**\n     * Given a node and one of its containing elements, find a set containing\n     * the indices of those neighbouring node(s) that are NOT also in the element.\n     *\n     * Note that we allow for more than one such index, since there is no reason\n     * a priori to assume that each node is contained by exactly three elements.\n     *\n     * @param nodeIndex global index of the node\n     * @param elemIndex global index of the element\n     *\n     * @return its neighbouring nodes that are not in the element\n     */\n    std::set<unsigned> GetNeighbouringNodeNotAlsoInElement(unsigned nodeIndex, unsigned elemIndex);\n\n    /**\n     * Given an element, find a set containing the indices of its neighbouring elements.\n     *\n     * @param elementIndex global index of the element\n     * @return its neighbouring element indices\n     */\n    std::set<unsigned> GetNeighbouringElementIndices(unsigned elementIndex);\n\n    /**\n     * Return a pointer to the vertex mesh\n     *\n     * This method may be overridden in daughter classes for non-Euclidean metrics.\n     * This can then be used when writing to VTK.\n     *\n     * @return a pointer to the vertex mesh\n     */\n    virtual VertexMesh<ELEMENT_DIM, SPACE_DIM>* GetMeshForVtk();\n\n    /**\n     * A smart iterator over the elements in the mesh.\n     *\n     * \\todo This is the same as in AbstractTetrahedralMesh and PottsMesh - merge? (#1379)\n     */\n    class VertexElementIterator\n    {\n    public:\n        /**\n         * Dereference the iterator giving you a *reference* to the current element.\n         * @return reference\n         * Make sure to use a reference for the result to avoid copying elements unnecessarily.\n         */\n        inline VertexElement<ELEMENT_DIM, SPACE_DIM>& operator*();\n\n        /**\n         * Member access from a pointer.\n         * @return pointer\n         */\n        inline VertexElement<ELEMENT_DIM, SPACE_DIM>* operator->();\n\n        /**\n         * Comparison not-equal-to.\n         * @return true if not equal\n         * @param rOther iterator with which comparison is made\n         */\n        inline bool operator!=(const typename VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator& rOther);\n\n        /**\n         * Prefix increment operator.\n         * @return reference to incremented object\n         */\n        inline VertexElementIterator& operator++();\n\n        /**\n         * Constructor for a new iterator.\n         *\n         * This should not be called directly by user code; use the mesh methods\n         * VertexMesh::GetElementIteratorBegin and VertexMesh::GetElementIteratorEnd instead.\n         *\n         * @param rMesh the mesh to iterator over\n         * @param elementIter where to start iterating\n         * @param skipDeletedElements whether to include deleted elements\n         */\n        VertexElementIterator(VertexMesh<ELEMENT_DIM, SPACE_DIM>& rMesh,\n                              typename std::vector<VertexElement<ELEMENT_DIM, SPACE_DIM>*>::iterator elementIter,\n                              bool skipDeletedElements = true);\n\n    private:\n        /** The mesh we're iterating over. */\n        VertexMesh& mrMesh;\n\n        /** The actual element iterator. */\n        typename std::vector<VertexElement<ELEMENT_DIM, SPACE_DIM>*>::iterator mElementIter;\n\n        /** Whether to skip deleted elements. */\n        bool mSkipDeletedElements;\n\n        /**\n         * Helper method to say when we're at the end.\n         * @return true if at end\n         */\n        inline bool IsAtEnd();\n\n        /**\n         * Helper method to say if we're allowed to point at this element.\n         * @return true if allowed\n         */\n        inline bool IsAllowedElement();\n    };\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_ALL_DIMS(VertexMesh)\n\n//////////////////////////////////////////////////////////////////////////////\n// VertexElementIterator class implementation - most methods are inlined    //\n//////////////////////////////////////////////////////////////////////////////\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\ntypename VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator VertexMesh<ELEMENT_DIM, SPACE_DIM>::GetElementIteratorBegin(\n    bool skipDeletedElements)\n{\n    return VertexElementIterator(*this, mElements.begin(), skipDeletedElements);\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\ntypename VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator VertexMesh<ELEMENT_DIM, SPACE_DIM>::GetElementIteratorEnd()\n{\n    return VertexElementIterator(*this, mElements.end());\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nVertexElement<ELEMENT_DIM, SPACE_DIM>& VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator::operator*()\n{\n    assert(!IsAtEnd());\n    return **mElementIter;\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nVertexElement<ELEMENT_DIM, SPACE_DIM>* VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator::operator->()\n{\n    assert(!IsAtEnd());\n    return *mElementIter;\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nbool VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator::operator!=(const typename VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator& rOther)\n{\n    return mElementIter != rOther.mElementIter;\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\ntypename VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator& VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator::operator++()\n{\n    do\n    {\n        ++mElementIter;\n    } while (!IsAtEnd() && !IsAllowedElement());\n\n    return (*this);\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nVertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator::VertexElementIterator(\n    VertexMesh<ELEMENT_DIM, SPACE_DIM>& rMesh,\n    typename std::vector<VertexElement<ELEMENT_DIM, SPACE_DIM>*>::iterator elementIter,\n    bool skipDeletedElements)\n        : mrMesh(rMesh),\n          mElementIter(elementIter),\n          mSkipDeletedElements(skipDeletedElements)\n{\n    if (mrMesh.mElements.empty())\n    {\n        // Cope with empty meshes\n        mElementIter = mrMesh.mElements.end();\n    }\n    else\n    {\n        // Make sure we start at an allowed element\n        if (mElementIter == mrMesh.mElements.begin() && !IsAllowedElement())\n        {\n            ++(*this);\n        }\n    }\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nbool VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator::IsAtEnd()\n{\n    return mElementIter == mrMesh.mElements.end();\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nbool VertexMesh<ELEMENT_DIM, SPACE_DIM>::VertexElementIterator::IsAllowedElement()\n{\n    return !(mSkipDeletedElements && (*this)->IsDeleted());\n}\n\n#endif /*VERTEXMESH_HPP_*/\n", "meta": {"hexsha": "40c6acb5ca7197f8287449a9d83c537466e1728f", "size": 28543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mesh/src/vertex/VertexMesh.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": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mesh/src/vertex/VertexMesh.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": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mesh/src/vertex/VertexMesh.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": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6060606061, "max_line_length": 156, "alphanum_fraction": 0.6845811583, "num_tokens": 6437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405053215160805, "lm_q2_score": 0.019719127531259237, "lm_q1q2_score": 0.0061928024947573886}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Coagulation class declared in the\n    swp_coagulation.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_PAH_primary.h\"\n#include \"swp_coagulation.h\"\n#include \"swp_mechanism.h\"\n#include <stdexcept>\n#include <iostream>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_01.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::Processes;\nusing namespace std;\n\n// Base coagulation class.\n\n/*!\n * @param[in]   mech    Mechanism to which this process should look for services like LPDA\n *\n * Default rate scaling to 1 for backwards compatibility\n */\n Coagulation::Coagulation(const Sweep::Mechanism &mech)\n : Process(mech)\n , mPositionChoice(NoPositionChoice)\n {}\n\n/*!\n * @param[in]       t       Time at which rates are to be calculated\n * @param[in]       sys     System for which rates are to be calculated\n * @param[in]       local_geom  Spatial configuration information\n * @param[in]       coags   Coagulation processes defining the rates\n * @param[in,out]   rates   Vector to which to add the rates of the individual coagulations\n * @param[in]       start   Position in rates at which to start inserting rates\n *\n * @return      Total rate of all the coagulation processes\n */\ndouble Coagulation::CalcRates(double t, const Cell &sys, const Geometry::LocalGeometry1d &local_geom,\n                            const CoagPtrVector &coags, fvector &rates, unsigned int start)\n{\n    // Iterators for the coagulation processes\n    CoagPtrVector::const_iterator itCoag = coags.begin();\n    const CoagPtrVector::const_iterator itCoagEnd = coags.end();\n\n    // Iterator for the rate vector\n    fvector::iterator it = (rates.begin()+start);\n\n    // Use this variable to accumulate the overall sum of the rates\n    double sum = 0.0;\n    while(itCoag != itCoagEnd) {\n        // Store the rate and move on to the next coagulation process\n        *it = (*itCoag++)->Rate(t, sys, local_geom);\n\n        // Add the rate to the sum and move the rates vector iterator onto the next position\n        sum += *it++;\n    }\n    return sum;\n}\n\n/*!\n * @param[in]       t       Time at which rates are to be calculated\n * @param[in]       sys     System for which rates are to be calculated\n * @param[in]       local_geom  Spatial configuration information\n * @param[in]       coags   Coagulation processes defining the rates\n * @param[in,out]   iterm   Iterator to point at which to put rate terms of the individual coagulations\n *\n * @return      Total rate of all the coagulation processes\n */\ndouble Coagulation::CalcRateTerms(double t, const Cell &sys, const Geometry::LocalGeometry1d &local_geom,\n                                const CoagPtrVector &coags, fvector::iterator &iterm) {\n    // Iterators for the coagulation processes\n    CoagPtrVector::const_iterator itCoag = coags.begin();\n    const CoagPtrVector::const_iterator itCoagEnd = coags.end();\n\n    // Use this variable to accumulate the overall sum of the rates\n    double sum = 0.0;\n    while(itCoag != itCoagEnd) {\n        // The next line does three things, effectively in the following order\n        // i) Calls RateTerms on *itCoag\n        // ii) Advances itCoag\n        // iii) Adds the return value of RateTerms to sum\n        // Note that the order of 2 and 3 could be reversed without having any effect\n        sum += (*itCoag++)->RateTerms(t, sys, local_geom, iterm);\n    }\n    return sum;\n }\n\n/*!\n *@param[in]        t           Time at which coagulation is being performed\n *@param[in]        ip1         Index of first particle in ensemble\n *@param[in,out]    sp1         Pointer to first particle\n *@param[in]        ip2         Index of second particle in ensemble\n *@param[in,out]    sp2         Pointer to second particle\n *@param[in]        sys         Cell containing particles that are coagulating\n *@param[in,out]    rng         Random number generator\n *\n *@return       Index of new, larger particle\n */\nint Coagulation::JoinParticles(const double t, const int ip1, Particle *sp1,\n                               const int ip2, Particle *sp2,\n                               Cell &sys, rng_type &rng) const {\n\n    // Position for particle after coagulation, default is to take whatever happens\n    // to be in sp1\n    double newPos = sp1->getPosition();\n    double newPosTime = sp1->getPositionTime();\n    if(mPositionChoice == UniformPositionChoice) {\n        // Change to position of sp2 with prob 0.5 (bernoulli distribution defaults to prob 0.5)\n        boost::bernoulli_distribution<> bernoulliDistrib;\n        boost::variate_generator<rng_type &, boost::bernoulli_distribution<> > positionChooser(rng, bernoulliDistrib);\n        if(positionChooser()) {\n            newPos = sp2->getPosition();\n            newPosTime = sp2->getPositionTime();\n        }\n    }\n    else if (mPositionChoice == MassPositionChoice) {\n        // Change to position of sp2 with prob sp2->Mass()/(sp1->Mass() + sp2->Mass())\n        boost::bernoulli_distribution<double> bernoulliDistrib(sp2->Mass()/(sp1->Mass() + sp2->Mass()));\n        boost::variate_generator<rng_type &, boost::bernoulli_distribution<double> > positionChooser(rng, bernoulliDistrib);\n\n        if(positionChooser()) {\n            newPos = sp2->getPosition();\n            newPosTime = sp2->getPositionTime();\n        }\n    }\n    else if (mPositionChoice == LargestMassPositionChoice) {\n        // Change to position of particle with largest mass (default to first particle if masses equal)\n        if(sp1->Mass() < sp2->Mass()) {\n            newPos = sp2->getPosition();\n            newPosTime = sp2->getPositionTime();\n        }\n        else {\n            newPos = sp1->getPosition();\n            newPosTime = sp1->getPositionTime();\n        }\n    }\n    else if (mPositionChoice == MidpointPositionChoice) {\n        // Pick the half way point\n        newPos = (sp1->getPosition() + sp2->getPosition()) / 2;\n        newPosTime = (sp1->getPositionTime() + sp2->getPositionTime()) / 2;\n    }\n    else if (mPositionChoice == CentreOfMassPositionChoice) {\n        const double m1 = sp1->Mass();\n        const double m2 = sp2->Mass();\n        newPos = (m1 * sp1->getPosition() + m2 * sp2->getPosition()) / (m1 + m2);\n        newPosTime = (m1 * sp1->getPositionTime() + m2 * sp2->getPositionTime()) / (m1 + m2);\n    }\n\n\n    //sys.Particles().SetNumOfInceptedPAH(-1,sp1->Primary());\n\n    // Add contents of particle 2 onto particle 1\n    sp1->Coagulate(*sp2, rng);\n    sp1->setPositionAndTime(newPos, newPosTime);\n    sp1->SetTime(t);\n    sp1->incrementCoagCount();\n\n\t//if one of the coagulating particles is tracked then we wish to keep tracking it \n\tif (sys.Particles().TrackedParticleNumber() > 0){\n\t\tsys.Particles().UpdateTracking(ip2, ip1);\n\t}\n\n    // Tell the ensemble that particle 1 has changed\n    sys.Particles().Update(ip1);\n    // Particle 2 is now part of particle 1\n\n    // For hybrid particle model\n    // if this particle was introduced from the particle-number model, \n    // it does not exist in the ensemble\n    if (!(m_mech->IsHybrid() && ip2 == -2)) \n        sys.Particles().Remove(ip2, true);\n    return ip1;\n}\n\n/*!\n *@param[in]        t           Time at which coagulation is being performed\n *@param[in]        prop1       Rule for choosing first particle\n *@param[in]        prop2       Rule for choosing second particle\n *@param[in]        weight_rule Specify how to combine particle weights\n *@param[in,out]    sys         Cell containing particles that are coagulating\n *@param[in,out]    rng         Random number generator\n *@param[in]        maj         Specify which majorant to use\n *\n *@return       Negative on failure, 0 on success\n *\n * Weighted coagulation is not symmetric, nothing happens to the second particle,\n * it simply defined a size increment for the first particle.\n */\nint Coagulation::WeightedPerform(const double t, const Sweep::PropID prop1,\n                                 const Sweep::PropID prop2,\n                                 const Sweep::Processes::CoagWeightRule weight_rule,\n                                 Cell &sys, rng_type &rng,\n                                 MajorantType maj) const {\n\n\tPartPtrVector dummy;\n\n    int ip1 = sys.Particles().Select(prop1, rng);\n    int ip2 = sys.Particles().Select(prop2, rng);\n\n    // Choose and get first particle, then update it.\n    Particle *sp1=NULL;\n    if (ip1 >= 0) {\n        sp1 = sys.Particles().At(ip1);\n    } else {\n        // Failed to choose a particle.\n        return -1;\n    }\n\n    // Choose and get unique second particle, then update it.  Note, we are allowed to do\n    // this even if the first particle was invalidated.\n    unsigned int guard = 0;\n    while ((ip2 == ip1) && (++guard<1000))\n            ip2 = sys.Particles().Select(prop2, rng);\n\n    Particle *sp2=NULL;\n    if ((ip2>=0) && (ip2!=ip1)) {\n        sp2 = sys.Particles().At(ip2);\n    } else {\n        // Failed to select a unique particle.\n        return -1;\n    }\n\n    //Calculate the majorant rate before updating the particles\n    const double majk = MajorantKernel(*sp1, *sp2, sys, maj);\n\n    //Update the particles\n\tm_mech->UpdateParticle(*sp1, sys, t, ip1, rng, dummy);\n    // Check that particle is still valid.  If not,\n    // remove it and cease coagulating.\n    if (!sp1->IsValid()) {\n        // Must remove first particle now.\n        sys.Particles().Remove(ip1);\n\n        // Invalidating the index tells this routine not to perform coagulation.\n        ip1 = -1;\n        return 0;\n    }\n\n\tm_mech->UpdateParticle(*sp2, sys, t, ip2, rng, dummy);\n    // Check validity of particles after update.\n    if (!sp2->IsValid()) {\n        // Tell the ensemble to update particle one before we confuse things\n        // by removing particle 2\n        sys.Particles().Update(ip1);\n\n        // Must remove second particle now.\n        sys.Particles().Remove(ip2);\n\n        // Invalidating the index tells this routine not to perform coagulation.\n        ip2 = -1;\n\n        return 0;\n    }\n\n    // Check that both the particles are still valid.\n    if ((ip1>=0) && (ip2>=0)) {\n        // Must check for ficticious event now by comparing the original\n        // majorant rate and the current (after updates) true rate.\n\n        double truek = CoagKernel(*sp1, *sp2, sys);\n        double ceff=0;\n        if (majk<truek)\n            std::cout << \"maj< true\"<< std::endl;\n\n\t\t//added by ms785 to include the collision efficiency in the calculation of the rate\n\t\tif (sys.ParticleModel()->AggModel()==AggModels::PAH_KMC_ID)\n\t\t{\n\t\t\t ceff=sys.ParticleModel()->CollisionEff(sp1,sp2);\n\t\t\t truek*=ceff;\n\t\t}\n\n        if (!Fictitious(majk, truek, rng)) {\n            //Adjust the statistical weight\n            switch(weight_rule) {\n            case Sweep::Processes::CoagWeightHarmonic :\n                sp1->setStatisticalWeight(1.0 / (1.0 / sp1->getStatisticalWeight() +\n                                                 1.0 / sp2->getStatisticalWeight()));\n                break;\n            case Sweep::Processes::CoagWeightHalf :\n                sp1->setStatisticalWeight(0.5 * sp1->getStatisticalWeight());\n                break;\n            case Sweep::Processes::CoagWeightMass :\n                sp1->setStatisticalWeight(sp1->getStatisticalWeight() * sp1->Mass() /\n                                          (sp1->Mass() + sp2->Mass()));\n                break;\n            case Sweep::Processes::CoagWeightRule4 : {\n                // This is an arbitrary weighting for illustrative purposes\n                const double x1 = sp1->Mass() / std::sqrt(sp1->getStatisticalWeight());\n                const double x2 = sp1->Mass() / std::sqrt(sp2->getStatisticalWeight());\n                sp1->setStatisticalWeight(sp1->getStatisticalWeight() * x1 /\n                                          (x1 + x2));\n                break;\n                }\n            default:\n                throw std::logic_error(\"Unrecognised weight rule (Coagulation::WeightedPerform)\");\n            }\n\n            // In the weighted particle method the contents of particle 2\n            // is added to particle 1 while particle 2 is left unchanged.\n            // If particle 1 is a single primary particle made up one PAH:\n            // the incepted PAH, after the coagulate event there is then\n            // one less incepted PAH. This is what the check does. If\n            // particle 1 is a PAH other than the incepted PAH, there is\n            // not a need to made an adjustment to the number of incepted PAHs.\n\t\t\t//sys.Particles().SetNumOfInceptedPAH(-1,sp1->Primary());\n\n            // Add contents of particle 2 onto particle 1\n            sp1->Coagulate(*sp2, rng);\n            sp1->SetTime(t);\n            sp1->incrementCoagCount();\n\n            assert(sp1->IsValid());\n            // Tell the ensemble that particles 1 and 2 have changed\n            sys.Particles().Update(ip1);\n            sys.Particles().Update(ip2);\n        } else {\n            sys.Particles().Update(ip1);\n            sys.Particles().Update(ip2);\n            return 1; // Ficticious event.\n        }\n    } else {\n        // One or both particles were invalidated on update,\n        // but that's not a problem.  Information on the update\n        // of valid particles must be propagated into the binary\n        // tree\n        if(ip1 >= 0)\n            sys.Particles().Update(ip1);\n\n        if(ip2 >= 0)\n            sys.Particles().Update(ip2);\n    }\n\n    return 0;\n}\n\n// Writes the object to a binary stream.\nvoid Coagulation::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Output position choice rule\n        out.write(reinterpret_cast<const char*>(&mPositionChoice), sizeof(mPositionChoice));\n\n        // Serialize base class.\n        Process::Serialize(out);\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, Coagulation::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid Coagulation::Deserialize(std::istream &in, const Sweep::Mechanism &mech)\n{\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        switch (version) {\n            case 0:\n                in.read(reinterpret_cast<char*>(&mPositionChoice), sizeof(mPositionChoice));\n\n                // Deserialize base class.\n                Process::Deserialize(in, mech);\n\n                break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, Coagulation::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, Coagulation::Deserialize).\");\n    }\n}\n\n\n//==============================================================\n", "meta": {"hexsha": "6af73333ef49b0f0c761aac3f6466720e59901a3", "size": 16335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_coagulation.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_coagulation.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_coagulation.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 38.3450704225, "max_line_length": 124, "alphanum_fraction": 0.6139577594, "num_tokens": 3917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2309197629292718, "lm_q2_score": 0.02675928580494465, "lm_q1q2_score": 0.0061792479342344464}}
{"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__UTILS_HPP_\n#define OPTIMIZATION__UTILS_HPP_\n\n#include <common/types.hpp>\n#include <optimization/visibility_control.hpp>\n#include <Eigen/Core>\n#include <functional>\n#include <limits>\n\nusing autoware::common::types::bool8_t;\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace optimization\n{\n/// Configuration class to sepcify which terms should get\n/// computed during the evaluation of an expression. By default all terms default to false.\n/// Terms to be computed should be enabled/set by either the constructor or the setter\n/// methods.\nclass OPTIMIZATION_PUBLIC ComputeMode\n{\npublic:\n  /// Constructor\n  ComputeMode() = default;\n  /// Constructor with initial values.\n  /// \\param score True if score is to be computed.\n  /// \\param jacobian True if jacobian is to be computed.\n  /// \\param hessian True if hessian is to be computed.\n  ComputeMode(bool8_t score, bool8_t jacobian, bool8_t hessian);\n  /// Set score to true, return the new state for method chaining.\n  /// \\return Current modified instance.\n  ComputeMode & set_score() noexcept;\n  /// Set jacobian to true, return the new state for method chaining.\n  /// \\return Current modified instance.\n  ComputeMode & set_jacobian() noexcept;\n  /// Set hessian to true, return the new state for method chaining.\n  /// \\return Current modified instance.\n  ComputeMode & set_hessian() noexcept;\n\n  /// Get if score term is enabled.\n  /// \\return True if score term is enabled.\n  bool8_t score() const noexcept;\n  /// Get if jacobian term is enabled.\n  /// \\return True if jacobian term is enabled.\n  bool8_t jacobian() const noexcept;\n  /// Get if hessian term is enabled.\n  /// \\return True if hessian term is enabled.\n  bool8_t hessian() const noexcept;\n\n  bool8_t operator==(const ComputeMode & other) const noexcept;\n  bool8_t operator!=(const ComputeMode & other) const noexcept;\n\nprivate:\n  bool8_t m_score{false};\n  bool8_t m_jacobian{false};\n  bool8_t m_hessian{false};\n};\n\n/// Enum class representing expression terms\nenum class ExpressionTerm\n{\n  SCORE,  // Evaluation of the expression\n  JACOBIAN,  // Evaluation of the first derivative\n  HESSIAN   // Evaluation of the second derivative\n};\n\n/// Generic equality comparison functor for eigen matrices.\nclass OPTIMIZATION_PUBLIC EigenComparator\n{\npublic:\n  template<typename T, int H, int W>\n  typename std::enable_if_t<std::is_floating_point<T>::value, bool8_t>\n  operator()(const Eigen::Matrix<T, H, W> & lhs, const Eigen::Matrix<T, H, W> & rhs) const\n  {\n    return lhs.isApprox(rhs, std::numeric_limits<T>::epsilon());\n  }\n\n  template<typename T, int H, int W>\n  typename std::enable_if_t<std::is_integral<T>::value, bool8_t>\n  operator()(const Eigen::Matrix<T, H, W> & lhs, const Eigen::Matrix<T, H, W> & rhs) const\n  {\n    return lhs == rhs;\n  }\n};\n\n/// State machine to keep track of the cache state of an expression\n/// \\tparam DomainValue Value type\n/// \\tparam ComparatorT Equality comparison functor for DomainValue\ntemplate<typename DomainValue, typename ComparatorT = decltype(std::equal_to<DomainValue>())>\nclass OPTIMIZATION_PUBLIC CacheStateMachine\n{\npublic:\n  /// Constructor\n  /// \\param comparator Equality comparison functor object.\n  explicit CacheStateMachine(const ComparatorT & comparator = ComparatorT())\n  : m_comparator(comparator) {}\n\n  /// Constructor with initial values.\n  /// \\param value Initial value\n  /// \\param mode Initial mode\n  /// \\param comparator Equality comparison functor object.\n  CacheStateMachine(\n    const DomainValue & value, const ComputeMode & mode,\n    const ComparatorT & comparator = ComparatorT())\n  : m_comparator(comparator), m_last_mode(mode), m_last_value(value)\n  {\n  }\n\n  /// Update the state with the given parameter and the computation mode/\n  /// \\param value Parameter value used in computation\n  /// \\param mode Computation mode\n  void update(const DomainValue & value, const ComputeMode & mode) noexcept\n  {\n    m_last_mode = mode;\n    m_last_value = value;\n  }\n\n  /// Check if the term is already evaluated and cached for a given parameter\n  /// \\param x Parameter value\n  /// \\param term Expression term to query the cache status. Can be one of the following:\n  /// SCORE, JACOBIAN, HESSIAN\n  /// \\return True if the result for this term with the given parameter matches the previous\n  /// state and is already cached.\n  bool8_t is_cached(const DomainValue & x, const ExpressionTerm & term) const noexcept\n  {\n    bool8_t ret = false;\n    if (m_comparator(x, m_last_value)) {\n      switch (term) {\n        case ExpressionTerm::SCORE:\n          ret = m_last_mode.score();\n          break;\n        case ExpressionTerm::JACOBIAN:\n          ret = m_last_mode.jacobian();\n          break;\n        case ExpressionTerm::HESSIAN:\n          ret = m_last_mode.hessian();\n          break;\n        default:\n          ret = false;\n      }\n    }\n    return ret;\n  }\n\nprivate:\n  const ComparatorT m_comparator;\n  DomainValue m_last_value;\n  ComputeMode m_last_mode;\n};\n\n}  // namespace optimization\n}  // namespace common\n}  // namespace autoware\n\n#endif  // OPTIMIZATION__UTILS_HPP_\n", "meta": {"hexsha": "f110d694f46e9a7a2d22cb416347dc0cbab429e7", "size": 5733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/optimization/include/optimization/utils.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/utils.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/utils.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": 32.9482758621, "max_line_length": 93, "alphanum_fraction": 0.7167277167, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434190962774393, "lm_q2_score": 0.030214585866664673, "lm_q1q2_score": 0.006174106174605702}}
{"text": "#include \"AMR3D.hpp\"\n#include \"../../3D/GeometryCommon/Voronoi3D.hpp\"\n#include \"../../misc/utils.hpp\"\n#include <boost/array.hpp>\n#include <iostream>\n#include \"../../3D/r3d/Intersection3D.hpp\"\n#include <boost/scoped_ptr.hpp>\n\n//#define debug_amr 1\n\nnamespace\n{\n\tvoid RemoveRefineNeighborRemove(Tessellation3D const& tess, std::vector<size_t> const& remove,\n\t\tstd::vector<size_t> &refine, std::vector<Vector3D> &refine_direction)\n\t{\n\t\tvector<size_t> neigh;\n\t\tsize_t Nrefine = refine.size();\n\t\tvector<size_t> newrefine;\n\t\tnewrefine.reserve(Nrefine);\n\t\tstd::vector<Vector3D> new_direction;\n\t\tnew_direction.reserve(Nrefine);\n\t\tfor (size_t i = 0; i < Nrefine; ++i)\n\t\t{\n\t\t\ttess.GetNeighbors(refine[i], neigh);\n\t\t\tneigh.push_back(refine[i]);\n\t\t\tbool good = true;\n\t\t\tfor (size_t j = 0; j < neigh.size(); ++j)\n\t\t\t{\n\t\t\t\tif (std::binary_search(remove.begin(), remove.end(), neigh[j]))\n\t\t\t\t{\n\t\t\t\t\tgood = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (good)\n\t\t\t{\n\t\t\t\tnewrefine.push_back(refine[i]);\n\t\t\t\tif (!refine_direction.empty())\n\t\t\t\t\tnew_direction.push_back(refine_direction[i]);\n\t\t\t}\n\t\t}\n\t\trefine = newrefine;\n\t\trefine_direction = new_direction;\n\t}\n\n\tstd::pair<vector<size_t>, vector<double> > RemoveNeighbors(vector<double> const& merits, vector<size_t> const& candidates,\n\t\tTessellation3D const& tess)\n\t{\n\t\tvector<size_t> result_names;\n\t\tvector<double> result_merits;\n\t\tif (merits.size() != candidates.size())\n\t\t\tthrow UniversalError(\"Merits and Candidates don't have same size in RemoveNeighbors\");\n\t\t// Make sure there are no neighbors\n\t\tvector<size_t> bad_neigh;\n\t\tvector<size_t> neigh;\n\t\tfor (size_t i = 0; i < merits.size(); ++i)\n\t\t{\n\t\t\tbool good = true;\n\t\t\ttess.GetNeighbors(candidates[i], neigh);\n\t\t\tsize_t nneigh = neigh.size();\n\t\t\tif (find(bad_neigh.begin(), bad_neigh.end(), candidates[i]) != bad_neigh.end())\n\t\t\t\tgood = false;\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor (size_t j = 0; j < nneigh; ++j)\n\t\t\t\t{\n\t\t\t\t\tif (binary_search(candidates.begin(), candidates.end(), neigh[j]))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (merits[i] < merits[static_cast<size_t>(lower_bound(candidates.begin(), candidates.end(),\n\t\t\t\t\t\t\tneigh[j]) - candidates.begin())])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tgood = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (fabs(merits[i] - merits[static_cast<size_t>(lower_bound(candidates.begin(), candidates.end(),\n\t\t\t\t\t\t\tneigh[j]) - candidates.begin())]) < 1e-9)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (find(bad_neigh.begin(), bad_neigh.end(), neigh[j]) == bad_neigh.end())\n\t\t\t\t\t\t\t\tbad_neigh.push_back(neigh[j]);\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\tif (good)\n\t\t\t{\n\t\t\t\tresult_names.push_back(candidates[i]);\n\t\t\t\tresult_merits.push_back(merits[i]);\n\t\t\t}\n\t\t}\n\t\treturn std::pair<vector<size_t>, vector<double> >(result_names, result_merits);\n\t}\n\n#ifdef RICH_MPI\n\tstd::pair<vector<size_t>, vector<double> > RemoveMPINeighbors(vector<double> const& merits, vector<size_t> const& candidates,\n\t\tTessellation3D const& tess)\n\t{\n\t\tvector<vector<size_t> > duplicated_indeces = tess.GetDuplicatedPoints();\n\t\tvector<vector<size_t> > sort_indeces(duplicated_indeces.size());\n\t\tfor (size_t i = 0; i < duplicated_indeces.size(); ++i)\n\t\t{\n\t\t\tsort_index(duplicated_indeces[i], sort_indeces[i]);\n\t\t\tstd::sort(duplicated_indeces[i].begin(), duplicated_indeces[i].end());\n\t\t}\n\t\tsize_t nproc = duplicated_indeces.size();\n\t\tvector<vector<size_t> > indeces(nproc);\n\t\tvector<vector<double> > merit_send(nproc);\n\t\tvector<size_t> neigh;\n\t\tsize_t Norg = tess.GetPointNo();\n\t\tsize_t Nreomve = merits.size();\n\t\t// Send/recv data\n\t\tfor (size_t i = 0; i < Nreomve; ++i)\n\t\t{\n\t\t\ttess.GetNeighbors(candidates[i], neigh);\n\t\t\tsize_t Nneigh = neigh.size();\n\t\t\tfor (size_t j = 0; j < Nneigh; ++j)\n\t\t\t{\n\t\t\t\tif (neigh[j] >= Norg)\n\t\t\t\t{\n\t\t\t\t\tfor (size_t k = 0; k < nproc; ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tvector<size_t>::const_iterator it = binary_find(duplicated_indeces[k].begin(),\n\t\t\t\t\t\t\tduplicated_indeces[k].end(), candidates[i]);\n\t\t\t\t\t\tif (it != duplicated_indeces[k].end())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tindeces[k].push_back(sort_indeces[k][static_cast<size_t>(it - duplicated_indeces[k].begin())]);\n\t\t\t\t\t\t\tmerit_send[k].push_back(merits[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\tindeces = MPI_exchange_data(tess.GetDuplicatedProcs(), indeces);\n\t\tmerit_send = MPI_exchange_data(tess.GetDuplicatedProcs(), merit_send);\n\t\tvector<size_t> all_indeces, temp;\n\t\tvector<double> all_merits;\n\t\tfor (size_t i = 0; i < nproc; ++i)\n\t\t{\n\t\t\tif (!indeces[i].empty())\n\t\t\t{\n\t\t\t\tindeces[i] = VectorValues(tess.GetGhostIndeces()[i], indeces[i]);\n\t\t\t\tall_indeces.insert(all_indeces.end(), indeces[i].begin(), indeces[i].end());\n\t\t\t\tall_merits.insert(all_merits.end(), merit_send[i].begin(), merit_send[i].end());\n\t\t\t}\n\t\t}\n\t\tsort_index(all_indeces, temp);\n\t\tstd::sort(all_indeces.begin(), all_indeces.end());\n\t\tall_merits = VectorValues(all_merits, temp);\n\t\t// remove neighbors\n\t\tstd::pair<vector<size_t>, vector<double> > res;\n\t\tres.first.reserve(Nreomve);\n\t\tres.second.reserve(Nreomve);\n\t\tfor (size_t i = 0; i < Nreomve; ++i)\n\t\t{\n\t\t\tbool good = true;\n\t\t\ttess.GetNeighbors(candidates[i], neigh);\n\t\t\tsize_t Nneigh = neigh.size();\n\t\t\tfor (size_t j = 0; j < Nneigh; ++j)\n\t\t\t{\n\t\t\t\tif (neigh[j] >= Norg)\n\t\t\t\t{\n\t\t\t\t\tvector<size_t>::const_iterator it = binary_find(all_indeces.begin(), all_indeces.end(), neigh[j]);\n\t\t\t\t\tif (it != all_indeces.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (all_merits[static_cast<size_t>(it - all_indeces.begin())] > merits[i])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tgood = false;\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\tif (good)\n\t\t\t{\n\t\t\t\tres.first.push_back(candidates[i]);\n\t\t\t\tres.second.push_back(merits[i]);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n#endif //RICH_MPI\n\n\tstd::vector<Vector3D> GetNewPoints(Tessellation3D const& tess, std::pair<vector<size_t>,\n\t\tvector<Vector3D> > &ToRefine\n#ifdef RICH_MPI\n\t\t, Tessellation3D const& tproc\n#endif\n\t)\n\t{\n#ifdef RICH_MPI\n\t\tint rank = 0;\n\t\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n#endif\n\t\tstd::vector<size_t> bad_indeces;\n\t\tstd::vector<size_t> neigh;\n\t\tsize_t Nrefine = ToRefine.first.size();\n\t\tstd::vector<Vector3D> res;\n\t\tres.reserve(Nrefine);\n\t\t// Do we have a prefred direction?\n\t\tif (!ToRefine.second.empty())\n\t\t{\n\t\t\tfor (size_t i = 0; i < Nrefine; ++i)\n\t\t\t{\n\t\t\t\tdouble R = tess.GetWidth(ToRefine.first[i]);\n\t\t\t\tVector3D newpoint = tess.GetMeshPoint(ToRefine.first[i]) + 0.25*R*ToRefine.second[i] / fastabs(ToRefine.second[i]);\n\t\t\t\tres.push_back(newpoint);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Find direction by opposite to closest point\n\t\t\tfor (size_t i = 0; i < Nrefine; ++i)\n\t\t\t{\n\t\t\t\t// Find closest neighbor\n\t\t\t\tVector3D point = tess.GetMeshPoint(ToRefine.first[i]);\n\t\t\t\ttess.GetNeighbors(ToRefine.first[i], neigh);\n\t\t\t\tdouble min_dist2 = ScalarProd(point - tess.GetMeshPoint(neigh[0]), point - tess.GetMeshPoint(neigh[0]));\n\t\t\t\tsize_t index = 0;\n\t\t\t\tfor (size_t j = 1; j < neigh.size(); ++j)\n\t\t\t\t{\n\t\t\t\t\tdouble temp = ScalarProd(point - tess.GetMeshPoint(neigh[j]), point - tess.GetMeshPoint(neigh[j]));\n\t\t\t\t\tif (temp < min_dist2)\n\t\t\t\t\t{\n\t\t\t\t\t\tindex = j;\n\t\t\t\t\t\tmin_dist2 = temp;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Make new point\n\t\t\t\tVector3D n_split = (point - tess.GetMeshPoint(neigh[index]));\n\t\t\t\tn_split = normalize(n_split);\n\t\t\t\tres.push_back(point + 0.25*tess.GetWidth(ToRefine.first[i])*n_split);\n\t\t\t}\n\t\t}\n\t\t// Make sure point is inside domian\n#ifndef RICH_MPI\n\t\tstd::pair<Vector3D, Vector3D> bb = tess.GetBoxCoordinates();\n#endif\n\t\tfor (size_t i = 0; i < Nrefine; ++i)\n\t\t{\n#ifdef RICH_MPI\n\t\t\tif (!PointInPoly(tproc, res[i], rank))\n\t\t\t\tbad_indeces.push_back(i);\n#else\n\t\t\tif (res[i].x > bb.second.x || res[i].x<bb.first.x || res[i].y>bb.second.y || res[i].y<bb.first.y\n\t\t\t\t|| res[i].z>bb.second.z || res[i].z < bb.first.z)\n\t\t\t\tbad_indeces.push_back(i);\n#endif\n\t\t}\n\t\tif (!bad_indeces.empty())\n\t\t{\n\t\t\tRemoveVector(res, bad_indeces);\n\t\t\tRemoveVector(ToRefine.first, bad_indeces);\n\t\t}\n\t\treturn res;\n\t}\n\n#ifdef RICH_MPI\n\tvoid SendRecvMPIFullRemove(Tessellation3D const& tess, vector<size_t> const& toremove, vector<vector<size_t> >\n\t\t&nghost_index, vector<vector<vector<size_t> > > &duplicated_index, vector<vector<vector<Vector3D> > > &planes,\n\t\tvector<vector<vector<double> > > &planes_d)\n\t{\n\t\tvector<size_t> temp;\n\t\tsize_t Nprocs = tess.GetDuplicatedProcs().size();\n\t\tnghost_index.clear();\n\t\tnghost_index.resize(Nprocs);\n\t\tduplicated_index.clear();\n\t\tduplicated_index.resize(Nprocs);\n\t\tplanes_d.clear();\n\t\tplanes_d.resize(Nprocs);\n\t\tplanes.clear();\n\t\tplanes.resize(Nprocs);\n\t\tvector<vector<size_t> > duplicated_points = tess.GetDuplicatedPoints();\n\t\tvector<vector<size_t> > ghost_points = tess.GetGhostIndeces();\n\t\tvector<vector<size_t> > sort_indeces(Nprocs), sort_indecesg(Nprocs);\n\t\tfor (size_t i = 0; i < Nprocs; ++i)\n\t\t{\n\t\t\tsort_index(duplicated_points[i], sort_indeces[i]);\n\t\t\tsort(duplicated_points[i].begin(), duplicated_points[i].end());\n\t\t\tsort_index(ghost_points[i], sort_indecesg[i]);\n\t\t\tsort(ghost_points[i].begin(), ghost_points[i].end());\n\t\t}\n\n\t\tsize_t nremove = toremove.size();\n\t\tsize_t Norg = tess.GetPointNo();\n\t\tvector<r3d_plane> r_planes;\n\t\tfor (size_t i = 0; i < nremove; ++i)\n\t\t{\n\t\t\tvector<vector<size_t> > ghosts(Nprocs);\n\t\t\ttess.GetNeighbors(toremove[i], temp);\n\t\t\tsize_t Nneigh = temp.size();\n\t\t\tbool added = false;\n\t\t\tfor (size_t j = 0; j < Nneigh; ++j)\n\t\t\t{\n\t\t\t\tif (temp[j] >= Norg)\n\t\t\t\t{\n\t\t\t\t\tfor (size_t k = 0; k < Nprocs; ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tvector<size_t>::const_iterator it = binary_find(ghost_points[k].begin(),\n\t\t\t\t\t\t\tghost_points[k].end(), temp[j]);\n\t\t\t\t\t\tif (it != ghost_points[k].end())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tghosts[k].push_back(sort_indecesg[k][static_cast<size_t>(it - ghost_points[k].begin())]);\n\t\t\t\t\t\t\tadded = true;\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\tif (added)\n\t\t\t{\n\t\t\t\tGetPlanes(r_planes, tess, toremove[i]);\n\t\t\t\tsize_t nplanes = r_planes.size();\n\t\t\t\tvector<Vector3D> v_plane(nplanes);\n\t\t\t\tvector<double> d_plane(nplanes);\n\t\t\t\tfor (size_t j = 0; j < nplanes; ++j)\n\t\t\t\t{\n\t\t\t\t\td_plane[j] = r_planes[j].d;\n\t\t\t\t\tv_plane[j].x = r_planes[j].n.xyz[0];\n\t\t\t\t\tv_plane[j].y = r_planes[j].n.xyz[1];\n\t\t\t\t\tv_plane[j].z = r_planes[j].n.xyz[2];\n\t\t\t\t}\n\t\t\t\tfor (size_t k = 0; k < Nprocs; ++k)\n\t\t\t\t\tif (!ghosts[k].empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tduplicated_index[k].push_back(ghosts[k]);\n\t\t\t\t\t\tnghost_index[k].push_back(sort_indeces[k][static_cast<size_t>(binary_find(duplicated_points[k].begin(),\n\t\t\t\t\t\t\tduplicated_points[k].end(), toremove[i]) - duplicated_points[k].begin())]);\n\t\t\t\t\t\tplanes[k].push_back(v_plane);\n\t\t\t\t\t\tplanes_d[k].push_back(d_plane);\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// send/recv the data\n\t\tnghost_index = MPI_exchange_data(tess.GetDuplicatedProcs(), nghost_index);\n\t\tduplicated_index = MPI_exchange_data(tess, duplicated_index);\n\t\tplanes = MPI_exchange_data(tess.GetDuplicatedProcs(), planes, tess.GetMeshPoint(0));\n\t\tplanes_d = MPI_exchange_data(tess, planes_d);\n\t\t// convert the data\n\t\tfor (size_t i = 0; i < Nprocs; ++i)\n\t\t{\n\t\t\tsize_t size = nghost_index[i].size();\n\t\t\tassert(duplicated_index[i].size() == size);\n\t\t\tfor (size_t j = 0; j < size; ++j)\n\t\t\t{\n\t\t\t\tnghost_index[i][j] = tess.GetGhostIndeces()[i].at(nghost_index[i][j]);\n\t\t\t\tsize_t size2 = duplicated_index[i][j].size();\n\t\t\t\tfor (size_t k = 0; k < size2; ++k)\n\t\t\t\t\tduplicated_index[i][j][k] = tess.GetDuplicatedPoints()[i].at(duplicated_index[i][j][k]);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid SendRecvMPIRefine(Tessellation3D const& tess, std::vector<std::vector<size_t> > const& to_send,\n\t\tstd::vector<size_t> const& refined_points, Tessellation3D const& oldtess,\n\t\tstd::vector<std::vector<std::vector<size_t> > > &neigh_index, std::vector<std::vector<double> > &planes,\n\t\tstd::vector < std::vector<size_t> > &n_planes, std::vector<std::vector<size_t> > &changed_byouter)\n\t{\n\t\t// to_send is the list of outer neighbors for each refine point\n\t\t// refined_points is the index of the refined points in new tess\n\t\tassert(refined_points.size() == to_send.size());\n\t\tvector<vector<size_t> > duplicated_points = oldtess.GetDuplicatedPoints();\n\t\tsize_t Nprocs = duplicated_points.size();\n\t\tvector<vector<size_t> > ghost_points = oldtess.GetGhostIndeces();\n\t\tvector<vector<size_t> > sort_indeces(Nprocs), sort_indecesg(Nprocs);\n\t\t// sort the indeces\n\t\tfor (size_t i = 0; i < Nprocs; ++i)\n\t\t{\n\t\t\tsort_index(duplicated_points[i], sort_indeces[i]);\n\t\t\tsort(duplicated_points[i].begin(), duplicated_points[i].end());\n\t\t\tsort_index(ghost_points[i], sort_indecesg[i]);\n\t\t\tsort(ghost_points[i].begin(), ghost_points[i].end());\n\t\t}\n\t\t// Create send data\n\t\tneigh_index.clear();\n\t\tneigh_index.resize(Nprocs);\n\t\tplanes.clear();\n\t\tplanes.resize(Nprocs);\n\t\tn_planes.clear();\n\t\tn_planes.resize(Nprocs);\n\t\tchanged_byouter.clear();\n\t\tchanged_byouter.resize(Nprocs);\n\t\tsize_t nsend = to_send.size();\n\t\tvector<r3d_plane> r_planes;\n\t\tfor (size_t i = 0; i < nsend; ++i)\n\t\t{\n\t\t\tr_planes.clear();\n\t\t\t// Get the polyhedra of new cell\n\t\t\tGetPlanes(r_planes, tess, refined_points[i]);\n\t\t\t// find indeces of neighbors\n\t\t\tfor (size_t k = 0; k < Nprocs; ++k)\n\t\t\t{\n\t\t\t\tstd::vector<size_t> indeces_toadd;\n\t\t\t\tfor (size_t j = 0; j < to_send[i].size(); ++j)\n\t\t\t\t{\n\t\t\t\t\tvector<size_t>::const_iterator it = binary_find(ghost_points[k].begin(),\n\t\t\t\t\t\tghost_points[k].end(), to_send[i][j]);\n\t\t\t\t\tif (it != ghost_points[k].end())\n\t\t\t\t\t\tindeces_toadd.push_back(sort_indecesg[k][static_cast<size_t>(it - ghost_points[k].begin())]);\n\t\t\t\t}\n\t\t\t\tif (!indeces_toadd.empty())\n\t\t\t\t{\n\t\t\t\t\tchanged_byouter[k].push_back(refined_points[i]);\n\t\t\t\t\tneigh_index[k].push_back(indeces_toadd);\n\t\t\t\t\tsize_t nplanes = r_planes.size();\n\t\t\t\t\tfor (size_t j = 0; j < nplanes; ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tplanes[k].push_back(r_planes[j].d);\n\t\t\t\t\t\tplanes[k].push_back(r_planes[j].n.xyz[0]);\n\t\t\t\t\t\tplanes[k].push_back(r_planes[j].n.xyz[1]);\n\t\t\t\t\t\tplanes[k].push_back(r_planes[j].n.xyz[2]);\n\t\t\t\t\t}\n\t\t\t\t\tn_planes[k].push_back(nplanes);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// send/recv the data\n\t\tneigh_index = MPI_exchange_data(oldtess, neigh_index);\n\t\tplanes = MPI_exchange_data(oldtess.GetDuplicatedProcs(), planes);\n\t\tn_planes = MPI_exchange_data(oldtess.GetDuplicatedProcs(), n_planes);\n\t\t// convert the data\n\t\tfor (size_t i = 0; i < Nprocs; ++i)\n\t\t{\n\t\t\tsize_t size = neigh_index[i].size();\n\t\t\tfor (size_t j = 0; j < size; ++j)\n\t\t\t{\n\t\t\t\tsize_t size2 = neigh_index[i][j].size();\n\t\t\t\tfor (size_t k = 0; k < size2; ++k)\n\t\t\t\t{\n\t\t\t\t\tneigh_index[i][j][k] = oldtess.GetDuplicatedPoints()[i].at(neigh_index[i][j][k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\tvoid LocalRemove(Tessellation3D const& oldtess, std::vector<size_t> const& ToRemove, AMRExtensiveUpdater3D const& eu,\n\t\tstd::vector<ComputationalCell3D> const& cells, EquationOfState const& eos, TracerStickerNames const& tsn,\n\t\tTessellation3D const& tess, std::vector<Conserved3D> &extensives,SpatialReconstruction3D &interp)\n\t{\n\t\tstd::vector<size_t> neigh,temp2;\n\t\tpoint_vec temp;\n\t\tr3d_poly poly, poly2;\n\t\tstd::vector<std::vector<int> > i_temp;\n\t\tsize_t NRemove = ToRemove.size();\n\t\tsize_t Norg = oldtess.GetPointNo();\n\t\tfor (size_t i = 0; i < NRemove; ++i)\n\t\t{\n\t\t\toldtess.GetNeighbors(ToRemove[i], neigh);\n\t\t\tsize_t Nneigh = neigh.size();\n\t\t\t// Get old poly\n\t\t\tif (GetPoly(oldtess, ToRemove[i], poly, temp, temp2, i_temp))\n\t\t\t{\n\t\t\t\tfor (size_t j = 0; j < Nneigh; ++j)\n\t\t\t\t{\n\t\t\t\t\tif (neigh[j] >= Norg)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t// copy poly\n\t\t\t\t\tpoly2.nverts = poly.nverts;\n\t\t\t\t\tfor (int k = 0; k < poly2.nverts; ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t l = 0; l < 3; ++l)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpoly2.verts[k].pos.xyz[l] = poly.verts[k].pos.xyz[l];\n\t\t\t\t\t\t\tpoly2.verts[k].pnbrs[l] = poly.verts[k].pnbrs[l];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tsize_t index_remove = static_cast<size_t>(std::lower_bound(ToRemove.begin(), ToRemove.end(), neigh[j])\n\t\t\t\t\t\t- ToRemove.begin());\n\t\t\t\t\tstd::pair<bool, std::array<double,4> > dv = PolyhedraIntersection(tess, neigh[j] - index_remove, poly2);\n#ifdef RICH_DEBUG\n\t\t\t\t\ttry\n\t\t\t\t\t{\n#endif\n\t\t\t\t\t\tif(dv.first)\n\t\t\t\t\t\t\textensives[neigh[j] - index_remove] += eu.ConvertPrimitveToExtensive3D(cells[ToRemove[i]], eos, dv.second[0], tsn, interp.GetSlopes()[ToRemove[i]],\n\t\t\t\t\t\t\t\toldtess.GetCellCM(ToRemove[i]), Vector3D(dv.second[1], dv.second[2], dv.second[3]));\n#ifdef RICH_DEBUG\n\t\t\t\t}\n\t\t\t\tcatch (UniversalError &eo)\n\t\t\t\t{\n\t\t\t\t\teo.AddEntry(\"Error in LocalRemove\", 0);\n\t\t\t\t\teo.AddEntry(\"Volume\", dv.second[0]);\n\t\t\t\t\teo.AddEntry(\"Current remove\", ToRemove[i]);\n\t\t\t\t\teo.AddEntry(\"Current remove ID\", cells[ToRemove[i]].ID);\n\t\t\t\t\teo.AddEntry(\"New mass\", extensives[neigh[j] - index_remove].mass);\n\t\t\t\t\teo.AddEntry(\"Remove index\", i);\n\t\t\t\t\teo.AddEntry(\"neigh index\",j);\n\t\t\t\t\teo.AddEntry(\"neigh\", neigh[j]);\n\t\t\t\t\teo.AddEntry(\"index_remove\", index_remove);\n\t\t\t\t\tthrow eo;\n\t\t\t\t}\n#endif\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n#ifdef RICH_MPI\n\tvoid MPIRemove(Tessellation3D const& oldtess, Tessellation3D const& tess, std::vector<size_t> const& ToRemove,\n\t\tAMRExtensiveUpdater3D const& eu, EquationOfState const& eos, TracerStickerNames const& tsn,\n\t\tstd::vector<ComputationalCell3D> const& cells, std::vector<Conserved3D> &extensives,SpatialReconstruction3D &interp)\n\t{\n\t\tvector<vector<size_t> > nghost_index;\n\t\tvector<vector<vector<size_t> > > duplicate_index;\n\t\tvector<vector < vector<Vector3D> > > planes_v;\n\t\tvector<vector < vector<double> > > planes_d;\n\t\tvector<r3d_plane> planes;\n\t\tr3d_poly poly, poly2;\n\t\tstd::vector<size_t>  temp2;\n\t\tpoint_vec temp;\n\t\tstd::vector<std::vector<int> > i_temp;\n\t\tSendRecvMPIFullRemove(oldtess, ToRemove, nghost_index, duplicate_index, planes_v, planes_d);\n\t\tsize_t Nproc = nghost_index.size();\n\t\tfor (size_t i = 0; i < Nproc; ++i)\n\t\t{\n\t\t\tsize_t NremoveMPI = duplicate_index[i].size();\n\t\t\tfor (size_t j = 0; j < NremoveMPI; ++j)\n\t\t\t{\n\t\t\t\t// build planes for outer point\n\t\t\t\tsize_t Nplane = planes_v[i].at(j).size();\n\t\t\t\tplanes.resize(Nplane);\n\t\t\t\tfor (size_t k = 0; k < Nplane; ++k)\n\t\t\t\t{\n\t\t\t\t\tplanes[k].d = planes_d[i][j].at(k);\n\t\t\t\t\tplanes[k].n.xyz[0] = planes_v[i][j].at(k).x;\n\t\t\t\t\tplanes[k].n.xyz[1] = planes_v[i][j][k].y;\n\t\t\t\t\tplanes[k].n.xyz[2] = planes_v[i][j][k].z;\n\t\t\t\t}\n\t\t\t\tsize_t NChangeLocal = duplicate_index[i][j].size();\n\t\t\t\tfor (size_t k = 0; k < NChangeLocal; ++k)\n\t\t\t\t{\n\t\t\t\t\tsize_t index_remove = static_cast<size_t>(std::lower_bound(ToRemove.begin(), ToRemove.end(),\n\t\t\t\t\t\tduplicate_index[i][j].at(k)) - ToRemove.begin());\n\t\t\t\t\tif (GetPoly(tess, duplicate_index[i][j][k] - index_remove, poly, temp, temp2, i_temp))\n\t\t\t\t\t{\n\t\t\t\t\t\t// copy poly\n\t\t\t\t\t\tpoly2.nverts = poly.nverts;\n\t\t\t\t\t\tfor (int kk = 0; kk < poly2.nverts; ++kk)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (size_t l = 0; l < 3; ++l)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpoly2.verts[kk].pos.xyz[l] = poly.verts[kk].pos.xyz[l];\n\t\t\t\t\t\t\t\tpoly2.verts[kk].pnbrs[l] = poly.verts[kk].pnbrs[l];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstd::pair<bool, std::array<double,4> > dv = PolyhedraIntersection(oldtess, 0, poly2, &planes);\n#ifdef RICH_DEBUG\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n#endif\n\t\t\t\t\t\textensives[duplicate_index[i][j][k] - index_remove] += eu.ConvertPrimitveToExtensive3D(\n\t\t\t\t\t\t\tcells[nghost_index[i][j]], eos, dv.second[0], tsn,interp.GetSlopes()[nghost_index[i][j]],oldtess.GetCellCM(nghost_index[i][j]),\n\t\t\t\t\t\t\tVector3D(dv.second[1], dv.second[2], dv.second[3]));\n#ifdef RICH_DEBUG\n\t\t\t\t\t}\n\t\t\t\t\tcatch (UniversalError &eo)\n\t\t\t\t\t{\n\t\t\t\t\t\teo.AddEntry(\"Error in MPIRemove\", 0);\n\t\t\t\t\t\teo.AddEntry(\"Volume\", dv.second[0]);\n\t\t\t\t\t\teo.AddEntry(\"Current remove\", nghost_index[i][j]);\n\t\t\t\t\t\teo.AddEntry(\"Current remove ID\", cells[nghost_index[i][j]].ID);\n\t\t\t\t\t\teo.AddEntry(\"New mass\", extensives[duplicate_index[i][j][k] - index_remove].mass);\n\t\t\t\t\t\teo.AddEntry(\"Remove index i\", i);\n\t\t\t\t\t\teo.AddEntry(\"Remove index j\", j);\n\t\t\t\t\t\teo.AddEntry(\"Remove index k\", k);\n\t\t\t\t\t\teo.AddEntry(\"neigh index\", j);\n\t\t\t\t\t\teo.AddEntry(\"duplicate_index[i][j][k] - index_remove\", duplicate_index[i][j][k] - index_remove);\n\t\t\t\t\t\teo.AddEntry(\"index_remove\", index_remove);\n\t\t\t\t\t\tthrow eo;\n\t\t\t\t\t}\n#endif\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\tvoid LocalRefine(Tessellation3D const& oldtess, Tessellation3D const& tess, std::vector<size_t> const& ToRefine,\n\t\tstd::vector<ComputationalCell3D> const& cells, EquationOfState const& eos, TracerStickerNames const& tsn,\n\t\tAMRExtensiveUpdater3D const&eu, std::vector<Conserved3D> &extensives,SpatialReconstruction3D &interp)\n\t{\n\t\tsize_t Nrefine = ToRefine.size();\n\t\tstd::vector<size_t> neigh, temp2;\n\t\tpoint_vec temp;\n\t\tstd::vector<std::vector<int> > i_temp;\n\t\tr3d_poly poly, poly2;\n\t\tboost::container::flat_set<size_t> checked;\n\t\tstd::stack<size_t> tocheck;\n\t\tsize_t Norg = tess.GetPointNo() - ToRefine.size();\n\t\tsize_t Norg2 = oldtess.GetPointNo();\n\t\tfor (size_t i = 0; i < Nrefine; ++i)\n\t\t{\n\t\t\tchecked.clear();\n\t\t\t// Get new cell poly\n\t\t\tif (GetPoly(tess, Norg + i, poly, temp, temp2, i_temp))\n\t\t\t{\n\t\t\t\t// Get neigh to check\n\t\t\t\toldtess.GetNeighbors(ToRefine[i], neigh);\n\t\t\t\tsize_t Nneigh = neigh.size();\n\t\t\t\tfor (size_t j = 0; j < Nneigh; ++j)\n\t\t\t\t\ttocheck.push(neigh[j]);\n\t\t\t\ttocheck.push(ToRefine[i]);\n\t\t\t\twhile (!tocheck.empty())\n\t\t\t\t{\n\t\t\t\t\tsize_t cur_check = tocheck.top();\n\t\t\t\t\ttocheck.pop();\n\t\t\t\t\t// did we check this cell yet?\n\t\t\t\t\tif (checked.count(cur_check) == 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\telse // keep track of visted cells\n\t\t\t\t\t\tchecked.insert(cur_check);\n\t\t\t\t\tif (cur_check >= Norg2)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t// copy poly\n\t\t\t\t\tpoly2.nverts = poly.nverts;\n\t\t\t\t\tfor (int k = 0; k < poly2.nverts; ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t l = 0; l < 3; ++l)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpoly2.verts[k].pos.xyz[l] = poly.verts[k].pos.xyz[l];\n\t\t\t\t\t\t\tpoly2.verts[k].pnbrs[l] = poly.verts[k].pnbrs[l];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Check intersectrion\n\t\t\t\t\tstd::pair<bool, std::array<double, 4> > dv = PolyhedraIntersection(oldtess, cur_check, poly2);\n\t\t\t\t\tif (dv.first)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Remove extensive from neigh cell and add to new cell\n#ifdef RICH_DEBUG\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n#endif\n\t\t\t\t\t\t\tConserved3D toadd = eu.ConvertPrimitveToExtensive3D(cells[cur_check], eos, dv.second[0], tsn, interp.GetSlopes()[cur_check],\n\t\t\t\t\t\t\t\toldtess.GetCellCM(cur_check), Vector3D(dv.second[1], dv.second[2], dv.second[3]));\n\t\t\t\t\t\t\textensives[cur_check] -= toadd;\n\t\t\t\t\t\t\t//extensives[Norg2 + i].tracers.resize(toadd.tracers.size());\n\t\t\t\t\t\t\textensives[Norg2 + i] += toadd;\n\t\t\t\t\t\t\toldtess.GetNeighbors(cur_check, neigh);\n\t\t\t\t\t\t\tNneigh = neigh.size();\n\t\t\t\t\t\t\tfor (size_t j = 0; j < Nneigh; ++j)\n\t\t\t\t\t\t\t\ttocheck.push(neigh[j]);\n#ifdef RICH_DEBUG\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (UniversalError &eo)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\teo.AddEntry(\"Error in LocalRefine\", 0);\n\t\t\t\t\t\t\teo.AddEntry(\"Volume\", dv.second[0]);\n\t\t\t\t\t\t\teo.AddEntry(\"Current check\", cur_check);\n\t\t\t\t\t\t\teo.AddEntry(\"Current check ID\",cells[cur_check].ID);\n\t\t\t\t\t\t\teo.AddEntry(\"Old mass\", extensives[cur_check].mass);\n\t\t\t\t\t\t\teo.AddEntry(\"Old density\", cells[cur_check].density);\n\t\t\t\t\t\t\teo.AddEntry(\"New mass\", extensives[Norg + i].mass);\n\t\t\t\t\t\t\teo.AddEntry(\"Refine index\", i);\n\t\t\t\t\t\t\teo.AddEntry(\"Norg\", Norg2);\n\t\t\t\t\t\t\tthrow eo;\n\t\t\t\t\t\t}\n#endif\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\textensives[Norg2 + i] = eu.ConvertPrimitveToExtensive3D(cells[ToRefine[i]], eos, tess.GetVolume(Norg + i), tsn, interp.GetSlopes()[0], \n\t\t\t\t\tVector3D(), Vector3D());\n\t\t\t\textensives[ToRefine[i]] -= extensives[Norg2 + i];\n\t\t\t\tstd::cout << \"Warning no good poly localrefine\" << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n#ifdef RICH_MPI\n\tvoid MPIRefine(Tessellation3D const& oldtess, Tessellation3D const& tess, std::vector<size_t> const& ToRefine,\n\t\tAMRExtensiveUpdater3D const& eu, EquationOfState const& eos, TracerStickerNames const& tsn,\n\t\tstd::vector<ComputationalCell3D> const& cells, std::vector<Conserved3D> &extensives,SpatialReconstruction3D &interp)\n\t{\n\t\tstd::vector<size_t> temp, temp2;\n\t\tpoint_vec ptemp;\n\t\tsize_t Norg = oldtess.GetPointNo();\n\t\t// Get outer refine points\n\t\tsize_t Nrefine = ToRefine.size();\n\t\tstd::vector<std::vector<size_t> >  to_send;\n\t\tstd::vector<size_t> refined_points;\n\t\tfor (size_t i = 0; i < Nrefine; ++i)\n\t\t{\n\t\t\toldtess.GetNeighbors(ToRefine[i], temp);\n\t\t\ttemp2.clear();\n\t\t\tfor (size_t j = 0; j < temp.size(); ++j)\n\t\t\t{\n\t\t\t\tif (temp[j] >= Norg && !oldtess.IsPointOutsideBox(temp[j]))\n\t\t\t\t\ttemp2.push_back(temp[j]);\n\t\t\t}\n\t\t\tif (!temp2.empty())\n\t\t\t{\n\t\t\t\trefined_points.push_back(tess.GetPointNo() - Nrefine + i);\n\t\t\t\tto_send.push_back(temp2);\n\t\t\t}\n\t\t}\n\t\t// send / recv data\n\t\tstd::vector<std::vector<size_t> > n_planes;\n\t\tstd::vector<std::vector<std::vector<size_t> > > neigh_index;\n\t\tstd::vector < std::vector<double> > planes;\n\t\tstd::vector<std::vector<size_t> > changed_byouter;\n\t\tSendRecvMPIRefine(tess, to_send, refined_points, oldtess, neigh_index, planes, n_planes, changed_byouter);\n\t\t// Find the intersections\n\t\tr3d_poly poly;\n\t\tstd::vector<r3d_plane> r_planes;\n\t\tstd::vector<std::vector<int> > i_temp;\n\t\tboost::container::flat_set<size_t> checked;\n\t\tstd::stack<size_t> tocheck;\n\t\tsize_t Nprocs = neigh_index.size();\n\t\tstd::vector<std::vector<Conserved3D> > extensive_tosend(Nprocs);\n\t\tfor (size_t i = 0; i < Nprocs; ++i)\n\t\t{\n\t\t\textensive_tosend[i].resize(neigh_index[i].size());\n\t\t\tsize_t counter = 0;\n\t\t\tfor (size_t j = 0; j < neigh_index[i].size(); ++j)\n\t\t\t{\n\t\t\t\tchecked.clear();\n\t\t\t\t// Create planes for intersection\n\t\t\t\tr_planes.resize(n_planes[i][j]);\n\t\t\t\tfor (size_t k = 0; k < n_planes[i][j]; ++k)\n\t\t\t\t{\n\t\t\t\t\tr_planes[k].d = planes[i][counter];\n\t\t\t\t\tr_planes[k].n.xyz[0] = planes[i][counter + 1];\n\t\t\t\t\tr_planes[k].n.xyz[1] = planes[i][counter + 2];\n\t\t\t\t\tr_planes[k].n.xyz[2] = planes[i].at(counter + 3);\n\t\t\t\t\tcounter += 4;\n\t\t\t\t}\n\t\t\t\t// Check for intersections\n\t\t\t\tfor (size_t k = 0; k < neigh_index[i][j].size(); ++k)\n\t\t\t\t\ttocheck.push(neigh_index[i][j][k]);\n\t\t\t\twhile (!tocheck.empty())\n\t\t\t\t{\n\t\t\t\t\tsize_t cur_check = tocheck.top();\n\t\t\t\t\ttocheck.pop();\n\t\t\t\t\t// did we check this cell yet?\n\t\t\t\t\tif (checked.count(cur_check) == 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\telse // keep track of visted cells\n\t\t\t\t\t\tchecked.insert(cur_check);\n\t\t\t\t\tif (cur_check >= Norg)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (GetPoly(oldtess, cur_check, poly, ptemp, temp2, i_temp))\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::pair<bool, std::array<double,4> > dv = PolyhedraIntersection(oldtess, cur_check, poly, &r_planes);\n\t\t\t\t\t\tif (dv.first)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// add and remove the extensive\n#ifdef RICH_DEBUG\n\t\t\t\t\t\t\ttry\n\t\t\t\t\t\t\t{\n#endif\n\t\t\t\t\t\t\tConserved3D toadd = eu.ConvertPrimitveToExtensive3D(cells[cur_check], eos, dv.second[0], tsn, interp.GetSlopes()[cur_check],\n\t\t\t\t\t\t\t\toldtess.GetCellCM(cur_check), Vector3D(dv.second[1], dv.second[2], dv.second[3]));\n\t\t\t\t\t\t\textensives[cur_check] -= toadd;\n\t\t\t\t\t\t\textensive_tosend[i][j] += toadd;\n\t\t\t\t\t\t\toldtess.GetNeighbors(cur_check, temp);\n\t\t\t\t\t\t\tsize_t Nneigh = temp.size();\n\t\t\t\t\t\t\tfor (size_t k = 0; k < Nneigh; ++k)\n\t\t\t\t\t\t\t\ttocheck.push(temp[k]);\n#ifdef RICH_DEBUG\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch (UniversalError &eo)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\teo.AddEntry(\"Error in MPIRefine\", 0);\n\t\t\t\t\t\t\t\teo.AddEntry(\"Volume\", dv.second[0]);\n\t\t\t\t\t\t\t\teo.AddEntry(\"Current check\", cur_check);\n\t\t\t\t\t\t\t\teo.AddEntry(\"Current check ID\", cells[cur_check].ID);\n\t\t\t\t\t\t\t\teo.AddEntry(\"Old mass\", extensives[cur_check].mass);\n\t\t\t\t\t\t\t\teo.AddEntry(\"Old density\", cells[cur_check].density);\n\t\t\t\t\t\t\t\teo.AddEntry(\"Refine index i\", i);\n\t\t\t\t\t\t\t\teo.AddEntry(\"Refine index j\", j);\n\t\t\t\t\t\t\t\tthrow eo;\n\t\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tint rank = 0;\n\t\t\t\t\t\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\t\t\t\t\t\tstd::cout << \"warning bad poly in MPIRefine in rank \" <<rank<< std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\textensive_tosend = MPI_exchange_data(oldtess.GetDuplicatedProcs(), extensive_tosend, extensives.at(0));\n\t\tsize_t Nremove = oldtess.GetPointNo() + Nrefine - tess.GetPointNo();\n\t\tfor (size_t i = 0; i < Nprocs; ++i)\n\t\t{\n\t\t\tfor (size_t j = 0; j < extensive_tosend[i].size(); ++j)\n\t\t\t\textensives[changed_byouter[i][j] + Nremove] += extensive_tosend[i][j];\n\t\t}\n\t}\n#endif\n\n}\n\nAMRCellUpdater3D::~AMRCellUpdater3D(void) {}\n\nAMRExtensiveUpdater3D::~AMRExtensiveUpdater3D(void) {}\n\nConserved3D SimpleAMRExtensiveUpdater3D::ConvertPrimitveToExtensive3D(const ComputationalCell3D& cell, const EquationOfState& eos,\n\tdouble volume, TracerStickerNames const& tracerstickernames, Slope3D const& slope, Vector3D const& CMold, Vector3D const& CMnew) const\n{\n\tConserved3D res;\n\tVector3D diff(CMnew);\n\tdiff -= CMold;\n\t\n\tComputationalCell3D cell_temp(cell);\n\tComputationalCellAddMult(cell_temp, slope.xderivative, diff.x);\n\tComputationalCellAddMult(cell_temp, slope.yderivative, diff.y);\n\tComputationalCellAddMult(cell_temp, slope.zderivative, diff.z);\n\tcell_temp.internal_energy = eos.dp2e(cell_temp.density, cell_temp.pressure, cell_temp.tracers, tracerstickernames.tracer_names);\n\tconst double mass = volume* cell_temp.density;\n\tres.mass = mass;\n\tres.internal_energy = cell_temp.internal_energy*mass;\n\tres.energy = res.internal_energy + 0.5*mass*ScalarProd(cell_temp.velocity, cell_temp.velocity);\n\tres.momentum = mass* cell_temp.velocity;\n\tsize_t N = cell_temp.tracers.size();\n\t//res.tracers.resize(N);\n\tfor (size_t i = 0; i < N; ++i)\n\t\tres.tracers[i] = cell_temp.tracers[i] * mass;\n\treturn res;\n}\n\nConserved3D SimpleAMRExtensiveUpdaterSR3D::ConvertPrimitveToExtensive3D(const ComputationalCell3D& cell, const EquationOfState& eos,\n\tdouble volume, TracerStickerNames const& tracerstickernames, Slope3D const& slope, Vector3D const& CMold, Vector3D const& CMnew) const\n{\n\tConserved3D res;\n\tVector3D diff(CMnew);\n\tdiff -= CMold;\n\tComputationalCell3D cell_temp(cell);\n\tComputationalCellAddMult(cell_temp, slope.xderivative, diff.x);\n\tComputationalCellAddMult(cell_temp, slope.yderivative, diff.y);\n\tComputationalCellAddMult(cell_temp, slope.zderivative, diff.z);\n\tcell_temp.internal_energy = eos.dp2e(cell_temp.density, cell_temp.pressure, cell_temp.tracers, tracerstickernames.tracer_names);\n\tdouble gamma = 1.0 / std::sqrt(1 - ScalarProd(cell_temp.velocity, cell_temp.velocity));\n\tconst double mass = volume * cell_temp.density*gamma;\n\tres.mass = mass;\n\tsize_t N = cell_temp.tracers.size();\n\t//res.tracers.resize(N);\n\tfor (size_t i = 0; i < N; ++i)\n\t\tres.tracers[i] = cell_temp.tracers[i] * mass;\n\tdouble enthalpy = cell_temp.internal_energy;\n\tif (fastabs(cell_temp.velocity) < 1e-5)\n\t\tres.energy = (gamma*enthalpy + 0.5*ScalarProd(cell_temp.velocity, cell_temp.velocity))* mass - cell_temp.pressure*volume;\n\telse\n\t\tres.energy = (gamma*enthalpy + (gamma - 1))* mass - cell_temp.pressure*volume;\n\tres.momentum = mass * cell_temp.velocity *gamma*(enthalpy + 1);\n\treturn res;\n}\n\nSimpleAMRCellUpdater3D::SimpleAMRCellUpdater3D(vector<string> toskip) :toskip_(toskip) {}\n\nComputationalCell3D SimpleAMRCellUpdater3D::ConvertExtensiveToPrimitve3D(const Conserved3D& extensive, const EquationOfState& eos,\n\tdouble volume, ComputationalCell3D const& old_cell, TracerStickerNames const& tracerstickernames) const\n{\n\tfor (size_t i = 0; i < toskip_.size(); ++i)\n\t{\n\t\tif (*safe_retrieve(old_cell.stickers.begin(), tracerstickernames.sticker_names.begin(),\n\t\t\ttracerstickernames.sticker_names.end(), toskip_[i]))\n\t\t\treturn old_cell;\n\t}\n\n\tComputationalCell3D res;\n\tconst double vol_inv = 1.0 / volume;\n\tres.density = extensive.mass*vol_inv;\n\tres.velocity = extensive.momentum / extensive.mass;\n\tres.ID  = old_cell.ID;\n\ttry\n\t{\n\t\tres.pressure = eos.de2p(res.density, extensive.internal_energy / extensive.mass);\n\t}\n\tcatch (UniversalError &eo)\n\t{\n\t\teo.AddEntry(\"Density\", res.density);\n\t\teo.AddEntry(\"Vx\", res.velocity.x);\n\t\teo.AddEntry(\"Vy\", res.velocity.y);\n\t\teo.AddEntry(\"Vz\", res.velocity.z);\n\t\teo.AddEntry(\"ID\", static_cast<double>(res.ID));\n\t\teo.AddEntry(\"internal energy\", extensive.internal_energy / extensive.mass);\n\t\teo.AddEntry(\"Volume\", 1.0 / vol_inv);\n\t\tthrow eo;\n\t}\n\tres.internal_energy = extensive.internal_energy / extensive.mass;\n\tsize_t N = extensive.tracers.size();\n//\tres.tracers.resize(N);\n\tfor (size_t i = 0; i < N; ++i)\n\t\tres.tracers[i] = extensive.tracers[i] / extensive.mass;\n\tres.stickers = old_cell.stickers;\n\treturn res;\n}\n\nSimpleAMRCellUpdaterSR3D::SimpleAMRCellUpdaterSR3D(double G, vector<string> toskip) : G_(G), toskip_(toskip) {}\n\nComputationalCell3D SimpleAMRCellUpdaterSR3D::ConvertExtensiveToPrimitve3D(const Conserved3D& extensive, const EquationOfState& /*eos*/,\n\tdouble volume, ComputationalCell3D const& old_cell, TracerStickerNames const& tracerstickernames) const\n{\n\tfor (size_t i = 0; i < toskip_.size(); ++i)\n\t\tif (*safe_retrieve(old_cell.stickers.begin(), tracerstickernames.sticker_names.begin(),\n\t\t\ttracerstickernames.sticker_names.end(), toskip_[i]))\n\t\t\treturn old_cell;\n\t\t//if (safe_retrieve(old_cell.stickers, tracerstickernames.sticker_names, toskip_[i]))\n\t\t\t//return old_cell;\n\n\tdouble v = GetVelocity(extensive, G_);\n\tvolume = 1.0 / volume;\n\tComputationalCell3D res;\n\tif (res.density < 0)\n\t\tthrow UniversalError(\"Negative density in SimpleAMRCellUpdaterSR\");\n\tres.velocity = (fastabs(extensive.momentum)*1e8 < extensive.mass) ? extensive.momentum / extensive.mass : v * extensive.momentum / abs(extensive.momentum);\n\tdouble gamma_1 = std::sqrt(1 - ScalarProd(res.velocity, res.velocity));\n\tres.density = extensive.mass *gamma_1*volume;\n\tres.stickers = old_cell.stickers;\n\t//\tsize_t N = extensive.tracers.size();\n//\tres.tracers.resize(N);\n\tfor (size_t i = 0; i < extensive.tracers.size(); ++i)\n\t\tres.tracers[i] = extensive.tracers[i] / extensive.mass;\n\tif (fastabs(res.velocity) < 1e-5)\n\t\tres.pressure = (G_ - 1)*((extensive.energy - ScalarProd(extensive.momentum, res.velocity))*volume\n\t\t\t+ (0.5*ScalarProd(res.velocity, res.velocity))*res.density);\n\telse\n\t\tres.pressure = (G_ - 1)*(extensive.energy*volume - ScalarProd(extensive.momentum, res.velocity)*volume\n\t\t\t+ (1.0 / gamma_1 - 1)*res.density);\n\treturn res;\n}\n\nSimpleAMRExtensiveUpdater3D::SimpleAMRExtensiveUpdater3D(void) {}\n\nCellsToRemove3D::~CellsToRemove3D(void) {}\n\nCellsToRefine3D::~CellsToRefine3D(void) {}\n\nAMR3D::AMR3D(EquationOfState const& eos, \n\t     CellsToRefine3D const& refine,\n\t     CellsToRemove3D const& remove,\n\t     SpatialReconstruction3D &interp,\n\t     AMRCellUpdater3D* cu,\n\t     AMRExtensiveUpdater3D* eu):\n  eos_(eos), \n  refine_(refine), \n  remove_(remove),\n  scu_(SimpleAMRCellUpdater3D()),\n  seu_(SimpleAMRExtensiveUpdater3D()), \n  interp_(interp), \n  cu_(cu), \n  eu_(eu)\n{\n\tif (!cu)\n\t\tcu_ = &scu_;\n\tif (!eu)\n\t\teu_ = &seu_;\n}\n\n\nvoid AMR3D::operator() (HDSim3D &sim)\n{\n\tTessellation3D &tess = sim.getTesselation();\n\tstd::vector<ComputationalCell3D> &cells = sim.getCells();\n\tstd::vector<Conserved3D> &extensives = sim.getExtensives();\n\tEquationOfState const& eos = eos_;\n\tTracerStickerNames tsn = sim.GetTracerStickerNames();\n\tdouble time = sim.GetTime();\n\t// Get remove list\n\tstd::pair<vector<size_t>, vector<double> > ToRemove = remove_.ToRemove(tess, cells, time, tsn);\n\t// sort\n\tvector<size_t> indeces = sort_index(ToRemove.first);\n\tToRemove.second = VectorValues(ToRemove.second, indeces);\n\tToRemove.first = VectorValues(ToRemove.first, indeces);\n\t// remove neighboring remove points\n\tToRemove = RemoveNeighbors(ToRemove.second, ToRemove.first, tess);\n#ifdef RICH_MPI\n\tToRemove = RemoveMPINeighbors(ToRemove.second, ToRemove.first, tess);\n#endif\n\t// Get points to refine\n\tstd::pair<vector<size_t>, std::vector<Vector3D> > ToRefine = refine_.ToRefine(tess, cells, time, tsn);\n\tsort_index(ToRefine.first, indeces);\n\tsort(ToRefine.first.begin(), ToRefine.first.end());\n\tif (!ToRefine.second.empty())\n\t\tVectorValues(ToRefine.second, indeces);\n\t// remove neighboring refine/remove\n\tRemoveRefineNeighborRemove(tess, ToRemove.first, ToRefine.first, ToRefine.second);\n\n\t// Do we need to rebuild tess ?\n\tint ntotal = static_cast<int>(ToRemove.first.size() + ToRefine.first.size());\n#ifdef RICH_MPI\n\tint ntemp = 0;\n\tMPI_Allreduce(&ntotal, &ntemp, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\tntotal = ntemp;\n#endif\n\tif (ntotal == 0)\n\t\treturn;\n\tinterp_.BuildSlopes(tess, cells, time, tsn);\n\t// Get new points from refine\n\tstd::vector<Vector3D> new_points = GetNewPoints(tess, ToRefine\n#ifdef RICH_MPI\n\t\t, sim.getProcTesselation()\n#endif\n\t);\n\t// Create copy of old tess\n\tboost::scoped_ptr<Tessellation3D> oldtess(tess.clone());\n\t// Build new tess\n\tvector<Vector3D> new_mesh = tess.GetMeshPoints();\n\tsize_t Norg = tess.GetPointNo();\n\tnew_mesh.resize(Norg);\n\tRemoveVector(new_mesh, ToRemove.first);\n\tnew_mesh.insert(new_mesh.end(), new_points.begin(), new_points.end());\n#ifdef RICH_MPI\n\ttess.Build(new_mesh, sim.getProcTesselation());\n#else\n\ttess.Build(new_mesh);\n#endif\n\t// Fix extensives for refine\n\textensives.resize(oldtess->GetPointNo() + ToRefine.first.size());\n\tLocalRefine(*oldtess, tess, ToRefine.first, cells, eos, tsn, *eu_, extensives,interp_);\n#ifdef RICH_MPI\n\tMPIRefine(*oldtess, tess, ToRefine.first, *eu_, eos, tsn, cells, extensives,interp_);\n#endif\n\t// Remove from extensive the remove cells\n\tRemoveVector(extensives, ToRemove.first);\n\t// Add the removed extensive to the neighboring cells\n\tLocalRemove(*oldtess, ToRemove.first, *eu_, cells, eos_, tsn, tess, extensives,interp_);\n\n#ifdef RICH_MPI\n\tMPIRemove(*oldtess, tess, ToRemove.first, *eu_, eos, tsn, cells, extensives,interp_);\n#endif\n\t// Recalc cells\n\tRemoveVector(cells, ToRemove.first);\n\tsize_t NorgNew = tess.GetPointNo();\n\tcells.resize(NorgNew);\n\tfor (size_t i = 0; i < (Norg - ToRemove.first.size()); ++i)\n\t{\n\t\ttry\n\t\t{\n\t\t\tcells[i] = cu_->ConvertExtensiveToPrimitve3D(extensives[i], eos, tess.GetVolume(i), cells[i], tsn);\n\t\t}\n\t\tcatch (UniversalError & eo)\n\t\t{\n\t\t\teo.AddEntry(\"First loop\", static_cast<double>(i));\n\t\t\teo.AddEntry(\"Norg\", static_cast<double>(Norg));\n\t\t\tthrow eo;\n\t\t}\n\t}\n\n\t// Get index for ID\n\tsize_t Nrefine = ToRefine.first.size();\n\tsize_t Nstart = sim.GetMaxID() + 1;\n#ifdef RICH_MPI\n\tint ws = 0, rank = 0;\n\tMPI_Comm_size(MPI_COMM_WORLD, &ws);\n\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\tstd::vector<size_t> nrecv(static_cast<size_t>(ws), 0);\n\tMPI_Allgather(&Nrefine, 1, MPI_UNSIGNED_LONG_LONG, &nrecv[0], 1, MPI_UNSIGNED_LONG_LONG, MPI_COMM_WORLD);\n\tfor (size_t i = 0; i < static_cast<size_t>(rank); ++i)\n\t\tNstart += nrecv[i];\n#endif\n\t// Add new refined cells\t\n\tfor (size_t i = 0; i< ToRefine.first.size(); ++i)\n\t{\n\t\tsize_t index_remove = static_cast<size_t>(std::lower_bound(ToRemove.first.begin(), ToRemove.first.end(),\n\t\t\tToRefine.first[i]) - ToRemove.first.begin());\n\t\ttry\n\t\t{\n\t\t\tcells[(Norg - ToRemove.first.size()) + i] = cu_->ConvertExtensiveToPrimitve3D(extensives[(Norg -\n\t\t\t\tToRemove.first.size()) + i], eos, tess.GetVolume((Norg - ToRemove.first.size()) + i),\n\t\t\t\tcells[ToRefine.first[i] - index_remove], tsn);\n\t\t\t// Add new ID\n\t\t\tcells[(Norg - ToRemove.first.size()) + i].ID = Nstart + i;\n\t\t}\n\t\tcatch (UniversalError & eo)\n\t\t{\n\t\t\teo.AddEntry(\"Second loop\", static_cast<double>(i));\n\t\t\teo.AddEntry(\"Norg\", static_cast<double>(Norg));\n\t\t\teo.AddEntry(\"Nrefine\", static_cast<double>(ToRefine.first.size()));\n\t\t\tthrow eo;\n\t\t}\n\t}\n\t// Recalc entropy if needed\n\tsize_t entropy_index = static_cast<size_t>(std::find(tsn.tracer_names.begin(), tsn.tracer_names.end(), std::string(\"Entropy\")) -\n\t\ttsn.tracer_names.begin());\n\tif (entropy_index < tsn.tracer_names.size())\n\t{\n\t\tsize_t Nentropy = cells.size();\n\t\tfor (size_t i = 0; i < Nentropy; ++i)\n\t\t{\n\t\t\tcells[i].tracers[entropy_index] = eos.dp2s(cells[i].density, cells[i].pressure, cells[i].tracers, tsn.tracer_names);\n\t\t\textensives[i].tracers[entropy_index] = cells[i].tracers[entropy_index] * extensives[i].mass;\n\t\t}\n\t}\n\n#ifdef RICH_MPI\n\t// Update cells\n\tComputationalCell3D cdummy;\n\tMPI_exchange_data(tess, cells, true,&cdummy);\n#endif\n\t// Update Max ID\n\tsize_t & MaxID = sim.GetMaxID();\n#ifdef RICH_MPI\n\tfor (size_t i = 0; i < static_cast<size_t>(ws); ++i)\n\t\tMaxID += nrecv[i];\n#else\n\tMaxID += Nrefine;\n#endif\n}\n\nAMR3D::~AMR3D(void) {}\n", "meta": {"hexsha": "96f7f44e18393fc79624a16db6e40906102f7390", "size": 38714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/three_dimensional/AMR3D.cpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/three_dimensional/AMR3D.cpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/three_dimensional/AMR3D.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": 34.8774774775, "max_line_length": 156, "alphanum_fraction": 0.6687503229, "num_tokens": 12052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.02161533425952185, "lm_q1q2_score": 0.006151205453379324}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Alexander Sokolov <asokolov@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_PACK_HPP\n#define CRYPTO3_DETAIL_PACK_HPP\n\n#include <nil/crypto3/detail/type_traits.hpp>\n#include <nil/crypto3/detail/stream_endian.hpp>\n#include <nil/crypto3/detail/exploder.hpp>\n#include <nil/crypto3/detail/imploder.hpp>\n#include <nil/crypto3/detail/reverser.hpp>\n#include <nil/crypto3/detail/predef.hpp>\n\n#include <boost/static_assert.hpp>\n#include <boost/predef/other/endian.h>\n#include <boost/predef/architecture.h>\n\n#include <algorithm>\n#include <climits>\n#include <iterator>\n#include <type_traits>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace detail {\n\n            /*!\n             * @defgroup pack Pack functions\n             */\n\n            /*!\n             * @brief The group of traits below is used to determine the possibility of fast data copy.\n             * By fast data copy we mean that the data is stored contiguously in the memory, so it can be\n             * copied faster byte-by-byte. Currently, fast data copy is implemented by memcpy function call.\n             */\n\n            /*!\n             * @brief host_can_memcpy trait checks whether the data to be copied and the container to be copied to\n             * are byte-aligned. Parameter types InT and OutT may refer to pointed data types or to iterator types.\n             *\n             * @ingroup pack\n             *\n             * @tparam UnitBits\n             * @tparam ValueBits\n             * @tparam InT\n             * @tparam OutT\n             */\n            template<int UnitBits, int InputBits, int OutputBits, typename InT, typename OutT>\n            struct host_can_memcpy {\n                constexpr static const bool value = !(UnitBits % CHAR_BIT) && InputBits >= UnitBits &&\n                                                    OutputBits >= UnitBits && sizeof(InT) * CHAR_BIT == InputBits &&\n                                                    sizeof(OutT) * CHAR_BIT == OutputBits;\n            };\n\n            /*!\n             * @brief can_memcpy trait is derived from host_can_memcpy trait and is invoked depending on\n             * data endianness. Note that there is a single endianness template parameter since otherwise\n             * we have to transform data in accordance with endianness conversion rules.\n             *\n             * @ingroup pack\n             *\n             * @tparam Endianness\n             * @tparam ValueBits\n             * @tparam InT\n             * @tparam OutT\n             */\n            template<typename Endianness, int InputBits, int OutputBits, typename InT, typename OutT>\n            struct can_memcpy {\n                constexpr static const bool value = InputBits == OutputBits && sizeof(InT) == sizeof(OutT);\n            };\n\n            template<int UnitBits, int InputBits, int OutputBits, typename InT, typename OutT>\n            struct can_memcpy<stream_endian::host_unit<UnitBits>, InputBits, OutputBits, InT, OutT>\n                : host_can_memcpy<UnitBits, InputBits, OutputBits, InT, OutT> { };\n\n#ifdef BOOST_ENDIAN_LITTLE_BYTE_AVAILABLE\n            template<int UnitBits, int InputBits, int OutputBits, typename InT, typename OutT>\n            struct can_memcpy<stream_endian::little_unit_big_bit<UnitBits>, InputBits, OutputBits, InT, OutT>\n                : host_can_memcpy<UnitBits, InputBits, OutputBits, InT, OutT> { };\n\n            template<int UnitBits, int InputBits, int OutputBits, typename InT, typename OutT>\n            struct can_memcpy<stream_endian::little_unit_little_bit<UnitBits>, InputBits, OutputBits, InT, OutT>\n                : host_can_memcpy<UnitBits, InputBits, OutputBits, InT, OutT> { };\n\n#elif defined(BOOST_ENDIAN_BIG_BYTE_AVAILABLE)\n            template<int UnitBits, int InputBits, int OutputBits, typename InT, typename OutT>\n            struct can_memcpy<stream_endian::big_unit_big_bit<UnitBits>, ValueBits, InT, OutT>\n                : host_can_memcpy<UnitBits, InputBits, OutputBits, InT, OutT> { };\n            template<int UnitBits, int InputBits, int OutputBits, typename InT, typename OutT>\n            struct can_memcpy<stream_endian::big_unit_little_bit<UnitBits>, ValueBits, InT, OutT>\n                : host_can_memcpy<UnitBits, InputBits, OutputBits, , InT, OutT> { };\n#endif\n\n            /*!\n             * @brief Real_packer is used to transform input data divided into chunks of the bit size InputValueBits\n             * represented in input endianness (InputEndianness)\n             * into output data (of the same bit length) divided into chunks of the bit size OutputValueBits\n             * represented in output endianness (OutputEndianness).\n             *\n             * The choice of packer depends on the following conditions:\n             * 1. input and output chunk size relation (equal, less, or greater);\n             * 2. input and output endianness relation (same or different);\n             * 3. the possibility of fast data copy using memcpy.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             * @tparam SameEndianness\n             * @tparam Implode\n             * @tparam Explode\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputType, typename OutputType,\n                     bool SameEndianness = std::is_same<InputEndianness, OutputEndianness>::value,\n                     bool Implode = (InputValueBits < OutputValueBits),\n                     bool Explode = (InputValueBits > OutputValueBits)>\n            struct real_packer { };\n\n            /*!\n             * @brief This real_packer deals with the case of equal sizes (i.e. InputValueBits == OutputValueBits)\n             * and same endianness representations (i.e., speaking informally,\n             * InputEndianness == OutputEndianness). It packs input elements with ValueBits size represented\n             * in Endianness endianness into output elements with the same ValueBits size represented in the\n             * same Endianness endianness.\n             *\n             * @ingroup pack\n             *\n             * @tparam Endianness\n             * @tparam ValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             */\n            template<typename Endianness, std::size_t ValueBits, typename InputType, typename OutputType>\n            struct real_packer<Endianness, Endianness, ValueBits, ValueBits, InputType, OutputType, true, false,\n                               false> {\n                /*!\n                 * @brief Packs n InputType elements pointed by constant pointer in\n                 * (which, hence, cannot be iterated) into OutType elements pointed by out.\n                 * This function is invoked only if memcpy call is possible.\n                 *\n                 * @ingroup pack\n                 *\n                 * @param in\n                 * @param n\n                 * @param out\n                 *\n                 * @return\n                 */\n                template<std::size_t InputValueBits, std::size_t OutputValueBits>\n                inline static typename std::enable_if<\n                    can_memcpy<Endianness, InputValueBits, OutputValueBits, InputType, OutputType>::value>::type\n                    pack_n(InputType const *in, std::size_t n, OutputType *out) {\n                    std::memcpy(out, in, n * sizeof(InputType));\n                }\n\n                /*!\n                 * @brief Packs n InputType elements pointed by pointer in into OutType elements pointed by out.\n                 * This function is invoked only if memcpy call is possible.\n                 *\n                 * @ingroup pack\n                 *\n                 * @param in\n                 * @param n\n                 * @param out\n                 *\n                 * @return\n                 */\n                template<std::size_t InputValueBits, std::size_t OutputValueBits>\n                inline static typename std::enable_if<\n                    can_memcpy<Endianness, InputValueBits, OutputValueBits, InputType, OutputType>::value>::type\n                    pack_n(InputType *in, std::size_t n, OutputType *out) {\n                    std::memcpy(out, in, n * sizeof(InputType));\n                }\n\n                /*!\n                 * @brief Packs in_n elements iterated by in into elements iterated by out.\n                 *\n                 * @ingroup pack\n                 *\n                 * @tparam InputIterator\n                 * @tparam OutputIterator\n                 *\n                 * @param in\n                 * @param in_n\n                 * @param out\n                 *\n                 * @return\n                 */\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t in_n, OutputIterator out) {\n                    std::copy(in, in + in_n, out);\n                }\n\n                /*!\n                 * @brief Packs elements in range [first, last) into elements iterated by out.\n                 * This function is invoked only if input and output iterators meet RandomAccessIterator\n                 * requirements. However, the restriction can be weakened to ContiguousIterator usage.\n                 *\n                 * @ingroup pack\n                 *\n                 * @tparam InputIterator\n                 * @tparam OutputIterator\n                 *\n                 * @param first\n                 * @param last\n                 * @param random_access_iterator_tag\n                 * @param out\n                 * @param random_access_iterator_tag\n                 *\n                 * @return\n                 */\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, std::random_access_iterator_tag,\n                                        OutputIterator out, std::random_access_iterator_tag) {\n                    pack_n(first, std::distance(first, last), out);\n                }\n\n                /*!\n                 * @brief Packs elements in range [first, last) into elements iterated by out.\n                 * This function is invoked only if input or output iterator doesn't meet RandomAccessIterator\n                 * requirements.\n                 *\n                 * @ingroup pack\n                 *\n                 * @tparam InputIterator\n                 * @tparam InCatT\n                 * @tparam OutputIterator\n                 * @tparam OutCatT\n                 *\n                 * @param first\n                 * @param last\n                 * @param InCatT\n                 * @param out\n                 * @param OutCatT\n                 *\n                 * @return\n                 */\n                template<typename InputIterator, typename InCatT, typename OutputIterator, typename OutCatT>\n                inline static void pack(InputIterator first, InputIterator last, InCatT, OutputIterator out, OutCatT) {\n                    std::copy(first, last, out);\n                }\n\n                /*!\n                 * @brief Generic function that chooses pack function depending on input and output iterator category.\n                 *\n                 * @ingroup pack\n                 *\n                 * @tparam InputIterator\n                 * @tparam OutputIterator\n                 *\n                 * @param first\n                 * @param last\n                 * @param out\n                 *\n                 * @return\n                 */\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n\n                    typedef typename std::iterator_traits<InputIterator>::iterator_category in_cat;\n                    typedef typename std::iterator_traits<OutputIterator>::iterator_category out_cat;\n\n                    pack(first, last, in_cat(), out, out_cat());\n                }\n            };\n\n            /*!\n             * @brief This real_packer deals with the case of equal sizes (i.e. InputValueBits == OutputValueBits)\n             * and different endianness representations (or, speaking informally,\n             * InputEndianness != OutputEndianness). It invokes functions which pack input elements\n             * with ValueBits size represented in InputEndianness endianness into output elements\n             * with the same ValueBits size represented in another OutputEndianness endianness.\n             *\n             * @ingroup pack\n             *\n             * @tparam UnitBits\n             * @tparam InputEndian\n             * @tparam OutputEndian\n             * @tparam ValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             */\n            template<int UnitBits, template<int> class InputEndian, template<int> class OutputEndian,\n                     std::size_t ValueBits, typename InputType, typename OutputType>\n            struct real_packer<InputEndian<UnitBits>, OutputEndian<UnitBits>, ValueBits, ValueBits, InputType,\n                               OutputType, false, false, false> {\n\n                typedef InputEndian<UnitBits> InputEndianness;\n                typedef OutputEndian<UnitBits> OutputEndianness;\n\n                typedef unit_reverser<InputEndianness, OutputEndianness, UnitBits> units_reverser;\n                typedef bit_reverser<InputEndianness, OutputEndianness, UnitBits> bits_reverser;\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t in_n, OutputIterator out) {\n\n                    std::transform(in, in + in_n, out, [](InputType const &elem) {\n                        return units_reverser::reverse(bits_reverser::reverse(elem));\n                    });\n                }\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n\n                    std::transform(first, last, out, [](InputType const &elem) {\n                        return units_reverser::reverse(bits_reverser::reverse(elem));\n                    });\n                }\n            };\n\n            /*!\n             * @brief This real_packer deals with case InputValueBits < OutputValueBits and invokes implode function,\n             * which, in its turn, packs input elements with InputValueBits size represented in InputEndianness\n             * endianness into output elements with OutputValueBits size represented in OutputEndianness\n             * endianness.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             * @tparam SameEndianness\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputType, typename OutputType, bool SameEndianness>\n            struct real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                               OutputType, SameEndianness, true, false> {\n\n                BOOST_STATIC_ASSERT(!(OutputValueBits % InputValueBits));\n\n                typedef detail::imploder<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits> imploder;\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t in_n, OutputIterator out) {\n                    std::size_t out_n = in_n / (OutputValueBits / InputValueBits);\n\n                    while (out_n--) {\n                        OutputType value = OutputType();\n                        imploder::implode(in, value);\n                        *out++ = value;\n                    }\n                }\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n                    while (first != last) {\n                        OutputType value = OutputType();\n                        imploder::implode(first, value);\n                        *out++ = value;\n                    }\n                }\n            };\n\n            /*!\n             * @brief This real_packer deals with case InputValueBits > OutputValueBits and invokes explode function,\n             * which, in its turn, packs input elements with InputValueBits size represented in InputEndianness\n             * endianness into output elements with OutputValueBits size represented in OutputEndianness\n             * endianness.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             * @tparam SameEndianness\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputType, typename OutputType, bool SameEndianness>\n            struct real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                               OutputType, SameEndianness, false, true> {\n\n                BOOST_STATIC_ASSERT(!(InputValueBits % OutputValueBits));\n\n                typedef detail::exploder<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits> exploder;\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t in_n, OutputIterator out) {\n                    while (in_n--) {\n                        InputType const value = *in++;\n                        exploder::explode(value, out);\n                    }\n                }\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n                    while (first != last) {\n                        InputType const value = *first++;\n                        exploder::explode(value, out);\n                    }\n                }\n            };\n\n            /*!\n             * @brief This packer deals with arbitrary input and output (but not bool) data elements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputType, typename OutputType>\n            struct packer {\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t n, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                                        OutputType>\n                        packer_type;\n\n                    packer_type::pack_n(in, n, out);\n                }\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                                        OutputType>\n                        packer_type;\n\n                    packer_type::pack(first, last, out);\n                }\n            };\n\n            /*!\n             * @brief This packer deals with bool input and output data elements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits>\n            struct packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, bool, bool> {\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t n, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, bool, bool>\n                        packer_type;\n\n                    packer_type::pack_n(in, n, out);\n                }\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, bool, bool>\n                        packer_type;\n\n                    packer_type::pack(first, last, out);\n                }\n            };\n\n            /*!\n             * @brief This packer deals with bool input data and arbitrary (but not bool) output data elements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam OutputType\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename OutputType>\n            struct packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, bool, OutputType> {\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t n, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, bool,\n                                        OutputType>\n                        packer_type;\n\n                    packer_type::pack_n(in, n, out);\n                }\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, bool,\n                                        OutputType>\n                        packer_type;\n\n                    packer_type::pack(first, last, out);\n                }\n            };\n\n            /*!\n             * @brief This packer deals with arbitrary (but not bool) input data and bool output data elements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputType\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputType>\n            struct packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType, bool> {\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack_n(InputIterator in, std::size_t n, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                                        bool>\n                        packer_type;\n\n                    packer_type::pack_n(in, n, out);\n                }\n\n                template<typename InputIterator, typename OutputIterator>\n                inline static void pack(InputIterator first, InputIterator last, OutputIterator out) {\n                    typedef real_packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                                        bool>\n                        packer_type;\n\n                    packer_type::pack(first, last, out);\n                }\n            };\n\n            /*!\n             * @brief Packs elements from range [first, last) represented in machine-dependent endianness\n             * into elements starting from out represented in OutputEndianness endianness.\n             *\n             * @ingroup pack\n             *\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param first\n             * @param last\n             * @param out\n             *\n             * @return\n             */\n            template<typename OutputEndianness, std::size_t InputValueBits, std::size_t OutputValueBits,\n                     typename InputIterator, typename OutputIterator>\n            inline void pack_to(InputIterator first, InputIterator last, OutputIterator out) {\n\n                typedef typename std::iterator_traits<InputIterator>::value_type InputType;\n                typedef typename std::iterator_traits<OutputIterator>::value_type OutputType;\n\n#ifdef BOOST_ENDIAN_BIG_BYTE_AVAILABLE\n                typedef packer<stream_endian::big_octet_big_bit, OutputEndianness, InputValueBits, OutputValueBits,\n                               InputType, OutputType>\n                    packer_type;\n#elif defined(BOOST_ENDIAN_LITTLE_BYTE_AVAILABLE)\n                typedef packer<stream_endian::little_octet_big_bit, OutputEndianness, InputValueBits, OutputValueBits,\n                               InputType, OutputType>\n                    packer_type;\n#elif defined(BOOST_ENDIAN_BIG_WORD_AVAILABLE)\n                typedef packer<stream_endian::big_unit_big_bit<BOOST_ARCH_CURRENT_WORD_BITS>, OutputEndianness, InputValueBits,\n                               OutputValueBits, InputType, OutputType>\n                    packer_type;\n#elif defined(BOOST_ENDIAN_LITTLE_WORD_AVAILABLE)\n                typedef packer<stream_endian::little_unit_big_bit<BOOST_ARCH_CURRENT_WORD_BITS>, OutputEndianness,\n                               InputValueBits, OutputValueBits, InputType, OutputType>\n                    packer_type;\n#else\n#error \"Unknown endianness\"\n#endif\n\n                packer_type::pack(first, last, out);\n            }\n\n            /*!\n             * @brief Packs elements from range [first, last) represented in InputEndianness endianness\n             * into elements starting from out represented in machine-dependent endianness.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param first\n             * @param last\n             * @param out\n             *\n             * @return\n             */\n            template<typename InputEndianness, std::size_t InputValueBits, std::size_t OutputValueBits,\n                     typename InputIterator, typename OutputIterator>\n            inline void pack_from(InputIterator first, InputIterator last, OutputIterator out) {\n\n                typedef typename std::iterator_traits<InputIterator>::value_type InputType;\n                typedef typename std::iterator_traits<OutputIterator>::value_type OutputType;\n\n#ifdef BOOST_ENDIAN_BIG_BYTE_AVAILABLE\n                typedef packer<InputEndianness, stream_endian::big_octet_big_bit, InputValueBits, OutputValueBits,\n                               InputType, OutputType>\n                    packer_type;\n#elif defined(BOOST_ENDIAN_LITTLE_BYTE_AVAILABLE)\n                typedef packer<InputEndianness, stream_endian::little_octet_big_bit, InputValueBits, OutputValueBits,\n                               InputType, OutputType>\n                    packer_type;\n#elif defined(BOOST_ENDIAN_BIG_WORD_AVAILABLE)\n                typedef packer<InputEndianness, stream_endian::big_unit_big_bit<BOOST_ARCH_CURRENT_WORD_BITS>, InputValueBits,\n                               OutputValueBits, InputType, OutputType>\n                    packer_type;\n#elif defined(BOOST_ENDIAN_LITTLE_WORD_AVAILABLE)\n                typedef packer<InputEndianness, stream_endian::little_unit_big_bit<BOOST_ARCH_CURRENT_WORD_BITS>,\n                               InputValueBits, OutputValueBits, InputType, OutputType>\n                    packer_type;\n#else\n#error \"Unknown endianness\"\n#endif\n\n                packer_type::pack(first, last, out);\n            }\n\n            /*!\n             * @brief Packs in_n input elements starting from in into output elements beginning from out.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param in\n             * @param in_n\n             * @param out\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename OutputIterator>\n            inline void pack_n(InputIterator in, std::size_t in_n, OutputIterator out) {\n                typedef typename std::iterator_traits<InputIterator>::value_type InputType;\n                typedef typename std::iterator_traits<OutputIterator>::value_type OutputType;\n                typedef packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                               OutputType>\n                    packer_type;\n\n                packer_type::pack_n(in, in_n, out);\n            }\n\n            /*!\n             * @brief Packs in_n input elements starting from in into in_out elements beginning from out.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param in\n             * @param in_n\n             * @param out\n             * @param out_n\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename OutputIterator>\n            inline void pack_n(InputIterator in, std::size_t in_n, OutputIterator out, std::size_t out_n) {\n                BOOST_ASSERT(in_n * InputValueBits == out_n * OutputValueBits);\n\n                pack_n<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(in, in_n, out);\n            }\n\n            /*!\n             * @brief Packs elements from the range [first, last) into elements starting from out.\n             * Works for input containers meeting RandomAccessIterator requirements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param first\n             * @param last\n             * @param random_access_iterator_tag\n             * @param out\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename OutputIterator>\n            inline void pack(InputIterator first, InputIterator last, std::random_access_iterator_tag,\n                             OutputIterator out) {\n                pack_n<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(first, last - first, out);\n            }\n\n            /*!\n             * @brief Packs elements from the range [first, last) into elements starting from out.\n             * Works for input containers meeting InCatT category requirements and output containers\n             * meeting OutputIterator requirements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam InCatT\n             * @tparam OutputIterator\n             *\n             * @param first\n             * @param last\n             * @param InCatT\n             * @param out\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename InCatT, typename OutputIterator,\n                     typename = typename std::enable_if<detail::is_iterator<InputIterator>::value>::type,\n                     typename = typename std::enable_if<detail::is_iterator<OutputIterator>::value>::type>\n            inline void pack(InputIterator first, InputIterator last, InCatT, OutputIterator out) {\n                typedef typename std::iterator_traits<InputIterator>::value_type InputType;\n                typedef typename std::iterator_traits<OutputIterator>::value_type OutputType;\n                typedef packer<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits, InputType,\n                               OutputType>\n                    packer_type;\n\n                packer_type::pack(first, last, out);\n            }\n\n            /*!\n             * @brief Generic function that chooses pack function depending on input iterator category.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param first\n             * @param last\n             * @param out\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename OutputIterator,\n                     typename = typename std::enable_if<detail::is_iterator<OutputIterator>::value>::type>\n            inline void pack(InputIterator first, InputIterator last, OutputIterator out) {\n                typedef typename std::iterator_traits<InputIterator>::iterator_category in_cat;\n\n                pack<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(first, last, in_cat(), out);\n            }\n\n            /*!\n             * @brief Packs elements from the range [first, last) into elements starting from out.\n             * Works for input and output containers meeting RandomAccessIterator requirements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param in_first\n             * @param in_last\n             * @param random_access_iterator_tag\n             * @param out_first\n             * @param out_last\n             * @param random_access_iterator_tag\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename OutputIterator>\n            inline void pack(InputIterator in_first, InputIterator in_last, std::random_access_iterator_tag,\n                             OutputIterator out_first, OutputIterator out_last, std::random_access_iterator_tag) {\n                pack_n<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(\n                    in_first, in_last - in_first, out_first, out_last - out_first);\n            }\n\n            /*!\n             * @brief Packs elements from the range [first, last) into elements starting from out.\n             * Works for input containers meeting InCatT category requirements and output containers\n             * meeting OutCatT category requirements.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam InCatT\n             * @tparam OutputIterator\n             * @tparam OutCatT\n             *\n             * @param in_first\n             * @param in_last\n             * @param InCatT\n             * @param out\n             * @param OutputIterator\n             * @param OutCatT\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename InCatT, typename OutputIterator,\n                     typename OutCatT>\n            inline void pack(InputIterator in_first, InputIterator in_last, InCatT, OutputIterator out, OutputIterator,\n                             OutCatT) {\n                pack<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(in_first, in_last, out);\n            }\n\n            /*!\n             * @brief Generic function that chooses pack function depending on input and output iterator category.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputIterator\n             * @tparam OutputIterator\n             *\n             * @param in_first\n             * @param in_last\n             * @param out_first\n             * @param out_last\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename OutputIterator>\n            inline void pack(InputIterator in_first, InputIterator in_last, OutputIterator out_first,\n                             OutputIterator out_last) {\n                typedef typename std::iterator_traits<InputIterator>::iterator_category in_cat;\n                typedef typename std::iterator_traits<OutputIterator>::iterator_category out_cat;\n\n                pack<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(\n                    in_first, in_last, in_cat(), out_first, out_last, out_cat());\n            }\n\n            /*!\n             * @brief Packs immutable data referenced by in into data referenced by out.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             *\n             * @param in\n             * @param out\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputType, typename OutputType>\n            inline void pack(const InputType &in, OutputType &out) {\n                pack_n<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(in.begin(), in.size(),\n                                                                                           out.begin(), out.size());\n            }\n\n            /*!\n             * @brief Packs elements from range [first, last) into data referenced by out with\n             * non-arithmetic value type.\n             *\n             * @ingroup pack\n             *\n             * @tparam InputEndianness\n             * @tparam OutputEndianness\n             * @tparam InputValueBits\n             * @tparam OutputValueBits\n             * @tparam InputType\n             * @tparam OutputType\n             *\n             * @param in\n             * @param out\n             *\n             * @return\n             */\n            template<typename InputEndianness, typename OutputEndianness, std::size_t InputValueBits,\n                     std::size_t OutputValueBits, typename InputIterator, typename OutputType,\n                     typename = typename std::enable_if<!std::is_arithmetic<OutputType>::value>::type>\n            inline void pack(InputIterator first, InputIterator last, OutputType &out) {\n                pack_n<InputEndianness, OutputEndianness, InputValueBits, OutputValueBits>(\n                    first, std::distance(first, last), out.begin(), out.size());\n            }\n\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_DETAIL_PACK_HPP", "meta": {"hexsha": "4a167ac0c4eed1508ddd6b64cd841826a0bd9b26", "size": 43800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/detail/pack.hpp", "max_stars_repo_name": "JasonCoombs/crypto3-pkmodes", "max_stars_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/detail/pack.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-pkmodes", "max_issues_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-01T15:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T03:45:24.000Z", "max_forks_repo_path": "include/nil/crypto3/detail/pack.hpp", "max_forks_repo_name": "JasonCoombs/crypto3-pkmodes", "max_forks_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:40:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:13:02.000Z", "avg_line_length": 46.1052631579, "max_line_length": 127, "alphanum_fraction": 0.5628995434, "num_tokens": 8476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451645880021026, "lm_q2_score": 0.03732688935207537, "lm_q1q2_score": 0.006140887654230715}}
{"text": "/**\n* Copyright 2018 Woods Hole Oceanographic Institution\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n*\n* 1. Redistributions of source code must retain the above copyright notice,\n*    this list of conditions and the following disclaimer.\n*\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n*    this list of conditions and the following disclaimer in the documentation\n*    and/or other materials provided with the distribution.\n*\n* 3. Neither the name of the copyright holder nor the names of its contributors\n*    may be used to endorse or promote products derived from this software\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\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// lots of this implementation blatently stolen from:\n// https://github.com/ros-simulation/gazebo_ros_pkgs/blob/kinetic-devel/gazebo_plugins/src/gazebo_ros_imu_sensor.cpp\n#include \"dsros_dvl_plugin.hh\"\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\nusing namespace gazebo;\n\nGZ_REGISTER_SENSOR_PLUGIN(dsrosRosDvlSensor);\n\ndsrosRosDvlSensor::dsrosRosDvlSensor() : SensorPlugin() {\n\n    sensor = NULL;\n    seed = 0;\n};\n\ndsrosRosDvlSensor::~dsrosRosDvlSensor() {\n    if (connection.get()) {\n        connection.reset();\n    }\n    node->shutdown();\n}\n\nvoid dsrosRosDvlSensor::Load(sensors::SensorPtr sensor_, sdf::ElementPtr sdf_) {\n    sdf = sdf_;\n    sensor = std::dynamic_pointer_cast<gazebo::sensors::DsrosDvlSensor>(sensor_);\n    if (sensor == NULL) {\n        ROS_FATAL(\"Error! Unable to convert sensor pointer!\");\n        return;\n    }\n    sensor->SetActive(true);\n\n    if (!LoadParameters()) {\n        ROS_FATAL(\"Error loading parameters for sensor plugin!\");\n        return;\n    }\n\n    if (!ros::isInitialized()) {\n        ROS_FATAL(\"ROS has not been initialized properly...\");\n        return;\n    }\n\n    node = new ros::NodeHandle(this->robot_namespace);\n\n    dvl_data_publisher = node->advertise<ds_sensor_msgs::Dvl>(topic_name, 1);\n    rng_publisher = node->advertise<ds_sensor_msgs::Ranges3D>(ranges_topic_name, 1);\n    pt_data_publisher  = node->advertise<sensor_msgs::PointCloud>(topic_name + \"_cloud\", 1);\n    current_profile_publisher = node->advertise<ds_sensor_msgs::Adcp>(topic_name + \"_current\", 1);\n    pt_data_publisher  = node->advertise<sensor_msgs::PointCloud>(topic_name + \"_cloud\", 1);\n    connection = gazebo::event::Events::ConnectWorldUpdateBegin(\n                boost::bind(&dsrosRosDvlSensor::UpdateChild, this, _1));\n    last_time = sensor->LastUpdateTime();\n\n    // Initialize data members and the Adcp message for current profiling\n    current_profile_cell_depth = (sensor->RangeMax() - sensor->RangeMin()) / water_track_bins;\n    current_profile_bin0_distance = sensor->RangeMin() + current_profile_cell_depth / 2.0;\n    for (size_t beam = 0; beam < 4; beam++)\n    {\n        ignition::math::Vector3d unit_vec = sensor->GetBeamUnitVec(beam);\n        adcp.beam_unit_vec[beam].x = unit_vec.X();\n        adcp.beam_unit_vec[beam].y = unit_vec.Y();\n        adcp.beam_unit_vec[beam].z = unit_vec.Z();\n    } // for (size_t beam = 0;...\n    adcp.vel_bin_beams.resize(water_track_bins);\n    for (size_t bin = 0; bin < water_track_bins; bin++)\n    {\n        if (current_profile_coord_mode == ds_sensor_msgs::Adcp::ADCP_COORD_BEAM)\n        {\n            adcp.vel_bin_beams[bin].velocity_bin_beam.resize(4);\n//            adcp.vel_bin_beams[bin].bin_intensity.resize(4);     // Commented out in msg def for now\n//            adcp.vel_bin_beams[bin].bin_correlation.resize(4);   // Commented out in msg def for now\n        }\n        else\n        {\n            adcp.vel_bin_beams[bin].velocity_bin_beam.resize(1);\n//            adcp.vel_bin_beams[bin].bin_intensity.resize(1);     // Commented out in msg def for now\n//            adcp.vel_bin_beams[bin].bin_correlation.resize(1);   // Commented out in msg def for now\n        }\n    } // for (size_t bin = 0;...\n}\n\nvoid dsrosRosDvlSensor::UpdateChild(const gazebo::common::UpdateInfo &_info) {\n\n    common::Time current_time = sensor->LastUpdateTime();\n\n    if(update_rate>0 && (current_time-last_time).Double() < 1.0/update_rate) {\n        return;\n    }\n\n    // add noise and recompute the velocity\n    std::vector<double> ranges(4);\n    Eigen::VectorXd raw_beam_vel(4);\n    Eigen::VectorXd beam_vel(4);\n    Eigen::VectorXd beam_wtr_vel(4);\n    Eigen::MatrixXd beam_unit(4,3);\n    Eigen::MatrixXd beam_wtr_unit(4,3);\n    Eigen::Vector3d velocity;\n    Eigen::Vector3d wtr_velocity;\n    double speed = 0;\n    double course = 0;\n    double altitude = 0;\n    double wtr_speed = 0;\n    double wtr_course = 0;\n    int fillIn = 0;\n    for (size_t i=0; i<sensor->NumBeams(); i++) {\n\n        ignition::math::Vector3d beamUnit = sensor->GetBeamUnitVec(i);\n        if (sensor->BeamValid(i)) {\n            ranges[i] = sensor->GetBeamRange(i) + GaussianKernel(0, gaussian_noise_range);\n            raw_beam_vel(i) = sensor->GetBeamVelocity(i) + GaussianKernel(0, gaussian_noise_vel);\n            beam_vel(fillIn) = raw_beam_vel(i);\n            beam_unit(fillIn, 0) = beamUnit.X();\n            beam_unit(fillIn, 1) = beamUnit.Y();\n            beam_unit(fillIn, 2) = beamUnit.Z();\n            altitude += ranges[i];\n            fillIn++;\n        } else {\n            ranges[i] = std::numeric_limits<double>::quiet_NaN();\n        }\n        beam_wtr_vel(i) = sensor->GetBeamWaterVelocity(i) + GaussianKernel(0, gaussian_noise_wtr_vel);\n        beam_wtr_unit(i, 0) = beamUnit.X();\n        beam_wtr_unit(i, 1) = beamUnit.Y();\n        beam_wtr_unit(i, 2) = beamUnit.Z();\n    }\n\n    if (fillIn >= 3) {\n        // trim the arrays\n        beam_unit = beam_unit.topRows(fillIn);\n        beam_vel = beam_vel.head(fillIn);\n\n        // solve a least-squares problem to get velocity based on the noisy ranges\n        velocity = beam_unit.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(beam_vel);\n\n        altitude /= static_cast<float>(fillIn);\n        altitude *= cos(M_PI/6); // convert range to altitude\n\n        speed = sqrt(velocity(0)*velocity(0) + velocity(1)*velocity(1));\n        course = atan2(velocity(0), velocity(1)) * 180.0/M_PI;\n        if (course < 0) {\n            course += 360.0;\n        }\n    }\n    // same method to compute a water track velocity based on the noisy beam water velocities\n    wtr_velocity = beam_wtr_unit.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(beam_wtr_vel);\n    wtr_speed = sqrt(wtr_velocity(0)*wtr_velocity(0) + wtr_velocity(1)*wtr_velocity(1));\n    wtr_course = atan2(wtr_velocity(0), wtr_velocity(1)) * 180.0/M_PI;\n    if (wtr_course < 0) {\n        wtr_course += 360.0;\n    }\n\n    // publish DVL data message\n    if(dvl_data_publisher.getNumSubscribers() > 0) {\n\n        // prepare message header\n        msg.header.frame_id = frame_name;\n        msg.header.stamp.sec = current_time.sec;\n        msg.header.stamp.nsec = current_time.nsec;\n        msg.header.seq++;\n\n        msg.ds_header.io_time.sec = current_time.sec;\n        msg.ds_header.io_time.nsec = current_time.nsec;\n\n        if ((fillIn >= 3) || (!water_track_enabled)) {\n            msg.velocity.x = velocity(0);\n            msg.velocity.y = velocity(1);\n            msg.velocity.z = velocity(2);\n            msg.course_gnd = course;\n            msg.speed_gnd = speed;\n            msg.velocity_mode = ds_sensor_msgs::Dvl::DVL_MODE_BOTTOM;\n            msg.velocity_covar[0] = gaussian_noise_vel*gaussian_noise_vel;\n            msg.velocity_covar[1] = 0;\n            msg.velocity_covar[2] = 0;\n\n            msg.velocity_covar[3] = 0;\n            msg.velocity_covar[4] = gaussian_noise_vel*gaussian_noise_vel;\n            msg.velocity_covar[5] = 0;\n\n            msg.velocity_covar[6] = 0;\n            msg.velocity_covar[7] = 0;\n            msg.velocity_covar[8] = gaussian_noise_vel*gaussian_noise_vel;\n        } else {\n            msg.velocity.x = wtr_velocity(0);\n            msg.velocity.y = wtr_velocity(1);\n            msg.velocity.z = wtr_velocity(2);\n            msg.course_gnd = wtr_course;\n            msg.speed_gnd = wtr_speed;\n            msg.velocity_mode = ds_sensor_msgs::Dvl::DVL_MODE_WATER;\n            msg.velocity_covar[0] = gaussian_noise_wtr_vel*gaussian_noise_wtr_vel;\n            msg.velocity_covar[1] = 0;\n            msg.velocity_covar[2] = 0;\n\n            msg.velocity_covar[3] = 0;\n            msg.velocity_covar[4] = gaussian_noise_wtr_vel*gaussian_noise_wtr_vel;\n            msg.velocity_covar[5] = 0;\n\n            msg.velocity_covar[6] = 0;\n            msg.velocity_covar[7] = 0;\n            msg.velocity_covar[8] = gaussian_noise_wtr_vel*gaussian_noise_wtr_vel;\n        }\n        msg.num_good_beams = sensor->ValidBeams();\n        msg.speed_sound = 1500.0;\n        msg.altitude = altitude;\n\n        for (size_t i=0; i<sensor->NumBeams(); i++) {\n            msg.range[i] = ranges[i];\n            msg.range_covar[i] = gaussian_noise_range*gaussian_noise_range;\n            ignition::math::Vector3d beamUnit = sensor->GetBeamUnitVec(i);\n            msg.beam_unit_vec[i].x = beamUnit.X();\n            msg.beam_unit_vec[i].y = beamUnit.Y();\n            msg.beam_unit_vec[i].z = beamUnit.Z();\n            if (fillIn >= 3) {\n                msg.raw_velocity[i] = raw_beam_vel(i);\n                msg.raw_velocity_covar[i] = gaussian_noise_vel*gaussian_noise_vel;\n            } else {\n                msg.raw_velocity[i] = beam_wtr_vel(i);\n                msg.raw_velocity_covar[i] = gaussian_noise_wtr_vel*gaussian_noise_wtr_vel;\n            }\n        }\n\n        //ROS_INFO_STREAM(\"DVL_SENDING_INST: \" <<velocity(0) <<\" \" <<velocity(1) <<\" \" <<velocity(2));\n\n        msg.coordinate_mode = ds_sensor_msgs::Dvl::DVL_COORD_INSTRUMENT;\n        msg.dvl_time = static_cast<double>(current_time.sec) + static_cast<double>(current_time.nsec)/1.0e9;\n\n        // publish data\n        dvl_data_publisher.publish(msg);\n        ros::spinOnce();\n    }\n\n    // publish current profile (ADCP) message\n    if ((current_profile_publisher.getNumSubscribers() > 0) && \n        ((current_profile_coord_mode == ds_sensor_msgs::Adcp::ADCP_COORD_BEAM) ||\n         (current_profile_coord_mode == ds_sensor_msgs::Adcp::ADCP_COORD_INSTRUMENT)) &&\n        (water_track_enabled)) {  // No current profile if water track unavailable or unsupported mode\n        // prepare message header\n        adcp.header.frame_id = frame_name;\n        adcp.header.stamp.sec = current_time.sec;\n        adcp.header.stamp.nsec = current_time.nsec;\n        adcp.header.seq++;\n\n        msg.ds_header.io_time.sec = current_time.sec;\n        msg.ds_header.io_time.nsec = current_time.nsec;\n\n        // Fill message-level fields\n        adcp.coordinate_mode = current_profile_coord_mode;\n        adcp.adcp_type = ds_sensor_msgs::Adcp::ADCP_TYPE_PISTON;\n        adcp.cells = water_track_bins;\n        adcp.cell_depth = current_profile_cell_depth;\n        adcp.bin0_distance = current_profile_bin0_distance;\n\n        // Fill in beam-specific bin velocities as water velocity plus noise\n        // out to the beam's current range.  No solution (0.0) beyond that\n        for (size_t bin = 0; bin < water_track_bins; bin ++)\n        {\n            double bin_range = current_profile_bin0_distance + \n                               (current_profile_cell_depth * bin);\n\n            if (current_profile_coord_mode == ds_sensor_msgs::Adcp::ADCP_COORD_BEAM)\n            {   // Calculate a velocity in beam coordinates for each beam for every cell\n                for (size_t beam=0; beam < sensor->NumBeams(); beam++)\n                {\n                    // add noise to the beam's bin-specific velocity\n                    double bin_velocity = sensor->GetBeamWaterVelocityBin(beam, bin) +\n                                          GaussianKernel(0, gaussian_noise_wtr_vel);\n                    if (bin_velocity != gazebo::sensors::DsrosDvlBeam::NO_VELOCITY)\n                    {\n                        ignition::math::Vector3d beamUnit = sensor->GetBeamUnitVec(beam);\n                        adcp.vel_bin_beams[bin].velocity_bin_beam[beam].x = -bin_velocity * beamUnit.X();\n                        adcp.vel_bin_beams[bin].velocity_bin_beam[beam].y = -bin_velocity * beamUnit.Y();\n                        adcp.vel_bin_beams[bin].velocity_bin_beam[beam].z = -bin_velocity * beamUnit.Z();\n                    } // if (beam_range >=...\n                    else \n                    {\n                        adcp.vel_bin_beams[bin].velocity_bin_beam[beam].x = 0.0;\n                        adcp.vel_bin_beams[bin].velocity_bin_beam[beam].y = 0.0;\n                        adcp.vel_bin_beams[bin].velocity_bin_beam[beam].z = 0.0;\n                    } // else\n                } // for (size_t beam = 0;...\n            } // if (current_profile_coord_mode ==...\n            else\n            {   // Calculate a single velocity in instrument coordinates for every cell\n                bool range_solution = true;\n                for (size_t beam=0; beam < sensor->NumBeams(); beam++)\n                {\n                    double bin_velocity = sensor->GetBeamWaterVelocityBin(beam, bin);\n                    if (range_solution &&\n                        (bin_velocity != gazebo::sensors::DsrosDvlBeam::NO_VELOCITY))\n                    {\n                        ignition::math::Vector3d beamUnit = sensor->GetBeamUnitVec(beam);\n                        beam_wtr_vel(beam) = sensor->GetBeamWaterVelocityBin(beam, bin) +\n                                             GaussianKernel(0, gaussian_noise_wtr_vel);\n                        beam_wtr_unit(beam, 0) = beamUnit.X();\n                        beam_wtr_unit(beam, 1) = beamUnit.Y();\n                        beam_wtr_unit(beam, 2) = beamUnit.Z();\n                    } // if (!no_solution...\n                    else\n                    {\n                        range_solution = false;\n                    } // else\n                } // for (size_t beam=0;...\n                if (range_solution)  // if bin for any beam is beyond bottom, solution will be 0\n                {\n                    Eigen::Vector3d bin_velocity =\n                        beam_wtr_unit.jacobiSvd(Eigen::ComputeThinU |\n                                                Eigen::ComputeThinV).\n                                      solve(beam_wtr_vel);\n                    adcp.vel_bin_beams[bin].velocity_bin_beam[0].x = -bin_velocity[0];\n                    adcp.vel_bin_beams[bin].velocity_bin_beam[0].y = -bin_velocity[1];\n                    adcp.vel_bin_beams[bin].velocity_bin_beam[0].z = -bin_velocity[2];\n                } // if (range_solution)\n                else\n                {\n                    adcp.vel_bin_beams[bin].velocity_bin_beam[0].x = 0.0;\n                    adcp.vel_bin_beams[bin].velocity_bin_beam[0].y = 0.0;\n                    adcp.vel_bin_beams[bin].velocity_bin_beam[0].z = 0.0;\n                } // else\n            } // else\n        } // for (size_t bin = 0;...\n\n        current_profile_publisher.publish(adcp);\n        ros::spinOnce();\n    }\n\n    // publish point cloud message\n    if (pt_data_publisher.getNumSubscribers() > 0) {\n        // prepare message header\n        pt_msg.header.frame_id = pointcloud_frame;\n        pt_msg.header.stamp.sec = current_time.sec;\n        pt_msg.header.stamp.nsec = current_time.nsec;\n        pt_msg.header.seq++;\n\n        // fill in some points\n        size_t NUM_PTS_PER_BEAM = 1000;\n        double range = sensor->RangeMax() - sensor->RangeMin();\n        pt_msg.points.resize(NUM_PTS_PER_BEAM*sensor->NumBeams()); // use 100 pts\n        size_t fillIn = 0;\n        for (size_t j=0; j<sensor->NumBeams(); j++) {\n\n            ignition::math::Pose3d beamPose = sensor->GetBeamPose(j);\n            for (size_t i=0; i<NUM_PTS_PER_BEAM; i++) {\n                ignition::math::Vector3d vec;\n                vec.X() = 0;\n                vec.Y() = 0;\n                vec.Z() = sensor->RangeMin() + static_cast<double>(i)/static_cast<double>(\n                                NUM_PTS_PER_BEAM-1)*(range);\n    \n                ignition::math::Vector3d beam = beamPose.Rot().RotateVector(vec) + beamPose.Pos();\n                pt_msg.points[fillIn].x = beam.X();\n                pt_msg.points[fillIn].y = beam.Y();\n                pt_msg.points[fillIn].z = beam.Z();\n                fillIn++;\n            }\n        }\n        // publish data\n        pt_data_publisher.publish(pt_msg);\n        ros::spinOnce();\n    }\n\n    // publish DVL contact range message\n    if (rng_publisher.getNumSubscribers() > 0) {\n        // prepare message header\n        rng.header.frame_id = frame_name;\n        rng.header.stamp.sec = current_time.sec;\n        rng.header.stamp.nsec = current_time.nsec;\n        rng.header.seq++;\n\n        // fill in some points\n        size_t NUM_PTS_PER_BEAM = 1000;\n        rng.ranges.resize(sensor->NumBeams());\n        for (size_t j=0; j<sensor->NumBeams(); j++) {\n            // correctly report ranges in the instrument frame\n            ignition::math::Vector3d beamUnit = sensor->GetBeamUnitVec(j);\n      \t    rng.ranges[j].range.point.x = ranges[j]*beamUnit.X();\n      \t    rng.ranges[j].range.point.y = ranges[j]*beamUnit.Y();\n      \t    rng.ranges[j].range.point.z = ranges[j]*beamUnit.Z();\n      \t    if (sensor->BeamValid(j)) {\n                rng.ranges[j].range_validity = ds_sensor_msgs::Range3D::RANGE_VALID;\n                rng.ranges[j].range_quality = 250;\n            } else {\n                rng.ranges[j].range_validity = ds_sensor_msgs::Range3D::RANGE_INDETERMINANT;\n                rng.ranges[j].range_quality = 10;\n            }\n    \t      rng.ranges[j].range.header.frame_id = frame_name;\n\t          rng.ranges[j].range.header.stamp.sec = current_time.sec;\n      \t    rng.ranges[j].range.header.stamp.nsec = current_time.nsec;\n        }\n        // publish data\n        rng_publisher.publish(rng);\n        ros::spinOnce();\n    }\n\n    last_time = current_time;\n}\n\ndouble dsrosRosDvlSensor::GaussianKernel(double mu, double sigma) {\n  // generation of two normalized uniform random variables\n  double U1 = static_cast<double>(rand_r(&seed)) / static_cast<double>(RAND_MAX);\n  double U2 = static_cast<double>(rand_r(&seed)) / static_cast<double>(RAND_MAX);\n\n  // using Box-Muller transform to obtain a varaible with a standard normal distribution\n  double Z0 = sqrt(-2.0 * ::log(U1)) * cos(2.0*M_PI * U2);\n\n  // scaling\n  Z0 = sigma * Z0 + mu;\n  return Z0;\n}\n\nbool dsrosRosDvlSensor::LoadParameters() {\n\n//loading parameters from the sdf file\n\n  //NAMESPACE\n  if (sdf->HasElement(\"robotNamespace\"))\n  {\n    robot_namespace =  sdf->Get<std::string>(\"robotNamespace\") +\"/\";\n    ROS_INFO_STREAM(\"<robotNamespace> set to: \"<<robot_namespace);\n  }\n  else\n  {\n    std::string scoped_name = sensor->ParentName();\n    std::size_t it = scoped_name.find(\"::\");\n\n    robot_namespace = \"/\" +scoped_name.substr(0,it)+\"/\";\n    ROS_WARN_STREAM(\"missing <robotNamespace>, set to default: \" << robot_namespace);\n  }\n\n  //TOPIC\n  if (sdf->HasElement(\"topicName\"))\n  {\n    topic_name =  sdf->Get<std::string>(\"topicName\");\n    ROS_INFO_STREAM(\"<topicName> set to: \"<<topic_name);\n  }\n  else\n  {\n    topic_name = \"/dvl\";\n    ROS_WARN_STREAM(\"missing <topicName>, set to /namespace/default: \" << topic_name);\n  }\n\n  //RANGES TOPIC\n  if (sdf->HasElement(\"rangesTopicName\"))\n  {\n    ranges_topic_name =  sdf->Get<std::string>(\"rangesTopicName\");\n    ROS_INFO_STREAM(\"<rangesTopicName> set to: \"<<ranges_topic_name);\n  }\n  else\n  {\n    ranges_topic_name = \"/dvl_ranges\";\n    ROS_WARN_STREAM(\"missing <rangesTopicName>, set to /namespace/default: \" << ranges_topic_name);\n  }\n\n  //BODY NAME\n  if (sdf->HasElement(\"frameName\"))\n  {\n    frame_name =  sdf->Get<std::string>(\"frameName\");\n    ROS_INFO_STREAM(\"<frameName> set to: \"<<frame_name);\n  }\n  else\n  {\n    ROS_FATAL(\"missing <frameName>, cannot proceed\");\n    return false;\n  }\n\n  if (sdf->HasElement(\"pointcloudFrame\")) {\n    pointcloud_frame =  sdf->Get<std::string>(\"pointcloudFrame\");\n    ROS_INFO_STREAM(\"<pointcloudFrame> set to: \"<<pointcloud_frame);\n  }\n  else\n  {\n    ROS_FATAL(\"missing <pointcloudFrame>, cannot proceed\");\n    return false;\n\n  }\n\n  //UPDATE RATE\n  if (sdf->HasElement(\"updateRateHZ\"))\n  {\n    update_rate =  sdf->Get<double>(\"updateRateHZ\");\n    ROS_INFO_STREAM(\"<updateRateHZ> set to: \" << update_rate);\n  }\n  else\n  {\n    update_rate = 1.0;\n    ROS_WARN_STREAM(\"missing <updateRateHZ>, set to default: \" << update_rate);\n  }\n\n  //NOISE\n  if (sdf->HasElement(\"gaussianNoiseBeamVel\"))\n  {\n    gaussian_noise_vel =  sdf->Get<double>(\"gaussianNoiseBeamVel\");\n    ROS_INFO_STREAM(\"<gaussianNoiseBeamVel> set to: \" << gaussian_noise_vel);\n  }\n  else\n  {\n    gaussian_noise_vel = 0.0;\n    ROS_WARN_STREAM(\"missing <gaussianNoiseBeamVel>, set to default: \" << gaussian_noise_vel);\n  }\n\n  if (sdf->HasElement(\"gaussianNoiseBeamWtrVel\"))\n  {\n    gaussian_noise_wtr_vel =  sdf->Get<double>(\"gaussianNoiseBeamWtrVel\");\n    ROS_INFO_STREAM(\"<gaussianNoiseBeamWtrVel> set to: \" << gaussian_noise_wtr_vel);\n  }\n  else\n  {\n    gaussian_noise_wtr_vel = 2.0 * gaussian_noise_vel;\n    ROS_WARN_STREAM(\"missing <gaussianNoiseBeamWtrVel>, set to default: \" << gaussian_noise_wtr_vel);\n  }\n\n  if (sdf->HasElement(\"gaussianNoiseBeamRange\"))\n  {\n    gaussian_noise_range =  sdf->Get<double>(\"gaussianNoiseBeamRange\");\n    ROS_INFO_STREAM(\"<gaussianNoiseBeamRange> set to: \" << gaussian_noise_range);\n  }\n  else\n  {\n    gaussian_noise_range = 0.0;\n    ROS_WARN_STREAM(\"missing <gaussianNoiseBeamRange>, set to default: \" << gaussian_noise_range);\n  }\n\n  //WATER TRACKING\n  if (sdf->HasElement(\"enableWaterTrack\"))\n  {\n    water_track_enabled = sdf->Get<bool>(\"enableWaterTrack\");\n    ROS_INFO_STREAM(\"<enableWaterTrack> set to: \" << water_track_enabled);\n  }\n  else\n  {\n    water_track_enabled = false;\n    ROS_WARN_STREAM(\"missing <enableWaterTrack>, set to default: \" << water_track_enabled);\n  }\n\n  if (sdf->HasElement(\"currentProfileCoordMode\") && water_track_enabled)\n  {\n    current_profile_coord_mode = sdf->Get<int>(\"currentProfileCoordMode\");\n    ROS_INFO_STREAM(\"<currentProfileCoordMode> set to: \" << current_profile_coord_mode);\n  }\n  else if (water_track_enabled)\n  {\n    current_profile_coord_mode = ds_sensor_msgs::Adcp::ADCP_COORD_BEAM;\n    ROS_WARN_STREAM(\"missing <currentProfileCoordMode>, set to default: \" << current_profile_coord_mode);\n  }\n\n  if (sdf->HasElement(\"waterTrackBins\") && water_track_enabled)\n  {\n    water_track_bins = sdf->Get<int>(\"waterTrackBins\");\n    ROS_INFO_STREAM(\"<waterTrackBins> set to: \" << water_track_bins);\n  }\n  else if (water_track_enabled)\n  {\n    water_track_bins = 1;\n    ROS_WARN_STREAM(\"missing <waterTrackBins>, set to default: \" << water_track_bins);\n  }\n\n  return true;\n}\n", "meta": {"hexsha": "11673f011f44566bc48867e43affc0e65ec3cc6f", "size": 23466, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dsros_dvl_plugin.cc", "max_stars_repo_name": "Field-Robotics-Lab/ds_sim", "max_stars_repo_head_hexsha": "20fc160e302083aed03f65662abecb75d80cd47a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dsros_dvl_plugin.cc", "max_issues_repo_name": "Field-Robotics-Lab/ds_sim", "max_issues_repo_head_hexsha": "20fc160e302083aed03f65662abecb75d80cd47a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T06:44:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T19:12:02.000Z", "max_forks_repo_path": "src/dsros_dvl_plugin.cc", "max_forks_repo_name": "Field-Robotics-Lab/ds_sim", "max_forks_repo_head_hexsha": "20fc160e302083aed03f65662abecb75d80cd47a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9761499148, "max_line_length": 116, "alphanum_fraction": 0.6223898406, "num_tokens": 5915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418373713166, "lm_q2_score": 0.02333076880848049, "lm_q1q2_score": 0.006132302140906415}}
{"text": "//-*****************************************************************************\n//\n// Copyright (c) 2009-2011,\n//  Sony Pictures Imageworks, Inc. and\n//  Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.\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 Sony Pictures Imageworks, nor\n// Industrial Light & Magic nor the names of their 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\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 <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n\n#include <iostream>\n#include <string>\n\nnamespace client\n{\n    namespace qi = boost::spirit::qi;\n    namespace ascii = boost::spirit::ascii;\n\n    ///////////////////////////////////////////////////////////////////////////////\n    //  Parse roman hundreds (100..900) numerals using the symbol table.\n    //  Notice that the data associated with each slot is the parser's attribute\n    //  (which is passed to attached semantic actions).\n    ///////////////////////////////////////////////////////////////////////////////\n    //[tutorial_roman_hundreds\n    struct hundreds_ : qi::symbols<char, unsigned>\n    {\n        hundreds_()\n        {\n            add\n                (\"C\"    , 100)\n                (\"CC\"   , 200)\n                (\"CCC\"  , 300)\n                (\"CD\"   , 400)\n                (\"D\"    , 500)\n                (\"DC\"   , 600)\n                (\"DCC\"  , 700)\n                (\"DCCC\" , 800)\n                (\"CM\"   , 900)\n            ;\n        }\n\n    } hundreds;\n    //]\n\n    ///////////////////////////////////////////////////////////////////////////////\n    //  Parse roman tens (10..90) numerals using the symbol table.\n    ///////////////////////////////////////////////////////////////////////////////\n    //[tutorial_roman_tens\n    struct tens_ : qi::symbols<char, unsigned>\n    {\n        tens_()\n        {\n            add\n                (\"X\"    , 10)\n                (\"XX\"   , 20)\n                (\"XXX\"  , 30)\n                (\"XL\"   , 40)\n                (\"L\"    , 50)\n                (\"LX\"   , 60)\n                (\"LXX\"  , 70)\n                (\"LXXX\" , 80)\n                (\"XC\"   , 90)\n            ;\n        }\n\n    } tens;\n    //]\n\n    ///////////////////////////////////////////////////////////////////////////////\n    //  Parse roman ones (1..9) numerals using the symbol table.\n    ///////////////////////////////////////////////////////////////////////////////\n    //[tutorial_roman_ones\n    struct ones_ : qi::symbols<char, unsigned>\n    {\n        ones_()\n        {\n            add\n                (\"I\"    , 1)\n                (\"II\"   , 2)\n                (\"III\"  , 3)\n                (\"IV\"   , 4)\n                (\"V\"    , 5)\n                (\"VI\"   , 6)\n                (\"VII\"  , 7)\n                (\"VIII\" , 8)\n                (\"IX\"   , 9)\n            ;\n        }\n\n    } ones;\n    //]\n\n    ///////////////////////////////////////////////////////////////////////////////\n    //  roman (numerals) grammar\n    //\n    //      Note the use of the || operator. The expression\n    //      a || b reads match a or b and in sequence. Try\n    //      defining the roman numerals grammar in YACC or\n    //      PCCTS. Spirit rules! :-)\n    ///////////////////////////////////////////////////////////////////////////////\n    //[tutorial_roman_grammar\n    template <typename Iterator>\n    struct roman : qi::grammar<Iterator, unsigned()>\n    {\n        roman() : roman::base_type(start)\n        {\n            using qi::eps;\n            using qi::lit;\n            using qi::_val;\n            using qi::_1;\n            using ascii::char_;\n\n            start = eps             [_val = 0] >>\n                (\n                    +lit('M')       [_val += 1000]\n                    ||  hundreds    [_val += _1]\n                    ||  tens        [_val += _1]\n                    ||  ones        [_val += _1]\n                )\n            ;\n        }\n\n        qi::rule<Iterator, unsigned()> start;\n    };\n    //]\n}\n\n///////////////////////////////////////////////////////////////////////////////\n//  Main program\n///////////////////////////////////////////////////////////////////////////////\nint\nmain()\n{\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"\\t\\tRoman Numerals Parser\\n\\n\";\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\n    std::cout << \"Type a Roman Numeral ...or [q or Q] to quit\\n\\n\";\n\n    typedef std::string::const_iterator iterator_type;\n    typedef client::roman<iterator_type> roman;\n\n    roman roman_parser; // Our grammar\n\n    std::string str;\n    unsigned result;\n    while ( std::getline( std::cin, str ) )\n    {\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\n            break;\n\n        std::string::const_iterator iter = str.begin();\n        std::string::const_iterator end = str.end();\n        //[tutorial_roman_grammar_parse\n        bool r = parse(iter, end, roman_parser, result);\n\n        if (r && iter == end)\n        {\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing succeeded\\n\";\n            std::cout << \"result = \" << result << std::endl;\n            std::cout << \"-------------------------\\n\";\n        }\n        else\n        {\n            std::string rest(iter, end);\n            std::cout << \"-------------------------\\n\";\n            std::cout << \"Parsing failed\\n\";\n            std::cout << \"stopped at: \\\": \" << rest << \"\\\"\\n\";\n            std::cout << \"-------------------------\\n\";\n        }\n        //]\n    }\n\n    std::cout << \"Bye... :-) \\n\\n\";\n    return 0;\n}\n\n\n", "meta": {"hexsha": "163974f07fd8249f731d9c28b5f6ed42c1e7f856", "size": 7094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/AbcClients/WFObjConvert/Tests/parserTestWorked.cpp", "max_stars_repo_name": "ryu-sw/alembic", "max_stars_repo_head_hexsha": "395450bad88f9d5ed6d20612e9201aac93a5eb54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 921.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T11:04:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:38:34.000Z", "max_issues_repo_path": "examples/AbcClients/WFObjConvert/Tests/parserTestWorked.cpp", "max_issues_repo_name": "ryu-sw/alembic", "max_issues_repo_head_hexsha": "395450bad88f9d5ed6d20612e9201aac93a5eb54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T17:15:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:14:51.000Z", "max_forks_repo_path": "examples/AbcClients/WFObjConvert/Tests/parserTestWorked.cpp", "max_forks_repo_name": "ryu-sw/alembic", "max_forks_repo_head_hexsha": "395450bad88f9d5ed6d20612e9201aac93a5eb54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276.0, "max_forks_repo_forks_event_min_datetime": "2015-01-12T01:34:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T09:19:42.000Z", "avg_line_length": 33.9425837321, "max_line_length": 83, "alphanum_fraction": 0.4321962222, "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.02333076829916378, "lm_q1q2_score": 0.006132302007036676}}
{"text": "#ifndef STAN_LANG_GRAMMARS_TERM_GRAMMAR_DEF_HPP\n#define STAN_LANG_GRAMMARS_TERM_GRAMMAR_DEF_HPP\n\n#include <stan/lang/ast.hpp>\n#include <stan/lang/grammars/expression_grammar.hpp>\n#include <stan/lang/grammars/indexes_grammar.hpp>\n#include <stan/lang/grammars/semantic_actions.hpp>\n#include <stan/lang/grammars/term_grammar.hpp>\n#include <stan/lang/grammars/whitespace_grammar.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <string>\n#include <sstream>\n#include <vector>\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::index_op,\n                          (stan::lang::expression, expr_)\n                          (std::vector<std::vector<stan::lang::expression> >,\n                           dimss_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::index_op_sliced,\n                          (stan::lang::expression, expr_)\n                          (std::vector<stan::lang::idx>, idxs_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::integrate_ode,\n                          (std::string, integration_function_name_)\n                          (std::string, system_function_name_)\n                          (stan::lang::expression, y0_)\n                          (stan::lang::expression, t0_)\n                          (stan::lang::expression, ts_)\n                          (stan::lang::expression, theta_)\n                          (stan::lang::expression, x_)\n                          (stan::lang::expression, x_int_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::integrate_ode_control,\n                          (std::string, integration_function_name_)\n                          (std::string, system_function_name_)\n                          (stan::lang::expression, y0_)\n                          (stan::lang::expression, t0_)\n                          (stan::lang::expression, ts_)\n                          (stan::lang::expression, theta_)\n                          (stan::lang::expression, x_)\n                          (stan::lang::expression, x_int_)\n                          (stan::lang::expression, rel_tol_)\n                          (stan::lang::expression, abs_tol_)\n                          (stan::lang::expression, max_num_steps_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::algebra_solver,\n                           (std::string, system_function_name_)\n                           (stan::lang::expression, y_)\n                           (stan::lang::expression, theta_)\n                           (stan::lang::expression, x_r_)\n                           (stan::lang::expression, x_i_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::algebra_solver_control,\n                           (std::string, system_function_name_)\n                           (stan::lang::expression, y_)\n                           (stan::lang::expression, theta_)\n                           (stan::lang::expression, x_r_)\n                           (stan::lang::expression, x_i_)\n                           (stan::lang::expression, rel_tol_)\n                           (stan::lang::expression, fun_tol_)\n                           (stan::lang::expression, max_num_steps_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::univariate_integral_control,\n                          (std::string, integration_function_name_)\n                          (std::string, system_function_name_)\n                          (stan::lang::expression, t0_)\n                          (stan::lang::expression, t1_)\n                          (stan::lang::expression, theta_)\n                          (stan::lang::expression, x_r_)\n                          (stan::lang::expression, x_i_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::generalOdeModel_control,\n                          (std::string, integration_function_name_)\n                          (std::string, system_function_name_)\n                          (stan::lang::expression, nCmt_)\n                          (stan::lang::expression, time_)\n                          (stan::lang::expression, amt_)\n                          (stan::lang::expression, rate_)\n                          (stan::lang::expression, ii_)\n                          (stan::lang::expression, evid_)\n                          (stan::lang::expression, cmt_)\n                          (stan::lang::expression, addl_)\n                          (stan::lang::expression, ss_)\n                          (stan::lang::expression, pMatrix_)\n                          (stan::lang::expression, biovar_)\n                          (stan::lang::expression, tlag_)\n                          (stan::lang::expression, rel_tol_)\n                          (stan::lang::expression, abs_tol_)\n                          (stan::lang::expression, max_num_steps_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::fun,\n                          (std::string, name_)\n                          (std::vector<stan::lang::expression>, args_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::array_expr,\n                          (std::vector<stan::lang::expression>, args_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::row_vector_expr,\n                          (std::vector<stan::lang::expression>, args_) )\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::int_literal,\n                          (int, val_)\n                          (stan::lang::expr_type, type_))\n\nBOOST_FUSION_ADAPT_STRUCT(stan::lang::double_literal,\n                          (double, val_)\n                          (stan::lang::expr_type, type_) )\n\n\nnamespace stan {\n\n  namespace lang {\n\n    template <typename Iterator>\n    term_grammar<Iterator>::term_grammar(variable_map& var_map,\n                                         std::stringstream& error_msgs,\n                                         expression_grammar<Iterator>& eg)\n      : term_grammar::base_type(term_r),\n        var_map_(var_map),\n        error_msgs_(error_msgs),\n        expression_g(eg),\n        indexes_g(var_map, error_msgs, eg) {\n      using boost::spirit::qi::_1;\n      using boost::spirit::qi::_a;\n      using boost::spirit::qi::_b;\n      using boost::spirit::qi::_c;\n      using boost::spirit::qi::_d;\n      using boost::spirit::qi::char_;\n      using boost::spirit::qi::double_;\n      using boost::spirit::qi::eps;\n      using boost::spirit::qi::int_;\n      using boost::spirit::qi::hold;\n      using boost::spirit::qi::lexeme;\n      using boost::spirit::qi::lit;\n      using boost::spirit::qi::no_skip;\n      using boost::spirit::qi::string;\n      using boost::spirit::qi::_pass;\n      using boost::spirit::qi::_val;\n      using boost::spirit::qi::labels::_r1;\n\n      term_r.name(\"expression\");\n      term_r\n        = (negated_factor_r(_r1)[assign_lhs_f(_val, _1)]\n            >> *((lit('*') > negated_factor_r(_r1)\n                             [multiplication_f(_val, _1,\n                                           boost::phoenix::ref(error_msgs_))])\n                 | (lit('/') > negated_factor_r(_r1)\n                               [division_f(_val, _1,\n                                           boost::phoenix::ref(error_msgs_))])\n                 | (lit('%') > negated_factor_r(_r1)\n                               [modulus_f(_val, _1, _pass,\n                                          boost::phoenix::ref(error_msgs_))])\n                 | (lit('\\\\') > negated_factor_r(_r1)\n                                [left_division_f(_val, _pass, _1,\n                                         boost::phoenix::ref(error_msgs_))])\n                 | (lit(\".*\") > negated_factor_r(_r1)\n                                [elt_multiplication_f(_val, _1,\n                                          boost::phoenix::ref(error_msgs_))])\n                 | (lit(\"./\") > negated_factor_r(_r1)\n                                [elt_division_f(_val, _1,\n                                        boost::phoenix::ref(error_msgs_))])));\n\n      negated_factor_r.name(\"expression\");\n      negated_factor_r\n        = lit('-') >> negated_factor_r(_r1)\n                      [negate_expr_f(_val, _1, _pass,\n                                     boost::phoenix::ref(error_msgs_))]\n        | lit('!') >> negated_factor_r(_r1)\n                      [logical_negate_expr_f(_val, _1,\n                                             boost::phoenix::ref(error_msgs_))]\n        | lit('+') >> negated_factor_r(_r1)[assign_lhs_f(_val, _1)]\n        | exponentiated_factor_r(_r1)[assign_lhs_f(_val, _1)];\n\n      exponentiated_factor_r.name(\"expression\");\n      exponentiated_factor_r\n        = idx_factor_r(_r1)[assign_lhs_f(_val, _1)]\n        >> -(lit('^')\n             > negated_factor_r(_r1)\n               [exponentiation_f(_val, _1, _r1, _pass,\n                                 boost::phoenix::ref(error_msgs_))]);\n\n      idx_factor_r.name(\"expression\");\n      idx_factor_r\n        =  factor_r(_r1)[assign_lhs_f(_val, _1)]\n        > *( ( (+dims_r(_r1))[assign_lhs_f(_a, _1)]\n               > eps\n               [add_expression_dimss_f(_val, _a, _pass,\n                                       boost::phoenix::ref(error_msgs_) )] )\n            | (indexes_g(_r1)[assign_lhs_f(_b, _1)]\n               > eps[add_idxs_f(_val, _b, _pass,\n                              boost::phoenix::ref(error_msgs_))])\n            | (lit(\"'\")\n               > eps[transpose_f(_val, _pass,\n                                 boost::phoenix::ref(error_msgs_))]) );\n\n      integrate_ode_control_r.name(\"expression\");\n      integrate_ode_control_r\n        %= ( (string(\"integrate_ode_rk45\") >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"integrate_ode_bdf\") >> no_skip[!char_(\"a-zA-Z0-9_\")]) )\n        >> lit('(')              // >> allows backtracking to non-control\n        >> identifier_r          // 1) system function name (function only)\n        >> lit(',')\n        >> expression_g(_r1)     // 2) y0\n        >> lit(',')\n        >> expression_g(_r1)     // 3) t0 (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 4) ts (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 5) theta\n        >> lit(',')\n        >> expression_g(_r1)     // 6) x (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 7) x_int (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 8) relative tolerance (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 9) absolute tolerance (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 10) maximum number of steps (data only)\n        > lit(')')\n          [validate_integrate_ode_control_f(_val, boost::phoenix::ref(var_map_),\n                                            _pass,\n                                            boost::phoenix::ref(error_msgs_))];\n\n      integrate_ode_r.name(\"expression\");\n      integrate_ode_r\n        %= ( (string(\"integrate_ode_rk45\") >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"integrate_ode_bdf\") >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"integrate_ode\") >> no_skip[!char_(\"a-zA-Z0-9_\")])\n               [deprecated_integrate_ode_f(boost::phoenix::ref(error_msgs_))] )\n        > lit('(')\n        > identifier_r          // 1) system function name (function only)\n        > lit(',')\n        > expression_g(_r1)     // 2) y0\n        > lit(',')\n        > expression_g(_r1)     // 3) t0 (data only)\n        > lit(',')\n        > expression_g(_r1)     // 4) ts (data only)\n        > lit(',')\n        > expression_g(_r1)     // 5) theta\n        > lit(',')\n        > expression_g(_r1)     // 6) x (data only)\n        > lit(',')\n        > expression_g(_r1)     // 7) x_int (data only)\n        > lit(')')\n          [validate_integrate_ode_f(_val, boost::phoenix::ref(var_map_),\n                                    _pass, boost::phoenix::ref(error_msgs_))];\n\n      algebra_solver_control_r.name(\"expression\");\n      algebra_solver_control_r\n        %= lit(\"algebra_solver\")\n        >> lit('(')\n        >> identifier_r          // 1) system function name (function only)\n        >> lit(',')\n        >> expression_g(_r1)     // 2) y (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 3) theta\n        >> lit(',')\n        >> expression_g(_r1)     // 4) x_r (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 5) x_i (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 6) relative tolerance (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 7) function tolerance (data only)\n        >> lit(',')\n        >> expression_g(_r1)     // 8) maximum number of steps (data only)\n        > lit(')')\n          [validate_algebra_solver_control_f(_val,\n                                             boost::phoenix::ref(var_map_),\n                                             _pass,\n                                             boost::phoenix::ref(error_msgs_))];\n\n      algebra_solver_r.name(\"expression\");\n      algebra_solver_r\n        %= lit(\"algebra_solver\")\n        > lit('(')\n        > identifier_r          // 1) system function name (function only)\n        > lit(',')\n        > expression_g(_r1)     // 2) y (data only)\n        > lit(',')\n        > expression_g(_r1)     // 3) theta\n        > lit(',')\n        > expression_g(_r1)     // 4) x_r (data only)\n        > lit(',')\n        > expression_g(_r1)     // 5) x_i (data only)\n        > lit(')')\n        [validate_algebra_solver_f(_val, boost::phoenix::ref(var_map_),\n                                   _pass, boost::phoenix::ref(error_msgs_))];\n\n      univariate_integral_control_r.name(\"expression\");\n      univariate_integral_control_r\n        %= ( (string(\"univariate_integral_rk45\") >>\n              no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"univariate_integral_bdf\") >>\n                no_skip[!char_(\"a-zA-Z0-9_\")]) )\n        > lit('(')\n        > identifier_r          // 1) system function name (function only)\n        > lit(',')\n        > expression_g(_r1)     // 2) t0 (data only)\n        > lit(',')\n        > expression_g(_r1)     // 2) t1 (data only)\n        > lit(',')\n        > expression_g(_r1)     // 3) theta\n        > lit(',')\n        > expression_g(_r1)     // 4) x_r (data only)\n        > lit(',')\n        > expression_g(_r1)     // 5) x_i (data only)\n        > lit(')')\n        [validate_univariate_integral_control_f(_val,\n                                       boost::phoenix::ref(var_map_),\n                                       _pass,\n                                       boost::phoenix::ref(error_msgs_))];\n\n      generalOdeModel_control_r.name(\"expression\");\n      generalOdeModel_control_r\n        %= ( (string(\"generalOdeModel_bdf\") >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"generalOdeModel_rk45\")\n                >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"mixOde1CptModel_rk45\")\n                >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"mixOde1CptModel_bdf\")\n                >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"mixOde2CptModel_rk45\")\n                >> no_skip[!char_(\"a-zA-Z0-9_\")])\n             | (string(\"mixOde2CptModel_bdf\")\n                >> no_skip[!char_(\"a-zA-Z0-9_\")]))\n        > lit('(')            // >> allows backtracking to non-control\n        > identifier_r        // 1) system function name (function only)\n        > lit(',')\n        > expression_g(_r1)   // 2) nCmt\n        > lit(',')\n        > expression_g(_r1)   // 3) time\n        > lit(',')\n        > expression_g(_r1)   // 4) amt\n        > lit(',')\n        > expression_g(_r1)   // 5) rate\n        > lit(',')\n        > expression_g(_r1)   // 6) ii\n        > lit(',')\n        > expression_g(_r1)   // 7) evid (data only)\n        > lit(',')\n        > expression_g(_r1)   // 8) cmt (data only)\n        > lit(',')\n        > expression_g(_r1)   // 9) addl (data only)\n        > lit(',')\n        > expression_g(_r1)   // 10) ss (data only)\n        > lit(',')\n        > expression_g(_r1)   // 11) pMatrix\n        > lit(',')\n        > expression_g(_r1)   // 12) biovar\n        > lit(',')\n        > expression_g(_r1)   // 13) tlag\n        > lit(',')\n        > expression_g(_r1)   // 14) relative tolerance (data only)\n        > lit(',')\n        > expression_g(_r1)   // 15) absolute tolerance (data only)\n        > lit(',')\n        > expression_g(_r1)   // 16) maximum number of steps\n        > lit(')')\n        [validate_generalOdeModel_control_f(_val,\n                               boost::phoenix::ref(var_map_), _pass,\n                               boost::phoenix::ref(error_msgs_))];\n\n      factor_r.name(\"expression\");\n      factor_r =\n        integrate_ode_control_r(_r1)[assign_lhs_f(_val, _1)]\n        | integrate_ode_r(_r1)[assign_lhs_f(_val, _1)]\n        | algebra_solver_control_r(_r1)[assign_lhs_f(_val, _1)]\n        | algebra_solver_r(_r1)[assign_lhs_f(_val, _1)]\n        | univariate_integral_control_r(_r1)[assign_lhs_f(_val, _1)]\n        | generalOdeModel_control_r(_r1)[assign_lhs_f(_val, _1)]\n        | (fun_r(_r1)[assign_lhs_f(_b, _1)]\n           > eps[set_fun_type_named_f(_val, _b, _r1, _pass,\n                                      boost::phoenix::ref(var_map_),\n                                      boost::phoenix::ref(error_msgs_))])\n        | (variable_r[assign_lhs_f(_a, _1)]\n           > eps[set_var_type_f(_a, _val, boost::phoenix::ref(var_map_),\n                                boost::phoenix::ref(error_msgs_),\n                                _pass)])\n        | int_literal_r[assign_lhs_f(_val, _1)]\n        | double_literal_r[assign_lhs_f(_val, _1)]\n        | (array_expr_r(_r1)[assign_lhs_f(_c, _1)]\n           > eps[infer_array_expr_type_f(_val, _c, _r1, _pass,\n                                       boost::phoenix::ref(var_map_),\n                                       boost::phoenix::ref(error_msgs_))])\n        | (vec_expr_r(_r1)[assign_lhs_f(_d, _1)]\n           > eps[infer_vec_or_matrix_expr_type_f(_val, _d, _r1, _pass,\n                                     boost::phoenix::ref(var_map_),\n                                     boost::phoenix::ref(error_msgs_))])\n        | (lit('(')\n           > expression_g(_r1)[assign_lhs_f(_val, _1)]\n           > lit(')'));\n\n      int_literal_r.name(\"integer literal\");\n      int_literal_r\n        %= int_\n        >> !(lit('.') | lit('e') | lit('E'));\n\n      double_literal_r.name(\"real literal\");\n      double_literal_r\n        %= double_;\n\n      fun_r.name(\"function and argument expressions\");\n      fun_r\n        %= (hold[identifier_r[is_prob_fun_f(_1, _pass)]]\n            >> &lit('(')\n            > prob_args_r(_r1))\n        | (identifier_r >> args_r(_r1));\n\n      identifier_r.name(\"identifier\");\n      identifier_r\n        %= lexeme[char_(\"a-zA-Z\")\n                  >> *char_(\"a-zA-Z0-9_.\")];\n\n      prob_args_r.name(\"probability function argument\");\n      prob_args_r\n        %= (lit('(') >> lit(')'))\n        | hold[lit('(')\n               >> expression_g(_r1)\n               >> lit(')')]\n        | (lit('(')\n           >> expression_g(_r1)\n           >> (lit(',')\n               [require_vbar_f(_pass, boost::phoenix::ref(error_msgs_))]\n               | (eps > lit('|')))\n           >> (expression_g(_r1) % ',')\n           >> lit(')'));\n\n      args_r.name(\"function arguments\");\n      args_r\n        %= (lit('(') >> lit(')'))\n        | (lit('(') >> (expression_g(_r1) % ',') >> lit(')'));\n\n      dim_r.name(\"array dimension (integer expression)\");\n      dim_r\n        %= expression_g(_r1)\n        >> eps[validate_int_expr_silent_f(_val, _pass)];\n\n      dims_r.name(\"array dimensions\");\n      dims_r\n        %= lit('[')\n        >> (dim_r(_r1)\n           % ',' )\n        >> lit(']');\n\n      variable_r.name(\"variable name\");\n      variable_r\n        %= identifier_r\n        > !lit('(');    // negative lookahead to prevent failure in\n                        // fun to try to evaluate as variable [cleaner\n                        // error msgs]\n\n      array_expr_r.name(\"array expression\");\n      array_expr_r\n        %=  lit('{')\n        >> expression_g(_r1) % ','\n        >> lit('}');\n\n      vec_expr_r.name(\"row vector or matrix expression\");\n      vec_expr_r\n        %=  lit('[')\n        >> expression_g(_r1) % ','\n        >> lit(']');\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "ce07aa5401211e7747e720566385924d6348aee4", "size": 19947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/src/stan/lang/grammars/term_grammar_def.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/src/stan/lang/grammars/term_grammar_def.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/src/stan/lang/grammars/term_grammar_def.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": 42.3503184713, "max_line_length": 80, "alphanum_fraction": 0.4850353437, "num_tokens": 4868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943704494217, "lm_q2_score": 0.019719127495253782, "lm_q1q2_score": 0.006126621902949756}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include \"DataFactory.h\"\n\n#include <boost/python/extract.hpp>\n#include <boost/scoped_array.hpp>\n\n#include <exception>\n#include <iostream>\n#include <fstream>\n\n\n#ifdef ESYS_HAVE_NETCDF\n #ifdef NETCDF4\n  #include <ncDim.h>\n  #include <ncVar.h>\n  #include <ncFile.h>\n  \n #include \"NCHelper.h\"  \n  \n #else\n  #include <netcdfcpp.h>\n #endif\n#endif\n\nnamespace bp = boost::python;\n#ifdef NETCDF4\nusing namespace netCDF;\n#endif\n\n\nnamespace escript {\n\nData Scalar(double value, const FunctionSpace& what, bool expanded)\n{\n    // an empty shape is a scalar\n    DataTypes::ShapeType shape;\n    return Data(value, shape, what, expanded);\n}\n\nData Scalar(DataTypes::cplx_t value, const FunctionSpace& what, bool expanded)\n{\n    // an empty shape is a scalar\n    DataTypes::ShapeType shape;\n    return Data(value, shape, what, expanded);\n}\n\nData\nScalarFromObj(boost::python::object o,\n\tconst FunctionSpace& what,\n\tbool expanded)\n{\n    // check for real first\n    try {\n        double v = bp::extract<double>(o);\n        return Scalar(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }    \n    // check for real first\n    try {\n        DataTypes::cplx_t v = bp::extract<DataTypes::cplx_t>(o);\n        return Scalar(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }    \n    throw DataException(\"Can not make a Scalar from a non-scalar value.\");\n}\n\nData Vector(double value, const FunctionSpace& what, bool expanded)\n{\n    DataTypes::ShapeType shape(1, what.getDomain()->getDim());\n    return Data(value, shape, what, expanded);\n}\n\nData VectorFromObj(bp::object o, const FunctionSpace& what, bool expanded)\n{    \n    // first try to get a double and route it to the other method\n    try {\n        double v = bp::extract<double>(o);\n        return Vector(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }\n    DataTypes::ShapeType shape(1, what.getDomain()->getDim());\n    Data d(o, what, expanded);\n    if (d.getDataPointShape() != shape) {\n        throw DataException(\"VectorFromObj: Shape of vector passed to function\"\n               \" does not match the dimension of the domain. \");\n    }\n    return d;\n}\n\nData Tensor(double value, const FunctionSpace& what, bool expanded)\n{\n    DataTypes::ShapeType shape(2, what.getDomain()->getDim());\n    return Data(value, shape, what, expanded);\n}\n\nData TensorC(DataTypes::cplx_t value, const FunctionSpace& what, bool expanded)\n{\n    DataTypes::ShapeType shape(2, what.getDomain()->getDim());\n    return Data(value, shape, what, expanded);\n}\n\n// We need to take some care here because this signature trumps the other one from boost's point of view\nData TensorFromObj(bp::object o, const FunctionSpace& what, bool expanded)\n{\n    // first try to get a double and route it to the other method\n    try {\n        double v = bp::extract<double>(o);\n        return Tensor(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }\n    // now try to get a complex and route to scalar factory\n    try {\n        DataTypes::cplx_t v = bp::extract<DataTypes::cplx_t>(o);\n        return TensorC(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }    \n    DataTypes::ShapeType shape(2, what.getDomain()->getDim());\n    Data d(o, what, expanded);\n    if (d.getDataPointShape() != shape) {\n        throw DataException(\"TensorFromObj: Shape of tensor passed to function\"\n               \" does not match the dimension of the domain.\");\n    }\n    return d;\n}\n\nData Tensor3(double value, const FunctionSpace& what, bool expanded)\n{\n    DataTypes::ShapeType shape(3, what.getDomain()->getDim());\n    return Data(value, shape, what, expanded);\n}\n\nData Tensor3C(DataTypes::cplx_t  value, const FunctionSpace& what, bool expanded)\n{\n    DataTypes::ShapeType shape(3, what.getDomain()->getDim());\n    return Data(value, shape, what, expanded);\n}\n\n\nData Tensor3FromObj(bp::object o, const FunctionSpace& what, bool expanded)\n{\n    // first try to get a double and route it to the other method\n    try {\n        double v = bp::extract<double>(o);\n        return Tensor3(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }\n    // first try to get a complex and route it to the other method\n    try {\n        DataTypes::cplx_t v = bp::extract<DataTypes::cplx_t>(o);\n        return Tensor3C(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }    \n    DataTypes::ShapeType shape(3, what.getDomain()->getDim());\n    Data d(o, what, expanded);\n    if (d.getDataPointShape() != shape) {\n        throw DataException(\"Tensor3FromObj: Shape of tensor passed to \"\n                \"function does not match the dimension of the domain.\");\n    }\n    return d;\n}\n\nData Tensor4(double value, const FunctionSpace& what, bool expanded)\n{\n    DataTypes::ShapeType shape(4, what.getDomain()->getDim());\n    return Data(value, shape, what, expanded);\n}\n\nData Tensor4C(DataTypes::cplx_t value, const FunctionSpace& what, bool expanded)\n{\n    DataTypes::ShapeType shape(4, what.getDomain()->getDim());\n    return Data(value, shape, what, expanded);\n}\n\n\nData Tensor4FromObj(bp::object o, const FunctionSpace& what, bool expanded)\n{\n    // first try to get a double and route it to the other method\n    try {\n        double v = bp::extract<double>(o);\n        return Tensor4(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }\n    // first try to get a double and route it to the other method\n    try {\n        DataTypes::cplx_t v = bp::extract<DataTypes::cplx_t>(o);\n        return Tensor4C(v, what, expanded);\n    } catch(...) {\n        PyErr_Clear();\n    }    \n    DataTypes::ShapeType shape(4, what.getDomain()->getDim());\n    Data d(o, what, expanded);\n    if (d.getDataPointShape() != shape) {\n        throw DataException(\"VectorFromObj: Shape of tensor passed to function\"\n               \" does not match the dimension of the domain.\");\n    }\n    return d;\n}\n\n#ifdef NETCDF4\n\n// Warning: at time of writing, calls to ncVar::getVar are not range checked as was done under the previous API\n// we want to see if it works first, but at some stage that should be tightened up\n\nData load(const std::string fileName, const AbstractDomain& domain)\n{\n#ifdef ESYS_HAVE_NETCDF\n    JMPI mpiInfo(domain.getMPI());\n    const std::string newFileName(mpiInfo->appendRankToFileName(fileName));\n    NcFile dataFile;\n    if (!openNcFile(dataFile, newFileName))\n    {\n        throw DataException(\"load: opening of netCDF file for input failed.\");\n    }\n    Data out;\n    int error = 0;\n    std::string msg;\n    try {\n        int line=0;\n        int rank=-1;\n        int type=-1;\n        int function_space_type=0;  // =0 should not actually be used but we keep compiler happy\n        try\n        {\n            // recover function space            \n            NcGroupAtt fst=dataFile.getAtt(\"function_space_type\");\n            if (fst.getAttLength()!=1)\n            {\n                throw DataException(\"load: oversize attribute function_space_type\");\n            }\n            fst.getValues(&function_space_type);\n        }\n        catch (exceptions::NcException* e)\n        {\n                throw DataException(\"load: cannot recover function_space_type attribute from escript netCDF file.\");    \n        }\n        line=0;\n        if (!domain.isValidFunctionSpaceType(function_space_type))\n        {       // jump to outer catch\n            throw DataException(\"load: function space type code in netCDF file is invalid for given domain.\");\n        }\n        FunctionSpace function_space=FunctionSpace(domain.getPtr(), function_space_type);\n        try\n        {\n            line++;\n            NcGroupAtt rt=dataFile.getAtt(\"rank\");\n            if (rt.getAttLength()!=1)\n            {\n                throw DataException(\"load: oversize attribute rank\");\n            }\n            rt.getValues(&rank);\n            line++;\n            if (rank<0 || rank>DataTypes::maxRank)\n                throw DataException(\"load: rank in escript netCDF file is greater than maximum rank.\");            \n            // recover type attribute\n            //   looks like we can have either \"type\" or \"typeid\"\n            NcGroupAtt tatt=dataFile.getAtt(\"type\");\n            if (!tatt.isNull())\n            {\n                std::string type_str;\n                tatt.getValues(&type_str);\n                if (type_str==\"constant\")\n                {\n                    type = 0;\n                }\n                else if (type_str==\"tagged\")\n                {\n                    type = 1;\n                }\n                else // if (type_str==\"expanded\")\n                {\n                    type = 2;\n                }\n            }\n            else \n            {\n                tatt=dataFile.getAtt(\"type_id\");\n                if (!tatt.isNull())\n                {\n                    if (tatt.getAttLength()>1)\n                    {\n                        throw DataException(\"load: oversize attribute type_id\");\n                    }\n                    //type=dataFile.getAtt(\"type_id\").as_int(0);\n                    tatt.getValues(&type);\n                }\n                else\n                {\n                    throw DataException(\"load: cannot recover type attribute from escript netCDF file.\");\n                }\n            }\n        }\n        catch (exceptions::NcException* e)\n        {\n            switch (line)\n            {\n            case 1: throw DataException(\"load: cannot recover rank attribute from escript netCDF file.\");\n            default:\n                throw DataException(\"load: unspecified error.\");\n            }\n        }\n        // recover dimension\n        int ndims=dataFile.getDimCount();\n        int ntags =0 , num_samples =0 , num_data_points_per_sample =0, d=0, len_data_point=1;\n        NcDim d_dim, tags_dim, num_samples_dim, num_data_points_per_sample_dim;\n        /* recover shape */\n        DataTypes::ShapeType shape;\n//        long dims[DataTypes::maxRank+2];\n        if (rank>0) {\n            if ((d_dim=dataFile.getDim(\"d0\")).isNull() )\n                throw DataException(\"load: unable to recover d0 from netCDF file.\");\n            d=d_dim.getSize();\n            shape.push_back(d);\n//             dims[0]=d;\n            len_data_point*=d;\n        }\n        if (rank>1) {\n            if ((d_dim=dataFile.getDim(\"d1\")).isNull() )\n                throw DataException(\"load: unable to recover d1 from netCDF file.\");\n            d=d_dim.getSize();\n            shape.push_back(d);\n//             dims[1]=d;\n            len_data_point*=d;\n        }\n        if (rank>2) {\n            if ((d_dim=dataFile.getDim(\"d2\")).isNull() )\n                throw DataException(\"load: unable to recover d2 from netCDF file.\");\n            d=d_dim.getSize();\n            shape.push_back(d);\n//             dims[2]=d;\n            len_data_point*=d;\n        }\n        if (rank>3) {\n            if ((d_dim=dataFile.getDim(\"d3\")).isNull() )\n                throw DataException(\"load: unable to recover d3 from netCDF file.\");\n            d=d_dim.getSize();\n            shape.push_back(d);\n//             dims[3]=d;\n            len_data_point*=d;\n        }\n\n        NcVar var, ids_var, tags_var;\n        if (type == 0) {\n            // constant data\n            if ( ! ( (ndims == rank && rank >0) || ( ndims ==1 && rank == 0 ) ) )\n                throw DataException(\"load: illegal number of dimensions for constant data in netCDF file.\");\n            if (rank == 0) {\n                if ((d_dim=dataFile.getDim(\"l\")).isNull() )\n                    throw DataException(\"load: unable to recover d0 for scalar constant data in netCDF file.\");\n                int d0 = d_dim.getSize();\n                if (d0 != 1)\n                    throw DataException(\"load: d0 is expected to be one for scalar constant data in netCDF file.\");\n//                 dims[0]=1;\n            }\n            out=Data(0,shape,function_space,false);\n            if ((var = dataFile.getVar(\"data\")).isNull())\n                throw DataException(\"load: unable to find data in netCDF file.\");\n            var.getVar(&(out.getDataAtOffsetRW(out.getDataOffset(0,0), static_cast<DataTypes::real_t>(0))));\n        } else if (type == 1) { \n            // tagged data\n            if ( ! (ndims == rank + 1) )\n                throw DataException(\"load: illegal number of dimensions for tagged data in netCDF file.\");\n            if ((tags_dim=dataFile.getDim(\"num_tags\")).isNull() )\n                throw DataException(\"load: unable to recover number of tags from netCDF file.\");\n            ntags=tags_dim.getSize();\n//             dims[rank]=ntags;\n            std::vector<int> tags(ntags);\n            if (( tags_var = dataFile.getVar(\"tags\")).isNull() )\n                throw DataException(\"load: unable to find tags in netCDF file.\");\n            // oversize could be a problem here?\n            tags_var.getVar(&tags[0]);\n\n            // A) create a DataTagged dt\n            // B) Read data from file\n            // C) copy default value into dt\n            // D) copy tagged values into dt\n            // E) create a new Data based on dt\n\n            NcVar var1;\n            DataTypes::RealVectorType data1(len_data_point * ntags, 0., len_data_point * ntags);\n            if ((var1 = dataFile.getVar(\"data\")).isNull())\n                throw DataException(\"load: unable to find data in netCDF file.\");\n            var1.getVar(&(data1[0])); \n            DataTagged* dt=new DataTagged(function_space, shape, &tags[0], data1);\n            out=Data(dt);\n        } else if (type == 2) {\n            // expanded data\n            if ( ! (ndims == rank + 2) )\n                throw DataException(\"load: illegal number of dimensions for expanded data in netCDF file.\");\n            if ((num_samples_dim = dataFile.getDim(\"num_samples\")).isNull() )\n                throw DataException(\"load: unable to recover number of samples from netCDF file.\");\n            num_samples = num_samples_dim.getSize();\n            if ((num_data_points_per_sample_dim = dataFile.getDim(\"num_data_points_per_sample\")).isNull() )\n                throw DataException(\"load: unable to recover number of data points per sample from netCDF file.\");\n            num_data_points_per_sample=num_data_points_per_sample_dim.getSize();\n            // check shape:\n            if ( ! (num_samples == function_space.getNumSamples() && num_data_points_per_sample == function_space.getNumDataPointsPerSample()) )\n                throw DataException(\"load: data sample layout of file does not match data layout of function space.\");\n            if (num_samples==0) {\n                out = Data(0,shape,function_space,true);\n            } else {\n                // get ids\n                if (( ids_var = dataFile.getVar(\"id\")).isNull() )\n                    throw DataException(\"load: unable to find reference ids in netCDF file.\");\n                const DataTypes::dim_t* ids_p=function_space.borrowSampleReferenceIDs();\n                std::vector<DataTypes::dim_t> ids_of_nc(num_samples);\n                // oversize could be a problem here\n                ids_var.getVar(&ids_of_nc[0]);\n                // check order:\n                int failed=-1, local_failed=-1, i;\n#pragma omp parallel private(local_failed)\n                {\n                    local_failed=-1;\n#pragma omp for private(i) schedule(static)\n                    for (i=0; i < num_samples; ++i) {\n                        if (ids_of_nc[i]!=ids_p[i]) local_failed=i;\n                    }\n#pragma omp critical\n                    if (local_failed>=0) failed = local_failed;\n                }\n                // get the data:\n//                 dims[rank]=num_data_points_per_sample;\n//                 dims[rank+1]=num_samples;\n                out=Data(0,shape,function_space,true);\n                if ((var = dataFile.getVar(\"data\")).isNull())\n                    throw DataException(\"load: unable to find data in netCDF file.\");\n                var.getVar(&(out.getDataAtOffsetRW(out.getDataOffset(0,0), static_cast<DataTypes::real_t>(0))));\n                if (failed >= 0) {\n                    try {\n                        std::cout << \"Information - load: start reordering data from netCDF file \" << fileName << std::endl;\n                        out.borrowData()->reorderByReferenceIDs(&ids_of_nc[0]);\n                    } catch (std::exception&) {\n                        throw DataException(\"load: unable to reorder data in netCDF file.\");\n                    }\n                }\n            }\n        } else {\n            throw DataException(\"load: unknown escript data type in netCDF file.\");\n        }\n    } catch (DataException& e) {\n        error=1;\n        msg=e.what();\n    }\n    int gerror = error;\n    checkResult(error, gerror, mpiInfo);\n    if (gerror > 0) {\n        char* gmsg;\n        shipString(msg.c_str(), &gmsg, mpiInfo->comm);\n        throw DataException(gmsg);\n    }\n    return out;\n#else\n    throw DataException(\"load: not compiled with netCDF. Please contact your\"\n                        \" installation manager.\");\n#endif // ESYS_HAVE_NETCDF\n}\n\n#else\n\nData load(const std::string fileName, const AbstractDomain& domain)\n{\n#ifdef ESYS_HAVE_NETCDF\n    NcAtt *type_att, *rank_att, *function_space_type_att;\n    // netCDF error handler\n    NcError err(NcError::silent_nonfatal);\n    JMPI mpiInfo(domain.getMPI());\n    const std::string newFileName(mpiInfo->appendRankToFileName(fileName));\n    NcFile dataFile(newFileName.c_str(), NcFile::ReadOnly);\n    Data out;\n    int error = 0;\n    std::string msg;\n    try {\n        if (!dataFile.is_valid())\n            throw DataException(\"load: opening of netCDF file for input failed.\");\n       // recover function space\n        if (! (function_space_type_att=dataFile.get_att(\"function_space_type\")) )\n            throw DataException(\"load: cannot recover function_space_type attribute from escript netCDF file.\");\n        int function_space_type = function_space_type_att->as_int(0);\n        delete function_space_type_att;\n        // test if function space id is valid and create function space instance\n        if (!domain.isValidFunctionSpaceType(function_space_type)) \n            throw DataException(\"load: function space type code in netCDF file is invalid for given domain.\");\n        FunctionSpace function_space=FunctionSpace(domain.getPtr(), function_space_type);\n        // recover rank\n        if (! (rank_att=dataFile.get_att(\"rank\")) )\n            throw DataException(\"load: cannot recover rank attribute from escript netCDF file.\");\n        int rank = rank_att->as_int(0);\n        delete rank_att;\n        if (rank<0 || rank>DataTypes::maxRank)\n            throw DataException(\"load: rank in escript netCDF file is greater than maximum rank.\");\n        // recover type attribute\n        int type=-1;\n        if ((type_att=dataFile.get_att(\"type\")) ) {\n            boost::scoped_array<char> type_str(type_att->as_string(0));\n            if (strncmp(type_str.get(), \"constant\", strlen(\"constant\")) == 0 ) {\n                type = 0;\n            } else if (strncmp(type_str.get(), \"tagged\", strlen(\"tagged\")) == 0 ) {\n                type = 1;\n            } else if (strncmp(type_str.get(), \"expanded\", strlen(\"expanded\")) == 0 ) {\n                type = 2;\n            }\n        } else {\n            if (! (type_att=dataFile.get_att(\"type_id\")) )\n                throw DataException(\"load: cannot recover type attribute from escript netCDF file.\");\n            type=type_att->as_int(0);\n        }\n        delete type_att;\n\n        // recover dimension\n        int ndims=dataFile.num_dims();\n        int ntags =0 , num_samples =0 , num_data_points_per_sample =0, d=0, len_data_point=1;\n        NcDim *d_dim, *tags_dim, *num_samples_dim, *num_data_points_per_sample_dim;\n        /* recover shape */\n        DataTypes::ShapeType shape;\n        long dims[DataTypes::maxRank+2];\n        if (rank>0) {\n            if (! (d_dim=dataFile.get_dim(\"d0\")) )\n                throw DataException(\"load: unable to recover d0 from netCDF file.\");\n            d=d_dim->size();\n            shape.push_back(d);\n            dims[0]=d;\n            len_data_point*=d;\n        }\n        if (rank>1) {\n            if (! (d_dim=dataFile.get_dim(\"d1\")) )\n                throw DataException(\"load: unable to recover d1 from netCDF file.\");\n            d=d_dim->size();\n            shape.push_back(d);\n            dims[1]=d;\n            len_data_point*=d;\n        }\n        if (rank>2) {\n            if (! (d_dim=dataFile.get_dim(\"d2\")) )\n                throw DataException(\"load: unable to recover d2 from netCDF file.\");\n            d=d_dim->size();\n            shape.push_back(d);\n            dims[2]=d;\n            len_data_point*=d;\n        }\n        if (rank>3) {\n            if (! (d_dim=dataFile.get_dim(\"d3\")) )\n                throw DataException(\"load: unable to recover d3 from netCDF file.\");\n            d=d_dim->size();\n            shape.push_back(d);\n            dims[3]=d;\n            len_data_point*=d;\n        }\n\n        NcVar *var, *ids_var, *tags_var;\n        if (type == 0) {\n            // constant data\n            if ( ! ( (ndims == rank && rank >0) || ( ndims ==1 && rank == 0 ) ) )\n                throw DataException(\"load: illegal number of dimensions for constant data in netCDF file.\");\n            if (rank == 0) {\n                if (! (d_dim=dataFile.get_dim(\"l\")) )\n                    throw DataException(\"load: unable to recover d0 for scalar constant data in netCDF file.\");\n                int d0 = d_dim->size();\n                if (d0 != 1)\n                    throw DataException(\"load: d0 is expected to be one for scalar constant data in netCDF file.\");\n                dims[0]=1;\n            }\n            out=Data(0,shape,function_space,false);\n            if (!(var = dataFile.get_var(\"data\")))\n                throw DataException(\"load: unable to find data in netCDF file.\");\n            if (! var->get(&(out.getDataAtOffsetRW(out.getDataOffset(0,0), static_cast<DataTypes::real_t>(0))), dims) ) \n                throw DataException(\"load: unable to recover data from netCDF file.\");\n        } else if (type == 1) { \n            // tagged data\n            if ( ! (ndims == rank + 1) )\n                throw DataException(\"load: illegal number of dimensions for tagged data in netCDF file.\");\n            if (! (tags_dim=dataFile.get_dim(\"num_tags\")) )\n                throw DataException(\"load: unable to recover number of tags from netCDF file.\");\n            ntags=tags_dim->size();\n            dims[rank]=ntags;\n            std::vector<int> tags(ntags);\n            if (! ( tags_var = dataFile.get_var(\"tags\")) )\n                throw DataException(\"load: unable to find tags in netCDF file.\");\n            if (! tags_var->get(&tags[0], ntags) ) \n                throw DataException(\"load: unable to recover tags from netCDF file.\");\n\n            // A) create a DataTagged dt\n            // B) Read data from file\n            // C) copy default value into dt\n            // D) copy tagged values into dt\n            // E) create a new Data based on dt\n\n            NcVar* var1;\n            DataTypes::RealVectorType data1(len_data_point * ntags, 0., len_data_point * ntags);\n            if (!(var1 = dataFile.get_var(\"data\")))\n                throw DataException(\"load: unable to find data in netCDF file.\");\n            if (! var1->get(&(data1[0]), dims) ) \n                throw DataException(\"load: unable to recover data from netCDF file.\");\n            DataTagged* dt=new DataTagged(function_space, shape, &tags[0], data1);\n            out=Data(dt);\n        } else if (type == 2) {\n            // expanded data\n            if ( ! (ndims == rank + 2) )\n                throw DataException(\"load: illegal number of dimensions for expanded data in netCDF file.\");\n            if ( ! (num_samples_dim = dataFile.get_dim(\"num_samples\") ) )\n                throw DataException(\"load: unable to recover number of samples from netCDF file.\");\n            num_samples = num_samples_dim->size();\n            if ( ! (num_data_points_per_sample_dim = dataFile.get_dim(\"num_data_points_per_sample\") ) )\n                throw DataException(\"load: unable to recover number of data points per sample from netCDF file.\");\n            num_data_points_per_sample=num_data_points_per_sample_dim->size();\n            // check shape:\n            if ( ! (num_samples == function_space.getNumSamples() && num_data_points_per_sample == function_space.getNumDataPointsPerSample()) )\n                throw DataException(\"load: data sample layout of file does not match data layout of function space.\");\n            if (num_samples==0) {\n                out = Data(0,shape,function_space,true);\n            } else {\n                // get ids\n                if (! ( ids_var = dataFile.get_var(\"id\")) )\n                    throw DataException(\"load: unable to find reference ids in netCDF file.\");\n                const DataTypes::dim_t* ids_p=function_space.borrowSampleReferenceIDs();\n                std::vector<DataTypes::dim_t> ids_of_nc(num_samples);\n                if (! ids_var->get(&ids_of_nc[0], (long) num_samples) ) \n                    throw DataException(\"load: unable to recover ids from netCDF file.\");\n                // check order:\n                int failed=-1, local_failed=-1, i;\n#pragma omp parallel private(local_failed)\n                {\n                    local_failed=-1;\n#pragma omp for private(i) schedule(static)\n                    for (i=0; i < num_samples; ++i) {\n                        if (ids_of_nc[i]!=ids_p[i]) local_failed=i;\n                    }\n#pragma omp critical\n                    if (local_failed>=0) failed = local_failed;\n                }\n                // get the data:\n                dims[rank]=num_data_points_per_sample;\n                dims[rank+1]=num_samples;\n                out=Data(0,shape,function_space,true);\n                if (!(var = dataFile.get_var(\"data\")))\n                    throw DataException(\"load: unable to find data in netCDF file.\");\n                if (! var->get(&(out.getDataAtOffsetRW(out.getDataOffset(0,0), static_cast<DataTypes::real_t>(0))), dims)) \n                    throw DataException(\"load: unable to recover data from netCDF file.\");\n                if (failed >= 0) {\n                    try {\n                        std::cout << \"Information - load: start reordering data from netCDF file \" << fileName << std::endl;\n                        out.borrowData()->reorderByReferenceIDs(&ids_of_nc[0]);\n                    } catch (std::exception&) {\n                        throw DataException(\"load: unable to reorder data in netCDF file.\");\n                    }\n                }\n            }\n        } else {\n            throw DataException(\"load: unknown escript data type in netCDF file.\");\n        }\n    } catch (DataException& e) {\n        error=1;\n        msg=e.what();\n    }\n    int gerror = error;\n    checkResult(error, gerror, mpiInfo);\n    if (gerror > 0) {\n        char* gmsg;\n        shipString(msg.c_str(), &gmsg, mpiInfo->comm);\n        throw DataException(gmsg);\n    }\n    return out;\n#else\n    throw DataException(\"load: not compiled with netCDF. Please contact your\"\n                        \" installation manager.\");\n#endif // ESYS_HAVE_NETCDF\n}\n\n#endif\n\nbool loadConfigured()\n{\n#ifdef ESYS_HAVE_NETCDF\n    return true;\n#else\n    return false;\n#endif\n}\n\nData convertToData(const bp::object& value, const FunctionSpace& what) \n{\n    // first we try to extract a Data object from value \n    bp::extract<Data> value_data(value);\n    if (value_data.check()) {\n        Data extracted_data=value_data();\n        if (extracted_data.isEmpty()) {\n            return extracted_data;\n        } else {\n            return Data(extracted_data,what);\n        }\n    } else {\n        return Data(value,what,false);\n    }\n}\n\n}  // end of namespace\n\n", "meta": {"hexsha": "946d47e68090480f79b4097ffc61bc5c394793b5", "size": 28334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "escriptcore/src/DataFactory.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "escriptcore/src/DataFactory.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "escriptcore/src/DataFactory.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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.4075104312, "max_line_length": 144, "alphanum_fraction": 0.5650455283, "num_tokens": 6429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271165, "lm_q2_score": 0.025565214572891078, "lm_q1q2_score": 0.006119017422186556}}
{"text": "/*\n * Copyright (c) 2017, <copyright holder> <email>\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 <organization> 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 <copyright holder> <email> ''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 <copyright holder> <email> 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 \"extractgeometryfeature.h\"\n#include <boost/graph/graph_concepts.hpp>\n\n\n\nnamespace geomeasurer {\n  \nkeypoint::keypoint()\n{\n\n}\nkeypoint::keypoint(const int & index_, const double& score_)\n{\nindex=index_;\nscore=score_;\n}\n\nbool keypoint::compare(const keypoint& kp1, const keypoint& kp2)\n{\n    if(kp1.score>kp2.score)\n     {\n       return true;\n    }\n    else{\n      return false;\n    }     \n}\n\n  \nextractGeometryFeature::extractGeometryFeature()\n{\n}\n \nextractGeometryFeature::extractGeometryFeature(const PointCloud& pcd)\n{\n   candiate_pcd=pcd;\n}\n\nextractGeometryFeature::extractGeometryFeature(const sensor::rangeData& ranges_data)\n{\n  candiate_pcd=sensor::fromRangeData(ranges_data);\n  ranges=ranges_data;\n}\n\nvoid extractGeometryFeature::setSlideWindowSizes(const int& slide_window_sizes_)\n{\n  slide_window_sizes=slide_window_sizes_;\n}\n\nvoid extractGeometryFeature::setRegionGrowRadius(const double& region_grow_radius_)\n{\n  region_grow_radius=region_grow_radius_;\n}\n\nvoid extractGeometryFeature::setClusterMinSize(const uint32_t& cluster_min_size_)\n{\n  cluster_min_size=cluster_min_size_;\n}\n\n\nvoid extractGeometryFeature::setMinAloneNum(const int& alone_)\n{\n  alone=alone_;\n}\n\nvoid extractGeometryFeature::setMinIncludedAngle(const double min_angle_)\n{\n  min_angle=min_angle_;\n}\n\nvoid extractGeometryFeature::setNeigh_a(const double& a_)\n{\n  a=a_;\n}\n\nvoid extractGeometryFeature::setNeigh_b(const double& b_)\n{\n  b=b_;\n}\n\nvoid extractGeometryFeature::setIsClustering(const bool& IsClustering_)\n{\n  IsClustering=IsClustering_;\n}\n\nvoid extractGeometryFeature::setMinNeighNum(const int& min_point_num_)\n{\n  min_point_num=min_point_num_;\n}\n\nvoid extractGeometryFeature::setNMSRadius(const double& NMS_radius_)\n{\n NMS_radius=NMS_radius_;\n}\n\nvoid extractGeometryFeature::setGridSetorNum(const int gridSectorsNum_)\n{\n  gridSectorsNum=gridSectorsNum_;\n}\n\nvoid extractGeometryFeature::ChooseMethodofComputingOrientation(const bool& keypoints_based_method_)\n{\n  keypoints_based_method=keypoints_based_method_;\n}\n\nvoid extractGeometryFeature::setDesSectorNum(const int& dscpSectorsNum_)\n{\n  dscpSectorsNum=dscpSectorsNum_;\n}\n\nvoid extractGeometryFeature::setMatchDistinctRatio(const double distinct_ratio_)\n{\n  distinct_ratio=distinct_ratio_;\n}\n\nvoid extractGeometryFeature::setMatchDistThres(const double& match_dist_thres_)\n{\n  match_dist_thres=match_dist_thres_;\n}\n\nvoid extractGeometryFeature::setMatchMinScore(const double match_score_min_)\n{\n  match_score_min=match_score_min_;\n}\n\n\n\n\n\n\nstd::vector< pcl::PointIndices > extractGeometryFeature::EuclideanClusterExtraction() const\n{\n  std::vector<pcl::PointIndices> ret;\n  pcl::PointIndices cluster_indices;\n  int indice=0;\n  point3d bound_point;\n  for(auto point:candiate_pcd.points)\n  {\n    \n    if(cluster_indices.indices.empty())\n    {\n     bound_point=point;     \n     cluster_indices.indices.emplace_back(indice);\n    }\n    else\n    {\n      double dist=math::pointDistance(bound_point,point);\n      DALKO_DEBUG(\"distance:\"<<dist<<std::endl);\n      bound_point=point;\n          if(dist<region_grow_radius)\n\t  {\n\t    //std::cout<<\"该类新增加一个点\"<<std::endl;\n\t    cluster_indices.indices.emplace_back(indice);\n\t   }\n\t  else\n\t  {\n\t    DALKO_DEBUG(\"发现一个新的类,其尺寸为：\"<<cluster_indices.indices.size()<< std::endl);\n\t     ret.emplace_back(cluster_indices);\n\t     cluster_indices.indices.clear();\n\t     cluster_indices.indices.emplace_back(indice);\n\t  }\t  \n    }\n    indice++;\n  }\n  ret.emplace_back(cluster_indices);\n  return ret;\n}\n\n\n\nvoid extractGeometryFeature::setInputRanges(const sensor::rangeData& ranges_)\n{\n    candiate_pcd.clear();  \n    candiate_pcd=sensor::fromRangeData(ranges_);\n   ranges=ranges_;\n}\n\n\n\n/**\n * @brief FAKLO\n */\nfeaturePointSet extractGeometryFeature::extractFAKLO()\n{\n\tfeaturePointSet ret_keypoints;\n\tfalkolib::FALKOExtractor fe;\n\tfe.setMinScoreTh(0);\n\tfe.setMinExtractionRange(0.5);\n\tfe.setMaxExtractionRange(30);\n\tfe.enableSubbeam(false);\n\tfe.setNMSRadius(0.2);\n\tfe.setNeighB(0.07);\n\tfe.setBRatio(3);//2.5\n\tfe.setGridSectors(36);//16\n\n\tfalkolib::LaserScan scan(ranges.angle_min,6*3.1419f/4, ranges.ranges.size());\n\tscan.fromRanges(ranges.ranges);\n\tstd::vector<falkolib::FALKO> keypoints;\n\tfe.extract(scan, keypoints);\n\tfor(falkolib::FALKO keypoint:keypoints)\n\t{\n\t  ret_keypoints.push_back(candiate_pcd.points[keypoint.index]);\n\t}\n\treturn ret_keypoints;\n}\n\n\n\nvoid extractGeometryFeature::getNeiborhoodMember\n(const int &numberofCenter2clusterboundary, const size_t& center_index, const double& radius, std::vector< point3d >& neigh, bool flag_Left)\n{\n     \n     //根据邻域半径找到左右邻域内的点\n     double growing_dl;\n    int j=0;\n     while(1)\n     {\n       if(flag_Left)\n       {\n       j++;\n       }\n       else \n       {\n\t j--;\n      }\n        if(std::abs(j)<=numberofCenter2clusterboundary)\n       {\t\n\t growing_dl=math::pointDistance(candiate_pcd.points[center_index],candiate_pcd.points[center_index-j]);\t \n\t if(growing_dl<radius)\n\t {\n\t    neigh.push_back(candiate_pcd.points[center_index-j]);\n\t }\n\t else{\n\t   break;\n\t}\n       }\n       else\n       {\n\t break;\n      }\n    }  \n}\n\nstd::tuple< double, double,double> extractGeometryFeature::jointEvaluate\n(const point3d& center, const std::vector< point3d >& LeftNeigh, const std::vector< point3d >& rightNeigh)\n{\n\n    //size_t max_scale= std::max<size_t>(LeftNeigh.size(),rightNeigh.size());\n  std::vector<double> response_Angle_ratios;\n  std::vector<double> all_angle_ratios;\n  double score=0;\n  int count=0, Response_count=0;\n  double response_area=0;\n\n  for(auto left:LeftNeigh)\n  {\n    for(auto right:rightNeigh)\n    {\n      double area=computeAreaGivenEndpointCoordinates(center,left,right);\n      double edg1,edg2, angleRatio;\n    edg1=math::pointDistance(center,left);\n    edg2=math::pointDistance(center,right);\n    double area_min=getAreaThres(edg1,edg2);\n    angleRatio=area/area_min;\n    if(area>area_min)\n    {\n      Response_count++;\n      response_area+=angleRatio;\n      response_Angle_ratios.push_back(angleRatio);\n    }\n    score+=angleRatio; \n    all_angle_ratios.push_back(angleRatio);\n    count++;\n    }    \n  }  \n  \n  //数据分布均值\n  double mean=score/double(count);\n  //理论分布均值\n  double response_mean=response_area/double(Response_count);\n  \n  double error=0, error1=0, error2=0;\n  double sigma=0;\n  \n  for(auto angle_Ratio:response_Angle_ratios)\n  {\n    double residual=angle_Ratio-response_mean;\n     error+=residual*residual;\n  }\n    double variance_response=error/double(Response_count-1);\n  \n    for(auto angle_Ratio:all_angle_ratios)\n  {\n     double residual=angle_Ratio-mean;\n      error1+=residual*residual;\n  }\n    double variance_all=error1/double(count-1);\n    \n    for(auto angle_Ratio:all_angle_ratios)\n  {\n    double residual=angle_Ratio-response_mean;\n     error2+=residual*residual;\n  } \n  double mutual_variance=error2/double(count-1);\n \n  \n  //计算相对熵\n  double sigma_theroy=std::sqrt(variance_response);\n  double sigma_data=std::sqrt(variance_all);\n  double alpha_data=1/(double(std::sqrt(M_PI)*sigma_data));\n  double alpha_theroy=alpha_data*(sigma_data/sigma_theroy);\n \n  double D_P_Q=0;\n\n  std::vector<double> P, Q;\n  double sum_p=0,sum_q=0;\n    for(auto angle_Ratio:all_angle_ratios)\n  {\n      //   std::cout<<\"alpha_data:\"<<alpha_data<<std::endl;\n   //std::cout<<\"alpha_theroy:\"<<alpha_theroy<<std::endl;\n    double residual=angle_Ratio-response_mean;\n    double residual_data=angle_Ratio-mean;\n   // std::cout<<\"residual:\"<<residual<<std::endl;\n   //std::cout<<\"residual_data:\"<<residual_data<<std::endl;\n    double qi=alpha_theroy*exp(-1/2.d*(residual*residual)/variance_response);\n    double pi=alpha_data*exp(-1/2.d*(residual_data*residual_data)/variance_all);\n   //std::cout<<\"qi:\"<<qi<<std::endl;\n    sum_p+=pi;\n    sum_q+=qi;\n   //std::cout<<\"pi:\"<<qi<<std::endl;\n    P.push_back(pi);\n    Q.push_back(qi);\n   //double d=(qi*log(qi/pi)+pi*log(pi/qi))/2;  \n   // D_P_Q+=d;\n  }\n  \n\n  for(int i=0;i<P.size();i++)\n  {\n      D_P_Q+=(P[i]/sum_p*log(P[i]*sum_q/(sum_p*Q[i]))+Q[i]/sum_q*log(Q[i]*sum_p/(sum_q*P[i])))/2;   \n    // D_P_Q+=Q[i]/sum_q*log(Q[i]*sum_p/(sum_q*P[i]));\n    // D_P_Q+= P[i]/sum_p*log(P[i]*sum_q/(sum_p*Q[i]));\n  }\n\n  // D_P_Q=sum_q;\n  return std::make_tuple(response_mean,mutual_variance,D_P_Q);\n  \n}\n\n\n\nfeaturePointSet extractGeometryFeature::extractCornerWithimprovedFAKLO(const ClusterIndices& cluster)\n{\n  featurePointSet ret;\n  keypoints.clear();  \n    std::vector<point3d> NeighL;\n    std::vector<point3d> NeighR;  \n  for(int i=0;i<cluster.indices.size();i++)\n  {\n    point3d point_i;\n\n    point_i=candiate_pcd.points[cluster.indices[i]];\n    if(i<min_point_num)\n    {\n      continue;\n    }\n    \n    //计算左右邻域\n    double Neigh_Radius=getNeiborhood(ranges.ranges[cluster.indices[i]]);\n    \n    ratio_invariance=adaptiveResponsefactor(Neigh_Radius);\n    \n    DALKO_DEBUG(\"Neigh_R:\"<<Neigh_Radius<<std::endl);\n\n    double numofcenter2clusterboundary;\n    numofcenter2clusterboundary=i;\n    getNeiborhoodMember(numofcenter2clusterboundary, cluster.indices[i],Neigh_Radius, NeighL,true);\n    if(NeighL.size()>=min_point_num)\n    {\n      numofcenter2clusterboundary=cluster.indices.size()-i-1;\n      getNeiborhoodMember(numofcenter2clusterboundary,cluster.indices[i],Neigh_Radius, NeighR,false);\n    }\n    else{\n      NeighL.clear();       \n      continue;\n    }\n   if(NeighR.size()<min_point_num)\n    {\n     NeighL.clear(); \n     NeighR.clear();\n    continue;\n    } \n    \n\n    //根据面积决定是否被选为特征点候选点\n    point3d x_L=candiate_pcd.points[cluster.indices[i-NeighL.size()]];\n    point3d x_R=candiate_pcd.points[cluster.indices[i+NeighR.size()]];\n\n   //double area=computeAreaGivenEndpointCoordinates(point_i,x_L,x_R); \n   // double edg1=math::pointDistance(point_i, x_L);\n   // double edg2=math::pointDistance(point_i, x_R);\n    \n\n    \n    //****************************************\n    //直接使用面积作为响应\n   //****************************************\n    /*    \n    area_min_size=getAreaThres(edg1,edg2);\n    std::cout<<\"area_min_size: \"<<area_min_size<<std::endl;\n   if(area>area_min_size)*/\n\n    //*********************\n     //下面为FAKLO使用的方法 \n    //*********************\n  /*\n    //底边长度\n    double BaseEdge=std::abs(math::pointDistance(x_L,x_R));\n    //高\n    double High_length=area/BaseEdge;    \n     std::cout<<\"底边:\"<<BaseEdge<<std::endl;\n     std::cout<<\"高:\"<<High_length<<std::endl;\n     std::cout<<\"Thres:\"<<ri/b_ratio<<std::endl;\n     //if(deterBaseEdge>=(ri/b_ratio)&&deterHigh>=(ri/b_ratio))*/\n\n     std::pair<double,double> InvarianceAndRightAngleScore;\n     \n    InvarianceAndRightAngleScore=EvaulateInvarianceNeigh(point_i,NeighL,NeighR);\n   if(InvarianceAndRightAngleScore.first>ratio_invariance)\n    {\n      //计算栅格分值\n         double ScoreL=0, ScoreR=0,score=0,extra_reward=0;\n\tScoreL=EvaulateNeighDivergence(point_i,NeighL);\n\t// std::cout<<ScoreL<<std::endl;\n\tScoreR=EvaulateNeighDivergence(point_i,NeighR);     \n\tdouble DivergenceScore=ScoreL+ScoreR;  \n\t// double AngleInvarianceScore=EvaulateAngleQuality(point_i,NeighL,NeighR);\n\t//score=InvarianceAndRightAngleScore.second;\n\t//score=AngleInvarianceScore;\n\t//score=gainClosingRightAngle*RightAnglescore;\n\t//score=DivergenceScore;\n\t//score=AngleInvarianceScore+gainClosingRightAngle*RightAnglescore+DivergenceScore;\n\tdouble RightAnglescore,Variance;\n\tdouble responseScore;\n      std::tie(RightAnglescore,Variance,responseScore) =jointEvaluate(point_i,NeighL,NeighR);\n      //score=1000+0.8*RightAnglescoreAndVariance.first-0*RightAnglescoreAndVariance.second;\n      //score=responseScore*RightAnglescore/std::sqrt(Variance);\n       double expect=1/sin(min_angle/180.d*M_PI);\n      // score=1000-responseScore;\n      score=exp((expect-RightAnglescore)*(expect-RightAnglescore)*Variance);\n      DALKO_DEBUG(\"score:\"<<score<<std::endl);      \n      keypoints.emplace_back(keypoint(cluster.indices[i], score));\n    }    \n   NeighL.clear();\n   NeighR.clear();\n  }\n  \n  //如果不判断，当为空的情况下，迭代器就不会生效，这是对迭代器进行取值就会出错。\n    if(!keypoints.empty())\n    {\n     auto kp_with_maxvalue=std::max_element(keypoints.begin(),keypoints.end(),keypoint::compare);\n     keypoint temkp=*kp_with_maxvalue;\n    double max_score=temkp.score;\n\t\n\tfor(auto iter=keypoints.begin();iter!=keypoints.end();++iter)\n\t{\n\t  double tem=(*iter).score;\n\t  (*iter).score=tem;\t \n\t}\n    }\n \n  //孤立点抑制\n alonePointSupress();  \n //非极大值抑制 \n return NonMaxSupress();\n return fromKeypoints();\n \n}\n\n\n//TODO\nfeaturePointSet extractGeometryFeature::extractFLIRT()\n{\n// PeakFinder * pf;\n// RangeDetector range_detector(pf);\n// std::vector<double> phl, rho;\n// for(int i=0;i<ranges.ranges.size();i++)\n// {\n//   phl.emplace_back(ranges.angle_min+i*ranges.angle_increment);\n//   rho.emplace_back(ranges.ranges[i]);\n// }\n// LaserReading Laser_reading(phl,rho);\n// std::vector<InterestPoint*> kps;\n// range_detector.detect(Laser_reading,kps);\n}\n\n\n/*\ndiscriptors extractGeometryFeature::getGCdiscriptor(const point3d &center)\n{\n  getNeiborhoodMember();\n\n}*/\n\n\n\n\n\n\n//主要提取特征的主函数\n\nfeaturePointSet extractGeometryFeature::extractgfs(std::string T)\n{  \n  \n   KeypointsVclear();\n  featurePointSet ret;\n   if(T== \"FAKLO\")\n     {\n         ret=extractFAKLO();\n\t return ret;\n     }\n  //首先对点云进行聚类\n  //不能使用大于阈值的特征点响应方法，要使用NMS的方法，每一个点都有一个响应值，在一个区域里面挑出一个最大的\n  //对于二维首先统计出稳定的线点，然后对这点使用区域生成法恢复直线，然后对所有点进行聚类\n  //由于初始的种子点可能在一个类中，所以，当种子被聚类到某一类中时，这个种子就会被删除点\n  //然后再在每一个类中找到角点 \n  DALKO_DEBUG(\"点云尺寸：\"<<candiate_pcd.size()<<std::endl);\n  assert(!candiate_pcd.empty());\n  std::vector<pcl::PointIndices> clustersWithindices;\n  if(IsClustering)\n  {\n   clustersWithindices=EuclideanClusterExtraction();  \n  }\n  else\n  {\n    pcl::PointIndices tempCluster;\n    for(int i=0;i<ranges.ranges.size();i++)\n    {\n      tempCluster.indices.emplace_back(i);\n    }\n    clustersWithindices.emplace_back(tempCluster);\n  }\n  \n  DALKO_DEBUG(\"聚类个数：\"<<clustersWithindices.size()<<std::endl);\n \n  for(pcl::PointIndices cluster: clustersWithindices)\n  {    \n    if( T==\"IFAKLO\")\n   {\n         if(cluster.indices.size()>cluster_min_size)\n\t {\n           ret+=extractCornerWithimprovedFAKLO(cluster);\n\t }\n   }\n    else if( T==\"AT\")\n    {\n        ret+=extractCornerWithAreaTsensor(cluster);\n    }\n    else\n    {\n       std::cout<<\"please set feature type you would like to chose from FAKLO, IFAKLO, AT\"<<std::endl;\n    }\n } \n    return ret;\n}\n\n\n\nfeaturePointSet extractGeometryFeature::extractCornerWithAreaTsensor(const ClusterIndices &cluster)\n{\n    featurePointSet ret;\n    keypoints.clear();    \n  /*\n   * 首先两个端点，用它构建面积张量, 在里面滑动我们的窗口，窗口的点选为端点。求出这个窗口内，在当前窗口形态下的响应值\n   * 这样应该就很好检测直线特征点\n   * 相对于最小least square的好处在于不用计算法向量，法向量十分容易受到噪声干扰\n   */\n  std::vector<std::pair<int,double> > responses;\n  \n  bool line_flag=false;\n  int step=1;\n  double rep,rep1,rep2;\n  Eigen::Matrix3d S;\n  S.col(2)<<1,1,1;\n  if(cluster.indices.size()>=cluster_min_size)\n  {      \n    for(int n=0;n<cluster.indices.size()-slide_window_sizes-1;   n+=step)\n    {\n     std::cout<<\"点在类中位置：\"<<n<<std::endl;      \n      if(line_flag==false)\n      { \n\t std::vector<point3d> Neigh;\t \n        double growingR=math::pointDistance(candiate_pcd.points[cluster.indices[n]],candiate_pcd.points[cluster.indices[n+1]]);\n\tstd::cout<<\"growingR:\"<<growingR<<std::endl;\n\t       int j=1;\n\t       ri=getNeiborhood(ranges.ranges[cluster.indices[n]]);\n\t   while(growingR<=ri&&(n+j)<cluster.indices.size())\n\t  {\n\t      Neigh.push_back(candiate_pcd.points[cluster.indices[n+j]]);\n\t      growingR=math::pointDistance(candiate_pcd.points[cluster.indices[n]],candiate_pcd.points[cluster.indices[n+j]]);\n\t      j++;\n\t   }\n         slide_window_sizes=Neigh.size();\n\t std::cout<<\"slide_window_sizes:\" <<slide_window_sizes<<std::endl;\n\t Neigh.clear();\n\t if(slide_window_sizes<min_point_num)\n\t {\n\t   step=1;\n\t   continue;\n\t}\n\t  S(0,0)=candiate_pcd.points[cluster.indices[n]].x; \n\t  S(0,1)=candiate_pcd.points[cluster.indices[n]].y;\n\t  S(1,0)=candiate_pcd.points[cluster.indices[n+slide_window_sizes]].x; \n\t  S(1,1)=candiate_pcd.points[cluster.indices[n+slide_window_sizes]].y;\n\t  for(int j=0;j<slide_window_sizes;j++)\n\t  {\n\t    S(2,0)=candiate_pcd.points[cluster.indices[n+j]].x;\n\t    S(2,1)=candiate_pcd.points[cluster.indices[n+j]].y;\n\t      rep=std::abs(S.determinant());\n              std::cout<<\"case0 当前面积：\"<<rep<<std::endl;\n\t      if(rep>area_min_size)\n\t\t{\n\t\t  std::cout<<\"case1 当前面积：\"<<rep<<std::endl;\n\t\t  line_flag=false;\n\t\t  step=1;\n\t\t break;\n\t\t}\n\t\telse\n\t\t{\n\t\t  line_flag=true;\n\t\t  step++;\n\t\t}\n\t  } //for(int j=0;j<slide_window_sizes;j++)\n      }\n      else\n      {\n        S(2,0)=candiate_pcd.points[cluster.indices[n]].x;\n        S(2,1)=candiate_pcd.points[cluster.indices[n]].y;\n\n\trep=std::abs(S.determinant());\n\t\n\tif(rep>area_min_size)\n\t    {\n\t    std::cout<<\"case2 当前面积：\"<<rep<<std::endl;\n\t    line_flag=false;\n\t    S(2,0)=candiate_pcd.points[cluster.indices[n+1]].x;\n\t    S(2,1)=candiate_pcd.points[cluster.indices[n+1]].y;\n\t   rep1=std::abs(S.determinant());\n\t    S(2,0)=candiate_pcd.points[cluster.indices[n+2]].x;\n\t    S(2,1)=candiate_pcd.points[cluster.indices[n+2]].y;\n\t     rep2=std::abs(S.determinant());\t\n\t   if(rep1>area_min_size&&rep2>area_min_size)\n\t      keypoints.emplace_back(keypoint(cluster.indices[n-1],rep));\n\t     break;\n\t    }\n\t    else\n\t    {\n\t      step=1;\n\t     }\n      }     \n    }//for     \n  }//if   \n  //return fromKeypoints();\n  return ret=NonMaxSupress();\n}\n\n\n\n\nfeaturePointSet extractGeometryFeature::NonMaxSupress()\n{\n  \n  \n  //仍然有待改进，也最好是先计算索引窗口范围，在这个索引窗口内直接抑制。同时，对于打分十分接近的，直接选用打分接近的结构上在中间的点，就不要在抑制了\n  //先找出最大值，然后找到在该点抑制半径范围内的点，将这些点去除\n  //直到容器为空\n  KeyPoints nmsed_keypoints;\n    featurePointSet ret;\n  if(keypoints.empty())\n  {\n        return ret;      \n  }\n  \n   /*\n   std::cout<<\"检测到特征点个数\"<<keypoints.size()<<std::endl;     \n   for(auto kp:keypoints)\n   {\n     std::cout<<\"index:\"<<kp.index<<\" \"<<\"score:\"<<kp.score<<std::endl;\n  }\n  */\n   double max_score=0;\n   bool first=true;\n  while(!keypoints.empty())\n  {\n     KeyPoints tem_keypoints;\n     auto kp_with_maxvalue=std::max_element(keypoints.begin(),keypoints.end(),keypoint::compare);\n     keypoint temkp=*kp_with_maxvalue;\n     if(first)\n     {\n       max_score=temkp.score;\n    }\n    nmsed_keypoints.emplace_back(temkp);\n    keypoints.erase(kp_with_maxvalue);\n    if(keypoints.empty())\n    {\n      break;\n    }\n    //注意，当中间元素被删除之后，容器后面的迭代器就会失效，所以不能直接在以下程序中使用keypoints.erase(it)。\n    //为防止这种情况发生，加入一个临时容器    \n    for(KeyPoints::iterator it=keypoints.begin();it!=keypoints.end();++it)\n    {\n      double dist=math::pointDistance(candiate_pcd.points[temkp.index],candiate_pcd.points[(*it).index]);\n      \n      DALKO_DEBUG(\"dist:\"<<dist<<std::endl);\n        if(dist>NMS_radius)\n      {\n\ttem_keypoints.emplace_back(*it);\n      }\n    }   \n   keypoints.clear();\n   if(!tem_keypoints.empty())\n   {\n    keypoints.assign(tem_keypoints.begin(),tem_keypoints.end());\n   }\n   else\n   {\n     break;\n  }    \n  } \n  keypoints.clear();\n  keypoints.assign(nmsed_keypoints.begin(),nmsed_keypoints.end());\n  \n  for(keypoint kp:keypoints)\n  {\n    if(kp.score>=minValPercent*max_score)\n    {\n      ret.push_back(candiate_pcd.points[kp.index]);\n      Allkeypoints.push_back(kp);\n    }\n  }\n  //keypoints.clear();\n  DALKO_DEBUG(\"NMS后特征点个数:\"<<ret.size()<<std::endl); \n  return ret;  \n }  \n \n \nfeaturePointSet extractGeometryFeature::alonePointSupress()\n{\n  KeyPoints tem_keypoints;\n  for(auto kpi:keypoints)\n  {\n    int count=0;\n    for(auto kpj:keypoints)\n    {\n      double dist=math::pointDistance(candiate_pcd.points[kpi.index],candiate_pcd.points[kpj.index]);\n      if(dist<=alone_radius)\n      {\n\tcount++;\n      }\n      if(count>=alone)\n      {\n\ttem_keypoints.emplace_back(kpi);\n\t//这个break很重要，不然太消耗时间\n\tbreak;\n      }\n    }\n  }\n  keypoints.clear();\n  keypoints.assign(tem_keypoints.begin(),tem_keypoints.end());\n  return fromKeypoints();\n}\n\n \n \n //把特征点用点云输出\nfeaturePointSet extractGeometryFeature::fromKeypoints()\n{\n  featurePointSet kp_PCD;\n     for(auto kp:keypoints)\n     {\n       kp_PCD.push_back(candiate_pcd.points[kp.index]);\n    }\n    return kp_PCD;\n}\n\nfeaturePointSet extractGeometryFeature::fromAllkeypoints()\n{\n    keypointPcd.clear();\n     for(auto kp:Allkeypoints)\n     {\n      keypointPcd.push_back(candiate_pcd.points[kp.index]);\n    }\n    return keypointPcd;\n}\n\n\n \nfloat extractGeometryFeature::getNeiborhood(const double& range)\n{  \n  ri=a*exp(b*range);\n  return ri;\n}\n\ndouble extractGeometryFeature::getAreaThres()\n{\n  return 1/2.d*ri*ri*sin(min_angle/180.d*M_PI);\n}\n\n\ndouble extractGeometryFeature::getAreaThres(double edge1, double edge2)\n{\n  return 1/2.d*edge1*edge2*sin(min_angle/180.d*M_PI);\n}\n\ndouble extractGeometryFeature::extra_reward_from(const double& area,const double& area_min)\n{\n   return gainClosingRightAngle*area/area_min;\n}\n\nstd::vector< int > extractGeometryFeature::computeNeighPlorDistribution(const point3d& center, const std::vector< point3d >& singleSideNeigh)\n{\n std::vector<int> V_sector;\n      double scoreSingleSide=0;\n       int count=0;\n      for(auto point:singleSideNeigh)\n      {\n\tint SecNum=std::floor(gridSectorsNum/(2*M_PI)*std::atan2(point.y-center.y, point.x-center.x));\n\tif(SecNum<0)\n\t{\n\t  SecNum=gridSectorsNum+SecNum;\n\t}\t\n\tV_sector.push_back(SecNum);\n      }\n      return V_sector;\n}\n\ndouble extractGeometryFeature::EvaulateAngleQuality(const point3d& center, const std::vector< point3d >& LeftNeigh, const std::vector< point3d >& rightNeigh)\n{\n  std::vector<int> V_left,V_Right, V_dist;\n  V_left=computeNeighPlorDistribution(center,LeftNeigh);\n  V_Right=computeNeighPlorDistribution(center,rightNeigh);\n  int sum_dist=0,count=0,dist=0;\n  for(auto left:V_left)\n  {\n    for(auto right:V_Right)\n    {\n     count++;      \n     dist= std::abs((abs(left-right)+gridSectorsNum/2)%gridSectorsNum-gridSectorsNum/2);\n     sum_dist+=dist;\n     V_dist.emplace_back(dist);\n    }\n  }\n  double mean_dist=sum_dist/double(count);\n  double error=0,residual=0;\n for(auto dist:V_dist)\n {\n   residual=dist-mean_dist;\n   error+=residual*residual;\n}\ndouble variance=error/double(count-1); \nreturn variance;\n}\n\n\ndouble extractGeometryFeature::EvaulateNeighDivergence(const point3d &center, const  std::vector< point3d > &singleSideNeigh)\n{\n      std::vector<int> V_sector;\n      double scoreSingleSide=0;\n       int count=0;\n      for(auto point:singleSideNeigh)\n      {\n\tint SecNum=std::floor(gridSectorsNum/(2*M_PI)*std::atan2(point.y-center.y, point.x-center.x));\n\tif(SecNum<0)\n\t{\n\t  SecNum=gridSectorsNum+SecNum;\n\t}\n\tif(V_sector.size()>0)\n\t{\n\t    for(auto Sec_i:V_sector)\n\t    {\n\t      count++;\n\t      scoreSingleSide+=std::abs((abs(SecNum-Sec_i)+gridSectorsNum/2)%gridSectorsNum-gridSectorsNum/2);\n\t    }\n\t  }\n\tV_sector.push_back(SecNum);\n      }\n     //scoreSingleSide=scoreSingleSide/count;\n     V_sector.clear();\n      return scoreSingleSide;\n}\n\n\nstd::pair<double,double> extractGeometryFeature::EvaulateInvarianceNeigh(const point3d& center, const std::vector< point3d >& LeftNeigh, const std::vector< point3d >& rightNeigh)\n{\n  /*\n  size_t max_scale= std::max<size_t>(LeftNeigh.size(),rightNeigh.size());\n  std::vector<double> sin_Angle_ratios;\n  double score=0;\n  int Response_count=0;\n  for(int i=0;i<max_scale;i++)\n  {\n    double area=computeAreaGivenEndpointCoordinates(center,LeftNeigh[i],rightNeigh[i]);\n    double edg1,edg2, angleRatio;\n    edg1=math::pointDistance(center,LeftNeigh[i]);\n    edg2=math::pointDistance(center,rightNeigh[i]);\n    double area_min=getAreaThres(edg1,edg2);\n    angleRatio=area/area_min;\n    score+=angleRatio;\n    if(area>area_min) Response_count++;\n    }\n    return std::make_pair(Response_count/double(max_scale),score/double(max_scale));\n    */\n\n  double score=0;\n  int count=0, Response_count=0;\n  double response_area=0;\n  for(auto left:LeftNeigh)\n  {\n    for(auto right:rightNeigh)\n    {\n      double area=computeAreaGivenEndpointCoordinates(center,left,right);\n      double edg1,edg2, angleRatio;\n    edg1=math::pointDistance(center,left);\n    edg2=math::pointDistance(center,right);\n    double area_min=getAreaThres(edg1,edg2);\n    angleRatio=area/area_min;\n    if(area>area_min)\n    {\n      Response_count++;\n    }\n    count++;\n    }    \n  }   \n return std::make_pair(Response_count/double(count),score/double(count));\n\n}\n\n\ndouble extractGeometryFeature::computeAreaGivenEndpointCoordinates(const point3d& A1, const point3d& A2, const point3d& A3)\n{\n    Eigen::Matrix3f S;\n    S.col(2)<<1,1,1;\n    S(0,0)=A1.x;    S(0,1)=A1.y;\n    S(1,0)=A2.x;    S(1,1)=A2.y;\n    S(2,0)=A3.x;    S(2,1)=A3.y;\n    //面积\n    double area=1/2.d*std::abs(S.determinant());\n    return area;\n}\n\n\ndouble extractGeometryFeature::adaptiveResponsefactor(const double & ri)\n{\n   return double(0.5-5*(ri-0.2)*(ri-2)); \n}\n\n\n\nDiscriptors extractGeometryFeature::getGCdiscriptor()\n{\n  \n    fromAllkeypoints();\n    GCdiscriptors.resize(dscpSectorsNum,Allkeypoints.size()); \n    DALKO_DEBUG(GCdiscriptors.rows()<<std::endl);\n    DALKO_DEBUG(GCdiscriptors.cols()<<std::endl);\n//     std::cout<<GCdiscriptors.rows()<<std::endl;\n//     std::cout<<GCdiscriptors.cols()<<std::endl;\n    GCdiscriptors.setZero();\n         int j=0,i=0;\n    for(keypoint kp:Allkeypoints)\n    {      \n    point3d current_point=candiate_pcd.points[kp.index];    \n   \n    int Cornerorientation;\n    if(!keypoints_based_method)\n    { Cornerorientation=getCornerOrientationfromNeigh(kp.index);}\n    else {Cornerorientation=getCornerOrientationBasedonKeypoints(kp.index);}  \n\n    //计算特征点在栅格内的分布\n    for(keypoint kpj:Allkeypoints)\n      {\n      if(kpj.index==kp.index)\n      {\n\tcontinue;\n      }\n      point3d kppoint=candiate_pcd.points[kpj.index];\n       int kp_sector_num;\n       kp_sector_num=floor(dscpSectorsNum/(2*M_PI)*atan2(kppoint.y-current_point.y,kppoint.x-current_point.x));\n       if(kp_sector_num<0)\n       {\n\t kp_sector_num+=dscpSectorsNum;\n      }\n      int diff=kp_sector_num-Cornerorientation;\n      if(diff<0)\n      {\n\tkp_sector_num=dscpSectorsNum+diff;\n      }\n      else{\n\tkp_sector_num=diff;\n      }\n       double dist=math::pointDistance(kppoint,current_point);\n       if(GCdiscriptors(kp_sector_num,i)==0)\n       GCdiscriptors(kp_sector_num,i)=log(dist);\n       else if (GCdiscriptors(kp_sector_num,i)>log(dist))\n       {\n\t    GCdiscriptors(kp_sector_num,i)=log(dist);\n       }      \n    }\n     i++; \n    }\n    return GCdiscriptors;\n}\n\nint extractGeometryFeature::getCornerOrientationfromNeigh(const int& index)\n{\n    double r=getNeiborhood(ranges.ranges[index]);\n      std::vector<point3d> NeighL,NeighR;\n      point3d current_point=candiate_pcd.points[index];\n      getNeiborhoodMember(index,index,r,NeighL,true);\n      getNeiborhoodMember(ranges.ranges.size()-index-1,index,r,NeighR, false);\n      \n      point3d centriod, centriod_left, centriod_right;\n      centriod.x=0;centriod.y=0;centriod.z=0;\n      centriod_left.x=0;centriod_left.y=0;centriod_left.z=0;\n      centriod_right.x=0;centriod_right.y=0;centriod_right.z=0;\n\n      //计算左右边各自的栅格分布\n      double left_edge=0, right_edge=0;\n      for(point3d temp:NeighL)\n      {\n\tcentriod_left.x+=temp.x;\n\tcentriod_left.y+=temp.y;\n\tcentriod_left.z+=temp.z;\n      }\n      centriod_left.x/=NeighL.size();      \n      centriod_left.y/=NeighL.size();\n      int Orientation_l=floor(dscpSectorsNum/(2*M_PI)*atan2(centriod_left.y-current_point.y,centriod_left.x-current_point.x));\n      if(Orientation_l<0)\n      {\n\tOrientation_l+=dscpSectorsNum;\n      }\n      \n      for(point3d temp:NeighR)\n      {\n\tcentriod_right.x+=temp.x;\n\tcentriod_right.y+=temp.y;\n\tcentriod_right.z+=temp.z;\n      }\n      centriod_right.x/=NeighR.size();\n      centriod_right.y/=NeighR.size();\n      int Orientation_r=floor(dscpSectorsNum/(2*M_PI)*atan2(centriod_right.y-current_point.y,centriod_right.x-current_point.x));\n      if(Orientation_r<0)\n      {\n\tOrientation_r+=dscpSectorsNum;\n      }    \n     \n      int Cornerorientation=1/2*(Orientation_l+Orientation_r);\n      if ((distanceofSectors(Orientation_l,Cornerorientation)+distanceofSectors(Orientation_r,Cornerorientation))>(dscpSectorsNum/2.d))\n      {\n         Cornerorientation=(Cornerorientation+dscpSectorsNum/2)%dscpSectorsNum;\n      }\n      return Cornerorientation;\n}\n\n\nint extractGeometryFeature::getCornerOrientationBasedonKeypoints(const int & index)\n{  \n      int left_endpoint_index,right_endpoint_index;\n      point3d current_point=candiate_pcd.points[index];\n      double dist_min, dist_second;\n      bool first=true;\n     if(!isCreatedKdtree)\n     { \n      kdtree_keypoints.setInputCloud(keypointPcd.makeShared());\n      isCreatedKdtree=true;\n     }\n      \n       size_t K=3;\n       std:: vector<int> pointIdxNKNSearch(K);//用来存放搜索到的点的index\n       std::vector<float> pointNKNSquaredDistance(K);//存放搜索到的点到当前的欧式距离\n       kdtree_keypoints.nearestKSearch(current_point,K,pointIdxNKNSearch,pointNKNSquaredDistance);\n       left_endpoint_index=pointIdxNKNSearch[1];\n       right_endpoint_index=pointIdxNKNSearch[2];    \n      point3d left_endpoint=keypointPcd.points[left_endpoint_index];\n      point3d right_endpoint=keypointPcd.points[right_endpoint_index];\n      point3d centriod;\n      centriod.x=(left_endpoint.x+right_endpoint.x+current_point.x)/3;\n      centriod.y=(left_endpoint.y+right_endpoint.y+current_point.y)/3;      \n     int Cornerorientation=floor(dscpSectorsNum/(2*M_PI)*atan2(centriod.y-current_point.y,centriod.x-current_point.x));\n      if (Cornerorientation<0)\n      {\n         Cornerorientation+=dscpSectorsNum;\n      }\n      return Cornerorientation;\n}\n\n\nint extractGeometryFeature::distanceofSectors(const int& index1, const int& index2)\n{\n    int fyb=abs(int(abs(index1-index2)+dscpSectorsNum/2.f)%dscpSectorsNum-dscpSectorsNum/2);\n    return fyb;\n}\n\n\nstd::vector<std::tuple< int, int, double > > extractGeometryFeature::match(const KeyPoints& kps, const Discriptors& GCS)\n{ \n     int i=0;\n     std::vector<std::tuple<int,int,double>> pairs;\n    assert(GCS.cols()>0&&GCS.rows()>0);\n    for(keypoint kpi:Allkeypoints)\n    {double max_score=0, second_score=0;\n      int max_index;\n     int  j=0;\n      for(keypoint kpj:kps)\n      {\t \n\tdouble score=0;\n\tfor(int k=0;k<GCS.rows();k++)\n\t{\n\t  if(GCS(k,j)>0&&GCdiscriptors(k,i)>0)\n\t  {\n\t  double dist=abs(GCS(k,j)-GCdiscriptors(k,i));\n\t  if(abs(dist)<=match_dist_thres)\n\t  {\n\t    score+=20.d;\n\t  }\n\t  }\n\t}\n\t if(score>=max_score)\n\t {\n\tsecond_score=max_score;\n\tmax_score=score;\n\tmax_index=kpj.index;\n\t }\t\n\tj++;\n      }\n      if((max_score/second_score)>=distinct_ratio&&(max_score>=match_score_min))\n      {\n\tpairs.push_back(std::make_tuple(kpi.index,max_index,max_score));\n      }\n      i++;\n    }    \n    return pairs;\n}\n\n\n/**\n * 特征点，还有有一个特性也很重要，就是明显区别于其他点。这样可以减少在匹配中产生模糊性，可以想象，如果没有\n * 使用面积张量来检测特征点\n */\nfeaturePointSet extractGeometryFeature::extractfromTensorField(const ClusterIndices & cluster)\n{\n    featurePointSet ret;\n    keypoints.clear();    \n  /*\n   * 首先两个端点，用它构建面积张量, 在里面滑动我们的窗口，窗口的点选为端点。求出这个窗口内，在当前窗口形态下的响应值\n   * 这样应该就很好检测直线特征点\n   * 相对于最小least square的好处在于不用计算法向量，法向量十分容易受到噪声干扰\n   */\n  std::vector<std::pair<int,double> > responses;\n  \n  if(cluster.indices.size()>=cluster_min_size)\n  {\n    for(int n=0;n<cluster.indices.size()-slide_window_sizes;n++)\n    {\n      Eigen::Matrix3d S;\n      S.col(2)<<1,1,1;\n      S(0,0)=candiate_pcd.points[cluster.indices[n]].x; \n      S(0,1)=candiate_pcd.points[cluster.indices[n]].y;\n      S(1,0)=candiate_pcd.points[cluster.indices[n+slide_window_sizes]].x; \n      S(1,1)=candiate_pcd.points[cluster.indices[n+slide_window_sizes]].y;\n      \n      for(int j=0;j<slide_window_sizes;j++)\n      {\n\tS(2,0)=candiate_pcd.points[n+j].x;\n        S(2,1)=candiate_pcd.points[n+j].y;\n\t  double rep=std::abs(S.determinant());\n\t  if(rep>area_min_size)\n\t    {\t    \n\t      responses.push_back(std::make_pair(cluster.indices[n+j],rep));\n\t    }\n\t    else\n\t    {\n\t      responses.push_back(std::make_pair(cluster.indices[n+j],0.d));\n\t    }\n      }\n    }\n  }\n  //创建一个积分图像  \n  std::vector<double> integral_response;\n  double rep_integ=0;\n  for(auto response:responses)\n  {   \n    rep_integ+=response.second;\n    integral_response.emplace_back(rep_integ);\n    std::cout<<response.second<<\" \";\n  }\n   std::cout<<std::endl; \n   \n   for(auto response:responses)\n   {\n     keypoints.emplace_back(keypoint(response.first, response.second));\n  }\n   \n   //局部最大值\n   for(int j=0;j<responses.size();j++)\n   {\n     if(j>1&&j<responses.size()-2)\n     {\n       if((responses[j].second>responses[j-1].second&&responses[j].second>responses[j+1].second)\n\t ||(responses[j].second<responses[j-1].second&&responses[j].second<responses[j+1].second))\n       {\n\tdouble variance=3*responses[j].second-(integral_response[j+1]-integral_response[j-1]);\n\tstd::cout<<variance<<std::endl;\n\tkeypoints.emplace_back(keypoint(responses[j].first, responses[j].second));\n       }\n    }\n  }\n  //return ret=fromKeypoints();\n  return ret=NonMaxSupress();\n}\n\n\nKeyPoints extractGeometryFeature::getKeypoints()\n{\n   return Allkeypoints;\n}\n\npoint3d extractGeometryFeature::GetPoint3dfromIndex(const int & pointIndex)\n{\n  return candiate_pcd.points[pointIndex];\n}\n\n\nvoid extractGeometryFeature::KeypointsVclear()\n{\n  Allkeypoints.clear();\n  keypointPcd.clear();\n  keypoints.clear();\n}\n\n\n \n}", "meta": {"hexsha": "9f7374c05f7ce590493db127fd6987331f33974d", "size": 34390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geomeasurer/extract_geometry_feature/extractgeometryfeature.cpp", "max_stars_repo_name": "zoumaguanxin/geomeasurer", "max_stars_repo_head_hexsha": "30a58f61552285809352ebd49ed9c245752a8f54", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-15T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T18:09:38.000Z", "max_issues_repo_path": "geomeasurer/extract_geometry_feature/extractgeometryfeature.cpp", "max_issues_repo_name": "zoumaguanxin/geomeasurer", "max_issues_repo_head_hexsha": "30a58f61552285809352ebd49ed9c245752a8f54", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geomeasurer/extract_geometry_feature/extractgeometryfeature.cpp", "max_forks_repo_name": "zoumaguanxin/geomeasurer", "max_forks_repo_head_hexsha": "30a58f61552285809352ebd49ed9c245752a8f54", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-01T16:03:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T18:09:44.000Z", "avg_line_length": 27.0574350905, "max_line_length": 178, "alphanum_fraction": 0.6861878453, "num_tokens": 10398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.01826427674872807, "lm_q1q2_score": 0.00611103415225048}}
{"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 GRAPH_MOTIFS_HH\n#define GRAPH_MOTIFS_HH\n\n#include <boost/graph/isomorphism.hpp>\n#include <unordered_set>\n#include <boost/functional/hash.hpp>\n#include <algorithm>\n#include <vector>\n\n#include \"random.hh\"\n\nnamespace graph_tool\n{\nusing namespace boost;\n\ntemplate <class Value>\nvoid insert_sorted(std::vector<Value>& v, const Value& val)\n{\n    typeof(v.begin()) iter = lower_bound(v.begin(), v.end(), val);\n    if (iter != v.end() && *iter == val)\n        return; // no repetitions\n    v.insert(iter, val);\n}\n\ntemplate <class Value>\nbool has_val(std::vector<Value>& v, const Value& val)\n{\n    typeof(v.begin()) iter = lower_bound(v.begin(), v.end(), val);\n    if (iter == v.end())\n        return false;\n    return *iter == val;\n}\n\n// gets all the subgraphs starting from vertex v and store it in subgraphs.\ntemplate <class Graph, class Sampler>\nvoid get_subgraphs(Graph& g, typename graph_traits<Graph>::vertex_descriptor v,\n                   size_t n,\n                   std::vector<std::vector<typename graph_traits<Graph>::vertex_descriptor> >& subgraphs,\n                   Sampler sampler)\n{\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n\n    // extension and subgraph stack\n    std::vector<std::vector<vertex_t> > ext_stack(1);\n    std::vector<std::vector<vertex_t> > sub_stack(1);\n    std::vector<std::vector<vertex_t> > sub_neighbours_stack(1);\n\n    sub_stack[0].push_back(v);\n    typename graph_traits<Graph>::out_edge_iterator e, e_end;\n    for (tie(e, e_end) = out_edges(v, g); e != e_end; ++e)\n    {\n        typename graph_traits<Graph>::vertex_descriptor u = target(*e, g);\n        if (u > v && !has_val(ext_stack[0], u))\n        {\n            insert_sorted(ext_stack[0], u);\n            insert_sorted(sub_neighbours_stack[0],u);\n        }\n    }\n\n    while (!sub_stack.empty())\n    {\n        std::vector<vertex_t>& ext = ext_stack.back();\n        std::vector<vertex_t>& sub = sub_stack.back();\n        std::vector<vertex_t>& sub_neighbours = sub_neighbours_stack.back();\n\n        if (sub.size() == n)\n        {\n            // found a subgraph of the desired size; put it in the list and go\n            // back a level\n            subgraphs.push_back(sub);\n            sub_stack.pop_back();\n            ext_stack.pop_back();\n            sub_neighbours_stack.pop_back();\n            continue;\n        }\n\n        if (ext.empty())\n        {\n            // no where else to go\n            ext_stack.pop_back();\n            sub_stack.pop_back();\n            sub_neighbours_stack.pop_back();\n            continue;\n        }\n        else\n        {\n            // extend subgraph\n            std::vector<vertex_t> new_ext, new_sub = sub,\n                new_sub_neighbours = sub_neighbours;\n\n            // remove w from ext\n            vertex_t w = ext.back();\n            ext.pop_back();\n\n            // insert w in subgraph\n            insert_sorted(new_sub, w);\n\n            // update new_ext\n            new_ext = ext;\n            for (tie(e, e_end) = out_edges(w, g); e != e_end; ++e)\n            {\n                vertex_t u = target(*e,g);\n                if (u > v)\n                {\n                    if (!has_val(sub_neighbours, u))\n                        insert_sorted(new_ext, u);\n                    insert_sorted(new_sub_neighbours, u);\n                }\n            }\n\n            sampler(new_ext, ext_stack.size());\n\n            ext_stack.push_back(new_ext);\n            sub_stack.push_back(new_sub);\n            sub_neighbours_stack.push_back(new_sub_neighbours);\n        }\n    }\n}\n\n// sampling selectors\n\nstruct sample_all\n{\n    template <class val_type>\n    void operator()(std::vector<val_type>&, size_t) {}\n};\n\nstruct sample_some\n{\n    sample_some(std::vector<double>& p, rng_t& rng): _p(&p), _rng(&rng) {}\n    sample_some() {}\n\n    template <class val_type>\n    void operator()(std::vector<val_type>& extend, size_t d)\n    {\n        typedef std::uniform_real_distribution<double> rdist_t;\n        auto random = std::bind(rdist_t(), std::ref(*_rng));\n\n        double pd = (*_p)[d+1];\n        size_t nc = extend.size();\n        double u = nc*pd - floor(nc*pd);\n        size_t n;\n        double r;\n        {\n            #pragma omp critical\n            r = random();\n        }\n        if (r < u)\n            n = size_t(ceil(nc*pd));\n        else\n            n = size_t(floor(nc*pd));\n\n        if (n == extend.size())\n            return;\n        if (n == 0)\n        {\n            extend.clear();\n            return;\n        }\n\n        typedef std::uniform_int_distribution<size_t> idist_t;\n        for (size_t i = 0; i < n; ++i)\n        {\n            auto random_v = std::bind(idist_t(0, extend.size()-i-1),\n                                      std::ref(*_rng));\n            size_t j;\n            {\n                #pragma omp critical\n                j = i + random_v();\n            }\n            swap(extend[i], extend[j]);\n        }\n        extend.resize(n);\n    }\n\n    std::vector<double>* _p;\n    rng_t* _rng;\n};\n\n\n// build the actual induced subgraph from the vertex list\ntemplate <class Graph, class GraphSG>\nvoid make_subgraph\n    (std::vector<typename graph_traits<Graph>::vertex_descriptor>& vlist,\n     Graph& g, GraphSG& sub)\n{\n    for (size_t i = 0; i < vlist.size(); ++i)\n        add_vertex(sub);\n    for (size_t i = 0; i < vlist.size(); ++i)\n    {\n        typename graph_traits<Graph>::vertex_descriptor ov = vlist[i], ot;\n        typename graph_traits<GraphSG>::vertex_descriptor nv = vertex(i,sub);\n        typename graph_traits<Graph>::out_edge_iterator e, e_end;\n        for (tie(e, e_end) = out_edges(ov, g); e != e_end; ++e)\n        {\n            ot = target(*e, g);\n            typeof(vlist.begin()) viter =\n                lower_bound(vlist.begin(), vlist.end(), ot);\n            size_t ot_index = viter - vlist.begin();\n            if (viter != vlist.end() && vlist[ot_index] == ot &&\n                (is_directed::apply<Graph>::type::value || ot < ov))\n                add_edge(nv, vertex(ot_index, sub), sub);\n        }\n    }\n}\n\n// compare two graphs for labeled exactness (not isomorphism)\ntemplate <class Graph>\nbool graph_cmp(Graph& g1, Graph& g2)\n{\n    if (num_vertices(g1) != num_vertices(g2) || num_edges(g1) != num_edges(g2))\n        return false;\n\n    typename graph_traits<Graph>::vertex_iterator v1, v1_end;\n    typename graph_traits<Graph>::vertex_iterator v2, v2_end;\n    tie(v2, v2_end) = vertices(g2);\n    for (tie(v1, v1_end) = vertices(g1); v1 != v1_end; ++v1)\n    {\n        if (out_degree(*v1, g1) != out_degree(*v2, g2))\n            return false;\n        if (in_degreeS()(*v1, g1) != in_degreeS()(*v2, g2))\n            return false;\n\n        std::vector<typename graph_traits<Graph>::vertex_descriptor> out1, out2;\n        typename graph_traits<Graph>::out_edge_iterator e, e_end;\n        for (tie(e, e_end) = out_edges(*v1, g1); e != e_end; ++e)\n            out1.push_back(target(*e, g1));\n        for (tie(e, e_end) = out_edges(*v2, g2); e != e_end; ++e)\n            out2.push_back(target(*e, g2));\n        sort(out1.begin(), out1.end());\n        sort(out2.begin(), out2.end());\n        if (out1 != out2)\n            return false;\n    }\n    return true;\n}\n\n// short hand for both types of subgraphs\ntypedef adj_list<size_t> d_graph_t;\ntypedef adj_list<size_t> u_graph_t;\n\n// we need this wrap to use the UndirectedAdaptor only on directed graphs\nstruct wrap_undirected\n{\n    template <class Graph>\n    struct apply\n    {\n        typedef typename mpl::if_<typename is_directed::apply<Graph>::type,\n                                  UndirectedAdaptor<Graph>,\n                                  Graph&>::type type;\n    };\n};\n\n// get the signature of the graph: sorted degree sequence\ntemplate <class Graph>\nvoid get_sig(Graph& g, std::vector<size_t>& sig)\n{\n    sig.clear();\n    size_t N = num_vertices(g);\n    if (N > 0)\n        sig.resize(is_directed::apply<Graph>::type::value ? 2 * N : N);\n    for (size_t i = 0; i < N; ++i)\n    {\n        typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);\n        sig[i] = out_degree(v, g);\n        if(is_directed::apply<Graph>::type::value)\n            sig[i + N] = in_degreeS()(v, g);\n    }\n    sort(sig.begin(), sig.end());\n}\n\n// gets (or samples) all the subgraphs in graph g\nstruct get_all_motifs\n{\n    get_all_motifs(bool collect_vmaps, double p, bool comp_iso, bool fill_list,\n                   rng_t& rng)\n        : collect_vmaps(collect_vmaps), p(p),\n          comp_iso(comp_iso), fill_list(fill_list), rng(rng) {}\n    bool collect_vmaps;\n    double p;\n    bool comp_iso;\n    bool fill_list;\n    rng_t& rng;\n\n    template <class Graph, class Sampler, class VMap>\n    void operator()(Graph& g, size_t k, boost::any& list,\n                    std::vector<size_t>& hist, std::vector<std::vector<VMap> >& vmaps,\n                    Sampler sampler) const\n    {\n        typedef typename mpl::if_<typename is_directed::apply<Graph>::type,\n                                  d_graph_t,\n                                  u_graph_t>::type graph_sg_t;\n\n        // the main subgraph lists\n        std::vector<graph_sg_t>& subgraph_list =\n            any_cast<std::vector<graph_sg_t>&>(list);\n\n        // this hashes subgraphs according to their signature\n        std::unordered_map<std::vector<size_t>,\n                           std::vector<pair<size_t, graph_sg_t> >,\n                           std::hash<std::vector<size_t>>> sub_list;\n        std::vector<size_t> sig; // current signature\n\n        for (size_t i = 0; i < subgraph_list.size(); ++i)\n        {\n            get_sig(subgraph_list[i], sig);\n            sub_list[sig].push_back(make_pair(i,subgraph_list[i]));\n        }\n\n        // the subgraph count\n        hist.resize(subgraph_list.size());\n\n        typedef std::uniform_real_distribution<double> rdist_t;\n        auto random = std::bind(rdist_t(), std::ref(rng));\n\n        // the set of vertices V to be sampled (filled only if p < 1)\n        std::vector<size_t> V;\n        if (p < 1)\n        {\n            typename graph_traits<Graph>::vertex_iterator v, v_end;\n            for (tie(v, v_end) = vertices(g); v != v_end; ++v)\n                V.push_back(*v);\n\n            size_t n;\n            if (random() < p)\n                n = size_t(ceil(V.size()*p));\n            else\n                n = size_t(floor(V.size()*p));\n\n            typedef std::uniform_int_distribution<size_t> idist_t;\n            for (size_t i = 0; i < n; ++i)\n            {\n                auto random_v = std::bind(idist_t(0, V.size()-i-1),\n                                          std::ref(rng));\n                size_t j = i + random_v();\n                swap(V[i], V[j]);\n            }\n            V.resize(n);\n        }\n\n        int i, N = (p < 1) ? V.size() : num_vertices(g);\n        #pragma omp parallel for default(shared) private(i, sig) \\\n            schedule(runtime) if (N > 100)\n        for (i = 0; i < N; ++i)\n        {\n            std::vector<std::vector<typename graph_traits<Graph>::vertex_descriptor> >\n                subgraphs;\n            typename graph_traits<Graph>::vertex_descriptor v =\n                (p < 1) ? V[i] : vertex(i, g);\n            if (v == graph_traits<Graph>::null_vertex())\n                continue;\n\n            typename wrap_undirected::apply<Graph>::type ug(g);\n            get_subgraphs(ug, v, k, subgraphs, sampler);\n\n            #pragma omp critical\n\n            for (size_t j = 0; j < subgraphs.size(); ++j)\n            {\n                graph_sg_t sub;\n                make_subgraph(subgraphs[j], g, sub);\n                get_sig(sub, sig);\n\n                typeof(sub_list.begin()) iter = sub_list.find(sig);\n                if(iter == sub_list.end())\n                {\n                    if (!fill_list)\n                        continue; // avoid inserting an element in sub_list\n                    sub_list[sig].clear();\n                }\n\n                bool found = false;\n                size_t pos;\n                typeof(sub_list.begin()) sl = sub_list.find(sig);\n                if (sl != sub_list.end())\n                {\n                    for (size_t l = 0; l < sl->second.size(); ++l)\n                    {\n                        graph_sg_t& motif = sl->second[l].second;\n                        if (comp_iso)\n                        {\n                            if (isomorphism(motif, sub,\n                                            vertex_index1_map(get(vertex_index, motif)).\n                                            vertex_index2_map(get(vertex_index, sub))))\n                                found = true;\n                        }\n                        else\n                        {\n                            if (graph_cmp(motif, sub))\n                                found = true;\n                        }\n                        if (found)\n                        {\n                            pos = sl->second[l].first;\n                            hist[pos]++;\n                            break;\n                        }\n                    }\n                }\n\n                if (found == false && fill_list)\n                {\n                    subgraph_list.push_back(sub);\n                    sub_list[sig].push_back(make_pair(subgraph_list.size() - 1,\n                                                      sub));\n                    hist.push_back(1);\n                    pos = hist.size() - 1;\n                    found = true;\n                }\n\n                if (found && collect_vmaps)\n                {\n                    if (pos >= vmaps.size())\n                        vmaps.resize(pos + 1);\n                    vmaps[pos].push_back(VMap(get(boost::vertex_index,sub)));\n                    for (size_t vi = 0; vi < num_vertices(sub); ++vi)\n                        vmaps[pos].back()[vertex(vi, sub)] = subgraphs[j][vi];\n                }\n            }\n        }\n    }\n};\n\n} //graph-tool namespace\n\n#endif // GRAPH_MOTIFS_HH\n", "meta": {"hexsha": "33b9ae6445fc1f843db77ac0a08ce1e30c98c1a5", "size": 14660, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/clustering/graph_motifs.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/clustering/graph_motifs.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/clustering/graph_motifs.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": 33.018018018, "max_line_length": 105, "alphanum_fraction": 0.5199863574, "num_tokens": 3450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.02297737183352882, "lm_q1q2_score": 0.00610923449368905}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_CollisionHandler.hpp\n//! \\author Alex Robinson\n//! \\brief  Collision handler class declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_COLLISION_HANDLER_HPP\n#define MONTE_CARLO_COLLISION_HANDLER_HPP\n\n// Boost Includes\n#include <boost/unordered_map.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_NeutronMaterial.hpp\"\n#include \"MonteCarlo_PhotonMaterial.hpp\"\n#include \"MonteCarlo_ElectronMaterial.hpp\"\n#include \"MonteCarlo_NeutronState.hpp\"\n#include \"MonteCarlo_PhotonState.hpp\"\n#include \"MonteCarlo_ElectronState.hpp\"\n#include \"Geometry_ModuleTraits.hpp\"\n\nnamespace MonteCarlo{\n\n//! The collision handler class\nclass CollisionHandler\n{\n\nprivate:\n\n  // Typedef for cell id neutron material map\n  typedef boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n\t\t\t       Teuchos::RCP<NeutronMaterial> >\n  CellIdNeutronMaterialMap;\n\n  // Typedef for cell id photon material map\n  typedef boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n\t\t\t       Teuchos::RCP<PhotonMaterial> >\n  CellIdPhotonMaterialMap;\n\n  // Typedef for cell id electron material map\n  typedef boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n\t\t\t       Teuchos::RCP<ElectronMaterial> >\n  CellIdElectronMaterialMap;\n\npublic:\n\n  //! Add a material to the collision handler\n  static void addMaterial( \n\t      const Teuchos::RCP<NeutronMaterial>& material,\n\t      const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>&\n\t      cells_containing_material );\n\n  //! Add a material to the collision handler\n  static void addMaterial(\n\t      const Teuchos::RCP<PhotonMaterial>& material,\n\t      const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>&\n\t      cells_containing_material );\n\n  //! Add a material to the collision handler\n  static void addMaterial(\n\t      const Teuchos::RCP<NeutronMaterial>& neutron_material,\n\t      const Teuchos::RCP<PhotonMaterial>& photon_material,\n\t      const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>&\n\t      cells_containing_material );\n\n  //! Add a material to the collision handler\n  static void addMaterial(\n\t      const Teuchos::RCP<ElectronMaterial>& material,\n\t      const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>&\n\t      cells_containing_material );\n  \n  //! Check if a cell is void\n  static bool isCellVoid(const Geometry::ModuleTraits::InternalCellHandle cell,\n\t\t\t const ParticleType particle_type );\n    \n  //! Get the neutron material contained in a cell\n  static const Teuchos::RCP<NeutronMaterial>& \n  getCellNeutronMaterial( \n\t\t       const Geometry::ModuleTraits::InternalCellHandle cell );\n\n  //! Get the photon material contained in a cell\n  static const Teuchos::RCP<PhotonMaterial>&\n  getCellPhotonMaterial(\n\t\t       const Geometry::ModuleTraits::InternalCellHandle cell );\n\n  //! Get the electron material contained in a cell\n  static const Teuchos::RCP<ElectronMaterial>&\n  getCellElectronMaterial(\n\t\t       const Geometry::ModuleTraits::InternalCellHandle cell );\n\n  //! Get the total macroscopic cross section of a material\n  static double getMacroscopicTotalCrossSection( const NeutronState& particle);\n\n  //! Get the total macroscopic cross section of a material\n  static double getMacroscopicTotalCrossSection( const PhotonState& particle );\n\n  //! Get the total macroscopic cross section of a material\n  static double getMacroscopicTotalCrossSection( const ElectronState& particle );\n\n  //! Get the macroscopic cross section for a specific reaction\n  static double getMacroscopicReactionCrossSection(\n\t\t\t\t\t  const NeutronState& particle,\n\t\t\t\t\t  const NuclearReactionType reaction );\n\n  //! Get the macroscopic cross section for a specific reaction\n  static double getMacroscopicReactionCrossSection(\n\t\t\t\t      const PhotonState& particle,\n\t\t\t\t      const PhotoatomicReactionType reaction );\n\n  //! Get the macroscopic cross section for a specific reaction\n  static double getMacroscopicReactionCrossSection(\n\t\t\t\t     const PhotonState& particle,\n\t\t\t\t     const PhotonuclearReactionType reaction );\n\n  //! Get the macroscopic cross section for a specific reaction\n  static double getMacroscopicReactionCrossSection(\n\t\t\t\t      const ElectronState& particle,\n\t\t\t\t      const ElectroatomicReactionType reaction );\n\n  //! Collide with the material in a cell\n  static void collideWithCellMaterial( PhotonState& particle,\n\t\t\t\t       ParticleBank& bank,\n\t\t\t\t       const bool analogue );\n  \n  //! Collide with the material in a cell\n  static void collideWithCellMaterial( NeutronState& particle,\n\t\t\t\t       ParticleBank& bank,\n\t\t\t\t       const bool analogue );\n\n  //! Collide with the material in a cell\n  static void collideWithCellMaterial( ElectronState& particle,\n\t\t\t\t       ParticleBank& bank,\n\t\t\t\t       const bool analogue );\n\nprivate:\n  \n  // The cell id neutron material map\n  static CellIdNeutronMaterialMap master_neutron_map;\n  \n  static CellIdPhotonMaterialMap master_photon_map;\n\n  static CellIdElectronMaterialMap master_electron_map;\n};\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_COLLISION_HANDLER_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_CollisionHandler.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "52cf894dfe507bd04391bfceb0942b156e4ef331", "size": 5414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_CollisionHandler.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_CollisionHandler.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_CollisionHandler.hpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1558441558, "max_line_length": 81, "alphanum_fraction": 0.7087181382, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.018833128410427107, "lm_q1q2_score": 0.0061063666582577706}}
{"text": "/* Authors: Lutong Wang and Bangqi Xu */\n/*\n * Copyright (c) 2019, The Regents of the University of California\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 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 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 REGENTS 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 \"io/frShapeUtil.h\"\n#include <boost/icl/interval_map.hpp>\n\nnamespace fr {\n  void frRect2Poly(frRect &rectIn, boostPolygon &polyOut) {\n    frBox tmpBox;\n    rectIn.getBBox(tmpBox);\n    polyOut = boostPolygon();\n    bg::append(polyOut, boostPoint(tmpBox.left(), tmpBox.bottom()));\n    bg::append(polyOut, boostPoint(tmpBox.left(), tmpBox.top()));\n    bg::append(polyOut, boostPoint(tmpBox.right(), tmpBox.top()));\n    bg::append(polyOut, boostPoint(tmpBox.right(), tmpBox.bottom()));\n    bg::append(polyOut, boostPoint(tmpBox.left(), tmpBox.bottom()));\n  }\n\n  void frPolygon2Poly(frPolygon &polygonIn, boostPolygon &polyOut) {\n    polyOut = boostPolygon();\n    auto polyPoints = polygonIn.getPoints();\n    for (auto &point: polyPoints) {\n      bg::append(polyOut, boostPoint((int)point.x(), (int)point.y()));\n    }\n  }\n\n  void frBox2Poly(frBox &boxIn, boostPolygon &polyOut) {\n    polyOut = boostPolygon();\n    bg::append(polyOut, boostPoint(boxIn.left(), boxIn.bottom()));\n    bg::append(polyOut, boostPoint(boxIn.left(), boxIn.top()));\n    bg::append(polyOut, boostPoint(boxIn.right(), boxIn.top()));\n    bg::append(polyOut, boostPoint(boxIn.right(), boxIn.bottom()));\n    bg::append(polyOut, boostPoint(boxIn.left(), boxIn.bottom()));\n  }\n\n  void frBox2Rectangle(frBox &boxIn, Rectangle &rectOut) {\n    rectOut = Rectangle(boxIn.left(), boxIn.bottom(), boxIn.right(), boxIn.top());\n  }\n\n  void frRect2Rectangle(frRect &rectIn, Rectangle &rectOut) {\n    frBox rectInBox;\n    rectIn.getBBox(rectInBox);\n    rectOut = Rectangle(rectInBox.left(), rectInBox.bottom(), rectInBox.right(), rectInBox.top());\n  }\n\n  void frBlockage2Poly(frBlockage &blockageIn, boostPolygon &polyOut) {\n    auto points = blockageIn.getPoints();\n    polyOut = boostPolygon();\n    for (auto point: points) {\n      bg::append(polyOut, boostPoint(point.x(), point.y()));\n    }\n  }\n\n  // Use before checking overlapping\n  double frBox2BoxDist(frBox &box1, frBox &box2) {\n    frCoord xDist = std::max(0, std::max(box1.left(), box2.left()) - std::min(box1.right(), box2.right()) );\n    frCoord yDist = std::max(0, std::max(box1.bottom(), box2.bottom()) - std::min(box1.top(), box2.top()));\n    return std::sqrt(xDist * xDist + yDist * yDist);\n  }\n\n  double frBox2BoxDist(box_t &box1, box_t &box2) {\n    frCoord llx1, lly1, urx1, ury1, llx2, lly2, urx2, ury2;\n    llx1 = bg::get<bg::min_corner, 0>(box1);\n    lly1 = bg::get<bg::min_corner, 1>(box1);\n    urx1 = bg::get<bg::max_corner, 0>(box1);\n    ury1 = bg::get<bg::max_corner, 1>(box1);\n    llx2 = bg::get<bg::min_corner, 0>(box2);\n    lly2 = bg::get<bg::min_corner, 1>(box2);\n    urx2 = bg::get<bg::max_corner, 0>(box2);\n    ury2 = bg::get<bg::max_corner, 1>(box2);\n    frCoord xDist = std::max(0, std::max(llx1, llx2) - std::min(urx1, urx2));\n    frCoord yDist = std::max(0, std::max(lly1, lly2) - std::min(ury1, ury2));\n    return std::sqrt(xDist * xDist + yDist * yDist);\n  }\n\n  bool isSamePoint(boostPoint &pt1, boostPoint &pt2) {\n    auto x1 = bg::get<0>(pt1);\n    auto y1 = bg::get<1>(pt1);\n    auto x2 = bg::get<0>(pt2);\n    auto y2 = bg::get<1>(pt2);\n    return (x1 == x2 && y1 == y2);\n  }\n\n  frCoord getEdgeWidth(boostEdge &edge) {\n    auto point1 = edge.first;\n    auto point2 = edge.second;\n    auto pt1X = bg::get<0>(point1);\n    auto pt1Y = bg::get<1>(point1);\n    auto pt2X = bg::get<0>(point2);\n    auto pt2Y = bg::get<1>(point2);\n\n    if (pt1X == pt2X) {\n      return (std::abs(pt2Y - pt1Y));\n    } else if (pt1Y == pt2Y) {\n      return (std::abs(pt2X - pt1X));\n    } else {\n      std::cout << \"Warning: edge is not orthogonal\\n\";\n      return 0;\n    }\n\n  }\n\n  void polyCovering(boostPolygon &polygon, frCollection<frRect> &rects) {\n    // debug \n    // std::cout << \"  start polyCovering\\n\" << std::flush; \n    frCollection<frCoord> x, y;\n    frCollection<boostPoint> points;\n    std::set<frCoord> xIntv, yIntv;\n    std::vector<frCoord> xTick, yTick;\n    std::set<std::pair<int,int> > HSliceStart, VSliceStart;\n    std::vector<std::vector<bool> > isOccupied;\n    std::set<std::pair<int, int> > maxHSlice, maxVSlice;\n    std::set<std::tuple<int, int, int, int> > maxRectSet;\n    std::pair<int, int> tmpPoint;\n\n\n\n    \n    // exterior ring\n    auto ring = bg::exterior_ring(polygon);\n    for (auto it = ring.begin(); it != ring.end(); ++it) {\n      points.push_back(*it);\n    }\n    // interior rings\n    BOOST_FOREACH(auto & ring, bg::interior_rings(polygon)) {\n      for (auto it = ring.begin(); it != ring.end(); ++it) {\n        points.push_back(*it);\n      }\n    }\n\n    // push_back to x and y \n    for (auto &point: points) {\n      x.push_back(point.get<0>());\n      y.push_back(point.get<1>());\n    }\n    xIntv = std::set<frCoord>(x.begin(), x.end());\n    yIntv = std::set<frCoord>(y.begin(), y.end());\n\n    std::copy(xIntv.begin(), xIntv.end(), std::back_inserter(xTick));\n    std::copy(yIntv.begin(), yIntv.end(), std::back_inserter(yTick));\n\n    // std::cout << \"    polyCovering: num points = \" << points.size() << std::endl;\n    // std::cout << \"    polyCovering: |xTick| = \" << xTick.size() << \", |yTick| = \" << yTick.size() << std::endl;\n\n    isOccupied = std::vector<std::vector<bool> >(xTick.size() - 1, std::vector<bool>(yTick.size() - 1, false));\n\n    // debug \n    // std::cout << \"    start building k-map\\n\" << std::flush; \n    // build k-map\n    for (int i = 0; i < (int)xTick.size() - 1; i++) {\n      for (int j = 0; j < (int)yTick.size() - 1; j++) {\n        frCoord tempX = (xTick.at(i) + xTick.at(i + 1)) / 2;\n        frCoord tempY = (yTick.at(j) + yTick.at(j + 1)) / 2;\n        boostPoint tempPt(tempX, tempY);\n        if (bg::covered_by(tempPt, polygon)) {\n          isOccupied[i][j] = true;\n        }\n      }\n    }\n\n    // printBoolMatrix(isOccupied);\n\n    // debug \n    // std::cout << \"    start building slices\\n\" << std::flush; \n    // build slices\n    for (int i = 0; i < (int)isOccupied.size(); i++) {\n      for (int j = 0; j < (int)isOccupied[i].size(); j++) {\n        if (isOccupied[i][j] == false) {\n          continue;\n        } else {\n          // horizontal\n          // debug\n          // std::cout << \"      H slices\\n\" << std::flush;\n          if (getMaxHSlice(i, j, isOccupied, maxHSlice, tmpPoint)) {\n            // std::cout << \"        getting max H rect\\n\" << std::flush;\n            // std::cout << \"          starting point = (\" << tmpPoint.first << \", \" << tmpPoint.second << \")\\n\";\n            getMaxHRect(tmpPoint, isOccupied, maxHSlice, maxRectSet);\n            // std::cout << \"        finish getting max H rect\\n\" << std::flush;\n          }\n          // vertical\n          // debug\n          // std::cout << \"      V slices\\n\" << std::flush;\n          if (getMaxVSlice(i, j, isOccupied, maxVSlice, tmpPoint)) {\n            // std::cout << \"        getting max V rect\\n\" << std::flush;\n            // std::cout << \"          starting point = (\" << tmpPoint.first << \", \" << tmpPoint.second << \")\\n\";\n            getMaxVRect(tmpPoint, isOccupied, maxVSlice, maxRectSet);\n            // std::cout << \"        finish getting max V rect\\n\" << std::flush;\n          }\n        }\n      }\n    }\n\n    // debug \n    // std::cout << \"    start outputing result\\n\" << std::flush; \n    // std::cout << \"      num rects = \" << maxRectSet.size() << std::endl;\n    for (auto it = maxRectSet.begin(); it != maxRectSet.end(); ++it) {\n      auto &tmpTuple = *it;\n      // std::cout << \"       (\" << get<0>(tmpTuple) << \", \" << get<1>(tmpTuple) << \") -- (\" \n      //           << get<2>(tmpTuple) << \", \" << get<3>(tmpTuple) << \")\" << std::endl;\n      frBox tmpBox;\n      frRect tmpRect;\n      tmpBox.set(xTick[get<0>(tmpTuple)], yTick[get<1>(tmpTuple)], xTick[get<2>(tmpTuple) + 1], yTick[get<3>(tmpTuple) + 1]);\n      tmpRect.setBBox(tmpBox);\n      rects.push_back(tmpRect);\n    }\n\n  }\n\n  // every rect in maxRectSet is maximum among all rects seen so far\n  void maintainMaxRects(std::tuple<int, int, int, int> &newRect, std::set<std::tuple<int, int, int, int> > &maxRectSet) {\n    // std::cout << \"processNewRect of (\" << std::get<0>(newRect) << \", \" << std::get<1>(newRect) << \") -- (\" \n    //           << std::get<2>(newRect) << \", \" << std::get<3>(newRect) << \")\" << std::endl;\n\n    boostBox tmpNewRect(boostPoint(std::get<0>(newRect), std::get<1>(newRect)), boostPoint(std::get<2>(newRect), std::get<3>(newRect)));\n    \n    if (maxRectSet.size() == 0) {\n      // std::cout << \"@@@debug@@@: insert (\" << std::get<0>(newRect) << \", \" << std::get<1>(newRect) \n      //           << \") -- (\" << std::get<2>(newRect) << \",\" << std::get<3>(newRect) << \")\\n\";\n      \n      maxRectSet.insert(newRect);\n      return;\n    }\n\n    if (maxRectSet.find(newRect) != maxRectSet.end()) {\n      return;\n    }\n    \n    std::vector<std::tuple<int, int, int, int> > coveredRects;\n    // isSkip = false;\n    for (auto it = maxRectSet.begin(); it != maxRectSet.end(); it++) {\n      boostBox tmpRect(boostPoint(std::get<0>(*it), std::get<1>(*it)), boostPoint(std::get<2>(*it), std::get<3>(*it)));\n      // std::cout << \"    checking against (\" << std::get<0>(*it) << \", \" << std::get<1>(*it) << \") -- (\" \n            // << std::get<2>(*it) << \", \" << std::get<3>(*it) << \")\" << std::endl;\n      if (bg::covered_by(tmpNewRect, tmpRect)) {\n        // std::cout << \"@@@debug@@@: covered_by (\" << std::get<0>(*it) << \", \" << std::get<1>(*it) \n        //           << \") -- (\" << std::get<2>(*it) << \",\" << std::get<3>(*it) << \")\\n\";\n      \n        // newRect is strictly within some existing Rect\n        return;\n      } else if (bg::covered_by(tmpRect, tmpNewRect)) {\n        coveredRects.push_back(*it);\n        // maxRectSet.erase(it);\n        // maxRectSet.insert(newRect);\n        // break;\n      }\n    }\n\n    if (!coveredRects.empty()) {\n      for (int i = 0; i < (int)coveredRects.size(); i++) {\n        auto it = maxRectSet.find(coveredRects[i]);\n        // std::cout << \"@@@debug@@@: erase (\" << std::get<0>(coveredRects[i]) << \", \" << std::get<1>(coveredRects[i]) \n        //         << \") -- (\" << std::get<2>(coveredRects[i]) << \",\" << std::get<3>(coveredRects[i]) << \")\\n\";\n      \n        maxRectSet.erase(it);\n      }\n      \n    }\n    // std::cout << \"@@@debug@@@: insert (\" << std::get<0>(newRect) << \", \" << std::get<1>(newRect) \n    //             << \") -- (\" << std::get<2>(newRect) << \",\" << std::get<3>(newRect) << \")\\n\";\n      \n    maxRectSet.insert(newRect);\n    return;\n  }\n\n  bool processNewRect(std::tuple<int, int, int, int> &newRect, std::set<std::tuple<int, int, int, int> > &maxRectSet) {\n    // std::cout << \"processNewRect of (\" << std::get<0>(newRect) << \", \" << std::get<1>(newRect) << \") -- (\" \n    //           << std::get<2>(newRect) << \", \" << std::get<3>(newRect) << \")\" << std::endl;\n\n    boostBox tmpNewRect(boostPoint(std::get<0>(newRect), std::get<1>(newRect)), boostPoint(std::get<2>(newRect), std::get<3>(newRect)));\n    bool isChanged = true;\n    if (maxRectSet.find(newRect) != maxRectSet.end()) {\n      return false;\n    }\n    if (maxRectSet.size() == 0) {\n      // std::cout << \"@@@debug@@@: insert (\" << std::get<0>(newRect) << \", \" << std::get<1>(newRect) \n      //           << \") -- (\" << std::get<2>(newRect) << \",\" << std::get<3>(newRect) << \")\\n\";\n      maxRectSet.insert(newRect);\n\n      return true;\n    }\n    \n    isChanged = false;\n    std::vector<std::tuple<int, int, int, int> > coveredRects;\n    // isSkip = false;\n    for (auto it = maxRectSet.begin(); it != maxRectSet.end(); it++) {\n      boostBox tmpRect(boostPoint(std::get<0>(*it), std::get<1>(*it)), boostPoint(std::get<2>(*it), std::get<3>(*it)));\n      // std::cout << \"    checking against (\" << std::get<0>(*it) << \", \" << std::get<1>(*it) << \") -- (\" \n            // << std::get<2>(*it) << \", \" << std::get<3>(*it) << \")\" << std::endl;\n      if (bg::covered_by(tmpNewRect, tmpRect)) {\n        // newRect is strictly within some existing Rect\n        return false;\n      } else if (bg::covered_by(tmpRect, tmpNewRect)) {\n        coveredRects.push_back(*it);\n        // maxRectSet.erase(it);\n        // maxRectSet.insert(newRect);\n        isChanged = true;\n        break;\n      }\n    }\n    if (isChanged == true) {\n      for (int i = 0; i < (int)coveredRects.size(); i++) {\n        auto it = maxRectSet.find(coveredRects[i]);\n        maxRectSet.erase(it);\n      }\n      return true;\n    }\n\n    return false;\n  }\n\n  bool getMaxHSlice(int xIdx, int yIdx, std::vector<std::vector<bool> > &isOccupied, std::set<std::pair<int, int> > &sliceSet, std::pair<int, int> &retPt) {\n    // std::cout << \"getMaxHSlice\" << std::endl;\n    int xl, xh;\n    xl = xh = xIdx;\n    while (xl - 1 >= 0 && isOccupied[xl - 1][yIdx] == true) {\n      xl--;\n    }\n    while (xh + 1 < (int)isOccupied.size() && isOccupied[xh + 1][yIdx] == true) {\n      xh++;\n    }\n    std::pair<int, int> tmpPt = std::make_pair(xl, yIdx);\n    retPt = tmpPt;\n    if (sliceSet.find(tmpPt) != sliceSet.end()) {\n      return false;\n    } else {\n      sliceSet.insert(tmpPt);\n      return true;\n    }\n  }\n\n\n\n  bool getMaxVSlice(int xIdx, int yIdx, std::vector<std::vector<bool> > &isOccupied, std::set<std::pair<int, int> > &sliceSet, std::pair<int, int> &retPt) {\n    // std::cout << \"getMaxVSlice\" << std::endl;\n    int yl, yh;\n    yl = yh = yIdx;\n    while (yl - 1 >= 0 && isOccupied[xIdx][yl - 1] == true) {\n      yl--;\n    }\n    while (yh + 1 < (int)isOccupied[xIdx].size() && isOccupied[xIdx][yh + 1] == true) {\n      yh++;\n    }\n    std::pair<int, int> tmpPt = std::make_pair(xIdx, yl);\n    retPt = tmpPt;\n    if (sliceSet.find(tmpPt) != sliceSet.end()) {\n      return false;\n    } else {\n      sliceSet.insert(tmpPt);\n      return true;\n    }\n  }\n\n\n  void getMaxHRect(std::pair<int, int> startPt, std::vector<std::vector<bool> > &isOccupied, std::set<std::pair<int, int> > &sliceSet, std::set<std::tuple<int, int, int, int> > &maxRectSet) {\n    // std::cout << \"getMaxHRect start pnt = (\" << startPt.first << \", \" << startPt.second << \")\" << std::endl;\n    int xl, xh, yl, yh;\n    xl = xh = startPt.first;\n    yl = yh = startPt.second;\n    while (xh + 1 < (int)isOccupied.size() && isOccupied[xh + 1][startPt.second] == true) {\n      xh++;\n    }\n    \n\n    // upward\n    bool flag = true;\n    while (flag) {\n      // std::cout << \"      upward\\n\" << std::flush;\n      if (yh + 1 < (int)isOccupied[xl].size()) {\n        for (int tempX = xl; tempX <= xh; tempX++) {\n          if (isOccupied[tempX][yh + 1] == false) {\n            flag = false;\n            break;\n          }\n        }\n        if (flag == true) {\n          yh++;\n        }\n      } else {\n        flag = false;\n        break;\n      }\n    }\n\n    // downward\n    flag = true;\n    while (flag) {\n      // std::cout << \"      downward\\n\" << std::flush;\n      if (yl - 1 >= 0) {\n        // yl--;\n        for (int tempX = xl; tempX <= xh; tempX++) {\n          if (isOccupied[tempX][yl - 1] == false) {\n            flag = false;\n            break;\n          }\n        }\n        if (flag == true) {\n          yl--;\n        }\n      } else {\n        flag = false;\n        break;\n      }\n    }\n    // std::cout << \"xl = \" << xl << \", \" << \"xh = \" << xh << std::endl;\n    // std::cout << \"yl = \" << yl << \", yh = \" << yh << std::endl;\n    std::tuple<int, int, int, int> tmpTuple = std::make_tuple(xl, yl, xh, yh);\n    // printRect(tmpTuple);\n    maintainMaxRects(tmpTuple, maxRectSet);\n    // return (maintainRects(tmpTuple, maxRectSet));\n\n  }\n\n\n  void getMaxVRect(std::pair<int, int> startPt, std::vector<std::vector<bool> > &isOccupied, std::set<std::pair<int, int> > &sliceSet, std::set<std::tuple<int, int, int, int> > &maxRectSet) {\n    // std::cout << \"getMaxVRect start pnt = (\" << startPt.first << \", \" << startPt.second << \")\" << std::endl;\n    int xl, xh, yl, yh;\n    xl = xh = startPt.first;\n    yl = yh = startPt.second;\n    while (yh + 1 < (int)isOccupied[startPt.first].size() && isOccupied[startPt.first][yh + 1]) {\n      yh++;\n    }\n\n    // upward\n    bool flag = true;\n    while (flag) {\n      if (xh + 1 < (int)isOccupied.size()) {\n        // xh++;\n        for (int tempY = yl; tempY <= yh; tempY++) {\n          if (isOccupied[xh + 1][tempY] == false) {\n            flag = false;\n            break;\n          }\n        }\n        if (flag == true) {\n          xh++;\n        }\n      } else {\n        flag = false;\n      }\n    }\n    // downward\n    flag = true;\n    while (flag) {\n      if (xl - 1 >= 0) {\n        // xl--;\n        for (int tempY = yl; tempY <= yh; tempY++) {\n          if (isOccupied[xl - 1][tempY] == false) {\n            flag = false;\n            break;\n          }\n        }\n        if (flag == true) {\n          xl--;\n        }\n      } else {\n        flag = false;\n      }\n    }\n    \n    // std::cout << \"xl = \" << xl << \", \" << \"xh = \" << xh << std::endl;\n    // std::cout << \"yl = \" << yl << \", \" << \"yh = \" << yh << std::endl;\n    std::tuple<int, int, int, int> tmpTuple = std::make_tuple(xl, yl, xh, yh);\n    maintainMaxRects(tmpTuple, maxRectSet);\n    // return (processNewRect(tmpTuple, maxRectSet));\n\n  }\n\n  void getPolyWithHole(const std::vector<Point> &vertices, Polygon &outline, std::vector<Polygon> &holes) {\n    typedef boost::icl::interval_map<int, int> IntvMap;\n    std::vector<Polygon> polys;\n    std::vector<std::pair<Point, Point> > edges;\n    std::vector<bool> validEdges;\n    std::map<int, IntvMap> horzIntv2Edge, vertIntv2Edge;\n    for (int i = 0; i < (int)vertices.size(); ++i) {\n      Point currPt = vertices[i];\n      Point nextPt = vertices[(i + 1) % vertices.size()];\n      edges.push_back(std::make_pair(currPt, nextPt));\n      validEdges.push_back(true);\n\n      int edgeIdx = -1;\n      bool isHorizontal = true;\n      auto itResHorz = horzIntv2Edge[nextPt.y()].equal_range(boost::icl::interval<int>::closed(nextPt.x(), nextPt.x()));\n      int horzCnt = 0;\n      for (auto it = itResHorz.first; it != itResHorz.second; ++it) {\n        if (horzCnt > 0) {\n          std::cout << \"Error: more than one interval found\\n\";\n          break;\n        }\n        if ((it->second - 1) > edgeIdx && validEdges[(it->second  - 1)] == true) {\n          edgeIdx = it->second - 1;\n          isHorizontal = true;\n        }\n        horzCnt++;\n      }\n      // vert\n      auto itResVert = vertIntv2Edge[nextPt.x()].equal_range(boost::icl::interval<int>::closed(nextPt.y(), nextPt.y()));\n      int vertCnt = 0;\n      for (auto it = itResVert.first; it != itResVert.second; ++it) {\n        if (vertCnt > 0) {\n          std::cout << \"Error: more than one interval found\\n\";\n          break;\n        }\n        if ((it->second  - 1) > edgeIdx && validEdges[(it->second  - 1)] == true) {\n          edgeIdx = it->second - 1;\n          isHorizontal = false;\n        }\n        vertCnt++;\n      }\n      // get poly\n      if (edgeIdx == -1) {\n        ;\n      } else if ((i - edgeIdx) > 2) {\n        std::vector<Point> vertices;\n        int edgeCnt = 0;\n        for (int currEdgeIdx = edgeIdx; currEdgeIdx <= i; ++currEdgeIdx) {\n          if (validEdges[currEdgeIdx] == false) {\n            continue;\n          }\n          edgeCnt++;\n          vertices.push_back(edges[currEdgeIdx].second);\n          if (currEdgeIdx == edgeIdx) {\n            if (nextPt == edges[currEdgeIdx].first) {\n              // cout << \"  invalidate \" << currEdgeIdx << endl;\n              validEdges[currEdgeIdx] = false;\n            } else {\n              Point tmpEndPoint = edges[currEdgeIdx].second;\n              edges[currEdgeIdx].second = nextPt;\n              if (isHorizontal) {\n                horzIntv2Edge[nextPt.y()] -= std::make_pair(boost::icl::interval<int>::right_open(std::min(tmpEndPoint.x(), nextPt.x()), std::max(tmpEndPoint.x(), nextPt.x())), edgeIdx);\n                // cout << \"  erase y = \" << nextPt.y() << \", x = [\" << min(tmpEndPoint.x(), nextPt.x()) << \", \" << max(tmpEndPoint.x(), nextPt.x()) << \"] edgeIdx = \" << edgeIdx << \"\\n\";\n              } else {\n                vertIntv2Edge[nextPt.x()] -= std::make_pair(boost::icl::interval<int>::right_open(std::min(tmpEndPoint.y(), nextPt.y()), std::max(tmpEndPoint.y(), nextPt.y())), edgeIdx);\n                // cout << \"  erase x = \" << nextPt.x() << \", x = [\" << min(tmpEndPoint.y(), nextPt.y()) << \", \" << max(tmpEndPoint.y(), nextPt.y()) << \"] edgeIdx = \" << edgeIdx << \"\\n\";\n              }\n            }\n          } else {\n            // cout << \"  invalidate \" << currEdgeIdx << endl;\n            validEdges[currEdgeIdx] = false;\n          }\n        }\n        if (edgeCnt > 2) {\n          // cout << \"poly startIdx = \" << edgeIdx << \", endIdx = \" << i << endl;\n          Polygon tmpPoly;\n          Point pt1, pt2, pt3;\n          pt1 = vertices.back();\n          pt2 = vertices.front();\n          pt3 = vertices[vertices.size() - 2];\n          // cout << \"xxx2\\n\";\n\n          if ((pt1.x() == pt2.x() && pt2.x() == pt3.x()) ||\n              (pt1.y() == pt2.y() && pt2.y() == pt3.y())) {\n            vertices.pop_back();\n          }\n          set_points(tmpPoly, vertices.begin(), vertices.end());\n          polys.push_back(tmpPoly);\n        }\n      } else {\n        // cout << \"erase startIdx = \" << edgeIdx << \", endIdx = \" << i << endl;\n        for (int currEdgeIdx = edgeIdx; currEdgeIdx <= i; ++currEdgeIdx) {\n          if (validEdges[currEdgeIdx] == false) {\n            continue;\n          }\n          if (currEdgeIdx == edgeIdx) {\n            if (nextPt == edges[currEdgeIdx].first) {\n              validEdges[currEdgeIdx] = false;\n            } else {\n              edges[currEdgeIdx].second = nextPt;\n            }\n          } else {\n            validEdges[currEdgeIdx] = false;\n          }\n        }\n      }\n\n      // insert to interval map\n      if (edgeIdx == -1) {\n        if (currPt.x() == nextPt.x()) {\n          auto edgeIntv = boost::icl::interval<int>::closed(std::min(currPt.y(), nextPt.y()), std::max(currPt.y(), nextPt.y()));\n          vertIntv2Edge[nextPt.x()] += std::make_pair(edgeIntv, i + 1);\n          // cout << \"add x = \" << currPt.x() << \", y = [\" << edgeIntv.lower() << \", \" << edgeIntv.upper() << \"]\\n\";\n        } \n        if (currPt.y() == nextPt.y()) {\n          auto edgeIntv = boost::icl::interval<int>::closed(std::min(currPt.x(), nextPt.x()), std::max(currPt.x(), nextPt.x()));\n          horzIntv2Edge[nextPt.y()] += std::make_pair(edgeIntv, i + 1);\n          // cout << \"add y = \" << currPt.y() << \", x = [\" << edgeIntv.lower() << \", \" << edgeIntv.upper() << \"]\\n\";\n        }\n      }\n\n    }\n    \n    std::vector<Point> tmpPts;\n    for (int currEdgeIdx = 0; currEdgeIdx < int(edges.size()); ++currEdgeIdx) {\n      if (validEdges[currEdgeIdx] == false) {\n        continue;\n      }\n      tmpPts.push_back(edges[currEdgeIdx].second);\n      // std::cout << \"pushing (\" << tmpPts.back().x() << \", \" << tmpPts.back().y() << \"\\n\";\n    }\n\n    for (int i = 0; i < (int)polys.size() - 1; ++i) {\n      holes.push_back(polys[i]);\n    }\n    if (polys.size() > 0) {\n      outline = polys.back();\n    }\n\n\n  }\n\n  bool isColinear(const Point &pt1, const Point &pt2, const Point &pt3) {\n    return ((pt1.x() == pt2.x() && pt2.x() == pt3.x()) ||\n            (pt1.y() == pt2.y() && pt2.y() == pt3.y()));\n  }\n\n  void getNonColinearVertex(const std::vector<Point> &in, std::vector<Point> &out) {\n    int inSize = in.size();\n    int cornerIdx = -1;\n    int startIdx, endIdx;\n    Point lastCorner;\n    std::vector<int> cornerIdxs;\n    if (inSize < 3) {\n      out = in;\n      return;\n    }\n    Point tmpPt1 = in[0];\n    Point tmpPt2 = in[1];\n    Point tmpPt3;\n    for (int i = 2; i < inSize; ++i) {\n      tmpPt3 = in[i];\n      if (!isColinear(tmpPt1, tmpPt2, tmpPt3)) {\n        cornerIdx = i - 1;\n        break;\n      }\n    }\n    if (cornerIdx == -1) {\n      out.push_back(in.front());\n      out.push_back(in.back());\n      return;\n    } else {\n      cornerIdxs.push_back(cornerIdx);\n      lastCorner = in[cornerIdx];\n    }\n    //\n    for (int i = cornerIdx+1; i < cornerIdx + inSize; ++i) {\n      startIdx = i % inSize;\n      tmpPt1 = in[startIdx];\n      // find next corner\n      for (int j = i + 1; j <= cornerIdx + inSize; ++j) {\n        endIdx = j % inSize;\n        tmpPt2 = in[endIdx];\n        if (!isColinear(lastCorner, tmpPt1, tmpPt2)) {\n          int lastCornerIdx = (endIdx + inSize - 1) % inSize;\n          cornerIdxs.push_back(lastCornerIdx);\n          lastCorner = in[lastCornerIdx];\n          i = j-1;\n          break;\n        }\n      }\n    }\n    for (int i = 0; i < (int)cornerIdxs.size(); ++i) {\n      out.push_back(in[cornerIdxs[i]]);\n    }\n    return;\n\n  }\n\n  void getPolyWithHole_new(const Polygon &polyIn, std::vector<Polygon> &polys) {\n    using namespace boost::polygon::operators;\n    using PolygonX = boost::polygon::polygon_90_with_holes_data<int>;\n    using PolygonSetData = boost::polygon::polygon_90_set_data<int>;\n    PolygonSetData psd;\n    psd += polyIn;\n    std::vector<PolygonX> psx;\n    psd.get(psx);\n    \n    for (auto &poly: psx) {\n      Polygon outlinePoly;\n      std::vector<Point> outlinePolyVtx;\n      for (auto it = poly.begin(); it != poly.end(); it++) {\n        outlinePolyVtx.push_back(*it);\n      }\n      boost::polygon::set_points(outlinePoly, outlinePolyVtx.rbegin(), outlinePolyVtx.rend());\n      for (auto it1 = poly.begin_holes(); it1 != poly.end_holes(); it1++) {\n        std::vector<Point> vtx;\n        Polygon holePoly;\n        for (auto it2 = (*it1).begin(); it2 != (*it1).end(); it2++) {\n          vtx.push_back(*it2);\n        }\n        boost::polygon::set_points(holePoly, vtx.rbegin(), vtx.rend());\n        polys.push_back(holePoly);\n      }\n      polys.push_back(outlinePoly);\n    }\n  }\n\n  void getPolyWithHole(const Polygon &polyIn, std::vector<Polygon> &polys) {\n    typedef boost::icl::interval_map<int, int> IntvMap;\n    std::vector<Point> origVertices, vertices;\n    for (auto ptIt = begin_points(polyIn); ptIt != end_points(polyIn); ++ptIt) {\n      origVertices.push_back(*ptIt);\n    }\n\n    // getNonColinearVertex(origVertices, vertices);\n    vertices = origVertices;\n    std::vector<std::pair<Point, Point> > edges;\n    std::vector<bool> validEdges;\n    std::map<int, IntvMap> horzIntv2Edge, vertIntv2Edge;\n    for (int i = 0; i < (int)vertices.size(); ++i) {\n      Point currPt = vertices[i];\n      Point nextPt = vertices[(i + 1) % vertices.size()];\n      edges.push_back(std::make_pair(currPt, nextPt));\n      validEdges.push_back(true);\n\n      int edgeIdx = -1;\n      bool isHorizontal = true;\n      auto itResHorz = horzIntv2Edge[nextPt.y()].equal_range(boost::icl::interval<int>::closed(nextPt.x(), nextPt.x()));\n      int horzCnt = 0;\n      for (auto it = itResHorz.first; it != itResHorz.second; ++it) {\n        if (horzCnt > 0) {\n          std::cout << \"Error: more than one interval found\\n\";\n          break;\n        }\n        if ((it->second - 1) > edgeIdx && validEdges[(it->second  - 1)] == true) {\n          edgeIdx = it->second - 1;\n          isHorizontal = true;\n        }\n        horzCnt++;\n      }\n      // vert\n      auto itResVert = vertIntv2Edge[nextPt.x()].equal_range(boost::icl::interval<int>::closed(nextPt.y(), nextPt.y()));\n      int vertCnt = 0;\n      for (auto it = itResVert.first; it != itResVert.second; ++it) {\n        if (vertCnt > 0) {\n          std::cout << \"Error: more than one interval found\\n\";\n          break;\n        }\n        if ((it->second  - 1) > edgeIdx && validEdges[(it->second  - 1)] == true) {\n          edgeIdx = it->second - 1;\n          isHorizontal = false;\n        }\n        vertCnt++;\n      }\n      // get poly\n      if (edgeIdx == -1) {\n        ;\n      } else if ((i - edgeIdx) > 2) {\n        // std::cout << \"push new poly\\n\";\n        std::vector<Point> vertices;\n        int edgeCnt = 0;\n        for (int currEdgeIdx = edgeIdx; currEdgeIdx <= i; ++currEdgeIdx) {\n          if (validEdges[currEdgeIdx] == false) {\n            continue;\n          }\n          if (vertices.size() < 2) {\n            edgeCnt++;\n            vertices.push_back(edges[currEdgeIdx].second);\n            // std::cout << \"pushing (\" << vertices.back().x() / 2000.0 << \", \" << vertices.back().y() / 2000.0 << \")\\n\";\n          } else if (!isColinear(vertices.back(), vertices[vertices.size() - 2], edges[currEdgeIdx].second)) {\n            edgeCnt++;\n            vertices.push_back(edges[currEdgeIdx].second);\n            // std::cout << \"pushing (\" << vertices.back().x() / 2000.0 << \", \" << vertices.back().y() / 2000.0 << \")\\n\";\n          } else {\n            // std::cout << \"pop (\" << vertices.back().x() / 2000.0 << \", \" << vertices.back().y() / 2000.0 << \")\\n\";\n            vertices.pop_back();\n            vertices.push_back(edges[currEdgeIdx].second);\n            // std::cout << \"push (\" << vertices.back().x() / 2000.0 << \", \" << vertices.back().y() / 2000.0 << \")\\n\";\n          }\n          if (currEdgeIdx == edgeIdx) {\n            if (nextPt == edges[currEdgeIdx].first) {\n              // cout << \"  invalidate \" << currEdgeIdx << endl;\n              validEdges[currEdgeIdx] = false;\n            } else {\n              Point tmpEndPoint = edges[currEdgeIdx].second;\n              edges[currEdgeIdx].second = nextPt;\n              if (isHorizontal) {\n                horzIntv2Edge[nextPt.y()] -= std::make_pair(boost::icl::interval<int>::right_open(std::min(tmpEndPoint.x(), nextPt.x()), std::max(tmpEndPoint.x(), nextPt.x())), edgeIdx);\n                // cout << \"  erase y = \" << nextPt.y() << \", x = [\" << min(tmpEndPoint.x(), nextPt.x()) << \", \" << max(tmpEndPoint.x(), nextPt.x()) << \"] edgeIdx = \" << edgeIdx << \"\\n\";\n              } else {\n                vertIntv2Edge[nextPt.x()] -= std::make_pair(boost::icl::interval<int>::right_open(std::min(tmpEndPoint.y(), nextPt.y()), std::max(tmpEndPoint.y(), nextPt.y())), edgeIdx);\n                // cout << \"  erase x = \" << nextPt.x() << \", x = [\" << min(tmpEndPoint.y(), nextPt.y()) << \", \" << max(tmpEndPoint.y(), nextPt.y()) << \"] edgeIdx = \" << edgeIdx << \"\\n\";\n              }\n            }\n          } else {\n            // cout << \"  invalidate \" << currEdgeIdx << endl;\n            validEdges[currEdgeIdx] = false;\n          }\n        }\n        if (edgeCnt > 2) {\n          // cout << \"poly startIdx = \" << edgeIdx << \", endIdx = \" << i << endl;\n          Polygon tmpPoly;\n          Point pt1, pt2, pt3;\n          pt1 = vertices.back();\n          pt2 = vertices.front();\n          pt3 = vertices[vertices.size() - 2];\n          // cout << \"xxx2\\n\";\n\n          if ((pt1.x() == pt2.x() && pt2.x() == pt3.x()) ||\n              (pt1.y() == pt2.y() && pt2.y() == pt3.y())) {\n            vertices.pop_back();\n          }\n          set_points(tmpPoly, vertices.begin(), vertices.end());\n          polys.push_back(tmpPoly);\n        }\n      } else {\n        // cout << \"erase startIdx = \" << edgeIdx << \", endIdx = \" << i << endl;\n        for (int currEdgeIdx = edgeIdx; currEdgeIdx <= i; ++currEdgeIdx) {\n          if (validEdges[currEdgeIdx] == false) {\n            continue;\n          }\n          if (currEdgeIdx == edgeIdx) {\n            if (nextPt == edges[currEdgeIdx].first) {\n              validEdges[currEdgeIdx] = false;\n            } else {\n              edges[currEdgeIdx].second = nextPt;\n            }\n          } else {\n            validEdges[currEdgeIdx] = false;\n          }\n        }\n      }\n\n      // insert to interval map\n      if (edgeIdx == -1) {\n        // vertical\n        if (currPt.x() == nextPt.x()) {\n          // fix bug for the case where the new interval intersects with old interval\n          auto edgeIntv = boost::icl::interval<int>::closed(std::min(currPt.y(), nextPt.y()), std::max(currPt.y(), nextPt.y()));\n          auto itResVert = vertIntv2Edge[nextPt.x()].equal_range(edgeIntv);\n          std::vector<std::pair<int, int> > intvPairs;\n          for (auto it = itResVert.first; it != itResVert.second; ++it) {\n            auto &ovlpIntv = it->first;\n            it->second = 0;\n            intvPairs.push_back(std::make_pair(ovlpIntv.lower(), ovlpIntv.upper()));\n          }\n          for (auto &intvPair: intvPairs) {\n            vertIntv2Edge[nextPt.x()] -= std::make_pair(boost::icl::interval<int>::right_open(intvPair.first, intvPair.second), -i - 1);\n          }\n          vertIntv2Edge[nextPt.x()] += std::make_pair(edgeIntv, i + 1);\n          // cout << \"add x = \" << currPt.x() << \", y = [\" << edgeIntv.lower() << \", \" << edgeIntv.upper() << \"]\\n\";\n        } \n        if (currPt.y() == nextPt.y()) {\n          // horizontal\n          auto edgeIntv = boost::icl::interval<int>::closed(std::min(currPt.x(), nextPt.x()), std::max(currPt.x(), nextPt.x()));\n          auto itResHorz = horzIntv2Edge[nextPt.y()].equal_range(edgeIntv);\n          std::vector<std::pair<int, int> > intvPairs;\n          for (auto it = itResHorz.first; it != itResHorz.second; ++it) {\n            auto &ovlpIntv = it->first;\n            it->second = 0;\n            intvPairs.push_back(std::make_pair(ovlpIntv.lower(), ovlpIntv.upper()));\n          }\n          for (auto &intvPair: intvPairs) {\n            horzIntv2Edge[nextPt.y()] -= std::make_pair(boost::icl::interval<int>::right_open(intvPair.first, intvPair.second), -i - 1);\n          }\n          horzIntv2Edge[nextPt.y()] += std::make_pair(edgeIntv, i + 1);\n          // cout << \"add y = \" << currPt.y() << \", x = [\" << edgeIntv.lower() << \", \" << edgeIntv.upper() << \"]\\n\";\n        }\n      }\n\n    }\n    \n    // std::vector<Point> tmpPts;\n    // for (int currEdgeIdx = 0; currEdgeIdx < edges.size(); ++currEdgeIdx) {\n    //   if (validEdges[currEdgeIdx] == false) {\n    //     continue;\n    //   }\n    //   tmpPts.push_back(edges[currEdgeIdx].second);\n    //   // std::cout << \"pushing (\" << tmpPts.back().x() << \", \" << tmpPts.back().y() << \"\\n\";\n    // }\n\n    // for (int i = 0; i < (int)polys.size() - 1; ++i) {\n    //   holes.push_back(polys[i]);\n    // }\n    // if (polys.size() > 0) {\n    //   outline = polys.back();\n    // }\n\n\n  }\n\n}\n\n\n", "meta": {"hexsha": "f57742b5521ea7e8dc7426df91908a17793610c3", "size": 35318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/io/frShapeUtil.cpp", "max_stars_repo_name": "killruana/TritonRoute", "max_stars_repo_head_hexsha": "9afba7c5e22d68a5668cab330906efbb8767fe0f", "max_stars_repo_licenses": ["CC-BY-3.0", "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/io/frShapeUtil.cpp", "max_issues_repo_name": "killruana/TritonRoute", "max_issues_repo_head_hexsha": "9afba7c5e22d68a5668cab330906efbb8767fe0f", "max_issues_repo_licenses": ["CC-BY-3.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/io/frShapeUtil.cpp", "max_forks_repo_name": "killruana/TritonRoute", "max_forks_repo_head_hexsha": "9afba7c5e22d68a5668cab330906efbb8767fe0f", "max_forks_repo_licenses": ["CC-BY-3.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T11:01:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T11:01:43.000Z", "avg_line_length": 38.8964757709, "max_line_length": 191, "alphanum_fraction": 0.5291069709, "num_tokens": 10482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224196, "lm_q2_score": 0.028436035206176487, "lm_q1q2_score": 0.006104972752339704}}
{"text": "//=======================================================================\n// Copyright 2014-2015 David Simmons-Duffin.\n// Distributed under the MIT License.\n// (See accompanying file LICENSE or copy at\n//  http://opensource.org/licenses/MIT)\n//=======================================================================\n\n\n#include <iostream>\n#include <ostream>\n#include <sstream>\n#include \"omp.h\"\n#include \"boost/archive/text_oarchive.hpp\"\n#include \"boost/archive/text_iarchive.hpp\"\n//Tweak to allow Ubuntu-14.04/gcc-4.8.4 and similar environments to compile\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n#include <boost/filesystem.hpp>\n#undef BOOST_NO_CXX11_SCOPED_ENUMS\n#include \"boost/filesystem/fstream.hpp\"\n#include \"boost/date_time/posix_time/posix_time.hpp\"\n#include \"SDPSolver.h\"\n#include \"serialize.h\"\n#include \"Timers.h\"\n\nusing boost::filesystem::path;\nusing boost::posix_time::time_duration;\nusing boost::posix_time::microseconds;\nusing std::cout;\n\nostream& operator<<(ostream& os, const SDPSolverParameters& p) {\n  os << std::boolalpha;\n  os << \"maxIterations                = \" << p.maxIterations                << endl;\n  os << \"maxRuntime                   = \" << p.maxRuntime                   << endl;\n  os << \"checkpointInterval           = \" << p.checkpointInterval           << endl;\n  os << \"noFinalCheckpoint            = \" << p.noFinalCheckpoint            << endl;\n  os << \"findPrimalFeasible           = \" << p.findPrimalFeasible           << endl;\n  os << \"findDualFeasible             = \" << p.findDualFeasible             << endl;\n  os << \"detectPrimalFeasibleJump     = \" << p.detectPrimalFeasibleJump     << endl;\n  os << \"detectDualFeasibleJump       = \" << p.detectDualFeasibleJump       << endl;\n  os << \"precision(actual)            = \" << p.precision << \"(\" << mpf_get_default_prec() << \")\" << endl;\n  os << \"maxThreads(using)            = \" << p.maxThreads << \"(\" << omp_get_max_threads() << \")\" << endl;\n  os << \"dualityGapThreshold          = \" << p.dualityGapThreshold          << endl;\n  os << \"primalErrorThreshold         = \" << p.primalErrorThreshold         << endl;\n  os << \"dualErrorThreshold           = \" << p.dualErrorThreshold           << endl;\n  os << \"initialMatrixScalePrimal     = \" << p.initialMatrixScalePrimal     << endl;\n  os << \"initialMatrixScaleDual       = \" << p.initialMatrixScaleDual       << endl;\n  os << \"feasibleCenteringParameter   = \" << p.feasibleCenteringParameter   << endl;\n  os << \"infeasibleCenteringParameter = \" << p.infeasibleCenteringParameter << endl;\n  os << \"stepLengthReduction          = \" << p.stepLengthReduction          << endl;\n  os << \"choleskyStabilizeThreshold   = \" << p.choleskyStabilizeThreshold   << endl;\n  os << \"maxComplementarity           = \" << p.maxComplementarity           << endl;\n  return os;\n}\n\nostream &operator<<(ostream& os, const SDPSolverTerminateReason& r) {\n  switch (r) {\n  case PrimalDualOptimal:\n    os << \"found primal-dual optimal solution\";\n    break;\n  case PrimalFeasible:\n    os << \"found primal feasible solution\";\n    break;\n  case DualFeasible:\n    os << \"found dual feasible solution\";\n    break;\n  case PrimalFeasibleJumpDetected:\n    os << \"primal feasible jump detected\";\n    break;\n  case DualFeasibleJumpDetected:\n    os << \"dual feasible jump detected\";\n    break;\n  case MaxIterationsExceeded:\n    os << \"maxIterations exceeded\";\n    break;\n  case MaxRuntimeExceeded:\n    os << \"maxRuntime exceeded\";\n    break;\n  case MaxComplementarityExceeded:\n    os << \"maxComplementarity exceeded\";\n    break;\n  }\n  return os;\n}\n\nvoid SDPSolver::printHeader() {\n  cout << \"\\n     time      mu        P-obj       D-obj      gap         P-err       D-err      P-step   D-step   beta  dim/stabilized\\n\";\n  cout << \"-------------------------------------------------------------------------------------------------------------------------\\n\";\n}\n\nvoid SDPSolver::printIteration(int iteration,\n                               Real mu,\n                               Real primalStepLength,\n                               Real dualStepLength,\n                               Real betaCorrector) {\n  time_duration td(microseconds(timers[\"Solver runtime\"].elapsed().wall)/1000);\n  std::stringstream ss;\n  ss << td;\n  gmp_fprintf(stdout,\n              \"%3d  %s  %-8.1Fe %-+11.2Fe %-+11.2Fe %-9.2Fe  %-+10.2Fe  %-+10.2Fe  %-8.3Fg %-8.3Fg %-4.2Fg  %d/%d\",\n              iteration,\n              ss.str().substr(0, 8).c_str(),\n              mu.get_mpf_t(),\n              primalObjective.get_mpf_t(),\n              dualObjective.get_mpf_t(),\n              dualityGap.get_mpf_t(),\n              primalError.get_mpf_t(),\n              dualError.get_mpf_t(),\n              primalStepLength.get_mpf_t(),\n              dualStepLength.get_mpf_t(),\n              betaCorrector.get_mpf_t(),\n              static_cast<int>(sdp.dualObjective.size()),\n              Q.rows);\n  cout << endl;\n}\n\nvoid backupCheckpointFile(path const& checkpointFile) {\n  path backupFile(checkpointFile);\n  backupFile.replace_extension(\".ck.bk\");\n  cout << \"Backing up checkpoint to: \" << backupFile << endl;\n  copy_file(checkpointFile, backupFile, boost::filesystem::copy_option::overwrite_if_exists);\n}\n\nvoid SDPSolver::saveCheckpoint(const path &checkpointFile) {\n  if (exists(checkpointFile))\n    backupCheckpointFile(checkpointFile);\n  boost::filesystem::ofstream ofs(checkpointFile);\n  boost::archive::text_oarchive ar(ofs);\n  cout << \"Saving checkpoint to    : \" << checkpointFile << endl;\n  boost::serialization::serializeSDPSolverState(ar, x, X, y, Y);\n  timers[\"Last checkpoint\"].start();\n}\n\nvoid SDPSolver::loadCheckpoint(const path &checkpointFile) {\n  boost::filesystem::ifstream ifs(checkpointFile);\n  boost::archive::text_iarchive ar(ifs);\n  cout << \"Loading checkpoint from : \" << checkpointFile << endl;\n  boost::serialization::serializeSDPSolverState(ar, x, X, y, Y);\n}\n\nvoid SDPSolver::saveSolution(const SDPSolverTerminateReason terminateReason, const path &outFile) {\n  boost::filesystem::ofstream ofs(outFile);\n  float runtime = static_cast<float>(timers[\"Solver runtime\"].elapsed().wall)/1000000000;\n  cout << \"Saving solution to      : \" << outFile << endl;\n  ofs.precision(static_cast<int>(primalObjective.get_prec() * 0.31 + 5));\n  ofs << \"terminateReason = \\\"\" << terminateReason << \"\\\";\\n\";\n  ofs << \"primalObjective = \" << primalObjective   << \";\\n\";\n  ofs << \"dualObjective   = \" << dualObjective     << \";\\n\";\n  ofs << \"dualityGap      = \" << dualityGap        << \";\\n\";\n  ofs << \"primalError     = \" << primalError       << \";\\n\";\n  ofs << \"dualError       = \" << dualError         << \";\\n\";\n  ofs << \"runtime         = \" << runtime           << \";\\n\";\n  ofs << \"y = \" << y << \";\\n\";\n  // ofs << \"Y = \" << Y << \";\\n\";\n  ofs << \"x = \" << x << \";\\n\";\n  // ofs << \"X = \" << X << \";\\n\";\n}\n", "meta": {"hexsha": "8a8ef7c8c4d3ae4a1e5b6bfa52f452df095346c7", "size": 6782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SDPSolverIO.cpp", "max_stars_repo_name": "rajeeves/sdpb", "max_stars_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SDPSolverIO.cpp", "max_issues_repo_name": "rajeeves/sdpb", "max_issues_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SDPSolverIO.cpp", "max_forks_repo_name": "rajeeves/sdpb", "max_forks_repo_head_hexsha": "374be89b3dcb9690296641bafefcb154194d6cd2", "max_forks_repo_licenses": ["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.1974522293, "max_line_length": 138, "alphanum_fraction": 0.5813919198, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091975234373585, "lm_q2_score": 0.02635535102983882, "lm_q1q2_score": 0.006085971132742604}}
{"text": "/* Copyright 2018 Nils Bore (nbore@kth.se)\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * 2. 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 * 3. Neither the name of the copyright holder nor the names of its contributors may be used 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 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <data_tools/gsf_data.h>\n\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n#include <boost/date_time.hpp>\n#undef BOOST_NO_CXX11_SCOPED_ENUMS\n#include <gsf.h>\n#include <data_tools/lat_long_utm.h>\n\nusing namespace std;\n\nnamespace gsf_data {\n\nusing namespace std_data;\nusing namespace csv_data;\n\nvoid match_sound_speeds(gsf_mbes_ping::PingsT& pings, gsf_sound_speed::SpeedsT& speeds)\n{\n\n    std::stable_sort(pings.begin(), pings.end(), [](const gsf_mbes_ping& ping1, const gsf_mbes_ping& ping2) {\n        return ping1.time_stamp_ < ping2.time_stamp_;\n    });\n    std::stable_sort(speeds.begin(), speeds.end(), [](const gsf_sound_speed& speed1, const gsf_sound_speed& speed2) {\n        return speed1.time_stamp_ < speed2.time_stamp_;\n    });\n\n    auto pos = speeds.begin();\n    for (gsf_mbes_ping& ping : pings) {\n        pos = std::find_if(pos, speeds.end(), [&](const gsf_sound_speed& speed) {\n            return speed.time_stamp_ > ping.time_stamp_;\n        });\n        double ss;\n        if (pos == speeds.end()) {\n            ss = speeds.back().below_speed;\n        }\n        else {\n            ss = pos->below_speed;\n        }\n        for (int i = 0; i < ping.travel_times.size(); ++i) {\n            ping.distances.push_back(.5*ss*ping.travel_times[i]);\n            //ping.distances.push_back(ss*ping.travel_times[i]);\n        }\n    }\n\n}\n\nmbes_ping::PingsT convert_matched_entries(gsf_mbes_ping::PingsT& pings, gsf_nav_entry::EntriesT& entries)\n{\n    mbes_ping::PingsT new_pings;\n\n    std::stable_sort(entries.begin(), entries.end(), [](const gsf_nav_entry& entry1, const gsf_nav_entry& entry2) {\n        return entry1.time_stamp_ < entry2.time_stamp_;\n    });\n\n    auto pos = entries.begin();\n    for (gsf_mbes_ping& ping : pings) {\n        pos = std::find_if(pos, entries.end(), [&](const gsf_nav_entry& entry) {\n            return entry.time_stamp_ > ping.time_stamp_;\n        });\n\n        mbes_ping new_ping;\n        new_ping.time_stamp_ = ping.time_stamp_;\n        new_ping.time_string_ = ping.time_string_;\n        new_ping.first_in_file_ = ping.first_in_file_;\n        if (pos == entries.end()) {\n            new_ping.pos_ = entries.back().pos_;\n            new_ping.heading_ = entries.back().yaw_;\n            new_ping.pitch_ = entries.back().pitch_;\n            new_ping.roll_ = entries.back().roll_;\n        }\n        else {\n            if (pos == entries.begin()) {\n                //if (ping.long_ == 0) {\n                new_ping.pos_ = pos->pos_;\n                /*}\n                else {\n                    new_ping.pos_ = Eigen::Vector3d(ping.lat_, ping.long_, -ping.depth_);\n                }*/\n                if (ping.heading_ == 0) {\n                    new_ping.heading_ = pos->yaw_;\n                    new_ping.pitch_ = pos->pitch_;\n                    new_ping.roll_ = pos->roll_;\n                }\n                else {\n                    new_ping.heading_ = ping.heading_;\n                    new_ping.pitch_ = ping.pitch_;\n                    new_ping.roll_ = ping.roll_;\n                }\n            }\n            else {\n                gsf_nav_entry& previous = *(pos - 1);\n                double ratio = double(ping.time_stamp_ - previous.time_stamp_)/double(pos->time_stamp_ - previous.time_stamp_);\n                //if (ping.long_ == 0) {\n                new_ping.pos_ = previous.pos_ + ratio*(pos->pos_ - previous.pos_);\n                /*}\n                else {\n                    new_ping.pos_ = Eigen::Vector3d(ping.lat_, ping.long_, -ping.depth_);\n                }*/\n                if (ping.heading_ == 0) {\n                    new_ping.heading_ = previous.yaw_ + ratio*(pos->yaw_ - previous.yaw_);\n                    new_ping.pitch_ = previous.pitch_ + ratio*(pos->pitch_ - previous.pitch_);\n                    new_ping.roll_ = previous.roll_ + ratio*(pos->roll_ - previous.roll_);\n                }\n                else {\n                    new_ping.heading_ = ping.heading_;\n                    new_ping.pitch_ = ping.pitch_;\n                    new_ping.roll_ = ping.roll_;\n                    cout << \"heading diff: \" << previous.yaw_ + ratio*(pos->yaw_ - previous.yaw_) - new_ping.heading_ << endl;\n                    cout << \"pitch diff: \" << previous.pitch_ + ratio*(pos->pitch_ - previous.pitch_) - new_ping.pitch_ << endl;\n                    cout << \"roll diff: \" << previous.roll_ + ratio*(pos->roll_ - previous.roll_) - new_ping.roll_ << endl;\n                }\n                //cout << \"Ping timestamp: \" << ping.time_string_ << \", pos time stamp: \" << pos->time_string_ << endl;\n            }\n        }\n\n        //new_ping.heading_ = 0.5*M_PI-new_ping.heading_;\n        for (int i = 0; i < ping.distances.size(); ++i) {\n            double d = 1.*ping.distances[i];\n            if (d < 0.1) { // || ping.amplitudes[i] < 10) {\n                continue;\n            }\n            double th = M_PI/180.*ping.beam_angles[i];\n            Eigen::Vector3d p = new_ping.pos_;\n            Eigen::Vector3d sensor_p(0.62, 0., 0.);\n            Eigen::Vector3d beam(0., -d*sin(th), -d*cos(th)); // 0.55 comes from the log\n            //std::swap(new_ping.roll_, new_ping.pitch_);\n            //Eigen::Vector3d beam = ping.beams[i];\n\n            //Eigen::Matrix3d beam_Rx = Eigen::AngleAxisd(-0.12, Eigen::Vector3d::UnitX()).matrix();\n            Eigen::Matrix3d beam_Rx = Eigen::AngleAxisd(-0.06, Eigen::Vector3d::UnitX()).matrix();\n            Eigen::Matrix3d beam_Ry = Eigen::AngleAxisd(-0.15, Eigen::Vector3d::UnitY()).matrix();\n            Eigen::Matrix3d beam_Rz = Eigen::Matrix3d::Identity();\n\n            Eigen::Matrix3d Rx = Eigen::AngleAxisd(0*new_ping.roll_, Eigen::Vector3d::UnitX()).matrix();\n            Eigen::Matrix3d Ry = Eigen::AngleAxisd(0*new_ping.pitch_, Eigen::Vector3d::UnitY()).matrix();\n            Eigen::Matrix3d Rz = Eigen::AngleAxisd(new_ping.heading_, Eigen::Vector3d::UnitZ()).matrix();\n            Eigen::Matrix3d R = Rz*Ry*Rx;\n\n            new_ping.beams.push_back(p + R*(sensor_p+beam_Rz*beam_Ry*beam_Rx*beam));\n            //new_ping.beams.push_back(p + R*(sensor_p+beam));\n        }\n\n        new_pings.push_back(new_ping);\n    }\n\n    return new_pings;\n}\n\nmbes_ping::PingsT convert_pings(gsf_mbes_ping::PingsT& pings)\n{\n    mbes_ping::PingsT new_pings;\n\n    for (gsf_mbes_ping& ping : pings) {\n\n        mbes_ping new_ping;\n        new_ping.time_stamp_ = ping.time_stamp_;\n        new_ping.time_string_ = ping.time_string_;\n        new_ping.first_in_file_ = ping.first_in_file_;\n        new_ping.heading_ = ping.heading_;\n        new_ping.pitch_ = ping.pitch_;\n        new_ping.roll_ = ping.roll_;\n        double easting, northing;\n        string utm_zone;\n        tie(northing, easting, utm_zone) = lat_long_utm::lat_long_to_UTM(ping.lat_, ping.long_);\n        new_ping.pos_ = Eigen::Vector3d(easting, northing, -ping.depth_);\n\n        //ping.pos_ = new_ping.pos_;\n        int i = 0;\n        for (const Eigen::Vector3d& beam : ping.beams) {\n            if (beam(2) > -5. || beam(2) < -25.) {\n                ++i;\n                continue;\n            }\n            Eigen::Matrix3d Rz = Eigen::AngleAxisd(new_ping.heading_, Eigen::Vector3d::UnitZ()).matrix();\n            /*Eigen::Matrix3d Ry = Eigen::AngleAxisd(new_ping.pitch_, Eigen::Vector3d::UnitY()).matrix();\n            Eigen::Matrix3d Rx = Eigen::AngleAxisd(new_ping.roll_, Eigen::Vector3d::UnitX()).matrix();\n            Eigen::Matrix3d R = Rx*Ry*Rz;*/\n\n            // it seems it has already been compensated for pitch, roll\n            new_ping.beams.push_back(new_ping.pos_ + Rz*beam);\n            new_ping.back_scatter.push_back(ping.amplitudes[i]);\n            ++i;\n        }\n\n        new_pings.push_back(new_ping);\n    }\n\n    return new_pings;\n}\n\nmbes_ping::PingsT convert_matched_entries(gsf_mbes_ping::PingsT& pings, csv_nav_entry::EntriesT& entries)\n{\n    mbes_ping::PingsT new_pings;\n\n    std::stable_sort(entries.begin(), entries.end(), [](const csv_nav_entry& entry1, const csv_nav_entry& entry2) {\n        return entry1.time_stamp_ < entry2.time_stamp_;\n    });\n\n    auto pos = entries.begin();\n    for (gsf_mbes_ping& ping : pings) {\n        pos = std::find_if(pos, entries.end(), [&](const csv_nav_entry& entry) {\n            return entry.time_stamp_ > ping.time_stamp_;\n        });\n\n        mbes_ping new_ping;\n        new_ping.time_stamp_ = ping.time_stamp_;\n        new_ping.time_string_ = ping.time_string_;\n        new_ping.first_in_file_ = ping.first_in_file_;\n        //cout << \"Ping has time: \" << ping.time_string_ << \", time stamp: \" << ping.time_stamp_ << endl;\n        if (pos == entries.end()) {\n            //cout << \"Found only last entry with time: \" << entries.back().time_string_ << \", time stamp: \" << entries.back().time_stamp_ << endl;\n            new_ping.pos_ = entries.back().pos_;\n            new_ping.heading_ = entries.back().heading_;\n            new_ping.pitch_ = entries.back().pitch_;\n            new_ping.roll_ = entries.back().roll_;\n        }\n        else {\n            if (pos == entries.begin()) {\n                //cout << \"Found only first entry with time: \" << pos->time_string_ << \", time stamp: \" << pos->time_stamp_ << endl;\n                new_ping.pos_ = pos->pos_;\n                if (ping.heading_ == 0) {\n                    new_ping.heading_ = pos->heading_;\n                    new_ping.pitch_ = pos->pitch_;\n                    new_ping.roll_ = pos->roll_;\n                }\n                else {\n                    new_ping.heading_ = ping.heading_;\n                    new_ping.pitch_ = ping.pitch_;\n                    new_ping.roll_ = ping.roll_;\n                }\n            }\n            else {\n                //cout << \"Found entry with time: \" << pos->time_string_ << \", time stamp: \" << pos->time_stamp_ << endl;\n                csv_nav_entry& previous = *(pos - 1);\n                double ratio = double(ping.time_stamp_ - previous.time_stamp_)/double(pos->time_stamp_ - previous.time_stamp_);\n                new_ping.pos_ = previous.pos_ + ratio*(pos->pos_ - previous.pos_);\n                if (ping.heading_ == 0) {\n                    new_ping.heading_ = previous.heading_ + ratio*(pos->heading_ - previous.heading_);\n                    new_ping.pitch_ = previous.pitch_ + ratio*(pos->pitch_ - previous.pitch_);\n                    new_ping.roll_ = previous.roll_ + ratio*(pos->roll_ - previous.roll_);\n                }\n                else {\n                    new_ping.heading_ = ping.heading_;\n                    new_ping.pitch_ = ping.pitch_;\n                    new_ping.roll_ = ping.roll_;\n                    //cout << \"heading diff: \" << previous.yaw_ + ratio*(pos->yaw_ - previous.yaw_) - new_ping.heading_ << endl;\n                    //cout << \"pitch diff: \" << previous.pitch_ + ratio*(pos->pitch_ - previous.pitch_) - new_ping.pitch_ << endl;\n                    //cout << \"roll diff: \" << previous.roll_ + ratio*(pos->roll_ - previous.roll_) - new_ping.roll_ << endl;\n                }\n            }\n        }\n\n        for (const Eigen::Vector3d& beam : ping.beams) {\n            //new_ping.beams.push_back(new_ping.pos_ + beam);\n\n            Eigen::Matrix3d Rx = Eigen::AngleAxisd(new_ping.roll_, Eigen::Vector3d::UnitX()).matrix();\n            Eigen::Matrix3d Ry = Eigen::AngleAxisd(new_ping.pitch_, Eigen::Vector3d::UnitY()).matrix();\n            Eigen::Matrix3d Rz = Eigen::AngleAxisd(new_ping.heading_, Eigen::Vector3d::UnitZ()).matrix();\n            Eigen::Matrix3d R = Rz*Ry*Rx;\n\n            new_ping.beams.push_back(new_ping.pos_ + R*beam);\n        }\n\n        new_pings.push_back(new_ping);\n    }\n\n    return new_pings;\n}\n\n} // namespace gsf_data\n\nnamespace std_data {\n\nusing namespace gsf_data;\n\n/*\n% VEHICLE_POSE_FILE VERSION 3\n% \n% File:          dr_pose_est.data\n% Date Created:  Thu Jun  9 22:06:01 2011\n% Created from:  bpslam\n% \n% Timing Statistics: \n%     Program took 0.533 minutes to process mission.\n%     Total Mission Time: 157.063 minutes.\n%     Start Nav Time: 1224108800.202\n%     Stop Time:  1224118223.970\n%     Start Map Time: 1224109095.920\n%     Loop closure detection took 0.058 minutes to process.\n%     Particle Weighting took -0.000 minutes to process.\n%     GP Raytracing took 0.000 minutes to process.\n%     GP Learning took 0.000 minutes to process.\n% SLAM Statistics: \n%     Number of particles:    320\n%     Average number of particles:    320.000\n%     Number of resampling events passed:    0\n%     Number of resampling events prevented: 0\n%     Number of resampling events other: 0\n%     Number of multibeam poses available: 51416\n%     Number of multibeam poses stored: 11849\n%     Number of multibeam poses sampled: 2954\n%     Percentage of multibeam stored: 23.045%\n% \n%     Percentage of multibeam sampled: 5.745%\n% \n% \n% Pose Statistics:\n% \tNumber of Poses Written: 11849\n% \n% \n% Each line of this file describes the pose of the vehicle relative to the local\n% navigation frame. The vehicle poses may have been estimated since they are the\n% locations at which stereo images or multibeam sonar data were acquired.\n% \n% If a pose was estimated because it was the location images were acquired,\n% additional information for that pose can be found in the file\n% stereo_pose_est.data. The pose identifier can be used to locate matching\n% poses.\n% \n% The X and Y coordinates are produced using a local transverse Mercator \n% projection using the WGS84 ellipsoid and a central meridian at the origin\n% latitude. You will probably want to use the provided latitude and longitude to\n% produce coordinates in what map projection you require.\n% \n% The first two lines of the data contain the latitude and longitude of the\n% origin.\n% \n% Each line contains the following items describing the pose of the vehicle:\n% \n% 1) Pose identifier                   - integer value\n% 2) Timestamp                         - in seconds\n% 3) Latitude                          - in degrees\n% 4) Longitude                         - in degrees\n% 5) X position (Northing)             - in meters, relative to local nav frame\n% 6) Y position (Easting)              - in meters, relative to local nav frame\n% 7) Z position (Depth)                - in meters, relative to local nav frame\n% 8) X-axis Euler angle (Roll)         - in radians, relative to local nav frame\n% 9) Y-axis Euler angle (Pitch)        - in radians, relative to local nav frame\n% 10) Z-axis Euler angle (Yaw/Heading) - in radians, relative to local nav frame\n% 11) Altitude                         - in meters. (0 when unknown)\n*/\ntemplate <>\ngsf_nav_entry::EntriesT parse_file(const boost::filesystem::path& file)\n{\n    gsf_nav_entry::EntriesT entries;\n\n    gsf_nav_entry entry;\n    double x, y, z;\n    double time_seconds;\n    const boost::posix_time::ptime epoch = boost::posix_time::time_from_string(\"1970-01-01 00:00:00.000\");\n\t\n    string line;\n    std::ifstream infile(file.string());\n    while (std::getline(infile, line))  // this does the checking!\n    {\n        if (line.empty() || line[0] == '%' || line[0] == '\\n') {\n            continue;\n        }\n        istringstream iss(line);\n\n        double roll, pitch, yaw;\n\t\tiss >> entry.id_ >> time_seconds >> entry.lat_ >> entry.long_ >> x >> y >> z >> roll >> pitch >> yaw >> entry.altitude;\n        entry.pos_ = Eigen::Vector3d(y, x, -z);\n        entry.yaw_ = 0.5*M_PI-yaw-2.*M_PI;\n        entry.pitch_ = roll;\n        entry.roll_ = pitch;\n\n        entry.time_stamp_ = (long long)(1000. * time_seconds); // double seconds to milliseconds\n\n        boost::posix_time::ptime t = epoch + boost::posix_time::milliseconds(entry.time_stamp_);\n\n        stringstream time_ss;\n        time_ss << t;\n        entry.time_string_ = time_ss.str();\n\n\t\tentries.push_back(entry);\n    }\n\n\treturn entries;\n}\n\n// reads multibeam swaths from a .gsf file\ntemplate <>\ngsf_mbes_ping::PingsT parse_file(const boost::filesystem::path& file)\n{\n    gsf_mbes_ping::PingsT pings;\n    if (boost::filesystem::extension(file) != \".gsf\") {\n        return pings;\n    }\n\n    if (!boost::filesystem::exists(file)) {\n        cout << \"File \" << file << \" does not exist, exiting...\" << endl;\n        exit(0);\n    }\n    int handle;\n    //gsfOpen(file.string().c_str(), GSF_READONLY, &handle);\n    if (gsfOpen(file.string().c_str(), GSF_READONLY, &handle) != 0 || handle < 0)\n    {\n        cout << \"File \" << file << \" could not be opened!\" << endl;\n        return pings;\n        //exit(0);\n    }\n    //cout << \"Result: \" << result << \", handle: \" << handle << endl;\n\n    gsfDataID data_id;\n    gsfRecords records;\n    const boost::posix_time::ptime epoch = boost::posix_time::time_from_string(\"1970-01-01 00:00:00.000\");\n\n    while (gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0) != -1) {\n        if (data_id.recordID == GSF_RECORD_SWATH_BATHYMETRY_PING) {\n            gsf_mbes_ping ping;\n            for (int i = 0; i < records.mb_ping.number_beams; ++i) {\n                ping.travel_times.push_back(records.mb_ping.travel_time[i]);\n                ping.beam_angles.push_back(records.mb_ping.beam_angle[i]);\n                ping.amplitudes.push_back(records.mb_ping.mr_amplitude[i]);\n            }\n            if (records.mb_ping.depth != nullptr) {\n                double x, y, z;\n                for (int i = 0; i < records.mb_ping.number_beams; ++i) {\n                    x = records.mb_ping.along_track[i];\n                    y = -records.mb_ping.across_track[i];\n                    z = -records.mb_ping.depth[i];\n                    ping.beams.push_back(Eigen::Vector3d(x, y, z));\n                }\n            }\n            if (records.mb_ping.heading != 0) {\n                ping.heading_ = M_PI/180.*records.mb_ping.heading;\n                ping.heading_ = 0.5*M_PI-ping.heading_; // TODO: need to keep this for old data\n                ping.roll_ = M_PI/180.*records.mb_ping.roll;\n                ping.pitch_ = M_PI/180.*records.mb_ping.pitch;\n            }\n            else {\n                ping.heading_ = ping.roll_ = ping.pitch_ = 0.;\n            }\n            if (records.mb_ping.latitude != 0) {\n                ping.lat_ = records.mb_ping.latitude;\n                ping.long_ = records.mb_ping.longitude;\n                ping.depth_ = records.mb_ping.depth_corrector;\n            }\n            else {\n                ping.lat_ = ping.long_ = ping.depth_ = 0.;\n            }\n\n            long long sec = records.mb_ping.ping_time.tv_sec;\n            long long nsec = records.mb_ping.ping_time.tv_nsec;\n            ping.time_stamp_ = 1000*sec + nsec/1000000;\n            boost::posix_time::ptime t = epoch + boost::posix_time::milliseconds(ping.time_stamp_);\n\n            stringstream time_ss;\n            time_ss << t;\n            ping.time_string_ = time_ss.str();\n\n            ping.first_in_file_ = false;\n            pings.push_back(ping);\n        }\n    }\n\n    gsfClose(handle);\n\n    if (!pings.empty()) {\n        pings[0].first_in_file_ = true;\n    }\n\n    return pings;\n}\n\n/*\n% SOUND_SPEED_FILE VERSION 1\n% \n% Produced by mk_sound_speed\n% \n% \n% Each line of this file describes the sound speed measured \n% at the time indicated.\n% \n% On each line of the file are 4 items:\n% \n% 1) Record identifier                  - integer value\n% 2) Timestamp                        - in seconds\n% 3) Sound speed at vehicle           - in meters/second\n% 4) Mean sound speed beneath vehicle - in meters/second (best guess)\n*/\ntemplate <>\ngsf_sound_speed::SpeedsT parse_file(const boost::filesystem::path& file)\n{\n    gsf_sound_speed::SpeedsT speeds;\n\n    gsf_sound_speed speed;\n    double time_seconds;\n    int id_;\n    const boost::posix_time::ptime epoch = boost::posix_time::time_from_string(\"1970-01-01 00:00:00.000\");\n\t\n    string line;\n    std::ifstream infile(file.string());\n    while (std::getline(infile, line))  // this does the checking!\n    {\n        if (line.empty() || line[0] == '%' || line[0] == '\\n') {\n            continue;\n        }\n        istringstream iss(line);\n\n\t\tiss >> id_ >> time_seconds >> speed.near_speed >> speed.below_speed;\n\n        speed.time_stamp_ = (long long)(1000. * time_seconds); // double seconds to milliseconds\n\n        boost::posix_time::ptime t = epoch + boost::posix_time::milliseconds(speed.time_stamp_);\n\n        stringstream time_ss;\n        time_ss << t;\n        speed.time_string_ = time_ss.str();\n\n\t\tspeeds.push_back(speed);\n    }\n\n\treturn speeds;\n}\n\n} // namespace std_data\n", "meta": {"hexsha": "3dcc70a17d5fb069069e363a804a34c77be7c350", "size": 21802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/data_tools/src/gsf_data.cpp", "max_stars_repo_name": "luxiya01/auvlib", "max_stars_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T16:17:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:25:08.000Z", "max_issues_repo_path": "src/data_tools/src/gsf_data.cpp", "max_issues_repo_name": "luxiya01/auvlib", "max_issues_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-01-11T16:17:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:41:48.000Z", "max_forks_repo_path": "src/data_tools/src/gsf_data.cpp", "max_forks_repo_name": "luxiya01/auvlib", "max_forks_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T16:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:18:58.000Z", "avg_line_length": 41.213610586, "max_line_length": 758, "alphanum_fraction": 0.5984772039, "num_tokens": 5396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766830082071396, "lm_q2_score": 0.018546565122406676, "lm_q1q2_score": 0.006077121479719712}}
{"text": "/**\n *\n * Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net)\n *\n * Authors: Matthias Walter\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_BIPARTITE_HPP\n#define BOOST_GRAPH_BIPARTITE_HPP\n\n#include <utility>\n#include <vector>\n#include <exception>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/bind.hpp>\n\nnamespace boost {\n\n  namespace detail {\n\n    /**\n     * The bipartite_visitor_error is thrown if an edge cannot be colored.\n     * The witnesses are the edges incident vertices.\n     */\n\n    template <typename Vertex>\n    struct bipartite_visitor_error: std::exception\n    {\n      std::pair <Vertex, Vertex> witnesses;\n\n      bipartite_visitor_error (Vertex a, Vertex b) :\n        witnesses (a, b)\n      {\n\n      }\n\n      const char* what () const throw ()\n      {\n        return \"Graph is not bipartite.\";\n      }\n    };\n\n    /**\n     * Functor which colors edges to be non-monochromatic.\n     */\n\n    template <typename PartitionMap>\n    struct bipartition_colorize\n    {\n      typedef on_tree_edge event_filter;\n\n      bipartition_colorize (PartitionMap partition_map) :\n        partition_map_ (partition_map)\n      {\n\n      }\n\n      template <typename Edge, typename Graph>\n      void operator() (Edge e, const Graph& g)\n      {\n        typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t;\n        typedef color_traits <typename property_traits <PartitionMap>::value_type> color_traits;\n\n        vertex_descriptor_t source_vertex = source (e, g);\n        vertex_descriptor_t target_vertex = target (e, g);\n        if (get (partition_map_, source_vertex) == color_traits::white ())\n          put (partition_map_, target_vertex, color_traits::black ());\n        else\n          put (partition_map_, target_vertex, color_traits::white ());\n      }\n\n    private:\n      PartitionMap partition_map_;\n    };\n\n    /**\n     * Creates a bipartition_colorize functor which colors edges\n     * to be non-monochromatic.\n     *\n     * @param partition_map Color map for the bipartition\n     * @return The functor.\n     */\n\n    template <typename PartitionMap>\n    inline bipartition_colorize <PartitionMap> colorize_bipartition (PartitionMap partition_map)\n    {\n      return bipartition_colorize <PartitionMap> (partition_map);\n    }\n\n    /**\n     * Functor which tests an edge to be monochromatic.\n     */\n\n    template <typename PartitionMap>\n    struct bipartition_check\n    {\n      typedef on_back_edge event_filter;\n\n      bipartition_check (PartitionMap partition_map) :\n        partition_map_ (partition_map)\n      {\n\n      }\n\n      template <typename Edge, typename Graph>\n      void operator() (Edge e, const Graph& g)\n      {\n        typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t;\n\n        vertex_descriptor_t source_vertex = source (e, g);\n        vertex_descriptor_t target_vertex = target (e, g);\n        if (get (partition_map_, source_vertex) == get (partition_map_, target_vertex))\n          throw bipartite_visitor_error <vertex_descriptor_t> (source_vertex, target_vertex);\n      }\n\n    private:\n      PartitionMap partition_map_;\n    };\n\n    /**\n     * Creates a bipartition_check functor which raises an error if a\n     * monochromatic edge is found.\n     *\n     * @param partition_map The map for a bipartition.\n     * @return The functor.\n     */\n\n    template <typename PartitionMap>\n    inline bipartition_check <PartitionMap> check_bipartition (PartitionMap partition_map)\n    {\n      return bipartition_check <PartitionMap> (partition_map);\n    }\n\n    /**\n     * Find the beginning of a common suffix of two sequences\n     * \n     * @param sequence1 Pair of bidirectional iterators defining the first sequence.\n     * @param sequence2 Pair of bidirectional iterators defining the second sequence.\n     * @return Pair of iterators pointing to the beginning of the common suffix.\n     */\n\n    template <typename BiDirectionalIterator1, typename BiDirectionalIterator2>\n    inline std::pair <BiDirectionalIterator1, BiDirectionalIterator2> reverse_mismatch (std::pair <\n        BiDirectionalIterator1, BiDirectionalIterator1> sequence1, std::pair <BiDirectionalIterator2,\n        BiDirectionalIterator2> sequence2)\n    {\n      if (sequence1.first == sequence1.second || sequence2.first == sequence2.second)\n        return std::make_pair (sequence1.first, sequence2.first);\n\n      BiDirectionalIterator1 iter1 = sequence1.second;\n      BiDirectionalIterator2 iter2 = sequence2.second;\n\n      while (true)\n      {\n        --iter1;\n        --iter2;\n        if (*iter1 != *iter2)\n        {\n          ++iter1;\n          ++iter2;\n          break;\n        }\n        if (iter1 == sequence1.first)\n          break;\n        if (iter2 == sequence2.first)\n          break;\n      }\n\n      return std::make_pair (iter1, iter2);\n    }\n\n  }\n\n  /**\n   * Checks a given graph for bipartiteness and fills the given color map with\n   * white and black according to the bipartition. If the graph is not\n   * bipartite, the contents of the color map are undefined. Runs in linear\n   * time in the size of the graph, if access to the property maps is in\n   * constant time.\n   *\n   * @param graph The given graph.\n   * @param index_map An index map associating vertices with an index.\n   * @param partition_map A color map to fill with the bipartition.\n   * @return true if and only if the given graph is bipartite.\n   */\n\n  template <typename Graph, typename IndexMap, typename PartitionMap>\n  bool is_bipartite (const Graph& graph, const IndexMap index_map, PartitionMap partition_map)\n  {\n    /// General types and variables\n    typedef typename property_traits <PartitionMap>::value_type partition_color_t;\n    typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t;\n\n    /// Declare dfs visitor\n    //    detail::empty_recorder recorder;\n    //    typedef detail::bipartite_visitor <PartitionMap, detail::empty_recorder> dfs_visitor_t;\n    //    dfs_visitor_t dfs_visitor (partition_map, recorder);\n\n\n    /// Call dfs\n    try\n    {\n      depth_first_search (graph, vertex_index_map (index_map).visitor (make_dfs_visitor (std::make_pair (\n          detail::colorize_bipartition (partition_map), std::make_pair (detail::check_bipartition (partition_map),\n              put_property (partition_map, color_traits <partition_color_t>::white (), on_start_vertex ()))))));\n    }\n    catch (detail::bipartite_visitor_error <vertex_descriptor_t> error)\n    {\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Checks a given graph for bipartiteness.\n   *\n   * @param graph The given graph.\n   * @param index_map An index map associating vertices with an index.\n   * @return true if and only if the given graph is bipartite.\n   */\n\n  template <typename Graph, typename IndexMap>\n  bool is_bipartite (const Graph& graph, const IndexMap index_map)\n  {\n    typedef one_bit_color_map <IndexMap> partition_map_t;\n    partition_map_t partition_map (num_vertices (graph), index_map);\n\n    return is_bipartite (graph, index_map, partition_map);\n  }\n\n  /**\n   * Checks a given graph for bipartiteness. The graph must\n   * have an internal vertex_index property. Runs in linear time in the\n   * size of the graph, if access to the property maps is in constant time.\n   *\n   * @param graph The given graph.\n   * @return true if and only if the given graph is bipartite.\n   */\n\n  template <typename Graph>\n  bool is_bipartite (const Graph& graph)\n  {\n    return is_bipartite (graph, get (vertex_index, graph));\n  }\n\n  /**\n   * Checks a given graph for bipartiteness and fills a given color map with\n   * white and black according to the bipartition. If the graph is not\n   * bipartite, a sequence of vertices, producing an odd-cycle, is written to\n   * the output iterator. The final iterator value is returned. Runs in linear\n   * time in the size of the graph, if access to the property maps is in\n   * constant time.\n   *\n   * @param graph The given graph.\n   * @param index_map An index map associating vertices with an index.\n   * @param partition_map A color map to fill with the bipartition.\n   * @param result An iterator to write the odd-cycle vertices to.\n   * @return The final iterator value after writing.\n   */\n\n  template <typename Graph, typename IndexMap, typename PartitionMap, typename OutputIterator>\n  OutputIterator find_odd_cycle (const Graph& graph, const IndexMap index_map, PartitionMap partition_map,\n      OutputIterator result)\n  {\n    /// General types and variables\n    typedef typename property_traits <PartitionMap>::value_type partition_color_t;\n    typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t;\n    typedef typename graph_traits <Graph>::vertex_iterator vertex_iterator_t;\n    vertex_iterator_t vertex_iter, vertex_end;\n\n    /// Declare predecessor map\n    typedef std::vector <vertex_descriptor_t> predecessors_t;\n    typedef iterator_property_map <typename predecessors_t::iterator, IndexMap, vertex_descriptor_t,\n        vertex_descriptor_t&> predecessor_map_t;\n\n    predecessors_t predecessors (num_vertices (graph), graph_traits <Graph>::null_vertex ());\n    predecessor_map_t predecessor_map (predecessors.begin (), index_map);\n\n    /// Initialize predecessor map\n    for (boost::tie (vertex_iter, vertex_end) = vertices (graph); vertex_iter != vertex_end; ++vertex_iter)\n    {\n      put (predecessor_map, *vertex_iter, *vertex_iter);\n    }\n\n    /// Call dfs\n    try\n    {\n      depth_first_search (graph, vertex_index_map (index_map).visitor (make_dfs_visitor (std::make_pair (\n          detail::colorize_bipartition (partition_map), std::make_pair (detail::check_bipartition (partition_map),\n              std::make_pair (put_property (partition_map, color_traits <partition_color_t>::white (),\n                  on_start_vertex ()), record_predecessors (predecessor_map, on_tree_edge ())))))));\n    }\n    catch (detail::bipartite_visitor_error <vertex_descriptor_t> error)\n    {\n      typedef std::vector <vertex_descriptor_t> path_t;\n\n      path_t path1, path2;\n      vertex_descriptor_t next, current;\n\n      /// First path\n      next = error.witnesses.first;\n      do\n      {\n        current = next;\n        path1.push_back (current);\n        next = predecessor_map[current];\n      }\n      while (current != next);\n\n      /// Second path\n      next = error.witnesses.second;\n      do\n      {\n        current = next;\n        path2.push_back (current);\n        next = predecessor_map[current];\n      }\n      while (current != next);\n\n      /// Find beginning of common suffix\n      std::pair <typename path_t::iterator, typename path_t::iterator> mismatch = detail::reverse_mismatch (\n          std::make_pair (path1.begin (), path1.end ()), std::make_pair (path2.begin (), path2.end ()));\n\n      /// Copy the odd-length cycle\n      result = std::copy (path1.begin (), mismatch.first + 1, result);\n      return std::reverse_copy (path2.begin (), mismatch.second, result);\n    }\n\n    return result;\n  }\n\n  /**\n   * Checks a given graph for bipartiteness. If the graph is not bipartite, a\n   * sequence of vertices, producing an odd-cycle, is written to the output\n   * iterator. The final iterator value is returned. Runs in linear time in the\n   * size of the graph, if access to the property maps is in constant time.\n   *\n   * @param graph The given graph.\n   * @param index_map An index map associating vertices with an index.\n   * @param result An iterator to write the odd-cycle vertices to.\n   * @return The final iterator value after writing.\n   */\n\n  template <typename Graph, typename IndexMap, typename OutputIterator>\n  OutputIterator find_odd_cycle (const Graph& graph, const IndexMap index_map, OutputIterator result)\n  {\n    typedef one_bit_color_map <IndexMap> partition_map_t;\n    partition_map_t partition_map (num_vertices (graph), index_map);\n\n    return find_odd_cycle (graph, index_map, partition_map, result);\n  }\n\n  /**\n   * Checks a given graph for bipartiteness. If the graph is not bipartite, a\n   * sequence of vertices, producing an odd-cycle, is written to the output\n   * iterator. The final iterator value is returned. The graph must have an\n   * internal vertex_index property. Runs in linear time in the size of the\n   * graph, if access to the property maps is in constant time.\n   *\n   * @param graph The given graph.\n   * @param result An iterator to write the odd-cycle vertices to.\n   * @return The final iterator value after writing.\n   */\n\n  template <typename Graph, typename OutputIterator>\n  OutputIterator find_odd_cycle (const Graph& graph, OutputIterator result)\n  {\n    return find_odd_cycle (graph, get (vertex_index, graph), result);\n  }\n}\n\n#endif /// BOOST_GRAPH_BIPARTITE_HPP\n", "meta": {"hexsha": "74316fd537b4e0949205b39f34e404d7720b3583", "size": 12960, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/graph/bipartite.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/bipartite.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/bipartite.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 33.9267015707, "max_line_length": 114, "alphanum_fraction": 0.6913580247, "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678279774722, "lm_q2_score": 0.020964242844334027, "lm_q1q2_score": 0.006032834628506267}}
{"text": "// Copyright 2005 The Trustees of Indiana University.\r\n\r\n// Use, modification and distribution is subject to the Boost Software\r\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Douglas Gregor\r\n//           Andrew Lumsdaine\r\n\r\n// An implementation of Walter Hohberg's distributed biconnected\r\n// components algorithm, from:\r\n//\r\n//   Walter Hohberg. How to Find Biconnected Components in Distributed\r\n//   Networks. J. Parallel Distrib. Comput., 9(4):374-386, 1990.\r\n//\r\n#ifndef BOOST_GRAPH_DISTRIBUTED_HOHBERG_BICONNECTED_COMPONENTS_HPP\r\n#define BOOST_GRAPH_DISTRIBUTED_HOHBERG_BICONNECTED_COMPONENTS_HPP\r\n\r\n#ifndef BOOST_GRAPH_USE_MPI\r\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\r\n#endif\r\n\r\n/* You can define PBGL_HOHBERG_DEBUG to an integer value (1, 2, or 3)\r\n * to enable debugging information. 1 includes only the phases of the\r\n * algorithm and messages as their are received. 2 and 3 add\r\n * additional levels of detail about internal data structures related\r\n * to the algorithm itself.\r\n *\r\n * #define PBGL_HOHBERG_DEBUG 1\r\n*/\r\n\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/parallel/container_traits.hpp>\r\n#include <boost/graph/parallel/process_group.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/mpi/operations.hpp>\r\n#include <boost/type_traits/is_convertible.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/optional.hpp>\r\n#include <utility> // for std::pair\r\n#include <cassert>\r\n#include <algorithm> // for std::find, std::mismatch\r\n#include <vector>\r\n#include <boost/graph/parallel/algorithm.hpp>\r\n#include <boost/graph/distributed/connected_components.hpp>\r\n\r\nnamespace boost { namespace graph { namespace distributed {\r\n\r\nnamespace hohberg_detail {\r\n  enum message_kind {\r\n    /* A header for the PATH message, stating which edge the message\r\n       is coming on and how many vertices will be following. The data\r\n       structure communicated will be a path_header. */\r\n    msg_path_header,\r\n    /* A message containing the vertices that make up a path. It will\r\n       always follow a msg_path_header and will contain vertex\r\n       descriptors, only. */\r\n    msg_path_vertices,\r\n    /* A header for the TREE message, stating the value of gamma and\r\n       the number of vertices to come in the following\r\n       msg_tree_vertices. */\r\n    msg_tree_header,\r\n    /* A message containing the vertices that make up the set of\r\n       vertices in the same bicomponent as the sender. It will always\r\n       follow a msg_tree_header and will contain vertex descriptors,\r\n       only. */\r\n    msg_tree_vertices,\r\n    /* Provides a name for the biconnected component of the edge. */\r\n    msg_name\r\n  };\r\n\r\n  // Payload for a msg_path_header message.\r\n  template<typename EdgeDescriptor>\r\n  struct path_header\r\n  {\r\n    // The edge over which the path is being communicated\r\n    EdgeDescriptor edge;\r\n\r\n    // The length of the path, i.e., the number of vertex descriptors\r\n    // that will be coming in the next msg_path_vertices message.\r\n    std::size_t    path_length;\r\n\r\n    template<typename Archiver>\r\n    void serialize(Archiver& ar, const unsigned int /*version*/)\r\n    {\r\n      ar & edge & path_length;\r\n    }\r\n  };\r\n\r\n  // Payload for a msg_tree_header message.\r\n  template<typename Vertex, typename Edge>\r\n  struct tree_header\r\n  {\r\n    // The edge over which the tree is being communicated\r\n    Edge edge;\r\n\r\n    // Gamma, which is the eta of the sender.\r\n    Vertex gamma;\r\n\r\n    // The length of the list of vertices in the bicomponent, i.e.,\r\n    // the number of vertex descriptors that will be coming in the\r\n    // next msg_tree_vertices message.\r\n    std::size_t    bicomp_length;\r\n\r\n    template<typename Archiver>\r\n    void serialize(Archiver& ar, const unsigned int /*version*/)\r\n    {\r\n      ar & edge & gamma & bicomp_length;\r\n    }\r\n  };\r\n\r\n  // Payload for the msg_name message.\r\n  template<typename EdgeDescriptor>\r\n  struct name_header\r\n  {\r\n    // The edge being communicated and named.\r\n    EdgeDescriptor edge;\r\n\r\n    // The 0-based name of the component\r\n    std::size_t name;\r\n\r\n    template<typename Archiver>\r\n    void serialize(Archiver& ar, const unsigned int /*version*/)\r\n    {\r\n      ar & edge & name;\r\n    }\r\n  };\r\n\r\n  /* Computes the branch point between two paths. The branch point is\r\n     the last position at which both paths are equivalent, beyond\r\n     which the paths diverge. Both paths must have length > 0 and the\r\n     initial elements of the paths must be equal. This is guaranteed\r\n     in Hohberg's algorithm because all paths start at the\r\n     leader. Returns the value at the branch point. */\r\n  template<typename T>\r\n  T branch_point(const std::vector<T>& p1, const std::vector<T>& p2)\r\n  {\r\n    assert(!p1.empty());\r\n    assert(!p2.empty());\r\n    assert(p1.front() == p2.front());\r\n\r\n    typedef typename std::vector<T>::const_iterator iterator;\r\n\r\n    iterator mismatch_pos;\r\n    if (p1.size() <= p2.size())\r\n      mismatch_pos = std::mismatch(p1.begin(), p1.end(), p2.begin()).first;\r\n    else\r\n      mismatch_pos = std::mismatch(p2.begin(), p2.end(), p1.begin()).first;\r\n    --mismatch_pos;\r\n    return *mismatch_pos;\r\n  }\r\n\r\n  /* Computes the infimum of vertices a and b in the given path. The\r\n     infimum is the largest element that is on the paths from a to the\r\n     root and from b to the root. */\r\n  template<typename T>\r\n  T infimum(const std::vector<T>& parent_path, T a, T b)\r\n  {\r\n    using std::swap;\r\n\r\n    typedef typename std::vector<T>::const_iterator iterator;\r\n    iterator first = parent_path.begin(), last = parent_path.end();\r\n\r\n#if defined(PBGL_HOHBERG_DEBUG) and PBGL_HOHBERG_DEBUG > 2\r\n    std::cerr << \"infimum(\";\r\n    for (iterator i = first; i != last; ++i) {\r\n      if (i != first) std::cerr << ' ';\r\n      std::cerr << local(*i) << '@' << owner(*i);\r\n    }\r\n    std::cerr << \", \" << local(a) << '@' << owner(a) << \", \"\r\n              << local(b) << '@' << owner(b) << \") = \";\r\n#endif\r\n\r\n    if (a == b) {\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 2\r\n      std::cerr << local(a) << '@' << owner(a) << std::endl;\r\n#endif\r\n      return a;\r\n    }\r\n\r\n    // Try to find a or b, whichever is closest to the end\r\n    --last;\r\n    while (*last != a) {\r\n      // If we match b, swap the two so we'll be looking for b later.\r\n      if (*last == b) { swap(a,b); break; }\r\n\r\n      if (last == first) {\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 2\r\n        std::cerr << local(*first) << '@' << owner(*first) << std::endl;\r\n#endif\r\n        return *first;\r\n      }\r\n      else --last;\r\n    }\r\n\r\n    // Try to find b (which may originally have been a)\r\n    while (*last != b) {\r\n      if (last == first) {\r\n#if defined(PBGL_HOHBERG_DEBUG) and PBGL_HOHBERG_DEBUG > 2\r\n        std::cerr << local(*first) << '@' << owner(*first) << std::endl;\r\n#endif\r\n        return *first;\r\n      }\r\n      else --last;\r\n    }\r\n\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 2\r\n    std::cerr << local(*last) << '@' << owner(*last) << std::endl;\r\n#endif\r\n    // We've found b; it's the infimum.\r\n    return *last;\r\n  }\r\n} // end namespace hohberg_detail\r\n\r\n/* A message that will be stored for each edge by Hohberg's algorithm. */\r\ntemplate<typename Graph>\r\nstruct hohberg_message\r\n{\r\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n  typedef typename graph_traits<Graph>::edge_descriptor   Edge;\r\n\r\n  // Assign from a path message\r\n  void assign(const std::vector<Vertex>& path)\r\n  {\r\n    gamma = graph_traits<Graph>::null_vertex();\r\n    path_or_bicomp = path;\r\n  }\r\n\r\n  // Assign from a tree message\r\n  void assign(Vertex gamma, const std::vector<Vertex>& in_same_bicomponent)\r\n  {\r\n    this->gamma = gamma;\r\n    path_or_bicomp = in_same_bicomponent;\r\n  }\r\n\r\n  bool is_path() const { return gamma == graph_traits<Graph>::null_vertex(); }\r\n  bool is_tree() const { return gamma != graph_traits<Graph>::null_vertex(); }\r\n\r\n  /// The \"gamma\" of a tree message, or null_vertex() for a path message\r\n  Vertex gamma;\r\n\r\n  // Either the path for a path message or the in_same_bicomponent\r\n  std::vector<Vertex> path_or_bicomp;\r\n};\r\n\r\n\r\n/* An abstraction of a vertex processor in Hohberg's algorithm. The\r\n   hohberg_vertex_processor class is responsible for processing\r\n   messages transmitted to it via its edges. */\r\ntemplate<typename Graph>\r\nclass hohberg_vertex_processor\r\n{\r\n  typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n  typedef typename graph_traits<Graph>::edge_descriptor   Edge;\r\n  typedef typename graph_traits<Graph>::degree_size_type  degree_size_type;\r\n  typedef typename graph_traits<Graph>::edges_size_type   edges_size_type;\r\n  typedef typename boost::graph::parallel::process_group_type<Graph>::type\r\n    ProcessGroup;\r\n  typedef std::vector<Vertex> path_t;\r\n  typedef typename path_t::iterator path_iterator;\r\n\r\n public:\r\n  hohberg_vertex_processor()\r\n    : phase(1),\r\n      parent(graph_traits<Graph>::null_vertex()),\r\n      eta(graph_traits<Graph>::null_vertex())\r\n  {\r\n  }\r\n\r\n  // Called to initialize a leader in the algorithm, which involves\r\n  // sending out the initial path messages and being ready to receive\r\n  // them.\r\n  void initialize_leader(Vertex alpha, const Graph& g);\r\n\r\n  /// Handle a path message on edge e. The path will be destroyed by\r\n  /// this operation.\r\n  void\r\n  operator()(Edge e, path_t& path, const Graph& g);\r\n\r\n  /// Handle a tree message on edge e. in_same_bicomponent will be\r\n  /// destroyed by this operation.\r\n  void\r\n  operator()(Edge e, Vertex gamma, path_t& in_same_bicomponent,\r\n             const Graph& g);\r\n\r\n  // Handle a name message.\r\n  void operator()(Edge e, edges_size_type name, const Graph& g);\r\n\r\n  // Retrieve the phase\r\n  unsigned char get_phase() const { return phase; }\r\n\r\n  // Start the naming phase. The current phase must be 3 (echo), and\r\n  // the offset contains the offset at which this processor should\r\n  // begin when labelling its bicomponents. The offset is just a\r\n  // parallel prefix sum of the number of bicomponents in each\r\n  // processor that precedes it (globally).\r\n  void\r\n  start_naming_phase(Vertex alpha, const Graph& g, edges_size_type offset);\r\n\r\n  /* Determine the number of bicomponents that we will be naming\r\n   * ourselves.\r\n   */\r\n  edges_size_type num_starting_bicomponents(Vertex alpha, const Graph& g);\r\n\r\n  // Fill in the edge component map with biconnected component\r\n  // numbers.\r\n  template<typename ComponentMap>\r\n  void fill_edge_map(Vertex alpha, const Graph& g, ComponentMap& component);\r\n\r\n protected:\r\n  /* Start the echo phase (phase 3) where we propagate information up\r\n     the tree. */\r\n  void echo_phase(Vertex alpha, const Graph& g);\r\n\r\n  /* Retrieve the index of edge in the out-edges list of target(e, g). */\r\n  std::size_t get_edge_index(Edge e, const Graph& g);\r\n\r\n  /* Retrieve the index of the edge incidence on v in the out-edges\r\n     list of vertex u. */\r\n  std::size_t get_incident_edge_index(Vertex u, Vertex v, const Graph& g);\r\n\r\n  /* Keeps track of which phase of the algorithm we are in. There are\r\n   * four phases plus the \"finished\" phase:\r\n   *\r\n   *   1) Building the spanning tree\r\n   *   2) Discovering cycles\r\n   *   3) Echoing back up the spanning tree\r\n   *   4) Labelling biconnected components\r\n   *   5) Finished\r\n   */\r\n  unsigned char phase;\r\n\r\n  /* The parent of this vertex in the spanning tree. This value will\r\n     be graph_traits<Graph>::null_vertex() for the leader. */\r\n  Vertex parent;\r\n\r\n  /* The farthest ancestor up the tree that resides in the same\r\n     biconnected component as we do. This information is approximate:\r\n     we might not know about the actual farthest ancestor, but this is\r\n     the farthest one we've seen so far. */\r\n  Vertex eta;\r\n\r\n  /* The number of edges that have not yet transmitted any messages to\r\n     us. This starts at the degree of the vertex and decreases as we\r\n     receive messages. When this counter hits zero, we're done with\r\n     the second phase of the algorithm. In Hohberg's paper, the actual\r\n     remaining edge set E is stored with termination when all edges\r\n     have been removed from E, but we only need to detect termination\r\n     so the set E need not be explicitly represented. */\r\n  degree_size_type num_edges_not_transmitted;\r\n\r\n  /* The path from the root of the spanning tree to this vertex. This\r\n     vector will always store only the parts of the path leading up to\r\n     this vertex, and not the vertex itself. Thus, it will be empty\r\n     for the leader. */\r\n  std::vector<Vertex> path_from_root;\r\n\r\n  /* Structure containing all of the extra data we need to keep around\r\n     PER EDGE. This information can not be contained within a property\r\n     map, because it can't be shared among vertices without breaking\r\n     the algorithm. Decreasing the size of this structure will drastically */\r\n  struct per_edge_data\r\n  {\r\n    hohberg_message<Graph> msg;\r\n    std::vector<Vertex> M;\r\n    bool is_tree_edge;\r\n    degree_size_type partition;\r\n  };\r\n\r\n  /* Data for each edge in the graph. This structure will be indexed\r\n     by the position of the edge in the out_edges() list. */\r\n  std::vector<per_edge_data> edge_data;\r\n\r\n  /* The mapping from local partition numbers (0..n-1) to global\r\n     partition numbers. */\r\n  std::vector<edges_size_type> local_to_global_partitions;\r\n\r\n  friend class boost::serialization::access;\r\n\r\n  // We cannot actually serialize a vertex processor, nor would we\r\n  // want to. However, the fact that we're putting instances into a\r\n  // distributed_property_map means that we need to have a serialize()\r\n  // function available.\r\n  template<typename Archiver>\r\n  void serialize(Archiver&, const unsigned int /*version*/)\r\n  {\r\n    assert(false);\r\n  }\r\n};\r\n\r\ntemplate<typename Graph>\r\nvoid\r\nhohberg_vertex_processor<Graph>::initialize_leader(Vertex alpha,\r\n                                                   const Graph& g)\r\n{\r\n  using namespace hohberg_detail;\r\n\r\n  ProcessGroup pg = process_group(g);\r\n\r\n  typename property_map<Graph, vertex_owner_t>::const_type\r\n    owner = get(vertex_owner, g);\r\n\r\n  path_header<Edge> header;\r\n  header.path_length = 1;\r\n  BGL_FORALL_OUTEDGES_T(alpha, e, g, Graph) {\r\n    header.edge = e;\r\n    send(pg, get(owner, target(e, g)), msg_path_header, header);\r\n    send(pg, get(owner, target(e, g)), msg_path_vertices, alpha);\r\n  }\r\n\r\n  num_edges_not_transmitted = degree(alpha, g);\r\n  edge_data.resize(num_edges_not_transmitted);\r\n  phase = 2;\r\n}\r\n\r\ntemplate<typename Graph>\r\nvoid\r\nhohberg_vertex_processor<Graph>::operator()(Edge e, path_t& path,\r\n                                            const Graph& g)\r\n{\r\n  using namespace hohberg_detail;\r\n\r\n  typename property_map<Graph, vertex_owner_t>::const_type\r\n    owner = get(vertex_owner, g);\r\n\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n//  std::cerr << local(source(e, g)) << '@' << owner(source(e, g)) << \" -> \"\r\n//            << local(target(e, g)) << '@' << owner(target(e, g)) << \": path(\";\r\n//  for (std::size_t i = 0; i < path.size(); ++i) {\r\n//    if (i > 0) std::cerr << ' ';\r\n//    std::cerr << local(path[i]) << '@' << owner(path[i]);\r\n//  }\r\n  std::cerr << \"), phase = \" << (int)phase << std::endl;\r\n#endif\r\n\r\n  // Get access to edge-specific data\r\n  if (edge_data.empty())\r\n    edge_data.resize(degree(target(e, g), g));\r\n  per_edge_data& edata = edge_data[get_edge_index(e, g)];\r\n\r\n  // Record the message. We'll need it in phase 3.\r\n  edata.msg.assign(path);\r\n\r\n  // Note: \"alpha\" refers to the vertex \"processor\" receiving the\r\n  // message.\r\n  Vertex alpha = target(e, g);\r\n\r\n  switch (phase) {\r\n  case 1:\r\n    {\r\n      num_edges_not_transmitted = degree(alpha, g) - 1;\r\n      edata.is_tree_edge = true;\r\n      parent = path.back();\r\n      eta = parent;\r\n      edata.M.clear(); edata.M.push_back(parent);\r\n\r\n      // Broadcast the path from the root to our potential children in\r\n      // the spanning tree.\r\n      path.push_back(alpha);\r\n      path_header<Edge> header;\r\n      header.path_length = path.size();\r\n      ProcessGroup pg = process_group(g);\r\n      BGL_FORALL_OUTEDGES_T(alpha, oe, g, Graph) {\r\n        // Skip the tree edge we just received\r\n        if (target(oe, g) != source(e, g)) {\r\n          header.edge = oe;\r\n          send(pg, get(owner, target(oe, g)), msg_path_header, header);\r\n          send(pg, get(owner, target(oe, g)), msg_path_vertices, &path[0],\r\n               header.path_length);\r\n        }\r\n      }\r\n      path.pop_back();\r\n\r\n      // Swap the old path in, to save some extra copying. Nobody\r\n      path_from_root.swap(path);\r\n\r\n      // Once we have received our place in the spanning tree, move on\r\n      // to phase 2.\r\n      phase = 2;\r\n\r\n      // If we only had only edge, skip to phase 3.\r\n      if (num_edges_not_transmitted == 0)\r\n        echo_phase(alpha, g);\r\n      return;\r\n    }\r\n\r\n  case 2:\r\n    {\r\n      --num_edges_not_transmitted;\r\n      edata.is_tree_edge = false;\r\n\r\n      // Determine if alpha (our vertex) is in the path\r\n      path_iterator pos = std::find(path.begin(), path.end(), alpha);\r\n      if (pos != path.end()) {\r\n        // Case A: There is a cycle alpha beta ... gamma alpha\r\n        // M(e) <- {beta, gammar}\r\n        edata.M.clear();\r\n        ++pos;\r\n        // If pos == path.end(), we have a self-loop\r\n        if (pos != path.end()) {\r\n          // Add beta\r\n          edata.M.push_back(*pos);\r\n          ++pos;\r\n        }\r\n        // If pos == path.end(), we have a self-loop or beta == gamma\r\n        // (parallel edge). Otherwise, add gamma.\r\n        if (pos != path.end()) edata.M.push_back(path.back());\r\n      } else {\r\n        // Case B: There is a cycle but we haven't seen alpha yet.\r\n        // M(e) = {parent, path.back()}\r\n        edata.M.clear();\r\n        edata.M.push_back(path.back());\r\n        if (parent != path.back()) edata.M.push_back(parent);\r\n\r\n        // eta = inf(eta, bra(pi_t, pi))\r\n        eta = infimum(path_from_root, eta, branch_point(path_from_root, path));\r\n      }\r\n      if (num_edges_not_transmitted == 0)\r\n        echo_phase(alpha, g);\r\n      break;\r\n    }\r\n\r\n  default:\r\n//    std::cerr << \"Phase is \" << int(phase) << \"\\n\";\r\n    assert(false);\r\n  }\r\n}\r\n\r\ntemplate<typename Graph>\r\nvoid\r\nhohberg_vertex_processor<Graph>::operator()(Edge e, Vertex gamma,\r\n                                            path_t& in_same_bicomponent,\r\n                                            const Graph& g)\r\n{\r\n  using namespace hohberg_detail;\r\n\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n  std::cerr << local(source(e, g)) << '@' << owner(source(e, g)) << \" -> \"\r\n            << local(target(e, g)) << '@' << owner(target(e, g)) << \": tree(\"\r\n            << local(gamma) << '@' << owner(gamma) << \", \";\r\n  for (std::size_t i = 0; i < in_same_bicomponent.size(); ++i) {\r\n    if (i > 0) std::cerr << ' ';\r\n    std::cerr << local(in_same_bicomponent[i]) << '@'\r\n              << owner(in_same_bicomponent[i]);\r\n  }\r\n  std::cerr << \", \" << local(source(e, g)) << '@' << owner(source(e, g))\r\n            << \"), phase = \" << (int)phase << std::endl;\r\n#endif\r\n\r\n  // Get access to edge-specific data\r\n  per_edge_data& edata = edge_data[get_edge_index(e, g)];\r\n\r\n  // Record the message. We'll need it in phase 3.\r\n  edata.msg.assign(gamma, in_same_bicomponent);\r\n\r\n  // Note: \"alpha\" refers to the vertex \"processor\" receiving the\r\n  // message.\r\n  Vertex alpha = target(e, g);\r\n  Vertex beta = source(e, g);\r\n\r\n  switch (phase) {\r\n  case 2:\r\n    --num_edges_not_transmitted;\r\n    edata.is_tree_edge = true;\r\n\r\n    if (gamma == alpha) {\r\n      // Case C\r\n      edata.M.swap(in_same_bicomponent);\r\n    } else {\r\n      // Case D\r\n      edata.M.clear();\r\n      edata.M.push_back(parent);\r\n      if (beta != parent) edata.M.push_back(beta);\r\n      eta = infimum(path_from_root, eta, gamma);\r\n    }\r\n    if (num_edges_not_transmitted == 0)\r\n      echo_phase(alpha, g);\r\n    break;\r\n\r\n  default:\r\n    assert(false);\r\n  }\r\n}\r\n\r\ntemplate<typename Graph>\r\nvoid\r\nhohberg_vertex_processor<Graph>::operator()(Edge e, edges_size_type name,\r\n                                            const Graph& g)\r\n{\r\n  using namespace hohberg_detail;\r\n\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n  std::cerr << local(source(e, g)) << '@' << owner(source(e, g)) << \" -> \"\r\n            << local(target(e, g)) << '@' << owner(target(e, g)) << \": name(\"\r\n            << name << \"), phase = \" << (int)phase << std::endl;\r\n#endif\r\n\r\n  assert(phase == 4);\r\n\r\n  typename property_map<Graph, vertex_owner_t>::const_type\r\n    owner = get(vertex_owner, g);\r\n\r\n  // Send name messages along the spanning tree edges that are in the\r\n  // same bicomponent as the edge to our parent.\r\n  ProcessGroup pg = process_group(g);\r\n\r\n  Vertex alpha = target(e, g);\r\n\r\n  std::size_t idx = 0;\r\n  BGL_FORALL_OUTEDGES_T(alpha, e, g, Graph) {\r\n    per_edge_data& edata = edge_data[idx++];\r\n    if (edata.is_tree_edge\r\n        && find(edata.M.begin(), edata.M.end(), parent) != edata.M.end()\r\n        && target(e, g) != parent) {\r\n      // Notify our children in the spanning tree of this name\r\n      name_header<Edge> header;\r\n      header.edge = e;\r\n      header.name = name;\r\n      send(pg, get(owner, target(e, g)), msg_name, header);\r\n    } else if (target(e, g) == parent) {\r\n      // Map from local partition numbers to global bicomponent numbers\r\n      local_to_global_partitions[edata.partition] = name;\r\n    }\r\n  }\r\n\r\n  // Final stage\r\n  phase = 5;\r\n}\r\n\r\ntemplate<typename Graph>\r\ntypename hohberg_vertex_processor<Graph>::edges_size_type\r\nhohberg_vertex_processor<Graph>::\r\nnum_starting_bicomponents(Vertex alpha, const Graph& g)\r\n{\r\n  edges_size_type not_mapped = (std::numeric_limits<edges_size_type>::max)();\r\n\r\n  edges_size_type result = 0;\r\n  std::size_t idx = 0;\r\n  BGL_FORALL_OUTEDGES_T(alpha, e, g, Graph) {\r\n    per_edge_data& edata = edge_data[idx++];\r\n    if (edata.is_tree_edge\r\n        && find(edata.M.begin(), edata.M.end(), parent) == edata.M.end()) {\r\n      // Map from local partition numbers to global bicomponent numbers\r\n      if (local_to_global_partitions[edata.partition] == not_mapped)\r\n        local_to_global_partitions[edata.partition] = result++;\r\n    }\r\n  }\r\n\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n  std::cerr << local(alpha) << '@' << owner(alpha) << \" has \" << result\r\n            << \" bicomponents originating at it.\" << std::endl;\r\n#endif\r\n\r\n  return result;\r\n}\r\n\r\ntemplate<typename Graph>\r\ntemplate<typename ComponentMap>\r\nvoid\r\nhohberg_vertex_processor<Graph>::\r\nfill_edge_map(Vertex alpha, const Graph& g, ComponentMap& component)\r\n{\r\n  std::size_t idx = 0;\r\n  BGL_FORALL_OUTEDGES_T(alpha, e, g, Graph) {\r\n    per_edge_data& edata = edge_data[idx++];\r\n    local_put(component, e, local_to_global_partitions[edata.partition]);\r\n\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 2\r\n    std::cerr << \"component(\"\r\n              << local(source(e, g)) << '@' << owner(source(e, g)) << \" -> \"\r\n              << local(target(e, g)) << '@' << owner(target(e, g)) << \") = \"\r\n              << local_to_global_partitions[edata.partition]\r\n              << \" (partition = \" << edata.partition << \" of \"\r\n              << local_to_global_partitions.size() << \")\" << std::endl;\r\n#endif\r\n  }\r\n}\r\n\r\ntemplate<typename Graph>\r\nvoid\r\nhohberg_vertex_processor<Graph>::\r\nstart_naming_phase(Vertex alpha, const Graph& g, edges_size_type offset)\r\n{\r\n  using namespace hohberg_detail;\r\n\r\n  assert(phase == 4);\r\n\r\n  typename property_map<Graph, vertex_owner_t>::const_type\r\n    owner = get(vertex_owner, g);\r\n\r\n  // Send name messages along the spanning tree edges of the\r\n  // components that we get to number.\r\n  ProcessGroup pg = process_group(g);\r\n\r\n  bool has_more_children_to_name = false;\r\n\r\n  // Map from local partition numbers to global bicomponent numbers\r\n  edges_size_type not_mapped = (std::numeric_limits<edges_size_type>::max)();\r\n  for (std::size_t i = 0; i < local_to_global_partitions.size(); ++i) {\r\n    if (local_to_global_partitions[i] != not_mapped)\r\n      local_to_global_partitions[i] += offset;\r\n  }\r\n\r\n  std::size_t idx = 0;\r\n  BGL_FORALL_OUTEDGES_T(alpha, e, g, Graph) {\r\n    per_edge_data& edata = edge_data[idx++];\r\n    if (edata.is_tree_edge\r\n        && find(edata.M.begin(), edata.M.end(), parent) == edata.M.end()) {\r\n      // Notify our children in the spanning tree of this new name\r\n      name_header<Edge> header;\r\n      header.edge = e;\r\n      header.name = local_to_global_partitions[edata.partition];\r\n      send(pg, get(owner, target(e, g)), msg_name, header);\r\n    } else if (edata.is_tree_edge) {\r\n      has_more_children_to_name = true;\r\n    }\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 2\r\n    std::cerr << \"M[\" << local(source(e, g)) << '@' << owner(source(e, g))\r\n              << \" -> \" << local(target(e, g)) << '@' << owner(target(e, g))\r\n              << \"] = \";\r\n    for (std::size_t i = 0; i < edata.M.size(); ++i) {\r\n      std::cerr << local(edata.M[i]) << '@' << owner(edata.M[i]) << ' ';\r\n    }\r\n    std::cerr << std::endl;\r\n#endif\r\n  }\r\n\r\n  // See if we're done.\r\n  if (!has_more_children_to_name)\r\n    // Final stage\r\n    phase = 5;\r\n}\r\n\r\ntemplate<typename Graph>\r\nvoid\r\nhohberg_vertex_processor<Graph>::echo_phase(Vertex alpha, const Graph& g)\r\n{\r\n  using namespace hohberg_detail;\r\n\r\n  typename property_map<Graph, vertex_owner_t>::const_type\r\n    owner = get(vertex_owner, g);\r\n\r\n  /* We're entering the echo phase. */\r\n  phase = 3;\r\n\r\n  if (parent != graph_traits<Graph>::null_vertex()) {\r\n    Edge edge_to_parent;\r\n\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 1\r\n     std::cerr << local(alpha) << '@' << owner(alpha) << \" echo: parent = \"\r\n               << local(parent) << '@' << owner(parent) << \", eta = \"\r\n               << local(eta) << '@' << owner(eta) << \", Gamma = \";\r\n#endif\r\n\r\n    std::vector<Vertex> bicomp;\r\n    std::size_t e_index = 0;\r\n    BGL_FORALL_OUTEDGES_T(alpha, e, g, Graph) {\r\n      if (target(e, g) == parent && parent == eta) {\r\n        edge_to_parent = e;\r\n        if (find(bicomp.begin(), bicomp.end(), alpha) == bicomp.end()) {\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 1\r\n          std::cerr << local(alpha) << '@' << owner(alpha) << ' ';\r\n#endif\r\n          bicomp.push_back(alpha);\r\n        }\r\n      } else {\r\n        if (target(e, g) == parent) edge_to_parent = e;\r\n\r\n        per_edge_data& edata = edge_data[e_index];\r\n\r\n        if (edata.msg.is_path()) {\r\n          path_iterator pos = std::find(edata.msg.path_or_bicomp.begin(),\r\n                                        edata.msg.path_or_bicomp.end(),\r\n                                        eta);\r\n          if (pos != edata.msg.path_or_bicomp.end()) {\r\n            ++pos;\r\n            if (pos != edata.msg.path_or_bicomp.end()\r\n                && find(bicomp.begin(), bicomp.end(), *pos) == bicomp.end()) {\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 1\r\n              std::cerr << local(*pos) << '@' << owner(*pos) << ' ';\r\n#endif\r\n              bicomp.push_back(*pos);\r\n            }\r\n          }\r\n        } else if (edata.msg.is_tree() && edata.msg.gamma == eta) {\r\n          for (path_iterator i = edata.msg.path_or_bicomp.begin();\r\n               i != edata.msg.path_or_bicomp.end(); ++i) {\r\n            if (find(bicomp.begin(), bicomp.end(), *i) == bicomp.end()) {\r\n#if defined(PBGL_HOHBERG_DEBUG) && PBGL_HOHBERG_DEBUG > 1\r\n              std::cerr << local(*i) << '@' << owner(*i) << ' ';\r\n#endif\r\n              bicomp.push_back(*i);\r\n            }\r\n          }\r\n        }\r\n      }\r\n      ++e_index;\r\n    }\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n    std::cerr << std::endl;\r\n#endif\r\n\r\n    // Send tree(eta, bicomp) to parent\r\n    tree_header<Vertex, Edge> header;\r\n    header.edge = edge_to_parent;\r\n    header.gamma = eta;\r\n    header.bicomp_length = bicomp.size();\r\n    ProcessGroup pg = process_group(g);\r\n    send(pg, get(owner, parent), msg_tree_header, header);\r\n    send(pg, get(owner, parent), msg_tree_vertices, &bicomp[0],\r\n         header.bicomp_length);\r\n  }\r\n\r\n  // Compute the partition of edges such that iff two edges e1 and e2\r\n  // are in different subsets then M(e1) is disjoint from M(e2).\r\n\r\n  // Start by putting each edge in a different partition\r\n  std::vector<degree_size_type> parent_vec(edge_data.size());\r\n  degree_size_type idx = 0;\r\n  for (idx = 0; idx < edge_data.size(); ++idx)\r\n    parent_vec[idx] = idx;\r\n\r\n  // Go through each edge e, performing a union() on the edges\r\n  // incident on all vertices in M[e].\r\n  idx = 0;\r\n  BGL_FORALL_OUTEDGES_T(alpha, e, g, Graph) {\r\n    per_edge_data& edata = edge_data[idx++];\r\n\r\n    // Compute union of vertices in M\r\n    if (!edata.M.empty()) {\r\n      degree_size_type e1 = get_incident_edge_index(alpha, edata.M.front(), g);\r\n      while (parent_vec[e1] != e1) e1 = parent_vec[e1];\r\n\r\n      for (std::size_t i = 1; i < edata.M.size(); ++i) {\r\n        degree_size_type e2 = get_incident_edge_index(alpha, edata.M[i], g);\r\n        while (parent_vec[e2] != e2) e2 = parent_vec[e2];\r\n        parent_vec[e2] = e1;\r\n      }\r\n    }\r\n  }\r\n\r\n  edges_size_type not_mapped = (std::numeric_limits<edges_size_type>::max)();\r\n\r\n  // Determine the number of partitions\r\n  for (idx = 0; idx < parent_vec.size(); ++idx) {\r\n    if (parent_vec[idx] == idx) {\r\n      edge_data[idx].partition = local_to_global_partitions.size();\r\n      local_to_global_partitions.push_back(not_mapped);\r\n    }\r\n  }\r\n\r\n  // Assign partition numbers to each edge\r\n  for (idx = 0; idx < parent_vec.size(); ++idx) {\r\n    degree_size_type rep = parent_vec[idx];\r\n    while (rep != parent_vec[rep]) rep = parent_vec[rep];\r\n    edge_data[idx].partition = edge_data[rep].partition;\r\n  }\r\n\r\n  // Enter the naming phase (but don't send anything yet).\r\n  phase = 4;\r\n}\r\n\r\ntemplate<typename Graph>\r\nstd::size_t\r\nhohberg_vertex_processor<Graph>::get_edge_index(Edge e, const Graph& g)\r\n{\r\n  std::size_t result = 0;\r\n  BGL_FORALL_OUTEDGES_T(target(e, g), oe, g, Graph) {\r\n    if (source(e, g) == target(oe, g)) return result;\r\n    ++result;\r\n  }\r\n  assert(false);\r\n}\r\n\r\ntemplate<typename Graph>\r\nstd::size_t\r\nhohberg_vertex_processor<Graph>::get_incident_edge_index(Vertex u, Vertex v,\r\n                                                         const Graph& g)\r\n{\r\n  std::size_t result = 0;\r\n  BGL_FORALL_OUTEDGES_T(u, e, g, Graph) {\r\n    if (target(e, g) == v) return result;\r\n    ++result;\r\n  }\r\n  assert(false);\r\n}\r\n\r\ntemplate<typename Graph, typename InputIterator, typename ComponentMap,\r\n         typename VertexProcessorMap>\r\ntypename graph_traits<Graph>::edges_size_type\r\nhohberg_biconnected_components\r\n  (const Graph& g,\r\n   ComponentMap component,\r\n   InputIterator first, InputIterator last,\r\n   VertexProcessorMap vertex_processor)\r\n{\r\n  using namespace boost::graph::parallel;\r\n  using namespace hohberg_detail;\r\n  using boost::parallel::all_reduce;\r\n\r\n  typename property_map<Graph, vertex_owner_t>::const_type\r\n    owner = get(vertex_owner, g);\r\n\r\n  // The graph must be undirected\r\n  BOOST_STATIC_ASSERT(\r\n    (is_convertible<typename graph_traits<Graph>::directed_category,\r\n                    undirected_tag>::value));\r\n\r\n  // The graph must model Incidence Graph\r\n  function_requires< IncidenceGraphConcept<Graph> >();\r\n\r\n  typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\r\n  typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\r\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n  typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n\r\n  // Retrieve the process group we will use for communication\r\n  typedef typename process_group_type<Graph>::type process_group_type;\r\n  process_group_type pg = process_group(g);\r\n\r\n  // Keeps track of the edges that we know to be tree edges.\r\n  std::vector<edge_descriptor> tree_edges;\r\n\r\n  // The leaders send out a path message to initiate the algorithm\r\n  while (first != last) {\r\n    vertex_descriptor leader = *first;\r\n    if (process_id(pg) == get(owner, leader))\r\n      vertex_processor[leader].initialize_leader(leader, g);\r\n    ++first;\r\n  }\r\n  synchronize(pg);\r\n\r\n  // Will hold the number of bicomponents in the graph.\r\n  edges_size_type num_bicomponents = 0;\r\n\r\n  // Keep track of the path length that we should expect, based on the\r\n  // level in the breadth-first search tree. At present, this is only\r\n  // used as a sanity check. TBD: This could be used to decrease the\r\n  // amount of communication required per-edge (by about 4 bytes).\r\n  std::size_t path_length = 1;\r\n\r\n  typedef std::vector<vertex_descriptor> path_t;\r\n  typedef typename path_t::iterator path_iterator;\r\n\r\n  unsigned char minimum_phase = 5;\r\n  do {\r\n    while (optional<std::pair<int, int> > msg = probe(pg)) {\r\n      switch (msg->second) {\r\n      case msg_path_header:\r\n        {\r\n          // Receive the path header\r\n          path_header<edge_descriptor> header;\r\n          receive(pg, msg->first, msg->second, header);\r\n          assert(path_length == header.path_length);\r\n\r\n          // Receive the path itself\r\n          path_t path(path_length);\r\n          receive(pg, msg->first, msg_path_vertices, &path[0], path_length);\r\n\r\n          edge_descriptor e = header.edge;\r\n          vertex_processor[target(e, g)](e, path, g);\r\n        }\r\n        break;\r\n\r\n      case msg_path_vertices:\r\n        // Should be handled in msg_path_header case, unless we're going\r\n        // stateless.\r\n        assert(false);\r\n        break;\r\n\r\n      case msg_tree_header:\r\n        {\r\n          // Receive the tree header\r\n          tree_header<vertex_descriptor, edge_descriptor> header;\r\n          receive(pg, msg->first, msg->second, header);\r\n\r\n          // Receive the tree itself\r\n          path_t in_same_bicomponent(header.bicomp_length);\r\n          receive(pg, msg->first, msg_tree_vertices, &in_same_bicomponent[0],\r\n                  header.bicomp_length);\r\n\r\n          edge_descriptor e = header.edge;\r\n          vertex_processor[target(e, g)](e, header.gamma, in_same_bicomponent,\r\n                                         g);\r\n        }\r\n        break;\r\n\r\n      case msg_tree_vertices:\r\n        // Should be handled in msg_tree_header case, unless we're\r\n        // going stateless.\r\n        assert(false);\r\n        break;\r\n\r\n      case msg_name:\r\n        {\r\n          name_header<edge_descriptor> header;\r\n          receive(pg, msg->first, msg->second, header);\r\n          edge_descriptor e = header.edge;\r\n          vertex_processor[target(e, g)](e, header.name, g);\r\n        }\r\n        break;\r\n\r\n      default:\r\n        assert(false);\r\n      }\r\n    }\r\n    ++path_length;\r\n\r\n    // Compute minimum phase locally\r\n    minimum_phase = 5;\r\n    unsigned char maximum_phase = 1;\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      minimum_phase = (std::min)(minimum_phase, vertex_processor[v].get_phase());\r\n      maximum_phase = (std::max)(maximum_phase, vertex_processor[v].get_phase());\r\n    }\r\n\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n    if (process_id(pg) == 0)\r\n      std::cerr << \"<---------End of stage------------->\" << std::endl;\r\n#endif\r\n    // Compute minimum phase globally\r\n    minimum_phase = all_reduce(pg, minimum_phase, boost::mpi::minimum<char>());\r\n\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n    if (process_id(pg) == 0)\r\n      std::cerr << \"Minimum phase = \" << (int)minimum_phase << std::endl;\r\n#endif\r\n\r\n    if (minimum_phase == 4\r\n        && all_reduce(pg, maximum_phase, boost::mpi::maximum<char>()) == 4) {\r\n\r\n#ifdef PBGL_HOHBERG_DEBUG\r\n      if (process_id(pg) == 0)\r\n        std::cerr << \"<---------Naming phase------------->\" << std::endl;\r\n#endif\r\n      // Compute the biconnected component number offsets for each\r\n      // vertex.\r\n      std::vector<edges_size_type> local_offsets;\r\n      local_offsets.reserve(num_vertices(g));\r\n      edges_size_type num_local_bicomponents = 0;\r\n      BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n        local_offsets.push_back(num_local_bicomponents);\r\n        num_local_bicomponents +=\r\n          vertex_processor[v].num_starting_bicomponents(v, g);\r\n      }\r\n\r\n      synchronize(pg);\r\n\r\n      // Find our the number of bicomponent names that will originate\r\n      // from each process. This tells us how many bicomponents are in\r\n      // the entire graph and what our global offset is for computing\r\n      // our own biconnected component names.\r\n      std::vector<edges_size_type> all_bicomponents(num_processes(pg));\r\n      all_gather(pg, &num_local_bicomponents, &num_local_bicomponents + 1,\r\n                 all_bicomponents);\r\n      num_bicomponents = 0;\r\n      edges_size_type my_global_offset = 0;\r\n      for (std::size_t i = 0; i < all_bicomponents.size(); ++i) {\r\n        if (i == (std::size_t)process_id(pg)) \r\n          my_global_offset = num_bicomponents;\r\n        num_bicomponents += all_bicomponents[i];\r\n      }\r\n\r\n      std::size_t index = 0;\r\n      BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n        edges_size_type offset = my_global_offset + local_offsets[index++];\r\n        vertex_processor[v].start_naming_phase(v, g, offset);\r\n      }\r\n    }\r\n\r\n    synchronize(pg);\r\n  } while (minimum_phase < 5);\r\n\r\n  // Number the edges appropriately.\r\n  BGL_FORALL_VERTICES_T(v, g, Graph)\r\n    vertex_processor[v].fill_edge_map(v, g, component);\r\n\r\n  return num_bicomponents;\r\n}\r\n\r\ntemplate<typename Graph, typename ComponentMap, typename InputIterator>\r\ntypename graph_traits<Graph>::edges_size_type\r\nhohberg_biconnected_components\r\n  (const Graph& g, ComponentMap component,\r\n   InputIterator first, InputIterator last)\r\n\r\n{\r\n  std::vector<hohberg_vertex_processor<Graph> >\r\n    vertex_processors(num_vertices(g));\r\n  return hohberg_biconnected_components\r\n           (g, component, first, last,\r\n            make_iterator_property_map(vertex_processors.begin(),\r\n                                       get(vertex_index, g)));\r\n}\r\n\r\ntemplate<typename Graph, typename ComponentMap, typename ParentMap>\r\ntypename graph_traits<Graph>::edges_size_type\r\nhohberg_biconnected_components(const Graph& g, ComponentMap component,\r\n                               ParentMap parent)\r\n{\r\n  // We need the connected components of the graph, but we don't care\r\n  // about component numbers.\r\n  connected_components(g, dummy_property_map(), parent);\r\n\r\n  // Each root in the parent map is a leader\r\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n  std::vector<vertex_descriptor> leaders;\r\n  BGL_FORALL_VERTICES_T(v, g, Graph)\r\n    if (get(parent, v) == v) leaders.push_back(v);\r\n\r\n  return hohberg_biconnected_components(g, component,\r\n                                        leaders.begin(), leaders.end());\r\n}\r\n\r\ntemplate<typename Graph, typename ComponentMap>\r\ntypename graph_traits<Graph>::edges_size_type\r\nhohberg_biconnected_components(const Graph& g, ComponentMap component)\r\n{\r\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n  std::vector<vertex_descriptor> parents(num_vertices(g));\r\n  return hohberg_biconnected_components\r\n           (g, component, make_iterator_property_map(parents.begin(),\r\n                                                     get(vertex_index, g)));\r\n}\r\n\r\n} } } // end namespace boost::graph::distributed\r\n\r\n#endif // BOOST_GRAPH_DISTRIBUTED_HOHBERG_BICONNECTED_COMPONENTS_HPP\r\n", "meta": {"hexsha": "03dc59cb6e272a4a7aadcd715de6331443a6ecbf", "size": 39218, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/graph/distributed/hohberg_biconnected_components.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T01:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-26T07:38:43.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/graph/distributed/hohberg_biconnected_components.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T01:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T01:56:28.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/graph/distributed/hohberg_biconnected_components.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": 34.7061946903, "max_line_length": 102, "alphanum_fraction": 0.6312917538, "num_tokens": 9650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706247, "lm_q2_score": 0.027585280528006684, "lm_q1q2_score": 0.005995316487344775}}
{"text": "// Copyright (c) 2020-2021 Franz Alt\n// This code is licensed under MIT license (see LICENSE.txt for details).\n\n#include <libcvpg/imageproc/algorithms/k_means.hpp>\n\n#include <algorithm>\n#include <cstdint>\n#include <iterator>\n#include <memory>\n#include <random>\n#include <vector>\n\n#include <boost/asynchronous/algorithm/then.hpp>\n\n#include <libcvpg/core/exception.hpp>\n#include <libcvpg/core/histogram.hpp>\n#include <libcvpg/imageproc/algorithms/tiling.hpp>\n#include <libcvpg/imageproc/algorithms/tiling/histogram.hpp>\n#include <libcvpg/imageproc/algorithms/tiling/functors/histogram.hpp>\n\nnamespace {\n\nvoid histogram_if_gray_8bit(std::uint8_t * src, std::vector<std::size_t> * dst, std::uint8_t * predicate_img, std::function<bool(std::uint8_t const & cluster)> predicate, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n{\n    const std::size_t image_width = parameters.image_width;\n\n    std::uint8_t * src_line = nullptr;\n    std::uint8_t * predicate_line = nullptr;\n\n    for (std::size_t y = from_y; y <= to_y; ++y)\n    {\n        src_line = src + image_width * y;\n        predicate_line = predicate_img + image_width * y;\n\n        for (std::size_t x = from_x; x <= to_x; ++x)\n        {\n            if (predicate(predicate_line[x]))\n            {\n                ++((*dst)[src_line[x]]);\n            }\n        }\n    }\n}\n\nstruct merge_histograms_task : public boost::asynchronous::continuation_task<std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > >>\n{\n    merge_histograms_task(std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > a, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > b)\n        : boost::asynchronous::continuation_task<std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > >(\"k_means_task::merge_histograms_task\")\n        , m_a(a)\n        , m_b(b)\n    {}\n\n    void operator()()\n    {\n        try\n        {\n            if (m_a->size() != m_b->size())\n            {\n                throw cvpg::exception(\"cannot merge histograms of different sizes\");\n            }\n\n            std::vector<cvpg::histogram<std::size_t> > histograms;\n            histograms.reserve(m_a->size());\n\n            for (std::size_t i = 0; i < m_a->size(); ++i)\n            {\n                histograms.push_back(m_a->at(i) + m_b->at(i));\n            }\n\n            this_task_result().set_value(std::make_shared<std::vector<cvpg::histogram<std::size_t> > >(std::move(histograms)));\n        }\n        catch (...)\n        {\n            this_task_result().set_exception(std::current_exception());\n        }\n    }\n\nprivate:\n    std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > m_a;\n    std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > m_b;\n};\n\nboost::asynchronous::detail::callback_continuation<std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > >\nmerge_histograms(std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > a, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > b)\n{\n    return boost::asynchronous::top_level_callback_continuation<std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > >(\n               merge_histograms_task(a, b)\n           );\n}\n\nstruct point\n{\n    point() = default;\n\n    point(std::uint8_t x_, std::uint8_t y_, std::uint8_t z_)\n        : x(x_)\n        , y(y_)\n        , z(z_)\n    {}\n\n    std::uint8_t x = 0;\n    std::uint8_t y = 0;\n    std::uint8_t z = 0;\n};\n\nvoid determine_cluster_gray_8bit(std::uint8_t * src, std::uint8_t * dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters, std::vector<point> centers)\n{\n    const std::size_t image_width = parameters.image_width;\n    const std::size_t clusters = centers.size();\n\n    std::vector<std::size_t> distances(clusters, 0);\n\n    std::uint8_t * src_line = nullptr;\n    std::uint8_t * dst_line = nullptr;\n\n    for (std::size_t y = from_y; y <= to_y; ++y)\n    {\n        const std::size_t offset_y = image_width * y;\n\n        src_line = src + offset_y;\n        dst_line = dst + offset_y;\n\n        for (std::size_t x = from_x; x <= to_x; ++x)\n        {\n            const point p = { src_line[x], 0, 0 };\n\n            for (std::size_t i = 0; i < clusters; ++i)\n            {\n                const point & c = centers[i];\n\n                const double dxs = static_cast<double>(static_cast<std::int16_t>(p.x) - static_cast<std::int16_t>(c.x));\n\n                // calculate the euclidian distance between current pixel and center of current cluster\n                distances[i] = static_cast<std::size_t>(std::abs(dxs));\n            }\n\n            // determine index of cluster with the smallest distance to current pixel (in color space) for c=[1..k]\n            const std::uint8_t c = static_cast<std::uint8_t>(std::distance(distances.begin(), std::min_element(distances.begin(), distances.end()))) + 1;\n\n            // write cluster number to destination image\n            dst_line[x] = c;\n        }\n    }\n}\n\nvoid determine_cluster_rgb_8bit(std::uint8_t * src_red, std::uint8_t * src_green, std::uint8_t * src_blue, std::uint8_t * dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters, std::vector<point> centers)\n{\n    const std::size_t image_width = parameters.image_width;\n    const std::size_t clusters = centers.size();\n\n    std::vector<std::size_t> distances(clusters, 0);\n\n    std::uint8_t * src_red_line = nullptr;\n    std::uint8_t * src_green_line = nullptr;\n    std::uint8_t * src_blue_line = nullptr;\n    std::uint8_t * dst_line = nullptr;\n\n    for (std::size_t y = from_y; y <= to_y; ++y)\n    {\n        const std::size_t offset_y = image_width * y;\n\n        src_red_line = src_red + offset_y;\n        src_green_line = src_green + offset_y;\n        src_blue_line = src_blue + offset_y;\n        dst_line = dst + offset_y;\n\n        for (std::size_t x = from_x; x <= to_x; ++x)\n        {\n            const point p = { src_red_line[x], src_green_line[x], src_blue_line[x] };\n\n            for (std::size_t i = 0; i < clusters; ++i)\n            {\n                const point & c = centers[i];\n\n                const double dxs = static_cast<double>(static_cast<std::int16_t>(p.x) - static_cast<std::int16_t>(c.x));\n                const double dys = static_cast<double>(static_cast<std::int16_t>(p.y) - static_cast<std::int16_t>(c.y));\n                const double dzs = static_cast<double>(static_cast<std::int16_t>(p.z) - static_cast<std::int16_t>(c.z));\n\n                // calculate the euclidian distance between current pixel and center of current cluster\n                distances[i] = static_cast<std::size_t>(std::sqrt(dxs * dxs + dys * dys + dzs * dzs));\n            }\n\n            // determine index of cluster with the smallest distance to current pixel (in color space) for c=[1..k]\n            const std::uint8_t c = static_cast<std::uint8_t>(std::distance(distances.begin(), std::min_element(distances.begin(), distances.end()))) + 1;\n\n            // write cluster number to destination image\n            dst_line[x] = c;\n        }\n    }\n}\n\ntemplate<class image_type>\nstruct determine_cluster_task : public boost::asynchronous::continuation_task<cvpg::image_gray_8bit> {};\n\ntemplate<>\nstruct determine_cluster_task<cvpg::image_gray_8bit> : public boost::asynchronous::continuation_task<cvpg::image_gray_8bit>\n{\n    determine_cluster_task(std::shared_ptr<cvpg::image_gray_8bit> image, std::vector<point> centers)\n        : boost::asynchronous::continuation_task<cvpg::image_gray_8bit>(\"k_means_task::determine_cluster_task\")\n        , m_image(std::move(image))\n        , m_centers(std::move(centers))\n    {}\n\n    void operator()()\n    {\n        auto tf = cvpg::imageproc::algorithms::tiling_functors::image<cvpg::image_gray_8bit, cvpg::image_gray_8bit>({{ *m_image }});\n        tf.parameters.image_width = m_image->width();\n        tf.parameters.image_height = m_image->height();\n        tf.parameters.cutoff_x = 512; // TODO use parameter\n        tf.parameters.cutoff_y = 512; // TODO use parameter\n\n        tf.tile_algorithm_task = [centers = m_centers](std::shared_ptr<cvpg::image_gray_8bit> src1, std::shared_ptr<cvpg::image_gray_8bit> /*src2*/, std::shared_ptr<cvpg::image_gray_8bit> dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n        {\n            determine_cluster_gray_8bit(src1->data(0).get(), dst->data(0).get(), from_x, to_x, from_y, to_y, std::move(parameters), std::move(centers));\n        };\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result()](auto cont_res)\n            {\n                try\n                {\n                    result.set_value(std::get<0>(cont_res).get());\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            cvpg::imageproc::algorithms::tiling(std::move(tf))\n        );\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_gray_8bit> m_image;\n\n    std::vector<point> m_centers;\n};\n\ntemplate<>\nstruct determine_cluster_task<cvpg::image_rgb_8bit> : public boost::asynchronous::continuation_task<cvpg::image_gray_8bit>\n{\n    determine_cluster_task(std::shared_ptr<cvpg::image_rgb_8bit> image, std::vector<point> centers)\n        : boost::asynchronous::continuation_task<cvpg::image_gray_8bit>(\"k_means_task::determine_cluster_task\")\n        , m_image(std::move(image))\n        , m_centers(std::move(centers))\n    {}\n\n    void operator()()\n    {\n        auto tf = cvpg::imageproc::algorithms::tiling_functors::image<cvpg::image_rgb_8bit, cvpg::image_gray_8bit>({{ *m_image }});\n        tf.parameters.image_width = m_image->width();\n        tf.parameters.image_height = m_image->height();\n        tf.parameters.cutoff_x = 512; // TODO use parameter\n        tf.parameters.cutoff_y = 512; // TODO use parameter\n\n        tf.tile_algorithm_task = [centers = m_centers](std::shared_ptr<cvpg::image_rgb_8bit> src1, std::shared_ptr<cvpg::image_rgb_8bit> /*src2*/, std::shared_ptr<cvpg::image_gray_8bit> dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n        {\n            determine_cluster_rgb_8bit(src1->data(0).get(), src1->data(1).get(), src1->data(2).get(), dst->data(0).get(), from_x, to_x, from_y, to_y, std::move(parameters), std::move(centers));\n        };\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result()](auto cont_res)\n            {\n                try\n                {\n                    result.set_value(std::get<0>(cont_res).get());\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            cvpg::imageproc::algorithms::tiling(std::move(tf))\n        );\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_rgb_8bit> m_image;\n\n    std::vector<point> m_centers;\n};\n\ntemplate<class image_type>\nboost::asynchronous::detail::callback_continuation<cvpg::image_gray_8bit> determine_cluster(std::shared_ptr<image_type> image, std::vector<point> centers)\n{\n    return boost::asynchronous::top_level_callback_continuation<cvpg::image_gray_8bit>(\n               determine_cluster_task<image_type>(std::move(image), std::move(centers))\n           );\n}\n\ntemplate<class image_type>\nstruct calculate_cluster_means_task : public boost::asynchronous::continuation_task<std::pair<cvpg::image_gray_8bit, std::vector<point> > > {};\n\ntemplate<>\nstruct calculate_cluster_means_task<cvpg::image_gray_8bit> : public boost::asynchronous::continuation_task<std::pair<cvpg::image_gray_8bit, std::vector<point> > >\n{\n    calculate_cluster_means_task(std::shared_ptr<cvpg::image_gray_8bit> image, cvpg::image_gray_8bit clusters, std::size_t k)\n        : boost::asynchronous::continuation_task<std::pair<cvpg::image_gray_8bit, std::vector<point> > >(\"k_means_task::calculate_cluster_means_task\")\n        , m_image(std::move(image))\n        , m_clusters(std::make_shared<cvpg::image_gray_8bit>(std::move(clusters)))\n        , m_k(k)\n    {}\n\n    void operator()()\n    {\n        auto tf = cvpg::imageproc::algorithms::tiling_functors::histogram<cvpg::image_gray_8bit, std::vector<cvpg::histogram<std::size_t> > >({{ *m_image }});\n        tf.parameters.image_width = m_image->width();\n        tf.parameters.image_height = m_image->height();\n        tf.parameters.cutoff_x = 512; // TODO use parameter\n        tf.parameters.cutoff_y = 512; // TODO use parameter\n\n        tf.tile_algorithm_task = [clusters = m_clusters, k = m_k](std::shared_ptr<cvpg::image_gray_8bit> src1, std::shared_ptr<cvpg::image_gray_8bit> /*src2*/, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n        {\n            // for each cluster ('k' pieces) create one histograms\n            std::vector<std::vector<std::size_t> > h(k, std::vector<std::size_t>(256));\n\n            for (std::size_t i = 0; i < k; ++i)\n            {\n                histogram_if_gray_8bit(src1->data(0).get(), &h[i], clusters->data(0).get(), [i](std::uint8_t const & c){ return c == (i + 1); }, from_x, to_x, from_y, to_y, parameters);\n            }\n\n            // move arrays into histogram structure\n            std::vector<cvpg::histogram<std::size_t> > histograms;\n            histograms.reserve(h.size());\n\n            std::for_each(h.begin(),\n                          h.end(),\n                          [&histograms](auto & histogram)\n                          {\n                              histograms.emplace_back(std::move(histogram));\n                          });\n\n            *dst = std::move(histograms);\n        };\n\n        tf.horizontal_merge_task = [](std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst1, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst2, std::size_t /*from_x*/, std::size_t /*to_x*/, std::size_t /*from_y*/, std::size_t /*to_y*/, cvpg::imageproc::algorithms::tiling_parameters /*parameters*/)\n        {\n            return merge_histograms(dst1, dst2);\n        };\n\n        tf.vertical_merge_task = [](std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst1, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst2, std::size_t /*from_x*/, std::size_t /*to_x*/, std::size_t /*from_y*/, std::size_t /*to_y*/, cvpg::imageproc::algorithms::tiling_parameters /*parameters*/)\n        {\n            return merge_histograms(dst1, dst2);\n        };\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result(), image = std::move(m_image), clusters = std::move(m_clusters), k = m_k](auto cont_res) mutable\n            {\n                try\n                {\n                    auto histograms = std::move(std::get<0>(cont_res).get());\n\n                    auto sum_histogram =\n                        [](const auto & histogram) -> std::pair<std::size_t, std::size_t>\n                        {\n                            std::size_t sum = 0;\n                            std::size_t entries = 0;\n\n                            for (std::size_t i = 0; i < histogram.bins(); ++i)\n                            {\n                                sum += i * histogram.at(i);\n                                entries += histogram.at(i);\n                            }\n\n                            return { sum, entries };\n                        };\n\n                    // create new mean centers of all clusters\n                    std::vector<point> centers;\n                    centers.reserve(k);\n\n                    for (std::size_t i = 0; i < k; ++i)\n                    {\n                        auto [sum, entries] = sum_histogram(histograms.at(i));\n\n                        centers.emplace_back(\n                            entries != 0 ? (sum / entries) : 0,\n                            0,\n                            0\n                        );\n                    }\n\n                    result.set_value({ std::move(*clusters), std::move(centers) });\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            cvpg::imageproc::algorithms::tiling(std::move(tf))\n        );\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_gray_8bit> m_image;\n\n    std::shared_ptr<cvpg::image_gray_8bit> m_clusters;\n\n    std::size_t m_k;\n};\n\ntemplate<>\nstruct calculate_cluster_means_task<cvpg::image_rgb_8bit> : public boost::asynchronous::continuation_task<std::pair<cvpg::image_gray_8bit, std::vector<point> > >\n{\n    calculate_cluster_means_task(std::shared_ptr<cvpg::image_rgb_8bit> image, cvpg::image_gray_8bit clusters, std::size_t k)\n        : boost::asynchronous::continuation_task<std::pair<cvpg::image_gray_8bit, std::vector<point> > >(\"k_means_task::calculate_cluster_means_task\")\n        , m_image(std::move(image))\n        , m_clusters(std::make_shared<cvpg::image_gray_8bit>(std::move(clusters)))\n        , m_k(k)\n    {}\n\n    void operator()()\n    {\n        auto tf = cvpg::imageproc::algorithms::tiling_functors::histogram<cvpg::image_rgb_8bit, std::vector<cvpg::histogram<std::size_t> > >({{ *m_image }});\n        tf.parameters.image_width = m_image->width();\n        tf.parameters.image_height = m_image->height();\n        tf.parameters.cutoff_x = 512; // TODO use parameter\n        tf.parameters.cutoff_y = 512; // TODO use parameter\n\n        tf.tile_algorithm_task = [clusters = m_clusters, k = m_k](std::shared_ptr<cvpg::image_rgb_8bit> src1, std::shared_ptr<cvpg::image_rgb_8bit> /*src2*/, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n        {\n            // for each cluster ('k' pieces) create 3 histograms for red, green and blue parts\n            std::vector<std::vector<std::size_t> > h(k * 3, std::vector<std::size_t>(256));\n\n            for (std::size_t i = 0; i < k; ++i)\n            {\n                histogram_if_gray_8bit(src1->data(0).get(), &h[i * 3 + 0], clusters->data(0).get(), [i](std::uint8_t const & c){ return c == (i + 1); }, from_x, to_x, from_y, to_y, parameters);\n                histogram_if_gray_8bit(src1->data(1).get(), &h[i * 3 + 1], clusters->data(0).get(), [i](std::uint8_t const & c){ return c == (i + 1); }, from_x, to_x, from_y, to_y, parameters);\n                histogram_if_gray_8bit(src1->data(2).get(), &h[i * 3 + 2], clusters->data(0).get(), [i](std::uint8_t const & c){ return c == (i + 1); }, from_x, to_x, from_y, to_y, parameters);\n            }\n\n            // move arrays into histogram structure\n            std::vector<cvpg::histogram<std::size_t> > histograms;\n            histograms.reserve(h.size());\n\n            std::for_each(h.begin(),\n                          h.end(),\n                          [&histograms](auto & histogram)\n                          {\n                              histograms.emplace_back(std::move(histogram));\n                          });\n\n            *dst = std::move(histograms);\n        };\n\n        tf.horizontal_merge_task = [](std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst1, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst2, std::size_t /*from_x*/, std::size_t /*to_x*/, std::size_t /*from_y*/, std::size_t /*to_y*/, cvpg::imageproc::algorithms::tiling_parameters /*parameters*/)\n        {\n            return merge_histograms(dst1, dst2);\n        };\n\n        tf.vertical_merge_task = [](std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst1, std::shared_ptr<std::vector<cvpg::histogram<std::size_t> > > dst2, std::size_t /*from_x*/, std::size_t /*to_x*/, std::size_t /*from_y*/, std::size_t /*to_y*/, cvpg::imageproc::algorithms::tiling_parameters /*parameters*/)\n        {\n            return merge_histograms(dst1, dst2);\n        };\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result(), image = std::move(m_image), clusters = std::move(m_clusters), k = m_k](auto cont_res) mutable\n            {\n                try\n                {\n                    auto histograms = std::move(std::get<0>(cont_res).get());\n\n                    if (histograms.size() % 3 != 0)\n                    {\n                        throw cvpg::exception(\"invalid amount of histograms\");\n                    }\n\n                    auto sum_histogram =\n                        [](const auto & histogram) -> std::pair<std::size_t, std::size_t>\n                        {\n                            std::size_t sum = 0;\n                            std::size_t entries = 0;\n\n                            for (std::size_t i = 0; i < histogram.bins(); ++i)\n                            {\n                                sum += i * histogram.at(i);\n                                entries += histogram.at(i);\n                            }\n\n                            return { sum, entries };\n                        };\n\n                    // create new mean centers of all clusters\n                    std::vector<point> centers;\n                    centers.reserve(k);\n\n                    for (std::size_t i = 0; i < k; ++i)\n                    {\n                        auto [sum_red, entries_red] = sum_histogram(histograms.at(i * 3 + 0));\n                        auto [sum_green, entries_green] = sum_histogram(histograms.at(i * 3 + 1));\n                        auto [sum_blue, entries_blue] = sum_histogram(histograms.at(i * 3 + 2));\n\n                        centers.emplace_back(\n                            entries_red != 0 ? (sum_red / entries_red) : 0,\n                            entries_green != 0 ? (sum_green / entries_green) : 0,\n                            entries_blue != 0 ? (sum_blue / entries_blue) : 0\n                        );\n                    }\n\n                    result.set_value({ std::move(*clusters), std::move(centers) });\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            cvpg::imageproc::algorithms::tiling(std::move(tf))\n        );\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_rgb_8bit> m_image;\n\n    std::shared_ptr<cvpg::image_gray_8bit> m_clusters;\n\n    std::size_t m_k;\n};\n\ntemplate<class image_type>\nboost::asynchronous::detail::callback_continuation<std::pair<cvpg::image_gray_8bit, std::vector<point> > > calculate_cluster_means(std::shared_ptr<image_type> image, cvpg::image_gray_8bit clusters, std::size_t k)\n{\n    return boost::asynchronous::top_level_callback_continuation<std::pair<cvpg::image_gray_8bit, std::vector<point> > >(\n               calculate_cluster_means_task<image_type>(std::move(image), std::move(clusters), k)\n           );\n}\n\nvoid create_cluster_result_gray_8bit(std::uint8_t * src, std::uint8_t * dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters, std::vector<point> centers)\n{\n    const std::size_t image_width = parameters.image_width;\n\n    std::uint8_t * src_line = nullptr;\n    std::uint8_t * dst_line = nullptr;\n\n    for (std::size_t y = from_y; y <= to_y; ++y)\n    {\n        const std::size_t offset_y = image_width * y;\n\n        src_line = src + offset_y;\n        dst_line = dst + offset_y;\n\n        for (std::size_t x = from_x; x <= to_x; ++x)\n        {\n            const std::uint8_t cluster_number = src_line[x] - 1;\n            const auto & cluster = centers.at(cluster_number);\n\n            dst_line[x] = cluster.x;\n        }\n    }\n}\n\nvoid create_cluster_result_rgb_8bit(std::uint8_t * src, std::uint8_t * dst_red, std::uint8_t * dst_green, std::uint8_t * dst_blue, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters, std::vector<point> centers)\n{\n    const std::size_t image_width = parameters.image_width;\n\n    std::uint8_t * src_line = nullptr;\n    std::uint8_t * dst_red_line = nullptr;\n    std::uint8_t * dst_green_line = nullptr;\n    std::uint8_t * dst_blue_line = nullptr;\n\n    for (std::size_t y = from_y; y <= to_y; ++y)\n    {\n        const std::size_t offset_y = image_width * y;\n\n        src_line = src + offset_y;\n        dst_red_line = dst_red + offset_y;\n        dst_green_line = dst_green + offset_y;\n        dst_blue_line = dst_blue + offset_y;\n\n        for (std::size_t x = from_x; x <= to_x; ++x)\n        {\n            const std::uint8_t cluster_number = src_line[x] - 1;\n            const auto & cluster = centers.at(cluster_number);\n\n            dst_red_line[x] = cluster.x;\n            dst_green_line[x] = cluster.y;\n            dst_blue_line[x] = cluster.z;\n        }\n    }\n}\n\ntemplate<class image_type>\nstruct create_result_image_task : public boost::asynchronous::continuation_task<image_type> {};\n\ntemplate<>\nstruct create_result_image_task<cvpg::image_gray_8bit> : public boost::asynchronous::continuation_task<cvpg::image_gray_8bit>\n{\n    create_result_image_task(std::shared_ptr<cvpg::image_gray_8bit> clusters, std::vector<point> centers)\n        : boost::asynchronous::continuation_task<cvpg::image_gray_8bit>(\"k_means_task::create_result_image_task\")\n        , m_clusters(std::move(clusters))\n        , m_centers(std::move(centers))\n    {}\n\n    void operator()()\n    {\n        auto result_image = std::make_shared<cvpg::image_gray_8bit>(m_clusters->width(), m_clusters->height());\n\n        auto tf = cvpg::imageproc::algorithms::tiling_functors::image<cvpg::image_gray_8bit, cvpg::image_gray_8bit>({{ *m_clusters }});\n        tf.parameters.image_width = m_clusters->width();\n        tf.parameters.image_height = m_clusters->height();\n        tf.parameters.cutoff_x = 512; // TODO use parameter\n        tf.parameters.cutoff_y = 512; // TODO use parameter\n\n        tf.tile_algorithm_task = [centers = m_centers](std::shared_ptr<cvpg::image_gray_8bit> src1, std::shared_ptr<cvpg::image_gray_8bit> /*src2*/, std::shared_ptr<cvpg::image_gray_8bit> dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n        {\n            create_cluster_result_gray_8bit(src1->data(0).get(), dst->data(0).get(), from_x, to_x, from_y, to_y, std::move(parameters), std::move(centers));\n        };\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result()](auto cont_res)\n            {\n                try\n                {\n                    result.set_value(std::get<0>(cont_res).get());\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            cvpg::imageproc::algorithms::tiling(std::move(tf))\n        );\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_gray_8bit> m_clusters;\n\n    std::vector<point> m_centers;\n};\n\ntemplate<>\nstruct create_result_image_task<cvpg::image_rgb_8bit> : public boost::asynchronous::continuation_task<cvpg::image_rgb_8bit>\n{\n    create_result_image_task(std::shared_ptr<cvpg::image_gray_8bit> clusters, std::vector<point> centers)\n        : boost::asynchronous::continuation_task<cvpg::image_rgb_8bit>(\"k_means_task::create_result_image_task\")\n        , m_clusters(std::move(clusters))\n        , m_centers(std::move(centers))\n    {}\n\n    void operator()()\n    {\n        auto result_image = std::make_shared<cvpg::image_rgb_8bit>(m_clusters->width(), m_clusters->height());\n\n        auto tf = cvpg::imageproc::algorithms::tiling_functors::image<cvpg::image_gray_8bit, cvpg::image_rgb_8bit>({{ *m_clusters }});\n        tf.parameters.image_width = m_clusters->width();\n        tf.parameters.image_height = m_clusters->height();\n        tf.parameters.cutoff_x = 512; // TODO use parameter\n        tf.parameters.cutoff_y = 512; // TODO use parameter\n\n        tf.tile_algorithm_task = [centers = m_centers](std::shared_ptr<cvpg::image_gray_8bit> src1, std::shared_ptr<cvpg::image_gray_8bit> /*src2*/, std::shared_ptr<cvpg::image_rgb_8bit> dst, std::size_t from_x, std::size_t to_x, std::size_t from_y, std::size_t to_y, cvpg::imageproc::algorithms::tiling_parameters parameters)\n        {\n            create_cluster_result_rgb_8bit(src1->data(0).get(), dst->data(0).get(), dst->data(1).get(), dst->data(2).get(), from_x, to_x, from_y, to_y, std::move(parameters), std::move(centers));\n        };\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result()](auto cont_res)\n            {\n                try\n                {\n                    result.set_value(std::get<0>(cont_res).get());\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            cvpg::imageproc::algorithms::tiling(std::move(tf))\n        );\n    }\n\nprivate:\n    std::shared_ptr<cvpg::image_gray_8bit> m_clusters;\n\n    std::vector<point> m_centers;\n};\n\ntemplate<class image_type>\nboost::asynchronous::detail::callback_continuation<image_type> create_result_image(std::shared_ptr<cvpg::image_gray_8bit> clusters, std::vector<point> centers)\n{\n    return boost::asynchronous::top_level_callback_continuation<image_type>(\n               create_result_image_task<image_type>(std::move(clusters), std::move(centers))\n           );\n}\n\ntemplate<class image_type>\nstruct k_means_iteration_task : public boost::asynchronous::continuation_task<image_type>\n{\n    k_means_iteration_task(std::shared_ptr<image_type> image, std::vector<point> centers, std::size_t k, std::size_t iteration, std::size_t max_iterations, std::uint8_t eps)\n        : boost::asynchronous::continuation_task<image_type>(std::string(\"k_means_task::k_means_iteration_task#iteration\").append(std::to_string(iteration)))\n        , m_image(std::move(image))\n        , m_centers(std::move(centers))\n        , m_k(k)\n        , m_iteration(iteration)\n        , m_max_iterations(max_iterations)\n        , m_eps(eps)\n    {}\n\n    void operator()()\n    {\n        auto old_centers = m_centers;\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result(), old_centers = std::move(old_centers), iteration = m_iteration, max_iterations = m_max_iterations, image = m_image, k = m_k, eps = m_eps](auto cont_res) mutable\n            {\n                try\n                {\n                    auto cluster_result = std::move(std::get<0>(cont_res).get());\n\n                    auto clusters_image = std::make_shared<cvpg::image_gray_8bit>(std::move(cluster_result.first));\n                    auto new_centers = std::move(cluster_result.second);\n\n                    // calculate the distances of old and new center points\n                    std::vector<std::uint8_t> distances;\n                    distances.reserve(old_centers.size());\n\n                    std::transform(old_centers.begin(),\n                                   old_centers.end(),\n                                   new_centers.begin(),\n                                   std::back_inserter(distances),\n                                   [](point const & a, point const & b)\n                                   {\n                                       const auto dx = static_cast<std::int16_t>(a.x) - static_cast<std::int16_t>(b.x);\n                                       const auto dy = static_cast<std::int16_t>(a.y) - static_cast<std::int16_t>(b.y);\n                                       const auto dz = static_cast<std::int16_t>(a.z) - static_cast<std::int16_t>(b.z);\n\n                                       return static_cast<std::uint8_t>(std::sqrt(dx * dx + dy * dy + dz * dz));\n                                   });\n\n                    // check if all distances are not moving (moving below threshold)\n                    const bool all_centers_steady = std::all_of(distances.begin(),\n                                                                distances.end(),\n                                                                [eps](auto const & distance)\n                                                                {\n                                                                    return distance < eps; // TODO define a parameter for this !!!\n                                                                });\n\n                    // check if no further iterations are needed\n                    if ((iteration + 1) >= max_iterations || all_centers_steady)\n                    {\n                        boost::asynchronous::create_callback_continuation(\n                            [result = std::move(result)](auto cont_res) mutable\n                            {\n                                try\n                                {\n                                    result.set_value(std::move(std::get<0>(cont_res).get()));\n                                }\n                                catch (...)\n                                {\n                                    result.set_exception(std::current_exception());\n                                }\n                            },\n                            create_result_image<image_type>(clusters_image, std::move(new_centers))\n                        );\n                    }\n                    else\n                    {\n                        boost::asynchronous::create_callback_continuation(\n                            [result = std::move(result)](auto cont_res) mutable\n                            {\n                                try\n                                {\n                                    result.set_value(std::move(std::get<0>(cont_res).get()));\n                                }\n                                catch (...)\n                                {\n                                    result.set_exception(std::current_exception());\n                                }\n                            },\n                            k_means_iteration_task(image, std::move(new_centers), k, iteration + 1, max_iterations, eps)\n                        );\n                    }\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            boost::asynchronous::then(\n                determine_cluster<image_type>(m_image, std::move(m_centers)),\n                [image = m_image, k = m_k](auto cont_res)\n                {\n                    return calculate_cluster_means<image_type>(image, std::move(cont_res.get()), k);\n                }\n            )\n        );\n    }\n\nprivate:\n    std::shared_ptr<image_type> m_image;\n\n    std::vector<point> m_centers;\n\n    std::size_t m_k;\n\n    std::size_t m_iteration;\n    std::size_t m_max_iterations;\n\n    std::uint8_t m_eps;\n};\n\ntemplate<class image_type>\nstruct k_means_task : public boost::asynchronous::continuation_task<image_type>\n{\n    k_means_task(image_type image, std::size_t k, std::size_t max_iterations, std::uint8_t eps)\n        : boost::asynchronous::continuation_task<image_type>(\"k_means_task\")\n        , m_image(std::make_shared<image_type>(std::move(image)))\n        , m_k(k)\n        , m_max_iterations(max_iterations)\n        , m_eps(eps)\n    {}\n\n    void operator()()\n    {\n        // create K random numbers\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_int_distribution<> distribution(0, 255);\n\n        std::vector<point> centers;\n        centers.reserve(m_k);\n\n        for (std::size_t i = 0; i < m_k; ++i)\n        {\n            centers.emplace_back(distribution(gen), distribution(gen), distribution(gen));\n        }\n\n        boost::asynchronous::create_callback_continuation(\n            [result = this->this_task_result()](auto cont_res)\n            {\n                try\n                {\n                    result.set_value(std::move(std::get<0>(cont_res).get()));\n                }\n                catch (...)\n                {\n                    result.set_exception(std::current_exception());\n                }\n            },\n            k_means_iteration_task(m_image, std::move(centers), m_k, 0, m_max_iterations, m_eps)\n        );\n    }\n\nprivate:\n    std::shared_ptr<image_type> m_image;\n\n    std::size_t m_k;\n\n    std::size_t m_max_iterations;\n\n    std::uint8_t m_eps;\n};\n\n}\n\nnamespace cvpg::imageproc::algorithms {\n\nboost::asynchronous::detail::callback_continuation<image_gray_8bit> k_means(image_gray_8bit image, std::size_t k, std::size_t max_iterations, std::uint8_t eps)\n{\n    return boost::asynchronous::top_level_callback_continuation<image_gray_8bit>(\n               k_means_task(std::move(image), k, max_iterations, eps)\n           );\n}\n\nboost::asynchronous::detail::callback_continuation<image_rgb_8bit> k_means(image_rgb_8bit image, std::size_t k, std::size_t max_iterations, std::uint8_t eps)\n{\n    return boost::asynchronous::top_level_callback_continuation<image_rgb_8bit>(\n               k_means_task(std::move(image), k, max_iterations, eps)\n           );\n}\n\n} // namespace cvpg::imageproc::algoritms\n", "meta": {"hexsha": "e00d668db31a10860070698ecd185f24f55ced15", "size": 37465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libcvpg/imageproc/algorithms/k_means.cpp", "max_stars_repo_name": "franz-alt/cv-playground", "max_stars_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libcvpg/imageproc/algorithms/k_means.cpp", "max_issues_repo_name": "franz-alt/cv-playground", "max_issues_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libcvpg/imageproc/algorithms/k_means.cpp", "max_forks_repo_name": "franz-alt/cv-playground", "max_forks_repo_head_hexsha": "d6c3bbdb500bf121c28299d117e459730b2b912d", "max_forks_repo_licenses": ["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.0137772675, "max_line_length": 360, "alphanum_fraction": 0.574776458, "num_tokens": 9029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180408675583, "lm_q2_score": 0.015424555193445825, "lm_q1q2_score": 0.005994260420530438}}
{"text": "// Copyright (C) 2008-2011 Anders Logg and Ola Skavhaug\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// Modified by Niclas Jansson 2009.\n// Modified by Garth N. Wells 2010.\n//\n// First added:  2008-08-12\n// Last changed: 2011-11-14\n\n#include <ufc.h>\n#include <boost/random.hpp>\n#include <boost/unordered_map.hpp>\n\n#include <dolfin/common/Timer.h>\n#include <dolfin/log/log.h>\n#include <dolfin/mesh/BoundaryMesh.h>\n#include <dolfin/mesh/Facet.h>\n#include <dolfin/mesh/Mesh.h>\n#include <dolfin/mesh/Vertex.h>\n#include \"DofMap.h\"\n#include \"UFCCell.h\"\n#include \"UFCMesh.h\"\n#include \"DofMapBuilder.h\"\n\nusing namespace dolfin;\n\n//-----------------------------------------------------------------------------\nvoid DofMapBuilder::build(DofMap& dofmap, const Mesh& dolfin_mesh,\n                          const UFCMesh& ufc_mesh, bool distributed)\n{\n  // Start timer for dofmap initialization\n  Timer t0(\"Init dofmap\");\n\n  // Create space for dof map\n  dofmap._dofmap.resize(dolfin_mesh.num_cells());\n\n  dofmap._off_process_owner.clear();\n\n  dolfin_assert(dofmap._ufc_dofmap);\n\n  std::cout << \"DofMapBuilder: initialized\" << std::endl;\n\n  // Build dofmap from ufc::dofmap\n  dolfin::UFCCell ufc_cell(dolfin_mesh);\n  std::cout << \"Processing cells: \";\n  for (dolfin::CellIterator cell(dolfin_mesh); !cell.end(); ++cell)\n  {\n    std::cout << cell->index() << \",\";\n    // Update UFC cell\n    ufc_cell.update(*cell);\n\n    // Get standard local dimension\n    const unsigned int local_dim = dofmap._ufc_dofmap->local_dimension(ufc_cell);\n    dofmap._dofmap[cell->index()].resize(local_dim);\n\n    // Tabulate standard UFC dof map\n    dofmap._ufc_dofmap->tabulate_dofs(&dofmap._dofmap[cell->index()][0],\n                                      ufc_mesh, ufc_cell);\n  }\n  std::cout << std::endl;\n  std::cout << \"DofMapBuilder: dofmap built\" << std::endl;\n\n  // Build (renumber) dofmap when running in parallel\n  if (distributed)\n  {\n    // Build set of global dofs\n    const set global_dofs = compute_global_dofs(dofmap, dolfin_mesh);\n\n    // Build distributed dof map\n    build_distributed(dofmap, global_dofs, dolfin_mesh);\n  }\n  else\n    dofmap._ownership_range = std::make_pair(0, dofmap.global_dimension());\n}\n//-----------------------------------------------------------------------------\nvoid DofMapBuilder::build_distributed(DofMap& dofmap,\n                                      const DofMapBuilder::set& global_dofs,\n                                      const Mesh& mesh)\n{\n  // Create data structures\n  DofMapBuilder::set owned_dofs, shared_owned_dofs, shared_unowned_dofs;\n\n  // Computed owned and shared dofs (and owned and un-owned)\n  compute_ownership(owned_dofs, shared_owned_dofs, shared_unowned_dofs,\n                    dofmap, global_dofs, mesh);\n\n  // Renumber dofs owned dofs and received new numbering for unowned shared dofs\n  parallel_renumber(owned_dofs, shared_owned_dofs, shared_unowned_dofs,\n                    dofmap, mesh);\n}\n//-----------------------------------------------------------------------------\nvoid DofMapBuilder::compute_ownership(set& owned_dofs, set& shared_owned_dofs,\n                                      set& shared_unowned_dofs,\n                                      const DofMap& dofmap,\n                                      const DofMapBuilder::set& global_dofs,\n                                      const Mesh& mesh)\n{\n  log(TRACE, \"Determining dof ownership for parallel dof map\");\n\n  // Create a radom number generator for ownership 'voting'\n  boost::mt19937 engine(MPI::process_number());\n  boost::uniform_int<> distribution(0, 100000000);\n  boost::variate_generator<boost::mt19937&, boost::uniform_int<> > rng(engine, distribution);\n\n  // Clear data structures\n  owned_dofs.clear();\n  shared_owned_dofs.clear();\n  shared_unowned_dofs.clear();\n\n  // Data structures for computing ownership\n  boost::unordered_map<uint, uint> dof_vote;\n  std::vector<uint> facet_dofs(dofmap.num_facet_dofs());\n\n  // Communication buffer\n  std::vector<uint> send_buffer;\n\n  // Extract the interior boundary\n  BoundaryMesh interior_boundary;\n  interior_boundary.init_interior_boundary(mesh);\n\n  // Build set of dofs on process boundary (assume all are owned by this process)\n  const MeshFunction<unsigned int>& cell_map = interior_boundary.cell_map();\n  if (cell_map.size() > 0)\n  {\n    for (CellIterator bc(interior_boundary); !bc.end(); ++bc)\n    {\n      // Get boundary facet\n      Facet f(mesh, cell_map[*bc]);\n\n      // Get cell to which facet belongs (pick first)\n      Cell c(mesh, f.entities(mesh.topology().dim())[0]);\n\n      // Tabulate dofs on cell\n      const std::vector<uint>& cell_dofs = dofmap.cell_dofs(c.index());\n\n      // Tabulate which dofs are on the facet\n      dofmap.tabulate_facet_dofs(&facet_dofs[0], c.index(f));\n\n      // Insert shared dofs into set and assign a 'vote'\n      for (uint i = 0; i < dofmap.num_facet_dofs(); i++)\n      {\n        if (shared_owned_dofs.find(cell_dofs[facet_dofs[i]]) == shared_owned_dofs.end())\n        {\n          shared_owned_dofs.insert(cell_dofs[facet_dofs[i]]);\n          dof_vote[cell_dofs[facet_dofs[i]]] = rng();\n\n          send_buffer.push_back(cell_dofs[facet_dofs[i]]);\n          send_buffer.push_back(dof_vote[cell_dofs[facet_dofs[i]]]);\n        }\n      }\n    }\n  }\n\n  // Decide ownership of shared dofs\n  const uint num_proc = MPI::num_processes();\n  const uint proc_num = MPI::process_number();\n  //const uint max_recv = MPI::max(send_buffer.size());\n  std::vector<uint> recv_buffer;\n  for (uint k = 1; k < MPI::num_processes(); ++k)\n  {\n    const uint src  = (proc_num - k + num_proc) % num_proc;\n    const uint dest = (proc_num + k) % num_proc;\n    MPI::send_recv(send_buffer, dest, recv_buffer, src);\n\n    for (uint i = 0; i < recv_buffer.size(); i += 2)\n    {\n      const uint received_dof  = recv_buffer[i];\n      const uint received_vote = recv_buffer[i + 1];\n      if (shared_owned_dofs.find(received_dof) != shared_owned_dofs.end())\n      {\n        // Move dofs with higher ownership votes from shared to shared but not owned\n        if (received_vote < dof_vote[received_dof])\n        {\n          shared_unowned_dofs.insert(received_dof);\n          shared_owned_dofs.erase(received_dof);\n        }\n        else if (received_vote == dof_vote[received_dof])\n        {\n          // FIXME: Eventually replace this with a more robust condition. It's\n          // good for testing that ownership of shared dofs is spread roughly\n          // equally\n          dolfin_error(\"DofMapBuilder.cpp\",\n                       \"compute mapping of degrees of freedom\",\n                       \"Cannot decide on dof ownership; votes are equal\");\n        }\n      }\n    }\n  }\n\n  // Add/remove global dofs to relevant sets (process 0 owns local dofs)\n  if (MPI::process_number() == 0)\n  {\n    shared_owned_dofs.insert(global_dofs.begin(), global_dofs.end());\n    for (set::const_iterator dof = global_dofs.begin(); dof != global_dofs.begin(); ++dof)\n    {\n      set::const_iterator _dof = shared_unowned_dofs.find(*dof);\n      if (_dof != shared_unowned_dofs.end())\n        shared_unowned_dofs.erase(_dof);\n    }\n  }\n  else\n  {\n    shared_unowned_dofs.insert(global_dofs.begin(), global_dofs.end());\n    for (set::const_iterator dof = global_dofs.begin(); dof != global_dofs.begin(); ++dof)\n    {\n      set::const_iterator _dof = shared_owned_dofs.find(*dof);\n      if (_dof != shared_owned_dofs.end())\n        shared_owned_dofs.erase(_dof);\n    }\n  }\n\n  // Mark all shared and owned dofs as owned by the processes\n  for (CellIterator cell(mesh); !cell.end(); ++cell)\n  {\n    const std::vector<uint>& cell_dofs = dofmap.cell_dofs(cell->index());\n    const uint cell_dimension = dofmap.cell_dimension(cell->index());\n    for (uint i = 0; i < cell_dimension; ++i)\n    {\n      // Mark dof as owned if in unowned set\n      if (shared_unowned_dofs.find(cell_dofs[i]) == shared_unowned_dofs.end())\n        owned_dofs.insert(cell_dofs[i]);\n    }\n  }\n\n  // Check that sum of locally owned dofs is equal to global dimension\n  const uint _owned_dim = owned_dofs.size();\n  dolfin_assert(MPI::sum(_owned_dim) == dofmap.global_dimension());\n\n  log(TRACE, \"Finished determining dof ownership for parallel dof map\");\n}\n//-----------------------------------------------------------------------------\nvoid DofMapBuilder::parallel_renumber(const set& owned_dofs,\n                             const set& shared_owned_dofs,\n                             const set& shared_unowned_dofs,\n                             DofMap& dofmap, const Mesh& mesh)\n{\n  log(TRACE, \"Renumber dofs for parallel dof map\");\n\n  // FIXME: Handle double-renumbered dof map\n  if (dofmap.ufc_map_to_dofmap.size() > 0)\n  {\n    dolfin_error(\"DofMapBuilder.cpp\",\n                 \"compute parallel renumbering of degrees of freedom\",\n                 \"The degree of freedom mapping cannot (yet) be renumbered twice\");\n  }\n\n  const std::vector<std::vector<uint> >& old_dofmap = dofmap._dofmap;\n  std::vector<std::vector<uint> > new_dofmap(old_dofmap.size());\n  dolfin_assert(old_dofmap.size() == mesh.num_cells());\n\n  // Compute offset for owned and non-shared dofs\n  const uint process_offset = MPI::global_offset(owned_dofs.size(), true);\n\n  // Clear some data\n  dofmap._off_process_owner.clear();\n\n  // Map from old to new index for dofs\n  boost::unordered_map<uint, uint> old_to_new_dof_index;\n\n  // Renumber owned dofs and buffer dofs that are owned but shared with another\n  // process\n  uint counter = 0;\n  std::vector<uint> send_buffer;\n  for (set_iterator owned_dof = owned_dofs.begin(); owned_dof != owned_dofs.end(); ++owned_dof, counter++)\n  {\n    // Set new dof number\n    old_to_new_dof_index[*owned_dof] = process_offset + counter;\n\n    // Update UFC-to-renumbered map for new number\n    dofmap.ufc_map_to_dofmap[*owned_dof] = process_offset + counter;\n\n    // If this dof is shared and owned, buffer old and new index for sending\n    if (shared_owned_dofs.find(*owned_dof) != shared_owned_dofs.end())\n    {\n      send_buffer.push_back(*owned_dof);\n      send_buffer.push_back(process_offset + counter);\n    }\n  }\n\n  // Exchange new dof numbers for dofs that are shared\n  const uint num_proc = MPI::num_processes();\n  const uint proc_num = MPI::process_number();\n  //const uint max_recv = MPI::max(send_buffer.size());\n  std::vector<uint> recv_buffer;\n  for (uint k = 1; k < MPI::num_processes(); ++k)\n  {\n    const uint src  = (proc_num - k + num_proc) % num_proc;\n    const uint dest = (proc_num + k) % num_proc;\n    MPI::send_recv(send_buffer, dest, recv_buffer, src);\n\n    // Add dofs renumbered by another process to the old-to-new map\n    for (uint i = 0; i < recv_buffer.size(); i += 2)\n    {\n      const uint received_old_dof_index = recv_buffer[i];\n      const uint received_new_dof_index = recv_buffer[i + 1];\n\n      // Check if this process has shared dof (and is not the owner)\n      if (shared_unowned_dofs.find(received_old_dof_index) != shared_unowned_dofs.end())\n      {\n        // Add to old-to-new dof map\n        old_to_new_dof_index[received_old_dof_index] = received_new_dof_index;\n\n        // Store map from off-process dof to owner\n        dofmap._off_process_owner[received_new_dof_index] = src;\n\n        // Update UFC-to-renumbered map\n        dofmap.ufc_map_to_dofmap[received_old_dof_index] = received_new_dof_index;\n      }\n    }\n  }\n\n  // Build new dof map\n  for (CellIterator cell(mesh); !cell.end(); ++cell)\n  {\n    const uint cell_index = cell->index();\n    const uint cell_dimension = dofmap.cell_dimension(cell_index);\n\n    // Resize cell map and insert dofs\n    new_dofmap[cell_index].resize(cell_dimension);\n    for (uint i = 0; i < cell_dimension; ++i)\n    {\n      const uint old_index = old_dofmap[cell_index][i];\n      new_dofmap[cell_index][i] = old_to_new_dof_index[old_index];\n    }\n  }\n\n  // Set new dof map\n  dofmap._dofmap = new_dofmap;\n\n  // Set ownership range\n  dofmap._ownership_range = std::make_pair<uint, uint>(process_offset, process_offset + owned_dofs.size());\n\n  log(TRACE, \"Finished renumbering dofs for parallel dof map\");\n}\n//-----------------------------------------------------------------------------\nDofMapBuilder::set DofMapBuilder::compute_global_dofs(const DofMap& dofmap,\n                                                       const Mesh& dolfin_mesh)\n{\n  // Wrap UFC dof map\n  boost::shared_ptr<const ufc::dofmap> _dofmap(dofmap._ufc_dofmap.get(),\n                                               NoDeleter());\n\n  // Create UFCMesh\n  const UFCMesh ufc_mesh(dolfin_mesh);\n\n  // Compute global dof indices\n  uint offset = 0;\n  set global_dof_indices;\n  compute_global_dofs(global_dof_indices, offset, _dofmap, dolfin_mesh, ufc_mesh);\n\n  return global_dof_indices;\n}\n//-----------------------------------------------------------------------------\nvoid DofMapBuilder::compute_global_dofs(DofMapBuilder::set& global_dofs,\n                            uint& offset,\n                            boost::shared_ptr<const ufc::dofmap> dofmap,\n                            const Mesh& dolfin_mesh, const UFCMesh& ufc_mesh)\n{\n  dolfin_assert(dofmap);\n  const uint D = dolfin_mesh.topology().dim();\n\n  if (dofmap->num_sub_dofmaps() == 0)\n  {\n    // Check if dofmap is for global dofs\n    bool global_dof = true;\n    for (uint d = 0; d <= D; ++d)\n    {\n      if (dofmap->needs_mesh_entities(d))\n      {\n        global_dof = false;\n        break;\n      }\n    }\n\n    if (global_dof)\n    {\n      // Check that we have just one dof\n      if (dofmap->global_dimension() != 1)\n      {\n        dolfin_error(\"DofMapBuilder.cpp\",\n                     \"compute global degrees of freedom\",\n                     \"Global degree of freedom has dimension != 1\");\n      }\n\n      boost::scoped_ptr<ufc::mesh> ufc_mesh(new ufc::mesh);\n      boost::scoped_ptr<ufc::cell> ufc_cell(new ufc::cell);\n      uint dof = 0;\n      dofmap->tabulate_dofs(&dof, *ufc_mesh, *ufc_cell);\n\n      // Insert global dof index\n      std::pair<DofMapBuilder::set::iterator, bool> ret = global_dofs.insert(dof + offset);\n      if (!ret.second)\n      {\n        dolfin_error(\"DofMapBuilder.cpp\",\n                     \"compute global degrees of freedom\",\n                     \"Global degree of freedom already exists\");\n      }\n    }\n  }\n  else\n  {\n    for (uint i = 0; i < dofmap->num_sub_dofmaps(); ++i)\n    {\n      // Extract sub-dofmap and intialise\n      boost::shared_ptr<ufc::dofmap> sub_dofmap(dofmap->create_sub_dofmap(i));\n      DofMap::init_ufc_dofmap(*sub_dofmap, ufc_mesh, dolfin_mesh);\n\n      compute_global_dofs(global_dofs, offset, sub_dofmap, dolfin_mesh,\n                          ufc_mesh);\n\n      // Get offset\n      if (sub_dofmap->num_sub_dofmaps() == 0)\n        offset += sub_dofmap->global_dimension();\n    }\n  }\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "09c3f17d6a45e9662d3fb79823bb3146f6fea8fd", "size": 15408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/fem/DofMapBuilder.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/fem/DofMapBuilder.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/fem/DofMapBuilder.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.6666666667, "max_line_length": 107, "alphanum_fraction": 0.6281152648, "num_tokens": 3909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16026602430611822, "lm_q2_score": 0.03732688306051186, "lm_q1q2_score": 0.005982231147847626}}
{"text": "/* Copyright 2018 Nils Bore (nbore@kth.se)\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * 2. 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 * 3. Neither the name of the copyright holder nor the names of its contributors may be used 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 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <data_tools/navi_data.h>\n#include <data_tools/colormap.h>\n#include <data_tools/transforms.h>\n\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <tuple>\n\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n#include <boost/date_time.hpp>\n#undef BOOST_NO_CXX11_SCOPED_ENUMS\n\n#include <cereal/archives/json.hpp>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace navi_data {\n\nusing namespace std_data;\n\nvoid match_timestamps(mbes_ping::PingsT& pings, nav_entry::EntriesT& entries)\n{\n\n    std::stable_sort(pings.begin(), pings.end(), [](const mbes_ping& ping1, const mbes_ping& ping2) {\n        return ping1.time_stamp_ < ping2.time_stamp_;\n    });\n    std::sort(entries.begin(), entries.end(), [](const nav_entry& entry1, const nav_entry& entry2) {\n        return entry1.time_stamp_ < entry2.time_stamp_;\n    });\n\n    // NOTE: this works, but is terribly slow\n    /*\n    for (mbes_ping& ping : pings) {\n        auto entry = std::min_element(entries.begin(), entries.end(), [&](const nav_entry& entry1, const nav_entry& entry2) {\n            return abs(entry1.time_stamp_ - ping.time_stamp_) < abs(entry2.time_stamp_ - ping.time_stamp_);\n        });\n        ping.pos_ = entry->pos_;\n        //cout << \"Ping \" << ping.time_string_ << \" closest to Entry \" << entry->time_string_ << endl;\n    }\n    */\n\n    auto pos = entries.begin();\n    for (mbes_ping& ping : pings) {\n        pos = std::find_if(pos, entries.end(), [&](const nav_entry& entry) {\n            return entry.time_stamp_ > ping.time_stamp_;\n        });\n        if (pos == entries.end()) {\n            //cout << \"Ping \" << ping.time_string_ << \" closest to LAST Entry \" << entries.back().time_string_ << endl;\n            ping.pos_ = entries.back().pos_;\n        }\n        else {\n            ping.pos_ = pos->pos_;\n            //cout << \"Ping \" << ping.time_string_ << \" closest to Entry \" << pos->time_string_ << endl;\n        }\n    }\n}\n\n\nvoid save_submaps_files(const std_data::mbes_ping::PingsT& pings, const boost::filesystem::path& folder){\n\n    // Save submaps in external files\n    string file_name;\n    int sm_cnt = 0;\n    std::ofstream myfile;\n    for (const std_data::mbes_ping& ping_i: pings){\n        // If new submap, open new file\n        if(ping_i.first_in_file_){\n            myfile.close();\n            file_name = \"/submap_\" + std::to_string(sm_cnt) + \".xyz\";\n            myfile.open(folder.string() + file_name, std::ofstream::out);\n            sm_cnt += 1;\n        }\n        if(myfile.is_open()){\n            for(unsigned int i=0; i<ping_i.beams.size(); i++){\n                myfile << ping_i.beams.at(i)(0) - 669000.0 << \" \" << ping_i.beams.at(i)(1) - 6383000.0 << \" \" << ping_i.beams.at(i)(2) << \"\\n\";\n            }\n        }\n    }\n}\n\n\ndouble compute_info_in_submap(std_data::mbes_ping::PingsT& submap_pings){\n\n    // Beams z centroid\n    double mean_beam = 0;\n    int beam_cnt = 0;\n    for (const std_data::mbes_ping& ping: submap_pings){\n        for(const Eigen::Vector3d& beam_i: ping.beams){\n            mean_beam += beam_i[2];\n            ++beam_cnt;\n        }\n    }\n    mean_beam = mean_beam / beam_cnt;\n\n    // Condition number of z\n    double cond_num = 0;\n    for (const std_data::mbes_ping& ping: submap_pings){\n        for(const Eigen::Vector3d& beam_i: ping.beams){\n            cond_num += std::abs(beam_i[2] - mean_beam);\n        }\n    }\n    return cond_num = cond_num / beam_cnt;\n}\n\nvoid divide_tracks_adaptive(mbes_ping::PingsT& pings)\n{\n    double info_thres = 0.3;\n    // For every line (one line per file)\n    for (auto pos = pings.begin(); pos != pings.end(); ) {\n        auto next = std::find_if(pos, pings.end(), [&](const mbes_ping& ping) {\n            return ping.first_in_file_ && (&ping != &(*pos));\n        });\n\n        mbes_ping::PingsT::iterator first_pos_it = pos;\n        Vector3d last_pos;\n        double mean_width = 0.; double count = 0.;\n        for (auto it = pos; it != next; ++it) {\n            last_pos = it->pos_;\n            mean_width += 1.7*(it->beams.front() - it->beams.back()).norm();\n            count += 1;\n        }\n        mean_width /= count;\n        double length = (last_pos - first_pos_it->pos_).norm();\n\n        int nbr_submaps = int(length/mean_width+2.5);\n        double min_submap_length = length / double(nbr_submaps);\n        double ext_step = min_submap_length/4;\n        double max_submap_length = 3*min_submap_length;\n\n        cout << \"Min submap length: \" << min_submap_length << \", Growing step: \"\n             << ext_step << \", Max submap length: \" << max_submap_length << endl;\n\n        // For every ping in a line\n        mbes_ping::PingsT::iterator latest_pos_it = first_pos_it;\n        int steps = 0;\n        int counter = 0; // TODO: remove!\n        int last_submap_cnt = 0;\n        for (auto it = pos; it != next; ++it) {\n            // If submap too close to end of line\n            if ((last_pos - it->pos_).norm() < min_submap_length) {\n                cout << \"Too close to end, breaking at \" << counter << endl;\n                break;\n            }\n            // If submap reaches max length\n            if((latest_pos_it->pos_ - it->pos_).norm() > max_submap_length){\n                cout << \"Breaking up submap with max length at \" << counter\n                     << \" out of \" << std::distance(pos, next) << endl;\n                it->first_in_file_ = true;\n                latest_pos_it = it;\n                steps = 0;\n                last_submap_cnt = counter;\n            }\n            // If submap bigger than min length or min_length + extension * steps\n            else if (((latest_pos_it->pos_ - it->pos_).norm() >= min_submap_length && steps == 0) ||\n                    (latest_pos_it->pos_ - it->pos_).norm() >= min_submap_length + ext_step*steps) {\n\n                // Compute information quantity on submap\n                mbes_ping::PingsT pings_submap(pos+last_submap_cnt, it);\n                double info_in_submap = compute_info_in_submap(pings_submap);\n                cout << \"Info in submap \" << info_in_submap << endl;\n\n                // If big, break here\n                if(info_in_submap > info_thres){\n                    cout << \"Breaking up submap with enough info at \" << counter\n                         << \" out of \" << std::distance(pos, next) << endl;\n                    it->first_in_file_ = true;\n                    latest_pos_it = it;\n                    steps = 0;\n                    last_submap_cnt = counter;\n                }\n                // If small, keep extending submap\n                else{\n                    steps++;\n                }\n\n            }\n            ++counter;\n        }\n        pos = next;\n    }\n}\n\n\nvoid divide_tracks(mbes_ping::PingsT& pings)\n{\n    for (auto pos = pings.begin(); pos != pings.end(); ) {\n        auto next = std::find_if(pos, pings.end(), [&](const mbes_ping& ping) {\n            return ping.first_in_file_ && (&ping != &(*pos));\n        });\n\n        Vector3d first_pos = pos->pos_;\n        Vector3d last_pos;\n        double mean_width = 0.; double count = 0.;\n        for (auto it = pos; it != next; ++it) {\n            last_pos = it->pos_;\n            mean_width += 1.7*(it->beams.front() - it->beams.back()).norm();\n            count += 1;\n        }\n        mean_width /= count;\n        double length = (last_pos - first_pos).norm();\n\n        int nbr_submaps = int(length/mean_width+0.5);\n        double submap_length = length / double(nbr_submaps);\n\n        cout << \"Mean width: \" << mean_width << \", Length: \" << length << \",  Nbr submaps: \" << nbr_submaps << \", Submap length: \" << submap_length << endl;\n\n        Vector3d recent_pos = first_pos;\n        int last_submap_cnt = 0;\n        int counter = 0; // TODO: remove!\n        for (auto it = pos; it != next; ++it) {\n            if ((last_pos - it->pos_).norm() < submap_length/2.) {\n                cout << \"Too close to end, breaking at \" << counter << endl;\n                break;\n            }\n            if ((it->pos_ - recent_pos).norm() > submap_length) {\n                cout << \"Breaking up submap at \" << counter << \" out of \" << std::distance(pos, next) << endl;\n                it->first_in_file_ = true;\n                recent_pos = it->pos_;\n//                mbes_ping::PingsT pings_submap(pos+last_submap_cnt, it);\n//                double info_in_submap = computeInfoInSubmap(pings_submap);\n//                cout << \"Info in submap \" << info_in_submap << endl;\n                last_submap_cnt = counter;\n            }\n            ++counter;\n        }\n\n        pos = next;\n    }\n}\n\nvoid divide_tracks_equal(mbes_ping::PingsT& pings)\n{\n    Vector2d point1, point2, dir; // first and last point on line\n    vector<bool> line_positive_directions;\n    double first_line_pos = -1000000;\n    double last_line_pos = 1000000;\n\n    cout << \"Really First first in file?: \" << pings[0].first_in_file_ << endl;\n\n    double mean_width = 0.; double count = 0.;\n    for (auto pos = pings.begin(); pos != pings.end(); ) {\n        auto next = std::find_if(pos, pings.end(), [&](const mbes_ping& ping) {\n            return ping.first_in_file_ && (&ping != &(*pos));\n        });\n\n        Vector2d first_pos = pos->pos_.head<2>();\n        Vector2d last_pos;\n        for (auto it = pos; it != next; ++it) {\n            last_pos = it->pos_.head<2>();\n            mean_width += 1.7*(it->beams.front() - it->beams.back()).norm();\n            count += 1;\n        }\n        if (pos == pings.begin()) {\n            point1 = first_pos;\n            point2 = last_pos;\n            dir = point2-point1;\n            dir.normalize();\n        }\n\n        bool positive_direction = dir.dot(last_pos - first_pos) > 0;\n        line_positive_directions.push_back(positive_direction);\n\n        double line_pos1 = dir.dot(first_pos - point1);\n        double line_pos2 = dir.dot(last_pos - point1);\n        cout << \"Number pings: \" << std::distance(pos, next) << endl;\n        cout << \"First == last? \" << (pos == next) << endl;\n        cout << \"First beams: \" << pos->beams.size() << \" Next beams: \" << next->beams.size() << endl;\n        cout << \"First firs in file?: \" << pos->first_in_file_ << \", Next first in file?: \" << next->first_in_file_ << endl;\n        cout << \"First time: \" << pos->time_stamp_ << \", Next time: \" << next->time_stamp_ << endl;\n        cout << \"First pos: \" << first_pos.transpose() << endl;\n        cout << \"Last pos: \" << last_pos.transpose() << \", Point 1: \" << point1.transpose() << \"Dir: \" << dir.transpose() << endl;\n        cout << \"Line pos 1: \" << line_pos1 << \", Line pos 2: \" << line_pos2 << endl;\n        if (!positive_direction) {\n            std::swap(line_pos1, line_pos2);\n        }\n\n        first_line_pos = std::max(first_line_pos, line_pos1);\n        last_line_pos = std::min(last_line_pos, line_pos2);\n\n        pos = next;\n    }\n\n    mean_width /= count;\n    //double length = (point2 - point1).norm();\n    double line_pos_length = last_line_pos - first_line_pos;\n    int nbr_submaps = int(line_pos_length/mean_width+0.5);\n    double submap_length = line_pos_length / double(nbr_submaps);\n\n    cout << \"First line pos: \" << first_line_pos << \", last line pos: \" << last_line_pos << endl;\n    cout << \"Mean width: \" << mean_width << \", Length: \" << line_pos_length << \",  Nbr submaps: \" << nbr_submaps << \", Submap length: \" << submap_length << endl;\n    cout << \"------------\" << endl;\n    int track_counter = 0;\n    int min_since_last = 5;\n    for (auto pos = pings.begin(); pos != pings.end(); ) {\n        auto next = std::find_if(pos, pings.end(), [&](const mbes_ping& ping) {\n            return ping.first_in_file_ && (&ping != &(*pos));\n        });\n\n        bool positive_direction = line_positive_directions[track_counter];\n        //Vector3d recent_pos = pos->pos_;\n        //int counter;\n        double recent_line_pos = positive_direction?\n                    dir.dot(pos->pos_.head<2>() - point1) - first_line_pos:\n                    last_line_pos - dir.dot(pos->pos_.head<2>() - point1);\n        int time_since_last = 0;\n        for (auto it = pos; it != next; ++it) {\n            if (std::distance(it, next) < min_since_last) {\n                break;\n            }\n            double line_pos = positive_direction?\n                        dir.dot(it->pos_.head<2>() - point1) - first_line_pos :\n                        last_line_pos - dir.dot(it->pos_.head<2>() - point1);\n            if (line_pos > 0 && line_pos < line_pos_length) {\n                if ((recent_line_pos < 0 || recent_line_pos > line_pos_length) &&\n                        time_since_last > min_since_last) {\n                    it->first_in_file_ = true;\n                    time_since_last = 0;\n                }\n                else if ((int(recent_line_pos/submap_length) < int(line_pos/submap_length)) &&\n                        time_since_last > min_since_last) {\n                    it->first_in_file_ = true;\n                    time_since_last = 0;\n                }\n            }\n            else if ((recent_line_pos > 0 && recent_line_pos < line_pos_length) &&\n                    time_since_last > min_since_last) {\n                it->first_in_file_ = true;\n                time_since_last = 0;\n            }\n            //++counter;\n            recent_line_pos = line_pos;\n            ++time_since_last;\n        }\n\n        pos = next;\n        ++track_counter;\n    }\n}\n\ntuple<ObsT, TransT, AngsT, MatchesT, BBsT, ObsT> create_submaps(const mbes_ping::PingsT& pings)\n{\n    ObsT submaps;\n    TransT trans;\n    AngsT angs;\n    MatchesT matches;\n    BBsT bounds;\n    ObsT tracks;\n    for (auto pos = pings.begin(); pos != pings.end(); ) {\n        auto next = std::find_if(pos, pings.end(), [&](const mbes_ping& ping) {\n            return ping.first_in_file_ && (&ping != &(*pos));\n        });\n        mbes_ping::PingsT track_pings;\n        track_pings.insert(track_pings.end(), pos, next);\n        cout << \"found 1 pos!\" << endl;\n\n        if (pos == next) {\n            break;\n        }\n\n        MatrixXd points(track_pings.size()*track_pings[0].beams.size(), 3);\n        MatrixXd track(track_pings.size(), 3);\n\n        // get the direction of the submap as the mean direction\n        Vector3d dir = track_pings.back().pos_ - track_pings.front().pos_;\n        Vector3d ang; ang << 0., 0., std::atan2(dir(1), dir(0));\n        Eigen::Matrix3d RM = data_transforms::euler_to_matrix(ang(0), ang(1), ang(2));\n\n        int counter = 0;\n        int ping_counter = 0;\n        for (const mbes_ping& ping : track_pings) {\n            //cout << \"Counter : \" << counter << \" and size: \" << points.rows() << \" and new points: \" << ping.beams.size() << endl;\n            if (counter + ping.beams.size() > points.rows()) {\n                points.conservativeResize(counter + ping.beams.size(), 3);\n            }\n            for (const Vector3d& p : ping.beams) {\n                points.row(counter) = p;\n                ++counter;\n            }\n            track.row(ping_counter) = ping.pos_;\n            ++ping_counter;\n        }\n        if (counter == 0) {\n            pos = next;\n            continue;\n        }\n        points.conservativeResize(counter, 3);\n        trans.push_back(points.colwise().mean().transpose());\n        angs.push_back(ang);\n        points.array().rowwise() -= trans.back().transpose().array();\n        points = points*RM;\n        track.array().rowwise() -= trans.back().transpose().array();\n        track = track*RM;\n        Matrix2d bb;\n        bb(0, 0) = points.col(0).minCoeff();\n        bb(0, 1) = points.col(1).minCoeff();\n        bb(1, 0) = points.col(0).maxCoeff();\n        bb(1, 1) = points.col(1).maxCoeff();\n        submaps.push_back(points);\n        bounds.push_back(bb);\n        tracks.push_back(track);\n\n        pos = next;\n    }\n\n    // homogenize angles\n    /*\n    for (int i = 0; i < submaps.size(); ++i) {\n        if (fabs(angs[i](2)) > M_PI/2.) {\n            submaps[i].leftCols(2).array() *= -1.; // rotate 180 degrees\n            tracks[i].leftCols(2).array() *= -1.; // rotate 180 degrees\n            Matrix2d bb = bounds[i];\n            bounds[i].row(0) = -bb.row(1);\n            bounds[i].row(1) = -bb.row(0);\n            if (angs[i](2) < -M_PI/2.) {\n                angs[i](2) += M_PI;\n            }\n            else {\n                angs[i](2) -= M_PI;\n            }\n        }\n    }\n    */\n\n    return make_tuple(submaps, trans, angs, matches, bounds, tracks);\n}\n\n\n} // namespace navi_data\n\nnamespace std_data {\n\n// Extract space-separated numbers: Nav files\n// 0: Year\n// 1: Time (day, hour)\n// 2: Second\n// 3: Ping num\n// 4: Beam num\n// 5: X\n// 6: Y\n// 7: Z\n// 8: Tide\n// 9: Heading\n// 10: Heave\n// 11: Pitch\n// 12: Roll\ntemplate <>\nmbes_ping::PingsT parse_file(const boost::filesystem::path& file)\n{\n    mbes_ping::PingsT pings;\n\n    string line;\n    std::ifstream infile(file.string());\n\n    mbes_ping ping;\n    string time;\n    int beam_id;\n    double tide, x, y, z;\n    string year_string, date_string, second_string;\n    const std::locale loc = std::locale(std::locale::classic(), new boost::posix_time::time_input_facet(\"%Y %m%d%H%M %S%f\"));\n    const boost::posix_time::ptime epoch = boost::posix_time::time_from_string(\"1970-01-01 00:00:00.000\");\n\n    std::getline(infile, line); // throw away first line as it contains description\n    int counter = 0;\n    while (std::getline(infile, line))  // this does the checking!\n    {\n        istringstream iss(line);\n\n        iss >> year_string >> date_string >> second_string >> ping.id_ >> beam_id >> x >> y >> z >> tide >> ping.heading_ >> ping.heave_ >> ping.pitch_ >> ping.roll_;\n\n        /*\n        if (beam_id != 255 && counter % 10 != 0) {\n            ++counter;\n            continue;\n        }\n        */\n\n        ping.beams.push_back(Vector3d(x, y, -z));\n\n        if (beam_id == 255) {\n            ping.first_in_file_ = pings.empty();\n            std::istringstream is(year_string + \" \" + date_string + \" \" + second_string);\n            is.imbue(loc);\n            boost::posix_time::ptime t;\n            is >> t;\n            boost::posix_time::time_duration const diff = t - epoch;\n            ping.time_stamp_ = diff.total_milliseconds();\n            stringstream time_ss;\n            time_ss << t;\n            ping.time_string_ = time_ss.str();\n            //cout << year_string << \" \" << date_string << \" \" << second_string << endl;\n            //cout << t << endl;\n\n            pings.push_back(ping);\n            ping.beams.resize(0);\n        }\n\n        ++counter;\n    }\n\n    return pings;\n}\n\n// Extract space-separated numbers: Nav files\n// 0: Day\n// 1: Time\n// 2: Easting\n// 3: Northing\n// 4: Depth (given in positive values!)\n// 5: Zeros\ntemplate <>\nnav_entry::EntriesT parse_file(const boost::filesystem::path& file)\n{\n    nav_entry::EntriesT entries;\n\n    nav_entry entry;\n    double x, y, z;\n    string date_string, time_string;\n    const std::locale loc = std::locale(std::locale::classic(), new boost::posix_time::time_input_facet(\"%Y.%m.%d %H:%M:%S%f\"));\n    const boost::posix_time::ptime epoch = boost::posix_time::time_from_string(\"1970-01-01 00:00:00.000\");\n\n    string line;\n    std::ifstream infile(file.string());\n    while (std::getline(infile, line))  // this does the checking!\n    {\n        istringstream iss(line);\n\n        //iss >> entry.year_ >> entry.time_stamp_ >> x >> y >> z;\n        iss >> date_string >> time_string >> x >> y >> z;\n        entry.pos_ = Vector3d(x, y, -z);\n\n        std::istringstream is(date_string + \" \" + time_string);\n        is.imbue(loc);\n        boost::posix_time::ptime t;\n        is >> t;\n        boost::posix_time::time_duration const diff = t - epoch;\n        entry.time_stamp_ = diff.total_milliseconds();\n        stringstream time_ss;\n        time_ss << t;\n        entry.time_string_ = time_ss.str();\n\n        //cout << date_string << \" \" << time_string << endl;\n        //cout << t << endl;\n        //cout << ms << endl;\n        entry.first_in_file_ = entries.empty();\n\n        entries.push_back(entry);\n    }\n\n    return entries;\n}\n} // namespace std_data\n", "meta": {"hexsha": "4c88e67e37d45c046ff8181ec11305fc674301e4", "size": 21450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/data_tools/src/navi_data.cpp", "max_stars_repo_name": "luxiya01/auvlib", "max_stars_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T16:17:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:25:08.000Z", "max_issues_repo_path": "src/data_tools/src/navi_data.cpp", "max_issues_repo_name": "luxiya01/auvlib", "max_issues_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-01-11T16:17:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:41:48.000Z", "max_forks_repo_path": "src/data_tools/src/navi_data.cpp", "max_forks_repo_name": "luxiya01/auvlib", "max_forks_repo_head_hexsha": "26b7b04277cf320084ed25df735886844ca6a629", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T16:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:18:58.000Z", "avg_line_length": 37.9646017699, "max_line_length": 758, "alphanum_fraction": 0.5648484848, "num_tokens": 5495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.02033235204409113, "lm_q1q2_score": 0.0059820823906603605}}
{"text": "#ifndef PRIMITIVES\n#define PRIMITIVES\n\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <functional>\n#include <string>\n#include <iomanip>      // std::put_time\n#include <boost/unordered_set.hpp> // hash_combine\n#include <chrono>\n\n#include \"../include/rapidjson/document.h\"\n\ntypedef long long int i64;\n\n/**\n * @brief The parameters_t struct\n * Parameters of the conflict optimizer\n */\nstruct Parameters\n{\n    std::string instance_name = \"\";\n    std::string solution_name = \"\";\n    std::string info_name = \"\";\n    std::string algorithm = \"greedy\";\n    double power = 1.2;\n    double noise_mean = 1;\n    double noise_var = 0.15;\n    long max_queue = -1;\n    long max_run_time = 3600;\n    bool dfs = true;\n    bool easy = true;\n    bool loop = false;\n    int loop_time = 3600;\n    std::vector<double> power_loop = {1.1, 1.2, 1.3, 1.5, 2.0};\n    long loop_index = 0;\n\n    void read(const std::string &filename)\n    {\n        std::ifstream in(filename, std::ifstream::in | std::ifstream::binary);\n        if (!in.is_open())\n        {\n            std::cerr << \"Error reading \" << filename << std::endl;\n            exit(EXIT_FAILURE);\n        }\n\n        rapidjson::IStreamWrapper isw {in};\n        rapidjson::Document doc {};\n        doc.ParseStream(isw);\n        if (doc.HasParseError())\n        {\n            std::cerr << \"Error  : \" << doc.GetParseError()  << std::endl;\n            std::cerr << \"Offset : \" << doc.GetErrorOffset() << std::endl;\n            exit(EXIT_FAILURE);\n        }\n\n        if (doc.HasMember(\"instance\"))\n            instance_name = doc[\"instance\"].GetString();\n        else\n        {\n            std::clog << \"Missing mandatory argument from parameters file: instance\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n        if (doc.HasMember(\"solution\"))\n            solution_name = doc[\"solution\"].GetString();\n        if (doc.HasMember(\"info\"))\n            info_name = doc[\"info\"].GetString();\n        if (doc.HasMember(\"algorithm\"))\n            algorithm = doc[\"algorithm\"].GetString();\n        if (doc.HasMember(\"power\"))\n            power = doc[\"power\"].GetDouble();\n        if (doc.HasMember(\"noise_mean\"))\n            noise_mean = doc[\"noise_mean\"].GetDouble();\n        if (doc.HasMember(\"noise_var\"))\n            noise_var = doc[\"noise_var\"].GetDouble();\n        if (doc.HasMember(\"max_queue\"))\n            max_queue = doc[\"max_queue\"].GetInt();\n        if (doc.HasMember(\"max_run_time\"))\n            max_run_time =  doc[\"max_run_time\"].GetInt();\n        if (doc.HasMember(\"dfs\"))\n            dfs = doc[\"dfs\"].GetBool();\n        if (doc.HasMember(\"easy\"))\n            easy = doc[\"easy\"].GetBool();\n        if (doc.HasMember(\"loop\"))\n        {\n            loop = doc[\"loop\"].GetBool();\n            if (loop)\n                power = 1.1;\n        }\n        if (doc.HasMember(\"loop_time\"))\n            loop_time = doc[\"loop_time\"].GetInt();\n\n        std::clog << \"{ instance: \" << instance_name << \", \"\n                  << \"solution: \" << solution_name << \", \"\n                  << \"info: \" << info_name << \", \"\n                  << \"power: \" << power << \", \"\n                  << \"noise_mean: \" << noise_mean << \", \"\n                  << \"noise_var: \" << noise_var << \", \"\n                  << \"max_queue: \" << max_queue << \", \"\n                  << \"max_run_time: \" << max_run_time << \", \"\n                  << \"dfs: \" << dfs << \", \"\n                  << \"easy: \" << easy << \", \"\n                  << \"loop: \" << loop << \", \"\n                  << \"loop_time: \" << loop_time << \" }\" << std::endl;\n    }\n};\n\nclass Point {\npublic:\n    i64 x,y;\n\n    Point() {\n    }\n\n    Point(i64 _x, i64 _y) : x(_x), y(_y) {\n    }\n\n    i64 l1(const Point &p = Point(0,0)) const {\n        return abs(x-p.x) + abs(y-p.y);\n    }\n\n    i64 linf(const Point &p = Point(0,0)) const {\n        return std::max(abs(x-p.x), abs(y-p.y));\n    }\n\n    i64 l2sq(const Point &p = Point(0,0)) const {\n        return (x-p.x)*(x-p.x) + (y-p.y)*(x-p.x);\n    }\n\n    friend bool operator==(const Point &p, const Point &q) {\n        return p.x == q.x && p.y == q.y;\n    }\n\n    friend bool operator!=(const Point &p, const Point &q) {\n        return !(p == q);\n    }\n\n    friend bool operator<(const Point &p, const Point &q) {\n        return p.x < q.x || (p.x == q.x && p.y < q.y);\n    }\n\n    //  auto operator<=>(const Point& p) const = default;\n\n    Point operator-(const Point &p) const {\n        return Point(x-p.x, y-p.y);\n    }\n\n    Point operator+(const Point &p) const {\n        return Point(x+p.x, y+p.y);\n    }\n\n    // Dot product\n    i64 operator*(const Point &p) const {\n        return x*p.x + y*p.y;\n    }\n\n    std::string toString() const {\n        std::string s = \"(\" + std::to_string(x) + \",\" + std::to_string(y) + \")\";\n        return s;\n    }\n\n    bool inside(const Point &p, const Point &q) const {\n        i64 minx = std::min(p.x, q.x);\n        i64 miny = std::min(p.y, q.y);\n        i64 maxx = std::max(p.x, q.x);\n        i64 maxy = std::max(p.y, q.y);\n        return x >= minx && x <= maxx && y >= miny && y <= maxy;\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, const Point& p) {\n        os << p.toString();\n        return os;\n    }\n};\n\n\nclass Segment {\n    Point p,q;\npublic:\n    Segment() {\n    }\n\n    Segment(const Point  &_p, const Point  &_q) {\n        if (_p < _q) {\n            p = _p;\n            q = _q;\n        }\n        else {\n            p = _q;\n            q = _p;\n        }\n    }\n\n    const Point &get_p() const {\n        return p;\n    }\n\n    const Point &get_q() const{\n        return q;\n    }\n\n    i64 l1() const {\n        return p.l1(q);\n    }\n\n    i64 linf() const {\n        return p.linf(q);\n    }\n\n    i64 l2sq() const {\n        return p.l2sq(q);\n    }\n\n    double slope() const {\n        Point d = q - p;\n        return (double) d.y / d.x;\n    }\n\n    friend bool operator==(const Segment &s, const Segment &t) {\n        return s.p == t.p && s.q == t.q;\n    }\n\n    int orientation(const Point &r) const {\n        i64 d1 = (q.y - p.y);\n        i64 d2 = (r.x - q.x);\n        i64 d3 = (q.x - p.x);\n        i64 d4 = (r.y - q.y);\n        i64 val = d1*d2 - d3*d4;\n\n        return (val > 0) - (val < 0);\n    }\n\n    bool cross(const Segment &s) const {\n        int o1 = orientation(s.p);\n        int o2 = orientation(s.q);\n        int o3 = s.orientation(p);\n        int o4 = s.orientation(q);\n\n        // No 3 colinear points\n        if (o1 != 0 && o2 != 0 && o3 != 0 && o4 != 0) {\n            return o1 != o2 && o3 != o4;\n        }\n\n        // Colinear but 4 distinct points\n        if (s.p != p && s.q != q && s.p != q && s.q != p)\n            return s.p.inside(p, q) || s.q.inside(p, q) || p.inside(s.p, s.q) || q.inside(s.p, s.q);\n\n        // Same segment twice, return false for convinience\n        if (*this == s)\n            return false;\n\n        // 3 points among 4 vertices, not all colinear\n        if (o1 != 0 || o2 != 0 || o3 != 0 || o4 != 0)\n            return false;\n\n        // 3 points among 4 vertices, all colinear\n        if (s.p == p)\n            return q.inside(s.p, s.q) || s.q.inside(p, q);\n        if (s.q == q)\n            return p.inside(s.p, s.q) || s.p.inside(p, q);\n        if (s.p == q)\n            return p.inside(s.p, s.q) || s.q.inside(p, q);\n        //      if (s.q == p)\n        return q.inside(s.p, s.q) || s.p.inside(p, q);\n    }\n\n    std::string toString() const {\n        std::string s = p.toString() + \"-\" + q.toString();\n        return s;\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, const Segment& s) {\n        os << s.toString();\n        return os;\n    }\n};\n\nnamespace std {\n\ntemplate <> struct hash<Point> {\n    size_t operator()(const Point& p) const {\n        size_t seed = 0;\n        boost::hash_combine(seed, p.x);\n        boost::hash_combine(seed, p.y);\n        return seed;\n    }\n};\n\ntemplate <> struct hash<Segment> {\n    size_t operator()(const Segment& s) const {\n        size_t seed = 0;\n        boost::hash_combine(seed, s.get_p().x);\n        boost::hash_combine(seed, s.get_p().y);\n        boost::hash_combine(seed, s.get_q().x);\n        boost::hash_combine(seed, s.get_q().y);\n        return seed;\n    }\n};\n\n}\n\n\n#endif // PRIMITIVES\n", "meta": {"hexsha": "f045902e1c9f1c1ee972e1457103fa4e6878f452", "size": 8167, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/primitives.hpp", "max_stars_repo_name": "gfonsecabr/shadoks-CGSHOP2022", "max_stars_repo_head_hexsha": "ffa0b7a8d41937f329bc8bfe7907d4bd7d4bcb65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/primitives.hpp", "max_issues_repo_name": "gfonsecabr/shadoks-CGSHOP2022", "max_issues_repo_head_hexsha": "ffa0b7a8d41937f329bc8bfe7907d4bd7d4bcb65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/primitives.hpp", "max_forks_repo_name": "gfonsecabr/shadoks-CGSHOP2022", "max_forks_repo_head_hexsha": "ffa0b7a8d41937f329bc8bfe7907d4bd7d4bcb65", "max_forks_repo_licenses": ["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.7770491803, "max_line_length": 100, "alphanum_fraction": 0.486592384, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070895174993, "lm_q2_score": 0.027169232027997987, "lm_q1q2_score": 0.005977423662905462}}
{"text": "// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers\n// Copyright (c) 2016-2018  zawy12\n// Copyright (c) 2016-2018, The Karbowanec developers\n// Copyright (c) 2018-2022, The Deocoin Group.\n//\n// This file is part of Deocoin.\n//\n// Deocoin 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// Deocoin 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 Deocoin.  If not, see <http://www.gnu.org/licenses/>.\n\n#include <algorithm>\n#include <cctype>\n#include <cmath>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <Common/Base58.h>\n#include <Common/int-util.h>\n#include <Common/Math.h>\n#include <Common/StringTools.h>\n#include <CryptoNoteCore/Account.h>\n#include <CryptoNoteCore/CryptoNoteBasicImpl.h>\n#include <CryptoNoteCore/CryptoNoteFormatUtils.h>\n#include <CryptoNoteCore/CryptoNoteTools.h>\n#include <CryptoNoteCore/Currency.h>\n#include <CryptoNoteCore/TransactionExtra.h>\n#include <CryptoNoteCore/UpgradeDetector.h>\n#include <Global/Constants.h>\n#include <Global/CryptoNoteConfig.h>\n\n#undef ERROR\n\nusing namespace Logging;\nusing namespace Common;\nusing namespace Deocoin;\n\nnamespace CryptoNote {\n\nbool Currency::init()\n{\n    if (!generateGenesisBlock()) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to generate genesis block\";\n        return false;\n    }\n\n    if (!get_block_hash(m_genesisBlock, m_genesisBlockHash)) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to get genesis block hash\";\n        return false;\n    }\n\n    if (isTestnet()) {\n        m_upgradeHeightV2 = 10;\n        m_upgradeHeightV3 = 60;\n        m_upgradeHeightV4 = 70;\n        m_upgradeHeightV5 = 80;\n        m_upgradeHeightV6 = 100;\n        m_governancePercent = 10;\n        m_governanceHeightStart = 1;\n        m_governanceHeightEnd = 100;\n        m_blocksFileName = \"testnet_\" + m_blocksFileName;\n        m_blocksCacheFileName = \"testnet_\" + m_blocksCacheFileName;\n        m_blockIndexesFileName = \"testnet_\" + m_blockIndexesFileName;\n        m_txPoolFileName = \"testnet_\" + m_txPoolFileName;\n        m_blockchainIndicesFileName = \"testnet_\" + m_blockchainIndicesFileName;\n    }\n\n    return true;\n}\n\nbool Currency::generateGenesisBlock()\n{\n    m_genesisBlock = boost::value_initialized<Block>();\n\n    // Hard code coinbase tx in genesis block, because \"tru\" generating tx use random,\n    // but genesis should be always the same\n    std::string genesisCoinbaseTxHex = GENESIS_COINBASE_TX_HEX;\n    BinaryArray minerTxBlob;\n\n    bool r = fromHex(genesisCoinbaseTxHex, minerTxBlob)\n             && fromBinaryArray(m_genesisBlock.baseTransaction, minerTxBlob);\n\n    if (!r) {\n        logger(ERROR, BRIGHT_RED) << \"failed to parse coinbase tx from hard coded blob\";\n        return false;\n    }\n\n    m_genesisBlock.majorVersion = BLOCK_MAJOR_VERSION_1;\n    m_genesisBlock.minorVersion = BLOCK_MINOR_VERSION_0;\n    m_genesisBlock.timestamp = 0;\n    m_genesisBlock.nonce = 70;\n    if (m_testnet) {\n        ++m_genesisBlock.nonce;\n    }\n\n    //miner::find_nonce_for_given_block(bl, 1, 0);\n\n    return true;\n}\n\nsize_t Currency::blockGrantedFullRewardZoneByBlockVersion(uint8_t blockMajorVersion) const\n{\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_4) {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2;\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_3) {\n        return m_blockGrantedFullRewardZone;\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_2) {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2;\n    } else {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V1;\n    }\n}\n\nuint32_t Currency::upgradeHeight(uint8_t majorVersion) const\n{\n    if (majorVersion == BLOCK_MAJOR_VERSION_6) {\n        return m_upgradeHeightV6;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_5) {\n        return m_upgradeHeightV5;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_4) {\n        return m_upgradeHeightV4;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_2) {\n        return m_upgradeHeightV2;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_3) {\n        return m_upgradeHeightV3;\n    } else {\n        return static_cast<uint32_t>(-1);\n    }\n}\n\nbool Currency::getBlockReward(\n    uint8_t blockMajorVersion,\n    size_t medianSize,\n    size_t currentBlockSize,\n    uint64_t alreadyGeneratedCoins,\n    uint64_t fee,\n    uint64_t &reward,\n    int64_t &emissionChange,\n    uint32_t height,\n    uint64_t blockTarget) const\n{\n    //assert(alreadyGeneratedCoins <= m_moneySupply);\n    assert(m_emissionSpeedFactor > 0 && m_emissionSpeedFactor <= 8 * sizeof(uint64_t));\n\n    // Consistency\n    double consistency = 1.0;\n    double exponent = 0.25; \n    if (height >= CryptoNote::parameters::UPGRADE_HEIGHT_V6 && difficultyTarget() != 0) {\n        // blockTarget is (Timestamp of New Block - Timestamp of Previous Block)\n        consistency = (double) blockTarget / (double) difficultyTarget();\n\n        // consistency range is 0..2\n        if (consistency < 1.0) {\n            consistency = std::max<double>(consistency, 0.0);\n        }\n        else if (consistency > 1.0) {\n            consistency = pow(consistency, exponent);\n            consistency = std::min<double>(consistency, 2.0);\n        }\n        else {\n            consistency = 1.0;\n        }\n    }  \n\n    // Tail emission\n\n    uint64_t baseReward = ((m_moneySupply - alreadyGeneratedCoins) >> m_emissionSpeedFactor) * consistency;\n    if (alreadyGeneratedCoins + CryptoNote::parameters::TAIL_EMISSION_REWARD >= m_moneySupply\n        || baseReward < CryptoNote::parameters::TAIL_EMISSION_REWARD) {\n        baseReward = CryptoNote::parameters::TAIL_EMISSION_REWARD;\n    }\n\n    size_t blockGrantedFullRewardZone = blockGrantedFullRewardZoneByBlockVersion(blockMajorVersion);\n    medianSize = std::max(medianSize, blockGrantedFullRewardZone);\n    if (currentBlockSize > medianSize * UINT64_C(2)) {\n        logger(TRACE)\n            << \"Block cumulative size is too big: \"\n            << currentBlockSize\n            << \", expected less than \"\n            << medianSize * UINT64_C(2);\n        return false;\n    }\n\n    uint64_t penalizedBaseReward = getPenalizedAmount(baseReward, medianSize, currentBlockSize);\n    uint64_t penalizedFee = fee;\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2 || cryptonoteCoinVersion() == 1) {\n        penalizedFee = getPenalizedAmount(fee, medianSize, currentBlockSize);\n    }\n\n    emissionChange = penalizedBaseReward - (fee - penalizedFee);\n    reward = penalizedBaseReward + penalizedFee;\n\n    return true;\n}\n\nsize_t Currency::maxBlockCumulativeSize(uint64_t height) const\n{\n    assert(height <= std::numeric_limits<uint64_t>::max() / m_maxBlockSizeGrowthSpeedNumerator);\n\n    size_t maxSize =\n        static_cast<size_t>(m_maxBlockSizeInitial\n        + (height * m_maxBlockSizeGrowthSpeedNumerator) / m_maxBlockSizeGrowthSpeedDenominator);\n\n    assert(maxSize >= m_maxBlockSizeInitial);\n\n    return maxSize;\n}\n\nbool Currency::isGovernanceEnabled(uint32_t height) const\n{\n    if (height >= m_governanceHeightStart && height <= m_governanceHeightEnd) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nuint64_t Currency::getGovernanceReward(uint64_t base_reward) const\n{\n    // minimum is 1% to avoid a zero amount and maximum is 50%\n    uint16_t percent = (m_governancePercent < 1) ? 1 : (m_governancePercent > 50) ? 50 : m_governancePercent;\n    return (uint64_t)(base_reward * (percent * 0.01));\n}\n\nbool Currency::validate_government_fee(const Transaction &baseTx) const\n{\n    AccountKeys governanceKeys;\n    getGovernanceAddressAndKey(governanceKeys);\n\n    Crypto::PublicKey txPublicKey = getTransactionPublicKeyFromExtra(baseTx.extra);\n\n    Crypto::KeyDerivation derivation;\n    if (!Crypto::generate_key_derivation( txPublicKey,\n                                  governanceKeys.viewSecretKey,\n                                  derivation)) {\n        return false;\n    }\n\n    uint64_t minerReward = 0;\n    uint64_t governmentFee = 0;\n    for (size_t idx = 0; idx < baseTx.outputs.size(); ++idx) {\n        minerReward += baseTx.outputs[idx].amount;\n        if (baseTx.outputs[idx].target.type() != typeid(CryptoNote::KeyOutput))\n            continue;\n        Crypto::PublicKey outEphemeralKey;\n        Crypto::derive_public_key(derivation, idx,\n            governanceKeys.address.spendPublicKey, outEphemeralKey);\n        if (outEphemeralKey == boost::get<KeyOutput>(baseTx.outputs[idx].target).key)\n            governmentFee += baseTx.outputs[idx].amount;\n    }\n\n    return (governmentFee == getGovernanceReward(minerReward));\n}\n\nbool Currency::getGovernanceAddressAndKey(AccountKeys& governanceKeys) const\n{\n    std::string address       = GOVERNANCE_WALLET_ADDRESS;\n    std::string viewSecretkey = GOVERNANCE_VIEW_SECRET_KEY;\n\n    AccountPublicAddress governanceAddress = boost::value_initialized<AccountPublicAddress>();\n    if (!parseAccountAddressString(address, governanceAddress)) {\n        logger(Logging::ERROR)\n            << \"Failed to parse governance wallet address (\"\n            << address\n            << \"), \"\n            << \"Check /lib/Global/CryptoNoteConfig.h\";\n        return false;\n    }\n\n    Crypto::SecretKey governanceViewSecretKey;\n    if (!Common::podFromHex(viewSecretkey, governanceViewSecretKey)) {\n        logger(Logging::ERROR)\n            << \"Failed to parse governance view secret key\"\n            << \"Check /lib/Global/CryptoNoteConfig.h\";\n        return false;\n    }\n\n    governanceKeys.address = governanceAddress;\n    governanceKeys.viewSecretKey = governanceViewSecretKey;\n\n    return true;\n}\n\nbool Currency::constructMinerTx(\n    uint8_t blockMajorVersion,\n    uint32_t height,\n    size_t medianSize,\n    uint64_t alreadyGeneratedCoins,\n    size_t currentBlockSize,\n    uint64_t fee,\n    const AccountPublicAddress &minerAddress,\n    Transaction &tx,\n    const BinaryArray &extraNonce /* = BinaryArray()*/,\n    size_t maxOuts /* = 1*/,\n    uint64_t blockTarget /* = 0xffffffffffffffff*/) const\n{\n    if (blockTarget == 0xffffffffffffffff)\n        blockTarget = difficultyTarget();\n    tx.inputs.clear();\n    tx.outputs.clear();\n    tx.extra.clear();\n\n    KeyPair txkey = generateKeyPair();\n    addTransactionPublicKeyToExtra(tx.extra, txkey.publicKey);\n    if (!extraNonce.empty()) {\n        if (!addExtraNonceToTransactionExtra(tx.extra, extraNonce)) {\n            return false;\n        }\n    }\n\n    BaseInput in;\n    in.blockIndex = height;\n\n    uint64_t governanceReward = 0;\n    uint64_t totalRewardWGR = 0; //totalRewardWithoutGovernanceReward\n\n    uint64_t blockReward;\n    int64_t emissionChange;\n\n    if (!getBlockReward(\n            blockMajorVersion,\n            medianSize,\n            currentBlockSize,\n            alreadyGeneratedCoins,\n            fee,\n            blockReward,\n            emissionChange,\n            height,\n            blockTarget)\n        ) {\n        logger(INFO) << \"Block is too big\";\n        return false;\n    }\n\n    totalRewardWGR = blockReward;\n\n    // If Governance Fee blockReward is decreased by GOVERNANCE_PERCENT_FEE\n    bool enableGovernance = isGovernanceEnabled(height);\n\n    if (enableGovernance) {\n        governanceReward = getGovernanceReward(blockReward);\n\n        if (alreadyGeneratedCoins != 0) {\n            blockReward -= governanceReward;\n            totalRewardWGR  = blockReward + governanceReward;\n        }\n    }\n\n    std::vector<uint64_t> outAmounts;\n    decompose_amount_into_digits(\n        blockReward,\n        UINT64_C(0),\n        [&outAmounts](uint64_t a_chunk) { outAmounts.push_back(a_chunk); },\n        [&outAmounts](uint64_t a_dust) { outAmounts.push_back(a_dust); }\n    );\n\n    if (maxOuts < 1) {\n        logger(ERROR, BRIGHT_RED) << \"max_out must be non-zero\";\n        return false;\n    }\n    while (maxOuts < outAmounts.size()) {\n        outAmounts[outAmounts.size() - 2] += outAmounts.back();\n        outAmounts.resize(outAmounts.size() - 1);\n    }\n\n    uint64_t summaryAmounts = 0;\n    for (size_t no = 0; no < outAmounts.size(); no++) {\n        Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();\n        Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();\n\n        bool r = Crypto::generate_key_derivation(\n            minerAddress.viewPublicKey,\n            txkey.secretKey,\n            derivation\n        );\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to generate_key_derivation(\"\n                << minerAddress.viewPublicKey\n                << \", \"\n                << txkey.secretKey\n                << \")\";\n            return false;\n        }\n\n        r = Crypto::derive_public_key(derivation,no,minerAddress.spendPublicKey,outEphemeralPubKey);\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to derive_public_key(\"\n                << derivation << \", \"\n                << no << \", \"\n                << minerAddress.spendPublicKey\n                << \")\";\n            return false;\n        }\n\n        KeyOutput tk;\n        tk.key = outEphemeralPubKey;\n\n        TransactionOutput out;\n        summaryAmounts += out.amount = outAmounts[no];\n        out.target = tk;\n        tx.outputs.push_back(out);\n    }\n\n    if (enableGovernance) {\n        AccountKeys governanceKeys;\n        getGovernanceAddressAndKey(governanceKeys);\n\n        Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();\n        Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();\n\n        bool r = Crypto::generate_key_derivation(governanceKeys.address.viewPublicKey, txkey.secretKey, derivation);\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to generate_key_derivation(\"\n                << governanceKeys.address.viewPublicKey << \", \" << txkey.secretKey << \")\";\n            return false;\n        }\n        size_t pos = tx.outputs.size();\n        r = Crypto::derive_public_key(derivation, pos++, governanceKeys.address.spendPublicKey, outEphemeralPubKey);\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to derive_public_key(\"\n                << derivation << \", \" << 0 << \", \"\n                << governanceKeys.address.spendPublicKey << \")\";\n            return false;\n        }\n        KeyOutput tk;\n        tk.key = outEphemeralPubKey;\n\n        TransactionOutput out;\n        summaryAmounts += out.amount = governanceReward;\n        out.target = tk;\n        tx.outputs.push_back(out);\n    }\n\n    if (summaryAmounts != totalRewardWGR) {\n        logger(ERROR, BRIGHT_RED)\n            << \"Failed to construct miner tx, summaryAmounts = \"\n            << summaryAmounts\n            << \" not equal blockReward = \"\n            << blockReward;\n        return false;\n    }\n\n    tx.version = CURRENT_TRANSACTION_VERSION;\n    //lock\n    tx.unlockTime = height + m_minedMoneyUnlockWindow;\n    tx.inputs.push_back(in);\n\n    return true;\n}\n\nbool Currency::isFusionTransaction(\n    const std::vector<uint64_t> &inputsAmounts,\n    const std::vector<uint64_t> &outputsAmounts,\n    size_t size,\n    uint32_t height) const\n{\n    // TODO: Simplify if (...) content.\n    if (height <= CryptoNote::parameters::UPGRADE_HEIGHT_V3 ? size > CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_CURRENT * 30 / 100 : size > fusionTxMaxSize()) {\n        logger(ERROR) << \"Fusion transaction verification failed: size exceeded max allowed size.\";\n        return false;\n    }\n\n    if (inputsAmounts.size() < fusionTxMinInputCount()) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"inputs count is less than minimum.\";\n        return false;\n    }\n\n    if (inputsAmounts.size() < outputsAmounts.size() * fusionTxMinInOutCountRatio()) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"inputs to outputs count ratio is less than minimum.\";\n        return false;\n    }\n\n    uint64_t inputAmount = 0;\n    for (auto amount : inputsAmounts) {\n        if (height < CryptoNote::parameters::UPGRADE_HEIGHT_V4) {\n            if (amount < defaultDustThreshold()) {\n                logger(ERROR)\n                    << \"Fusion transaction verification failed: amount \"\n                    << amount\n                    << \" is less than dust threshold.\";\n                return false;\n            }\n        }\n        inputAmount += amount;\n    }\n\n    std::vector<uint64_t> expectedOutputsAmounts;\n    expectedOutputsAmounts.reserve(outputsAmounts.size());\n    decomposeAmount(\n        inputAmount,\n        height < CryptoNote::parameters::UPGRADE_HEIGHT_V4\n        ? defaultDustThreshold()\n        : UINT64_C(0), expectedOutputsAmounts);\n    std::sort(expectedOutputsAmounts.begin(), expectedOutputsAmounts.end());\n\n    bool decompose = expectedOutputsAmounts == outputsAmounts;\n    if (!decompose) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"decomposed output amounts do not match expected.\";\n        return false;\n    }\n\n    return true;\n}\n\nbool Currency::isFusionTransaction(const Transaction &transaction,size_t size,uint32_t height) const\n{\n    assert(getObjectBinarySize(transaction) == size);\n\n    std::vector<uint64_t> outputsAmounts;\n    outputsAmounts.reserve(transaction.outputs.size());\n    for (const TransactionOutput &output : transaction.outputs) {\n        outputsAmounts.push_back(output.amount);\n    }\n\n    return isFusionTransaction(getInputsAmounts(transaction), outputsAmounts, size, height);\n}\n\nbool Currency::isFusionTransaction(const Transaction &transaction, uint32_t height) const\n{\n    return isFusionTransaction(transaction, getObjectBinarySize(transaction), height);\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(\n    uint64_t amount,\n    uint64_t threshold,\n    uint32_t height) const\n{\n    uint8_t ignore;\n    return isAmountApplicableInFusionTransactionInput(amount, threshold, ignore, height);\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(\n    uint64_t amount,\n    uint64_t threshold,\n    uint8_t &amountPowerOfTen,\n    uint32_t height) const\n{\n    if (amount >= threshold) {\n        return false;\n    }\n\n    if (height < CryptoNote::parameters::UPGRADE_HEIGHT_V4 && amount < defaultDustThreshold()) {\n        return false;\n    }\n\n    auto it = std::lower_bound(\n        Constants::PRETTY_AMOUNTS.begin(),\n        Constants::PRETTY_AMOUNTS.end(),\n        amount\n    );\n    if (it == Constants::PRETTY_AMOUNTS.end() || amount != *it) {\n        return false;\n    }\n\n    amountPowerOfTen = static_cast<uint8_t>(std::distance(Constants::PRETTY_AMOUNTS.begin(), it)/9);\n\n    return true;\n}\n\nstd::string Currency::accountAddressAsString(const AccountBase &account) const\n{\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, account.getAccountKeys().address);\n}\n\nstd::string Currency::accountAddressAsString(const AccountPublicAddress &accountPublicAddress) const\n{\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, accountPublicAddress);\n}\n\nbool Currency::parseAccountAddressString(const std::string &str, AccountPublicAddress &addr) const\n{\n    uint64_t prefix;\n    if (!CryptoNote::parseAccountAddressString(prefix, addr, str)) {\n        return false;\n    }\n\n    if (prefix != m_publicAddressBase58Prefix) {\n        logger(DEBUGGING)\n        << \"Wrong address prefix: \" << prefix\n        << \", expected \" << m_publicAddressBase58Prefix;\n        return false;\n    }\n\n    return true;\n}\n\nstd::string Currency::formatAmount(uint64_t amount) const\n{\n    std::string s = std::to_string(amount);\n    if (s.size() < m_numberOfDecimalPlaces + 1) {\n        s.insert(0, m_numberOfDecimalPlaces + 1 - s.size(), '0');\n    }\n    s.insert(s.size() - m_numberOfDecimalPlaces, \".\");\n\n    return s;\n}\n\nstd::string Currency::formatAmount(int64_t amount) const\n{\n    std::string s = formatAmount(static_cast<uint64_t>(std::abs(amount)));\n\n    if (amount < 0) {\n        s.insert(0, \"-\");\n    }\n\n    return s;\n}\n\nbool Currency::parseAmount(const std::string &str, uint64_t &amount) const\n{\n    std::string strAmount = str;\n    boost::algorithm::trim(strAmount);\n\n    size_t pointIndex = strAmount.find_first_of('.');\n    size_t fractionSize;\n    if (std::string::npos != pointIndex) {\n        fractionSize = strAmount.size() - pointIndex - 1;\n        while (m_numberOfDecimalPlaces < fractionSize && '0' == strAmount.back()) {\n            strAmount.erase(strAmount.size() - 1, 1);\n            --fractionSize;\n        }\n        if (m_numberOfDecimalPlaces < fractionSize) {\n            return false;\n        }\n        strAmount.erase(pointIndex, 1);\n    } else {\n        fractionSize = 0;\n    }\n\n    if (strAmount.empty()) {\n        return false;\n    }\n\n    if (!std::all_of(strAmount.begin(), strAmount.end(), ::isdigit)) {\n        return false;\n    }\n\n    if (fractionSize < m_numberOfDecimalPlaces) {\n        strAmount.append(m_numberOfDecimalPlaces - fractionSize, '0');\n    }\n\n    return Common::fromString(strAmount, amount);\n}\n\n// Copyright (c) 2017-2018 Zawy\n// http://zawy1.blogspot.com/2017/12/using-difficulty-to-get-constant-value.html\n// Moore's law application by Sergey Kozlov\nuint64_t Currency::getMinimalFee(\n    uint64_t dailyDifficulty,\n    uint64_t reward,\n    uint64_t avgHistoricalDifficulty,\n    uint64_t medianHistoricalReward,\n    uint32_t height) const\n{\n    const uint64_t blocksInTwoYears = parameters::EXPECTED_NUMBER_OF_BLOCKS_PER_DAY * 365 * 2;\n    const double gauge = double(0.25);\n    uint64_t minimumFee(0);\n    double dailyDifficultyMoore = dailyDifficulty\n                                  / pow(2, static_cast<double>(height)\n                                  / static_cast<double>(blocksInTwoYears));\n    double minFee = gauge * parameters::COIN * static_cast<double>(avgHistoricalDifficulty)\n                    / dailyDifficultyMoore * static_cast<double>(reward)\n                    / static_cast<double>(medianHistoricalReward);\n    if (minFee == 0 || !std::isfinite(minFee)) {\n        return CryptoNote::parameters::MAXIMUM_FEE; // zero test\n    }\n    minimumFee = static_cast<uint64_t>(minFee);\n\n    // TODO: return std::min<uint64_t>(CryptoNote::parameters::MAXIMUM_FEE, minimumFee);\n    return CryptoNote::parameters::MINIMUM_FEE_V1;\n}\n\nuint64_t Currency::roundUpMinFee(uint64_t minimalFee, int digits) const\n{\n    uint64_t ret(0);\n    std::string minFeeString = formatAmount(minimalFee);\n    double minFee = boost::lexical_cast<double>(minFeeString);\n    double scale = pow(10., floor(log10(fabs(minFee))) + (1 - digits));\n    double roundedFee = ceil(minFee / scale) * scale;\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(12) << roundedFee;\n    std::string roundedFeeString = ss.str();\n    parseAmount(roundedFeeString, ret);\n\n    return ret;\n}\n\ndifficulty_type Currency::nextDifficulty(uint32_t height,\n    uint8_t blockMajorVersion,\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties,\n    uint64_t nextBlockTime, lazy_stat_callback_type &lazy_stat_cb) const\n{\n    // check if we use special scenario with some fixed diff\n    if (CryptoNote::parameters::FIXED_DIFFICULTY > 0)\n    {\n        logger (WARNING) << \"Fixed difficulty is used: \" <<\n                            CryptoNote::parameters::FIXED_DIFFICULTY;\n        return CryptoNote::parameters::FIXED_DIFFICULTY;\n    }\n    if (m_fixedDifficulty > 0)\n    {\n        logger (WARNING) << \"Fixed difficulty is used: \" <<\n                            m_fixedDifficulty;\n        return m_fixedDifficulty;\n    }\n\n    uint64_t last_timestamp = 0;\n    if (!timestamps.empty()) {\n        last_timestamp = timestamps.back();\n    }\n    if ((blockMajorVersion >= BLOCK_MAJOR_VERSION_6) &&\n            (nextBlockTime > last_timestamp + CryptoNote::parameters::CRYPTONOTE_CLIF_THRESHOLD)) {\n        size_t array_size = cumulativeDifficulties.size();\n        difficulty_type last_difficulty = 1;\n        if (array_size >= 2) {\n            last_difficulty = cumulativeDifficulties[array_size - 1] - cumulativeDifficulties[array_size - 2];\n        }\n        uint64_t currentSolveTime = nextBlockTime - last_timestamp;\n        return getClifDifficulty(height, blockMajorVersion,\n                               last_difficulty, last_timestamp,\n                               currentSolveTime, lazy_stat_cb);\n    }\n\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_6) {\n        return nextDifficultyV6(blockMajorVersion, timestamps, cumulativeDifficulties, height);\n    } else if (blockMajorVersion >= BLOCK_MAJOR_VERSION_5) {\n        return nextDifficultyV5(blockMajorVersion, timestamps, cumulativeDifficulties);\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_3\n               || blockMajorVersion == BLOCK_MAJOR_VERSION_4) {\n        return nextDifficultyV3(timestamps, cumulativeDifficulties);\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_2) {\n        return nextDifficultyV2(timestamps, cumulativeDifficulties);\n    } else {\n        return nextDifficultyV1(timestamps, cumulativeDifficulties);\n    }\n}\n\ndifficulty_type Currency::nextDifficultyV1(\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    assert(m_difficultyWindow >= 2);\n\n    if (timestamps.size() > m_difficultyWindow) {\n        timestamps.resize(m_difficultyWindow);\n        cumulativeDifficulties.resize(m_difficultyWindow);\n    }\n\n    size_t length = timestamps.size();\n    assert(length == cumulativeDifficulties.size());\n    assert(length <= m_difficultyWindow);\n    if (length <= 1) {\n        return 1;\n    }\n\n    sort(timestamps.begin(), timestamps.end());\n\n    size_t cutBegin, cutEnd;\n    assert(2 * m_difficultyCut <= m_difficultyWindow - 2);\n    if (length <= m_difficultyWindow - 2 * m_difficultyCut) {\n        cutBegin = 0;\n        cutEnd = length;\n    } else {\n        cutBegin = (length - (m_difficultyWindow - 2 * m_difficultyCut) + 1) / 2;\n        cutEnd = cutBegin + (m_difficultyWindow - 2 * m_difficultyCut);\n    }\n    assert(/*cut_begin >= 0 &&*/ cutBegin + 2 <= cutEnd && cutEnd <= length);\n    uint64_t timeSpan = timestamps[cutEnd - 1] - timestamps[cutBegin];\n    if (timeSpan == 0) {\n        timeSpan = 1;\n    }\n\n    difficulty_type totalWork = cumulativeDifficulties[cutEnd - 1]-cumulativeDifficulties[cutBegin];\n    assert(totalWork > 0);\n\n    uint64_t low, high;\n    low = mul128(totalWork, m_difficultyTarget, &high);\n    if (high != 0 || low + timeSpan - 1 < low) {\n        return 0;\n    }\n\n    return (low + timeSpan - 1) / timeSpan;\n}\n\ndifficulty_type Currency::nextDifficultyV2(\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    // Difficulty calculation v. 2\n    // based on Zawy difficulty algorithm v1.0\n    // next Diff = Avg past N Diff * TargetInterval / Avg past N solve times\n    // as described at https://github.com/monero-project/research-lab/issues/3\n    // Window time span and total difficulty is taken instead of average\n    // as suggested by Nuclear_chaos\n\n    size_t m_difficultyWindow_2 = CryptoNote::parameters::DIFFICULTY_WINDOW_V2;\n    assert(m_difficultyWindow_2 >= 2);\n\n    if (timestamps.size() > m_difficultyWindow_2) {\n        timestamps.resize(m_difficultyWindow_2);\n        cumulativeDifficulties.resize(m_difficultyWindow_2);\n    }\n\n    size_t length = timestamps.size();\n    assert(length == cumulativeDifficulties.size());\n    assert(length <= m_difficultyWindow_2);\n    if (length <= 1) {\n        return 1;\n    }\n\n    sort(timestamps.begin(), timestamps.end());\n\n    uint64_t timeSpan = timestamps.back() - timestamps.front();\n    if (timeSpan == 0) {\n        timeSpan = 1;\n    }\n\n    difficulty_type totalWork = cumulativeDifficulties.back() - cumulativeDifficulties.front();\n    assert(totalWork > 0);\n\n    // uint64_t nextDiffZ = totalWork * m_difficultyTarget / timeSpan;\n\n    uint64_t low, high;\n    low = mul128(totalWork, m_difficultyTarget, &high);\n    // blockchain error \"Difficulty overhead\" if this function returns zero\n    if (high != 0) {\n        return 0;\n    }\n\n    uint64_t nextDiffZ = low / timeSpan;\n\n    // minimum limit\n    if (!isTestnet() && nextDiffZ < 100000) {\n        nextDiffZ = 100000;\n    }\n\n    return nextDiffZ;\n}\n\ndifficulty_type Currency::nextDifficultyV3(\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    // LWMA difficulty algorithm\n    // Copyright (c) 2017-2018 Zawy\n    // MIT license http://www.opensource.org/licenses/mit-license.php.\n    // This is an improved version of Tom Harding's (Deger8) \"WT-144\"\n    // Karbowanec, Masari, Bitcoin Gold, and Bitcoin Cash have contributed.\n    // See https://github.com/zawy12/difficulty-algorithms/issues/1 for other algos.\n    // Do not use \"if solvetime < 0 then solvetime = 1\" which allows a catastrophic exploit.\n    // T= target_solvetime;\n    // N = int(45 * (600 / T) ^ 0.3));\n\n    const int64_t T = static_cast<int64_t>(m_difficultyTarget);\n    size_t N = CryptoNote::parameters::DIFFICULTY_WINDOW_V3;\n\n    // return a difficulty of 1 for first 3 blocks if it's the start of the chain\n    if (timestamps.size() < 4) {\n        return 1;\n    } else if (timestamps.size() < N + 1) {\n        // otherwise, use a smaller N if the start of the chain is less than N+1\n        N = timestamps.size() - 1;\n    } else if (timestamps.size() > N + 1) {\n        timestamps.erase(timestamps.begin(), timestamps.end() - N - 1);\n        cumulativeDifficulties.erase(\n            cumulativeDifficulties.begin(),\n            cumulativeDifficulties.end() - N - 1\n        );\n    }\n\n    // To get an average solvetime to within +/- ~0.1%, use an adjustment factor.\n    const double adjust = 0.998;\n    // The divisor k normalizes LWMA.\n    const double k = N * (N + 1) / 2;\n\n    double LWMA(0), sum_inverse_D(0), harmonic_mean_D(0), nextDifficulty(0);\n    int64_t solveTime(0);\n    uint64_t difficulty(0), next_difficulty(0);\n\n    // Loop through N most recent blocks.\n    for (size_t i = 1; i <= N; i++) {\n        solveTime = static_cast<int64_t>(timestamps[i]) - static_cast<int64_t>(timestamps[i - 1]);\n        solveTime = std::min<int64_t>((T * 7), std::max<int64_t>(solveTime, (-6 * T)));\n        difficulty = cumulativeDifficulties[i] - cumulativeDifficulties[i - 1];\n        LWMA += (int64_t)(solveTime * i) / k;\n        sum_inverse_D += 1 / static_cast<double>(difficulty);\n    }\n\n    // Keep LWMA sane in case something unforeseen occurs.\n    if (static_cast<int64_t>(boost::math::round(LWMA)) < T / 20)\n    LWMA = static_cast<double>(T) / 20;\n\n    harmonic_mean_D = N / sum_inverse_D * adjust;\n    nextDifficulty = harmonic_mean_D * T / LWMA;\n    next_difficulty = static_cast<uint64_t>(nextDifficulty);\n\n    // minimum limit\n    if (!isTestnet() && next_difficulty < 100000) {\n        next_difficulty = 100000;\n    }\n\n    return next_difficulty;\n}\n\ntemplate <typename T>\ninline T clamp(T lo, T v, T hi)\n{\n    return v < lo ? lo : v > hi ? hi : v;\n}\n\n// difficulty for block version 5.0\ndifficulty_type Currency::nextDifficultyV5(\n    uint8_t blockMajorVersion,\n    std::vector<std::uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    // LWMA-2 difficulty algorithm\n    // Copyright (c) 2017-2018 Zawy, MIT License\n    // https://github.com/zawy12/difficulty-algorithms/issues/3\n    // with modifications by Ryo Currency developers\n    // courtesy to aivve from Karbo\n\n    const int64_t  T = static_cast<int64_t>(m_difficultyTarget);\n    int64_t  N = difficultyBlocksCount3();\n    int64_t  L(0), ST, sum_3_ST(0);\n    uint64_t nextDiffV5, prev_D;\n\n    assert(timestamps.size() == cumulativeDifficulties.size()\n           && timestamps.size() <= static_cast<uint64_t>(N + 1));\n\n    int64_t max_TS, prev_max_TS;\n    prev_max_TS = timestamps[0];\n    for (int64_t i = 1; i <= N; i++) {\n        if (static_cast<int64_t>(timestamps[i]) > prev_max_TS) {\n            max_TS = timestamps[i];\n        } else {\n            max_TS = prev_max_TS + 1;\n        }\n        ST = std::min(6 * T, max_TS - prev_max_TS);\n        prev_max_TS = max_TS;\n        L += ST * i;\n        if (i > N - 3) {\n            sum_3_ST += ST;\n        }\n    }\n\n    // It is a potential error,  N should be less than cumulativeDifficulties.size()\n    nextDiffV5 = uint64_t((cumulativeDifficulties[N] - cumulativeDifficulties[0]) * T * (N + 1))\n                 / uint64_t(2 * L);\n    nextDiffV5 = (nextDiffV5 * 99ull) / 100ull;\n\n    // It is a potential error,  N should be less than cumulativeDifficulties.size()\n    prev_D = cumulativeDifficulties[N] - cumulativeDifficulties[N - 1];\n    nextDiffV5 = clamp(\n        (uint64_t)(prev_D * 67ull / 100ull),\n        nextDiffV5,\n        (uint64_t)(prev_D * 150ull / 100ull)\n    );\n    if (sum_3_ST < (8 * T) / 10) {\n        nextDiffV5 = (prev_D * 110ull) / 100ull;\n    }\n\n    // minimum limit\n    if (nextDiffV5 < 10000000) {\n        nextDiffV5 = 10000000;\n    }\n    if(isTestnet()){\n        nextDiffV5 = 10000;\n    }\n\n    return nextDiffV5;\n}\n\n// difficulty for block version 6.0\ndifficulty_type Currency::nextDifficultyV6(uint8_t blockMajorVersion,\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties,\n    uint32_t height) const\n{\n    if(isTestnet()){\n        return CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    }\n\n    if (timestamps.empty()) {\n        return CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    }\n    // Dynamic difficulty calculation window\n    uint32_t diffWindow = timestamps.size() - 1;\n\n    difficulty_type nextDiffV6 = CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    difficulty_type min_difficulty = CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    // Condition #1 When starting a chain or a working testnet requiring\n    // block sample gathering until enough blocks are available (Kick-off Scenario)\n    // We shall set a baseline for the hashrate that is specific to mining\n    // algo and I propose doing so in the config file.\n    // *** During this initial sampling period, a best guess is the best strategy.\n    // Consider this as a service or trial period.\n    // With EPoW reward algo in place, we don't really need to worry about attackers\n    // or large miners taking advanatage of our system.\n    if (height < CryptoNote::parameters::UPGRADE_HEIGHT_V6 + diffWindow) {\n        return nextDiffV6;\n    }\n\n    // check all values in input vectors greater than previous value to calc adjacent differences later\n    if (std::adjacent_find(timestamps.begin(), timestamps.end(), std::greater<uint64_t>()) != timestamps.end()) {\n        logger (ERROR) << \"Invalid timestamps for difficulty calculation\";\n        return nextDiffV6;\n    }\n    if (std::adjacent_find(cumulativeDifficulties.begin(), cumulativeDifficulties.end(), std::greater_equal<difficulty_type>()) != cumulativeDifficulties.end()) {\n        logger (ERROR) << \"Invalid cumulativeDifficulties for difficulty calculation\";\n        return nextDiffV6;\n    }\n\n    uint64_t difficulty_target = CryptoNote::parameters::DIFFICULTY_TARGET;\n    uint64_t window_target = difficulty_target * diffWindow;\n    uint64_t window_time = timestamps.back() - timestamps.front(); // now subtraction is safe,  we know it is not negative\n\n    // get solvetimes from timestamps\n    std::vector<uint64_t> solveTimes;\n    solveTimes.resize(timestamps.size());\n    std::adjacent_difference(timestamps.begin(), timestamps.end(), solveTimes.begin()); // we check it before and all diffs are positive\n    solveTimes.erase(solveTimes.begin());\n\n    // get difficulties from the cumulative difficulties\n    std::vector<difficulty_type> difficulties;\n    difficulties.resize(cumulativeDifficulties.size());\n    std::adjacent_difference(cumulativeDifficulties.begin(),\n                             cumulativeDifficulties.end(),\n                             difficulties.begin()); // we check it before and all diffs are positive\n    difficulties.erase(difficulties.begin());\n    difficulty_type prev_difficulty = difficulties.back();\n\n    // calc stat values to detect outliers\n    double avg_solvetime = Common::meanValue(solveTimes);\n    double stddev_solvetime = Common::stddevValue(solveTimes);\n    double solvetime_lowborder = 1.0;\n    if(avg_solvetime > stddev_solvetime)\n        solvetime_lowborder = avg_solvetime - stddev_solvetime;\n    double solvetime_highborder = avg_solvetime + stddev_solvetime;\n    size_t valid_solvetime_number = 0;\n    uint64_t valid_solvetime_sum = 0;\n    size_t invalid_solvetime_number = 0;\n    uint64_t invalid_solvetime_sum = 0;\n    std::for_each(solveTimes.begin(), solveTimes.end(),\n                  [solvetime_lowborder, solvetime_highborder,\n                   &valid_solvetime_number, &valid_solvetime_sum,\n                   &invalid_solvetime_number, &invalid_solvetime_sum] (uint64_t st) {\n        if ((st >= solvetime_lowborder) && (st <= solvetime_highborder)) {\n            valid_solvetime_number++;\n            valid_solvetime_sum += st;\n        } else {\n            invalid_solvetime_number++;\n            invalid_solvetime_sum += st;\n        }\n    });\n\n    // if there is no \"invalid\" solvetimes we can use previous difficulty value\n    if (invalid_solvetime_number == 0) {\n        return std::max(prev_difficulty, min_difficulty);\n    }\n\n    // process data with \"invalid\" solvetimes\n    double valid_solvetime_mean = double(valid_solvetime_sum) / valid_solvetime_number;\n    double invalid_solvetime_mean = double(invalid_solvetime_sum) / invalid_solvetime_number;\n\n    if ( (window_time >= window_target * 0.97) &&\n         (window_time <= window_target * 1.03) ) {\n        if (valid_solvetime_mean >= invalid_solvetime_mean) {\n            double coef = double(difficulty_target) / double(valid_solvetime_mean);\n            if (valid_solvetime_mean < difficulty_target) {\n                nextDiffV6 = prev_difficulty * std::min(1.01, coef) + 0.5;\n            } else {\n                nextDiffV6 = prev_difficulty * std::max(0.99, coef) + 0.5;\n            }\n        } else {\n            double coef = double(difficulty_target) / double(invalid_solvetime_mean);\n            if (invalid_solvetime_mean < difficulty_target) {\n                nextDiffV6 = prev_difficulty * std::min(1.01, coef) + 0.5;\n            } else {\n                nextDiffV6 = prev_difficulty * std::max(0.99, coef) + 0.5;\n            }\n        }\n    } else if (window_time < window_target * 0.97) {\n        nextDiffV6 = prev_difficulty * 1.02 + 0.5;\n    } else {\n        nextDiffV6 = prev_difficulty * 0.98 + 0.5;\n    }\n\n    return std::max(nextDiffV6, min_difficulty);\n}\n\ndifficulty_type Currency::getClifDifficulty(uint32_t height,\n                                          uint8_t blockMajorVersion,\n                                          difficulty_type last_difficulty,\n                                          uint64_t last_timestamp,\n                                          uint64_t currentSolveTime,\n                                          lazy_stat_callback_type &lazy_stat_cb) const\n{\n    logger (INFO) << \"CLIF difficulty inputs: height \" << height <<\n                     \", block version \" << (int)blockMajorVersion <<\n                     \", last difficulty \" << last_difficulty <<\n                     \", current solve time \" << currentSolveTime;\n\n    difficulty_type new_diff = last_difficulty;\n\n    if (new_diff > CryptoNote::parameters::DEFAULT_DIFFICULTY) {\n        uint64_t correction_interval = currentSolveTime -\n                CryptoNote::parameters::CRYPTONOTE_CLIF_THRESHOLD;\n        //below equation shall return quotient of the division.\n        int decrease_counter = ((int)correction_interval / (int)CryptoNote::parameters::DIFFICULTY_TARGET) + 1;\n        int round_counter = 1;\n\n        new_diff = new_diff / 2;\n        logger (INFO) << \"CLIF decreased difficulty \" << round_counter <<\n            \" times, intermediate difficulty is \" << new_diff;\n        difficulty_type mean_diff = lazy_stat_cb(IMinerHandler::stat_period::hour, last_timestamp);\n        logger (INFO) << \"Last hour average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::day, last_timestamp);\n        logger (INFO) << \"Last day average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::week, last_timestamp);\n        logger (INFO) << \"Last week average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::month, last_timestamp);\n        logger (INFO) << \"Last month average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::halfyear, last_timestamp);\n        logger (INFO) << \"Last halfyear average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::year, last_timestamp);\n        logger (INFO) << \"Last year average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n\n        if (decrease_counter > 1) {\n            while (round_counter < decrease_counter) {\n                new_diff = new_diff / 2;\n                round_counter++;\n                if (new_diff <= CryptoNote::parameters::DEFAULT_DIFFICULTY)\n                    break;\n            }\n            logger (INFO) << \"CLIF decreased difficulty \" << round_counter <<\n                \" times, intermediate difficulty is \" << new_diff;\n        }\n\n        new_diff = std::max(new_diff, difficulty_type(CryptoNote::parameters::DEFAULT_DIFFICULTY));\n    }\n\n    logger (INFO) << \"CLIF difficulty result: \" << new_diff;\n    return new_diff;\n}\n\nbool Currency::checkProofOfWorkV1(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    if (BLOCK_MAJOR_VERSION_2 == block.majorVersion||BLOCK_MAJOR_VERSION_3 == block.majorVersion) {\n        return false;\n    }\n\n    if (!get_block_longhash(context, block, proofOfWork)) {\n        return false;\n    }\n\n    return check_hash(proofOfWork, currentDiffic);\n}\n\nbool Currency::checkProofOfWorkV2(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    if (block.majorVersion < BLOCK_MAJOR_VERSION_2) {\n        return false;\n    }\n\n    if (!get_block_longhash(context, block, proofOfWork)) {\n        return false;\n    }\n\n    if (!check_hash(proofOfWork, currentDiffic)) {\n        return false;\n    }\n\n    TransactionExtraMergeMiningTag mmTag;\n    if (!getMergeMiningTagFromExtra(block.parentBlock.baseTransaction.extra, mmTag)) {\n        logger(ERROR)\n            << \"merge mining tag wasn't found in extra of the parent block miner transaction\";\n        return false;\n    }\n\n    if (8 * sizeof(m_genesisBlockHash) < block.parentBlock.blockchainBranch.size()) {\n        return false;\n    }\n\n    Crypto::Hash auxBlockHeaderHash;\n    if (!get_aux_block_header_hash(block, auxBlockHeaderHash)) {\n        return false;\n    }\n\n    Crypto::Hash auxBlocksMerkleRoot;\n    Crypto::tree_hash_from_branch(\n        block.parentBlock.blockchainBranch.data(),\n        block.parentBlock.blockchainBranch.size(),\n        auxBlockHeaderHash,\n        &m_genesisBlockHash,\n        auxBlocksMerkleRoot\n    );\n\n    if (auxBlocksMerkleRoot != mmTag.merkleRoot) {\n        logger(ERROR, BRIGHT_YELLOW) << \"Aux block hash wasn't found in merkle tree\";\n        return false;\n    }\n\n    return true;\n}\n\nbool Currency::checkProofOfWork(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    switch (block.majorVersion) {\n    case BLOCK_MAJOR_VERSION_1:\n        // fall through\n    case BLOCK_MAJOR_VERSION_4:\n        // fall through\n    case BLOCK_MAJOR_VERSION_5:\n        // fall through\n    case BLOCK_MAJOR_VERSION_6:\n        return checkProofOfWorkV1(context, block, currentDiffic, proofOfWork);\n    case BLOCK_MAJOR_VERSION_2:\n        // fall through\n    case BLOCK_MAJOR_VERSION_3:\n        return checkProofOfWorkV2(context, block, currentDiffic, proofOfWork);\n    }\n\n    logger(ERROR, BRIGHT_RED)\n        << \"Unknown block major version: \"\n        << block.majorVersion\n        << \".\"\n        << block.minorVersion;\n\n    return false;\n}\n\nsize_t Currency::getApproximateMaximumInputCount(\n    size_t transactionSize,\n    size_t outputCount,\n    size_t mixinCount) const\n{\n    const size_t KEY_IMAGE_SIZE = sizeof(Crypto::KeyImage);\n    const size_t OUTPUT_KEY_SIZE = sizeof(decltype(KeyOutput::key));\n    const size_t AMOUNT_SIZE = sizeof(uint64_t) + 2; // varint\n    const size_t GLOBAL_INDEXES_VECTOR_SIZE_SIZE = sizeof(uint8_t); // varint\n    const size_t GLOBAL_INDEXES_INITIAL_VALUE_SIZE = sizeof(uint32_t); // varint\n    const size_t GLOBAL_INDEXES_DIFFERENCE_SIZE = sizeof(uint32_t); // varint\n    const size_t SIGNATURE_SIZE = sizeof(Crypto::Signature);\n    const size_t EXTRA_TAG_SIZE = sizeof(uint8_t);\n    const size_t INPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t OUTPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t PUBLIC_KEY_SIZE = sizeof(Crypto::PublicKey);\n    const size_t TRANSACTION_VERSION_SIZE = sizeof(uint8_t);\n    const size_t TRANSACTION_UNLOCK_TIME_SIZE = sizeof(uint64_t);\n\n    const size_t outputsSize = outputCount * (OUTPUT_TAG_SIZE + OUTPUT_KEY_SIZE + AMOUNT_SIZE);\n    const size_t headerSize = TRANSACTION_VERSION_SIZE\n                              + TRANSACTION_UNLOCK_TIME_SIZE\n                              + EXTRA_TAG_SIZE\n                              + PUBLIC_KEY_SIZE;\n    const size_t inputSize = INPUT_TAG_SIZE\n                             + AMOUNT_SIZE\n                             + KEY_IMAGE_SIZE\n                             + SIGNATURE_SIZE\n                             + GLOBAL_INDEXES_VECTOR_SIZE_SIZE\n                             + GLOBAL_INDEXES_INITIAL_VALUE_SIZE\n                             + mixinCount * (GLOBAL_INDEXES_DIFFERENCE_SIZE + SIGNATURE_SIZE);\n\n    return (transactionSize - headerSize - outputsSize) / inputSize;\n}\n\nCurrencyBuilder::CurrencyBuilder(Logging::ILogger &log)\n    : m_currency(log)\n{\n    maxBlockNumber(parameters::CRYPTONOTE_MAX_BLOCK_NUMBER);\n    maxBlockBlobSize(parameters::CRYPTONOTE_MAX_BLOCK_BLOB_SIZE);\n    maxTxSize(parameters::CRYPTONOTE_MAX_TX_SIZE);\n    publicAddressBase58Prefix(parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX);\n    minedMoneyUnlockWindow(parameters::CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW);\n    transactionSpendableAge(parameters::CRYPTONOTE_TX_SPENDABLE_AGE);\n    safeTransactionSpendableAge(parameters::CRYPTONOTE_SAFE_TX_SPENDABLE_AGE);\n    expectedNumberOfBlocksPerDay(parameters::EXPECTED_NUMBER_OF_BLOCKS_PER_DAY);\n\n    timestampCheckWindow(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);\n    timestampCheckWindow_v1(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW_V1);\n    blockFutureTimeLimit(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT);\n    blockFutureTimeLimit_v1(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT_V1);\n\n    moneySupply(parameters::MONEY_SUPPLY);\n    emissionSpeedFactor(parameters::EMISSION_SPEED_FACTOR);\n    cryptonoteCoinVersion(parameters::CRYPTONOTE_COIN_VERSION);\n\n    rewardBlocksWindow(parameters::CRYPTONOTE_REWARD_BLOCKS_WINDOW);\n    blockGrantedFullRewardZone(parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE);\n    minerTxBlobReservedSize(parameters::CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE);\n    maxTransactionSizeLimit(parameters::MAX_TRANSACTION_SIZE_LIMIT);\n\n    governancePercent(parameters::GOVERNANCE_PERCENT_FEE);\n    governanceHeightStart(parameters::GOVERNANCE_HEIGHT_START);\n    governanceHeightEnd(parameters::GOVERNANCE_HEIGHT_END);\n\n    minMixin(parameters::MIN_TX_MIXIN_SIZE);\n    maxMixin(parameters::MAX_TX_MIXIN_SIZE);\n\n    numberOfDecimalPlaces(parameters::CRYPTONOTE_DISPLAY_DECIMAL_POINT);\n\n    minimumFee(parameters::MINIMUM_FEE);\n    defaultDustThreshold(parameters::DEFAULT_DUST_THRESHOLD);\n\n    difficultyTarget(parameters::DIFFICULTY_TARGET);\n    difficultyWindow(parameters::DIFFICULTY_WINDOW);\n    difficultyLag(parameters::DIFFICULTY_LAG);\n    difficultyCut(parameters::DIFFICULTY_CUT);\n\n    maxBlockSizeInitial(parameters::MAX_BLOCK_SIZE_INITIAL);\n    maxBlockSizeGrowthSpeedNumerator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_NUMERATOR);\n    maxBlockSizeGrowthSpeedDenominator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_DENOMINATOR);\n\n    lockedTxAllowedDeltaSeconds(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS);\n    lockedTxAllowedDeltaBlocks(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS);\n\n    mempoolTxLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_LIVETIME);\n    mempoolTxFromAltBlockLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME);\n    numberOfPeriodsToForgetTxDeletedFromPool(\n        parameters::CRYPTONOTE_NUMBER_OF_PERIODS_TO_FORGET_TX_DELETED_FROM_POOL\n    );\n\n    fusionTxMaxSize(parameters::FUSION_TX_MAX_SIZE);\n    fusionTxMinInputCount(parameters::FUSION_TX_MIN_INPUT_COUNT);\n    fusionTxMinInOutCountRatio(parameters::FUSION_TX_MIN_IN_OUT_COUNT_RATIO);\n\n    upgradeHeightV2(parameters::UPGRADE_HEIGHT_V2);\n    upgradeHeightV3(parameters::UPGRADE_HEIGHT_V3);\n    upgradeHeightV4(parameters::UPGRADE_HEIGHT_V4);\n    upgradeHeightV5(parameters::UPGRADE_HEIGHT_V5);\n    upgradeHeightV6(parameters::UPGRADE_HEIGHT_V6);\n    upgradeVotingThreshold(parameters::UPGRADE_VOTING_THRESHOLD);\n    upgradeVotingWindow(parameters::UPGRADE_VOTING_WINDOW);\n    upgradeWindow(parameters::UPGRADE_WINDOW);\n\n    blocksFileName(parameters::CRYPTONOTE_BLOCKS_FILENAME);\n    blocksCacheFileName(parameters::CRYPTONOTE_BLOCKSCACHE_FILENAME);\n    blockIndexesFileName(parameters::CRYPTONOTE_BLOCKINDEXES_FILENAME);\n    txPoolFileName(parameters::CRYPTONOTE_POOLDATA_FILENAME);\n    blockchainIndicesFileName(parameters::CRYPTONOTE_BLOCKCHAIN_INDICES_FILENAME);\n\n    testnet(false);\n    fix_difficulty(0);\n}\n\nTransaction CurrencyBuilder::generateGenesisTransaction()\n{\n    CryptoNote::Transaction tx;\n    auto ac = boost::value_initialized<CryptoNote::AccountPublicAddress>();\n\n    m_currency.constructMinerTx(1, 0, 0, 0, 0, 0, ac, tx); // zero fee in genesis\n\n    return tx;\n}\n\nCurrencyBuilder& CurrencyBuilder::emissionSpeedFactor(unsigned int val)\n{\n    if (val <= 0 || val > 8 * sizeof(uint64_t)) {\n        throw std::invalid_argument(\"val at emissionSpeedFactor()\");\n    }\n\n    m_currency.m_emissionSpeedFactor = val;\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::numberOfDecimalPlaces(size_t val)\n{\n    m_currency.m_numberOfDecimalPlaces = val;\n    m_currency.m_coin = 1;\n    for (size_t i = 0; i < m_currency.m_numberOfDecimalPlaces; ++i) {\n        m_currency.m_coin *= 10;\n    }\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::difficultyWindow(size_t val)\n{\n    if (val < 2) {\n        throw std::invalid_argument(\"val at difficultyWindow()\");\n    }\n\n    m_currency.m_difficultyWindow = val;\n\n    return *this;\n}\n\nCurrencyBuilder& CurrencyBuilder::upgradeVotingThreshold(unsigned int val)\n{\n    if (val <= 0 || val > 100) {\n        throw std::invalid_argument(\"val at upgradeVotingThreshold()\");\n    }\n\n    m_currency.m_upgradeVotingThreshold = val;\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::upgradeWindow(size_t val)\n{\n    if (val <= 0) {\n        throw std::invalid_argument(\"val at upgradeWindow()\");\n    }\n\n    m_currency.m_upgradeWindow = static_cast<uint32_t>(val);\n\n    return *this;\n}\n\n} // namespace CryptoNote\n", "meta": {"hexsha": "b488b4f6daba42d59889df34e38ee77f489faccb", "size": 52426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/CryptoNoteCore/Currency.cpp", "max_stars_repo_name": "deocoin-project/deocoin", "max_stars_repo_head_hexsha": "26944a1b6729e031d0c14af8c23a17c3af877535", "max_stars_repo_licenses": ["MIT"], "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/CryptoNoteCore/Currency.cpp", "max_issues_repo_name": "deocoin-project/deocoin", "max_issues_repo_head_hexsha": "26944a1b6729e031d0c14af8c23a17c3af877535", "max_issues_repo_licenses": ["MIT"], "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/CryptoNoteCore/Currency.cpp", "max_forks_repo_name": "deocoin-project/deocoin", "max_forks_repo_head_hexsha": "26944a1b6729e031d0c14af8c23a17c3af877535", "max_forks_repo_licenses": ["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.9082191781, "max_line_length": 183, "alphanum_fraction": 0.6705260748, "num_tokens": 12638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776782797747225, "lm_q2_score": 0.02064592934572146, "lm_q1q2_score": 0.005941234244394619}}
{"text": "/*  \n *  Copyright 2010-2011 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#ifndef HALFEDGEDIAGRAM_HPP\n#define HALFEDGEDIAGRAM_HPP\n\n#include <vector>\n#include <list>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/foreach.hpp> \n\n// bundled BGL properties, see: http://www.boost.org/doc/libs/1_44_0/libs/graph/doc/bundles.html\n\n// dcel notes from http://www.holmes3d.net/graphics/dcel/\n\n// vertex (boost::out_edges)\n//  -leaving pointer to HalfEdge that has this vertex as origin\n//   if many HalfEdges have this vertex as origin, choose one arbitrarily\n\n// HalfEdge\n//  - origin pointer to vertex (boost::source)\n//  - face to the left of halfedge\n//  - twin pointer to HalfEdge (on the right of this edge)\n//  - next pointer to HalfEdge\n//     this edge starts from h->twin->origin and ends at next vertex in h->face\n//     traveling ccw around boundary\n//     (allows face traverse, follow h->next until we arrive back at h)\n\n// Face\n//  - edge pointer to HalfEdge\n//    this edge has this Face object as face\n//    half-edge can be any one on the boundary of face\n// special \"infinite face\", face on \"outside\" of boundary\n// may or may not store edge pointer\n\n\n/// HEDIGraph is a A half-edge diagram class.\n/// Templated on Vertex/Edge/Face property classes which allow\n/// attaching information to vertices/edges/faces that is \n/// required for a particular algorithm.\n/// \n/// Inherits from boost::adjacency_list\n/// minor additions allow storing face-properties.\n///\n/// the hedi namespace contains functions for manipulating HEDIGraphs\n///\n/// For a general description of the half-edge data structure see e.g.:\n///  - http://www.holmes3d.net/graphics/dcel/\n///  - http://openmesh.org/index.php?id=228\n\nnamespace ocl {\n\nnamespace hedi  { \n\ntemplate <class TOutEdgeList, \n          class TVertexList,\n          class TDirected, \n          class TVertexProperties,\n          class TEdgeProperties,\n          class TFaceProperties,\n          class TGraphProperties,\n          class TEdgeList \n          >\nclass HEDIGraph {\n    public:\n        \n        typedef typename boost::adjacency_list< TOutEdgeList,            \n                                                TVertexList,            \n                                                TDirected,   \n                                                TVertexProperties,             \n                                                TEdgeProperties,                \n                                                TGraphProperties,\n                                                TEdgeList\n                                                > BGLGraph;\n        typedef unsigned int Face; \n        typedef typename boost::graph_traits< BGLGraph >::edge_descriptor Edge;\n        typedef typename boost::graph_traits< BGLGraph >::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits< BGLGraph >::vertex_iterator    VertexItr;\n        typedef typename boost::graph_traits< BGLGraph >::edge_iterator      EdgeItr;\n        typedef typename boost::graph_traits< BGLGraph >::out_edge_iterator  OutEdgeItr;\n        typedef typename boost::graph_traits< BGLGraph >::adjacency_iterator AdjacencyItr;\n                \n        typedef std::vector<Vertex> VertexVector;\n        typedef std::vector<Face> FaceVector;\n        typedef std::vector<Edge> EdgeVector;  \n\n        inline TFaceProperties& operator[](Face f)  { return faces[f];  }\n        inline const TFaceProperties& operator[](Face f) const  { return faces[f]; } \n        \n        inline TEdgeProperties& operator[](Edge e)  { return g[e];  }\n        inline const TEdgeProperties& operator[](Edge e) const  { return g[e];  }\n        \n        inline TVertexProperties& operator[](Vertex v)  { return g[v];  }\n        inline const TVertexProperties& operator[](Vertex v) const  { return g[v];  }\n        \n//DATA\n        std::vector< TFaceProperties > faces;\n        BGLGraph g;\n\nVertex null_vertex() {\n    return boost::graph_traits<BGLGraph>::null_vertex();\n}\n\n/// add a blank vertex and return its descriptor\nVertex add_vertex() { \n    return boost::add_vertex( g );\n}\n\n/*\n/// add a vertex with given properties, return vertex descriptor\ntemplate < class FVertexProperty>\ntypename boost::graph_traits< BGLGraph >::vertex_descriptor add_vertex(typedef const FVertexProperty& prop) {\n    return boost::add_vertex( prop, g );\n}*/\n\n/// add an edge between vertices v1-v2\nEdge add_edge(Vertex v1, Vertex v2) {\n    Edge e;\n    bool b;\n    boost::tie( e , b ) = boost::add_edge( v1, v2, g);\n    return e;\n}\n\n/// add an edge with given properties between vertices v1-v2\n//template < class EdgeProperty>\n/*\ntypename boost::graph_traits< BGLGraph >::edge_descriptor add_edge( \n                                                       typename boost::graph_traits< BGLGraph >::vertex_descriptor v1, \n                                                       typename boost::graph_traits< BGLGraph >::vertex_descriptor v2, \n                                                       typename  TEdgeProperties prop\n                                                       ) {\n    typename boost::graph_traits< BGLGraph >::edge_descriptor e;\n    bool b;\n    boost::tie( e , b ) = boost::add_edge( v1, v2, prop, g);\n    return e;\n}*/\n\n/// make e1 the twin of e2 (and vice versa)\nvoid twin_edges( Edge e1, Edge e2 ) {\n    g[e1].twin = e2;\n    g[e2].twin = e1;\n}\n\n\n/// add a face \nFace add_face() {\n    TFaceProperties f_prop;\n    faces.push_back( f_prop); \n    Face index = faces.size()-1;\n    faces[index].idx = index;\n    return index;    \n}\n        \n\n/// return the target vertex of the given edge\nVertex target( Edge e ) { \n    return boost::target( e, g);\n}\n\n/// return the source vertex of the given edge\nVertex source( Edge e )  { \n    return boost::source( e, g); \n}\n\n/// return all vertices in a vector of vertex descriptors\nVertexVector vertices()  {\n    typedef typename boost::graph_traits< BGLGraph >::vertex_descriptor  HEVertex;\n    typedef std::vector<HEVertex> VertexVector;\n    typedef typename boost::graph_traits< BGLGraph >::vertex_iterator    HEVertexItr;\n    VertexVector vv;\n    HEVertexItr it_begin, it_end, itr;\n    boost::tie( it_begin, it_end ) = boost::vertices( g );\n    for ( itr=it_begin ; itr != it_end ; ++itr ) {\n        vv.push_back( *itr );\n    }\n    return vv;\n}\n\n/// return all vertices adjecent to given vertex\nVertexVector adjacent_vertices(  Vertex v) {\n    VertexVector vv;\n    BOOST_FOREACH( Edge edge, out_edges( v ) ) {\n        vv.push_back( target( edge ) );\n    }\n    return vv;\n}\n\n/// return all vertices of given face\n\nVertexVector face_vertices(Face face_idx) {\n    VertexVector verts;\n    Edge startedge = faces[face_idx].edge; // the edge where we start\n    Vertex start_target = boost::target( startedge, g); \n    verts.push_back(start_target);\n    Edge current = g[startedge].next;\n    do {\n        Vertex current_target = boost::target( current, g); \n        verts.push_back(current_target);\n        current = g[current].next;\n    } while ( current != startedge );\n    return verts;\n}\n\n/// return edges of face f\nEdgeVector face_edges( Face f ) {\n    //Edge start_edge = g[ f ].edge; // was cast: (Face)f\n    Edge start_edge = faces[f].edge;\n    Edge current_edge = start_edge;\n    EdgeVector out;\n    do {\n        out.push_back(current_edge);\n        current_edge = g[current_edge].next;\n    } while( current_edge != start_edge );\n    return out;\n}\n\n\n/// return degree of given vertex\nunsigned int degree( Vertex v)  { \n    return boost::degree( v, g); \n}\n\n/// return number of vertices in graph\nunsigned int num_vertices() const { \n    return boost::num_vertices( g ); \n}\n\n/// return out_edges of given vertex\nEdgeVector out_edges( Vertex v) { \n    typedef typename boost::graph_traits< BGLGraph >::out_edge_iterator  HEOutEdgeItr;\n    EdgeVector ev;\n    HEOutEdgeItr it, it_end;\n    boost::tie( it, it_end ) = boost::out_edges( v, g );\n    for ( ; it != it_end ; ++it ) {\n        ev.push_back(*it);\n    }\n    return ev;\n}\n\n/// return all edges\nEdgeVector  edges() {\n    typedef typename boost::graph_traits< BGLGraph >::edge_iterator      HEEdgeItr; \n    EdgeVector ev;\n    HEEdgeItr it, it_end;\n    boost::tie( it, it_end ) = boost::edges( g );\n    for ( ; it != it_end ; ++it ) {\n        ev.push_back(*it);\n    }\n    return ev;\n}\n\n/// return v1-v2 edge descriptor\nEdge edge( Vertex v1, Vertex v2 ) {\n    typedef typename std::pair<Edge, bool> EdgeBool;\n    EdgeBool result = boost::edge(v1, v2, g );\n    return result.first;\n}\n\n/// return the previous edge. traverses all edges in face until previous found.\nEdge previous_edge( Edge e ) {\n    Edge previous = g[e].next;\n    while ( g[previous].next != e ) {\n        previous = g[previous].next;\n    }\n    return previous;\n}\n\n\n/// return true if v1-v2 edge exists\nbool has_edge( Vertex v1, Vertex v2) {\n    typedef typename std::pair<Edge, bool> EdgeBool;\n    EdgeBool result = boost::edge(v1, v2, g );\n    return result.second;\n}\n\n/// return adjacent faces to the given vertex\nFaceVector adjacent_faces( Vertex q ) {\n    typedef typename boost::graph_traits< BGLGraph >::out_edge_iterator  HEOutEdgeItr;\n    std::set<unsigned int> face_set;\n    HEOutEdgeItr itr, itr_end;\n    boost::tie( itr, itr_end) = boost::out_edges(q, g);\n    for ( ; itr!=itr_end ; ++itr ) {\n        face_set.insert( g[*itr].face );\n    }\n    FaceVector fv;\n    BOOST_FOREACH(unsigned int m, face_set) {\n        fv.push_back(m);\n    }\n    return fv;\n}\n\n/// return number of faces in graph\nunsigned int num_faces() const { \n    return faces.size(); \n}\n\n/// return number of edges in graph\nunsigned int num_edges() const { \n    return boost::num_edges( g ); \n}\n\n/// inserts given vertex into edge e, and into the twin edge e_twin\nvoid insert_vertex_in_edge(Vertex v, Edge e ) {\n    // the vertex v is in the middle of edge e\n    //                    face\n    //                    e1   e2\n    // previous-> source  -> v -> target -> next\n    //            tw_trg  <- v <- tw_src <- tw_previous\n    //                    te2  te1\n    //                    twin_face\n    \n    Edge twin = g[e].twin;\n    Vertex source = boost::source( e , g );\n    Vertex target = boost::target( e , g);\n    Vertex twin_source = boost::source( twin , g);\n    Vertex twin_target = boost::target( twin , g );\n    assert( source == twin_target );    \n    assert( target == twin_source );\n    \n    Face face = g[e].face;\n    Face twin_face = g[twin].face;\n    Edge previous = previous_edge(e);\n    assert( g[previous].face == g[e].face );\n    Edge twin_previous = previous_edge(twin);\n    assert( g[twin_previous].face == g[twin].face );\n    \n    Edge e1 = add_edge( source, v );\n    Edge e2 = add_edge( v, target );\n    \n    // preserve the left/right face link\n    g[e1].face = face;\n    g[e2].face = face;\n    // next-pointers\n    g[previous].next = e1;\n    g[e1].next = e2;\n    g[e2].next = g[e].next;\n    \n    \n    Edge te1 = add_edge( twin_source, v  );\n    Edge te2 = add_edge( v, twin_target  );\n    \n    g[te1].face = twin_face;\n    g[te2].face = twin_face;\n    \n    g[twin_previous].next = te1;\n    g[te1].next = te2;\n    g[te2].next = g[twin].next;\n    \n    // TWINNING (note indices 'cross', see ASCII art above)\n    g[e1].twin = te2;\n    g[te2].twin = e1;\n    g[e2].twin = te1;\n    g[te1].twin = e2;\n    \n    // update the faces (required here?)\n    faces[face].edge = e1;\n    faces[twin_face].edge = te1;\n    \n    // finally, remove the old edge\n    boost::remove_edge( e   , g);\n    boost::remove_edge( twin, g);\n}\n\n\n/// inserts given vertex into edge e\n/*\ntemplate <class BGLGraph>\nvoid insert_vertex_in_half_edge(typename boost::graph_traits< BGLGraph >::vertex_descriptor  v, \n                           typename boost::graph_traits< BGLGraph >::edge_descriptor e, \n                           BGLGraph& g) {\n    typedef typename boost::graph_traits< BGLGraph >::edge_descriptor    HEEdge;\n    typedef typename boost::graph_traits< BGLGraph >::vertex_descriptor  HEVertex;\n    // the vertex v is in the middle of edge e\n    //                    face\n    //                    e1   e2\n    // previous-> source  -> v -> target -> next\n    \n    HEVertex source = boost::source( e , g );\n    HEVertex target = boost::target( e , g);\n    unsigned int face = g[e].face;\n    HEEdge previous = previous_edge(e, g);\n    assert( g[previous].face == g[e].face );\n    HEEdge e1 = add_edge( source, v , g);\n    HEEdge e2 = add_edge( v, target , g);\n    // preserve the left/right face link\n    g[e1].face = face;\n    g[e2].face = face;\n    // next-pointers\n    g[previous].next = e1;\n    g[e1].next = e2;\n    g[e2].next = g[e].next;\n    // update the faces (required here?)\n    g.faces[face].edge = e1;\n    // finally, remove the old edge\n    boost::remove_edge( e   , g);\n    // NOTE: twinning is not done here, since the twin edge is not split...\n}\n\n*/\n        /// check that all edges belong to the correct face, TODO: template this to make it a useful check\n        /*\n        bool checkFaces() {\n            BOOST_FOREACH(FaceProps f, faces) {\n                BOOST_FOREACH( HEEdge e, face_edges(f.idx)) {\n                    if ( g[e].face != f.idx )\n                        return false;\n                }\n            }\n            return true;\n        }*/\n\n/// delete a vertex\nvoid delete_vertex(Vertex v) { \n    clear_vertex(v);\n    remove_vertex(v); \n}\n\n/// clear given vertex. this removes all edges connecting to the vertex.\nvoid clear_vertex( Vertex v) { \n    boost::clear_vertex( v, g ); \n}\n/// remove given vertex\nvoid remove_vertex( Vertex v) { \n    boost::remove_vertex( v , g );\n}\n\nvoid remove_edge( Vertex v1, Vertex v2) {\n    boost::remove_edge( v1, v2  , g);\n}\n\nvoid remove_edge( Edge e) {\n    boost::remove_edge( e   , g);\n}\n\n}; // end class definition\n\n\n} // end hedi namespace\n\n} // end ocl namespace\n#endif\n// end halfedgediagram.hpp\n", "meta": {"hexsha": "43e42760ee59b36128fb88df3751db484683ff45", "size": 14522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/common/halfedgediagram.hpp", "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/common/halfedgediagram.hpp", "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/common/halfedgediagram.hpp", "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": 31.6383442266, "max_line_length": 119, "alphanum_fraction": 0.6125877978, "num_tokens": 3664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930800266002904, "lm_q2_score": 0.029760091149257793, "lm_q1q2_score": 0.005931424325938979}}
{"text": "/* Copyright Singapore-MIT Alliance for Research and Technology */\n#pragma once\n\n#include <boost/shared_ptr.hpp>\n#include <map>\n#include <vector>\n#include <set>\n#include <string>\n#include \"geospatial/network/Link.hpp\"\n#include \"geospatial/network/Node.hpp\"\n#include \"geospatial/network/WayPoint.hpp\"\n\nnamespace sim_mob\n{\n\n/**\n * Class encapsulating K-shortest path algorithm as documented by Dr. Huang He\n *\n * \\author Zhang Huai Peng\n * \\author Vahid Saber Hamishagi\n * \\author Harish Loganathan\n */\nclass K_ShortestPathImpl\n{\npublic:\n    virtual ~K_ShortestPathImpl();\n\n    static boost::shared_ptr<K_ShortestPathImpl> getInstance();\n\n    /**\n     * primary operation provided by this class: Find K-Shortest Paths\n     * @param from Origin\n     * @param to Destination\n     * @param res generated paths (output param)\n     * @return number of paths found\n     *\n     * Note: naming conventions follows the Huang HE's documented algorithm.\n     */\n    int getKShortestPaths(const sim_mob::Node *from, const sim_mob::Node *to, std::vector<std::vector<sim_mob::WayPoint> > &res);\n\n    void setK(int value)\n    {\n        k = value;\n    }\n\n    int getK()\n    {\n        return k;\n    }\n\nprivate:\n    K_ShortestPathImpl();\n\n    /**\n     * Obtain the end segments of a given node, as per requirement of Yen's shortest path (mentioned in He's Algorithm)\n     * @param spurNode input node\n     * @param upLinks output\n     */\n    std::set<const Link*> getUpstreamLinks(const Node *spurNode) const;\n\n    /**\n     * Validates the intermediary results\n     * @param RootPath root path of the k-shortest path\n     * @param spurPath spur path of the k-shortest path\n     * @return true if all the validations are valid, false otherwise\n     */\n    bool validatePath(const std::vector<sim_mob::WayPoint> &rootPath, const std::vector<sim_mob::WayPoint> &spurPath);\n\n    /**\n     * number of shortest paths to generate when getKShortestPaths() function is called\n     */\n    int k;\n\n    /**\n     * store all segments in A, key=id, value=road segment\n     */\n    std::map<std::string, const sim_mob::RoadSegment*> A_Segments;\n\n    /**\n     * store all upstream links for each node\n     */\n    std::map<const Node *, std::set<const Link *> > upstreamLinksLookup;\n\n    /**\n     * static singleton instance\n     */\n    static boost::shared_ptr<K_ShortestPathImpl> instance;\n};\n\n} //end namespace sim_mob\n", "meta": {"hexsha": "fd2e718b0fc814b5e61da6b78da05058af9075eb", "size": 2384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dev/Basic/shared/geospatial/streetdir/KShortestPathImpl.hpp", "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/geospatial/streetdir/KShortestPathImpl.hpp", "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/geospatial/streetdir/KShortestPathImpl.hpp", "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": 26.1978021978, "max_line_length": 129, "alphanum_fraction": 0.6703020134, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946967146026513, "lm_q2_score": 0.028007521924369488, "lm_q1q2_score": 0.005866726415913849}}
{"text": "// Copyright (c) 2017, 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 crosses functor and function.\n\n#include <memory>  // std::unique_ptr\n\n#include <boost/geometry.hpp>\n\n#include \"sql/dd/types/spatial_reference_system.h\"  // dd::Spatial_reference_system\n#include \"sql/gis/crosses_functor.h\"\n#include \"sql/gis/difference_functor.h\"\n#include \"sql/gis/disjoint_functor.h\"\n#include \"sql/gis/gc_utils.h\"\n#include \"sql/gis/geometries.h\"\n#include \"sql/gis/geometries_traits.h\"\n#include \"sql/gis/relops.h\"\n#include \"sql/gis/within_functor.h\"\n#include \"sql/sql_exception_handler.h\"  // handle_gis_exception\n\nnamespace bg = boost::geometry;\n\nnamespace gis {\n\n/// Apply a Crosses functor to two geometries, which both may be geometry\n/// collections, and return the booelan result of the functor applied on each\n/// combination of elements in the collections.\n///\n/// @tparam GC Coordinate specific gometry collection type.\n///\n/// @param f Functor to apply.\n/// @param g1 First geometry.\n/// @param g2 Second geometry.\n///\n/// @retval true g1 crosses g2.\n/// @retval false g1 doesn't cross g2.\ntemplate <typename GC>\nstatic bool geometry_collection_apply_crosses(const Crosses &f,\n                                              const Geometry *g1,\n                                              const Geometry *g2) {\n  if (g1->type() == Geometry_type::kGeometrycollection) {\n    std::unique_ptr<Multipoint> g1_mpt;\n    std::unique_ptr<Multilinestring> g1_mls;\n    std::unique_ptr<Multipolygon> g1_mpy;\n    split_gc(down_cast<const Geometrycollection *>(g1), &g1_mpt, &g1_mls,\n             &g1_mpy);\n    if (!g1_mpy->empty()) throw null_value_exception();\n    gc_union(f.semi_major(), f.semi_minor(), &g1_mpt, &g1_mls, &g1_mpy);\n\n    if (g2->type() == Geometry_type::kGeometrycollection) {\n      std::unique_ptr<Multipoint> g2_mpt;\n      std::unique_ptr<Multilinestring> g2_mls;\n      std::unique_ptr<Multipolygon> g2_mpy;\n      split_gc(down_cast<const Geometrycollection *>(g2), &g2_mpt, &g2_mls,\n               &g2_mpy);\n      if (!g2_mpt->empty() && g2_mls->empty() && g2_mpy->empty())\n        throw null_value_exception();\n      gc_union(f.semi_major(), f.semi_minor(), &g2_mpt, &g2_mls, &g2_mpy);\n\n      // g1 and g2 must have at least one interior point in common.\n      bool shared_interior = false;\n      DBUG_ASSERT(g1_mpy->empty());  // Should have returned already.\n      if (g1->coordinate_system() == Coordinate_system::kCartesian) {\n        if (g1_mpy->empty() && !g1_mls->empty() && g2_mpy->empty() &&\n            !g2_mls->empty()) {\n          // Both g1 and g2 are of dimenision 1, so the common interior has to\n          // be of dimension 0 for g1 and g2 to cross.\n          boost::geometry::de9im::mask mask(\"0********\");\n          shared_interior = bg::relate(\n              *down_cast<Cartesian_multipoint *>(g1_mpt.get()),\n              *down_cast<Cartesian_multipoint *>(g2_mpt.get()), mask);\n          for (std::size_t i = 0;\n               i < down_cast<Cartesian_multipoint *>(g1_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Cartesian_multipoint *>(g1_mpt.get()))[i];\n            shared_interior |= bg::relate(\n                pt, *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                mask);\n          }\n          for (std::size_t i = 0;\n               i < down_cast<Cartesian_multipoint *>(g2_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Cartesian_multipoint *>(g2_mpt.get()))[i];\n            shared_interior |= bg::relate(\n                pt, *down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                mask);\n          }\n          if (bg::relate(*down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                         *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                         mask)) {\n            shared_interior = true;\n          } else {\n            boost::geometry::de9im::mask line_mask(\"1********\");\n            if (bg::relate(\n                    *down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                    *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                    line_mask)) {\n              shared_interior = false;  // Shared interior is a line.\n            }\n          }\n        } else {\n          // Either g1 or g2 are not of dimension 1. Therefore, it's enough to\n          // have some common interior, there's no requirement on the\n          // dimensionality.\n          boost::geometry::de9im::mask mask(\"T********\");\n          shared_interior = bg::relate(\n              *down_cast<Cartesian_multipoint *>(g1_mpt.get()),\n              *down_cast<Cartesian_multipoint *>(g2_mpt.get()), mask);\n          for (std::size_t i = 0;\n               i < down_cast<Cartesian_multipoint *>(g1_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Cartesian_multipoint *>(g1_mpt.get()))[i];\n            shared_interior |=\n                bg::relate(\n                    pt, *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                    mask) ||\n                bg::relate(pt,\n                           *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                           mask);\n          }\n          for (std::size_t i = 0;\n               i < down_cast<Cartesian_multipoint *>(g2_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Cartesian_multipoint *>(g2_mpt.get()))[i];\n            shared_interior |= bg::relate(\n                pt, *down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                mask);\n          }\n          shared_interior |=\n              bg::relate(*down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                         *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                         mask) ||\n              bg::relate(*down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                         *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                         mask);\n        }\n      } else {\n        DBUG_ASSERT(g1->coordinate_system() == Coordinate_system::kGeographic);\n        if (g1_mpy->empty() && !g1_mls->empty() && g2_mpy->empty() &&\n            !g2_mls->empty()) {\n          // Both g1 and g2 are of dimenision 1, so the common interior has to\n          // be of dimension 0 for g1 and g2 to cross.\n          boost::geometry::de9im::mask mask(\"0********\");\n          shared_interior = bg::relate(\n              *down_cast<Geographic_multipoint *>(g1_mpt.get()),\n              *down_cast<Geographic_multipoint *>(g2_mpt.get()), mask);\n          for (std::size_t i = 0;\n               i < down_cast<Geographic_multipoint *>(g1_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Geographic_multipoint *>(g1_mpt.get()))[i];\n            shared_interior |= bg::relate(\n                pt, *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                mask);\n          }\n          for (std::size_t i = 0;\n               i < down_cast<Geographic_multipoint *>(g2_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Geographic_multipoint *>(g2_mpt.get()))[i];\n            shared_interior |= bg::relate(\n                pt, *down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                mask);\n          }\n          if (bg::relate(*down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                         *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                         mask)) {\n            shared_interior = true;\n          } else {\n            boost::geometry::de9im::mask line_mask(\"1********\");\n            if (bg::relate(\n                    *down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                    *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                    line_mask)) {\n              shared_interior = false;  // Shared interior is a line.\n            }\n          }\n        } else {\n          // Either g1 or g2 are not of dimension 1. Therefore, it's enough to\n          // have some common interior, there's no requirement on the\n          // dimensionality.\n          boost::geometry::de9im::mask mask(\"T********\");\n          boost::geometry::strategy::within::geographic_winding<\n              Geographic_point>\n              geographic_pl_pa_strategy(\n                  bg::srs::spheroid<double>(f.semi_major(), f.semi_minor()));\n          boost::geometry::strategy::intersection::geographic_segments<>\n              geographic_ll_la_aa_strategy(\n                  bg::srs::spheroid<double>(f.semi_major(), f.semi_minor()));\n\n          shared_interior = bg::relate(\n              *down_cast<Geographic_multipoint *>(g1_mpt.get()),\n              *down_cast<Geographic_multipoint *>(g2_mpt.get()), mask);\n          for (std::size_t i = 0;\n               i < down_cast<Geographic_multipoint *>(g1_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Geographic_multipoint *>(g1_mpt.get()))[i];\n            shared_interior |=\n                bg::relate(\n                    pt, *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                    mask, geographic_pl_pa_strategy) ||\n                bg::relate(pt,\n                           *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                           mask, geographic_pl_pa_strategy);\n          }\n          for (std::size_t i = 0;\n               i < down_cast<Geographic_multipoint *>(g2_mpt.get())->size();\n               i++) {\n            auto &pt = (*down_cast<Geographic_multipoint *>(g2_mpt.get()))[i];\n            shared_interior |= bg::relate(\n                pt, *down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                mask, geographic_pl_pa_strategy);\n          }\n          shared_interior |=\n              bg::relate(*down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                         *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                         mask, geographic_ll_la_aa_strategy) ||\n              bg::relate(*down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                         *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                         mask, geographic_ll_la_aa_strategy);\n        }\n      }\n\n      if (!shared_interior) return false;\n\n      // At least one point of g1 must be in g2's exterior.\n      std::unique_ptr<Multipoint> mpt_diff;\n      Difference d(f.semi_major(), f.semi_minor());\n      mpt_diff.reset(down_cast<Multipoint *>(d(g1_mpt.get(), g2_mpt.get())));\n      mpt_diff.reset(down_cast<Multipoint *>(d(mpt_diff.get(), g2_mls.get())));\n      mpt_diff.reset(down_cast<Multipoint *>(d(mpt_diff.get(), g2_mpy.get())));\n      if (mpt_diff->size() > 0) return true;\n      std::unique_ptr<Multilinestring> mls_diff;\n      mls_diff.reset(\n          down_cast<Multilinestring *>(d(g1_mls.get(), g2_mls.get())));\n      mls_diff.reset(\n          down_cast<Multilinestring *>(d(mls_diff.get(), g2_mpy.get())));\n      return (mls_diff->size() > 0);\n    } else {\n      if (g1->coordinate_system() == Coordinate_system::kCartesian) {\n        Cartesian_geometrycollection gc;\n        gc.push_back(*g2);\n        return geometry_collection_apply_crosses<Cartesian_geometrycollection>(\n            f, g1, &gc);\n      } else {\n        DBUG_ASSERT(g1->coordinate_system() == Coordinate_system::kGeographic);\n        Geographic_geometrycollection gc;\n        gc.push_back(*g2);\n        return geometry_collection_apply_crosses<Geographic_geometrycollection>(\n            f, g1, &gc);\n      }\n    }\n  } else {\n    if (g2->type() == Geometry_type::kGeometrycollection) {\n      if (g1->coordinate_system() == Coordinate_system::kCartesian) {\n        Cartesian_geometrycollection gc;\n        gc.push_back(*g1);\n        return geometry_collection_apply_crosses<Cartesian_geometrycollection>(\n            f, &gc, g2);\n      } else {\n        DBUG_ASSERT(g1->coordinate_system() == Coordinate_system::kGeographic);\n        Geographic_geometrycollection gc;\n        gc.push_back(*g1);\n        return geometry_collection_apply_crosses<Geographic_geometrycollection>(\n            f, &gc, g2);\n      }\n    } else {\n      return f(g1, g2);\n    }\n  }\n}\n\nCrosses::Crosses(double semi_major, double semi_minor)\n    : m_semi_major(semi_major),\n      m_semi_minor(semi_minor),\n      m_geographic_pl_pa_strategy(\n          bg::srs::spheroid<double>(semi_major, semi_minor)),\n      m_geographic_ll_la_aa_strategy(\n          bg::srs::spheroid<double>(semi_major, semi_minor)) {}\n\nbool Crosses::operator()(const Geometry *g1, const Geometry *g2) const {\n  return apply(*this, g1, g2);\n}\n\nbool Crosses::eval(const Geometry *g1, const Geometry *g2) const {\n  // All parameter type combinations have been implemented.\n  DBUG_ASSERT(false);\n  throw not_implemented_exception::for_non_projected(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Cartesian_point, *)\n\nbool Crosses::eval(const Cartesian_point *, const Cartesian_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_point *,\n                   const Cartesian_linestring *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\nbool Crosses::eval(const Cartesian_point *, const Cartesian_polygon *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\nbool Crosses::eval(const Cartesian_point *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  // Must be evaluated in case g2 contains a single point.\n  return geometry_collection_apply_crosses<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Cartesian_point *,\n                   const Cartesian_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_point *,\n                   const Cartesian_multilinestring *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\nbool Crosses::eval(const Cartesian_point *,\n                   const Cartesian_multipolygon *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Cartesian_linestring, *)\n\nbool Crosses::eval(const Cartesian_linestring *,\n                   const Cartesian_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_linestring *g1,\n                   const Cartesian_linestring *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\nbool Crosses::eval(const Cartesian_linestring *g1,\n                   const Cartesian_polygon *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\nbool Crosses::eval(const Cartesian_linestring *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_crosses<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Cartesian_linestring *,\n                   const Cartesian_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_linestring *g1,\n                   const Cartesian_multilinestring *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\nbool Crosses::eval(const Cartesian_linestring *g1,\n                   const Cartesian_multipolygon *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Cartesian_polygon, *)\n\nbool Crosses::eval(const Cartesian_polygon *, const Geometry *) const {\n  // If g1 is a 2d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Cartesian_geometrycollection, *)\n\nbool Crosses::eval(const Cartesian_geometrycollection *g1,\n                   const Geometry *g2) const {\n  return geometry_collection_apply_crosses<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Cartesian_multipoint, *)\n\nbool Crosses::eval(const Cartesian_multipoint *,\n                   const Cartesian_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_linestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\nbool Crosses::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_polygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\nbool Crosses::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_crosses<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Cartesian_multipoint *,\n                   const Cartesian_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_multilinestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\nbool Crosses::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_multipolygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Cartesian_multilinestring, *)\n\nbool Crosses::eval(const Cartesian_multilinestring *,\n                   const Cartesian_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_linestring *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\nbool Crosses::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_polygon *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\nbool Crosses::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_crosses<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Cartesian_multilinestring *,\n                   const Cartesian_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_multilinestring *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\nbool Crosses::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_multipolygon *g2) const {\n  return bg::crosses(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Cartesian_multipolygon, *)\n\nbool Crosses::eval(const Cartesian_multipolygon *, const Geometry *) const {\n  // If g1 is a 2d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Geographic_point, *)\n\nbool Crosses::eval(const Geographic_point *, const Geographic_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_point *,\n                   const Geographic_linestring *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\nbool Crosses::eval(const Geographic_point *, const Geographic_polygon *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\nbool Crosses::eval(const Geographic_point *g1,\n                   const Geographic_geometrycollection *g2) const {\n  // Must be evaluated in case g2 contains a single point.\n  return geometry_collection_apply_crosses<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Geographic_point *,\n                   const Geographic_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_point *,\n                   const Geographic_multilinestring *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\nbool Crosses::eval(const Geographic_point *,\n                   const Geographic_multipolygon *) const {\n  // A point may never cross another geometry.\n  return false;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Geographic_linestring, *)\n\nbool Crosses::eval(const Geographic_linestring *,\n                   const Geographic_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_linestring *g1,\n                   const Geographic_linestring *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Crosses::eval(const Geographic_linestring *g1,\n                   const Geographic_polygon *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Crosses::eval(const Geographic_linestring *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_crosses<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Geographic_linestring *,\n                   const Geographic_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_linestring *g1,\n                   const Geographic_multilinestring *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Crosses::eval(const Geographic_linestring *g1,\n                   const Geographic_multipolygon *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Geographic_polygon, *)\n\nbool Crosses::eval(const Geographic_polygon *, const Geometry *) const {\n  // If g1 is a 2d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Geographic_geometrycollection, *)\n\nbool Crosses::eval(const Geographic_geometrycollection *g1,\n                   const Geometry *g2) const {\n  return geometry_collection_apply_crosses<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Geographic_multipoint, *)\n\nbool Crosses::eval(const Geographic_multipoint *,\n                   const Geographic_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_multipoint *g1,\n                   const Geographic_linestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\nbool Crosses::eval(const Geographic_multipoint *g1,\n                   const Geographic_polygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\nbool Crosses::eval(const Geographic_multipoint *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_crosses<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Geographic_multipoint *,\n                   const Geographic_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_multipoint *g1,\n                   const Geographic_multilinestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\nbool Crosses::eval(const Geographic_multipoint *g1,\n                   const Geographic_multipolygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  Disjoint disjoint(m_semi_major, m_semi_minor);\n  bool found_within = false;\n  bool found_disjoint = false;\n\n  // At least one point in g1 has to be within g2, and at least one point in\n  // g1\n  // has to be disjoint from g2.\n  for (auto &pt : *g1) {\n    bool pt_disjoint = false;\n    if (!found_disjoint) {\n      pt_disjoint = disjoint(&pt, g2);\n      found_disjoint = pt_disjoint;\n    }\n    if (!pt_disjoint && !found_within) {\n      found_within = within(&pt, g2);\n    }\n    if (found_disjoint && found_within) break;\n  }\n\n  return found_disjoint && found_within;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Geographic_multilinestring, *)\n\nbool Crosses::eval(const Geographic_multilinestring *,\n                   const Geographic_point *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_multilinestring *g1,\n                   const Geographic_linestring *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Crosses::eval(const Geographic_multilinestring *g1,\n                   const Geographic_polygon *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Crosses::eval(const Geographic_multilinestring *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_crosses<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Crosses::eval(const Geographic_multilinestring *,\n                   const Geographic_multipoint *) const {\n  // If g2 is a 0d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\nbool Crosses::eval(const Geographic_multilinestring *g1,\n                   const Geographic_multilinestring *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Crosses::eval(const Geographic_multilinestring *g1,\n                   const Geographic_multipolygon *g2) const {\n  return bg::crosses(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// crosses(Geographic_multipolygon, *)\n\nbool Crosses::eval(const Geographic_multipolygon *, const Geometry *) const {\n  // If g1 is a 2d geometry, return NULL (SQL/MM 2015, Sect. 5.1.51).\n  throw null_value_exception();\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\nbool crosses(const dd::Spatial_reference_system *srs, const Geometry *g1,\n             const Geometry *g2, const char *func_name, bool *crosses,\n             bool *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 ((*null = (g1->is_empty() || g2->is_empty()))) return false;\n\n    Crosses crosses_func(srs ? srs->semi_major_axis() : 0.0,\n                         srs ? srs->semi_minor_axis() : 0.0);\n    *crosses = crosses_func(g1, g2);\n  } catch (const null_value_exception &) {\n    *null = true;\n    return false;\n  } catch (...) {\n    handle_gis_exception(func_name);\n    return true;\n  }\n\n  return false;\n}\n\n}  // namespace gis\n", "meta": {"hexsha": "26d75b869b2c450999298a07623fb55e2b6ea368", "size": 32757, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mysql-server/sql/gis/crosses.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/crosses.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/crosses.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": 36.4777282851, "max_line_length": 83, "alphanum_fraction": 0.6118997466, "num_tokens": 8045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111972642778714, "lm_q2_score": 0.017712299383966186, "lm_q1q2_score": 0.005864891726425946}}
{"text": "\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <cstring>\n#include <getopt.h>\n\nusing namespace std;\n\n#include \"rate_model.h\"\n#include \"tree.h\"\n#include \"tree_reader.h\"\n#include \"state_reconstructor_simple.h\"\n#include \"seq_reader.h\"\n#include \"sequence.h\"\n#include \"seq_utils.h\"\n#include \"utils.h\"\n#include \"mcmc.h\"\n#include \"log.h\"\n\n#include <armadillo>\nusing namespace arma;\n\nvoid print_help() {\n    cout << \"Calculate Selection Model 0 with K and w with seqs and tree.\" << endl;\n    cout << \"Can read from stdin or file.\" << endl;\n    cout << endl;\n    cout << \"Usage: pxsm2a [OPTION]... [FILE]...\" << endl;\n    cout << endl;\n    cout << \" -s, --seqf=FILE     input sequence file\" << endl;\n    cout << \" -t, --treef=FILE    input tree file\" << endl;\n    cout << \" -o, --outf=FILE     output sequence file, stout otherwise\" << endl;\n    cout << \" -h, --help          display this help and exit\" << endl;\n    cout << \" -V, --version       display version and exit\" << endl;\n    cout << endl;\n    cout << \"Report bugs to: <https://github.com/FePhyFoFum/phyx/issues>\" << endl;\n    cout << \"phyx home page: <https://github.com/FePhyFoFum/phyx>\" << endl;\n}\n\nstring versionline(\"pxsm2a 0.1\\nCopyright (C) 2014 FePhyFoFum\\nLicense GPLv3\\nwritten by Stephen A. Smith (blackrim)\");\n\nstatic struct option const long_options[] =\n{\n    {\"seqf\", required_argument, NULL, 's'},\n    {\"treef\", required_argument, NULL, 't'},\n    {\"outf\", required_argument, NULL, 'o'},\n    {\"help\", no_argument, NULL, 'h'},\n    {\"version\", no_argument, NULL, 'V'},\n    {NULL, 0, NULL, 0}\n};\n\nint main(int argc, char * argv[]) {\n    \n    log_call(argc, argv);\n    \n    bool sfileset = false;\n    bool tfileset = false;\n    bool outfileset = false;\n    char * seqf = NULL;\n    char * treef = NULL;\n    char * outf = NULL;\n    while (1) {\n        int oi = -1;\n        int c = getopt_long(argc, argv, \"s:t:o:hV\", long_options, &oi);\n        if (c == -1) {\n            break;\n        }\n        switch(c) {\n            case 's':\n                sfileset = true;\n                seqf = strdup(optarg);\n                check_file_exists(seqf);\n                break;\n            case 't':\n                tfileset = true;\n                treef = strdup(optarg);\n                check_file_exists(treef);\n                break;\n            case 'o':\n                outfileset = true;\n                outf = strdup(optarg);\n                break;\n            case 'h':\n                print_help();\n                exit(0);\n            case 'V':\n                cout << versionline << endl;\n                exit(0);\n            default:\n                print_error(argv[0], (char)c);\n                exit(0);\n        }\n    }\n    istream * spios = NULL;\n    istream * tpios = NULL;\n    ostream * poos = NULL;\n    ifstream * sfstr = NULL;\n    ifstream * tfstr = NULL;\n    ofstream * ofstr = NULL;\n    \n    if (sfileset == true) {\n        sfstr = new ifstream(seqf);\n        spios = sfstr;\n    }\n    if (tfileset == true) {\n        tfstr = new ifstream(treef);\n        tpios = tfstr;\n    }\n    if (tfileset == false || sfileset == false) {\n        cout << \"you have to set the tree and seq files\" << endl;\n        exit(0);\n    }\n    if (outfileset == true) {\n        ofstr = new ofstream(outf);\n        poos = ofstr;\n    } else {\n        poos = &cout;\n    }\n    //read seqs\n    vector<Sequence> seqs;\n    vector<Sequence> sr_seqs;\n    Sequence seq;\n    string retstring;\n    int ft = test_seq_filetype_stream(*spios,retstring);\n    while (read_next_seq_from_stream(*spios,ft,retstring,seq)) {\n        (*poos) << seq.get_fasta();\n        seqs.push_back(seq);\n        Sequence tseq(seq.get_id(),\"\");\n        sr_seqs.push_back(tseq);\n    }\n    if (ft == 2) {\n        (*poos) << seq.get_fasta();\n        seqs.push_back(seq);\n        Sequence tseq(seq.get_id(),\"\");\n        sr_seqs.push_back(tseq);\n    }\n    \n    //read trees \n    ft = test_tree_filetype_stream(*tpios, retstring);\n    if (ft != 1) {\n        cerr << \"this really only works with newick\" << endl;\n        exit(0);\n    }\n    bool going = true;\n    Tree * tree;\n    if (ft == 1) {\n        while (going) {\n            tree = read_next_tree_from_stream_newick(*tpios, retstring, &going);\n            break;\n        }\n    }\n\n    map<string,string> codon_dict;\n    vector<string> codon_list;\n    map<string,vector<int> > codon_pos;\n    populate_codon_list(&codon_list);\n    populate_map_codon_dict(&codon_dict);\n    populate_map_codon_indices(&codon_pos);\n\n    mat bf(61,61);\n    mat K(61,61);\n    mat w(61,61);\n    mat inq0(61,61);\n    mat inq1(61,61);\n    mat inq2(61,61);\n    generate_bigpibf_K_w(&bf,&K,&w,codon_dict,codon_pos,codon_list);\n    update_simple_goldman_yang_q(&inq0,1.36714,0.001,bf,K,w);\n    update_simple_goldman_yang_q(&inq1,1.36714,1.0,bf,K,w);\n    update_simple_goldman_yang_q(&inq2,1.36714,8.21486,bf,K,w);\n//    cout << inq << endl;\n\n    RateModel rm(61);\n    rm.selection_model = 2;\n    rm.set_n_qs(3);\n    rm.set_Q_which(inq0,0);\n    rm.set_Q_which(inq1,1);\n    rm.set_Q_which(inq2,2);\n    //rm.set_Q(inq);\n//    cout << rm.get_Q() << endl;\n    int sites = (seqs[0].get_sequence().size()/3);\n    StateReconstructorSimple sr(rm,sites);\n    sr.set_tree(tree);\n    cout << \"there are \" << sites << \" sites\" << endl;\n    sm2a_mcmc(0,10,tree,sr,rm,seqs,sr_seqs,codon_pos,bf,K,w,inq0,inq1,inq2);\n    \n    sfstr->close();\n    delete spios;\n    tfstr->close();\n    delete tpios;\n\n    if (outfileset) {\n        ofstr->close();\n        delete poos;\n    }\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "988d6edac38f0e47e4eab90c6ecbfbef1bbec351", "size": 5546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/main_sm2a.cpp", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/main_sm2a.cpp", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/main_sm2a.cpp", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 28.0101010101, "max_line_length": 119, "alphanum_fraction": 0.5542733502, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082131381216084, "lm_q2_score": 0.018264274978606686, "lm_q1q2_score": 0.005859568694463173}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2020 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014-2017 by Centre for Geoscience Computing (GeoComp)\n* Development from 2019 by School of Earth and Environmental Sciences\n**\n*****************************************************************************/\n\n#include \"SolverOptions.h\"\n#include \"EsysException.h\"\n\n#include <boost/python.hpp>\n\n#ifdef ESYS_HAVE_TRILINOS\n#include <Amesos2.hpp>\n#endif\n\nnamespace bp = boost::python;\n\ntemplate <class R>\nbool convert(bp::object bpo, R& result)\n{\n    bool b = bp::extract<R>(bpo).check();\n    if (b)\n        result = bp::extract<R>(bpo);\n    return b;\n}\n\nnamespace escript {\n\nSolverBuddy::SolverBuddy() :\n    target(SO_TARGET_CPU),\n    package(SO_DEFAULT),\n    method(SO_DEFAULT),\n    preconditioner(SO_PRECONDITIONER_JACOBI),\n    ode_solver(SO_ODESOLVER_LINEAR_CRANK_NICOLSON),\n    reordering(SO_REORDERING_DEFAULT),\n    sweeps(1),\n    tolerance(1e-8),\n    absolute_tolerance(0.),\n    inner_tolerance(0.9),\n    drop_tolerance(0.0005),\n    drop_storage(2.),\n    iter_max(100000),\n    inner_iter_max(10),\n    truncation(20),\n    restart(0),\n    is_complex(false),\n    symmetric(false),\n    hermitian(false),\n    verbose(false),\n    adapt_inner_tolerance(true),\n    accept_convergence_failure(false),\n    relaxation(0.3),\n    use_local_preconditioner(false),\n    refinements(2),\n    dim(2),\n    using_default_solver_method(false)\n{\n    // setPackage(SO_DEFAULT);\n    // setSolverMethod(SO_DEFAULT);\n    resetDiagnostics(true);\n}\n\nSolverBuddy::~SolverBuddy()\n{\n}\n\n\nstd::string SolverBuddy::getSummary() const\n{\n    std::stringstream out;\n    out << \"Solver Package = \" << getName(getPackage()) << std::endl\n        << \"Verbosity = \" << isVerbose() << std::endl\n        << \"Accept failed convergence = \" << acceptConvergenceFailure() << std::endl\n        << \"Relative tolerance = \" << getTolerance() << std::endl\n        << \"Absolute tolerance = \" << getAbsoluteTolerance() << std::endl\n        << \"Symmetric problem = \" << isSymmetric() << std::endl\n        << \"Hermitian problem = \" << isHermitian() << std::endl\n        << \"Maximum number of iteration steps = \" << getIterMax() << std::endl\n        << \"Inner tolerance = \" << getInnerTolerance() << std::endl\n        << \"Adapt innner tolerance = \" << adaptInnerTolerance() << std::endl;\n\n    if (getPackage() == SO_DEFAULT || getPackage() == SO_PACKAGE_PASO ||\n            getPackage() == SO_PACKAGE_TRILINOS) {\n        out << \"Solver method = \" << getName(getSolverMethod()) << std::endl;\n        if (getSolverMethod() == SO_METHOD_GMRES) {\n            out << \"Truncation  = \" << getTruncation() << std::endl\n                << \"Restart  = \" << getRestart() << std::endl;\n        }\n        out << \"Preconditioner = \" << getName(getPreconditioner()) << std::endl\n            << \"Apply preconditioner locally = \" << useLocalPreconditioner()\n            << std::endl;\n        switch (getPreconditioner()) {\n            case SO_PRECONDITIONER_GAUSS_SEIDEL:\n                out << \"Number of sweeps = \" << getNumSweeps() << std::endl;\n                break;\n            case SO_PRECONDITIONER_ILUT:\n                out << \"Drop tolerance = \" << getDropTolerance() << std::endl;\n                out << \"Storage increase = \" << getDropStorage() << std::endl;\n                break;\n            case SO_PRECONDITIONER_RILU:\n                out << \"Relaxation factor = \" << getRelaxationFactor()\n                    << std::endl;\n                break;\n            default:\n                break;\n        } // preconditioner switch\n        out << \"ODE solver = \" << getName(getODESolver()) << std::endl;\n    }\n    return out.str();\n}\n\nconst char* SolverBuddy::getName(int key) const\n{\n    switch (static_cast<SolverOptions>(key)) {\n        case SO_DEFAULT: return \"DEFAULT\";\n        case SO_TARGET_CPU: return \"CPU\";\n        case SO_TARGET_GPU: return \"GPU\";\n\n        case SO_PACKAGE_MKL: return \"MKL\";\n        case SO_PACKAGE_PASO: return \"PASO\";\n        case SO_PACKAGE_TRILINOS: return \"TRILINOS\";\n        case SO_PACKAGE_UMFPACK: return \"UMFPACK\";\n        case SO_PACKAGE_MUMPS: return \"MUMPS\";\n\n        case SO_METHOD_BICGSTAB: return \"BICGSTAB\";\n        case SO_METHOD_CGLS: return \"CGLS\";\n        case SO_METHOD_CGS: return \"CGS\";\n        case SO_METHOD_CHOLEVSKY: return \"CHOLEVSKY\";\n        case SO_METHOD_CR: return \"CR\";\n        case SO_METHOD_DIRECT: return \"DIRECT\";\n        case SO_METHOD_DIRECT_MUMPS: return \"DIRECT_MUMPS\";\n        case SO_METHOD_DIRECT_PARDISO: return \"DIRECT_PARDISO\";\n        case SO_METHOD_DIRECT_SUPERLU: return \"DIRECT_SUPERLU\";\n        case SO_METHOD_DIRECT_TRILINOS: return \"DIRECT_TRILINOS\";\n        case SO_METHOD_GMRES: return \"GMRES\";\n        case SO_METHOD_HRZ_LUMPING: return \"HRZ_LUMPING\";\n        case SO_METHOD_ITERATIVE: return \"ITERATIVE\";\n        case SO_METHOD_LSQR: return \"LSQR\";\n        case SO_METHOD_MINRES: return \"MINRES\";\n        case SO_METHOD_NONLINEAR_GMRES: return \"NONLINEAR_GMRES\";\n        case SO_METHOD_PCG: return \"PCG\";\n        case SO_METHOD_PRES20: return \"PRES20\";\n        case SO_METHOD_ROWSUM_LUMPING: return \"ROWSUM_LUMPING\";\n        case SO_METHOD_TFQMR: return \"TFQMR\";\n\n        case SO_PRECONDITIONER_AMG: return \"AMG\";\n        case SO_PRECONDITIONER_GAUSS_SEIDEL: return \"GAUSS_SEIDEL\";\n        case SO_PRECONDITIONER_ILU0: return \"ILU0\";\n        case SO_PRECONDITIONER_ILUT: return \"ILUT\";\n        case SO_PRECONDITIONER_JACOBI: return \"JACOBI\";\n        case SO_PRECONDITIONER_NONE: return \"NO_PRECONDITIONER\";\n        case SO_PRECONDITIONER_REC_ILU: return \"REC_ILU\";\n        case SO_PRECONDITIONER_RILU: return \"RILU\";\n\n        case SO_ODESOLVER_BACKWARD_EULER: return \"BACKWARD_EULER\";\n        case SO_ODESOLVER_CRANK_NICOLSON: return \"CRANK_NICOLSON\";\n        case SO_ODESOLVER_LINEAR_CRANK_NICOLSON: return \"LINEAR_CRANK_NICOLSON\";\n\n        case SO_INTERPOLATION_CLASSIC: return \"CLASSIC_INTERPOLATION\";\n        case SO_INTERPOLATION_CLASSIC_WITH_FF_COUPLING:\n            return \"CLASSIC_INTERPOLATION_WITH_FF\";\n        case SO_INTERPOLATION_DIRECT: return \"DIRECT_INTERPOLATION\";\n\n\n        case SO_REORDERING_DEFAULT: return \"DEFAULT_REORDERING\";\n        case SO_REORDERING_MINIMUM_FILL_IN: return \"MINIMUM_FILL_IN\";\n        case SO_REORDERING_NESTED_DISSECTION: return \"NESTED_DISSECTION\";\n        case SO_REORDERING_NONE: return \"NO_REORDERING\";\n        default:\n            throw ValueError(\"getName() invalid option given\");\n    }\n    return \"invalid option\";\n}\n\nvoid SolverBuddy::resetDiagnostics(bool all)\n{\n    num_iter = 0;\n    num_level = 0;\n    num_inner_iter = 0;\n    time = 0.;\n    set_up_time = 0.;\n    net_time = 0.;\n    residual_norm = 0.;\n    converged = false;\n    preconditioner_size = -1;\n    time_step_backtracking_used = false;\n    coarse_level_sparsity = 0;\n    num_coarse_unknowns = 0;\n    if (all) {\n        cum_num_inner_iter = 0;\n        cum_num_iter = 0;\n        cum_time = 0.;\n        cum_set_up_time = 0.;\n        cum_net_time = 0.;\n    }\n}\n\nvoid SolverBuddy::updateDiagnostics(const std::string& name, bool value)\n{\n    if (name == \"converged\") {\n        converged = value;\n    } else if (name == \"time_step_backtracking_used\") {\n        time_step_backtracking_used = value;\n    } else {\n        throw ValueError(std::string(\"Unknown diagnostic: \") + name);\n    }\n}\n\nvoid SolverBuddy::updateDiagnostics(const std::string& name, int value)\n{\n    if (name == \"num_iter\") {\n        cum_num_iter += num_iter = value;\n    } else if (name == \"num_level\") {\n        num_level = value;\n    } else if (name == \"num_inner_iter\") {\n        cum_num_inner_iter += num_inner_iter = value;\n    } else if (name == \"num_coarse_unknowns\") {\n        num_coarse_unknowns = value;\n    } else {\n        throw ValueError(std::string(\"Unknown diagnostic: \") + name);\n    }\n}\n\nvoid SolverBuddy::updateDiagnostics(const std::string& name, double value)\n{\n    if (name == \"time\") {\n        cum_time += time = value;\n    } else if (name == \"set_up_time\") {\n        cum_set_up_time += set_up_time = value;\n    } else if (name == \"net_time\") {\n        cum_net_time += net_time = value;\n    } else if (name == \"residual_norm\") {\n        residual_norm = value;\n    } else if (name == \"coarse_level_sparsity\") {\n        coarse_level_sparsity = value;\n    } else {\n        throw ValueError(std::string(\"Unknown diagnostic: \") + name);\n    }\n}\n\nvoid SolverBuddy::updateDiagnosticsPy(const std::string& name,\n                                      const bp::object& value)\n{\n    int i=0;\n    double d=0; // to keep older compilers happy\n    bool b=false;\n    bool ib = convert<int>(value, i);\n    bool db = convert<double>(value, d);\n    bool bb = convert<bool>(value, b);\n\n    if (name == \"num_iter\") {\n        if (!ib)\n            throw ValueError(\"setting num_iter to non-int value\");\n        cum_num_iter += num_iter = i;\n    } else if (name == \"num_level\") {\n        if (!ib)\n            throw ValueError(\"setting num_level to non-int value\");\n        num_level = i;\n    } else if (name == \"num_inner_iter\") {\n        if (!ib)\n            throw ValueError(\"setting num_inner_iter to non-int value\");\n        cum_num_inner_iter += num_inner_iter = i;\n    } else if (name == \"time\") {\n        if (!db)\n            throw ValueError(\"setting time to non-double value\");\n        cum_time += time = d;\n    } else if (name == \"set_up_time\") {\n        if (!db)\n            throw ValueError(\"setting set_up_time to non-double value\");\n        cum_set_up_time += set_up_time = d;\n    } else if (name == \"net_time\") {\n        if (!db)\n            throw ValueError(\"setting net_time to non-double value\");\n        cum_net_time += net_time = d;\n    } else if (name == \"residual_norm\") {\n        if (!db)\n            throw ValueError(\"setting residual_norm to non-double value\");\n        residual_norm = d;\n    } else if (name == \"converged\") {\n        if (!bb)\n            throw ValueError(\"setting converged to non-bool value\");\n        converged = b;\n    } else if (name == \"time_step_backtracking_used\") {\n        if (!bb)\n            throw ValueError(\"setting time_step_backtracking_used to non-bool value\");\n        time_step_backtracking_used = b;\n    } else if (name == \"coarse_level_sparsity\") {\n        if (!db)\n            throw ValueError(\"setting coarse_level_sparsity to non-double value\");\n        coarse_level_sparsity = d;\n    } else if (name == \"num_coarse_unknowns\") {\n        if (!ib)\n            throw ValueError(\"setting num_coarse_unknowns to non-int value\");\n        num_coarse_unknowns = i;\n    } else {\n        throw ValueError(std::string(\"Unknown diagnostic: \") + name);\n    }\n}\n\ndouble SolverBuddy::getDiagnostics(const std::string name) const\n{\n    if (name == \"num_iter\") return num_iter;\n    else if (name == \"cum_num_iter\") return cum_num_iter;\n    else if (name == \"num_inner_iter\") return num_inner_iter;\n    else if (name == \"cum_num_inner_iter\") return cum_num_inner_iter;\n    else if (name == \"time\") return time;\n    else if (name == \"cum_time\") return cum_time;\n    else if (name == \"set_up_time\") return set_up_time;\n    else if (name == \"cum_set_up_time\") return cum_set_up_time;\n    else if (name == \"net_time\") return net_time;\n    else if (name == \"cum_net_time\") return cum_net_time;\n    else if (name == \"residual_norm\") return residual_norm;\n    else if (name == \"converged\") return converged;\n    else if (name == \"preconditioner_size\") return preconditioner_size;\n    else if (name == \"time_step_backtracking_used\")\n        return  time_step_backtracking_used;\n    throw ValueError(std::string(\"unknown diagnostic item: \") + name);\n}\n\nbool SolverBuddy::hasConverged() const\n{\n    return converged;\n}\n\nvoid SolverBuddy::setPreconditioner(int precon)\n{\n    SolverOptions preconditioner = static_cast<SolverOptions>(precon);\n    switch(preconditioner) {\n        case SO_PRECONDITIONER_AMG:\n#if !defined(ESYS_HAVE_TRILINOS) && !defined(ESYS_HAVE_MUMPS)\n        throw ValueError(\"escript was not compiled with Trilinos or MUMPS enabled\");\n#endif\n        case SO_PRECONDITIONER_GAUSS_SEIDEL:\n        case SO_PRECONDITIONER_JACOBI: // This is the default preconditioner in ifpack2\n        case SO_PRECONDITIONER_ILU0:\n        case SO_PRECONDITIONER_ILUT:\n        case SO_PRECONDITIONER_NONE:\n        case SO_PRECONDITIONER_REC_ILU:\n        case SO_PRECONDITIONER_RILU:\n            this->preconditioner = preconditioner;\n            break;\n        default:\n            throw ValueError(\"unknown preconditioner\");\n    }\n}\n\nSolverOptions SolverBuddy::getPreconditioner() const\n{\n    return preconditioner;\n}\n\nvoid SolverBuddy::setSolverMethod(int method)\n{\n    SolverOptions meth = static_cast<SolverOptions>(method);\n\n//     bool havePASODirect = false;\n//     using_default_solver_method=false;\n// #if defined(ESYS_HAVE_PASO) && (defined(ESYS_HAVE_MKL) || defined(ESYS_HAVE_UMFPACK) || defined(ESYS_HAVE_MUMPS))\n//     havePASODirect = true;\n// #endif\n\n    switch(meth) {\n        case SO_DEFAULT:\n        case SO_METHOD_ITERATIVE:\n        case SO_METHOD_BICGSTAB:\n        case SO_METHOD_CGLS:\n        case SO_METHOD_CGS:\n        case SO_METHOD_CHOLEVSKY:\n        case SO_METHOD_CR:\n        case SO_METHOD_GMRES:\n        case SO_METHOD_HRZ_LUMPING:\n        case SO_METHOD_LSQR:\n        case SO_METHOD_MINRES:\n        case SO_METHOD_NONLINEAR_GMRES:\n        case SO_METHOD_PCG:\n        case SO_METHOD_PRES20:\n        case SO_METHOD_ROWSUM_LUMPING:\n        case SO_METHOD_TFQMR:\n            this->method = meth;\n            break;\n        case SO_METHOD_DIRECT:\n#if defined(ESYS_HAVE_UMFPACK) || defined(ESYS_HAVE_TRILINOS) || defined(ESYS_HAVE_MKL) || defined(ESYS_HAVE_MUMPS)\n#ifdef ESYS_HAVE_TRILINOS\n            // translate specific direct solver setting to generic one for PASO\n            this->method = meth;\n#else\n            this->method = SO_METHOD_DIRECT;\n#endif\n            break;\n#else\n            throw ValueError(\"Cannot use DIRECT solver method, the running \"\n                    \"escript was not compiled with a direct solver enabled\");\n#endif\n        case SO_METHOD_DIRECT_TRILINOS:\n#ifdef ESYS_HAVE_TRILINOS\n            this->method = meth;\n            break;\n#else\n            throw ValueError(\"escript was not compiled with Trilinos\");\n#endif\n        case SO_METHOD_DIRECT_MUMPS:\n#ifdef ESYS_HAVE_MUMPS\n            this->method=meth;\n#else\n            throw ValueError(\"escript was not compiled with MUMPS\");\n#endif\n        case SO_METHOD_DIRECT_PARDISO:\n#ifdef ESYS_HAVE_TRILINOS\n            if(Amesos2::query(\"pardiso_mkl\"))\n                this->method = meth;\n            else\n                throw ValueError(\"Trilinos was not compiled with MKL Pardiso\");\n#else\n            throw ValueError(\"escript was not compiled with Trilinos\");\n#endif\n        case SO_METHOD_DIRECT_SUPERLU:\n#ifdef ESYS_HAVE_TRILINOS\n            if(Amesos2::query(\"superludist\") || Amesos2::query(\"superlu\") || Amesos2::query(\"superlumt\"))\n                this->method = meth;\n            else\n                throw ValueError(\"Trilinos was not compiled with SuperLU \");\n#else\n            throw ValueError(\"escript was not compiled with Trilinos\");\n#endif\n        default:\n            throw ValueError(\"unknown solver method\");\n    }\n}\n\nSolverOptions SolverBuddy::getSolverMethod() const\n{\n    return method;\n}\n\nvoid SolverBuddy::setPackage(int package)\n{\n    SolverOptions pack = static_cast<SolverOptions>(package);\n    switch (pack) {\n        case SO_DEFAULT:\n        // Default to trilinos if it is available, else use PASO\n        // This should always work because escript cannot be compiled\n        // unless at least one of these is available\n#ifdef ESYS_HAVE_TRILINOS\n            this->package = SO_PACKAGE_TRILINOS;\n            setSolverMethod(getSolverMethod());\n            break;\n#else\n            this->package = SO_PACKAGE_PASO;\n            setSolverMethod(getSolverMethod());\n            break;\n#endif\n        // Set to PASO iff escript was compiled with PASO\n        case SO_PACKAGE_PASO:\n#ifdef ESYS_HAVE_PASO\n            this->package = SO_PACKAGE_PASO;\n            setSolverMethod(getSolverMethod());\n            break;\n#else\n            throw ValueError(\"escript was not compiled with PASO enabled\");\n#endif\n        // Set to Trilinos iff escript was compiled with Trilinos\n        case SO_PACKAGE_TRILINOS:\n#ifdef ESYS_HAVE_TRILINOS\n            this->package = SO_PACKAGE_TRILINOS;\n            setSolverMethod(getSolverMethod());\n            break;\n#else\n            throw ValueError(\"escript was not compiled with Trilinos enabled\");\n#endif\n        // Set to MKL iff escript was compiled with MKL\n        case SO_PACKAGE_MKL:\n#ifdef ESYS_HAVE_MKL\n            this->package = SO_PACKAGE_MKL;\n            setSolverMethod(getSolverMethod());\n            break;\n#else\n            throw ValueError(\"escript was not compiled with MKL enabled\");\n#endif\n        // Set to Umfpack iff escript was compiled with Umfpack\n        case SO_PACKAGE_UMFPACK:\n#ifdef ESYS_HAVE_UMFPACK\n            this->package = SO_PACKAGE_UMFPACK;\n            setSolverMethod(getSolverMethod());\n            break;\n#else\n            throw ValueError(\"escript was not compiled with UMFPACK enabled\");\n#endif\n        // Set to MUMPS iff escript was compiled with MUMPS\n        case SO_PACKAGE_MUMPS:\n#ifdef ESYS_HAVE_MUMPS\n            this->package = SO_PACKAGE_MUMPS;\n            setSolverMethod(getSolverMethod());\n            break;\n#else\n            throw ValueError(\"escript was not compiled with MUMPS enabled\");\n#endif\n        default:\n            throw ValueError(\"unknown solver package\");\n    }\n}\n\nSolverOptions SolverBuddy::getPackage() const\n{\n    return package;\n}\n\nvoid SolverBuddy::setReordering(int ordering)\n{\n    SolverOptions ord = static_cast<SolverOptions>(ordering);\n    switch (ordering) {\n        case SO_REORDERING_DEFAULT:\n        case SO_REORDERING_MINIMUM_FILL_IN:\n        case SO_REORDERING_NESTED_DISSECTION:\n        case SO_REORDERING_NONE:\n            reordering = ord;\n            break;\n        default:\n            throw ValueError(\"unknown reordering strategy\");\n    }\n}\n\nSolverOptions SolverBuddy::getReordering() const\n{\n    return reordering;\n}\n\nvoid SolverBuddy::setRestart(int restart)\n{\n    if (restart < 0)\n        throw ValueError(\"restart must be non-negative.\");\n\n    this->restart = restart;\n}\n\nint SolverBuddy::getRestart() const\n{\n    return restart;\n}\n\nint SolverBuddy::_getRestartForC() const\n{\n    int r = getRestart();\n    if (r == 0)\n        return -1;\n    return r;\n}\n\nvoid SolverBuddy::setTruncation(int truncation)\n{\n    if (truncation < 1)\n        throw ValueError(\"truncation must be positive.\");\n    this->truncation = truncation;\n}\n\nint SolverBuddy::getTruncation() const\n{\n    return truncation;\n}\n\nvoid SolverBuddy::setInnerIterMax(int iter_max)\n{\n    if (iter_max < 1)\n        throw ValueError(\"maximum number of inner iteration must be positive.\");\n    inner_iter_max = iter_max;\n}\n\nint SolverBuddy::getInnerIterMax() const\n{\n    return inner_iter_max;\n}\n\nvoid SolverBuddy::setIterMax(int iter_max)\n{\n    if (iter_max < 1)\n        throw ValueError(\"maximum number of iteration steps must be positive.\");\n    this->iter_max = iter_max;\n}\n\nint SolverBuddy::getIterMax() const\n{\n    return iter_max;\n}\n\nvoid SolverBuddy::setNumSweeps(int sweeps)\n{\n    if (sweeps < 1)\n        throw ValueError(\"number of sweeps must be positive.\");\n    this->sweeps = sweeps;\n}\n\nint SolverBuddy::getNumSweeps() const\n{\n    return sweeps;\n}\n\nvoid SolverBuddy::setTolerance(double rtol)\n{\n    if (rtol < 0. || rtol > 1.)\n        throw ValueError(\"tolerance must be between 0 and 1.\");\n    tolerance = rtol;\n}\n\ndouble SolverBuddy::getTolerance() const\n{\n    return tolerance;\n}\n\nvoid SolverBuddy::setAbsoluteTolerance(double atol)\n{\n    if (atol < 0.)\n       throw ValueError(\"absolute tolerance must be non-negative.\");\n    absolute_tolerance = atol;\n}\n\ndouble SolverBuddy::getAbsoluteTolerance() const\n{\n    return absolute_tolerance;\n}\n\nvoid SolverBuddy::setInnerTolerance(double rtol)\n{\n    if (rtol <= 0. || rtol > 1.)\n        throw ValueError(\"tolerance must be positive and less than or equal to 1.\");\n    inner_tolerance = rtol;\n}\n\ndouble SolverBuddy::getInnerTolerance() const\n{\n    return inner_tolerance;\n}\n\nvoid SolverBuddy::setDropTolerance(double drop_tol)\n{\n    if (drop_tol < 0. || drop_tol > 1.)\n        throw ValueError(\"drop tolerance must be between 0 and 1.\");\n    drop_tolerance = drop_tol;\n}\n\ndouble SolverBuddy::getDropTolerance() const\n{\n    return drop_tolerance;\n}\n\nvoid SolverBuddy::setDropStorage(double storage)\n{\n    if (storage < 1.)\n        throw ValueError(\"allowed storage increase must be greater than or equal to 1.\");\n    drop_storage = storage;\n}\n\ndouble SolverBuddy::getDropStorage() const\n{\n    return drop_storage;\n}\n\nvoid SolverBuddy::setRelaxationFactor(double factor)\n{\n    if (factor < 0.)\n        throw ValueError(\"relaxation factor must be non-negative.\");\n    relaxation = factor;\n}\n\ndouble SolverBuddy::getRelaxationFactor() const\n{\n    return relaxation;\n}\n\nbool SolverBuddy::isComplex() const\n{\n    return is_complex;\n}\n\nvoid SolverBuddy::setComplex(bool flag)\n{\n    is_complex = flag;\n}\n\nbool SolverBuddy::isSymmetric() const\n{\n    return symmetric;\n}\n\nvoid SolverBuddy::setSymmetryOn()\n{\n    symmetric = true;\n}\n\nvoid SolverBuddy::setSymmetryOff()\n{\n    symmetric = false;\n}\n\nvoid SolverBuddy::setSymmetry(bool flag)\n{\n    if (flag)\n        setSymmetryOn();\n    else\n        setSymmetryOff();\n}\n\nbool SolverBuddy::isHermitian() const\n{\n    return hermitian;\n}\n\nvoid SolverBuddy::setHermitianOn()\n{\n    hermitian = true;\n}\n\nvoid SolverBuddy::setHermitianOff()\n{\n    hermitian = false;\n}\n\nvoid SolverBuddy::setHermitian(bool flag)\n{\n    if (flag)\n        setHermitianOn();\n    else\n        setHermitianOff();\n}\n\nbool SolverBuddy::isVerbose() const\n{\n    return verbose;\n}\n\nvoid SolverBuddy::setVerbosityOn()\n{\n    verbose = true;\n}\n\nvoid SolverBuddy::setVerbosityOff()\n{\n    verbose = false;\n}\n\nvoid SolverBuddy::setVerbosity(bool verbose)\n{\n    if (verbose)\n        setVerbosityOn();\n    else\n        setVerbosityOff();\n}\n\nbool SolverBuddy::adaptInnerTolerance() const\n{\n    return adapt_inner_tolerance;\n}\n\nvoid SolverBuddy::setInnerToleranceAdaptionOn()\n{\n    adapt_inner_tolerance = true;\n}\n\nvoid SolverBuddy::setInnerToleranceAdaptionOff()\n{\n    adapt_inner_tolerance = false;\n}\n\nvoid SolverBuddy::setInnerToleranceAdaption(bool adapt)\n{\n    if (adapt)\n        setInnerToleranceAdaptionOn();\n    else\n        setInnerToleranceAdaptionOff();\n}\n\nbool SolverBuddy::acceptConvergenceFailure() const\n{\n    return accept_convergence_failure;\n}\n\nvoid SolverBuddy::setAcceptanceConvergenceFailureOn()\n{\n    accept_convergence_failure = true;\n}\n\nvoid SolverBuddy::setAcceptanceConvergenceFailureOff()\n{\n    accept_convergence_failure = false;\n}\n\nvoid SolverBuddy::setAcceptanceConvergenceFailure(bool accept)\n{\n    if (accept)\n        setAcceptanceConvergenceFailureOn();\n    else\n        setAcceptanceConvergenceFailureOff();\n}\n\nbool SolverBuddy::useLocalPreconditioner() const\n{\n    return use_local_preconditioner;\n}\n\nvoid SolverBuddy::setLocalPreconditionerOn()\n{\n    use_local_preconditioner = true;\n}\n\nvoid SolverBuddy::setLocalPreconditionerOff()\n{\n    use_local_preconditioner=false;\n}\n\nvoid SolverBuddy::setLocalPreconditioner(bool use)\n{\n    if (use)\n        setLocalPreconditionerOn();\n    else\n        setLocalPreconditionerOff();\n}\n\nvoid SolverBuddy::setNumRefinements(int refinements)\n{\n    if (refinements < 0)\n        throw ValueError(\"number of refinements must be non-negative.\");\n    this->refinements = refinements;\n}\n\nint SolverBuddy::getNumRefinements() const\n{\n    return refinements;\n}\n\nvoid SolverBuddy::setODESolver(int method)\n{\n    SolverOptions ode = static_cast<SolverOptions>(method);\n    switch (ode) {\n        case SO_ODESOLVER_BACKWARD_EULER:\n        case SO_ODESOLVER_CRANK_NICOLSON:\n        case SO_ODESOLVER_LINEAR_CRANK_NICOLSON:\n            ode_solver = ode;\n            break;\n        default:\n            throw ValueError(\"unknown ODE solver method\");\n    }\n}\n\nSolverOptions SolverBuddy::getODESolver() const\n{\n    return ode_solver;\n}\n\nvoid SolverBuddy::setTrilinosParameter(const std::string& name,\n                                       const bp::object& value)\n{\n#ifdef ESYS_HAVE_TRILINOS\n    trilinosParams[name] = value;\n#endif\n}\n\nbp::dict SolverBuddy::getTrilinosParameters() const\n{\n    return trilinosParams;\n}\n\nvoid SolverBuddy::setDim(int dim)\n{\n    if (dim != 2 && dim != 3)\n        throw ValueError(\"Dimension must be either 2 or 3.\");\n    this->dim = dim;\n}\n\nint SolverBuddy::getDim()\n{\n    return dim;\n}\n\nbool SolverBuddy::using_default_method() const\n{\n    return using_default_solver_method;\n}\n\n} // namespace escript\n", "meta": {"hexsha": "c0a325ed34e539f1a8aefa8ada1640c62af94a76", "size": 25054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "escriptcore/src/SolverOptions.cpp", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "escriptcore/src/SolverOptions.cpp", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "escriptcore/src/SolverOptions.cpp", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1822272216, "max_line_length": 116, "alphanum_fraction": 0.6500359224, "num_tokens": 6308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667540468797665, "lm_q2_score": 0.03514485006417277, "lm_q1q2_score": 0.0058577821071442585}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2013, 2014, 2015.\n// Modifications copyright (c) 2013-2015 Oracle and/or its affiliates.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_LL_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_LL_HPP\n\n#include <boost/geometry/core/assert.hpp>\n\n#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>\n#include <boost/geometry/algorithms/detail/overlay/get_turn_info_for_endpoint.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry {\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace overlay {\n\ntemplate<typename AssignPolicy>\nstruct get_turn_info_linear_linear\n{\n    static const bool handle_spikes = true;\n\n    template\n    <\n        typename Point1,\n        typename Point2,\n        typename TurnInfo,\n        typename RobustPolicy,\n        typename OutputIterator\n    >\n    static inline OutputIterator apply(\n                Point1 const& pi, Point1 const& pj, Point1 const& pk,\n                Point2 const& qi, Point2 const& qj, Point2 const& qk,\n                bool is_p_first, bool is_p_last,\n                bool is_q_first, bool is_q_last,\n                TurnInfo const& tp_model,\n                RobustPolicy const& robust_policy,\n                OutputIterator out)\n    {\n        typedef intersection_info<Point1, Point2, typename TurnInfo::point_type, RobustPolicy>\n            inters_info;\n\n        inters_info inters(pi, pj, pk, qi, qj, qk, robust_policy);\n\n        char const method = inters.d_info().how;\n\n        // Copy, to copy possibly extended fields\n        TurnInfo tp = tp_model;\n\n        // Select method and apply\n        switch(method)\n        {\n            case 'a' : // collinear, \"at\"\n            case 'f' : // collinear, \"from\"\n            case 's' : // starts from the middle\n                get_turn_info_for_endpoint<AssignPolicy, true, true>\n                    ::apply(pi, pj, pk, qi, qj, qk,\n                            is_p_first, is_p_last, is_q_first, is_q_last,\n                            tp_model, inters, method_none, out);\n                break;\n\n            case 'd' : // disjoint: never do anything\n                break;\n\n            case 'm' :\n            {\n                if ( get_turn_info_for_endpoint<AssignPolicy, false, true>\n                        ::apply(pi, pj, pk, qi, qj, qk,\n                                is_p_first, is_p_last, is_q_first, is_q_last,\n                                tp_model, inters, method_touch_interior, out) )\n                {\n                    // do nothing\n                }\n                else\n                {\n                    typedef touch_interior\n                        <\n                            TurnInfo\n                        > policy;\n\n                    // If Q (1) arrives (1)\n                    if ( inters.d_info().arrival[1] == 1)\n                    {\n                        policy::template apply<0>(pi, pj, pk, qi, qj, qk,\n                                                  tp, inters.i_info(), inters.d_info(),\n                                                  inters.sides());\n                    }\n                    else\n                    {\n                        // Swap p/q\n                        side_calculator\n                            <\n                                typename inters_info::robust_point2_type,\n                                typename inters_info::robust_point1_type\n                            > swapped_side_calc(inters.rqi(), inters.rqj(), inters.rqk(),\n                                                inters.rpi(), inters.rpj(), inters.rpk());\n\n                        policy::template apply<1>(qi, qj, qk, pi, pj, pk,\n                                                  tp, inters.i_info(), inters.d_info(),\n                                                  swapped_side_calc);\n                    }\n                    \n                    if ( tp.operations[0].operation == operation_blocked )\n                    {\n                        tp.operations[1].is_collinear = true;\n                    }\n                    if ( tp.operations[1].operation == operation_blocked )\n                    {\n                        tp.operations[0].is_collinear = true;\n                    }\n\n                    replace_method_and_operations_tm(tp.method,\n                                                     tp.operations[0].operation,\n                                                     tp.operations[1].operation);\n                    \n                    AssignPolicy::apply(tp, pi, qi, inters);\n                    *out++ = tp;\n                }\n            }\n            break;\n            case 'i' :\n            {\n                crosses<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                                         tp, inters.i_info(), inters.d_info());\n\n                replace_operations_i(tp.operations[0].operation, tp.operations[1].operation);\n\n                AssignPolicy::apply(tp, pi, qi, inters);\n                *out++ = tp;\n            }\n            break;\n            case 't' :\n            {\n                // Both touch (both arrive there)\n                if ( get_turn_info_for_endpoint<AssignPolicy, false, true>\n                        ::apply(pi, pj, pk, qi, qj, qk,\n                                is_p_first, is_p_last, is_q_first, is_q_last,\n                                tp_model, inters, method_touch, out) )\n                {\n                    // do nothing\n                }\n                else \n                {\n                    touch<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                                           tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                    // workarounds for touch<> not taking spikes into account starts here\n                    // those was discovered empirically\n                    // touch<> is not symmetrical!\n                    // P spikes and Q spikes may produce various operations!\n                    // TODO: this is not optimal solution - think about rewriting touch<>\n\n                    if ( tp.operations[0].operation == operation_blocked\n                      && tp.operations[1].operation == operation_blocked )\n                    {\n                        // two touching spikes on the same line\n                        if ( inters.is_spike_p() && inters.is_spike_q() )\n                        {\n                            tp.operations[0].operation = operation_union;\n                            tp.operations[1].operation = operation_union; \n                        }\n                        else\n                        {\n                            tp.operations[0].is_collinear = true;\n                            tp.operations[1].is_collinear = true;\n                        }\n                    }\n                    else if ( tp.operations[0].operation == operation_blocked )\n                    {\n                        // a spike on P on the same line with Q1\n                        if ( inters.is_spike_p() )\n                        {\n                            if ( inters.sides().qk_wrt_p1() == 0 )\n                            {\n                                tp.operations[0].is_collinear = true;\n                            }\n                            else\n                            {\n                                tp.operations[0].operation = operation_union;                                \n                            }\n                        }\n                        else\n                        {\n                            tp.operations[1].is_collinear = true;\n                        }\n                    }\n                    else if ( tp.operations[1].operation == operation_blocked )\n                    {\n                        // a spike on Q on the same line with P1\n                        if ( inters.is_spike_q() )\n                        {\n                            if ( inters.sides().pk_wrt_q1() == 0 )\n                            {\n                                tp.operations[1].is_collinear = true;\n                            }\n                            else\n                            {\n                                tp.operations[1].operation = operation_union;                                \n                            }\n                        }\n                        else\n                        {\n                            tp.operations[0].is_collinear = true;\n                        }\n                    }\n                    else if ( tp.operations[0].operation == operation_continue\n                           && tp.operations[1].operation == operation_continue )\n                    {\n                        // P spike on the same line with Q2 (opposite)\n                        if ( inters.sides().pk_wrt_q1() == -inters.sides().qk_wrt_q1()\n                          && inters.is_spike_p() )\n                        {\n                            tp.operations[0].operation = operation_union;\n                            tp.operations[1].operation = operation_union; \n                        }\n                    }\n                    else if ( tp.operations[0].operation == operation_none\n                           && tp.operations[1].operation == operation_none )\n                    {\n                        // spike not handled by touch<>\n                        bool const is_p = inters.is_spike_p();\n                        bool const is_q = inters.is_spike_q();\n\n                        if ( is_p || is_q )\n                        {\n                            tp.operations[0].operation = operation_union;\n                            tp.operations[1].operation = operation_union;\n\n                            if ( inters.sides().pk_wrt_q2() == 0 )\n                            {\n                                tp.operations[0].operation = operation_continue; // will be converted to i\n                                if ( is_p )\n                                {\n                                    tp.operations[0].is_collinear = true;\n                                }\n                            }\n\n                            if ( inters.sides().qk_wrt_p2() == 0 )\n                            {\n                                tp.operations[1].operation = operation_continue; // will be converted to i\n                                if ( is_q )\n                                {\n                                    tp.operations[1].is_collinear = true;\n                                }\n                            }\n                        }\n                    }\n\n                    // workarounds for touch<> not taking spikes into account ends here\n\n                    replace_method_and_operations_tm(tp.method,\n                                                     tp.operations[0].operation,\n                                                     tp.operations[1].operation);\n\n// TODO: move this into the append_xxx and call for each turn?\n                    AssignPolicy::apply(tp, pi, qi, inters);\n\n                    if ( ! BOOST_GEOMETRY_CONDITION(handle_spikes)\n                      || ! append_opposite_spikes<append_touches>(tp, inters,\n                                                                  is_p_last, is_q_last,\n                                                                  out) )\n                    {\n                        *out++ = tp;\n                    }\n                }\n            }\n            break;\n            case 'e':\n            {\n                if ( get_turn_info_for_endpoint<AssignPolicy, true, true>\n                        ::apply(pi, pj, pk, qi, qj, qk,\n                                is_p_first, is_p_last, is_q_first, is_q_last,\n                                tp_model, inters, method_equal, out) )\n                {\n                    // do nothing\n                }\n                else\n                {\n                    tp.operations[0].is_collinear = true;\n                    tp.operations[1].is_collinear = true;\n\n                    if ( ! inters.d_info().opposite )\n                    {\n                        // Both equal\n                        // or collinear-and-ending at intersection point\n                        equal<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                            tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                        operation_type spike_op\n                            = ( tp.operations[0].operation != operation_continue\n                             || tp.operations[1].operation != operation_continue ) ?\n                                operation_union :\n                                operation_continue;\n\n                        // transform turn\n                        turn_transformer_ec transformer(method_touch);\n                        transformer(tp);\n\n// TODO: move this into the append_xxx and call for each turn?\n                        AssignPolicy::apply(tp, pi, qi, inters);\n\n                        // conditionally handle spikes\n                        if ( ! BOOST_GEOMETRY_CONDITION(handle_spikes)\n                          || ! append_collinear_spikes(tp, inters,\n                                                       is_p_last, is_q_last,\n                                                       method_touch, spike_op,\n                                                       out) )\n                        {\n                            *out++ = tp; // no spikes\n                        }\n                    }\n                    else\n                    {\n                        // TODO: ignore for spikes or generate something else than opposite?\n\n                        equal_opposite\n                            <\n                                TurnInfo,\n                                AssignPolicy\n                            >::apply(pi, qi, tp, out, inters);\n                    }\n                }\n            }\n            break;\n            case 'c' :\n            {\n                // Collinear\n                if ( get_turn_info_for_endpoint<AssignPolicy, true, true>\n                        ::apply(pi, pj, pk, qi, qj, qk,\n                                is_p_first, is_p_last, is_q_first, is_q_last,\n                                tp_model, inters, method_collinear, out) )\n                {\n                    // do nothing\n                }\n                else\n                {\n                    // NOTE: this is for spikes since those are set in the turn_transformer_ec\n                    tp.operations[0].is_collinear = true;\n                    tp.operations[1].is_collinear = true;\n\n                    if ( ! inters.d_info().opposite )\n                    {\n                        method_type method_replace = method_touch_interior;\n                        operation_type spike_op = operation_continue;\n\n                        if ( inters.d_info().arrival[0] == 0 )\n                        {\n                            // Collinear, but similar thus handled as equal\n                            equal<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                                    tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                            method_replace = method_touch;\n                            if ( tp.operations[0].operation != operation_continue\n                              || tp.operations[1].operation != operation_continue )\n                            {\n                                spike_op = operation_union;\n                            }\n                        }\n                        else\n                        {\n                            collinear<TurnInfo>::apply(pi, pj, pk, qi, qj, qk,\n                                    tp, inters.i_info(), inters.d_info(), inters.sides());\n\n                            //method_replace = method_touch_interior;\n                            //spike_op = operation_continue;\n                        }\n\n                        // transform turn\n                        turn_transformer_ec transformer(method_replace);\n                        transformer(tp);\n                        \n// TODO: move this into the append_xxx and call for each turn?\n                        AssignPolicy::apply(tp, pi, qi, inters);\n\n                        // conditionally handle spikes\n                        if ( ! BOOST_GEOMETRY_CONDITION(handle_spikes)\n                          || ! append_collinear_spikes(tp, inters,\n                                                       is_p_last, is_q_last,\n                                                       method_replace, spike_op,\n                                                       out) )\n                        {\n                            // no spikes\n                            *out++ = tp;\n                        }\n                    }\n                    else\n                    {\n                        // If this always 'm' ?\n                        turn_transformer_ec transformer(method_touch_interior);\n\n                        // conditionally handle spikes\n                        if ( BOOST_GEOMETRY_CONDITION(handle_spikes) )\n                        {\n                            append_opposite_spikes<append_collinear_opposite>(tp, inters,\n                                                                              is_p_last, is_q_last,\n                                                                              out);\n                        }\n\n                        // TODO: ignore for spikes?\n                        //       E.g. pass is_p_valid = !is_p_last && !is_pj_spike,\n                        //       the same with is_q_valid\n\n                        collinear_opposite\n                            <\n                                TurnInfo,\n                                AssignPolicy\n                            >::apply(pi, pj, pk, qi, qj, qk,\n                                tp, out, inters, inters.sides(),\n                                transformer, !is_p_last, !is_q_last);\n                    }\n                }\n            }\n            break;\n            case '0' :\n            {\n                // degenerate points\n                if ( BOOST_GEOMETRY_CONDITION(AssignPolicy::include_degenerate) )\n                {\n                    only_convert::apply(tp, inters.i_info());\n\n                    // if any, only one of those should be true\n                    if ( is_p_first\n                      && equals::equals_point_point(pi, tp.point) )\n                    {\n                        tp.operations[0].position = position_front;\n                    }\n                    else if ( is_p_last\n                           && equals::equals_point_point(pj, tp.point) )\n                    {\n                        tp.operations[0].position = position_back;\n                    }\n                    else if ( is_q_first\n                           && equals::equals_point_point(qi, tp.point) )\n                    {\n                        tp.operations[1].position = position_front;\n                    }\n                    else if ( is_q_last\n                           && equals::equals_point_point(qj, tp.point) )\n                    {\n                        tp.operations[1].position = position_back;\n                    }\n\n                    AssignPolicy::apply(tp, pi, qi, inters);\n                    *out++ = tp;\n                }\n            }\n            break;\n            default :\n            {\n#if defined(BOOST_GEOMETRY_DEBUG_ROBUSTNESS)\n                std::cout << \"TURN: Unknown method: \" << method << std::endl;\n#endif\n#if ! defined(BOOST_GEOMETRY_OVERLAY_NO_THROW)\n                throw turn_info_exception(method);\n#endif\n            }\n            break;\n        }\n\n        return out;\n    }\n\n    template <typename TurnInfo,\n              typename IntersectionInfo,\n              typename OutIt>\n    static inline bool append_collinear_spikes(TurnInfo & tp,\n                                               IntersectionInfo const& inters_info,\n                                               bool is_p_last, bool is_q_last,\n                                               method_type method, operation_type spike_op,\n                                               OutIt out)\n    {\n        // method == touch || touch_interior\n        // both position == middle\n\n        bool is_p_spike = tp.operations[0].operation == spike_op\n                       && ! is_p_last\n                       && inters_info.is_spike_p();\n        bool is_q_spike = tp.operations[1].operation == spike_op\n                       && ! is_q_last\n                       && inters_info.is_spike_q();\n\n        if ( is_p_spike && is_q_spike )\n        {\n            if ( tp.method == method_equal\n              && tp.operations[0].operation == operation_continue\n              && tp.operations[1].operation == operation_continue )\n            {\n                // treat both non-opposite collinear spikes as no-spikes\n                return false;\n            }\n\n            tp.method = method;\n            tp.operations[0].operation = operation_blocked;\n            tp.operations[1].operation = operation_blocked;\n            *out++ = tp;\n            tp.operations[0].operation = operation_intersection;\n            tp.operations[1].operation = operation_intersection;\n            *out++ = tp;\n\n            return true;\n        }\n        else if ( is_p_spike )\n        {\n            tp.method = method;\n            tp.operations[0].operation = operation_blocked;\n            tp.operations[1].operation = operation_union;\n            *out++ = tp;\n            tp.operations[0].operation = operation_intersection;\n            //tp.operations[1].operation = operation_union;\n            *out++ = tp;\n\n            return true;\n        }\n        else if ( is_q_spike )\n        {\n            tp.method = method;\n            tp.operations[0].operation = operation_union;\n            tp.operations[1].operation = operation_blocked;\n            *out++ = tp;\n            //tp.operations[0].operation = operation_union;\n            tp.operations[1].operation = operation_intersection;\n            *out++ = tp;\n\n            return true;\n        }\n        \n        return false;\n    }\n\n    enum append_version { append_touches, append_collinear_opposite };\n\n    template <append_version Version,\n              typename TurnInfo,\n              typename IntersectionInfo,\n              typename OutIt>\n    static inline bool append_opposite_spikes(TurnInfo & tp,\n                                              IntersectionInfo const& inters,\n                                              bool is_p_last, bool is_q_last,\n                                              OutIt out)\n    {\n        static const bool is_version_touches = (Version == append_touches);\n\n        bool is_p_spike = ( is_version_touches ?\n                            ( tp.operations[0].operation == operation_continue\n                           || tp.operations[0].operation == operation_intersection ) :\n                            true )\n                       && ! is_p_last\n                       && inters.is_spike_p();\n        bool is_q_spike = ( is_version_touches ?\n                            ( tp.operations[1].operation == operation_continue\n                           || tp.operations[1].operation == operation_intersection ) :\n                            true )\n                       && ! is_q_last\n                       && inters.is_spike_q();\n\n        bool res = false;\n\n        if ( is_p_spike\n          && ( BOOST_GEOMETRY_CONDITION(is_version_touches)\n            || inters.d_info().arrival[0] == 1 ) )\n        {\n            if ( BOOST_GEOMETRY_CONDITION(is_version_touches) )\n            {\n                tp.operations[0].is_collinear = true;\n                tp.operations[1].is_collinear = false;\n                tp.method = method_touch;\n            }\n            else // Version == append_collinear_opposite\n            {\n                tp.operations[0].is_collinear = true;\n                tp.operations[1].is_collinear = false;\n                \n                BOOST_GEOMETRY_ASSERT(inters.i_info().count > 1);\n                \n                base_turn_handler::assign_point(tp, method_touch_interior,\n                                                inters.i_info(), 1);\n\n                AssignPolicy::apply(tp, inters.pi(), inters.qi(), inters);\n            }\n\n            tp.operations[0].operation = operation_blocked;\n            tp.operations[1].operation = operation_intersection;\n            *out++ = tp;\n            tp.operations[0].operation = operation_intersection;\n            //tp.operations[1].operation = operation_intersection;\n            *out++ = tp;\n\n            res = true;\n        }\n\n        if ( is_q_spike\n          && ( BOOST_GEOMETRY_CONDITION(is_version_touches)\n            || inters.d_info().arrival[1] == 1 ) )\n        {\n            if ( BOOST_GEOMETRY_CONDITION(is_version_touches) )\n            {\n                tp.operations[0].is_collinear = false;\n                tp.operations[1].is_collinear = true;\n                tp.method = method_touch;\n            }\n            else // Version == append_collinear_opposite\n            {\n                tp.operations[0].is_collinear = false;\n                tp.operations[1].is_collinear = true;\n                \n                BOOST_GEOMETRY_ASSERT(inters.i_info().count > 0);\n\n                base_turn_handler::assign_point(tp, method_touch_interior, inters.i_info(), 0);\n\n                AssignPolicy::apply(tp, inters.pi(), inters.qi(), inters);\n            }\n\n            tp.operations[0].operation = operation_intersection;\n            tp.operations[1].operation = operation_blocked;\n            *out++ = tp;\n            //tp.operations[0].operation = operation_intersection;\n            tp.operations[1].operation = operation_intersection;\n            *out++ = tp;\n\n            res = true;\n        }\n        \n        return res;\n    }\n\n    static inline void replace_method_and_operations_tm(method_type & method,\n                                                        operation_type & op0,\n                                                        operation_type & op1)\n    {\n        if ( op0 == operation_blocked && op1 == operation_blocked )\n        {\n            // NOTE: probably only if methods are WRT IPs, not segments!\n            method = (method == method_touch ? method_equal : method_collinear);\n            op0 = operation_continue;\n            op1 = operation_continue;\n        }\n        else\n        {\n            if ( op0 == operation_continue || op0 == operation_blocked )\n            {\n                op0 = operation_intersection;\n            }\n            else if ( op0 == operation_intersection )\n            {\n                op0 = operation_union;\n            }\n\n            if ( op1 == operation_continue || op1 == operation_blocked )\n            {\n                op1 = operation_intersection;\n            }\n            else if ( op1 == operation_intersection )\n            {\n                op1 = operation_union;\n            }\n\n            // spikes in 'm'\n            if ( method == method_error )\n            {\n                method = method_touch_interior;\n                op0 = operation_union;\n                op1 = operation_union;\n            }\n        }\n    }\n\n    class turn_transformer_ec\n    {\n    public:\n        explicit turn_transformer_ec(method_type method_t_or_m)\n            : m_method(method_t_or_m)\n        {}\n\n        template <typename Turn>\n        void operator()(Turn & turn) const\n        {\n            operation_type & op0 = turn.operations[0].operation;\n            operation_type & op1 = turn.operations[1].operation;\n\n            BOOST_GEOMETRY_ASSERT(op0 != operation_blocked || op1 != operation_blocked );\n\n            if ( op0 == operation_blocked )\n            {\n                op0 = operation_intersection;\n            }\n            else if ( op0 == operation_intersection )\n            {\n                op0 = operation_union;\n            }\n\n            if ( op1 == operation_blocked )\n            {\n                op1 = operation_intersection;\n            }\n            else if ( op1 == operation_intersection )\n            {\n                op1 = operation_union;\n            }\n\n            if ( op0 == operation_intersection || op0 == operation_union\n              || op1 == operation_intersection || op1 == operation_union )\n            {\n                turn.method = m_method;\n            }\n\n// TODO: is this correct?\n//       it's equivalent to comparing to operation_blocked at the beginning of the function\n            turn.operations[0].is_collinear = op0 != operation_intersection;\n            turn.operations[1].is_collinear = op1 != operation_intersection;\n        }\n\n    private:\n        method_type m_method;\n    };\n\n    static inline void replace_operations_i(operation_type & op0, operation_type & op1)\n    {\n        if ( op0 == operation_intersection )\n        {\n            op0 = operation_union;\n        }\n\n        if ( op1 == operation_intersection )\n        {\n            op1 = operation_union;\n        }\n    }\n};\n\n}} // namespace detail::overlay\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_LL_HPP\n", "meta": {"hexsha": "f6db5d07ee6ea1a50807eb71f6f7e858b341a1ce", "size": 29686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/overlay/get_turn_info_ll.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/overlay/get_turn_info_ll.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/overlay/get_turn_info_ll.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": 39.7402945114, "max_line_length": 118, "alphanum_fraction": 0.430674392, "num_tokens": 5212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.014063627327344041, "lm_q1q2_score": 0.0058349827458309385}}
{"text": "// Copyright (c) 2017, 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 touches functor and function.\n\n#include <cstddef>  // std::size_t\n#include <memory>   // std::unique_ptr\n\n#include <boost/geometry.hpp>\n\n#include \"sql/dd/types/spatial_reference_system.h\"  // dd::Spatial_reference_system\n#include \"sql/gis/box.h\"\n#include \"sql/gis/box_traits.h\"\n#include \"sql/gis/gc_utils.h\"\n#include \"sql/gis/geometries.h\"\n#include \"sql/gis/geometries_traits.h\"\n#include \"sql/gis/mbr_utils.h\"\n#include \"sql/gis/relops.h\"\n#include \"sql/gis/touches_functor.h\"\n#include \"sql/gis/within_functor.h\"\n#include \"sql/sql_exception_handler.h\"  // handle_gis_exception\n\nnamespace bg = boost::geometry;\n\nnamespace gis {\n\n/// Apply a Touches functor to two geometries, which both may be geometry\n/// collections, and return the booelan result of the functor applied on each\n/// combination of elements in the collections.\n///\n/// @tparam GC Coordinate specific gometry collection type.\n///\n/// @param f Functor to apply.\n/// @param g1 First geometry.\n/// @param g2 Second geometry.\n///\n/// @retval true g1 touches g2.\n/// @retval false g1 doesn't touch g2.\ntemplate <typename GC>\nstatic bool geometry_collection_apply_touches(const Touches &f,\n                                              const Geometry *g1,\n                                              const Geometry *g2) {\n  boost::geometry::strategy::within::geographic_winding<Geographic_point>\n      geographic_pl_pa_strategy(\n          bg::srs::spheroid<double>(f.semi_major(), f.semi_minor()));\n  boost::geometry::strategy::intersection::geographic_segments<>\n      geographic_ll_la_aa_strategy(\n          bg::srs::spheroid<double>(f.semi_major(), f.semi_minor()));\n\n  if (g1->type() == Geometry_type::kGeometrycollection) {\n    if (g2->type() == Geometry_type::kGeometrycollection) {\n      std::unique_ptr<Multipoint> g1_mpt;\n      std::unique_ptr<Multilinestring> g1_mls;\n      std::unique_ptr<Multipolygon> g1_mpy;\n      std::unique_ptr<Multipoint> g2_mpt;\n      std::unique_ptr<Multilinestring> g2_mls;\n      std::unique_ptr<Multipolygon> g2_mpy;\n      split_gc(down_cast<const Geometrycollection *>(g1), &g1_mpt, &g1_mls,\n               &g1_mpy);\n      gc_union(f.semi_major(), f.semi_minor(), &g1_mpt, &g1_mls, &g1_mpy);\n      split_gc(down_cast<const Geometrycollection *>(g2), &g2_mpt, &g2_mls,\n               &g2_mpy);\n      gc_union(f.semi_major(), f.semi_minor(), &g2_mpt, &g2_mls, &g2_mpy);\n\n      if (!g1_mpt->empty() && g1_mls->empty() && g1_mpy->empty() &&\n          !g2_mpt->empty() && g2_mls->empty() && g2_mpy->empty())\n        throw null_value_exception();\n\n      // Check that at least one part of g1 touches at least one part of g2.\n      if (!((!g1_mpt->empty() && !g2_mls->empty() &&\n             f(g1_mpt.get(), g2_mls.get())) ||\n            (!g1_mpt->empty() && !g2_mpy->empty() &&\n             f(g1_mpt.get(), g2_mpy.get())) ||\n            (!g1_mls->empty() && !g2_mpt->empty() &&\n             f(g1_mls.get(), g2_mpt.get())) ||\n            (!g1_mls->empty() && !g2_mls->empty() &&\n             f(g1_mls.get(), g2_mls.get())) ||\n            (!g1_mls->empty() && !g2_mpy->empty() &&\n             f(g1_mls.get(), g2_mpy.get())) ||\n            (!g1_mpy->empty() && !g2_mpt->empty() &&\n             f(g1_mpy.get(), g2_mpt.get())) ||\n            (!g1_mpy->empty() && !g2_mls->empty() &&\n             f(g1_mpy.get(), g2_mls.get())) ||\n            (!g1_mpy->empty() && !g2_mpy->empty() &&\n             f(g1_mpy.get(), g2_mpy.get()))))\n        return false;\n\n      // Check that the interiors of g1 and g2 are disjoint.\n      boost::geometry::de9im::mask mask(\"T********\");\n      if (g1->coordinate_system() == Coordinate_system::kCartesian) {\n        for (std::size_t i = 0;\n             i < down_cast<Cartesian_multipoint *>(g1_mpt.get())->size(); i++) {\n          auto &pt = (*down_cast<Cartesian_multipoint *>(g1_mpt.get()))[i];\n          if (bg::relate(pt, *down_cast<Cartesian_multipoint *>(g2_mpt.get()),\n                         mask) ||\n              bg::relate(pt,\n                         *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                         mask) ||\n              bg::relate(pt, *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                         mask))\n            return false;\n        }\n        for (std::size_t i = 0;\n             i < down_cast<Cartesian_multipoint *>(g2_mpt.get())->size(); i++) {\n          auto &pt = (*down_cast<Cartesian_multipoint *>(g2_mpt.get()))[i];\n          if (bg::relate(pt,\n                         *down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                         mask) ||\n              bg::relate(pt, *down_cast<Cartesian_multipolygon *>(g1_mpy.get()),\n                         mask))\n            return false;\n        }\n\n        if (bg::relate(*down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                       *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                       mask) ||\n            bg::relate(*down_cast<Cartesian_multilinestring *>(g1_mls.get()),\n                       *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                       mask) ||\n            bg::relate(*down_cast<Cartesian_multipolygon *>(g1_mpy.get()),\n                       *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                       mask) ||\n            bg::relate(*down_cast<Cartesian_multipolygon *>(g1_mpy.get()),\n                       *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                       mask))\n          return false;\n      } else {\n        DBUG_ASSERT(g1->coordinate_system() == Coordinate_system::kGeographic);\n        for (std::size_t i = 0;\n             i < down_cast<Geographic_multipoint *>(g1_mpt.get())->size();\n             i++) {\n          auto &pt = (*down_cast<Geographic_multipoint *>(g1_mpt.get()))[i];\n          if (bg::relate(pt, *down_cast<Geographic_multipoint *>(g2_mpt.get()),\n                         mask) ||\n              bg::relate(pt,\n                         *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                         mask, geographic_pl_pa_strategy) ||\n              bg::relate(pt,\n                         *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                         mask, geographic_pl_pa_strategy))\n            return false;\n        }\n        for (std::size_t i = 0;\n             i < down_cast<Geographic_multipoint *>(g2_mpt.get())->size();\n             i++) {\n          auto &pt = (*down_cast<Geographic_multipoint *>(g2_mpt.get()))[i];\n          if (bg::relate(pt,\n                         *down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                         mask, geographic_pl_pa_strategy) ||\n              bg::relate(pt,\n                         *down_cast<Geographic_multipolygon *>(g1_mpy.get()),\n                         mask, geographic_pl_pa_strategy))\n            return false;\n        }\n\n        if (bg::relate(*down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                       *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                       mask, geographic_ll_la_aa_strategy) ||\n            bg::relate(*down_cast<Geographic_multilinestring *>(g1_mls.get()),\n                       *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                       mask, geographic_ll_la_aa_strategy) ||\n            bg::relate(*down_cast<Geographic_multipolygon *>(g1_mpy.get()),\n                       *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                       mask, geographic_ll_la_aa_strategy) ||\n            bg::relate(*down_cast<Geographic_multipolygon *>(g1_mpy.get()),\n                       *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                       mask, geographic_ll_la_aa_strategy))\n          return false;\n      }\n\n      return true;\n    } else {\n      return f(g2, g1);\n    }\n  } else {\n    if (g2->type() == Geometry_type::kGeometrycollection) {\n      std::unique_ptr<Multipoint> g2_mpt;\n      std::unique_ptr<Multilinestring> g2_mls;\n      std::unique_ptr<Multipolygon> g2_mpy;\n      split_gc(down_cast<const Geometrycollection *>(g2), &g2_mpt, &g2_mls,\n               &g2_mpy);\n      gc_union(f.semi_major(), f.semi_minor(), &g2_mpt, &g2_mls, &g2_mpy);\n\n      // Check that at g1 touches at least one part of g2.\n      if (!((!g2_mpt->empty() && f(g1, g2_mpt.get())) ||\n            (!g2_mls->empty() && f(g1, g2_mls.get())) ||\n            (!g2_mpy->empty() && f(g1, g2_mpy.get()))))\n        return false;\n\n      // Check that the interiors of g1 and g2 are disjoint.\n      boost::geometry::de9im::mask mask(\"T********\");\n      if (g1->coordinate_system() == Coordinate_system::kCartesian) {\n        switch (g1->type()) {\n          case Geometry_type::kPoint:\n            if (!g2_mpt->empty() && g2_mls->empty() && g2_mpy->empty())\n              throw null_value_exception();\n            if (bg::relate(*down_cast<const Cartesian_point *>(g1),\n                           *down_cast<Cartesian_multipoint *>(g2_mpt.get()),\n                           mask) ||\n                bg::relate(\n                    *down_cast<const Cartesian_point *>(g1),\n                    *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                    mask) ||\n                bg::relate(*down_cast<const Cartesian_point *>(g1),\n                           *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                           mask))\n              return false;\n            break;\n          case Geometry_type::kLinestring:\n            for (std::size_t i = 0;\n                 i < down_cast<Cartesian_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Cartesian_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt, *down_cast<const Cartesian_linestring *>(g1),\n                             mask))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Cartesian_linestring *>(g1),\n                    *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                    mask) ||\n                bg::relate(*down_cast<const Cartesian_linestring *>(g1),\n                           *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                           mask))\n              return false;\n            break;\n          case Geometry_type::kPolygon:\n            for (std::size_t i = 0;\n                 i < down_cast<Cartesian_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Cartesian_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt, *down_cast<const Cartesian_polygon *>(g1),\n                             mask))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Cartesian_polygon *>(g1),\n                    *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                    mask) ||\n                bg::relate(*down_cast<const Cartesian_polygon *>(g1),\n                           *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                           mask))\n              return false;\n            break;\n          case Geometry_type::kMultipoint:\n            if (!g2_mpt->empty() && g2_mls->empty() && g2_mpy->empty())\n              throw null_value_exception();\n            for (std::size_t i = 0;\n                 i < down_cast<const Cartesian_multipoint *>(g1)->size(); i++) {\n              auto &pt = (*down_cast<const Cartesian_multipoint *>(g1))[i];\n              if (bg::relate(\n                      pt, *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                      mask) ||\n                  bg::relate(pt,\n                             *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                             mask))\n                return false;\n            }\n            if (bg::relate(*down_cast<const Cartesian_multipoint *>(g1),\n                           *down_cast<Cartesian_multipoint *>(g2_mpt.get()),\n                           mask))\n              return false;\n            break;\n          case Geometry_type::kMultilinestring:\n            for (std::size_t i = 0;\n                 i < down_cast<Cartesian_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Cartesian_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt,\n                             *down_cast<const Cartesian_multilinestring *>(g1),\n                             mask))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Cartesian_multilinestring *>(g1),\n                    *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                    mask) ||\n                bg::relate(*down_cast<const Cartesian_multilinestring *>(g1),\n                           *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                           mask))\n              return false;\n            break;\n          case Geometry_type::kMultipolygon:\n            for (std::size_t i = 0;\n                 i < down_cast<Cartesian_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Cartesian_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt, *down_cast<const Cartesian_multipolygon *>(g1),\n                             mask))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Cartesian_multipolygon *>(g1),\n                    *down_cast<Cartesian_multilinestring *>(g2_mls.get()),\n                    mask) ||\n                bg::relate(*down_cast<const Cartesian_multipolygon *>(g1),\n                           *down_cast<Cartesian_multipolygon *>(g2_mpy.get()),\n                           mask))\n              return false;\n            break;\n          default:\n            DBUG_ASSERT(false); /* purecov: inspected */\n            return false;\n        }\n      } else {\n        DBUG_ASSERT(g1->coordinate_system() == Coordinate_system::kGeographic);\n        switch (g1->type()) {\n          case Geometry_type::kPoint:\n            if (bg::relate(*down_cast<const Geographic_point *>(g1),\n                           *down_cast<Geographic_multipoint *>(g2_mpt.get()),\n                           mask) ||\n                bg::relate(\n                    *down_cast<const Geographic_point *>(g1),\n                    *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                    mask, geographic_pl_pa_strategy) ||\n                bg::relate(*down_cast<const Geographic_point *>(g1),\n                           *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                           mask, geographic_pl_pa_strategy))\n              return false;\n            break;\n          case Geometry_type::kLinestring:\n            for (std::size_t i = 0;\n                 i < down_cast<Geographic_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Geographic_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt, *down_cast<const Geographic_linestring *>(g1),\n                             mask, geographic_pl_pa_strategy))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Geographic_linestring *>(g1),\n                    *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                    mask, geographic_ll_la_aa_strategy) ||\n                bg::relate(*down_cast<const Geographic_linestring *>(g1),\n                           *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                           mask, geographic_ll_la_aa_strategy))\n              return false;\n            break;\n          case Geometry_type::kPolygon:\n            for (std::size_t i = 0;\n                 i < down_cast<Geographic_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Geographic_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt, *down_cast<const Geographic_polygon *>(g1),\n                             mask, geographic_pl_pa_strategy))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Geographic_polygon *>(g1),\n                    *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                    mask, geographic_ll_la_aa_strategy) ||\n                bg::relate(*down_cast<const Geographic_polygon *>(g1),\n                           *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                           mask, geographic_ll_la_aa_strategy))\n              return false;\n            break;\n          case Geometry_type::kMultipoint:\n            for (std::size_t i = 0;\n                 i < down_cast<const Geographic_multipoint *>(g1)->size();\n                 i++) {\n              auto &pt = (*down_cast<const Geographic_multipoint *>(g1))[i];\n              if (bg::relate(\n                      pt,\n                      *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                      mask, geographic_pl_pa_strategy) ||\n                  bg::relate(\n                      pt, *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                      mask, geographic_pl_pa_strategy))\n                return false;\n            }\n            // Default strategy is OK for multipoint-multipoint.\n            if (bg::relate(*down_cast<const Geographic_multipoint *>(g1),\n                           *down_cast<Geographic_multipoint *>(g2_mpt.get()),\n                           mask))\n              return false;\n            break;\n          case Geometry_type::kMultilinestring:\n            for (std::size_t i = 0;\n                 i < down_cast<Geographic_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Geographic_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt,\n                             *down_cast<const Geographic_multilinestring *>(g1),\n                             mask, geographic_pl_pa_strategy))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Geographic_multilinestring *>(g1),\n                    *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                    mask, geographic_ll_la_aa_strategy) ||\n                bg::relate(*down_cast<const Geographic_multilinestring *>(g1),\n                           *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                           mask, geographic_ll_la_aa_strategy))\n              return false;\n            break;\n          case Geometry_type::kMultipolygon:\n            for (std::size_t i = 0;\n                 i < down_cast<Geographic_multipoint *>(g2_mpt.get())->size();\n                 i++) {\n              auto &pt = (*down_cast<Geographic_multipoint *>(g2_mpt.get()))[i];\n              if (bg::relate(pt,\n                             *down_cast<const Geographic_multipolygon *>(g1),\n                             mask, geographic_pl_pa_strategy))\n                return false;\n            }\n            if (bg::relate(\n                    *down_cast<const Geographic_multipolygon *>(g1),\n                    *down_cast<Geographic_multilinestring *>(g2_mls.get()),\n                    mask, geographic_ll_la_aa_strategy) ||\n                bg::relate(*down_cast<const Geographic_multipolygon *>(g1),\n                           *down_cast<Geographic_multipolygon *>(g2_mpy.get()),\n                           mask, geographic_ll_la_aa_strategy))\n              return false;\n            break;\n          default:\n            DBUG_ASSERT(false); /* purecov: inspected */\n            return false;\n        }\n      }\n\n      return true;\n    } else {\n      return f(g1, g2);\n    }\n  }\n}\n\nTouches::Touches(double semi_major, double semi_minor)\n    : m_semi_major(semi_major),\n      m_semi_minor(semi_minor),\n      m_geographic_pl_pa_strategy(\n          bg::srs::spheroid<double>(semi_major, semi_minor)),\n      m_geographic_ll_la_aa_strategy(\n          bg::srs::spheroid<double>(semi_major, semi_minor)) {}\n\nbool Touches::operator()(const Geometry *g1, const Geometry *g2) const {\n  return apply(*this, g1, g2);\n}\n\nbool Touches::operator()(const Box *b1, const Box *b2) const {\n  DBUG_ASSERT(b1->coordinate_system() == b2->coordinate_system());\n  switch (b1->coordinate_system()) {\n    case Coordinate_system::kCartesian:\n      return eval(down_cast<const Cartesian_box *>(b1),\n                  down_cast<const Cartesian_box *>(b2));\n    case Coordinate_system::kGeographic:\n      return eval(down_cast<const Geographic_box *>(b1),\n                  down_cast<const Geographic_box *>(b2));\n  }\n\n  DBUG_ASSERT(false);\n  return false;\n}\n\nbool Touches::eval(const Geometry *g1, const Geometry *g2) const {\n  // All parameter type combinations have been implemented.\n  DBUG_ASSERT(false);\n  throw not_implemented_exception::for_non_projected(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Cartesian_point, *)\n\nbool Touches::eval(const Cartesian_point *, const Cartesian_point *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Cartesian_point *g1,\n                   const Cartesian_linestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_point *g1,\n                   const Cartesian_polygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_point *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Cartesian_point *,\n                   const Cartesian_multipoint *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Cartesian_point *g1,\n                   const Cartesian_multilinestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_point *g1,\n                   const Cartesian_multipolygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Cartesian_linestring, *)\n\nbool Touches::eval(const Cartesian_linestring *g1,\n                   const Cartesian_point *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_linestring *g1,\n                   const Cartesian_linestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_linestring *g1,\n                   const Cartesian_polygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_linestring *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Cartesian_linestring *g1,\n                   const Cartesian_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Cartesian_linestring *g1,\n                   const Cartesian_multilinestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_linestring *g1,\n                   const Cartesian_multipolygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Cartesian_polygon, *)\n\nbool Touches::eval(const Cartesian_polygon *g1,\n                   const Cartesian_point *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_polygon *g1,\n                   const Cartesian_linestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_polygon *g1,\n                   const Cartesian_polygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_polygon *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Cartesian_polygon *g1,\n                   const Cartesian_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Cartesian_polygon *g1,\n                   const Cartesian_multilinestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_polygon *g1,\n                   const Cartesian_multipolygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Cartesian_geometrycollection, *)\n\nbool Touches::eval(const Cartesian_geometrycollection *g1,\n                   const Geometry *g2) const {\n  return geometry_collection_apply_touches<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Cartesian_multipoint, *)\n\nbool Touches::eval(const Cartesian_multipoint *,\n                   const Cartesian_point *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_linestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\nbool Touches::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_polygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\nbool Touches::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Cartesian_multipoint *,\n                   const Cartesian_multipoint *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_multilinestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\nbool Touches::eval(const Cartesian_multipoint *g1,\n                   const Cartesian_multipolygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Cartesian_multilinestring, *)\n\nbool Touches::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_point *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_linestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_polygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_multilinestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multilinestring *g1,\n                   const Cartesian_multipolygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Cartesian_multipolygon, *)\n\nbool Touches::eval(const Cartesian_multipolygon *g1,\n                   const Cartesian_point *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multipolygon *g1,\n                   const Cartesian_linestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multipolygon *g1,\n                   const Cartesian_polygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multipolygon *g1,\n                   const Cartesian_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Cartesian_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Cartesian_multipolygon *g1,\n                   const Cartesian_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Cartesian_multipolygon *g1,\n                   const Cartesian_multilinestring *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\nbool Touches::eval(const Cartesian_multipolygon *g1,\n                   const Cartesian_multipolygon *g2) const {\n  return bg::touches(*g1, *g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Geographic_point, *)\n\nbool Touches::eval(const Geographic_point *, const Geographic_point *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Geographic_point *g1,\n                   const Geographic_linestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\nbool Touches::eval(const Geographic_point *g1,\n                   const Geographic_polygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\nbool Touches::eval(const Geographic_point *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Geographic_point *,\n                   const Geographic_multipoint *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Geographic_point *g1,\n                   const Geographic_multilinestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\nbool Touches::eval(const Geographic_point *g1,\n                   const Geographic_multipolygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Geographic_linestring, *)\n\nbool Touches::eval(const Geographic_linestring *g1,\n                   const Geographic_point *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\nbool Touches::eval(const Geographic_linestring *g1,\n                   const Geographic_linestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_linestring *g1,\n                   const Geographic_polygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_linestring *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Geographic_linestring *g1,\n                   const Geographic_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Geographic_linestring *g1,\n                   const Geographic_multilinestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_linestring *g1,\n                   const Geographic_multipolygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Geographic_polygon, *)\n\nbool Touches::eval(const Geographic_polygon *g1,\n                   const Geographic_point *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\nbool Touches::eval(const Geographic_polygon *g1,\n                   const Geographic_linestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_polygon *g1,\n                   const Geographic_polygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_polygon *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Geographic_polygon *g1,\n                   const Geographic_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Geographic_polygon *g1,\n                   const Geographic_multilinestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_polygon *g1,\n                   const Geographic_multipolygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Geographic_geometrycollection, *)\n\nbool Touches::eval(const Geographic_geometrycollection *g1,\n                   const Geometry *g2) const {\n  return geometry_collection_apply_touches<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Geographic_multipoint, *)\n\nbool Touches::eval(const Geographic_multipoint *,\n                   const Geographic_point *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Geographic_multipoint *g1,\n                   const Geographic_linestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2, m_geographic_pl_pa_strategy);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\nbool Touches::eval(const Geographic_multipoint *g1,\n                   const Geographic_polygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2, m_geographic_pl_pa_strategy);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\nbool Touches::eval(const Geographic_multipoint *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Geographic_multipoint *,\n                   const Geographic_multipoint *) const {\n  // If dim(g1) == 0 and dim(g2) == 0, return NULL (SQL/MM 2015 Part 3,\n  // Sect. 5.1.50).\n  throw null_value_exception();\n}\n\nbool Touches::eval(const Geographic_multipoint *g1,\n                   const Geographic_multilinestring *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2, m_geographic_pl_pa_strategy);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\nbool Touches::eval(const Geographic_multipoint *g1,\n                   const Geographic_multipolygon *g2) const {\n  Within within(m_semi_major, m_semi_minor);\n  bool touches = false;\n\n  // At least one point in g1 has to touch g2, and none of the points in g1\n  // may be within g2.\n  for (auto &pt : *g1) {\n    bool pt_touches = false;\n    if (!touches) {\n      pt_touches = bg::touches(pt, *g2, m_geographic_pl_pa_strategy);\n      touches = pt_touches;\n    }\n    if (!pt_touches) {\n      if (within(&pt, g2)) return false;\n    }\n  }\n\n  return touches;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Geographic_multilinestring, *)\n\nbool Touches::eval(const Geographic_multilinestring *g1,\n                   const Geographic_point *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\nbool Touches::eval(const Geographic_multilinestring *g1,\n                   const Geographic_linestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_multilinestring *g1,\n                   const Geographic_polygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_multilinestring *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Geographic_multilinestring *g1,\n                   const Geographic_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Geographic_multilinestring *g1,\n                   const Geographic_multilinestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_multilinestring *g1,\n                   const Geographic_multipolygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// touches(Geographic_multipolygon, *)\n\nbool Touches::eval(const Geographic_multipolygon *g1,\n                   const Geographic_point *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_pl_pa_strategy);\n}\n\nbool Touches::eval(const Geographic_multipolygon *g1,\n                   const Geographic_linestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_multipolygon *g1,\n                   const Geographic_polygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_multipolygon *g1,\n                   const Geographic_geometrycollection *g2) const {\n  return geometry_collection_apply_touches<Geographic_geometrycollection>(\n      *this, g1, g2);\n}\n\nbool Touches::eval(const Geographic_multipolygon *g1,\n                   const Geographic_multipoint *g2) const {\n  return eval(g2, g1);\n}\n\nbool Touches::eval(const Geographic_multipolygon *g1,\n                   const Geographic_multilinestring *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\nbool Touches::eval(const Geographic_multipolygon *g1,\n                   const Geographic_multipolygon *g2) const {\n  return bg::touches(*g1, *g2, m_geographic_ll_la_aa_strategy);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\n// equals(Box, Box)\n\nbool Touches::eval(const Cartesian_box *b1, const Cartesian_box *b2) const {\n  if (mbr_is_point(*b1)) {\n    if (mbr_is_point(*b2)) {\n      // For two geometries to touch, the interior must not intersect. If\n      // g1 and g2 are points, the MBRs will either be disjoint or\n      // equal. Hence, point-point mbr_touches is always false.\n      return false;\n    }\n\n    if (mbr_is_line(*b2)) {\n      return (b1->min_corner().x() == b2->min_corner().x() &&\n              b1->min_corner().y() == b2->min_corner().y()) ||\n             (b1->min_corner().x() == b2->max_corner().x() &&\n              b1->min_corner().y() == b2->max_corner().y());\n    }\n\n    return bg::touches(*b1, *b2);\n  }\n\n  if (mbr_is_line(*b1)) {\n    if (mbr_is_point(*b2)) {\n      return (b2->min_corner().x() == b1->min_corner().x() &&\n              b2->min_corner().y() == b1->min_corner().y()) ||\n             (b2->min_corner().x() == b1->max_corner().x() &&\n              b2->min_corner().y() == b1->max_corner().y());\n    }\n\n    if (mbr_is_line(*b2)) {\n      Cartesian_point b1_ls_start(b1->min_corner().x(), b1->min_corner().y());\n      Cartesian_point b1_ls_end(b1->max_corner().x(), b1->max_corner().y());\n      Cartesian_linestring b1_ls;\n      b1_ls.push_back(b1_ls_start);\n      b1_ls.push_back(b1_ls_end);\n\n      Cartesian_point b2_ls_start(b2->min_corner().x(), b2->min_corner().y());\n      Cartesian_point b2_ls_end(b2->max_corner().x(), b2->max_corner().y());\n      Cartesian_linestring b2_ls;\n      b2_ls.push_back(b2_ls_start);\n      b2_ls.push_back(b2_ls_end);\n\n      return eval(&b1_ls, &b2_ls);\n    }\n\n    return bg::touches(*b1, *b2);\n  }\n\n  return bg::touches(b1, b2);\n}\n\nbool Touches::eval(const Geographic_box *b1, const Geographic_box *b2) const {\n  if (mbr_is_point(*b1)) {\n    if (mbr_is_point(*b2)) {\n      // For two geometries to touch, the interior must not intersect. If\n      // g1 and g2 are points, the MBRs will either be disjoint or\n      // equal. Hence, point-point mbr_touches is always false.\n      return false;\n    }\n\n    if (mbr_is_line(*b2)) {\n      return (b1->min_corner().x() == b2->min_corner().x() &&\n              b1->min_corner().y() == b2->min_corner().y()) ||\n             (b1->min_corner().x() == b2->max_corner().x() &&\n              b1->min_corner().y() == b2->max_corner().y());\n    }\n\n    return bg::touches(*b1, *b2);\n  }\n\n  if (mbr_is_line(*b1)) {\n    if (mbr_is_point(*b2)) {\n      return (b2->min_corner().x() == b1->min_corner().x() &&\n              b2->min_corner().y() == b1->min_corner().y()) ||\n             (b2->min_corner().x() == b1->max_corner().x() &&\n              b2->min_corner().y() == b1->max_corner().y());\n    }\n\n    if (mbr_is_line(*b2)) {\n      Geographic_point b1_ls_start(b1->min_corner().x(), b1->min_corner().y());\n      Geographic_point b1_ls_end(b1->max_corner().x(), b1->max_corner().y());\n      Geographic_linestring b1_ls;\n      b1_ls.push_back(b1_ls_start);\n      b1_ls.push_back(b1_ls_end);\n\n      Geographic_point b2_ls_start(b2->min_corner().x(), b2->min_corner().y());\n      Geographic_point b2_ls_end(b2->max_corner().x(), b2->max_corner().y());\n      Geographic_linestring b2_ls;\n      b2_ls.push_back(b2_ls_start);\n      b2_ls.push_back(b2_ls_end);\n\n      return eval(&b1_ls, &b2_ls);\n    }\n\n    return bg::touches(*b1, *b2);\n  }\n\n  return bg::touches(*b1, *b2);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n\nbool touches(const dd::Spatial_reference_system *srs, const Geometry *g1,\n             const Geometry *g2, const char *func_name, bool *touches,\n             bool *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 ((*null = (g1->is_empty() || g2->is_empty()))) return false;\n\n    Touches touches_func(srs ? srs->semi_major_axis() : 0.0,\n                         srs ? srs->semi_minor_axis() : 0.0);\n    *touches = touches_func(g1, g2);\n  } catch (const null_value_exception &) {\n    *null = true;\n    return false;\n  } catch (...) {\n    handle_gis_exception(func_name);\n    return true;\n  }\n\n  return false;\n}\n\nbool mbr_touches(const dd::Spatial_reference_system *srs, const Geometry *g1,\n                 const Geometry *g2, const char *func_name, bool *touches,\n                 bool *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 ((*null = (g1->is_empty() || g2->is_empty()))) return false;\n\n    Touches touches_func(srs ? srs->semi_major_axis() : 0.0,\n                         srs ? srs->semi_minor_axis() : 0.0);\n\n    switch (g1->coordinate_system()) {\n      case Coordinate_system::kCartesian: {\n        Cartesian_box mbr1;\n        box_envelope(g1, srs, &mbr1);\n        Cartesian_box mbr2;\n        box_envelope(g2, srs, &mbr2);\n        *touches = touches_func(&mbr1, &mbr2);\n        break;\n      }\n      case Coordinate_system::kGeographic: {\n        Geographic_box mbr1;\n        box_envelope(g1, srs, &mbr1);\n        Geographic_box mbr2;\n        box_envelope(g2, srs, &mbr2);\n        *touches = touches_func(&mbr1, &mbr2);\n        break;\n      }\n    }\n  } catch (...) {\n    handle_gis_exception(func_name);\n    return true;\n  }\n\n  return false;\n}\n\n}  // namespace gis\n", "meta": {"hexsha": "c848e6e565254ef6b6bb3287540d493b5defcd8f", "size": 47569, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mysql-server/sql/gis/touches.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/touches.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/touches.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": 36.6479198767, "max_line_length": 83, "alphanum_fraction": 0.5759423154, "num_tokens": 11693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339458, "lm_q2_score": 0.016657040314322573, "lm_q1q2_score": 0.005807396074649984}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstring>\n#include <stdio.h>\n#include <cstdlib>\n#include <unistd.h>\n#include <stdlib.h>\n#include <math.h>\n#include <boost/thread.hpp>\n\n\nusing namespace std;\nint steps1 = 0;\nint steps2 = 0;\nint steps3 = 0;\nint steps4 = 0;\n\nint stp1_1a = 47;\nint stp1_1b = 46;\nint stp1_2a = 27;\nint stp1_2b = 65;\n\nint stp2_1a = 66;\nint stp2_1b = 69;\nint stp2_2a = 45;\nint stp2_2b = 23;\n\nint stp3_1a = 67;\nint stp3_1b = 68;\nint stp3_2a = 44;\nint stp3_2b = 26;\n\nint stp4_1a = 30;\nint stp4_1b = 60;\nint stp4_2a = 31;\nint stp4_2b = 50;\n\nint global_ms=7;\nfloat inchtocm=25.4;\nint inch;\n\nFILE *export_file = NULL;\nFILE *IO_direction = NULL;\n\nint direction[6];\nstring str123[2];\n//float dist[2];\nfloat extruder1=0;\nint ttime = 0;\nfloat multi = 1;\n/*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/\nvoid pinexport(int a)\n{//exports pin number a\n\n\n\tchar str[100];       //value to pass to export file\n\tsprintf(str, \"%d\", a);\n\n\texport_file = fopen(\"/sys/class/gpio/export\", \"w\");\n\tfwrite(str, 1, sizeof(str), export_file);\n\tfclose(export_file);\n\tprintf(\"Exported pin %d\\n\", a);\n\n}\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nvoid pinwrite(int a, int b)\n{\n\t///// pinwrite(pin,value)/////\n\n\tchar str[100];\n\tchar str1[] = \"low\";\n\tchar str2[] = \"high\";\n\n\n\tsprintf(str, \"/sys/class/gpio/gpio%d/direction\", a);\n\n\tIO_direction = fopen(str, \"w\");\n\n\tif (b == 0)\n\t{\n\t\tfwrite(str1, 1, sizeof(str1), IO_direction);   //set the pin to LOW\n\t}\n\telse if (b == 1)\n\t{\n\t\tfwrite(str2, 1, sizeof(str2), IO_direction);   //set the pin to HIGH\n\t}\n\tfclose(IO_direction);\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/\nvoid incstepperx()\n{\n\tint a, b, c, d, stp;\n\n\ta = stp1_1a;\n\tb = stp1_1b;\n\tc = stp1_2a;\n\td = stp1_2b;\n\n\tstp = steps1;\n\n\n\tif (direction[1] == 1)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 2;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 0;\n\t\t}\n\n\t\t//printf(\"\\t\\t\\t\\t\\t\\t\\tstep1=%d\\n\",steps1);\n\n\t\tsteps1 = stp;\n\t}\n\telse if (direction[1] == 0)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 0;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 2;\n\t\t}\n\t\t//printf(\"\\t\\t\\t\\t\\t\\t\\tstep1=%d\\n\",steps1);\n\t\tsteps1 = stp;\n\n\t}\n\t//usleep(10);\n}\n/*YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY*/\nvoid incsteppery()\n{\n\tint a, b, c, d, stp;\n\n\ta = stp2_1a;\n\tb = stp2_1b;\n\tc = stp2_2a;\n\td = stp2_2b;\n\n\tstp = steps2;\n\n\tif (direction[2] == 1)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 2;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 0;\n\t\t}\n\t\t//printf(\"\\t\\t\\t\\t\\t\\t\\t\\tstep2=%d\\n\",steps2);\n\n\t\tsteps2 = stp;\n\t}\n\telse if (direction[2] == 0)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 0;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 2;\n\t\t}\n\t\t//printf(\"\\t\\t\\t\\t\\t\\t\\t\\tstep2=%d\\n\",steps2);\n\n\t\tsteps2 = stp;\n\t}\n\t//usleep(10);\n}\n/*ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ*/\nvoid incstepperz()\n{\n\tint a, b, c, d, stp;\n\t//printf(\"Direction_3==%d\\t%d\\n\",direction[3],steps3);\n\ta = stp3_1a;\n\tb = stp3_1b;\n\tc = stp3_2a;\n\td = stp3_2b;\n\n\tstp = steps3;\n\n\n\tif (direction[3] == 1)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 2;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 0;\n\t\t}\n\n\t\t//\tprintf(\"\\t\\t\\t\\t\\t\\t\\tstep3=%d\\n\",steps3);\n\n\t\tsteps3 = stp;\n\t}\n\telse if (direction[3] == 0)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 0;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 2;\n\t\t}\n\t\t//printf(\"\\t\\t\\t\\t\\t\\t\\tstep3=%d\\n\",steps3);\n\t\tsteps3 = stp;\n\n\t}\n\t//usleep(10);\n}\n/*EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE1111111111111111111111111111111111111111*/\nvoid incsteppere()\n{\n\tint a, b, c, d, stp;\n\t//printf(\"Direction_4==%d\\t%d\\n\",direction[4],steps4);\n\ta = stp4_1a;\n\tb = stp4_1b;\n\tc = stp4_2a;\n\td = stp4_2b;\n\n\tstp = steps4;\n\n\n\tif (direction[4] == 1)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 2;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 0;\n\t\t}\n\n\t\t//\tprintf(\"\\t\\t\\t\\t\\t\\t\\tstep3=%d\\n\",steps3);\n\n\t\tsteps4 = stp;\n\t}\n\telse if (direction[4] == 0)\n\t{\n\t\tif (stp == 0)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 3;\n\t\t}\n\t\telse if (stp == 1)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 1);\n\t\t\tpinwrite(d, 0);\n\t\t\tstp = 0;\n\t\t}\n\t\telse if (stp == 2)\n\t\t{\n\t\t\tpinwrite(a, 0);\n\t\t\tpinwrite(b, 1);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 1;\n\t\t}\n\t\telse if (stp == 3)\n\t\t{\n\t\t\tpinwrite(a, 1);\n\t\t\tpinwrite(b, 0);\n\t\t\tpinwrite(c, 0);\n\t\t\tpinwrite(d, 1);\n\t\t\tstp = 2;\n\t\t}\n\t\t//printf(\"\\t\\t\\t\\t\\t\\t\\tstep4=%d\\n\",steps4);\n\t\tsteps4 = stp;\n\n\t}\n\t//usleep(10);\n}\n\n/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\nvoid stepper(int num, float dist, int time) /*num from 1 to 3; dist in mm; time in usec */\n{\n\tprintf(\"num=%d\\tdist= %f\\ttime= %d\\t\", num, dist, time);\n\n\tif ((dist <= 0.00001) && (dist >= -0.00001))\n\t{\n\t\tprintf(\"Dist zero for %d motor\\n\", num);\n\t\treturn;\n\t}\n\tif (dist<0)\n\t{\n\t\tdirection[num] = 0; //reverse\n\t\tdist = fabs(dist);\n\t}\n\telse\n\t\tdirection[num] = 1;//forward\n\n\tif (dist != 0)\n\t{\n\t\tint stps;\n\t\tfloat t;\n\t\tfloat rstps = (dist * 25) - 0.5;\n\t\tstps = ceil(rstps);\n\t\n\t\tint t1;\n\t\tif (stps != 0)\n\t\t{\n\t\t\tt = (float)time / (float)stps;\n\t\t\tt1 = ceil(t * 1000 - 0.5);\n\t\t}\n\t\telse t1 = 10001;\n\t\t//printf(\"%f\\n\",t);\n\t\t\t\tprintf(\"\\t\\tmotor:%d ,  %d steps, %d time\\n\", num, stps, t1);\n\n\t\t\tfor (int i = 0; i<stps; i++)\n\t\t\t{\n\n\t\t\t\tif (num == 1) { incstepperx(); }\n\t\t\t\telse if (num == 2) { incsteppery(); }\n\t\t\t\telse if (num == 3) { incstepperz(); }\n\t\t\t\telse if (num == 4) { incsteppere(); }\n\n\t\t\t\tusleep(t1);\n\n\t\t\t}\n\t\t\t//printf(\"Moved Motor %d in direction %d for distance of %f mm, %d steps with step time %d micro sec.\\n\\n\", num, direction[num], dist, stps, t1);\n\t\n\t\t//else\n\t\t//printf(\"time too small for %d\\nCalulated time: %f\\nFor %f mm, time must be %f sec\\n\",num,t*1000,dist,(float)stps/100); \n\t}\n\n}\n\nvoid clearall()\n{\n\tpinwrite(stp1_1a, 0);\n\tpinwrite(stp1_1b, 0);\n\tpinwrite(stp1_2a, 0);\n\tpinwrite(stp1_2b, 0);\n\n\tpinwrite(stp2_1a, 0);\n\tpinwrite(stp2_1b, 0);\n\tpinwrite(stp2_2a, 0);\n\tpinwrite(stp2_2b, 0);\n\n\tpinwrite(stp3_1a, 0);\n\tpinwrite(stp3_1b, 0);\n\tpinwrite(stp3_2a, 0);\n\tpinwrite(stp3_2b, 0);\n\n\tpinwrite(stp4_1a, 0);\n\tpinwrite(stp4_1b, 0);\n\tpinwrite(stp4_2a, 0);\n\tpinwrite(stp4_2b, 0);\n\n}\n\nvoid movex(float f)\n{\n\t//printf(\"1\\t%f\\n\",f);\n\tstepper(1, f, ttime);\n}\n\nvoid movey(float f)\n{\n\n\t//printf(\"\\t2\\t%f\\n\",f);\n\tstepper(2, f, ttime);\n\n}\n\nvoid movee(float e)\n{\n\nextruder1=e+extruder1;\nif((extruder1>=0.021)||(extruder1<=-0.021))\n{stepper(4, extruder1, ttime);\nextruder1=0;\n}\n//printf(\"/t/t/t/t/tetr1=%f\\n\",extruder1);\n\n}\n\nvoid multithread(float dist1, float dist2, float e, int time)\n{\n\n\tint k = time;\n\tttime = time;\n\n\t//dist[1]=dist1;\n\t//dist[2]=dist2;\n\n\t//printf(\"Motor 1 will rotate for %f mm and motor 2 for %f mm in %f sec\\n\",dist1,dist2,(float)k/1000);\n\n\tboost::thread th1(&movex, dist1);\n\tboost::thread th2(&movey, dist2);\n\tboost::thread th3(&movee, e);\n\n\n\tth1.join();\n\tth2.join();\n\tth3.join();\n\n\tclearall();\n}\n\n/*GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG*/\n//void g23(int n, float x, float y, float X, float Y,float i,float j)\n//{printf(\"Gcode: %d x=%f y=%f X=%f Y=%f I=%f J=%f\\n\",n,x,y,X,Y,i,j);}\n\n\nvoid g23(int n, float x, float y, float X, float Y, float i, float j, float e)\n{\n\t//int n;\n\t//float x=0, y=0; //current coordinates\n\t//float X=10, Y=10; //destination coordinates\n\t//float i=10, j=0; //distance from x,y to centre\n\tfloat a = 0, b = 0; //centre coordinates\n\tfloat r = 0; //radius\n\tfloat R = 0;\n\tfloat pi = 3.14159;\n\tfloat theta1 = 0;\n\tfloat theta2 = 0;\n\tfloat beta = 0;\n\tfloat alpha = 0;\n\tfloat z = 0;\n\tfloat steps = 0;\n\tfloat p = 10;//number of steps per mm\n\tint s = 0;\n\tfloat stepper_x;\n\tfloat stepper_y;\n\tint time;\n\tfloat abs_stepperx, abs_steppery;\n\tfloat xold = x, yold = y;\n\n\ta = x + i;\n\tb = y + j;\n\n\tr = sqrt(i*i + j*j);\n\tR = 4 * p * r;\n\n\tif (j != 0)\n\t{\n\t\tz = fabs(i / j);\n\t\tbeta = atan(z);\n\t}\n\telse\n\t{\n\t\tbeta = pi;\n\t}\n\n\tif (n == 2)\n\t{\n\t\tif (i >= 0 && j > 0)//1\n\t\t{\n\t\t\talpha = 3 * pi / 2 - beta;\n\t\t\tif (X <= a && Y > y)\n\t\t\t{\n\t\t\t\tsteps = (Y - y) * p;\n\t\t\t}\n\t\t\telse if (X >= a)\n\t\t\t{\n\t\t\t\tsteps = ((r + j) + (2 * r - (Y - (b - r)))) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a && Y <= y)\n\t\t\t{\n\t\t\t\tsteps = ((r + j) + 2 * r + (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (i >= 0 && j < 0)//2\n\t\t{\n\t\t\talpha = pi / 2 + beta;\n\t\t\tif (X <= a && Y > y)\n\t\t\t{\n\t\t\t\tsteps = (Y - y) * p*multi;\n\t\t\t}\n\t\t\telse if (X >= a)\n\t\t\t{\n\t\t\t\tsteps = ((b + r - y) + (2 * r - (Y - (b - r)))) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a && Y <= y)\n\t\t\t{\n\t\t\t\tsteps = ((b + r - y) + 2 * r + (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (i <= 0 && j > 0)//3\n\t\t{\n\t\t\talpha = 3 * pi / 2 + beta;\n\t\t\tif (X >= a && Y < y)\n\t\t\t{\n\t\t\t\tsteps = (y - Y) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a)\n\t\t\t{\n\t\t\t\tsteps = ((y - (b - r)) + 2 * r - (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t\telse if (X >= a && Y >= y)\n\t\t\t{\n\t\t\t\tsteps = ((y - (b - r)) + 2 * r + (b + r - Y)) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (j == 0 && i > 0)//4\n\t\t{\n\t\t\talpha = pi;\n\t\t\tif (X <= a && Y > y)\n\t\t\t{\n\t\t\t\tsteps = (Y - y) * p*multi;\n\t\t\t}\n\t\t\telse if (X >= a)\n\t\t\t{\n\t\t\t\tsteps = (r + 2 * r - (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a && Y <= y)\n\t\t\t{\n\t\t\t\tsteps = (3 * r + (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (j == 0 && i < 0)//5\n\t\t{\n\t\t\talpha = 0;\n\t\t\tif (X >= a && Y < y)\n\t\t\t{\n\t\t\t\tsteps = (y - Y) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a)\n\t\t\t{\n\t\t\t\tsteps = (y - (b - r) + 2 * r - (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsteps = (3 * r + (b + r - Y)) * p*multi;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (n == 3)\n\t{\n\t\tif (i >= 0 && j > 0)//1\n\t\t{\n\t\t\talpha = 3 * pi / 2 - beta;\n\t\t\tif (X <= a && Y < y)\n\t\t\t{\n\t\t\t\tsteps = (y - Y) * p*multi;\n\t\t\t}\n\t\t\telse if (X >= a)\n\t\t\t{\n\t\t\t\tsteps = ((y - (b - r)) + (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a && Y >= y)\n\t\t\t{\n\t\t\t\tsteps = ((y - (b - r)) + 2 * r + (b + r - Y)) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (i >= 0 && j < 0)//2\n\t\t{\n\t\t\talpha = pi / 2 + beta;\n\t\t\tif (X <= a && Y < y)\n\t\t\t{\n\t\t\t\tsteps = (y - Y) * p*multi;\n\t\t\t}\n\t\t\telse if (X >= a)\n\t\t\t{\n\t\t\t\tsteps = ((y - (b - r)) + (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a && Y >= y)\n\t\t\t{\n\t\t\t\tsteps = ((y - (b - r)) + 2 * r + (b + r - Y)) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (i <= 0 && j > 0)//3\n\t\t{\n\t\t\talpha = 3 * pi / 2 + beta;\n\t\t\tif (X >= a && Y > y)\n\t\t\t{\n\t\t\t\tsteps = (Y - y) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a)\n\t\t\t{\n\t\t\t\tsteps = ((b + r - y) + (b + r - Y)) * p*multi;\n\t\t\t}\n\t\t\telse if (X >= a && Y <= y)\n\t\t\t{\n\t\t\t\tsteps = ((b + r - y) + 2 * r + (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (j == 0 && i > 0)//4\n\t\t{\n\t\t\talpha = pi;\n\t\t\tif (X <= a && Y < y)\n\t\t\t{\n\t\t\t\tsteps = (y - Y) * p*multi;\n\t\t\t}\n\t\t\telse if (X >= a)\n\t\t\t{\n\t\t\t\tsteps = (r + Y - (b - r)) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a && Y >= y)\n\t\t\t{\n\t\t\t\tsteps = (3 * r + (b + r - Y)) * p*multi;\n\t\t\t}\n\t\t}\n\n\t\telse if (j == 0 && i < 0)//5\n\t\t{\n\t\t\talpha = 0;\n\t\t\tif (X >= a && Y > y)\n\t\t\t{\n\t\t\t\tsteps = (Y - y) * p*multi;\n\t\t\t}\n\t\t\telse if (X <= a)\n\t\t\t{\n\t\t\t\tsteps = (r + b + r - Y) * p*multi;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsteps = (3 * r + (Y - (b - r))) * p*multi;\n\t\t\t}\n\t\t}\n\t}\n\te = e / steps;\n\tfor (s = 0; s <= steps; s++)\n\t{\n\t\t//if(G2)\n\t\ttheta1 = (alpha - ((2 * pi* s) / (R)));\n\t\ttheta2 = (alpha + ((2 * pi*s) / (R)));\n\t\tif (n == 2)\n\t\t{\n\t\t\tstepper_x = a + r*cos(theta1);\n\t\t\tstepper_y = b + r*sin(theta1);\n\t\t}\n\n\t\telse if (n == 3)\n\t\t{\n\t\t\tstepper_x = a + r*cos(theta2);\n\t\t\tstepper_y = b + r*sin(theta2);\n\n\t\t}\n\t\t//\n\n\t\tstepper_x = stepper_x - xold; stepper_y = stepper_y - yold;\n\t\txold = stepper_x + xold; yold = stepper_y + yold;\n\n\n\t\tabs_stepperx = fabs(stepper_x);\n\t\tabs_steppery = fabs(stepper_y);\n\t\tif (abs_stepperx>abs_steppery) { abs_stepperx = (abs_stepperx * 25*global_ms) - 0.5; time = ceil(abs_stepperx); }\n\t\telse { abs_steppery = (abs_steppery * 25*global_ms) - 0.5; time = ceil(abs_steppery); }\n\n\n\t\tmultithread(stepper_x, stepper_y, e, time);\n\n\t\t//printf(\"dist_x==%f\\tdist_y==%f\\tin time==%d\\n\",stepper_x,stepper_y,time);\n\t}\n\n}\n\n\n/*LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL*/\nvoid plot_line(float X, float Y, float x, float y, float e)\n{\n\tprintf(\"#############################################################################\\n##################################################################\\n\");\n\tprintf(\"from X= %f to %f and Y= %f to %f with E= %e\\n\", x, X, y, Y,e);\nprintf(\"#############################################################################\\n##################################################################\\n\");\n\t\n\tfloat stepper_x_old = x, stepper_y_old = y, stepper_x1, stepper_y1;\n\tfloat m;\n\tfloat n = 0;\n\tfloat c;\n\tfloat i = 0;\n\tfloat j = 0;\n\tint steps1 = 0;\n\tfloat x1, y1;\n\tint time;\n\n\tfloat steps = 0;\n\tint s = 0;\n\tfloat p = 1;//number of steps per mm\n\tfloat stepper_x = x;\n\tfloat stepper_y = y;\n\n\tm = (Y - y) / (X - x);\n\ti = X - x;\n\tj = Y - y;\n\tc = y - m*x;\n\n\tif (j != 0)\n\t{\n\t\tsteps = fabs(j*multi*p);\n\t}\n\telse\n\t{\n\t\tsteps = fabs(i*multi*p);\n\t}\n\tsteps1 = ceil(steps - 0.5);\n\te = e / (steps1 + 1);\n\tfor (s = 0; s < steps1; s++)\n\t{\n\t\tif (j != 0)\n\t\t{\n\t\t\tif (j > 0)\n\t\t\t{\n\t\t\t\tn = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tn = -1;\n\t\t\t}\n\t\t\tif (i != 0)\n\t\t\t{\n\t\t\t\tstepper_y = stepper_y + (n * 1/(p*multi));\n\t\t\t\tstepper_x = (stepper_y - c) / m;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstepper_y = stepper_y + (n * 1/(p*multi));\n\t\t\t\tstepper_x = x;\n\t\t\t}\n\t\t}\n\t\telse if (j == 0)\n\t\t{\n\t\t\tif (i > 0)\n\t\t\t{\n\t\t\t\tn = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tn = -1;\n\t\t\t}\n\t\t\tstepper_x = stepper_x + (n * 1/(p*multi));\n\t\t\tstepper_y = y;\n\t\t}\n\n\n\t\t//abs\n\n\t\tstepper_x1 = stepper_x; stepper_y1 = stepper_y;\n\t\tstepper_x1 = stepper_x1 - stepper_x_old; stepper_y1 = stepper_y1 - stepper_y_old;\n\t\tstepper_x_old = stepper_x1 + stepper_x_old; stepper_y_old = stepper_y1 + stepper_y_old;\n\n\t\tx1 = abs(stepper_x1);\n\t\ty1 = abs(stepper_y1);\n\t\tif (x1>y1) { x1 = (x1 * 25*global_ms) - 0.5; time = ceil(x1); }\n\t\telse { y1 = (y1 * 25*global_ms) - 0.5; time = ceil(y1); }\n\n\n\n\t\tprintf(\"### xold=%f Yold=%f    x=%f y=%f \\te=%f steps:%d\\n\", stepper_x_old, stepper_y_old, stepper_x1, stepper_y1,e,steps1+1);\n\t\tmultithread(stepper_x1, stepper_y1, e, time);\n\n\t}\n\tstepper_x = X;\n\tstepper_y = Y;\n\n\tstepper_x1 = stepper_x; stepper_y1 = stepper_y;\n\tstepper_x1 = stepper_x1 - stepper_x_old; stepper_y1 = stepper_y1 - stepper_y_old;\n\tstepper_x_old = stepper_x1 + stepper_x_old; stepper_y_old = stepper_y1 + stepper_y_old;\n\n\tx1 = abs(stepper_x1);\n\ty1 = abs(stepper_y1);\n\tif (x1>y1) { x1 = (x1 * 25*global_ms) - 0.5; time = ceil(x1); }\n\telse { y1 = (y1 * 25*global_ms) - 0.5; time = ceil(y1); }\n\n\tmultithread(stepper_x1, stepper_y1, e, time);\n\n\tprintf(\"##################enddd###########################################################\\n##################################################################\\n\");\n\n}\n\n/*GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG*/\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nint main(int argc, char* argv[])\n{\n\tfloat i, j;\n\tint k;\n\n\tpinexport(stp1_1a); //stepper1 input1a\n\tpinexport(stp1_1b); //stepper1 input1b\n\tpinexport(stp1_2a); //stepper1 input2a\n\tpinexport(stp1_2b); //stepper1 input1b\n\n\tpinexport(stp2_1a); //stepper2 input1a\n\tpinexport(stp2_1b); //stepper2 input1b\n\tpinexport(stp2_2a); //stepper2 input2a\n\tpinexport(stp2_2b); //stepper2 input1b\n\n\tpinexport(stp3_1a); //stepper3 input1a\n\tpinexport(stp3_1b); //stepper3 input1b\n\tpinexport(stp3_2a); //stepper3 input2a\n\tpinexport(stp3_2b); //stepper3 input1b\n\n\tpinexport(stp4_1a); //stepper3 input1a\n\tpinexport(stp4_1b); //stepper3 input1b\n\tpinexport(stp4_2a); //stepper3 input2a\n\tpinexport(stp4_2b); //stepper3 input1b\n\n\n\tstring line;\n\tchar linec[100];\n\tint lineno = 0;\n\n\tstring str1, str2, str3, strI, strJ, strtmp, strE;\n\n\tchar x_coord[10], tmprry;\n\tchar y_coord[10];\n\tchar z_coord[10];\n\tchar i_coord[10];\n\tchar j_coord[10];\n\tchar e_coord[10];\n\n\tstrcpy(x_coord, \"X0\");\n\tstrcpy(y_coord, \"Y0\");\n\tstrcpy(z_coord, \"Z0\");\n\tstrcpy(i_coord, \"I0\");\n\tstrcpy(j_coord, \"J0\");\n\tstrcpy(e_coord, \"E0\");\n\n\tfloat circle_i = 0, circle_j = 0, extru = 0;\n\tfloat x = 0, y = 0, x1 = 0, y1 = 0, z = 0, z1 = 0, e = 0, e1 = 0;\n\tint a = 0, b = 0;\n\tint gcode = 999;\n\tchar * pch;\n\tint time = 0;\n\n\tfloat xold = 0;\n\tfloat yold = 0;\n\tfloat zold = 0;\n\tfloat eold = 0;\n\n\tint is_z = 0;\n\tifstream myfile(\"/var/www/html/Upload/sample.gcode\");\n\tif (myfile.is_open())\n\t{\n\t\twhile (getline(myfile, line)) //string: line // char linec\n\t\t{\n\t\t\tlineno++;\n\t\t\tstrcpy(linec, line.c_str());\n\n\n\n\t\t\tpch = strtok(linec, \" \");\n\t\t\twhile (pch != NULL)\n\t\t\t{\n\n\t\t\t\t/*///////////////////////////////////////////////////////////////////////////////////////////*/\n\n\t\t\t\tif (pch[0] == 'G') {\n\t\t\t\t\tcout << pch << endl;\n\n\t\t\t\t\tif (strlen(pch) == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (pch[1] == '1')\n\t\t\t\t\t\t\tgcode = 1;\n\t\t\t\t\t\telse if (pch[1] == '0')\n\t\t\t\t\t\t\tgcode = 0;\n\n\t\t\t\t\t\telse if (pch[1] == '2')\n\t\t\t\t\t\t\tgcode = 2;\n\t\t\t\t\t\telse if (pch[1] == '3')\n\t\t\t\t\t\t\tgcode = 3;\n\n\n\n\t\t\t\t\t}\n\t\t\t\t\telse if (strlen(pch) == 3)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((pch[1] == '0') && (pch[2] == '1'))\n\t\t\t\t\t\t\tgcode = 1;\n\t\t\t\t\t\telse if ((pch[1] == '0') && (pch[2] == '0'))\n\t\t\t\t\t\t\tgcode = 0;\n\t\t\t\t\t\telse if ((pch[1] == '0') && (pch[2] == '2'))\n\t\t\t\t\t\t\tgcode = 2;\n\t\t\t\t\t\telse if ((pch[1] == '0') && (pch[2] == '3'))\n\t\t\t\t\t\t\tgcode = 3;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pch[0] == 'X') { strcpy(x_coord, pch); }\n\t\t\t\tif (pch[0] == 'Y') { strcpy(y_coord, pch); }\n\t\t\t\tif (pch[0] == 'Z') { strcpy(z_coord, pch); is_z = 1; }\n\t\t\t\telse { z = zold; is_z = 0; }\n\t\t\t\tif (pch[0] == 'I') { strcpy(i_coord, pch); }\n\t\t\t\tif (pch[0] == 'J') { strcpy(j_coord, pch); }\n\t\t\t\tif (pch[0] == 'E') { strcpy(e_coord, pch); }\n\n\n\n\n\t\t\t\tpch = strtok(NULL, \" \");\n\t\t\t}\n\t\t\t/*///////////////////////////////////////////////////////////////////////////////////////////*/\n\t\t\tstr1 = x_coord; str1 = str1.substr(1); x = atof(str1.c_str());\n\t\t\tstr2 = y_coord; str2 = str2.substr(1); y = atof(str2.c_str());\n\t\t\tstr3 = z_coord; str3 = str3.substr(1); z = atof(str3.c_str());\n\t\t\tstrI = i_coord; strI = strI.substr(1); circle_i = atof(strI.c_str());\n\t\t\tstrJ = j_coord; strJ = strJ.substr(1); circle_j = atof(strJ.c_str());\n\t\t\tstrE = e_coord; strE = strE.substr(1); e = atof(strE.c_str());\n/*\nmulti=10;\nx=x*inchtocm;\n//xold=xold*inchtocm;\ny=y*inchtocm;\n//yold=yold*inchtocm;\nz=z*inchtocm;\n//zold=zold*inchtocm;\ne=e*inchtocm;\n//eold=eold*inchtocm;\n*/\ncout << \"x=\" << x << \"xold=\" << xold << endl;\n\n\t\t\tx = x - xold; y = y - yold; e = e - eold; \n\t\t\txold = x + xold; yold = y + yold; eold = e + eold;\n\t\t\t//eold = dist_after\n\t\t\t//e=0.displacement\t\n\t\t\tif (is_z == 1)\n\t\t\t{\n\n\t\t\t\tz = z - zold;\n\t\t\t\tzold = z + zold;\n\n\t\t\t}\n\t\t\tprintf(\"Gcode: %d X=%f Y=%f Z=%f I=%f J=%f E=%f\", gcode, x, y, z, circle_i, circle_j, extruder1);\n\n\t\t\t//\n\t\t\tif (is_z == 1) { printf(\"Z= %f\\n\", z); }\n\t\t\telse printf(\"\\n\");\n\nif (gcode == 20)\n{\ninch=1;\nprintf(\"\\n\\n\\n\\nunits set to inches\\n\\n\\n\\n\\n\");\n}\t\t\t\n\n\n\t\t\t/*########################################################*/\n\t\t\tif (gcode == 1 || gcode == 0)\n\t\t\t{\n\n\n\n\t\t\t\tif ((x<10) && (y<10))\n\t\t\t\t{\n\t\t\t\t\tx1 = abs(x);\n\t\t\t\t\ty1 = abs(y);\n\t\t\t\t\tif (x1>y1) { x1 = (x1 * 25*global_ms) - 0.5; a = ceil(x1); time = a; }\n\t\t\t\t\telse { y1 = (y1 * 25*global_ms) - 0.5; b = ceil(y1); time = b; }\n\n\t\t\t\t\tmultithread(x, y, e, time);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tplot_line(x + xold, y + yold, xold, yold, e);\n\t\t\t\t}\n\t\t\t\tif (is_z == 1) { z1 = abs(z); z1 = z1 * 25*global_ms - 0.5; time = ceil(z1); stepper(3, z, time); printf(\"------------------------------------------------\\n\"); is_z = 0; }\n\n\n\t\t\t}\n\n\n\t\t\telse if (gcode == 2 || gcode == 3)\n\t\t\t{\n\t\t\t\tprintf(\"Gcode: %d x=%f y=%f X=%f Y=%f I=%f J=%f\\n\", gcode, x, y, xold, yold, circle_i, circle_j);\n\n\n\t\t\t\tg23(gcode, x + xold, y + yold, xold, yold, circle_i, circle_j, e);\n\n\t\t\t\t//g23(2,0,10,10,0,0,-10);\n\n\t\t\t}\n\n\t\t\t/*########################################################*/\n\n\t\t}\n\t}\n\tclearall();\n\tprintf(\"#####################\\n#####################\\nJOB DONE\\n#####################\\n#####################\\n\");\n\treturn 0;\n\n}\n", "meta": {"hexsha": "f1f5d24660f5a41422f98bd389bd2c359359b0ff", "size": 22720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3d1.cpp", "max_stars_repo_name": "AdityaChavan/Colour3Dprinter_CNC", "max_stars_repo_head_hexsha": "e828ce3863d0d8957f767eb50123ef20ab89f20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3d1.cpp", "max_issues_repo_name": "AdityaChavan/Colour3Dprinter_CNC", "max_issues_repo_head_hexsha": "e828ce3863d0d8957f767eb50123ef20ab89f20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3d1.cpp", "max_forks_repo_name": "AdityaChavan/Colour3Dprinter_CNC", "max_forks_repo_head_hexsha": "e828ce3863d0d8957f767eb50123ef20ab89f20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4354148845, "max_line_length": 191, "alphanum_fraction": 0.4882922535, "num_tokens": 9302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.017986206573458403, "lm_q1q2_score": 0.0057703581897970225}}
{"text": "#include \"optimize.hpp\"\n#include <boost/program_options.hpp> \n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#include \"boost/filesystem.hpp\"\n#include <time.h>  \n#include <set>  \n\nTimer timer;\n\npo::variables_map check_options(int argc, char** argv) {\n    uint32_t num_cores = tbb::task_scheduler_init::default_num_threads();\n    std::string num_threads_message = \"Number of threads to use when possible [DEFAULT uses all available cores, \" + std::to_string(num_cores) + \" detected on this machine]\";\n\n    po::options_description desc(\"optimize options\");\n    desc.add_options()\n        (\"input-mat,i\", po::value<std::string>()->required(),\n         \"Input mutation-annotated tree file to optimize [REQUIRED].\")\n        (\"output-mat,o\", po::value<std::string>()->required(),\n         \"Output optimized mutation-annotated tree file [REQUIRED].\") \n        (\"sample-names,f\", po::value<std::string>()->default_value(\"\"),\n         \"File containing sample names whose ancestral nodes would be considered for optimization.\") \n        (\"input-vcf,v\", po::value<std::string>()->default_value(\"\"),\n         \"Input vcf filename to reassign resolved bases using Fitch-Sankoff initially.\")\n        (\"radius,r\", po::value<uint32_t>()->default_value(10), \\\n         \"Radius in which to restrict the SPR moves.\")\n        (\"optimization-seconds,s\", po::value<uint32_t>()->default_value(3600), \\\n         \"Approximate number of seconds to run the tree optimization stage. The stage terminates as soon as the elapsed time exceeds this value.\")\n        (\"save-every-seconds,S\", po::value<uint32_t>()->default_value(300), \\\n         \"Periodically save the optimized tree after every specified number of seconds have elapsed since the last save.\") \n        (\"threads,T\", po::value<uint32_t>()->default_value(num_cores), num_threads_message.c_str())\n        (\"help,h\", \"Print help messages\");\n\n    po::options_description all_options;\n    all_options.add(desc);\n    po::positional_options_description p;\n    po::variables_map vm;\n    try{\n        po::store(po::command_line_parser(argc, argv)\n                .options(all_options)\n                .positional(p)\n                .run(), vm);\n        po::notify(vm);\n    }\n    catch(std::exception &e){\n        std::cerr << desc << std::endl;\n        // Return with error code 1 unless\n        // the user specifies help\n            if (vm.count(\"help\"))\n                exit(0);\n            else\n                exit(1);\n    }\n    return vm;\n}\n\nstruct Pruned_Sample {\n    std::string sample_name;\n    std::vector<MAT::Mutation> sample_mutations;\n    std::unordered_set<uint32_t> positions;\n\n    // Assumes mutations are added in reverse chrono order\n    void add_mutation (MAT::Mutation mut) {\n        // If not reversal to reference allele \n        if ((mut.ref_nuc != mut.mut_nuc) && (positions.find(mut.position) == positions.end())) {\n            auto iter = std::lower_bound(sample_mutations.begin(), sample_mutations.end(), mut);\n            mut.par_nuc = mut.ref_nuc;\n            sample_mutations.insert(iter, mut);\n        }\n        positions.insert(mut.position);\n    }\n\n    Pruned_Sample (std::string name) {\n        sample_name = name;\n        sample_mutations.clear();\n        positions.clear();\n    }\n};\n\n\ninline std::string get_reversal_mutation(const std::string& mut_string) {\n    std::vector<std::string> words;\n    MAT::string_split(mut_string, words);\n    assert(words.size() == 4);\n    return words[0] + \"\\t\" + words[3] + \"\\t\" + words[2] + \"\\t\" + words[1]; \n}\n\nsize_t get_node_distance (const MAT::Tree& T, MAT::Node* source, MAT::Node* dest) {\n    auto s_anc = T.rsearch(source->identifier, true);\n    auto d_anc = T.rsearch(dest->identifier, true);\n\n    size_t s_off=0, d_off=0, num_iter=0;\n    if (s_anc.size() <= d_anc.size()) {\n        d_off = d_anc.size() - s_anc.size();\n        num_iter = s_anc.size();\n    }\n    else {\n        s_off = s_anc.size() - d_anc.size();\n        num_iter = d_anc.size();\n    }\n    \n    auto distance = s_off+d_off;\n    for (size_t i=0; i<num_iter; i++) {\n        if (s_anc[s_off+i] == d_anc[d_off+i]) {\n            break;\n        }\n        else {\n            distance+=2;\n        }\n    }\n\n    return distance;\n}\n\n/*\nvoid optimize_main_old(po::parsed_options parsed) {\n    po::variables_map vm = parse_optimize_command(parsed);\n    std::string input_mat_filename = vm[\"input-mat\"].as<std::string>();\n    std::string output_mat_filename = vm[\"output-mat\"].as<std::string>();\n    uint32_t max_seconds = vm[\"optimization-seconds\"].as<uint32_t>();\n    uint32_t num_threads = vm[\"threads\"].as<uint32_t>();\n    tbb::task_scheduler_init init(num_threads);\n    srand (time(NULL));\n    timer.Start();\n    fprintf(stderr, \"Loading input MAT file %s.\\n\", input_mat_filename.c_str()); \n    // Load input MAT and uncondense tree\n    MAT::Tree T = MAT::load_mutation_annotated_tree(input_mat_filename);\n    T.uncondense_leaves();\n    fprintf(stderr, \"The parsimony score for this MAT is %zu\\n\", T.get_parsimony_score());\n    fprintf(stderr, \"Completed in %ld msec \\n\\n\", timer.Stop());\n    timer.Start();\n    fprintf(stderr, \"Starting tree optimization.\\n\\n\"); \n    \n    fprintf(stderr, \"Finding the nodes with recurrent or reversal mutations.\\n\");\n    auto dfs = T.depth_first_expansion();\n    \n    std::map<std::string, int> mutation_counts;\n    tbb::mutex tbb_lock;\n    static tbb::affinity_partitioner ap;\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, dfs.size()),\n            [&](const tbb::blocked_range<size_t> r) {\n            for (size_t i=r.begin(); i<r.end(); ++i){\n            auto n = dfs[i];\n            n->clear_annotations();\n            \n            for (auto m: n->mutations) {\n               std::string mut_string = m.chrom + \"\\t\" + std::to_string(m.par_nuc) + \"\\t\" + \n                   std::to_string(m.position) + \"\\t\" + std::to_string(m.mut_nuc);\n               tbb_lock.lock();\n               if (mutation_counts.find(mut_string) == mutation_counts.end()) {\n                   mutation_counts[mut_string] = 1;\n               }\n               else {\n                   mutation_counts[mut_string] += 1;\n               }\n               tbb_lock.unlock();\n           }\n        }\n    }, ap);\n    std::vector<std::string> nodes_to_prune;\n    for (auto n: dfs) {\n        if ((n == T.root) || (T.get_num_leaves(n) > 1000)) {\n            continue;\n        }\n        for (auto m: n->mutations) {\n            std::string mut_string = m.chrom + \"\\t\" + std::to_string(m.par_nuc) + \"\\t\" + \n                std::to_string(m.position) + \"\\t\" + std::to_string(m.mut_nuc);\n            // Contains recurrent mutation\n            if (mutation_counts[mut_string] > 1) {\n                nodes_to_prune.emplace_back(n->identifier);\n                break;\n            }\n            auto reversal_string = get_reversal_mutation(mut_string);\n            // reversal mutation found\n            if (mutation_counts.find(reversal_string) != mutation_counts.end()) {\n                nodes_to_prune.emplace_back(n->identifier);\n                break;\n            }\n        }\n    }\n    // Shuffle the nodes to be pruned\n    std::random_shuffle(nodes_to_prune.begin(), nodes_to_prune.end());\n    fprintf(stderr, \"%zu nodes found with recurrent or reversal mutations.\\n\\n\", nodes_to_prune.size());\n    auto best_parsimony_score = T.get_parsimony_score();\n    for (auto node_to_prune: nodes_to_prune) {\n        if (T.get_node(node_to_prune) == NULL) {\n            continue;\n        }\n        auto copy = MAT::get_tree_copy(T);\n        fprintf(stderr, \"Pruning subtree at node %s.\\n\", node_to_prune.c_str());\n        auto leaves_to_prune = T.get_leaves(node_to_prune);\n        std::vector<Pruned_Sample> pruned_samples;\n        for (auto l: leaves_to_prune) {\n            Pruned_Sample to_prune(l->identifier);\n            auto root_to_node = T.rsearch(l->identifier, true); \n            std::reverse(root_to_node.begin(), root_to_node.end());\n            for (auto curr: root_to_node) {\n                for (auto m: curr->mutations) {\n                    to_prune.add_mutation(m);\n                }\n            }\n            // move_level set to false as moving it would be an unnecessary overhead\n            T.remove_node(l->identifier, false);\n            pruned_samples.emplace_back(to_prune);\n        }\n        fprintf(stderr, \"Pruned %zu samples at node %s.\\n\", pruned_samples.size(), node_to_prune.c_str());\n        fprintf(stderr, \"Placing %zu samples at node %s in random order.\\n\", pruned_samples.size(), node_to_prune.c_str());\n        std::random_shuffle(pruned_samples.begin(), pruned_samples.end());\n        for (auto s: pruned_samples) {\n            dfs = T.depth_first_expansion();\n            size_t total_nodes = dfs.size();\n            // Stores the excess mutations to place the sample at each\n            // node of the tree in DFS order. When placement is as a\n            // child, it only contains parsimony-increasing mutations in\n            // the sample. When placement is as a sibling, it contains \n            // parsimony-increasing mutations as well as the mutations\n            // on the placed node in common with the new sample. Note\n            // guaranteed to be corrrect only for optimal nodes since\n            // the mapper can terminate the search early for non-optimal\n            // nodes\n            std::vector<std::vector<MAT::Mutation>> node_excess_mutations(total_nodes);\n            // Stores the imputed mutations for ambiguous bases in the\n            // sampled in order to place the sample at each node of the \n            // tree in DFS order. Again, guaranteed to be corrrect only \n            // for pasrimony-optimal nodes \n            std::vector<std::vector<MAT::Mutation>> node_imputed_mutations(total_nodes);\n            std::vector<int> node_set_difference;\n            size_t best_node_num_leaves = 0;\n            // The maximum number of mutations is bound by the number\n            // of mutations in the missing sample (place at root)\n            //int best_set_difference = 1e9;\n            // TODO: currently number of root mutations is also added to\n            // this value since it forces placement as child but this\n            // could be changed later \n            int best_set_difference = s.sample_mutations.size() + T.root->mutations.size() + 1;\n            size_t best_j = 0;\n            bool best_node_has_unique = false;\n            std::vector<bool> node_has_unique(total_nodes, false);\n            std::vector<size_t> best_j_vec;\n            size_t num_best = 1;\n            MAT::Node* best_node = T.root;\n            best_j_vec.emplace_back(0);\n            // Parallel for loop to search for most parsimonious\n            // placements. Real action happens within mapper2_body\n            static tbb::affinity_partitioner ap;\n            tbb::parallel_for( tbb::blocked_range<size_t>(0, total_nodes),\n                    [&](tbb::blocked_range<size_t> r) {\n                    for (size_t k=r.begin(); k<r.end(); ++k){\n                    mapper2_input inp;\n                    inp.T = &T;\n                    inp.node = dfs[k];\n                    inp.missing_sample_mutations = &s.sample_mutations;\n                    inp.excess_mutations = &node_excess_mutations[k];\n                    inp.imputed_mutations = &node_imputed_mutations[k];\n                    inp.best_node_num_leaves = &best_node_num_leaves;\n                    inp.best_set_difference = &best_set_difference;\n                    inp.best_node = &best_node;\n                    inp.best_j =  &best_j;\n                    inp.num_best = &num_best;\n                    inp.j = k;\n                    inp.has_unique = &best_node_has_unique;\n                    inp.best_j_vec = &best_j_vec;\n                    inp.node_has_unique = &(node_has_unique);\n                    mapper2_body(inp, false);\n                    }       \n                    }, ap); \n            // Ensure sample not already in the tree\n            if (T.get_node(s.sample_name) == NULL) {\n                // Is placement as sibling\n                if (best_node->is_leaf() || best_node_has_unique) {\n                    std::string nid = std::to_string(++T.curr_internal_node);\n                    T.create_node(nid, best_node->parent->identifier);\n                    T.create_node(s.sample_name, nid);\n                    T.move_node(best_node->identifier, nid);\n                    // common_mut stores mutations common to the\n                    // best node branch and the sample, l1_mut\n                    // stores mutations unique to best node branch\n                    // and l2_mut stores mutations unique to the\n                    // sample not in best node branch\n                    std::vector<MAT::Mutation> common_mut, l1_mut, l2_mut;\n                    std::vector<MAT::Mutation> curr_l1_mut;\n                    // Compute current best node branch mutations\n                    for (auto m1: best_node->mutations) {\n                        MAT::Mutation m = m1.copy();\n                        curr_l1_mut.emplace_back(m);\n                    }\n                    // Clear mutations on the best node branch which\n                    // will be later replaced by l1_mut\n                    best_node->clear_mutations();\n                    // Compute l1_mut\n                    for (auto m1: curr_l1_mut) {\n                        bool found = false;\n                        for (auto m2: node_excess_mutations[best_j]) {\n                            if (m1.is_masked()) {\n                                break;\n                            }\n                            if (m1.position == m2.position) {\n                                if (m1.mut_nuc == m2.mut_nuc) {\n                                    found = true;\n                                    break;\n                                }\n                            }\n                        }\n                        if (!found) {\n                            MAT::Mutation m = m1.copy();\n                            l1_mut.emplace_back(m);\n                        }\n                    }\n                    // Compute l2_mut\n                    for (auto m1: node_excess_mutations[best_j]) {\n                        bool found = false;\n                        for (auto m2: curr_l1_mut) {\n                            if (m1.is_masked()) {\n                                break;\n                            }\n                            if (m1.position == m2.position) {\n                                if (m1.mut_nuc == m2.mut_nuc) {\n                                    found = true;\n                                    MAT::Mutation m = m1.copy();\n                                    common_mut.emplace_back(m);\n                                    break;\n                                }\n                            }\n                        }\n                        if (!found) {\n                            MAT::Mutation m = m1.copy();\n                            l2_mut.emplace_back(m);\n                        }\n                    }\n                    // Add mutations to new node using common_mut\n                    for (auto m: common_mut) {\n                        T.get_node(nid)->add_mutation(m);\n                    }\n                    // Add mutations to best node using l1_mut\n                    for (auto m: l1_mut) {\n                        T.get_node(best_node->identifier)->add_mutation(m);\n                    }\n                    // Add new sample mutations using l2_mut\n                    for (auto m: l2_mut) {\n                        T.get_node(s.sample_name)->add_mutation(m);\n                    }\n                }\n                // Else placement as child\n                else {\n                    MAT::Node* node = T.create_node(s.sample_name, best_node->identifier);\n                    std::vector<MAT::Mutation> node_mut;\n                    std::vector<MAT::Mutation> curr_l1_mut;\n                    for (auto m1: best_node->mutations) {\n                        MAT::Mutation m = m1.copy();\n                        curr_l1_mut.emplace_back(m);\n                    }\n                    for (auto m1: node_excess_mutations[best_j]) {\n                        bool found = false;\n                        for (auto m2: curr_l1_mut) {\n                            if (m1.is_masked()) {\n                                break;\n                            }\n                            if (m1.position == m2.position) {\n                                if (m1.mut_nuc == m2.mut_nuc) {\n                                    found = true;\n                                    break;\n                                }\n                            }\n                        }\n                        if (!found) {\n                            MAT::Mutation m = m1.copy();\n                            node_mut.emplace_back(m);\n                        }\n                    }\n                    for (auto m: node_mut) {\n                        node->add_mutation(m);\n                    }\n                }\n            }\n        }\n        fprintf(stderr, \"Done pruning and placing samples at node %s\\n\", node_to_prune.c_str());\n        auto new_parsimony_score = T.get_parsimony_score();\n        if (new_parsimony_score >= best_parsimony_score) {\n            fprintf(stderr, \"Placement resulted in a parsimony score of %zu. Retaining old tree.\\n\", new_parsimony_score);\n            MAT::clear_tree(T);\n            T = copy;\n        }\n        else {\n            MAT::clear_tree(copy);\n            best_parsimony_score = new_parsimony_score; \n            fprintf(stderr, \"Placement lowered parsimony score to %zu!\\n\", best_parsimony_score);\n        }\n        auto elapsed_time = timer.Stop()/1000;\n        fprintf(stderr, \"Elapsed time (tree optimization stage): %ld seconds.\\n\\n\", elapsed_time);\n        if (elapsed_time >= max_seconds) {\n            break;\n        }\n    }\n    \n    fprintf(stderr, \"Optimization complete. Saving the final MAT with a parsimony score of %zu\\n\", T.get_parsimony_score());\n    T.collapse_tree();\n    T.condense_leaves();\n    MAT::save_mutation_annotated_tree(T, output_mat_filename);\n    \n    fprintf(stderr, \"Completed in %ld msec \\n\\n\", timer.Stop());\n}\n*/\n\nint main(int argc, char** argv) {\n    po::variables_map vm = check_options(argc, argv);\n    std::string input_mat_filename = vm[\"input-mat\"].as<std::string>();\n    std::string input_vcf_filename = vm[\"input-vcf\"].as<std::string>();\n    std::string output_mat_filename = vm[\"output-mat\"].as<std::string>();\n    std::string sample_name_filename = vm[\"sample-names\"].as<std::string>();\n    uint32_t max_seconds = vm[\"optimization-seconds\"].as<uint32_t>();\n    uint32_t save_every = vm[\"save-every-seconds\"].as<uint32_t>();\n    uint32_t radius = vm[\"radius\"].as<uint32_t>();\n\n    uint32_t num_threads = vm[\"threads\"].as<uint32_t>();\n\n    tbb::task_scheduler_init init(num_threads);\n    srand (time(NULL));\n\n    static tbb::affinity_partitioner ap;\n\n    timer.Start();\n    fprintf(stderr, \"Loading input MAT file %s.\\n\", input_mat_filename.c_str()); \n\n    // Load input MAT and uncondense tree\n    MAT::Tree T = MAT::load_mutation_annotated_tree(input_mat_filename);\n    T.uncondense_leaves();\n\n\n\n    // If VCF specified, re-compute the assignments using Fitch-Sankoff\n    if (input_vcf_filename != \"\") {\n        fprintf(stderr, \"Computing parsimonious assignments for input variants.\\n\"); \n        timer.Start();\n\n        // Variables below used to store the different fields of the input VCF file \n        bool header_found = false;\n        std::vector<std::string> variant_ids;\n        std::vector<Missing_Sample> missing_samples;\n\n        // Vector used to store all tree nodes in breadth-first search (BFS) order\n        std::vector<MAT::Node*> bfs;\n        // Map the node identifier string to index in the BFS traversal\n        std::unordered_map<std::string, size_t> bfs_idx;\n\n        // Breadth-first expansion to populate bfs and bfs_idx\n        bfs = T.breadth_first_expansion();\n        for (size_t idx = 0; idx < bfs.size(); idx++) {\n            bfs_idx[bfs[idx]->identifier] = idx;\n            // clear the node mutations\n            bfs[idx]->clear_mutations();\n        }\n\n        // Boost library used to stream the contents of the input VCF file in\n        // uncompressed or compressed .gz format\n        std::ifstream infile(input_vcf_filename, std::ios_base::in | std::ios_base::binary);\n        if (!infile) {\n            fprintf(stderr, \"ERROR: Could not open the VCF file: %s!\\n\", input_vcf_filename.c_str());\n            exit(1);\n        }\n        boost::iostreams::filtering_istream instream;\n        try {\n            if (input_vcf_filename.find(\".gz\\0\") != std::string::npos) {\n                instream.push(boost::iostreams::gzip_decompressor());\n            }\n            instream.push(infile);\n        }\n        catch(const boost::iostreams::gzip_error& e) {\n            std::cout << e.what() << '\\n';\n        }\n        \n\n        // A TBB flow graph containing a single source_node (reader) connected\n        // to several mappers. The source_node sequentially reads in the different \n        // lines of the input VCF file and constructs a mapper task for each\n        // VCF line. Each mapper task takes a mapper_input as input, which stores\n        // the alternate alleles, ambiguous bases and missing data (Ns) for\n        // different tree samples at the corresponding VCF line/position. The \n        // mappers use Fitch-Sankoff algorithm to assign mutations at different\n        // branches of the tree and update the mutation-annotated tree (T)\n        // accordingly. \n        tbb::flow::graph mapper_graph;\n\n        tbb::flow::function_node<mapper_input, int> mapper(mapper_graph, tbb::flow::unlimited, mapper_body());\n        tbb::flow::source_node <mapper_input> reader (mapper_graph,\n                [&] (mapper_input &inp) -> bool {\n                \n                //check if reached end-of-file\n                int curr_char = instream.peek();\n                if(curr_char == EOF)\n                    return false;\n                \n                std::string s;\n                std::getline(instream, s);\n                std::vector<std::string> words;\n                MAT::string_split(s, words);\n                inp.variant_pos = -1;\n\n                // Header is found when \"POS\" is the second word in the line\n                if ((not header_found) && (words.size() > 1)) {\n                  if (words[1] == \"POS\") {\n                  // Sample names start from the 10th word in the header\n                    for (size_t j=9; j < words.size(); j++) {\n                      variant_ids.emplace_back(words[j]);\n                      // If sample name not in tree, add it to missing_samples\n                      if (bfs_idx.find(words[j]) == bfs_idx.end()) {\n                        missing_samples.emplace_back(Missing_Sample(words[j]));\n                      }\n                    }\n                    header_found = true;\n                  }\n                }\n                else if (header_found) {\n                    if (words.size() != 9+variant_ids.size()) {\n                        fprintf(stderr, \"ERROR! Incorrect VCF format.\\n\");\n                        exit(1);\n                    }\n                    std::vector<std::string> alleles;\n                    alleles.clear();\n                    inp.variant_pos = std::stoi(words[1]); \n                    MAT::string_split(words[4], ',', alleles);\n                    // T will be modified by the mapper with mutation\n                    // annotations\n                    inp.T = &T;\n                    inp.chrom = words[0];\n                    inp.bfs = &bfs;\n                    inp.bfs_idx = &bfs_idx;\n                    inp.variant_ids = &variant_ids;\n                    inp.missing_samples = &missing_samples;\n                    // Ref nuc id uses one-hot encoding (A:0b1, C:0b10, G:0b100,\n                    // T:0b1000)\n                    inp.ref_nuc = MAT::get_nuc_id(words[3][0]);\n                    assert((inp.ref_nuc & (inp.ref_nuc-1)) == 0); //check if it is power of 2\n                    inp.variants.clear();\n                    for (size_t j=9; j < words.size(); j++) {\n                        if (isdigit(words[j][0])) {\n                            int allele_id = std::stoi(words[j]);\n                            if (allele_id > 0) { \n                                std::string allele = alleles[allele_id-1];\n                                inp.variants.emplace_back(std::make_tuple(j-9, MAT::get_nuc_id(allele[0])));\n                            }\n                        }\n                        else {\n                            inp.variants.emplace_back(std::make_tuple(j-9, MAT::get_nuc_id('N')));\n                        }\n                    }\n                }\n                return true;\n                }, true );\n        tbb::flow::make_edge(reader, mapper);\n        mapper_graph.wait_for_all();\n\n        fprintf(stderr, \"Completed in %ld msec \\n\\n\", timer.Stop());\n    }\n\n    // Collapse tree for optimal performance and results\n    T.collapse_tree();\n    \n    fprintf(stderr, \"The parsimony score for this MAT is %zu\\n\", T.get_parsimony_score());\n    fprintf(stderr, \"Completed in %ld msec \\n\\n\", timer.Stop());\n\n    float last_update = 0;\n    \n    timer.Start();\n    fprintf(stderr, \"Finding the nodes to prune.\\n\");\n    auto bfs = T.breadth_first_expansion();\n    \n    std::set<std::string> nodes_to_prune;\n    \n    if (sample_name_filename != \"\") {\n        std::ifstream infile(sample_name_filename);\n        if (!infile) {\n            fprintf(stderr, \"ERROR: Could not open the sample name file: %s!\\n\", sample_name_filename.c_str());\n            exit(1);\n        }    \n        std::string line;\n\n        fprintf(stderr, \"Reading sample name file.\\n\"); \n        timer.Start();\n        while (std::getline(infile, line)) {\n            std::vector<std::string> words;\n            MAT::string_split(line, words);\n            if (words.size() != 1) {\n                fprintf(stderr, \"ERROR: Incorrect format for sample name file: %s!\\n\", sample_name_filename.c_str());\n                exit(1);\n            }\n            auto n = T.get_node(words[0]);\n            if (n == NULL) {\n                fprintf(stderr, \"WARNING: Node id %s not found in the tree!\\n\", words[0].c_str());\n                exit(1);\n            }\n            else {\n                for (auto anc: T.rsearch(words[0], true)) {\n                    if (anc->level >= 4) { \n                        nodes_to_prune.insert(anc->identifier);\n                    }\n                }\n            }\n        }\n        infile.close();\n    }\n\n    else {\n        fprintf(stderr, \"\\n\");\n        std::unordered_map<int, std::vector<std::string>> pos_to_nid;\n        for (auto n: bfs) {\n            for (auto m: n->mutations) {\n                if (pos_to_nid.find(m.position) != pos_to_nid.end()) {\n                    pos_to_nid[m.position].emplace_back(n->identifier);\n                }\n                else {\n                    pos_to_nid[m.position] = std::vector<std::string>();\n                    pos_to_nid[m.position].emplace_back(n->identifier);\n                }\n            }\n        }\n\n        size_t curr=0;\n        tbb::mutex tbb_lock;\n        tbb::parallel_for(tbb::blocked_range<size_t>(0, pos_to_nid.size()),\n                [&](tbb::blocked_range<size_t> r) {\n                for (size_t it = r.begin(); it < r.end(); it++) {\n                  auto at  = __sync_fetch_and_add(&curr, 1);\n                  if (at % 10 == 0) { \n                     tbb_lock.lock();\n                     fprintf(stderr, \"\\rAt %zu of %zu\", at, pos_to_nid.size());\n                     fflush(stderr);\n                     tbb_lock.unlock();\n                  }\n                  auto cn = pos_to_nid.begin();\n                  std::advance(cn, it);\n                  size_t num_elem = cn->second.size();\n                  for (size_t i=0; i<num_elem; i++) {\n                      tbb_lock.lock();\n                      if (nodes_to_prune.find(cn->second[i]) != nodes_to_prune.end()) {\n                          tbb_lock.unlock();\n                          continue;\n                      }\n                      tbb_lock.unlock();\n                      auto n = T.get_node(cn->second[i]);\n                      for (size_t j=i+1; j<num_elem; j++) {\n                          auto n2 = T.get_node(cn->second[j]);\n                          if (get_node_distance(T, n, n2) <= radius) {\n                              tbb_lock.lock();\n                              nodes_to_prune.insert(n->identifier);\n                              nodes_to_prune.insert(n2->identifier);\n                              tbb_lock.unlock();\n                              break;\n                          }\n                      }\n                  }\n                }\n            }, ap);\n        \n        fprintf(stderr, \"\\n\");\n    }\n\n    fprintf(stderr, \"%zu nodes found to prune.\\n\", nodes_to_prune.size());\n    fprintf(stderr, \"Completed in %ld msec \\n\\n\", timer.Stop());\n    \n    timer.Start();\n    fprintf(stderr, \"Starting tree optimization.\\n\\n\"); \n\n    auto best_parsimony_score = T.get_parsimony_score();\n    size_t curr=0;\n    for (auto nid_to_prune: nodes_to_prune) {\n        fprintf(stderr, \"At %zu of %zu\\n\", ++curr, nodes_to_prune.size());\n        \n        auto node_to_prune = T.get_node(nid_to_prune);\n        if (node_to_prune == NULL) {\n            continue;\n        }\n        \n        fprintf(stderr, \"Pruning subtree at node %s.\\n\", nid_to_prune.c_str());\n\n        // Find mutations on the node to prune\n        Pruned_Sample pruned_sample(nid_to_prune);\n\n        auto node_to_root = T.rsearch(nid_to_prune, true); \n        //std::reverse(root_to_node.begin(), root_to_node.end());\n        for (auto curr: node_to_root) {\n            for (auto m: curr->mutations) {\n                pruned_sample.add_mutation(m);\n            }\n        }\n\n        // Now prune the node_to_prune from the tree\n        auto curr_parent = node_to_prune->parent; \n        auto iter = std::find(curr_parent->children.begin(), curr_parent->children.end(), node_to_prune);\n        assert (iter != curr_parent->children.end());\n        curr_parent->children.erase(iter);\n\n        // Set source to current parent\n        auto source = curr_parent;\n\n        // Remove curr_parent if it has no children\n        if (curr_parent->children.size() == 0) {\n            auto ancestors = T.rsearch(curr_parent->identifier, true);\n            T.remove_node(curr_parent->identifier, true);\n\n            // Since remove_node can remove multiple levels of ancestors,\n            // reassign source to nearest ancestor currently in the tree\n            for (auto anc: ancestors) {\n                if (T.get_node(anc->identifier) != NULL) {\n                    source = anc;\n                    break;\n                }\n            }\n        }\n\n        // Move the remaining child one level up if it is the only child of its parent \n        if (curr_parent->children.size() == 1) {\n            auto child = curr_parent->children[0];\n            if (curr_parent->parent != NULL) {\n                child->parent = curr_parent->parent;\n                child->level = curr_parent->parent->level + 1;\n\n                std::vector<MAT::Mutation> tmp;\n                for (auto m: child->mutations) {\n                    tmp.emplace_back(m.copy());\n                }\n\n                //Clear and add back mutations in chrono order\n                child->clear_mutations();\n                for (auto m: curr_parent->mutations) {\n                    child->add_mutation(m.copy());\n                }\n                for (auto m: tmp) {\n                    child->add_mutation(m.copy());\n                }\n\n                curr_parent->parent->children.push_back(child);\n\n                curr_parent->children.clear();\n                T.remove_node(curr_parent->identifier, false);\n\n                source = child;\n            }\n        }\n\n        bfs = T.breadth_first_expansion();\n        size_t total_nodes = bfs.size();\n\n        std::vector<std::vector<MAT::Mutation>> node_excess_mutations(total_nodes);\n        std::vector<std::vector<MAT::Mutation>> imputed_mutations(total_nodes);\n\n        std::vector<int> node_set_difference;\n\n        size_t best_node_num_leaves = 0;\n        int best_set_difference = 1e9;\n\n        std::vector<bool> node_has_unique(total_nodes);\n        size_t best_j = 0;\n        bool best_node_has_unique = false;\n\n        size_t best_distance = 1e9;\n\n        std::vector<size_t> best_j_vec;\n\n        size_t num_best = 1;\n        MAT::Node* best_node = T.root;\n        best_j_vec.emplace_back(0);\n\n        std::vector<size_t> node_distance(total_nodes);\n\n        static tbb::affinity_partitioner ap;\n        tbb::parallel_for( tbb::blocked_range<size_t>(0, total_nodes),\n                [&](tbb::blocked_range<size_t> r) {\n                for (size_t k=r.begin(); k<r.end(); ++k){\n                node_distance[k] = get_node_distance(T, source, bfs[k]);\n                if (node_distance[k] > radius) {\n                   continue;\n                }\n                \n                node_has_unique[k] = false;\n\n                mapper2_input inp;\n                inp.T = &T;\n                inp.node = bfs[k];\n                inp.missing_sample_mutations = &pruned_sample.sample_mutations;\n                inp.excess_mutations = &node_excess_mutations[k];\n                inp.imputed_mutations = &imputed_mutations[k];\n                inp.best_node_num_leaves = &best_node_num_leaves;\n                inp.best_set_difference = &best_set_difference;\n                inp.best_node = &best_node;\n                inp.best_j =  &best_j;\n                inp.num_best = &num_best;\n                inp.j = k;\n                inp.has_unique = &best_node_has_unique;\n\n                inp.distance = node_distance[k];\n                inp.best_distance = &best_distance;\n\n                inp.best_j_vec = &best_j_vec;\n                inp.node_has_unique = &(node_has_unique);\n\n                mapper2_body(inp, false);\n                }       \n                }, ap); \n\n        auto distance = node_distance[best_j]; \n\n        // Clear current mutations of the node to prune\n        node_to_prune->clear_mutations();\n\n        // Is placement as sibling\n        if (best_node->is_leaf() || best_node_has_unique) {\n            std::string nid = std::to_string(++T.curr_internal_node);\n            auto new_node = T.create_node(nid, best_node->parent->identifier);\n            node_to_prune->parent = new_node;\n            new_node->children.emplace_back(node_to_prune);\n            T.move_node(best_node->identifier, nid);\n            \n            std::vector<MAT::Mutation> common_mut, l1_mut, l2_mut;\n            std::vector<MAT::Mutation> curr_l1_mut;\n\n            // Compute current best node branch mutations\n            for (auto m1: best_node->mutations) {\n                MAT::Mutation m = m1.copy();\n                curr_l1_mut.emplace_back(m);\n            }\n            // Clear mutations on the best node branch which\n            // will be later replaced by l1_mut\n            best_node->clear_mutations();\n\n            // Compute l1_mut\n            for (auto m1: curr_l1_mut) {\n                bool found = false;\n                for (auto m2: node_excess_mutations[best_j]) {\n                    if (m1.is_masked()) {\n                        break;\n                    }\n                    if (m1.position == m2.position) {\n                        if (m1.mut_nuc == m2.mut_nuc) {\n                            found = true;\n                            break;\n                        }\n                    }\n                }\n                if (!found) {\n                    MAT::Mutation m = m1.copy();\n                    l1_mut.emplace_back(m);\n                }\n            }\n            // Compute l2_mut\n            for (auto m1: node_excess_mutations[best_j]) {\n                bool found = false;\n                for (auto m2: curr_l1_mut) {\n                    if (m1.is_masked()) {\n                        break;\n                    }\n                    if (m1.position == m2.position) {\n                        if (m1.mut_nuc == m2.mut_nuc) {\n                            found = true;\n                            MAT::Mutation m = m1.copy();\n                            common_mut.emplace_back(m);\n                            break;\n                        }\n                    }\n                }\n                if (!found) {\n                    MAT::Mutation m = m1.copy();\n                    l2_mut.emplace_back(m);\n                }\n            }\n\n            // Add mutations to new node using common_mut\n            for (auto m: common_mut) {\n                new_node->add_mutation(m);\n            }\n            // Add mutations to best node using l1_mut\n            for (auto m: l1_mut) {\n                best_node->add_mutation(m);\n            }\n            // Add new sample mutations using l2_mut\n            for (auto m: l2_mut) {\n                node_to_prune->add_mutation(m);\n            }\n        }\n        // Else placement as child\n        else {\n            best_node->children.emplace_back(node_to_prune);\n            node_to_prune->parent = best_node;\n\n            std::vector<MAT::Mutation> node_mut;\n\n            std::vector<MAT::Mutation> curr_l1_mut;\n\n            for (auto m1: best_node->mutations) {\n                MAT::Mutation m = m1.copy();\n                curr_l1_mut.emplace_back(m);\n            }\n\n            for (auto m1: node_excess_mutations[best_j]) {\n                bool found = false;\n                for (auto m2: curr_l1_mut) {\n                    if (m1.is_masked()) {\n                        break;\n                    }\n                    if (m1.position == m2.position) {\n                        if (m1.mut_nuc == m2.mut_nuc) {\n                            found = true;\n                            break;\n                        }\n                    }\n                }\n                if (!found) {\n                    MAT::Mutation m = m1.copy();\n                    node_mut.emplace_back(m);\n                }\n            }\n            for (auto m: node_mut) {\n                node_to_prune->add_mutation(m);\n            }\n        }\n        \n        fprintf(stderr, \"Done pruning and placing samples at node %s\\n\", best_node->identifier.c_str());\n        fprintf(stderr, \"Distance from original placement: %zu\\n\", distance);\n\n        auto new_parsimony_score = T.get_parsimony_score();\n        assert(new_parsimony_score <= best_parsimony_score);\n        if (new_parsimony_score == best_parsimony_score) {\n            fprintf(stderr, \"Parsimony score of %zu unchanged after placement.\\n\", new_parsimony_score);\n        }\n        else {\n            best_parsimony_score = new_parsimony_score; \n            fprintf(stderr, \"Placement lowered parsimony score to %zu!\\n\", best_parsimony_score);\n        }\n        \n        float elapsed_sec = static_cast<float>(timer.Stop())/1000;\n        fprintf(stderr, \"Elapsed time (tree optimization stage): %.3f sec\\n\\n\", elapsed_sec);\n\n        if (elapsed_sec >= max_seconds) {\n            break;\n        }\n        \n        if (elapsed_sec-last_update >= save_every) {\n            // Levels need to be adjusted after placement \n            bfs = T.depth_first_expansion();\n            for (auto n: bfs) {\n                if (n == T.root) {\n                    n->level = 1;\n                }\n                else {\n                    n->level = n->parent->level+1;\n                }\n            }\n\n            fprintf(stderr, \"Saving the current MAT with a parsimony score of %zu\\n\\n\", T.get_parsimony_score());\n            T.condense_leaves();\n            MAT::save_mutation_annotated_tree(T, output_mat_filename);\n            last_update = elapsed_sec;\n\n            // Uncondense for the next iteration\n            T.uncondense_leaves();\n        }\n    }\n    \n    // Levels need to be adjusted after placement \n    bfs = T.breadth_first_expansion();\n    for (auto n: bfs) {\n        if (n == T.root) {\n            n->level = 1;\n        }\n        else {\n            n->level = n->parent->level+1;\n        }\n    }\n\n    fprintf(stderr, \"Optimization complete. Saving the final MAT with a parsimony score of %zu\\n\", T.get_parsimony_score());\n    T.condense_leaves();\n    MAT::save_mutation_annotated_tree(T, output_mat_filename);\n    \n    fprintf(stderr, \"Completed in %ld msec \\n\\n\", timer.Stop());\n}\n\n", "meta": {"hexsha": "448a9a038c21dc6a286f054c4bd30ab420fdc962", "size": 40507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matOptimize/main.cpp", "max_stars_repo_name": "lgozasht/usher", "max_stars_repo_head_hexsha": "4afe8e59a5d60ee9516a52111c1852b2d6fb53df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matOptimize/main.cpp", "max_issues_repo_name": "lgozasht/usher", "max_issues_repo_head_hexsha": "4afe8e59a5d60ee9516a52111c1852b2d6fb53df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matOptimize/main.cpp", "max_forks_repo_name": "lgozasht/usher", "max_forks_repo_head_hexsha": "4afe8e59a5d60ee9516a52111c1852b2d6fb53df", "max_forks_repo_licenses": ["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.5030737705, "max_line_length": 174, "alphanum_fraction": 0.5127261955, "num_tokens": 8770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2281565021609253, "lm_q2_score": 0.025178840191895407, "lm_q1q2_score": 0.005744716106651777}}
{"text": "#include <ScrimpTrivialParVec.hpp>\n#include <logging.hpp>\n#include <partitioning_1d.h>\n#include <binproffile.h>\n#include <settings.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <chrono>\n#include <cassert>\n#include <memory>\n#include <cstddef>\n\n#include <boost/assert.hpp>\n#include <boost/align.hpp>\n#include <boost/filesystem.hpp>\n\n#include <mpi.h>\n\n#include <papiwrapper.hpp>\n\nusing DiagPartition = Partition1D;\n\n// easy aligned allocation.\n// code from https://www.boost.org/doc/libs/1_57_0/doc/html/align/examples.html#align.examples.aligned_ptr, licensed under the Boost Software License - Version 1.0\n// see copy of the license terms provided under /licenses/boostSoftwareLicense.txt\ntemplate<class T>\nusing aligned_ptr = std::unique_ptr<T,\n  boost::alignment::aligned_delete>;\n\ntemplate<class T, class... Args>\ninline aligned_ptr<T> make_aligned(Args&&... args)\n{\n  auto p = boost::alignment::\n    aligned_alloc(alignof(T), sizeof(T));\n  if (!p) {\n\tthrow std::bad_alloc();\n  }\n  try {\n\tauto q = ::new(p) T(std::forward<Args>(args)...);\n\treturn aligned_ptr<T>(q);\n  } catch (...) {\n\tboost::alignment::aligned_free(p);\n\tthrow;\n  }\n}\n// condinue own code\n\n\n#define TIMEPOINT( varname ) const std::chrono::steady_clock::time_point varname = std::chrono::steady_clock::now();\n\nusing namespace matrix_profile;\n\nstatic FactoryRegistration<ScrimpTrivialParVec> s_trivParReg(\"triv_par_vec\");\nstatic const int notification_interval_iter = 10000;\n\nvoid commit_mpi_SOA_prof_type(MPI_Datatype* ptr_mpi_type, tsa_dtype* profile_buf, idx_dtype* idx_buf, int profile_length)\n{\n\tconst int blocklen[] = {profile_length,profile_length};\n\tMPI_Aint profBufAddr, idxBufAddr;\n\tMPI_Aint disps[2];\n\t//assertion for DOUBLE usage!!! TODO employ some preprocessor or template magic to automatically use a diffferent MPI Datatype...\n\tstatic_assert(sizeof(tsa_dtype) == sizeof(double), \"NO FLOAT POSSIBLE without modifing MPI Datatype!\" );\n\tstatic_assert(std::is_same<idx_dtype, long>::value, \"Index datatype does not match the MPI Datatype!\");\n\tconst MPI_Datatype dtypes[] = {MPI_DOUBLE, MPI_LONG};\n\t// official way of handling addresses\n\tMPI_Get_address(profile_buf, &profBufAddr);\n\tMPI_Get_address(idx_buf, &idxBufAddr);\n\tdisps[0] = 0;\n\tdisps[1] = MPI_Aint_diff(idxBufAddr, profBufAddr);\n\n\tMPI_Type_create_struct(2, blocklen, disps, dtypes, ptr_mpi_type);\n\tMPI_Type_commit(ptr_mpi_type);\n}\n\nvoid decompose_datatype(\n        const void * const invec,\n        const void * const inoutvec,\n        MPI_Datatype *datatype,\n        tsa_dtype** inoutprof, idx_dtype** inout_idx,\n        tsa_dtype** in2_prof, idx_dtype** in2_idx,\n        idx_dtype& blocklen\n        )\n{\n\tEXEC_TRACE(\"reducing a MatProfSOA!\");\n\t// retrieve the profile length: This is equal to the block length of the datastructure, not the length specified in the reduction!\n\tint num_int, num_add, num_dtype, combiner;\n\tMPI_Aint inout_addr, in2_addr;\n\tMPI_Get_address(invec, &in2_addr);\n\tMPI_Get_address(inoutvec, &inout_addr);\n\tMPI_Type_get_envelope(*datatype, &num_int, &num_add ,&num_dtype, &combiner);\n\n\tif (num_int>3 || num_add>2 || num_dtype >2){\n\t\tEXEC_ERROR(\"Invalid dataype sizes retrieved: num_i \" << num_int\n\t\t           << \" num_add \" << num_add\n\t\t           << \" num_dtype \" << num_dtype\n\t\t           << \"aborting as buffers are too small\");\n\t\tMPI_Abort(MPI_COMM_WORLD, 1);\n\t}\n\n\tint blocklens[3];\n\tMPI_Aint addresses[2];\n\tMPI_Datatype dtypes[2];\n\tMPI_Type_get_contents(*datatype, num_int, num_add, num_dtype, blocklens, addresses, dtypes);\n\n\tassert(blocklens[1] == blocklens[2]);\n\n\n\t//\"shortcuts\" for coding conveniencebb\n\t*inoutprof = reinterpret_cast<tsa_dtype*>(MPI_Aint_add(inout_addr, addresses[0]) );;\n\t*inout_idx = reinterpret_cast<idx_dtype*>(MPI_Aint_add(inout_addr, addresses[1]) );\n\t*in2_prof = reinterpret_cast<tsa_dtype*>(MPI_Aint_add(in2_addr, addresses[0]) );\n\t*in2_idx = reinterpret_cast<idx_dtype*>(MPI_Aint_add(in2_addr, addresses[1]) );\n\tblocklen = blocklens[1];\n}\n\nvoid ScrimpTrivialParVec::MPI_MatProfSOA_reduction(void * invec, void *inoutvec, int *len, MPI_Datatype *datatype) {\n\ttsa_dtype *inout_prof, *in2_prof;\n\tidx_dtype *inout_idx, *in2_idx;\n\tidx_dtype blocklen;\n\n\tassert(*len == 1); // only reduction with size 1 is supported: Otherwise strides between SOAs needed to be considered....\n\tdecompose_datatype(invec, inoutvec, datatype, &inout_prof, &inout_idx, &in2_prof, &in2_idx, blocklen);\n\tEXEC_TRACE(\"reduction with len \" << *len << \" and blocklen \" << blocklen);\n\n\t//finally the matrix profile reduction\n\tconst int limit = blocklen; // avoid unnecessary reads\n\tfor (int i = 0; i < limit; ++i) {\n\t\tif (in2_prof[i] < inout_prof[i]) {\n\t\t\tinout_prof[i] = in2_prof[i];\n\t\t\tinout_idx[i] = in2_idx[i];\n\t\t}\n\t}\n}\n\nvoid ScrimpTrivialParVec::compute_matrix_profile(const Scrimppp_params& params) {\n\tTIMEPOINT( tstart );\n\taligned_tsdtype_vec A = fetch_time_series<aligned_tsdtype_vec::allocator_type>(params); //load the time series data\n\tTIMEPOINT( tfileread );\n\taligned_tsdtype_vec AMean(A.size());\n\taligned_tsdtype_vec ASigma(A.size());\n\taligned_tsdtype_vec dotproducts(A.size());\n\tint windowSize = params.query_window_len;\n\tint exclusionZone = windowSize / 4;\n\tint timeSeriesLength = A.size();\n\tint profile_length = timeSeriesLength - windowSize + 1;\n\taligned_tsdtype_vec profile(profile_length, -1.0);//overallocation to enable usage of aligned avx-writes up to the end\n\taligned_int_vec profileIndex(profile_length, 0);  //overallocation to enable usage of aligned avx-writes up to the end\n\tconst int BLOCKING_SIZE = params.block_length;\n\tconst bool distrib_io = (params.filetype == Scrimppp_params::BIN) && params.use_distributed_io;\n\n\tif (params.filetype != Scrimppp_params::BIN && params.use_distributed_io) {\n\t\tEXEC_ERROR(\"distributed I/O is NOT supported with ASCII files. Falling back to master I/O!\");\n\t}\n\n\t// code instrumentaion (if enabled)\n\tPerfCounters ctrs_diaginit(\"diagonal initialization\");\n\tPerfCounters ctrs_eval(\"block evaluations\");\n\tPerfCounters ctrs_mpi_comm(\"MPI communication\");\n\n\t// retrieve basic MPI information\n\tint world_size;\n\tint world_rank;\n\tMPI_Datatype mpi_result_type;\n\tMPI_Op reduction_op;\n\tMPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\tMPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n\n\tEXEC_INFO( \"MPI INFO: comm size: \" << world_size << \" world rank: \" << world_rank);\n\tEXEC_INFO( \"Blocking size: \" << BLOCKING_SIZE)\n\n\tif (profile_length > RESULT_ALLOC_LEN) { // check, whether the data fit into the preallocated result storage\n\t\tthrow std::runtime_error(\"resulting profile length EXCEEDS MAXIMUM LENGTH. Recompile with different allocation size or choose a smaller problem\");\n\t}\n\telse if(profile_length<=0) {\n\t\tthrow std::runtime_error(\"parameters chosen badly: resulting matrix profile of length 0. done.\");\n\t}\n\n\t//create the MPI dataype for the result\n\tcommit_mpi_SOA_prof_type(&mpi_result_type, profile.data(), profileIndex.data(), profile_length );\n\n\t//create the reduction operation for the custom datatype\n\tMPI_Op_create(MPI_MatProfSOA_reduction, 1, &reduction_op);\n\n\t// values regarding work partitioning\n\tconst int num_partitions = 2*world_size; //number of partitions. 2 partitions per process for the sake of balancing\n\tconst int diags_to_process_world = profile_length-exclusionZone-1; //total number of diagonals in the \"adjacency\" matrix to process\n\t// likely the partitions can not be of exactly even size. We assume the first ones to be of partition_size_full_load and the remaining ones to be one element smaller\n\tconst PartitioningInfo partinfo = {\n\t    ._num_partitions = 2*world_size,\n\t    ._num_partitions_full_load = diags_to_process_world - ((diags_to_process_world/num_partitions) * num_partitions),\n\t    ._size_full_load = (diags_to_process_world/num_partitions) + 1\n\t};\n\n\t/*const bool proc_has_reduced_load = world_rank<num_reduced_load;\n\tconst int diags_to_process_proc = (proc_has_reduced_load?diags_to_process_reduced_load:diags_to_process_full_load);\n\tconst int proc_offset = (proc_has_reduced_load? world_rank*diags_to_process_reduced_load\n\t\t\t\t\t\t\t\t\t\t\t\t\t: diags_to_process_reduced_load*num_reduced_load\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+diags_to_process_full_load*(world_rank-num_reduced_load));*/\n\n\t// retrieve the local partitions: each process gets 2. A \"long\" one in the upper half of the triangle and a \"short\" one in the lower half of the triangle\n\tstd::vector<DiagPartition> local_partitions;\n\t    // the upper partition is the \"process-rank\"-th one\n\tDiagPartition part_offsets = get_partition(world_rank, partinfo);\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(profile_length-1, exclusionZone+1+part_offsets._last_id)} );\n\tpart_offsets = get_partition(num_partitions-world_rank-1, partinfo);\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(profile_length-1, exclusionZone+1+part_offsets._last_id)} );\n\n\t//sum up, how many diags the local proc has to evaluate\n\tint diags_to_process_proc = 0;\n\tfor (auto partit = local_partitions.begin(); partit < local_partitions.end(); ++partit) {\n\t\tdiags_to_process_proc += partit->_last_id - partit->_first_id +1;\n\t}\n\n#ifndef NDEBUG\n\t// sum up over all processes\n\tint num_processed_diags = 0;\n\tMPI_Reduce(&diags_to_process_proc, &num_processed_diags, 1, MPI_INTEGER, MPI_SUM, 0, MPI_COMM_WORLD);\n\tif (world_rank == 0) {\n\t\tBOOST_ASSERT_MSG(num_processed_diags==diags_to_process_world, \"work partitioning of the diagonals is ivalid\");\n\t}\n\tEXEC_INFO(\"partitioning is fine!\");\n#endif\n\n//\tEXEC_INFO(\"Processing all the matrix profile!\");\n//\tlocal_partitions.clear();\n//\tlocal_partitions.push_back( {exclusionZone+1, ProfileLength-1} );\n/*\n\tconst int tmprank=0;\n\tEXEC_INFO(\"Processing the rank\" << tmprank << \" partition of the matrix profile!\");\n\tlocal_partitions.clear();\n\tpart_offsets = get_partition(tmprank, partinfo);\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(ProfileLength-1, exclusionZone+1+part_offsets._last_id)} );\n\tpart_offsets = get_partition(num_partitions-tmprank-1, partinfo);\n\tlocal_partitions.push_back( {exclusionZone+1+part_offsets._first_id, std::min(ProfileLength-1, exclusionZone+1+part_offsets._last_id)} );\n*/\n\n\t//validation of parameters\n\tif (timeSeriesLength < windowSize) {\n\t\tthrow std::invalid_argument(\"ERROR: Time series is shorter than the window length, can not proceed\");\n\t}\n\n\tTIMEPOINT( tsetup );\n\n\t//precompute the mean and standard deviations of the sliding windows along the time series\n\tprecompute_window_statistics(windowSize, A, profile_length, AMean, ASigma);\n\n\t//start time measurment\n\tTIMEPOINT( tprecomputations );\n\n\t// randomly shuffle the comutation order of diagonal blocks (according to the blocking size).\n\t// In order to do so split the local partition into blocks and shuffle them.\n\tstd::vector<DiagPartition> eval_blocks;\n\teval_blocks.reserve((diags_to_process_proc/BLOCKING_SIZE) +1);\n\n\tfor (auto partit = local_partitions.begin(); partit < local_partitions.end(); ++partit) {\n\t\t    // split the partitions into block which preserve cache locality\n\t\tconst int partlen = partit->_last_id - partit->_first_id;\n\t\tconst int num_prolonged_blocks = std::max(partlen % BLOCKING_SIZE, partlen/BLOCKING_SIZE) ;\n\t\tint prev_block_end = partit->_first_id-1;\n\n\t\tEXEC_TRACE(\"splitting into blocks a partition with start: \" << partit->_first_id << \" and last: \" << partit->_last_id);\n\n\t\tfor ( int blocki = 0; prev_block_end < partit->_last_id; ++blocki) {\n\t\t\tDiagPartition part;\n\t\t\tpart._first_id = prev_block_end+1;\n\t\t\tif (blocki < num_prolonged_blocks) {\n\t\t\t\tpart._last_id = std::min(part._first_id + BLOCKING_SIZE-1, partit->_last_id);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpart._last_id = std::min(part._first_id+BLOCKING_SIZE-1, partit->_last_id);\n\t\t\t}\n\t\t\teval_blocks.push_back( part );\n\t\t\tprev_block_end = part._last_id;\n\t\t}\n\t}\n\t//std::random_shuffle(eval_blocks.begin(), eval_blocks.end());\n\n\tTIMEPOINT( tpartitioning )\n\tEXEC_DEBUG( \"Proc \" << world_rank << \" shall process \" << diags_to_process_proc << \" diagonals\");\n\n\t//init_all_diagonals(dotproducts, A, windowSize);\n\n\t//iteratively evaluate the diagonals of the distance matrix\n\tint progressctr=0;\n\tint next_notification_thresh = notification_interval_iter;\n\tfor (auto blockiter = eval_blocks.begin(); blockiter < eval_blocks.end(); ++blockiter) {\n\t\tconst int blocklen = blockiter->_last_id +1 - blockiter->_first_id;\n\n\t\t// compute distance of the first entry for each entry in the block\n\n\t\t    // might be more efficient, if performed with MASS for ech partition (when splitting them up into blocks)\n\t\t{\n\t\t\tconst ScopedPerfAccumulator monitor(ctrs_diaginit);\n\t\t\tinit_diagonals(blockiter->_first_id, blockiter->_last_id, dotproducts, A, windowSize);\n\t\t}\n\n\t\tEXEC_DEBUG(\"Rank \" << world_rank << \" evaluating diags \" << blockiter->_first_id << \" to \" << blockiter->_last_id);\n\t\t{\n\t\t\tconst ScopedPerfAccumulator monitor(ctrs_eval);\n\t\t\teval_diagonal_block(blocklen, profileIndex, A, dotproducts, windowSize, ASigma, AMean, blockiter->_first_id, profile);\n\n\t\t\tprogressctr+=blocklen;\n\t\t}\n\t\t//Show time per 10000 iterations\n\t\tif (progressctr > next_notification_thresh && false) //disable in or der for the logging not to disturb the timing\n\t\t{\n\t\t\tconst auto tcur = std::chrono::steady_clock::now();\n\t\t\tstd::chrono::duration<float> time_elapsed = tcur - tpartitioning;\n\t\t\tEXEC_INFO (\"finished \" << progressctr << \" iterations in: \" << std::setprecision(4) << time_elapsed.count() << \" seconds.\");\n\t\t\tnext_notification_thresh += notification_interval_iter;\n\t\t}\n\t}\n\n\tTIMEPOINT( tevaluations)\n\tEXEC_DEBUG(\"apply transformation from score to distance values\")\n\t// apply a correction of the distance values, as we dropped a factor of 2 to avoid unnecessary computations\n\ttsa_dtype twice_m = 2.0*static_cast<tsa_dtype>(windowSize);\n\tfor (int i = 0; i<profile_length; ++i) {\n\t\tprofile[i] = twice_m - 2.0 * profile[i];\n\t}\n\tTIMEPOINT( tpostprocessing)\n\t{\n\t\tconst ScopedPerfAccumulator monitor(ctrs_mpi_comm);\n\t\tEXEC_INFO(\"reduce the processes individual results\")\n\t\t//update matrix profile and matrix profile index if the current distance value is smaller\n\t\tif (distrib_io) { //distributed I/O => everyone needs the result => Allreduce\n\t\t\t// actually only a fraction is required: the partition which will be written. That would require several reductions (one for each partition), where the receiver is the process responsible for the partition...\n\t\t\tMPI_Allreduce(MPI_IN_PLACE, profile.data(), 1, mpi_result_type, reduction_op, MPI_COMM_WORLD); // in case of distributed binary I/O everyone needs the result\n\t\t}\n\t\telse { // reduction into master only, in case it is the only one writing...\n\t\t\tif (world_rank != 0) {\n\t\t\t\tMPI_Reduce(profile.data(), profile.data(), 1, mpi_result_type, reduction_op, 0, MPI_COMM_WORLD); // Reduction of length 1, as the datatype is defined as ProfileLength!\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMPI_Reduce(MPI_IN_PLACE, profile.data(), 1, mpi_result_type, reduction_op, 0, MPI_COMM_WORLD); // Reduction of length 1, as the datatype is defined as ProfileLength!\n\t\t\t}\n\t\t}\n\t\tEXEC_INFO( \"rank \" << world_rank << \" done with reduction\");\n\t}\n\n\tTIMEPOINT( tcommunication)\n\t// MPI_Barrier(MPI_COMM_WORLD); //just for \"debugging\"\n\n\t//store the result\n\tif (world_rank == 0 || distrib_io ){ // storing in parallel if BIN type specified...\n\t\tEXEC_DEBUG(\"Rank \" << world_rank << \"storing the result\");\n\t\tstore_matrix_profile(profile.data(), profileIndex.data(), profile_length, params, distrib_io);\n\t}\n\n\tTIMEPOINT( tfilewrite )\n\n\t// MPI cleanup\n\tMPI_Op_free(&reduction_op);\n\tMPI_Type_free(&mpi_result_type);\n\n\tTIMEPOINT( tmpiclean)\n\n\tstd::chrono::duration<double> setup_time, comp_time, comm_time, evaluation_time, io_time, work_time, precomp_time;\n\tsetup_time = tsetup-tfileread + tmpiclean-tfilewrite + tpartitioning-tprecomputations;\n\tcomm_time = tcommunication-tpostprocessing ;\n\tevaluation_time = tevaluations-tpartitioning;\n\tprecomp_time = tprecomputations-tsetup;\n\tcomp_time = evaluation_time + precomp_time + tpostprocessing-tevaluations;\n\twork_time = comp_time + comm_time + setup_time;\n\tio_time = tfileread - tstart + tfilewrite-tcommunication;\n\t// log computation performance\n\tconst double triang_len = profile_length-exclusionZone;\n\tauto timerprecision = std::numeric_limits<tsa_dtype>::digits10 + 2;\n\tPERF_LOG ( \"evaluation time: \" << std::setprecision(timerprecision) << evaluation_time.count() << \" seconds.\" );\n\tPERF_LOG ( \"local comp time (eval+precomp): \" << std::setprecision(timerprecision) << comp_time.count() << \" seconds.\" );\n\tPERF_LOG ( \"communication time: \" << std::setprecision(timerprecision) << comm_time.count() << \" seconds\" );\n\tPERF_LOG ( \"local working time: \" << std::setprecision(timerprecision) << work_time.count() << \" seconds\" );\n\tPERF_LOG ( \"I/O time: \" << std::setprecision(timerprecision) << io_time.count() << \" seconds\" );\n\n\tPERF_LOG ( \"local throughput evaluations: \" << std::setprecision(6) << diags_to_process_proc * triang_len / evaluation_time.count() << \" matrix entries/second\" );\n\tPERF_LOG ( \"throughput evaluations: \" << std::setprecision(6) << triang_len * triang_len / evaluation_time.count() << \" matrix entries/second (estimate based on local)\" );\n\tPERF_LOG ( \"local throughput computations: \" << std::setprecision(6) << diags_to_process_proc * triang_len / comp_time.count() << \" matrix entries/second\" );\n\tPERF_LOG ( \"throughput computations: \" << std::setprecision(6) << triang_len * triang_len / comp_time.count() << \" matrix entries/second (estimate based on local)\" );\n\n\tusing unit_seconds = std::chrono::duration<double>;\n\t// log exhaustive timing information\n#define TIME_TRACE( timer, description ) PERF_TRACE ( \"timepoint after \" << description << \": \" << \\\n\t    std::setprecision(timerprecision) << std::chrono::duration_cast< unit_seconds >(timer.time_since_epoch()).count() << \" seconds\");\n\tTIME_TRACE( tstart, \"start\");\n\tTIME_TRACE( tfileread, \"fileread\");\n\tTIME_TRACE( tsetup, \"setup\");\n\tTIME_TRACE( tprecomputations, \"precomputations\");\n\tTIME_TRACE( tpartitioning, \"partitioning\");\n\tTIME_TRACE( tevaluations, \"matrix_eval\");\n\tTIME_TRACE( tpostprocessing, \"postprocessing\");\n\tTIME_TRACE( tcommunication, \"communication\");\n\tTIME_TRACE( tfilewrite, \"postprocessing\");\n\tTIME_TRACE( tmpiclean, \"mpi_cleanup\")\n\n\n    #ifdef PROFILING\n\t    PERF_LOG(\"number of matrix profile updates: \" << _profile_updates);\n\t    PERF_LOG(\"number of evaluations: \" << _eval_ctr);\n    #endif\n\tctrs_diaginit.log_perf();\n\tctrs_eval.log_perf();\n\tctrs_mpi_comm.log_perf();\n}\n", "meta": {"hexsha": "4c26f5bd720635bc36aef255f1815a54a20d28dd", "size": 18500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimppp/src/ScrimpTrivialParVec.cpp", "max_stars_repo_name": "4rchangel/ThesisCode", "max_stars_repo_head_hexsha": "0adb0615cfaa3f76ab04de6eac11bf3055173061", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T22:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:14:16.000Z", "max_issues_repo_path": "scrimppp/src/ScrimpTrivialParVec.cpp", "max_issues_repo_name": "4rchangel/ThesisCode", "max_issues_repo_head_hexsha": "0adb0615cfaa3f76ab04de6eac11bf3055173061", "max_issues_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scrimppp/src/ScrimpTrivialParVec.cpp", "max_forks_repo_name": "4rchangel/ThesisCode", "max_forks_repo_head_hexsha": "0adb0615cfaa3f76ab04de6eac11bf3055173061", "max_forks_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-20T22:41:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T09:15:48.000Z", "avg_line_length": 44.794188862, "max_line_length": 211, "alphanum_fraction": 0.7469189189, "num_tokens": 4809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181323186177208, "lm_q2_score": 0.028436031603970194, "lm_q1q2_score": 0.005738767439320716}}
{"text": "//=============================================================================================================\n/**\n * @file     mne_cov_matrix.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\n *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n *           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>\n * @version  dev\n * @date     January, 2017\n *\n * @section  LICENSE\n *\n * Copyright (C) 2017, Lorenz Esch, Matti Hamalainen, Christoph Dinh. 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 the MneCovMatrix Class.\n *\n */\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"mne_cov_matrix.h\"\n#include \"mne_sss_data.h\"\n#include \"mne_proj_item.h\"\n#include \"mne_proj_op.h\"\n\n\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace FIFFLIB;\nusing namespace MNELIB;\n\n\n\n#ifndef FAIL\n#define FAIL -1\n#endif\n\n#ifndef OK\n#define OK 0\n#endif\n\n\n\n#define MALLOC_30(x,t) (t *)malloc((x)*sizeof(t))\n#define REALLOC_30(x,y,t) (t *)((x == NULL) ? malloc((y)*sizeof(t)) : realloc((x),(y)*sizeof(t)))\n\n\n#define FREE_30(x) if ((char *)(x) != NULL) free((char *)(x))\n\n#define FREE_CMATRIX_30(m) mne_free_cmatrix_30((m))\n#define FREE_DCMATRIX_30(m) mne_free_dcmatrix_30((m))\n\n\n\nvoid mne_free_cmatrix_30 (float **m)\n{\n    if (m) {\n        FREE_30(*m);\n        FREE_30(m);\n    }\n}\n\n\nvoid mne_free_dcmatrix_30 (double **m)\n\n{\n    if (m) {\n        FREE_30(*m);\n        FREE_30(m);\n    }\n}\n\n\n\n\n#define ALLOC_CMATRIX_30(x,y) mne_cmatrix_30((x),(y))\n\n\n#define ALLOC_DCMATRIX_30(x,y) mne_dmatrix_30((x),(y))\n\n\n\n\n\nstatic void matrix_error_30(int kind, int nr, int nc)\n\n{\n    if (kind == 1)\n        printf(\"Failed to allocate memory pointers for a %d x %d matrix\\n\",nr,nc);\n    else if (kind == 2)\n        printf(\"Failed to allocate memory for a %d x %d matrix\\n\",nr,nc);\n    else\n        printf(\"Allocation error for a %d x %d matrix\\n\",nr,nc);\n    if (sizeof(void *) == 4) {\n        printf(\"This is probably because you seem to be using a computer with 32-bit architecture.\\n\");\n        printf(\"Please consider moving to a 64-bit platform.\");\n    }\n    printf(\"Cannot continue. Sorry.\\n\");\n    exit(1);\n}\n\n\n\n\nfloat **mne_cmatrix_30(int nr,int nc)\n\n{\n    int i;\n    float **m;\n    float *whole;\n\n    m = MALLOC_30(nr,float *);\n    if (!m) matrix_error_30(1,nr,nc);\n    whole = MALLOC_30(nr*nc,float);\n    if (!whole) matrix_error_30(2,nr,nc);\n\n    for(i=0;i<nr;i++)\n        m[i] = whole + i*nc;\n    return m;\n}\n\n\n\ndouble **mne_dmatrix_30(int nr, int nc)\n\n{\n    int i;\n    double **m;\n    double *whole;\n\n    m = MALLOC_30(nr,double *);\n    if (!m) matrix_error_30(1,nr,nc);\n    whole = MALLOC_30(nr*nc,double);\n    if (!whole) matrix_error_30(2,nr,nc);\n\n    for(i=0;i<nr;i++)\n        m[i] = whole + i*nc;\n    return m;\n}\n\n\n\n\n//============================= mne_decompose.c =============================\n\n\nint mne_decompose_eigen (double *mat,\n                         double *lambda,\n                         float  **vectors, /* Eigenvectors fit into floats easily */\n                         int    dim)\n/*\n      * Compute the eigenvalue decomposition of\n      * a symmetric matrix using the LAPACK routines\n      *\n      * 'mat' contains the lower triangle of the matrix\n      */\n{\n    int    np  =   dim*(dim+1)/2;\n    double *w    = MALLOC_30(dim,double);\n    double *z    = MALLOC_30(dim*dim,double);\n    double *work = MALLOC_30(3*dim,double);\n    double *dmat = MALLOC_30(np,double);\n    float  *vecp = vectors[0];\n\n    const char   *uplo  = \"U\";\n    const char   *compz = \"V\";\n    int    info,k;\n    int    one = 1;\n    int    maxi;\n    double scale;\n\n//    maxi = idamax(&np,mat,&one);\n// idamax workaround begin\n    maxi = 0;\n    for(int i = 0; i < np; ++i)\n        if (std::fabs(mat[i]) > std::fabs(mat[maxi]))\n            maxi = i;\n// idamax workaround end\n\n    scale = 1.0/mat[maxi];//scale = 1.0/mat[maxi-1];\n\n    for (k = 0; k < np; k++)\n        dmat[k] = mat[k]*scale;\n//    dspev(compz,uplo,&dim,dmat,w,z,&dim,work,&info);\n\n\n// dspev workaround begin\n    MatrixXd dmat_tmp = MatrixXd::Zero(dim,dim);\n    int idx = 0;\n    for (int i = 0; i < dim; ++i) {\n        for(int j = 0; j <= i; ++j) {\n            dmat_tmp(i,j) = dmat[idx];\n            dmat_tmp(j,i) = dmat[idx];\n            ++idx;\n        }\n    }\n    SelfAdjointEigenSolver<MatrixXd> es;\n    es.compute(dmat_tmp);\n    for ( int i = 0; i < dim; ++i )\n        w[i] = es.eigenvalues()[i];\n\n    idx = 0;\n    for ( int j = 0; j < dim; ++j ) {\n        for( int i = 0; i < dim; ++i ) {\n            z[idx] = es.eigenvectors()(i,j);// Column Major\n            ++idx;\n        }\n    }\n// dspev workaround end\n\n    info = 0;\n\n    qDebug() << \"!!!DEBUG ToDo: dspev(compz,uplo,&dim,dmat,w,z,&dim,work,&info);\";\n\n    FREE_30(work);\n    if (info != 0)\n        printf(\"Eigenvalue decomposition failed (LAPACK info = %d)\",info);\n    else {\n        scale = 1.0/scale;\n        for (k = 0; k < dim; k++)\n            lambda[k] = scale*w[k];\n        for (k = 0; k < dim*dim; k++)\n            vecp[k] = z[k];\n    }\n    FREE_30(w);\n    FREE_30(z);\n    if (info == 0)\n        return 0;\n    else\n        return -1;\n}\n\n\n\n\n\n\n\ndouble **mne_dmatt_dmat_mult2 (double **m1,double **m2, int d1,int d2,int d3)\n/* Matrix multiplication\n      * result(d1 x d3) = m1(d2 x d1)^T * m2(d2 x d3) */\n\n{\n    double **result = ALLOC_DCMATRIX_30(d1,d3);\n#ifdef BLAS\n    char  *transa = \"N\";\n    char  *transb = \"T\";\n    double zero = 0.0;\n    double one  = 1.0;\n\n    dgemm (transa,transb,&d3,&d1,&d2,\n           &one,m2[0],&d3,m1[0],&d1,&zero,result[0],&d3);\n\n    return result;\n#else\n    int j,k,p;\n    double sum;\n\n    for (j = 0; j < d1; j++)\n        for (k = 0; k < d3; k++) {\n            sum = 0.0;\n            for (p = 0; p < d2; p++)\n                sum = sum + m1[p][j]*m2[p][k];\n            result[j][k] = sum;\n        }\n    return result;\n#endif\n}\n\n\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nMneCovMatrix::MneCovMatrix(int p_kind,\n                           int p_ncov,\n                           const QStringList& p_names,\n                           double *p_cov,\n                           double *p_cov_diag,\n                           FiffSparseMatrix* p_cov_sparse)\n:kind(p_kind)\n,ncov(p_ncov)\n,nproj(0)\n,nzero(0)\n,names(p_names)\n,cov(p_cov)\n,cov_diag(p_cov_diag)\n,cov_sparse(p_cov_sparse)\n,eigen(NULL)\n,lambda(NULL)\n,chol(NULL)\n,inv_lambda(NULL)\n,nfree(1)\n,ch_class(NULL)\n,proj(NULL)\n,sss(NULL)\n,nbad(0)\n{\n\n}\n\n\n//*************************************************************************************************************\n\nMneCovMatrix::~MneCovMatrix()\n{\n    FREE_30(cov);\n    FREE_30(cov_diag);\n    if(cov_sparse)\n        delete cov_sparse;\n    names.clear();\n    FREE_CMATRIX_30(eigen);\n    FREE_30(lambda);\n    FREE_30(inv_lambda);\n    FREE_30(chol);\n    FREE_30(ch_class);\n    if(proj)\n        delete proj;\n    if (sss)\n        delete sss;\n    bads.clear();\n}\n\n\n//*************************************************************************************************************\n\nMneCovMatrix *MneCovMatrix::mne_dup_cov(MneCovMatrix *c)\n{\n    double       *vals;\n    int          nval;\n    int          k;\n    MneCovMatrix* res;\n\n    if (c->cov_diag)\n        nval = c->ncov;\n    else\n        nval = (c->ncov*(c->ncov+1))/2;\n\n    vals = MALLOC_30(nval,double);\n    if (c->cov_diag) {\n        for (k = 0; k < nval; k++)\n            vals[k] = c->cov_diag[k];\n        res = mne_new_cov(c->kind,c->ncov,c->names,NULL,vals);\n    }\n    else {\n        for (k = 0; k < nval; k++)\n            vals[k] = c->cov[k];\n        res = mne_new_cov(c->kind,c->ncov,c->names,vals,NULL);\n    }\n    /*\n        * Duplicate additional items\n        */\n    if (c->ch_class) {\n        res->ch_class = MALLOC_30(c->ncov,int);\n        for (k = 0; k < c->ncov; k++)\n            res->ch_class[k] = c->ch_class[k];\n    }\n    res->bads = c->bads;\n    res->nbad = c->nbad;\n    res->proj = MneProjOp::mne_dup_proj_op(c->proj);\n    res->sss  = new MneSssData(*(c->sss));\n\n    return res;\n}\n\n\n//*************************************************************************************************************\n\nint MneCovMatrix::mne_is_diag_cov(MneCovMatrix *c)\n{\n    return c->cov_diag != NULL;\n}\n\n\n//*************************************************************************************************************\n\nint MneCovMatrix::mne_add_inv_cov(MneCovMatrix *c)\n/*\n          * Calculate the inverse square roots for whitening\n          */\n{\n    double *src = c->lambda ? c->lambda : c->cov_diag;\n    int k;\n\n    if (src == NULL) {\n        qCritical(\"Covariance matrix is not diagonal or not decomposed.\");\n        return FAIL;\n    }\n    c->inv_lambda = REALLOC_30(c->inv_lambda,c->ncov,double);\n    for (k = 0; k < c->ncov; k++) {\n        if (src[k] <= 0.0)\n            c->inv_lambda[k] = 0.0;\n        else\n            c->inv_lambda[k] = 1.0/sqrt(src[k]);\n    }\n    return OK;\n}\n\n\n//*************************************************************************************************************\n\nint MneCovMatrix::condition_cov(MneCovMatrix *c, float rank_threshold, int use_rank)\n{\n    double *scale  = NULL;\n    double *cov    = NULL;\n    double *lambda = NULL;\n    float  **eigen = NULL;\n    double **data1 = NULL;\n    double **data2 = NULL;\n    double magscale,gradscale,eegscale;\n    int    nmag,ngrad,neeg,nok;\n    int    j,k;\n    int    res = FAIL;\n\n    if (c->cov_diag)\n        return OK;\n    if (!c->ch_class) {\n        qCritical(\"Channels not classified. Rank cannot be determined.\");\n        return FAIL;\n    }\n    magscale = gradscale = eegscale = 0.0;\n    nmag = ngrad = neeg = 0;\n    for (k = 0; k < c->ncov; k++) {\n        if (c->ch_class[k] == MNE_COV_CH_MEG_MAG) {\n            magscale += c->cov[mne_lt_packed_index(k,k)]; nmag++;\n        }\n        else if (c->ch_class[k] == MNE_COV_CH_MEG_GRAD) {\n            gradscale += c->cov[mne_lt_packed_index(k,k)]; ngrad++;\n        }\n        else if (c->ch_class[k] == MNE_COV_CH_EEG) {\n            eegscale += c->cov[mne_lt_packed_index(k,k)]; neeg++;\n        }\n#ifdef DEBUG\n        fprintf(stdout,\"%d \",c->ch_class[k]);\n#endif\n    }\n#ifdef DEBUG\n    fprintf(stdout,\"\\n\");\n#endif\n    if (nmag > 0)\n        magscale = magscale > 0.0 ? sqrt(nmag/magscale) : 0.0;\n    if (ngrad > 0)\n        gradscale = gradscale > 0.0 ? sqrt(ngrad/gradscale) : 0.0;\n    if (neeg > 0)\n        eegscale = eegscale > 0.0 ? sqrt(neeg/eegscale) : 0.0;\n#ifdef DEBUG\n    fprintf(stdout,\"%d %g\\n\",nmag,magscale);\n    fprintf(stdout,\"%d %g\\n\",ngrad,gradscale);\n    fprintf(stdout,\"%d %g\\n\",neeg,eegscale);\n#endif\n    scale = MALLOC_30(c->ncov,double);\n    for (k = 0; k < c->ncov; k++) {\n        if (c->ch_class[k] == MNE_COV_CH_MEG_MAG)\n            scale[k] = magscale;\n        else if (c->ch_class[k] == MNE_COV_CH_MEG_GRAD)\n            scale[k] = gradscale;\n        else if (c->ch_class[k] == MNE_COV_CH_EEG)\n            scale[k] = eegscale;\n        else\n            scale[k] = 1.0;\n    }\n    cov    = MALLOC_30(c->ncov*(c->ncov+1)/2.0,double);\n    lambda = MALLOC_30(c->ncov,double);\n    eigen  = ALLOC_CMATRIX_30(c->ncov,c->ncov);\n    for (j = 0; j < c->ncov; j++)\n        for (k = 0; k <= j; k++)\n            cov[mne_lt_packed_index(j,k)] = c->cov[mne_lt_packed_index(j,k)]*scale[j]*scale[k];\n    if (mne_decompose_eigen(cov,lambda,eigen,c->ncov) == 0) {\n#ifdef DEBUG\n        for (k = 0; k < c->ncov; k++)\n            fprintf(stdout,\"%g \",lambda[k]/lambda[c->ncov-1]);\n        fprintf(stdout,\"\\n\");\n#endif\n        nok = 0;\n        for (k = c->ncov-1; k >= 0; k--) {\n            if (lambda[k] >= rank_threshold*lambda[c->ncov-1])\n                nok++;\n            else\n                break;\n        }\n        printf(\"\\n\\tEstimated covariance matrix rank = %d (%g)\\n\",nok,lambda[c->ncov-nok]/lambda[c->ncov-1]);\n        if (use_rank > 0 && use_rank < nok) {\n            nok = use_rank;\n            fprintf(stderr,\"\\tUser-selected covariance matrix rank = %d (%g)\\n\",nok,lambda[c->ncov-nok]/lambda[c->ncov-1]);\n        }\n        /*\n         * Put it back together\n         */\n        for (j = 0; j < c->ncov-nok; j++)\n            lambda[j] = 0.0;\n        data1 = ALLOC_DCMATRIX_30(c->ncov,c->ncov);\n        for (j = 0; j < c->ncov; j++) {\n#ifdef DEBUG\n            mne_print_vector(stdout,NULL,eigen[j],c->ncov);\n#endif\n            for (k = 0; k < c->ncov; k++)\n                data1[j][k] = sqrt(lambda[j])*eigen[j][k];\n        }\n        data2 = mne_dmatt_dmat_mult2(data1,data1,c->ncov,c->ncov,c->ncov);\n#ifdef DEBUG\n        printf(\">>>\\n\");\n        for (j = 0; j < c->ncov; j++)\n            mne_print_dvector(stdout,NULL,data2[j],c->ncov);\n        printf(\">>>\\n\");\n#endif\n        /*\n         * Scale back\n         */\n        for (k = 0; k < c->ncov; k++)\n            if (scale[k] > 0.0)\n                scale[k] = 1.0/scale[k];\n        for (j = 0; j < c->ncov; j++)\n            for (k = 0; k <= j; k++)\n                if (c->cov[mne_lt_packed_index(j,k)] != 0.0)\n                    c->cov[mne_lt_packed_index(j,k)] = scale[j]*scale[k]*data2[j][k];\n        res = nok;\n    }\n    FREE_30(cov);\n    FREE_30(lambda);\n    FREE_CMATRIX_30(eigen);\n    FREE_DCMATRIX_30(data1);\n    FREE_DCMATRIX_30(data2);\n    return res;\n}\n\n\n//*************************************************************************************************************\n\nint MneCovMatrix::mne_decompose_eigen_cov_small(MneCovMatrix *c, float p_small, int use_rank)\n/*\n          * Do the eigenvalue decomposition\n          */\n{\n    int   np,k,p,rank;\n    float rank_threshold = 1e-6;\n\n    if (p_small < 0)\n        p_small = 1.0;\n\n    if (!c)\n        return OK;\n    if (c->cov_diag)\n        return mne_add_inv_cov(c);\n    if (c->lambda && c->eigen) {\n        fprintf(stderr,\"\\n\\tEigenvalue decomposition had been precomputed.\\n\");\n        c->nzero = 0;\n        for (k = 0; k < c->ncov; k++, c->nzero++)\n            if (c->lambda[k] > 0)\n                break;\n    }\n    else {\n        FREE_30(c->lambda); c->lambda = NULL;\n        FREE_CMATRIX_30(c->eigen); c->eigen = NULL;\n\n        if ((rank = condition_cov(c,rank_threshold,use_rank)) < 0)\n            return FAIL;\n\n        np = c->ncov*(c->ncov+1)/2;\n        c->lambda = MALLOC_30(c->ncov,double);\n        c->eigen  = ALLOC_CMATRIX_30(c->ncov,c->ncov);\n        if (mne_decompose_eigen (c->cov,c->lambda,c->eigen,c->ncov) != 0)\n            goto bad;\n        c->nzero = c->ncov - rank;\n        for (k = 0; k < c->nzero; k++)\n            c->lambda[k] = 0.0;\n        /*\n         * Find which eigenvectors correspond to EEG/MEG\n         */\n        {\n            float meglike,eeglike;\n            int   nmeg,neeg;\n\n            nmeg = neeg = 0;\n            for (k = c->nzero; k < c->ncov; k++) {\n                meglike = eeglike = 0.0;\n                for (p = 0; p < c->ncov; p++)  {\n                    if (c->ch_class[p] == MNE_COV_CH_EEG)\n                        eeglike += std::fabs(c->eigen[k][p]);\n                    else if (c->ch_class[p] == MNE_COV_CH_MEG_MAG || c->ch_class[p] == MNE_COV_CH_MEG_GRAD)\n                        meglike += std::fabs(c->eigen[k][p]);\n                }\n                if (meglike > eeglike)\n                    nmeg++;\n                else\n                    neeg++;\n            }\n            printf(\"\\t%d MEG and %d EEG-like channels remain in the whitened data\\n\",nmeg,neeg);\n        }\n    }\n    return mne_add_inv_cov(c);\n\nbad : {\n        FREE_30(c->lambda); c->lambda = NULL;\n        FREE_CMATRIX_30(c->eigen); c->eigen = NULL;\n        return FAIL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nint MneCovMatrix::mne_decompose_eigen_cov(MneCovMatrix *c)\n\n{\n    return mne_decompose_eigen_cov_small(c,-1.0,-1);\n}\n\n\n//*************************************************************************************************************\n\nint MneCovMatrix::mne_lt_packed_index(int j, int k)\n\n{\n    if (j >= k)\n        return k + j*(j+1)/2;\n    else\n        return j + k*(k+1)/2;\n}\n", "meta": {"hexsha": "70e29e0f0de203cd65557010bc2bff191b001eb8", "size": 18355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/mne/c/mne_cov_matrix.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/mne/c/mne_cov_matrix.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/mne/c/mne_cov_matrix.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": 28.1518404908, "max_line_length": 123, "alphanum_fraction": 0.4850994279, "num_tokens": 5124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.01640303209543693, "lm_q1q2_score": 0.00571883712277381}}
{"text": "/***********************************************************************\n*\n* OpenSkeletonFitting\n* Skeleton fitting by the use of energy minimization\n* Copyright (C) 2012 Norman Link <norman.link@gmx.net>\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 \"precompiled.h\"\n#include <iostream>\n#include <stdio.h>\n#include <boost/math/quaternion.hpp>\n#include \"Utils.h\"\n\nusing namespace std;\n\nnamespace osf\n{\n\tbool loadCvMat(const char* filename, cv::Mat& image, float* timestamp)\n\t{\n\t\tif (!filename || strlen(filename) == 0)\n\t\t\t\t\tthrow Exception(\"invalid input filename\");\n\n\t\tFILE* file = NULL;\n\n#ifdef _WIN32\n\t\terrno_t err = fopen_s(&file, filename, \"rb\");\n\t\tif(!file || err) {\n\t\t\tcerr << \"could not open file: \" << filename << endl;\n\t\t\treturn false;\n\t\t}\n#elif __APPLE__ & __MACH__\n\t\tfile = fopen(filename, \"rb\");\n\t\tif(!file || ferror(file)) {\n\t\t\tcerr << \"could not open file: \" << filename << endl;\n\t\t\treturn false;\n\t\t}\n#endif\n\n\t\t// read header\n\t\tint flags = 0;\n\t\tint headerSize = 0;\n\t\tcv::Size imgSize(0, 0);\n\t\tint dims = 0;\n\t\tcv::Size origSize(0, 0);\n\t\tcv::Point startPoint(0, 0);\n\t\tint size = 0;\n\t\tfloat ts = 0;\n\n\t\tchar buffer[4];\n\t\tfread(&buffer, sizeof(char), 3, file);\n\t\tbuffer[3] = '\\0';\n\n\t\tif (strcmp(buffer, \"CVM\") != 0) {\n\t\t\tcerr << \"file does not have cvm format: \" << filename << endl;\n\t\t\tfclose(file);\n\t\t\treturn 0;\n\t\t}\n\n\t\t// read header\n\t\tfread(&headerSize, sizeof(int), 1, file);\n\t\tfread(&flags, sizeof(int), 1, file);\n\t\tfread(&imgSize.width, sizeof(int), 1, file);\n\t\tfread(&imgSize.height, sizeof(int), 1, file);\n\t\tfread(&dims, sizeof(int), 1, file);\n\t\tfread(&origSize.width, sizeof(int), 1, file);\n\t\tfread(&origSize.height, sizeof(int), 1, file);\n\t\tfread(&startPoint.x, sizeof(int), 1, file);\n\t\tfread(&startPoint.y, sizeof(int), 1, file);\n\t\tfread(&size, sizeof(int), 1, file);\n\n\t\t// read timestamp\n\t\tfread(&ts, sizeof(float), 1, file);\n\n\t\tif (timestamp)\n\t\t\t*timestamp = ts;\n\n\t\timage = cv::Mat(origSize.height, origSize.width, CV_MAT_TYPE(flags));\n\n\t\t// set file pointer\n\t\tfseek(file, headerSize, SEEK_SET);\n\n\t\t// read actual data\n\t\tfread(image.data, sizeof(unsigned char), size, file);\n\n\t\t// NOTE: Can be speeded up: don't create new image with the specified roi\n\t\t// like here, but only set image.dataStart and image.dataEnd accordingly\n\t\t// to point to the image region specified by the roi. [9/15/2011 Norman]\n\t\timage = image(cv::Rect(startPoint.x, startPoint.y, imgSize.width, imgSize.height));\n\n\t\tfclose(file);\n\n\t\treturn true;\n\t}\n\n\tbool saveCvMat(const char* filename, const cv::Mat& image)\n\t{\n\t\tif (!filename || strlen(filename) == 0)\n\t\t\tthrow Exception(\"invalid input filename\");\n\t\t\t\t\n\t\tFILE* file = NULL;\n\n#ifdef _WIN32\n\t\terrno_t err = fopen_s(&file, filename, \"wb\");\n\t\tif(!file || err) {\n\t\t\tcerr << \"could not create file: \" << filename << endl;\n\t\t\treturn false;\n\t\t}\n#elif __APPLE__ & __MACH__\n\t\tfile = fopen(filename, \"wb\");\n\t\tif(!file || ferror(file)) {\n\t\t\tcerr << \"could not create file: \" << filename << endl;\n\t\t\treturn false;\n\t\t}\n#endif\n\t\t\n\t\t// process roi information if available\n\t\tsize_t step = image.step;\n\t\tcv::Size origSize = cv::Size(0, 0);\n\t\tcv::Point startPoint = cv::Point(0, 0);\n\t\t\n\t\timage.locateROI(origSize, startPoint);\n\t\tint size = image.elemSize() * origSize.width * origSize.height;\n\t\t\t\t\n\t\t// header size\n\t\tconst int headerSize = 3 * sizeof(char) +\n\t\t\t10 * sizeof(int) +\n\t\t\tsizeof(float);\n\n\t\t// write identification string\n\t\tfwrite(\"CVM\", sizeof(char), 3, file);\n\n\t\t// write header\n\t\tfwrite(&headerSize, sizeof(int), 1, file);\n\t\tfwrite(&image.flags, sizeof(int), 1, file);\n\t\tfwrite(&image.cols, sizeof(int), 1, file);\n\t\tfwrite(&image.rows, sizeof(int), 1, file);\n\t\tfwrite(&image.dims, sizeof(int), 1, file);\n\t\tfwrite(&origSize.width, sizeof(int), 1, file);\n\t\tfwrite(&origSize.height, sizeof(int), 1, file);\n\t\tfwrite(&startPoint.x, sizeof(int), 1, file);\n\t\tfwrite(&startPoint.y, sizeof(int), 1, file);\n\t\tfwrite(&size, sizeof(int), 1, file);\n\n\t\t// write timestamp\n\t\tfloat time = Timer::getTimestamp();\n\t\tfwrite(&time, sizeof(float), 1, file);\n\t\t\n\t\t// write data\n\t\tfwrite(image.data, sizeof(uchar), size, file);\n\t\t\t\t\t\t\n\t\tfclose(file);\n\n\t\treturn true;\n\t}\n\t\n\tvoid matrix2Quat(const double* rot, double* quat)\n\t{\n\t\t// convert rotation matrix to quaternion (adapted from OgreQuaternion.cpp)\n\n\t\tdouble matrix[3][3] = {\n\t\t\t{rot[0], rot[1], rot[2]},\n\t\t\t{rot[3], rot[4], rot[5]},\n\t\t\t{rot[6], rot[7], rot[8]}\n\t\t};\n\n\t\tdouble trace = matrix[0][0] + matrix[1][1] + matrix[2][2];\n\t\tdouble root;\n\n\t\tif (trace > 0.0) {\n\t\t\troot = sqrt(trace + 1.0);\n\t\t\tquat[3] = 0.5 * root;\n\t\t\troot = 0.5 / root;\n\n\t\t\tquat[0] = (matrix[2][1] - matrix[1][2]) * root;\n\t\t\tquat[1] = (matrix[0][2] - matrix[2][0]) * root;\n\t\t\tquat[2] = (matrix[1][0] - matrix[0][1]) * root;\n\t\t}\n\t\telse {\n\t\t\tstatic size_t next[3] = {1, 2, 0};\n\t\t\tsize_t i = 0;\n\t\t\tif (matrix[1][1] > matrix[0][0])\n\t\t\t\ti = 1;\n\t\t\tif (matrix[2][2] > matrix[i][i])\n\t\t\t\ti = 2;\n\t\t\tsize_t j = next[i];\n\t\t\tsize_t k = next[j];\n\n\t\t\troot = sqrt(matrix[i][i] - matrix[j][j] - matrix[k][k] + 1.0);\n\t\t\tdouble* apkQuat[3] = {&quat[0], &quat[1], &quat[2]};\n\t\t\t*apkQuat[i] = 0.5 * root;\n\t\t\troot = 0.5 / root;\n\t\t\tquat[3] = (matrix[k][j] - matrix[j][k]) * root;\n\t\t\t*apkQuat[j] = (matrix[j][i] + matrix[i][j]) * root;\n\t\t\t*apkQuat[k] = (matrix[k][i] + matrix[i][k]) * root;\n\t\t}\n\t}\n\n\tvoid matrix2Quat(const cv::Mat& rot, quaternion<double>& quat)\n\t{\n\t\tif (rot.type() != CV_64F)\n\t\t\tthrow Exception(\"invalid type\");\n\n\t\tdouble q[4] = { quat.R_component_2(),\n\t\t\tquat.R_component_3(),\n\t\t\tquat.R_component_4(),\n\t\t\tquat.R_component_1() };\n\t\t\n\t\tmatrix2Quat((double*)&rot.data[0], q);\n\n\t\tquat = boost::math::quaternion<double>(q[3], q[0], q[1], q[2]);\n\t}\n\n\tvoid quat2Matrix(const double* quat, double* rot)\n\t{\n\t\t// convert quaternion to rotation matrix (adapted from OgreQuaternion.cpp)\n\n\t\tdouble tx = quat[0] + quat[0];\n\t\tdouble ty = quat[1] + quat[1];\n\t\tdouble tz = quat[2] + quat[2];\n\t\tdouble twx = tx * quat[3];\n\t\tdouble twy = ty * quat[3];\n\t\tdouble twz = tz * quat[3];\n\t\tdouble txx = tx * quat[0];\n\t\tdouble txy = ty * quat[0];\n\t\tdouble txz = tz * quat[0];\n\t\tdouble tyy = ty * quat[1];\n\t\tdouble tyz = tz * quat[1];\n\t\tdouble tzz = tz * quat[2];\n\t\t\n\t\tdouble matrix[3][3];\n\n\t\tmatrix[0][0] = 1.0 - (tyy + tzz);\n\t\tmatrix[0][1] = txy - twz;\n\t\tmatrix[0][2] = txz + twy;\n\t\tmatrix[1][0] = txy + twz;\n\t\tmatrix[1][1] = 1.0 - (txx + tzz);\n\t\tmatrix[1][2] = tyz - twx;\n\t\tmatrix[2][0] = txz - twy;\n\t\tmatrix[2][1] = tyz + twx;\n\t\tmatrix[2][2] = 1.0 - (txx + tyy);\n\n\t\trot[0] = matrix[0][0];\n\t\trot[1] = matrix[0][1];\n\t\trot[2] = matrix[0][2];\n\t\trot[3] = matrix[1][0];\n\t\trot[4] = matrix[1][1];\n\t\trot[5] = matrix[1][2];\n\t\trot[6] = matrix[2][0];\n\t\trot[7] = matrix[2][1];\n\t\trot[8] = matrix[2][2];\n\t}\n\n\tvoid quat2Matrix(const quaternion<double>& quat, cv::Mat& rot)\n\t{\n\t\tif (!rot.empty() && rot.type() != CV_64F)\n\t\t\tthrow Exception(\"invalid type\");\n\t\telse\n\t\t\trot = cv::Mat(3, 3, CV_64FC1);\n\n\t\tdouble q[4] = { quat.R_component_2(),\n\t\t\tquat.R_component_3(),\n\t\t\tquat.R_component_4(),\n\t\t\tquat.R_component_1() };\n\t\t\n\t\tquat2Matrix(q, (double*)&rot.data[0]);\n\t}\n\t\n\tvoid euler2Quat(quaternion<double>& quat, double angleX, double angleY, double angleZ)\n\t{\n\t\tdouble r = DEG2RAD(angleX / 2.0);\n\t\tdouble p = DEG2RAD(angleY / 2.0);\n\t\tdouble y = DEG2RAD(angleZ / 2.0);\n \n\t\tdouble sinp = sin(p);\n\t\tdouble siny = sin(y);\n\t\tdouble sinr = sin(r);\n\t\tdouble cosp = cos(p);\n\t\tdouble cosy = cos(y);\n\t\tdouble cosr = cos(r);\n\t\t\n\t\tquat = quaternion<double>(\n\t\t\tcosr * cosp * cosy + sinr * sinp * siny,\n\t\t\tsinr * cosp * cosy - cosr * sinp * siny,\n\t\t\tcosr * sinp * cosy + sinr * cosp * siny,\n\t\t\tcosr * cosp * siny - sinr * sinp * cosy);\n\n\t\t// normalize\n\t\tquat /= norm(quat);\n\n\t\t/*quaternion<double> quatX(0, 0, 0, 0);\n\t\taxis2Quat(quatX, cv::Point3d(1, 0, 0), angleX);\n\n\t\tquaternion<double> quatY(0, 0, 0, 0);\n\t\taxis2Quat(quatY, cv::Point3d(0, 1, 0), angleY);\n\n\t\tquaternion<double> quatZ(0, 0, 0, 0);\n\t\taxis2Quat(quatZ, cv::Point3d(0, 0, 1), angleZ);\n\n\t\tquat = quatX * quatY * quatZ;\n\t\tquat /= norm(quat);*/\n\t}\n\n\tvoid quat2Euler(const quaternion<double>& quat, double& angleX, double& angleY, double& angleZ)\n\t{\n\t\tquaternion<double> myQuat = quat;\n\t\tmyQuat /= norm(myQuat);\n\n\t\tcv::Point3d euler(0, 0, 0);\n\n\t\tdouble qW = myQuat.R_component_1();\n\t\tdouble qX = myQuat.R_component_2();\n\t\tdouble qY = myQuat.R_component_3();\n\t\tdouble qZ = myQuat.R_component_4();\n\t\t\n\t\tdouble test = (qW * qY - qZ * qX);\n\t\tdouble unit = qX * qX + qY * qY + qZ * qZ + qW * qW;\n\t\t\n\t\t// handle singularities\n\t\tif (test > 0.4999999 * unit) {\n\t\t\teuler.x = 2 * atan2(qX, qW);\n\t\t\teuler.y = M_PI / 2.0;\n\t\t\teuler.z = 0;\n\t\t}\n\t\telse if (test < -0.4999999 * unit) {\n\t\t\teuler.x = 2 * atan2(qX, qW);\n\t\t\teuler.y = -M_PI / 2.0;\n\t\t\teuler.z = 0;\n\t\t}\n\t\telse {\n\t\t\teuler.x = atan2(2 * (qW * qX + qY * qZ), 1 - 2 * (qX * qX + qY * qY));\n\t\t\teuler.y = asin(2 * test);\n\t\t\teuler.z = atan2(2 * (qW * qZ + qX * qY), 1 - 2 * (qY * qY + qZ * qZ));\n\t\t}\n\n\t\tangleX = RAD2DEG(euler.x);\n\t\tangleY = RAD2DEG(euler.y);\n\t\tangleZ = RAD2DEG(euler.z);\n\t}\n\n\tvoid axis2Quat(quaternion<double>& quat, const cv::Point3d& axis, double angle)\n\t{\n\t\tcv::Point3d myAxis = axis;\n\t\tmyAxis *= (1.0 / cv::norm(myAxis));\n\n\t\tdouble halfAngle = DEG2RAD(angle / 2.0);\n\t\tdouble sinAngle = sin(halfAngle);\n\n\t\tquat = quaternion<double>(cos(halfAngle),\n\t\t\tmyAxis.x * sinAngle, myAxis.y * sinAngle, myAxis.z * sinAngle);\n\t}\n\n\tvoid quat2Axis(const quaternion<double>& quat, cv::Point3d& axis, double& angle)\n\t{\n\t\tquaternion<double> myQuat = quat;\n\t\tdouble qw = myQuat.R_component_1();\n\n\t\t// normalize\n\t\tif (qw > 1.0)\n\t\t\tmyQuat /= norm(myQuat);\n\t\t\n\t\tangle = RAD2DEG(2.0 * acos(qw));\n\t\tdouble s = sqrt(1.0 - qw * qw);\n\n\t\tif (s < 0.0001) {\n\t\t\t// avoid divbyzero, any arbitrary axis is valid\n\t\t\taxis.x = 0;\n\t\t\taxis.y = 1;\n\t\t\taxis.z = 0;\n\t\t}\n\t\telse {\n\t\t\taxis.x = myQuat.R_component_2() / s;\n\t\t\taxis.y = myQuat.R_component_3() / s;\n\t\t\taxis.z = myQuat.R_component_4() / s;\n\t\t}\n\t}\n\n\tvoid quatRotate(const quaternion<double>& quat, cv::Point3d& point)\n\t{\n\t\tquaternion<double> pointTemp(0, point.x, point.y, point.z);\n\t\tpointTemp = conj(quat) * pointTemp * quat;\n\t\tpoint = cv::Point3d(pointTemp.R_component_2(), pointTemp.R_component_3(),\n\t\t\tpointTemp.R_component_4());\n\t}\n\t\n\tvoid quatRotateInv(const quaternion<double>& quat, cv::Point3d& point)\n\t{\n\t\tquaternion<double> pointTemp(0, point.x, point.y, point.z);\n\t\tpointTemp = quat * pointTemp * conj(quat);\n\t\tpoint = cv::Point3d(pointTemp.R_component_2(), pointTemp.R_component_3(),\n\t\t\tpointTemp.R_component_4());\n\t}\n}\n", "meta": {"hexsha": "ed12b6287a3c67e49d79da661676415e6f9a5c3c", "size": 11030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OpenSF/Utils.cpp", "max_stars_repo_name": "Norman0406/OpenSkeletonFitting", "max_stars_repo_head_hexsha": "43a6ba856a629a8b67683605194e90c1a2846300", "max_stars_repo_licenses": ["DOC"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-04-06T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T18:16:41.000Z", "max_issues_repo_path": "OpenSF/Utils.cpp", "max_issues_repo_name": "solbach/open-skeleton-fitting", "max_issues_repo_head_hexsha": "80f53861481eb9998a26993f4a22478e97e3748b", "max_issues_repo_licenses": ["DOC"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-07-08T16:23:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-23T15:00:20.000Z", "max_forks_repo_path": "OpenSF/Utils.cpp", "max_forks_repo_name": "solbach/open-skeleton-fitting", "max_forks_repo_head_hexsha": "80f53861481eb9998a26993f4a22478e97e3748b", "max_forks_repo_licenses": ["DOC"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T14:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T18:16:47.000Z", "avg_line_length": 27.1007371007, "max_line_length": 96, "alphanum_fraction": 0.6089755213, "num_tokens": 3825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127756822482, "lm_q2_score": 0.02262920122773129, "lm_q1q2_score": 0.005677955691522196}}
{"text": "/*\n    Copyright (c) 2011-2014 University of Zurich\n    \n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n    \n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n    \n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n*/\n\n#ifndef PLLL_INCLUDE_GUARD__PLLL2_LLL_HPP\n#define PLLL_INCLUDE_GUARD__PLLL2_LLL_HPP\n\n/**\n   \\file\n   \\brief Main header for the `plll` library.\n   \n   This is the main header for the `plll` lattice reduction library. It is usually the only header\n   you have to include to use the library. It provides the main namespace, [plll](@ref plll),\n   which contains all definitions.\n   \n   Most prominently, it contains the class [LatticeReduction](@ref plll::LatticeReduction), which\n   provides the main interface to all lattice reduction algorithms.\n*/\n\n/**\n   \\dir /plll/include\n   \\brief Contains the main `plll` header `plll.hpp`.\n */\n\n/**\n   \\dir /plll/include/plll\n   \\brief Contains individual public headers for the `plll` library.\n */\n\n#include <plll/config.hpp>\n#include <plll/arithmetic.hpp>\n#include <plll/arithmetic-nint.hpp>\n#include <plll/matrix.hpp>\n#include <exception>\n#include <iostream>\n#include <limits>\n#include <boost/function.hpp>\n\n/**\n   \\brief Contains the `plll` library.\n   \n   The `plll` namespace contains all definitions of the `plll` library.\n*/\nnamespace plll\n{\n    class LatticeReductionImpl;\n    \n    class LatticeReduction\n    /**\n       \\brief Provides an interface to the lattice reduction algorithms of the `plll` library.\n       \n       This class provides an interface to all lattice reduction algorithms of the `plll`\n       library. It is possible to configure the algorithms using the interface and execute them. The\n       lattice can be set and retrieved, and also callback functions can be set up.\n    */\n    {\n    private:\n        std::auto_ptr<LatticeReductionImpl> d_impl; /// A pointer to the implementation. Used to hide internals\n                                                    /// of the implementation from the user.\n        \n        // Disable copy constructor and operator\n        LatticeReduction(const LatticeReduction &);\n        LatticeReduction & operator = (const LatticeReduction &);\n        \n    public:\n        /**@{\n           \\name Exceptions.\n         */\n        class stop_reduction : public std::exception\n        /**\n           \\brief This exception should be thrown by callback functions to stop reduction and return\n                  the current state of reduction to the caller.\n           \n           \\see \\ref desc-genconf-callback\n         */\n        {\n        public:\n            virtual ~stop_reduction() PLLL_INTERNAL_NOTHROW_POSTFIX_ENFORCE\n            {\n            }\n            \n            virtual const char * what() const PLLL_INTERNAL_NOTHROW_POSTFIX_ENFORCE;\n        };\n        \n        class stop_enumeration : public std::exception\n        /**\n           \\brief This exception should be thrown by callback functions to stop enumeration and\n                  return the currently found vector to the caller.\n           \n           \\see \\ref desc-genconf-callback\n         */\n        {\n        public:\n            virtual ~stop_enumeration() PLLL_INTERNAL_NOTHROW_POSTFIX_ENFORCE\n            {\n            }\n            \n            virtual const char * what() const PLLL_INTERNAL_NOTHROW_POSTFIX_ENFORCE;\n        };\n        ///@}\n        \n        /**@{\n           \\name Configuration enums.\n         */\n        enum Arithmetic\n        /**\n           \\brief Specifies which arithmetic to use for Gram-Schmidt orthogonalization.\n           \n           Specifies which arithmetic should be used by the `plll` library for Gram-Schmidt\n           orthogonalizations. The choice of arithmetics might vary depending on the platform, but\n           except for \"Fast Compile\" scenarios, at least rational, real, long double and double\n           arithmetic is supported.\n           \n           \\see \\ref desc-genconf-arith\n        */\n        {\n            A_Rational,\n            /**< Rational arithmetic, i.e. a pair of `arithmetic::Integer` objects is used for numerator\n                 and denominator. While this yields infinite precision, it is also quite slow.\n            */\n            A_Real,\n            /**< MPFR-based `arithmetic::Real` arithmetic. This is a floating point type with arbitrary\n                 (but fixed) precision. A precision is automatically selected by the library.\n            */\n            A_LongDouble,\n            /**< The system's native `long double` arithmetic. This is a finite-precision floating\n                 point type with implementation defined precision. On Intel/AMD/... platforms, it\n                 usually provides a mantissa of 80 bits, while on UltraSparc platforms, this is a\n                 Float128 type with 112 bit mantissa, whose arithmetic is unfortunately usually\n                 implemented in software and not in hardware.\n                 \n                 This is the default setting for `plll`.\n            */\n            A_Double,\n            /**< The system's native `double` arithmetic. This is a finite-precision floating point\n                 type with implementation defined precision. It usually has a mantissa of 53 bits.\n            */\n            A_DoubleDouble,\n            /**< Uses two native `double` floating point numbers to represent floating point numbers\n                 with higher precision. While the exponent is still limited to a `double`'s range,\n                 the precision is much higher; double double numbers correspond to floating point\n                 numbers with a mantissa of 104 bits.\n                 \n                 Support for this arithmetic depends on the libqd library by Yozo Hida. It\n                 apparently does not work on UltraSparc CPUs.\n            */\n            A_QuadDouble,\n            /**< Uses four native `double` floating point numbers to represent floating point\n                 numbers with higher precision. While the exponent is still limited to a `double`'s\n                 range, the precision is much higher; quad double numbers correspond to floating\n                 point numbers with a mantissa of 209 bits.\n                 \n                 Support for this arithmetic depends on the libqd library by Yozo Hida. It\n                 apparently does not work on UltraSparc CPUs.\n            */\n            A_Default = A_LongDouble\n            /**< Alias for the default arithmetic, i.e. for `A_LongDouble`. */\n        };\n        \n        enum Integers\n        /**\n           \\brief Specifies which arithmetic to use for integer operations.\n           \n           Specifies which arithmetic should be used by the `plll` library for integer\n           operations. Besides GMP-based arbitrary precision integers, it also provides support for\n           system-dependent `long int` integers and for an automatic decision mode which uses\n           arbitrary precision integers if necessary and system integers otherwise.\n           \n           \\see \\ref desc-genconf-arith\n         */\n        {\n            I_Auto,\n            /**< Decides based on the input whether to use arbitrary precision integer arithmetic or\n                 system-dependent integer arithmetic. This decision is analyzed from time to time,\n                 and arithmetic is changed when necessary.\n                 \n                 This is the default setting for `plll`.\n            */\n            I_ArbitraryPrecision,\n            /**< Uses `arithmetic::Integer` arbitrary precision integers. These are provided by GMP and\n                 are only limited by the system's available RAM.\n            */\n            I_LongInt,\n            /**< Uses `long int` native CPU arithmetic. On modern CPUs, this yields at least 64 bits\n                 of precision.\n            */\n            I_Default = I_Auto\n            /**< Alias for the default integer arithmetic, i.e. for `A_Auto`. */\n        };\n        \n        enum GramSchmidt\n        /**\n           \\brief Specifies which Gram-Schmidt orthogonalization is used.\n           \n           Specifies which Gram-Schmidt orthogonalization should be used by the `plll`\n           library. Always available are classic GS, classic GS with integer arithmetic, and\n           numerically stable GS. For floating-point arithmetic, also Givens rotations can be used\n           for GS orthogonalization.\n           \n           \\see \\ref desc-genconf-gs\n         */\n        {\n            G_Classic,\n            /**< \"Classical\" Gram-Schmidt orthogonalization. Uses formulae to update Gram-Schmidt\n                 coefficients on swaps, transformations etc., which can introduce additional error\n                 with floating point arithmetic.\n            */\n            G_ClassicInteger,\n            /**< Integer-based Gram-Schmidt orthogonalization. Internally uses arbitrary precision\n                 integers respectively rational numbers. Slow, but always accurate.\n            */\n            G_Givens,\n            /**< Uses Givens rotations to compute Gram-Schmidt orthogonalization. Only available for\n                 floating-point arithmetic (i.e. everything but `A_Rational`). Uses formulae to\n                 update Gram-Schmidt coefficients on swaps, transformations etc., which can\n                 introduce additional error with floating point arithmetic.\n            */\n            G_NumStable,\n            /**< Uses numerically stable Gram-Schmidt orthogonalization as described by P. Q. Nguyen\n                 and D. Stehle in\n                 \\cite nguyen-stehle-fplll-revisited. This arithmetic is more resilient against\n                 approximation errors than other approaches. Instead of updating GS coefficients for\n                 swaps, transformations etc., these are recomputed to ensure maximal precision.\n                 \n                 This is the default setting for `plll`.\n            */\n            G_Default = G_NumStable\n            /**< Alias for the default Gram-Schmidt orthogonalization, i.e. for `A_NumStable`. */\n        };\n        \n        enum Transform\n        /**\n           \\brief Specifies which transformation matrix is computed.\n           \n           Specifies which kind of transformation matrix is computed by the `plll` library, if\n           computation of transformation matrices is requested.\n         */\n        {\n            T_Normal,\n            /**< Computes a transformation matrix \\f$T_1\\f$ such that if \\f$A\\f$ is the old and\n                 \\f$A'\\f$ the new matrix representing the lattice before respectively after\n                 reduction, then \\f$T_1 \\cdot A = A'\\f$.\n            */\n            T_Inverse\n            /**< Computes a transformation matrix \\f$T_2\\f$ such that if \\f$A\\f$ is the old and\n                 \\f$A'\\f$ the new matrix representing the lattice before respectively after\n                 reduction, then \\f$T_2 \\cdot A' = A\\f$. Note that if the matrices are square, then\n                 both are invertible and \\f$T_2 = T_1^{-1}\\f$.\n            */\n        };\n        \n        enum LLLMode\n        /**\n           \\brief Specifies which LLL condition is used.\n           \n           Specifies which LLL condition is used by the `plll` library. One can choose between the\n           original condition introduced by Lenstra, Lenstra and Lovász, a \"unprojected\" variant\n           comparing the norms in the ambient space, and the Siegel condition.\n         */\n        {\n            LLL_Classic,\n            /**< The original condition by Lenstra, Lenstra and Lovász, called the *Lovász\n                 condition*, which compares the projected lengths of two adjacent vectors, where the\n                 vectors are projected onto the orthogonal complement of all previous vectors.\n                 \n                 In terms of the Gram-Schmidt orthogonalization \\f$\\pi_1(b_1), \\dots, \\pi_k(b_k)\\f$\n                 of the basis \\f$b_1, \\dots, b_k\\f$, this condition can be expressed as \\f$\\alpha\n                 \\cdot \\|\\pi_k(b_k)\\|^2 > \\|\\pi_k(b_{k+1})\\|^2\\f$.\n                 \n                 This is the default setting for `plll`.\n                 \n                 \\see \\ref desc-algs-lll-classic\n            */\n            LLL_Unprojected,\n            /**< A simpler condition, which compares the unprojected lengths of two adjacent.\n\n                 In terms of the basis \\f$b_1, \\dots, b_k\\f$, this condition can be expressed as\n                 \\f$\\alpha \\cdot \\|b_k\\|^2 > \\|b_{k+1}\\|^2\\f$.\n                 \n                 \\see \\ref desc-algs-lll-unproj\n            */\n            LLL_Siegel,\n            /**< A simpler condition, which allows to prove the same bounds on the output quality,\n                 called the *Siegel condition*. Note that the Lovász condition implies the Siegel\n                 condition.\n                 \n                 In terms of the Gram-Schmidt orthogonalization \\f$\\pi_1(b_1), \\dots, \\pi_k(b_k)\\f$\n                 of the basis \\f$b_1, \\dots, b_k\\f$, this condition can be expressed as\n                 \\f$\\frac{3}{4} \\cdot \\alpha \\cdot \\|\\pi_k(b_k)\\|^2 > \\|\\pi_{k+1}(b_{k+1})\\|^2\\f$.\n                 \n                 \\see \\ref desc-algs-lll-siegel\n            */\n            LLL_Default = LLL_Classic\n            /**< Alias for the default LLL condition, i.e. for `LLL_Classic`. */\n        };\n        \n        enum BKZMode\n        /**\n           \\brief Specifies which BKZ algorithm is used.\n           \n           Specifies which BKZ algorithm is used by the `plll` library. Note that BKZ is somewhat\n           misleading here, since most of these algorithms are known under completely different\n           names. What all these algorithms have in common that they compute Korkine-Zolotarev or at\n           least SVP bases for certain blocks of (projected) basis vectors, or their dual.\n         */\n        {\n            BKZ_SchnorrEuchner,\n            /**< The classical Schnorr-Euchner BKZ algorithm, as described in Section 6 of\n                 \\cite schnorr-euchner-BKZ by C.-P. Schnorr and M. Euchner.\n                 \n                 This is the default setting for `plll`.\n                 \n                 \\see \\ref dest-algs-bkz-schnorreuchner\n            */\n            BKZ_Simplified,\n            /**< A simplified version of the BKZ algorithm, as described by G. Hanrot, X. Pujol and\n                 D. Stehle in\n                 \\cite hanrot-pujol-stehle-BKZdynamic.\n                 \n                 \\see \\ref dest-algs-bkz-simplified\n            */\n            BKZ_HanrotPujolStehleHKZ,\n            /**< A \"Terminating BKZ\" variant of the simplified version of the BKZ algorithm, as\n                 described by G. Hanrot, X. Pujol and D. Stehle in\n                 \\cite hanrot-pujol-stehle-BKZdynamic. This version computes\n                 Hermite-Korkine-Zolotarev (HKZ) bases for every block.\n                 \n                 \\see \\ref dest-algs-bkz-terminating\n            */\n            BKZ_HanrotPujolStehleSVP,\n            /**< A \"Terminating BKZ\" variant of the simplified version of the BKZ algorithm, as\n                 described by G. Hanrot, X. Pujol and D. Stehle in\n                 \\cite hanrot-pujol-stehle-BKZdynamic. This version computes Shortest Vector (SVP)\n                 bases for every block.\n                 \n                 \\see \\ref dest-algs-bkz-terminating\n            */\n            BKZ_PrimalDual,\n            /**< The primal-dual BKZ algorithm by H. Koy, as described in Section 3 of\n                 \\cite schnorr-bkzrevisited\n                 \n                 \\see \\ref dest-algs-bkz-primaldual\n            */\n            BKZ_SlideReduction,\n            /**< The slide reduction algorithm, as described by N. Gama and P. Q. Nguyen in\n                 \\cite gama-nguyen-mordellsinequality.\n                 \n                 \\see \\ref dest-algs-bkz-slide\n            */\n            BKZ_ImprovedSlideReduction,\n            /**< A improved and accelerated version of Slide Reduction, as described in\n                 \\cite schnorr-accslide by C.-P. Schnorr (Section 3).\n                 \n                 \\see \\ref dest-algs-bkz-improvslide\n            */\n            BKZ_ImprovedSlideReduction2,\n            /**< A improved and accelerated version of Slide Reduction, as described in\n                 \\cite schnorr-accslide by C.-P. Schnorr (Section 3).\n                 \n                 This variant uses a larger dual SVP enumeration and a single primal SVP\n                 enumeration.\n                 \n                 \\see \\ref dest-algs-bkz-improvslide\n            */\n            BKZ_ImprovedSlideReduction3,\n            /**< A improved and accelerated version of Slide Reduction, as described in\n                 \\cite schnorr-accslide by C.-P. Schnorr (Section 3).\n                 \n                 This variant uses a single larger primal SVP enumeration and one dual SVP\n                 enumeration.\n                 \n                 \\see \\ref dest-algs-bkz-improvslide\n            */\n            BKZ_SemiBlock2k,\n            /**< The semi block 2k-reduction, as described by C.-P. Schnorr in Section 2 of\n                 \\cite schnorr-bkzrevisited.\n                 \n                 \\see \\ref dest-algs-bkz-semiblock2k\n            */\n            BKZ_SamplingReduction,\n            /**< The Sampling Reduction, as described by J. A. Buchmann and C. Ludwig in\n                 \\cite buchmann-ludwig-samplingreduction.\n                 \n                 \\see \\ref dest-algs-bkz-sr\n            */\n            BKZ_Experimental, // An experimental variant which should *not* be used.\n            BKZ_Default = BKZ_SchnorrEuchner\n            /**< Alias for the default BKZ variant, i.e. for `BKZ_SchnorrEuchner`. */\n        };\n        \n        enum SVPMode\n        /**\n           \\brief Specifies which SVP solver is used.\n           \n           Specifies which SVP solver is used by the `plll` library. For small enough dimensions,\n           always a simple (but efficient) enumeration variant is used, except for the highest level\n           reduction, where always the selected solver is used.\n         */\n        {\n            SVP_KannanSchnorrEuchner,\n            /**< A variant of the Kannan-Schnorr-Euchner enumeration algorithm\n                 \\cite schnorr-euchner-BKZ with various improvements; see, for example, Appendix B of\n                 \\cite gama-nguyen-regev-extremepruning.\n                 \n                 \\see \\ref desc-algs-svp-kse\n            */\n            SVP_ParallelKannanSchnorrEuchner,\n            /**< A parallelized variant of the Kannan-Schnorr-Euchner enumeration algorithm\n                 \\cite schnorr-euchner-BKZ with various improvements. The parallelization uses\n                 multiple cores. There is almost no communication between cores, except if a shorter\n                 vector is found by one, or if one core runs out of work and asks others to split\n                 their workload.\n                 \n                 This is the default setting for `plll`. Note that in case only one core is\n                 available, automatically the solver `SVP_KannanSchnorrEuchner` will be used.\n                 \n                 \\see \\ref desc-algs-svp-kse\n            */\n            SVP_SchnorrFast,\n            /**< A (single threaded) version of Schnorr's new SVP solver, as described in\n                 \\cite schnorr-factoringcvp by C.-P. Schnorr.\n                 \n                 This implementation is still experimental.\n                 \n                 \\see \\ref desc-algs-svp-schnorr\n            */\n            SVP_VoronoiCellSVP,\n            /**< A deterministic SVP solver which first computes the voronoi cell of the\n                 lattice. While being deterministic and asymptotically faster than enumeration, in\n                 practice this algorithm is only usable for very low dimensions, say at most 10,\n                 where enumeration is still much faster. This algorithm was described by\n                 D. Micciancio and P. Voulgaris in\n                 \\cite micciancio-voulgaris-voronoicell.\n                 \n                 \\see \\ref desc-algs-svp-voronoi\n            */\n            SVP_ListSieve,\n            /**< The probabilistic list sieve SVP solver. It was described by D. Micciancio and\n                 P. Voulgaris in Section 3.1 of\n                 \\cite micciancio-voulgaris-fastersvp.\n                 \n                 This implementation is still experimental.\n                 \n                 \\see \\ref desc-algs-svp-list\n            */\n            SVP_ListSieveBirthday,\n            /**< The probabilistic list sieve (with birthday paradox exploitation) SVP solver. It\n                 was described by X. Pujol and D. Stehle in the paper\n                 \\cite pujol-stehle-birthdaysieve.\n                 \n                 This implementation is still experimental.\n                 \n                 \\see \\ref desc-algs-svp-lsb\n            */\n            SVP_GaussSieve,\n            /**< The probabilistic Gauss sieve SVP solver. It was described by D. Micciancio and\n                 P. Voulgaris in Section 3.2 of\n                 \\cite micciancio-voulgaris-fastersvp. Our implementation is similar to <a\n                 href=\"http://cseweb.ucsd.edu/~pvoulgar/impl.html\">one by P. Voulgaris</a>.\n                 \n                 \\see \\ref desc-algs-svp-gauss\n            */\n            SVP_Default = SVP_ParallelKannanSchnorrEuchner\n            /**< Alias for the default SVP solver, i.e. for `SVP_ParallelKannanSchnorrEuchner`. */\n        };\n        \n        enum DIMethod\n        /**\n           \\brief Specifies which Deep Insertion mode is used.\n           \n           Specifies which Deep Insertion mode is used by the `plll` library. Note that Deep\n           Insertions are not supported directly by all LLL and BKZ algorithms, but will be used by\n           recursive LLL and BKZ calls.\n           \n           The idea of Deep Insertions is that while usual LLL only swaps adjacent vectors, Deep\n           Insertions also compares the current vectors with more previous vectors to decide where\n           it could be inserted.\n         */\n        {\n            DI_None,\n            /**< Disable Deep Insertions.\n                 \n                 This is the default setting for `plll`.\n            */\n            DI_Classic,\n            /**< Uses classic Deep Insertions as described by C.-P. Schnorr and M. Euchner in\n                 \\cite schnorr-euchner-BKZ.\n            */\n            DI_MinimizePotential1,\n            /**< Uses potential minimizing Deep Insertions (PotLLL) as described by F. Fontein,\n                 M. Schneider and U. Wagner in\n                 \\cite fontein-schneider-wagner-minpot-wcc and\n                 \\cite fontein-schneider-wagner-potlll.\n            */\n            DI_MinimizePotential2,\n            /**< Uses a variant of the potential minimizing Deep Insertions (PotLLL2) as described\n                 by F. Fontein, M. Schneider and U. Wagner in\n                 \\cite fontein-schneider-wagner-potlll. See \"PotLLL2\" in Section 3.1.\n            */\n            DI_Default = DI_None\n            /**< Alias for the default Deep Insertions mode, i.e. for `DI_None`. */\n        };\n        \n        enum DIChoice\n        /**\n           \\brief Specifies which Deep Insertion choice is used.\n           \n           Specifies which vectors are considered for Deep Insertions by the `plll` library.\n         */\n        {\n            DIC_First,\n            /**< Deep Insertions considers only the first t vectors of the basis, where t is given.\n            */\n            DIC_Block,\n            /**< Deep Insertions considers only the block of t basis vectors ending at the current\n                 vector, where t is given.\n            */\n            DIC_FirstBlock,\n            /**< Deep Insertions considers both the first t basis vectors, and the block of t basis\n                 vectors ending at the current vector, where t is given.\n                 \n                 This is the default setting for the LLL reduction in V. Shoup's Number Theory\n                 Library, if Deep Insertions are enabled.\n            */\n            DIC_All,\n            /**< Deep Insertions considers all basis vectors as possible destinations.\n                 \n                 This is the default setting for `plll`.\n            */\n            DIC_Default = DIC_All\n            /**< Alias for the default Deep Insertions choice, i.e. for `DIC_All`. */\n        };\n        \n        enum DIMode\n        /**\n           \\brief Specifies which Deep Insertions mode is used.\n           \n           Specifies which kind Deep Insertions mode is used, i.e. whether the insertions are done\n           before and/or after size reduction.\n         */\n        {\n            DIM_BeforeSR,\n            /**< Do Deep Insertions only before size reduction.\n            */\n            DIM_AfterSR,\n            /**< Do Deep Insertions only after size reduction.\n            */\n            DIM_Both,\n            /**< Do Deep Insertions both before and after size reduction.\n                 \n                 This is the default setting for `plll`.\n            */\n            DIM_Default = DIM_Both\n            /**< Alias for the default Deep Insertions mode, i.e. for `DIM_Both`. */\n        };\n        \n        enum VerboseOutputLevel\n        /**\n            \\brief Specifies the verbosity output level.\n            \n            Specifies the verbosity output level of the `plll` library. It can be configured\n            between no output, and full output. Note that by outputting, it is meant that the\n            specified `VerboseFunction` is called (or its default, which uses `std::cerr`).\n            \n            \\see \\ref desc-genconf-verbose\n        */\n        {\n            VOL_None,\n            /**< Outputs nothing. */\n            VOL_Warnings,\n            /**< Outputs only warnings and errors. */\n            VOL_Informative,\n            /**< Outputs warnings, errors and informative messages. */\n            VOL_Full\n            /**< Outputs everything. */\n        };\n        \n        enum VerboseLevel\n        /**\n            \\brief Specifies a warning level for a specific output message.\n            \n            Specifies the level of a specific output message. This is used to inform a\n            `VerboseFunction` callback function which level the given message has.\n            \n            \\see \\ref desc-genconf-verbose\n        */\n        {\n            VL_Error,\n            /**< The given message is an error. */\n            VL_Warning,\n            /**< The given message is a warning. */\n            VL_Information,\n            /**< The given message is purely informative. */\n            VL_Chatter\n            /**< The given message is chatter which can safely be ignored. Can be helpful for\n                 debugging purposes or to see more about how the algorithms work. */\n        };\n        ///@}\n        \n        struct Statistics\n        /**\n           \\brief Describes lattice basis reduction statistics.\n           \n           Describes statistics collected while reducting lattice bases. These statistics count the\n           numer of operations done.\n         */\n        {\n            unsigned long swaps;\n            /**< Counts the number of times two adjacent vectors are swapped.\n            */\n            unsigned long adds;\n            /**< Counts the number of times a non-zero multiple of a basis vector was added to\n                 another basis vector.\n            */\n            unsigned long adds_pm1;\n            /**< Counts the number of times a basis vector was added or subtracted from another\n                 basis vector. This number is never larger than `adds`.\n            */\n            unsigned long adds_pm2;\n            /**< Counts the number of times a basis vector was added or subtracted twice from\n                 another basis vector. This number is never larger than `adds`.\n            */\n            unsigned long flips;\n            /**< Counts the number of times a basis vector was flipped, i.e. all its signs where\n                 changed.\n            */\n            unsigned long trans;\n            /**< Counts the number of times a 2 x 2 invertible transformation was applied to two\n                 basis vectors.\n            */\n            unsigned long sizereductions;\n            /**< Counts the number of applied size reductions.\n            */\n            unsigned long deepinsertions;\n            /**< Counts the number of Deep Insertions with insertion distance at least 2. (An\n                 insertion distance of 1 is counted by `swaps`.)\n            */\n            unsigned long enumcalls;\n            /**< Counts the number of calls to the SVP solver.\n            */\n            unsigned long enumfails;\n            /**< Counts the number of calls to the SVP solver where the solver did not find any\n                 vector at all. (This happens if heuristics for the enumeration radius are used\n                 which are too small.)\n            */\n            unsigned long vectorinsertions;\n            /**< Counts the number of insertions of (completely) new vectors. This can be a result\n                 of enumeration or of Sampling Reduction.\n            */\n            unsigned long vectorinsertions_rearrange;\n            /**< Counts the number of where the basis is rearranged to move one basis vector to an\n                 earlier position. This is usually the result of an SVP solver returning a vector\n                 which already is part of the basis.\n            */\n            \n            void reset(); ///< \\brief Resets the statistics.\n            Statistics(); ///< \\brief Creates a new statistics object with all values set to zero.\n        };\n        \n        class GramSchmidtInformer\n        /**\n           \\brief Provides information on the Gram-Schmidt coefficients.\n           \n           An interface for a Gram-Schmidt Informer, which is a little object providing access to\n           the Gram-Schmidt coefficients. This is for example provided to annealing callbacks.\n        */\n        {\n        protected:\n            GramSchmidtInformer() { }\n            virtual ~GramSchmidtInformer() { }\n            \n        public:\n            virtual double getGSCoefficientD(unsigned, unsigned) const = 0;\n            /**< \\brief Returns the `(i, j)` Gram-Schmidt coefficient as a `double`. */\n            virtual long double getGSCoefficientLD(unsigned, unsigned) const = 0;\n            /**< \\brief Returns the `(i, j)` Gram-Schmidt coefficient as a `long double`. */\n            virtual arithmetic::Real getGSCoefficientR(unsigned, unsigned, const arithmetic::RealContext &) const = 0;\n            /**< \\brief Returns the `(i, j)` Gram-Schmidt coefficient as a `arithmetic::Real`\n                        number. */\n            \n            virtual double getGSSqNormD(unsigned) const = 0;\n            /**< \\brief Returns the squared norm of the `i`-th Gram-Schmidt orthogonalized basis\n                        vector as a `double`.\n            */\n            virtual long double getGSSqNormLD(unsigned) const = 0;\n            /**< \\brief Returns the squared norm of the `i`-th Gram-Schmidt orthogonalized basis\n                        vector as a `long double`.\n            */\n            virtual arithmetic::Real getGSSqNormR(unsigned, const arithmetic::RealContext &) const = 0;\n            /**< \\brief Returns the squared norm of the `i`-th Gram-Schmidt orthogonalized basis\n                        vector as a `arithmetic::Real` number.\n            */\n            \n            virtual double computeProjectionLengthD(unsigned k, unsigned b,\n                                                    const linalg::math_rowvector<arithmetic::Integer> & vec) const = 0;\n            /**< \\brief Returns the squared norm of the given vector projected into the orthogonal\n                        complement of the first `k`-th basis vectors.\n                 \n                 The given vector is a linear combination of basis vectors `b`, `b + 1`, ..., where\n                 the linear combination is provided in the variable `vec`. The result is returned as\n                 a `double`.\n            */\n            virtual long double computeProjectionLengthLD(unsigned k, unsigned b,\n                                                          const linalg::math_rowvector<arithmetic::Integer> & vec) const = 0;\n            /**< \\brief Returns the squared norm of the given vector projected into the orthogonal\n                        complement of the first `k`-th basis vectors.\n                 \n                 The given vector is a linear combination of basis vectors `b`, `b + 1`, ..., where\n                 the linear combination is provided in the variable `vec`. The result is returned as\n                 a `long double`.\n            */\n            virtual arithmetic::Real computeProjectionLengthR(unsigned k, unsigned b,\n                                                              const linalg::math_rowvector<arithmetic::Integer> & vec,\n                                                              const arithmetic::RealContext &) const = 0;\n            /**< \\brief Returns the squared norm of the given vector projected into the orthogonal\n                        complement of the first `k`-th basis vectors.\n                 \n                 The given vector is a linear combination of basis vectors `b`, `b + 1`, ..., where\n                 the linear combination is provided in the variable `vec`. The result is returned as\n                 a `arithmetic::Real` number.\n            */\n            \n            inline arithmetic::Real getGSCoefficientR(unsigned i, unsigned j) const\n            /**< \\brief Returns the `(i, j)` Gram-Schmidt coefficient as a `arithmetic::Real`\n                        number.\n                 \n                 Uses the default `arithmetic::RealContext`.\n            */\n            {\n                return getGSCoefficientR(i, j, arithmetic::getThreadRealContext());\n            }\n            \n            inline arithmetic::Real getGSSqNormR(unsigned i) const\n            /**< \\brief Returns the squared norm of the `i`-th Gram-Schmidt orthogonalized basis\n                        vector as a `arithmetic::Real` number.\n                 \n                 Uses the default `arithmetic::RealContext`.\n            */\n            {\n                return getGSSqNormR(i, arithmetic::getThreadRealContext());\n            }\n            \n            inline arithmetic::Real computeProjectionLengthR(unsigned k, unsigned b,\n                                                             const linalg::math_rowvector<arithmetic::Integer> & vec) const\n            /**< \\brief Returns the squared norm of the given vector projected into the orthogonal\n                        complement of the first `k`-th basis vectors.\n                 \n                 The given vector is a linear combination of basis vectors `b`, `b + 1`, ..., where\n                 the linear combination is provided in the variable `vec`. The result is returned as\n                 a `arithmetic::Real` number.\n                 \n                 Uses the default `arithmetic::RealContext`.\n            */\n            {\n                return computeProjectionLengthR(k, b, vec, arithmetic::getThreadRealContext());\n            }\n        };\n        \n        /**@{\n           \\name Callback function types.\n         */\n        typedef boost::function<void(const linalg::math_matrix<arithmetic::Integer> &)> CallbackFunction;\n        /**< \\brief A generic callback function.\n             \n             The current lattice will be passed as an argument and shall not be modified. The\n             function can throw an exception of type `stop_reduction` to abort reduction.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        typedef boost::function<void(const linalg::math_matrix<arithmetic::NInt<long int> > &)> CallbackFunction_LI;\n        /**< \\brief A generic callback function for `long int` lattices.\n             \n             The current lattice will be passed as an argument and shall not be modified. The\n             function can throw an exception of type `stop_reduction` to abort reduction.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        \n        typedef boost::function<void(const linalg::math_matrix<arithmetic::Integer> &, unsigned,\n                                     const arithmetic::Integer &)> MinCallbackFunction;\n        /**< \\brief A callback function for newly found shortest vectors.\n             \n             The basis is given as an argument together with an index to the shortest vector in that\n             base (encourntered so far). The function can throw an exception of type\n             `stop_reduction` to abort reduction.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        typedef boost::function<void(const linalg::math_matrix<arithmetic::NInt<long int> > &, unsigned,\n                                     const arithmetic::NInt<long int> &)> MinCallbackFunction_LI;\n        /**< \\brief A callback function for newly found shortest vectors for `long int` lattices.\n             \n             The basis is given as an argument together with an index to the shortest vector in that\n             base (encourntered so far). The function can throw an exception of type\n             `stop_reduction` to abort reduction.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        \n        typedef boost::function<void(const linalg::math_matrix<arithmetic::Integer> & basis,\n                                     int p,\n                                     const linalg::math_rowvector<arithmetic::Integer> & vec)> EnumCallbackFunction;\n        /**< \\brief A callback function for newly found shortest vectors during enumerations, or\n                    more generally SVP solving.\n             \n             The basis is given as an argument together with an index and a vector with\n             coefficients, such that the shortest vector is a linear combination of the basis\n             vectors `p`, `p + 1`, ... with the coefficients given in `vec`.\n             \n             The function can throw an exception of type `stop_enumeration` to stop enumeration (and\n             return the currently found vector), or of type `stop_reduction` to abort reduction.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        typedef boost::function<void(const linalg::math_matrix<arithmetic::NInt<long int> > & basis,\n                                     int p,\n                                     const linalg::math_rowvector<arithmetic::NInt<long int> > & vec)> EnumCallbackFunction_LI;\n        /**< \\brief A callback function for newly found shortest vectors during enumerations, or\n                    more generally SVP solving. This callback is for `long int` lattices.\n             \n             The basis is given as an argument together with an index and a vector with\n             coefficients, such that the shortest vector is a linear combination of the basis\n             vectors `p`, `p + 1`, ... with the coefficients given in `vec`.\n             \n             The function can throw an exception of type `stop_enumeration` to stop enumeration (and\n             return the currently found vector), or of type `stop_reduction` to abort reduction.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        \n        typedef boost::function<bool(const linalg::math_matrix<arithmetic::Integer> &,\n                                     arithmetic::RealContext &,\n                                     arithmetic::Real & T)> AnnealCallbackFunction;\n        /**< \\brief A callback function for Simulated Annealing.\n             \n             It will be given the current basis and current temperature. It should modify the\n             temperature `T`, and return `true` if another annealing round should be started or\n             `false` if the algorithm should terminate.\n             \n             If the given temperature `T` was negative when this function was called, then this call\n             was done before the first annealing round and after the first LLL reduction.\n        */\n        \n        typedef boost::function<bool(const linalg::math_matrix<arithmetic::Integer> &,\n                                     int k,\n                                     arithmetic::RealContext &,\n                                     arithmetic::RandomNumberGenerator &,\n                                     arithmetic::Real & T,\n                                     GramSchmidtInformer *)> LLL_AnnealFunction;\n        /**< \\brief A annealing function for LLL.\n             \n             It receives the current basis, the current index, a `arithmetic::Real` context, a\n             random number generator, the current temparature `T`, as well as a Gram-Schmidt\n             informer object. It can return `true` to indicate that basis vector `k` should be\n             swapped with basis vector `k - 1`, or `false` to indicate that nothing should be done.\n        */\n        \n        typedef boost::function<bool (const linalg::math_matrix<arithmetic::Integer> &,\n                                      int k, int windowsize,\n                                      linalg::math_rowvector<arithmetic::Integer> & lincomb,\n                                      arithmetic::RealContext &,\n                                      arithmetic::RandomNumberGenerator &,\n                                      arithmetic::Real & T,\n                                      GramSchmidtInformer *)> BKZ_AnnealFunction;\n        /**< \\brief A annealing function for BKZ.\n             \n             It receives the current basis, the current index, the current window size, a linear\n             combination `comb` of the basis vectors `k`, `k+1`, ... of the currently shortest\n             vector found (by SVP solving), a `arithmetic::Real` context, a random number generator,\n             the current temparature `T`, as well as a Gram-Schmidt informer object.\n             \n             It can return `true` to indicate that the vector given by the linear combination\n             `lincomb` should be inserted, or `false` to not insert a vector. Note that the function\n             can freely modify the linear combination.\n        */\n        \n        typedef boost::function<void(VerboseLevel, const std::string &)> VerboseFunction;\n        /**< \\brief A verbose output callback function.\n             \n             Given a verbose level (of type `VerboseLevel`) and a message, should somehow inform the\n             caller about the content of the message.\n             \n             \\see \\ref desc-genconf-verbose\n        */\n        ///@}\n        \n        LatticeReduction();\n        /**< \\brief Creates a default `LatticeReduction` object with default settings. */\n        LatticeReduction(const linalg::math_matrix<arithmetic::Integer> & lattice);\n        /**< \\brief Creates a `LatticeReduction` object with default settings, and sets the lattice\n                    basis to the given matrix.\n             \n             \\param lattice The matrix whose rows to take as a generating system for the lattice.\n             \\sa void setLattice(const linalg::math_matrix<arithmetic::Integer> & lattice)\n        */\n        template<typename IType>\n        LatticeReduction(const linalg::math_matrix<arithmetic::NInt<IType> > & lattice);\n        /**< \\brief Creates a `LatticeReduction` object with default settings, and sets the lattice\n                    basis to the given matrix.\n             \n             \\param lattice The matrix whose rows to take as a generating system for the lattice.\n             \\tparam IType A native CPU integer type. Must be `int`, `long int` or `long long`.\n             \\sa void setLattice(const linalg::math_matrix<arithmetic::Integer> & lattice)\n        */\n#if __cplusplus >= 201103L\n        LatticeReduction(linalg::math_matrix<arithmetic::Integer> && lattice);\n        /**< \\brief Creates a `LatticeReduction` object with default settings, and moves the lattice\n                    basis from the given matrix.\n             \n             \\param lattice The matrix whose rows to take as a generating system for the lattice.\n             \\sa void setLattice(linalg::math_matrix<arithmetic::Integer> && lattice)\n        */\n        LatticeReduction(LatticeReduction &&);\n        /**< \\brief Moves a given `LatticeReduction` object into a newly constructed one. The old\n                    `LatticeReduction` object is left in a state in which only deconstruction and\n                    `operator = (LatticeReduction &&)` are valid calls.\n        */\n        LatticeReduction & operator = (LatticeReduction &&);\n        /**< \\brief Moves a given `LatticeReduction` object into this one. The old\n                    `LatticeReduction` object is left in a state in which only deconstruction and\n                    `operator = (LatticeReduction &&)` are valid calls.\n        */\n#endif\n        ~LatticeReduction();\n        /**< \\brief Destroys the `LatticeReduction` object. */\n        \n        /**@{\n           \\name Lattice setting and retrieving functions.\n         */\n        void setLattice(const linalg::math_matrix<arithmetic::Integer> & lattice);\n        /**< \\brief Sets the current lattice of the `LatticeReduction` object to the lattice given\n                    by the current matrix.\n             \n             The rows of the matrix `lattice` are taken as the generating set.\n        */\n        template<typename IType>\n        void setLattice(const linalg::math_matrix<arithmetic::NInt<IType> > & lattice);\n        /**< \\brief Sets the current lattice of the `LatticeReduction` object to the lattice given\n                    by the current matrix.\n             \n             The rows of the matrix `lattice` are taken as the generating set.\n             \n             \\tparam IType A native CPU integer type. Must be `int`, `long int` or `long long`.\n        */\n#if __cplusplus >= 201103L\n        void setLattice(linalg::math_matrix<arithmetic::Integer> && lattice);\n        /**< \\brief Sets the current lattice of the `LatticeReduction` object to the lattice given\n                    by the current matrix. Leaves the matrix in a \"moved-away\" state.\n             \n             The rows of the matrix `lattice` are taken as the generating set.\n        */\n#endif\n        const linalg::math_matrix<arithmetic::Integer> & getLattice() const;\n        /**< \\brief Returns the current lattice generating set as a matrix.\n             \n             The rows of the matrix are the vectors.\n        */\n        ///@}\n        \n        /**@{\n           \\name Lattice information functions.\n         */\n        unsigned rank() const;\n        /**< \\brief Returns the current rank, i.e. the number of generating vectors.\n             \n             After calling LLL or another reduction algorithm (not `sort` etc.), this equals the\n             rank of the lattice since the vectors are in fact a basis.\n        */\n        unsigned dimension() const;\n        /**< \\brief Returns the dimension of the ambient space in which the lattice exists.\n             \n             When there is no linear dependence among the vectors, `dimension()` is never less than\n             `rank()`.\n        */\n        ///@}\n        \n        /**@{\n           \\name Arithmetic configuration functions.\n         */\n        void setArithmetic(Arithmetic);\n        /**< \\brief Sets which arithmetic will be used for Gram-Schmidt orthogonalizations.\n             \n             \\see \\ref desc-genconf-arith\n         */\n        Arithmetic getArithmetic() const;\n        /**< \\brief Returns the currently set arithmetic for Gram-Schmidt orthogonalizations.\n             \n             \\see \\ref desc-genconf-arith\n         */\n        bool ensurePrecision(unsigned long);\n        /**< \\brief Ensures a minimal floating point precision (if possible).\n             \n             For variable precision floating point arithmetic (i.e. `A_Real`), ensures that the\n             given minimum precision is used. Returns `true` if the precision can be set, or `false`\n             if it cannot.\n             \n             \\see \\ref desc-genconf-arith\n        */\n        void setIntegers(Integers);\n        /**< \\brief Sets which integer arithmetic will be used for all lattice operations.\n             \n             \\see \\ref desc-genconf-arith\n         */\n        Integers getIntegers() const;\n        /**< \\brief Returns the currently set integer arithmetic.\n             \n             \\see \\ref desc-genconf-arith\n         */\n        ///@}\n        \n        /**@{\n           \\name Gram-Schmidt orthogonalization configuration functions.\n         */\n        void setGramSchmidt(GramSchmidt);\n        /**< \\brief Sets which Gram-Schmidt orthogonalization method will be used.\n             \n             \\see \\ref desc-genconf-gs\n         */\n        void setGramSchmidtRestart(bool);\n        /**< \\brief Sets that the current Gram-Schmidt method should use restarts.\n\n             This makes only sense for `G_Classic` and `G_Givens`, where `swap()`, `add()`\n             etc. modify the Gram-Schmidt coefficients directly and thus might propagate\n             approximation errors.\n             \n             Currently experimental.\n             \n             \\see \\ref desc-genconf-gs\n        */\n        GramSchmidt getGramSchmidt() const;\n        /**< \\brief Returns the currently used Gram-Schmidt orthogonalization method.\n             \n             \\see \\ref desc-genconf-gs\n         */\n        bool getGramSchmidtRestart() const;\n        /**< \\brief Returns whether restarts are used for the current Gram-Schmidt orthogonalization\n                    method.\n             \n             \\see \\ref desc-genconf-gs\n        */\n        ///@}\n        \n        /**@{\n           \\name Gram-Schmidt orthogonalization querying functions.\n         */\n        void forceGSRebuild(bool makeSureAllComputed = false);\n        /**< \\brief Forces the Gram-Schmidt coefficients to be rebuild.\n             \n             If the argument `makeSureAllComputed` is set to `true`, all Gram-Schmidt coefficients\n             are build now and not when they are needed.\n             \n             This can be called when no algorithm is currently running.\n        */\n        double getGSCoefficientD(unsigned, unsigned) const;\n        /**< \\brief Returns the (i, j) Gram-Schmidt coefficient as a `double`.\n             \n             This can be called when no algorithm is currently running.\n        */\n        long double getGSCoefficientLD(unsigned, unsigned) const;\n        /**< \\brief Returns the (i, j) Gram-Schmidt coefficient as a `long double`.\n             \n             This can be called when no algorithm is currently running.\n        */\n        arithmetic::Real getGSCoefficientR(unsigned, unsigned) const;\n        /**< \\brief Returns the (i, j) Gram-Schmidt coefficient as a `arithmetic::Real` number.\n             \n             This can be called when no algorithm is currently running.\n        */\n        arithmetic::Real getGSCoefficientR(unsigned, unsigned, const arithmetic::RealContext &) const;\n        /**< \\brief Returns the (i, j) Gram-Schmidt coefficient as a `arithmetic::Real` number.\n             \n             This can be called when no algorithm is currently running. Uses the default\n             `arithmetic::RealContext`.\n        */\n        double getGSSqNormD(unsigned) const;\n        /**< \\brief Returns the squared norm of the i-th Gram-Schmidt orthogonalized basis vector as\n                    a `double`.\n             \n             This can be called when no algorithm is currently running.\n        */\n        long double getGSSqNormLD(unsigned) const;\n        /**< \\brief Returns the squared norm of the i-th Gram-Schmidt orthogonalized basis vector as\n                    a `long double`.\n             \n             This can be called when no algorithm is currently running.\n        */\n        arithmetic::Real getGSSqNormR(unsigned) const;\n        /**< \\brief Returns the squared norm of the i-th Gram-Schmidt orthogonalized basis vector as\n                    a `arithmetic::Real` number.\n             \n             This can be called when no algorithm is currently running.\n        */\n        arithmetic::Real getGSSqNormR(unsigned, const arithmetic::RealContext &) const;\n        /**< \\brief Returns the squared norm of the i-th Gram-Schmidt orthogonalized basis vector as\n                    a `arithmetic::Real` number.\n             \n             This can be called when no algorithm is currently running. Uses the default\n             `arithmetic::RealContext`.\n        */\n        ///@}\n        \n        /**@{\n           \\name Modifying functions.\n         */\n        void modFlip(unsigned);\n        /**< \\brief Flips the signs of the given basis vector.\n             \n             This can be called when no algorithm is currently running.\n        */\n        void modSwap(unsigned, unsigned);\n        /**< \\brief Swaps two given basis vectors.\n             \n             This can be called when no algorithm is currently running.\n        */\n        void modAdd(unsigned i, unsigned j, const arithmetic::Integer & m);\n        /**< \\brief Adds `m` times the `i`-th basis vector to the `j`-th basis vector.\n             \n             This can be called when no algorithm is currently running.\n        */\n        ///@}\n        \n        /**@{\n           \\name Transformation recording related functions.\n         */\n        void enableTransform(Transform = T_Normal);\n        /**< \\brief Enables that from this point on, a transformation matrix is recorded.\n             \n             The argument allows to chose which transformation matrix is created; by default, a\n             normal one is created, such that if \\f$A\\f$ denotes the basis at this point, \\f$A'\\f$\n             at a later point and \\f$T\\f$ the transformation matrix at that point, then \\f$T \\cdot A\n             = A'\\f$.\n             \n             \\see \\ref desc-genconf-trans\n        */\n        void disableTransform();\n        /**< \\brief Disables recording of a transformation matrix.\n             \n             \\see \\ref desc-genconf-trans\n         */\n        bool isTransformationRecorded() const;\n        /**< \\brief Queries whether a transformation matrix is recorded.\n             \n             \\see \\ref desc-genconf-trans\n         */\n        Transform getTransformationMode() const;\n        /**< \\brief Queries whether transformation matrix (normal or inverse) is recorded.\n             \n             \\see \\ref desc-genconf-trans\n         */\n        const linalg::math_matrix<arithmetic::Integer> * getTransformation() const;\n        /**< \\brief Queries the current transformation matrix.\n             \n             If none is recorded, `NULL` is returned.\n             \n             \\see \\ref desc-genconf-trans\n        */\n        ///@}\n        \n        /**@{\n           \\name SVP mode related functions.\n         */\n        void setSVPMode(SVPMode);\n        /**< \\brief Sets the current SVP solver. */\n        SVPMode getSVPMode() const;\n        /**< \\brief Retrieves the current SVP solver. */\n        ///@}\n        \n        /**@{\n           \\name Multi-threading related functions.\n         */\n        void setMaximalCoreUsage(unsigned);\n        /**< \\brief Setups the maximal number of cores which will be used by the `plll` library.\n             \n             If 0 is specified, as many as possible (i.e. needed and available) are used. This\n             currently only affects parallel enumeration.\n             \n             The default value is 0.\n             \n             \\see \\ref desc-genconf-multithreading\n        */\n        unsigned getMaximalCoreUsage();\n        /**< \\brief Returns the current maximal number of cores used.\n             \n             \\see \\ref desc-genconf-multithreading\n         */\n        ///@}\n        \n        /**@{\n           \\name Callback related functions.\n         */\n        void setCallbackFunction(const CallbackFunction &, const CallbackFunction_LI & = CallbackFunction_LI());\n        /**< \\brief Sets a callback function.\n             \n             The callback function will be called in regular intervals during calls to reduction\n             algorithms. These intervals are garuanteed minimal waiting times between calls; there\n             is no upper bound; if for example an enumeration is running, this function will only be\n             called when the enumeration eventually finishes.\n             \n             \\warning If only a usual `CallbackFunction` callback function is set and the integer\n                      arithmetic is set to `I_LongInt` or `I_Auto` (and `long int` lattices are\n                      processed), the lattice must be converted for every call.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        void setCallbackFunction(const CallbackFunction_LI &);\n        /**< \\brief Sets a callback function.\n             \n             The callback function will be called in regular intervals during calls to reduction\n             algorithms. These intervals are garuanteed minimal waiting times between calls; there\n             is no upper bound; if for example an enumeration is running, this function will only be\n             called when the enumeration eventually finishes.\n             \n             \\warning If the integer arithmetic is set to `I_ArbitraryPrecision` or `I_Auto` (and\n                      `arithmetic::Integer` lattices are processed), the lattice must be converted\n                      for every call.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        void setCallbackInterval(double = 60.0*5.0);\n        /**< \\brief Sets the callback interval for the callback function.\n             \n             By default, the interval is every 5 minutes. The value can be set in seconds, where\n             fractional multiples are allowed.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        std::pair<CallbackFunction, CallbackFunction_LI> getCallbackFunction() const;\n        /**< \\brief Retrieves the currently set callback function.\n             \n             \\see \\ref desc-genconf-callback\n         */\n        double getCallbackInterval() const;\n        /**< \\brief Retrieves the current (minimal) callback interval.\n             \n             \\see \\ref desc-genconf-callback\n         */\n        \n        void setMinCallbackFunction(const MinCallbackFunction &, const MinCallbackFunction_LI & = MinCallbackFunction_LI());\n        /**< \\brief Sets a minimum callback function which will be called as soon as a new shortest\n                    vector is found during reduction.\n             \n             It will *not* be called during enumerations (see [setEnumCallbackFunction](@ref\n             setEnumCallbackFunction) for this case), but only afterwards if the returned vector is\n             shorter than the previous ones.\n             \n             (Note that the unprojected norms will be used to compare lengths.)\n             \n             \\warning If only a usual `MinCallbackFunction` callback function is set and the integer\n                      arithmetic is set to `I_LongInt` or `I_Auto` (and `long int` lattices are\n                      processed), the lattice must be converted for every call.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        void setMinCallbackFunction(const MinCallbackFunction_LI &);\n        /**< \\brief Sets a minimum callback function which will be called as soon as a new shortest\n                    vector is found during reduction.\n             \n             It will *not* be called during enumerations (see [setEnumCallbackFunction](@ref\n             setEnumCallbackFunction) for this case), but only afterwards if the returned vector is\n             shorter than the previous ones.\n             \n             (Note that the unprojected norms will be used to compare lengths.)\n             \n             \\warning If the integer arithmetic is set to `I_ArbitraryPrecision` or `I_Auto` (and\n                      `arithmetic::Integer` lattices are processed), the lattice must be converted\n                      for every call.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        std::pair<MinCallbackFunction, MinCallbackFunction_LI> getMinCallbackFunction() const;\n        /**< \\brief Retrieves the currently set minimum callback function.\n             \n             \\see \\ref desc-genconf-callback\n         */\n        \n        void setEnumCallbackFunction(const EnumCallbackFunction &, const EnumCallbackFunction_LI & = EnumCallbackFunction_LI());\n        /**< \\brief Sets a enumeration callback function which will be used if a new shortest vector\n                    is found during an enumeration.\n             \n             Note that the found vector might be much longer than vectors found during previous\n             enumerations or during previous calls of a `MinCallbackFunction`; it will only be\n             shorter than the vectors found during the current enumeration.\n             \n             \\warning If only a usual `EnumCallbackFunction` callback function is set and the\n                      integer arithmetic is set to `I_LongInt` or `I_Auto` (and `long int` lattices\n                      are processed), the lattice must be converted for every call.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        void setEnumCallbackFunction(const EnumCallbackFunction_LI &);\n        /**< \\brief Sets a enumeration callback function which will be used if a new shortest vector\n                    is found during an enumeration.\n             \n             Note that the found vector might be much longer than vectors found during previous\n             enumerations or during previous calls of a `MinCallbackFunction`; it will only be\n             shorter than the vectors found during the current enumeration.\n             \n             \\warning If the integer arithmetic is set to `I_ArbitraryPrecision` or `I_Auto` (and\n                      `arithmetic::Integer` lattices are processed), the lattice must be converted\n                      for every call.\n             \n             \\see \\ref desc-genconf-callback\n        */\n        std::pair<EnumCallbackFunction, EnumCallbackFunction_LI> getEnumCallbackFunction();\n        /**< \\brief Retrieves the current enumeration callback function.\n             \n             \\see \\ref desc-genconf-callback\n         */\n        ///@}\n        \n        /**@{\n           \\name Simulated Annealing related functions.\n         */\n        void setDefaultAnnealing();\n        /**< \\brief Sets the default annealing functions.\n             \n             This is equivalent to a call both to `setDefaultAnnealingLLL()` and\n             `setDefaultAnnealingBKZ()`. */\n        void setDefaultAnnealingLLL();\n        /**< \\brief Sets the defalut LLL annealing function.\n\n             \\sa setDefaultAnnealing()\n        */\n        void setDefaultAnnealingBKZ();\n        /**< \\brief Sets the defalut BKZ annealing function.\n\n             \\sa setDefaultAnnealing()\n        */\n        void setAnnealing(const AnnealCallbackFunction &, const LLL_AnnealFunction &, const BKZ_AnnealFunction &);\n        /**< \\brief Sets annealing functions for both LLL and BKZ.\n        */\n        void setAnnealingLLL(const AnnealCallbackFunction &, const LLL_AnnealFunction &);\n        /**< \\brief Sets annealing functions for LLL.\n             \n             \\sa setAnnealing()\n        */\n        void setAnnealingBKZ(const AnnealCallbackFunction &, const BKZ_AnnealFunction &);\n        /**< \\brief Sets annealing functions for BKZ.\n             \n             \\sa setAnnealing()\n        */\n        void disableAnnealing();\n        /**< \\brief Disable annealing for both LLL and BKZ.\n             \n        */\n        void disableAnnealingLLL();\n        /**< \\brief Disable annealing for LLL.\n             \n             \\sa disableAnnealing()\n        */\n        void disableAnnealingBKZ();\n        /**< \\brief Disable annealing for LLL.\n             \n             \\sa disableAnnealing()\n        */\n        bool isAnnealingLLLEnabled() const;\n        /**< \\brief Tests whether annealing for LLL is enabled. */\n        bool isAnnealingBKZEnabled() const;\n        /**< \\brief Tests whether annealing for BKZ is enabled. */\n        ///@}\n        \n        /**@{\n           \\name Deep Insertions related functions.\n         */\n        void setDeepInsertionMethod(DIMethod, DIMode = DIM_Default);\n        /**< \\brief Sets the Deep Insertions method and optionally also the mode.\n             \n             The default for the mode is `DIM_Default`.\n             \n             \\see \\ref desc-algconf-di\n        */\n        void setDeepInsertionMode(DIMode);\n        /**< \\brief Sets the Deep Insertions mode.\n             \n             \\see \\ref desc-algconf-di\n         */\n        void setDeepInsertionChoice(DIChoice, unsigned = 1);\n        /**< \\brief Sets the Deep Insertion choice and block size, which by default is 1.\n             \n             \\see \\ref desc-algconf-di\n        */\n        DIMethod getDeepInsertionMethod() const;\n        /**< \\brief Retrieves the current Deep Insertions method.\n             \n             \\see \\ref desc-algconf-di\n         */\n        DIMode getDeepInsertionMode() const;\n        /**< \\brief Retrieves the current Deep Insertions mode.\n             \n             \\see \\ref desc-algconf-di\n         */\n        DIChoice getDeepInsertionChoice() const;\n        /**< \\brief Retrieves the current Deep Insertions choice.\n             \n             \\see \\ref desc-algconf-di\n         */\n        unsigned getDeepInsertionBlocksize() const;\n        /**< \\brief Retrieves the current Deep Insertions choice block size parameter.\n             \n             \\see \\ref desc-algconf-di\n         */\n        ///@}\n        \n        /**@{\n           \\name Range related functions.\n         */\n        void setRange(unsigned begin, unsigned end = std::numeric_limits<unsigned>::max());\n        /**< \\brief Retricts all algorithms to the range [begin, end].\n             \n             If not said otherwise, they will be dealt with after projection into the orthogonal\n             complement of the first `begin` basis vectors.\n             \n             If `end` is larger than the index of the last vector, all basis vectors following index\n             `begin` will be used. The default is to handle *all* basis vectors.\n             \n             \\see \\ref desc-genconf-range\n        */\n        std::pair<unsigned, unsigned> getRange() const;\n        /**< \\brief Retrieves the current range.\n             \n             \\see \\ref desc-genconf-range\n         */\n        ///@}\n        \n        /**@{\n           \\name Lattice functions.\n         */\n        void sort(bool projected = false);\n        /**< \\brief Sorts the vectors by their norm.\n             \n             If the parameter `projected` is set to `true`, the Gram-Schmidt projected norms are\n             used instead.\n        */\n        \n        void sizereduction();\n        /**< \\brief Applies only size reduction to the vectors.\n             \n             \\see \\ref howitworks\n         */\n        void lll(double alpha = 0.99, LLLMode mode = LLL_Classic);\n        /**< \\brief Applies LLL with given reduction parameter `alpha` (\\f$\\alpha\\f$) and mode\n                    `mode`.\n             \n             By default, the reduction parameter is 0.99 and the mode is `LLL_Classic`.\n             \n             Note that often 0.99 completely suffices as a reduction parameter, and that the default\n             `alpha` used by Lenstra, Lenstra and Lovász is 0.75.\n             \n             \\see \\ref desc-algs-lll\n        */\n        void bkz(double alpha = 0.99, unsigned blocksize = 20, BKZMode mode = BKZ_SchnorrEuchner);\n        /**< \\brief Applies BKZ (or one of its variants) with given reduction parameter `alpha`\n                    (\\f$\\alpha\\f$), block size `blocksize` and mode `mode`.\n             \n             By default, the reduction parameter is 0.99, the block size is 20 and the mode is\n             `BKZ_SchnorrEuchner`.\n             \n             Note that often 0.99 completely suffices as a reduction parameter, and that the default\n             `alpha` used by Lenstra, Lenstra and Lovász is 0.75.\n             \n             \\see \\ref desc-algs-bkz\n        */\n        void hkz(bool dual = false);\n        /**< \\brief Computes a Hermite-Korkine-Zolotarev reduced basis.\n             \n             This is one of the strongest reduction method known and cannot be computed\n             efficiently. It will be computed by \\f$k\\f$ calls to the SVP solver if a lattice of\n             rank \\f$k\\f$ is given.\n             \n             In case `dual` is set to `true`, a HKZ basis will be computed of the reversed dual of\n             the current lattice.\n        */\n        void svp(bool make_basis = true, bool extreme = false, bool dual = false);\n        /**< \\brief Computes a shortest vector of the lattice and inserts it at the beginning.\n             \n             If `make_basis` is set to `true`, the resulting generating system is reduced to a basis\n             using LLL, so that the first vector is the shortest (such bases are also called *SVP\n             bases*).\n             \n             If `extreme` is set to `true`, *Extreme Pruning* as described by N. Gama, P. Q. Nguyen\n             and O. Regev in\n             \\cite gama-nguyen-regev-extremepruning will be used. Note that this is experimental at\n             the moment.\n             \n             In case `dual` is set to `true`, a SVP generating system respectively basis will be\n             computed of the reversed dual of the current lattice.\n             \n             \\see \\ref desc-algs-svp\n        */\n        ///@}\n        \n        /**@{\n           \\name Lattice reduction testing functions.\n         */\n        bool isSizeReduced() const;\n        /**< \\brief Tests whether the given lattice is size reduced. */\n        bool isLLLBasis(double alpha = 0.99, LLLMode mode = LLL_Classic) const;\n        /**< \\brief Tests whether the given lattice basis is LLL reduced with respect to the given\n                    reduction parameter `alpha` (\\f$\\alpha\\f$) and mode `mode`.\n             \n             \\sa lll(alpha, mode)\n        */\n        bool isBKZBasis(double alpha = 0.99, unsigned blocksize = 20, BKZMode mode = BKZ_SchnorrEuchner) const;\n        /**< \\brief Tests whether the given lattice basis is BKZ reduced with respect to the given\n                    reduction parameter `alpha` (\\f$\\alpha\\f$), the given block size `blocksize` and\n                    mode `mode`.\n             \n             \\sa bkz(alpha, blocksize, mode)\n        */\n        bool isHKZBasis(bool dual = false) const;\n        /**< \\brief Tests whether the given lattice basis (or its reversed dual, in case `dual` is\n                    `true`) is HKZ reduced.\n             \n             \\sa hkz(dual)\n        */\n        bool isSVPBasis(bool dual = false) const;\n        /**< \\brief Tests whether the given lattice basis (or its reversed dual, in case `dual` is\n                    `true`) has a shortest vector at the first index.\n             \n             \\sa svp(*, *, dual)\n        */\n        ///@}\n        \n        /**@{\n           \\name Statistics related functions.\n         */\n        const Statistics & getStatistics() const;\n        /**< \\brief Retrieves the current statistics object. */\n        void resetStatistics();\n        /**< \\brief Resets the current statistics object. */\n        ///@}\n        \n        /**@{\n           \\name Verbosity related functions.\n         */\n        void setVerbose(VerboseOutputLevel level, const VerboseFunction & = 0);\n        /**< \\brief Sets the verbose output level to `level`.\n             \n             If given, the current verbose output function will also be set.\n             \n             \\see \\ref desc-genconf-verbose\n        */\n        VerboseOutputLevel getVerboseOutputLevel();\n        /**< \\brief Retrieves the current verbose output level.\n             \n             \\see \\ref desc-genconf-verbose\n         */\n        const VerboseFunction & getVerboseFunction();\n        /**< \\brief Retrieves the current verbose output function.\n             \n             \\see \\ref desc-genconf-verbose\n         */\n        ///@}\n    };\n}\n\n#endif\n", "meta": {"hexsha": "5926a630fbc3cf9270620adda836c8a846f0c9dc", "size": 73558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "plll/include/plll.hpp", "max_stars_repo_name": "KudrinMatvey/myfplll", "max_stars_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plll/include/plll.hpp", "max_issues_repo_name": "KudrinMatvey/myfplll", "max_issues_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plll/include/plll.hpp", "max_forks_repo_name": "KudrinMatvey/myfplll", "max_forks_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.673857868, "max_line_length": 128, "alphanum_fraction": 0.5697408847, "num_tokens": 14998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541662624228417, "lm_q2_score": 0.025178839688993274, "lm_q1q2_score": 0.005675729095388188}}
{"text": "/* \n* Copyright (C) 2020-2021 German Aerospace Center (DLR-SC)\n*\n* Authors: Wadim Koslow, Daniel Abele, Martin J. Kuehn, Lena Ploetzke\n*\n* Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>\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 \"secir/secir_parameters_io.h\"\n\n#ifdef MEMILIO_HAS_JSONCPP\n\n#include \"secir/secir_result_io.h\"\n#include \"memilio/io/io.h\"\n#include \"memilio/utils/memory.h\"\n#include \"memilio/utils/uncertain_value.h\"\n#include \"memilio/utils/stl_util.h\"\n#include \"memilio/mobility/graph.h\"\n#include \"memilio/mobility/mobility.h\"\n#include \"memilio/epidemiology/damping.h\"\n#include \"memilio/epidemiology/populations.h\"\n#include \"memilio/epidemiology/uncertain_matrix.h\"\n#include \"memilio/utils/compiler_diagnostics.h\"\n#include \"memilio/utils/date.h\"\n\n#include <json/json.h>\n\n#include <boost/filesystem.hpp>\n\n#include <numeric>\n#include <vector>\n#include <iostream>\n#include <string>\n#include <random>\n#include <fstream>\n\nnamespace mio\n{\n\nnamespace details\n{\n    IOResult<Date> get_max_date(const Json::Value& root)\n    {\n        Date max_date = Date(0, 1, 1);\n        for (unsigned int i = 0; i < root.size(); i++) {\n            auto js_date = root[i][\"Date\"];\n            if (!js_date.isString()) {\n                log_error(\"Date element must be a string.\");\n                return failure(StatusCode::InvalidType, \"Date element must be a string.\");\n            }\n            auto date_temp = parse_date(js_date.asString());\n            if (date_temp > max_date) {\n                max_date = date_temp;\n            }\n        }\n\n        return success(max_date);\n    }\n\n    void interpolate_ages(const std::vector<double>& age_ranges, std::vector<std::vector<double>>& interpolation,\n                          std::vector<bool>& carry_over)\n    {\n        std::vector<double> param_ranges = {5., 10., 20., 25., 20., 20.};\n\n        //counter for parameter age groups\n        size_t counter = 0;\n\n        //residual of param age groups\n        double res = 0.0;\n        for (size_t i = 0; i < age_ranges.size(); i++) {\n\n            // if current param age group didn't fit into previous rki age group, transfer residual to current age group\n            if (res < 0) {\n                interpolation[i].push_back(std::min(-res / age_ranges[i], 1.0));\n            }\n\n            if (counter < param_ranges.size() - 1) {\n                res += age_ranges[i];\n                if (std::abs(res) < age_ranges[i]) {\n                    counter++;\n                }\n                // iterate over param age groups while there is still room in the current rki age group\n                while (res > 0) {\n                    res -= param_ranges[counter];\n                    interpolation[i].push_back((param_ranges[counter] + std::min(res, 0.0)) / age_ranges[i]);\n                    if (res >= 0) {\n                        counter++;\n                    }\n                }\n                if (res < 0) {\n                    carry_over.push_back(true);\n                }\n                else if (res == 0) {\n                    carry_over.push_back(false);\n                }\n            }\n            // if last param age group is reached\n            else {\n                interpolation[i].push_back((age_ranges[i] + res) / age_ranges[i]);\n                if (res < 0 || counter == 0) {\n                    carry_over.push_back(true);\n                }\n                else if (res == 0) {\n                    carry_over.push_back(false);\n                }\n                res = 0;\n            }\n        }\n        // last entries for \"unknown\" age group\n        interpolation.push_back({1.0});\n        carry_over.push_back(true);\n    }\n\n    IOResult<void> read_rki_data(\n        std::string const& path, const std::string& id_name, std::vector<int> const& vregion, Date date,\n        std::vector<std::vector<double>>& vnum_exp, std::vector<std::vector<double>>& vnum_car,\n        std::vector<std::vector<double>>& vnum_inf, std::vector<std::vector<double>>& vnum_hosp,\n        std::vector<std::vector<double>>& vnum_icu, std::vector<std::vector<double>>& vnum_death,\n        std::vector<std::vector<double>>& vnum_rec, const std::vector<std::vector<int>>& vt_car_to_rec,\n        const std::vector<std::vector<int>>& vt_car_to_inf, const std::vector<std::vector<int>>& vt_exp_to_car,\n        const std::vector<std::vector<int>>& vt_inf_to_rec, const std::vector<std::vector<int>>& vt_inf_to_hosp,\n        const std::vector<std::vector<int>>& vt_hosp_to_rec, const std::vector<std::vector<int>>& vt_hosp_to_icu,\n        const std::vector<std::vector<int>>& vt_icu_to_dead, const std::vector<std::vector<double>>& vmu_C_R,\n        const std::vector<std::vector<double>>& vmu_I_H, const std::vector<std::vector<double>>& vmu_H_U,\n        const std::vector<double>& scaling_factor_inf)\n    {\n        if (!boost::filesystem::exists(path)) {\n            log_error(\"RKI data file not found: {}.\", path);\n            return failure(StatusCode::FileNotFound, path);\n        }\n\n        Json::Reader reader;\n        Json::Value root;\n\n        std::ifstream rki(path);\n        if (!reader.parse(rki, root)) {\n            log_error(reader.getFormattedErrorMessages());\n            return failure(StatusCode::UnknownError, path + \", \" + reader.getFormattedErrorMessages());\n        }\n\n        BOOST_OUTCOME_TRY(max_date, get_max_date(root));\n        if (max_date == Date(0, 1, 1)) {\n            log_error(\"RKI data file is empty.\");\n            return failure(StatusCode::InvalidFileFormat, path + \", file is empty.\");\n        }\n        if (max_date < date) {\n            log_error(\"Specified date does not exist in RKI data\");\n            return failure(StatusCode::OutOfRange, path + \", specified date does not exist in RKI data.\");\n        }\n        auto days_surplus = get_offset_in_days(max_date, date) - 6;\n\n        if (days_surplus > 0) {\n            days_surplus = 0;\n        }\n\n        std::vector<std::string> age_names = {\"A00-A04\", \"A05-A14\", \"A15-A34\", \"A35-A59\", \"A60-A79\", \"A80+\", \"unknown\"};\n        std::vector<double> age_ranges     = {5., 10., 20., 25., 20., 20.};\n\n        for (unsigned int i = 0; i < root.size(); i++) {\n            auto it = std::find_if(vregion.begin(), vregion.end(), [&root, i, &id_name](auto r) {\n                return r == 0 || root[i][id_name].asInt() == r;\n            });\n            if (it != vregion.end()) {\n                auto region_idx = size_t(it - vregion.begin());\n\n                auto& t_exp_to_car  = vt_exp_to_car[region_idx];\n                auto& t_car_to_rec  = vt_car_to_rec[region_idx];\n                auto& t_car_to_inf  = vt_car_to_inf[region_idx];\n                auto& t_inf_to_rec  = vt_inf_to_rec[region_idx];\n                auto& t_inf_to_hosp = vt_inf_to_hosp[region_idx];\n                auto& t_hosp_to_rec = vt_hosp_to_rec[region_idx];\n                auto& t_hosp_to_icu = vt_hosp_to_icu[region_idx];\n                auto& t_icu_to_dead = vt_icu_to_dead[region_idx];\n\n                auto& num_car   = vnum_car[region_idx];\n                auto& num_inf   = vnum_inf[region_idx];\n                auto& num_rec   = vnum_rec[region_idx];\n                auto& num_exp   = vnum_exp[region_idx];\n                auto& num_hosp  = vnum_hosp[region_idx];\n                auto& num_death = vnum_death[region_idx];\n                auto& num_icu   = vnum_icu[region_idx];\n\n                auto& mu_C_R = vmu_C_R[region_idx];\n                auto& mu_I_H = vmu_I_H[region_idx];\n                auto& mu_H_U = vmu_H_U[region_idx];\n\n                auto date_df = parse_date(root[i][\"Date\"].asString());\n\n                auto it_age = std::find(age_names.begin(), age_names.end() - 1, root[i][\"Age_RKI\"].asString());\n                if (it_age != age_names.end() - 1) {\n                    auto age = size_t(it_age - age_names.begin());\n\n                    bool read_icu = false; //params.populations.get({age, SecirCompartments::U}) == 0;\n\n                    if (date_df == offset_date_by_days(date, 0)) {\n                        num_inf[age] += (1 - mu_C_R[age]) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                        num_rec[age] += root[i][\"Confirmed\"].asDouble();\n                    }\n                    if (date_df == offset_date_by_days(date, days_surplus)) {\n                        num_car[age] +=\n                            (2 * mu_C_R[age] - 1) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // -R9\n                    if (date_df == offset_date_by_days(date, -t_car_to_rec[age] + days_surplus)) {\n                        num_car[age] -= mu_C_R[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // +R2\n                    if (date_df == offset_date_by_days(date, +t_exp_to_car[age] + days_surplus)) {\n                        num_exp[age] += mu_C_R[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // +R3\n                    if (date_df == offset_date_by_days(date, +t_car_to_inf[age] + days_surplus)) {\n                        num_car[age] += (1 - mu_C_R[age]) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                        num_exp[age] -= (1 - mu_C_R[age]) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // R2 - R9\n                    if (date_df == offset_date_by_days(date, t_exp_to_car[age] - t_car_to_rec[age] + days_surplus)) {\n                        num_exp[age] -= mu_C_R[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // R2 + R3\n                    if (date_df == offset_date_by_days(date, t_exp_to_car[age] + t_car_to_inf[age] + days_surplus)) {\n                        num_exp[age] += (1 - mu_C_R[age]) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // -R4\n                    if (date_df == offset_date_by_days(date, -t_inf_to_rec[age])) {\n                        num_inf[age] -= (1 - mu_C_R[age]) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // -R6\n                    if (date_df == offset_date_by_days(date, -t_inf_to_hosp[age])) {\n                        num_inf[age] -= mu_I_H[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                        num_hosp[age] += mu_I_H[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // -R6 - R7\n                    if (date_df == offset_date_by_days(date, -t_inf_to_hosp[age] - t_hosp_to_icu[age])) {\n                        num_inf[age] +=\n                            mu_I_H[age] * mu_H_U[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                        num_hosp[age] -=\n                            mu_I_H[age] * mu_H_U[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                        if (read_icu) {\n                            num_icu[age] +=\n                                mu_H_U[age] * mu_I_H[age] * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                        }\n                    }\n                    // -R6 - R5\n                    if (date_df == offset_date_by_days(date, -t_inf_to_hosp[age] - t_hosp_to_rec[age])) {\n                        num_inf[age] +=\n                            mu_I_H[age] * (1 - mu_H_U[age]) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                        num_hosp[age] -=\n                            mu_I_H[age] * (1 - mu_H_U[age]) * scaling_factor_inf[age] * root[i][\"Confirmed\"].asDouble();\n                    }\n                    // -R10 - R6 - R7\n                    if (date_df ==\n                        offset_date_by_days(date, -t_icu_to_dead[age] - t_inf_to_hosp[age] - t_hosp_to_icu[age])) {\n                        num_death[age] += root[i][\"Deaths\"].asDouble();\n                    }\n                    if (read_icu) {\n                        // -R6 - R7 - R7\n                        if (date_df == offset_date_by_days(date, -t_inf_to_hosp[age] - 2 * t_hosp_to_icu[age])) {\n                            num_icu[age] -= mu_I_H[age] * mu_H_U[age] * mu_H_U[age] * scaling_factor_inf[age] *\n                                            root[i][\"Confirmed\"].asDouble();\n                        }\n                        // -R6 - R5 - R7\n                        if (date_df == offset_date_by_days(date, -t_inf_to_hosp[age] - t_hosp_to_icu[age])) {\n                            num_icu[age] -= mu_I_H[age] * mu_H_U[age] * (1 - mu_H_U[age]) * scaling_factor_inf[age] *\n                                            root[i][\"Confirmed\"].asDouble();\n                        }\n                    }\n                }\n            }\n        }\n\n        for (size_t region_idx = 0; region_idx < vregion.size(); ++region_idx) {\n            auto region = vregion[region_idx];\n\n            auto& num_car   = vnum_car[region_idx];\n            auto& num_inf   = vnum_inf[region_idx];\n            auto& num_rec   = vnum_rec[region_idx];\n            auto& num_exp   = vnum_exp[region_idx];\n            auto& num_hosp  = vnum_hosp[region_idx];\n            auto& num_death = vnum_death[region_idx];\n            auto& num_icu   = vnum_icu[region_idx];\n\n            size_t num_groups = age_ranges.size();\n            for (size_t i = 0; i < num_groups; i++) {\n                auto try_fix_constraints = [region, &age_names, i](double& value, double error, auto str) {\n                    if (value < error) {\n                        //this should probably return a failure\n                        //but the algorithm is not robust enough to avoid large negative values and there are tests that rely on it\n                        log_error(\"{:s} for age group {:s} is {:.4f} for region {:d}, exceeds expected negative value.\",\n                                  str, age_names[i], value, region);\n                        value = 0.0;\n                    }\n                    else if (value < 0) {\n                        log_info(\"{:s} for age group {:s} is {:.4f} for region {:d}, automatically corrected\", str,\n                                 age_names[i], value, region);\n                        value = 0.0;\n                    }\n                };\n\n                try_fix_constraints(num_inf[i], -5, \"Infected\");\n                try_fix_constraints(num_car[i], -5, \"Carrier\");\n                try_fix_constraints(num_exp[i], -5, \"Exposed\");\n                try_fix_constraints(num_hosp[i], -5, \"Hospitalized\");\n                try_fix_constraints(num_death[i], -5, \"Dead\");\n                try_fix_constraints(num_icu[i], -5, \"ICU\");\n                try_fix_constraints(num_rec[i], -20, \"Recovered\");\n            }\n        }\n\n        return success();\n    }\n\n    IOResult<void> set_rki_data(std::vector<SecirModel>& model, const std::string& path, const std::string& id_name,\n                      std::vector<int> const& region, Date date, const std::vector<double>& scaling_factor_inf)\n    {\n\n        std::vector<double> age_ranges = {5., 10., 20., 25., 20., 20.};\n        assert(scaling_factor_inf.size() == age_ranges.size());\n\n        std::vector<std::vector<int>> t_car_to_rec{model.size()}; // R9\n        std::vector<std::vector<int>> t_car_to_inf{model.size()}; // R3\n        std::vector<std::vector<int>> t_exp_to_car{model.size()}; // R2\n        std::vector<std::vector<int>> t_inf_to_rec{model.size()}; // R4\n        std::vector<std::vector<int>> t_inf_to_hosp{model.size()}; // R6\n        std::vector<std::vector<int>> t_hosp_to_rec{model.size()}; // R5\n        std::vector<std::vector<int>> t_hosp_to_icu{model.size()}; // R7\n        std::vector<std::vector<int>> t_icu_to_dead{model.size()}; // R10\n\n        std::vector<std::vector<double>> mu_C_R{model.size()};\n        std::vector<std::vector<double>> mu_I_H{model.size()};\n        std::vector<std::vector<double>> mu_H_U{model.size()};\n\n        for (size_t county = 0; county < model.size(); county++) {\n            for (size_t group = 0; group < age_ranges.size(); group++) {\n\n                t_car_to_inf[county].push_back(\n                    static_cast<int>(2 * (model[county].parameters.get<mio::IncubationTime>()[(mio::AgeGroup)group] -\n                                          model[county].parameters.get<mio::SerialInterval>()[(mio::AgeGroup)group])));\n                t_car_to_rec[county].push_back(static_cast<int>(\n                    t_car_to_inf[county][group] + 0.5 * model[county].parameters.get<mio::InfectiousTimeMild>()[(mio::AgeGroup)group]));\n                t_exp_to_car[county].push_back(\n                    static_cast<int>(2 * model[county].parameters.get<mio::SerialInterval>()[(mio::AgeGroup)group] -\n                                     model[county].parameters.get<mio::IncubationTime>()[(mio::AgeGroup)group]));\n                t_inf_to_rec[county].push_back(\n                    static_cast<int>(model[county].parameters.get<mio::InfectiousTimeMild>()[(mio::AgeGroup)group]));\n                t_inf_to_hosp[county].push_back(\n                    static_cast<int>(model[county].parameters.get<mio::HomeToHospitalizedTime>()[(mio::AgeGroup)group]));\n                t_hosp_to_rec[county].push_back(\n                    static_cast<int>(model[county].parameters.get<mio::HospitalizedToHomeTime>()[(mio::AgeGroup)group]));\n                t_hosp_to_icu[county].push_back(\n                    static_cast<int>(model[county].parameters.get<mio::HospitalizedToICUTime>()[(mio::AgeGroup)group]));\n                t_icu_to_dead[county].push_back(\n                    static_cast<int>(model[county].parameters.get<mio::ICUToDeathTime>()[(mio::AgeGroup)group]));\n\n                mu_C_R[county].push_back(model[county].parameters.get<mio::AsymptoticCasesPerInfectious>()[(mio::AgeGroup)group]);\n                mu_I_H[county].push_back(\n                    model[county].parameters.get<mio::HospitalizedCasesPerInfectious>()[(mio::AgeGroup)group]);\n                mu_H_U[county].push_back(model[county].parameters.get<mio::ICUCasesPerHospitalized>()[(mio::AgeGroup)group]);\n            }\n        }\n        std::vector<std::vector<double>> num_inf(model.size(), std::vector<double>(age_ranges.size(), 0.0));\n        std::vector<std::vector<double>> num_death(model.size(), std::vector<double>(age_ranges.size(), 0.0));\n        std::vector<std::vector<double>> num_rec(model.size(), std::vector<double>(age_ranges.size(), 0.0));\n        std::vector<std::vector<double>> num_exp(model.size(), std::vector<double>(age_ranges.size(), 0.0));\n        std::vector<std::vector<double>> num_car(model.size(), std::vector<double>(age_ranges.size(), 0.0));\n        std::vector<std::vector<double>> num_hosp(model.size(), std::vector<double>(age_ranges.size(), 0.0));\n        std::vector<std::vector<double>> num_icu(model.size(), std::vector<double>(age_ranges.size(), 0.0));\n\n        BOOST_OUTCOME_TRY(read_rki_data(path, id_name, region, date, num_exp, num_car, num_inf, num_hosp, num_icu,\n                                        num_death, num_rec, t_car_to_rec, t_car_to_inf, t_exp_to_car, t_inf_to_rec,\n                                        t_inf_to_hosp, t_hosp_to_rec, t_hosp_to_icu, t_icu_to_dead, mu_C_R, mu_I_H,\n                                        mu_H_U, scaling_factor_inf));\n\n        for (size_t county = 0; county < model.size(); county++) {\n            if (std::accumulate(num_inf[county].begin(), num_inf[county].end(), 0.0) > 0) {\n                size_t num_groups = (size_t)model[county].parameters.get_num_groups();\n                for (size_t i = 0; i < num_groups; i++) {\n                    model[county].populations[{AgeGroup(i), InfectionState::Exposed}] =\n                        num_exp[county][i];\n                    model[county].populations[{AgeGroup(i), InfectionState::Carrier}] =\n                        num_car[county][i];\n                    model[county].populations[{AgeGroup(i), InfectionState::Infected}] =\n                        num_inf[county][i];\n                    model[county].populations[{AgeGroup(i), InfectionState::Hospitalized}] =\n                        num_hosp[county][i];\n                    model[county].populations[{AgeGroup(i), InfectionState::Dead}] =\n                        num_death[county][i];\n                    model[county].populations[{AgeGroup(i), InfectionState::Recovered}] =\n                        num_rec[county][i];\n                }\n            }\n            else {\n                log_warning(\"No infections reported on date \" + std::to_string(date.year) + \"-\" +\n                            std::to_string(date.month) + \"-\" + std::to_string(date.day) + \" for region \" +\n                            std::to_string(region[county]) + \". Population data has not been set.\");\n            }\n        }\n        return success();\n    }\n\n    IOResult<void> read_divi_data(const std::string& path, const std::string& id_name, const std::vector<int>& vregion,\n                                  Date date, std::vector<double>& vnum_icu)\n    {\n        if (!boost::filesystem::exists(path)) {\n            log_error(\"DIVI data file not found: {}.\", path);\n            return failure(StatusCode::FileNotFound, path);\n        }\n\n        Json::Reader reader;\n        Json::Value root;\n\n        std::ifstream divi(path);\n        if (!reader.parse(divi, root)) {\n            log_error(reader.getFormattedErrorMessages());\n            return failure(StatusCode::UnknownError, path + \", \" + reader.getFormattedErrorMessages());\n        }\n\n        BOOST_OUTCOME_TRY(max_date, get_max_date(root));\n        if (max_date == Date(0, 1, 1)) {\n            log_error(\"DIVI data file is empty.\");\n            return failure(StatusCode::InvalidFileFormat, path + \", file is empty.\");\n        }\n        if (max_date < date) {\n            log_error(\"Specified date does not exist in DIVI data.\");\n            return failure(StatusCode::OutOfRange, path + \", specified date does not exist in DIVI data.\");\n        }\n\n        for (unsigned int i = 0; i < root.size(); i++) {\n            auto it      = std::find_if(vregion.begin(), vregion.end(), [&root, i, &id_name](auto r) {\n                return r == 0 || r == root[i][id_name].asInt();\n            });\n            auto date_df = parse_date(root[i][\"Date\"].asString());\n            if (it != vregion.end() && date_df == date) {\n                auto region_idx = size_t(it - vregion.begin());\n                auto& num_icu   = vnum_icu[region_idx];\n                num_icu         = root[i][\"ICU\"].asDouble();\n            }\n        }\n\n        return success();\n    }\n\n    IOResult<std::vector<std::vector<double>>> read_population_data(const std::string& path, const std::string& id_name,\n                                                                    const std::vector<int>& vregion)\n    {\n        if (!boost::filesystem::exists(path)) {\n            log_error(\"Population data file not found: {}.\", path);\n            return failure(StatusCode::FileNotFound, path);\n        }\n\n        Json::Reader reader;\n        Json::Value root;\n\n        std::ifstream census(path);\n        if (!reader.parse(census, root)) {\n            log_error(reader.getFormattedErrorMessages());\n            return failure(StatusCode::UnknownError, path + \", \" + reader.getFormattedErrorMessages());\n        }\n\n        std::vector<std::string> age_names = {\"<3 years\",    \"3-5 years\",   \"6-14 years\",  \"15-17 years\",\n                                              \"18-24 years\", \"25-29 years\", \"30-39 years\", \"40-49 years\",\n                                              \"50-64 years\", \"65-74 years\", \">74 years\"};\n        std::vector<double> age_ranges     = {3., 3., 9., 3., 7., 5., 10., 10., 15., 10., 25.};\n\n        std::vector<std::vector<double>> interpolation(age_names.size());\n        std::vector<bool> carry_over;\n\n        interpolate_ages(age_ranges, interpolation, carry_over);\n\n        std::vector<std::vector<double>> vnum_population(vregion.size(), std::vector<double>(age_names.size(), 0.0));\n\n        for (unsigned int i = 0; i < root.size(); i++) {\n            auto it = std::find_if(vregion.begin(), vregion.end(), [&root, i, &id_name](auto r) {\n                return r == 0 || (int)root[i][id_name].asDouble() / 1000 == r || root[i][id_name] == r;\n            });\n            if (it != vregion.end()) {\n                auto region_idx      = size_t(it - vregion.begin());\n                auto& num_population = vnum_population[region_idx];\n                for (size_t age = 0; age < age_names.size(); age++) {\n                    num_population[age] += root[i][age_names[age]].asDouble();\n                }\n            }\n        }\n\n        std::vector<std::vector<double>> interpol_population(vregion.size(),\n                                                             std::vector<double>(age_names.size(), 0.0));\n        for (size_t region_idx = 0; region_idx < vregion.size(); ++region_idx) {\n            auto& num_population = vnum_population[region_idx];\n\n            int counter = 0;\n            for (size_t i = 0; i < interpolation.size() - 1; i++) {\n                for (size_t j = 0; j < interpolation[i].size(); j++) {\n                    interpol_population[region_idx][counter] += interpolation[i][j] * num_population[i];\n                    if (j < interpolation[i].size() - 1 || !carry_over[i]) {\n                        counter++;\n                    }\n                }\n            }\n        }\n\n        return success(interpol_population);\n    }\n\n    IOResult<void> set_population_data(std::vector<SecirModel>& model, const std::string& path,\n                                       const std::string& id_name, const std::vector<int>& vregion)\n    {\n        BOOST_OUTCOME_TRY(num_population, read_population_data(path, id_name, vregion));\n\n        for (size_t region = 0; region < vregion.size(); region++) {\n            if (std::accumulate(num_population[region].begin(), num_population[region].end(), 0.0) > 0) {\n                auto num_groups = model[region].parameters.get_num_groups();\n                for (auto i = AgeGroup(0); i < num_groups; i++) {\n                    model[region].populations.set_difference_from_group_total<mio::AgeGroup>(\n                        {i, InfectionState::Susceptible}, num_population[region][size_t(i)]);\n                }\n            }\n            else {\n                log_warning(\"No population data available for region \" + std::to_string(region) +\n                            \". Population data has not been set.\");\n            }\n        }\n\n        return success();\n    }\n\n    IOResult<void> set_divi_data(std::vector<SecirModel>& model, const std::string& path, const std::string& id_name,\n                                 const std::vector<int>& vregion, Date date, double scaling_factor_icu)\n    {\n        std::vector<double> sum_mu_I_U(vregion.size(), 0);\n        std::vector<std::vector<double>> mu_I_U{model.size()};\n        for (size_t region = 0; region < vregion.size(); region++) {\n            auto num_groups = model[region].parameters.get_num_groups();\n            for (auto i = mio::AgeGroup(0); i < num_groups; i++) {\n                sum_mu_I_U[region] += model[region].parameters.get<mio::ICUCasesPerHospitalized>()[i] *\n                                      model[region].parameters.get<mio::HospitalizedCasesPerInfectious>()[i];\n                mu_I_U[region].push_back(model[region].parameters.get<mio::ICUCasesPerHospitalized>()[i] *\n                                         model[region].parameters.get<mio::HospitalizedCasesPerInfectious>()[i]);\n            }\n        }\n        std::vector<double> num_icu(model.size(), 0.0);\n        BOOST_OUTCOME_TRY(read_divi_data(path, id_name, vregion, date, num_icu));\n\n        for (size_t region = 0; region < vregion.size(); region++) {\n            auto num_groups = model[region].parameters.get_num_groups();\n            for (auto i = mio::AgeGroup(0); i < num_groups; i++) {\n                model[region].populations[{i, mio::InfectionState::ICU}] =\n                    scaling_factor_icu * num_icu[region] * mu_I_U[region][(size_t)i] / sum_mu_I_U[region];\n            }\n        }\n\n        return success();\n    }\n\n} // namespace details\n\nIOResult<std::vector<int>> get_county_ids(const std::string& path)\n{\n    Json::Reader reader;\n    Json::Value root;\n\n    std::vector<int> id;\n\n    auto filename = path_join(path, \"county_current_population.json\");\n    std::ifstream census(filename);\n    if (!reader.parse(census, root)) {\n        log_error(reader.getFormattedErrorMessages());\n        return failure(StatusCode::UnknownError, filename + \", \" + reader.getFormattedErrorMessages());\n    }\n\n    for (unsigned int i = 0; i < root.size(); i++) {\n        auto val = root[i][\"ID_County\"];\n        if (!val.isInt())\n        {\n            log_error(\"ID_County field must be an integer.\");\n            return failure(StatusCode::InvalidFileFormat, filename + \", ID_County field must be an integer.\");\n        }\n        id.push_back(val.asInt());\n    }\n\n    return success(id);\n}\n\n} // namespace mio\n\n#endif // MEMILIO_HAS_JSONCPP\n", "meta": {"hexsha": "61346ce35a5e95e5cd64141a035c93d11d68f510", "size": 29628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/models/secir/secir_parameters_io.cpp", "max_stars_repo_name": "lelange/memilio", "max_stars_repo_head_hexsha": "e90aa96a3494899c54cd6326a31687d37f5505c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T11:01:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T12:45:39.000Z", "max_issues_repo_path": "cpp/models/secir/secir_parameters_io.cpp", "max_issues_repo_name": "lelange/memilio", "max_issues_repo_head_hexsha": "e90aa96a3494899c54cd6326a31687d37f5505c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2021-08-16T15:38:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:37:24.000Z", "max_forks_repo_path": "cpp/models/secir/secir_parameters_io.cpp", "max_forks_repo_name": "lelange/memilio", "max_forks_repo_head_hexsha": "e90aa96a3494899c54cd6326a31687d37f5505c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T08:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T12:45:42.000Z", "avg_line_length": 49.5451505017, "max_line_length": 136, "alphanum_fraction": 0.5401647091, "num_tokens": 7167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.01971913033968523, "lm_q1q2_score": 0.005674531066558732}}
{"text": "//=============================================================================================================\n/**\n* @file     hpifit.cpp\n* @author   Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     March, 2017\n*\n* @section  LICENSE\n*\n* Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    HPIFit class defintion.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"hpifit.h\"\n#include \"hpifitdata.h\"\n\n#include <fiff/fiff_dig_point_set.h>\n\n#include <utils/ioutils.h>\n#include <utils/mnemath.h>\n\n#include <iostream>\n#include <fiff/fiff_cov.h>\n#include <fstream>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Dense>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QFuture>\n#include <QtConcurrent/QtConcurrent>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace INVERSELIB;\nusing namespace FIFFLIB;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nHPIFit::HPIFit()\n{\n\n}\n\n\n//*************************************************************************************************************\n\nvoid HPIFit::fitHPI(const MatrixXd& t_mat,\n                        const Eigen::MatrixXd& t_matProjectors,\n                        FiffCoordTrans& transDevHead,\n                        const QVector<int>& vFreqs,\n                        QVector<double>& vGof,\n                        FiffDigPointSet& fittedPointSet,\n                        FiffInfo::SPtr pFiffInfo,\n                        bool bDoDebug,\n                        const QString& sHPIResourceDir)\n{\n    //Check if data was passed\n    if(t_mat.rows() == 0 || t_mat.cols() == 0 ) {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - No data passed. Returning.\";\n    }\n\n    //Check if projector was passed\n    if(t_matProjectors.rows() == 0 || t_matProjectors.cols() == 0 ) {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - No projector passed. Returning.\";\n    }\n\n    vGof.clear();\n\n    struct SensorInfo sensors;\n    struct CoilParam coil;\n    int numCh = pFiffInfo->nchan;\n    int samF = pFiffInfo->sfreq;\n    int samLoc = t_mat.cols(); // minimum samples required to localize numLoc times in a second\n\n    //Get HPI coils from digitizers and set number of coils\n    int numCoils = 0;\n    QList<FiffDigPoint> lHPIPoints;\n\n    for(int i = 0; i < pFiffInfo->dig.size(); ++i) {\n        if(pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) {\n            numCoils++;\n            lHPIPoints.append(pFiffInfo->dig[i]);\n        }\n    }\n\n    //Set coil frequencies\n    Eigen::VectorXd coilfreq(numCoils);\n\n    if(vFreqs.size() >= numCoils) {\n        for(int i = 0; i < numCoils; ++i) {\n            coilfreq[i] = vFreqs.at(i);\n            //std::cout<<std::endl << coilfreq[i] << \"Hz\";\n        }\n    } else {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - Not enough coil frequencies specified. Returning.\";\n        return;\n    }\n\n    // Initialize HPI coils location and moment\n    coil.pos = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.mom = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.dpfiterror = Eigen::VectorXd::Zero(numCoils);\n    coil.dpfitnumitr = Eigen::VectorXd::Zero(numCoils);\n\n    // Generate simulated data\n    Eigen::MatrixXd simsig(samLoc,numCoils*2);\n    Eigen::VectorXd time(samLoc);\n\n    for (int i = 0; i < samLoc; ++i) {\n        time[i] = i*1.0/samF;\n    }\n\n    for(int i = 0; i < numCoils; ++i) {\n        for(int j = 0; j < samLoc; ++j) {\n            simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]);\n            simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]);\n        }\n    }\n\n    // Create digitized HPI coil position matrix\n    Eigen::MatrixXd headHPI(numCoils,3);\n\n    // check the pFiffInfo->dig information. If dig is empty, set the headHPI is 0;\n    if (lHPIPoints.size() > 0) {\n        for (int i = 0; i < lHPIPoints.size(); ++i) {\n            headHPI(i,0) = lHPIPoints.at(i).r[0];\n            headHPI(i,1) = lHPIPoints.at(i).r[1];\n            headHPI(i,2) = lHPIPoints.at(i).r[2];\n        }\n    } else {\n        for (int i = 0; i < numCoils; ++i) {\n            headHPI(i,0) = 0;\n            headHPI(i,1) = 0;\n            headHPI(i,2) = 0;\n        }\n    }\n\n    // Get the indices of inner layer channels and exclude bad channels.\n    //TODO: Only supports babymeg and vectorview gradiometeres for hpi fitting.\n    QVector<int> innerind(0);\n\n    for (int i = 0; i < numCh; ++i) {\n        if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG ||\n                pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 ||\n                pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 ||\n                pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) {\n            // Check if the sensor is bad, if not append to innerind\n            if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) {\n                innerind.append(i);\n            }\n        }\n    }\n\n    //Create new projector based on the excluded channels, first exclude the rows then the columns\n    MatrixXd matProjectorsRows(innerind.size(),t_matProjectors.cols());\n    MatrixXd matProjectorsInnerind(innerind.size(),innerind.size());\n\n    for (int i = 0; i < matProjectorsRows.rows(); ++i) {\n        matProjectorsRows.row(i) = t_matProjectors.row(innerind.at(i));\n    }\n\n    for (int i = 0; i < matProjectorsInnerind.cols(); ++i) {\n        matProjectorsInnerind.col(i) = matProjectorsRows.col(innerind.at(i));\n    }\n\n    //UTILSLIB::IOUtils::write_eigen_matrix(matProjectorsInnerind, \"matProjectorsInnerind.txt\");\n    //UTILSLIB::IOUtils::write_eigen_matrix(t_matProjectors, \"t_matProjectors.txt\");\n\n    // Initialize inner layer sensors\n    sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size());\n\n    for(int i = 0; i < innerind.size(); i++) {\n        sensors.coilpos(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.r0[0];\n        sensors.coilpos(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.r0[1];\n        sensors.coilpos(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.r0[2];\n        sensors.coilori(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.ez[0];\n        sensors.coilori(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.ez[1];\n        sensors.coilori(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.ez[2];\n    }\n\n    Eigen::MatrixXd topo(innerind.size(), numCoils*2);\n    Eigen::MatrixXd amp(innerind.size(), numCoils);\n    Eigen::MatrixXd ampC(innerind.size(), numCoils);\n\n    // Get the data from inner layer channels\n    Eigen::MatrixXd innerdata(innerind.size(), t_mat.cols());\n\n    for(int j = 0; j < innerind.size(); ++j) {\n        innerdata.row(j) << t_mat.row(innerind[j]);\n    }\n\n    // Calculate topo\n    topo = innerdata * UTILSLIB::MNEMath::pinv(simsig).transpose(); // topo: # of good inner channel x 8\n\n    // Select sine or cosine component depending on the relative size\n    amp  = topo.leftCols(numCoils); // amp: # of good inner channel x 4\n    ampC = topo.rightCols(numCoils);\n\n    for(int j = 0; j < numCoils; ++j) {\n       float nS = 0.0;\n       float nC = 0.0;\n       for(int i = 0; i < innerind.size(); ++i) {\n           nS += amp(i,j)*amp(i,j);\n           nC += ampC(i,j)*ampC(i,j);\n       }\n\n       if(nC > nS) {\n         for(int i = 0; i < innerind.size(); ++i) {\n           amp(i,j) = ampC(i,j);\n         }\n       }\n    }\n\n    //Find good seed point/starting point for the coil position in 3D space\n    //Find biggest amplitude per pickup coil (sensor) and store corresponding sensor channel index\n    VectorXi chIdcs(numCoils);\n\n    for (int j = 0; j < numCoils; j++) {\n        double maxVal = 0;\n        int chIdx = 0;\n\n        for (int i = 0; i < amp.rows(); ++i) {\n            if(std::fabs(amp(i,j)) > maxVal) {\n                maxVal = std::fabs(amp(i,j));\n\n                if(chIdx < innerind.size()) {\n                    chIdx = innerind.at(i);\n                }\n            }\n        }\n\n        chIdcs(j) = chIdx;\n    }\n\n    //Generate seed point by projection the found channel position 3cm inwards\n    Eigen::MatrixXd coilPos = Eigen::MatrixXd::Zero(numCoils,3);\n\n    for (int j = 0; j < chIdcs.rows(); ++j) {\n        int chIdx = chIdcs(j);\n\n        if(chIdx < pFiffInfo->chs.size()) {\n            double x = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[0];\n            double y = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[1];\n            double z = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[2];\n\n            coilPos(j,0) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[0] * 0.03 + x;\n            coilPos(j,1) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[1] * 0.03 + y;\n            coilPos(j,2) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[2] * 0.03 + z;\n        }\n\n        //std::cout << \"HPIFit::fitHPI - Coil \" << j << \" max value index \" << chIdx << std::endl;\n    }\n\n    coil.pos = coilPos;\n\n    coil = dipfit(coil, sensors, amp, numCoils, matProjectorsInnerind);\n\n    Eigen::Matrix4d trans = computeTransformation(headHPI, coil.pos);\n    //Eigen::Matrix4d trans = computeTransformation(coil.pos, headHPI);\n\n    // Store the final result to fiff info\n    // Set final device/head matrix and its inverse to the fiff info\n    transDevHead.from = 1;\n    transDevHead.to = 4;\n\n    for(int r = 0; r < 4; ++r) {\n        for(int c = 0; c < 4 ; ++c) {\n            transDevHead.trans(r,c) = trans(r,c);\n        }\n    }\n\n    // Also store the inverse\n    transDevHead.invtrans = transDevHead.trans.inverse();\n\n    //Calculate GOF\n    MatrixXd temp = coil.pos;\n    temp.conservativeResize(coil.pos.rows(),coil.pos.cols()+1);\n\n    temp.block(0,3,numCoils,1).setOnes();\n    temp.transposeInPlace();\n\n    MatrixXd testPos = trans * temp;\n    MatrixXd diffPos = testPos.block(0,0,3,numCoils) - headHPI.transpose();\n\n    for(int i = 0; i < diffPos.cols(); ++i) {\n        vGof.append(diffPos.col(i).norm());\n    }\n\n    //Generate final fitted points and store in digitizer set\n    for(int i = 0; i < coil.pos.rows(); ++i) {\n        FiffDigPoint digPoint;\n        digPoint.kind = FIFFV_POINT_EEG;\n        digPoint.ident = i;\n        digPoint.r[0] = coil.pos(i,0);\n        digPoint.r[1] = coil.pos(i,1);\n        digPoint.r[2] = coil.pos(i,2);\n\n        fittedPointSet << digPoint;\n    }\n\n    if(bDoDebug) {\n        // DEBUG HPI fitting and write debug results\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - dpfiterror\" << coil.dpfiterror << std::endl << coil.pos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - Initial seed point for HPI coils\" << std::endl << coil.pos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - temp\" << std::endl << temp << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - testPos\" << std::endl << testPos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - Diff fitted - original\" << std::endl << diffPos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - dev/head trans\" << std::endl << trans << std::endl;\n\n        QString sTimeStamp = QDateTime::currentDateTime().toString(\"yyMMdd_hhmmss\");\n\n        if(!QDir(sHPIResourceDir).exists()) {\n            QDir().mkdir(sHPIResourceDir);\n        }\n\n        UTILSLIB::IOUtils::write_eigen_matrix(coilPos, QString(\"%1/%2_coilPosSeed_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(coil.pos, QString(\"%1/%2_coilPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(headHPI, QString(\"%1/%2_headHPI_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXd testPosCut = testPos.transpose();//block(0,0,3,4);\n        UTILSLIB::IOUtils::write_eigen_matrix(testPosCut, QString(\"%1/%2_testPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXi idx_mat(chIdcs.rows(),1);\n        idx_mat.col(0) = chIdcs;\n        UTILSLIB::IOUtils::write_eigen_matrix(idx_mat, QString(\"%1/%2_idx_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXd coilFreq_mat(coilfreq.rows(),1);\n        coilFreq_mat.col(0) = coilfreq;\n        UTILSLIB::IOUtils::write_eigen_matrix(coilFreq_mat, QString(\"%1/%2_coilFreq_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(diffPos, QString(\"%1/%2_diffPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(amp, QString(\"%1/%2_amp_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n    }\n}\n\n\n//*************************************************************************************************************\n\nCoilParam HPIFit::dipfit(struct CoilParam coil, struct SensorInfo sensors, const Eigen::MatrixXd& data, int numCoils, const Eigen::MatrixXd& t_matProjectors)\n{\n    //Do this in conncurrent mode\n    //Generate QList structure which can be handled by the QConcurrent framework\n    QList<HPIFitData> lCoilData;\n\n    for(qint32 i = 0; i < numCoils; ++i) {\n        HPIFitData coilData;\n        coilData.coilPos = coil.pos.row(i);\n        coilData.sensorData = data.col(i);\n        coilData.sensorPos = sensors;\n        coilData.matProjector = t_matProjectors;\n\n        lCoilData.append(coilData);\n    }\n    //Do the concurrent filtering\n    if(!lCoilData.isEmpty()) {\n//        //Do sequential\n//        for(int l = 0; l < lCoilData.size(); ++l) {\n//            doDipfitConcurrent(lCoilData[l]);\n//        }\n\n        //Do concurrent\n        QFuture<void> future = QtConcurrent::map(lCoilData,\n                                             &HPIFitData::doDipfitConcurrent);\n        future.waitForFinished();\n\n        //Transform results to final coil information\n        for(qint32 i = 0; i < lCoilData.size(); ++i) {\n            coil.pos.row(i) = lCoilData.at(i).coilPos;\n            coil.mom = lCoilData.at(i).errorInfo.moment.transpose();\n            coil.dpfiterror(i) = lCoilData.at(i).errorInfo.error;\n            coil.dpfitnumitr(i) = lCoilData.at(i).errorInfo.numIterations;\n\n            //std::cout<<std::endl<< \"HPIFit::dipfit - Itr steps for coil \" << i << \" =\" <<coil.dpfitnumitr(i);\n        }\n    }\n\n    return coil;\n}\n\n\n//*************************************************************************************************************\n\nEigen::Matrix4d HPIFit::computeTransformation(Eigen::MatrixXd NH, Eigen::MatrixXd BT)\n{\n    Eigen::MatrixXd xdiff, ydiff, zdiff, C, Q;\n    Eigen::Matrix4d transFinal = Eigen::Matrix4d::Identity(4,4);\n    Eigen::Matrix4d Rot = Eigen::Matrix4d::Zero(4,4);\n    Eigen::Matrix4d Trans = Eigen::Matrix4d::Identity(4,4);\n    double meanx,meany,meanz,normf;\n\n    for(int i = 0; i < 15; ++i) {\n        // Calculate mean translation for all points -> centroid of both data sets\n        xdiff = NH.col(0) - BT.col(0);\n        ydiff = NH.col(1) - BT.col(1);\n        zdiff = NH.col(2) - BT.col(2);\n\n        meanx = xdiff.mean();\n        meany = ydiff.mean();\n        meanz = zdiff.mean();\n\n        // Apply translation -> bring both data sets to the same center location\n        for (int j = 0; j < BT.rows(); ++j) {\n            BT(j,0) = BT(j,0) + meanx;\n            BT(j,1) = BT(j,1) + meany;\n            BT(j,2) = BT(j,2) + meanz;\n        }\n\n        // Estimate rotation component\n        C = BT.transpose() * NH;\n\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd(C ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n        Q = svd.matrixU() * svd.matrixV().transpose();\n\n        //Handle special reflection case\n        if(Q.determinant() < 0) {\n            Q(0,2) = Q(0,2) * -1;\n            Q(1,2) = Q(1,2) * -1;\n            Q(2,2) = Q(2,2) * -1;\n        }\n\n        // Apply rotation on translated points\n        BT = BT * Q;\n\n        // Calculate GOF\n        normf = (NH.transpose()-BT.transpose()).norm();\n\n        // Store rotation part to transformation matrix\n        Rot(3,3) = 1;\n        for(int j = 0; j < 3; ++j) {\n            for(int k = 0; k < 3; ++k) {\n                Rot(j,k) = Q(k,j);\n            }\n        }\n\n        // Store translation part to transformation matrix\n        Trans(0,3) = meanx;\n        Trans(1,3) = meany;\n        Trans(2,3) = meanz;\n\n        // Safe rotation and translation to final matrix for next iteration step\n        // This step is safe to do since we change one of the input point sets (BT)\n        // ToDo: Replace this for loop with a least square solution process\n        transFinal = Rot * Trans * transFinal;\n    }\n\n    return transFinal;\n}\n", "meta": {"hexsha": "3a812d07a19ae6d16235fd2ce382c9ca825ac2fc", "size": 19835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/inverse/hpiFit/hpifit.cpp", "max_stars_repo_name": "ChunmingGu/mne-cpp-master", "max_stars_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T07:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-14T07:38:25.000Z", "max_issues_repo_path": "libraries/inverse/hpiFit/hpifit.cpp", "max_issues_repo_name": "ChunmingGu/mne-cpp-master", "max_issues_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-23T12:40:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-23T12:40:56.000Z", "max_forks_repo_path": "libraries/inverse/hpiFit/hpifit.cpp", "max_forks_repo_name": "ChunmingGu/mne-cpp-master", "max_forks_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1222879684, "max_line_length": 157, "alphanum_fraction": 0.5300226872, "num_tokens": 5096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.015906391099524245, "lm_q1q2_score": 0.005659094599619396}}
{"text": "/*************** <auto-copyright.rb BEGIN do not edit this line> **************\n *\n * Copyright 2012-2013 by Ames Laboratory\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License version 2.1 as published by the Free Software Foundation.\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 * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** <auto-copyright.rb END do not edit this line> ***************/\n\n\n// --- LEAF Includes --- //\n#include <leaf/wrapper/daycent/soil/Soils.h>\n#include <leaf/wrapper/daycent/file/F_header.h>\n\n// --- Boost Includes --- //\n#include <boost/assign.hpp>\n\n// --- STL Includes --- //\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace leaf::open;\nusing namespace leaf::util;\n\nnamespace leaf\n{\nnamespace wrapper\n{\nnamespace daycent\n{\nnamespace soil\n{\n\n////////////////////////////////////////////////////////////////////////////////\nstd::set< unsigned int > const Soils::ADEP = boost::assign::list_of\n    ( 10 )                          //ADEP(1)\n    ( 30 )                          //ADEP(2)\n    ( 45 )                          //ADEP(3)\n    ( 60 )                          //ADEP(4)\n    ( 90 )                          //ADEP(5)\n    ( 120 )                         //ADEP(6)\n    ( 150 )                         //ADEP(7)\n    ( 180 )                         //ADEP(8)\n    ( 210 )                         //ADEP(9)\n    ( 240 );                        //ADEP(10)\n////////////////////////////////////////////////////////////////////////////////\nstd::set< unsigned int > const Soils::LAYER = boost::assign::list_of\n    ( 2 ) ( 5 ) ( 10 )              //ADEP(1)\n    ( 20 ) ( 30 )                   //ADEP(2)\n    ( 45 )                          //ADEP(3)\n    ( 60 )                          //ADEP(4)\n    ( 75 ) ( 90 )                   //ADEP(5)\n    ( 105 ) ( 120 )                 //ADEP(6)\n    ( 150 )                         //ADEP(7)\n    ( 180 )                         //ADEP(8)\n    ( 210 )                         //ADEP(9)\n    ( 240 );                        //ADEP(10)\n////////////////////////////////////////////////////////////////////////////////\nstd::vector< double > const Soils::EVAP_COEFF = boost::assign::list_of\n    ( 0.8 ) ( 0.2 ) ( 0.0 )         //ADEP(1)\n    ( 0.0 ) ( 0.0 )                 //ADEP(2)\n    ( 0.0 )                         //ADEP(3)\n    ( 0.0 )                         //ADEP(4)\n    ( 0.0 ) ( 0.0 )                 //ADEP(5)\n    ( 0.0 ) ( 0.0 )                 //ADEP(6)\n    ( 0.0 )                         //ADEP(7)\n    ( 0.0 )                         //ADEP(8)\n    ( 0.0 )                         //ADEP(9)\n    ( 0.0 );                        //ADEP(10)\n////////////////////////////////////////////////////////////////////////////////\nstd::vector< double > const Soils::TRANS_COEFF = boost::assign::list_of\n    ( 0.01 ) ( 0.04 ) ( 0.25 )      //ADEP(1)\n    ( 0.30 ) ( 0.10 )               //ADEP(2)\n    ( 0.05 )                        //ADEP(3)\n    ( 0.04 )                        //ADEP(4)\n    ( 0.03 ) ( 0.02 )               //ADEP(5)\n    ( 0.01 ) ( 0.0 )                //ADEP(6)\n    ( 0.0 )                         //ADEP(7)\n    ( 0.0 )                         //ADEP(8)\n    ( 0.0 )                         //ADEP(9)\n    ( 0.0 );                        //ADEP(10)\n////////////////////////////////////////////////////////////////////////////////\nstd::vector< double > const Soils::MIN_VSWC = boost::assign::list_of\n    ( 0.8 ) ( 0.6 ) ( 0.4 )         //ADEP(1)\n    ( 0.1 ) ( 0.0 )                 //ADEP(2)\n    ( 0.0 )                         //ADEP(3)\n    ( 0.0 )                         //ADEP(4)\n    ( 0.0 ) ( 0.0 )                 //ADEP(5)\n    ( 0.0 ) ( 0.0 )                 //ADEP(6)\n    ( 0.0 )                         //ADEP(7)\n    ( 0.0 )                         //ADEP(8)\n    ( 0.0 )                         //ADEP(9)\n    ( 0.0 );                        //ADEP(10)\n////////////////////////////////////////////////////////////////////////////////\nSoils::Soils()\n{\n    ;\n}\n////////////////////////////////////////////////////////////////////////////////\nSoils::~Soils()\n{\n    ;\n}\n////////////////////////////////////////////////////////////////////////////////\nbool Soils::LoadSQL(\n    soi::Component const& component,\n    std::string const& dir,\n    std::string const& abbr )\n{\n    std::string cokey = Convert< std::string >( component.GetCokey() );\n\n    //Get the component horizons\n    soi::CHorizons const& horizons = component.GetHorizons();\n    soi::CHorizonsByHzdept::const_iterator chitr =\n        horizons.get< HZDEPT >().begin();\n\n    //This requires at least the first horizon to be valid\n    if( chitr == horizons.get< HZDEPT >().end() ) return false;\n    Layer layer( **chitr );\n    if( !( layer.IsValid() ) ) return false;\n\n    Layers layers;\n    double totEvapCoeff( 0.0 ), totTransCoeff( 0.0 );\n    std::set< unsigned int >::const_iterator itr = LAYER.begin();\n    for( unsigned int lyr = 0; itr != LAYER.end(); ++itr, ++lyr )\n    {\n        LayerPtr nxtlay( NULL );\n        unsigned int const& value = *itr;\n        double const& hzdept = layer.GetMinDepth();\n        double hzdepb = layer.GetMaxDepth();\n        bool success( true );\n        if( hzdepb < value )\n        {\n            Layer agglay = layer;\n            agglay *= ( hzdepb - hzdept ) / ( value - hzdept );\n            do\n            {\n                success = ( ++chitr != horizons.get< HZDEPT >().end() );\n                if( !success ) break;\n                if( Convert< double >((**chitr).GetSandtotal()) == 0 &&\n                    Convert< double >((**chitr).GetSilttotal()) == 0 &&\n                    Convert< double >((**chitr).GetClaytotal()) == 0 )\n                {\n                    success = false;\n                }\n                else\n                {\n                    nxtlay.reset( new Layer( **chitr ) );\n                    success = layer.IsValid();\n                }\n\n            if( !success ) break;\n                double const& maxdept = nxtlay->GetMaxDepth();\n                agglay += *nxtlay * ( ( std::min< double >(\n                    maxdept, value ) - hzdepb ) / ( value - hzdept ) );\n                hzdepb = maxdept;\n            }\n            while( hzdepb < value );\n            if( success ) layer = agglay;\n        }\n\n        layer.SetMaxDepth( value );\n        layer.SetEvapCoeff( EVAP_COEFF.at( lyr ) );\n        layer.SetTransCoeff( TRANS_COEFF.at( lyr ) );\n        layer.SetMinVolH2O( MIN_VSWC.at( lyr ) * layer.GetWltPnt() );\n        totEvapCoeff += layer.GetEvapCoeff();\n        totTransCoeff += layer.GetTransCoeff();\n        layers.push_back( layer );\n\n        if( !success ) break;\n        if( hzdepb > value )\n        {\n            if( nxtlay != NULL ) layer = *nxtlay;\n            layer.SetMinDepth( value );\n            layer.SetMaxDepth( hzdepb );\n        }\n        else\n        {\n            if( ++chitr == horizons.get< HZDEPT >().end() ) break;\n            layer = Layer( **chitr );\n            if( !( layer.IsValid() ) ) break;\n        }\n    }\n\n    //file: DailyDayCent/Swconst.h - #define FNSOIL \"soils.in\"\n    std::ofstream myfile;\n    std::string fileDir( dir );\n    myfile.open( ( fileDir.append( \"/soils.in\" ) ).c_str() );\n    //Update site file\n    unsigned int maxdepth = layer.GetMaxDepth();\n    std::cout << \"Max Depth: \" << maxdepth << std::endl;\n    std::set< unsigned int >::const_iterator adep = ADEP.begin();\n    for( ; adep != ADEP.end(); ++adep )\n    {\n        std::cout << *adep << std::endl;\n        if( maxdepth <= *adep )\n        {\n            maxdepth = *adep;\n            std::cout << maxdepth << std::endl;\n            break;\n        }\n    }\n    std::cout << maxdepth << std::endl;\n\n    SetNLayer( \n        std::distance( ADEP.begin(), ADEP.find( maxdepth ) ) + 1);\n    SetSilt( Convert< double >( (**horizons.get< HZDEPT >().begin()).GetSilttotal() ) );\n    SetSand( Convert< double >( (**horizons.get< HZDEPT >().begin()).GetSandtotal() ) );\n    SetClay( Convert< double >( (**horizons.get< HZDEPT >().begin()).GetClaytotal() ) );\n    SetBulkDensity( Convert< double >( (**horizons.get< HZDEPT >().begin()).GetDbthirdbar() ) );\n    std::cout << Convert< double >( (**horizons.get< HZDEPT >().begin()).GetDbthirdbar() ) << std::endl;\n\n    std::cout << \"NALYER \" << std::distance( ADEP.begin(), ADEP.find( maxdepth ) ) + 1 << std::endl;\n    //opt.SetValue( \"NLAYER\", adep );\n    //Use first layer to set these values (probably not needed at all)\n    Layers::iterator litr = layers.begin();\n\n    //Normalize evapCoeff and transCoeff to 1 and write layer to file\n    for( ; litr != layers.end(); ++litr )\n    {\n        Layer& l = *litr;\n        assert( totEvapCoeff != 0.0 && totTransCoeff != 0.0 );\n        l.SetEvapCoeff( l.GetEvapCoeff() / totEvapCoeff );\n        l.SetTransCoeff( l.GetTransCoeff() / totTransCoeff );\n        myfile << l;\n    }\n    myfile.close();\n\n    return true;\n}\n////////////////////////////////////////////////////////////////////////////////\nSoils::Layer::Layer(\n    open::soi::CHorizon const& horizon )\n    :\n    m_isValid( false ),\n    m_minDepth( NaN ),\n    m_maxDepth( NaN ),\n    m_bulkDens( NaN ),\n    m_fldCpcty( NaN ),\n    m_wltPnt( NaN ),\n    m_evapCoeff( NaN ),\n    m_transCoeff( NaN ),\n    m_sandFrac( NaN ),\n    m_clayFrac( NaN ),\n    m_siltFrac( NaN ),\n    m_om( NaN ),\n    m_minVolH2O( NaN ),\n    m_satHydCond( NaN ),\n    m_ph( NaN )\n{\n    m_sandFrac = Convert< double >( horizon.GetSandtotal(), NaN ) / 100.0;\n    m_clayFrac = Convert< double >( horizon.GetClaytotal(), NaN ) / 100.0;\n    m_siltFrac = Convert< double >( horizon.GetSilttotal(), NaN ) / 100.0;\n    double acoef = (exp(-4.396 - 0.0715 * m_clayFrac*100 - 4.88e-4 *\n              pow(m_sandFrac*100, 2) - 4.285e-5 * pow(m_sandFrac*100, 2) * m_clayFrac*100));\n    double bcoef = (-3.14 - 0.00222 * pow(m_clayFrac*100, 2) - 3.484e-5 *\n              pow(m_sandFrac*100, 2) * m_clayFrac*100);\n    double sat = (0.332 - 7.251e-4 * m_sandFrac*100 + 0.1276 * log10(m_clayFrac*100));\n    std::cout << acoef << \" \" << bcoef << \" \" << sat << std::endl;\n\n    double wp_raw = (pow((15.0 / acoef), (1.0 / bcoef)));\n    double fc_raw = (pow((0.333 / acoef), (1.0 / bcoef)));\n    double ksat_raw = (exp((12.012 - 0.0755 * m_sandFrac*100) + (-3.895 + 0.03671 *\n             m_sandFrac*100 - 0.1103 * m_clayFrac*100 + 8.7546e-4 * pow(m_clayFrac*100, 2)) /\n             sat));\n    double bd_raw = (1 - sat) * 2.65f;\n    std::cout << wp_raw << \" \" << fc_raw << \" \" << ksat_raw << std::endl;\n\n    /* Corrections from Steve Del Grosso */\n    double wiltpt = wp_raw + (-0.15f * wp_raw);\n    double fieldc = fc_raw + (0.07f * fc_raw);\n    double ksat = ksat_raw / 3600;\n    double bulkd = bd_raw + (-0.08f * bd_raw);\n\n    m_minDepth = Convert< double >( horizon.GetHzdept(), NaN );\n    m_maxDepth = Convert< double >( horizon.GetHzdepb(), NaN );\n    m_bulkDens = bulkd;//bd_raw;//Convert< double >( horizon.GetDbthirdbar(), NaN );\n    m_fldCpcty = fieldc;//fc_raw;//Convert< double >( horizon.GetWthirdbar(), NaN ) / 100.0;\n    m_wltPnt = wiltpt;//wp_raw;//Convert< double >( horizon.GetWfifteenbar(), NaN ) / 100.0;\n    \n    m_om = Convert< double >( horizon.GetOm(), NaN ) / 100.0;\n    m_minVolH2O = wiltpt;//wp_rawK;\n    // micrometer/sec to cm/sec\n    m_satHydCond = ksat;//ksat_raw;//Convert< double >( horizon.GetKsat(), NaN ) / 10000.0;\n    m_ph = Convert< double >( horizon.GetPh01mcacl2(),\n        Convert< double >( horizon.GetPh1to1h2o(), NaN ) );\n\n    //Normalize to make sure that the SAND, SILT, and CLAY values sum to 1.0\n    double sscsum = m_sandFrac + m_siltFrac + m_clayFrac;\n    std::cout << m_sandFrac << \" \" << m_siltFrac << \" \" << m_clayFrac << \" \" <<sscsum << std::endl;\n    if( sscsum != 1.0 )\n    {\n        m_sandFrac /= sscsum;\n        m_siltFrac /= sscsum;\n        m_clayFrac /= sscsum;\n    }\n\n    //\n    m_isValid = !(\n        *this == NaN ||\n        m_maxDepth < m_minDepth ||\n        fabs( sscsum - 1.0 ) > 0.1 ||\n        sscsum == 0 );\n\n    SetIsValid( m_isValid );\n}\n////////////////////////////////////////////////////////////////////////////////\nSoils::Layer::~Layer()\n{\n    ;\n}\n////////////////////////////////////////////////////////////////////////////////\nbool const& Soils::Layer::IsValid() const\n{\n    return m_isValid;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::Layer::SetIsValid( bool valid )\n{\n    m_isValid = valid;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetMinDepth() const\n{\n    return m_minDepth;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::Layer::SetMinDepth(\n    double const& minDepth )\n{\n    m_minDepth = minDepth;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetMaxDepth() const\n{\n    return m_maxDepth;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::Layer::SetMaxDepth(\n    double const& maxDepth )\n{\n    m_maxDepth = maxDepth;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetBulkDens() const\n{\n    return m_bulkDens;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetFldCpcty() const\n{\n    return m_fldCpcty;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetWltPnt() const\n{\n    return m_wltPnt;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetEvapCoeff() const\n{\n    return m_evapCoeff;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::Layer::SetEvapCoeff(\n    double const& evapCoeff )\n{\n    m_evapCoeff = evapCoeff;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetTransCoeff() const\n{\n    return m_transCoeff;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::Layer::SetTransCoeff(\n    double const& transCoeff )\n{\n    m_transCoeff = transCoeff;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetMinVolH2O() const\n{\n    return m_minVolH2O;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::Layer::SetMinVolH2O(\n    double const& minVolH2O )\n{\n    m_minVolH2O = minVolH2O;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetSandFrac() const\n{\n    return m_sandFrac;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetClayFrac() const\n{\n    return m_clayFrac;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetSiltFrac() const\n{\n    return m_siltFrac;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetOm() const\n{\n    return m_om;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetSatHydCond() const\n{\n    return m_satHydCond;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble const& Soils::Layer::GetPh() const\n{\n    return m_ph;\n}\n////////////////////////////////////////////////////////////////////////////////\nint Soils::GetNLayer()\n{\n    return m_nlayer;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::SetNLayer( int const& layer )\n{\n    m_nlayer = layer;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble Soils::GetSilt()\n{\n    return m_silt;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::SetSilt( double const& silt )\n{\n    m_silt = silt;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble Soils::GetSand()\n{\n    return m_sand;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::SetSand( double const& sand )\n{\n    m_sand = sand;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble Soils::GetClay()\n{\n    return m_clay;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::SetClay( double const& clay )\n{\n    m_clay = clay;\n}\n////////////////////////////////////////////////////////////////////////////////\ndouble Soils::GetBulkDensity()\n{\n    return m_bulkden;\n}\n////////////////////////////////////////////////////////////////////////////////\nvoid Soils::SetBulkDensity( double const& bulkden )\n{\n    m_bulkden = bulkden;\n}\n////////////////////////////////////////////////////////////////////////////////\n\n} //end soil\n} //end daycent\n} //end wrapper\n} //end leaf\n", "meta": {"hexsha": "63ca850545e92b608ab468bdaddef3af714d84d4", "size": 17429, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/leaf/wrapper/daycent/soil/Soils.cxx", "max_stars_repo_name": "IdahoLabCuttingBoard/LEAF", "max_stars_repo_head_hexsha": "9254bcbaa795071da30b4c22df7a2856ca90e36c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-28T22:52:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-28T22:52:33.000Z", "max_issues_repo_path": "src/leaf/wrapper/daycent/soil/Soils.cxx", "max_issues_repo_name": "IdahoLabCuttingBoard/LEAF", "max_issues_repo_head_hexsha": "9254bcbaa795071da30b4c22df7a2856ca90e36c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/leaf/wrapper/daycent/soil/Soils.cxx", "max_forks_repo_name": "IdahoLabCuttingBoard/LEAF", "max_forks_repo_head_hexsha": "9254bcbaa795071da30b4c22df7a2856ca90e36c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T20:35:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-26T17:10:38.000Z", "avg_line_length": 35.5693877551, "max_line_length": 104, "alphanum_fraction": 0.4225715761, "num_tokens": 4399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.278256793702402, "lm_q2_score": 0.020332354492818717, "lm_q1q2_score": 0.005657615769592365}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Primary class declared in the\n    swp_primary.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_primary.h\"\n#include \"swp_model_factory.h\"\n#include \"swp_cell.h\"\n#include \"swp_kmc_typedef.h\"\n\n#include <stdexcept>\n#include <memory.h>\n\n#include <boost/random/uniform_smallint.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::KMC_ARS;\n\nusing namespace std;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n//! Default constructor (protected).\nAggModels::Primary::Primary(void)\n: m_pmodel(NULL), m_createt(0.0), m_time(0.0), m_diam(0.0), m_dcol(0.0), \nm_dmob(0.0), m_surf(0.0), m_vol(0.0), m_mass(0.0), m_numcarbon(0), m_frag(0), m_numOf6Rings(0), m_phaseterm(0.0)\n{\n}\n\n// Initialising constructor.\nAggModels::Primary::Primary(double time, const Sweep::ParticleModel &model)\n{\n    init();\n    m_pmodel  = &model;\n    \n    // Set particle create and update times.\n    m_createt = time;\n    m_time    = time;\n\n    // Resize component and tracker vectors to match number of\n    // each in the particle model.\n    m_comp.resize(model.ComponentCount(), 0.0);\n    m_values.resize(model.TrackerCount(), 0.0);\n}\n\n// Copy constructor.\nAggModels::Primary::Primary(const Primary &copy)\n{\n    init();\n    *this = copy;\n}\n\n// Stream-reading constructor.\nAggModels::Primary::Primary(std::istream &in, const Sweep::ParticleModel &model)\n{\n    Deserialize(in, model);\n}\n\n// Default destructor.\nAggModels::Primary::~Primary()\n{\n    releaseMem();\n}\n\n\n// OPERATOR OVERLOADS.\n\n//! Assignment operator.\nAggModels::Primary &AggModels::Primary::operator=(const Primary &rhs)\n{\n    if (this != &rhs) {\n        // Check if the RHS uses the same particle model before copying\n        // components and tracker values.\n        if (rhs.m_pmodel == m_pmodel) {\n            // Copy composition.\n            memcpy(&m_comp[0], &rhs.m_comp[0], sizeof(double)*m_comp.size());        \n            // Copy tracker variables.\n            memcpy(&m_values[0], &rhs.m_values[0], sizeof(double)*m_values.size());\n        } else {\n            // Set the particle model.\n            m_pmodel = rhs.m_pmodel;\n            // Copy components.\n            m_comp.assign(rhs.m_comp.begin(), rhs.m_comp.end());\n            // Copy tracker variables.\n            m_values.assign(rhs.m_values.begin(), rhs.m_values.end());\n        }\n\n        // Copy primary time.\n        m_createt = rhs.m_createt;\n        m_time    = rhs.m_time;\n\n        //! Copy derived and basic properties.\n        m_diam = rhs.m_diam;\n        m_dcol = rhs.m_dcol;\n        m_dmob = rhs.m_dmob;\n        m_surf = rhs.m_surf;\n        m_vol  = rhs.m_vol;\n        m_mass = rhs.m_mass;\n        m_numcarbon = rhs.m_numcarbon;\n\t\tm_numOf6Rings = rhs.m_numOf6Rings;\n        m_frag = rhs.m_frag;\n\t\tm_phaseterm = rhs.m_phaseterm;\n    }\n    return *this;\n}\n\n// DEFINING PARTICLE MODEL.\n\n// Returns the particle model used to create this primary.\nconst Sweep::ParticleModel *const AggModels::Primary::ParticleModel(void) const\n{\n    return m_pmodel;\n}\n\n\n// PARTICLE COMPOSITION.\n\n//Returns named component\ndouble AggModels::Primary::GetComponent(std::string name) const\n{\n\tint index = m_pmodel->ComponentIndex(name);\n\treturn Composition(index);\n}\n\n// Returns the composition vector.\nconst fvector &AggModels::Primary::Composition() const\n{\n\treturn m_comp;\n}\n\n// Returns the ith component value.  Returns 0.0 if i is invalid.\ndouble AggModels::Primary::Composition(unsigned int i) const\n{\n\tif (i < m_comp.size()) {\n\t\treturn m_comp[i];\n\t} else {\n\t\treturn 0.0;\n\t}\n}\n\n// Sets the composition vector.\nvoid AggModels::Primary::SetComposition(const Sweep::fvector &comp)\n{\n\tm_comp.assign(comp.begin(), comp.end());\n}\n\n\n// TRACKER VARIABLE VALUES.\n\n// Returns the tracker value vector.\nconst fvector &AggModels::Primary::Values() const\n{\n\treturn m_values;\n}\n\n// Returns the ith tracker variable value.  Returns 0.0 if i is invalid.\ndouble AggModels::Primary::Values(unsigned int i) const\n{\n\tif (i < m_values.size()) {\n\t\treturn m_values[i];\n\t} else {\n\t\treturn 0.0;\n\t}\n}\n\n// Sets the values vector.\nvoid AggModels::Primary::SetValues(const fvector &vals)\n{\n    m_values.assign(vals.begin(), vals.end());\n}\n\n// Sets the ith trackervalue.\nvoid AggModels::Primary::SetValue(unsigned int i, double val)\n{\n\tif (i < m_values.size()) {\n\t\tm_values[i] = val;\n\t}\n}\n\n// PHASE VARIABLES\n\n// Get the mass of a specific phase\ndouble AggModels::Primary::GetPhaseMass(int i) const{\n\n\t// Get component indices for phase \n\tstd::vector<unsigned int> indices = m_pmodel->GetPhaseComponents(i);\n\n\t// Loop over composition and calculate mass and volume.\n\tdouble mass = 0.0;\n\tfor (std::vector<unsigned int>::const_iterator it = indices.begin(); it != indices.end(); ++it){\n\t\tmass += m_pmodel->Components((*it))->MolWt() * m_comp[(*it)] / NA;\n\t}\n\n\treturn mass;\n}\n\n// PRIMARY CREATE TIME.\n\n// Returns the primary create time.\ndouble AggModels::Primary::CreateTime() const {return m_createt;}\n\n\n// LAST UPDATE TIME.\n\n// Returns the primary last update time.\ndouble AggModels::Primary::LastUpdateTime() const {return m_time;}\n\n// Sets the last update time of the primary.\nvoid AggModels::Primary::SetTime(double t) {m_time = t;}\n\n\n// AGGREGATION MODEL.\n\n// Returns the aggregation model which this primary describes.\nAggModels::AggModelType AggModels::Primary::AggID(void) const {return AggModels::Spherical_ID;}\n\n// BASIC DERIVED PARTICLE PROPERTIES.\n\n//! Calculates the derived properties from the unique properties.\nvoid AggModels::Primary::UpdateCache(void)\n{\n    double m = 0.0;\n    int m_numcarbon_temp = 0;\n\n    // Loop over composition and calculate mass and volume.\n    m_mass = m_vol = 0.0;\n    for (unsigned int i=0; i!=m_pmodel->ComponentCount(); ++i) {\n        m = m_pmodel->Components(i)->MolWt() * m_comp[i] / NA;\n        m_mass += m;\n        if (m_pmodel->Components(i)->Density() > 0.0)\n            m_vol  += m / m_pmodel->Components(i)->Density();\n    }\n\n    /**\n     * Get the number of carbon atoms.\n     * It is assumed that the 0th index of m_comp contains the number of carbon\n     * atoms.\n     */\n    m_numcarbon = 0;\n    m_numcarbon = m_comp[0];\n\n    /**\n     * For particles with one carbon atom, set the number of carbon atoms to 0.\n     * m_numcarbon is used to calculate the rate of fragmentation. Particles\n     * with an m_numcarbon of 1 cannot further fragment; therefore, to exclude\n     * these particles from the rate calculation m_numcarbon is set to 0.  \n     */\n    if(m_numcarbon < 2) {\n        m_numcarbon = 0;\n    }\n\n    /**\n     * Indicate that a particle with one carbon atom cannot fragment.\n     * m_frag is used in the uniform selection of particle for fragmentation.\n     * By default, a particle is able to fragment.\n     */\n    m_frag = 0;\n    if(m_numcarbon >= 2) {\n        m_frag = 1;\n    }\n\n    // Calculate other properties (of sphere).\n    m_diam = pow(6.0 * m_vol / PI, ONE_THIRD);\n    m_dcol = m_diam;\n    m_dmob = m_diam;\n    m_surf = PI * m_diam * m_diam;\n    m_numcarbon = 0;\n    for (unsigned int i=0; i!=m_pmodel->ComponentCount(); ++i) {\n        m_numcarbon_temp = m_comp[i];\n        m_numcarbon += m_numcarbon_temp;\n    }\n\n\t// phaseterm for kinetic titania phase transformation\n\t// Components An and Ru assumed, 0 if components don't exist\n\tdouble An = AggModels::Primary::GetComponent(\"An\");\n\tdouble Ru = AggModels::Primary::GetComponent(\"Ru\");\n\tm_phaseterm = pow( An, TWO_THIRDS) * pow((An + Ru), ONE_THIRD);\n}\n\n// Returns the particle equivalent sphere diameter.\ndouble AggModels::Primary::SphDiameter(void) const {return m_diam;}\n\n// Returns the collision diameter.\ndouble AggModels::Primary::CollDiameter(void) const {return m_dcol;}\n\n// Rethrns the mobility diameter.\ndouble AggModels::Primary::MobDiameter(void) const {return m_dmob;}\n\n// Returns the surface area.\ndouble AggModels::Primary::SurfaceArea(void) const {return m_surf;}\n\n// Returns the equivalent sphere surface area, based\n// on the volume.\ndouble AggModels::Primary::SphSurfaceArea(void) const\n{\n    return PI * m_diam * m_diam;\n}\n\n// Returns the volume.\ndouble AggModels::Primary::Volume(void) const {return m_vol;}\n\n// Returns the mass.\ndouble AggModels::Primary::Mass(void) const {return m_mass;}\n\n//! Returns the number of carbon atoms.\nint AggModels::Primary::NumCarbon(void) const {return m_numcarbon;}\n\n//! Returns fragmentation flag.\nint AggModels::Primary::Frag(void) const {return m_frag;}\nint AggModels::Primary::NumRings(void) const { return m_numOf6Rings; }\n\n//! Returns the property with the given ID.\ndouble AggModels::Primary::Property(const Sweep::PropID id) const\n{\n    switch (id) {\n        case iDsph:      // Equivalent sphere diameter.\n            return m_diam;\n        case iDcol:   // Collision diameter.\n            return m_dcol;\n        case iDmob:   // Mobility diameter.\n            return m_dmob;\n        case iS:      // Surface area.\n            return m_surf;\n        case iASN:      // Surface area.\n            return GetSites();\n        case iV:      // Volume.\n            return m_vol;\n        case iM:      // Mass.\n            return m_mass;\n        case iNumCarbon:        //! Number of carbon atoms.\n            return m_numcarbon;\n        case iFrag:             //! Fragmentation flag.\n            return m_frag;\n        default:\n            return 0.0;\n    }\n}\n\n\n// BASIC DERIVED PROPERTY OVERWRITES.\n\n// Sets the spherical particle diameter\nvoid AggModels::Primary::SetSphDiameter(double diam) {m_diam = diam;}\n\n// Sets the collision diameter of the particle.\nvoid AggModels::Primary::SetCollDiameter(double dcol) {m_dcol = dcol;}\n\n// Sets the mobility diameter.\nvoid AggModels::Primary::SetMobDiameter(double dmob) {m_dmob = dmob;}\n\n// Sets the surface area, subject to minimum spherical area condition.\nvoid AggModels::Primary::SetSurfaceArea(double surf) {m_surf = surf;}\n\n// Sets the volume.\nvoid AggModels::Primary::SetVolume(double vol) {m_vol = vol;}\n\n// Sets the mass.\nvoid AggModels::Primary::SetMass(double m) {m_mass = m;}\n\n//! Sets the number of carbon atoms.\nvoid AggModels::Primary::SetNumCarbon(int numcarbon) {m_numcarbon = numcarbon;}\n\n//! Sets fragmentation flag.\nvoid AggModels::Primary::SetFrag(int frag) {m_frag = frag;}\n/*!\n * Check that this primary is a physically valid particle.  This currently\n * means checking that the amount of each component is within a range specifed\n * for that component.\n *\n *@return   True iff primary particle is valid as a physical particle\n */\nbool AggModels::Primary::IsValid() const {\n    for(unsigned int i = 0; i < m_comp.size(); ++i) {\n        // Check each component value, but stop as soon as an invalid value\n        // is found\n        if(!m_pmodel->Components(i)->IsValidValue(m_comp[i]))\n            return false;\n    }\n\n    // Check one of the cached values, all the m_??? could be added here\n    // if necessary.\n    return (m_mass > 0);\n}\n\n// OPERATIONS.\n\n// Adjusts the primary with the given composition and \n// tracker values changes n times.  If the particle cannot be adjust\n// n times, then this function returns the number of times\n// it was adjusted.\nunsigned int AggModels::Primary::Adjust(const fvector &dcomp, const fvector &dvalues, rng_type &rng, unsigned int n)\n{\n\tunsigned int i = 0;\n\n\tn = CalculateMaxAdjustments(dcomp, n);\n\n\t// Add the components.\n\tfor (i=0; i!=min(m_comp.size(),dcomp.size()); ++i) {\n\t\tm_comp[i] += dcomp[i] * (double)n;\n\t}\n\n\t// Add the tracker values.\n\tfor (i=0; i!=min(m_values.size(),dvalues.size()); ++i) {\n\t\tm_values[i] += dvalues[i] * (double)n;\n\t}\n\n    // Update property cache.\n\tif (n > 0) {\n\t\tAggModels::Primary::UpdateCache();\n\t}\n\n    return n;\n}\n\n/*!\n * Calculates the maximum number of LPDA adjustments allowed.\n *\n * This is relevant for Processes which remove components from a Primary,\n * particularly where multiple components are present in a particle.\n *\n * @param dcomp     The component changes for the Process\n * @param n         Number of times requested\n * @return          Actual number of times allowed\n */\nunsigned int AggModels::Primary::CalculateMaxAdjustments(\n        const fvector &dcomp,\n        unsigned int n) const\n{\n    unsigned int i;\n\n    // First check if there is a negative in dcomp\n    bool neg_change(false);\n    for (i=0; i!=dcomp.size(); ++i) {\n        if (dcomp[i] < 0.0) neg_change = true;\n    }\n\n    // Calculate the actual number of events only if there is a negative\n    // change in the component amount\n    if (neg_change) {\n        for (i=0; i!=min(m_comp.size(),dcomp.size()); ++i) {\n            if (dcomp[i] < 0.0)\n                n = std::min(n, (unsigned int) abs(m_comp[i]/dcomp[i]));\n        }\n    }\n\n    return n;\n}\n\n/*!\n* Calculates the maximum possible number of adjustments\n*\n* This is relevant for Processes which remove components from a Primary,\n* particularly where multiple components are present in a particle.\n*\n* @param dcomp     The component changes for the Process\n* @return          Number of times allowed\n*/\nunsigned int AggModels::Primary::CalculateMaxAdjustments(const fvector &dcomp) const\n{\n\tunsigned int i;\n\tunsigned int n = 0;\n\n\t// First check if there is a negative in dcomp\n\tbool neg_change(false);\n\tfor (i = 0; i != dcomp.size(); ++i) {\n\t\tif (dcomp[i] < 0.0) {\n\t\t\tneg_change = true;\n\t\t\tn = std::numeric_limits<unsigned int>::max();\n\t\t}\n\t}\n\n\t// Calculate the actual number of events only if there is a negative\n\t// change in the component amount\n\tif (neg_change) {\n\t\tfor (i = 0; i != min(m_comp.size(), dcomp.size()); ++i) {\n\t\t\tif (dcomp[i] < 0.0)\n\t\t\t\tn = std::min(n, (unsigned int)abs(m_comp[i] / dcomp[i]));\n\t\t}\n\t}\n\n\treturn n;\n}\n\n// Adjusts the particle n times for IntParticle reaction\nunsigned int AggModels::Primary::AdjustIntPar(const fvector &dcomp, const fvector &dvalues, rng_type &rng, unsigned int n)\n{\n    n = AggModels::Primary::Adjust(dcomp, dvalues, rng, n);\n\n    return n;\n}\n\n//Adjusts the particle n times for the phase transformation process\nunsigned int AggModels::Primary::AdjustPhase(const fvector &dcomp,\n                              const fvector &dvalues,\n                              rng_type &rng,\n\t\t\t\t\t\t\t  unsigned int n)\n{\n\tn = AggModels::Primary::Adjust(dcomp, dvalues, rng, n);\n\t\n    return n;\n}\n\n//Thermodynamic phase transformation (melting model)\nvoid AggModels::Primary::Melt(rng_type &rng, Cell &sys)\n{\n\t\n\tfvector dcomp(m_pmodel->ComponentCount(), 0.0);\n\tstd::vector<fvector> all_dcomp;\n\tfvector dvalues(m_pmodel->TrackerCount(), 0.0); //for now the transformation model doesn't adjust the tracker variables\n\tunsigned int n = 0;\n\n\t//check if liquid\n\tbool Liquid = ParticleModel()->MeltModel().IsLiquid(sys, *this);\n\n\t//has the particle melted?\n\tif (Liquid == true){\n\t\t// melt the particle\n\t\tParticleModel()->MeltModel().MeltingCompositionChange(all_dcomp);\n\t}\n\telse{ //particle is solid\n\t\t//total composition excluding liquid phase\n\t\tdouble mass = 0.0;\n\t\tfvector phaseMass(m_pmodel->PhaseCount(), 0.0);\n\t\t\n\t\t//add all components excluding liquid components\n\t\tfor (unsigned int i = 0; i < m_pmodel->PhaseCount(); i++){\n\t\t\tif (!m_pmodel->PhaseIsLiquid(i)){\n\t\t\t\tphaseMass[i] = GetPhaseMass(i);\n\t\t\t\tmass += phaseMass[i];\n\t\t\t}\n\t\t}\n\n\t\tif (mass > 0.0){\n\t\t\t//if solid phases exist then convert liquid to solid phase probabilistically\n\t\t\t//weighted by mass of existing solid phases\n\t\t\tboost::uniform_01<rng_type&, double> uniformGenerator(rng);\n\t\t\tdouble j = uniformGenerator() * mass; //generate random number\n\t\t\tfor (unsigned int i = 0; i < m_pmodel->PhaseCount(); i++){\n\n\t\t\t\tif (j <= phaseMass[i]){ \n\t\t\t\t\t//get change in composition\t\n\t\t\t\t\tParticleModel()->MeltModel().CompositionChange(i, all_dcomp);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tj -= phaseMass[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\t//if everything is liquid then tranform based on melting model\n\t\t\tParticleModel()->MeltModel().CompositionChange(sys, *this, all_dcomp); //get change in composition\t\n\t\t}\n\t}\n\n\t//loop over all composition changes and transform components\n\tfor (std::vector<fvector>::const_iterator it = all_dcomp.begin(); it != all_dcomp.end(); ++it){\n\n\t\tdcomp = *it;\n\n\t\t// transform components\n\t\tn = Primary::CalculateMaxAdjustments(dcomp); //transform everything: get max adjustment\n\t\tif (n > 0){ n = Primary::Adjust(dcomp, dvalues, rng, n); }; //adjust primary\n\t}\n}\n\n// Property for titania phase transformation model\ndouble AggModels::Primary::GetPhaseTerm(void) const\n{\n\treturn m_phaseterm;\t\n}\n\n/*!\n *  Combines this primary with another.\n *\n *  Note the very strange behaviour when the primaries do not\n *  have equal particle model pointers.  Users should also\n *  be very careful about not mixing different types that inherit\n *  from PrimaryParticle.\n *\n * \\param[in]       rhs         Primary particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nAggModels::Primary &AggModels::Primary::Coagulate(const Primary &rhs, rng_type &rng)\n{\n    // Check if the RHS uses the same particle model.  If not, then\n    // just use the assignment operator because you can't add apples \n    // and bananas!\n    if (rhs.m_pmodel == m_pmodel) {\n        // Add the components.\n        for (unsigned int i=0; i!=min(m_comp.size(),rhs.m_comp.size()); ++i) {\n            m_comp[i] += rhs.m_comp[i];\n        }\n\n        // Add the tracker values.\n        for (unsigned int i=0; i!=min(m_values.size(),rhs.m_values.size()); ++i) {\n            m_values[i] += rhs.m_values[i];\n        }\n\n        // Create time is the earliest time.\n        m_createt = min(m_createt, rhs.m_createt);\n        m_time    = min(m_time, rhs.m_time);\n    } else {\n        // Different particle models!\n        *this = rhs;\n        std::cerr << \"Sweep::AggModels::Primary::Coagulate called for particles with models \" << m_pmodel\n                  << \" and \" << rhs.m_pmodel << std::endl;\n    }\n    AggModels::Primary::UpdateCache();\n    return *this;\n}\n\n/*!\n *  Combines this primary with another.\n *\n *  Note the very strange behaviour when the primaries do not\n *  have equal particle model pointers.  Users should also\n *  be very careful about not mixing different types that inherit\n *  from PrimaryParticle.\n *\n * \\param[in]       rhs         Primary particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nAggModels::Primary &AggModels::Primary::Fragment(const Primary &rhs, rng_type &rng)\n{\n    // Check if the RHS uses the same particle model.  If not, then\n    // just use the assignment operator because you can't add apples \n    // and bananas!\n    if (rhs.m_pmodel == m_pmodel) {\n        // Add the components.\n        for (unsigned int i=0; i!=min(m_comp.size(),rhs.m_comp.size()); ++i) {\n            m_comp[i] += rhs.m_comp[i];\n        }\n\n        // Add the tracker values.\n        for (unsigned int i=0; i!=min(m_values.size(),rhs.m_values.size()); ++i) {\n            m_values[i] += rhs.m_values[i];\n        }\n\n        // Create time is the earliest time.\n        m_createt = min(m_createt, rhs.m_createt);\n        m_time    = min(m_time, rhs.m_time);\n    } else {\n        // Different particle models!\n        *this = rhs;\n        std::cerr << \"Sweep::AggModels::Primary::Fragment called for particles with models \" << m_pmodel\n                  << \" and \" << rhs.m_pmodel << std::endl;\n    }\n    AggModels::Primary::UpdateCache();\n    return *this;\n}\n\n// This routine sinters the Primary for the given length of\n// time using the provided sintering model.\nvoid AggModels::Primary::Sinter(double dt, Cell &sys,\n                     const Processes::SinteringModel &model,\n                     rng_type &rng,\n                     double wt)\n{\n    // Spherical primaries don't sinter.\n\t\n    return;\n}\n\n/*!\n * @brief       Gets the ratio of second to first component number\n *\n * A coarse estimation of the coverage fraction; as the amount of the second\n * component relative to the amount of the first. Returns 1.0 for single comp.\n *\n * @return      Ratio of number of second to first component\n */\ndouble AggModels::Primary::GetCoverageFraction() const\n{\n    double val = 1.0;\n\n    if (m_pmodel->ComponentCount() > 1 && m_comp[0] > 0.0) {\n        val = m_comp[1]/m_comp[0];\n    }\n\n    return val;\n}\n\n// READ/WRITE/COPY.\n\n// Returns a copy of the model data.\nAggModels::Primary *const AggModels::Primary::Clone(void) const\n{\n    return new Primary(*this);\n}\n\n//! Writes the object to a binary stream.\nvoid AggModels::Primary::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Write number of components.\n        unsigned int n = (unsigned int)m_comp.size();\n        out.write((char*)&n, sizeof(n));\n\n        // Write components.\n        double val = 0.0;\n        for (unsigned int i=0; i!=n; ++i) {\n            val = (double)m_comp[i];\n            out.write((char*)&val, sizeof(val));\n        }\n\n        // Write number of tracker values.\n        n = (unsigned int)m_values.size();\n        out.write((char*)&n, sizeof(n));\n\n        // Write values.\n        for (unsigned int i=0; i!=n; ++i) {\n            val = (double)m_values[i];\n            out.write((char*)&val, sizeof(val));\n        }\n\n        // Write create time.\n        val = (double)m_createt;\n        out.write((char*)&val, sizeof(val));\n\n        // Write last update time.\n        val = (double)m_time;\n        out.write((char*)&val, sizeof(val));\n\n        // Write equivalent sphere diameter.\n        val = (double)m_diam;\n        out.write((char*)&val, sizeof(val));\n\n        // Write collision diameter.\n        val = (double)m_dcol;\n        out.write((char*)&val, sizeof(val));\n\n        // Write mobility diameter.\n        val = (double)m_dmob;\n        out.write((char*)&val, sizeof(val));\n\n        // Write surface area.\n        val = (double)m_surf;\n        out.write((char*)&val, sizeof(val));\n\n        // Write volume.\n        val = (double)m_vol;\n        out.write((char*)&val, sizeof(val));\n\n        // Write mass.\n        val = (double)m_mass;\n        out.write((char*)&val, sizeof(val));\n\n        //! Write number of carbon atoms.\n        val = (int)m_numcarbon;\n        out.write((char*)&val, sizeof(val));\n\n        //! Write fragmentation flag.\n        val = (int)m_frag;\n        out.write((char*)&val, sizeof(val));\n\n\t\t// Write phaseterm.\n        val = (double)m_phaseterm;\n        out.write((char*)&val, sizeof(val));\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, AggModels::Primary::Serialize).\");\n    }\n}\n\n//! Reads the object from a binary stream.\nvoid AggModels::Primary::Deserialize(std::istream &in, const Sweep::ParticleModel &model)\n{\n    releaseMem();\n    m_pmodel = &model;\n\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        unsigned int n = 0;\n        double val = 0.0;\n\n        switch (version) {\n            case 0:\n                // Read number of components.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n\n                // Read components.\n                for (unsigned int i=0; i!=n; ++i) {\n                    in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                    m_comp.push_back((double)val);\n                }\n\n                // Read number of tracker values.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n\n                // Read values.\n                for (unsigned int i=0; i!=n; ++i) {\n                    in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                    m_values.push_back((double)val);\n                }\n\n                // Read create time.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_createt = (double)val;\n\n                // Read last update time.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_time = (double)val;\n\n                // Read equivalent sphere diameter.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_diam = (double)val;\n\n                // Read collision diameter.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_dcol = (double)val;\n\n                // Read mobility diameter.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_dmob = (double)val;\n\n                // Read surface area.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_surf = (double)val;\n\n                // Read volume.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_vol = (double)val;\n\n                // Read mass.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_mass = (double)val;\n\n                //! Read number of carbon atoms.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_numcarbon = (int)val;\n\n                //! Read fragmentation flag.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_frag = (int)val;\n\n\t\t\t\t// Read phaseterm.\n                in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                m_phaseterm = (double)val;\n\n                break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, AggModels::Primary::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, AggModels::Primary::Deserialize).\");\n    }\n}\n\n\n// DATA MANAGEMENT.\n\n// Release all memory associated with object.\nvoid AggModels::Primary::releaseMem(void)\n{\n    m_comp.clear();\n    m_values.clear();\n}\n\n//! Initialisation routine.\nvoid AggModels::Primary::init(void)\n{\n    m_pmodel = NULL;\n    m_createt = 0.0;\n    m_time = 0.0;\n    m_diam = 0.0; // Equivalent spherical diameter.\n    m_dcol = 0.0; // Collision diameter.\n    m_dmob = 0.0; // Mobility diameter.\n    m_surf = 0.0; // Surface area.\n    m_vol = 0.0;  // Volume.\n    m_mass = 0.0; // Mass.\n    m_numcarbon = 0;\n\tm_numOf6Rings = 0;\n    m_frag = 0;      //!< Fragmentation flag.\n\tm_phaseterm = 0.0; // Phase term.\n    releaseMem();\n}\n\n//! Check whether the number of carbon atoms in the primary is equal to that of\n//! the inception species.\nint AggModels::Primary::InceptedPAH() const\n{\n    std::vector<ParticleModel::PostProcessStartingStr> str_list = ParticleModel()->InceptedPAH();\n\tfor (std::vector<int>::size_type ii = 0; ii!=str_list.size(); ii++){\n\t\tParticleModel::PostProcessStartingStr str = str_list[ii];\n\t\t//A1, A1CH3, A2, A4, A4CH3, R5A3, A5\n\t\tswitch (str){\n\t\t\tcase ParticleModel::A1:\n\t\t\t\tif (NumCarbon() == BENZENE_C)\n\t\t\t\t\treturn 1;\n\t\t\t\tbreak;\n\t\t\tcase ParticleModel::A1CH3:\n\t\t\t\tif (NumCarbon() == TOLUENE_C)\n\t\t\t\t\treturn 1;\n\t\t\t\tbreak;\n\t\t\tcase ParticleModel::A2:\n\t\t\t\tif (NumCarbon() == NAPHTHALENE_C)\n\t\t\t\t\treturn 1;\n\t\t\t\tbreak;\n\t\t\tcase ParticleModel::A4:\n\t\t\t\tif (NumCarbon() == PYRENE_C)\n\t\t\t\t\treturn 1;\n\t\t\t\tbreak;\n\t\t\tcase ParticleModel::A4CH3:\n\t\t\t\tif (NumCarbon() == METHYLPYRENE_C)\n\t\t\t\t\treturn 1;\n\t\t\t\tbreak;\n\t\t\tcase ParticleModel::R5A3:\n\t\t\t\tif (NumCarbon() == MPHENANTHRENER_C)\n\t\t\t\t\treturn 1;\n\t\t\t\tbreak;\n\t\t\tcase ParticleModel::A5:\n\t\t\t\tif (NumCarbon() == BENZOPYRENE_C)\n\t\t\t\t\treturn 1;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}\n\n//! Returns the frame position and orientation, and primary coordinates\n//\tUsed by bintree_primary for particle tracking\nvoid AggModels::Primary::GetFrameCoords(std::vector<fvector> &coords) const\n{\n\t//unused\n}\n\nvoid AggModels::Primary::setTracking()\n{\n\t//spherical particles don't have primaries\n}\n\nvoid AggModels::Primary::removeTracking()\n{\n\t//spherical particles don't have primaries\n}", "meta": {"hexsha": "d5ccf45f2a567c4820d919631422f3f763c0e147", "size": 29235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_primary.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_primary.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_primary.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 29.5303030303, "max_line_length": 122, "alphanum_fraction": 0.6297588507, "num_tokens": 7475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2043418950913969, "lm_q2_score": 0.027585282826360594, "lm_q1q2_score": 0.00563682896937069}}
{"text": "/*\n// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n#ifndef STAPL_CONTAINERS_GRAPH_ALGORITHMS_GRAPH_COLORING_HPP\n#define STAPL_CONTAINERS_GRAPH_ALGORITHMS_GRAPH_COLORING_HPP\n\n#include <stapl/algorithms/algorithm.hpp>\n#include <stapl/containers/graph/views/graph_view.hpp>\n#include <stapl/views/native_view.hpp>\n#include <stapl/views/array_view.hpp>\n#include <stapl/views/repeated_view.hpp>\n#include <stapl/containers/array/static_array.hpp>\n#include <stapl/domains/interval.hpp>\n#include <stapl/containers/partitions/explicit.hpp>\n#include <boost/unordered_map.hpp>\n#include <vector>\n#include <utility>\n\nnamespace stapl {\n\nnamespace graph_coloring_impl {\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Functor to extract color of a remote-neighbor vertex.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct get_remote_neighbor_colors\n{\n  typedef boost::unordered_map<size_t, size_t> result_type;\n\nprivate:\n  size_t m_key;\n\npublic:\n  get_remote_neighbor_colors(size_t const& key)\n    : m_key(key)\n  { }\n\n  template <typename HashMap>\n  result_type operator()(HashMap& hmap) const\n  {\n    typename HashMap::iterator it;\n    it = hmap.find(m_key);\n\n    if (it == hmap.end())\n      return result_type();\n\n    return it->second;\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_key);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Functor to store received color from a neighbor vertex.\n/// Used by @ref set_remote_neighbor_colors_of_vertex.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct set_remote_neighbor_colors\n{\n  typedef void result_type;\n\nprivate:\n  typedef std::pair<size_t, size_t> neighbor_color_type;\n\n  size_t              m_vid;\n  neighbor_color_type m_neighbor_color;\n\npublic:\n  set_remote_neighbor_colors(size_t const& vid,\n                             neighbor_color_type const& neighbor_color)\n    : m_vid(vid), m_neighbor_color(neighbor_color)\n  { }\n\n  template <typename HashMap>\n  void operator()(HashMap& hmap) const\n  {\n    hmap[m_vid][m_neighbor_color.first] = m_neighbor_color.second;\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_vid);\n    t.member(m_neighbor_color);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to inform the neighbors of a vertex of its color\n/// using @ref set_remote_neighbor_colors.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\ntemplate <typename HashMap>\nclass set_remote_neighbor_colors_of_vertex\n{\npublic:\n  typedef std::pair<size_t, size_t> neighbor_color_type;\n  typedef void                      result_type;\n\nprivate:\n  neighbor_color_type               m_neighbor_color;\n  p_object_pointer_wrapper<HashMap> m_hashmap;\n\npublic:\n  set_remote_neighbor_colors_of_vertex(\n    neighbor_color_type const& neighbor_color,\n    HashMap& hashmap)\n    : m_neighbor_color(neighbor_color),\n      m_hashmap(&hashmap)\n  { }\n\n  template <typename Vertex>\n  void operator()(Vertex&& v) const\n  {\n    m_hashmap->apply_set(\n      m_hashmap->get_location_id(),\n      set_remote_neighbor_colors(v.descriptor(), m_neighbor_color)\n    );\n  }\n\n  void define_type(typer& t)\n  {\n    t.member(m_neighbor_color);\n    t.member(m_hashmap);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Function to pick a color that does not conflict with the\n/// provided colors. Used to pick a safe color for a vertex.\n/// @param neighbor_colors A domain specifying the colors of all neighbors\n/// of the vertex in question.\n/// @return A safe color that can be assigned to the vertex without creating\n/// conflicts with the input set of colors.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\ninline size_t pick_vertex_color(domset1D<size_t> const& neighbor_colors)\n{\n  size_t num_colors = neighbor_colors.size();\n  domset1D<size_t> contiguous_dom(num_colors);\n  contiguous_dom -= neighbor_colors;\n  if (contiguous_dom.empty())\n    return num_colors;\n  else\n    return contiguous_dom.first();\n}\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to compute graph coloring.\n/// Works over a partition of the graph to compute the coloring for\n/// each partition independently. The coloring for border vertices is\n/// is then adjusted to reflect any colors received from neighbors in\n/// a different partition.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct graph_coloring_wf\n{\n  typedef void result_type;\n\n  template <typename Partition, typename GView, typename ColorMap,\n            typename Array>\n  void operator()(Partition const& p, GView& gview, ColorMap& color_map,\n                  Array& hashmap_array) const\n  {\n    typedef boost::unordered_map<size_t, size_t> color_boundary_map_type;\n    typename Partition::const_vertex_iterator it = p.begin(),\n                                          end_it = p.end();\n    for (; it!=end_it; ++it) {\n      bool boundary_vertex = false;\n      domset1D<size_t> neighbor_colors;\n      std::vector<size_t> remote_neighbors;\n      size_t vid = (*it).descriptor();\n      typename Partition::const_vertex_iterator::reference::adj_edge_iterator\n        edge_it = (*it).begin(), edge_end_it = (*it).end();\n      for (; edge_it!=edge_end_it; ++edge_it) {\n        size_t target = (*edge_it).target();\n\n        //Get colors of local neighbors\n        if (p.domain().contains(target) && (target != vid)) {\n          neighbor_colors += color_map.get(target);\n        } else {\n          remote_neighbors.push_back(target);\n          boundary_vertex = true;\n        }\n      } //endfor over edges\n\n      //Check received colors of remote neighbors\n      if (boundary_vertex) {\n        color_boundary_map_type bmap =\n          hashmap_array.apply_get(\n            hashmap_array.container().get_location_id(),\n            get_remote_neighbor_colors(vid)\n          );\n        color_boundary_map_type::iterator map_it = bmap.begin(),\n                                          map_end_it = bmap.end();\n        for (; map_it!=map_end_it; ++map_it)\n          neighbor_colors += map_it->second;\n      }\n\n      size_t mycolor = pick_vertex_color(neighbor_colors);\n      //set my color\n      color_map.put(vid, mycolor);\n\n      //send my color to neighbors\n      if (boundary_vertex) {\n        std::vector<size_t>::iterator vect_it = remote_neighbors.begin(),\n                                      vect_end_it = remote_neighbors.end();\n        for (; vect_it!=vect_end_it; ++vect_it) {\n          typedef typename view_traits<Array>::container hashmap_type;\n\n          gview.apply_set(*vect_it,\n                          set_remote_neighbor_colors_of_vertex<hashmap_type>(\n                            std::make_pair(vid, mycolor),\n                            hashmap_array.container()));\n        }\n      }\n    } //endfor over the vertices\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to return if the coloring stored in the provided\n/// vertex property map (color_map) is valid for the input graph.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct is_valid_graph_coloring_wf\n{\n  typedef bool result_type;\n\n  template <typename Vertex, typename ColorMap>\n  bool operator()(Vertex const& v, ColorMap& color_map) const\n  {\n    size_t vid = v.descriptor();\n    size_t mycolor = color_map.get(v);\n    typename Vertex::const_adj_edge_iterator edge_it = v.begin(),\n                                             edge_end_it = v.end();\n    for (; edge_it!=edge_end_it; ++edge_it)\n    {\n      size_t target = (*edge_it).target();\n      if ((color_map.get(target) == mycolor) && (target != vid))\n        return false;\n    }\n    return true;\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to return the color of a vertex.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct get_vertex_color\n{\n  typedef domset1D<size_t> result_type;\n\n  template <typename Vertex, typename ColorMap>\n  result_type operator()(Vertex const& v, ColorMap& color_map) const\n  {\n    size_t mycolor = color_map.get(v);\n    return result_type(mycolor, mycolor);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to merge two vectors. Used in reduce.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\ntemplate<typename T>\nstruct reduce_vector_wf\n{\n  typedef std::vector<T> result_type;\n  template<typename Element1, typename Element2>\n  result_type operator()(Element1 const& elt1, Element2 const& elt2)\n  {\n    result_type result = elt1;\n    std::copy(elt2.begin(), elt2.end(), std::back_inserter(result));\n    return result;\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to return the sub-domain of the elements in\n/// the hash-map.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\ntemplate <typename HashMap, typename DomainType>\nstruct get_sub_domain\n{\n  typedef std::vector<DomainType> result_type;\n  template<typename Element>\n  result_type operator()(Element const& elt)\n  {\n    HashMap hmap = elt;\n    DomainType dom;\n    typename HashMap::iterator it = hmap.begin(),\n                           end_it = hmap.end();\n    for (; it!=end_it; ++it)\n    {\n      dom += it->first;\n    }\n    return result_type(1, dom);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to resolve color conflicts between boundary\n/// vertices that end up with the same colors despite being neighbors.\n/// In such cases, one of the vertices is re-assigned its colors based\n/// on the next safe color it can use.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct resolve_color_conflicts\n{\n  typedef bool result_type;\n\n  template <typename Partition, typename GView, typename ColorMap,\n            typename Array>\n  result_type operator()(Partition const& p, GView& gview, ColorMap& color_map,\n                         Array& hashmap_array) const\n  {\n    typedef boost::unordered_map<size_t, size_t> color_boundary_map_type;\n    bool partition_conflict = false;\n    typedef typename Partition::const_vertex_iterator const_vertex_iterator;\n    const_vertex_iterator it = p.begin(), end_it = p.end();\n    for (; it!=end_it; ++it) {\n      bool responsible_for_conflict = false;\n      domset1D<size_t> neighbor_colors;\n      size_t vid = (*it).descriptor();\n      size_t mycolor = color_map.get(vid);\n      color_boundary_map_type bmap =\n        hashmap_array.apply_get(\n          hashmap_array.container().get_location_id(),\n          get_remote_neighbor_colors(vid)\n        );\n\n      color_boundary_map_type::iterator map_it = bmap.begin(),\n                                        map_end_it = bmap.end();\n      //Compare my color with remote neighbors' colors\n      for (; map_it!=map_end_it; ++map_it) {\n        size_t neighbor_id = map_it->first;\n        size_t neighbor_color = map_it->second;\n        neighbor_colors += neighbor_color;\n        if (mycolor == neighbor_color && (vid < neighbor_id)) {\n          partition_conflict = true;\n          responsible_for_conflict = true;\n        }\n      }\n\n      if (responsible_for_conflict) {\n        const auto p = *it;\n\n        typename decltype(p)::const_adj_edge_iterator\n          edge_it = p.begin(), edge_end_it = p.end();\n        for (; edge_it!=edge_end_it; ++edge_it) {\n          size_t target = (*edge_it).target();\n\n          //Get colors of local neighbors\n          if (!bmap.count(target) && (target != vid)) {\n            neighbor_colors += color_map.get(target);\n          }\n        }\n\n        size_t new_color = pick_vertex_color(neighbor_colors);\n\n        //set my color\n        color_map.put(vid, new_color);\n\n        //send my new color to remote neighbors\n        map_it = bmap.begin();\n        for (; map_it!=map_end_it; ++map_it) {\n          typedef typename view_traits<Array>::container hashmap_type;\n\n          gview.apply_set(map_it->first,\n                          set_remote_neighbor_colors_of_vertex<hashmap_type>(\n                            std::make_pair(vid, new_color),\n                            hashmap_array.container()));\n        }\n      }\n    }\n    return partition_conflict;\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to populate an output undirected graph with\n/// vertices from the directed graph.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct build_vertex_undirected_graph_wf\n{\n  typedef void result_type;\n\n  template <typename Vertex,typename UGraph>\n  void operator()(Vertex v, UGraph& ugraph) const\n  {\n    ugraph.add_vertex(v.descriptor(), typename UGraph::vertex_property());\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work-function to create an undirected version of a directed graph.\n/// Adds bi-directional edges for each directed edge in the input graph.\n/// @ingroup pgraphAlgoDetails\n//////////////////////////////////////////////////////////////////////\nstruct build_edge_undirected_graph_wf\n{\n  typedef void result_type;\n\n  template <typename Vertex,typename UGraph>\n  void operator()(Vertex v, UGraph& ugraph) const\n  {\n    typedef typename UGraph::edge_descriptor edge_descriptor;\n    typename Vertex::adj_edge_iterator edge_it = v.begin(),\n                                       edge_end_it = v.end();\n    for (; edge_it!=edge_end_it; ++edge_it)\n    {\n      ugraph.add_edge_async(edge_descriptor((*edge_it).source(),\n                                            (*edge_it).target()));\n    }\n  }\n};\n\n} // namespace graph_coloring_impl\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Parallel Level-Synchronized Graph Coloring Algorithm.\n///\n/// Assigns coloring to the vertices of the input graph, such that\n/// neighboring vertices are not assigned the same color.\n/// @param graph The @ref graph_view over the input graph.\n/// @param color_map The output vertex property map where the color information\n/// will be stored. [vertex->color (int)]\n/// Specialization for directed graphs.\n/// Copies the directed graph to an undirected graph and computes coloring\n/// for the undirected graph.\n/// @warning  This method invalidates the input graph view.\n/// @ingroup pgraphAlgo\n/// @todo This could be using an @ref undirected_view over the input graph\n/// instead of creating its own methods to make the undirected graph.\n//////////////////////////////////////////////////////////////////////\ntemplate <template<typename, typename, typename, typename> class GView,\n          template<graph_attributes, graph_attributes, typename...> class Graph,\n          graph_attributes M, typename ...OptionalParams,\n          typename Dom, typename MapFunc, typename Derived, typename ColorMap>\nvoid color_graph(GView<Graph<DIRECTED, M, OptionalParams...>,\n                 Dom, MapFunc, Derived> const& graph,\n                 ColorMap& color_map)\n{\n  typedef Graph<UNDIRECTED, NONMULTIEDGES, OptionalParams...>\n                                                        undirected_graph_type;\n  typedef graph_view<undirected_graph_type,\n                typename undirected_graph_type::domain_type,\n                MapFunc,Derived>                        undirected_view_type;\n\n  undirected_graph_type undir_graph;\n  undirected_view_type undir_view(undir_graph);\n\n  //Add vertices.\n  map_func(graph_coloring_impl::build_vertex_undirected_graph_wf(),\n           graph, make_repeat_view(undir_view));\n\n  //Add undirected edges.\n  map_func(graph_coloring_impl::build_edge_undirected_graph_wf(), graph,\n           make_repeat_view(undir_view));\n\n  undirected_view_type undir_view2(undir_graph);\n  color_graph(undir_view2, color_map);\n}\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Parallel Level-Synchronized Graph Coloring Algorithm.\n///\n/// Assigns coloring to the vertices of the input graph, such that\n/// neighboring vertices are not assigned the same color.\n/// @param graph The @ref graph_view over the input graph.\n/// @param color_map The output vertex property map where the color information\n/// will be stored. [vertex->color (int)]\n/// Specialization for @ref iterator_domain based @ref graph_view over\n/// @ref dynamic_graph, because sparse-domain is needed in the algorithm to\n/// have a view over the boundary vertices.\n/// @ingroup pgraphAlgo\n//////////////////////////////////////////////////////////////////////\ntemplate <template<typename, typename, typename, typename> class GView,\n          template<graph_attributes, graph_attributes, typename...> class Graph,\n          graph_attributes M, typename ...OptionalParams,\n          typename Dist, typename DomMap,\n          typename MapFunc, typename Derived, typename ColorMap>\nvoid color_graph(GView<Graph<UNDIRECTED, M, OptionalParams...>,\n                 iterator_domain<Dist, DomMap>, MapFunc, Derived>\n                 const& graph, ColorMap& color_map)\n{\n  typedef Graph<UNDIRECTED, M, OptionalParams...>        undirected_graph_type;\n  typedef GView<undirected_graph_type, domset1D<size_t>,\n                MapFunc, Derived>                        view_type;\n  typedef GView<undirected_graph_type,\n                iterator_domain<Dist, DomMap>,\n                MapFunc, Derived>                        original_view_type;\n\n  //graph might have come from the directed color_graph method, which means\n  //it might be invalid. The constructor below calls a map_reduce, so we need\n  //to reconstruct the view in this case to make sure it is valid.\n  original_view_type const& valid_graph = graph.is_valid() ?\n    graph : original_view_type(\n              graph.container(), graph.domain(), graph.mapfunc(), graph);\n\n  view_type new_view(valid_graph);\n\n  //Call graph coloring with the domset1D view\n  color_graph(new_view, color_map);\n}\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Parallel Level-Synchronized Graph Coloring Algorithm.\n///\n/// Assigns coloring to the vertices of the input graph, such that\n/// neighboring vertices are not assigned the same color.\n/// @param graph The @ref graph_view over the input graph.\n/// @param color_map The output vertex property map where the color information\n/// will be stored. [vertex->color (int)]\n/// @ingroup pgraphAlgo\n//////////////////////////////////////////////////////////////////////\ntemplate <typename GView, typename ColorMap>\nvoid color_graph(GView const& graph, ColorMap& color_map)\n{\n  typedef GView                                       graph_view;\n  typedef typename graph_view::gid_type               vertex_descriptor;\n  typedef typename graph_view::domain_type            domain_type;\n  typedef boost::unordered_map<vertex_descriptor,\n                               size_t>                vertex_color_map_type;\n  typedef boost::unordered_map<vertex_descriptor,\n                               vertex_color_map_type> hashmap_type;\n  typedef static_array<hashmap_type>                  array_type;\n  typedef array_view<array_type>                      array_view_type;\n\n  using namespace graph_coloring_impl;\n  size_t num_locs = get_num_locations();\n  array_type hashmap_array(num_locs);\n  array_view_type hashmap_array_view(hashmap_array);\n\n  map_func(graph_coloring_wf(), stapl::native_view(graph),\n           make_repeat_view(graph), make_repeat_view(color_map),\n           make_repeat_view(hashmap_array_view));\n\n  /*Resolve conflicts with boundary vertices*/\n  //create domains of boundary vertices\n  typedef explicit_partition<typename GView::domain_type>   partition_type;\n  typedef segmented_view<GView,\n                           partition_type>                  segment_view_type;\n\n  std::vector<domain_type> sub_domains =\n    map_reduce(get_sub_domain<hashmap_type, domain_type>(),\n               reduce_vector_wf<domain_type>(),hashmap_array_view);\n  segment_view_type\n    boundary_view(graph, partition_type(graph.domain(), sub_domains));\n\n  while (map_reduce(resolve_color_conflicts(), plus<bool>(), boundary_view,\n                    make_repeat_view(graph), make_repeat_view(color_map),\n                    make_repeat_view(hashmap_array_view)))\n  { }\n}\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Extracts the colors from the input graph, given the color map.\n///\n/// @param graph The @ref graph_view over the input graph.\n/// @param color_map The input vertex property map where the color information\n/// is stored. [vertex->color (int)]. Must have been previously populated by\n/// calling @ref color_graph().\n/// @return The domain of colors in the graph.\n/// @ingroup pgraphAlgo\n//////////////////////////////////////////////////////////////////////\ntemplate <typename GView, typename ColorMap>\ndomset1D<size_t> get_graph_colors(GView const& graph, ColorMap& color_map)\n{\n  typedef domset1D<size_t> domain_type;\n  return map_reduce(graph_coloring_impl::get_vertex_color(),\n                    plus<domain_type>(), graph, make_repeat_view(color_map));\n}\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Computes if the given coloring is valid for the input graph.\n///\n/// @param graph The @ref graph_view over the input graph.\n/// @param color_map The input vertex property map where the color information\n/// is stored. [vertex->color (int)]. Must have been previously populated by\n/// calling @ref color_graph().\n/// @return True if the coloring is valid, false otherwise.\n/// @ingroup pgraphAlgo\n//////////////////////////////////////////////////////////////////////\ntemplate <typename GView, typename ColorMap>\nbool is_valid_graph_coloring(GView const& graph, ColorMap& color_map)\n{\n  return map_reduce(graph_coloring_impl::is_valid_graph_coloring_wf(),\n                    logical_and<bool>(), graph, make_repeat_view(color_map));\n}\n\n} // namespace stapl\n\n#endif\n", "meta": {"hexsha": "de069b8eace7bfb65c0d912db70bea80260f4154", "size": 22768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stapl_release/stapl/containers/graph/algorithms/graph_coloring.hpp", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": "stapl_release/stapl/containers/graph/algorithms/graph_coloring.hpp", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/stapl/containers/graph/algorithms/graph_coloring.hpp", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-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.312599681, "max_line_length": 80, "alphanum_fraction": 0.6095836261, "num_tokens": 4549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.02002344048536054, "lm_q1q2_score": 0.005634708673947568}}
{"text": "//=============================================================================================================\n/**\n* @file     hpifit.cpp\n* @author   Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     March, 2017\n*\n* @section  LICENSE\n*\n* Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    HPIFit class defintion.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"hpifit.h\"\n\n#include <fiff/fiff_dig_point_set.h>\n\n#include <utils/ioutils.h>\n\n#include <iostream>\n#include <fiff/fiff_cov.h>\n#include <fstream>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QFuture>\n#include <QtConcurrent/QtConcurrent>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace INVERSELIB;\nusing namespace FIFFLIB;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\nEigen::MatrixXd pinv(Eigen::MatrixXd a)\n{\n    double epsilon = std::numeric_limits<double>::epsilon();\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n    double tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs()(0);\n    return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(),0).matrix().asDiagonal() * svd.matrixU().adjoint();\n}\n\n\n/*********************************************************************************\n * magnetic_dipole leadfield for a magnetic dipole in an infinite medium\n * The function has been compared with matlab magnetic_dipole and it gives same output\n *********************************************************************************/\n\nEigen::MatrixXd magnetic_dipole(Eigen::MatrixXd pos, Eigen::MatrixXd pnt, Eigen::MatrixXd ori) {\n\n    double u0 = 1e-7;\n    int nchan;\n    Eigen::MatrixXd r, r2, r5, x, y, z, mx, my, mz, Tx, Ty, Tz, lf;\n\n    nchan = pnt.rows();\n\n    // Shift the magnetometers so that the dipole is in the origin\n    pnt.array().col(0) -= pos(0);\n    pnt.array().col(1) -= pos(1);\n    pnt.array().col(2) -= pos(2);\n\n    r = pnt.array().square().rowwise().sum().sqrt();\n\n    r2 = r5 = x = y = z = mx = my = mz = Tx = Ty = Tz = lf = Eigen::MatrixXd::Zero(nchan,3);\n\n    for(int i = 0;i < nchan;i++) {\n        r2.row(i).array().fill(pow(r(i),2));\n        r5.row(i).array().fill(pow(r(i),5));\n    }\n\n    for(int i = 0;i < nchan;i++) {\n        x.row(i).array().fill(pnt(i,0));\n        y.row(i).array().fill(pnt(i,1));\n        z.row(i).array().fill(pnt(i,2));\n    }\n\n    mx.col(0).array().fill(1);\n    my.col(1).array().fill(1);\n    mz.col(2).array().fill(1);\n\n    Tx = 3 * x.cwiseProduct(pnt) - mx.cwiseProduct(r2);\n    Ty = 3 * y.cwiseProduct(pnt) - my.cwiseProduct(r2);\n    Tz = 3 * z.cwiseProduct(pnt) - mz.cwiseProduct(r2);\n\n    for(int i = 0;i < nchan;i++) {\n        lf(i,0) = Tx.row(i).dot(ori.row(i));\n        lf(i,1) = Ty.row(i).dot(ori.row(i));\n        lf(i,2) = Tz.row(i).dot(ori.row(i));\n    }\n\n    for(int i = 0;i < nchan;i++) {\n        for(int j = 0;j < 3;j++) {\n            lf(i,j) = u0 * lf(i,j)/(4 * M_PI * r5(i,j));\n        }\n    }\n\n    return lf;\n}\n\n\n/*********************************************************************************\n * compute_leadfield computes a forward solution for a dipole in a a volume\n * conductor model. The forward solution is expressed as the leadfield\n * matrix (Nchan*3), where each column corresponds with the potential or field\n * distributions on all sensors for one of the x,y,z-orientations of the dipole.\n * The function has been compared with matlab ft_compute_leadfield and it gives\n * same output\n *********************************************************************************/\n\nEigen::MatrixXd compute_leadfield(const Eigen::MatrixXd& pos, const struct SensorInfo& sensors)\n{\n\n    Eigen::MatrixXd pnt, ori, lf;\n\n    pnt = sensors.coilpos; // position of each coil\n    ori = sensors.coilori; // orientation of each coil\n\n    lf = magnetic_dipole(pos, pnt, ori);\n\n    lf = sensors.tra * lf;\n\n    return lf;\n}\n\n\n/*********************************************************************************\n * dipfitError computes the error between measured and model data\n * and can be used for non-linear fitting of dipole position.\n * The function has been compared with matlab dipfit_error and it gives\n * same output\n *********************************************************************************/\n\nDipFitError dipfitError(const Eigen::MatrixXd& pos, const Eigen::MatrixXd& data, const struct SensorInfo& sensors, const Eigen::MatrixXd& matProjectors)\n{\n    // Variable Declaration\n    struct DipFitError e;\n    Eigen::MatrixXd lf, dif;\n\n    // Compute lead field for a magnetic dipole in infinite vacuum\n    lf = compute_leadfield(pos, sensors);\n\n    e.moment = pinv(lf) * data;\n\n    //dif = data - lf * e.moment;\n    dif = data - matProjectors * lf * e.moment;\n\n    e.error = dif.array().square().sum()/data.array().square().sum();\n\n    e.numIterations = 0;\n\n    return e;\n}\n\n\n/*********************************************************************************\n * Compare function for sorting\n *********************************************************************************/\n\nbool compare(HPISortStruct a, HPISortStruct b)\n{\n    return (a.base_arr < b.base_arr);\n}\n\n\n/*********************************************************************************\n * fminsearch Multidimensional unconstrained nonlinear minimization (Nelder-Mead).\n * X = fminsearch(X0, maxiter, maxfun, display, data, sensors) starts at X0 and\n * attempts to find a local minimizer\n *********************************************************************************/\n\nEigen::MatrixXd fminsearch(const Eigen::MatrixXd& pos,\n                           int maxiter,\n                           int maxfun,\n                           int display,\n                           const Eigen::MatrixXd& data,\n                           const Eigen::MatrixXd& matProjectors,\n                           const struct SensorInfo& sensors,\n                           int &simplex_numitr)\n{\n    double tolx, tolf, rho, chi, psi, sigma, func_evals, usual_delta, zero_term_delta, temp1, temp2;\n    std::string header, how;\n    int n, itercount, prnt;\n    Eigen::MatrixXd onesn, two2np1, one2n, v, y, v1, tempX1, tempX2, xbar, xr, x, xe, xc, xcc, xin, posCopy;\n    std::vector <double> fv, fv1;\n    std::vector <int> idx;\n\n    DipFitError tempdip, fxr, fxe, fxc, fxcc;\n\n    //tolx = tolf = 1e-4;\n    // Seok\n    tolx = tolf = 1e-9;\n\n    switch(display) {\n        case 0:\n            prnt = 0;\n            break;\n        default:\n            prnt = 1;\n    }\n\n    header = \" Iteration   Func-count     min f(x) Procedure\";\n\n    posCopy = pos;\n\n    n = posCopy.cols();\n\n    // Initialize parameters\n    rho = 1; chi = 2; psi = 0.5; sigma = 0.5;\n    onesn = Eigen::MatrixXd::Ones(1,n);\n    two2np1 = one2n = Eigen::MatrixXd::Zero(1,n);\n\n    for(int i = 0;i < n;i++) {\n        two2np1(i) = 1 + i;\n        one2n(i) = i;\n    }\n\n    v = v1 = Eigen::MatrixXd::Zero(n, n+1);\n    fv.resize(n+1);\n    idx.resize(n+1);\n    fv1.resize(n+1);\n\n    for(int i = 0;i < n; i++) {\n        v(i,0) = posCopy(i);\n    }\n\n    tempdip = dipfitError(posCopy, data, sensors, matProjectors);\n    fv[0] = tempdip.error;\n\n    func_evals = 1;\n    itercount = 0;\n    how = \"\";\n\n    // Continue setting up the initial simplex.\n    // Following improvement suggested by L.Pfeffer at Stanford\n    usual_delta = 0.05;             // 5 percent deltas for non-zero terms\n    zero_term_delta = 0.00025;      // Even smaller delta for zero elements of x\n    xin = posCopy.transpose();\n\n    for(int j = 0;j < n;j++) {\n        y = xin;\n\n        if(y(j) != 0) {\n            y(j) = (1 + usual_delta) * y(j);\n        } else {\n            y(j) = zero_term_delta;\n        }\n\n        v.col(j+1).array() = y;\n        posCopy = y.transpose();\n        tempdip = dipfitError(posCopy, data, sensors, matProjectors);\n        fv[j+1] = tempdip.error;\n    }\n\n    // Sort elements of fv\n    std::vector<HPISortStruct> vecSortStruct;\n\n    for (int i = 0; i < fv.size(); i++) {\n        HPISortStruct structTemp;\n        structTemp.base_arr = fv[i];\n        structTemp.idx = i;\n        vecSortStruct.push_back(structTemp);\n    }\n\n    sort (vecSortStruct.begin(), vecSortStruct.end(), compare);\n\n    for (int i = 0; i < vecSortStruct.size(); i++) {\n        idx[i] = vecSortStruct[i].idx;\n    }\n\n    for (int i = 0;i < n+1;i++) {\n        v1.col(i) = v.col(idx[i]);\n        fv1[i] = fv[idx[i]];\n    }\n\n    v = v1;fv = fv1;\n\n    how = \"initial simplex\";\n    itercount = itercount + 1;\n    func_evals = n + 1;\n\n    tempX1 = Eigen::MatrixXd::Zero(1,n);\n\n    while ((func_evals < maxfun) && (itercount < maxiter)) {\n\n        for (int i = 0;i < n;i++) {\n            tempX1(i) = abs(fv[0] - fv[i+1]);\n        }\n\n        temp1 = tempX1.maxCoeff();\n\n        tempX2 = Eigen::MatrixXd::Zero(n,n);\n\n        for(int i = 0;i < n;i++) {\n            tempX2.col(i) = v.col(i+1) -  v.col(0);\n        }\n\n        tempX2 = tempX2.array().abs();\n\n        temp2 = tempX2.maxCoeff();\n\n        if((temp1 <= tolf) && (temp2 <= tolx)) {\n            break;\n        }\n\n        xbar = v.block(0,0,n,n).rowwise().sum();\n        xbar /= n;\n\n        xr = (1+rho) * xbar - rho * v.block(0,n,v.rows(),1);\n\n        x = xr.transpose();\n        //std::cout << \"Iteration Count: \" << itercount << \":\" << x << std::endl;\n\n        fxr = dipfitError(x, data, sensors, matProjectors);\n\n        func_evals = func_evals+1;\n\n        if (fxr.error < fv[0]) {\n            // Calculate the expansion point\n            xe = (1 + rho * chi) * xbar - rho * chi * v.col(v.cols()-1);\n            x = xe.transpose();\n            fxe = dipfitError(x, data, sensors, matProjectors);\n            func_evals = func_evals+1;\n\n            if(fxe.error < fxr.error) {\n                v.col(v.cols()-1) = xe;\n                fv[n] = fxe.error;\n                how = \"expand\";\n            } else {\n                v.col(v.cols()-1) = xr;\n                fv[n] = fxr.error;\n                how = \"reflect\";\n            }\n        }\n        else {\n            if(fxr.error < fv[n-1]) {\n                v.col(v.cols()-1) = xr;\n                fv[n] = fxr.error;\n                how = \"reflect\";\n            } else { // fxr.error >= fv[:,n-1]\n                // Perform contraction\n                if(fxr.error < fv[n]) {\n                    // Perform an outside contraction\n                    xc = (1 + psi * rho) * xbar - psi * rho * v.col(v.cols()-1);\n                    x = xc.transpose();\n                    fxc = dipfitError(x, data, sensors, matProjectors);\n                    func_evals = func_evals + 1;\n\n                    if(fxc.error <= fxr.error) {\n                        v.col(v.cols()-1) = xc;\n                        fv[n] = fxc.error;\n                        how = \"contract outside\";\n                    } else {\n                        // perform a shrink\n                        how = \"shrink\";\n                    }\n                } else {\n                    xcc = (1 - psi) * xbar + psi * v.col(v.cols()-1);\n                    x = xcc.transpose();\n                    fxcc = dipfitError(x, data, sensors, matProjectors);\n                    func_evals = func_evals+1;\n                    if(fxcc.error < fv[n]) {\n                        v.col(v.cols()-1) = xcc;\n                        fv[n] = fxcc.error;\n                        how = \"contract inside\";\n                    } else {\n                        // perform a shrink\n                        how = \"shrink\";\n                    }\n                }\n\n                if(how.compare(\"shrink\") == 0) {\n                    for(int j = 1;j < n+1;j++) {\n                        v.col(j).array() = v.col(0).array() + sigma * (v.col(j).array() - v.col(0).array());\n                        x = v.col(j).array().transpose();\n                        tempdip = dipfitError(x,data, sensors, matProjectors);\n                        fv[j] = tempdip.error;\n                    }\n                }\n            }\n        }\n\n        // Sort elements of fv\n        vecSortStruct.clear();\n\n        for (int i = 0; i < fv.size(); i++) {\n            HPISortStruct structTemp;\n            structTemp.base_arr = fv[i];\n            structTemp.idx = i;\n            vecSortStruct.push_back(structTemp);\n        }\n\n        sort (vecSortStruct.begin(), vecSortStruct.end(), compare);\n\n        for (int i = 0; i < vecSortStruct.size(); i++) {\n            idx[i] = vecSortStruct[i].idx;\n        }\n\n        for (int i = 0;i < n+1;i++) {\n            v1.col(i) = v.col(idx[i]);\n            fv1[i] = fv[idx[i]];\n        }\n\n        v = v1;\n        fv = fv1;\n        itercount = itercount + 1;\n    }\n\n    x = v.col(0).transpose();\n\n    // Seok\n    simplex_numitr = itercount;\n\n    return x;\n}\n\n\n/*********************************************************************************\n * dipfit function is adapted from Fieldtrip Software. It has been\n * heavily edited for use with MNE Scan Software\n *********************************************************************************/\n\nvoid doDipfitConcurrent(FittingCoilData& lCoilData)\n{\n    // Initialize variables\n    Eigen::RowVectorXd currentCoil = lCoilData.coilPos;\n    Eigen::VectorXd currentData = lCoilData.sensorData;\n    SensorInfo currentSensors = lCoilData.sensorPos;\n\n    int display = 0;\n    int maxiter = 500;\n    int simplex_numitr = 0;\n\n    lCoilData.coilPos = fminsearch(currentCoil,\n                                       maxiter,\n                                       2 * maxiter * currentCoil.cols(),\n                                       display,\n                                       currentData,\n                                       lCoilData.matProjector,\n                                       currentSensors,\n                                       simplex_numitr);\n\n    lCoilData.errorInfo = dipfitError(currentCoil, currentData, currentSensors, lCoilData.matProjector);\n    lCoilData.errorInfo.numIterations = simplex_numitr;\n}\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nHPIFit::HPIFit()\n{\n\n}\n\n\n//*************************************************************************************************************\n\nvoid HPIFit::fitHPI(const MatrixXd& t_mat,\n                        const Eigen::MatrixXd& t_matProjectors,\n                        FiffCoordTrans& transDevHead,\n                        const QVector<int>& vFreqs,\n                        QVector<double>& vGof,\n                        FiffDigPointSet& fittedPointSet,\n                        FiffInfo::SPtr pFiffInfo,\n                        bool bDoDebug,\n                        const QString& sHPIResourceDir)\n{\n    //Check if data was passed\n    if(t_mat.rows() == 0 || t_mat.cols() == 0 ) {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - No data passed. Returning.\";\n    }\n\n    //Check if projector was passed\n    if(t_matProjectors.rows() == 0 || t_matProjectors.cols() == 0 ) {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - No projector passed. Returning.\";\n    }\n\n    vGof.clear();\n\n    struct SensorInfo sensors;\n    struct CoilParam coil;\n    int numCh = pFiffInfo->nchan;\n    int samF = pFiffInfo->sfreq;\n    int samLoc = t_mat.cols(); // minimum samples required to localize numLoc times in a second\n\n    //Get HPI coils from digitizers and set number of coils\n    int numCoils = 0;\n    QList<FiffDigPoint> lHPIPoints;\n\n    for(int i = 0; i < pFiffInfo->dig.size(); ++i) {\n        if(pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) {\n            numCoils++;\n            lHPIPoints.append(pFiffInfo->dig[i]);\n        }\n    }\n\n    //Set coil frequencies\n    Eigen::VectorXd coilfreq(numCoils);\n\n    if(vFreqs.size() >= numCoils) {\n        for(int i = 0; i < numCoils; ++i) {\n            coilfreq[i] = vFreqs.at(i);\n            //std::cout<<std::endl << coilfreq[i] << \"Hz\";\n        }\n    } else {\n        std::cout<<std::endl<< \"HPIFit::fitHPI - Not enough coil frequencies specified. Returning.\";\n        return;\n    }\n\n    // Initialize HPI coils location and moment\n    coil.pos = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.mom = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.dpfiterror = Eigen::VectorXd::Zero(numCoils);\n    coil.dpfitnumitr = Eigen::VectorXd::Zero(numCoils);\n\n    // Generate simulated data\n    Eigen::MatrixXd simsig(samLoc,numCoils*2);\n    Eigen::VectorXd time(samLoc);\n\n    for (int i = 0; i < samLoc; ++i) {\n        time[i] = i*1.0/samF;\n    }\n\n    for(int i = 0; i < numCoils; ++i) {\n        for(int j = 0; j < samLoc; ++j) {\n            simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]);\n            simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]);\n        }\n    }\n\n    // Create digitized HPI coil position matrix\n    Eigen::MatrixXd headHPI(numCoils,3);\n\n    // check the pFiffInfo->dig information. If dig is empty, set the headHPI is 0;\n    if (lHPIPoints.size() > 0) {\n        for (int i = 0; i < lHPIPoints.size(); ++i) {\n            headHPI(i,0) = lHPIPoints.at(i).r[0];\n            headHPI(i,1) = lHPIPoints.at(i).r[1];\n            headHPI(i,2) = lHPIPoints.at(i).r[2];\n        }\n    } else {\n        for (int i = 0; i < numCoils; ++i) {\n            headHPI(i,0) = 0;\n            headHPI(i,1) = 0;\n            headHPI(i,2) = 0;\n        }\n    }\n\n    // Get the indices of inner layer channels and exclude bad channels.\n    //TODO: Only supports babymeg and vectorview gradiometeres for hpi fitting.\n    QVector<int> innerind(0);\n\n    for (int i = 0; i < numCh; ++i) {\n        if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG ||\n                pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 ||\n                pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 ||\n                pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) {\n            // Check if the sensor is bad, if not append to innerind\n            if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) {\n                innerind.append(i);\n            }\n        }\n    }\n\n    //Create new projector based on the excluded channels, first exclude the rows then the columns\n    MatrixXd matProjectorsRows(innerind.size(),t_matProjectors.cols());\n    MatrixXd matProjectorsInnerind(innerind.size(),innerind.size());\n\n    for (int i = 0; i < matProjectorsRows.rows(); ++i) {\n        matProjectorsRows.row(i) = t_matProjectors.row(innerind.at(i));\n    }\n\n    for (int i = 0; i < matProjectorsInnerind.cols(); ++i) {\n        matProjectorsInnerind.col(i) = matProjectorsRows.col(innerind.at(i));\n    }\n\n    //UTILSLIB::IOUtils::write_eigen_matrix(matProjectorsInnerind, \"matProjectorsInnerind.txt\");\n    //UTILSLIB::IOUtils::write_eigen_matrix(t_matProjectors, \"t_matProjectors.txt\");\n\n    // Initialize inner layer sensors\n    sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size());\n\n    for(int i = 0; i < innerind.size(); i++) {\n        sensors.coilpos(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.r0[0];\n        sensors.coilpos(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.r0[1];\n        sensors.coilpos(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.r0[2];\n        sensors.coilori(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.ez[0];\n        sensors.coilori(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.ez[1];\n        sensors.coilori(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.ez[2];\n    }\n\n    Eigen::MatrixXd topo(innerind.size(), numCoils*2);\n    Eigen::MatrixXd amp(innerind.size(), numCoils);\n    Eigen::MatrixXd ampC(innerind.size(), numCoils);\n\n    // Get the data from inner layer channels\n    Eigen::MatrixXd innerdata(innerind.size(), t_mat.cols());\n\n    for(int j = 0; j < innerind.size(); ++j) {\n        innerdata.row(j) << t_mat.row(innerind[j]);\n    }\n\n    // Calculate topo\n    topo = innerdata * pinv(simsig).transpose(); // topo: # of good inner channel x 8\n\n    // Select sine or cosine component depending on the relative size\n    amp  = topo.leftCols(numCoils); // amp: # of good inner channel x 4\n    ampC = topo.rightCols(numCoils);\n\n    for(int j = 0; j < numCoils; ++j) {\n       float nS = 0.0;\n       float nC = 0.0;\n       for(int i = 0; i < innerind.size(); ++i) {\n           nS += amp(i,j)*amp(i,j);\n           nC += ampC(i,j)*ampC(i,j);\n       }\n\n       if(nC > nS) {\n         for(int i = 0; i < innerind.size(); ++i) {\n           amp(i,j) = ampC(i,j);\n         }\n       }\n    }\n\n    //Find good seed point/starting point for the coil position in 3D space\n    //Find biggest amplitude per pickup coil (sensor) and store corresponding sensor channel index\n    VectorXi chIdcs(numCoils);\n\n    for (int j = 0; j < numCoils; j++) {\n        double maxVal = 0;\n        int chIdx = 0;\n\n        for (int i = 0; i < amp.rows(); ++i) {\n            if(abs(amp(i,j)) > maxVal) {\n                maxVal = abs(amp(i,j));\n\n                if(chIdx < innerind.size()) {\n                    chIdx = innerind.at(i);\n                }\n            }\n        }\n\n        chIdcs(j) = chIdx;\n    }\n\n    //Generate seed point by projection the found channel position 3cm inwards\n    Eigen::MatrixXd coilPos = Eigen::MatrixXd::Zero(numCoils,3);\n\n    for (int j = 0; j < chIdcs.rows(); ++j) {\n        int chIdx = chIdcs(j);\n\n        if(chIdx < pFiffInfo->chs.size()) {\n            double x = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[0];\n            double y = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[1];\n            double z = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[2];\n\n            coilPos(j,0) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[0] * 0.03 + x;\n            coilPos(j,1) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[1] * 0.03 + y;\n            coilPos(j,2) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[2] * 0.03 + z;\n        }\n\n        //std::cout << \"HPIFit::fitHPI - Coil \" << j << \" max value index \" << chIdx << std::endl;\n    }\n\n    coil.pos = coilPos;\n\n    coil = dipfit(coil, sensors, amp, numCoils, matProjectorsInnerind);\n\n    Eigen::Matrix4d trans = computeTransformation(headHPI, coil.pos);\n    //Eigen::Matrix4d trans = computeTransformation(coil.pos, headHPI);\n\n    // Store the final result to fiff info\n    // Set final device/head matrix and its inverse to the fiff info\n    transDevHead.from = 1;\n    transDevHead.to = 4;\n\n    for(int r = 0; r < 4; ++r) {\n        for(int c = 0; c < 4 ; ++c) {\n            transDevHead.trans(r,c) = trans(r,c);\n        }\n    }\n\n    // Also store the inverse\n    transDevHead.invtrans = transDevHead.trans.inverse();\n\n    //Calculate GOF\n    MatrixXd temp = coil.pos;\n    temp.conservativeResize(coil.pos.rows(),coil.pos.cols()+1);\n\n    temp.block(0,3,numCoils,1).setOnes();\n    temp.transposeInPlace();\n\n    MatrixXd testPos = trans * temp;\n    MatrixXd diffPos = testPos.block(0,0,3,numCoils) - headHPI.transpose();\n\n    for(int i = 0; i < diffPos.cols(); ++i) {\n        vGof.append(diffPos.col(i).norm());\n    }\n\n    //Generate final fitted points and store in digitizer set\n    for(int i = 0; i < coil.pos.rows(); ++i) {\n        FiffDigPoint digPoint;\n        digPoint.kind = FIFFV_POINT_EEG;\n        digPoint.ident = i;\n        digPoint.r[0] = coil.pos(i,0);\n        digPoint.r[1] = coil.pos(i,1);\n        digPoint.r[2] = coil.pos(i,2);\n\n        fittedPointSet << digPoint;\n    }\n\n    if(bDoDebug) {\n        // DEBUG HPI fitting and write debug results\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - dpfiterror\" << coil.dpfiterror << std::endl << coil.pos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - Initial seed point for HPI coils\" << std::endl << coil.pos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - temp\" << std::endl << temp << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - testPos\" << std::endl << testPos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - Diff fitted - original\" << std::endl << diffPos << std::endl;\n        std::cout << std::endl << std::endl << \"HPIFit::fitHPI - dev/head trans\" << std::endl << trans << std::endl;\n\n        QString sTimeStamp = QDateTime::currentDateTime().toString(\"yyMMdd_hhmmss\");\n\n        if(!QDir(sHPIResourceDir).exists()) {\n            QDir().mkdir(sHPIResourceDir);\n        }\n\n        UTILSLIB::IOUtils::write_eigen_matrix(coilPos, QString(\"%1/%2_coilPosSeed_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(coil.pos, QString(\"%1/%2_coilPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(headHPI, QString(\"%1/%2_headHPI_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXd testPosCut = testPos.transpose();//block(0,0,3,4);\n        UTILSLIB::IOUtils::write_eigen_matrix(testPosCut, QString(\"%1/%2_testPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXi idx_mat(chIdcs.rows(),1);\n        idx_mat.col(0) = chIdcs;\n        UTILSLIB::IOUtils::write_eigen_matrix(idx_mat, QString(\"%1/%2_idx_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        MatrixXd coilFreq_mat(coilfreq.rows(),1);\n        coilFreq_mat.col(0) = coilfreq;\n        UTILSLIB::IOUtils::write_eigen_matrix(coilFreq_mat, QString(\"%1/%2_coilFreq_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(diffPos, QString(\"%1/%2_diffPos_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n\n        UTILSLIB::IOUtils::write_eigen_matrix(amp, QString(\"%1/%2_amp_mat\").arg(sHPIResourceDir).arg(sTimeStamp));\n    }\n}\n\n\n//*************************************************************************************************************\n\nCoilParam HPIFit::dipfit(struct CoilParam coil, struct SensorInfo sensors, const Eigen::MatrixXd& data, int numCoils, const Eigen::MatrixXd& t_matProjectors)\n{\n    //Do this in conncurrent mode\n    //Generate QList structure which can be handled by the QConcurrent framework\n    QList<FittingCoilData> lCoilData;\n\n    for(qint32 i = 0; i < numCoils; ++i) {\n        FittingCoilData coilData;\n        coilData.coilPos = coil.pos.row(i);\n        coilData.sensorData = data.col(i);\n        coilData.sensorPos = sensors;\n        coilData.matProjector = t_matProjectors;\n\n        lCoilData.append(coilData);\n    }\n    //Do the concurrent filtering\n    if(!lCoilData.isEmpty()) {\n        //Do sequential\n        for(int l = 0; l < lCoilData.size(); ++l) {\n            doDipfitConcurrent(lCoilData[l]);\n        }\n\n//        //Do concurrent\n//        QFuture<void> future = QtConcurrent::map(lCoilData,\n//                                             doDipfitConcurrent);\n//        future.waitForFinished();\n\n        //Transform results to final coil information\n        for(qint32 i = 0; i < lCoilData.size(); ++i) {\n            coil.pos.row(i) = lCoilData.at(i).coilPos;\n            coil.mom = lCoilData.at(i).errorInfo.moment.transpose();\n            coil.dpfiterror(i) = lCoilData.at(i).errorInfo.error;\n            coil.dpfitnumitr(i) = lCoilData.at(i).errorInfo.numIterations;\n\n            //std::cout<<std::endl<< \"HPIFit::dipfit - Itr steps for coil \" << i << \" =\" <<coil.dpfitnumitr(i);\n        }\n    }\n\n    return coil;\n}\n\n\n//*************************************************************************************************************\n\nEigen::Matrix4d HPIFit::computeTransformation(Eigen::MatrixXd NH, Eigen::MatrixXd BT)\n{\n    Eigen::MatrixXd xdiff, ydiff, zdiff, C, Q;\n    Eigen::Matrix4d transFinal = Eigen::Matrix4d::Identity(4,4);\n    Eigen::Matrix4d Rot = Eigen::Matrix4d::Zero(4,4);\n    Eigen::Matrix4d Trans = Eigen::Matrix4d::Identity(4,4);\n    double meanx,meany,meanz,normf;\n\n    for(int i = 0; i < 15; ++i) {\n        // Calcualte mean translation for all points -> centroid of both data sets\n        xdiff = NH.col(0) - BT.col(0);\n        ydiff = NH.col(1) - BT.col(1);\n        zdiff = NH.col(2) - BT.col(2);\n\n        meanx = xdiff.mean();\n        meany = ydiff.mean();\n        meanz = zdiff.mean();\n\n        // Apply translation -> bring both data sets to the same center location\n        for (int j = 0; j < BT.rows(); ++j) {\n            BT(j,0) = BT(j,0) + meanx;\n            BT(j,1) = BT(j,1) + meany;\n            BT(j,2) = BT(j,2) + meanz;\n        }\n\n        // Estimate rotation component\n        C = BT.transpose() * NH;\n\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd(C ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n        Q = svd.matrixU() * svd.matrixV().transpose();\n\n        //Handle special reflection case\n        if(Q.determinant() < 0) {\n            Q(0,2) = Q(0,2) * -1;\n            Q(1,2) = Q(1,2) * -1;\n            Q(2,2) = Q(2,2) * -1;\n        }\n\n        // Apply rotation on translated points\n        BT = BT * Q;\n\n        // Calculate GOF\n        normf = (NH.transpose()-BT.transpose()).norm();\n\n        // Store rotation part to transformation matrix\n        Rot(3,3) = 1;\n        for(int j = 0; j < 3; ++j) {\n            for(int k = 0; k < 3; ++k) {\n                Rot(j,k) = Q(k,j);\n            }\n        }\n\n        // Store translation part to transformation matrix\n        Trans(0,3) = meanx;\n        Trans(1,3) = meany;\n        Trans(2,3) = meanz;\n\n        // Safe rotation and translation to final matrix for next iteration step\n        transFinal = Rot * Trans * transFinal;\n    }\n\n    return transFinal;\n}\n", "meta": {"hexsha": "70f7688501a0a51d243ec19077826b0657a1e230", "size": 32725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/inverse/hpiFit/hpifit.cpp", "max_stars_repo_name": "13grife37/mne-cpp-swpold", "max_stars_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T20:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-26T16:30:25.000Z", "max_issues_repo_path": "MNE/inverse/hpiFit/hpifit.cpp", "max_issues_repo_name": "13grife37/mne-cpp-swpold", "max_issues_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/inverse/hpiFit/hpifit.cpp", "max_forks_repo_name": "13grife37/mne-cpp-swpold", "max_forks_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T15:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-23T15:55:31.000Z", "avg_line_length": 35.7650273224, "max_line_length": 173, "alphanum_fraction": 0.5072880061, "num_tokens": 8388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339458, "lm_q2_score": 0.016152836657403625, "lm_q1q2_score": 0.005631607922447607}}
{"text": "#pragma once\n\n#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <common_robotics_utilities/maybe.hpp>\n#include <common_robotics_utilities/serialization.hpp>\n#include <common_robotics_utilities/voxel_grid.hpp>\n#include <common_robotics_utilities/zlib_helpers.hpp>\n\nnamespace voxelized_geometry_tools\n{\n/// Using declaration to make naming clearer and easier to read.\nusing EstimateDistanceQuery = common_robotics_utilities::OwningMaybe<double>;\n\n/// This is similar to std::optional<Eigen::Vector4d>, but lets us enforce\n/// specific behavior in the contained Vector4d.\nclass GradientQuery\n{\nprivate:\n  Eigen::Vector4d gradient_ = Eigen::Vector4d(0.0, 0.0, 0.0, 0.0);\n  bool has_value_ = false;\n\npublic:\n  explicit GradientQuery(const Eigen::Vector4d& gradient)\n      : gradient_(gradient), has_value_(true)\n  {\n    if (gradient_(3) != 0.0)\n    {\n      throw std::invalid_argument(\"gradient(3) != 0.0\");\n    }\n  }\n\n  GradientQuery(const double x, const double y, const double z)\n      : gradient_(Eigen::Vector4d(x, y, z, 0.0)), has_value_(true) {}\n\n  GradientQuery() : has_value_(false) {}\n\n  const Eigen::Vector4d& Value() const\n  {\n    if (HasValue())\n    {\n      return gradient_;\n    }\n    else\n    {\n      throw std::runtime_error(\"GradientQuery does not have value\");\n    }\n  }\n\n  bool HasValue() const { return has_value_; }\n\n  explicit operator bool() const { return HasValue(); }\n};\n\n/// This is equivalent to std::optional<Eigen::Vector4d>, but kept separate here\n/// so as to not require C++17 support with a working std::optional<T>. This\n/// also allows us to enforce specific behavior in the contained Vector4d.\nclass ProjectedPosition\n{\nprivate:\n  const Eigen::Vector4d gradient_ = Eigen::Vector4d(0.0, 0.0, 0.0, 1.0);\n  const bool has_value_ = false;\n\npublic:\n  explicit ProjectedPosition(const Eigen::Vector4d& gradient)\n      : gradient_(gradient), has_value_(true)\n  {\n    if (gradient_(3) != 1.0)\n    {\n      throw std::invalid_argument(\"gradient(3) != 1.0\");\n    }\n  }\n\n  ProjectedPosition(const double x, const double y, const double z)\n      : gradient_(Eigen::Vector4d(x, y, z, 1.0)), has_value_(true) {}\n\n  ProjectedPosition() : has_value_(false) {}\n\n  const Eigen::Vector4d& Value() const\n  {\n    if (HasValue())\n    {\n      return gradient_;\n    }\n    else\n    {\n      throw std::runtime_error(\"ProjectedPosition does not have value\");\n    }\n  }\n\n  bool HasValue() const { return has_value_; }\n\n  explicit operator bool() const { return HasValue(); }\n};\n\ntemplate<typename ScalarType>\nclass SignedDistanceField final\n    : public common_robotics_utilities::voxel_grid\n        ::VoxelGridBase<ScalarType, std::vector<ScalarType>>\n{\nprivate:\n  using ScalarTypeSerializer\n      = common_robotics_utilities::serialization::Serializer<ScalarType>;\n  using ScalarTypeDeserializer\n      = common_robotics_utilities::serialization::Deserializer<ScalarType>;\n  using DeserializedSignedDistanceField\n      = common_robotics_utilities::serialization\n          ::Deserialized<SignedDistanceField<ScalarType>>;\n\n  std::string frame_;\n  bool locked_ = false;\n\n  /// Internal helper used in \"Fine\" gradient computation.\n  inline double ComputeAxisFineGradient(\n      const EstimateDistanceQuery& query_point_distance_estimate,\n      const EstimateDistanceQuery& minus_axis_distance_estimate,\n      const EstimateDistanceQuery& 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.HasValue()\n        && minus_axis_distance_estimate.HasValue()\n        && plus_axis_distance_estimate.HasValue())\n    {\n      const double window_size = plus_point_axis_value\n                                 - minus_point_axis_value;\n      const double distance_delta = plus_axis_distance_estimate.Value()\n                                    - minus_axis_distance_estimate.Value();\n      return distance_delta / window_size;\n    }\n    else if (query_point_distance_estimate.HasValue()\n             && minus_axis_distance_estimate.HasValue())\n    {\n      const double window_size = query_point_axis_value\n                                 - minus_point_axis_value;\n      const double distance_delta = query_point_distance_estimate.Value()\n                                    - minus_axis_distance_estimate.Value();\n      return distance_delta / window_size;\n    }\n    else if (query_point_distance_estimate.HasValue()\n             && plus_axis_distance_estimate.HasValue())\n    {\n      const double window_size = plus_point_axis_value\n                                 - query_point_axis_value;\n      const double distance_delta = plus_axis_distance_estimate.Value()\n                                    - query_point_distance_estimate.Value();\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  /// Bilinear interpolation used in trilinear interpolation.\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  /// Wrapper around bilinear interpolation to set arguments more easily.\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  /// Trilinear distance interpolation.\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  /// Computes \"corrected\" center distance accounting for the fact that SDF\n  /// distance is the distance to the next filled cell center, *not* the\n  /// distance to the boundary.\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 auto query = this->GetImmutable(x_idx, y_idx, z_idx);\n    if (query)\n    {\n      const double nominal_sdf_distance = static_cast<double>(query.Value());\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  /// Computes the axis lookup indices to use for interpolation.\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  /// Estimates distance via trilinear interpolation of the surrounding 8 cells.\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        = this->GetInverseOriginTransform() * query_location;\n    // Switch between all the possible options of where we are\n    const Eigen::Vector4d cell_center_location\n        = this->GridIndexToLocationInGridFrame(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    // We can't catch the easiest case of being at a cell center, since doing so\n    // breaks the ability of Eigen's Autodiff to autodiff this function.\n    // Find the best-matching 8 surrounding cell centers\n    const std::pair<int64_t, int64_t> x_axis_indices\n        = GetAxisInterpolationIndices(\n            x_idx, this->GetNumXCells(), query_offset(0));\n    const std::pair<int64_t, int64_t> y_axis_indices\n        = GetAxisInterpolationIndices(\n            y_idx, this->GetNumYCells(), query_offset(1));\n    const std::pair<int64_t, int64_t> z_axis_indices\n        = GetAxisInterpolationIndices(\n            z_idx, this->GetNumZCells(), query_offset(2));\n    const Eigen::Vector4d lower_corner_location\n        = this->GridIndexToLocationInGridFrame(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\n  /// You *must* provide valid indices to this function, hence why it's private.\n  void FollowGradientsToLocalExtremaUnsafe(\n      const int64_t x_index, const int64_t y_index, const int64_t z_index,\n      common_robotics_utilities::voxel_grid::VoxelGrid<Eigen::Vector3d>&\n          watershed_map) const\n  {\n    // First, check if we've already found the local extrema for the current\n    // cell\n    const Eigen::Vector3d& stored\n        = watershed_map.GetImmutable(x_index, y_index, z_index).Value();\n    if (stored.x() != -std::numeric_limits<double>::infinity()\n        && stored.y() != -std::numeric_limits<double>::infinity()\n        && stored.z() != -std::numeric_limits<double>::infinity())\n    {\n      // We've already found it for this cell, so we can skip it\n      return;\n    }\n    // Find the local extrema\n    GradientQuery raw_gradient\n        = GetCoarseGradient(x_index, y_index, z_index, true);\n    Eigen::Vector4d gradient_vector = raw_gradient.Value();\n    if (GradientIsEffectiveFlat(gradient_vector))\n    {\n      const Eigen::Vector4d location\n          = this->GridIndexToLocationInGridFrame(x_index, y_index, z_index);\n      const Eigen::Vector3d local_extrema(\n          location(0), location(1), location(2));\n      watershed_map.SetValue(x_index, y_index, z_index, local_extrema);\n    }\n    else\n    {\n      // Follow the gradient, one cell at a time, until we reach a local maxima\n      std::unordered_map<common_robotics_utilities::voxel_grid::GridIndex,\n                         int8_t> path;\n      common_robotics_utilities::voxel_grid::GridIndex current_index(\n            x_index, y_index, z_index);\n      path[current_index] = 1;\n      Eigen::Vector3d local_extrema(-std::numeric_limits<double>::infinity(),\n                                    -std::numeric_limits<double>::infinity(),\n                                    -std::numeric_limits<double>::infinity());\n      while (true)\n      {\n        if (path.size() == 10000)\n        {\n          std::cerr << \"Warning, gradient path is long (i.e >= 10000 steps)\"\n                    << std::endl;\n        }\n        current_index = GetNextFromGradient(current_index, gradient_vector);\n        if (path[current_index] != 0)\n        {\n          // If we've already been here, then we are done\n          const Eigen::Vector4d location\n              = this->GridIndexToLocationInGridFrame(current_index);\n          local_extrema\n              = Eigen::Vector3d(location(0), location(1), location(2));\n          break;\n        }\n        // Check if we've been pushed past the edge\n        if (!this->IndexInBounds(current_index))\n        {\n          // We have the \"off the grid\" local maxima\n          local_extrema\n              = Eigen::Vector3d(std::numeric_limits<double>::infinity(),\n                                std::numeric_limits<double>::infinity(),\n                                std::numeric_limits<double>::infinity());\n          break;\n        }\n        path[current_index] = 1;\n        // Check if the new index has already been checked\n        const Eigen::Vector3d& new_stored\n            = watershed_map.GetImmutable(current_index).Value();\n        if (new_stored.x() != -std::numeric_limits<double>::infinity()\n            && new_stored.y() != -std::numeric_limits<double>::infinity()\n            && new_stored.z() != -std::numeric_limits<double>::infinity())\n        {\n          // We have the local maxima\n          local_extrema = new_stored;\n          break;\n        }\n        else\n        {\n          raw_gradient = GetCoarseGradient(current_index, true);\n          gradient_vector = raw_gradient.Value();\n          if (GradientIsEffectiveFlat(gradient_vector))\n          {\n            // We have the local maxima\n            const Eigen::Vector4d location\n                = this->GridIndexToLocationInGridFrame(current_index);\n            local_extrema\n                = Eigen::Vector3d(location(0), location(1), location(2));\n            break;\n          }\n        }\n      }\n      // Now, go back and mark the entire explored path with the local maxima\n      for (auto path_itr = path.begin(); path_itr != path.end(); ++path_itr)\n      {\n        const common_robotics_utilities::voxel_grid::GridIndex& index\n            = path_itr->first;\n        watershed_map.SetValue(index, local_extrema);\n      }\n    }\n  }\n\n  bool GradientIsEffectiveFlat(const Eigen::Vector4d& gradient) const\n  {\n    // A gradient is at a local maxima if the absolute value of all components\n    // (x,y,z) are less than 1/2 SDF resolution\n    const double step_resolution = GetResolution() * 0.06125;\n    if (std::abs(gradient(0)) <= step_resolution\n        && std::abs(gradient(1)) <= step_resolution\n        && std::abs(gradient(2)) <= step_resolution)\n    {\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  common_robotics_utilities::voxel_grid::GridIndex GetNextFromGradient(\n      const common_robotics_utilities::voxel_grid::GridIndex& index,\n      const Eigen::Vector4d& gradient) const\n  {\n    // Check if it's inside an obstacle\n    const ScalarType stored_distance = this->GetImmutable(index).Value();\n    Eigen::Vector4d working_gradient = gradient;\n    if (stored_distance < 0.0)\n    {\n      working_gradient = gradient * -1.0;\n    }\n    // Given the gradient, pick the \"best fit\" of the 26 neighboring points\n    common_robotics_utilities::voxel_grid::GridIndex next_index = index;\n    const double step_resolution = GetResolution() * 0.06125;\n    if (working_gradient(0) > step_resolution)\n    {\n      next_index.X() += 1;\n    }\n    else if (working_gradient(0) < -step_resolution)\n    {\n      next_index.X() -= 1;\n    }\n    if (working_gradient(1) > step_resolution)\n    {\n      next_index.Y() += 1;\n    }\n    else if (working_gradient(1) < -step_resolution)\n    {\n      next_index.Y() -= 1;\n    }\n    if (working_gradient(2) > step_resolution)\n    {\n      next_index.Z() += 1;\n    }\n    else if (working_gradient(2) < -step_resolution)\n    {\n      next_index.Z() -= 1;\n    }\n    return next_index;\n  }\n\n  /// Implement the VoxelGridBase interface.\n\n  /// We need to implement cloning.\n  std::unique_ptr<common_robotics_utilities::voxel_grid\n      ::VoxelGridBase<ScalarType, std::vector<ScalarType>>>\n  DoClone() const override\n  {\n    return std::unique_ptr<SignedDistanceField<ScalarType>>(\n        new SignedDistanceField<ScalarType>(*this));\n  }\n\n  /// We need to serialize the frame and locked flag.\n  uint64_t DerivedSerializeSelf(\n      std::vector<uint8_t>& buffer,\n      const ScalarTypeSerializer& value_serializer) const override\n  {\n    CRU_UNUSED(value_serializer);\n    const uint64_t start_size = buffer.size();\n    common_robotics_utilities::serialization::SerializeString(frame_, buffer);\n    common_robotics_utilities::serialization::SerializeMemcpyable<uint8_t>(\n        static_cast<uint8_t>(locked_), buffer);\n    const uint64_t bytes_written = buffer.size() - start_size;\n    return bytes_written;\n  }\n\n  /// We need to deserialize the frame and locked flag.\n  uint64_t DerivedDeserializeSelf(\n      const std::vector<uint8_t>& buffer, const uint64_t starting_offset,\n      const ScalarTypeDeserializer& value_deserializer) override\n  {\n    CRU_UNUSED(value_deserializer);\n    uint64_t current_position = starting_offset;\n    // Deserialize SDF stuff\n    const auto frame_deserialized\n        = common_robotics_utilities::serialization::DeserializeString<char>(\n            buffer, current_position);\n    frame_ = frame_deserialized.Value();\n    current_position += frame_deserialized.BytesRead();\n    const auto locked_deserialized\n        = common_robotics_utilities::serialization\n            ::DeserializeMemcpyable<uint8_t>(buffer, current_position);\n    locked_ = static_cast<bool>(locked_deserialized.Value());\n    current_position += locked_deserialized.BytesRead();\n    // Figure out how many bytes were read\n    const uint64_t bytes_read = current_position - starting_offset;\n    return bytes_read;\n  }\n\n  /// We do not allow mutable access if the SDF is locked.\n  bool OnMutableAccess(const int64_t x_index,\n                       const int64_t y_index,\n                       const int64_t z_index) override\n  {\n    CRU_UNUSED(x_index);\n    CRU_UNUSED(y_index);\n    CRU_UNUSED(z_index);\n    return !IsLocked();\n  }\n\npublic:\n  static uint64_t Serialize(\n      const SignedDistanceField<ScalarType>& sdf, std::vector<uint8_t>& buffer)\n  {\n    return sdf.SerializeSelf(\n        buffer,\n        common_robotics_utilities::serialization\n            ::SerializeMemcpyable<ScalarType>);\n  }\n\n  static DeserializedSignedDistanceField Deserialize(\n      const std::vector<uint8_t>& buffer, const uint64_t starting_offset)\n  {\n    SignedDistanceField<ScalarType> temp_sdf;\n    const uint64_t bytes_read = temp_sdf.DeserializeSelf(\n        buffer, starting_offset,\n        common_robotics_utilities::serialization\n            ::DeserializeMemcpyable<ScalarType>);\n    return common_robotics_utilities::serialization::MakeDeserialized(\n        temp_sdf, bytes_read);\n  }\n\n  static void SaveToFile(\n      const SignedDistanceField<ScalarType>& sdf, const std::string& filepath,\n      const bool compress)\n  {\n    std::vector<uint8_t> buffer;\n    SignedDistanceField<ScalarType>::Serialize(sdf, buffer);\n    std::ofstream output_file(filepath, std::ios::out|std::ios::binary);\n    if (compress)\n    {\n      output_file.write(\"SDFZ\", 4);\n      const std::vector<uint8_t> compressed\n          = common_robotics_utilities::zlib_helpers::CompressBytes(buffer);\n      const size_t serialized_size = compressed.size();\n      output_file.write(\n          reinterpret_cast<const char*>(compressed.data()),\n          static_cast<std::streamsize>(serialized_size));\n    }\n    else\n    {\n      output_file.write(\"SDFR\", 4);\n      const size_t serialized_size = buffer.size();\n      output_file.write(\n          reinterpret_cast<const char*>(buffer.data()),\n          static_cast<std::streamsize>(serialized_size));\n    }\n    output_file.close();\n  }\n\n  static SignedDistanceField<ScalarType> LoadFromFile(\n      const std::string& filepath)\n  {\n    std::ifstream input_file(\n        filepath, std::ios::in | std::ios::binary | std::ios::ate);\n    if (input_file.good() == false)\n    {\n      throw std::invalid_argument(\"File does not exist\");\n    }\n    const std::streampos end = input_file.tellg();\n    input_file.seekg(0, std::ios::beg);\n    const std::streampos begin = input_file.tellg();\n    const std::streamsize serialized_size = end - begin;\n    const std::streamsize header_size = 4;\n    if (serialized_size >= header_size)\n    {\n      // Load the header\n      std::vector<uint8_t> file_header(header_size + 1, 0x00);\n      input_file.read(reinterpret_cast<char*>(file_header.data()),\n                      header_size);\n      const std::string header_string(\n            reinterpret_cast<const char*>(file_header.data()));\n      // Load the rest of the file\n      std::vector<uint8_t> file_buffer(\n            static_cast<size_t>(serialized_size - header_size), 0x00);\n      input_file.read(reinterpret_cast<char*>(file_buffer.data()),\n                      serialized_size - header_size);\n      // Deserialize\n      if (header_string == \"SDFZ\")\n      {\n        const std::vector<uint8_t> decompressed\n            = common_robotics_utilities::zlib_helpers\n                ::DecompressBytes(file_buffer);\n        return SignedDistanceField<ScalarType>::Deserialize(\n            decompressed, 0).Value();\n      }\n      else if (header_string == \"SDFR\")\n      {\n        return SignedDistanceField<ScalarType>::Deserialize(\n            file_buffer, 0).Value();\n      }\n      else\n      {\n        throw std::invalid_argument(\n              \"File has invalid header [\" + header_string + \"]\");\n      }\n    }\n    else\n    {\n      throw std::invalid_argument(\"File is too small\");\n    }\n  }\n\n  SignedDistanceField(\n      const Eigen::Isometry3d& origin_transform, const std::string& frame,\n      const common_robotics_utilities::voxel_grid::GridSizes& sizes,\n      const ScalarType default_value)\n      : SignedDistanceField(\n          origin_transform, frame, sizes, default_value, default_value) {}\n\n  SignedDistanceField(\n      const std::string& frame,\n      const common_robotics_utilities::voxel_grid::GridSizes& sizes,\n      const ScalarType default_value)\n      : SignedDistanceField(frame, sizes, default_value, default_value) {}\n\n  SignedDistanceField(\n      const Eigen::Isometry3d& origin_transform, const std::string& frame,\n      const common_robotics_utilities::voxel_grid::GridSizes& sizes,\n      const ScalarType default_value, const ScalarType oob_value)\n      : common_robotics_utilities::voxel_grid\n            ::VoxelGridBase<ScalarType, std::vector<ScalarType>>(\n                origin_transform, sizes, default_value, oob_value),\n        frame_(frame), locked_(false)\n  {\n    if (!this->HasUniformCellSize())\n    {\n      throw std::invalid_argument(\"SDF cannot have non-uniform cell sizes\");\n    }\n  }\n\n  SignedDistanceField(\n      const std::string& frame,\n      const common_robotics_utilities::voxel_grid::GridSizes& sizes,\n      const ScalarType default_value, const ScalarType oob_value)\n      : common_robotics_utilities::voxel_grid\n            ::VoxelGridBase<ScalarType, std::vector<ScalarType>>(\n                sizes, default_value, oob_value),\n        frame_(frame), locked_(false)\n  {\n    if (!this->HasUniformCellSize())\n    {\n      throw std::invalid_argument(\"SDF cannot have non-uniform cell sizes\");\n    }\n  }\n\n  SignedDistanceField()\n      : common_robotics_utilities::voxel_grid\n            ::VoxelGridBase<ScalarType, std::vector<ScalarType>>() {}\n\n  bool IsLocked() const { return locked_; }\n\n  void Lock() { locked_ = true; }\n\n  void Unlock() { locked_ = false; }\n\n  double GetResolution() const { return this->GetCellSizes().x(); }\n\n  const std::string& GetFrame() const { return frame_; }\n\n  void SetFrame(const std::string& frame) { frame_ = frame; }\n\n  /// For classical SDF distance queries, see the API of VoxelGridBase for how\n  /// to retrieve and set cell values.\n\n  /// \"Estimated\" distance is computed by performing trilinear interpolation\n  /// against the distances in eight cells that surround the query point. This\n  /// produces a continuous, but not necessarily smooth distance function that\n  /// is more accurate and smoother than the raw distance values inside cells.\n  /// Note that it is both more expensive than a simple grid lookup, but also\n  /// this rounds inside and outside corners of cells. This can be a problem at\n  /// coarse grid resolutions.\n\n  EstimateDistanceQuery EstimateDistance(\n      const double x, const double y, const double z) const\n  {\n      return EstimateDistance4d(Eigen::Vector4d(x, y, z, 1.0));\n  }\n\n  EstimateDistanceQuery EstimateDistance3d(\n      const Eigen::Vector3d& location) const\n  {\n    const common_robotics_utilities::voxel_grid::GridIndex index\n        = this->LocationToGridIndex3d(location);\n    if (this->IndexInBounds(index))\n    {\n      return EstimateDistanceQuery(\n          EstimateDistanceInterpolateFromNeighbors<double>(\n              Eigen::Vector4d(location.x(), location.y(), location.z(), 1.0),\n              index.X(), index.Y(), index.Z()));\n    }\n    else\n    {\n      return EstimateDistanceQuery();\n    }\n  }\n\n  EstimateDistanceQuery EstimateDistance4d(\n      const Eigen::Vector4d& location) const\n  {\n    const common_robotics_utilities::voxel_grid::GridIndex index\n        = this->LocationToGridIndex4d(location);\n    if (this->IndexInBounds(index))\n    {\n      return EstimateDistanceQuery(\n          EstimateDistanceInterpolateFromNeighbors<double>(\n              location, index.X(), index.Y(), index.Z()));\n    }\n    else\n    {\n      return EstimateDistanceQuery();\n    }\n  }\n\n  /// \"Coarse\" gradient is computed by retrieving the distance from the\n  /// surrounding size cells (+/-x, +/-y, +/-z) and differencing. This is the\n  /// fastest method to compute a gradient, and also has the most potential\n  /// error and least-smooth behavior.\n\n  GradientQuery GetCoarseGradient(\n      const double x, const double y, const double z,\n      const bool enable_edge_gradients=false) const\n  {\n    return GetCoarseGradient4d(\n        Eigen::Vector4d(x, y, z, 1.0), enable_edge_gradients);\n  }\n\n  GradientQuery GetCoarseGradient3d(\n      const Eigen::Vector3d& location,\n      const bool enable_edge_gradients=false) const\n  {\n    const common_robotics_utilities::voxel_grid::GridIndex index\n        = this->LocationToGridIndex3d(location);\n    if (this->IndexInBounds(index))\n    {\n      return GetCoarseGradient(index, enable_edge_gradients);\n    }\n    else\n    {\n      return GradientQuery();\n    }\n  }\n\n  GradientQuery GetCoarseGradient4d(\n      const Eigen::Vector4d& location,\n      const bool enable_edge_gradients=false) const\n  {\n    const common_robotics_utilities::voxel_grid::GridIndex index\n        = this->LocationToGridIndex4d(location);\n    if (this->IndexInBounds(index))\n    {\n      return GetCoarseGradient(index, enable_edge_gradients);\n    }\n    else\n    {\n      return GradientQuery();\n    }\n  }\n\n  GradientQuery GetCoarseGradient(\n      const common_robotics_utilities::voxel_grid::GridIndex& index,\n      const bool enable_edge_gradients=false) const\n  {\n    return GetCoarseGradient(\n        index.X(), index.Y(), index.Z(), enable_edge_gradients);\n  }\n\n  GradientQuery GetCoarseGradient(\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 GradientQuery grid_aligned_gradient\n        = GetGridAlignedCoarseGradient(x_index, y_index, z_index,\n                                       enable_edge_gradients);\n    if (grid_aligned_gradient.HasValue())\n    {\n      const Eigen::Vector4d gradient\n          = this->GetOriginTransform() * grid_aligned_gradient.Value();\n      return GradientQuery(gradient);\n    }\n    else\n    {\n      return grid_aligned_gradient;\n    }\n  }\n\n  GradientQuery GetGridAlignedCoarseGradient(\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 (this->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 < (this->GetNumXCells() - 1))\n          && (y_index < (this->GetNumYCells() - 1))\n          && (z_index < (this->GetNumZCells() - 1)))\n      {\n        const double inv_twice_resolution = 1.0 / (2.0 * GetResolution());\n        const double gx\n            = (this->GetImmutable(x_index + 1, y_index, z_index).Value()\n               - this->GetImmutable(x_index - 1, y_index, z_index).Value())\n              * inv_twice_resolution;\n        const double gy\n            = (this->GetImmutable(x_index, y_index + 1, z_index).Value()\n               - this->GetImmutable(x_index, y_index - 1, z_index).Value())\n              * inv_twice_resolution;\n        const double gz\n            = (this->GetImmutable(x_index, y_index, z_index + 1).Value()\n               - this->GetImmutable(x_index, y_index, z_index - 1).Value())\n              * inv_twice_resolution;\n        return GradientQuery(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\n            = std::max(static_cast<int64_t>(0), x_index - 1);\n        const int64_t high_x_index\n            = std::min(this->GetNumXCells() - 1, x_index + 1);\n        const int64_t low_y_index\n            = std::max(static_cast<int64_t>(0), y_index - 1);\n        const int64_t high_y_index\n            = std::min(this->GetNumYCells() - 1, y_index + 1);\n        const int64_t low_z_index\n            = std::max(static_cast<int64_t>(0), z_index - 1);\n        const int64_t high_z_index\n            = std::min(this->GetNumZCells() - 1, z_index + 1);\n        // Compute the axis increments\n        const double x_increment\n            = static_cast<double>(high_x_index - low_x_index) * GetResolution();\n        const double y_increment\n            = static_cast<double>(high_y_index - low_y_index) * GetResolution();\n        const double z_increment\n            = static_cast<double>(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              = this->GetImmutable(high_x_index, y_index, z_index).Value();\n          const double low_x_value\n              = this->GetImmutable(low_x_index, y_index, z_index).Value();\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              = this->GetImmutable(x_index, high_y_index, z_index).Value();\n          const double low_y_value\n              = this->GetImmutable(x_index, low_y_index, z_index).Value();\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              = this->GetImmutable(x_index, y_index, high_z_index).Value();\n          const double low_z_value\n              = this->GetImmutable(x_index, y_index, low_z_index).Value();\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 GradientQuery(gx, gy, gz);\n      }\n      // Edge gradients disabled, return no gradient\n      else\n      {\n        return GradientQuery();\n      }\n    }\n    // If we're out of bounds, return no gradient\n    else\n    {\n      return GradientQuery();\n    }\n  }\n\n  /// \"Fine\" gradient is also computed by differencing, but instead of using the\n  /// surrounding cells, this uses EstimateDistance() at +/- half of\n  /// \"window size\" to compute the gradient. This is slower than the \"coarse\"\n  /// gradient, since this needs to call EstimateDistance() six times, but\n  /// produces a more accurate and smoother gradient. In the limit as\n  /// \"window size\" -> 0 this produces the true gradient.\n\n  GradientQuery GetFineGradient3d(\n      const Eigen::Vector3d& location,\n      const double nominal_window_size) const\n  {\n    return GetFineGradient(location.x(), location.y(), location.z(),\n                           nominal_window_size);\n  }\n\n  GradientQuery GetFineGradient4d(\n      const Eigen::Vector4d& location,\n      const double nominal_window_size) const\n  {\n    return GetFineGradient(location(0), location(1), location(2),\n                           nominal_window_size);\n  }\n\n  GradientQuery GetFineGradient(\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 (this->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 EstimateDistanceQuery point_distance = EstimateDistance(x, y, z);\n      const EstimateDistanceQuery mx_distance = EstimateDistance(min_x, y, z);\n      const EstimateDistanceQuery px_distance = EstimateDistance(max_x, y, z);\n      const EstimateDistanceQuery my_distance = EstimateDistance(x, min_y, z);\n      const EstimateDistanceQuery py_distance = EstimateDistance(x, max_y, z);\n      const EstimateDistanceQuery mz_distance = EstimateDistance(x, y, min_z);\n      const EstimateDistanceQuery pz_distance = EstimateDistance(x, y, max_z);\n      // Compute gradient for each axis\n      const double gx = ComputeAxisFineGradient(point_distance,\n                                                  mx_distance,\n                                                  px_distance,\n                                                  x, min_x, max_x);\n      const double gy = ComputeAxisFineGradient(point_distance,\n                                                  my_distance,\n                                                  py_distance,\n                                                  y, min_y, max_y);\n      const double gz = ComputeAxisFineGradient(point_distance,\n                                                  mz_distance,\n                                                  pz_distance,\n                                                  z, min_z, max_z);\n      return GradientQuery(gx, gy, gz);\n    }\n    else\n    {\n      return GradientQuery();\n    }\n  }\n\n  GradientQuery GetFineGradient(\n      const common_robotics_utilities::voxel_grid::GridIndex& index,\n      const double nominal_window_size) const\n  {\n    return GetFineGradient4d(\n        this->GridIndexToLocation(index), nominal_window_size);\n  }\n\n  GradientQuery GetFineGradient(\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 GetFineGradient4d(\n        this->GridIndexToLocation(x_index, y_index, z_index),\n        nominal_window_size);\n  }\n\n  /// Project the provided point out of collision.\n\n  ProjectedPosition ProjectOutOfCollision(\n      const double x, const double y, const double z,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    return ProjectOutOfCollision4d(\n        Eigen::Vector4d(x, y, z, 1.0), stepsize_multiplier);\n  }\n\n  ProjectedPosition ProjectOutOfCollision3d(\n      const Eigen::Vector3d& location,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    return ProjectOutOfCollision(\n        location.x(), location.y(), location.z(), stepsize_multiplier);\n  }\n\n  ProjectedPosition ProjectOutOfCollision4d(\n      const Eigen::Vector4d& location,\n      const double stepsize_multiplier = 1.0 / 10.0) const\n  {\n    return ProjectOutOfCollisionToMinimumDistance4d(\n        location, 0.0, stepsize_multiplier);\n  }\n\n  ProjectedPosition 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), minimum_distance, stepsize_multiplier);\n  }\n\n  ProjectedPosition 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  ProjectedPosition 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 (this->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).Value();\n      while (sdf_dist <= minimum_distance)\n      {\n        const GradientQuery gradient\n            = GetCoarseGradient4d(mutable_location, enable_edge_gradients);\n        if (gradient.HasValue())\n        {\n          const Eigen::Vector4d& grad_vector = gradient.Value();\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).Value();\n          }\n          else\n          {\n            std::cerr << \"Encountered flat gradient - stuck\" << std::endl;\n            return ProjectedPosition();\n          }\n        }\n        else\n        {\n          std::cerr << \"Failed to compute gradient - out of SDF?\" << std::endl;\n          return ProjectedPosition();\n        }\n      }\n    }\n    return ProjectedPosition(mutable_location);\n  }\n\n  /// The following function can be *very expensive* to compute, since it\n  /// performs gradient ascent/descent across the SDF.\n  common_robotics_utilities::voxel_grid::VoxelGrid<Eigen::Vector3d>\n  ComputeLocalExtremaMap() const\n  {\n    const Eigen::Vector3d default_value(\n        -std::numeric_limits<double>::infinity(),\n        -std::numeric_limits<double>::infinity(),\n        -std::numeric_limits<double>::infinity());\n    common_robotics_utilities::voxel_grid::VoxelGrid<Eigen::Vector3d>\n        watershed_map(this->GetOriginTransform(), this->GetGridSizes(),\n                      default_value);\n    for (int64_t x_idx = 0; x_idx < watershed_map.GetNumXCells(); x_idx++)\n    {\n      for (int64_t y_idx = 0; y_idx < watershed_map.GetNumYCells(); y_idx++)\n      {\n        for (int64_t z_idx = 0; z_idx < watershed_map.GetNumZCells(); z_idx++)\n        {\n          // We use an \"unsafe\" function here because we know all the indices\n          // we provide it will be safe\n          FollowGradientsToLocalExtremaUnsafe(\n              x_idx, y_idx, z_idx, watershed_map);\n        }\n      }\n    }\n    return watershed_map;\n  }\n};\n}  // namespace voxelized_geometry_tools\n\nextern template class voxelized_geometry_tools::SignedDistanceField<double>;\nextern template class voxelized_geometry_tools::SignedDistanceField<float>;\n", "meta": {"hexsha": "8699742c8eb9571e50c097964f72fdb99055965a", "size": 45180, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/voxelized_geometry_tools/signed_distance_field.hpp", "max_stars_repo_name": "ToyotaResearchInstitute/voxelized_geometry_tools", "max_stars_repo_head_hexsha": "3928899e8493b9a812bb7b0998fd5fe9a5c98b8f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T20:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-09T02:16:33.000Z", "max_issues_repo_path": "include/voxelized_geometry_tools/signed_distance_field.hpp", "max_issues_repo_name": "ToyotaResearchInstitute/voxelized_geometry_tools", "max_issues_repo_head_hexsha": "3928899e8493b9a812bb7b0998fd5fe9a5c98b8f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/voxelized_geometry_tools/signed_distance_field.hpp", "max_forks_repo_name": "ToyotaResearchInstitute/voxelized_geometry_tools", "max_forks_repo_head_hexsha": "3928899e8493b9a812bb7b0998fd5fe9a5c98b8f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-16T08:24:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T08:24:54.000Z", "avg_line_length": 37.6186511241, "max_line_length": 80, "alphanum_fraction": 0.6374280655, "num_tokens": 10299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982564942392716, "lm_q2_score": 0.02161533449587041, "lm_q1q2_score": 0.005616218322904945}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n#include \"Data.h\"\n\n#include \"AbstractContinuousDomain.h\"\n#include \"DataConstant.h\"\n#include \"DataEmpty.h\"\n#include \"DataExpanded.h\"\n#include \"DataLazy.h\"\n#include \"DataTagged.h\"\n#include \"EscriptParams.h\"\n#include \"FunctionSpaceException.h\"\n#include \"FunctionSpaceFactory.h\"\n#include \"BinaryDataReadyOps.h\"\n\n#ifdef IKNOWWHATIMDOING\n#include \"Dodgy.h\"\n#endif\n\n#include <algorithm>\n#include <fstream>\n#include <functional>\n#include <sstream>      // so we can throw messages about ranks\n#include <vector>\n#include <iostream>\n\n#include <boost/python/dict.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/long.hpp>\n#include \"WrappedArray.h\"\n\nnamespace bp = boost::python;\nusing namespace escript;\nusing namespace escript::DataTypes;\nusing namespace std;\nusing DataTypes::real_t;\nusing DataTypes::cplx_t;\n\n\n#define THROWONCOMPLEX if (m_data->isComplex()){throw DataException(\"Operation does not support complex objects\");}\n#define THROWONCOMPLEXA(Z) if (Z.isComplex()){throw DataException(\"Operation does not support complex objects\");}\n\n// ensure the current object is not a DataLazy\n// The idea was that we could add an optional warning whenever a resolve is forced\n// #define forceResolve() if (isLazy()) {#resolve();}\n\n#define AUTOLAZYON escriptParams.getAutoLazy()\n#define MAKELAZYOP(X) do {\\\n  if (isLazy() || (AUTOLAZYON && m_data->isExpanded())) \\\n  {\\\n        DataLazy* c=new DataLazy(borrowDataPtr(),X);\\\n        return Data(c);\\\n  }\\\n}while(0)\n\n#define MAKELAZYOPOFF(X,Y) do {\\\n  if (isLazy() || (AUTOLAZYON && m_data->isExpanded())) \\\n  {\\\n        DataLazy* c=new DataLazy(borrowDataPtr(),X,Y);\\\n        return Data(c);\\\n  }\\\n}while(0)\n\n#define MAKELAZYOP2(X,Y,Z) do {\\\n  if (isLazy() || (AUTOLAZYON && m_data->isExpanded())) \\\n  {\\\n        DataLazy* c=new DataLazy(borrowDataPtr(),X,Y,Z);\\\n        return Data(c);\\\n  }\\\n}while(0)\n\n#define MAKELAZYBINSELF(R,X) do {\\\n  if (isLazy() || R.isLazy() || (AUTOLAZYON && (isExpanded() || R.isExpanded()))) \\\n  {\\\n        DataLazy* c=new DataLazy(m_data,R.borrowDataPtr(),X);\\\n/*         m_data=c->getPtr();*/     set_m_data(c->getPtr());\\\n        return (*this);\\\n  }\\\n}while(0)\n\n// like the above but returns a new data rather than *this\n#define MAKELAZYBIN(R,X) do {\\\n  if (isLazy() || R.isLazy() || (AUTOLAZYON && (isExpanded() || R.isExpanded()))) \\\n  {\\\n        DataLazy* c=new DataLazy(m_data,R.borrowDataPtr(),X);\\\n        return Data(c);\\\n  }\\\n}while(0)\n\n#define MAKELAZYBIN2(L,R,X) do {\\\n  if (L.isLazy() || R.isLazy() || (AUTOLAZYON && (L.isExpanded() || R.isExpanded()))) \\\n  {\\\n/*  if (L.isComplex() || R.isComplex()) \\\n  {\\\n      throw DataException(\"Lazy operations on complex not supported yet\");\\\n  }\\\n*/        DataLazy* c=new DataLazy(L.borrowDataPtr(),R.borrowDataPtr(),X);\\\n        return Data(c);\\\n  }\\\n}while(0)\n\n#define CHECK_DO_CRES escriptParams.getResolveCollective()\n\n\nnamespace\n{\n\ntemplate <class ARR>\ninline\nbp::tuple\npointToTuple1(const DataTypes::ShapeType& shape, ARR v, unsigned long offset)\n{\n    bp::list l;\n    unsigned int dim=shape[0];\n    for (size_t i=0;i<dim;++i)\n    {\n        l.append(v[i+offset]);\n    }\n    return bp::tuple(l);\n}\n\ntemplate <class ARR>\ninline\nbp::tuple\npointToTuple2(const DataTypes::ShapeType& shape, ARR v, unsigned long offset)\n{\n    unsigned int shape0=shape[0];\n    unsigned int shape1=shape[1];\n    bp::list lj;\n    for (size_t j=0;j<shape0;++j)\n    {\n        bp::list li;\n        for (size_t i=0;i<shape1;++i)\n        {\n            li.append(v[offset+DataTypes::getRelIndex(shape,j,i)]);\n        }\n        lj.append(bp::tuple(li));\n    }\n    return bp::tuple(lj);\n}\n\ntemplate <class ARR>\ninline\nbp::tuple\npointToTuple3(const DataTypes::ShapeType& shape, ARR v, unsigned long offset)\n{\n    unsigned int shape0=shape[0];\n    unsigned int shape1=shape[1];\n    unsigned int shape2=shape[2];\n\n    bp::list lk;\n    for (size_t k=0;k<shape0;++k)\n    {\n        bp::list lj;\n        for (size_t j=0;j<shape1;++j)\n        {\n            bp::list li;\n            for (size_t i=0;i<shape2;++i)\n            {\n                li.append(v[offset+DataTypes::getRelIndex(shape,k,j,i)]);\n            }\n            lj.append(bp::tuple(li));\n        }\n        lk.append(bp::tuple(lj));\n    }\n    return bp::tuple(lk);\n}\n\ntemplate <class ARR>\ninline\nbp::tuple\npointToTuple4(const DataTypes::ShapeType& shape, ARR v, unsigned long offset)\n{\n    unsigned int shape0=shape[0];\n    unsigned int shape1=shape[1];\n    unsigned int shape2=shape[2];\n    unsigned int shape3=shape[3];\n\n    bp::list ll;\n    for (size_t l=0;l<shape0;++l)\n    {\n        bp::list lk;\n        for (size_t k=0;k<shape1;++k)\n        {\n            bp::list lj;\n            for (size_t j=0;j<shape2;++j)\n            {\n                bp::list li;\n                for (size_t i=0;i<shape3;++i)\n                {\n                    li.append(v[offset+DataTypes::getRelIndex(shape,l,k,j,i)]);\n                }\n                lj.append(bp::tuple(li));\n            }\n            lk.append(bp::tuple(lj));\n        }\n        ll.append(bp::tuple(lk));\n    }\n    return bp::tuple(ll);\n}\n\n\n// This should be safer once the DataC RO changes have been brought in\ntemplate <class ARR>\nbp::tuple\npointToTuple( const DataTypes::ShapeType& shape,ARR v)\n{\n    int rank=shape.size();\n    if (rank==0)\n    {\n        return bp::make_tuple(v[0]);\n    }\n    else if (rank==1)\n    {\n        return pointToTuple1(shape,v,0);\n    }\n    else if (rank==2)\n    {\n        return pointToTuple2(shape,v,0);\n    }\n    else if (rank==3)\n    {\n        return pointToTuple3(shape,v,0);\n    }\n    else if (rank==4)\n    {\n        return pointToTuple4(shape,v,0);\n    }\n    else\n        throw DataException(\"Unknown rank in pointToTuple.\");\n}\n\n}  // anonymous namespace\n\nData::Data()\n    :  m_lazy(false)\n{\n    //\n    // Default data is type DataEmpty\n    DataAbstract* temp=new DataEmpty();\n    set_m_data(temp->getPtr());\n    m_protected=false;\n}\n\n\n\nData::Data(real_t value,\n           const DataTypes::ShapeType& dataPointShape,\n           const FunctionSpace& what,\n           bool expanded)\n        :  m_lazy(false)\n{\n    initialise(value, dataPointShape, what, expanded);\n    m_protected=false;\n}\n\nData::Data(cplx_t value,\n           const DataTypes::ShapeType& dataPointShape,\n           const FunctionSpace& what,\n           bool expanded)\n        :  m_lazy(false)\n{\n    initialise(value, dataPointShape, what, expanded);\n    m_protected=false;\n}\n\n// Ordering is: shape, functionspace, expanded\nData::Data(boost::python::object value,\n       boost::python::object par2,\n       boost::python::object par3,\n       boost::python::object par4)\n{\n    if (value.is_none())\n    {\n\tthrow DataException(\"Data contructor from python - first argument must not be None.\");\n    }\n      // now to enforce contiguous Nones\n    if ((par2.is_none() && (!par3.is_none() || !par4.is_none())) ||\n        (par3.is_none() && !par4.is_none()))\n    {\n\tthrow DataException(\"Data contructor from python - arguments must be omitted from the right.\");\n    }\n  \n    // what is the first arg\n    boost::python::extract<DataTypes::cplx_t> exc(value);\n    boost::python::extract<DataTypes::real_t> exr(value);\n    boost::python::extract<Data> exd(value);\n    if (exc.check() || exr.check())\n    {\n\t//(value, shape, functionspace, expanded), but shape could be missing in which case => ()\n        DataTypes::ShapeType dataPointShape;\t// default to scalar\n\tif (!par2.is_none())\n\t{\n\t    boost::python::extract<boost::python::tuple> ex2t(par2);\n\t    boost::python::extract<FunctionSpace> ex2fs(par2);\n\t    if (ex2t.check())\n\t    {\n\t\tfor (int i = 0; i < par2.attr(\"__len__\")(); ++i) {\n\t\t    dataPointShape.push_back(bp::extract<const int>(par2[i]));\n\t\t}\t    \n\t    }\n\t    else if (ex2fs.check())\n\t    {\n\t\t// shape will default to ()\n\t        // now we copy the params up to make it look like they did specify one\n\t        par4=par3;\n\t\tpar3=par2;\n\t    }\n\t    else\n\t    {\n\t\tthrow DataException(\"Data contructor from python - expected a tuple or None as second argument.\");\n\t    }\n\t}\n\tboost::python::extract<FunctionSpace> ex3fs(par3);\t\n\tif (!par3.is_none())\n\t{\n\t    if (!ex3fs.check())\n\t    {\n\t\tthrow DataException(\"Data contructor from python - expected a FunctionSpace or None as third argument.\");\n\t    }\n\t}\n\tbool expa=false;\n\tif (!par4.is_none())\n\t{\n\t    boost::python::extract<bool> ex4b(par4);\n\t    if (!ex4b.check())\n\t    {\n\t\tthrow DataException(\"Data contructor from python - expected a boolean or None as fourth argument.\");\t      \n\t    }\n\t    expa=ex4b();\n\t}\n\tif (exr.check())\n\t{\n\t    int len = DataTypes::noValues(dataPointShape);\n\t    RealVectorType temp_data(len,exr(),len);\n\t    initialise(temp_data, dataPointShape, par3.is_none()?FunctionSpace():ex3fs(), expa);\n\t    m_protected=false;\t  \t  \n\t}\n\telse\n\t{\n\t    int len = DataTypes::noValues(dataPointShape);\n\t    CplxVectorType temp_data(len,exc(),len);\n\t    initialise(temp_data, dataPointShape, par3.is_none()?FunctionSpace():ex3fs(), expa);\n\t    m_protected=false;\t  \n\t}\n    }\n    else if (exd.check())\t// Construct from (Data, [FunctionSpace]\n    {\n\tboost::python::extract<FunctionSpace> ex2fs(par2);\t      \n\tif (!par2.is_none())\n\t{\n\t    if (!ex2fs.check())\n\t    {\n\t\tthrow DataException(\"Data contructor from python - expected a FunctionSpace or None as second argument.\");\t      \n\t    }\n\t}        \n        init_from_data_and_fs(exd(), par2.is_none()?FunctionSpace():ex2fs());\n    }\n    else\t//non-data, non-scalar first argument\n    {   //               2         3\n\t//(value, functionspace, expanded)      \n        if (!par4.is_none())\n\t{\n\t    throw DataException(\"Data contructor from python - unexpected fourth argument.\");\n\t}\n\tbool expa=false;\n\tif (!par3.is_none())\n\t{\n\t    boost::python::extract<bool> ex3b(par3);\n\t    if (!ex3b.check())\n\t    {\n\t\tthrow DataException(\"Data contructor from python - expected a boolean or None as third argument.\");\t      \n\t    }\n\t    expa=ex3b();\n\t}\n\tboost::python::extract<FunctionSpace> ex2fs(par2);\t \n\tif (!par2.is_none())\n\t{\n\t    if (!ex2fs.check())\n\t    {\n\t\tthrow DataException(\"Data contructor from python - expected a FunctionSpace or None as second argument.\");\t      \n\t    }\n\t}\n\tWrappedArray w(value);\n\tinitialise(w,par2.is_none()?FunctionSpace():ex2fs(),expa);\n\tm_protected=false;\n    }\n}\n\nData::Data(const Data& inData)\n        :  m_lazy(false)\n{\n    set_m_data(inData.m_data);\n    m_protected=inData.isProtected();\n}\n\n\nData::Data(const Data& inData,\n           const DataTypes::RegionType& region)\n        :  m_lazy(false)\n{\n    DataAbstract_ptr dat=inData.m_data;\n    if (inData.isLazy())\n    {\n        dat=inData.m_data->resolve();\n    }\n    else\n    {\n        dat=inData.m_data;\n    }\n    //\n    // Create Data which is a slice of another Data\n    DataAbstract* tmp = dat->getSlice(region);\n    set_m_data(DataAbstract_ptr(tmp));\n    m_protected=false;\n\n}\n\nvoid Data::init_from_data_and_fs(const Data& inData,\n           const FunctionSpace& functionspace)\n{\n    if (inData.isEmpty())\n    {\n        throw DataException(\"Error - will not interpolate for instances of DataEmpty.\");\n    }\n    \n    if (inData.getFunctionSpace()==functionspace) {\n        set_m_data(inData.m_data);\n    } \n    else \n    {\n        if (inData.isConstant()) \n        {  // for a constant function, we just need to use the new function space\n            if (!inData.probeInterpolation(functionspace))\n            { // Even though this is constant, we still need to check whether interpolation is allowed\n                throw FunctionSpaceException(\"Cannot interpolate across to the domain of the specified FunctionSpace. (DataConstant)\");\n            }\n            // if the data is not lazy, this will just be a cast to DataReady\n            DataReady_ptr dr=inData.m_data->resolve();\n            DataConstant* dc=0;\n            if (inData.isComplex())\n            {\n                dc=new DataConstant(functionspace,inData.m_data->getShape(),dr->getTypedVectorRO((DataTypes::cplx_t)0));     \t      \n            }\n            else\n            {\n                dc=new DataConstant(functionspace,inData.m_data->getShape(),dr->getTypedVectorRO((DataTypes::real_t)0));     \t      \n            }\n            set_m_data(DataAbstract_ptr(dc));\n        } \n        else \n        {\n            if (inData.isComplex())\n            {\n                Data tmp((DataTypes::cplx_t)0,inData.getDataPointShape(),functionspace,true);\n                const_Domain_ptr inDataDomain=inData.getDomain();\n                if  (inDataDomain==functionspace.getDomain()) {\n                    if (inData.isLazy())\n                    {\n                        Data temp(inData);\n                        temp.resolve();     // since complex lazy is not a thing\n                        inDataDomain->interpolateOnDomain(tmp,temp);\n                    }\n                    else\n                    {\n                        inDataDomain->interpolateOnDomain(tmp,inData);\n                    }\n                } \n                else \n                {\n                    if (inData.isLazy())\n                    {\n                        Data temp(inData);\n                        temp.resolve();\n                        inDataDomain->interpolateAcross(tmp,temp);\n                    }\n                    else\n                    {\n                        inDataDomain->interpolateAcross(tmp,inData);\n                    }\n                }\n                set_m_data(tmp.m_data);\t      \t      \n            }\n            else\n            {\n                Data tmp(0,inData.getDataPointShape(),functionspace,true);\n                const_Domain_ptr inDataDomain=inData.getDomain();\n                if  (inDataDomain==functionspace.getDomain()) {\n                    inDataDomain->interpolateOnDomain(tmp,inData);\n                } else {\n                    inDataDomain->interpolateAcross(tmp,inData);\n                }\n                set_m_data(tmp.m_data);\n            }\n        }\n    }\n    m_protected=false;\n}\n\n\nData::Data(const Data& inData,\n           const FunctionSpace& functionspace)\n        :  m_lazy(false)\n{\n    init_from_data_and_fs(inData, functionspace);  \n}\n\nData::Data(DataAbstract* underlyingdata)\n        :  m_lazy(false)\n{\n    set_m_data(underlyingdata->getPtr());\n    m_protected=false;\n}\n\nData::Data(DataAbstract_ptr underlyingdata)\n        :  m_lazy(false)\n{\n    set_m_data(underlyingdata);\n    m_protected=false;\n}\n\nData::Data(const DataTypes::RealVectorType& value,\n           const DataTypes::ShapeType& shape,\n           const FunctionSpace& what,\n           bool expanded)\n        :  m_lazy(false)\n{\n    initialise(value,shape,what,expanded);\n    m_protected=false;\n}\n\n\n\n\nData::Data(const WrappedArray& w, const FunctionSpace& what,\n           bool expanded)\n           : m_lazy(false)\n{\n    initialise(w,what,expanded);  \n    m_protected=false; \n}\n\n\nData::Data(const boost::python::object& value,\n           const Data& other)\n        :  m_lazy(false)\n{\n    WrappedArray w(value);\n\n    // extract the shape of the array\n    const DataTypes::ShapeType& tempShape=w.getShape();\n    if (w.getRank()==0) {\n\n        if (w.isComplex()==true)\n        {\n            // get the space for the data vector\n            int len1 = DataTypes::noValues(tempShape);\n            CplxVectorType temp_data(len1, 0.0, len1);\n            temp_data.copyFromArray(w,1);\n\n            int len = DataTypes::noValues(other.getDataPointShape());\n\n            CplxVectorType temp2_data(len, temp_data[0], len);\n            DataConstant* t=new DataConstant(other.getFunctionSpace(),other.getDataPointShape(),temp2_data);\n            set_m_data(DataAbstract_ptr(t));\n        }\n        else\n        {\n            // get the space for the data vector\n            int len1 = DataTypes::noValues(tempShape);\n            RealVectorType temp_data(len1, 0.0, len1);\n            temp_data.copyFromArray(w,1);\n\n            int len = DataTypes::noValues(other.getDataPointShape());\n\n            RealVectorType temp2_data(len, temp_data[0], len);\n            DataConstant* t=new DataConstant(other.getFunctionSpace(),other.getDataPointShape(),temp2_data);\n            set_m_data(DataAbstract_ptr(t));\n        }\n    } else {\n        //\n        // Create a DataConstant with the same sample shape as other\n        DataConstant* t=new DataConstant(w,other.getFunctionSpace());\n        set_m_data(DataAbstract_ptr(t));\n    }\n    m_protected=false;\n}\n\n\nData::~Data()\n{\n    set_m_data(DataAbstract_ptr());\n}\n\n\n// only call in thread safe contexts.\n// This method should be atomic\nvoid Data::set_m_data(DataAbstract_ptr p)\n{\n    if (p.get()!=0)\n    {\n        m_data=p;\n        m_lazy=m_data->isLazy();\n    }\n}\n\nvoid Data::initialise(const WrappedArray& value,\n                      const FunctionSpace& what,\n                      bool expanded)\n{\n    //\n    // Construct a Data object of the appropriate type.\n    // Construct the object first as there seems to be a bug which causes\n    // undefined behaviour if an exception is thrown during construction\n    // within the shared_ptr constructor.\n    if (expanded) {\n        DataAbstract* temp=new DataExpanded(value, what);\n        set_m_data(temp->getPtr());\n    } else {\n        DataAbstract* temp=new DataConstant(value, what);\n        set_m_data(temp->getPtr());\n    }\n}\n\n\nvoid\nData::initialise(const DataTypes::RealVectorType& value,\n                 const DataTypes::ShapeType& shape,\n                 const FunctionSpace& what,\n                 bool expanded)\n{\n    //\n    // Construct a Data object of the appropriate type.\n    // Construct the object first as there seems to be a bug which causes\n    // undefined behaviour if an exception is thrown during construction\n    // within the shared_ptr constructor.\n    if (expanded) {\n        DataAbstract* temp=new DataExpanded(what, shape, value);\n        set_m_data(temp->getPtr());\n    } else {\n        DataAbstract* temp=new DataConstant(what, shape, value);\n        set_m_data(temp->getPtr());\n    }\n}\n\nvoid\nData::initialise(const DataTypes::CplxVectorType& value,\n                 const DataTypes::ShapeType& shape,\n                 const FunctionSpace& what,\n                 bool expanded)\n{\n    //\n    // Construct a Data object of the appropriate type.\n    // Construct the object first as there seems to be a bug which causes\n    // undefined behaviour if an exception is thrown during construction\n    // within the shared_ptr constructor.\n    if (expanded) {\n        DataAbstract* temp=new DataExpanded(what, shape, value);\n        set_m_data(temp->getPtr());\n    } else {\n        DataAbstract* temp=new DataConstant(what, shape, value);\n        set_m_data(temp->getPtr());\n    }\n}\n\n\nvoid\nData::initialise(const real_t value,\n                 const DataTypes::ShapeType& shape,\n                 const FunctionSpace& what,\n                 bool expanded)\n{\n    //\n    // Construct a Data object of the appropriate type.\n    // Construct the object first as there seems to be a bug which causes\n    // undefined behaviour if an exception is thrown during construction\n    // within the shared_ptr constructor.\n    if (expanded) {\n        DataAbstract* temp=new DataExpanded(what, shape, value);\n        DataAbstract_ptr p(temp);\n        set_m_data(p);\n    } else {\n        DataAbstract* temp=new DataConstant(what, shape, value);\n        DataAbstract_ptr p(temp);\n        set_m_data(p);\n    }\n}\n\n\nvoid\nData::initialise(const cplx_t value,\n                 const DataTypes::ShapeType& shape,\n                 const FunctionSpace& what,\n                 bool expanded)\n{\n    //\n    // Construct a Data object of the appropriate type.\n    // Construct the object first as there seems to be a bug which causes\n    // undefined behaviour if an exception is thrown during construction\n    // within the shared_ptr constructor.\n    if (expanded) {\n        DataAbstract* temp=new DataExpanded(what, shape, value);\n        DataAbstract_ptr p(temp);\n        set_m_data(p);\n    } else {\n        DataAbstract* temp=new DataConstant(what, shape, value);\n        DataAbstract_ptr p(temp);\n        set_m_data(p);\n    }\n}\n\nconst bp::tuple\nData::getShapeTuple() const\n{\n    const DataTypes::ShapeType& shape=getDataPointShape();\n    switch(getDataPointRank()) {\n        case 0:\n            return bp::make_tuple();\n        case 1:\n            return bp::make_tuple(bp::long_(shape[0]));\n        case 2:\n            return bp::make_tuple(bp::long_(shape[0]),bp::long_(shape[1]));\n        case 3:\n            return bp::make_tuple(bp::long_(shape[0]),bp::long_(shape[1]),bp::long_(shape[2]));\n        case 4:\n            return bp::make_tuple(bp::long_(shape[0]),bp::long_(shape[1]),bp::long_(shape[2]),bp::long_(shape[3]));\n        default:\n            throw DataException(\"Error - illegal Data rank.\");\n    }\n}\n\n\nlong\nData::getShapeProduct() const\n{\n    const DataTypes::ShapeType& shape=getDataPointShape();\n    switch(getDataPointRank()) {\n        case 0:\n            return 1;\n        case 1:\n            return shape[0];\n        case 2:\n            return shape[0]*shape[1];\n        case 3:\n            return shape[0]*shape[1]*shape[2];\n        case 4:\n            return shape[0]*shape[1]*shape[2]*shape[3];\n        default:\n            throw DataException(\"Error - illegal Data rank.\");\n    }\n}\n\n\n// The different name is needed because boost has trouble with overloaded functions.\n// It can't work out what type the function is based solely on its name.\n// There are ways to fix this involving creating function pointer variables for each form\n// but there doesn't seem to be a need given that the methods have the same name from the python point of view\nData\nData::copySelf() const\n{\n    DataAbstract* temp=m_data->deepCopy();\n    return Data(temp);\n}\n\nvoid\nData::copy(const Data& other)\n{\n    DataAbstract* temp=other.m_data->deepCopy();\n    DataAbstract_ptr p=temp->getPtr();\n    set_m_data(p);\n}\n\n\nData\nData::delay()\n{\n    if (!isLazy())\n    {\n        DataLazy* dl=new DataLazy(m_data);\n        return Data(dl);\n    }\n    return *this;\n}\n\nvoid\nData::delaySelf()\n{\n    if (!isLazy())\n    {\n        set_m_data((new DataLazy(m_data))->getPtr());\n    }\n}\n\n\n// For lazy data, it would seem that DataTagged will need to be treated differently since even after setting all tags\n// to zero, all the tags from all the DataTags would be in the result.\n// However since they all have the same value (0) whether they are there or not should not matter.\n// So I have decided that for all types this method will create a constant 0.\n// It can be promoted up as required.\n// A possible efficiency concern might be expanded->constant->expanded which has an extra memory management\n// but we can deal with that if it arises.\n//\nvoid\nData::setToZero()\n{\n    if (isEmpty())\n    {\n        throw DataException(\"Error - Operations (setToZero)  permitted on instances of DataEmpty.\");\n    }\n    if (isLazy())\n    {\n\t// This can't actually be complex yet but Just putting in this for later\n        if (isComplex())\n\t{\n\t    throw DataException(\"Programmer Error - setToZero is not supported on lazy complex values.\");\n\t}\n        DataTypes::RealVectorType v(getNoValues(),0);\n        DataConstant* dc=new DataConstant(getFunctionSpace(),getDataPointShape(),v);\n        DataLazy* dl=new DataLazy(dc->getPtr());\n        set_m_data(dl->getPtr());\n    }\n    else\n    {\n\t// we don't want to call exclusiveWrite() here because\n        // as soon as we get the copy we'd overwrite it\n        if (isShared())\n        {\t  \n                DataAbstract* t=m_data->zeroedCopy();\n                set_m_data(DataAbstract_ptr(t));\n        }\t\n\telse\n\t{\n\t    m_data->setToZero();\n\t}\n    }\n}\n\n\nvoid\nData::copyWithMask(const Data& other,\n                   const Data& mask)\n{\n    // 1. Interpolate if required so all Data use the same FS as this\n    // 2. Tag or Expand so that all Data's are the same type\n    // 3. Iterate over the data vectors copying values where mask is >0\n    if (other.isEmpty() || mask.isEmpty())\n    {\n        throw DataException(\"Error - copyWithMask not permitted using instances of DataEmpty.\");\n    }\n    if (mask.isComplex())\n    {\n        throw DataException(\"Error - copyWithMask not permitted using a complex mask.\");\n    }\n    Data other2(other);\n    Data mask2(mask);\n    other2.resolve();\n    mask2.resolve();\n    this->resolve();\n    FunctionSpace myFS=getFunctionSpace();\n    FunctionSpace oFS=other2.getFunctionSpace();\n    FunctionSpace mFS=mask2.getFunctionSpace();\n    if (oFS!=myFS)\n    {\n        if (other2.probeInterpolation(myFS))\n        {\n            other2=other2.interpolate(myFS);\n        }\n        else\n        {\n            throw DataException(\"Error - copyWithMask: other FunctionSpace is not compatible with this one.\");\n        }\n    }\n    if (mFS!=myFS)\n    {\n        if (mask2.probeInterpolation(myFS))\n        {\n            mask2=mask2.interpolate(myFS);\n        }\n        else\n        {\n            throw DataException(\"Error - copyWithMask: mask FunctionSpace is not compatible with this one.\");\n        }\n    }\n    // Ensure that all args have the same type\n    if (this->isExpanded() || mask2.isExpanded() || other2.isExpanded())\n    {\n        this->expand();\n        other2.expand();\n        mask2.expand();\n    }\n    else if (this->isTagged() || mask2.isTagged() || other2.isTagged())\n    {\n        this->tag();\n        other2.tag();\n        mask2.tag();\n    }\n    else if (this->isConstant() && mask2.isConstant() && other2.isConstant())\n    {\n    }\n    else\n    {\n        throw DataException(\"Error - Unknown DataAbstract passed to copyWithMask.\");\n    }\n    unsigned int selfrank=getDataPointRank();\n    unsigned int otherrank=other2.getDataPointRank();\n    unsigned int maskrank=mask2.getDataPointRank();\n    if ((selfrank==0) && (otherrank>0 || maskrank>0))\n    {\n        // to get here we must be copying from a large object into a scalar\n        // I am not allowing this.\n        // If you are calling copyWithMask then you are considering keeping some existing values\n        // and so I'm going to assume that you don't want your data objects getting a new shape.\n        throw DataException(\"Attempt to copyWithMask into a scalar from an object or mask with rank>0.\");\n    }\n    if ((selfrank>0) && (otherrank==0) &&(maskrank==0))\n    {\n        // Not allowing this combination.\n        // it is not clear what the rank of the target should be.\n        // Should it be filled with the scalar (rank stays the same); \n        // or should the target object be reshaped to be a scalar as well.\n        throw DataException(\"Attempt to copyWithMask from scalar mask and data into non-scalar target.\");\n    }\n    \n    if (isComplex()!=other2.isComplex())\n    {\n        complicate();\n        other2.complicate();\n    }\n    \n    exclusiveWrite();\n    if (!isComplex())\n    {\n\tmaskWorker(other2, mask2, DataTypes::real_t(0));\n    }\n    else\n    {\n\tmaskWorker(other2, mask2, DataTypes::cplx_t(0));\n    }\n}\n\ntemplate <typename S>\nvoid \nData::maskWorker(Data& other2, Data& mask2, S sentinel)\n{\n     // Now we iterate over the elements\n    auto& self=getReady()->getTypedVectorRW(sentinel);\n    auto& ovec=other2.getReadyPtr()->getTypedVectorRO(sentinel);\n    auto& mvec=mask2.getReadyPtr()->getTypedVectorRO(DataTypes::real_t(0));\n\n    unsigned int selfrank=getDataPointRank();\n    unsigned int otherrank=other2.getDataPointRank();\n    unsigned int maskrank=mask2.getDataPointRank();    \n\n    if ((selfrank>0) && (otherrank>0) &&(maskrank==0))\n    {\n        if (mvec[0]>0)          // copy whole object if scalar is >0\n        {\n            copy(other2);\n        }\n        return;\n    }\n    if (isTagged())               // so all objects involved will also be tagged\n    {\n        // note the !\n        if (!((getDataPointShape()==mask2.getDataPointShape()) && \n                ((other2.getDataPointShape()==mask2.getDataPointShape()) || (otherrank==0))))\n        {\n            throw DataException(\"copyWithMask, shape mismatch.\");\n        }\n\n        // We need to consider the possibility that tags are missing or in the wrong order\n        // My guiding assumption here is: All tagged Data are assumed to have the default value for\n        // all tags which are not explicitly defined\n\n        const DataTagged* mptr=dynamic_cast<const DataTagged*>(mask2.m_data.get());\n        const DataTagged* optr=dynamic_cast<const DataTagged*>(other2.m_data.get());\n        DataTagged* tptr=dynamic_cast<DataTagged*>(m_data.get());\n\n        // first, add any tags missing from other or mask\n        const DataTagged::DataMapType& olookup=optr->getTagLookup();\n        const DataTagged::DataMapType& mlookup=mptr->getTagLookup();\n        const DataTagged::DataMapType& tlookup=tptr->getTagLookup();\n        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n        for (i=olookup.begin();i!=olookup.end();i++)\n        {\n            tptr->addTag(i->first); \n        }\n        for (i=mlookup.begin();i!=mlookup.end();i++) {\n            tptr->addTag(i->first);\n        }\n        // now we know that *this has all the required tags but they aren't guaranteed to be in\n        // the same order\n\n        // There are two possibilities: 1. all objects have the same rank. 2. other is a scalar\n        if ((selfrank==otherrank) && (otherrank==maskrank))\n        {\n            for (i=tlookup.begin();i!=tlookup.end();i++)\n            {\n                // get the target offset\n\t        // yes this is explicitly RealType but size_t should not vary\n\t        DataTypes::RealVectorType::size_type toff=tptr->getOffsetForTag(i->first);\n                DataTypes::RealVectorType::size_type moff=mptr->getOffsetForTag(i->first);\n                DataTypes::RealVectorType::size_type ooff=optr->getOffsetForTag(i->first);\n                for (int j=0;j<getDataPointSize();++j)\n                {\n                    if (mvec[j+moff]>0)\n                    {\n                        self[j+toff]=ovec[j+ooff];\n                    }\n                }\n            }\n            // now for the default value\n            for (int j=0;j<getDataPointSize();++j)\n            {\n                if (mvec[j+mptr->getDefaultOffset()]>0)\n                {\n                    self[j+tptr->getDefaultOffset()]=ovec[j+optr->getDefaultOffset()];\n                }\n            }\n        }\n        else    // other is a scalar\n        {\n            for (i=tlookup.begin();i!=tlookup.end();i++)\n            {\n                // get the target offset\n\t        DataTypes::RealVectorType::size_type toff=tptr->getOffsetForTag(i->first);\n                DataTypes::RealVectorType::size_type moff=mptr->getOffsetForTag(i->first);\n                DataTypes::RealVectorType::size_type ooff=optr->getOffsetForTag(i->first);\t      \n                for (int j=0;j<getDataPointSize();++j)\n                {\n                    if (mvec[j+moff]>0)\n                    {\n                        self[j+toff]=ovec[ooff];\n                    }\n                }\n            }\n            // now for the default value\n            for (int j=0;j<getDataPointSize();++j)\n            {\n                if (mvec[j+mptr->getDefaultOffset()]>0)\n                {\n                    self[j+tptr->getDefaultOffset()]=ovec[0];\n                }\n            }\n        }\n\n        return;  // ugly\n    }\n    // mixed scalar and non-scalar operation\n    if ((selfrank>0) && (otherrank==0) && (mask2.getDataPointShape()==getDataPointShape()))\n    {\n        size_t num_points=self.size();\n        // OPENMP 3.0 allows unsigned loop vars.\n        #if defined(_OPENMP) && (_OPENMP < 200805)\n        long i;\n        #else\n        size_t i;\n        #endif  \n        size_t psize=getDataPointSize();        \n        #pragma omp parallel for private(i) schedule(static)\n        for (i=0;i<num_points;++i)\n        {\n            if (mvec[i]>0)\n            {\n                self[i]=ovec[i/psize]; // since this is expanded there is one scalar \n            }                          // dest point\n        } \n        return; // ugly!\n    }\n    // tagged data is already taken care of so we only need to worry about shapes\n    // special cases with scalars are already dealt with so all we need to worry about is shape\n    if ((getDataPointShape()!=other2.getDataPointShape()) || getDataPointShape()!=mask2.getDataPointShape())\n    {\n        ostringstream oss;\n        oss <<\"Error - size mismatch in arguments to copyWithMask.\";\n        oss << \"\\nself_shape=\" << DataTypes::shapeToString(getDataPointShape());\n        oss << \" other2_shape=\" << DataTypes::shapeToString(other2.getDataPointShape());\n        oss << \" mask2_shape=\" << DataTypes::shapeToString(mask2.getDataPointShape());\n        throw DataException(oss.str());\n    }\n    size_t num_points=self.size();\n\n    // OPENMP 3.0 allows unsigned loop vars.\n#if defined(_OPENMP) && (_OPENMP < 200805)\n    long i;\n#else\n    size_t i;\n#endif\n#pragma omp parallel for private(i) schedule(static)\n    for (i=0;i<num_points;++i)\n    {\n        if (mvec[i]>0)\n        {\n            self[i]=ovec[i];\n        }\n    }\n}\n\nbool\nData::isExpanded() const\n{\n    DataExpanded* temp=dynamic_cast<DataExpanded*>(m_data.get());\n    return (temp!=0);\n}\n\nbool\nData::actsExpanded() const\n{\n    return m_data->actsExpanded();\n}\n\n\nbool\nData::isTagged() const\n{\n    DataTagged* temp=dynamic_cast<DataTagged*>(m_data.get());\n    return (temp!=0);\n}\n\nbool\nData::isEmpty() const\n{\n    DataEmpty* temp=dynamic_cast<DataEmpty*>(m_data.get());\n    return (temp!=0);\n}\n\nbool\nData::isConstant() const\n{\n    DataConstant* temp=dynamic_cast<DataConstant*>(m_data.get());\n    return (temp!=0);\n}\n\nbool\nData::isLazy() const\n{\n    return m_lazy;  // not asking m_data because we need to be able to ask this while m_data is changing\n}\n\n// at the moment this is synonymous with !isLazy() but that could change\nbool\nData::isReady() const\n{\n    return (dynamic_cast<DataReady*>(m_data.get())!=0);\n}\n\n\nbool\nData::isComplex() const\n{\n    return m_data->isComplex();\n}\n\nvoid\nData::setProtection()\n{\n    m_protected=true;\n}\n\nbool\nData::isProtected() const\n{\n    return m_protected;\n}\n\n\n\nvoid\nData::expand()\n{\n    if (isConstant()) {\n        DataConstant* tempDataConst=dynamic_cast<DataConstant*>(m_data.get());\n        DataAbstract* temp=new DataExpanded(*tempDataConst);\n        set_m_data(temp->getPtr());\n    } else if (isTagged()) {\n        DataTagged* tempDataTag=dynamic_cast<DataTagged*>(m_data.get());\n        DataAbstract* temp=new DataExpanded(*tempDataTag);\n        set_m_data(temp->getPtr());\n    } else if (isExpanded()) {\n        //\n        // do nothing\n    } else if (isEmpty()) {\n        throw DataException(\"Error - Expansion of DataEmpty not possible.\");\n    } else if (isLazy()) {\n        resolve();\n        expand();   // resolve might not give us expanded data\n    } else {\n        throw DataException(\"Error - Expansion not implemented for this Data type.\");\n    }\n}\n\nvoid\nData::tag()\n{\n    if (isConstant()) {\n        DataConstant* tempDataConst=dynamic_cast<DataConstant*>(m_data.get());\n        DataAbstract* temp=new DataTagged(*tempDataConst);\n        set_m_data(temp->getPtr());\n    } else if (isTagged()) {\n        // do nothing\n    } else if (isExpanded()) {\n        throw DataException(\"Error - Creating tag data from DataExpanded not possible.\");\n    } else if (isEmpty()) {\n        throw DataException(\"Error - Creating tag data from DataEmpty not possible.\");\n    } else if (isLazy()) {\n        DataAbstract_ptr res=m_data->resolve();\n        if (m_data->isExpanded())\n        {\n            throw DataException(\"Error - data would resolve to DataExpanded, tagging is not possible.\");\n        }\n        set_m_data(res);\n        tag();\n    } else {\n        throw DataException(\"Error - Tagging not implemented for this Data type.\");\n    }\n}\n\nvoid\nData::resolve()\n{\n    if (isLazy())\n    {\n        set_m_data(m_data->resolve());\n    }\n}\n\nvoid \nData::requireWrite()\n{\n    resolve();\n    exclusiveWrite();\n}\n\nData\nData::oneOver() const\n{\n    MAKELAZYOP(RECIP);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::RECIP);    \n}\n\nData\nData::wherePositive() const\n{\n    if (isComplex())\n    {\n        throw DataException(\"The wherePositive operation is not supported for complex data.\");\n    }\n    MAKELAZYOP(GZ);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::GZ);    \n}\n\nData\nData::whereNegative() const\n{\n    if (isComplex())\n    {\n        throw DataException(\"The whereNegative operation is not supported for complex data.\");\n    }\n    MAKELAZYOP(LZ);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::LZ);    \n}\n\nData\nData::whereNonNegative() const\n{\n    if (isComplex())\n    {\n        throw DataException(\"The whereNonNegative operation is not supported for complex data.\");\n    }\n    MAKELAZYOP(GEZ);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::GEZ);    \n}\n\nData\nData::whereNonPositive() const\n{\n    if (isComplex())\n    {\n        throw DataException(\"The whereNonPositive operation is not supported for complex data.\");\n    }\n    MAKELAZYOP(LEZ);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::LEZ);\n}\n\nData\nData::whereZero(real_t tol) const\n{\n    MAKELAZYOPOFF(EZ,tol);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::EZ, tol);\n}\n\nData\nData::whereNonZero(real_t tol) const\n{\n    MAKELAZYOPOFF(NEZ,tol);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::NEZ, tol);\n}\n\nData\nData::interpolate(const FunctionSpace& functionspace) const\n{\n    return Data(*this,functionspace);\n}\n\nbool\nData::probeInterpolation(const FunctionSpace& functionspace) const\n{\n    return getFunctionSpace().probeInterpolation(functionspace);\n}\n\nData\nData::gradOn(const FunctionSpace& functionspace) const\n{\n    if (isEmpty())\n    {\n        throw DataException(\"Error - operation not permitted on instances of DataEmpty.\");\n    }\n    if (functionspace.getDomain()!=getDomain())\n        throw DataException(\"Error - gradient cannot be calculated on different domains.\");\n    DataTypes::ShapeType grad_shape=getDataPointShape();\n    grad_shape.push_back(functionspace.getDim());\n    Data out(0.0,grad_shape,functionspace,true);\n    if (isComplex())\n        out.complicate();    \n    if (isLazy() && isComplex())\n    {\n        Data temp(*this);\n        temp.resolve();     // since lazy complex is not a thing       \n        getDomain()->setToGradient(out, temp);\n    } \n    else\n    {\n        getDomain()->setToGradient(out,*this);\n    }\n    return out;\n}\n\nData\nData::grad() const\n{\n    if (isEmpty())\n    {\n        throw DataException(\"Error - operation not permitted on instances of DataEmpty.\");\n    }\n    return gradOn(escript::function(*getDomain()));\n}\n\nint\nData::getDataPointSize() const\n{\n    return m_data->getNoValues();\n}\n\n\nDataTypes::RealVectorType::size_type\nData::getLength() const\n{\n    return m_data->getLength();\n}\n\n\n// There is no parallelism here ... elements need to be added in the correct order.\n//   If we could pre-size the list and then fill in the elements it might work\n//   This would need setting elements to be threadsafe.\n//   Having multiple C threads calling into one interpreter is apparently a no-no.\nconst bp::object\nData::toListOfTuples(bool scalarastuple)\n{\n    if (get_MPISize()>1)\n    {\n        throw DataException(\"::toListOfTuples is not available for MPI with more than one process.\");\n    }\n    unsigned int rank=getDataPointRank();\n    unsigned int size=getDataPointSize();\n\n    int npoints=getNumDataPoints();\n    expand();                   // This will also resolve if required\n    bp::list temp;\n    temp.append(bp::object());\n    bp::list res(temp*npoints);// pre-size the list by the \"[None] * npoints\"  trick\n    if (isComplex())\n    {\n        const DataTypes::CplxVectorType& vec=getReady()->getTypedVectorRO(cplx_t(0));\n        if (rank==0)\n        {\n            long count;\n            if (scalarastuple)\n            {\n                for (count=0;count<npoints;++count)\n                {\n                    res[count]=bp::make_tuple(vec[count]);\n                }\n            }\n            else\n            {\n                for (count=0;count<npoints;++count)\n                {\n                    res[count]=vec[count];\n                }\n            }\n        }\n        else if (rank==1)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple1(getDataPointShape(), vec, offset);\n            }\n        }\n        else if (rank==2)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple2(getDataPointShape(), vec, offset);\n            }\n        }\n        else if (rank==3)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple3(getDataPointShape(), vec, offset);\n            }\n        }\n        else if (rank==4)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple4(getDataPointShape(), vec, offset);\n            }\n        }\n        else\n        {\n            throw DataException(\"Unknown rank in ::toListOfTuples()\");\n        }      \n    }\n    else\n    {\n        const DataTypes::RealVectorType& vec=getReady()->getVectorRO();\n        if (rank==0)\n        {\n            long count;\n            if (scalarastuple)\n            {\n                for (count=0;count<npoints;++count)\n                {\n                    res[count]=bp::make_tuple(vec[count]);\n                }\n            }\n            else\n            {\n                for (count=0;count<npoints;++count)\n                {\n                    res[count]=vec[count];\n                }\n            }\n        }\n        else if (rank==1)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple1(getDataPointShape(), vec, offset);\n            }\n        }\n        else if (rank==2)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple2(getDataPointShape(), vec, offset);\n            }\n        }\n        else if (rank==3)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple3(getDataPointShape(), vec, offset);\n            }\n        }\n        else if (rank==4)\n        {\n            size_t count;\n            size_t offset=0;\n            for (count=0;count<npoints;++count,offset+=size)\n            {\n                res[count]=pointToTuple4(getDataPointShape(), vec, offset);\n            }\n        }\n        else\n        {\n            throw DataException(\"Unknown rank in ::toListOfTuples()\");\n        }\n    }\n    return res;\n}\n\nconst bp::object\nData::getValueOfDataPointAsTuple(int dataPointNo)\n{\n    forceResolve();\n    if (getNumDataPointsPerSample()>0) {\n        int sampleNo = dataPointNo/getNumDataPointsPerSample();\n        int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();\n        //\n        // Check a valid sample number has been supplied\n        if ((sampleNo >= getNumSamples()) || (sampleNo < 0 )) {\n            throw DataException(\"Error - Data::getValueOfDataPointAsTuple: invalid sampleNo.\");\n        }\n\n        //\n        // Check a valid data point number has been supplied\n        if ((dataPointNoInSample >= getNumDataPointsPerSample()) || (dataPointNoInSample < 0)) {\n            throw DataException(\"Error - Data::getValueOfDataPointAsTuple: invalid dataPointNoInSample.\");\n        }\n        // TODO: global error handling\n        if (isComplex())\n\t{\n\t    DataTypes::CplxVectorType::size_type offset=getDataOffset(sampleNo, dataPointNoInSample);\n\t    return pointToTuple(getDataPointShape(),&(getDataAtOffsetRO(offset, cplx_t(0))));\n\t}\n\telse\n\t{\n\t    DataTypes::RealVectorType::size_type offset=getDataOffset(sampleNo, dataPointNoInSample);\n\t    return pointToTuple(getDataPointShape(),&(getDataAtOffsetRO(offset, real_t(0))));\n\t}\n    }\n    else\n    {\n        // The pre-numpy method would return an empty array of the given shape\n        // I'm going to throw an exception because if we have zero points per sample we have problems\n        throw DataException(\"Error - need at least 1 datapoint per sample.\");\n    }\n}\n\n\nvoid\nData::setValueOfDataPointToPyObject(int dataPointNo, const bp::object& py_object)\n{\n    // this will throw if the value cannot be represented\n    setValueOfDataPointToArray(dataPointNo,py_object);\n}\n\n\nvoid\nData::setTupleForGlobalDataPoint(int id, int proc, bp::object v)\n{\n    THROWONCOMPLEX\n#ifdef ESYS_MPI \n    int error=0;\n#endif\n    if( get_MPIRank()==proc )\n    {\n        try\n        {\n            bp::extract<real_t> dex(v);\n            if (dex.check())\n            {\n                setValueOfDataPoint(id, dex());\n            }\n            else\n            {\n                setValueOfDataPointToArray(id, v);          \n            }\n        } \n        catch (...)\n        {\n#ifdef ESYS_MPI \n            error=1;\n            int e2;\n            MPI_Allreduce( &error, &e2, 1, MPI_INT, MPI_SUM, getDomain()->getMPIComm() );      \n#endif      \n            // participate in gather\n            throw;\n        }\n    }\n#ifdef ESYS_MPI\n    int e2;\n    // If we get here, then either we succeeded or it was on another rank\n    MPI_Allreduce( &error, &e2, 1, MPI_INT, MPI_MAX, getDomain()->getMPIComm() );       \n    // participate in gather\n    if (e2)\n    {\n        throw DataException(\"Error in another rank performing setTupleForGlobalDataPoint\");      \n    }\n#endif    \n}\n\n\nvoid\nData::setValueOfDataPointToArray(int dataPointNo, const bp::object& obj)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n\n    WrappedArray w(obj);\n    if (w.isComplex() && (static_cast<unsigned int>(w.getRank())==0))\n    {\n\tcplx_t v=w.getEltC();\n\tsetValueOfDataPointC(dataPointNo, v);\n\treturn;\n    }\n    //\n    // check rank\n    if (static_cast<unsigned int>(w.getRank())<getDataPointRank())\n        throw DataException(\"Rank of array does not match Data object rank\");\n\n    //\n    // check shape of array\n    for (unsigned int i=0; i<getDataPointRank(); i++) {\n        if (w.getShape()[i]!=getDataPointShape()[i])\n            throw DataException(\"Shape of array does not match Data object rank\");\n    }\n\n    exclusiveWrite();\n\n    //\n    // make sure data is expanded:\n    //\n    if (!isExpanded()) {\n        expand();\n    }\n    if (getNumDataPointsPerSample()>0) {\n        int sampleNo = dataPointNo/getNumDataPointsPerSample();\n        int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();\n        m_data->copyToDataPoint(sampleNo, dataPointNoInSample,w);\n    } else {\n        m_data->copyToDataPoint(-1, 0,w);\n    }\n}\n\nvoid\nData::setValueOfDataPoint(int dataPointNo, const real_t value)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    //\n    // make sure data is expanded:\n    exclusiveWrite();\n    if (!isExpanded()) {\n        expand();\n    }\n    if (getNumDataPointsPerSample()>0) {\n        int sampleNo = dataPointNo/getNumDataPointsPerSample();\n        int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();\n        m_data->copyToDataPoint(sampleNo, dataPointNoInSample,value);\n    } else {\n        m_data->copyToDataPoint(-1, 0,value);\n    }\n}\n\nvoid\nData::setValueOfDataPointC(int dataPointNo, const cplx_t value)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    //\n    // make sure data is expanded:\n    exclusiveWrite();\n    if (!isExpanded()) {\n        expand();\n    }\n    if (getNumDataPointsPerSample()>0) {\n        int sampleNo = dataPointNo/getNumDataPointsPerSample();\n        int dataPointNoInSample = dataPointNo - sampleNo * getNumDataPointsPerSample();\n        m_data->copyToDataPoint(sampleNo, dataPointNoInSample,value);\n    } else {\n        m_data->copyToDataPoint(-1, 0,value);\n    }\n}\n\n\nconst\nbp::object\nData::getValueOfGlobalDataPointAsTuple(int procNo, int dataPointNo)\n{\n\n    // copy datapoint into a buffer\n    // broadcast buffer to all nodes\n    // convert buffer to tuple\n    // return tuple\n\n    bp::tuple t;\n\n    // This could be lazier than it is now\n    forceResolve();\n\n    int ndpps = getNumDataPointsPerSample();\n    int sampleNo = dataPointNo/ndpps;\n    int dataPointNoInSample = dataPointNo - sampleNo * ndpps;\n\n    const DataTypes::ShapeType& dataPointShape = getDataPointShape();\n    size_t length=DataTypes::noValues(dataPointShape);\n\n    // TODO: global error handling\n    if (get_MPIRank() == procNo && ndpps > 0 && ((sampleNo >= getNumSamples()) || (sampleNo < 0 ))) {\n        throw DataException(\"Error - Data::getValueOfGlobalDataPointAsTuple: invalid sampleNo.\");\n    }\n\n    if (get_MPIRank() == procNo && ndpps > 0 && ((dataPointNoInSample >= ndpps) || (dataPointNoInSample < 0))) {\n        throw DataException(\"Error - Data::getValueOfGlobalDataPointAsTuple: invalid dataPointNoInSample.\");\n    }\n\n    if(isComplex()){\n\n        cplx_t *tmpData = new cplx_t[length];\n\n        if( get_MPIRank() == procNo && ndpps > 0){\n            DataTypes::CplxVectorType::size_type offset = getDataOffset(sampleNo, dataPointNoInSample);\n            memcpy(tmpData,&(getDataAtOffsetRO(offset, static_cast<DataTypes::cplx_t>(0))), length*sizeof(cplx_t));\n        }\n\n        #ifdef ESYS_MPI\n            // broadcast the data to all other processes\n            MPI_Bcast(tmpData, length, MPI_DOUBLE_COMPLEX, procNo, get_MPIComm());\n        #endif\n\n        t = pointToTuple(dataPointShape,tmpData);\n        delete [] tmpData;\n\n    } else {\n\n        real_t *tmpData = new real_t[length];\n\n        if( get_MPIRank() == procNo && ndpps > 0){\n            DataTypes::RealVectorType::size_type offset = getDataOffset(sampleNo, dataPointNoInSample);\n            memcpy(tmpData,&(getDataAtOffsetRO(offset, static_cast<DataTypes::real_t>(0))), length*sizeof(real_t));\n        }\n\n        #ifdef ESYS_MPI\n            // broadcast the data to all other processes\n            MPI_Bcast(tmpData, length, MPI_DOUBLE, procNo, get_MPIComm());\n        #endif\n\n        t = pointToTuple(dataPointShape,tmpData);\n        delete [] tmpData;\n\n    }\n    \n    // return the loaded array\n    return t;\n}\n\n\nbp::object\nData::integrateToTuple_const() const\n{\n    if (isLazy())\n    {\n        throw DataException(\"Error - cannot integrate for constant lazy data.\");\n    }\n    if (isComplex()) {\n        return integrateWorker<cplx_t>();\n    } else {\n        return integrateWorker<real_t>();\n    }\n}\n\nbp::object\nData::integrateToTuple()\n{\n    if (isLazy())\n    {\n        expand();       // Can't do a non-resolving version of this without changing the domain object\n    }                     // see the dom->setToIntegrals call. Not saying it can't be done, just not doing it yet.\n    if (isComplex()) {\n        return integrateWorker<cplx_t>();\n    } else {\n        return integrateWorker<real_t>();\n    }\n}\n\ntemplate<typename Scalar>\nbp::object\nData::integrateWorker() const\n{\n    DataTypes::ShapeType shape = getDataPointShape();\n    int dataPointSize = getDataPointSize();\n\n    //\n    // calculate the integral values\n    vector<Scalar> integrals(dataPointSize);\n    vector<Scalar> integrals_local(dataPointSize);\n    const AbstractContinuousDomain* dom=dynamic_cast<const AbstractContinuousDomain*>(getDomain().get());\n    if (dom == 0)\n    {                             \n        throw DataException(\"Can not integrate over non-continuous domains.\");\n    }\n   \n#ifdef ESYS_MPI\n    if (isLazy() && isComplex())\n    {\n        Data temp(*this);\n        temp.resolve();\n        dom->setToIntegrals(integrals_local, temp);\n    }\n    else\n    {\n        dom->setToIntegrals(integrals_local, *this);\n    }\n    \n    // Global sum: use an array instead of a vector because elements of array are guaranteed to be contiguous in memory\n    Scalar* tmp = new Scalar[dataPointSize];\n    Scalar* tmp_local = new Scalar[dataPointSize];\n    for (int i=0; i<dataPointSize; i++) { tmp_local[i] = integrals_local[i]; }\n    if (sizeof(Scalar) == sizeof(double)) {\n        MPI_Allreduce(&tmp_local[0], &tmp[0], dataPointSize, MPI_DOUBLE, MPI_SUM, getDomain()->getMPIComm());\n    } else {\n        MPI_Allreduce(&tmp_local[0], &tmp[0], dataPointSize, MPI_DOUBLE_COMPLEX, MPI_SUM, getDomain()->getMPIComm());\n    }\n    for (int i=0; i<dataPointSize; i++) { integrals[i] = tmp[i]; }\n    bp::tuple result = pointToTuple(shape, tmp);\n    delete[] tmp;\n    delete[] tmp_local;\n#else\n    if (isLazy() && isComplex())\n    {\n        Data temp(*this);\n        temp.resolve();\n        dom->setToIntegrals(integrals, temp);\n    }\n    else\n    {\n        dom->setToIntegrals(integrals, *this);\n    }\n    bp::tuple result = pointToTuple(shape, integrals);\n#endif\n\n    return result;\n}\n\nData\nData::besselFirstKind(int order)\n{\n    THROWONCOMPLEX\n    return bessel(order,boost::math::cyl_bessel_j);\n}\n\nData\nData::besselSecondKind(int order)\n{\n    THROWONCOMPLEX\n    return bessel(order,boost::math::cyl_neumann);\n}\n\nData\nData::bessel(int order, real_t (*besselfunc) (int,real_t) )\n{\n    THROWONCOMPLEX\n    DataTypes::real_t wantreal=0;\n    if (isEmpty())  // do this before we attempt to interpolate\n    {\n     throw DataException(\"Error - Operations (bessel) not permitted on instances of DataEmpty.\");\n    }\n    if (isLazy())\n    {\n        resolve();\n    }\n    // Interpolate if necessary and find an appropriate function space\n    Data arg_0_Z = Data(*this);\n\n    // Get rank and shape of inputs\n    const DataTypes::ShapeType& shape0 = arg_0_Z.getDataPointShape();\n    int size0 = arg_0_Z.getDataPointSize();\n\n    // Declare output Data object\n    Data res;\n\n    if (arg_0_Z.isConstant()) {\n        res = Data(0.0, shape0, arg_0_Z.getFunctionSpace(),false);      // DataConstant output\n        const real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(0, wantreal));\n        real_t *ptr_2 = &(res.getDataAtOffsetRW(0, wantreal));\n        for (int i = 0; i < size0; ++i) {\n            ptr_2[i] = besselfunc(order, ptr_0[i]);\n        }\n    }\n    else if (arg_0_Z.isTagged()) {\n\n        // Borrow DataTagged input from Data object\n        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());\n\n        // Prepare a DataTagged output 2\n        res = Data(0.0, shape0, arg_0_Z.getFunctionSpace(), false);   // DataTagged output\n        res.tag();\n        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());\n\n        // Get the pointers to the actual data\n        const real_t *ptr_0 = &(tmp_0->getDefaultValueRO(0, wantreal));\n        real_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, wantreal));\n        // Compute a result for the default\n        for (int i = 0; i < size0; ++i) {\n            ptr_2[i] = besselfunc(order, ptr_0[i]);\n        }\n        // Compute a result for each tag\n        const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n        for (i=lookup_0.begin();i!=lookup_0.end();i++) {\n            tmp_2->addTag(i->first);\n            const real_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0));\n            real_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0));\n            for (int i = 0; i < size0; ++i) {\n                ptr_2[i] = besselfunc(order, ptr_0[i]);\n            }\n\n        }\n\n    }\n    else if (arg_0_Z.isExpanded()) {\n\n        res = Data(0.0, shape0, arg_0_Z.getFunctionSpace(),true); // DataExpanded output\n        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());\n        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());\n\n        int sampleNo_0,dataPointNo_0;\n        int numSamples_0 = arg_0_Z.getNumSamples();\n        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();\n\tDataTypes::real_t wantreal=0;\n        #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n        for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n            dataPointNo_0=0;\n        //      for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n            int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n            int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n            const real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, wantreal));\n            real_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, wantreal));\n            for (int i = 0; i < size0*numDataPointsPerSample_0; ++i) {\n                ptr_2[i] = besselfunc(order, ptr_0[i]);\n            }\n        //      }\n        }\n  }\n  else {\n    throw DataException(\"Error - Bessel function: unknown combination of inputs\");\n  }\n\n  return res;\n}\n\nData\nData::conjugate() const\n{\n    if (isLazy())\n    {\n        Data temp(*this);\n        temp.resolve();\n        return temp.conjugate();\n    }\n    if (isComplex())\n    {\n        return C_TensorUnaryOperation(*this, escript::ES_optype::CONJ);      \n    }\n    else\n    {\n        return copySelf();\n    }\n}\n\n\nData\nData::real() const\n{\n    if (isLazy())\n    {\n        Data temp(*this);\n        temp.resolve();\n        return temp.real();\n    }\n    if (isComplex())\n    {\n        return C_TensorUnaryOperation(*this, escript::ES_optype::REAL);      \n    }\n    else\n    {\n        return copySelf();\n    }\n}\n\nData\nData::imag() const\n{\n    if (isLazy())\n    {\n        Data temp(*this);\n        temp.resolve();\n        return temp.imag();\n    }\n    if (isComplex())\n    {\n        return C_TensorUnaryOperation(*this, escript::ES_optype::IMAG);      \n    }\n    else\n    {\n        return copySelf()*Data(0, m_data->getShape(), getFunctionSpace(),false);      // return an object with same tags etc but all values 0\n                                // This is not efficient, but why are you taking imag of R anyway?\n    }\n}\n\nData\nData::phase() const\n{\n    if (isLazy())\n    {\n        Data temp(*this);\n        temp.resolve();\n        return temp.phase();\n    }\n    if (isComplex())\n    {\n        return C_TensorUnaryOperation(*this, escript::ES_optype::PHS);      \n    }\n    else\n    {\n        return whereNegative()*Data(M_PI, DataTypes::scalarShape, getFunctionSpace(), false);\n    }\n}\n\n\n\n\n\nData\nData::sin() const\n{\n    MAKELAZYOP(SIN);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::SIN);\n}\n\nData\nData::cos() const\n{\n    MAKELAZYOP(COS);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::COS);\n}\n\nData\nData::tan() const\n{\n    MAKELAZYOP(TAN);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::TAN);\n}\n\nData\nData::asin() const\n{\n    MAKELAZYOP(ASIN);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ASIN);\n}\n\nData\nData::acos() const\n{\n    MAKELAZYOP(ACOS);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ACOS);\n}\n\n\nData\nData::atan() const\n{\n    MAKELAZYOP(ATAN);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ATAN);\n}\n\nData\nData::sinh() const\n{\n    MAKELAZYOP(SINH);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::SINH);\n}\n\nData\nData::cosh() const\n{\n    MAKELAZYOP(COSH);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::COSH);\n}\n\nData\nData::tanh() const\n{\n    MAKELAZYOP(TANH);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::TANH);\n}\n\n\nData\nData::erf() const\n{\n#if defined (_WIN32) && !defined(__INTEL_COMPILER)\n    throw DataException(\"Error - Data:: erf function is not supported on _WIN32 platforms.\");\n#else\n    MAKELAZYOP(ERF);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ERF);\n#endif\n}\n\nData\nData::asinh() const\n{\n    MAKELAZYOP(ASINH);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ASINH);\n}\n\nData\nData::acosh() const\n{\n    MAKELAZYOP(ACOSH);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ACOSH);    \n}\n\nData\nData::atanh() const\n{\n    MAKELAZYOP(ATANH);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ATANH); \n}\n\nData\nData::log10() const\n{\n    MAKELAZYOP(LOG10);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::LOG10);\n}\n\nData\nData::log() const\n{\n    MAKELAZYOP(LOG);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::LOG);\n}\n\nData\nData::sign() const\n{\n    THROWONCOMPLEX\n    MAKELAZYOP(SIGN);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::SIGN);\n}\n\nData\nData::abs() const\n{\n    MAKELAZYOP(ABS);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::ABS);\n}\n\nData\nData::neg() const\n{\n    MAKELAZYOP(NEG);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::NEG);\n}\n\nData\nData::pos() const\n{\n    THROWONCOMPLEX\n    // not doing lazy check here is deliberate.\n    // since a deep copy of lazy data should be cheap, I'll just let it happen now\n    Data result;\n    // perform a deep copy\n    result.copy(*this);\n    return result;\n}\n\nData\nData::exp() const\n{\n    MAKELAZYOP(EXP);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::EXP);\n}\n\nData\nData::sqrt() const\n{\n    MAKELAZYOP(SQRT);\n    return C_TensorUnaryOperation(*this, escript::ES_optype::SQRT);\n}\n\nreal_t\nData::Lsup_const() const\n{\n    if (isLazy())\n    {\n        throw DataException(\"Error - cannot compute Lsup for constant lazy data.\");\n    }\n    return LsupWorker();\n}\n\nreal_t\nData::Lsup() \n{\n    if (isLazy())\n    {\n        if (!actsExpanded() || CHECK_DO_CRES)\n        {\n            resolve();\n        }\n        else\n        {\n#ifdef ESYS_MPI\n            if (isComplex())\n            {\n                return lazyAlgWorker<AbsMax<cplx_t> >(0,MPI_MAX);\n            }\n            else\n            {\n                return lazyAlgWorker<AbsMax<real_t> >(0,MPI_MAX);             \n            }\n#else\n            if (isComplex())\n            {\n                return lazyAlgWorker<AbsMax<cplx_t> >(0);\n            }\n            else\n            {\n                return lazyAlgWorker<AbsMax<real_t> >(0);\n            }\n#endif\n        }\n    }\n    return LsupWorker();\n}\n\nreal_t\nData::sup_const() const\n{\n    if (isComplex())\n    {\n        throw DataException(\"Error Cannot compute sup() for complex data.\");\n    }  \n    if (isLazy())\n    {\n        throw DataException(\"Error - cannot compute sup for constant lazy data.\");\n    }\n    return supWorker();\n}\n\nreal_t\nData::sup() \n{\n    if (isComplex())\n    {\n        throw DataException(\"Error Cannot compute sup() for complex data.\");\n    }\n    if (isLazy())\n    {\n        if (!actsExpanded() || CHECK_DO_CRES)\n        {\n            resolve();\n        }\n        else\n        {\n#ifdef ESYS_MPI\n            return lazyAlgWorker<FMax>(numeric_limits<real_t>::max()*-1, MPI_MAX);\n#else\n            return lazyAlgWorker<FMax>(numeric_limits<real_t>::max()*-1);\n#endif\n        }\n    }\n    return supWorker();\n}\n\nreal_t\nData::inf_const() const\n{\n    if (isComplex())\n    {\n        throw DataException(\"Error Cannot compute inf() for complex data.\");\n    }  \n    if (isLazy())\n    {\n        throw DataException(\"Error - cannot compute inf for constant lazy data.\");\n    }\n    return infWorker();\n}\n\nreal_t\nData::inf() \n{\n    if (isComplex())\n    {\n        throw DataException(\"Error Cannot compute inf() for complex data.\");\n    }  \n    if (isLazy())\n    {\n        if (!actsExpanded() || CHECK_DO_CRES)\n        {\n            resolve();\n        }\n        else\n        {\n#ifdef ESYS_MPI\n            return lazyAlgWorker<FMin>(numeric_limits<real_t>::max(), MPI_MIN);\n#else\n            return lazyAlgWorker<FMin>(numeric_limits<real_t>::max());\n#endif\n        }\n    }\n    return infWorker();\n}\n\ntemplate <class BinaryOp>\nreal_t\n#ifdef ESYS_MPI\nData::lazyAlgWorker(real_t init, MPI_Op mpiop_type)\n#else\nData::lazyAlgWorker(real_t init)\n#endif\n{\n    if (!isLazy() || !m_data->actsExpanded())\n    {\n        throw DataException(\"Error - lazyAlgWorker can only be called on lazy(expanded) data.\");\n    }\n    DataLazy* dl=dynamic_cast<DataLazy*>(m_data.get());\n    ESYS_ASSERT(dl!=NULL, \"Programming error - casting to DataLazy.\");\n    real_t val=init;\n    int i=0;\n    const size_t numsamples=getNumSamples();\n    const size_t samplesize=getNoValues()*getNumDataPointsPerSample();\n    BinaryOp operation;\n    real_t localValue=0, globalValue;    \n    #pragma omp parallel private(i)\n    {\n        real_t localtot=init;\n        #pragma omp for schedule(static) private(i)\n        for (i=0;i<numsamples;++i)\n        {\n            size_t roffset=0;\n            auto v=dl->resolveTypedSample(i, roffset, typename BinaryOp::second_argument_type(0));\n            // Now we have the sample, run operation on all points\n            for (size_t j=0;j<samplesize;++j)\n            {\n                localtot=operation(localtot,(*v)[j+roffset]);\n            }\n            if (escript::vectorHasNaN(*v,roffset, samplesize))\n            {\n                #pragma omp critical\n                {\n                    localValue=1.0;\n                }\n            }\n        }\n        #pragma omp critical\n        val=operation(val,localtot);\n    }\n#ifdef ESYS_MPI\n    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, getDomain()->getMPIComm() );\n#else\n    globalValue=localValue;\n#endif\n    if (globalValue!=0)\n    {\n        return makeNaN();\n    }\n#ifdef ESYS_MPI\n    MPI_Allreduce( &val, &globalValue, 1, MPI_DOUBLE, mpiop_type, getDomain()->getMPIComm() );\n    return globalValue;\n#else\n    return val;\n#endif\n}\n\nbool\nData::hasNaN()\n{\n    if (isLazy())\n    {\n        resolve();\n    }\n    bool haveNaN=getReady()->hasNaN(); \n    return haveNaN;\n}\n\nvoid\nData::replaceNaN(real_t value)\n{\n    if (isLazy())\n    {\n        resolve();\n    }\n    getReady()->replaceNaN(value); \n}\n\nvoid\nData::replaceNaN(cplx_t value)\n{\n    if (isLazy())\n    {\n        resolve();\n    }\n    getReady()->replaceNaN(value); \n}\n\nvoid\nData::replaceNaNPython(boost::python::object obj)\n{\n    boost::python::extract<DataTypes::real_t> exr(obj);\n    if (exr.check())\n    {\n\treplaceNaN(exr());\n    }\n    else\n    {\n\treplaceNaN(boost::python::extract<DataTypes::cplx_t>(obj)());\n    }\n}\n\nbool\nData::hasInf()\n{\n    if (isLazy())\n    {\n        resolve();\n    }\n    bool haveInf=getReady()->hasInf(); \n    return haveInf;\n}\n\nvoid\nData::replaceInf(real_t value)\n{\n    if (isLazy())\n    {\n        resolve();\n    }\n    getReady()->replaceInf(value); \n}\n\nvoid\nData::replaceInf(cplx_t value)\n{\n    if (isLazy())\n    {\n        resolve();\n    }\n    getReady()->replaceInf(value); \n}\n\nvoid\nData::replaceInfPython(boost::python::object obj)\n{\n    boost::python::extract<DataTypes::real_t> exr(obj);\n    if (exr.check())\n    {\n\treplaceInf(exr());\n    }\n    else\n    {\n\treplaceInf(boost::python::extract<DataTypes::cplx_t>(obj)());\n    }\n}\n\n// Do not call this on Lazy Data use the proper entry point\nreal_t\nData::LsupWorker() const\n{\n    bool haveNaN=getReady()->hasNaN();\n\n  \n#ifdef ESYS_MPI\n    int nanchecker=0;    \n    if (haveNaN)\n    {\n        nanchecker=1.0;\n    }\n    int globalnan;\n    MPI_Allreduce( &nanchecker, &globalnan, 1, MPI_INT, MPI_MAX, getDomain()->getMPIComm() );\n    if (globalnan!=0)\n    {\n        return makeNaN();\n    }\n#else\n    if (haveNaN) \n    {\n        return makeNaN();\n    }\n#endif\n\n    //\n    // set the initial absolute maximum value to zero\n    if (isComplex())\n    {\n        AbsMax<cplx_t> abs_max_func;\n        real_t localValue=0;\n        localValue = reduction(abs_max_func,0);\n\n    #ifdef ESYS_MPI\n        real_t globalValue=0;\n        MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, getDomain()->getMPIComm() );\n        return globalValue;\n    #else\n        return localValue;\n    #endif\n    }\n    else\n    {  \n        AbsMax<real_t> abs_max_func;\n        real_t localValue=0;\n        localValue = reduction(abs_max_func,0);\n\n    #ifdef ESYS_MPI\n        real_t globalValue=0;   \n        MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, getDomain()->getMPIComm() );\n        return globalValue;\n    #else\n        return localValue;\n    #endif\n    }\n}\n\nreal_t\nData::supWorker() const\n{\n    bool haveNaN=getReady()->hasNaN();\n    real_t localValue=0;\n\n#ifdef ESYS_MPI\n    if (haveNaN)\n    {\n        localValue=1.0;\n    }\n    real_t globalValue;\n    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, getDomain()->getMPIComm() );\n    if (globalValue!=0)\n    {\n        return makeNaN();\n    }\n#else\n    if (haveNaN) \n    {\n        return makeNaN();\n    }\n#endif\n\n    //\n    // set the initial maximum value to min possible real_t\n    FMax fmax_func;\n    if (hasNoSamples())\n    {\n\tlocalValue = numeric_limits<real_t>::infinity()*-1;\n    }\n    else\n    {\n\tlocalValue = reduction(fmax_func,numeric_limits<real_t>::infinity()*-1);      \n    }\n    #ifdef ESYS_MPI\n    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, getDomain()->getMPIComm() );\n    return globalValue;\n#else\n    return localValue;\n#endif\n}\n\nreal_t\nData::infWorker() const\n{\n    bool haveNaN=getReady()->hasNaN();\n    real_t localValue=0;\n\n#ifdef ESYS_MPI\n    if (haveNaN)\n    {\n        localValue=1.0;\n    }\n    real_t globalValue;\n    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MAX, getDomain()->getMPIComm() );\n    if (globalValue!=0)\n    {\n        return makeNaN();\n    }\n#else\n    if (haveNaN) \n    {\n        return makeNaN();\n    }\n#endif\n    //\n    // set the initial minimum value to max possible real_t\n    FMin fmin_func;\n    if (hasNoSamples())\n    {\n\tlocalValue = numeric_limits<real_t>::infinity();\n    }\n    else\n    {\n\tlocalValue = reduction(fmin_func,numeric_limits<real_t>::infinity());\n    }\n#ifdef ESYS_MPI\n    MPI_Allreduce( &localValue, &globalValue, 1, MPI_DOUBLE, MPI_MIN, getDomain()->getMPIComm() );\n    return globalValue;\n#else\n    return localValue;\n#endif\n}\n\n/* global reduction */\n\n\ninline Data\nData::minval_nonlazy() const\n{\n    THROWONCOMPLEX\n    //\n    // set the initial minimum value to max possible real_t\n    FMin fmin_func;\n    return dp_algorithm(fmin_func,numeric_limits<real_t>::max());\n}\n\n\ninline Data\nData::maxval_nonlazy() const\n{\n    THROWONCOMPLEX\n    //\n    // set the initial maximum value to min possible real_t\n    FMax fmax_func;\n    return dp_algorithm(fmax_func,numeric_limits<real_t>::max()*-1);\n}\n\n\nData\nData::maxval() const\n{\n    THROWONCOMPLEX\n    MAKELAZYOP(MAXVAL);\n    return maxval_nonlazy();\n}\n\n\nData\nData::minval() const\n{\n    THROWONCOMPLEX\n    MAKELAZYOP(MINVAL);\n    return minval_nonlazy();\n}\n\n\nData\nData::swapaxes(const int axis0, const int axis1) const\n{\n    int axis0_tmp,axis1_tmp;\n    DataTypes::ShapeType s=getDataPointShape();\n    DataTypes::ShapeType ev_shape;\n    // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]\n    // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)\n    int rank=getDataPointRank();\n    if (rank<2) {\n        throw DataException(\"Error - Data::swapaxes argument must have at least rank 2.\");\n    }\n    if (axis0<0 || axis0>rank-1) {\n        stringstream e;\n        e << \"Error - Data::swapaxes: axis0 must be between 0 and rank-1=\" << (rank-1);\n        throw DataException(e.str());\n    }\n    if (axis1<0 || axis1>rank-1) {\n        stringstream e;\n        e << \"Error - Data::swapaxes: axis1 must be between 0 and rank-1=\" << (rank-1);\n        throw DataException(e.str());\n    }\n    if (axis0 == axis1) {\n         throw DataException(\"Error - Data::swapaxes: axis indices must be different.\");\n    }\n    MAKELAZYOP2(SWAP,axis0,axis1);\n    if (axis0 > axis1)\n    {\n        axis0_tmp=axis1;\n        axis1_tmp=axis0;\n    }\n    else\n    {\n        axis0_tmp=axis0;\n        axis1_tmp=axis1;\n    }\n    for (int i=0; i<rank; i++)\n    {\n        if (i == axis0_tmp)\n        {\n            ev_shape.push_back(s[axis1_tmp]);\n        } \n        else if (i == axis1_tmp)\n        {\n            ev_shape.push_back(s[axis0_tmp]);\n        }\n        else\n        {\n            ev_shape.push_back(s[i]);\n        }\n    }\n    Data ev(0.,ev_shape,getFunctionSpace(), false);\n    ev.typeMatchRight(*this);\n    m_data->swapaxes(ev.m_data.get(), axis0_tmp, axis1_tmp);\n    return ev;\n}\n\nData\nData::symmetric() const\n{\n    // check input\n    DataTypes::ShapeType s=getDataPointShape();\n    if (getDataPointRank()==2) {\n        if(s[0] != s[1])\n            throw DataException(\"Error - Data::symmetric can only be calculated for rank 2 object with equal first and second dimension.\");\n    }\n    else if (getDataPointRank()==4) {\n        if(!(s[0] == s[2] && s[1] == s[3]))\n            throw DataException(\"Error - Data::symmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.\");\n    }\n    else {\n        throw DataException(\"Error - Data::symmetric can only be calculated for rank 2 or 4 object.\");\n    }\n    MAKELAZYOP(SYM);\n    Data ev(0.,getDataPointShape(),getFunctionSpace(), false);\n    ev.typeMatchRight(*this);\n    m_data->symmetric(ev.m_data.get());\n    return ev;\n}\n\nData\nData::antisymmetric() const\n{\n    // check input\n    DataTypes::ShapeType s=getDataPointShape();\n    if (getDataPointRank()==2) {\n        if(s[0] != s[1])\n            throw DataException(\"Error - Data::antisymmetric can only be calculated for rank 2 object with equal first and second dimension.\");\n\tMAKELAZYOP(NSYM);\n        DataTypes::ShapeType ev_shape;\n        ev_shape.push_back(s[0]);\n        ev_shape.push_back(s[1]);\n        Data ev(0.,ev_shape,getFunctionSpace(),false);\n        ev.typeMatchRight(*this);\n        m_data->antisymmetric(ev.m_data.get());\n        return ev;\n    }\n    else if (getDataPointRank()==4) {\n        if(!(s[0] == s[2] && s[1] == s[3]))\n            throw DataException(\"Error - Data::antisymmetric can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.\");\n\tMAKELAZYOP(NSYM);\n        DataTypes::ShapeType ev_shape;\n        ev_shape.push_back(s[0]);\n        ev_shape.push_back(s[1]);\n        ev_shape.push_back(s[2]);\n        ev_shape.push_back(s[3]);\n        Data ev(0.,ev_shape,getFunctionSpace(),false);\n        ev.typeMatchRight(*this);\n        m_data->antisymmetric(ev.m_data.get());\n        return ev;\n    }\n    else {\n        throw DataException(\"Error - Data::antisymmetric can only be calculated for rank 2 or 4 object.\");\n    }\n}\n\nData\nData::hermitian() const\n{\n    if (!isComplex())\n    {\n        return symmetric();\n    }\n    // check input\n    DataTypes::ShapeType s=getDataPointShape();\n    if (getDataPointRank()==2) {\n        if(s[0] != s[1])\n            throw DataException(\"Error - Data::hermitian can only be calculated for rank 2 object with equal first and second dimension.\");\n    }\n    else if (getDataPointRank()==4) {\n        if(!(s[0] == s[2] && s[1] == s[3]))\n            throw DataException(\"Error - Data::hermitian can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.\");\n    }\n    else {\n        throw DataException(\"Error - Data::hermitian can only be calculated for rank 2 or 4 object.\");\n    }\n    MAKELAZYOP(HER);\n    Data ev(0.,getDataPointShape(),getFunctionSpace(), false);\n    ev.typeMatchRight(*this);\n    m_data->hermitian(ev.m_data.get());\n    return ev;\n}\n\nData\nData::antihermitian() const\n{\n    if (!isComplex())\n    {\n        return antisymmetric();\n    }  \n    // check input\n    DataTypes::ShapeType s=getDataPointShape();\n    if (getDataPointRank()==2) {\n        if(s[0] != s[1])\n            throw DataException(\"Error - Data::antihermitian can only be calculated for rank 2 object with equal first and second dimension.\");\n\tMAKELAZYOP(NHER);\n        DataTypes::ShapeType ev_shape;\n        ev_shape.push_back(s[0]);\n        ev_shape.push_back(s[1]);\n        Data ev(0.,ev_shape,getFunctionSpace(), false);\n        ev.typeMatchRight(*this);\n        m_data->antihermitian(ev.m_data.get());\n        return ev;\n    }\n    else if (getDataPointRank()==4) {\n        if(!(s[0] == s[2] && s[1] == s[3]))\n            throw DataException(\"Error - Data::antihermitian can only be calculated for rank 4 object with dim0==dim2 and dim1==dim3.\");\n\tMAKELAZYOP(NHER);\n        DataTypes::ShapeType ev_shape;\n        ev_shape.push_back(s[0]);\n        ev_shape.push_back(s[1]);\n        ev_shape.push_back(s[2]);\n        ev_shape.push_back(s[3]);\n        Data ev(0.,ev_shape,getFunctionSpace(), false);\n        ev.typeMatchRight(*this);\n        m_data->antihermitian(ev.m_data.get());\n        return ev;\n    }\n    else {\n        throw DataException(\"Error - Data::antihermitian can only be calculated for rank 2 or 4 object.\");\n    }\n}\n\nData\nData::trace(int axis_offset) const\n{\n    MAKELAZYOPOFF(TRACE,axis_offset);\n    if ((axis_offset<0) || (axis_offset>getDataPointRank()))\n    {\n        throw DataException(\"Error - Data::trace, axis_offset must be between 0 and rank-2 inclusive.\");\n    }\n    DataTypes::ShapeType s=getDataPointShape();\n    if (getDataPointRank()==2) {\n        DataTypes::ShapeType ev_shape;\n        Data ev(0.,ev_shape,getFunctionSpace(),false);\n        ev.typeMatchRight(*this);\n        m_data->trace(ev.m_data.get(), axis_offset);\n        return ev;\n    }\n    if (getDataPointRank()==3) {\n        DataTypes::ShapeType ev_shape;\n        if (axis_offset==0) {\n            int s2=s[2];\n            ev_shape.push_back(s2);\n        }\n        else if (axis_offset==1) {\n            int s0=s[0];\n            ev_shape.push_back(s0);\n        }\n        Data ev(0.,ev_shape,getFunctionSpace(),false);\n        ev.typeMatchRight(*this);\n        m_data->trace(ev.m_data.get(), axis_offset);\n        return ev;\n    }\n    if (getDataPointRank()==4) {\n        DataTypes::ShapeType ev_shape;\n        if (axis_offset==0) {\n            ev_shape.push_back(s[2]);\n            ev_shape.push_back(s[3]);\n        }\n        else if (axis_offset==1) {\n            ev_shape.push_back(s[0]);\n            ev_shape.push_back(s[3]);\n        }\n        else if (axis_offset==2) {\n            ev_shape.push_back(s[0]);\n            ev_shape.push_back(s[1]);\n        }\n        Data ev(0.,ev_shape,getFunctionSpace(),false);\n        ev.typeMatchRight(*this);\n        m_data->trace(ev.m_data.get(), axis_offset);\n        return ev;\n    }\n    else {\n        throw DataException(\"Error - Data::trace can only be calculated for rank 2, 3 or 4 object.\");\n    }\n}\n\nData\nData::transpose(int axis_offset) const\n{   \n    MAKELAZYOPOFF(TRANS,axis_offset);\n    DataTypes::ShapeType s=getDataPointShape();\n    DataTypes::ShapeType ev_shape;\n    // Here's the equivalent of python s_out=s[axis_offset:]+s[:axis_offset]\n    // which goes thru all shape vector elements starting with axis_offset (at index=rank wrap around to 0)\n    int rank=getDataPointRank();\n    if (axis_offset<0 || axis_offset>rank) {\n        stringstream e;\n        e << \"Error - Data::transpose must have 0 <= axis_offset <= rank=\" << rank;\n        throw DataException(e.str());\n    }\n    for (int i=0; i<rank; i++) {\n        int index = (axis_offset+i)%rank;\n        ev_shape.push_back(s[index]); // Append to new shape\n    }\n    Data ev(0.,ev_shape,getFunctionSpace(), false);\n    ev.typeMatchRight(*this);\n    m_data->transpose(ev.m_data.get(), axis_offset);\n    return ev;\n}\n\nData\nData::eigenvalues() const\n{\n    if (isLazy())\n    {\n        Data temp(*this);       // to get around the fact that you can't resolve a const Data\n        temp.resolve();\n        return temp.eigenvalues();\n    }\n    // check input\n    DataTypes::ShapeType s=getDataPointShape();\n    if (getDataPointRank()!=2)\n        throw DataException(\"Error - Data::eigenvalues can only be calculated for rank 2 object.\");\n    if(s[0] != s[1])\n        throw DataException(\"Error - Data::eigenvalues can only be calculated for object with equal first and second dimension.\");\n    if (isComplex() && (s[0]>2))\n    {\n        throw DataException(\"Error - Data::eigenvalues not supported for complex 3x3.\");\n    }\n    // create return\n    DataTypes::ShapeType ev_shape(1,s[0]);\n    Data ev(0.,ev_shape,getFunctionSpace(),false);\n    ev.typeMatchRight(*this);\n    m_data->eigenvalues(ev.m_data.get());\n    return ev;\n}\n\nconst bp::tuple\nData::eigenvalues_and_eigenvectors(const real_t tol) const\n{\n    THROWONCOMPLEX\n    if (isLazy())\n    {\n        Data temp(*this);       // to get around the fact that you can't resolve a const Data\n        temp.resolve();\n        return temp.eigenvalues_and_eigenvectors(tol);\n    }\n    DataTypes::ShapeType s=getDataPointShape();\n    if (getDataPointRank()!=2)\n        throw DataException(\"Error - Data::eigenvalues and eigenvectors can only be calculated for rank 2 object.\");\n    if(s[0] != s[1])\n        throw DataException(\"Error - Data::eigenvalues and eigenvectors can only be calculated for object with equal first and second dimension.\");\n    // create return\n    DataTypes::ShapeType ev_shape(1,s[0]);\n    Data ev(0.,ev_shape,getFunctionSpace(), false);\n    ev.typeMatchRight(*this);\n    DataTypes::ShapeType V_shape(2,s[0]);\n    Data V(0.,V_shape,getFunctionSpace(), false);\n    V.typeMatchRight(*this);\n    m_data->eigenvalues_and_eigenvectors(ev.m_data.get(),V.m_data.get(),tol);\n    return bp::make_tuple(bp::object(ev),bp::object(V));\n}\n\nconst bp::tuple\nData::minGlobalDataPoint() const\n{\n    // NB: calc_minGlobalDataPoint( had to be split off from minGlobalDataPoint( as boost::make_tuple causes an\n    // abort (for unknown reasons) if there are openmp directives with it in the\n    // surrounding function\n\n    THROWONCOMPLEX\n    int DataPointNo;\n    int ProcNo;\n    calc_minGlobalDataPoint(ProcNo,DataPointNo);\n    if (ProcNo==-1) {\n\tthrow DataException(\"There are no values to find minimum of.\");\n    }\n    return bp::make_tuple(ProcNo,DataPointNo);\n}\n\nvoid\nData::calc_minGlobalDataPoint(int& ProcNo,\n                        int& DataPointNo) const\n{\n    THROWONCOMPLEX\n    if (isLazy())\n    {\n        Data temp(*this);   // to get around the fact that you can't resolve a const Data\n        temp.resolve();\n        return temp.calc_minGlobalDataPoint(ProcNo,DataPointNo);\n    }\n    int i,j;\n    int lowi=0,lowj=0;\n    real_t min=numeric_limits<real_t>::max();\n\n    Data temp=minval_nonlazy();   // need to do this to prevent autolazy from reintroducing laziness\n\n    int numSamples=temp.getNumSamples();\n    int numDPPSample=temp.getNumDataPointsPerSample();\n\n    real_t local_val, local_min;\n#ifdef ESYS_MPI\n    real_t next[2];\n#endif\n    int local_lowi=0,local_lowj=0;        \n\n#pragma omp parallel firstprivate(local_lowi,local_lowj) private(local_val,local_min)\n    {\n        local_min=min;\n\tDataTypes::real_t wantreal=0;\n#pragma omp for private(i,j) schedule(static)\n        for (i=0; i<numSamples; i++) {\n            for (j=0; j<numDPPSample; j++) {\n                local_val=temp.getDataAtOffsetRO(temp.getDataOffset(i,j), wantreal);\n                if (local_val<local_min) {\n                    local_min=local_val;\n                    local_lowi=i;\n                    local_lowj=j;\n                }\n            }\n        }\n#pragma omp critical\n        if (local_min<min) { // If we found a smaller value than our sentinel\n            min=local_min;\n            lowi=local_lowi;\n            lowj=local_lowj;\n        }\n    } // parallel section\n\n#ifdef ESYS_MPI\n    // determine the processor on which the minimum occurs\n    next[0] = min;\n    next[1] = numSamples;\n    int lowProc = 0;\n    real_t *globalMins = new real_t[get_MPISize()*2+1];\n    /*int error =*/ MPI_Gather (next, 2, MPI_DOUBLE, globalMins, 2, MPI_DOUBLE, 0, get_MPIComm() );\n\n    if ( get_MPIRank()==0 ) {\n        for (lowProc=0; lowProc<get_MPISize(); lowProc++) {\n            if (globalMins[lowProc*2+1] > 0) break;\n        }\n\tif (lowProc<get_MPISize()) {\n            min = globalMins[lowProc*2];\n            for( i=lowProc+1; i<get_MPISize(); i++ )\n                if( globalMins[i*2+1]>0 && min>globalMins[i*2] ) {\n                    lowProc = i;\n                    min = globalMins[i*2];\n                }\n        }\n    }\n    MPI_Bcast( &lowProc, 1, MPI_INT, 0, get_MPIComm() );\n    DataPointNo = lowj + lowi * numDPPSample;\n    if (lowProc>=get_MPISize()) {\n        ProcNo = -1;\n    } else {\n        MPI_Bcast(&DataPointNo, 1, MPI_INT, lowProc, get_MPIComm() );\n        ProcNo = lowProc;\n    }\n    delete [] globalMins;\n#else\n    ProcNo = 0;\n    DataPointNo = lowj + lowi * numDPPSample;\n#endif\n}\n\n\nconst bp::tuple\nData::maxGlobalDataPoint() const\n{\n    THROWONCOMPLEX\n    int DataPointNo;\n    int ProcNo;\n    calc_maxGlobalDataPoint(ProcNo,DataPointNo);\n    return bp::make_tuple(ProcNo,DataPointNo);\n}\n\nvoid\nData::calc_maxGlobalDataPoint(int& ProcNo,\n                        int& DataPointNo) const\n{\n    if (isLazy())\n    {\n        Data temp(*this);   // to get around the fact that you can't resolve a const Data\n        temp.resolve();\n        return temp.calc_maxGlobalDataPoint(ProcNo,DataPointNo);\n    }\n    THROWONCOMPLEX\n    int i,j;\n    int highi=0,highj=0;\n    //-------------\n    real_t max= -numeric_limits<real_t>::max();\n\n    Data temp=maxval_nonlazy();   // need to do this to prevent autolazy from reintroducing laziness\n\n    int numSamples=temp.getNumSamples();\n    int numDPPSample=temp.getNumDataPointsPerSample();\n\n    real_t local_val, local_max;\n#ifdef ESYS_MPI\n    real_t next[2];\n#endif\n    int local_highi=0,local_highj=0;      \n\n#pragma omp parallel firstprivate(local_highi,local_highj) private(local_val,local_max)\n    {\n        local_max=max;\n\tDataTypes::real_t wantreal=0;\n#pragma omp for private(i,j) schedule(static)\n        for (i=0; i<numSamples; i++) {\n            for (j=0; j<numDPPSample; j++) {\n                local_val=temp.getDataAtOffsetRO(temp.getDataOffset(i,j), wantreal);\n                if (local_val>local_max) {\n                    local_max=local_val;\n                    local_highi=i;\n                    local_highj=j;\n                }\n            }\n        }\n#pragma omp critical\n        if (local_max>max) { // If we found a larger value than our sentinel\n            max=local_max;\n            highi=local_highi;\n            highj=local_highj;\n        }\n    }\n#ifdef ESYS_MPI\n    // determine the processor on which the maximum occurs\n    next[0] = max;\n    next[1] = numSamples;\n    int highProc = 0;\n    real_t *globalMaxs = new real_t[get_MPISize()*2+1];\n    /*int error =*/ MPI_Gather ( next, 2, MPI_DOUBLE, globalMaxs, 2, MPI_DOUBLE, 0, get_MPIComm() );\n    if( get_MPIRank()==0 ){\n        for (highProc=0; highProc<get_MPISize(); highProc++)\n            if (globalMaxs[highProc*2+1] > 0) break;\n        max = globalMaxs[highProc*2];\n        for( i=highProc+1; i<get_MPISize(); i++ )\n        {\n            if( globalMaxs[i*2+1]>0 && max<globalMaxs[i*2] )\n            {\n                highProc = i;\n                max = globalMaxs[i*2];\n            }\n        }\n    }\n    MPI_Bcast( &highProc, 1, MPI_INT, 0, get_MPIComm() );\n    DataPointNo = highj + highi * numDPPSample;  \n    MPI_Bcast(&DataPointNo, 1, MPI_INT, highProc, get_MPIComm() );\n\n    delete [] globalMaxs;\n    ProcNo = highProc;\n#else\n    ProcNo = 0;\n    DataPointNo = highj + highi * numDPPSample;\n#endif\n}\n\nData&\nData::operator+=(const Data& right)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    MAKELAZYBINSELF(right,ADD);    // for lazy + is equivalent to +=\n    exclusiveWrite();                     // Since Lazy data does not modify its leaves we only need to worry here\n    if (!isComplex() && right.isComplex())\n    {\n        complicate();\n    }\n    TensorSelfUpdateBinaryOperation(right, escript::ES_optype::ADD);  \n    return (*this);\n}\n\nData&\nData::operator+=(const boost::python::object& right)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    Data tmp(right,getFunctionSpace(),false);\n    (*this)+=tmp;\n    return *this;\n}\n\n// Hmmm, operator= makes a deep copy but the copy constructor does not?\nData&\nData::operator=(const Data& other)\n{\n    m_protected=false; // since any changes should be caught by exclusiveWrite()\n    set_m_data(other.m_data);\n    return (*this);\n}\n\nData&\nData::operator-=(const Data& right)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    MAKELAZYBINSELF(right,SUB);\n    exclusiveWrite();\n    if (!isComplex() && right.isComplex())\n    {\n        complicate();\n    }\n    TensorSelfUpdateBinaryOperation(right, escript::ES_optype::SUB);\n    return (*this);\n}\n\nData&\nData::operator-=(const boost::python::object& right)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    Data tmp(right,getFunctionSpace(),false);\n    (*this)-=tmp;\n    return (*this);\n}\n\nData&\nData::operator*=(const Data& right)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    MAKELAZYBINSELF(right,MUL);\n    exclusiveWrite();\n    if (!isComplex() && right.isComplex())\n    {\n        complicate();\n    }\n    TensorSelfUpdateBinaryOperation(right, escript::ES_optype::MUL);\n    return (*this);\n}\n\nData&\nData::operator*=(const boost::python::object& right)\n{  \n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    Data tmp(right,getFunctionSpace(),false);\n    (*this)*=tmp;\n    return (*this);\n}\n\nData&\nData::operator/=(const Data& right)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    MAKELAZYBINSELF(right,DIV);\n    exclusiveWrite();\n    if (!isComplex() && right.isComplex())\n    {\n        complicate();\n    }\n    TensorSelfUpdateBinaryOperation(right, escript::ES_optype::DIV);\n    return (*this);\n}\n\nData&\nData::operator/=(const boost::python::object& right)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    Data tmp(right,getFunctionSpace(),false);\n    (*this)/=tmp;\n    return (*this);\n}\n\n/* Be careful trying to make this operation lazy.\nAt time of writing, resolve() and resolveSample() do not throw.\nChanging this would mean that any resolve call would need to use MPI (to check for global errors)\n*/\nData\nData::matrixInverse() const\n{\n    if (isLazy())       // Cannot use lazy for this because individual inversions could throw.\n    {\n        Data d(*this);\n        d.resolve();\n        return d.matrixInverse();\n    }\n    THROWONCOMPLEX\n    Data out(0.,getDataPointShape(),getFunctionSpace(),false);\n    out.typeMatchRight(*this);\n\n    DataReady* drp=out.getReadyPtr().get();\n    int errcode=m_data->matrixInverse(drp);\n#ifdef ESYS_MPI\n    int globalval=0;\n    MPI_Allreduce( &errcode, &globalval, 1, MPI_INT, MPI_MAX, get_MPIComm() );\n    errcode=globalval;\n#endif\n    if (errcode)\n    {\n        escript::matrixInverseError(errcode); // throws exceptions\n    }\n    return out;\n}\n\n\nData\nData::rpowO(const bp::object& left) const\n{\n    Data left_d(left,*this);\n    return left_d.powD(*this);\n}\n\nData\nData::powO(const bp::object& right) const\n{\n    Data tmp(right,getFunctionSpace(),false);\n    return powD(tmp);\n}\n\nData\nData::powD(const Data& right) const\n{\n    MAKELAZYBIN(right,POW);\n    \n    return C_TensorBinaryOperation(*this, right, ES_optype::POW);    \n    \n}\n\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator+(const Data& left, const Data& right)\n{\n    MAKELAZYBIN2(left,right,ADD);\n    \n    return C_TensorBinaryOperation(left, right, ES_optype::ADD);\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator-(const Data& left, const Data& right)\n{\n    MAKELAZYBIN2(left,right,SUB);\n    return C_TensorBinaryOperation(left, right, ES_optype::SUB);    \n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator*(const Data& left, const Data& right)\n{\n    MAKELAZYBIN2(left,right,MUL);    \n    \n    return C_TensorBinaryOperation(left, right, ES_optype::MUL);        \n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator/(const Data& left, const Data& right)\n{\n    MAKELAZYBIN2(left,right,DIV);\n    return C_TensorBinaryOperation(left, right, ES_optype::DIV);        \n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator+(const Data& left, const boost::python::object& right)\n{\n    Data tmp(right,left.getFunctionSpace(),false);\n    MAKELAZYBIN2(left,tmp,ADD);\n    return left+tmp;\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator-(const Data& left, const boost::python::object& right)\n{\n    Data tmp(right,left.getFunctionSpace(),false);\n    MAKELAZYBIN2(left,tmp,SUB);\n    return left-tmp;\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator*(const Data& left, const boost::python::object& right)\n{\n    Data tmp(right,left.getFunctionSpace(),false);\n    MAKELAZYBIN2(left,tmp,MUL);\n    return left*tmp;\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator/(const Data& left, const boost::python::object& right)\n{\n    Data tmp(right,left.getFunctionSpace(),false);\n    MAKELAZYBIN2(left,tmp,DIV);\n    return left/tmp;\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator+(const boost::python::object& left, const Data& right)\n{\n    Data tmp(left,right.getFunctionSpace(),false);\n    MAKELAZYBIN2(tmp,right,ADD);\n    return tmp+right;\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator-(const boost::python::object& left, const Data& right)\n{\n    Data tmp(left,right.getFunctionSpace(),false);\n    MAKELAZYBIN2(tmp,right,SUB);\n    return tmp-right;\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator*(const boost::python::object& left, const Data& right)\n{\n    Data tmp(left,right.getFunctionSpace(),false);\n    MAKELAZYBIN2(tmp,right,MUL);\n    return tmp*right;\n}\n\n//\n// NOTE: It is essential to specify the namespace this operator belongs to\nData\nescript::operator/(const boost::python::object& left, const Data& right)\n{\n    Data tmp(left,right.getFunctionSpace(),false);\n    MAKELAZYBIN2(tmp,right,DIV);\n    return tmp/right;\n}\n\n\n/* TODO */\n/* global reduction */\nData\nData::getItem(const bp::object& key) const\n{\n    DataTypes::RegionType slice_region=DataTypes::getSliceRegion(getDataPointShape(),key);\n\n    if (slice_region.size()!=getDataPointRank()) {\n        throw DataException(\"Error - slice size does not match Data rank.\");\n    }\n\n    return getSlice(slice_region);\n}\n\n/* TODO */\n/* global reduction */\nData\nData::getSlice(const DataTypes::RegionType& region) const\n{\n    return Data(*this,region);\n}\n\n/* TODO */\n/* global reduction */\nvoid\nData::setItemO(const bp::object& key,\n               const bp::object& value)\n{\n    Data tempData(value,getFunctionSpace(),false);\n    setItemD(key,tempData);\n}\n\nvoid\nData::setItemD(const bp::object& key,\n               const Data& value)\n{\n    DataTypes::RegionType slice_region=DataTypes::getSliceRegion(getDataPointShape(),key);\n    if (slice_region.size()!=getDataPointRank()) {\n        throw DataException(\"Error - slice size does not match Data rank.\");\n    }\n    exclusiveWrite();\n    if (getFunctionSpace()!=value.getFunctionSpace()) {\n        setSlice(Data(value,getFunctionSpace()),slice_region);\n    } else {\n        setSlice(value,slice_region);\n    }\n}\n\nvoid\nData::setSlice(const Data& value,\n               const DataTypes::RegionType& region)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    forceResolve();\n    exclusiveWrite(); // In case someone finds a way to call this without going through setItemD\n    Data tempValue(value);\n    typeMatchLeft(tempValue);\n    typeMatchRight(tempValue);\n    getReady()->setSlice(tempValue.m_data.get(),region);\n}\n\nvoid\nData::typeMatchLeft(Data& right) const\n{\n    if (right.isLazy() && !isLazy())\n    {\n        right.resolve();\n    }\n    if (isComplex())\n    {\n        right.complicate();\n    }\n    if (isExpanded()) {\n        right.expand();\n    } else if (isTagged()) {\n        if (right.isConstant()) {\n            right.tag();\n        }\n    }\n}\n\nvoid\nData::typeMatchRight(const Data& right)\n{\n    if (isLazy() && !right.isLazy())\n    {\n        resolve();\n    }\n    if (right.isComplex())\n    {\n\tcomplicate();\n    }    \n    if (isTagged()) {\n        if (right.isExpanded()) {\n            expand();\n        }\n    } else if (isConstant()) {\n        if (right.isExpanded()) {\n            expand();\n        } else if (right.isTagged()) {\n            tag();\n        }\n    }\n}\n\n// The normal TaggedValue adds the tag if it is not already present\n// This form does not. It throws instead.\n// This is because the names are maintained by the domain and cannot be added\n// without knowing the tag number to map it to.\nvoid\nData::setTaggedValueByName(std::string name,\n                           const bp::object& value)\n{\n    if (getFunctionSpace().getDomain()->isValidTagName(name)) {\n        forceResolve();\n        exclusiveWrite();\n        int tagKey=getFunctionSpace().getDomain()->getTag(name);\n        setTaggedValue(tagKey,value);\n    }\n    else\n    {\n        std::string msg=\"Error - unknown tag (\"+name+\") in setTaggedValueByName.\";\n        throw DataException(msg);\n    }\n}\n\nvoid\nData::setTaggedValue(int tagKey,\n                     const bp::object& value)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    //\n    // Ensure underlying data object is of type DataTagged\n    forceResolve();\n    exclusiveWrite();\n    if (isConstant()) tag();\n    WrappedArray w(value);\n\n    if (w.isComplex())\n    {\n        CplxVectorType temp_data2;\n        temp_data2.copyFromArray(w,1);\n\n        m_data->setTaggedValue(tagKey,w.getShape(), temp_data2);\n\n    }\n    else\n    {\n        RealVectorType temp_data2;\n        temp_data2.copyFromArray(w,1);\n        if (isComplex())\t// set real value in complex\n        {\n\t    CplxVectorType temp_data3;\n            fillComplexFromReal(temp_data2,temp_data3);\n            m_data->setTaggedValue(tagKey,w.getShape(), temp_data3);\n        }\n        else\n        {\n            m_data->setTaggedValue(tagKey,w.getShape(), temp_data2);\n        }\n    }\n}\n\n\nvoid\nData::setTaggedValueFromCPP(int tagKey,\n                            const DataTypes::ShapeType& pointshape,\n                            const DataTypes::RealVectorType& value,\n                            int dataOffset)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    //\n    // Ensure underlying data object is of type DataTagged\n    forceResolve();\n    if (isConstant()) tag();\n    exclusiveWrite();\n    //\n    // Call DataAbstract::setTaggedValue\n    m_data->setTaggedValue(tagKey,pointshape, value, dataOffset);\n}\n\nvoid\nData::setTaggedValueFromCPP(int tagKey,\n                            const DataTypes::ShapeType& pointshape,\n                            const DataTypes::CplxVectorType& value,\n                            int dataOffset)\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }\n    //\n    // Ensure underlying data object is of type DataTagged\n    forceResolve();\n    if (isConstant()) tag();\n    exclusiveWrite();\n    //\n    // Call DataAbstract::setTaggedValue\n    m_data->setTaggedValue(tagKey,pointshape, value, dataOffset);\n}\n\n\nint\nData::getTagNumber(int dpno)\n{\n    if (isEmpty())\n    {\n        throw DataException(\"Error - operation not permitted on instances of DataEmpty.\");\n    }\n    return getFunctionSpace().getTagFromDataPointNo(dpno);\n}\n\n\nostream& escript::operator<<(ostream& o, const Data& data)\n{\n    o << data.toString();\n    return o;\n}\n\nData\nescript::C_GeneralTensorProduct(Data& arg_0,\n                     Data& arg_1,\n                     int axis_offset,\n                     int transpose)\n{\n    // General tensor product: res(SL x SR) = arg_0(SL x SM) * arg_1(SM x SR)\n    // SM is the product of the last axis_offset entries in arg_0.getShape().\n\n    // deal with any lazy data\n    if (arg_0.isLazy() || arg_1.isLazy() || (AUTOLAZYON && (arg_0.isExpanded() || arg_1.isExpanded())))\n    {\n        DataLazy* c=new DataLazy(arg_0.borrowDataPtr(), arg_1.borrowDataPtr(), PROD, axis_offset,transpose);\n        return Data(c);\n    }\n\n    // Interpolate if necessary and find an appropriate function space\n    Data arg_0_Z, arg_1_Z;\n    if (arg_0.getFunctionSpace()!=arg_1.getFunctionSpace()) {\n        if (arg_0.probeInterpolation(arg_1.getFunctionSpace())) {\n            arg_0_Z = arg_0.interpolate(arg_1.getFunctionSpace());\n            arg_1_Z = Data(arg_1);\n        }\n        else if (arg_1.probeInterpolation(arg_0.getFunctionSpace())) {\n            arg_1_Z=arg_1.interpolate(arg_0.getFunctionSpace());\n            arg_0_Z =Data(arg_0);\n        }\n        else {\n            throw DataException(\"Error - C_GeneralTensorProduct: arguments have incompatible function spaces.\");\n        }\n    } else {\n        arg_0_Z = Data(arg_0);\n        arg_1_Z = Data(arg_1);\n    }\n    // Get rank and shape of inputs\n    int rank0 = arg_0_Z.getDataPointRank();\n    int rank1 = arg_1_Z.getDataPointRank();\n    const DataTypes::ShapeType& shape0 = arg_0_Z.getDataPointShape();\n    const DataTypes::ShapeType& shape1 = arg_1_Z.getDataPointShape();\n\n    // Prepare for the loops of the product and verify compatibility of shapes\n    int start0=0, start1=0;\n    if (transpose == 0)           {}\n    else if (transpose == 1)      { start0 = axis_offset; }\n    else if (transpose == 2)      { start1 = rank1-axis_offset; }\n    else                          { throw DataException(\"C_GeneralTensorProduct: Error - transpose should be 0, 1 or 2\"); }\n\n\n    // Adjust the shapes for transpose\n    DataTypes::ShapeType tmpShape0(rank0); // pre-sizing the vectors rather\n    DataTypes::ShapeType tmpShape1(rank1); // than using push_back\n    for (int i=0; i<rank0; i++)   { tmpShape0[i]=shape0[(i+start0)%rank0]; }\n    for (int i=0; i<rank1; i++)   { tmpShape1[i]=shape1[(i+start1)%rank1]; }\n\n    // Prepare for the loops of the product\n    int SL=1, SM=1, SR=1;\n    for (int i=0; i<rank0-axis_offset; i++) {\n        SL *= tmpShape0[i];\n    }\n    for (int i=rank0-axis_offset; i<rank0; i++) {\n        if (tmpShape0[i] != tmpShape1[i-(rank0-axis_offset)]) {\n            throw DataException(\"C_GeneralTensorProduct: Error - incompatible shapes\");\n        }\n        SM *= tmpShape0[i];\n    }\n    for (int i=axis_offset; i<rank1; i++) {\n        SR *= tmpShape1[i];\n    }\n\n    // Define the shape of the output (rank of shape is the sum of the loop ranges below)\n    DataTypes::ShapeType shape2(rank0+rank1-2*axis_offset);       \n    { // block to limit the scope of out_index\n        int out_index=0;\n        for (int i=0; i<rank0-axis_offset; i++, ++out_index) { shape2[out_index]=tmpShape0[i]; } // First part of arg_0_Z\n        for (int i=axis_offset; i<rank1; i++, ++out_index)   { shape2[out_index]=tmpShape1[i]; } // Last part of arg_1_Z\n    }\n\n    if (shape2.size()>ESCRIPT_MAX_DATA_RANK)\n    {\n        ostringstream os;\n        os << \"C_GeneralTensorProduct: Error - Attempt to create a rank \" << shape2.size() << \" object. The maximum rank is \" << ESCRIPT_MAX_DATA_RANK << \".\";\n        throw DataException(os.str());\n    }\n\n    // Declare output Data object\n    Data res;\n\n    bool complexresult=arg_0_Z.isComplex() || arg_1_Z.isComplex();\n    cplx_t dummyc=0;\n    real_t dummyr=0;    \n    if (arg_0_Z.isConstant() && arg_1_Z.isConstant()) {\n        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(), false);        // DataConstant output\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {\n\t\tcplx_t dummyc=0;\n\t        res.complicate();\n\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(0,dummyc));\n\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(0,dummyc));\n\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(0,dummyc));\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\t\t\n\t    }\n\t    else\t// right is real\n\t    {\n\t\tcplx_t dummyc=0;\n\t\treal_t dummyr=0;\n\t        res.complicate();\n\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(0,dummyc));\n\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(0,dummyr));\n\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(0,dummyc));\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\t\t\n\t    }\n\t}\n\telse\t// arg_0_Z is real\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {\n\t\tcplx_t dummyc=0;\n\t\treal_t dummyr=0;\n\t        res.complicate();\n\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(0,dummyr));\n\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(0,dummyc));\n\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(0,dummyc));\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\t      \n\t    }\n\t    else\n\t    {\n\t        real_t dummyr=0;\n\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(0,0));\n\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(0,0));\n\t\treal_t *ptr_2 = &(res.getDataAtOffsetRW(0, dummyr));\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\t      \n\t    }\n\t}\n\n    }\n    else if (arg_0_Z.isConstant()   && arg_1_Z.isTagged()) {\n\n        // Prepare the DataConstant input\n        DataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());\n        if (tmp_0==0) { throw DataException(\"GTP Programming error - casting to DataConstant.\"); }\n\n        // Borrow DataTagged input from Data object\n        DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());\n        if (tmp_1==0) { throw DataException(\"GTP_1 Programming error - casting to DataTagged.\"); }\n\n        // Prepare a DataTagged output 2\n        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(), false);        // DataTagged output\n        res.tag();\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\t\n        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());\n        if (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataTagged.\"); }\n\n\tcplx_t dummyc=0;\n\treal_t dummyr=0;\n        \n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {        \n\t\t// Prepare offset into DataConstant\n\t\tint offset_0 = tmp_0->getPointOffset(0,0);\n\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\n\t\tconst cplx_t *ptr_1 = &(tmp_1->getDefaultValueRO(0, dummyc));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\n\t\t    const cplx_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0, dummyc));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummyc));\n\t\t\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t\t\n\t    }\n\t    else\n\t    {\n\t\t// Prepare offset into DataConstant\n\t\tint offset_0 = tmp_0->getPointOffset(0,0);\n\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\n\t\tconst real_t *ptr_1 = &(tmp_1->getDefaultValueRO(0, dummyr));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\n\t\t    const real_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0, dummyr));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummyc));\n\t\t\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t\t      \n\t    }\n\t}\n\telse\t// arg_0 is real\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {        \n\t\t// Prepare offset into DataConstant\n\t\tint offset_0 = tmp_0->getPointOffset(0,0);\n\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\n\t\tconst cplx_t *ptr_1 = &(tmp_1->getDefaultValueRO(0, dummyc));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0,dummyc));\t// the result\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\n\t\t    const cplx_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0,dummyc));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0,dummyc));\n\t\t\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t    else\n\t    {\n\t\t// Prepare offset into DataConstant\n\t        real_t dummyr=0;\n\t\tint offset_0 = tmp_0->getPointOffset(0,0);\n\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\n\t\tconst real_t *ptr_1 = &(tmp_1->getDefaultValueRO(0));\n\t\treal_t *ptr_2 = &(tmp_2->getDefaultValueRW(0));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\n\t\t    const real_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0));\n\t\t    real_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0));\n\t\t\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t}\n    }\n    else if (arg_0_Z.isConstant() && arg_1_Z.isExpanded()) {\n\n\tres = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\t\n\tDataConstant* tmp_0=dynamic_cast<DataConstant*>(arg_0_Z.borrowData());\n\tDataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());\n\tDataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());\n\tif (tmp_0==0) { throw DataException(\"GTP Programming error - casting to DataConstant.\"); }\n\tif (tmp_1==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n\tif (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n\tint sampleNo_1,dataPointNo_1;\n\tint numSamples_1 = arg_1_Z.getNumSamples();\n\tint numDataPointsPerSample_1 = arg_1_Z.getNumDataPointsPerSample();\n\tint offset_0 = tmp_0->getPointOffset(0,0);\t\n        \n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)\n\t\tfor (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {\n\t\t    for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)\n\t\tfor (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {\n\t\t    for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\telse\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {  \n\t\t#pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)\n\t\tfor (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {\n\t\t    for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t    else\t// both real\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_1,dataPointNo_1) schedule(static)\n\t\tfor (sampleNo_1 = 0; sampleNo_1 < numSamples_1; sampleNo_1++) {\n\t\t    for (dataPointNo_1 = 0; dataPointNo_1 < numDataPointsPerSample_1; dataPointNo_1++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_1,dataPointNo_1);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\treal_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyr));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\t  \n\t}\n    }\n    else if (arg_0_Z.isTagged() && arg_1_Z.isConstant()) {\n\t// Borrow DataTagged input from Data object\n\tDataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());\n\tif (tmp_0==0) { throw DataException(\"GTP_0 Programming error - casting to DataTagged.\"); }\n\n\t// Prepare the DataConstant input\n\tDataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());\n\tif (tmp_1==0) { throw DataException(\"GTP Programming error - casting to DataConstant.\"); }\n\n\t// Prepare a DataTagged output 2\n\tres = Data(0.0, shape2, arg_0_Z.getFunctionSpace(), false);        // DataTagged output\n\tres.tag();\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\t\n\tDataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());\n\tif (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataTagged.\"); }\n\n\t// Prepare offset into DataConstant\n\tint offset_1 = tmp_1->getPointOffset(0,0);      \n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\n\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\tconst cplx_t *ptr_0 = &(tmp_0->getDefaultValueRO(0, dummyc));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\n\t\t    tmp_2->addTag(i->first);\n\t\t    const cplx_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummyc));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummyc));\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t    else\t// arg_1_Z is real\n\t    {\n\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\tconst cplx_t *ptr_0 = &(tmp_0->getDefaultValueRO(0, dummyc));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\n\t\t    tmp_2->addTag(i->first);\n\t\t    const cplx_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummyc));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummyc));\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t}\n\telse\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\tconst real_t *ptr_0 = &(tmp_0->getDefaultValueRO(0, dummyr));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\n\t\t    tmp_2->addTag(i->first);\n\t\t    const real_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummyr));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummyc));\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t    else\n\t    {\n\t\treal_t dummyr=0;\n\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\tconst real_t *ptr_0 = &(tmp_0->getDefaultValueRO(0));\n\t\treal_t *ptr_2 = &(tmp_2->getDefaultValueRW(0));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\n\t\t    tmp_2->addTag(i->first);\n\t\t    const real_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0));\n\t\t    real_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0));\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t}\n    }\n    else if (arg_0_Z.isTagged() && arg_1_Z.isTagged()) {\n        // Borrow DataTagged input from Data object\n        DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());\n        if (tmp_0==0) { throw DataException(\"GTP Programming error - casting to DataTagged.\"); }\n\n        // Borrow DataTagged input from Data object\n        DataTagged* tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());\n        if (tmp_1==0) { throw DataException(\"GTP Programming error - casting to DataTagged.\"); }\n\n        // Prepare a DataTagged output 2\n        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(), false);\n        res.tag();  // DataTagged output\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\n        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());\n        if (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataTagged.\"); }\n      \n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\tconst cplx_t *ptr_0 = &(tmp_0->getDefaultValueRO(0, dummyc));\n\t\tconst cplx_t *ptr_1 = &(tmp_1->getDefaultValueRO(0, dummyc));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Merge the tags\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\t\t    tmp_2->addTag(i->first); // use tmp_2 to get correct shape\n\t\t}\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\t\t}\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();\n\t\tfor (i=lookup_2.begin();i!=lookup_2.end();i++) {\n\t\t    const cplx_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummyc));\n\t\t    const cplx_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0, dummyc));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummyc));\n\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t    else\t// arg_1_Z is real\n\t    {\n\t\tconst cplx_t *ptr_0 = &(tmp_0->getDefaultValueRO(0, dummyc));\n\t\tconst real_t *ptr_1 = &(tmp_1->getDefaultValueRO(0, dummyr));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Merge the tags\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\t\t    tmp_2->addTag(i->first); // use tmp_2 to get correct shape\n\t\t}\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\t\t}\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();\n\t\tfor (i=lookup_2.begin();i!=lookup_2.end();i++) {\n\t\t    const cplx_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummyc));\n\t\t    const real_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0, dummyr));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummyc));\n\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t}\n\telse\t// arg_0_Z is real\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\tconst real_t *ptr_0 = &(tmp_0->getDefaultValueRO(0, dummyr));\n\t\tconst cplx_t *ptr_1 = &(tmp_1->getDefaultValueRO(0, dummyc));\n\t\tcplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0, dummyc));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Merge the tags\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\t\t    tmp_2->addTag(i->first); // use tmp_2 to get correct shape\n\t\t}\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\t\t}\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();\n\t\tfor (i=lookup_2.begin();i!=lookup_2.end();i++) {\n\t\t    const real_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummyr));\n\t\t    const cplx_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0, dummyc));\n\t\t    cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0,dummyc));\n\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t\t      \n\t    }\n\t    else\n\t    {\n\t\tconst real_t *ptr_0 = &(tmp_0->getDefaultValueRO(0));\n\t\tconst real_t *ptr_1 = &(tmp_1->getDefaultValueRO(0));\n\t\treal_t *ptr_2 = &(tmp_2->getDefaultValueRW(0));\n\n\t\t// Compute an MVP for the default\n\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t// Merge the tags\n\t\tDataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n\t\tconst DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n\t\tconst DataTagged::DataMapType& lookup_1=tmp_1->getTagLookup();\n\t\tfor (i=lookup_0.begin();i!=lookup_0.end();i++) {\n\t\t    tmp_2->addTag(i->first); // use tmp_2 to get correct shape\n\t\t}\n\t\tfor (i=lookup_1.begin();i!=lookup_1.end();i++) {\n\t\t    tmp_2->addTag(i->first);\n\t\t}\n\t\t// Compute an MVP for each tag\n\t\tconst DataTagged::DataMapType& lookup_2=tmp_2->getTagLookup();\n\t\tfor (i=lookup_2.begin();i!=lookup_2.end();i++) {\n\t\t    const real_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0));\n\t\t    const real_t *ptr_1 = &(tmp_1->getDataByTagRO(i->first,0));\n\t\t    real_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0));\n\n\t\t    matrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t}\t      \n\t    }\n\t}\n    }\n    else if (arg_0_Z.isTagged() && arg_1_Z.isExpanded()) {\n      \n\t// After finding a common function space above the two inputs have the same numSamples and num DPPS\n\tres = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\n\tDataTagged*   tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());\n\tDataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());\n\tDataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());    \n\tif (tmp_0==0) { throw DataException(\"GTP Programming error - casting to DataTagged.\"); }\n\tif (tmp_1==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n\tif (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n\tint sampleNo_0,dataPointNo_0;\n\tint numSamples_0 = arg_0_Z.getNumSamples();\n\tint numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();\t\n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0\n\t\t    const cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t    else\t// arg_1_Z is real\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0\n\t\t    const cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\telse\t// arg_0_Z is real\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0\n\t\t    const real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t    else\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_0 = tmp_0->getPointOffset(sampleNo_0,0); // They're all the same, so just use #0\n\t\t    const real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\treal_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyr));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n    }\n    else if (arg_0_Z.isExpanded() && arg_1_Z.isConstant()) {\n        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\n        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());\n        DataConstant* tmp_1=dynamic_cast<DataConstant*>(arg_1_Z.borrowData());\n        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());\n        if (tmp_0==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n        if (tmp_1==0) { throw DataException(\"GTP Programming error - casting to DataConstant.\"); }\n        if (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n        int sampleNo_0,dataPointNo_0;\n        int numSamples_0 = arg_0_Z.getNumSamples();\n        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();\n        int offset_1 = tmp_1->getPointOffset(0,0);      \n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t\t      \n\t    }\n\t    else\t// arg_1_Z is real\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\telse\t// arg_0_Z is real\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\t      \n\t\t}\n\t    }\n\t    else\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\treal_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyr));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\n\n    }\n    else if (arg_0_Z.isExpanded() && arg_1_Z.isTagged()) {\n        // After finding a common function space above the two inputs have the same numSamples and num DPPS\n        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\n        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());\n        DataTagged*   tmp_1=dynamic_cast<DataTagged*>(arg_1_Z.borrowData());\n        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());\n        if (tmp_0==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n        if (tmp_1==0) { throw DataException(\"GTP Programming error - casting to DataTagged.\"); }\n        if (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n        int sampleNo_0,dataPointNo_0;\n        int numSamples_0 = arg_0_Z.getNumSamples();\n        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();      \n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);\n\t\t    const cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t    else\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);\n\t\t    const real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\telse\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);\n\t\t    const cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t    else\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    int offset_1 = tmp_1->getPointOffset(sampleNo_0,0);\n\t\t    const real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\treal_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyr));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\n\n    }\n    else if (arg_0_Z.isExpanded() && arg_1_Z.isExpanded()) {\n        // After finding a common function space above the two inputs have the same numSamples and num DPPS\n        res = Data(0.0, shape2, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n\tif (complexresult)\n\t{\n\t    res.complicate();\n\t}\n        DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());\n        DataExpanded* tmp_1=dynamic_cast<DataExpanded*>(arg_1_Z.borrowData());\n        DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());\n        if (tmp_0==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n        if (tmp_1==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n        if (tmp_2==0) { throw DataException(\"GTP Programming error - casting to DataExpanded.\"); }\n        int sampleNo_0,dataPointNo_0;\n        int numSamples_0 = arg_0_Z.getNumSamples();\n        int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();      \n\tif (arg_0_Z.isComplex())\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t    else\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyc));\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\telse\n\t{\n\t    if (arg_1_Z.isComplex())\n\t    {   \n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\tconst cplx_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyc));\n\t\t\tcplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyc));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t    else\n\t    {\n\t\t#pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n\t\tfor (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n\t\t    for (dataPointNo_0 = 0; dataPointNo_0 < numDataPointsPerSample_0; dataPointNo_0++) {\n\t\t\tint offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_1 = tmp_1->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tint offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n\t\t\tconst real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n\t\t\tconst real_t *ptr_1 = &(arg_1_Z.getDataAtOffsetRO(offset_1, dummyr));\n\t\t\treal_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyr));\n\t\t\tmatrix_matrix_product(SL, SM, SR, ptr_0, ptr_1, ptr_2, transpose);\n\t\t    }\n\t\t}\t      \n\t    }\n\t}\n\n\n    }\n    else {\n        throw DataException(\"Error - C_GeneralTensorProduct: unknown combination of inputs\");\n    }\n\n    return res;\n}\n\nDataAbstract*\nData::borrowData() const\n{\n    return m_data.get();\n}\n\n// Not all that happy about returning a non-const from a const\nDataAbstract_ptr\nData::borrowDataPtr() const\n{\n    return m_data;\n}\n\n// Not all that happy about returning a non-const from a const\nDataReady_ptr\nData::borrowReadyPtr() const\n{\n    DataReady_ptr dr=REFCOUNTNS::dynamic_pointer_cast<DataReady>(m_data);\n    ESYS_ASSERT(dr!=NULL, \"Casting to DataReady.\");\n    return dr;\n}\n\nstd::string\nData::toString() const\n{\n    int localNeedSummary=0;\n#ifdef ESYS_MPI\n    int globalNeedSummary=0;\n#endif\n    if (!m_data->isEmpty() &&\n        m_data->isExpanded() &&\n        !m_data->isLazy() && \n        getLength() > escriptParams.getTooManyLines())\n    {\n        localNeedSummary=1;\n    }\n\n#ifdef ESYS_MPI\n    MPI_Allreduce( &localNeedSummary, &globalNeedSummary, 1, MPI_INT, MPI_MAX, get_MPIComm() );\n    localNeedSummary=globalNeedSummary;\n#endif\n\n    if (localNeedSummary){\n        if (isComplex())\n\t{\n\t    stringstream temp;\n\t    temp << \"Summary: Lsup=\"<< Lsup_const() << \" data points=\" << getNumDataPoints();\n\t    return  temp.str();\n\t}\n\telse\n\t{\n\t    stringstream temp;\n\t    temp << \"Summary: inf=\"<< inf_const() << \" sup=\" << sup_const() << \" data points=\" << getNumDataPoints();\n\t    return  temp.str();\n\t}\n    }\n    return m_data->toString();\n}\n\n\n// This method is not thread-safe\nDataTypes::RealVectorType::reference\nData::getDataAtOffsetRW(DataTypes::RealVectorType::size_type i, DataTypes::real_t dummy)\n{\n    checkExclusiveWrite();\n    return getReady()->getDataAtOffsetRW(i);\n}\n\n// This method is not thread-safe\nDataTypes::RealVectorType::const_reference\nData::getDataAtOffsetRO(DataTypes::RealVectorType::size_type i, DataTypes::real_t dummy)\n{\n    forceResolve();\n    return getReady()->getDataAtOffsetRO(i);\n}\n\n// This method is not thread-safe\nDataTypes::CplxVectorType::reference\nData::getDataAtOffsetRW(DataTypes::RealVectorType::size_type i, DataTypes::cplx_t dummy)\n{\n    checkExclusiveWrite();\n    return getReady()->getDataAtOffsetRWC(i);\n}\n\n// This method is not thread-safe\nDataTypes::CplxVectorType::const_reference\nData::getDataAtOffsetRO(DataTypes::RealVectorType::size_type i, DataTypes::cplx_t dummy)\n{\n    forceResolve();\n    return getReady()->getDataAtOffsetROC(i);\n}\n\nDataTypes::RealVectorType::const_reference\nData::getDataPointRO(int sampleNo, int dataPointNo)\n{\n    forceResolve();\n    if (!isReady())\n    {\n        throw DataException(\"Programmer error -getDataPointRO() not permitted on Lazy Data.\");\n    }\n    else\n    {\n        const DataReady* dr=getReady();\n        return dr->getDataAtOffsetRO(dr->getPointOffset(sampleNo, dataPointNo));\n    }\n}\n\n\nDataTypes::RealVectorType::reference\nData::getDataPointRW(int sampleNo, int dataPointNo)\n{\n    checkExclusiveWrite();\n    DataReady* dr=getReady();\n    return dr->getDataAtOffsetRW(dr->getPointOffset(sampleNo, dataPointNo));\n}\n\nData\nData::interpolateFromTable3DP(bp::object table, real_t Amin, real_t Astep,\n                Data& B, real_t Bmin, real_t Bstep,\n                Data& C, real_t Cmin, real_t Cstep,\n                real_t undef, bool check_boundaries)\n{\n    WrappedArray t(table);\n    return interpolateFromTable3D(t, Amin, Astep, undef, B, Bmin, Bstep, C, Cmin, Cstep, check_boundaries);\n}\n\nData\nData::interpolateFromTable2DP(bp::object table, real_t Amin, real_t Astep,\n                Data& B, real_t Bmin, real_t Bstep,\n                real_t undef, bool check_boundaries)\n{\n    WrappedArray t(table);\n    return interpolateFromTable2D(t, Amin, Astep, undef, B, Bmin, Bstep,check_boundaries);\n}\n\nData\nData::interpolateFromTable1DP(bp::object table, real_t Amin, real_t Astep,\n                              real_t undef,bool check_boundaries)\n{\n    WrappedArray t(table);\n    return interpolateFromTable1D(t, Amin, Astep, undef, check_boundaries);\n}\n\n\nData\nData::interpolateFromTable1D(const WrappedArray& table, real_t Amin,\n                             real_t Astep, real_t undef, bool check_boundaries)\n{\n    table.convertArray(); // critical! Calling getElt on an unconverted array is not thread safe\n    int error=0;\n    if ((getDataPointRank()!=0))\n    {\n        throw DataException(\"Input to 1D interpolation must be scalar\");\n    }\n    if (table.getRank()!=1)\n    {\n        throw DataException(\"Table for 1D interpolation must be 1D\");\n    }\n    if (Astep<=0)\n    {\n        throw DataException(\"Astep must be positive\");\n    }\n    if (!isExpanded())\n    {\n        expand();\n    }\n    Data res(0, DataTypes::scalarShape, getFunctionSpace(), true);\n    int numpts=getNumDataPoints();\n    int twidth=table.getShape()[0]-1;       \n    bool haserror=false;\n    const RealVectorType* adat=0;\n    RealVectorType* rdat=0;\n    try\n    {\n        adat=&(getReady()->getVectorRO());\n        rdat=&(res.getReady()->getVectorRW());\n    } catch (DataException& d)\n    {\n        haserror=true;\n        error=3;\n    }\n    if (!haserror)\n    {\n        int l=0;\n#pragma omp parallel for private(l) schedule(static)\n        for (l=0;l<numpts; ++l)\n        {\n            int lerror=0;\n#pragma omp flush(haserror) // In case haserror was in register\n            if (!haserror)                \n            {\n                real_t a=(*adat)[l];\n                int x=static_cast<int>(((a-Amin)/Astep));\n                if (check_boundaries)\n                {\n                    if ((a<Amin) || (x<0))\n                    {\n                        lerror=1;\n                    } \n                    else if (a>Amin+Astep*twidth) \n                    {\n                        lerror=4;\n                    }\n                }\n                if (!lerror)\n                {\n                    if (x<0) x=0;\n                    if (x>twidth) x=twidth;\n                    try {\n                        if (x==twidth) // value is on the far end of the table\n                        {\n                            real_t e=table.getElt(x);\n                            if (e>undef)\n                            {\n                                lerror=2;\n                            }\n                            else\n                            {\n                                (*rdat)[l]=e;\n                            }\n                        }\n                        else            // x and y are in bounds\n                        {\n                            real_t e=table.getElt(x);\n                            real_t w=table.getElt(x+1);\n                            if ((e>undef) || (w>undef))\n                            {\n                                lerror=2;\n                            }\n                            else\n                            {\n                                // map x*Astep <= a << (x+1)*Astep to [-1,1] \n                                real_t la = 2.0*(a-Amin-(x*Astep))/Astep-1;\n                                (*rdat)[l]=((1-la)*e + (1+la)*w)/2;\n                            }\n                        }\n                    }\n                    catch (DataException& d)\n                    {\n                        lerror=3;\n                    }   \n                } // if !lerror\n                if (lerror!=0)\n                {\n#pragma omp critical // Doco says there is a flush associated with critical\n                    {\n                        haserror=true; // We only care that error is recorded.\n                        error=lerror;  // We don't care which one.\n                    }\n                }\n            } // if (!error)\n        }   // parallelised for\n    } // if !haserror\n#ifdef ESYS_MPI\n    int rerror=0;\n    MPI_Allreduce( &error, &rerror, 1, MPI_INT, MPI_MAX, get_MPIComm() );\n    error=rerror;\n#endif\n    if (error)\n    {\n        switch (error)\n        {\n            case 1: throw DataException(\"Value below lower table range.\");\n            case 2: throw DataException(\"Interpolated value too large\");\n            case 4: throw DataException(\"Value greater than upper table range.\");\n            default:\n                throw DataException(\"Unknown error in interpolation\");          \n        }\n    }\n    return res;\n}\n\nData\nData::interpolateFromTable2D(const WrappedArray& table, real_t Amin,\n                             real_t Astep, real_t undef, Data& B, real_t Bmin,\n                             real_t Bstep, bool check_boundaries)\n{\n    table.convertArray(); // critical! Calling getElt on an unconverted array is not thread safe\n    int error=0;\n    if ((getDataPointRank()!=0) || (B.getDataPointRank()!=0))\n    {\n        throw DataException(\"Inputs to 2D interpolation must be scalar\");\n    }\n    if (table.getRank()!=2)\n    {\n        throw DataException(\"Table for 2D interpolation must be 2D\");\n    }\n    if ((Astep<=0) || (Bstep<=0))\n    {\n        throw DataException(\"All step components must be strictly positive.\");\n    }\n    if (getFunctionSpace()!=B.getFunctionSpace())\n    {\n        Data n=B.interpolate(getFunctionSpace());\n        return interpolateFromTable2D(table, Amin, Astep, undef, \n                n , Bmin, Bstep, check_boundaries);      \n    }\n\n    if (!isExpanded())\n    {\n        expand();\n    }\n    if (!B.isExpanded())\n    {\n        B.expand();\n    }\n\n    Data res(0, DataTypes::scalarShape, getFunctionSpace(), true);\n\n    int numpts=getNumDataPoints();\n    const RealVectorType* adat=0;\n    const RealVectorType* bdat=0;\n    RealVectorType* rdat=0;\n    const DataTypes::ShapeType& ts=table.getShape();\n    try\n    {\n        adat=&(getReady()->getVectorRO());\n        bdat=&(B.getReady()->getVectorRO());\n        rdat=&(res.getReady()->getVectorRW());\n    }\n    catch (DataException& e)\n    {\n        error=3;\n    }\n    if (!error)\n    {\n        int twx=ts[1]-1;        // table width x\n        int twy=ts[0]-1;        // table width y\n\n        bool haserror=false;\n        int l=0;\n#pragma omp parallel for private(l) shared(res,rdat, adat, bdat) schedule(static) \n        for (l=0; l<numpts; ++l)\n        {\n#pragma omp flush(haserror) // In case haserror was in register\n           if (!haserror)               \n           {\n                int lerror=0;\n                real_t a=(*adat)[l];\n                real_t b=(*bdat)[l];\n                int x=static_cast<int>(((a-Amin)/Astep));\n                int y=static_cast<int>(((b-Bmin)/Bstep));\n                if (check_boundaries)\n                {\n                    if ( (a<Amin) || (b<Bmin) || (x<0) || (y<0))\n                    {\n                        lerror=1;\n                    }\n                    else if ( (a>Amin+Astep*twx) || (b>Bmin+Bstep*twy))\n                    {\n                        lerror=4;\n                    }\n                } \n                if (lerror==0)\n                {\n                    if (x<0) x=0;\n                    if (y<0) y=0;\n\n                    if (x>twx) x=twx;\n                    if (y>twy) y=twy;\n                    try\n                    {\n                        int nx=x+1;\n                        int ny=y+1;\n\n                        real_t la=0; // map position of a between x and nx to [-1,1]\n                        real_t lb=0;\n                        real_t weight=4;\n\n                        // now we work out which terms we should be considering\n                        bool usex=(x!=twx);\n                        bool usey=(y!=twy);\n\n                        la = 2.0*(a-Amin-(x*Astep))/Astep-1;\n                        lb = 2.0*(b-Bmin-(y*Bstep))/Bstep-1;\n\n                        real_t sw=table.getElt(y,x);\n                        real_t nw=usey?table.getElt(ny,x):0; // 0 because if !usey ny does not actually exist\n                        real_t se=usex?table.getElt(y,nx):0;\n                        real_t ne=(usex&&usey)?table.getElt(ny,nx):0;                \n\n                        real_t ans=(1-la)*(1-lb)*sw +\n                                   (1-la)*(1+lb)*nw +\n                                   (1+la)*(1-lb)*se +\n                                   (1+la)*(1+lb)*ne;\n                        ans/=weight;\n                        (*rdat)[l]=ans;\n                        // this code does not check to see if any of the points used in the interpolation are undef\n                        if (ans>undef)\n                        {\n                            lerror=2;\n                        }\n                    }\n                    catch (DataException& d)\n                    {\n                        lerror=3;\n                    }\n                }\n                if (lerror!=0)\n                {\n#pragma omp critical  // Doco says there is a flush associated with critical\n                    {\n                        error=lerror;\n                    }               \n                }\n            }  // if (!haserror)\n        } // parallel for\n    } // !error\n#ifdef ESYS_MPI\n    int rerror=0;\n    MPI_Allreduce( &error, &rerror, 1, MPI_INT, MPI_MAX, get_MPIComm() );\n    error=rerror;\n#endif\n    if (error)\n    {\n        switch (error)\n        {\n            case 1: throw DataException(\"Value below lower table range.\");\n            case 2: throw DataException(\"Interpolated value too large\");\n            case 4: throw DataException(\"Value greater than upper table range.\");\n            default:\n                throw DataException(\"Unknown error in interpolation\");            \n        }\n    }\n    return res;\n}\n\n\nData\nData::interpolateFromTable3D(const WrappedArray& table, real_t Amin,\n                             real_t Astep, real_t undef, Data& B, real_t Bmin,\n                             real_t Bstep, Data& C, real_t Cmin, real_t Cstep,\n                             bool check_boundaries)\n{\n    table.convertArray(); // critical! Calling getElt on an unconverted array is not thread safe\n    int error=0;\n    if ((getDataPointRank()!=0) || (B.getDataPointRank()!=0) || (C.getDataPointRank()!=0))\n    {\n        throw DataException(\"Inputs to 3D interpolation must be scalar\");\n    }\n    if (table.getRank()!=3)\n    {\n        throw DataException(\"Table for 3D interpolation must be 3D\");\n    }\n    if ((Astep<=0) || (Bstep<=0) || (Cstep<=0))\n    {\n        throw DataException(\"All step components must be strictly positive.\");\n    }\n    if (getFunctionSpace()!=B.getFunctionSpace())\n    {\n        Data n=B.interpolate(getFunctionSpace());\n        return interpolateFromTable3D(table, Amin, Astep, undef, \n                n , Bmin, Bstep, C, Cmin, Cstep, check_boundaries);\n    }\n    if (getFunctionSpace()!=C.getFunctionSpace())\n    {\n        Data n=C.interpolate(getFunctionSpace());\n        return interpolateFromTable3D(table, Amin, Astep, undef, \n                B , Bmin, Bstep, n, Cmin, Cstep, check_boundaries);\n    }\n\n    if (!isExpanded())\n    {\n        expand();\n    }\n    if (!B.isExpanded())\n    {\n        B.expand();\n    }\n    if (!C.isExpanded())\n    {\n        C.expand();\n    }\n\n    Data res(0, DataTypes::scalarShape, getFunctionSpace(), true);\n\n    int numpts=getNumDataPoints();\n    const RealVectorType* adat=0;\n    const RealVectorType* bdat=0;\n    const RealVectorType* cdat=0;\n    RealVectorType* rdat=0;\n    const DataTypes::ShapeType& ts=table.getShape();\n    try\n    {\n        adat=&(getReady()->getVectorRO());\n        bdat=&(B.getReady()->getVectorRO());\n        cdat=&(C.getReady()->getVectorRO());\n        rdat=&(res.getReady()->getVectorRW());\n    }\n    catch (DataException& e)\n    {\n        error=3;\n    }\n    if (!error)\n    {\n        int twx=ts[2]-1;        // table width x\n        int twy=ts[1]-1;        // table width y\n        int twz=ts[0]-1;        // table width z\n\n        bool haserror=false;\n        int l=0;\n#pragma omp parallel for private(l) shared(res,rdat, adat, bdat) schedule(static) \n        for (l=0; l<numpts; ++l)\n        {\n#pragma omp flush(haserror) // In case haserror was in register\n           if (!haserror)               \n           {\n                int lerror=0;\n                real_t a=(*adat)[l];\n                real_t b=(*bdat)[l];\n                real_t c=(*cdat)[l];\n                int x=static_cast<int>(((a-Amin)/Astep));\n                int y=static_cast<int>(((b-Bmin)/Bstep));\n                int z=static_cast<int>(((c-Cmin)/Cstep));\n                if (check_boundaries)\n                {\n                    if ( (a<Amin) || (b<Bmin) || (c<Cmin)|| (x<0) || (y<0) || (z<0))\n                    {\n                        lerror=1;\n                    }\n                    else if ( (a>Amin+Astep*twx) || (b>Bmin+Bstep*twy) || (c>Cmin+Cstep*twz))\n                    {\n                        lerror=4;\n                    }\n                } \n                if (lerror==0)\n                {\n                    if (x<0) x=0;\n                    if (y<0) y=0;\n                    if (z<0) z=0;\n\n                    if (x>twx) x=twx;\n                    if (y>twy) y=twy;\n                    if (z>twz) z=twz;\n                    try\n                    {\n                        int nx=x+1;\n                        int ny=y+1;\n                        int nz=z+1;\n                        real_t la=0; // map position of a between x and nx to [-1,1]\n                        real_t lb=0;\n                        real_t lc=0;\n                        real_t weight=8;\n\n                        // now we work out which terms we should be considering\n                        bool usex=(x!=twx);\n                        bool usey=(y!=twy);\n                        bool usez=(z!=twz);\n\n                        la = 2.0*(a-Amin-(x*Astep))/Astep-1;\n                        lb = 2.0*(b-Bmin-(y*Bstep))/Bstep-1;\n                        lc = 2.0*(c-Cmin-(z*Cstep))/Cstep-1;\n\n                        real_t swb=table.getElt(z,y,x);\n                        real_t swt=usez?table.getElt(nz,y,x):0;\n                        real_t nwb=usey?table.getElt(z,ny,x):0;\n                        real_t nwt=(usey&&usez)?table.getElt(nz,ny,x):0;\n                        real_t seb=usex?table.getElt(z,y,nx):0;\n                        real_t set=(usex&&usez)?table.getElt(nz,y,nx):0;\n                        real_t neb=(usex&&usey)?table.getElt(z,ny,nx):0;\n                        real_t net=(usex&&usey&&usez)?table.getElt(nz,ny,nx):0;\n\n                        real_t ans=(1-la)*(1-lb)*(1-lc)*swb +\n                                   (1-la)*(1-lb)*(1+lc)*swt +\n                                   (1-la)*(1+lb)*(1-lc)*nwb +\n                                   (1-la)*(1+lb)*(1+lc)*nwt +\n                                   (1+la)*(1-lb)*(1-lc)*seb +\n                                   (1+la)*(1-lb)*(1+lc)*set +\n                                   (1+la)*(1+lb)*(1-lc)*neb +\n                                   (1+la)*(1+lb)*(1+lc)*net;\n                        ans/=weight;\n                        (*rdat)[l]=ans;\n                        // this code does not check to see if any of the points used in the interpolation are undef\n                        if (ans>undef)\n                        {\n                            lerror=2;\n                        }\n                    }\n                    catch (DataException& d)\n                    {\n                        lerror=3;\n                    }\n                }\n                if (lerror!=0)\n                {\n#pragma omp critical // Doco says there is a flush associated with critical\n                    {\n                        error=lerror;\n                    }               \n                }\n            }  // if (!haserror)\n        } // parallel for\n    } // !error\n#ifdef ESYS_MPI\n    int rerror=0;\n    MPI_Allreduce( &error, &rerror, 1, MPI_INT, MPI_MAX, get_MPIComm() );\n    error=rerror;\n#endif\n    if (error)\n    {\n        switch (error)\n        {\n            case 1: throw DataException(\"Value below lower table range.\");\n            case 2: throw DataException(\"Interpolated value too large\");\n            case 4: throw DataException(\"Value greater than upper table range.\");\n            default:\n                throw DataException(\"Unknown error in interpolation\");            \n        }\n    }\n    return res;\n}\n\nData Data::nonuniforminterp(boost::python::object in, boost::python::object out, bool check_boundaries)\n{\n    WrappedArray win(in);\n    win.convertArray();\n    WrappedArray wout(out);\n    wout.convertArray();\n    if ((win.getRank()!=1) || (wout.getRank()!=1) || (win.getShape()[0]<1))\n    {\n        throw DataException(\"Input and output must be arrays/lists of scalars\");\n    }\n    if (win.getShape()!=win.getShape())\n    {\n        throw DataException(\"Input and output must contain the same number of items.\");\n    }\n    if (getDataPointRank()!=0)\n    {\n        throw DataException(\"The data being interpolated must be scalar.\");\n    }\n    // now create an object the same size as this one\n    // We'll expand it later if we need to\n    expand();\n    Data result(0, DataTypes::scalarShape, getFunctionSpace(), true);  \n    int numpts=getNumDataPoints();\n    const RealVectorType& sdat=getReady()->getVectorRO();\n    RealVectorType& rdat=result.getReady()->getVectorRW();\n    real_t maxlimit=win.getElt(win.getShape()[0]-1);\n    real_t maxout=wout.getElt(wout.getShape()[0]-1);\n    int ipoints=win.getShape()[0];\n    int l=0;\n    bool error=false;\n    #pragma omp parallel for private(l) schedule(static) \n    for (l=0; l<numpts; ++l)\n    {\n        if ((sdat)[l]<win.getElt(0))\n        {\n           if (check_boundaries)\n           {\n               error=true;              // Could have done an early exit but I'm not sure it's worth it\n           }\n           else\n           {\n               rdat[l]=wout.getElt(0);\n           }\n        }\n        else if (sdat[l]>maxlimit)\n        {\n           if (check_boundaries)\n           {\n               error=true;              // Could have done an early exit but I'm not sure it's worth it\n           }\n           else\n           {\n               rdat[l]=maxout;\n           }\n        }\n        else\n        {\n            int i=0;\n            for (;i<ipoints-2;++i)\n            {\n                if (sdat[l]<win.getElt(i+1))\n                {\n                    break;\n                }\n            }\n            // we must have found one by this point or we would have triggered earlier branches\n            rdat[l]=(wout.getElt(i+1)-wout.getElt(i))/(win.getElt(i+1)-win.getElt(i)) * (sdat[l]-win.getElt(i)) + wout.getElt(i);\n        }\n    }\n    if (error)  // we had an illegal value (below the start threshold)\n    {\n        throw DataException(\"Data being interpolated contains a value outside the range given.\");\n    }\n    return result;\n}\n\nData Data::nonuniformslope(boost::python::object in, boost::python::object out, bool check_boundaries)\n{\n    WrappedArray win(in);\n    win.convertArray();\n    WrappedArray wout(out);\n    wout.convertArray();\n    if ((win.getRank()!=1) || (wout.getRank()!=1) || (win.getShape()[0]<1))\n    {\n        throw DataException(\"Input and output must be arrays/lists of scalars\");\n    }\n    if (win.getShape()!=win.getShape())\n    {\n        throw DataException(\"Input and output must contain the same number of items.\");\n    }\n    if (getDataPointRank()!=0)\n    {\n        throw DataException(\"The data being interpolated must be scalar.\");\n    }\n    // now create an object the same size as this one\n    // We'll expand it later if we need to\n    expand();\n    Data result(0, DataTypes::scalarShape, getFunctionSpace(), true);  \n    int numpts=getNumDataPoints();\n    const RealVectorType& sdat=getReady()->getVectorRO();\n    RealVectorType& rdat=result.getReady()->getVectorRW();\n    real_t maxlimit=win.getElt(win.getShape()[0]-1);\n    int ipoints=win.getShape()[0];\n    int l=0;\n    bool error=false;\n    #pragma omp parallel for private(l) schedule(static) \n    for (l=0; l<numpts; ++l)\n    {\n        if ((sdat)[l]<win.getElt(0))\n        {\n           if (check_boundaries)\n           {\n               error=true;              // Could have done an early exit but I'm not sure it's worth it\n           }\n           else\n           {\n               rdat[l]=0;\n           }\n        }\n        else if (sdat[l]>maxlimit)\n        {\n           if (check_boundaries)\n           {\n               error=true;              // Could have done an early exit but I'm not sure it's worth it\n           }\n           else\n           {\n               rdat[l]=0;\n           }\n        }\n        else\n        {\n            int i=0;\n            for (;i<ipoints-2;++i)\n            {\n                if (sdat[l]<=win.getElt(i+1))\n                {\n                    break;\n                }\n            }\n            // we must have found one by this point or we would have triggered earlier branches\n            rdat[l]=(wout.getElt(i+1)-wout.getElt(i))/(win.getElt(i+1)-win.getElt(i));\n        }\n    }\n    if (error)  // we had an illegal value (below the start threwshold)\n    {\n        throw DataException(\"Data being interpolated contains a value outside the range given.\");\n    }\n    return result;\n}\n\n\n/* Member functions specific to the MPI implementation */\n\nvoid\nData::print()\n{\n    int i,j;\n\n    printf( \"Data is %dX%d\\n\", getNumSamples(), getNumDataPointsPerSample() );\n    if (isComplex())\n    {\n\tfor( i=0; i<getNumSamples(); i++ )\n\t{\n\t    printf( \"[%6d]\", i );\n\t    for( j=0; j<getNumDataPointsPerSample(); j++ )\n\t    {\n\t        DataTypes::cplx_t* v=getSampleDataRW(i, static_cast<DataTypes::cplx_t>(0));\n\t\tprintf( \"\\t%10.7g,%10.7g\", std::real(v[j]), std::imag(v[j]) );    // doesn't really need RW access\n\t    }\n\t    printf( \"\\n\" );\n\t}      \n    }\n    else\n    {\n\tfor( i=0; i<getNumSamples(); i++ )\n\t{\n\t    printf( \"[%6d]\", i );\n\t    for( j=0; j<getNumDataPointsPerSample(); j++ )\n\t\tprintf( \"\\t%10.7g\", (getSampleDataRW(i, static_cast<DataTypes::real_t>(0)))[j] );    // doesn't really need RW access\n\t    printf( \"\\n\" );\n\t}\n    }\n}\nvoid\nData::dump(const std::string fileName) const\n{\n    try\n    {\n        if (isLazy())\n        {\n            Data temp(*this);     // this is to get a non-const object which we can resolve\n            temp.resolve();\n            temp.dump(fileName);\n        }\n        else\n        {\n            return m_data->dump(fileName);\n        }\n    }\n    catch (std::exception& e)\n    {\n        std::cout << e.what() << std::endl;\n    }\n}\n\nint\nData::get_MPISize() const\n{\n    int size;\n#ifdef ESYS_MPI\n    /*int error =*/ MPI_Comm_size( get_MPIComm(), &size );\n#else\n    size = 1;\n#endif\n    return size;\n}\n\nint\nData::get_MPIRank() const\n{\n    int rank;\n#ifdef ESYS_MPI\n    /*int error =*/ MPI_Comm_rank( get_MPIComm(), &rank );\n#else\n    rank = 0;\n#endif\n    return rank;\n}\n\nMPI_Comm\nData::get_MPIComm() const\n{\n#ifdef ESYS_MPI\n        return getDomain()->getMPIComm();\n#else\n        return -1;\n#endif\n}\n\n#ifdef IKNOWWHATIMDOING\n\n// Considered having a generic option argument for extra info for function.\n// If you pass a python object in we may have threading issues, if it's a C object then it's not python friendly.\n// It's better if the library supplying the C function has its own interface for doing configuration\nESCRIPT_DLL_API\nData\nescript::applyBinaryCFunction(bp::object cfunc, bp::tuple shape, escript::Data& ind, escript::Data& ine)\n{\n    int err=255;\n    PyObject* p=cfunc.ptr();\n    if (!PyCObject_Check(p))\n    {\n        throw DataException(\"applyBinaryCFunction: function must be a PyCObject.\");\n    }\n    void* v=PyCObject_AsVoidPtr(p);\n    binOpFnPtr func=binOpFnPtrFromVoidPtr(v);\n    Data d(ind),e(ine);\n    if (ind.getFunctionSpace()!=ine.getFunctionSpace())\n    {\n        if (ind.getDomain()!=ine.getDomain())\n        {\n            throw DataException(\"applyBinaryCFunction: can't interpolate between domains.\");\n        }\n        std::vector<int> fstypes(2);\n        fstypes[0]=ind.getFunctionSpace().getTypeCode();\n        fstypes[1]=ine.getFunctionSpace().getTypeCode();\n        int bestfs;\n        ind.getDomain()->commonFunctionSpace(fstypes, bestfs);\n        FunctionSpace best(ind.getDomain(),bestfs);\n        d=ind.interpolate(best);\n        e=ine.interpolate(best);\n    }\n    // now we find the result shape\n    DataTypes::ShapeType resultshape;\n    for (int i = 0; i < shape.attr(\"__len__\")(); ++i) {\n        resultshape.push_back(bp::extract<const int>(shape[i]));\n    }\n\n    if (d.isLazy() && !d.actsExpanded())\n    {\n        d.resolve(); // If you aren't expanded you probably won't get benefit from lazy anyway\n    }\n    if (e.isLazy() && !e.actsExpanded())\n    {\n        e.resolve();\n    }\n    Data res(0,resultshape,d.getFunctionSpace());\n    int dpointsize=d.getNoValues();\n    int epointsize=e.getNoValues();\n    int rpointsize=res.getNoValues();\n    if (d.actsExpanded() && !e.actsExpanded())\n    {\n        e.expand();\n    }\n    else if (!d.actsExpanded() && e.actsExpanded())\n    {\n        d.expand();\n    }\n    else if (d.isTagged() && e.isConstant())\n    {\n        e.tag();\n    }\n    else if (e.isTagged() && d.isConstant())\n    {\n        d.tag();\n    }\n    if (d.isConstant() && e.isConstant())\n    {\n        const real_t* src=d.getSampleDataRO(0);\n        const real_t* src2=e.getSampleDataRO(0);\n        real_t* dest=res.getSampleDataRW(0);\n        err=func(dest,src,src2,rpointsize, dpointsize, epointsize);\n    }\n    else if (d.isTagged() && e.isTagged())\n    {\n        res.tag();\n        DataTagged& srcd=*dynamic_cast<DataTagged*>(d.m_data.get());\n        DataTagged& srce=*dynamic_cast<DataTagged*>(e.m_data.get());\n        DataTagged& destd=*dynamic_cast<DataTagged*>(res.m_data.get());\n        std::list<int> alltags;\n        const DataTagged::DataMapType& srcLookupd=srcd.getTagLookup();\n        DataTagged::DataMapType::const_iterator i;\n        DataTagged::DataMapType::const_iterator srcLookupEnd=srcLookupd.end();\n        for (i=srcLookupd.begin();i!=srcLookupEnd;i++)\n        {\n           alltags.push_back(i->first);\n        }               \n        const DataTagged::DataMapType& srcLookupe=srce.getTagLookup();\n        srcLookupEnd=srcLookupe.end();\n        for (i=srcLookupe.begin();i!=srcLookupEnd;i++)\n        {\n            if (find(alltags.begin(), alltags.end(), i->first)==alltags.end())   // we have already seen the tag\n            {\n                alltags.push_back(i->first);\n            }\n        }\n        err=0;\n        // now all tags will be a complete list of tags from both inputs\n        for (std::list<int>::iterator j=alltags.begin();(j!=alltags.end()) && (err==0);++j)\n        {\n            destd.addTag(*j);\n            const real_t *ptr_0 = &(srcd.getDataByTagRO(*j,0));\n            const real_t *ptr_1 = &(srce.getDataByTagRO(*j,0));\n            real_t *ptr_2 = &(destd.getDataByTagRW(*j,0));\n            err=func(ptr_2,ptr_0,ptr_1,rpointsize, dpointsize, epointsize);\n        }\n        if (err==0)\n        {\n            // now we do the default tag\n            const real_t *ptr_0 = &(srcd.getDefaultValueRO(0));\n            const real_t *ptr_1 = &(srce.getDefaultValueRO(0));\n            real_t *ptr_2 = &(destd.getDefaultValueRW(0));\n            err=func(ptr_2,ptr_0,ptr_1,rpointsize, dpointsize, epointsize);\n        }\n    }\n    else if (e.actsExpanded() && d.actsExpanded())\n    {\n        res.expand();\n        int numsamples=d.getNumSamples();\n        \n        int dpps=d.getNumDataPointsPerSample();\n        err=0;\n#pragma omp parallel shared(err)\n        {\n           int localerr=0;\n           int sampleid;\n#pragma omp for schedule(dynamic)\n           for (sampleid=0;sampleid<numsamples;++sampleid)\n           {\n                if(!localerr)\n                {\n                    const real_t* src=d.getSampleDataRO(sampleid);\n                    const real_t* src2=e.getSampleDataRO(sampleid);\n                    real_t* dest=res.getSampleDataRW(sampleid);\n                    for (int pointnum=0;pointnum<dpps;++pointnum)\n                    {\n                        localerr=func(dest,src,src2,rpointsize, dpointsize, epointsize);\n                        if (localerr!=0)\n                        {\n                            break;\n                        }\n                        src+=dpointsize;\n                        src2+=epointsize;\n                        dest+=rpointsize;\n                    }\n                }\n            }\n            if (localerr)\n            {\n#pragma omp critical\n                err=localerr;\n            }\n        }\n    }\n    else\n    {\n        throw DataException(\"applyBinaryCFunction: Unsupported combination of inputs.\");\n    }\n#ifdef ESYS_MPI\n    int global;\n    MPI_Allreduce(&err, &global, 1, MPI_INT, MPI_MAX, getDomain()->getMPIComm());\n    err=global;\n#endif\n    if (err>0)\n    {\n        ostringstream oss;\n        oss << \"applyBinaryCFunction: error code \" << err << \" from C function.\";\n        throw DataException(oss.str());\n    }\n    return res;\n}\n\n#endif // IKNOWWHATIMDOING\n\nData\nescript::condEval(escript::Data& mask, escript::Data& trueval, escript::Data& falseval)\n{\n    if (trueval.isComplex()!=falseval.isComplex())\n    {\n        trueval.complicate();\n        falseval.complicate();\n    }\n    if (trueval.isComplex())\n    {\n        return condEvalWorker(mask, trueval, falseval, static_cast<DataTypes::cplx_t>(0));\n    }\n    else\n    {\n        return condEvalWorker(mask, trueval, falseval, static_cast<DataTypes::real_t>(0));\n    }\n}\n\n\ntemplate <typename S>\nData\nescript::condEvalWorker(escript::Data& mask, escript::Data& trueval, escript::Data& falseval, S sentinel)\n{\n    // First, we need to make sure that trueval and falseval are compatible types.\n    // also need to ensure that mask is a proper type for a mask\n    // Need to choose a functionspace and shape for result\n    // need to catch DataEmpty as well ?\n\n    // only allowing scalar masks\n\n    if (mask.getDataPointRank()!=0) \n    {\n        throw DataException(\"Only supporting scalar masks\");\n        // Allowing people to slice two different objects together within a single datapoint - not allowing that\n\n    }\n\n    if (trueval.getDataPointShape()!=falseval.getDataPointShape()) \n    {\n        throw DataException(\"condEval: shapes of true and false values must match.\");\n    }\n    \n    FunctionSpace fs=trueval.getFunctionSpace();        // should check this for compatibility as well\n    if (trueval.getFunctionSpace()!=falseval.getFunctionSpace())\n    {\n        throw DataException(\"condEval: FunctionSpaces must match.\");\n    }\n    // We aren't going to both with anything lazy except expanded data\n    if (mask.isLazy() && !mask.actsExpanded())\n    {\n        mask.resolve();\n    }\n    if (trueval.isLazy() && !trueval.actsExpanded())\n    {\n        trueval.resolve();\n    }\n    if (falseval.isLazy() && !falseval.actsExpanded())\n    {\n        falseval.resolve();\n    }\n\n    if (mask.isConstant() && trueval.isConstant() && falseval.isConstant())\n    {\n        Data result(0,trueval.getDataPointShape(), fs , false);\n        if (mask.getSampleDataRO(0,static_cast<DataTypes::real_t>(0))[0]>0)\t// mask is always real\n        {\n            result.copy(trueval);\n        }\n        else\n        {\n            result.copy(falseval);\n        }\n        return result;\n    }\n    // Now we need to promote to correct ReadyData types\n    // If they are lazy, they must be expanded\n    if (mask.actsExpanded() || trueval.actsExpanded() || falseval.actsExpanded())\n    {\n        if (!mask.isLazy()) {mask.expand();}\n        if (!trueval.isLazy()) {trueval.expand();}\n        if (!falseval.isLazy()) {falseval.expand();}\n    }\n    else if (mask.isTagged() || trueval.isTagged() || falseval.isTagged())\n    {\n        mask.tag();\n        trueval.tag();\n        falseval.tag();\n    }\n    // by this point all data will be of the same ready type.\n    if (mask.isTagged())\n    {\n        Data result(0,trueval.getDataPointShape(), fs , false);\n        result.tag();\n        DataTagged* rdat=dynamic_cast<DataTagged*>(result.getReady());\n        const DataTagged* tdat=dynamic_cast<const DataTagged*>(trueval.getReady());\n        const DataTagged* fdat=dynamic_cast<const DataTagged*>(falseval.getReady());\n        const DataTagged* mdat=dynamic_cast<DataTagged*>(mask.getReady());\n        //RealVectorType::const_pointer srcptr;\n\tconst S* srcptr;\n\n        // default value first\n        if (mdat->getDefaultValueRO(0)>0)\n        {\n            srcptr=&(tdat->getDefaultValueRO(0, sentinel));\n        } else {\n            srcptr=&(fdat->getDefaultValueRO(0, sentinel));\n        }\n        for (int i=0;i<trueval.getDataPointSize();++i)\n        {\n            *(&(rdat->getDefaultValueRW(0, sentinel))+i)=*(srcptr+i);\n        }\n\n        // now we copy the tags from the mask - if the mask does not have it then it doesn't appear\n        const DataTagged::DataMapType& maskLookup=mdat->getTagLookup();\n        DataTagged::DataMapType::const_iterator it;\n        DataTagged::DataMapType::const_iterator thisLookupEnd=maskLookup.end();\n        for (it=maskLookup.begin();it!=thisLookupEnd;it++)\n        {\n            if (mdat->getDataByTagRO(it->first,0)>0)\n            {\n                rdat->addTaggedValue(it->first,trueval.getDataPointShape(), tdat->getVectorRO(), tdat->getOffsetForTag(it->first));\n            }\n            else\n            {\n                rdat->addTaggedValue(it->first,falseval.getDataPointShape(), fdat->getVectorRO(), fdat->getOffsetForTag(it->first));\n            }\n        }\n\n        return result;\n    }\n    if (!trueval.actsExpanded() || !falseval.actsExpanded() || !mask.actsExpanded())\n    {\n        throw DataException(\"Programmer Error - Only actsExpanded Data should reach this point.\");\n    }\n    else if (mask.actsExpanded() && trueval.actsExpanded() && falseval.actsExpanded())\n    {\n        // Here is the code for all expanded objects\n        // this code will handle lazy data without expanding it just fine but lets allow people to lazify things\n\n        if (mask.isLazy() || trueval.isLazy() || falseval.isLazy() || AUTOLAZYON)\n        {\n            DataAbstract_ptr pm=mask.borrowDataPtr();\n            DataAbstract_ptr pt=trueval.borrowDataPtr();\n            DataAbstract_ptr pf=falseval.borrowDataPtr();\n            // now we create a lazy node for this\n            DataLazy* p=new DataLazy(pm, pt, pf);\n            return Data(p);\n        }\n        else\n        {\n            Data result(sentinel,trueval.getDataPointShape(), fs , true);  // Need to support non-expanded as well\n            // OPENMP 3.0 allows unsigned loop vars.\n#if defined(_OPENMP) && (_OPENMP < 200805)\n            long i;\n#else\n            size_t i;\n#endif\n            auto& rvec=result.getReady()->getTypedVectorRW(sentinel);      // don't need to get acquireWrite since we made it\n            unsigned int psize=result.getDataPointSize();\n                \n            size_t numsamples=result.getNumSamples();\n            size_t dppsample=result.getNumDataPointsPerSample();\n#pragma omp parallel for private(i) schedule(static)\n            for (i=0;i<numsamples;++i)\n            {\n                // We are assuming that the first datapoint in the sample determines which side to use\n                // for the whole sample.\n                const decltype(sentinel)* src=0;\n                const DataTypes::real_t* masksample=mask.getSampleDataRO(i, static_cast<DataTypes::real_t>(0));\n                if (masksample[0]>0)    // first scalar determines whole sample\n                {\n                    src=trueval.getSampleDataRO(i, sentinel);\n                }\n                else\n                {\n                    src=falseval.getSampleDataRO(i, sentinel);\n                }\n                for (int j=0;j<dppsample;++j)\n                {\n                    size_t offset=j*psize;\n                    for (long k=0;k<psize;++k)\n                    {\n                        rvec[i*dppsample*psize+offset+k]=(src)[offset+k];\n                    }\n                }\n                \n            }\n            return result;\n        }\n    } else {\n        throw DataException(\"condEval: Unsupported combination of DataAbstracts\");\n    }\n}\n\nDataTypes::RealVectorType& Data::getExpandedVectorReference(DataTypes::real_t dummy)\n{\n    if (!isExpanded())\n    {\n        expand();\n    }\n    return getReady()->getTypedVectorRW(dummy);\n}\n\nDataTypes::CplxVectorType& Data::getExpandedVectorReference(DataTypes::cplx_t dummy)\n{\n    if (!isExpanded())\n    {\n        expand();\n    }\n    return getReady()->getTypedVectorRW(dummy);\n}\n\nsize_t Data::getNumberOfTaggedValues() const\n{\n    if (isTagged())\n    {\n        return m_data->getTagCount();\n    }\n    else\n    {\n        return 0;\n    }\n}\n\n\nData escript::randomData(const boost::python::tuple& shape,\n       const FunctionSpace& what,\n       long seed, const boost::python::tuple& filter)\n{\n  \n    DataTypes::ShapeType dataPointShape;\n    for (int i = 0; i < shape.attr(\"__len__\")(); ++i) {\n        dataPointShape.push_back(bp::extract<const int>(shape[i]));\n    }  \n  \n  \n    // first check what they have asked for in filter\n    // does our domain support this?\n    if (what.getDomain()->supportsFilter(filter))\n    {\n        return what.getDomain()->randomFill(dataPointShape, what, seed, filter);\n    }\n    else\n    {\n        throw DataException(\"The specified domain does not support those filter options.\");\n    }\n}\n\n\nnamespace {\n  \nbp::object getNotImplemented()\n{\n    static bp::object notimpl=bp::object(bp::handle<>(\n                bp::borrowed(PyImport_AddModule(\"__main__\"))))\n                        .attr(\"__builtins__\").attr(\"NotImplemented\");  \n    return notimpl;\n}\n  \n}\n\n/* Implement part of pythons operator methods.\n** We are doing this rather than just using boost's overloading shortcuts because we\n** want to be able to return NotImplemented.\n*/\nbp::object Data::__add__(const bp::object& right)\n{\n    bp::extract<Data> data_extractor(right);\n    if (data_extractor.check())   // if this is wrapping a Data\n    {\n        return bp::object(*this+data_extractor());\n    }\n    bool wrapok=false;  // If the object can't be wrapped we should return NotImplemented\n    try                 // if the exception is due to something else we should rethrow it\n    {\n        WrappedArray w(right);\n        wrapok=true;\n        return bp::object(*this+Data(w, this->getFunctionSpace(), false));    \n    }\n    catch (DataException& e)\n    {\n        if (wrapok)\n        {\n            throw e;\n        }\n        return getNotImplemented();\n    }\n}\n\nbp::object Data::__sub__(const bp::object& right)\n{\n    bp::extract<Data> data_extractor(right);\n    if (data_extractor.check())   // if this is wrapping a Data\n    {\n        return bp::object(*this-data_extractor());\n    }\n    bool wrapok=false;  // If the object can't be wrapped we should return NotImplemented\n    try                 // if the exception is due to something else we should rethrow it\n    {\n        WrappedArray w(right);\n        wrapok=true;\n        return bp::object(*this-Data(w, this->getFunctionSpace(), false));  \n    }\n    catch (DataException& e)\n    {\n        if (wrapok)\n        {\n            throw e;\n        }\n        return getNotImplemented();\n    }    \n}\n\nbp::object Data::__rsub__(const bp::object& right)\n{\n    bp::extract<Data> data_extractor(right);\n    if (data_extractor.check())   // if this is wrapping a Data\n    {\n        return bp::object(data_extractor()-*this);\n    }\n    bool wrapok=false;  // If the object can't be wrapped we should return NotImplemented\n    try                 // if the exception is due to something else we should rethrow it\n    {\n        WrappedArray w(right);\n        wrapok=true;\n        return bp::object(Data(w, this->getFunctionSpace(),false)-*this); \n    }\n    catch (DataException& e)\n    {\n        if (wrapok)\n        {\n            throw e;\n        }\n        return getNotImplemented();\n    }      \n \n}\n\nbp::object Data::__mul__(const bp::object& right)\n{\n    bp::extract<Data> data_extractor(right);\n    if (data_extractor.check())   // if this is wrapping a Data\n    {\n        return bp::object(*this*data_extractor());\n    }\n    bool wrapok=false;  // If the object can't be wrapped we should return NotImplemented\n    try                 // if the exception is due to something else we should rethrow it\n    {\n        WrappedArray w(right);\n        wrapok=true;\n        return bp::object(*this*Data(w, this->getFunctionSpace(),false));  \n    }\n    catch (DataException& e)\n    {\n        if (wrapok)\n        {\n            throw e;\n        }\n        return getNotImplemented();\n    }       \n}\n\nbp::object Data::__div__(const bp::object& right)\n{\n    bp::extract<Data> data_extractor(right);\n    if (data_extractor.check())   // if this is wrapping a Data\n    {\n        return bp::object(*this/data_extractor());\n    }\n    bool wrapok=false;  // If the object can't be wrapped we should return NotImplemented\n    try                 // if the exception is due to something else we should rethrow it\n    {\n        WrappedArray w(right);\n        wrapok=true;\n        return bp::object(*this/Data(w, this->getFunctionSpace(),false));  \n    }\n    catch (DataException& e)\n    {\n        if (wrapok)\n        {\n            throw e;\n        }\n        return getNotImplemented();\n    }     \n}\n\nbp::object Data::__rdiv__(const bp::object& right)\n{\n    bp::extract<Data> data_extractor(right);\n    if (data_extractor.check())   // if this is wrapping a Data\n    {\n        return bp::object(data_extractor()/(*this));\n    }\n    bool wrapok=false;  // If the object can't be wrapped we should return NotImplemented\n    try                 // if the exception is due to something else we should rethrow it\n    {\n        WrappedArray w(right);\n        wrapok=true;\n        return bp::object(Data(w, this->getFunctionSpace(),false)/(*this));  \n    }\n    catch (DataException& e)\n    {\n        if (wrapok)\n        {\n            throw e;\n        }\n        return getNotImplemented();\n    }         \n}\n\nvoid Data::complicate()\n{\n    if (isProtected()) {\n        throw DataException(\"Error - attempt to update protected Data object.\");\n    }  \n    \n    if (m_data->isLazy())\n    {\n            // This is different to the other types because instead of switching from \n            // one internal storage vector to the other within the same node\n            // m_data needs to be replaced with an new root (promote) node.\n        DataLazy_ptr nn=dynamic_pointer_cast<DataLazy>(m_data);\n        DataLazy_ptr res=makePromote(nn);\n        set_m_data(res);\n    }\n    else\n    {\n        m_data->complicate();\n    }\n}\n\nData\nescript::C_TensorUnaryOperation(Data const &arg_0,\n                       escript::ES_optype operation,\n                       DataTypes::real_t tol)\n{\n  if (arg_0.isEmpty())  // do this before we attempt to interpolate\n  {\n     throw DataException(\"Error - Operations (C_TensorUnaryOperation) not permitted on instances of DataEmpty.\");\n  }\n  if (arg_0.isLazy())\n  {\n     throw DataException(\"Error - Operations not permitted on lazy data.\");\n  }\n  \n  if (arg_0.isComplex() && !supports_cplx(operation))\n  {\n      throw DataException(\"Error - the requested operation does not support complex values\");\n  }\n  \n  // Interpolate if necessary and find an appropriate function space\n  Data arg_0_Z = Data(arg_0);\n\n  // Get rank and shape of inputs\n  const DataTypes::ShapeType& shape0 = arg_0_Z.getDataPointShape();\n  int size0 = arg_0_Z.getDataPointSize();\n  \n  // Declare output Data object\n  Data res;\n  bool emptyResult=(arg_0_Z.getNumSamples()==0);\n  if (arg_0_Z.isConstant()) {\n    if (arg_0_Z.isComplex())                    // this is not taking into account cplx->real\n    {\n        DataTypes::cplx_t dummy=0;\n        res = Data(0.0, shape0, arg_0_Z.getFunctionSpace(),0);      // DataConstant output\n        const DataTypes::cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(0, dummy));\n        if (always_real(operation))\n        {\n\t    if (emptyResult)\n\t    {\n\t\treturn res;\n\t    }\n            DataTypes::real_t *ptr_2 = &(res.getDataAtOffsetRW(0, (real_t)(0)));\n            tensor_unary_array_operation_real(size0, ptr_0, ptr_2, operation, tol);       \n        }\n        else\n        {\n            res.complicate();\n\t    if (emptyResult)\n\t    {\n\t\treturn res;\n\t    }\t    \n            DataTypes::cplx_t *ptr_2 = &(res.getDataAtOffsetRW(0, dummy));\n            tensor_unary_array_operation(size0, ptr_0, ptr_2, operation, tol);\n        }\n    }\n    else\n    {\n        // This currently does not call the tensor_unary_array_operation_real\n        // functions like .real() and .imag() but they are caught in the Data interface\n        DataTypes::real_t dummy=0;\n        res = Data(0.0, shape0, arg_0_Z.getFunctionSpace(),false);      // DataConstant output\n\tif (emptyResult)\n\t{\n\t    return res;\n\t}\n\t\n        const DataTypes::real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(0, dummy));\n        DataTypes::real_t *ptr_2 = &(res.getDataAtOffsetRW(0, dummy));\n        if (always_real(operation))\n        {\n            tensor_unary_array_operation_real(size0, ptr_0, ptr_2, operation, tol);\n        }\n        else\n        {\n            tensor_unary_array_operation(size0, ptr_0, ptr_2, operation, tol);\n        }\n    }\n  }\n  else if (arg_0_Z.isTagged()) {\n\n    // Borrow DataTagged input from Data object\n    DataTagged* tmp_0=dynamic_cast<DataTagged*>(arg_0_Z.borrowData());\n\n    // Prepare a DataTagged output 2\n    res = Data(0.0, shape0, arg_0_Z.getFunctionSpace(),false);   // DataTagged output\n\n\n    if (arg_0_Z.isComplex())\n    {\n        if (always_real(operation))\n        {\n            res.tag();\n\t    if (emptyResult)\n\t    {\n\t\treturn res;\n\t    }\n\t    \n            DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());      \n          \n            DataTypes::cplx_t dummy=0;\n            // Get the pointers to the actual data\n            const DataTypes::cplx_t *ptr_0 = &(tmp_0->getDefaultValueRO(0,dummy));\n            DataTypes::real_t *ptr_2 = &(tmp_2->getDefaultValueRW(0,real_t(0)));\n            // Compute a result for the default\n            tensor_unary_array_operation_real(size0, ptr_0, ptr_2, operation, tol);\n            // Compute a result for each tag\n            const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n            DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n            for (i=lookup_0.begin();i!=lookup_0.end();i++) {\n              tmp_2->addTag(i->first);\n              const DataTypes::cplx_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummy));\n              DataTypes::real_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, real_t(0)));\n              tensor_unary_array_operation_real(size0, ptr_0, ptr_2, operation, tol);\n            }\n        }\n        else\n        {\n            res.complicate();\n            res.tag();\n\t    if (emptyResult)\n\t    {\n\t\treturn res;\n\t    }\n\t    \n            DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());      \n          \n            DataTypes::cplx_t dummy=0;\n            // Get the pointers to the actual data\n            const DataTypes::cplx_t *ptr_0 = &(tmp_0->getDefaultValueRO(0,dummy));\n            DataTypes::cplx_t *ptr_2 = &(tmp_2->getDefaultValueRW(0,dummy));\n            // Compute a result for the default\n            tensor_unary_array_operation(size0, ptr_0, ptr_2, operation, tol);\n            // Compute a result for each tag\n            const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n            DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n            for (i=lookup_0.begin();i!=lookup_0.end();i++) {\n              tmp_2->addTag(i->first);\n              const DataTypes::cplx_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0, dummy));\n              DataTypes::cplx_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0, dummy));\n              tensor_unary_array_operation(size0, ptr_0, ptr_2, operation, tol);\n            }\n        }\n    }\n    else\n    {\n      \n        res.tag();\n\tif (emptyResult)\n\t{\n\t    return res;\n\t}\n\t\n        DataTagged* tmp_2=dynamic_cast<DataTagged*>(res.borrowData());      \n      \n        // Get the pointers to the actual data\n        const DataTypes::real_t *ptr_0 = &(tmp_0->getDefaultValueRO(0));\n        DataTypes::real_t *ptr_2 = &(tmp_2->getDefaultValueRW(0));\n        // Compute a result for the default\n        if (always_real(operation))\n        {\n            tensor_unary_array_operation_real(size0, ptr_0, ptr_2, operation, tol);       \n        }\n        else\n        {\n            tensor_unary_array_operation(size0, ptr_0, ptr_2, operation, tol);\n        }\n        // Compute a result for each tag\n        const DataTagged::DataMapType& lookup_0=tmp_0->getTagLookup();\n        DataTagged::DataMapType::const_iterator i; // i->first is a tag, i->second is an offset into memory\n        for (i=lookup_0.begin();i!=lookup_0.end();i++) {\n          tmp_2->addTag(i->first);\n          const DataTypes::real_t *ptr_0 = &(tmp_0->getDataByTagRO(i->first,0));\n          DataTypes::real_t *ptr_2 = &(tmp_2->getDataByTagRW(i->first,0));\n          if (always_real(operation))\n          {\n              tensor_unary_array_operation_real(size0, ptr_0, ptr_2, operation, tol);\n          }\n          else\n          {\n              tensor_unary_array_operation(size0, ptr_0, ptr_2, operation, tol);\n          }\n        }\n    }\n  }\n  else if (arg_0_Z.isExpanded()) \n  {\n\n    res = Data(0.0, shape0, arg_0_Z.getFunctionSpace(),true); // DataExpanded output\n    if (arg_0_Z.isComplex() && !always_real(operation))\n    {\n        res.complicate();\n    }\n    if (emptyResult)\n    {\n\treturn res;\n    }\n    \n    DataExpanded* tmp_0=dynamic_cast<DataExpanded*>(arg_0_Z.borrowData());\n    DataExpanded* tmp_2=dynamic_cast<DataExpanded*>(res.borrowData());\n\n    int sampleNo_0,dataPointNo_0;\n    int numSamples_0 = arg_0_Z.getNumSamples();\n    int numDataPointsPerSample_0 = arg_0_Z.getNumDataPointsPerSample();\n    if (arg_0_Z.isComplex())\n    {\n        if (always_real(operation))\n        {\n            DataTypes::cplx_t dummy=0;\n            #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n            for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n                dataPointNo_0=0;\n                int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n                int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n                const DataTypes::cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummy));\n                DataTypes::real_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, real_t(0)));\n                tensor_unary_array_operation_real(size0*numDataPointsPerSample_0, ptr_0, ptr_2, operation, tol);\n            }             \n        }\n        else\n        {\n            DataTypes::cplx_t dummy=0;\n            #pragma omp parallel for private(sampleNo_0,dataPointNo_0) schedule(static)\n            for (sampleNo_0 = 0; sampleNo_0 < numSamples_0; sampleNo_0++) {\n                dataPointNo_0=0;\n                int offset_0 = tmp_0->getPointOffset(sampleNo_0,dataPointNo_0);\n                int offset_2 = tmp_2->getPointOffset(sampleNo_0,dataPointNo_0);\n                const DataTypes::cplx_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummy));\n                DataTypes::cplx_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummy));\n                tensor_unary_array_operation(size0*numDataPointsPerSample_0, ptr_0, ptr_2, operation, tol);\n            }     \n        }\n    }\n    else\n    {\n        // we require storage to be contiguous so let's do it in one chunk\n        #pragma omp parallel private(sampleNo_0,dataPointNo_0)\n        {\n#ifdef _OPENMP\n            int tid=omp_get_thread_num();\n            int mt=omp_get_num_threads();\n            int rem=numSamples_0%mt;\n            size_t samples_per=numSamples_0/mt;\n            size_t startsample=samples_per*tid+((tid<rem)?tid:rem);\n            size_t nextsample=samples_per*(tid+1)+(((tid+1)<rem)?(tid+1):rem);\n            size_t ulimit=min<size_t>(nextsample, numSamples_0);\n            size_t samples=ulimit-startsample;    \n#else\n            size_t startsample=0;\n            size_t samples=numSamples_0;\n#endif      \n            if (startsample<numSamples_0)\n            {\n\t        real_t dummyr=0;\n                size_t offset_0 = tmp_0->getPointOffset(startsample,0);\n                size_t offset_2 = tmp_2->getPointOffset(startsample,0);\n                const DataTypes::real_t *ptr_0 = &(arg_0_Z.getDataAtOffsetRO(offset_0, dummyr));\n                DataTypes::real_t *ptr_2 = &(res.getDataAtOffsetRW(offset_2, dummyr));\n                if (always_real(operation))\n                {\n                    tensor_unary_array_operation_real(size0*samples*numDataPointsPerSample_0, ptr_0, ptr_2, operation, tol);\n                }\n                else\n                {\n                    tensor_unary_array_operation(size0*samples*numDataPointsPerSample_0, ptr_0, ptr_2, operation, tol);\n                }\n            }\n        }           \n    }\n  }\n  else {\n    throw DataException(\"Error - C_TensorUnaryOperation: unknown combination of inputs\");\n  }\n\n  return res;\n}\n\nData\nescript::C_TensorBinaryOperation(Data const &arg_0,\n                        Data const &arg_1,\n                        escript::ES_optype operation)\n{\n  if (arg_0.isEmpty() || arg_1.isEmpty())\n  {\n     throw DataException(\"Error - Operations (C_TensorBinaryOperation) not permitted on instances of DataEmpty.\");\n  }\n  if (arg_0.isLazy() || arg_1.isLazy())\n  {\n     throw DataException(\"Error - Operations not permitted on lazy data.\");\n  }\n  \n  // Interpolate if necessary and find an appropriate function space\n  Data arg_0_Z, arg_1_Z;\n  FunctionSpace fsl=arg_0.getFunctionSpace();\n  FunctionSpace fsr=arg_1.getFunctionSpace();\n  if (fsl!=fsr) {\n     signed char intres=fsl.getDomain()->preferredInterpolationOnDomain(fsr.getTypeCode(), fsl.getTypeCode());\n     if (intres==0)\n     {\n         std::string msg=\"Error - C_TensorBinaryOperation: arguments have incompatible function spaces.\";\n         msg+=fsl.toString();\n         msg+=\" \";\n         msg+=fsr.toString();\n         throw DataException(msg.c_str());\n     } \n     else if (intres==1)\n     {\n      arg_1_Z=arg_1.interpolate(arg_0.getFunctionSpace());\n      arg_0_Z =Data(arg_0);      \n     }\n     else\t// reverse interpolation preferred\n     {\n      arg_0_Z = arg_0.interpolate(arg_1.getFunctionSpace());\n      arg_1_Z = Data(arg_1);\n     }    \n  } else {\n      arg_0_Z = Data(arg_0);\n      arg_1_Z = Data(arg_1);\n  }\n  DataTypes::ShapeType shape0 = arg_0_Z.getDataPointShape();\n  DataTypes::ShapeType shape1 = arg_1_Z.getDataPointShape();\n  \n  DataTypes::ShapeType resultshape=((arg_0_Z.getDataPointRank()!=0)?shape0:shape1);\n\n  bool emptyResult=((arg_0_Z.getNumSamples()==0) || (arg_1_Z.getNumSamples()==0));\n  if ((shape0==shape1) || (arg_0_Z.getDataPointRank()==0) || (arg_1_Z.getDataPointRank()==0))\n  {\n    if (arg_0_Z.isConstant()   && arg_1_Z.isConstant())\n    {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(),false);      // DataConstant output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      if (!emptyResult)\n      {      \n          binaryOpDataCCC(*dynamic_cast<DataConstant*>(res.borrowData()), *dynamic_cast<const DataConstant*>(arg_0_Z.borrowData()), *dynamic_cast<const DataConstant*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isConstant()   && arg_1_Z.isTagged())\n    {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(), false);      // DataTagged output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      res.tag();\n      if (!emptyResult)\n      {\n          binaryOpDataTCT(*dynamic_cast<DataTagged*>(res.borrowData()), *dynamic_cast<const DataConstant*>(arg_0_Z.borrowData()), *dynamic_cast<const DataTagged*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isConstant()   && arg_1_Z.isExpanded())\n    {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      if (!emptyResult)\n      {\n          binaryOpDataECE(*dynamic_cast<DataExpanded*>(res.borrowData()), *dynamic_cast<const DataConstant*>(arg_0_Z.borrowData()), *dynamic_cast<const DataExpanded*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isTagged()     && arg_1_Z.isConstant())\n    {\n      Data res(0.0, resultshape, arg_0_Z.getFunctionSpace(),false);      // DataTagged output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      res.tag();\n      if (!emptyResult)\n      {\n          binaryOpDataTTC(*dynamic_cast<DataTagged*>(res.borrowData()), *dynamic_cast<const DataTagged*>(arg_0_Z.borrowData()), *dynamic_cast<const DataConstant*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isTagged()     && arg_1_Z.isTagged())\n    {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(), false);\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      res.tag();        // DataTagged output\n      if (!emptyResult)\n      {\n          binaryOpDataTTT(*dynamic_cast<DataTagged*>(res.borrowData()), *dynamic_cast<const DataTagged*>(arg_0_Z.borrowData()), *dynamic_cast<const DataTagged*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isTagged()     && arg_1_Z.isExpanded())\n    {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      if (!emptyResult)\n      {\n          binaryOpDataETE(*dynamic_cast<DataExpanded*>(res.borrowData()), *dynamic_cast<const DataTagged*>(arg_0_Z.borrowData()), *dynamic_cast<const DataExpanded*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isExpanded()   && arg_1_Z.isConstant()) {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      if (!emptyResult)\n      {\n          binaryOpDataEEC(*dynamic_cast<DataExpanded*>(res.borrowData()), *dynamic_cast<const DataExpanded*>(arg_0_Z.borrowData()), *dynamic_cast<const DataConstant*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isExpanded()   && arg_1_Z.isTagged()) {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      if (!emptyResult)\n      {\n          binaryOpDataEET(*dynamic_cast<DataExpanded*>(res.borrowData()), *dynamic_cast<const DataExpanded*>(arg_0_Z.borrowData()), *dynamic_cast<const DataTagged*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else if (arg_0_Z.isExpanded()   && arg_1_Z.isExpanded()) {\n      Data res(0.0, resultshape, arg_1_Z.getFunctionSpace(),true); // DataExpanded output\n      if (arg_0_Z.isComplex() || arg_1_Z.isComplex())\n      {\n        res.complicate();\n      }\n      if (!emptyResult)\n      {\n          binaryOpDataEEE(*dynamic_cast<DataExpanded*>(res.borrowData()), *dynamic_cast<const DataExpanded*>(arg_0_Z.borrowData()), *dynamic_cast<const DataExpanded*>(arg_1_Z.borrowData()), operation);\n      }\n      return res;\n    }\n    else {\n      throw DataException(\"Error - C_TensorBinaryOperation: unknown combination of inputs\");\n    }\n  } else {\n    throw DataException(\"Error - C_TensorBinaryOperation: arguments have incompatible shapes\");\n  }\n}\n\n\nvoid\nData::TensorSelfUpdateBinaryOperation(const Data& right,\n                   escript::ES_optype operation)\n{\n   //\n   // if this has a rank of zero promote it to the rank of the RHS\n   if (getDataPointRank()==0 && right.getDataPointRank()!=0) {\n     throw DataException(\"Error - attempt to update rank zero object with object with rank bigger than zero.\");\n   }\n\n   if (isLazy() || right.isLazy())\n   {\n     throw DataException(\"Programmer error - attempt to call binaryOp with Lazy Data.\");\n   }\n   //\n   // initially make the temporary a shallow copy\n   Data tempRight(right);\n   FunctionSpace fsl=getFunctionSpace();\n   FunctionSpace fsr=right.getFunctionSpace();\n   if (fsl!=fsr) {\n     signed char intres=fsl.getDomain()->preferredInterpolationOnDomain(fsr.getTypeCode(), fsl.getTypeCode());\n     if (intres==0)\n     {\n         std::string msg=\"Error - attempt to combine incompatible FunctionSpaces.\";\n         msg+=fsl.toString();\n         msg+=\"  \";\n         msg+=fsr.toString();\n         throw DataException(msg.c_str());\n     } \n     else if (intres==1)\n     {\n       // an interpolation is required so create a new Data\n       tempRight=Data(right,fsl);\n     }\n     else       // reverse interpolation preferred\n     {\n        // interpolate onto the RHS function space\n       Data tempLeft(*this,fsr);\n       set_m_data(tempLeft.m_data);\n     }\n   }\n   operandCheck(tempRight);\n   //\n   // ensure this has the right type for the RHS\n   typeMatchRight(tempRight);\n   //\n   // Need to cast to the concrete types so that the correct binaryOp\n   // is called.\n   if (isExpanded()) {\n     //\n     // Expanded data will be done in parallel, the right hand side can be\n     // of any data type\n     DataExpanded* leftC=dynamic_cast<DataExpanded*>(m_data.get());\n     ESYS_ASSERT(leftC!=NULL, \"Programming error - casting to DataExpanded.\");\n     \n     if (right.isExpanded())\n     {\n\tbinaryOpDataEEE(*leftC, *leftC, *dynamic_cast<const DataExpanded*>(tempRight.getReady()), operation);\n     }\n     else if (right.isTagged())\n     {\n\tbinaryOpDataEET(*leftC, *leftC, *dynamic_cast<const DataTagged*>(tempRight.getReady()), operation);\n     }\n     else\t// it's constant\n     {\n\tbinaryOpDataEEC(*leftC, *leftC, *dynamic_cast<const DataConstant*>(tempRight.getReady()), operation);\n     }\n       \n     //escript::binaryOpDataReady(*leftC,*(tempRight.getReady()),operation);\n   } else if (isTagged()) {\n     //\n     // Tagged data is operated on serially, the right hand side can be\n     // either DataConstant or DataTagged\n     DataTagged* leftC=dynamic_cast<DataTagged*>(m_data.get());\n     ESYS_ASSERT(leftC!=NULL, \"Programming error - casting to DataTagged.\");\n     if (right.isTagged()) {\n       DataTagged* rightC=dynamic_cast<DataTagged*>(tempRight.m_data.get());\n       ESYS_ASSERT(rightC!=NULL, \"Programming error - casting to DataTagged.\");\n       binaryOpDataTTT(*leftC, *leftC, *rightC, operation);\n       //escript::binaryOpDataReady(*leftC,*rightC,operation);\n     } else {\n       DataConstant* rightC=dynamic_cast<DataConstant*>(tempRight.m_data.get());\n       ESYS_ASSERT(rightC!=NULL, \"Programming error - casting to DataConstant.\");\n       binaryOpDataTTC(*leftC, *leftC, *rightC, operation);\n       //escript::binaryOpDataReady(*leftC,*rightC,operation);\n     }\n   } else if (isConstant()) {\n     DataConstant* leftC=dynamic_cast<DataConstant*>(m_data.get());\n     DataConstant* rightC=dynamic_cast<DataConstant*>(tempRight.m_data.get());\n     ESYS_ASSERT(leftC!=NULL && rightC!=NULL, \"Programming error - casting to DataConstant.\");\n     binaryOpDataCCC(*leftC, *leftC, *rightC, operation);\n     //escript::binaryOpDataReady(*leftC,*rightC,operation);\n   }  \n}\n\n#if 0\nvoid\nData::binaryDataOp(const Data& right,\n                   escript::ES_optype operation)\n{\n   //\n   // if this has a rank of zero promote it to the rank of the RHS\n   if (getDataPointRank()==0 && right.getDataPointRank()!=0) {\n     throw DataException(\"Error - attempt to update rank zero object with object with rank bigger than zero.\");\n   }\n\n   if (isLazy() || right.isLazy())\n   {\n     throw DataException(\"Programmer error - attempt to call binaryOp with Lazy Data.\");\n   }\n   //\n   // initially make the temporary a shallow copy\n   Data tempRight(right);\n   FunctionSpace fsl=getFunctionSpace();\n   FunctionSpace fsr=right.getFunctionSpace();\n   if (fsl!=fsr) {\n     signed char intres=fsl.getDomain()->preferredInterpolationOnDomain(fsr.getTypeCode(), fsl.getTypeCode());\n     if (intres==0)\n     {\n         std::string msg=\"Error - attempt to combine incompatible FunctionSpaces.\";\n         msg+=fsl.toString();\n         msg+=\"  \";\n         msg+=fsr.toString();\n         throw DataException(msg.c_str());\n     } \n     else if (intres==1)\n     {\n       // an interpolation is required so create a new Data\n       tempRight=Data(right,fsl);\n     }\n     else       // reverse interpolation preferred\n     {\n        // interpolate onto the RHS function space\n       Data tempLeft(*this,fsr);\n       set_m_data(tempLeft.m_data);\n     }\n   }\n   operandCheck(tempRight);\n   //\n   // ensure this has the right type for the RHS\n   typeMatchRight(tempRight);\n   //\n   // Need to cast to the concrete types so that the correct binaryOp\n   // is called.\n   if (isExpanded()) {\n     //\n     // Expanded data will be done in parallel, the right hand side can be\n     // of any data type\n     DataExpanded* leftC=dynamic_cast<DataExpanded*>(m_data.get());\n     ESYS_ASSERT(leftC!=NULL, \"Programming error - casting to DataExpanded.\");\n     escript::binaryOpDataReady(*leftC,*(tempRight.getReady()),operation);\n   } else if (isTagged()) {\n     //\n     // Tagged data is operated on serially, the right hand side can be\n     // either DataConstant or DataTagged\n     DataTagged* leftC=dynamic_cast<DataTagged*>(m_data.get());\n     ESYS_ASSERT(leftC!=NULL, \"Programming error - casting to DataTagged.\");\n     if (right.isTagged()) {\n       DataTagged* rightC=dynamic_cast<DataTagged*>(tempRight.m_data.get());\n       ESYS_ASSERT(rightC!=NULL, \"Programming error - casting to DataTagged.\");\n       escript::binaryOpDataReady(*leftC,*rightC,operation);\n     } else {\n       DataConstant* rightC=dynamic_cast<DataConstant*>(tempRight.m_data.get());\n       ESYS_ASSERT(rightC!=NULL, \"Programming error - casting to DataConstant.\");\n       escript::binaryOpDataReady(*leftC,*rightC,operation);\n     }\n   } else if (isConstant()) {\n     DataConstant* leftC=dynamic_cast<DataConstant*>(m_data.get());\n     DataConstant* rightC=dynamic_cast<DataConstant*>(tempRight.m_data.get());\n     ESYS_ASSERT(leftC!=NULL && rightC!=NULL,\n             \"Programming error - casting to DataConstant.\");\n     escript::binaryOpDataReady(*leftC,*rightC,operation);\n   }  \n}\n\n#endif\n\n", "meta": {"hexsha": "926257aab939a7e5eaab44f6483c9f965b0180f6", "size": 211252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "escriptcore/src/Data.cpp", "max_stars_repo_name": "svn2github/Escript", "max_stars_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "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": "escriptcore/src/Data.cpp", "max_issues_repo_name": "svn2github/Escript", "max_issues_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T03:07:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T03:07:43.000Z", "max_forks_repo_path": "escriptcore/src/Data.cpp", "max_forks_repo_name": "svn2github/Escript", "max_forks_repo_head_hexsha": "9c616a3b164446c65d4b8564ecd04fafd7dcf0d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4831594635, "max_line_length": 201, "alphanum_fraction": 0.6037149944, "num_tokens": 56463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1943678110187447, "lm_q2_score": 0.028870904543998464, "lm_q1q2_score": 0.005611574518348111}}
{"text": "// -*- mode: c++ -*-\n// WangLandau.hpp replaces mjson with libjson C++ class for JSON parser\n#ifndef LSMS_WANG_LANDAU_H\n#define LSMS_WANG_LANDAU_H\n\n#include <cstdio>\n#include <string>\n#include <vector>\n#include <utility>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n// we use BOOST for the random number generator\n// #include <boost/random.hpp>\n#include <random>\n#include \"../../libjson/json.hpp\"\n// #include \"../../mjson/json.h\"\n#include \"EvecGenerator.h\"\n#include \"Graph1dMoments.hpp\"\n#include \"SystemParameters.hpp\"\n#include \"../Potential/PotentialShifter.hpp\"\n\nvoid inline performGlobalUpdate(Graph1dMoments<double,double> &g, double kappa, double lambda, double omega)\n{\n  for(int i=0; i<g.getN(); i++)\n    if(g[i]>omega) g[i]+=kappa*std::exp(-lambda/(g[i]-omega));\n}\n\nclass StatesWriter\n{\npublic:\n  StatesWriter(const char *filename=NULL)\n  {\n    if(filename==NULL) writeFlag=false;\n    else {writeFlag=true; of.open(filename);\n      of.setf(std::ios::scientific,std::ios::floatfield);\n      of.precision(17);}\n  }\n  ~StatesWriter() {if(writeFlag) of.close();}\n  void writeHeader(double lnF, int numWalk, int numSpin, double **spins)\n  {\n    if(writeFlag)\n      {\n\tof<<lnF<<\" \"<<numWalk<<\" \"<<numSpin<<std::endl;\n\tfor(int i=0; i<numWalk; i++)\n\t  {\n\t    of<<i;\n\t    for(int j=0; j<3*numSpin; j++) of<<\" \"<<spins[i][j];\n\t    of<<std::endl;\n\t  }\n      }\n  }\n  void writeChange(int iWalk, int numRet, int ispin, double *ev, double E)\n  {\n    if(writeFlag)\n      of<<iWalk<<\" \"<<numRet<<\" \"<<ispin<<\" \"<<ev[0]<<\" \"<<ev[1]<<\" \"<<ev[2]<<\" \"<<E<<std::endl;\n  }\n  void writeChangeOcc(int iWalk, int numRet, int i, int j, int occ_i, int occ_j, double E)\n  {\n    if(writeFlag)\n      of<<iWalk<<\" \"<<numRet<<\" (\"<<i<<\"<-->\"<<j<<\") \"<<occ_i<<\" \"<< occ_j <<\" \"<<E<<std::endl;\n  }\n  void newFile(const char *filename=NULL)\n  {\n    if(writeFlag) of.close();\n    writeFlag=false;\n    if(filename!=NULL){\n      writeFlag=true;\n      of.open(filename);\n      of.setf(std::ios::scientific,std::ios::floatfield);\n      of.precision(8);\n    }\n  }\nprivate:\n  bool writeFlag;\n  std::ofstream of;\n};\n\ntemplate<class RNG = std::mt19937>\n// template<class RNG = boost::mt19937>\nclass WL1dEvecGenerator : public EvecGenerator\n{\n public:\n  WL1dEvecGenerator(int num_spins, int num_instances, double ** ev_p,\n                    PotentialShifter &potentialShifter,\n                    const char *init_file_name=NULL, const char *out_file_name=NULL,\n                    const char *states_filename=NULL);\n\n  bool determineAcceptance(int instance, double energy);\n  bool determineAcceptance(int instance, double energy, double magnetization);\n\n  bool updateHistogram(int instance, double *evecs, bool accepted);\n/*\n  bool updateHistogram(int instance, double *evecs, double energy, bool *accepted);\n  bool updateHistogram(int instance, double *evecs, double energy, double magnetization, bool *accepted);\n  bool updateHistogram(int instance, double *evecs, double energy) {bool h; return updateHistogram(instance, evecs, energy, &h);}\n  bool updateHistogram(int instance, double *evecs) {std::cerr<<\"Need energy for WL1dEvecGenerator\\n\"; exit(1);}\n*/\n\n  void generateEvec(int instance, double *evecs, bool accepted);\n  //void generateEvec(int instance, double *evecs, double energy);\n  void generatePotentialShift(int instance, double *potentialShifts, bool accepted);\n\n  void initializeEvecAndPotentialShift(int inst, double *evecs, double *potentialShifts);\n  void initializeEvec(int instance, double *evecs);\n\n  // Wang-Landau for occupancy variables\n  MoveChoice_t selectMoveType(bool isSpinSim, bool isOccSim);\n  void setAlloyClasses(AlloyMixingDesc&, int* siteclass);\n  void generateOccupancies(int instance, int *occ, bool acceptedOcc);\n  void generateUnsampledOcc(int inst, int *occ);\n  void initializeOccupancies(int inst, int *occ);\n  void updateLog(int instance, double *evecs, int * occ, bool accepted, MoveChoice_t MoveChoice);\n\n  void generateUnsampledEvec(int instance, double *evecs, double energy)\n  {\n    initializeEvec(instance, evecs); \n    //return false;\n  }\n\n  void startSampling(void)\n  { sw.writeHeader(gamma, n_walkers, n_spins, evecs_pointer); }\n\n  void writeState(const char *name);\n  void writeDos(const char *name);\n\n private:\n  size_t n_walkers;\n  int n_spins;\n  double ** evecs_pointer;\n  int n_initialized_from_file;\n\n  std::string dos_out_name;\n\n  int stepsSinceLastHistogramUpdate;\n  int numberOfUpdatesSinceLastBoost;\n  int cycleCount;\n  int modificationFactorChanges;\n\n  // Random number generator and distribution:\n  RNG rng;\n  // boost::uniform_real<double> rnd; //, rnd11(-1.0,1.0),rnd0pi(0.0,2.0*M_PI);\n  std::uniform_real_distribution<double> rnd; //, rnd11(-1.0,1.0),rnd0pi(0.0,2.0*M_PI);\n  std::uniform_real_distribution<double> rnd01; //(0.0,1.0);\n\n  /*\n  // Histogramm and dos:\n  double xMin, xMax, interval;\n  int nX;\n  double *dos; // std::vector<double> dos;\n  int *histo; // std::vector<int> histo;\n  int hMinimum;\n  */\n\n  double hMinimum;\n  Graph1dMoments<double,double> dos, histo;\n  Kernel1d<double,double> dosKernel, histoKernel, nullKernel;\n  KernelType kernelType;\n\n  unsigned long accept, reject, acceptSinceLastChange;\n  double flatnessCriterion;\n\n  double gamma, gammaFinal;\n  int flipPerUpdate, updateCycle;\n\n  // instance specific:\n  std::vector<long> ref0, ref1;\n  std::vector<double> position, magnetizationAtPosition;\n  std::vector<bool> out;\n  std::vector<int> lastChange;\n  std::vector<int> lastChangePotentialShift;\n  std::vector<int> lastAccepted;\n  std::vector<int> lastAcceptedPotentialShiftIndex;\n  std::vector<double> lastAcceptedEnergy;\n  std::vector<double> lastAcceptedEvec;\n  std::vector<double> oldSpin;  // oldSpin[instance*3 + {x=0, y=1, z=2}]\n  std::vector<double> oldPotentialShift;\n  std::vector<double> lastAcceptedPotentialShift;\n\n  // changes to accomodate alloying (i.e. variable site occupancies)\n  std::vector< std::pair<int,int> > lastSwapOcc;\n  std::vector< std::pair<int,int> > lastAcceptedSwap;\n  AlloyMixingDesc& alloyDesc;\n  std::vector<int> siteAlloyClass;\n  std::vector<int> numSites_per_AlloyClass;\n\n  std::vector<int> numRetentions;\n\n  char *statesFile;\n  StatesWriter sw;\n\n  int changeMode;\n  bool histogramUpdateMode;\n  int updatesPerBin;\n\n  struct {double kappa, lambda, omega; int frequency, changes;} globalUpdate;\n\n#ifdef ISING\n    void inline random_evec_1(double ev[3])\n  {\n    ev[0]=ev[1]=0.0;\n    ev[2]=1.0;\n    if(rng()%2 == 0) ev[2]=-ev[2];\n  }\n#else\n  void inline random_evec_1(double ev[3])\n  {\n    double x,y,z;\n    do {\n      x = rnd(rng);\n      y = rnd(rng);\n    } while(x*x+y*y>1);\n    z = rnd(rng);\n    double r = sqrt((1-z*z)/(x*x+y*y));\n    x *= r;\n    y *= r;\n    if (rng() % 2 == 0) x = -x;\n    if (rng() % 2 == 0) y = -y;\n    if (rng() % 2 == 0) z = -z;\n    r=1.0/sqrt(x*x+y*y+z*z);\n    ev[0]=x*r; ev[1]=y*r; ev[2]=z*r;\n  }\n#endif\n\n#ifdef ISING    \n  void inline random_evec(double ev[3])\n  {\n    ev[2]=-ev[2];\n  }\n#else\n  void inline random_evec(double ev[3])\n  {\n    double x, y, z;\n    do {\n      x = rnd(rng); y = rnd(rng);\n    } while(x*x+y*y>1); \n    z = rnd(rng);\n    double r = sqrt((1-z*z)/(x*x+y*y));\n    x *= r; y*= r;\n    if (rng() % 2 == 0) x = -x;\n    if (rng() % 2 == 0) y = -y;\n    if (rng() % 2 == 0) z = -z; \n    // Project out the parallel component;\n    r = x*ev[0] + y*ev[1] + z*ev[2];\n    x -= r*ev[0]; y -= r*ev[1]; z -= r*ev[2];\n    r = x*x + y*y + z*z;\n    double t = 1-0.3*rnd(rng);\n    ev[0] *= t; ev[1] *= t; ev[2] *= t;\n    r = sqrt((1-t*t)/r);\n    ev[0] += x*r; ev[1] += y*r; ev[2] += z*r;\n    r=1.0/sqrt(ev[0]*ev[0]+ev[1]*ev[1]+ev[2]*ev[2]);\n    ev[0]*=r; ev[1]*=r; ev[2]*=r;\n    \n    /*  \n    ev[2]=1.0-2.0*rnd(rng);\n    // ev[2]=rnd11(rng);\n    double phi=2.0*M_PI*rnd(rng);\n    // double phi=rnd0pi(rng);\n    double cos_theta=sqrt(1-ev[2]*ev[2]);\n    ev[0]=cos_theta*cos(phi);\n    ev[1]=cos_theta*sin(phi);\n    */  \n  }\n#endif\n\n  double minVxShift {0.0}, maxVxShift {0.0}, rangeVxShift {0.0};\n\n  double inline randomPotentialShift()\n  {\n    return minVxShift + rangeVxShift * rnd01(rng);\n  }\n};\n\ntemplate<typename T>\nvoid getValue(JSON::Value &data, const char *key, T &val)\n{ if(data[key].type()!=JSON::NIL) val=(T)data[key]; }\n\n\ntemplate<class RNG>\nWL1dEvecGenerator<RNG>::WL1dEvecGenerator(int num_spins, int num_instances, double ** ev_p,\n                                          PotentialShifter &potentialShifter,\n\t\t\t\t\t  const char *init_file_name, const char *out_file_name, \n                                          const char *states_filename)\n: sw(states_filename)\n{\n\n  printf(\"Running WL1D constructor!\\n\");\n\n  if (potentialShifter.vSpinShiftFlag) {\n    minVxShift = potentialShifter.minShift;\n    maxVxShift = potentialShifter.maxShift;\n    rangeVxShift = maxVxShift - minVxShift;\n  }\n\n  verbosity=3;\n\n  changeMode = 8+16;\n\n  globalUpdate.frequency=0;\n  globalUpdate.changes=0;\n  globalUpdate.kappa=1.0;\n  globalUpdate.lambda=1.0;\n  globalUpdate.omega=0.5;\n\n  long nX=-1;\n  histogramUpdateMode=false;\n  updatesPerBin=100;\n  double interval=0.01;\n  double kernelWidth=0.1;\n  double xMin=-HUGE;\n  double xMax=1.0;\n  bool readPositions=false;\n  n_spins=num_spins;\n  n_walkers = num_instances;\n  n_initialized_from_file = 0;\n  evecs_pointer = ev_p;\n  ref0.resize(n_walkers);  for(int i=0; i<n_walkers; i++) ref0[i]=-1; // ref0[i]=HUGE;\n  ref1.resize(n_walkers);\n  position.resize(n_walkers);\n  magnetizationAtPosition.resize(n_walkers);\n  out.resize(n_walkers);\n  lastChange.resize(n_walkers);\n  lastAccepted.resize(n_walkers);\n  lastAcceptedEnergy.resize(n_walkers);\n  lastAcceptedEvec.resize(3*n_walkers);\n\n  oldPotentialShift.resize(n_walkers);\n\n  lastChangePotentialShift.resize(n_walkers);\n  lastAcceptedPotentialShiftIndex.resize(n_walkers);\n  lastAcceptedPotentialShift.resize(n_walkers);\n\n  lastSwapOcc.resize(n_walkers);\n  lastAcceptedSwap.resize(n_walkers);\n\n  for(int i=0; i<n_walkers; i++)\n  {\n    lastAccepted[i]=-2;\n    lastAcceptedPotentialShiftIndex[i] = -2;\n    lastAcceptedPotentialShift[i] = 0.0;\n  }\n  for(int i=0; i<3*n_walkers; i++)  lastAcceptedEvec[i]=0.0;\n\n  for(int i=0; i<n_walkers; i++) initializeEvec(i,evecs_pointer[i]);\n\n  oldSpin.resize(3*n_walkers);\n\n  statesFile=NULL;\n  if(states_filename!=NULL)\n    {\n      statesFile=(char *)malloc(sizeof(char)*(1+strlen(states_filename)));\n      strcpy(statesFile,states_filename);\n    }\n\n  numRetentions.resize(n_walkers);\n  for(int i=0; i<n_walkers; i++) numRetentions[i]=0;\n\n  /*\n  nX = -1;\n  xMin = -HUGE; xMax= 1.0; interval = 0.01; // (xMax-xMin)/double(nX);\n  */\n  dos_out_name=\"dos1d.out\";\n  stepsSinceLastHistogramUpdate=0;\n  numberOfUpdatesSinceLastBoost=0;\n  modificationFactorChanges=0;\n  cycleCount=0;\n  hMinimum= 1;     //   10\n  acceptSinceLastChange=accept=reject=0;\n  gammaFinal=1.e-6;\n  flipPerUpdate=1; //  100\n  updateCycle= 5*num_instances;  // 1000\n  gamma = 1.0;\n  flatnessCriterion = 0.75;\n  updatesPerBin =100;\n\n  kernelType=None;\n\n  // special processing flags:\n  int clearHistogram = 0;\n  int setFirstWalkerToFM = 0;\n\n  // dos = NULL;   // dos.resize(nX);\n  // histo = NULL; // histo.resize(nX);\n  dos.setDeltaAndClear(interval);\n  histo.setDeltaAndClear(interval);\n\n  if(init_file_name!=NULL && init_file_name[0]!=0)\n  {\n    std::string label, value;\n\n    std::cout<<\"Reading Wang-Landau configuration from: \"<<init_file_name<<std::endl;\n\n    dos_out_name=std::string(init_file_name)+\".out\";\n    if(out_file_name!=NULL && out_file_name[0]!=0) dos_out_name=out_file_name;\n    std::ifstream inp(init_file_name);\n    std::ostringstream buff;\n\n    std::string line;\n    while(std::getline(inp,line)) \n      buff << line << std::endl;\n\n    inp.close();\n\n    std::string fileString = buff.str();\n    const char* fileChars  = fileString.c_str();\n\n    // json_t *json_root=NULL;\n    JSON::Value data=parse_file(fileChars);\n    // json_parse_document(&json_root, (char *)fileChars);\n\n    if(data.type() != JSON::OBJECT)\n    {\n      std::ostringstream message;\n      std::cerr << \"In WL1dEvecGenerator(\" << init_file_name << \") parsing failed (bad format)\\n\";\n      exit(1);\n    }\n  \n// check if the input file is for start (specifies \"interval\") or a restart (specifies \"nX\")\n\n    if(data[\"nX\"].type()==JSON::NIL) // initial WLstart file\n    {\n      interval=data[\"interval\"].as_float();\n    } else {\n      xMin=data[\"xMin\"].as_float();\n      xMax=data[\"xMax\"].as_float();\n      nX=data[\"nX\"].as_int();\n      dos.setRangeAndClear(xMin,xMax,nX);\n      histo.setRangeAndClear(xMin,xMax,nX);\n    }\n\n// common data for both start and restart files\n    getValue(data,\"gamma\",gamma);\n    getValue(data,\"gammaFinal\",gammaFinal);\n    getValue(data,\"kernelWidth\",kernelWidth);\n    if(data[\"kernelType\"].type()==JSON::STRING) { std::string str=data[\"kernelType\"].as_string(); kernelType=getKernelType(str); }\n    getValue(data,\"flipPerUpdate\",flipPerUpdate);\n    getValue(data,\"updateCycle\",updateCycle);\n    getValue(data,\"cycleCount\",cycleCount);\n    getValue(data,\"changeMode\",changeMode);\n    getValue(data,\"flatnessCriterion\",flatnessCriterion);\n    getValue(data,\"histogramMinimum\",hMinimum);\n    getValue(data,\"updatesPerBin\",updatesPerBin);\n    getValue(data,\"globalUpdate.frequency\",globalUpdate.frequency);\n    getValue(data,\"globalUpdate.changes\",globalUpdate.changes);\n    getValue(data,\"globalUpdate.kappa\",globalUpdate.kappa);\n    getValue(data,\"globalUpdate.lambda\",globalUpdate.lambda);\n    getValue(data,\"globalUpdate.omega\",globalUpdate.omega);\n    if(data[\"seed\"].type()!=JSON::NIL) rng.seed(data[\"seed\"].as_int());\n    if(data[\"rngState\"].type()==JSON::STRING)\n    {\n      std::string str=data[\"rngState\"].as_string();\n      std::stringstream strStream(str, std::stringstream::in);\n      strStream>>rng;\n    }\n    getValue(data,\"accept\",accept);\n    getValue(data,\"acceptSinceLastChange\",acceptSinceLastChange);\n    getValue(data,\"reject\",reject);\n\n    getValue(data,\"stepsSinceLastHistogramUpdate\",stepsSinceLastHistogramUpdate);\n    getValue(data,\"numberOfUpdatesSinceLastBoost\",numberOfUpdatesSinceLastBoost);\n    getValue(data,\"modificationFactorChanges\",modificationFactorChanges);\n    getValue(data,\"clearHistogram\",clearHistogram);\n    getValue(data,\"setFirstWalkerToFM\",setFirstWalkerToFM);\n\n    if(data[\"dos\"].type()==JSON::ARRAY)\n    {\n      const JSON::Array &a=data[\"dos\"].as_array();\n      if(a.size()!=nX) {std::cout<<\"ERROR #(dos) \"<<a.size()<<\" != nX \"<<dos.getN()<<std::endl; exit(1);}\n      for(size_t i=0; i<nX; i++) dos[i]=a[i].as_float();\n    }\n\n    if(data[\"histo\"].type()==JSON::ARRAY)\n    {\n      const JSON::Array &a=(JSON::Array)data[\"histo\"];\n      if(a.size()!=nX) {std::cout<<\"ERROR #(histo) \"<<a.size()<<\" != nX \"<<histo.getN()<<std::endl; exit(1);}\n      for(size_t i=0; i<nX; i++) histo[i]=a[i].as_float();\n    }\n\n    if(data[\"moments.k\"].type()!=JSON::NIL) dos.setNumberOfMoments(data[\"moments.k\"].as_int());\n    if(data[\"moments\"].type()==JSON::ARRAY)\n    {\n      const JSON::Array &a=(JSON::Array)data[\"moments\"];\n      int k=a[0].as_int();\n      dos.setNumberOfMoments(k);\n      const JSON::Array &b=(JSON::Array)a[1]; // Samples At Index\n      for(size_t i=0; i<nX; i++)\n        dos.setNumberOfSamplesAtIdx(i,b[i].as_int());\n      for(int j=0; j<k; j++)\n      {\n        const JSON::Array &c=(JSON::Array)a[2+j];\n        for(size_t i=0; i<nX; i++)\n          dos.setMomentAtIdx(i,j,c[i].as_float()); \n      }\n    }\n\n    if(data[\"evecs\"].type()!=JSON::NIL)\n    {\n      const JSON::Array &a=(JSON::Array)data[\"evecs\"];\n      n_initialized_from_file=std::min(n_walkers,a.size());\n      for(int j=0; j<n_initialized_from_file; j++)\n      {\n        const JSON::Array &b=(JSON::Array)a[j];\n        for(size_t i=0; i<3*nX; i++)\n          evecs_pointer[j][i]=b[i].as_float();\n// // initialize oldSpin and lastChange to point to site 0\n//            lastChange[n_initialized_from_file]=0;\n//            oldSpin[  3*n_initialized_from_file]=evecs_pointer[n_initialized_from_file][0];\n//            oldSpin[1+3*n_initialized_from_file]=evecs_pointer[n_initialized_from_file][1];\n//            oldSpin[2+3*n_initialized_from_file]=evecs_pointer[n_initialized_from_file][2];\n// //\n      }\n    }\n    if(data[\"oldSpin\"].type()!=JSON::NIL)\n    {\n      const JSON::Array &a=(JSON::Array)data[\"oldSpin\"];\n      int n_initialized=std::min(n_walkers,a.size());\n      for(int j=0; j<n_initialized; j++)\n      {\n        for(int i=0; i<3; i++)\n          oldSpin[j*3+i]=a[j][i].as_float();\n      }\n    }\n    if(data[\"lastChange\"].type()!=JSON::NIL)\n    {\n      const JSON::Array &a=(JSON::Array)data[\"lastChange\"];\n      int n_initialized=std::min(n_walkers,a.size());\n      for(int i=0; i<n_initialized; i++)\n        lastChange[i]=a[i].as_int();\n    }\n    if(data[\"position\"].type()!=JSON::NIL) // \"position\" is energy\n    {\n      const JSON::Array &a=(JSON::Array)data[\"position\"];\n      int n_initialized=std::min(n_walkers,a.size());\n      for(int i=0; i<n_initialized; i++)\n        position[i]=a[i].as_float();\n      readPositions=true;\n    }\n    if(data[\"magnetizationAtPosition\"].type()!=JSON::NIL) \n    {\n      const JSON::Array &a=(JSON::Array)data[\"magnetizationAtPosition\"];\n      int n_initialized=std::min(n_walkers,a.size());\n      for(int i=0; i<n_initialized; i++)\n        magnetizationAtPosition[i]=a[i].as_float();\n      readPositions=true;\n    }\n\n\n    // set xMax and xMin or interval depending on nX:\n    if(nX>0)\n    {\n      interval=(xMax-xMin)/double(nX);\n      dos.setRange(xMin,xMax); histo.setRange(xMin,xMax);\n    } else {\n      dos.setDeltaAndClear(interval); histo.setDeltaAndClear(interval);\n    }\n\n    // json_free_value(&json_root);\n  }\n\n  dosKernel.setWidthAndClear(interval,kernelWidth);\n  histoKernel.setWidthAndClear(interval,kernelWidth);\n  nullKernel.setWidthAndClear(interval,kernelWidth);\n  initKernel(kernelType,dosKernel);\n  dosKernel.scale(gamma/dosKernel(0.0));\n  initKernel(kernelType,histoKernel);\n  histoKernel.scale(1.0/histoKernel(0.0));\n  initKernel(kernelType,nullKernel);\n  nullKernel.scale(0.0);\n//  histoKernel.scale(interval);\n\n  if(readPositions)\n    for(int i=0; i<n_walkers; i++)\n      ref0[i]=dos.idx(position[i]);\n\n  if(clearHistogram!=0)\n  {\n    std::cout<<\"Clearing Wang-Landau Histogram.\\n\";\n    histo.clear();\n  }\n\n  if(setFirstWalkerToFM!=0)\n  {\n    std::cout<<\"Setting first walker to FM.\\n\";\n    for(int i=0; i<n_spins; i++)\n    {\n      evecs_pointer[0][  3*i]=0.0;\n      evecs_pointer[0][1+3*i]=0.0;\n      evecs_pointer[0][2+3*i]=1.0;\n    }\n// initialize oldSpin and lastChange to point to site 0\n   lastChange[0]=0;\n   oldSpin[0]=evecs_pointer[0][0];\n   oldSpin[1]=evecs_pointer[0][1];\n   oldSpin[2]=evecs_pointer[0][2];\n\n// initialize oldPotentialShift and lastChangePotentialShift to point to site 0\n    lastChangePotentialShift[0] = 0;\n    oldPotentialShift[0] = 0.0;\n  }\n\n  if(out_file_name!=NULL && out_file_name[0]!=0) dos_out_name=out_file_name;\n  std::cout<<\"Wang-Landau output will be written to: \"<<dos_out_name<<std::endl;\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::initializeEvecAndPotentialShift(int inst, double *evecs, double *potentialShifts)\n{\n  for (size_t j=0; j<n_spins; j++)\n    potentialShifts[j] = 0.0;\n\n  initializeEvec(inst, evecs);\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::initializeEvec(int inst, double *evecs)\n{\n  bool firstFerromagnetic=true;\n  if(inst>=n_initialized_from_file)\n    {\n      if(firstFerromagnetic)\n        if(inst==0)\n\t  for(size_t j=0; j<3*n_spins; j+=3)\n\t    {evecs[j]=0.0; evecs[j+1]=0.0; evecs[j+2]=1.0;}\n        else if(inst==1)\n          for(size_t j=0; j<3*n_spins; j+=3)\n            {evecs[j+2]= (j/3)%2 ? 1.0 : -1.0 ; evecs[j+1]=0.0; evecs[j]=0.0;}\n        else\n\t  for(size_t j=0; j<3*n_spins; j+=3)\n\t    random_evec_1(&evecs[j]);\n      else\n        for(size_t j=0; j<3*n_spins; j+=3)\n          random_evec_1(&evecs[j]);\n    }\n\n  out[inst]=false;\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::writeState(const char* name)\n{\n  // if(!syncronizeGraphs(dos,histo))\n  if(dos.getN()!=histo.getN())\n  {\n    std::cout<<\"Histogramm size dosn't match DOS! Clearing histogramm!\\n\";\n    histo.setRangeAndClear(dos.getMinX(),dos.getMaxX(),dos.getN());\n  }\n  std::ofstream ofile(name);\n  if(ofile)\n  {\n    ofile.setf(std::ios::scientific,std::ios::floatfield);\n    ofile.precision(12);\n    ofile<<\"{\\n\";\n    ofile<<\"\\\"xMin\\\" : \" << dos.getMinX() << \",\\n\";\n    ofile<<\"\\\"xMax\\\" : \" << dos.getMaxX() << \",\\n\";\n    ofile<<\"\\\"nX\\\" : \" << dos.getN() << \",\\n\";\n    if(kernelType!=None)\n      ofile<<\"\\\"kernelWidth\\\" : \" << dosKernel.getWidth() << \",\\n\";\n    std::string kernelName;\n    getKernelName(kernelType,kernelName);\n    ofile<<\"\\\"kernelType\\\" : \\\"\" << kernelName << \"\\\",\\n\";\n    ofile<<\"\\\"gamma\\\" : \" << gamma << \",\\n\";\n    ofile<<\"\\\"accept\\\" : \" << accept <<\",\\n\";\n    ofile<<\"\\\"acceptSinceLastChange\\\" : \" << acceptSinceLastChange <<\",\\n\";\n    ofile<<\"\\\"reject\\\" : \" << reject <<\",\\n\";\n    ofile<<\"\\\"gammaFinal\\\" : \" << gammaFinal << \",\\n\";\n\n    ofile<<\"\\\"changeMode\\\" : \"<< changeMode <<\",\\n\";\n    ofile<<\"\\\"flatnessCriterion\\\" : \"<< flatnessCriterion <<\",\\n\";\n    ofile<<\"\\\"histogramMinimum\\\" : \"<< hMinimum <<\",\\n\";\n    ofile<<\"\\\"updatesPerBin\\\" : \"<< updatesPerBin <<\",\\n\";\n    ofile<<\"\\\"flipPerUpdate\\\" : \" << flipPerUpdate << \",\\n\";\n    ofile<<\"\\\"updateCycle\\\" : \" << updateCycle << \",\\n\";\n\n    ofile<<\"\\\"globalUpdate.frequency\\\" : \"<<  globalUpdate.frequency << \",\\n\";\n    ofile<<\"\\\"globalUpdate.changes\\\" : \"<<  globalUpdate.changes << \",\\n\";\n    ofile<<\"\\\"globalUpdate.kappa\\\" : \"<<  globalUpdate.kappa << \",\\n\";\n    ofile<<\"\\\"globalUpdate.lambda\\\" : \"<<  globalUpdate.lambda << \",\\n\";\n    ofile<<\"\\\"globalUpdate.omega\\\" : \"<<  globalUpdate.omega << \",\\n\";\n\n    ofile<<\"\\\"dos\\\" : [\"<<std::endl;\n    for(int i=0; i<dos.getN(); i++) ofile<<dos[i]<<((i==dos.getN()-1)?\"\\n\":\",\\n\");\n    ofile<<\"],\\n\";\n    ofile<<\"\\\"histo\\\" : [\"<<std::endl;\n    for(int i=0; i<histo.getN(); i++) ofile<<histo[i]<<((i==histo.getN()-1)?\"\\n\":\",\\n\");\n    ofile<<\"],\\n\";\n    if(dos.getNumberOfMoments()>0)\n    {\n      ofile<<\"\\\"moments\\\" : [\"<<std::endl;\n      ofile<<dos.getNumberOfMoments()<<\", [\"<<std::endl;\n      for(int i=0; i<dos.getN(); i++) ofile<<dos.getNumberOfSamplesAtIdx(i)<<((i==dos.getN()-1)?\"\\n\":\",\\n\");\n      ofile<<\"], [\\n\";\n      for(int j=0; j<dos.getNumberOfMoments(); j++)\n      {\n        for(int i=0; i<dos.getN(); i++) ofile<<dos.getMomentAtIdx(i,j)<<((i==dos.getN()-1)?\"\\n\":\",\\n\");\n        if(j!=dos.getNumberOfMoments()-1) ofile<<\"], [\\n\";\n      }\n      ofile<<\"] ],\\n\";\n    }\n    ofile<<\"\\\"rngState\\\" : \\\"\"<<rng<<\"\\\",\\n\";\n    ofile<<\"\\\"evecs\\\" : [\\n\";\n    for(int i=0; i<n_walkers; i++)\n    {\n      ofile<<\"[\\n\";\n      for(int j=0; j<3*n_spins; j+=3)\n        ofile<<evecs_pointer[i][j]<<\", \"<<evecs_pointer[i][j+1]\n             <<\", \"<<evecs_pointer[i][j+2]<<((j==3*n_spins-3)?\"\\n\":\",\\n\");\n      ofile<<((i==n_walkers-1)?\"]\\n\":\"],\\n\");\n    }\n    ofile<<\"],\\n\";\n    ofile<<\"\\\"oldSpin\\\" : [\\n\";\n    for(int i=0; i<n_walkers; i++)\n    {\n      ofile<<\"[ \"<<oldSpin[3*i]<<\", \"<<oldSpin[3*i+1]\n             <<\", \"<<oldSpin[3*i+2];\n      ofile<<((i==n_walkers-1)?\"]\\n\":\"],\\n\");\n    }\n    ofile<<\"],\\n\";\n    ofile<<\"\\\"lastChange\\\" : [\\n\";\n    for(int i=0; i<n_walkers; i++)\n    {\n      ofile<< lastChange[i]<<((i==n_walkers-1)?\"\\n\":\",\\n\");\n    }\n    ofile<<\"],\\n\";\n    ofile<<\"\\\"position\\\" : [\\n\";\n    for(int i=0; i<n_walkers; i++)\n    {\n      ofile<< position[i]<<((i==n_walkers-1)?\"\\n\":\",\\n\");\n    }\n    ofile<<\"],\\n\";\n    ofile<<\"\\\"magnetizationAtPosition\\\" : [\\n\";\n    for(int i=0; i<n_walkers; i++)\n    {\n      ofile<< magnetizationAtPosition[i]<<((i==n_walkers-1)?\"\\n\":\",\\n\");\n    }\n    ofile<<\"],\\n\";\n    ofile<<\"\\\"stepsSinceLastHistogramUpdate\\\" : \" << stepsSinceLastHistogramUpdate << \",\\n\";\n    ofile<<\"\\\"numberOfUpdatesSinceLastBoost\\\" : \" << numberOfUpdatesSinceLastBoost << \",\\n\";\n    ofile<<\"\\\"modificationFactorChanges\\\" : \" << modificationFactorChanges << \",\\n\";\n    ofile<<\"\\\"cycleCount\\\" : \" << cycleCount << \"\\n\";\n    ofile<<\"}\\n\";\n    ofile.close();\n  } else std::cerr<<\"# CAUTION: DoS output file could not be opened!\\n\";\n} \n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::writeDos(const char* name)\n{\n  std::ofstream ofile(name);\n  ofile.setf(std::ios::scientific,std::ios::floatfield);\n  ofile.precision(12);\n  // write dos;\n  // we are using JSON as our file format\n  if(ofile)\n  {\n    ofile<<\"{\\n\";\n    ofile<<\"\\\"xMin\\\" : \" << dos.getMinX() << \",\" <<std::endl;\n    ofile<<\"\\\"xMax\\\" : \" << dos.getMaxX() << \",\" <<std::endl;\n    ofile<<\"\\\"nX\\\" : \" << dos.getN() << \",\" <<std::endl;\n    ofile<<\"\\\"kernelWidth\\\" : \" << dosKernel.getWidth() << \",\\n\";\n    std::string kernelName;\n    getKernelName(kernelType,kernelName);\n    ofile<<\"\\\"kernelType\\\" : \\\"\" << kernelName << \"\\\",\\n\";\n    ofile<<\"\\\"gamma\\\" : \" << gamma <<\",\" <<std::endl;\n    ofile<<\"\\\"gammaFinal\\\" : \" << gammaFinal << \",\" <<std::endl;\n    ofile<<\"\\\"globalUpdate.changes\\\" : \"<<  globalUpdate.changes << \",\\n\";\n    ofile<<\"\\\"flipPerUpdate\\\" : \" << flipPerUpdate << \",\" <<std::endl;\n    ofile<<\"\\\"updateCycle\\\" : \" << updateCycle << \",\" <<std::endl;\n    ofile<<\"\\\"dos\\\" : [\"<<std::endl;\n    for(int i=0; i<dos.getN(); i++) ofile<<dos[i]<<((i==dos.getN()-1)?\"\\n\":\",\\n\");\n    ofile<<\"],\\n\";\n    if(dos.getNumberOfMoments()>0)\n    {\n      ofile<<\"\\\"moments\\\" : [\"<<std::endl;\n      ofile<<dos.getNumberOfMoments()<<\", [\"<<std::endl;\n      for(int i=0; i<dos.getN(); i++) ofile<<dos.getNumberOfSamplesAtIdx(i)<<((i==dos.getN()-1)?\"\\n\":\",\\n\");\n      ofile<<\"], [\\n\";\n      for(int j=0; j<dos.getNumberOfMoments(); j++)\n      {\n        for(int i=0; i<dos.getN(); i++) ofile<<dos.getMomentAtIdx(i,j)<<((i==dos.getN()-1)?\"\\n\":\",\\n\");\n        if(j!=dos.getNumberOfMoments()-1) ofile<<\"], [\\n\";\n      }\n      ofile<<\"] ],\\n\";\n    }\n    ofile<<\"\\\"histo\\\" : [\"<<std::endl;\n    for(int i=0; i<histo.getN(); i++) ofile<<histo[i]<<((i==histo.getN()-1)?\"\\n\":\",\\n\");\n    ofile<<\"]\\n}\\n\";\n    ofile.close();\n  } else std::cerr<<\"# CAUTION: DoS output file could not be opened!\\n\";\n}\n\n\ntemplate<class RNG>\nbool WL1dEvecGenerator<RNG>::determineAcceptance(int instance, double energy)\n{\n  return determineAcceptance(instance, energy, 0.0);\n}\n\n\ntemplate<class RNG>\nbool WL1dEvecGenerator<RNG>::determineAcceptance(int instance, double energy, double magnetization)\n{\n\n  bool accept_step;\n  // +++++++++ Added by Odbadrakh and Don on Aug 11, 2010\n  // +++ If a flip of spin results in energy in the same bin as previous accepted \n  // +++ state, it is accepted all the time. We change it by accepting if the\n  // +++ new state has lower density of states according to a linear spline of DOS\n  \n  double dos_differ;\n  double energy_differ;\n  double to_go_or_not;\n\n  // +++++++++ end of modification. Follow the new variables to see the actual changes \n  // energy between xMin and xMax ?\n  int grid = dos.idx(energy);\n\n  // dos.test();\n\n  stepsSinceLastHistogramUpdate++; // counter[0]++\n\n  // record initial energy for step out\n  if (lastAccepted[instance] == -2)\n  {\n    position[instance] = lastAcceptedEnergy[instance] = energy;\n    lastAccepted[instance] = -1;\n  }\n  \n  if (grid < 0 || grid > dos.getN()-1)\n  {\n    dos.extendTo(energy - dosKernel.getWidth()); histo.extendTo(energy - histoKernel.getWidth());\n    dos.extendTo(energy + dosKernel.getWidth()); histo.extendTo(energy + histoKernel.getWidth());\n    grid = dos.idx(energy);\n    // we need to adjust the grid point of the walker positions (ref0) for all walkers\n    for (long ii=0; ii<n_walkers; ii++)\n      if (ref0[ii] >= 0) ref0[ii] = dos.idx(position[ii]);\n  }\n  numRetentions[instance]++;\n  out[instance] = false;\n  ref1[instance] = grid;\n  if (ref0[instance] < 0)\n  {\n      accept_step = true;\n      ref0[instance] = ref1[instance];\n      position[instance] = energy;\n      magnetizationAtPosition[instance] = magnetization;\n  }\n  else \n  {\n    if (abs(ref1[instance] - ref0[instance]) < 1 ) \n    {\n// Actual change made by Odbadrakh, Aug 30, 2010\n      dos_differ = dos[ref0[instance]-1] - dos[ref0[instance]];\n      energy_differ = energy - lastAcceptedEnergy[instance];\n      to_go_or_not = dos_differ * energy_differ;\n      if (to_go_or_not >= 0.0)        // accepts all downhill changes\n      {\n        accept_step = true;\n        ref0[instance] = ref1[instance];\n        position[instance] = energy;\n        magnetizationAtPosition[instance] = magnetization;\n      } \n      else       // uphill moves\n      {\n        if(rnd(rng) < exp(to_go_or_not/dos.getDelta()))\n        { //std::cout<<\" dos \"<<instance<<\"  weight \"<<dos.getDelta()<<std::endl;\n          accept_step = true;\n          ref0[instance] = ref1[instance];\n          position[instance] = energy;\n          magnetizationAtPosition[instance] = magnetization;\n        }\n        else\n        {\n          accept_step = false;\n        }\n      }\n    }\n    else\n    { \n      if (dos[ref1[instance]] <= dos[ref0[instance]])\n      {\n        accept_step = true;\n        ref0[instance] = ref1[instance];\n        position[instance] = energy;\n        magnetizationAtPosition[instance] = magnetization;\n      }\n      else\n      {\n        if(rnd(rng) < exp(dos[ref0[instance]] - dos[ref1[instance]]))\n        {\n          accept_step = true;\n          ref0[instance] = ref1[instance];\n          position[instance] = energy;\n          magnetizationAtPosition[instance] = magnetization;\n        }\n        else \n        {\n          accept_step = false;\n        }\n      }\n      \n    }\n\n }\n\n// End of change made on Aug 30, 2010\n  if (verbosity > 2)\n    std::cout << \"WangLandau 1d EvecGenerator step \"\n              << modificationFactorChanges << \":\" << numberOfUpdatesSinceLastBoost << \":\"\n              << stepsSinceLastHistogramUpdate << \" nX=\" << dos.getN()\n\t      << \" [\" << dos.getMinX() << \", \" << dos.getMaxX() << \"] \"\n              << (accept_step ? \"accepted\" : \"rejected\")\n              << \" Energy = \" << energy << \", Instance \" << instance << std::endl;\n\n  return accept_step;\n\n}\n\n\n/*\ntemplate<class RNG>\nbool WL1dEvecGenerator<RNG>::updateHistogram(int instance, double *evecs, double energy, bool *accepted)\n{\n  return updateHistogram(instance, evecs, energy, 0.0, accepted);\n}\n*/\n\ntemplate<class RNG>\nbool WL1dEvecGenerator<RNG>::updateHistogram(int instance, double *evecs, bool accepted)\n{\n\n// Update histogram and DOS\n  if(stepsSinceLastHistogramUpdate >= flipPerUpdate)\n  {\n    stepsSinceLastHistogramUpdate = 0;       // counter[0]\n    numberOfUpdatesSinceLastBoost++;         // counter[1]\n    cycleCount++;\n    // modify the DoS\n    if(!out[instance])\n    {\n      // addKernel(dos,dosKernel,energy);\n      if (!histogramUpdateMode)             // standard Wang-Landau\n      {\n        addKernel(dos, dosKernel, position[instance]);\n        dos.addMomentsAtIdx(dos.idx(position[instance]), magnetizationAtPosition[instance]);\n        // if(accepted) addKernel(histo,histoKernel,position[instance]);\n        addKernel(histo, histoKernel, position[instance]);\n        // addKernel(dos, dosKernel, energy);\n        // addKernel(histo, histoKernel, energy);\n      }\n      else\n      {\n        // addKernel(dos, nullKernel, position[instance]);\n        if(accepted) addKernel(histo, histoKernel, position[instance]);\n      }\n    } \n    else\n    {\n      std::cerr << \"ATTENTION: We should never reach this place in WL1dEvecGenerator!\\n\";\n      exit(1);\n    }\n  }\n\n// 1/t algorithm, change gamma at every step\n// Reference: Phys. Rev. E 75, 046701 (2007).\n  if(changeMode & (8+16+32))\n  {\n    long n = accept + reject;\n    double dn;\n\n    if ((changeMode &  (8+16)) == 8) n = accept;\n    else if ((changeMode &  (8+16)) == 16) n = reject;\n    else if ((changeMode &  (8+16)) == 8+16) n = accept + reject;\n\n    if (changeMode & 32) dn = double(n) / double(n_walkers);\n    else dn = double(n);\n\n    gamma = 1.0 / dn;\n    if (gamma > 1.0) gamma = 1.0;\n\n    initKernel(kernelType, dosKernel);\n    dosKernel.scale(gamma);\n  }\n\n// 1. write configuration\n// 2. check histogram flatness\n// 3. perform global update\n  if (cycleCount >= updateCycle)\n  {\n    cycleCount = 0;\n    // syncronizeGraphs(dos, histo);\n    if (dos.getN() != histo.getN())\n    {\n      std::cout << \"Histogramm size dosn't match DOS! Clearing histogramm!\\n\";\n      histo.setRangeAndClear(dos.getMinX(), dos.getMaxX(), dos.getN());\n    }\n\n    writeState(\"WL1d.state\");\n\n    if (!histogramUpdateMode)        // Normal Wang-Landau\n    {\n      // calculate minimum nonzero histogram\n      // we look only at the histogram inside the energy interval that was actually sampled if we use kernel updates\n      double hMin, hMax, hMean;\n\n      if (kernelType == None)\n      {\n        hMean = histo.getMeanY();\n        histo.getMinMaxY(hMin,hMax);\n      }\n      else \n      {\n        hMean = histo.getMeanYInInterval(dos.getMinX() + dosKernel.getWidth(),\n                                         dos.getMaxX() - dosKernel.getWidth());\n        histo.getMinMaxYInInterval(dos.getMinX() + dosKernel.getWidth(),\n                                   dos.getMaxX() - dosKernel.getWidth(),\n                                   hMin, hMax);\n      }\n\n      // double currentFlatnessCriterion = double(hMin-hMax) / hMean;\n      double currentFlatnessCriterion = double(hMin) / hMean;\n      \n      std::cout << \"# acceptence ratio = \" << double(accept) / double(accept+reject) << \"\\n\";\n      std::cout << \"# current flatness = \" << currentFlatnessCriterion << (changeMode & 4 ? \" *\":\"\") << \"\\n\";\n      std::cout << \"# current histogram minimum = \" << hMin << (changeMode & 2 ? \" *\":\"\") << \"\\n\";\n      std::cout << \"# average accepted steps/bin since last gamma change = \"\n                << double(acceptSinceLastChange) / double(histo.getN())\n                << (changeMode & 1 ? \" *\":\"\") << \"\\n\";\n\n      if (changeMode != 0 && changeMode < 8)\n      {\n        // perform global update\n        if (globalUpdate.frequency > 0 && (globalUpdate.frequency*histo.getN()) < acceptSinceLastChange) \n        {\n          char fn[256];\n          snprintf(fn,255,\"Dos_Global_%02d_Changes_%03d.jsn\",globalUpdate.changes,modificationFactorChanges);\n          writeDos(fn);\n          globalUpdate.changes++;\n          std::cout<<\"# global update \"<<globalUpdate.changes<<std::endl;\n          performGlobalUpdate(dos,globalUpdate.kappa,globalUpdate.lambda,globalUpdate.omega);\n          histo.clear();\n          acceptSinceLastChange=0;\n        }\n        else if (((acceptSinceLastChange>=histo.getN()*updatesPerBin || !(changeMode &1)) &&\n                  (hMin >= hMinimum || !(changeMode & 2)) &&\n                  (currentFlatnessCriterion>flatnessCriterion || !(changeMode & 4)) ))\n        {\n          std::cout << \"# level \" << modificationFactorChanges << \" with gamma = \" << gamma << \" is finished.\\n\";\n          modificationFactorChanges++; // counter[2]\n\n          // write dos;\n          // we are using JSON as our file format\n          char fn[256];\n          snprintf(fn,255,\"Dos_Global_%02d_Changes_%03d.jsn\",globalUpdate.changes,modificationFactorChanges);\n          writeDos(fn);\n          // writeDos(dos_out_name.data());\n\n          // clear the Histogram\n          histo.clear();\n          acceptSinceLastChange = 0;\n \n          // change gamma\n          dosKernel.scale(0.5);\n          gamma = 0.5 * gamma;\n          std::cout << \"# level \" << modificationFactorChanges << \" with gamma = \" << gamma << \" begins.\\n\";\n          if(statesFile != NULL)\n\t  {\n            // char fn[256];\n            snprintf(fn,255,\"%s_%02d\",statesFile,modificationFactorChanges);\n            sw.newFile(fn);\n            sw.writeHeader(gamma,n_walkers,n_spins,evecs_pointer);\n          }\n        }\n      }\n    } \n    else            // histogram update mode != 0\n    {\n      if (acceptSinceLastChange >= histo.getN() * updatesPerBin)\n      {\n        acceptSinceLastChange = 0;\n        for (int ix=0; ix<dos.getN(); ix++)\n          dos[ix] += gamma * histo[ix];\n        histo.clear();\n        gamma = 0.5 * gamma;\n\n        std::cout << \"# level \" << modificationFactorChanges << \" with gamma = \" << gamma << \" begins.\\n\";\n        if (statesFile != NULL)\n        {\n          char fn[256];\n          snprintf(fn,255,\"%s_%02d\",statesFile,modificationFactorChanges);\n          sw.newFile(fn);\n          sw.writeHeader(gamma,n_walkers,n_spins,evecs_pointer);\n        }\n      }\n    }\n  }\n\n  if (accepted) \n  {\n    // suffian: moved to routine updateLog(), see below\n/*    sw.writeChange(instance, numRetentions[instance], lastAccepted[instance], &lastAcceptedEvec[3*instance], lastAcceptedEnergy[instance]);\n    lastAccepted[instance] = lastChange[instance];\n    lastAcceptedEnergy[instance] = position[instance];\n    //lastAcceptedEnergy[instance] = energy;\n    lastAcceptedEvec[  3*instance] = evecs[  3*lastChange[instance]];\n    lastAcceptedEvec[1+3*instance] = evecs[1+3*lastChange[instance]];\n    lastAcceptedEvec[2+3*instance] = evecs[2+3*lastChange[instance]]; */\n    accept++;\n    acceptSinceLastChange++;\n  }\n  else\n    reject++;\n\n  if (gamma < gammaFinal) return true;\n  else return false;\n\n}\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::updateLog(int instance, double *evecs, int * occ, bool accepted, MoveChoice_t MoveChoice) {\n\n  // use static variables to keep track of the last move type\n  static bool firstrun = true;\n  static std::vector<MoveChoice_t> lastAcceptedMove;\n  if( firstrun ) {\n    lastAcceptedMove.resize(n_walkers);\n    firstrun = false;\n  }\n\n  // return unless state changed\n  if( !accepted ) return;\n\n  // print output corresponding to previous state\n  if( lastAcceptedMove[instance] == SpinMove )\n    sw.writeChange(instance, numRetentions[instance], lastAccepted[instance], &lastAcceptedEvec[3*instance], lastAcceptedEnergy[instance]);\n  else\n    sw.writeChangeOcc(instance, numRetentions[instance], \n        lastAcceptedSwap[instance].first,\n        lastAcceptedSwap[instance].second,\n        lastAcceptedOcc[instance].first, \n        lastAcceptedOcc[instance].second, \n        lastAcceptedEnergy[instance]);\n\n  // remember the new configuration\n  lastAcceptedEnergy[instance] = position[instance];\n  if( MoveChoice == SpinMove ) {\n    lastAccepted[instance] = lastChange[instance];\n    //lastAcceptedEnergy[instance] = energy;\n    lastAcceptedEvec[  3*instance] = evecs[  3*lastChange[instance]];\n    lastAcceptedEvec[1+3*instance] = evecs[1+3*lastChange[instance]];\n    lastAcceptedEvec[2+3*instance] = evecs[2+3*lastChange[instance]]; \n  }\n  else {\n    lastAcceptedSwap[instance].first  = lastSwapOcc[instance].first;\n    lastAcceptedSwap[instance].second = lastSwapOcc[instance].second;\n    lastAcceptedOcc[instance].first  = occ[ lastSwapOcc[instance].first ];\n    lastAcceptedOcc[instance].second = occ[ lastSwapOcc[instance].second ];\n  }\n\n  lastAcceptedMove[instance] = MoveChoice;\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::generatePotentialShift(int instance, double *potentialShifts, bool accepted)\n{\n\n  if (accepted)\n  {\n    lastChangePotentialShift[instance] = int(rnd(rng)*n_spins);\n    oldPotentialShift[instance] = potentialShifts[lastChangePotentialShift[instance]];\n    potentialShifts[lastChangePotentialShift[instance]] = randomPotentialShift();\n  } else {\n    potentialShifts[lastChangePotentialShift[instance]] = oldPotentialShift[instance];\n    lastChangePotentialShift[instance] = int(rnd(rng)*n_spins);\n    oldPotentialShift[instance] = potentialShifts[lastChangePotentialShift[instance]];\n    potentialShifts[lastChangePotentialShift[instance]] = randomPotentialShift();\n  }\n\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::generateEvec(int instance, double *evecs, bool acceptedEvec)\n{\n  if (acceptedEvec)\n  {\n    lastChange[instance] = int(rnd(rng)*n_spins);\n    oldSpin[  3*instance] = evecs[  3*lastChange[instance]];\n    oldSpin[1+3*instance] = evecs[1+3*lastChange[instance]];\n    oldSpin[2+3*instance] = evecs[2+3*lastChange[instance]];\n    random_evec(&evecs[3*lastChange[instance]]);\n    numRetentions[instance] = 0;\n  }\n  else \n  {\n    evecs[  3*lastChange[instance]] = oldSpin[  3*instance];\n    evecs[1+3*lastChange[instance]] = oldSpin[1+3*instance];\n    evecs[2+3*lastChange[instance]] = oldSpin[2+3*instance];\n    lastChange[instance] = int(rnd(rng)*n_spins);\n    oldSpin[  3*instance] = evecs[  3*lastChange[instance]];\n    oldSpin[1+3*instance] = evecs[1+3*lastChange[instance]];\n    oldSpin[2+3*instance] = evecs[2+3*lastChange[instance]];\n    random_evec(&evecs[3*lastChange[instance]]);\n  }\n\n}\n\n// additions for Wang-Landau for alloying\n// swapping atoms preserves concentration\n\ntemplate<class RNG>\nMoveChoice_t WL1dEvecGenerator<RNG>::selectMoveType(bool isSpinSim, bool isOccSim) {\n\n  printf(\"inside correct 'selectMoveType'\\n\");\n\n  // choose between spin and occupancy equally\n  // is this a good choice??\n  if( isSpinSim && isOccSim ) {\n    int c = int(rnd(rng)*2);\n    if( c == 0 ) \n      return SpinMove\n    else\n      return OccupancyMove;\n  }\n\n  if( isSpinSim )\n    return SpinMove;\n  if( isOccSim )\n    return OccupancyMove;\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::setAlloyClasses(const AlloyMixingDesc& alloyDesc, int *siteclass) {\n  this->alloyDesc = alloyDesc;\n\n  siteAlloyClass.resize(n_spins);\n  for(int i = 0; i < n_spins; i++)\n    siteAlloyClass[i] = siteclass[i];\n\n  // remember number of sites per alloy class \n  int nclasses = alloyDesc.size();\n  numSites_per_AlloyClass.resize(nclasses);\n  int *nsites = numSites_per_AlloyClass.data();\n  for(int i = 0; i < nclasses; i++)\n    nsites[i] = 0;\n  for(int i = 0; i < n_spins; i++)\n    nsites[ siteAlloyClass[i] ]++;\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::generateOccupancies(int instance, int *occ, bool acceptedOcc) {\n\n  int temp, atom_i, atom_j;\n\n  // if previous move not accepted, \n  // revert occupancies\n  if( !acceptedOcc ) {\n    atom_i = lastSwapOcc[instance].first;\n    atom_j = lastSwapOcc[instance].second;\n\n    temp = occ[atom_i];\n    occ[atom_i] = occ[atom_j];\n    occ[atom_j] = temp;\n  }\n  else\n    numRetentions[instance] = 0;\n\n  // pick an alloy class\n  int ac = int(rnd(rng)*alloyDesc.size());\n\n  // pick two distinct atoms within mixing class\n  // here we assume there are few alloy classes\n  do{ atom_i = int(rnd(rng)*n_spins) } \n    while( siteAlloyClass[atom_i] != ac );\n  do{ atom_j = int(rnd(rng)*n_spins) } \n    while( siteAlloyClass[atom_j] != ac || occ[atom_j] == occ[atom_i] );\n\n  // swap atoms\n  temp = occ[atom_i];\n  occ[atom_i] = occ[atom_j];\n  occ[atom_j] = temp;\n\n  // remember which atoms were swapped\n  lastSwapOcc[instance].first  = atom_i;\n  lastSwapOcc[instance].second = atom_j;\n}\n\ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::generateUnsampledOcc(int inst, int *occ) {\n  initializeOccupancies(inst, occ);\n}\n \ntemplate<class RNG>\nvoid WL1dEvecGenerator<RNG>::initializeOccupancies(int inst, int *occ) {\n \n  printf(\"inside correct 'initializeOccupancies'\\n\");\n\n  // determine number atoms of each component type given concentration\n  std::vector< std::vector<int> > atomsLeft;\n  atomsLeft.resize(alloyDesc.size());\n  for(int i = 0; i < atomsLeft.size(); i++) {\n    atomsLeft[i].resize(alloyDesc[i].size());\n    for(int j = 0; j < atomsLeft[i].size(); j++) {\n\n      // how many sites for this alloy class and component?\n      double nfrac = alloyDesc[i][j].conc * numSites_per_AlloyClass[i];\n      double error = fmod(nfrac, 1.0);\n\n      // ensure concentrations commensurate with number of sites\n      const double tol = 1.e-06;\n      if( tol < error && error < 1.0-tol ) {\n        printf(\"error: alloy concentrations are incommensurate with supercell\\n\");\n        printf(\"alloy class = %d, component = %d\\, concentration = %f\\n\", \n            i+1, j+1, alloyDesc[i][j].conc);\n        printf(\"desired sites = %f\\n\", nfrac);\n        exit(1);\n      }\n\n      atomsLeft[i][j] = int(nfrac + 0.5);\n    }\n  }\n\n  // distribute atoms across sites\n  for(int i = 0; i < n_spins; i++) {\n\n     // pick an atom from the right class\n     int type, ac = siteAlloyClass[i];\n     do { type = int( rnd(rng) * alloyDesc[ac].size() ) }\n       while( atomsLeft[ac][type] == 0 )\n\n     // assign to site\n     occ[i] = type; atomsLeft[ac][type]--;\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "6226d4b988eee7074566fba882c083628d85ccb2", "size": 43910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Main/WangLandau.hpp", "max_stars_repo_name": "rdietric/lsms", "max_stars_repo_head_hexsha": "8d0d5f01186abf9a1cc54db3f97f9934b422cf92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T20:05:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T09:08:01.000Z", "max_issues_repo_path": "src/Main/WangLandau.hpp", "max_issues_repo_name": "rdietric/lsms", "max_issues_repo_head_hexsha": "8d0d5f01186abf9a1cc54db3f97f9934b422cf92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T13:59:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:43:35.000Z", "max_forks_repo_path": "lsms/src/Main/WangLandau.hpp", "max_forks_repo_name": "hkershaw-brown/MuST", "max_forks_repo_head_hexsha": "9db4bc5061c2f2c4d7dfd92f53b4ef952602c070", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2020-02-11T17:04:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:23:46.000Z", "avg_line_length": 32.8667664671, "max_line_length": 141, "alphanum_fraction": 0.6235937144, "num_tokens": 12838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535945, "lm_q2_score": 0.02297737070451605, "lm_q1q2_score": 0.0055652485179429655}}
{"text": "// $Id$\n//\n//  Copyright (C) 2003-2012 greg Landrum and Rational Discovery LLC\n//\n//  @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n#include \"BitVects.h\"\n#include \"BitOps.h\"\n#include <math.h>\n#include <string>\n#include <iostream>\n#include <RDGeneral/StreamOps.h>\n#include <RDGeneral/types.h>\n#include <RDGeneral/Exceptions.h>\n#include <sstream>\n#include <cstdlib>\n\n#include <boost/lexical_cast.hpp>\n\nusing namespace RDKit;\n\nint getBitId(const char*& text, int format, int size, int curr) {\n  PRECONDITION(text, \"no text\");\n  int res = -1;\n  if ((format == 0) ||\n      ((format == 1) && (size >= std::numeric_limits<unsigned short>::max()))) {\n    int tmp;\n    tmp = EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)text);\n    text += sizeof(tmp);\n    res = tmp;\n  } else if (format == 1) {  // version 16 and on bits sotred as short ints\n    unsigned short tmp;\n    tmp = EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(\n        *(unsigned short*)text);\n    text += sizeof(tmp);\n    res = tmp;\n  } else if (format == 2) {  // run length encoded format\n    res = curr + RDKit::pullPackedIntFromString(text);\n  }\n  return res;\n}\n\nbool AllProbeBitsMatch(const std::string& probe, const std::string& ref) {\n  return AllProbeBitsMatch(probe.c_str(), ref.c_str());\n}\n\nbool AllProbeBitsMatch(const char* probe, const char* ref) {\n  PRECONDITION(probe, \"no probe text\");\n  PRECONDITION(ref, \"no probe text\");\n  int probeFormat = 0;\n  int refFormat = 0;\n  int version = 0;\n\n  int probeSize =\n      EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)probe);\n  probe += sizeof(probeSize);\n  if (probeSize < 0) {\n    version = -1 * probeSize;\n    if (version == 16) {\n      probeFormat = 1;\n    } else if (version == 32) {\n      probeFormat = 2;\n    } else {\n      throw(\"Unknown version type for the encode bit vect\");\n    }\n    probeSize =\n        EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)probe);\n    probe += sizeof(probeSize);\n  }\n\n  int refSize =\n      EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)ref);\n  ref += sizeof(refSize);\n  if (refSize < 0) {\n    version = -1 * refSize;\n    if (version == 16) {\n      refFormat = 1;\n    } else if (version == 32) {\n      refFormat = 2;\n    } else {\n      throw(\"Unknown version type for the encode bit vect\");\n    }\n    refSize =\n        EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)ref);\n    ref += sizeof(refSize);\n  }\n\n  int nProbeOn =\n      EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)probe);\n  probe += sizeof(nProbeOn);\n  int nRefOn =\n      EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)ref);\n  ref += sizeof(nRefOn);\n\n  int currProbeBit = 0;\n  currProbeBit = getBitId(probe, probeFormat, probeSize, currProbeBit);\n  nProbeOn--;\n\n  int currRefBit = 0;\n  currRefBit = getBitId(ref, refFormat, refSize, currRefBit);\n  nRefOn--;\n\n  while (nProbeOn) {\n    while (currRefBit < currProbeBit && nRefOn > 0) {\n      if (refFormat == 2) currRefBit++;\n      currRefBit = getBitId(ref, refFormat, refSize, currRefBit);\n      nRefOn--;\n    }\n    if (currRefBit != currProbeBit) return false;\n    if (probeFormat == 2) currProbeBit++;\n    currProbeBit = getBitId(probe, probeFormat, probeSize, currProbeBit);\n    nProbeOn--;\n  }\n  return true;\n}\n\ntemplate <typename T1>\nbool AllProbeBitsMatch(const T1& probe, const std::string& pkl) {\n  const char* text = pkl.c_str();\n  int format = 0;\n  int nOn = 0, size, version = 0;\n  size = EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)text);\n  text += sizeof(size);\n  if (size < 0) {\n    version = -1 * size;\n    if (version == 16) {\n      format = 1;\n    } else if (version == 32) {\n      format = 2;\n    } else {\n      throw(\"Unknown version type for the encode bit vect\");\n    }\n    size = EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)text);\n    text += sizeof(size);\n  }\n  nOn = EndianSwapBytes<LITTLE_ENDIAN_ORDER, HOST_ENDIAN_ORDER>(*(int*)text);\n  text += sizeof(nOn);\n\n  int currBit = 0;\n  currBit = getBitId(text, format, size, currBit);\n  nOn--;\n  std::vector<int> obl;\n  probe.getOnBits(obl);\n\n  // for(int i=0;i<probe.getNumBits();i++){\n  //  if(probe.getBit(i)){\n  for (std::vector<int>::const_iterator i = obl.begin(); i != obl.end(); i++) {\n    while (currBit < *i && nOn > 0) {\n      if (format == 2) currBit++;\n      currBit = getBitId(text, format, size, currBit);\n      nOn--;\n    }\n    if (currBit != *i) return false;\n    //}\n  }\n  return true;\n}\ntemplate bool AllProbeBitsMatch(const SparseBitVect& bv1,\n                                const std::string& pkl);\ntemplate bool AllProbeBitsMatch(const ExplicitBitVect& bv1,\n                                const std::string& pkl);\ntemplate <typename T1>\nbool AllProbeBitsMatch(const T1& probe, const T1& ref) {\n  for (unsigned int i = 0; i < probe.getNumBits(); ++i) {\n    if (probe.getBit(i) && !ref.getBit(i)) {\n      return false;\n    }\n  }\n  return true;\n}\ntemplate bool AllProbeBitsMatch(const SparseBitVect& bv1,\n                                const SparseBitVect& bv2);\n// template bool AllProbeBitsMatch(const ExplicitBitVect& bv1,const\n// ExplicitBitVect &bv2);\n\nbool AllProbeBitsMatch(const ExplicitBitVect& probe,\n                       const ExplicitBitVect& ref) {\n  return probe.dp_bits->is_subset_of(*(ref.dp_bits));\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  NumOnBitsInCommon(T1,T2)\n//  Returns the number of on bits which are set in both T1 and T2.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\nint NumOnBitsInCommon(const T1& bv1, const T2& bv2) {\n  return static_cast<int>(OnBitsInCommon(bv1, bv2).size());\n}\n\nint NumOnBitsInCommon(const ExplicitBitVect& bv1, const ExplicitBitVect& bv2) {\n  return static_cast<int>(((*bv1.dp_bits) & (*bv2.dp_bits)).count());\n}\n\n// In all these similarity metrics the notation is selected to be\n//   consistent with J.W. Raymond and P. Willett, JCAMD _16_ 59-71 (2002)\n// \"\"\" -------------------------------------------------------\n//\n//  TanimotoSimilarity(T1,T2)\n//   returns the Tanamoto similarity between T1 and T2, a double.\n//\n//  T1 and T2 should be the same length.\n//\n//  C++ Notes: T1 and T2 must support operator&, getNumBits()\n//  and getOnBits().\n//\n//  Python Notes: T1 and T2 are BitVects.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\ndouble TanimotoSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n  if ((y + z - x) == 0.0)\n    return 1.0;\n  else\n    return x / (y + z - x);\n}\n\ntemplate <typename T1, typename T2>\ndouble TverskySimilarity(const T1& bv1, const T2& bv2, double a, double b) {\n  RANGE_CHECK(0, a, 1);\n  RANGE_CHECK(0, b, 1);\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n  double denom = a * y + b * z + (1 - a - b) * x;\n  if (denom == 0.0)\n    return 1.0;\n  else\n    return x / denom;\n}\n\ntemplate <typename T1, typename T2>\ndouble CosineSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n\n  if (y * z > 0.0) {\n    return x / sqrt(y * z);\n  } else {\n    return 0.0;\n  }\n}\n\ntemplate <typename T1, typename T2>\ndouble KulczynskiSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n\n  if (y * z > 0.0) {\n    return x * (y + z) / (2 * y * z);\n  } else {\n    return 0.0;\n  }\n}\n\ntemplate <typename T1, typename T2>\ndouble DiceSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n\n  if (y + z > 0.0) {\n    return 2 * x / (y + z);\n  } else {\n    return 0.0;\n  }\n}\n\ntemplate <typename T1, typename T2>\ndouble SokalSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n\n  return x / (2 * y + 2 * z - 3 * x);\n}\n\ntemplate <typename T1, typename T2>\ndouble McConnaugheySimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n\n  if (y * z > 0.0) {\n    return (x * (y + z) - (y * z)) / (y * z);\n  } else {\n    return 0.0;\n  }\n}\n\ntemplate <typename T>\ninline T tmin(T v1, T v2) {\n  if (v1 < v2) return v1;\n  return v2;\n}\n\ntemplate <typename T>\ninline T tmax(T v1, T v2) {\n  if (v1 > v2) return v1;\n  return v2;\n}\n\ntemplate <typename T1, typename T2>\ndouble AsymmetricSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n\n  if (tmin(y, z) > 0) {\n    return x / tmin(y, z);\n  } else {\n    return 0.0;\n  }\n}\n\ntemplate <typename T1, typename T2>\ndouble BraunBlanquetSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n\n  if (tmax(y, z) > 0) {\n    return x / tmax(y, z);\n  } else {\n    return 0.0;\n  }\n}\n\ntemplate <typename T1, typename T2>\ndouble RusselSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  return x / bv1.getNumBits();\n}\n\ntemplate <typename T1, typename T2>\ndouble RogotGoldbergSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  double x = NumOnBitsInCommon(bv1, bv2);\n  double y = bv1.getNumOnBits();\n  double z = bv2.getNumOnBits();\n  double l = bv1.getNumBits();\n  double d = l - y - z + x;\n  if ((x == l) || (d == l))\n    return 1.0;\n  else\n    return (x / (y + z) + (d) / (2 * l - y - z));\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  OnBitSimilarity(T1,T2)\n//  Returns the percentage of possible on bits in common\n//  between T1 and T2 (a double)\n//\n//  C++ Notes: T1 and T2 must support operator|, operator&\n//  and getOnBits().\n//\n//  Python Notes: T1 and T2 are BitVects.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\ndouble OnBitSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n\n  double num = NumOnBitsInCommon(bv1, bv2);\n  double denom = (bv1 | bv2).getNumOnBits();\n\n  if (denom > 0) {\n    return num / denom;\n  } else {\n    return 0;\n  }\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  NumBitsInCommon(T1,T2)\n//  Returns the number of bits in common (on and off)\n//  between T1 and T2 (an int)\n//\n//  T1 and T2 should be the same length.\n//\n//  C++ Notes: T1 and T2 must support operator^, getNumBits().\n//\n//  Python Notes: T1 and T2 are BitVects.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\nint NumBitsInCommon(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n\n  return bv1.getNumBits() - (bv1 ^ bv2).getNumOnBits();\n}\n\nint NumBitsInCommon(const ExplicitBitVect& bv1, const ExplicitBitVect& bv2) {\n  return bv1.getNumBits() - static_cast<int>(((*bv1.dp_bits) ^ (*bv2.dp_bits)).count());\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  AllBitSimilarity(T1,T2)\n//  Returns the percentage of bits in common (on and off)\n//  between T1 and T2 (a double)\n//\n//  T1 and T2 should be the same length.\n//\n//  C++ Notes: T1 and T2 must support operator^, getNumBits()\n//  and getNumOnBits().\n//\n//  Python Notes: T1 and T2 are BitVects.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\ndouble AllBitSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n\n  return double(NumBitsInCommon(bv1, bv2)) / bv1.getNumBits();\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  OnBitsInCommon(T1,T2)\n//  Returns the on bits which are set in both T1 and T2.\n//\n//  T1 and T2 should be the same length.\n//\n//  C++ Notes: T1 and T2 must support operator&, getNumBits()\n//  and getOnBits(), the return value is an IntVect.\n//\n//  Python Notes: T1 and T2 are BitVects, the return value\n//  is a tuple of ints.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\nIntVect OnBitsInCommon(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  IntVect res;\n  (bv1 & bv2).getOnBits(res);\n  return res;\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  OffBitsInCommon(T1,T2)\n//  Returns the off bits which are set in both T1 and T2.\n//\n//  T1 and T2 should be the same length.\n//\n//  C++ Notes: T1 and T2 must support operator|, operator~,\n// getNumBits() and getOnBits(), the return value is an IntVect.\n//\n//  Python Notes: T1 and T2 are BitVects, the return value\n//  is a tuple of ints.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\nIntVect OffBitsInCommon(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  IntVect res;\n  (~(bv1 | bv2)).getOnBits(res);\n  return res;\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  OnBitProjSimilarity(T1,T2)\n//  Returns the projected similarity between the on bits of\n//  T1 and T2.\n//\n//  The on bit projected similarity of T1 onto T2 is the\n//  percentage of T1's on bits which are on in T2.\n//\n//  This type of measure may be useful for substructure-type\n//  searches.\n//\n//  Two values are returned, the projection of T1 onto T2\n//  and the projection of T2 onto T1\n//\n//  T1 and T2 should be the same length.\n//\n//  C++ Notes: T1 and T2 must support operator&, getNumBits()\n//  and getNumOnBits(), the return value is an DoubleVect with\n//  two elements.\n//\n//  Python Notes: T1 and T2 are BitVects, the return value\n//  is a 2-tuple of doubles.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\nDoubleVect OnBitProjSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  DoubleVect res(2, 0.0);\n  double num = NumOnBitsInCommon(bv1, bv2);\n  if (num) {\n    res[0] = num / bv1.getNumOnBits();\n    res[1] = num / bv2.getNumOnBits();\n  }\n  return res;\n}\n\n// \"\"\" -------------------------------------------------------\n//\n//  OffBitProjSimilarity(T1,T2)\n//  Returns the projected similarity between the off bits of\n//  T1 and T2.\n//\n//  The off bit projected similarity of T1 onto T2 is the\n//  percentage of T1's off bits which are off in T2.\n//\n//  This type of measure may be useful for substructure-type\n//  searches.\n//\n//  Two values are returned, the projection of T1 onto T2\n//  and the projection of T2 onto T1\n//\n//  T1 and T2 should be the same length.\n//\n//  C++ Notes: T1 and T2 must support operator|, getNumBits()\n//  and getNumOffBits(), the return value is an DoubleVect with\n//  two elements.\n//\n//  Python Notes: T1 and T2 are BitVects, the return value\n//  is a 2-tuple of doubles.\n//\n// \"\"\" -------------------------------------------------------\ntemplate <typename T1, typename T2>\nDoubleVect OffBitProjSimilarity(const T1& bv1, const T2& bv2) {\n  if (bv1.getNumBits() != bv2.getNumBits())\n    throw ValueErrorException(\"BitVects must be same length\");\n  DoubleVect res(2, 0.0);\n  double num = (bv1 | bv2).getNumOffBits();\n  if (num) {\n    res[0] = num / bv1.getNumOffBits();\n    res[1] = num / bv2.getNumOffBits();\n  }\n  return res;\n}\n\ntemplate <typename T1>\nT1* FoldFingerprint(const T1& bv1, unsigned int factor) {\n  if (factor <= 0 || factor >= bv1.getNumBits())\n    throw ValueErrorException(\"invalid fold factor\");\n\n  int initSize = bv1.getNumBits();\n  int resSize = initSize / factor;\n  T1* res = new T1(resSize);\n\n  IntVect onBits;\n  bv1.getOnBits(onBits);\n  for (IntVectIter iv = onBits.begin(); iv != onBits.end(); iv++) {\n    int pos = (*iv) % resSize;\n    res->setBit(pos);\n  }\n  return res;\n}\n\ntemplate <typename T1>\nstd::string BitVectToText(const T1& bv1) {\n  std::string res(bv1.getNumBits(), '0');\n  for (unsigned int i = 0; i < bv1.getNumBits(); i++) {\n    if (bv1.getBit(i)) res[i] = '1';\n  }\n  return res;\n}\n\nconst char bin2Hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',\n                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\ntemplate <typename T1>\nstd::string BitVectToFPSText(const T1& bv1) {\n  unsigned int size =\n      2 * (bv1.getNumBits() / 8 + (bv1.getNumBits() % 8 ? 1 : 0));\n  std::string res(size, 0);\n  unsigned char c = 0;\n  unsigned int byte = 0;\n  for (unsigned int i = 0; i < bv1.getNumBits(); i++) {\n    if (bv1.getBit(i)) {\n      c |= 1 << (i % 8);\n    }\n    if (!((i + 1) % 8)) {\n      res[byte++] = bin2Hex[(c >> 4) % 16];\n      res[byte++] = bin2Hex[c % 16];\n      c = 0;\n    }\n  }\n  if (byte < size) {\n    res[byte++] = bin2Hex[(c >> 4) % 16];\n    res[byte++] = bin2Hex[c % 16];\n  }\n  return res;\n}\n\ntemplate <typename T1>\nstd::string BitVectToBinaryText(const T1& bv1) {\n  std::string res(bv1.getNumBits() / 8 + (bv1.getNumBits() % 8 ? 1 : 0), 0);\n  unsigned char c = 0;\n  unsigned int byte = 0;\n  for (unsigned int i = 0; i < bv1.getNumBits(); i++) {\n    if (bv1.getBit(i)) {\n      c |= 1 << (i % 8);\n    }\n    if (!((i + 1) % 8)) {\n      res[byte++] = c;\n      c = 0;\n    }\n  }\n  if (bv1.getNumBits() % 8) {\n    res[byte] = c;\n  }\n  return res;\n}\n\ntemplate <typename T1>\nvoid UpdateBitVectFromFPSText(T1& bv1, const std::string& fps) {\n  PRECONDITION(fps.length() * 4 >= bv1.getNumBits(), \"bad FPS length\");\n  PRECONDITION(fps.length() % 2 == 0, \"bad FPS length\");\n  unsigned int bitIdx = 0;\n  char tptr[3];\n  tptr[2] = (char)0;\n  for (unsigned int i = 0; i < fps.size() && bitIdx < bv1.getNumBits();\n       i += 2) {\n    unsigned short c = 0;\n    try {\n      tptr[0] = fps[i];\n      tptr[1] = fps[i + 1];\n      c = static_cast<unsigned short>(strtol(tptr, NULL, 16));\n    } catch (...) {\n      std::ostringstream errout;\n      errout << \"Cannot convert FPS word: \" << fps.substr(i, 2) << \" to int\";\n      std::cerr << errout.str() << std::endl;\n      throw ValueErrorException(errout.str());\n    }\n    for (unsigned int bit = 0; bit < 8 && bitIdx < bv1.getNumBits();\n         ++bit, ++bitIdx) {\n      if (c & (1 << bit)) bv1.setBit(bitIdx);\n    }\n  }\n}\n\ntemplate <typename T1>\nvoid UpdateBitVectFromBinaryText(T1& bv1, const std::string& fps) {\n  PRECONDITION(fps.length() * 8 >= bv1.getNumBits(), \"bad FPS length\");\n  unsigned int bitIdx = 0;\n  for (unsigned int i = 0; i < fps.size() && bitIdx < bv1.getNumBits(); i++) {\n    unsigned short c = fps[i];\n    for (unsigned int bit = 0; bit < 8 && bitIdx < bv1.getNumBits();\n         ++bit, ++bitIdx) {\n      if (c & (1 << bit)) bv1.setBit(bitIdx);\n    }\n  }\n}\n\ntemplate double TanimotoSimilarity(const SparseBitVect& bv1,\n                                   const SparseBitVect& bv2);\ntemplate double TverskySimilarity(const SparseBitVect& bv1,\n                                  const SparseBitVect& bv2, double a, double b);\ntemplate double CosineSimilarity(const SparseBitVect& bv1,\n                                 const SparseBitVect& bv2);\ntemplate double KulczynskiSimilarity(const SparseBitVect& bv1,\n                                     const SparseBitVect& bv2);\ntemplate double DiceSimilarity(const SparseBitVect& bv1,\n                               const SparseBitVect& bv2);\ntemplate double SokalSimilarity(const SparseBitVect& bv1,\n                                const SparseBitVect& bv2);\ntemplate double McConnaugheySimilarity(const SparseBitVect& bv1,\n                                       const SparseBitVect& bv2);\ntemplate double AsymmetricSimilarity(const SparseBitVect& bv1,\n                                     const SparseBitVect& bv2);\ntemplate double BraunBlanquetSimilarity(const SparseBitVect& bv1,\n                                        const SparseBitVect& bv2);\ntemplate double RusselSimilarity(const SparseBitVect& bv1,\n                                 const SparseBitVect& bv2);\ntemplate double RogotGoldbergSimilarity(const SparseBitVect& bv1,\n                                        const SparseBitVect& bv2);\ntemplate double OnBitSimilarity(const SparseBitVect& bv1,\n                                const SparseBitVect& bv2);\ntemplate int NumBitsInCommon(const SparseBitVect& bv1,\n                             const SparseBitVect& bv2);\ntemplate double AllBitSimilarity(const SparseBitVect& bv1,\n                                 const SparseBitVect& bv2);\ntemplate int NumOnBitsInCommon(const SparseBitVect& bv1,\n                               const SparseBitVect& bv2);\ntemplate IntVect OnBitsInCommon(const SparseBitVect& bv1,\n                                const SparseBitVect& bv2);\ntemplate IntVect OffBitsInCommon(const SparseBitVect& bv1,\n                                 const SparseBitVect& bv2);\ntemplate DoubleVect OnBitProjSimilarity(const SparseBitVect& bv1,\n                                        const SparseBitVect& bv2);\ntemplate DoubleVect OffBitProjSimilarity(const SparseBitVect& bv1,\n                                         const SparseBitVect& bv2);\n\ntemplate double TanimotoSimilarity(const ExplicitBitVect& bv1,\n                                   const ExplicitBitVect& bv2);\ntemplate double TverskySimilarity(const ExplicitBitVect& bv1,\n                                  const ExplicitBitVect& bv2, double a,\n                                  double b);\ntemplate double CosineSimilarity(const ExplicitBitVect& bv1,\n                                 const ExplicitBitVect& bv2);\ntemplate double KulczynskiSimilarity(const ExplicitBitVect& bv1,\n                                     const ExplicitBitVect& bv2);\ntemplate double DiceSimilarity(const ExplicitBitVect& bv1,\n                               const ExplicitBitVect& bv2);\ntemplate double SokalSimilarity(const ExplicitBitVect& bv1,\n                                const ExplicitBitVect& bv2);\ntemplate double McConnaugheySimilarity(const ExplicitBitVect& bv1,\n                                       const ExplicitBitVect& bv2);\ntemplate double AsymmetricSimilarity(const ExplicitBitVect& bv1,\n                                     const ExplicitBitVect& bv2);\ntemplate double BraunBlanquetSimilarity(const ExplicitBitVect& bv1,\n                                        const ExplicitBitVect& bv2);\ntemplate double RusselSimilarity(const ExplicitBitVect& bv1,\n                                 const ExplicitBitVect& bv2);\ntemplate double RogotGoldbergSimilarity(const ExplicitBitVect& bv1,\n                                        const ExplicitBitVect& bv2);\ntemplate double OnBitSimilarity(const ExplicitBitVect& bv1,\n                                const ExplicitBitVect& bv2);\ntemplate int NumBitsInCommon(const ExplicitBitVect& bv1,\n                             const ExplicitBitVect& bv2);\ntemplate double AllBitSimilarity(const ExplicitBitVect& bv1,\n                                 const ExplicitBitVect& bv2);\ntemplate IntVect OnBitsInCommon(const ExplicitBitVect& bv1,\n                                const ExplicitBitVect& bv2);\ntemplate IntVect OffBitsInCommon(const ExplicitBitVect& bv1,\n                                 const ExplicitBitVect& bv2);\ntemplate DoubleVect OnBitProjSimilarity(const ExplicitBitVect& bv1,\n                                        const ExplicitBitVect& bv2);\ntemplate DoubleVect OffBitProjSimilarity(const ExplicitBitVect& bv1,\n                                         const ExplicitBitVect& bv2);\n\ntemplate SparseBitVect* FoldFingerprint(const SparseBitVect&, unsigned int);\ntemplate ExplicitBitVect* FoldFingerprint(const ExplicitBitVect&, unsigned int);\n\ntemplate std::string BitVectToText(const SparseBitVect&);\ntemplate std::string BitVectToText(const ExplicitBitVect&);\n\ntemplate std::string BitVectToFPSText(const SparseBitVect&);\ntemplate std::string BitVectToFPSText(const ExplicitBitVect&);\ntemplate void UpdateBitVectFromFPSText(SparseBitVect&, const std::string&);\ntemplate void UpdateBitVectFromFPSText(ExplicitBitVect&, const std::string&);\n\ntemplate std::string BitVectToBinaryText(const SparseBitVect&);\ntemplate std::string BitVectToBinaryText(const ExplicitBitVect&);\ntemplate void UpdateBitVectFromBinaryText(SparseBitVect&, const std::string&);\ntemplate void UpdateBitVectFromBinaryText(ExplicitBitVect&, const std::string&);\n\n// from here:\n// http://stackoverflow.com/questions/3849337/msvc-equivalent-to-builtin-popcount\n// but corrected to get the ifdef right\n#ifdef _MSC_VER\n#include <intrin.h>\n#ifdef _WIN64\n#define BUILTIN_POPCOUNT_INSTR __popcnt64\n#define BUILTIN_POPCOUNT_TYPE boost::uint64_t\n#else\n#define BUILTIN_POPCOUNT_INSTR __popcnt\n#define BUILTIN_POPCOUNT_TYPE boost::uint32_t\n#endif\n#else\n#define BUILTIN_POPCOUNT_INSTR __builtin_popcountll\n#define BUILTIN_POPCOUNT_TYPE boost::uint64_t\n#endif\n\n// the Bitmap Tanimoto and Dice similarity code is adapted\n// from Andrew Dalke's chem-fingerprints code\n// http://code.google.com/p/chem-fingerprints/\nnamespace {\nstatic int byte_popcounts[] = {\n    0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4,\n    2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n    2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4,\n    2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n    2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6,\n    4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n    2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5,\n    3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n    2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6,\n    4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n    4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};\n}\nunsigned int CalcBitmapPopcount(const unsigned char* afp, unsigned int nBytes) {\n  PRECONDITION(afp, \"no afp\");\n  unsigned int popcount = 0;\n#ifndef USE_BUILTIN_POPCOUNT\n  for (unsigned int i = 0; i < nBytes; i++) {\n    popcount += byte_popcounts[afp[i]];\n  }\n#else\n  unsigned int eidx = nBytes / sizeof(BUILTIN_POPCOUNT_TYPE);\n  for (unsigned int i = 0; i < eidx; ++i) {\n    popcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)afp)[i]));\n  }\n  for (unsigned int i = eidx * sizeof(BUILTIN_POPCOUNT_TYPE); i < nBytes; ++i) {\n    popcount += byte_popcounts[afp[i]];\n  }\n#endif\n  return popcount;\n}\ndouble CalcBitmapTanimoto(const unsigned char* afp, const unsigned char* bfp,\n                          unsigned int nBytes) {\n  PRECONDITION(afp, \"no afp\");\n  PRECONDITION(bfp, \"no bfp\");\n  unsigned int union_popcount = 0, intersect_popcount = 0;\n#ifndef USE_BUILTIN_POPCOUNT\n  for (unsigned int i = 0; i < nBytes; i++) {\n    union_popcount += byte_popcounts[afp[i] | bfp[i]];\n    intersect_popcount += byte_popcounts[afp[i] & bfp[i]];\n  }\n#else\n  BUILTIN_POPCOUNT_TYPE eidx = nBytes / sizeof(BUILTIN_POPCOUNT_TYPE);\n  for (BUILTIN_POPCOUNT_TYPE i = 0; i < eidx; ++i) {\n    union_popcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)afp)[i] |\n                                           ((BUILTIN_POPCOUNT_TYPE*)bfp)[i]));\n    intersect_popcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)afp)[i] &\n                                               ((BUILTIN_POPCOUNT_TYPE*)bfp)[i]));\n  }\n  for (BUILTIN_POPCOUNT_TYPE i = eidx * sizeof(BUILTIN_POPCOUNT_TYPE); i < nBytes; ++i) {\n    union_popcount += byte_popcounts[afp[i] | bfp[i]];\n    intersect_popcount += byte_popcounts[afp[i] & bfp[i]];\n  }\n#endif\n  if (union_popcount == 0) {\n    return 0.0;\n  }\n  return (intersect_popcount + 0.0) /\n         union_popcount; /* +0.0 to coerce to double */\n}\n\ndouble CalcBitmapDice(const unsigned char* afp, const unsigned char* bfp,\n                      unsigned int nBytes) {\n  PRECONDITION(afp, \"no afp\");\n  PRECONDITION(bfp, \"no bfp\");\n  unsigned int intersect_popcount = 0, a_popcount = 0, b_popcount = 0;\n\n#ifndef USE_BUILTIN_POPCOUNT\n  for (unsigned int i = 0; i < nBytes; i++) {\n    a_popcount += byte_popcounts[afp[i]];\n    b_popcount += byte_popcounts[bfp[i]];\n    intersect_popcount += byte_popcounts[afp[i] & bfp[i]];\n  }\n#else\n  BUILTIN_POPCOUNT_TYPE eidx = nBytes / sizeof(BUILTIN_POPCOUNT_TYPE);\n  for (BUILTIN_POPCOUNT_TYPE i = 0; i < eidx; ++i) {\n    a_popcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)afp)[i]));\n    b_popcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)bfp)[i]));\n    intersect_popcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)afp)[i] &\n                                               ((BUILTIN_POPCOUNT_TYPE*)bfp)[i]));\n  }\n  for (BUILTIN_POPCOUNT_TYPE i = eidx * sizeof(BUILTIN_POPCOUNT_TYPE); i < nBytes; ++i) {\n    a_popcount += byte_popcounts[afp[i]];\n    b_popcount += byte_popcounts[bfp[i]];\n    intersect_popcount += byte_popcounts[afp[i] & bfp[i]];\n  }\n#endif\n\n  if (a_popcount + b_popcount == 0) {\n    return 0.0;\n  }\n  return (2.0 * intersect_popcount) / (a_popcount + b_popcount);\n}\n\ndouble CalcBitmapTversky(const unsigned char* afp, const unsigned char* bfp,\n                         unsigned int nBytes, double ca, double cb) {\n  PRECONDITION(afp, \"no afp\");\n  PRECONDITION(bfp, \"no bfp\");\n  unsigned int intersect_popcount = 0, acount = 0, bcount = 0;\n\n#ifndef USE_BUILTIN_POPCOUNT\n  for (unsigned int i = 0; i < nBytes; i++) {\n    intersect_popcount += byte_popcounts[afp[i] & bfp[i]];\n    acount += byte_popcounts[afp[i]];\n    bcount += byte_popcounts[bfp[i]];\n  }\n#else\n  BUILTIN_POPCOUNT_TYPE eidx = nBytes / sizeof(BUILTIN_POPCOUNT_TYPE);\n  for (BUILTIN_POPCOUNT_TYPE i = 0; i < eidx; ++i) {\n    intersect_popcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)afp)[i] &\n                                               ((BUILTIN_POPCOUNT_TYPE*)bfp)[i]));\n    acount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)afp)[i]));\n    bcount += static_cast<unsigned int>(BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)bfp)[i]));\n  }\n  for (BUILTIN_POPCOUNT_TYPE i = eidx * sizeof(BUILTIN_POPCOUNT_TYPE); i < nBytes; ++i) {\n    intersect_popcount += byte_popcounts[afp[i] & bfp[i]];\n    acount += byte_popcounts[afp[i]];\n    bcount += byte_popcounts[bfp[i]];\n  }\n#endif\n  double denom = ca * acount + cb * bcount + (1 - ca - cb) * intersect_popcount;\n  if (denom == 0.0) {\n    return 0.0;\n  }\n  return intersect_popcount / denom;\n}\n\nbool CalcBitmapAllProbeBitsMatch(const unsigned char* probe,\n                                 const unsigned char* ref,\n                                 unsigned int nBytes) {\n  PRECONDITION(probe, \"no probe\");\n  PRECONDITION(ref, \"no ref\");\n\n#ifndef USE_BUILTIN_POPCOUNT\n  for (unsigned int i = 0; i < nBytes; i++) {\n    if (byte_popcounts[probe[i] & ref[i]] != byte_popcounts[probe[i]]) {\n      return false;\n    }\n  }\n#else\n  unsigned int eidx = nBytes / sizeof(BUILTIN_POPCOUNT_TYPE);\n  for (unsigned int i = 0; i < eidx; ++i) {\n    if (BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)probe)[i] &\n                           ((BUILTIN_POPCOUNT_TYPE*)ref)[i]) !=\n        BUILTIN_POPCOUNT_INSTR(((BUILTIN_POPCOUNT_TYPE*)probe)[i])) {\n      return false;\n    }\n  }\n  for (unsigned int i = eidx * sizeof(BUILTIN_POPCOUNT_TYPE); i < nBytes; ++i) {\n    if (byte_popcounts[probe[i] & ref[i]] != byte_popcounts[probe[i]]) {\n      return false;\n    }\n  }\n#endif\n  return true;\n}\n", "meta": {"hexsha": "f59a951ae181508238788733189e005d3125060c", "size": 33249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/DataStructs/BitOps.cpp", "max_stars_repo_name": "docking-org/rdk", "max_stars_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_stars_repo_licenses": ["PostgreSQL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/DataStructs/BitOps.cpp", "max_issues_repo_name": "docking-org/rdk", "max_issues_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/DataStructs/BitOps.cpp", "max_forks_repo_name": "docking-org/rdk", "max_forks_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-04T02:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T01:18:46.000Z", "avg_line_length": 34.6704900938, "max_line_length": 109, "alphanum_fraction": 0.6127402328, "num_tokens": 9891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.022629198014416436, "lm_q1q2_score": 0.005546077292538292}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Process class declared in the\n    swp_process.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_process.h\"\n\n#include \"swp_params.h\"\n#include \"swp_mechanism.h\"\n#include \"swp_sprog_idealgas_wrapper.h\"\n\n#include <stdexcept>\n#include <cmath>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::Processes;\nusing namespace std;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor.\nProcess::Process(void)\n: m_name(\"\"), m_mech(NULL), m_a(1.0)\n{\n}\n\n// Initialising constructor.\nProcess::Process(const Sweep::Mechanism &mech)\n: m_name(\"\"), m_mech(&mech), m_a(1.0)\n{\n}\n\n// Copy constructor.\nProcess::Process(const Process &copy)\n{\n    *this = copy;\n}\n\n// Default destructor.\nProcess::~Process(void)\n{\n}\n\n\n// OPERATOR OVERLOADS.\n\n// Assigment operator.\nProcess &Process::operator=(const Process &rhs)\n{\n    if (this != &rhs) {\n        m_name = rhs.m_name;\n        m_mech = rhs.m_mech;\n\n        m_a = rhs.m_a;\n\n        // Copy reactants.\n        Sprog::StoichMap::const_iterator i;\n        for (i=rhs.m_reac.begin(); i!=rhs.m_reac.end(); ++i) {\n            m_reac[i->first] = i->second;\n        }\n\n        // Copy products.\n        for (i=rhs.m_prod.begin(); i!=rhs.m_prod.end(); ++i) {\n            m_prod[i->first] = i->second;\n        }\n    }\n    return *this;\n}\n\n\n// PROCESS NAME/DESCRIPTION.\n\n// Returns the process name.\nconst std::string &Process::Name(void) const {return m_name;}\n\n// Sets the process name.\nvoid Process::SetName(const std::string &name) {m_name = name;}\n\n\n// PARENT MECHANISM.\n\n// Returns reference to parent mechanism.\nconst Sweep::Mechanism *const Process::Mechanism() const\n{\n    return m_mech;\n}\n\n// Sets the parent mechanism\nvoid Process::SetMechanism(const Sweep::Mechanism &mech)\n{\n    m_mech = &mech;\n}\n\n// REACTANTS.\n\n// Returns the reactant count.\nunsigned int Process::ReactantCount() const\n{\n    return m_reac.size();\n}\n\n// Returns the stoichiometric reactant coefficients.\nconst Sprog::StoichMap &Process::Reactants(void) const\n{\n    return m_reac;\n}\n\n// Returns the stoichiometry of the ith reactant.\nint Process::Reactants(unsigned int i) const\n{\n    Sprog::StoichMap::const_iterator j = m_reac.find(i);\n    if (j != m_reac.end()) {\n        return j->second;\n    } else {\n        return 0;\n    }\n}\n\n// Adds a reactant to the reaction.\nvoid Process::AddReactant(unsigned int isp, int mu)\n{\n    m_reac[isp] = mu;\n}\n\n// Adds a reactant given the species name.\nvoid Process::AddReactant(const std::string &name, int mu)\n{\n    // Locate the species.\n    unsigned int i;\n    for (i=0; i!=m_mech->Species()->size(); ++i) {\n        if (name.compare((*m_mech->Species())[i]->Name()) == 0) {\n            // Set reactant.\n            m_reac[i] = mu;\n            return;\n        }\n    }\n}\n\n// Removes a reactant, given by name, from the reaction.\nvoid Process::RemoveReactant(const std::string &name)\n{\n    // Locate the species.\n    unsigned int i;\n    for (i=0; i!=m_mech->Species()->size(); ++i) {\n        if (name.compare((*m_mech->Species())[i]->Name()) == 0) {\n            // Delete reactant.\n            m_reac.erase(i);\n            return;\n        }\n    }\n}\n\n\n// PRODUCTS.\n\n// Returns the product count.\nunsigned int Process::ProductCount() const\n{\n    return m_prod.size();\n}\n\n// Returns the stoichiometric product coefficients.\nconst Sprog::StoichMap &Process::Products(void) const\n{\n    return m_prod;\n}\n\n// Returns the stoichiometry of the ith product.\nint Process::Products(unsigned int i) const\n{\n    Sprog::StoichMap::const_iterator j = m_prod.find(i);\n    if (j != m_prod.end()) {\n        return j->second;\n    } else {\n        return 0;\n    }\n}\n\n// Adds a product to the reaction.\nvoid Process::AddProduct(unsigned int isp, int mu)\n{\n    m_prod[isp] = mu;\n}\n\n/*!\n * Virtual parent class function.\n *\n * @param t     Current time of the system\n * @param dt    Time to remove particles over\n * @param sys   The system to do transport for\n * @param local_geom    Geometry of the process\n * @param rng   Random number generator\n */\nvoid Process::PerformDT (\n        const double t,\n        const double dt,\n        Sweep::Cell &sys,\n        const Geometry::LocalGeometry1d& local_geom,\n        rng_type &rng) const {\n    assert(dt > 0.0);\n}\n\n// FICTICIOUS EVENTS.\n\n/*!\n * @param[in]       majr        Majorant rate for event\n * @param[in]       truer       True rate for event\n * @param[in,out]   rng         Random number generator\n *\n * @pre     truer <= majr, if truer > majr, cerr a warning and return false\n *\n * @return      True with probability 1-truer/majr, otherwise false\n */\nbool Process::Fictitious(double majr, double truer, rng_type &rng)\n{\n    // ensure truer <= maj, otherwise it will crash the program.\n    if (truer>majr)\n    {\n        // if the following warning msg show frequently, a better solution ensuring truer <= maj should be considered.\n        std::cerr<<\"maj is still smaller than true\"<<std::endl;\n        return false;\n    }\n    typedef boost::bernoulli_distribution<double> bernoulli_distrib;\n    bernoulli_distrib fictitiousDistrib(1.0 - truer/majr);\n    boost::variate_generator<rng_type&, bernoulli_distrib> fictitiousGenerator(rng, fictitiousDistrib);\n    const bool isFictitious = fictitiousGenerator();\n    return isFictitious;\n}\n\n\n// READ/WRITE/COPY.\n\n// Writes the object to a binary stream.\nvoid Process::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Write the length of the name to the stream.\n        unsigned int n = m_name.length();\n        out.write((char*)&n, sizeof(n));\n\n        // Write the name to the stream.\n        out.write(m_name.c_str(), n);\n\n\n        // Write reactant count.\n        n = (unsigned int)m_reac.size();\n        out.write((char*)&n, sizeof(n));\n\n        // Write reactant stoichiometry.\n        int m = 0;\n        for (Sprog::StoichMap::const_iterator i=m_reac.begin(); i!=m_reac.end(); ++i) {\n            // Write species ID.\n            n = (unsigned int)i->first;\n            out.write((char*)&n, sizeof(n));\n\n            // Write stoichiometry.\n            m = (int)i->second;\n            out.write((char*)&m, sizeof(m));\n        }\n\n        // Write product count.\n        n = (unsigned int)m_prod.size();\n        out.write((char*)&n, sizeof(n));\n\n        // Write product stoichiometry.\n        for (Sprog::StoichMap::const_iterator i=m_prod.begin(); i!=m_prod.end(); ++i) {\n            // Write species ID.\n            n = (unsigned int)i->first;\n            out.write((char*)&n, sizeof(n));\n\n            // Write stoichiometry.\n            m = (int)i->second;\n            out.write((char*)&m, sizeof(m));\n        }\n\n        // Write scaling factor\n        out.write(reinterpret_cast<const char*>(&m_a), sizeof(m_a));\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, Process::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid Process::Deserialize(std::istream &in, const Sweep::Mechanism &mech)\n{\n    m_mech = &mech;\n    m_prod.clear();\n    m_reac.clear();\n\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        int m = 0;\n        unsigned int n = 0, id = 0;\n        char *name = NULL;\n\n        switch (version) {\n            case 0:\n                // Read the length of the process name.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n\n                // Read the process name.\n                name = new char[n];\n                in.read(name, n);\n                m_name.assign(name, n);\n                delete [] name;\n\n                // Read reactant count.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n\n                // Read reactant stoichiometry.\n                for (unsigned int i=0; i!=n; ++i) {\n                    // Read species ID.\n                    in.read(reinterpret_cast<char*>(&id), sizeof(id));\n                    // Read stoichiometry.\n                    in.read(reinterpret_cast<char*>(&m), sizeof(m));\n                    // Create reactant.\n                    m_reac[id] = m;\n                }\n\n                // Read product count.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n\n                // Read product stoichiometry.\n                for (unsigned int i=0; i!=n; ++i) {\n                    // Read species ID.\n                    in.read(reinterpret_cast<char*>(&id), sizeof(id));\n                    // Read stoichiometry.\n                    in.read(reinterpret_cast<char*>(&m), sizeof(m));\n                    // Create product.\n                    m_prod[id] = m;\n                }\n\n                // Read scaling factor\n                double a;\n                in.read(reinterpret_cast<char*>(&a), sizeof(a));\n                SetA(a);\n\n                break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, Process::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, Process::Deserialize).\");\n    }\n}\n\n\n// PROTECTED HELPER FUNCTIONS.\n\n/*!\n *@param[in]    gas     Gas phase mixture\n *\n *@return       Gas phase part of reaction rate\n */\ndouble Process::chemRatePart(const EnvironmentInterface &gas) const\n{\n    double rate = 1.0;\n\n    Sprog::StoichMap::const_iterator i;\n    for (i=m_reac.begin(); i!=m_reac.end(); ++i) {\n        double conc = gas.SpeciesConcentration(i->first) ;\n        for (int j=0; j!=i->second; ++j) {\n            rate *= conc;\n        }\n    }\n\n    return rate;\n}\n\n/*!\n * Adjusts the gas-phase composition using the reactants and\n * products defined for this process.\n *\n * Think carefully about whether calling this function is a\n * good idea:  The use of this method was found to be problematic\n * in \"A predictor-corrector algorithm for the coupling of stiff\n * ODEs to a particle population balance\", Celnik et al, Preprint 58.\n * The requirement that the gas phase mixture be implemented via a\n * SprogIdealGasWrapper will also restrict future applications of the\n * code.  In situations where updating the gas phase during stochastic\n * particle reactions is definitely required, this is the method\n * to use.\n *\n * @param[in,out]   sys     System in which the gas phase is changing\n * @param[in]       wt      Statistical weight of reaction\n * @param[in]       n       Repeat count of reaction\n *\n * @pre      The gas phase in sys must be of type SprogIdealGasWrapper\n *\n * @exception   std::runtime_error      Could not cast gas phase to SprogIdealGasWrapper\n */\nvoid Process::adjustGas(Cell &sys, double wt, unsigned int n) const\n{\n    if(!sys.FixedChem()) {\n        // This method requires write access to the gas phase, which is not\n        // standard in sweep.  This means it cannot use the generic gas\n        // phase interface\n        SprogIdealGasWrapper *gasWrapper = dynamic_cast<SprogIdealGasWrapper*>(&sys.GasPhase());\n        if(gasWrapper == NULL)\n            throw std::runtime_error(\"Could not cast gas phase to SprogIdealGasWrapper in Process::adjustGas\");\n\n        // If excecution reaches here, the cast must have been successful\n        Sprog::Thermo::IdealGas *gas = gasWrapper->Implementation();\n\n        // Get the existing concentrations\n        fvector newConcs;\n        gas->GetConcs(newConcs);\n\n        // Now adjust the concentrations\n        Sprog::StoichMap::const_iterator i;\n        double n_NAvol = wt * (double)n / (NA * sys.SampleVolume());\n        for (i=m_reac.begin(); i!=m_reac.end(); ++i)\n            newConcs[i->first] -= (double)(i->second) * n_NAvol;\n        for (i=m_prod.begin(); i!=m_prod.end(); ++i)\n            newConcs[i->first] +=(double)(i->second) * n_NAvol;\n\n        // Set the new data\n        gas->SetConcs(newConcs);\n    }\n}\n\n// Adjusts the gas-phase composition and temperature \n// using the change in composition of the particle\n// Currently only implemented for titania!\n/*\n* Same warning as in adjustGas above applies\n* @param[in, out]   sys        System in which the gas phase is changing\n* @param[in]        wt         Statistical weight of reaction\n* @param[in]        n          Repeat count of reaction\n* @param[in]        dcomp      Composition change in particle\n* @param[in]        processID  Identify process as reaction (1, 2) or flow (3, 4)\n*\n* @pre      The gas phase in sys must be of type SprogIdealGasWrapper\n*\n* @exception   std::runtime_error      Could not cast gas phase to SprogIdealGasWrapper\n*/\nvoid Process::adjustParticleTemperature(Cell &sys, double wt, unsigned int n, double dcomp, int processID) const \n{\n\tif (!sys.FixedChem())\n\t{\n\t\t// This method requires write access to the gas phase, which is not\n\t\t// standard in sweep.  This means it cannot use the generic gas\n\t\t// phase interface\n\t\tSprogIdealGasWrapper *gasWrapper = dynamic_cast<SprogIdealGasWrapper*>(&sys.GasPhase());\n\n\t\tif (gasWrapper == NULL)\n\t\t\tthrow std::runtime_error(\"Could not cast gas phase to SprogIdealGasWrapper in Process::adjustGas\");\n\n\t\t// If excecution reaches here, the cast must have been successful\n\t\tSprog::Thermo::IdealGas *gas = gasWrapper->Implementation();\n\n\t\t// Function will update the temperature oldTg to temperature newTg\n\t\tdouble oldTg = sys.GasPhase().Temperature();\n\t\tdouble newTg = oldTg;\n\n\t\t// Thermal parameters \n\t\t// Cg, Cp, Cp * rhop and Hs/Us are stored on sys object for\n\t\t// faster computation. They are updated less frequently.\n\t\tfvector Hs, Cs;\n\t\tsys.getEnthalpies(Hs);\n\t\tdouble Cg = sys.getBulkHeatCapacity();\n\t\tdouble Cp = sys.getParticleHeatCapacity();\n\t\tbool constv = sys.IsConstV();\n\t\tint pindex = m_mech->GetParticleSpeciesIndex();\n\t\t// Set enthalpy, heat capacity and density for both phases\n\t\t// Uncomment to update properties each time this function is called. \n\t\t/*if (constv)\n\t\t{\n\t\t\tgas->Us(Hs);\n\t\t\tgas->CalcCvs(oldTg, Cs);\n\t\t\tCg = gas->BulkCv();\n\t\t\tCp = Cs[pindex]; \n\t\t}\n\t\telse\n\t\t{\n\t\t\tgas->Hs(Hs); \n\t\t\tgas->CalcCps(oldTg, Cs);\n\t\t\tCg = gas->BulkCp();\n\t\t\tCp = Cs[pindex];\n\t\t}*/\n\t\tdouble mw = sys.ParticleModel()->Components()[0]->MolWt(); \n\t\tdouble rhop = (sys.Particles().GetSum(iM) + sys.Particles().GetTotalMass()) / (mw * sys.SampleVolume());\n\t\tdouble rhog = gas->Density();\n\t\tdouble Cprhop = Cp * rhop;\n\t\tdouble Cgrhog = Cg * rhog;\n\t\tdouble rhog_mass = gas->MassDensity();\n\t\tdouble P_R = gas->Pressure() / R;\n\t\tdouble Hp = Hs[pindex];\n\n\t\t// Get the existing concentrations\n\t\tfvector newConcs;\n\t\tgas->GetConcs(newConcs);\n\n\t\t// Concentration change in system due to new particle(s)\n\t\tdouble n_NAvol = wt * (double)n / (NA * sys.SampleVolume());\n\n\t\t// Compute the change in concentrations and enthalpy\n\t\tdouble deltaHr = 0.0;\n\t\tdouble gdot = 0.0;\n\t\tdouble change = 0.0;\n\t\tif (processID == 1 || processID == 2) {                // Inception or surface growth\n\t\t\tSprog::StoichMap::const_iterator i;\n\t\t\tfor (i = m_reac.begin(); i != m_reac.end(); ++i)\n\t\t\t{\n\t\t\t\tchange = (double)(i->second) * n_NAvol;\n\t\t\t\tnewConcs[i->first] -= change;\n\t\t\t\tdeltaHr -= change * Hs[i->first];\n\t\t\t\tgdot -= change;\n\t\t\t}\n\t\t\tfor (i = m_prod.begin(); i != m_prod.end(); ++i)\n\t\t\t{\n\t\t\t\tchange = (double)(i->second) * n_NAvol;\n\t\t\t\tnewConcs[i->first] += change;\n\t\t\t\tdeltaHr += change * Hs[i->first];\n\t\t\t\tgdot += change;\n\t\t\t}\n\t\t\tdeltaHr += (dcomp * n_NAvol * Hp);                 // Contribution of particle formation\n\t\t} else if (processID == 4) {                           // Inflow - need to get (f/tau and?) Hp_in\n\t\t\tdouble Hp_in = Hp;\n\t\t\tdeltaHr += n_NAvol * (Hp_in - Hp);\n\t\t}\n\n\t\t// Start to adjust the temperature by subtracting deltaHr/(rho*C)\n\t\tdeltaHr *= 1.0 / (Cgrhog + Cprhop);\n\t\tnewTg -= deltaHr;\n\t\t\n\t\tif (constv)\n\t\t{\n\t\t\t// a) dCk/dt = gdot_k\n\t\t\t// b) drho/dt = dC/dt (constant volume)\n\t\t\t// c) dT/dt * rho * Cv = - deltaHr_total + deltaHflow - (drho/dt * R * T) \n\t\t\n\t\t\t// Adjust the concentrations as in a) and b) above\n\t\t\tgas->SetConcs(newConcs);\n\n\t\t\t// Add denominator to gdot\n\t\t\tgdot *= 1.0 / (Cgrhog + Cprhop);\n\t\t\t\n\t\t\t// Finish adjusting the temperature as in c) above\n\t\t\t// newTg *= 1.0 / (1.0 + R * gdot);                // This way assumes T at tf\n\t\t\tnewTg -= (R * oldTg * gdot);                       // This way assumes T at t0\n\t\t\tgas->SetTemperature(newTg);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// a) dT/dt * rho * Cv = - deltaHr_total + deltaHflow\n\t\t\t// b) gamma = (drho/dt / rho) + (dT/dt / T)\n\t\t\t// c) dCk/dt = gdot_k - gamma * Ck\n\t\t\t// d) rho = P / (R * T)\n\n\t\t\t// Adjust the temperature as in a) above\n\t\t\t// Taking rho at tf:\n\t\t\t//double a = Cprhop;\n\t\t\t//double b = (Cg * P_R) - (oldTg * Cprhop) + (deltaHr);\n\t\t\t//double c = -oldTg * Cg * P_R;\n\t\t\t//newTg = (-b + sqrt((b * b) - (4 * a * c))) / (2 * a); \n\t\t\t// Taking rho at t0, temperature update is already complete.\n\t\t\tgas->SetTemperature(newTg);\n\n\t\t\t// Compute gas-phase expansion as in b) above\n\t\t\tdouble gamma = (gdot / rhog) + ((newTg - oldTg) / oldTg);\t\n\n\t\t\t// Adjust the concentrations as in c) above\n\t\t\tfvector::const_iterator j;\t\t\t\t\t\n\t\t\tfor (int j = 0; j != newConcs.size(); ++j)\n\t\t\t\tnewConcs[j] -= (gamma * newConcs[j]);\n\t\t\tgas->SetConcs(newConcs);\n\t\t\t\n\t\t\t// Account for gas phase expansion (via gamma)\n\t\t\tsys.AdjustSampleVolume(rhog_mass / gas->MassDensity());\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "e67e18bb5dc9c319a6068b191f0d50d1aa703833", "size": 18798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_process.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_process.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_process.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 30.0768, "max_line_length": 118, "alphanum_fraction": 0.6081498032, "num_tokens": 4998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667541296674693, "lm_q2_score": 0.03308597517092889, "lm_q1q2_score": 0.005514618575022109}}
{"text": "// Copyright (C) 2010 Anders Logg\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// Modified by Garth N. Wells, 2011.\n//\n// First added:  2010-11-27\n// Last changed: 2011-01-16\n\n#include <algorithm>\n#include <vector>\n#include <boost/scoped_array.hpp>\n\n#include <dolfin/log/log.h>\n#include <dolfin/common/Timer.h>\n#include <dolfin/common/utils.h>\n#include \"Cell.h\"\n#include \"Mesh.h\"\n#include \"MeshEditor.h\"\n#include \"MeshTopology.h\"\n#include \"MeshGeometry.h\"\n#include \"MeshRenumbering.h\"\n#include \"ParallelData.h\"\n\nusing namespace dolfin;\n\n//-----------------------------------------------------------------------------\ndolfin::Mesh\nMeshRenumbering::renumber_by_color(const Mesh& mesh,\n                                   const std::vector<unsigned int> coloring_type)\n{\n  // Start timer\n  Timer timer(\"Renumber mesh by color\");\n\n  // Get some some mesh\n  const uint tdim = mesh.topology().dim();\n  const uint gdim = mesh.geometry().dim();\n  const uint num_vertices = mesh.num_vertices();\n  const uint num_cells = mesh.num_cells();\n\n  // Check that requested coloring is a cell coloring\n  if (coloring_type[0] != tdim)\n    dolfin_error(\"MeshRenumbering.cpp\",\n                 \"renumber mesh by color\",\n                 \"Coloring is not a cell coloring: only cell colorings are supported\");\n\n  // Compute renumbering\n  std::vector<double> new_coordinates;\n  std::vector<uint> new_connections;\n  MeshRenumbering::compute_renumbering(mesh, coloring_type, new_coordinates,\n                                       new_connections);\n\n  // Create new mesh\n  Mesh new_mesh;\n\n  // Create mesh editor\n  MeshEditor editor;\n  editor.open(new_mesh, mesh.type().cell_type(), tdim, gdim);\n  editor.init_cells(num_cells);\n  editor.init_vertices(num_vertices);\n\n  // Add vertices\n  dolfin_assert(new_coordinates.size() == num_vertices*gdim);\n  for (uint i = 0; i < num_vertices; ++i)\n  {\n    const Point p(gdim, &new_coordinates[i*gdim]);\n    editor.add_vertex(i, p);\n  }\n\n  // Add cells\n  dolfin_assert(new_coordinates.size() == num_vertices*gdim);\n  const uint vertices_per_cell = mesh.type().num_entities(0);\n  for (uint i = 0; i < num_cells; ++i)\n  {\n    std::vector<uint> c(vertices_per_cell);\n    std::copy(new_connections.begin() + i*vertices_per_cell,\n              new_connections.begin() + i*vertices_per_cell + vertices_per_cell,\n              c.begin());\n    editor.add_cell(i, c);\n  }\n\n  editor.close();\n\n  // Initialise coloring data\n  typedef std::map<const std::vector<uint>, std::pair<MeshFunction<uint>,\n           std::vector<std::vector<uint> > > >::const_iterator ConstMeshColoringData;\n\n  // Get old coloring\n  ConstMeshColoringData mesh_coloring\n    = mesh.parallel_data().coloring.find(coloring_type);\n  if (mesh_coloring == mesh.parallel_data().coloring.end())\n    dolfin_error(\"MeshRenumbering.cpp\",\n                 \"renumber mesh by color\",\n                 \"Requested mesh coloring has not been computed\");\n\n  // Get old coloring data\n  const MeshFunction<uint>& colors = mesh_coloring->second.first;\n  const std::vector<std::vector<uint> >&\n    entities_of_color = mesh_coloring->second.second;\n  dolfin_assert(colors.size() == num_cells);\n  dolfin_assert(entities_of_color.size() > 0);\n  const uint num_colors = entities_of_color.size();\n\n  // New coloring data\n  dolfin_assert(new_mesh.parallel_data().coloring.size() == 0);\n  MeshFunction<uint> new_colors(mesh, tdim);\n  std::vector<std::vector<uint> > new_entities_of_color(num_colors);\n\n  uint current_cell = 0;\n  for (uint color = 0; color < num_colors; color++)\n  {\n    // Get the array of cell indices of current color\n    const std::vector<uint>& colored_cells = entities_of_color[color];\n    std::vector<uint>& new_colored_cells = new_entities_of_color[color];\n\n    // Update cell color data\n    for (uint i = 0; i < colored_cells.size(); i++)\n    {\n      new_colored_cells.push_back(current_cell);\n      new_colors[current_cell] = color;\n      current_cell++;\n    }\n  }\n\n  // Set new coloring mesh data\n  std::pair<ConstMeshColoringData, bool> insert\n    = new_mesh.parallel_data().coloring.insert(std::make_pair(coloring_type,\n                          std::make_pair(new_colors, new_entities_of_color)));\n  dolfin_assert(insert.second);\n\n  return new_mesh;\n}\n//-----------------------------------------------------------------------------\nvoid MeshRenumbering::compute_renumbering(const Mesh& mesh,\n                                          const std::vector<dolfin::uint>& coloring_type,\n                                          std::vector<double>& new_coordinates,\n                                          std::vector<uint>& new_connections)\n{\n  // Get some some mesh\n  const uint tdim = mesh.topology().dim();\n  const uint gdim = mesh.geometry().dim();\n  const uint num_vertices = mesh.num_vertices();\n  const uint num_cells = mesh.num_cells();\n\n  // Resize vectors\n  const MeshConnectivity& connectivity = mesh.topology()(tdim, 0);\n  const uint connections_size = connectivity.size();\n  new_connections.resize(connections_size);\n\n  const uint coordinates_size = mesh.geometry().size()*mesh.geometry().dim();\n  new_coordinates.resize(coordinates_size);\n\n  typedef std::map<const std::vector<uint>, std::pair<MeshFunction<uint>,\n           std::vector<std::vector<uint> > > >::const_iterator MeshColoringData;\n\n  info(\"Renumbering mesh by cell colors.\");\n  info(mesh);\n\n  // Check that requested coloring is a cell coloring\n  if (coloring_type[0] != mesh.topology().dim())\n    dolfin_error(\"MeshRenumbering.cpp\",\n                 \"compute renumbering of mesh\",\n                 \"Coloring is not a cell coloring: only cell colorings are supported\");\n\n  // Get coloring\n  MeshColoringData mesh_coloring = mesh.parallel_data().coloring.find(coloring_type);\n\n  // Check that requested coloring has been computed\n  if (mesh_coloring == mesh.parallel_data().coloring.end())\n    dolfin_error(\"MeshRenumbering.cpp\",\n                 \"compute renumbering of mesh\",\n                 \"Requested mesh coloring has not been computed\");\n\n  // Get coloring data (copies since the data will be deleted mesh.clear())\n  const MeshFunction<uint>& colors_old = mesh_coloring->second.first;\n  const std::vector<std::vector<uint> >&\n    entities_of_color_old = mesh_coloring->second.second;\n  dolfin_assert(colors_old.size() == num_cells);\n  dolfin_assert(entities_of_color_old.size() > 0);\n\n  // Get coordinates\n  const double* coordinates = mesh.geometry().coordinates;\n\n  // New vertex indices, -1 if not yet renumbered\n  std::vector<int> new_vertex_indices(num_vertices, -1);\n\n  // Iterate over colors\n  const uint num_colors = entities_of_color_old.size();\n  uint connections_offset = 0;\n  uint current_vertex = 0;\n  for (uint color = 0; color < num_colors; ++color)\n  {\n    // Get the array of cell indices of current color\n    const std::vector<uint>& colored_cells = entities_of_color_old[color];\n\n    // Iterate over cells for current color\n    for (uint i = 0; i < colored_cells.size(); i++)\n    {\n      // Current cell\n      Cell cell(mesh, colored_cells[i]);\n\n      // Get array of vertices for current cell\n      const uint* cell_vertices = cell.entities(0);\n      const uint num_vertices   = cell.num_entities(0);\n\n      // Iterate over cell vertices\n      for (uint j = 0; j < num_vertices; j++)\n      {\n        // Get vertex index\n        const uint vertex_index = cell_vertices[j];\n\n        // Renumber and copy coordinate data if vertex is not yet renumbered\n        if (new_vertex_indices[vertex_index] == -1)\n        {\n          std::copy(coordinates + vertex_index*gdim,\n                    coordinates + (vertex_index + 1)*gdim,\n                    new_coordinates.begin() + current_vertex*gdim);\n          new_vertex_indices[vertex_index] = current_vertex++;\n        }\n\n        // Renumber and copy connectivity data (must be done after vertex renumbering)\n        const uint new_vertex_index = new_vertex_indices[vertex_index];\n        dolfin_assert(new_vertex_index >= 0);\n        new_connections[connections_offset++] = new_vertex_index;\n      }\n    }\n  }\n\n  // Check that all vertices have been renumbered\n  for (uint i = 0; i < new_vertex_indices.size(); i++)\n  {\n    if (new_vertex_indices[i] == -1)\n      dolfin_error(\"MeshRenumbering.cpp\",\n                   \"compute renumbering of mesh\",\n                   \"Some vertices were not renumbered\");\n  }\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "0cad8cf2ed6162c9bbdcebd1e05738ddcf39ef2b", "size": 9061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/mesh/MeshRenumbering.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/mesh/MeshRenumbering.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/mesh/MeshRenumbering.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.9563492063, "max_line_length": 89, "alphanum_fraction": 0.6556671449, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682619422045972, "lm_q2_score": 0.028007521315885776, "lm_q1q2_score": 0.005512613830154199}}
{"text": "// Copyright (c) 2010 Satoshi Nakamoto\n// Copyright (c) 2009-2013 The Bitcoin developers\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n\n\n#include \"base58.h\"\n#include \"bitcoinrpc.h\"\n#include \"init.h\"\n#include \"net.h\"\n#include \"uint256.h\"\n#include \"wallet.h\"\n#include \"script.h\"\n\n#include <stdint.h>\n#include <string>\n#include <openssl/ec.h>\n#include <openssl/sha.h>\n#include <openssl/bn.h>\n#include <openssl/obj_mac.h>\n#include <openssl/ecdsa.h>\n\n#include <boost/assign/list_of.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include \"json/json_spirit_utils.h\"\n#include \"json/json_spirit_value.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace json_spirit;\n\nvoid ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)\n{\n    txnouttype type;\n    vector<CTxDestination> addresses;\n    int nRequired;\n\n    out.push_back(Pair(\"asm\", scriptPubKey.ToString()));\n    if (fIncludeHex)\n        out.push_back(Pair(\"hex\", HexStr(scriptPubKey.begin(), scriptPubKey.end())));\n\n    if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))\n    {\n        out.push_back(Pair(\"type\", GetTxnOutputType(type)));\n        return;\n    }\n\n    out.push_back(Pair(\"reqSigs\", nRequired));\n    out.push_back(Pair(\"type\", GetTxnOutputType(type)));\n\n    Array a;\n    BOOST_FOREACH(const CTxDestination& addr, addresses)\n        a.push_back(CBitcoinAddress(addr).ToString());\n    out.push_back(Pair(\"addresses\", a));\n}\n\nvoid TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)\n{\n    entry.push_back(Pair(\"txid\", tx.GetHash().GetHex()));\n    entry.push_back(Pair(\"version\", tx.nVersion));\n    entry.push_back(Pair(\"locktime\", (boost::int64_t)tx.nLockTime));\n    Array vin;\n    BOOST_FOREACH(const CTxIn& txin, tx.vin)\n    {\n        Object in;\n        if (tx.IsCoinBase())\n            in.push_back(Pair(\"coinbase\", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));\n        else\n        {\n            in.push_back(Pair(\"txid\", txin.prevout.hash.GetHex()));\n            in.push_back(Pair(\"vout\", (boost::int64_t)txin.prevout.n));\n            Object o;\n            o.push_back(Pair(\"asm\", txin.scriptSig.ToString()));\n            o.push_back(Pair(\"hex\", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));\n            in.push_back(Pair(\"scriptSig\", o));\n        }\n        in.push_back(Pair(\"sequence\", (boost::int64_t)txin.nSequence));\n        vin.push_back(in);\n    }\n    entry.push_back(Pair(\"vin\", vin));\n    Array vout;\n    for (unsigned int i = 0; i < tx.vout.size(); i++)\n    {\n        const CTxOut& txout = tx.vout[i];\n        Object out;\n        out.push_back(Pair(\"value\", ValueFromAmount(txout.nValue)));\n        out.push_back(Pair(\"n\", (boost::int64_t)i));\n        Object o;\n        ScriptPubKeyToJSON(txout.scriptPubKey, o, false);\n        out.push_back(Pair(\"scriptPubKey\", o));\n        vout.push_back(out);\n    }\n    entry.push_back(Pair(\"vout\", vout));\n\n    if (hashBlock != 0)\n    {\n        entry.push_back(Pair(\"blockhash\", hashBlock.GetHex()));\n        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);\n        if (mi != mapBlockIndex.end() && (*mi).second)\n        {\n            CBlockIndex* pindex = (*mi).second;\n            if (chainActive.Contains(pindex))\n            {\n                entry.push_back(Pair(\"confirmations\", 1 + chainActive.Height() - pindex->nHeight));\n                entry.push_back(Pair(\"time\", (boost::int64_t)pindex->nTime));\n                entry.push_back(Pair(\"blocktime\", (boost::int64_t)pindex->nTime));\n            }\n            else\n                entry.push_back(Pair(\"confirmations\", 0));\n        }\n    }\n}\n\nValue getrawtransaction(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() < 1 || params.size() > 2)\n        throw runtime_error(\n            \"getrawtransaction \\\"txid\\\" ( verbose )\\n\"\n            \"\\nReturn the raw transaction data.\\n\"\n            \"\\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\\n\"\n            \"If verbose is non-zero, returns an Object with information about 'txid'.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"txid\\\"      (string, required) The transaction id\\n\"\n            \"2. verbose       (numeric, optional, default=0) If 0, return a string, other return a json object\\n\"\n\n            \"\\nResult (if verbose is not set or set to 0):\\n\"\n            \"\\\"data\\\"      (string) The serialized, hex-encoded data for 'txid'\\n\"\n\n            \"\\nResult (if verbose > 0):\\n\"\n            \"{\\n\"\n            \"  \\\"hex\\\" : \\\"data\\\",       (string) The serialized, hex-encoded data for 'txid'\\n\"\n            \"  \\\"txid\\\" : \\\"id\\\",        (string) The transaction id (same as provided)\\n\"\n            \"  \\\"version\\\" : n,          (numeric) The version\\n\"\n            \"  \\\"locktime\\\" : ttt,       (numeric) The lock time\\n\"\n            \"  \\\"vin\\\" : [               (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"txid\\\": \\\"id\\\",    (string) The transaction id\\n\"\n            \"       \\\"vout\\\": n,         (numeric) \\n\"\n            \"       \\\"scriptSig\\\": {     (json object) The script\\n\"\n            \"         \\\"asm\\\": \\\"asm\\\",  (string) asm\\n\"\n            \"         \\\"hex\\\": \\\"hex\\\"   (string) hex\\n\"\n            \"       },\\n\"\n            \"       \\\"sequence\\\": n      (numeric) The script sequence number\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"vout\\\" : [              (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"value\\\" : x.xxx,            (numeric) The value in btc\\n\"\n            \"       \\\"n\\\" : n,                    (numeric) index\\n\"\n            \"       \\\"scriptPubKey\\\" : {          (json object)\\n\"\n            \"         \\\"asm\\\" : \\\"asm\\\",          (string) the asm\\n\"\n            \"         \\\"hex\\\" : \\\"hex\\\",          (string) the hex\\n\"\n            \"         \\\"reqSigs\\\" : n,            (numeric) The required sigs\\n\"\n            \"         \\\"type\\\" : \\\"pubkeyhash\\\",  (string) The type, eg 'pubkeyhash'\\n\"\n            \"         \\\"addresses\\\" : [           (json array of string)\\n\"\n            \"           \\\"bitcoinaddress\\\"        (string) bitcoin address\\n\"\n            \"           ,...\\n\"\n            \"         ]\\n\"\n            \"       }\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"blockhash\\\" : \\\"hash\\\",   (string) the block hash\\n\"\n            \"  \\\"confirmations\\\" : n,      (numeric) The confirmations\\n\"\n            \"  \\\"time\\\" : ttt,             (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"blocktime\\\" : ttt         (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"getrawtransaction\", \"\\\"mytxid\\\"\")\n            + HelpExampleCli(\"getrawtransaction\", \"\\\"mytxid\\\" 1\")\n            + HelpExampleRpc(\"getrawtransaction\", \"\\\"mytxid\\\", 1\")\n        );\n\n    \n    uint256 hash = ParseHashV(params[0], \"parameter 1\");\n\n    bool fVerbose = false;\n    if (params.size() > 1)\n        fVerbose = (params[1].get_int() != 0);\n\n    CTransaction tx;\n    uint256 hashBlock = 0;\n    if (!GetTransaction(hash, tx, hashBlock, true))\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"No information available about transaction\");\n\n    CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);\n    ssTx << tx;\n    string strHex = HexStr(ssTx.begin(), ssTx.end());\n\n    if (!fVerbose)\n        return strHex;\n\n    Object result;\n    result.push_back(Pair(\"hex\", strHex));\n    TxToJSON(tx, hashBlock, result);\n    return result;\n}\n\nValue listunspent(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() > 3)\n        throw runtime_error(\n            \"listunspent ( minconf maxconf  [\\\"address\\\",...] )\\n\"\n            \"\\nReturns array of unspent transaction outputs\\n\"\n            \"with between minconf and maxconf (inclusive) confirmations.\\n\"\n            \"Optionally filter to only include txouts paid to specified addresses.\\n\"\n            \"Results are an array of Objects, each of which has:\\n\"\n            \"{txid, vout, scriptPubKey, amount, confirmations}\\n\"\n            \"\\nArguments:\\n\"\n            \"1. minconf          (numeric, optional, default=1) The minimum confirmationsi to filter\\n\"\n            \"2. maxconf          (numeric, optional, default=9999999) The maximum confirmations to filter\\n\"\n            \"3. \\\"addresses\\\"    (string) A json array of bitcoin addresses to filter\\n\"\n            \"    [\\n\"\n            \"      \\\"address\\\"   (string) bitcoin address\\n\"\n            \"      ,...\\n\"\n            \"    ]\\n\"\n            \"\\nResult\\n\"\n            \"[                   (array of json object)\\n\"\n            \"  {\\n\"\n            \"    \\\"txid\\\" : \\\"txid\\\",        (string) the transaction id \\n\"\n            \"    \\\"vout\\\" : n,               (numeric) the vout value\\n\"\n            \"    \\\"address\\\" : \\\"address\\\",  (string) the bitcoin address\\n\"\n            \"    \\\"account\\\" : \\\"account\\\",  (string) The associated account, or \\\"\\\" for the default account\\n\"\n            \"    \\\"scriptPubKey\\\" : \\\"key\\\", (string) the script key\\n\"\n            \"    \\\"amount\\\" : x.xxx,         (numeric) the transaction amount in btc\\n\"\n            \"    \\\"confirmations\\\" : n       (numeric) The number of confirmations\\n\"\n            \"  }\\n\"\n            \"  ,...\\n\"\n            \"]\\n\"\n\n            \"\\nExamples\\n\"\n            + HelpExampleCli(\"listunspent\", \"\")\n            + HelpExampleCli(\"listunspent\", \"6 9999999 \\\"[\\\\\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\\\\\",\\\\\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\\\\\"]\\\"\")\n            + HelpExampleRpc(\"listunspent\", \"6, 9999999 \\\"[\\\\\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\\\\\",\\\\\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\\\\\"]\\\"\")\n        );\n\n    RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));\n\n    int nMinDepth = 1;\n    if (params.size() > 0)\n        nMinDepth = params[0].get_int();\n\n    int nMaxDepth = 9999999;\n    if (params.size() > 1)\n        nMaxDepth = params[1].get_int();\n\n    set<CBitcoinAddress> setAddress;\n    if (params.size() > 2)\n    {\n        Array inputs = params[2].get_array();\n        BOOST_FOREACH(Value& input, inputs)\n        {\n            CBitcoinAddress address(input.get_str());\n            if (!address.IsValid())\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string(\"Invalid Bitcoin address: \")+input.get_str());\n            if (setAddress.count(address))\n                throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter, duplicated address: \")+input.get_str());\n           setAddress.insert(address);\n        }\n    }\n\n    Array results;\n    vector<COutput> vecOutputs;\n    assert(pwalletMain != NULL);\n    pwalletMain->AvailableCoins(vecOutputs, false);\n    BOOST_FOREACH(const COutput& out, vecOutputs)\n    {\n        if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)\n            continue;\n\n        if (setAddress.size())\n        {\n            CTxDestination address;\n            if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))\n                continue;\n\n            if (!setAddress.count(address))\n                continue;\n        }\n\n        int64_t nValue = out.tx->vout[out.i].nValue;\n        const CScript& pk = out.tx->vout[out.i].scriptPubKey;\n        Object entry;\n        entry.push_back(Pair(\"txid\", out.tx->GetHash().GetHex()));\n        entry.push_back(Pair(\"vout\", out.i));\n        CTxDestination address;\n        if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))\n        {\n            entry.push_back(Pair(\"address\", CBitcoinAddress(address).ToString()));\n            if (pwalletMain->mapAddressBook.count(address))\n                entry.push_back(Pair(\"account\", pwalletMain->mapAddressBook[address].name));\n        }\n        entry.push_back(Pair(\"scriptPubKey\", HexStr(pk.begin(), pk.end())));\n        if (pk.IsPayToScriptHash())\n        {\n            CTxDestination address;\n            if (ExtractDestination(pk, address))\n            {\n                const CScriptID& hash = boost::get<const CScriptID&>(address);\n                CScript redeemScript;\n                if (pwalletMain->GetCScript(hash, redeemScript))\n                    entry.push_back(Pair(\"redeemScript\", HexStr(redeemScript.begin(), redeemScript.end())));\n            }\n        }\n        entry.push_back(Pair(\"amount\",ValueFromAmount(nValue)));\n        entry.push_back(Pair(\"confirmations\",out.nDepth));\n        results.push_back(entry);\n    }\n\n    return results;\n}\n\nValue createrawtransaction(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 2)\n        throw runtime_error(\n            \"createrawtransaction [{\\\"txid\\\":\\\"id\\\",\\\"vout\\\":n},...] {\\\"address\\\":amount,...}\\n\"\n            \"\\nCreate a transaction spending the given inputs and sending to the given addresses.\\n\"\n            \"Returns hex-encoded raw transaction.\\n\"\n            \"Note that the transaction's inputs are not signed, and\\n\"\n            \"it is not stored in the wallet or transmitted to the network.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"transactions\\\"        (string, required) A json array of json objects\\n\"\n            \"     [\\n\"\n            \"       {\\n\"\n            \"         \\\"txid\\\":\\\"id\\\",  (string, required) The transaction id\\n\"\n            \"         \\\"vout\\\":n        (numeric, required) The output number\\n\"\n            \"       }\\n\"\n            \"       ,...\\n\"\n            \"     ]\\n\"\n            \"2. \\\"addresses\\\"           (string, required) a json object with addresses as keys and amounts as values\\n\"\n            \"    {\\n\"\n            \"      \\\"address\\\": x.xxx   (numeric, required) The key is the bitcoin address, the value is the btc amount\\n\"\n            \"      ,...\\n\"\n            \"    }\\n\"\n\n            \"\\nResult:\\n\"\n            \"\\\"transaction\\\"            (string) hex string of the transaction\\n\"\n\n            \"\\nExamples\\n\"\n            + HelpExampleCli(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\" \\\"{\\\\\\\"address\\\\\\\":0.01}\\\"\")\n            + HelpExampleRpc(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\":\\\\\\\"myid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\", \\\"{\\\\\\\"address\\\\\\\":0.01}\\\"\")\n        );\n\n    RPCTypeCheck(params, list_of(array_type)(obj_type));\n\n    Array inputs = params[0].get_array();\n    Object sendTo = params[1].get_obj();\n\n    CTransaction rawTx;\n\n    BOOST_FOREACH(const Value& input, inputs)\n    {\n        const Object& o = input.get_obj();\n\n        uint256 txid = ParseHashO(o, \"txid\");\n\n        const Value& vout_v = find_value(o, \"vout\");\n        if (vout_v.type() != int_type)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, missing vout key\");\n        int nOutput = vout_v.get_int();\n        if (nOutput < 0)\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid parameter, vout must be positive\");\n\n        CTxIn in(COutPoint(txid, nOutput));\n        rawTx.vin.push_back(in);\n    }\n\n    set<CBitcoinAddress> setAddress;\n    BOOST_FOREACH(const Pair& s, sendTo)\n    {\n        CBitcoinAddress address(s.name_);\n        if (!address.IsValid())\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string(\"Invalid Bitcoin address: \")+s.name_);\n\n        if (setAddress.count(address))\n            throw JSONRPCError(RPC_INVALID_PARAMETER, string(\"Invalid parameter, duplicated address: \")+s.name_);\n        setAddress.insert(address);\n\n        CScript scriptPubKey;\n        scriptPubKey.SetDestination(address.Get());\n        int64_t nAmount = AmountFromValue(s.value_);\n\n        CTxOut out(nAmount, scriptPubKey);\n        rawTx.vout.push_back(out);\n    }\n\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    ss << rawTx;\n    return HexStr(ss.begin(), ss.end());\n}\n\nValue decoderawtransaction(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"decoderawtransaction \\\"hexstring\\\"\\n\"\n            \"\\nReturn a JSON object representing the serialized, hex-encoded transaction.\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"txid\\\"      (string, required) The transaction hex string\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"hex\\\" : \\\"data\\\",       (string) The serialized, hex-encoded data for 'txid'\\n\"\n            \"  \\\"txid\\\" : \\\"id\\\",        (string) The transaction id (same as provided)\\n\"\n            \"  \\\"version\\\" : n,          (numeric) The version\\n\"\n            \"  \\\"locktime\\\" : ttt,       (numeric) The lock time\\n\"\n            \"  \\\"vin\\\" : [               (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"txid\\\": \\\"id\\\",    (string) The transaction id\\n\"\n            \"       \\\"vout\\\": n,         (numeric) The output number\\n\"\n            \"       \\\"scriptSig\\\": {     (json object) The script\\n\"\n            \"         \\\"asm\\\": \\\"asm\\\",  (string) asm\\n\"\n            \"         \\\"hex\\\": \\\"hex\\\"   (string) hex\\n\"\n            \"       },\\n\"\n            \"       \\\"sequence\\\": n     (numeric) The script sequence number\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"vout\\\" : [             (array of json objects)\\n\"\n            \"     {\\n\"\n            \"       \\\"value\\\" : x.xxx,            (numeric) The value in btc\\n\"\n            \"       \\\"n\\\" : n,                    (numeric) index\\n\"\n            \"       \\\"scriptPubKey\\\" : {          (json object)\\n\"\n            \"         \\\"asm\\\" : \\\"asm\\\",          (string) the asm\\n\"\n            \"         \\\"hex\\\" : \\\"hex\\\",          (string) the hex\\n\"\n            \"         \\\"reqSigs\\\" : n,            (numeric) The required sigs\\n\"\n            \"         \\\"type\\\" : \\\"pubkeyhash\\\",  (string) The type, eg 'pubkeyhash'\\n\"\n            \"         \\\"addresses\\\" : [           (json array of string)\\n\"\n            \"           \\\"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\\\"   (string) bitcoin address\\n\"\n            \"           ,...\\n\"\n            \"         ]\\n\"\n            \"       }\\n\"\n            \"     }\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"blockhash\\\" : \\\"hash\\\",   (string) the block hash\\n\"\n            \"  \\\"confirmations\\\" : n,      (numeric) The confirmations\\n\"\n            \"  \\\"time\\\" : ttt,             (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"  \\\"blocktime\\\" : ttt         (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"decoderawtransaction\", \"\\\"hexstring\\\"\")\n            + HelpExampleRpc(\"decoderawtransaction\", \"\\\"hexstring\\\"\")\n        );\n\n    vector<unsigned char> txData(ParseHexV(params[0], \"argument\"));\n    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n    CTransaction tx;\n    try {\n        ssData >> tx;\n    }\n    catch (std::exception &e) {\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n    }\n\n    Object result;\n    TxToJSON(tx, 0, result);\n\n    return result;\n}\n\nValue decodescript(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() != 1)\n        throw runtime_error(\n            \"decodescript \\\"hex\\\"\\n\"\n            \"\\nDecode a hex-encoded script.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"hex\\\"     (string) the hex encoded script\\n\"\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"asm\\\":\\\"asm\\\",   (string) Script public key\\n\"\n            \"  \\\"hex\\\":\\\"hex\\\",   (string) hex encoded public key\\n\"\n            \"  \\\"type\\\":\\\"type\\\", (string) The output type\\n\"\n            \"  \\\"reqSigs\\\": n,    (numeric) The required signatures\\n\"\n            \"  \\\"addresses\\\": [   (json array of string)\\n\"\n            \"     \\\"address\\\"     (string) bitcoin address\\n\"\n            \"     ,...\\n\"\n            \"  ],\\n\"\n            \"  \\\"p2sh\\\",\\\"address\\\" (string) script address\\n\"\n            \"}\\n\"\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"decodescript\", \"\\\"hexstring\\\"\")\n            + HelpExampleRpc(\"decodescript\", \"\\\"hexstring\\\"\")\n        );\n\n    RPCTypeCheck(params, list_of(str_type));\n\n    Object r;\n    CScript script;\n    if (params[0].get_str().size() > 0){\n        vector<unsigned char> scriptData(ParseHexV(params[0], \"argument\"));\n        script = CScript(scriptData.begin(), scriptData.end());\n    } else {\n        // Empty scripts are valid\n    }\n    ScriptPubKeyToJSON(script, r, false);\n\n    r.push_back(Pair(\"p2sh\", CBitcoinAddress(script.GetID()).ToString()));\n    return r;\n}\n\nValue signrawtransaction(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() < 1 || params.size() > 4)\n        throw runtime_error(\n            \"signrawtransaction \\\"hexstring\\\" ( [{\\\"txid\\\":\\\"id\\\",\\\"vout\\\":n,\\\"scriptPubKey\\\":\\\"hex\\\",\\\"redeemScript\\\":\\\"hex\\\"},...] [\\\"privatekey1\\\",...] sighashtype )\\n\"\n            \"\\nSign inputs for raw transaction (serialized, hex-encoded).\\n\"\n            \"The second optional argument (may be null) is an array of previous transaction outputs that\\n\"\n            \"this transaction depends on but may not yet be in the block chain.\\n\"\n            \"The third optional argument (may be null) is an array of base58-encoded private\\n\"\n            \"keys that, if given, will be the only keys used to sign the transaction.\\n\"\n            + HelpRequiringPassphrase() + \"\\n\"\n\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\"     (string, required) The transaction hex string\\n\"\n            \"2. \\\"prevtxs\\\"       (string, optional) An json array of previous dependent transaction outputs\\n\"\n            \"     [               (json array of json objects)\\n\"\n            \"       {\\n\"\n            \"         \\\"txid\\\":\\\"id\\\",             (string, required) The transaction id\\n\"\n            \"         \\\"vout\\\":n,                  (numeric, required) The output number\\n\"\n            \"         \\\"scriptPubKey\\\": \\\"hex\\\",   (string, required) script key\\n\"\n            \"         \\\"redeemScript\\\": \\\"hex\\\"    (string, required) redeem script\\n\"\n            \"       }\\n\"\n            \"       ,...\\n\"\n            \"    ]\\n\"\n            \"3. \\\"privatekeys\\\"     (string, optional) A json array of base58-encoded private keys for signing\\n\"\n            \"    [                  (json array of strings)\\n\"\n            \"      \\\"privatekey\\\"   (string) private key in base58-encoding\\n\"\n            \"      ,...\\n\"\n            \"    ]\\n\"\n            \"4. \\\"sighashtype\\\"     (string, optional, default=ALL) The signature has type. Must be one of\\n\"\n            \"       \\\"ALL\\\"\\n\"\n            \"       \\\"NONE\\\"\\n\"\n            \"       \\\"SINGLE\\\"\\n\"\n            \"       \\\"ALL|ANYONECANPAY\\\"\\n\"\n            \"       \\\"NONE|ANYONECANPAY\\\"\\n\"\n            \"       \\\"SINGLE|ANYONECANPAY\\\"\\n\"\n\n            \"\\nResult:\\n\"\n            \"{\\n\"\n            \"  \\\"hex\\\": \\\"value\\\",   (string) The raw transaction with signature(s) (hex-encoded string)\\n\"\n            \"  \\\"complete\\\": n       (numeric) if transaction has a complete set of signature (0 if not)\\n\"\n            \"}\\n\"\n\n            \"\\nExamples:\\n\"\n            + HelpExampleCli(\"signrawtransaction\", \"\\\"myhex\\\"\")\n            + HelpExampleRpc(\"signrawtransaction\", \"\\\"myhex\\\"\")\n        );\n\n    RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);\n\n    vector<unsigned char> txData(ParseHexV(params[0], \"argument 1\"));\n    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n    vector<CTransaction> txVariants;\n    while (!ssData.empty())\n    {\n        try {\n            CTransaction tx;\n            ssData >> tx;\n            txVariants.push_back(tx);\n        }\n        catch (std::exception &e) {\n            throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n        }\n    }\n\n    if (txVariants.empty())\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"Missing transaction\");\n\n    // mergedTx will end up with all the signatures; it\n    // starts as a clone of the rawtx:\n    CTransaction mergedTx(txVariants[0]);\n    bool fComplete = true;\n\n    // Fetch previous transactions (inputs):\n    CCoinsView viewDummy;\n    CCoinsViewCache view(viewDummy);\n    {\n        LOCK(mempool.cs);\n        CCoinsViewCache &viewChain = *pcoinsTip;\n        CCoinsViewMemPool viewMempool(viewChain, mempool);\n        view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view\n\n        BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {\n            const uint256& prevHash = txin.prevout.hash;\n            CCoins coins;\n            view.GetCoins(prevHash, coins); // this is certainly allowed to fail\n        }\n\n        view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long\n    }\n\n    bool fGivenKeys = false;\n    CBasicKeyStore tempKeystore;\n    if (params.size() > 2 && params[2].type() != null_type)\n    {\n        fGivenKeys = true;\n        Array keys = params[2].get_array();\n        BOOST_FOREACH(Value k, keys)\n        {\n            CBitcoinSecret vchSecret;\n            bool fGood = vchSecret.SetString(k.get_str());\n            if (!fGood)\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid private key\");\n            CKey key = vchSecret.GetKey();\n            tempKeystore.AddKey(key);\n        }\n    }\n    else\n        EnsureWalletIsUnlocked();\n\n    // Add previous txouts given in the RPC call:\n    if (params.size() > 1 && params[1].type() != null_type)\n    {\n        Array prevTxs = params[1].get_array();\n        BOOST_FOREACH(Value& p, prevTxs)\n        {\n            if (p.type() != obj_type)\n                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"expected object with {\\\"txid'\\\",\\\"vout\\\",\\\"scriptPubKey\\\"}\");\n\n            Object prevOut = p.get_obj();\n\n            RPCTypeCheck(prevOut, map_list_of(\"txid\", str_type)(\"vout\", int_type)(\"scriptPubKey\", str_type));\n\n            uint256 txid = ParseHashO(prevOut, \"txid\");\n\n            int nOut = find_value(prevOut, \"vout\").get_int();\n            if (nOut < 0)\n                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"vout must be positive\");\n\n            vector<unsigned char> pkData(ParseHexO(prevOut, \"scriptPubKey\"));\n            CScript scriptPubKey(pkData.begin(), pkData.end());\n\n            CCoins coins;\n            if (view.GetCoins(txid, coins)) {\n                if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {\n                    string err(\"Previous output scriptPubKey mismatch:\\n\");\n                    err = err + coins.vout[nOut].scriptPubKey.ToString() + \"\\nvs:\\n\"+\n                        scriptPubKey.ToString();\n                    throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);\n                }\n                // what todo if txid is known, but the actual output isn't?\n            }\n            if ((unsigned int)nOut >= coins.vout.size())\n                coins.vout.resize(nOut+1);\n            coins.vout[nOut].scriptPubKey = scriptPubKey;\n            coins.vout[nOut].nValue = 0; // we don't know the actual output value\n            view.SetCoins(txid, coins);\n\n            // if redeemScript given and not using the local wallet (private keys\n            // given), add redeemScript to the tempKeystore so it can be signed:\n            if (fGivenKeys && scriptPubKey.IsPayToScriptHash())\n            {\n                RPCTypeCheck(prevOut, map_list_of(\"txid\", str_type)(\"vout\", int_type)(\"scriptPubKey\", str_type)(\"redeemScript\",str_type));\n                Value v = find_value(prevOut, \"redeemScript\");\n                if (!(v == Value::null))\n                {\n                    vector<unsigned char> rsData(ParseHexV(v, \"redeemScript\"));\n                    CScript redeemScript(rsData.begin(), rsData.end());\n                    tempKeystore.AddCScript(redeemScript);\n                }\n            }\n        }\n    }\n\n    const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);\n\n    int nHashType = SIGHASH_ALL;\n    if (params.size() > 3 && params[3].type() != null_type)\n    {\n        static map<string, int> mapSigHashValues =\n            boost::assign::map_list_of\n            (string(\"ALL\"), int(SIGHASH_ALL))\n            (string(\"ALL|ANYONECANPAY\"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))\n            (string(\"NONE\"), int(SIGHASH_NONE))\n            (string(\"NONE|ANYONECANPAY\"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))\n            (string(\"SINGLE\"), int(SIGHASH_SINGLE))\n            (string(\"SINGLE|ANYONECANPAY\"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))\n            ;\n        string strHashType = params[3].get_str();\n        if (mapSigHashValues.count(strHashType))\n            nHashType = mapSigHashValues[strHashType];\n        else\n            throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid sighash param\");\n    }\n\n    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);\n\n    // Sign what we can:\n    for (unsigned int i = 0; i < mergedTx.vin.size(); i++)\n    {\n        CTxIn& txin = mergedTx.vin[i];\n        CCoins coins;\n        if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))\n        {\n            fComplete = false;\n            continue;\n        }\n        const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;\n\n        txin.scriptSig.clear();\n        // Only sign SIGHASH_SINGLE if there's a corresponding output:\n        if (!fHashSingle || (i < mergedTx.vout.size()))\n            SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);\n\n        // ... and merge in other signatures:\n        BOOST_FOREACH(const CTransaction& txv, txVariants)\n        {\n            txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);\n        }\n        if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))\n            fComplete = false;\n    }\n\n    Object result;\n    CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);\n    ssTx << mergedTx;\n    result.push_back(Pair(\"hex\", HexStr(ssTx.begin(), ssTx.end())));\n    result.push_back(Pair(\"complete\", fComplete));\n\n    return result;\n}\n\nValue sendrawtransaction(const Array& params, bool fHelp)\n{\n    if (fHelp || params.size() < 1 || params.size() > 2)\n        throw runtime_error(\n            \"sendrawtransaction \\\"hexstring\\\" ( allowhighfees )\\n\"\n            \"\\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\\n\"\n            \"\\nAlso see createrawtransaction and signrawtransaction calls.\\n\"\n            \"\\nArguments:\\n\"\n            \"1. \\\"hexstring\\\"    (string, required) The hex string of the raw transaction)\\n\"\n            \"2. allowhighfees    (boolean, optional, default=false) Allow high fees\\n\"\n            \"\\nResult:\\n\"\n            \"\\\"hex\\\"             (string) The transaction hash in hex\\n\"\n            \"\\nExamples:\\n\"\n            \"\\nCreate a transaction\\n\"\n            + HelpExampleCli(\"createrawtransaction\", \"\\\"[{\\\\\\\"txid\\\\\\\" : \\\\\\\"mytxid\\\\\\\",\\\\\\\"vout\\\\\\\":0}]\\\" \\\"{\\\\\\\"myaddress\\\\\\\":0.01}\\\"\") +\n            \"Sign the transaction, and get back the hex\\n\"\n            + HelpExampleCli(\"signrawtransaction\", \"\\\"myhex\\\"\") +\n            \"\\nSend the transaction (signed hex)\\n\"\n            + HelpExampleCli(\"sendrawtransaction\", \"\\\"signedhex\\\"\") +\n            \"\\nAs a json rpc call\\n\"\n            + HelpExampleRpc(\"sendrawtransaction\", \"\\\"signedhex\\\"\")\n        );\n\n\n    // parse hex string from parameter\n    vector<unsigned char> txData(ParseHexV(params[0], \"parameter\"));\n    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);\n    CTransaction tx;\n\n    bool fOverrideFees = false;\n    if (params.size() > 1)\n        fOverrideFees = params[1].get_bool();\n\n    // deserialize binary data stream\n    try {\n        ssData >> tx;\n    }\n    catch (std::exception &e) {\n        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX decode failed\");\n    }\n    uint256 hashTx = tx.GetHash();\n\n    bool fHave = false;\n    CCoinsViewCache &view = *pcoinsTip;\n    CCoins existingCoins;\n    {\n        fHave = view.GetCoins(hashTx, existingCoins);\n        if (!fHave) {\n            // push to local node\n            CValidationState state;\n            if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees))\n                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, \"TX rejected\"); // TODO: report validation state\n        }\n    }\n    if (fHave) {\n        if (existingCoins.nHeight < 1000000000)\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"transaction already in block chain\");\n        // Not in block, but already in the memory pool; will drop\n        // through to re-relay it.\n    } else {\n        SyncWithWallets(hashTx, tx, NULL);\n    }\n    RelayTransaction(tx, hashTx);\n\n    return hashTx.GetHex();\n}\n\nvector<char *> getsignaturevalues(CTransaction tx, unsigned int input, bool needk) {\n    \n    //Prepare error message for convinence\n    std::ostringstream errmsg;\n    errmsg << tx.GetHash().ToString() << \":\" <<  input << \" - \";\n    \n    //Store results to return\n    vector<char *> values;\n    \n    if (input >= tx.vin.size()) {\n        errmsg << \" the input does not exist.\";\n        throw runtime_error(errmsg.str());\n    }\n    \n    \n    unsigned int i = input;\n    vector<vector<unsigned char> > stack;\n    \n    //Fill stack with scriptsig + pub key\n    EvalScript(stack, tx.vin[i].scriptSig, tx, i, false, 0);\n    \n    CTxIn& txin = tx.vin[i];\n    CTransaction txprev;\n    uint256 hashBlock = 0;\n    if (!GetTransaction(txin.prevout.hash, txprev, hashBlock, true)) {\n        errmsg << \" cannot find this transaction. Remember to use -txindex.\";\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg.str());\n    }\n\n    const CTxOut& txout = txprev.vout[txin.prevout.n];\n    \n    vector<unsigned char> vchSig;\n    vector<unsigned char> vchPubKey;\n    vchSig= stack.front();\n    vchPubKey = stack.back();\n    \n    std::string t(vchSig.begin(), vchSig.end());\n    \n    //Evaluate signature and public key\n    EvalScript(stack, txout.scriptPubKey, tx, i, false, 0);\n    \n    \n    //Get script instructions\n    CScript scriptSig(tx.vin[i].scriptSig.begin(), tx.vin[i].scriptSig.end());\n    CScript scriptPubKey(txout.scriptPubKey.begin(), txout.scriptPubKey.end());\n    \n    //Remove signature from the script - cannot sign a signature\n    scriptPubKey.FindAndDelete(CScript(vchSig));\n    \n    //Get signature hash\n    uint256 sighash = SignatureHash(scriptPubKey, tx, i, 1);\n    \n    //Time to get the R & S values\n    ECDSA_SIG *sig = ECDSA_SIG_new();\n    const unsigned char *sigbuf = &vchSig[0];\n    d2i_ECDSA_SIG(&sig, &sigbuf, vchSig.size()\n                  );\n    \n    // Lets make sure we found a signature (this implementation relies on script-to-pubkey-hash.. can be extended to multi-sig and p2sh)\n    if(sig == NULL) {\n        errmsg << \" signature cannot be found.\";\n        \n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg.str());\n    }\n    \n    char *r = BN_bn2dec(sig->r);\n    char *s = BN_bn2dec(sig->s);\n    \n    values.push_back(r);\n    values.push_back(s);\n    \n    if(needk) {\n\n        //Get private key\n        const CKeyStore& keystore = *pwalletMain;\n        CKey key;\n        CKeyID keyID = CPubKey(vchPubKey).GetID();\n        if(!keystore.GetKey(keyID, key)) {\n            errmsg << \" could not fetch the private key.\";\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg.str());\n        } else {\n            char *k = key.GetK((unsigned char*)&sighash, sizeof(sighash), r, s);\n            values.push_back(k);\n        }\n    }\n    \n    return values;\n}\n\nvoid hashlength(SHA_CTX *sha, size_t l)\n{\n    unsigned char b[2];\n    \n    OPENSSL_assert(l <= 0xffff);\n    b[0] = l >> 8;\n    b[1] = l&0xff;\n    SHA1_Update(sha, b, 2);\n}\n\n\nvoid hashstring(SHA_CTX *sha, const char *string)\n{\n    size_t l = strlen(string);\n    \n    hashlength(sha, l);\n    SHA1_Update(sha, string, l);\n}\n\nvoid hashbn(SHA_CTX *sha, const BIGNUM *bn)\n{\n    size_t l = BN_num_bytes(bn);\n    unsigned char *bin = (unsigned char*) malloc(l);\n    \n    hashlength(sha, l);\n    BN_bn2bin(bn, bin);\n    SHA1_Update(sha, bin, l);\n    OPENSSL_free(bin);\n}\n\nvoid hashpoint(const EC_GROUP *group, SHA_CTX *sha, const EC_POINT *point)\n{\n\n    BIGNUM *bn = BN_new();\n    BN_CTX *ctx = BN_CTX_new();\n    \n    //Convert EC_POINT to number\n    EC_POINT_point2bn(group, point, POINT_CONVERSION_UNCOMPRESSED, bn, ctx);\n    \n    //Get size of EC_POINT\n    size_t l = BN_num_bytes(bn);\n    unsigned char *bin = (unsigned char*) malloc(l);\n    \n    //Create hash for a given point\n    hashlength(sha, l);\n    \n    BN_bn2bin(bn, bin);\n\n    SHA1_Update(sha, bin, l);\n\n    OPENSSL_free(bin);\n}\n\nValue calculateSharedKey(char *k, char *x, char *y)\n{\n    /*\n     * Using our secret 'k' and Bob's (x,y) co-ordinates\n     * we are going to generate a shared secret using the formula:\n     * ---> k . (x',y') = (x'',y'')\n     *\n     */\n    BIGNUM *alice_k = NULL;\n    BIGNUM *bob_x = NULL;\n    BIGNUM *bob_y = NULL;\n    BN_CTX *ctx = BN_CTX_new();\n    EC_POINT *bob_point = NULL;\n    EC_POINT *result_point = NULL;\n    BIGNUM *result_x = BN_new();\n    BIGNUM *result_y = BN_new();\n    \n    //Converting alice and bob's values to OpenSSL bignums\n    BN_dec2bn(&alice_k, k);\n    BN_dec2bn(&bob_x, x);\n    BN_dec2bn(&bob_y, y);\n    \n    //Sort out the EC environment\n    EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n    const EC_GROUP *group;\n    group = EC_KEY_get0_group(pkey);\n    \n    //Lets make sure we are using compressed co-ordinates\n    if(BN_is_zero(bob_y) || BN_is_one(bob_y)) {\n        \n        //Set bob's point on the curve\n        bob_point = EC_POINT_new(group);\n        EC_POINT_set_compressed_coordinates_GFp(group, bob_point,\n                                                bob_x,\n                                                atoi(y), NULL);\n        \n        result_point = EC_POINT_new(group);\n        \n        //Scalar multiplication with Alice's k and Bob's point on the curve\n        EC_POINT_mul(group, result_point, NULL, bob_point, alice_k, ctx);\n        \n        //Lets get the results\n        EC_POINT_get_affine_coordinates_GFp(group, result_point, result_x, result_y, ctx);\n        \n        unsigned char md[SHA_DIGEST_LENGTH];\n        SHA_CTX sha;\n        \n        SHA1_Init(&sha);\n        \n        hashbn(&sha, result_x);\n        \n        BIGNUM *h = BN_new();\n        \n        SHA1_Final(md, &sha);\n        BN_bin2bn(md, SHA_DIGEST_LENGTH, h);\n        \n        return BN_bn2dec(h);\n        \n    }\n    \n    return 0;\n    \n}\n\n\n/* h=hash(g, g^v, g^x, name) */\nvoid zkp_hash(const EC_GROUP *group, char *p, char *a, char *b, char *g, char *order, BIGNUM *h, EC_POINT *gw, EC_POINT *gv,  BIGNUM *x_coordinate)\n{\n    unsigned char md[SHA_DIGEST_LENGTH];\n    SHA_CTX sha;\n    \n    SHA1_Init(&sha);\n    \n    std::stringstream ss;\n    ss << p << a << b << g << order;\n    \n    std::string s = ss.str();\n    \n    char *full = new char[s.length() + 1];\n    strcpy(full, s.c_str());\n    \n    //Get hash for each parameter and combine them\n    hashstring(&sha, full);\n    \n    hashpoint(group, &sha, gw);\n    \n    hashbn(&sha, x_coordinate);\n    \n    hashpoint(group, &sha, gv);\n\n    SHA1_Final(md, &sha);\n    BN_bin2bn(md, SHA_DIGEST_LENGTH, h);\n}\n\n/*\n * Prove knowledge of x\n * Note that p->gx has already been calculated\n */\nBIGNUM *generate_zkp(const EC_GROUP *group, char *p, char *a, char *b, const EC_POINT *g, BIGNUM *v, EC_POINT *gv, BIGNUM *w, EC_POINT *gw, BIGNUM *k, BIGNUM * x_coordinate, BIGNUM *order, BIGNUM *h, const char *txid, BN_CTX *ctx)\n{\n    BIGNUM *t = BN_new();\n    BIGNUM *temp_s = BN_new();\n    BIGNUM *bn_g = BN_new();\n    BIGNUM *bn_order = BN_new();\n\n    EC_GROUP_get_order(group, bn_order, ctx);\n    \n    EC_POINT_point2bn(group, g, POINT_CONVERSION_UNCOMPRESSED, bn_g, ctx);\n    \n    char *char_g = BN_bn2dec(bn_g);\n    char *char_order = BN_bn2dec(bn_order);\n    \n    /* h=hash... */\n    zkp_hash(group, p, a, b, char_g, char_order, h, gw, gv, x_coordinate);\n    \n    /* s = v - w*h */\n    BN_mod_mul(t, w, h, order, ctx);\n    \n    BN_mod_sub(temp_s, v, t, order, ctx);\n    \n    \n    \n    return temp_s;\n\n}\n\nint verify_zkp(const EC_GROUP *group, char *p, char *a, char *b, const EC_POINT *g, EC_POINT *gw, EC_POINT *gv, BIGNUM *x_coordinate, BIGNUM *s, const char *txid,\n                      BN_CTX *ctx)\n{\n    BIGNUM *h = BN_new();\n    BIGNUM *bn_g = BN_new();\n    BIGNUM *bn_order = BN_new();\n    \n    EC_GROUP_get_order(group, bn_order, ctx);\n    \n    EC_POINT_point2bn(group, g, POINT_CONVERSION_UNCOMPRESSED, bn_g, ctx);\n    \n    char *char_g = BN_bn2dec(bn_g);\n    char *char_order = BN_bn2dec(bn_order);\n    \n    EC_POINT *t1 = EC_POINT_new(group);\n    EC_POINT *t2 = EC_POINT_new(group);\n    EC_POINT *t3 = EC_POINT_new(group);\n    int ret = 0;\n    \n    zkp_hash(group, p, a, b, char_g, char_order, h, gw, gv, x_coordinate);\n    \n    //Remember, we are proving knowledge of r - lets make sure rG is not a point at infinity\n    if(EC_POINT_is_at_infinity(group, gw) == 1) {\n        return ret;\n    }\n    \n    //Next lets make sure the x and y co-ordinates of rG are in Fq\n    \n    //Lets make sure its on the curve\n    if(EC_POINT_is_on_curve(group, gw, ctx) == 0) {\n        return ret;\n    }\n    \n    //std::cout << \"H:\" << BN_bn2dec(h) << endl;\n    \n    /* t1 = g^s */\n    EC_POINT_mul(group, t1, NULL, g, s, ctx);\n    \n    /* t2 = (g^w)^h = g^{hr} */\n    EC_POINT_mul(group, t2, NULL, gw, h, ctx);\n    \n    \n    //BN_mod_exp(t2, p->gx, h, ctx->p.p, ctx->ctx);\n    /* t3 = t1 + t2 = g^{hr} * g^b = g^{hr+b} = g^w (allegedly) */\n    EC_POINT_add(group, t3, t1, t2, ctx);\n    \n    /* verify t3 == g^v */\n    if(EC_POINT_cmp(group, t3, gv, ctx) == 0) {\n        ret = 1;\n    }\n\n    \n    return ret;\n}\n\n// Look at the example function ZKPTest\nchar * getyaksecret(char * p_gw, char *p_gv, char *p_gk, char *p_s, char *p_k, char *p_w, char *p_txid, char *x_coordinate) {\n    \n    Value res;\n    \n    //Expecting: g^v, g^w, g^k, s, txid, r, k\n    BIGNUM *bn_gw = BN_new();\n    BIGNUM *bn_gv = BN_new();\n    BIGNUM *bn_gk = BN_new();\n    BIGNUM *s = BN_new();\n    BIGNUM *w = BN_new();\n    BIGNUM *k = BN_new();\n    BIGNUM *order = BN_new();\n    BIGNUM *bn_x_coordinate = BN_new();\n    BN_CTX *ctx = BN_CTX_new();\n    \n    //Sort out the EC environment\n    EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n    const EC_GROUP *group;\n    group = EC_KEY_get0_group(pkey);\n    \n    //Get generator\n    const EC_POINT *g = EC_GROUP_get0_generator(group);\n    \n    //Get points ready\n    EC_POINT *gw = EC_POINT_new(group);\n    EC_POINT *gv = EC_POINT_new(group);\n    EC_POINT *gk = EC_POINT_new(group);\n    \n    //Get all parameters\n    BN_dec2bn(&bn_gw, p_gw);\n    BN_dec2bn(&bn_gv,  p_gv);\n    BN_dec2bn(&bn_gk, p_gk);\n    BN_dec2bn(&s, p_s);\n    BN_dec2bn(&k,  p_k);\n    BN_dec2bn(&w, p_w);\n    BN_dec2bn(&bn_x_coordinate, x_coordinate);\n    \n    //Convert BIGNUM to EC_POINT\n    EC_POINT_bn2point(group, bn_gw, gw, ctx);\n    EC_POINT_bn2point(group, bn_gv, gv, ctx);\n    EC_POINT_bn2point(group, bn_gk, gk, ctx);\n    \n    //Get curve details for zero knowledge proof\n    BIGNUM *p = BN_new();\n    BIGNUM *a = BN_new();\n    BIGNUM *b = BN_new();\n    \n    EC_GROUP_get_curve_GFp(group, p, a, b, ctx);\n    \n    char *char_p = BN_bn2dec(p);\n    char *char_a = BN_bn2dec(a);\n    char *char_b = BN_bn2dec(b);\n\n    //Verify ZKP provided\n    if(verify_zkp(group, char_p, char_a, char_b, g, gw, gv, bn_x_coordinate, s, p_txid, ctx)) {\n        \n        //Prepare to start generating shared secret\n        EC_POINT *t1 = EC_POINT_new(group);\n        BIGNUM *t2 = BN_new();\n        EC_POINT *t3 = EC_POINT_new(group);\n        \n        //t1 = (g^v' . g^k');\n        EC_POINT_add(group, t1, gw, gk, ctx);\n        \n        //t2 = w+k\n        BN_mod_add(t2, w, k, order, ctx);\n        \n        //t3 = (g^v' . g^k')\n        EC_POINT_mul(group, t3, NULL, t1, t2, ctx);\n        \n        BIGNUM *x1 = BN_new();\n        BIGNUM *y1 = BN_new();\n        EC_POINT_get_affine_coordinates_GFp(group, t3, x1, y1, ctx);\n        \n        unsigned char md[SHA_DIGEST_LENGTH];\n        SHA_CTX sha;\n        \n        SHA1_Init(&sha);\n        \n        hashbn(&sha, x1);\n        \n        BIGNUM *fin = BN_new();\n        \n        SHA1_Final(md, &sha);\n        BN_bin2bn(md, SHA_DIGEST_LENGTH, fin);\n        \n        return BN_bn2dec(fin);\n    } else {\n    \n        throw runtime_error(\"Zero knowledge proof provided by your partner was not valid\");\n    }\n    \n}\n\n// Look at the example function ZKPTest\nvector<char *> getyakzkp(char *txid_a, char *a_input, char *txid_b, char *b_input, int print) {\n    \n    Value res;\n\n    vector<char *> results;\n    \n    //Assume first input of transaction\n    unsigned int first_input = 0;\n    first_input = atoi(a_input);\n    unsigned int second_input = 0;\n    second_input = atoi(a_input);\n        \n    //Get transaction ID from parameter\n    uint256 hash = ParseHashV(txid_a, \"parameter 1\");\n    uint256 hash_b = ParseHashV(txid_b, \"parameter 2\");\n    \n    //Find transaction in client\n    CTransaction tx;\n    uint256 hashBlock = 0;\n    if (!GetTransaction(hash, tx, hashBlock, true))\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"No information available about transaction\");\n    \n    //Returns r,s, optional: k\n    vector<char *> first_tx = getsignaturevalues(tx, first_input, true);\n    \n    //Find transaction in client\n    CTransaction tx_b;\n    hashBlock = 0;\n    if (!GetTransaction(hash_b, tx_b, hashBlock, true))\n        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"No information available about transaction\");\n    \n    \n    //Returns r,s, optional: k\n    vector<char *> second_tx = getsignaturevalues(tx_b, second_input, false);\n    \n    //Do we have K?\n    if(first_tx.size() == 3) {\n        \n        //Sort out the EC environment\n        EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n        const EC_GROUP *group;\n        group = EC_KEY_get0_group(pkey);\n        \n        //Get generator\n        const EC_POINT *g = EC_GROUP_get0_generator(group);\n        \n        //Get order\n        BN_CTX *ctx = BN_CTX_new();\n        BIGNUM *order = BN_new();\n        EC_GROUP_get_order(group, order, ctx);\n        \n        //Get K\n        BIGNUM *k = BN_new();\n        BN_dec2bn(&k, first_tx[2]);\n\n        //Get g^k\n        EC_POINT *gk = EC_POINT_new(group);\n        \n        EC_POINT_mul(group, gk, k, NULL, NULL, ctx);\n        \n        /*\n         * Get our estimated public key (x,+).\n         */\n        \n        BIGNUM *estimated_r = BN_new();\n        \n        char *compressed_y = \"1\";\n        \n        BN_dec2bn(&estimated_r,first_tx[0]);\n\n        \n        EC_POINT *estimated_compressed = EC_POINT_new(group);\n        EC_POINT_set_compressed_coordinates_GFp(group, estimated_compressed,\n                                                estimated_r,\n                                                atoi(compressed_y), NULL);\n \n        BIGNUM *actual_y = BN_new();\n        BIGNUM *actual_x = BN_new();\n        BIGNUM *estimated_y = BN_new();\n        BIGNUM *estimated_x = BN_new();\n        EC_POINT_get_affine_coordinates_GFp(group, estimated_compressed, estimated_x, estimated_y, ctx);\n        EC_POINT_get_affine_coordinates_GFp(group, gk, actual_x, actual_y, ctx);\n        \n        //If they are different - means default gk is Map(x,+) - we want Map(x,-)\n        if(BN_cmp(estimated_y, actual_y) == 0) {\n            //No worries TODO: Fix\n        } else {\n            BN_set_negative(k, 1);\n            \n            gk = estimated_compressed;\n        }\n    \n        /*\n         * Let's get an estimated public key for Bob\n         */\n        \n        BIGNUM *r_b = BN_new();\n        BN_dec2bn(&r_b, second_tx[0]);\n        \n        EC_POINT *bob_estimated_compressed = EC_POINT_new(group);\n        EC_POINT_set_compressed_coordinates_GFp(group, bob_estimated_compressed,\n                                                r_b,\n                                                atoi(compressed_y), NULL);\n        \n        BIGNUM *partner_gk = BN_new();\n        EC_POINT_point2bn(group, bob_estimated_compressed, POINT_CONVERSION_UNCOMPRESSED, partner_gk, ctx);\n        \n        //Get curve details for zero knowledge proof\n        BIGNUM *p = BN_new();\n        BIGNUM *a = BN_new();\n        BIGNUM *b = BN_new();\n        \n        EC_GROUP_get_curve_GFp(group, p, a, b, ctx);\n        \n        char *char_p = BN_bn2dec(p);\n        char *char_a = BN_bn2dec(a);\n        char *char_b = BN_bn2dec(b);\n        \n        /*\n         * NOW START THE PROTOCOL\n         */\n        \n        //Generate random v and w\n        BIGNUM *w = BN_new();\n        BN_rand_range(w, order);\n        \n        BIGNUM *v = BN_new();\n        BN_rand_range(v, order);\n        \n        //Get g^v and g^w\n        EC_POINT *gw = EC_POINT_new(group);\n        EC_POINT_mul(group, gw, w, NULL, NULL, ctx);\n        \n        EC_POINT *gv = EC_POINT_new(group);\n        EC_POINT_mul(group, gv, v, NULL, NULL, ctx);\n        \n        //Get h and s\n        BIGNUM *s = BN_new();\n        BIGNUM *h = BN_new();\n        \n        //Create zero knowledge proof\n        s = generate_zkp(group, char_p, char_a, char_b, g, v, gv, w, gw, k, estimated_r, order, h, hash.ToString().c_str(), ctx);\n\n        BIGNUM *bn_gw = BN_new();\n        BIGNUM *bn_gv = BN_new();\n        BIGNUM *bn_gk = BN_new();\n        \n        EC_POINT_point2bn(group, gw, POINT_CONVERSION_COMPRESSED, bn_gw, ctx);\n        EC_POINT_point2bn(group, gv, POINT_CONVERSION_COMPRESSED, bn_gv, ctx);\n        EC_POINT_point2bn(group, gk, POINT_CONVERSION_COMPRESSED, bn_gk, ctx);\n    \n        results.push_back(BN_bn2dec(bn_gw)); //to prove little 'w'\n        results.push_back(BN_bn2dec(bn_gv)); //random factor in zkp\n        results.push_back(BN_bn2dec(s)); //zkp\n        results.push_back(BN_bn2dec(k)); //my secret\n        results.push_back(BN_bn2dec(w)); //my little 'w' from zkp\n        results.push_back(BN_bn2dec(partner_gk));\n        results.push_back(BN_bn2dec(estimated_r));\n    \n        \n        return results;\n        \n    }\n    \n    throw runtime_error(\"Your wallet does not have the private key.\");\n}\n\nValue zkptest (const Array& params, bool fHelp) {\n    vector<char *> alice_zkp;\n    vector<char *> bob_zkp;\n    vector<char *> alice_gets_secret;\n    vector<char *> bob_gets_secret;\n    \n    /* \n     * These are hard-coded transaction ID's... \n     * You will NEED to change these to ID's which are also in\n     * your wallet... Just demonstrates how to do the YAK protocol.\n     */\n    alice_zkp = getyakzkp(\"2dac21b624821f6a0c41ec030ed5b03a10e4bb9df2627d16f84dbe364b709647\", \"0\", \"348abac7317f5afb8af32c54d3504c53cc973948322cb5be301e8ca47bc8de85\", \"0\", 1);\n    bob_zkp = getyakzkp(\"348abac7317f5afb8af32c54d3504c53cc973948322cb5be301e8ca47bc8de85\", \"0\", \"2dac21b624821f6a0c41ec030ed5b03a10e4bb9df2627d16f84dbe364b709647\", \"0\", 0);\n    \n    /* Array returned by getyakzkp...\n    * [0] = g^w\n    * [1] = g^v\n    * [2] = s\n    * [3] = k\n    * [4] = w\n    * [5] = partners compressed key\n    * [6] = x co-ordinate from sig\n    */\n    \n    // Use Bob's g^w, g^v, s, and his transaction ID. \n    // Use Alice's secret random nonce 'k', 'w'.\n    return getyaksecret(bob_zkp[0], bob_zkp[1], alice_zkp[5], bob_zkp[2], alice_zkp[3], alice_zkp[4], \"348abac7317f5afb8af32c54d3504c53cc973948322cb5be301e8ca47bc8de85\", bob_zkp[6]);\n}\n\nValue getdiffiesecret(const Array& params, bool fHelp)\n{\n    \n    Value res;\n\n\tif (fHelp || (params.size() != 2 && params.size() != 4))\n\t\tthrow runtime_error(\n\t\t\t\t\t\t\t\"getdiffiesecret \\\"txid txid\\\"\\n\"\n\t\t\t\t\t\t\t\"\\nGenerate a shared secret between your transaction and a partners.\\n\"\n\t\t\t\t\t\t\t\"\\nArguments:\\n\"\n\t\t\t\t\t\t\t\"1. \\\"txid_1\\\"     (string) Transaction ID \\n\"\n\t\t\t\t\t\t\t\"2. \\\"txid_2\\\"     (string) Transaction ID \\n\"\n\t\t\t\t\t\t\t\"3. \\\"input_txid_1\\\" (optional) Input number for first transaction \\n\"\n\t\t\t\t\t\t\t\"4. \\\"input_txid_2\\\" (optional) Input number for second transaction \\n\"\n\t\t\t\t\t\t\t\"\\nResult: (x,y) co-ordinate\"\n\t\t\t\t\t\t\t);\n    \n\tunsigned int first_input = 0;\n\tunsigned int second_input = 0;\n    \n\t/*\n\t * Two parameters = Diffie\n\t * Four parameters = Diffie\n\t *\n\t */\n\tif(params.size() == 4) {\n\t\tfirst_input = atoi(params[2].get_str().c_str());\n\t\tsecond_input = atoi(params[3].get_str().c_str());\n\t}\n    \n    \n\t//Get first transaction\n\tuint256 hash = ParseHashV(params[0], \"parameter 1\");\n    \n\tCTransaction tx;\n\tuint256 hashBlock = 0;\n\tif (!GetTransaction(hash, tx, hashBlock, true))\n\t\tthrow JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"No information available about transaction\");\n    \n\t//Returns r,s, optional: k\n\tvector<char *> first_tx = getsignaturevalues(tx, first_input, true);\n    \n\t//Get second transaction\n\thash = ParseHashV(params[1], \"parameter 2\");\n    \n\tif (!GetTransaction(hash, tx, hashBlock, true))\n\t\tthrow JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"No information available about transaction\");\n    \n\t//Returns r,s, optional: k\n\tvector<char *> second_tx = getsignaturevalues(tx, second_input, false);\n    \n\tif(first_tx.size() == 3) {\n\t\tres = calculateSharedKey(first_tx[2], second_tx[0], \"0\");\n\t} else if(second_tx.size() == 3) {\n\t\tres = calculateSharedKey(second_tx[2], first_tx[0], \"0\");\n\t}\n\n    return res;\n}\n\n", "meta": {"hexsha": "8b731fadbe867791e4b1e65c1cbc4fb27532b5b4", "size": 53109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rpcrawtransaction.cpp", "max_stars_repo_name": "stonecoldpat/Authenticated-Key-Exchange-Over-Bitcoin", "max_stars_repo_head_hexsha": "d39e4f42e2e914ddf7120c76d02e201a49c58229", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T12:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-02T12:39:49.000Z", "max_issues_repo_path": "src/rpcrawtransaction.cpp", "max_issues_repo_name": "stonecoldpat/Authenticated-Key-Exchange-Over-Bitcoin", "max_issues_repo_head_hexsha": "d39e4f42e2e914ddf7120c76d02e201a49c58229", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rpcrawtransaction.cpp", "max_forks_repo_name": "stonecoldpat/Authenticated-Key-Exchange-Over-Bitcoin", "max_forks_repo_head_hexsha": "d39e4f42e2e914ddf7120c76d02e201a49c58229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-21T18:41:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-21T18:41:10.000Z", "avg_line_length": 35.9573459716, "max_line_length": 230, "alphanum_fraction": 0.5637462577, "num_tokens": 14236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.018264277683886602, "lm_q1q2_score": 0.005492900765984074}}
{"text": "// ======================================================================\n/*!\n * \\file NFmiLocation.cpp\n * \\brief Implementation of class NFmiLocation\n */\n// ======================================================================\n/*!\n * \\class NFmiLocation\n *\n * An NFmiLocation instance is an object with a name and geographic\n * coordinates. The name service is provided by the base class\n * NFmiIndividual, NFmiLocation adds coordinate properties.\n *\n * The class is old fashioned and should not be used. The class also\n * contains many methods which would be better off outside the class\n * as namespace members, including all the astronomical methods.\n * Inheritance from NFmiIndividual should be removed and a name\n * variable provided instead.\n *\n */\n// ======================================================================\n\n#include \"NFmiLocation.h\"\n#include \"NFmiAngle.h\"\n#include \"NFmiGeoTools.h\"\n#include \"NFmiMetTime.h\"\n#include <boost/functional/hash.hpp>\n#include <fmt/format.h>\n#include <macgyver/Exception.h>\n#include <algorithm>\n#include <fstream>\n\nusing namespace std;\n\nconst double kRefractCorr = -0.0145386;  // See comments in the CalcSunriseOrSunsetTime()\n\n// ----------------------------------------------------------------------\n/*!\n * Equality comparison\n *\n * \\param theLocation The location to compare with\n * \\return True if the locations are equal\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLocation::operator==(const NFmiLocation &theLocation) const\n{\n  try\n  {\n    return (GetName() == theLocation.GetName() && itsLatlon == theLocation.itsLatlon);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Less than comparison\n *\n * \\param theLocation The location to compare with\n * \\return True if this is smaller than theLocation\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLocation::operator<(const NFmiLocation &theLocation) const\n{\n  try\n  {\n    if (GetName() != theLocation.GetName())\n      return GetName() < theLocation.GetName();\n\n    if (itsLatlon.Y() != theLocation.itsLatlon.Y())\n      return itsLatlon.Y() < theLocation.itsLatlon.Y();\n\n    return itsLatlon.X() < theLocation.itsLatlon.X();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theSortable Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLocation::IsEqual(const NFmiSortable &theSortable) const\n{\n  try\n  {\n    return (itsLatlon.Y() == (static_cast<const NFmiLocation *>(&theSortable))->itsLatlon.Y() &&\n            itsLatlon.X() == (static_cast<const NFmiLocation *>(&theSortable))->itsLatlon.X());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theSortable Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nbool NFmiLocation::IsLessThan(const NFmiSortable &theSortable) const\n{\n  try\n  {\n    return (itsLatlon.Y() > (static_cast<const NFmiLocation *>(&theSortable))->itsLatlon.Y() &&\n            itsLatlon.X() > (static_cast<const NFmiLocation *>(&theSortable))->itsLatlon.X());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Assignment operator\n *\n * \\param theLocation The object being copied\n * \\return The object assigned to\n * \\todo Should protect from self assignment\n */\n// ----------------------------------------------------------------------\n\nNFmiLocation &NFmiLocation::operator=(const NFmiLocation &theLocation)\n{\n  try\n  {\n    if (this != &theLocation)\n    {\n      NFmiIndividual::operator=(theLocation);\n      itsLatlon = theLocation.itsLatlon;\n    }\n    return *this;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theLocation Undocumented\n */\n// ----------------------------------------------------------------------\n\nvoid NFmiLocation::SetLocation(const NFmiLocation &theLocation)\n{\n  try\n  {\n    itsLatlon = theLocation.itsLatlon;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * [Venäläinen: lisenssiaattitutkimus ANNEX (A4)]\n * The time given as a parameter must be a local solar time.\n * These calculations of a declination angle of the Sun does not give very accurate\n * estimations. May be the inaccuracy is mostly caused because of inaccurate\n * calculation of the yearAngle (a measure to Earths circulation around the Sun).\n * This inaccuracy causes an inaccurate elevation angle. But the calculation\n * of the elevation angle uses also the method NFmiLocation::AtzimuthAngle(),\n * where calculates a correction term, which quite successfully compensates\n * errors of the elevation angle.\n *\n * \\param theSolarTime a local solar time\n * \\return a declination angle in radians\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::CalcDeclinationAngle(const NFmiTime &theSolarTime)\n{\n  try\n  {\n    double yearAngle =\n        2.0 * kPii *\n        (theSolarTime.GetJulianDay() +\n         (theSolarTime.GetHour() + theSolarTime.GetMin() / 60. + theSolarTime.GetSec() / 3600.) /\n             24.  // 17.09.2002/Viljo adds the seconds\n         - 1.0) /\n        365.;\n    return (0.006918 - 0.399912 * cos(yearAngle) + 0.070257 * sin(yearAngle) -\n            0.006758 * cos(2 * yearAngle) + 0.000907 * sin(2 * yearAngle) -\n            0.002697 * cos(3 * yearAngle) + 0.00148 * sin(3 * yearAngle));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * The time given as a parameter must be a local solar time. Here the\n * atzimuth angle = 0 when the Sun is in the North.\n * There's also an odd correction term anEqualizerTerm (Laura Thölix:\n * pro gradu, page 16), which perhaps somehow compensates the inaccurate\n * calculation of the yearAngle (a measure to the Earths circulaton around the Sun).\n * See also comments of the method NFmiLocation::CalcDeclinationAngle().\n *\n * \\param theSolarTime a local solar time for this NFmiLocation\n * \\return the atzimuth angle in radians\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::CalcAtzimuthAngle(const NFmiTime &theSolarTime)\n{\n  try\n  {\n    double hour =\n        theSolarTime.GetHour() + theSolarTime.GetMin() / 60. + theSolarTime.GetSec() / 3600.;\n    double yearAngle = 2.0 * kPii * (theSolarTime.GetJulianDay() + hour / 24. - 1.0) / 365.;\n    double anEqualizerTerm = (0.0172 + 0.4281 * cos(yearAngle) - 7.3515 * sin(yearAngle) -\n                              3.3495 * cos(2. * yearAngle) - 9.3619 * sin(2. * yearAngle)) /\n                             60.;\n    return (hour + anEqualizerTerm) * kPii / 12.;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * [Venäläinen: lisenssiaattitutkimus ANNEX (A3)]\n * These calculations of a elevation angle of the Sun does not give very\n * accurate estimations. This inaccuracy is partly caused by\n * the inaccurate calculations of declination angle.\n * The time given as a parameter must be a local solar time.\n *\n * \\param theSolarTime a local solar time\n * \\return a elevation angle in radians\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::ElevationAngleFromSolarTime(const NFmiTime &theSolarTime)\n{\n  try\n  {\n    return asin(sin(CalcDeclinationAngle(theSolarTime)) * sin(GetLatitude() * kPii / 180.) -\n                cos(CalcDeclinationAngle(theSolarTime)) * cos(GetLatitude() * kPii / 180.) *\n                    cos(CalcAtzimuthAngle(theSolarTime)));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theTime, UTC-time\n * \\return a declination angle in degrees\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::DeclinationAngle(const NFmiMetTime &theTime)\n{\n  try\n  {\n    NFmiTime solarTime(LocalSolarTime(theTime));\n    return 180. / kPii * CalcDeclinationAngle(solarTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theTime Undocumented\n * \\return an elevation angle in degrees\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::ElevationAngle(const NFmiMetTime &theTime)\n{\n  try\n  {\n    NFmiTime solarTime(LocalSolarTime(theTime));\n    return 180. / kPii * ElevationAngleFromSolarTime(solarTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theTime, UTC-time\n * \\return an atzimuth angle in degrees\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::AtzimuthAngle(const NFmiMetTime &theTime)\n{\n  try\n  {\n    NFmiTime solarTime(LocalSolarTime(theTime));\n    return 180. / kPii * CalcAtzimuthAngle(solarTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * theTime given as a parameter must be an UTC-time (= a solar time\n * in Greenwich, where itsLongitude = 0). The transformation is\n *\n *\t\t+4 min/1 deg towards east from Greenwich\n *\n * \\param theTime Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiTime NFmiLocation::LocalSolarTime(const NFmiMetTime &theTime)\n{\n  try\n  {\n    NFmiTime t(static_cast<NFmiTime>(theTime));\n    t.ChangeBySeconds(long(240 * itsLatlon.X()));\n    return t;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * This conversion is reverse to the LocalSolarTime().\n *\n * \\param theSolarTime Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiMetTime NFmiLocation::UtcTimeFromSolarTime(const NFmiTime &theSolarTime)\n{\n  try\n  {\n    NFmiMetTime t(theSolarTime, 1);\n    t.ChangeBySeconds(long(-240 * itsLatlon.X()));\n    if (t.GetSec() > 29)\n      t.ChangeByMinutes(1);\n    t.SetSec(0);  // NFmiMetTime does not have seconds\n    return t;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * In ordinary case returns is the time of sunrise to the current day\n * (the day gets from the local solar time, see comments e.g.in the\n *  method NextTimeOfSunset).\n *\n * If case of the\n *\n *   - polar night:   returns the NEXT sunrise time\n *   - midnight sun:  returns the LAST sunrise time\n *\n * and the bool& isCurrentDay sets to false.\n *\n * \\param theTime, UTC-time\n * \\param isCurrentDay, true if the returnig time fits into the current day, others false\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiMetTime NFmiLocation::TimeOfSunrise(const NFmiMetTime &theTime, bool &isCurrentDay)\n{\n  try\n  {\n    bool isMidNightSun, isPolarNight;\n    NFmiMetTime sunrise = LastTimeOfSunrise(theTime, isMidNightSun, isPolarNight);\n    if (isPolarNight)\n      sunrise = NextTimeOfSunrise(theTime, isMidNightSun, isPolarNight);\n    isCurrentDay = !isMidNightSun && !isPolarNight;\n    return sunrise;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * In ordinary case returns the time of sunset to the current day\n * (the day gets from the local solar time, see comments e.g.in the\n *  method NextTimeOfSunset).\n *\n * If case of the\n *\n *\t\t- polar night:   returns the LAST sunset time.\n *\t\t- midnight sun:  returns the NEXT sunset time.\n *\n * and the bool& isCurrentDay sets to false.\n *\n * \\param theTime Undocumented\n * \\param isCurrentDay, true if the returnig time fits into the current day, others false\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiMetTime NFmiLocation::TimeOfSunset(const NFmiMetTime &theTime, bool &isCurrentDay)\n{\n  try\n  {\n    bool isMidNightSun, isPolarNight;\n    NFmiMetTime sunset = NextTimeOfSunset(theTime, isMidNightSun, isPolarNight);\n    if (isPolarNight)\n      sunset = LastTimeOfSunset(theTime, isMidNightSun, isPolarNight);\n    isCurrentDay = !isMidNightSun && !isPolarNight;\n    return sunset;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Here calculates the time of the next sunset. First calculates the local solar\n * time from the UTC-time theTime. The use of the solarTime makes sure that\n * calculations begins from the correct day. In case of the polar night or the\n * midnight sun finds first the next day, when the sunset will happen.\n * Before the calculation of the time of the sunset the solarTime must be set\n * to the time 00:00.\n *\n * \\param theTime Undocumented\n * \\param isMidNightSun Undocumented\n * \\param isPolarNight Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiMetTime NFmiLocation::NextTimeOfSunset(const NFmiMetTime &theTime,\n                                           bool &isMidNightSun,\n                                           bool &isPolarNight)\n{\n  try\n  {\n    NFmiTime solarTime = LocalSolarTime(theTime);\n    solarTime.SetHour(12);\n    solarTime.SetMin(0);\n    solarTime.SetSec(0);\n    isMidNightSun = false;\n    isPolarNight = false;\n    if (ElevationAngleFromSolarTime(solarTime) < kRefractCorr)\n    {\n      // polar night\n      isPolarNight = true;\n      do\n      {\n        solarTime.ChangeByDays(1);  // finds the next day of the sunset\n      } while (ElevationAngleFromSolarTime(solarTime) < kRefractCorr);\n      solarTime.ChangeByHours(12);  // next midnight\n    }\n    else\n    {\n      solarTime.ChangeByHours(12);  // next midnight\n      if (ElevationAngleFromSolarTime(solarTime) > kRefractCorr)\n      {\n        // midnight sun\n        isMidNightSun = true;\n        do\n        {\n          solarTime.ChangeByDays(1);  // finds the next day of the sunset\n        } while (ElevationAngleFromSolarTime(solarTime) > kRefractCorr);\n      }\n    }\n\n    CalcSunriseOrSunsetTime(solarTime);  // solarTime == 24:00\n    return UtcTimeFromSolarTime(solarTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Here calculates the time of the next sunrise. First calculates the local solar\n * time from the UTC-time theTime. The use of the solarTime makes sure that\n * calculations begins from the correct day. In case of the polar night or the\n * midnight sun finds first the next day, when the sunrise will happen.\n * Before the calculation of the time of the sunrise the solarTime must be set\n * to the time 12:00.\n *\n * \\param theTime Undocumented\n * \\param isMidNightSun Undocumented\n * \\param isPolarNight Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiMetTime NFmiLocation::NextTimeOfSunrise(const NFmiMetTime &theTime,\n                                            bool &isMidNightSun,\n                                            bool &isPolarNight)\n{\n  try\n  {\n    NFmiTime solarTime = LocalSolarTime(theTime);\n    solarTime.SetHour(12);\n    solarTime.SetMin(0);\n    solarTime.SetSec(0);\n    isMidNightSun = false;\n    isPolarNight = false;\n    if (ElevationAngleFromSolarTime(solarTime) < kRefractCorr)\n    {\n      // polar night\n      isPolarNight = true;\n      do\n      {\n        solarTime.ChangeByDays(1);  // finds the next day of the sunrise\n      } while (ElevationAngleFromSolarTime(solarTime) < kRefractCorr);\n    }\n    else\n    {\n      solarTime.ChangeByHours(12);  // next midnight\n      if (ElevationAngleFromSolarTime(solarTime) > kRefractCorr)\n      {\n        // midnight sun\n        isMidNightSun = true;\n        do\n        {\n          solarTime.ChangeByDays(1);  // finds the next day of the sunrise\n        } while (ElevationAngleFromSolarTime(solarTime) > kRefractCorr);\n      }\n      solarTime.SetHour(12);\n    }\n    CalcSunriseOrSunsetTime(solarTime);  // solarTime == 12:00\n    return UtcTimeFromSolarTime(solarTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Here calculates the time of the last sunset. First calculates the local solar\n * time from the UTC-time theTime. The use of the solarTime makes sure that\n * calculations begins from the correct day. In case of the polar night or the\n * midnight sun finds first the last day, when the sunset has happened.\n * Before the calculation of the time of the sunset the solarTime must be set\n * to the time 00:00.\n *\n * \\param theTime Undocumented\n * \\param isMidNightSun Undocumented\n * \\param isPolarNight Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiMetTime NFmiLocation::LastTimeOfSunset(const NFmiMetTime &theTime,\n                                           bool &isMidNightSun,\n                                           bool &isPolarNight)\n{\n  try\n  {\n    NFmiTime solarTime = LocalSolarTime(theTime);\n    solarTime.SetHour(12);\n    solarTime.SetMin(0);\n    solarTime.SetSec(0);\n    isMidNightSun = false;\n    isPolarNight = false;\n    if (ElevationAngleFromSolarTime(solarTime) < kRefractCorr)\n    {\n      // polar night\n      isPolarNight = true;\n      do\n      {\n        solarTime.ChangeByDays(-1);  // finds the last day of the sunset\n      } while (ElevationAngleFromSolarTime(solarTime) < kRefractCorr);\n      solarTime.ChangeByHours(12);  // midnight\n    }\n    else\n    {\n      solarTime.SetHour(0);  // previous midnight\n      if (ElevationAngleFromSolarTime(solarTime) > kRefractCorr)\n      {\n        // midnight sun\n        isMidNightSun = true;\n        do\n        {\n          solarTime.ChangeByDays(-1);  // finds the last day of the sunset\n        } while (ElevationAngleFromSolarTime(solarTime) > kRefractCorr);\n      }\n    }\n    CalcSunriseOrSunsetTime(solarTime);  // solarTime == 24:00\n    return UtcTimeFromSolarTime(solarTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Here calculates the time of the last sunrise. First calculates the local solar\n * time from the UTC-time theTime. The use of the solarTime makes sure that\n * calculations begins from the correct day. In case of the polar night or the\n * midnight sun finds first the last day, when the sunrise has happened.\n * Before the calculation of the time of the sunrise the solarTime must be set\n * to the time 12:00.\n *\n * \\param theTime Undocumented\n * \\param isMidNightSun Undocumented\n * \\param isPolarNight Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiMetTime NFmiLocation::LastTimeOfSunrise(const NFmiMetTime &theTime,\n                                            bool &isMidNightSun,\n                                            bool &isPolarNight)\n{\n  try\n  {\n    NFmiTime solarTime = LocalSolarTime(theTime);\n    solarTime.SetHour(12);\n    solarTime.SetMin(0);\n    solarTime.SetSec(0);\n    isMidNightSun = false;\n    isPolarNight = false;\n\n    if (ElevationAngleFromSolarTime(solarTime) < kRefractCorr)\n    {\n      // polar night\n      isPolarNight = true;\n      do\n      {\n        solarTime.ChangeByDays(-1);  // finds the last day of the sunrise\n      } while (ElevationAngleFromSolarTime(solarTime) < kRefractCorr);\n    }\n    else\n    {\n      solarTime.SetHour(0);  // previous midnight\n      if (ElevationAngleFromSolarTime(solarTime) > kRefractCorr)\n      {\n        // midnight sun\n        isMidNightSun = true;\n        do\n        {\n          solarTime.ChangeByDays(-1);  // finds the last day of the sunrise\n        } while (ElevationAngleFromSolarTime(solarTime) > kRefractCorr);\n      }\n      solarTime.SetHour(12);\n    }\n    CalcSunriseOrSunsetTime(solarTime);  // solarTime == 12:00\n    return UtcTimeFromSolarTime(solarTime);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n *\tThis protected method calculates time of sunrise or sunset.\n *\tBefore calling this method, the hour of the parameter time theSolarTime\n *  must be set to 12:00 or 24:00 - the first setting leads to the\n *  calculation\tof sunrise, the latter to sunset..\n *  Sunrise/sunset is considered to occur when the Sun's upper limb is\n *  35 arc minutes (0.583 degrees) below the horizon (refraction of the\n *  Earth's atmosphere). When the correction from the center to the upper\n *  limb of the Sun is taken into consideration, the total correction\n *  is around\n *\t\t\tkRefractCorr = -0.833 degrees\n *  Calculations of sunrise and sunset uses kRefractCorr instead of the\n *  null elevation angle due to the center of the Sun.\n *\n *  Next iterative searching of the sunrise or the sunset isn't sophisticated but\n *  simple. If the sunrise have to been found, backwards iteration begins from\n *  tempSolarTime = 12 and in case of sunset from  tempSolarTime = 24 (next midnight).\n *  Iterations time step is 1 hour and lenght 12 hours. When the hour of sunrise or\n *  sunset has been found, iterates minutes (forwards).\n *\n *\tSunrise: beginHour =12:00, stopHour = 23:00 (previous night)\n *\tSunset:  beginHour =00:00, stopHour = 11:00 (previous day)\n *\n * \\param theSolarTime Undocumented\n */\n// ----------------------------------------------------------------------\n\nvoid NFmiLocation::CalcSunriseOrSunsetTime(NFmiTime &theSolarTime)\n{\n  try\n  {\n    short stopHour = 23;\n    double angle1 = kFloatMissing, angle2 = kFloatMissing;\n    if (theSolarTime.GetHour() == 0)  // Sunset\n    {\n      stopHour = 11;\n      angle2 = -1 * kFloatMissing;\n      ;  // angle2 must have a negative initial value in case of sunset (XOR-checking)\n    }\n\n    while (theSolarTime.GetHour() != stopHour)\n    {\n      theSolarTime.ChangeByHours(-1);\n      angle1 = ElevationAngleFromSolarTime(theSolarTime);\n      if ((angle1 < kRefractCorr) ^ (angle2 < kRefractCorr))  // XOR\n      {\n        do\n        {\n          theSolarTime.ChangeByMinutes(1);\n          angle2 = ElevationAngleFromSolarTime(theSolarTime);\n          if ((angle1 < kRefractCorr) ^ (angle2 < kRefractCorr))  // XOR\n          {\n            if (fabs(angle1 + kRefractCorr) < fabs(angle2 + kRefractCorr))\n              theSolarTime.ChangeByMinutes(-1);  // rounding to a nearest minute\n            return;\n          }\n          angle1 = angle2;\n        } while (theSolarTime.GetMin() != 0);  // beginnig of the next hour is already handled\n      }\n      angle2 = angle1;\n    }\n    return;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n * \\todo Should return boost::shared_ptr\n */\n// ----------------------------------------------------------------------\n\nNFmiLocation *NFmiLocation::Clone() const\n{\n  try\n  {\n    return new NFmiLocation(*this);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n// ----------------------------------------------------------------------\n/*!\n * Write the object to the given output stream\n *\n * \\param file The output stream to write to\n * \\return The output stream written to\n */\n// ----------------------------------------------------------------------\n\nstd::ostream &NFmiLocation::Write(std::ostream &file) const\n{\n  try\n  {\n    file << fmt::format(\"{} {}\\n\", itsLatlon.X(), itsLatlon.Y());\n\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Read new object contents from the given input stream\n *\n * \\param file The input stream to read from\n * \\return The input stream read from\n */\n// ----------------------------------------------------------------------\n\nstd::istream &NFmiLocation::Read(std::istream &file)\n{\n  try\n  {\n    double lon = kFloatMissing;\n    double lat = kFloatMissing;\n    file >> lon >> lat;\n    itsLatlon = NFmiPoint(lon, lat);\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Returns the azimuth bearing (in degrees [0..360] clockwise, 0 = north)\n * between points p1 = (current point) and p2 = (lo2, la2), both in degrees:\n *\n * \\param theLatLon Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::Direction(const NFmiPoint &theLatLon) const\n{\n  try\n  {\n    // Returns the azimuth bearing (in degrees [0..360] CLOCKWISE, 0 = north, 180 = south)\n    // between points (lon1, lat1) (current point) and (lon2, lat2):\n\n    double lon1 = FmiRad(GetLongitude());\n    double lat1 = FmiRad(GetLatitude());\n\n    double lon2 = FmiRad(theLatLon.X());\n    double lat2 = FmiRad(theLatLon.Y());\n    double dlon = lon2 - lon1;\n\n    if (dlon == 0.)\n    {\n      // Points along meridian\n      if (lat2 - lat1 > 0.)\n        return 0.;  // Exact north\n\n      return 180.;  // Exact south\n    }\n\n    ////////////////!!!!!!!!!!!!!!!\n    // From:\n    //  Movable Type Ltd:\n    // http://www.movable-type.co.uk/\n    //\n    // -AND-\n    //\n    // calculate (initial) bearing (in radians clockwise) between two points\n    //\n    // from: Ed Williams' Aviation Formulary, http://williams.best.vwh.net/avform.htm#Crs\n    //\n\n    return FmiDeg(atan2(sin(dlon) * cos(lat2),\n                        cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)));  // [deg]\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n *  Haversine Formula (from R.W. Sinnott, \"Virtues of the Haversine\",\n *  Sky and Telescope, vol. 68, no. 2, 1984, p. 159)\n *  will give mathematically and computationally exact results. The\n *  intermediate result c is the great circle distance in radians. The\n *  great circle distance d will be in the same units as R.\n *\n *  When the two points are antipodal (on opposite sides of the Earth),\n *  the Haversine Formula is ill-conditioned, but the error, perhaps\n *  as large as 2 km (1 mi), is in the context of a distance near\n *  20,000 km (12,000 mi). Further, there is a possibility that roundoff\n *  errors might cause the value of sqrt(a) to exceed 1.0, which would\n *  cause the inverse sine to crash without the bulletproofing provided by\n *  the min() function.\n *\n * \\param theLocation\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiLocation::Distance(const NFmiLocation &theLocation) const\n{\n  try\n  {\n    return NFmiGeoTools::GeoDistance(\n        GetLongitude(), GetLatitude(), theLocation.GetLongitude(), theLocation.GetLatitude());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ======================================================================\n\n// 9.8.04/EL -->\nNFmiLocation NFmiLocation::ComputeLocation(double theAzimuthInDegrees,\n                                           double theDistanceInMeters,\n                                           bool usePacificView) const\n{\n  // Palauttaa maantieteellisen paikan nykysijainnin suhteen azimuutin (asteissa) ja etäisyyden\n  // (metreissä) avulla.\n  // Azimuutti kasvaa myötäpäivään pohjoisesta, pohjoinen = 0 astetta\n  //\n  // Lähde:\n  //\n  // \"Ask Dr. Math - Questions and Answers from our Archive\"\n  // Date: 02/13/97 at 12:59:12\n  // From: Doctor Mitteldorf\n  // Subject: Re: Calculating new position and heading after a walk around the world\n\n  // Alkuperäinen pseudokoodi:\n\n  /*\n\n  First, definitions:\n\n  Start at a point with given longitude, we'll call this long1, and\n  given latitude, we'll call this lat1.\n\n  Travel in a compass heading, we'll call this hdng1, and go a certain\n  distance, we'll call this dist.  The compass heading is measured from\n  due north, which is equal to 0.\n\n  Define alpha = dist/[earth radius] to be the angular distance covered\n  on the earth's surface.\n\n  You're looking for coordinates of the point that you reach, which\n  we'll call lat2 and long2.\n\n  You also want to know your new compass heading, which we'll call\n  hdng2.\n\n  First calculate the new latitude:\n\n  1) sin(lat2) = cos(hdng1)*cos(lat1)*sin(alpha) + sin(lat1)*cos(alpha)\n\n  Then calculate the new longitude, using your result for lat2:\n\n                                                          cos(alpha) - sin(lat1)*sin(lat2)\n  2)    cos(long2-long1) =   ----------------------------------\n                                                                  cos(lat1)*cos(lat2)\n\n\n\n  Again, using lat2 you can calculate the new compass heading:\n\n                                          sin(lat1) - sin(lat2)*cos(alpha)\n  3)    cos(hdng2) =   ----------------------------------\n                                                  cos(lat2)*sin(alpha)\n\n  hdng2 is the compass setting from point 2 to point 1; it's just 180\n  degrees from the compass heading that one has when traveling from\n  point 1 to point 2 and continuing on from there.\n  */\n\n  // Tämä metodi laskee uuden maantiet. sijainnin (long2, lat2),\n  // muttei kuitenkaan uutta \"kompassisuuntaa\" 'hdng2'.\n  // min() ja max() -funktioilla estetään mahd. pyöristysvirheiden vaikutus:\n\n  try\n  {\n    double azimuthInDegrees =\n        theAzimuthInDegrees - int(theAzimuthInDegrees / 360) * 360;  // Kulma välille [-360..360]\n    double alpha = theDistanceInMeters / kRearth;\n    double lat1 = FmiRad(itsLatlon.Y());\n    double value = cos(FmiRad(azimuthInDegrees)) * cos(lat1) * sin(alpha) + sin(lat1) * cos(alpha);\n    double lat2 = asin(std::min(std::max(value, -1.0), 1.0));\n    double newLatitude = FmiDeg(lat2);\n\n    // Lasketaan uusi longitudi:\n\n    value = (cos(alpha) - sin(lat1) * sin(lat2)) / (cos(lat1) * cos(lat2));\n    double longDiff = FmiDeg(acos(std::min(std::max(value, -1.0), 1.0)));\n\n    int sign = 1;\n\n    if (((azimuthInDegrees < 0.) && (azimuthInDegrees >= -180.)) ||\n        ((azimuthInDegrees >= 180.) && (azimuthInDegrees < 360.)))\n      sign = -1;\n\n    double newLongitude = itsLatlon.X() + sign * longDiff;\n    NFmiLongitude longitude(newLongitude, usePacificView);\n    newLongitude = longitude.Value();\n\n    return NFmiLocation(newLongitude, newLatitude);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nvoid NFmiLocation::SetLocation(double theAzimuthInDegrees,\n                               double theDistanceInMeters,\n                               bool usePacificView)\n{\n  try\n  {\n    // Laskee maantieteellisen paikan nykysijainnin suhteen azimuutin (asteissa) ja etäisyyden\n    // (metreissä) avulla.\n    // Azimuutti kasvaa myötäpäivään pohjoisesta, pohjoinen = 0 astetta\n    // HUOM! Tämä metodi muuttaa olion datajäseniä (*this) eli\n    // käytännössä muuttaa olion maant. sijainnin argumentteja vastaavaksi sijainniksi\n\n    *this = ComputeLocation(theAzimuthInDegrees, theDistanceInMeters, usePacificView);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst NFmiLocation NFmiLocation::GetLocation(double theAzimuthInDegrees,\n                                             double theDistanceInMeters,\n                                             bool usePacificView) const\n{\n  try\n  {\n    // Laskee maantieteellisen paikan nykysijainnin suhteen azimuutin (asteissa) ja etäisyyden\n    // (metreissä) avulla.\n    // Azimuutti kasvaa myötäpäivään pohjoisesta, pohjoinen = 0 astetta\n    // Metodi EI muuta datajäseniään; ainoastaan palauttaa argumentteja vastaavan maant. sijainnin\n\n    return ComputeLocation(theAzimuthInDegrees, theDistanceInMeters, usePacificView);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return hash value for the location\n */\n// ----------------------------------------------------------------------\n\nstd::size_t NFmiLocation::HashValue() const\n{\n  try\n  {\n    std::size_t hash = NFmiIndividual::HashValue();\n    boost::hash_combine(hash, itsLatlon.HashValue());\n    return hash;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n", "meta": {"hexsha": "337367ef4688a73763c430b1adb65b1be2032c78", "size": 33828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "newbase/NFmiLocation.cpp", "max_stars_repo_name": "fmidev/smartmet-library-newbase", "max_stars_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newbase/NFmiLocation.cpp", "max_issues_repo_name": "fmidev/smartmet-library-newbase", "max_issues_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-01-17T10:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-21T07:50:17.000Z", "max_forks_repo_path": "newbase/NFmiLocation.cpp", "max_forks_repo_name": "fmidev/smartmet-library-newbase", "max_forks_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-17T07:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-26T07:10:23.000Z", "avg_line_length": 31.4679069767, "max_line_length": 99, "alphanum_fraction": 0.5715974932, "num_tokens": 8308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.013848610978699228, "lm_q1q2_score": 0.005484993758331858}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the tsppd program and library for solving           */\n/*  Traveling Salesman Problems with Pickup and Delivery. tsppd requires     */\n/*  other commercial and open source software to build. tsppd is decribed    */\n/*  in the paper \"Exact Methods for Solving Traveling Salesman Problems      */\n/*  with Pickup and Delivery in Real Time\".                                  */\n/*                                                                           */\n/*  Copyright (C) 2017 Ryan J. O'Neil <roneil1@gmu.edu>                      */\n/*                                                                           */\n/*  tsppd is distributed under the terms of the ZIB Academic License.        */\n/*  You should have received a copy of the ZIB Academic License along with   */\n/*  tsppd. See the file LICENSE. If not, email roneil1@gmu.edu.              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <regex>\n#include <string>\n\n#include <boost/algorithm/string.hpp>\n\n#include <tsppd/io/tsp_problem_reader.h>\n#include <tsppd/util/exception.h>\n#include <tsppd/util/string.h>\n\nusing namespace TSPPD::Data;\nusing namespace TSPPD::IO;\nusing namespace TSPPD::Util;\nusing namespace std;\n\nTSPPDProblem TSPProblemReader::read(string filename) {\n    // Defaults for problem attributes.\n    string name = \"unknown\";\n    auto type = TSP;\n    string comment = \"no comment\";\n    unsigned int dimension = 0;\n    auto edge_weight_type = EUC_2D;\n    vector<string> nodes{};\n    vector<pair<double, double>> coordinates{};\n\n    // Read in the input problem definition.\n    ifstream is(filename);\n    if (!is.is_open())\n        throw TSPPDException(\"unable to read file '\" + filename + \"'\");\n\n    vector<string> lines;\n    string line;\n    while (getline(is, line)) {\n        boost::trim_left(line);\n        boost::trim_right(line);\n        lines.push_back(line);\n    }\n\n    bool in_edge_weight = false;\n    bool in_coordinate = false;\n    bool in_precedence = false;\n\n    vector<string> edge_weight_lines;\n    vector<string> coordinate_lines;\n    vector<string> precedence_lines;\n\n    for (auto line : lines) {\n        if (boost::starts_with(line, \"EOF\")) {\n            break;\n\n        } else if (boost::starts_with(line, \"EDGE_WEIGHT_SECTION\")) {\n            in_edge_weight = true;\n            in_coordinate = false;\n            in_precedence = false;\n\n        } else if (boost::starts_with(line, \"NODE_COORD_SECTION\")) {\n            in_edge_weight = false;\n            in_coordinate = true;\n            in_precedence = false;\n\n        } else if (boost::starts_with(line, \"PRECEDENCE_SECTION\")) {\n            in_edge_weight = false;\n            in_coordinate = false;\n            in_precedence = true;\n\n        } else if (in_edge_weight) {\n            edge_weight_lines.push_back(line);\n\n        } else if (in_coordinate) {\n            coordinate_lines.push_back(line);\n\n        } else if (in_precedence) {\n            precedence_lines.push_back(line);\n\n        } else {\n            // Parse problem metadata.\n            auto comps = resplit(line, regex(\"\\\\s*:\\\\s*\"));\n\n            if (comps.size() != 2)\n                throw TSPPDException(\"invalid input '\" + line + \"'\");\n\n            auto lhs = comps[0];\n            auto rhs = comps[1];\n\n            if (lhs == \"NAME\") {\n                name = rhs;\n            } else if (lhs == \"COMMENT\") {\n                comment = rhs;\n            } else if (lhs == \"TYPE\") {\n                if (rhs != \"TSP\") throw TSPPDException(\"invalid type '\" + rhs + \"'\");\n            } else if (lhs == \"DIMENSION\") {\n                dimension = stoi(rhs);\n            } else if (lhs == \"EDGE_WEIGHT_TYPE\") {\n                if (rhs != \"EUC_2D\" && rhs != \"EXPLICIT\") throw TSPPDException(\"invalid edge weight type '\" + rhs + \"'\");\n                if (rhs == \"EXPLICIT\") edge_weight_type = EXPLICIT;\n            } else if (lhs == \"EDGE_WEIGHT_FORMAT\" && edge_weight_type == EXPLICIT) {\n                if (rhs != \"LOWER_DIAG_ROW\") throw TSPPDException(\"invalid edge weight format '\" + rhs + \"'\");\n            } else {\n                throw TSPPDException(\"invalid field '\" + lhs + \"'\");\n            }\n        }\n    }\n\n    is.close();\n\n    // Parse explicit edge weights\n    auto edge_weights = read_edge_weights(edge_weight_lines);\n\n    // Parse node and coordinate section.\n    auto coord_data = read_coordinate(coordinate_lines);\n    nodes = coord_data.first;\n    coordinates = coord_data.second;\n\n    // Pickup and delivery pairs, if they exist.\n    auto precedence = read_precedence(precedence_lines);\n\n    // Make sure the problem can actually be solved.\n    TSPPDProblem problem(name, type, comment, dimension, edge_weight_type, nodes, coordinates, precedence, edge_weights);\n    problem.validate();\n\n    return problem;\n}\n\nvector<vector<int>> TSPProblemReader::read_edge_weights(vector<string> lines) {\n    vector<vector<int>> weights;\n    for (auto line : lines) {\n        vector<int> w;\n        for (auto weight : wssplit(line))\n            w.push_back(stoi(weight));\n        weights.push_back(w);\n    }\n    return weights;\n}\n\npair<vector<string>, vector<pair<double, double>>> TSPProblemReader::read_coordinate(vector<string> lines) {\n    vector<string> nodes;\n    vector<pair<double, double>> coordinates;\n\n    for (auto line : lines) {\n        boost::trim_left(line);\n        boost::trim_right(line);\n        auto comps = wssplit(line);\n        if (comps.size() != 3)\n            throw TSPPDException(\"invalid coordinate input '\" + line + \"'\");\n\n        nodes.push_back(comps[0]);\n        coordinates.push_back({stod(comps[1]), stod(comps[2])});\n    }\n\n    return {nodes, coordinates};\n}\n\nvector<pair<string, string>> TSPProblemReader::read_precedence(vector<string> lines) {\n    vector<pair<string, string>> pairs;\n\n    for (auto line : lines) {\n        boost::trim_left(line);\n        boost::trim_right(line);\n        auto comps = wssplit(line);\n        if (comps.size() != 2)\n            throw TSPPDException(\"invalid precedence input '\" + line + \"'\");\n\n        pairs.push_back({comps[0], comps[1]});\n    }\n\n    return pairs;\n}\n", "meta": {"hexsha": "144645e598692d1d1c6643437bf1388a24888379", "size": 6366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tsppd/io/tsp_problem_reader.cpp", "max_stars_repo_name": "ryanjoneil/tsppd", "max_stars_repo_head_hexsha": "f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4", "max_stars_repo_licenses": ["AFL-1.1"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-03-30T20:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-25T01:48:09.000Z", "max_issues_repo_path": "src/tsppd/io/tsp_problem_reader.cpp", "max_issues_repo_name": "ryanjoneil/tsppd", "max_issues_repo_head_hexsha": "f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4", "max_issues_repo_licenses": ["AFL-1.1"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-04-21T13:42:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-09T15:49:56.000Z", "max_forks_repo_path": "src/tsppd/io/tsp_problem_reader.cpp", "max_forks_repo_name": "ryanjoneil/tsppd-hybrid", "max_forks_repo_head_hexsha": "f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4", "max_forks_repo_licenses": ["AFL-1.1"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-01T16:19:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-01T16:19:18.000Z", "avg_line_length": 34.7868852459, "max_line_length": 121, "alphanum_fraction": 0.5512095507, "num_tokens": 1460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181322226037884, "lm_q2_score": 0.027169233898802454, "lm_q1q2_score": 0.005483110639463239}}
{"text": "//=============================================================================================================\n/**\n* @file     fixdictmp.cpp\n* @author   Martin Henfling <martin.henfling@tu-ilmenau.de>\n*           Daniel Knobl <daniel.knobl@tu-ilmenau.de>\n*           Sebastian Krause <sebastian.krause@tu-ilmenau.de>\n*\n* @version  1.0\n* @date     July, 2014\n\n* @section  LICENSE\n*\n* Copyright (C) 2014, Sebastian Krause,Daniel Knobl and Martin Henfling All rights reserved.\n*\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    Implemetation of the Matching Pursuit Algorithm using static atom dictionaries to find best matching\n*           approximation of signals.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"fixdictmp.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// STL INCLUDES\n//=============================================================================================================\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/SparseCore>\n#include <unsupported/Eigen/FFT>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Qt INCLUDES\n//=============================================================================================================\n\n#include <QThread>\n#include <QtConcurrent>\n#include <QFuture>\n#include <QFile>\n#include <QStringList>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace UTILSLIB;\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nFixDictMp::FixDictMp()\n: it(0)\n, signal_energy(0)\n, current_energy(0)\n, epsilon(0)\n, max_iterations(0)\n{\n\n}\n\n\n//*************************************************************************************************************\n\nFixDictMp::~FixDictMp()\n{\n\n}\n\n\n//*************************************************************************************************************\n\nDictionary::Dictionary()\n: type(GABORATOM)\n, sample_count(0)\n{\n\n}\n\n\n//*************************************************************************************************************\n\nDictionary::~Dictionary()\n{\n\n}\n\n\n//*************************************************************************************************************\n\nvoid FixDictMp::matching_pursuit(MatrixXd signal, qint32 max_iterations, qreal epsilon, qint32 boost, QString path, qreal delta)\n{\n    Eigen::initParallel();\n\n    std::cout << \"\\nFixDict Matching Pursuit Algorithm started...\\n\";\n\n    QList<Dictionary> parsed_dicts;\n\n    qint32 sample_count = signal.rows();\n    qint32 channel_count = signal.cols();\n\n    signal_energy = 0;\n    qreal residuum_energy = 0;\n    qreal energy_threshold = 0;\n    qreal last_energy = 0;\n    bool sample_count_mismatch = false;\n\n    this->residuum = signal;\n    parsed_dicts = parse_xml_dict(path);\n\n    //calculate signal_energy\n    for(qint32 channel = 0; channel < channel_count; channel++)\n    {\n        for(qint32 sample = 0; sample < sample_count; sample++)\n            signal_energy += (signal(sample, channel) * signal(sample, channel));\n\n        energy_threshold = 0.01 * epsilon * signal_energy;\n        residuum_energy = signal_energy;\n    }\n\n    std::cout << \"absolute energy of signal: \" << residuum_energy << \"\\n\";\n\n    while(it < max_iterations && energy_threshold < residuum_energy)\n    {\n        FixDictAtom global_best_matching;\n\n        QList<find_best_matching> list_of_best;\n        for(qint32 i = 0; i < parsed_dicts.length(); i++)\n        {\n            find_best_matching current_best_matching;\n            current_best_matching.pdict = parsed_dicts.at(i);\n            current_best_matching.current_resid = this->residuum;\n            current_best_matching.boost = boost;\n            list_of_best.append(current_best_matching);\n        }\n\n        QFuture<FixDictAtom> mapped_best_matchings = QtConcurrent::mapped(list_of_best, &find_best_matching::parallel_correlation);// parse_threads;\n        mapped_best_matchings.waitForFinished();\n\n        QFuture<FixDictAtom>::const_iterator i;\n        for (i = mapped_best_matchings.constBegin(); i != mapped_best_matchings.constEnd(); i++)\n        {\n            //FixDictAtom current_best_matching = correlation(parsed_dicts.at(i));\n            if(i == mapped_best_matchings.constBegin())\n                global_best_matching = *i;\n\n            else if(std::fabs(i->max_scalar_product) > std::fabs(global_best_matching.max_scalar_product))\n                global_best_matching = *i;\n        }\n\n        global_best_matching.display_text = create_display_text(global_best_matching);\n\n        VectorXd fitted_atom = VectorXd::Zero(this->residuum.rows());\n        VectorXd resized_atom = VectorXd::Zero(this->residuum.rows());\n\n        if(global_best_matching.atom_samples.rows() > this->residuum.rows())\n            for(qint32 k = 0; k < this->residuum.rows(); k++)    \n                resized_atom[k] = global_best_matching.atom_samples[k + floor(global_best_matching.atom_samples.rows() / 2) - floor(this->residuum.rows() / 2)];\n        else    resized_atom = global_best_matching.atom_samples;\n\n\n        for(qint32 k = 0; k < resized_atom.rows(); k++)\n            if((k + global_best_matching.translation - floor(resized_atom.rows() / 2)) >= 0\n                    && (k + global_best_matching.translation - floor(resized_atom.rows() / 2)) < fitted_atom.rows())\n                    fitted_atom[(k + global_best_matching.translation - floor(resized_atom.rows() / 2))] += resized_atom[k];\n\n        //normalization\n        qreal norm = 0;\n        norm = fitted_atom.norm();\n        if(norm != 0) fitted_atom /= norm;\n\n        for(qint32 chn = 0; chn < this->residuum.cols(); chn++)\n        {\n            qreal scalarproduct = 0;\n            for(qint32 sample = 0; sample < this->residuum.rows(); sample++)\n                scalarproduct += (this->residuum(sample, chn) * fitted_atom[sample]);\n\n            global_best_matching.max_scalar_list.append(scalarproduct);//residuum(global_best_matching.translation, chn) / fitted_atom[global_best_matching.translation]);\n\n            for(qint32 k = 0; k < fitted_atom.rows(); k++)\n            {\n                this->residuum(k,chn) -= global_best_matching.max_scalar_list.at(chn) * fitted_atom[k];\n                global_best_matching.energy += pow(global_best_matching.max_scalar_list.at(chn) * fitted_atom[k], 2); //  * global_best_matching.max_scalar_list.at(chn) * fitted_atom[k];\n            }\n        }\n\n        global_best_matching.atom_samples = fitted_atom;\n\n\n        last_energy = residuum_energy;\n        /*residuum_energy = 0;\n        for(qint32 channel = 0; channel < residuum.cols(); channel++)\n        {\n            for(qint32 sample = 0; sample < residuum.rows(); sample++)\n                residuum_energy += pow(residuum(sample, channel), 2);\n        }*/\n\n        residuum_energy -= global_best_matching.energy;\n        current_energy += global_best_matching.energy;\n\n        fix_dict_list.append(global_best_matching);\n\n        if(global_best_matching.sample_count != signal.rows() && !sample_count_mismatch)\n        {\n            std::cout <<  \"\\n=============================================\\n\"\n                      << \"  INFO\\n\\n(part-)dictionary does not fit the signal!\\n\\nResults might be better by creating dictionaries\\ncontaining atoms of the same length as the signal\\n\"\n                      << \"\\nsignal samples: \" << signal.rows() << \"\\n\"\n                      << \"atom samples: \" << global_best_matching.sample_count << \"\\n\"\n                      <<  \"=============================================\\n\";\n            sample_count_mismatch = true;\n        }\n\n        std::cout << \"\\n\" << \"===============\" << it + 1 <<\"th atom found\" << \"===============\" << \":\\n\\n\"<<\n                     qPrintable(global_best_matching.display_text) << \"\\n\\n\" <<  \"sample_count: \" << global_best_matching.sample_count <<\n                     \" source_dict: \" << qPrintable(global_best_matching.dict_source) << \" Atom ID: \" << global_best_matching.id <<\n                     \"\\nsclr_prdct: \" << global_best_matching.max_scalar_product << \"\\n\" <<\n                     \"\\nabsolute energy of residue: \" << residuum_energy << \"\\n\";\n\n        it++;\n\n        emit current_result(it, max_iterations, current_energy, signal_energy, residuum, adaptive_list, fix_dict_list);\n\n\n        if(((last_energy * 100 / signal_energy) - (residuum_energy * 100 / signal_energy)) < delta)\n        {\n            std::cout <<  \"\\n=============================================\\n\"\n                      << \"  ALGORITHM ABORTED\\n\\ndictionary excludes atoms to reduce further residual energy\\n\"\n                      <<  \"=============================================\\n\";\n            emit send_warning(1);\n            break;\n        }\n        if( QThread::currentThread()->isInterruptionRequested())\n        {\n            send_warning(10);\n            break;\n        }\n\n    }//end while iterations\n\n    std::cout << \"\\nFixDict Matching Pursuit Algorithm finished.\\n\";\n    emit finished_calc();\n    //return atom_list;\n}\n\n\n//*************************************************************************************************************\n\n// calc scalarproduct of Atom and Signal\nFixDictAtom FixDictMp::correlation(Dictionary current_pdict, MatrixXd current_resid, qint32 boost)\n{\n    #ifdef EIGEN_FFTW_DEFAULT\n        fftw_make_planner_thread_safe();\n    #endif\n\n    qint32 channel_count = current_resid.cols() * (boost / 100.0); //reducing the number of observed channels in the algorithm to increase speed performance\n    if(boost == 0 || channel_count == 0)\n        channel_count = 1;\n\n    Eigen::FFT<double> fft;\n    std::ptrdiff_t max_index;\n    VectorXcd fft_atom = VectorXcd::Zero(current_resid.rows());\n\n    FixDictAtom best_matching;\n    qreal max_scalar_product = 0;\n\n    for(qint32 i = 0; i < current_pdict.atoms.length(); i++)\n    {\n        VectorXd fitted_atom = VectorXd::Zero(current_resid.rows());\n        qint32 p = floor(current_resid.rows() / 2);//translation\n\n        VectorXd resized_atom = VectorXd::Zero(current_resid.rows());\n\n        if(current_pdict.atoms.at(i).atom_samples.rows() > current_resid.rows())\n            for(qint32 k = 0; k < current_resid.rows(); k++)\n                resized_atom[k] = current_pdict.atoms.at(i).atom_samples[k + floor(current_pdict.atoms.at(i).atom_samples.rows() / 2) - floor(current_resid.rows() / 2)];\n        else resized_atom = current_pdict.atoms.at(i).atom_samples;\n\n        if(resized_atom.rows() < current_resid.rows())\n            for(qint32 k = 0; k < resized_atom.rows(); k++)\n                fitted_atom[(k + p - floor(resized_atom.rows() / 2))] = resized_atom[k];\n        else fitted_atom = resized_atom;\n\n        //normalization\n        qreal norm = 0;\n        norm = fitted_atom.norm();\n        if(norm != 0) fitted_atom /= norm;\n\n        fft.fwd(fft_atom, fitted_atom);\n\n        for(qint32 chn = 0; chn < channel_count; chn++)\n        {\n            p = floor(current_resid.rows() / 2);//translation\n            VectorXd corr_coeffs = VectorXd::Zero(current_resid.rows());\n            VectorXcd fft_signal = VectorXcd::Zero(current_resid.rows());\n            VectorXcd fft_sig_atom = VectorXcd::Zero(current_resid.rows());\n\n            fft.fwd(fft_signal, current_resid.col(chn));\n\n            for( qint32 m = 0; m < current_resid.rows(); m++)\n                fft_sig_atom[m] = fft_signal[m] * conj(fft_atom[m]);\n\n            fft.inv(corr_coeffs, fft_sig_atom);\n\n            //find index of maximum correlation-coefficient to use in translation\n            max_scalar_product = corr_coeffs.maxCoeff(&max_index);\n\n            if(i == 0)\n            {\n                best_matching = current_pdict.atoms.at(i);\n                best_matching.max_scalar_product = max_scalar_product;\n\n                //adapting translation p to create atomtranslation correctly\n                if(max_index >= p && current_resid.rows() % (2) == 0) p = max_index - p;\n                else if(max_index >= p && current_resid.rows() % (2) != 0) p = max_index - p - 1;\n                else p = max_index + p;\n\n                best_matching.translation = p;\n            }\n\n            else if(std::fabs(max_scalar_product) > std::fabs(best_matching.max_scalar_product))\n            {\n                best_matching = current_pdict.atoms.at(i);\n                best_matching.max_scalar_product = max_scalar_product;\n\n                //adapting translation p to create atomtranslation correctly\n                if(max_index >= p && current_resid.rows() % (2) == 0) p = max_index - p;\n                else if(max_index >= p && current_resid.rows() % (2) != 0) p = max_index - p - 1;\n                else p = max_index + p;\n\n                best_matching.translation = p;\n            }\n        }\n    }\n    best_matching.atom_formula = current_pdict.atom_formula;\n    best_matching.dict_source = current_pdict.source;\n    best_matching.type = current_pdict.type;\n    best_matching.sample_count = current_pdict.sample_count;\n\n    return best_matching;\n}\n\n\n//*************************************************************************************************************\n\nQList<Dictionary> FixDictMp::parse_xml_dict(QString path)\n{\n    QFile current_dict(path);\n    std::cout << \"\\nparsing dictionary, please be patient...\";\n\n    QDomDocument dictionary;\n    dictionary.setContent(&current_dict);\n    QList<Dictionary> parsed_dict;\n    QDomElement current_element = dictionary.documentElement();\n    QDomNodeList node_list = current_element.childNodes();\n    QList<parse_node> pdict_nodes;\n    QList<QDomNode> nodes_listed;\n    bool is_emitted = false;\n\n    for(qint32 i = 0; i < node_list.length(); i++)\n    {\n        parse_node temp_parse;\n        temp_parse.node = node_list.at(i);\n        pdict_nodes.append(temp_parse);\n        nodes_listed.append(node_list.at(i));\n    }\n\n    //multithreading\n    QFuture<Dictionary> mapped_dicts = QtConcurrent::mapped(pdict_nodes, &parse_node::fill_dict_in_map);// parse_threads;\n    mapped_dicts.waitForFinished();\n\n    QFuture<Dictionary>::const_iterator i;\n\n    for (i = mapped_dicts.constBegin(); i != mapped_dicts.constEnd(); i++)\n    {\n        //find_best_matching current_best_matching;\n        //current_best_matching.pdict = *i;\n        //current_best_matching.current_resid = this->residuum;\n        if(i->sample_count != this->residuum.rows() && !is_emitted)\n        {\n            is_emitted = true;\n            emit send_warning(2);\n        }\n\n        parsed_dict.append(*i);\n    }\n\n    std::cout << \"   done.\\n\\n\";\n\n    return parsed_dict;\n}\n\n\n//*************************************************************************************************************\n\nDictionary FixDictMp::fill_dict(const QDomNode &pdict)\n{\n    Dictionary current_dict;\n    QDomElement atom = pdict.firstChildElement(\"ATOM\");\n\n    current_dict.source = pdict.toElement().attribute(\"source_dict\");\n    current_dict.atom_count();// = pdict.toElement().attribute(\"atom_count\").toInt();\n    current_dict.atom_formula = pdict.toElement().attribute(\"formula\");\n    current_dict.sample_count = pdict.toElement().attribute(\"sample_count\").toInt();\n\n    if(current_dict.atom_formula == QString(\"Gaboratom\"))\n    {\n        current_dict.type = GABORATOM;\n\n        while(!atom.isNull())\n        {\n            FixDictAtom current_atom;\n\n            current_atom.id = atom.attribute(\"ID\").toInt();\n            current_atom.gabor_atom.scale = atom.attribute(\"scale\").toDouble();\n            current_atom.gabor_atom.modulation = atom.attribute(\"modu\").toDouble();\n            current_atom.gabor_atom.phase = atom.attribute(\"phase\").toDouble();\n\n            if(atom.hasChildNodes())\n            {\n                QString sample_string = atom.firstChild().toElement().attribute(\"samples\");\n                QStringList sample_list = sample_string.split(\":\",  QString::SkipEmptyParts);\n                current_atom.atom_samples = VectorXd::Zero(sample_list.length());\n                for(qint32 i = 0; i < sample_list.length(); i++)\n                    current_atom.atom_samples[i] = sample_list.at(i).toDouble();\n            }\n            current_dict.atoms.append(current_atom);\n            atom = atom.nextSiblingElement(\"ATOM\");\n        }        \n    }\n    else if(current_dict.atom_formula == QString(\"Chirpatom\"))\n    {\n        current_dict.type = CHIRPATOM;\n\n        while(!atom.isNull())\n        {\n            FixDictAtom current_atom;\n\n            current_atom.id = atom.attribute(\"id\").toInt();\n            current_atom.chirp_atom.scale = atom.attribute(\"scale\").toDouble();\n            current_atom.chirp_atom.modulation = atom.attribute(\"modu\").toDouble();\n            current_atom.chirp_atom.phase = atom.attribute(\"phase\").toDouble();\n            current_atom.chirp_atom.chirp = atom.attribute(\"chirp\").toDouble();\n\n            if(atom.hasChildNodes())\n            {\n                QString sample_string = atom.firstChild().toElement().attribute(\"samples\");\n                QStringList sample_list = sample_string.split(\":\", QString::SkipEmptyParts);\n                current_atom.atom_samples = VectorXd::Zero(sample_list.length());\n                for(qint32 i = 0; i < sample_list.length(); i++)\n                    current_atom.atom_samples[i] = sample_list.at(i).toDouble();\n            }\n            current_dict.atoms.append(current_atom);\n            atom = atom.nextSiblingElement(\"ATOM\");\n        }\n    }\n    else\n    {\n        current_dict.type = FORMULAATOM;\n\n        while(!atom.isNull())\n        {\n            FixDictAtom current_atom;\n\n            current_atom.id = atom.attribute(\"id\").toInt();\n            current_atom.formula_atom.a = atom.attribute(\"a\").toDouble();\n            current_atom.formula_atom.b = atom.attribute(\"b\").toDouble();\n            current_atom.formula_atom.c = atom.attribute(\"c\").toDouble();\n            current_atom.formula_atom.d = atom.attribute(\"d\").toDouble();\n            current_atom.formula_atom.e = atom.attribute(\"e\").toDouble();\n            current_atom.formula_atom.f = atom.attribute(\"f\").toDouble();\n            current_atom.formula_atom.g = atom.attribute(\"g\").toDouble();\n            current_atom.formula_atom.h = atom.attribute(\"h\").toDouble();\n\n            if(atom.hasChildNodes())\n            {\n                QString sample_string = atom.firstChild().toElement().attribute(\"samples\");\n                QStringList sample_list = sample_string.split(\":\", QString::SkipEmptyParts);\n                current_atom.atom_samples = VectorXd::Zero(sample_list.length());\n                for(qint32 i = 0; i < sample_list.length(); i++)\n                    current_atom.atom_samples[i] = sample_list.at(i).toDouble();\n            }\n            current_dict.atoms.append(current_atom);\n            atom = atom.nextSiblingElement(\"ATOM\");\n        }\n    }\n\n    return current_dict;\n}\n\n\n//*************************************************************************************************************\n\nQString FixDictMp::create_display_text(const FixDictAtom& global_best_matching)\n{\n    QString display_text = \"\";\n    if(global_best_matching.type == GABORATOM)\n    {\n        display_text = QString(\"Gaboratom: scale: %0, translation: %1, modulation: %2, phase: %3\")\n                .arg(QString::number(global_best_matching.gabor_atom.scale, 'f', 2))\n                .arg(QString::number(global_best_matching.translation, 'f', 2))\n                .arg(QString::number(global_best_matching.gabor_atom.modulation, 'f', 2))\n                .arg(QString::number(global_best_matching.gabor_atom.phase, 'f', 2));\n    }\n    else if(global_best_matching.type == CHIRPATOM)\n    {\n        display_text = QString(\"Chripatom: scale: %0, translation: %1, modulation: %2, phase: %3, chirp: %4\")\n                .arg(QString::number(global_best_matching.chirp_atom.scale, 'f', 2))\n                .arg(QString::number(global_best_matching.translation, 'f', 2))\n                .arg(QString::number(global_best_matching.chirp_atom.modulation, 'f', 2))\n                .arg(QString::number(global_best_matching.chirp_atom.phase, 'f', 2))\n                .arg(QString::number(global_best_matching.chirp_atom.chirp, 'f', 2));\n    }\n    else if(global_best_matching.type == FORMULAATOM)\n    {\n        display_text = QString(\"%0:  transl: %1 a: %2, b: %3 c: %4, d: %5, e: %6, f: %7, g: %8, h: %9\")\n                .arg(global_best_matching.atom_formula)\n                .arg(QString::number(global_best_matching.translation,    'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.a, 'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.b, 'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.c, 'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.d, 'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.e, 'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.f, 'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.g, 'f', 2))\n                .arg(QString::number(global_best_matching.formula_atom.h, 'f', 2));\n    }\n\n    return display_text;\n}\n\n\n//*************************************************************************************************************\n\nvoid FixDictMp::recieve_input(MatrixXd signal, qint32 max_iterations, qreal epsilon, qint32 boost, QString path, qreal delta)\n{\n    matching_pursuit(signal, max_iterations, epsilon, boost, path, delta);\n}\n\n\n//*************************************************************************************************************\n\nqint32 Dictionary::atom_count()\n{\n    return atoms.length();\n}\n\n\n//*************************************************************************************************************\n\n void Dictionary::clear()\n {\n     this->atoms.clear();\n     this->atom_formula = \"\";\n     this->sample_count = 0;\n     this->source = \"\";\n }\n\n\n //*************************************************************************************************************\n\n/*\nvoid FixDictMp::create_tree_dict(QString save_path)\n{\n    QFile file(save_path);\n    QDomDocument atom_xml_file;\n    atom_xml_file.setContent(&file);\n    GaborAtom* gabor_Atom = new GaborAtom;\n\n    qint32 sample_count = 0;\n    qreal scale = 0;\n    quint32 translation = 0;\n    qreal modulation = 0;\n    qreal phase = 0;\n\n    QDomElement xml_element = atom_xml_file.documentElement();\n\n    QString root_tag = xml_element.tagName();\n\n    if(root_tag == \"builtAtomsTreebasedMP\")\n        sample_count = xml_element.attribute(\"sample_count\").toInt();\n\n    VectorXd compare_atom = VectorXd::Zero(sample_count);\n\n    QString write_save_path = save_path;\n    write_save_path.replace(\".tbd\", \".dict\");\n    QFile write_file(write_save_path);\n    write_file.open(QIODevice::WriteOnly);\n\n    QXmlStreamWriter write_molecules_to_xml(&write_file);\n    write_molecules_to_xml.setAutoFormatting(true);\n\n    write_molecules_to_xml.writeStartDocument();\n    write_molecules_to_xml.writeStartElement(\"TreebasedStructureFor_TBMP\");\n    write_molecules_to_xml.writeAttribute(\"sample_count\", QString::number(sample_count));\n\n    QDomNodeList node_list = xml_element.elementsByTagName(\"Atom\");\n    qint32 max_it = node_list.count();\n    qint32 number_of_molecs = 0;//only debugout\n\n    for(qint32 i = 0; i < max_it; i++)\n    {\n        QDomElement current_element = node_list.at(0).toElement();\n\n        if(!current_element.isNull())\n        {\n            scale = (current_element.attribute(\"scale\", current_element.text())).toDouble();\n            translation = (current_element.attribute(\"translation\", current_element.text())).toInt();\n            modulation = (current_element.attribute(\"modulation\", current_element.text())).toDouble();\n            phase = (current_element.attribute(\"phase\", current_element.text())).toDouble();\n        }\n\n        compare_atom = gabor_Atom->create_real(sample_count,scale,translation,modulation,phase);\n        qreal threshold = 0.8 * compare_atom.dot(compare_atom); //vary this to find optimum of seperation\n\n        QList<qint32> similar_atoms;        \n        VectorXd temp_atom = VectorXd::Zero(sample_count);\n\n        //finding atoms with low differences\n        for (qint32 next = 0; next < node_list.count(); next++)//;32)\n        {\n            //try the next atom\n            current_element = node_list.at(next).toElement();\n\n            if(!current_element.isNull())\n            {\n                scale = (current_element.attribute(\"scale\", current_element.text())).toDouble();\n                translation = (current_element.attribute(\"translation\", current_element.text())).toInt();\n                modulation = (current_element.attribute(\"modulation\", current_element.text())).toDouble();\n                phase = (current_element.attribute(\"phase\", current_element.text())).toDouble();\n            }\n\n            //set atoms out of xml to compare with compare_atom\n            temp_atom = gabor_Atom->create_real(sample_count,scale,translation,modulation,phase);\n\n            //fill list of similar atoms to save as molecule\n            if( compare_atom.dot(temp_atom) > threshold)\n                similar_atoms.append(current_element.attribute(\"ID\", current_element.text()).toInt());\n\n            //if (similar_atoms.length() == 32)//vary this for testing\n            //    break;\n        }\n\n        qreal molec_scale = 0;\n        quint32 molec_translation = 0;\n        qreal molec_modulation = 0;\n        qreal molec_phase = 0;\n\n        //calc molecule params\n\n        for(qint32 j = 0; j < similar_atoms.length(); j++)\n        {            \n            current_element = node_list.at(0).toElement();\n\n            while(!current_element.isNull())\n            {\n                if(current_element.attribute(\"ID\", current_element.text()).toInt() == similar_atoms.at(j))\n                {\n                        molec_scale += (current_element.attribute(\"scale\", current_element.text())).toDouble();\n                        molec_translation += (current_element.attribute(\"translation\", current_element.text())).toInt();\n                        molec_modulation += (current_element.attribute(\"modulation\", current_element.text())).toDouble();\n                        molec_phase += (current_element.attribute(\"phase\", current_element.text())).toDouble();\n                }\n                current_element = current_element.nextSibling().toElement();\n            }\n        }\n\n        molec_scale /= similar_atoms.length();\n        molec_translation /= similar_atoms.length();\n        molec_modulation /= similar_atoms.length();\n        molec_phase /= similar_atoms.length();\n\n        write_molecules_to_xml.writeStartElement(\"Molecule\");\n        write_molecules_to_xml.writeAttribute(\"level\", \"0\");\n        write_molecules_to_xml.writeAttribute(\"ID\", QString::number(i));\n        write_molecules_to_xml.writeAttribute(\"scale\", QString::number(molec_scale));\n        write_molecules_to_xml.writeAttribute(\"translation\", QString::number(molec_translation));\n        write_molecules_to_xml.writeAttribute(\"modulation\", QString::number(molec_modulation));\n        write_molecules_to_xml.writeAttribute(\"phase\", QString::number(molec_phase));\n\n        // write atoms to molecule\n        for(qint32 k = 0; k < similar_atoms.length(); k++)\n        {\n            current_element = node_list.at(0).toElement();\n\n            while(!current_element.isNull())\n            {\n                if(current_element.attribute(\"ID\", current_element.text()).toInt() == similar_atoms.at(k))\n                {\n                    write_molecules_to_xml.writeStartElement(\"Atom\");\n                    write_molecules_to_xml.writeAttribute(\"ID\", current_element.attribute(\"ID\", current_element.text()));\n                    write_molecules_to_xml.writeAttribute(\"scale\", current_element.attribute(\"scale\", current_element.text()));\n                    write_molecules_to_xml.writeAttribute(\"translation\", current_element.attribute(\"translation\", current_element.text()));\n                    write_molecules_to_xml.writeAttribute(\"modulation\", current_element.attribute(\"modulation\", current_element.text()));\n                    write_molecules_to_xml.writeAttribute(\"phase\", current_element.attribute(\"phase\", current_element.text()));\n\n                    write_molecules_to_xml.writeEndElement();//atom\n                }\n                current_element = current_element.nextSibling().toElement();\n            }\n        }\n        write_molecules_to_xml.writeEndElement();//molecule\n\n        //remove found atoms from node list\n        for(qint32 n = 0; n < similar_atoms.length(); n++)\n        {\n            current_element = node_list.at(0).toElement();\n            QDomNode to_remove = current_element.parentNode();\n\n            while(!current_element.isNull())\n            {\n                if(current_element.attribute(\"ID\", current_element.text()).toInt() == similar_atoms.at(n))\n                    to_remove.removeChild(current_element);\n\n                current_element = current_element.nextSibling().toElement();\n            }\n        }\n\n        if(node_list.count() == 0)\n            break;\n\n        number_of_molecs++;\n    }//for max_it of nodelist\n\n    write_molecules_to_xml.writeEndElement();//header\n    write_molecules_to_xml.writeEndDocument();\n\n    cout << \"...start to build tree recursive... number of built molecules:  \" << number_of_molecs + 1 << \"\\n\";\n\n    //close reader and writer\n    file.close();\n    write_file.close();\n    delete gabor_Atom;\n\n    //ToDo: recursion\n    build_molecule_xml_file(0);\n\n    cout << \"finished treebuilding\\n\";\n\n\n}\n\n\n//******************************************************************************************************************\n\nvoid FixDictMp::build_molecule_xml_file(qint32 level_counter)\n{\n    //qint32 i = 0;\n    if(level_counter < 10)\n    {\n        QString save_path = QString(\"Matching-Pursuit-Toolbox/my_first_16atoms.dict\");//ToDo: make it flexible\n        QFile file(save_path);\n        QString temp_path(\"Matching-Pursuit-Toolbox/__temp.dict\");\n        file.copy(temp_path);\n        QFile temp_file(temp_path);\n\n        QDomDocument atom_xml_file;\n        atom_xml_file.setContent(&file);\n        QDomElement xml_element = atom_xml_file.documentElement();\n        xml_element = atom_xml_file.documentElement();\n\n        GaborAtom* gabor_Atom = new GaborAtom;\n        qint32 sample_count = 0;\n        qreal scale = 0;\n        quint32 translation = 0;\n        qreal modulation = 0;\n        qreal phase = 0;\n        //qint32 level_counter = 0;\n\n        QString root_tag = xml_element.tagName();\n        root_tag = xml_element.tagName();\n\n        if(root_tag == \"TreebasedStructureFor_TBMP\")\n            sample_count = xml_element.attribute(\"sample_count\").toInt();\n\n        VectorXd compare_molec = VectorXd::Zero(sample_count);\n\n        QDomNodeList node_list = xml_element.elementsByTagName(\"Molecule\");\n\n        qint32 max_it = node_list.count();\n        QDomElement current_element;\n\n        temp_file.open(QIODevice::WriteOnly);\n\n        QXmlStreamWriter write_molecules_to_xml(&temp_file);\n        write_molecules_to_xml.setAutoFormatting(true);\n\n        write_molecules_to_xml.writeStartDocument();\n        write_molecules_to_xml.writeStartElement(\"TreebasedStructureFor_TBMP\");\n        write_molecules_to_xml.writeAttribute(\"sample_count\", QString::number(sample_count));\n\n        for(qint32 i = 0; i < max_it; i++)\n        {\n            current_element = node_list.at(0).toElement();\n            QList<qint32> similar_molecs;\n\n            if(current_element.attribute(\"level\").toInt() == level_counter && current_element.nodeName() == \"Molecule\")\n            {\n                if(!current_element.isNull())\n                {\n                    scale = (current_element.attribute(\"scale\", current_element.text())).toDouble();\n                    translation = (current_element.attribute(\"translation\", current_element.text())).toInt();\n                    modulation = (current_element.attribute(\"modulation\", current_element.text())).toDouble();\n                    phase = (current_element.attribute(\"phase\", current_element.text())).toDouble();\n                }\n                compare_molec = gabor_Atom->create_real(sample_count,scale,translation,modulation,phase);\n                qreal threshold = 0.6 * compare_molec.dot(compare_molec); //vary this to find optimum of seperation\n\n                VectorXd temp_molec = VectorXd::Zero(sample_count);\n\n                //finding molecules with low differences\n                for (qint32 next = 0; next < node_list.count(); next++)//;32)\n                {\n                    current_element = node_list.at(next).toElement();\n                    //try the next molecule\n                    if(current_element.attribute(\"level\").toInt() == level_counter && current_element.nodeName() == \"Molecule\")\n                    {    //current_element = node_list.at(next).toElement();\n\n                        if(!current_element.isNull())\n                        {\n                            scale = (current_element.attribute(\"scale\", current_element.text())).toDouble();\n                            translation = (current_element.attribute(\"translation\", current_element.text())).toInt();\n                            modulation = (current_element.attribute(\"modulation\", current_element.text())).toDouble();\n                            phase = (current_element.attribute(\"phase\", current_element.text())).toDouble();\n                        }\n                        //set molecules out of xml to compare with molecule\n                        temp_molec = gabor_Atom->create_real(sample_count,scale,translation,modulation,phase);\n\n                        //fill list of similar molecules to save as new molecule\n                        if( compare_molec.dot(temp_molec) > threshold)\n                            similar_molecs.append(current_element.attribute(\"ID\", current_element.text()).toInt());\n\n                        //if (similar_molecs.length() == 32)//vary this for testing\n                        //    break;\n                    }\n                }\n\n                qreal molec_scale = 0;\n                quint32 molec_translation = 0;\n                qreal molec_modulation = 0;\n                qreal molec_phase = 0;\n\n                //calc molecule params\n                for(qint32 j = 0; j < similar_molecs.length(); j++)\n                {\n                    current_element = node_list.at(0).toElement();\n\n                    while(!current_element.isNull())\n                    {\n                        if(current_element.attribute(\"ID\", current_element.text()).toInt() == similar_molecs.at(j) && current_element.attribute(\"level\").toInt() == level_counter)\n                        {\n                            molec_scale += (current_element.attribute(\"scale\", current_element.text())).toDouble();\n                            molec_translation += (current_element.attribute(\"translation\", current_element.text())).toInt();\n                            molec_modulation += (current_element.attribute(\"modulation\", current_element.text())).toDouble();\n                            molec_phase += (current_element.attribute(\"phase\", current_element.text())).toDouble();\n                        }\n                        current_element = current_element.nextSiblingElement(\"Molecule\").toElement();\n                    }\n                }\n\n                molec_scale /= similar_molecs.length();\n                molec_translation /= similar_molecs.length();\n                molec_modulation /= similar_molecs.length();\n                molec_phase /= similar_molecs.length();\n\n                write_molecules_to_xml.writeStartElement(\"Molecule\");\n                write_molecules_to_xml.writeAttribute(\"level\", QString::number(level_counter + 1));\n                write_molecules_to_xml.writeAttribute(\"ID\", QString::number(i));\n                write_molecules_to_xml.writeAttribute(\"scale\", QString::number(molec_scale));\n                write_molecules_to_xml.writeAttribute(\"translation\", QString::number(molec_translation));\n                write_molecules_to_xml.writeAttribute(\"modulation\", QString::number(molec_modulation));\n                write_molecules_to_xml.writeAttribute(\"phase\", QString::number(molec_phase));\n\n                //treedepth building\n\n                current_element = node_list.at(0).toElement();\n                qint32 root_counter = 0;\n\n                for(qint32 k = 0; k < similar_molecs.length(); k++)\n                {                    \n                    //current_element = node_list.at(current_element.attribute(\"ID\", current_element.text()).toInt() == similar_molecs.at(k) && current_element.attribute(\"level\").toInt() == level_counter).toElement();\n                    current_element = node_list.at(0).toElement();\n\n                    while(!current_element.isNull())\n                    {\n                        root_counter = 0;\n\n                        if(current_element.attribute(\"ID\").toInt() == similar_molecs.at(k) && current_element.attribute(\"level\").toInt() == level_counter)\n                        {                           \n                            QDomElement temp_element = current_element;\n                            qint32 end_element_counter = 0;\n                            qint32 child_counter = 0;//ToDo: set right child for right position in tree to write all atoms and molecules\n                            root_counter = 0;\n\n                            while(temp_element.hasChildNodes())\n                            {\n                                end_element_counter = 0;\n                                child_counter = 0;\n\n                                while(!temp_element.isNull())\n                                {                                    \n                                    write_molecules_to_xml.writeStartElement(temp_element.nodeName());\n\n                                    if(temp_element.nodeName() == \"Molecule\")\n                                        write_molecules_to_xml.writeAttribute(\"level\", temp_element.attribute(\"level\", temp_element.text()));\n\n                                    write_molecules_to_xml.writeAttribute(\"ID\", temp_element.attribute(\"ID\", temp_element.text()));\n                                    write_molecules_to_xml.writeAttribute(\"scale\", temp_element.attribute(\"scale\", temp_element.text()));\n                                    write_molecules_to_xml.writeAttribute(\"translation\", temp_element.attribute(\"translation\", temp_element.text()));\n                                    write_molecules_to_xml.writeAttribute(\"modulation\", temp_element.attribute(\"modulation\", temp_element.text()));\n                                    write_molecules_to_xml.writeAttribute(\"phase\", temp_element.attribute(\"phase\", temp_element.text()));\n\n                                    if(temp_element.nodeName() == \"Atom\")\n                                        write_molecules_to_xml.writeEndElement();//close atoms immediately\n                                    else\n                                        end_element_counter++;//keep in mind how many molecules are opened\n\n                                    if(temp_element.hasChildNodes())//if there are children, that means the current element is not an atom: go to next child\n                                    {\n                                        temp_element = temp_element.firstChild().toElement();\n                                        child_counter++;//keep in mind how many children exist\n                                    }\n                                    else\n                                        temp_element = temp_element.nextSibling().toElement();//else there are no children, there must be an atom , so take the next atom\n\n                                }\n                                root_counter++;\n                                write_molecules_to_xml.writeEndElement();\n\n                                temp_element = current_element;\n\n                                //for(qint32 node_depth = 2; node_depth < child_counter; node_depth++)\n                                //    temp_element = temp_element.firstChildElement();\n\n                                for(qint32 node_depth = 2; node_depth < child_counter; node_depth++)\n                                    temp_element = temp_element.childNodes().at(root_counter).toElement();\n\n                            }\n                            //for(qint32 close_root_molecs = end_element_counter; close_root_molecs > 1; close_root_molecs--)\n                            for(qint32 close_root_molecs = level_counter; close_root_molecs > 0; close_root_molecs--)\n                                write_molecules_to_xml.writeEndElement();//end elements for one submolecule in a \"parentmolecule\"\n\n                        }\n\n                        //for(qint32 close_parent_molecs = root_counter; close_parent_molecs > 1; close_parent_molecs--)\n                        //    write_molecules_to_xml.writeEndElement();//close all submolecules inside a new parentmolecule\n\n                        current_element = current_element.nextSiblingElement(\"Molecule\").toElement();\n                    }\n\n                }//for all similar molecules\n\n                //for(qint32 close_parent_molecs = root_counter; close_parent_molecs > 1; close_parent_molecs--)\n                write_molecules_to_xml.writeEndElement();\n\n                //remove found molecules from node list\n                for(qint32 n = 0; n < similar_molecs.length(); n++)\n                {\n                    current_element = node_list.at(0).toElement();\n                    QDomNode to_remove = current_element.parentNode();\n\n                    while(!current_element.isNull())\n                    {\n                        if(current_element.attribute(\"ID\").toInt() == similar_molecs.at(n) && current_element.attribute(\"level\").toInt() == level_counter)\n                            to_remove.removeChild(current_element);\n\n                        current_element = current_element.nextSiblingElement(\"Molecule\").toElement();\n                    }\n                }\n            }//if\n\n            cout << node_list.count() <<\"\\n\";\n\n            if(node_list.count() == 0)\n                break;\n        }//for nodelist\n\n        write_molecules_to_xml.writeEndElement();//header\n        write_molecules_to_xml.writeEndDocument();\n\n        file.flush();\n        temp_file.flush();\n        file.close();\n        temp_file.close();\n\n        file.remove();        \n\n        temp_file.copy(save_path);\n        temp_file.remove();\n\n        level_counter++;\n\n        build_molecule_xml_file(level_counter);\n    }\n}\n*/\n", "meta": {"hexsha": "dc73daa6c279c2c81d57f34c941470eef012d235", "size": 45665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/utils/mp/fixdictmp.cpp", "max_stars_repo_name": "MagCPP/mne-cpp", "max_stars_repo_head_hexsha": "05f634a8401b20226bd719254a5da227e67a379b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T07:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-14T07:38:25.000Z", "max_issues_repo_path": "libraries/utils/mp/fixdictmp.cpp", "max_issues_repo_name": "MagCPP/mne-cpp", "max_issues_repo_head_hexsha": "05f634a8401b20226bd719254a5da227e67a379b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-23T12:40:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-23T12:40:56.000Z", "max_forks_repo_path": "libraries/utils/mp/fixdictmp.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": 44.1207729469, "max_line_length": 217, "alphanum_fraction": 0.5556553159, "num_tokens": 8736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.01744248403391106, "lm_q1q2_score": 0.005477821616860668}}
{"text": "\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ASTRONOMY_COORDINATE_HELIOCENTRIC_HPP\n#define BOOST_ASTRONOMY_COORDINATE_HELIOCENTRIC_HPP\n\n#include <boost/astronomy/coordinate/base_ecliptic_frame.hpp>\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\ntemplate\n<\n    typename Representation, typename Differential\n>\nstruct heliocentric : public base_ecliptic_frame<Representation, Differential>\n{\n\npublic:\n    //default constructor no initialization\n    heliocentric() {}\n\n    //!constructs object from another representation object\n    template <typename OtherRepresentation>\n    heliocentric(OtherRepresentation const& representation_data) : base_ecliptic_frame\n        <Representation, Differential>(representation_data) {}\n\n    //!constructs object from provided components of representation\n    heliocentric\n    (\n        typename Representation::quantity1 const& lat,\n        typename Representation::quantity2 const& lon,\n        typename Representation::quantity3 const& distance\n    ) : base_ecliptic_frame<Representation, Differential>(lat, lon, distance) {}\n\n    //!constructs object from provided components of representation and differential\n    heliocentric\n    (\n        typename Representation::quantity1 const& lat,\n        typename Representation::quantity2 const& lon,\n        typename Representation::quantity3 const& distance,\n        typename Differential::quantity1 const& pm_lat,\n        typename Differential::quantity2 const& pm_lon_coslat,\n        typename Differential::quantity3 const& radial_velocity\n    ) : base_ecliptic_frame<Representation, Differential>\n            (lat, lon, distance, pm_lat, pm_lon_coslat, radial_velocity) {}\n\n    //!constructs object from other representation and differential objects\n    template <typename OtherRepresentation, typename OtherDifferential>\n    heliocentric\n    (\n        OtherRepresentation const& representation_data,\n        OtherDifferential const& differential_data\n    ) : base_ecliptic_frame<Representation, Differential>\n            (representation_data, differential_data) {}\n};\n\n}}} //namespace boost::astronomy::coordinate\n\n#endif // !BOOST_ASTRONOMY_COORDINATE_HELIOCENTRIC_HPP\n\n", "meta": {"hexsha": "a752ea11aba5cd39d9b48dec44e1620bf8daec04", "size": 2315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/heliocentric.hpp", "max_stars_repo_name": "Solariii/astronomy", "max_stars_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/astronomy/coordinate/heliocentric.hpp", "max_issues_repo_name": "Solariii/astronomy", "max_issues_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/astronomy/coordinate/heliocentric.hpp", "max_forks_repo_name": "Solariii/astronomy", "max_forks_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.746031746, "max_line_length": 86, "alphanum_fraction": 0.7555075594, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850131323717, "lm_q2_score": 0.022286183956366563, "lm_q1q2_score": 0.005462009687616551}}
{"text": "#include <votca/ctp/xinductor.h>\n#include <boost/format.hpp>\n#include <vector>\n#include <boost/timer/timer.hpp>\n\nusing boost::format;\n\nnamespace votca { namespace ctp {\n\n    \nXInductor::~XInductor() {\n    vector<InduWorker*>::iterator wit;\n    for (wit = _indus.begin(); wit != _indus.end(); ++wit) {\n        delete *wit;\n    }\n    _indus.clear();\n}\n    \n\nvoid XInductor::Evaluate(XJob *job) {    \n    \n    this->Configure(job);\n    \n//    _qm0.clear();\n//    _mm1.clear();\n//    _mm2.clear();\n//    _qmm.clear();\n//    \n//    _job = job;\n//    _isConverged = !this->_induce;\n//    \n//    // QMM = [ QM0 --- MM1 ] --- MM2 = [ MM2 ]    \n//    _qm0 = job->getPolarTop()->QM0();\n//    _mm1 = job->getPolarTop()->MM1();\n//    _mm2 = job->getPolarTop()->MM2();    \n//\n//    _qmm.reserve(_qm0.size()+_mm1.size());\n//    _qmm.insert(_qmm.end(),_qm0.begin(),_qm0.end());\n//    _qmm.insert(_qmm.end(),_mm1.begin(),_mm1.end());\n\n    // ++++++++++++++++++++++++++ //\n    // (De-)polarize, charge to N //\n    // ++++++++++++++++++++++++++ //\n\n    if (job->StartFromCPT()) {\n        // Permanent fields already computed, do not zero these out ...\n        CTP_LOG(logDEBUG,*_log) << \"Carry out partial depolarization.\" << flush;\n        vector< PolarSeg* >   ::iterator sit;\n        vector< APolarSite* > ::iterator pit;\n\n        // Partially depolarize inner sphere\n        for (sit = _qmm.begin(); sit < _qmm.end(); ++sit) {\n        for (pit = (*sit)->begin(); pit < (*sit)->end(); ++pit) {\n            (*pit)->ResetFieldU();\n            (*pit)->ResetU1Hist();\n        }}\n\n        // Partially depolarize outer shell\n        for (sit = _mm2.begin(); sit < _mm2.end(); ++sit) {\n        for (pit = (*sit)->begin(); pit < (*sit)->end(); ++pit) {\n            (*pit)->ResetFieldU();\n            (*pit)->ResetU1Hist();\n        }}\n    }\n    else {        \n        CTP_LOG(logDEBUG,*_log) << \"Carry out full depolarization.\" << flush;        \n        vector< PolarSeg* >   ::iterator sit;\n        vector< APolarSite* > ::iterator pit;\n\n        // Depolarize inner sphere\n        for (sit = _qmm.begin(); sit < _qmm.end(); ++sit) {\n        for (pit = (*sit)->begin(); pit < (*sit)->end(); ++pit) {\n            (*pit)->Depolarize();\n            (*pit)->Charge(0); // <- Not necessarily neutral state\n        }}\n\n        // Depolarize outer shell\n        for (sit = _mm2.begin(); sit < _mm2.end(); ++sit) {\n        for (pit = (*sit)->begin(); pit < (*sit)->end(); ++pit) {\n            (*pit)->Depolarize();\n            (*pit)->Charge(0); // <- Not necessarily neutral state\n        }}\n    }\n    \n//    // +++++++++++++++++ //\n//    // Induction workers //\n//    // +++++++++++++++++ //\n//\n//    for (int id = 0; id < this->_subthreads; ++id) {\n//        InduWorker *newIndu = new InduWorker(id, _top, this);\n//        _indus.push_back(newIndu);\n//        newIndu->InitSpheres(&_qmm, &_mm2);\n//        newIndu->SetSwitch(1);\n//    }\n//    \n//    this->InitChunks();\n    \n    // ++++++++++++++++++++++++++ //\n    // Compute state energy       //\n    // ++++++++++++++++++++++++++ //\n\n    //[-Wunused-but-set-variable]\n    //double  E_state  = 0.0;\n    \n    int     iter     = 0;\n    \n    boost::timer::cpu_timer cpu_t;\n    cpu_t.start();\n    boost::timer::cpu_times t0 = cpu_t.elapsed();    \n    if (this->_induce) { iter      = this->Induce(job); }\n    boost::timer::cpu_times t1 = cpu_t.elapsed();\n    \n    \n    //[-Wunused-but-set-variable]\n    //if (this->_induce) E_state   = this->Energy(job);\n    //else               E_state   = this->EnergyStatic(job);\n    if (this->_induce) this->Energy(job);\n    else               this->EnergyStatic(job);\n    boost::timer::cpu_times t2 = cpu_t.elapsed();\n    \n    double t_indu = (t1.wall - t0.wall)/1e9/60.;\n    double t_ener = (t2.wall - t1.wall)/1e9/60.;\n    CTP_LOG(logINFO,*_log) << (format(\"  o Total:     %1$1.2f min\")\n        % (t_ener+t_indu)) << flush;\n    CTP_LOG(logINFO,*_log) << (format(\"  o Induction: %1$1.2f min\")\n        % (t_indu)) << flush;\n    CTP_LOG(logINFO,*_log) << (format(\"  o Energy:    %1$1.2f min\")\n        % (t_ener)) << flush;\n\n    job->setInduIter(iter);\n    return;\n}\n\n\nvoid XInductor::Configure(XJob *job) {\n    // SETUP MULTIPOLAR DENSITIES\n    _qm0.clear();\n    _mm1.clear();\n    _mm2.clear();\n    _qmm.clear();\n    \n    _job = job;\n    _isConverged = !this->_induce;\n    \n    // QMM = [ QM0 --- MM1 ] --- MM2 = [ MM2 ]    \n    _qm0 = job->getPolarTop()->QM0();\n    _mm1 = job->getPolarTop()->MM1();\n    _mm2 = job->getPolarTop()->MM2();    \n\n    _qmm.reserve(_qm0.size()+_mm1.size());\n    _qmm.insert(_qmm.end(),_qm0.begin(),_qm0.end());\n    _qmm.insert(_qmm.end(),_mm1.begin(),_mm1.end());\n    \n    // INDUCTION & ENERGY WORKERS\n    // Delete previous ...\n    vector<InduWorker*>::iterator wit;\n    for (wit = _indus.begin(); wit != _indus.end(); ++wit) {\n        delete *wit;\n    }\n    _indus.clear();\n    // ... and allocate new workers.\n    for (int id = 0; id < this->_subthreads; ++id) {\n        InduWorker *newIndu = new InduWorker(id, _top, this);\n        _indus.push_back(newIndu);\n        newIndu->InitSpheres(&_qmm, &_mm2);\n        newIndu->SetSwitch(1);\n    }\n    \n    this->InitChunks();\n    \n    return;\n}\n\n\nint XInductor::Induce(XJob *job) {\n    \n    for (int id = 0; id < this->_subthreads; ++id) {\n        _indus[id]->SetSwitch(1);\n    }\n\n    vector< PolarSeg* >   ::iterator sit1;\n    vector< PolarSeg* >   ::iterator sit2;\n    vector< APolarSite* > ::iterator pit1;\n    vector< APolarSite* > ::iterator pit2;\n    \n    // CONVERGENCE PARAMETERS\n    double wSOR = this->_wSOR_N;\n    double eTOL = this->_epsTol;\n    int    maxI = this->_maxIter;\n    \n    // Adapt wSOR if any segment in QM region is charged\n    for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n        double Q = (*sit1)->CalcTotQ();\n        if (Q*Q > 0.5) { \n            wSOR = this->_wSOR_C;\n            break;\n        }\n    }\n    \n    CTP_LOG(logINFO,*_log) << \"Inductor: Using WSOR = \" << wSOR \n        << \", ASHARP = \" << _aDamp << flush;\n\n    // Intra-pair induction ...\n    bool   induce_intra_pair = this->_induce_intra_pair;\n    // ... change this for jobs of type \"site\":\n    if (_qmm.size() == 1) { induce_intra_pair = true; }\n    \n    \n    // Compute CoM positions, generate coarsegrained sites\n    vector<PolarFrag*>::iterator fit;\n    for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n        (*sit1)->CalcPos();\n        (*sit1)->GeneratePermInduCgSite(false);\n        for (fit = (*sit1)->PolarFrags().begin(); \n            fit < (*sit1)->PolarFrags().end(); ++fit) {\n            (*fit)->CalcPosCenterOfGeom();\n            (*fit)->GeneratePermInduCgSite(false);\n        }\n    }\n    \n    double r_switch_cg_frag = 100.; // 2.5;\n    double r_switch_cg_seg  = 100.; // 4.5;\n    \n    // ++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Inter-site fields (arising from perm. m'poles) //\n    // ++++++++++++++++++++++++++++++++++++++++++++++ //\n    \n    boost::timer::cpu_timer cpu_t_perm;\n    cpu_t_perm.start();\n    boost::timer::cpu_times t_perm_0 = cpu_t_perm.elapsed();\n    \n    for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n    for (sit2 = sit1 + 1; sit2 < _qmm.end(); ++sit2) {\n\n        // Intra-pair permanent induction field?\n         if ( !induce_intra_pair ) {\n             if ( job->isInCenter((*sit1)->getId())\n               && job->isInCenter((*sit2)->getId()) ) {\n                 continue;\n             }\n         }\n//         for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n//         for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n//             _actor.BiasStat(*(*pit1), *(*pit2));\n//             _actor.FieldPerm(*(*pit1), *(*pit2));\n//         }}\n         \n         double dr = votca::tools::abs((*sit1)->getPos()-(*sit2)->getPos());\n         if (dr > r_switch_cg_seg) {\n            for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                _actor.BiasStat(*(*pit1), *((*sit2)->getPermCgSite()));\n                _actor.FieldPermAsPerm_At_By(*(*pit1), *((*sit2)->getPermCgSite()));\n            }\n            for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n                _actor.BiasStat(*(*pit2), *((*sit1)->getPermCgSite()));\n                _actor.FieldPermAsPerm_At_By(*(*pit2), *((*sit1)->getPermCgSite()));\n            }\n        }\n        // Interaction atom <> fragment (cg)\n        else if (dr > r_switch_cg_frag) {\n            for (fit = (*sit2)->PolarFrags().begin(); fit < (*sit2)->PolarFrags().end(); ++fit) {\n                for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                    _actor.BiasStat(*(*pit1), *((*fit)->getPermCgSite()));\n                    _actor.FieldPermAsPerm_At_By(*(*pit1), *((*fit)->getPermCgSite()));\n                }\n            }\n            for (fit = (*sit1)->PolarFrags().begin(); fit < (*sit1)->PolarFrags().end(); ++fit) {\n                for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n                    _actor.BiasStat(*(*pit2), *((*fit)->getPermCgSite()));\n                    _actor.FieldPermAsPerm_At_By(*(*pit2), *((*fit)->getPermCgSite()));\n                }\n            }\n        }\n        // Interaction atom <> atom\n        else {\n            for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n            for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n                _actor.BiasStat(*(*pit1),*(*pit2));\n                _actor.FieldPerm(*(*pit1), *(*pit2));\n            }}\n        }\n    }}\n    \n    // Permanent fields generated by outer shell    \n    // (Outer shell itself is treated as non-polarizable)\n    for (sit2 = _mm2.begin();\n         sit2 < _mm2.end();\n         ++sit2) {\n    for (sit1 = _qmm.begin(); \n         sit1 < _qmm.end();\n         ++sit1) {\n         for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n         for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n             _actor.BiasStat(*(*pit1), *(*pit2));\n             _actor.FieldPerm(*(*pit1), *(*pit2));\n         }}\n    }}\n    \n    boost::timer::cpu_times t_perm_1 = cpu_t_perm.elapsed();\n    double t_perm = (t_perm_1.wall-t_perm_0.wall)/1e9;\n    CTP_LOG(logINFO,*_log) << (format(\"  PERM      |  T=%1$1.2fs \") \n        % (t_perm));\n    CTP_LOG(logINFO,*_log) << flush;\n\n    // +++++++++++++++++++ //\n    // 1st-order induction //\n    // +++++++++++++++++++ //\n\n    // Direct induction. Could also be restored from file (in the case of\n    // iterative QM/MM being performed)\n    if (true || !job->StartFromCPT()) {\n        for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n            for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                (*pit1)->InduceDirect();\n            }\n        }\n    }\n    else {\n        CTP_LOG(logINFO,*_log) << \"Job started from archive, reusing existing \"\n            << \"state as starting configuration\" << flush;\n    }\n    \n    \n    \n    // Transition ranges atm<>atm, atm<>frag, atm<>seg\n    vector<double> rcs_frag;\n    vector<double> rcs_seg;\n    vector<double> ets;\n    //rcs_frag.push_back(1.5);\n    //rcs_frag.push_back(2.0);\n    rcs_frag.push_back(r_switch_cg_frag);\n    //rcs_seg.push_back(3.0);\n    //rcs_seg.push_back(3.75);\n    rcs_seg.push_back(r_switch_cg_seg);\n    //ets.push_back(100*eTOL);\n    //ets.push_back(50*eTOL);\n    ets.push_back(eTOL);\n    \n    int iter_cg = 0;\n    \n    for (int ridx = 0; ridx < 1; ++ridx) {\n        double rc_frag = rcs_frag[ridx];\n        double rc_seg = rcs_seg[ridx];\n        double rc_eTOL = ets[ridx];\n        iter_cg = 0;\n        for ( ; iter_cg < maxI; ++iter_cg) {\n\n            boost::timer::cpu_timer cpu_t;\n            cpu_t.start();\n            boost::timer::cpu_times t0 = cpu_t.elapsed();\n\n            // Reset fields FUx, FUy, FUz\n            for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n                for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                    (*pit1)->ResetFieldU();\n                }\n            }\n\n            boost::timer::cpu_times t1 = cpu_t.elapsed();\n            // Coarsegrain polar segments & fragments\n            for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n                (*sit1)->GeneratePermInduCgSite(false);\n                for (fit = (*sit1)->PolarFrags().begin(); \n                    fit < (*sit1)->PolarFrags().end(); ++fit) {\n                    (*fit)->GeneratePermInduCgSite(false);\n                }\n            }\n\n\n            boost::timer::cpu_times t2 = cpu_t.elapsed();\n            // Intra-site contribution to induction field\n            for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n                for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                for (pit2 = pit1 + 1;        pit2 < (*sit1)->end(); ++pit2) {\n                    _actor.BiasIndu(*(*pit1),*(*pit2));\n                    _actor.FieldIndu(*(*pit1),*(*pit2));\n                }}\n            }\n\n            boost::timer::cpu_times t3 = cpu_t.elapsed();\n            int count_atm_atm   = 0;\n            int count_atm_frag  = 0;\n            int count_atm_seg   = 0;\n            // Inter-site contribution to induction field\n            for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n            for (sit2 = sit1 + 1; sit2 < _qmm.end(); ++sit2) {\n                double dr = votca::tools::abs((*sit1)->getPos()-(*sit2)->getPos());\n                // Interaction atom <> segment (cg)\n                if (dr > rc_seg) {\n                    count_atm_seg += 1;\n                    for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                        _actor.BiasIndu(*(*pit1), *((*sit2)->getInduCgSite()));\n                        _actor.FieldPermAsIndu_At_By(*(*pit1), *((*sit2)->getInduCgSite()));\n                    }\n                    for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n                        _actor.BiasIndu(*(*pit2), *((*sit1)->getInduCgSite()));\n                        _actor.FieldPermAsIndu_At_By(*(*pit2), *((*sit1)->getInduCgSite()));\n                    }\n                }\n                // Interaction atom <> fragment (cg)\n                else if (dr > rc_frag) {\n                    count_atm_frag += 1;\n                    for (fit = (*sit2)->PolarFrags().begin(); fit < (*sit2)->PolarFrags().end(); ++fit) {\n                        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                            _actor.BiasIndu(*(*pit1), *((*fit)->getInduCgSite()));\n                            _actor.FieldPermAsIndu_At_By(*(*pit1), *((*fit)->getInduCgSite()));\n                        }\n                    }\n                    for (fit = (*sit1)->PolarFrags().begin(); fit < (*sit1)->PolarFrags().end(); ++fit) {\n                        for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n                            _actor.BiasIndu(*(*pit2), *((*fit)->getInduCgSite()));\n                            _actor.FieldPermAsIndu_At_By(*(*pit2), *((*fit)->getInduCgSite()));\n                        }\n                    }\n                }\n                 // Interaction atom <> atom\n                else {\n                    count_atm_atm += 1;\n                    for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                    for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n                        _actor.BiasIndu(*(*pit1),*(*pit2));\n                        _actor.FieldIndu(*(*pit1), *(*pit2));\n                    }}\n                }\n            }}\n\n            boost::timer::cpu_times t4 = cpu_t.elapsed();\n\n            // Induce again\n            for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n                 for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                     (*pit1)->Induce(wSOR);                                         \n                 }\n            }\n\n            // Check for convergence\n            bool    converged       = true;\n            double  maxdU_U         = -1;\n            double  avgdU_U         = 0.0;\n            double  rmsdU           = 0.0;\n            int     baseN           = 0;\n            for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n                 for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                     double dU_U = (*pit1)->HistdU();\n                     avgdU_U += dU_U;\n                     double dU2 = (*pit1)->HistdU2();\n                     rmsdU += dU2;\n                     ++baseN;\n                     if ( dU_U > maxdU_U ) { maxdU_U = dU_U; }\n                     if ( dU_U > rc_eTOL) { converged = false; }\n                 }\n            }\n            avgdU_U /= baseN;\n            rmsdU /= baseN;\n            rmsdU = sqrt(rmsdU);\n            if (avgdU_U < rc_eTOL/10.) { converged = true; }\n\n\n            boost::timer::cpu_times t5 = cpu_t.elapsed();\n\n\n            double t_total = (t5.wall-t0.wall)/1e9;\n            double t_cg    = (t2.wall-t1.wall)/1e9;\n            double t_intra = (t3.wall-t2.wall)/1e9;\n            double t_inter = (t4.wall-t3.wall)/1e9;\n\n            CTP_LOG(logINFO,*_log) << (boost::format(\n                \"  ITER %1$3d  |  AVG(dU/U) %3$1.7e  EPS %11$1.1e  |  NN(0<>%7$1.1f<>%6$1.1f) %8$04d|%9$04d|%10$04d\") \n                % iter_cg % maxdU_U % avgdU_U % rmsdU % baseN % rc_seg \n                % rc_frag % count_atm_atm % count_atm_frag % count_atm_seg \n                % eTOL).str();\n            CTP_LOG(logINFO,*_log) << (format(\"  |  T=%1$1.2fs CG/I/O %2$2.2f%% %3$2.2f%% %4$2.2f%%\") \n                % (t_total) % (100*t_cg/t_total) % (100*t_intra/t_total) \n                % (100*t_inter/t_total));\n            CTP_LOG(logINFO,*_log) << flush;\n\n\n            // Break if converged\n            if      (converged) { \n                _isConverged = true;\n                break; \n            }\n            else if (iter_cg == maxI - 1) {\n                _isConverged = false;\n                this->setError((boost::format(\"Did not converge to precision \"\n                   \"(%1$d steps, AVG(dU:U) = %2$1.3e)\") % maxI % avgdU_U).str());\n                break;\n            }\n        }\n    }\n\n    // Reset U1 history\n    for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n            (*pit1)->ResetU1Hist();\n        }\n    }\n\n    return iter_cg;\n//    assert(false);\n//    \n//    \n//    // ++++++++++++++++++++++ //\n//    // Higher-order induction //\n//    // ++++++++++++++++++++++ //\n//\n//    \n//    int iter = 0;\n//    for ( ; iter < maxI; ++iter) {\n//        // Reset fields FUx, FUy, FUz\n//        for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n//            for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n//                (*pit1)->ResetFieldU();\n//            }\n//        }\n//\n//        // Intra-site contribution to induction field\n//        for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n//            for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n//            for (pit2 = pit1 + 1;        pit2 < (*sit1)->end(); ++pit2) {\n//                _actor.BiasIndu(*(*pit1),*(*pit2));\n//                _actor.FieldIndu(*(*pit1),*(*pit2));\n//            }}\n//        }\n//\n//        // Inter-site contribution to induction field\n//        //for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n//        //for (sit2 = sit1 + 1; sit2 < _qmm.end(); ++sit2) {\n//        //    for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n//        //    for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n//        //        _actor.FieldIndu(*(*pit1), *(*pit2));\n//        //    }}\n//        //}}\n//\n//        for (int id = 0; id < this->_subthreads; ++id) { \n//            _indus[id]->Start();\n//        }\n//\n//        for (int id = 0; id < this->_subthreads; ++id) {\n//            _indus[id]->WaitDone();\n//        }\n//\n//        this->ClearTodoTable();\n//\n//\n//\n//        // Induce again\n//        for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n//             for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n//                 (*pit1)->Induce(wSOR);                                         \n//             }\n//        }\n//\n//        // Check for convergence\n//        bool    converged       = true;\n//        double  maxdU_U         = -1;\n//        double  avgdU_U         = 0.0;\n//        double  rmsdU           = 0.0;\n//        int     baseN           = 0;\n//        for (sit1 = _qmm.begin(); sit1 < _qmm.end(); ++sit1) {\n//             for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n//                 double dU_U = (*pit1)->HistdU();\n//                 avgdU_U += dU_U;\n//                 double dU2 = (*pit1)->HistdU2();\n//                 rmsdU += dU2;\n//                 ++baseN;\n//                 if ( dU_U > maxdU_U ) { maxdU_U = dU_U; }\n//                 if ( dU_U > eTOL) { converged = false; }\n//             }\n//        }\n//        avgdU_U /= baseN;\n//        rmsdU /= baseN;\n//        rmsdU = sqrt(rmsdU);\n//        if (avgdU_U < eTOL/10.) { converged = true; }\n//        \n//        CTP_LOG(logINFO,*_log) << (boost::format(\n//            \"  Iter %1$3d | max(dU/U) %2$1.7e  avg(dU/U) %3$1.7e  rms(dU) %4$1.7e  N %5$d\") \n//            % iter % maxdU_U % avgdU_U % rmsdU % baseN).str() << flush;\n//\n//        // Break if converged\n//        if      (converged) { \n//            _isConverged = true;\n//            break; \n//        }\n//        else if (iter == maxI - 1) {\n//            _isConverged = false;\n//            //this->setError(\"Did not converge to precision (\" \n//            //    + boost::lexical_cast<string>(maxI) + \" steps, AVG dU:U \" \n//            //    + boost::lexical_cast<string>(avgdU) + \")\");\n//            this->setError((boost::format(\"Did not converge to precision \"\n//               \"(%1$d steps, AVG(dU:U) = %2$1.3e)\") % maxI % avgdU_U).str());\n//            break;\n//        }\n//    }    \n//    \n//    return iter;\n\n}\n\n\ndouble XInductor::Energy(XJob *job) {\n\n    double int2eV = 1/(4*M_PI*8.854187817e-12) * 1.602176487e-19 / 1.000e-9;    \n\n    _actor.ResetEnergy();\n    \n    // Energy splittings =======================================================\n    // PAIR/SITE        <->        SPH1         <->          SPH2 = OUT       //\n    double E_Tot = 0.0;\n    // ... 0th kind    \n    double E_Pair_Pair = 0.0;    \n    double E_Pair_Sph1 = 0.0;\n    double E_Sph1_Sph1 = 0.0;    \n    double E_Pair_Sph2 = 0.0;\n    double E_Sph1_Sph2 = 0.0;\n    // ... 1st kind\n    double eu_inter = 0.0;\n    double eu_intra = 0.0;\n    double e_perm   = 0.0;\n    // ... 2nd kind\n    double epp      = 0.0;\n    double epu      = 0.0;\n    double euu      = 0.0;\n    // ... 3rd kind\n    double e_f_c_c          = 0.0;\n    double e_f_c_non_c      = 0.0;\n    double e_f_c_out        = 0.0;\n    double e_f_non_c_non_c  = 0.0;   \n    double e_f_non_c_out    = 0.0;\n    double e_m_c            = 0.0;\n    double e_m_c_out        = 0.0;\n    double e_m_non_c        = 0.0;\n    double e_m_non_c_out    = 0.0;\n    double e_m_out          = 0.0;\n    // =========================================================================\n\n    vector< PolarSeg* >     ::iterator      sit1;\n    vector< PolarSeg* >     ::iterator      sit2;\n    vector< APolarSite* >   ::iterator      pit1;\n    vector< APolarSite* >   ::iterator      pit2;\n\n    \n    // =============================================================== //\n    // System Energy | QM | MM1 | MM2 |                                //\n    // =============================================================== //\n    \n\n    for (int id = 0; id < this->_subthreads; ++id) {\n        _indus[id]->SetSwitch(0);\n    }\n\n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Inter-site energy comprising central + first polarization shell //\n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n\n\n    for (int id = 0; id < this->_subthreads; ++id) {\n        _indus[id]->Start();\n    }\n\n    for (int id = 0; id < this->_subthreads; ++id) {\n        _indus[id]->WaitDone();\n    }\n\n    for (int id = 0; id < this->_subthreads; ++id) {\n        E_Pair_Pair += _indus[id]->GetEPairPair();\n        E_Pair_Sph1 += _indus[id]->GetEPairSph1();\n        E_Sph1_Sph1 += _indus[id]->GetESph1Sph1();\n\n        eu_inter += _indus[id]->GetActor().getEU_INTER();\n        eu_intra += _indus[id]->GetActor().getEU_INTRA();\n        e_perm   += _indus[id]->GetActor().getEP();\n\n        epp += _indus[id]->GetActor().getEPP();\n        epu += _indus[id]->GetActor().getEPU();\n        euu += _indus[id]->GetActor().getEUU();\n\n        e_f_c_c             += _indus[id]->GetE_f_C_C();\n        e_f_c_non_c         += _indus[id]->GetE_f_C_non_C();\n        e_f_non_c_non_c     += _indus[id]->GetE_f_non_C_non_C();            \n        e_m_c               += _indus[id]->GetE_m_C();\n        e_m_non_c           += _indus[id]->GetE_m_non_C();\n    }\n\n    this->ClearTodoTable(); \n\n\n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Inter-site energy resulting from interaction with static shell  //\n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n\n    // Interaction between central and static shell\n    for (sit1 = _qm0.begin(); sit1 < _qm0.end(); ++sit1) {\n    for (sit2 = _mm2.begin(); sit2 < _mm2.end(); ++sit2) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_c_out += _actor.E_f(*(*pit1), *(*pit2));\n            e_m_c_out += _actor.E_m(*(*pit1), *(*pit2));            \n        }}\n    }}\n    \n    // Interaction between polarizable and static shell\n    for (sit1 = _mm1.begin(); sit1 < _mm1.end(); ++sit1) {\n    for (sit2 = _mm2.begin(); sit2 < _mm2.end(); ++sit2) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_non_c_out += _actor.E_f(*(*pit1), *(*pit2));\n            e_m_non_c_out += _actor.E_m(*(*pit1), *(*pit2));            \n        }}\n    }}\n\n    // Increment energies\n    // ... 0th kind        \n    E_Pair_Sph2 += e_f_c_out + e_m_c_out;\n    E_Sph1_Sph2 += e_f_non_c_out + e_m_non_c_out;\n    // ... 1st kind\n    e_perm      += _actor.getEP();\n    eu_inter    += _actor.getEU_INTER();\n    // ... 2nd kind\n    epp += _actor.getEPP();\n    epu += _actor.getEPU();\n    euu += _actor.getEUU();\n    // ... 3rd kind\n    // ... ... -> done in loop above, but need to summarize e_m_*\n    e_m_c      += e_m_c_out;\n    e_m_non_c  += e_m_non_c_out;\n\n\n    E_Tot = E_Pair_Pair + E_Pair_Sph1 + E_Sph1_Sph1 + E_Pair_Sph2;\n    \n    \n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Intramolecular field interaction                                //\n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    double e_f_intra_0 = 0.0;\n    double e_m_intra_0 = 0.0;\n    for (sit1 = _qm0.begin(); sit1 < _qm0.end(); ++sit1) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = pit1+1; pit2 < (*sit1)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_intra_0 += _actor.E_f_intra(*(*pit1), *(*pit2));\n            e_m_intra_0 += _actor.E_m_intra(*(*pit1), *(*pit2));\n            _actor.RevBias();\n            e_m_intra_0 += _actor.E_m_intra(*(*pit2), *(*pit1));\n        }}\n    }\n    double e_f_intra_1 = 0.0;\n    double e_m_intra_1 = 0.0;\n    for (sit1 = _mm1.begin(); sit1 < _mm1.end(); ++sit1) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = pit1+1; pit2 < (*sit1)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_intra_1 += _actor.E_f_intra(*(*pit1), *(*pit2));\n            e_m_intra_1 += _actor.E_m_intra(*(*pit1), *(*pit2));\n            _actor.RevBias();\n            e_m_intra_1 += _actor.E_m_intra(*(*pit2), *(*pit1));\n        }}\n    }\n    double e_f_intra_2 = 0.0;\n    double e_m_intra_2 = 0.0;\n    for (sit1 = _mm2.begin(); sit1 < _mm2.end(); ++sit1) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = pit1+1; pit2 < (*sit1)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_intra_2 += _actor.E_f_intra(*(*pit1), *(*pit2));\n            e_m_intra_2 += _actor.E_m_intra(*(*pit1), *(*pit2));\n            _actor.RevBias();\n            e_m_intra_2 += _actor.E_m_intra(*(*pit2), *(*pit1));\n        }}\n    }\n    \n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Total ind. work (to be used with pre-generated perm. fields)    //\n    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    double e_m_0 = 0.0;\n    double e_m_1 = 0.0;\n    double e_m_2 = 0.0;\n    for (sit1 = _qm0.begin(); sit1 < _qm0.end(); ++sit1) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n            e_m_0 += (*pit1)->InductionWork();\n        }\n    }\n    for (sit1 = _mm1.begin(); sit1 < _mm1.end(); ++sit1) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n            e_m_1 += (*pit1)->InductionWork();\n        }\n    }\n    for (sit1 = _mm2.begin(); sit1 < _mm2.end(); ++sit1) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n            e_m_2 += (*pit1)->InductionWork();\n        }\n    }\n    \n//    cout << endl << \"E_f_intra_0 \" << e_f_intra_0*int2eV << flush;\n//    cout << endl << \"E_m_intra_0 \" << e_m_intra_0*int2eV << flush;\n//    cout << endl << \"E_f_intra_1 \" << e_f_intra_1*int2eV << flush;\n//    cout << endl << \"E_m_intra_1 \" << e_m_intra_1*int2eV << flush;\n//    cout << endl << \"E_f_intra_2 \" << e_f_intra_2*int2eV << flush;\n//    cout << endl << \"E_m_intra_2 \" << e_m_intra_2*int2eV << flush;\n//    cout << endl << \"E_m_0 \" << e_m_0*int2eV << flush;\n//    cout << endl << \"E_m_1 \" << e_m_1*int2eV << flush;\n//    cout << endl << \"E_m_2 \" << e_m_2*int2eV << flush;\n    \n    // This is important if permanent/induction fields have been applied\n    // that do not originate in QM0, MM1, MM2\n    \n    e_m_c     = e_m_0 + e_f_intra_0;\n    e_m_non_c = e_m_1 + e_f_intra_1;\n    e_m_out   = e_m_2 + e_f_intra_2;\n    \n    //e_f_c_c += e_f_intra_0;\n    //e_f_non_c_non_c += e_f_intra_1;\n    \n    \n    \n    \n    \n    \n    \n    \n\n    // =============================================================== //\n    // Energy Output                                                   //\n    // =============================================================== //\n\n    // ... 0th kind\n    E_Tot = E_Pair_Pair\n          + E_Pair_Sph1\n          + E_Sph1_Sph1\n          + E_Pair_Sph2\n          + E_Sph1_Sph2;\n\n//    CTP_LOG(logINFO,*_log) \n//             << \"... E(X) = \" << E_Tot * int2eV << \" eV \"\n//             << flush << \"...      = (Site, Site) \" << E_Pair_Pair * int2eV\n//             << flush << \"...      + (Site, Sph1) \" << E_Pair_Sph1 * int2eV\n//             << flush << \"...      + (Sph1, Sph1) \" << E_Sph1_Sph1 * int2eV\n//             << flush << \"...      + (Site, Sph2) \" << E_Pair_Sph2 * int2eV\n//             << flush << \"...      + (Sph1, Sph2) \" << E_Sph1_Sph2 * int2eV\n//             << flush;\n\n    // ... 1st kind\n    double E_PPUU = epp \n                  + epu \n                  + euu;\n\n//    CTP_LOG(logINFO,*_log)\n//             << \"... E(X) = \" << E_PPUU * int2eV << \" eV \" \n//             << flush << \"...      = (PP) \"    << epp  * int2eV\n//             << flush << \"...      + (PU) \"    << epu  * int2eV\n//             << flush << \"...      + (UU) \"    << euu  * int2eV\n//             << flush;\n\n    // ... 2nd kind\n    double E_f_m = e_f_c_c \n                 + e_f_c_non_c\n                 + e_f_c_out \n                 + e_f_non_c_non_c \n                 + e_f_non_c_out\n                 + e_m_c \n                 + e_m_non_c\n                 + e_m_out;\n\n    CTP_LOG(logINFO,*_log)\n        << (format(\"PP-PU-UU Splitting\")).str()\n        << flush << (format(\"  + U [Q  -  Q]       = %1$+1.7f eV\") % (epp      * int2eV)).str()\n        << flush << (format(\"  + U [Q  - dQ]       = %1$+1.7f eV\") % (epu      * int2eV)).str()       \n        << flush << (format(\"  + U [dQ - dQ]       = %1$+1.7f eV\") % (euu      * int2eV)).str()\n        << flush << (format(\"  = ------------------------------\")).str()\n        << flush << (format(\"  + SUM(E)            = %1$+1.7f eV\") % (E_PPUU   * int2eV)).str()\n        << flush;\n    CTP_LOG(logINFO,*_log)\n        << (format(\"QM0-MM1-MM2 Splitting\")).str()\n        << flush << (format(\"  + Field-term [0-0]  = %1$+1.7f eV (%2$+1.7f)\") % (e_f_c_c          * int2eV) % (e_f_intra_0*int2eV)).str()\n        << flush << (format(\"  + Field-term [0-1]  = %1$+1.7f eV\") % (e_f_c_non_c      * int2eV)).str()       \n        << flush << (format(\"  + Field-term [0-2]  = %1$+1.7f eV\") % (e_f_c_out        * int2eV)).str()\n        << flush << (format(\"  + Field-term [1-1]  = %1$+1.7f eV (%2$+1.7f)\") % (e_f_non_c_non_c  * int2eV) % (e_f_intra_1*int2eV)).str()\n        << flush << (format(\"  + Field-term [1-2]  = %1$+1.7f eV\") % (e_f_non_c_out    * int2eV)).str()\n        << flush << (format(\"    ------------------------------\")).str()\n        << flush << (format(\"  + Work-term  [-0-]  = %1$+1.7f eV\") % (e_m_c            * int2eV)).str()\n        << flush << (format(\"  + Work-term  [-1-]  = %1$+1.7f eV\") % (e_m_non_c        * int2eV)).str()\n        << flush << (format(\"  + Work-term  [-2-]  = %1$+1.7f eV\") % (e_m_out          * int2eV)).str()\n        << flush << (format(\"  = ------------------------------\")).str()\n        << flush << (format(\"    SUM(E)            = %1$+1.7f eV\") % (E_f_m               *int2eV)).str()\n        << flush;\n    \n    \n//    CTP_LOG(logINFO,*_log)\n//             << \"... E(X) = \" << E_f_m * int2eV << \" eV \" \n//             << flush << \"...      = (f,0-0) \" << e_f_c_c          * int2eV\n//             << flush << \"...      + (f,0-1) \" << e_f_c_non_c      * int2eV\n//             << flush << \"...      + (f,0-2) \" << e_f_c_out        * int2eV\n//             << flush << \"...      + (f,1-1) \" << e_f_non_c_non_c  * int2eV\n//             << flush << \"...      + (f,1-2) \" << e_f_non_c_out    * int2eV\n//             << flush << \"...      + (m,-0-) \" << e_m_c            * int2eV\n//             << flush << \"...      + (m,-1-) \" << e_m_non_c        * int2eV\n//             << flush << \"...      + (m,-2-) \" << e_m_out          * int2eV\n//             << flush;\n\n    // Forward results to job\n    job->setEnergy(E_Tot            *int2eV,           \n                   E_Pair_Pair      *int2eV,\n                   E_Pair_Sph1      *int2eV,\n                   E_Pair_Sph2      *int2eV, \n                   E_Sph1_Sph1      *int2eV,\n                   E_Sph1_Sph2      *int2eV,                       \n                   e_perm           *int2eV,\n                   eu_inter         *int2eV);\n\n    job->setEnergy_PPUU(epp         *int2eV,\n                        epu         *int2eV,\n                        euu         *int2eV);\n\n    job->setEnergy_f_m(e_f_c_c         *int2eV,\n                       e_f_c_non_c     *int2eV,\n                       e_f_c_out       *int2eV,\n                       e_f_non_c_non_c *int2eV, \n                       e_f_non_c_out   *int2eV,\n                       e_m_c           *int2eV, \n                       e_m_non_c       *int2eV,\n                       e_m_out         *int2eV);\n\n    return E_Tot;\n}\n\n\ndouble XInductor::EnergyStatic(XJob *job) {\n    \n    double int2eV = 1/(4*M_PI*8.854187817e-12) * 1.602176487e-19 / 1.000e-9;\n\n    _actor.ResetEnergy();\n    \n    // Energy splittings =======================================================\n    // PAIR/SITE        <->        SPH1         <->          SPH2 = OUT       //\n    double E_Tot = 0.0;\n    // ... 0th kind    \n    double E_Pair_Pair = 0.0;    \n    double E_Pair_Sph1 = 0.0;\n    double E_Sph1_Sph1 = 0.0;    \n    double E_Pair_Sph2 = 0.0;\n    double E_Sph1_Sph2 = 0.0;\n    // ... 1st kind\n    double eu_inter = 0.0;\n    \n    //[-Wunused-variable]\n    //double eu_intra = 0.0;\n\n    double e_perm   = 0.0;\n    // ... 2nd kind\n    double epp      = 0.0;\n    double epu      = 0.0;\n    double euu      = 0.0;\n    // ... 3rd kind\n    double e_f_c_c          = 0.0;\n    double e_f_c_non_c      = 0.0;\n    double e_f_c_out        = 0.0;\n    double e_f_non_c_non_c  = 0.0;   \n    double e_f_non_c_out    = 0.0;\n    double e_m_c            = 0.0;\n    \n    //[-Wunused-variable]\n    //double e_m_c_out        = 0.0;\n    \n    double e_m_non_c        = 0.0;\n    \n    //[-Wunused-variable]\n    //double e_m_non_c_out    = 0.0;\n    \n    double e_m_out          = 0.0;\n    // =========================================================================\n\n    \n    vector< PolarSeg* >    ::iterator      sit1;\n    vector< PolarSeg* >    ::iterator      sit2;\n    vector< APolarSite* >  ::iterator      pit1;\n    vector< APolarSite* >  ::iterator      pit2;\n\n        \n    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Interaction pair <-> inner cut-off, without intra-pair interaction //\n    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n\n    for (sit1 = _qm0.begin(); sit1 < _qm0.end(); ++sit1) {\n    for (sit2 = _mm1.begin(); sit2 < _mm1.end(); ++sit2) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_c_non_c += _actor.E_f(*(*pit1), *(*pit2));\n        }}\n    }}\n\n\n    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Interaction pair <-> outer cut-off                                 //\n    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n\n    for (sit1 = _qm0.begin(); sit1 < _qm0.end(); ++sit1) {\n    for (sit2 = _mm2.begin(); sit2 < _mm2.end(); ++sit2) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_c_out += _actor.E_f(*(*pit1), *(*pit2));            \n        }}\n    }}\n\n\n    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    // Intra-pair interaction                                             //\n    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //\n    \n    for (sit1 = _qm0.begin(); sit1 < _qm0.end(); ++sit1) {\n    for (sit2 = sit1 + 1; sit2 < _qm0.end(); ++sit2) {\n        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n            _actor.BiasIndu(*(*pit1), *(*pit2));\n            e_f_c_c += _actor.E_f(*(*pit1), *(*pit2));            \n        }}\n    }}\n\n\n    // Increment energies\n    // ... 0th kind\n    E_Pair_Pair     += e_f_c_c;\n    E_Pair_Sph1     += e_f_c_non_c;\n    E_Pair_Sph2     += e_f_c_out;\n    // ... 1st kind\n    e_perm          += _actor.getEP();\n    eu_inter        += _actor.getEU_INTER();\n    // ... 2nd kind\n    epp             += _actor.getEPP();\n    epu             += _actor.getEPU();\n    euu             += _actor.getEUU();\n    // ... 3rd kind\n    // ... ... -> done in loops above        \n\n\n    // =============================================================== //\n    // Energy Output                                                   //\n    // =============================================================== //\n\n    // ... 0th kind\n    E_Tot = E_Pair_Pair\n          + E_Pair_Sph1\n          + E_Sph1_Sph1\n          + E_Pair_Sph2\n          + E_Sph1_Sph2;\n    \n//    CTP_LOG(logINFO,*_log) \n//             << \"... E(X) = \" << E_Tot * int2eV << \" eV \"\n//             << flush << \"...      = (Site, Site) \" << E_Pair_Pair * int2eV\n//             << flush << \"...      + (Site, Sph1) \" << E_Pair_Sph1 * int2eV\n//             << flush << \"...      + (Sph1, Sph1) \" << E_Sph1_Sph1 * int2eV\n//             << flush << \"...      + (Site, Sph2) \" << E_Pair_Sph2 * int2eV\n//             << flush << \"...      + (Sph1, Sph2) \" << E_Sph1_Sph2 * int2eV\n//             << flush;\n\n    // ... 1st kind\n    double E_PPUU = epp \n                  + epu \n                  + euu;\n\n//    CTP_LOG(logINFO,*_log)\n//             << \"... E(X) = \" << E_PPUU * int2eV << \" eV \" \n//             << flush << \"...      = (PP) \"    << epp  * int2eV\n//             << flush << \"...      + (PU) \"    << epu  * int2eV\n//             << flush << \"...      + (UU) \"    << euu  * int2eV\n//             << flush;\n\n    // ... 2nd kind\n    double E_f_m = e_f_c_c \n                 + e_f_c_non_c\n                 + e_f_c_out \n                 + e_f_non_c_non_c \n                 + e_f_non_c_out\n                 + e_m_c \n                 + e_m_non_c\n                 + e_m_out;\n\n//    CTP_LOG(logINFO,*_log)\n//             << \"... E(X) = \" << E_f_m * int2eV << \" eV \" \n//             << flush << \"...      = (f,0-0) \" << e_f_c_c          * int2eV\n//             << flush << \"...      + (f,0-1) \" << e_f_c_non_c      * int2eV\n//             << flush << \"...      + (f,0-2) \" << e_f_c_out        * int2eV\n//             << flush << \"...      + (f,1-1) \" << e_f_non_c_non_c  * int2eV\n//             << flush << \"...      + (f,1-2) \" << e_f_non_c_out    * int2eV\n//             << flush << \"...      + (m,-0-) \" << e_m_c            * int2eV\n//             << flush << \"...      + (m,-1-) \" << e_m_non_c        * int2eV\n//             << flush << \"...      + (m,-2-) \" << e_m_out          * int2eV\n//             << flush;\n\n    \n    CTP_LOG(logINFO,*_log)\n        << (format(\"PP-PU-UU Splitting\")).str()\n        << flush << (format(\"  + U [Q  -  Q]       = %1$+1.7f eV\") % (epp      * int2eV)).str()\n        << flush << (format(\"  + U [Q  - dQ]       = %1$+1.7f eV\") % (epu      * int2eV)).str()       \n        << flush << (format(\"  + U [dQ - dQ]       = %1$+1.7f eV\") % (euu      * int2eV)).str()\n        << flush << (format(\"    ------------------------------\")).str()\n        << flush << (format(\"    SUM(E)            = %1$+1.7f eV\") % (E_PPUU   * int2eV)).str()\n        << flush;\n    CTP_LOG(logINFO,*_log)\n        << (format(\"QM0-MM1-MM2 Splitting\")).str()\n        << flush << (format(\"  + Field-term [0-0]  = %1$+1.7f eV\") % (e_f_c_c          * int2eV)).str()\n        << flush << (format(\"  + Field-term [0-1]  = %1$+1.7f eV\") % (e_f_c_non_c      * int2eV)).str()       \n        << flush << (format(\"  + Field-term [0-2]  = %1$+1.7f eV\") % (e_f_c_out        * int2eV)).str()\n        << flush << (format(\"  + Field-term [1-1]  = %1$+1.7f eV\") % (e_f_non_c_non_c  * int2eV)).str()\n        << flush << (format(\"  + Field-term [1-2]  = %1$+1.7f eV\") % (e_f_non_c_out    * int2eV)).str()\n        << flush << (format(\"    ------------------------------\")).str()\n        << flush << (format(\"  + Work-term  [-0-]  = %1$+1.7f eV\") % (e_m_c            * int2eV)).str()\n        << flush << (format(\"  + Work-term  [-1-]  = %1$+1.7f eV\") % (e_m_non_c        * int2eV)).str()\n        << flush << (format(\"  + Work-term  [-2-]  = %1$+1.7f eV\") % (e_m_out          * int2eV)).str()\n        << flush << (format(\"    ------------------------------\")).str()\n        << flush << (format(\"    SUM(E)            = %1$+1.7f eV\") % (E_f_m               *int2eV)).str()\n        << flush;\n    \n    \n    // Forward results to job\n    job->setEnergy(E_Tot            *int2eV,           \n                   E_Pair_Pair      *int2eV,\n                   E_Pair_Sph1      *int2eV,\n                   E_Pair_Sph2      *int2eV, \n                   E_Sph1_Sph1      *int2eV,\n                   E_Sph1_Sph2      *int2eV,                       \n                   e_perm           *int2eV,\n                   eu_inter         *int2eV);\n\n    job->setEnergy_PPUU(epp         *int2eV,\n                        epu         *int2eV,\n                        euu         *int2eV);\n\n    job->setEnergy_f_m(e_f_c_c         *int2eV,\n                       e_f_c_non_c     *int2eV,\n                       e_f_c_out       *int2eV,\n                       e_f_non_c_non_c *int2eV, \n                       e_f_non_c_out   *int2eV,\n                       e_m_c           *int2eV, \n                       e_m_non_c       *int2eV,\n                       e_m_out         *int2eV);    \n    \n    return E_Tot;\n}\n\n\nXInductor::XInductor(Topology *top, Property *opt, \n                     string sfx, int nst, bool mav)\n                  : _subthreads(nst), _maverick(mav) {\n    \n    string key = sfx + \".tholemodel\";\n\n        if ( opt->exists(key+\".induce\") ) {\n            int induce = opt->get(key+\".induce\").as< int >();\n            _induce = (induce == 0) ? false : true;\n        }\n        else { _induce = true; }\n\n        if ( opt->exists(key+\".induce_intra_pair\") ) {\n            int induce = opt->get(key+\".induce_intra_pair\").as< int >();\n            _induce_intra_pair = (induce == 0) ? false : true;\n        }\n        else { _induce_intra_pair = true; }\n\n        if ( opt->exists(key+\".exp_damp\") ) {\n            _aDamp = opt->get(key+\".exp_damp\").as< double >();\n        }\n        else {\n            cout << endl << \"... ... WARNING: No sharpness parameter supplied\";\n            cout << endl << \"... ... ... Using default a = 0.39\";\n            _aDamp = 0.39;\n        }\n\n    key = sfx + \".convergence\";\n\n        if ( opt->exists(key+\".wSOR_N\") ) {\n            _wSOR_N = opt->get(key+\".wSOR_N\").as< float >();\n        }\n        else { _wSOR_N = 0.75; }\n        if ( opt->exists(key+\".wSOR_C\") ) {\n            _wSOR_C = opt->get(key+\".wSOR_C\").as< float >();\n        }\n        else { _wSOR_C = 0.75; }\n\n        if ( opt->exists(key+\".max_iter\") ) {\n            _maxIter = opt->get(key+\".max_iter\").as< int >();\n        }\n        else { _maxIter = 512; }\n\n        if ( opt->exists(key+\".tolerance\") ) {\n            _epsTol = opt->get(key+\".tolerance\").as< double >();\n        }\n        else { _epsTol = 0.001; }\n    \n    _actor = XInteractor(NULL, _aDamp);\n    \n}\n\n\n}}", "meta": {"hexsha": "c1ccf3d8a11b62450f091f76ec55885cc07a6d22", "size": 46041, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libctp/xinductor.cc", "max_stars_repo_name": "jimbach/ctp", "max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "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/libctp/xinductor.cc", "max_issues_repo_name": "jimbach/ctp", "max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libctp/xinductor.cc", "max_forks_repo_name": "jimbach/ctp", "max_forks_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "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.4315525876, "max_line_length": 137, "alphanum_fraction": 0.422905671, "num_tokens": 14283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.017442486460018693, "lm_q1q2_score": 0.005419282795079369}}
{"text": "// Copyright (c) 2020, OUXT-Polaris\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 <polaris/types/type_base.hpp>\n#include <polaris/built_in_functions/functions.hpp>\n#include <polaris/exception.hpp>\n\n#include <quaternion_operation/quaternion_operation.h>\n#include <geometry_msgs/msg/quaternion.hpp>\n#include <geometry_msgs/msg/point.hpp>\n\n#include <boost/optional.hpp>\n#include <boost/any.hpp>\n\n#include <functional>\n#include <unordered_map>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace polaris\n{\nnamespace built_in_functions\n{\nboost::any Functions::fetchVariable(std::shared_ptr<peg::Ast> ast)\n{\n  if (variables_.count(ast->token) == 0) {\n    POLARIS_THROW_EVALUATION_ERROR(ast->nodes[0],\n      \"variable \" + ast->token + \" did not defined yet.\");\n  }\n  return variables_[ast->token];\n}\n\nboost::any Functions::constructBoolean(std::shared_ptr<peg::Ast> ast)\n{\n  if (ast->name == \"BOOLEAN\") {\n    types::TypeBase<bool> bool_value;\n    if (ast->token == \"true\") {\n      bool_value.setValue(true);\n    } else if (ast->token == \"false\") {\n      bool_value.setValue(false);\n    } else {\n      POLARIS_THROW_EVALUATION_ERROR(ast, \"bool value should be true or false\");\n    }\n    return bool_value;\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructEntity(std::shared_ptr<peg::Ast> ast)\n{\n  auto pose_value = evaluate(ast->nodes[0]->name, ast->nodes[0]);\n  geometry_msgs::msg::Pose pose;\n  if (pose_value.type() == typeid(types::TypeBase<geometry_msgs::msg::Pose>)) {\n    pose = boost::any_cast<types::TypeBase<geometry_msgs::msg::Pose>>(pose_value).getValue();\n  } else {\n    POLARIS_THROW_EVALUATION_ERROR(ast->nodes[0], \"failed to parse pose\");\n  }\n  auto type_value = evaluate(ast->nodes[1]->name, ast->nodes[1]);\n  std::string type;\n  std::vector<std::string> types;\n  if (type_value.type() == typeid(types::TypeBase<std::string>)) {\n    type = boost::any_cast<types::TypeBase<std::string>>(type_value).getValue();\n  } else if (type_value.type() == typeid(types::TypeBase<std::vector<std::string>>)) {\n    types = boost::any_cast<types::TypeBase<std::vector<std::string>>>(type_value).getValue();\n  } else {\n    POLARIS_THROW_EVALUATION_ERROR(ast->nodes[1], \"failed to parse types\");\n  }\n  auto polygon_value = evaluate(ast->nodes[2]->name, ast->nodes[2]);\n  std::vector<geometry_msgs::msg::Point> polygon;\n  if (polygon_value.type() == typeid(types::TypeBase<std::vector<geometry_msgs::msg::Point>>)) {\n    polygon =\n      boost::any_cast<types::TypeBase<std::vector<geometry_msgs::msg::Point>>>(polygon_value).\n      getValue();\n  } else {\n    POLARIS_THROW_EVALUATION_ERROR(ast->nodes[2], \"failed to parse polygon\");\n  }\n  if (types.size() == 0) {\n    return types::TypeBase<polaris::types::Entity>(polaris::types::Entity(pose, type, polygon));\n  } else {\n    return types::TypeBase<polaris::types::Entity>(polaris::types::Entity(pose, types, polygon));\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructArray(std::shared_ptr<peg::Ast> ast)\n{\n  if (ast->nodes.size() == 0) {\n    POLARIS_THROW_EVALUATION_ERROR(ast,\n      \"array is empty\");\n  }\n  const auto first_value = evaluate(ast->nodes[0]->name, ast->nodes[0]);\n  const auto & value_type = first_value.type();\n  if (value_type == typeid(types::TypeBase<int>)) {\n    types::TypeBase<std::vector<int>> array;\n    std::vector<int> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<int>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<int>>(value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not int\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  if (value_type == typeid(types::TypeBase<double>)) {\n    types::TypeBase<std::vector<double>> array;\n    std::vector<double> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<double>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<double>>(value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not double\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  if (value_type == typeid(types::TypeBase<std::string>)) {\n    types::TypeBase<std::vector<std::string>> array;\n    std::vector<std::string> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<std::string>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<std::string>>(value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not string\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  if (value_type == typeid(types::TypeBase<bool>)) {\n    types::TypeBase<std::vector<bool>> array;\n    std::vector<bool> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<bool>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<bool>>(value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not bool\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  if (value_type == typeid(types::TypeBase<geometry_msgs::msg::Quaternion>)) {\n    types::TypeBase<std::vector<geometry_msgs::msg::Quaternion>> array;\n    std::vector<geometry_msgs::msg::Quaternion> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<geometry_msgs::msg::Quaternion>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<geometry_msgs::msg::Quaternion>>(\n            value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not quaternion\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  if (value_type == typeid(types::TypeBase<geometry_msgs::msg::Point>)) {\n    types::TypeBase<std::vector<geometry_msgs::msg::Point>> array;\n    std::vector<geometry_msgs::msg::Point> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<geometry_msgs::msg::Point>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<geometry_msgs::msg::Point>>(\n            value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not point\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  if (value_type == typeid(types::TypeBase<geometry_msgs::msg::Pose>)) {\n    types::TypeBase<std::vector<geometry_msgs::msg::Pose>> array;\n    std::vector<geometry_msgs::msg::Pose> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<geometry_msgs::msg::Pose>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<geometry_msgs::msg::Pose>>(\n            value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not pose\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  if (value_type == typeid(types::TypeBase<types::Entity>)) {\n    types::TypeBase<std::vector<types::Entity>> array;\n    std::vector<types::Entity> array_value;\n    for (const auto & node : ast->nodes) {\n      auto value = evaluate(node->name, node);\n      if (value.type() == typeid(types::TypeBase<types::Entity>)) {\n        array_value.emplace_back(boost::any_cast<types::TypeBase<types::Entity>>(\n            value).getValue());\n      } else {\n        POLARIS_THROW_EVALUATION_ERROR(ast, \"array value is not pose\");\n      }\n    }\n    array.setValue(array_value);\n    return array;\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructString(std::shared_ptr<peg::Ast> ast)\n{\n  if (ast->name == \"STRING\") {\n    types::TypeBase<std::string> str_value;\n    str_value.setValue(ast->token);\n    return str_value;\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructInteger(std::shared_ptr<peg::Ast> ast)\n{\n  if (ast->name == \"INTEGER\") {\n    try {\n      types::TypeBase<int> int_value;\n      int_value.setValue(std::stoi(ast->token));\n      return int_value;\n    } catch (std::invalid_argument) {\n      POLARIS_THROW_EVALUATION_ERROR(ast,\n        \"failed to parse token into int value, std::invalid_argument\");\n    } catch (std::out_of_range) {\n      POLARIS_THROW_EVALUATION_ERROR(ast,\n        \"failed to parse token into int value, std::out_of_range\");\n    }\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructDouble(std::shared_ptr<peg::Ast> ast)\n{\n  if (ast->name == \"DOUBLE\" || ast->name == \"INTEGER\") {\n    try {\n      types::TypeBase<double> double_value;\n      double_value.setValue(std::stod(ast->token));\n      return double_value;\n    } catch (std::invalid_argument) {\n      POLARIS_THROW_EVALUATION_ERROR(ast,\n        \"failed to parse token into double value, std::invalid_argument\");\n    } catch (std::out_of_range) {\n      POLARIS_THROW_EVALUATION_ERROR(ast,\n        \"failed to parse token into double value, std::out_of_range\");\n    }\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructPose(std::shared_ptr<peg::Ast> ast)\n{\n  geometry_msgs::msg::Pose pose;\n  if (ast->name == \"ARGUMENTS\") {\n    if (ast->nodes[0]->name == \"CALL\") {\n      if (ast->nodes[0]->nodes[0]->name == \"IDENTIFIER\") {\n        boost::any val = evaluate(ast->nodes[0]->nodes[0]->token, ast->nodes[0]);\n        if (ast->nodes[0]->nodes[0]->token == \"point\") {\n          if (val.type() == typeid(types::TypeBase<geometry_msgs::msg::Point>)) {\n            auto p = boost::any_cast<types::TypeBase<geometry_msgs::msg::Point>>(val).getValue();\n            pose.position = p;\n          } else {\n            POLARIS_THROW_EVALUATION_ERROR(ast,\n              \"constracting point type failed\");\n          }\n        } else {\n          POLARIS_THROW_EVALUATION_ERROR(ast,\n            \"first argument shold be point type\");\n        }\n      }\n    } else if (ast->nodes[0]->name == \"IDENTIFIER\") {\n      if (variables_.count(ast->nodes[0]->token) == 0) {\n        POLARIS_THROW_EVALUATION_ERROR(ast,\n          \"variable \" + ast->nodes[0]->token + \" did not difined.\");\n      }\n      if (variables_[ast->nodes[0]->token].type() ==\n        typeid(types::TypeBase<geometry_msgs::msg::Point>))\n      {\n        pose.position =\n          boost::any_cast<types::TypeBase<geometry_msgs::msg::Point>>(variables_[ast->nodes[0]->\n            token]).getValue();\n      }\n    } else {\n      POLARIS_THROW_EVALUATION_ERROR(ast, \"name of the node is invalid\");\n    }\n    if (ast->nodes[1]->name == \"CALL\") {\n      if (ast->nodes[1]->nodes[0]->name == \"IDENTIFIER\") {\n        boost::any val = evaluate(ast->nodes[1]->nodes[0]->token, ast->nodes[1]);\n        if (ast->nodes[1]->nodes[0]->token == \"quaternion\") {\n          if (val.type() == typeid(types::TypeBase<geometry_msgs::msg::Quaternion>)) {\n            auto q =\n              boost::any_cast<types::TypeBase<geometry_msgs::msg::Quaternion>>(val).getValue();\n            pose.orientation = q;\n          } else {\n            POLARIS_THROW_EVALUATION_ERROR(ast,\n              \"constracting quaternion type failed\");\n          }\n        } else {\n          POLARIS_THROW_EVALUATION_ERROR(ast,\n            \"second argument shold be quaternion type\");\n        }\n      }\n    } else if (ast->nodes[1]->name == \"IDENTIFIER\") {\n      if (variables_.count(ast->nodes[1]->token) == 0) {\n        POLARIS_THROW_EVALUATION_ERROR(ast,\n          \"variable \" + ast->nodes[1]->token + \" did not difined.\");\n      }\n      if (variables_[ast->nodes[1]->token].type() ==\n        typeid(types::TypeBase<geometry_msgs::msg::Quaternion>))\n      {\n        pose.orientation =\n          boost::any_cast<types::TypeBase<geometry_msgs::msg::Quaternion>>(\n          variables_[ast->nodes[1]->token]).getValue();\n      }\n    } else {\n      POLARIS_THROW_EVALUATION_ERROR(ast, \"name of the node is invalid\");\n    }\n  }\n  types::TypeBase<geometry_msgs::msg::Pose> pose_value;\n  pose_value.setValue(pose);\n  return pose_value;\n}\n\nboost::any Functions::constructPoint(std::shared_ptr<peg::Ast> ast)\n{\n  geometry_msgs::msg::Point point;\n  if (ast->name == \"ARGUMENTS\") {\n    try {\n      if (ast->nodes[0]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[0]->nodes[0]->token, ast->nodes[0]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        point.x = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[0]->name == \"IDENTIFIER\") {\n        point.x =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[0]->token]).getValue();\n      } else {\n        point.x =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[0])).getValue();\n      }\n      if (ast->nodes[1]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[1]->nodes[0]->token, ast->nodes[1]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        point.y = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[1]->name == \"IDENTIFIER\") {\n        point.y =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[1]->token]).getValue();\n      } else {\n        point.y =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[1])).getValue();\n      }\n      if (ast->nodes[2]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[2]->nodes[0]->token, ast->nodes[2]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        point.z = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[2]->name == \"IDENTIFIER\") {\n        point.z =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[2]->token]).getValue();\n      } else {\n        point.z =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[2])).getValue();\n      }\n      types::TypeBase<geometry_msgs::msg::Point> point_value;\n      point_value.setValue(point);\n      return point_value;\n    } catch (boost::bad_any_cast) {\n      POLARIS_THROW_EVALUATION_ERROR(ast,\n        \"failed to cast as double value in constructing point, boost::bad_any_cast\");\n    }\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructQuaternionFromRpy(std::shared_ptr<peg::Ast> ast)\n{\n  geometry_msgs::msg::Vector3 rpy;\n  if (ast->name == \"ARGUMENTS\") {\n    try {\n      if (ast->nodes[0]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[0]->nodes[0]->token, ast->nodes[0]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        rpy.x = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[0]->name == \"IDENTIFIER\") {\n        rpy.x =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[0]->token]).getValue();\n      } else {\n        rpy.x =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[0])).getValue();\n      }\n      if (ast->nodes[1]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[1]->nodes[0]->token, ast->nodes[1]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        rpy.y = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[1]->name == \"IDENTIFIER\") {\n        rpy.y =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[1]->token]).getValue();\n      } else {\n        rpy.y =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[1])).getValue();\n      }\n      if (ast->nodes[2]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[2]->nodes[0]->token, ast->nodes[2]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        rpy.z = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[2]->name == \"IDENTIFIER\") {\n        rpy.z =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[2]->token]).getValue();\n      } else {\n        rpy.z =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[2])).getValue();\n      }\n      types::TypeBase<geometry_msgs::msg::Quaternion> quat_value;\n      geometry_msgs::msg::Quaternion quat =\n        quaternion_operation::convertEulerAngleToQuaternion(rpy);\n      quat_value.setValue(quat);\n      return quat_value;\n    } catch (boost::bad_any_cast) {\n      POLARIS_THROW_EVALUATION_ERROR(ast,\n        \"failed to cast as double value in constructing quaternion, boost::bad_any_cast\");\n    }\n  }\n  return boost::none;\n}\n\nboost::any Functions::constructQuaternion(std::shared_ptr<peg::Ast> ast)\n{\n  geometry_msgs::msg::Quaternion quat;\n  if (ast->name == \"ARGUMENTS\") {\n    try {\n      if (ast->nodes[0]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[0]->nodes[0]->token, ast->nodes[0]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        quat.x = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[0]->name == \"IDENTIFIER\") {\n        quat.x =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[0]->token]).getValue();\n      } else {\n        quat.x =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[0])).getValue();\n      }\n      if (ast->nodes[1]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[1]->nodes[0]->token, ast->nodes[1]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        quat.y = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[1]->name == \"IDENTIFIER\") {\n        quat.y =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[1]->token]).getValue();\n      } else {\n        quat.y =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[1])).getValue();\n      }\n      if (ast->nodes[2]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[2]->nodes[0]->token, ast->nodes[2]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        quat.z = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[2]->name == \"IDENTIFIER\") {\n        quat.z =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[2]->token]).getValue();\n      } else {\n        quat.z =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[2])).getValue();\n      }\n      if (ast->nodes[3]->name == \"CALL\") {\n        auto val = evaluate(ast->nodes[3]->nodes[0]->token, ast->nodes[3]->nodes[1]);\n        if (val.type() != typeid(types::TypeBase<double>)) {\n          POLARIS_THROW_EVALUATION_ERROR(ast, \"failed to interprit as double value\");\n        }\n        quat.w = boost::any_cast<types::TypeBase<double>>(val).getValue();\n      } else if (ast->nodes[3]->name == \"IDENTIFIER\") {\n        quat.w =\n          boost::any_cast<types::TypeBase<double>>(variables_[ast->nodes[3]->token]).getValue();\n      } else {\n        quat.w =\n          boost::any_cast<types::TypeBase<double>>(constructDouble(ast->nodes[3])).getValue();\n      }\n      types::TypeBase<geometry_msgs::msg::Quaternion> quat_value;\n      quat_value.setValue(quat);\n      return quat_value;\n    } catch (boost::bad_any_cast) {\n      POLARIS_THROW_EVALUATION_ERROR(ast,\n        \"failed to cast as double value in constructing quaternion, boost::bad_any_cast\");\n    }\n  }\n  return boost::none;\n}\n\nboost::any Functions::multiplication(std::shared_ptr<peg::Ast> ast)\n{\n  auto v0 = evaluate(ast->nodes[0]->name, ast->nodes[0]);\n  auto v1 = evaluate(ast->nodes[2]->name, ast->nodes[2]);\n  // (quaternion value) * (quaternion value)\n  if (v0.type() == typeid(types::TypeBase<geometry_msgs::msg::Quaternion>) &&\n    v1.type() == typeid(types::TypeBase<geometry_msgs::msg::Quaternion>))\n  {\n    types::TypeBase<geometry_msgs::msg::Quaternion> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<geometry_msgs::msg::Quaternion>>(v0).getValue() *\n      boost::any_cast<types::TypeBase<geometry_msgs::msg::Quaternion>>(v1).getValue());\n    return ret;\n  }\n  // (double value) * (double value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() *\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (int value) * (double value)\n  if (v0.type() == typeid(types::TypeBase<int>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<int>>(v0).getValue() *\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (double value) * (int value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() *\n      boost::any_cast<types::TypeBase<int>>(v1).getValue());\n    return ret;\n  }\n  // (int value) * (int value)\n  if (v0.type() == typeid(types::TypeBase<int>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<int> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<int>>(v0).getValue() *\n      boost::any_cast<types::TypeBase<int>>(v1).getValue());\n    return ret;\n  }\n  POLARIS_THROW_EVALUATION_ERROR(ast, \"multiplication operators did not defined yet.\");\n}\n\nboost::any Functions::division(std::shared_ptr<peg::Ast> ast)\n{\n  auto v0 = evaluate(ast->nodes[0]->name, ast->nodes[0]);\n  auto v1 = evaluate(ast->nodes[2]->name, ast->nodes[2]);\n  // (double value) * (double value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() /\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (int value) * (double value)\n  if (v0.type() == typeid(types::TypeBase<int>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<int>>(v0).getValue() /\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (double value) * (int value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() /\n      boost::any_cast<types::TypeBase<int>>(v1).getValue());\n    return ret;\n  }\n  // (int value) * (int value)\n  if (v0.type() == typeid(types::TypeBase<int>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<int> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<int>>(v0).getValue() /\n      boost::any_cast<types::TypeBase<int>>(v1).getValue());\n    return ret;\n  }\n  POLARIS_THROW_EVALUATION_ERROR(ast, \"division operators did not defined yet.\");\n}\n\nboost::any Functions::subtraction(std::shared_ptr<peg::Ast> ast)\n{\n  auto v0 = evaluate(ast->nodes[0]->name, ast->nodes[0]);\n  auto v1 = evaluate(ast->nodes[2]->name, ast->nodes[2]);\n  // (double value) - (double value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() -\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (int value) - (double value)\n  if (v0.type() == typeid(types::TypeBase<int>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(static_cast<double>(boost::any_cast<types::TypeBase<int>>(v0).getValue()) -\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (double value) - (int value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() -\n      static_cast<double>(boost::any_cast<types::TypeBase<int>>(v1).getValue()));\n    return ret;\n  }\n  // (int value) - (int value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<int> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<int>>(v0).getValue() -\n      boost::any_cast<types::TypeBase<int>>(v1).getValue());\n    return ret;\n  }\n  POLARIS_THROW_EVALUATION_ERROR(ast, \"subcraction operators did not defined yet.\");\n}\n\nboost::any Functions::addition(std::shared_ptr<peg::Ast> ast)\n{\n  auto v0 = evaluate(ast->nodes[0]->name, ast->nodes[0]);\n  auto v1 = evaluate(ast->nodes[2]->name, ast->nodes[2]);\n  // (double value) + (double value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() +\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (int value) + (double value)\n  if (v0.type() == typeid(types::TypeBase<int>) &&\n    v1.type() == typeid(types::TypeBase<double>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(static_cast<double>(boost::any_cast<types::TypeBase<int>>(v0).getValue()) +\n      boost::any_cast<types::TypeBase<double>>(v1).getValue());\n    return ret;\n  }\n  // (double value) + (int value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<double> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<double>>(v0).getValue() +\n      static_cast<double>(boost::any_cast<types::TypeBase<int>>(v1).getValue()));\n    return ret;\n  }\n  // (int value) + (int value)\n  if (v0.type() == typeid(types::TypeBase<double>) &&\n    v1.type() == typeid(types::TypeBase<int>))\n  {\n    types::TypeBase<int> ret;\n    ret.setValue(boost::any_cast<types::TypeBase<int>>(v0).getValue() +\n      boost::any_cast<types::TypeBase<int>>(v1).getValue());\n    return ret;\n  }\n  POLARIS_THROW_EVALUATION_ERROR(ast, \"addition operators did not defined yet.\");\n}\n}  // namespace built_in_functions\n}  // namespace polaris\n", "meta": {"hexsha": "1b9934b7189e6832744e42304e860c82d5beebaa", "size": 27949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/built_in_functions/functions.cpp", "max_stars_repo_name": "OUXT-Polaris/polaris", "max_stars_repo_head_hexsha": "43ff1b949609196687aa29969f3359c5a676f997", "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/built_in_functions/functions.cpp", "max_issues_repo_name": "OUXT-Polaris/polaris", "max_issues_repo_head_hexsha": "43ff1b949609196687aa29969f3359c5a676f997", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/built_in_functions/functions.cpp", "max_forks_repo_name": "OUXT-Polaris/polaris", "max_forks_repo_head_hexsha": "43ff1b949609196687aa29969f3359c5a676f997", "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.6439716312, "max_line_length": 98, "alphanum_fraction": 0.6288239293, "num_tokens": 7492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934935817440722, "lm_q2_score": 0.022629199415092085, "lm_q1q2_score": 0.005416284356002962}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2016 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#define BOOST_PYTHON_MAX_ARITY 46\n#include <boost/python.hpp>\n#include <cmath>\n#include <iostream>\n#include <functional>\n\n#include \"numpy_bind.hh\"\n\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n#include \"graph_filtering.hh\"\n\n#include \"graph.hh\"\n#include \"graph_selectors.hh\"\n#include \"graph_properties.hh\"\n#include \"graph_util.hh\"\n#include \"graph_python_interface.hh\"\n\n#include \"random.hh\"\n\n#include \"config.h\"\n\n#include \"graph_blockmodel_covariates.hh\"\n#include \"graph_blockmodel.hh\"\n#include \"graph_blockmodel_overlap.hh\"\n\nusing namespace graph_tool;\nusing namespace std;\n\n\ntemplate <class Eprop, class Vprop, class VVprop, class VEprop, class BMap>\nstruct cov_move_sweep_dispatch\n{\n    cov_move_sweep_dispatch(Eprop ce, VVprop cv, VVprop vmap,\n                            vector<std::reference_wrapper<Eprop>>& eweight,\n                            vector<std::reference_wrapper<Vprop>>& vweight,\n                            vector<std::reference_wrapper<boost::any>>& egroups,\n                            vector<std::reference_wrapper<VEprop>>& esrcpos,\n                            vector<std::reference_wrapper<VEprop>>& etgtpos,\n                            Vprop& label, vector<int>& vlist, bool deg_corr,\n                            bool dense, bool multigraph, double beta,\n                            bool sequential, bool parallel, bool random_move,\n                            bool node_coherent, bool confine_layers, double c,\n                            bool verbose, size_t meindex,\n                            vector<size_t> max_edge_index, size_t nmerges,\n                            size_t niter, Vprop merge_map,\n                            vector<std::reference_wrapper<partition_stats_t>>& partition_stats,\n                            vector<std::reference_wrapper<overlap_partition_stats_t>>& overlap_partition_stats,\n                            vector<std::reference_wrapper<overlap_stats_t>>& overlap_stats,\n                            vector<bool>& master, vector<bool>& slave,\n                            rng_t& rng, double& S, size_t& nmoves,\n                            vector<std::reference_wrapper<GraphInterface>>& bgi,\n                            BMap& block_map,\n                            vector<std::reference_wrapper<Vprop>>& block_rmap,\n                            vector<std::reference_wrapper<vector<size_t>>>& free_blocks,\n                            size_t B)\n\n        : ce(ce), cv(cv), vmap(vmap), eweight(eweight), vweight(vweight),\n          oegroups(egroups), esrcpos(esrcpos), etgtpos(etgtpos), label(label), vlist(vlist),\n          deg_corr(deg_corr), dense(dense), multigraph(multigraph), beta(beta),\n          sequential(sequential), parallel(parallel), random_move(random_move),\n          node_coherent(node_coherent), confine_layers(confine_layers),\n          c(c), verbose(verbose), meindex(meindex),\n          max_edge_index(max_edge_index),\n          nmerges(nmerges), niter(niter), merge_map(merge_map),\n          partition_stats(partition_stats),\n          overlap_partition_stats(overlap_partition_stats),\n          overlap_stats(overlap_stats),\n          master(master), slave(slave),\n          rng(rng), S(S), nmoves(nmoves), bgi(bgi), block_map(block_map),\n          block_rmap(block_rmap), free_blocks(free_blocks), B(B)\n    {}\n\n    Eprop ce;\n    VVprop cv;\n    VVprop vmap;\n    vector<std::reference_wrapper<Eprop>>& eweight;\n    vector<std::reference_wrapper<Vprop>>& vweight;\n    vector<std::reference_wrapper<boost::any>> oegroups;\n    vector<std::reference_wrapper<VEprop>>& esrcpos;\n    vector<std::reference_wrapper<VEprop>>& etgtpos;\n    Vprop& label;\n    size_t n;\n    vector<int>& vlist;\n    bool deg_corr;\n    bool dense;\n    bool multigraph;\n    double beta;\n    bool sequential;\n    bool parallel;\n    bool random_move;\n    bool node_coherent;\n    bool confine_layers;\n    double c;\n    bool verbose;\n    size_t meindex;\n    vector<size_t> max_edge_index;\n    size_t nmerges;\n    size_t niter;\n    Vprop merge_map;\n    vector<std::reference_wrapper<partition_stats_t>>& partition_stats;\n    vector<std::reference_wrapper<overlap_partition_stats_t>>& overlap_partition_stats;\n    vector<std::reference_wrapper<overlap_stats_t>>& overlap_stats;\n    vector<bool> master;\n    vector<bool> slave;\n    rng_t& rng;\n    double& S;\n    size_t& nmoves;\n    vector<std::reference_wrapper<GraphInterface>>& bgi;\n    BMap& block_map;\n    vector<std::reference_wrapper<Vprop>>& block_rmap;\n    vector<std::reference_wrapper<vector<size_t>>>& free_blocks;\n    size_t B;\n\n    template <class Graph>\n    void operator()(vector<std::reference_wrapper<Eprop>>& mrs,\n                    vector<std::reference_wrapper<Vprop>>& mrp,\n                    vector<std::reference_wrapper<Vprop>>& mrm,\n                    vector<std::reference_wrapper<Vprop>>& wr,\n                    Vprop& b, vector<std::reference_wrapper<Vprop>>& bs,\n                    vector<std::reference_wrapper<GraphInterface>>& bgis, Graph& g,\n                    vector<std::reference_wrapper<GraphInterface>>& ags,\n                    vector<std::reference_wrapper<boost::any>>& emat,\n                    vector<std::reference_wrapper<boost::any>>& sampler,\n                    vector<std::reference_wrapper<boost::any>>& cavity_sampler,\n                    bool weighted) const\n    {\n        vector<std::reference_wrapper<Graph>> gs;\n        for (GraphInterface& ag : ags)\n            gs.push_back(*any_cast<Graph*>(ag.GetGraphView()));\n\n        if (is_directed::apply<Graph>::type::value)\n        {\n            vector<std::reference_wrapper<GraphInterface::multigraph_t>> bgs;\n            for (GraphInterface& bgi : bgis)\n                bgs.push_back(bgi.GetGraph());\n            dispatch(mrs, mrp, mrm, wr, b, bs, g, gs, emat, sampler,\n                     cavity_sampler, bgs, weighted);\n        }\n        else\n        {\n            vector<UndirectedAdaptor<GraphInterface::multigraph_t>> ubgs;\n            for (GraphInterface& bgi : bgis)\n                ubgs.push_back(UndirectedAdaptor<GraphInterface::multigraph_t>(bgi.GetGraph()));\n            vector<std::reference_wrapper<UndirectedAdaptor<GraphInterface::multigraph_t>>> rubgs;\n            for (auto& bg : ubgs)\n                rubgs.push_back(bg);\n            dispatch(mrs, mrp, mrm, wr, b, bs, g, gs, emat, sampler,\n                     cavity_sampler, rubgs, weighted);\n        }\n    }\n\n    template <class Graph, class BGraph>\n    void dispatch(vector<std::reference_wrapper<Eprop>>& mrs,\n                  vector<std::reference_wrapper<Vprop>>& mrp,\n                  vector<std::reference_wrapper<Vprop>>& mrm,\n                  vector<std::reference_wrapper<Vprop>>& wr,\n                  Vprop& b,\n                  vector<std::reference_wrapper<Vprop>>& bs, Graph& g,\n                  vector<std::reference_wrapper<Graph>>& gs,\n                  vector<std::reference_wrapper<boost::any>>& aemat,\n                  vector<std::reference_wrapper<boost::any>>& asampler,\n                  vector<std::reference_wrapper<boost::any>>& acavity_sampler,\n                  vector<std::reference_wrapper<BGraph>>& bg,\n                  bool weighted) const\n    {\n        if (weighted)\n        {\n            typedef typename property_map_type::apply<DynamicSampler<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,\n                                                      GraphInterface::vertex_index_map_t>::type vemap_t;\n            vector<std::reference_wrapper<vemap_t>> egroups;\n            for (auto& eg : oegroups)\n                egroups.push_back(any_cast<vemap_t&>(eg));\n\n            try\n            {\n                typedef typename get_emat_t::apply<BGraph>::type emat_t;\n                vector<std::reference_wrapper<emat_t>> emat;\n                for (auto& m : aemat)\n                    emat.push_back(any_cast<emat_t&>(m));\n                size_t B = num_vertices(bg[0].get());\n                size_t max_BE = is_directed::apply<Graph>::type::value ?\n                    B * B : (B * (B + 1)) / 2;\n                vector<typename Eprop::unchecked_t> umrs;\n                for (auto& m : mrs)\n                    umrs.push_back(m.get().get_unchecked(max_BE));\n                vector<std::reference_wrapper<typename Eprop::unchecked_t>> rumrs;\n                for (auto& m : umrs)\n                    rumrs.push_back(m);\n                dispatch(rumrs, mrp, mrm, wr, b, bs, g, gs, asampler,\n                         acavity_sampler, bg, egroups, emat);\n            }\n            catch (bad_any_cast)\n            {\n                typedef typename get_ehash_t::apply<BGraph>::type emat_t;\n                vector<std::reference_wrapper<emat_t>> emat;\n                for (auto& m : aemat)\n                    emat.push_back(any_cast<emat_t&>(m));\n                dispatch(mrs, mrp, mrm, wr, b, bs, g, gs, asampler,\n                         acavity_sampler, bg, egroups, emat);\n            }\n        }\n        else\n        {\n            typedef typename property_map_type::apply<vector<std::tuple<typename graph_traits<Graph>::edge_descriptor, bool> >,\n                                                      GraphInterface::vertex_index_map_t>::type vemap_t;\n            vector<std::reference_wrapper<vemap_t>> egroups;\n            for (auto& eg : oegroups)\n                egroups.push_back(any_cast<vemap_t&>(eg));\n\n            try\n            {\n                typedef typename get_emat_t::apply<BGraph>::type emat_t;\n                vector<std::reference_wrapper<emat_t>> emat;\n                for (auto& m : aemat)\n                    emat.push_back(any_cast<emat_t&>(m));\n                dispatch(mrs, mrp, mrm, wr, b, bs, g, gs, asampler,\n                         acavity_sampler, bg, egroups, emat);\n            }\n            catch (bad_any_cast)\n            {\n                typedef typename get_ehash_t::apply<BGraph>::type emat_t;\n                vector<std::reference_wrapper<emat_t>> emat;\n                for (auto& m : aemat)\n                    emat.push_back(any_cast<emat_t&>(m));\n                dispatch(mrs, mrp, mrm, wr, b, bs, g, gs, asampler,\n                         acavity_sampler, bg, egroups, emat);\n            }\n        }\n    }\n\n    template <class Graph, class BGraph, class Egroups, class Emat, class EMprop>\n    void dispatch(vector<std::reference_wrapper<EMprop>>& mrs,\n                  vector<std::reference_wrapper<Vprop>>& mrp,\n                  vector<std::reference_wrapper<Vprop>>& mrm,\n                  vector<std::reference_wrapper<Vprop>>& wr,\n                  Vprop& b,\n                  vector<std::reference_wrapper<Vprop>>& bs, Graph& g,\n                  vector<std::reference_wrapper<Graph>>& gs,\n                  vector<std::reference_wrapper<boost::any>>& asampler,\n                  vector<std::reference_wrapper<boost::any>>& acavity_sampler,\n                  vector<std::reference_wrapper<BGraph>>& bgs,\n                  vector<std::reference_wrapper<Egroups>>& egroups,\n                  vector<std::reference_wrapper<Emat>>& emat) const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n\n        typedef typename property_map<Graph, vertex_index_t>::type vindex_map_t;\n        typedef typename property_map_type::apply<Sampler<vertex_t, boost::mpl::false_>,\n                                                  vindex_map_t>::type::unchecked_t\n            sampler_map_t;\n\n        vector<std::reference_wrapper<sampler_map_t>> sampler;\n        for (auto& s : asampler)\n            sampler.push_back(any_cast<sampler_map_t&>(s.get()));\n        vector<std::reference_wrapper<sampler_map_t>> cavity_sampler;\n        for (auto& s : acavity_sampler)\n            cavity_sampler.push_back(any_cast<sampler_map_t&>(s.get()));\n\n        bool overlap = overlap_stats[0].get().is_enabled();\n        if (!overlap)\n        {\n            typedef BlockState<Graph, BGraph, EMprop,\n                               typename Eprop::unchecked_t,\n                               typename Vprop::unchecked_t, Emat,\n                               typename Egroups::unchecked_t,\n                               typename VEprop::unchecked_t, sampler_map_t,\n                               partition_stats_t,\n                               overlap_stats_t,\n                               typename BMap::value_type,\n                               typename Vprop::unchecked_t> state_t;\n\n            vector<state_t> states;\n            vector<EntrySet<Graph>> m_entries;\n            overlap_stats_t ostats;\n\n            for (size_t i = 0; i < mrs.size(); ++i)\n            {\n                size_t eidx = random_move ? 1 : max_edge_index[i];\n\n                state_t state = make_block_state(gs[i].get(),\n                                                 eweight[i].get().get_unchecked(max_edge_index[i]),\n                                                 vweight[i].get().get_unchecked(num_vertices(gs[i].get())),\n                                                 bs[i].get().get_unchecked(num_vertices(gs[i].get())),\n                                                 bgs[i].get(),\n                                                 emat[i].get(),\n                                                 mrs[i].get(),\n                                                 mrp[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 mrm[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 wr[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 egroups[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 esrcpos[i].get().get_unchecked(eidx),\n                                                 etgtpos[i].get().get_unchecked(eidx),\n                                                 sampler[i].get(), cavity_sampler[i].get(),\n                                                 partition_stats[i].get(), ostats,\n                                                 block_map[i],\n                                                 block_rmap[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 free_blocks[i].get(),\n                                                 master[i],\n                                                 slave[i],\n                                                 false);\n                states.push_back(state);\n                m_entries.emplace_back(num_vertices(bgs[i].get()));\n            }\n\n            move_sweep(states, m_entries,\n                       wr[0].get().get_unchecked(B),\n                       b.get_unchecked(num_vertices(g)),\n                       cv.get_unchecked(num_vertices(g)),\n                       vmap.get_unchecked(num_vertices(g)),\n                       label.get_unchecked(B),\n                       vlist, deg_corr,\n                       dense, multigraph, beta,\n                       eweight[0].get().get_unchecked(max_edge_index[0]),\n                       vweight[0].get().get_unchecked(num_vertices(g)),\n                       g, sequential, parallel, random_move, c,\n                       nmerges,\n                       merge_map.get_unchecked(num_vertices(g)),\n                       niter, B,\n                       verbose, rng, S, nmoves);\n        }\n        else\n        {\n            typedef BlockState<Graph, BGraph, EMprop,\n                               typename Eprop::unchecked_t,\n                               typename Vprop::unchecked_t, Emat,\n                               typename Egroups::unchecked_t,\n                               typename VEprop::unchecked_t, sampler_map_t,\n                               overlap_partition_stats_t,\n                               overlap_stats_t,\n                               typename BMap::value_type,\n                               typename Vprop::unchecked_t> state_t;\n\n            vector<state_t> states;\n            for (size_t i = 0; i < mrs.size(); ++i)\n            {\n                size_t eidx = random_move ? 1 : max_edge_index[i];\n\n                state_t state = make_block_state(gs[i].get(),\n                                                 eweight[i].get().get_unchecked(max_edge_index[i]),\n                                                 vweight[i].get().get_unchecked(num_vertices(gs[i].get())),\n                                                 bs[i].get().get_unchecked(num_vertices(gs[i].get())),\n                                                 bgs[i].get(),\n                                                 emat[i].get(),\n                                                 mrs[i].get(),\n                                                 mrp[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 mrm[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 wr[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 egroups[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 esrcpos[i].get().get_unchecked(eidx),\n                                                 etgtpos[i].get().get_unchecked(eidx),\n                                                 sampler[i].get(), cavity_sampler[i].get(),\n                                                 overlap_partition_stats[i].get(),\n                                                 overlap_stats[i].get(),\n                                                 block_map[i],\n                                                 block_rmap[i].get().get_unchecked(num_vertices(bgs[i].get())),\n                                                 free_blocks[i].get(),\n                                                 master[i],\n                                                 slave[i],\n                                                 false);\n                states.push_back(state);\n            }\n            vector<SingleEntrySet<Graph>> m_entries(states.size());\n\n            if (nmerges == 0)\n            {\n                if (!node_coherent)\n                {\n                    move_sweep_overlap(states, m_entries, overlap_stats[0].get(),\n                                       wr[0].get().get_unchecked(B),\n                                       b.get_unchecked(num_vertices(g)), cv,\n                                       vmap, label.get_unchecked(B),\n                                       vlist, deg_corr, dense, multigraph, beta,\n                                       vweight[0].get().get_unchecked(num_vertices(g)), g,\n                                       sequential, parallel, random_move, c, niter,\n                                       B, verbose, rng, S, nmoves);\n                }\n                else\n                {\n                    vector<EntrySet<Graph>> m_entries;\n                    for (auto& state : states)\n                        m_entries.emplace_back(num_vertices(state.bg));\n                    coherent_move_sweep_overlap(states, m_entries, overlap_stats[0].get(),\n                                                wr[0].get().get_unchecked(B),\n                                                b.get_unchecked(num_vertices(g)), cv,\n                                                vmap, label.get_unchecked(B),\n                                                vlist, deg_corr, dense, multigraph, beta,\n                                                vweight[0].get().get_unchecked(num_vertices(g)), g,\n                                                sequential, random_move, c,\n                                                confine_layers, niter,\n                                                B, rng, S, nmoves);\n                }\n            }\n            else\n            {\n                merge_sweep_overlap(states, m_entries, overlap_stats[0].get(),\n                                    wr[0].get().get_unchecked(B),\n                                    b.get_unchecked(num_vertices(g)), ce, cv,\n                                    vmap, label.get_unchecked(B), vlist,\n                                    deg_corr, dense, multigraph, g,\n                                    random_move, confine_layers, nmerges, niter,\n                                    B, rng, S, nmoves);\n            }\n        }\n    }\n};\n\ntemplate <class Type>\nvector<Type> from_list(boost::python::object list)\n{\n    vector<Type> v;\n    for (int i = 0; i < boost::python::len(list); ++i)\n        v.push_back(boost::python::extract<Type>(list[i])());\n    return v;\n};\n\ntemplate <class Type>\nvector<std::reference_wrapper<Type>> from_rlist(boost::python::object list)\n{\n    vector<std::reference_wrapper<Type>> v;\n    for (int i = 0; i < boost::python::len(list); ++i)\n        v.emplace_back(boost::python::extract<Type&>(list[i])());\n    return v;\n};\n\ntemplate <class Type>\nvector<std::reference_wrapper<Type>> from_any_list(boost::python::object list)\n{\n    vector<std::reference_wrapper<Type>> v;\n    for (int i = 0; i < boost::python::len(list); ++i)\n        v.emplace_back(any_cast<Type&>(boost::python::extract<boost::any&>(list[i])()));\n    return v;\n};\n\nboost::python::object do_cov_move_sweep(GraphInterface& gi,\n                                        boost::any& oce,\n                                        boost::any& ocv,\n                                        boost::any& ovmap,\n                                        boost::python::object& ogis,\n                                        boost::python::object& obgi,\n                                        boost::python::object& oemat,\n                                        boost::python::object& osampler,\n                                        boost::python::object& ocavity_sampler,\n                                        boost::python::object& omrs,\n                                        boost::python::object& omrp,\n                                        boost::python::object& omrm,\n                                        boost::python::object& owr,\n                                        boost::any& ob,\n                                        boost::python::object& obs,\n                                        bmap_t& bmap,\n                                        boost::python::object& obrmap,\n                                        boost::python::object& ofree_blocks,\n                                        boost::python::object& omaster,\n                                        boost::python::object& oslave,\n                                        boost::any& olabel, vector<int>& vlist,\n                                        bool deg_corr, bool dense,\n                                        bool multigraph,\n                                        boost::python::object& oeweight,\n                                        boost::python::object& ovweight,\n                                        boost::python::object& oegroups,\n                                        boost::python::object& oesrcpos,\n                                        boost::python::object& oetgtpos,\n                                        double beta, bool sequential,\n                                        bool parallel, bool random_move,\n                                        boost::python::object onode_coherent,\n                                        double c, bool weighted, size_t nmerges,\n                                        boost::any omerge_map,\n                                        size_t niter,\n                                        size_t B,\n                                        boost::python::object& opartition_stats,\n                                        boost::python::object& ooverlap_partition_stats,\n                                        boost::python::object& ooverlap_stats,\n                                        bool verbose, rng_t& rng)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n    auto mrs = from_any_list<emap_t>(omrs);\n    auto mrp = from_any_list<vmap_t>(omrp);\n    auto mrm = from_any_list<vmap_t>(omrm);\n    auto wr = from_any_list<vmap_t>(owr);\n    vmap_t b = any_cast<vmap_t>(ob);\n    auto bs = from_any_list<vmap_t>(obs);\n\n    auto brmap = from_any_list<vmap_t>(obrmap);\n    auto free_blocks = from_rlist<vector<size_t>>(ofree_blocks);\n\n    auto eweight = from_any_list<emap_t>(oeweight);\n    auto vweight = from_any_list<vmap_t>(ovweight);\n    auto egroups = from_rlist<boost::any>(oegroups);\n    auto esrcpos = from_any_list<emap_t>(oesrcpos);\n    auto etgtpos = from_any_list<emap_t>(oetgtpos);\n\n    vmap_t label = any_cast<vmap_t>(olabel);\n    emap_t ce = any_cast<emap_t>(oce);\n    vvmap_t cv = any_cast<vvmap_t>(ocv);\n    vvmap_t vmap = any_cast<vvmap_t>(ovmap);\n\n    double S = 0;\n    size_t nmoves = 0;\n\n    vmap_t merge_map = any_cast<vmap_t>(omerge_map);\n\n    auto gis = from_rlist<GraphInterface>(ogis);\n\n    vector<size_t> eidx;\n    for (GraphInterface& g : gis)\n        eidx.push_back(g.GetMaxEdgeIndex());\n\n    auto bgi = from_rlist<GraphInterface>(obgi);\n\n    auto partition_stats = from_rlist<partition_stats_t>(opartition_stats);\n    auto overlap_partition_stats = from_rlist<overlap_partition_stats_t>(ooverlap_partition_stats);\n    auto overlap_stats = from_rlist<overlap_stats_t>(ooverlap_stats);\n\n    auto emat = from_rlist<boost::any>(oemat);\n\n    auto sampler = from_rlist<boost::any>(osampler);\n    auto cavity_sampler = from_rlist<boost::any>(ocavity_sampler);\n\n    auto master = from_list<bool>(omaster);\n    auto slave = from_list<bool>(oslave);\n\n\n    bool node_coherent = python::extract<bool>(onode_coherent[0]);\n    bool confine_layers = python::extract<bool>(onode_coherent[1]);\n\n    run_action<graph_tool::detail::all_graph_views, boost::mpl::true_>()\n        (gi, std::bind(cov_move_sweep_dispatch<emap_t, vmap_t, vvmap_t, emap_t, bmap_t>\n                       (ce, cv, vmap, eweight, vweight, egroups, esrcpos, etgtpos,\n                        label, vlist, deg_corr, dense, multigraph, beta,\n                        sequential, parallel, random_move, node_coherent,\n                        confine_layers, c, verbose,\n                        gi.GetMaxEdgeIndex(), eidx, nmerges, niter, merge_map,\n                        partition_stats, overlap_partition_stats, overlap_stats,\n                        master, slave, rng, S, nmoves, bgi, bmap, brmap, free_blocks, B),\n                       std::ref(mrs), std::ref(mrp), std::ref(mrm), std::ref(wr),\n                       std::ref(b), std::ref(bs), std::ref(bgi), placeholders::_1, std::ref(gis),\n                       std::ref(emat), std::ref(sampler), std::ref(cavity_sampler), weighted))();\n\n    return boost::python::make_tuple(S, nmoves);\n}\n\nstruct covariate_entropy\n{\n    template <class Graph, class Emap>\n    void operator()(Graph& bg, Emap mrs, double& S) const\n    {\n        for (auto e : edges_range(bg))\n            S -= lgamma_fast(mrs[e] + 1);\n    }\n};\n\ndouble do_covariate_entropy(GraphInterface& gi, boost::any omrs)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    emap_t mrs = any_cast<emap_t>(omrs);\n\n    double S = 0;\n    run_action<>()\n        (gi, std::bind(covariate_entropy(),\n                       placeholders::_1, mrs, std::ref(S)))();\n    return S;\n}\n\n// void do_create_echash(GraphInterface& gi, size_t l, size_t L,\n//                       boost::any& emat_orig, boost::any& emat)\n// {\n//     run_action<>()(gi, std::bind<void>(create_echash(), placeholders::_1, l, L,\n//                                        std::ref(emat_orig), std::ref(emat)))();\n// }\n\nvoid do_ec_hist(GraphInterface& gi, boost::any& aevc, boost::any& aec)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n    typename emap_t::unchecked_t ec =\n        any_cast<emap_t&>(aec).get_unchecked(gi.GetMaxEdgeIndex());\n    run_action<>()(gi, std::bind<void>(ec_hist(), placeholders::_1,\n                                       placeholders::_2, std::ref(ec)),\n                   edge_properties())(aevc);\n}\n\n\nvoid do_split_graph(GraphInterface& gi, boost::any& aec, boost::any& ab,\n                    boost::any& aeweight, boost::any& avweight, boost::any& avc,\n                    boost::any& avmap, boost::python::object& ous,\n                    boost::python::object& oub,\n                    boost::python::object& oueweight,\n                    boost::python::object& ouvweight,\n                    bmap_t& bmap,\n                    boost::python::object& obrmap,\n                    boost::python::object& ouvmap)\n{\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::vertex_index_map_t>::type\n        vmap_t;\n    typedef property_map_type::apply<vector<int32_t>,\n                                     GraphInterface::vertex_index_map_t>::type\n        vvmap_t;\n    typedef property_map_type::apply<int32_t,\n                                     GraphInterface::edge_index_map_t>::type\n        emap_t;\n\n    emap_t& ec = any_cast<emap_t&>(aec);\n    vmap_t& b = any_cast<vmap_t&>(ab);\n    vmap_t& vweight = any_cast<vmap_t&>(avweight);\n    emap_t& eweight = any_cast<emap_t&>(aeweight);\n    vvmap_t& vc = any_cast<vvmap_t&>(avc);\n    vvmap_t& vmap = any_cast<vvmap_t&>(avmap);\n\n    auto us = from_rlist<GraphInterface>(ous);\n    auto ub = from_any_list<vmap_t>(oub);\n    auto uvweight = from_any_list<vmap_t>(ouvweight);\n    auto ueweight = from_any_list<emap_t>(oueweight);\n\n    auto rbmap = from_any_list<vmap_t>(obrmap);\n    auto uvmap = from_any_list<vmap_t>(ouvmap);\n\n    run_action<>()(gi, std::bind<void>(split_graph(), placeholders::_1,\n                                       std::ref(ec), std::ref(b), std::ref(eweight),\n                                       std::ref(vweight), std::ref(vc),\n                                       std::ref(vmap), std::ref(us),\n                                       std::ref(ub),\n                                       std::ref(uvweight), std::ref(ueweight),\n                                       std::ref(bmap), std::ref(rbmap),\n                                       std::ref(uvmap)))();\n}\n\nbool bmap_has(const bmap_t& bmap, size_t c, size_t r)\n{\n    if (c > bmap.size())\n        throw GraphException(\"invalid covariate value:\" + lexical_cast<string>(c));\n    auto iter = bmap[c].find(r);\n    if (iter == bmap[c].end())\n        return false;\n    return true;\n}\n\nsize_t bmap_get(const bmap_t& bmap, size_t c, size_t r)\n{\n    if (c > bmap.size())\n        throw GraphException(\"invalid covariate value:\" + lexical_cast<string>(c));\n    auto iter = bmap[c].find(r);\n    if (iter == bmap[c].end())\n        throw GraphException(\"no mapping for block \" + lexical_cast<string>(r)\n                             + \" in layer \" + lexical_cast<string>(c));\n    return iter->second;\n}\n\nvoid bmap_set(bmap_t& bmap, size_t c, size_t r, size_t r_u)\n{\n    if (c > bmap.size())\n        throw GraphException(\"invalid covariate value:\" + lexical_cast<string>(c));\n    bmap[c][r] = r_u;\n}\n\nvoid bmap_del_c(bmap_t& bmap, size_t c)\n{\n    if (c > bmap.size())\n        throw GraphException(\"invalid covariate value:\" + lexical_cast<string>(c));\n    bmap.erase(bmap.begin() + c);\n}\n\nbmap_t bmap_copy(const bmap_t& bmap)\n{\n    return bmap;\n}\n\n\nvoid export_blockmodel_covariate()\n{\n    boost::python::class_<bmap_t>(\"bmap_t\")\n        .def(\"has\", bmap_has)\n        .def(\"get\", bmap_get)\n        .def(\"set\", bmap_set)\n        .def(\"del_c\", bmap_del_c)\n        .def(\"copy\", bmap_copy);\n\n    boost::python::def(\"cov_move_sweep\", do_cov_move_sweep);\n    boost::python::def(\"covariate_entropy\", do_covariate_entropy);\n    // boost::python::def(\"create_echash\", do_create_echash);\n    boost::python::def(\"ec_hist\", do_ec_hist);\n    boost::python::def(\"split_graph\", do_split_graph);\n}\n", "meta": {"hexsha": "bb4bb04d0cef8f79baf8179369cc29b88f62198f", "size": 33016, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/community/graph_blockmodel_covariates.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/community/graph_blockmodel_covariates.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/community/graph_blockmodel_covariates.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": 46.3057503506, "max_line_length": 135, "alphanum_fraction": 0.5112975527, "num_tokens": 6940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748935136304, "lm_q2_score": 0.015189046551155437, "lm_q1q2_score": 0.0054038814193109}}
{"text": "﻿// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-\n#include <arcane/ItemPrinter.h>\n#include <vector>\n\n#include <boost/static_assert.hpp>\n\n#include \"Numerics/DiscreteOperator/AdvectionUpwind/AdvectionUpwindService.h\"\n\n#include \"Utils/ItemGroupBuilder.h\"\n\n#include \"Appli/IAppServiceMng.h\"\n#include \"Numerics/BCs/IBoundaryCondition.h\"\n\nusing namespace Arcane;\n\nvoid AdvectionUpwindService::init() {\n  if( m_initialized ) return;\n\n  // Retrieve and initialize application service manager\n  IAppServiceMng* app_service_mng = IAppServiceMng::instance(subDomain()->serviceMng());\n  \n  // Retrieve shared geometry service  \n  m_geometry_service = app_service_mng->find<IGeometryMng>(true);\n\n  m_cells_group_name = IMPLICIT_UNIQ_NAME;\n  m_faces_group_name = IMPLICIT_UNIQ_NAME;\n\n  m_theta_upwind = options()->thetaUpwind();\n  \n  m_initialized = true;\n}\n\n////////////////////////////////////////////////////////////\n\nvoid AdvectionUpwindService::prepare(const FaceGroup& internal_faces,\n\t\t\t\t     const FaceGroup& boundary_faces,\n\t\t\t\t     FaceGroup& c_internal_faces,\n\t\t\t\t     FaceGroup& cf_internal_faces,\n\t\t\t\t     CoefficientArrayT<Cell>* cell_coefficients,\n\t\t\t\t     CoefficientArrayT<Face>* face_coefficients) {\n\n  if( !m_initialized )\n    error() << \" Numerical service not initialized\";\n\n  m_internal_faces = internal_faces;\n  m_boundary_faces = boundary_faces;\n  \n  m_cell_coefficients = cell_coefficients;\n  m_face_coefficients = face_coefficients;\n\n  // Form face and cell groups\n  ItemGroupBuilder<Face> faces_builder(m_internal_faces.mesh(), m_faces_group_name);\n  faces_builder.add(m_internal_faces.enumerator());\n  faces_builder.add(m_boundary_faces.enumerator());\n  m_faces = faces_builder.buildGroup();\n\n  ItemGroupBuilder<Face> c_internal_faces_builder(m_internal_faces.mesh(), \n                                                  c_internal_faces.name());\n  c_internal_faces_builder.add(m_internal_faces.enumerator());\n  m_c_internal_faces = c_internal_faces_builder.buildGroup();  \n\n  ItemGroupBuilder<Face> cf_internal_faces_builder(m_internal_faces.mesh(),\n                                                   cf_internal_faces.name());\n  m_cf_internal_faces = cf_internal_faces_builder.buildGroup(); // Empty group\n\n  ItemGroupBuilder<Cell> cells_builder(m_internal_faces.mesh(), m_cells_group_name);\n\n  ItemGroupMapT<Face, Integer> cell_stencil_sizes(m_faces);\n  ItemGroupMapT<Face, Integer> face_stencil_sizes(m_faces);\n\n  ENUMERATE_FACE(iF, m_internal_faces) {\n    const Face& F = *iF;\n\n    cells_builder.add(F.cells());\n\n    cell_stencil_sizes[F] = 2;\n    face_stencil_sizes[F] = 0;\n  }\n\n  ENUMERATE_FACE(iF, m_boundary_faces) {\n    const Face& F = *iF;\n\n    cells_builder.add(F.cells());\n\n    cell_stencil_sizes[F] = 1;\n    face_stencil_sizes[F] = 1;\n  }\n  m_cells = cells_builder.buildGroup();  \n\n  // Compute stencils\n  m_cell_coefficients->init(cell_stencil_sizes);\n  m_face_coefficients->init(face_stencil_sizes);\n\n  ENUMERATE_FACE(iF, m_internal_faces) {\n    const Face& F = *iF;\n\n    ArrayView<Integer> stencil_F = m_cell_coefficients->stencilLocalId(F);\n    stencil_F[0] = F.backCell().localId();\n    stencil_F[1] = F.frontCell().localId();\n  }\n  \n  ENUMERATE_FACE(iF, m_boundary_faces) {\n    const Face& F = *iF;\n\n    info() << ItemPrinter(F);\n    \n    ArrayView<Integer> c_stencil_F = m_cell_coefficients->stencilLocalId(F);\n    ArrayView<Integer> f_stencil_F = m_face_coefficients->stencilLocalId(F);\n\n    c_stencil_F[0] = F.boundaryCell().localId();\n    f_stencil_F[0] = F.localId();\n  }\n\n  m_prepared = true;\n}\n\n////////////////////////////////////////////////////////////\n\nvoid AdvectionUpwindService::finalize() {\n  m_prepared = false;\n}\n\n////////////////////////////////////////////////////////////\n\nvoid AdvectionUpwindService::formDiscreteOperator(const VelocityFluxType& q) {\n  if(!m_prepared) error() << \" Numerical service not prepared\";\n\n  ENUMERATE_FACE(iF, m_internal_faces) {\n    const Face& F = *iF;\n\n    // Retrieve neighbour cells\n    // const Cell& T0 = F.backCell();\n    // const Cell& T1 = F.frontCell();\n    \n    // Determine face orientation \n    // By convention n = n(back->front) \n    const Real alpha = 1.;\n        \n    // Get face velocity flux\n    const Real& qF = q[F];\n    \n    // Build theta upwind scheme\n    const Real& thetaF = m_theta_upwind ; \n    const Real a0 = (qF*alpha>0) ? thetaF : (1-thetaF);\n    \n    // Compute transmissivities    \n    StencilFluxCoeffType tau_F = m_cell_coefficients->coefficients(F);\n    tau_F[0] = a0*qF;\n    tau_F[1] = (1-a0)*qF;\n  }\n\n  // Boundary faces\n  ENUMERATE_FACE(iF, m_boundary_faces) {\n    const Face& F = *iF;\n\n    // Retrieve neighbour cell \n    const Cell& T0  = F.boundaryCell();\n    \n    // Determine output-face orientation \n    const Real alpha = (F.backCell() == T0) ? 1. : -1.;\n           \n    // Get face velocity flux (with output-face orientation)\n    const Real& qF = q[F]*alpha;\n        \n    // Build theta upwind scheme\n    const Real& thetaF  = m_theta_upwind; \n    Real a0 = (qF>0) ? thetaF : (1-thetaF);\n    \n    // Compute transmissivities\n    StencilFluxCoeffType c_tau_F = m_cell_coefficients->coefficients(F);\n    StencilFluxCoeffType f_tau_F = m_face_coefficients->coefficients(F);\n    c_tau_F[0] = a0*qF;\n    f_tau_F[0] = (1-a0)*qF;\n  }\n}\n\nARCANE_REGISTER_SERVICE_ADVECTIONUPWIND(AdvectionUpwind,\n\t\t\t\t\tAdvectionUpwindService);\n", "meta": {"hexsha": "6029b7ab6f4e4e360c8c0e4e99318e3214ca80ba", "size": 5375, "ext": "cc", "lang": "C++", "max_stars_repo_path": "arcane/extras/NumericalModel/src/Numerics/DiscreteOperator/AdvectionUpwind/AdvectionUpwindService.cc", "max_stars_repo_name": "cedricga91/framework", "max_stars_repo_head_hexsha": "143eeccb5bf375df4a3f11b888681f84f60380c6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T12:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:19:14.000Z", "max_issues_repo_path": "arcane/extras/NumericalModel/src/Numerics/DiscreteOperator/AdvectionUpwind/AdvectionUpwindService.cc", "max_issues_repo_name": "cedricga91/framework", "max_issues_repo_head_hexsha": "143eeccb5bf375df4a3f11b888681f84f60380c6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2021-09-17T13:49:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:24:07.000Z", "max_forks_repo_path": "arcane/extras/NumericalModel/src/Numerics/DiscreteOperator/AdvectionUpwind/AdvectionUpwindService.cc", "max_forks_repo_name": "cedricga91/framework", "max_forks_repo_head_hexsha": "143eeccb5bf375df4a3f11b888681f84f60380c6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T16:48:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T19:06:56.000Z", "avg_line_length": 30.0279329609, "max_line_length": 88, "alphanum_fraction": 0.6705116279, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220563966531902, "lm_q2_score": 0.022286183509919195, "lm_q1q2_score": 0.005397839332718663}}
{"text": "// Copyright (C) 2010 Anders Logg\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n// First added:  2010-02-23\n// Last changed: 2011-03-17\n\n#include <boost/scoped_array.hpp>\n#include <dolfin/common/constants.h>\n#include \"GenericMatrix.h\"\n\nusing namespace dolfin;\n\n//-----------------------------------------------------------------------------\nvoid GenericMatrix::ident_zeros()\n{\n  std::vector<uint> columns;\n  std::vector<double> values;\n  std::vector<uint> zero_rows;\n\n  // Check which rows are zero\n  for (uint row = 0; row < size(0); row++)\n  {\n    // Get value for row\n    getrow(row, columns, values);\n\n    // Get maximum value in row\n    double max = 0.0;\n    for (uint k = 0; k < values.size(); k++)\n      max = std::max(max, std::abs(values[k]));\n\n    // Check if row is zero\n    if (max < DOLFIN_EPS)\n      zero_rows.push_back(row);\n  }\n\n  // Write a message\n  log(TRACE, \"Found %d zero row(s), inserting ones on the diagonal.\", zero_rows.size());\n\n  // Insert one on the diagonal for rows with only zeros. Note that we\n  // are not calling ident() since that fails in PETSc if nothing\n  // has been assembled into those rows.\n  for (uint i = 0; i < zero_rows.size(); i++)\n  {\n    std::pair<uint, uint> ij(zero_rows[i], zero_rows[i]);\n    setitem(ij, 1.0);\n  }\n\n  // Apply changes\n  apply(\"insert\");\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "dc8640cb73d94a1cd7d6f895a6c7c4ac0af0a174", "size": 2031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/la/GenericMatrix.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/la/GenericMatrix.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/la/GenericMatrix.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.7727272727, "max_line_length": 88, "alphanum_fraction": 0.623338257, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1755380649971796, "lm_q2_score": 0.030675801156820358, "lm_q1q2_score": 0.00538477077730649}}
{"text": "/*  \n *  Copyright 2010-2011 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#ifndef KDTREE_H\n#define KDTREE_H\n\n#include <iostream>\n#include <list>\n\n#include <boost/foreach.hpp>\n\n#include \"kdnode.hpp\"\n#include \"bbox.hpp\"\n#include \"millingcutter.hpp\"\n#include \"clpoint.hpp\"\n#include \"numeric.hpp\"\n\nnamespace ocl\n{\n    \nclass Point;\nclass CLPoint;\nclass Triangle;\nclass MillingCutter;\n\n/// \\brief KDTree spread, a measure of how spread-out a list of triangles are.\n///\n/// simple struct-like class for storing the \"spread\" or maximum \n/// extent of a list of triangles. Used by the kd-tree algorithm.\nclass Spread {\n    public:\n        /// constructor\n        Spread(int dim, double v, double s) {\n            d = dim;\n            val = v;\n            start = s;\n        };\n        /// dimension\n        int d;\n        /// spread-value\n        double val;\n        /// minimum or start value\n        double start;\n        /// comparison of Spread objects. Used for finding the largest spread\n        /// along which the next partition/cut is made.\n        static bool spread_compare(Spread *x, Spread *y) {\n            if (x->val > y->val)\n                return true;\n            else\n                return false;\n        };\n};\n\n/// a kd-tree for storing triangles and fast searching for triangles\n/// that overlap the cutter\ntemplate <class BBObj>\nclass KDTree {\n    public:\n        KDTree() {};\n        virtual ~KDTree() {\n            // std::cout << \" ~KDTree()\\n\";\n            delete root;\n        }\n        /// set the bucket-size \n        void setBucketSize(int b){\n            //std::cout << \"KDTree::setBucketSize = \" << b << \"\\n\"; \n            bucketSize = b;\n        }\n        /// set the search dimension to the XY-plane\n        void setXYDimensions(){\n            //std::cout << \"KDTree::setXYDimensions()\\n\"; \n            dimensions.clear();\n            dimensions.push_back(0); // x\n            dimensions.push_back(1); // x\n            dimensions.push_back(2); // y\n            dimensions.push_back(3); // y\n        } // for drop-cutter search in XY plane\n        /// set search-plane to YZ\n        void setYZDimensions(){ // for X-fibers\n            //std::cout << \"KDTree::setYZDimensions()\\n\"; \n            dimensions.clear();\n            dimensions.push_back(2); // y\n            dimensions.push_back(3); // y\n            dimensions.push_back(4); // z\n            dimensions.push_back(5); // z\n        } // for X-fibers\n        /// set search plane to XZ\n        void setXZDimensions(){ // for Y-fibers\n            //std::cout << \"KDTree::setXZDimensions()\\n\";\n            dimensions.clear();\n            dimensions.push_back(0); // x\n            dimensions.push_back(1); // x\n            dimensions.push_back(4); // z\n            dimensions.push_back(5); // z\n        } // for Y-fibers\n        /// build the kd-tree based on a list of input objects\n        void build(const std::list<BBObj>& list){\n            //std::cout << \"KDTree::build() list.size()= \" << list.size() << \" \\n\";\n            root = build_node( &list, 0, NULL ); \n        }\n        /// search for overlap with input Bbox bb, return found objects\n        std::list<BBObj>* search( const Bbox& bb ){\n            assert( !dimensions.empty() );\n            std::list<BBObj>* tris = new std::list<BBObj>();\n            this->search_node( tris, bb, root );\n            return tris;\n        }\n        /// search for overlap with a MillingCutter c positioned at cl, return found objects\n        std::list<BBObj>* search_cutter_overlap(const MillingCutter* c, CLPoint* cl ){\n            double r = c->getRadius();\n            // build a bounding-box at the current CL\n            Bbox bb( cl->x-r, cl->x+r, cl->y-r, cl->y+r, cl->z, cl->z+c->getLength() );    \n            return this->search( bb );\n        }\n        /// string repr\n        std::string str() const;\n        \n    protected:\n        /// build and return a KDNode containing list *tris at depth dep.\n        KDNode<BBObj>* build_node(     const std::list<BBObj> *tris,  // triangles \n                                        int dep,                       // depth of node\n                                        KDNode<BBObj> *par)   {       // parent node\n            //std::cout << \"KDNode::build_node list.size()=\" << tris->size() << \"\\n\";\n            \n            if (tris->size() == 0 ) { //this is a fatal error.\n                std::cout << \"ERROR: KDTree::build_node() called with tris->size()==0 ! \\n\";\n                assert(0);\n                return 0;\n            }\n            Spread* spr = calc_spread(tris); // calculate spread in order to know how to cut\n            double cutvalue = spr->start + spr->val/2; // cut in the middle\n            //std::cout << \" cutvalue= \" << cutvalue << \"\\n\";\n            if ( (tris->size() <= bucketSize) ||  isZero_tol( spr->val ) ) {  // then return a bucket/leaf node\n                //std::cout << \"KDNode::build_node BUCKET list.size()=\" << tris->size() << \"\\n\";\n                KDNode<BBObj> *bucket;   //  dim   cutv   parent   hi    lo   triangles depth\n                bucket = new KDNode<BBObj>(spr->d, cutvalue , par , NULL, NULL, tris, dep);\n                assert( bucket->isLeaf );\n                delete spr;\n                return bucket; // this is the leaf/end of the recursion-tree\n            }\n            // build lists of triangles for hi and lo child nodes\n            std::list<BBObj>* lolist = new std::list<BBObj>();\n            std::list<BBObj>* hilist = new std::list<BBObj>();\n            BOOST_FOREACH(BBObj t, *tris) { // loop through each triangle and put it in either lolist or hilist\n                if (t.bb[spr->d] > cutvalue) \n                    hilist->push_back(t);\n                else\n                    lolist->push_back(t);\n            } \n            \n            /*\n            if (hilist->empty() || lolist->empty()) {// an error ??\n                std::cout << \"kdtree: hilist.size()==0! or lolist.size()==0! \\n\";\n                std::cout << \"kdtree: tris->size()= \" << tris->size()<< \"\\n\";\n                std::cout << \"kdtree: hilist.size()= \" << hilist->size()<< \"\\n\";\n                std::cout << \"kdtree: lolist.size()= \" << lolist->size()<< \"\\n\";\n                BOOST_FOREACH(BBObj t, *tris) {\n                    std::cout << t << \"\\n\";\n                    std::cout << t.bb << \"\\n\";\n                }\n                std::cout << \"kdtree: spr->d= \" << spr->d << \"\\n\";\n                std::cout << \"kdtree: cutvalue= \" << cutvalue << \"\\n\";\n                assert(0);\n            }*/\n            \n            \n            // create the current node  dim     value    parent  hi   lo   trilist  depth\n            KDNode<BBObj> *node = new KDNode<BBObj>(spr->d, cutvalue, par, NULL,NULL,NULL, dep);\n            // create the child-nodes through recursion\n            //                    list    depth   parent\n            if (!hilist->empty())\n                node->hi = build_node(hilist, dep+1, node); \n            //else\n                //std::cout << \"hilist empty!\\n\";\n                \n            if (!lolist->empty()) {\n                node->lo = build_node(lolist, dep+1, node); \n            } else {\n                //std::cout << \"lolist empty!\\n\";\n            }\n             \n            lolist->clear();\n            hilist->clear();\n            delete spr;\n            delete lolist;\n            delete hilist;\n            \n            return node; // return a new node\n        };\n        \n        /// calculate the spread of list *tris                        \n        Spread* calc_spread(const std::list<BBObj> *tris) {\n            std::vector<double> maxval( 6 );\n            std::vector<double> minval( 6 );\n            if ( tris->empty() ) {\n                std::cout << \" ERROR, KDTree::calc_spread() called with tris->size()==0 ! \\n\";\n                assert( 0 );\n                return NULL;\n            } else {\n                // find out the maximum spread\n                //std::cout << \"calc_spread()...\\n\";\n                bool first=true;\n                BOOST_FOREACH(BBObj t, *tris) { // check each triangle\n                    for (unsigned int m=0;m<dimensions.size();++m) {\n                        // dimensions[m] is the dimensions we want to update\n                        // t.bb[ dimensions[m] ]   is the update value\n                        if (first) {\n                            maxval[ dimensions[m] ] = t.bb[ dimensions[m] ];\n                            minval[ dimensions[m] ] = t.bb[ dimensions[m] ];\n                            if (m==(dimensions.size()-1) )\n                                first=false;\n                        } else {\n                            if (maxval[ dimensions[m] ] < t.bb[ dimensions[m] ] )\n                                maxval[ dimensions[m] ] = t.bb[ dimensions[m] ];\n                            if (minval[ dimensions[m] ] > t.bb[ dimensions[m] ])\n                                minval[ dimensions[m] ] = t.bb[ dimensions[m] ];\n                        }\n                    }\n                } \n                std::vector<Spread*> spreads;// calculate the spread along each dimension\n                for (unsigned int m=0;m<dimensions.size();++m) {   // dim,  spread, start\n                    spreads.push_back( new Spread(dimensions[m] , \n                                       maxval[dimensions[m]]-minval[dimensions[m]], \n                                       minval[dimensions[m]] ) );  \n                }// priority-queue could also be used ??  \n                assert( !spreads.empty() );\n                //std::cout << \" spreads.size()=\" << spreads.size() << \"\\n\";\n                std::sort(spreads.begin(), spreads.end(), Spread::spread_compare); // sort the list\n                Spread* s= new Spread(*spreads[0]); // this is the one we want to return\n                while(!spreads.empty()) delete spreads.back(), spreads.pop_back(); // delete the others\n                //std::cout << \"calc_spread() done\\n\";\n                return s; // select the biggest spread and return\n            } // end tris->size != 0\n        } // end spread();\n        \n        \n        /// search kd-tree starting at *node, looking for overlap with bb, and placing\n        /// found objects in *tris\n        void search_node( std::list<BBObj> *tris, const Bbox& bb, KDNode<BBObj> *node) {\n            if (node->isLeaf ) { // we found a bucket node, so add all triangles and return.\n            \n                BOOST_FOREACH( BBObj t, *(node->tris) ) {\n                        tris->push_back(t); \n                } \n                //std::cout << \" search_node Leaf bucket tris-size() = \" << tris->size() << \"\\n\";\n                return; // end recursion\n            } else if ( (node->dim % 2) == 0) { // cutting along a min-direction: 0, 2, 4\n                // not a bucket node, so recursevily seach hi/lo branches of KDNode\n                unsigned int maxdim = node->dim+1;\n                if ( node->cutval > bb[maxdim] ) { // search only lo\n                    search_node(tris, bb, node->lo );\n                } else { // need to search both child nodes\n                    if (node->hi)\n                        search_node(tris, bb, node->hi );\n                    if (node->lo)\n                        search_node(tris, bb, node->lo );\n                }\n            } else { // cutting along a max-dimension: 1,3,5\n                unsigned int mindim = node->dim-1;\n                if ( node->cutval < bb[mindim] ) { // search only hi\n                    search_node(tris, bb, node->hi);\n                } else { // need to search both child nodes\n                    if (node->hi)\n                        search_node(tris, bb, node->hi);\n                    if (node->lo)\n                        search_node(tris, bb, node->lo);\n                }\n            }\n            return; // Done. We get here after all the recursive calls above.\n        } // end search_kdtree();\n    // DATA\n        /// bucket size of tree\n        unsigned int bucketSize;\n        /// pointer to root KDNode\n        KDNode<BBObj>* root;\n        /// the dimensions in this kd-tree\n        std::vector<int> dimensions;\n};\n\n} // end ocl namespace\n#endif\n// end file kdtree.hpp\n", "meta": {"hexsha": "141fbace877b3bd152134a3c78747d39537c0baa", "size": 12886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "opencamlib/src/common/kdtree.hpp", "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/common/kdtree.hpp", "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/common/kdtree.hpp", "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": 43.0969899666, "max_line_length": 111, "alphanum_fraction": 0.4877386311, "num_tokens": 3075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418373713166, "lm_q2_score": 0.02002344048536054, "lm_q1q2_score": 0.005262997887667372}}
{"text": "//=============================================================================================================\n/**\n* @file     fwd_bem_model.cpp\n* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     January, 2017\n*\n* @section  LICENSE\n*\n* Copyright (C) 2017, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Definition of the FwdBemModel Class.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"fwd_bem_model.h\"\n#include \"fwd_bem_solution.h\"\n#include \"fwd_eeg_sphere_model.h\"\n#include <mne/c/mne_surface_old.h>\n#include <mne/c/mne_triangle.h>\n#include <mne/c/mne_source_space_old.h>\n\n#include \"fwd_comp_data.h\"\n#include \"fwd_bem_model.h\"\n\n#include \"fwd_thread_arg.h\"\n\n#include <fiff/fiff_stream.h>\n\n#include <QFile>\n#include <QList>\n#include <QThread>\n#include <QtConcurrent>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#include <Eigen/Dense>\n\n\nstatic float Qx[] = {1.0,0.0,0.0};\nstatic float Qy[] = {0.0,1.0,0.0};\nstatic float Qz[] = {0.0,0.0,1.0};\n\n\n#ifndef TRUE\n#define TRUE 1\n#endif\n\n#ifndef FALSE\n#define FALSE 0\n#endif\n\n#ifndef FAIL\n#define FAIL -1\n#endif\n\n#ifndef OK\n#define OK 0\n#endif\n\n\n\n\n\n#define X_40 0\n#define Y_40 1\n#define Z_40 2\n\n\n#define VEC_DIFF_40(from,to,diff) {\\\n    (diff)[X_40] = (to)[X_40] - (from)[X_40];\\\n    (diff)[Y_40] = (to)[Y_40] - (from)[Y_40];\\\n    (diff)[Z_40] = (to)[Z_40] - (from)[Z_40];\\\n    }\n\n\n#define VEC_COPY_40(to,from) {\\\n    (to)[X_40] = (from)[X_40];\\\n    (to)[Y_40] = (from)[Y_40];\\\n    (to)[Z_40] = (from)[Z_40];\\\n    }\n\n\n\n#define VEC_DOT_40(x,y) ((x)[X_40]*(y)[X_40] + (x)[Y_40]*(y)[Y_40] + (x)[Z_40]*(y)[Z_40])\n\n#define VEC_LEN_40(x) sqrt(VEC_DOT_40(x,x))\n\n#define CROSS_PRODUCT_40(x,y,xy) {\\\n    (xy)[X_40] =   (x)[Y_40]*(y)[Z_40]-(y)[Y_40]*(x)[Z_40];\\\n    (xy)[Y_40] = -((x)[X_40]*(y)[Z_40]-(y)[X_40]*(x)[Z_40]);\\\n    (xy)[Z_40] =   (x)[X_40]*(y)[Y_40]-(y)[X_40]*(x)[Y_40];\\\n    }\n\n\n\n\n#define MALLOC_40(x,t) (t *)malloc((x)*sizeof(t))\n\n#define ALLOC_CMATRIX_40(x,y) mne_cmatrix_40((x),(y))\n\n#define FREE_40(x) if ((char *)(x) != NULL) free((char *)(x))\n\n#define FREE_CMATRIX_40(m) mne_free_cmatrix_40((m))\n\n\n\n\nvoid mne_free_cmatrix_40 (float **m)\n{\n    if (m) {\n        FREE_40(*m);\n        FREE_40(m);\n    }\n}\n\n\nstatic void matrix_error_40(int kind, int nr, int nc)\n\n{\n    if (kind == 1)\n        printf(\"Failed to allocate memory pointers for a %d x %d matrix\\n\",nr,nc);\n    else if (kind == 2)\n        printf(\"Failed to allocate memory for a %d x %d matrix\\n\",nr,nc);\n    else\n        printf(\"Allocation error for a %d x %d matrix\\n\",nr,nc);\n    if (sizeof(void *) == 4) {\n        printf(\"This is probably because you seem to be using a computer with 32-bit architecture.\\n\");\n        printf(\"Please consider moving to a 64-bit platform.\");\n    }\n    printf(\"Cannot continue. Sorry.\\n\");\n    exit(1);\n}\n\n\n\nfloat **mne_cmatrix_40 (int nr,int nc)\n\n{\n    int i;\n    float **m;\n    float *whole;\n\n    m = MALLOC_40(nr,float *);\n    if (!m) matrix_error_40(1,nr,nc);\n    whole = MALLOC_40(nr*nc,float);\n    if (!whole) matrix_error_40(2,nr,nc);\n\n    for(i=0;i<nr;i++)\n        m[i] = whole + i*nc;\n    return m;\n}\n\n\n\n\n\n//float\nEigen::MatrixXf toFloatEigenMatrix_40(float **mat, const int m, const int n)\n{\n    Eigen::MatrixXf eigen_mat(m,n);\n\n    for ( int i = 0; i < m; ++i)\n        for ( int j = 0; j < n; ++j)\n            eigen_mat(i,j) = mat[i][j];\n\n    return eigen_mat;\n}\n\nvoid fromFloatEigenMatrix_40(const Eigen::MatrixXf& from_mat, float **& to_mat, const int m, const int n)\n{\n    for ( int i = 0; i < m; ++i)\n        for ( int j = 0; j < n; ++j)\n            to_mat[i][j] = from_mat(i,j);\n}\n\nvoid fromFloatEigenMatrix_40(const Eigen::MatrixXf& from_mat, float **& to_mat)\n{\n    fromFloatEigenMatrix_40(from_mat, to_mat, from_mat.rows(), from_mat.cols());\n}\n\n\n\n\n\n\n\n\nfloat **mne_lu_invert_40(float **mat,int dim)\n/*\n      * Invert a matrix using the LU decomposition from\n      * LAPACK\n      */\n{\n    Eigen::MatrixXf eigen_mat = toFloatEigenMatrix_40(mat, dim, dim);\n    Eigen::MatrixXf eigen_mat_inv = eigen_mat.inverse();\n    fromFloatEigenMatrix_40(eigen_mat_inv, mat);\n    return mat;\n}\n\n\n\n\n\n\nvoid mne_transpose_square_40(float **mat, int n)\n/*\n      * In-place transpose of a square matrix\n      */\n{\n    int j,k;\n    float val;\n\n    for (j = 1; j < n; j++)\n        for (k = 0; k < j; k++) {\n            val = mat[j][k];\n            mat[j][k] = mat[k][j];\n            mat[k][j] = val;\n        }\n    return;\n}\n\n\n\nfloat mne_dot_vectors_40(float *v1,\n                       float *v2,\n                       int   nn)\n\n{\n#ifdef BLAS\n    int one = 1;\n    float res = sdot(&nn,v1,&one,v2,&one);\n    return res;\n#else\n    float res = 0.0;\n    int   k;\n\n    for (k = 0; k < nn; k++)\n        res = res + v1[k]*v2[k];\n    return res;\n#endif\n}\n\n\n\n\n\nvoid mne_add_scaled_vector_to_40(float *v1,float scale, float *v2,int nn)\n\n{\n#ifdef BLAS\n    float fscale = scale;\n    int   one = 1;\n    saxpy(&nn,&fscale,v1,&one,v2,&one);\n#else\n    int k;\n    for (k = 0; k < nn; k++)\n        v2[k] = v2[k] + scale*v1[k];\n#endif\n    return;\n}\n\n\nvoid mne_scale_vector_40(double scale,float *v,int   nn)\n\n{\n#ifdef BLAS\n    float  fscale = scale;\n    int    one    = 1;\n    sscal(&nn,&fscale,v,&one);\n#else\n    int k;\n    for (k = 0; k < nn; k++)\n        v[k] = v[k]*scale;\n#endif\n}\n\n#include <Eigen/Core>\nusing namespace Eigen;\n\nfloat **mne_mat_mat_mult_40 (float **m1,\n                             float **m2,\n                             int d1,\n                             int d2,\n                             int d3)\n/* Matrix multiplication\n      * result(d1 x d3) = m1(d1 x d2) * m2(d2 x d3) */\n\n{\n#ifdef BLAS\n    float **result = ALLOC_CMATRIX_40(d1,d3);\n    char  *transa = \"N\";\n    char  *transb = \"N\";\n    float zero = 0.0;\n    float one  = 1.0;\n    sgemm (transa,transb,&d3,&d1,&d2,\n           &one,m2[0],&d3,m1[0],&d2,&zero,result[0],&d3);\n    return (result);\n#else\n    float **result = ALLOC_CMATRIX_40(d1,d3);\n    int j,k,p;\n    float sum;\n\n    // TODO: Hack to include faster Eigen processing. This should eventually be replaced dwith pure Eigen logic.\n    MatrixXf a(d1,d2);\n    MatrixXf b(d2,d3);\n\n    for (j = 0; j < d1; j++) {\n        for (k = 0; k < d2; k++) {\n            a(j,k) = m1[j][k];\n        }\n    }\n\n    for (j = 0; j < d2; j++) {\n        for (k = 0; k < d3; k++) {\n            b(j,k) = m2[j][k];\n        }\n    }\n\n    MatrixXf resultMat = a * b;\n\n    for (j = 0; j < d1; j++) {\n        for (k = 0; k < d3; k++) {\n            result[j][k] = resultMat(j,k);\n        }\n    }\n\n//    for (j = 0; j < d1; j++)\n//        for (k = 0; k < d3; k++) {\n//            sum = 0.0;\n//            for (p = 0; p < d2; p++)\n//                sum = sum + m1[j][p]*m2[p][k];\n//            result[j][k] = sum;\n//        }\n    return (result);\n#endif\n}\n\n\n\n\nstatic struct {\n    int  kind;\n    const QString name;\n} surf_expl[] = { { FIFFV_BEM_SURF_ID_BRAIN , \"inner skull\" },\n{ FIFFV_BEM_SURF_ID_SKULL , \"outer skull\" },\n{ FIFFV_BEM_SURF_ID_HEAD  , \"scalp\" },\n{ -1                      , \"unknown\" } };\n\n\nstatic struct {\n    int  method;\n    const QString name;\n} method_expl[] = { { FWD_BEM_CONSTANT_COLL , \"constant collocation\" },\n{ FWD_BEM_LINEAR_COLL   , \"linear collocation\" },\n{ -1                    , \"unknown\" } };\n\n\n#define BEM_SUFFIX     \"-bem.fif\"\n#define BEM_SOL_SUFFIX \"-bem-sol.fif\"\n\n\n\n//============================= misc_util.c =============================\n\nstatic QString strip_from(const QString& s, const QString& suffix)\n{\n    QString res;\n\n    if (s.endsWith(suffix)) {\n        res = s;\n        res.chop(suffix.size());\n    }\n    else\n        res = s;\n\n    return res;\n}\n\n//============================= mne_coord_transforms.c =============================\n\ntypedef struct {\n    int frame;\n    const QString name;\n} frameNameRec_40;\n\n\nconst QString mne_coord_frame_name_40(int frame)\n\n{\n    static frameNameRec_40 frames[] = {\n        {FIFFV_COORD_UNKNOWN,\"unknown\"},\n        {FIFFV_COORD_DEVICE,\"MEG device\"},\n        {FIFFV_COORD_ISOTRAK,\"isotrak\"},\n        {FIFFV_COORD_HPI,\"hpi\"},\n        {FIFFV_COORD_HEAD,\"head\"},\n        {FIFFV_COORD_MRI,\"MRI (surface RAS)\"},\n        {FIFFV_MNE_COORD_MRI_VOXEL, \"MRI voxel\"},\n        {FIFFV_COORD_MRI_SLICE,\"MRI slice\"},\n        {FIFFV_COORD_MRI_DISPLAY,\"MRI display\"},\n        {FIFFV_MNE_COORD_CTF_DEVICE,\"CTF MEG device\"},\n        {FIFFV_MNE_COORD_CTF_HEAD,\"CTF/4D/KIT head\"},\n        {FIFFV_MNE_COORD_RAS,\"RAS (non-zero origin)\"},\n        {FIFFV_MNE_COORD_MNI_TAL,\"MNI Talairach\"},\n        {FIFFV_MNE_COORD_FS_TAL_GTZ,\"Talairach (MNI z > 0)\"},\n        {FIFFV_MNE_COORD_FS_TAL_LTZ,\"Talairach (MNI z < 0)\"},\n        {-1,\"unknown\"}\n    };\n    int k;\n    for (k = 0; frames[k].frame != -1; k++) {\n        if (frame == frames[k].frame)\n            return frames[k].name;\n    }\n    return frames[k].name;\n}\n\n\n\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace FIFFLIB;\nusing namespace MNELIB;\nusing namespace FWDLIB;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nFwdBemModel::FwdBemModel()\n:ntri       (NULL)\n,np         (NULL)\n,nsurf      (0)\n,sigma      (NULL)\n,gamma      (NULL)\n,source_mult(NULL)\n,field_mult (NULL)\n,bem_method (FWD_BEM_UNKNOWN)\n,solution   (NULL)\n,nsol       (0)\n,head_mri_t (NULL)\n,v0         (NULL)\n,use_ip_approach(false)\n,ip_approach_limit(FWD_BEM_IP_APPROACH_LIMIT)\n{\n\n}\n\n\n//*************************************************************************************************************\n\nFwdBemModel::~FwdBemModel()\n{\n    for (int k = 0; k < this->nsurf; k++)\n        delete this->surfs[k];\n    FREE_40(this->ntri);\n    FREE_40(this->np);\n    FREE_40(this->sigma);\n    FREE_40(this->source_mult);\n    FREE_40(this->field_mult);\n    FREE_CMATRIX_40(this->gamma);\n    if(this->head_mri_t)\n        delete this->head_mri_t;\n    this->fwd_bem_free_solution();\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_free_solution()\n{\n    FREE_CMATRIX_40(this->solution); this->solution = NULL;\n    this->sol_name.clear();\n    FREE_40(this->v0); this->v0 = NULL;\n    this->bem_method = FWD_BEM_UNKNOWN;\n    this->nsol       = 0;\n\n    return;\n}\n\n\n//*************************************************************************************************************\n\nQString FwdBemModel::fwd_bem_make_bem_sol_name(const QString& name)\n/*\n    * Make a standard BEM solution file name\n    */\n{\n    QString s1, s2;\n\n    s1 = strip_from(name,\".fif\");\n    s2 = strip_from(s1,\"-sol\");\n    s1 = strip_from(s2,\"-bem\");\n    s2 = QString(\"%1%2\").arg(s1).arg(BEM_SOL_SUFFIX);\n    return s2;\n}\n\n\n//*************************************************************************************************************\n\nconst QString& FwdBemModel::fwd_bem_explain_surface(int kind)\n{\n    int k;\n\n    for (k = 0; surf_expl[k].kind >= 0; k++)\n        if (surf_expl[k].kind == kind)\n            return surf_expl[k].name;\n\n    return surf_expl[k].name;\n}\n\n\n//*************************************************************************************************************\n\nconst QString& FwdBemModel::fwd_bem_explain_method(int method)\n\n{\n    int k;\n\n    for (k = 0; method_expl[k].method >= 0; k++)\n        if (method_expl[k].method == method)\n            return method_expl[k].name;\n\n    return method_expl[k].name;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::get_int(FiffStream::SPtr &stream, const FiffDirNode::SPtr &node, int what, int *res)\n/*\n    * Wrapper to get int's\n    */\n{\n    FiffTag::SPtr t_pTag;\n    if(node->find_tag(stream, what, t_pTag)) {\n        if (t_pTag->getType() != FIFFT_INT) {\n            printf(\"Expected an integer tag : %d (found data type %d instead)\\n\",what,t_pTag->getType() );\n            return FAIL;\n        }\n        *res = *t_pTag->toInt();\n        return OK;\n    }\n    return FAIL;\n}\n\n\n//*************************************************************************************************************\n\nMneSurfaceOld *FwdBemModel::fwd_bem_find_surface(int kind)\n{\n    //    if (!model) {\n    //        printf(\"No model specified for fwd_bem_find_surface\");\n    //        return NULL;\n    //    }\n    for (int k = 0; k < this->nsurf; k++)\n        if (this->surfs[k]->id == kind)\n            return this->surfs[k];\n    printf(\"Desired surface (%d = %s) not found.\", kind,fwd_bem_explain_surface(kind).toUtf8().constData());\n    return NULL;\n}\n\n\n//*************************************************************************************************************\n\nFwdBemModel *FwdBemModel::fwd_bem_load_surfaces(const QString &name, int *kinds, int nkind)\n/*\n* Load a set of surfaces\n*/\n{\n    QList<MneSurfaceOld*> surfs;// = NULL;\n    float      *sigma = NULL;\n    float      *sigma1;\n    FwdBemModel *m = NULL;\n    int         j,k;\n\n    if (nkind <= 0) {\n        qCritical(\"No surfaces specified to fwd_bem_load_surfaces\");\n        return NULL;\n    }\n\n//    surfs = MALLOC_40(nkind,MneSurfaceOld*);\n    sigma = MALLOC_40(nkind,float);\n//    for (k = 0; k < nkind; k++)\n//        surfs[k] = NULL;\n\n    for (k = 0; k < nkind; k++) {\n        surfs.append(MneSurfaceOld::read_bem_surface(name,kinds[k],TRUE,sigma+k));\n        if (surfs[k] == NULL)\n            goto bad;\n        if ((surfs[k] = MneSurfaceOld::read_bem_surface(name,kinds[k],TRUE,sigma+k)) == NULL)\n            goto bad;\n        if (sigma[k] < 0.0) {\n            qCritical(\"No conductivity available for surface %s\",fwd_bem_explain_surface(kinds[k]).toUtf8().constData());\n            goto bad;\n        }\n        if (surfs[k]->coord_frame != FIFFV_COORD_MRI) { /* We make our life much easier with this */\n            qCritical(\"Surface %s not specified in MRI coordinates.\",fwd_bem_explain_surface(kinds[k]).toUtf8().constData());\n            goto bad;\n        }\n    }\n    m = new FwdBemModel;\n\n    m->surf_name = name;\n    m->nsurf     = nkind;\n    m->surfs     = surfs;\n    m->sigma     = sigma;\n    m->ntri      = MALLOC_40(nkind,int);\n    m->np        = MALLOC_40(nkind,int);\n    m->gamma = ALLOC_CMATRIX_40(nkind,nkind);\n    m->source_mult = MALLOC_40(nkind,float);\n    m->field_mult  = MALLOC_40(nkind,float);\n    /*\n       * Dirty trick for the zero conductivity outside\n       */\n    sigma1 = MALLOC_40(nkind+1,float);\n    sigma1[0] = 0.0;\n    sigma  = sigma1+1;\n    for (k = 0; k < m->nsurf; k++)\n        sigma[k] = m->sigma[k];\n    /*\n       * Gamma factors and multipliers\n       */\n    for (j = 0; j < m->nsurf; j++) {\n        m->ntri[j] = m->surfs[j]->ntri;\n        m->np[j]   = m->surfs[j]->np;\n        m->source_mult[j] = 2.0/(sigma[j]+sigma[j-1]);\n        m->field_mult[j] = sigma[j]-sigma[j-1];\n        for (k = 0; k < m->nsurf; k++)\n            m->gamma[j][k] = (sigma[k]-sigma[k-1])/(sigma[j]+sigma[j-1]);\n    }\n    FREE_40(sigma1);\n\n    return m;\n\nbad : {\n        FREE_40(sigma);\n        for (k = 0; k < surfs.size(); k++)\n            delete surfs[k];\n//        FREE_40(surfs);\n        surfs.clear();\n        return NULL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nFwdBemModel *FwdBemModel::fwd_bem_load_homog_surface(const QString &name)\n/*\n* Load surfaces for the homogeneous model\n*/\n{\n    int kinds[] = { FIFFV_BEM_SURF_ID_BRAIN };\n    int nkind   = 1;\n\n    return fwd_bem_load_surfaces(name,kinds,nkind);\n}\n\n\n//*************************************************************************************************************\n\nFwdBemModel *FwdBemModel::fwd_bem_load_three_layer_surfaces(const QString &name)\n/*\n* Load surfaces for three-layer model\n*/\n{\n    int kinds[] = { FIFFV_BEM_SURF_ID_HEAD, FIFFV_BEM_SURF_ID_SKULL, FIFFV_BEM_SURF_ID_BRAIN };\n    int nkind   = 3;\n\n    return fwd_bem_load_surfaces(name,kinds,nkind);\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_load_solution(const QString &name, int bem_method, FwdBemModel *m)\n/*\n    * Load the potential solution matrix and attach it to the model:\n    *\n    * return values:\n    *\n    *       TRUE   found a suitable solution\n    *       FALSE  did not find a suitable solution\n    *       FAIL   error in reading the solution\n    *\n    */\n{\n    QFile file(name);\n    FiffStream::SPtr stream(new FiffStream(&file));\n\n    float       **sol = NULL;\n    FiffDirNode::SPtr bem_node;\n    int         method;\n    FiffTag::SPtr t_pTag;\n    int         nsol;\n\n    if(!stream->open())\n        goto not_found;\n\n    /*\n       * Find the BEM data\n       */\n    {\n        QList<FiffDirNode::SPtr> nodes = stream->dirtree()->dir_tree_find(FIFFB_BEM);\n\n        if (nodes.size() == 0) {\n            printf (\"No BEM data in %s\",name.toUtf8().constData());\n            goto not_found;\n        }\n        bem_node = nodes[0];\n    }\n    /*\n        * Approximation method\n        */\n    if (get_int(stream,bem_node,FIFF_BEM_APPROX,&method) != OK)\n        goto not_found;\n    if (method == FIFFV_BEM_APPROX_CONST)\n        method = FWD_BEM_CONSTANT_COLL;\n    else if (method == FIFFV_BEM_APPROX_LINEAR)\n        method = FWD_BEM_LINEAR_COLL;\n    else {\n        printf (\"Cannot handle BEM approximation method : %d\",method);\n        goto bad;\n    }\n    if (bem_method != FWD_BEM_UNKNOWN && method != bem_method) {\n        printf(\"Approximation method in file : %d desired : %d\",method,bem_method);\n        goto not_found;\n    }\n    {\n        int         dim,k;\n\n        if (!bem_node->find_tag(stream, FIFF_BEM_POT_SOLUTION, t_pTag))\n            goto bad;\n        qint32 ndim;\n        QVector<qint32> dims;\n        t_pTag->getMatrixDimensions(ndim, dims);\n\n        if (ndim != 2) {\n            printf(\"Expected a two-dimensional solution matrix instead of a %d dimensional one\",ndim);\n            goto bad;\n        }\n        for (k = 0, dim = 0; k < m->nsurf; k++)\n            dim = dim + ((method == FWD_BEM_LINEAR_COLL) ? m->surfs[k]->np : m->surfs[k]->ntri);\n        if (dims[0] != dim || dims[1] != dim) {\n            printf(\"Expected a %d x %d solution matrix instead of a %d x %d  one\",dim,dim,dims[0],dims[1]);\n            goto not_found;\n        }\n\n        MatrixXf tmp_sol = t_pTag->toFloatMatrix().transpose();\n        sol = ALLOC_CMATRIX_40(tmp_sol.rows(),tmp_sol.cols());\n        fromFloatEigenMatrix_40(tmp_sol, sol);\n        nsol = dims[1];\n    }\n    if(m)\n        m->fwd_bem_free_solution();\n    m->sol_name = name;\n    m->solution = sol;\n    m->nsol     = nsol;\n    m->bem_method = method;\n    stream->close();\n\n    return TRUE;\n\nbad : {\n        stream->close();\n        FREE_CMATRIX_40(sol);\n        return FAIL;\n    }\n\nnot_found : {\n        stream->close();\n        FREE_CMATRIX_40(sol);\n        return FALSE;\n    }\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_set_head_mri_t(FwdBemModel *m, FiffCoordTransOld *t)\n/*\n    * Set the coordinate transformation\n    */\n{\n    if (t->from == FIFFV_COORD_HEAD && t->to == FIFFV_COORD_MRI) {\n        if(m->head_mri_t)\n            delete m->head_mri_t;\n        m->head_mri_t = new FiffCoordTransOld( *t );\n        return OK;\n    }\n    else if (t->from == FIFFV_COORD_MRI && t->to == FIFFV_COORD_HEAD) {\n        if(m->head_mri_t)\n            delete m->head_mri_t;\n        m->head_mri_t = t->fiff_invert_transform();\n        return OK;\n    }\n    else {\n        printf (\"Improper coordinate transform delivered to fwd_bem_set_head_mri_t\");\n        return FAIL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nMneSurfaceOld* FwdBemModel::make_guesses(MneSurfaceOld* guess_surf, float guessrad, float *guess_r0, float grid, float exclude, float mindist)\t\t   /* Exclude points closer than this to\n                                                        * the guess boundary surface */\n/*\n     * Make a guess space inside a sphere\n     */\n{\n    char *bemname     = NULL;\n    MneSurfaceOld* sphere = NULL;\n    MneSurfaceOld* res    = NULL;\n    int        k;\n    float      dist;\n    float      r0[] = { 0.0, 0.0, 0.0 };\n\n    if (!guess_r0)\n        guess_r0 = r0;\n\n    if (!guess_surf) {\n        printf(\"Making a spherical guess space with radius %7.1f mm...\\n\",1000*guessrad);\n        //#ifdef USE_SHARE_PATH\n        //    if ((bemname = mne_compose_mne_name(\"share/mne\",\"icos.fif\")) == NULL)\n        //#else\n        //    if ((bemname = mne_compose_mne_name(\"setup/mne\",\"icos.fif\")) == NULL)\n        //#endif\n        //      goto out;\n\n        //    QFile bemFile(\"/usr/pubsw/packages/mne/stable/share/mne/icos.fif\");\n\n        QFile bemFile(QString(QCoreApplication::applicationDirPath() + \"/resources/general/surf2bem/icos.fif\"));\n        if ( !QCoreApplication::startingUp() )\n            bemFile.setFileName(QCoreApplication::applicationDirPath() + QString(\"/resources/general/surf2bem/icos.fif\"));\n        else if (!bemFile.exists())\n            bemFile.setFileName(\"./resources/general/surf2bem/icos.fif\");\n\n        if( !bemFile.exists () ){\n            qDebug() << bemFile.fileName() << \"does not exists.\";\n            goto out;\n        }\n\n        bemname = MALLOC_40(strlen(bemFile.fileName().toUtf8().data())+1,char);\n        strcpy(bemname,bemFile.fileName().toUtf8().data());\n\n        if ((sphere = MneSourceSpaceOld::read_bem_surface(bemname,9003,FALSE,NULL)) == NULL)\n            goto out;\n\n        for (k = 0; k < sphere->np; k++) {\n            dist = VEC_LEN_40(sphere->rr[k]);\n            sphere->rr[k][X_40] = guessrad*sphere->rr[k][X_40]/dist + guess_r0[X_40];\n            sphere->rr[k][Y_40] = guessrad*sphere->rr[k][Y_40]/dist + guess_r0[Y_40];\n            sphere->rr[k][Z_40] = guessrad*sphere->rr[k][Z_40]/dist + guess_r0[Z_40];\n        }\n        if (MneSurfaceOrVolume::mne_source_space_add_geometry_info((MneSourceSpaceOld*)sphere,TRUE) == FAIL)\n            goto out;\n        guess_surf = sphere;\n    }\n    else {\n        printf(\"Guess surface (%d = %s) is in %s coordinates\\n\",\n               guess_surf->id,FwdBemModel::fwd_bem_explain_surface(guess_surf->id).toUtf8().constData(),\n               mne_coord_frame_name_40(guess_surf->coord_frame).toUtf8().constData());\n    }\n    printf(\"Filtering (grid = %6.f mm)...\\n\",1000*grid);\n    res = (MneSurfaceOld*)MneSurfaceOrVolume::make_volume_source_space(guess_surf,grid,exclude,mindist);\n\nout : {\n        FREE_40(bemname);\n        if(sphere)\n            delete sphere;\n        return res;\n    }\n}\n\n\n//*************************************************************************************************************\n\ndouble FwdBemModel::calc_beta(double *rk, double *rk1)\n\n{\n    double rkk1[3];\n    double size;\n    double res;\n\n    VEC_DIFF_40(rk,rk1,rkk1);\n    size = VEC_LEN_40(rkk1);\n\n    res = log((VEC_LEN_40(rk)*size + VEC_DOT_40(rk,rkk1))/\n              (VEC_LEN_40(rk1)*size + VEC_DOT_40(rk1,rkk1)))/size;\n    return (res);\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::lin_pot_coeff(float *from, MneTriangle* to, double omega[])\t/* The final result */\n/*\n          * The linear potential matrix element computations\n          */\n{\n    double y1[3],y2[3],y3[3];\t/* Corners with origin at from */\n    double *y[5];\n    double **yy;\n    double l1,l2,l3;\t\t/* Lengths of y1, y2, and y3 */\n    double solid;\t\t\t/* The standard solid angle */\n    double vec_omega[3];\t\t/* The cross-product integral */\n    double cross[3];\t\t/* y1 x y2 */\n    double triple;\t\t/* VEC_DOT_40(y1 x y2,y3) */\n    double ss;\n    double beta[3],bbeta[3];\n    int   j,k;\n    double z[3];\n    double n2,area2;\n    double diff[3];\n    static const double solid_eps = 4.0*M_PI/1.0E6;\n    /*\n       * This circularity makes things easy for us...\n       */\n    y[0] = y3;\n    y[1] = y1;\n    y[2] = y2;\n    y[3] = y3;\n    y[4] = y1;\n    yy = y + 1;\t\t\t/* yy can have index -1! */\n    /*\n       * The standard solid angle computation\n       */\n    VEC_DIFF_40(from,to->r1,y1);\n    VEC_DIFF_40(from,to->r2,y2);\n    VEC_DIFF_40(from,to->r3,y3);\n\n    CROSS_PRODUCT_40(y1,y2,cross);\n    triple = VEC_DOT_40(cross,y3);\n\n    l1 = VEC_LEN_40(y1);\n    l2 = VEC_LEN_40(y2);\n    l3 = VEC_LEN_40(y3);\n    ss = (l1*l2*l3+VEC_DOT_40(y1,y2)*l3+VEC_DOT_40(y1,y3)*l2+VEC_DOT_40(y2,y3)*l1);\n    solid  = 2.0*atan2(triple,ss);\n    if (std::fabs(solid) < solid_eps) {\n        for (k = 0; k < 3; k++)\n            omega[k] = 0.0;\n    }\n    else {\n        /*\n         * Calculate the magic vector vec_omega\n         */\n        for (j = 0; j < 3; j++)\n            beta[j] = calc_beta(yy[j],yy[j+1]);\n        bbeta[0] = beta[2] - beta[0];\n        bbeta[1] = beta[0] - beta[1];\n        bbeta[2] = beta[1] - beta[2];\n\n        for (j = 0; j < 3; j++)\n            vec_omega[j] = 0.0;\n        for (j = 0; j < 3; j++)\n            for (k = 0; k < 3; k++)\n                vec_omega[k] = vec_omega[k] + bbeta[j]*yy[j][k];\n        /*\n         * Put it all together...\n         */\n        area2 = 2.0*to->area;\n        n2 = 1.0/(area2*area2);\n        for (k = 0; k < 3; k++) {\n            CROSS_PRODUCT_40(yy[k+1],yy[k-1],z);\n            VEC_DIFF_40(yy[k+1],yy[k-1],diff);\n            omega[k] = n2*(-area2*VEC_DOT_40(z,to->nn)*solid +\n                           triple*VEC_DOT_40(diff,vec_omega));\n        }\n    }\n#ifdef CHECK\n    /*\n       * Check it out!\n       *\n       * omega1 + omega2 + omega3 = solid\n       */\n    rel1 = (solid + omega[X_40]+omega[Y_40]+omega[Z_40])/solid;\n    /*\n       * The other way of evaluating...\n       */\n    for (j = 0; j < 3; j++)\n        check[j] = 0;\n    for (k = 0; k < 3; k++) {\n        CROSS_PRODUCT_40(to->nn[to],yy[k],z);\n        for (j = 0; j < 3; j++)\n            check[j] = check[j] + omega[k]*z[j];\n    }\n    for (j = 0; j < 3; j++)\n        check[j] = -area2*check[j]/triple;\n    fprintf (stderr,\"(%g,%g,%g) =? (%g,%g,%g)\\n\",\n             check[X_40],check[Y_40],check[Z_40],\n             vec_omega[X_40],vec_omega[Y_40],vec_omega[Z_40]);\n    for (j = 0; j < 3; j++)\n        check[j] = check[j] - vec_omega[j];\n    rel2 = sqrt(VEC_DOT_40(check,check)/VEC_DOT_40(vec_omega,vec_omega));\n    fprintf (stderr,\"err1 = %g, err2 = %g\\n\",100*rel1,100*rel2);\n#endif\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::correct_auto_elements(MneSurfaceOld *surf, float **mat)\n/*\n          * Improve auto-element approximation...\n          */\n{\n    float *row;\n    float sum,miss;\n    int   nnode = surf->np;\n    int   ntri  = surf->ntri;\n    int   nmemb;\n    int   j,k;\n    float pi2 = 2.0*M_PI;\n    MneTriangle*   tri;\n\n#ifdef SIMPLE\n    for (j = 0; j < nnode; j++) {\n        row = mat[j];\n        sum = 0.0;\n        for (k = 0; k < nnode; k++)\n            sum = sum + row[k];\n        fprintf (stderr,\"row %d sum = %g missing = %g\\n\",j+1,sum/pi2,\n                 1.0-sum/pi2);\n        row[j] = pi2 - sum;\n    }\n#else\n    for (j = 0; j < nnode; j++) {\n        /*\n         * How much is missing?\n         */\n        row = mat[j];\n        sum = 0.0;\n        for (k = 0; k < nnode; k++)\n            sum = sum + row[k];\n        miss  = pi2-sum;\n        nmemb = surf->nneighbor_tri[j];\n        /*\n         * The node itself receives one half\n         */\n        row[j] = miss/2.0;\n        /*\n         * The rest is divided evenly among the member nodes...\n         */\n        miss = miss/(4.0*nmemb);\n        for (k = 0,tri = surf->tris; k < ntri; k++,tri++) {\n            if (tri->vert[0] == j) {\n                row[tri->vert[1]] = row[tri->vert[1]] + miss;\n                row[tri->vert[2]] = row[tri->vert[2]] + miss;\n            }\n            else if (tri->vert[1] == j) {\n                row[tri->vert[0]] = row[tri->vert[0]] + miss;\n                row[tri->vert[2]] = row[tri->vert[2]] + miss;\n            }\n            else if (tri->vert[2] == j) {\n                row[tri->vert[0]] = row[tri->vert[0]] + miss;\n                row[tri->vert[1]] = row[tri->vert[1]] + miss;\n            }\n        }\n        /*\n         * Just check it it out...\n         *\n        for (k = 0, sum = 0; k < nnode; k++)\n          sum = sum + row[k];\n        fprintf (stderr,\"row %d sum = %g\\n\",j+1,sum/pi2);\n        */\n    }\n#endif\n    return;\n}\n\n\n//*************************************************************************************************************\n\nfloat **FwdBemModel::fwd_bem_lin_pot_coeff(const QList<MneSurfaceOld*>& surfs)\n/*\n* Calculate the coefficients for linear collocation approach\n*/\n{\n    float **mat = NULL;\n    float **sub_mat = NULL;\n    int   np1,np2,ntri,np_tot,np_max;\n    float **nodes;\n    MneTriangle*   tri;\n    double omega[3];\n    double *row = NULL;\n    int    j,k,p,q,c;\n    int    joff,koff;\n    MneSurfaceOld* surf1;\n    MneSurfaceOld* surf2;\n\n    for (p = 0, np_tot = np_max = 0; p < surfs.size(); p++) {\n        np_tot += surfs[p]->np;\n        if (surfs[p]->np > np_max)\n            np_max = surfs[p]->np;\n    }\n\n    mat = ALLOC_CMATRIX_40(np_tot,np_tot);\n    for (j = 0; j < np_tot; j++)\n        for (k = 0; k < np_tot; k++)\n            mat[j][k] = 0.0;\n    row        = MALLOC_40(np_max,double);\n    sub_mat = MALLOC_40(np_max,float *);\n    for (p = 0, joff = 0; p < surfs.size(); p++, joff = joff + np1) {\n        surf1 = surfs[p];\n        np1   = surf1->np;\n        nodes = surf1->rr;\n        for (q = 0, koff = 0; q < surfs.size(); q++, koff = koff + np2) {\n            surf2 = surfs[q];\n            np2   = surf2->np;\n            ntri  = surf2->ntri;\n\n            fprintf(stderr,\"\\t\\t%s (%d) -> %s (%d) ... \",\n                    fwd_bem_explain_surface(surf1->id).toUtf8().constData(),np1,\n                    fwd_bem_explain_surface(surf2->id).toUtf8().constData(),np2);\n\n            for (j = 0; j < np1; j++) {\n                for (k = 0; k < np2; k++)\n                    row[k] = 0.0;\n                for (k = 0, tri = surf2->tris; k < ntri; k++,tri++) {\n                    /*\n               * No contribution from a triangle that\n               * this vertex belongs to\n               */\n                    if (p == q && (tri->vert[0] == j || tri->vert[1] == j || tri->vert[2] == j))\n                        continue;\n                    /*\n               * Otherwise do the hard job\n               */\n                    lin_pot_coeff (nodes[j],tri,omega);\n                    for (c = 0; c < 3; c++)\n                        row[tri->vert[c]] = row[tri->vert[c]] - omega[c];\n                }\n                for (k = 0; k < np2; k++)\n                    mat[j+joff][k+koff] = row[k];\n            }\n            if (p == q) {\n                for (j = 0; j < np1; j++)\n                    sub_mat[j] = mat[j+joff]+koff;\n                correct_auto_elements (surf1,sub_mat);\n            }\n            fprintf(stderr,\"[done]\\n\");\n        }\n    }\n    FREE_40(row);\n    FREE_40(sub_mat);\n    return(mat);\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_linear_collocation_solution(FwdBemModel *m)\n/*\n     * Compute the linear collocation potential solution\n     */\n{\n    float **coeff = NULL;\n    float ip_mult;\n    int k;\n\n    if(m)\n        m->fwd_bem_free_solution();\n\n    fprintf(stderr,\"\\nComputing the linear collocation solution...\\n\");\n    fprintf (stderr,\"\\tMatrix coefficients...\\n\");\n    if ((coeff = fwd_bem_lin_pot_coeff (m->surfs)) == NULL)\n        goto bad;\n\n    for (k = 0, m->nsol = 0; k < m->nsurf; k++)\n        m->nsol += m->surfs[k]->np;\n\n    fprintf (stderr,\"\\tInverting the coefficient matrix...\\n\");\n    if ((m->solution = fwd_bem_multi_solution (coeff,m->gamma,m->nsurf,m->np)) == NULL)\n        goto bad;\n\n    /*\n       * IP approach?\n       */\n    if ((m->nsurf == 3) &&\n            (ip_mult = m->sigma[m->nsurf-2]/m->sigma[m->nsurf-1]) <= m->ip_approach_limit) {\n        float **ip_solution = NULL;\n\n        fprintf (stderr,\"IP approach required...\\n\");\n\n        fprintf (stderr,\"\\tMatrix coefficients (homog)...\\n\");\n        QList<MneSurfaceOld*> last_surfs;\n        last_surfs << m->surfs.last();\n        if ((coeff = fwd_bem_lin_pot_coeff(last_surfs))== NULL)//m->surfs+m->nsurf-1,1)) == NULL)\n            goto bad;\n\n        fprintf (stderr,\"\\tInverting the coefficient matrix (homog)...\\n\");\n        if ((ip_solution = fwd_bem_homog_solution (coeff,m->surfs[m->nsurf-1]->np)) == NULL)\n            goto bad;\n\n        fprintf (stderr,\"\\tModify the original solution to incorporate IP approach...\\n\");\n\n        fwd_bem_ip_modify_solution(m->solution,ip_solution,ip_mult,m->nsurf,m->np);\n        FREE_CMATRIX_40(ip_solution);\n\n    }\n    m->bem_method = FWD_BEM_LINEAR_COLL;\n    fprintf(stderr,\"Solution ready.\\n\");\n    return OK;\n\nbad : {\n        if(m)\n            m->fwd_bem_free_solution();\n        FREE_CMATRIX_40(coeff);\n        return FAIL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nfloat **FwdBemModel::fwd_bem_multi_solution(float **solids, float **gamma, int nsurf, int *ntri)       /* Number of triangles or nodes on each surface */\n/*\n          * Invert I - solids/(2*M_PI)\n          * Take deflation into account\n          * The matrix is destroyed after inversion\n          * This is the general multilayer case\n          */\n{\n    int j,k,p,q;\n    float defl;\n    float pi2 = 1.0/(2*M_PI);\n    float mult;\n    int   joff,koff,jup,kup,ntot;\n\n    for (j = 0,ntot = 0; j < nsurf; j++)\n        ntot += ntri[j];\n    defl = 1.0/ntot;\n    /*\n       * Modify the matrix\n       */\n    for (p = 0, joff = 0; p < nsurf; p++) {\n        jup = ntri[p] + joff;\n        for (q = 0, koff = 0; q < nsurf; q++) {\n            kup = ntri[q] + koff;\n            mult = (gamma == NULL) ? pi2 : pi2*gamma[p][q];\n            for (j = joff; j < jup; j++)\n                for (k = koff; k < kup; k++)\n                    solids[j][k] = defl - solids[j][k]*mult;\n            koff = kup;\n        }\n        joff = jup;\n    }\n    for (k = 0; k < ntot; k++)\n        solids[k][k] = solids[k][k] + 1.0;\n\n    return (mne_lu_invert_40(solids,ntot));\n}\n\n\n//*************************************************************************************************************\n\nfloat **FwdBemModel::fwd_bem_homog_solution(float **solids, int ntri)\n/*\n          * Invert I - solids/(2*M_PI)\n          * Take deflation into account\n          * The matrix is destroyed after inversion\n          * This is the homogeneous model case\n          */\n{\n    return fwd_bem_multi_solution (solids,NULL,1,&ntri);\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_ip_modify_solution(float **solution, float **ip_solution, float ip_mult, int nsurf, int *ntri)                  /* Number of triangles (nodes) on each surface */\n/*\n          * Modify the solution according to the IP approach\n          */\n{\n    int s;\n    int j,k,joff,koff,ntot,nlast;\n    float mult;\n    float *row = NULL;\n    float **sub = NULL;\n\n    for (s = 0, koff = 0; s < nsurf-1; s++)\n        koff = koff + ntri[s];\n    nlast = ntri[nsurf-1];\n    ntot  = koff + nlast;\n\n    row = MALLOC_40(nlast,float);\n    sub = MALLOC_40(ntot,float *);\n    mult = (1.0 + ip_mult)/ip_mult;\n\n    fprintf(stderr,\"\\t\\tCombining...\");\n#ifndef OLD\n    fprintf(stderr,\"t \");\n    mne_transpose_square_40(ip_solution,nlast);\n#endif\n    for (s = 0, joff = 0; s < nsurf; s++) {\n        fprintf(stderr,\"%d3 \",s+1);\n        /*\n        * Pick the correct submatrix\n        */\n        for (j = 0; j < ntri[s]; j++)\n            sub[j] = solution[j+joff]+koff;\n        /*\n        * Multiply\n        */\n#ifdef OLD\n        for (j = 0; j < ntri[s]; j++) {\n            for (k = 0; k < nlast; k++) {\n                res = mne_dot_vectors_skip_skip(sub[j],1,ip_solution[0]+k,nlast,nlast);\n                row[k] = sub[j][k] - 2.0*res;\n            }\n            for (k = 0; k < nlast; k++)\n                sub[j][k] = row[k];\n        }\n#else\n        for (j = 0; j < ntri[s]; j++) {\n            for (k = 0; k < nlast; k++)\n                row[k] = mne_dot_vectors_40(sub[j],ip_solution[k],nlast);\n            mne_add_scaled_vector_to_40(row,-2.0,sub[j],nlast);\n        }\n#endif\n        joff = joff+ntri[s];\n    }\n#ifndef OLD\n    fprintf(stderr,\"t \");\n    mne_transpose_square_40(ip_solution,nlast);\n#endif\n    fprintf(stderr,\"33 \");\n    /*\n    * The lower right corner is a special case\n    */\n    for (j = 0; j < nlast; j++)\n        for (k = 0; k < nlast; k++)\n            sub[j][k] = sub[j][k] + mult*ip_solution[j][k];\n    /*\n    * Final scaling\n    */\n    fprintf(stderr,\"done.\\n\\t\\tScaling...\");\n    mne_scale_vector_40(ip_mult,solution[0],ntot*ntot);\n    fprintf(stderr,\"done.\\n\");\n    FREE_40(row); FREE_40(sub);\n    return;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_check_solids(float **angles, int ntri1, int ntri2, float desired)\n/*\n* Check the angle computations\n*/\n{\n    float *sums = MALLOC_40(ntri1,float);\n    float sum;\n    int j,k;\n    int res = 0;\n\n    for (j = 0; j < ntri1; j++) {\n        sum = 0;\n        for (k = 0; k < ntri2; k++)\n            sum = sum + angles[j][k];\n        sums[j] = sum/(2*M_PI);\n    }\n    for (j = 0; j < ntri1; j++)\n        /*\n        * Three cases:\n        * same surface: sum = 2*pi\n        * to outer:     sum = 4*pi\n        * to inner:     sum = 0*pi;\n        */\n        if (std::fabs(sums[j]-desired) > 1e-4) {\n            printf(\"solid angle matrix: rowsum[%d] = 2PI*%g\",\n                   j+1,sums[j]);\n            res = -1;\n            break;\n        }\n    FREE_40(sums);\n    return res;\n}\n\n\n//*************************************************************************************************************\n\nfloat **FwdBemModel::fwd_bem_solid_angles(const QList<MneSurfaceOld*>& surfs)\n/*\n          * Compute the solid angle matrix\n          */\n{\n    MneSurfaceOld* surf1;\n    MneSurfaceOld* surf2;\n    MneTriangle* tri;\n    int ntri1,ntri2,ntri_tot;\n    int j,k,p,q;\n    int joff,koff;\n    float **solids;\n    float result;\n    float **sub_solids = NULL;\n    float desired;\n\n    for (p = 0,ntri_tot = 0; p < surfs.size(); p++)\n        ntri_tot += surfs[p]->ntri;\n\n    sub_solids = MALLOC_40(ntri_tot,float *);\n    solids = ALLOC_CMATRIX_40(ntri_tot,ntri_tot);\n    for (p = 0, joff = 0; p < surfs.size(); p++, joff = joff + ntri1) {\n        surf1 = surfs[p];\n        ntri1 = surf1->ntri;\n        for (q = 0, koff = 0; q < surfs.size(); q++, koff = koff + ntri2) {\n            surf2 = surfs[q];\n            ntri2 = surf2->ntri;\n            fprintf(stderr,\"\\t\\t%s (%d) -> %s (%d) ... \",fwd_bem_explain_surface(surf1->id).toUtf8().constData(),ntri1,fwd_bem_explain_surface(surf2->id).toUtf8().constData(),ntri2);\n            for (j = 0; j < ntri1; j++)\n                for (k = 0, tri = surf2->tris; k < ntri2; k++, tri++) {\n                    if (p == q && j == k)\n                        result = 0.0;\n                    else\n                        result = MneSurfaceOrVolume::solid_angle (surf1->tris[j].cent,tri);\n                    solids[j+joff][k+koff] = result;\n                }\n            for (j = 0; j < ntri1; j++)\n                sub_solids[j] = solids[j+joff]+koff;\n            fprintf(stderr,\"[done]\\n\");\n            if (p == q)\n                desired = 1;\n            else if (p < q)\n                desired = 0;\n            else\n                desired = 2;\n            if (fwd_bem_check_solids(sub_solids,ntri1,ntri2,desired) == FAIL) {\n                FREE_CMATRIX_40(solids);\n                FREE_40(sub_solids);\n                return NULL;\n            }\n        }\n    }\n    FREE_40(sub_solids);\n    return (solids);\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_constant_collocation_solution(FwdBemModel *m)\n/*\n     * Compute the solution for the constant collocation approach\n     */\n{\n    float  **solids = NULL;\n    int    k;\n    float  ip_mult;\n\n    if(m)\n        m->fwd_bem_free_solution();\n\n    fprintf(stderr,\"\\nComputing the constant collocation solution...\\n\");\n    fprintf(stderr,\"\\tSolid angles...\\n\");\n    if ((solids = fwd_bem_solid_angles(m->surfs)) == NULL)\n        goto bad;\n\n    for (k = 0, m->nsol = 0; k < m->nsurf; k++)\n        m->nsol += m->surfs[k]->ntri;\n\n    fprintf (stderr,\"\\tInverting the coefficient matrix...\\n\");\n    if ((m->solution = fwd_bem_multi_solution (solids,m->gamma,m->nsurf,m->ntri)) == NULL)\n        goto bad;\n    /*\n       * IP approach?\n       */\n    if ((m->nsurf == 3) &&\n            (ip_mult = m->sigma[m->nsurf-2]/m->sigma[m->nsurf-1]) <= m->ip_approach_limit) {\n        float **ip_solution = NULL;\n\n        fprintf (stderr,\"IP approach required...\\n\");\n\n        fprintf (stderr,\"\\tSolid angles (homog)...\\n\");\n        QList<MneSurfaceOld*> last_surfs;\n        last_surfs << m->surfs.last();\n        if ((solids = fwd_bem_solid_angles (last_surfs)) == NULL)//m->surfs+m->nsurf-1,1)) == NULL)\n            goto bad;\n\n        fprintf (stderr,\"\\tInverting the coefficient matrix (homog)...\\n\");\n        if ((ip_solution = fwd_bem_homog_solution (solids,m->surfs[m->nsurf-1]->ntri)) == NULL)\n            goto bad;\n\n        fprintf (stderr,\"\\tModify the original solution to incorporate IP approach...\\n\");\n        fwd_bem_ip_modify_solution(m->solution,ip_solution,ip_mult,m->nsurf,m->ntri);\n        FREE_CMATRIX_40(ip_solution);\n    }\n    m->bem_method = FWD_BEM_CONSTANT_COLL;\n    fprintf (stderr,\"Solution ready.\\n\");\n\n    return OK;\n\nbad : {\n        if(m)\n            m->fwd_bem_free_solution();\n        FREE_CMATRIX_40(solids);\n        return FAIL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_compute_solution(FwdBemModel *m, int bem_method)\n/*\n* Compute the solution\n*/\n{\n    /*\n        * Compute the solution\n        */\n    if (bem_method == FWD_BEM_LINEAR_COLL)\n        return fwd_bem_linear_collocation_solution(m);\n    else if (bem_method == FWD_BEM_CONSTANT_COLL)\n        return fwd_bem_constant_collocation_solution(m);\n\n    if(m)\n        m->fwd_bem_free_solution();\n    printf (\"Unknown BEM method: %d\\n\",bem_method);\n    return FAIL;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_load_recompute_solution(const QString& name, int bem_method, int force_recompute, FwdBemModel *m)\n/*\n* Load or recompute the potential solution matrix\n*/\n{\n    int solres;\n\n    if (!m) {\n        printf (\"No model specified for fwd_bem_load_recompute_solution\");\n        return FAIL;\n    }\n\n    if (!force_recompute) {\n        if(m)\n            m->fwd_bem_free_solution();\n        solres = fwd_bem_load_solution(name,bem_method,m);\n        if (solres == TRUE) {\n            fprintf(stderr,\"\\nLoaded %s BEM solution from %s\\n\",fwd_bem_explain_method(m->bem_method).toUtf8().constData(),name.toUtf8().constData());\n            return OK;\n        }\n        else if (solres == FAIL)\n            return FAIL;\n#ifdef DEBUG\n        else\n            fprintf(stderr,\"Desired BEM  solution not available in %s (%s)\\n\",name,err_get_error());\n#endif\n    }\n    if (bem_method == FWD_BEM_UNKNOWN)\n        bem_method = FWD_BEM_LINEAR_COLL;\n    return fwd_bem_compute_solution(m,bem_method);\n}\n\n\n//*************************************************************************************************************\n\nfloat FwdBemModel::fwd_bem_inf_field(float *rd, float *Q, float *rp, float *dir)     /* Which field component */\n/*\n     * Infinite-medium magnetic field\n     * (without \\mu_0/4\\pi)\n     */\n{\n    float diff[3],diff2,cross[3];\n\n    VEC_DIFF_40(rd,rp,diff);\n    diff2 = VEC_DOT_40(diff,diff);\n    CROSS_PRODUCT_40(Q,diff,cross);\n\n    return (VEC_DOT_40(cross,dir)/(diff2*sqrt(diff2)));\n}\n\n\n//*************************************************************************************************************\n\nfloat FwdBemModel::fwd_bem_inf_pot(float *rd, float *Q, float *rp)\t/* Potential point */\n/*\n     * The infinite medium potential\n     */\n{\n    float diff[3];\n    float diff2;\n    VEC_DIFF_40(rd,rp,diff);\n    diff2 = VEC_DOT_40(diff,diff);\n    return (VEC_DOT_40(Q,diff)/(4.0*M_PI*diff2*sqrt(diff2)));\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_specify_els(FwdBemModel* m, FwdCoilSet *els)\n/*\n     * Set up for computing the solution at a set of electrodes\n     */\n{\n    FwdCoil*     el;\n    MneSurfaceOld*  scalp;\n    int         k,p,q,v;\n    float       *one_sol,*pick_sol;\n    float       r[3],w[3],dist;\n    int         best;\n    MneTriangle* tri;\n    float       x,y,z;\n    FwdBemSolution* sol;\n\n    if (!m) {\n        printf(\"Model missing in fwd_bem_specify_els\");\n        goto bad;\n    }\n    if (!m->solution) {\n        printf(\"Solution not computed in fwd_bem_specify_els\");\n        goto bad;\n    }\n    if (!els || els->ncoil == 0)\n        return OK;\n    els->fwd_free_coil_set_user_data();\n    /*\n       * Hard work follows\n       */\n    els->user_data = sol = new FwdBemSolution();\n    els->user_data_free = FwdBemSolution::fwd_bem_free_coil_solution;\n\n    sol->ncoil = els->ncoil;\n    sol->np    = m->nsol;\n    sol->solution  = ALLOC_CMATRIX_40(sol->ncoil,sol->np);\n    /*\n       * Go through all coils\n       */\n    for (k = 0; k < els->ncoil; k++) {\n        el = els->coils[k];\n        one_sol = sol->solution[k];\n        for (q = 0; q < m->nsol; q++)\n            one_sol[q] = 0.0;\n        scalp = m->surfs[0];\n        /*\n         * Go through all 'integration points'\n         */\n        for (p = 0; p < el->np; p++) {\n            VEC_COPY_40(r,el->rmag[p]);\n            if (m->head_mri_t != NULL)\n                FiffCoordTransOld::fiff_coord_trans(r,m->head_mri_t,FIFFV_MOVE);\n            best = MneSurfaceOrVolume::mne_project_to_surface(scalp,NULL,r,FALSE,&dist);\n            if (best < 0) {\n                printf(\"One of the electrodes could not be projected onto the scalp surface. How come?\");\n                goto bad;\n            }\n            if (m->bem_method == FWD_BEM_CONSTANT_COLL) {\n                /*\n             * Simply pick the value at the triangle\n             */\n                pick_sol = m->solution[best];\n                for (q = 0; q < m->nsol; q++)\n                    one_sol[q] += el->w[p]*pick_sol[q];\n            }\n            else if (m->bem_method == FWD_BEM_LINEAR_COLL) {\n                /*\n             * Calculate a linear interpolation between the vertex values\n             */\n                tri = scalp->tris+best;\n                MneSurfaceOrVolume::mne_triangle_coords(r,scalp,best,&x,&y,&z);\n\n                w[X_40] = el->w[p]*(1.0 - x - y);\n                w[Y_40] = el->w[p]*x;\n                w[Z_40] = el->w[p]*y;\n                for (v = 0; v < 3; v++) {\n                    pick_sol = m->solution[tri->vert[v]];\n                    for (q = 0; q < m->nsol; q++)\n                        one_sol[q] += w[v]*pick_sol[q];\n                }\n            }\n            else {\n                printf(\"Unknown BEM approximation method : %d\\n\",m->bem_method);\n                goto bad;\n            }\n        }\n    }\n    return OK;\n\nbad : {\n        els->fwd_free_coil_set_user_data();\n        return FAIL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_pot_grad_calc(float *rd, float *Q, FwdBemModel* m, FwdCoilSet* els, int all_surfs, float *xgrad, float *ygrad, float *zgrad)\n/*\n* Compute the potentials due to a current dipole\n*/\n{\n    MneTriangle* tri;\n    int         ntri;\n    int         s,k,p,nsol,pp;\n    float       mult;\n    float       *v0,ee[3];\n    float       **solution;\n    float       mri_rd[3],mri_Q[3];\n\n    float  *grads[3];\n    float  *grad;\n\n    grads[0] = xgrad;\n    grads[1] = ygrad;\n    grads[2] = zgrad;\n\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n\n    VEC_COPY_40(mri_rd,rd);\n    VEC_COPY_40(mri_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(mri_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(mri_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    for (pp = 0; pp < 3; pp++) {\n        grad = grads[pp];\n\n        for (p = 0; p < 3; p++)\n            ee[p] = p == pp ? 1.0 : 0.0;\n        if (m->head_mri_t)\n            FiffCoordTransOld::fiff_coord_trans(ee,m->head_mri_t,FIFFV_NO_MOVE);\n\n        for (s = 0, p = 0; s < m->nsurf; s++) {\n            ntri = m->surfs[s]->ntri;\n            tri  = m->surfs[s]->tris;\n            mult = m->source_mult[s];\n            for (k = 0; k < ntri; k++, tri++)\n                v0[p++] = mult*fwd_bem_inf_pot_der(mri_rd,mri_Q,tri->cent,ee);\n        }\n        if (els) {\n            FwdBemSolution* sol = (FwdBemSolution*)els->user_data;\n            solution = sol->solution;\n            nsol     = sol->ncoil;\n        }\n        else {\n            solution = m->solution;\n            nsol     = all_surfs ? m->nsol : m->surfs[0]->ntri;\n        }\n        for (k = 0; k < nsol; k++)\n            grad[k] = mne_dot_vectors_40(solution[k],v0,m->nsol);\n    }\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_lin_pot_calc(float *rd, float *Q, FwdBemModel *m, FwdCoilSet *els, int all_surfs, float *pot)              /* Put the result here */\n/*\n* Compute the potentials due to a current dipole\n* using the linear potential approximation\n*/\n{\n    float **rr;\n    int   np;\n    int   s,k,p,nsol;\n    float mult,mri_rd[3],mri_Q[3];\n\n    float *v0;\n    float **solution;\n\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n\n    VEC_COPY_40(mri_rd,rd);\n    VEC_COPY_40(mri_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(mri_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(mri_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    for (s = 0, p = 0; s < m->nsurf; s++) {\n        np     = m->surfs[s]->np;\n        rr     = m->surfs[s]->rr;\n        mult   = m->source_mult[s];\n        for (k = 0; k < np; k++)\n            v0[p++] = mult*fwd_bem_inf_pot(mri_rd,mri_Q,rr[k]);\n    }\n    if (els) {\n        FwdBemSolution* sol = (FwdBemSolution*)els->user_data;\n        solution = sol->solution;\n        nsol     = sol->ncoil;\n    }\n    else {\n        solution = m->solution;\n        nsol     = all_surfs ? m->nsol : m->surfs[0]->np;\n    }\n    for (k = 0; k < nsol; k++)\n        pot[k] = mne_dot_vectors_40(solution[k],v0,m->nsol);\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_lin_pot_grad_calc(float *rd, float *Q, FwdBemModel *m, FwdCoilSet *els, int all_surfs, float *xgrad, float *ygrad, float *zgrad)\n/*\n* Compute the derivaties of potentials due to a current dipole with respect to the dipole position\n* using the linear potential approximation\n*/\n{\n    float **rr;\n    int   np;\n    int   s,k,p,nsol,pp;\n    float mult,mri_rd[3],mri_Q[3];\n\n    float *v0,ee[3];\n    float **solution;\n\n    float  *grads[3];\n    float  *grad;\n\n    grads[0] = xgrad;\n    grads[1] = ygrad;\n    grads[2] = zgrad;\n\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n\n    VEC_COPY_40(mri_rd,rd);\n    VEC_COPY_40(mri_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(mri_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(mri_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    for (pp = 0; pp < 3; pp++) {\n        grad = grads[pp];\n\n        for (p = 0; p < 3; p++)\n            ee[p] = p == pp ? 1.0 : 0.0;\n        if (m->head_mri_t)\n            FiffCoordTransOld::fiff_coord_trans(ee,m->head_mri_t,FIFFV_NO_MOVE);\n\n        for (s = 0, p = 0; s < m->nsurf; s++) {\n            np     = m->surfs[s]->np;\n            rr     = m->surfs[s]->rr;\n            mult   = m->source_mult[s];\n            for (k = 0; k < np; k++)\n                v0[p++] = mult*fwd_bem_inf_pot_der(mri_rd,mri_Q,rr[k],ee);\n        }\n        if (els) {\n            FwdBemSolution* sol = (FwdBemSolution*)els->user_data;\n            solution = sol->solution;\n            nsol     = sol->ncoil;\n        }\n        else {\n            solution = m->solution;\n            nsol     = all_surfs ? m->nsol : m->surfs[0]->np;\n        }\n        for (k = 0; k < nsol; k++)\n            grad[k] = mne_dot_vectors_40(solution[k],v0,m->nsol);\n    }\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_pot_calc(float *rd, float *Q, FwdBemModel *m, FwdCoilSet *els, int all_surfs, float *pot)\n/*\n          * Compute the potentials due to a current dipole\n          */\n{\n    MneTriangle* tri;\n    int         ntri;\n    int         s,k,p,nsol;\n    float       mult;\n    float       *v0;\n    float       **solution;\n    float       mri_rd[3],mri_Q[3];\n\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n\n    VEC_COPY_40(mri_rd,rd);\n    VEC_COPY_40(mri_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(mri_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(mri_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    for (s = 0, p = 0; s < m->nsurf; s++) {\n        ntri = m->surfs[s]->ntri;\n        tri  = m->surfs[s]->tris;\n        mult = m->source_mult[s];\n        for (k = 0; k < ntri; k++, tri++)\n            v0[p++] = mult*fwd_bem_inf_pot(mri_rd,mri_Q,tri->cent);\n    }\n    if (els) {\n        FwdBemSolution* sol = (FwdBemSolution*)els->user_data;\n        solution = sol->solution;\n        nsol     = sol->ncoil;\n    }\n    else {\n        solution = m->solution;\n        nsol     = all_surfs ? m->nsol : m->surfs[0]->ntri;\n    }\n    for (k = 0; k < nsol; k++)\n        pot[k] = mne_dot_vectors_40(solution[k],v0,m->nsol);\n    return;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_pot_els(float *rd, float *Q, FwdCoilSet *els, float *pot, void *client) /* The model */\n/*\n     * This version calculates the potential on all surfaces\n     */\n{\n    FwdBemModel*    m = (FwdBemModel*)client;\n    FwdBemSolution* sol = (FwdBemSolution*)els->user_data;\n\n    if (!m) {\n        printf(\"No BEM model specified to fwd_bem_pot_els\");\n        return FAIL;\n    }\n    if (!m->solution) {\n        printf(\"No solution available for fwd_bem_pot_els\");\n        return FAIL;\n    }\n    if (!sol || sol->ncoil != els->ncoil) {\n        printf(\"No appropriate electrode-specific data available in fwd_bem_pot_coils\");\n        return FAIL;\n    }\n    if (m->bem_method == FWD_BEM_CONSTANT_COLL)\n        fwd_bem_pot_calc(rd,Q,m,els,FALSE,pot);\n    else if (m->bem_method == FWD_BEM_LINEAR_COLL)\n        fwd_bem_lin_pot_calc(rd,Q,m,els,FALSE,pot);\n    else {\n        printf(\"Unknown BEM method : %d\",m->bem_method);\n        return FAIL;\n    }\n    return OK;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_pot_grad_els(float *rd, float *Q, FwdCoilSet *els, float *pot, float *xgrad, float *ygrad, float *zgrad, void *client) /* The model */\n/*\n     * This version calculates the potential on all surfaces\n     */\n{\n    FwdBemModel*    m = (FwdBemModel*)client;\n    FwdBemSolution* sol = (FwdBemSolution*)els->user_data;\n\n    if (!m) {\n        qCritical(\"No BEM model specified to fwd_bem_pot_els\");\n        return FAIL;\n    }\n    if (!m->solution) {\n        qCritical(\"No solution available for fwd_bem_pot_els\");\n        return FAIL;\n    }\n    if (!sol || sol->ncoil != els->ncoil) {\n        qCritical(\"No appropriate electrode-specific data available in fwd_bem_pot_coils\");\n        return FAIL;\n    }\n    if (m->bem_method == FWD_BEM_CONSTANT_COLL) {\n        if (pot)\n            fwd_bem_pot_calc(rd,Q,m,els,FALSE,pot);\n        fwd_bem_pot_grad_calc(rd,Q,m,els,FALSE,xgrad,ygrad,zgrad);\n    }\n    else if (m->bem_method == FWD_BEM_LINEAR_COLL) {\n        if (pot)\n            fwd_bem_lin_pot_calc(rd,Q,m,els,FALSE,pot);\n        fwd_bem_lin_pot_grad_calc(rd,Q,m,els,FALSE,xgrad,ygrad,zgrad);\n    }\n    else {\n        qCritical(\"Unknown BEM method : %d\",m->bem_method);\n        return FAIL;\n    }\n    return OK;\n}\n\n\n//*************************************************************************************************************\n\n#define ARSINH(x) log((x) + sqrt(1.0+(x)*(x)))\n\nvoid FwdBemModel::calc_f(double *xx, double *yy, double *f0, double *fx, double *fy)\t        /* The weights in the linear approximation */\n{\n    double det = -xx[Y_40]*yy[X_40] + xx[Z_40]*yy[X_40] +\n            xx[X_40]*yy[Y_40] - xx[Z_40]*yy[Y_40] - xx[X_40]*yy[Z_40] + xx[Y_40]*yy[Z_40];\n    int k;\n\n    f0[X_40] = -xx[Z_40]*yy[Y_40] + xx[Y_40]*yy[Z_40];\n    f0[Y_40] = xx[Z_40]*yy[X_40] - xx[X_40]*yy[Z_40];\n    f0[Z_40] = -xx[Y_40]*yy[X_40] + xx[X_40]*yy[Y_40];\n\n    fx[X_40] =  yy[Y_40] - yy[Z_40];\n    fx[Y_40] = -yy[X_40] + yy[Z_40];\n    fx[Z_40] = yy[X_40] - yy[Y_40];\n\n    fy[X_40] = -xx[Y_40] + xx[Z_40];\n    fy[Y_40] = xx[X_40] - xx[Z_40];\n    fy[Z_40] = -xx[X_40] + xx[Y_40];\n\n    for (k = 0; k < 3; k++) {\n        f0[k] = f0[k]/det;\n        fx[k] = fx[k]/det;\n        fy[k] = fy[k]/det;\n    }\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::calc_magic(double u, double z, double A, double B, double *beta, double *D)\n/*\n* Calculate Urankar's magic numbers\n*/\n{\n    double B2 = 1.0 + B*B;\n    double ABu = A + B*u;\n    *D = sqrt(u*u + z*z + ABu*ABu);\n    beta[0] = ABu/sqrt(u*u + z*z);\n    beta[1] = (A*B + B2*u)/sqrt(A*A + B2*z*z);\n    beta[2] = (B*z*z - A*u)/(z*(*D));\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::field_integrals(float *from, MneTriangle* to, double *I1p, double *T, double *S1, double *S2, double *f0, double *fx, double *fy)\n{\n    double y1[3],y2[3],y3[3];\n    double xx[4],yy[4];\n    double A,B,z,dx;\n    double beta[3],I1,Tx,Ty,Txx,Tyy,Sxx,mult;\n    double S1x,S1y,S2x,S2y;\n    double D1,B2;\n    int k;\n    /*\n       * Preliminaries...\n       *\n       * 1. Move origin to viewpoint...\n       *\n       */\n    VEC_DIFF_40(from,to->r1,y1);\n    VEC_DIFF_40(from,to->r2,y2);\n    VEC_DIFF_40(from,to->r3,y3);\n    /*\n       * 2. Calculate local xy coordinates...\n       */\n    xx[0] = VEC_DOT_40(y1,to->ex);\n    xx[1] = VEC_DOT_40(y2,to->ex);\n    xx[2] = VEC_DOT_40(y3,to->ex);\n    xx[3] = xx[0];\n\n    yy[0] = VEC_DOT_40(y1,to->ey);\n    yy[1] = VEC_DOT_40(y2,to->ey);\n    yy[2] = VEC_DOT_40(y3,to->ey);\n    yy[3] = yy[0];\n\n    calc_f (xx,yy,f0,fx,fy);\n    /*\n       * 3. Distance of the plane from origin...\n       */\n    z = VEC_DOT_40(y1,to->nn);\n    /*\n       * Put together the line integral...\n       * We use the convention where the local y-axis\n       * is parallel to the last side and, therefore, dx = 0\n       * on that side. We can thus omit the last side from this\n       * computation in some cases.\n       */\n    I1 = 0.0;\n    Tx = 0.0;\n    Ty = 0.0;\n    S1x = 0.0;\n    S1y = 0.0;\n    S2x = 0.0;\n    S2y = 0.0;\n    for (k = 0; k < 2; k++) {\n        dx = xx[k+1] - xx[k];\n        A = (yy[k]*xx[k+1] - yy[k+1]*xx[k])/dx;\n        B = (yy[k+1]-yy[k])/dx;\n        B2 = (1.0 + B*B);\n        /*\n         * Upper limit\n         */\n        calc_magic (xx[k+1],z,A,B,beta,&D1);\n        I1 = I1 - xx[k+1]*ARSINH(beta[0]) - (A/sqrt(1.0+B*B))*ARSINH(beta[1])\n                - z*atan(beta[2]);\n        Txx = ARSINH(beta[1])/sqrt(B2);\n        Tx = Tx + Txx;\n        Ty = Ty + B*Txx;\n        Sxx = (D1 - A*B*Txx)/B2;\n        S1x = S1x + Sxx;\n        S1y = S1y + B*Sxx;\n        Sxx = (B*D1 + A*Txx)/B2;\n        S2x = S2x + Sxx;\n        /*\n         * Lower limit\n         */\n        calc_magic (xx[k],z,A,B,beta,&D1);\n        I1 = I1 + xx[k]*ARSINH(beta[0]) + (A/sqrt(1.0+B*B))*ARSINH(beta[1])\n                + z*atan(beta[2]);\n        Txx = ARSINH(beta[1])/sqrt(B2);\n        Tx = Tx - Txx;\n        Ty = Ty - B*Txx;\n        Sxx = (D1 - A*B*Txx)/B2;\n        S1x = S1x - Sxx;\n        S1y = S1y - B*Sxx;\n        Sxx = (B*D1 + A*Txx)/B2;\n        S2x = S2x - Sxx;\n    }\n    /*\n       * Handle last side (dx = 0) in a special way;\n       */\n    mult = 1.0/sqrt(xx[k]*xx[k]+z*z);\n    /*\n       * Upper...\n       */\n    Tyy = ARSINH(mult*yy[k+1]);\n    Ty = Ty + Tyy;\n    S1y = S1y + xx[k]*Tyy;\n    /*\n       * Lower...\n       */\n    Tyy = ARSINH(mult*yy[k]);\n    Ty = Ty - Tyy;\n    S1y = S1y - xx[k]*Tyy;\n    /*\n       * Set return values\n       */\n    *I1p = I1;\n    T[X_40] = Tx;\n    T[Y_40] = Ty;\n    S1[X_40] = S1x;\n    S1[Y_40] = S1y;\n    S2[X_40] = S2x;\n    S2[Y_40] = -S1x;\n    return;\n}\n\n\n//*************************************************************************************************************\n\ndouble FwdBemModel::one_field_coeff(float *dest, float *normal, MneTriangle* tri)\n/*\n* Compute the integral over one triangle.\n* This looks magical but it is not.\n*/\n{\n    double *yy[4];\n    double y1[3],y2[3],y3[3];\n    double beta[3];\n    double bbeta[3];\n    double coeff[3];\n    int   j,k;\n\n    yy[0] = y1;\n    yy[1] = y2;\n    yy[2] = y3;\n    yy[3] = y1;\n    VEC_DIFF_40(dest,tri->r1,y1);\n    VEC_DIFF_40(dest,tri->r2,y2);\n    VEC_DIFF_40(dest,tri->r3,y3);\n    for (j = 0; j < 3; j++)\n        beta[j] = calc_beta(yy[j],yy[j+1]);\n    bbeta[0] = beta[2] - beta[0];\n    bbeta[1] = beta[0] - beta[1];\n    bbeta[2] = beta[1] - beta[2];\n\n    for (j = 0; j < 3; j++)\n        coeff[j] = 0.0;\n    for (j = 0; j < 3; j++)\n        for (k = 0; k < 3; k++)\n            coeff[k] = coeff[k] + yy[j][k]*bbeta[j];\n    return (VEC_DOT_40(coeff,normal));\n}\n\n\n//*************************************************************************************************************\n\nfloat **FwdBemModel::fwd_bem_field_coeff(FwdBemModel *m, FwdCoilSet *coils)\t/* Gradiometer coil positions */\n/*\n     * Compute the weighting factors to obtain the magnetic field\n     */\n{\n    MneSurfaceOld*     surf;\n    MneTriangle*    tri;\n    FwdCoil*        coil;\n    FwdCoilSet*     tcoils = NULL;\n    int            ntri;\n    float          **coeff = NULL;\n    int            j,k,p,s,off;\n    double         res;\n    double         mult;\n\n    if (m->solution == NULL) {\n        printf(\"Solution matrix missing in fwd_bem_field_coeff\");\n        return NULL;\n    }\n    if (m->bem_method != FWD_BEM_CONSTANT_COLL) {\n        printf(\"BEM method should be constant collocation for fwd_bem_field_coeff\");\n        return NULL;\n    }\n    if (coils->coord_frame != FIFFV_COORD_MRI) {\n        if (coils->coord_frame == FIFFV_COORD_HEAD) {\n            if (!m->head_mri_t) {\n                printf(\"head -> mri coordinate transform missing in fwd_bem_field_coeff\");\n                return NULL;\n            }\n            else {\n                if (!coils) {\n                    qWarning(\"No coils to duplicate\");\n                    return NULL;\n                }\n                /*\n                    * Make a transformed duplicate\n                    */\n                if ((tcoils = coils->dup_coil_set(m->head_mri_t)) == NULL)\n                    return NULL;\n                coils = tcoils;\n            }\n        }\n        else {\n            printf(\"Incompatible coil coordinate frame %d for fwd_bem_field_coeff\",coils->coord_frame);\n            return NULL;\n        }\n    }\n    ntri  = m->nsol;\n    coeff = ALLOC_CMATRIX_40(coils->ncoil,ntri);\n\n    for (s = 0, off = 0; s < m->nsurf; s++) {\n        surf = m->surfs[s];\n        ntri = surf->ntri;\n        tri  = surf->tris;\n        mult = m->field_mult[s];\n\n        for (k = 0; k < ntri; k++,tri++) {\n            for (j = 0; j < coils->ncoil; j++) {\n                coil = coils->coils[j];\n                res = 0.0;\n                for (p = 0; p < coil->np; p++)\n                    res = res + coil->w[p]*one_field_coeff(coil->rmag[p],coil->cosmag[p],tri);\n                coeff[j][k+off] = mult*res;\n            }\n        }\n        off = off + ntri;\n    }\n    delete tcoils;\n    return coeff;\n}\n\n\n//*************************************************************************************************************\n\ndouble FwdBemModel::calc_gamma(double *rk, double *rk1)\n{\n    double rkk1[3];\n    double size;\n    double res;\n\n    VEC_DIFF_40(rk,rk1,rkk1);\n    size = VEC_LEN_40(rkk1);\n\n    res = log((VEC_LEN_40(rk1)*size + VEC_DOT_40(rk1,rkk1))/\n              (VEC_LEN_40(rk)*size + VEC_DOT_40(rk,rkk1)))/size;\n    return (res);\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_one_lin_field_coeff_ferg(float *dest, float *dir, MneTriangle* tri, double *res)\t/* The results */\n{\n    double c[3];\t\t\t/* Component of dest vector normal to\n                                     * the triangle plane */\n    double A[3];\t\t\t/* Projection of dest onto the triangle */\n    double c1[3],c2[3],c3[3];\n    double y1[3],y2[3],y3[3];\n    double *yy[4],*cc[4];\n    double rjk[3][3];\n    double cross[3],triple,l1,l2,l3,solid,clen;\n    double common,sum,beta,gamma;\n    int    k;\n\n    yy[0] = y1;   cc[0] = c1;\n    yy[1] = y2;   cc[1] = c2;\n    yy[2] = y3;   cc[2] = c3;\n    yy[3] = y1;   cc[3] = c1;\n\n    VEC_DIFF_40(tri->r2,tri->r3,rjk[0]);\n    VEC_DIFF_40(tri->r3,tri->r1,rjk[1]);\n    VEC_DIFF_40(tri->r1,tri->r2,rjk[2]);\n\n    for (k = 0; k < 3; k++) {\n        y1[k] = tri->r1[k] - dest[k];\n        y2[k] = tri->r2[k] - dest[k];\n        y3[k] = tri->r3[k] - dest[k];\n    }\n    clen  = VEC_DOT_40(y1,tri->nn);\n    for (k = 0; k < 3; k++) {\n        c[k]  = clen*tri->nn[k];\n        A[k]  = dest[k] + c[k];\n        c1[k] = tri->r1[k] - A[k];\n        c2[k] = tri->r2[k] - A[k];\n        c3[k] = tri->r3[k] - A[k];\n    }\n    /*\n       * beta and gamma...\n       */\n    for (sum = 0.0, k = 0; k < 3; k++) {\n        CROSS_PRODUCT_40(cc[k],cc[k+1],cross);\n        beta  = VEC_DOT_40(cross,tri->nn);\n        gamma = calc_gamma (yy[k],yy[k+1]);\n        sum = sum + beta*gamma;\n    }\n    /*\n       * Solid angle...\n       */\n    CROSS_PRODUCT_40(y1,y2,cross);\n    triple = VEC_DOT_40(cross,y3);\n\n    l1 = VEC_LEN_40(y1);\n    l2 = VEC_LEN_40(y2);\n    l3 = VEC_LEN_40(y3);\n    solid = 2.0*atan2(triple,\n                      (l1*l2*l3+\n                       VEC_DOT_40(y1,y2)*l3+\n                       VEC_DOT_40(y1,y3)*l2+\n                       VEC_DOT_40(y2,y3)*l1));\n    /*\n       * Now we are ready to assemble it all together\n       */\n    common = (sum-clen*solid)/(2.0*tri->area);\n    for (k = 0; k < 3; k++)\n        res[k] = -VEC_DOT_40(rjk[k],dir)*common;\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_one_lin_field_coeff_uran(float *dest, float *dir, MneTriangle* tri, double *res)\t/* The results */\n{\n    double      I1,T[2],S1[2],S2[2];\n    double      f0[3],fx[3],fy[3];\n    double      res_x,res_y;\n    double      x_fac,y_fac;\n    int         k;\n    double      len;\n    /*\n       * Compute the component integrals\n       */\n    field_integrals (dest,tri,&I1,T,S1,S2,f0,fx,fy);\n    /*\n       * Compute the coefficient for each node...\n       */\n    len = VEC_LEN_40(dir);\n    dir[X_40] = dir[X_40]/len;\n    dir[Y_40] = dir[Y_40]/len;\n    dir[Z_40] = dir[Z_40]/len;\n\n    x_fac = -VEC_DOT_40(dir,tri->ex);\n    y_fac = -VEC_DOT_40(dir,tri->ey);\n    for (k = 0; k < 3; k++) {\n        res_x = f0[k]*T[X_40] + fx[k]*S1[X_40] + fy[k]*S2[X_40] + fy[k]*I1;\n        res_y = f0[k]*T[Y_40] + fx[k]*S1[Y_40] + fy[k]*S2[Y_40] - fx[k]*I1;\n        res[k] = x_fac*res_x + y_fac*res_y;\n    }\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_one_lin_field_coeff_simple(float *dest, float *normal, MneTriangle* source, double *res)     /* The result for each triangle node */\n/*\n          * Simple version...\n          */\n{\n    float diff[3];\n    float vec_result[3];\n    float dl;\n    int   k;\n    float *rr[3];\n\n\n    rr[0] = source->r1;\n    rr[1] = source->r2;\n    rr[2] = source->r3;\n\n    for (k = 0; k < 3; k++) {\n        VEC_DIFF_40(rr[k],dest,diff);\n        dl = VEC_DOT_40(diff,diff);\n        CROSS_PRODUCT_40(diff,source->nn,vec_result);\n        res[k] = source->area*VEC_DOT_40(vec_result,normal)/(3.0*dl*sqrt(dl));\n    }\n    return;\n}\n\n\n//*************************************************************************************************************\n\nfloat **FwdBemModel::fwd_bem_lin_field_coeff(FwdBemModel *m, FwdCoilSet *coils, int method)    /* Which integration formula to use */\n/*\n          * Compute the weighting factors to obtain the magnetic field\n          * in the linear potential approximation\n          */\n{\n    MneSurfaceOld*  surf;\n    MneTriangle* tri;\n    FwdCoil*     coil;\n    FwdCoilSet*  tcoils = NULL;\n    int         ntri;\n    float       **coeff  = NULL;\n    int         j,k,p,pp,off,s;\n    double      res[3],one[3];\n    float       mult;\n    linFieldIntFunc func;\n\n    if (m->solution == NULL) {\n        printf(\"Solution matrix missing in fwd_bem_lin_field_coeff\");\n        return NULL;\n    }\n    if (m->bem_method != FWD_BEM_LINEAR_COLL) {\n        printf(\"BEM method should be linear collocation for fwd_bem_lin_field_coeff\");\n        return NULL;\n    }\n    if (coils->coord_frame != FIFFV_COORD_MRI) {\n        if (coils->coord_frame == FIFFV_COORD_HEAD) {\n            if (!m->head_mri_t) {\n                printf(\"head -> mri coordinate transform missing in fwd_bem_lin_field_coeff\");\n                return NULL;\n            }\n            else {\n                if (!coils) {\n                    qWarning(\"No coils to duplicate\");\n                    return NULL;\n                }\n                /*\n                    * Make a transformed duplicate\n                    */\n                if ((tcoils = coils->dup_coil_set(m->head_mri_t)) == NULL)\n                    return NULL;\n                coils = tcoils;\n            }\n        }\n        else {\n            printf(\"Incompatible coil coordinate frame %d for fwd_bem_field_coeff\",coils->coord_frame);\n            return NULL;\n        }\n    }\n    if (method == FWD_BEM_LIN_FIELD_FERGUSON)\n        func = fwd_bem_one_lin_field_coeff_ferg;\n    else if (method == FWD_BEM_LIN_FIELD_URANKAR)\n        func = fwd_bem_one_lin_field_coeff_uran;\n    else\n        func = fwd_bem_one_lin_field_coeff_simple;\n\n    coeff = ALLOC_CMATRIX_40(coils->ncoil,m->nsol);\n    for (k = 0; k < m->nsol; k++)\n        for (j = 0; j < coils->ncoil; j++)\n            coeff[j][k] = 0.0;\n    /*\n       * Process each of the surfaces\n       */\n    for (s = 0, off = 0; s < m->nsurf; s++) {\n        surf = m->surfs[s];\n        ntri = surf->ntri;\n        tri  = surf->tris;\n        mult = m->field_mult[s];\n\n        for (k = 0; k < ntri; k++,tri++) {\n            for (j = 0; j < coils->ncoil; j++) {\n                coil = coils->coils[j];\n                for (pp = 0; pp < 3; pp++)\n                    res[pp] = 0;\n                /*\n             * Accumulate the coefficients for each triangle node...\n             */\n                for (p = 0; p < coil->np; p++) {\n                    func(coil->rmag[p],coil->cosmag[p],tri,one);\n                    for (pp = 0; pp < 3; pp++)\n                        res[pp] = res[pp] + coil->w[p]*one[pp];\n                }\n                /*\n             * Add these to the corresponding coefficient matrix\n             * elements...\n             */\n                for (pp = 0; pp < 3; pp++)\n                    coeff[j][tri->vert[pp]+off] = coeff[j][tri->vert[pp]+off] + mult*res[pp];\n            }\n        }\n        off = off + surf->np;\n    }\n    /*\n       * Discard the duplicate\n       */\n    delete tcoils;\n    return (coeff);\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_specify_coils(FwdBemModel *m, FwdCoilSet *coils)\n/*\n     * Set up for computing the solution at a set of coils\n      */\n{\n    float **sol = NULL;\n    FwdBemSolution* csol;\n\n    if (!m) {\n        printf(\"Model missing in fwd_bem_specify_coils\");\n        goto bad;\n    }\n    if (!m->solution) {\n        printf(\"Solution not computed in fwd_bem_specify_coils\");\n        goto bad;\n    }\n    if(coils)\n        coils->fwd_free_coil_set_user_data();\n    if (!coils || coils->ncoil == 0)\n        return OK;\n    if (m->bem_method == FWD_BEM_CONSTANT_COLL)\n        sol = fwd_bem_field_coeff(m,coils);\n    else if (m->bem_method == FWD_BEM_LINEAR_COLL)\n        sol = fwd_bem_lin_field_coeff(m,coils,FWD_BEM_LIN_FIELD_SIMPLE);\n    else {\n        printf(\"Unknown BEM method in fwd_bem_specify_coils : %d\",m->bem_method);\n        goto bad;\n    }\n    coils->user_data = csol = new FwdBemSolution();\n    coils->user_data_free   = FwdBemSolution::fwd_bem_free_coil_solution;\n\n    csol->ncoil     = coils->ncoil;\n    csol->np        = m->nsol;\n    csol->solution  = mne_mat_mat_mult_40(sol,\n                                          m->solution,\n                                          coils->ncoil,\n                                          m->nsol,\n                                          m->nsol);//TODO: Suspicion, that this is slow - use Eigen\n\n    FREE_CMATRIX_40(sol);\n    return OK;\n\nbad : {\n        FREE_CMATRIX_40(sol);\n        return FAIL;\n\n    }\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_lin_field_calc(float *rd, float *Q, FwdCoilSet *coils, FwdBemModel *m, float *B)\n/*\n     * Calculate the magnetic field in a set of coils\n     */\n{\n    float *v0;\n    int   s,k,p,np;\n    FwdCoil* coil;\n    float  mult;\n    float  **rr;\n    float  my_rd[3],my_Q[3];\n    FwdBemSolution* sol = (FwdBemSolution*)coils->user_data;\n    /*\n       * Infinite-medium potentials\n       */\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n    /*\n       * The dipole location and orientation must be transformed\n       */\n    VEC_COPY_40(my_rd,rd);\n    VEC_COPY_40(my_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(my_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(my_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    /*\n       * Compute the inifinite-medium potentials at the vertices\n       */\n    for (s = 0, p = 0; s < m->nsurf; s++) {\n        np     = m->surfs[s]->np;\n        rr     = m->surfs[s]->rr;\n        mult   = m->source_mult[s];\n        for (k = 0; k < np; k++)\n            v0[p++] = mult*fwd_bem_inf_pot(my_rd,my_Q,rr[k]);\n    }\n    /*\n       * Primary current contribution\n       * (can be calculated in the coil/dipole coordinates)\n       */\n    for (k = 0; k < coils->ncoil; k++) {\n        coil = coils->coils[k];\n        B[k] = 0.0;\n        for (p = 0; p < coil->np; p++)\n            B[k] = B[k] + coil->w[p]*fwd_bem_inf_field(rd,Q,coil->rmag[p],coil->cosmag[p]);\n    }\n    /*\n       * Volume current contribution\n       */\n    for (k = 0; k < coils->ncoil; k++)\n        B[k] = B[k] + mne_dot_vectors_40(sol->solution[k],v0,m->nsol);\n    /*\n       * Scale correctly\n       */\n    for (k = 0; k < coils->ncoil; k++)\n        B[k] = MAG_FACTOR*B[k];\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_field_calc(float *rd, float *Q, FwdCoilSet *coils, FwdBemModel *m, float *B)\n/*\n     * Calculate the magnetic field in a set of coils\n     */\n{\n    float *v0;\n    int   s,k,p,ntri;\n    FwdCoil* coil;\n    MneTriangle* tri;\n    float   mult;\n    float  my_rd[3],my_Q[3];\n    FwdBemSolution* sol = (FwdBemSolution*)coils->user_data;\n    /*\n       * Infinite-medium potentials\n       */\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n    /*\n       * The dipole location and orientation must be transformed\n       */\n    VEC_COPY_40(my_rd,rd);\n    VEC_COPY_40(my_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(my_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(my_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    /*\n       * Compute the inifinite-medium potentials at the centers of the triangles\n       */\n    for (s = 0, p = 0; s < m->nsurf; s++) {\n        ntri = m->surfs[s]->ntri;\n        tri  = m->surfs[s]->tris;\n        mult = m->source_mult[s];\n        for (k = 0; k < ntri; k++, tri++)\n            v0[p++] = mult*fwd_bem_inf_pot(my_rd,my_Q,tri->cent);\n    }\n    /*\n       * Primary current contribution\n       * (can be calculated in the coil/dipole coordinates)\n       */\n    for (k = 0; k < coils->ncoil; k++) {\n        coil = coils->coils[k];\n        B[k] = 0.0;\n        for (p = 0; p < coil->np; p++)\n            B[k] = B[k] + coil->w[p]*fwd_bem_inf_field(rd,Q,coil->rmag[p],coil->cosmag[p]);\n    }\n    /*\n       * Volume current contribution\n       */\n    for (k = 0; k < coils->ncoil; k++)\n        B[k] = B[k] + mne_dot_vectors_40(sol->solution[k],v0,m->nsol);\n    /*\n       * Scale correctly\n       */\n    for (k = 0; k < coils->ncoil; k++)\n        B[k] = MAG_FACTOR*B[k];\n    return;\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_field_grad_calc(float *rd, float *Q, FwdCoilSet* coils, FwdBemModel* m, float *xgrad, float *ygrad, float *zgrad)\n/*\n* Calculate the magnetic field in a set of coils\n*/\n{\n    FwdBemSolution* sol = (FwdBemSolution*)coils->user_data;\n    float          *v0;\n    int            s,k,p,ntri,pp;\n    FwdCoil*       coil;\n    MneTriangle*   tri;\n    float          mult;\n    float          *grads[3],ee[3],mri_ee[3],mri_rd[3],mri_Q[3];\n    float          *grad;\n\n    grads[0] = xgrad;\n    grads[1] = ygrad;\n    grads[2] = zgrad;\n    /*\n       * Infinite-medium potentials\n       */\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n    /*\n       * The dipole location and orientation must be transformed\n       */\n    VEC_COPY_40(mri_rd,rd);\n    VEC_COPY_40(mri_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(mri_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(mri_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    for (pp = 0; pp < 3; pp++) {\n        grad = grads[pp];\n        /*\n         * Select the correct gradient component\n         */\n        for (p = 0; p < 3; p++)\n            ee[p] = p == pp ? 1.0 : 0.0;\n        VEC_COPY_40(mri_ee,ee);\n        if (m->head_mri_t)\n            FiffCoordTransOld::fiff_coord_trans(mri_ee,m->head_mri_t,FIFFV_NO_MOVE);\n        /*\n         * Compute the inifinite-medium potential derivatives at the centers of the triangles\n         */\n        for (s = 0, p = 0; s < m->nsurf; s++) {\n            ntri = m->surfs[s]->ntri;\n            tri  = m->surfs[s]->tris;\n            mult = m->source_mult[s];\n            for (k = 0; k < ntri; k++, tri++) {\n                v0[p++] = mult*fwd_bem_inf_pot_der(mri_rd,mri_Q,tri->cent,mri_ee);\n            }\n        }\n        /*\n         * Primary current contribution\n         * (can be calculated in the coil/dipole coordinates)\n         */\n        for (k = 0; k < coils->ncoil; k++) {\n            coil = coils->coils[k];\n            grad[k] = 0.0;\n            for (p = 0; p < coil->np; p++)\n                grad[k] = grad[k] + coil->w[p]*fwd_bem_inf_field_der(rd,Q,coil->rmag[p],coil->cosmag[p],ee);\n        }\n        /*\n         * Volume current contribution\n         */\n        for (k = 0; k < coils->ncoil; k++)\n            grad[k] = grad[k] + mne_dot_vectors_40(sol->solution[k],v0,m->nsol);\n        /*\n         * Scale correctly\n         */\n        for (k = 0; k < coils->ncoil; k++)\n            grad[k] = MAG_FACTOR*grad[k];\n    }\n    return;\n}\n\n\n//*************************************************************************************************************\n\nfloat FwdBemModel::fwd_bem_inf_field_der(float *rd, float *Q, float *rp, float *dir, float *comp)\t   /* Which gradient component */\n/*\n* Derivative of the infinite-medium magnetic field with respect to\n* one of the dipole position coordinates (without \\mu_0/4\\pi)\n*/\n{\n    float diff[3],diff2,diff3,diff5,cross[3],crossn[3],res;\n\n    VEC_DIFF_40(rd,rp,diff);\n    diff2 = VEC_DOT_40(diff,diff);\n    diff3 = sqrt(diff2)*diff2;\n    diff5 = diff3*diff2;\n    CROSS_PRODUCT_40(Q,diff,cross);\n    CROSS_PRODUCT_40(dir,Q,crossn);\n\n    res = 3*VEC_DOT_40(cross,dir)*VEC_DOT_40(comp,diff)/diff5 - VEC_DOT_40(comp,crossn)/diff3;\n    return res;\n}\n\n\n//*************************************************************************************************************\n\nfloat FwdBemModel::fwd_bem_inf_pot_der(float *rd, float *Q, float *rp, float *comp) /* Which gradient component */\n/*\n* Derivative of the infinite-medium potential with respect to one of\n* the dipole position coordinates\n*/\n{\n    float diff[3];\n    float diff2,diff5,diff3;\n    float res;\n\n    VEC_DIFF_40(rd,rp,diff);\n    diff2 = VEC_DOT_40(diff,diff);\n    diff3 = sqrt(diff2)*diff2;\n    diff5 = diff3*diff2;\n\n    res = 3*VEC_DOT_40(Q,diff)*VEC_DOT_40(comp,diff)/diff5 - VEC_DOT_40(comp,Q)/diff3;\n    return (res/(4.0*M_PI));\n}\n\n\n//*************************************************************************************************************\n\nvoid FwdBemModel::fwd_bem_lin_field_grad_calc(float *rd, float *Q, FwdCoilSet *coils, FwdBemModel *m, float *xgrad, float *ygrad, float *zgrad)\n/*\n     * Calculate the gradient with respect to dipole position coordinates in a set of coils\n     */\n{\n    FwdBemSolution* sol = (FwdBemSolution*)coils->user_data;\n\n    float   *v0;\n    int     s,k,p,np,pp;\n    FwdCoil *coil;\n    float   mult;\n    float   **rr,ee[3],mri_ee[3],mri_rd[3],mri_Q[3];\n    float   *grads[3];\n    float   *grad;\n\n    grads[0] = xgrad;\n    grads[1] = ygrad;\n    grads[2] = zgrad;\n    /*\n       * Space for infinite-medium potentials\n       */\n    if (!m->v0)\n        m->v0 = MALLOC_40(m->nsol,float);\n    v0 = m->v0;\n    /*\n       * The dipole location and orientation must be transformed\n       */\n    VEC_COPY_40(mri_rd,rd);\n    VEC_COPY_40(mri_Q,Q);\n    if (m->head_mri_t) {\n        FiffCoordTransOld::fiff_coord_trans(mri_rd,m->head_mri_t,FIFFV_MOVE);\n        FiffCoordTransOld::fiff_coord_trans(mri_Q,m->head_mri_t,FIFFV_NO_MOVE);\n    }\n    for (pp = 0; pp < 3; pp++) {\n        grad = grads[pp];\n        /*\n         * Select the correct gradient component\n         */\n        for (p = 0; p < 3; p++)\n            ee[p] = p == pp ? 1.0 : 0.0;\n        VEC_COPY_40(mri_ee,ee);\n        if (m->head_mri_t)\n            FiffCoordTransOld::fiff_coord_trans(mri_ee,m->head_mri_t,FIFFV_NO_MOVE);\n        /*\n         * Compute the inifinite-medium potentials at the vertices\n         */\n        for (s = 0, p = 0; s < m->nsurf; s++) {\n            np     = m->surfs[s]->np;\n            rr     = m->surfs[s]->rr;\n            mult   = m->source_mult[s];\n\n            for (k = 0; k < np; k++)\n                v0[p++] = mult*fwd_bem_inf_pot_der(mri_rd,mri_Q,rr[k],mri_ee);\n        }\n        /*\n         * Primary current contribution\n         * (can be calculated in the coil/dipole coordinates)\n         */\n        for (k = 0; k < coils->ncoil; k++) {\n            coil = coils->coils[k];\n            grad[k] = 0.0;\n            for (p = 0; p < coil->np; p++)\n                grad[k] = grad[k] + coil->w[p]*fwd_bem_inf_field_der(rd,Q,coil->rmag[p],coil->cosmag[p],ee);\n        }\n        /*\n         * Volume current contribution\n         */\n        for (k = 0; k < coils->ncoil; k++)\n            grad[k] = grad[k] + mne_dot_vectors_40(sol->solution[k],v0,m->nsol);\n        /*\n         * Scale correctly\n         */\n        for (k = 0; k < coils->ncoil; k++)\n            grad[k] = MAG_FACTOR*grad[k];\n    }\n    return;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_field(float *rd, float *Q, FwdCoilSet *coils, float *B, void *client)  /* The model */\n/*\n     * This version calculates the magnetic field in a set of coils\n     * Call fwd_bem_specify_coils first to establish the coil-specific\n     * solution matrix\n     */\n{\n    FwdBemModel* m = (FwdBemModel*)client;\n    FwdBemSolution* sol = (FwdBemSolution*)coils->user_data;\n\n    if (!m) {\n        printf(\"No BEM model specified to fwd_bem_field\");\n        return FAIL;\n    }\n    if (!sol || !sol->solution || sol->ncoil != coils->ncoil) {\n        printf(\"No appropriate coil-specific data available in fwd_bem_field\");\n        return FAIL;\n    }\n    if (m->bem_method == FWD_BEM_CONSTANT_COLL)\n        fwd_bem_field_calc(rd,Q,coils,m,B);\n    else if (m->bem_method == FWD_BEM_LINEAR_COLL)\n        fwd_bem_lin_field_calc(rd,Q,coils,m,B);\n    else {\n        printf(\"Unknown BEM method : %d\",m->bem_method);\n        return FAIL;\n    }\n    return OK;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_bem_field_grad(float *rd, float Q[], FwdCoilSet *coils, float Bval[], float xgrad[], float ygrad[], float zgrad[], void *client)  /* Client data to be passed to some foward modelling routines */\n{\n    FwdBemModel* m = (FwdBemModel*)client;\n    FwdBemSolution* sol = (FwdBemSolution*)coils->user_data;\n\n    if (!m) {\n        qCritical(\"No BEM model specified to fwd_bem_field\");\n        return FAIL;\n    }\n    if (!sol || !sol->solution || sol->ncoil != coils->ncoil) {\n        qCritical(\"No appropriate coil-specific data available in fwd_bem_field\");\n        return FAIL;\n    }\n    if (m->bem_method == FWD_BEM_CONSTANT_COLL) {\n        if (Bval)\n            fwd_bem_field_calc(rd,Q,coils,m,Bval);\n        fwd_bem_field_grad_calc(rd,Q,coils,m,xgrad,ygrad,zgrad);\n    }\n    else if (m->bem_method == FWD_BEM_LINEAR_COLL) {\n        if (Bval)\n            fwd_bem_lin_field_calc(rd,Q,coils,m,Bval);\n        fwd_bem_lin_field_grad_calc(rd,Q,coils,m,xgrad,ygrad,zgrad);\n    }\n    else {\n        qCritical(\"Unknown BEM method : %d\",m->bem_method);\n        return FAIL;\n    }\n    return OK;\n\n}\n\n\n//*************************************************************************************************************\n\nvoid *FwdBemModel::meg_eeg_fwd_one_source_space(void *arg)\n/*\n* Compute the MEG or EEG forward solution for one source space\n* and possibly for only one source component\n*/\n{\n    FwdThreadArg* a = (FwdThreadArg*)arg;\n    MneSourceSpaceOld* s = a->s;\n    int            j,p,q;\n    float          *xyz[3];\n\n    p = a->off;\n    q = 3*a->off;\n    if (a->fixed_ori) {\t\t\t\t\t  /* The normal source component only */\n        if (a->field_pot_grad && a->res_grad) {                   /* Gradient requested? */\n            for (j = 0; j < s->np; j++)\n                if (s->inuse[j]) {\n                    if (a->field_pot_grad(s->rr[j],s->nn[j],a->coils_els,a->res[p],\n                                          a->res_grad[q],a->res_grad[q+1],a->res_grad[q+2],\n                                          a->client) != OK)\n                        goto bad;\n                    q = q + 3;\n                    p++;\n                }\n        }\n        else {\n            for (j = 0; j < s->np; j++)\n                if (s->inuse[j])\n                    if (a->field_pot(s->rr[j],s->nn[j],a->coils_els,a->res[p++],a->client) != OK)\n                        goto bad;\n        }\n    }\n    else {\t\t\t\t\t\t  /* All source components */\n        if (a->field_pot_grad && a->res_grad) {               /* Gradient requested? */\n            for (j = 0; j < s->np; j++) {\n                if (s->inuse[j]) {\n                    if (a->comp < 0) {\t\t\t\t  /* Compute all components */\n                        if (a->field_pot_grad(s->rr[j],Qx,a->coils_els,a->res[p],\n                                              a->res_grad[q],a->res_grad[q+1],a->res_grad[q+2],\n                                              a->client) != OK)\n                            goto bad;\n                        q = q + 3; p++;\n                        if (a->field_pot_grad(s->rr[j],Qy,a->coils_els,a->res[p],\n                                              a->res_grad[q],a->res_grad[q+1],a->res_grad[q+2],\n                                              a->client) != OK)\n                            goto bad;\n                        q = q + 3; p++;\n                        if (a->field_pot_grad(s->rr[j],Qz,a->coils_els,a->res[p],\n                                              a->res_grad[q],a->res_grad[q+1],a->res_grad[q+2],\n                                              a->client) != OK)\n                            goto bad;\n                        q = q + 3; p++;\n                    }\n                    else if (a->comp == 0) {\t\t\t  /* Compute x component */\n                        if (a->field_pot_grad(s->rr[j],Qx,a->coils_els,a->res[p],\n                                              a->res_grad[q],a->res_grad[q+1],a->res_grad[q+2],\n                                              a->client) != OK)\n                            goto bad;\n                        q = q + 3; p++;\n                        q = q + 3; p++;\n                        q = q + 3; p++;\n                    }\n                    else if (a->comp == 1) {\t\t\t  /* Compute y component */\n                        q = q + 3; p++;\n                        if (a->field_pot_grad(s->rr[j],Qy,a->coils_els,a->res[p],\n                                              a->res_grad[q],a->res_grad[q+1],a->res_grad[q+2],\n                                              a->client) != OK)\n                            goto bad;\n                        q = q + 3; p++;\n                        q = q + 3; p++;\n                    }\n                    else if (a->comp == 2) {\t\t\t  /* Compute z component */\n                        q = q + 3; p++;\n                        q = q + 3; p++;\n                        if (a->field_pot_grad(s->rr[j],Qz,a->coils_els,a->res[p],\n                                              a->res_grad[q],a->res_grad[q+1],a->res_grad[q+2],\n                                              a->client) != OK)\n                            goto bad;\n                        q = q + 3; p++;\n                    }\n                }\n            }\n        }\n        else {\n            for (j = 0; j < s->np; j++) {\n                if (s->inuse[j]) {\n                    if (a->vec_field_pot) {\n                        xyz[0] = a->res[p++];\n                        xyz[1] = a->res[p++];\n                        xyz[2] = a->res[p++];\n                        if (a->vec_field_pot(s->rr[j],a->coils_els,xyz,a->client) != OK)\n                            goto bad;\n                    }\n                    else {\n                        if (a->comp < 0) {\t\t\t\t  /* Compute all components here */\n                            if (a->field_pot(s->rr[j],Qx,a->coils_els,a->res[p++],a->client) != OK)\n                                goto bad;\n                            if (a->field_pot(s->rr[j],Qy,a->coils_els,a->res[p++],a->client) != OK)\n                                goto bad;\n                            if (a->field_pot(s->rr[j],Qz,a->coils_els,a->res[p++],a->client) != OK)\n                                goto bad;\n                        }\n                        else if (a->comp == 0) {\t\t\t  /* Compute x component */\n                            if (a->field_pot(s->rr[j],Qx,a->coils_els,a->res[p++],a->client) != OK)\n                                goto bad;\n                            p++; p++;\n                        }\n                        else if (a->comp == 1) {\t\t\t  /* Compute y component */\n                            p++;\n                            if (a->field_pot(s->rr[j],Qy,a->coils_els,a->res[p++],a->client) != OK)\n                                goto bad;\n                            p++;\n                        }\n                        else if (a->comp == 2) {\t\t\t  /* Compute z component */\n                            p++; p++;\n                            if (a->field_pot(s->rr[j],Qz,a->coils_els,a->res[p++],a->client) != OK)\n                                goto bad;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    a->stat = OK;\n    return NULL;\n\nbad : {\n        a->stat = FAIL;\n        return NULL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::compute_forward_meg(MneSourceSpaceOld **spaces,\n                                     int nspace,\n                                     FwdCoilSet *coils,\n                                     FwdCoilSet *comp_coils,\n                                     MneCTFCompDataSet *comp_data,\n                                     bool fixed_ori,\n                                     FwdBemModel *bem_model,\n                                     Vector3f *r0,\n                                     bool use_threads,\n                                     MneNamedMatrix **resp,\n                                     MneNamedMatrix **resp_grad)\n/*\n* Compute the MEG forward solution\n* Use either the sphere model or BEM in the calculations\n*/\n{\n    float               **res = NULL;       /* The forward solution matrix */\n    float               **res_grad = NULL;  /* The gradient with respect to the dipole position */\n    FwdCompData         *comp = NULL;\n    fwdFieldFunc        field;              /* Computes the field for one dipole orientation */\n    fwdVecFieldFunc     vec_field;          /* Computes the field for all dipole orientations */\n    fwdFieldGradFunc    field_grad;         /* Computes the field and gradient with respect to dipole position\n                                             * for one dipole orientation */\n    int                 nmeg = coils->ncoil;/* Number of channels */\n    int                 nsource;            /* Total number of sources */\n    int                 k,p,q,off;\n    QStringList         names;              /* Channel names */\n    void                *client;\n    FwdThreadArg*       one_arg = NULL;\n    int                 nproc = QThread::idealThreadCount();\n    QStringList         emptyList;\n\n    if (bem_model) {\n        /*\n         * Use the new compensated field computation\n         * It works the same way independent of whether or not the compensation is in effect\n         */\n#ifdef TEST\n        fprintf(stderr,\"Using differences.\\n\");\n        comp = FwdCompData::fwd_make_comp_data(comp_data,coils,comp_coils,\n                                               FwdBemModel::fwd_bem_field,NULL,my_bem_field_grad,bem_model,NULL);\n#else\n        comp = FwdCompData::fwd_make_comp_data(comp_data,coils,comp_coils,\n                                               FwdBemModel::fwd_bem_field,NULL,FwdBemModel::fwd_bem_field_grad,bem_model,NULL);\n#endif\n        if (!comp)\n            goto bad;\n        /*\n        * Field computation matrices...\n        */\n        qDebug() << \"!!!TODO Speed the following with Eigen up!\";\n        printf(\"Composing the field computation matrix...\");\n        if (fwd_bem_specify_coils(bem_model,coils) == FAIL)\n            goto bad;\n        fprintf(stderr,\"[done]\\n\");\n\n        if (comp->set && comp->set->current) { /* Test just to specify confusing output */\n            fprintf(stderr,\"Composing the field computation matrix (compensation coils)...\");\n            if (fwd_bem_specify_coils(bem_model,comp->comp_coils) == FAIL)\n                goto bad;\n            fprintf(stderr,\"[done]\\n\");\n        }\n        field      = FwdCompData::fwd_comp_field;\n        vec_field  = NULL;\n        field_grad = FwdCompData::fwd_comp_field_grad;\n        client     = comp;\n    }\n    else {\n        /*\n         * Use the new compensated field computation\n         * It works the same way independent of whether or not the compensation is in effect\n         */\n#ifdef TEST\n        fprintf(stderr,\"Using differences.\\n\");\n        comp = FwdCompData::fwd_make_comp_data(comp_data,coils,comp_coils,\n                                               fwd_sphere_field,\n                                               fwd_sphere_field_vec,\n                                               my_sphere_field_grad,\n                                               r0,NULL);\n#else\n        comp = FwdCompData::fwd_make_comp_data(comp_data,coils,comp_coils,\n                                               fwd_sphere_field,\n                                               fwd_sphere_field_vec,\n                                               fwd_sphere_field_grad,\n                                               r0,NULL);\n#endif\n        if (!comp)\n            goto bad;\n        field       = FwdCompData::fwd_comp_field;\n        vec_field   = FwdCompData::fwd_comp_field_vec;\n        field_grad  = FwdCompData::fwd_comp_field_grad;\n        client      = comp;\n    }\n    /*\n       * Count the sources\n       */\n    for (k = 0, nsource = 0; k < nspace; k++)\n        nsource += spaces[k]->nuse;\n    /*\n       * Allocate space for the solution\n       */\n    if (fixed_ori)\n        res = ALLOC_CMATRIX_40(nsource,nmeg);\n    else\n        res = ALLOC_CMATRIX_40(3*nsource,nmeg);\n    if (resp_grad) {\n        if (fixed_ori)\n            res_grad = ALLOC_CMATRIX_40(3*nsource,nmeg);\n        else\n            res_grad = ALLOC_CMATRIX_40(3*3*nsource,nmeg);\n    }\n    /*\n    * Set up the argument for the field computation\n    */\n    one_arg = new FwdThreadArg();\n    one_arg->res            = res;\n    one_arg->res_grad       = res_grad;\n    one_arg->off            = 0;\n    one_arg->coils_els      = coils;\n    one_arg->client         = client;\n    one_arg->s              = NULL;\n    one_arg->fixed_ori      = fixed_ori;\n    one_arg->field_pot      = field;\n    one_arg->vec_field_pot  = vec_field;\n    one_arg->field_pot_grad = field_grad;\n\n    if (nproc < 2)\n        use_threads = false;\n\n    if (use_threads) {\n        int            nthread  = (fixed_ori || vec_field || nproc < 6) ? nspace : 3*nspace;\n        QList <FwdThreadArg*> args; //fwdThreadArg   *args    = MALLOC_40(nthread,fwdThreadArg);\n        int            stat;\n        /*\n        * We need copies to allocate separate workspace for each thread\n        */\n        if (fixed_ori || vec_field || nproc < 6) {\n            for (k = 0, off = 0; k < nthread; k++) {\n                FwdThreadArg* t_arg = FwdThreadArg::create_meg_multi_thread_duplicate(one_arg,bem_model != NULL);\n                t_arg->s   = spaces[k];\n                t_arg->off = off;\n                off = fixed_ori ? off + spaces[k]->nuse : off + 3*spaces[k]->nuse;\n                args.append(t_arg);\n            }\n            fprintf(stderr,\"%d processors. I will use one thread for each of the %d source spaces.\\n\",\n                    nproc,nspace);\n        }\n        else {\n            for (k = 0, off = 0, q = 0; k < nspace; k++) {\n                for (p = 0; p < 3; p++,q++) {\n                    FwdThreadArg* t_arg = FwdThreadArg::create_meg_multi_thread_duplicate(one_arg,bem_model != NULL);\n                    t_arg->s    = spaces[k];\n                    t_arg->off  = off;\n                    t_arg->comp = p;\n                    args.append(t_arg);\n                }\n                off = fixed_ori ? off + spaces[k]->nuse : off + 3*spaces[k]->nuse;\n            }\n            fprintf(stderr,\"%d processors. I will use %d threads : %d source spaces x 3 source components.\\n\",\n                    nproc,nthread,nspace);\n        }\n        fprintf(stderr,\"Computing MEG at %d source locations (%s orientations)...\",\n                nsource,fixed_ori ? \"fixed\" : \"free\");\n        /*\n        * Ready to start the threads & Wait for them to complete\n        */\n        QtConcurrent::blockingMap(args, meg_eeg_fwd_one_source_space);\n        /*\n        * Check the results\n        */\n        for (k = 0, stat = OK; k < nthread; k++)\n            if (args[k]->stat != OK) {\n                stat = FAIL;\n                break;\n            }\n        for (k = 0; k < args.size(); k++)//nthread == args.size()\n            FwdThreadArg::free_meg_multi_thread_duplicate(args[k],bem_model != NULL);\n        if (stat != OK)\n            goto bad;\n    }\n    else {\n        fprintf(stderr,\"Computing MEG at %d source locations (%s orientations, no threads)...\",\n                nsource,fixed_ori ? \"fixed\" : \"free\");\n        for (k = 0, off = 0; k < nspace; k++) {\n            one_arg->s   = spaces[k];\n            one_arg->off = off;\n            meg_eeg_fwd_one_source_space(one_arg);\n            if (one_arg->stat != OK)\n                goto bad;\n            off = fixed_ori ? off + one_arg->s->nuse : off + 3*one_arg->s->nuse;\n        }\n    }\n    fprintf(stderr,\"done.\\n\");\n    {\n        QStringList orig_names;\n        for (k = 0; k < nmeg; k++)\n            orig_names.append(coils->coils[k]->chname);\n        names = orig_names;\n    }\n    if(one_arg)\n        delete one_arg;\n    if(comp)\n        delete comp;\n\n\n    *resp = MneNamedMatrix::build_named_matrix(fixed_ori ? nsource : 3*nsource,\n                                               nmeg,\n                                               emptyList,\n                                               names,\n                                               res);\n    if (resp_grad && res_grad)\n        *resp_grad = MneNamedMatrix::build_named_matrix(fixed_ori ? 3*nsource : 3*3*nsource,\n                                                        nmeg,\n                                                        emptyList,\n                                                        names,\n                                                        res_grad);\n    return OK;\n\nbad : {\n        if(one_arg)\n            delete one_arg;\n        if(comp)\n            delete comp;\n        FREE_CMATRIX_40(res);\n        FREE_CMATRIX_40(res_grad);\n        return FAIL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::compute_forward_eeg(MneSourceSpaceOld **spaces, int nspace, FwdCoilSet *els, bool fixed_ori, FwdBemModel *bem_model, FwdEegSphereModel *m, bool use_threads, MneNamedMatrix **resp, MneNamedMatrix **resp_grad)\n/*\n    * Compute the EEG forward solution\n    * Use either the sphere model or BEM in the calculations\n    */\n{\n    float            **res = NULL;          /* The forward solution matrix */\n    float            **res_grad = NULL;     /* The gradient with respect to the dipole position */\n    fwdFieldFunc     pot;                   /* Computes the potentials for one dipole orientation */\n    fwdVecFieldFunc  vec_pot;               /* Computes the potentials for all dipole orientations */\n    fwdFieldGradFunc pot_grad;              /* Computes the potential and gradient with respect to dipole position\n                                             * for one dipole orientation */\n    int             nsource;                /* Total number of sources */\n    int             neeg = els->ncoil;      /* Number of channels */\n    int             k,p,q,off;\n    QStringList     names;                  /* Channel names */\n    void            *client;\n    FwdThreadArg*   one_arg = NULL;\n    int             nproc = QThread::idealThreadCount();\n    QStringList     emptyList;\n    /*\n       * Count the sources\n       */\n    for (k = 0, nsource = 0; k < nspace; k++)\n        nsource += spaces[k]->nuse;\n\n    if (bem_model) {\n        if (fwd_bem_specify_els(bem_model,els) == FAIL)\n            goto bad;\n        client   = bem_model;\n        pot      = fwd_bem_pot_els;\n        vec_pot  = NULL;\n#ifdef TEST\n        fprintf(stderr,\"Using differences.\\n\");\n        pot_grad = my_bem_pot_grad;\n#else\n        pot_grad = fwd_bem_pot_grad_els;\n#endif\n    }\n    else {\n        if (m->nfit == 0) {\n            fprintf(stderr,\"Using the standard series expansion for a multilayer sphere model for EEG\\n\");\n            pot      = FwdEegSphereModel::fwd_eeg_multi_spherepot_coil1;\n            vec_pot  = NULL;\n            pot_grad = NULL;\n        }\n        else {\n            fprintf(stderr,\"Using the equivalent source approach in the homogeneous sphere for EEG\\n\");\n            pot      = FwdEegSphereModel::fwd_eeg_spherepot_coil;\n            vec_pot  = FwdEegSphereModel::fwd_eeg_spherepot_coil_vec;\n            pot_grad = FwdEegSphereModel::fwd_eeg_spherepot_grad_coil;\n        }\n        client   = m;\n    }\n    /*\n    * Allocate space for the solution\n    */\n    if (fixed_ori)\n        res = ALLOC_CMATRIX_40(nsource,neeg);\n    else\n        res = ALLOC_CMATRIX_40(3*nsource,neeg);\n    if (resp_grad) {\n        if (!pot_grad) {\n            qCritical(\"EEG gradient calculation function not available\");\n            goto bad;\n        }\n        if (fixed_ori)\n            res_grad = ALLOC_CMATRIX_40(3*nsource,neeg);\n        else\n            res_grad = ALLOC_CMATRIX_40(3*3*nsource,neeg);\n    }\n    /*\n       * Set up the argument for the field computation\n       */\n    one_arg = new FwdThreadArg();\n    one_arg->res            = res;\n    one_arg->res_grad       = res_grad;\n    one_arg->off            = 0;\n    one_arg->coils_els      = els;\n    one_arg->client         = client;\n    one_arg->s              = NULL;\n    one_arg->fixed_ori      = fixed_ori;\n    one_arg->field_pot      = pot;\n    one_arg->vec_field_pot  = vec_pot;\n    one_arg->field_pot_grad = pot_grad;\n\n    if (nproc < 2)\n        use_threads = false;\n\n    if (use_threads) {\n        int            nthread  = (fixed_ori || vec_pot || nproc < 6) ? nspace : 3*nspace;\n        QList <FwdThreadArg*> args; //FwdThreadArg*   *args    = MALLOC_40(nthread,FwdThreadArg*);\n        int            stat;\n        /*\n        * We need copies to allocate separate workspace for each thread\n        */\n        if (fixed_ori || vec_pot || nproc < 6) {\n            for (k = 0, off = 0; k < nthread; k++) {\n                FwdThreadArg* t_arg = FwdThreadArg::create_eeg_multi_thread_duplicate(one_arg,bem_model != NULL);\n                t_arg->s   = spaces[k];\n                t_arg->off = off;\n                off = fixed_ori ? off + spaces[k]->nuse : off + 3*spaces[k]->nuse;\n                args.append(t_arg);\n            }\n            printf(\"%d processors. I will use one thread for each of the %d source spaces.\\n\",nproc,nspace);\n        }\n        else {\n            for (k = 0, off = 0, q = 0; k < nspace; k++) {\n                for (p = 0; p < 3; p++,q++) {\n                    FwdThreadArg* t_arg = FwdThreadArg::create_eeg_multi_thread_duplicate(one_arg,bem_model != NULL);\n                    t_arg->s    = spaces[k];\n                    t_arg->off  = off;\n                    t_arg->comp = p;\n                    args.append(t_arg);\n                }\n                off = fixed_ori ? off + spaces[k]->nuse : off + 3*spaces[k]->nuse;\n            }\n            printf(\"%d processors. I will use %d threads : %d source spaces x 3 source components.\\n\",nproc,nthread,nspace);\n        }\n        printf(\"Computing EEG at %d source locations (%s orientations)...\",\n                nsource,fixed_ori ? \"fixed\" : \"free\");\n        /*\n        * Ready to start the threads & Wait for them to complete\n        */\n        QtConcurrent::blockingMap(args, meg_eeg_fwd_one_source_space);\n        /*\n        * Check the results\n        */\n        for (k = 0, stat = OK; k < nthread; k++)\n            if (args[k]->stat != OK) {\n                stat = FAIL;\n                break;\n            }\n        for (k = 0; k < args.size(); k++)//nthread == args.size()\n            FwdThreadArg::free_eeg_multi_thread_duplicate(args[k],bem_model != NULL);\n        if (stat != OK)\n            goto bad;\n    }\n    else {\n        fprintf(stderr,\"Computing EEG at %d source locations (%s orientations, no threads)...\",\n                nsource,fixed_ori ? \"fixed\" : \"free\");\n        for (k = 0, off = 0; k < nspace; k++) {\n            one_arg->s   = spaces[k];\n            one_arg->off = off;\n            meg_eeg_fwd_one_source_space(one_arg);\n            if (one_arg->stat != OK)\n                goto bad;\n            off = fixed_ori ? off + one_arg->s->nuse : off + 3*one_arg->s->nuse;\n        }\n    }\n    fprintf(stderr,\"done.\\n\");\n    {\n        QStringList orig_names;\n        for (k = 0; k < neeg; k++)\n            orig_names.append(els->coils[k]->chname);\n        names = orig_names;\n    }\n    if(one_arg)\n        delete one_arg;\n    *resp = MneNamedMatrix::build_named_matrix(fixed_ori ? nsource : 3*nsource,neeg,emptyList,names,res);\n    if (resp_grad && res_grad)\n        *resp_grad = MneNamedMatrix::build_named_matrix(fixed_ori ? 3*nsource : 3*3*nsource,neeg,emptyList,\n                                            names,res_grad);\n    return OK;\n\nbad : {\n        if(one_arg)\n            delete one_arg;\n        FREE_CMATRIX_40(res);\n        FREE_CMATRIX_40(res_grad);\n        return FAIL;\n    }\n}\n\n\n//*************************************************************************************************************\n\n#define EPS   1e-5   /* Points closer to origin than this many\n                        meters are considered to be at the\n                        origin */\n#define CEPS       1e-5\n\nint FwdBemModel::fwd_sphere_field(float *rd, float Q[], FwdCoilSet *coils, float Bval[], void *client)\t/* Client data will be the sphere model origin */\n{\n    /* This version uses Jukka Sarvas' field computation\n         for details, see\n\n         Jukka Sarvas:\n\n         Basic mathematical and electromagnetic concepts\n         of the biomagnetic inverse problem,\n\n         Phys. Med. Biol. 1987, Vol. 32, 1, 11-22\n\n         The formulas have been manipulated for efficient computation\n         by Matti Hamalainen, February 1990\n\n      */\n    float *r0 = (float *)client;      /* The sphere model origin */\n    float v[3],a_vec[3];\n    float a,a2,r,r2;\n    float ar,ar0,rr0;\n    float vr,ve,re,r0e;\n    float F,g0,gr,result,sum;\n    int   j,k,p;\n    FwdCoil* this_coil;\n    float *this_pos,*this_dir;\t/* These point to the coil structure! */\n    int   np;\n    float myrd[3];\n    float pos[3];\n    /*\n       * Shift to the sphere model coordinates\n       */\n    for (p = 0; p < 3; p++)\n        myrd[p] = rd[p] - r0[p];\n    rd = myrd;\n    /*\n       * Check for a dipole at the origin\n       */\n    for (k = 0 ; k < coils->ncoil ; k++)\n        if (FWD_IS_MEG_COIL(coils->coils[k]->coil_class))\n            Bval[k] = 0.0;\n    r = VEC_LEN_40(rd);\n    if (r > EPS)\t{\t\t/* The hard job */\n\n        CROSS_PRODUCT_40(Q,rd,v);\n\n        for (k = 0; k < coils->ncoil; k++) {\n            this_coil = coils->coils[k];\n            if (FWD_IS_MEG_COIL(this_coil->type)) {\n\n                np = this_coil->np;\n\n                for (j = 0, sum = 0.0; j < np; j++) {\n\n                    this_pos = this_coil->rmag[j];\n                    this_dir = this_coil->cosmag[j];\n\n                    for (p = 0; p < 3; p++)\n                        pos[p] = this_pos[p] - r0[p];\n                    this_pos = pos;\n                    result = 0.0;\n\n                    /* Vector from dipole to the field point */\n\n                    VEC_DIFF_40(rd,this_pos,a_vec);\n\n                    /* Compute the dot products needed */\n\n                    a2  = VEC_DOT_40(a_vec,a_vec);       a = sqrt(a2);\n\n                    if (a > 0.0) {\n                        r2  = VEC_DOT_40(this_pos,this_pos); r = sqrt(r2);\n                        if (r > 0.0) {\n                            rr0 = VEC_DOT_40(this_pos,rd);\n                            ar = (r2-rr0);\n                            if (std::fabs(ar/(a*r)+1.0) > CEPS) { /* There is a problem on the negative 'z' axis if the dipole location\n                                                    * and the field point are on the same line */\n                                ar0  = ar/a;\n\n                                ve = VEC_DOT_40(v,this_dir); vr = VEC_DOT_40(v,this_pos);\n                                re = VEC_DOT_40(this_pos,this_dir); r0e = VEC_DOT_40(rd,this_dir);\n\n                                /* The main ingredients */\n\n                                F  = a*(r*a + ar);\n                                gr = a2/r + ar0 + 2.0*(a+r);\n                                g0 = a + 2*r + ar0;\n\n                                /* Mix them together... */\n\n                                sum = sum + this_coil->w[j]*(ve*F + vr*(g0*r0e - gr*re))/(F*F);\n                            }\n                        }\n                    }\n                }\t\t\t\t/* All points done */\n                Bval[k] = MAG_FACTOR*sum;\n            }\n        }\n    }\n    return OK;          /* Happy conclusion: this works always */\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_sphere_field_vec(float *rd, FwdCoilSet *coils, float **Bval, void *client)\t/* Client data will be the sphere model origin */\n{\n    /* This version uses Jukka Sarvas' field computation\n         for details, see\n\n         Jukka Sarvas:\n\n         Basic mathematical and electromagnetic concepts\n         of the biomagnetic inverse problem,\n\n         Phys. Med. Biol. 1987, Vol. 32, 1, 11-22\n\n         The formulas have been manipulated for efficient computation\n         by Matti Hamalainen, February 1990\n\n         The idea of matrix kernels is from\n\n         Mosher, Leahy, and Lewis: EEG and MEG: Forward Solutions for Inverse Methods\n\n         which has been simplified here using standard vector notation\n\n      */\n    float *r0 = (float *)client;      /* The sphere model origin */\n    float a_vec[3],v1[3],v2[3];\n    float a,a2,r,r2;\n    float ar,ar0,rr0;\n    float re,r0e;\n    float F,g0,gr,g,sum[3];\n    int   j,k,p;\n    FwdCoil* this_coil;\n    float *this_pos,*this_dir;\t/* These point to the coil structure! */\n    int   np;\n    float myrd[3];\n    float pos[3];\n    /*\n       * Shift to the sphere model coordinates\n       */\n    for (p = 0; p < 3; p++)\n        myrd[p] = rd[p] - r0[p];\n    rd = myrd;\n    /*\n       * Check for a dipole at the origin\n       */\n    r = VEC_LEN_40(rd);\n    for (k = 0; k < coils->ncoil; k++) {\n        this_coil = coils->coils[k];\n        if (FWD_IS_MEG_COIL(this_coil->coil_class)) {\n            if (r < EPS) {\n                Bval[0][k] = Bval[1][k] = Bval[2][k] = 0.0;\n            }\n            else { \t/* The hard job */\n\n                np = this_coil->np;\n                sum[0] = sum[1] = sum[2] = 0.0;\n\n                for (j = 0; j < np; j++) {\n\n                    this_pos = this_coil->rmag[j];\n                    this_dir = this_coil->cosmag[j];\n\n                    for (p = 0; p < 3; p++)\n                        pos[p] = this_pos[p] - r0[p];\n                    this_pos = pos;\n\n                    /* Vector from dipole to the field point */\n\n                    VEC_DIFF_40(rd,this_pos,a_vec);\n\n                    /* Compute the dot products needed */\n\n                    a2  = VEC_DOT_40(a_vec,a_vec);       a = sqrt(a2);\n\n                    if (a > 0.0) {\n                        r2  = VEC_DOT_40(this_pos,this_pos); r = sqrt(r2);\n                        if (r > 0.0) {\n                            rr0 = VEC_DOT_40(this_pos,rd);\n                            ar = (r2-rr0);\n                            if (std::fabs(ar/(a*r)+1.0) > CEPS) { /* There is a problem on the negative 'z' axis if the dipole location\n                                                    * and the field point are on the same line */\n\n                                /* The main ingredients */\n\n                                ar0  = ar/a;\n                                F  = a*(r*a + ar);\n                                gr = a2/r + ar0 + 2.0*(a+r);\n                                g0 = a + 2*r + ar0;\n\n                                re = VEC_DOT_40(this_pos,this_dir); r0e = VEC_DOT_40(rd,this_dir);\n                                CROSS_PRODUCT_40(rd,this_dir,v1);\n                                CROSS_PRODUCT_40(rd,this_pos,v2);\n\n                                g = (g0*r0e - gr*re)/(F*F);\n                                /*\n                     * Mix them together...\n                     */\n                                for (p = 0; p < 3; p++)\n                                    sum[p] = sum[p] + this_coil->w[j]*(v1[p]/F + v2[p]*g);\n                            }\n                        }\n                    }\n                }\t\t\t\t/* All points done */\n                for (p = 0; p < 3; p++)\n                    Bval[p][k] = MAG_FACTOR*sum[p];\n            }\n        }\n    }\n    return OK;\t\t\t/* Happy conclusion: this works always */\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_sphere_field_grad(float *rd, float Q[], FwdCoilSet *coils, float Bval[], float xgrad[], float ygrad[], float zgrad[], void *client)  /* Client data to be passed to some foward modelling routines */\n/*\n* Compute the derivatives of the sphere model field with respect to\n* dipole coordinates\n*/\n{\n    /* This version uses Jukka Sarvas' field computation\n         for details, see\n\n         Jukka Sarvas:\n\n         Basic mathematical and electromagnetic concepts\n         of the biomagnetic inverse problem,\n\n         Phys. Med. Biol. 1987, Vol. 32, 1, 11-22\n\n         The formulas have been manipulated for efficient computation\n         by Matti Hamalainen, February 1990\n\n         */\n\n    float v[3],a_vec[3];\n    float a,a2,r,r2;\n    float ar,rr0;\n    float vr,ve,re,r0e;\n    float F,g0,gr,result,G,F2;\n\n    int   j,k,p;\n    float huu;\n    float ggr[3],gg0[3];\t\t/* Gradient of gr & g0 */\n    float ga[3];\t\t\t/* Grapdient of a */\n    float gar[3];\t\t\t/* Gradient of ar */\n    float gFF[3];\t\t\t/* Gradient of F divided by F */\n    float gresult[3];\n    float eQ[3],rQ[3];\t\t/* e x Q and r x Q */\n    int   do_field = 0;\n    FwdCoil* this_coil;\n    float *this_pos,*this_dir;\n    int   np;\n    float myrd[3];\n    float pos[3];\n    float *r0 = (float *)client;      /* The sphere model origin */\n    /*\n       * Shift to the sphere model coordinates\n       */\n    for (p = 0; p < 3; p++)\n        myrd[p] = rd[p] - r0[p];\n    rd = myrd;\n\n    if (Bval)\n        do_field = 1;\n\n    /* Check for a dipole at the origin */\n\n    r = VEC_LEN_40(rd);\n    for (k = 0; k < coils->ncoil ; k++) {\n        if (FWD_IS_MEG_COIL(coils->coils[k]->coil_class)) {\n            if (do_field)\n                Bval[k] = 0.0;\n            xgrad[k] = 0.0;\n            ygrad[k] = 0.0;\n            zgrad[k] = 0.0;\n        }\n    }\n    if (r > EPS) {\t\t/* The hard job */\n\n        v[X_40] = Q[Y_40]*rd[Z_40] - Q[Z_40]*rd[Y_40];\n        v[Y_40] = -Q[X_40]*rd[Z_40] + Q[Z_40]*rd[X_40];\n        v[Z_40] = Q[X_40]*rd[Y_40] - Q[Y_40]*rd[X_40];\n\n        for (k = 0 ; k < coils->ncoil ; k++) {\n\n            this_coil = coils->coils[k];\n\n            if (FWD_IS_MEG_COIL(this_coil->type)) {\n\n                np = this_coil->np;\n\n                for (j = 0; j < np; j++) {\n\n                    this_pos = this_coil->rmag[j];\n                    /*\n           * Shift to the sphere model coordinates\n           */\n                    for (p = 0; p < 3; p++)\n                        pos[p] = this_pos[p] - r0[p];\n                    this_pos = pos;\n\n                    this_dir = this_coil->cosmag[j];\n\n                    /* Vector from dipole to the field point */\n\n                    a_vec[X_40] = this_pos[X_40] - rd[X_40];\n                    a_vec[Y_40] = this_pos[Y_40] - rd[Y_40];\n                    a_vec[Z_40] = this_pos[Z_40] - rd[Z_40];\n\n                    /* Compute the dot and cross products needed */\n\n                    a2  = VEC_DOT_40(a_vec,a_vec);       a = sqrt(a2);\n                    r2  = VEC_DOT_40(this_pos,this_pos); r = sqrt(r2);\n                    rr0 = VEC_DOT_40(this_pos,rd);\n                    ar  = (r2 - rr0)/a;\n\n                    ve = VEC_DOT_40(v,this_dir); vr = VEC_DOT_40(v,this_pos);\n                    re = VEC_DOT_40(this_pos,this_dir); r0e = VEC_DOT_40(rd,this_dir);\n\n                    /* eQ = this_dir x Q */\n\n                    eQ[X_40] = this_dir[Y_40]*Q[Z_40] - this_dir[Z_40]*Q[Y_40];\n                    eQ[Y_40] = -this_dir[X_40]*Q[Z_40] + this_dir[Z_40]*Q[X_40];\n                    eQ[Z_40] = this_dir[X_40]*Q[Y_40] - this_dir[Y_40]*Q[X_40];\n\n                    /* rQ = this_pos x Q */\n\n                    rQ[X_40] = this_pos[Y_40]*Q[Z_40] - this_pos[Z_40]*Q[Y_40];\n                    rQ[Y_40] = -this_pos[X_40]*Q[Z_40] + this_pos[Z_40]*Q[X_40];\n                    rQ[Z_40] = this_pos[X_40]*Q[Y_40] - this_pos[Y_40]*Q[X_40];\n\n                    /* The main ingredients */\n\n                    F  = a*(r*a + r2 - rr0);\n                    F2 = F*F;\n                    gr = a2/r + ar + 2.0*(a+r);\n                    g0 = a + 2.0*r + ar;\n                    G = g0*r0e - gr*re;\n\n                    /* Mix them together... */\n\n                    result = (ve*F + vr*G)/F2;\n\n                    /* The computation of the gradient... */\n\n                    huu = 2.0 + 2.0*a/r;\n                    for (p = X_40; p <= Z_40; p++) {\n                        ga[p] = -a_vec[p]/a;\n                        gar[p] = -(ga[p]*ar + this_pos[p])/a;\n                        gg0[p] = ga[p] + gar[p];\n                        ggr[p] = huu*ga[p] + gar[p];\n                        gFF[p] = ga[p]/a - (r*a_vec[p] + a*this_pos[p])/F;\n                        gresult[p] = -2.0*result*gFF[p] + (eQ[p]+gFF[p]*ve)/F +\n                                (rQ[p]*G + vr*(gg0[p]*r0e + g0*this_dir[p] - ggr[p]*re))/F2;\n                    }\n\n                    if (do_field)\n                        Bval[k] = Bval[k] + this_coil->w[j]*result;\n                    xgrad[k] = xgrad[k] + this_coil->w[j]*gresult[X_40];\n                    ygrad[k] = ygrad[k] + this_coil->w[j]*gresult[Y_40];\n                    zgrad[k] = zgrad[k] + this_coil->w[j]*gresult[Z_40];\n                }\n                if (do_field)\n                    Bval[k] = MAG_FACTOR*Bval[k];\n                xgrad[k] = MAG_FACTOR*xgrad[k];\n                ygrad[k] = MAG_FACTOR*ygrad[k];\n                zgrad[k] = MAG_FACTOR*zgrad[k];\n            }\n        }\n    }\n    return OK;\t\t\t/* Happy conclusion: this works always */\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_mag_dipole_field(float *rm, float M[], FwdCoilSet *coils, float Bval[], void *client)\t/* Client data will be the sphere model origin */\n/*\n* This is for a specific dipole component\n*/\n{\n    int     j,k,np;\n    FwdCoil* this_coil;\n    float   sum,diff[3],dist,dist2,dist5,*dir;\n\n\n    for (k = 0; k < coils->ncoil; k++) {\n        this_coil = coils->coils[k];\n        if (FWD_IS_MEG_COIL(this_coil->type)) {\n            np = this_coil->np;\n            /*\n           * Go through all points\n           */\n            for (j = 0, sum = 0.0; j < np; j++) {\n                dir = this_coil->cosmag[j];\n                VEC_DIFF_40(rm,this_coil->rmag[j],diff);\n                dist = VEC_LEN_40(diff);\n                if (dist > EPS) {\n                    dist2 = dist*dist;\n                    dist5 = dist2*dist2*dist;\n                    sum = sum + this_coil->w[j]*(3*VEC_DOT_40(M,diff)*VEC_DOT_40(diff,dir) - dist2*VEC_DOT_40(M,dir))/dist5;\n                }\n            }\t\t\t\t/* All points done */\n            Bval[k] = MAG_FACTOR*sum;\n        }\n        else if (this_coil->type == FWD_COILC_EEG)\n            Bval[k] = 0.0;\n    }\n    return OK;\n}\n\n\n//*************************************************************************************************************\n\nint FwdBemModel::fwd_mag_dipole_field_vec(float *rm, FwdCoilSet *coils, float **Bval, void *client)     /* Client data will be the sphere model origin */\n/*\n* This is for all dipole components\n* For EEG this produces a zero result\n*/\n{\n    int     j,k,p,np;\n    FwdCoil* this_coil;\n    float   sum[3],diff[3],dist,dist2,dist5,*dir;\n\n\n    for (k = 0; k < coils->ncoil; k++) {\n        this_coil = coils->coils[k];\n        if (FWD_IS_MEG_COIL(this_coil->type)) {\n            np = this_coil->np;\n            sum[0] = sum[1] = sum[2] = 0.0;\n            /*\n           * Go through all points\n           */\n            for (j = 0; j < np; j++) {\n                dir = this_coil->cosmag[j];\n                VEC_DIFF_40(rm,this_coil->rmag[j],diff);\n                dist = VEC_LEN_40(diff);\n                if (dist > EPS) {\n                    dist2 = dist*dist;\n                    dist5 = dist2*dist2*dist;\n                    for (p = 0; p < 3; p++)\n                        sum[p] = sum[p] + this_coil->w[j]*(3*diff[p]*VEC_DOT_40(diff,dir) - dist2*dir[p])/dist5;\n                }\n            }           /* All points done */\n            for (p = 0; p < 3; p++)\n                Bval[p][k] = MAG_FACTOR*sum[p];\n        }\n        else if (this_coil->type == FWD_COILC_EEG) {\n            for (p = 0; p < 3; p++)\n                Bval[p][k] = 0.0;\n        }\n    }\n    return OK;\n}\n", "meta": {"hexsha": "4ad6c5127aced9c20344ddfd52ab84df8851adba", "size": 127422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fwd/fwd_bem_model.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/fwd/fwd_bem_model.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/fwd/fwd_bem_model.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": 31.8316262803, "max_line_length": 224, "alphanum_fraction": 0.4772409788, "num_tokens": 35806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082128783705344, "lm_q2_score": 0.016403032996992927, "lm_q1q2_score": 0.005262442170528953}}
{"text": "#ifndef CMDSTAN_COMMAND_HPP\n#define CMDSTAN_COMMAND_HPP\n\n#include <cmdstan/arguments/argument_parser.hpp>\n#include <cmdstan/arguments/arg_data.hpp>\n#include <cmdstan/arguments/arg_id.hpp>\n#include <cmdstan/arguments/arg_init.hpp>\n#include <cmdstan/arguments/arg_output.hpp>\n#include <cmdstan/arguments/arg_random.hpp>\n#include <cmdstan/write_model.hpp>\n#include <cmdstan/write_stan.hpp>\n#include <cmdstan/io/json/json_data.hpp>\n#include <stan/callbacks/interrupt.hpp>\n#include <stan/callbacks/logger.hpp>\n#include <stan/callbacks/stream_logger.hpp>\n#include <stan/callbacks/stream_writer.hpp>\n#include <stan/callbacks/writer.hpp>\n#include <stan/io/dump.hpp>\n#include <stan/io/stan_csv_reader.hpp>\n#include <stan/io/ends_with.hpp>\n#include <stan/model/model_base.hpp>\n#include <stan/services/diagnose/diagnose.hpp>\n#include <stan/services/optimize/bfgs.hpp>\n#include <stan/services/optimize/lbfgs.hpp>\n#include <stan/services/optimize/newton.hpp>\n#include <stan/services/sample/fixed_param.hpp>\n#include <stan/services/sample/hmc_nuts_dense_e.hpp>\n#include <stan/services/sample/hmc_nuts_dense_e_adapt.hpp>\n#include <stan/services/sample/hmc_nuts_diag_e.hpp>\n#include <stan/services/sample/hmc_nuts_diag_e_adapt.hpp>\n#include <stan/services/sample/hmc_nuts_unit_e.hpp>\n#include <stan/services/sample/hmc_nuts_unit_e_adapt.hpp>\n#include <stan/services/sample/hmc_static_dense_e.hpp>\n#include <stan/services/sample/hmc_static_dense_e_adapt.hpp>\n#include <stan/services/sample/hmc_static_diag_e.hpp>\n#include <stan/services/sample/hmc_static_diag_e_adapt.hpp>\n#include <stan/services/sample/hmc_static_unit_e.hpp>\n#include <stan/services/sample/hmc_static_unit_e_adapt.hpp>\n#include <stan/services/sample/standalone_gqs.hpp>\n#include <stan/services/experimental/advi/fullrank.hpp>\n#include <stan/services/experimental/advi/meanfield.hpp>\n#include <stan/math/opencl/opencl_context.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <boost/date_time/posix_time/posix_time_types.hpp>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <memory>\n\n#include <stan/math/prim/core/init_threadpool_tbb.hpp>\n\n#ifdef STAN_MPI\n#include <stan/math/prim/arr/functor/mpi_cluster.hpp>\n#include <stan/math/prim/arr/functor/mpi_command.hpp>\n#include <stan/math/prim/arr/functor/mpi_distributed_apply.hpp>\n#endif\n\n// forward declaration for function defined in another translation unit\nstan::model::model_base& new_model(stan::io::var_context& data_context,\n                                   unsigned int seed,\n                                   std::ostream* msg_stream);\n\nnamespace cmdstan {\n\n#ifdef STAN_MPI\n  stan::math::mpi_cluster& get_mpi_cluster() {\n    static stan::math::mpi_cluster cluster;\n    return cluster;\n  }\n#endif\n\n  std::shared_ptr<stan::io::var_context> get_var_context(const std::string file) {\n    std::fstream stream(file.c_str(), std::fstream::in);\n    if (file != \"\" && (stream.rdstate() & std::ifstream::failbit)) {\n      std::stringstream msg;\n      msg << \"Can't open specified file, \\\"\" << file << \"\\\"\" << std::endl;\n      throw std::invalid_argument(msg.str());\n    }\n    if (stan::io::ends_with(\".json\", file)) {\n      cmdstan::json::json_data var_context(stream);\n      stream.close();\n      std::shared_ptr<stan::io::var_context> result = std::make_shared<cmdstan::json::json_data>(var_context);\n      return result;\n    }\n    stan::io::dump var_context(stream);\n    stream.close();\n    std::shared_ptr<stan::io::var_context> result = std::make_shared<stan::io::dump>(var_context);\n    return result;\n  }\n\n  static int hmc_fixed_cols = 7; // hmc sampler outputs columns __lp + 6\n\n\n  int command(int argc, const char* argv[]) {\n    stan::callbacks::stream_writer info(std::cout);\n    stan::callbacks::stream_writer err(std::cout);\n    stan::callbacks::stream_logger logger(std::cout, std::cout, std::cout,\n                                          std::cerr, std::cerr);\n\n#ifdef STAN_MPI\n    stan::math::mpi_cluster& cluster = get_mpi_cluster();\n    cluster.listen();\n    if (cluster.rank_ != 0) return 0;\n#endif\n\n    stan::math::init_threadpool_tbb();\n\n    // Read arguments\n    std::vector<argument*> valid_arguments;\n    valid_arguments.push_back(new arg_id());\n    valid_arguments.push_back(new arg_data());\n    valid_arguments.push_back(new arg_init());\n    valid_arguments.push_back(new arg_random());\n    valid_arguments.push_back(new arg_output());\n    argument_parser parser(valid_arguments);\n    int err_code = parser.parse_args(argc, argv, info, err);\n    if (err_code != 0) {\n      std::cout << \"Failed to parse arguments, terminating Stan\" << std::endl;\n      return err_code;\n    }\n    if (parser.help_printed())\n      return err_code;\n\n    int_argument* random_arg = dynamic_cast<int_argument*>(parser.arg(\"random\")->arg(\"seed\"));\n    unsigned int random_seed;\n    if (random_arg->is_default()) {\n      random_seed = (boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::posix_time::min_date_time)).total_milliseconds();\n    } else {\n      random_seed = static_cast<unsigned int>(random_arg->value());\n    }\n    parser.print(info);\n    info();\n  \n#ifdef STAN_THREADS\n    std::stringstream msg_threads;\n    msg_threads << \"STAN_THREADS is enabled. map_rect will run with at most \";\n    msg_threads << stan::math::internal::get_num_threads();\n    msg_threads << \" thread(s).\" << std::endl;\n    info(msg_threads.str());\n#endif\n\n#ifdef STAN_OPENCL\n    \n    std::stringstream msg_opencl;\n    if((stan::math::opencl_context.platform() > 0) && (stan::math::opencl_context.device() > 0)) {\n      msg_opencl << \"STAN_OPENCL is enabled. OpenCL supported functions will use:\" << std::endl;\n      msg_opencl << \"Platform: \" << stan::math::opencl_context.platform()[0].getInfo<CL_PLATFORM_NAME>() << std::endl;    \n      msg_opencl << \"Device: \" << stan::math::opencl_context.device()[0].getInfo<CL_DEVICE_NAME>();\n      info(msg_opencl.str());\n    }    \n#endif\n\n    stan::callbacks::writer init_writer;\n    stan::callbacks::interrupt interrupt;\n\n\n    std::fstream output_stream(dynamic_cast<string_argument*>(parser.arg(\"output\")->arg(\"file\"))->value().c_str(),\n                               std::fstream::out);\n    stan::callbacks::stream_writer sample_writer(output_stream, \"# \");\n\n    std::fstream diagnostic_stream(dynamic_cast<string_argument*>(parser.arg(\"output\")->arg(\"diagnostic_file\"))->value().c_str(),\n                                   std::fstream::out);\n    stan::callbacks::stream_writer diagnostic_writer(diagnostic_stream, \"# \");\n\n\n    //////////////////////////////////////////////////\n    //                Initialize Model              //\n    //////////////////////////////////////////////////\n\n    std::string filename(dynamic_cast<string_argument*>(parser.arg(\"data\")->arg(\"file\"))->value());\n    std::shared_ptr<stan::io::var_context> var_context = get_var_context(filename);\n\n    stan::model::model_base& model = new_model(*var_context, random_seed, &std::cout);\n\n    write_stan(sample_writer);\n    write_model(sample_writer, model.model_name());\n    parser.print(sample_writer);\n\n    write_stan(diagnostic_writer);\n    write_model(diagnostic_writer, model.model_name());\n    parser.print(diagnostic_writer);\n\n    int refresh = dynamic_cast<int_argument*>(parser.arg(\"output\")->arg(\"refresh\"))->value();\n    unsigned int id = dynamic_cast<int_argument*>(parser.arg(\"id\"))->value();\n\n    std::string init = dynamic_cast<string_argument*>(parser.arg(\"init\"))->value();\n    double init_radius = 2.0;\n    // argument \"init\" can be non-negative number of filename\n    try {\n      init_radius = boost::lexical_cast<double>(init);\n      init = \"\";\n    } catch (const boost::bad_lexical_cast& e) {\n    }\n    std::shared_ptr<stan::io::var_context> init_context = get_var_context(init);\n\n    int return_code = stan::services::error_codes::CONFIG;\n\n    if (parser.arg(\"method\")->arg(\"generate_quantities\")) {\n      // read sample from cmdstan csv output file\n      string_argument* fitted_params_file =\n        dynamic_cast<string_argument*>(parser.arg(\"method\")->arg(\"generate_quantities\")->arg(\"fitted_params\"));\n      if (fitted_params_file->is_default()) {\n        info(\"Must specify argument fitted_params which is a csv file containing the sample.\");\n        return_code = stan::services::error_codes::CONFIG;\n      }\n      std::string fname(fitted_params_file->value());\n      std::ifstream stream(fname.c_str());\n      if (fname != \"\" && (stream.rdstate() & std::ifstream::failbit)) {\n        std::stringstream msg;\n        msg << \"Can't open specified file, \\\"\" << fname << \"\\\"\" << std::endl;\n        throw std::invalid_argument(msg.str());\n      }\n      stan::io::stan_csv fitted_params;\n      std::stringstream msg;\n      stan::io::stan_csv_reader::read_metadata(stream, fitted_params.metadata, &msg);\n      if (!stan::io::stan_csv_reader::read_header(stream, fitted_params.header, &msg)) {\n        msg << \"Error reading fitted param names from sample csv file \\\"\" << fname << \"\\\"\" << std::endl;\n        throw std::invalid_argument(msg.str());\n      }\n      stan::io::stan_csv_reader::read_adaptation(stream, fitted_params.adaptation, &msg);\n      fitted_params.timing.warmup = 0;\n      fitted_params.timing.sampling = 0;\n      stan::io::stan_csv_reader::read_samples(stream, fitted_params.samples, fitted_params.timing, &msg);\n      stream.close();\n\n      std::vector<std::string> param_names;\n      model.constrained_param_names(param_names, false, false);\n      size_t num_cols = param_names.size();\n      size_t num_rows = fitted_params.metadata.num_samples;\n\n      // check that all parameter names are in sample, in order\n      if (num_cols + hmc_fixed_cols > fitted_params.header.size()) {\n        std::stringstream msg;\n        msg << \"Mismatch between model and fitted_parameters csv file \\\"\" << fname << \"\\\"\" << std::endl;\n        throw std::invalid_argument(msg.str());\n      }\n      for (size_t i = 0; i < num_cols; ++i) {\n        if (param_names[i].compare(fitted_params.header[i + hmc_fixed_cols]) != 0) {\n          std::stringstream msg;\n          msg << \"Mismatch between model and fitted_parameters csv file \\\"\" << fname << \"\\\"\" << std::endl;\n          throw std::invalid_argument(msg.str());\n        }\n      }\n      return_code = stan::services::standalone_generate(model,\n                                          fitted_params.samples.block(0, hmc_fixed_cols, num_rows, num_cols),\n                                          random_seed,\n                                          interrupt,\n                                          logger,\n                                          sample_writer);\n    } else if (parser.arg(\"method\")->arg(\"diagnose\")) {\n      list_argument* test = dynamic_cast<list_argument*>(parser.arg(\"method\")->arg(\"diagnose\")->arg(\"test\"));\n\n      if (test->value() == \"gradient\") {\n        double epsilon = dynamic_cast<real_argument*>(test->arg(\"gradient\")->arg(\"epsilon\"))->value();\n        double error = dynamic_cast<real_argument*>(test->arg(\"gradient\")->arg(\"error\"))->value();\n        return_code = stan::services::diagnose::diagnose(model,\n                                                         *init_context,\n                                                         random_seed, id,\n                                                         init_radius,\n                                                         epsilon, error,\n                                                         interrupt,\n                                                         logger,\n                                                         init_writer,\n                                                         sample_writer);\n      }\n    } else if (parser.arg(\"method\")->arg(\"optimize\")) {\n      list_argument* algo = dynamic_cast<list_argument*>(parser.arg(\"method\")->arg(\"optimize\")->arg(\"algorithm\"));\n      int num_iterations = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"optimize\")->arg(\"iter\"))->value();\n      bool save_iterations = dynamic_cast<bool_argument*>(parser.arg(\"method\")->arg(\"optimize\")->arg(\"save_iterations\"))->value();\n\n      if (algo->value() == \"newton\") {\n        return_code = stan::services::optimize::newton(model,\n                                                       *init_context,\n                                                       random_seed,\n                                                       id,\n                                                       init_radius,\n                                                       num_iterations,\n                                                       save_iterations,\n                                                       interrupt,\n                                                       logger,\n                                                       init_writer,\n                                                       sample_writer);\n      } else if (algo->value() == \"bfgs\") {\n        double init_alpha = dynamic_cast<real_argument*>(algo->arg(\"bfgs\")->arg(\"init_alpha\"))->value();\n        double tol_obj = dynamic_cast<real_argument*>(algo->arg(\"bfgs\")->arg(\"tol_obj\"))->value();\n        double tol_rel_obj = dynamic_cast<real_argument*>(algo->arg(\"bfgs\")->arg(\"tol_rel_obj\"))->value();\n        double tol_grad = dynamic_cast<real_argument*>(algo->arg(\"bfgs\")->arg(\"tol_grad\"))->value();\n        double tol_rel_grad = dynamic_cast<real_argument*>(algo->arg(\"bfgs\")->arg(\"tol_rel_grad\"))->value();\n        double tol_param = dynamic_cast<real_argument*>(algo->arg(\"bfgs\")->arg(\"tol_param\"))->value();\n\n        return_code = stan::services::optimize::bfgs(model,\n                                                     *init_context,\n                                                     random_seed,\n                                                     id,\n                                                     init_radius,\n                                                     init_alpha,\n                                                     tol_obj,\n                                                     tol_rel_obj,\n                                                     tol_grad,\n                                                     tol_rel_grad,\n                                                     tol_param,\n                                                     num_iterations,\n                                                     save_iterations,\n                                                     refresh,\n                                                     interrupt,\n                                                     logger,\n                                                     init_writer,\n                                                     sample_writer);\n      } else if (algo->value() == \"lbfgs\") {\n        int history_size = dynamic_cast<int_argument*>(algo->arg(\"lbfgs\")->arg(\"history_size\"))->value();\n        double init_alpha = dynamic_cast<real_argument*>(algo->arg(\"lbfgs\")->arg(\"init_alpha\"))->value();\n        double tol_obj = dynamic_cast<real_argument*>(algo->arg(\"lbfgs\")->arg(\"tol_obj\"))->value();\n        double tol_rel_obj = dynamic_cast<real_argument*>(algo->arg(\"lbfgs\")->arg(\"tol_rel_obj\"))->value();\n        double tol_grad = dynamic_cast<real_argument*>(algo->arg(\"lbfgs\")->arg(\"tol_grad\"))->value();\n        double tol_rel_grad = dynamic_cast<real_argument*>(algo->arg(\"lbfgs\")->arg(\"tol_rel_grad\"))->value();\n        double tol_param = dynamic_cast<real_argument*>(algo->arg(\"lbfgs\")->arg(\"tol_param\"))->value();\n\n        return_code = stan::services::optimize::lbfgs(model,\n                                                      *init_context,\n                                                      random_seed,\n                                                      id,\n                                                      init_radius,\n                                                      history_size,\n                                                      init_alpha,\n                                                      tol_obj,\n                                                      tol_rel_obj,\n                                                      tol_grad,\n                                                      tol_rel_grad,\n                                                      tol_param,\n                                                      num_iterations,\n                                                      save_iterations,\n                                                      refresh,\n                                                      interrupt,\n                                                      logger,\n                                                      init_writer,\n                                                      sample_writer);\n      }\n    } else if (parser.arg(\"method\")->arg(\"sample\")) {\n      int num_warmup = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"sample\")->arg(\"num_warmup\"))->value();\n      int num_samples = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"sample\")->arg(\"num_samples\"))->value();\n      int num_thin = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"sample\")->arg(\"thin\"))->value();\n      bool save_warmup = dynamic_cast<bool_argument*>(parser.arg(\"method\")->arg(\"sample\")->arg(\"save_warmup\"))->value();\n      list_argument* algo = dynamic_cast<list_argument*>(parser.arg(\"method\")->arg(\"sample\")->arg(\"algorithm\"));\n      categorical_argument* adapt = dynamic_cast<categorical_argument*>(parser.arg(\"method\")->arg(\"sample\")->arg(\"adapt\"));\n      bool adapt_engaged = dynamic_cast<bool_argument*>(adapt->arg(\"engaged\"))->value();\n\n      if (model.num_params_r() == 0 && algo->value() != \"fixed_param\") {\n        info(\"Must use algorithm=fixed_param for model that has no parameters.\");\n        return_code = stan::services::error_codes::CONFIG;\n      } else if (algo->value() == \"fixed_param\") {\n        return_code = stan::services::sample::fixed_param(model,\n                                                          *init_context,\n                                                          random_seed,\n                                                          id,\n                                                          init_radius,\n                                                          num_samples,\n                                                          num_thin,\n                                                          refresh,\n                                                          interrupt,\n                                                          logger,\n                                                          init_writer,\n                                                          sample_writer,\n                                                          diagnostic_writer);\n      } else if (algo->value() == \"hmc\") {\n        list_argument* engine = dynamic_cast<list_argument*>(algo->arg(\"hmc\")->arg(\"engine\"));\n\n        list_argument* metric = dynamic_cast<list_argument*>(algo->arg(\"hmc\")->arg(\"metric\"));\n        string_argument* metric_file = dynamic_cast<string_argument*>(algo->arg(\"hmc\")->arg(\"metric_file\"));\n        bool metric_supplied = !metric_file->is_default();\n        std::string metric_filename(dynamic_cast<string_argument*>(algo->arg(\"hmc\")->arg(\"metric_file\"))->value());\n        std::shared_ptr<stan::io::var_context> metric_context = get_var_context(metric_filename);\n\n        categorical_argument* adapt = dynamic_cast<categorical_argument*>(parser.arg(\"method\")->arg(\"sample\")->arg(\"adapt\"));\n        categorical_argument* hmc = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\"));\n        double stepsize = dynamic_cast<real_argument*>(hmc->arg(\"stepsize\"))->value();\n        double stepsize_jitter= dynamic_cast<real_argument*>(hmc->arg(\"stepsize_jitter\"))->value();\n\n        if (adapt_engaged == true && num_warmup == 0) {\n          info(\"The number of warmup samples (num_warmup) must be greater than zero if adaptation is enabled.\");\n          return_code = stan::services::error_codes::CONFIG;\n        } else if (engine->value() == \"nuts\" && metric->value() == \"dense_e\" && adapt_engaged == false && metric_supplied == false) {\n          int max_depth = dynamic_cast<int_argument*>(dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"))->arg(\"max_depth\"))->value();\n          return_code = stan::services::sample::hmc_nuts_dense_e(model,\n                                                                 *init_context,\n                                                                 random_seed,\n                                                                 id,\n                                                                 init_radius,\n                                                                 num_warmup,\n                                                                 num_samples,\n                                                                 num_thin,\n                                                                 save_warmup,\n                                                                 refresh,\n                                                                 stepsize,\n                                                                 stepsize_jitter,\n                                                                 max_depth,\n                                                                 interrupt,\n                                                                 logger,\n                                                                 init_writer,\n                                                                 sample_writer,\n                                                                 diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"dense_e\" && adapt_engaged == false && metric_supplied == true) {\n          int max_depth = dynamic_cast<int_argument*>(dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"))->arg(\"max_depth\"))->value();\n          return_code = stan::services::sample::hmc_nuts_dense_e(model,\n                                                                 *init_context,\n                                                                 *metric_context,\n                                                                 random_seed,\n                                                                 id,\n                                                                 init_radius,\n                                                                 num_warmup,\n                                                                 num_samples,\n                                                                 num_thin,\n                                                                 save_warmup,\n                                                                 refresh,\n                                                                 stepsize,\n                                                                 stepsize_jitter,\n                                                                 max_depth,\n                                                                 interrupt,\n                                                                 logger,\n                                                                 init_writer,\n                                                                 sample_writer,\n                                                                 diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"dense_e\" && adapt_engaged == true && metric_supplied == false) {\n          int max_depth = dynamic_cast<int_argument*>(dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"))->arg(\"max_depth\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_nuts_dense_e_adapt(model,\n                                                                       *init_context,\n                                                                       random_seed,\n                                                                       id,\n                                                                       init_radius,\n                                                                       num_warmup,\n                                                                       num_samples,\n                                                                       num_thin,\n                                                                       save_warmup,\n                                                                       refresh,\n                                                                       stepsize,\n                                                                       stepsize_jitter,\n                                                                       max_depth,\n                                                                       delta,\n                                                                       gamma,\n                                                                       kappa,\n                                                                       t0,\n                                                                       init_buffer,\n                                                                       term_buffer,\n                                                                       window,\n                                                                       interrupt,\n                                                                       logger,\n                                                                       init_writer,\n                                                                       sample_writer,\n                                                                       diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"dense_e\" && adapt_engaged == true && metric_supplied == true) {\n          int max_depth = dynamic_cast<int_argument*>(dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"))->arg(\"max_depth\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_nuts_dense_e_adapt(model,\n                                                                       *init_context,\n                                                                       *metric_context,\n                                                                       random_seed,\n                                                                       id,\n                                                                       init_radius,\n                                                                       num_warmup,\n                                                                       num_samples,\n                                                                       num_thin,\n                                                                       save_warmup,\n                                                                       refresh,\n                                                                       stepsize,\n                                                                       stepsize_jitter,\n                                                                       max_depth,\n                                                                       delta,\n                                                                       gamma,\n                                                                       kappa,\n                                                                       t0,\n                                                                       init_buffer,\n                                                                       term_buffer,\n                                                                       window,\n                                                                       interrupt,\n                                                                       logger,\n                                                                       init_writer,\n                                                                       sample_writer,\n                                                                       diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"diag_e\" && adapt_engaged == false && metric_supplied == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"));\n          int max_depth = dynamic_cast<int_argument*>(base->arg(\"max_depth\"))->value();\n          return_code = stan::services::sample::hmc_nuts_diag_e(model,\n                                                                *init_context,\n                                                                random_seed,\n                                                                id,\n                                                                init_radius,\n                                                                num_warmup,\n                                                                num_samples,\n                                                                num_thin,\n                                                                save_warmup,\n                                                                refresh,\n                                                                stepsize,\n                                                                stepsize_jitter,\n                                                                max_depth,\n                                                                interrupt,\n                                                                logger,\n                                                                init_writer,\n                                                                sample_writer,\n                                                                diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"diag_e\" && adapt_engaged == false && metric_supplied == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"));\n          int max_depth = dynamic_cast<int_argument*>(base->arg(\"max_depth\"))->value();\n          return_code = stan::services::sample::hmc_nuts_diag_e(model,\n                                                                *init_context,\n                                                                *metric_context,\n                                                                random_seed,\n                                                                id,\n                                                                init_radius,\n                                                                num_warmup,\n                                                                num_samples,\n                                                                num_thin,\n                                                                save_warmup,\n                                                                refresh,\n                                                                stepsize,\n                                                                stepsize_jitter,\n                                                                max_depth,\n                                                                interrupt,\n                                                                logger,\n                                                                init_writer,\n                                                                sample_writer,\n                                                                diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"diag_e\" && adapt_engaged == true && metric_supplied == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"));\n          int max_depth = dynamic_cast<int_argument*>(base->arg(\"max_depth\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_nuts_diag_e_adapt(model,\n                                                                      *init_context,\n                                                                      random_seed,\n                                                                      id,\n                                                                      init_radius,\n                                                                      num_warmup,\n                                                                      num_samples,\n                                                                      num_thin,\n                                                                      save_warmup,\n                                                                      refresh,\n                                                                      stepsize,\n                                                                      stepsize_jitter,\n                                                                      max_depth,\n                                                                      delta,\n                                                                      gamma,\n                                                                      kappa,\n                                                                      t0,\n                                                                      init_buffer,\n                                                                      term_buffer,\n                                                                      window,\n                                                                      interrupt,\n                                                                      logger,\n                                                                      init_writer,\n                                                                      sample_writer,\n                                                                      diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"diag_e\" && adapt_engaged == true && metric_supplied == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"));\n          int max_depth = dynamic_cast<int_argument*>(base->arg(\"max_depth\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_nuts_diag_e_adapt(model,\n                                                                      *init_context,\n                                                                      *metric_context,\n                                                                      random_seed,\n                                                                      id,\n                                                                      init_radius,\n                                                                      num_warmup,\n                                                                      num_samples,\n                                                                      num_thin,\n                                                                      save_warmup,\n                                                                      refresh,\n                                                                      stepsize,\n                                                                      stepsize_jitter,\n                                                                      max_depth,\n                                                                      delta,\n                                                                      gamma,\n                                                                      kappa,\n                                                                      t0,\n                                                                      init_buffer,\n                                                                      term_buffer,\n                                                                      window,\n                                                                      interrupt,\n                                                                      logger,\n                                                                      init_writer,\n                                                                      sample_writer,\n                                                                      diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"unit_e\" && adapt_engaged == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"));\n          int max_depth = dynamic_cast<int_argument*>(base->arg(\"max_depth\"))->value();\n          return_code = stan::services::sample::hmc_nuts_unit_e(model,\n                                                                *init_context,\n                                                                random_seed,\n                                                                id,\n                                                                init_radius,\n                                                                num_warmup,\n                                                                num_samples,\n                                                                num_thin,\n                                                                save_warmup,\n                                                                refresh,\n                                                                stepsize,\n                                                                stepsize_jitter,\n                                                                max_depth,\n                                                                interrupt,\n                                                                logger,\n                                                                init_writer,\n                                                                sample_writer,\n                                                                diagnostic_writer);\n        } else if (engine->value() == \"nuts\" && metric->value() == \"unit_e\" && adapt_engaged == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"nuts\"));\n          int max_depth = dynamic_cast<int_argument*>(base->arg(\"max_depth\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          return_code = stan::services::sample::hmc_nuts_unit_e_adapt(model,\n                                                                      *init_context,\n                                                                      random_seed,\n                                                                      id,\n                                                                      init_radius,\n                                                                      num_warmup,\n                                                                      num_samples,\n                                                                      num_thin,\n                                                                      save_warmup,\n                                                                      refresh,\n                                                                      stepsize,\n                                                                      stepsize_jitter,\n                                                                      max_depth,\n                                                                      delta,\n                                                                      gamma,\n                                                                      kappa,\n                                                                      t0,\n                                                                      interrupt,\n                                                                      logger,\n                                                                      init_writer,\n                                                                      sample_writer,\n                                                                      diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"dense_e\" && adapt_engaged == false && metric_supplied == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          return_code = stan::services::sample::hmc_static_dense_e(model,\n                                                                   *init_context,\n                                                                   random_seed,\n                                                                   id,\n                                                                   init_radius,\n                                                                   num_warmup,\n                                                                   num_samples,\n                                                                   num_thin,\n                                                                   save_warmup,\n                                                                   refresh,\n                                                                   stepsize,\n                                                                   stepsize_jitter,\n                                                                   int_time,\n                                                                   interrupt,\n                                                                   logger,\n                                                                   init_writer,\n                                                                   sample_writer,\n                                                                   diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"dense_e\" && adapt_engaged == false && metric_supplied == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          return_code = stan::services::sample::hmc_static_dense_e(model,\n                                                                   *init_context,\n                                                                   *metric_context,\n                                                                   random_seed,\n                                                                   id,\n                                                                   init_radius,\n                                                                   num_warmup,\n                                                                   num_samples,\n                                                                   num_thin,\n                                                                   save_warmup,\n                                                                   refresh,\n                                                                   stepsize,\n                                                                   stepsize_jitter,\n                                                                   int_time,\n                                                                   interrupt,\n                                                                   logger,\n                                                                   init_writer,\n                                                                   sample_writer,\n                                                                   diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"dense_e\" && adapt_engaged == true && metric_supplied == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_static_dense_e_adapt(model,\n                                                                         *init_context,\n                                                                         random_seed,\n                                                                         id,\n                                                                         init_radius,\n                                                                         num_warmup,\n                                                                         num_samples,\n                                                                         num_thin,\n                                                                         save_warmup,\n                                                                         refresh,\n                                                                         stepsize,\n                                                                         stepsize_jitter,\n                                                                         int_time,\n                                                                         delta,\n                                                                         gamma,\n                                                                         kappa,\n                                                                         t0,\n                                                                         init_buffer,\n                                                                         term_buffer,\n                                                                         window,\n                                                                         interrupt,\n                                                                         logger,\n                                                                         init_writer,\n                                                                         sample_writer,\n                                                                         diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"dense_e\" && adapt_engaged == true && metric_supplied == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_static_dense_e_adapt(model,\n                                                                         *init_context,\n                                                                         *metric_context,\n                                                                         random_seed,\n                                                                         id,\n                                                                         init_radius,\n                                                                         num_warmup,\n                                                                         num_samples,\n                                                                         num_thin,\n                                                                         save_warmup,\n                                                                         refresh,\n                                                                         stepsize,\n                                                                         stepsize_jitter,\n                                                                         int_time,\n                                                                         delta,\n                                                                         gamma,\n                                                                         kappa,\n                                                                         t0,\n                                                                         init_buffer,\n                                                                         term_buffer,\n                                                                         window,\n                                                                         interrupt,\n                                                                         logger,\n                                                                         init_writer,\n                                                                         sample_writer,\n                                                                         diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"diag_e\" && adapt_engaged == false && metric_supplied == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          return_code = stan::services::sample::hmc_static_diag_e(model,\n                                                                  *init_context,\n                                                                  random_seed,\n                                                                  id,\n                                                                  init_radius,\n                                                                  num_warmup,\n                                                                  num_samples,\n                                                                  num_thin,\n                                                                  save_warmup,\n                                                                  refresh,\n                                                                  stepsize,\n                                                                  stepsize_jitter,\n                                                                  int_time,\n                                                                  interrupt,\n                                                                  logger,\n                                                                  init_writer,\n                                                                  sample_writer,\n                                                                  diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"diag_e\" && adapt_engaged == false && metric_supplied == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          return_code = stan::services::sample::hmc_static_diag_e(model,\n                                                                  *init_context,\n                                                                  *metric_context,\n                                                                  random_seed,\n                                                                  id,\n                                                                  init_radius,\n                                                                  num_warmup,\n                                                                  num_samples,\n                                                                  num_thin,\n                                                                  save_warmup,\n                                                                  refresh,\n                                                                  stepsize,\n                                                                  stepsize_jitter,\n                                                                  int_time,\n                                                                  interrupt,\n                                                                  logger,\n                                                                  init_writer,\n                                                                  sample_writer,\n                                                                  diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"diag_e\" && adapt_engaged == true && metric_supplied == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_static_diag_e_adapt(model,\n                                                                        *init_context,\n                                                                        random_seed,\n                                                                        id,\n                                                                        init_radius,\n                                                                        num_warmup,\n                                                                        num_samples,\n                                                                        num_thin,\n                                                                        save_warmup,\n                                                                        refresh,\n                                                                        stepsize,\n                                                                        stepsize_jitter,\n                                                                        int_time,\n                                                                        delta,\n                                                                        gamma,\n                                                                        kappa,\n                                                                        t0,\n                                                                        init_buffer,\n                                                                        term_buffer,\n                                                                        window,\n                                                                        interrupt,\n                                                                        logger,\n                                                                        init_writer,\n                                                                        sample_writer,\n                                                                        diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"diag_e\" && adapt_engaged == true && metric_supplied == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          unsigned int init_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"init_buffer\"))->value();\n          unsigned int term_buffer = dynamic_cast<u_int_argument*>(adapt->arg(\"term_buffer\"))->value();\n          unsigned int window = dynamic_cast<u_int_argument*>(adapt->arg(\"window\"))->value();\n          return_code = stan::services::sample::hmc_static_diag_e_adapt(model,\n                                                                        *init_context,\n                                                                        *metric_context,\n                                                                        random_seed,\n                                                                        id,\n                                                                        init_radius,\n                                                                        num_warmup,\n                                                                        num_samples,\n                                                                        num_thin,\n                                                                        save_warmup,\n                                                                        refresh,\n                                                                        stepsize,\n                                                                        stepsize_jitter,\n                                                                        int_time,\n                                                                        delta,\n                                                                        gamma,\n                                                                        kappa,\n                                                                        t0,\n                                                                        init_buffer,\n                                                                        term_buffer,\n                                                                        window,\n                                                                        interrupt,\n                                                                        logger,\n                                                                        init_writer,\n                                                                        sample_writer,\n                                                                        diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"unit_e\" && adapt_engaged == false) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          return_code = stan::services::sample::hmc_static_unit_e(model,\n                                                                  *init_context,\n                                                                  random_seed,\n                                                                  id,\n                                                                  init_radius,\n                                                                  num_warmup,\n                                                                  num_samples,\n                                                                  num_thin,\n                                                                  save_warmup,\n                                                                  refresh,\n                                                                  stepsize,\n                                                                  stepsize_jitter,\n                                                                  int_time,\n                                                                  interrupt,\n                                                                  logger,\n                                                                  init_writer,\n                                                                  sample_writer,\n                                                                  diagnostic_writer);\n        } else if (engine->value() == \"static\" && metric->value() == \"unit_e\" && adapt_engaged == true) {\n          categorical_argument* base = dynamic_cast<categorical_argument*>(algo->arg(\"hmc\")->arg(\"engine\")->arg(\"static\"));\n          double int_time = dynamic_cast<real_argument*>(base->arg(\"int_time\"))->value();\n          double delta = dynamic_cast<real_argument*>(adapt->arg(\"delta\"))->value();\n          double gamma = dynamic_cast<real_argument*>(adapt->arg(\"gamma\"))->value();\n          double kappa = dynamic_cast<real_argument*>(adapt->arg(\"kappa\"))->value();\n          double t0 = dynamic_cast<real_argument*>(adapt->arg(\"t0\"))->value();\n          return_code = stan::services::sample::hmc_static_unit_e_adapt(model,\n                                                                        *init_context,\n                                                                        random_seed,\n                                                                        id,\n                                                                        init_radius,\n                                                                        num_warmup,\n                                                                        num_samples,\n                                                                        num_thin,\n                                                                        save_warmup,\n                                                                        refresh,\n                                                                        stepsize,\n                                                                        stepsize_jitter,\n                                                                        int_time,\n                                                                        delta,\n                                                                        gamma,\n                                                                        kappa,\n                                                                        t0,\n                                                                        interrupt,\n                                                                        logger,\n                                                                        init_writer,\n                                                                        sample_writer,\n                                                                        diagnostic_writer);\n        }\n      }\n    } else if (parser.arg(\"method\")->arg(\"variational\")) {\n      list_argument* algo = dynamic_cast<list_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"algorithm\"));\n      int grad_samples = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"grad_samples\"))->value();\n      int elbo_samples = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"elbo_samples\"))->value();\n      int max_iterations = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"iter\"))->value();\n      double tol_rel_obj = dynamic_cast<real_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"tol_rel_obj\"))->value();\n      double eta = dynamic_cast<real_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"eta\"))->value();\n      bool adapt_engaged = dynamic_cast<bool_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"adapt\")->arg(\"engaged\"))->value();\n      int adapt_iterations = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"adapt\")->arg(\"iter\"))->value();\n      int eval_elbo = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"eval_elbo\"))->value();\n      int output_samples = dynamic_cast<int_argument*>(parser.arg(\"method\")->arg(\"variational\")->arg(\"output_samples\"))->value();\n\n      if (algo->value() == \"fullrank\") {\n        return_code = stan::services::experimental::advi::fullrank(model,\n                                                                   *init_context,\n                                                                   random_seed,\n                                                                   id,\n                                                                   init_radius,\n                                                                   grad_samples,\n                                                                   elbo_samples,\n                                                                   max_iterations,\n                                                                   tol_rel_obj,\n                                                                   eta,\n                                                                   adapt_engaged,\n                                                                   adapt_iterations,\n                                                                   eval_elbo,\n                                                                   output_samples,\n                                                                   interrupt,\n                                                                   logger,\n                                                                   init_writer,\n                                                                   sample_writer,\n                                                                   diagnostic_writer);\n      } else if (algo->value() == \"meanfield\") {\n        return_code = stan::services::experimental::advi::meanfield(model,\n                                                                    *init_context,\n                                                                    random_seed,\n                                                                    id,\n                                                                    init_radius,\n                                                                    grad_samples,\n                                                                    elbo_samples,\n                                                                    max_iterations,\n                                                                    tol_rel_obj,\n                                                                    eta,\n                                                                    adapt_engaged,\n                                                                    adapt_iterations,\n                                                                    eval_elbo,\n                                                                    output_samples,\n                                                                    interrupt,\n                                                                    logger,\n                                                                    init_writer,\n                                                                    sample_writer,\n                                                                    diagnostic_writer);\n      }\n    }\n\n    output_stream.close();\n    diagnostic_stream.close();\n    for (size_t i = 0; i < valid_arguments.size(); ++i)\n      delete valid_arguments.at(i);\n#ifdef STAN_MPI\n    cluster.stop_listen();\n#endif\n    return return_code;\n  }\n\n}\n#endif\n", "meta": {"hexsha": "ba34f14f2e85ddc006972448938e96e6bda5e193", "size": 71805, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cmdstan/command.hpp", "max_stars_repo_name": "wesbarnett/cmdstan", "max_stars_repo_head_hexsha": "4aaab0f38c386991dfbc54ff3460b48d6ead2cbd", "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/cmdstan/command.hpp", "max_issues_repo_name": "wesbarnett/cmdstan", "max_issues_repo_head_hexsha": "4aaab0f38c386991dfbc54ff3460b48d6ead2cbd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cmdstan/command.hpp", "max_forks_repo_name": "wesbarnett/cmdstan", "max_forks_repo_head_hexsha": "4aaab0f38c386991dfbc54ff3460b48d6ead2cbd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.5189243028, "max_line_length": 164, "alphanum_fraction": 0.3560754822, "num_tokens": 9532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206881431678098, "lm_q2_score": 0.02479815992531721, "lm_q1q2_score": 0.005258916372599934}}
{"text": "//\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2015  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// Credits: the nitty gritty of this is based on code by Peter Fisk and Bruce Warrington\n//\n\n#include <stdio.h>\n#include <cstdlib>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <cstring>\n#include <cmath>\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <vector>\n\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/split.hpp>\n\n#include \"Antenna.h\"\n#include \"Application.h\"\n#include \"Debug.h\"\n#include \"GPS.h\"\n#include \"HexBin.h\"\n#include \"Javad.h\"\n#include \"ReceiverMeasurement.h\"\n#include \"SVMeasurement.h\"\n#include \"Timer.h\"\n\nextern ostream *debugStream;\nextern Application *app;\n\n// JAVAD types\n#define I1 char\n#define I2 short\n#define I4 int\n#define U1 unsigned char\n#define U2 unsigned short\n#define U4 unsigned int\n#define F4 float\n#define F8 double\n\n#define MAX_CHANNELS 32\n\n// Receiver message flags\n#define AZ_MSG 0x01\n#define EL_MSG 0x02\n#define F1_MSG 0x04\n#define F2_MSG 0x08\n#define FC_MSG 0x10\n#define R1_r1_1R_1r_MSG 0x20\n#define R2_r2_2R_2r_MSG 0x40\n#define RC_rc_MSG 0x80\n#define RD_MSG 0x100\n#define RT_MSG 0x200\n#define SI_MSG 0x400\n#define SS_MSG 0x800\n#define TO_MSG 0x1000\n#define YA_MSG 0x2000\n#define ZA_MSG 0x4000\n\nJavad::Javad(Antenna *ant,string m):Receiver(ant)\n{\n  modelName=m;\n\tmanufacturer=\"Javad\";\n\tswversion=\"0.1\";\n\tconstellations=GNSSSystem::GPS;\n\tdualFrequency=false;\n\tcodes=GNSSSystem::C1;\n\tchannels=32;\n\tif (modelName==\"HE_GD\"){\n\t\tdualFrequency=true;\n\t\tcodes = GNSSSystem::C1 | GNSSSystem::P1 | GNSSSystem::P2;\n\t}\n\telse{\n\t\tapp->logMessage(\"Unknown receiver model: \" + modelName);\n\t\tapp->logMessage(\"Assuming generic single frequency receiver\");\n\t\tmodelName=\"generic\";\n\t}\n}\n\nJavad::~Javad()\n{\n}\n\nbool Javad::readLog(string fname,int mjd,int startTime,int stopTime,int rinexObsInterval)\n{\n\tTimer timer;\n\t\n\ttimer.start();\n\t\n\tDBGMSG(debugStream,INFO,\"reading \" << fname);\t\n\t\n\t\n\tifstream infile (fname.c_str());\n\tstring line;\n\tint linecount=0;\n\t\n\tstring msgid,currpctime,pctime,msg,gpstime;\n\t\n\tU4 gpsTOD;\n\tF8 rxTimeOffset;\n\tF4 sawtooth;  \n\t\n\tvector<string> rxid;\n\t\n\tvector<SVMeasurement *> gpsmeas;\n\tgotIonoData = false;\n\tgotUTCdata=false;\n\t\n\tU1 uint8buf;\n\tI1 sint8buf;\n\tI2 sint16buf;\n\tI4 sint32buf;\n\tU4 u4buf;\n\t\n\tunsigned int currMsgs=0,reqdMsgs;\n\tunsigned int nSats;\n\tunsigned char trackedSVs[MAX_CHANNELS];\n\tunsigned char navStatus[MAX_CHANNELS];\n\tunsigned char elevs[MAX_CHANNELS];\n\tunsigned char azimuths[MAX_CHANNELS];\n\t\n\tF8 CApr[MAX_CHANNELS];\n\tunsigned char CAlockFlags[MAX_CHANNELS*2];\n\t\n\tF8 P1pr[MAX_CHANNELS];\n\tF8 relP1pr[MAX_CHANNELS];\n\tunsigned char P1lockFlags[MAX_CHANNELS*2];\n\t\n\tF8 P2pr[MAX_CHANNELS];\n\tF8 relP2pr[MAX_CHANNELS];\n\tunsigned char P2lockFlags[MAX_CHANNELS*2];\n\t\n\tI2 i2bufarray[MAX_CHANNELS];\n\tI4 i4bufarray[MAX_CHANNELS];\n\tF4 f4bufarray[MAX_CHANNELS];\n\tF8 f8bufarray[MAX_CHANNELS];\n\t\n\tF8 smoothingOffset;\n\tint rcCnt=0,RCcnt=0; \n\tint R1cnt=0,r1Cnt=0,m1RCnt=0,m1rCnt=0;\n\tint R2cnt=0,r2Cnt=0,m2RCnt=0,m2rCnt=0;\n\tunsigned int errorCount=0,badC1Measurements=0,badP1Measurements=0,badP2Measurements=0,numSVmeasurements=0;\n\tU2 RDyyyy;\n\tU1 RDmm,RDdd;\n\t\n\treqdMsgs = AZ_MSG | EL_MSG | FC_MSG | RC_rc_MSG| RT_MSG | SI_MSG | SS_MSG | TO_MSG | YA_MSG| ZA_MSG;\n\tif (dualFrequency)\n\t\treqdMsgs |= R1_r1_1R_1r_MSG | R2_r2_2R_2r_MSG | F1_MSG | F2_MSG;\n\t\n\n  if (infile.is_open()){\n    while ( getline (infile,line) ){\n\t\t\tlinecount++;\n\t\t\t\n\t\t\tif (line.size()==0) continue; // skip empty line\n\t\t\tif ('#' == line.at(0)) continue; // skip comments\n\t\t\tif ('%' == line.at(0)) continue;\n\t\t\n\t\t\tif ('@' == line.at(0)){ \n\t\t\t\tsize_t pos;\n\t\t\t\tif (string::npos != (pos = line.find(\"RXID\",2 )) ){\n\t\t\t\t\trxid.push_back(line.substr(pos+4,line.size()-pos-4));\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstringstream sstr(line);\n\t\t\t\n\t\t\t// Basic check on the format \n\t\t\tif ( (line.size() < 16) || // too short\n\t\t\t\t(line.at(2) != ' ') || // missing delimiter\n\t\t\t\t(line.at(5) != ':') || // missing delimiter\n\t\t\t\t(line.at(8) != ':') ||\n\t\t\t\t(line.at(11) != ' ')){\n\t\t\t\terrorCount++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsstr >> msgid >> currpctime >> msg;\n\t\t\tif (sstr.fail()){\n\t\t\t\tDBGMSG(debugStream,WARNING,\" bad data at line \" << linecount);\n\t\t\t\terrorCount++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tint hh,mm,ss;\n\t\t\tif ((3==sscanf(currpctime.c_str(),\"%d:%d:%d\",&hh,&mm,&ss))){\n\t\t\t\tint ts = hh*3600+mm*60+ss;\n\t\t\t\tif (ts < startTime || ts > stopTime)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t// FIXME could improve parser by converting the msgid to a hex value?\n\t\t\t// Some messages we just don't want\n\t\t\tif (msgid == \"NP\"){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// FIXME Valid checksum?\n\t\t\t// If we compute a valid checksum, then checking the message size is a bit paranoid\n\t\t\t//HexToBin(hexdata,count/2,rawdata);\n\t\t\t//sprintf(temp,\"%s%03X\",command,count/2);\n\t\t\t//for (i=0;i<count/2;i++) temp[i+5] = rawdata[i];\n\t\t\t//if (cs(temp,count/2 + 5 - 1 ) != rawdata[count/2 - 1]) continue;\n\t\t\n\t\t\t//\n\t\t\t// Messages that occur once per second\n\t\t\t//\n\t\t\t\n\t\t\t// \n\t\t\t// The Receiver Date message starts each second\n\t\t\t//\n\t\t\t\n\t\t\tif(msgid==\"RD\"){ // Receiver Date (RD) message \n\t\t\t\t\n\t\t\t\tif ((currMsgs == reqdMsgs) && (rcCnt <= 1) && (RCcnt <= 1)){ // save measurements\n\t\t\t\t\t\n\t\t\t\t\tif ((dualFrequency &&\n\t\t\t\t\t\t!((R1cnt<=1) && (r1Cnt<=1) && (m1RCnt<=1) && (m1rCnt<=1) &&\n\t\t\t\t\t\t(R2cnt<=1) && (r2Cnt<=1) && (m2RCnt<=1) && (m2rCnt<=1))))\n\t\t\t\t\t{\n\t\t\t\t\t\tDBGMSG(debugStream,INFO,\"Too many P1/2 messages\");\n\t\t\t\t\t\tpctime=currpctime;\n\t\t\t\t\t\tcurrMsgs=0;\n\t\t\t\t\t\trcCnt=RCcnt=0;\n\t\t\t\t\t\tR1cnt=r1Cnt=m1RCnt=m1rCnt=0;\n\t\t\t\t\t\tR2cnt=r2Cnt=m2RCnt=m2rCnt=0;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tReceiverMeasurement *rmeas = new ReceiverMeasurement();\n\t\t\t\t\tnumSVmeasurements += nSats;\n\t\t\t\t\t\n\t\t\t\t\t// For each tracked satellite, get the pseudorange for each code\n\t\t\t\t\tfor (unsigned int chan=0; chan < nSats; chan++){\n\t\t\t\t\t\t\n\t\t\t\t\t\t// FIXME ignore GLONASS for the present\n\t\t\t\t\t\t// GPS USID 1..37, GLONASS 38..69,70 \n\t\t\t\t\t\tif (trackedSVs[chan] > 37){\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (codes & GNSSSystem::C1){\n\t\t\t\t\t\t\tbool ok=true;\n\t\t\t\t\t\t\t// Check that PLLs are locked for each channel before we use the data\n\t\t\t\t\t\t\tif (CAlockFlags[chan*2] != 83){\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" C/A unlocked at line \" << linecount << \"(prn=\" << (int) trackedSVs[chan] << \")\");\n\t\t\t\t\t\t\t\tbadC1Measurements++;\n\t\t\t\t\t\t\t\tok=false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Simple sanity check in case pseudoranges or the receiver time offset are wild\n\t\t\t\t\t\t\tif (((CApr[chan]-rxTimeOffset)<0.05) || ((CApr[chan]-rxTimeOffset)>0.10)){\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" C/A pseudorange too large at line \" << linecount << \"(\" << CApr[chan]-rxTimeOffset << \")\");\n\t\t\t\t\t\t\t\tif (ok) badC1Measurements++; // don't count it twice\n\t\t\t\t\t\t\t\tok=false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (ok){\n\t\t\t\t\t\t\t\tSVMeasurement *svm = new SVMeasurement(trackedSVs[chan],GNSSSystem::GPS,GNSSSystem::C1,CApr[chan]-rxTimeOffset,rmeas); // pseudorange is corrected for rx offset \n\t\t\t\t\t\t\t\tsvm->dbuf3 = CApr[chan];\n\t\t\t\t\t\t\t\trmeas->meas.push_back(svm);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t} // if codes & C1\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (codes & GNSSSystem::P1){\n\t\t\t\t\t\t\tbool ok=true;\n\t\t\t\t\t\t\tif (P1lockFlags[chan*2] != 83){\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" P1 unlocked at line \" << linecount << \"(prn=\" << (int) trackedSVs[chan] << \")\");\n\t\t\t\t\t\t\t\tbadP1Measurements++;\n\t\t\t\t\t\t\t\tok=false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// FIXME better sanity check\n\t\t\t\t\t\t\tok = ok && !isnan(P1pr[chan]);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (ok){\n\t\t\t\t\t\t\t\tSVMeasurement *svm = new SVMeasurement(trackedSVs[chan],GNSSSystem::GPS,GNSSSystem::P1,P1pr[chan]-rxTimeOffset,rmeas); // pseudorange is corrected for rx offset \n\t\t\t\t\t\t\t\trmeas->meas.push_back(svm);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t} // if codes & P1\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif (codes & GNSSSystem::P2){\n\t\t\t\t\t\t\tbool ok = true;\n\t\t\t\t\t\t\tif (P2lockFlags[chan*2] != 83){\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" P2 unlocked at line \" << linecount << \"(prn=\" << (int) trackedSVs[chan] << \")\");\n\t\t\t\t\t\t\t\tbadP2Measurements++;\n\t\t\t\t\t\t\t\tok=false;\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// FIXME better sanity check\n\t\t\t\t\t\t\tok = ok && !isnan(P2pr[chan]);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (ok){\n\t\t\t\t\t\t\t\tSVMeasurement *svm = new SVMeasurement(trackedSVs[chan],GNSSSystem::GPS,GNSSSystem::P2,P2pr[chan]-rxTimeOffset,rmeas); // pseudorange is corrected for rx offset \n\t\t\t\t\t\t\t\trmeas->meas.push_back(svm);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t} // if codes & P2\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (rmeas->meas.size() > 0){ // FIXME check other codes\n\t\t\t\t\t\tint pchh,pcmm,pcss;\n\t\t\t\t\t\tif ((3==sscanf(pctime.c_str(),\"%d:%d:%d\",&pchh,&pcmm,&pcss))){\n\t\t\t\t\t\t\trmeas->pchh=pchh;\n\t\t\t\t\t\t\trmeas->pcmm=pcmm;\n\t\t\t\t\t\t\trmeas->pcss=pcss;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// One more check\n\t\t\t\t\t\t\tif ((gpsTOD/1000.0+rxTimeOffset) > -0.1 && (gpsTOD/1000.0+rxTimeOffset < 86400.1)){\n\t\t\t\t\t\t\t\tint igpsTOD = gpsTOD/1000;\n\t\t\t\t\t\t\t\tint hh = (int) (igpsTOD/3600);\n\t\t\t\t\t\t\t\tint mm = (int) (igpsTOD - hh*3600)/60;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\trmeas->tmGPS.tm_sec= igpsTOD - hh*3600 - mm*60;\n\t\t\t\t\t\t\t\trmeas->tmGPS.tm_min= mm;\n\t\t\t\t\t\t\t\trmeas->tmGPS.tm_hour=hh ;\n\t\t\t\t\t\t\t\trmeas->tmGPS.tm_mday=RDdd;\n\t\t\t\t\t\t\t\trmeas->tmGPS.tm_mon=RDmm-1;\n\t\t\t\t\t\t\t\trmeas->tmGPS.tm_year=RDyyyy-1900;\n\t\t\t\t\t\t\t\trmeas->tmGPS.tm_isdst=0;\n\t\t\t\t\t\t\t\tmktime(&(rmeas->tmGPS)); // this sets wday (note: TZ=UTC enforced in Main.cpp) so DST stays correct\n\t\t\t\t\t\t\t\trmeas->gpstow = 86400*rmeas->tmGPS.tm_wday+igpsTOD;\n\t\t\t\t\t\t\t\trmeas->tmfracs = rxTimeOffset;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// The time offset can be negative so have to account for rollovers\n// \t\t\t\t\t\t\t\ttime_t ttGPS = (time_t)(mktime(&(rmeas->tmGPS)) + rxTimeOffset);\n// \t\t\t\t\t\t\t\tstruct tm *tmGPS = gmtime(&ttGPS);\n// \t\t\t\t\t\t\t\trmeas->tmGPS=*tmGPS;\n// \t\t\t\t\t\t\t\trmeas->tmfracs = rxTimeOffset;\n// \t\t\t\t\t\t\t\tif (rmeas->tmfracs < 0)\n// \t\t\t\t\t\t\t\t\trmeas->tmfracs += 1.0;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// YA and TO messages can roll over at different times - handle this case\n\t\t\t\t\t\t\t\t// Typically, the difference between the smoothed and receiver time offsets is <= 1 ns\n\t\t\t\t\t\t\t\tif ((smoothingOffset - rxTimeOffset)> 5e-4) smoothingOffset-=1e-3;\n\t\t\t\t\t\t\t\tif ((smoothingOffset - rxTimeOffset)<-5e-4) smoothingOffset+=1e-3;\n\t\t\t\t\n\t\t\t\t\t\t\t\trmeas->sawtooth=sawtooth-(smoothingOffset-rxTimeOffset); // added to the counter measurement\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\t\t\t\t\t\t\t\t\t\t\t\t // the term (moothingOffset-rxTimeOffset) is typically zero\n\t\t\t\t\t\t\t\trmeas->timeOffset = rxTimeOffset; // just used for diagnostics\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t// All OK\n\t\t\t\t\t\t\t\tmeasurements.push_back(rmeas);\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,TRACE,rmeas->meas.size() << \" measurements at \"  << (int) gpsTOD << \" \"\n\t\t\t\t\t\t\t\t\t<< hh << \":\" << mm << \":\" << (int) rmeas->tmGPS.tm_sec << \" (GPS), \" \n\t\t\t\t\t\t\t\t\t<< pchh << \":\" << pcmm << \":\" << pcss << \" (PC)\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"GPS TOD out of range at \" << pchh << \":\" << pcmm << \":\" << pcss << \" (PC)\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Unreadable PC time \" << currpctime);\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"No useable GPS measurements at \" << currpctime);\n\t\t\t\t\t\tdelete rmeas;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (msg.size() == 6*2){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),sizeof(U2),(unsigned char *) &RDyyyy);\n\t\t\t\t\tHexToBin((char *) msg.substr(2*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &RDmm);\n\t\t\t\t\tHexToBin((char *) msg.substr(3*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &RDdd);\n\t\t\t\t\tHexToBin((char *) msg.substr(4*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &uint8buf);\n\t\t\t\t\tDBGMSG(debugStream,TRACE,\" RD \" << (int) RDyyyy << \":\" << (int) RDmm << \":\" << (int) RDdd << \" rx ref time=\" << (int) uint8buf);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" RD msg wrong size at line \" << linecount);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpctime=currpctime;\n\t\t\t\tcurrMsgs=0;\n\t\t\t\trcCnt=RCcnt=0;\n\t\t\t\tR1cnt=r1Cnt=m1RCnt=m1rCnt=0;\n\t\t\t\tR2cnt=r2Cnt=m2RCnt=m2rCnt=0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif (msgid == \"~~\"){\n\t\t\t\tif (msg.size() == 5*2 ){\n\t\t\t\t\tHexToBin((char *) msg.substr(0,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &gpsTOD);\n\t\t\t\t\tcurrMsgs |= RT_MSG;\n\t\t\t\t\tDBGMSG(debugStream,TRACE,\" RT \" << (int) gpsTOD);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" bad data at line \" << linecount);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(msgid==\"SI\"){ // Satellite Indices (SI) message\n\t\t\t\tif (currMsgs & SI_MSG){\n\t\t\t\t\tcurrMsgs=0; // unexpected SI message\n\t\t\t\t\trcCnt=RCcnt=0;\n\t\t\t\t\tR1cnt=r1Cnt=m1RCnt=m1rCnt=0;\n\t\t\t\t\tR2cnt=r2Cnt=m2RCnt=m2rCnt=0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Can't check the message size!\n\t\t\t\tcurrMsgs |= SI_MSG;\n\t\t\t\tnSats=(msg.size() - 2) / 2;\n\t\t\t\tHexToBin((char *) msg.c_str(),nSats,trackedSVs);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(msgid==\"TO\"){ // Reference Time to Receiver Time Offset (TO) message \n\t\t\t\tif (msg.size() == 9*2){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),sizeof(F8),(unsigned char *) &rxTimeOffset);\n\t\t\t\t\t// Discard outliers\n\t\t\t\t\tif ((fabs(rxTimeOffset)>0.001) || (fabs(rxTimeOffset)<1E-10)){ \n\t\t\t\t\t\tbadC1Measurements++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" TO outlier at line \" << linecount << \":\" << rxTimeOffset);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcurrMsgs |= TO_MSG;\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\" TO \" << rxTimeOffset *1.0E9 << \" ns\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" TO msg wrong size at line \" << linecount);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(msgid==\"YA\"){ // smoothing offset (YA) message - assuming we are using pps A\n\t\t\t\tif (msg.size() == 10*2){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),sizeof(F8),(unsigned char *) &smoothingOffset);\n\t\t\t\t\t// Discard outliers. YA is occasionally reported as zero following a tracking glitch.\n\t\t\t\t\tif ((fabs(smoothingOffset)>0.001) || (smoothingOffset==0)){\n\t\t\t\t\t\tbadC1Measurements++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" YA outlier at line \" << linecount << \":\" << smoothingOffset);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcurrMsgs |= YA_MSG;\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\" YA \" << smoothingOffset *1.0E9 << \" ns\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" YA msg wrong size at line \" << linecount << \":\" << msg.size());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(msgid==\"ZA\"){ // PPS offset (ZA) message - assuming we are using pps A\n\t\t\t\tif (msg.size() == 5*2){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),sizeof(F4),(unsigned char *) &sawtooth); // units are ns\n\t\t\t\t\t// Discard outliers\n\t\t\t\t\tif (fabs(sawtooth)> 50.0){\n\t\t\t\t\t\tbadC1Measurements++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" ZA outlier at line \" << linecount << \":\" << sawtooth);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\" ZA \" << sawtooth << \" ns\");\n\t\t\t\t\t\tsawtooth *= 1.0E-9;\n\t\t\t\t\t\tcurrMsgs |= ZA_MSG;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" ZA msg wrong size at line \" << linecount);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Need the SI message to parse the following messages\n\t\t\tif (!(currMsgs & SI_MSG)) continue;\n\t\t\t\n\t\t\tif(msgid == \"SS\"){ //  Navigation Status (SS) message \n\t\t\t\tunsigned int ssnSats = (msg.size() - 4) / 2;\n\t\t\t\tif (ssnSats == nSats){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats,navStatus);\n\t\t\t\t\tcurrMsgs |= SS_MSG;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" SS msg wrong size at line \" << linecount << \":\" << ssnSats << \" \" << nSats);\t\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(msgid == \"EL\"){ //  Satellite Elevations (EL) message \n\t\t\t\tunsigned int elnSats = (msg.size() - 2) / 2;\n\t\t\t\tif (elnSats == nSats){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats,elevs);\n\t\t\t\t\tcurrMsgs |= EL_MSG;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" EL msg wrong size at line \" << linecount);\t\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(msgid == \"AZ\"){ //  Satellite Azimuths (AZ) message \n\t\t\t\tunsigned int aznSats = (msg.size() - 2) / 2;\n\t\t\t\tif (aznSats == nSats){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats,azimuths);\n\t\t\t\t\tcurrMsgs |= AZ_MSG;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" AZ msg wrong size at line \" << linecount);\t\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\n\t\t\t// L1C measurements\n\t\t\tif(msgid == \"rc\"){ // Delta C/A Pseudoranges (rc) message\n\t\t\t\tif (RCcnt) continue; // full pseudoranges take precedence\n\t\t\t\tunsigned int rcnSats = (msg.size() - 2) / 8;\n\t\t\t\tif (rcnSats == nSats){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(I4),(unsigned char *) (i4bufarray));\n\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\tCApr[i] = (double)(i4bufarray[i])*1e-11 + 0.075;\n\t\t\t\t\tcurrMsgs |= RC_rc_MSG;\n\t\t\t\t\trcCnt++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" rc msg wrong size at line \" << linecount);\t\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(msgid == \"RC\"){ // Full C/A Pseudoranges (RC) message\n\t\t\t\tunsigned int RCnSats = (msg.size() - 2) / 16;\n\t\t\t\tif (RCnSats == nSats){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(F8),(unsigned char *) (f8bufarray));\n\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\tCApr[i] = (double) f8bufarray[i];\n\t\t\t\t\tcurrMsgs |= RC_rc_MSG;\n\t\t\t\t\tRCcnt++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" RC msg wrong size at line \" << linecount);\t\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(msgid == \"FC\"){ // F/A Signal Lock Flags (FC) message\n\t\t\t\tunsigned int FCnSats = (msg.size() - 2) / 4;\n\t\t\t\tif (FCnSats == nSats){\n\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(U2),(unsigned char *) (CAlockFlags));\n\t\t\t\t\tcurrMsgs |= FC_MSG;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\" FC msg wrong size at line \" << linecount);\t\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\n\t\t\t// P1 & P2 messages \n\t\t\tif (dualFrequency){\n\n\t\t\t\t// Four pseudorange messages for each signal\n\t\t\t\tif(msgid == \"R1\"){ // Full P1 pseudorange (R1) message\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(F8));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(F8),(unsigned char *) (f8bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\tP1pr[i] = (double) f8bufarray[i];\n\t\t\t\t\t\tcurrMsgs |= R1_r1_1R_1r_MSG;\n\t\t\t\t\t\tR1cnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" R1 msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"r1\"){ // Short P1 pseudoranges (r1) message\n\t\t\t\t\tif (R1cnt) continue; // full pseudoranges take precedence\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(I4));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(I4),(unsigned char *) (i4bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\tP1pr[i] = (double)(i4bufarray[i])*1e-11 + 0.075;\n\t\t\t\t\t\tcurrMsgs |= R1_r1_1R_1r_MSG;\n\t\t\t\t\t\tr1Cnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" r1 msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"1R\"){ // Relative P1 pseudoranges (1R) message\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(F4));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(F4),(unsigned char *) (f4bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\trelP1pr[i] = (double) f4bufarray[i];\n\t\t\t\t\t\tcurrMsgs |= R1_r1_1R_1r_MSG;\n\t\t\t\t\t\tm1RCnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" 1R msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"1r\"){ // Short relative P1 pseudoranges (1r) message\n\t\t\t\t\tif (m1RCnt) continue; // full relative pseudoranges take precedence\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(I2));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(I2),(unsigned char *) (i2bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\trelP1pr[i] = (double)(i2bufarray[i])*1e-11 + 2.0e-7;\n\t\t\t\t\t\tcurrMsgs |= R1_r1_1R_1r_MSG;\n\t\t\t\t\t\tm1rCnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" 1r msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"R2\"){ // Full P2 pseudorange (R2) message\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(F8));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(F8),(unsigned char *) (f8bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\tP2pr[i] = (double) f8bufarray[i];\n\t\t\t\t\t\tcurrMsgs |= R2_r2_2R_2r_MSG;\n\t\t\t\t\t\tR2cnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" R2 msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"r2\"){ // Short P2 pseudoranges (r2) message\n\t\t\t\t\tif (R2cnt) continue; // full pseudoranges take precedence\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(I4));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(I4),(unsigned char *) (i4bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\tP2pr[i] = (double)(i4bufarray[i])*1e-11 + 0.075;\n\t\t\t\t\t\tcurrMsgs |= R2_r2_2R_2r_MSG;\n\t\t\t\t\t\tr2Cnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" r2 msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"2R\"){ // Relative P2 pseudoranges (2R) message\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(F4));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(F4),(unsigned char *) (f4bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\trelP2pr[i] = (double) f4bufarray[i];\n\t\t\t\t\t\tcurrMsgs |= R2_r2_2R_2r_MSG;\n\t\t\t\t\t\tm2RCnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" 2R msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"2r\"){ // Short relative P2 pseudoranges (2r) message\n\t\t\t\t\tif (m2RCnt) continue; // full delta pseudoranges take precedence\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) / (2*sizeof(I2));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(I2),(unsigned char *) (i2bufarray));\n\t\t\t\t\t\tfor (unsigned int i=0;i<nSats;i++) \n\t\t\t\t\t\t\trelP2pr[i] = (double)(i2bufarray[i])*1e-11 + 2.0e-7;\n\t\t\t\t\t\tcurrMsgs |= R2_r2_2R_2r_MSG;\n\t\t\t\t\t\tm2rCnt++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" 2r msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(msgid == \"F1\"){ // P1 Lock Flags (F1) message\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) /(2*sizeof(U2));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(U2),(unsigned char *) (P1lockFlags));\n\t\t\t\t\t\tcurrMsgs |= F1_MSG;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" F1 msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\n\t\t\t\tif(msgid == \"F2\"){ // P2 Lock Flags (F2) message\n\t\t\t\t\tunsigned int msgSats = (msg.size() - 2) /(2*sizeof(U2));\n\t\t\t\t\tif (msgSats == nSats){\n\t\t\t\t\t\tHexToBin((char *) msg.c_str(),nSats*sizeof(U2),(unsigned char *) (P2lockFlags));\n\t\t\t\t\t\tcurrMsgs |= F2_MSG;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\" F2 msg wrong size at line \" << linecount);\t\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t} // if dualFrequency\n\t\t\n\t\t\t//\n\t\t\t// Intermittent  messages - parse last\n\t\t\t//\n\t\t\t\n\t\t\tif (!gotIonoData){\n\t\t\t\tif (msgid==\"IO\"){\n\t\t\t\t\tif (msg.size()==39*2){\n\t\t\t\t\t\tHexToBin((char *) msg.substr(6*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.a0));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(10*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.a1));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(14*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.a2));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(18*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.a3));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(22*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.B0));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(26*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.B1));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(30*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.B2));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(34*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.ionoData.B3));\n\t\t\t\t\t\tgotIonoData=true;\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\"ionosphere parameters: a0=\" << gps.ionoData.a0);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad I0 message size\");\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\tif (!gotUTCdata){\n\t\t\t\tif (msgid==\"UO\"){\n\t\t\t\t\tif (msg.size()==24*2){\n\t\t\t\t\t\tHexToBin((char *) msg.substr(0*2,2*sizeof(F8)).c_str(),sizeof(F8),(unsigned char *) &(gps.UTCdata.A0));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(8*2,2*sizeof(F4)).c_str(),sizeof(F4),(unsigned char *) &(gps.UTCdata.A1));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(12*2,2*sizeof(U4)).c_str(),sizeof(U4),(unsigned char *) &u4buf);\n\t\t\t\t\t\tgps.UTCdata.t_ot=u4buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(16*2,2*sizeof(U2)).c_str(),sizeof(U2),(unsigned char *) &(gps.UTCdata.WN_t));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(18*2,2*sizeof(I1)).c_str(),sizeof(I1),(unsigned char *) &(sint8buf));\n\t\t\t\t\t\tgps.UTCdata.dtlS=sint8buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(19*2,2*sizeof(U1)).c_str(),sizeof(U1),(unsigned char *) &uint8buf);\n\t\t\t\t\t\tgps.UTCdata.DN=uint8buf;\n\t\t\t\t\t\tHexToBin((char *) msg.substr(20*2,2*sizeof(U2)).c_str(),sizeof(U2),(unsigned char *) &(gps.UTCdata.WN_LSF));\n\t\t\t\t\t\tHexToBin((char *) msg.substr(22*2,2*sizeof(I1)).c_str(),sizeof(I1),(unsigned char *) &sint8buf);\n\t\t\t\t\t\tgps.UTCdata.dt_LSF=sint8buf;\n\t\t\t\t\t\tDBGMSG(debugStream,TRACE,\"UTC parameters: dtLS=\" << gps.UTCdata.dtlS << \",dt_LSF=\" << gps.UTCdata.dt_LSF);\n\t\t\t\t\t\tgotUTCdata = gps.currentLeapSeconds(mjd,&leapsecs);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad U0 message size\");\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(msgid == \"GE\"){  // GPS ephemeris\n\t\t\t\tif (msg.length() == 123*2){\n\t\t\t\t\tGPS::EphemerisData *ed = new GPS::EphemerisData;\n \t\t\t\t\tHexToBin((char *) msg.substr(0*2,2*sizeof(UINT8)).c_str(), sizeof(UINT8),  (unsigned char *) &(ed->SVN));\n\t\t\t\t\tHexToBin((char *) msg.substr(1*2,2*sizeof(UINT32)).c_str(),sizeof(UINT32), (unsigned char *) &(u4buf));\n \t\t\t\t\ted->t_ephem=u4buf;\n\t\t\t\t\t\n\t\t\t\t\tHexToBin((char *) msg.substr(6*2,2*sizeof(SINT16)).c_str(),sizeof(SINT16), (unsigned char *) &(sint16buf));\n\t\t\t\t\t\ted-> IODC=sint16buf;\n\t\t\t\t\tHexToBin((char *) msg.substr(8*2,2*sizeof(SINT32)).c_str(),sizeof(SINT32), (unsigned char *) &(sint32buf));\n\t\t\t\t\ted->t_OC=sint32buf;\n\t\t\t\t\tHexToBin((char *) msg.substr(12*2,2*sizeof(SINT8)).c_str(), sizeof(SINT8),  (unsigned char *) &(sint8buf));\n\t\t\t\t\ted->SV_accuracy_raw = sint8buf;\n\t\t\t\t\ted->SV_accuracy = GPS::URA[ed->SV_accuracy_raw];\n\t\t\t\t\tHexToBin((char *) msg.substr(13*2,2*sizeof(UINT8)).c_str(), sizeof(UINT8),  (unsigned char *) &(ed->SV_health));\n\t\t\t\t\tHexToBin((char *) msg.substr(14*2,2*sizeof(SINT16)).c_str(),sizeof(SINT16), (unsigned char *) &sint16buf);\n\t\t\t\t\ted->week_number=(UINT16) sint16buf;\n\t\t\t\t\tHexToBin((char *) msg.substr(16*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->t_GD));\n\t\t\t\t\t\n\t\t\t\t\tHexToBin((char *) msg.substr(20*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->a_f2));\n\t\t\t\t\tHexToBin((char *) msg.substr(24*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->a_f1));\n\t\t\t\t\tHexToBin((char *) msg.substr(28*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->a_f0));\n\t\t\t\t\tHexToBin((char *) msg.substr(32*2,2*sizeof(SINT32)).c_str(),sizeof(SINT32), (unsigned char *) &sint32buf);\n\t\t\t\t\ted->t_oe=sint32buf;\n\t\t\t\t\tHexToBin((char *) msg.substr(36*2,2*sizeof(SINT16)).c_str(), sizeof(SINT16),  (unsigned char *) &sint16buf);\n\t\t\t\t\ted->IODE=(UINT8) sint16buf; // WARNING! Truncated\n\t\t\t\t\tHexToBin((char *) msg.substr(38*2,2*sizeof(DOUBLE)).c_str(),sizeof(DOUBLE), (unsigned char *) &(ed->sqrtA));\n\t\t\t\t\t\n\t\t\t\t\tHexToBin((char *) msg.substr(46*2,2*sizeof(DOUBLE)).c_str(),sizeof(DOUBLE), (unsigned char *) &(ed->e));\n\t\t\t\t\tHexToBin((char *) msg.substr(54*2,2*sizeof(DOUBLE)).c_str(),sizeof(DOUBLE), (unsigned char *) &(ed->M_0));\n\t\t\t\t\ted->M_0 *= M_PI;\n\t\t\t\t\tHexToBin((char *) msg.substr(62*2,2*sizeof(DOUBLE)).c_str(),sizeof(DOUBLE), (unsigned char *) &(ed->OMEGA_0));\n\t\t\t\t\ted->OMEGA_0 *= M_PI;\n\t\t\t\t\tHexToBin((char *) msg.substr(70*2,2*sizeof(DOUBLE)).c_str(),sizeof(DOUBLE), (unsigned char *) &(ed->i_0));\n\t\t\t\t\ted->i_0 *= M_PI;\n\t\t\t\t\tHexToBin((char *) msg.substr(78*2,2*sizeof(DOUBLE)).c_str(),sizeof(DOUBLE), (unsigned char *) &(ed->OMEGA));\n\t\t\t\t\ted->OMEGA *= M_PI;\n\t\t\t\t\tHexToBin((char *) msg.substr(86*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->delta_N));\n\t\t\t\t\ted->delta_N *=M_PI;\n\t\t\t\t\tHexToBin((char *) msg.substr(90*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->OMEGADOT));\n\t\t\t\t\ted->OMEGADOT *= M_PI;\n\t\t\t\t\tHexToBin((char *) msg.substr(94*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->IDOT));\n\t\t\t\t\ted->IDOT *= M_PI;\n\t\t\t\t\tHexToBin((char *) msg.substr(98*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->C_rc));\n\t\t\t\t\tHexToBin((char *) msg.substr(102*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->C_rs));\n\t\t\t\t\tHexToBin((char *) msg.substr(106*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->C_uc));\n\t\t\t\t\tHexToBin((char *) msg.substr(110*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->C_us));\n\t\t\t\t\tHexToBin((char *) msg.substr(114*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->C_ic));\n\t\t\t\t\tHexToBin((char *) msg.substr(118*2,2*sizeof(F4)).c_str(),sizeof(F4), (unsigned char *) &(ed->C_is));\n\t\t\t\t\t\n\t\t\t\t\tint pchh,pcmm,pcss;\n\t\t\t\t\tif ((3==sscanf(pctime.c_str(),\"%d:%d:%d\",&pchh,&pcmm,&pcss)))\n\t\t\t\t\t\ted->tLogged = pchh*3600 + pcmm*60 + pcss; \n\t\t\t\t\telse\n\t\t\t\t\t\ted->tLogged = -1;\n\t\t\t\t\t\t\n\t\t\t\t\tDBGMSG(debugStream,TRACE,\"Ephemeris: SVN=\"<< (unsigned int) ed->SVN << \",toe=\"<< ed->t_oe << \",IODE=\" << (int) ed->IODE);\n\t\t\t\t\tgps.addEphemeris(ed);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\terrorCount++;\n\t\t\t\t\tDBGMSG(debugStream,WARNING,\"Bad GE message size\");\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\telse{\n\t\tapp->logMessage(\"Unable to open \"+fname);\n\t\treturn false;\n\t}\n\t\n\tinfile.close();\n\n\tif (!gotIonoData){\n\t\tapp->logMessage(\"failed to find ionosphere parameters - no IO messages\");\n\t\treturn false;\n\t}\n\t\n\tif (!gotUTCdata){\n\t\tapp->logMessage(\"failed to find UTC parameters - no U0 messages\");\n\t\treturn false;\n\t}\n\t\n\t// Post load cleanups \n\t\n\tinterpolateMeasurements();\n\t\n\t// Calculate UTC time of measurements, now that the number of leap seconds is known\n\tfor (unsigned int i=0;i<measurements.size();i++){\n\t\ttime_t tUTC = mktime(&(measurements[i]->tmGPS));\n\t\ttUTC -= leapsecs;\n\t\tstruct tm *tmUTC = gmtime(&tUTC);\n\t\tmeasurements[i]->tmUTC=*tmUTC;\n\t}\n\t\n\t// Extract the receiver id\n\tif (rxid.size() !=0) {\n\t\tif ((rxid.size() % 4 == 0)){\n\t\t\tint idx = (rxid.size() / 4) -1;\n\t\t\tstring rxinfo = rxid.at(idx) + rxid.at(idx+1) + rxid.at(idx+2) + rxid.at(idx+3);\n\t\t\trxinfo.erase(std::remove(rxinfo.begin(),rxinfo.end(),'{'), rxinfo.end());\n\t\t\trxinfo.erase(std::remove(rxinfo.begin(),rxinfo.end(),'}'), rxinfo.end());\n\t\t\trxinfo.erase(std::remove(rxinfo.begin(),rxinfo.end(),'\\\"'), rxinfo.end());\n\t\t\tstd::vector<std::string> vals;\n\t\t\tboost::split(vals, rxinfo,boost::is_any_of(\",\"), boost::token_compress_on);\n\t\t\tboost::algorithm::trim_left(vals.at(0));\n\t\t\tserialNumber = vals.at(0);\n\t\t\tmodelName = vals.at(1);\n\t\t\tboost::algorithm::trim_left(vals.at(4));\n\t\t\tswversion = vals.at(4)+\" \"+vals.at(5)+\" \"+vals.at(6);\n\t\t\tDBGMSG(debugStream,INFO,\"rx s/n \" << vals.at(0) << \",model \" << modelName << \",sw \" << swversion);\n\t\t\t\n\t\t}\n\t\telse{\n\t\t\tDBGMSG(debugStream,INFO, \"Unable to find receiver ID\");\n\t\t}\n\t}\n\t\n\ttimer.stop();\n\t\n\tDBGMSG(debugStream,INFO,\"done: read \" << linecount << \" lines\");\n\tDBGMSG(debugStream,INFO,measurements.size() << \" measurements read\");\n\tDBGMSG(debugStream,INFO,gps.ephemeris.size() << \" GPS ephemeris entries read\");\n\tDBGMSG(debugStream,INFO,errorCount << \" errors in input file\");\n\tif (codes & GNSSSystem::C1){\n\t\tDBGMSG(debugStream,INFO,badC1Measurements  << \" SV C1 measurements rejected\");\n\t}\n\tif (codes & GNSSSystem::P1){\n\t\tDBGMSG(debugStream,INFO,badP1Measurements  << \" SV P1 measurements rejected\");\n\t}\n\tif (codes & GNSSSystem::P2){\n\t\tDBGMSG(debugStream,INFO,badP2Measurements  << \" SV P2 measurements rejected\");\n\t}\n\tDBGMSG(debugStream,INFO,\"elapsed time: \" << timer.elapsedTime(Timer::SECS) << \" s\");\n\treturn true;\n\t\n}\n\n", "meta": {"hexsha": "7bb0aa88fa6f9f8e5d447c4a6107cf3a321e8c27", "size": 32960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/gpscv/common/process/mktimetx/Javad.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/Javad.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/Javad.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": 34.6218487395, "max_line_length": 169, "alphanum_fraction": 0.6050364078, "num_tokens": 10663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469142916152645, "lm_q2_score": 0.02442309040915126, "lm_q1q2_score": 0.005243428184481854}}
{"text": "//=============================================================================================================\r\n/**\r\n * @file     fiff_proj.cpp\r\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\r\n *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\r\n *           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>\r\n * @version  dev\r\n * @date     July, 2012\r\n *\r\n * @section  LICENSE\r\n *\r\n * Copyright (C) 2012, Lorenz Esch, Matti Hamalainen, Christoph Dinh. 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 FiffProj Class.\r\n *\r\n */\r\n\r\n//=============================================================================================================\r\n// INCLUDES\r\n//=============================================================================================================\r\n\r\n#include \"fiff_proj.h\"\r\n#include <stdio.h>\r\n#include <utils/mnemath.h>\r\n\r\n\r\n//=============================================================================================================\r\n// EIGEN INCLUDES\r\n//=============================================================================================================\r\n\r\n#include <Eigen/SVD>\r\n\r\n//=============================================================================================================\r\n// USED NAMESPACES\r\n//=============================================================================================================\r\n\r\nusing namespace UTILSLIB;\r\nusing namespace FIFFLIB;\r\nusing namespace Eigen;\r\n\r\n//=============================================================================================================\r\n// DEFINE MEMBER METHODS\r\n//=============================================================================================================\r\n\r\nFiffProj::FiffProj()\r\n: kind(-1)\r\n, active(false)\r\n, desc(\"\")\r\n, data(new FiffNamedMatrix)\r\n{\r\n\r\n}\r\n\r\n//=============================================================================================================\r\n\r\nFiffProj::FiffProj(const FiffProj& p_FiffProj)\r\n: kind(p_FiffProj.kind)\r\n, active(p_FiffProj.active)\r\n, desc(p_FiffProj.desc)\r\n, data(p_FiffProj.data)\r\n{\r\n\r\n}\r\n\r\n//=============================================================================================================\r\n\r\nFiffProj::FiffProj( fiff_int_t p_kind, bool p_active, QString p_desc, FiffNamedMatrix& p_data)\r\n: kind(p_kind)\r\n, active(p_active)\r\n, desc(p_desc)\r\n, data(new FiffNamedMatrix(p_data))\r\n{\r\n\r\n}\r\n\r\n//=============================================================================================================\r\n\r\nFiffProj::~FiffProj()\r\n{\r\n\r\n}\r\n\r\n//=============================================================================================================\r\n\r\nvoid FiffProj::activate_projs(QList<FiffProj> &p_qListFiffProj)\r\n{\r\n    // Activate the projection items\r\n    QList<FiffProj>::Iterator it;\r\n    for(it = p_qListFiffProj.begin(); it != p_qListFiffProj.end(); ++it)\r\n        it->active = true;\r\n\r\n    printf(\"\\t%d projection items activated.\\n\", p_qListFiffProj.size());\r\n}\r\n\r\n//=============================================================================================================\r\n\r\nfiff_int_t FiffProj::make_projector(const QList<FiffProj>& projs, const QStringList& ch_names, MatrixXd& proj, const QStringList& bads, MatrixXd& U)\r\n{\r\n    fiff_int_t nchan = ch_names.size();\r\n    if (nchan == 0)\r\n    {\r\n        printf(\"No channel names specified\\n\");//ToDo throw here\r\n        return 0;\r\n    }\r\n\r\n//    if(proj)\r\n//        delete proj;\r\n    proj = MatrixXd::Identity(nchan,nchan);\r\n    fiff_int_t nproj = 0;\r\n    U = MatrixXd();\r\n\r\n    //\r\n    //   Check trivial cases first\r\n    //\r\n    if (projs.size() == 0)\r\n        return 0;\r\n\r\n    fiff_int_t nvec    = 0;\r\n    fiff_int_t k, l;\r\n    for (k = 0; k < projs.size(); ++k)\r\n    {\r\n        if (projs[k].active)\r\n        {\r\n            ++nproj;\r\n            nvec += projs[k].data->nrow;\r\n        }\r\n    }\r\n\r\n    if (nproj == 0) {\r\n        printf(\"FiffProj::make_projector - No projectors nproj=0\\n\");\r\n        return 0;\r\n    }\r\n\r\n    if (nvec <= 0) {\r\n        printf(\"FiffProj::make_projector - No rows in projector matrices found nvec<=0\\n\");\r\n        return 0;\r\n    }\r\n\r\n    //\r\n    //   Pick the appropriate entries\r\n    //\r\n    MatrixXd vecs = MatrixXd::Zero(nchan,nvec);\r\n    nvec = 0;\r\n    fiff_int_t nonzero = 0;\r\n    qint32 p, c, i, j, v;\r\n    double onesize;\r\n    bool isBad = false;\r\n    RowVectorXi sel(nchan);\r\n    RowVectorXi vecSel(nchan);\r\n    sel.setConstant(-1);\r\n    vecSel.setConstant(-1);\r\n    for (k = 0; k < projs.size(); ++k)\r\n    {\r\n        if (projs[k].active)\r\n        {\r\n            FiffProj one = projs[k];\r\n\r\n            QMap<QString, int> uniqueMap;\r\n            for(l = 0; l < one.data->col_names.size(); ++l)\r\n                uniqueMap[one.data->col_names[l] ] = 0;\r\n\r\n            if (one.data->col_names.size() != uniqueMap.keys().size())\r\n            {\r\n                printf(\"Channel name list in projection item %d contains duplicate items\",k);\r\n                return 0;\r\n            }\r\n\r\n            //\r\n            // Get the two selection vectors to pick correct elements from\r\n            // the projection vectors omitting bad channels\r\n            //\r\n            sel.resize(nchan);\r\n            vecSel.resize(nchan);\r\n            sel.setConstant(-1);\r\n            vecSel.setConstant(-1);\r\n            p = 0;\r\n            for (c = 0; c < nchan; ++c)\r\n            {\r\n                for (i = 0; i < one.data->col_names.size(); ++i)\r\n                {\r\n                    if (QString::compare(ch_names.at(c),one.data->col_names[i]) == 0)\r\n                    {\r\n                        isBad = false;\r\n                        for (j = 0; j < bads.size(); ++j)\r\n                        {\r\n                            if (QString::compare(ch_names.at(c),bads.at(j)) == 0)\r\n                            {\r\n                                isBad = true;\r\n                            }\r\n                        }\r\n\r\n                        if (!isBad && sel[p] != c)\r\n                        {\r\n                            sel[p] = c;\r\n                            vecSel[p] = i;\r\n                            ++p;\r\n                        }\r\n\r\n                    }\r\n                }\r\n            }\r\n            sel.conservativeResize(p);\r\n            vecSel.conservativeResize(p);\r\n            //\r\n            // If there is something to pick, pickit\r\n            //\r\n            if (sel.cols() > 0)\r\n                for (v = 0; v < one.data->nrow; ++v)\r\n                    for (i = 0; i < p; ++i)\r\n                        vecs(sel[i],nvec+v) = one.data->data(v,vecSel[i]);\r\n\r\n            //\r\n            //   Rescale for more straightforward detection of small singular values\r\n            //\r\n            for (v = 0; v < one.data->nrow; ++v)\r\n            {\r\n                onesize = sqrt((vecs.col(nvec+v).transpose()*vecs.col(nvec+v))(0,0));\r\n                if (onesize > 0.0)\r\n                {\r\n                    vecs.col(nvec+v) = vecs.col(nvec+v)/onesize;\r\n                    ++nonzero;\r\n                }\r\n            }\r\n            nvec += one.data->nrow;\r\n        }\r\n    }\r\n    //\r\n    //   Check whether all of the vectors are exactly zero\r\n    //\r\n    if (nonzero == 0)\r\n        return 0;\r\n\r\n    //\r\n    //   Reorthogonalize the vectors\r\n    //\r\n    JacobiSVD<MatrixXd> svd(vecs.block(0,0,vecs.rows(),nvec), ComputeFullU);\r\n    //Sort singular values and singular vectors\r\n    VectorXd S = svd.singularValues();\r\n    MatrixXd t_U = svd.matrixU();\r\n    MNEMath::sort<double>(S, t_U);\r\n\r\n    //\r\n    //   Throw away the linearly dependent guys\r\n    //\r\n    nproj = 0;\r\n    for(k = 0; k < S.size(); ++k)\r\n        if (S[k]/S[0] > 1e-2)\r\n            ++nproj;\r\n\r\n    U = t_U.block(0, 0, t_U.rows(), nproj);\r\n\r\n    //\r\n    //   Here is the celebrated result\r\n    //\r\n    proj -= U*U.transpose();\r\n\r\n    return nproj;\r\n}\r\n", "meta": {"hexsha": "28a12c93250cfc159786b8ff66df42e52751d03c", "size": 9360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/fiff/fiff_proj.cpp", "max_stars_repo_name": "gabrielbmotta/mne-cpp", "max_stars_repo_head_hexsha": "f3e68a4d2e33369dfe637591c055e34000c73a46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/fiff/fiff_proj.cpp", "max_issues_repo_name": "gabrielbmotta/mne-cpp", "max_issues_repo_head_hexsha": "f3e68a4d2e33369dfe637591c055e34000c73a46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/fiff/fiff_proj.cpp", "max_forks_repo_name": "gabrielbmotta/mne-cpp", "max_forks_repo_head_hexsha": "f3e68a4d2e33369dfe637591c055e34000c73a46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6690647482, "max_line_length": 149, "alphanum_fraction": 0.4433760684, "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091976292927183, "lm_q2_score": 0.02262919900312865, "lm_q1q2_score": 0.005225529269081782}}
{"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/mitsuba.h>\n#include <mitsuba/core/util.h>\n#include <mitsuba/core/random.h>\n#include <mitsuba/core/quad.h>\n#include <mitsuba/core/sse.h>\n#include <mitsuba/core/frame.h>\n#include <boost/bind.hpp>\n#include <stdarg.h>\n#include <iomanip>\n#include <errno.h>\n\n#if defined(__OSX__)\n#include <sys/sysctl.h>\n#include <mach/mach.h>\n#elif defined(__WINDOWS__)\n#include <windows.h>\n#include <direct.h>\n#include <psapi.h>\n#else\n#include <malloc.h>\n#endif\n\n#if defined(__WINDOWS__)\n# include <windows.h>\n# include <winsock2.h>\n# include <ws2tcpip.h>\n#else\n# include <sys/types.h>\n# include <sys/socket.h>\n# include <netdb.h>\n# include <fenv.h>\n#endif\n\n// SSE is not enabled in general when using double precision, however it is\n// required in OS X for FP exception handling\n#if defined(__OSX__) && !defined(MTS_SSE)\n#include <xmmintrin.h>\n#undef enable_fpexcept_sse\n#undef query_fpexcept_sse\n#undef disable_fpexcept_sse\n\nnamespace {\ninline void enable_fpexcept_sse() {\n\t_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() &\n\t\t~(_MM_MASK_INVALID | _MM_MASK_DIV_ZERO));\n}\ninline unsigned int query_fpexcept_sse() {\n\treturn (~_MM_GET_EXCEPTION_MASK() &\n\t\t(_MM_MASK_INVALID | _MM_MASK_DIV_ZERO));\n}\ninline void disable_fpexcept_sse() {\n\t_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() |\n\t\t_MM_MASK_INVALID | _MM_MASK_DIV_ZERO);\n}\n} // namespace\n\n#endif\n\nMTS_NAMESPACE_BEGIN\n\n// -----------------------------------------------------------------------\n//  General utility functions\n// -----------------------------------------------------------------------\n\nstd::vector<std::string> tokenize(const std::string &string, const std::string &delim) {\n\tstd::string::size_type lastPos = string.find_first_not_of(delim, 0);\n\tstd::string::size_type pos = string.find_first_of(delim, lastPos);\n\tstd::vector<std::string> tokens;\n\n\twhile (std::string::npos != pos || std::string::npos != lastPos) {\n\t\ttokens.push_back(string.substr(lastPos, pos - lastPos));\n\t\tlastPos = string.find_first_not_of(delim, pos);\n\t\tpos = string.find_first_of(delim, lastPos);\n\t}\n\n\treturn tokens;\n}\n\nstd::string trim(const std::string& str) {\n\tstd::string::size_type\n\t\tstart = str.find_first_not_of(\" \\t\\r\\n\"),\n\t\tend = str.find_last_not_of(\" \\t\\r\\n\");\n\n\treturn str.substr(start == std::string::npos ? 0 : start,\n\t\t\tend == std::string::npos ? str.length() - 1 : end - start + 1);\n}\n\nstd::string indent(const std::string &string, int amount) {\n\t/* This could probably be done faster (is not\n\t   really speed-critical though) */\n\tstd::istringstream iss(string);\n\tstd::ostringstream oss;\n\tstd::string str;\n\tbool firstLine = true;\n\twhile (!iss.eof()) {\n\t\tstd::getline(iss, str);\n\t\tif (!firstLine) {\n\t\t\tfor (int i=0; i<amount; ++i)\n\t\t\t\toss << \"  \";\n\t\t}\n\t\toss << str;\n\t\tif (!iss.eof())\n\t\t\toss << endl;\n\t\tfirstLine = false;\n\t}\n\treturn oss.str();\n}\n\nvoid * __restrict allocAligned(size_t size) {\n#if defined(__WINDOWS__)\n\treturn _aligned_malloc(size, L1_CACHE_LINE_SIZE);\n#elif defined(__OSX__)\n\t/* OSX malloc already returns 16-byte aligned data suitable\n\t   for AltiVec and SSE computations */\n\treturn malloc(size);\n#else\n\treturn memalign(L1_CACHE_LINE_SIZE, size);\n#endif\n}\n\nvoid freeAligned(void *ptr) {\n#if defined(__WINDOWS__)\n\t_aligned_free(ptr);\n#else\n\tfree(ptr);\n#endif\n}\n\nstatic int __cached_core_count = 0;\n\nint getCoreCount() {\n\t// assumes atomic word size memory access\n\tif (__cached_core_count)\n\t\treturn __cached_core_count;\n\n#if defined(__WINDOWS__)\n\tSYSTEM_INFO sys_info;\n\tGetSystemInfo(&sys_info);\n\t__cached_core_count = sys_info.dwNumberOfProcessors;\n\treturn sys_info.dwNumberOfProcessors;\n#elif defined(__OSX__)\n\tint nprocs;\n\tsize_t nprocsSize = sizeof(int);\n\tif (sysctlbyname(\"hw.activecpu\", &nprocs, &nprocsSize, NULL, 0))\n\t\tSLog(EError, \"Could not detect the number of processors!\");\n\t__cached_core_count = nprocs;\n\treturn nprocs;\n#else\n\t/* Determine the number of present cores */\n\tint nCores = sysconf(_SC_NPROCESSORS_CONF);\n\n\t/* Don't try to query CPU affinity if running inside Valgrind */\n\tif (getenv(\"VALGRIND_OPTS\") == NULL) {\n\t\t/* Some of the cores may not be available to the user\n\t\t   (e.g. on certain cluster nodes) -- determine the number\n\t\t   of actual available cores here. */\n\t\tint nLogicalCores = nCores;\n\t\tsize_t size = 0;\n\t\tcpu_set_t *cpuset = NULL;\n\t\tint retval = 0;\n\n\t\t/* The kernel may expect a larger cpu_set_t than would\n\t\t   be warranted by the physical core count. Keep querying\n\t\t   with increasingly larger buffers if the\n\t\t   pthread_getaffinity_np operation fails */\n\t\tfor (int i = 0; i<6; ++i) { \n\t\t\tsize = CPU_ALLOC_SIZE(nLogicalCores);\n\t\t\tcpuset = CPU_ALLOC(nLogicalCores);\n\t\t\tif (!cpuset) {\n\t\t\t\tSLog(EWarn, \"getCoreCount(): could not allocate cpu_set_t\");\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tCPU_ZERO_S(size, cpuset);\n\n\t\t\tint retval = pthread_getaffinity_np(pthread_self(), size, cpuset);\n\t\t\tif (retval == 0)\n\t\t\t\tbreak;\n\t\t\tCPU_FREE(cpuset);\n\t\t\tnLogicalCores *= 2;\n\t\t}\n\n\t\tif (retval) {\n\t\t\tSLog(EWarn, \"getCoreCount(): pthread_getaffinity_np(): could \"\n\t\t\t\t\"not read thread affinity map: %s\", strerror(retval));\n\t\t\tgoto done;\n\t\t}\n\n\t\tint availableCores = 0;\n\t\tfor (int i=0; i<nLogicalCores; ++i)\n\t\t\tavailableCores += CPU_ISSET_S(i, size, cpuset) ? 1 : 0;\n\t\tnCores = availableCores;\n\t\tCPU_FREE(cpuset);\n\t}\n\ndone:\n\t__cached_core_count = nCores;\n\treturn nCores;\n#endif\n}\n\nsize_t getTotalSystemMemory() {\n#if defined(__WINDOWS__)\n\tMEMORYSTATUSEX status;\n\tstatus.dwLength = sizeof(status);\n\tGlobalMemoryStatusEx(&status);\n\treturn (size_t) status.ullTotalPhys;\n#elif defined(__OSX__)\n\tint mib[2] = { CTL_HW, HW_MEMSIZE };\n\tuint64_t size;\n\tsize_t len = sizeof(size);\n\tif (sysctl(mib, 2, &size, &len, NULL, 0) < 0)\n\t\treturn 0;\n\treturn (size_t) size;\n#else\n\tsize_t pages = sysconf(_SC_PHYS_PAGES);\n\tsize_t page_size = sysconf(_SC_PAGE_SIZE);\n\treturn pages * page_size;\n#endif\n}\n\nsize_t getPrivateMemoryUsage() {\n#if defined(__WINDOWS__)\n\tPROCESS_MEMORY_COUNTERS_EX pmc;\n\tGetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *) &pmc, sizeof(pmc));\n\treturn (size_t) pmc.PrivateUsage; /* Process-private memory usage (RAM + swap) */\n#elif defined(__OSX__)\n\tstruct task_basic_info_64 t_info;\n\tmach_msg_type_number_t t_info_count = TASK_BASIC_INFO_64_COUNT;\n\n\tif (task_info(mach_task_self(), TASK_BASIC_INFO_64,\n\t\t\t(task_info_t)&t_info, &t_info_count) != KERN_SUCCESS)\n\t\treturn 0;\n\n\treturn (size_t) t_info.resident_size; /* Not exactly what we want -- oh well.. */\n#else\n\tFILE* file = fopen(\"/proc/self/status\", \"r\");\n\tif (!file)\n\t\treturn 0;\n\n\tchar buffer[128];\n\tsize_t result = 0;\n\twhile (fgets(buffer, sizeof(buffer), file) != NULL) {\n\t\tif (strncmp(buffer, \"VmRSS:\", 6) != 0 && /* Non-swapped physical memory specific to this process */\n\t\t    strncmp(buffer, \"VmSwap:\", 7) != 0)  /* Swapped memory specific to this process */\n\t\t\tcontinue;\n\n\t\tchar *line = buffer;\n\t\twhile (*line < '0' || *line > '9')\n\t\t\t++line;\n\t\tline[strlen(line)-3] = '\\0';\n\t\tresult += (size_t) atoi(line) * 1024;\n\t}\n\n\tfclose(file);\n\treturn result;\n#endif\n}\n\n#if defined(__WINDOWS__)\nstd::string lastErrorText() {\n\tDWORD errCode = GetLastError();\n\tchar *errorText = NULL;\n\tif (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER\n\t\t| FORMAT_MESSAGE_FROM_SYSTEM\n\t\t| FORMAT_MESSAGE_IGNORE_INSERTS,\n\t\tNULL,\n\t\terrCode,\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n\t\t(LPTSTR) &errorText,\n\t\t0,\n\t\tNULL)) {\n\t\treturn \"Internal error while looking up an error code\";\n\t}\n\tstd::string result(errorText);\n\tLocalFree(errorText);\n\treturn result;\n}\n#endif\n\nbool enableFPExceptions() {\n\tbool exceptionsWereEnabled = false;\n#if defined(__WINDOWS__)\n\t_clearfp();\n\tuint32_t cw = _controlfp(0, 0);\n\texceptionsWereEnabled = ~cw & (_EM_INVALID | _EM_ZERODIVIDE | _EM_OVERFLOW);\n\tcw &= ~(_EM_INVALID | _EM_ZERODIVIDE | _EM_OVERFLOW);\n\t_controlfp(cw, _MCW_EM);\n#elif defined(__OSX__)\n\texceptionsWereEnabled = query_fpexcept_sse() != 0;\n#else\n\texceptionsWereEnabled =\n\t\tfegetexcept() & (FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);\n\tfeenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);\n#endif\n\tenable_fpexcept_sse();\n\treturn exceptionsWereEnabled;\n}\n\nbool disableFPExceptions() {\n\tbool exceptionsWereEnabled = false;\n#if defined(__WINDOWS__)\n\t_clearfp();\n\tuint32_t cw = _controlfp(0, 0);\n\texceptionsWereEnabled = ~cw & (_EM_INVALID | _EM_ZERODIVIDE | _EM_OVERFLOW);\n\tcw |= _EM_INVALID | _EM_ZERODIVIDE | _EM_OVERFLOW;\n\t_controlfp(cw, _MCW_EM);\n#elif defined(__OSX__)\n\texceptionsWereEnabled = query_fpexcept_sse() != 0;\n#else\n\texceptionsWereEnabled =\n\t\tfegetexcept() & (FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);\n\tfedisableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);\n#endif\n\tdisable_fpexcept_sse();\n\treturn exceptionsWereEnabled;\n}\n\nvoid restoreFPExceptions(bool oldState) {\n\tbool currentState;\n#if defined(__WINDOWS__)\n\tuint32_t cw = _controlfp(0, 0);\n\tcurrentState = ~cw & (_EM_INVALID | _EM_ZERODIVIDE | _EM_OVERFLOW);\n#elif defined(__OSX__)\n\tcurrentState = query_fpexcept_sse() != 0;\n#else\n\tcurrentState = fegetexcept() & (FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);\n#endif\n\tif (oldState != currentState) {\n\t\tif (oldState)\n\t\t\tenableFPExceptions();\n\t\telse\n\t\t\tdisableFPExceptions();\n\t}\n}\n\nstd::string getHostName() {\n\tchar hostName[128];\n\tif (gethostname(hostName, sizeof(hostName)) != 0)\n#if defined(__WINDOWS__)\n\t\tSLog(EError, \"Could not retrieve the computer's host name: %s!\",\n\t\t\tlastErrorText().c_str());\n#else\n\t\tSLog(EError, \"Could not retrieve the computer's host name : %s!\",\n\t\t\tstrerror(errno));\n#endif\n\treturn hostName;\n}\n\nstd::string getFQDN() {\n\tstruct addrinfo *addrInfo = NULL, hints;\n\tmemset(&hints, 0, sizeof(addrinfo));\n\t// Only look for IPv4 addresses -- perhaps revisit this later\n\thints.ai_family = AF_INET; // AF_UNSPEC\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_protocol = IPPROTO_TCP;\n\n\tint retVal = getaddrinfo(getHostName().c_str(), NULL, &hints, &addrInfo);\n\tif (addrInfo == NULL || retVal != 0) {\n\t\tSLog(EWarn, \"Could not retrieve the computer's fully \"\n\t\t\t\"qualified domain name: could not resolve host address \\\"%s\\\"!\",\n\t\t\tgetHostName().c_str());\n\t\treturn getHostName();\n\t}\n\n\tchar fqdn[NI_MAXHOST];\n\tretVal = getnameinfo(addrInfo->ai_addr, sizeof(struct sockaddr_in),\n\t\tfqdn, NI_MAXHOST, NULL, 0, 0);\n\tif (retVal != 0) {\n\t\tfreeaddrinfo(addrInfo);\n#if defined(__WINDOWS__)\n\t\tSLog(EWarn, \"Could not retrieve the computer's fully \"\n\t\t\t\"qualified domain name: error %i!\", WSAGetLastError());\n#else\n\t\tSLog(EWarn, \"Could not retrieve the computer's fully \"\n\t\t\t\"qualified domain name: error %i!\", gai_strerror(retVal));\n#endif\n\t\treturn getHostName();\n\t}\n\n\tfreeaddrinfo(addrInfo);\n\n\treturn fqdn;\n}\n\nstd::string formatString(const char *fmt, ...) {\n\tchar tmp[512];\n\tva_list iterator;\n\n#if defined(__WINDOWS__)\n\tva_start(iterator, fmt);\n\tsize_t size = _vscprintf(fmt, iterator) + 1;\n\n\tif (size >= sizeof(tmp)) {\n\t\tchar *dest = new char[size];\n\t\tvsnprintf_s(dest, size, size-1, fmt, iterator);\n\t\tva_end(iterator);\n\t\tstd::string result(dest);\n\t\tdelete[] dest;\n\t\treturn result;\n\t}\n\n\tvsnprintf_s(tmp, size, size-1, fmt, iterator);\n\tva_end(iterator);\n#else\n\tva_start(iterator, fmt);\n\tsize_t size = vsnprintf(tmp, sizeof(tmp), fmt, iterator);\n\tva_end(iterator);\n\n\tif (size >= sizeof(tmp)) {\n\t\t/* Overflow! -- dynamically allocate memory */\n\t\tchar *dest = new char[size+1];\n\t\tva_start(iterator, fmt);\n\t\tvsnprintf(dest, size+1, fmt, iterator);\n\t\tva_end(iterator);\n\n\t\tstd::string result(dest);\n\t\tdelete[] dest;\n\t\treturn result;\n\t}\n#endif\n\n\treturn std::string(tmp);\n}\n\n// -----------------------------------------------------------------------\n//  Numerical utility functions\n// -----------------------------------------------------------------------\n\nbool solveQuadratic(Float a, Float b, Float c, Float &x0, Float &x1) {\n\t/* Linear case */\n\tif (a == 0) {\n\t\tif (b != 0) {\n\t\t\tx0 = x1 = -c / b;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tFloat discrim = b*b - 4.0f*a*c;\n\n\t/* Leave if there is no solution */\n\tif (discrim < 0)\n\t\treturn false;\n\n\tFloat temp, sqrtDiscrim = std::sqrt(discrim);\n\n\t/* Numerically stable version of (-b (+/-) sqrtDiscrim) / (2 * a)\n\t *\n\t * Based on the observation that one solution is always\n\t * accurate while the other is not. Finds the solution of\n\t * greater magnitude which does not suffer from loss of\n\t * precision and then uses the identity x1 * x2 = c / a\n\t */\n\tif (b < 0)\n\t\ttemp = -0.5f * (b - sqrtDiscrim);\n\telse\n\t\ttemp = -0.5f * (b + sqrtDiscrim);\n\n\tx0 = temp / a;\n\tx1 = c / temp;\n\n\t/* Return the results so that x0 < x1 */\n\tif (x0 > x1)\n\t\tstd::swap(x0, x1);\n\n\treturn true;\n}\n\nbool solveQuadraticDouble(double a, double b, double c, double &x0, double &x1) {\n\t/* Linear case */\n\tif (a == 0) {\n\t\tif (b != 0) {\n\t\t\tx0 = x1 = -c / b;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tdouble discrim = b*b - 4.0f*a*c;\n\n\t/* Leave if there is no solution */\n\tif (discrim < 0)\n\t\treturn false;\n\n\tdouble temp, sqrtDiscrim = std::sqrt(discrim);\n\n\t/* Numerically stable version of (-b (+/-) sqrtDiscrim) / (2 * a)\n\t *\n\t * Based on the observation that one solution is always\n\t * accurate while the other is not. Finds the solution of\n\t * greater magnitude which does not suffer from loss of\n\t * precision and then uses the identity x1 * x2 = c / a\n\t */\n\tif (b < 0)\n\t\ttemp = -0.5f * (b - sqrtDiscrim);\n\telse\n\t\ttemp = -0.5f * (b + sqrtDiscrim);\n\n\tx0 = temp / a;\n\tx1 = c / temp;\n\n\t/* Return the results so that x0 < x1 */\n\tif (x0 > x1)\n\t\tstd::swap(x0, x1);\n\n\treturn true;\n}\n\nbool solveLinearSystem2x2(const Float a[2][2], const Float b[2], Float x[2]) {\n\tFloat det = a[0][0] * a[1][1] - a[0][1] * a[1][0];\n\n\tif (std::abs(det) <= RCPOVERFLOW)\n\t\treturn false;\n\n\tFloat inverse = (Float) 1.0f / det;\n\n\tx[0] = (a[1][1] * b[0] - a[0][1] * b[1]) * inverse;\n\tx[1] = (a[0][0] * b[1] - a[1][0] * b[0]) * inverse;\n\n\treturn true;\n}\n\nvoid stratifiedSample1D(Random *random, Float *dest, int count, bool jitter) {\n\tFloat invCount = 1.0f / count;\n\n\tfor (int i=0; i<count; i++) {\n\t\tFloat offset = jitter ? random->nextFloat() : 0.5f;\n\t\t*dest++ = (i + offset) * invCount;\n\t}\n}\n\nvoid stratifiedSample2D(Random *random, Point2 *dest, int countX, int countY, bool jitter) {\n\tFloat invCountX = 1.0f / countX;\n\tFloat invCountY = 1.0f / countY;\n\n\tfor (int x=0; x<countX; x++) {\n\t\tfor (int y=0; y<countY; y++) {\n\t\t\tFloat offsetX = jitter ? random->nextFloat() : 0.5f;\n\t\t\tFloat offsetY = jitter ? random->nextFloat() : 0.5f;\n\t\t\t*dest++ = Point2(\n\t\t\t\t(x + offsetX) * invCountX,\n\t\t\t\t(y + offsetY) * invCountY\n\t\t\t);\n\t\t}\n\t}\n}\n\nvoid latinHypercube(Random *random, Float *dest, size_t nSamples, size_t nDim) {\n\tFloat delta = 1 / (Float) nSamples;\n\tfor (size_t i = 0; i < nSamples; ++i)\n\t\tfor (size_t j = 0; j < nDim; ++j)\n\t\t\tdest[nDim * i + j] = (i + random->nextFloat()) * delta;\n\tfor (size_t i = 0; i < nDim; ++i) {\n\t\tfor (size_t j = 0; j < nSamples; ++j) {\n\t\t\tsize_t other = random->nextSize(nSamples);\n\t\t\tstd::swap(dest[nDim * j + i], dest[nDim * other + i]);\n\t\t}\n\t}\n}\n\nVector sphericalDirection(Float theta, Float phi) {\n\tFloat sinTheta, cosTheta, sinPhi, cosPhi;\n\n\tmath::sincos(theta, &sinTheta, &cosTheta);\n\tmath::sincos(phi, &sinPhi, &cosPhi);\n\n\treturn Vector(\n\t\tsinTheta * cosPhi,\n\t\tsinTheta * sinPhi,\n\t\tcosTheta\n\t);\n}\n\nvoid coordinateSystem(const Vector &a, Vector &b, Vector &c) {\n\tif (std::abs(a.x) > std::abs(a.y)) {\n\t\tFloat invLen = 1.0f / std::sqrt(a.x * a.x + a.z * a.z);\n\t\tc = Vector(a.z * invLen, 0.0f, -a.x * invLen);\n\t} else {\n\t\tFloat invLen = 1.0f / std::sqrt(a.y * a.y + a.z * a.z);\n\t\tc = Vector(0.0f, a.z * invLen, -a.y * invLen);\n\t}\n\tb = cross(c, a);\n}\n\nvoid computeShadingFrame(const Vector &n, const Vector &dpdu, Frame &frame) {\n\tframe.n = n;\n\tframe.s = normalize(dpdu - frame.n\n\t\t* dot(frame.n, dpdu));\n\tframe.t = cross(frame.n, frame.s);\n}\n\nvoid computeShadingFrameDerivative(const Vector &n, const Vector &dpdu, const Vector &dndu, const Vector &dndv, Frame &du, Frame &dv) {\n\tVector s = dpdu - n * dot(n, dpdu);\n\tFloat invLen_s = 1.0f / s.length();\n\ts *= invLen_s;\n\n\tdu.s = invLen_s * (-dndu * dot(n, dpdu) - n * dot(dndu, dpdu));\n\tdv.s = invLen_s * (-dndv * dot(n, dpdu) - n * dot(dndv, dpdu));\n\n\tdu.s -= s * dot(du.s, s);\n\tdv.s -= s * dot(dv.s, s);\n\n\tdu.t = cross(dndu, s) + cross(n, du.s);\n\tdv.t = cross(dndv, s) + cross(n, dv.s);\n\n\tdu.n = dndu;\n\tdv.n = dndv;\n}\n\nPoint2 toSphericalCoordinates(const Vector &v) {\n\tPoint2 result(\n\t\tstd::acos(v.z),\n\t\tstd::atan2(v.y, v.x)\n\t);\n\tif (result.y < 0)\n\t\tresult.y += 2*M_PI;\n\treturn result;\n}\n\nFloat fresnelDielectric(Float cosThetaI, Float cosThetaT, Float eta) {\n\tif (EXPECT_NOT_TAKEN(eta == 1))\n\t\treturn 0.0f;\n\n\tFloat Rs = (cosThetaI - eta * cosThetaT)\n\t\t\t / (cosThetaI + eta * cosThetaT);\n\tFloat Rp = (eta * cosThetaI - cosThetaT)\n\t\t\t / (eta * cosThetaI + cosThetaT);\n\n\t/* No polarization -- return the unpolarized reflectance */\n\treturn 0.5f * (Rs * Rs + Rp * Rp);\n}\n\nFloat fresnelDielectricExt(Float cosThetaI_, Float &cosThetaT_, Float eta) {\n\tif (EXPECT_NOT_TAKEN(eta == 1)) {\n\t\tcosThetaT_ = -cosThetaI_;\n\t\treturn 0.0f;\n\t}\n\n\t/* Using Snell's law, calculate the squared sine of the\n\t   angle between the normal and the transmitted ray */\n\tFloat scale = (cosThetaI_ > 0) ? 1/eta : eta,\n\t      cosThetaTSqr = 1 - (1-cosThetaI_*cosThetaI_) * (scale*scale);\n\n\t/* Check for total internal reflection */\n\tif (cosThetaTSqr <= 0.0f) {\n\t\tcosThetaT_ = 0.0f;\n\t\treturn 1.0f;\n\t}\n\n\t/* Find the absolute cosines of the incident/transmitted rays */\n\tFloat cosThetaI = std::abs(cosThetaI_);\n\tFloat cosThetaT = std::sqrt(cosThetaTSqr);\n\n\tFloat Rs = (cosThetaI - eta * cosThetaT)\n\t\t\t / (cosThetaI + eta * cosThetaT);\n\tFloat Rp = (eta * cosThetaI - cosThetaT)\n\t\t\t / (eta * cosThetaI + cosThetaT);\n\n\tcosThetaT_ = (cosThetaI_ > 0) ? -cosThetaT : cosThetaT;\n\n\t/* No polarization -- return the unpolarized reflectance */\n\treturn 0.5f * (Rs * Rs + Rp * Rp);\n}\n\nFloat fresnelConductorApprox(Float cosThetaI, Float eta, Float k) {\n\tFloat cosThetaI2 = cosThetaI*cosThetaI;\n\n\tFloat tmp = (eta*eta + k*k) * cosThetaI2;\n\n\tFloat Rp2 = (tmp - (eta * (2 * cosThetaI)) + 1)\n\t          / (tmp + (eta * (2 * cosThetaI)) + 1);\n\n\tFloat tmpF = eta*eta + k*k;\n\n\tFloat Rs2 = (tmpF - (eta * (2 * cosThetaI)) + cosThetaI2) /\n\t            (tmpF + (eta * (2 * cosThetaI)) + cosThetaI2);\n\n\treturn 0.5f * (Rp2 + Rs2);\n}\n\nSpectrum fresnelConductorApprox(Float cosThetaI, const Spectrum &eta, const Spectrum &k) {\n\tFloat cosThetaI2 = cosThetaI*cosThetaI;\n\n\tSpectrum tmp = (eta*eta + k*k) * cosThetaI2;\n\n\tSpectrum Rp2 = (tmp - (eta * (2 * cosThetaI)) + Spectrum(1.0f))\n\t             / (tmp + (eta * (2 * cosThetaI)) + Spectrum(1.0f));\n\n\tSpectrum tmpF = eta*eta + k*k;\n\n\tSpectrum Rs2 = (tmpF - (eta * (2 * cosThetaI)) + Spectrum(cosThetaI2)) /\n\t               (tmpF + (eta * (2 * cosThetaI)) + Spectrum(cosThetaI2));\n\n\treturn 0.5f * (Rp2 + Rs2);\n}\n\nFloat fresnelConductorExact(Float cosThetaI, Float eta, Float k) {\n\t/* Modified from \"Optics\" by K.D. Moeller, University Science Books, 1988 */\n\n\tFloat cosThetaI2 = cosThetaI*cosThetaI,\n\t      sinThetaI2 = 1-cosThetaI2,\n\t\t  sinThetaI4 = sinThetaI2*sinThetaI2;\n\n\tFloat temp1 = eta*eta - k*k - sinThetaI2,\n\t      a2pb2 = math::safe_sqrt(temp1*temp1 + 4*k*k*eta*eta),\n\t      a     = math::safe_sqrt(0.5f * (a2pb2 + temp1));\n\n\tFloat term1 = a2pb2 + cosThetaI2,\n\t      term2 = 2*a*cosThetaI;\n\n\tFloat Rs2 = (term1 - term2) / (term1 + term2);\n\n\tFloat term3 = a2pb2*cosThetaI2 + sinThetaI4,\n\t      term4 = term2*sinThetaI2;\n\n\tFloat Rp2 = Rs2 * (term3 - term4) / (term3 + term4);\n\n\treturn 0.5f * (Rp2 + Rs2);\n}\n\nSpectrum fresnelConductorExact(Float cosThetaI, const Spectrum &eta, const Spectrum &k) {\n\t/* Modified from \"Optics\" by K.D. Moeller, University Science Books, 1988 */\n\n\tFloat cosThetaI2 = cosThetaI*cosThetaI,\n\t      sinThetaI2 = 1-cosThetaI2,\n\t\t  sinThetaI4 = sinThetaI2*sinThetaI2;\n\n\tSpectrum temp1 = eta*eta - k*k - Spectrum(sinThetaI2),\n\t         a2pb2 = (temp1*temp1 + k*k*eta*eta*4).safe_sqrt(),\n\t         a     = ((a2pb2 + temp1) * 0.5f).safe_sqrt();\n\n\tSpectrum term1 = a2pb2 + Spectrum(cosThetaI2),\n\t         term2 = a*(2*cosThetaI);\n\n\tSpectrum Rs2 = (term1 - term2) / (term1 + term2);\n\n\tSpectrum term3 = a2pb2*cosThetaI2 + Spectrum(sinThetaI4),\n\t         term4 = term2*sinThetaI2;\n\n\tSpectrum Rp2 = Rs2 * (term3 - term4) / (term3 + term4);\n\n\treturn 0.5f * (Rp2 + Rs2);\n}\n\nVector reflect(const Vector &wi, const Normal &n) {\n\treturn 2 * dot(wi, n) * Vector(n) - wi;\n}\n\nVector refract(const Vector &wi, const Normal &n, Float eta, Float cosThetaT) {\n\tif (cosThetaT < 0)\n\t\teta = 1 / eta;\n\n\treturn n * (dot(wi, n) * eta + cosThetaT) - wi * eta;\n}\n\nVector refract(const Vector &wi, const Normal &n, Float eta) {\n\tif (EXPECT_NOT_TAKEN(eta == 1))\n\t\treturn -wi;\n\n\tFloat cosThetaI = dot(wi, n);\n\tif (cosThetaI > 0)\n\t\teta = 1 / eta;\n\n\t/* Using Snell's law, calculate the squared sine of the\n\t   angle between the normal and the transmitted ray */\n\tFloat cosThetaTSqr = 1 - (1-cosThetaI*cosThetaI) * (eta*eta);\n\n\t/* Check for total internal reflection */\n\tif (cosThetaTSqr <= 0.0f)\n\t\treturn Vector(0.0f);\n\n\treturn n * (cosThetaI * eta - math::signum(cosThetaI)\n\t\t* std::sqrt(cosThetaTSqr)) - wi * eta;\n}\n\nVector refract(const Vector &wi, const Normal &n, Float eta, Float &cosThetaT, Float &F) {\n\tFloat cosThetaI = dot(wi, n);\n\tF = fresnelDielectricExt(cosThetaI, cosThetaT, eta);\n\n\tif (F == 1.0f) /* Total internal reflection */\n\t\treturn Vector(0.0f);\n\n\tif (cosThetaT < 0)\n\t\teta = 1 / eta;\n\n\treturn n * (eta * cosThetaI + cosThetaT) - wi * eta;\n}\n\nnamespace {\n\t/// Integrand used by fresnelDiffuseReflectance\n\tinline Float fresnelDiffuseIntegrand(Float eta, Float xi) {\n\t\treturn fresnelDielectricExt(std::sqrt(xi), eta);\n\t}\n};\n\nFloat fresnelDiffuseReflectance(Float eta, bool fast) {\n\tif (fast) {\n\t\t/* Fast mode: the following code approximates the\n\t\t * diffuse Frensel reflectance for the eta<1 and\n\t\t * eta>1 cases. An evalution of the accuracy led\n\t\t * to the following scheme, which cherry-picks\n\t\t * fits from two papers where they are best.\n\t\t */\n\t\tif (eta < 1) {\n\t\t\t/* Fit by Egan and Hilgeman (1973). Works\n\t\t\t   reasonably well for \"normal\" IOR values (<2).\n\n\t\t\t   Max rel. error in 1.0 - 1.5 : 0.1%\n\t\t\t   Max rel. error in 1.5 - 2   : 0.6%\n\t\t\t   Max rel. error in 2.0 - 5   : 9.5%\n\t\t\t*/\n\t\t\treturn -1.4399f * (eta * eta)\n\t\t\t\t  + 0.7099f * eta\n\t\t\t\t  + 0.6681f\n\t\t\t\t  + 0.0636f / eta;\n\t\t} else {\n\t\t\t/* Fit by d'Eon and Irving (2011)\n\t\t\t *\n\t\t\t * Maintains a good accuracy even for\n\t\t\t * unrealistic IOR values.\n\t\t\t *\n\t\t\t * Max rel. error in 1.0 - 2.0   : 0.1%\n\t\t\t * Max rel. error in 2.0 - 10.0  : 0.2%\n\t\t\t */\n\t\t\tFloat invEta = 1.0f / eta,\n\t\t\t\t  invEta2 = invEta*invEta,\n\t\t\t\t  invEta3 = invEta2*invEta,\n\t\t\t\t  invEta4 = invEta3*invEta,\n\t\t\t\t  invEta5 = invEta4*invEta;\n\n\t\t\treturn 0.919317f - 3.4793f * invEta\n\t\t\t\t + 6.75335f * invEta2\n\t\t\t\t - 7.80989f * invEta3\n\t\t\t\t + 4.98554f * invEta4\n\t\t\t\t - 1.36881f * invEta5;\n\t\t}\n\t} else {\n\t\tGaussLobattoIntegrator quad(1024, 0, 1e-5f);\n\t\treturn quad.integrate(\n\t\t\tboost::bind(&fresnelDiffuseIntegrand, eta, _1), 0, 1);\n\t}\n\n\treturn 0.0f;\n}\n\nstd::string timeString(Float time, bool precise) {\n\tif (std::isnan(time) || std::isinf(time))\n\t\treturn \"inf\";\n\n\tchar suffix = 's';\n\tif (time > 60) {\n\t\ttime /= 60; suffix = 'm';\n\t\tif (time > 60) {\n\t\t\ttime /= 60; suffix = 'h';\n\t\t\tif (time > 12) {\n\t\t\t\ttime /= 12; suffix = 'd';\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::ostringstream os;\n\tos << std::setprecision(precise ? 4 : 1)\n\t   << std::fixed << time << suffix;\n\n\treturn os.str();\n}\n\nstd::string memString(size_t size, bool precise) {\n\tFloat value = (Float) size;\n\tconst char *suffixes[] = {\n\t\t\"B\", \"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\"\n\t};\n\tint suffix = 0;\n\twhile (suffix < 5 && value > 1024.0f) {\n\t\tvalue /= 1024.0f; ++suffix;\n\t}\n\n\tstd::ostringstream os;\n\tos << std::setprecision(suffix == 0 ? 0 : (precise ? 4 : 1))\n\t   << std::fixed << value << \" \" << suffixes[suffix];\n\n\treturn os.str();\n}\n\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "a113bb40ee4785ba1bbc0870d694740038e6b889", "size": 24211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/libcore/util.cpp", "max_stars_repo_name": "NTForked-ML/pbrs", "max_stars_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T00:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:33:10.000Z", "max_issues_repo_path": "mitsuba-af602c6fd98a/src/libcore/util.cpp", "max_issues_repo_name": "NTForked-ML/pbrs", "max_issues_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-08-15T18:22:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-01T05:44:41.000Z", "max_forks_repo_path": "mitsuba-af602c6fd98a/src/libcore/util.cpp", "max_forks_repo_name": "NTForked-ML/pbrs", "max_forks_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-21T03:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T06:55:34.000Z", "avg_line_length": 26.782079646, "max_line_length": 135, "alphanum_fraction": 0.6561893354, "num_tokens": 7603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14804719051380197, "lm_q2_score": 0.035144842484767305, "lm_q1q2_score": 0.005203095190919906}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\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//  Authors: Douglas Gregor\r\n//           Andrew Lumsdaine\r\n#ifndef BOOST_GRAPH_PARALLEL_BRANDES_BETWEENNESS_CENTRALITY_HPP\r\n#define BOOST_GRAPH_PARALLEL_BRANDES_BETWEENNESS_CENTRALITY_HPP\r\n\r\n#ifndef BOOST_GRAPH_USE_MPI\r\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\r\n#endif\r\n\r\n// #define COMPUTE_PATH_COUNTS_INLINE\r\n\r\n#include <boost/graph/betweenness_centrality.hpp>\r\n#include <boost/graph/overloading.hpp>\r\n#include <boost/graph/distributed/concepts.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/config.hpp>\r\n\r\n// For additive_reducer\r\n#include <boost/graph/distributed/distributed_graph_utility.hpp>\r\n#include <boost/type_traits/is_convertible.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n\r\n#include <boost/property_map/parallel/distributed_property_map.hpp>\r\n#include <boost/graph/distributed/detail/dijkstra_shortest_paths.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n\r\n// NGE - Needed for minstd_rand at L807, should pass vertex list\r\n//       or generator instead \r\n#include <boost/random/linear_congruential.hpp>\r\n\r\n#include <algorithm>\r\n#include <stack>\r\n#include <vector>\r\n\r\n// Appending reducer\r\ntemplate <typename T>\r\nstruct append_reducer {\r\n  BOOST_STATIC_CONSTANT(bool, non_default_resolver = true);\r\n      \r\n  template<typename K>\r\n  T operator()(const K&) const { return T(); }\r\n      \r\n  template<typename K>\r\n  T operator()(const K&, const T& x, const T& y) const \r\n  { \r\n    T z(x.begin(), x.end());\r\n    for (typename T::const_iterator iter = y.begin(); iter != y.end(); ++iter)\r\n      if (std::find(z.begin(), z.end(), *iter) == z.end())\r\n        z.push_back(*iter);\r\n    \r\n    return z;\r\n  }\r\n};\r\n\r\nnamespace boost {\r\n\r\n  namespace serialization {\r\n\r\n    // TODO(nge): Write generalized serialization for tuples\r\n    template<typename Archive, typename T1, typename T2, typename T3, \r\n             typename T4>\r\n    void serialize(Archive & ar,\r\n                   boost::tuple<T1,T2,T3, T4>& t,\r\n                   const unsigned int)\r\n    {\r\n      ar & boost::tuples::get<0>(t);\r\n      ar & boost::tuples::get<1>(t);\r\n      ar & boost::tuples::get<2>(t);\r\n      ar & boost::tuples::get<3>(t);\r\n    }\r\n\r\n  } // serialization\r\n\r\n  template <typename OwnerMap, typename Tuple>\r\n  class get_owner_of_first_tuple_element {\r\n\r\n  public:\r\n    typedef typename property_traits<OwnerMap>::value_type owner_type;\r\n    \r\n    get_owner_of_first_tuple_element(OwnerMap owner) : owner(owner) { }\r\n\r\n    owner_type get_owner(Tuple t) { return get(owner, boost::tuples::get<0>(t)); }\r\n\r\n  private:\r\n    OwnerMap owner;\r\n  };\r\n\r\n  template <typename OwnerMap, typename Tuple>\r\n  typename get_owner_of_first_tuple_element<OwnerMap, Tuple>::owner_type\r\n  get(get_owner_of_first_tuple_element<OwnerMap, Tuple> o, Tuple t)\r\n  { return o.get_owner(t); } \r\n\r\n  template <typename OwnerMap>\r\n  class get_owner_of_first_pair_element {\r\n\r\n  public:\r\n    typedef typename property_traits<OwnerMap>::value_type owner_type;\r\n    \r\n    get_owner_of_first_pair_element(OwnerMap owner) : owner(owner) { }\r\n\r\n    template <typename Vertex, typename T>\r\n    owner_type get_owner(std::pair<Vertex, T> p) { return get(owner, p.first); }\r\n\r\n  private:\r\n    OwnerMap owner;\r\n  };\r\n\r\n  template <typename OwnerMap, typename Vertex, typename T>\r\n  typename get_owner_of_first_pair_element<OwnerMap>::owner_type\r\n  get(get_owner_of_first_pair_element<OwnerMap> o, std::pair<Vertex, T> p)\r\n  { return o.get_owner(p); } \r\n\r\n  namespace graph { namespace parallel { namespace detail {\r\n\r\n  template<typename DistanceMap, typename IncomingMap>\r\n  class betweenness_centrality_msg_value\r\n  {\r\n    typedef typename property_traits<DistanceMap>::value_type distance_type;\r\n    typedef typename property_traits<IncomingMap>::value_type incoming_type;\r\n    typedef typename incoming_type::value_type incoming_value_type;\r\n\r\n  public:\r\n    typedef std::pair<distance_type, incoming_value_type> type;\r\n    \r\n    static type create(distance_type dist, incoming_value_type source)\r\n    { return std::make_pair(dist, source); }\r\n  };\r\n\r\n\r\n  /************************************************************************/\r\n  /* Delta-stepping Betweenness Centrality                                */\r\n  /************************************************************************/\r\n\r\n  template<typename Graph, typename DistanceMap, typename IncomingMap, \r\n           typename EdgeWeightMap, typename PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           , typename IsSettledMap, typename VertexIndexMap\r\n#endif\r\n           >\r\n  class betweenness_centrality_delta_stepping_impl { \r\n    // Could inherit from delta_stepping_impl to get run() method\r\n    // but for the time being it's just reproduced here\r\n\r\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n    typedef typename graph_traits<Graph>::degree_size_type Degree;\r\n    typedef typename property_traits<EdgeWeightMap>::value_type Dist;\r\n    typedef typename property_traits<IncomingMap>::value_type IncomingType;\r\n    typedef typename boost::graph::parallel::process_group_type<Graph>::type \r\n      ProcessGroup;\r\n    \r\n    typedef std::list<Vertex> Bucket;\r\n    typedef typename Bucket::iterator BucketIterator;\r\n    typedef typename std::vector<Bucket*>::size_type BucketIndex;\r\n\r\n    typedef betweenness_centrality_msg_value<DistanceMap, IncomingMap> \r\n      MessageValue;\r\n    \r\n    enum { \r\n      // Relax a remote vertex. The message contains a pair<Vertex,\r\n      // MessageValue>, the first part of which is the vertex whose\r\n      // tentative distance is being relaxed and the second part\r\n      // contains either the new distance (if there is no predecessor\r\n      // map) or a pair with the distance and predecessor.\r\n      msg_relax \r\n    };\r\n\r\n  public:\r\n\r\n    // Must supply delta, ctor that guesses delta removed \r\n    betweenness_centrality_delta_stepping_impl(const Graph& g,\r\n                                               DistanceMap distance, \r\n                                               IncomingMap incoming,\r\n                                               EdgeWeightMap weight,\r\n                                               PathCountMap path_count,\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n                                               IsSettledMap is_settled,\r\n                                               VertexIndexMap vertex_index,\r\n#endif\r\n                                               Dist delta);\r\n    \r\n    void run(Vertex s);\r\n\r\n  private:\r\n    // Relax the edge (u, v), creating a new best path of distance x.\r\n    void relax(Vertex u, Vertex v, Dist x);\r\n\r\n    // Synchronize all of the processes, by receiving all messages that\r\n    // have not yet been received.\r\n    void synchronize()\r\n    {\r\n      using boost::graph::parallel::synchronize;\r\n      synchronize(pg);\r\n    }\r\n    \r\n    // Setup triggers for msg_relax messages\r\n    void setup_triggers()\r\n    {\r\n      using boost::graph::parallel::simple_trigger;\r\n      simple_trigger(pg, msg_relax, this, \r\n                     &betweenness_centrality_delta_stepping_impl::handle_msg_relax);\r\n    }\r\n\r\n    void handle_msg_relax(int /*source*/, int /*tag*/,\r\n                          const std::pair<Vertex, typename MessageValue::type>& data,\r\n                          trigger_receive_context)\r\n    { relax(data.second.second, data.first, data.second.first); }\r\n\r\n    const Graph& g;\r\n    IncomingMap incoming;\r\n    DistanceMap distance;\r\n    EdgeWeightMap weight;\r\n    PathCountMap path_count;\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n    IsSettledMap is_settled;\r\n    VertexIndexMap vertex_index;\r\n#endif\r\n    Dist delta;\r\n    ProcessGroup pg;\r\n    typename property_map<Graph, vertex_owner_t>::const_type owner;\r\n    typename property_map<Graph, vertex_local_t>::const_type local;\r\n    \r\n    // A \"property map\" that contains the position of each vertex in\r\n    // whatever bucket it resides in.\r\n    std::vector<BucketIterator> position_in_bucket;\r\n    \r\n    // Bucket data structure. The ith bucket contains all local vertices\r\n    // with (tentative) distance in the range [i*delta,\r\n    // (i+1)*delta). \r\n    std::vector<Bucket*> buckets;\r\n    \r\n    // This \"dummy\" list is used only so that we can initialize the\r\n    // position_in_bucket property map with non-singular iterators. This\r\n    // won't matter for most implementations of the C++ Standard\r\n    // Library, but it avoids undefined behavior and allows us to run\r\n    // with library \"debug modes\".\r\n    std::list<Vertex> dummy_list;\r\n    \r\n    // A \"property map\" that states which vertices have been deleted\r\n    // from the bucket in this iteration.\r\n    std::vector<bool> vertex_was_deleted;\r\n  };\r\n\r\n  template<typename Graph, typename DistanceMap, typename IncomingMap, \r\n           typename EdgeWeightMap, typename PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           , typename IsSettledMap, typename VertexIndexMap\r\n#endif\r\n           >\r\n  betweenness_centrality_delta_stepping_impl<\r\n    Graph, DistanceMap, IncomingMap, EdgeWeightMap, PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           , IsSettledMap, VertexIndexMap\r\n#endif\r\n    >::\r\n  betweenness_centrality_delta_stepping_impl(const Graph& g,\r\n                                             DistanceMap distance,\r\n                                             IncomingMap incoming,\r\n                                             EdgeWeightMap weight,\r\n                                             PathCountMap path_count,\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n                                             IsSettledMap is_settled,\r\n                                             VertexIndexMap vertex_index,\r\n#endif\r\n                                             Dist delta)\r\n    : g(g),\r\n      incoming(incoming),\r\n      distance(distance),\r\n      weight(weight),\r\n      path_count(path_count),\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n      is_settled(is_settled),\r\n      vertex_index(vertex_index),\r\n#endif\r\n      delta(delta),\r\n      pg(boost::graph::parallel::process_group_adl(g), attach_distributed_object()),\r\n      owner(get(vertex_owner, g)),\r\n      local(get(vertex_local, g))\r\n\r\n  { setup_triggers(); }\r\n\r\n  template<typename Graph, typename DistanceMap, typename IncomingMap, \r\n           typename EdgeWeightMap, typename PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           , typename IsSettledMap, typename VertexIndexMap\r\n#endif\r\n           >\r\n  void\r\n  betweenness_centrality_delta_stepping_impl<\r\n    Graph, DistanceMap, IncomingMap, EdgeWeightMap, PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           , IsSettledMap, VertexIndexMap\r\n#endif\r\n    >::\r\n  run(Vertex s)\r\n  {\r\n    typedef typename boost::graph::parallel::process_group_type<Graph>::type \r\n      process_group_type;\r\n    typename process_group_type::process_id_type id = process_id(pg);\r\n\r\n    Dist inf = (std::numeric_limits<Dist>::max)();\r\n    \r\n    // None of the vertices are stored in the bucket.\r\n    position_in_bucket.clear();\r\n    position_in_bucket.resize(num_vertices(g), dummy_list.end());\r\n    \r\n    // None of the vertices have been deleted\r\n    vertex_was_deleted.clear();\r\n    vertex_was_deleted.resize(num_vertices(g), false);\r\n    \r\n    // No path from s to any other vertex, yet\r\n    BGL_FORALL_VERTICES_T(v, g, Graph)\r\n      put(distance, v, inf);\r\n    \r\n    // The distance to the starting node is zero\r\n    if (get(owner, s) == id) \r\n      // Put \"s\" into its bucket (bucket 0)\r\n      relax(s, s, 0);\r\n    else\r\n      // Note that we know the distance to s is zero\r\n      cache(distance, s, 0);\r\n    \r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n    // Synchronize here to deliver initial relaxation since we don't\r\n    // synchronize at the beginning of the inner loop any more\r\n    synchronize(); \r\n\r\n    // Incoming edge count map is an implementation detail and should\r\n    // be freed as soon as possible so build it here\r\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\r\n\r\n    std::vector<edges_size_type> incoming_edge_countS(num_vertices(g));\r\n    iterator_property_map<typename std::vector<edges_size_type>::iterator, VertexIndexMap> \r\n      incoming_edge_count(incoming_edge_countS.begin(), vertex_index);\r\n#endif\r\n\r\n    BucketIndex max_bucket = (std::numeric_limits<BucketIndex>::max)();\r\n    BucketIndex current_bucket = 0;\r\n    do {\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n      // We need to clear the outgoing map after every bucket so just build it here\r\n      std::vector<IncomingType> outgoingS(num_vertices(g));\r\n      IncomingMap outgoing(outgoingS.begin(), vertex_index);\r\n      \r\n      outgoing.set_reduce(append_reducer<IncomingType>());\r\n#else\r\n      // Synchronize with all of the other processes.\r\n      synchronize();\r\n#endif    \r\n  \r\n      // Find the next bucket that has something in it.\r\n      while (current_bucket < buckets.size() \r\n             && (!buckets[current_bucket] || buckets[current_bucket]->empty()))\r\n        ++current_bucket;\r\n      if (current_bucket >= buckets.size())\r\n        current_bucket = max_bucket;\r\n      \r\n      // Find the smallest bucket (over all processes) that has vertices\r\n      // that need to be processed.\r\n      using boost::parallel::all_reduce;\r\n      using boost::parallel::minimum;\r\n      current_bucket = all_reduce(pg, current_bucket, minimum<BucketIndex>());\r\n      \r\n      if (current_bucket == max_bucket)\r\n        // There are no non-empty buckets in any process; exit. \r\n        break;\r\n      \r\n      // Contains the set of vertices that have been deleted in the\r\n      // relaxation of \"light\" edges. Note that we keep track of which\r\n      // vertices were deleted with the property map\r\n      // \"vertex_was_deleted\".\r\n      std::vector<Vertex> deleted_vertices;\r\n      \r\n      // Repeatedly relax light edges\r\n      bool nonempty_bucket;\r\n      do {\r\n        // Someone has work to do in this bucket.\r\n        \r\n        if (current_bucket < buckets.size() && buckets[current_bucket]) {\r\n          Bucket& bucket = *buckets[current_bucket];\r\n          // For each element in the bucket\r\n          while (!bucket.empty()) {\r\n            Vertex u = bucket.front();\r\n            \r\n            // Remove u from the front of the bucket\r\n            bucket.pop_front();\r\n            \r\n            // Insert u into the set of deleted vertices, if it hasn't\r\n            // been done already.\r\n            if (!vertex_was_deleted[get(local, u)]) {\r\n              vertex_was_deleted[get(local, u)] = true;\r\n              deleted_vertices.push_back(u);\r\n            }\r\n            \r\n            // Relax each light edge. \r\n            Dist u_dist = get(distance, u);\r\n            BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\r\n              if (get(weight, e) <= delta) // light edge \r\n                relax(u, target(e, g), u_dist + get(weight, e));\r\n          }\r\n        }\r\n\r\n        // Synchronize with all of the other processes.\r\n        synchronize();\r\n        \r\n        // Is the bucket empty now?\r\n        nonempty_bucket = (current_bucket < buckets.size() \r\n                           && buckets[current_bucket]\r\n                           && !buckets[current_bucket]->empty());\r\n      } while (all_reduce(pg, nonempty_bucket, std::logical_or<bool>()));\r\n      \r\n      // Relax heavy edges for each of the vertices that we previously\r\n      // deleted.\r\n      for (typename std::vector<Vertex>::iterator iter = deleted_vertices.begin();\r\n           iter != deleted_vertices.end(); ++iter) {\r\n        // Relax each heavy edge. \r\n        Vertex u = *iter;\r\n        Dist u_dist = get(distance, u);\r\n        BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\r\n          if (get(weight, e) > delta) // heavy edge\r\n            relax(u, target(e, g), u_dist + get(weight, e)); \r\n\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n        // Set outgoing paths\r\n        IncomingType in = get(incoming, u);\r\n        for (typename IncomingType::iterator pred = in.begin(); pred != in.end(); ++pred) \r\n          if (get(owner, *pred) == id) {\r\n            IncomingType x = get(outgoing, *pred);\r\n            if (std::find(x.begin(), x.end(), u) == x.end())\r\n              x.push_back(u);\r\n            put(outgoing, *pred, x);\r\n          } else {\r\n            IncomingType in;\r\n            in.push_back(u);\r\n            put(outgoing, *pred, in);\r\n          }\r\n\r\n        // Set incoming edge counts\r\n        put(incoming_edge_count, u, in.size());\r\n#endif\r\n      }\r\n\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n      synchronize();  // Deliver heavy edge relaxations and outgoing paths\r\n\r\n      // Build Queue\r\n      typedef typename property_traits<PathCountMap>::value_type PathCountType;\r\n      typedef std::pair<Vertex, PathCountType> queue_value_type;\r\n      typedef typename property_map<Graph, vertex_owner_t>::const_type OwnerMap;\r\n      typedef typename get_owner_of_first_pair_element<OwnerMap> IndirectOwnerMap;\r\n\r\n      typedef boost::queue<queue_value_type> local_queue_type;\r\n      typedef boost::graph::distributed::distributed_queue<process_group_type,\r\n                                                           IndirectOwnerMap,\r\n                                                           local_queue_type> dist_queue_type;\r\n\r\n      IndirectOwnerMap indirect_owner(owner);\r\n      dist_queue_type Q(pg, indirect_owner);\r\n\r\n      // Find sources to initialize queue\r\n      BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n        if (get(is_settled, v) && !(get(outgoing, v).empty())) {\r\n          put(incoming_edge_count, v, 1); \r\n          Q.push(std::make_pair(v, 0)); // Push this vertex with no additional path count\r\n        }\r\n      }\r\n\r\n      // Set path counts for vertices in this bucket\r\n      while (!Q.empty()) {\r\n        queue_value_type t = Q.top(); Q.pop();\r\n        Vertex v = t.first;\r\n        PathCountType p = t.second;\r\n\r\n        put(path_count, v, get(path_count, v) + p);\r\n        put(incoming_edge_count, v, get(incoming_edge_count, v) - 1);\r\n\r\n        if (get(incoming_edge_count, v) == 0) {\r\n          IncomingType out = get(outgoing, v);\r\n          for (typename IncomingType::iterator iter = out.begin(); iter != out.end(); ++iter)\r\n            Q.push(std::make_pair(*iter, get(path_count, v)));\r\n        }\r\n      }\r\n\r\n      // Mark the vertices in this bucket settled \r\n      for (typename std::vector<Vertex>::iterator iter = deleted_vertices.begin();\r\n           iter != deleted_vertices.end(); ++iter) \r\n        put(is_settled, *iter, true);\r\n\r\n      // No need to clear path count map as it is never read/written remotely\r\n      // No need to clear outgoing map as it is re-alloced every bucket \r\n#endif\r\n      \r\n      // Go to the next bucket: the current bucket must already be empty.\r\n      ++current_bucket;\r\n    } while (true);\r\n    \r\n    // Delete all of the buckets.\r\n    for (typename std::vector<Bucket*>::iterator iter = buckets.begin();\r\n         iter != buckets.end(); ++iter) {\r\n      if (*iter) {\r\n        delete *iter;\r\n        *iter = 0;\r\n      }\r\n    }\r\n  }\r\n        \r\n  template<typename Graph, typename DistanceMap, typename IncomingMap, \r\n           typename EdgeWeightMap, typename PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           , typename IsSettledMap, typename VertexIndexMap\r\n#endif\r\n           >\r\n  void\r\n  betweenness_centrality_delta_stepping_impl<\r\n    Graph, DistanceMap, IncomingMap, EdgeWeightMap, PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           , IsSettledMap, VertexIndexMap\r\n#endif\r\n    >::\r\n  relax(Vertex u, Vertex v, Dist x)\r\n  {\r\n\r\n    if (x <= get(distance, v)) {\r\n      \r\n      // We're relaxing the edge to vertex v.\r\n      if (get(owner, v) == process_id(pg)) {\r\n        if (x < get(distance, v)) {\r\n          // Compute the new bucket index for v\r\n          BucketIndex new_index = static_cast<BucketIndex>(x / delta);\r\n        \r\n          // Make sure there is enough room in the buckets data structure.\r\n          if (new_index >= buckets.size()) buckets.resize(new_index + 1, 0);\r\n        \r\n          // Make sure that we have allocated the bucket itself.\r\n          if (!buckets[new_index]) buckets[new_index] = new Bucket;\r\n          \r\n          if (get(distance, v) != (std::numeric_limits<Dist>::max)()\r\n              && !vertex_was_deleted[get(local, v)]) {\r\n            // We're moving v from an old bucket into a new one. Compute\r\n            // the old index, then splice it in.\r\n            BucketIndex old_index \r\n              = static_cast<BucketIndex>(get(distance, v) / delta);\r\n            buckets[new_index]->splice(buckets[new_index]->end(),\r\n                                       *buckets[old_index],\r\n                                       position_in_bucket[get(local, v)]);\r\n          } else {\r\n            // We're inserting v into a bucket for the first time. Put it\r\n            // at the end.\r\n            buckets[new_index]->push_back(v);\r\n          }\r\n          \r\n          // v is now at the last position in the new bucket\r\n          position_in_bucket[get(local, v)] = buckets[new_index]->end();\r\n          --position_in_bucket[get(local, v)];\r\n          \r\n          // Update tentative distance information and incoming, path_count\r\n          if (u != v) put(incoming, v, IncomingType(1, u));\r\n          put(distance, v, x);\r\n        }        // u != v covers initial source relaxation and self-loops\r\n        else if (x == get(distance, v) && u != v) {\r\n\r\n          // Add incoming edge if it's not already in the list\r\n          IncomingType in = get(incoming, v);\r\n          if (std::find(in.begin(), in.end(), u) == in.end()) {\r\n            in.push_back(u);\r\n            put(incoming, v, in);\r\n          }\r\n        }\r\n      } else {\r\n        // The vertex is remote: send a request to the vertex's owner\r\n        send(pg, get(owner, v), msg_relax, \r\n             std::make_pair(v, MessageValue::create(x, u)));\r\n\r\n        // Cache tentative distance information\r\n        cache(distance, v, x);\r\n      }\r\n    }\r\n  }\r\n\r\n  /************************************************************************/\r\n  /* Shortest Paths function object for betweenness centrality            */\r\n  /************************************************************************/\r\n\r\n  template<typename WeightMap>\r\n  struct brandes_shortest_paths {\r\n    typedef typename property_traits<WeightMap>::value_type weight_type;\r\n\r\n    brandes_shortest_paths() \r\n      : weight(1), delta(0)  { }\r\n    brandes_shortest_paths(weight_type delta) \r\n      : weight(1), delta(delta)  { }\r\n    brandes_shortest_paths(WeightMap w) \r\n      : weight(w), delta(0)  { }\r\n    brandes_shortest_paths(WeightMap w, weight_type delta) \r\n      : weight(w), delta(delta)  { }\r\n\r\n    template<typename Graph, typename IncomingMap, typename DistanceMap,\r\n             typename PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n             , typename IsSettledMap, typename VertexIndexMap\r\n#endif\r\n\r\n             > \r\n    void \r\n    operator()(Graph& g, \r\n               typename graph_traits<Graph>::vertex_descriptor s,\r\n               IncomingMap incoming,\r\n               DistanceMap distance,\r\n               PathCountMap path_count\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n               , IsSettledMap is_settled,\r\n               VertexIndexMap vertex_index \r\n#endif\r\n               )\r\n    {  \r\n      typedef typename property_traits<DistanceMap>::value_type \r\n        distance_type;\r\n\r\n      typedef std::plus<distance_type> Combine;\r\n      typedef std::less<distance_type> Compare;\r\n\r\n      // The \"distance\" map needs to act like one, retrieving the default\r\n      // value of infinity.\r\n      set_property_map_role(vertex_distance, distance);\r\n      \r\n      // Only calculate delta the first time operator() is called\r\n      // This presumes g is the same every time, but so does the fact\r\n      // that we're reusing the weight map\r\n      if (delta == 0)\r\n        set_delta(g);\r\n      \r\n      // TODO (NGE): Restructure the code so we don't have to construct\r\n      //             impl every time?\r\n      betweenness_centrality_delta_stepping_impl<\r\n          Graph, DistanceMap, IncomingMap, WeightMap, PathCountMap\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n          , IsSettledMap, VertexIndexMap\r\n#endif\r\n            >\r\n        impl(g, distance, incoming, weight, path_count, \r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n             is_settled, vertex_index, \r\n#endif\r\n             delta);\r\n\r\n      impl.run(s);\r\n    }\r\n\r\n  private:\r\n\r\n    template <typename Graph>\r\n    void\r\n    set_delta(const Graph& g)\r\n    {\r\n      using boost::parallel::all_reduce;\r\n      using boost::parallel::maximum;\r\n      using std::max;\r\n\r\n      typedef typename graph_traits<Graph>::degree_size_type Degree;\r\n      typedef weight_type Dist;\r\n\r\n      // Compute the maximum edge weight and degree\r\n      Dist max_edge_weight = 0;\r\n      Degree max_degree = 0;\r\n      BGL_FORALL_VERTICES_T(u, g, Graph) {\r\n        max_degree = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_degree, out_degree(u, g));\r\n        BGL_FORALL_OUTEDGES_T(u, e, g, Graph)\r\n          max_edge_weight = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_edge_weight, get(weight, e));\r\n      }\r\n      \r\n      max_edge_weight = all_reduce(process_group(g), max_edge_weight, maximum<Dist>());\r\n      max_degree = all_reduce(process_group(g), max_degree, maximum<Degree>());\r\n      \r\n      // Take a guess at delta, based on what works well for random\r\n      // graphs.\r\n      delta = max_edge_weight / max_degree;\r\n      if (delta == 0)\r\n        delta = 1;\r\n    }\r\n\r\n    WeightMap     weight;\r\n    weight_type   delta;\r\n  };\r\n\r\n  // Perform a single SSSP from the specified vertex and update the centrality map(s)\r\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\r\n           typename IncomingMap, typename DistanceMap, typename DependencyMap, \r\n           typename PathCountMap, \r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n           typename IsSettledMap,\r\n#endif \r\n           typename VertexIndexMap, typename ShortestPaths> \r\n  void\r\n  do_brandes_sssp(const Graph& g, \r\n                  CentralityMap centrality,     \r\n                  EdgeCentralityMap edge_centrality_map,\r\n                  IncomingMap incoming,\r\n                  DistanceMap distance,\r\n                  DependencyMap dependency,\r\n                  PathCountMap path_count, \r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n                  IsSettledMap is_settled,\r\n#endif \r\n                  VertexIndexMap vertex_index,\r\n                  ShortestPaths shortest_paths,\r\n                  typename graph_traits<Graph>::vertex_descriptor s)\r\n  {\r\n    using boost::detail::graph::update_centrality;      \r\n    using boost::graph::parallel::process_group;\r\n\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\r\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\r\n\r\n    typedef typename property_traits<IncomingMap>::value_type incoming_type;\r\n    typedef typename property_traits<DistanceMap>::value_type distance_type;\r\n    typedef typename property_traits<DependencyMap>::value_type dependency_type;\r\n    typedef typename property_traits<PathCountMap>::value_type path_count_type;\r\n\r\n    typedef typename incoming_type::iterator incoming_iterator;\r\n\r\n    typedef typename property_map<Graph, vertex_owner_t>::const_type OwnerMap;\r\n    OwnerMap owner = get(vertex_owner, g);\r\n\r\n    typedef typename boost::graph::parallel::process_group_type<Graph>::type \r\n      process_group_type;\r\n    process_group_type pg = process_group(g);\r\n    typename process_group_type::process_id_type id = process_id(pg);\r\n\r\n    // TODO: Is it faster not to clear some of these maps?\r\n    // Initialize for this iteration\r\n    distance.clear();\r\n    incoming.clear();\r\n    path_count.clear();\r\n    dependency.clear();\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      put(path_count, v, 0);\r\n      put(dependency, v, 0);\r\n    }\r\n\r\n    if (get(owner, s) == id) {\r\n      put(incoming, s, incoming_type());\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n      put(path_count, s, 1);\r\n      put(is_settled, s, true);\r\n#endif\r\n    }\r\n\r\n    // Execute the shortest paths algorithm. This will be either\r\n    // a weighted or unweighted customized breadth-first search,\r\n    shortest_paths(g, s, incoming, distance, path_count\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n                   , is_settled, vertex_index\r\n#endif \r\n                   );\r\n\r\n#ifndef COMPUTE_PATH_COUNTS_INLINE\r\n\r\n    //\r\n    // TODO: Optimize case where source has no out-edges\r\n    //\r\n \r\n    // Count of incoming edges to tell when all incoming edges have been relaxed in \r\n    // the induced shortest paths DAG \r\n    std::vector<edges_size_type> incoming_edge_countS(num_vertices(g));\r\n    iterator_property_map<typename std::vector<edges_size_type>::iterator, VertexIndexMap> \r\n      incoming_edge_count(incoming_edge_countS.begin(), vertex_index);\r\n\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      put(incoming_edge_count, v, get(incoming, v).size());\r\n    }\r\n\r\n    if (get(owner, s) == id) {\r\n      put(incoming_edge_count, s, 1);\r\n      put(incoming, s, incoming_type());\r\n    }\r\n\r\n    std::vector<incoming_type> outgoingS(num_vertices(g));\r\n    iterator_property_map<typename std::vector<incoming_type>::iterator, VertexIndexMap> \r\n      outgoing(outgoingS.begin(), vertex_index);\r\n\r\n    outgoing.set_reduce(append_reducer<incoming_type>());\r\n\r\n    // Mark forward adjacencies in DAG of shortest paths\r\n\r\n    // TODO: It's possible to do this using edge flags but it's not currently done this way\r\n    //       because during traversal of the DAG we would have to examine all out edges\r\n    //       which would lead to more memory accesses and a larger cache footprint.\r\n    //\r\n    //       In the bidirectional graph case edge flags would be an excellent way of marking\r\n    //       edges in the DAG of shortest paths  \r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      incoming_type i = get(incoming, v);\r\n      for (typename incoming_type::iterator iter = i.begin(); iter != i.end(); ++iter) {\r\n        if (get(owner, *iter) == id) {\r\n          incoming_type x = get(outgoing, *iter);\r\n          if (std::find(x.begin(), x.end(), v) == x.end())\r\n            x.push_back(v);\r\n          put(outgoing, *iter, x);\r\n        } else {\r\n          incoming_type in;\r\n          in.push_back(v);\r\n          put(outgoing, *iter, in);\r\n        }\r\n      }\r\n    }\r\n\r\n    synchronize(pg);\r\n\r\n    // Traverse DAG induced by forward edges in dependency order and compute path counts\r\n    {\r\n      typedef std::pair<vertex_descriptor, path_count_type> queue_value_type;\r\n      typedef get_owner_of_first_pair_element<OwnerMap> IndirectOwnerMap;\r\n\r\n      typedef boost::queue<queue_value_type> local_queue_type;\r\n      typedef boost::graph::distributed::distributed_queue<process_group_type,\r\n                                                           IndirectOwnerMap,\r\n                                                           local_queue_type> dist_queue_type;\r\n\r\n      IndirectOwnerMap indirect_owner(owner);\r\n      dist_queue_type Q(pg, indirect_owner);\r\n\r\n      if (get(owner, s) == id)\r\n        Q.push(std::make_pair(s, 1));\r\n\r\n      while (!Q.empty()) {\r\n        queue_value_type t = Q.top(); Q.pop();\r\n        vertex_descriptor v = t.first;\r\n        path_count_type p = t.second;\r\n\r\n        put(path_count, v, get(path_count, v) + p);\r\n        put(incoming_edge_count, v, get(incoming_edge_count, v) - 1);\r\n\r\n        if (get(incoming_edge_count, v) == 0) {\r\n          incoming_type out = get(outgoing, v);\r\n          for (typename incoming_type::iterator iter = out.begin(); iter != out.end(); ++iter)\r\n            Q.push(std::make_pair(*iter, get(path_count, v)));\r\n        }\r\n      }\r\n    }\r\n\r\n#endif // COMPUTE_PATH_COUNTS_INLINE\r\n\r\n    //\r\n    // Compute dependencies \r\n    //    \r\n\r\n\r\n    // Build the distributed_queue\r\n    // Value type consists of 1) target of update 2) source of update\r\n    // 3) dependency of source 4) path count of source\r\n    typedef boost::tuple<vertex_descriptor, vertex_descriptor, dependency_type, path_count_type>\r\n      queue_value_type;\r\n    typedef get_owner_of_first_tuple_element<OwnerMap, queue_value_type> IndirectOwnerMap;\r\n\r\n    typedef boost::queue<queue_value_type> local_queue_type;\r\n    typedef boost::graph::distributed::distributed_queue<process_group_type,\r\n                                                         IndirectOwnerMap,\r\n                                                         local_queue_type> dist_queue_type;\r\n\r\n    IndirectOwnerMap indirect_owner(owner);\r\n    dist_queue_type Q(pg, indirect_owner);\r\n\r\n    // Calculate number of vertices each vertex depends on, when a vertex has been pushed\r\n    // that number of times then we will update it\r\n    // AND Request path counts of sources of incoming edges\r\n    std::vector<dependency_type> dependency_countS(num_vertices(g), 0);\r\n    iterator_property_map<typename std::vector<dependency_type>::iterator, VertexIndexMap> \r\n      dependency_count(dependency_countS.begin(), vertex_index);\r\n\r\n    dependency_count.set_reduce(boost::graph::distributed::additive_reducer<dependency_type>());\r\n\r\n    path_count.set_max_ghost_cells(0);\r\n\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      if (get(distance, v) < (std::numeric_limits<distance_type>::max)()) {\r\n        incoming_type el = get(incoming, v);\r\n        for (incoming_iterator vw = el.begin(); vw != el.end(); ++vw) {\r\n          if (get(owner, *vw) == id)\r\n            put(dependency_count, *vw, get(dependency_count, *vw) + 1);\r\n          else {\r\n            put(dependency_count, *vw, 1);\r\n\r\n            // Request path counts\r\n            get(path_count, *vw); \r\n          }\r\n\r\n          // request() doesn't work here, perhaps because we don't have a copy of this \r\n          // ghost cell already?\r\n        }\r\n      }\r\n    }\r\n\r\n    synchronize(pg);\r\n\r\n    // Push vertices with non-zero distance/path count and zero dependency count\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      if (get(distance, v) < (std::numeric_limits<distance_type>::max)()\r\n          && get(dependency_count, v) == 0) \r\n        Q.push(boost::make_tuple(v, v, get(dependency, v), get(path_count, v)));\r\n    }\r\n\r\n    dependency.set_max_ghost_cells(0);\r\n    while(!Q.empty()) {\r\n\r\n      queue_value_type x = Q.top(); Q.pop();\r\n      vertex_descriptor w = boost::tuples::get<0>(x);\r\n      vertex_descriptor source = boost::tuples::get<1>(x);\r\n      dependency_type dep = boost::tuples::get<2>(x);\r\n      path_count_type pc = boost::tuples::get<3>(x);\r\n\r\n      cache(dependency, source, dep);\r\n      cache(path_count, source, pc);\r\n\r\n      if (get(dependency_count, w) != 0)\r\n        put(dependency_count, w, get(dependency_count, w) - 1);\r\n\r\n      if (get(dependency_count, w) == 0) { \r\n\r\n        // Update dependency and centrality of sources of incoming edges\r\n        incoming_type el = get(incoming, w);\r\n        for (incoming_iterator vw = el.begin(); vw != el.end(); ++vw) {\r\n          vertex_descriptor v = *vw;\r\n\r\n          assert(get(path_count, w) != 0);\r\n\r\n          dependency_type factor = dependency_type(get(path_count, v))\r\n            / dependency_type(get(path_count, w));\r\n          factor *= (dependency_type(1) + get(dependency, w));\r\n          \r\n          if (get(owner, v) == id)\r\n            put(dependency, v, get(dependency, v) + factor);\r\n          else\r\n            put(dependency, v, factor);\r\n          \r\n          update_centrality(edge_centrality_map, v, factor);\r\n        }\r\n        \r\n        if (w != s)\r\n          update_centrality(centrality, w, get(dependency, w));\r\n\r\n        // Push sources of edges in incoming edge list\r\n        for (incoming_iterator vw = el.begin(); vw != el.end(); ++vw)\r\n          Q.push(boost::make_tuple(*vw, w, get(dependency, w), get(path_count, w)));\r\n      }\r\n    }\r\n  }\r\n\r\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\r\n           typename IncomingMap, typename DistanceMap, typename DependencyMap, \r\n           typename PathCountMap, typename VertexIndexMap, typename ShortestPaths, \r\n           typename Buffer>\r\n  void \r\n  brandes_betweenness_centrality_impl(const Graph& g, \r\n                                      CentralityMap centrality,     \r\n                                      EdgeCentralityMap edge_centrality_map,\r\n                                      IncomingMap incoming,\r\n                                      DistanceMap distance,\r\n                                      DependencyMap dependency,\r\n                                      PathCountMap path_count, \r\n                                      VertexIndexMap vertex_index,\r\n                                      ShortestPaths shortest_paths,\r\n                                      Buffer sources)\r\n  {\r\n    using boost::detail::graph::init_centrality_map;\r\n    using boost::detail::graph::divide_centrality_by_two;       \r\n    using boost::graph::parallel::process_group;\r\n    \r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\r\n    typedef typename graph_traits<Graph>::edge_iterator edge_iterator;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\r\n\r\n    typedef typename property_traits<DistanceMap>::value_type distance_type;\r\n    typedef typename property_traits<DependencyMap>::value_type dependency_type;\r\n\r\n    // Initialize centrality\r\n    init_centrality_map(vertices(g), centrality);\r\n    init_centrality_map(edges(g), edge_centrality_map);\r\n\r\n    // Set the reduction operation on the dependency map to be addition\r\n    dependency.set_reduce(boost::graph::distributed::additive_reducer<dependency_type>()); \r\n    distance.set_reduce(boost::graph::distributed::choose_min_reducer<distance_type>());\r\n\r\n    // Don't allow remote procs to write incoming or path_count maps\r\n    // updating them is handled inside the betweenness_centrality_queue\r\n    incoming.set_consistency_model(0);\r\n    path_count.set_consistency_model(0);\r\n\r\n    typedef typename boost::graph::parallel::process_group_type<Graph>::type \r\n      process_group_type;\r\n    process_group_type pg = process_group(g);\r\n\r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n    // Build is_settled maps\r\n    std::vector<bool> is_settledS(num_vertices(g));\r\n    typedef iterator_property_map<std::vector<bool>::iterator, VertexIndexMap> \r\n      IsSettledMap;\r\n\r\n    IsSettledMap is_settled(is_settledS.begin(), vertex_index);\r\n#endif\r\n\r\n    if (!sources.empty()) {\r\n      // DO SSSPs\r\n      while (!sources.empty()) {\r\n        do_brandes_sssp(g, centrality, edge_centrality_map, incoming, distance,\r\n                        dependency, path_count, \r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n                        is_settled,\r\n#endif \r\n                        vertex_index, shortest_paths, sources.top());\r\n        sources.pop();\r\n      }\r\n    } else { // Exact Betweenness Centrality\r\n      typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\r\n      vertices_size_type n = num_vertices(g);\r\n      n = boost::parallel::all_reduce(pg, n, std::plus<vertices_size_type>());\r\n      \r\n      for (vertices_size_type i = 0; i < n; ++i) {\r\n        vertex_descriptor v = vertex(i, g);\r\n\r\n        do_brandes_sssp(g, centrality, edge_centrality_map, incoming, distance,\r\n                        dependency, path_count, \r\n#ifdef COMPUTE_PATH_COUNTS_INLINE\r\n                        is_settled,\r\n#endif \r\n                        vertex_index, shortest_paths, v);\r\n      }\r\n    }\r\n\r\n    typedef typename graph_traits<Graph>::directed_category directed_category;\r\n    const bool is_undirected = \r\n      is_convertible<directed_category*, undirected_tag*>::value;\r\n    if (is_undirected) {\r\n      divide_centrality_by_two(vertices(g), centrality);\r\n      divide_centrality_by_two(edges(g), edge_centrality_map);\r\n    }\r\n  }\r\n\r\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\r\n           typename IncomingMap, typename DistanceMap, typename DependencyMap, \r\n           typename PathCountMap, typename VertexIndexMap, typename ShortestPaths,\r\n           typename Stack>\r\n  void\r\n  do_sequential_brandes_sssp(const Graph& g, \r\n                             CentralityMap centrality,     \r\n                             EdgeCentralityMap edge_centrality_map,\r\n                             IncomingMap incoming,\r\n                             DistanceMap distance,\r\n                             DependencyMap dependency,\r\n                             PathCountMap path_count, \r\n                             VertexIndexMap vertex_index,\r\n                             ShortestPaths shortest_paths,\r\n                             Stack& ordered_vertices,\r\n                             typename graph_traits<Graph>::vertex_descriptor v)\r\n  {\r\n    using boost::detail::graph::update_centrality;\r\n\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n\r\n    typedef typename property_traits<IncomingMap>::value_type incoming_type;\r\n\r\n    // Initialize for this iteration\r\n    BGL_FORALL_VERTICES_T(w, g, Graph) {\r\n      // put(path_count, w, 0);\r\n      incoming[w].clear();\r\n      put(dependency, w, 0);\r\n    }\r\n\r\n    put(path_count, v, 1);\r\n    incoming[v].clear();\r\n\r\n    // Execute the shortest paths algorithm. This will be either\r\n    // Dijkstra's algorithm or a customized breadth-first search,\r\n    // depending on whether the graph is weighted or unweighted.\r\n    shortest_paths(g, v, ordered_vertices, incoming, distance,\r\n                   path_count, vertex_index);\r\n    \r\n    while (!ordered_vertices.empty()) {\r\n      vertex_descriptor w = ordered_vertices.top();\r\n      ordered_vertices.pop();\r\n      \r\n      typedef typename property_traits<IncomingMap>::value_type\r\n            incoming_type;\r\n      typedef typename incoming_type::iterator incoming_iterator;\r\n      typedef typename property_traits<DependencyMap>::value_type \r\n        dependency_type;\r\n      \r\n      for (incoming_iterator vw = incoming[w].begin();\r\n           vw != incoming[w].end(); ++vw) {\r\n        vertex_descriptor v = source(*vw, g);\r\n        dependency_type factor = dependency_type(get(path_count, v))\r\n          / dependency_type(get(path_count, w));\r\n        factor *= (dependency_type(1) + get(dependency, w));\r\n        put(dependency, v, get(dependency, v) + factor);\r\n        update_centrality(edge_centrality_map, *vw, factor);\r\n      }\r\n      \r\n      if (w != v) {\r\n        update_centrality(centrality, w, get(dependency, w));\r\n      }\r\n    }\r\n  }\r\n\r\n  // Betweenness Centrality variant that duplicates graph across processors\r\n  // and parallizes SSSPs\r\n  // This function expects a non-distributed graph and property-maps\r\n  template<typename ProcessGroup, typename Graph, \r\n           typename CentralityMap, typename EdgeCentralityMap,\r\n           typename IncomingMap, typename DistanceMap, \r\n           typename DependencyMap, typename PathCountMap,\r\n           typename VertexIndexMap, typename ShortestPaths,\r\n           typename Buffer>\r\n  void\r\n  non_distributed_brandes_betweenness_centrality_impl(const ProcessGroup& pg,\r\n                                                      const Graph& g,\r\n                                                      CentralityMap centrality,\r\n                                                      EdgeCentralityMap edge_centrality_map,\r\n                                                      IncomingMap incoming, // P\r\n                                                      DistanceMap distance,         // d\r\n                                                      DependencyMap dependency,     // delta\r\n                                                      PathCountMap path_count,      // sigma\r\n                                                      VertexIndexMap vertex_index,\r\n                                                      ShortestPaths shortest_paths,\r\n                                                      Buffer sources)\r\n  {\r\n    using boost::detail::graph::init_centrality_map;\r\n    using boost::detail::graph::divide_centrality_by_two;       \r\n    using boost::graph::parallel::process_group;\r\n\r\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\r\n    typedef typename graph_traits<Graph>::edge_iterator edge_iterator;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\r\n\r\n    typedef typename property_traits<DistanceMap>::value_type distance_type;\r\n\r\n    typedef ProcessGroup process_group_type;\r\n\r\n    typename process_group_type::process_id_type id = process_id(pg);\r\n    typename process_group_type::process_size_type p = num_processes(pg);\r\n\r\n    // Initialize centrality\r\n    init_centrality_map(vertices(g), centrality);\r\n    init_centrality_map(edges(g), edge_centrality_map);\r\n\r\n    std::stack<vertex_descriptor> ordered_vertices;\r\n\r\n    if (!sources.empty()) {\r\n      std::vector<vertex_descriptor> local_sources;\r\n\r\n      for (int i = 0; i < id; ++i) if (!sources.empty()) sources.pop();\r\n      while (!sources.empty()) {\r\n        local_sources.push_back(sources.top());\r\n\r\n        for (int i = 0; i < p; ++i) if (!sources.empty()) sources.pop();\r\n      }\r\n\r\n      // DO SSSPs\r\n      for(size_t i = 0; i < local_sources.size(); ++i)\r\n        do_sequential_brandes_sssp(g, centrality, edge_centrality_map, incoming,\r\n                                   distance, dependency, path_count, vertex_index,\r\n                                   shortest_paths, ordered_vertices, local_sources[i]);\r\n\r\n    } else { // Exact Betweenness Centrality\r\n      typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\r\n      vertices_size_type n = num_vertices(g);\r\n      \r\n      for (vertices_size_type i = id; i < n; i += p) {\r\n        vertex_descriptor v = vertex(i, g);\r\n\r\n        do_sequential_brandes_sssp(g, centrality, edge_centrality_map, incoming,\r\n                                   distance, dependency, path_count, vertex_index,\r\n                                   shortest_paths, ordered_vertices, v);\r\n      }\r\n    }\r\n\r\n    typedef typename graph_traits<Graph>::directed_category directed_category;\r\n    const bool is_undirected = \r\n      is_convertible<directed_category*, undirected_tag*>::value;\r\n    if (is_undirected) {\r\n      divide_centrality_by_two(vertices(g), centrality);\r\n      divide_centrality_by_two(edges(g), edge_centrality_map);\r\n    }\r\n\r\n    // Merge the centrality maps by summing the values at each vertex)\r\n    // TODO(nge): this copy-out, reduce, copy-in is lame\r\n    typedef typename property_traits<CentralityMap>::value_type centrality_type;\r\n    typedef typename property_traits<EdgeCentralityMap>::value_type edge_centrality_type;\r\n\r\n    std::vector<centrality_type> centrality_v(num_vertices(g));\r\n    std::vector<edge_centrality_type> edge_centrality_v;\r\n    edge_centrality_v.reserve(num_edges(g));\r\n\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      centrality_v[get(vertex_index, v)] = get(centrality, v);\r\n    }\r\n    \r\n    // Skip when EdgeCentralityMap is a dummy_property_map\r\n    if (!is_same<EdgeCentralityMap, dummy_property_map>::value) {\r\n      BGL_FORALL_EDGES_T(e, g, Graph) {\r\n        edge_centrality_v.push_back(get(edge_centrality_map, e));\r\n      }\r\n      // NGE: If we trust that the order of elements in the vector isn't changed in the\r\n      //      all_reduce below then this method avoids the need for an edge index map\r\n    }\r\n\r\n    using boost::parallel::all_reduce;\r\n\r\n    all_reduce(pg, &centrality_v[0], &centrality_v[centrality_v.size()],\r\n               &centrality_v[0], std::plus<centrality_type>());\r\n\r\n    if (edge_centrality_v.size()) \r\n      all_reduce(pg, &edge_centrality_v[0], &edge_centrality_v[edge_centrality_v.size()],\r\n                 &edge_centrality_v[0], std::plus<edge_centrality_type>());\r\n\r\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n      put(centrality, v, centrality_v[get(vertex_index, v)]);\r\n    }\r\n\r\n    // Skip when EdgeCentralityMap is a dummy_property_map\r\n    if (!is_same<EdgeCentralityMap, dummy_property_map>::value) {\r\n      int i = 0;\r\n      BGL_FORALL_EDGES_T(e, g, Graph) {\r\n        put(edge_centrality_map, e, edge_centrality_v[i]);\r\n        ++i;\r\n      }\r\n    }\r\n  }\r\n\r\n} } } // end namespace graph::parallel::detail\r\n\r\ntemplate<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\r\n         typename IncomingMap, typename DistanceMap, typename DependencyMap, \r\n         typename PathCountMap, typename VertexIndexMap, typename Buffer>\r\nvoid \r\nbrandes_betweenness_centrality(const Graph& g, \r\n                               CentralityMap centrality,\r\n                               EdgeCentralityMap edge_centrality_map,\r\n                               IncomingMap incoming, \r\n                               DistanceMap distance, \r\n                               DependencyMap dependency,     \r\n                               PathCountMap path_count,   \r\n                               VertexIndexMap vertex_index,\r\n                               Buffer sources,\r\n                               typename property_traits<DistanceMap>::value_type delta\r\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,distributed_graph_tag))\r\n{\r\n  typedef typename property_traits<DistanceMap>::value_type distance_type;\r\n  typedef static_property_map<distance_type> WeightMap;\r\n\r\n  graph::parallel::detail::brandes_shortest_paths<WeightMap> \r\n    shortest_paths(delta);\r\n\r\n  graph::parallel::detail::brandes_betweenness_centrality_impl(g, centrality, \r\n                                                               edge_centrality_map,\r\n                                                               incoming, distance,\r\n                                                               dependency, path_count,\r\n                                                               vertex_index, \r\n                                                               shortest_paths,\r\n                                                               sources);\r\n}\r\n\r\ntemplate<typename Graph, typename CentralityMap, typename EdgeCentralityMap, \r\n         typename IncomingMap, typename DistanceMap, typename DependencyMap, \r\n         typename PathCountMap, typename VertexIndexMap, typename WeightMap, \r\n         typename Buffer>    \r\nvoid \r\nbrandes_betweenness_centrality(const Graph& g, \r\n                               CentralityMap centrality,\r\n                               EdgeCentralityMap edge_centrality_map,\r\n                               IncomingMap incoming, \r\n                               DistanceMap distance, \r\n                               DependencyMap dependency,\r\n                               PathCountMap path_count, \r\n                               VertexIndexMap vertex_index,\r\n                               Buffer sources,\r\n                               typename property_traits<WeightMap>::value_type delta,\r\n                               WeightMap weight_map\r\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,distributed_graph_tag))\r\n{\r\n  graph::parallel::detail::brandes_shortest_paths<WeightMap> shortest_paths(weight_map, delta);\r\n\r\n  graph::parallel::detail::brandes_betweenness_centrality_impl(g, centrality, \r\n                                                               edge_centrality_map,\r\n                                                               incoming, distance,\r\n                                                               dependency, path_count,\r\n                                                               vertex_index, \r\n                                                               shortest_paths,\r\n                                                               sources);\r\n}\r\n\r\nnamespace graph { namespace parallel { namespace detail {\r\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\r\n           typename WeightMap, typename VertexIndexMap, typename Buffer>\r\n  void \r\n  brandes_betweenness_centrality_dispatch2(const Graph& g,\r\n                                           CentralityMap centrality,\r\n                                           EdgeCentralityMap edge_centrality_map,\r\n                                           WeightMap weight_map,\r\n                                           VertexIndexMap vertex_index,\r\n                                           Buffer sources,\r\n                                           typename property_traits<WeightMap>::value_type delta)\r\n  {\r\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename mpl::if_c<(is_same<CentralityMap, \r\n                                        dummy_property_map>::value),\r\n                                         EdgeCentralityMap, \r\n                               CentralityMap>::type a_centrality_map;\r\n    typedef typename property_traits<a_centrality_map>::value_type \r\n      centrality_type;\r\n\r\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\r\n\r\n    std::vector<std::vector<vertex_descriptor> > incoming(V);\r\n    std::vector<centrality_type> distance(V);\r\n    std::vector<centrality_type> dependency(V);\r\n    std::vector<degree_size_type> path_count(V);\r\n\r\n    brandes_betweenness_centrality(\r\n      g, centrality, edge_centrality_map,\r\n      make_iterator_property_map(incoming.begin(), vertex_index),\r\n      make_iterator_property_map(distance.begin(), vertex_index),\r\n      make_iterator_property_map(dependency.begin(), vertex_index),\r\n      make_iterator_property_map(path_count.begin(), vertex_index),\r\n      vertex_index, unwrap_ref(sources), delta,\r\n      weight_map);\r\n  }\r\n  \r\n  // TODO: Should the type of the distance and dependency map depend on the \r\n  //       value type of the centrality map?\r\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\r\n           typename VertexIndexMap, typename Buffer>\r\n  void \r\n  brandes_betweenness_centrality_dispatch2(const Graph& g,\r\n                                           CentralityMap centrality,\r\n                                           EdgeCentralityMap edge_centrality_map,\r\n                                           VertexIndexMap vertex_index,\r\n                                           Buffer sources,\r\n                                           typename graph_traits<Graph>::edges_size_type delta)\r\n  {\r\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\r\n    typedef typename graph_traits<Graph>::edges_size_type edges_size_type;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename mpl::if_c<(is_same<CentralityMap, \r\n                                        dummy_property_map>::value),\r\n                                         EdgeCentralityMap, \r\n                               CentralityMap>::type a_centrality_map;\r\n\r\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\r\n    \r\n    std::vector<std::vector<vertex_descriptor> > incoming(V);\r\n    std::vector<edges_size_type> distance(V);\r\n    std::vector<edges_size_type> dependency(V);\r\n    std::vector<degree_size_type> path_count(V);\r\n\r\n    brandes_betweenness_centrality(\r\n      g, centrality, edge_centrality_map,\r\n      make_iterator_property_map(incoming.begin(), vertex_index),\r\n      make_iterator_property_map(distance.begin(), vertex_index),\r\n      make_iterator_property_map(dependency.begin(), vertex_index),\r\n      make_iterator_property_map(path_count.begin(), vertex_index),\r\n      vertex_index, unwrap_ref(sources), delta); \r\n  }\r\n\r\n  template<typename WeightMap>\r\n  struct brandes_betweenness_centrality_dispatch1\r\n  {\r\n    template<typename Graph, typename CentralityMap, typename EdgeCentralityMap, \r\n             typename VertexIndexMap, typename Buffer>\r\n    static void \r\n    run(const Graph& g, CentralityMap centrality, EdgeCentralityMap edge_centrality_map, \r\n        VertexIndexMap vertex_index, Buffer sources,\r\n        typename property_traits<WeightMap>::value_type delta, WeightMap weight_map) \r\n    {\r\n      boost::graph::parallel::detail::brandes_betweenness_centrality_dispatch2(\r\n       g, centrality, edge_centrality_map, weight_map, vertex_index, sources, delta);\r\n    }\r\n  };\r\n\r\n  template<>\r\n  struct brandes_betweenness_centrality_dispatch1<boost::detail::error_property_not_found> \r\n  {\r\n    template<typename Graph, typename CentralityMap, typename EdgeCentralityMap, \r\n             typename VertexIndexMap, typename Buffer>\r\n    static void \r\n    run(const Graph& g, CentralityMap centrality, EdgeCentralityMap edge_centrality_map, \r\n        VertexIndexMap vertex_index, Buffer sources,\r\n        typename graph_traits<Graph>::edges_size_type delta,\r\n        boost::detail::error_property_not_found)\r\n    {\r\n      boost::graph::parallel::detail::brandes_betweenness_centrality_dispatch2(\r\n       g, centrality, edge_centrality_map, vertex_index, sources, delta);\r\n    }\r\n  };\r\n\r\n} } } // end namespace graph::parallel::detail\r\n\r\ntemplate<typename Graph, typename Param, typename Tag, typename Rest>\r\nvoid \r\nbrandes_betweenness_centrality(const Graph& g, \r\n                               const bgl_named_params<Param,Tag,Rest>& params\r\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,distributed_graph_tag))\r\n{\r\n  typedef bgl_named_params<Param,Tag,Rest> named_params;\r\n\r\n  typedef queue<typename graph_traits<Graph>::vertex_descriptor> queue_t;\r\n  queue_t q;\r\n\r\n  typedef typename property_value<named_params, edge_weight_t>::type ew;\r\n  graph::parallel::detail::brandes_betweenness_centrality_dispatch1<ew>::run(\r\n    g, \r\n    choose_param(get_param(params, vertex_centrality), \r\n                 dummy_property_map()),\r\n    choose_param(get_param(params, edge_centrality), \r\n                 dummy_property_map()),\r\n    choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n    choose_param(get_param(params, buffer_param_t()), boost::ref(q)),\r\n    choose_param(get_param(params, lookahead_t()), 0),\r\n    get_param(params, edge_weight));\r\n}\r\n\r\ntemplate<typename Graph, typename CentralityMap>\r\nvoid \r\nbrandes_betweenness_centrality(const Graph& g, CentralityMap centrality\r\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,distributed_graph_tag))\r\n{\r\n  typedef queue<typename graph_traits<Graph>::vertex_descriptor> queue_t;\r\n  queue_t q;\r\n\r\n  boost::graph::parallel::detail::brandes_betweenness_centrality_dispatch2(\r\n    g, centrality, dummy_property_map(), get(vertex_index, g), boost::ref(q), 0);\r\n}\r\n\r\ntemplate<typename Graph, typename CentralityMap, typename EdgeCentralityMap>\r\nvoid \r\nbrandes_betweenness_centrality(const Graph& g, CentralityMap centrality,\r\n                               EdgeCentralityMap edge_centrality_map\r\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,distributed_graph_tag))\r\n{\r\n  typedef queue<int> queue_t;\r\n  queue_t q;\r\n\r\n  boost::graph::parallel::detail::brandes_betweenness_centrality_dispatch2(\r\n    g, centrality, edge_centrality_map, get(vertex_index, g), boost::ref(q), 0);\r\n}\r\n  \r\ntemplate<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n         typename EdgeCentralityMap, typename IncomingMap, typename DistanceMap, \r\n         typename DependencyMap, typename PathCountMap, typename VertexIndexMap, \r\n         typename Buffer>\r\nvoid \r\nnon_distributed_brandes_betweenness_centrality(const ProcessGroup& pg,\r\n                                               const Graph& g, \r\n                                               CentralityMap centrality,\r\n                                               EdgeCentralityMap edge_centrality_map,\r\n                                               IncomingMap incoming, \r\n                                               DistanceMap distance, \r\n                                               DependencyMap dependency,     \r\n                                               PathCountMap path_count,      \r\n                                               VertexIndexMap vertex_index,\r\n                                               Buffer sources)\r\n{\r\n  typedef typename property_traits<DistanceMap>::value_type distance_type;\r\n  typedef static_property_map<distance_type> WeightMap;\r\n  \r\n  detail::graph::brandes_unweighted_shortest_paths shortest_paths;\r\n  \r\n  graph::parallel::detail::non_distributed_brandes_betweenness_centrality_impl(pg, g, centrality, \r\n                                                                               edge_centrality_map,\r\n                                                                               incoming, distance,\r\n                                                                               dependency, path_count,\r\n                                                                               vertex_index, \r\n                                                                               shortest_paths,\r\n                                                                               sources);\r\n}\r\n  \r\ntemplate<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n         typename EdgeCentralityMap, typename IncomingMap, typename DistanceMap, \r\n         typename DependencyMap, typename PathCountMap, typename VertexIndexMap, \r\n         typename WeightMap, typename Buffer>\r\nvoid \r\nnon_distributed_brandes_betweenness_centrality(const ProcessGroup& pg,\r\n                                               const Graph& g, \r\n                                               CentralityMap centrality,\r\n                                               EdgeCentralityMap edge_centrality_map,\r\n                                               IncomingMap incoming, \r\n                                               DistanceMap distance, \r\n                                               DependencyMap dependency,\r\n                                               PathCountMap path_count, \r\n                                               VertexIndexMap vertex_index,\r\n                                               WeightMap weight_map,\r\n                                               Buffer sources)\r\n{\r\n  detail::graph::brandes_dijkstra_shortest_paths<WeightMap> shortest_paths(weight_map);\r\n\r\n  graph::parallel::detail::non_distributed_brandes_betweenness_centrality_impl(pg, g, centrality, \r\n                                                                               edge_centrality_map,\r\n                                                                               incoming, distance,\r\n                                                                               dependency, path_count,\r\n                                                                               vertex_index, \r\n                                                                               shortest_paths,\r\n                                                                               sources);\r\n}\r\n\r\nnamespace detail { namespace graph {\r\n  template<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n           typename EdgeCentralityMap, typename WeightMap, typename VertexIndexMap,\r\n           typename Buffer>\r\n  void \r\n  non_distributed_brandes_betweenness_centrality_dispatch2(const ProcessGroup& pg,\r\n                                                           const Graph& g,\r\n                                                           CentralityMap centrality,\r\n                                                           EdgeCentralityMap edge_centrality_map,\r\n                                                           WeightMap weight_map,\r\n                                                           VertexIndexMap vertex_index,\r\n                                                           Buffer sources)\r\n  {\r\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n    typedef typename mpl::if_c<(is_same<CentralityMap, \r\n                                        dummy_property_map>::value),\r\n                                         EdgeCentralityMap, \r\n                               CentralityMap>::type a_centrality_map;\r\n    typedef typename property_traits<a_centrality_map>::value_type \r\n      centrality_type;\r\n\r\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\r\n    \r\n    std::vector<std::vector<edge_descriptor> > incoming(V);\r\n    std::vector<centrality_type> distance(V);\r\n    std::vector<centrality_type> dependency(V);\r\n    std::vector<degree_size_type> path_count(V);\r\n\r\n    non_distributed_brandes_betweenness_centrality(\r\n      pg, g, centrality, edge_centrality_map,\r\n      make_iterator_property_map(incoming.begin(), vertex_index),\r\n      make_iterator_property_map(distance.begin(), vertex_index),\r\n      make_iterator_property_map(dependency.begin(), vertex_index),\r\n      make_iterator_property_map(path_count.begin(), vertex_index),\r\n      vertex_index, weight_map, unwrap_ref(sources));\r\n  }\r\n  \r\n\r\n  template<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n           typename EdgeCentralityMap, typename VertexIndexMap, typename Buffer>\r\n  void \r\n  non_distributed_brandes_betweenness_centrality_dispatch2(const ProcessGroup& pg,\r\n                                                           const Graph& g,\r\n                                                           CentralityMap centrality,\r\n                                                           EdgeCentralityMap edge_centrality_map,\r\n                                                           VertexIndexMap vertex_index,\r\n                                                           Buffer sources)\r\n  {\r\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n    typedef typename mpl::if_c<(is_same<CentralityMap, \r\n                                        dummy_property_map>::value),\r\n                                         EdgeCentralityMap, \r\n                               CentralityMap>::type a_centrality_map;\r\n    typedef typename property_traits<a_centrality_map>::value_type \r\n      centrality_type;\r\n\r\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\r\n    \r\n    std::vector<std::vector<edge_descriptor> > incoming(V);\r\n    std::vector<centrality_type> distance(V);\r\n    std::vector<centrality_type> dependency(V);\r\n    std::vector<degree_size_type> path_count(V);\r\n\r\n    non_distributed_brandes_betweenness_centrality(\r\n      pg, g, centrality, edge_centrality_map,\r\n      make_iterator_property_map(incoming.begin(), vertex_index),\r\n      make_iterator_property_map(distance.begin(), vertex_index),\r\n      make_iterator_property_map(dependency.begin(), vertex_index),\r\n      make_iterator_property_map(path_count.begin(), vertex_index),\r\n      vertex_index, unwrap_ref(sources));\r\n  }\r\n\r\n  template<typename WeightMap>\r\n  struct non_distributed_brandes_betweenness_centrality_dispatch1\r\n  {\r\n    template<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n             typename EdgeCentralityMap, typename VertexIndexMap, typename Buffer>\r\n    static void \r\n    run(const ProcessGroup& pg, const Graph& g, CentralityMap centrality, \r\n        EdgeCentralityMap edge_centrality_map, VertexIndexMap vertex_index,\r\n        Buffer sources, WeightMap weight_map)\r\n    {\r\n      non_distributed_brandes_betweenness_centrality_dispatch2(pg, g, centrality, edge_centrality_map,\r\n                                                               weight_map, vertex_index, sources);\r\n    }\r\n  };\r\n\r\n  template<>\r\n  struct non_distributed_brandes_betweenness_centrality_dispatch1<detail::error_property_not_found>\r\n  {\r\n    template<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n             typename EdgeCentralityMap, typename VertexIndexMap, typename Buffer>\r\n    static void \r\n    run(const ProcessGroup& pg, const Graph& g, CentralityMap centrality, \r\n        EdgeCentralityMap edge_centrality_map, VertexIndexMap vertex_index,\r\n        Buffer sources, detail::error_property_not_found)\r\n    {\r\n      non_distributed_brandes_betweenness_centrality_dispatch2(pg, g, centrality, edge_centrality_map,\r\n                                                               vertex_index, sources);\r\n    }\r\n  };\r\n\r\n} } // end namespace detail::graph\r\n\r\ntemplate<typename ProcessGroup, typename Graph, typename Param, typename Tag, typename Rest>\r\nvoid \r\nnon_distributed_brandes_betweenness_centrality(const ProcessGroup& pg, const Graph& g, \r\n                                               const bgl_named_params<Param,Tag,Rest>& params)\r\n{\r\n  typedef bgl_named_params<Param,Tag,Rest> named_params;\r\n\r\n  typedef queue<int> queue_t;\r\n  queue_t q;\r\n\r\n  typedef typename property_value<named_params, edge_weight_t>::type ew;\r\n  detail::graph::non_distributed_brandes_betweenness_centrality_dispatch1<ew>::run(\r\n    pg, g, \r\n    choose_param(get_param(params, vertex_centrality), \r\n                 dummy_property_map()),\r\n    choose_param(get_param(params, edge_centrality), \r\n                 dummy_property_map()),\r\n    choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n    choose_param(get_param(params, buffer_param_t()),  boost::ref(q)),\r\n    get_param(params, edge_weight));\r\n}\r\n\r\ntemplate<typename ProcessGroup, typename Graph, typename CentralityMap>\r\nvoid \r\nnon_distributed_brandes_betweenness_centrality(const ProcessGroup& pg, const Graph& g, \r\n                                               CentralityMap centrality)\r\n{\r\n  typedef queue<int> queue_t;\r\n  queue_t q;\r\n\r\n  detail::graph::non_distributed_brandes_betweenness_centrality_dispatch2(\r\n    pg, g, centrality, dummy_property_map(), get(vertex_index, g), boost::ref(q));\r\n}\r\n\r\ntemplate<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n         typename Buffer>\r\nvoid \r\nnon_distributed_brandes_betweenness_centrality(const ProcessGroup& pg, const Graph& g, \r\n                                               CentralityMap centrality, Buffer sources)\r\n{\r\n  detail::graph::non_distributed_brandes_betweenness_centrality_dispatch2(\r\n    pg, g, centrality, dummy_property_map(), get(vertex_index, g), sources);\r\n}\r\n\r\ntemplate<typename ProcessGroup, typename Graph, typename CentralityMap, \r\n         typename EdgeCentralityMap, typename Buffer>\r\nvoid \r\nnon_distributed_brandes_betweenness_centrality(const ProcessGroup& pg, const Graph& g, \r\n                                               CentralityMap centrality,\r\n                                               EdgeCentralityMap edge_centrality_map, \r\n                                               Buffer sources)\r\n{\r\n  detail::graph::non_distributed_brandes_betweenness_centrality_dispatch2(\r\n    pg, g, centrality, edge_centrality_map, get(vertex_index, g), sources);\r\n}\r\n\r\n// Compute the central point dominance of a graph.\r\n// TODO: Make sure central point dominance works in parallel case\r\ntemplate<typename Graph, typename CentralityMap>\r\ntypename property_traits<CentralityMap>::value_type\r\ncentral_point_dominance(const Graph& g, CentralityMap centrality\r\n                        BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,distributed_graph_tag))\r\n{\r\n  using std::max;\r\n\r\n  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\r\n  typedef typename property_traits<CentralityMap>::value_type centrality_type;\r\n  typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\r\n\r\n  typedef typename boost::graph::parallel::process_group_type<Graph>::type \r\n    process_group_type;\r\n  process_group_type pg = boost::graph::parallel::process_group(g);\r\n\r\n  vertices_size_type n = num_vertices(g);\r\n\r\n  using boost::parallel::all_reduce;  \r\n  n = all_reduce(pg, n, std::plus<vertices_size_type>());\r\n\r\n  // Find max centrality\r\n  centrality_type max_centrality(0);\r\n  vertex_iterator v, v_end;\r\n  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {\r\n    max_centrality = (max)(max_centrality, get(centrality, *v));\r\n  }\r\n\r\n  // All reduce to get global max centrality\r\n  max_centrality = all_reduce(pg, max_centrality, boost::parallel::maximum<centrality_type>());\r\n\r\n  // Compute central point dominance\r\n  centrality_type sum(0);\r\n  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {\r\n    sum += (max_centrality - get(centrality, *v));\r\n  }\r\n\r\n  sum = all_reduce(pg, sum, std::plus<centrality_type>());\r\n\r\n  return sum/(n-1);\r\n}\r\n\r\n} // end namespace boost\r\n\r\n#endif // BOOST_GRAPH_PARALLEL_BRANDES_BETWEENNESS_CENTRALITY_HPP\r\n", "meta": {"hexsha": "9ccc6aa1e21676bd33edd934f09fefcfb7afb845", "size": 73082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/graph/distributed/betweenness_centrality.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T01:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-26T07:38:43.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/graph/distributed/betweenness_centrality.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T01:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T01:56:28.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/graph/distributed/betweenness_centrality.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": 42.3663768116, "max_line_length": 103, "alphanum_fraction": 0.6082756356, "num_tokens": 14898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682620364309852, "lm_q2_score": 0.026355352176963606, "lm_q1q2_score": 0.005187423914668619}}
{"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 \"base/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 \"metis.h\"\n}\n\n#include \"util/logging.h\"\n\nnamespace colmap {\nnamespace {\n\n// Wrapper class for weighted, undirected Metis graph.\nclass MetisGraph {\n public:\n  MetisGraph(const std::vector<std::pair<int, int>>& edges,\n             const std::vector<int>& weights) {\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    idx_t 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) {\n        continue;\n      }\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    nvtxs = vertex_id_to_idx_.size();\n\n    xadj = xadj_.data();\n    adjncy = adjncy_.data();\n\n    vwgt = nullptr;\n    adjwgt = adjwgt_.data();\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  idx_t nvtxs = 0;\n  idx_t* xadj = nullptr;\n  idx_t* vwgt = nullptr;\n  idx_t* adjncy = nullptr;\n  idx_t* adjwgt = nullptr;\n\n private:\n  std::unordered_map<int, int> vertex_id_to_idx_;\n  std::unordered_map<int, int> vertex_idx_to_id_;\n  std::vector<idx_t> xadj_;\n  std::vector<idx_t> adjncy_;\n  std::vector<idx_t> adjwgt_;\n};\n\n}  // namespace\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  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 =\n      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  CHECK(!edges.empty());\n  CHECK_EQ(edges.size(), weights.size());\n  CHECK_GT(num_parts, 0);\n\n  MetisGraph graph(edges, weights);\n\n  idx_t ncon = 1;\n  idx_t edgecut = -1;\n  idx_t nparts = num_parts;\n\n  idx_t metisOptions[METIS_NOPTIONS];\n  METIS_SetDefaultOptions(metisOptions);\n\n  std::vector<idx_t> cut_labels(graph.nvtxs, -1);\n  const int metisResult = METIS_PartGraphKway(\n      &graph.nvtxs,\n      /*ncon=*/&ncon, graph.xadj, graph.adjncy,\n      /*vwgt=*/nullptr,\n      /*vsize=*/nullptr, graph.adjwgt, &nparts,\n      /*tpwgts=*/nullptr,\n      /*ubvec=*/nullptr, metisOptions, &edgecut, cut_labels.data());\n\n  if (metisResult == METIS_ERROR_INPUT) {\n    LOG(FATAL) << \"INTERNAL: Metis input error\";\n  } else if (metisResult == METIS_ERROR_MEMORY) {\n    LOG(FATAL) << \"INTERNAL: Metis memory error\";\n  } else if (metisResult == METIS_ERROR) {\n    LOG(FATAL) << \"INTERNAL: Metis 'some other type of error'\";\n  }\n\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 colmap\n", "meta": {"hexsha": "5b696caf223dab410e5947d67f35eea79002dace", "size": 6861, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/base/graph_cut.cc", "max_stars_repo_name": "ashishd/colmap", "max_stars_repo_head_hexsha": "30521f19de45c1cb2df8809728e780bf95fc8836", "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/base/graph_cut.cc", "max_issues_repo_name": "ashishd/colmap", "max_issues_repo_head_hexsha": "30521f19de45c1cb2df8809728e780bf95fc8836", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/graph_cut.cc", "max_forks_repo_name": "ashishd/colmap", "max_forks_repo_head_hexsha": "30521f19de45c1cb2df8809728e780bf95fc8836", "max_forks_repo_licenses": ["BSD-3-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.1449275362, "max_line_length": 79, "alphanum_fraction": 0.6775980178, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418258225589, "lm_q2_score": 0.019719129295526803, "lm_q1q2_score": 0.005183011947667374}}
{"text": "// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers\n// Copyright (c) 2016-2018  zawy12\n// Copyright (c) 2016-2018, The Karbowanec developers\n// Copyright (c) 2018-2021, The Qwertycoin Group.\n//\n// This file is part of Qwertycoin.\n//\n// Qwertycoin 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// Qwertycoin 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 Qwertycoin.  If not, see <http://www.gnu.org/licenses/>.\n\n#include <algorithm>\n#include <cctype>\n#include <cmath>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <Common/Base58.h>\n#include <Common/int-util.h>\n#include <Common/Math.h>\n#include <Common/StringTools.h>\n#include <CryptoNoteCore/Account.h>\n#include <CryptoNoteCore/CryptoNoteBasicImpl.h>\n#include <CryptoNoteCore/CryptoNoteFormatUtils.h>\n#include <CryptoNoteCore/CryptoNoteTools.h>\n#include <CryptoNoteCore/Currency.h>\n#include <CryptoNoteCore/TransactionExtra.h>\n#include <CryptoNoteCore/UpgradeDetector.h>\n#include <Global/Constants.h>\n#include <Global/CryptoNoteConfig.h>\n\n#undef ERROR\n\nusing namespace Logging;\nusing namespace Common;\nusing namespace Qwertycoin;\n\nnamespace CryptoNote {\n\nbool Currency::init()\n{\n    if (!generateGenesisBlock()) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to generate genesis block\";\n        return false;\n    }\n\n    if (!get_block_hash(m_genesisBlock, m_genesisBlockHash)) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to get genesis block hash\";\n        return false;\n    }\n\n    if (isTestnet()) {\n        m_upgradeHeightV2 = 10;\n        m_upgradeHeightV3 = 60;\n        m_upgradeHeightV4 = 70;\n        m_upgradeHeightV5 = 80;\n        m_upgradeHeightV6 = 100;\n        m_governancePercent = 10;\n        m_governanceHeightStart = 1;\n        m_governanceHeightEnd = 100;\n        m_blocksFileName = \"testnet_\" + m_blocksFileName;\n        m_blocksCacheFileName = \"testnet_\" + m_blocksCacheFileName;\n        m_blockIndexesFileName = \"testnet_\" + m_blockIndexesFileName;\n        m_txPoolFileName = \"testnet_\" + m_txPoolFileName;\n        m_blockchainIndicesFileName = \"testnet_\" + m_blockchainIndicesFileName;\n    }\n\n    return true;\n}\n\nbool Currency::generateGenesisBlock()\n{\n    m_genesisBlock = boost::value_initialized<Block>();\n\n    // Hard code coinbase tx in genesis block, because \"tru\" generating tx use random,\n    // but genesis should be always the same\n    std::string genesisCoinbaseTxHex = GENESIS_COINBASE_TX_HEX;\n    BinaryArray minerTxBlob;\n\n    bool r = fromHex(genesisCoinbaseTxHex, minerTxBlob)\n             && fromBinaryArray(m_genesisBlock.baseTransaction, minerTxBlob);\n\n    if (!r) {\n        logger(ERROR, BRIGHT_RED) << \"failed to parse coinbase tx from hard coded blob\";\n        return false;\n    }\n\n    m_genesisBlock.majorVersion = BLOCK_MAJOR_VERSION_1;\n    m_genesisBlock.minorVersion = BLOCK_MINOR_VERSION_0;\n    m_genesisBlock.timestamp = 0;\n    m_genesisBlock.nonce = 70;\n    if (m_testnet) {\n        ++m_genesisBlock.nonce;\n    }\n\n    //miner::find_nonce_for_given_block(bl, 1, 0);\n\n    return true;\n}\n\nsize_t Currency::blockGrantedFullRewardZoneByBlockVersion(uint8_t blockMajorVersion) const\n{\n    return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE;\n}\n\nuint32_t Currency::upgradeHeight(uint8_t majorVersion) const\n{\n    if (majorVersion == BLOCK_MAJOR_VERSION_6) {\n        return m_upgradeHeightV6;\n    }\n    else if (majorVersion == BLOCK_MAJOR_VERSION_5) {\n        return m_upgradeHeightV5;\n    }\n    else if (majorVersion == BLOCK_MAJOR_VERSION_4) {\n        return m_upgradeHeightV4;\n    }\n    else if (majorVersion == BLOCK_MAJOR_VERSION_3) {\n        return m_upgradeHeightV3;\n    }\n    else if (majorVersion == BLOCK_MAJOR_VERSION_2) {\n        return m_upgradeHeightV2;\n    }\n    else {\n        return static_cast<uint32_t>(-1);\n    }\n}\n\nbool Currency::getBlockReward(\n    uint8_t blockMajorVersion,\n    size_t medianSize,\n    size_t currentBlockSize,\n    uint64_t alreadyGeneratedCoins,\n    uint64_t fee,\n    uint64_t &reward,\n    int64_t &emissionChange,\n    uint32_t height,\n    uint64_t blockTarget) const\n{\n    //assert(alreadyGeneratedCoins <= m_moneySupply);\n    assert(m_emissionSpeedFactor > 0 && m_emissionSpeedFactor <= 8 * sizeof(uint64_t));\n\n    // Consistency\n    double consistency = 1.0;\n    double exponent = 0.25; \n    if (height >= CryptoNote::parameters::UPGRADE_HEIGHT_V1 && difficultyTarget() != 0) {\n        // blockTarget is (Timestamp of New Block - Timestamp of Previous Block)\n        consistency = (double) blockTarget / (double) difficultyTarget();\n\n        // consistency range is 0..2\n        if (consistency < 1.0) {\n            consistency = std::max<double>(consistency, 0.0);\n        }\n        else if (consistency > 1.0) {\n            consistency = pow(consistency, exponent);\n            consistency = std::min<double>(consistency, 2.0);\n        }\n        else {\n            consistency = 1.0;\n        }\n    }  \n\n    // Tail emission\n\n    uint64_t baseReward = ((m_moneySupply - alreadyGeneratedCoins) >> m_emissionSpeedFactor) * consistency;\n    if (alreadyGeneratedCoins + CryptoNote::parameters::TAIL_EMISSION_REWARD >= m_moneySupply\n        || baseReward < CryptoNote::parameters::TAIL_EMISSION_REWARD) {\n        baseReward = CryptoNote::parameters::TAIL_EMISSION_REWARD;\n    }\n\n    size_t blockGrantedFullRewardZone = blockGrantedFullRewardZoneByBlockVersion(blockMajorVersion);\n    medianSize = std::max(medianSize, blockGrantedFullRewardZone);\n    if (currentBlockSize > medianSize * UINT64_C(2)) {\n        logger(TRACE)\n            << \"Block cumulative size is too big: \"\n            << currentBlockSize\n            << \", expected less than \"\n            << medianSize * UINT64_C(2);\n        return false;\n    }\n\n    uint64_t penalizedBaseReward = getPenalizedAmount(baseReward, medianSize, currentBlockSize);\n    uint64_t penalizedFee = getPenalizedAmount(fee, medianSize, currentBlockSize);\n\n    emissionChange = penalizedBaseReward - (fee - penalizedFee);\n    reward = penalizedBaseReward + penalizedFee;\n\n    return true;\n}\n\nsize_t Currency::maxBlockCumulativeSize(uint64_t height) const\n{\n    assert(height <= std::numeric_limits<uint64_t>::max() / m_maxBlockSizeGrowthSpeedNumerator);\n\n    size_t maxSize =\n        static_cast<size_t>(m_maxBlockSizeInitial\n        + (height * m_maxBlockSizeGrowthSpeedNumerator) / m_maxBlockSizeGrowthSpeedDenominator);\n\n    assert(maxSize >= m_maxBlockSizeInitial);\n\n    return maxSize;\n}\n\nbool Currency::isGovernanceEnabled(uint32_t height) const\n{\n    if (height >= m_governanceHeightStart && height <= m_governanceHeightEnd) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nuint64_t Currency::getGovernanceReward(uint64_t base_reward) const\n{\n    // minimum is 1% to avoid a zero amount and maximum is 50%\n    uint16_t percent = (m_governancePercent < 1) ? 1 : (m_governancePercent > 50) ? 50 : m_governancePercent;\n    return (uint64_t)(base_reward * (percent * 0.01));\n}\n\nbool Currency::validate_government_fee(const Transaction &baseTx) const\n{\n    AccountKeys governanceKeys;\n    getGovernanceAddressAndKey(governanceKeys);\n\n    Crypto::PublicKey txPublicKey = getTransactionPublicKeyFromExtra(baseTx.extra);\n\n    Crypto::KeyDerivation derivation;\n    if (!Crypto::generate_key_derivation( txPublicKey,\n                                  governanceKeys.viewSecretKey,\n                                  derivation)) {\n        return false;\n    }\n\n    uint64_t minerReward = 0;\n    uint64_t governmentFee = 0;\n    for (size_t idx = 0; idx < baseTx.outputs.size(); ++idx) {\n        minerReward += baseTx.outputs[idx].amount;\n        if (baseTx.outputs[idx].target.type() != typeid(CryptoNote::KeyOutput))\n            continue;\n        Crypto::PublicKey outEphemeralKey;\n        Crypto::derive_public_key(derivation, idx,\n            governanceKeys.address.spendPublicKey, outEphemeralKey);\n        if (outEphemeralKey == boost::get<KeyOutput>(baseTx.outputs[idx].target).key)\n            governmentFee += baseTx.outputs[idx].amount;\n    }\n\n    return (governmentFee == getGovernanceReward(minerReward));\n}\n\nbool Currency::getGovernanceAddressAndKey(AccountKeys& governanceKeys) const\n{\n    std::string address       = GOVERNANCE_WALLET_ADDRESS;\n    std::string viewSecretkey = GOVERNANCE_VIEW_SECRET_KEY;\n\n    AccountPublicAddress governanceAddress = boost::value_initialized<AccountPublicAddress>();\n    if (!parseAccountAddressString(address, governanceAddress)) {\n        logger(Logging::ERROR)\n            << \"Failed to parse governance wallet address (\"\n            << address\n            << \"), \"\n            << \"Check /lib/Global/CryptoNoteConfig.h\";\n        return false;\n    }\n\n    Crypto::SecretKey governanceViewSecretKey;\n    if (!Common::podFromHex(viewSecretkey, governanceViewSecretKey)) {\n        logger(Logging::ERROR)\n            << \"Failed to parse governance view secret key\"\n            << \"Check /lib/Global/CryptoNoteConfig.h\";\n        return false;\n    }\n\n    governanceKeys.address = governanceAddress;\n    governanceKeys.viewSecretKey = governanceViewSecretKey;\n\n    return true;\n}\n\nbool Currency::constructMinerTx(\n    uint8_t blockMajorVersion,\n    uint32_t height,\n    size_t medianSize,\n    uint64_t alreadyGeneratedCoins,\n    size_t currentBlockSize,\n    uint64_t fee,\n    const AccountPublicAddress &minerAddress,\n    Transaction &tx,\n    const BinaryArray &extraNonce /* = BinaryArray()*/,\n    size_t maxOuts /* = 1*/,\n    uint64_t blockTarget /* = 0xffffffffffffffff*/) const\n{\n    if (blockTarget == 0xffffffffffffffff)\n        blockTarget = difficultyTarget();\n    tx.inputs.clear();\n    tx.outputs.clear();\n    tx.extra.clear();\n\n    KeyPair txkey = generateKeyPair();\n    addTransactionPublicKeyToExtra(tx.extra, txkey.publicKey);\n    if (!extraNonce.empty()) {\n        if (!addExtraNonceToTransactionExtra(tx.extra, extraNonce)) {\n            return false;\n        }\n    }\n\n    BaseInput in;\n    in.blockIndex = height;\n\n    uint64_t governanceReward = 0;\n    uint64_t totalRewardWGR = 0; //totalRewardWithoutGovernanceReward\n\n    uint64_t blockReward;\n    int64_t emissionChange;\n\n    if (!getBlockReward(\n            blockMajorVersion,\n            medianSize,\n            currentBlockSize,\n            alreadyGeneratedCoins,\n            fee,\n            blockReward,\n            emissionChange,\n            height,\n            blockTarget)\n        ) {\n        logger(INFO) << \"Block is too big\";\n        return false;\n    }\n\n    totalRewardWGR = blockReward;\n\n    // If Governance Fee blockReward is decreased by GOVERNANCE_PERCENT_FEE\n    bool enableGovernance = isGovernanceEnabled(height);\n\n    if (enableGovernance) {\n        governanceReward = getGovernanceReward(blockReward);\n\n        if (alreadyGeneratedCoins != 0) {\n            blockReward -= governanceReward;\n            totalRewardWGR  = blockReward + governanceReward;\n        }\n    }\n\n    std::vector<uint64_t> outAmounts;\n    decompose_amount_into_digits(\n        blockReward,\n        UINT64_C(0),\n        [&outAmounts](uint64_t a_chunk) { outAmounts.push_back(a_chunk); },\n        [&outAmounts](uint64_t a_dust) { outAmounts.push_back(a_dust); }\n    );\n\n    if (maxOuts < 1) {\n        logger(ERROR, BRIGHT_RED) << \"max_out must be non-zero\";\n        return false;\n    }\n    while (maxOuts < outAmounts.size()) {\n        outAmounts[outAmounts.size() - 2] += outAmounts.back();\n        outAmounts.resize(outAmounts.size() - 1);\n    }\n\n    uint64_t summaryAmounts = 0;\n    for (size_t no = 0; no < outAmounts.size(); no++) {\n        Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();\n        Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();\n\n        bool r = Crypto::generate_key_derivation(\n            minerAddress.viewPublicKey,\n            txkey.secretKey,\n            derivation\n        );\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to generate_key_derivation(\"\n                << minerAddress.viewPublicKey\n                << \", \"\n                << txkey.secretKey\n                << \")\";\n            return false;\n        }\n\n        r = Crypto::derive_public_key(derivation,no,minerAddress.spendPublicKey,outEphemeralPubKey);\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to derive_public_key(\"\n                << derivation << \", \"\n                << no << \", \"\n                << minerAddress.spendPublicKey\n                << \")\";\n            return false;\n        }\n\n        KeyOutput tk;\n        tk.key = outEphemeralPubKey;\n\n        TransactionOutput out;\n        summaryAmounts += out.amount = outAmounts[no];\n        out.target = tk;\n        tx.outputs.push_back(out);\n    }\n\n    if (enableGovernance) {\n        AccountKeys governanceKeys;\n        getGovernanceAddressAndKey(governanceKeys);\n\n        Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();\n        Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();\n\n        bool r = Crypto::generate_key_derivation(governanceKeys.address.viewPublicKey, txkey.secretKey, derivation);\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to generate_key_derivation(\"\n                << governanceKeys.address.viewPublicKey << \", \" << txkey.secretKey << \")\";\n            return false;\n        }\n        size_t pos = tx.outputs.size();\n        r = Crypto::derive_public_key(derivation, pos++, governanceKeys.address.spendPublicKey, outEphemeralPubKey);\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to derive_public_key(\"\n                << derivation << \", \" << 0 << \", \"\n                << governanceKeys.address.spendPublicKey << \")\";\n            return false;\n        }\n        KeyOutput tk;\n        tk.key = outEphemeralPubKey;\n\n        TransactionOutput out;\n        summaryAmounts += out.amount = governanceReward;\n        out.target = tk;\n        tx.outputs.push_back(out);\n    }\n\n    if (summaryAmounts != totalRewardWGR) {\n        logger(ERROR, BRIGHT_RED)\n            << \"Failed to construct miner tx, summaryAmounts = \"\n            << summaryAmounts\n            << \" not equal blockReward = \"\n            << blockReward;\n        return false;\n    }\n\n    tx.version = CURRENT_TRANSACTION_VERSION;\n    //lock\n    tx.unlockTime = height + m_minedMoneyUnlockWindow;\n    tx.inputs.push_back(in);\n\n    return true;\n}\n\nbool Currency::isFusionTransaction(\n    const std::vector<uint64_t> &inputsAmounts,\n    const std::vector<uint64_t> &outputsAmounts,\n    size_t size,\n    uint32_t height) const\n{\n    // TODO: Simplify if (...) content.\n    if (size > fusionTxMaxSize()) {\n        logger(ERROR) << \"Fusion transaction verification failed: size exceeded max allowed size.\";\n        return false;\n    }\n\n    if (inputsAmounts.size() < fusionTxMinInputCount()) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"inputs count is less than minimum.\";\n        return false;\n    }\n\n    if (inputsAmounts.size() < outputsAmounts.size() * fusionTxMinInOutCountRatio()) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"inputs to outputs count ratio is less than minimum.\";\n        return false;\n    }\n\n    uint64_t inputAmount = 0;\n    for (auto amount : inputsAmounts) {\n        inputAmount += amount;\n    }\n\n    std::vector<uint64_t> expectedOutputsAmounts;\n    expectedOutputsAmounts.reserve(outputsAmounts.size());\n    decomposeAmount(\n        inputAmount,\n        UINT64_C(0), expectedOutputsAmounts);\n    std::sort(expectedOutputsAmounts.begin(), expectedOutputsAmounts.end());\n\n    bool decompose = expectedOutputsAmounts == outputsAmounts;\n    if (!decompose) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"decomposed output amounts do not match expected.\";\n        return false;\n    }\n\n    return true;\n}\n\nbool Currency::isFusionTransaction(const Transaction &transaction,size_t size,uint32_t height) const\n{\n    assert(getObjectBinarySize(transaction) == size);\n\n    std::vector<uint64_t> outputsAmounts;\n    outputsAmounts.reserve(transaction.outputs.size());\n    for (const TransactionOutput &output : transaction.outputs) {\n        outputsAmounts.push_back(output.amount);\n    }\n\n    return isFusionTransaction(getInputsAmounts(transaction), outputsAmounts, size, height);\n}\n\nbool Currency::isFusionTransaction(const Transaction &transaction, uint32_t height) const\n{\n    return isFusionTransaction(transaction, getObjectBinarySize(transaction), height);\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(\n    uint64_t amount,\n    uint64_t threshold,\n    uint32_t height) const\n{\n    uint8_t ignore;\n    return isAmountApplicableInFusionTransactionInput(amount, threshold, ignore, height);\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(\n    uint64_t amount,\n    uint64_t threshold,\n    uint8_t &amountPowerOfTen,\n    uint32_t height) const\n{\n    if (amount >= threshold) {\n        return false;\n    }\n\n    auto it = std::lower_bound(\n        Constants::PRETTY_AMOUNTS.begin(),\n        Constants::PRETTY_AMOUNTS.end(),\n        amount\n    );\n    if (it == Constants::PRETTY_AMOUNTS.end() || amount != *it) {\n        return false;\n    }\n\n    amountPowerOfTen = static_cast<uint8_t>(std::distance(Constants::PRETTY_AMOUNTS.begin(), it)/9);\n\n    return true;\n}\n\nstd::string Currency::accountAddressAsString(const AccountBase &account) const\n{\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, account.getAccountKeys().address);\n}\n\nstd::string Currency::accountAddressAsString(const AccountPublicAddress &accountPublicAddress) const\n{\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, accountPublicAddress);\n}\n\nbool Currency::parseAccountAddressString(const std::string &str, AccountPublicAddress &addr) const\n{\n    uint64_t prefix;\n    if (!CryptoNote::parseAccountAddressString(prefix, addr, str)) {\n        return false;\n    }\n\n    if (prefix != m_publicAddressBase58Prefix) {\n        logger(DEBUGGING)\n        << \"Wrong address prefix: \" << prefix\n        << \", expected \" << m_publicAddressBase58Prefix;\n        return false;\n    }\n\n    return true;\n}\n\nstd::string Currency::formatAmount(uint64_t amount) const\n{\n    std::string s = std::to_string(amount);\n    if (s.size() < m_numberOfDecimalPlaces + 1) {\n        s.insert(0, m_numberOfDecimalPlaces + 1 - s.size(), '0');\n    }\n    s.insert(s.size() - m_numberOfDecimalPlaces, \".\");\n\n    return s;\n}\n\nstd::string Currency::formatAmount(int64_t amount) const\n{\n    std::string s = formatAmount(static_cast<uint64_t>(std::abs(amount)));\n\n    if (amount < 0) {\n        s.insert(0, \"-\");\n    }\n\n    return s;\n}\n\nbool Currency::parseAmount(const std::string &str, uint64_t &amount) const\n{\n    std::string strAmount = str;\n    boost::algorithm::trim(strAmount);\n\n    size_t pointIndex = strAmount.find_first_of('.');\n    size_t fractionSize;\n    if (std::string::npos != pointIndex) {\n        fractionSize = strAmount.size() - pointIndex - 1;\n        while (m_numberOfDecimalPlaces < fractionSize && '0' == strAmount.back()) {\n            strAmount.erase(strAmount.size() - 1, 1);\n            --fractionSize;\n        }\n        if (m_numberOfDecimalPlaces < fractionSize) {\n            return false;\n        }\n        strAmount.erase(pointIndex, 1);\n    } else {\n        fractionSize = 0;\n    }\n\n    if (strAmount.empty()) {\n        return false;\n    }\n\n    if (!std::all_of(strAmount.begin(), strAmount.end(), ::isdigit)) {\n        return false;\n    }\n\n    if (fractionSize < m_numberOfDecimalPlaces) {\n        strAmount.append(m_numberOfDecimalPlaces - fractionSize, '0');\n    }\n\n    return Common::fromString(strAmount, amount);\n}\n\n// Copyright (c) 2017-2018 Zawy\n// http://zawy1.blogspot.com/2017/12/using-difficulty-to-get-constant-value.html\n// Moore's law application by Sergey Kozlov\nuint64_t Currency::getMinimalFee(\n    uint64_t dailyDifficulty,\n    uint64_t reward,\n    uint64_t avgHistoricalDifficulty,\n    uint64_t medianHistoricalReward,\n    uint32_t height) const\n{\n    return CryptoNote::parameters::MINIMUM_FEE;\n}\n\nuint64_t Currency::roundUpMinFee(uint64_t minimalFee, int digits) const\n{\n    uint64_t ret(0);\n    std::string minFeeString = formatAmount(minimalFee);\n    double minFee = boost::lexical_cast<double>(minFeeString);\n    double scale = pow(10., floor(log10(fabs(minFee))) + (1 - digits));\n    double roundedFee = ceil(minFee / scale) * scale;\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(12) << roundedFee;\n    std::string roundedFeeString = ss.str();\n    parseAmount(roundedFeeString, ret);\n\n    return ret;\n}\n\ndifficulty_type Currency::nextDifficulty(\n    uint8_t blockMajorVersion,\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties,\n    uint32_t height) const\n{\n    if(isTestnet()){\n        return CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    }\n\n    if (timestamps.empty()) {\n        return CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    }\n    // Dynamic difficulty calculation window\n    uint32_t diffWindow = timestamps.size() - 1;\n\n    difficulty_type nextDiffV6 = CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    difficulty_type min_difficulty = CryptoNote::parameters::DEFAULT_DIFFICULTY;\n    // Condition #1 When starting a chain or a working testnet requiring\n    // block sample gathering until enough blocks are available (Kick-off Scenario)\n    // We shall set a baseline for the hashrate that is specific to mining\n    // algo and I propose doing so in the config file.\n    // *** During this initial sampling period, a best guess is the best strategy.\n    // Consider this as a service or trial period.\n    // With EPoW reward algo in place, we don't really need to worry about attackers\n    // or large miners taking advanatage of our system.\n    if (height < CryptoNote::parameters::UPGRADE_HEIGHT_V1 + diffWindow) {\n        return nextDiffV6;\n    }\n\n    // check all values in input vectors greater than previous value to calc adjacent differences later\n    if (std::adjacent_find(timestamps.begin(), timestamps.end(), std::greater<uint64_t>()) != timestamps.end()) {\n        logger (ERROR) << \"Invalid timestamps for difficulty calculation\";\n        return nextDiffV6;\n    }\n    if (std::adjacent_find(cumulativeDifficulties.begin(), cumulativeDifficulties.end(), std::greater_equal<difficulty_type>()) != cumulativeDifficulties.end()) {\n        logger (ERROR) << \"Invalid cumulativeDifficulties for difficulty calculation\";\n        return nextDiffV6;\n    }\n\n    uint64_t difficulty_target = CryptoNote::parameters::DIFFICULTY_TARGET;\n    uint64_t window_target = difficulty_target * diffWindow;\n    uint64_t window_time = timestamps.back() - timestamps.front(); // now subtraction is safe,  we know it is not negative\n\n    // get solvetimes from timestamps\n    std::vector<uint64_t> solveTimes;\n    solveTimes.resize(timestamps.size());\n    std::adjacent_difference(timestamps.begin(), timestamps.end(), solveTimes.begin()); // we check it before and all diffs are positive\n    solveTimes.erase(solveTimes.begin());\n\n    // get difficulties from the cumulative difficulties\n    std::vector<difficulty_type> difficulties;\n    difficulties.resize(cumulativeDifficulties.size());\n    std::adjacent_difference(cumulativeDifficulties.begin(),\n                             cumulativeDifficulties.end(),\n                             difficulties.begin()); // we check it before and all diffs are positive\n    difficulties.erase(difficulties.begin());\n    difficulty_type prev_difficulty = difficulties.back();\n\n    // calc stat values to detect outliers\n    double avg_solvetime = Common::meanValue(solveTimes);\n    double stddev_solvetime = Common::stddevValue(solveTimes);\n    double solvetime_lowborder = 1.0;\n    if(avg_solvetime > stddev_solvetime)\n        solvetime_lowborder = avg_solvetime - stddev_solvetime;\n    double solvetime_highborder = avg_solvetime + stddev_solvetime;\n    size_t valid_solvetime_number = 0;\n    uint64_t valid_solvetime_sum = 0;\n    size_t invalid_solvetime_number = 0;\n    uint64_t invalid_solvetime_sum = 0;\n    std::for_each(solveTimes.begin(), solveTimes.end(),\n                  [solvetime_lowborder, solvetime_highborder,\n                          &valid_solvetime_number, &valid_solvetime_sum,\n                          &invalid_solvetime_number, &invalid_solvetime_sum] (uint64_t st) {\n                      if ((st >= solvetime_lowborder) && (st <= solvetime_highborder)) {\n                          valid_solvetime_number++;\n                          valid_solvetime_sum += st;\n                      } else {\n                          invalid_solvetime_number++;\n                          invalid_solvetime_sum += st;\n                      }\n                  });\n\n    // if there is no \"invalid\" solvetimes we can use previous difficulty value\n    if (invalid_solvetime_number == 0) {\n        return std::max(prev_difficulty, min_difficulty);\n    }\n\n    // process data with \"invalid\" solvetimes\n    double valid_solvetime_mean = double(valid_solvetime_sum) / valid_solvetime_number;\n    double invalid_solvetime_mean = double(invalid_solvetime_sum) / invalid_solvetime_number;\n\n    if ( (window_time >= window_target * 0.97) &&\n         (window_time <= window_target * 1.03) ) {\n        if (valid_solvetime_mean >= invalid_solvetime_mean) {\n            double coef = double(difficulty_target) / double(valid_solvetime_mean);\n            if (valid_solvetime_mean < difficulty_target) {\n                nextDiffV6 = prev_difficulty * std::min(1.01, coef) + 0.5;\n            } else {\n                nextDiffV6 = prev_difficulty * std::max(0.99, coef) + 0.5;\n            }\n        } else {\n            double coef = double(difficulty_target) / double(invalid_solvetime_mean);\n            if (invalid_solvetime_mean < difficulty_target) {\n                nextDiffV6 = prev_difficulty * std::min(1.01, coef) + 0.5;\n            } else {\n                nextDiffV6 = prev_difficulty * std::max(0.99, coef) + 0.5;\n            }\n        }\n    } else if (window_time < window_target * 0.97) {\n        nextDiffV6 = prev_difficulty * 1.02 + 0.5;\n    } else {\n        nextDiffV6 = prev_difficulty * 0.98 + 0.5;\n    }\n\n    return std::max(nextDiffV6, min_difficulty);\n}\n\ndifficulty_type Currency::getClifDifficulty(uint32_t height,\n                                          uint8_t blockMajorVersion,\n                                          difficulty_type last_difficulty,\n                                          uint64_t last_timestamp,\n                                          uint64_t currentSolveTime,\n                                          lazy_stat_callback_type &lazy_stat_cb) const\n{\n    logger (INFO) << \"CLIF difficulty inputs: height \" << height <<\n                     \", block version \" << (int)blockMajorVersion <<\n                     \", last difficulty \" << last_difficulty <<\n                     \", current solve time \" << currentSolveTime;\n\n    difficulty_type new_diff = last_difficulty;\n\n    if (new_diff > CryptoNote::parameters::DEFAULT_DIFFICULTY) {\n        uint64_t correction_interval = currentSolveTime -\n                CryptoNote::parameters::CRYPTONOTE_CLIF_THRESHOLD;\n        //below equation shall return quotient of the division.\n        int decrease_counter = ((int)correction_interval / (int)CryptoNote::parameters::DIFFICULTY_TARGET) + 1;\n        int round_counter = 1;\n\n        new_diff = new_diff / 2;\n        logger (INFO) << \"CLIF decreased difficulty \" << round_counter <<\n            \" times, intermediate difficulty is \" << new_diff;\n        difficulty_type mean_diff = lazy_stat_cb(IMinerHandler::stat_period::hour, last_timestamp);\n        logger (INFO) << \"Last hour average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::day, last_timestamp);\n        logger (INFO) << \"Last day average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::week, last_timestamp);\n        logger (INFO) << \"Last week average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::month, last_timestamp);\n        logger (INFO) << \"Last month average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::halfyear, last_timestamp);\n        logger (INFO) << \"Last halfyear average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n        mean_diff = lazy_stat_cb(IMinerHandler::stat_period::year, last_timestamp);\n        logger (INFO) << \"Last year average difficulty is \" << mean_diff;\n        if (mean_diff > 0)\n            new_diff = std::min(mean_diff, new_diff);\n\n        if (decrease_counter > 1) {\n            while (round_counter < decrease_counter) {\n                new_diff = new_diff / 2;\n                round_counter++;\n                if (new_diff <= CryptoNote::parameters::DEFAULT_DIFFICULTY)\n                    break;\n            }\n            logger (INFO) << \"CLIF decreased difficulty \" << round_counter <<\n                \" times, intermediate difficulty is \" << new_diff;\n        }\n\n        new_diff = std::max(new_diff, difficulty_type(CryptoNote::parameters::DEFAULT_DIFFICULTY));\n    }\n\n    logger (INFO) << \"CLIF difficulty result: \" << new_diff;\n    return new_diff;\n}\n\nbool Currency::checkProofOfWorkV1(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    if (BLOCK_MAJOR_VERSION_2 == block.majorVersion) {\n        return false;\n    }\n\n    if (!get_block_longhash(context, block, proofOfWork)) {\n        return false;\n    }\n\n    return check_hash(proofOfWork, currentDiffic);\n}\n\nbool Currency::checkProofOfWorkV2(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    if (block.majorVersion < BLOCK_MAJOR_VERSION_2) {\n        return false;\n    }\n\n    if (!get_block_longhash(context, block, proofOfWork)) {\n        return false;\n    }\n\n    if (!check_hash(proofOfWork, currentDiffic)) {\n        return false;\n    }\n\n    TransactionExtraMergeMiningTag mmTag;\n    if (!getMergeMiningTagFromExtra(block.parentBlock.baseTransaction.extra, mmTag)) {\n        logger(ERROR)\n            << \"merge mining tag wasn't found in extra of the parent block miner transaction\";\n        return false;\n    }\n\n    if (8 * sizeof(m_genesisBlockHash) < block.parentBlock.blockchainBranch.size()) {\n        return false;\n    }\n\n    Crypto::Hash auxBlockHeaderHash;\n    if (!get_aux_block_header_hash(block, auxBlockHeaderHash)) {\n        return false;\n    }\n\n    Crypto::Hash auxBlocksMerkleRoot;\n    Crypto::tree_hash_from_branch(\n        block.parentBlock.blockchainBranch.data(),\n        block.parentBlock.blockchainBranch.size(),\n        auxBlockHeaderHash,\n        &m_genesisBlockHash,\n        auxBlocksMerkleRoot\n    );\n\n    if (auxBlocksMerkleRoot != mmTag.merkleRoot) {\n        logger(ERROR, BRIGHT_YELLOW) << \"Aux block hash wasn't found in merkle tree\";\n        return false;\n    }\n\n    return true;\n}\n\nbool Currency::checkProofOfWork(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    switch (block.majorVersion) {\n    case BLOCK_MAJOR_VERSION_1:\n    case BLOCK_MAJOR_VERSION_3:\n    case BLOCK_MAJOR_VERSION_4:\n    case BLOCK_MAJOR_VERSION_5:\n    case BLOCK_MAJOR_VERSION_6:\n        return checkProofOfWorkV1(context, block, currentDiffic, proofOfWork);\n    case BLOCK_MAJOR_VERSION_2:\n        return checkProofOfWorkV2(context, block, currentDiffic, proofOfWork);\n    }\n\n    logger(ERROR, BRIGHT_RED)\n        << \"Unknown block major version: \"\n        << block.majorVersion\n        << \".\"\n        << block.minorVersion;\n\n    return false;\n}\n\nsize_t Currency::getApproximateMaximumInputCount(\n    size_t transactionSize,\n    size_t outputCount,\n    size_t mixinCount) const\n{\n    const size_t KEY_IMAGE_SIZE = sizeof(Crypto::KeyImage);\n    const size_t OUTPUT_KEY_SIZE = sizeof(decltype(KeyOutput::key));\n    const size_t AMOUNT_SIZE = sizeof(uint64_t) + 2; // varint\n    const size_t GLOBAL_INDEXES_VECTOR_SIZE_SIZE = sizeof(uint8_t); // varint\n    const size_t GLOBAL_INDEXES_INITIAL_VALUE_SIZE = sizeof(uint32_t); // varint\n    const size_t GLOBAL_INDEXES_DIFFERENCE_SIZE = sizeof(uint32_t); // varint\n    const size_t SIGNATURE_SIZE = sizeof(Crypto::Signature);\n    const size_t EXTRA_TAG_SIZE = sizeof(uint8_t);\n    const size_t INPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t OUTPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t PUBLIC_KEY_SIZE = sizeof(Crypto::PublicKey);\n    const size_t TRANSACTION_VERSION_SIZE = sizeof(uint8_t);\n    const size_t TRANSACTION_UNLOCK_TIME_SIZE = sizeof(uint64_t);\n\n    const size_t outputsSize = outputCount * (OUTPUT_TAG_SIZE + OUTPUT_KEY_SIZE + AMOUNT_SIZE);\n    const size_t headerSize = TRANSACTION_VERSION_SIZE\n                              + TRANSACTION_UNLOCK_TIME_SIZE\n                              + EXTRA_TAG_SIZE\n                              + PUBLIC_KEY_SIZE;\n    const size_t inputSize = INPUT_TAG_SIZE\n                             + AMOUNT_SIZE\n                             + KEY_IMAGE_SIZE\n                             + SIGNATURE_SIZE\n                             + GLOBAL_INDEXES_VECTOR_SIZE_SIZE\n                             + GLOBAL_INDEXES_INITIAL_VALUE_SIZE\n                             + mixinCount * (GLOBAL_INDEXES_DIFFERENCE_SIZE + SIGNATURE_SIZE);\n\n    return (transactionSize - headerSize - outputsSize) / inputSize;\n}\n\nCurrencyBuilder::CurrencyBuilder(Logging::ILogger &log)\n    : m_currency(log)\n{\n    maxBlockNumber(parameters::CRYPTONOTE_MAX_BLOCK_NUMBER);\n    maxBlockBlobSize(parameters::CRYPTONOTE_MAX_BLOCK_BLOB_SIZE);\n    maxTxSize(parameters::CRYPTONOTE_MAX_TX_SIZE);\n    publicAddressBase58Prefix(parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX);\n    minedMoneyUnlockWindow(parameters::CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW);\n    transactionSpendableAge(parameters::CRYPTONOTE_TX_SPENDABLE_AGE);\n    safeTransactionSpendableAge(parameters::CRYPTONOTE_SAFE_TX_SPENDABLE_AGE);\n    expectedNumberOfBlocksPerDay(parameters::EXPECTED_NUMBER_OF_BLOCKS_PER_DAY);\n\n    timestampCheckWindow(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);\n    timestampCheckWindow_v1(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW_V2);\n    blockFutureTimeLimit(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT);\n    blockFutureTimeLimit_v1(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT_V2);\n\n    moneySupply(parameters::MONEY_SUPPLY);\n    emissionSpeedFactor(parameters::EMISSION_SPEED_FACTOR);\n    cryptonoteCoinVersion(parameters::CRYPTONOTE_COIN_VERSION);\n\n    rewardBlocksWindow(parameters::CRYPTONOTE_REWARD_BLOCKS_WINDOW);\n    blockGrantedFullRewardZone(parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE);\n    minerTxBlobReservedSize(parameters::CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE);\n    maxTransactionSizeLimit(parameters::MAX_TRANSACTION_SIZE_LIMIT);\n\n    governancePercent(parameters::GOVERNANCE_PERCENT_FEE);\n    governanceHeightStart(parameters::GOVERNANCE_HEIGHT_START);\n    governanceHeightEnd(parameters::GOVERNANCE_HEIGHT_END);\n\n    minMixin(parameters::MIN_TX_MIXIN_SIZE);\n    maxMixin(parameters::MAX_TX_MIXIN_SIZE);\n\n    numberOfDecimalPlaces(parameters::CRYPTONOTE_DISPLAY_DECIMAL_POINT);\n\n    minimumFee(parameters::MINIMUM_FEE);\n    defaultDustThreshold(parameters::DEFAULT_DUST_THRESHOLD);\n\n    difficultyTarget(parameters::DIFFICULTY_TARGET);\n    difficultyWindow(parameters::DIFFICULTY_WINDOW);\n    difficultyLag(parameters::DIFFICULTY_LAG);\n    difficultyCut(parameters::DIFFICULTY_CUT);\n\n    maxBlockSizeInitial(parameters::MAX_BLOCK_SIZE_INITIAL);\n    maxBlockSizeGrowthSpeedNumerator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_NUMERATOR);\n    maxBlockSizeGrowthSpeedDenominator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_DENOMINATOR);\n\n    lockedTxAllowedDeltaSeconds(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS);\n    lockedTxAllowedDeltaBlocks(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS);\n\n    mempoolTxLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_LIVETIME);\n    mempoolTxFromAltBlockLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME);\n    numberOfPeriodsToForgetTxDeletedFromPool(\n        parameters::CRYPTONOTE_NUMBER_OF_PERIODS_TO_FORGET_TX_DELETED_FROM_POOL\n    );\n\n    fusionTxMaxSize(parameters::FUSION_TX_MAX_SIZE);\n    fusionTxMinInputCount(parameters::FUSION_TX_MIN_INPUT_COUNT);\n    fusionTxMinInOutCountRatio(parameters::FUSION_TX_MIN_IN_OUT_COUNT_RATIO);\n\n    upgradeHeightV2(parameters::UPGRADE_HEIGHT_V2);\n    upgradeHeightV3(parameters::UPGRADE_HEIGHT_V3);\n    upgradeHeightV4(parameters::UPGRADE_HEIGHT_V4);\n    upgradeHeightV5(parameters::UPGRADE_HEIGHT_V5);\n    upgradeHeightV6(parameters::UPGRADE_HEIGHT_V6);\n    upgradeVotingThreshold(parameters::UPGRADE_VOTING_THRESHOLD);\n    upgradeVotingWindow(parameters::UPGRADE_VOTING_WINDOW);\n    upgradeWindow(parameters::UPGRADE_WINDOW);\n\n    blocksFileName(parameters::CRYPTONOTE_BLOCKS_FILENAME);\n    blocksCacheFileName(parameters::CRYPTONOTE_BLOCKSCACHE_FILENAME);\n    blockIndexesFileName(parameters::CRYPTONOTE_BLOCKINDEXES_FILENAME);\n    txPoolFileName(parameters::CRYPTONOTE_POOLDATA_FILENAME);\n    blockchainIndicesFileName(parameters::CRYPTONOTE_BLOCKCHAIN_INDICES_FILENAME);\n\n    testnet(false);\n    fix_difficulty(0);\n}\n\nTransaction CurrencyBuilder::generateGenesisTransaction()\n{\n    CryptoNote::Transaction tx;\n    auto ac = boost::value_initialized<CryptoNote::AccountPublicAddress>();\n\n    m_currency.constructMinerTx(1, 0, 0, 0, 0, 0, ac, tx); // zero fee in genesis\n\n    return tx;\n}\n\nCurrencyBuilder& CurrencyBuilder::emissionSpeedFactor(unsigned int val)\n{\n    if (val <= 0 || val > 8 * sizeof(uint64_t)) {\n        throw std::invalid_argument(\"val at emissionSpeedFactor()\");\n    }\n\n    m_currency.m_emissionSpeedFactor = val;\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::numberOfDecimalPlaces(size_t val)\n{\n    m_currency.m_numberOfDecimalPlaces = val;\n    m_currency.m_coin = 1;\n    for (size_t i = 0; i < m_currency.m_numberOfDecimalPlaces; ++i) {\n        m_currency.m_coin *= 10;\n    }\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::difficultyWindow(size_t val)\n{\n    if (val < 2) {\n        throw std::invalid_argument(\"val at difficultyWindow()\");\n    }\n\n    m_currency.m_difficultyWindow = val;\n\n    return *this;\n}\n\nCurrencyBuilder& CurrencyBuilder::upgradeVotingThreshold(unsigned int val)\n{\n    if (val <= 0 || val > 100) {\n        throw std::invalid_argument(\"val at upgradeVotingThreshold()\");\n    }\n\n    m_currency.m_upgradeVotingThreshold = val;\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::upgradeWindow(size_t val)\n{\n    if (val <= 0) {\n        throw std::invalid_argument(\"val at upgradeWindow()\");\n    }\n\n    m_currency.m_upgradeWindow = static_cast<uint32_t>(val);\n\n    return *this;\n}\n\n} // namespace CryptoNote\n", "meta": {"hexsha": "2fc18c3a50a88066d36141de1fd7736968fd0268", "size": 40078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/CryptoNoteCore/Currency.cpp", "max_stars_repo_name": "exploshot/qwertycoin-forkable", "max_stars_repo_head_hexsha": "ff63cbd3a2944ad63a015e5f85414d6ff5feaa89", "max_stars_repo_licenses": ["MIT"], "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/CryptoNoteCore/Currency.cpp", "max_issues_repo_name": "exploshot/qwertycoin-forkable", "max_issues_repo_head_hexsha": "ff63cbd3a2944ad63a015e5f85414d6ff5feaa89", "max_issues_repo_licenses": ["MIT"], "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/CryptoNoteCore/Currency.cpp", "max_forks_repo_name": "exploshot/qwertycoin-forkable", "max_forks_repo_head_hexsha": "ff63cbd3a2944ad63a015e5f85414d6ff5feaa89", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T17:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T17:11:02.000Z", "avg_line_length": 35.3733451015, "max_line_length": 162, "alphanum_fraction": 0.6754828085, "num_tokens": 9373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.01941934623165752, "lm_q1q2_score": 0.005163224963362249}}
{"text": "/*\nCopyright (c) 2019 Naomasa Matsubayashi (aka. Fadis)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include <memory>\n#include <tuple>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <boost/scope_exit.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <liblnn/buffer.h>\n#include <liblnn/load_mnist.h>\n#include <liblnn/exceptions.h>\nnamespace liblnn {\n  mnist::mnist(\n    const std::string &image_filename,\n    const std::string &label_filename\n  ) : current_image( 0 ), gen( std::random_device()() ) {\n    {\n      int fd = open( image_filename.c_str(), O_RDONLY );\n      if( fd == -1 ) throw unable_to_load_file();\n      size_t file_size = 0;\n      {\n        struct stat stat_;\n        if( fstat( fd, &stat_ ) == -1 ) {\n          close( fd );\n          throw unable_to_load_file();\n        }\n        file_size = stat_.st_size;\n      }\n      void *addr = mmap( nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0 );\n      if( !addr ) {\n        close( fd );\n        throw unable_to_load_file();\n      }\n      images.reset(\n        reinterpret_cast< unsigned char* >( addr ),\n        [file_size,fd]( unsigned char *p ) {\n          munmap( reinterpret_cast< void* >( p ), file_size );\n          close( fd );\n        }\n      );\n      {\n        auto hbegin = images.get();\n        const auto hend = std::next( hbegin, 16 );\n        uint32_t magic;\n        boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, magic );\n        if( magic != 0x803 ) throw corrupted_file();\n        boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, image_count );\n        boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, image_width );\n        boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, image_height );\n        image_head = hend;\n        if( file_size < ( 16 + image_count * image_width * image_height ) ) throw corrupted_file();\n      }\n    }\n    {\n      int fd = open( label_filename.c_str(), O_RDONLY );\n      if( fd == -1 ) throw unable_to_load_file();\n      size_t file_size = 0;\n      {\n        struct stat stat_;\n        if( fstat( fd, &stat_ ) == -1 ) {\n          close( fd );\n          throw unable_to_load_file();\n        }\n        file_size = stat_.st_size;\n      }\n      void *addr = mmap( nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0 );\n      if( !addr ) {\n        close( fd );\n        throw unable_to_load_file();\n      }\n      labels.reset(\n        reinterpret_cast< unsigned char* >( addr ),\n        [file_size,fd]( unsigned char *p ) {\n          munmap( reinterpret_cast< void* >( p ), file_size );\n          close( fd );\n        }\n      );\n      {\n        auto hbegin = labels.get();\n        const auto hend = std::next( hbegin, 8 );\n        uint32_t magic;\n        boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, magic );\n        if( magic != 0x801 ) throw corrupted_file();\n\tuint32_t label_count;\n        boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, label_count );\n\tif( label_count != image_count ) throw invalid_data_length();\n        label_head = hend;\n        if( file_size < ( 8 + label_count ) ) throw corrupted_file();\n\tlabel_width = 10;\n      }\n    }\n  }\n  void mnist::operator()(\n    vk::CommandBuffer&,\n    const std::shared_ptr< vk::Device >&,\n    const std::shared_ptr< vk::Queue >&,\n    const device_props&,\n    const buffer_view< float > &image_buffer,\n    const buffer_view< float > &label_buffer\n  ) {\n    if( image_buffer.size() % ( image_width * image_height ) ) throw invalid_data_length();\n    uint32_t batch_size = image_buffer.size() / ( image_width * image_height );\n    if( label_buffer.size() != batch_size * 10 ) throw invalid_data_length();\n    std::uniform_int_distribution< uint32_t > dist( 0u, image_count - 1u );\n    std::vector< uint32_t > selected_index;\n    selected_index.reserve( batch_size );\n    {\n      auto mapped = image_buffer.map();\n      auto obegin = mapped.get();\n      for( uint32_t local_image_index = 0; local_image_index != batch_size; ++local_image_index ) {\n        selected_index.push_back( dist( gen ) );\n        uint32_t global_image_index = selected_index.back(); // ( current_image + local_image_index ) % image_count;\n\tauto ibegin = image_head + global_image_index * image_width * image_height;\n\tauto iend = image_head + ( global_image_index + 1 ) * image_width * image_height;\n        std::transform( ibegin, iend, obegin, []( unsigned char v ) { return v / 255.f; } );\n\tobegin += image_width * image_height;\n      }\n    }\n    {\n      auto mapped = label_buffer.map();\n      auto obegin = mapped.get();\n      std::fill( obegin, std::next( obegin, label_buffer.size() ), 0.f );\n      for( uint32_t local_label_index = 0; local_label_index != batch_size; ++local_label_index ) {\n        uint32_t global_label_index = selected_index[ local_label_index ]; // ( current_image + local_label_index ) % image_count;\n\tauto ibegin = label_head + global_label_index;\n\tobegin[ int( *ibegin ) ] = 1.f;\n\tobegin += 10;\n      }\n    }\n    current_image += batch_size;\n    current_image %= image_count;\n  }\n\n  std::tuple< std::shared_ptr< buffer< float > >, uint32_t >\n  load_mnist_images(\n    const std::shared_ptr< VmaAllocator > &allocator,\n    const std::string &filename\n  ) {\n    int fd = open( filename.c_str(), O_RDONLY );\n    if( fd == -1 ) throw unable_to_load_file();\n    BOOST_SCOPE_EXIT( &fd ) {\n      close( fd );\n    } BOOST_SCOPE_EXIT_END\n    struct stat stat_;\n    if( fstat( fd, &stat_ ) == -1 ) throw unable_to_load_file();\n    const size_t file_size = stat_.st_size;\n    void *addr = mmap( nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0 );\n    if( !addr ) throw unable_to_load_file();\n    {\n      BOOST_SCOPE_EXIT( &addr, &file_size ) {\n        munmap( addr, file_size );\n      } BOOST_SCOPE_EXIT_END\n      auto hbegin = reinterpret_cast< const unsigned char* >( addr );\n      const auto hend = std::next( hbegin, 16 );\n      uint32_t magic;\n      boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, magic );\n      if( magic != 0x803 ) throw corrupted_file();\n      uint32_t data_count;\n      boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, data_count );\n      uint32_t width = 0;\n      boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, width );\n      if( width != 0x1c ) throw corrupted_file();\n      uint32_t height = 0;\n      boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, height );\n      if( height != 0x1c ) throw corrupted_file();\n      auto dbegin = hend;\n      size_t output_size = 32 * 32 * data_count;\n      std::shared_ptr< liblnn::buffer< float > > output( new liblnn::buffer< float >( allocator, VMA_MEMORY_USAGE_CPU_TO_GPU,\n        vk::BufferCreateInfo()\n          .setSize( output_size * sizeof( float ) )\n          .setUsage( vk::BufferUsageFlagBits::eStorageBuffer )\n      ) );\n      {\n        auto mapped = output->map();\n        auto obegin = mapped.get();\n\tauto oend = std::next( obegin, output_size );\n\tstd::fill( obegin, oend, 0.f );\n\tfor( uint32_t data_index = 0; data_index != data_count; ++data_index ) {\n\t  for( uint32_t y = 0; y != height; ++y ) {\n\t    for( uint32_t x = 0; x != width; ++x ) {\n\t      obegin[ data_index * 32 * 32 + ( y + 2 ) * width + x + 2 ] = dbegin[ data_index * width * height + y * width + x ] / 255.f;\n\t    }\n\t  }\n\t}\n      }\n      return std::make_tuple( output, data_count ); \n    }\n  }\n  std::tuple< std::shared_ptr< buffer< float > >, uint32_t >\n  load_mnist_labels(\n    const std::shared_ptr< VmaAllocator > &allocator,\n    const std::string &filename\n  ) {\n    int fd = open( filename.c_str(), O_RDONLY );\n    if( fd == -1 ) throw unable_to_load_file();\n    BOOST_SCOPE_EXIT( &fd ) {\n      close( fd );\n    } BOOST_SCOPE_EXIT_END\n    struct stat stat_;\n    if( fstat( fd, &stat_ ) == -1 ) throw unable_to_load_file();\n    const size_t file_size = stat_.st_size;\n    void *addr = mmap( nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0 );\n    if( !addr ) throw unable_to_load_file();\n    {\n      BOOST_SCOPE_EXIT( &addr, &file_size ) {\n        munmap( addr, file_size );\n      } BOOST_SCOPE_EXIT_END\n      auto hbegin = reinterpret_cast< const unsigned char* >( addr );\n      const auto hend = std::next( hbegin, 16 );\n      uint32_t magic;\n      boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, magic );\n      if( magic != 0x801 ) throw corrupted_file();\n      uint32_t data_count;\n      boost::spirit::qi::parse( hbegin, hend, boost::spirit::qi::big_dword, data_count );\n      auto dbegin = hend;\n      size_t output_size = 10 * data_count;\n      std::shared_ptr< liblnn::buffer< float > > output( new liblnn::buffer< float >( allocator, VMA_MEMORY_USAGE_CPU_TO_GPU,\n        vk::BufferCreateInfo()\n          .setSize( output_size * sizeof( float ) )\n          .setUsage( vk::BufferUsageFlagBits::eStorageBuffer )\n      ) );\n      {\n        auto mapped = output->map();\n        auto obegin = mapped.get();\n\tauto oend = std::next( obegin, output_size );\n\tstd::fill( obegin, oend, 0.f );\n\tfor( uint32_t data_index = 0; data_index != data_count; ++data_index ) {\n\t  obegin[ data_index * 10 + dbegin[ data_index ] ] = 1.f;\n\t}\n      }\n      return std::make_tuple( output, data_count ); \n    }\n  }\n}\n", "meta": {"hexsha": "2516606c8c0f853ec969391dbf033ac0df8fc08b", "size": 10374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/load_mnist.cpp", "max_stars_repo_name": "Fadis/kernelvm_20190720_samples", "max_stars_repo_head_hexsha": "8f51e7e24313122d25edf51aa4acc3f0581e3238", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-07-20T06:37:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T18:40:31.000Z", "max_issues_repo_path": "src/load_mnist.cpp", "max_issues_repo_name": "Fadis/kernelvm_20190720_samples", "max_issues_repo_head_hexsha": "8f51e7e24313122d25edf51aa4acc3f0581e3238", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/load_mnist.cpp", "max_forks_repo_name": "Fadis/kernelvm_20190720_samples", "max_forks_repo_head_hexsha": "8f51e7e24313122d25edf51aa4acc3f0581e3238", "max_forks_repo_licenses": ["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.5954198473, "max_line_length": 130, "alphanum_fraction": 0.6322537112, "num_tokens": 2769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.01912403765933078, "lm_q1q2_score": 0.005143245870433734}}
{"text": "// Copyright (c) 2012-2016, NVIDIA CORPORATION. All rights reserved.\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 <dp/culling/ObjectBitSet.h>\n#include <dp/culling/ResultBitSet.h>\n#include <dp/culling/ManagerBitSet.h>\n#include <dp/culling/GroupBitSet.h>\n#include <dp/util/BitArray.h>\n#include <boost/scoped_array.hpp>\n\n#include <dp/util/FrameProfiler.h>\n\n#include <limits>\n\n// TODO verify alignment of vectors/matrices on linux\n#if defined(DP_ARCH_X86_64) && defined(DP_OS_WINDOWS)\n#define SSE\n#endif\n\n#if defined(SSE)\n#include <dp/math/sse/Vecnt.h>\n#include <dp/math/sse/Matmnt.h>\nstatic bool useSSE = true;\n#else\nstatic bool useSSE = false;\n#endif\n\n#if defined(DP_ARCH_ARM_32)\n#define NEON\n#endif\n\n#if defined(NEON)\n#include <dp/math/neon/Vecnt.h>\n#include <dp/math/neon/Matmnt.h>\nstatic bool useNEON = true;\n#else\nstatic bool useNEON = false;\n#endif\n\n\nnamespace dp\n{\n  namespace culling\n  {\n\n    ManagerBitSet::ManagerBitSet()\n    {\n\n    }\n    ManagerBitSet::~ManagerBitSet()\n    {\n\n    }\n\n    void ManagerBitSet::objectSetUserData( const ObjectSharedPtr& object, PayloadSharedPtr const& userData )\n    {\n      std::static_pointer_cast<ObjectBitSet>(object)->setUserData( userData );\n    }\n\n    PayloadSharedPtr const& ManagerBitSet::objectGetUserData( const ObjectSharedPtr& object )\n    {\n      return( std::static_pointer_cast<ObjectBitSet>(object)->getUserData() );\n    }\n\n    void ManagerBitSet::objectSetTransformIndex( const ObjectSharedPtr& object, size_t index )\n    {\n      ObjectBitSetSharedPtr objectImpl = std::static_pointer_cast<ObjectBitSet>(object);\n\n      objectImpl->setTransformIndex( index );\n      if ( objectImpl->getGroup() )\n      {\n        objectImpl->getGroup()->setOBBDirty( true );\n      }\n    }\n\n    void ManagerBitSet::objectSetBoundingBox( const ObjectSharedPtr& object, const dp::math::Box3f& boundingBox )\n    {\n      ObjectBitSetSharedPtr objectImpl = std::static_pointer_cast<ObjectBitSet>(object);\n      objectImpl->setLowerLeft( dp::math::Vec4f(boundingBox.getLower(), 1.0f ) );\n      objectImpl->setExtent( dp::math::Vec4f( boundingBox.getSize(), 0.0f ) );\n\n      if ( objectImpl->getGroup() )\n      {\n        objectImpl->getGroup()->setOBBDirty( true );\n      }\n    }\n\n    void ManagerBitSet::groupAddObject( const GroupSharedPtr& group, const ObjectSharedPtr& object )\n    {\n      std::static_pointer_cast<GroupBitSet>(group)->addObject( std::static_pointer_cast<ObjectBitSet>(object) );\n    }\n\n    ObjectSharedPtr ManagerBitSet::groupGetObject( const GroupSharedPtr& group, size_t index )\n    {\n      return( std::static_pointer_cast<GroupBitSet>(group)->getObject( index ) );\n    }\n\n    void ManagerBitSet::groupRemoveObject( const GroupSharedPtr& group, const ObjectSharedPtr& objectHandle )\n    {\n      std::static_pointer_cast<GroupBitSet>(group)->removeObject( std::static_pointer_cast<ObjectBitSet>(objectHandle) );\n    }\n\n    size_t ManagerBitSet::groupGetCount( const GroupSharedPtr& group )\n    {\n      return( std::static_pointer_cast<GroupBitSet>(group)->getObjectCount() );\n    }\n\n    void ManagerBitSet::groupSetMatrices( const GroupSharedPtr& group, void const* matrices, size_t numberOfMatrices, size_t stride )\n    {\n      std::static_pointer_cast<GroupBitSet>(group)->setMatrices( matrices, numberOfMatrices, stride );\n    }\n\n    void ManagerBitSet::groupMatrixChanged( GroupSharedPtr const& group, size_t index )\n    {\n      std::static_pointer_cast<GroupBitSet>(group)->markMatrixDirty( index );\n    }\n\n    std::vector<ObjectSharedPtr> const & ManagerBitSet::resultGetChanged( const ResultSharedPtr& result )\n    {\n      return( std::static_pointer_cast<ResultBitSet>(result)->getChangedObjects() );\n    }\n\n    bool ManagerBitSet::resultObjectIsVisible( ResultSharedPtr const& result, ObjectSharedPtr const& object )\n    {\n      return( std::static_pointer_cast<ResultBitSet>(result)->isVisible( std::static_pointer_cast<ObjectBitSet>(object) ) );\n    }\n\n    dp::math::Box3f ManagerBitSet::getBoundingBox( const GroupSharedPtr& group ) const\n    {\n      dp::util::ProfileEntry p(\"cull::getBoundingBox\");\n\n      GroupBitSetSharedPtr groupImpl = std::static_pointer_cast<GroupBitSet>(group);\n      if ( groupImpl->isBoundingBoxDirty() )\n      {\n        groupImpl->setBoundingBox( calculateBoundingBox( group ) );\n        groupImpl->setBoundingBoxDirty( false );\n      }\n      return groupImpl->getBoundingBox();\n    }\n\n    dp::math::Box3f ManagerBitSet::calculateBoundingBox( const GroupSharedPtr& group ) const\n    {\n#if defined(SSE)\n      if ( useSSE )\n      {\n        GroupBitSetSharedPtr groupImpl = std::static_pointer_cast<GroupBitSet>(group);\n\n        __m128 minValue = _mm_set1_ps( std::numeric_limits<float>::signaling_NaN() );\n        __m128 maxValue = _mm_set1_ps( std::numeric_limits<float>::signaling_NaN() );\n\n        char const* basePtr = reinterpret_cast<char const*>(groupImpl->getMatrices());\n        for ( size_t index = 0;index < groupImpl->getObjectCount(); ++index )\n        {\n          ObjectBitSetSharedPtr objectImpl = std::static_pointer_cast<ObjectBitSet>(groupImpl->getObject( index ));\n          dp::math::sse::Mat44f const& modelView = *reinterpret_cast<dp::math::sse::Mat44f const*>(basePtr + objectImpl->getTransformIndex() * groupImpl->getMatricesStride());\n          dp::math::Vec4f const& extent = objectImpl->getExtent();\n\n          dp::math::sse::Vec4f vectors[8];\n          vectors[0] = *reinterpret_cast<dp::math::sse::Vec4f const*>(&objectImpl->getLowerLeft()) * modelView;\n\n          dp::math::sse::Vec4f x( extent[0] * modelView[0] );\n          dp::math::sse::Vec4f y( extent[1] * modelView[1] );\n          dp::math::sse::Vec4f z( extent[2] * modelView[2] );\n\n          vectors[1] = vectors[0] + x;\n          vectors[2] = vectors[0] + y;\n          vectors[3] = vectors[1] + y;\n          vectors[4] = vectors[0] + z;\n          vectors[5] = vectors[1] + z;\n          vectors[6] = vectors[2] + z;\n          vectors[7] = vectors[3] + z;\n\n          for ( unsigned int i = 0;i < 8; ++i )\n          {\n            minValue = _mm_min_ps( minValue, vectors[i].sse() );\n            maxValue = _mm_max_ps( maxValue, vectors[i].sse() );\n          }\n        }\n\n        dp::math::Vec3f minVec, maxVec;\n        _MM_EXTRACT_FLOAT( minVec[0], minValue, 0);\n        _MM_EXTRACT_FLOAT( minVec[1], minValue, 1);\n        _MM_EXTRACT_FLOAT( minVec[2], minValue, 2);\n\n        _MM_EXTRACT_FLOAT( maxVec[0], maxValue, 0);\n        _MM_EXTRACT_FLOAT( maxVec[1], maxValue, 1);\n        _MM_EXTRACT_FLOAT( maxVec[2], maxValue, 2);\n\n        return dp::math::Box3f( minVec, maxVec );\n      }\n      else\n#elif defined(NEON)\n        if ( useNEON )\n        {\n          const GroupBitSetSharedPtr& groupImpl = std::static_pointer_cast<GroupBitSet>(group);\n\n          float32x4_t minValue = vdupq_n_f32( std::numeric_limits<float>::max() );\n          float32x4_t maxValue = vdupq_n_f32( -std::numeric_limits<float>::max() );\n\n          char const* basePtr = reinterpret_cast<char const*>(groupImpl->getMatrices());\n          for ( size_t index = 0;index < groupImpl->getObjectCount(); ++index )\n          {\n            const ObjectBitSetSharedPtr objectImpl = std::static_pointer_cast<ObjectBitSet>(groupImpl->getObject( index ));\n            dp::math::neon::Mat44f const& modelView = *reinterpret_cast<dp::math::neon::Mat44f const*>(basePtr + objectImpl->getTransformIndex() * groupImpl->getMatricesStride());\n            dp::math::Vec4f const& extent = objectImpl->getExtent();\n\n            dp::math::neon::Vec4f vectors[8];\n            vectors[0] = *reinterpret_cast<dp::math::neon::Vec4f const*>(&objectImpl->getLowerLeft()) * modelView;\n\n            dp::math::neon::Vec4f x( extent[0] * modelView[0] );\n            dp::math::neon::Vec4f y( extent[1] * modelView[1] );\n            dp::math::neon::Vec4f z( extent[2] * modelView[2] );\n\n            vectors[1] = vectors[0] + x;\n            vectors[2] = vectors[0] + y;\n            vectors[3] = vectors[1] + y;\n            vectors[4] = vectors[0] + z;\n            vectors[5] = vectors[1] + z;\n            vectors[6] = vectors[2] + z;\n            vectors[7] = vectors[3] + z;\n\n            for ( unsigned int i = 0;i < 8; ++i )\n            {\n              minValue = vminq_f32( minValue, vectors[i].neon() );\n              maxValue = vmaxq_f32( maxValue, vectors[i].neon() );\n            }\n\n          }\n\n          dp::math::Vec3f minVec, maxVec;\n\n          vst1q_lane_f32( &minVec[0], minValue, 0);\n          vst1q_lane_f32( &minVec[1], minValue, 1);\n          vst1q_lane_f32( &minVec[2], minValue, 2);\n\n          vst1q_lane_f32( &maxVec[0], maxValue, 0);\n          vst1q_lane_f32( &maxVec[1], maxValue, 1);\n          vst1q_lane_f32( &maxVec[2], maxValue, 2);\n\n          return dp::math::Box3f( minVec, maxVec );\n        }\n        else\n\n#endif\n      // CPU fallback\n      {\n        const GroupBitSetSharedPtr& groupImpl = std::static_pointer_cast<GroupBitSet>(group);\n\n        dp::math::Box4f boundingBox;\n\n        char const* basePtr = reinterpret_cast<char const*>(groupImpl->getMatrices());\n        for ( size_t index = 0;index < groupImpl->getObjectCount(); ++index )\n        {\n          const ObjectBitSetSharedPtr objectImpl = std::static_pointer_cast<ObjectBitSet>(groupImpl->getObject( index ));\n          dp::math::Mat44f const& modelView = reinterpret_cast<dp::math::Mat44f const&>(*(basePtr + objectImpl->getTransformIndex() * groupImpl->getMatricesStride()));\n          dp::math::Vec4f const& extent = objectImpl->getExtent();\n\n          dp::math::Vec4f vectors[8];\n          vectors[0] = (objectImpl->getLowerLeft() * modelView);\n\n          dp::math::Vec4f x( extent[0] * modelView.getPtr()[0], extent[0] * modelView.getPtr()[1], extent[0] * modelView.getPtr()[2], extent[0] * modelView.getPtr()[3] );\n          dp::math::Vec4f y( extent[1] * modelView.getPtr()[4], extent[1] * modelView.getPtr()[5], extent[1] * modelView.getPtr()[6], extent[1] * modelView.getPtr()[7] );\n          dp::math::Vec4f z( extent[2] * modelView.getPtr()[8], extent[2] * modelView.getPtr()[9], extent[2] * modelView.getPtr()[10], extent[2] * modelView.getPtr()[11] );\n\n          vectors[1] = vectors[0] + x;\n          vectors[2] = vectors[0] + y;\n          vectors[3] = vectors[1] + y;\n          vectors[4] = vectors[0] + z;\n          vectors[5] = vectors[1] + z;\n          vectors[6] = vectors[2] + z;\n          vectors[7] = vectors[3] + z;\n\n          for ( unsigned int i = 0;i < 8; ++i )\n          {\n            boundingBox.update( vectors[i] );\n          }\n        }\n\n        dp::math::Vec4f lower = boundingBox.getLower();\n        dp::math::Vec4f upper = boundingBox.getUpper();\n\n        return dp::math::Box3f( dp::math::Vec3f( lower[0], lower[1], lower[2]), dp::math::Vec3f( upper[0], upper[1], upper[2]));\n      }\n    }\n\n  } // namespace culling\n} // namespace dp\n", "meta": {"hexsha": "db1c7d35fd69db05a42e4719e4d131a49fe05a4b", "size": 12234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dp/culling/src/ManagerBitSet.cpp", "max_stars_repo_name": "siddharthuniv/nv-propipeline", "max_stars_repo_head_hexsha": "1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef", "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": "dp/culling/src/ManagerBitSet.cpp", "max_issues_repo_name": "siddharthuniv/nv-propipeline", "max_issues_repo_head_hexsha": "1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dp/culling/src/ManagerBitSet.cpp", "max_forks_repo_name": "siddharthuniv/nv-propipeline", "max_forks_repo_head_hexsha": "1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef", "max_forks_repo_licenses": ["BSD-3-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.3376205788, "max_line_length": 179, "alphanum_fraction": 0.6489292137, "num_tokens": 3245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25982563796098374, "lm_q2_score": 0.019719127315226487, "lm_q1q2_score": 0.005123534834712582}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2020 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014-2017 by Centre for Geoscience Computing (GeoComp)\n* Development from 2019 by School of Earth and Environmental Sciences\n**\n*****************************************************************************/\n\n#include \"FunctionSpace.h\" \n\n#include \"Data.h\" \n#include \"DataFactory.h\" \n#include \"FunctionSpaceException.h\"\n#include \"NullDomain.h\"\n\n#include <iostream>\n#include <sstream>\n#include <boost/smart_ptr.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nnamespace escript {\n\n  bool canInterpolate(FunctionSpace src, FunctionSpace dest)\n  {\n      return src.getDomain()->probeInterpolationOnDomain(src.getTypeCode(), dest.getTypeCode());\n  }\n\n\nnamespace {\n//\n// Create a null domain for use with any default-constructed function space\n// NullDomain const FunctionSpace::nullDomainValue;\nconst_Domain_ptr nullDomainValue(new NullDomain());\n}\n\nFunctionSpace::FunctionSpace():\n//   m_domain(static_cast<const AbstractDomain*>(&nullDomainValue)),\n  m_domain(nullDomainValue),\n  m_functionSpaceType(dynamic_cast<const NullDomain*>(nullDomainValue.get())->getFunctionCode())\n{\n}\n\n// FunctionSpace::FunctionSpace(const AbstractDomain& domain,\n//                              int functionSpaceType):\n// /*  m_domain(dynamic_cast<const AbstractDomain*>(&domain)),*/\n//   m_domain(domain.getPtr()),\n//   m_functionSpaceType(functionSpaceType)\n// {\n//   if (!m_domain->isValidFunctionSpaceType(functionSpaceType)) {\n//     std::stringstream temp;\n//     temp << \"Invalid function space type: \" << functionSpaceType \n// \t << \" for domain: \" << m_domain->getDescription();\n//     throw FunctionSpaceException(temp.str());\n//   }\n// }\n\nFunctionSpace::FunctionSpace(const_Domain_ptr domain,\n                             int functionSpaceType):\n/*  m_domain(dynamic_cast<const AbstractDomain*>(&domain)),*/\n  m_domain(domain),\n  m_functionSpaceType(functionSpaceType)\n{\n  if (!m_domain->isValidFunctionSpaceType(functionSpaceType)) {\n    std::stringstream temp;\n    temp << \"Invalid function space type: \" << functionSpaceType \n\t << \" for domain: \" << m_domain->getDescription();\n    throw FunctionSpaceException(temp.str());\n  }\n}\n\nFunctionSpace::FunctionSpace(const FunctionSpace& other)\n:m_domain(other.m_domain),\nm_functionSpaceType(other.m_functionSpaceType)\n{\n}\n\nstd::pair<int,DataTypes::dim_t>\nFunctionSpace::getDataShape() const\n{\n  return m_domain->getDataShape(m_functionSpaceType);\n}\n\nint\nFunctionSpace::getTypeCode() const \n{\n  return  m_functionSpaceType;\n}\n\n// const\n// AbstractDomain&\nconst_Domain_ptr\nFunctionSpace::getDomain() const\n{\n  return m_domain;\n}\n\nDomain_ptr\nFunctionSpace::getDomainPython() const\n{\n  // cast away the const-ness because python ignores it anyway\n  return const_pointer_cast<AbstractDomain>(m_domain);\n}\n\n\n\nstd::string\nFunctionSpace::toString() const\n{\n  std::stringstream temp;\n  temp << m_domain->functionSpaceTypeAsString(m_functionSpaceType)\n       << \" on \" << m_domain->getDescription();\n\n  return temp.str();\n}\n\n\n#ifdef DEBUG_PY_STRINGS\nPyObject *\nFunctionSpace::toPyString() const\n{\n  boost::python::to_python_value<const std::string &> cvtr;\n  std::stringstream temp;\n\n  temp << m_domain->functionSpaceTypeAsString(m_functionSpaceType)\n       << \" on \" << m_domain->getDescription();\n\n  return cvtr(temp.str());\n}\n#endif\n\n\nint\nFunctionSpace::getTagFromSampleNo(DataTypes::dim_t sampleNo) const\n{\n  return m_domain->getTagFromSampleNo(m_functionSpaceType,sampleNo);\n}\n\nint\nFunctionSpace::getTagFromDataPointNo(DataTypes::dim_t dataPointNo) const\n{\n  //\n  // Get the number of samples and data-points per sample\n  int numSamples = getNumSamples();\n  int numDataPointsPerSample = getNumDPPSample();\n  int numDataPoints = numSamples * numDataPointsPerSample;\n\n  if (numDataPointsPerSample==0) {\n    throw DataException(\"FunctionSpace::getTagFromDataPointNo error: no data-points associated with this object.\");\n  }\n\n  if (dataPointNo<0 || dataPointNo>=numDataPoints) {\n    throw DataException(\"FunctionSpace::getTagFromDataPointNo error: invalid data-point number supplied.\");\n  }\n\n  //\n  // Determine the sample number which corresponds to this data-point number\n  int sampleNo = dataPointNo / numDataPointsPerSample;\n\n  //\n  // Determine the tag number which corresponds to this sample number\n  int tagNo = getTagFromSampleNo(sampleNo);\n\n  //\n  // return the tag number\n  return(tagNo);\n}\n\nDataTypes::dim_t FunctionSpace::getReferenceIDFromDataPointNo(DataTypes::dim_t dataPointNo) const\n{\n     //\n     // Get the number of samples and data-points per sample\n    DataTypes::dim_t numSamples = getNumSamples();\n    int numDataPointsPerSample = getNumDPPSample();\n    const DataTypes::dim_t* referenceIDs= borrowSampleReferenceIDs();\n    DataTypes::dim_t numDataPoints = numSamples * numDataPointsPerSample;\n\n    if (numDataPointsPerSample==0) {\n        throw DataException(\"FunctionSpace::getReferenceIDFromDataPointNo error: no data-points associated with this object.\");\n    }\n    if (dataPointNo<0 || dataPointNo>numDataPoints) {\n        throw DataException(\"FunctionSpace::getReferenceIDFromDataPointNo error: invalid data-point number supplied.\");\n    }\n    DataTypes::dim_t sampleNo = dataPointNo / numDataPointsPerSample;\n    return referenceIDs[sampleNo];\n}\n\nconst DataTypes::dim_t*\nFunctionSpace::borrowSampleReferenceIDs() const\n{\n  return m_domain->borrowSampleReferenceIDs(m_functionSpaceType);\n}\n\n// FunctionSpace instances should not be overwritten to point to different domains/types\n// The only time this was actually used was in constructors and the copy constructor can deal with that\nFunctionSpace&\nFunctionSpace::operator=(const FunctionSpace& other)\n{\n  throw DataException(\"FunctionSpace::= should not be called. Programming Error.\");\n  // explicitly defined assignment operator to emphasise pointer copy\n/*  m_functionSpaceType=other.m_functionSpaceType;\n  m_domain=other.m_domain;\n  return *this;*/\n}\n\nbool\nFunctionSpace::operator==(const FunctionSpace& other) const\n{\n  return ((*(other.m_domain)==*(m_domain)) && (other.m_functionSpaceType==m_functionSpaceType));\n}\n\nbool\nFunctionSpace::operator!=(const FunctionSpace& other) const\n{\n  return !(operator==(other));\n}\n\nescript::Data\nFunctionSpace::getX() const \n{\n  Data out=escript::Vector(0,*this,true);\n  getDomain()->setToX(out);\n  out.setProtection();\n  return out;\n}\n\n#ifdef ESYS_HAVE_BOOST_NUMPY\nboost::python::numpy::ndarray \nFunctionSpace::getNumpyX() const\n{\n    // Initialise boost numpy\n    boost::python::numpy::initialize();\n\n    // Get the data\n    Data data=escript::Vector(0,*this,true);\n    getDomain()->setToX(data);\n    data.setProtection();\n\n    // This is needed below in getSampleDataRW\n    const DataTypes::real_t onlyreal = 0;\n\n    // Work out how many data points there are\n    int numDataPoints = data.getNumSamples();\n    int dpps = data.getNumDataPointsPerSample();\n\n    // Work out the data point shape\n    std::vector<int> shape = data.getDataPointShape();\n    \n    // Work out how many spatial dimensions there are\n    int dimensions = data.getShapeProduct();\n\n    // Initialise the ndarray\n    boost::python::tuple arrayshape = boost::python::make_tuple(dimensions, dpps * numDataPoints);\n    boost::python::numpy::dtype datatype = boost::python::numpy::dtype::get_builtin<double>();\n    boost::python::numpy::ndarray dataArray = boost::python::numpy::zeros(arrayshape, datatype);\n\n    // Initialise variables\n    std::string localmsg;\n    std::vector<const DataTypes::real_t*> samplesR(1);\n    \n// #pragma omp parallel for \n    for (int i = 0; i < numDataPoints; ++i) {\n        for (int j = 0; j < shape[0]; j++) {\n            dataArray[j][i] = *(data.getSampleDataRW(i, onlyreal)+j);\n        }\n    }\n\n    // Print out the ndarray to the console - used during debugging \n    // std::cout << \"Finished array:\\n\" << bp::extract<char const *>(bp::str(dataArray)) << std::endl;\n\n    return dataArray;\n}\n#endif\n\nescript::Data\nFunctionSpace::getNormal() const\n{\n  Data out=escript::Vector(0,*this,true);\n  getDomain()->setToNormal(out);\n  out.setProtection();\n  return out;\n}\n\nescript::Data\nFunctionSpace::getSize() const\n{\n  Data out=escript::Scalar(0,*this,true);\n  getDomain()->setToSize(out);\n  out.setProtection();\n  return out;\n}\n\nvoid\nFunctionSpace::setTags(const int newTag, const escript::Data& mask) const\n{\n   if (mask.getFunctionSpace()== *this) {\n          m_domain->setTags(m_functionSpaceType,newTag,mask);\n   } else {\n          throw FunctionSpaceException(\"illegal function space of mask.\");\n   }\n}\n\nvoid\nFunctionSpace::setTagsByString(const std::string& name, const escript::Data& mask) const\n{\n   int newTag=m_domain->getTag(name);\n   if (mask.getFunctionSpace()== *this) {\n          m_domain->setTags(m_functionSpaceType,newTag,mask);\n   } else {\n          throw FunctionSpaceException(\"illegal function space of mask.\");\n   }\n}\n\nint \nFunctionSpace::getNumberOfTagsInUse() const\n{\n   return  m_domain->getNumberOfTagsInUse(m_functionSpaceType);\n}\n\nconst int* FunctionSpace::borrowListOfTagsInUse() const\n{\n   return m_domain->borrowListOfTagsInUse(m_functionSpaceType);\n}\n\nstd::list<int> FunctionSpace::getListOfTagsSTL() const \n{\n  const int* tags=borrowListOfTagsInUse();\n  std::list<int> taglist(tags, tags+getNumberOfTagsInUse());\n  return taglist;\n}\n\n\nboost::python::list FunctionSpace::getListOfTags() const \n{\n  const int* tags=borrowListOfTagsInUse();\n  boost::python::list taglist;\n  for (int i=0; i<getNumberOfTagsInUse(); ++i)\n      taglist.append(tags[i]);\n  return taglist;\n}\n\nbool\nFunctionSpace::canTag() const\n{\n  return m_domain->canTag(m_functionSpaceType);\n}\n\nint \nFunctionSpace::getApproximationOrder() const\n{\n   return m_domain->getApproximationOrder(m_functionSpaceType);\n}\n\n}  // end of namespace\n\n", "meta": {"hexsha": "03ff52e81f875a1e162acaadeb203e95ae0e6c15", "size": 10133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "escriptcore/src/FunctionSpace.cpp", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "escriptcore/src/FunctionSpace.cpp", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "escriptcore/src/FunctionSpace.cpp", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6857923497, "max_line_length": 127, "alphanum_fraction": 0.7146945623, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032526, "lm_q2_score": 0.024423090453531766, "lm_q1q2_score": 0.005115896974403008}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n#include \"iqm.h\"\n\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <votca/ctp/logger.h>\n#include <votca/tools/constants.h>\n#include <votca/xtp/qminterface.h>\n#include <votca/xtp/qmpackagefactory.h>\n\nusing boost::format;\nusing namespace boost::filesystem;\n\nnamespace votca {\n  namespace xtp {\n\n    void IQM::Initialize(votca::tools::Property* options) {\n\n\n      _do_dft_input = false;\n      _do_dft_run = false;\n      _do_dft_parse = false;\n      _do_dftcoupling = false;\n      _do_gwbse = false;\n      _do_bsecoupling = false;\n\n      _store_dft = false;\n      _store_singlets = false;\n      _store_triplets = false;\n      _store_ehint = false;\n      ParseOptionsXML(*options);\n\n      // register all QM packages (Gaussian, turbomole, etc))\n      QMPackageFactory::RegisterAll();\n      return;\n    }\n\n    void IQM::ParseOptionsXML(votca::tools::Property &opt) {\n\n\n      // parsing general ibse options\n      string key = \"options.\" + Identify();\n      // _energy_difference = opt.get( key + \".degeneracy\" ).as< double > ();\n\n\n      // job tasks\n      string tasks_string = opt.get(key + \".tasks\").as<string> ();\n      if (tasks_string.find(\"input\") != std::string::npos) _do_dft_input = true;\n      if (tasks_string.find(\"dft\") != std::string::npos) _do_dft_run = true;\n      if (tasks_string.find(\"parse\") != std::string::npos) _do_dft_parse = true;\n      if (tasks_string.find(\"dftcoupling\") != std::string::npos) _do_dftcoupling = true;\n      if (tasks_string.find(\"gwbse\") != std::string::npos) _do_gwbse = true;\n      if (tasks_string.find(\"bsecoupling\") != std::string::npos) _do_bsecoupling = true;\n\n      // storage options\n      string store_string = opt.get(key + \".store\").as<string> ();\n      if (store_string.find(\"dft\") != std::string::npos) _store_dft = true;\n      if (store_string.find(\"singlets\") != std::string::npos) _store_singlets = true;\n      if (store_string.find(\"triplets\") != std::string::npos) _store_triplets = true;\n      if (store_string.find(\"ehint\") != std::string::npos) _store_ehint = true;\n\n\n      if (_do_dft_input || _do_dft_run || _do_dft_parse) {\n        string _package_xml = opt.get(key + \".dftpackage\").as<string> ();\n        load_property_from_xml(_dftpackage_options, _package_xml.c_str());\n        string dftname = \"package.name\";\n        _package = _dftpackage_options.get(dftname).as<string> ();\n      }\n\n      // read linker groups\n      string linker = opt.ifExistsReturnElseReturnDefault<string>(key + \".linker_names\", \"\");\n      Tokenizer toker(linker, \",\");\n      toker.ToVector(_linker_names);\n\n      if (_do_dftcoupling) {\n        _dftcoupling_options = opt.get(key + \".dftcoupling_options\");\n      }\n\n      if (_do_gwbse) {\n        string _gwbse_xml = opt.get(key + \".gwbse_options\").as<string> ();\n        load_property_from_xml(_gwbse_options, _gwbse_xml.c_str());\n      }\n      if (_do_bsecoupling) {\n        string _coupling_xml = opt.get(key + \".bsecoupling_options\").as<string>();\n        load_property_from_xml(_bsecoupling_options, _coupling_xml.c_str());\n      }\n\n\n      //options for parsing data into sql file   \n      key = \"options.\" + Identify() + \".readjobfile\";\n      if (opt.exists(key + \".singlet\")) {\n        string parse_string_s = opt.get(key + \".singlet\").as<string> ();\n        _singlet_levels = FillParseMaps(parse_string_s);\n      }\n      if (opt.exists(key + \".triplet\")) {\n        string parse_string_t = opt.get(key + \".triplet\").as<string> ();\n        _triplet_levels = FillParseMaps(parse_string_t);\n      }\n\n      if (opt.exists(key + \".hole\")) {\n        string parse_string_h = opt.get(key + \".hole\").as<string> ();\n        _hole_levels = FillParseMaps(parse_string_h);\n      }\n      if (opt.exists(key + \".electron\")) {\n        string parse_string_e = opt.get(key + \".electron\").as<string> ();\n        _electron_levels = FillParseMaps(parse_string_e);\n      }\n\n      // job file specification\n      key = \"options.\" + Identify();\n\n      if (opt.exists(key + \".job_file\")) {\n        _jobfile = opt.get(key + \".job_file\").as<string>();\n      } else {\n        throw std::runtime_error(\"Job-file not set. Abort.\");\n      }\n\n      return;\n    }\n\n    std::map<std::string, QMState> IQM::FillParseMaps(const string& Mapstring) {\n      Tokenizer split_options(Mapstring, \", \\t\\n\");\n      std::map<std::string, QMState> type2level;\n      for (const string& substring : split_options) {\n        std::vector<string> segmentpnumber;\n        Tokenizer tok(substring, \":\");\n        tok.ToVector(segmentpnumber);\n        if (segmentpnumber.size() != 2) {\n          throw runtime_error(\"Parser iqm: Segment and exciton labels:\" + substring + \"are not separated properly\");\n        }\n        QMState state=QMState(segmentpnumber[1]);\n        string segmentname = segmentpnumber[0];\n        type2level[segmentname] = state;\n      }\n      return type2level;\n    }\n\n    void IQM::addLinkers(std::vector< ctp::Segment* > &segments, ctp::Topology *top) {\n      ctp::Segment* seg1 = segments[0];\n      ctp::Segment* seg2 = segments[1];\n      int moleculeIdSeg1 = seg1->getMolecule()-> getId();\n      int moleculeIdSeg2 = seg2->getMolecule()-> getId();\n      if (moleculeIdSeg1 == moleculeIdSeg2) {// Check that both segments belong to the same molecule\n        int idSeg1 = seg1->getId();\n        int idSeg2 = seg2->getId();\n        std::vector<ctp::Segment*> segmentsInMolecule = top->getMolecule(moleculeIdSeg1)->Segments();\n        for (ctp::Segment* segment : segmentsInMolecule) {\n          int idIterator = segment->getId();\n          if (idIterator != idSeg1 && idIterator != idSeg2 && isLinker(segment->getName())) {\n            segments.push_back(segment);\n          }\n        }\n      }\n      return;\n    }\n\n    bool IQM::isLinker(const std::string& name) {\n      return (std::find(_linker_names.begin(), _linker_names.end(), name) != _linker_names.end());\n    }\n\n    void IQM::WriteCoordinatesToOrbitalsPBC(ctp::QMPair& pair, Orbitals& orbitals) {\n      ctp::Segment* seg1 = pair.Seg1();\n      ctp::Segment* seg2 = pair.Seg2();\n      ctp::Segment* ghost = NULL;\n      ctp::Topology* _top = seg1->getTopology();\n      ctp::vec r1 = seg1->getPos();\n      ctp::vec r2 = seg2->getPos();\n      ctp::vec _R = _top->PbShortestConnect(r1, r2); // => _R points from 1 to 2\n\n      // Check whether pair formed across periodic boundary\n      if (abs(r2 - r1 - _R) > 1e-8) {\n        ghost = new ctp::Segment(seg2);\n        //ghost->TranslateBy(r1 - r2 + _R); // DO NOT USE THIS METHOD !\n        for (ctp::Atom* atom : ghost->Atoms()) {\n          atom->setQMPos(atom->getQMPos() + r1 - r2 + _R);\n        }\n      }\n      std::vector< ctp::Segment* > segments;\n      segments.push_back(seg1);\n      if (ghost) {\n        segments.push_back(ghost);\n      } else {\n        segments.push_back(seg2);\n      }\n      QMInterface interface;\n      orbitals.QMAtoms() = interface.Convert(segments);\n      delete ghost;\n    }\n\n    void IQM::SetJobToFailed(ctp::Job::JobResult& jres, ctp::Logger* pLog, const string& errormessage) {\n      CTP_LOG(ctp::logERROR, *pLog) << errormessage << flush;\n      cout << *pLog;\n      jres.setError(errormessage);\n      jres.setStatus(ctp::Job::FAILED);\n    }\n    \n    void IQM::WriteLoggerToFile(const string& logfile, ctp::Logger& logger){\n      std::ofstream ofs;\n      ofs.open(logfile.c_str(), std::ofstream::out);\n      if (!ofs.is_open()) {\n        throw runtime_error(\"Bad file handle: \" + logfile);\n      }\n      ofs << logger << endl;\n      ofs.close();\n    }\n\n    ctp::Job::JobResult IQM::EvalJob(ctp::Topology *top, ctp::Job *job, ctp::QMThread *opThread) {\n\n      // report back to the progress observer\n      ctp::Job::JobResult jres = ctp::Job::JobResult();\n\n      string iqm_work_dir = \"OR_FILES\";\n      string eqm_work_dir = \"OR_FILES\";\n      string frame_dir = \"frame_\" + boost::lexical_cast<string>(top->getDatabaseId());\n\n      ctp::Logger* pLog = opThread->getLogger();\n\n      // get the information about the job executed by the thread\n      int job_ID = job->getId();\n      Property job_input = job->getInput();\n      list<Property*> segment_list = job_input.Select(\"segment\");\n      int ID_A = segment_list.front()->getAttribute<int>(\"id\");\n      string type_A = segment_list.front()->getAttribute<string>(\"type\");\n      int ID_B = segment_list.back()->getAttribute<int>(\"id\");\n      string type_B = segment_list.back()->getAttribute<string>(\"type\");\n\n      // set the folders \n      string pair_dir = (format(\"%1%%2%%3%%4%%5%\") % \"pair\" % \"_\" % ID_A % \"_\" % ID_B).str();\n       \n      boost::filesystem::path arg_path, arg_pathA, arg_pathB, arg_pathAB;\n      \n      string orbFileA = (arg_pathA / eqm_work_dir / \"molecules\" / frame_dir / (format(\"%1%_%2%%3%\") % \"molecule\" % ID_A % \".orb\").str()).c_str();\n      string orbFileB = (arg_pathB / eqm_work_dir / \"molecules\" / frame_dir / (format(\"%1%_%2%%3%\") % \"molecule\" % ID_B % \".orb\").str()).c_str();\n      string orbFileAB = (arg_pathAB / iqm_work_dir / \"pairs_iqm\" / frame_dir / (format(\"%1%%2%%3%%4%%5%\") % \"pair_\" % ID_A % \"_\" % ID_B % \".orb\").str()).c_str();\n      string orb_dir = (arg_path / iqm_work_dir / \"pairs_iqm\" / frame_dir).c_str();\n\n      ctp::Segment *seg_A = top->getSegment(ID_A);\n      ctp::Segment *seg_B = top->getSegment(ID_B);\n      ctp::QMNBList* nblist = &top->NBList();\n      ctp::QMPair* pair = nblist->FindPair(seg_A, seg_B);\n\n      CTP_LOG(ctp::logINFO, *pLog) << ctp::TimeStamp() << \" Evaluating pair \"\n              << job_ID << \" [\" << ID_A << \":\" << ID_B << \"] out of \" <<\n              (top->NBList()).size() << flush;\n\n      string package_append = _package + \"_\" + Identify();\n      std::vector< ctp::Segment* > segments;\n      segments.push_back(seg_A);\n      segments.push_back(seg_B);\n      string work_dir = (arg_path / iqm_work_dir / package_append / frame_dir / pair_dir).c_str();\n\n      if (_linker_names.size() > 0) {\n        addLinkers(segments, top);\n      }\n      Orbitals orbitalsAB;\n      // if a pair object is available and is not linked take into account PBC, otherwise write as is\n      if (pair == NULL || segments.size() > 2) {\n        if (pair == NULL) {\n          CTP_LOG(ctp::logWARNING, *pLog) << \"PBCs are not taken into account when writing the coordinate file!\" << flush;\n        }\n        QMInterface interface;\n        orbitalsAB.QMAtoms() = interface.Convert(segments);\n      } else {\n        WriteCoordinatesToOrbitalsPBC(*pair, orbitalsAB);\n      }\n\n      if (_do_dft_input || _do_dft_run || _do_dft_parse) {\n        string qmpackage_work_dir = (arg_path / iqm_work_dir / package_append / frame_dir / pair_dir).c_str();\n        \n        ctp::Logger dft_logger(ctp::logDEBUG);\n        dft_logger.setMultithreading(false);\n        dft_logger.setPreface(ctp::logINFO, (format(\"\\nDFT INF ...\")).str());\n        dft_logger.setPreface(ctp::logERROR, (format(\"\\nDFT ERR ...\")).str());\n        dft_logger.setPreface(ctp::logWARNING, (format(\"\\nDFT WAR ...\")).str());\n        dft_logger.setPreface(ctp::logDEBUG, (format(\"\\nDFT DBG ...\")).str());\n\n        QMPackage *qmpackage = QMPackages().Create(_package);\n        qmpackage->setLog(&dft_logger);\n        qmpackage->setRunDir(qmpackage_work_dir);\n        qmpackage->Initialize(_dftpackage_options);\n\n\n        // if asked, prepare the input files\n        if (_do_dft_input) {\n          boost::filesystem::create_directories(qmpackage_work_dir);\n          if (qmpackage->GuessRequested()) {\n            if (_linker_names.size() > 0) {\n              throw std::runtime_error(\"Error: You are using a linker and want \"\n                      \"to use a monomer guess for the dimer. These are mutually exclusive.\");\n            }\n\n            CTP_LOG(ctp::logINFO, *pLog) << \"Guess requested, reading molecular orbitals\" << flush;\n\n            if (qmpackage->getPackageName() == \"orca\") {\n              CTP_LOG(ctp::logINFO, *pLog) << \"Copying monomer .gbw files to pair folder\" << flush;\n              string gbwFileA = (arg_pathA / eqm_work_dir / \"molecules\" / frame_dir / (format(\"%1%_%2%%3%\") % \"molecule\" % ID_A % \".gbw\").str()).c_str();\n              string gbwFileB = (arg_pathB / eqm_work_dir / \"molecules\" / frame_dir / (format(\"%1%_%2%%3%\") % \"molecule\" % ID_B % \".gbw\").str()).c_str();\n              string gbwFileA_workdir = (qmpackage_work_dir / \"molA.gbw\").c_str();\n              string gbwFileB_workdir = (qmpackage_work_dir / \"molB.gbw\").c_str();\n              boost::filesystem::copy_file(gbwFileA, gbwFileA_workdir, boost::filesystem::copy_option::overwrite_if_exists);\n              boost::filesystem::copy_file(gbwFileB, gbwFileB_workdir, boost::filesystem::copy_option::overwrite_if_exists);\n            } else {\n              Orbitals orbitalsB;\n              Orbitals orbitalsA;\n\n              try {\n                orbitalsA.ReadFromCpt(orbFileA);\n              } catch (std::runtime_error& error) {\n                SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileA);\n                delete qmpackage;\n                return jres;\n              }\n\n              try {\n                orbitalsB.ReadFromCpt(orbFileB);\n              } catch (std::runtime_error& error) {\n                SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileB);\n                delete qmpackage;\n                return jres;\n              }\n              CTP_LOG(ctp::logDEBUG, *pLog) << \"Constructing the guess for dimer orbitals\" << flush;\n              orbitalsAB.PrepareDimerGuess(orbitalsA, orbitalsB);\n            }\n          } else {\n            CTP_LOG(ctp::logINFO, *pLog) << \"No Guess requested, starting from DFT starting Guess\" << flush;\n          }\n          qmpackage->WriteInputFile(orbitalsAB);\n        }\n\n        if (_do_dft_run) {\n          CTP_LOG(ctp::logDEBUG, *pLog) << \"Running DFT\" << flush;\n          bool _run_dft_status = qmpackage->Run(orbitalsAB);\n          if (!_run_dft_status) {\n            SetJobToFailed(jres, pLog, qmpackage->getPackageName() + \" run failed\");\n            delete qmpackage;\n            return jres;\n          }\n        }\n\n        if (_do_dft_parse) {\n          bool parse_log_status = qmpackage->ParseLogFile(orbitalsAB);\n          if (!parse_log_status) {\n            SetJobToFailed(jres, pLog, \"LOG parsing failed\");\n            delete qmpackage;\n            return jres;\n          }\n\n          bool parse_orbitals_status = qmpackage->ParseOrbitalsFile(orbitalsAB);\n\n          if (!parse_orbitals_status) {\n            SetJobToFailed(jres, pLog, \"Orbitals parsing failed\");\n            delete qmpackage;\n            return jres;\n          }\n\n        }// end of the parse orbitals/log\n        qmpackage->CleanUp();\n        delete qmpackage;\n        WriteLoggerToFile(work_dir + \"/dft.log\",dft_logger);\n      } else {\n        try {\n          orbitalsAB.ReadFromCpt(orbFileAB);\n        } catch (std::runtime_error& error) {\n          SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileAB);\n          return jres;\n        }\n      }\n      Property _job_summary;\n      Property &job_output = _job_summary.add(\"output\", \"\");\n      if (_do_dftcoupling) {\n        DFTcoupling dftcoupling;\n        dftcoupling.setLogger(pLog);\n        dftcoupling.Initialize(_dftcoupling_options);\n        Orbitals orbitalsB;\n        Orbitals orbitalsA;\n\n        try {\n          orbitalsA.ReadFromCpt(orbFileA);\n        } catch (std::runtime_error& error) {\n          SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileA);\n          return jres;\n        }\n\n        try {\n          orbitalsB.ReadFromCpt(orbFileB);\n        } catch (std::runtime_error& error) {\n          SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileB);\n          return jres;\n        }\n\n        try {\n          dftcoupling.CalculateCouplings(orbitalsA, orbitalsB, orbitalsAB);\n          dftcoupling.Addoutput(job_output, orbitalsA, orbitalsB);\n        } catch (std::runtime_error& error) {\n          std::string errormessage(error.what());\n          SetJobToFailed(jres, pLog, errormessage);\n          return jres;\n        }\n      }\n\n\n      // do excited states calculation\n      if (_do_gwbse) {\n        try {\n          CTP_LOG(ctp::logDEBUG, *pLog) << \"Running GWBSE\" << flush;\n          ctp::Logger gwbse_logger(ctp::logDEBUG);\n          gwbse_logger.setMultithreading(false);\n          gwbse_logger.setPreface(ctp::logINFO, (format(\"\\nGWBSE INF ...\")).str());\n          gwbse_logger.setPreface(ctp::logERROR, (format(\"\\nGWBSE ERR ...\")).str());\n          gwbse_logger.setPreface(ctp::logWARNING, (format(\"\\nGWBSE WAR ...\")).str());\n          gwbse_logger.setPreface(ctp::logDEBUG, (format(\"\\nGWBSE DBG ...\")).str());\n          GWBSE gwbse = GWBSE(orbitalsAB);\n          gwbse.setLogger(&gwbse_logger);\n          gwbse.Initialize(_gwbse_options);\n          gwbse.Evaluate();\n           WriteLoggerToFile(work_dir + \"/gwbse.log\", gwbse_logger);\n        } catch (std::runtime_error& error) {\n          std::string errormessage(error.what());\n          SetJobToFailed(jres, pLog, errormessage);\n          return jres;\n        }\n\n      } // end of excited state calculation, exciton data is in _orbitalsAB\n\n      // calculate the coupling\n\n\n      if (_do_bsecoupling) {\n        CTP_LOG(ctp::logDEBUG, *pLog) << \"Running BSECoupling\" << flush;\n        BSECoupling bsecoupling;\n        // orbitals must be loaded from a file\n        if (!_do_gwbse) {\n          try {\n            orbitalsAB.ReadFromCpt(orbFileAB);\n          } catch (std::runtime_error& error) {\n            SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileAB);\n            return jres;\n          }\n        }\n\n        Orbitals orbitalsB;\n        Orbitals orbitalsA;\n\n        try {\n          orbitalsA.ReadFromCpt(orbFileA);\n        } catch (std::runtime_error& error) {\n          SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileA);\n          return jres;\n        }\n\n        try {\n          orbitalsB.ReadFromCpt(orbFileB);\n        } catch (std::runtime_error& error) {\n          SetJobToFailed(jres, pLog, \"Do input: failed loading orbitals from \" + orbFileB);\n          return jres;\n        }\n\n        try {\n          ctp::Logger bsecoupling_logger(ctp::logDEBUG);\n          bsecoupling_logger.setMultithreading(false);\n          bsecoupling_logger.setPreface(ctp::logINFO, (format(\"\\nGWBSE INF ...\")).str());\n          bsecoupling_logger.setPreface(ctp::logERROR, (format(\"\\nGWBSE ERR ...\")).str());\n          bsecoupling_logger.setPreface(ctp::logWARNING, (format(\"\\nGWBSE WAR ...\")).str());\n          bsecoupling_logger.setPreface(ctp::logDEBUG, (format(\"\\nGWBSE DBG ...\")).str());\n          bsecoupling.setLogger(&bsecoupling_logger);\n          bsecoupling.Initialize(_bsecoupling_options);\n          bsecoupling.CalculateCouplings(orbitalsA, orbitalsB, orbitalsAB);\n          bsecoupling.Addoutput(job_output, orbitalsA, orbitalsB);\n          WriteLoggerToFile(work_dir + \"/bsecoupling.log\", bsecoupling_logger);\n        } catch (std::runtime_error& error) {\n          std::string errormessage(error.what());\n          SetJobToFailed(jres, pLog, errormessage);\n          return jres;\n        }\n\n      }\n\n      tools::PropertyIOManipulator iomXML(tools::PropertyIOManipulator::XML, 1, \"\");\n      stringstream sout;\n      sout << iomXML << _job_summary;\n      CTP_LOG(ctp::logINFO, *pLog) << ctp::TimeStamp() << \" Finished evaluating pair \" << ID_A << \":\" << ID_B << flush;\n      if (_store_dft || _store_singlets || _store_triplets || _store_ehint) {\n        boost::filesystem::create_directories(orb_dir);\n        CTP_LOG(ctp::logDEBUG, *pLog) << \"Saving orbitals to \" << orbFileAB << flush;\n        if (!_store_dft) {\n          orbitalsAB.AOVxc().resize(0, 0);\n          orbitalsAB.MOCoefficients().resize(0, 0);\n        }\n        if (!_store_singlets) {\n          orbitalsAB.BSESingletCoefficients().resize(0, 0);\n          orbitalsAB.BSESingletEnergies().resize(0, 0);\n        }\n        if (!_store_triplets) {\n          orbitalsAB.BSETripletCoefficients().resize(0, 0);\n          orbitalsAB.BSETripletEnergies().resize(0, 0);\n        }\n        if (!_store_ehint) {\n          orbitalsAB.eh_t().resize(0, 0);\n          orbitalsAB.eh_s().resize(0, 0);\n        }\n        orbitalsAB.WriteToCpt(orbFileAB);\n      } else {\n        CTP_LOG(ctp::logDEBUG, *pLog) << \"Orb file is not saved according to options \" << flush;\n      }\n\n      jres.setOutput(_job_summary);\n      jres.setStatus(ctp::Job::COMPLETE);\n\n      return jres;\n    }\n\n    void IQM::WriteJobFile(ctp::Topology * top) {\n\n      cout << endl << \"... ... Writing job file \" << flush;\n      std::ofstream ofs;\n      ofs.open(_jobfile.c_str(), std::ofstream::out);\n      if (!ofs.is_open()) throw runtime_error(\"\\nERROR: bad file handle: \" + _jobfile);\n\n      ctp::QMNBList &nblist = top->NBList();\n\n      int jobCount = 0;\n      if (nblist.size() == 0) {\n        cout << endl << \"... ... No pairs in neighbor list, skip.\" << flush;\n        return;\n      }\n\n      ofs << \"<jobs>\" << endl;\n      string tag = \"\";\n\n      for (ctp::QMPair* pair : nblist) {\n        if (pair->getType() == ctp::QMPair::Excitoncl) {\n          continue;\n        }\n        int id1 = pair->Seg1()->getId();\n        string name1 = pair->Seg1()->getName();\n        int id2 = pair->Seg2()->getId();\n        string name2 = pair->Seg2()->getName();\n        int id = pair->getId();\n        Property Input;\n        Property &pInput = Input.add(\"input\", \"\");\n        Property &pSegmentA = pInput.add(\"segment\", boost::lexical_cast<string>(id1));\n        pSegmentA.setAttribute<string>(\"type\", name1);\n        pSegmentA.setAttribute<int>(\"id\", id1);\n        Property & pSegmentB = pInput.add(\"segment\", boost::lexical_cast<string>(id2));\n        pSegmentB.setAttribute<string>(\"type\", name2);\n        pSegmentB.setAttribute<int>(\"id\", id2);\n        ctp::Job job(id, tag, Input, ctp::Job::AVAILABLE);\n        job.ToStream(ofs, \"xml\");\n      }\n      // CLOSE STREAM\n      ofs << \"</jobs>\" << endl;\n      ofs.close();\n      cout << endl << \"... ... In total \" << jobCount << \" jobs\" << flush;\n      return;\n    }\n\n    double IQM::GetDFTCouplingFromProp(tools::Property& dftprop, int stateA, int stateB) {\n      double J = 0;\n      double found=false;\n      for (Property* state : dftprop.Select(\"coupling\")) {\n        int state1 = state->getAttribute<int>(\"levelA\");\n        int state2 = state->getAttribute<int>(\"levelB\");\n        if (state1 == stateA && state2 == stateB) {\n          J = state->getAttribute<double>(\"j\");\n          found=true;\n          break;\n        }\n\n      }\n     if(found){\n      return J*J;\n      }else{\n        return -1;\n      }\n    }\n\n    double IQM::GetBSECouplingFromProp(tools::Property& bseprop,const QMState& stateA,const QMState& stateB) {\n      double J = 0;\n      std::string algorithm=bseprop.getAttribute<std::string>(\"algorithm\");\n      double found=false;\n      for (Property* state : bseprop.Select(\"coupling\")) {\n        QMState state1;\n        state1.FromString(state->getAttribute<std::string>(\"stateA\"));\n        QMState state2;\n        state2.FromString(state->getAttribute<std::string>(\"stateB\"));\n        if (state1 == stateA && state2 == stateB) {\n          J = state->getAttribute<double>(algorithm);\n          found=true;\n          break;\n        }\n      }\n      if(found){\n      return J*J;\n      }else{\n        return -1;\n      }\n    }\n    \n    \n    QMState IQM::GetElementFromMap(const std::map<std::string, QMState>& elementmap,const std::string& elementname )const{\n      QMState state;\n      try{\n        state = elementmap.at(elementname);\n      }\n      catch (std::out_of_range& error) {\n        std::string errormessage=\"Map does not have segment of type: \"+elementname;\n        errormessage+=\"\\n segments in map are:\";\n        for(const auto& s:elementmap){\n         errormessage+=\"\\n\\t\"+s.first;\n        }\n        throw std::runtime_error(errormessage);\n      }\n      return state;\n    }\n\n    void IQM::ReadJobFile(ctp::Topology * top) {\n      // gets the neighborlist from the topology\n      ctp::QMNBList &nblist = top->NBList();\n      int number_of_pairs = nblist.size();\n      int dft_h = 0;\n      int dft_e = 0;\n      int bse_s = 0;\n      int bse_t = 0;\n      int incomplete_jobs = 0;\n      ctp::Logger log;\n      log.setReportLevel(ctp::logINFO);\n        \n      Property xml;\n      // load the QC results in a vector indexed by the pair ID\n      load_property_from_xml(xml, _jobfile);\n      list<Property*> jobProps = xml.Select(\"jobs.job\");\n      vector<Property*> records = std::vector<Property*>(nblist.size() + 1, NULL);\n\n      // loop over all jobs = pair records in the job file\n      for (Property* job : jobProps) {\n        if (job->exists(\"status\")) {\n          if (job->get(\"status\").as<std::string>() != \"COMPLETE\" || !job->exists(\"output\")) {\n            incomplete_jobs++;\n            continue;\n          }\n        }\n\n        // get the output records\n        Property poutput = job->get(\"output\");\n        // job file is stupid, because segment ids are only in input have to get them out l\n        list<Property*> segmentprobs = job->Select(\"input.segment\");\n        vector<int> id;\n        for (Property* segment : segmentprobs) {\n          id.push_back(segment->getAttribute<int>(\"id\"));\n        }\n        if (id.size() != 2) throw std::runtime_error(\"Getting pair ids from jobfile failed, check jobfile.\");\n\n        double idA = id[0];\n        double idB = id[1];\n\n        // segments which correspond to these ids           \n        ctp::Segment *segA = top->getSegment(idA);\n        ctp::Segment *segB = top->getSegment(idB);\n        // pair that corresponds to the two segments\n        ctp::QMPair *qmp = nblist.FindPair(segA, segB);\n        // output using logger\n        \n        if (qmp == NULL) { // there is no pair in the neighbor list with this name\n          CTP_LOG_SAVE(ctp::logINFO, log) << \"No pair \" << idA << \":\" << idB << \" found in the neighbor list. Ignoring\" << flush;\n        } else {\n          records[qmp->getId()] = &(job->get(\"output\"));\n        }\n\n      } // finished loading from the file\n\n      for (ctp::QMPair *pair:top->NBList()) {\n\n        if (records[ pair->getId() ] == NULL) continue; //skip pairs which are not in the jobfile\n\n        ctp::Segment* segmentA = pair->Seg1();\n        ctp::Segment* segmentB = pair->Seg2();\n\n        ctp::QMPair::PairType ptype = pair->getType();\n        if (ptype != ctp::QMPair::PairType::Hopping\n                && ptype != ctp::QMPair::PairType::SuperExchangeAndHopping) {\n          cout << \"WARNING Pair \" << pair->getId() << \" is not of any of the \"\n                  \"Hopping or SuperExchangeAndHopping type. Skipping pair\" << flush;\n          continue;\n        }\n        \n        Property* pair_property = records[ pair->getId() ];\n\n        if (pair_property->exists(\"dftcoupling\")) {\n          tools::Property& dftprop = pair_property->get(\"dftcoupling\");\n          int homoA = dftprop.getAttribute<int>(\"homoA\");\n          int homoB = dftprop.getAttribute<int>(\"homoB\");\n          QMStateType hole=QMStateType(QMStateType::Hole);\n          if (dftprop.exists(hole.ToLongString())) {\n            tools::Property& holes = dftprop.get(hole.ToLongString());\n            QMState stateA = GetElementFromMap(_hole_levels,segmentA->getName());\n            QMState stateB = GetElementFromMap(_hole_levels,segmentB->getName());\n            int levelA = homoA - stateA.Index(); //h1 is is homo;\n            int levelB = homoB - stateB.Index();\n            double J2 = GetDFTCouplingFromProp(holes, levelA, levelB);\n            if(J2>0){\n              pair->setJeff2(J2, 1);\n              pair->setIsPathCarrier(true, 1);\n              dft_h++;\n            }\n          }\n          QMStateType electron=QMStateType(QMStateType::Electron);\n          if (dftprop.exists(electron.ToLongString())) {\n            tools::Property& electrons = dftprop.get(electron.ToLongString());\n            QMState stateA = GetElementFromMap(_electron_levels,segmentA->getName());\n            QMState stateB = GetElementFromMap(_electron_levels,segmentB->getName());\n            int levelA = homoA +1+stateA.Index(); //e1 is lumo;\n            int levelB = homoB +1+stateB.Index();\n            double J2 = GetDFTCouplingFromProp(electrons, levelA, levelB);\n            if(J2>0){\n              pair->setJeff2(J2, -1);\n              pair->setIsPathCarrier(true, -1);\n              dft_e++;\n            }\n          }\n        }\n        if (pair_property->exists(\"bsecoupling\")) {\n          tools::Property& bseprop = pair_property->get(\"bsecoupling\");\n          QMStateType singlet=QMStateType(QMStateType::Singlet);\n          if (bseprop.exists(singlet.ToLongString())) {\n            tools::Property& singlets = bseprop.get(singlet.ToLongString());\n            QMState stateA = GetElementFromMap(_singlet_levels,segmentA->getName());\n            QMState stateB = GetElementFromMap(_singlet_levels,segmentB->getName());\n            double J2 = GetBSECouplingFromProp(singlets, stateA, stateB);\n            if(J2>0){\n              pair->setJeff2(J2, 2);\n              pair->setIsPathCarrier(true, 2);\n              bse_s++;\n            }\n          }\n          QMStateType triplet=QMStateType(QMStateType::Triplet);\n          if (bseprop.exists(triplet.ToLongString())) {\n            tools::Property& triplets = bseprop.get(triplet.ToLongString());\n            QMState stateA = GetElementFromMap(_triplet_levels,segmentA->getName());\n            QMState stateB = GetElementFromMap(_triplet_levels,segmentB->getName());\n            double J2 = GetBSECouplingFromProp(triplets, stateA, stateB);\n            if(J2>0){\n              pair->setJeff2(J2, 3);\n              pair->setIsPathCarrier(true, 3);\n              bse_t++;\n            }\n          }\n        }\n\n      }\n\n      CTP_LOG_SAVE(ctp::logINFO, log) << \"Pairs [total:updated(e,h,s,t)] \"\n              << number_of_pairs << \":(\" << dft_e << \",\"<< dft_h << \",\" << bse_s<< \",\" << bse_t\n              << \") Incomplete jobs: \" << incomplete_jobs << flush;\n      cout<<std::endl;\n      cout << log;\n      return;\n    }\n\n  }\n};\n", "meta": {"hexsha": "ae435bc02e2ce701f63f5e0ae4f2a85ccbbf03a6", "size": 30810, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/jobcalculators/iqm.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/jobcalculators/iqm.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/jobcalculators/iqm.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4494238156, "max_line_length": 162, "alphanum_fraction": 0.5904251866, "num_tokens": 8259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561048974454574, "lm_q2_score": 0.03258974758481733, "lm_q1q2_score": 0.005087419204501253}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Coagulation class declared in the\n    swp_coagulation.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_PAH_primary.h\"\n#include \"swp_fragmentation.h\"\n#include \"swp_mechanism.h\"\n#include <stdexcept>\n#include <iostream>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::Processes;\nusing namespace std;\n\n// Base coagulation class.\n\n/*!\n * @param[in]   mech    Mechanism to which this process should look for services like LPDA\n *\n * Default rate scaling to 1 for backwards compatibility\n */\n Fragmentation::Fragmentation(const Sweep::Mechanism &mech)\n : Process(mech)\n , mPositionChoice(NoPositionChoice)\n {}\n\n/*!\n * @param[in]       t       Time at which rates are to be calculated\n * @param[in]       sys     System for which rates are to be calculated\n * @param[in]       local_geom  Spatial configuration information\n * @param[in]       coags   Coagulation processes defining the rates\n * @param[in,out]   rates   Vector to which to add the rates of the individual coagulations\n * @param[in]       start   Position in rates at which to start inserting rates\n *\n * @return      Total rate of all the coagulation processes\n */\ndouble Fragmentation::CalcRates(double t, const Cell &sys, const Geometry::LocalGeometry1d &local_geom,\n                            const FragPtrVector &frags, fvector &rates, unsigned int start)\n{\n    // Iterators for the coagulation processes\n    FragPtrVector::const_iterator itFrag = frags.begin();\n    const FragPtrVector::const_iterator itFragEnd = frags.end();\n\n    // Iterator for the rate vector\n    fvector::iterator it = (rates.begin()+start);\n\n    // Use this variable to accumulate the overall sum of the rates\n    double sum = 0.0;\n    while(itFrag != itFragEnd) {\n        // Store the rate and move on to the next coagulation process\n        *it = (*itFrag++)->Rate(t, sys, local_geom);\n\n        // Add the rate to the sum and move the rates vector iterator onto the next position\n        sum += *it++;\n    }\n    return sum;\n}\n\n/*!\n * @param[in]       t       Time at which rates are to be calculated\n * @param[in]       sys     System for which rates are to be calculated\n * @param[in]       local_geom  Spatial configuration information\n * @param[in]       coags   Coagulation processes defining the rates\n * @param[in,out]   iterm   Iterator to point at which to put rate terms of the individual coagulations\n *\n * @return      Total rate of all the coagulation processes\n */\ndouble Fragmentation::CalcRateTerms(double t, const Cell &sys, const Geometry::LocalGeometry1d &local_geom,\n                                const FragPtrVector &frags, fvector::iterator &iterm) {\n    // Iterators for the coagulation processes\n    FragPtrVector::const_iterator itFrag = frags.begin();\n    const FragPtrVector::const_iterator itFragEnd = frags.end();\n\n    // Use this variable to accumulate the overall sum of the rates\n    double sum = 0.0;\n    while(itFrag != itFragEnd) {\n        // The next line does three things, effectively in the following order\n        // i) Calls RateTerms on *itCoag\n        // ii) Advances itCoag\n        // iii) Adds the return value of RateTerms to sum\n        // Note that the order of 2 and 3 could be reversed without having any effect\n        sum += (*itFrag++)->RateTerms(t, sys, local_geom, iterm);\n    }\n    return sum;\n }\n\n/*!\n *@param[in]        t           Time at which coagulation is being performed\n *@param[in]        ip1         Index of first particle in ensemble\n *@param[in,out]    sp1         Pointer to first particle\n *@param[in]        ip2         Index of second particle in ensemble\n *@param[in,out]    sp2         Pointer to second particle\n *@param[in]        sys         Cell containing particles that are coagulating\n *@param[in,out]    rng         Random number generator\n *\n *@return       Index of new, larger particle\n */\nint Fragmentation::JoinParticles(const double t, const int ip1, Particle *sp1,\n                               const int ip2, Particle *sp2,\n                               Cell &sys, rng_type &rng) const {\n\n    // Position for particle after coagulation, default is to take whatever happens\n    // to be in sp1\n    double newPos = sp1->getPosition();\n    double newPosTime = sp1->getPositionTime();\n    if(mPositionChoice == UniformPositionChoice) {\n        // Change to position of sp2 with prob 0.5 (bernoulli distribution defaults to prob 0.5)\n        boost::bernoulli_distribution<> bernoulliDistrib;\n        boost::variate_generator<rng_type &, boost::bernoulli_distribution<> > positionChooser(rng, bernoulliDistrib);\n        if(positionChooser()) {\n            newPos = sp2->getPosition();\n            newPosTime = sp2->getPositionTime();\n        }\n    }\n    else if (mPositionChoice == MassPositionChoice) {\n        // Change to position of sp2 with prob sp2->Mass()/(sp1->Mass() + sp2->Mass())\n        boost::bernoulli_distribution<double> bernoulliDistrib(sp2->Mass()/(sp1->Mass() + sp2->Mass()));\n        boost::variate_generator<rng_type &, boost::bernoulli_distribution<double> > positionChooser(rng, bernoulliDistrib);\n\n        if(positionChooser()) {\n            newPos = sp2->getPosition();\n            newPosTime = sp2->getPositionTime();\n        }\n    }\n    else if (mPositionChoice == LargestMassPositionChoice) {\n        // Change to position of particle with largest mass (default to first particle if masses equal)\n        if(sp1->Mass() < sp2->Mass()) {\n            newPos = sp2->getPosition();\n            newPosTime = sp2->getPositionTime();\n        }\n        else {\n            newPos = sp1->getPosition();\n            newPosTime = sp1->getPositionTime();\n        }\n    }\n    else if (mPositionChoice == MidpointPositionChoice) {\n        // Pick the half way point\n        newPos = (sp1->getPosition() + sp2->getPosition()) / 2;\n        newPosTime = (sp1->getPositionTime() + sp2->getPositionTime()) / 2;\n    }\n    else if (mPositionChoice == CentreOfMassPositionChoice) {\n        const double m1 = sp1->Mass();\n        const double m2 = sp2->Mass();\n        newPos = (m1 * sp1->getPosition() + m2 * sp2->getPosition()) / (m1 + m2);\n        newPosTime = (m1 * sp1->getPositionTime() + m2 * sp2->getPositionTime()) / (m1 + m2);\n    }\n\n\n    //sys.Particles().SetNumOfInceptedPAH(-1,sp1->Primary());\n\n    // Add contents of particle 2 onto particle 1\n    sp1->Fragment(*sp2, rng);\n    sp1->setPositionAndTime(newPos, newPosTime);\n    sp1->SetTime(t);\n    sp1->incrementFragCount();\n\n    // Tell the ensemble that particle 1 has changed\n    sys.Particles().Update(ip1);\n    // Particle 2 is now part of particle 1\n    sys.Particles().Remove(ip2, true);\n    return ip1;\n}\n\n/*!\n *@param[in]        t           Time at which coagulation is being performed\n *@param[in]        prop1       Rule for choosing first particle\n *@param[in]        prop2       Rule for choosing second particle\n *@param[in]        weight_rule Specify how to combine particle weights\n *@param[in,out]    sys         Cell containing particles that are coagulating\n *@param[in,out]    rng         Random number generator\n *@param[in]        maj         Specify which majorant to use\n *\n *@return       Negative on failure, 0 on success\n *\n * Weighted coagulation is not symmetric, nothing happens to the second particle,\n * it simply defined a size increment for the first particle.\n */\nint Fragmentation::WeightedPerform(const double t, const Sweep::PropID prop,\n                                 const Sweep::Processes::FragWeightRule weight_rule,\n                                 Cell &sys, rng_type &rng,\n                                 MajorantType maj) const {\n\tPartPtrVector dummy;\n\n    int i = -1;\n    i = sys.Particles().Select(m_pid, rng);\n    if (i >= 0) {\n        Particle *sp = sys.Particles().At(i);\n        std::vector<double> m_dcomp(1);\n        std::vector<double> m_dvals(1);\n        m_dvals[0] = 0.0;\n        if (m_mech->AnyDeferred()) {\n            m_mech->UpdateParticle(*sp, sys, t, i, rng, dummy);\n            if (sp->IsValid()) {\n                double majk = MajorantKernel(*sp, sys, Default);\n                double truek = FragKernel(*sp, sys);\n                if (!Fictitious(majk, truek, rng)) {\n                    switch(weight_rule) {\n                        case Sweep::Processes::FragWeightSymmetric :\n                            sp->setStatisticalWeight(2 * sp->getStatisticalWeight());\n                            m_dcomp[0] = - sp->NumCarbon() / 2;\n                            break;\n                        case Sweep::Processes::FragWeightNumber:\n                            sp->setStatisticalWeight(sp->getStatisticalWeight() + 1);\n                            m_dcomp[0] = - 1.0;\n                            break;\n                        case Sweep::Processes::FragWeightMass:\n                            sp->setStatisticalWeight(sp->getStatisticalWeight() * sp->NumCarbon() / ( sp->NumCarbon() - 1));\n                            m_dcomp[0] = - 1.0;\n                            break;\n                        default:\n                            throw std::logic_error(\"Unrecognised weight rule (Fragmentation::WeightedPerform)\");\n                    }\n                    sp->Adjust(m_dcomp, m_dvals, rng, 1);\n                    sys.Particles().Update(i);\n                    sp->SetTime(t);\n                    sp->incrementFragCount();\n                }\n            } else {\n                sys.Particles().Remove(i);\n            }\n        } else {\n            switch(weight_rule) {\n                case Sweep::Processes::FragWeightSymmetric :\n                    sp->setStatisticalWeight(2 * sp->getStatisticalWeight());\n                    m_dcomp[0] = - sp->NumCarbon() / 2;\n                    break;\n                case Sweep::Processes::FragWeightNumber:\n                    sp->setStatisticalWeight(sp->getStatisticalWeight() + 1);\n                    m_dcomp[0] = - 1.0;\n                    break;\n                case Sweep::Processes::FragWeightMass:\n                    sp->setStatisticalWeight(sp->getStatisticalWeight() * sp->NumCarbon() / ( sp->NumCarbon() - 1));\n                    m_dcomp[0] = - 1.0;\n                    break;\n                default:\n                    throw std::logic_error(\"Unrecognised weight rule (Fragmentation::WeightedPerform)\");\n            }\n            sp->Adjust(m_dcomp, m_dvals, rng, 1);\n            sys.Particles().Update(i);\n            sp->SetTime(t);\n            sp->incrementFragCount();\n        }\n    } else {\n        return -1;\n    }\n    return 0;\n}\n\n// Writes the object to a binary stream.\nvoid Fragmentation::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Output position choice rule\n        out.write(reinterpret_cast<const char*>(&mPositionChoice), sizeof(mPositionChoice));\n\n        // Serialize base class.\n        Process::Serialize(out);\n\n    } else {\n        throw invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, Fragmentation::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid Fragmentation::Deserialize(std::istream &in, const Sweep::Mechanism &mech)\n{\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        switch (version) {\n            case 0:\n                in.read(reinterpret_cast<char*>(&mPositionChoice), sizeof(mPositionChoice));\n\n                // Deserialize base class.\n                Process::Deserialize(in, mech);\n\n                break;\n            default:\n                throw runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, Fragmentation::Deserialize).\");\n        }\n    } else {\n        throw invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, Fragmentation::Deserialize).\");\n    }\n}\n\n\n//==============================================================\n", "meta": {"hexsha": "268bd5ceb69ef4a31d5e883a072392c4f009cdb0", "size": 13517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_fragmentation.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_fragmentation.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_fragmentation.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 39.8731563422, "max_line_length": 124, "alphanum_fraction": 0.5970999482, "num_tokens": 3122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2337063569140403, "lm_q2_score": 0.02161533366865044, "lm_q1q2_score": 0.005051640885181692}}
{"text": "/*\n * Copyright (c) 2018 Eliane Briand\n *\n * This file is part of SmolDock.\n *\n * SmolDock is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SmolDock is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SmolDock.  If not, see <https://www.gnu.org/licenses/>.\n *\n */\n\n#include <memory>\n#include <cmath>\n#include <boost/log/trivial.hpp>\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/count.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n\n#include <Utilities/TimingsLog.h>\n\n#include \"Protein.h\"\n#include \"Atom.h\"\n\n#include \"Structures/Common/ResiduePropertiesAssignation.h\"\n#include \"Structures/Common/PDBResiduePropertiesTable.h\"\n\nnamespace SmolDock {\n\n    void Protein::populateFromESBTLSystems(std::string friendlyName,\n            std::vector<ESBTL::Default_system>& systems,\n            std::vector<std::shared_ptr<InputModifier::InputModifier> > modifiers)\n    {\n        if (systems.empty() || systems[0].has_no_model()) {\n            BOOST_LOG_TRIVIAL(error) << \"No atoms found in protein PDB\";\n            std::exit(-1);\n        }\n\n        /*\n         * For reference purpose, the hierarchy of the PDB file reading is :\n         * System (defined by ESBTL, like input filter in some ways)\n         * Model (PDB-file specification : more or less, protein)\n         * Chain (Amino acid chain)\n         * Residue (=Amino acid)\n         * Atom\n         *\n         * Heteroatoms (Cl, or crystallographic ions) are mixed in at the residue level.\n         * We detect those if residueName is not in {set of defined residueName}\n         * TODO : Differentiate between legit biological ions (metalloprotein, ...) and crystallographic heavy atoms\n         */\n\n        unsigned int total_nb_model = 0, total_nb_chain = 0, total_nb_atom = 0, total_nb_hetatm = 0, total_nb_residue = 0;\n\n        using namespace boost::accumulators;\n        accumulator_set<double, stats<tag::mean, tag::count, tag::min, tag::max> > acc_x, acc_y, acc_z;\n        accumulator_set<double, stats<tag::mean, tag::max> > acc_distance;\n\n        //Iterate over all models in the first system\n        for (ESBTL::Default_system::Models_iterator\n                     it_model = systems[0].models_begin();\n             it_model != systems[0].models_end();\n             ++it_model) {\n\n            const ESBTL::Default_system::Model &model = *it_model;\n            total_nb_model++;\n\n            // Iterating over chains\n            for (ESBTL::Default_system::Model::Chains_const_iterator it_ch = model.chains_begin();\n                 it_ch != model.chains_end(); ++it_ch) {\n\n                total_nb_chain++;\n\n                // Iterating over residues in the chain\n                for (ESBTL::Default_system::Chain::Residues_const_iterator it_res = it_ch->residues_begin();\n                     it_res != it_ch->residues_end(); ++it_res) {\n                    total_nb_residue++;\n\n                    if (stringToResType(it_res->residue_name()) == AminoAcid::AAType::unknown) {\n                        // We have an heteroatom\n                        this->heteroatoms.emplace_back(std::make_shared<Atom>(it_res->residue_name()));\n                        total_nb_hetatm++;\n                        total_nb_atom++;\n                        continue;\n                    }\n\n                    // else : It's a normal residue\n                    auto current_residue = this->aminoacids.emplace_back(\n                            std::make_shared<AminoAcid>(it_res->residue_name())\n                    );\n\n\n                    current_residue->setAAId(it_res->residue_sequence_number());\n\n                    accumulator_set<double, stats<tag::mean, tag::count, tag::min, tag::max> > acc_res_x, acc_res_y, acc_res_z;\n                    accumulator_set<double, stats<tag::mean, tag::max> > acc_res_distance;\n\n                    // Iterate over atoms in the residue\n                    for (ESBTL::Default_system::Residue::Atoms_const_iterator it_atm = it_res->atoms_begin();\n                         it_atm != it_res->atoms_end(); ++it_atm) {\n\n                        BOOST_ASSERT(it_atm->is_hetatm() ==\n                               0); // We expect heteroatoms to have been taken care of previously\n\n\n                        total_nb_atom++;\n\n                        auto current_atom = current_residue->atoms.emplace_back(\n                                std::shared_ptr<Atom>(new Atom(it_atm->atom_name(), true /* use PDB format */,\n                                                               stringToResType(it_res->residue_name())))\n                        );\n\n                        current_atom->setAtomPosition(std::make_tuple(it_atm->x(), it_atm->y(), it_atm->z()));\n                        current_atom->setCharge(static_cast<double>(it_atm->charge()));\n\n                        double distance = std::sqrt(\n                                std::pow(it_atm->x(), 2) + std::pow(it_atm->y(), 2) + std::pow(it_atm->z(), 2));\n                        acc_distance(distance);\n                        acc_x(it_atm->x());\n                        acc_y(it_atm->y());\n                        acc_z(it_atm->z());\n\n\n                        acc_res_x(it_atm->x());\n                        acc_res_y(it_atm->y());\n                        acc_res_z(it_atm->z());\n\n\n                    }\n\n\n                    current_residue->centroid[0] = mean(acc_res_x);\n                    current_residue->centroid[1] = mean(acc_res_y);\n                    current_residue->centroid[2] = mean(acc_res_z);\n\n                    for (ESBTL::Default_system::Residue::Atoms_const_iterator it_atm = it_res->atoms_begin();\n                         it_atm != it_res->atoms_end(); ++it_atm) {\n                        double distance_to_centroid = std::sqrt(\n                                std::pow(current_residue->centroid[0] - it_atm->x(), 2) +\n                                std::pow(current_residue->centroid[1] - it_atm->y(), 2) +\n                                std::pow(current_residue->centroid[2] - it_atm->z(), 2));\n                        acc_res_distance(distance_to_centroid);\n\n                    }\n\n                    current_residue->maxDistanceFromCentroid = max(acc_res_distance);\n\n\n                    assignPropertiesForResidueAtom(*current_residue,\n                                                   PDBResidueVariantAssignationType::GeneralPurpose);\n\n                }\n            }\n\n\n            // Post processing\n            for (auto modifier : modifiers) {\n                for (auto &residue: aminoacids) {\n                    for (auto &atom: residue->atoms) {\n                        modifier->postProcessAtomFromProtein(*atom, *residue);\n                    }\n                }\n            }\n\n\n            this->center_x = mean(acc_x);\n            this->center_y = mean(acc_y);\n            this->center_z = mean(acc_z);\n\n            this->min_x = min(acc_x);\n            this->min_y = min(acc_y);\n            this->min_z = min(acc_z);\n\n            this->max_x = max(acc_x);\n            this->max_y = max(acc_y);\n            this->max_z = max(acc_z);\n\n            this->max_distance_to_center = max(acc_distance);\n\n\n            BOOST_LOG_TRIVIAL(info) << \"Loaded protein : \" << friendlyName;\n            BOOST_LOG_TRIVIAL(info) << \"  --> \" << total_nb_model\n                                    << \" models, \"\n                                    << total_nb_chain << \" chains, \" << total_nb_residue << \" residues, \"\n                                    << total_nb_atom << \" atoms (\" << total_nb_hetatm << \" heteroatoms)\";\n\n#ifdef SMOLDOCK_VERBOSE_DEBUG\n            BOOST_LOG_TRIVIAL(debug) << \"Protein centered on : (\"\n                                     << this->center_x << \", \" << this->center_y << \", \" << this->center_z\n                                     << \") [n=\" <<\n                                     count(acc_x) << \"]\";\n#endif\n\n        }\n    }\n\n\n    bool Protein::populateFromPDB(const std::string &filename,\n                                  std::vector<std::shared_ptr<InputModifier::InputModifier> > modifiers) {\n\n\n\n        // Read all non-water atoms/stuff and water in two separate system\n        // TODO : do something with the water or switch to one system\n        ESBTL::PDB_line_selector_two_systems sel;\n\n        std::vector<ESBTL::Default_system> systems;\n\n\n        ESBTL::All_atom_system_builder<ESBTL::Default_system> builder(systems, sel.max_nb_systems());\n\n\n        if (ESBTL::read_a_pdb_file(filename, sel, builder,\n                                   ESBTL::Accept_none_occupancy_policy<ESBTL::PDB::Line_format<> >())) {\n            this->populateFromESBTLSystems(filename, systems,modifiers);\n\n        } else {\n            BOOST_LOG_TRIVIAL(error) << \"Could not load protein PDB file: \" << filename;\n            return false;\n        }\n\n        return true;\n    }\n\n    bool Protein::populateFromPDBString(const std::string &PDB_Block,\n                                  std::vector<std::shared_ptr<InputModifier::InputModifier> > modifiers) {\n\n        ESBTL::PDB_line_selector_two_systems sel;\n        std::vector<ESBTL::Default_system> systems;\n        ESBTL::All_atom_system_builder<ESBTL::Default_system> builder(systems, sel.max_nb_systems());\n\n        std::istringstream inputStream(PDB_Block);\n\n        if (ESBTL::Line_reader<ESBTL::PDB::Line_format<>,\n                ESBTL::PDB_line_selector_two_systems,\n                ESBTL::All_atom_system_builder<ESBTL::Default_system>>(sel,builder)\n                .read_stream(inputStream,\n                        ESBTL::Accept_none_occupancy_policy<ESBTL::PDB::Line_format<> >())\n            ) {\n            this->populateFromESBTLSystems(\"DirectStringInput\", systems,modifiers);\n\n        } else {\n            BOOST_LOG_TRIVIAL(error) << \"Could not load protein from PDB block string \";\n            return false;\n        }\n\n        return true;\n    }\n\n    iProtein Protein::getiProtein() const {\n        iProtein prot;\n\n        prot.center_x = this->center_x;\n        prot.center_y = this->center_y;\n        prot.center_z = this->center_z;\n\n        prot.radius = this->max_distance_to_center;\n\n\n        for (auto &residue: this->aminoacids) {\n            unsigned long size_before = prot.x.size();\n            residue->filliProtein(prot, true /* Skip hydrogen */);\n            unsigned long size_after = prot.x.size();\n\n            // Visual demo :\n            //\n            // index\n            //\n            // size 0\n            //\n            // index    0   1\n            //         [A] [A]   For residue A : <begin_idx, end_idx> = <0,1> = <size_before, size_after -1>\n            // size 0 > 1 > 2\n            //\n            // index    0   1   2   3   4\n            //         [A] [A] [B] [B] [B] For residue B : <begin_idx, end_idx> = <2,4> = <size_before, size_after -1>\n            // size 0 > 1 > 2 > 3 > 4 > 5\n            //\n            // The size_before gives us the index of the first atom that belongs to this residue\n            // The size_after lags behind by one.\n            // This works even if there is only one atom added (then begin_idx = end_idx = size_before = size_after-1)\n            // However there is an edge case : when the residue has no atom, this is incorrect, so :\n            BOOST_ASSERT(size_after > size_before); // At least one atom added\n\n            prot.AAId_to_AtomPositionInVect[residue->getAAId()] = std::make_tuple(size_before, size_after - 1);\n        }\n        if(prot.x.size() == 0)\n        {\n            BOOST_LOG_TRIVIAL(error) << \"The iProtein being generated has 0 atoms. Check your docking box settings.\";\n            std::terminate();\n        }\n        return prot;\n    }\n\n    double Protein::getMaxRadius() const {\n        return this->max_distance_to_center;\n    }\n\n    iProtein Protein::getPartialiProtein_sphere(std::array<double, 3> center, double radius, double margin) const {\n        iProtein prot;\n\n        prot.radius = radius;\n\n        prot.center_x = center[0];\n        prot.center_y = center[1];\n        prot.center_z = center[2];\n\n\n        for (auto &residue: this->aminoacids) {\n\n            double distanceToGivenCenter = std::sqrt(\n                    std::pow(residue->centroid[0] - center[0], 2) +\n                    std::pow(residue->centroid[1] - center[1], 2) +\n                    std::pow(residue->centroid[2] - center[2], 2));\n\n            if (distanceToGivenCenter > (radius + margin)) {\n                continue;\n            }\n\n\n            unsigned long size_before = prot.x.size();\n            residue->filliProtein(prot, true /* Skip hydrogen */);\n            unsigned long size_after = prot.x.size();\n\n            // Visual demo :\n            //\n            // index\n            //\n            // size 0\n            //\n            // index    0   1\n            //         [A] [A]   For residue A : <begin_idx, end_idx> = <0,1> = <size_before, size_after -1>\n            // size 0 > 1 > 2\n            //\n            // index    0   1   2   3   4\n            //         [A] [A] [B] [B] [B] For residue B : <begin_idx, end_idx> = <2,4> = <size_before, size_after -1>\n            // size 0 > 1 > 2 > 3 > 4 > 5\n            //\n            // The size_before gives us the index of the first atom that belongs to this residue\n            // The size_after lags behind by one.\n            // This works even if there is only one atom added (then begin_idx = end_idx = size_before = size_after-1)\n            // However there is an edge case : when the residue has no atom, this is incorrect, so :\n            BOOST_ASSERT(size_after > size_before); // At least one atom added\n\n            prot.AAId_to_AtomPositionInVect[residue->getAAId()] = std::make_tuple(size_before, size_after - 1);\n        }\n        if(prot.x.size() == 0)\n        {\n            BOOST_LOG_TRIVIAL(error) << \"The iProtein being generated has 0 atoms. Check your docking box settings.\";\n            std::terminate();\n        }\n        return prot;\n    }\n\n    bool Protein::applySpecialResidueTyping(AminoAcid::AAType resType,\n                                            unsigned int serialNumber,\n                                            SpecialResidueTyping specialType,\n                                            const bool ignoreMismatchingResType) {\n        if(serialNumber == 0)\n        {\n            BOOST_LOG_TRIVIAL(error) << \"applySpecialResidueTyping : Cannot find residue number 0 : residue numbering starts at 1.\";\n            return false;\n        }\n        if(this->aminoacids.size() < serialNumber)\n        {\n            BOOST_LOG_TRIVIAL(error) << \"Attempting to apply special typing to residue #\" << serialNumber << \"but protein only has \" <<this->aminoacids.size();\n            return false;\n        }\n\n        auto itFoundResidue = std::find_if(std::begin(this->aminoacids),\n                std::end(this->aminoacids),\n                [serialNumber](const std::shared_ptr<AminoAcid>& elem){\n            return elem->getAAId() == serialNumber;\n        });\n\n        if(itFoundResidue == std::end(this->aminoacids))\n        {\n            BOOST_LOG_TRIVIAL(error) << \"Cannot find amino acid #\" << serialNumber;\n            return false;\n        }\n\n        auto residue = *itFoundResidue;\n\n        if(residue->getType() != resType)\n        {\n            if(!ignoreMismatchingResType)\n            {\n                BOOST_LOG_TRIVIAL(error) << \"Attempting to apply special typing to residue \" << resTypeToString(resType) <<\n                                         \" #\" << serialNumber << \" but this residue is actually a \" << resTypeToString(residue->getType());\n                return false;\n            }else {\n                BOOST_LOG_TRIVIAL(warning) << \"Attempting to apply special typing to residue \" << resTypeToString(resType) <<\n                                         \" #\" << serialNumber << \" but this residue is actually a \" << resTypeToString(residue->getType());\n                BOOST_LOG_TRIVIAL(warning) << \"The ignoreMismatchingType was set so this error is overridden.\";\n            }\n        }\n\n        return residue->applySpecialResidueTyping(specialType);\n    }\n\n    Protein::Protein() = default;\n\n\n}", "meta": {"hexsha": "bb65a3a98f0556cc3fd3a1ecf89b0239d6cf95d9", "size": 16704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Structures/Protein.cpp", "max_stars_repo_name": "ElianeBriand/SMolDock", "max_stars_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T02:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T02:33:13.000Z", "max_issues_repo_path": "Structures/Protein.cpp", "max_issues_repo_name": "ElianeBriand/SMolDock", "max_issues_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Structures/Protein.cpp", "max_forks_repo_name": "ElianeBriand/SMolDock", "max_forks_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T19:11:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:45:49.000Z", "avg_line_length": 40.2506024096, "max_line_length": 159, "alphanum_fraction": 0.5461566092, "num_tokens": 3804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.018833130613229138, "lm_q1q2_score": 0.004950134653835138}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\r\r\n\r\r\n//Distributed under the Boost Software License, Version 1.0. (See accompanying\r\r\n//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\r\n\r\r\n#ifndef UUID_E6519754D19211DFB8405F74DFD72085\r\r\n#define UUID_E6519754D19211DFB8405F74DFD72085\r\r\n\r\r\n#include <boost/qvm/inline.hpp>\r\r\n#include <boost/qvm/enable_if.hpp>\r\r\n#include <boost/qvm/deduce_quat.hpp>\r\r\n#include <boost/qvm/mat_traits.hpp>\r\r\n#include <boost/qvm/scalar_traits.hpp>\r\r\n#include <boost/qvm/math.hpp>\r\r\n#include <boost/qvm/assert.hpp>\r\r\n#include <boost/qvm/error.hpp>\r\r\n#include <boost/qvm/throw_exception.hpp>\r\r\n#include <string>\r\r\n\r\r\nnamespace\r\r\nboost\r\r\n    {\r\r\n    namespace\r\r\n    qvm\r\r\n        {\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            void const *\r\r\n            get_valid_ptr_quat_operations()\r\r\n                {\r\r\n                static int const obj=0;\r\r\n                return &obj;\r\r\n                }\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        msvc_parse_bug_workaround\r\r\n            {\r\r\n            template <class A,class B>\r\r\n            struct\r\r\n            quats\r\r\n                {\r\r\n                static bool const value=is_quat<A>::value && is_quat<B>::value;\r\r\n                };\r\r\n            }\r\r\n\r\r\n        namespace\r\r\n        qvm_to_string_detail\r\r\n            {\r\r\n            template <class T>\r\r\n            std::string to_string( T const & x );\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        inline\r\r\n        typename boost::enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            std::string>::type\r\r\n        to_string( A const & a )\r\r\n            {\r\r\n            using namespace qvm_to_string_detail;\r\r\n            return '('+\r\r\n                to_string(quat_traits<A>::template read_element<0>(a))+','+\r\r\n                to_string(quat_traits<A>::template read_element<1>(a))+','+\r\r\n                to_string(quat_traits<A>::template read_element<2>(a))+','+\r\r\n                to_string(quat_traits<A>::template read_element<3>(a))+')';\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            A &>::type\r\r\n        assign( A & a, B const & b )\r\r\n            {\r\r\n            quat_traits<A>::template write_element<0>(a) = quat_traits<B>::template read_element<0>(b);\r\r\n            quat_traits<A>::template write_element<1>(a) = quat_traits<B>::template read_element<1>(b);\r\r\n            quat_traits<A>::template write_element<2>(a) = quat_traits<B>::template read_element<2>(b);\r\r\n            quat_traits<A>::template write_element<3>(a) = quat_traits<B>::template read_element<3>(b);\r\r\n            return a;\r\r\n            }\r\r\n\r\r\n        template <class A,class B,class Cmp>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            bool>::type\r\r\n        cmp( A const & a, B const & b, Cmp f )\r\r\n            {\r\r\n            typedef typename deduce_scalar<\r\r\n                typename quat_traits<A>::scalar_type,\r\r\n                typename quat_traits<B>::scalar_type>::type T;\r\r\n            T q1[4] =\r\r\n                {\r\r\n                quat_traits<A>::template read_element<0>(a),\r\r\n                quat_traits<A>::template read_element<1>(a),\r\r\n                quat_traits<A>::template read_element<2>(a),\r\r\n                quat_traits<A>::template read_element<3>(a)\r\r\n                };\r\r\n            T q2[4] =\r\r\n                {\r\r\n                quat_traits<B>::template read_element<0>(b),\r\r\n                quat_traits<B>::template read_element<1>(b),\r\r\n                quat_traits<B>::template read_element<2>(b),\r\r\n                quat_traits<B>::template read_element<3>(b)\r\r\n                };\r\r\n            int i;\r\r\n            for( i=0; i!=4; ++i )\r\r\n                if( !f(q1[i],q2[i]) )\r\r\n                    break;\r\r\n            if( i==4 )\r\r\n                return true;\r\r\n            for( i=0; i!=4; ++i )\r\r\n                if( !f(q1[i],-q2[i]) )\r\r\n                    return false;\r\r\n            return true;\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        template <class R,class A>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        typename enable_if_c<\r\r\n            is_quat<R>::value && is_quat<A>::value,\r\r\n            R>::type\r\r\n        convert_to( A const & a )\r\r\n            {\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r) = quat_traits<A>::template read_element<0>(a);\r\r\n            quat_traits<R>::template write_element<1>(r) = quat_traits<A>::template read_element<1>(a);\r\r\n            quat_traits<R>::template write_element<2>(r) = quat_traits<A>::template read_element<2>(a);\r\r\n            quat_traits<R>::template write_element<3>(r) = quat_traits<A>::template read_element<3>(a);\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class R,class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<R>::value && is_mat<A>::value &&\r\r\n            mat_traits<A>::rows==3 && mat_traits<A>::cols==3,\r\r\n            R>::type\r\r\n        convert_to( A const & a )\r\r\n            {\r\r\n            typedef typename mat_traits<A>::scalar_type T;\r\r\n            T const mat[3][3] =\r\r\n                {\r\r\n                    { mat_traits<A>::template read_element<0,0>(a), mat_traits<A>::template read_element<0,1>(a), mat_traits<A>::template read_element<0,2>(a) },\r\r\n                    { mat_traits<A>::template read_element<1,0>(a), mat_traits<A>::template read_element<1,1>(a), mat_traits<A>::template read_element<1,2>(a) },\r\r\n                    { mat_traits<A>::template read_element<2,0>(a), mat_traits<A>::template read_element<2,1>(a), mat_traits<A>::template read_element<2,2>(a) }\r\r\n                };\r\r\n            R r;\r\r\n            if( mat[0][0]+mat[1][1]+mat[2][2] > scalar_traits<T>::value(0) )\r\r\n                {\r\r\n                T t = mat[0][0] + mat[1][1] + mat[2][2] + scalar_traits<T>::value(1);\r\r\n                T s = (scalar_traits<T>::value(1)/sqrt<T>(t))/2;\r\r\n                quat_traits<R>::template write_element<0>(r)=s*t;\r\r\n                quat_traits<R>::template write_element<1>(r)=(mat[2][1]-mat[1][2])*s;\r\r\n                quat_traits<R>::template write_element<2>(r)=(mat[0][2]-mat[2][0])*s;\r\r\n                quat_traits<R>::template write_element<3>(r)=(mat[1][0]-mat[0][1])*s;\r\r\n                }\r\r\n            else if( mat[0][0]>mat[1][1] && mat[0][0]>mat[2][2] )\r\r\n                {\r\r\n                T t = mat[0][0] - mat[1][1] - mat[2][2] + scalar_traits<T>::value(1);\r\r\n                T s = (scalar_traits<T>::value(1)/sqrt<T>(t))/2;\r\r\n                quat_traits<R>::template write_element<0>(r)=(mat[2][1]-mat[1][2])*s;\r\r\n                quat_traits<R>::template write_element<1>(r)=s*t;\r\r\n                quat_traits<R>::template write_element<2>(r)=(mat[1][0]+mat[0][1])*s;\r\r\n                quat_traits<R>::template write_element<3>(r)=(mat[0][2]+mat[2][0])*s;\r\r\n                }\r\r\n            else if( mat[1][1]>mat[2][2] )\r\r\n                {\r\r\n                T t = - mat[0][0] + mat[1][1] - mat[2][2] + scalar_traits<T>::value(1);\r\r\n                T s = (scalar_traits<T>::value(1)/sqrt<T>(t))/2;\r\r\n                quat_traits<R>::template write_element<0>(r)=(mat[0][2]-mat[2][0])*s;\r\r\n                quat_traits<R>::template write_element<1>(r)=(mat[1][0]+mat[0][1])*s;\r\r\n                quat_traits<R>::template write_element<2>(r)=s*t;\r\r\n                quat_traits<R>::template write_element<3>(r)=(mat[2][1]+mat[1][2])*s;\r\r\n                }\r\r\n            else\r\r\n                {\r\r\n                T t = - mat[0][0] - mat[1][1] + mat[2][2] + scalar_traits<T>::value(1);\r\r\n                T s = (scalar_traits<T>::value(1)/sqrt<T>(t))/2;\r\r\n                quat_traits<R>::template write_element<0>(r)=(mat[1][0]-mat[0][1])*s;\r\r\n                quat_traits<R>::template write_element<1>(r)=(mat[0][2]+mat[2][0])*s;\r\r\n                quat_traits<R>::template write_element<2>(r)=(mat[2][1]+mat[1][2])*s;\r\r\n                quat_traits<R>::template write_element<3>(r)=s*t;\r\r\n                }\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            deduce_quat<A> >::type\r\r\n        conjugate( A const & a )\r\r\n            {\r\r\n            typedef typename deduce_quat<A>::type R;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r)=quat_traits<A>::template read_element<0>(a);\r\r\n            quat_traits<R>::template write_element<1>(r)=-quat_traits<A>::template read_element<1>(a);\r\r\n            quat_traits<R>::template write_element<2>(r)=-quat_traits<A>::template read_element<2>(a);\r\r\n            quat_traits<R>::template write_element<3>(r)=-quat_traits<A>::template read_element<3>(a);\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class T>\r\r\n            class\r\r\n            identity_quat_\r\r\n                {\r\r\n                identity_quat_( identity_quat_ const & );\r\r\n                identity_quat_ & operator=( identity_quat_ const & );\r\r\n                ~identity_quat_();\r\r\n\r\r\n                public:\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n                };\r\r\n            }\r\r\n\r\r\n        template <class T>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::identity_quat_<T> >\r\r\n            {\r\r\n            typedef qvm_detail::identity_quat_<T> this_quaternion;\r\r\n            typedef T scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return scalar_traits<T>::value(I==0);\r\r\n                }\r\r\n\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element_idx( int i, this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_ASSERT(i>=0);\r\r\n                BOOST_QVM_ASSERT(i<4);\r\r\n                return scalar_traits<T>::value(i==0);\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class T>\r\r\n        struct\r\r\n        deduce_quat< qvm_detail::identity_quat_<T> >\r\r\n            {\r\r\n            typedef quat<T> type;\r\r\n            };\r\r\n\r\r\n        template <class T>\r\r\n        struct\r\r\n        deduce_quat2< qvm_detail::identity_quat_<T>, qvm_detail::identity_quat_<T> >\r\r\n            {\r\r\n            typedef quat<T> type;\r\r\n            };\r\r\n\r\r\n        template <class T>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        qvm_detail::identity_quat_<T> const &\r\r\n        identity_quat()\r\r\n            {\r\r\n            return *(qvm_detail::identity_quat_<T> const *)qvm_detail::get_valid_ptr_quat_operations();\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        set_identity( A & a )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type T;\r\r\n            T const zero=scalar_traits<T>::value(0);\r\r\n            T const one=scalar_traits<T>::value(1);\r\r\n            quat_traits<A>::template write_element<0>(a) = one;\r\r\n            quat_traits<A>::template write_element<1>(a) = zero;\r\r\n            quat_traits<A>::template write_element<2>(a) = zero;\r\r\n            quat_traits<A>::template write_element<3>(a) = zero;\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class OriginalType,class Scalar>\r\r\n            class\r\r\n            quaternion_scalar_cast_\r\r\n                {\r\r\n                quaternion_scalar_cast_( quaternion_scalar_cast_ const & );\r\r\n                quaternion_scalar_cast_ & operator=( quaternion_scalar_cast_ const & );\r\r\n                ~quaternion_scalar_cast_();\r\r\n\r\r\n                public:\r\r\n\r\r\n                template <class T>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                quaternion_scalar_cast_ &\r\r\n                operator=( T const & x )\r\r\n                    {\r\r\n                    assign(*this,x);\r\r\n                    return *this;\r\r\n                    }\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n                };\r\r\n\r\r\n            template <bool> struct scalar_cast_quaternion_filter { };\r\r\n            template <> struct scalar_cast_quaternion_filter<true> { typedef int type; };\r\r\n            }\r\r\n\r\r\n        template <class OriginalType,class Scalar>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::quaternion_scalar_cast_<OriginalType,Scalar> >\r\r\n            {\r\r\n            typedef Scalar scalar_type;\r\r\n            typedef qvm_detail::quaternion_scalar_cast_<OriginalType,Scalar> this_quaternion;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return scalar_type(quat_traits<OriginalType>::template read_element<I>(reinterpret_cast<OriginalType const &>(x)));\r\r\n                }\r\r\n\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element_idx( int i, this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_ASSERT(i>=0);\r\r\n                BOOST_QVM_ASSERT(i<4);\r\r\n                return scalar_type(quat_traits<OriginalType>::read_element_idx(i,reinterpret_cast<OriginalType const &>(x)));\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class Scalar,class T>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        qvm_detail::quaternion_scalar_cast_<T,Scalar> const &\r\r\n        scalar_cast( T const & x, typename qvm_detail::scalar_cast_quaternion_filter<is_quat<T>::value>::type=0 )\r\r\n            {\r\r\n            return reinterpret_cast<qvm_detail::quaternion_scalar_cast_<T,Scalar> const &>(x);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value && is_scalar<B>::value,\r\r\n            A &>::type\r\r\n        operator/=( A & a, B b )\r\r\n            {\r\r\n            quat_traits<A>::template write_element<0>(a)/=b;\r\r\n            quat_traits<A>::template write_element<1>(a)/=b;\r\r\n            quat_traits<A>::template write_element<2>(a)/=b;\r\r\n            quat_traits<A>::template write_element<3>(a)/=b;\r\r\n            return a;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value && is_scalar<B>::value,\r\r\n            deduce_quat<A> >::type\r\r\n        operator/( A const & a, B b )\r\r\n            {\r\r\n            typedef typename deduce_quat<A>::type R;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r) = quat_traits<A>::template read_element<0>(a)/b;\r\r\n            quat_traits<R>::template write_element<1>(r) = quat_traits<A>::template read_element<1>(a)/b;\r\r\n            quat_traits<R>::template write_element<2>(r) = quat_traits<A>::template read_element<2>(a)/b;\r\r\n            quat_traits<R>::template write_element<3>(r) = quat_traits<A>::template read_element<3>(a)/b;\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            deduce_scalar<typename quat_traits<A>::scalar_type,typename quat_traits<B>::scalar_type> >::type\r\r\n        dot( A const & a, B const & b )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type Ta;\r\r\n            typedef typename quat_traits<B>::scalar_type Tb;\r\r\n            typedef typename deduce_scalar<Ta,Tb>::type Tr;\r\r\n            Ta const a0=quat_traits<A>::template read_element<0>(a);\r\r\n            Ta const a1=quat_traits<A>::template read_element<1>(a);\r\r\n            Ta const a2=quat_traits<A>::template read_element<2>(a);\r\r\n            Ta const a3=quat_traits<A>::template read_element<3>(a);\r\r\n            Tb const b0=quat_traits<B>::template read_element<0>(b);\r\r\n            Tb const b1=quat_traits<B>::template read_element<1>(b);\r\r\n            Tb const b2=quat_traits<B>::template read_element<2>(b);\r\r\n            Tb const b3=quat_traits<B>::template read_element<3>(b);\r\r\n            Tr const dp=a0*b0+a1*b1+a2*b2+a3*b3;\r\r\n            return dp;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            bool>::type\r\r\n        operator==( A const & a, B const & b )\r\r\n            {\r\r\n            return\r\r\n                quat_traits<A>::template read_element<0>(a)==quat_traits<B>::template read_element<0>(b) &&\r\r\n                quat_traits<A>::template read_element<1>(a)==quat_traits<B>::template read_element<1>(b) &&\r\r\n                quat_traits<A>::template read_element<2>(a)==quat_traits<B>::template read_element<2>(b) &&\r\r\n                quat_traits<A>::template read_element<3>(a)==quat_traits<B>::template read_element<3>(b);\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            deduce_quat<A> >::type\r\r\n        inverse( A const & a )\r\r\n            {\r\r\n            typedef typename deduce_quat<A>::type R;\r\r\n            typedef typename quat_traits<A>::scalar_type TA;\r\r\n            TA aa = quat_traits<A>::template read_element<0>(a);\r\r\n            TA ab = quat_traits<A>::template read_element<1>(a);\r\r\n            TA ac = quat_traits<A>::template read_element<2>(a);\r\r\n            TA ad = quat_traits<A>::template read_element<3>(a);\r\r\n            TA m2 = ab*ab + ac*ac + ad*ad + aa*aa;\r\r\n            if( m2==scalar_traits<TA>::value(0) )\r\r\n                BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\r\r\n            TA rm=scalar_traits<TA>::value(1)/m2;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r) = aa*rm;\r\r\n            quat_traits<R>::template write_element<1>(r) = -ab*rm;\r\r\n            quat_traits<R>::template write_element<2>(r) = -ac*rm;\r\r\n            quat_traits<R>::template write_element<3>(r) = -ad*rm;\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            typename quat_traits<A>::scalar_type>::type\r\r\n        mag_sqr( A const & a )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type T;\r\r\n            T x=quat_traits<A>::template read_element<0>(a);\r\r\n            T y=quat_traits<A>::template read_element<1>(a);\r\r\n            T z=quat_traits<A>::template read_element<2>(a);\r\r\n            T w=quat_traits<A>::template read_element<3>(a);\r\r\n            return x*x+y*y+z*z+w*w;\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            typename quat_traits<A>::scalar_type>::type\r\r\n        mag( A const & a )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type T;\r\r\n            T x=quat_traits<A>::template read_element<0>(a);\r\r\n            T y=quat_traits<A>::template read_element<1>(a);\r\r\n            T z=quat_traits<A>::template read_element<2>(a);\r\r\n            T w=quat_traits<A>::template read_element<3>(a);\r\r\n            return sqrt<T>(x*x+y*y+z*z+w*w);\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if<\r\r\n            msvc_parse_bug_workaround::quats<A,B>,\r\r\n            A &>::type\r\r\n        operator-=( A & a, B const & b )\r\r\n            {\r\r\n            quat_traits<A>::template write_element<0>(a)-=quat_traits<B>::template read_element<0>(b);\r\r\n            quat_traits<A>::template write_element<1>(a)-=quat_traits<B>::template read_element<1>(b);\r\r\n            quat_traits<A>::template write_element<2>(a)-=quat_traits<B>::template read_element<2>(b);\r\r\n            quat_traits<A>::template write_element<3>(a)-=quat_traits<B>::template read_element<3>(b);\r\r\n            return a;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            deduce_quat2<A,B> >::type\r\r\n        operator-( A const & a, B const & b )\r\r\n            {\r\r\n            typedef typename deduce_quat2<A,B>::type R;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r)=quat_traits<A>::template read_element<0>(a)-quat_traits<B>::template read_element<0>(b);\r\r\n            quat_traits<R>::template write_element<1>(r)=quat_traits<A>::template read_element<1>(a)-quat_traits<B>::template read_element<1>(b);\r\r\n            quat_traits<R>::template write_element<2>(r)=quat_traits<A>::template read_element<2>(a)-quat_traits<B>::template read_element<2>(b);\r\r\n            quat_traits<R>::template write_element<3>(r)=quat_traits<A>::template read_element<3>(a)-quat_traits<B>::template read_element<3>(b);\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            deduce_quat<A> >::type\r\r\n        operator-( A const & a )\r\r\n            {\r\r\n            typedef typename deduce_quat<A>::type R;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r)=-quat_traits<A>::template read_element<0>(a);\r\r\n            quat_traits<R>::template write_element<1>(r)=-quat_traits<A>::template read_element<1>(a);\r\r\n            quat_traits<R>::template write_element<2>(r)=-quat_traits<A>::template read_element<2>(a);\r\r\n            quat_traits<R>::template write_element<3>(r)=-quat_traits<A>::template read_element<3>(a);\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if<\r\r\n            msvc_parse_bug_workaround::quats<A,B>,\r\r\n            A &>::type\r\r\n        operator*=( A & a, B const & b )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type TA;\r\r\n            typedef typename quat_traits<B>::scalar_type TB;\r\r\n            TA const aa=quat_traits<A>::template read_element<0>(a);\r\r\n            TA const ab=quat_traits<A>::template read_element<1>(a);\r\r\n            TA const ac=quat_traits<A>::template read_element<2>(a);\r\r\n            TA const ad=quat_traits<A>::template read_element<3>(a);\r\r\n            TB const ba=quat_traits<B>::template read_element<0>(b);\r\r\n            TB const bb=quat_traits<B>::template read_element<1>(b);\r\r\n            TB const bc=quat_traits<B>::template read_element<2>(b);\r\r\n            TB const bd=quat_traits<B>::template read_element<3>(b);\r\r\n            quat_traits<A>::template write_element<0>(a) = aa*ba - ab*bb - ac*bc - ad*bd;\r\r\n            quat_traits<A>::template write_element<1>(a) = aa*bb + ab*ba + ac*bd - ad*bc;\r\r\n            quat_traits<A>::template write_element<2>(a) = aa*bc + ac*ba + ad*bb - ab*bd;\r\r\n            quat_traits<A>::template write_element<3>(a) = aa*bd + ad*ba + ab*bc - ac*bb;\r\r\n            return a;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value && is_scalar<B>::value,\r\r\n            A &>::type\r\r\n        operator*=( A & a, B b )\r\r\n            {\r\r\n            quat_traits<A>::template write_element<0>(a)*=b;\r\r\n            quat_traits<A>::template write_element<1>(a)*=b;\r\r\n            quat_traits<A>::template write_element<2>(a)*=b;\r\r\n            quat_traits<A>::template write_element<3>(a)*=b;\r\r\n            return a;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            deduce_quat2<A,B> >::type\r\r\n        operator*( A const & a, B const & b )\r\r\n            {\r\r\n            typedef typename deduce_quat2<A,B>::type R;\r\r\n            typedef typename quat_traits<A>::scalar_type TA;\r\r\n            typedef typename quat_traits<B>::scalar_type TB;\r\r\n            TA const aa=quat_traits<A>::template read_element<0>(a);\r\r\n            TA const ab=quat_traits<A>::template read_element<1>(a);\r\r\n            TA const ac=quat_traits<A>::template read_element<2>(a);\r\r\n            TA const ad=quat_traits<A>::template read_element<3>(a);\r\r\n            TB const ba=quat_traits<B>::template read_element<0>(b);\r\r\n            TB const bb=quat_traits<B>::template read_element<1>(b);\r\r\n            TB const bc=quat_traits<B>::template read_element<2>(b);\r\r\n            TB const bd=quat_traits<B>::template read_element<3>(b);\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r) = aa*ba - ab*bb - ac*bc - ad*bd;\r\r\n            quat_traits<R>::template write_element<1>(r) = aa*bb + ab*ba + ac*bd - ad*bc;\r\r\n            quat_traits<R>::template write_element<2>(r) = aa*bc + ac*ba + ad*bb - ab*bd;\r\r\n            quat_traits<R>::template write_element<3>(r) = aa*bd + ad*ba + ab*bc - ac*bb;\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value && is_scalar<B>::value,\r\r\n            deduce_quat<A> >::type\r\r\n        operator*( A const & a, B b )\r\r\n            {\r\r\n            typedef typename deduce_quat<A>::type R;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r)=quat_traits<A>::template read_element<0>(a)*b;\r\r\n            quat_traits<R>::template write_element<1>(r)=quat_traits<A>::template read_element<1>(a)*b;\r\r\n            quat_traits<R>::template write_element<2>(r)=quat_traits<A>::template read_element<2>(a)*b;\r\r\n            quat_traits<R>::template write_element<3>(r)=quat_traits<A>::template read_element<3>(a)*b;\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            bool>::type\r\r\n        operator!=( A const & a, B const & b )\r\r\n            {\r\r\n            return\r\r\n                quat_traits<A>::template read_element<0>(a)!=quat_traits<B>::template read_element<0>(b) ||\r\r\n                quat_traits<A>::template read_element<1>(a)!=quat_traits<B>::template read_element<1>(b) ||\r\r\n                quat_traits<A>::template read_element<2>(a)!=quat_traits<B>::template read_element<2>(b) ||\r\r\n                quat_traits<A>::template read_element<3>(a)!=quat_traits<B>::template read_element<3>(b);\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            deduce_quat<A> >::type\r\r\n        normalized( A const & a )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type T;\r\r\n            T const a0=quat_traits<A>::template read_element<0>(a);\r\r\n            T const a1=quat_traits<A>::template read_element<1>(a);\r\r\n            T const a2=quat_traits<A>::template read_element<2>(a);\r\r\n            T const a3=quat_traits<A>::template read_element<3>(a);\r\r\n            T const m2=a0*a0+a1*a1+a2*a2+a3*a3;\r\r\n            if( m2==scalar_traits<typename quat_traits<A>::scalar_type>::value(0) )\r\r\n                BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\r\r\n            T const rm=scalar_traits<T>::value(1)/sqrt<T>(m2);\r\r\n            typedef typename deduce_quat<A>::type R;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r)=a0*rm;\r\r\n            quat_traits<R>::template write_element<1>(r)=a1*rm;\r\r\n            quat_traits<R>::template write_element<2>(r)=a2*rm;\r\r\n            quat_traits<R>::template write_element<3>(r)=a3*rm;\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        normalize( A & a )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type T;\r\r\n            T const a0=quat_traits<A>::template read_element<0>(a);\r\r\n            T const a1=quat_traits<A>::template read_element<1>(a);\r\r\n            T const a2=quat_traits<A>::template read_element<2>(a);\r\r\n            T const a3=quat_traits<A>::template read_element<3>(a);\r\r\n            T const m2=a0*a0+a1*a1+a2*a2+a3*a3;\r\r\n            if( m2==scalar_traits<typename quat_traits<A>::scalar_type>::value(0) )\r\r\n                BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\r\r\n            T const rm=scalar_traits<T>::value(1)/sqrt<T>(m2);\r\r\n            quat_traits<A>::template write_element<0>(a)*=rm;\r\r\n            quat_traits<A>::template write_element<1>(a)*=rm;\r\r\n            quat_traits<A>::template write_element<2>(a)*=rm;\r\r\n            quat_traits<A>::template write_element<3>(a)*=rm;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if<\r\r\n            msvc_parse_bug_workaround::quats<A,B>,\r\r\n            A &>::type\r\r\n        operator+=( A & a, B const & b )\r\r\n            {\r\r\n            quat_traits<A>::template write_element<0>(a)+=quat_traits<B>::template read_element<0>(b);\r\r\n            quat_traits<A>::template write_element<1>(a)+=quat_traits<B>::template read_element<1>(b);\r\r\n            quat_traits<A>::template write_element<2>(a)+=quat_traits<B>::template read_element<2>(b);\r\r\n            quat_traits<A>::template write_element<3>(a)+=quat_traits<B>::template read_element<3>(b);\r\r\n            return a;\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value,\r\r\n            deduce_quat2<A,B> >::type\r\r\n        operator+( A const & a, B const & b )\r\r\n            {\r\r\n            typedef typename deduce_quat2<A,B>::type R;\r\r\n            R r;\r\r\n            quat_traits<R>::template write_element<0>(r)=quat_traits<A>::template read_element<0>(a)+quat_traits<B>::template read_element<0>(b);\r\r\n            quat_traits<R>::template write_element<1>(r)=quat_traits<A>::template read_element<1>(a)+quat_traits<B>::template read_element<1>(b);\r\r\n            quat_traits<R>::template write_element<2>(r)=quat_traits<A>::template read_element<2>(a)+quat_traits<B>::template read_element<2>(b);\r\r\n            quat_traits<R>::template write_element<3>(r)=quat_traits<A>::template read_element<3>(a)+quat_traits<B>::template read_element<3>(b);\r\r\n            return r;\r\r\n            }\r\r\n\r\r\n        template <class A,class B,class C>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename lazy_enable_if_c<\r\r\n            is_quat<A>::value && is_quat<B>::value && is_scalar<C>::value,\r\r\n            deduce_quat2<A,B> >::type\r\r\n        slerp( A const & a, B const & b, C t )\r\r\n            {\r\r\n            typedef typename deduce_quat2<A,B>::type R;\r\r\n            typedef typename quat_traits<R>::scalar_type TR;\r\r\n            TR const one = scalar_traits<TR>::value(1);\r\r\n            TR dp = dot(a,b);\r\r\n            TR sc=one;\r\r\n            if( dp < one )\r\r\n                {\r\r\n                TR const theta = acosf(dp);\r\r\n                TR const invsintheta = one/sin<TR>(theta);\r\r\n                TR const scale = sin<TR>(theta*(one-t)) * invsintheta;\r\r\n                TR const invscale = sin<TR>(theta*t) * invsintheta * sc;\r\r\n                return a*scale + b*invscale;\r\r\n                }\r\r\n            else\r\r\n                return normalized(a+(b-a)*t);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class T>\r\r\n            class\r\r\n            qref_\r\r\n                {\r\r\n                qref_( qref_ const & );\r\r\n                qref_ & operator=( qref_ const & );\r\r\n                ~qref_();\r\r\n\r\r\n                public:\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                qref_ &\r\r\n                operator=( R const & x )\r\r\n                    {\r\r\n                    assign(*this,x);\r\r\n                    return *this;\r\r\n                    }\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n                };\r\r\n            }\r\r\n\r\r\n        template <class Q>\r\r\n        struct quat_traits;\r\r\n\r\r\n        template <class Q>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::qref_<Q> >\r\r\n            {\r\r\n            typedef typename quat_traits<Q>::scalar_type scalar_type;\r\r\n            typedef qvm_detail::qref_<Q> this_quaternion;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return quat_traits<Q>::template read_element<I>(reinterpret_cast<Q const &>(x));\r\r\n                }\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type &\r\r\n            write_element( this_quaternion & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return quat_traits<Q>::template write_element<I>(reinterpret_cast<Q &>(x));\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class Q>\r\r\n        struct\r\r\n        deduce_quat< qvm_detail::qref_<Q> >\r\r\n            {\r\r\n            typedef quat<typename quat_traits<Q>::scalar_type> type;\r\r\n            };\r\r\n\r\r\n        template <class Q>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        typename enable_if_c<\r\r\n            is_quat<Q>::value,\r\r\n            qvm_detail::qref_<Q> const &>::type\r\r\n        qref( Q const & a )\r\r\n            {\r\r\n            return reinterpret_cast<qvm_detail::qref_<Q> const &>(a);\r\r\n            }\r\r\n\r\r\n        template <class Q>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        typename enable_if_c<\r\r\n            is_quat<Q>::value,\r\r\n            qvm_detail::qref_<Q> &>::type\r\r\n        qref( Q & a )\r\r\n            {\r\r\n            return reinterpret_cast<qvm_detail::qref_<Q> &>(a);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class T>\r\r\n            class\r\r\n            zero_q_\r\r\n                {\r\r\n                zero_q_( zero_q_ const & );\r\r\n                zero_q_ & operator=( zero_q_ const & );\r\r\n                ~zero_q_();\r\r\n\r\r\n                public:\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n                };\r\r\n            }\r\r\n\r\r\n        template <class T>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::zero_q_<T> >\r\r\n            {\r\r\n            typedef qvm_detail::zero_q_<T> this_quaternion;\r\r\n            typedef T scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return scalar_traits<scalar_type>::value(0);\r\r\n                }\r\r\n\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element_idx( int i, this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_ASSERT(i>=0);\r\r\n                BOOST_QVM_ASSERT(i<4);\r\r\n                return scalar_traits<scalar_type>::value(0);\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class T>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        qvm_detail::zero_q_<T> const &\r\r\n        zero_quat()\r\r\n            {\r\r\n            return *(qvm_detail::zero_q_<T> const *)qvm_detail::get_valid_ptr_quat_operations();\r\r\n            }\r\r\n\r\r\n        template <class A>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        set_zero( A & a )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type T;\r\r\n            T const zero=scalar_traits<T>::value(0);\r\r\n            quat_traits<A>::template write_element<0>(a) = zero;\r\r\n            quat_traits<A>::template write_element<1>(a) = zero;\r\r\n            quat_traits<A>::template write_element<2>(a) = zero;\r\r\n            quat_traits<A>::template write_element<3>(a) = zero;\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class V>\r\r\n            struct\r\r\n            rot_quat_\r\r\n                {\r\r\n                typedef typename vec_traits<V>::scalar_type scalar_type;\r\r\n                scalar_type a[4];\r\r\n\r\r\n                template <class Angle>\r\r\n                BOOST_QVM_INLINE\r\r\n                rot_quat_( V const & axis, Angle angle )\r\r\n                    {\r\r\n                    scalar_type const x=vec_traits<V>::template read_element<0>(axis);\r\r\n                    scalar_type const y=vec_traits<V>::template read_element<1>(axis);\r\r\n                    scalar_type const z=vec_traits<V>::template read_element<2>(axis);\r\r\n                    scalar_type const m2=x*x+y*y+z*z;\r\r\n                    if( m2==scalar_traits<scalar_type>::value(0) )\r\r\n                        BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\r\r\n                    scalar_type const rm=scalar_traits<scalar_type>::value(1)/sqrt<scalar_type>(m2);\r\r\n                    angle/=2;\r\r\n                    scalar_type const s=sin<Angle>(angle);\r\r\n                    a[0] = cos<Angle>(angle);\r\r\n                    a[1] = rm*x*s;\r\r\n                    a[2] = rm*y*s;\r\r\n                    a[3] = rm*z*s;\r\r\n                    }\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n                };\r\r\n            }\r\r\n\r\r\n        template <class V>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::rot_quat_<V> >\r\r\n            {\r\r\n            typedef qvm_detail::rot_quat_<V> this_quaternion;\r\r\n            typedef typename this_quaternion::scalar_type scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return x.a[I];\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class V>\r\r\n        struct\r\r\n        deduce_quat< qvm_detail::rot_quat_<V> >\r\r\n            {\r\r\n            typedef quat<typename vec_traits<V>::scalar_type> type;\r\r\n            };\r\r\n\r\r\n        template <class A,class Angle>\r\r\n        BOOST_QVM_INLINE\r\r\n        typename enable_if_c<\r\r\n            is_vec<A>::value && vec_traits<A>::dim==3,\r\r\n            qvm_detail::rot_quat_<A> >::type\r\r\n        rot_quat( A const & axis, Angle angle )\r\r\n            {\r\r\n            return qvm_detail::rot_quat_<A>(axis,angle);\r\r\n            }\r\r\n\r\r\n        template <class A,class B,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value &&\r\r\n            is_vec<B>::value && vec_traits<B>::dim==3,\r\r\n            void>::type\r\r\n        set_rot( A & a, B const & axis, Angle angle )\r\r\n            {\r\r\n            assign(a,rot_quat(axis,angle));\r\r\n            }\r\r\n\r\r\n        template <class A,class B,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value &&\r\r\n            is_vec<B>::value && vec_traits<B>::dim==3,\r\r\n            void>::type\r\r\n        rotate( A & a, B const & axis, Angle angle )\r\r\n            {\r\r\n            a *= rot_quat(axis,angle);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class T>\r\r\n            struct\r\r\n            rotx_quat_\r\r\n                {\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                rotx_quat_()\r\r\n                    {\r\r\n                    }\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n\r\r\n                private:\r\r\n\r\r\n                rotx_quat_( rotx_quat_ const & );\r\r\n                rotx_quat_ & operator=( rotx_quat_ const & );\r\r\n                ~rotx_quat_();\r\r\n                };\r\r\n\r\r\n            template <int I>\r\r\n            struct\r\r\n            rotx_q_get\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & )\r\r\n                    {\r\r\n                    return scalar_traits<T>::value(0);\r\r\n                    }\r\r\n                };\r\r\n\r\r\n            template <>\r\r\n            struct\r\r\n            rotx_q_get<1>\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & angle )\r\r\n                    {\r\r\n                    return sin<T>(angle/2);\r\r\n                    }\r\r\n                };\r\r\n\r\r\n            template <>\r\r\n            struct\r\r\n            rotx_q_get<0>\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & angle )\r\r\n                    {\r\r\n                    return cos<T>(angle/2);\r\r\n                    }\r\r\n                };\r\r\n            }\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::rotx_quat_<Angle> >\r\r\n            {\r\r\n            typedef qvm_detail::rotx_quat_<Angle> this_quaternion;\r\r\n            typedef Angle scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return qvm_detail::rotx_q_get<I>::get(reinterpret_cast<Angle const &>(x));\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        deduce_quat< qvm_detail::rotx_quat_<Angle> >\r\r\n            {\r\r\n            typedef quat<Angle> type;\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        deduce_quat2< qvm_detail::rotx_quat_<Angle>, qvm_detail::rotx_quat_<Angle> >\r\r\n            {\r\r\n            typedef quat<Angle> type;\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        qvm_detail::rotx_quat_<Angle> const &\r\r\n        rotx_quat( Angle const & angle )\r\r\n            {\r\r\n            return reinterpret_cast<qvm_detail::rotx_quat_<Angle> const &>(angle);\r\r\n            }\r\r\n\r\r\n        template <class A,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        set_rotx( A & a, Angle angle )\r\r\n            {\r\r\n            assign(a,rotx_quat(angle));\r\r\n            }\r\r\n\r\r\n        template <class A,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        rotate_x( A & a, Angle angle )\r\r\n            {\r\r\n            a *= rotx_quat(angle);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class T>\r\r\n            struct\r\r\n            roty_quat_\r\r\n                {\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                roty_quat_()\r\r\n                    {\r\r\n                    }\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n\r\r\n                private:\r\r\n\r\r\n                roty_quat_( roty_quat_ const & );\r\r\n                roty_quat_ & operator=( roty_quat_ const & );\r\r\n                ~roty_quat_();\r\r\n                };\r\r\n\r\r\n            template <int I>\r\r\n            struct\r\r\n            roty_q_get\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & )\r\r\n                    {\r\r\n                    return scalar_traits<T>::value(0);\r\r\n                    }\r\r\n                };\r\r\n\r\r\n            template <>\r\r\n            struct\r\r\n            roty_q_get<2>\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & angle )\r\r\n                    {\r\r\n                    return sin<T>(angle/2);\r\r\n                    }\r\r\n                };\r\r\n\r\r\n            template <>\r\r\n            struct\r\r\n            roty_q_get<0>\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & angle )\r\r\n                    {\r\r\n                    return cos<T>(angle/2);\r\r\n                    }\r\r\n                };\r\r\n            }\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::roty_quat_<Angle> >\r\r\n            {\r\r\n            typedef qvm_detail::roty_quat_<Angle> this_quaternion;\r\r\n            typedef Angle scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return qvm_detail::roty_q_get<I>::get(reinterpret_cast<Angle const &>(x));\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        deduce_quat< qvm_detail::roty_quat_<Angle> >\r\r\n            {\r\r\n            typedef quat<Angle> type;\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        deduce_quat2< qvm_detail::roty_quat_<Angle>, qvm_detail::roty_quat_<Angle> >\r\r\n            {\r\r\n            typedef quat<Angle> type;\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        qvm_detail::roty_quat_<Angle> const &\r\r\n        roty_quat( Angle const & angle )\r\r\n            {\r\r\n            return reinterpret_cast<qvm_detail::roty_quat_<Angle> const &>(angle);\r\r\n            }\r\r\n\r\r\n        template <class A,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        set_roty( A & a, Angle angle )\r\r\n            {\r\r\n            assign(a,roty_quat(angle));\r\r\n            }\r\r\n\r\r\n        template <class A,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        rotate_y( A & a, Angle angle )\r\r\n            {\r\r\n            a *= roty_quat(angle);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        qvm_detail\r\r\n            {\r\r\n            template <class T>\r\r\n            struct\r\r\n            rotz_quat_\r\r\n                {\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                rotz_quat_()\r\r\n                    {\r\r\n                    }\r\r\n\r\r\n                template <class R>\r\r\n                BOOST_QVM_INLINE_TRIVIAL\r\r\n                operator R() const\r\r\n                    {\r\r\n                    R r;\r\r\n                    assign(r,*this);\r\r\n                    return r;\r\r\n                    }\r\r\n\r\r\n                private:\r\r\n\r\r\n                rotz_quat_( rotz_quat_ const & );\r\r\n                rotz_quat_ & operator=( rotz_quat_ const & );\r\r\n                ~rotz_quat_();\r\r\n                };\r\r\n\r\r\n            template <int I>\r\r\n            struct\r\r\n            rotz_q_get\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & )\r\r\n                    {\r\r\n                    return scalar_traits<T>::value(0);\r\r\n                    }\r\r\n                };\r\r\n\r\r\n            template <>\r\r\n            struct\r\r\n            rotz_q_get<3>\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & angle )\r\r\n                    {\r\r\n                    return sin<T>(angle/2);\r\r\n                    }\r\r\n                };\r\r\n\r\r\n            template <>\r\r\n            struct\r\r\n            rotz_q_get<0>\r\r\n                {\r\r\n                template <class T>\r\r\n                static\r\r\n                BOOST_QVM_INLINE_CRITICAL\r\r\n                T\r\r\n                get( T const & angle )\r\r\n                    {\r\r\n                    return cos<T>(angle/2);\r\r\n                    }\r\r\n                };\r\r\n            }\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        quat_traits< qvm_detail::rotz_quat_<Angle> >\r\r\n            {\r\r\n            typedef qvm_detail::rotz_quat_<Angle> this_quaternion;\r\r\n            typedef Angle scalar_type;\r\r\n\r\r\n            template <int I>\r\r\n            static\r\r\n            BOOST_QVM_INLINE_CRITICAL\r\r\n            scalar_type\r\r\n            read_element( this_quaternion const & x )\r\r\n                {\r\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\r\n                BOOST_QVM_STATIC_ASSERT(I<4);\r\r\n                return qvm_detail::rotz_q_get<I>::get(reinterpret_cast<Angle const &>(x));\r\r\n                }\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        deduce_quat< qvm_detail::rotz_quat_<Angle> >\r\r\n            {\r\r\n            typedef quat<Angle> type;\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        struct\r\r\n        deduce_quat2< qvm_detail::rotz_quat_<Angle>, qvm_detail::rotz_quat_<Angle> >\r\r\n            {\r\r\n            typedef quat<Angle> type;\r\r\n            };\r\r\n\r\r\n        template <class Angle>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        qvm_detail::rotz_quat_<Angle> const &\r\r\n        rotz_quat( Angle const & angle )\r\r\n            {\r\r\n            return reinterpret_cast<qvm_detail::rotz_quat_<Angle> const &>(angle);\r\r\n            }\r\r\n\r\r\n        template <class A,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        set_rotz( A & a, Angle angle )\r\r\n            {\r\r\n            assign(a,rotz_quat(angle));\r\r\n            }\r\r\n\r\r\n        template <class A,class Angle>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value,\r\r\n            void>::type\r\r\n        rotate_z( A & a, Angle angle )\r\r\n            {\r\r\n            a *= rotz_quat(angle);\r\r\n            }\r\r\n\r\r\n        template <class A,class B>\r\r\n        BOOST_QVM_INLINE_OPERATIONS\r\r\n        typename enable_if_c<\r\r\n            is_quat<A>::value && is_vec<B>::value && vec_traits<B>::dim==3,\r\r\n            typename quat_traits<A>::scalar_type>::type\r\r\n        axis_angle( A const & a, B & b )\r\r\n            {\r\r\n            typedef typename quat_traits<A>::scalar_type T;\r\r\n            T a0=quat_traits<A>::template read_element<0>(a);\r\r\n            T a1=quat_traits<A>::template read_element<1>(a);\r\r\n            T a2=quat_traits<A>::template read_element<2>(a);\r\r\n            T a3=quat_traits<A>::template read_element<3>(a);\r\r\n            if( a0>1 )\r\r\n                {\r\r\n                T const m2=a0*a0+a1*a1+a2*a2+a3*a3;\r\r\n                if( m2==scalar_traits<T>::value(0) )\r\r\n                    BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error());\r\r\n                T const s=sqrt<T>(m2);\r\r\n                a0/=s;\r\r\n                a1/=s;\r\r\n                a2/=s;\r\r\n                a3/=s;\r\r\n                }\r\r\n            if( T s=sqrt<T>(1-a0*a0) )\r\r\n                {\r\r\n                vec_traits<B>::template write_element<0>(b) = a1/s;\r\r\n                vec_traits<B>::template write_element<1>(b) = a2/s;\r\r\n                vec_traits<B>::template write_element<2>(b) = a3/s;\r\r\n                }\r\r\n            else\r\r\n                {\r\r\n                typedef typename vec_traits<B>::scalar_type T;\r\r\n                vec_traits<B>::template write_element<0>(b) = scalar_traits<T>::value(1);\r\r\n                vec_traits<B>::template write_element<1>(b) = vec_traits<B>::template write_element<2>(b) = scalar_traits<T>::value(0);\r\r\n                }\r\r\n            return scalar_traits<T>::value(2) * qvm::acos(a0);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        namespace\r\r\n        sfinae\r\r\n            {\r\r\n            using ::boost::qvm::assign;\r\r\n            using ::boost::qvm::cmp;\r\r\n            using ::boost::qvm::convert_to;\r\r\n            using ::boost::qvm::conjugate;\r\r\n            using ::boost::qvm::set_identity;\r\r\n            using ::boost::qvm::set_zero;\r\r\n            using ::boost::qvm::scalar_cast;\r\r\n            using ::boost::qvm::operator/=;\r\r\n            using ::boost::qvm::operator/;\r\r\n            using ::boost::qvm::dot;\r\r\n            using ::boost::qvm::operator==;\r\r\n            using ::boost::qvm::inverse;\r\r\n            using ::boost::qvm::mag_sqr;\r\r\n            using ::boost::qvm::mag;\r\r\n            using ::boost::qvm::slerp;\r\r\n            using ::boost::qvm::operator-=;\r\r\n            using ::boost::qvm::operator-;\r\r\n            using ::boost::qvm::operator*=;\r\r\n            using ::boost::qvm::operator*;\r\r\n            using ::boost::qvm::operator!=;\r\r\n            using ::boost::qvm::normalized;\r\r\n            using ::boost::qvm::normalize;\r\r\n            using ::boost::qvm::operator+=;\r\r\n            using ::boost::qvm::operator+;\r\r\n            using ::boost::qvm::qref;\r\r\n            using ::boost::qvm::rot_quat;\r\r\n            using ::boost::qvm::set_rot;\r\r\n            using ::boost::qvm::rotate;\r\r\n            using ::boost::qvm::rotx_quat;\r\r\n            using ::boost::qvm::set_rotx;\r\r\n            using ::boost::qvm::rotate_x;\r\r\n            using ::boost::qvm::roty_quat;\r\r\n            using ::boost::qvm::set_roty;\r\r\n            using ::boost::qvm::rotate_y;\r\r\n            using ::boost::qvm::rotz_quat;\r\r\n            using ::boost::qvm::set_rotz;\r\r\n            using ::boost::qvm::rotate_z;\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n        }\r\r\n    }\r\r\n\r\r\n#endif\r\r\n", "meta": {"hexsha": "8844409340da6321de77d2ef4471d9b6f7be1418", "size": 57307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost_1_63_0/boost/qvm/quat_operations.hpp", "max_stars_repo_name": "newtondev/drachtio-server", "max_stars_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/boost_1_63_0/boost/qvm/quat_operations.hpp", "max_issues_repo_name": "newtondev/drachtio-server", "max_issues_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/boost_1_63_0/boost/qvm/quat_operations.hpp", "max_forks_repo_name": "newtondev/drachtio-server", "max_forks_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_forks_repo_licenses": ["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.9768058317, "max_line_length": 163, "alphanum_fraction": 0.4683721011, "num_tokens": 12768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127980882971, "lm_q2_score": 0.01971912655911187, "lm_q1q2_score": 0.004947781220804013}}
{"text": "//=============================================================================================================\n/**\n* @file     filterdata.cpp\n* @author   Florian Schlembach <florian.schlembach@tu-ilmenau.de>;\n*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n*           Jens Haueisen <jens.haueisen@tu-ilmenau.de>\n* @version  1.0\n* @date     February, 2014\n*\n* @section  LICENSE\n*\n* Copyright (C) 2014, Florian Schlembach, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Contains all FilterData.\n*\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"filterdata.h\"\n\n#include \"../mnemath.h\"\n\n#include \"parksmcclellan.h\"\n#include \"cosinefilter.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// STL INCLUDES\n//=============================================================================================================\n\n#include <iostream>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Qt INCLUDES\n//=============================================================================================================\n\n#include <QDebug>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/SparseCore>\n//#ifndef EIGEN_FFTW_DEFAULT\n//#define EIGEN_FFTW_DEFAULT\n//#endif\n#include <unsupported/Eigen/FFT>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace UTILSLIB;\n\n\n//*************************************************************************************************************\n\nFilterData::FilterData()\n: m_Type(UNKNOWN)\n, m_iFilterOrder(80)\n, m_iFFTlength(512)\n, m_sName(\"Unknown\")\n, m_dParksWidth(0.1)\n, m_designMethod(External)\n, m_dCenterFreq(0.5)\n, m_dBandwidth(0.1)\n, m_sFreq(1000)\n, m_dLowpassFreq(4)\n, m_dHighpassFreq(40)\n{\n\n}\n\n\n//*************************************************************************************************************\n\nFilterData::FilterData(QString unique_name, FilterType type, int order, double centerfreq, double bandwidth, double parkswidth, double sFreq, qint32 fftlength, DesignMethod designMethod)\n: m_Type(type)\n, m_iFilterOrder(order)\n, m_iFFTlength(fftlength)\n, m_sName(unique_name)\n, m_dParksWidth(parkswidth)\n, m_designMethod(designMethod)\n, m_dCenterFreq(centerfreq)\n, m_dBandwidth(bandwidth)\n, m_sFreq(sFreq)\n{\n    designFilter();\n}\n\n\n//*************************************************************************************************************\n\nvoid FilterData::designFilter()\n{\n    switch(m_designMethod) {\n        case Tschebyscheff: {\n            ParksMcClellan filter(m_iFilterOrder, m_dCenterFreq, m_dBandwidth, m_dParksWidth, (ParksMcClellan::TPassType)m_Type);\n            m_dCoeffA = filter.FirCoeff;\n\n            //fft-transform m_dCoeffA in order to be able to perform frequency-domain filtering\n            fftTransformCoeffs();\n\n            break;\n        }\n\n        case Cosine: {\n            CosineFilter filtercos;\n\n            switch(m_Type) {\n                case LPF:\n                    filtercos = CosineFilter (m_iFFTlength,\n                                            (m_dCenterFreq)*(m_sFreq/2),\n                                            m_dParksWidth*(m_sFreq/2),\n                                            (m_dCenterFreq)*(m_sFreq/2),\n                                            m_dParksWidth*(m_sFreq/2),\n                                            m_sFreq,\n                                            (CosineFilter::TPassType)m_Type);\n\n                    break;\n\n                case HPF:\n                    filtercos = CosineFilter (m_iFFTlength,\n                                            (m_dCenterFreq)*(m_sFreq/2),\n                                            m_dParksWidth*(m_sFreq/2),\n                                            (m_dCenterFreq)*(m_sFreq/2),\n                                            m_dParksWidth*(m_sFreq/2),\n                                            m_sFreq,\n                                            (CosineFilter::TPassType)m_Type);\n\n                    break;\n\n                case BPF:\n                    filtercos = CosineFilter (m_iFFTlength,\n                                            (m_dCenterFreq + m_dBandwidth/2)*(m_sFreq/2),\n                                            m_dParksWidth*(m_sFreq/2),\n                                            (m_dCenterFreq - m_dBandwidth/2)*(m_sFreq/2),\n                                            m_dParksWidth*(m_sFreq/2),\n                                            m_sFreq,\n                                            (CosineFilter::TPassType)m_Type);\n\n                    break;\n            }\n\n            //This filter is designed in the frequency domain, hence the time domain impulse response need to be shortend by the users dependent number of taps\n            m_dCoeffA.resize(m_iFilterOrder);\n            m_dCoeffA.head(m_iFilterOrder/2) = filtercos.m_dCoeffA.tail(m_iFilterOrder/2);\n            m_dCoeffA.tail(m_iFilterOrder/2) = filtercos.m_dCoeffA.head(m_iFilterOrder/2);\n\n            //Now generate the fft version of the shortened impulse response\n            fftTransformCoeffs();\n\n            break;\n        }\n    }\n\n    switch(m_Type) {\n        case LPF:\n            m_dLowpassFreq = 0;\n            m_dHighpassFreq = m_dCenterFreq*(m_sFreq/2);\n        break;\n\n        case HPF:\n            m_dLowpassFreq = m_dCenterFreq*(m_sFreq/2);\n            m_dHighpassFreq = 0;\n        break;\n\n        case BPF:\n            m_dLowpassFreq = (m_dCenterFreq + m_dBandwidth/2)*(m_sFreq/2);\n            m_dHighpassFreq = (m_dCenterFreq - m_dBandwidth/2)*(m_sFreq/2);\n        break;\n    }\n\n}\n\n\n//*************************************************************************************************************\n\nvoid FilterData::fftTransformCoeffs()\n{\n    //zero-pad m_dCoeffA to m_iFFTlength\n    RowVectorXd t_coeffAzeroPad = RowVectorXd::Zero(m_iFFTlength);\n    t_coeffAzeroPad.head(m_dCoeffA.cols()) = m_dCoeffA;\n\n    //generate fft object\n    Eigen::FFT<double> fft;\n    fft.SetFlag(fft.HalfSpectrum);\n\n    //fft-transform filter coeffs\n    m_dFFTCoeffA = RowVectorXcd::Zero(m_iFFTlength);\n    fft.fwd(m_dFFTCoeffA,t_coeffAzeroPad);\n}\n\n\n//*************************************************************************************************************\n\nRowVectorXd FilterData::applyConvFilter(const RowVectorXd& data, bool keepOverhead, CompensateEdgeEffects compensateEdgeEffects) const\n{\n    if(data.cols()<m_dCoeffA.cols() && compensateEdgeEffects==MirrorData){\n        qDebug()<<QString(\"Error in FilterData: Number of filter taps(%1) bigger then data size(%2). Not enough data to perform mirroring!\").arg(m_dCoeffA.cols()).arg(data.cols());\n        return data;\n    }\n\n    //Do zero padding or mirroring depending on user input\n    RowVectorXd t_dataZeroPad = RowVectorXd::Zero(2*m_dCoeffA.cols() + data.cols());\n    RowVectorXd t_filteredTime = RowVectorXd::Zero(2*m_dCoeffA.cols() + data.cols());\n\n    switch(compensateEdgeEffects) {\n        case MirrorData:\n            t_dataZeroPad.head(m_dCoeffA.cols()) = data.head(m_dCoeffA.cols()).reverse();   //front\n            t_dataZeroPad.segment(m_dCoeffA.cols(), data.cols()) = data;                    //middle\n            t_dataZeroPad.tail(m_dCoeffA.cols()) = data.tail(m_dCoeffA.cols()).reverse();   //back\n            break;\n\n        case ZeroPad:\n            t_dataZeroPad.segment(m_dCoeffA.cols(), data.cols()) = data;\n            break;\n\n        default:\n            t_dataZeroPad.segment(m_dCoeffA.cols(), data.cols()) = data;\n            break;\n    }\n\n    //Do the convolution\n    for(int i=m_dCoeffA.cols(); i<t_filteredTime.cols(); i++)\n        t_filteredTime(i-m_dCoeffA.cols()) = t_dataZeroPad.segment(i-m_dCoeffA.cols(),m_dCoeffA.cols()) * m_dCoeffA.transpose();\n\n    //Return filtered data\n    if(!keepOverhead)\n        return t_filteredTime.segment(m_dCoeffA.cols()/2, data.cols());\n\n    return t_filteredTime.head(data.cols()+m_dCoeffA.cols());\n}\n\n\n//*************************************************************************************************************\n\nRowVectorXd FilterData::applyFFTFilter(const RowVectorXd& data, bool keepOverhead, CompensateEdgeEffects compensateEdgeEffects) const\n{\n    if(data.cols()<m_dCoeffA.cols() && compensateEdgeEffects==MirrorData) {\n        qDebug()<<QString(\"Error in FilterData: Number of filter taps(%1) bigger then data size(%2). Not enough data to perform mirroring!\").arg(m_dCoeffA.cols()).arg(data.cols());\n        return data;\n    }\n\n//    std::cout<<\"m_iFFTlength: \"<<m_iFFTlength<<std::endl;\n//    std::cout<<\"2*m_dCoeffA.cols() + data.cols(): \"<<2*m_dCoeffA.cols() + data.cols()<<std::endl;\n\n    if(2*m_dCoeffA.cols() + data.cols()>m_iFFTlength) {\n        qDebug()<<\"Error in FilterData: Number of mirroring/zeropadding size plus data size is bigger then fft length!\";\n        return data;\n    }\n\n    //Do zero padding or mirroring depending on user input\n    RowVectorXd t_dataZeroPad = RowVectorXd::Zero(m_iFFTlength);\n\n    switch(compensateEdgeEffects) {\n        case MirrorData:\n            t_dataZeroPad.head(m_dCoeffA.cols()) = data.head(m_dCoeffA.cols()).reverse();   //front\n            t_dataZeroPad.segment(m_dCoeffA.cols(), data.cols()) = data;                    //middle\n            t_dataZeroPad.tail(m_dCoeffA.cols()) = data.tail(m_dCoeffA.cols()).reverse();   //back\n            break;\n\n        case ZeroPad:\n            t_dataZeroPad.head(data.cols()) = data;\n            break;\n\n        default:\n            t_dataZeroPad.head(data.cols()) = data;\n            break;\n    }\n\n    //generate fft object\n    Eigen::FFT<double> fft;\n    fft.SetFlag(fft.HalfSpectrum);\n\n    //fft-transform data sequence\n    RowVectorXcd t_freqData;\n    fft.fwd(t_freqData,t_dataZeroPad);\n\n    //perform frequency-domain filtering\n    RowVectorXcd t_filteredFreq = m_dFFTCoeffA.array()*t_freqData.array();\n\n    //inverse-FFT\n    RowVectorXd t_filteredTime;\n    fft.inv(t_filteredTime,t_filteredFreq);\n\n    //Return filtered data\n    if(!keepOverhead)\n        return t_filteredTime.segment(m_dCoeffA.cols()/2, data.cols());\n\n    return t_filteredTime.head(data.cols()+m_dCoeffA.cols());\n}\n\n\n//*************************************************************************************************************\n\nQString FilterData::getStringForDesignMethod(const FilterData::DesignMethod &designMethod)\n{\n    QString designMethodString = \"External\";\n\n    if(designMethod == FilterData::External)\n        designMethodString = \"External\";\n\n    if(designMethod == FilterData::Cosine)\n        designMethodString = \"Cosine\";\n\n    if(designMethod == FilterData::Tschebyscheff)\n        designMethodString = \"Tschebyscheff\";\n\n    return designMethodString;\n}\n\n\n//*************************************************************************************************************\n\nQString FilterData::getStringForFilterType(const FilterData::FilterType &filterType)\n{\n    QString filterTypeString = \"LPF\";\n\n    if(filterType == FilterData::LPF)\n        filterTypeString = \"LPF\";\n\n    if(filterType == FilterData::HPF)\n        filterTypeString = \"HPF\";\n\n    if(filterType == FilterData::BPF)\n        filterTypeString = \"BPF\";\n\n    if(filterType == FilterData::NOTCH)\n        filterTypeString = \"NOTCH\";\n\n    return filterTypeString;\n}\n\n\n//*************************************************************************************************************\n\nFilterData::DesignMethod FilterData::getDesignMethodForString(const QString &designMethodString)\n{\n    FilterData::DesignMethod designMethod = FilterData::External;\n\n    if(designMethodString == \"External\")\n        designMethod = FilterData::External;\n\n    if(designMethodString == \"Tschebyscheff\")\n        designMethod = FilterData::Tschebyscheff;\n\n    if(designMethodString == \"Cosine\")\n        designMethod = FilterData::Cosine;\n\n    return designMethod;\n}\n\n\n//*************************************************************************************************************\n\nFilterData::FilterType FilterData::getFilterTypeForString(const QString &filterTypeString)\n{\n    FilterData::FilterType filterType = FilterData::UNKNOWN;\n\n    if(filterTypeString == \"LPF\")\n        filterType = FilterData::LPF;\n\n    if(filterTypeString == \"HPF\")\n        filterType = FilterData::HPF;\n\n    if(filterTypeString == \"BPF\")\n        filterType = FilterData::BPF;\n\n    if(filterTypeString == \"NOTCH\")\n        filterType = FilterData::NOTCH;\n\n    return filterType;\n}\n", "meta": {"hexsha": "c04dd01bef22cb43caeeb5da1ffef9492130ad37", "size": 15136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/utils/filterTools/filterdata.cpp", "max_stars_repo_name": "13grife37/mne-cpp-swpold", "max_stars_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T20:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-26T16:30:25.000Z", "max_issues_repo_path": "MNE/utils/filterTools/filterdata.cpp", "max_issues_repo_name": "13grife37/mne-cpp-swpold", "max_issues_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/utils/filterTools/filterdata.cpp", "max_forks_repo_name": "13grife37/mne-cpp-swpold", "max_forks_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T15:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-23T15:55:31.000Z", "avg_line_length": 37.2807881773, "max_line_length": 186, "alphanum_fraction": 0.513147463, "num_tokens": 3044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.0159063896416899, "lm_q1q2_score": 0.004942025918895213}}
{"text": "//=============================================================================================================\n/**\n* @file     rthpis.cpp\n* @author   Chiran Doshi <chiran.doshi@childrens.harvard.edu>;\n*           Limin Sun <liminsun@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n*\n* @version  1.0\n* @date     March, 2015\n*\n* @section  LICENSE\n*\n* Copyright (C) 2015, Chiran Doshi, Limin Sun, and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief     implementation of the RtHPIS Class.\n*\n*/\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n#include <Eigen/Dense>\n\n#include \"rthpis.h\"\n\n#include <iostream>\n#include <fiff/fiff_cov.h>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QDebug>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace RTINVLIB;\nusing namespace FIFFLIB;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nRtHPIS::RtHPIS(FiffInfo::SPtr p_pFiffInfo, QObject *parent)\n: QThread(parent)\n, m_pFiffInfo(p_pFiffInfo)\n, m_bIsRunning(false)\n{\n    qRegisterMetaType<Eigen::MatrixXd>(\"Eigen::MatrixXd\");\n    //qRegisterMetaType<QVector<double>>(\"QVector<double>\");\n    SendDataToBuffer = true;\n\n}\n\n\n//*************************************************************************************************************\n\nRtHPIS::~RtHPIS()\n{\n    if(this->isRunning()){\n        stop();\n    }\n}\n\n\n//*************************************************************************************************************\n\nvoid RtHPIS::append(const MatrixXd &p_DataSegment)\n{\n    if(!m_pRawMatrixBuffer)\n        m_pRawMatrixBuffer = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(8, p_DataSegment.rows(), p_DataSegment.cols()));\n\n    if (SendDataToBuffer)\n        m_pRawMatrixBuffer->push(&p_DataSegment);\n}\n\n\n//*************************************************************************************************************\n\nbool RtHPIS::start()\n{\n    //Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated.\n    if(this->isRunning())\n        QThread::wait();\n\n    m_bIsRunning = true;\n    QThread::start();\n\n    return true;\n}\n\n\n//*************************************************************************************************************\n\nbool RtHPIS::stop()\n{\n    m_bIsRunning = false;\n\n    m_pRawMatrixBuffer->releaseFromPop();\n\n    m_pRawMatrixBuffer->clear();\n\n    qDebug()<<\" RtHPIS Thread is stopped.\";\n\n    return true;\n}\n\n\n//*************************************************************************************************************\n\nvoid RtHPIS::run()\n{\n\n    struct sens sensors;\n    struct coilParam coil;\n    int numCoils = 4;\n    int numCh = m_pFiffInfo->nchan;\n    int samF = m_pFiffInfo->sfreq;\n    int numLoc = 1, numBlock, samLoc; // numLoc : Number of times to localize in a second\n    samLoc = samF/numLoc; // minimum samples required to localize numLoc times in a second\n    Eigen::VectorXd coilfreq(numCoils);\n    coilfreq[0] = 154;coilfreq[1] = 158;coilfreq[2] = 162;coilfreq[3] = 166;\n\n    // Initialize HPI coils location and moment\n    coil.pos = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.mom = Eigen::MatrixXd::Zero(numCoils,3);\n\n    // Generate simulated data\n    Eigen::MatrixXd simsig(samLoc,numCoils*2);\n    Eigen::VectorXd time(samLoc);\n\n    for (int i = 0;i < samLoc;i++) time[i] = i*1.0/samF;\n\n    for(int i=0;i<numCoils;i++) {\n        for(int j=0;j<samLoc;j++) {\n            simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]);\n            simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]);\n        }\n    }\n\n\n    // Get the indices of inner layer channels\n    QVector<int> innerind(0);\n    for (int i = 0;i < numCh;i++) {\n        if(m_pFiffInfo->chs[i].coil_type == 7002) {\n            // Check if the sensor is bad, if not append to innerind\n            if(!(m_pFiffInfo->bads.contains(m_pFiffInfo->ch_names.at(i)))) innerind.append(i);\n        }\n    }\n\n    // Initialize inner layer sensors\n    sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size());\n\n    for(int i=0;i<innerind.size();i++) {\n        sensors.coilpos(i,0) = m_pFiffInfo->chs[innerind.at(i)].loc(0,0);\n        sensors.coilpos(i,1) = m_pFiffInfo->chs[innerind.at(i)].loc(1,0);\n        sensors.coilpos(i,2) = m_pFiffInfo->chs[innerind.at(i)].loc(2,0);\n        sensors.coilori(i,0) = m_pFiffInfo->chs[innerind.at(i)].loc(9,0);\n        sensors.coilori(i,1) = m_pFiffInfo->chs[innerind.at(i)].loc(10,0);\n        sensors.coilori(i,2) = m_pFiffInfo->chs[innerind.at(i)].loc(11,0);\n    }\n\n    //load polhemus HPI\n    Eigen::MatrixXd headHPI(numCoils,3);\n\n    // check the m_pFiffInfo->dig information. If dig is empty, set the headHPI is 0;\n    if (m_pFiffInfo->dig.size()>0)\n    {\n        for (int i=0;i<numCoils;i++) {\n            headHPI(i,0) = m_pFiffInfo->dig.at(i+3).r[0];headHPI(i,1) = m_pFiffInfo->dig.at(i+3).r[1];headHPI(i,2) = m_pFiffInfo->dig.at(i+3).r[2];\n        }\n    }\n    else\n    {\n        for (int i=0;i<numCoils;i++) {\n            headHPI(i,0) = 0;headHPI(i,1) = 0;headHPI(i,2) = 0;\n        }\n        qDebug()<< \"Forget to load polhemus HPI! Please stop running and load it again!\";\n    }\n\n    Eigen::MatrixXd topo(innerind.size(),numCoils*2);\n    Eigen::MatrixXd amp(innerind.size(),numCoils);\n    Eigen::Matrix4d trans;\n\n\n    QVector<MatrixXd> buffer;\n    double phase;\n\n    while(m_bIsRunning)\n    {\n        if(m_pRawMatrixBuffer)\n        {\n            MatrixXd t_mat = m_pRawMatrixBuffer->pop();\n\n            buffer.append(t_mat);\n\n            if(buffer.size()*t_mat.cols() >= samLoc) {\n\n                Eigen::MatrixXd alldata(t_mat.rows(),buffer.size()*t_mat.cols());\n\n                // Concatenate data into a matrix\n                for(int i=0;i<buffer.size();i++) alldata << buffer[i];\n\n                // Get the data from inner layer channels\n                Eigen::MatrixXd innerdata(innerind.size(),samLoc);\n\n                numBlock = alldata.cols()/samLoc;\n\n                // Loop for localizing coils\n                for(int i = 0;i<numBlock;i++) {\n                    for(int j = 0;j < innerind.size();j++)\n                        innerdata.row(j) << alldata.block(innerind[j],i*samLoc,1,samLoc);\n\n\n                    topo = innerdata * pinv(simsig).transpose();\n\n                    amp = (topo.leftCols(numCoils).array().square() + topo.rightCols(numCoils).array().square()).array().sqrt();\n\n\n                    for (int i = 0;i < numCoils;i++) {\n                        for (int j = 0;j < innerind.size();j++) {\n                            phase = atan2(topo(j,i+numCoils),topo(j,i)) * 180/M_PI;\n                            if(phase < 0) phase = 360 + phase;\n                            if(phase <= 90) phase = 1;\n                            else if(phase > 90 || phase <= 270) phase = -1;\n                            else phase = 1;\n\n                            amp(j,i) = amp(j,i) * phase;\n\n                        }\n                    }\n\n\n                    coil = dipfit(coil, sensors, amp, numCoils);\n\n                    qDebug()<<\"HPI head \"<<headHPI(0,0)<<\" \"<<headHPI(0,1)<<\" \"<<headHPI(0,2);\n                    qDebug()<<\"HPI head \"<<headHPI(1,0)<<\" \"<<headHPI(1,1)<<\" \"<<headHPI(1,2);\n                    qDebug()<<\"HPI head \"<<headHPI(2,0)<<\" \"<<headHPI(2,1)<<\" \"<<headHPI(2,2);\n                    qDebug()<<\"HPI head \"<<headHPI(3,0)<<\" \"<<headHPI(3,1)<<\" \"<<headHPI(3,2);\n\n\n                    qDebug()<<\"HPI device \"<<coil.pos(0,0)<<\" \"<<coil.pos(0,1)<<\" \"<<coil.pos(0,2);\n                    qDebug()<<\"HPI device \"<<coil.pos(1,0)<<\" \"<<coil.pos(1,1)<<\" \"<<coil.pos(1,2);\n                    qDebug()<<\"HPI device \"<<coil.pos(2,0)<<\" \"<<coil.pos(2,1)<<\" \"<<coil.pos(2,2);\n                    qDebug()<<\"HPI device \"<<coil.pos(3,0)<<\" \"<<coil.pos(3,1)<<\" \"<<coil.pos(3,2);\n\n                    trans = computeTransformation(coil.pos,headHPI);\n\n                    for(int ti =0; ti<4;ti++)\n                        for(int tj=0;tj<4;tj++)\n                    m_pFiffInfo->dev_head_t.trans(ti,tj) = trans(ti,tj);\n\n                }\n                buffer.clear();\n            }\n\n\n        }//m_pRawMatrixBuffer\n\n\n\n    } //m_bIsRunning\n\n}\n\n//*************************************************************************************************************\n\nvoid RtHPIS::test()\n{\n\n    struct sens sensors;\n    struct coilParam coil;\n    int numCoils = 4;\n    int numCh = m_pFiffInfo->nchan;\n    int samF = m_pFiffInfo->sfreq;\n    int numLoc = 3, numBlock, samLoc; // numLoc : Number of times to localize in a second\n    samLoc = samF/numLoc; // minimum samples required to localize numLoc times in a second\n    Eigen::VectorXd coilfreq(numCoils);\n    coilfreq[0] = 154;coilfreq[1] = 158;coilfreq[2] = 162;coilfreq[3] = 166;\n\n    // Initialize HPI coils location and moment\n    coil.pos = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.mom = Eigen::MatrixXd::Zero(numCoils,3);\n\n    // Generate simulated data\n    Eigen::MatrixXd simreal(numCoils,samLoc);\n    Eigen::MatrixXd simimag(numCoils,samLoc);\n    Eigen::VectorXd time(samLoc);\n\n    for (int i = 0;i < samLoc;i++) time[i] = i*1.0/samF;\n\n    double coilnorm;\n\n    for(int i=0;i<numCoils;i++) {\n        for(int j=0;j<samLoc;j++) {\n            simreal(i,j) = cos(2*M_PI*coilfreq[i]*time[j]);\n            simimag(i,j) = sin(2*M_PI*coilfreq[i]*time[j]);\n        }\n        coilnorm = sqrt((simreal.row(i).array().square() + simimag.row(i).array().square()).array().sum());\n        simreal.row(i) = simreal.row(i) / coilnorm;\n        simimag.row(i) = simimag.row(i) / coilnorm;\n    }\n\n    // Get the indices of reference channels\n    QVector<int> refind(0);\n    if (m_pFiffInfo->ch_names.indexOf(\"TRG013\",0) >= 0) refind.append(m_pFiffInfo->ch_names.indexOf(\"TRG009\",0)+1);\n    if (m_pFiffInfo->ch_names.indexOf(\"TRG014\",0) >= 0) refind.append(m_pFiffInfo->ch_names.indexOf(\"TRG010\",0)+1);\n    if (m_pFiffInfo->ch_names.indexOf(\"TRG015\",0) >= 0) refind.append(m_pFiffInfo->ch_names.indexOf(\"TRG011\",0)+1);\n    if (m_pFiffInfo->ch_names.indexOf(\"TRG016\",0) >= 0) refind.append(m_pFiffInfo->ch_names.indexOf(\"TRG012\",0)+1);\n\n    // Get the indices of inner layer channels\n    QVector<int> innerind(0);\n    for (int i = 0;i < numCh;i++) {\n        if(m_pFiffInfo->chs[i].coil_type == 7002) {\n            // Check if the sensor is bad, if not append to innerind\n            if(!(m_pFiffInfo->bads.contains(m_pFiffInfo->ch_names.at(i)))) innerind.append(i);\n        }\n    }\n\n    // Initialize inner layer sensors\n    sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size());\n\n    for(int i=0;i<innerind.size();i++) {\n        sensors.coilpos(i,0) = m_pFiffInfo->chs[innerind.at(i)].loc(0,0);\n        sensors.coilpos(i,1) = m_pFiffInfo->chs[innerind.at(i)].loc(1,0);\n        sensors.coilpos(i,2) = m_pFiffInfo->chs[innerind.at(i)].loc(2,0);\n        sensors.coilori(i,0) = m_pFiffInfo->chs[innerind.at(i)].loc(9,0);\n        sensors.coilori(i,1) = m_pFiffInfo->chs[innerind.at(i)].loc(10,0);\n        sensors.coilori(i,2) = m_pFiffInfo->chs[innerind.at(i)].loc(11,0);\n    }\n\n    //load polhemus HPI\n    Eigen::MatrixXd headHPI(numCoils,3);\n\n    // check the m_pFiffInfo->dig information. If dig is empty, set the headHPI is 0;\n    if (m_pFiffInfo->dig.size()>0)\n    {\n        for (int i=0;i<numCoils;i++) {\n            headHPI(i,0) = m_pFiffInfo->dig.at(i+3).r[0];\n            headHPI(i,1) = m_pFiffInfo->dig.at(i+3).r[1];\n            headHPI(i,2) = m_pFiffInfo->dig.at(i+3).r[2];\n        }\n    }\n    else\n    {\n        for (int i=0;i<numCoils;i++) {\n            headHPI(i,0) = 0;\n            headHPI(i,1) = 0;\n            headHPI(i,2) = 0;\n        }\n        qDebug()<< \"Forget to load polhemus HPI! Please stop running and load it again!\";\n    }\n\n    Eigen::MatrixXd ampreal(innerind.size(),numCoils);\n    Eigen::MatrixXd ampimag(innerind.size(),numCoils);\n    Eigen::Matrix4d trans;\n    Eigen::MatrixXd phasereal(1,samLoc);\n    Eigen::MatrixXd phaseimag(1,samLoc);\n    Eigen::MatrixXd ampl(1,samLoc);\n\n    QVector<MatrixXd> buffer;\n\n\n    while(m_bIsRunning)\n    {\n        if(m_pRawMatrixBuffer)\n        {\n            MatrixXd t_mat = m_pRawMatrixBuffer->pop();\n\n\n\n\n\n            buffer.append(t_mat);\n\n            if(buffer.size()*t_mat.cols() >= samLoc) {\n\n                Eigen::MatrixXd alldata(t_mat.rows(),buffer.size()*t_mat.cols());\n\n                // Concatenate data into a matrix\n                for(int i=0;i<buffer.size();i++) alldata << buffer[i];\n\n\n                // Get the data from inner layer channels\n                Eigen::MatrixXd innerdata(innerind.size(),samLoc);\n                Eigen::MatrixXd refdata(numCoils,samLoc);\n\n                numBlock = alldata.cols()/samLoc;\n\n                // Loop for localizing coils\n                for(int i = 0;i<numBlock;i++) {\n\n                    for(int j = 0;j < innerind.size();j++) {\n                        std::cout << innerind[j] << std::endl;\n                        innerdata.row(j) << alldata.block(innerind[j],i*samLoc,1,samLoc);\n                    }\n\n                    for(int j = 0;j < refind.size();j++)\n                        refdata.row(j) << alldata.block(refind[j],i*samLoc,1,samLoc);\n\n                    ampreal = innerdata*simreal.transpose();\n                    ampimag = innerdata*simimag.transpose()*-1;\n\n                    phasereal = (refdata.array() * simreal.array()).array().colwise().sum();\n                    phaseimag = (refdata.array() * simimag.array()).array().colwise().sum();\n\n                    ampl = sqrt(phasereal.array().square() + phaseimag.array().square());\n\n                    phasereal = phasereal.array() / ampl.array();\n                    phaseimag = phaseimag.array() / ampl.array();\n\n                    for(int i = 0;i < numCoils;i++)\n                        ampreal.col(i).array() = ampreal.col(i) * phasereal(i) - ampimag.col(i) * phaseimag(i);\n\n//                    for(int i = 0;i<innerdata.rows();i++) {\n//                        for(int j=0;j<4;j++) {\n//                            std::cout<<innerdata(i,j)<< \"  \";\n\n//                        }\n//                        std::cout << std::endl;\n//                     }\n\n\n\n\n//                    std::cout << ampreal.rows() << std::endl;\n//                    std::cout << ampreal.cols() << std::endl;\n\n                    coil = dipfit(coil, sensors, ampreal, numCoils);\n\n                    qDebug()<<\"HPI head \"<<headHPI(0,0)<<\" \"<<headHPI(0,1)<<\" \"<<headHPI(0,2);\n                    qDebug()<<\"HPI head \"<<headHPI(1,0)<<\" \"<<headHPI(1,1)<<\" \"<<headHPI(1,2);\n                    qDebug()<<\"HPI head \"<<headHPI(2,0)<<\" \"<<headHPI(2,1)<<\" \"<<headHPI(2,2);\n                    qDebug()<<\"HPI head \"<<headHPI(3,0)<<\" \"<<headHPI(3,1)<<\" \"<<headHPI(3,2);\n\n\n                    qDebug()<<\"HPI device \"<<coil.pos(0,0)<<\" \"<<coil.pos(0,1)<<\" \"<<coil.pos(0,2);\n                    qDebug()<<\"HPI device \"<<coil.pos(1,0)<<\" \"<<coil.pos(1,1)<<\" \"<<coil.pos(1,2);\n                    qDebug()<<\"HPI device \"<<coil.pos(2,0)<<\" \"<<coil.pos(2,1)<<\" \"<<coil.pos(2,2);\n                    qDebug()<<\"HPI device \"<<coil.pos(3,0)<<\" \"<<coil.pos(3,1)<<\" \"<<coil.pos(3,2);\n\n                    trans = computeTransformation(coil.pos,headHPI);\n\n                    for(int ti =0; ti<4;ti++)\n                        for(int tj=0;tj<4;tj++)\n                    m_pFiffInfo->dev_head_t.trans(ti,tj) = trans(ti,tj);\n\n                }\n                buffer.clear();\n            }\n\n\n        }//m_pRawMatrixBuffer\n\n\n\n    } //m_bIsRunning\n\n}\n\n\n/*********************************************************************************\n * dipfit function is adapted from Fieldtrip Software. It has been\n * heavily edited for use with MNE-X Software\n *********************************************************************************/\n\ncoilParam RtHPIS::dipfit(struct coilParam coil, struct sens sensors, Eigen::MatrixXd data, int numCoils)\n{\n    // Initialize variables\n    int display = 0;\n    int maxiter = 100;\n\n    dipError temp;\n\n    for(int i = 0;i<numCoils;i++) {\n        coil.pos.row(i).array() = fminsearch(coil.pos.row(i), maxiter, 2 * maxiter * coil.pos.cols(), display, data.col(i), sensors);\n        temp = dipfitError(coil.pos.row(i), data.col(i), sensors);\n        coil.mom = temp.moment.transpose();\n    }\n\n\n    return coil;\n}\n\n/*********************************************************************************\n * fminsearch Multidimensional unconstrained nonlinear minimization (Nelder-Mead).\n * X = fminsearch(X0, maxiter, maxfun, display, data, sensors) starts at X0 and\n * attempts to find a local minimizer\n *********************************************************************************/\n\nEigen::MatrixXd RtHPIS::fminsearch(Eigen::MatrixXd pos,int maxiter, int maxfun, int display, Eigen::MatrixXd data, struct sens sensors)\n{\n    double tolx, tolf, rho, chi, psi, sigma, func_evals, usual_delta, zero_term_delta, temp1, temp2;\n    std::string header, how;\n    int n, itercount, prnt;\n    Eigen::MatrixXd onesn, two2np1, one2n, v, y, v1, tempX1, tempX2, xbar, xr, x, xe, xc, xcc, xin;\n    std::vector <double> fv, fv1;\n    std::vector <int> idx;\n\n    dipError tempdip, fxr, fxe, fxc, fxcc;\n\n    tolx = tolf = 1e-4;\n\n    switch(display)\n    {\n        case 0:\n            prnt = 0;\n            break;\n        default:\n            prnt = 1;\n    }\n\n    header = \" Iteration   Func-count     min f(x) Procedure\";\n\n    n = pos.cols();\n\n    // Initialize parameters\n    rho = 1; chi = 2; psi = 0.5; sigma = 0.5;\n    onesn = Eigen::MatrixXd::Ones(1,n);\n    two2np1 = one2n = Eigen::MatrixXd::Zero(1,n);\n\n    for(int i = 0;i < n;i++) {\n        two2np1(i) = 1 + i;\n        one2n(i) = i;\n    }\n\n    v = v1 = Eigen::MatrixXd::Zero(n, n+1);\n    fv.resize(n+1);idx.resize(n+1);fv1.resize(n+1);\n\n    for(int i = 0;i < n; i++) v(i,0) = pos(i);\n\n    tempdip = dipfitError(pos, data, sensors);\n    fv[0] = tempdip.error;\n\n\n    func_evals = 1;itercount = 0;how = \"\";\n\n    // Continue setting up the initial simplex.\n    // Following improvement suggested by L.Pfeffer at Stanford\n    usual_delta = 0.05;             // 5 percent deltas for non-zero terms\n    zero_term_delta = 0.00025;      // Even smaller delta for zero elements of x\n    xin = pos.transpose();\n\n    for(int j = 0;j < n;j++) {\n        y = xin;\n\n        if(y(j) != 0) y(j) = (1 + usual_delta) * y(j);\n        else y(j) = zero_term_delta;\n\n        v.col(j+1).array() = y;\n        pos = y.transpose();\n        tempdip = dipfitError(pos, data, sensors);\n        fv[j+1] = tempdip.error;\n    }\n\n    // Sort elements of fv\n    base_arr = fv;\n    for (int i = 0; i < n+1; i++) idx[i] = i;\n\n    sort (idx.begin(), idx.end(), RtHPIS::compar);\n\n    for (int i = 0;i < n+1;i++) {\n        v1.col(i) = v.col(idx[i]);\n        fv1[i] = fv[idx[i]];\n    }\n\n    v = v1;fv = fv1;\n\n    how = \"initial simplex\";\n    itercount = itercount + 1;\n    func_evals = n + 1;\n\n    tempX1 = Eigen::MatrixXd::Zero(1,n);\n\n    while ((func_evals < maxfun) && (itercount < maxiter)) {\n        for (int i = 0;i < n;i++) tempX1(i) = abs(fv[0] - fv[i+1]);\n        temp1 = tempX1.maxCoeff();\n\n        tempX2 = Eigen::MatrixXd::Zero(n,n);\n\n        for(int i = 0;i < n;i++) tempX2.col(i) = v.col(i+1) -  v.col(0);\n\n        tempX2 = tempX2.array().abs();\n\n        temp2 = tempX2.maxCoeff();\n\n        if((temp1 <= tolf) && (temp2 <= tolx)) break;\n\n        xbar = v.block(0,0,n,n).rowwise().sum();\n        xbar /= n;\n\n        xr = (1+rho) * xbar - rho * v.block(0,n,v.rows(),1);\n\n        x = xr.transpose();\n        //std::cout << \"Iteration Count: \" << itercount << \":\" << x << std::endl;\n\n        fxr = dipfitError(x, data, sensors);\n\n        func_evals = func_evals+1;\n\n        if (fxr.error < fv[0]) {\n            // Calculate the expansion point\n            xe = (1 + rho * chi) * xbar - rho * chi * v.col(v.cols()-1);\n            x = xe.transpose();\n            fxe = dipfitError(x, data, sensors);\n            func_evals = func_evals+1;\n\n            if(fxe.error < fxr.error) {\n                v.col(v.cols()-1) = xe;\n                fv[n] = fxe.error;\n                how = \"expand\";\n            }\n            else {\n                v.col(v.cols()-1) = xr;\n                fv[n] = fxr.error;\n                how = \"reflect\";\n            }\n        }\n        else {\n            if(fxr.error < fv[n-1]) {\n                v.col(v.cols()-1) = xr;\n                fv[n] = fxr.error;\n                how = \"reflect\";\n            }\n            else { // fxr.error >= fv[:,n-1]\n                // Perform contraction\n                if(fxr.error < fv[n]) {\n                    // Perform an outside contraction\n                    xc = (1 + psi * rho) * xbar - psi * rho * v.col(v.cols()-1);\n                    x = xc.transpose();\n                    fxc = dipfitError(x, data, sensors);\n                    func_evals = func_evals + 1;\n\n                    if(fxc.error <= fxr.error) {\n                        v.col(v.cols()-1) = xc;\n                        fv[n] = fxc.error;\n                        how = \"contract outside\";\n                    }\n                    else {\n                        // perform a shrink\n                        how = \"shrink\";\n                    }\n                }\n                else {\n                    xcc = (1 - psi) * xbar + psi * v.col(v.cols()-1);\n                    x = xcc.transpose();\n                    fxcc = dipfitError(x, data, sensors);\n                    func_evals = func_evals+1;\n                    if(fxcc.error < fv[n]) {\n                        v.col(v.cols()-1) = xcc;\n                        fv[n] = fxcc.error;\n                        how = \"contract inside\";\n                    }\n                    else {\n                        // perform a shrink\n                        how = \"shrink\";\n                    }\n                }\n                if(how.compare(\"shrink\") == 0) {\n                    for(int j = 1;j < n+1;j++) {\n                        v.col(j).array() = v.col(0).array() + sigma * (v.col(j).array() - v.col(0).array());\n                        x = v.col(j).array().transpose();\n                        tempdip = dipfitError(x,data, sensors);\n                        fv[j] = tempdip.error;\n                    }\n                }\n            }\n        }\n        // Sort elements of fv\n        base_arr = fv;\n        for (int i = 0; i < n+1; i++) idx[i] = i;\n        sort (idx.begin (), idx.end (), compar);\n        for (int i = 0;i < n+1;i++) {\n            v1.col(i) = v.col(idx[i]);\n            fv1[i] = fv[idx[i]];\n        }\n        v = v1;fv = fv1;\n        itercount = itercount + 1;\n    }\n\n    x = v.col(0).transpose();\n\n    return x;\n}\n\n\n/*********************************************************************************\n * dipfitError computes the error between measured and model data\n * and can be used for non-linear fitting of dipole position.\n * The function has been compared with matlab dipfit_error and it gives\n * same output\n *********************************************************************************/\n\ndipError RtHPIS::dipfitError(Eigen::MatrixXd pos, Eigen::MatrixXd data, struct sens sensors)\n{\n    // Variable Declaration\n    struct dipError e;\n    Eigen::MatrixXd lf, dif;\n\n    // Compute lead field for a magnetic dipole in infinite vacuum\n    lf = ft_compute_leadfield(pos, sensors);\n\n    e.moment = pinv(lf) * data;\n\n    dif = data - lf * e.moment;\n\n    e.error = dif.array().square().sum()/data.array().square().sum();\n\n    return e;\n}\n\n/*********************************************************************************\n * ft_compute_leadfield computes a forward solution for a dipole in a a volume\n * conductor model. The forward solution is expressed as the leadfield\n * matrix (Nchan*3), where each column corresponds with the potential or field\n * distributions on all sensors for one of the x,y,z-orientations of the dipole.\n * The function has been compared with matlab ft_compute_leadfield and it gives\n * same output\n *********************************************************************************/\n\nEigen::MatrixXd RtHPIS::ft_compute_leadfield(Eigen::MatrixXd pos, struct sens sensors)\n{\n\n    Eigen::MatrixXd pnt, ori, lf;\n\n    pnt = sensors.coilpos; // position of each coil\n    ori = sensors.coilori; // orientation of each coil\n\n    lf = magnetic_dipole(pos, pnt, ori);\n\n    lf = sensors.tra * lf;\n\n    return lf;\n}\n\n/*********************************************************************************\n * magnetic_dipole leadfield for a magnetic dipole in an infinite medium\n * The function has been compared with matlab magnetic_dipole and it gives same output\n *********************************************************************************/\n\nEigen::MatrixXd RtHPIS::magnetic_dipole(Eigen::MatrixXd pos, Eigen::MatrixXd pnt, Eigen::MatrixXd ori) {\n\n    double u0 = 1e-7;\n    int nchan;\n    Eigen::MatrixXd r, r2, r5, x, y, z, mx, my, mz, Tx, Ty, Tz, lf, temp;\n\n    nchan = pnt.rows();\n\n    // Shift the magnetometers so that the dipole is in the origin\n    pnt.array().col(0) -= pos(0);pnt.array().col(1) -= pos(1);pnt.array().col(2) -= pos(2);\n\n    r = pnt.array().square().rowwise().sum().sqrt();\n\n   r2 = r5 = x = y = z = mx = my = mz = Tx = Ty = Tz = lf = Eigen::MatrixXd::Zero(nchan,3);\n\n    for(int i = 0;i < nchan;i++) {\n            r2.row(i).array().fill(pow(r(i),2));\n            r5.row(i).array().fill(pow(r(i),5));\n    }\n\n    for(int i = 0;i < nchan;i++) {\n        x.row(i).array().fill(pnt(i,0));\n        y.row(i).array().fill(pnt(i,1));\n        z.row(i).array().fill(pnt(i,2));\n    }\n    mx.col(0).array().fill(1);my.col(1).array().fill(1);mz.col(2).array().fill(1);\n\n    Tx = 3 * x.cwiseProduct(pnt) - mx.cwiseProduct(r2);\n    Ty = 3 * y.cwiseProduct(pnt) - my.cwiseProduct(r2);\n    Tz = 3 * z.cwiseProduct(pnt) - mz.cwiseProduct(r2);\n\n    for(int i = 0;i < nchan;i++) {\n        lf(i,0) = Tx.row(i).dot(ori.row(i));\n        lf(i,1) = Ty.row(i).dot(ori.row(i));\n        lf(i,2) = Tz.row(i).dot(ori.row(i));\n    }\n\n    for(int i = 0;i < nchan;i++) {\n        for(int j = 0;j < 3;j++) {\n            lf(i,j) = u0 * lf(i,j)/(4 * M_PI * r5(i,j));\n        }\n    }\n    return lf;\n}\n\nbool RtHPIS::compar (int a, int b){\n  return ((base_arr)[a] < (base_arr)[b]);\n}\n\nEigen::Matrix4d RtHPIS::computeTransformation(Eigen::MatrixXd NH, Eigen::MatrixXd BT)\n{\n    Eigen::MatrixXd xdiff, ydiff, zdiff, C, Q;\n    Eigen::Matrix4d trans = Eigen::Matrix4d::Identity(4,4), Rot = Eigen::Matrix4d::Zero(4,4), Trans = Eigen::Matrix4d::Identity(4,4);\n    double meanx,meany,meanz,normf;\n\n    for(int i = 0;i < 15;i++) {\n        zdiff = NH.col(2) - BT.col(2);\n        ydiff = NH.col(1) - BT.col(1);\n        xdiff = NH.col(0) - BT.col(0);\n\n        meanx=xdiff.mean();\n        meany=ydiff.mean();\n        meanz=zdiff.mean();\n\n        for (int j=0;j<NH.rows();j++) {\n            BT(j,0) = BT(j,0) + meanx;\n            BT(j,1) = BT(j,1) + meany;\n            BT(j,2) = BT(j,2) + meanz;\n        }\n\n        C = BT.transpose() * NH;\n\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd(C ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n        Q = svd.matrixU() * svd.matrixV().transpose();\n\n        BT = BT * Q;\n\n        normf = (NH.transpose()-BT.transpose()).norm();\n\n        for(int j=0;j<3;j++) {\n            for(int k=0;k<3;k++) Rot(j,k) = Q(k,j);\n        }\n\n        Rot(3,3) = 1;\n        Trans(0,3) = meanx;Trans(1,3) = meany;Trans(2,3) = meanz;\n        trans = Rot * Trans * trans;\n    }\n    return trans;\n}\n\nEigen::MatrixXd RtHPIS::pinv(Eigen::MatrixXd a)\n{\n    double epsilon = std::numeric_limits<double>::epsilon();\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n    double tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs()(0);\n    return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(),0).matrix().asDiagonal() * svd.matrixU().adjoint();\n}\nstd::vector <double>RtHPIS::base_arr;\n\n", "meta": {"hexsha": "335e110134c95b0ccbbbbc99e2294219d6d05d68", "size": 30949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/rtProcessing/rthpis.cpp", "max_stars_repo_name": "yvnxs/mne-cpp", "max_stars_repo_head_hexsha": "29c90a86f49c843b5f0ca8f9180cb38e0e774176", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-18T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T08:33:44.000Z", "max_issues_repo_path": "MNE/rtProcessing/rthpis.cpp", "max_issues_repo_name": "yvnxs/mne-cpp", "max_issues_repo_head_hexsha": "29c90a86f49c843b5f0ca8f9180cb38e0e774176", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/rtProcessing/rthpis.cpp", "max_forks_repo_name": "yvnxs/mne-cpp", "max_forks_repo_head_hexsha": "29c90a86f49c843b5f0ca8f9180cb38e0e774176", "max_forks_repo_licenses": ["BSD-3-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.4107551487, "max_line_length": 238, "alphanum_fraction": 0.4957833856, "num_tokens": 8142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.014957087114567837, "lm_q1q2_score": 0.004900963516459496}}
{"text": "// Author: Mohamed Aly <malaa@vision.caltech.edu>\n// Date: October 6, 2010\n\n#include <cstdlib>\n#include <cmath>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <iterator>\n#include <boost/random.hpp>\n\n#include \"ccCommon.hpp\"\n#include \"ccLsh.hpp\"\n\n//random number generator\n//boost::lagged_fibonacci23209         randEngine(0x123456);\nboost::mt19937                      randEngine(0x123456);\n//boost::uniform_01<boost::mt19937>   randUniReal(randEngine);\n//boost::uniform_int<uint32_t>        randUniInt;\n//boost::normal_distribution<double>  randNorm;\n\n\n\n//a random number between 0 -> 1\n//#define URAND (((double)randEngine() - randEngine().min()) / (double)randEngine().max_value)\n//#define URAND (randEngine())\n//#define URAND ((double)randUniInt(randEngine) / randUniInt.max())\n//#define URAND (randUniReal())\n#define URAND ((double)rand() / (double)RAND_MAX)\n\n//get a random number between M1->M2-1\n#define RAND(M1, M2) (URAND * ((M2)-(M1)) + (M1))\n//#define RAND(M1, M2) ((double)randUniInt(randEngine) / randUniInt.max() * ((M2)-(M1)) + (M1))\n//#define RAND(M1, M2) (float)rand() / (float)RAND_MAX * ((M2)-(M1)) + (M1)\n//#define RAND(M2) RAND(0,M2)\n\n#define IRAND(M1, M2) floor(RAND(M1,M2))\n//#define IRAND(M2) IRAND(0,M2)\n\n\n//normal random\n//#define NRAND   randNorm(randEngine)\n#define NRAND randn()\n\n//PI\n#define PI 3.141592653589793f\n\n//------------------------------------------------------------------------\n// // Template function definitions\n// #define TEMPLATE(F)         \\\n//   F(float)                  \\\n//   F(double)                 \\\n//   F(char)                   \\\n//   F(int)                    \\\n//   F(unsigned int)           \\\n//   F(unsigned char)          \n  \n#define SEARCHPOINTS(T) \\\n  template void searchPoints(Lsh&, Data<T>&, LshPointList*);\n\n#define INSERTPOINTS(T) \\\n  template void insertPoints(Lsh&, Data<T>&, uint);\n\n#define BUCKETID(T) \\\n  template void getBucketId(Lsh&, Data<T>&, BucketIdList*);\n\n#define GETFUNCVAL(T) \\\ntemplate void getFuncVal(Lsh&, Data<T>&, LshFuncValList*);\n\n#define GETKNN_FL(T) \\\ntemplate void getKnn(Lsh&, Data<T>&, Data<T>&, uint k, DistanceType, uint*, float* );\n\n#define GETKNN_DB(T) \\\ntemplate void getKnn(Lsh&, Data<T>&, Data<T>&, uint k, DistanceType, uint*, double* );\n\n\nTEMPLATE(SEARCHPOINTS)\nTEMPLATE(INSERTPOINTS)\nTEMPLATE(BUCKETID)\nTEMPLATE(GETFUNCVAL)\nTEMPLATE(GETKNN_FL)\nTEMPLATE(GETKNN_DB)\n\n//-----------------------------------------------------------------------\n/// stream overloads for LshOptions\nostream& operator<<(ostream& s, LshOptions& o)\n{\n  //write\n  s.write((char*) &o, sizeof(LshOptions));\n//  s.write((char*) &o.ntables, sizeof(o.ntables));\n//  s.write((char*) &o.nfuncs, sizeof(o.nfuncs));\n//  s.write((char*) &o.htype, sizeof(o.htype));\n//  s.write((char*) &o.dist, sizeof(o.dist));\n//  s.write((char*) &o.norm, sizeof(o.norm));\n//  s.write((char*) &o.ndims, sizeof(o.ndims));\n//  s.write((char*) &o.nbits, sizeof(o.nbits));\n//  s.write((char*) &o.hwidth, sizeof(o.hwidth));\n//  s.write((char*) &o.opt1, sizeof(o.opt1));\n//  s.write((char*) &o.opt2, sizeof(o.opt2));\n//  s.write((char*) &o.tablesize, sizeof(o.tablesize));\n//  s.write((char*) &o.str, sizeof(o.str));\n//  s.write((char*) &o.forest, sizeof(o.forest));\n//  s.write((char*) &o.verbose, sizeof(o.verbose));\n}\n\nistream& operator>>(istream& s, LshOptions& o)\n{\n  //read\n  s.read((char*) &o, sizeof(LshOptions));\n//  s.read((char*) &o.ntables, sizeof(o.ntables));\n//  s.read((char*) &o.nfuncs, sizeof(o.nfuncs));\n//  s.read((char*) &o.htype, sizeof(o.htype));\n//  s.read((char*) &o.dist, sizeof(o.dist));\n//  s.read((char*) &o.norm, sizeof(o.norm));\n//  s.read((char*) &o.ndims, sizeof(o.ndims));\n//  s.read((char*) &o.nbits, sizeof(o.nbits));\n//  s.read((char*) &o.hwidth, sizeof(o.hwidth));\n//  s.read((char*) &o.opt1, sizeof(o.opt1));\n//  s.read((char*) &o.opt2, sizeof(o.opt2));\n//  s.read((char*) &o.tablesize, sizeof(o.tablesize));\n//  s.read((char*) &o.str, sizeof(o.str));\n//  s.read((char*) &o.forest, sizeof(o.forest));\n//  s.read((char*) &o.verbose, sizeof(o.verbose));\n}\n\n//-----------------------------------------------------------------------\n// a simple function to compute standard gaussian random numbers\n// using Box-Muller polar transformations\ninline float randn()\n{\n  float x1, x2, w;\n  do \n  { \n    x1 = 2.0 * URAND - 1.0; \n    x2 = 2.0 * URAND - 1.0; \n    w = x1 * x1 + x2 * x2; \n  } while ( w >= 1.0  || w == 0); \n  return x1 * sqrt(-2.0 * log( w ) / w);\n}\n\n//-----------------------------------------------------------------------\n// a simple hash function that returns the remainder modulo a prime number\n// using Rabin's algorithm\ninline uint64_t hash(uint64_t v) { return (v % HASH_POLY); }\ninline uint64_t hash(uint32_t v) { return ((uint64_t)v % HASH_POLY); }\ninline uint64_t hash(int64_t v) { return ((uint64_t)v % HASH_POLY); }\ninline uint64_t hash(int32_t v) { return ((uint64_t)v % HASH_POLY); }\ninline uint64_t hash(float v) { return ((uint64_t)v % HASH_POLY); }\ninline uint64_t hash(double v) { return ((uint64_t)v % HASH_POLY); }\n\n\n//-----------------------------------------------------------------------\nvoid LshFunc::create(const LshOptions& opt)\n{\n  this->type = opt.htype;\n  this->ndims = (int)opt.ndims;\n  float norm = 0.;\n  switch(this->type)\n  {\n    case LSH_HASH_TYPE_HAM:\n      //choose a random dimension\n      if (!opt.bitsperdim)\n        this->func.ham = (uint)IRAND(0, opt.ndims);\n      else\n        this->func.ham = (uint)IRAND(0, opt.ndims * opt.bitsperdim);\n      break;\n      \n    case LSH_HASH_TYPE_L1:\n      // choose a random dimension\n      this->func.l1.dim = (uint)IRAND(0, opt.ndims);\n      //random shift\n      this->func.l1.s = (float)RAND(0, opt.w);\n      break;\n\n    case LSH_HASH_TYPE_L2:\n      //random shift\n      this->func.l2.b = (float)RAND(0, opt.w);\n      //allocate memory\n      this->func.l2.r = new float[(uint)opt.ndims];\n      //random direction\n      for (uint i=0; i<opt.ndims; ++i)\n      {\n//        this->func.l2.r[i] = randn();\n        this->func.l2.r[i] = (float)NRAND;\n//        cout << this->func.l2.r[i] << \" \";\n        norm += this->func.l2.r[i] * this->func.l2.r[i];\n      }\n//      cout << endl;\n      //normalize\n      norm = sqrt(norm);\n      for (uint i=0; i<opt.ndims; ++i)\n        this->func.l2.r[i] /= norm;\n      break;\n\n    case LSH_HASH_TYPE_COS:\n      //allocate memory\n      this->func.cos = new float[(uint)opt.ndims];\n      //get random direction\n      for (uint i=0; i<opt.ndims; ++i)\n      {\n//        this->func.cos[i] = randn();\n        this->func.cos[i] = (float)NRAND;\n        norm += this->func.cos[i] * this->func.cos[i];\n      }\n      //normalize\n      norm = sqrt(norm);\n      for (uint i=0; i<opt.ndims; ++i)\n        this->func.cos[i] /= norm;\n      break;\n      \n    case LSH_HASH_TYPE_MHASH:\n    \n      //choose two random numbers 0->2^32-1\n      this->func.minhash.a = (uint32_t)IRAND(0, 0xFFFFFFFF); //(uint32_t)IRAND(0, 1e6); // 0xFFFFFFFF);\n      this->func.minhash.b = (uint32_t)IRAND(0, 0xFFFFFFFF); //(uint32_t)IRAND(0, 1e6); //0xFFFFFFFF);\n//      cout << \"randmax = \" << RAND_MAX << endl << flush;\n      break;\n      \n    case LSH_HASH_TYPE_SPH_SIMPLEX:\n    case LSH_HASH_TYPE_SPH_ORTHOPLEX:\n    case LSH_HASH_TYPE_SPH_HYPERCUBE:    \n      //allocate memory\n      this->func.sphere = new float[this->ndims*(this->ndims+1)];\n      //get the random rotation matrix: loop over columns\n      for (uint j=0; j<this->ndims; ++j)\n      {\n        //generate this column\n        for (uint i=0; i<this->ndims; ++i)\n          this->func.sphere[j*this->ndims + i] = (float)NRAND;\n        //do gram-schmidt\n        for (uint k=0; k<j; ++k)\n        {\n          //get dot-product\n          float dp = 0.;\n          for (uint i=0; i<this->ndims; ++i)\n            dp += this->func.sphere[j*this->ndims + i] * this->func.sphere[k*this->ndims + i];\n          //subtract\n          for (uint i=0; i<this->ndims; ++i)\n            this->func.sphere[j*this->ndims+i] -= dp * this->func.sphere[k*this->ndims+i];\n        }\n\n        //calculate norm for this column\n        norm = 0.;\n        for (uint i=0; i<this->ndims; ++i)\n          norm += this->func.sphere[j*this->ndims+i] * this->func.sphere[j*this->ndims+i];\n        //normalize\n        norm = sqrt(norm);\n        for (uint i=0; i<this->ndims; ++i)\n          this->func.sphere[j*this->ndims+i] /= norm;\n      }\n      \n//      cout << \"matrix:\" << endl;\n//      std::copy(this->func.sphere, this->func.sphere+this->ndims*(this->ndims+1),\n//              ostream_iterator<float>(cout, \" \"));\n//      cout << endl;\n\n      //special handling for simplex\n      if (this->type == LSH_HASH_TYPE_SPH_SIMPLEX)\n      {\n        //compute temp values\n        float d1 = (this->ndims + 1 - sqrt(this->ndims+1)) / \n                (this->ndims * (this->ndims+1));\n        float d2 = (1 - sqrt(this->ndims+1)) / this->ndims - d1;\n\n        //compute vertices locations and rotate them\n        float* v = new float[this->ndims * (this->ndims+1)];\n        //loop on vertices: 1->d\n        for (uint j=0; j<this->ndims; ++j)\n          for (uint i=0; i<this->ndims; ++i)\n            v[j*this->ndims + i] = (j==i? 1. : 0.) - d1;\n        //last vertex\n        for (uint i=0; i<this->ndims; ++i)\n          v[this->ndims*this->ndims + i] = d2;\n\n        //now rotate\n        float* rot = new float[this->ndims * (this->ndims+1)];\n        for (uint j=0; j<this->ndims+1; ++j)\n          for (uint i=0; i<this->ndims; ++i)\n          {\n            float p = 0;\n            for (uint k=0; k<this->ndims; ++k)\n              p += this->func.sphere[k*this->ndims + i] * v[j*this->ndims + k];\n             rot[j*this->ndims + i] = p;\n          }\n\n        //copy rotated vertices matrix into a\n        copy(rot, rot+this->ndims*(this->ndims+1), this->func.sphere);\n\n        //cleat memory\n        delete [] v;\n        delete [] rot;\n      }\n    \n//      cout << \"xx=[\" ;\n//      std::copy(this->func.sphere, this->func.sphere+this->ndims*(this->ndims+1),\n//              ostream_iterator<float>(cout, \" \"));\n//      cout << \"];\" << endl;\n      \n      break;    \n      \n    //Binary hashing with Gaussian Kernels\n    case LSH_HASH_TYPE_BIN_GAUSS:\n      //b: uniform [0 2pi]\n      this->func.bingauss.b = (float)RAND(0, 2*PI);\n      //t: uniform [-1 1]\n      this->func.bingauss.t = (float)RAND(-1, 1);\n      //w: independent gaussian with variance opt.w\n      double l = sqrt(opt.w);\n      this->func.bingauss.w = new float[(uint)opt.ndims];      \n      for (uint i=0; i<opt.ndims; ++i)\n        this->func.bingauss.w[i] = (float)(NRAND * l);\n      \n      break;\n  }\n}\n\n//------------------------------------------------------------------------\n/// computes the bucket id for this data\ntemplate <class T>\n// uint64_t getId(LshFunc& func, const T* data, uint ndims, const LshOptions& opt,\n//         float norm1, float norm2)\nuint64_t getId(LshFunc& func, Data<T>& data, uint pid, const LshOptions& opt,\n        float norm1, float norm2)\n\n{\n  float val;\n  uint64_t ret;\n  uint i;\n  \n  //stuff for non-sparse data\n  T* point; uint ndims;\n  if (!data.isSparse())\n  {\n    pair<T*,uint> p = data.getPoint(pid);\n    point = p.first;\n    ndims = p.second;\n  }\n  //sparse\n  else\n  {\n    ndims = data.getSpPointDim(pid);\n  }\n  //rest should work just fine if not sparse, should handle sparse differently\n  //inside each one\n  \n  //which hash function\n  switch(func.type)\n  {\n    case LSH_HASH_TYPE_HAM:\n      //the bit is 1 or 0\n      if (opt.bitsperdim == 0)\n        val = point[func.func.ham]==1;\n      else\n      {\n        // compact binary data\n        int m = func.func.ham % opt.bitsperdim;\n        int d = (int) func.func.ham / opt.bitsperdim;         \n        val = (float)( static_cast<uint64_t>(point[d]) >> m \n                  & (static_cast<uint64_t>(1)) );\n//         cout << \"m: \" << m << \" d: \" << d << endl;\n      }\n      ret = (uint64_t) val;\n      break;\n      \n    case LSH_HASH_TYPE_L1:\n      //which cell is it in?\n      if (opt.norm)\n        val = floor(((float)point[func.func.l1.dim]/norm1 - func.func.l1.s + 1.) \n          / opt.w);\n      else\n        val = floor(((float)point[func.func.l1.dim] - func.func.l1.s) / opt.w);\n      ret = (uint64_t) val;\n      break;\n\n    case LSH_HASH_TYPE_L2:\n      //project the data point\n      for (i=0, val=0; i<ndims; ++i)\n      {\n        val += (float)point[i] * func.func.l2.r[i];\n//        norm += (float)point[i] * (float)point[i];\n      }      \n      //add offset to make values 0->2\n      if (opt.norm)\n      {\n        norm2 = sqrt(norm2);\n        val = (val / norm2) + 1.0; //norm2;\n      }\n      //which cell\n//      cout << \" val = \" << val << \" b=\" << func.func.l2.b << endl;\n      val = floor((val + func.func.l2.b) / opt.w);\n      ret = (uint64_t) val;\n      break;\n\n    case LSH_HASH_TYPE_COS:\n      //dot product\n      for (val=0, i=0; i<ndims; ++i)\n        val += (float)point[i] * func.func.cos[i];\n      //get sign\n      val = val>=0 ? 1 : 0;\n      ret = (uint64_t) val;\n      break;\n      \n    case LSH_HASH_TYPE_MHASH:\n      //init\n      ret = 0xffffffffffffffffl;\n      uint64_t h;\n      //loop \n      for (i=0; i<ndims; ++i)\n      {\n        //get hash\n        h = ((uint64_t)func.func.minhash.a * (uint64_t)point[i] + \n                (uint64_t) func.func.minhash.b) % MIN_HASH_P;\n        //compare min\n        if (h<ret)  ret = h;\n      }\n//      //compute hash values\n//      uint64_t* h = new uint64_t[ndims];\n//      for (i=0; i<ndims; ++i)\n//        h[i] = ((uint64_t)func.func.minhash.a * (uint64_t)point[i] + \n//                (uint64_t) func.func.minhash.b) % MIN_HASH_P;\n//      \n////      cout << \"  d:\"; copy(data, data+ndims, ostream_iterator<T>(cout, \" \")); cout << endl;\n////      cout << \"  h:\"; copy(h, h+ndims, ostream_iterator<uint64_t>(cout, \" \")); cout << endl;\n//              \n//      //sort and keep the minimum\n//      uint64_t* m = min_element(h, h+ndims);\n//      ret = *m;\n//      \n//      //clear\n//      delete [] h;\n\n      break;\n      \n      case LSH_HASH_TYPE_SPH_SIMPLEX:\n      {\n        //compute inner product with all vertices and get the max\n        float vmax = -10;\n        uint64_t idmax = 0;\n        //loop on vertices\n        uint j;\n        for (i=0; i<ndims+1; ++i)\n        {\n          //get dot-product\n          for (j=0, val=0.; j<ndims; ++j)\n            val += func.func.sphere[i*ndims + j] * (float)point[j];\n          val /= sqrt(norm2);\n          //compare max\n          if (val >= vmax)\n          {\n            vmax = val;\n            idmax = i;\n          }                   \n        }\n        \n        //return\n        ret = idmax;\n        break;\n      }\n      case LSH_HASH_TYPE_SPH_ORTHOPLEX:\n      {\n        //compute inner product with all vertices and get the max\n        float vmax = 0.;\n        uint64_t idmax = 0;\n        //loop on vertices\n        uint j;\n        for (i=0; i<func.ndims; ++i)\n        {\n          //get dot-product\n          for (j=0, val=0.; j<ndims; ++j)\n            val += func.func.sphere[i*ndims + j] * (float)point[j];\n          val /= sqrt(norm2);\n          //compare max\n          if ((val>=0? val : -val) >= (vmax>=0? vmax : -vmax))\n          {\n            vmax = val;\n            idmax = i;\n          }                   \n        }\n        \n        //return\n        ret = vmax>0 ? idmax : idmax + ndims;\n        break;\n      } \n      case LSH_HASH_TYPE_SPH_HYPERCUBE:\n        //compute inner products\n        ret = 0;\n        for (i=0; i<ndims; ++i)\n        {\n          //get dot-product\n          float t = 0;\n          for (uint j=0; j<ndims; ++j)\n            t += func.func.sphere[i*func.ndims + j] * (float)point[j];\n          //if +ve, update with 2^i-1\n          if (t>=0)\n            ret += (1L << (i-1));\n        }\n        break;\n    //Binary hashing with Gaussian Kernels\n    case LSH_HASH_TYPE_BIN_GAUSS:\n        //dot product of w with x: w . x + b\n        float v;\n        \n        //sparse?\n        if (!data.isSparse())\n          for (i=0; i<ndims; ++i)\n            v += func.func.bingauss.w[i] * (float)point[i];\n        //sparse\n        else\n          for (i=0; i<ndims; ++i)\n          {\n            //get sparse point val\n            uint row; T val;\n            data.getSpPointVal(pid, i, val, row);\n            //update dot product\n            v += func.func.bingauss.w[row] * (float)val;\n          }        \n        \n        //normalize if required by L2 norm\n        if (opt.norm)\n          v /= sqrt(norm2);\n        \n//         cout << \"w.x=\" << v << endl;\n        \n        //cos(w.x + b) + t\n        v = (float)cos(v + func.func.bingauss.b) + func.func.bingauss.t;\n//         cout << \" cos(w.x+b)+t=\" << v;\n        //quantize with Q(v) = sign(v)\n        v = v>=0 ? 1 : -1;\n        //get binary\n        v = 0.5 * (1 + v);\n        ret = (uint64_t) v;\n//         cout << \" final=\" << v << endl;\n        \n        break;\n      \n  }\n  \n//  cout << \"  val = \" << ret  << endl;\n//  << \" a=\" << func.func.minhash.a << \" b=\" << \n//          func.func.minhash.b << endl;\n  return ret;\n}\n\n\n//------------------------------------------------------------------------\n// Stream overloads for LshFunc\nostream& operator<<(ostream& s, LshFunc& f)\n{\n  //write type and ndims\n  s.write((char*)&f.type, sizeof(f.type));\n  s.write((char*)&f.ndims, sizeof(f.ndims));\n  \n  //write function\n  switch(f.type)\n  {\n    case LSH_HASH_TYPE_HAM:\n      s.write((char*) &f.func.ham, sizeof(f.func.ham));\n      break;\n      \n    case LSH_HASH_TYPE_L1:\n      s.write((char*) &f.func.l1.dim, sizeof(f.func.l1.dim));\n      s.write((char*) &f.func.l1.s, sizeof(f.func.l1.s));\n      break;\n\n    case LSH_HASH_TYPE_L2:\n      s.write((char*) &f.func.l2.b, sizeof(f.func.l2.b));\n      s.write((char*) f.func.l2.r, sizeof(float)*f.ndims);\n      break;\n\n    case LSH_HASH_TYPE_COS:\n      s.write((char*) f.func.cos, sizeof(float)*f.ndims);\n      break;\n      \n    case LSH_HASH_TYPE_MHASH:\n      s.write((char*) &f.func.minhash, sizeof(f.func.minhash));\n      break;\n      \n    case LSH_HASH_TYPE_SPH_SIMPLEX:\n    case LSH_HASH_TYPE_SPH_ORTHOPLEX:\n    case LSH_HASH_TYPE_SPH_HYPERCUBE:\n      s.write((char*) f.func.sphere, sizeof(float)*f.ndims*(f.ndims+1));\n      break;\n  }\n}\n\nistream& operator>>(istream& s, LshFunc& f)\n{\n  //read type and ndims\n  s.read((char*)&f.type, sizeof(f.type));\n  s.read((char*)&f.ndims, sizeof(f.ndims));\n  \n  //read function\n  switch(f.type)\n  {\n    case LSH_HASH_TYPE_HAM:\n      s.read((char*) &f.func.ham, sizeof(f.func.ham));\n      break;\n      \n    case LSH_HASH_TYPE_L1:\n      s.read((char*) &f.func.l1.dim, sizeof(f.func.l1.dim));\n      s.read((char*) &f.func.l1.s, sizeof(f.func.l1.s));\n      break;\n\n    case LSH_HASH_TYPE_L2:\n      s.read((char*) &f.func.l2.b, sizeof(f.func.l2.b));\n      f.func.l2.r = new float[f.ndims];\n      s.read((char*) f.func.l2.r, sizeof(*f.func.l2.r)*f.ndims);\n      break;\n\n    case LSH_HASH_TYPE_COS:\n      f.func.cos = new float[f.ndims];\n      s.read((char*) f.func.cos, sizeof(*f.func.l2.r)*f.ndims);\n      break;\n\n    case LSH_HASH_TYPE_MHASH:\n      s.read((char*) &f.func.minhash, sizeof(f.func.minhash));\n      break;      \n      \n    case LSH_HASH_TYPE_SPH_SIMPLEX:\n    case LSH_HASH_TYPE_SPH_ORTHOPLEX:\n    case LSH_HASH_TYPE_SPH_HYPERCUBE:\n      f.func.sphere = new float[f.ndims * (f.ndims+1)];\n      s.read((char*) f.func.sphere, sizeof(float)*f.ndims*(f.ndims+1));\n      break;\n  }  \n}\n\n//------------------------------------------------------------------------\n// Stream overloads for LshFunc\nostream& operator<<(ostream& s, LshFuncs& f)\n{\n  //first write the size\n  uint z = f.size();\n  s.write((char*) &z, sizeof(z));\n  //then write the list of functions\n  for (uint i=0; i<z; ++i)\n    s << f[i];\n}\n\nistream& operator>>(istream& s, LshFuncs& f)\n{\n  //first read the size\n  uint z;\n  s.read((char*)&z, sizeof(z));\n  //create the list and load\n  f.funcs.resize(z);\n  for (uint i=0; i<z; ++i)\n    s >> f[i];\n}\n\n//------------------------------------------------------------------------\nvoid LshBucketId::addId(uint64_t val, int pos, const LshOptions& opt)\n{\n  //string id\n  if (this->str)\n  {\n    //make a string stream\n    stringstream ss;\n    //convert the value to string\n    ss << setw((uint)opt.nbits) << val;\n    //append this value to the string id\n    this->id.s += ss.str();\n  }\n  //double id\n  else\n  {\n//    //shift the input val the right number of bits\n//    int i;\n//    double t = 1;\n//    for (i=0; i < opt.nbits * pos; ++i)\n//      t *= 2;\n//    t *= (double)val;\n//    //add the value to the id\n//    this->id.d += t;\n    \n//    //shift val the right number of bits\n//    this->id.d += (val << opt.nbits*pos);\n    \n    //compute the hash for the new value\n    //the new value f(AB) = f( f(A) * f(t^64) ) + f(B)\n    // where A = this->id.d and B = val\n    // and f(t^64) is HASH_POLY_REM specific to the HASH_POLY used\n//    this->id.d = hash(val) + hash(this->id.d * HASH_POLY_REM);\n//    cout << \" \" << this->id.d;\n    if (opt.hwidth == 0)\n      this->id.d = (val * HASH_POLY_A[pos % HASH_POLY_A_NUM] % HASH_POLY) + \n              (this->id.d * HASH_POLY_REM % HASH_POLY);\n    else\n      this->id.d = (this->id.d << opt.hwidth) | val;\n//    cout << \" + \" << val <<  \" -> \" << this->id.d << endl;\n  }\n}\n\n//------------------------------------------------------------------------\n// LshBucketId getId(LshFuncs& funcs, const T* data, uint ndims,\n//       const LshOptions& opt, float norm1, float norm2)\ntemplate <class T>\nLshBucketId getId(LshFuncs& funcs, Data<T>& data, uint pid,\n      const LshOptions& opt, float norm1, float norm2)\n{\n  //create a bucket id with the correct representation\n  LshBucketId id(opt.str);\n  \n  //loop on the individual functions\n  for (uint i=0, s=funcs.size(); i<s; ++i)\n  {\n    //get the value for this function\n    uint64_t val = getId(funcs[i], data, pid, opt, norm1, norm2);\n    \n    //combine into the Id\n    if (s>1)\n      id.addId(val, i, opt);\n    else\n      id.id.d = val;\n  }\n  \n  //return\n  return id;\n}\n\n//------------------------------------------------------------------------\n/// stream overloads\nostream& operator<<(ostream& s, LshBucketId& b)\n{\n  //put the type\n  s.write((char*) &b.str, sizeof(b.str));\n  //put the id\n  if (b.str)\n    s << b.id.s;\n  else\n    s.write((char*) &b.id.d, sizeof(b.id.d));\n}\n\nistream& operator>>(istream& s, LshBucketId& b)\n{\n  //read the type\n  s.read((char*) &b.str, sizeof(b.str));\n  //put the id\n  if (b.str)\n    s >> b.id.s;\n  else\n    s.read((char*) &b.id.d, sizeof(b.id.d));\n}\n\n\n//------------------------------------------------------------------------\n// Stream overloads for LshBucket\nostream& operator<<(ostream& s, LshBucket& b)\n{\n  //write the bucket id\n  s << b.id;\n  //put the size of list of points\n  uint z = b.size();\n  s.write((char*) &z, sizeof(z));\n  //put the ponits\n  for (uint i=0; i<z; ++i)\n    s.write((char*) &(b.plist[i]), sizeof(b.plist[i]));\n}\n\nistream& operator>>(istream& s, LshBucket& b)\n{\n  //read the bucket id\n  s >> b.id;\n  //get the size of list of points\n  uint z;\n  s.read((char*) &z, sizeof(z));\n  b.resize(z);\n  //get the ponits\n  for (uint i=0; i<z; ++i)\n    s.read((char*) &b.plist[i], sizeof(b.plist[i]));\n}\n\n//------------------------------------------------------------------------\nvoid LshFuncs::create(LshOptions& opt)\n{\n  //allocate\n  this->funcs.resize(opt.nfuncs);\n\n  //loop on the list of functions and create\n  for (uint i=0; i<opt.nfuncs; ++i)\n    this->funcs[i].create(opt);\n}\n\n//------------------------------------------------------------------------\n/// find a specific bucket in the list\nbool LshBuckets::find(const LshBucket& b, LshBucketIt& bit, uint& id)\n{\n  bool found;\n  LshBucketList* blist;\n  \n  //check if not fixed size\n  if (this->fixed == false)\n  {\n    blist = &(this->varBuckets);\n  }\n  //fixed size table, so just take the mod and go to the bucket and get its \n  //list\n  else\n  {\n    //get the index\n    id = b.id.id.d % this->fixedBuckets.size(); //opt.tablesize;\n    //get the iterator of the bucket head\n    blist = &(this->fixedBuckets[id]);\n//    //now search for it in the list\n//    bit = lower_bound(bhead->buckets.begin(), bhead->buckets.end(), b);\n//    //always found\n//    found = true;\n  }\n  \n  // binary search using lower_bound\n  bit = lower_bound(blist->begin(), blist->end(), b);\n\n  //check if found or not\n  if (bit!=blist->end() && *bit == b)\n    found = true;\n  else\n    found = false;\n  \n  //return\n  return found;\n}\n\n//------------------------------------------------------------------------\n/// insert a bucket into the list\nLshBucketIt LshBuckets::insert(LshBucket& b, LshBucketIt bit, uint id)\n{\n  //insert into the list\n  if (this->fixed)\n    bit = this->fixedBuckets[id].insert(bit, b);\n  else\n    bit = this->varBuckets.insert(bit, b);\n  \n  return bit;\n}\n\n\n//------------------------------------------------------------------------\n/// stream overloads for LshBucketList\nostream& operator<<(ostream& s, LshBucketList& b)\n{\n  //write size\n  uint z = b.size();\n  s.write((char*) &z, sizeof(z));\n  //write the list of buckets\n  for (LshBucketIt bs=b.begin(), be=b.end(); bs!=be; bs++)\n    s << *bs;  \n}\nistream& operator>>(istream& s, LshBucketList& b)\n{\n  //read size\n  uint z;\n  s.read((char*) &z, sizeof(z));\n  //allocate\n  b.resize(z);\n  //read the list of buckets\n  for (LshBucketIt bs=b.begin(), be=b.end(); bs!=be; bs++)\n    s >> *bs;  \n}\n\n//------------------------------------------------------------------------\n/// stream overloads for LshBuckets\nostream& operator<<(ostream& s, LshBuckets& b)\n{\n  //write type\n  s.write((char*) &b.fixed, sizeof(b.fixed));\n  //type?\n  if (fixed)\n  {\n    //write size\n    uint z = b.size();\n    s.write((char*) &z, sizeof(z));\n    //loop on lists and write\n    for (LshBucketListIt bs=b.fixedBuckets.begin(), be=b.fixedBuckets.end();\n      bs!=be; bs++)\n      s << *bs;\n  }\n  else\n    s << b.varBuckets;\n}\n\nistream& operator>>(istream& s, LshBuckets& b)\n{\n  //read type\n  s.read((char*) &b.fixed, sizeof(b.fixed));\n  //type?\n  if (fixed)\n  {\n    //read number of lists\n    uint z;\n    s.read((char*) &z, sizeof(z));  \n    //resize\n    b.fixedBuckets.resize(z);\n    for (LshBucketListIt bs=b.fixedBuckets.begin(), be=b.fixedBuckets.end();\n      bs!=be; bs++)\n      s >> *bs;\n  }\n  else\n    s >> b.varBuckets;\n}\n\n//------------------------------------------------------------------------\n/// create functions for this table\nvoid LshTable::createFuncs(LshOptions& opt)\n{\n  //create the functions\n  this->funcs.create(opt);\n}\n\n//------------------------------------------------------------------------\n/// stream overloads\nostream& operator<<(ostream& s, LshTable& t)\n{\n  //write funcs and buckets\n  s << t.funcs;\n  s << t.buckets;\n}\n\nistream& operator>>(istream& s, LshTable& t)\n{\n  //read\n  s >> t.funcs;\n  s >> t.buckets;\n}\n\n//------------------------------------------------------------------------\n/// stream overloads for LshTables\nostream& operator<<(ostream& s, LshTables& t)\n{\n  //write size\n  uint z = t.size();\n  s.write((char*) &z, sizeof(z));\n  //write the list of tables\n  for (uint i=0; i<z; ++i)\n    s << t[i];  \n}\n\nistream& operator>>(istream& s, LshTables& t)\n{\n  //read size\n  uint z;\n  s.read((char*) &z, sizeof(z));\n  //allocate\n  t.resize((uint)z);\n  //read the list of buckets\n  for (uint i=0; i<z; ++i)\n    s >> t[i];  \n}\n  \n//------------------------------------------------------------------------\n// void insertPoint(LshTable& lshtab, T* point, uint ndims, uint pid, \n//         LshOptions& opt, float norm1, float norm2)\ntemplate <class T>\nvoid insertPoint(LshTable& lshtab, Data<T>& data, uint inpid, uint pid,\n        LshOptions& opt, float norm1, float norm2)\n{\n//  if (opt.verbose)\n//    cout << \"Inserting point \" << pid << endl;\n  \n  // get the bucket id\n  LshBucketId bid = getId(lshtab.funcs, data, inpid, opt, norm1, norm2);\n  \n  // make a bucket and search for it\n  LshBucket b(bid);\n  bool found;\n  LshBucketIt bit;\n  uint id;\n  found = lshtab.buckets.find(b, bit, id);\n//  LshBucketIt bit = lshtab.buckets.find(b, found, opt);\n  \n//  cout << \"bucket id = \" << bid.id.d << endl;\n  \n  //if not found, isnert it\n  if (!found)\n    bit = lshtab.buckets.insert(b, bit, id);\n//    bit = blist->insert(b, bit);\n//    bit = lshtab.buckets.insert(b, bit);\n  \n  //now we have an iterator for the bucket, so insert the point in there\n  bit->insert(pid);\n}\n\n//------------------------------------------------------------------------\n/// insert a set of points into the table\ntemplate <class T>\nvoid insertPoints(LshTable& lshtab, Data<T>& data, uint idshift, \n        LshOptions& opt, float* norms1, float* norms2)\n{\n  //loop on the points and insert\n  uint npoints = data.size();\n//   pair<T*, uint> p;\n  if (opt.norm)\n    for (uint i=0; i<npoints; ++i)\n    {\n      insertPoint(lshtab, data, i, i+idshift, opt, norms1[i], norms2[i]);//       //get the pointer\n//       p = data.getPoint(i);\n//       //insert\n//       insertPoint(lshtab, p.first, p.second, i+idshift, opt, norms1[i], norms2[i]);\n    }\n  else\n    for (uint i=0; i<npoints; ++i)\n    {\n      insertPoint(lshtab, data, i, i+idshift, opt, 0, 0);\n//       //get the pointer\n//       p = data.getPoint(i);\n//       //insert\n//       insertPoint(lshtab, p.first, p.second, i+idshift, opt, 0, 0);\n    }\n    \n  //print size of table\n  if (opt.verbose)\n    cout << \"Table has \" << lshtab.buckets.size() << \" buckets\" << endl << flush;\n  \n//  //print bucket ids\n//  for (uint i=0; i<lshtab.buckets.size(); ++i)\n//    cout << \" id = \" << lshtab.buckets[i].id.id.d << endl;\n}\n\n//------------------------------------------------------------------------\n//get norm of the data to save time\ntemplate<class T>\nvoid normDataInit(LshOptions& opt, Data<T>& data, float* &n1, float* &n2)\n{\n  //compute norms for the data\n  if (opt.norm)\n  {\n    n1 = new float[data.size()];\n    n2 = new float[data.size()];\n    data.norm(n1, n2);\n  }\n}\n\ntemplate<class T>\nvoid normDataEnd(LshOptions& opt, Data<T>& data, float* &n1, float* &n2)\n{\n  if (opt.norm)\n  {\n    delete [] n1;\n    delete [] n2;\n  }\n}\n\n//------------------------------------------------------------------------\n/// insert points into the list of tables\ntemplate <class T>\nvoid insertPoints(LshTables& lshtabs, Data<T>& data, uint idshift, LshOptions& opt)\n{\n  //compute norms for the data\n  float* norms1;\n  float* norms2;\n  normDataInit(opt, data, norms1, norms2);\n  \n  //loop on the tables and isnert\n  for (uint i=0; i<lshtabs.size(); ++i)\n    insertPoints(lshtabs[i], data, idshift, opt, norms1, norms2);\n  \n  //cleat memory\n  normDataEnd(opt, data, norms1, norms2);\n}\n\n//------------------------------------------------------------------------\n// /// look for a point in the table\n// void searchPoint(LshTable& lshtab, T* point, uint ndims, LshPointList& pl, \n//         LshOptions& opt, float norm1, float norm2)template <class T>\ntemplate <class T>\nvoid searchPoint(LshTable& lshtab, Data<T>& data, uint pid, LshPointList& pl, \n        LshOptions& opt, float norm1, float norm2)\n{\n  //get the bucket id for that point\n  LshBucketId bid = getId(lshtab.funcs, data, pid, opt, norm1, norm2);\n  \n  //search for this bucket\n  LshBucket b(bid);\n  bool found;\n  LshBucketIt bit;\n  uint id;\n  found = lshtab.buckets.find(b, bit, id);\n//  LshBucketIt bit = lshtab.buckets.find(b, found, opt);\n\n  //check if found\n  if (found && !bit->plist.empty())\n  {\n    //insert points\n    pl.insert(pl.end(), bit->plist.begin(), bit->plist.end());\n//    //loop on the points in that bucket and fill in retids\n//    uint i;\n//    for (i=0; i<nret && i<bit->size(); ++i)\n//      retids[i] = (*bit)[i];\n  }\n}\n\n//------------------------------------------------------------------------\n/// look for a set of points in the table\ntemplate <class T>\nvoid searchPoints(LshTable& lshtab, Data<T>& data, LshPointList* pls, \n        LshOptions& opt, float* norms1, float* norms2)\n{\n  //loop on points and search\n  uint npoints = data.size();\n  pair<T*, uint> p;\n  if (opt.norm)\n    for (uint i=0; i<npoints; ++i)\n    {\n      searchPoint(lshtab, data, i, pls[i], opt, norms1[i], norms2[i]);\n//       //get the data pointer\n//       p = data.getPoint(i);\n//       //search\n//       searchPoint(lshtab, p.first, p.second, pls[i], opt, norms1[i], norms2[i]);\n    }\n  else\n    for (uint i=0; i<npoints; ++i)\n    {\n      searchPoint(lshtab, data, i, pls[i], opt, 0, 0);\n//       //get the data pointer\n//       p = data.getPoint(i);\n//       //search\n//       searchPoint(lshtab, p.first, p.second, pls[i], opt, 0, 0);\n    }    \n}\n\n//------------------------------------------------------------------------\n//------------------------------------------------------------------------\n/// look for a set of points in the table\ntemplate <class T>\nvoid searchPoints(LshTables& lshtabs, Data<T>& data, \n        LshPointList* pls, LshOptions& opt)\n{\n  //compute norms for the data\n  float* norms1;\n  float* norms2;\n  if (opt.norm)\n  {\n    norms1 = new float[data.size()];\n    norms2 = new float[data.size()];    \n    data.norm(norms1, norms2);\n  }\n  \n  //loop on the tables and search within the tables\n  for (uint i=0; i<lshtabs.size(); ++i)\n    searchPoints(lshtabs[i], data, pls, opt, norms1, norms2);\n  \n  //delete memory\n  if (opt.norm)\n  {\n    delete [] norms1;\n    delete [] norms2;\n  }\n}\n\n\n//------------------------------------------------------------------------\n/// return the k-nearest neighbors\ntemplate <class Tret, class T>\nvoid getKnn(Lsh& lsh, Data<T>& lshData, Data<T>& sdata, \n        uint k, DistanceType dist, uint* ids, Tret* dists)\n{\n  //normalize data\n  float* norms1,* norms2;\n  normDataInit(lsh.opt, sdata, norms1, norms2);\n\n//   cout << \"size1:\" << lshData.size() << \" size2:\" << sdata.size() << endl;\n  //filter for search data\n  DataFilter sfilter(1);\n  \n  //loop on the search data\n  for (uint i=0, size=sdata.size(); i<size; ++i)\n  {\n//     //get the point\n//     pair<T*,uint> p = sdata.getPoint(i);\n            \n    //point list\n    LshPointList pl;\n    if (lsh.opt.norm)\n      //loop on the tables\n      for (uint t=0; t<lsh.opt.ntables; ++t)\n        //get the points in the same bucket\n        searchPoint(lsh.tables[t], sdata, i, pl, lsh.opt, norms1[i], norms2[i]);\n//         searchPoint(lsh.tables[t], p.first, p.second, pl, lsh.opt, norms1[i], norms2[i]);\n    else\n      //loop on the tables\n      for (uint t=0; t<lsh.opt.ntables; ++t)\n        //get the points in the same bucket\n        searchPoint(lsh.tables[t], sdata, i, pl, lsh.opt, 0, 0);\n//         searchPoint(lsh.tables[t], p.first, p.second, pl, lsh.opt, 0, 0);\n      \n\n    //get the filter\n//    DataFilter filter(pl);\n//    filter.resize(pl.size());\n//    for (uint f=0; f<pl.size(); f++) filter[f] = pl[f];\n    //get rid of duplicates\n    sort(pl.begin(), pl.end());\n    LshPointIt it = unique(pl.begin(), pl.end());\n    pl.resize(it - pl.begin());\n    \n    //print pl\n//     cout << \"point: \" << i << endl;\n//     for (uint f=0; f<pl.size(); f++) cout << pl[f] << \" \"; cout << endl;\n    \n    \n    //set the filter for Lsh Data\n    lshData.setFilter(&pl);\n    \n    //set filter for sdata\n    sfilter[0] = i;\n    sdata.setFilter(&sfilter);\n    \n    //get Knn\n    knn(dists+(i*k), ids+(i*k), k, sdata, lshData, dist);\n    \n    \n    //update ids to get the real ones\n    for (uint f=0, fs=pl.size(), j=i*k; f<fs && f<k; ++f, ++j)\n      ids[j] = pl[ids[j]];\n    \n    //reset filter\n    lshData.clearFilter();\n    sdata.clearFilter();\n    pl.clear();\n  }\n  \n  //clear memoery\n  sfilter.clear();\n  normDataEnd(lsh.opt, sdata, norms1, norms2);  \n}\n\n//------------------------------------------------------------------------\ntemplate <class T>\nvoid getBucketId(Lsh& lsh, Data<T>& data, BucketIdList* ids)\n{\n  //normalize data\n  float* norms1,* norms2;\n  normDataInit(lsh.opt, data, norms1, norms2);\n  \n  //loop on points\n  for (uint i=0; i<data.size(); ++i)\n  {\n    //allocate ids\n    ids[i].reserve(lsh.opt.ntables);\n    \n//     //get the data pointer\n//     pair<T*,uint> p = data.getPoint(i);\n\n    //loop on tables\n    if (lsh.opt.norm)\n      for (uint t=0; t<lsh.tables.size(); ++t)\n      {\n        //get bucket id\n        LshBucketId bid = getId(lsh.tables[t].funcs, data, i, \n                lsh.opt, norms1[i], norms2[i]);\n        //put it\n        ids[i].push_back(bid.id.d);\n      } //for t    \n    else\n      for (uint t=0; t<lsh.tables.size(); ++t)\n      {\n        //get bucket id\n        LshBucketId bid = getId(lsh.tables[t].funcs, data, i, \n                lsh.opt, 0, 0);\n        //put it\n        ids[i].push_back(bid.id.d);\n      } //for t    \n      \n  } //for i\n  \n  //clear memoery\n  normDataEnd(lsh.opt, data, norms1, norms2);\n}\n\n//------------------------------------------------------------------------\ntemplate <class T>\nvoid getFuncVal(Lsh& lsh, Data<T>& data, LshFuncValList* vals)\n{\n  //normalize data\n  float* norms1,* norms2;\n  normDataInit(lsh.opt, data, norms1, norms2);\n  \n  //loop on points\n  for (uint i=0; i<data.size(); ++i)\n  {\n    //allocate ids\n    vals[i].reserve(lsh.opt.ntables * lsh.opt.nfuncs);\n    \n//     //get the data\n//     pair<T*,uint> p = data.getPoint(i);\n    //loop on tables\n    for (uint t=0; t<lsh.tables.size(); ++t)\n    {\n      //loop on the functions\n      for (uint f=0; f<lsh.opt.nfuncs; ++f)\n      {\n        //get bucket id\n        LshFuncVal_t v = (LshFuncVal_t) getId(lsh.tables[t].funcs[f], \n               data, i, lsh.opt, norms1[i], norms2[i]);\n        //put it\n        vals[i].push_back(v);\n      } //for f\n    } //for t    \n  } //for i\n  \n  //clear memoery\n  normDataEnd(lsh.opt, data, norms1, norms2);\n}\n\n\n//------------------------------------------------------------------------\nvoid getBucketPoints(Lsh& lsh, BucketIdList& bids, uint table, LshPointList* pls)\n{\n  //check valid table id\n  if (table >= lsh.tables.size()) return;\n\n  //loop on the bucket ids  \n  for (uint b=0; b<bids.size(); b++)\n  {\n    //get the bucket with that id\n    LshBucketId bid; bid.id.d = bids[b];\n    LshBucket bucket(bid);\n    \n    //search for that bucket and get the iterator\n    LshBucketIt bit; uint id;\n    bool found = lsh.tables[table].buckets.find(bucket, bit, id);\n//    cout << \"bucket: \" << b << \" found: \" << found << endl;;\n    //check if found then add points\n    if (found)\n      pls[b].insert(pls[b].end(), bit->plist.begin(), bit->plist.end());    \n  }\n}\n  \n//------------------------------------------------------------------------\n/// insert points into the Lsh\ntemplate <class T>\nvoid insertPoints(Lsh& lsh, Data<T>& data, uint idshift)\n{\n  //insert in the tables\n  insertPoints(lsh.tables, data, idshift, lsh.opt);\n}\n  \n//------------------------------------------------------------------------\n/// look for points in the Lsh\ntemplate <class T>\nvoid searchPoints(Lsh& lsh, Data<T>& data, LshPointList* pls)\n{\n  //search for poits in the tables\n  searchPoints(lsh.tables, data, pls, lsh.opt);\n}\n\n//------------------------------------------------------------------------\n/// initialize\nvoid Lsh::init()\n{\n  //set the random number seed\n//   srand(0xffff00);  \n  srand(this->opt.seed);\n  \n//   randEngine.seed(0xffff00);\n  randEngine.seed(this->opt.seed);\n}\n  \n//------------------------------------------------------------------------\n/// create the Lsh functions to use\nvoid Lsh::createFuncs()\n{\n  //create the tables\n  this->tables.resize(opt.ntables);\n  \n  //now create the functions\n//  cout << \"table size: \" << tables.size() << endl;\n  for (uint i=0; i<this->tables.size(); ++i)\n    this->tables[i].createFuncs(this->opt);\n  \n  //allocate buckets if fixed size\n  if (this->opt.tablesize > 0)\n    for (uint i=0; i<this->tables.size(); ++i)\n    {\n      this->tables[i].buckets.fixed = true;\n      this->tables[i].buckets.resize(this->opt.tablesize);\n    }\n}\n\n//------------------------------------------------------------------------\n/// stream overloads for Lsh\nostream& operator<<(ostream& s, Lsh& l)\n{\n  //write options and tables\n  s << l.opt << l.tables;\n}\n\nistream& operator>>(istream& s, Lsh& l)\n{\n  s >> l.opt >> l.tables;\n}\n\n//------------------------------------------------------------------------\n/// load and save for Lsh\nvoid Lsh::load(string filename)\n{\n  //open the file for opening\n  ifstream f;\n  f.open(filename.c_str(), ifstream::binary);\n  //read\n  f >> *this;  \n  //close file\n  f.close();  \n}\n\nvoid Lsh::save(string filename)\n{\n  //open the file for writing\n  ofstream f;\n  f.open(filename.c_str(), ofstream::binary);\n  //read\n  f << *this;\n  //close file\n  f.close();  \n}\n\n//------------------------------------------------------------------------\n// Compute Stats\nvoid LshTable::computeStats(LshOptions& opt)\n{\n  //array to hold sizes of buckets\n  vector<int> sizes;\n  vector<int> listsizes;\n  \n  //loop on the buckets and fill points\n  this->stats.nFullBuckets = 0;  \n  this->stats.meanCollision = 0;\n  //variable table size\n  if (opt.tablesize == 0)\n  {\n    for (uint i=0; i<this->buckets.varBuckets.size(); ++i)\n      if (this->buckets.varBuckets[i].size() > 0)\n      {\n        this->stats.nFullBuckets ++;\n        sizes.push_back(this->buckets.varBuckets[i].size());\n      }\n  }\n  //fixed table size, so we have to go through every bucket's list to \n  //count collisions\n  else\n  {\n    //looop on bucket list in table\n    for (uint i=0; i<this->buckets.fixedBuckets.size(); ++i)\n    {      \n      if (this->buckets.fixedBuckets[i].size() > 0)\n        listsizes.push_back(this->buckets.fixedBuckets[i].size());\n      //loop on bucket list within each bucket (buckets with the same mod id)\n      for (LshBucketIt bs = this->buckets.fixedBuckets[i].begin(), \n            be = this->buckets.fixedBuckets[i].end(); bs != be; bs++)\n        if (bs->size() > 0)\n        {\n          this->stats.nFullBuckets ++;\n          sizes.push_back(bs->size());\n        }     \n    }\n  }\n        \n  int size = sizes.size();\n  \n  //get mean and median\n  double mean = 0., mean2 = 0., median=0.;\n  for (uint i=0; i<size; ++i)\n  {\n    mean += sizes[i];\n    mean2 += sizes[i] * sizes[i];\n  }\n  mean /= size;\n  mean2 = sqrt((mean2/size) - (mean*mean));\n  \n  //sort and get median\n  sort(sizes.begin(), sizes.end());\n  median = size % 2 == 0 ? (sizes[size/2] +  sizes[size/2-1])/2 : \n    sizes[(size-1)/2];\n    \n  //mean collision size\n  double cmean=0.;\n  cmean = listsizes.size();\n//  for (uint i=0; i<listsizes.size(); ++i)\n//    cmean += listsizes[i];\n//  cmean /= listsizes.size();\n    \n  //return\n  this->stats.meanBucketSize = (int) mean;\n  this->stats.stdBucketSize = (int) mean2;\n  this->stats.medianBucketSize = (int) median;\n  this->stats.meanCollision = (int) cmean;\n  \n  //clear\n  sizes.clear();\n  listsizes.clear();\n}\n\n//------------------------------------------------------------------------\n// Compute Stats\nvoid Lsh::computeStats()\n{\n  //loop on tables and compute stats\n  for (uint i=0; i<this->opt.ntables; ++i)\n    this->tables[i].computeStats(this->opt);    \n}\n", "meta": {"hexsha": "dd32d27099ef6aad99d91ff55d68344c50984e04", "size": 42727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "svc_kube_vision_opencvplus/extras/ctis/ccLsh.cpp", "max_stars_repo_name": "lucmichalski/kube-vproxy", "max_stars_repo_head_hexsha": "c7cc0edbcbcd07a48f0fc48b9457eae693b76688", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T07:55:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T19:18:16.000Z", "max_issues_repo_path": "svc_kube_vision_opencvplus/extras/ctis/ccLsh.cpp", "max_issues_repo_name": "lucmichalski/kube-vproxy", "max_issues_repo_head_hexsha": "c7cc0edbcbcd07a48f0fc48b9457eae693b76688", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svc_kube_vision_opencvplus/extras/ctis/ccLsh.cpp", "max_forks_repo_name": "lucmichalski/kube-vproxy", "max_forks_repo_head_hexsha": "c7cc0edbcbcd07a48f0fc48b9457eae693b76688", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-04T04:56:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T04:56:50.000Z", "avg_line_length": 28.4656895403, "max_line_length": 103, "alphanum_fraction": 0.5267629368, "num_tokens": 12624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.021287349426241116, "lm_q1q2_score": 0.004856847185368554}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\r\r\n\r\r\n//Distributed under the Boost Software License, Version 1.0. (See accompanying\r\r\n//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\r\n\r\r\n#ifndef UUID_47B1D1217B411E08424FA0ADFD72085\r\r\n#define UUID_47B1D1217B411E08424FA0ADFD72085\r\r\n\r\r\n#include <boost/qvm/mat_traits.hpp>\r\r\n#include <boost/qvm/inline.hpp>\r\r\n#include <boost/qvm/static_assert.hpp>\r\r\n#include <boost/qvm/enable_if.hpp>\r\r\n\r\r\nnamespace\r\r\nboost\r\r\n    {\r\r\n    namespace\r\r\n    qvm\r\r\n        {\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        template <int R,int C,class M>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        typename enable_if_c<\r\r\n            is_mat<M>::value,\r\r\n            typename mat_traits<M>::scalar_type>::type\r\r\n        A( M const & a )\r\r\n            {\r\r\n            BOOST_STATIC_ASSERT(R>=0);\r\r\n            BOOST_STATIC_ASSERT(R<mat_traits<M>::rows);\r\r\n            BOOST_STATIC_ASSERT(C>=0);\r\r\n            BOOST_STATIC_ASSERT(C<mat_traits<M>::cols);\r\r\n            return mat_traits<M>::template read_element<R,C>(a);\r\r\n            }\r\r\n\r\r\n        template <int R,int C,class M>\r\r\n        BOOST_QVM_INLINE_TRIVIAL\r\r\n        typename enable_if_c<\r\r\n            is_mat<M>::value,\r\r\n            typename mat_traits<M>::scalar_type &>::type\r\r\n        A( M & a )\r\r\n            {\r\r\n            BOOST_STATIC_ASSERT(R>=0);\r\r\n            BOOST_STATIC_ASSERT(R<mat_traits<M>::rows);\r\r\n            BOOST_STATIC_ASSERT(C>=0);\r\r\n            BOOST_STATIC_ASSERT(C<mat_traits<M>::cols);\r\r\n            return mat_traits<M>::template write_element<R,C>(a);\r\r\n            }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A00( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A01( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A02( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A03( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A04( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A05( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A06( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A07( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A08( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A09( M const & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<0,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A10( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A11( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A12( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A13( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A14( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A15( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A16( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A17( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A18( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A19( M const & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<1,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A20( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A21( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A22( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A23( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A24( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A25( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A26( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A27( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A28( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A29( M const & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<2,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A30( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A31( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A32( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A33( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A34( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A35( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A36( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A37( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A38( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A39( M const & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<3,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A40( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A41( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A42( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A43( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A44( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A45( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A46( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A47( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A48( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A49( M const & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<4,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A50( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A51( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A52( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A53( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A54( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A55( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A56( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A57( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A58( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A59( M const & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<5,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A60( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A61( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A62( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A63( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A64( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A65( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A66( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A67( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A68( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A69( M const & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<6,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A70( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A71( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A72( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A73( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A74( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A75( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A76( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A77( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A78( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A79( M const & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<7,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A80( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A81( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A82( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A83( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A84( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A85( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A86( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A87( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A88( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A89( M const & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<8,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A90( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A91( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A92( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A93( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A94( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A95( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A96( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A97( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A98( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type>::type A99( M const & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template read_element<9,9>(a); }\r\r\n\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A00( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A01( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A02( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A03( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A04( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A05( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A06( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A07( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A08( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A09( M & a ) { BOOST_STATIC_ASSERT(0<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<0,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A10( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A11( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A12( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A13( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A14( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A15( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A16( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A17( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A18( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A19( M & a ) { BOOST_STATIC_ASSERT(1<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<1,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A20( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A21( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A22( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A23( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A24( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A25( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A26( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A27( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A28( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A29( M & a ) { BOOST_STATIC_ASSERT(2<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<2,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A30( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A31( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A32( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A33( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A34( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A35( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A36( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A37( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A38( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A39( M & a ) { BOOST_STATIC_ASSERT(3<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<3,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A40( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A41( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A42( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A43( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A44( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A45( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A46( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A47( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A48( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A49( M & a ) { BOOST_STATIC_ASSERT(4<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<4,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A50( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A51( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A52( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A53( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A54( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A55( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A56( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A57( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A58( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A59( M & a ) { BOOST_STATIC_ASSERT(5<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<5,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A60( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A61( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A62( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A63( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A64( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A65( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A66( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A67( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A68( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A69( M & a ) { BOOST_STATIC_ASSERT(6<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<6,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A70( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A71( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A72( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A73( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A74( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A75( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A76( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A77( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A78( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A79( M & a ) { BOOST_STATIC_ASSERT(7<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<7,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A80( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A81( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A82( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A83( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A84( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A85( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A86( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A87( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A88( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A89( M & a ) { BOOST_STATIC_ASSERT(8<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<8,9>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A90( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 0<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,0>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A91( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 1<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,1>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A92( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 2<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,2>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A93( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 3<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,3>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A94( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 4<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,4>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A95( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 5<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,5>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A96( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 6<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,6>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A97( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 7<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,7>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A98( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 8<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,8>(a); }\r\r\n        template <class M> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_mat<M>::value,typename mat_traits<M>::scalar_type &>::type A99( M & a ) { BOOST_STATIC_ASSERT(9<mat_traits<M>::rows && 9<mat_traits<M>::cols); return mat_traits<M>::template write_element<9,9>(a); }\r\r\n\r\r\n        ////////////////////////////////////////////////\r\r\n        }\r\r\n    }\r\r\n\r\r\n#endif\r\r\n", "meta": {"hexsha": "6a7de3d1dd889cdf3163495cd40de1f109a7663e", "size": 57513, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost_1_63_0/boost/qvm/mat_access.hpp", "max_stars_repo_name": "newtondev/drachtio-server", "max_stars_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/boost_1_63_0/boost/qvm/mat_access.hpp", "max_issues_repo_name": "newtondev/drachtio-server", "max_issues_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/boost_1_63_0/boost/qvm/mat_access.hpp", "max_forks_repo_name": "newtondev/drachtio-server", "max_forks_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 222.0579150579, "max_line_length": 279, "alphanum_fraction": 0.7186723002, "num_tokens": 16212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.018833131611373892, "lm_q1q2_score": 0.004836950695812388}}
{"text": "/*\n * This file is part of the Sequoia MSO Solver.\n * \n * Copyright 2012 Alexander Langer, Theoretical Computer Science,\n *                                  RWTH Aachen University\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 Alexander Langer\n */\n#include \"cache_join.h\"\n#include \"game_determined.h\"\n#include \"game_q.h\"\n#include \"game_q_introduce_iterator.h\"\n#include \"game_q_forget_iterator.h\"\n#include \"pair_iterator.h\"\n\n#include <boost/scoped_ptr.hpp>\n\nnamespace sequoia {\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::minimize() const {\n    assert(outcome() == MCGame::UNDETERMINED);\n    if (empty()) {\n    \tdelete this;\n    \treturn determined.get(MCGame::opponent<_player>::value);\n    } else {\n        return MCGameFlyFactory::make(this);\n    }\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player> \nvoid QUndetGame<TFormula, TMove, _player>::set_subgame(const TMove *move,\n\t\t\t\t\t\t       const MCGame_f* game) {\n    bool res = _subgames.insert(move, game);\n    if (!res) { // new entry\n        // equivalent entry exists already, delete this game.\n        delete game;\n    }\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::add_subgame(const TMove* move,\n\t\t\t\t\t\t\t\t  const MCGame_f* game) {\n    if (game->get()->outcome() == _player) {\n\tif (is_pointmove<TMove>::value && move == NULL) { // compiler will optimize this away for non-pointmoves\n\t    /*\n\t     * The current player must not use the NULL move for their advantage.\n\t     * An example where this may happen is testing whether the graph is\n\t     * a complete graph:  ALL x ALL y adj(x, y).\n\t     * If there is a non-vertex in the PAST, the game for adj(x,y)\n\t     * will return FALSE for the NULL move (due to the graph separator\n\t     * property).  Returning FALSE here would be wrong, when there is\n\t     * no vertex left to come.  We have to wait until this move is concrete.\n\t     */\n\t    DPRINTLN(\" --> re-check this \"\n\t\t    << formula()->variable()->identifier()\n\t\t    << \" later (when concrete)!\");\n\t    QUndetGame<TFormula, TMove, _player>::set_subgame(NULL, game);\n\t    return NULL;\n\t} else {\n                DPRINTLN(\" --> determines!\");\n                delete this;\n\t\treturn game;\n\t}\n    }\n    if (game->get()->outcome() == MCGame::opponent<_player>::value) {\n\t    DPRINTLN(\" --> ignore this \"\n\t\t    << formula()->variable()->identifier()<< \"!\");\n\t    delete game;\n\t    return NULL;\n    }\n    DPRINTLN(\" --> re-check this \"\n            << formula()->variable()->identifier() << \" later!\");\n    QUndetGame<TFormula, TMove, _player>::set_subgame(move, game);\n    return NULL;\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::convert() const {\n    DEBUG({\n        tab_prefix(level()) << \"Building for game: \"\n                << toString() << std::endl;\n    });\n    QUndetGame<TFormula, TMove, _player>* returngame = new QUndetGame<TFormula, TMove, _player>(formula());\n    typename QUndetGame<TFormula, TMove, _player>::GamesContainer::GameIterator\n    \tit(QUndetGame<TFormula, TMove, _player>::begin(),\n\t   QUndetGame<TFormula, TMove, _player>::end());\n    while (it.has_next()) {\n\tstd::pair<const TMove*, const MCGame_f*> res = it.next();\n\tconst TMove* oldmove = res.first;\n\tconst MCGame_f* oldgame = res.second;\n        //DEBUG(tab_prefix(level()) << TOSTRING(res.first) << \" --> \" << res.second->get()->toString());\n        DEBUG(tab_prefix(level()) << \"Found Game for: \" << TOSTRING(oldmove) << std::endl);\n\tDEBUG(tab_prefix(level()) << \"Found Game \" << oldgame->get()->toString() << std::endl);\n\tif (oldmove == NULL) continue; // this game is to be cut\n\tconst MCGame_f* sub = oldgame->get()->convert();\n\tDEBUG(tab_prefix(level()) << TOSTRING(oldmove) << \" --> \" << sub->get()->toString());\n        const MCGame_f* tmpgame = returngame->add_subgame(res.first, sub);\n        if (tmpgame != NULL) return tmpgame;\n    }\n    return returngame->minimize();\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::forget(const ConstantSymbol* tsym,\n\t\t\t\t\t\t\t     int signature_depth,\n\t\t\t\t\t\t\t     const PointMove* replacement,\n\t\t\t\t\t\t\t     const Assignment_f* alpha) const {\n    DEBUG({tab_prefix(level()) << \"Building for game: \" << TOSTRING(this) << std::endl;});\n\n    QUndetGame<TFormula, TMove, _player>* returngame = new QUndetGame<TFormula, TMove, _player>(formula());\n    DEBUG(returngame->level(level()));\n    QUndetGameForgetIterator<TMove> it(tsym,\n\t\t\t\t       signature_depth,\n\t\t\t\t       replacement,\n\t\t\t\t       alpha,\n\t\t\t\t       formula()->variable(),\n\t\t\t\t       QUndetGame<TFormula, TMove, _player>::begin(),\n\t\t\t\t       QUndetGame<TFormula, TMove, _player>::end()\n\t\t\t\t       );\n    DEBUG(it.level(level()));\n    while (it.has_next()) {\n\tconst std::pair<const TMove*, const MCGame_f*> res = it.next();\n        DEBUG(tab_prefix(level()) << TOSTRING(res.first) << \" --> \" << res.second->get()->toString());\n        const MCGame_f* tmpgame = returngame->add_subgame(res.first, res.second);\n        if (tmpgame != NULL) return tmpgame;\n    }\n    return returngame->minimize();\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::introduce(const ConstantSymbol* tsym,\n\t\t\t\t\t\t\t\tint signature_depth,\n\t\t\t\t\t\t\t\tconst Assignment_f* alpha) const {\n    DEBUG({ tab_prefix(level()) << \"Building for game: \" << TOSTRING(this) << std::endl; });\n    QUndetGame<TFormula, TMove, _player>* returngame = new QUndetGame<TFormula, TMove, _player>(formula());\n    DEBUG(returngame->level(level()));\n    QUndetGameIntroduceIterator<TMove> it(tsym,\n\t\t\t signature_depth,\n\t\t\t alpha,\n\t\t\t formula()->variable(),\n\t\t\t QUndetGame<TFormula, TMove, _player>::begin(),\n\t\t\t QUndetGame<TFormula, TMove, _player>::end()\n\t\t\t );\n    DEBUG(it.level(level()));\n    while (it.has_next()) {\n\tconst std::pair<const TMove*, const MCGame_f*> res = it.next();\n        DEBUG(tab_prefix(level()) << TOSTRING(res.first) << \" --> \" << res.second->get()->toString());\n        const MCGame_f* tmpgame = returngame->add_subgame(res.first, res.second);\n        if (tmpgame != NULL) return tmpgame;\n    }\n    return returngame->minimize();\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::join(const MCGame_f* other,\n\t\t\t\t\t\t\t   const Assignment_f* alpha) const {\n    DEBUG({\n        tab_prefix(level()) << \"Building for game: \"\n                << toString() << std::endl;\n    });\n    if (other->get()->outcome() != MCGame::UNDETERMINED) {\n        DEBUG(tab_prefix(level()) << \"Found determined game, return.\" << std::endl);\n        return other->clone();\n    }\n    return QUndetGame<TFormula, TMove, _player>::join_impl(other, alpha, tag<TMove>());\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::join_impl(const MCGame_f* other,\n\t\t\t\t\t\t\t   const Assignment_f* alpha,\n\t\t\t\t\t\t\t   tag<SetMove>) const {\n    typedef QUndetGame<TFormula, TMove, _player> MyType;\n    typedef PairIterator<subgames_iterator, subgames_iterator> GamePairIterator;\n    typedef typename GamePairIterator::value_type GamePairIteratorValue;\n    const MyType* gother = static_cast<const MyType*>(other->get());\n    MyType* returngame = new MyType(formula());\n    DEBUG(returngame->level(level()));\n    \n    const_iterator mit = begin();\n    const_iterator mitend = end();\n    for (; mit != mitend; mit++) {\n\tconst SetMove* oldmove = mit->first;\n        DEBUG(tab_prefix(level()) << \"Found Games for: \" << TOSTRING(oldmove) << std::endl);\n\n\tboost::scoped_ptr<const Assignment_f> my_alpha(AssignmentFlyFactory::make(\n                new SetAssignment(alpha, formula()->variable(), oldmove)));\n\n\tconst_iterator mit2 = gother->find(oldmove);\n\tif (mit2 == gother->end()) {\n\t    DEBUG(tab_prefix(level()) << TOSTRING(oldmove) << \" --> ignored in other, skip\" << std::endl);\n            continue;\n\t}\n\tGamePairIterator git(mit->second->begin(), mit->second->end(),\n\t                     mit2->second->begin(), mit2->second->end());\n\twhile (git.has_next()) {\n\t    GamePairIteratorValue res = git.next();\n\t    const MCGame_f* g1 = res.first;\n\t    const MCGame_f* g2 = res.second;\n#if USE_CACHE_SUBGAMES\n\t    const MCGame_f *sub = cache_join_lookup(g1->get()->formula(), my_alpha.get(), g1, g2);\n#else\n\t    const MCGame_f *sub = NULL;\n#endif\n\t    if (sub == NULL) {\n\t\tsub = g1->get()->join(g2, my_alpha.get());\n#if USE_CACHE_SUBGAMES\n\t\tcache_join_store(g1->get()->formula(), my_alpha.get(), g1, g2, sub);\n#endif\n\t    }\n\t    DEBUG(tab_prefix(level()) << TOSTRING(oldmove) << \" x \"\n\t\t    << TOSTRING(oldmove) << \" --> \"\n\t\t    << sub->get()->toString() << std::endl);\n\t    const MCGame_f* tmpgame = returngame->add_subgame(oldmove, sub);\n\t    if (tmpgame != NULL) return tmpgame;\n\t}\n    }\n    return returngame->minimize();\n}\n\ntemplate <typename TFormula, typename TMove, MCGame::Player _player>\nconst MCGame_f* QUndetGame<TFormula, TMove, _player>::join_impl(const MCGame_f* other,\n\t\t\t\t\t\t\t   const Assignment_f* alpha,\n\t\t\t\t\t\t\t   tag<PointMove>) const {\n    typedef QUndetGame<TFormula, TMove, _player> MyType;\n    typedef PairIterator<subgames_iterator, subgames_iterator> GamePairIterator;\n    typedef typename GamePairIterator::value_type GamePairIteratorValue;\n    const MyType* gother = static_cast<const MyType*>(other->get());\n    MyType* returngame = new MyType(formula());\n    DEBUG(returngame->level(level()));\n\n    /*\n     * We need to combine in a Cartesian manner:\n     * - all TERMINAL moves with all TERMINAL moves on the other side (use the same move)\n     * - all ANON moves with the NULL move on the other side, and vice versa;\n     *\t this case includes the NULL x NULL case\n     */\n    const MyType* sides[] = { this, gother }; \n    for (int i = 0; i < 2; i++) {\n        DEBUG(tab_prefix(level()) << \"Join \" << sides[i] << \" with \"\n                << sides[1-i] << std::endl);\n\tconst_iterator mit = sides[i]->begin();\n\tconst_iterator mitend = sides[i]->end();\n\tfor (; mit != mitend; mit++) {\n            const PointMove* oldmove = mit->first;\n            DEBUG(tab_prefix(level()) << \"Found Games for: \"\n                    << TOSTRING(oldmove) << std::endl);\n            // in the second run we do not need to re-check Terminal x Terminal\n            // or NULL x *\n            if (i == 1) {\n                if (oldmove == NULL || oldmove->terminal()) {\n                    DEBUG(tab_prefix(level()) << \" --> checked before, skip\" << std::endl);\n                    continue;\n                }\n            }\n\n            // set the lookup key that we expect for this move\n\t    // for terminals we require the same move on the other side,\n\t    // in all other cases the NULL move is the correct one.\n            const PointMove* lookupmove = NULL;\n            if (oldmove != NULL && oldmove->terminal())\n                lookupmove = oldmove;\n\n            // now lookup the corresponding SubGamesContainer container; continue if nonexistent\n\t    const_iterator mit2 = sides[1-i]->find(lookupmove);\n\t    if (mit2 == sides[1-i]->end()) {\n                DEBUG(tab_prefix(level()) << TOSTRING(lookupmove)\n                        << \" nonexistent in other, \"\n                        << (i == 1 ? \"break\" : \"skip\")\n                        << std::endl);\n                // In the second visit of the for loop, we already\n                // joined all terminals, so we can stop here early (saves a bit of time)\n                // In the first run, we just continue with the next move.\n                if (i == 1)\n                    break;\n                else\n                    continue;\n            }\n            \n\t    boost::scoped_ptr<const Assignment_f> my_alpha(AssignmentFlyFactory::make(\n                new ObjAssignment(alpha, formula()->variable(), oldmove)));\n\n\t    GamePairIterator git(mit->second->begin(), mit->second->end(),\n\t                         mit2->second->begin(), mit2->second->end());\n\t    while (git.has_next()) {\n\t\tGamePairIteratorValue res = git.next();\n\t\tconst MCGame_f* g1 = res.first;\n\t\tconst MCGame_f* g2 = res.second;\n#if USE_CACHE_SUBGAMES\n\t\tconst MCGame_f *sub = cache_join_lookup(g1->get()->formula(), my_alpha.get(), g1, g2);\n#else\n\t\tconst MCGame_f *sub = NULL;\n#endif\n\t\tif (sub == NULL) {\n\t\t    sub = g1->get()->join(g2, my_alpha.get());\n#if USE_CACHE_SUBGAMES\n\t\t    cache_join_store(g1->get()->formula(), my_alpha.get(), g1, g2, sub);\n#endif\n\t\t}\n\t\tDEBUG(tab_prefix(level()) << TOSTRING(oldmove) << \" x \"\n                            << TOSTRING(lookupmove) << \" --> \"\n                            << sub->get()->toString() << std::endl);\n\t\tconst MCGame_f* tmpgame = returngame->add_subgame(oldmove, sub);\n\t\tif (tmpgame != NULL) return tmpgame;\n\t    }\n\t}\n    }\n    return returngame->minimize();\n}\n\n#ifdef DODEBUG\ntemplate <typename TFormula, typename TMove, MCGame::Player _player> \nvoid QUndetGame<TFormula, TMove, _player>::recursive_print_game(int level,\n\t\t\t\t\t\t\t\tbool skip_first) const {\n    (skip_first ? std::cout : tab_prefix(level))\n\t    << \"[\" << toString() \n\t    << \" with subgames\" << std::endl;\n\n    typename QUndetGame<TFormula, TMove, _player>::GamesContainer::GameIterator\n    \tit(QUndetGame<TFormula, TMove, _player>::begin(),\n\t   QUndetGame<TFormula, TMove, _player>::end());\n    while (it.has_next()) {\n\tconst std::pair<const TMove*, const MCGame_f*> res = it.next();\n\ttab_prefix(level+1) << TOSTRING(res.first) << \": \" << std::endl;\n\tres.second->get()->recursive_print_game(level+2, false);\n    }\n    tab_prefix(level) << \"]\" << std::endl;\n}\n#endif\n\n}; // namespace\n", "meta": {"hexsha": "df6a8b88cfd4a90ebfad5e3f042c9d79a56383af", "size": 14288, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/game_q.hpp", "max_stars_repo_name": "sequoia-mso/sequoia-core", "max_stars_repo_head_hexsha": "d2a6a461ffbe38dc8abb005b2c8f1f3bc1dc2bbe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-11-12T17:55:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T20:23:27.000Z", "max_issues_repo_path": "src/game_q.hpp", "max_issues_repo_name": "sequoia-mso/sequoia-core", "max_issues_repo_head_hexsha": "d2a6a461ffbe38dc8abb005b2c8f1f3bc1dc2bbe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/game_q.hpp", "max_forks_repo_name": "sequoia-mso/sequoia-core", "max_forks_repo_head_hexsha": "d2a6a461ffbe38dc8abb005b2c8f1f3bc1dc2bbe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-05-12T13:51:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T22:01:28.000Z", "avg_line_length": 41.4144927536, "max_line_length": 107, "alphanum_fraction": 0.6254899216, "num_tokens": 3641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.015424551204934474, "lm_q1q2_score": 0.004792321619874862}}
{"text": "// Copyright Nick Thompson, 2019\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#ifndef BOOST_MATH_INTERPOLATORS_WHITAKKER_SHANNON_HPP\r\n#define BOOST_MATH_INTERPOLATORS_WHITAKKER_SHANNON_HPP\r\n#include <memory>\r\n#include <boost/math/interpolators/detail/whittaker_shannon_detail.hpp>\r\n\r\nnamespace boost { namespace math { namespace interpolators {\r\n\r\ntemplate<class RandomAccessContainer>\r\nclass whittaker_shannon {\r\npublic:\r\n\r\n    using Real = typename RandomAccessContainer::value_type;\r\n    whittaker_shannon(RandomAccessContainer&& y, Real const & t0, Real const & h)\r\n     : m_impl(std::make_shared<detail::whittaker_shannon_detail<RandomAccessContainer>>(std::move(y), t0, h))\r\n    {}\r\n\r\n    inline Real operator()(Real t) const\r\n    {\r\n        return m_impl->operator()(t);\r\n    }\r\n\r\n    inline Real prime(Real t) const\r\n    {\r\n        return m_impl->prime(t);\r\n    }\r\n\r\n    inline Real operator[](size_t i) const\r\n    {\r\n        return m_impl->operator[](i);\r\n    }\r\n\r\n    RandomAccessContainer&& return_data()\r\n    {\r\n        return m_impl->return_data();\r\n    }\r\n\r\n\r\nprivate:\r\n    std::shared_ptr<detail::whittaker_shannon_detail<RandomAccessContainer>> m_impl;\r\n};\r\n}}}\r\n#endif\r\n", "meta": {"hexsha": "589356bcad8270e3fc21766ab4e190df76307bf7", "size": 1338, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/interpolators/whittaker_shannon.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/whittaker_shannon.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/whittaker_shannon.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": 27.875, "max_line_length": 110, "alphanum_fraction": 0.6943198804, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092537, "lm_q2_score": 0.02096424307371591, "lm_q1q2_score": 0.004783128370150429}}
{"text": "/*\n    Residue.hpp\n    ===========\n        Class Residue implementation.\n*/\n\n#pragma once\n\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <utility>\n#include <cctype>\n#include <boost/format.hpp>\n#include <Eigen/Dense>\n#include \"Residue.h\"\n#include \"Chain.h\"\n#include \"Atom.h\"\n#include \"Math.hpp\"\n#include \"Constants.hpp\"\n\nnamespace PDBTools\n{\n\n////////////////////////////////////////////////////////////////////////////////\n// Using\n////////////////////////////////////////////////////////////////////////////////\n\nusing std::string;\nusing std::vector;\nusing std::unordered_map;\nusing std::pair;\nusing boost::format;\nusing Eigen::RowVector3d;\nusing Eigen::Matrix3d;\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Constructor\n////////////////////////////////////////////////////////////////////////////////\n\nResidue::Residue(const string &name, int num, const string &ins, Chain *owner):\n    __name (name),\n    __num  (num),\n    __ins  (ins),\n    __owner(owner)\n{\n    if (owner)\n    {\n        owner->sub().push_back(this);\n    }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Getter: __name\n////////////////////////////////////////////////////////////////////////////////\n\nstring &Residue::name()\n{\n    return __name;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Getter: __num\n////////////////////////////////////////////////////////////////////////////////\n\nint Residue::num()\n{\n    return __num;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Getter: __ins\n////////////////////////////////////////////////////////////////////////////////\n\nstring &Residue::ins()\n{\n    return __ins;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Getter: __owner\n////////////////////////////////////////////////////////////////////////////////\n\nChain *Residue::owner()\n{\n    return __owner;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Getter: __sub\n////////////////////////////////////////////////////////////////////////////////\n\nvector<Atom *> &Residue::sub()\n{\n    return __sub;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Setter: __name\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::name(const string &val)\n{\n    __name = val;\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Setter: __num\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::num(int val)\n{\n    __num = val;\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Setter: __ins\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::ins(const string &val)\n{\n    __ins = val;\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Setter: __owner\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::owner(Chain *val)\n{\n    __owner = val;\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Setter: __sub\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::sub(const vector<Atom *> &val)\n{\n    __sub = val;\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Getter: compNum\n////////////////////////////////////////////////////////////////////////////////\n\nstring Residue::compNum()\n{\n    return (format(\"%d%s\") %\n        __num              %\n        __ins\n    ).str();\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Setter: compNum\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::compNum(int num, const string &ins)\n{\n    __num = num;\n    __ins = ins;\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Setter: compNum (by compNumPair)\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::compNum(const pair<int, string> &compNumPair)\n{\n    __num = compNumPair.first;\n    __ins = compNumPair.second;\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Copy\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::copy()\n{\n    auto copyResPtr = new Residue(__name, __num, __ins);\n\n    for (auto atomPtr: __sub)\n    {\n        auto copyAtomPtr = atomPtr->copy();\n\n        copyAtomPtr->owner(copyResPtr);\n\n        copyResPtr->__sub.push_back(copyAtomPtr);\n    }\n\n    return copyResPtr;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// GetResidues\n////////////////////////////////////////////////////////////////////////////////\n\nvector<Residue *> Residue::getResidues()\n{\n    return {this};\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// GetAtoms\n////////////////////////////////////////////////////////////////////////////////\n\nvector<Atom *> Residue::getAtoms()\n{\n    return __sub;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// subMap\n////////////////////////////////////////////////////////////////////////////////\n\nunordered_map<string, Atom *> Residue::subMap()\n{\n    unordered_map<string, Atom *> atomPtrMap;\n\n    for (auto atomPtr: __sub)\n    {\n        atomPtrMap.emplace(atomPtr->name(), atomPtr);\n    }\n\n    return atomPtrMap;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// coordMap\n////////////////////////////////////////////////////////////////////////////////\n\nunordered_map<string, RowVector3d> Residue::coordMap()\n{\n    unordered_map<string, RowVector3d> coordPtrMap;\n\n    for (auto atomPtr: __sub)\n    {\n        coordPtrMap.emplace(atomPtr->name(), atomPtr->coord());\n    }\n\n    return coordPtrMap;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Backbone Dihedral Angle\n////////////////////////////////////////////////////////////////////////////////\n\ndouble Residue::calcBBDihedralAngle(DIH dihedralEnum)\n{\n    auto atomCoordMap = coordMap();\n\n    if (dihedralEnum == DIH::L)\n    {\n        return calcDihedralAngle(\n            prev()->coordMap().at(\"C\"),\n            atomCoordMap.at(\"N\"),\n            atomCoordMap.at(\"CA\"),\n            atomCoordMap.at(\"C\")\n        );\n    }\n    else\n    {\n        return calcDihedralAngle(\n            atomCoordMap.at(\"N\"),\n            atomCoordMap.at(\"CA\"),\n            atomCoordMap.at(\"C\"),\n            next()->coordMap().at(\"N\")\n        );\n    }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Backbone Rotation Matrix By Delta Angle\n////////////////////////////////////////////////////////////////////////////////\n\npair<RowVector3d, Matrix3d> Residue::calcBBRotationMatrixByDeltaAngle(\n    DIH dihedralEnum, SIDE sideEnum, double deltaAngle)\n{\n    RowVector3d moveCoord;\n    Matrix3d rotationMatrix;\n\n    auto atomCoordMap = coordMap();\n\n    if (sideEnum == SIDE::L)\n    {\n        deltaAngle = -deltaAngle;\n    }\n\n    if (dihedralEnum == DIH::L)\n    {\n        moveCoord = atomCoordMap.at(\"N\");\n        rotationMatrix = calcRotationMatrix(atomCoordMap.at(\"CA\") - moveCoord, deltaAngle);\n    }\n    else\n    {\n        moveCoord = atomCoordMap.at(\"CA\");\n        rotationMatrix = calcRotationMatrix(atomCoordMap.at(\"C\") - moveCoord, deltaAngle);\n    }\n\n    return {moveCoord, rotationMatrix};\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Backbone Rotation Matrix By Target Angle\n////////////////////////////////////////////////////////////////////////////////\n\npair<RowVector3d, Matrix3d> Residue::calcBBRotationMatrixByTargetAngle(\n    DIH dihedralEnum, SIDE sideEnum, double targetAngle)\n{\n    return calcBBRotationMatrixByDeltaAngle(dihedralEnum, sideEnum,\n        targetAngle - calcBBDihedralAngle(dihedralEnum));\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Get Backbone Rotation Atom Pointer\n////////////////////////////////////////////////////////////////////////////////\n\nvector<Atom *> Residue::getBBRotationAtomPtr(DIH dihedralEnum, SIDE sideEnum)\n{\n    vector<Atom *> rotationAtomObjList;\n    auto iterInOwner = iter();\n\n    if (sideEnum == SIDE::L)\n    {\n        for (auto resIter = __owner->sub().begin(); resIter != iterInOwner; resIter++)\n        {\n            for (auto atomPtr: **resIter)\n            {\n                rotationAtomObjList.push_back(atomPtr);\n            }\n        }\n\n        if (dihedralEnum == DIH::R)\n        {\n            for (auto atomPtr: __sub)\n            {\n                if (atomPtr->name() != \"CA\" && atomPtr->name() != \"C\" &&\n                    atomPtr->name() != \"O\" && atomPtr->name() != \"OXT\")\n                {\n                    rotationAtomObjList.push_back(atomPtr);\n                }\n            }\n        }\n    }\n    else\n    {\n        if (dihedralEnum == DIH::L)\n        {\n            for (auto atomPtr: __sub)\n            {\n                if (atomPtr->name() != \"N\" && atomPtr->name() != \"CA\")\n                {\n                    rotationAtomObjList.push_back(atomPtr);\n                }\n            }\n        }\n        else\n        {\n            for (auto atomPtr: __sub)\n            {\n                if (atomPtr->name() == \"O\" || atomPtr->name() == \"OXT\")\n                {\n                    rotationAtomObjList.push_back(atomPtr);\n                }\n            }\n        }\n\n        for (auto resIter = iterInOwner + 1; resIter != __owner->sub().end(); resIter++)\n        {\n            for (auto atomPtr: **resIter)\n            {\n                rotationAtomObjList.push_back(atomPtr);\n            }\n        }\n    }\n\n    return rotationAtomObjList;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Rotate Backbone Dihedral Angle By Delta Angle\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::rotateBBDihedralAngleByDeltaAngle(DIH dihedralEnum,\n    SIDE sideEnum, double deltaAngle)\n{\n    auto [moveCoord, rotationMatrix] = calcBBRotationMatrixByDeltaAngle(\n        dihedralEnum, sideEnum, deltaAngle);\n\n    for (auto atomPtr: getBBRotationAtomPtr(dihedralEnum, sideEnum))\n    {\n        atomPtr->coord((atomPtr->coord() - moveCoord) * rotationMatrix + moveCoord);\n    }\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Rotate Backbone Dihedral Angle By Target Angle\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::rotateBBDihedralAngleByTargetAngle(DIH dihedralEnum,\n    SIDE sideEnum, double targetAngle)\n{\n    return rotateBBDihedralAngleByDeltaAngle(dihedralEnum, sideEnum,\n        targetAngle - calcBBDihedralAngle(dihedralEnum));\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Side Chain Dihedral Angle\n////////////////////////////////////////////////////////////////////////////////\n\ndouble Residue::calcSCDihedralAngle(int dihedralIdx)\n{\n    auto atomCoordMap = coordMap();\n\n    return calcDihedralAngle(\n        atomCoordMap[__RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(__name).at(dihedralIdx)[0]],\n        atomCoordMap[__RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(__name).at(dihedralIdx)[1]],\n        atomCoordMap[__RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(__name).at(dihedralIdx)[2]],\n        atomCoordMap[__RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(__name).at(dihedralIdx)[3]]);\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Side Chain Rotation Matrix By Delta Angle\n////////////////////////////////////////////////////////////////////////////////\n\npair<RowVector3d, Matrix3d> Residue::calcSCRotationMatrixByDeltaAngle(\n    int dihedralIdx, double deltaAngle)\n{\n    auto atomCoordMap = coordMap();\n\n    auto moveCoord = atomCoordMap[__RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(\n        __name).at(dihedralIdx)[1]];\n\n    auto rotationMatrix = calcRotationMatrix(atomCoordMap[\n        __RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(__name).at(dihedralIdx)[2]] -\n        moveCoord, deltaAngle);\n\n    return {moveCoord, rotationMatrix};\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Side Chain Rotation Matrix By Target Angle\n////////////////////////////////////////////////////////////////////////////////\n\npair<RowVector3d, Matrix3d> Residue::calcSCRotationMatrixByTargetAngle(\n    int dihedralIdx, double targetAngle)\n{\n    return calcSCRotationMatrixByDeltaAngle(dihedralIdx,\n        targetAngle - calcSCDihedralAngle(dihedralIdx));\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Get Side Chain Rotation Atom Pointer\n////////////////////////////////////////////////////////////////////////////////\n\nvector<Atom *> Residue::getSCRotationAtomPtr(int dihedralIdx)\n{\n    vector<Atom *> rotationAtomObjList;\n\n    unordered_set<string> rotationAtomNameSet(\n        __RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(__name).at(dihedralIdx).cbegin() + 3,\n        __RESIDUE_SIDE_CHAIN_ROTATION_ATOMS_NAME_MAP.at(__name).at(dihedralIdx).cend());\n\n    for (auto atomPtr: __sub)\n    {\n        if (rotationAtomNameSet.count(atomPtr->name()))\n        {\n            rotationAtomObjList.push_back(atomPtr);\n        }\n    }\n\n    return rotationAtomObjList;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Rotate Side Chain Dihedral Angle By Delta Angle\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::rotateSCDihedralAngleByDeltaAngle(int dihedralIdx, double deltaAngle)\n{\n    auto [moveCoord, rotationMatrix] = calcSCRotationMatrixByDeltaAngle(\n        dihedralIdx, deltaAngle);\n\n    for (auto atomPtr: getSCRotationAtomPtr(dihedralIdx))\n    {\n        atomPtr->coord((atomPtr->coord() - moveCoord) * rotationMatrix + moveCoord);\n    }\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Rotate Side Chain Dihedral Angle By Target Angle\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::rotateSCDihedralAngleByTargetAngle(int dihedralIdx, double targetAngle)\n{\n    return rotateSCDihedralAngleByDeltaAngle(dihedralIdx, targetAngle -\n        calcSCDihedralAngle(dihedralIdx));\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Dump\n////////////////////////////////////////////////////////////////////////////////\n\nResidue *Residue::dump(const string &dumpFilePath, const string &fileMode)\n{\n    string chainName;\n\n    if (__owner)\n    {\n        chainName = __owner->name();\n    }\n\n    FILE *fo = fopen(dumpFilePath.c_str(), fileMode.c_str());\n\n    for (auto atomPtr: __sub)\n    {\n        if (isdigit(atomPtr->name()[0]) || atomPtr->name().size() == 4)\n        {\n            fprintf(fo, \"ATOM  %5d %-4s%1s%3s %1s%4d%1s   %8.3f%8.3f%8.3f%6s%6s          %2s%2s\\n\",\n                atomPtr->num(),\n                atomPtr->name().c_str(),\n                atomPtr->alt().c_str(),\n                __name.c_str(),\n                chainName.c_str(),\n                __num,\n                __ins.c_str(),\n                atomPtr->coord()[0],\n                atomPtr->coord()[1],\n                atomPtr->coord()[2],\n                atomPtr->occ().c_str(),\n                atomPtr->tempF().c_str(),\n                atomPtr->ele().c_str(),\n                atomPtr->chg().c_str()\n            );\n        }\n        else\n        {\n            fprintf(fo, \"ATOM  %5d  %-3s%1s%3s %1s%4d%1s   %8.3f%8.3f%8.3f%6s%6s          %2s%2s\\n\",\n                atomPtr->num(),\n                atomPtr->name().c_str(),\n                atomPtr->alt().c_str(),\n                __name.c_str(),\n                chainName.c_str(),\n                __num,\n                __ins.c_str(),\n                atomPtr->coord()[0],\n                atomPtr->coord()[1],\n                atomPtr->coord()[2],\n                atomPtr->occ().c_str(),\n                atomPtr->tempF().c_str(),\n                atomPtr->ele().c_str(),\n                atomPtr->chg().c_str()\n            );\n        }\n    }\n\n    fclose(fo);\n\n    return this;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Destructor\n////////////////////////////////////////////////////////////////////////////////\n\nResidue::~Residue()\n{\n    for (auto subPtr: __sub)\n    {\n        delete subPtr;\n    }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// str\n////////////////////////////////////////////////////////////////////////////////\n\nstring Residue::__str() const\n{\n    return (format(\"<Residue object: %d%s %s, at 0x%p>\") %\n        __num                                            %\n        __ins                                            %\n        __name                                           %\n        this\n    ).str();\n}\n\n\n}  // End namespace PDBTools\n", "meta": {"hexsha": "4cf8b0c8b2744246a5b9f684ffbb2762a119b2d3", "size": 17510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Residue.hpp", "max_stars_repo_name": "yingyulou/PDBToolsCpp", "max_stars_repo_head_hexsha": "61d0f72851d42b4f3b06931be4f47d393d82dd2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:29:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-03T05:19:41.000Z", "max_issues_repo_path": "src/Residue.hpp", "max_issues_repo_name": "yingyulou/PDBToolsCpp", "max_issues_repo_head_hexsha": "61d0f72851d42b4f3b06931be4f47d393d82dd2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Residue.hpp", "max_forks_repo_name": "yingyulou/PDBToolsCpp", "max_forks_repo_head_hexsha": "61d0f72851d42b4f3b06931be4f47d393d82dd2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-03T05:19:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:16:55.000Z", "avg_line_length": 27.231726283, "max_line_length": 100, "alphanum_fraction": 0.3990291262, "num_tokens": 3203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181321265898594, "lm_q2_score": 0.02368947379800174, "lm_q1q2_score": 0.0047808488133756}}
{"text": "/**\n * Copyright (c) 2018, University Osnabrück\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 University Osnabrück 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 University Osnabrück 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 * DualOctree.hpp\n *\n *  Created on: 18.01.2019\n *      Author: Benedikt Schumacher\n */\n\n#ifndef DualOctree_HPP_\n#define DualOctree_HPP_\n\n#include <boost/thread.hpp>\n#include \"OctreeTables.hpp\"\n\nnamespace lvr2\n{\n\ntemplate<typename BaseVecT, typename BoxT>\nclass DualLeaf\n{\npublic:\n\n    /**\n     * @brief Constructor.\n     *\n     * @param middle Center of the voxel\n     */\n    DualLeaf(BaseVecT vertices[]);\n\n    /**\n     * @brief Destructor (virtual)\n     */\n    virtual ~DualLeaf(){};\n\n    /**\n     * @brief Calculates and returns the bit-pattern respectively index from the edges of the represented voxel for the MC-Table.\n     *\n     * @param  distances Distances of the eight edges.\n     * @return Index for the MC-Table.\n     */\n    int getIndex(float distances[]);\n\n    BaseVecT getIntersectionPoint(float intersection, BaseVecT corner_one, BaseVecT corner_two);\n    BaseVecT getIntersectionPoint(BaseVecT corner_one, float intersection, BaseVecT corner_two);\n    BaseVecT getIntersectionPoint(BaseVecT corner_one, BaseVecT corner_two, float intersection);\n\n    /**\n     * @brief Calculates the twelve possible intersections between the cell and the surface to interpolate.\n     *\n     * @param corners   Eight corners of the current cell.\n     * @param distance  Corresponding distance value.\n     * @param positions Interpolated intersections.\n     */\n    void getIntersections(\n            BaseVecT corners[],\n            float distance[],\n            BaseVecT positions[]);\n\n    /**\n     * @brief Returns edges of the voxel.\n     *\n     * @param corner Corners of the voxel.\n     */\n    void getVertices(\n            BaseVecT corners[]);\n\n    /**\n     * @brief Returns the stored intersection between the cell and the surface at a given edge.\n     *\n     * @param i Index of the edge.\n     */\n    uint getIntersection(char i);\n\n    /**\n     * @brief Returns the middle of the represented voxel.\n     *\n     * @return Middle of the represented voxel.\n     */\n    BaseVecT& getMiddle();\n\n    /**\n     * @brief Sets the intersection between the cell and the surface at a given edge.\n     *\n     * @param i     Index of the edge.\n     * @param value Value of the intersection.\n     */\n    void setIntersection(char i, uint value);\n\nprotected:\n\n    /**\n     * @brief Interpolates the intersection between x1 and x1.\n     *\n     * @param x1 First coordinate.\n     * @param x2 Second coordinate.\n     * @param d1 Distance value for the first coordinate.\n     * @param d2 Distance value for the second coordinate.\n     * @return Interpolated distance.\n     */\n    float calcIntersection(float x1, float x2, float d1, float d2);\n\n    // Vertices of the represented voxel.\n    BaseVecT m_vertices[8];\n\n    // Twelve possible intersections.\n    uint m_intersections[12];\n};\n\n}\n\n#include \"DualOctree.tcc\"\n\n#endif /* DualOctree_HPP_ */\n", "meta": {"hexsha": "bd61c2bf62f36c222cb227a4b982b177ec306175", "size": 4432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lvr2/reconstruction/DualOctree.hpp", "max_stars_repo_name": "uos/lvr", "max_stars_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-06-19T15:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:08:24.000Z", "max_issues_repo_path": "include/lvr2/reconstruction/DualOctree.hpp", "max_issues_repo_name": "uos/lvr", "max_issues_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:31:25.000Z", "max_forks_repo_path": "include/lvr2/reconstruction/DualOctree.hpp", "max_forks_repo_name": "uos/lvr", "max_forks_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-04-16T11:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T07:47:44.000Z", "avg_line_length": 31.6571428571, "max_line_length": 129, "alphanum_fraction": 0.6888537906, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208212878370535, "lm_q2_score": 0.014728613876752788, "lm_q1q2_score": 0.004725252871994526}}
{"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#pragma once\n\n#include <chrono>\n#include <thread>\n#include \"ivarp/prover/cuboid_queue.hpp\"\n#include \"ivarp/bound_propagation.hpp\"\n#include \"ivarp/splitter.hpp\"\n#include <boost/range/iterator_range.hpp>\n\nnamespace ivarp {\nnamespace impl {\n    template<typename NumberType, std::size_t NumArgs> struct ProofDriverQueueEntry {\n        IVARP_DEFAULT_CM(ProofDriverQueueEntry);\n\n        ProofDriverQueueEntry() = default;\n        explicit IVARP_HD ProofDriverQueueEntry(const Array<NumberType,NumArgs>& a) : depth(0) {\n            for(std::size_t i = 0; i < NumArgs; ++i) {\n                elements[i] = a[i];\n            }\n        }\n\n        NumberType elements[NumArgs];\n        std::size_t depth;\n    };\n\n    struct CuboidCounts {\n        std::size_t num_cuboids{0};\n        std::size_t num_leaf_cuboids{0};\n        std::size_t num_critical_cuboids{0};\n        std::size_t num_repeated_nodes{0};\n\n        IVARP_HD CuboidCounts &operator+=(const CuboidCounts& c) noexcept {\n            num_cuboids += c.num_cuboids;\n            num_leaf_cuboids += c.num_leaf_cuboids;\n            num_critical_cuboids += c.num_critical_cuboids;\n            num_repeated_nodes += c.num_repeated_nodes;\n            return *this;\n        }\n\n#if defined(__CUDA_ARCH__)\n        IVARP_D void gpu_atomic_add(const CuboidCounts& c) noexcept {\n\t\t\tivarp::gpu_atomic_add(&num_cuboids, c.num_cuboids);\n\t\t\tivarp::gpu_atomic_add(&num_leaf_cuboids, c.num_leaf_cuboids);\n\t\t\tivarp::gpu_atomic_add(&num_critical_cuboids, c.num_critical_cuboids);\n\t\t\tivarp::gpu_atomic_add(&num_repeated_nodes, c.num_repeated_nodes);\n        }\n#endif\n    };\n\n    static inline IVARP_HD ProofInformation& operator+=(ProofInformation& p, const CuboidCounts& c) noexcept {\n        p.num_cuboids += c.num_cuboids;\n        p.num_leaf_cuboids += c.num_leaf_cuboids;\n        p.num_critical_cuboids += c.num_critical_cuboids;\n        p.num_repeated_nodes += c.num_repeated_nodes;\n        return p;\n    }\n\n    /**\n     * An object that captures the state of the proof in a proof driver.\n     */\n    class ProofDriverState {\n    public:\n        /**\n         * Create a new ProofDriverState in its initial state.\n         *\n         * @param num_threads\n         * @param queue_mutex\n         */\n        ProofDriverState(std::size_t num_threads, std::mutex* queue_mutex) noexcept :\n            mutex(queue_mutex), num_threads(num_threads)\n        {}\n\n        /**\n         * Re-throws the error, if there was any, on the thread calling this method.\n         * Does not have to take a lock.\n         */\n        void reraise_error_if_any() const {\n            if(have_error.load() == 2) {\n                std::rethrow_exception(error);\n            }\n        }\n\n        /**\n         * Set an error. The error is only ever set once.\n         * @param error The error to set.\n         * @param error_thread The thread ID raising the error.\n         */\n        void set_error(std::exception_ptr error, std::size_t error_thread) noexcept {\n            int expected = 0;\n            if(have_error.compare_exchange_strong(expected, 1)) {\n                this->error = error;\n                this->error_thread = error_thread;\n                have_error.store(2);\n                state_changed.notify_all();\n            }\n        }\n\n        /**\n         * Check whether there is an error. Does not need to lock.\n         * @return\n         */\n        bool error_is_set() const noexcept {\n            return have_error.load() == 2;\n        }\n\n        std::size_t get_error_thread() const noexcept {\n            return error_thread;\n        }\n\n        /**\n         * Declare that the thread calling this method is done with proof initialization.\n         */\n        void init_done() noexcept {\n            std::unique_lock<std::mutex> lock(*mutex);\n            if(++threads_done_init >= num_threads) {\n                state_changed.notify_all();\n            }\n        }\n\n        /**\n         * Wait for all threads to be done with proof initialization.\n         * Reraises the error if any is set.\n         */\n        void wait_for_init() const {\n            std::unique_lock<std::mutex> lock(*mutex);\n            state_changed.wait(lock, [&]() -> bool {\n                return error_is_set() || threads_done_init >= num_threads;\n            });\n            reraise_error_if_any();\n        }\n\n        /**\n         * Declare that queue compaction is done.\n         */\n        void queue_compaction_done() noexcept {\n            std::unique_lock<std::mutex> lock(*mutex);\n            compaction_done = true;\n            state_changed.notify_all();\n        }\n\n        /**\n         * Wait for queue compaction to complete.\n         * Re-raises the error if any is set.\n         */\n         void wait_for_queue_compaction() const {\n            std::unique_lock<std::mutex> lock(*mutex);\n            state_changed.wait(lock, [&]() -> bool {\n                return error_is_set() || compaction_done;\n            });\n            reraise_error_if_any();\n         }\n\n         /**\n          * Declare that the proof is done. Only called by the main thread.\n          */\n         void declare_proof_done() noexcept {\n            std::unique_lock<std::mutex> lock(*mutex);\n            proof_done = true;\n            state_changed.notify_all();\n         }\n\n         /**\n          * The method used by the progress observer to wait for:\n          *   * a specific time limit to occur,\n          *   * an error being set,\n          *   * the proof being done.\n          * Uses an external lock. Returns true if the proof was done in time.\n          * Re-raises the error if any is set.\n          */\n         template<typename TimePoint>\n            bool wait_until_done(std::unique_lock<std::mutex>& lock, TimePoint wait_until)\n         {\n            bool status = state_changed.wait_until(lock, wait_until, [&] () -> bool {\n                return error_is_set() || proof_done;\n            });\n\n            if(!status) {\n                return false;\n            }\n            reraise_error_if_any();\n            return true;\n         }\n\n    private:\n        std::mutex* mutex; ///< The mutex to use for waiting and other situations where locking is necessary.\n        mutable std::condition_variable state_changed; ///< A condition variable to wait for state changes.\n        std::size_t num_threads; ///< The number of threads running the proof.\n        std::size_t threads_done_init{0}; ///< The number of threads done with proof initialization.\n        std::atomic<int> have_error{0}; ///< Whether we have encountered an exception on any thread. 0: no error, 1: error is being set, 2: error is set.\n        std::exception_ptr error; ///< The error, if any.\n        std::size_t error_thread; ///< The thread that set the error.\n        bool compaction_done{false}; ///< Whether queue compaction after initialization is done.\n        bool proof_done{false}; ///< Whether the proof is done.\n    };\n\n    template<typename ProverInputType, typename CoreProver, typename OnCritical, typename ProgressReporter>\n    class ProofDriver\n    {\n    private:\n        // Number of variables and args.\n        static constexpr std::size_t num_args = ProverInputType::num_args;\n        static constexpr std::size_t num_vars = ProverInputType::num_vars;\n        static constexpr std::size_t initial_queue_size = ProverInputType::initial_queue_size;\n\n        // Prover input types\n        using Context = typename ProverInputType::Context;\n        using DynamicSplitInfo = typename ProverInputType::DynamicSplitInfo;\n        using StaticSplitInfo = typename ProverInputType::StaticSplitInfo;\n        using RBT = typename ProverInputType::RuntimeBoundTable;\n        using RCT = typename ProverInputType::RuntimeConstraintTable;\n\n        // Propagation information\n        using DBA = DynamicBoundApplication<RBT, Context>;\n\n        // Number-type and queue related types\n        using NumberType = typename Context::NumberType;\n        using QueueElement = ProofDriverQueueEntry<NumberType, num_args>;\n        using QueueType = CuboidQueue<QueueElement, true, CuboidQueueOrder::LIFO>;\n        using Lock = std::unique_lock<std::mutex>;\n\n        struct ProofDriverThread {\n            ProofDriverThread(ProofDriver* driver, std::size_t id) :\n                driver(driver),\n                id(id),\n                handle()\n            {\n                dequeue_buffer.reserve(driver->settings.dequeue_buffer_size);\n            }\n\n            ProofDriverThread(const ProofDriverThread&) = delete;\n            ProofDriverThread &operator=(const ProofDriverThread&) = delete;\n\n            ProofDriverThread(ProofDriverThread&& o) noexcept :\n                driver(o.driver),\n                id(o.id),\n                handle(std::move(o.handle)),\n                dequeue_buffer(std::move(o.dequeue_buffer)),\n                result_buffer(std::move(o.result_buffer))\n            {}\n\n            ProofDriverThread &operator=(ProofDriverThread&& o) noexcept {\n                driver = o.driver;\n                id = o.id;\n                handle = std::move(o.handle);\n                dequeue_buffer.swap(o.dequeue_buffer);\n                result_buffer.swap(o.result_buffer);\n                return *this;\n            }\n\n            void join() {\n                if(id != 0 && handle.joinable()) {\n                    handle.join();\n                }\n            }\n\n            ~ProofDriverThread() {\n                if(handle.joinable()) {\n                    handle.join();\n                }\n            }\n\n            void entry_point() noexcept {\n                try {\n                    proof_init();\n                    driver->state.init_done();\n                    driver->state.wait_for_queue_compaction();\n                    proof_main();\n                } catch(...) {\n                    std::exception_ptr cexp = std::current_exception();\n                    driver->state.set_error(cexp, id);\n                }\n            }\n\n            void spawn() {\n                assert(!handle.joinable());\n                handle = std::thread(&ProofDriverThread::entry_point, this);\n                assert(handle.joinable());\n            }\n\n            void proof_init() {\n                proof_init_begin(driver->initial_cuboid, DynamicSplitInfo{});\n            }\n\n            static constexpr auto rec_limit = static_cast<std::uint8_t>(ivarp::min(num_args,255));\n            static constexpr auto it_limit = 2*num_args;\n\n            void proof_init_set_to_empty(std::size_t count, std::size_t* offset) const noexcept {\n                // mark as empty by making the first interval empty; all empty entries will be compacted\n                // after the initial phase to allow parallel initialization\n                for(std::size_t j = 0; j < count; ++j) {\n                    QueueElement& qe = driver->queue[*offset];\n                    qe.elements[0].set_lb(1);\n                    qe.elements[0].set_ub(0);\n                    *offset += 1;\n                }\n            }\n\n            template<typename S1, typename... Splits>\n                void proof_init_begin(const Array<NumberType,num_args>& initial, const SplitInfoSequence<S1,Splits...>&)\n            {\n                using BoundEv = BoundEvent<S1::arg, BoundID::BOTH>;\n                const auto& rbt = driver->rbt;\n                const auto& dba = driver->dba;\n                const auto num_threads = static_cast<std::size_t>(driver->settings.thread_count);\n                constexpr std::size_t s1s = S1::initial;\n                constexpr std::size_t rem_initial = initial_queue_size / s1s;\n\n                const std::size_t s1s_per_thread = ivarp::max(s1s / num_threads, 1);\n                if(id >= s1s) {\n                    return;\n                }\n\n                const std::size_t beg = id * s1s_per_thread;\n                const std::size_t end = (id != num_threads-1) ? (id+1) * s1s_per_thread : s1s;\n                Splitter<NumberType> splitter(initial[S1::arg], static_cast<int>(s1s));\n                std::size_t offset = beg * rem_initial;\n                for(int i = static_cast<int>(beg); i < static_cast<int>(end); ++i) {\n                    ++counts.num_cuboids;\n                    QueueElement qsub{initial};\n                    qsub.elements[S1::arg] = splitter.subrange(i);\n                    if(propagate_iterated_recursive::propagate<BoundEv,Context>(rbt, qsub.elements, dba,\n                                                                                it_limit, rec_limit).empty)\n                    {\n                        ++counts.num_leaf_cuboids;\n                        proof_init_set_to_empty(rem_initial, &offset);\n                    } else {\n                        proof_init_continue<rem_initial>(qsub, &offset, SplitInfoSequence<Splits...>{});\n                    }\n                }\n            }\n\n            template<std::size_t EntriesPerElement, typename SN, typename... Splits>\n            void proof_init_continue(const QueueElement& e, std::size_t* offset, const SplitInfoSequence<SN,Splits...>&)\n            {\n                using BoundEv = BoundEvent<SN::arg, BoundID::BOTH>;\n                const auto& rbt = driver->rbt;\n                const auto& dba = driver->dba;\n                constexpr std::size_t sns = SN::initial;\n                constexpr std::size_t next_epe = EntriesPerElement / sns;\n                Splitter<NumberType> splitter(e.elements[SN::arg], static_cast<int>(sns));\n                for(NumberType sub : splitter) {\n                    ++counts.num_cuboids;\n                    QueueElement qsub{e};\n                    qsub.elements[SN::arg] = sub;\n                    if(propagate_iterated_recursive::propagate<BoundEv, Context>(rbt, qsub.elements, dba,\n                                                                                 it_limit, rec_limit).empty)\n                    {\n                        ++counts.num_leaf_cuboids;\n                        proof_init_set_to_empty(next_epe, offset);\n                    } else {\n                        proof_init_continue<next_epe>(qsub, offset, SplitInfoSequence<Splits...>{});\n                    }\n                }\n            }\n\n            template<std::size_t EntriesPerElement>\n            void proof_init_continue(const QueueElement& e, std::size_t* offset, const SplitInfoSequence<>&) {\n                static_assert(EntriesPerElement == 1, \"Something is wrong with the initial queue size!\");\n                QueueElement& qe = driver->queue[*offset];\n                *offset += 1;\n\n                if(!driver->satisfies_all_constraints(e)) {\n                    qe.elements[0].set_lb(1);\n                    qe.elements[0].set_ub(0);\n                    ++counts.num_leaf_cuboids;\n                } else {\n                    qe = e;\n                }\n            }\n\n            void proof_main() {\n                driver->core->initialize_per_thread(id, static_cast<std::size_t>(driver->settings.thread_count));\n                while(refill_buffer()) {\n                    driver->state.reraise_error_if_any();\n                    counts += driver->core->handle_cuboids_nonfinal(id, dequeue_buffer, &result_buffer);\n                    dequeue_buffer.clear();\n                    if(!result_buffer.empty()) {\n                        handle_core_result();\n                    }\n                }\n            }\n\n            bool refill_buffer() {\n                driver->queue.pop_into(dequeue_buffer, driver->settings.dequeue_buffer_size);\n                return !dequeue_buffer.empty();\n            }\n\n            void handle_core_result() {\n                std::vector<QueueElement> final_elements;\n                for(const QueueElement& q : result_buffer) {\n                    if(q.depth >= driver->settings.generation_count) {\n                        final_elements.push_back(q);\n                    } else {\n                        dequeue_buffer.push_back(q);\n                    }\n                }\n                result_buffer.clear();\n\n                if(!final_elements.empty()) {\n                    counts += driver->core->handle_cuboids_final(id, final_elements);\n                }\n                if(!dequeue_buffer.empty()) {\n                    split_and_requeue();\n                }\n            }\n\n            void split_and_requeue() {\n                for(const QueueElement& e : dequeue_buffer) {\n                    split_into(e, result_buffer);\n                }\n                dequeue_buffer.clear();\n                if(!result_buffer.empty()) {\n                    driver->queue.enqueue_bulk(result_buffer.begin(), result_buffer.end());\n                }\n                result_buffer.clear();\n            }\n\n            struct SplitIntoImpl;\n            void split_into(QueueElement e, std::vector<QueueElement>& output);\n\n            ProofDriver* driver;\n            std::size_t id;\n            std::thread handle;\n            std::vector<QueueElement> dequeue_buffer, result_buffer;\n            CuboidCounts counts;\n        };\n\n    public:\n        explicit ProofDriver(ProverInputType input, const OnCritical* on_c,\n                             ProgressReporter* rep, ProofInformation* info,\n                             CoreProver* core, ProverSettings s) noexcept :\n            rbt(ivarp::move(input.runtime_bounds)),\n            dba(&rbt),\n            rct(ivarp::move(input.runtime_constraints)),\n            on_critical(on_c), reporter(rep),\n            information(info), core(core), settings(ivarp::move(s)),\n            initial_cuboid(ivarp::move(input.initial_runtime_bounds)),\n            queue(initial_queue_size, static_cast<unsigned>(settings.thread_count)),\n            state(static_cast<std::size_t>(settings.thread_count), &queue.mutex())\n        {\n            core->set_runtime_bounds(&rbt);\n            core->set_runtime_constraints(&rct);\n            core->set_dynamic_bound_application(&dba);\n            core->set_on_critical(on_critical);\n            core->set_settings(&settings);\n            core->initialize(static_cast<std::size_t>(settings.thread_count));\n            p_init_threads();\n        }\n\n        bool run() {\n            try {\n                p_start_progress();\n                p_spawn_threads();\n                threads.front().proof_init();\n                p_compact_initial_queue();\n                threads.front().proof_main();\n                p_join_threads();\n                state.declare_proof_done();\n            } catch(...) {\n                state.set_error(std::current_exception(), 0);\n                p_join_threads();\n            }\n\n            progress_observer.join();\n            state.reraise_error_if_any();\n            return information->num_critical_cuboids == 0;\n        }\n\n        bool satisfies_all_constraints(const QueueElement& e) const {\n            return satisfies_all_constraints(e.elements);\n        }\n\n        template<typename ArrayType>\n        bool satisfies_all_constraints(const ArrayType& values) const {\n            const auto& all_c = ProverInputType::all_constraints(rct);\n            bool all_sat = true;\n            auto visitor = [&] (const auto& constr) -> TupleVisitationControl {\n                auto cres = constr.template array_evaluate<Context>(values);\n                if(!possibly(cres)) {\n                    all_sat = false;\n                    return TupleVisitationControl::STOP;\n                }\n                return TupleVisitationControl::CONTINUE;\n            };\n            visit_tuple(visitor, all_c);\n            return all_sat;\n        }\n\n    private:\n        void p_spawn_threads() {\n            for(ProofDriverThread& t : boost::make_iterator_range(threads.begin() + 1, threads.end())) {\n                t.spawn();\n            }\n        }\n\n        void p_compact_initial_queue() {\n            state.init_done();\n            state.wait_for_init();\n            {\n                Lock lock(queue.mutex());\n                auto b = queue.begin();\n                auto e = queue.end();\n                auto new_end = std::remove_if(b, e, [] (const auto& e) { return e.elements[0].empty(); });\n                queue.unlocked_erase(new_end, e);\n            }\n            state.queue_compaction_done();\n        }\n\n        void p_join_threads() {\n            information->num_critical_cuboids = 0;\n            information->num_cuboids = 0;\n            information->num_leaf_cuboids = 0;\n            information->num_repeated_nodes = 0;\n            for(ProofDriverThread& t : threads) {\n                t.join();\n                *information += t.counts;\n            }\n        }\n\n        void p_init_threads() {\n            const auto nt = static_cast<std::size_t>(settings.thread_count);\n            threads.reserve(nt);\n            for(std::size_t i = 0; i < nt; ++i) {\n                threads.emplace_back(this, i);\n            }\n        }\n\n        // Progress observation.\n        void p_start_progress() {\n            progress_observer = std::thread(&ProofDriver::p_progress_main, this);\n        }\n\n        void p_progress_main() noexcept {\n            try {\n                auto begun_at = std::chrono::steady_clock::now();\n                auto begin_progress_at = begun_at + settings.start_progress_after;\n\n                // wait for initialization & compaction\n                state.wait_for_queue_compaction();\n\n                // take lock\n                Lock lock{queue.mutex()};\n                if(state.wait_until_done(lock, begin_progress_at)) {\n                    p_call_progress_observer_done();\n                    return;\n                }\n\n                for(;;) {\n                    p_call_progress_observer();\n                    auto next_progress_at = std::chrono::steady_clock::now() + settings.progress_every;\n                    if(state.wait_until_done(lock, next_progress_at)) {\n                        p_call_progress_observer_done();\n                        return;\n                    }\n                }\n            } catch(...) {\n                p_call_progress_observer_error(std::current_exception(), state.get_error_thread());\n            }\n        }\n\n        void p_call_progress_observer() {\n            ProgressInfo info;\n            info.queue_size = queue.unlocked_size();\n            for(const ProofDriverThread& t : threads) {\n                info.leaf_count += t.counts.num_leaf_cuboids;\n                info.critical_count += t.counts.num_critical_cuboids;\n                info.cuboid_count += t.counts.num_cuboids;\n            }\n            QueueElement element;\n            if(queue.unlocked_peek(element)) {\n                reporter->observe_progress(Context{}, element, info);\n            }\n        }\n\n        void p_call_progress_observer_done() {\n            reporter->observe_done();\n        }\n\n        void p_call_progress_observer_error(std::exception_ptr error, std::size_t error_thread_id) {\n            reporter->observe_error(error, error_thread_id);\n        }\n\n        // Progress observer thread.\n        std::thread progress_observer;\n\n        // Immutable information, such as settings, bounds/constraints.\n        const RBT rbt;\n        const DBA dba;\n        const RCT rct;\n        const OnCritical* const on_critical;\n        ProgressReporter* const reporter;\n        ProofInformation* const information;\n        CoreProver* const core;\n        ProverSettings const settings;\n        Array<NumberType, num_args> const initial_cuboid;\n\n        // The queue and per-thread information.\n        QueueType queue;\n\n        // The global state of the proof, i.e., what stage is running, etc.\n        ProofDriverState state;\n\n        // The threads running the proof, along with their state.\n        std::vector<ProofDriverThread> threads;\n    };\n}\n}\n\n#include \"pd_impl_split_into.hpp\"\n", "meta": {"hexsha": "5cd58ebc7f321734aa2f19b3d05b44b7d430523e", "size": 24922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ivarp/include/ivarp/prover/proof_driver.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/prover/proof_driver.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/prover/proof_driver.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": 39.4335443038, "max_line_length": 153, "alphanum_fraction": 0.5544498836, "num_tokens": 5058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256831980010821, "lm_q2_score": 0.01826427494520817, "lm_q1q2_score": 0.004690849897639844}}
{"text": "\n//////////////////////////////////////////////////////////////////////////////////\n// MIT License\n//\n// Copyright (c) 2017 Vicon Motion Systems Ltd\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\r\n\r\n#include \"ClientUtils.h\"\r\n\r\n\r\n#include <boost/asio.hpp>\r\n#include <boost/format.hpp>\r\n#include <boost/array.hpp>\r\n\r\n#include <numeric>\r\n\r\nnamespace ClientUtils\r\n{\r\n  // These functions clear a value\r\n  void Clear( bool & o_rValue )\r\n  {\r\n    o_rValue = false;\r\n  }\r\n\r\n  void Clear( unsigned int & o_rValue )\r\n  {\r\n    o_rValue = 0;\r\n  }\r\n\r\n  void Clear( double & o_rValue )\r\n  {\r\n    o_rValue = 0.0;\r\n  }\r\n\r\n  void Clear( std::string & o_rValue )\r\n  {\r\n    o_rValue.clear();\r\n  }\r\n\r\n  void Clear( ViconDataStreamSDK::Core::TimecodeStandard::Enum & o_rValue )\r\n  {\r\n    o_rValue = ViconDataStreamSDK::Core::TimecodeStandard::None;\r\n  }\r\n\r\n  void Clear( ViconDataStreamSDK::Core::DeviceType::Enum & o_rValue )\r\n  {\r\n    o_rValue = ViconDataStreamSDK::Core::DeviceType::Unknown;\r\n  }\r\n\r\n  void Clear( ViconDataStreamSDK::Core::Unit::Enum & o_rValue )\r\n  {\r\n    o_rValue = ViconDataStreamSDK::Core::Unit::Unknown;\r\n  }\r\n\r\n  // Determine whether an axis is positive or negative\r\n  double ComponentSign( ViconDataStreamSDK::Core::Direction::Enum i_Direction )\r\n  {\r\n    switch( i_Direction )\r\n    {\r\n    case ViconDataStreamSDK::Core::Direction::Forward :\r\n    case ViconDataStreamSDK::Core::Direction::Left    :\r\n    case ViconDataStreamSDK::Core::Direction::Up      : return 1.0;\r\n    case ViconDataStreamSDK::Core::Direction::Backward:\r\n    case ViconDataStreamSDK::Core::Direction::Right   :\r\n    case ViconDataStreamSDK::Core::Direction::Down    : return -1.0;\r\n    default                                           : assert( !\"Unknown enum value\" );\r\n                                                        return 0.0;\r\n    }\r\n  }\r\n\r\n  // Determine the index of an enum\r\n  unsigned int ComponentIndex( ViconDataStreamSDK::Core::Direction::Enum i_Direction )\r\n  {\r\n    switch( i_Direction )\r\n    {\r\n    case ViconDataStreamSDK::Core::Direction::Forward :\r\n    case ViconDataStreamSDK::Core::Direction::Backward: return 0;\r\n    case ViconDataStreamSDK::Core::Direction::Left    :\r\n    case ViconDataStreamSDK::Core::Direction::Right   : return 1;\r\n    case ViconDataStreamSDK::Core::Direction::Up      :\r\n    case ViconDataStreamSDK::Core::Direction::Down    : return 2;\r\n    default                                           : assert( !\"Unknown enum value\" );\r\n                                                        return 0;\r\n    }\r\n  }\r\n\r\n  std::string ComponentName( ViconDataStreamSDK::Core::Direction::Enum i_Direction )\r\n  {\r\n    switch( i_Direction )\r\n    {\r\n    case ViconDataStreamSDK::Core::Direction::Forward: return \"Forward\";\r\n    case ViconDataStreamSDK::Core::Direction::Backward: return \"Backward\";\r\n    case ViconDataStreamSDK::Core::Direction::Left: return \"Left\";\r\n    case ViconDataStreamSDK::Core::Direction::Right: return \"Right\";\r\n    case ViconDataStreamSDK::Core::Direction::Up: return \"Up\";\r\n    case ViconDataStreamSDK::Core::Direction::Down: return \"Down\";\r\n    default: assert( !\"Unknown enum value\" );\r\n      return \"\";\r\n    }\r\n\r\n  }\r\n\r\n  std::string AdaptCameraName( const std::string & i_rCameraName,\r\n                               const std::string & i_rDisplayType,\r\n                               const unsigned int  i_CameraID )\r\n  {\r\n    // Append Camera info to ensure uniqueness, since this name is used as keys in the DSSDK Camera APIs\r\n    return str( boost::format( \"%s (%d)\" ) %( i_rCameraName.empty()? i_rDisplayType : i_rCameraName ) %i_CameraID );\r\n  }\r\n\r\n  std::string AdaptDeviceName( const std::string & i_rDeviceName, \r\n                               const unsigned int  i_DeviceID )\r\n  {\r\n    if( !i_rDeviceName.empty() )\r\n    {\r\n      return i_rDeviceName;\r\n    }\r\n    else\r\n    {\r\n      return str( boost::format( \"Unnamed Device %d\" ) % i_DeviceID );\r\n    }\r\n  }\r\n\r\n  std::string AdaptDeviceOutputName( const std::string & i_rDeviceOutputName, \r\n                                     const unsigned int  i_DeviceOutputIndex )\r\n  {\r\n    if( !i_rDeviceOutputName.empty() )\r\n    {\r\n      return i_rDeviceOutputName;\r\n    }\r\n    else\r\n    {\r\n      return str( boost::format( \"Unnamed Device Output %d\" ) % ( i_DeviceOutputIndex + 1 ) );\r\n    }\r\n  }\r\n\r\n  bool IsValidMulticastIP( const std::string & i_MulticastIPAddress )\r\n  {\r\n    boost::asio::io_service Service;\r\n    boost::system::error_code Error;\r\n    boost::asio::ip::address_v4 Address = boost::asio::ip::address_v4::from_string( i_MulticastIPAddress, Error );\r\n    if( Error )\r\n    {\r\n      boost::asio::ip::tcp::resolver Resolver( Service );\r\n      boost::asio::ip::tcp::resolver::query Query( i_MulticastIPAddress, \"\" );\r\n      \r\n      boost::asio::ip::tcp::resolver::iterator It = Resolver.resolve( Query, Error );\r\n      boost::asio::ip::tcp::resolver::iterator End;\r\n      \r\n      if( ! Error )\r\n      {\r\n        for( ; It != End; ++It )\r\n        {\r\n          Error = boost::system::error_code();\r\n          boost::asio::ip::tcp::endpoint EndPoint( *It );\r\n\r\n          // Currently we only handle IPv4\r\n          if( EndPoint.address().is_v4() )\r\n          {\r\n            Address = EndPoint.address().to_v4();\r\n            break;\r\n          }\r\n        }\r\n      }\r\n      else\r\n      {\r\n        Address = boost::asio::ip::address_v4();\r\n      }\r\n    }\r\n\r\n    return( Address.is_multicast() || ( Address.to_ulong() == 0xFFFFFFFF ) );\r\n  }\r\n\r\n\r\n  void MatrixToQuaternion( const double i_M[9], double (&o_Q)[4])\r\n  {\r\n    // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\r\n    // article \"Quaternion Calculus and Fast Animation\".\r\n\r\n    double Trace = i_M[0*3+0]+i_M[1*3+1]+i_M[2*3+2];\r\n    double Root;\r\n\r\n    if( Trace > 0 )\r\n    {\r\n      // |w| > 1/2, may as well choose w > 1/2\r\n      Root = std::sqrt(Trace + 1.0);  // 2w\r\n      o_Q[3] = 0.5*Root;\r\n      Root = 0.5/Root;  // 1/(4w)\r\n      o_Q[0] = (i_M[2*3+1]-i_M[1*3+2])*Root;\r\n      o_Q[1] = (i_M[0*3+2]-i_M[2*3+0])*Root;\r\n      o_Q[2] = (i_M[1*3+0]-i_M[0*3+1])*Root;\r\n    }\r\n    else\r\n    {\r\n      // |w| <= 1/2\r\n      int s_Next[3] = { 1, 2, 0 };\r\n      int i = 0;\r\n      if ( i_M[1*3+1] > i_M[0*3+0] )\r\n          i = 1;\r\n      if ( i_M[2*3+2] > i_M[i*3+i] )\r\n          i = 2;\r\n      int j = s_Next[i];\r\n      int k = s_Next[j];\r\n\r\n      Root = std::sqrt(i_M[i*3+i]-i_M[j*3+j]-i_M[k*3+k] + 1.0);\r\n\r\n      o_Q[i] = 0.5*Root;\r\n      Root = 0.5/Root;\r\n      o_Q[3] = (i_M[k*3+j]-i_M[j*3+k])*Root;\r\n      o_Q[j] = (i_M[j*3+i]+i_M[i*3+j])*Root;\r\n      o_Q[k] = (i_M[k*3+i]+i_M[i*3+k])*Root;\r\n    }\r\n\r\n    // Normalize\r\n    const double InnerProduct = std::inner_product( o_Q, o_Q + 4, o_Q, 0.0 );\r\n    const double Magnitude = std::sqrt( InnerProduct );\r\n\r\n    o_Q[0] /= Magnitude;\r\n    o_Q[1] /= Magnitude;\r\n    o_Q[2] /= Magnitude;\r\n    o_Q[3] /= Magnitude;\r\n  }\r\n\r\n  \r\n  void MatrixToHelical( const double i_rM[9], double (&o_rAA)[3])\r\n  {\r\n    double Q[4];\r\n    MatrixToQuaternion( i_rM, Q );\r\n\r\n    const double Real = Q[3];\r\n\r\n    double Len = sqrt( std::inner_product( Q, Q+3, Q, 0.0 ) );\r\n    if( Len > std::numeric_limits< double >::epsilon() * 10 ) \r\n    {\r\n      const double Angle = 2.0 * atan2( Len, Real );\r\n      const double Scale = Angle / Len;\r\n      std::transform( Q, Q+3, o_rAA, [ Scale ]( double X ){ return Scale * X; } );\r\n    } \r\n    else \r\n    {\r\n      std::copy( Q, Q+3, o_rAA );\r\n    }\r\n\r\n  }\r\n\r\n  void MatrixToEulerXYZ( const double i_M[9], double (&o_rE)[3])\r\n  {\r\n    //  This original algorithm is the XYZ Euler order and is\r\n    //  the default input order argument, so no existing code\r\n    //  should need changing or will give different results\r\n\r\n    //  Algorithm: GraphicsGems II - Matrix Techniques VII.1 p 320\r\n\r\n    o_rE[1] = asin(i_M[0*3+2]);\r\n\r\n    if( fabs( cos(o_rE[1]) ) > std::numeric_limits< double >::epsilon() * 10 )   \r\n    {\r\n      o_rE[0] = std::atan2(-i_M[1*3+2], i_M[2*3+2]);\r\n      o_rE[2] = std::atan2(-i_M[0*3+1], i_M[0*3+0]);\r\n    }\r\n    else\r\n    {\r\n      // cos(y) ~= 0 Gimbal-Lock\r\n      o_rE[0] = (o_rE[1] > 0) ? std::atan2(i_M[1*3+0], i_M[1*3+1]) : -std::atan2(i_M[0*3+1], i_M[1*3+1]);\r\n      o_rE[2] = 0;\r\n    }\r\n  }\r\n\r\n    boost::array< double, 3 > operator*( const boost::array< double, 9 > & i_rM, const boost::array< double, 3 > & i_rX )\r\n  {\r\n    boost::array< double, 3 > Result;\r\n\r\n    for( size_t i = 0; i < 3; i++) \r\n    {  \r\n      double Sum = 0;\r\n      for( unsigned k = 0; k < 3; k++ ) \r\n      {\r\n        Sum += i_rM[i*3+k] * i_rX[k];\r\n      }\r\n      Result[i] = Sum;\r\n    }\r\n\r\n  return Result;\r\n  }\r\n\r\n  boost::array< double, 3 > & operator/=( boost::array< double, 3 > & i_rX, double i_Val )\r\n  {\r\n    std::transform( i_rX.begin(), i_rX.end(), i_rX.begin(), [ i_Val ]( double x ){ return x / i_Val; } );\r\n    return i_rX;\r\n  }\r\n\r\n  boost::array< double, 3 > & operator*=( boost::array< double, 3 > & i_rX, double i_Val )\r\n  {\r\n    std::transform( i_rX.begin(), i_rX.end(), i_rX.begin(), [ i_Val ]( double x ){ return x * i_Val; } );\r\n    return i_rX;\r\n  }\r\n\r\n  boost::array< double, 3 > operator+( const boost::array< double, 3 > & i_rX, const boost::array< double, 3 > & i_rY )\r\n  {\r\n    boost::array< double, 3 > Result;\r\n    std::transform( i_rX.begin(), i_rX.end(), i_rY.begin(), Result.begin(), []( double x, double y ){ return x + y; } );\r\n    return Result;\r\n  }\r\n\r\n  boost::array< double, 3 > operator-( const boost::array< double, 3 > & i_rX, const boost::array< double, 3 > & i_rY )\r\n  {\r\n    boost::array< double, 3 > Result;\r\n    std::transform( i_rX.begin(), i_rX.end(), i_rY.begin(), Result.begin(), []( double x, double y ){ return x - y; } );\r\n    return Result;\r\n  }\r\n    \r\n  boost::array< double, 9 > operator*( const boost::array< double, 9 > & i_rM, const boost::array< double, 9 > & i_rN )\r\n  {\r\n    boost::array< double, 9 > Result;\r\n\r\n    for( size_t i = 0; i < 3; i++) \r\n    {  \r\n      for( size_t j = 0; j < 3; j++) \r\n      { \r\n        double Sum = 0;\r\n        for( unsigned k = 0; k < 3; k++ ) \r\n        {\r\n          Sum += i_rM[i*3+k] * i_rN[k*3+j];\r\n        }\r\n        Result[i*3+j] = Sum;\r\n      }\r\n    }\r\n\r\n    return Result;\r\n  }\r\n\r\n\r\n  boost::array< double, 9 > Transpose( const boost::array< double, 9 > & i_rM )\r\n  {\r\n    boost::array< double, 9 > Result;\r\n\r\n    for( size_t i = 0; i < 3; i++) \r\n    {  \r\n      for( size_t j = 0; j < 3; j++) \r\n      { \r\n        Result[i*3+j] = i_rM[j*3+i];\r\n      }\r\n    }\r\n\r\n    return Result;\r\n  }\r\n\r\n  boost::array< double, 16 > Transpose( const boost::array< double, 16 > & i_rM )\r\n  {\r\n    boost::array< double, 16 > Result;\r\n\r\n    for( size_t i = 0; i < 4; i++) \r\n    {  \r\n      for( size_t j = 0; j < 4; j++) \r\n      { \r\n        Result[i*4+j] = i_rM[j*4+i];\r\n      }\r\n    }\r\n\r\n    return Result;\r\n  }\r\n\r\n  boost::array< double, 3 > CrossProduct( boost::array< double, 3 > & i_rA, boost::array< double, 3 > & i_rB )\r\n  {\r\n    boost::array< double, 3 > Result;\r\n    Result[0] = i_rA[1] * i_rB[2] - i_rA[2] * i_rB[1];\r\n    Result[1] = i_rA[2] * i_rB[0] - i_rA[0] * i_rB[2];\r\n    Result[2] = i_rA[0] * i_rB[1] - i_rA[1] * i_rB[0];\r\n    return Result;\r\n  }\r\n\r\n  double DotProduct( boost::array<double, 3> & i_rA, boost::array<double, 3> & i_rB )\r\n  {\r\n    double Result = 0;\r\n    for( unsigned i = 0; i < 3; ++i )\r\n    {\r\n      Result += i_rA[i] * i_rB[i];\r\n    }\r\n    return Result;\r\n  }\r\n}\r\n", "meta": {"hexsha": "39d4a1c3d8934c21510af33a7bf36f88cd804400", "size": 12437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mocap_vicon/src/vicon_sdk/Vicon/CrossMarket/DataStream/ViconDataStreamSDKCore/ClientUtils.cpp", "max_stars_repo_name": "ulvs/motion_capture_system", "max_stars_repo_head_hexsha": "ae4c0794d4a0b1e5436e830a6824761f2ce82f5f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T22:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T12:20:41.000Z", "max_issues_repo_path": "mocap_vicon/src/vicon_sdk/Vicon/CrossMarket/DataStream/ViconDataStreamSDKCore/ClientUtils.cpp", "max_issues_repo_name": "ulvs/motion_capture_system", "max_issues_repo_head_hexsha": "ae4c0794d4a0b1e5436e830a6824761f2ce82f5f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 187.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T16:02:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T00:14:32.000Z", "max_forks_repo_path": "mocap_vicon/src/vicon_sdk/Vicon/CrossMarket/DataStream/ViconDataStreamSDKCore/ClientUtils.cpp", "max_forks_repo_name": "ulvs/motion_capture_system", "max_forks_repo_head_hexsha": "ae4c0794d4a0b1e5436e830a6824761f2ce82f5f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2016-01-11T15:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T13:09:44.000Z", "avg_line_length": 31.0149625935, "max_line_length": 122, "alphanum_fraction": 0.5519819892, "num_tokens": 3717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1311732373477186, "lm_q2_score": 0.03567855126224297, "lm_q1q2_score": 0.004680071072944943}}
{"text": "/*-----------------------------------------------------------------------------+\r\nCopyright (c) 2010-2010: Joachim Faulhaber\r\n+------------------------------------------------------------------------------+\r\n   Distributed under the Boost Software License, Version 1.0.\r\n      (See accompanying file LICENCE.txt or copy at\r\n           http://www.boost.org/LICENSE_1_0.txt)\r\n+-----------------------------------------------------------------------------*/\r\n#ifndef BOOST_ICL_CONCEPT_INTERVAL_HPP_JOFA_100323\r\n#define BOOST_ICL_CONCEPT_INTERVAL_HPP_JOFA_100323\r\n\r\n#include <boost/assert.hpp>\r\n#include <boost/utility/enable_if.hpp>\r\n#include <boost/mpl/and.hpp>\r\n#include <boost/mpl/or.hpp>\r\n#include <boost/mpl/not.hpp>\r\n#include <boost/icl/detail/design_config.hpp>\r\n#include <boost/icl/type_traits/unit_element.hpp>\r\n#include <boost/icl/type_traits/identity_element.hpp>\r\n#include <boost/icl/type_traits/infinity.hpp>\r\n#include <boost/icl/type_traits/succ_pred.hpp>\r\n#include <boost/icl/type_traits/is_numeric.hpp>\r\n#include <boost/icl/type_traits/is_discrete.hpp>\r\n#include <boost/icl/type_traits/is_continuous.hpp>\r\n#include <boost/icl/type_traits/is_asymmetric_interval.hpp>\r\n#include <boost/icl/type_traits/is_discrete_interval.hpp>\r\n#include <boost/icl/type_traits/is_continuous_interval.hpp>\r\n\r\n#include <boost/icl/concept/interval_bounds.hpp>\r\n#include <boost/icl/interval_traits.hpp>\r\n#include <boost/icl/dynamic_interval_traits.hpp>\r\n\r\n#include <algorithm>\r\n\r\nnamespace boost{namespace icl\r\n{\r\n\r\n//==============================================================================\r\n//= Ordering\r\n//==============================================================================\r\ntemplate<class Type>\r\ninline typename enable_if<is_interval<Type>, bool>::type\r\ndomain_less(const typename interval_traits<Type>::domain_type& left,\r\n            const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    return typename interval_traits<Type>::domain_compare()(left, right);\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<is_interval<Type>, bool>::type\r\ndomain_less_equal(const typename interval_traits<Type>::domain_type& left,\r\n                  const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    return !(typename interval_traits<Type>::domain_compare()(right, left));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<is_interval<Type>, bool>::type\r\ndomain_equal(const typename interval_traits<Type>::domain_type& left,\r\n             const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    return !(domain_compare()(left, right)) && !(domain_compare()(right, left));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if< is_interval<Type>\r\n                         , typename interval_traits<Type>::domain_type>::type\r\ndomain_next(const typename interval_traits<Type>::domain_type value)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    return icl::successor<domain_type,domain_compare>::apply(value);\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if< is_interval<Type>\r\n                         , typename interval_traits<Type>::domain_type>::type\r\ndomain_prior(const typename interval_traits<Type>::domain_type value)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    return icl::predecessor<domain_type,domain_compare>::apply(value);\r\n}\r\n\r\n//==============================================================================\r\n//= Construct<Interval> singleton\r\n//==============================================================================\r\ntemplate<class Type>\r\ntypename enable_if\r\n<\r\n    mpl::and_< is_static_right_open<Type>\r\n             , is_discrete<typename interval_traits<Type>::domain_type> >\r\n  , Type\r\n>::type\r\nsingleton(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    //ASSERT: This always creates an interval with exactly one element\r\n    return interval_traits<Type>::construct(value, domain_next<Type>(value));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if\r\n<\r\n    mpl::and_< is_static_left_open<Type>\r\n             , is_discrete<typename interval_traits<Type>::domain_type> >\r\n  , Type\r\n>::type\r\nsingleton(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    //ASSERT: This always creates an interval with exactly one element\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                 ::is_less_than(value) ));\r\n\r\n    return interval_traits<Type>::construct(domain_prior<Type>(value), value);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<is_discrete_static_open<Type>, Type>::type\r\nsingleton(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    //ASSERT: This always creates an interval with exactly one element\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                 ::is_less_than(value)));\r\n\r\n    return interval_traits<Type>::construct( domain_prior<Type>(value)\r\n                                           , domain_next<Type>(value));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<is_discrete_static_closed<Type>, Type>::type\r\nsingleton(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    //ASSERT: This always creates an interval with exactly one element\r\n    return interval_traits<Type>::construct(value, value);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>, Type>::type\r\nsingleton(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    return dynamic_interval_traits<Type>::construct(value, value, interval_bounds::closed());\r\n}\r\n\r\nnamespace detail\r\n{\r\n\r\n//==============================================================================\r\n//= Construct<Interval> unit_trail == generalized singleton\r\n// The smallest interval on an incrementable (and decrementable) type that can\r\n// be constructed using ++ and -- and such that it contains a given value.\r\n// If 'Type' is discrete, 'unit_trail' and 'singleton' are identical. So we\r\n// can view 'unit_trail' as a generalized singleton for static intervals of\r\n// continuous types.\r\n//==============================================================================\r\ntemplate<class Type>\r\ntypename enable_if\r\n<\r\n    mpl::and_< is_static_right_open<Type>\r\n             , boost::detail::is_incrementable<typename interval_traits<Type>::domain_type> >\r\n  , Type\r\n>::type\r\nunit_trail(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    return interval_traits<Type>::construct(value, domain_next<Type>(value));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if\r\n<\r\n    mpl::and_< is_static_left_open<Type>\r\n             , boost::detail::is_incrementable<typename interval_traits<Type>::domain_type> >\r\n  , Type\r\n>::type\r\nunit_trail(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                 ::is_less_than(value) ));\r\n\r\n    return interval_traits<Type>::construct(domain_prior<Type>(value), value);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if\r\n<\r\n    mpl::and_< is_static_open<Type>\r\n             , is_discrete<typename interval_traits<Type>::domain_type> >\r\n  , Type\r\n>::type\r\nunit_trail(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                 ::is_less_than(value)));\r\n\r\n    return interval_traits<Type>::construct( domain_prior<Type>(value)\r\n                                           ,  domain_next<Type>(value));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if\r\n<\r\n    mpl::and_< is_static_closed<Type>\r\n             , is_discrete<typename interval_traits<Type>::domain_type> >\r\n  , Type\r\n>::type\r\nunit_trail(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    return interval_traits<Type>::construct(value, value);\r\n}\r\n\r\n//NOTE: statically bounded closed or open intervals of continuous domain types\r\n// are NOT supported by ICL. They can not be used with interval containers\r\n// consistently.\r\n\r\n\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>, Type>::type\r\nunit_trail(const typename interval_traits<Type>::domain_type& value)\r\n{\r\n    return dynamic_interval_traits<Type>::construct(value, value, interval_bounds::closed());\r\n}\r\n\r\n} //namespace detail\r\n\r\n//==============================================================================\r\n//= Construct<Interval> multon\r\n//==============================================================================\r\ntemplate<class Type>\r\ntypename enable_if<has_static_bounds<Type>, Type>::type\r\nconstruct(const typename interval_traits<Type>::domain_type& low,\r\n          const typename interval_traits<Type>::domain_type& up  )\r\n{\r\n    return interval_traits<Type>::construct(low, up);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>, Type>::type\r\nconstruct(const typename interval_traits<Type>::domain_type& low,\r\n          const typename interval_traits<Type>::domain_type& up,\r\n          interval_bounds bounds = interval_bounds::right_open())\r\n{\r\n    return dynamic_interval_traits<Type>::construct(low, up, bounds);\r\n}\r\n\r\n\r\n//- construct form bounded values ----------------------------------------------\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>, Type>::type\r\nconstruct(const typename Type::bounded_domain_type& low,\r\n          const typename Type::bounded_domain_type& up)\r\n{\r\n    return dynamic_interval_traits<Type>::construct_bounded(low, up);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<is_interval<Type>, Type>::type\r\nspan(const typename interval_traits<Type>::domain_type& left,\r\n     const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    if(domain_compare()(left,right))\r\n        return construct<Type>(left, right);\r\n    else\r\n        return construct<Type>(right, left);\r\n}\r\n\r\n\r\n//==============================================================================\r\ntemplate<class Type>\r\ntypename enable_if<is_static_right_open<Type>, Type>::type\r\nhull(const typename interval_traits<Type>::domain_type& left,\r\n     const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    if(domain_compare()(left,right))\r\n        return construct<Type>(left, domain_next<Type>(right));\r\n    else\r\n        return construct<Type>(right, domain_next<Type>(left));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<is_static_left_open<Type>, Type>::type\r\nhull(const typename interval_traits<Type>::domain_type& left,\r\n     const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    if(domain_compare()(left,right))\r\n    {\r\n        BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                     ::is_less_than(left) ));\r\n        return construct<Type>(domain_prior<Type>(left), right);\r\n    }\r\n    else\r\n    {\r\n        BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                     ::is_less_than(right) ));\r\n        return construct<Type>(domain_prior<Type>(right), left);\r\n    }\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<is_static_closed<Type>, Type>::type\r\nhull(const typename interval_traits<Type>::domain_type& left,\r\n     const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    if(domain_compare()(left,right))\r\n        return construct<Type>(left, right);\r\n    else\r\n        return construct<Type>(right, left);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<is_static_open<Type>, Type>::type\r\nhull(const typename interval_traits<Type>::domain_type& left,\r\n     const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    if(domain_compare()(left,right))\r\n    {\r\n        BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                     ::is_less_than(left) ));\r\n        return construct<Type>( domain_prior<Type>(left)\r\n                              ,  domain_next<Type>(right));\r\n    }\r\n    else\r\n    {\r\n        BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                     ::is_less_than(right) ));\r\n        return construct<Type>( domain_prior<Type>(right)\r\n                              ,  domain_next<Type>(left));\r\n    }\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>, Type>::type\r\nhull(const typename interval_traits<Type>::domain_type& left,\r\n     const typename interval_traits<Type>::domain_type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    if(domain_compare()(left,right))\r\n        return construct<Type>(left, right, interval_bounds::closed());\r\n    else\r\n        return construct<Type>(right, left, interval_bounds::closed());\r\n}\r\n\r\n//==============================================================================\r\n//= Selection\r\n//==============================================================================\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<is_interval<Type>,\r\n                          typename interval_traits<Type>::domain_type>::type\r\nlower(const Type& object)\r\n{\r\n    return interval_traits<Type>::lower(object);\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<is_interval<Type>,\r\n                          typename interval_traits<Type>::domain_type>::type\r\nupper(const Type& object)\r\n{\r\n    return interval_traits<Type>::upper(object);\r\n}\r\n\r\n\r\n//- first ----------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename\r\nenable_if< mpl::or_<is_static_right_open<Type>, is_static_closed<Type> >\r\n         , typename interval_traits<Type>::domain_type>::type\r\nfirst(const Type& object)\r\n{\r\n    return lower(object);\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename\r\nenable_if< mpl::and_< mpl::or_<is_static_left_open<Type>, is_static_open<Type> >\r\n                    , is_discrete<typename interval_traits<Type>::domain_type> >\r\n         , typename interval_traits<Type>::domain_type>::type\r\nfirst(const Type& object)\r\n{\r\n    return domain_next<Type>(lower(object));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<is_discrete_interval<Type>,\r\n                          typename interval_traits<Type>::domain_type>::type\r\nfirst(const Type& object)\r\n{\r\n    return is_left_closed(object.bounds()) ?\r\n                                 lower(object) :\r\n               domain_next<Type>(lower(object));\r\n}\r\n\r\n//- last -----------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename\r\nenable_if< mpl::or_<is_static_left_open<Type>, is_static_closed<Type> >\r\n         , typename interval_traits<Type>::domain_type>::type\r\nlast(const Type& object)\r\n{\r\n    return upper(object);\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename\r\nenable_if< mpl::and_< mpl::or_<is_static_right_open<Type>, is_static_open<Type> >\r\n                    , is_discrete<typename interval_traits<Type>::domain_type>  >\r\n         , typename interval_traits<Type>::domain_type>::type\r\nlast(const Type& object)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                 ::is_less_than(upper(object)) ));\r\n    return domain_prior<Type>(upper(object));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<is_discrete_interval<Type>,\r\n                          typename interval_traits<Type>::domain_type>::type\r\nlast(const Type& object)\r\n{\r\n    typedef typename interval_traits<Type>::domain_type    domain_type;\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n    BOOST_ASSERT((numeric_minimum<domain_type, domain_compare, is_numeric<domain_type>::value>\r\n                                 ::is_less_than_or(upper(object), is_right_closed(object.bounds())) ));\r\n    return is_right_closed(object.bounds()) ?\r\n                                  upper(object) :\r\n               domain_prior<Type>(upper(object));\r\n}\r\n\r\n//- last_next ------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename\r\nenable_if< mpl::and_< mpl::or_<is_static_left_open<Type>, is_static_closed<Type> >\r\n                    , is_discrete<typename interval_traits<Type>::domain_type>  >\r\n         , typename interval_traits<Type>::domain_type>::type\r\nlast_next(const Type& object)\r\n{\r\n    return domain_next<Type>(upper(object));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename\r\nenable_if< mpl::and_< mpl::or_<is_static_right_open<Type>, is_static_open<Type> >\r\n                    , is_discrete<typename interval_traits<Type>::domain_type>  >\r\n         , typename interval_traits<Type>::domain_type>::type\r\nlast_next(const Type& object)\r\n{\r\n    //CL typedef typename interval_traits<Type>::domain_type domain_type;\r\n    return upper(object); // NOTE: last_next is implemented to avoid calling pred(object)\r\n}                         // For unsigned integral types this may cause underflow.\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<is_discrete_interval<Type>,\r\n                          typename interval_traits<Type>::domain_type>::type\r\nlast_next(const Type& object)\r\n{\r\n    return is_right_closed(object.bounds()) ?\r\n               domain_next<Type>(upper(object)):\r\n                                 upper(object) ;\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>,\r\n                   typename Type::bounded_domain_type>::type\r\nbounded_lower(const Type& object)\r\n{\r\n    return typename\r\n        Type::bounded_domain_type(lower(object), object.bounds().left());\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>,\r\n                   typename Type::bounded_domain_type>::type\r\nreverse_bounded_lower(const Type& object)\r\n{\r\n    return typename\r\n        Type::bounded_domain_type(lower(object),\r\n                                  object.bounds().reverse_left());\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>,\r\n                   typename Type::bounded_domain_type>::type\r\nbounded_upper(const Type& object)\r\n{\r\n    return typename\r\n        Type::bounded_domain_type(upper(object),\r\n                                  object.bounds().right());\r\n}\r\n\r\ntemplate<class Type>\r\ntypename enable_if<has_dynamic_bounds<Type>,\r\n                   typename Type::bounded_domain_type>::type\r\nreverse_bounded_upper(const Type& object)\r\n{\r\n    return typename\r\n        Type::bounded_domain_type(upper(object),\r\n                                  object.bounds().reverse_right());\r\n}\r\n\r\n//- bounds ---------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename enable_if<has_dynamic_bounds<Type>, interval_bounds>::type\r\nbounds(const Type& object)\r\n{\r\n    return object.bounds();\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename enable_if<has_static_bounds<Type>, interval_bounds>::type\r\nbounds(const Type&)\r\n{\r\n    return interval_bounds(interval_bound_type<Type>::value);\r\n}\r\n\r\n\r\n//==============================================================================\r\n//= Emptieness\r\n//==============================================================================\r\n/** Is the interval empty? */\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, bool>::type\r\nis_empty(const Type& object)\r\n{\r\n    return domain_less_equal<Type>(upper(object), lower(object));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_static_closed<Type>, bool>::type\r\nis_empty(const Type& object)\r\n{\r\n    return domain_less<Type>(upper(object), lower(object));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_static_open<Type>, bool>::type\r\nis_empty(const Type& object)\r\n{\r\n    return domain_less_equal<Type>(upper(object),                   lower(object) )\r\n        || domain_less_equal<Type>(upper(object), domain_next<Type>(lower(object)));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\nis_empty(const Type& object)\r\n{\r\n    if(object.bounds() == interval_bounds::closed())\r\n        return domain_less<Type>(upper(object), lower(object));\r\n    else if(object.bounds() == interval_bounds::open())\r\n        return domain_less_equal<Type>(upper(object),                   lower(object) )\r\n            || domain_less_equal<Type>(upper(object), domain_next<Type>(lower(object)));\r\n    else\r\n        return domain_less_equal<Type>(upper(object), lower(object));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\nis_empty(const Type& object)\r\n{\r\n    return     domain_less<Type>(upper(object), lower(object))\r\n        || (   domain_equal<Type>(upper(object), lower(object))\r\n            && object.bounds() != interval_bounds::closed()    );\r\n}\r\n\r\n//==============================================================================\r\n//= Equivalences and Orderings\r\n//==============================================================================\r\n//- exclusive_less -------------------------------------------------------------\r\n/** Maximal element of <tt>left</tt> is less than the minimal element of\r\n    <tt>right</tt> */\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_asymmetric_interval<Type>, bool>::type\r\nexclusive_less(const Type& left, const Type& right)\r\n{\r\n    return icl::is_empty(left) || icl::is_empty(right)\r\n        || domain_less_equal<Type>(upper(left), lower(right));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\nexclusive_less(const Type& left, const Type& right)\r\n{\r\n    return icl::is_empty(left) || icl::is_empty(right)\r\n        || domain_less<Type>(last(left), first(right));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename boost::\r\nenable_if<has_symmetric_bounds<Type>, bool>::type\r\nexclusive_less(const Type& left, const Type& right)\r\n{\r\n    return icl::is_empty(left) || icl::is_empty(right)\r\n        || domain_less<Type>(last(left), first(right));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\nexclusive_less(const Type& left, const Type& right)\r\n{\r\n    return     icl::is_empty(left) || icl::is_empty(right)\r\n        ||     domain_less<Type>(upper(left), lower(right))\r\n        || (   domain_equal<Type>(upper(left), lower(right))\r\n            && inner_bounds(left,right) != interval_bounds::open() );\r\n}\r\n\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_static_bounds<Type>, bool>::type\r\nlower_less(const Type& left, const Type& right)\r\n{\r\n    return domain_less<Type>(lower(left), lower(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\nlower_less(const Type& left, const Type& right)\r\n{\r\n    return domain_less<Type>(first(left), first(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\nlower_less(const Type& left, const Type& right)\r\n{\r\n    if(left_bounds(left,right) == interval_bounds::right_open())  //'[(' == 10\r\n        return domain_less_equal<Type>(lower(left), lower(right));\r\n    else\r\n        return domain_less<Type>(lower(left), lower(right));\r\n}\r\n\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_static_bounds<Type>, bool>::type\r\nupper_less(const Type& left, const Type& right)\r\n{\r\n    return domain_less<Type>(upper(left), upper(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\nupper_less(const Type& left, const Type& right)\r\n{\r\n    return domain_less<Type>(last(left), last(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\nupper_less(const Type& left, const Type& right)\r\n{\r\n    if(right_bounds(left,right) == interval_bounds::left_open())\r\n        return domain_less_equal<Type>(upper(left), upper(right));\r\n    else\r\n        return domain_less<Type>(upper(left), upper(right));\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>,\r\n                          typename Type::bounded_domain_type   >::type\r\nlower_min(const Type& left, const Type& right)\r\n{\r\n    return lower_less(left, right) ? bounded_lower(left) : bounded_lower(right);\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>,\r\n                          typename Type::bounded_domain_type   >::type\r\nlower_max(const Type& left, const Type& right)\r\n{\r\n    return lower_less(left, right) ? bounded_lower(right) : bounded_lower(left);\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>,\r\n                          typename Type::bounded_domain_type   >::type\r\nupper_max(const Type& left, const Type& right)\r\n{\r\n    return upper_less(left, right) ? bounded_upper(right) : bounded_upper(left);\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>,\r\n                          typename Type::bounded_domain_type   >::type\r\nupper_min(const Type& left, const Type& right)\r\n{\r\n    return upper_less(left, right) ? bounded_upper(left) : bounded_upper(right);\r\n}\r\n\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, bool>::type\r\nlower_equal(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(lower(left), lower(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_symmetric_bounds<Type>, bool>::type\r\nlower_equal(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(first(left), first(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\nlower_equal(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(first(left), first(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\nlower_equal(const Type& left, const Type& right)\r\n{\r\n    return (left.bounds().left()==right.bounds().left())\r\n        && domain_equal<Type>(lower(left), lower(right));\r\n}\r\n\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, bool>::type\r\nupper_equal(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(upper(left), upper(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_symmetric_bounds<Type>, bool>::type\r\nupper_equal(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(last(left), last(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\nupper_equal(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(last(left), last(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\nupper_equal(const Type& left, const Type& right)\r\n{\r\n    return (left.bounds().right()==right.bounds().right())\r\n        && domain_equal<Type>(upper(left), upper(right));\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_interval<Type>, bool>::type\r\nlower_less_equal(const Type& left, const Type& right)\r\n{\r\n    return lower_less(left,right) || lower_equal(left,right);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_interval<Type>, bool>::type\r\nupper_less_equal(const Type& left, const Type& right)\r\n{\r\n    return upper_less(left,right) || upper_equal(left,right);\r\n}\r\n\r\n//==============================================================================\r\n//= Orderings, containedness (non empty)\r\n//==============================================================================\r\nnamespace non_empty\r\n{\r\n\r\n    template<class Type>\r\n    inline typename boost::enable_if<is_asymmetric_interval<Type>, bool>::type\r\n    exclusive_less(const Type& left, const Type& right)\r\n    {\r\n        BOOST_ASSERT(!(icl::is_empty(left) || icl::is_empty(right)));\r\n        return domain_less_equal<Type>(upper(left), lower(right));\r\n    }\r\n\r\n    template<class Type>\r\n    inline typename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\n    exclusive_less(const Type& left, const Type& right)\r\n    {\r\n        BOOST_ASSERT(!(icl::is_empty(left) || icl::is_empty(right)));\r\n        return domain_less<Type>(last(left), first(right));\r\n    }\r\n\r\n    template<class Type>\r\n    inline typename boost::\r\n    enable_if<has_symmetric_bounds<Type>, bool>::type\r\n    exclusive_less(const Type& left, const Type& right)\r\n    {\r\n        BOOST_ASSERT(!(icl::is_empty(left) || icl::is_empty(right)));\r\n        return domain_less<Type>(last(left), first(right));\r\n    }\r\n\r\n    template<class Type>\r\n    inline typename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\n    exclusive_less(const Type& left, const Type& right)\r\n    {\r\n        BOOST_ASSERT(!(icl::is_empty(left) || icl::is_empty(right)));\r\n        return     domain_less <Type>(upper(left), lower(right))\r\n            || (   domain_equal<Type>(upper(left), lower(right))\r\n                && inner_bounds(left,right) != interval_bounds::open() );\r\n    }\r\n\r\n    template<class Type>\r\n    inline typename boost::enable_if<is_interval<Type>, bool>::type\r\n    contains(const Type& super, const Type& sub)\r\n    {\r\n        return lower_less_equal(super,sub) && upper_less_equal(sub,super);\r\n    }\r\n\r\n} //namespace non_empty\r\n\r\n//- contains -------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_interval<Type>, bool>::type\r\ncontains(const Type& super, const Type& sub)\r\n{\r\n    return icl::is_empty(sub) || non_empty::contains(super, sub);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_static<Type>, bool>::type\r\ncontains(const Type& super, const typename interval_traits<Type>::domain_type& element)\r\n{\r\n    return domain_less_equal<Type>(icl::first(super), element                  )\r\n        && domain_less_equal<Type>(                   element, icl::last(super));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_left_open<Type>, bool>::type\r\ncontains(const Type& super, const typename interval_traits<Type>::domain_type& element)\r\n{\r\n    return domain_less      <Type>(icl::lower(super), element                   )\r\n        && domain_less_equal<Type>(                   element, icl::upper(super));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_right_open<Type>, bool>::type\r\ncontains(const Type& super, const typename interval_traits<Type>::domain_type& element)\r\n{\r\n    return domain_less_equal<Type>(icl::lower(super), element                   )\r\n        && domain_less      <Type>(                   element, icl::upper(super));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, bool>::type\r\ncontains(const Type& super, const typename interval_traits<Type>::domain_type& element)\r\n{\r\n    return\r\n        (is_left_closed(super.bounds())\r\n            ? domain_less_equal<Type>(lower(super), element)\r\n            :       domain_less<Type>(lower(super), element))\r\n    &&\r\n        (is_right_closed(super.bounds())\r\n            ? domain_less_equal<Type>(element, upper(super))\r\n            :       domain_less<Type>(element, upper(super)));\r\n}\r\n\r\n//- within ---------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_interval<Type>, bool>::type\r\nwithin(const Type& sub, const Type& super)\r\n{\r\n    return contains(super,sub);\r\n}\r\n\r\n//- operator == ----------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_interval<Type>, bool>::type\r\noperator == (const Type& left, const Type& right)\r\n{\r\n    return (icl::is_empty(left) && icl::is_empty(right))\r\n        || (lower_equal(left,right) && upper_equal(left,right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_interval<Type>, bool>::type\r\noperator != (const Type& left, const Type& right)\r\n{\r\n    return !(left == right);\r\n}\r\n\r\n//- operator < -----------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_interval<Type>, bool>::type\r\noperator < (const Type& left, const Type& right)\r\n{\r\n    if(icl::is_empty(left))\r\n        return !icl::is_empty(right);\r\n    else\r\n        return lower_less(left,right)\r\n            || (lower_equal(left,right) && upper_less(left,right));\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_interval<Type>, bool>::type\r\noperator > (const Type& left, const Type& right)\r\n{\r\n    return right < left;\r\n}\r\n\r\n\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, bool>::type\r\ntouches(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(upper(left), lower(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_symmetric_bounds<Type>, bool>::type\r\ntouches(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(last_next(left), first(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_interval<Type>, bool>::type\r\ntouches(const Type& left, const Type& right)\r\n{\r\n    return domain_equal<Type>(domain_next<Type>(last(left)), first(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_interval<Type>, bool>::type\r\ntouches(const Type& left, const Type& right)\r\n{\r\n    return is_complementary(inner_bounds(left,right))\r\n        && domain_equal<Type>(upper(left), lower(right));\r\n}\r\n\r\n\r\n//==============================================================================\r\n//= Size\r\n//==============================================================================\r\n//- cardinality ----------------------------------------------------------------\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_interval<Type>,\r\n    typename size_type_of<interval_traits<Type> >::type>::type\r\ncardinality(const Type& object)\r\n{\r\n    typedef typename size_type_of<interval_traits<Type> >::type SizeT;\r\n    if(icl::is_empty(object))\r\n        return icl::identity_element<SizeT>::value();\r\n    else if(   object.bounds() == interval_bounds::closed()\r\n            && domain_equal<Type>(lower(object), upper(object)))\r\n        return icl::unit_element<SizeT>::value();\r\n    else\r\n        return icl::infinity<SizeT>::value();\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_interval<Type>,\r\n    typename size_type_of<interval_traits<Type> >::type>::type\r\ncardinality(const Type& object)\r\n{\r\n    typedef typename size_type_of<interval_traits<Type> >::type SizeT;\r\n    return icl::is_empty(object) ? identity_element<SizeT>::value()\r\n                                 : static_cast<SizeT>(last_next(object) - first(object));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_asymmetric<Type>,\r\n    typename size_type_of<interval_traits<Type> >::type>::type\r\ncardinality(const Type& object)\r\n{\r\n    typedef typename size_type_of<interval_traits<Type> >::type SizeT;\r\n    if(icl::is_empty(object))\r\n        return icl::identity_element<SizeT>::value();\r\n    else\r\n        return icl::infinity<SizeT>::value();\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_asymmetric<Type>,\r\n    typename size_type_of<interval_traits<Type> >::type>::type\r\ncardinality(const Type& object)\r\n{\r\n    typedef typename size_type_of<interval_traits<Type> >::type SizeT;\r\n    return icl::is_empty(object) ? identity_element<SizeT>::value()\r\n                                 : static_cast<SizeT>(last_next(object) - first(object));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_symmetric_bounds<Type>,\r\n    typename size_type_of<interval_traits<Type> >::type>::type\r\ncardinality(const Type& object)\r\n{\r\n    typedef typename size_type_of<interval_traits<Type> >::type SizeT;\r\n    return icl::is_empty(object) ? identity_element<SizeT>::value()\r\n                                 : static_cast<SizeT>(last_next(object) - first(object));\r\n}\r\n\r\n\r\n\r\n//- size -----------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename enable_if<is_interval<Type>,\r\n    typename size_type_of<interval_traits<Type> >::type>::type\r\nsize(const Type& object)\r\n{\r\n    return cardinality(object);\r\n}\r\n\r\n//- length ---------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_continuous_interval<Type>,\r\n    typename difference_type_of<interval_traits<Type> >::type>::type\r\nlength(const Type& object)\r\n{\r\n    typedef typename difference_type_of<interval_traits<Type> >::type DiffT;\r\n    return icl::is_empty(object) ? identity_element<DiffT>::value()\r\n                                 : upper(object) - lower(object);\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_discrete_interval<Type>,\r\n    typename difference_type_of<interval_traits<Type> >::type>::type\r\nlength(const Type& object)\r\n{\r\n    typedef typename difference_type_of<interval_traits<Type> >::type DiffT;\r\n    return icl::is_empty(object) ? identity_element<DiffT>::value()\r\n                                 : last_next(object) - first(object);\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_continuous_asymmetric<Type>,\r\n    typename difference_type_of<interval_traits<Type> >::type>::type\r\nlength(const Type& object)\r\n{\r\n    typedef typename difference_type_of<interval_traits<Type> >::type DiffT;\r\n    return icl::is_empty(object) ? identity_element<DiffT>::value()\r\n                                 : upper(object) - lower(object);\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_discrete_static<Type>,\r\n    typename difference_type_of<interval_traits<Type> >::type>::type\r\nlength(const Type& object)\r\n{\r\n    typedef typename difference_type_of<interval_traits<Type> >::type DiffT;\r\n    return icl::is_empty(object) ? identity_element<DiffT>::value()\r\n                                 : last_next(object) - first(object);\r\n}\r\n\r\n//- iterative_size -------------------------------------------------------------\r\ntemplate<class Type>\r\ninline typename enable_if<is_interval<Type>,\r\n    typename size_type_of<interval_traits<Type> >::type>::type\r\niterative_size(const Type&)\r\n{\r\n    return 2;\r\n}\r\n\r\n\r\n//==============================================================================\r\n//= Addition\r\n//==============================================================================\r\n//- hull -----------------------------------------------------------------------\r\n/** \\c hull returns the smallest interval containing \\c left and \\c right. */\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_static_bounds<Type>, Type>::type\r\nhull(Type left, const Type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n\r\n    if(icl::is_empty(right))\r\n        return left;\r\n    else if(icl::is_empty(left))\r\n        return right;\r\n\r\n    return\r\n        construct<Type>\r\n        (\r\n            (std::min)(lower(left), lower(right), domain_compare()),\r\n            (std::max)(upper(left), upper(right), domain_compare())\r\n        );\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, Type>::type\r\nhull(Type left, const Type& right)\r\n{\r\n    if(icl::is_empty(right))\r\n        return left;\r\n    else if(icl::is_empty(left))\r\n        return right;\r\n\r\n    return  dynamic_interval_traits<Type>::construct_bounded\r\n            (\r\n                lower_min(left, right),\r\n                upper_max(left, right)\r\n            );\r\n}\r\n\r\n//==============================================================================\r\n//= Subtraction\r\n//==============================================================================\r\n//- left_subtract --------------------------------------------------------------\r\n/** subtract \\c left_minuend from the \\c right interval on it's left side.\r\n    Return the difference: The part of \\c right right of \\c left_minuend.\r\n\\code\r\nright_over = right - left_minuend; //on the left.\r\n...      d) : right\r\n... c)      : left_minuend\r\n     [c  d) : right_over\r\n\\endcode\r\n*/\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, Type>::type\r\nleft_subtract(Type right, const Type& left_minuend)\r\n{\r\n    if(exclusive_less(left_minuend, right))\r\n        return right;\r\n\r\n    return construct<Type>(upper(left_minuend), upper(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_static_closed<Type>, Type>::type\r\nleft_subtract(Type right, const Type& left_minuend)\r\n{\r\n    if(exclusive_less(left_minuend, right))\r\n        return right;\r\n    else if(upper_less_equal(right, left_minuend))\r\n        return identity_element<Type>::value();\r\n\r\n    return construct<Type>(domain_next<Type>(upper(left_minuend)), upper(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_static_open<Type>, Type>::type\r\nleft_subtract(Type right, const Type& left_minuend)\r\n{\r\n    if(exclusive_less(left_minuend, right))\r\n        return right;\r\n\r\n    return construct<Type>(domain_prior<Type>(upper(left_minuend)), upper(right));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, Type>::type\r\nleft_subtract(Type right, const Type& left_minuend)\r\n{\r\n    if(exclusive_less(left_minuend, right))\r\n        return right;\r\n    return  dynamic_interval_traits<Type>::construct_bounded\r\n            ( reverse_bounded_upper(left_minuend), bounded_upper(right) );\r\n}\r\n\r\n\r\n//- right_subtract -------------------------------------------------------------\r\n/** subtract \\c right_minuend from the \\c left interval on it's right side.\r\n    Return the difference: The part of \\c left left of \\c right_minuend.\r\n\\code\r\nleft_over = left - right_minuend; //on the right side.\r\n[a      ...  : left\r\n     [b ...  : right_minuend\r\n[a  b)       : left_over\r\n\\endcode\r\n*/\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, Type>::type\r\nright_subtract(Type left, const Type& right_minuend)\r\n{\r\n    if(exclusive_less(left, right_minuend))\r\n        return left;\r\n    return construct<Type>(lower(left), lower(right_minuend));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_static_closed<Type>, Type>::type\r\nright_subtract(Type left, const Type& right_minuend)\r\n{\r\n    if(exclusive_less(left, right_minuend))\r\n        return left;\r\n    else if(lower_less_equal(right_minuend, left))\r\n        return identity_element<Type>::value();\r\n\r\n    return construct<Type>(lower(left), domain_prior<Type>(lower(right_minuend)));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_static_open<Type>, Type>::type\r\nright_subtract(Type left, const Type& right_minuend)\r\n{\r\n    if(exclusive_less(left, right_minuend))\r\n        return left;\r\n\r\n    return construct<Type>(lower(left), domain_next<Type>(lower(right_minuend)));\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, Type>::type\r\nright_subtract(Type left, const Type& right_minuend)\r\n{\r\n    if(exclusive_less(left, right_minuend))\r\n        return left;\r\n\r\n    return  dynamic_interval_traits<Type>::construct_bounded\r\n            ( bounded_lower(left), reverse_bounded_lower(right_minuend) );\r\n}\r\n\r\n//==============================================================================\r\n//= Intersection\r\n//==============================================================================\r\n//- operator & -----------------------------------------------------------------\r\n/** Returns the intersection of \\c left and \\c right interval. */\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, Type>::type\r\noperator & (Type left, const Type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n\r\n    if(icl::is_empty(left) || icl::is_empty(right))\r\n        return identity_element<Type>::value();\r\n    else\r\n        return\r\n        construct<Type>\r\n        (\r\n            (std::max)(icl::lower(left), icl::lower(right), domain_compare()),\r\n            (std::min)(icl::upper(left), icl::upper(right), domain_compare())\r\n        );\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_symmetric_bounds<Type>, Type>::type\r\noperator & (Type left, const Type& right)\r\n{\r\n    typedef typename interval_traits<Type>::domain_compare domain_compare;\r\n\r\n    if(icl::is_empty(left) || icl::is_empty(right))\r\n        return identity_element<Type>::value();\r\n    else\r\n        return\r\n        construct<Type>\r\n        (\r\n            (std::max)(icl::lower(left), icl::lower(right), domain_compare()),\r\n            (std::min)(icl::upper(left), icl::upper(right), domain_compare())\r\n        );\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, Type>::type\r\noperator & (Type left, const Type& right)\r\n{\r\n    if(icl::is_empty(left) || icl::is_empty(right))\r\n        return identity_element<Type>::value();\r\n    else\r\n        return  dynamic_interval_traits<Type>::construct_bounded\r\n                (\r\n                    lower_max(left, right),\r\n                    upper_min(left, right)\r\n                );\r\n}\r\n\r\n\r\n//- intersects -----------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_interval<Type>, bool>::type\r\nintersects(const Type& left, const Type& right)\r\n{\r\n    return !(   icl::is_empty(left) || icl::is_empty(right)\r\n             || exclusive_less(left,right) || exclusive_less(right,left));\r\n}\r\n\r\n//- disjoint -------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_interval<Type>, bool>::type\r\ndisjoint(const Type& left, const Type& right)\r\n{\r\n    return icl::is_empty(left) || icl::is_empty(right)\r\n        || exclusive_less(left,right) || exclusive_less(right,left);\r\n}\r\n\r\n//==============================================================================\r\n//= Complement\r\n//==============================================================================\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_asymmetric_interval<Type>, Type>::type\r\ninner_complement(const Type& left, const Type& right)\r\n{\r\n    if(icl::is_empty(left) || icl::is_empty(right))\r\n        return  identity_element<Type>::value();\r\n    else if(exclusive_less(left, right))\r\n        return construct<Type>(upper(left), lower(right));\r\n    else if(exclusive_less(right, left))\r\n        return construct<Type>(upper(right), lower(left));\r\n    else\r\n        return identity_element<Type>::value();\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_static_closed<Type>, Type>::type\r\ninner_complement(const Type& left, const Type& right)\r\n{\r\n    if(icl::is_empty(left) || icl::is_empty(right))\r\n        return  identity_element<Type>::value();\r\n    else if(exclusive_less(left, right))\r\n        return construct<Type>(domain_next<Type>(upper(left)), domain_prior<Type>(lower(right)));\r\n    else if(exclusive_less(right, left))\r\n        return construct<Type>(domain_next<Type>(upper(right)), domain_prior<Type>(lower(left)));\r\n    else\r\n        return identity_element<Type>::value();\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<is_discrete_static_open<Type>, Type>::type\r\ninner_complement(const Type& left, const Type& right)\r\n{\r\n    if(icl::is_empty(left) || icl::is_empty(right))\r\n        return  identity_element<Type>::value();\r\n    else if(exclusive_less(left, right))\r\n        return construct<Type>(last(left), first(right));\r\n    else if(exclusive_less(right, left))\r\n        return construct<Type>(last(right), first(left));\r\n    else\r\n        return identity_element<Type>::value();\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, Type>::type\r\ninner_complement(const Type& left, const Type& right)\r\n{\r\n    if(icl::is_empty(left) || icl::is_empty(right))\r\n        return  identity_element<Type>::value();\r\n    else if(exclusive_less(left, right))\r\n        return right_subtract(left_subtract(hull(left, right), left), right);\r\n    else if(exclusive_less(right, left))\r\n        return right_subtract(left_subtract(hull(right, left), right), left);\r\n    else\r\n        return identity_element<Type>::value();\r\n}\r\n\r\ntemplate<class Type>\r\ninline typename boost::enable_if<is_interval<Type>, Type>::type\r\nbetween(const Type& left, const Type& right)\r\n{\r\n    return inner_complement(left, right);\r\n}\r\n\r\n\r\n\r\n//==============================================================================\r\n//= Distance\r\n//==============================================================================\r\ntemplate<class Type>\r\ntypename boost::\r\nenable_if< mpl::and_< is_interval<Type>\r\n                    , has_difference<typename interval_traits<Type>::domain_type>\r\n                    , is_discrete<typename interval_traits<Type>::domain_type>\r\n                    >\r\n         , typename difference_type_of<interval_traits<Type> >::type>::type\r\ndistance(const Type& x1, const Type& x2)\r\n{\r\n    typedef typename difference_type_of<interval_traits<Type> >::type difference_type;\r\n\r\n    if(icl::is_empty(x1) || icl::is_empty(x2))\r\n        return icl::identity_element<difference_type>::value();\r\n    else if(domain_less<Type>(last(x1), first(x2)))\r\n        return static_cast<difference_type>(icl::pred(first(x2) - last(x1)));\r\n    else if(domain_less<Type>(last(x2), first(x1)))\r\n        return static_cast<difference_type>(icl::pred(first(x1) - last(x2)));\r\n    else\r\n        return icl::identity_element<difference_type>::value();\r\n}\r\n\r\ntemplate<class Type>\r\ntypename boost::\r\nenable_if< mpl::and_< is_interval<Type>\r\n                    , has_difference<typename interval_traits<Type>::domain_type>\r\n                    , is_continuous<typename interval_traits<Type>::domain_type>\r\n                    >\r\n         , typename difference_type_of<interval_traits<Type> >::type>::type\r\ndistance(const Type& x1, const Type& x2)\r\n{\r\n    typedef typename difference_type_of<interval_traits<Type> >::type DiffT;\r\n\r\n    if(icl::is_empty(x1) || icl::is_empty(x2))\r\n        return icl::identity_element<DiffT>::value();\r\n    else if(domain_less<Type>(upper(x1), lower(x2)))\r\n        return lower(x2) - upper(x1);\r\n    else if(domain_less<Type>(upper(x2), lower(x1)))\r\n        return lower(x1) - upper(x2);\r\n    else\r\n        return icl::identity_element<DiffT>::value();\r\n}\r\n\r\n//==============================================================================\r\n//= Streaming, representation\r\n//==============================================================================\r\ntemplate<class Type>\r\ntypename boost::\r\n    enable_if< mpl::or_< is_static_left_open<Type>\r\n                       , is_static_open<Type>    >, std::string>::type\r\nleft_bracket(const Type&) { return \"(\"; }\r\n\r\ntemplate<class Type>\r\ntypename boost::\r\n    enable_if< mpl::or_< is_static_right_open<Type>\r\n                       , is_static_closed<Type>   >, std::string>::type\r\nleft_bracket(const Type&) { return \"[\"; }\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, std::string>::type\r\nleft_bracket(const Type& object)\r\n{\r\n    return left_bracket(object.bounds());\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class Type>\r\ntypename boost::\r\n    enable_if< mpl::or_< is_static_right_open<Type>\r\n                       , is_static_open<Type>     >, std::string>::type\r\nright_bracket(const Type&) { return \")\"; }\r\n\r\ntemplate<class Type>\r\ntypename boost::\r\n    enable_if< mpl::or_< is_static_left_open<Type>\r\n                       , is_static_closed<Type>    >, std::string>::type\r\nright_bracket(const Type&) { return \"]\"; }\r\n\r\ntemplate<class Type>\r\ntypename boost::enable_if<has_dynamic_bounds<Type>, std::string>::type\r\nright_bracket(const Type& object)\r\n{\r\n    return right_bracket(object.bounds());\r\n}\r\n\r\n//------------------------------------------------------------------------------\r\ntemplate<class CharType, class CharTraits, class Type>\r\ntypename boost::enable_if<is_interval<Type>,\r\n                          std::basic_ostream<CharType, CharTraits> >::type&\r\noperator << (std::basic_ostream<CharType, CharTraits> &stream, Type const& object)\r\n{\r\n    if(boost::icl::is_empty(object))\r\n        return stream << left_bracket<Type>(object) << right_bracket<Type>(object);\r\n    else\r\n        return stream << left_bracket<Type>(object)\r\n                      << interval_traits<Type>::lower(object)\r\n                      << \",\"\r\n                      << interval_traits<Type>::upper(object)\r\n                      << right_bracket<Type>(object) ;\r\n}\r\n\r\n}} // namespace icl boost\r\n\r\n#endif\r\n", "meta": {"hexsha": "fd6966d71535d466d38fcd229d5daa5e6e05adad", "size": 54667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/icl/concept/interval.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/icl/concept/interval.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/icl/concept/interval.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.9871447903, "max_line_length": 104, "alphanum_fraction": 0.6148133243, "num_tokens": 10663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512971193602087, "lm_q2_score": 0.01691490995255679, "lm_q1q2_score": 0.004653794302670682}}
{"text": "// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers\n// Copyright (c) 2016-2018  zawy12\n// Copyright (c) 2016-2018, The Karbowanec developers\n// Copyright (c) 2018-2020, The Qwertycoin Group.\n//\n// This file is part of Qwertycoin.\n//\n// Qwertycoin 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// Qwertycoin 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 Qwertycoin.  If not, see <http://www.gnu.org/licenses/>.\n\n#include <cctype>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <Common/Base58.h>\n#include <Common/int-util.h>\n#include <Common/StringTools.h>\n#include <CryptoNoteCore/Account.h>\n#include <CryptoNoteCore/CryptoNoteBasicImpl.h>\n#include <CryptoNoteCore/CryptoNoteFormatUtils.h>\n#include <CryptoNoteCore/CryptoNoteTools.h>\n#include <CryptoNoteCore/Currency.h>\n#include <CryptoNoteCore/TransactionExtra.h>\n#include <CryptoNoteCore/UpgradeDetector.h>\n#include <Global/Constants.h>\n\n#undef ERROR\n\nusing namespace Logging;\nusing namespace Common;\nusing namespace Qwertycoin;\n\nnamespace CryptoNote {\n\nbool Currency::init()\n{\n    if (!generateGenesisBlock()) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to generate genesis block\";\n        return false;\n    }\n\n    if (!get_block_hash(m_genesisBlock, m_genesisBlockHash)) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to get genesis block hash\";\n        return false;\n    }\n\n    if (isTestnet()) {\n        m_upgradeHeightV2 = 10;\n        m_upgradeHeightV3 = 60;\n        m_upgradeHeightV4 = 70;\n        m_upgradeHeightV5 = 80;\n        m_upgradeHeightV6 = 100;\n        m_governancePercent = 10;\n        m_governanceHeightStart = 1;\n        m_governanceHeightEnd = 100;\n        m_blocksFileName = \"testnet_\" + m_blocksFileName;\n        m_blocksCacheFileName = \"testnet_\" + m_blocksCacheFileName;\n        m_blockIndexesFileName = \"testnet_\" + m_blockIndexesFileName;\n        m_txPoolFileName = \"testnet_\" + m_txPoolFileName;\n        m_blockchainIndicesFileName = \"testnet_\" + m_blockchainIndicesFileName;\n    }\n\n    return true;\n}\n\nbool Currency::generateGenesisBlock()\n{\n    m_genesisBlock = boost::value_initialized<Block>();\n\n    // Hard code coinbase tx in genesis block, because \"tru\" generating tx use random,\n    // but genesis should be always the same\n    std::string genesisCoinbaseTxHex = GENESIS_COINBASE_TX_HEX;\n    BinaryArray minerTxBlob;\n\n    bool r = fromHex(genesisCoinbaseTxHex, minerTxBlob)\n             && fromBinaryArray(m_genesisBlock.baseTransaction, minerTxBlob);\n\n    if (!r) {\n        logger(ERROR, BRIGHT_RED) << \"failed to parse coinbase tx from hard coded blob\";\n        return false;\n    }\n\n    m_genesisBlock.majorVersion = BLOCK_MAJOR_VERSION_1;\n    m_genesisBlock.minorVersion = BLOCK_MINOR_VERSION_0;\n    m_genesisBlock.timestamp = 0;\n    m_genesisBlock.nonce = 70;\n    if (m_testnet) {\n        ++m_genesisBlock.nonce;\n    }\n\n    //miner::find_nonce_for_given_block(bl, 1, 0);\n\n    return true;\n}\n\nsize_t Currency::blockGrantedFullRewardZoneByBlockVersion(uint8_t blockMajorVersion) const\n{\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_4) {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2;\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_3) {\n        return m_blockGrantedFullRewardZone;\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_2) {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2;\n    } else {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V1;\n    }\n}\n\nuint32_t Currency::upgradeHeight(uint8_t majorVersion) const\n{\n    if (majorVersion == BLOCK_MAJOR_VERSION_6) {\n        return m_upgradeHeightV6;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_5) {\n        return m_upgradeHeightV5;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_4) {\n        return m_upgradeHeightV4;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_2) {\n        return m_upgradeHeightV2;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_3) {\n        return m_upgradeHeightV3;\n    } else {\n        return static_cast<uint32_t>(-1);\n    }\n}\n\nbool Currency::getBlockReward(\n    uint8_t blockMajorVersion,\n    size_t medianSize,\n    size_t currentBlockSize,\n    uint64_t alreadyGeneratedCoins,\n    uint64_t fee,\n    uint64_t &reward,\n    int64_t &emissionChange,\n    uint32_t height,\n    uint64_t blockTarget) const\n{\n    assert(alreadyGeneratedCoins <= m_moneySupply);\n    assert(m_emissionSpeedFactor > 0 && m_emissionSpeedFactor <= 8 * sizeof(uint64_t));\n\n    // Tail emission\n\n    uint64_t baseReward = (m_moneySupply - alreadyGeneratedCoins) >> m_emissionSpeedFactor;\n    if (alreadyGeneratedCoins + CryptoNote::parameters::TAIL_EMISSION_REWARD >= m_moneySupply\n        || baseReward < CryptoNote::parameters::TAIL_EMISSION_REWARD) {\n        baseReward = CryptoNote::parameters::TAIL_EMISSION_REWARD;\n    }\n\n    size_t blockGrantedFullRewardZone = blockGrantedFullRewardZoneByBlockVersion(blockMajorVersion);\n    medianSize = std::max(medianSize, blockGrantedFullRewardZone);\n    if (currentBlockSize > medianSize * UINT64_C(2)) {\n        logger(TRACE)\n            << \"Block cumulative size is too big: \"\n            << currentBlockSize\n            << \", expected less than \"\n            << medianSize * UINT64_C(2);\n        return false;\n    }\n\n    uint64_t penalizedBaseReward = getPenalizedAmount(baseReward, medianSize, currentBlockSize);\n    uint64_t penalizedFee = fee;\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2 || cryptonoteCoinVersion() == 1) {\n        penalizedFee = getPenalizedAmount(fee, medianSize, currentBlockSize);\n    }\n\n    double consistency = 1.0;\n    if (height >= CryptoNote::parameters::UPGRADE_HEIGHT_REWARD_SCHEME && difficultyTarget() != 0) {\n        // blockTarget is (Timestamp of New Block - Timestamp of Previous Block)\n        consistency = blockTarget / difficultyTarget();\n\n        // consistency range is 0..2\n        consistency = std::max<double>(consistency, 0.0);\n        consistency = std::min<double>(consistency, 2.0);\n    }\n\n    double penalizedReward = static_cast<double>(penalizedBaseReward + penalizedFee);\n\n    emissionChange = penalizedBaseReward - (fee - penalizedFee);\n    reward = static_cast<uint64_t>(penalizedReward * consistency);\n\n    return true;\n}\n\nsize_t Currency::maxBlockCumulativeSize(uint64_t height) const\n{\n    assert(height <= std::numeric_limits<uint64_t>::max() / m_maxBlockSizeGrowthSpeedNumerator);\n\n    size_t maxSize =\n        static_cast<size_t>(m_maxBlockSizeInitial\n        + (height * m_maxBlockSizeGrowthSpeedNumerator) / m_maxBlockSizeGrowthSpeedDenominator);\n\n    assert(maxSize >= m_maxBlockSizeInitial);\n\n    return maxSize;\n}\n\nbool Currency::isGovernanceEnabled(uint32_t height) const\n{\n    if (height >= m_governanceHeightStart && height <= m_governanceHeightEnd) {\n        return true;\n    }\n    else {\n        return false;\n    }\n}\n\nuint64_t Currency::getGovernanceReward(uint64_t base_reward) const\n{\n    // minimum is 1% to avoid a zero amount and maximum is 50%\n    uint16_t percent = (m_governancePercent < 1) ? 1 : (m_governancePercent > 50) ? 50 : m_governancePercent;\n    return (uint64_t)(base_reward * (percent * 0.01));\n}\n\nbool Currency::getGovernanceAddressAndKey(AccountKeys& governanceKeys) const\n{\n    std::string address       = GOVERNANCE_WALLET_ADDRESS;\n    std::string viewSecretkey = GOVERNANCE_VIEW_SECRET_KEY;\n\n    AccountPublicAddress governanceAddress = boost::value_initialized<AccountPublicAddress>();\n    if (!parseAccountAddressString(address, governanceAddress)) {\n        logger(Logging::ERROR)\n            << \"Failed to parse governance wallet address (\"\n            << address\n            << \"), \"\n            << \"Check /lib/Global/CryptoNoteConfig.h\";\n        return false;\n    }\n\n    Crypto::SecretKey governanceViewSecretKey;\n    if (!Common::podFromHex(viewSecretkey, governanceViewSecretKey)) {\n        logger(Logging::ERROR)\n            << \"Failed to parse governance view secret key\"\n            << \"Check /lib/Global/CryptoNoteConfig.h\";\n        return false;\n    }\n\n    governanceKeys.address = governanceAddress;\n    governanceKeys.viewSecretKey = governanceViewSecretKey;\n\n    return true;\n}\n\nbool Currency::constructMinerTx(\n    uint8_t blockMajorVersion,\n    uint32_t height,\n    size_t medianSize,\n    uint64_t alreadyGeneratedCoins,\n    size_t currentBlockSize,\n    uint64_t fee,\n    const AccountPublicAddress &minerAddress,\n    Transaction &tx,\n    const BinaryArray &extraNonce /* = BinaryArray()*/,\n    size_t maxOuts /* = 1*/) const\n{\n    tx.inputs.clear();\n    tx.outputs.clear();\n    tx.extra.clear();\n\n    KeyPair txkey = generateKeyPair();\n    addTransactionPublicKeyToExtra(tx.extra, txkey.publicKey);\n    if (!extraNonce.empty()) {\n        if (!addExtraNonceToTransactionExtra(tx.extra, extraNonce)) {\n            return false;\n        }\n    }\n\n    BaseInput in;\n    in.blockIndex = height;\n\n    uint64_t governanceReward = 0;\n    uint64_t totalRewardWGR = 0; //totalRewardWithoutGovernanceReward\n\n    uint64_t blockReward;\n    int64_t emissionChange;\n\n    if (!getBlockReward(\n            blockMajorVersion,\n            medianSize,\n            currentBlockSize,\n            alreadyGeneratedCoins,\n            fee,\n            blockReward,\n            emissionChange,\n            height,\n            difficultyTarget())\n        ) {\n        logger(INFO) << \"Block is too big\";\n        return false;\n    }\n\n    totalRewardWGR = blockReward;\n\n    // If Governance Fee blockReward is decreased by GOVERNANCE_PERCENT_FEE\n    bool enableGovernance = isGovernanceEnabled(height);\n\n    if (enableGovernance) {\n        governanceReward = getGovernanceReward(blockReward);\n\n        if (alreadyGeneratedCoins != 0) {\n            blockReward -= governanceReward;\n            totalRewardWGR  = blockReward + governanceReward;\n        }\n    }\n\n    std::vector<uint64_t> outAmounts;\n    decompose_amount_into_digits(\n        blockReward,\n        UINT64_C(0),\n        [&outAmounts](uint64_t a_chunk) { outAmounts.push_back(a_chunk); },\n        [&outAmounts](uint64_t a_dust) { outAmounts.push_back(a_dust); }\n    );\n\n    if (maxOuts < 1) {\n        logger(ERROR, BRIGHT_RED) << \"max_out must be non-zero\";\n        return false;\n    }\n    while (maxOuts < outAmounts.size()) {\n        outAmounts[outAmounts.size() - 2] += outAmounts.back();\n        outAmounts.resize(outAmounts.size() - 1);\n    }\n\n    uint64_t summaryAmounts = 0;\n    for (size_t no = 0; no < outAmounts.size(); no++) {\n        Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();\n        Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();\n\n        bool r = Crypto::generate_key_derivation(\n            minerAddress.viewPublicKey,\n            txkey.secretKey,\n            derivation\n        );\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to generate_key_derivation(\"\n                << minerAddress.viewPublicKey\n                << \", \"\n                << txkey.secretKey\n                << \")\";\n            return false;\n        }\n\n        r = Crypto::derive_public_key(derivation,no,minerAddress.spendPublicKey,outEphemeralPubKey);\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to derive_public_key(\"\n                << derivation << \", \"\n                << no << \", \"\n                << minerAddress.spendPublicKey\n                << \")\";\n            return false;\n        }\n\n        KeyOutput tk;\n        tk.key = outEphemeralPubKey;\n\n        TransactionOutput out;\n        summaryAmounts += out.amount = outAmounts[no];\n        out.target = tk;\n        tx.outputs.push_back(out);\n    }\n\n    if (enableGovernance) {\n        AccountKeys governanceKeys;\n        getGovernanceAddressAndKey(governanceKeys);\n\n        Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();\n        Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();\n\n        bool r = Crypto::generate_key_derivation(governanceKeys.address.viewPublicKey, txkey.secretKey, derivation);\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to generate_key_derivation(\"\n                << governanceKeys.address.viewPublicKey << \", \" << txkey.secretKey << \")\";\n            return false;\n        }\n        size_t pos = tx.outputs.size();\n        r = Crypto::derive_public_key(derivation, pos++, governanceKeys.address.spendPublicKey, outEphemeralPubKey);\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                << \"while creating outs: failed to derive_public_key(\"\n                << derivation << \", \" << 0 << \", \"\n                << governanceKeys.address.spendPublicKey << \")\";\n            return false;\n        }\n\n        KeyOutput tk;\n        tk.key = outEphemeralPubKey;\n\n        TransactionOutput out;\n        summaryAmounts += out.amount = governanceReward;\n        out.target = tk;\n        tx.outputs.push_back(out);\n    }\n\n    if (summaryAmounts != totalRewardWGR) {\n        logger(ERROR, BRIGHT_RED)\n            << \"Failed to construct miner tx, summaryAmounts = \"\n            << summaryAmounts\n            << \" not equal blockReward = \"\n            << blockReward;\n        return false;\n    }\n\n    tx.version = CURRENT_TRANSACTION_VERSION;\n    //lock\n    tx.unlockTime = height + m_minedMoneyUnlockWindow;\n    tx.inputs.push_back(in);\n\n    return true;\n}\n\nbool Currency::isFusionTransaction(\n    const std::vector<uint64_t> &inputsAmounts,\n    const std::vector<uint64_t> &outputsAmounts,\n    size_t size,\n    uint32_t height) const\n{\n    // TODO: Simplify if (...) content.\n    if (height <= CryptoNote::parameters::UPGRADE_HEIGHT_V3 ? size > CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_CURRENT * 30 / 100 : size > fusionTxMaxSize()) {\n        logger(ERROR) << \"Fusion transaction verification failed: size exceeded max allowed size.\";\n        return false;\n    }\n\n    if (inputsAmounts.size() < fusionTxMinInputCount()) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"inputs count is less than minimum.\";\n        return false;\n    }\n\n    if (inputsAmounts.size() < outputsAmounts.size() * fusionTxMinInOutCountRatio()) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"inputs to outputs count ratio is less than minimum.\";\n        return false;\n    }\n\n    uint64_t inputAmount = 0;\n    for (auto amount : inputsAmounts) {\n        if (height < CryptoNote::parameters::UPGRADE_HEIGHT_V4) {\n            if (amount < defaultDustThreshold()) {\n                logger(ERROR)\n                    << \"Fusion transaction verification failed: amount \"\n                    << amount\n                    << \" is less than dust threshold.\";\n                return false;\n            }\n        }\n        inputAmount += amount;\n    }\n\n    std::vector<uint64_t> expectedOutputsAmounts;\n    expectedOutputsAmounts.reserve(outputsAmounts.size());\n    decomposeAmount(\n        inputAmount,\n        height < CryptoNote::parameters::UPGRADE_HEIGHT_V4\n        ? defaultDustThreshold()\n        : UINT64_C(0), expectedOutputsAmounts);\n    std::sort(expectedOutputsAmounts.begin(), expectedOutputsAmounts.end());\n\n    bool decompose = expectedOutputsAmounts == outputsAmounts;\n    if (!decompose) {\n        logger(ERROR)\n            << \"Fusion transaction verification failed: \"\n            << \"decomposed output amounts do not match expected.\";\n        return false;\n    }\n\n    return true;\n}\n\nbool Currency::isFusionTransaction(const Transaction &transaction,size_t size,uint32_t height) const\n{\n    assert(getObjectBinarySize(transaction) == size);\n\n    std::vector<uint64_t> outputsAmounts;\n    outputsAmounts.reserve(transaction.outputs.size());\n    for (const TransactionOutput &output : transaction.outputs) {\n        outputsAmounts.push_back(output.amount);\n    }\n\n    return isFusionTransaction(getInputsAmounts(transaction), outputsAmounts, size, height);\n}\n\nbool Currency::isFusionTransaction(const Transaction &transaction, uint32_t height) const\n{\n    return isFusionTransaction(transaction, getObjectBinarySize(transaction), height);\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(\n    uint64_t amount,\n    uint64_t threshold,\n    uint32_t height) const\n{\n    uint8_t ignore;\n    return isAmountApplicableInFusionTransactionInput(amount, threshold, ignore, height);\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(\n    uint64_t amount,\n    uint64_t threshold,\n    uint8_t &amountPowerOfTen,\n    uint32_t height) const\n{\n    if (amount >= threshold) {\n        return false;\n    }\n\n    if (height < CryptoNote::parameters::UPGRADE_HEIGHT_V4 && amount < defaultDustThreshold()) {\n        return false;\n    }\n\n    auto it = std::lower_bound(\n        Constants::PRETTY_AMOUNTS.begin(),\n        Constants::PRETTY_AMOUNTS.end(),\n        amount\n    );\n    if (it == Constants::PRETTY_AMOUNTS.end() || amount != *it) {\n        return false;\n    }\n\n    amountPowerOfTen = static_cast<uint8_t>(std::distance(Constants::PRETTY_AMOUNTS.begin(), it)/9);\n\n    return true;\n}\n\nstd::string Currency::accountAddressAsString(const AccountBase &account) const\n{\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, account.getAccountKeys().address);\n}\n\nstd::string Currency::accountAddressAsString(const AccountPublicAddress &accountPublicAddress) const\n{\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, accountPublicAddress);\n}\n\nbool Currency::parseAccountAddressString(const std::string &str, AccountPublicAddress &addr) const\n{\n    uint64_t prefix;\n    if (!CryptoNote::parseAccountAddressString(prefix, addr, str)) {\n        return false;\n    }\n\n    if (prefix != m_publicAddressBase58Prefix) {\n        logger(DEBUGGING)\n        << \"Wrong address prefix: \" << prefix\n        << \", expected \" << m_publicAddressBase58Prefix;\n        return false;\n    }\n\n    return true;\n}\n\nstd::string Currency::formatAmount(uint64_t amount) const\n{\n    std::string s = std::to_string(amount);\n    if (s.size() < m_numberOfDecimalPlaces + 1) {\n        s.insert(0, m_numberOfDecimalPlaces + 1 - s.size(), '0');\n    }\n    s.insert(s.size() - m_numberOfDecimalPlaces, \".\");\n\n    return s;\n}\n\nstd::string Currency::formatAmount(int64_t amount) const\n{\n    std::string s = formatAmount(static_cast<uint64_t>(std::abs(amount)));\n\n    if (amount < 0) {\n        s.insert(0, \"-\");\n    }\n\n    return s;\n}\n\nbool Currency::parseAmount(const std::string &str, uint64_t &amount) const\n{\n    std::string strAmount = str;\n    boost::algorithm::trim(strAmount);\n\n    size_t pointIndex = strAmount.find_first_of('.');\n    size_t fractionSize;\n    if (std::string::npos != pointIndex) {\n        fractionSize = strAmount.size() - pointIndex - 1;\n        while (m_numberOfDecimalPlaces < fractionSize && '0' == strAmount.back()) {\n            strAmount.erase(strAmount.size() - 1, 1);\n            --fractionSize;\n        }\n        if (m_numberOfDecimalPlaces < fractionSize) {\n            return false;\n        }\n        strAmount.erase(pointIndex, 1);\n    } else {\n        fractionSize = 0;\n    }\n\n    if (strAmount.empty()) {\n        return false;\n    }\n\n    if (!std::all_of(strAmount.begin(), strAmount.end(), ::isdigit)) {\n        return false;\n    }\n\n    if (fractionSize < m_numberOfDecimalPlaces) {\n        strAmount.append(m_numberOfDecimalPlaces - fractionSize, '0');\n    }\n\n    return Common::fromString(strAmount, amount);\n}\n\n// Copyright (c) 2017-2018 Zawy\n// http://zawy1.blogspot.com/2017/12/using-difficulty-to-get-constant-value.html\n// Moore's law application by Sergey Kozlov\nuint64_t Currency::getMinimalFee(\n    uint64_t dailyDifficulty,\n    uint64_t reward,\n    uint64_t avgHistoricalDifficulty,\n    uint64_t medianHistoricalReward,\n    uint32_t height) const\n{\n    const uint64_t blocksInTwoYears = parameters::EXPECTED_NUMBER_OF_BLOCKS_PER_DAY * 365 * 2;\n    const double gauge = double(0.25);\n    uint64_t minimumFee(0);\n    double dailyDifficultyMoore = dailyDifficulty\n                                  / pow(2, static_cast<double>(height)\n                                  / static_cast<double>(blocksInTwoYears));\n    double minFee = gauge * parameters::COIN * static_cast<double>(avgHistoricalDifficulty)\n                    / dailyDifficultyMoore * static_cast<double>(reward)\n                    / static_cast<double>(medianHistoricalReward);\n    if (minFee == 0 || !std::isfinite(minFee)) {\n        return CryptoNote::parameters::MAXIMUM_FEE; // zero test\n    }\n    minimumFee = static_cast<uint64_t>(minFee);\n\n    // TODO: return std::min<uint64_t>(CryptoNote::parameters::MAXIMUM_FEE, minimumFee);\n    return CryptoNote::parameters::MINIMUM_FEE_V1;\n}\n\nuint64_t Currency::roundUpMinFee(uint64_t minimalFee, int digits) const\n{\n    uint64_t ret(0);\n    std::string minFeeString = formatAmount(minimalFee);\n    double minFee = boost::lexical_cast<double>(minFeeString);\n    double scale = pow(10., floor(log10(fabs(minFee))) + (1 - digits));\n    double roundedFee = ceil(minFee / scale) * scale;\n    std::stringstream ss;\n    ss << std::fixed << std::setprecision(12) << roundedFee;\n    std::string roundedFeeString = ss.str();\n    parseAmount(roundedFeeString, ret);\n\n    return ret;\n}\n\ndifficulty_type Currency::nextDifficulty(\n    uint32_t height,\n    uint8_t blockMajorVersion,\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_5) {\n        return nextDifficultyV5(blockMajorVersion, timestamps, cumulativeDifficulties);\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_3\n               || blockMajorVersion == BLOCK_MAJOR_VERSION_4) {\n        return nextDifficultyV3(timestamps, cumulativeDifficulties);\n    } else if (blockMajorVersion == BLOCK_MAJOR_VERSION_2) {\n        return nextDifficultyV2(timestamps, cumulativeDifficulties);\n    } else {\n        return nextDifficultyV1(timestamps, cumulativeDifficulties);\n    }\n}\n\ndifficulty_type Currency::nextDifficultyV1(\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    assert(m_difficultyWindow >= 2);\n\n    if (timestamps.size() > m_difficultyWindow) {\n        timestamps.resize(m_difficultyWindow);\n        cumulativeDifficulties.resize(m_difficultyWindow);\n    }\n\n    size_t length = timestamps.size();\n    assert(length == cumulativeDifficulties.size());\n    assert(length <= m_difficultyWindow);\n    if (length <= 1) {\n        return 1;\n    }\n\n    sort(timestamps.begin(), timestamps.end());\n\n    size_t cutBegin, cutEnd;\n    assert(2 * m_difficultyCut <= m_difficultyWindow - 2);\n    if (length <= m_difficultyWindow - 2 * m_difficultyCut) {\n        cutBegin = 0;\n        cutEnd = length;\n    } else {\n        cutBegin = (length - (m_difficultyWindow - 2 * m_difficultyCut) + 1) / 2;\n        cutEnd = cutBegin + (m_difficultyWindow - 2 * m_difficultyCut);\n    }\n    assert(/*cut_begin >= 0 &&*/ cutBegin + 2 <= cutEnd && cutEnd <= length);\n    uint64_t timeSpan = timestamps[cutEnd - 1] - timestamps[cutBegin];\n    if (timeSpan == 0) {\n        timeSpan = 1;\n    }\n\n    difficulty_type totalWork = cumulativeDifficulties[cutEnd - 1]-cumulativeDifficulties[cutBegin];\n    assert(totalWork > 0);\n\n    uint64_t low, high;\n    low = mul128(totalWork, m_difficultyTarget, &high);\n    if (high != 0 || low + timeSpan - 1 < low) {\n        return 0;\n    }\n\n    return (low + timeSpan - 1) / timeSpan;\n}\n\ndifficulty_type Currency::nextDifficultyV2(\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    // Difficulty calculation v. 2\n    // based on Zawy difficulty algorithm v1.0\n    // next Diff = Avg past N Diff * TargetInterval / Avg past N solve times\n    // as described at https://github.com/monero-project/research-lab/issues/3\n    // Window time span and total difficulty is taken instead of average\n    // as suggested by Nuclear_chaos\n\n    size_t m_difficultyWindow_2 = CryptoNote::parameters::DIFFICULTY_WINDOW_V2;\n    assert(m_difficultyWindow_2 >= 2);\n\n    if (timestamps.size() > m_difficultyWindow_2) {\n        timestamps.resize(m_difficultyWindow_2);\n        cumulativeDifficulties.resize(m_difficultyWindow_2);\n    }\n\n    size_t length = timestamps.size();\n    assert(length == cumulativeDifficulties.size());\n    assert(length <= m_difficultyWindow_2);\n    if (length <= 1) {\n        return 1;\n    }\n\n    sort(timestamps.begin(), timestamps.end());\n\n    uint64_t timeSpan = timestamps.back() - timestamps.front();\n    if (timeSpan == 0) {\n        timeSpan = 1;\n    }\n\n    difficulty_type totalWork = cumulativeDifficulties.back() - cumulativeDifficulties.front();\n    assert(totalWork > 0);\n\n    // uint64_t nextDiffZ = totalWork * m_difficultyTarget / timeSpan;\n\n    uint64_t low, high;\n    low = mul128(totalWork, m_difficultyTarget, &high);\n    // blockchain error \"Difficulty overhead\" if this function returns zero\n    if (high != 0) {\n        return 0;\n    }\n\n    uint64_t nextDiffZ = low / timeSpan;\n\n    // minimum limit\n    if (!isTestnet() && nextDiffZ < 100000) {\n        nextDiffZ = 100000;\n    }\n\n    return nextDiffZ;\n}\n\ndifficulty_type Currency::nextDifficultyV3(\n    std::vector<uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    // LWMA difficulty algorithm\n    // Copyright (c) 2017-2018 Zawy\n    // MIT license http://www.opensource.org/licenses/mit-license.php.\n    // This is an improved version of Tom Harding's (Deger8) \"WT-144\"\n    // Karbowanec, Masari, Bitcoin Gold, and Bitcoin Cash have contributed.\n    // See https://github.com/zawy12/difficulty-algorithms/issues/1 for other algos.\n    // Do not use \"if solvetime < 0 then solvetime = 1\" which allows a catastrophic exploit.\n    // T= target_solvetime;\n    // N = int(45 * (600 / T) ^ 0.3));\n\n    const int64_t T = static_cast<int64_t>(m_difficultyTarget);\n    size_t N = CryptoNote::parameters::DIFFICULTY_WINDOW_V3;\n\n    // return a difficulty of 1 for first 3 blocks if it's the start of the chain\n    if (timestamps.size() < 4) {\n        return 1;\n    } else if (timestamps.size() < N + 1) {\n        // otherwise, use a smaller N if the start of the chain is less than N+1\n        N = timestamps.size() - 1;\n    } else if (timestamps.size() > N + 1) {\n        timestamps.erase(timestamps.begin(), timestamps.end() - N - 1);\n        cumulativeDifficulties.erase(\n            cumulativeDifficulties.begin(),\n            cumulativeDifficulties.end() - N - 1\n        );\n    }\n\n    // To get an average solvetime to within +/- ~0.1%, use an adjustment factor.\n    const double adjust = 0.998;\n    // The divisor k normalizes LWMA.\n    const double k = N * (N + 1) / 2;\n\n    double LWMA(0), sum_inverse_D(0), harmonic_mean_D(0), nextDifficulty(0);\n    int64_t solveTime(0);\n    uint64_t difficulty(0), next_difficulty(0);\n\n    // Loop through N most recent blocks.\n    for (size_t i = 1; i <= N; i++) {\n        solveTime = static_cast<int64_t>(timestamps[i]) - static_cast<int64_t>(timestamps[i - 1]);\n        solveTime = std::min<int64_t>((T * 7), std::max<int64_t>(solveTime, (-6 * T)));\n        difficulty = cumulativeDifficulties[i] - cumulativeDifficulties[i - 1];\n        LWMA += (int64_t)(solveTime * i) / k;\n        sum_inverse_D += 1 / static_cast<double>(difficulty);\n    }\n\n    // Keep LWMA sane in case something unforeseen occurs.\n    if (static_cast<int64_t>(boost::math::round(LWMA)) < T / 20)\n    LWMA = static_cast<double>(T) / 20;\n\n    harmonic_mean_D = N / sum_inverse_D * adjust;\n    nextDifficulty = harmonic_mean_D * T / LWMA;\n    next_difficulty = static_cast<uint64_t>(nextDifficulty);\n\n    // minimum limit\n    if (!isTestnet() && next_difficulty < 100000) {\n        next_difficulty = 100000;\n    }\n\n    return next_difficulty;\n}\n\ntemplate <typename T>\ninline T clamp(T lo, T v, T hi)\n{\n    return v < lo ? lo : v > hi ? hi : v;\n}\n\n// difficulty for block version 5.0\ndifficulty_type Currency::nextDifficultyV5(\n    uint8_t blockMajorVersion,\n    std::vector<std::uint64_t> timestamps,\n    std::vector<difficulty_type> cumulativeDifficulties) const\n{\n    // LWMA-2 difficulty algorithm\n    // Copyright (c) 2017-2018 Zawy, MIT License\n    // https://github.com/zawy12/difficulty-algorithms/issues/3\n    // with modifications by Ryo Currency developers\n    // courtesy to aivve from Karbo\n\n    const int64_t  T = static_cast<int64_t>(m_difficultyTarget);\n    int64_t  N = difficultyBlocksCount3();\n    int64_t  L(0), ST, sum_3_ST(0);\n    uint64_t nextDiffV5, prev_D;\n\n    assert(timestamps.size() == cumulativeDifficulties.size()\n           && timestamps.size() <= static_cast<uint64_t>(N + 1));\n\n    int64_t max_TS, prev_max_TS;\n    prev_max_TS = timestamps[0];\n    for (int64_t i = 1; i <= N; i++) {\n        if (static_cast<int64_t>(timestamps[i]) > prev_max_TS) {\n            max_TS = timestamps[i];\n        } else {\n            max_TS = prev_max_TS + 1;\n        }\n        ST = std::min(6 * T, max_TS - prev_max_TS);\n        prev_max_TS = max_TS;\n        L += ST * i;\n        if (i > N - 3) {\n            sum_3_ST += ST;\n        }\n    }\n\n    nextDiffV5 = uint64_t((cumulativeDifficulties[N] - cumulativeDifficulties[0]) * T * (N + 1))\n                 / uint64_t(2 * L);\n    nextDiffV5 = (nextDiffV5 * 99ull) / 100ull;\n\n    prev_D = cumulativeDifficulties[N] - cumulativeDifficulties[N - 1];\n    nextDiffV5 = clamp(\n        (uint64_t)(prev_D * 67ull / 100ull),\n        nextDiffV5,\n        (uint64_t)(prev_D * 150ull / 100ull)\n    );\n    if (sum_3_ST < (8 * T) / 10) {\n        nextDiffV5 = (prev_D * 110ull) / 100ull;\n    }\n\n    // minimum limit\n    if (nextDiffV5 < 10000000) {\n        nextDiffV5 = 10000000;\n    }\n    if(isTestnet()){\n        nextDiffV5 = 10000;\n    }\n\n    return nextDiffV5;\n}\n\nbool Currency::checkProofOfWorkV1(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    if (BLOCK_MAJOR_VERSION_2 == block.majorVersion||BLOCK_MAJOR_VERSION_3 == block.majorVersion) {\n        return false;\n    }\n\n    if (!get_block_longhash(context, block, proofOfWork)) {\n        return false;\n    }\n\n    return check_hash(proofOfWork, currentDiffic);\n}\n\nbool Currency::checkProofOfWorkV2(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    if (block.majorVersion < BLOCK_MAJOR_VERSION_2) {\n        return false;\n    }\n\n    if (!get_block_longhash(context, block, proofOfWork)) {\n        return false;\n    }\n\n    if (!check_hash(proofOfWork, currentDiffic)) {\n        return false;\n    }\n\n    TransactionExtraMergeMiningTag mmTag;\n    if (!getMergeMiningTagFromExtra(block.parentBlock.baseTransaction.extra, mmTag)) {\n        logger(ERROR)\n            << \"merge mining tag wasn't found in extra of the parent block miner transaction\";\n        return false;\n    }\n\n    if (8 * sizeof(m_genesisBlockHash) < block.parentBlock.blockchainBranch.size()) {\n        return false;\n    }\n\n    Crypto::Hash auxBlockHeaderHash;\n    if (!get_aux_block_header_hash(block, auxBlockHeaderHash)) {\n        return false;\n    }\n\n    Crypto::Hash auxBlocksMerkleRoot;\n    Crypto::tree_hash_from_branch(\n        block.parentBlock.blockchainBranch.data(),\n        block.parentBlock.blockchainBranch.size(),\n        auxBlockHeaderHash,\n        &m_genesisBlockHash,\n        auxBlocksMerkleRoot\n    );\n\n    if (auxBlocksMerkleRoot != mmTag.merkleRoot) {\n        logger(ERROR, BRIGHT_YELLOW) << \"Aux block hash wasn't found in merkle tree\";\n        return false;\n    }\n\n    return true;\n}\n\nbool Currency::checkProofOfWork(\n    Crypto::cn_context &context,\n    const Block &block,\n    difficulty_type currentDiffic,\n    Crypto::Hash &proofOfWork) const\n{\n    switch (block.majorVersion) {\n    case BLOCK_MAJOR_VERSION_1:\n        // fall through\n    case BLOCK_MAJOR_VERSION_4:\n        // fall through\n    case BLOCK_MAJOR_VERSION_5:\n        // fall through\n    case BLOCK_MAJOR_VERSION_6:\n        return checkProofOfWorkV1(context, block, currentDiffic, proofOfWork);\n    case BLOCK_MAJOR_VERSION_2:\n        // fall through\n    case BLOCK_MAJOR_VERSION_3:\n        return checkProofOfWorkV2(context, block, currentDiffic, proofOfWork);\n    }\n\n    logger(ERROR, BRIGHT_RED)\n        << \"Unknown block major version: \"\n        << block.majorVersion\n        << \".\"\n        << block.minorVersion;\n\n    return false;\n}\n\nsize_t Currency::getApproximateMaximumInputCount(\n    size_t transactionSize,\n    size_t outputCount,\n    size_t mixinCount) const\n{\n    const size_t KEY_IMAGE_SIZE = sizeof(Crypto::KeyImage);\n    const size_t OUTPUT_KEY_SIZE = sizeof(decltype(KeyOutput::key));\n    const size_t AMOUNT_SIZE = sizeof(uint64_t) + 2; // varint\n    const size_t GLOBAL_INDEXES_VECTOR_SIZE_SIZE = sizeof(uint8_t); // varint\n    const size_t GLOBAL_INDEXES_INITIAL_VALUE_SIZE = sizeof(uint32_t); // varint\n    const size_t GLOBAL_INDEXES_DIFFERENCE_SIZE = sizeof(uint32_t); // varint\n    const size_t SIGNATURE_SIZE = sizeof(Crypto::Signature);\n    const size_t EXTRA_TAG_SIZE = sizeof(uint8_t);\n    const size_t INPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t OUTPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t PUBLIC_KEY_SIZE = sizeof(Crypto::PublicKey);\n    const size_t TRANSACTION_VERSION_SIZE = sizeof(uint8_t);\n    const size_t TRANSACTION_UNLOCK_TIME_SIZE = sizeof(uint64_t);\n\n    const size_t outputsSize = outputCount * (OUTPUT_TAG_SIZE + OUTPUT_KEY_SIZE + AMOUNT_SIZE);\n    const size_t headerSize = TRANSACTION_VERSION_SIZE\n                              + TRANSACTION_UNLOCK_TIME_SIZE\n                              + EXTRA_TAG_SIZE\n                              + PUBLIC_KEY_SIZE;\n    const size_t inputSize = INPUT_TAG_SIZE\n                             + AMOUNT_SIZE\n                             + KEY_IMAGE_SIZE\n                             + SIGNATURE_SIZE\n                             + GLOBAL_INDEXES_VECTOR_SIZE_SIZE\n                             + GLOBAL_INDEXES_INITIAL_VALUE_SIZE\n                             + mixinCount * (GLOBAL_INDEXES_DIFFERENCE_SIZE + SIGNATURE_SIZE);\n\n    return (transactionSize - headerSize - outputsSize) / inputSize;\n}\n\nCurrencyBuilder::CurrencyBuilder(Logging::ILogger &log)\n    : m_currency(log)\n{\n    maxBlockNumber(parameters::CRYPTONOTE_MAX_BLOCK_NUMBER);\n    maxBlockBlobSize(parameters::CRYPTONOTE_MAX_BLOCK_BLOB_SIZE);\n    maxTxSize(parameters::CRYPTONOTE_MAX_TX_SIZE);\n    publicAddressBase58Prefix(parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX);\n    minedMoneyUnlockWindow(parameters::CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW);\n    transactionSpendableAge(parameters::CRYPTONOTE_TX_SPENDABLE_AGE);\n    expectedNumberOfBlocksPerDay(parameters::EXPECTED_NUMBER_OF_BLOCKS_PER_DAY);\n\n    timestampCheckWindow(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);\n    timestampCheckWindow_v1(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW_V1);\n    blockFutureTimeLimit(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT);\n    blockFutureTimeLimit_v1(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT_V1);\n\n    moneySupply(parameters::MONEY_SUPPLY);\n    emissionSpeedFactor(parameters::EMISSION_SPEED_FACTOR);\n    cryptonoteCoinVersion(parameters::CRYPTONOTE_COIN_VERSION);\n\n    rewardBlocksWindow(parameters::CRYPTONOTE_REWARD_BLOCKS_WINDOW);\n    blockGrantedFullRewardZone(parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE);\n    minerTxBlobReservedSize(parameters::CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE);\n    maxTransactionSizeLimit(parameters::MAX_TRANSACTION_SIZE_LIMIT);\n\n    governancePercent(parameters::GOVERNANCE_PERCENT_FEE);\n    governanceHeightStart(parameters::GOVERNANCE_HEIGHT_START);\n    governanceHeightEnd(parameters::GOVERNANCE_HEIGHT_END);\n\n    minMixin(parameters::MIN_TX_MIXIN_SIZE);\n    maxMixin(parameters::MAX_TX_MIXIN_SIZE);\n\n    numberOfDecimalPlaces(parameters::CRYPTONOTE_DISPLAY_DECIMAL_POINT);\n\n    minimumFee(parameters::MINIMUM_FEE);\n    defaultDustThreshold(parameters::DEFAULT_DUST_THRESHOLD);\n\n    difficultyTarget(parameters::DIFFICULTY_TARGET);\n    difficultyWindow(parameters::DIFFICULTY_WINDOW);\n    difficultyLag(parameters::DIFFICULTY_LAG);\n    difficultyCut(parameters::DIFFICULTY_CUT);\n\n    maxBlockSizeInitial(parameters::MAX_BLOCK_SIZE_INITIAL);\n    maxBlockSizeGrowthSpeedNumerator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_NUMERATOR);\n    maxBlockSizeGrowthSpeedDenominator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_DENOMINATOR);\n\n    lockedTxAllowedDeltaSeconds(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS);\n    lockedTxAllowedDeltaBlocks(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS);\n\n    mempoolTxLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_LIVETIME);\n    mempoolTxFromAltBlockLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME);\n    numberOfPeriodsToForgetTxDeletedFromPool(\n        parameters::CRYPTONOTE_NUMBER_OF_PERIODS_TO_FORGET_TX_DELETED_FROM_POOL\n    );\n\n    fusionTxMaxSize(parameters::FUSION_TX_MAX_SIZE);\n    fusionTxMinInputCount(parameters::FUSION_TX_MIN_INPUT_COUNT);\n    fusionTxMinInOutCountRatio(parameters::FUSION_TX_MIN_IN_OUT_COUNT_RATIO);\n\n    upgradeHeightV2(parameters::UPGRADE_HEIGHT_V2);\n    upgradeHeightV3(parameters::UPGRADE_HEIGHT_V3);\n    upgradeHeightV4(parameters::UPGRADE_HEIGHT_V4);\n    upgradeHeightV5(parameters::UPGRADE_HEIGHT_V5);\n    upgradeHeightV6(parameters::UPGRADE_HEIGHT_V6);\n    upgradeVotingThreshold(parameters::UPGRADE_VOTING_THRESHOLD);\n    upgradeVotingWindow(parameters::UPGRADE_VOTING_WINDOW);\n    upgradeWindow(parameters::UPGRADE_WINDOW);\n\n    blocksFileName(parameters::CRYPTONOTE_BLOCKS_FILENAME);\n    blocksCacheFileName(parameters::CRYPTONOTE_BLOCKSCACHE_FILENAME);\n    blockIndexesFileName(parameters::CRYPTONOTE_BLOCKINDEXES_FILENAME);\n    txPoolFileName(parameters::CRYPTONOTE_POOLDATA_FILENAME);\n    blockchainIndicesFileName(parameters::CRYPTONOTE_BLOCKCHAIN_INDICES_FILENAME);\n\n    testnet(false);\n}\n\nTransaction CurrencyBuilder::generateGenesisTransaction()\n{\n    CryptoNote::Transaction tx;\n    auto ac = boost::value_initialized<CryptoNote::AccountPublicAddress>();\n\n    m_currency.constructMinerTx(1, 0, 0, 0, 0, 0, ac, tx); // zero fee in genesis\n\n    return tx;\n}\n\nCurrencyBuilder& CurrencyBuilder::emissionSpeedFactor(unsigned int val)\n{\n    if (val <= 0 || val > 8 * sizeof(uint64_t)) {\n        throw std::invalid_argument(\"val at emissionSpeedFactor()\");\n    }\n\n    m_currency.m_emissionSpeedFactor = val;\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::numberOfDecimalPlaces(size_t val)\n{\n    m_currency.m_numberOfDecimalPlaces = val;\n    m_currency.m_coin = 1;\n    for (size_t i = 0; i < m_currency.m_numberOfDecimalPlaces; ++i) {\n        m_currency.m_coin *= 10;\n    }\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::difficultyWindow(size_t val)\n{\n    if (val < 2) {\n        throw std::invalid_argument(\"val at difficultyWindow()\");\n    }\n\n    m_currency.m_difficultyWindow = val;\n\n    return *this;\n}\n\nCurrencyBuilder& CurrencyBuilder::upgradeVotingThreshold(unsigned int val)\n{\n    if (val <= 0 || val > 100) {\n        throw std::invalid_argument(\"val at upgradeVotingThreshold()\");\n    }\n\n    m_currency.m_upgradeVotingThreshold = val;\n\n    return *this;\n}\n\nCurrencyBuilder &CurrencyBuilder::upgradeWindow(size_t val)\n{\n    if (val <= 0) {\n        throw std::invalid_argument(\"val at upgradeWindow()\");\n    }\n\n    m_currency.m_upgradeWindow = static_cast<uint32_t>(val);\n\n    return *this;\n}\n\n} // namespace CryptoNote\n", "meta": {"hexsha": "2c88a2d5ab849505126228664fcdb0c04087557e", "size": 40163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/CryptoNoteCore/Currency.cpp", "max_stars_repo_name": "ezaruba/qwertycoin", "max_stars_repo_head_hexsha": "57f676667e692dda1d9ee580a47bcab74b1996bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-04T20:37:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T20:37:06.000Z", "max_issues_repo_path": "lib/CryptoNoteCore/Currency.cpp", "max_issues_repo_name": "ezaruba/qwertycoin", "max_issues_repo_head_hexsha": "57f676667e692dda1d9ee580a47bcab74b1996bb", "max_issues_repo_licenses": ["MIT"], "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/CryptoNoteCore/Currency.cpp", "max_forks_repo_name": "ezaruba/qwertycoin", "max_forks_repo_head_hexsha": "57f676667e692dda1d9ee580a47bcab74b1996bb", "max_forks_repo_licenses": ["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.6092050209, "max_line_length": 183, "alphanum_fraction": 0.6780618978, "num_tokens": 9806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2309197629292718, "lm_q2_score": 0.020023439023370237, "lm_q1q2_score": 0.004623807792305385}}
{"text": "#ifndef TYPE_TRAITS\n#define TYPE_TRAITS\n#include \"rider/faiz/cstddef.hpp\" // for size_t\n#include \"rider/faiz/faiz_fwd.hpp\"\n#include <boost/predef.h>\n#include <type_traits>\n/*\nDon't implement:\n*/\n\nnamespace Rider::Faiz\n{\n\t// Provides member typedef type, which is defined as T if B is true at\n\t// compile time, or as F if B is false.\n\tTpl<bool B, Typ T, Typ F> struct conditional : type_identity<T>\n\t{};\n\n\t// Provides member typedef type, which is defined as T if B is true at\n\t// compile time, or as F if B is false.\n\tTpl<Typ T, Typ F> struct conditional<false, T, F> : type_identity<F>\n\t{};\n\n\t//  Provides member typedef type, which is defined as T if B is true at\n\t//  compile time, or as F if B is false.\n\tTpl<bool B, Typ T, Typ F> using conditional_t = _t<conditional<B, T, F>>;\n\n\t// forward declaration\n\t// If the imaginary function definition tTo `test() { return\n\t// std::declval<tFrom>(); }` is well-formed, (that is, either\n\t// `Faiz::declval<tFrom>()` can be converted to tTo using implicit\n\t// conversions, or both tFrom and tTo are possibly `cv-qualified void`),\n\t// provides the member constant value equal to true. Otherwise value is\n\t// false. For the purposes of this check, the use of `Faiz::declval` in the\n\t// return statement is not considered an odr-use. Access checks are\n\t// performed as if from a context unrelated to either type. Only the\n\t// validity of the immediate context of the expression in the return\n\t// statement (including conversions to the return type) is considered.\n\tTpl<Typ tFrom, Typ tTo> struct is_convertible;\n\n\tnamespace detail\n\t{\n\n\t\tTpl<Typ Default,\n\t\t\tclass AlwaysVoid,\n\t\t\tTpl<Typ...> class Op,\n\t\t\tTyp... Args> struct detector : type_identity<Default>\n\t\t{\n\t\t\tusing value_t = false_;\n\t\t};\n\n\t\tTpl<Typ Default, Tpl<Typ...> class Op, class... Args> struct detector<\n\t\t\tDefault,\n\t\t\tvoid_t<Op<Args...>>,\n\t\t\tOp,\n\t\t\tArgs...>\n#if BOOST_COMP_GNUC\n\t\t\t: type_identity<Op<Args...>>\n#endif\n\t\t{\n\t\t\tusing value_t = true_;\n#if BOOST_COMP_CLANG\n\t\t\tusing type = Op<Args...>;\n#endif\n\t\t};\n\n\t} // namespace detail\n\n\t// nonesuch cannot be constructed, destroyed, or copied in the usual way.\n\t// However, it is an aggregate and therefore can be constructed (presumably\n\t// unintentionally) via aggregate initialization in contexts where the\n\t// destructor's availability is not an issue, such as a new-expression: new\n\t// std::experimental::nonesuch{}.\n\t//\n\t// This type was inspired by, and patterned after, the internal type __nat\n\t// (which we believe is an acronym for “not a type”) found in libc++.\n\tstruct nonesuch\n\t{\n\t\t~nonesuch() = delete;\n\t\tnonesuch(nonesuch const&) = delete;\n\t\tvoid\n\t\toperator=(nonesuch const&)\n\t\t\t= delete;\n\t};\n\n\n\t// The alias Tpl `is_detected` is equivalent to Typ\n\t// `detected_or<Faiz::nonesuch, Op, Args...>::value_t`. It is an\n\t// alias for `Faiz::true_type` if the `Tpl-id Op<Args...>` denotes a\n\t// valid type; otherwise it is an alias for `Faiz::false_type`.\n\tTpl<Tpl<Typ...> class Op, Typ... Args> using is_detected\n\t\t= Typ detail::detector<nonesuch, void, Op, Args...>::value_t;\n\n\n\t// The alias Tpl `detected_t` is equivalent to Typ\n\t// `detected_or<Faiz::nonesuch, Op, Args...>::type`. It is an\n\t// alias for `Op<Args...>` if that Tpl-id denotes a valid type;\n\t// otherwise it is an alias for the class `Faiz::nonesuch`.\n\tTpl<Tpl<Typ...> class Op, Typ... Args> using detected_t\n\t\t= _t<detail::detector<nonesuch, void, Op, Args...>>;\n\n\t// The alias Tpl `detected_or` is an alias for an unspecified class\n\t// type with two public member typedefs `value_t` and type, which are\n\t// defined as follows:\n\t//\n\t// - If the Tpl-id `Op<Args...>` denotes a valid type,\n\t// then `value_t`\n\t//  is an alias for `Faiz::true_type`, and type is an alias for\n\t// `Op<Args...>`;\n\t// - Otherwise, `value_t` is an alias for `Faiz::false_type` and type is\n\t// an alias for `Default`.\n\tTpl<Typ Default, Tpl<Typ...> class Op, Typ... Args> using detected_or\n\t\t= detail::detector<Default, void, Op, Args...>;\n\n\tTpl<Tpl<Typ...> class Op, Typ... Args> cexp bool is_detected_v\n\t\t= is_detected<Op, Args...>::value;\n\n\tTpl<Typ Default, Tpl<Typ...> class Op, Typ... Args> using detected_or_t\n\t\t= _t<detected_or<Default, Op, Args...>>;\n\t//\n\t// The alias Tpl is_detected_exact checks whether `detected_t<Op,\n\t// Args...>` is Expected.\n\tTpl<Typ Expected, Tpl<Typ...> class Op, Typ... Args> using is_detected_exact\n\t\t= is_same<Expected, detected_t<Op, Args...>>;\n\n\tTpl<Typ Expected, Tpl<Typ...> class Op, Typ... Args> cexp bool\n\t\tis_detected_exact_v\n\t\t= is_detected_exact<Expected, Op, Args...>::value;\n\t//\n\t//  The alias Tpl `is_detected_convertible` checks whether\n\t// `detected_t<Op, Args...>` is convertible to tTo.\n\tTpl<Typ tTo, Tpl<Typ...> class Op, Typ... Args> using is_detected_convertible\n\t\t= is_convertible<detected_t<Op, Args...>, tTo>;\n\n\tTpl<Typ tTo, Tpl<Typ...> class Op, Typ... Args> cexp bool\n\t\tis_detected_convertible_v\n\t\t= is_detected_convertible<tTo, Op, Args...>::value;\n\n\tTpl<Typ T> using is_void = is_same<void, remove_cv_t<T>>;\n\n\tIS_NOT_ARE_ANY(void)\n\n\tTpl<Typ T> using is_referenceable_aux = is_void<T&>;\n\tTpl<Typ T> cexp bool is_referenceable_v\n\t\t= is_detected_v<is_referenceable_aux, T> and not_void_v<T>;\n\tTpl<Typ T> struct is_referenceable : bool_<is_referenceable_v<T>>\n\t{};\n\n\tNOT(referenceable)\n\n\tTpl<Typ T> struct is_rvalue_reference;\n\n\tIS_NOT_ARE_ANY(rvalue_reference)\n\n\n} // namespace Rider::Faiz\n\n\nnamespace Rider::Faiz::detail\n{\n\tTpl<Typ T> struct is_member_pointer_helper : false_\n\t{};\n\n\tTpl<Typ T, Typ U> struct is_member_pointer_helper<T U::*> : true_\n\t{};\n\n\tTpl<Typ Base> true_\n\tis_base_of_test_func(const volatile Base*);\n\tTpl<Typ Base> Faiz::false_\n\tis_base_of_test_func(const volatile void*);\n\tTpl<Typ Base, Typ Derived> using pre_is_base_of\n\t\t= decltype(is_base_of_test_func<Base>(declval<Derived*>()));\n\n\t// with <experimental/type_traits>:\n\t// Tpl <Typ Base, Typ Derived>\n\t// using pre_is_base_of2 =\n\t// detected_or_t<true_, pre_is_base_of,\n\t// Base, Derived>;\n\tTpl<Typ Base, Typ Derived, Typ = void> struct pre_is_base_of2 : true_\n\t{};\n\t// note Faiz::void_t is a C++17 feature\n\tTpl<Typ Base, Typ Derived> struct pre_is_base_of2<Base,\n\t\tDerived,\n\t\tvoid_t<pre_is_base_of<Base, Derived>>> : pre_is_base_of<Base, Derived>\n\t{};\n\n\tTpl<Typ T, Typ> struct is_polymorphic_impl : false_\n\t{};\n\tTpl<Typ T> struct is_polymorphic_impl<T,\n\t\tdecltype(dynamic_cast<void*>(declval<remove_cv_t<T>*>()))> : true_\n\t{};\n\n\n\t// NOTE: !Rider::Faiz::is_assignable<bool &, std::nullptr_t>::value'\n\t// \"Error\", clang++ has a bug here.\n\t// TODO: use is_detected_v\n\tTpl<Typ T, Typ Arg, Typ> struct is_assignable_imp : false_\n\t{};\n\tTpl<Typ T, Typ Arg> struct is_assignable_imp<T,\n\t\tArg,\n\t\tvoid_t<decltype(declval<T>() = declval<Arg>())>> : not_void<Arg>\n\t{};\n\n\tTpl<bool IsArithmetic, Typ T> struct is_signed_impl : bool_<T(-1) < T(0)>\n\t{};\n\tTpl<Typ T> struct is_signed_impl<false, T> : false_\n\t{};\n\n\tTpl<bool IsArithmetic, Typ T> struct is_unsigned_impl\n\t\t: bool_<(T(-1) > T(0))>\n\t{};\n\tTpl<Typ T> struct is_unsigned_impl<false, T> : false_\n\t{};\n\n\tTpl<Typ T, Typ U = remove_cv_t<T>> struct is_floating_point_aux\n\t\t: is_any<U,\n\t\t\t  float,\n\t\t\t  double,\n#if _GLIBCXX_USE_FLOAT128\n\t\t\t  __float128, // add gcc specific\n#endif\n\t\t\t  long double>\n\t{};\n\n\tTpl<Typ T> cexp bool not_enum_rvalue_reference_v\n\t\t= logic::and_v<not_enum<T>, not_rvalue_reference<T>>;\n\n\t// TODO: use is_detected_v\n\tTpl<Typ T> using is_integral_arith\n\t\t= void_t<decltype(T{} * T{}), decltype(+T{})&, decltype(T{} % 1)>;\n\tTpl<Typ T> cexp bool is_integral_impl\n\t\t= is_detected_v<is_integral_arith,\n\t\t\t  T> and not_enum_rvalue_reference_v<T>;\n\n\tTpl<Typ T, bool = is_integral_impl<T>> struct is_integral_aux : false_\n\t{};\n\tTpl<Typ T> struct is_integral_aux<T, true> : true_\n\t{};\n\n\tTpl<Typ T> using is_arithmetic_arith\n\t\t= void_t<decltype(T{} * T{}), decltype(+T{})&>;\n\n\t// XXX: is_arithmetic_arith will allow std::complex, which is not arithmetic\n\t// type(If T is an arithmetic type (that is, an integral type or a\n\t// floating-point type) or a cv-qualified version thereof, provides the\n\t// member constant value equal true. For any other type, value is false.) ,\n\t// so add is_class to check.\n\tTpl<Typ T> cexp bool is_arithmetic_impl\n\t\t= is_detected_v<is_arithmetic_arith,\n\t\t\t  T> and not_class_v<T> and not_enum_rvalue_reference_v<T>;\n\n\tTpl<Typ T, bool = is_arithmetic_impl<T>> struct is_arithmetic_aux : false_\n\t{};\n\n\tTpl<Typ T> struct is_arithmetic_aux<T, true> : true_\n\t{};\n\n\tTpl<Typ T, bool = is_referenceable_v<T>> struct add_rvalue_reference_impl\n\t\t: type_identity<T&&>\n\t{};\n\tTpl<Typ T> struct add_rvalue_reference_impl<T, false> : type_identity<T>\n\t{};\n\n\tTpl<Typ T, bool = is_referenceable_v<T>> struct add_lvalue_reference_impl\n\t\t: type_identity<T&>\n\t{};\n\tTpl<Typ T> struct add_lvalue_reference_impl<T, false> : type_identity<T>\n\t{};\n\n\tTpl<Typ T> char\n\ttest(int T::*);\n\tstruct two\n\t{\n\t\tchar c[2];\n\t};\n\tTpl<Typ T> two\n\ttest(...);\n\n\tTpl<Typ T> struct is_pointer_helper : false_\n\t{};\n\tTpl<Typ T> struct is_pointer_helper<T*> : true_\n\t{};\n\n\n\tTpl<Typ T, bool is_function_type = false> struct add_pointer\n\t\t: type_identity<remove_reference_t<T>*>\n\t{};\n\n\tTpl<Typ T> struct add_pointer<T, true> : type_identity<T>\n\t{};\n\n\tTpl<Typ T, Typ... Args> struct add_pointer<T(Args...), true>\n\t\t: type_identity<T (*)(Args...)>\n\t{};\n\n\tTpl<Typ T, Typ... Args> struct add_pointer<T(Args..., ...), true>\n\t\t: type_identity<T (*)(Args..., ...)>\n\t{};\n\n\tTpl<Typ T, Typ... _Args> struct is_nt_constructible_impl\n\t\t: bool_<noexcept(T(declval<_Args>()...))>\n\t{};\n\n\tTpl<Typ T, Typ _Arg> struct is_nt_constructible_impl<T, _Arg>\n\t\t: bool_<noexcept(static_cast<T>(declval<_Arg>()))>\n\t{};\n\n\tTpl<Typ T> struct is_nt_constructible_impl<T>\n\t\t: is_nothrow_default_constructible<T>\n\t{};\n\n} // namespace Rider::Faiz::detail\n\nnamespace Rider::Faiz\n{\n\n\tTpl<Typ... B> using conjunction = logic::and_<B...>;\n\tTpl<Typ... B> inline cexp bool conjunction_v = conjunction<B...>::value;\n\n\tTpl<Typ... B> using disjunction = logic::or_<B...>;\n\tTpl<Typ... B> inline cexp bool disjunction_v = disjunction<B...>::value;\n\n\tTpl<Typ B> using negation = logic::not_<B>;\n\tTpl<Typ B> inline cexp bool negation_v = negation<B>::value;\n\n\t// clang-format on\n\n\tTpl<Typ T> struct remove_reference : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_reference<T&> : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_reference<T&&> : type_identity<T>\n\t{};\n\n\tTpl<Typ T> struct remove_const : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_const<const T> : type_identity<T>\n\t{};\n\n\tTpl<Typ T> struct remove_volatile : type_identity<T>\n\t{};\n\n\tTpl<Typ T> struct remove_volatile<volatile T> : type_identity<T>\n\t{};\n\n\tTpl<Typ T> struct remove_extent : type_identity<T>\n\t{};\n\n\tTpl<Typ T> struct remove_extent<T[]> : type_identity<T>\n\t{};\n\n\tTpl<Typ T, size_t N> struct remove_extent<T[N]> : type_identity<T>\n\t{};\n\tTpl<Typ T> using remove_extent_t = _t<remove_extent<T>>;\n\n\tTpl<Typ T> struct remove_all_extents;\n\tTpl<Typ T> using remove_all_extents_t = _t<remove_all_extents<T>>;\n\n\tTpl<Typ T> struct remove_all_extents : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_all_extents<T[]>\n\t\t: type_identity<remove_all_extents_t<T>>\n\t{};\n\tTpl<Typ T, size_t V> struct remove_all_extents<T[V]>\n\t\t: type_identity<remove_all_extents_t<T>>\n\t{};\n\n\n\t// Provides the member typedef type which is the type pointed to by T,\n\t// or, if T is not a pointer, then type is the same as T.\n\t// ```cpp\n\t// print_is_same<int, remove_pointer<int*>::type>();  // true\n\t// print_is_same<int, remove_pointer<int**>::type>(); // false\n\t// ```\n\tTpl<Typ T> struct remove_pointer : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_pointer<T*> : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_pointer<T* const> : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_pointer<T* volatile> : type_identity<T>\n\t{};\n\tTpl<Typ T> struct remove_pointer<T* const volatile> : type_identity<T>\n\t{};\n\n\tTpl<Typ T> using remove_cv_t = _t<remove_cv<T>>;\n\tTpl<Typ T> using remove_const_t = _t<remove_const<T>>;\n\tTpl<Typ T> using remove_volatile_t = _t<remove_volatile<T>>;\n\tTpl<Typ T> using remove_extent_t = _t<remove_extent<T>>;\n\tTpl<Typ T> using remove_pointer_t = _t<remove_pointer<T>>;\n\n\t// If the type **T** is a reference type, provides the member typedef\n\t// type which is the type referred to by\n\t// **T** with its topmost cv-qualifiers removed. Otherwise type is **T**\n\t// with its topmost cv-qualifiers removed.\n\t//\n\t// Removing cvref does most of what decay does, but doesn't convert\n\t// function types and array types to pointers.\n\n\tTpl<Typ T> struct remove_cvref : remove_cv<remove_reference_t<T>>\n\t{};\n\n\t// Tpl<Typ T> using remove_cvref_t = typename remove_cvref<T>::type;\n\n\t/******************** is *********************/\n\n\t// If T and U name the same type (including const/volatile\n\t// qualifications), provides the member constant value equal to true.\n\t// Otherwise value is false.\n\tTpl<Typ T, Typ U> struct is_same : false_\n\t{};\n\n\t// If T and U name the same type (including const/volatile\n\t// qualifications), provides the member constant value equal to true.\n\t// Otherwise value is false.\n\tTpl<Typ T> struct is_same<T, T> : true_\n\t{};\n\n\n\tTpl<Typ T> struct is_null_pointer : is_same<nullptr_t, remove_cv_t<T>>\n\t{};\n\tIS(null_pointer)\n\n\tTpl<Typ T> struct is_const : false_\n\t{};\n\tTpl<Typ T> struct is_const<const T> : true_\n\t{};\n\n\tIS_NOT_ARE_ANY(const)\n\n\tTpl<Typ T> struct is_reference : false_\n\t{};\n\tTpl<Typ T> struct is_reference<T&> : true_\n\t{};\n\tTpl<Typ T> struct is_reference<T&&> : true_\n\t{};\n\n\tIS_NOT_ARE_ANY(reference)\n\n\tTpl<Typ T> struct is_function\n\t\t: bool_<not_const_v<T const> and not_reference_v<T>>\n\t{};\n\n\tTpl<Typ T> struct is_volatile : false_\n\t{};\n\tTpl<Typ T> struct is_volatile<T volatile> : true_\n\t{};\n\tTpl<Typ T, size_t N> struct is_volatile<T volatile[N]> : true_\n\t{};\n\tTpl<Typ T> struct is_volatile<T volatile[]> : true_\n\t{};\n\n\tIS_NOT_ARE_ANY(volatile)\n\n\tIS_NOT_ARE_ANY(function)\n\n\tTpl<Typ T> struct is_floating_point : detail::is_floating_point_aux<T>\n\t{};\n\n\n\tIS_NOT_ARE_ANY(floating_point)\n\n\t// Checks whether T is an integral type. Provides the member constant\n\t// value which is equal to true, if T is the type bool, char, char16_t,\n\t// char32_t, wchar_t, short, int, long, long long, or any\n\t// implementation-defined extended integer types, including any signed,\n\t// unsigned, and cv-qualified variants. Otherwise, value is equal to\n\t// false.\n\n\tTpl<Typ T> struct is_integral : detail::is_integral_aux<T>\n\t{};\n\n\tIS_NOT_ARE_ANY(integral)\n\n\t//  If T is an arithmetic type (that is, an integral type or a\n\t// floating-point type) or a cv-qualified version thereof, provides the\n\t// member constant value equal true. For any other type, value is false.\n\t//\n\t// gcc may complains, latest msvc/clang compiles happily\n\tTpl<Typ T> struct is_arithmetic : detail::is_arithmetic_aux<T>\n\t{};\n\n\tIS_NOT_ARE_ANY(arithmetic)\n\n\n\t// Checks whether T is **a pointer to object** or **a pointer to\n\t// function** (but not a pointer to member/member function). Provides\n\t// the member constant value which is equal to true, if T is a\n\t// object/function pointer type. Otherwise, value is equal to false.\n\tTpl<Typ T> struct is_pointer : detail::is_pointer_helper<remove_cv_t<T>>\n\t{};\n\n\tIS_NOT_ARE_ANY(pointer)\n\n\tTpl<Typ T> struct is_lvalue_reference : false_\n\t{};\n\tTpl<Typ T> struct is_lvalue_reference<T&> : true_\n\t{};\n\n\tTpl<Typ T> struct is_rvalue_reference : false_\n\t{};\n\tTpl<Typ T> struct is_rvalue_reference<T&&> : true_\n\t{};\n\n\n\tTpl<Typ T> struct is_object\n\t\t: bool_<not_reference_v<T> and not_void_v<T> and not_function_v<T>>\n\t{};\n\n\n\tTpl<Typ T, unsigned N = 0> struct extent : size_t_<0>\n\t{};\n\n\tTpl<Typ T> struct extent<T[], 0> : size_t_<0>\n\t{};\n\n\tTpl<Typ T, unsigned N> struct extent<T[], N> : extent<T, N - 1>\n\t{};\n\n\tTpl<Typ T, size_t I> struct extent<T[I], 0> : size_t_<I>\n\t{};\n\n\tTpl<Typ T, size_t I, unsigned N> struct extent<T[I], N> : extent<T, N - 1>\n\t{};\n\tTpl<Typ T, unsigned N = 0> inline cexp size_t extent_v\n\t\t= extent<T, N>::value;\n\n\t//  If T is an object type or a function type that has no cv- or ref-\n\t//  qualifier (since C++17), provides a member typedef type which is T&. If\n\t//  T is an rvalue reference to some type U, then type is U&. Otherwise,\n\t//  type is T.\n\n\n\t// FIXME: add_rvalue_reference_impl is a workaround here, otherwise forward\n\t// declaration can also not solve type dependency.\n\tTpl<Typ T> struct add_rvalue_reference\n\t\t: detail::add_rvalue_reference_impl<T>\n\t{};\n\n\tTpl<Typ T> struct add_lvalue_reference\n\t\t: detail::add_lvalue_reference_impl<T>\n\t{};\n\n\n\t// Converts any type **T** to a reference type, making it possible to\n\t// use member functions in *decltype* expressions without the need to go\n\t// through constructors.\n\t//\n\t// *declval* is commonly used in tpls where acceptable Tpl\n\t// parameters may have no constructor in common, but have the same\n\t// member function whose return type is needed.\n\t//\n\t// Note that because no definition exists for *declval*, it can only be\n\t// used in unevaluated contexts; it is an error to evaluate an\n\t// expression that contains this function. Formally, the program is\n\t// *ill-formed* if this function is *odr-used*.\n\t//\n\t// Cannot be called and thus never returns a value. The return type is\n\t// T&& unless **T** is (possibly cv-qualified) void, in which case the\n\t// return type is **T**.\n\t//\n\t// return `add_rvalue_reference_t<T>` is for reference collapsing\n\n\tTpl<Typ T> struct add_cv : type_identity<const volatile T>\n\t{};\n\n\tTpl<Typ T> struct add_const : type_identity<const T>\n\t{};\n\n\tTpl<Typ T> struct add_volatile : type_identity<volatile T>\n\t{};\n\n\tTpl<Typ T> using add_cv_t = _t<add_cv<T>>;\n\tTpl<Typ T> using add_const_t = _t<add_const<T>>;\n\tTpl<Typ T> using add_volatile_t = _t<add_volatile<T>>;\n\n\t// p0007r0\n\t// https://stackoverflow.com/questions/34566063/why-is-the-const-overload-of-as-const-deleted\n\t// Forms lvalue reference to const type of t\n\tTpl<Typ T> cexp add_const_t<T>&\n\tas_const(T& t) noexcept;\n\n\t//  const rvalue reference overload is deleted to disallow rvalue arguments\n\tTpl<Typ T> void\n\tas_const(const T&&)\n\t\t= delete;\n\n\t// TODO: check whether standard has as_cref_t\n\tTpl<Typ T, Typ R = remove_reference_t<T>> using as_cref_t\n\t\t= add_lvalue_reference_t<add_const_t<R>>;\n\n\tTpl<Typ T> struct is_signed : detail::is_signed_impl<is_arithmetic_v<T>, T>\n\t{};\n\n\n\t// using std::is_signed_v;\n\t// IS_NOT_ARE_ANY(signed)\n\tIS_NOT_ARE_ANY(signed)\n\n\tTpl<Typ T> cexp bool is_unsigned_v = not_signed_v<T> and is_arithmetic_v<T>;\n\tTpl<Typ T> struct is_unsigned : bool_<is_unsigned_v<T>>\n\t{};\n\n\t// TODO: add support for compiler extension larger signed.\n\t// XXX: I don't want support non-standard extension now.\n\tTpl<Typ T> struct make_signed\n\t{\n\tprivate:\n\t\tstatic_assert((is_integral_v<T> or is_enum_v<T>),\n\t\t\t\"The Tpl argument to make_signed must be an integer or enum \"\n\t\t\t\"type.\");\n\t\tstatic_assert(not_same_v<remove_cv_t<T>, bool>,\n\t\t\t\"The Tpl argument to make_signed must not be the type bool.\");\n\n\t\tusing t_no_cv = remove_cv_t<T>;\n\n\t\tstatic cfn\n\t\tbase_integer_type_impl()\n\t\t{\n\t\t\tcIf(is_signed_v<\n\t\t\t\t\tT> and is_integral_v<T> and not_any_v<t_no_cv, char, wchar_t, bool>)\n\t\t\t{\n\t\t\t\treturn type_identity<T>{};\n\t\t\t}\n\t\t\tcElseIf(\n\t\t\t\tis_integral_v<T> and not_any_v<t_no_cv, char, wchar_t, bool>)\n\t\t\t{\n\t\t\t\tcIf(is_same_v<t_no_cv, unsigned char>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<signed char>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(is_same_v<t_no_cv, unsigned short>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<signed short>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(is_same_v<t_no_cv, unsigned int>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<int>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(is_same_v<t_no_cv, unsigned long>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<long>{};\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<long long>{};\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcIf(sizeof(t_no_cv) == sizeof(unsigned char))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<signed char>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(sizeof(t_no_cv) == sizeof(unsigned short))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<signed short>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(sizeof(t_no_cv) == sizeof(unsigned int))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<int>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(sizeof(t_no_cv) == sizeof(unsigned long))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<long>{};\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<long long>{};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tusing base_integer_type = _t<decltype(base_integer_type_impl())>;\n\n\t\t// Add back any const qualifier:\n\t\tusing const_base_integer_type = meta::\n\t\t\tif_<is_const<T>, add_const_t<base_integer_type>, base_integer_type>;\n\n\tpublic:\n\t\t// Add back any volatile qualifier:\n\t\tusing type = meta::if_<is_volatile<T>,\n\t\t\tadd_volatile_t<const_base_integer_type>,\n\t\t\tconst_base_integer_type>;\n\t};\n\n\tTpl<Typ T> struct make_unsigned\n\t{\n\tprivate:\n\t\tstatic_assert(is_integral_v<T> or is_enum_v<T>,\n\t\t\t\"The Tpl argument to make_unsigned must be an integer or enum \"\n\t\t\t\"type.\");\n\t\tstatic_assert(not_same_v<remove_cv_t<T>, bool>,\n\t\t\t\"The Tpl argument to make_unsigned must not be the type \"\n\t\t\t\"bool\");\n\n\t\tusing t_no_cv = remove_cv_t<T>;\n\n\t\t// clang-format off\n\t\tstatic cfn\n\t\tbase_integer_type_impl()\n\t\t{\n\t\t\tcIf(is_unsigned_v<T> and\n\t\t\t\t\t\t is_integral_v<T> and\n\t\t\t\t\t\t not_any_v<t_no_cv, char, wchar_t, bool>)\n\t\t\t{\n\t\t\t\treturn type_identity<T>{};\n\t\t\t}\n\t\t\tcElseIf(is_integral_v<T> and\n\t\t\t\t\t\t\t  not_any_v<t_no_cv, char, wchar_t, bool>)\n\t\t\t{\n\t\t\t\tcIf(is_same_v<t_no_cv, signed char>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned char>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(is_same_v<t_no_cv, short>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned short>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(is_same_v<t_no_cv, int>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned int>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(is_same_v<t_no_cv, long>)\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned long>{};\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned long long>{};\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcIf(sizeof(t_no_cv) == sizeof(unsigned char))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned char>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(sizeof(t_no_cv) == sizeof(unsigned short))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned short>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(sizeof(t_no_cv) == sizeof(unsigned int))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned int>{};\n\t\t\t\t}\n\t\t\t\tcElseIf(sizeof(t_no_cv) == sizeof(unsigned long))\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned long>{};\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn type_identity<unsigned long long>{};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// clang-format on\n\n\t\tusing base_integer_type = _t<decltype(base_integer_type_impl())>;\n\n\t\tusing const_base_integer_type = meta::\n\t\t\tif_<is_const<T>, add_const_t<base_integer_type>, base_integer_type>;\n\n\tpublic:\n\t\t// Add back any volatile qualifier:\n\t\tusing type = meta::if_<is_volatile<T>,\n\t\t\tadd_volatile_t<const_base_integer_type>,\n\t\t\tconst_base_integer_type>;\n\t};\n\n\tTpl<Typ T> using make_unsigned_t = _t<make_unsigned<T>>;\n\n\tTpl<Typ T> using make_signed_t = _t<make_signed<T>>;\n\n\tTpl<bool B, Typ T> struct enable_if\n\t{};\n\n\tTpl<Typ T> struct enable_if<true, T> : type_identity<T>\n\t{};\n\n\tTpl<Typ T> inline cexp bool is_array_v = false;\n\tTpl<Typ T> inline cexp bool is_array_v<T[]> = true;\n\tTpl<Typ T, size_t N> inline cexp bool is_array_v<T[N]> = true;\n\n\tTpl<Typ T> struct is_array : bool_<is_array_v<T>>\n\t{};\n\n\tNOT_ARE_ANY(array)\n\n\t// If the imaginary function definition tTo test() { return\n\t// std::declval<tFrom>(); } is well-formed, (that is, either\n\t// std::declval<tFrom>() can be converted to tTo using implicit conversions,\n\t// or both tFrom and tTo are possibly cv-qualified void), provides the\n\t// member constant value equal to true. Otherwise value is false. For the\n\t// purposes of this check, the use of std::declval in the return statement\n\t// is not considered an odr-use.\n\t//\n\t//  Access checks are performed as if from a context unrelated to either\n\t// type. Only the validity of the immediate context of the expression in the\n\t// return statement (including conversions to the return type) is\n\t// considered.\n\t// // using namespace logic;\n\t// Tpl<Typ tFrom, Typ tTo>\n\t// cexp bool is_convertible_v = or_<\n\t// \tand_<or_<is_void<tFrom>, is_function<tTo>, is_array<tTo>>,\n\t// is_void<tTo>>, \tis_detected<is_convertible_helper, tFrom, tTo>>::value;\n\t//\n\tTpl<Typ tTo1> static void test_aux(tTo1) noexcept;\n\n\tTpl<Typ tFrom, Typ tTo> using is_convertible_helper\n\t\t= decltype(test_aux<tTo>(declval<tFrom>()));\n\n\tTpl<Typ tFrom, Typ tTo> cfn\n\tmy_is_convertible()\n\t{\n\t\tcIf(disjunction_v<is_void<tFrom>, is_function<tTo>, is_array<tTo>>)\n\t\t{\n\t\t\treturn is_void<tTo>();\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn is_detected<is_convertible_helper, tFrom, tTo>();\n\t\t}\n\t}\n\n\tTpl<Typ tFrom, Typ tTo> struct is_convertible\n\t\t: decltype(my_is_convertible<tFrom, tTo>())\n\t{};\n\n\tBI_IS_NOT_ARE_ANY(convertible)\n\tBI_NOT_ALL(convertible)\n\n\t// TODO: use detection idiom implement is_convertible\n\t// If T is an object or reference type and the variable definition T\n\t// obj(std::declval<Args>()...); is well-formed, provides the member\n\t// constant value equal to true. In all other cases, value is false.\n\n\t// FIXME: the codes below cannot pass tests somehow\n\t// Tpl<Typ T, class, class...>\n\t// struct is_constructible_impl : false_\n\t// {};\n\t// Tpl<Typ T, class... Us>\n\t// struct is_constructible_impl<T,\n\t// \tdecltype(::new(declval<void*>()) T(declval<Us&>()...)),\n\t// \tUs...> : true_\n\t// {};\n\t// Tpl<Typ T, class... Us>\n\t// struct is_constructible : is_constructible_impl<T, void, Us...>\n\t// {};\n\n\tTpl<Typ Tp> struct is_copy_constructible\n\t\t: is_constructible<Tp, as_cref_t<Tp>>\n\t{};\n\n\tIS_NOT_ARE_ANY(copy_constructible)\n\n\tTpl<Typ T> inline cexp size_t rank_v = 0;\n\tTpl<Typ T> inline cexp size_t rank_v<T[]> = 1u + rank_v<T>;\n\tTpl<Typ T, size_t N> inline cexp size_t rank_v<T[N]> = 1u + rank_v<T>;\n\n\tTpl<Typ T> struct rank : size_t_<rank_v<T>>\n\t{};\n\n\t// If **T** is a reference type, then provides the member typedef type\n\t// which is a pointer to the referred type. Otherwise, if **T** names an\n\t// object type, a function type that is not **cv-** or **ref-qualified**\n\t// (since C++17), or a (possibly **cv-qualified**) void type, provides\n\t// the member typedef type which is the type T*. Otherwise (if T is a\n\t// **cv-** or **ref-qualified** function type), provides the member\n\t// typedef type which is the type **T**\n\t//\n\t// * type:\tpointer to T or to the type referenced by T\n\tTpl<Typ T> struct add_pointer : detail::add_pointer<T, is_function_v<T>>\n\t{};\n\tTpl<Typ T> using add_pointer_t = _t<add_pointer<T>>;\n\n\tTpl<Typ T, Typ U = remove_reference_t<T>, Typ E = remove_cv_t<U>> fn\n\tdecay_impl()\n\t{\n\t\tcIf(not_referenceable_v<T>)\n\t\t{\n\t\t\treturn type_identity<E>();\n\t\t}\n\t\tcElseIf(is_array_v<U>)\n\t\t{\n\t\t\treturn type_identity<add_pointer_t<remove_extent_t<U>>>();\n\t\t}\n\t\tcElseIf(is_function_v<U>)\n\t\t{\n\t\t\treturn type_identity<add_pointer_t<U>>();\n\t\t}\n\t\tcElse\n\t\t{\n\t\t\treturn type_identity<E>();\n\t\t}\n\t}\n\n\tTpl<Typ T> struct decay : decltype(decay_impl<T>())\n\t{};\n\n\tTpl<Typ T> using decay_t = _t<decay<T>>;\n\n\tTpl<Typ T, Typ Arg> struct is_assignable\n\t\t: detail::is_assignable_imp<T, Arg, void>\n\t{};\n\n\t// If Derived is derived from Base or if both are the same non-union class\n\t// (in both cases ignoring cv-qualification), provides the member constant\n\t// value equal to true. Otherwise value is false.\n\t//\n\t//  If both Base and Derived are non-union class types, and they are not the\n\t// same type (ignoring cv-qualification), Derived shall be a complete type;\n\t// otherwise the behavior is undefined.\n\t//\n\t// Faiz::is_base_of<A, B>::value is true even if A is a private, protected,\n\t// or ambiguous base class of B. In many situations,\n\t// Faiz::is_convertible<B*, A*> is the more appropriate test.\n\t//\n\t// Although no class is its own base, Faiz::is_base_of<T, T>::value is true\n\t// because the intent of the trait is to model the \"is-a\" relationship, and\n\t// T is a T. Despite that, Faiz::is_base_of<int, int>::value is false\n\t// because only classes participate in the relationship that this trait\n\t// models.\n\tTpl<Typ Base, Typ Derived> struct is_base_of\n\t\t: meta::if_<logic::and_<is_class<Base>, is_class<Derived>>,\n\t\t\t  detail::pre_is_base_of2<Base, Derived>,\n\t\t\t  false_>\n\t{};\n\tTpl<Typ Base, Typ Derived> inline cexp bool is_base_of_v\n\t\t= is_base_of<Base, Derived>::value;\n\n\n\tTpl<Typ T> struct is_member_pointer\n\t\t: detail::is_member_pointer_helper<remove_cv_t<T>>\n\t{};\n\n\tIS(member_pointer)\n\t// If `T` is a scalar type (that is a possibly **cv-qualified** arithmetic,\n\t// pointer, pointer to member, enumeration, or `Faiz::nullptr_t` type),\n\t// provides the member constant value equal `true`. For any other type,\n\t// value is `false`.\n\t//\n\t// Each individual memory location in the C++ memory model, including the\n\t// hidden memory locations used by language features (e.g virtual table\n\t// pointer), has scalar type (or is a sequence of adjacent bit-fields of\n\t// non-zero length). Sequencing of side-effects in expression evaluation,\n\t// interthread synchronization, and dependency ordering are all defined in\n\t// terms of individual scalar objects.\n\t//\n\tTpl<Typ T> struct is_scalar : disjunction<is_arithmetic<T>,\n\t\t\t\t\t\t\t\t\t  is_enum<T>,\n\t\t\t\t\t\t\t\t\t  is_pointer<T>,\n\t\t\t\t\t\t\t\t\t  is_member_pointer<T>,\n\t\t\t\t\t\t\t\t\t  is_null_pointer<T>>\n\t{};\n\n\tIS_NOT_ARE_ANY(scalar)\n\n\tTpl<Typ T> struct is_member_function_pointer_helper : false_\n\t{};\n\n\tTpl<Typ T, Typ U> struct is_member_function_pointer_helper<T U::*>\n\t\t: is_function<T>\n\t{};\n\t//\n\t//  Checks whether T is a non-static member function pointer. Provides the\n\t// member constant value which is equal to true, if T is a non-static member\n\t// function pointer type. Otherwise, value is equal to false.\n\tTpl<Typ T> struct is_member_function_pointer\n\t\t: is_member_function_pointer_helper<remove_cv_t<T>>\n\t{};\n\n\tIS_NOT_ARE_ANY(member_function_pointer)\n\n\t// Checks whether T is a non-static member object. Provides the member\n\t// constant value which is equal to true, if T is a non-static member object\n\t// type. Otherwise, value is equal to false.\n\tTpl<Typ T> struct is_member_object_pointer\n\t\t: bool_<is_member_pointer_v<T> and not_member_function_pointer_v<T>>\n\t{};\n\n\tIS_NOT_ARE_ANY(member_object_pointer)\n\n\t// Given two (possibly identical) types Base and Derived,\n\t// is_base_of<Base, Derived>::value == true if and only if Base is a\n\t// direct or indirect base class of Derived. This is like\n\t// is_base_of<Base, Derived> but returns false if Derived is the same as\n\t// Base. So is_derived is true only if Derived is actually a subclass of\n\t// Base and not Base itself.\n\t//\n\t// is_derived may only be applied to complete types.\n\t//\n\t// Example usage:\n\t//     is_derived<int, int>::value             => false\n\t//     is_derived<int, bool>::value            => false\n\t//     is_derived<Parent, Child>::value        => true\n\t//     is_derived<Child, Parent>::value        => false\n\tTpl<Typ Base, Typ Derived> struct is_derived\n\t\t: bool_<\n\t\t\t  is_base_of_v<Base,\n\t\t\t\t  Derived> and not_same_v<remove_cv_t<Base>, remove_cv_t<Derived>>>\n\t{};\n\n\tBI_IS_NOT_ARE_ANY(derived)\n\n\tTpl<Typ T> struct is_polymorphic : detail::is_polymorphic_impl<T, void*>\n\t{};\n\n\tIS(polymorphic)\n\n\tTpl<Typ T> struct is_copy_assignable\n\t\t: is_assignable<add_lvalue_reference_t<T>, as_cref_t<T>>\n\t{};\n\n\tIS_NOT_ARE_ANY(copy_assignable)\n\n\t// Tpl<Typ... T >\n\t// inline cexp bool are_copy_assignable_v = (is_copy_assignable_v<T> &&\n\t// ...);\n\n\t// Tpl<Typ... T>\n\t// struct are_copy_assignable : bool_<are_copy_assignable_v<T...>>\n\t// {\n\t// };\n\n\tTpl<Typ T> struct is_trivially_copy_assignable\n\t\t: is_trivially_assignable<add_lvalue_reference_t<T>, as_cref_t<T>>\n\t{};\n\n\tIS_NOT_ARE_ANY(trivially_copy_assignable)\n\n\tTpl<bool, Typ T, Typ A> struct is_nothrow_assignable_aux;\n\n\tTpl<Typ T, Typ A> struct is_nothrow_assignable_aux<false, T, A> : false_\n\t{};\n\n\tTpl<Typ T> using move_assignment_t\n\t\t= decltype(declval<T&>() = declval<T&&>());\n\n\tTpl<Typ T> inline cexp bool is_move_assignable_v\n\t\t= is_detected_v<move_assignment_t, T>;\n\n\tTpl<Typ T> struct is_move_assignable : bool_<is_move_assignable_v<T>>\n\t{};\n\n\tNOT_ARE_ANY(move_assignable)\n\n\t// // clang-format off\n\t// Tpl<Typ T>\n\t// inline cexp bool is_nothrow_move_assignable_v\n\t// \t= is_move_assignable_v<T> and noexcept(declval<T&>() = declval<T&&>());\n\t// // clang-format on\n\n\t// Tpl<Typ T>\n\t// struct is_nothrow_move_assignable :\n\t// bool_<is_nothrow_move_assignable_v<T>>\n\t// {};\n\n\tTpl<Typ T> struct is_nothrow_move_assignable\n\t\t: is_nothrow_assignable<add_lvalue_reference_t<T>,\n\t\t\t  add_rvalue_reference_t<T>>\n\t{};\n\n\tIS_NOT_ARE_ANY(nothrow_move_assignable)\n\n\tTpl<Typ T, Typ A> struct is_nothrow_assignable_aux<true, T, A>\n\t\t: bool_<noexcept(declval<T>() = declval<A>())>\n\t{};\n\n\tTpl<Typ T, Typ A> struct is_nothrow_assignable\n\t\t: is_nothrow_assignable_aux<is_assignable_v<T, A>, T, A>\n\t{};\n\n\tTpl<Typ T> struct is_nothrow_copy_assignable\n\t\t: is_nothrow_assignable<add_lvalue_reference_t<T>, as_cref_t<T>>\n\t{};\n\n\n\tIS_NOT_ARE_ANY(nothrow_copy_assignable)\n\n\tTpl<Typ T> struct is_unknown_bound_array : false_\n\t{};\n\tTpl<Typ T> struct is_unknown_bound_array<T[]> : true_\n\t{};\n\n\tIS_NOT_ARE_ANY(unknown_bound_array)\n\n\tTpl<Typ T, Typ U = remove_all_extents_t<T>> using has_dtor\n\t\t= decltype(declval<U>().~U());\n\n\t// clang-format off\n    // FIXME \\\\\\ fix compiler.....  gcc has bug here, I post a thread here: https://stackoverflow.com/questions/53456848/implement-is-destructible-with-detected-idiomhttps://stackoverflow.com/questions/53456848/implement-is-destructible-with-detected-idiom\n    // Tpl<Typ T>\n    // cexp bool is_destructible_v =\n    // \tis_reference_v<T> || (!(is_void_v<T> || is_function_v<T> || is_unknown_bound_array_v<T>) and is_object_v<T> and is_detected_v<has_dtor, T>);\n\n #if BOOST_COMP_CLANG or BOOST_COMP_MSVC\n    Tpl<Typ T>\n    cexp bool is_destructible_v =\n        (is_detected_v<has_dtor,\n           T>\n       or is_reference_v<T>)\n    and not_unknown_bound_array_v<T>\n        and not_function_v<T>;\n\n #elif BOOST_COMP_GNUC\n    Tpl<Typ T>\n    cexp bool\n    my_is_destructible()\n    {\n        cIf(is_reference_v<T>)\n        {\n            return true;\n        }\n        cElseIf(\n            is_same_v<remove_cv_t<T>,\n                void> || is_function_v<T> || is_unknown_bound_array<T>::value)\n        {\n            return false;\n        }\n        cElseIf(is_object_v<T>)\n        {\n            return is_detected_v<has_dtor, T>;\n        }\n        else\n        {\n            return false;\n        }\n    }\n    Tpl<Typ T>\n    cexp bool is_destructible_v = my_is_destructible<T>();\n #endif\n\t// clang-format on\n\tTpl<Typ T> struct is_destructible : bool_<is_destructible_v<T>>\n\t{};\n\n\tTpl<Typ T> inline cexp bool is_nothrow_destructible_v\n\t\t= is_destructible_v<T> and noexcept(is_destructible_v<T>);\n\tTpl<Typ T> struct is_nothrow_destructible\n\t\t: bool_<is_nothrow_destructible_v<T>>\n\t{};\n\n\n\tTpl<Typ T> struct alignment_of : size_t_<alignof(T)>\n\t{};\n\n#ifdef _WIN32\n\tenum class endian\n\t{\n\t\tlittle = 0,\n\t\tbig = 1,\n\t\tnative = little\n\t};\n#endif\n\n\n\t/// is_nothrow_constructible\n\tTpl<Typ T, Typ... _Args> struct is_nothrow_constructible\n\t\t: logic::and_<is_constructible<T, _Args...>,\n\t\t\t  detail::is_nt_constructible_impl<T, _Args...>>\n\t{};\n\n\tTpl<Typ T,\n\t\tbool = is_referenceable_v<T>> struct is_nothrow_copy_constructible_impl;\n\n\tTpl<Typ T> struct is_nothrow_copy_constructible_impl<T, false> : false_\n\t{};\n\n\tTpl<Typ T> struct is_nothrow_copy_constructible_impl<T, true>\n\t\t: is_nothrow_constructible<T, const T&>\n\t{};\n\n\t/// is_nothrow_copy_constructible\n\tTpl<Typ T> struct is_nothrow_copy_constructible\n\t\t: is_nothrow_copy_constructible_impl<T>\n\t{};\n\n\n\tIS_NOT_ARE_ANY(nothrow_copy_constructible)\n\n\tnamespace detail\n\t{\n\t\tTpl<Typ T,\n\t\t\tbool\n\t\t\t= is_referenceable_v<T>> struct is_nothrow_move_constructible_impl;\n\n\t\tTpl<Typ T> struct is_nothrow_move_constructible_impl<T, false> : false_\n\t\t{};\n\n\t\tTpl<Typ T> struct is_nothrow_move_constructible_impl<T, true>\n\t\t\t: is_nothrow_constructible<T, T&&>\n\t\t{};\n\t} // namespace detail\n\n\tTpl<Typ T, Typ... _Args> constexpr bool is_nothrow_constructible_v\n\t\t= is_nothrow_constructible<T, _Args...>::value;\n\n\tPACK_ARE(nothrow_constructible)\n\n\tTpl<Typ T> struct is_nothrow_move_constructible\n\t\t: detail::is_nothrow_move_constructible_impl<T>\n\t{};\n\tIS_NOT_ARE_ANY(nothrow_move_constructible)\n} // namespace Rider::Faiz\n\n#endif\n", "meta": {"hexsha": "5bf29af3fec0a748397e4d5100c914e3d411fe1c", "size": 35752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rider/faiz/type_traits.hpp", "max_stars_repo_name": "FirstLoveLife/Rider-Faiz", "max_stars_repo_head_hexsha": "ffa1ec3b335b836bd81600fb67587734325b2ce6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T08:36:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T08:30:59.000Z", "max_issues_repo_path": "include/rider/faiz/type_traits.hpp", "max_issues_repo_name": "FirstLoveLife/Faiz", "max_issues_repo_head_hexsha": "ffa1ec3b335b836bd81600fb67587734325b2ce6", "max_issues_repo_licenses": ["MIT"], "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/rider/faiz/type_traits.hpp", "max_forks_repo_name": "FirstLoveLife/Faiz", "max_forks_repo_head_hexsha": "ffa1ec3b335b836bd81600fb67587734325b2ce6", "max_forks_repo_licenses": ["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.6451077944, "max_line_length": 256, "alphanum_fraction": 0.6919612889, "num_tokens": 10594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13477591742295678, "lm_q2_score": 0.03410042828905513, "lm_q1q2_score": 0.0045959165071731535}}
{"text": "// Copyright John Maddock 2008.\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_TR1_HPP\n#define BOOST_MATH_TR1_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#ifdef __cplusplus\n\n#include <boost/config.hpp>\n#include <boost/static_assert.hpp>\n\nnamespace boost{ namespace math{ namespace tr1{ extern \"C\"{\n\n#endif // __cplusplus\n\n#ifdef BOOST_HAS_DECLSPEC // defined in config system\n// we need to import/export our code only if the user has specifically\n// asked for it by defining either BOOST_ALL_DYN_LINK if they want all boost\n// libraries to be dynamically linked, or BOOST_MATH_TR1_DYN_LINK\n// if they want just this one to be dynamically liked:\n#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_MATH_TR1_DYN_LINK)\n// export if this is our own source, otherwise import:\n#ifdef BOOST_MATH_TR1_SOURCE\n# define BOOST_MATH_TR1_DECL __declspec(dllexport)\n#else\n# define BOOST_MATH_TR1_DECL __declspec(dllimport)\n#endif  // BOOST_MATH_TR1_SOURCE\n#endif  // DYN_LINK\n#endif  // BOOST_HAS_DECLSPEC\n//\n// if BOOST_MATH_TR1_DECL isn't defined yet define it now:\n#ifndef BOOST_MATH_TR1_DECL\n#define BOOST_MATH_TR1_DECL\n#endif\n\n//\n// Now set up the libraries to link against:\n//\n#if !defined(BOOST_MATH_TR1_NO_LIB) && !defined(BOOST_MATH_TR1_SOURCE) \\\n   && !defined(BOOST_ALL_NO_LIB) && defined(__cplusplus)\n#  define BOOST_LIB_NAME boost_math_c99\n#  if defined(BOOST_MATH_TR1_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)\n#     define BOOST_DYN_LINK\n#  endif\n#  include <boost/config/auto_link.hpp>\n#endif\n#if !defined(BOOST_MATH_TR1_NO_LIB) && !defined(BOOST_MATH_TR1_SOURCE) \\\n   && !defined(BOOST_ALL_NO_LIB) && defined(__cplusplus)\n#  define BOOST_LIB_NAME boost_math_c99f\n#  if defined(BOOST_MATH_TR1_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)\n#     define BOOST_DYN_LINK\n#  endif\n#  include <boost/config/auto_link.hpp>\n#endif\n#if !defined(BOOST_MATH_TR1_NO_LIB) && !defined(BOOST_MATH_TR1_SOURCE) \\\n   && !defined(BOOST_ALL_NO_LIB) && defined(__cplusplus) \\\n   && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS)\n#  define BOOST_LIB_NAME boost_math_c99l\n#  if defined(BOOST_MATH_TR1_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)\n#     define BOOST_DYN_LINK\n#  endif\n#  include <boost/config/auto_link.hpp>\n#endif\n#if !defined(BOOST_MATH_TR1_NO_LIB) && !defined(BOOST_MATH_TR1_SOURCE) \\\n   && !defined(BOOST_ALL_NO_LIB) && defined(__cplusplus)\n#  define BOOST_LIB_NAME boost_math_tr1\n#  if defined(BOOST_MATH_TR1_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)\n#     define BOOST_DYN_LINK\n#  endif\n#  include <boost/config/auto_link.hpp>\n#endif\n#if !defined(BOOST_MATH_TR1_NO_LIB) && !defined(BOOST_MATH_TR1_SOURCE) \\\n   && !defined(BOOST_ALL_NO_LIB) && defined(__cplusplus)\n#  define BOOST_LIB_NAME boost_math_tr1f\n#  if defined(BOOST_MATH_TR1_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)\n#     define BOOST_DYN_LINK\n#  endif\n#  include <boost/config/auto_link.hpp>\n#endif\n#if !defined(BOOST_MATH_TR1_NO_LIB) && !defined(BOOST_MATH_TR1_SOURCE) \\\n   && !defined(BOOST_ALL_NO_LIB) && defined(__cplusplus) \\\n   && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS)\n#  define BOOST_LIB_NAME boost_math_tr1l\n#  if defined(BOOST_MATH_TR1_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)\n#     define BOOST_DYN_LINK\n#  endif\n#  include <boost/config/auto_link.hpp>\n#endif\n\n#ifndef FLT_EVAL_METHOD\ntypedef float float_t;\ntypedef double double_t;\n#elif FLT_EVAL_METHOD == 0\ntypedef float float_t;\ntypedef double double_t;\n#elif FLT_EVAL_METHOD == 1\ntypedef double float_t;\ntypedef double double_t;\n#else\ntypedef long double float_t;\ntypedef long double double_t;\n#endif\n\n// C99 Functions:\ndouble BOOST_MATH_TR1_DECL acosh BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL acoshf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL acoshl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL asinh BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL asinhf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL asinhl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL atanh BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL atanhf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL atanhl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL cbrt BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL cbrtf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL cbrtl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL copysign BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL copysignf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL copysignl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\n\ndouble BOOST_MATH_TR1_DECL erf BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL erff BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL erfl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL erfc BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL erfcf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL erfcl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#if 0\ndouble BOOST_MATH_TR1_DECL exp2 BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL exp2f BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL exp2l BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ndouble BOOST_MATH_TR1_DECL boost_expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL boost_expm1f BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL boost_expm1l BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#if 0\ndouble BOOST_MATH_TR1_DECL fdim BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL fdimf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL fdiml BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\ndouble BOOST_MATH_TR1_DECL fma BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y, double z);\nfloat BOOST_MATH_TR1_DECL fmaf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y, float z);\nlong double BOOST_MATH_TR1_DECL fmal BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y, long double z);\n#endif\ndouble BOOST_MATH_TR1_DECL fmax BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL fmaxf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL fmaxl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\n\ndouble BOOST_MATH_TR1_DECL fmin BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL fminf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL fminl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\n\ndouble BOOST_MATH_TR1_DECL hypot BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL hypotf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL hypotl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\n#if 0\nint BOOST_MATH_TR1_DECL ilogb BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nint BOOST_MATH_TR1_DECL ilogbf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nint BOOST_MATH_TR1_DECL ilogbl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ndouble BOOST_MATH_TR1_DECL lgamma BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL lgammaf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL lgammal BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#if 0\nlong long BOOST_MATH_TR1_DECL llrint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nlong long BOOST_MATH_TR1_DECL llrintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong long BOOST_MATH_TR1_DECL llrintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\nlong long BOOST_MATH_TR1_DECL llround BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nlong long BOOST_MATH_TR1_DECL llroundf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong long BOOST_MATH_TR1_DECL llroundl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL boost_log1p BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL boost_log1pf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL boost_log1pl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#if 0\ndouble BOOST_MATH_TR1_DECL log2 BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL log2f BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL log2l BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL logb BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL logbf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL logbl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\nlong BOOST_MATH_TR1_DECL lrint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nlong BOOST_MATH_TR1_DECL lrintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong BOOST_MATH_TR1_DECL lrintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\nlong BOOST_MATH_TR1_DECL lround BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nlong BOOST_MATH_TR1_DECL lroundf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong BOOST_MATH_TR1_DECL lroundl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#if 0\ndouble BOOST_MATH_TR1_DECL nan BOOST_PREVENT_MACRO_SUBSTITUTION(const char *str);\nfloat BOOST_MATH_TR1_DECL nanf BOOST_PREVENT_MACRO_SUBSTITUTION(const char *str);\nlong double BOOST_MATH_TR1_DECL nanl BOOST_PREVENT_MACRO_SUBSTITUTION(const char *str);\ndouble BOOST_MATH_TR1_DECL nearbyint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL nearbyintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL nearbyintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ndouble BOOST_MATH_TR1_DECL boost_nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL boost_nextafterf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL boost_nextafterl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\n\ndouble BOOST_MATH_TR1_DECL nexttoward BOOST_PREVENT_MACRO_SUBSTITUTION(double x, long double y);\nfloat BOOST_MATH_TR1_DECL nexttowardf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, long double y);\nlong double BOOST_MATH_TR1_DECL nexttowardl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\n#if 0\ndouble BOOST_MATH_TR1_DECL remainder BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL remainderf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL remainderl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\ndouble BOOST_MATH_TR1_DECL remquo BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y, int *pquo);\nfloat BOOST_MATH_TR1_DECL remquof BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y, int *pquo);\nlong double BOOST_MATH_TR1_DECL remquol BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y, int *pquo);\ndouble BOOST_MATH_TR1_DECL rint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL rintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL rintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ndouble BOOST_MATH_TR1_DECL round BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL roundf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL roundl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#if 0\ndouble BOOST_MATH_TR1_DECL scalbln BOOST_PREVENT_MACRO_SUBSTITUTION(double x, long ex);\nfloat BOOST_MATH_TR1_DECL scalblnf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, long ex);\nlong double BOOST_MATH_TR1_DECL scalblnl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long ex);\ndouble BOOST_MATH_TR1_DECL scalbn BOOST_PREVENT_MACRO_SUBSTITUTION(double x, int ex);\nfloat BOOST_MATH_TR1_DECL scalbnf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, int ex);\nlong double BOOST_MATH_TR1_DECL scalbnl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, int ex);\n#endif\ndouble BOOST_MATH_TR1_DECL tgamma BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL tgammaf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL tgammal BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble BOOST_MATH_TR1_DECL trunc BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL truncf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL truncl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\n// [5.2.1.1] associated Laguerre polynomials:\ndouble BOOST_MATH_TR1_DECL assoc_laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, unsigned m, double x);\nfloat BOOST_MATH_TR1_DECL assoc_laguerref BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, unsigned m, float x);\nlong double BOOST_MATH_TR1_DECL assoc_laguerrel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, unsigned m, long double x);\n\n// [5.2.1.2] associated Legendre functions:\ndouble BOOST_MATH_TR1_DECL assoc_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, double x);\nfloat BOOST_MATH_TR1_DECL assoc_legendref BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, float x);\nlong double BOOST_MATH_TR1_DECL assoc_legendrel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, long double x);\n\n// [5.2.1.3] beta function:\ndouble BOOST_MATH_TR1_DECL beta BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat BOOST_MATH_TR1_DECL betaf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double BOOST_MATH_TR1_DECL betal BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\n\n// [5.2.1.4] (complete) elliptic integral of the first kind:\ndouble BOOST_MATH_TR1_DECL comp_ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(double k);\nfloat BOOST_MATH_TR1_DECL comp_ellint_1f BOOST_PREVENT_MACRO_SUBSTITUTION(float k);\nlong double BOOST_MATH_TR1_DECL comp_ellint_1l BOOST_PREVENT_MACRO_SUBSTITUTION(long double k);\n\n// [5.2.1.5] (complete) elliptic integral of the second kind:\ndouble BOOST_MATH_TR1_DECL comp_ellint_2 BOOST_PREVENT_MACRO_SUBSTITUTION(double k);\nfloat BOOST_MATH_TR1_DECL comp_ellint_2f BOOST_PREVENT_MACRO_SUBSTITUTION(float k);\nlong double BOOST_MATH_TR1_DECL comp_ellint_2l BOOST_PREVENT_MACRO_SUBSTITUTION(long double k);\n\n// [5.2.1.6] (complete) elliptic integral of the third kind:\ndouble BOOST_MATH_TR1_DECL comp_ellint_3 BOOST_PREVENT_MACRO_SUBSTITUTION(double k, double nu);\nfloat BOOST_MATH_TR1_DECL comp_ellint_3f BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float nu);\nlong double BOOST_MATH_TR1_DECL comp_ellint_3l BOOST_PREVENT_MACRO_SUBSTITUTION(long double k, long double nu);\n#if 0\n// [5.2.1.7] confluent hypergeometric functions:\ndouble BOOST_MATH_TR1_DECL conf_hyperg BOOST_PREVENT_MACRO_SUBSTITUTION(double a, double c, double x);\nfloat BOOST_MATH_TR1_DECL conf_hypergf BOOST_PREVENT_MACRO_SUBSTITUTION(float a, float c, float x);\nlong double BOOST_MATH_TR1_DECL conf_hypergl BOOST_PREVENT_MACRO_SUBSTITUTION(long double a, long double c, long double x);\n#endif\n// [5.2.1.8] regular modified cylindrical Bessel functions:\ndouble BOOST_MATH_TR1_DECL cyl_bessel_i BOOST_PREVENT_MACRO_SUBSTITUTION(double nu, double x);\nfloat BOOST_MATH_TR1_DECL cyl_bessel_if BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x);\nlong double BOOST_MATH_TR1_DECL cyl_bessel_il BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x);\n\n// [5.2.1.9] cylindrical Bessel functions (of the first kind):\ndouble BOOST_MATH_TR1_DECL cyl_bessel_j BOOST_PREVENT_MACRO_SUBSTITUTION(double nu, double x);\nfloat BOOST_MATH_TR1_DECL cyl_bessel_jf BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x);\nlong double BOOST_MATH_TR1_DECL cyl_bessel_jl BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x);\n\n// [5.2.1.10] irregular modified cylindrical Bessel functions:\ndouble BOOST_MATH_TR1_DECL cyl_bessel_k BOOST_PREVENT_MACRO_SUBSTITUTION(double nu, double x);\nfloat BOOST_MATH_TR1_DECL cyl_bessel_kf BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x);\nlong double BOOST_MATH_TR1_DECL cyl_bessel_kl BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x);\n\n// [5.2.1.11] cylindrical Neumann functions;\n// cylindrical Bessel functions (of the second kind):\ndouble BOOST_MATH_TR1_DECL cyl_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(double nu, double x);\nfloat BOOST_MATH_TR1_DECL cyl_neumannf BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x);\nlong double BOOST_MATH_TR1_DECL cyl_neumannl BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x);\n\n// [5.2.1.12] (incomplete) elliptic integral of the first kind:\ndouble BOOST_MATH_TR1_DECL ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(double k, double phi);\nfloat BOOST_MATH_TR1_DECL ellint_1f BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float phi);\nlong double BOOST_MATH_TR1_DECL ellint_1l BOOST_PREVENT_MACRO_SUBSTITUTION(long double k, long double phi);\n\n// [5.2.1.13] (incomplete) elliptic integral of the second kind:\ndouble BOOST_MATH_TR1_DECL ellint_2 BOOST_PREVENT_MACRO_SUBSTITUTION(double k, double phi);\nfloat BOOST_MATH_TR1_DECL ellint_2f BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float phi);\nlong double BOOST_MATH_TR1_DECL ellint_2l BOOST_PREVENT_MACRO_SUBSTITUTION(long double k, long double phi);\n\n// [5.2.1.14] (incomplete) elliptic integral of the third kind:\ndouble BOOST_MATH_TR1_DECL ellint_3 BOOST_PREVENT_MACRO_SUBSTITUTION(double k, double nu, double phi);\nfloat BOOST_MATH_TR1_DECL ellint_3f BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float nu, float phi);\nlong double BOOST_MATH_TR1_DECL ellint_3l BOOST_PREVENT_MACRO_SUBSTITUTION(long double k, long double nu, long double phi);\n\n// [5.2.1.15] exponential integral:\ndouble BOOST_MATH_TR1_DECL expint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat BOOST_MATH_TR1_DECL expintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double BOOST_MATH_TR1_DECL expintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\n// [5.2.1.16] Hermite polynomials:\ndouble BOOST_MATH_TR1_DECL hermite BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, double x);\nfloat BOOST_MATH_TR1_DECL hermitef BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x);\nlong double BOOST_MATH_TR1_DECL hermitel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x);\n\n#if 0\n// [5.2.1.17] hypergeometric functions:\ndouble BOOST_MATH_TR1_DECL hyperg BOOST_PREVENT_MACRO_SUBSTITUTION(double a, double b, double c, double x);\nfloat BOOST_MATH_TR1_DECL hypergf BOOST_PREVENT_MACRO_SUBSTITUTION(float a, float b, float c, float x);\nlong double BOOST_MATH_TR1_DECL hypergl BOOST_PREVENT_MACRO_SUBSTITUTION(long double a, long double b, long double c,\nlong double x);\n#endif\n\n// [5.2.1.18] Laguerre polynomials:\ndouble BOOST_MATH_TR1_DECL laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, double x);\nfloat BOOST_MATH_TR1_DECL laguerref BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x);\nlong double BOOST_MATH_TR1_DECL laguerrel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x);\n\n// [5.2.1.19] Legendre polynomials:\ndouble BOOST_MATH_TR1_DECL legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, double x);\nfloat BOOST_MATH_TR1_DECL legendref BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, float x);\nlong double BOOST_MATH_TR1_DECL legendrel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, long double x);\n\n// [5.2.1.20] Riemann zeta function:\ndouble BOOST_MATH_TR1_DECL riemann_zeta BOOST_PREVENT_MACRO_SUBSTITUTION(double);\nfloat BOOST_MATH_TR1_DECL riemann_zetaf BOOST_PREVENT_MACRO_SUBSTITUTION(float);\nlong double BOOST_MATH_TR1_DECL riemann_zetal BOOST_PREVENT_MACRO_SUBSTITUTION(long double);\n\n// [5.2.1.21] spherical Bessel functions (of the first kind):\ndouble BOOST_MATH_TR1_DECL sph_bessel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, double x);\nfloat BOOST_MATH_TR1_DECL sph_besself BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x);\nlong double BOOST_MATH_TR1_DECL sph_bessell BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x);\n\n// [5.2.1.22] spherical associated Legendre functions:\ndouble BOOST_MATH_TR1_DECL sph_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, double theta);\nfloat BOOST_MATH_TR1_DECL sph_legendref BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, float theta);\nlong double BOOST_MATH_TR1_DECL sph_legendrel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, long double theta);\n\n// [5.2.1.23] spherical Neumann functions;\n// spherical Bessel functions (of the second kind):\ndouble BOOST_MATH_TR1_DECL sph_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, double x);\nfloat BOOST_MATH_TR1_DECL sph_neumannf BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x);\nlong double BOOST_MATH_TR1_DECL sph_neumannl BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x);\n\n#ifdef __cplusplus\n\n}}}}  // namespaces\n\n#include <boost/math/tools/promotion.hpp>\n\nnamespace boost{ namespace math{ namespace tr1{\n//\n// Declare overload of the functions which forward to the\n// C interfaces:\n//\n// C99 Functions:\ninline float acosh BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::acoshf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double acosh BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::acoshl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type acosh BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::acosh BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\ninline float asinh BOOST_PREVENT_MACRO_SUBSTITUTION(float x){ return boost::math::tr1::asinhf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double asinh BOOST_PREVENT_MACRO_SUBSTITUTION(long double x){ return boost::math::tr1::asinhl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type asinh BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::asinh BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\ninline float atanh BOOST_PREVENT_MACRO_SUBSTITUTION(float x){ return boost::math::tr1::atanhf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double atanh BOOST_PREVENT_MACRO_SUBSTITUTION(long double x){ return boost::math::tr1::atanhl(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type atanh BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::atanh BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\ninline float cbrt BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::cbrtf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double cbrt BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::cbrtl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type cbrt BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::cbrt BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\ninline float copysign BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y)\n{ return boost::math::tr1::copysignf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double copysign BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::copysignl BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type copysign BOOST_PREVENT_MACRO_SUBSTITUTION(T1 x, T2 y)\n{ return boost::math::tr1::copysign BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(x), static_cast<typename tools::promote_args<T1, T2>::type>(y)); }\n\ninline float erf BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::erff BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double erf BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::erfl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type erf BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::erf BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\ninline float erfc BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::erfcf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double erfc BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::erfcl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type erfc BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::erfc BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n#if 0\ndouble exp2 BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat exp2f BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double exp2l BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ninline float expm1f BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::boost_expm1f BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline double expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(double x)\n{ return boost::math::tr1::boost_expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double expm1l BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::boost_expm1l BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline float expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::expm1f BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::expm1l BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n#if 0\ndouble fdim BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat fdimf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double fdiml BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\ndouble fma BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y, double z);\nfloat fmaf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y, float z);\nlong double fmal BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y, long double z);\n#endif\ninline float fmax BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y)\n{ return boost::math::tr1::fmaxf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double fmax BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::fmaxl BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type fmax BOOST_PREVENT_MACRO_SUBSTITUTION(T1 x, T2 y)\n{ return boost::math::tr1::fmax BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(x), static_cast<typename tools::promote_args<T1, T2>::type>(y)); }\n\ninline float fmin BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y)\n{ return boost::math::tr1::fminf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double fmin BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::fminl BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type fmin BOOST_PREVENT_MACRO_SUBSTITUTION(T1 x, T2 y)\n{ return boost::math::tr1::fmin BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(x), static_cast<typename tools::promote_args<T1, T2>::type>(y)); }\n\ninline float hypot BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y)\n{ return boost::math::tr1::hypotf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double hypot BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::hypotl BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type hypot BOOST_PREVENT_MACRO_SUBSTITUTION(T1 x, T2 y)\n{ return boost::math::tr1::hypot BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(x), static_cast<typename tools::promote_args<T1, T2>::type>(y)); }\n#if 0\nint ilogb BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nint ilogbf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nint ilogbl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ninline float lgamma BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::lgammaf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double lgamma BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::lgammal BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type lgamma BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::lgamma BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n#if 0\nlong long llrint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nlong long llrintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong long llrintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ninline long long llround BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::llroundf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long long llround BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::llroundl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline long long llround BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return llround BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<double>(x)); }\n\ninline float log1pf BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::boost_log1pf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline double log1p BOOST_PREVENT_MACRO_SUBSTITUTION(double x)\n{ return boost::math::tr1::boost_log1p BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double log1pl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::boost_log1pl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline float log1p BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::log1pf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double log1p BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::log1pl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type log1p BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::log1p BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n#if 0\ndouble log2 BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat log2f BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double log2l BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n\ndouble logb BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat logbf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double logbl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\nlong lrint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nlong lrintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong lrintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ninline long lround BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::lroundf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long lround BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::lroundl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\nlong lround BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::lround BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<double>(x)); }\n#if 0\ndouble nan BOOST_PREVENT_MACRO_SUBSTITUTION(const char *str);\nfloat nanf BOOST_PREVENT_MACRO_SUBSTITUTION(const char *str);\nlong double nanl BOOST_PREVENT_MACRO_SUBSTITUTION(const char *str);\ndouble nearbyint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat nearbyintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double nearbyintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ninline float nextafterf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y)\n{ return boost::math::tr1::boost_nextafterf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline double nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y)\n{ return boost::math::tr1::boost_nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double nextafterl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::boost_nextafterl BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline float nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y)\n{ return boost::math::tr1::nextafterf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::nextafterl BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(T1 x, T2 y)\n{ return boost::math::tr1::nextafter BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(x), static_cast<typename tools::promote_args<T1, T2>::type>(y)); }\n\ninline float nexttoward BOOST_PREVENT_MACRO_SUBSTITUTION(float x, long double y)\n{ return boost::math::tr1::nexttowardf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double nexttoward BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::nexttowardl BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type nexttoward BOOST_PREVENT_MACRO_SUBSTITUTION(T1 x, T2 y)\n{ return boost::math::tr1::nexttoward BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(x), static_cast<long double>(y)); }\n#if 0\ndouble remainder BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y);\nfloat remainderf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y);\nlong double remainderl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y);\ndouble remquo BOOST_PREVENT_MACRO_SUBSTITUTION(double x, double y, int *pquo);\nfloat remquof BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y, int *pquo);\nlong double remquol BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y, int *pquo);\ndouble rint BOOST_PREVENT_MACRO_SUBSTITUTION(double x);\nfloat rintf BOOST_PREVENT_MACRO_SUBSTITUTION(float x);\nlong double rintl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x);\n#endif\ninline float round BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::roundf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double round BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::roundl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type round BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::round BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n#if 0\ndouble scalbln BOOST_PREVENT_MACRO_SUBSTITUTION(double x, long ex);\nfloat scalblnf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, long ex);\nlong double scalblnl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long ex);\ndouble scalbn BOOST_PREVENT_MACRO_SUBSTITUTION(double x, int ex);\nfloat scalbnf BOOST_PREVENT_MACRO_SUBSTITUTION(float x, int ex);\nlong double scalbnl BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, int ex);\n#endif\ninline float tgamma BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::tgammaf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double tgamma BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::tgammal BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type tgamma BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::tgamma BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\ninline float trunc BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::truncf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double trunc BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::truncl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type trunc BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::trunc BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\n# define NO_MACRO_EXPAND /**/\n// C99 macros defined as C++ templates\ntemplate<class T> bool signbit NO_MACRO_EXPAND(T x)\n{ BOOST_STATIC_ASSERT(sizeof(T) == 0); return false; } // must not be instantiated\ntemplate<> bool BOOST_MATH_TR1_DECL signbit<float> NO_MACRO_EXPAND(float x);\ntemplate<> bool BOOST_MATH_TR1_DECL signbit<double> NO_MACRO_EXPAND(double x);\ntemplate<> bool BOOST_MATH_TR1_DECL signbit<long double> NO_MACRO_EXPAND(long double x);\n\ntemplate<class T> int fpclassify NO_MACRO_EXPAND(T x)\n{ BOOST_STATIC_ASSERT(sizeof(T) == 0); return false; } // must not be instantiated\ntemplate<> int BOOST_MATH_TR1_DECL fpclassify<float> NO_MACRO_EXPAND(float x);\ntemplate<> int BOOST_MATH_TR1_DECL fpclassify<double> NO_MACRO_EXPAND(double x);\ntemplate<> int BOOST_MATH_TR1_DECL fpclassify<long double> NO_MACRO_EXPAND(long double x);\n\ntemplate<class T> bool isfinite NO_MACRO_EXPAND(T x)\n{ BOOST_STATIC_ASSERT(sizeof(T) == 0); return false; } // must not be instantiated\ntemplate<> bool BOOST_MATH_TR1_DECL isfinite<float> NO_MACRO_EXPAND(float x);\ntemplate<> bool BOOST_MATH_TR1_DECL isfinite<double> NO_MACRO_EXPAND(double x);\ntemplate<> bool BOOST_MATH_TR1_DECL isfinite<long double> NO_MACRO_EXPAND(long double x);\n\ntemplate<class T> bool isinf NO_MACRO_EXPAND(T x)\n{ BOOST_STATIC_ASSERT(sizeof(T) == 0); return false; } // must not be instantiated\ntemplate<> bool BOOST_MATH_TR1_DECL isinf<float> NO_MACRO_EXPAND(float x);\ntemplate<> bool BOOST_MATH_TR1_DECL isinf<double> NO_MACRO_EXPAND(double x);\ntemplate<> bool BOOST_MATH_TR1_DECL isinf<long double> NO_MACRO_EXPAND(long double x);\n\ntemplate<class T> bool isnan NO_MACRO_EXPAND(T x)\n{ BOOST_STATIC_ASSERT(sizeof(T) == 0); return false; } // must not be instantiated\ntemplate<> bool BOOST_MATH_TR1_DECL isnan<float> NO_MACRO_EXPAND(float x);\ntemplate<> bool BOOST_MATH_TR1_DECL isnan<double> NO_MACRO_EXPAND(double x);\ntemplate<> bool BOOST_MATH_TR1_DECL isnan<long double> NO_MACRO_EXPAND(long double x);\n\ntemplate<class T> bool isnormal NO_MACRO_EXPAND(T x)\n{ BOOST_STATIC_ASSERT(sizeof(T) == 0); return false; } // must not be instantiated\ntemplate<> bool BOOST_MATH_TR1_DECL isnormal<float> NO_MACRO_EXPAND(float x);\ntemplate<> bool BOOST_MATH_TR1_DECL isnormal<double> NO_MACRO_EXPAND(double x);\ntemplate<> bool BOOST_MATH_TR1_DECL isnormal<long double> NO_MACRO_EXPAND(long double x);\n\n#undef NO_MACRO_EXPAND   \n   \n// [5.2.1.1] associated Laguerre polynomials:\ninline float assoc_laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, unsigned m, float x)\n{ return boost::math::tr1::assoc_laguerref BOOST_PREVENT_MACRO_SUBSTITUTION(n, m, x); }\ninline long double assoc_laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, unsigned m, long double x)\n{ return boost::math::tr1::assoc_laguerrel BOOST_PREVENT_MACRO_SUBSTITUTION(n, m, x); }\ntemplate <class T> \ninline typename tools::promote_args<T>::type assoc_laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, unsigned m, T x)\n{ return boost::math::tr1::assoc_laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(n, m, static_cast<typename tools::promote_args<T>::type>(x)); }\n\n// [5.2.1.2] associated Legendre functions:\ninline float assoc_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, float x)\n{ return boost::math::tr1::assoc_legendref BOOST_PREVENT_MACRO_SUBSTITUTION(l, m, x); }\ninline long double assoc_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, long double x)\n{ return boost::math::tr1::assoc_legendrel BOOST_PREVENT_MACRO_SUBSTITUTION(l, m, x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type assoc_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, T x)\n{ return boost::math::tr1::assoc_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(l, m, static_cast<typename tools::promote_args<T>::type>(x)); }\n\n// [5.2.1.3] beta function:\ninline float beta BOOST_PREVENT_MACRO_SUBSTITUTION(float x, float y)\n{ return boost::math::tr1::betaf BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ninline long double beta BOOST_PREVENT_MACRO_SUBSTITUTION(long double x, long double y)\n{ return boost::math::tr1::betal BOOST_PREVENT_MACRO_SUBSTITUTION(x, y); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type beta BOOST_PREVENT_MACRO_SUBSTITUTION(T2 x, T1 y)\n{ return boost::math::tr1::beta BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(x), static_cast<typename tools::promote_args<T1, T2>::type>(y)); }\n\n// [5.2.1.4] (complete) elliptic integral of the first kind:\ninline float comp_ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(float k)\n{ return boost::math::tr1::comp_ellint_1f BOOST_PREVENT_MACRO_SUBSTITUTION(k); }\ninline long double comp_ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(long double k)\n{ return boost::math::tr1::comp_ellint_1l BOOST_PREVENT_MACRO_SUBSTITUTION(k); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type comp_ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(T k)\n{ return boost::math::tr1::comp_ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(k)); }\n\n// [5.2.1.5]  BOOST_PREVENT_MACRO_SUBSTITUTION(complete) elliptic integral of the second kind:\ninline float comp_ellint_2(float k)\n{ return boost::math::tr1::comp_ellint_2f(k); }\ninline long double comp_ellint_2(long double k)\n{ return boost::math::tr1::comp_ellint_2l(k); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type comp_ellint_2(T k)\n{ return boost::math::tr1::comp_ellint_2(static_cast<typename tools::promote_args<T>::type> BOOST_PREVENT_MACRO_SUBSTITUTION(k)); }\n\n// [5.2.1.6]  BOOST_PREVENT_MACRO_SUBSTITUTION(complete) elliptic integral of the third kind:\ninline float comp_ellint_3(float k, float nu)\n{ return boost::math::tr1::comp_ellint_3f(k, nu); }\ninline long double comp_ellint_3(long double k, long double nu)\n{ return boost::math::tr1::comp_ellint_3l(k, nu); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type comp_ellint_3(T1 k, T2 nu)\n{ return boost::math::tr1::comp_ellint_3(static_cast<typename tools::promote_args<T1, T2>::type> BOOST_PREVENT_MACRO_SUBSTITUTION(k), static_cast<typename tools::promote_args<T1, T2>::type> BOOST_PREVENT_MACRO_SUBSTITUTION(nu)); }\n\n#if 0\n// [5.2.1.7] confluent hypergeometric functions:\ndouble conf_hyperg BOOST_PREVENT_MACRO_SUBSTITUTION(double a, double c, double x);\nfloat conf_hypergf BOOST_PREVENT_MACRO_SUBSTITUTION(float a, float c, float x);\nlong double conf_hypergl BOOST_PREVENT_MACRO_SUBSTITUTION(long double a, long double c, long double x);\n#endif\n\n// [5.2.1.8] regular modified cylindrical Bessel functions:\ninline float cyl_bessel_i BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x)\n{ return boost::math::tr1::cyl_bessel_if BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ninline long double cyl_bessel_i BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x)\n{ return boost::math::tr1::cyl_bessel_il BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type cyl_bessel_i BOOST_PREVENT_MACRO_SUBSTITUTION(T1 nu, T2 x)\n{ return boost::math::tr1::cyl_bessel_i BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(nu), static_cast<typename tools::promote_args<T1, T2>::type>(x)); }\n\n// [5.2.1.9] cylindrical Bessel functions (of the first kind):\ninline float cyl_bessel_j BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x)\n{ return boost::math::tr1::cyl_bessel_jf BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ninline long double cyl_bessel_j BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x)\n{ return boost::math::tr1::cyl_bessel_jl BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type cyl_bessel_j BOOST_PREVENT_MACRO_SUBSTITUTION(T1 nu, T2 x)\n{ return boost::math::tr1::cyl_bessel_j BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(nu), static_cast<typename tools::promote_args<T1, T2>::type>(x)); }\n\n// [5.2.1.10] irregular modified cylindrical Bessel functions:\ninline float cyl_bessel_k BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x)\n{ return boost::math::tr1::cyl_bessel_kf BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ninline long double cyl_bessel_k BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x)\n{ return boost::math::tr1::cyl_bessel_kl BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type cyl_bessel_k BOOST_PREVENT_MACRO_SUBSTITUTION(T1 nu, T2 x)\n{ return boost::math::tr1::cyl_bessel_k BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type> BOOST_PREVENT_MACRO_SUBSTITUTION(nu), static_cast<typename tools::promote_args<T1, T2>::type>(x)); }\n\n// [5.2.1.11] cylindrical Neumann functions;\n// cylindrical Bessel functions (of the second kind):\ninline float cyl_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(float nu, float x)\n{ return boost::math::tr1::cyl_neumannf BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ninline long double cyl_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(long double nu, long double x)\n{ return boost::math::tr1::cyl_neumannl BOOST_PREVENT_MACRO_SUBSTITUTION(nu, x); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type cyl_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(T1 nu, T2 x)\n{ return boost::math::tr1::cyl_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(nu), static_cast<typename tools::promote_args<T1, T2>::type>(x)); }\n\n// [5.2.1.12] (incomplete) elliptic integral of the first kind:\ninline float ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float phi)\n{ return boost::math::tr1::ellint_1f BOOST_PREVENT_MACRO_SUBSTITUTION(k, phi); }\ninline long double ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(long double k, long double phi)\n{ return boost::math::tr1::ellint_1l BOOST_PREVENT_MACRO_SUBSTITUTION(k, phi); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(T1 k, T2 phi)\n{ return boost::math::tr1::ellint_1 BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(k), static_cast<typename tools::promote_args<T1, T2>::type>(phi)); }\n\n// [5.2.1.13] (incomplete) elliptic integral of the second kind:\ninline float ellint_2 BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float phi)\n{ return boost::math::tr1::ellint_2f BOOST_PREVENT_MACRO_SUBSTITUTION(k, phi); }\ninline long double ellint_2 BOOST_PREVENT_MACRO_SUBSTITUTION(long double k, long double phi)\n{ return boost::math::tr1::ellint_2l BOOST_PREVENT_MACRO_SUBSTITUTION(k, phi); }\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type ellint_2 BOOST_PREVENT_MACRO_SUBSTITUTION(T1 k, T2 phi)\n{ return boost::math::tr1::ellint_2 BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2>::type>(k), static_cast<typename tools::promote_args<T1, T2>::type>(phi)); }\n\n// [5.2.1.14] (incomplete) elliptic integral of the third kind:\ninline float ellint_3 BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float nu, float phi)\n{ return boost::math::tr1::ellint_3f BOOST_PREVENT_MACRO_SUBSTITUTION(k, nu, phi); }\ninline long double ellint_3 BOOST_PREVENT_MACRO_SUBSTITUTION(long double k, long double nu, long double phi)\n{ return boost::math::tr1::ellint_3l BOOST_PREVENT_MACRO_SUBSTITUTION(k, nu, phi); }\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type ellint_3 BOOST_PREVENT_MACRO_SUBSTITUTION(T1 k, T2 nu, T3 phi)\n{ return boost::math::tr1::ellint_3 BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T1, T2, T3>::type>(k), static_cast<typename tools::promote_args<T1, T2, T3>::type>(nu), static_cast<typename tools::promote_args<T1, T2, T3>::type>(phi)); }\n\n// [5.2.1.15] exponential integral:\ninline float expint BOOST_PREVENT_MACRO_SUBSTITUTION(float x)\n{ return boost::math::tr1::expintf BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ninline long double expint BOOST_PREVENT_MACRO_SUBSTITUTION(long double x)\n{ return boost::math::tr1::expintl BOOST_PREVENT_MACRO_SUBSTITUTION(x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type expint BOOST_PREVENT_MACRO_SUBSTITUTION(T x)\n{ return boost::math::tr1::expint BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(x)); }\n\n// [5.2.1.16] Hermite polynomials:\ninline float hermite BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x)\n{ return boost::math::tr1::hermitef BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ninline long double hermite BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x)\n{ return boost::math::tr1::hermitel BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type hermite BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, T x)\n{ return boost::math::tr1::hermite BOOST_PREVENT_MACRO_SUBSTITUTION(n, static_cast<typename tools::promote_args<T>::type>(x)); }\n\n#if 0\n// [5.2.1.17] hypergeometric functions:\ndouble hyperg BOOST_PREVENT_MACRO_SUBSTITUTION(double a, double b, double c, double x);\nfloat hypergf BOOST_PREVENT_MACRO_SUBSTITUTION(float a, float b, float c, float x);\nlong double hypergl BOOST_PREVENT_MACRO_SUBSTITUTION(long double a, long double b, long double c,\nlong double x);\n#endif\n\n// [5.2.1.18] Laguerre polynomials:\ninline float laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x)\n{ return boost::math::tr1::laguerref BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ninline long double laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x)\n{ return boost::math::tr1::laguerrel BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, T x)\n{ return boost::math::tr1::laguerre BOOST_PREVENT_MACRO_SUBSTITUTION(n, static_cast<typename tools::promote_args<T>::type>(x)); }\n\n// [5.2.1.19] Legendre polynomials:\ninline float legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, float x)\n{ return boost::math::tr1::legendref BOOST_PREVENT_MACRO_SUBSTITUTION(l, x); }\ninline long double legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, long double x)\n{ return boost::math::tr1::legendrel BOOST_PREVENT_MACRO_SUBSTITUTION(l, x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, T x)\n{ return boost::math::tr1::legendre BOOST_PREVENT_MACRO_SUBSTITUTION(l, static_cast<typename tools::promote_args<T>::type>(x)); }\n\n// [5.2.1.20] Riemann zeta function:\ninline float riemann_zeta BOOST_PREVENT_MACRO_SUBSTITUTION(float z)\n{ return boost::math::tr1::riemann_zetaf BOOST_PREVENT_MACRO_SUBSTITUTION(z); }\ninline long double riemann_zeta BOOST_PREVENT_MACRO_SUBSTITUTION(long double z)\n{ return boost::math::tr1::riemann_zetal BOOST_PREVENT_MACRO_SUBSTITUTION(z); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type riemann_zeta BOOST_PREVENT_MACRO_SUBSTITUTION(T z)\n{ return boost::math::tr1::riemann_zeta BOOST_PREVENT_MACRO_SUBSTITUTION(static_cast<typename tools::promote_args<T>::type>(z)); }\n\n// [5.2.1.21] spherical Bessel functions (of the first kind):\ninline float sph_bessel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x)\n{ return boost::math::tr1::sph_besself BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ninline long double sph_bessel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x)\n{ return boost::math::tr1::sph_bessell BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type sph_bessel BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, T x)\n{ return boost::math::tr1::sph_bessel BOOST_PREVENT_MACRO_SUBSTITUTION(n, static_cast<typename tools::promote_args<T>::type>(x)); }\n\n// [5.2.1.22] spherical associated Legendre functions:\ninline float sph_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, float theta)\n{ return boost::math::tr1::sph_legendref BOOST_PREVENT_MACRO_SUBSTITUTION(l, m, theta); }\ninline long double sph_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, long double theta)\n{ return boost::math::tr1::sph_legendrel BOOST_PREVENT_MACRO_SUBSTITUTION(l, m, theta); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type sph_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m, T theta)\n{ return boost::math::tr1::sph_legendre BOOST_PREVENT_MACRO_SUBSTITUTION(l, m, static_cast<typename tools::promote_args<T>::type>(theta)); }\n\n// [5.2.1.23] spherical Neumann functions;\n// spherical Bessel functions (of the second kind):\ninline float sph_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, float x)\n{ return boost::math::tr1::sph_neumannf BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ninline long double sph_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, long double x)\n{ return boost::math::tr1::sph_neumannl BOOST_PREVENT_MACRO_SUBSTITUTION(n, x); }\ntemplate <class T>\ninline typename tools::promote_args<T>::type sph_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, T x)\n{ return boost::math::tr1::sph_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(n, static_cast<typename tools::promote_args<T>::type>(x)); }\n\n}}} // namespaces\n\n#endif // __cplusplus\n\n#endif // BOOST_MATH_TR1_HPP\n\n", "meta": {"hexsha": "66f753235a59370ee6ae5d4c3728440a25c0f92b", "size": 53789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src-2007/public/python/boost/math/tr1.hpp", "max_stars_repo_name": "KyleGospo/City-17-Episode-One-Source", "max_stars_repo_head_hexsha": "2bc0bb56a2e0a63d963755e2831c15f2970c38e7", "max_stars_repo_licenses": ["Unlicense"], "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": "src/boost/math/tr1.hpp", "max_issues_repo_name": "cpmech/vismatrix", "max_issues_repo_head_hexsha": "a4994864d3592cfa2db24119427fad096303fb4f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "src/boost/math/tr1.hpp", "max_forks_repo_name": "cpmech/vismatrix", "max_forks_repo_head_hexsha": "a4994864d3592cfa2db24119427fad096303fb4f", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 62.6911421911, "max_line_length": 266, "alphanum_fraction": 0.8231980516, "num_tokens": 14234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224193, "lm_q2_score": 0.021287350047148615, "lm_q1q2_score": 0.004570211390761386}}
{"text": "//[ VirtualMember\n//  Copyright 2012 Eric Niebler. 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// This example demonstrates how to use BOOST_PROTO_EXTENDS_MEMBERS()\n// to add \"virtual\" data members to expressions within a domain. For\n// instance, with Phoenix you can create a lambda expression such as\n//\n//    if_(_1 > 0)[ std::cout << _2 ].else_[ std::cout << _3 ]\n//\n// In the above expression, \"else_\" is a so-called virtual data member\n// of the expression \"if_(_1 > 0)[ std::cout << _2 ]\". This example\n// shows how to implement the \".else_\" syntax with Proto.\n//\n// ****WARNING****WARNING****WARNING****WARNING****WARNING****WARNING****\n// * The virtual data member feature is experimental and can change at  *\n// * any time. Use it at your own risk.                                 *\n// **********************************************************************\n\n#include <iostream>\n#include <type_traits>\n#include <boost/proto/v5/proto.hpp>\n#include <boost/proto/v5/debug.hpp>\n\nnamespace proto = boost::proto;\nusing proto::_;\n\nnamespace std\n{\n    // For debugging purposes only. Don't do this in production code.\n    std::ostream & operator<<(std::ostream & s, std::ostream &)\n    {\n        return s << \"std::cout\";\n    }\n}\n\nnamespace mini_lambda\n{\n    // An MPL IntegralConstant\n    template<class N>\n    struct placeholder\n      : proto::env_tag<placeholder<N>>\n    {\n        using proto::env_tag<placeholder>::operator=;\n\n        // So placeholder terminals can be pretty-printed with display_expr\n        friend std::ostream & operator << (std::ostream & s, placeholder)\n        {\n            return s << \"_\" << N::value + 1;\n        }\n    };\n\n    template<std::size_t N>\n    using placeholder_c = placeholder<std::integral_constant<std::size_t, N>>;\n\n    // Some keyword types for our lambda EDSL\n    namespace keyword\n    {\n        struct if_ {};\n        struct else_ {};\n        struct do_ {};\n        struct while_ {};\n        struct try_ {};\n        struct catch_ {};\n    }\n\n    // Forward declaration for the mini-lambda grammar\n    struct grammar;\n    struct eval_if_else;\n\n    // The grammar for mini-lambda expressions with actions for\n    // evaluating the lambda expression.\n    struct grammar\n      : proto::def<\n            proto::match(\n                // When evaluating a placeholder, use the placeholder\n                // fetch a value from the environment parameter, which\n                // is a key/value store set up before calling grammar.\n                proto::case_(\n                    proto::terminal(placeholder<_>)\n                  , proto::get_env(proto::_value)\n                )\n                // When evaluating if/then/else expressions of the form\n                // \"if_( E0 )[ E1 ].else_[ E2 ]\", pass E0, E1 and E2 to\n                // eval_if_else along with the \"data\" parameter. Note the\n                // use of proto::member to match binary expressions like\n                // \"X.Y\" where \"Y\" is a virtual data member.\n              , proto::case_(\n                    proto::subscript(\n                        proto::member(\n                            proto::subscript(\n                                proto::function(\n                                    proto::terminal(keyword::if_)\n                                  , grammar\n                                )\n                              , grammar\n                            )\n                          , proto::terminal(keyword::else_)\n                        )\n                      , grammar\n                    )\n                  , eval_if_else(\n                        proto::_right(proto::_left(proto::_left(proto::_left)))\n                      , proto::_right(proto::_left(proto::_left))\n                      , proto::_right\n                      , proto::_env\n                    )\n                )\n              , proto::default_(\n                    proto::eval_with(grammar)\n                )\n            )\n        >\n    {};\n\n    // A callable PolymorphicFunctionObject that evaluates\n    // if/then/else expressions.\n    struct eval_if_else\n    {\n        template<typename If, typename Then, typename Else, typename Args>\n        void operator()(If const &if_, Then const &then_, Else const &else_, Args const &args) const\n        {\n            if(grammar()(if_, args))\n            {\n                grammar()(then_, args);\n            }\n            else\n            {\n                grammar()(else_, args);\n            }\n        }\n    };\n\n    // Here is the mini-lambda expression wrapper. It serves two purposes:\n    // 1) To define operator() overloads that evaluate the lambda expression, and\n    // 2) To define virtual data members like \"else_\" so that we can write\n    //    expressions like \"if_(X)[Y].else_[Z]\".\n    template<class ExprDesc>\n    struct expression\n      : proto::basic_expr<expression<ExprDesc>>\n      , proto::expr_assign<expression<ExprDesc>>\n      , proto::expr_subscript<expression<ExprDesc>>\n    {\n    private:\n        template<std::size_t ...I, typename ...A>\n        auto eval(proto::utility::indices<I...>, A &&...a) const\n        BOOST_PROTO_AUTO_RETURN(\n            grammar()(*this, proto::make_env(placeholder_c<I>() = std::forward<A>(a)...))\n        )\n\n    public:\n        using proto::basic_expr<expression<ExprDesc>>::basic_expr;\n        using proto::expr_assign<expression>::operator=;\n\n        // Use BOOST_PROTO_EXTENDS_MEMBERS() to define \"virtual\"\n        // data members that all expressions in the mini-lambda\n        // domain will have. They can be used to create expressions\n        // like \"if_(x)[y].else_[z]\" and \"do_[y].while_(z)\".\n        BOOST_PROTO_EXTENDS_MEMBERS(\n            expression,\n            ((keyword::else_,   else_))\n            ((keyword::while_,  while_))\n            ((keyword::catch_,  catch_))\n        );\n\n        template<typename ...A>\n        auto operator()(A &&... a) const\n        BOOST_PROTO_AUTO_RETURN(\n            this->eval(proto::utility::make_indices<sizeof...(A)>(), std::forward<A>(a)...)\n        )\n    };\n\n    template<typename T>\n    using var = proto::custom<expression<_>>::terminal<T>;\n\n    using domain = proto::result_of::domain_of<var<placeholder_c<0>>>::type;\n\n    namespace placeholders\n    {\n        // Define some placeholders\n        namespace\n        {\n            constexpr auto const & _1 = proto::utility::static_const<var<placeholder_c<0>>>::value;\n            constexpr auto const & _2 = proto::utility::static_const<var<placeholder_c<1>>>::value;\n            constexpr auto const & _3 = proto::utility::static_const<var<placeholder_c<2>>>::value;\n        }\n\n        BOOST_PROTO_IGNORE_UNUSED(_1, _2, _3);\n\n        // Define the if_() statement\n        template<typename E>\n        auto if_(E && e)\n        BOOST_PROTO_AUTO_RETURN(\n            proto::make_expr<proto::function, domain>(\n                keyword::if_()\n              , std::forward<E>(e)\n            )\n        )\n    }\n\n    using placeholders::if_;\n}\n\nint main()\n{\n    using namespace mini_lambda::placeholders;\n\n    // OK, we can create if/then/else lambda expressions\n    // and evaluate them.\n    auto fun =\n        if_(_1 > 0)\n        [\n            std::cout << _2 << '\\n'\n        ]\n        .else_\n        [\n            std::cout << _3 << '\\n'\n        ];\n\n    proto::display_expr(fun);\n    fun(42, \"positive\", \"non-positive\");\n    fun(-42, \"positive\", \"non-positive\");\n\n    // Even though all expressions in the mini-lambda\n    // domain have members named else_, while_, and catch_,\n    // they all occupy the same byte in the expression.\n    static_assert(sizeof(_1) == 3, \"_1 should be only 3 bytes\");\n}\n//]\n", "meta": {"hexsha": "6bcbdb0bef997b371fb3f4ee2dc0a78d1b96be01", "size": 7731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/proto/v5/example/virtual_member.cpp", "max_stars_repo_name": "ericniebler/proto-0x", "max_stars_repo_head_hexsha": "b8d80f1434e37a2a32613cdf58b02b5f7143cc1f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-10-27T08:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T03:30:17.000Z", "max_issues_repo_path": "libs/proto/v5/example/virtual_member.cpp", "max_issues_repo_name": "ericniebler/proto-0x", "max_issues_repo_head_hexsha": "b8d80f1434e37a2a32613cdf58b02b5f7143cc1f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-05T17:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-05T18:34:53.000Z", "max_forks_repo_path": "libs/proto/v5/example/virtual_member.cpp", "max_forks_repo_name": "ericniebler/proto-0x", "max_forks_repo_head_hexsha": "b8d80f1434e37a2a32613cdf58b02b5f7143cc1f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-26T17:15:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T17:15:12.000Z", "avg_line_length": 33.4675324675, "max_line_length": 100, "alphanum_fraction": 0.5435260639, "num_tokens": 1705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817434481176185, "lm_q2_score": 0.028870905379577382, "lm_q1q2_score": 0.004566636542537023}}
{"text": "// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. See LICENSE.txt for details.\n//\n// Author: Denis Bueno\n\n// Represented by HornTransStateSpace: What is common to all the sliced\n// transition relations? The state variables of the transition system; the rule\n// activation vars.\n//\n// Represented by HornSetTrans: What is different between the sliced transition\n// relations? The transition relation itself. The inputs derived from the\n// quantified vars. The inputs for the commander vars. The cones.\n\n\n#define BOOST_RESULT_OF_USE_DECLTYPE\n\n#include <boost/algorithm/cxx11/all_of.hpp>\n#include <boost/range/algorithm/transform.hpp>\n#include <boost/range/algorithm/copy.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/optional.hpp>\n#include <boost/program_options.hpp>\n#include <boost/range.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/range/combine.hpp>\n#include <fstream>\n#include <gmpxx.h>\n#include <map>\n#include <set>\n#include <sstream>\n#include <vector>\n#include <z3++.h>\n\n#include \"checker_types.h\"\n#include \"supp/expr_flattener.h\"\n#include \"supp/expr_iterators.h\"\n#include \"supp/expr_rewriter.h\"\n#include \"supp/expr_substitution.h\"\n#include \"supp/expr_supp.h\"\n#include \"supp/nnf_rewriter.h\"\n#include \"xsys/state_vars.h\"\n#include \"xsys/vmt_transition_system.h\"\n#include \"one_hot.h\"\n\nusing namespace std;\nusing namespace euforia;\n\nusing euforia::vmt::VmtTransitionSystem;\n\nnamespace {\nstruct Config {\n  string input_filename;\n  bool allocate_vars_by_sort = false;\n  bool allocate_inputs_by_sort = true;\n  boost::optional<string> varmap_filename;\n  bool slice_t = false;\n  bool enable_one_hots = true;\n};\n\nConfig config;\n\nclass Int2BvRewriter : public ExprRewriter<Int2BvRewriter>,\n    public ExprVisitor<Int2BvRewriter, z3::expr> {\n public:\n  Int2BvRewriter(z3::context& c, int bv_width) : bv_sort_(c.bv_sort(bv_width)) {}\n\n  z3::expr operator()(const z3::expr& e) { return Rewrite(e); }\n\n  z3::sort TranslateSort(const z3::sort& s) {\n    switch (s.sort_kind()) {\n      case Z3_INT_SORT:\n        return bv_sort_;\n      case Z3_ARRAY_SORT:\n        return ctx().array_sort(TranslateSort(s.array_domain()),\n                                TranslateSort(s.array_range()));\n      default:\n        return s;\n    }\n  }\n\n  z3::expr visitExpr(const z3::expr& e) {\n    return e.decl()(NewArgsExprVector(e));\n  }\n\n  z3::expr visitQUANTIFIER(const z3::expr& e) {\n    z3::expr e_new(e.ctx());\n    vector<Z3_sort> var_sorts;\n    vector<Z3_symbol> var_names;\n    for (unsigned i = 0; i < Z3_get_quantifier_num_bound(e.ctx(), e); i++) {\n      z3::sort var_sort(e.ctx(), Z3_get_quantifier_bound_sort(e.ctx(), e, i));\n      var_sorts.push_back(TranslateSort(var_sort));\n      var_names.push_back(Z3_get_quantifier_bound_name(e.ctx(), e, i));\n    }\n    if (e.is_forall()) {\n      Z3_pattern pats[0];\n      e_new = z3::to_expr(\n          e.ctx(),\n          Z3_mk_forall(e.ctx(), 0, 0, pats, var_sorts.size(),\n                       var_sorts.data(), var_names.data(), lookup(e.body())));\n    } else if (e.is_exists()) {\n      Z3_pattern pats[0];\n      e_new = z3::to_expr(\n          e.ctx(),\n          Z3_mk_exists(e.ctx(), 0, 0, pats, var_sorts.size(),\n                       var_sorts.data(), var_names.data(), lookup(e.body())));\n    } else {\n      EUFORIA_FATAL(\"unknown quantifier\");\n    }\n    // logger.Log(0, \"{}:{}\", e, e.get_sort());\n    // logger.Log(0, \"{}:{}\", e_new, e_new.get_sort());\n    return e_new;\n  }\n\n  z3::expr visitVAR(const z3::expr& e) {\n    auto ret = z3::to_expr(\n        e.ctx(),\n        Z3_mk_bound(e.ctx(), Z3_get_index_value(e.ctx(), e),\n                    TranslateSort(e.get_sort())));\n    return ret;\n  }\n\n  z3::expr visitANUM(const z3::expr& e) {\n    string decimal_str;\n    z3::expr bv(e.ctx());\n    if (!e.is_numeral(decimal_str)) {\n      EUFORIA_FATAL(\"not a numeral: {}\", e);\n    }\n    logger.Log(4, \"found numeral: {}\", decimal_str);\n    mpz_class num(decimal_str);\n    string binstr = num.get_str(2);\n    logger.Log(4, \"    binary: {}\", binstr);\n    // create bits, which has num but padded with zeros\n    string bits(bv_sort_.bv_size(), '0');\n    int width = static_cast<int>(bv_sort_.bv_size());\n    // binstr will be bits if num is positive, and -bits if num is negative\n    if (binstr[0] != '-') {\n      assert(binstr.size() > 0);\n      assert(binstr.size() <= bv_sort_.bv_size());\n      copy(binstr.begin(), binstr.end(),\n           bits.begin() + (bits.size() - binstr.size()));\n      bool bool_bits[width];\n      // bits is in reverse order from what z3 expects; z3 wants LSB first\n      for (int i = 0, j = width-1; i < width; i++, j--) {\n        bool_bits[j] = bits[i] == '0' ? false : true;\n      }\n      bv = ctx().bv_val(width, bool_bits);\n      logger.Log(4, \"    binary padded: {}\", bits);\n    } else {\n      assert(binstr.size() > 1);\n      // create bits, which has num but padded with zeros\n      copy(next(binstr.begin()), binstr.end(),\n           next(bits.begin()) + (bits.size() - binstr.size()));\n      logger.Log(4, \"    binary uminus: {}\", bits);\n      bool bool_bits[width];\n      // bits is in reverse order from what z3 expects; z3 wants LSB first\n      for (int i = 0, j = width-1; i < width; i++, j--) {\n        bool_bits[j] = bits[i] == '0' ? false : true;\n      }\n      bv = ctx().bv_val(width, bool_bits);\n      // constant 1 bits\n      for (int i = 0; i < width; i++) {\n        bool_bits[i] = true;\n      }\n      auto all_ones = ctx().bv_val(width, bool_bits);\n      // flip all the bits and add one: 2's complement representation \n      bv = bv ^ all_ones;\n      bv = bv + 1;\n      bv = bv.simplify();\n    }\n    logger.Log(4, \"    bv result: {}\", bv);\n    return bv;\n  }\n\n  z3::expr visitUNINTERPRETED(const z3::expr& e) {\n    assert(!e.is_array());\n    // Create an uninterpreted function that takes BVs instead of Ints\n    auto e_decl = e.decl();\n    vector<z3::sort> f_sorts;\n    for (unsigned i = 0; i < e_decl.arity(); i++) {\n      f_sorts.push_back(TranslateSort(e_decl.domain(i)));\n    }\n    auto f_decl = e.ctx().function(\n        e_decl.name(), e_decl.arity(), f_sorts.data(),\n        TranslateSort(e_decl.range()));\n    return f_decl(NewArgsExprVector(e));\n  }\n\n  z3::expr visitSELECT(const z3::expr& e) {\n    logger.Log(4, \"select {}\", e);\n    for (auto&& arg : boost::make_iterator_range(args_begin(e), args_end(e))) {\n      logger.Log(4, \"    rewritten args {}:{}\", arg, arg.get_sort());\n    }\n    return z3::select(arg(e,0), arg(e,1));\n  }\n\n  z3::expr visitSTORE(const z3::expr& e) {\n    return z3::store(arg(e,0), arg(e,1), arg(e,2));\n  }\n\n  z3::expr visitEQ(const z3::expr& e) {\n    return arg(e,0) == arg(e,1);\n  }\n\n  z3::expr visitADD(const z3::expr& e) {\n    z3::expr ret(e.ctx());\n    for (auto&& arg : boost::make_iterator_range(args_begin(e), args_end(e))) {\n      ret = bool(ret) ? ret + arg : arg;\n    }\n    return ret;\n  }\n\n  z3::expr visitSUB(const z3::expr& e) {\n    assert(e.num_args() == 2);\n    return arg(e,0) - arg(e,1);\n  }\n\n  z3::expr visitUMINUS(const z3::expr& e) {\n    return -arg(e,0);\n  }\n\n  z3::expr visitMUL(const z3::expr& e) {\n    assert(e.num_args() == 2);\n    return arg(e,0) * arg(e,1);\n  }\n\n  z3::expr visitDIV(const z3::expr& e) {\n    return arg(e,0) / arg(e,1); // signed division\n  }\n\n  z3::expr visitIDIV(const z3::expr& e) {\n    return arg(e,0) / arg(e,1);\n  }\n\n  z3::expr visitREM(const z3::expr& e) {\n    return z3::srem(arg(e,0), arg(e,1));\n  }\n\n  z3::expr visitMOD(const z3::expr& e) {\n    return z3::smod(arg(e,0), arg(e,1));\n  }\n\n  z3::expr visitLE(const z3::expr& e) {\n    return arg(e,0) <= arg(e,1);\n  }\n\n  z3::expr visitLT(const z3::expr& e) {\n    return arg(e,0) < arg(e,1);\n  }\n\n  z3::expr visitGE(const z3::expr& e) {\n    return arg(e,0) >= arg(e,1);\n  }\n\n  z3::expr visitGT(const z3::expr& e) {\n    return arg(e,0) > arg(e,1);\n  }\n\n  z3::context& ctx() const { return bv_sort_.ctx(); }\n\n private:\n  z3::sort bv_sort_;\n};\n\n//^----------------------------------------------------------------------------^\n//\n\nclass HornRule {\n public:\n  HornRule(const z3::expr& rule, int index) \n      : head_(rule.ctx()), body_(rule.ctx()), rule_(rule), index_(index) {\n    auto b = rule;\n    if (rule.is_quantifier()) {\n      b = rule.body();\n    } else if (is_not(rule) && rule.arg(0).is_quantifier()) {\n      b = rule.arg(0).body();\n    }\n    body_ = ctx().bool_val(true);\n    if (b.is_implies()) {\n      head_ = b.arg(1);\n      body_ = b.arg(0);\n    } else {\n      head_ = b;\n    }\n  }\n\n  bool is_linear() const {\n    IterExprSet visited;\n    int relation_count =\n        count_if(df_expr_ext_iterator::begin(body(), visited),\n                 df_expr_ext_iterator::end(body(), visited),\n                 [&](auto&& x) { return x.is_app() &&\n                     x.decl().decl_kind() == Z3_OP_UNINTERPRETED; });\n    // int relation_count =\n    //     count_if(df_expr_iterator::begin(rule.body()),\n    //              df_expr_iterator::end(rule.body()),\n    //              [&](auto&& x) { return x.is_app() &&\n    //                  relation_vars_.find(x.decl()) != relation_vars_.end(); });\n    if (relation_count > 1) {\n      return false;\n      // throw std::runtime_error(\"nonlinear Horn clause detected, exiting\");\n    }\n    return true;\n  }\n\n  bool is_query() const {\n    if (is_literal_false(head())) {\n      return true;\n    }\n   if (is_not(head()) &&\n       head().arg(0).decl().decl_kind() == Z3_OP_UNINTERPRETED) {\n     return true;\n   }\n   return false;\n  }\n\n  int index() const { return index_; }\n  z3::context& ctx() const { return head_.ctx(); }\n  z3::expr head() const { return head_; }\n  z3::expr body() const { return body_; }\n  operator z3::expr() const { return rule_; }\n  std::string head_name() const {\n    return head_.decl().name().str();\n  }\n\n private:\n  z3::expr head_;\n  z3::expr body_;\n  z3::expr rule_;\n  int index_;\n};\n\nstd::ostream& operator<<(std::ostream& os, const HornRule& r) {\n  fmt::print(os, \"HornRule: head {} body:\\n{}\", r.head(), r.body());\n  return os;\n}\n\n//^----------------------------------------------------------------------------^\n//\n\n//! Groups a set of Horn clauses all of which have the same head symbol. The\n//! head symbol is determined by the first rule added to the group.\nclass HornTransition {\n public:\n  HornTransition() {}\n\n  void AddRule(const HornRule& r, int i) {\n    if (head_name_) {\n      if (r.head_name() != head_name()) {\n        throw std::runtime_error(\n            fmt::format(\"adding bad rule to {} group: {}\", *head_name_, r));\n      }\n    } else {\n      head_name_ = r.head_name();\n    }\n    rules_.push_back({r,i});\n  }\n\n  const std::string& head_name() const { return *head_name_; }\n  const std::vector<HornRule>& rules() const { return rules_; }\n\n private:\n  boost::optional<std::string> head_name_;\n  std::vector<HornRule> rules_;\n};\n\n//^----------------------------------------------------------------------------^\n//\n\n// Represents a complete set of Horn clauses -- a model checking instance -- as\n// a collection of rules. Supports parsing both SMT2-style and\n// declare-rel-style Horn clauses, thanks to z3.\nclass HornClauses {\n public:\n  HornClauses(z3::context& c, const char *filename, bool int2bv = false) \n      : ctx_(c) {\n\n    // Reads file into buffer because we may need to parse twice\n    std::ifstream fin(filename);\n    std::stringstream sstr;\n    sstr << fin.rdbuf();\n    auto filebuf = sstr.str();\n\n    // Parses as declare-rel at first\n    z3::fixedpoint fp(ctx());\n    auto vec = Z3_fixedpoint_from_string(c, fp, filebuf.c_str());\n    if (!vec) {\n      fmt::print(cerr, \"Parse error: {}\", filename);\n      exit(1);\n    }\n    auto queries = z3::ast_vector_tpl<z3::expr>(c, vec);\n    z3::expr_vector rules(c);\n    rules = fp.rules();\n    \n    if (queries.size() > 0) {\n      assert(queries[0].num_args() == 0);\n      rules.push_back(z3::implies(queries[0], ctx().bool_val(false)));\n    }\n\n    if (rules.empty()) {\n      logger.Log(2, \"0 fp rules found, so parsing as smtlib2\");\n      // Parses again as SMTLIB-2 HORN file\n      rules = ctx().parse_string(filebuf.c_str());\n    }\n    logger.Log(1, \"parsed {} rules\", rules.size());\n    if (int2bv) {\n      Int2BvRewriter rewrite_int2bv(ctx(), 32);\n      for (unsigned i = 0; i < rules.size(); i++) {\n        auto r = rewrite_int2bv(rules[i]);\n        rules.set(i, r);\n      }\n    }\n    rules_.reserve(rules.size());\n    for (unsigned i = 0; i < rules.size(); i++) {\n      rules_.push_back(HornRule(rules[i], i));\n    }\n  }\n\n  z3::context& ctx() const { return ctx_; }\n\n  // Iterates over the database as HornRules\n  auto rules() const {\n    return boost::make_iterator_range(rules_.begin(), rules_.end());\n  }\n\n  FuncDeclMap<HornTransition> group_by_heads() const {\n    using namespace boost::adaptors; // indexed\n    // Groups horn rules by head symbol\n    FuncDeclMap<HornTransition> head2trans;\n    for (const auto& indexed_rule : rules() | indexed(0)) {\n      const auto& index = indexed_rule.index();\n      const auto& rule = indexed_rule.value();\n      head2trans[rule.head().decl()].AddRule(rule, index);\n    }\n    return head2trans;\n  }\n\n  size_t size() const { return rules_.size(); }\n \n private:\n  z3::context& ctx_;\n  // Contains all the rules plus the query written as a rule (false => head)\n  std::vector<HornRule> rules_;\n};\n\n//^----------------------------------------------------------------------------^\n//\n\nusing RelationVarMap = FuncDeclMap<z3::expr>;\nusing PlaceVarsMap = FuncDeclMap<vector<z3::expr>>;\n\nstatic string SortName(const z3::sort& sort) {\n  if (sort.is_bv()) {\n    return fmt::format(\"bv{}\", sort.bv_size());\n  } else if (sort.is_bool()) {\n    return \"bool\";\n  } else if (sort.is_array()) {\n    auto domain_name = SortName(sort.array_domain());\n    auto range_name = SortName(sort.array_range());\n    return fmt::format(\"arr-{}-{}\", domain_name, range_name);\n  } else {\n    fmt::print(\"{}\\n\", sort);\n    EUFORIA_FATAL(\"unhandled sort\");\n  }\n}\n\n\n//! Represents the state space for translating a set of Horn clauses. Creates\n//! relation variables, place variables, and rule activation inputs. All such\n//! objects are created in the current output transition system, set in the\n//! constructor and via set_output_xsys.\n//!\n//! This can be used to represent the state space for an entire set of clauses.\n//! But it also has the flexibility of representing the state space for a\n//! subset of clauses.\nclass HornTransStateSpace {\n public:\n  HornTransStateSpace() : xsys_(nullptr) {}\n  HornTransStateSpace(Config& cfg, const std::vector<HornRule>& rules,\n                      VmtTransitionSystem *xsys) \n      : xsys_(xsys) {\n    SortMap<std::vector<z3::expr>> relation_places_by_sort;\n    for (const auto& rule : rules) {\n      logger.Log(3, \"creating state space for rule: {} => {}\", rule.body(),\n                 rule.head());\n      // Creates rule activation variables\n      auto rule_activation_input =\n          ctx().bool_const((\"r-\" + to_string(rule.index())).c_str());\n      auto& rule_activation = xsys_->AddInput(MakeInput(rule_activation_input));\n      activation_input_vars_.push_back(rule_activation);\n      // Pick up relations from rule heads; then declare Boolean relation vars\n      // and place vars for each place. \n      if (auto decl = rule.head().decl();\n          decl.decl_kind() == Z3_OP_UNINTERPRETED) {\n        // Create r elation var\n        auto relation_name = decl.name().str();\n        auto var_name = \"at-\" + relation_name;\n        if (xsys_->FindVar(var_name)) { // Skips present variables.\n          continue;\n        }\n        auto& var = xsys_->AddVar(MakeStateVar(\n                ctx().bool_const(var_name.c_str()),\n                ctx().bool_const((var_name + \"+\").c_str())));\n        relation_vars_.insert({decl, var.current()});\n        // Ensures vector is initialized for all relations, even nullary ones\n        (void)place_vars_[decl];\n        // Open varmap file, if we need to\n        ofstream varmap_out;\n        if (cfg.varmap_filename) {\n          varmap_out = ofstream(*cfg.varmap_filename);\n          if (!varmap_out) {\n            fmt::print(cerr, \"warning: could not open varmap file: {}:\\n{}\\n\",\n                       *cfg.varmap_filename, strerror(errno));\n            cfg.varmap_filename = boost::none;\n          }\n        }\n        if (cfg.allocate_vars_by_sort) {\n          SortMap<int> counts;\n          for (unsigned i = 0; i < decl.arity(); i++) {\n            if (counts.find(decl.domain(i)) == counts.end()) {\n              counts[decl.domain(i)] = 0;\n            }\n            counts[decl.domain(i)] += 1;\n          }\n          for (auto&& [sort, num_occurrences] : counts) {\n            int num_places =\n                static_cast<int>(relation_places_by_sort[sort].size());\n            for (int i = 0; i < (num_occurrences - num_places); i++) {\n              auto name =\n                  (SortName(sort) + \"-place-\" + to_string(num_places+i));\n              auto& place_var = xsys_->AddVar(MakeStateVar(\n                      ctx().constant(name.c_str(), sort),\n                      ctx().constant((name + \"+\").c_str(), sort)));\n              relation_places_by_sort[sort].push_back(place_var.current());\n            }\n          }\n          counts.clear();\n          for (unsigned i = 0; i < decl.arity(); i++) {\n            auto place_var = relation_places_by_sort.at(\n                decl.domain(i))[counts[decl.domain(i)]];\n            if (varmap_out) {\n              fmt::print(varmap_out, \"Relation {} place {} mapped to var {}\\n\",\n                         relation_name, i, place_var);\n            }\n            // EUFORIA_DEBUG_BREAK;\n            place_vars_[decl].push_back(place_var);\n            counts[decl.domain(i)]++;\n          }\n        } else {\n          // allocate vars by relation\n          for (unsigned i = 0; i < decl.arity(); i++) {\n            auto place_name = relation_name + \"-place-\" + to_string(i);\n            auto& place_var = xsys_->AddVar(MakeStateVar(\n                    ctx().constant(place_name.c_str(), decl.domain(i)),\n                    ctx().constant((place_name + \"+\").c_str(),\n                                   decl.domain(i))));\n            if (varmap_out) {\n              fmt::print(varmap_out, \"Relation {} place {} mapped to var {}\\n\",\n                         relation_name, i, place_var.current());\n            }\n            place_vars_[decl].push_back(place_var.current());\n          }\n        }\n      }\n    }\n    logger.Log(3, \"created {} state variables\", xsys_->num_vars());\n    if (logger.ShouldLog(4)) {\n      for (auto&& v : xsys_->vars()) {\n        logger.Log(4, \"  {}\", v.current());\n      }\n    }\n    logger.Log(3, \"created {} inputs\", xsys_->num_inputs());\n  }\n\n  const StateVar& get_head_relation_var(const HornRule& r) const {\n    auto& v_expr = relation_vars_.at(r.head().decl());\n    return *xsys_->FindVar(v_expr);\n  } \n\n  const PrimaryInput& get_activation_var(const HornRule& r) const {\n    auto& i_expr = activation_input_vars_.at(r.index());\n    return *xsys_->FindInput(i_expr);\n  }\n\n  auto iter_place_vars(const z3::expr& e) const {\n    class GetVar {\n     public:\n      GetVar(const VmtTransitionSystem& xsys) : xsys_(xsys) {}\n      const StateVar& operator()(const z3::expr& var) const {\n        return *xsys_.FindVar(var);\n      }\n     private:\n      const VmtTransitionSystem& xsys_;\n    };\n    const auto& place_var_vec = place_vars_.at(e.decl());\n    return boost::make_iterator_range(\n        boost::make_transform_iterator(begin(place_var_vec),\n                                       GetVar(*xsys_)),\n        boost::make_transform_iterator(end(place_var_vec),\n                                       GetVar(*xsys_)));\n  }\n\n  //! Iterates over the place variables for the relation in r's head\n  auto iter_head_place_vars(const HornRule& r) const {\n    return iter_place_vars(r.head());\n  }\n\n  //! Iterates over the Boolean relation vars in the transition system\n  auto relation_vars() const {\n    class GetVar {\n     public:\n      GetVar(const VmtTransitionSystem& xsys) : xsys_(xsys) {}\n      const StateVar& operator()(const RelationVarMap::value_type& p) const {\n        return *xsys_.FindVar(p.second);\n      }\n      const VmtTransitionSystem& xsys_;\n    };\n    return boost::make_iterator_range(\n        boost::make_transform_iterator(relation_vars_.begin(), GetVar(*xsys_)),\n        boost::make_transform_iterator(relation_vars_.end(), GetVar(*xsys_)));\n  }\n\n  auto activation_input_vars_begin() const {\n    return activation_input_vars_.cbegin();\n  }\n\n  auto activation_input_vars_end() const {\n    return activation_input_vars_.cend();\n  }\n\n  //! Returns zipped iterator over [ <e-arg-0, place-var-0>, <e-arg-1,\n  //! place-var-1>, ... ]. Precondition: e must be an unintpreted Horn relation\n  //! symbol.\n  auto iter_args_with_places(const z3::expr& e) const {\n    assert(e.num_args() == place_vars_.at(e.decl()).size());\n    return boost::combine(ExprArgs(e), iter_place_vars(e));\n  }\n\n  //! Finds Boolean relation var for uninterpreted application e\n  boost::optional<z3::expr> find_relation_var(const z3::expr& e) const {\n    if (auto search = relation_vars_.find(e.decl());\n        search != relation_vars_.end()) {\n      return search->second;\n    }\n    return boost::none;\n  }\n\n  z3::context& ctx() const { return xsys_->ctx(); }\n  VmtTransitionSystem& xsys() const { return *xsys_; }\n  size_t num_relations() const { return relation_vars_.size(); }\n\n  void set_output_xsys(VmtTransitionSystem *xsys) { xsys_ = xsys; }\n \n private:\n  // output to\n  VmtTransitionSystem *xsys_;\n  // Maps func_decl to Boolean state var\n  RelationVarMap relation_vars_;\n  // List of Boolean state vars\n  std::vector<z3::expr> activation_input_vars_;\n  // Maps func_decl to list of place state vars\n  PlaceVarsMap place_vars_;\n};\n\n//^----------------------------------------------------------------------------^\n//\n//! Helper for rewriting the bodies of Horn clauses in terms of relation vars\n//! and place vars\nclass Horn2VmtRewriter : public ExprRewriter<Horn2VmtRewriter> {\n public:\n  Horn2VmtRewriter(const HornTransStateSpace& space) : space_(space) {}\n\n  z3::expr operator()(const z3::expr& e) { return Rewrite(e); }\n\n  // Precondition: e is a sub-formula of a Horn clause body.\n  // If e is a relation occurrence, rewrites it in T-land using the relation\n  // and place variables. Otherwise, simply rewrites e using previously\n  // rewritten children.\n  z3::expr visit(const z3::expr& e) {\n    if (e.is_app()) {\n      if (auto e_var = space_.find_relation_var(e)) {\n        z3::expr_vector conj(e.ctx());\n        ExprVectorInserter out(conj);\n        *out++ = *e_var;\n        for (auto&& zipped : space_.iter_args_with_places(e)) {\n          z3::expr arg = boost::get<0>(zipped);\n          const StateVar& place_var = boost::get<1>(zipped);\n          *out++ = (arg == place_var.current());\n        }\n        return expr_mk_and(conj);\n      }\n      return e.decl()(NewArgsExprVector(e));\n    }\n    return e;\n  }\n\n private:\n  const HornTransStateSpace& space_;\n};\n\n//^----------------------------------------------------------------------------^\n//\n//! Represents the translation of a set of Horn clauses into a transition\n//! relation. The transition relation is \"functional\" in that each state\n//! variable has exactly one top-level equation for it; the activation vars are\n//! also at the top level as implications.\n//!\n//! Anything head isn't simply H(...) for some uninterpreted H gets put into\n//! queries()\nclass HornSetTrans {\n public:\n  HornSetTrans(const HornTransStateSpace& space,\n                     const std::vector<HornRule>& rules) \n      : trans_(space.ctx()), to_vmt_(space) {\n    ExprAndInserter trans_out(trans_);\n    CreateQuantifiedVarInputs(space, rules);\n    for (const auto& rule : rules) {\n      if (rule.head().decl().decl_kind() != Z3_OP_UNINTERPRETED) {\n        queries_.push_back(rule);\n        continue;\n      }\n      const auto& activation_var = space.get_activation_var(rule);\n      // Translates head and body.\n      if (config.allocate_vars_by_sort) {\n        // Don't worry about it if we're using the normal allocation strategy\n        if (!rule.is_linear()) {\n          throw std::runtime_error(\"nonlinear Horn clause detected, exiting\");\n        }\n      }\n      // Fills in var_subst_curr for rule: find var occurrences in relations:\n      // 1. if it's a variable, maps [var -> place curr-state variable];\n      // 2. otherwise, maps [var -> fresh input]\n      ExprSubstitution var_subst_curr = make_var_subst(space, rule);\n      // Removes relation occurrences from the rule's body and replaces them\n      // with relation vars and place vars\n      auto body_condition = to_vmt_(rule.body());\n      logger.Log(3, \"Rule {} condition from Horn:\\n{}\", rule.index(),\n                 body_condition);\n      // Removes bound vars from body_condition\n      body_condition = var_subst_curr(body_condition);\n      auto rule_condition = z3::implies(activation_var, body_condition);\n      logger.Log(2, \"Global rule {} condition to emit:\\n{}\",\n                 rule.index(), rule_condition);\n      // Done processing body, but it hasn't emitted the rule yet: it'll figure\n      // out below which one to emit.\n\n      *trans_out++ = rule_condition; // emit the rule condition\n\n      // Adds this rule's next state to state-update cones\n      CreateConesFromRule(space, rule, var_subst_curr);\n    }\n\n    // Sends next-state cones, which are complete, to the transition relation\n    for (auto it = cones_.begin(), ie = cones_.end(); it != ie;\n         // Erases them because they could free a lot of memory\n         it = cones_.erase(it)) {\n      auto&& [next_var, val] = *it;\n      if (next_var.is_bool()) {\n        val = val.simplify();\n      }\n      *trans_out++ = (next_var == val);\n    }\n    \n    // Adds one-hot constraints for rules: exactly one rule should be chosen on\n    // each transition.\n    if (config.enable_one_hots) {\n      OneHotConstraints ohc(space.ctx());\n      ohc.insert(space.activation_input_vars_begin(),\n                 space.activation_input_vars_end());\n      if (space.activation_input_vars_begin() !=\n          space.activation_input_vars_end()) {\n        *trans_out++ = ohc.at_most(OneHotConstraints::Config::Commander(3));\n        // *trans_out++ = ohc.at_most(OneHotConstraints::Config::Naive());\n        for (auto&& v : ohc.commander_vars()) {\n          space.xsys().AddInput(MakeInput(v));\n        }\n      }\n    }\n  }\n\n  void CreateConesFromRule(const HornTransStateSpace& space,\n                      const HornRule& rule,\n                      const ExprSubstitution& var_subst_curr) {\n      const auto& activation_var = space.get_activation_var(rule);\n      const auto& relation_var = space.get_head_relation_var(rule);\n      // The code below fills in cones_, the list of next-state equations for\n      // the state variables updated by this rule.\n      auto else_elt =\n          cones_.insert({relation_var.next(),\n                        relation_var.current()}).first;\n      else_elt->second = z3::ite(activation_var, rule.ctx().bool_val(true),\n                                 else_elt->second);\n      for (auto&& zipped : space.iter_args_with_places(rule.head())) {\n        z3::expr arg = boost::get<0>(zipped);\n        const StateVar& place_var = boost::get<1>(zipped);\n        else_elt = \n            cones_.insert({place_var.next(),\n                          place_var.current()}).first;\n        else_elt->second = z3::ite(activation_var, var_subst_curr(arg),\n                                   else_elt->second);\n      }\n      logger.Log(3, \"cones fir this rule\");\n      for (auto&& [next_var, val] : cones_) {\n        logger.Log(3, \"    {}: {}\", next_var, val);\n      }\n  }\n\n  // outputs to rule_input_vars_\n  void CreateQuantifiedVarInputs(const HornTransStateSpace& space,\n                                 const vector<HornRule>& rules) {\n    SortMap<std::vector<PrimaryInputRef>> rule_places_by_sort;\n    for (auto& rule : rules) {\n      // Makes any inputs required to express the quantified variables in the\n      // rule, binning them by sort\n      if (z3::expr rule_expr = rule; rule_expr.is_quantifier()) {\n        const unsigned num_bound_vars =\n            Z3_get_quantifier_num_bound(rule_expr.ctx(), rule_expr); \n        if (config.allocate_inputs_by_sort) {\n          SortMap<int> counts;\n          for (unsigned i = 0; i < num_bound_vars; i++) {\n            z3::sort sort(\n                rule_expr.ctx(),\n                Z3_get_quantifier_bound_sort(rule_expr.ctx(), rule_expr, i));\n            if (counts.find(sort) == counts.end()) {\n              counts[sort] = 0;\n            }\n            counts[sort]++;\n          }\n          for (auto&& [sort, num_occurrences] : counts) {\n            int num_places =\n                static_cast<int>(rule_places_by_sort[sort].size());\n            for (int i = 0; i < (num_occurrences - num_places); i++) {\n              auto name =\n                  (SortName(sort) + \"-input-\" + to_string(num_places+i));\n              auto& input_var = space.xsys().AddInput(MakeInput(\n                      ctx().constant(name.c_str(), sort)));\n              rule_places_by_sort[sort].push_back(input_var);\n            }\n          }\n          counts.clear();\n          for (unsigned i = 0; i < num_bound_vars; i++) {\n            z3::sort sort(\n                rule_expr.ctx(),\n                Z3_get_quantifier_bound_sort(rule_expr.ctx(), rule_expr, i));\n            auto var = rule_places_by_sort.at(sort)[counts[sort]];\n            rule_input_vars_[rule.index()].push_back(var);\n            counts[sort]++;\n          }\n          // Apparently the de-bruijn indices of variables are the revers from\n          // the way they would be in a list...there's some verbiage to this\n          // effect in the constructor for forall's in the Z3 documentation but\n          // I didn't realize it would extend to this API. I guess it does. \n          std::reverse(rule_input_vars_[rule.index()].begin(),\n                       rule_input_vars_[rule.index()].end());\n        } else {\n          // Create inputs named input-<rule-number>-<deBruijn index>\n          for (unsigned i = 0; i < num_bound_vars; i++) {\n            z3::sort sort(\n                rule_expr.ctx(),\n                Z3_get_quantifier_bound_sort(rule_expr.ctx(), rule_expr, i));\n            z3::symbol var_name(\n                rule_expr.ctx(),\n                Z3_get_quantifier_bound_name(rule_expr.ctx(), rule_expr, i));\n            auto name = fmt::format(\"input-{}-{}\", rule.index(), var_name.str());\n            auto& input_var = space.xsys().AddInput(\n                MakeInput(ctx().constant(name.c_str(), sort)));\n            rule_input_vars_[rule.index()].push_back(input_var);\n          }\n          std::reverse(rule_input_vars_[rule.index()].begin(),\n                       rule_input_vars_[rule.index()].end());\n        }\n      }\n\n    }\n  }\n\n  z3::expr trans() const { return trans_; }\n  z3::context& ctx() const { return trans_.ctx(); }\n\n  auto queries() {\n    return boost::make_iterator_range(queries_.begin(), queries_.end());\n  }\n\n  z3::expr translate(const z3::expr& e) {\n    return to_vmt_(e);\n  }\n\n  const PrimaryInput& get_rule_input_var(const HornRule& r,\n                                         const z3::expr& bound_var) const {\n    // The inputs are indexed by rule and de-Bruijn index of the bound var\n    return rule_input_vars_.at(r.index()).at(\n        Z3_get_index_value(bound_var.ctx(), bound_var));\n  }\n\n private:\n  // Transition relation that has been translated from the Horn set\n  z3::expr trans_;\n  // Maps rule index to quantifier var place inputs\n  unordered_map<int, vector<PrimaryInputRef>> rule_input_vars_;\n  ExprMap<z3::expr> cones_;\n  std::vector<HornRule> queries_;\n  Horn2VmtRewriter to_vmt_;\n  ExprSubstitution make_var_subst(\n      const HornTransStateSpace&, const HornRule& rule);\n};\n  \nExprSubstitution HornSetTrans::make_var_subst(\n    const HornTransStateSpace& space, const HornRule& rule) {\n  ExprSubstitution var_subst_curr(rule.ctx());\n  // Set of vars mapped to places by visit_map_var()\n  IterExprSet vars_with_places;\n  // Set of all visited nodes for df traversal\n  IterExprSet visited;\n  // Precondition: e is a sub-expression of rule.body().\n  // visit_map_var(), for a relation occurrence R(a,b,c,...), looks in a,b,c\n  // for variable occurrences (as opposed to expressions) and maps them\n  // directly to place vars, because this helps EUForia's pre-image\n  // computation.\n  auto visit_map_var = [&](const z3::expr& e) {\n    if (e.is_app()) {\n      if (auto e_var = space.find_relation_var(e)) {\n        logger.Log(3, \"--- visiting relation {}\", e.decl());\n        for (auto&& zipped : space.iter_args_with_places(e)) {\n          z3::expr arg = boost::get<0>(zipped);\n          const StateVar& place_var = boost::get<1>(zipped);\n          if (arg.is_var()) {\n            vars_with_places.insert(arg);\n            logger.Log(3, \"adding place_var [{} / {}] to var_subst_curr\",\n                       arg, place_var);\n            var_subst_curr.AddSubstitution(arg, place_var.current());\n          }\n        }\n      }\n    }\n  };\n  // Precondition: e is a sub-expression of anything in rule that hasn't been\n  // visited by visit_map_var().\n  auto visit_create_input = [&](const z3::expr& e) {\n    if (e.is_var()) {\n      // for (unsigned i = 0; i < rule_input_vars.size(); i++) {\n      //   auto input = rule_input_vars[i];\n      //   logger.Log(3, \"    rule_place {}: {}:{}\", i, input, input.get_sort());\n      // }\n      // const z3::expr& i_expr = rule_input_vars[Z3_get_index_value(e.ctx(), e)];\n      const z3::expr& i_expr = get_rule_input_var(rule, e);\n      // auto fresh_input = \n      //     ctx().constant((\"y-\" + to_string(counter_++)).c_str(), e.get_sort());\n      // auto& input = xsys_.AddInput(MakeInput(fresh_input));\n      var_subst_curr.AddSubstitution(e, i_expr);\n      logger.Log(3, \"adding input [{} / {}] to var_subst_curr\", e, i_expr);\n    }\n  };\n  \n  // put var -> place in subst for anything in body\n  for_each(df_expr_ext_iterator::begin(rule.body(), visited),\n           df_expr_ext_iterator::end(rule.body(), visited), visit_map_var);\n  // fill in rest woth var -> input, over body and head, but skip visiting any\n  // vars already mapped to places\n  visited = vars_with_places; \n  for_each(df_expr_ext_iterator::begin(rule.body(), visited),\n           df_expr_ext_iterator::end(rule.body(), visited), visit_create_input);\n  for_each(df_expr_ext_iterator::begin(rule.head(), visited),\n           df_expr_ext_iterator::end(rule.head(), visited), visit_create_input);\n  return var_subst_curr;\n}\n\n} // end anonymous namespace\n\n//^----------------------------------------------------------------------------^\n//\n\nclass Horn2Vmt {\n public:\n  Horn2Vmt(const HornTransStateSpace& space, const vector<HornRule>& all_rules) \n      : state_space_(space), rules_(all_rules) {\n    // Sets transition relation\n    HornSetTrans all_trans(state_space_, all_rules);\n    xsys().set_trans(all_trans.trans());\n\n    // Sets property\n    for (const auto& rule : all_trans.queries()) {\n      if (is_not(rule.head()) &&\n          rule.head().arg(0).decl().decl_kind() == Z3_OP_UNINTERPRETED) {\n        // property is denoted by (assert !R)\n        xsys().set_property(all_trans.translate(rule.head()));\n      } else if (z3::eq(rule.head(), ctx().bool_val(false))) {\n        // property is denoted by (R => false)\n        xsys().set_property(!all_trans.translate(rule.body()));\n      } else {\n        EUFORIA_FATAL(\"unrecognized rule: {} => {}\", rule.body(), rule.head());\n      }\n    }\n    \n    // Sets initial state. In the initial state, all relations are false.\n    z3::expr init(ctx());\n    boost::transform(\n        state_space_.relation_vars(), ExprAndInserter(init),\n        [&](auto&& var) { return !var.current(); });\n    xsys().set_init_state(init);\n\n    // Performs normalizations that make Z3 a happy boi\n    NnfRewriter nnf;\n    ExprFlattener flatten;\n    auto normalize = [&](auto&& e) {\n      nnf.Reset(); flatten.Reset(); return flatten(nnf(e)); };\n    xsys().RewriteSystem(normalize);\n  }\n\n  void Print(std::ostream& os) const {\n    int64_t index = 0;\n    fmt::print(os, \"; {} rules\\n\", rules_.size());\n    fmt::print(os, \"; {} relations\\n\", state_space_.num_relations());\n    fmt::print(os, \"; {} state vars\\n\", xsys().num_vars());\n    for (auto&& var : xsys().vars()) {\n      fmt::print(os, \"{}\\n\", var.current().decl());\n      fmt::print(os, \"{}\\n\", var.next().decl());\n      fmt::print(os, \"(define-fun .def{} () {} (! {} :next {}))\\n\", index,\n                 var.current().get_sort(), var.current(),\n                 var.next());\n      ++index;\n    }\n    fmt::print(os, \"; {} inputs\\n\", xsys().num_inputs());\n    for (const z3::expr& input : xsys().inputs()) {\n      fmt::print(os, \"{}\\n\", input.decl());\n    }\n    fmt::print(os, \"(define-fun .def{} () Bool (! {} :init true))\\n\",\n               index++, xsys().init_state());\n    fmt::print(os, \"(define-fun .def{} () Bool (! {} :trans true))\\n\",\n               index++, xsys().trans());\n    fmt::print(os, \"(define-fun .def{} () Bool (! {} :invar-property 0))\\n\",\n               index, xsys().property());\n  }\n\n  // XXX instead of vmt print this in SMT2??????\n  void PrintTrans(std::ostream& os) {\n    int64_t index = 0;\n    fmt::print(os, \"; {} rules\\n\", rules_.size());\n    fmt::print(os, \"; {} relations\\n\", state_space_.num_relations());\n    fmt::print(os, \"; {} state vars\\n\", xsys().num_vars());\n    fmt::print(os, \"; begin state vars\\n\");\n    // XXX print all declares in a block then print the defines after in a block so they're easier to delet\n    for (auto&& var : xsys().vars()) {\n      fmt::print(os, \"{}\\n\", var.current().decl());\n      fmt::print(os, \"{}\\n\", var.next().decl());\n      // fmt::print(os, \"(define-fun .def{} () {} (! {} :next {}))\\n\", index,\n      //            var.current().get_sort(), var.current(),\n      //            var.next());\n      ++index;\n    }\n    fmt::print(os, \"; end state vars\\n\");\n    fmt::print(os, \"; {} inputs\\n\", xsys().num_inputs());\n    fmt::print(os, \"; begin inputs\\n\");\n    for (const z3::expr& input : xsys().inputs()) {\n      fmt::print(os, \"{}\\n\", input.decl());\n    }\n    fmt::print(os, \"; end inputs\\n\");\n    fmt::print(os, \"(declare-fun .trans () Bool)\\n\");\n    fmt::print(os, \"(assert (= .trans {}))\\n\", xsys().trans());\n    // fmt::print(os, \"(define-fun .def{} () Bool (! {} :trans true))\\n\",\n    //            index++, xsys().trans());\n  }\n\n\n  z3::context& ctx() const { return state_space_.ctx(); }\n\n private:\n  const HornTransStateSpace& state_space_;\n  const vector<HornRule>& rules_;\n  \n  const VmtTransitionSystem& xsys() const { return state_space_.xsys(); }\n  VmtTransitionSystem& xsys() { return state_space_.xsys(); }\n};\n\n\n//^----------------------------------------------------------------------------^\n//\nnamespace po = boost::program_options;\n\npo::options_description desc(\"options\");\n\nint main(int argc, char **argv) {\n  // option parsing\n  desc.add_options()\n      (\"help,h\", \"help\")\n      (\"v\", po::value<int>()->default_value(0), \"set log level\")\n      (\"int2bv\", \"convert ints to bvs as well\")\n      (\"slice\", po::value<string>()->default_value(\"\"), \n       \"output sliced transition using given prefix (suppresses normal output)\")\n      (\"onehots\", po::value<bool>()->default_value(true),\n       \"enable explicit one-hot transition constraints\")\n      (\"varmap\", po::value<string>(),\n       \"output mapping between relation places and state variables to this file\")\n      (\"strategy\", po::value<string>()->default_value(\"relation\"),\n       \"sort - allocates one state variable per distinct place of a given sort\\nrelation - allocates one state variable per relation place\")\n      (\"input-file\", po::value<string>(), \"SMT2 file to convert\");\n  po::positional_options_description pd;\n  pd.add(\"input-file\", -1);\n  po::variables_map opts;\n  po::store(po::command_line_parser(argc, argv).\n            options(desc).positional(pd).run(), opts);\n  po::notify(opts);\n\n  if (!opts.count(\"input-file\")) {\n    fmt::print(cerr, \"error: missing input-file\\n\");\n  }\n  if (opts.count(\"help\") || !opts.count(\"input-file\")) {\n    fmt::print(cout, \"{} input-file\\n\", argv[0]);\n    fmt::print(cout, \"{}\\n\", desc);\n    return EXIT_FAILURE;\n  }\n\n  logger.set_level(opts[\"v\"].as<int>());\n\n  config.enable_one_hots = opts[\"onehots\"].as<bool>();\n\n  config.allocate_vars_by_sort = true;\n  if (opts[\"strategy\"].as<string>() == \"relation\") {\n    config.allocate_vars_by_sort = false;\n  }\n  if (auto strat = opts[\"strategy\"].as<string>();\n      !(strat == \"sort\" || strat == \"relation\")) {\n    fmt::print(cerr, \"error: unknown variable allocation strategy: {}\\n\",\n               strat);\n    return EXIT_FAILURE;\n  }\n\n  if (opts.count(\"varmap\")) {\n    config.varmap_filename = string(opts[\"varmap\"].as<string>());\n  }\n\n  auto slice_prefix = opts[\"slice\"].as<string>();\n  config.slice_t = slice_prefix != \"\";\n\n  z3::context ctx;\n  config.input_filename = opts[\"input-file\"].as<string>();\n  HornClauses clause_db(ctx, config.input_filename.c_str(),\n                        bool(opts.count(\"int2bv\")));\n  if (config.slice_t) {\n    logger.Log(1, \"config: slicing T into multiple files\");\n    int i = 0;\n    auto head2trans = clause_db.group_by_heads();\n    vector<HornTransition> queries;\n    VmtTransitionSystem xsys(ctx);\n    vector<HornRule> all_rules;\n    boost::copy(clause_db.rules(), back_inserter(all_rules));\n    HornTransStateSpace space(config, all_rules, &xsys);\n    for (auto&& [head, horn_trans] : head2trans) {\n      if (boost::algorithm::all_of(\n              horn_trans.rules(),\n              [](const HornRule& r) { return r.is_query(); })) {\n        logger.Log(0, \"skipping {} queries due to T slicing\",\n                   horn_trans.rules().size());\n        continue;\n      }\n      \n      // Inputs for quantified vars will be created during translation to Vmt;\n      // make sure those go into xsys_copy since they shouldn't interact with\n      // other slices of T.\n      VmtTransitionSystem xsys_copy(xsys);\n      space.set_output_xsys(&xsys_copy);\n      logger.Log(1, \"translating {} clauses for slice of {}\",\n                 horn_trans.rules().size(), head.name());\n      std::vector<HornRule> rules;\n      boost::copy(horn_trans.rules(), back_inserter(rules));\n      Horn2Vmt h2v(space, rules);\n      ofstream trans_out(fmt::format(\"{}{}.vmt\", slice_prefix, i));\n      fmt::print(trans_out, \"; common head: {}\\n\", head.name());\n      h2v.PrintTrans(trans_out);\n      logger.Log(1, \"slice of {} written to {}{}.vmt\", head.name(),\n                 slice_prefix, i);\n      i++;\n    }\n  } else {\n    VmtTransitionSystem xsys(ctx);\n    std::vector<HornRule> all_rules;\n    boost::copy(clause_db.rules(), back_inserter(all_rules));\n    HornTransStateSpace space(config, all_rules, &xsys);\n    Horn2Vmt h2v(space, all_rules);\n    h2v.Print(std::cout);\n  }\n\n  if (config.varmap_filename) {\n    logger.Log(1, \"wrote varmap to {}\", *config.varmap_filename);\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "be8b1ed068eb6a295923800c5035de7cec05577d", "size": 43124, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/horn2vmt/main.cc", "max_stars_repo_name": "dbueno/euforia", "max_stars_repo_head_hexsha": "1833ce6d6c645ca41fb21026ec87e896d9e5257d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-06T23:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T23:23:35.000Z", "max_issues_repo_path": "tools/horn2vmt/main.cc", "max_issues_repo_name": "dbueno/euforia", "max_issues_repo_head_hexsha": "1833ce6d6c645ca41fb21026ec87e896d9e5257d", "max_issues_repo_licenses": ["MIT"], "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/horn2vmt/main.cc", "max_forks_repo_name": "dbueno/euforia", "max_forks_repo_head_hexsha": "1833ce6d6c645ca41fb21026ec87e896d9e5257d", "max_forks_repo_licenses": ["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.3608768971, "max_line_length": 228, "alphanum_fraction": 0.5956080141, "num_tokens": 11039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749626, "lm_q2_score": 0.012821216789139214, "lm_q1q2_score": 0.0045614672130260756}}
{"text": "// ===============================================================================================================\n// Copyright (c) 2019, Cornell University. 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//\n//     * Redistributions of source code must retain the above copyright otice, this list of conditions and\n//       the following disclaimer.\n//\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//       \n//     * Neither the name of Cornell University nor the names of its contributors may be used to endorse or\n//       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\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, 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 POSSIBILITY\n// OF SUCH DAMAGE.\n//\n// Author: Kai Zhang (kz298@cornell.edu)\n//\n// The research is based upon work supported by the Office of the Director of National Intelligence (ODNI),     \n// Intelligence Advanced Research Projects Activity (IARPA), via DOI/IBC Contract Number D17PC00287.            \n// The U.S. Government is authorized to reproduce and distribute copies of this work for Governmental purposes. \n// ===============================================================================================================\n//\n//\n// Copyright (c) 2018, 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 \"mvs/image.h\"\n\n#include <Eigen/Core>\n\n#include \"base/projection.h\"\n#include \"util/logging.h\"\n\nnamespace colmap {\nnamespace mvs {\n\n// helper function\ninline void Compute4by4ProjectionMatrix(const double K[9],\n\t\tconst double R[9],\n\t\tconst double T[9],\n\t\tconst double last_row[4],\n\t\tdouble P[16], double inv_P[16]) {\n\t  // 3 by 4 projection matrix\n\t  Eigen::Matrix<double, 3, 4, Eigen::RowMajor> P_3by4;\n\t  P_3by4.leftCols<3>() = Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(R);\n\t  P_3by4.rightCols<1>() = Eigen::Map<const Eigen::Matrix<double, 3, 1>>(T);\n\t  P_3by4 = Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(K) * P_3by4;\n\n\t  // 4 by 4 projection matrix\n\t  Eigen::Matrix<double, 4, 4, Eigen::RowMajor> P_4by4;\n\t  P_4by4.block<3, 4>(0, 0) = P_3by4;\n\t  P_4by4.row(3) = Eigen::Map<const Eigen::Matrix<double, 1, 4>>(last_row);\n\n\t  // try to make the projection matrix more numerically stable\n\t  // scale all the numbers to lie in [0, 10]\n\t  P_4by4 *= (10.0 / P_4by4.maxCoeff());\n\n\t  memcpy(P, P_4by4.data(), 16 * sizeof(double));\n\n\t  Eigen::Matrix<double, 4, 4, Eigen::RowMajor> inv_P_4by4 = P_4by4.inverse();\n\n\t  inv_P_4by4 *= (10.0 / inv_P_4by4.maxCoeff());\n\n\t  memcpy(inv_P, inv_P_4by4.data(), 16 * sizeof(double));\n}\n\n// helper function\ninline void ComputeProjectionCenter(const double R[9], const double T[9],\n\t\t\t\t\t\t\t\t\tdouble C[3]) {\n\t  // 3 by 4 projection matrix\n\t  Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> R_mat(R);\n\t  Eigen::Map<const Eigen::Matrix<double, 3, 1>> T_mat(T);\n\t  const Eigen::Matrix<double, 3, 1> C_mat = -R_mat.transpose() * T_mat;\n\n\t  memcpy(C, C_mat.data(), 3 * sizeof(double));\n}\n\n// helper function\ninline void DoubleArrToFloatArr(const double* double_arr, float* float_arr, int cnt) {\n\tfor (int i=0; i<cnt; ++i) {\n\t\tfloat_arr[i] = (float) double_arr[i];\n\t}\n}\n\n\nImage::Image(const std::string& path, const size_t width, const size_t height,\n             const double K[9], const double R[9], const double T[3])\n    : path_(path), width_(width), height_(height) {\n  memcpy(K_, K, 9 * sizeof(double));\n  memcpy(R_, R, 9 * sizeof(double));\n  memcpy(T_, T, 3 * sizeof(double));\n}\n\nvoid Image::SetBitmap(const Bitmap& bitmap) {\n  bitmap_ = bitmap;\n  CHECK_EQ(width_, bitmap_.Width());\n  CHECK_EQ(height_, bitmap_.Height());\n}\n\n\nvoid Image::SetK(const double K[9]) const {\n\tmemcpy(K_, K, 9 * sizeof(double));\n}\n\nsize_t Image::GetWidth() const { return width_; }\n\nsize_t Image::GetHeight() const { return height_; }\n\nconst Bitmap& Image::GetBitmap() const { return bitmap_; }\n\nconst std::string& Image::GetPath() const { return path_; }\n\n\nvoid Image::SetLastRow(const double last_row[4]) {\n  memcpy(last_row_, last_row, 4 * sizeof(double));\n}\n\nfloat Image::GetDepth(double x, double y, double z) const {\n\t  // 3 by 4 projection matrix\n\t  Eigen::Matrix<double, 3, 4, Eigen::RowMajor> P_3by4;\n\t  P_3by4.leftCols<3>() = Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(R_);\n\t  P_3by4.rightCols<1>() = Eigen::Map<const Eigen::Matrix<double, 3, 1>>(T_);\n\t  P_3by4 = Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(K_) * P_3by4;\n\n\t  // 4 by 4 projection matrix\n\t  Eigen::Matrix<double, 4, 4, Eigen::RowMajor> P_4by4;\n\t  P_4by4.block<3, 4>(0, 0) = P_3by4;\n\t  P_4by4.row(3) = Eigen::Map<const Eigen::Matrix<double, 1, 4>>(last_row_);\n\n\t  const Eigen::Matrix<double, 4, 1> X(x, y, z, 1.0);\n\n\t  Eigen::Matrix<double, 4, 1> result = P_4by4 * X;\n\t  // depth is the fourth component\n\t  double depth = result[3] / result[2];\n\n\t  // low precision output\n\t  return (float) depth;\n}\n\nconst double* Image::GetLastRow() const {\n\treturn last_row_;\n}\n\nvoid Image::GetK(float K[9]) const {\n\tDoubleArrToFloatArr(K_, K, 9);\n}\n\nvoid Image::GetRT(float R[9],  float T[3]) const {\n\tDoubleArrToFloatArr(R_, R, 9);\n\tDoubleArrToFloatArr(T_, T, 3);\n}\n\nvoid Image::GetC(float C[3]) const {\n\tdouble C_double[3];\n\tComputeProjectionCenter(R_, T_, C_double);\n\tDoubleArrToFloatArr(C_double, C, 3);\n}\n\nvoid Image::GetCDouble(double C[3]) const {\n\tComputeProjectionCenter(R_, T_, C);\n}\n\n\nvoid Image::GetKDouble(double K[9]) const {\n\tmemcpy(K, K_, 9*sizeof(double));\n}\n\nvoid Image::GetPinvP(float P[16], float inv_P[16]) const {\n\t// compute projection matrix\n\tdouble P_double[16];\n\tdouble inv_P_double[16];\n\tCompute4by4ProjectionMatrix(K_, R_, T_, last_row_, P_double, inv_P_double);\n\n\t// convert to low-precision\n\tDoubleArrToFloatArr(P_double, P, 16);\n\tDoubleArrToFloatArr(inv_P_double, inv_P, 16);\n}\n\nvoid Image::GetPinvPDouble(double P[16], double inv_P[16]) const {\n\t// compute projection matrix\n\tCompute4by4ProjectionMatrix(K_, R_, T_, last_row_, P, inv_P);\n}\n\n// low-precision output\nvoid Image::Original(float K[9], float inv_K[9], float R[9], float T[3], float P[16], float inv_P[16], float C[3]) const{\n\t// compute projection matrix\n\tdouble P_double[16];\n\tdouble inv_P_double[16];\n\tCompute4by4ProjectionMatrix(K_, R_, T_, last_row_, P_double, inv_P_double);\n\n\tdouble C_double[3];\n\tComputeProjectionCenter(R_, T_, C_double);\n\n\t// compute inverse K\n\tconst Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K_mat(K_);\n\tEigen::Matrix<double, 3, 3, Eigen::RowMajor> K_mat_inv = K_mat.inverse();\n\tconst double *K_mat_inv_data = K_mat_inv.data();\n\n\t// convert to low-precision\n\tDoubleArrToFloatArr(K_, K, 9);\n\tDoubleArrToFloatArr(K_mat_inv_data, inv_K, 9);\n\tDoubleArrToFloatArr(R_, R, 9);\n\tDoubleArrToFloatArr(T_, T, 3);\n\tDoubleArrToFloatArr(P_double, P, 16);\n\tDoubleArrToFloatArr(inv_P_double, inv_P, 16);\n\tDoubleArrToFloatArr(C_double, C, 3);\n}\n\ninline void MatrixPrint(float *mat, int row_cnt, int col_cnt) {\n\tfor (int i=0; i<row_cnt; ++i) {\n\t\tfor (int j=0; j<col_cnt; ++j) {\n\t\t\tstd::cout << mat[i*col_cnt+j] << \", \";\n\t\t}\n\t}\n}\n\n//void Image::Rotate90Multi_test(int cnt) const {\n//\tfloat K[9];\n//\tfloat R[9];\n//\tfloat T[3];\n//\tfloat P[16];\n//\tfloat inv_P[16];\n//\tfloat C[3];\n//\n//\tRotate90Multi(cnt, K, R, T, P, inv_P, C);\n//\n//\tfloat K_float[9];\n//\tDoubleArrToFloatArr(K_, K_float, 9);\n//\tstd::cout << \"\\nrot=0, K_: \";\n//\tMatrixPrint(K_float, 3, 3);\n//\tstd::cout << \"\\nwidth, height: \" << width_ << \", \" << height_;\n//\tstd::cout << \"\\nrot=\" << cnt << \", K: \";\n//\tMatrixPrint(K, 3, 3);\n//\n//\tfloat R_float[9];\n//\tDoubleArrToFloatArr(R_, R_float, 9);\n//\tstd::cout << \"\\nrot=0, R_: \";\n//\tMatrixPrint(R_float, 3, 3);\n//\tstd::cout << \"\\nrot=\" << cnt << \", R: \";\n//    MatrixPrint(R, 3, 3);\n//\n//\tfloat T_float[3];\n//\tDoubleArrToFloatArr(T_, T_float, 3);\n//\tstd::cout << \"\\nrot=0, T_: \";\n//\tMatrixPrint(T_float, 3, 1);\n//\tstd::cout << \"\\nrot=\" << cnt << \", T: \";\n//\tMatrixPrint(T, 3, 1);\n//\n//\tfloat last_row_float[4];\n//\tDoubleArrToFloatArr(last_row_, last_row_float, 4);\n//\tstd::cout << \"\\nlast_row_: \";\n//\tMatrixPrint(last_row_float, 1, 4);\n//\tstd::cout << \"\\nrot=\" << cnt << \", P: \";\n//\tMatrixPrint(P, 4, 4);\n//\tstd::cout << \"\\nrot=\" << cnt << \", inv_P: \";\n//\tMatrixPrint(inv_P, 4, 4);\n//\n//\tstd::cout << std::endl;\n//}\n\nvoid Image::Rotate90Multi(int cnt, float K[9], float inv_K[9], float R[9], float T[3], float P[16], float inv_P[16], float C[3]) const {\n\tswitch (cnt % 4) {\n\tcase 0:\n\t\tOriginal(K, inv_K, R, T, P, inv_P, C);\n\t\tbreak;\n\tcase 1:\n\t\tRotate90(K, inv_K, R, T, P, inv_P, C);\n\t\tbreak;\n\tcase 2:\n\t\tRotate180(K, inv_K, R, T, P, inv_P, C);\n\t\tbreak;\n\tcase 3:\n\t\tRotate270(K, inv_K, R, T, P, inv_P, C);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\n// rotate the camera coordinate frame by 90 degrees\n// a 3d point (X, Y, Z) in camera coordinate frame is rotated to (Y, -X, Z)\n// the corresponing pixel (u, v) is rotated to (v, w-1-u)\n// [u; v; 1] = K[X; Y; Z]\n// needs to modify the intrinsics so that the new mapping holds, i.e.,\n// [v; w-1-u; 1] = K'[Y; -X; Z]\n// first, [X; Y; Z]= [0, -1, 0; 1, 0, 0; 0, 0, 1][Y; -X; Z]\n// then, [v; w-1-u; 1] = [0, 1, 0; -1, 0, w-1; 0, 0, 1][u; v; 1]\nvoid Image::Rotate90(float K[9], float inv_K[9], float R[9], float T[3], float P[16], float inv_P[16], float C[3]) const {\n    // modify intrinsics\n    const Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K_old(K_);\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> A;\n    A << 0, 1, 0, -1, 0, width_-1, 0, 0, 1;\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> B;\n    B << 0, -1, 0, 1, 0, 0, 0, 0, 1;\n\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> K_new = A * K_old * B;\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> K_new_inv = K_new.inverse();\n\n\t// modify extrinsics\n\tEigen::Matrix<double, 3, 3, Eigen::RowMajor> rot;\n\trot << 0.0, 1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0;\n\tconst Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> R_old(R_);\n\tconst Eigen::Map<const Eigen::Matrix<double, 3, 1>> T_old(T_);\n\n\tconst Eigen::Matrix<double, 3, 3, Eigen::RowMajor> R_new = rot * R_old;\n\tconst Eigen::Matrix<double, 3, 1> T_new = rot * T_old;\n\n\tconst double *K_new_data = K_new.data();\n\tconst double *K_new_inv_data = K_new_inv.data();\n\tconst double *R_new_data = R_new.data();\n\tconst double *T_new_data = T_new.data();\n\n\t// compute projection matrix\n\tdouble P_new_double[16];\n\tdouble inv_P_new_double[16];\n\tCompute4by4ProjectionMatrix(K_new_data, R_new_data, T_new_data, last_row_, P_new_double, inv_P_new_double);\n\n\t// compute projection center\n\tdouble C_new_double[3];\n\tComputeProjectionCenter(R_new_data, T_new_data, C_new_double);\n\n\t// convert to low-precision\n\tDoubleArrToFloatArr(K_new_data, K, 9);\n\tDoubleArrToFloatArr(K_new_inv_data, inv_K, 9);\n\tDoubleArrToFloatArr(R_new_data, R, 9);\n\tDoubleArrToFloatArr(T_new_data, T, 3);\n\tDoubleArrToFloatArr(P_new_double, P, 16);\n\tDoubleArrToFloatArr(inv_P_new_double, inv_P, 16);\n\tDoubleArrToFloatArr(C_new_double, C, 3);\n}\n\n// a 3d point (X, Y, Z) in camera coordinate frame is rotated to (-X, -Y, Z)\n// the corresponing pixel (u, v) is rotated to (w-1-u, h-1-v)\n// [u; v; 1] = K[X; Y; Z]\n// needs to modify the intrinsics so that the new mapping holds, i.e.,\n// [w-1-u; h-1-v ; 1] = K'[-X; -Y; Z]\n// first, [X; Y; Z]= [-1, 0, 0; 0, -1, 0; 0, 0, 1][-X; -Y; Z]\n// then, [w-1-u; h-1-v; 1] = [-1, 0, w-1; 0, -1, h-1; 0, 0, 1][u; v; 1]\nvoid Image::Rotate180(float K[9], float inv_K[9], float R[9], float T[3], float P[16], float inv_P[16], float C[3]) const {\n    // modify intrinsics\n    const Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K_old(K_);\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> A;\n    A << -1, 0, width_-1, 0, -1, height_-1, 0, 0, 1;\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> B;\n    B << -1, 0, 0, 0, -1, 0, 0, 0, 1;\n\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> K_new = A * K_old * B;\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> K_new_inv = K_new.inverse();\n\n\t// modify extrinsics\n\tEigen::Matrix<double, 3, 3, Eigen::RowMajor> rot;\n\trot << 0.0, 1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0;\n\trot = rot * rot;\n\tconst Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> R_old(R_);\n\tconst Eigen::Map<const Eigen::Matrix<double, 3, 1>> T_old(T_);\n\n\tconst Eigen::Matrix<double, 3, 3, Eigen::RowMajor> R_new = rot * R_old;\n\tconst Eigen::Matrix<double, 3, 1> T_new = rot * T_old;\n\n\tconst double *K_new_data = K_new.data();\n\tconst double *K_new_inv_data = K_new_inv.data();\n\tconst double *R_new_data = R_new.data();\n\tconst double *T_new_data = T_new.data();\n\n\t// compute projection matrix\n\tdouble P_new_double[16];\n\tdouble inv_P_new_double[16];\n\tCompute4by4ProjectionMatrix(K_new_data, R_new_data, T_new_data, last_row_, P_new_double, inv_P_new_double);\n\n\t// compute projection center\n\tdouble C_new_double[3];\n\tComputeProjectionCenter(R_new_data, T_new_data, C_new_double);\n\n\t// convert to low-precision\n\tDoubleArrToFloatArr(K_new_data, K, 9);\n\tDoubleArrToFloatArr(K_new_inv_data, inv_K, 9);\n\tDoubleArrToFloatArr(R_new_data, R, 9);\n\tDoubleArrToFloatArr(T_new_data, T, 3);\n\tDoubleArrToFloatArr(P_new_double, P, 16);\n\tDoubleArrToFloatArr(inv_P_new_double, inv_P, 16);\n\tDoubleArrToFloatArr(C_new_double, C, 3);\n}\n\n// a 3d point (X, Y, Z) in camera coordinate frame is rotated to (-Y, X, Z)\n// the corresponing pixel (u, v) is rotated to (h-1-v, u)\n// needs to modify the intrinsics so that the new mapping holds, i.e.,\n// [h-1-v; u ; 1] = K'[-Y; X; Z]\n// first, [X; Y; Z]= [0, 1, 0; -1, 0, 0; 0, 0, 1][-Y; X; Z]\n// then, [h-1-v; u; 1] = [0, -1, h-1; 1, 0, 0; 0, 0, 1][u; v; 1]\nvoid Image::Rotate270(float K[9], float inv_K[9], float R[9], float T[3], float P[16], float inv_P[16], float C[3]) const {\n    // modify intrinsics\n    const Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K_old(K_);\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> A;\n    A << 0, -1, height_-1, 1, 0, 0, 0, 0, 1;\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> B;\n    B << 0, 1, 0, -1, 0, 0, 0, 0, 1;\n\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> K_new = A * K_old * B;\n    Eigen::Matrix<double, 3, 3, Eigen::RowMajor> K_new_inv = K_new.inverse();\n\n    // modify extrinsics\n\tEigen::Matrix<double, 3, 3, Eigen::RowMajor> rot;\n\trot << 0.0, 1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0;\n\trot = rot * rot * rot;\n\tconst Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> R_old(R_);\n\tconst Eigen::Map<const Eigen::Matrix<double, 3, 1>> T_old(T_);\n\n\tconst Eigen::Matrix<double, 3, 3, Eigen::RowMajor> R_new = rot * R_old;\n\tconst Eigen::Matrix<double, 3, 1> T_new = rot * T_old;\n\n\tconst double *K_new_data = K_new.data();\n\tconst double *K_new_inv_data = K_new_inv.data();\n\tconst double *R_new_data = R_new.data();\n\tconst double *T_new_data = T_new.data();\n\n\t// compute projection matrix\n\tdouble P_new_double[16];\n\tdouble inv_P_new_double[16];\n\tCompute4by4ProjectionMatrix(K_new_data, R_new_data, T_new_data, last_row_, P_new_double, inv_P_new_double);\n\n\t// compute projection center\n\tdouble C_new_double[3];\n\tComputeProjectionCenter(R_new_data, T_new_data, C_new_double);\n\n\t// convert to low-precision\n\tDoubleArrToFloatArr(K_new_data, K, 9);\n\tDoubleArrToFloatArr(K_new_inv_data, inv_K, 9);\n\tDoubleArrToFloatArr(R_new_data, R, 9);\n\tDoubleArrToFloatArr(T_new_data, T, 3);\n\tDoubleArrToFloatArr(P_new_double, P, 16);\n\tDoubleArrToFloatArr(inv_P_new_double, inv_P, 16);\n\tDoubleArrToFloatArr(C_new_double, C, 3);\n}\n\n\nvoid Image::Rescale(const float factor) { Rescale(factor, factor); }\n\nvoid Image::Rescale(const float factor_x, const float factor_y) {\n  const size_t new_width = std::round(width_ * factor_x);\n  const size_t new_height = std::round(height_ * factor_y);\n\n  if (bitmap_.Data() != nullptr) {\n    bitmap_.Rescale(new_width, new_height);\n  }\n\n  const double scale_x = new_width / static_cast<float>(width_);\n  const double scale_y = new_height / static_cast<float>(height_);\n  K_[0] *= scale_x;\n  K_[1] *= scale_x;\n  K_[2] *= scale_x;\n  K_[4] *= scale_y;\n  K_[5] *= scale_y;\n\n  width_ = new_width;\n  height_ = new_height;\n}\n\n\nvoid Image::Downsize(const size_t max_width, const size_t max_height) {\n  if (width_ <= max_width && height_ <= max_height) {\n    return;\n  }\n  const float factor_x = static_cast<float>(max_width) / width_;\n  const float factor_y = static_cast<float>(max_height) / height_;\n  Rescale(std::min(factor_x, factor_y));\n}\n\n\n}  // namespace mvs\n}  // namespace colmap\n", "meta": {"hexsha": "865cfaaf1b3b3b5373922e51e06aefce789a9b0b", "size": 18890, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mvs/image.cc", "max_stars_repo_name": "zemogoravla/ColmapForVisSat", "max_stars_repo_head_hexsha": "696399edbbc469be794a82a87e783fc9b9a31ed8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T04:08:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T17:01:39.000Z", "max_issues_repo_path": "src/mvs/image.cc", "max_issues_repo_name": "zemogoravla/ColmapForVisSat", "max_issues_repo_head_hexsha": "696399edbbc469be794a82a87e783fc9b9a31ed8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T08:40:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-15T08:33:39.000Z", "max_forks_repo_path": "src/mvs/image.cc", "max_forks_repo_name": "zemogoravla/ColmapForVisSat", "max_forks_repo_head_hexsha": "696399edbbc469be794a82a87e783fc9b9a31ed8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-16T08:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T04:27:01.000Z", "avg_line_length": 37.1850393701, "max_line_length": 136, "alphanum_fraction": 0.6697194283, "num_tokens": 5976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.01566364845319895, "lm_q1q2_score": 0.004557821994997615}}
{"text": "/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n\n/*! \n * \\file calibrate_share_weight_visitor.cpp\n * \\ingroup Objects\n * \\brief The CalibrateShareWeightVisitor class source file.\n * \\author Pralit Patel\n */\n\n#include \"util/base/include/definitions.h\"\n#include <cassert>\n#include <boost/math/tr1.hpp>\n\n#include \"util/base/include/calibrate_share_weight_visitor.h\"\n#include \"technologies/include/technology_container.h\"\n#include \"technologies/include/itechnology.h\"\n#include \"sectors/include/subsector.h\"\n#include \"sectors/include/nesting_subsector.h\"\n#include \"sectors/include/sector.h\"\n#include \"containers/include/gdp.h\"\n#include \"util/logger/include/ilogger.h\"\n#include \"functions/include/idiscrete_choice.hpp\"\n\nusing namespace std;\n\nextern Scenario* scenario;\n\n/*!\n * \\brief Constructor\n * \\param aRegionName Name of the region if starting the visiting below the\n *        region level.\n */\nCalibrateShareWeightVisitor::CalibrateShareWeightVisitor( const string& aRegionName, const GDP* aGDP )\n:mCurrentRegionName( aRegionName ), mGDP( aGDP )\n{\n}\n\n/*!\n * \\brief A generic method to calculate share-weights based off of calibrated outputs\n * \\details This method will make share-weights relative to the child container that has\n *          has the largest share, which will be given a share-weight of 1.\n *\n *          Note that because we want to generalize this routine to avoid code duplication\n *          but we have to deal with ContainerType that do not share a common interface we\n *          will rely on the following adaptor methods being defined to supply the behavior\n *          appropriate for the derived types that this tempalted function gets instatiated\n *          with:\n *            - getChildren: to get a vector of child containers to calculate share-weights for\n *            - isAvailable: determine if this child is \"available\" (i.e. not fixed)\n *            - getCalValue: get calibrated output of child to determine share\n *            - getCost: get cost of child\n *            - getFuelPrefElasticity: get fuel preference elasticity of child\n *            - getDiscreteChoice: get the discrete choice function to use\n *            - setShareWeight: sets the calibrated share-weight into the child\n *\n * \\param aContainer The container who's children need to have their share-weights calibrated.\n * \\param aPeriod The current model period.\n */\ntemplate<typename ContainerType>\nvoid CalibrateShareWeightVisitor::calibrateShareWeights( const ContainerType* aContainer, const int aPeriod ) const\n{\n    // Find out if we need to do calibration, make sure we do not have a mix of calibrated/non-calibrated\n    // children, and figure out the largest child to make the other children anchored by it.\n    int anchorIndex = -1;\n    bool hasCalValues = false;\n    double maxCalValue = 0;\n    int numCalChildren = 0;\n    double totalCalValue = 0;\n    auto childrenVec = getChildren( aContainer, aPeriod );\n    for( int childIndex = 0; childIndex < childrenVec.size(); ++childIndex ) {\n        double currCalValue = getCalValue( childrenVec[ childIndex ], aPeriod );\n        bool isAvail = isAvailable( childrenVec[ childIndex ], aPeriod );\n        \n        // check if the child is calibrated\n        if( hasCalValues && currCalValue <= 0 && isAvail ) {\n            // warn that we mixed calibrated and variable children\n            ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n            ILogger& calibrationLog = ILogger::getLogger( \"calibration_log\" );\n            mainLog.setLevel( ILogger::WARNING );\n            calibrationLog.setLevel( ILogger::WARNING );\n            mainLog << \"Mixed calibrated and variable children or read a zero calibration value in Region: \"\n                    << mCurrentRegionName << \" in sector: \" << mCurrentSectorName\n                    << \" for container: \" << childrenVec[ childIndex ]->getName() << endl;\n            calibrationLog << \"Mixed calibrated and variable children or read a zero calibration value in Region: \"\n                    << mCurrentRegionName << \" in sector: \" << mCurrentSectorName\n                    << \" for container: \" << childrenVec[ childIndex ]->getName() << endl;\n        }\n        else if( currCalValue > 0 ) {\n            hasCalValues = true;\n        }\n        \n        // If the calibrated value > 0 then increase the number of children to calibrate\n        // and include it in the total sum.\n        if( currCalValue > 0 ) {\n            ++numCalChildren;\n            totalCalValue += currCalValue;\n        }\n        \n        // attempt to locate the largest child\n        if( currCalValue > maxCalValue ) {\n            maxCalValue = currCalValue;\n            anchorIndex = childIndex;\n        }\n    }\n    \n    // If we are using the abosolute choice function, then we need to\n    // set the base cost for the model.  We will calculate an appropriate\n    // base cost and let the discrete choice function use it if it needs it.\n    \n    // The base cost is equal to the highest cost child that has a share if we\n    // have calibration data.  Otherwise, it is equal to the highest cost child\n    // that has a valid cost; otherwise, we may be in trouble if a user did not\n    // parse a value.\n    double baseCost = 0;\n    for( int childIndex = 0; childIndex < childrenVec.size(); ++childIndex ) {\n        double currCost = getCost( childrenVec[ childIndex ], aPeriod );\n        if( !boost::math::isnan( currCost )  && currCost > baseCost &&\n           ( ( hasCalValues && getCalValue( childrenVec[ childIndex ], aPeriod ) > 0 ) || !hasCalValues ) )\n        {\n            baseCost = currCost;\n        }\n    }\n    // In the case where there is only one child we will reset the base-price\n    // to one as the sharing should not matter.\n    if( baseCost == 0 && childrenVec.size() == 1 ) {\n        baseCost = 1;\n    }\n    // baseCost may still be zero and if a user did not parse a base cost an error\n    // will be generated.\n    IDiscreteChoice* choiceFn = getDiscreteChoice( aContainer );\n    choiceFn->setBaseValue( baseCost );\n    \n    // do calibration if we have cal values and there are more than one child in this nest\n    if( hasCalValues && numCalChildren > 1 ) {\n        // we should have found a child to have share weights anchored\n        assert( anchorIndex != -1 );\n        const double scaledGdpPerCapita = mGDP->getBestScaledGDPperCap( aPeriod );\n        const double anchorCost = getCost( childrenVec[ anchorIndex ], aPeriod );\n        const double anchorShare = ( getCalValue( childrenVec[ anchorIndex ], aPeriod )\n                                    / totalCalValue ) / pow( scaledGdpPerCapita, getFuelPrefElasticity( childrenVec[ anchorIndex ], aPeriod ) );\n        assert( anchorShare > 0 );\n        \n        for( int childIndex = 0; childIndex < childrenVec.size(); ++childIndex ) {\n            auto currChild = childrenVec[ childIndex ];\n            double currShare = ( getCalValue( currChild, aPeriod ) / totalCalValue )\n                / pow( scaledGdpPerCapita, getFuelPrefElasticity( currChild, aPeriod ) );\n            \n            // only set the share weight for valid children\n            if( currShare > 0 ) {\n                double currCost = getCost( currChild, aPeriod );\n                \n                double currShareWeight = choiceFn->calcShareWeight( currShare, currCost,\n                                                                    anchorShare, anchorCost, aPeriod );\n                setShareWeight( currChild, currShareWeight, aPeriod );\n            }\n        }\n    }\n    \n}\n\n// adaptor methods that allows us to generically define calibrateShareWeights even\n// though Sector/Subsector/Technology do not share a common interface\nstd::vector<Subsector*> CalibrateShareWeightVisitor::getChildren( const Sector* aSector, const int aPeriod ) const {\n    return aSector->mSubsectors;\n}\nstd::vector<Subsector*> CalibrateShareWeightVisitor::getChildren( const NestingSubsector* aSubsector, const int aPeriod ) const {\n    return aSubsector->mSubsectors;\n}\nstd::vector<ITechnology*> CalibrateShareWeightVisitor::getChildren( const Subsector* aSubsector, const int aPeriod ) const {\n    vector<ITechnology*> ret( aSubsector->mTechContainers.size() );\n    size_t index = 0;\n    for( auto techContainer : aSubsector->mTechContainers ) {\n        ret[index++] = techContainer->getNewVintageTechnology( aPeriod );\n    }\n    return ret;\n}\n\nbool CalibrateShareWeightVisitor::isAvailable( const Subsector* aSubsector, const int aPeriod ) const {\n    return !( aSubsector->containsOnlyFixedOutputTechnologies( aPeriod )\n        || aSubsector->mShareWeights[ aPeriod ] == 0 );\n}\nbool CalibrateShareWeightVisitor::isAvailable( const ITechnology* aTechnology, const int aPeriod ) const {\n    return aTechnology->isAvailable( aPeriod );\n}\n\ndouble CalibrateShareWeightVisitor::getCalValue( const Subsector* aSubsector, const int aPeriod ) const {\n    return aSubsector->getTotalCalOutputs( aPeriod );\n}\ndouble CalibrateShareWeightVisitor::getCalValue( const ITechnology* aTechnology, const int aPeriod ) const {\n    const bool hasRequired = false;\n    const string requiredName = \"\";\n    return aTechnology->getCalibrationOutput( hasRequired, requiredName, aPeriod );\n}\n\ndouble CalibrateShareWeightVisitor::getCost( const Subsector* aSubsector, const int aPeriod ) const {\n    return aSubsector->getPrice( mGDP, aPeriod );\n}\ndouble CalibrateShareWeightVisitor::getCost( const ITechnology* aTechnology, const int aPeriod ) const {\n    return aTechnology->getCost( aPeriod );\n}\n\ndouble CalibrateShareWeightVisitor::getFuelPrefElasticity( const Subsector* aSubsector, const int aPeriod ) const {\n    return aSubsector->mFuelPrefElasticity[ aPeriod ];\n}\ndouble CalibrateShareWeightVisitor::getFuelPrefElasticity( const ITechnology* aTechnology, const int aPeriod ) const {\n    return aTechnology->calcFuelPrefElasticity( aPeriod );\n}\n\nIDiscreteChoice* CalibrateShareWeightVisitor::getDiscreteChoice( const Sector* aSector ) const {\n    return aSector->mDiscreteChoiceModel;\n}\nIDiscreteChoice* CalibrateShareWeightVisitor::getDiscreteChoice( const Subsector* aSubsector ) const {\n    return aSubsector->mDiscreteChoiceModel;\n}\n\nvoid CalibrateShareWeightVisitor::setShareWeight( Subsector* aSubsector,\n                                                  const double aShareWeight,\n                                                  const int aPeriod ) const\n{\n    aSubsector->mShareWeights[ aPeriod ] = aShareWeight;\n}\nvoid CalibrateShareWeightVisitor::setShareWeight( ITechnology* aTechnology,\n                                                  const double aShareWeight,\n                                                  const int aPeriod ) const\n{\n    aTechnology->setShareWeight( aShareWeight );\n}\n\nvoid CalibrateShareWeightVisitor::startVisitSector( const Sector* aSector, const int aPeriod ) {\n    mCurrentSectorName = aSector->getName();\n}\n\nvoid CalibrateShareWeightVisitor::endVisitSector( const Sector* aSector, const int aPeriod ) {\n    // Doing subsector calibration in sector rather than in subsector because we will need access \n    // to all of the subsectors at the same time.  Also we need to do this in end visit sector\n    // because the subsector can't be calculated until we have gotten the correct share weights\n    // for the technologies.\n    \n    calibrateShareWeights( aSector, aPeriod );\n\n    mCurrentSectorName.clear();\n}\n\nvoid CalibrateShareWeightVisitor::startVisitSubsector( const Subsector* aSubsector, const int aPeriod ) {\n    // Doing technology calibration in subsector rather than in technology because we will need access \n    // to all of the technologies at the same time.\n\n    // First we need to make sure that the technologies have calculated their costs.\n    for( auto techContainer : aSubsector->mTechContainers ) {\n        techContainer->getNewVintageTechnology( aPeriod )->calcCost( mCurrentRegionName, mCurrentSectorName, aPeriod );\n    }\n    \n    calibrateShareWeights( aSubsector, aPeriod );\n}\n\nvoid CalibrateShareWeightVisitor::endVisitNestingSubsector( const NestingSubsector* aSubsector, const int aPeriod ) {\n    // We need to do this in end visit NestingSubsector because the child subsector\n    // can't be calculated until we have gotten the correct share weights from the\n    // bottom of the nesting strucutre first.\n    \n    calibrateShareWeights( aSubsector, aPeriod );\n}\n", "meta": {"hexsha": "8d3bd11378a6148bc0175b02c3328aa29092d58b", "size": 13927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp", "max_stars_repo_name": "cmcormack/gcam-core", "max_stars_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T00:28:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T00:28:33.000Z", "max_issues_repo_path": "cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp", "max_issues_repo_name": "cmcormack/gcam-core", "max_issues_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-30T21:13:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-14T13:21:13.000Z", "max_forks_repo_path": "cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp", "max_forks_repo_name": "cmcormack/gcam-core", "max_forks_repo_head_hexsha": "ccbe826dbfeb9ed85472977aac6d36dbbf763a23", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3707482993, "max_line_length": 144, "alphanum_fraction": 0.6949809722, "num_tokens": 3193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.015424554146815088, "lm_q1q2_score": 0.0045381347689317135}}
{"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/Core/Exception.h>          // for ArgumentErr, vw_throw, etc\n#include <vw/Math/Quaternion.h>         // for Quat, Quaternion\n#include <vw/Math/Vector.h>             // for Vector, Vector3, Vector4, etc\n#include <vw/Cartography/Datum.h>       // for Datum\n#include <vw/FileIO/DiskImageResourceGDAL.h>\n\n#include <asp/Camera/XMLBase.h>\n#include <asp/Camera/PeruSatXML.h>\n#include <asp/Camera/RPCModel.h>\n#include <asp/Camera/XMLBase.h>\n\n#include <xercesc/parsers/XercesDOMParser.hpp>\n#include <xercesc/sax/HandlerBase.hpp>\n#include <xercesc/sax/SAXException.hpp>\n#include <xercesc/sax/SAXParseException.hpp>\n#include <xercesc/dom/DOMException.hpp>\n#include <xercesc/util/PlatformUtils.hpp>\n#include <xercesc/sax/ErrorHandler.hpp>\n\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <iomanip>\n\nusing namespace vw;\nusing namespace vw::cartography;\nusing namespace xercesc;\n\nusing asp::XmlUtils::get_node;\nusing asp::XmlUtils::cast_xmlch;\n\nnamespace asp {\n\nDOMElement* PeruSatXML::open_xml_file(std::string const& xml_path) {\n\n  // Check if the file actually exists and throw a user helpful file.\n  if (!boost::filesystem::exists(xml_path))\n    vw_throw(ArgumentErr() << \"XML file \\\"\" << xml_path << \"\\\" does not exist.\");\n\n  std::string error_prefix = \"XML file \\\"\" + xml_path + \"\\\" is invalid.\\nException message is: \\n\";\n  std::string err_message  = \"\"; // Filled in later on error\n\n  try{\n    // Set up the XML parser if we have not already done so\n    if (!m_parser.get()) {\n      m_parser.reset(new XercesDOMParser());\n      m_err_handler.reset(new HandlerBase());\n      m_parser->setValidationScheme(XercesDOMParser::Val_Always);\n      m_parser->setDoNamespaces(true);   \n      m_parser->setErrorHandler(m_err_handler.get());\n    }\n\n    // Load the XML file\n    m_parser->parse(xml_path.c_str());\n    DOMDocument* doc  = m_parser->getDocument();\n    DOMElement * root = doc->getDocumentElement();\n    return root;\n\n  } catch (const XMLException& toCatch) {\n    char* message = XMLString::transcode(toCatch.getMessage());\n    err_message = error_prefix + message;\n    XMLString::release(&message);\n  } catch (const DOMException& toCatch) {\n    char* message = XMLString::transcode(toCatch.msg);\n    err_message = error_prefix + message;\n    XMLString::release(&message);\n  } catch (const SAXException& toCatch) {\n    char* message = XMLString::transcode(toCatch.getMessage());\n    err_message = error_prefix + message;\n    XMLString::release(&message);\n  } catch (const std::exception& e) {\n    err_message = error_prefix + e.what();\n  } catch (...) {\n    err_message = \"Unrecognized error in XML file \\\"\" + xml_path + \"\\\"\\n\";\n  }\n  vw_throw(ArgumentErr() << err_message); // Only get here on error\n\n  return 0;\n}\n\nvoid PeruSatXML::read_xml(std::string const& xml_path) {\n  DOMElement * root = open_xml_file(xml_path);\n  parse_xml(root);\n}\n\nvoid PeruSatXML::parse_xml(xercesc::DOMElement* root) {\n\n  xercesc::DOMElement* metadata_id = get_node<DOMElement>(root, \"Metadata_Identification\");\n\n  xercesc::DOMElement* metadata_profile = get_node<DOMElement>(metadata_id, \"METADATA_PROFILE\");\n\n  std::string sensor_name(XMLString::transcode(metadata_profile->getTextContent()));\n  std::string expected_name = \"PER1_SENSOR\";\n  if (sensor_name != expected_name) \n    vw_throw(ArgumentErr() << \"Incorrect sensor name. Expected: \"\n             << expected_name << \" but got: \" << sensor_name << \".\\n\");\n\n  xercesc::DOMElement* raster_data = get_node<DOMElement>(root, \"Raster_Data\");\n  read_image_size(raster_data);\n  \n  // Dig some levels down\n  xercesc::DOMElement* geometric_data = get_node<DOMElement>(root, \"Geometric_Data\");\n  xercesc::DOMElement* refined_model = get_node<DOMElement>(geometric_data, \"Refined_Model\");\n  \n  xercesc::DOMElement* time = get_node<DOMElement>(refined_model, \"Time\");\n  read_times(time);\n  \n  xercesc::DOMElement* ephemeris = get_node<DOMElement>(refined_model, \"Ephemeris\");\n  read_ephemeris(ephemeris);\n  \n  xercesc::DOMElement* attitudes = get_node<DOMElement>(refined_model, \"Attitudes\");\n  read_attitudes(attitudes);\n  \n  xercesc::DOMElement* geom_calib  = get_node<DOMElement>(refined_model, \"Geometric_Calibration\");\n  xercesc::DOMElement* instr_calib = get_node<DOMElement>(geom_calib,    \"Instrument_Calibration\");\n  xercesc::DOMElement* band_calib  = get_node<DOMElement>(instr_calib,   \"Band_Calibration\");\n  xercesc::DOMElement* look_angles = get_node<DOMElement>(band_calib,    \"Polynomial_Look_Angles\");\n  read_look_angles(look_angles);\n\n  xercesc::DOMElement* instr_biases = get_node<DOMElement>(instr_calib,   \"Instrument_Biases\");\n  read_instr_biases(instr_biases);\n\n  xercesc::DOMElement* use_area = get_node<DOMElement>(geometric_data, \"Use_Area\");\n  xercesc::DOMElement* geom_values = get_node<DOMElement>(use_area,\n                                                          \"Located_Geometric_Values\");\n  read_center_data(geom_values);\n}\n\nvoid PeruSatXML::read_image_size(xercesc::DOMElement* raster_data_node) {\n  xercesc::DOMElement* raster_dims_node = get_node<DOMElement>(raster_data_node,\n                                                                 \"Raster_Dimensions\");\n\n  cast_xmlch(get_node<DOMElement>(raster_dims_node, \"NROWS\")->getTextContent(), m_image_size[1]);\n  cast_xmlch(get_node<DOMElement>(raster_dims_node, \"NCOLS\")->getTextContent(), m_image_size[0]);\n}\n\nvoid PeruSatXML::read_times(xercesc::DOMElement* time) {\n  xercesc::DOMElement* time_range = get_node<DOMElement>(time, \"Time_Range\");\n\n  std::string start_time_str;\n  cast_xmlch(get_node<DOMElement>(time_range, \"START\")->getTextContent(), start_time_str);\n  bool is_start_time = true;\n  m_start_time = PeruSatXML::convert_time(start_time_str, is_start_time);\n\n  xercesc::DOMElement* time_stamp = get_node<DOMElement>(time, \"Time_Stamp\");\n  cast_xmlch(get_node<DOMElement>(time_stamp, \"LINE_PERIOD\")->getTextContent(), m_line_period);\n}\n  \nvoid PeruSatXML::read_ephemeris(xercesc::DOMElement* ephemeris) {\n\n  // Reset data storage\n  m_positions.clear(); \n  m_velocities.clear();\n\n  xercesc::DOMElement* point_list = get_node<DOMElement>(ephemeris, \"Point_List\");\n\n  // Pick out the \"Point\" nodes\n  DOMNodeList* children = point_list->getChildNodes();\n  for (XMLSize_t i = 0; i < children->getLength(); i++) {\n    \n    // Check child node type\n    DOMNode* child = children->item(i);\n    if (child->getNodeType() != DOMNode::ELEMENT_NODE)\n      continue;\n\n    // Check the node name\n    DOMElement* curr_element = dynamic_cast<DOMElement*>(child);\n    std::string tag(XMLString::transcode(curr_element->getTagName()));\n    if (tag.find(\"Point\") == std::string::npos)\n      continue;\n\n    // Get the three sub-nodes\n    std::string time_str, position_str, velocity_str;\n    Vector3 position_vec, velocity_vec;\n    \n    cast_xmlch(get_node<DOMElement>(curr_element, \"LOCATION_XYZ\")->getTextContent(), position_str);\n    cast_xmlch(get_node<DOMElement>(curr_element, \"VELOCITY_XYZ\")->getTextContent(), velocity_str);\n    cast_xmlch(get_node<DOMElement>(curr_element, \"TIME\")->getTextContent(),         time_str);\n\n    bool is_start_time = false;\n    double time = PeruSatXML::convert_time(time_str, is_start_time);\n    \n    std::string delimiters(\",\\t \");\n    position_vec = str_to_vec<Vector3>(position_str, delimiters);\n    velocity_vec = str_to_vec<Vector3>(velocity_str, delimiters);\n\n    m_positions.push_back(std::pair<double, Vector3>(time, position_vec));\n    m_velocities.push_back(std::pair<double, Vector3>(time, velocity_vec));\n  } // End loop through points\n  \n}\n  \nvoid PeruSatXML::read_attitudes(xercesc::DOMElement* attitudes) {\n\n  // Reset data storage\n  m_poses.clear();\n\n  xercesc::DOMElement* quaternion_list = get_node<DOMElement>(attitudes, \"Quaternion_List\");\n\n  // Pick out the \"Quaternion\" nodes\n  DOMNodeList* children = quaternion_list->getChildNodes();\n  for (XMLSize_t i = 0; i < children->getLength(); i++) {\n    \n    // Check child node type\n    DOMNode* child = children->item(i);\n    if (child->getNodeType() != DOMNode::ELEMENT_NODE)\n      continue;\n\n    // Check the node time\n    DOMElement* curr_element = dynamic_cast<DOMElement*>(child);\n    std::string tag(XMLString::transcode(curr_element->getTagName()));\n    if (tag.find(\"Quaternion\") == std::string::npos)\n      continue;\n  \n    // Parse the time and \n\n    std::pair<double, vw::Quaternion<double>> data;\n    std::string time_str;\n    cast_xmlch(get_node<DOMElement>(curr_element, \"TIME\")->getTextContent(), time_str);\n\n    bool is_start_time = false;\n    data.first = PeruSatXML::convert_time(time_str, is_start_time);\n    \n    double w, x, y, z;\n    cast_xmlch(get_node<DOMElement>(curr_element, \"Q0\")->getTextContent(), w);\n    cast_xmlch(get_node<DOMElement>(curr_element, \"Q1\")->getTextContent(), x);\n    cast_xmlch(get_node<DOMElement>(curr_element, \"Q2\")->getTextContent(), y);\n    cast_xmlch(get_node<DOMElement>(curr_element, \"Q3\")->getTextContent(), z);\n    data.second = vw::Quaternion<double>(w, x, y, z);\n\n    // Normalize the quaternions to remove any inaccuracy due to the\n    // limited precision used to save them on disk.\n    data.second = normalize(data.second);\n    \n    m_poses.push_back(data);\n  } // End loop through attitudes\n}\n\nvoid PeruSatXML::read_look_angles(xercesc::DOMElement* look_angles) {\n  std::string delimiters(\",\\t \");\n  std::string tan_psi_x_str;\n  cast_xmlch(get_node<DOMElement>(look_angles, \"LINE_OF_SIGHT_TANPSIX\")->getTextContent(),\n             tan_psi_x_str);\n  m_tan_psi_x = str_to_vec<Vector2>(tan_psi_x_str, delimiters);\n  \n  std::string tan_psi_y_str;\n  cast_xmlch(get_node<DOMElement>(look_angles, \"LINE_OF_SIGHT_TANPSIY\")->getTextContent(),\n             tan_psi_y_str);\n  m_tan_psi_y = str_to_vec<Vector2>(tan_psi_y_str, delimiters);\n}\n\nvoid PeruSatXML::read_instr_biases(xercesc::DOMElement* instr_biases) {\n    \n  double w, x, y, z;\n  cast_xmlch(get_node<DOMElement>(instr_biases, \"Q0\")->getTextContent(), w);\n  cast_xmlch(get_node<DOMElement>(instr_biases, \"Q1\")->getTextContent(), x);\n  cast_xmlch(get_node<DOMElement>(instr_biases, \"Q2\")->getTextContent(), y);\n  cast_xmlch(get_node<DOMElement>(instr_biases, \"Q3\")->getTextContent(), z);\n\n  m_instrument_biases = vw::Quaternion<double>(w, x, y, z);\n}\n\nvoid PeruSatXML::read_center_data(xercesc::DOMElement* geom_values) {\n\n  std::string center_time_str;\n  cast_xmlch(get_node<DOMElement>(geom_values, \"TIME\")->getTextContent(), center_time_str);\n  cast_xmlch(get_node<DOMElement>(geom_values, \"COL\")->getTextContent(), m_center_col);\n  cast_xmlch(get_node<DOMElement>(geom_values, \"ROW\")->getTextContent(), m_center_row);\n\n  bool is_start_time = false;\n  center_time = PeruSatXML::convert_time(center_time_str, is_start_time);\n\n  // Convert from 1-based to 0-based indices.  \n  m_center_col -= 1.0;\n  m_center_row -= 1.0;\n}\n\n// Converts a time from string to double precision value measured in seconds\n// relative to the start time.\n// Input strings look like this: 2008-03-04T12:31:03.08191Z.\ndouble PeruSatXML::convert_time(std::string const& s, bool is_start_time) {\n\n  if (!is_start_time && !m_start_time_is_set) \n    vw::vw_throw(vw::ArgumentErr()\n                 << \"Must set the start time before doing time conversions.\\n\");\n\n  try{\n    // Replace the T with a space so the default Boost function can\n    // parse the time.\n    std::string s2 = s;\n    boost::replace_all(s2, \"T\", \" \");\n\n    // Ensure there are exactly 6 digits for the millisecond or else\n    // Boost will complain.\n    s2 = fix_millisecond(s2);\n\n    boost::posix_time::ptime time = boost::posix_time::time_from_string(s2);\n\n    if (is_start_time) {\n      m_start_time_is_set = true;\n      m_start_time_stamp = time;\n    }\n\n    boost::posix_time::time_duration delta(time - m_start_time_stamp);\n    return delta.total_microseconds() / 1.0e+6;\n    \n  }catch(...){\n    vw::vw_throw(vw::ArgumentErr() << \"Failed to parse time from string: \" << s << \"\\n\");\n  }\n  return -1.0; // Never reached\n}\n\n// Find the time at each line (line starts from 0) by multiplying by\n// the period.  All times are relative to the starting time (see the\n// convert_time() function).\n  \n// Note: PeruSat also has the center time, under Located_Geometric_Values,\n// and that corresponds to line (num_lines - 1)/2.0 as expected. Yet PeruSat\n// also provides there a center row, but that one is wrong and not equal\n// to (num_lines - 1)/2.0.\nvw::camera::LinearTimeInterpolation PeruSatXML::setup_time_func() const {\n  return vw::camera::LinearTimeInterpolation(m_start_time, m_line_period);\n}\n\n// The position is already in GCC, so just pack into a function.\n// - Currently this is identical to the velocity function, but this may change later.\nvw::camera::LagrangianInterpolation PeruSatXML::setup_position_func\n(vw::camera::LinearTimeInterpolation const& time_func) const {\n\n  // Sanity check, we should be able to find the position for each image line\n  size_t num_lines           = m_image_size[1];\n  double first_line_time     = time_func(0);\n  double last_line_time      = time_func(num_lines - 1.0);\n  double num_positions       = m_positions.size();\n  double position_start_time = m_positions.front().first;\n  double position_stop_time  = m_positions.back().first;\n  double position_delta_t    = (position_stop_time - position_start_time) / (num_positions - 1.0);\n  \n  if (position_start_time > first_line_time || position_stop_time < last_line_time)\n    vw_throw(ArgumentErr() << \"The position timestamps do not fully span the \"\n             << \"range of times for the image lines.\");\n\n  // Use Lagrange interpolation with degree 3 polynomials with 4\n  // points in piecewise manner out of 5 provided in the xml\n  // file. This is what the doc recommends.\n  // TODO(oalexan1): Implement Lagrange interpolation of even degree\n  // using an odd number of points, and see if using all 5 points at\n  // once is any better.\n  const int INTERP_RADII = 2; \n  std::vector<double>  time_vec;\n  std::vector<Vector3> position_vec;\n\n  // Loop through the positions and extract values\n  int index = 0;\n  for (auto iter = m_positions.begin(); iter != m_positions.end(); iter++) {\n    time_vec.push_back(iter->first);\n    position_vec.push_back(iter->second);\n\n    // Sanity check. The times at which the positions are given must\n    // be uniformly distributed.\n    if (index > 0) {\n      double err = std::abs(time_vec[index] - time_vec[index - 1] - position_delta_t)\n        / position_delta_t;\n      if (err > 1.0e-6) \n        vw_throw(ArgumentErr() << \"The position timestamps are not uniformly distributed.\");\n    }\n    \n    index++;\n  }\n  \n  // More generic method for variable time intervals\n  // return vw::camera::LagrangianInterpolationVarTime(position_vec, time_vec, INTERP_RADII);\n  \n  // A faster method for when we know the time delta is constant\n  return vw::camera::LagrangianInterpolation(position_vec, position_start_time,\n                                             position_delta_t, position_stop_time, INTERP_RADII);\n}\n  \n// Velocities are the sum of inertial velocities and the instantaneous\n//  Earth rotation.\n\n// The velocity is already in GCC, so just pack into a function.\nvw::camera::LagrangianInterpolation PeruSatXML::setup_velocity_func\n(vw::camera::LinearTimeInterpolation const& time_func) const {\n\n  // Sanity check, we should be able to find the velocity for each image line\n  size_t num_lines           = m_image_size[1];\n  double first_line_time     = time_func(0);\n  double last_line_time      = time_func(num_lines - 1.0);\n  double num_velocities      = m_velocities.size();\n  double velocity_start_time = m_velocities.front().first;\n  double velocity_stop_time  = m_velocities.back().first;\n  double velocity_delta_t    = (velocity_stop_time - velocity_start_time) / (num_velocities - 1.0);\n\n  if (velocity_start_time > first_line_time || velocity_stop_time < last_line_time)\n    vw_throw(ArgumentErr() << \"The velocity timestamps do not fully span the \"\n             << \"range of times for the image lines.\");\n\n  if (velocity_start_time > first_line_time || velocity_stop_time < last_line_time)\n    vw_throw(ArgumentErr() << \"The velocity timestamps do not fully span the \"\n             << \"range of times for the image lines.\");\n\n  // See note when the position function was set up earlier.\n  const int INTERP_RADII = 2;\n  std::vector<double>  time_vec;\n  std::vector<Vector3> velocity_vec;\n\n  // Loop through the velocities and extract values\n  int index = 0;\n  for (auto iter = m_velocities.begin(); iter != m_velocities.end(); iter++) {\n    time_vec.push_back(iter->first);\n    velocity_vec.push_back(iter->second);\n\n    // Sanity check. The times at which the velocitys are given must\n    // be uniformly distributed.\n    if (index > 0) {\n      double err = std::abs(time_vec[index] - time_vec[index - 1] - velocity_delta_t)\n        / velocity_delta_t;\n      if (err > 1.0e-6) \n        vw_throw(ArgumentErr() << \"The velocity timestamps are not uniformly distributed.\");\n    }\n\n    index++;\n  }\n\n  // More generic method for variable time intervals\n  //return vw::camera::LagrangianInterpolationVarTime(velocity_vec, time_vec, INTERP_RADII);\n\n  // A faster method for when we know the time delta is constant\n  return vw::camera::LagrangianInterpolation(velocity_vec, velocity_start_time,\n                                             velocity_delta_t, velocity_stop_time, INTERP_RADII);\n}\n\n// Put the timestamps and poses in vectors and form the pose\n// interpolation object.\n\n// TODO(oalexan1): See if using bicubic pose interpolation (as the\n// SPOT-6 manual suggests) is better than the bilinear interpolation\n// used now.\nvw::camera::SLERPPoseInterpolation PeruSatXML::setup_pose_func\n  (vw::camera::LinearTimeInterpolation const& time_func) const {\n\n  size_t num_lines           = m_image_size[1];\n  double first_line_time     = time_func(0);\n  double last_line_time      = time_func(num_lines - 1.0);\n\n  double num_poses           = m_poses.size();\n  double pose_start_time     = m_poses.front().first;\n  double pose_stop_time      = m_poses.back().first;\n  double pose_delta_t        = (pose_stop_time - pose_start_time) / (num_poses - 1.0);\n\n  if (pose_start_time > first_line_time || pose_stop_time < last_line_time)\n    vw_throw(ArgumentErr() << \"The quaternion timestamps do not fully span the \"\n             << \"range of times for the image lines.\");\n  \n  std::vector<vw::Quaternion<double>> pose_vec(num_poses);\n  std::vector<double>  time_vec(num_poses);\n  int index = 0;\n  for (auto iter = m_poses.begin(); iter != m_poses.end(); iter++) {\n    time_vec[index] = iter->first;\n    pose_vec[index] = iter->second;\n\n    // Sanity check. The times at which the quaternions are given must\n    // be uniformly distributed. The quaternions are sampled more\n    // densely than the positions and velocities, so we tolerate\n    // a bit more divergence from uniform sampling.\n    if (index > 0) {\n      double err = std::abs(time_vec[index] - time_vec[index - 1] - pose_delta_t) / pose_delta_t;\n      if (err > 0.01) \n        vw_throw(ArgumentErr() << \"The quaternion timestamps are not uniformly distributed.\");\n    }\n    \n    index++;\n  }\n\n  // Using splines for pose interpolation changed the DEM heights on\n  // the order of 2 cm, so it appears not to make a difference.\n  bool use_splines = false;\n  double min_time = time_vec.front();\n  return vw::camera::SLERPPoseInterpolation(pose_vec, min_time, pose_delta_t, use_splines);\n}\n  \n// Boost does not like a time string such as \"2017-12-07 15:36:40.90795Z\"\n// because it expects precisely 6 digits after the dot. Fix that.\nstd::string PeruSatXML::fix_millisecond(std::string const& in_str) {\n\n  std::string out_str = \"\";\n  bool found_dot = false;\n  int num_digits_after_dot = 0;\n  for (size_t it = 0; it < in_str.size(); it++) {\n    \n    if (it + 1 < in_str.size()) {\n      // Not yet at the last character\n      \n      if (in_str[it] == '.') {\n        // Found the dot\n        found_dot = true;\n        out_str += in_str[it];\n        continue;\n      }\n\n      if (!found_dot) {\n        // Not at the dot yet\n        out_str += in_str[it];\n        continue;\n      }\n\n      // After the dot\n      if (num_digits_after_dot < 6) {\n        out_str += in_str[it];\n        num_digits_after_dot++;\n      }\n      continue;\n    }\n\n    // At the last character\n    if (in_str[it] >= '0' && in_str[it] <= '9') {\n      // The last character is a digit, just append it\n      if (num_digits_after_dot < 6) {\n        out_str += in_str[it];\n        num_digits_after_dot++;\n      }\n\n      // See if to append more\n      while (num_digits_after_dot < 6) {\n        out_str += \"0\";\n        num_digits_after_dot++;\n      }\n      \n    } else {\n\n      // The last character is not a digit, it is likely a \"Z\"\n      while (num_digits_after_dot < 6) {\n        // Append zeros\n        out_str += \"0\";\n        num_digits_after_dot++;\n      }\n\n      // Append the last character, whatever it is\n      out_str += in_str[it];\n    }\n    \n  } // End iterating over characters\n\n  return out_str;\n}\n  \n  \n} // end namespace asp\n\n\n", "meta": {"hexsha": "d6a9671415feeef1806fda9f45900539ed910aeb", "size": 21850, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Camera/PeruSatXML.cc", "max_stars_repo_name": "PicoJr/StereoPipeline", "max_stars_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 323.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T12:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:52:22.000Z", "max_issues_repo_path": "src/asp/Camera/PeruSatXML.cc", "max_issues_repo_name": "PicoJr/StereoPipeline", "max_issues_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 252.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T16:36:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:34:28.000Z", "max_forks_repo_path": "src/asp/Camera/PeruSatXML.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": 38.3333333333, "max_line_length": 99, "alphanum_fraction": 0.695423341, "num_tokens": 5718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930800741601248, "lm_q2_score": 0.022629198838343276, "lm_q1q2_score": 0.004510180529890943}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"gaussian.h\"\n#include <votca/ctp/segment.h>\n#include <votca/xtp/qminterface.h>\n#include <votca/xtp/aobasis.h>\n#include <boost/algorithm/string.hpp>\n\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <votca/tools/constants.h>\n#include <stdio.h>\n#include <iomanip>\n\n\n\nnamespace votca {\n    namespace xtp {\n      using namespace std;\n\n        void Gaussian::Initialize(tools::Property &options) {\n\n            // GAUSSIAN file names\n            std::string fileName = \"system\";\n            _input_file_name = fileName + \".com\";\n            _log_file_name = fileName + \".log\";\n            _shell_file_name = fileName + \".sh\";\n            _orb_file_name = \"fort.7\";\n            _input_vxc_file_name = fileName + \"-2.com\";\n\n\n            std::string key = \"package\";\n            std::string _name = options.get(key + \".name\").as<std::string> ();\n\n            if (_name != \"gaussian\") {\n                cerr << \"Tried to use \" << _name << \" package. \";\n                throw std::runtime_error(\"Wrong options file\");\n            }\n\n            _executable = options.get(key + \".executable\").as<std::string> ();\n            _charge = options.get(key + \".charge\").as<int> ();\n            _spin = options.get(key + \".spin\").as<int> ();\n            _options = options.get(key + \".options\").as<std::string> ();\n            _memory = options.get(key + \".memory\").as<std::string> ();\n            _threads = options.get(key + \".threads\").as<int> ();\n            _chk_file_name = options.get(key + \".checkpoint\").as<std::string> ();\n            _scratch_dir = options.get(key + \".scratch\").as<std::string> ();\n            _cleanup = options.get(key + \".cleanup\").as<std::string> ();\n\n\n            if (options.exists(key + \".vdWRadii\")) {\n                _vdWfooter = options.get(key + \".vdWRadii\").as<std::string> ();\n            } else _vdWfooter = \"\";\n\n\n            if (options.exists(key + \".outputVxc\")) {\n                _output_Vxc = options.get(key + \".outputVxc\").as<bool> ();\n            } else _output_Vxc = false;\n            \n\n            /* G09 by default deletes functions from the basisset according to some\n             * criterion based on, a.o., the contraction coefficients. This can lead\n             * to inconsistencies when MOs are later used in VOTCA's GWBSE modules\n             * (and other post-processing routines). G09's default can be modified\n             * by the keywork int=nobasistransform. This will add this keyword\n             * automatically to the _options string for runs with G09.\n             */\n            if ( _executable == \"g09\" ){\n                std::string::size_type basistransform_pos = (boost::algorithm::to_lower_copy(_options)).find(\"nobasistransform\");\n                if ( basistransform_pos == std::string::npos ){\n                    _options = _options + \" int=nobasistransform \";\n                }\n            }\n            \n            \n\n\n            // check if the guess keyword is present, if yes, append the guess later\n            std::string::size_type iop_pos = _options.find(\"cards\");\n            if (iop_pos != std::string::npos) {\n                _write_guess = true;\n            } else {\n                _write_guess = false;\n            }\n\n            // check if the pop keyword is present, if yes, get the charges and save them\n            iop_pos = _options.find(\"pop\");\n            if (iop_pos != std::string::npos) {\n                _get_charges = true;\n            } else {\n                _get_charges = false;\n            }\n\n            // check if the charge keyword is present, if yes, get the self energy and save it\n            \n\n            // check if the basis set is available (\"/gen\")\n            iop_pos = _options.find(\"gen\");\n            if (iop_pos != std::string::npos) {\n                _write_basis_set = true;\n                _basisset_name = options.get(key + \".basisset\").as<std::string> ();\n            } else {\n                _write_basis_set = false;\n            }\n\n            // check if pseudopotentials are required (\"pseudo\")\n            iop_pos = _options.find(\"pseudo\");\n            if (iop_pos != std::string::npos) {\n                _write_pseudopotentials = true;\n                _ecp_name = options.get(key + \".ecp\").as<std::string> ();\n            } else {\n                _write_pseudopotentials = false;\n            }\n\n        }\n\n        void Gaussian::WriteChargeOption() {\n          std::string::size_type iop_pos = _options.find(\"charge\");\n          if (iop_pos == std::string::npos) {\n            std::string::size_type pos = _options.find('\\n');\n            if (pos != std::string::npos) {\n              _options.insert(pos, \" charge\");\n            } else {\n              _options = _options + \" charge\";\n            }\n          }\n\n        }\n\n        /* Custom basis sets are written on a per-element basis to\n         * 'elementname'.gbs files, which are then included in the\n         * Gaussian input file using @'elementname'.gbs\n         */\n        void Gaussian::WriteBasisset(std::ofstream& com_file, std::vector<QMAtom*>& qmatoms) {\n\n\n          std::vector<std::string> UniqueElements= FindUniqueElements(qmatoms);\n            BasisSet bs;\n            bs.LoadBasisSet(_basisset_name);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Loaded Basis Set \" << _basisset_name << flush;\n\n            for (const std::string& element_name:UniqueElements) {\n               \n                const Element& element = bs.getElement(element_name);\n                /* Write each basis set to a element_name.gbs file\n                 * and include the gbs file in the com-file via Gaussian's @ function\n                 */\n                std::ofstream el_file;\n                std::string el_file_name = _run_dir + \"/\" + element_name + \".gbs\";\n\n                el_file.open(el_file_name.c_str());\n                // element name, [possibly indeces of centers], zero to indicate the end    \n                com_file << \"@\" << element_name << \".gbs\" << endl;\n                el_file << element_name << \" 0\" << endl;\n                for (const Shell& shell:element) {\n                    //gaussian can only use S,P,SP,D,F,G shells so we split them up if not SP\n                    if (shell.getType() == \"SP\" || !shell.isCombined()) {\n                        // shell type, number primitives, scale factor\n                        el_file << shell.getType() << \" \" << shell.getSize() << \" \" << FortranFormat(shell.getScale()) << endl;\n                        for (const GaussianPrimitive& gaussian:shell) {\n                            el_file << FortranFormat(gaussian._decay);\n                            for (const double& contraction:gaussian._contraction) {\n                                if (contraction!= 0.0) {\n                                    el_file << \" \" << FortranFormat(contraction);\n                                }\n                            }\n                            el_file << endl;\n                        }                              \n                    } else {\n                        string type = shell.getType();\n                        for (unsigned i = 0; i < type.size(); ++i) {\n                            string subtype = string(type, i, 1);\n                            el_file << subtype << \" \" << shell.getSize() << \" \" << FortranFormat(shell.getScale()) << endl;\n\n                            for (const GaussianPrimitive& gaussian:shell) {\n                                el_file << FortranFormat(gaussian._decay);\n                                el_file << \" \" << FortranFormat(gaussian._contraction[FindLmax(subtype)]);\n                            }\n                            el_file << endl;  \n                        }\n                    }\n                }\n\n                el_file << \"****\\n\";\n                el_file.close();\n\n            }\n                \n            com_file << endl;\n            return;\n        }\n\n        /* If custom ECPs are used, they need to be specified in the input file\n         * in a section following the basis set includes.\n         */\n        void Gaussian::WriteECP(std::ofstream& com_file, std::vector<QMAtom*>& qmatoms) {\n            std::vector<std::string> UniqueElements= FindUniqueElements(qmatoms);\n           \n            BasisSet ecp;\n            ecp.LoadPseudopotentialSet(_ecp_name);\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Loaded Pseudopotentials \" << _ecp_name << flush;\n\n            for (const std::string& element_name:UniqueElements) {\n                       try{    \n                        ecp.getElement(element_name);\n                       }catch(std::runtime_error& error){\n                         CTP_LOG(ctp::logDEBUG, *_pLog) << \"No pseudopotential for \" << element_name<<\" available\" << flush;\n                         continue;\n                       }\n                       const Element& element = ecp.getElement(element_name);\n                        // element name, [possibly indeces of centers], zero to indicate the end\n                        com_file << element_name << \" 0\\n\"\n                                << _ecp_name << \" \"\n                                << element.getLmax() << \" \" << element.getNcore() << endl;\n\n                       for (const Shell& shell:element) {\n                            // shell type, number primitives, scale factor\n                            com_file << shell.getType() << endl;\n                            com_file << shell.getSize() << endl;\n\n                           for (const GaussianPrimitive& gaussian:shell) {\n                                com_file << gaussian._power << \" \" << FortranFormat(gaussian._decay) << \" \" << FortranFormat(gaussian._contraction[0]) << endl;\n                            }\n                        }\n                    }     \n            com_file << endl;\n            return;\n        }\n\n        /* For QM/MM the molecules in the MM environment are represented by\n         * their atomic partial charge distributions. Triggered by the option\n         * keyword \"charge\" Gaussian expects them in x,y,z,q format in the\n         * input file. In g03 AFTER basis sets and ECPs, in g09 BEFORE.\n         */\n     \n        void Gaussian::WriteBackgroundCharges(std::ofstream& com_file) {\n            \n            boost::format fmt(\"%1$+1.7f %2$+1.7f %3$+1.7f %4$+1.7f\");\n            for (std::shared_ptr<ctp::PolarSeg> seg:_PolarSegments) {\n                for (ctp::APolarSite* site:*seg) {\n                    \n                    string sitestring=boost::str(fmt % ((site->getPos().getX())*votca::tools::conv::nm2ang) \n                            % (site->getPos().getY()*votca::tools::conv::nm2ang) \n                            % (site->getPos().getZ()*votca::tools::conv::nm2ang) \n                            % site->getQ00());\n                    if (site->getQ00() != 0.0) com_file << sitestring << endl;\n\n                    if (site->getRank() > 0 || _with_polarization ) {\n\n                        std::vector< std::vector<double> > _split_multipoles = SplitMultipoles(site);\n                        for (const auto& mpoles:_split_multipoles){\n                           string multipole=boost::str( fmt % mpoles[0] % mpoles[1] % mpoles[2] % mpoles[3]);\n                            com_file << multipole << endl;\n\n                        }\n                    }\n                }\n            }\n            com_file << endl;\n            return;\n        }\n\n        /* An initial guess for the electron density can be provided by\n         * a set of molecular orbital coefficients in the input file,\n         * triggered by the 'guess=cards' keyword. This MUST be done in\n         * Fortran fixed format 5D15.8. The information about the guess\n         * itself is taken from a prepared orbitals object.\n         */\n        void Gaussian::WriteGuess(Orbitals& orbitals_guess, std::ofstream& com_file) {\n            ReorderMOsBack(orbitals_guess);\n            com_file << \"(5D15.8)\" << endl;\n            int level = 1;\n            int ncolumns = 5;\n            for (int i=0;i<orbitals_guess.MOCoefficients().cols();++i) {\n                com_file << setw(5) << level << endl;\n                Eigen::VectorXd mr = orbitals_guess.MOCoefficients().col(i);\n                int column = 1;\n                for (unsigned j = 0; j < mr.size(); ++j) {\n                    com_file << FortranFormat(mr[j]);\n                    if (column == ncolumns) {\n                        com_file << std::endl;\n                        column = 0;\n                    }\n                    column++;\n                }\n                level++;\n                if (column != 1) com_file << endl;\n            }\n            com_file << 0 << endl;\n            return;\n        }\n\n        /* For output of the AO matrix of Vxc using the patched g03 version,\n         * g03 has to be called a second time after completing the single-point\n         * SCF calculation. A second input file is generated based on the\n         * originally specified options by forcing to read the converged\n         * electron density from the checkpoint file, setting run to serial.\n         */\n        void Gaussian::WriteVXCRunInputFile() {\n            std::ofstream com_file2;\n\n            std::string com_file_name_full2 = _run_dir + \"/\" + _input_vxc_file_name;\n\n            com_file2.open(com_file_name_full2.c_str());\n            // header\n            if (_chk_file_name.size()) com_file2 << \"%chk=\" << _chk_file_name << endl;\n            if (_memory.size()) com_file2 << \"%mem=\" << _memory << endl;\n            com_file2 << \"%nprocshared=1\" << endl;\n\n            // adjusting the options line to Vxc output only\n            std::string options_vxc = _options;\n            boost::algorithm::replace_all(options_vxc, \"pseudo=read\", \"Geom=AllCheck\");\n            boost::algorithm::replace_all(options_vxc, \"/gen\", \" chkbasis\");\n            boost::algorithm::replace_all(options_vxc, \"punch=mo\", \"guess=read\");\n            boost::algorithm::replace_all(options_vxc, \"guess=tcheck\", \"\");\n            boost::algorithm::replace_all(options_vxc, \"guess=huckel\", \"\");\n            boost::algorithm::replace_all(options_vxc, \"charge\", \"charge=check\");\n            if (options_vxc.size()) com_file2 << options_vxc << endl;\n\n            com_file2 << endl;\n            com_file2 << \"VXC output run \\n\";\n            com_file2 << endl;\n            com_file2.close();\n            return;\n        }\n\n\n        /* Coordinates are written in standard Element,x,y,z format to the\n         * input file.\n         */\n        void Gaussian::WriteCoordinates(std::ofstream& com_file, std::vector<QMAtom*>& qmatoms) {\n            for (QMAtom* atom:qmatoms) {\n              tools::vec pos=atom->getPos()*tools::conv::bohr2ang;\n                    com_file << setw(3) << atom->getType().c_str()\n                            << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getX()\n                            << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getY()\n                            << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getZ()\n                            << endl;\n            }\n            com_file << endl;\n            return;\n        }\n\n        /* Standard Gaussian Header is written to the input file, with checkpoint,\n         * memory, shared processor request, option string containing all\n         * relevant keywords, charge, and spin information.\n         */\n        void Gaussian::WriteHeader(std::ofstream& com_file) {\n            if (_chk_file_name.size()) com_file << \"%chk=\" << _chk_file_name << endl;\n            if (_memory.size()) com_file << \"%mem=\" << _memory << endl;\n            if (_threads > 0) com_file << \"%nprocshared=\" << _threads << endl;\n            if (_options.size()) com_file << _options << endl;\n\n            com_file << endl;\n            com_file << \"TITLE \";\n\n            com_file << endl << endl;\n            com_file << setw(2) << _charge << setw(2) << _spin << endl;\n            return;\n        }\n\n        /**\n         * Prepares the com file from a vector of segments\n         * Appends a guess constructed from monomer orbitals if supplied\n         */\n        bool Gaussian::WriteInputFile(Orbitals& orbitals) {\n\n            std::string temp_suffix = \"/id\";\n            std::string scratch_dir_backup = _scratch_dir;\n\n            std::ofstream com_file;\n            std::string _com_file_name_full = _run_dir + \"/\" + _input_file_name;\n            com_file.open(_com_file_name_full.c_str());\n\n            // header\n            WriteHeader(com_file);\n\n            std::vector< QMAtom* > qmatoms = orbitals.QMAtoms();\n\n            WriteCoordinates(com_file, qmatoms);\n\n            /* The order in which the following information has to appear\n             * in the Gaussian input file is different from version g03 to\n             * version g09. The newest version (g2016) is not supported.\n             */\n            if (_executable == \"g03\") {\n\n                // if we need to write basis sets, do it now\n                if (_write_basis_set) WriteBasisset(com_file, qmatoms);\n\n                // write ECPs\n                if (_write_pseudopotentials) WriteECP(com_file, qmatoms);\n\n                // write the background charges\n                //if (_write_charges) WriteBackgroundCharges(_com_file, qmatoms);\n                if (_write_charges) WriteBackgroundCharges(com_file);\n\n                // write inital guess\n                if (_write_guess){\n                    WriteGuess(orbitals, com_file);\n                }\n\n            } else if (_executable == \"g09\") {\n\n                // write the background charges\n                //if (_write_charges) WriteBackgroundCharges(_com_file, qmatoms);\n                if (_write_charges) WriteBackgroundCharges(com_file);\n                // if we need to write basis sets, do it now\n                if (_write_basis_set) WriteBasisset(com_file, qmatoms);\n\n                // write ECPs\n                if (_write_pseudopotentials) WriteECP(com_file, qmatoms);\n\n                // write inital guess\n                if (_write_guess){\n                    WriteGuess(orbitals, com_file);\n                }\n\n            } else {\n                throw std::runtime_error(\"Gaussian executable unknown. Must be either g03 or g09.\");\n            }\n\n            // for Vxc AO matrix output only with pre-compiled G03\n            if (_output_Vxc) WriteVXCRunInputFile();\n\n\n            com_file << _vdWfooter << endl;\n\n            com_file << endl;\n            com_file.close();\n            // and now generate a shell script to run both jobs\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Setting the scratch dir to \" << _scratch_dir + temp_suffix << flush;\n\n            _scratch_dir = scratch_dir_backup + temp_suffix;\n            WriteShellScript();\n            _scratch_dir = scratch_dir_backup;\n\n            return true;\n        }\n\n        /* Gaussian will be executed within a shell in order to set some\n         * environment variables for the local SCRATCH directory and\n         * (legacy mode) running a second instance for AO matrix of Vxc\n         * using patched g03. This function writes the shell script.\n         */\n        bool Gaussian::WriteShellScript() {\n            std::ofstream shell_file;\n\n            std::string shell_file_name_full = _run_dir + \"/\" + _shell_file_name;\n\n            shell_file.open(shell_file_name_full.c_str());\n\n            shell_file << \"#!/bin/tcsh\" << endl;\n            shell_file << \"mkdir -p \" << _scratch_dir << endl;\n            shell_file << \"setenv GAUSS_SCRDIR \" << _scratch_dir << endl;\n            shell_file << _executable << \" \" << _input_file_name << endl;\n            if (_output_Vxc) {\n                shell_file << \"rm fort.22\" << endl;\n                shell_file << \"setenv DoPrtXC YES\" << endl;\n                shell_file << _executable << \" \" << _input_vxc_file_name << \" >& /dev/null \" << endl;\n                shell_file << \"setenv DoPrtXC NO\" << endl;\n                shell_file << \"rm $GAUSS_SCRDIR/*\" << endl;\n            }\n            shell_file.close();\n\n            return true;\n        }\n\n        /**\n         * Runs the Gaussian job.\n         */\n        bool Gaussian::Run( Orbitals& orbitals ) {\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"GAUSSIAN: running [\" << _executable << \" \" << _input_file_name << \"]\" << flush;\n\n            if (std::system(NULL)) {\n                // if scratch is provided, run the shell script;\n                // otherwise run gaussian directly and rely on global variables\n                std::string command;\n                if (_scratch_dir.size() != 0 || _output_Vxc) {\n                    command = \"cd \" + _run_dir + \"; tcsh \" + _shell_file_name;\n                    //            _command  = \"cd \" + _run_dir + \"; mkdir -p \" + _scratch_dir +\"; \" + _executable + \" \" + _input_file_name;\n                } else {\n                    command = \"cd \" + _run_dir + \"; mkdir -p $GAUSS_SCRDIR; \" + _executable + \" \" + _input_file_name;\n                }\n                int check = std::system(command.c_str());\n                if (check == -1) {\n                    CTP_LOG(ctp::logERROR, *_pLog) << _input_file_name << \" failed to start\" << flush;\n                    return false;\n                }\n                if (CheckLogFile()) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"GAUSSIAN: finished job\" << flush;\n                    return true;\n                } else {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"GAUSSIAN: job failed\" << flush;\n                }\n            } else {\n                CTP_LOG(ctp::logERROR, *_pLog) << _input_file_name << \" failed to start\" << flush;\n                return false;\n            }\n            return true;\n        }\n\n        /**\n         * Cleans up after the Gaussian job\n         */\n        void Gaussian::CleanUp() {\n\n            // cleaning up the generated files\n            if (_cleanup.size() != 0) {\n\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"Removing \" << _cleanup << \" files\" << flush;\n                tools::Tokenizer tok_cleanup(_cleanup, \", \");\n                std::vector <std::string> cleanup_info;\n                tok_cleanup.ToVector(cleanup_info);\n                for (const std::string& substring:cleanup_info) {\n\n                    if (substring == \"com\") {\n                        std::string file_name = _run_dir + \"/\" + _input_file_name;\n                        remove(file_name.c_str());\n                        if (_output_Vxc) {\n                            std::string file_name = _run_dir + \"/\" + _input_vxc_file_name;\n                            remove(file_name.c_str());\n                        }\n                    }\n\n                    if (substring == \"sh\") {\n                        std::string file_name = _run_dir + \"/\" + _shell_file_name;\n                        remove(file_name.c_str());\n                    }\n\n                    if (substring == \"log\") {\n                        std::string file_name = _run_dir + \"/\" + _log_file_name;\n                        remove(file_name.c_str());\n                        if (_output_Vxc) {\n                            size_t lastdot = _log_file_name.find_last_of(\".\");\n                            if (lastdot == std::string::npos) {\n                                cerr << endl;\n                                cerr << \"Could not remove Vxc log file\" << flush;\n                            }\n                            std::string file_name2 = file_name.substr(0, lastdot) + \"-2.log\";\n                            remove(file_name2.c_str());\n                        }\n                    }\n\n                    if (substring == \"chk\") {\n                        std::string file_name = _run_dir + \"/\" + _chk_file_name;\n                        remove(file_name.c_str());\n                    }\n\n                    if (substring == \"fort.7\") {\n                        std::string file_name = _run_dir + \"/\" + substring;\n                        remove(file_name.c_str());\n                        if (_output_Vxc) {\n                            std::string file_name = _run_dir + \"/\" + \"fort.24\";\n                            remove(file_name.c_str());\n                        }\n                    }\n\n                    if (substring == \"gbs\" && _write_basis_set) {\n                        std::vector<std::string> fileswithfileending;\n                        boost::filesystem::recursive_directory_iterator fit(_run_dir);\n                        boost::filesystem::recursive_directory_iterator endit;\n                        while (fit != endit) {\n                            if (boost::filesystem::is_regular_file(* fit) && fit->path().extension() == substring) fileswithfileending.push_back(fit->path().filename().string());\n                            ++fit;\n                        }\n                        for (const auto filename : fileswithfileending) {\n                            std::string file_name = _run_dir + \"/\" + filename;\n                            remove(file_name.c_str());\n                        }\n                    }\n\n                }\n            }\n            return;\n        }\n\n        /**\n         * Reads in the MO coefficients from a GAUSSIAN fort.7 file\n         */\n        bool Gaussian::ParseOrbitalsFile(Orbitals & orbitals) {\n            std::map <int, std::vector<double> > coefficients;\n            std::map <int, double> energies;\n\n            std::string line;\n            unsigned levels = 0;\n            unsigned level = 0;\n            unsigned basis_size = 0;\n\n            std::string orb_file_name_full = _orb_file_name;\n            if (_run_dir != \"\") orb_file_name_full = _run_dir + \"/\" + _orb_file_name;\n            std::ifstream input_file(orb_file_name_full.c_str());\n\n            if (input_file.fail()) {\n                CTP_LOG(ctp::logERROR, *_pLog) << \"File \" << _orb_file_name << \" with molecular orbitals is not found \" << flush;\n                return false;\n            } else {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"Reading MOs from \" << _orb_file_name << flush;\n            }\n\n            // number of coefficients per line is  in the first line of the file (5D15.8)\n            getline(input_file, line);\n            std::vector<std::string> strs;\n            boost::algorithm::split(strs, line, boost::is_any_of(\"(D)\"));\n            std::string format = strs.at(2);\n\n\n            while (input_file) {\n\n                getline(input_file, line);\n                // if a line has an equality sign, must be energy\n                std::string::size_type energy_pos = line.find(\"=\");\n\n                if (energy_pos != std::string::npos) {\n\n                    std::vector<std::string> results;\n                    boost::trim(line);\n\n                    boost::algorithm::split(results, line, boost::is_any_of(\"\\t =\"),\n                            boost::algorithm::token_compress_on);\n                    //cout << results[1] << \":\" << results[2] << \":\" << results[3] << \":\" << results[4] << endl;\n\n                    level = boost::lexical_cast<int>(results.front());\n                    boost::replace_first(results.back(), \"D\", \"e\");\n                    energies[ level ] = boost::lexical_cast<double>(results.back());\n                    levels++;\n\n                } else {\n\n                    while (line.size() > 1) {\n                        std::string coefficient;\n                        coefficient.assign(line, 0, 15);\n                        boost::trim(coefficient);\n                        boost::replace_first(coefficient, \"D\", \"e\");\n                        double coef = boost::lexical_cast<double>(coefficient);\n                        coefficients[ level ].push_back(coef);\n                        line.erase(0, 15);\n                    }\n                }\n            }\n\n            // some sanity checks\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Energy levels: \" << levels << flush;\n\n            std::map< int, std::vector<double> >::iterator iter = coefficients.begin();\n            basis_size = iter->second.size();\n\n            for (iter = coefficients.begin()++; iter != coefficients.end(); iter++) {\n                if (iter->second.size() != basis_size) {\n                    CTP_LOG(ctp::logERROR, *_pLog) << \"Error reading \" << _orb_file_name << \". Basis set size change from level to level.\" << flush;\n                    return false;\n                }\n            }\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Basis set size: \" << basis_size << flush;\n\n            // copying information to the orbitals object\n            orbitals.setBasisSetSize(basis_size); // = _basis_size;\n\n            // copying energies to the orbitals object\n           Eigen::VectorXd &mo_energies = orbitals.MOEnergies();\n            mo_energies.resize(levels);\n            for (int i = 0; i < mo_energies.size(); i++) mo_energies[i] = energies[ i + 1 ];\n\n            // copying mo coefficients to the orbitals object\n            Eigen::MatrixXd &mo_coefficients = orbitals.MOCoefficients();\n            mo_coefficients.resize(levels, basis_size);\n            for (int i = 0; i < mo_coefficients.rows(); i++){\n                for (int j = 0; j < mo_coefficients.cols(); j++){\n                    mo_coefficients(j, i) = coefficients[i + 1][j];\n                }\n            }\n            \n            ReorderOutput(orbitals);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"GAUSSIAN: done reading MOs\" << flush;\n\n            return true;\n        }\n\n        bool Gaussian::CheckLogFile() {\n\n            // check if the log file exists\n            boost::filesystem::path arg_path;\n            char ch;\n\n            std::string full_name = (arg_path / _run_dir / _log_file_name).c_str();\n            ifstream input_file(full_name.c_str());\n\n            if (input_file.fail()) {\n                CTP_LOG(ctp::logERROR, *_pLog) << \"GAUSSIAN: \" << full_name << \" is not found\" << flush;\n                return false;\n            };\n\n            input_file.seekg(0, ios_base::end); // go to the EOF\n\n            // get empty lines and end of lines out of the way\n            do {\n                input_file.seekg(-2, ios_base::cur);\n                input_file.get(ch);\n            } while (ch == '\\n' || ch == ' ' || ch == '\\t' || (int) input_file.tellg() == -1);\n\n            // get the beginning of the line or the file\n            do {\n                input_file.seekg(-2, ios_base::cur);\n                input_file.get(ch);\n            } while (ch != '\\n' && (int) input_file.tellg() != -1);\n\n            std::string line;\n            getline(input_file, line); \n            input_file.close();\n\n            std::string::size_type self_energy_pos = line.find(\"Normal termination of Gaussian\");\n            if (self_energy_pos == std::string::npos) {\n                CTP_LOG(ctp::logERROR, *_pLog) << \"GAUSSIAN: \" << full_name << \" is incomplete\" << flush;\n                return false;\n            } else {\n                return true;\n            }\n        }\n\n        bool Gaussian::ReadESPCharges(Orbitals& orbitals, std::string& line, ifstream& input_file){\n          std::string::size_type charge_pos = line.find(\"Charges from ESP fit, RMS\");\n          bool has_charges=false;\n          if (charge_pos != std::string::npos && _get_charges) {\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Getting charges\" << flush;\n            has_charges = true;\n            getline(input_file, line);\n            getline(input_file, line);\n            \n            bool _has_atoms = orbitals.hasQMAtoms();\n            \n            std::vector<std::string> row=GetLineAndSplit(input_file, \"\\t \");\n            int nfields = row.size();\n            \n            while (nfields == 3) {\n              int atom_id = boost::lexical_cast< int >(row.at(0));\n              std::string atom_type = row.at(1);\n              double atom_charge = boost::lexical_cast< double >(row.at(2));\n              row=GetLineAndSplit(input_file, \"\\t \");\n              nfields = row.size();\n              QMAtom* pAtom;\n              if (_has_atoms == false) {\n                pAtom =orbitals.AddAtom(atom_id - 1,atom_type, tools::vec(0.0));\n              } else {\n                pAtom = orbitals.QMAtoms().at(atom_id - 1);\n              }\n              pAtom->setPartialcharge(atom_charge);\n            }\n          }\n          return has_charges;\n        }\n\n        /**\n         * Parses the Gaussian Log file and stores data in the Orbitals object\n         */\n        bool Gaussian::ParseLogFile(Orbitals & orbitals) {\n            std::string line;\n            std::vector<std::string> results;\n            bool has_occupied_levels = false;\n            bool has_unoccupied_levels = false;\n            bool has_number_of_electrons = false;\n            bool has_basis_set_size = false;\n            bool has_overlap_matrix = false;\n            bool has_charges = false;\n            bool has_self_energy = false;\n\n            bool read_vxc = false;\n\n            int occupied_levels = 0;\n            int unoccupied_levels = 0;\n            int number_of_electrons = 0;\n            int basis_set_size = 0;\n            int cart_basis_set_size = 0;\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"GAUSSIAN: parsing \" << _log_file_name << flush;\n\n            std::string log_file_name_full = _log_file_name;\n            if (_run_dir != \"\") log_file_name_full = _run_dir + \"/\" + _log_file_name;\n\n            // check if LOG file is complete\n            if (!CheckLogFile()) return false;\n\n            // save qmpackage name\n            orbitals.setQMpackage(\"gaussian\");\n            orbitals.setDFTbasis(_basisset_name);\n\n\n            if (_write_pseudopotentials) {\n                orbitals.setECP(_ecp_name);\n            }\n\n            read_vxc = _output_Vxc;\n            bool vxc_found = false;\n            // Start parsing the file line by line\n            ifstream input_file(log_file_name_full.c_str());\n            while (input_file) {\n\n                getline(input_file, line);\n                boost::trim(line);\n\n                /* Check for ScaHFX = factor of HF exchange included in functional */\n                std::string::size_type HFX_pos = line.find(\"ScaHFX=\");\n                if (HFX_pos != std::string::npos) {\n                    boost::algorithm::split(results, line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n                    double ScaHFX = boost::lexical_cast<double>(results.back());\n                    orbitals.setScaHFX(ScaHFX);\n                    vxc_found = true;\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"DFT with \" << ScaHFX << \" of HF exchange!\" << flush;\n                }\n\n                /*\n                 * number of occupied and virtual orbitals\n                 * N alpha electrons      M beta electrons\n                 */\n                std::string::size_type electrons_pos = line.find(\"alpha electrons\");\n                if (electrons_pos != std::string::npos) {\n                    boost::algorithm::split(results, line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n                    has_number_of_electrons = true;\n                    number_of_electrons = boost::lexical_cast<int>(results.front());\n                    orbitals.setNumberOfElectrons(number_of_electrons);\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Alpha electrons: \" << number_of_electrons << flush;\n                }\n\n                /*\n                 * basis set size\n                 * N basis functions,  M primitive gaussians,   K cartesian basis functions\n                 */\n                std::string::size_type basis_pos = line.find(\"basis functions,\");\n                if (basis_pos != std::string::npos) {\n                    boost::algorithm::split(results, line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n                    has_basis_set_size = true;\n                    basis_set_size = boost::lexical_cast<int>(results.front());\n                    orbitals.setBasisSetSize(basis_set_size);\n                    cart_basis_set_size = boost::lexical_cast<int>(results[6]);\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Basis functions: \" << basis_set_size << flush;\n                    if (read_vxc) {\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << \"Cartesian functions: \" << cart_basis_set_size << flush;\n                    }\n                }\n\n                /*\n                 * energies of occupied/unoccupied levels\n                 * Alpha  occ.(virt.) eigenvalues -- e1 e2 e3 e4 e5\n                 */\n                std::string::size_type eigenvalues_pos = line.find(\"Alpha\");\n                if (eigenvalues_pos != std::string::npos) {\n\n                    std::list<std::string> stringList;\n\n                    while (eigenvalues_pos != std::string::npos && !has_occupied_levels && !has_unoccupied_levels) {\n\n                        boost::iter_split(stringList, line, boost::first_finder(\"--\"));\n\n                        std::vector<std::string> energies;\n                        boost::trim(stringList.back());\n\n                        boost::algorithm::split(energies, stringList.back(), boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n\n                        if (stringList.front().find(\"virt.\") != std::string::npos) {\n                            unoccupied_levels += energies.size();\n                            energies.clear();\n                        }\n\n                        if (stringList.front().find(\"occ.\") != std::string::npos) {\n                            occupied_levels += energies.size();\n                            energies.clear();\n                        }\n\n                        getline(input_file, line);\n                        eigenvalues_pos = line.find(\"Alpha\");\n                        boost::trim(line);\n\n                        if (eigenvalues_pos == std::string::npos) {\n                            has_occupied_levels = true;\n                            has_unoccupied_levels = true;\n                            orbitals.setNumberOfLevels(occupied_levels, unoccupied_levels);\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Occupied levels: \" << occupied_levels << flush;\n                            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Unoccupied levels: \" << unoccupied_levels << flush;\n                        }\n                    } // end of the while loop\n                } // end of the eigenvalue parsing\n\n                /*\n                 *  Partial charges from the input file\n                 */\n                has_charges=ReadESPCharges(orbitals, line,input_file);\n\n                /*\n                 * Coordinates of the final configuration\n                 * stored in the archive at the end of the file\n                 */\n                int cpn = 0; // marker appearence marker\n                std::string::size_type coordinates_pos = line.find(\"\\\\\");\n\n                if (coordinates_pos != std::string::npos && cpn == 0) {\n                    ++cpn; // updates but ignores\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Getting the coordinates\" << flush;\n                    boost::trim(line);\n                    std::string archive = line;\n                    while (line.size() != 0) {\n                        getline(input_file, line);\n                        boost::trim(line);\n                        archive += line;\n                    }\n\n                    bool has_atoms = orbitals.hasQMAtoms();\n                    std::list<std::string> stringList;\n                    std::vector<std::string> results;\n                    boost::iter_split(stringList, archive, boost::first_finder(\"\\\\\\\\\"));\n\n                    std::list<std::string>::iterator coord_block = stringList.begin();\n                    std::advance(coord_block, 3);\n\n                    std::vector<std::string> atom_block;\n                    boost::algorithm::split(atom_block, *coord_block, boost::is_any_of(\"\\\\\"), boost::algorithm::token_compress_on);\n\n                    std::vector<std::string>::iterator atom_block_it;\n                    int aindex = 0;\n\n                    for (atom_block_it = ++atom_block.begin(); atom_block_it != atom_block.end(); ++atom_block_it) {\n                        std::vector<std::string> atom;\n                        boost::algorithm::split(atom, *atom_block_it, boost::is_any_of(\",\"), boost::algorithm::token_compress_on);\n                        std::string atom_type = atom.front();\n                        std::vector<std::string>::iterator it_atom;\n                        it_atom = atom.end();\n                        double z = boost::lexical_cast<double>(*(--it_atom));\n                        double y = boost::lexical_cast<double>(*(--it_atom));\n                        double x = boost::lexical_cast<double>(*(--it_atom));\n                        tools::vec pos=tools::vec(x,y,z);\n                        pos*=tools::conv::ang2bohr;\n\n                        if (has_atoms == false) {\n                            orbitals.AddAtom(aindex,atom_type, pos);\n                        } else {\n                            QMAtom* pAtom = orbitals.QMAtoms().at(aindex);\n                            pAtom->setPos(pos);\n                            \n                        }\n                        aindex++;\n                    }\n                    // get the QM energy out\n                    std::advance(coord_block, 1);\n                    std::vector<std::string> block;\n                    std::vector<std::string> energy;\n                    boost::algorithm::split(block, *coord_block, boost::is_any_of(\"\\\\\"), boost::algorithm::token_compress_on);\n                    map<std::string, std::string> properties;\n                    std::vector<std::string>::iterator block_it;\n                    for (block_it = block.begin(); block_it != block.end(); ++block_it) {\n                        std::vector<std::string> property;\n                        boost::algorithm::split(property, *block_it, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n                        properties[property[0]] = property[1];\n                    }\n                    if (properties.count(\"HF\") > 0) {\n                        double energy_hartree = boost::lexical_cast<double>(properties[\"HF\"]);\n                        orbitals. setQMEnergy(tools::conv::hrt2ev * energy_hartree);\n                        CTP_LOG(ctp::logDEBUG, *_pLog) << (boost::format(\"QM energy[eV]: %4.6f \") % orbitals.getQMEnergy()).str() << flush;\n                    } else {\n                        cout << endl;\n                        throw std::runtime_error(\"ERROR No energy in archive\");\n                    }\n\n                }\n\n                std::string::size_type self_energy_pos = line.find(\"Self energy of the charges\");\n\n                if (self_energy_pos != std::string::npos) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Getting the self energy\\n\";\n                    std::vector<std::string> block;\n                    std::vector<std::string> energy;\n                    boost::algorithm::split(block, line, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n                    boost::algorithm::split(energy, block[1], boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n                    orbitals.setSelfEnergy(tools::conv::hrt2ev * boost::lexical_cast<double> (energy[1]));\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Self energy \" << orbitals.getSelfEnergy() << flush;\n\n                }\n \n                std::string::size_type overlap_pos = line.find(\"*** Overlap ***\");\n                if (overlap_pos != std::string::npos) {\n\n                    // prepare the container\n                    Eigen::MatrixXd& overlap=orbitals.AOOverlap();\n                    overlap.resize(basis_set_size,basis_set_size);\n                    has_overlap_matrix = true;\n                    std::vector<int> j_indeces;\n                    int n_blocks = 1 + ((basis_set_size - 1) / 5);\n                    getline(input_file, line);\n                    boost::trim(line);\n\n                    for (int _block = 0; _block < n_blocks; _block++) {\n                        // first line gives the j index in the matrix\n                        boost::tokenizer<> tok(line);\n                        std::transform(tok.begin(), tok.end(), std::back_inserter(j_indeces), &boost::lexical_cast<int, std::string>);\n\n                        // read the block of max _basis_size lines + the following header\n                        for (int i = 0; i <= basis_set_size; i++) {\n                            getline(input_file, line);\n                            if (std::string::npos == line.find(\"D\")) break;\n                            // split the line on the i index and the rest\n                            std::vector<std::string> row=GetLineAndSplit(input_file, \"\\t \");\n                            int i_index = boost::lexical_cast<int>(row.front());\n                            row.erase(row.begin());\n                            std::vector<int>::iterator j_iter = j_indeces.begin();\n\n                            for (std::string& coefficient: row) {\n                                boost::replace_first(coefficient, \"D\", \"e\");\n                                int j_index = *j_iter;\n                                overlap(i_index - 1, j_index - 1) = boost::lexical_cast<double>(coefficient);\n                                overlap(j_index - 1, i_index - 1) = boost::lexical_cast<double>(coefficient);\n                                j_iter++;\n                            }\n                        }\n                        // clear the index for the next block\n                        j_indeces.clear();\n                    } // end of the blocks\n \n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Read the overlap matrix\" << flush;\n                } // end of the if \"Overlap\" found\n                // check if all information has been accumulated and quit\n                if (has_number_of_electrons &&\n                        has_basis_set_size &&\n                        has_occupied_levels &&\n                        has_unoccupied_levels &&\n                        has_overlap_matrix &&\n                        has_charges &&\n                        has_self_energy\n                        ) break;\n\n            } // end of reading the file line-by-line\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Done parsing\" << flush;\n            input_file.close();\n\n            if (!vxc_found) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"WARNING === WARNING \\n, could not find ScaHFX= entry in log.\"\n                        \"\\n probably you forgt #P in the beginning of the input file.\\n\"\n                        \" If you are running a hybrid functional calculation redo it! Now! Please!\\n ===WARNING=== \\n\"\n                        << flush;\n                orbitals.setScaHFX(0.0);\n            }\n            // - parse atomic orbitals Vxc matrix\n            if (read_vxc) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"Parsing fort.24 for Vxc\" << flush;\n                std::string log_file_name_full;\n                if (_run_dir == \"\") {\n                    log_file_name_full = \"fort.24\";\n                } else {\n                    log_file_name_full = _run_dir + \"/fort.24\";\n                }\n\n                ifstream input_file(log_file_name_full.c_str());\n                if (input_file.good()) {\n                    // prepare the container\n                    Eigen::MatrixXd vxc=Eigen::MatrixXd::Zero(cart_basis_set_size,cart_basis_set_size);\n                    std::vector<int> j_indeces;\n                    // Start parsing the file line by line\n\n                    while (input_file) {\n                        getline(input_file, line);\n                        if (input_file.eof()) break;\n\n                        std::vector<std::string> row;\n                        boost::trim(line);\n                        boost::algorithm::split(row, line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n\n                        int i_index = boost::lexical_cast<int>(row[0]);\n                        int j_index = boost::lexical_cast<int>(row[1]);\n                        vxc(i_index - 1, j_index - 1) = boost::lexical_cast<double>(row[2]);\n                        vxc(j_index - 1, i_index - 1) = boost::lexical_cast<double>(row[2]);\n                    }\n\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Done parsing\" << flush;\n                    input_file.close();\n                BasisSet dftbasisset;\n                dftbasisset.LoadBasisSet(_basisset_name);\n                if(!orbitals.hasQMAtoms()){\n                    throw runtime_error(\"Orbitals object has no QMAtoms\");\n                }\n                AOBasis dftbasis;\n                dftbasis.AOBasisFill(dftbasisset, orbitals.QMAtoms());\n                Eigen::MatrixXd carttrafo=dftbasis.getTransformationCartToSpherical(getPackageName());\n                orbitals.AOVxc()=carttrafo*vxc*carttrafo.transpose();\n                } else {\n                    throw std::runtime_error(\"Vxc file does not exist.\");\n                }\n            }\n            return true;\n        }\n\n        std::string Gaussian::FortranFormat(double number) {\n            std::stringstream ssnumber;\n            if (number >= 0) ssnumber << \" \";\n            ssnumber << setiosflags(ios::fixed) << setprecision(8) << std::scientific << number;\n            std::string snumber = ssnumber.str();\n            boost::replace_first(snumber, \"e\", \"D\");\n            return snumber;\n        }\n\n\n    }\n}\n", "meta": {"hexsha": "c9af4afbe4291e0aa0422d0a6b541e249cb1ae0e", "size": 50228, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/qmpackages/gaussian.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/qmpackages/gaussian.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/qmpackages/gaussian.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8865058088, "max_line_length": 178, "alphanum_fraction": 0.493768416, "num_tokens": 10718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181322226037884, "lm_q2_score": 0.022286184646330698, "lm_q1q2_score": 0.00449764673536578}}
{"text": "// Copyright (C) 2006-2010 Anders Logg\n//\n// This file is part of DOLFIN.\n//\n// DOLFIN 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// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.\n//\n#include <set>\n#include <vector>\n#include <algorithm>\n#include <stdio.h>\n//#include <boost/unordered_set.hpp>\n\n//#include <common/Timer.h>\n//#include <common/Timer.h>\n#include <common/utils.h>\n//#include <log/dolfin_log.h>\n#include \"CellType.h\"\n#include \"Mesh.h\"\n#include \"MeshConnectivity.h\"\n#include \"MeshEntity.h\"\n#include \"MeshEntityIterator.h\"\n#include \"MeshTopology.h\"\n#include \"TopologyComputation.h\"\n\nusing namespace dolfin;\n\n// Set typedefs\ntypedef std::set<dolfin::uint> set;\ntypedef std::set<dolfin::uint>::const_iterator set_iterator;\n//typedef boost::unordered_set<dolfin::uint> set;\n//typedef boost::unordered_set<dolfin::uint>::const_iterator set_iterator;\n\n//-----------------------------------------------------------------------------\ndolfin::uint TopologyComputation::compute_entities(Mesh& mesh, uint dim)\n{\n  // Generating an entity of topological dimension dim is equivalent\n  // to generating the connectivity dim - 0 (connections to vertices)\n  // and the connectivity mesh.topology().dim() - dim (connections from cells).\n  //\n  // We generate entities by iterating over all cells and generating a\n  // new entity only on its first occurence. Entities also contained\n  // in a previously visited cell are not generated. The new entities\n  // are computed in three steps:\n  //\n  //   1. Iterate over cells and count new entities\n  //\n  //   2. Allocate memory / prepare data structures\n  //\n  //   3. Iterate over cells and add new entities\n\n  // Get mesh topology and connectivity\n  MeshTopology& topology = mesh.topology();\n  MeshConnectivity& ce = topology(topology.dim(), dim);\n  MeshConnectivity& ev = topology(dim, 0);\n\n  // Check if entities have already been computed\n  if (topology.size(dim) > 0)\n  {\n    // Make sure we really have the connectivity\n    if ((ce.size() == 0 && dim != topology.dim()) || (ev.size() == 0 && dim != 0))\n      printf(\"TopologyComputation.cpp compute topological entities Entities of topological dimension %d exist but connectivity is missing\", dim);\n\n    return topology.size(dim);\n  }\n\n  // Make sure connectivity does not already exist\n  if (ce.size() > 0 || ev.size() > 0)\n      printf(\"TopologyComputation.cpp compute topological entities Connectivity for topological dimension %d exists but entities are missing\", dim);\n\n  //info(\"Computing mesh entities of topological dimension %d.\", dim);\n\n  // Compute connectivity dim - dim if not already computed\n  compute_connectivity(mesh, mesh.topology().dim(), mesh.topology().dim());\n\n  // Start timer\n  //info(\"Creating mesh entities of dimension %d.\", dim);\n//  Timer timer(\"compute entities dim = \" + to_string(dim));\n\n  // TODO Get cell type\n  const CellType& cell_type = mesh.type();\n\n  // Initialize local array of entities\n  const uint m = cell_type.num_entities(dim);\n  const uint n = cell_type.num_vertices(dim);\n  uint** entities = new uint*[m];\n  for (uint i = 0; i < m; i++)\n  {\n    entities[i] = new uint[n];\n    for (uint j = 0; j < n; j++)\n      entities[i][j] = 0;\n  }\n\n  // Count the number of entities\n  uint num_entities = 0;\n  for (MeshEntityIterator c(mesh, mesh.topology().dim()); !c.end(); ++c)\n  {\n    // Get vertices from cell\n    const uint* vertices = c->entities(0);\n//    dolfin_assert(vertices);\n\n    // Create entities\n    cell_type.create_entities(entities, dim, vertices);\n\n    // Count new entities\n    num_entities += count_entities(mesh, *c, entities, m, n, dim);\n  }\n\n  // Initialize the number of entities and connections\n  topology.init(dim, num_entities);\n  ce.init(mesh.num_cells(), m);\n  ev.init(num_entities, n);\n\n  // Add new entities\n  uint current_entity = 0;\n  for (MeshEntityIterator c(mesh, mesh.topology().dim()); !c.end(); ++c)\n  {\n    // Get vertices from cell\n    const uint* vertices = c->entities(0);\n//    dolfin_assert(vertices);\n\n    // Create entities\n    cell_type.create_entities(entities, dim, vertices);\n\n    // Add new entities to the mesh\n    add_entities(mesh, *c, entities, m, n, dim, ce, ev, current_entity);\n  }\n\n  // Delete temporary data\n  for (uint i = 0; i < m; i++)\n    delete [] entities[i];\n  delete [] entities;\n\n  //info(\"Created %d new entities.\", num_entities);\n\n  return num_entities;\n}\n//-----------------------------------------------------------------------------\nvoid TopologyComputation::compute_connectivity(Mesh& mesh, uint d0, uint d1)\n{\n  // This is where all the logic takes place to find a stragety for\n  // the connectivity computation. For any given pair (d0, d1), the\n  // connectivity is computed by suitably combining the following\n  // basic building blocks:\n  //\n  //   1. compute_entities():     d  - 0  from dim - 0\n  //   2. compute_transpose():    d0 - d1 from d1 - d0\n  //   3. compute_intersection(): d0 - d1 from d0 - d' - d1\n  //\n  // Each of these functions assume a set of preconditions that we\n  // need to satisfy.\n\n//  log(TRACE, \"Requesting connectivity %d - %d.\", d0, d1);\n\tprintf(\"Requesting connectivity %d - %d.\", d0, d1);\n\n  // Get mesh topology and connectivity\n  MeshTopology& topology = mesh.topology();\n  MeshConnectivity& connectivity = topology(d0, d1);\n\n  // Check if connectivity has already been computed\n  if (connectivity.size() > 0)\n    return;\n\n  //info(\"Computing mesh connectivity %d - %d.\", d0, d1);\n\n  // Compute entities if they don't exist\n  if (topology.size(d0) == 0)\n    compute_entities(mesh, d0);\n  if (topology.size(d1) == 0)\n    compute_entities(mesh, d1);\n\n  // Check is mesh has entities\n  if (topology.size(d0) == 0 && topology.size(d1) == 0)\n    return;\n\n  // Check if connectivity still needs to be computed\n  if (connectivity.size() > 0)\n    return;\n\n  // Start timer\n  //info(\"Computing mesh connectivity %d - %d.\", d0, d1);\n//  Timer timer(\"compute connectivity \" + to_string(d0) + \" - \" + to_string(d1));\n\n  // Decide how to compute the connectivity\n  if (d0 < d1)\n  {\n    // Compute connectivity d1 - d0 and take transpose\n    compute_connectivity(mesh, d1, d0);\n    compute_from_transpose(mesh, d0, d1);\n  }\n  else\n  {\n    // These connections should already exist\n//    dolfin_assert(!(d0 > 0 && d1 == 0));\n\n    // Choose how to take intersection\n    uint d = 0;\n    if (d0 == 0 && d1 == 0)\n      d = mesh.topology().dim();\n\n    // Compute connectivity d0 - d - d1 and take intersection\n    compute_connectivity(mesh, d0, d);\n    compute_connectivity(mesh, d, d1);\n    compute_from_intersection(mesh, d0, d1, d);\n  }\n}\n//----------------------------------------------------------------------------\nvoid TopologyComputation::compute_from_transpose(Mesh& mesh, uint d0, uint d1)\n{\n  // The transpose is computed in three steps:\n  //\n  //   1. Iterate over entities of dimension d1 and count the number\n  //      of connections for each entity of dimension d0\n  //\n  //   2. Allocate memory / prepare data structures\n  //\n  //   3. Iterate again over entities of dimension d1 and add connections\n  //      for each entity of dimension d0\n\n//  log(TRACE, \"Computing mesh connectivity %d - %d from transpose.\", d0, d1);\n\tprintf( \"Computing mesh connectivity %d - %d from transpose.\", d0, d1);\n\n  // Get mesh topology and connectivity\n  MeshTopology& topology = mesh.topology();\n  MeshConnectivity& connectivity = topology(d0, d1);\n\n  // Need connectivity d1 - d0\n//  dolfin_assert(topology(d1, d0).size() > 0);\n\n  // Temporary array\n  std::vector<uint> tmp(topology.size(d0));\n\n  // Reset size for each entity\n  for (uint i = 0; i < tmp.size(); i++)\n    tmp[i] = 0;\n\n  // Count the number of connections\n  for (MeshEntityIterator e1(mesh, d1); !e1.end(); ++e1)\n    for (MeshEntityIterator e0(*e1, d0); !e0.end(); ++e0)\n      tmp[e0->index()]++;\n\n  // Initialize the number of connections\n  connectivity.init(tmp);\n\n  // Reset current position for each entity\n  for (uint i = 0; i < tmp.size(); i++)\n    tmp[i] = 0;\n\n  // Add the connections\n  for (MeshEntityIterator e1(mesh, d1); !e1.end(); ++e1)\n    for (MeshEntityIterator e0(*e1, d0); !e0.end(); ++e0)\n      connectivity.set(e0->index(), e1->index(), tmp[e0->index()]++);\n}\n//----------------------------------------------------------------------------\nvoid TopologyComputation::compute_from_intersection(Mesh& mesh,\n                                                    uint d0, uint d1, uint d)\n{\n//  log(TRACE, \"Computing mesh connectivity %d - %d from intersection %d - %d - %d.\",\n//      d0, d1, d0, d, d1);\n\tprintf (\"Computing mesh connectivity %d - %d from intersection %d - %d - %d.\", d0, d1, d0, d, d1);\n\n  // Get mesh topology\n  MeshTopology& topology = mesh.topology();\n\n  // Check preconditions\n//  dolfin_assert(d0 >= d1);\n//  dolfin_assert(topology(d0, d).size() > 0);\n//  dolfin_assert(topology(d, d1).size() > 0);\n\n  // Temporary dynamic storage, later copied into static storage\n  std::vector<std::vector<uint> > connectivity(topology.size(d0));\n\n  // Iterate over all entities of dimension d0\n  uint max_size = 1;\n  for (MeshEntityIterator e0(mesh, d0); !e0.end(); ++e0)\n  {\n    // Get set of connected entities for current entity\n    std::vector<uint>& entities = connectivity[e0->index()];\n\n    // Reserve space\n    entities.reserve(max_size);\n\n    // Iterate over all connected entities of dimension d\n    for (MeshEntityIterator e(*e0, d); !e.end(); ++e)\n    {\n      // Iterate over all connected entities of dimension d1\n      for (MeshEntityIterator e1(*e, d1); !e1.end(); ++e1)\n      {\n        if (d0 == d1)\n        {\n          // An entity is not a neighbor to itself\n          if (e0->index() != e1->index() && std::find(entities.begin(), entities.end(), e1->index()) == entities.end())\n            entities.push_back(e1->index());\n        }\n        else\n        {\n          // Entity e1 must be completely contained in e0\n          if (contains(*e0, *e1) && std::find(entities.begin(), entities.end(), e1->index()) == entities.end())\n            entities.push_back(e1->index());\n        }\n      }\n    }\n\n    // Store maximum size\n    if (entities.size() > max_size)\n      max_size = entities.size();\n  }\n\n  // Copy to static storage\n  topology(d0, d1).set(connectivity);\n}\n//-----------------------------------------------------------------------------\ndolfin::uint TopologyComputation::count_entities(Mesh& mesh, MeshEntity& cell,\n                                                 uint** entities, uint m, uint n,\n                                                 uint dim)\n{\n  // For each entity, we iterate over connected and previously visited\n  // cells to see if the entity has already been counted.\n\n  // Needs to be a cell\n//  dolfin_assert(cell.dim() == mesh.topology().dim());\n\n  // Iterate over the given list of entities\n  uint num_entities = 0;\n  for (uint i = 0; i < m; i++)\n  {\n    // Iterate over connected cells and look for entity\n    for (MeshEntityIterator c(cell, mesh.topology().dim()); !c.end(); ++c)\n    {\n      // Check only previously visited cells\n      if (c->index() >= cell.index())\n        continue;\n\n      // Check for vertices\n      if (contains(c->entities(0), c->num_entities(0), entities[i], n))\n        goto found;\n    }\n\n    // Increase counter\n    num_entities++;\n\n    // Entity found, don't need to count\n    found:\n    ;\n  }\n\n  return num_entities;\n}\n//----------------------------------------------------------------------------\nvoid TopologyComputation::add_entities(Mesh& mesh, MeshEntity& cell,\n\t\t\t\t uint** entities, uint m, uint n, uint dim,\n\t\t\t\t MeshConnectivity& ce,\n\t\t\t\t MeshConnectivity& ev,\n\t\t\t\t uint& current_entity)\n{\n  // We repeat the same algorithm as in count_entities() but this time\n  // we add any entities that are new.\n\n  // Needs to be a cell\n//  dolfin_assert(cell.dim() == mesh.topology().dim());\n\n  // Iterate over the given list of entities\n  for (uint i = 0; i < m; i++)\n  {\n    // Iterate over connected cells and look for entity\n    for (MeshEntityIterator c(cell, mesh.topology().dim()); !c.end(); ++c)\n    {\n      // Check only previously visited cells\n      if (c->index() >= cell.index())\n        continue;\n\n      // Check all entities of dimension dim in connected cell\n      uint num_other_entities = c->num_entities(dim);\n      const uint* other_entities = c->entities(dim);\n      for (uint j = 0; j < num_other_entities; j++)\n      {\n        // Can't use iterators since connectivity has not been computed\n        MeshEntity e(mesh, dim, other_entities[j]);\n        if (contains(e.entities(0), e.num_entities(0), entities[i], n))\n        {\n          // Entity already exists, so pick the index\n          ce.set(cell.index(), e.index(), i);\n          goto found;\n        }\n      }\n    }\n\n    // Entity does not exist, so create it\n    ce.set(cell.index(), current_entity, i);\n    ev.set(current_entity, entities[i]);\n\n    // Increase counter\n    current_entity++;\n\n    // Entity found, don't need to create\n    found:\n    ;\n  }\n}\n//----------------------------------------------------------------------------\nbool TopologyComputation::contains(MeshEntity& e0, MeshEntity& e1)\n{\n  // Check vertices\n  return contains(e0.entities(0), e0.num_entities(0),\n\t\t  e1.entities(0), e1.num_entities(0));\n}\n//----------------------------------------------------------------------------\nbool TopologyComputation::contains(const uint* v0, uint n0, const uint* v1, uint n1)\n{\n//  dolfin_assert(v0);\n//  dolfin_assert(v1);\n\n  for (uint i1 = 0; i1 < n1; i1++)\n  {\n    bool found = false;\n    for (uint i0 = 0; i0 < n0; i0++)\n    {\n      if (v0[i0] == v1[i1])\n      {\n        found = true;\n        break;\n      }\n    }\n    if (!found)\n      return false;\n  }\n\n  return true;\n}\n//----------------------------------------------------------------------------\n", "meta": {"hexsha": "b2318688b329f129119acd1581c67165efcc5f3c", "size": 14283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dolfin/mesh/TopologyComputation.cpp", "max_stars_repo_name": "szmurlor/fiver", "max_stars_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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/dolfin/mesh/TopologyComputation.cpp", "max_issues_repo_name": "szmurlor/fiver", "max_issues_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dolfin/mesh/TopologyComputation.cpp", "max_forks_repo_name": "szmurlor/fiver", "max_forks_repo_head_hexsha": "083251420eb934d860c99dcf1eb07ae5b8ba7e8c", "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.387755102, "max_line_length": 148, "alphanum_fraction": 0.6097458517, "num_tokens": 3644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706242, "lm_q2_score": 0.020645928404169494, "lm_q1q2_score": 0.004487134899077331}}
{"text": "// ****************************************************************************\n//\n//    Copyright (c) 2014, Seth Billings, Russell Taylor, Johns Hopkins University\n//    All rights reserved.\n//\n//    Redistribution and use in source and binary forms, with or without\n//    modification, are permitted provided that the following conditions are\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 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\n#include <fstream>\n\n//#include <boost/filesystem.hpp>\n\n#include \"cisstNumerical.h\"\n\n#include \"utility.h\"\n#include \"cisstPointCloud.h\"\n#include \"utilities.h\"\n\n\n//void CreateDir(const std::string &dir)\n//{\n//  boost::filesystem::create_directories(dir.c_str());\n//}\n\n//#include <windows.h>\n//void CreateDir(const std::string &dir)\n//{\n//  int rv = CreateDirectory(dir.c_str(), NULL);\n//  if (rv || ERROR_ALREADY_EXISTS == GetLastError())\n//  {\n//    if (rv)\n//    { // created directory\n//      std::cout << \"Creating directory: \\\"\" << dir << \"\\\"\" << std::endl;\n//    }\n//    // else directory already exists\n//  }\n//  else\n//  { // failed to create directory\n//    std::cout << \"ERROR! create directory failed: \" << dir << std::endl;\n//    assert(0);\n//  }\n//}\n\nvoid transform_write(vctFrm3 &F, std::string &filename)\n{\n  // output format:\n  //  r00 r01 r02 r10 r11 r12 r20 r21 r22 tx ty tz  \n  std::ofstream out(filename.c_str());\n  if (out) {\n    out << F.Rotation().Row(0) << \" \" << F.Rotation().Row(1) << \" \"\n      << F.Rotation().Row(2) << \" \" << F.Translation();\n    //out << t.Rotation().Row(0) << \"  \" << t.Translation()[0] << std::endl \n    //  << t.Rotation().Row(1) << \"  \" << t.Translation()[1] << std::endl\n    //  << t.Rotation().Row(2) << \"  \" << t.Translation()[2] << std::endl;\n  }\n  else {\n    out << \"ERROR: cannot open transform file for writing\" << std::endl;\n    assert(0);\n  }\n  out.close();\n}\n\n\nvctDynamicVector<vctRot3> rotations_read(std::string &filepath)\n{\n  unsigned int itemsRead;\n  std::string line;\n  float f1, f2, f3, f4, f5, f6, f7, f8, f9;\n\n  std::cout << \"Reading vctRot3 matrices from file: \" << filepath << std::endl;\n  std::ifstream fs(filepath.c_str());\n  if (!fs.is_open())\n  {\n    std::cerr << \"ERROR: failed to open file: \" << filepath << std::endl;\n    assert(0);\n  }\n\n  // read matrices\n  unsigned int numRot = 0;\n  std::vector<vctRot3> rotVct;\n  vctRot3 rot;\n  while (fs.good())\n  {\n    std::getline(fs, line);\n    itemsRead = std::sscanf(line.c_str(), \"%f %f %f %f %f %f %f %f %f\",\n      &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9);\n    if (itemsRead != 9)\n    {\n      break;\n      //std::cerr << \"ERROR: expeced a covariance entry at line: \" << line << std::endl;\n      //assert(0);\n    }\n    rot.Assign(f1, f2, f3, f4, f5, f6, f7, f8, f9);\n    rotVct.push_back(rot);\n    numRot++;\n  }\n  //if (fs.bad() || fs.fail())\n  //{\n  //  std::cerr << \"ERROR: read pts from file failed; last line read: \" << line << std::endl;\n  //  assert(0);\n  //}\n  fs.close();\n\n  vctDynamicVector<vctRot3> rotArray(numRot);\n  for (unsigned int i = 0; i < numRot; i++)\n  {\n    rotArray[i] = rotVct[i];\n  }\n\n  return rotArray;\n}\n\nvctDynamicVector<vct3x3> cov_read(std::string &filepath)\n{\n  unsigned int itemsRead;\n  std::string line;\n  float f1, f2, f3, f4, f5, f6, f7, f8, f9;\n\n  std::cout << \"Reading 3x3 matrices from file: \" << filepath << std::endl;\n  std::ifstream fs(filepath.c_str());\n  if (!fs.is_open())\n  {\n    std::cerr << \"ERROR: failed to open file: \" << filepath << std::endl;\n    assert(0);\n  }\n\n  // read matrices\n  unsigned int numCov = 0;\n  std::vector<vct3x3> covVct;\n  vct3x3 cov;\n  while (fs.good())\n  {\n    std::getline(fs, line);\n    itemsRead = std::sscanf(line.c_str(), \"%f %f %f %f %f %f %f %f %f\",\n      &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9);\n    if (itemsRead != 9)\n    {\n      std::cerr << \"ERROR: expeced a covariance entry at line: \" << line << std::endl;\n      assert(0);\n    }\n    cov.Assign(f1, f2, f3, f4, f5, f6, f7, f8, f9);\n    covVct.push_back(cov);\n    numCov++;\n  }\n  if (fs.bad() || fs.fail())\n  {\n    std::cerr << \"ERROR: read pts from file failed; last line read: \" << line << std::endl;\n    assert(0);\n  }\n  fs.close();\n\n  vctDynamicVector<vct3x3> covArray(numCov);\n  for (unsigned int i = 0; i < numCov; i++)\n  {\n    covArray[i] = covVct[i];\n  }\n\n  return covArray;\n}\n\nvoid cov_write(vctDynamicVector<vct3x3> &cov, std::string &filename)\n{\n  std::ofstream out(filename.c_str());\n  if (out) {\n    unsigned int numCov = cov.size();\n    for (unsigned int i = 0; i < numCov; i++)\n    {\n      out << cov[i].Row(0) << \" \" << cov[i].Row(1) << \" \" << cov[i].Row(2) << std::endl;\n    }\n  }\n  else {\n    out << \"ERROR: cannot open covariance file for writing\" << std::endl;\n    assert(0);\n  }\n  out.close();\n}\n\n// Write cov to file\nvoid WriteToFile_Cov(const vctDynamicVector<vct3x3> &cov,\n  std::string &filePath)\n{\n  // Text file format:\n  //\n  //  c00 c01 c02 c10 c11 c12 c20 c21 c22\n  //   ...\n  //  c00 c01 c02 c10 c11 c12 c20 c21 c22\n  //\n  //  where vx's are indices into the pts array\n\n  std::cout << \"Saving cov to file: \" << filePath << std::endl;\n  std::ofstream fs(filePath.c_str());\n  if (!fs.is_open())\n  {\n    std::cerr << \"ERROR: failed to open file: \" << filePath << std::endl;\n    assert(0);\n  }\n  //fs << \"COV \" << cov.size() << \"\\n\";\n  unsigned int nCov = cov.size();\n  for (unsigned int i = 0; i < nCov; i++)\n  {\n    fs << cov.at(i)(0, 0) << \" \" << cov.at(i)(0, 1) << \" \" << cov.at(i)(0, 2) << \" \"\n      << cov.at(i)(1, 0) << \" \" << cov.at(i)(1, 1) << \" \" << cov.at(i)(1, 2) << \" \"\n      << cov.at(i)(2, 0) << \" \" << cov.at(i)(2, 1) << \" \" << cov.at(i)(2, 2) << \"\\n\";\n  }\n  fs.close();\n}\n\n// Write L to file\nvoid WriteToFile_L(const vctDynamicVector<vctFixedSizeMatrix<double, 3, 2> > &L,\n  std::string &filePath)\n{\n  // Text file format:\n  //\n  //  L1x L1y L1z L2x L2y L2z\n  //   ...\n  //  L1x L1y L1z L2x L2y L2z\n  //\n  //  where vx's are indices into the pts array\n\n  std::cout << \"Saving L to file: \" << filePath << std::endl;\n  std::ofstream fs(filePath.c_str());\n  if (!fs.is_open())\n  {\n    std::cerr << \"ERROR: failed to open file: \" << filePath << std::endl;\n    assert(0);\n  }\n  //fs << \"L \" << L.size() << \"\\n\";\n  unsigned int numL = L.size();\n  for (unsigned int i = 0; i < numL; i++)\n  {\n    fs << L.at(i)(0, 0) << \" \" << L.at(i)(1, 0) << \" \" << L.at(i)(2, 0) << \" \"\n      << L.at(i)(0, 1) << \" \" << L.at(i)(1, 1) << \" \" << L.at(i)(2, 1) << \"\\n\";\n  }\n  fs.close();\n}\n\n\ndouble ExtractGaussianRVFromStream(std::ifstream &randnStream)\n{\n  double p;\n  randnStream >> p;    // N(0,1) distributed RV\n  if (!randnStream.good())\n  {\n    std::cout << \"ERROR: could not read from Gaussian random number file!   Flags: \"\n      << randnStream.eofbit << \" \" << randnStream.failbit << \" \" << randnStream.badbit << std::endl;\n    assert(0);\n  }\n  return p;\n}\n\n\n//// This function uses the Box-Muller method to generate\n////  zero mean, unit variance Gaussian random variables\n////  from a source of uniform random variables\n//// Ref: http://www.springer.com/cda/content/document/cda_downloaddocument/9781447129929-c2.pdf?SGWID=0-0-45-1314437-p174313273\n//double GenerateGaussianRV( cmnRandomSequence &rvGen )\n//{\n//  // 1: generate two uniform variables (U1 & U2) on (0,1]\n//  //     Note: since log(U1) = inf, we must generate variables\n//  //           on (0,1] rather than [0,1]\n//  double U1 = rvGen.ExtractRandomDouble(1e-6, 1.0);\n//  double U2 = rvGen.ExtractRandomDouble(1e-6, 1.0);\n//\n//  // 2: compute theta & p\n//  double theta = 2*cmnPI*U2;\n//  double p = sqrt(-2.0*log(U1));\n//\n//  // 3: compute gaussian RV\n//  //     Note: Z1 = p*cos(theta) and Z2 = p*sin(theta)\n//  //           are both Gaussian variables; to reduce\n//  //           interdependency between generated variables,\n//  //           we only use one of these.\n//  double Z1 = p*cos(theta);\n//  return Z1;\n//}\n\n\nvoid ComputeGroundTruthStats(const vctDynamicVector<vct3> &samples,\n  const vctDynamicVector<vct3> &sampleNorms,\n  const vctFrm3 &Fgt, const vctFrm3 &Freg,\n  double &posErr_mean, double &posErr_SD,\n  double &normErr_mean, double &normErr_SD)\n{\n  unsigned int nSamps = samples.size();\n\n  // Note: samples represents validation samples, which are at the\n  //       ground truth position.\n  //       Fgt is the xfm that takes non-registered samples to the ground truth position\n  //        (i.e. it is what Freg should be)\n  //       Freg is the computed registration that takes non-registered samples to the\n  //        estimated registered position.\n  vctFrm3 dF(Freg*Fgt.Inverse());\n\n  // compute ground truth distance statistics\n  vctDynamicVector<double> posErr(samples.size());\n  vctDynamicVector<double> normErr(sampleNorms.size());\n\n  // position errors\n  posErr_mean = 0.0;\n  vct3 t1;\n  double t2;\n  for (unsigned int i = 0; i < nSamps; i++)\n  { // compute mean distances\n    t1 = samples[i] - dF*samples[i];\n    posErr[i] = t1.Norm();\n    posErr_mean += posErr[i];\n  }\n  posErr_mean /= nSamps;\n  double posErr_Var = 0.0;\n  for (unsigned int i = 0; i < nSamps; i++)\n  { // compute standard deviation of distance error\n    t2 = (posErr[i] - posErr_mean);\n    posErr_Var += t2*t2;\n  }\n  posErr_Var /= nSamps;\n  posErr_SD = sqrt(posErr_Var);\n\n  // orientation errors\n  normErr_mean = 0.0;\n  double dotProd;\n  for (unsigned int i = 0; i < nSamps; i++)\n  { // compute mean angular offset\n    dotProd = vctDotProduct(sampleNorms[i], dF.Rotation()*sampleNorms[i]);\n    normErr[i] = acos(dotProd) * (180.0 / cmnPI);\n    normErr_mean += normErr[i];\n  }\n  normErr_mean /= nSamps;\n\n  double normErr_Var = 0.0;\n  for (unsigned int i = 0; i < nSamps; i++)\n  { // compute standard deviation of angular offset\n    t2 = (normErr[i] - normErr_mean);\n    normErr_Var += t2*t2;\n  }\n  normErr_Var /= nSamps;\n  normErr_SD = sqrt(normErr_Var);\n}\n\n\nvoid GenerateRandomTransform(unsigned int randSeed, unsigned int &randSeqPos,\n  double minOffsetPos, double maxOffsetPos,\n  double minOffsetAng, double maxOffsetAng,\n  vctFrm3 &F)\n{\n  //initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  // Generate random rotation\n  vctRot3 R;\n  GenerateRandomRotation(randSeed, randSeqPos, minOffsetAng, maxOffsetAng, R);\n\n  // Generate random translation\n  // get translation direction\n  vct3 dir(0.0);\n  while (dir.Norm() < 1e-6)\n  {\n    double pa[3];\n    cisstRandomSeq.ExtractRandomDoubleArray(-1.0, 1.0, pa, 3);\n    dir.Assign(pa[0], pa[1], pa[2]);\n  }\n  dir.NormalizedSelf();\n  // get translation magnitude\n  double mag = cisstRandomSeq.ExtractRandomDouble(minOffsetPos, maxOffsetPos);\n  vct3 p = mag*dir;\n\n  randSeqPos = cisstRandomSeq.GetSequencePosition();\n\n  F.Assign(vctRot3(R), p);\n\n  //// Generate random translation\n  //double pa[3];\n  //double sign;\n  //cisstRandomSeq.ExtractRandomDoubleArray(minOffsetPos,maxOffsetPos, pa,3);\n  //sign = cisstRandomSeq.ExtractRandomDouble(0.0,1.0);\n  //if (sign < 0.5) sign = -1.0;\n  //else sign = 1.0;\n  //vct3 pi(sign*pa[0],sign*pa[1],sign*pa[2]);\n}\n\nvoid GenerateRandomRotation(unsigned int randSeed, unsigned int &randSeqPos,\n  double minOffsetAng, double maxOffsetAng,\n  vctRot3 &R)\n{\n  //initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  // Generate random rotation on the unit sphere with uniform rotation angle\n  //  Note: using a fixed polar reference, such as the z-axis,\n  //        results in rotation vectors that are more concentrated about\n  //        the poles (i.e. about rotation angles near zero/180 degrees) than\n  //        about the equator (i.e. rotation angles near 90 degrees), due to \n  //        increased surface area at the equator.\n  //  Note: one way to fix this would be a to choose a random polar reference\n  //\n  //  use z-axis as starting point for random rotation axis\n  //  set xy axis along random axis direction on the x-y plane\n  //  generate uniform rotation angle 0-180 deg\n  //    (covers both upper and lower hemisphere since only positive rotations\n  //     will be generated for actual angle of rotation)\n  //  apply rotation about the xy axis to the z-axis to get the random rotation axis\n  //  generate unsigned uniform rotation angle around the random axis\n  vct3 z(0.0, 0.0, 1.0);\n  double xyDir = cisstRandomSeq.ExtractRandomDouble(0.0, 359.999)*cmnPI / 180.0;\n  vct3 xyAx(cos(xyDir), sin(xyDir), 0.0);\n  double xyAn = cisstRandomSeq.ExtractRandomDouble(0.0, 180.0)*cmnPI / 180.0;\n  vctAxAnRot3 Rxy(xyAx, xyAn);\n  vct3 rndAx = vctRot3(Rxy)*z;\n  double rndAn = cisstRandomSeq.ExtractRandomDouble(minOffsetAng, maxOffsetAng)*cmnPI / 180.0;\n  vctAxAnRot3 Ri(rndAx, rndAn);\n\n  randSeqPos = cisstRandomSeq.GetSequencePosition();\n  R.Assign(vctRot3(Ri));\n}\n\nvoid GenerateRandomL(unsigned int randSeed, unsigned int &randSeqPos,\n  const vctDynamicVector<vct3> &uDir, vctDynamicVector<vct3x2> &L)\n{\n  //initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  unsigned int nL = uDir.size();\n  L.SetSize(nL);\n\n  for (unsigned int i = 0; i < nL; i++)\n  {\n    // Generate random major / minor axis for GIMLOP distribution where the\n    //  major / minor axis are perpendicular to each other and perpendicular\n    //  to the central direction\n    // generate any vector not parallel to central direction\n    vct3 v(0.0);\n    double rv[3];\n    while (v.Norm() < 1e-10)\n    {\n      cisstRandomSeq.ExtractRandomDoubleArray(0.1, 1.0, rv, 3);\n      v.Assign(rv[0], rv[1], rv[2]);\n      v.NormalizedSelf();\n      // compute 1st vector perpendicular to central direction\n      v = vctCrossProduct(v, uDir(i));\n    }    \n    L(i).Column(0) = v.Normalized();\n    // comptue 2nd vector perpendicular to central direction and the 1st vector\n    L(i).Column(1) = vctCrossProduct(uDir(i),L(i).Column(0)).Normalized();\n  }\n}\n\nvoid Draw3DGaussianSample(std::ifstream &randnStream,\n  const vct3x3 &M, vct3 &x)\n{\n  // Compute eigen decomposition of the covariance\n  //  this method is stable under small perturbations of M across\n  //  different machines\n  vct3 eigenValues;\n  vct3x3 eigenVectors;\n\n  ComputeCovEigenDecomposition_SVD(M, eigenValues, eigenVectors);\n  //ComputeCovEigenDecomposition_NonIter(M, eigenValues, eigenVectors);\n\n  vct3x3 Ninv;\n  Ninv.Column(0) = eigenVectors.Column(0)*sqrt(eigenValues[0]);\n  Ninv.Column(1) = eigenVectors.Column(1)*sqrt(eigenValues[1]);\n  Ninv.Column(2) = eigenVectors.Column(2)*sqrt(eigenValues[2]);\n\n  // Generate an isotropic Gaussian noise and then transform it \n  //  to the noise model defined by covariance M\n  //  f(x) ~ N(0,M) = x'inv(M)x = (Nx)'I(Nx)\n  //  p = Nx ~ N(0,I)\n  //  x = inv(N)*p\n  //  M = VSV'  =>  Minv = V*S^-1*V'  =>  N = S^(-1/2)*V'  =>  Ninv = V*S^(1/2)\n  double p1, p2, p3;\n  p1 = ExtractGaussianRVFromStream(randnStream);\n  p2 = ExtractGaussianRVFromStream(randnStream);\n  p3 = ExtractGaussianRVFromStream(randnStream);\n  vct3 p(p1, p2, p3);\n  x = Ninv*p;\n\n  // This is not stable for small differences in M\n  //  i.e. M can have slightly different values when running code on\n  //  different machines (like e-10 differences) and this creates large\n  //  differences in the generated noise vector when computing Ninv\n  //// compute covariance decomposition:\n  ////    M = U*S*V' = U*S*U'\n  ////    inv(N) = U*sqrt(S)\n  ////    M = inv(N)*inv(N'),  inv(M) = N'*N\n  //vctFixedSizeMatrix<double, 3, 3, VCT_COL_MAJOR> A;\n  //vctFixedSizeMatrix<double, 3, 3, VCT_COL_MAJOR> U;\n  //vctFixedSizeMatrix<double, 3, 3, VCT_COL_MAJOR> Vt;\n  //vct3 S;\n  //try\n  //{\n  //  A.Assign(M);\n  //  nmrSVD(A, U, S, Vt);\n  //}\n  //catch (...)\n  //{\n  //  assert(0);\n  //}\n  //vct3x3 Ninv;\n  //Ninv.Column(0) = U.Column(0)*sqrt(S[0]);\n  //Ninv.Column(1) = U.Column(1)*sqrt(S[1]);\n  //Ninv.Column(2) = U.Column(2)*sqrt(S[2]);\n}\n\n// Fisher Parameters\n//  k     ~ concentration  (Note: here we use an alternative approximation k ~= 1.0/circSD^2)\n//  mean  ~ central direction\nvoid DrawFisherSample(std::ifstream &randnStream, double k, const vct3 &mean, vct3 &n)\n{\n  // Use the approximation that the tangential to the mean direction\n  //  is approximately Gaussian distributed as: \n  //     sqrt(1/k)*Xperp ~ N(0,I2)  where  1/k ~= sigma2 (circular std dev squared)\n\n  // Compute noisy version of z-axis as: [N1,N2,t]'\n  double t, N1, N2;\n  double circSD = 1.0 / sqrt(k);\n  N1 = ExtractGaussianRVFromStream(randnStream) * circSD * (cmnPI / 180.0);\n  N2 = ExtractGaussianRVFromStream(randnStream) * circSD * (cmnPI / 180.0);\n  t = sqrt(1.0 - N1*N1 - N2*N2);\n  vct3 zn(N1, N2, t);\n  zn.NormalizedSelf();  // apply unit normalization to noisy z just to be safe\n  // find rotation that rotates z to the mean direction\n  vct3 z(0.0, 0.0, 1.0);\n  vct3 xProd = vctCrossProduct(z, mean);\n  if (xProd.Norm() < 1.0e-6)    // protect from divide-by-zero\n  { // sample norm is parallel to z\n    if (vctDotProduct(z, mean) > 0.0)\n      n = zn;\n    else\n      n = -zn;\n  }\n  else\n  {\n    // the norm of the cross product is the same for angles of x deg & x+180 deg\n    //  between two vectors => use dot product to determine the angle\n    //   NOTE: the angle corresponding to the cross product axis is always > 0;\n    //         acos of the dot product gives the correct form\n    //   NOTE: the problem with using norm of cross product isn't that we aren't\n    //         going the right direction, but rather that we don't rotate far enough\n    //         if A & B are seperated by more than 90 degrees.  I.e. if angular\n    //         seperation between A & B is 100 degrees, then asin(norm(AxB)) gives\n    //         the same angle as if A & B are seperated by 80 degrees => we don't\n    //         know if the actual angle is X or 90+X using the norm of cross product.\n    double dProd = vctDotProduct(z, mean);\n    vctAxAnRot3 Rs(xProd.Normalized(), acos(dProd));\n    // apply rotation to noisy Z to obtain the noisy sample\n    n = vctRot3(Rs)*zn;\n  }\n\n  //// Apply a Gaussian-distributed offset angle about a random rotation axis oriented\n  ////  perpendicular to the orientation direction\n  ////  Note: this method is more likely to generate angular offsets close to zero\n  ////        than a proper Fisher or binomial Gaussian approximation. (To do this correctly,\n  ////        the offset angle should be chi-square distributed.)\n  //// Compute noisey version of +z axis:\n  //// compute a random rotation axis on the xy plane to add noise to base (+Z) direction\n  //double xyDir = cisstRandomSeq.ExtractRandomDouble(0.0, 359.999)*cmnPI/180.0;\n  //vct3 xyAx(cos(xyDir),sin(xyDir),0.0);\n  //double xyAn;      \n  //xyAn = ExtractGaussianRVFromStream( randnStream ) * circStdDev * (cmnPI/180.0);\n  //vctAxAnRot3 Rn(xyAx,xyAn);\n  //vct3 zn = vctRot3(Rn)*z;     // noisy z             // *** why must convert to vctRot3 type?\n  //// find rotation that rotates z to the sample norm\n  //xProd = vctCrossProduct(z,sampleNorms.at(k));\n  //if (xProd.Norm() < 1e-6)\n  //{ // sample norm is parallel to z\n  //  // protect from divide-by-zero\n  //  if (vctDotProduct(z,sampleNorms.at(k)) > 0)\n  //    noisySampleNorms.at(k) = zn;\n  //  else\n  //    noisySampleNorms.at(k) = -zn;\n  //}\n  //else\n  //{\n  //  // the norm of the cross product is the same for angles of x deg & x+180 deg\n  //  //  between two vectors => use dot product to determine the angle\n  //  //   NOTE: the angle corresponding to the cross product axis is always > 0;\n  //  //         acos of the dot product gives the correct form\n  //  //   NOTE: the problem with using norm of cross product isn't that we aren't\n  //  //         going the right direction, but rather that we don't rotate far enough\n  //  //         if A & B are seperated by more than 90 degrees.  I.e. if angular\n  //  //         seperation between A & B is 100 degrees, then asin(norm(AxB)) gives\n  //  //         the same angle as if A & B are seperated by 80 degrees => we don't\n  //  //         know if the actual angle is X or 90+X using the norm of cross product.\n  //  double dProd = vctDotProduct(z,sampleNorms.at(k));\n  //  vctAxAnRot3 Rs(xProd.Normalized(), acos(dProd));\n  //  // apply rotation to noisy Z to obtain the noisy sample\n  //  noisySampleNorms.at(k) = vctRot3(Rs)*zn;\n  //}\n}\n\n// GIMLOP Parameters\n//  k  ~ concentration       (Note the approximation 1/k ~= circSD^2)\n//  B  ~ ovalness parameter  (Note eccentricity e = 2*Beta/k) \n//  mean ~ central direction\n//  L  ~ [l1,l2]\n//        l1 ~ major axis\n//        l2 ~ minor axis\nvoid DrawGIMLOPSample(std::ifstream &randnStream,\n  double k, double B, const vct3 &mean,\n  const vctFixedSizeMatrix<double, 3, 2> &L, vct3 &n)\n{\n  // Use the approximation that the tangential to the mean direction\n  //  is approximately Gaussian distributed as: \n  //     Z ~ N(0,[k*I3-2*A]^-1)  where  A = Beta*[l1*l1' - l2*l2'] \n  //                                    Z is the vector component tangential to the central direction\n  //\n  //  Since Z only has 2DOF, we can also compute Z using a 2D distribution:\n  //   define Zp = [l1'Z, l2'Z]'\n  //   then Zp is approximately 2D Gaussian distributed as: Zp ~ N(0,diag(k-2B,k+2B)^-1)\n  //\n  //  Alternatively, the 3D form may be expressed as:\n  //   Z ~ N(0,M^-1)  where  M = (k-2B)*l1*l1' + (k+2B)*l2*l2' + k*u*u'\n  //   which can be generated using 2 Gaussian distributed values\n  //   for lengths along l1 & l2 since Z is known to lie in the plane of l1 & l2\n  //\n  //   Variance along l1 = 1/(k-2B)\n  //   Variance along l2 = 1/(k+2B)\n  //\n  // Noisy vector X ~= u + Z  for concentrated points\n  //   more accurately, X = Zwrap where Zwrap is the \"wrapped\" position of Z on the unit\n  //   sphere starting from the central direction u\n\n  if (k <= 2 * B)\n  {\n    std::cout << \"ERROR: can only simulate for k > 2*B\" << std::endl;\n  }\n  double N1, N2, SD1, SD2;\n  N1 = ExtractGaussianRVFromStream(randnStream);\n  N2 = ExtractGaussianRVFromStream(randnStream);\n  SD1 = 1.0 / sqrt(k - 2.0*B);\n  SD2 = 1.0 / sqrt(k + 2.0*B);\n  // compute tangential vector Z\n  vct3 Z = N1*SD1*L.Column(0) + N2*SD2*L.Column(1);\n  // wrap Z onto unit sphere\n  //  do this by rotating u until it aligns with Zwrap\n  vct3 Raxis = vctCrossProduct(mean, Z);\n  Raxis.NormalizedSelf();\n  double Rangle = Z.Norm();\n  if (Rangle > cmnPI)\n  {\n    std::cout << \"WARNING: generated GIMLOP sample more than 180 degrees\"\n      << \" offset from the central direction\" << std::endl;\n  }\n  vctRot3 R(vctAxAnRot3(Raxis, Rangle));\n  n = R*mean;   // Zwrap\n}\n\n\nvoid CreateMesh(cisstMesh &mesh,\n  const std::string &meshLoadPath,\n  std::string *SavePath_Mesh)\n{\n  // load mesh\n  mesh.LoadPLY(meshLoadPath);\n  if (mesh.NumVertices() == 0)\n  {\n    printf(\"ERROR: Read mesh resulted in 0 triangles\\n\");\n    assert(0);\n  }\n\n  // save mesh\n  if (SavePath_Mesh)\n  {\n    // TODO: update\n    //if (mesh.SaveMeshFile((*SavePath_Mesh).append(\".mesh\")) < 0)\n    {\n      std::cout << \"ERROR: Save mesh failed\" << std::endl;\n      assert(0);\n    }\n  }\n}\n\n\nvoid GenerateSamples(cisstMesh &mesh,\n  unsigned int randSeed, unsigned int &randSeqPos,\n  unsigned int nSamps,\n  vctDynamicVector<vct3>   &samples,\n  vctDynamicVector<vct3>   &sampleNorms,\n  vctDynamicVector<unsigned int>  &sampleDatums,\n  std::string *SavePath_Samples)\n{\n  //initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  samples.SetSize(nSamps);\n  sampleNorms.SetSize(nSamps);\n  sampleDatums.SetSize(nSamps);\n\n  // generating samples\n  int Fx, Nf;\n  double mu0, mu1, mu2, mu;\n  double lam0, lam1, lam2;\n  // initialize samples\n  Nf = mesh.NumTriangles();\n  for (unsigned int s = 0; s < nSamps; s++) {\n    // sampling the object surface and generating second pointcloud from it\n    Fx = cisstRandomSeq.ExtractRandomInt(0, Nf - 1);\n    mu0 = cisstRandomSeq.ExtractRandomDouble(0.0, 1.0);\n    mu1 = cisstRandomSeq.ExtractRandomDouble(0.0, 1.0);\n    mu2 = cisstRandomSeq.ExtractRandomDouble(0.0, 1.0);\n    mu = mu0 + mu1 + mu2;\n    lam0 = mu0 / mu;\n    lam1 = mu1 / mu;\n    lam2 = mu2 / mu;\n    vct3 v0, v1, v2;\n    mesh.FaceCoords(Fx, v0, v1, v2);\n    samples.at(s) = lam0*v0 + lam1*v1 + lam2*v2;\n    sampleNorms.at(s) = mesh.faceNormals(Fx);\n    sampleDatums.at(s) = Fx;\n  }\n  randSeqPos = cisstRandomSeq.GetSequencePosition();\n\n  // save samples\n  if (SavePath_Samples)\n  {\n    if (cisstPointCloud::WritePointCloudToFile(*SavePath_Samples, samples, sampleNorms) < 0)\n    {\n      std::cout << \"ERROR: Samples save failed\" << std::endl;\n      assert(0);\n    }\n  }\n}\n\nvoid GenerateNoisySamples_Gaussian(\n  std::ifstream &randnStream,\n  const vctDynamicVector<vct3>   &samples,\n  const vctDynamicVector<vct3x3> &sampleCov,\n  vctDynamicVector<vct3>   &noisySamples,\n  std::string *SavePath_NoisySamples,\n  std::string *SavePath_Cov)\n{\n  unsigned int numSamps = samples.size();\n  noisySamples.SetSize(numSamps);\n  for (unsigned int i = 0; i < numSamps; i++)\n  {\n    //=== Generate position noise ===//\n\n    // generate Guassian noise\n    vct3 noise;\n    Draw3DGaussianSample(randnStream, sampleCov(i), noise);\n\n    // apply Gaussian noise to sample\n    noisySamples(i) = samples(i) + noise;\n  }\n\n  // save noisy samples\n  if (SavePath_NoisySamples)\n  {\n    std::string noisySampsSavePath = *SavePath_NoisySamples;\n    cisstPointCloud::WritePointCloudToFile(noisySampsSavePath, noisySamples);\n  }\n  // save sample covariances\n  if (SavePath_Cov)\n  {\n    WriteToFile_Cov(sampleCov, *SavePath_Cov);\n  }\n}\n\nvoid GenerateOutlierSamples_SurfaceOffset(\n  unsigned int randSeed, unsigned int &randSeqPos,\n  const vctDynamicVector<vct3>   &samples,\n  const vctDynamicVector<vct3>   &sampleNorms,\n  vctDynamicVector<vct3>   &outlierSamples,\n  double minPosOffsetOutlier, double maxPosOffsetOutlier,\n  std::string *SavePath_OutlierSamples)\n{\n  // add outliers to samples such that outliers are offset outward from\n  //  the shape (offset along the point normal direction)\n\n  // initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  unsigned int numOutliers = samples.size();\n  outlierSamples.SetSize(numOutliers);\n  for (unsigned int k = 0; k < numOutliers; k++)\n  {\n    //=== Generate position outlier ===//\n\n    // generate a random outlier\n    double offset = cisstRandomSeq.ExtractRandomDouble(minPosOffsetOutlier, maxPosOffsetOutlier);\n    outlierSamples(k) = samples(k) + offset*sampleNorms(k);\n  }\n\n  randSeqPos = cisstRandomSeq.GetSequencePosition();\n\n  // save noisy samples\n  if (SavePath_OutlierSamples)\n  {\n    std::string savePath = *SavePath_OutlierSamples;\n    cisstPointCloud::WritePointCloudToFile(savePath, outlierSamples);\n  }\n}\n\n// Generate noisy samples having the specified standard deviation of\n//  noise in directions parallel and perpendicular to the surface\nvoid ComputeCovariances_Random( \n  unsigned int randSeed, unsigned int &randSeqPos,\n  const vct3 &StdDev,\n  vctDynamicVector<vct3x3> &cov,\n  unsigned int nCov,\n  std::string *SavePath_Cov)\n{\n  // initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  vctRot3 R;\n  vct3x3 M0;\n\n  // define diagonal matrix of eigenvalues\n  M0.SetAll(0.0);\n  M0.Element(0, 0) = StdDev[0] * StdDev[0];\n  M0.Element(1, 1) = StdDev[1] * StdDev[1];\n  M0.Element(2, 2) = StdDev[2] * StdDev[2];\n\n  // Compute covariances\n  cov.SetSize(nCov);\n  for (unsigned int i = 0; i < nCov; i++)\n  {\n    // generate random rotation axis\n    vct3 axis;    \n    cisstRandomSeq.ExtractRandomDoubleArray(-1.0, 1.0, axis.Pointer(0), 3);    \n    if (axis.Norm() < 1e-12)  // protect from division by zero\n    {\n      axis = (1.0, 0.0, 0.0);\n    }\n    axis.NormalizedSelf();\n    // generate random rotation angle\n    double angle = cisstRandomSeq.ExtractRandomDouble(-cmnPI, cmnPI);\n    // form rotation matrix\n    vctRot3 R = vctRot3(vctAxAnRot3(axis, angle));\n\n    // form covariance \n    cov(i) = R*M0*R.Transpose();\n  }\n\n  // save model covariances\n  if (SavePath_Cov)\n  {\n    WriteToFile_Cov(cov, *SavePath_Cov);\n  }\n\n  randSeqPos = cisstRandomSeq.GetSequencePosition();\n}\n\n// Generate noisy samples having the specified standard deviation of\n//  noise in directions parallel and perpendicular to the surface\nvoid ComputeCovariances_SurfaceModel(\n  double StdDevInPlane, double StdDevPerpPlane,\n  vctDynamicVector<vct3>   &samples,\n  vctDynamicVector<vct3>   &sampleNorms,\n  vctDynamicVector<vct3x3> &modelCov,\n  //vctDynamicVector<vct3x3> &modelInvCov,\n  std::string *SavePath_Cov)\n{\n  unsigned int nSamps = samples.size();\n\n  vctRot3 R;\n  vct3x3 M, M0;\n  //vct3x3 invM0, Ninv;\n  vct3 x(1.0, 0.0, 0.0);\n  vct3 y(0.0, 1.0, 0.0);\n  vct3 z(0.0, 0.0, 1.0);\n\n  // Covariance Model\n  //  define model such that noise perpendicular to the surface\n  //  is different than noise in-plane with the surface\n  //  assume a z-axis surface orientation\n  M0.SetAll(0.0);\n  M0.Element(0, 0) = StdDevInPlane * StdDevInPlane;\n  M0.Element(1, 1) = StdDevInPlane * StdDevInPlane;\n  M0.Element(2, 2) = StdDevPerpPlane * StdDevPerpPlane;\n  //invM0.SetAll(0.0);\n  //invM0.Element(0, 0) = 1.0 / M0.Element(0, 0);\n  //invM0.Element(1, 1) = 1.0 / M0.Element(1, 1);\n  //invM0.Element(2, 2) = 1.0 / M0.Element(2, 2);\n\n  // Compute model covariances\n  modelCov.SetSize(nSamps);\n  //modelInvCov.SetSize(nSamps);\n  for (unsigned int i = 0; i < nSamps; i++)\n  {\n    //  find a rotation to rotate the sample normal to the z-axis\n    R = XProdRotation(sampleNorms(i), z);\n    // compute model covariance M of this sample\n    //   Note: rotate to align normal with z-axis, apply covariance model, rotate back\n    M = R.Transpose()*M0*R;\n\n    modelCov(i) = M;\n    //modelInvCov(i) = R.Transpose()*invM0*R;\n  }\n\n  // save model covariances\n  if (SavePath_Cov)\n  {\n    WriteToFile_Cov(modelCov, *SavePath_Cov);\n  }\n}\n\n// Generate noisy samples with noise distributed according the\n//  given covariance\nvoid GenerateSampleErrors_Covariance(\n  std::ifstream &randnStream,\n  const vctDynamicVector<vct3x3> &sampleCov,\n  const vctDynamicVector<vct3>   &samples,\n  const vctDynamicVector<vct3>   &sampleNorms,\n  vctDynamicVector<vct3>   &noisySamples,\n  std::string *SavePath_NoisySamples)\n{\n  unsigned int nSamps = samples.size();  \n\n  // Compute noise\n  noisySamples.SetSize(nSamps);\n  GenerateNoisySamples_Gaussian(randnStream, samples, sampleCov, noisySamples);\n\n  // save noisy samples\n  if (SavePath_NoisySamples)\n  {\n    std::string savePath = *SavePath_NoisySamples;\n    cisstPointCloud::WritePointCloudToFile(savePath, noisySamples);\n  }\n}\n\n// Generate noisy samples having the specified standard deviation of\n//  noise in directions parallel and perpendicular to the surface\n//  with the specified percentage of samples being outliers\nvoid GenerateSampleErrors_SurfaceNoise(\n  unsigned int randSeed, unsigned int &randSeqPos,\n  std::ifstream &randnStream,\n  double StdDevInPlane, double StdDevPerpPlane,\n  vctDynamicVector<vct3>   &samples,\n  vctDynamicVector<vct3>   &sampleNorms,\n  vctDynamicVector<vct3>   &noisySamples,\n  vctDynamicVector<vct3x3> &sampleCov,\n  //vctDynamicVector<vct3x3> &sampleInvCov,\n  double percentOutliers,\n  double minPosOffsetOutlier, double maxPosOffsetOutlier,\n  std::string *SavePath_NoisySamples,\n  std::string *SavePath_Cov)\n{\n  unsigned int nSamps = samples.size();\n  unsigned int nOutliers = (unsigned int)(percentOutliers*(double)nSamps);\n  unsigned int nNoisy = nSamps - nOutliers;\n\n  // Compute Covariance Model\n  //  define model such that noise perpendicular to the surface\n  //  is different than noise in-plane with the surface\n  ComputeCovariances_SurfaceModel(\n    StdDevInPlane, StdDevPerpPlane,\n    samples, sampleNorms,\n    sampleCov,\n    SavePath_Cov);\n\n  // Compute noise\n  vctDynamicVector<vct3> samplesNoisy(nNoisy);\n  GenerateNoisySamples_Gaussian(randnStream, samples, sampleCov, samplesNoisy);\n\n  // Compute outliers\n  vctDynamicVectorRef<vct3> samplesRef;\n  vctDynamicVectorRef<vct3> sampleNormsRef;\n  samplesRef.SetRef(samples, nNoisy, nOutliers);\n  sampleNormsRef.SetRef(sampleNorms, nNoisy, nOutliers);\n  vctDynamicVector<vct3> samplesOutliers(nOutliers);\n  GenerateOutlierSamples_SurfaceOffset(\n    randSeed, randSeqPos,\n    samplesRef, sampleNormsRef,\n    samplesOutliers,\n    minPosOffsetOutlier, maxPosOffsetOutlier);\n\n  // compose output samples\n  noisySamples.SetSize(nSamps);\n  for (unsigned int i = 0; i < nNoisy; i++)\n  {\n    noisySamples(i) = samplesNoisy(i);\n  }\n  for (unsigned int i = nNoisy; i < nSamps; i++)\n  {\n    noisySamples(i) = samplesOutliers(i - nNoisy);\n  }\n\n  // save noisy samples\n  if (SavePath_NoisySamples)\n  {\n    std::string savePath = *SavePath_NoisySamples;\n    cisstPointCloud::WritePointCloudToFile(savePath,noisySamples);\n  }\n}\n\n\n// Generate sample noise having a random position covariance with the\n//  specified eigenvalues and random orientation with the specified\n//  circular standard deviation and eccentricity.\nvoid GenerateSampleRandomNoise(unsigned int randSeed, unsigned int &randSeqPos,\n  std::ifstream &randnStream,\n  vct3 &covEigenvalues,\n  double circStdDev, double circEccentricity,\n  vctDynamicVector<vct3>   &samples,\n  vctDynamicVector<vct3>   &sampleNorms,\n  vctDynamicVector<vct3>   &noisySamples,\n  vctDynamicVector<vct3>   &noisySampleNorms,\n  vctDynamicVector<vct3x3> &sampleCov,\n  vctDynamicVector<vct3x3> &sampleInvCov,\n  vctDynamicVector<vct3x2> &noiseL,\n  double percentOutliers,\n  double minPosOffsetOutlier, double maxPosOffsetOutlier,\n  double minAngOffsetOutlier, double maxAngOffsetOutlier,\n  std::string *SavePath_NoisySamples,\n  std::string *SavePath_Cov,\n  std::string *savePath_L)\n{\n  // initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  unsigned int nSamps = samples.size();\n  unsigned int nOutliers = (unsigned int)(percentOutliers*(double)nSamps);\n  unsigned int nNoisy = nSamps - nOutliers;\n\n  noisySamples.SetSize(nSamps);\n  noisySampleNorms.SetSize(nSamps);\n  sampleCov.SetSize(nSamps);\n  sampleInvCov.SetSize(nSamps);\n  noiseL.SetSize(nSamps);\n\n  vct3x3 M, M0, invM0, Ninv;\n  vct3 n;\n  vctRot3 R;\n  vct3 x(1.0, 0.0, 0.0);\n  vct3 y(0.0, 1.0, 0.0);\n  vct3 z(0.0, 0.0, 1.0);\n\n  // set eigenvalues of noise covariance\n  //  assume a z-axis normal orientation\n  M0.SetAll(0.0);\n  M0.Element(0, 0) = covEigenvalues[0];\n  M0.Element(1, 1) = covEigenvalues[1];\n  M0.Element(2, 2) = covEigenvalues[2];\n  invM0.SetAll(0.0);\n  invM0.Element(0, 0) = 1.0 / M0.Element(0, 0);\n  invM0.Element(1, 1) = 1.0 / M0.Element(1, 1);\n  invM0.Element(2, 2) = 1.0 / M0.Element(2, 2);\n\n  // add random noise to samples such that noise perpendicular to the\n  //  sample triangle is different than noise in-plane with triangle\n  for (unsigned int i = 0; i < nNoisy; i++)\n  {\n    //=== Generate position noise ===//\n\n    // Generate random noise covariance for this sample\n    vctRot3 Rcov;\n    GenerateRandomRotation(randSeed, randSeqPos, 0.0, 180.0, Rcov);\n    M = Rcov.Transpose()*M0*Rcov;\n\n    // generate Guassian noise\n    vct3 p;\n    Draw3DGaussianSample(randnStream, M, p);\n\n    // apply Gaussian noise to the sample\n    noisySamples(i) = samples(i) + p;\n    sampleCov(i) = M;\n    sampleInvCov(i) = Rcov.Transpose()*invM0*Rcov;\n\n    //=== Generate orientation noise ===//\n\n    // Fisher Noise Model\n    // Uses the approximation that 1/k ~= circSD^2\n    //double k = 1.0/(circStdDev*circStdDev);\n    //DrawFisherSample( randnStream, k, sampleNorms(i), noisySampleNorms(i) );\n\n    // Generate a major/minor axis for this sample\n    vctFixedSizeMatrix<double, 3, 2> L;\n    // generate a random major/minor axis in the x-y plane\n    double xyAngle = cisstRandomSeq.ExtractRandomDouble(0.0, cmnPI);\n    vctRot3 Rz(vctAxAnRot3(z, xyAngle));\n    vct3 majorXY = Rz*x;\n    vct3 minorXY = Rz*y;\n    // rotate major/minor axis to be perpendicular to the sample orientation\n    //  apply rotation that takes z-axis to the sample norm\n    R = XProdRotation(sampleNorms(i), z);  // rotation takes sample norm to z-axis\n    L.Column(0) = R.Transpose()*majorXY;\n    L.Column(1) = R.Transpose()*minorXY;\n\n    // GIMLOP Noise Model\n    // Use the approximation that k ~= 1/circSD^2\n    double k = 1.0 / (circStdDev*circStdDev);\n    double B = circEccentricity*k / 2.0;\n    DrawGIMLOPSample(randnStream, k, B, sampleNorms(i), L, noisySampleNorms(i));\n\n    // TODO: change to 3x3 L allowing for a different central direction\n    //       than the observed sample\n    // Reorient \"reported\" L to be perpendicular to the noisySample rather than\n    //  the non-noisy sample (do this because the noisy sample will be used as\n    //  the central direction in the GIMLOP noise model to simulate an observed\n    //  data point with unknown ground truth orientation)\n    // Compute rotation from sample norm to noisy sample norm\n    vctRot3 Rl = XProdRotation(sampleNorms(i), noisySampleNorms(i));\n    noiseL(i) = Rl*L;\n  }\n\n  // TODO: how to define noise model for outliers (i.e. what to assign\n  //       as covariance, k, e, and L values?)\n  // TODO: need seperate k, e, and L for each sample (not just seperate L) if\n  //       using outliers?\n  // add outliers to samples such that outliers are offset outward from\n  //  the shape (offset along the point normal direction)\n  vctRot3 Routlier;\n  for (unsigned int k = nNoisy; k < nSamps; k++)\n  {\n    //=== Generate position outlier ===//\n\n    double offset = cisstRandomSeq.ExtractRandomDouble(minPosOffsetOutlier, maxPosOffsetOutlier);\n    noisySamples.at(k) = samples.at(k) + offset*sampleNorms.at(k);\n    sampleCov(k) = vct3x3::Eye();\n    sampleInvCov(k) = vct3x3::Eye();\n\n\n    //=== Generate orientation outlier ===//\n\n    // Generate random rotation on the unit sphere with uniform rotation angle\n    //  within the specified range for the outliers\n    GenerateRandomRotation(randSeed, randSeqPos, minAngOffsetOutlier, maxAngOffsetOutlier, Routlier);\n    noisySampleNorms.at(k) = Routlier*sampleNorms.at(k);\n    // define L\n    // find any two axis perpendicular to the noisy sample and to each other\n    vct3 xProd = vctCrossProduct(z, noisySampleNorms.at(k));\n    vct3 tmp1, tmp2;\n    if (xProd.Norm() <= 1.0e-8)  // protect from divide by zero\n    { // noisy samples points down z axis\n      tmp1 = x;\n      tmp2 = y;\n    }\n    else\n    {\n      tmp1 = xProd.Normalized();\n      tmp2 = vctCrossProduct(tmp1, noisySampleNorms.at(k));\n      tmp2.NormalizedSelf();\n    }\n    noiseL(k).Column(0) = tmp1;\n    noiseL(k).Column(1) = tmp2;\n  }\n  randSeqPos = cisstRandomSeq.GetSequencePosition();\n\n  // save noisy samples\n  if (SavePath_NoisySamples)\n  {\n    std::string noisySampsSavePath = *SavePath_NoisySamples;\n    if (cisstPointCloud::WritePointCloudToFile(noisySampsSavePath, noisySamples, noisySampleNorms) < 0)\n    {\n      std::cout << \"ERROR: Samples save failed\" << std::endl;\n      assert(0);\n    }\n  }\n  // save cov\n  if (SavePath_Cov)\n  {\n    WriteToFile_Cov(sampleCov, *SavePath_Cov);\n  }\n  // save L\n  if (savePath_L)\n  {\n    WriteToFile_L(noiseL, *savePath_L);\n  }\n}\n\n\n// Generate sample noise having the specified standard deviation of\n//  noise in directions parallel and perpendicular to the triangle\n//  plane from which the sample was drawn.\nvoid GenerateSampleSurfaceNoise(unsigned int randSeed, unsigned int &randSeqPos,\n  std::ifstream &randnStream,\n  double StdDevInPlane, double StdDevPerpPlane,\n  double circStdDev, double circEccentricity,\n  vctDynamicVector<vct3>   &samples,\n  vctDynamicVector<vct3>   &sampleNorms,\n  vctDynamicVector<vct3>   &noisySamples,\n  vctDynamicVector<vct3>   &noisySampleNorms,\n  vctDynamicVector<vct3x3> &sampleCov,\n  vctDynamicVector<vct3x3> &sampleInvCov,\n  vctDynamicVector<vct3x2> &noiseL,\n  double percentOutliers,\n  double minPosOffsetOutlier, double maxPosOffsetOutlier,\n  double minAngOffsetOutlier, double maxAngOffsetOutlier,\n  std::string *SavePath_NoisySamples,\n  std::string *SavePath_Cov,\n  std::string *savePath_L)\n{\n  // initialize random numbers\n  cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  cisstRandomSeq.SetSeed(randSeed);\n  cisstRandomSeq.SetSequencePosition(randSeqPos);\n\n  unsigned int nSamps = samples.size();\n  unsigned int nOutliers = (unsigned int)(percentOutliers*(double)nSamps);\n  unsigned int nNoisy = nSamps - nOutliers;\n\n  noisySamples.SetSize(nSamps);\n  noisySampleNorms.SetSize(nSamps);\n  sampleCov.SetSize(nSamps);\n  sampleInvCov.SetSize(nSamps);\n  noiseL.SetSize(nSamps);\n\n  vct3x3 M, M0, invM0, Ninv;\n  vct3 n;\n  vctRot3 R;\n  vct3 x(1.0, 0.0, 0.0);\n  vct3 y(0.0, 1.0, 0.0);\n  vct3 z(0.0, 0.0, 1.0);\n\n  // set eigenvalues of noise covariance\n  //  assume a z-axis normal orientation\n  M0.SetAll(0.0);\n  M0.Element(0, 0) = StdDevInPlane * StdDevInPlane;\n  M0.Element(1, 1) = StdDevInPlane * StdDevInPlane;\n  M0.Element(2, 2) = StdDevPerpPlane * StdDevPerpPlane;\n  invM0.SetAll(0.0);\n  invM0.Element(0, 0) = 1.0 / M0.Element(0, 0);\n  invM0.Element(1, 1) = 1.0 / M0.Element(1, 1);\n  invM0.Element(2, 2) = 1.0 / M0.Element(2, 2);\n\n  // add random noise to samples such that noise perpendicular to the\n  //  sample triangle is different than noise in-plane with triangle\n  for (unsigned int i = 0; i < nNoisy; i++)\n  {\n    //=== Generate position noise ===//\n\n    // Define the noise covariance for this sample\n    //  find rotation to rotate the sample normal to the z-axis\n    R = XProdRotation(sampleNorms(i), z);\n    // compute noise covariance M of this sample\n    //   Note: rotate to align normal with z-axis, apply noise covariance, rotate back\n    M = R.Transpose()*M0*R;\n\n    // generate Guassian noise\n    vct3 p;\n    Draw3DGaussianSample(randnStream, M, p);\n\n    // apply Gaussian noise to the sample\n    noisySamples(i) = samples(i) + p;\n    sampleCov(i) = M;\n    sampleInvCov(i) = R.Transpose()*invM0*R;\n\n    if (circStdDev > 0.0)\n    {\n      //=== Generate orientation noise ===//\n\n      // Fisher Noise Model\n      // Uses the approximation that 1/k ~= circSD^2\n      //double k = 1.0/(circStdDev*circStdDev);\n      //DrawFisherSample( randnStream, k, sampleNorms(i), noisySampleNorms(i) );\n\n      // Generate a major/minor axis for this sample\n      vctFixedSizeMatrix<double, 3, 2> L;\n      // generate a random major/minor axis in the x-y plane\n      double xyAngle = cisstRandomSeq.ExtractRandomDouble(0.0, cmnPI);\n      vctRot3 Rz(vctAxAnRot3(z, xyAngle));\n      vct3 majorXY = Rz*x;\n      vct3 minorXY = Rz*y;\n      // rotate major/minor axis to be perpendicular to the sample orientation\n      //  apply rotation that takes z-axis to the sample norm\n      L.Column(0) = R.Transpose()*majorXY;\n      L.Column(1) = R.Transpose()*minorXY;\n\n      // GIMLOP Noise Model\n      // Use the approximation that k ~= 1/circSD^2\n      double k = 1.0 / (circStdDev*circStdDev);\n      double B = circEccentricity*k / 2.0;\n      DrawGIMLOPSample(randnStream, k, B, sampleNorms(i), L, noisySampleNorms(i));\n\n      // Reorient \"reported\" L to be perpendicular to the noisySample rather than\n      //  the non-noisy sample (do this because the noisy sample will be used as\n      //  the central direction in the GIMLOP noise model to simulate an observed\n      //  data point with unknown ground truth orientation)\n      // Compute rotation from sample norm to noisy sample norm\n      vctRot3 Rl = XProdRotation(sampleNorms(i), noisySampleNorms(i));\n      noiseL(i) = Rl*L;\n    }\n    else\n    {\n      noisySampleNorms(i) = sampleNorms(i);\n      noiseL(i) = vct3x2(0.0);\n    }\n  }\n\n  // add outliers to samples such that outliers are offset outward from\n  //  the shape (offset along the point normal direction)\n  for (unsigned int k = nNoisy; k < nSamps; k++)\n  {\n    //=== Generate position outlier ===//\n\n    // generate a random outlier\n    double offset = cisstRandomSeq.ExtractRandomDouble(minPosOffsetOutlier, maxPosOffsetOutlier);\n    noisySamples.at(k) = samples.at(k) + offset*sampleNorms.at(k);\n\n    // Define the noise covariance for this sample\n    //  find rotation to rotate the sample normal to the z-axis\n    R = XProdRotation(sampleNorms.at(k), z);\n    // compute noise covariance M of this sample\n    //   Note: rotate to align normal with z-axis, apply noise covariance, rotate back\n    M = R.Transpose()*M0*R;\n    sampleCov.at(k) = M;\n    sampleInvCov.at(k) = R.Transpose()*invM0*R;\n\n    if (maxAngOffsetOutlier > 0.0)\n    {\n      //=== Generate orientation outlier ===//\n\n      // Generate random rotation on the unit sphere with uniform rotation angle\n      //  use z-axis as starting point for random rotation axis\n      //  set rotation axis along random direction on the x-y plane\n      //  generate uniform rotation angle 0-180 deg\n      //  apply rotation about the rotation axis to the z-axis to get the random rotation axis\n      //  generate a uniformly distributed rotation angle for the random rotation axis\n      vct3 z(0.0, 0.0, 1.0);\n      double xyDir = cisstRandomSeq.ExtractRandomDouble(0.0, 359.999)*cmnPI / 180.0;\n      vct3 xyAx(cos(xyDir), sin(xyDir), 0.0);\n      double xyAn = cisstRandomSeq.ExtractRandomDouble(0.0, 180.0)*cmnPI / 180.0;\n      vctAxAnRot3 Rxy(xyAx, xyAn);\n      vct3 rndAx = vctRot3(Rxy)*z;\n      double rndAn = cisstRandomSeq.ExtractRandomDouble(minAngOffsetOutlier, maxAngOffsetOutlier)*(cmnPI / 180.0);\n      vctAxAnRot3 Rrod(rndAx, rndAn);\n      noisySampleNorms.at(k) = vctRot3(Rrod)*sampleNorms.at(k);\n      // set L to any set of axis perpendicular to the sample\n      vct3 a = vctCrossProduct(z, sampleNorms.at(k));\n      if (a.Norm() > 0.001)\n      {\n        noiseL.at(k).Column(0) = a.NormalizedSelf();\n        noiseL.at(k).Column(1) = vctCrossProduct(a, sampleNorms.at(k)).Normalized();\n      }\n      else\n      {\n        noiseL.at(k).Column(0) = vct3(1.0, 0.0, 0.0);\n        noiseL.at(k).Column(1) = vct3(0.0, 1.0, 0.0);\n      }\n    }\n    else\n    {\n      noisySampleNorms.at(k) = sampleNorms.at(k);\n      noiseL.at(k) = vct3x2(0.0);\n    }\n  }\n  randSeqPos = cisstRandomSeq.GetSequencePosition();\n\n  // save noisy samples\n  if (SavePath_NoisySamples)\n  {\n    std::string noisySampsSavePath = *SavePath_NoisySamples;\n    if (cisstPointCloud::WritePointCloudToFile(noisySampsSavePath, noisySamples, noisySampleNorms) < 0)\n    {\n      std::cout << \"ERROR: Samples save failed\" << std::endl;\n      assert(0);\n    }\n  }\n  // save cov\n  if (SavePath_Cov)\n  {\n    WriteToFile_Cov(sampleCov, *SavePath_Cov);\n  }\n  // save L\n  if (savePath_L)\n  {\n    WriteToFile_L(noiseL, *savePath_L);\n  }\n}\n\n#if 0   // TODO: code needs to be updated for changes to library\n\n// Generate noise having different variance perpendicular to its mesh\n//  triangle than noise in-plane\nvoid GenerateNoisyMesh(cisstMesh &mesh,\n  cisstMesh &noisyMesh,\n  std::ifstream &randnStream,\n  //unsigned int randSeed, unsigned int &randSeqPos\n  double noiseStdDev,\n  std::string *SavePath_NoisyMesh)\n{\n  ////initialize random numbers\n  //cmnRandomSequence &cisstRandomSeq = cmnRandomSequence::GetInstance();\n  //cisstRandomSeq.SetSeed( randSeed );\n  //cisstRandomSeq.SetSequencePosition( 0 );\n\n  unsigned int numTriangles = mesh.NumTriangles();\n  unsigned int numVertices = mesh.NumVertices();\n\n  noisyMesh.faces.SetSize(numTriangles);\n  noisyMesh.vertices.SetSize(numVertices);\n  noisyMesh.TriangleCov.SetSize(numTriangles);\n  noisyMesh.TriangleCovEig.SetSize(numTriangles);\n\n  // add isotropic random noise to the mesh vertices\n  for (unsigned int k = 0; k < numVertices; k++)\n  {\n    //=== generate noisy vertices ===//\n\n    // Generate an isotropic Gaussian noise scaled by the noise standard deviation\n    double p1, p2, p3;\n    //p1 = GenerateGaussianRV(cisstRandomSeq);\n    //p2 = GenerateGaussianRV(cisstRandomSeq);\n    //p3 = GenerateGaussianRV(cisstRandomSeq);\n    p1 = ExtractGaussianRVFromStream(randnStream);\n    p2 = ExtractGaussianRVFromStream(randnStream);\n    p3 = ExtractGaussianRVFromStream(randnStream);\n    vct3 p(p1, p2, p3);\n    p.Multiply(noiseStdDev);\n\n    // Assign noisy vertex to noisy mesh\n    noisyMesh.vertices.Element(k) = mesh.vertices.Element(k) + p;\n  }\n\n  // construct triangles for noisy mesh\n  cisstTriangle T(&noisyMesh);\n  for (unsigned int i = 0; i < numTriangles; i++)\n  {\n    // get triangle vertex indices from old mesh\n    int v0, v1, v2;\n    mesh.TriangleVertexIndexes(i, v0, v1, v2);\n    // copy indices to new triangle and compute normal vector\n    T.SetVertexIndexes(v0, v1, v2);\n    T.UpdatePlaneFromVertices();\n    // assign triangle to noisy mesh\n    noisyMesh.Triangles.Element(i) = T;\n  }\n\n  double var = noiseStdDev * noiseStdDev;\n  vct3x3 M(0.0);\n  M.Element(0, 0) = var;\n  M.Element(1, 1) = var;\n  M.Element(2, 2) = var;\n  noisyMesh.TriangleCov.SetAll(M);\n  noisyMesh.TriangleCovEig.SetAll(vct3(var));\n\n  //randSeqPos = cisstRandomSeq.GetSequencePosition();\n\n  // save noisy target mesh\n  if (SavePath_NoisyMesh)\n  {\n    if (noisyMesh.SaveMeshFile((*SavePath_NoisyMesh).append(\".mesh\")) < 0)\n    {\n      std::cout << \"ERROR: Save mesh failed\" << std::endl;\n      assert(0);\n    }\n  }\n}\n\n\n// Defines the measurement noise for each triangle in a mesh\n//  (not the measurement noise of samples, but of the mesh itself)\nvoid SetMeshTriangleCovariances(cisstMesh &mesh,\n  double stdDevPerpPlane, double stdDevInPlane)\n{\n  unsigned int numTriangles = mesh.NumTriangles();\n  vct3x3 M;\n  vct3 n;\n  vctRot3 R;\n  vct3 z(0.0, 0.0, 1.0);\n  double EigMax = stdDevPerpPlane > stdDevInPlane ? stdDevPerpPlane : stdDevInPlane;\n  EigMax = EigMax*EigMax;\n\n  // ensure normals have been computed for this mesh\n  if (mesh.Triangles[0].norm.NormSquare() < 0.1)\n  {\n    std::cout << \"ERROR: it appears normals were not computed for this mesh!\" << std::endl;\n    assert(0);\n  }\n\n  // initialize size of triangle covariances\n  mesh.TriangleCov.SetSize(numTriangles);\n  mesh.TriangleCovEig.SetSize(numTriangles);\n  mesh.TriangleCovEig.SetAll(vct3(EigMax));\n\n  // set eigenvalues of noise covariance\n  M.SetAll(0.0);\n  M.Element(0, 0) = stdDevInPlane*stdDevInPlane;\n  M.Element(1, 1) = stdDevInPlane*stdDevInPlane;\n  M.Element(2, 2) = stdDevPerpPlane*stdDevPerpPlane;     // z-axis chosen for perpendicular noise component\n\n  for (unsigned int i = 0; i < numTriangles; i++)\n  {\n    // get normal to triangle plane\n    n = mesh.Triangles[i].norm;\n\n    // find rotation to align triangle normal with the z-axis\n    vct3 xProd = vctCrossProduct(n, z);\n    if (xProd.Norm() <= 1e-6)  // protect from divide by zero\n    { // norm is already oriented with z-axis\n      R = vctRot3::Identity();\n    }\n    else\n    {\n      // the norm of the cross product is the same for angles of x deg & x+180 deg\n      //  between two vectors => use dot product to determine the angle\n      //   NOTE: the angle corresponding to the cross product axis is always > 0;\n      //         acos of the dot product gives the correct form\n      //   NOTE: the problem with using norm of cross product isn't that we aren't\n      //         going the right direction, but rather that we don't rotate far enough\n      //         if A & B are seperated by more than 90 degrees.  I.e. if angular\n      //         seperation between A & B is 100 degrees, then asin(norm(AxB)) gives\n      //         the same angle as if A & B are seperated by 80 degrees => we don't\n      //         know if the actual angle is X or 90+X using the norm of cross product.\n      vct3 ax = xProd.Normalized();\n      double an = acos(vctDotProduct(n, z));\n      //double an = asin(t.Norm());\n      vctAxAnRot3 R_AxAn(ax, an);\n      R = vctRot3(R_AxAn);\n    }\n\n    // set noise covariance of this triangle\n    //  rotate to align normal with perpendicular, apply noise covariance, rotate back\n    mesh.TriangleCov[i] = R.Transpose()*M*R;\n  }\n}\n#endif\n\n// TODO: enable\n#if 0\n\nvoid Callback_TrackRegPath_Utility( cisstICP::CallbackArg &arg, void *userData )\n{\n  // cast to norm callback arg type\n  cisstICP::CallbackArgNormals *argp;\n  argp = dynamic_cast<cisstICP::CallbackArgNormals*>(&arg);\n  if (argp==0)\n  {\n    std::cerr << \"ERROR: cannot cast callback argument to cisstICP type\" << std::endl;\n    assert(argp);   // terminate program\n  }\n\n  // Save to file:\n  //  - error function (-loglik)\n  //  - incremental transform\n  //  - IMLP params\n  //  - residual match errors\n  // output format:\n  //  err r00 r01 r02 r10 r11 r12 r20 r21 r22 tx ty tz normWeight posWeight avgNormError avgPosError \n  std::ofstream *fs = (std::ofstream *)(userData);\n  (*fs) << argp->E << \" \" << argp->dF.Rotation().Row(0) << \" \" << argp->dF.Rotation().Row(1) << \" \" \n    << argp->dF.Rotation().Row(2) << \" \" << argp->dF.Translation() << \" \" \n    << argp->normWeight << \" \" << argp->posWeight << \" \"\n    << argp->MatchPosErrorAvg << \" \" << argp->MatchPosErrorSD << \" \"\n    << argp->MatchNormErrorAvg << \" \" << argp->MatchNormErrorSD << std::endl;\n}\n\nvoid Callback_SaveIterationsToFile_Utility( cisstICP::CallbackArg &arg, void *userData )\n{\n  // cast to norm callback arg type\n  cisstICP::CallbackArgNormals *argp;\n  argp = dynamic_cast<cisstICP::CallbackArgNormals*>(&arg);\n  if (argp==0)\n  {\n    std::cerr << \"ERROR: cannot cast callback argument to cisstICP type\" << std::endl;\n    assert(argp);   // terminate program\n  }\n\n  std::ofstream *fs = (std::ofstream *)(userData);\n  vctRodRot3 dR(argp->dF.Rotation());\n  std::stringstream ss;\n  ss << cmnPrintf(\"iter=%u E=%.1f tolE=%.4f  (dAng/dPos)=%.2f/%.2f  t=%.3f  nW/pW=%.4f/%.4f  (circSD/posSD)=%.2f/%.2f  NNodes=%u/%u/%u NOut=%u/%u  PosErr=%.2f/%.2f  NormErr=%.2f/%.2f\")\n    //  dTheta=%.2f/%.2f/%.2f  \n    << argp->iter \n    << argp->E\n    << argp->tolE\n    << dR.Norm()*180.0/cmnPI << arg.dF.Translation().Norm()\n    << argp->time\n    << argp->normWeight << argp->posWeight\n    << argp->circSD*180.0/cmnPI << sqrt(argp->posVar)\n    //<< argp->dThetaMin*180.0/cmnPI << argp->dThetaMax*180.0/cmnPI << argp->dThetaAvg*180.0/cmnPI\n    << argp->maxNodesSearched << argp->avgNodesSearched << argp->minNodesSearched\n    << argp->nOutliersPos << argp->nOutliersNorm\n    << argp->MatchPosErrorAvg << argp->MatchPosErrorSD\n    << argp->MatchNormErrorAvg << argp->MatchNormErrorSD;\n  (*fs) << ss.str();\n  if (arg.isAccelStep)\n  {\n    (*fs) << \"\\t-- accel step --\";\n  }\n  (*fs) << std::endl;\n}\n#endif\n\n// compute rotation of minimal angle that aligns vectors a & b:  b = R*a\nvctRot3 XProdRotation(const vct3 &a, const vct3 &b)\n{\n  double EPS = 1.0e-6;\n\n  // Find rotation that aligns a to b\n  vct3 xProd = vctCrossProduct(a, b);\n  double dProd = vctDotProduct(a, b);\n  if (xProd.Norm() <= EPS)  // protect from divide by zero\n  { // vectors are either already aligned or pointing opposite\n    if (dProd > 0)\n    {\n      return vctRot3::Identity();\n    }\n    else\n    {\n      // need to rotate a by 180 degrees towards b\n      int dim = 0;\n      vct3 v = a;\n      while (true)\n      {\n        // find any vector perpendicular to a & b\n        v(dim) += 1.0;  // find a vector not parrallel to vector \"a\"\n        v.NormalizedSelf();\n        vct3 xProd2 = vctCrossProduct(a, v);\n        if (xProd2.Norm() > EPS)\n        {\n          vct3 ax = xProd2.Normalized();\n          vctAxAnRot3 R_AxAn(ax, cmnPI);\n          return vctRot3(R_AxAn);\n        }\n      }\n    }\n  }\n  else\n  {\n    // the norm of the cross product is the same for angles of x deg & x+180 deg\n    //  between two vectors => use dot product to determine the angle\n    //   NOTE: the angle corresponding to the cross product axis is always > 0;\n    //         acos of the dot product gives the correct form\n    //   NOTE: the problem with using norm of cross product isn't that we aren't\n    //         going the right direction, but rather that we don't rotate far enough\n    //         if A & B are seperated by more than 90 degrees.  I.e. if angular\n    //         seperation between A & B is 100 degrees, then asin(norm(AxB)) gives\n    //         the same angle as if A & B are seperated by 80 degrees => we don't\n    //         know if the actual angle is X or 90+X using the norm of cross product.\n    vct3 ax = xProd.Normalized();\n    double an = acos(vctDotProduct(a, b));\n    //double an = asin(t.Norm());\n    vctAxAnRot3 R_AxAn(ax, an);\n    return vctRot3(R_AxAn);\n  }\n}\n\n#if 0\nbool vct3HasValue(int x, vctFixedSizeVector<int, 3> vj)\n{\n  if (x == vj[0] || x == vj[1] || x == vj[2])\n    return true;\n  else \n    return false;\n}\n\nbool TrianglesAreNeighbors(vctFixedSizeVector<int, 3> vi, vctFixedSizeVector<int, 3> vj)\n{\n  // Two triangles are neighbors if any two vertices are\n  //  held in common\n\n  if (vct3HasValue(vi[0],vj))\n  { // vertex 0 in common\n    if (vct3HasValue(vi[1], vj))\n    { // vertex 0 & 1 in common\n      return true;\n    }\n    else if (vct3HasValue(vi[2], vj))\n    { // vertex 0 & 2 in common\n      return true;\n    }\n  }\n  else if (vct3HasValue(vi[1], vj))\n  { // vertex 1 in common\n    if (vct3HasValue(vi[2], vj))\n    { // vertex 1 & 2 in common\n      return true;\n    }\n  }\n  return false;\n}\n\n\ndouble ComputeAvgNeighborDistance(std::string meshFile)\n{\n  cisstMesh mesh;\n  mesh.LoadMeshFile(meshFile);\n  return ComputeAvgNeighborDistance(mesh);\n}\n\n// Compute average distance between neighboring triangle\n//  center-points in a mesh\ndouble ComputeAvgNeighborDistance( cisstMesh mesh )\n{\n  unsigned int numT = mesh.NumTriangles();\n  double distSum = 0.0;\n  unsigned int numNbrs = 0;\n\n  // compute distances to triangle neighbors\n  vctFixedSizeVector<int,3> vi,vj;  // vertex indices of triangles\n  for (unsigned int i = 0; i < numT; i++)\n  {\n    mesh.TriangleVertexIndexes(i, vi[0], vi[1], vi[2]);\n    unsigned int numLocalNbrs = 0;\n\n    // find neighbors of triangle i\n    for (unsigned int j = i + 1; j < numT; j++)\n    {\n      mesh.TriangleVertexIndexes(j, vj[0], vj[1], vj[2]);\n      if (TrianglesAreNeighbors(vi, vj))\n      {\n        numNbrs++;\n        distSum += (mesh.Triangles(i).Midpoint() - mesh.Triangles(j).Midpoint()).Norm();\n\n        numLocalNbrs++;\n        if (numLocalNbrs >= 3)\n          break;  // a triangle cannot have more than 3 neighbors\n      }\n    }\n  }\n\n  return distSum / (double)numNbrs;\n}\n#endif", "meta": {"hexsha": "f5e1c270ccce274088b1ae8c4b0883649d2eed92", "size": 59599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cisstICP/cisstICP_App/utility.cpp", "max_stars_repo_name": "sbillin/IMLP", "max_stars_repo_head_hexsha": "38cbf6f528747ab5421f02f50b9bc3cd416cff8c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:54:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T06:16:37.000Z", "max_issues_repo_path": "cisstICP/cisstICP_App/utility.cpp", "max_issues_repo_name": "sbillin/IMLP", "max_issues_repo_head_hexsha": "38cbf6f528747ab5421f02f50b9bc3cd416cff8c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-01-11T15:10:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-28T16:16:32.000Z", "max_forks_repo_path": "cisstICP/cisstICP_App/utility.cpp", "max_forks_repo_name": "sbillin/IMLP", "max_forks_repo_head_hexsha": "38cbf6f528747ab5421f02f50b9bc3cd416cff8c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T20:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-13T15:40:39.000Z", "avg_line_length": 34.1345933562, "max_line_length": 184, "alphanum_fraction": 0.6601620833, "num_tokens": 18460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091977351480805, "lm_q2_score": 0.019419347863228232, "lm_q1q2_score": 0.004484311410381935}}
{"text": "/**\n * Author:      H.F. Herbst\n * Origin:      Stellenbosch University\n * For:         IARPA SuperTools Project\n * license:     MIT\n * Description: Function definitions for new mesh file operations.\n */\n#include \"new_meshfile_operations.hpp\"\n#include <boost/algorithm/string.hpp>\n#include <iostream>\n#include <fstream>\n\nMSH::mesh_file::mesh_file()\n{\n}\n\nMSH::mesh_file::~mesh_file()\n{\n}\n\n// if 0  = success\n// if !0 = fail\nint MSH::check_read_state(std::fstream &infile)\n{\n    if (infile.bad())\n    {\n        std::cout << \"Error: Reached bad read state of msh file.\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    else\n        return EXIT_SUCCESS;\n    return EXIT_FAILURE;\n}\n\nMSH::line_type MSH::hash_line_type(std::string const& inString)\n{\n    if(inString == \"$MeshFormat\") return eMeshFormat;\n    if(inString == \"$PhysicalNames\") return ePhysicalNames;\n    if(inString == \"$Nodes\") return eNodes;\n    if(inString == \"$Elements\") return eElements;\n    return eDefault;\n}\n\nint MSH::mesh_file::import_meshfile(const std::string &import_path)\n{\n    std::fstream mesh_file;\n    std::string line_buffer;\n    mesh_file.open(import_path, std::ios::in);\n    if (mesh_file.is_open())\n    {\n        while (getline(mesh_file, line_buffer))\n        {\n            boost::erase_all(line_buffer, \"\\r\");\n            line_type hash_line = hash_line_type(line_buffer);\n            switch (hash_line)\n            {\n            case eMeshFormat:\n                if(scan_MeshFormat(mesh_file, line_buffer)) return EXIT_FAILURE;\n                break;\n            case ePhysicalNames:\n                if(scan_PhysicalNames(mesh_file, line_buffer)) return EXIT_FAILURE;\n                break;\n            case eNodes:\n                if(scan_Nodes(mesh_file, line_buffer)) return EXIT_FAILURE;\n                break;\n            case eElements:\n                if(scan_Elements(mesh_file, line_buffer)) return EXIT_FAILURE;\n                break;\n            default:\n                break;\n            }\n        }\n    }\n    mesh_file.close();\n    return EXIT_SUCCESS;\n}\nint MSH::mesh_file::scan_MeshFormat(std::fstream &mesh_file, std::string &line_buffer)\n{\n    getline(mesh_file, line_buffer);\n    boost::erase_all(line_buffer, \"\\r\");\n    if (check_read_state(mesh_file)) return EXIT_FAILURE;\n    if (line_buffer.compare(\"2.2 0 8\"))\n    {\n        std::cout << \"Error: Katana only supports Gmsh 2.2 0 8 format. Export file into old format.\";\n        return EXIT_FAILURE;\n    }\n    getline(mesh_file, line_buffer);\n    boost::erase_all(line_buffer, \"\\r\");\n    if (check_read_state(mesh_file)) return EXIT_FAILURE;\n    if (line_buffer.compare(\"$EndMeshFormat\"))\n    {\n        std::cout << \"Error: End of mesh format section was not found.\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n\nint MSH::mesh_file::scan_PhysicalNames(std::fstream &mesh_file, std::string &line_buffer)\n{\n    while (line_buffer!=\"$EndPhysicalNames\")\n    {\n        getline(mesh_file,line_buffer);\n        boost::erase_all(line_buffer, \"\\r\");\n        if (line_buffer==\"$EndPhysicalNames\")\n            break;\n        if ( check_read_state(mesh_file) )\n            return EXIT_FAILURE;\n        std::vector<std::string> split_str_vec;\n        boost::split(split_str_vec, line_buffer, boost::is_any_of(\"\\\"\"));\n        if (split_str_vec.size()>2)\n            physical_names_vect.push_back(split_str_vec[1]);\n\n    }\n    return EXIT_SUCCESS;\n}\n\nint MSH::mesh_file::scan_Nodes(std::fstream &mesh_file, std::string &line_buffer)\n{\n    while (line_buffer!=\"EndNodes\")\n    {\n        getline(mesh_file,line_buffer);\n        boost::erase_all(line_buffer, \"\\r\");\n        if (line_buffer==\"$EndNodes\")\n            break;\n        if (check_read_state(mesh_file))\n            return EXIT_FAILURE;\n        std::vector<std::string> split_str_vec;\n        boost::split(split_str_vec, line_buffer, boost::is_any_of(\" \"));\n        if (split_str_vec.size()==4)\n        {\n            node input_node;\n            input_node.x = std::stod(split_str_vec[1]);\n            input_node.y = std::stod(split_str_vec[2]);\n            input_node.z = std::stod(split_str_vec[3]);\n            nodes_map.insert({std::stoi(split_str_vec[0]),input_node});\n        }\n    }\n    return EXIT_SUCCESS;\n}\n\nint MSH::mesh_file::scan_Elements(std::fstream &mesh_file, std::string &line_buffer)\n{\n    while (line_buffer!=\"$EndElements\")\n    {\n        getline(mesh_file,line_buffer);\n        boost::erase_all(line_buffer, \"\\r\");\n        if (line_buffer==\"$EndElements\")\n            break;\n        if (check_read_state(mesh_file))\n            return EXIT_FAILURE;\n        std::vector<std::string> split_str_vec;\n        boost::split(split_str_vec, line_buffer, boost::is_any_of(\" \"));\n        auto element_size = split_str_vec.size();\n        if (element_size>5)\n        {\n            element input_ele;\n            int counter = 0;\n            int index = std::stoi(split_str_vec[counter++]);\n            input_ele.type = std::stoi(split_str_vec[counter++]);\n            int tag_count = std::stoi(split_str_vec[counter++]);\n            auto first_end = counter+tag_count;\n            for (auto i = counter; i < first_end; i++)\n            {\n                input_ele.tags.push_back(std::stoi(split_str_vec[counter]));\n                counter++;\n            }\n            for (auto j = counter; j < element_size; j++)\n            {\n                input_ele.node_vect.push_back(std::stoi(split_str_vec[j]));\n            }\n            elements_map.insert({index, input_ele});\n        }\n    }\n    return EXIT_SUCCESS;\n}\n\nint MSH::mesh_file::print_volumes()\n{\n    if(physical_names_vect.size()!=0)\n    {\n        std::vector<double> volumes_vect;\n        auto pnv_end = physical_names_vect.end();\n        for (auto i = physical_names_vect.begin(); i != pnv_end; i++)\n        {\n            volumes_vect.push_back(0);\n        }\n        auto elmap_end = elements_map.end();\n        for (auto i = elements_map.begin(); i != elmap_end; i++)\n        {\n            if(i->second.type==4)\n            {\n                if (i->second.node_vect.size()==4)\n                {\n                    double tet_vol = vol_tetrahedron( nodes_map[i->second.node_vect[0]],\n                                                    nodes_map[i->second.node_vect[1]],\n                                                    nodes_map[i->second.node_vect[2]],\n                                                    nodes_map[i->second.node_vect[3]] );\n                    int location = i->second.tags[1]-1;\n                    volumes_vect[location] = volumes_vect[location] + tet_vol;\n                }\n                else\n                {\n                    std::cout << \"Error: Tetrahedron specified but not enough points.\" << std::endl;\n                    return EXIT_FAILURE;\n                }\n            }\n        }\n        std::cout << \"Volumes in mesh file units:\" << std::endl;\n        int counter = 0;\n        for (auto i = physical_names_vect.begin(); i != pnv_end; i++)\n        {\n            std::cout << *i << \" = \" << volumes_vect[counter++] << std::endl;\n        }\n        return EXIT_SUCCESS;\n    }\n    else\n    {\n        std::cout << \"No physical names detected.\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    return EXIT_FAILURE;\n}\n\nvoid MSH::cross_product(const node &U, const node &V, node &out)\n{\n    out.x = U.y * V.z - V.y * U.z;\n    out.y = V.x * U.z - U.x * V.z;\n    out.z = U.x * V.y - V.x * U.y;\n}\n\ndouble MSH::dot_product(const node &U, const node &V)\n{\n    double output = U.x * V.x + U.y * V.y + U.z * V.z;\n    return output;\n}\n\ndouble MSH::vol_tetrahedron(const node &a, const node &b, const node &c, const node &d)\n{\n    node a_minus_d, b_minus_d, c_minus_d;\n    a_minus_d.x = a.x - d.x;\n    a_minus_d.y = a.y - d.y;\n    a_minus_d.z = a.z - d.z;\n    b_minus_d.x = b.x - d.x;\n    b_minus_d.y = b.y - d.y;\n    b_minus_d.z = b.z - d.z;\n    c_minus_d.x = c.x - d.x;\n    c_minus_d.y = c.y - d.y;\n    c_minus_d.z = c.z - d.z;\n    node b_minus_d_X_c_minus_d;\n    cross_product(b_minus_d,c_minus_d, b_minus_d_X_c_minus_d);\n    double volume = std::abs(dot_product(a_minus_d,b_minus_d_X_c_minus_d))/6;\n    return volume;\n}", "meta": {"hexsha": "16ffa5b43d3219c06d7c722b30e6a9b670dcab0f", "size": 8153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "katana_backend/src/new_meshfile_operations.cpp", "max_stars_repo_name": "RustyCircuitry/Katana", "max_stars_repo_head_hexsha": "571ba27dbffcacd62b4dab425bc490c1d36f776b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-31T09:31:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T04:26:57.000Z", "max_issues_repo_path": "katana_backend/src/new_meshfile_operations.cpp", "max_issues_repo_name": "RustyCircuitry/Katana", "max_issues_repo_head_hexsha": "571ba27dbffcacd62b4dab425bc490c1d36f776b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-08T22:38:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T03:26:39.000Z", "max_forks_repo_path": "katana_backend/src/new_meshfile_operations.cpp", "max_forks_repo_name": "HeinrichHerbst/Katana", "max_forks_repo_head_hexsha": "571ba27dbffcacd62b4dab425bc490c1d36f776b", "max_forks_repo_licenses": ["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.2252964427, "max_line_length": 101, "alphanum_fraction": 0.5697289341, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238002855971873, "lm_q2_score": 0.02716923035412042, "lm_q1q2_score": 0.004411740400847651}}
{"text": "#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <Eigen/Dense>\n#include <math.h>\n#include<fstream>\n#include<vector>\n\nusing namespace std;\nusing namespace Eigen;\n\nMainWindow::MainWindow(QWidget *parent)\n    : QMainWindow(parent)\n    , ui(new Ui::MainWindow)\n{\n    ui->setupUi(this);\n\n}\n\nMainWindow::~MainWindow()\n{\n    delete ui;\n}\n\n\nvoid MainWindow::on_actionNew_triggered()\n{\n    currentFile.clear();\n\n    //https://stackoverflow.com/questions/8678684/access-the-widget-of-a-tab-in-a-qtabwidget\n    QTextEdit* pTextEdit = NULL;\n    QWidget* pWidget= ui->tab_text; // for the second tab\n    // You can use metaobject to get widget type or qobject_cast\n    if (pWidget->metaObject()->className() == \"QTextEdit\")\n        pTextEdit = (QTextEdit*)pWidget;\n    else\n    {\n        QList<QTextEdit *> allTextEdits = pWidget->findChildren<QTextEdit *>();\n        if (allTextEdits.count() != 1)\n        {\n            QMessageBox::warning(this, \"Warning\", \"shit's on fire\");\n            return;\n        }\n        pTextEdit = allTextEdits[0];\n    }\n\n    // Do whatever you want with it...\n    pTextEdit->setText(QString());\n}\n\nvoid MainWindow::on_actionOpen_triggered()\n{\n\n    // Opens a dialog that allows you to select a file to open\n    QString fileName = QFileDialog::getOpenFileName(this, \"Open the file\");\n\n    // An object for reading and writing files\n    QFile file(fileName);\n\n    // Store the currentFile name\n    currentFile = fileName;\n\n    // Try to open the file as a read only file if possible or display a\n    // warning dialog box\n    if (!file.open(QIODevice::ReadOnly | QFile::Text)) {\n        QMessageBox::warning(this, \"Warning\", \"Cannot open file: \" + file.errorString());\n        return;\n    }\n\n    // Set the title for the window to the file name\n    setWindowTitle(fileName);\n\n    // Interface for reading text\n    QTextStream in(&file);\n\n    // Copy text in the string\n    QString text = in.readAll();\n\n    // Put the text in the textEdit widget\n    ui->textEdit->setText(text);\n\n    // Close the file\n    file.close();\n\n}\n\nvoid MainWindow::on_actionSave_text_triggered()\n{\n    // Opens a dialog for saving a file\n    QString fileName = QFileDialog::getSaveFileName(this, \"Save as\");\n\n    // An object for reading and writing files\n    QFile file(fileName);\n\n    // Try to open a file with write only options\n    if (!file.open(QFile::WriteOnly | QFile::Text)) {\n        QMessageBox::warning(this, \"Warning\", \"Cannot save file: \" + file.errorString());\n        return;\n    }\n\n    // Store the currentFile name\n    currentFile = fileName;\n\n    // Set the title for the window to the file name\n    setWindowTitle(fileName);\n\n    // Interface for writing text\n    QTextStream out(&file);\n\n    // Copy text in the textEdit widget and convert to plain text\n    QString text = ui->textEdit->toPlainText();\n\n    // Output to file\n    out << text;\n\n    // Close the file\n    file.close();\n}\n\nvoid MainWindow::on_actionSave_text_2_triggered()\n{\n    //QString fileName = QFileDialog::getSaveFileName(this, \"Save\");\n    if(currentFile==\"\"){\n        currentFile=\"temp.csv\";\n    }\n    QString  fileName = currentFile;\n\n    QFile file(fileName);\n    if (!file.open(QFile::WriteOnly | QFile::Text)) {\n        QMessageBox::warning(this, \"Warning\", \"Cannot save file: \" + file.errorString());\n        return;\n    }\n    currentFile = fileName;\n    setWindowTitle(fileName);\n    QTextStream out(&file);\n    QString text = ui->textEdit->toPlainText();\n    out << text;\n    file.close();\n}\n\nvoid MainWindow::on_actionExit_triggered()\n{\n    QApplication::quit();\n}\n\nvoid MainWindow::on_actionCopy_triggered()\n{\n    ui->textEdit->copy();\n}\n\nvoid MainWindow::on_actionCut_triggered()\n{\n    ui->textEdit->cut();\n}\n\nvoid MainWindow::on_actionPaste_triggered()\n{\n    ui->textEdit->paste();\n}\n\nvoid MainWindow::on_actionUndo_triggered()\n{\n    ui->textEdit->undo();\n}\n\nvoid MainWindow::on_actionRedo_triggered()\n{\n    ui->textEdit->redo();\n}\n\nvoid MainWindow::on_actionPlot_current_data_triggered()\n{\n    //##################################################################\n    if(currentFile==\"\"){\n        currentFile=\"temp.csv\";\n    }\n    QString  fileName = currentFile;\n\n    QFile file(fileName);\n    if (!file.open(QFile::WriteOnly | QFile::Text)) {\n        QMessageBox::warning(this, \"Warning\", \"Cannot save file: \" + file.errorString());\n        return;\n    }\n\n    setWindowTitle(fileName);\n    QTextStream out(&file);\n    QString text = ui->textEdit->toPlainText();\n    out << text;\n    file.close();\n\n    if (file.size()==0) {\n        QMessageBox::warning(this, \"Warning\", \"Cannot plot empty file\");\n        return;\n    }\n\n    MatrixXd matrix;// matrix to be loaded from a file\n    vector<double> matrixEntries;// load the matrix from the file\n    ifstream matrixDataFile(currentFile.toStdString());// in this object we store the data from the matrix\n    string matrixRowString;// this variable is used to store the row of the matrix that contains commas\n    string matrixEntry;// this variable is used to store the matrix entry;\n    int matrixRowNumber = 0;// this variable is used to track the number of rows\n\n    //##################################################################\n    try {\n        while (getline(matrixDataFile, matrixRowString)) // here we read a row by row of matrixDataFile and store every line into the string variable matrixRowString\n        {\n            stringstream matrixRowStringStream(matrixRowString); //convert matrixRowString that is a string to a stream variable.\n\n            while (getline(matrixRowStringStream, matrixEntry, ',')) // here we read pieces of the stream matrixRowStringStream until every comma, and store the resulting character into the matrixEntry\n            {\n                matrixEntries.push_back(stod(matrixEntry));   //here we convert the string to double and fill in the row vector storing all the matrix entries\n            }\n            matrixRowNumber++; //update the column numbers\n        }\n\n        matrix = Map<Matrix<double, Dynamic, Dynamic, RowMajor>>(matrixEntries.data(), matrixRowNumber, matrixEntries.size() / matrixRowNumber);\n\n    } catch (const std::invalid_argument e) {\n        QMessageBox::warning(this, \"Warning\", \"Cannot plot file, try editing it in Editor tab for compatible format\");\n        return;\n    }\n\n    //##################################################################\n    int xColumn = ui->xAxis->value();\n    int yColumn = ui->yAxis->value();\n    VectorXd xValues, yValues;\n    int columns = int(matrixEntries.size() / matrixRowNumber);\n\n    try {\n        if(xColumn < columns && yColumn < columns) {\n            xValues = matrix.col(xColumn);\n            yValues = matrix.col(yColumn);\n        } else {\n            throw string(\"Matrix out of bonds\");\n        }\n    } catch (string &e) {\n        QMessageBox::warning(this, \"Warning\", \"Chosen column is out of bonds for the current data\");\n        return;\n    }\n\n    // convert the Eigen objects into the std::vector form\n    // .data() returns the pointer to the first memory location of the first entry of the stored object\n    // https://eigen.tuxfamily.org/dox/group__TopicStorageOrders.html\n    std::vector<double> xValuesStdVector(xValues.data(), xValues.data() + xValues.rows() * xValues.cols());\n    std::vector<double> yValuesStdVector(yValues.data(), yValues.data() + yValues.rows() * yValues.cols());\n\n    //convert the std::vector objects to the Qt QVector form\n    QVector<double> xValuesQVector = QVector<double>::fromStdVector(xValuesStdVector);\n    QVector<double> yValuesQVector = QVector<double>::fromStdVector(yValuesStdVector);\n\n    // this is necessary for seting the axes limits\n    double x_maxValue=xValues.maxCoeff();\n    double x_minValue=xValues.minCoeff();\n\n    // this is necessary for seting the axes limits\n    double y_maxValue=yValues.maxCoeff();\n    double y_minValue=yValues.minCoeff();\n\n    customPlot=ui->widgetGraph;\n    // create graph and assign data to it:\n    customPlot->addGraph();\n    customPlot->addGraph();\n    customPlot->graph(0)->setData(xValuesQVector, yValuesQVector);\n    customPlot->graph(1)->setData(xValuesQVector, yValuesQVector);\n\n    QPen pen0;\n    pen0.setColor(datacolor);\n    if(ui->checkBox_graphconnect->isChecked()){\n        switch(ui->comboBox_data->currentIndex()){\n        case 0:\n            pen0.setStyle(Qt::SolidLine);\n            break;\n        case 1:\n            pen0.setStyle(Qt::DashLine);\n            break;\n        case 3:\n            pen0.setStyle(Qt::DotLine);\n            break;\n        case 4:\n            pen0.setStyle(Qt::DashDotLine);\n            break;\n        case 5:\n            pen0.setStyle(Qt::DashDotDotLine);\n            break;\n        }\n    } else {\n        pen0.setStyle(Qt::NoPen);\n    }\n    pen0.setWidthF(ui->spinBox_datawidth->value());\n    customPlot->graph(0)->setPen(pen0);\n\n    customPlot->graph(1)->setPen(datacolor);\n    customPlot->graph(1)->setLineStyle(QCPGraph::lsNone);\n    customPlot->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, ui->spinBox_pointswidth->value()));\n\n    //##################################################################\n    //https://www.bragitoff.com/2015/09/c-program-to-linear-fit-the-data-using-least-squares-method/\n    double a,b;\n    if(ui->checkBox_regression->isChecked()) {\n        int i, n;\n        n = xValuesStdVector.size();\n\n\n        VectorXd x;\n        x.setLinSpaced(1000,x_minValue,x_maxValue);\n        std::vector<double> xn(x.data(), x.data() + x.rows() * x.cols());\n\n        double xsum=0,x2sum=0,ysum=0,xysum=0;                //variables for sums/sigma of xi,yi,xi^2,xiyi etc\n        for (i=0;i<n;i++)\n        {\n            xsum=xsum+xValuesQVector[i];                        //calculate sigma(xi)\n            ysum=ysum+yValuesQVector[i];                        //calculate sigma(yi)\n            x2sum=x2sum+pow(xValuesQVector[i],2);                //calculate sigma(x^2i)\n            xysum=xysum+xValuesQVector[i]*yValuesQVector[i];                    //calculate sigma(xi*yi)\n        }\n\n        a=(n*xysum-xsum*ysum)/(n*x2sum-xsum*xsum);            //calculate slope\n        b=(x2sum*ysum-xsum*xysum)/(x2sum*n-xsum*xsum);            //calculate intercept\n\n        vector<double> y_fit(1000);                        //an array to store the new fitted values of y\n        i=0;\n        for (auto& elem : y_fit)\n        {\n            elem = a*xn[i]+b;\n            i++;\n        }\n\n        reg_fit_calc = true;\n\n        QVector<double> xnw = QVector<double>::fromStdVector(xn);\n        QVector<double> ynw = QVector<double>::fromStdVector(y_fit);\n        customPlot->addGraph();\n        QPen pen0;\n        pen0.setColor(regcolor);\n        switch(ui->comboBox_reg->currentIndex()){\n        case 0:\n            pen0.setStyle(Qt::SolidLine);\n            break;\n        case 1:\n            pen0.setStyle(Qt::DashLine);\n            break;\n        case 3:\n            pen0.setStyle(Qt::DotLine);\n            break;\n        case 4:\n            pen0.setStyle(Qt::DashDotLine);\n            break;\n        case 5:\n            pen0.setStyle(Qt::DashDotDotLine);\n            break;\n        }\n        pen0.setWidthF(ui->spinBox_regwidth->value());\n        customPlot->graph(2)->setPen(pen0);\n        customPlot->graph(2)->setData(xnw, ynw);\n\n    }\n\n    //##################################################################\n    customPlot->rescaleAxes();\n    // set the title\n    customPlot->xAxis2->setVisible(true);\n    customPlot->xAxis2->setLabel(ui->lineEdit_title->text());\n    // give the axes some labels:\n    customPlot->xAxis->setLabel(ui->lineEdit_xaxis->text());\n    customPlot->yAxis->setLabel(ui->lineEdit_yaxis->text());\n    // set axes ranges, so we see all data:\n    customPlot->xAxis->setRange(x_minValue-0.1*abs(x_minValue), x_maxValue+0.1*abs(x_maxValue));\n    customPlot->yAxis->setRange(y_minValue-0.1*abs(y_minValue), y_maxValue+0.1*abs(y_maxValue));\n    // set legend\n    if(ui->checkBox_legend->isChecked()){\n        if(reg_fit_calc==true) {\n            char buffer[100];\n            string s = ui->lineEdit_xaxis->text().toStdString();\n            char c[s.size() + 1];\n            strcpy(c, s.c_str());\n\n            string s2 = ui->lineEdit_yaxis->text().toStdString();\n            char c2[s2.size() + 1];\n            strcpy(c2, s2.c_str());\n\n            std::snprintf(buffer, sizeof(buffer), \"%s = %.3f * %s + (%.3f)\", c2, a, c, b);\n            customPlot->xAxis2->setLabel(buffer);\n        } else {\n            QMessageBox::warning(this, \"Warning\", \"Cannot set regression equation as title without enabling regression fit\");\n        }\n    }\n\n    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);\n    customPlot->replot();\n    first_plot = true;\n    reg_fit_calc = false;\n}\n\nvoid MainWindow::on_pushButton_clicked()\n{\n    QColor color = QColorDialog::getColor(Qt::blue, this, \"Choose color\");\n    if(color.isValid()){\n        datacolor = color;\n    }\n}\n\nvoid MainWindow::on_pushButton_2_clicked()\n{\n    QColor color = QColorDialog::getColor(Qt::red, this, \"Choose color\");\n    if(color.isValid()){\n        regcolor = color;\n    }\n}\n\n\nvoid MainWindow::on_actionSave_current_plot_to_file_triggered()\n{\n    // Opens a dialog for saving a file\n    QString fileName = QFileDialog::getSaveFileName(this, \"Save as\");\n\n    QFile file(fileName);\n\n    if (!file.open(QFile::WriteOnly)) {\n        QMessageBox::warning(this, \"Warning\", \"Cannot save plot: \" + file.errorString());\n        return;\n    } else {\n        if(first_plot==false) {\n            QMessageBox::warning(this, \"Warning\", \"Cannot save empty plot\");\n            return;\n        } else {\n            customPlot->savePng(fileName);\n        }\n    }\n}\n", "meta": {"hexsha": "e18cee9e7445a3924f70217989a12042f58f86d7", "size": 13689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mainwindow.cpp", "max_stars_repo_name": "Jarartur/cppRegressor", "max_stars_repo_head_hexsha": "ed9a3918e388e1324788c595faa2cf01f6a35e2f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T13:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T12:54:59.000Z", "max_issues_repo_path": "mainwindow.cpp", "max_issues_repo_name": "Jarartur/cppRegressor", "max_issues_repo_head_hexsha": "ed9a3918e388e1324788c595faa2cf01f6a35e2f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-21T21:07:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T21:08:31.000Z", "max_forks_repo_path": "mainwindow.cpp", "max_forks_repo_name": "Jarartur/cppRegressor", "max_forks_repo_head_hexsha": "ed9a3918e388e1324788c595faa2cf01f6a35e2f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9090909091, "max_line_length": 201, "alphanum_fraction": 0.6090291475, "num_tokens": 3238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706247, "lm_q2_score": 0.020023443592090268, "lm_q1q2_score": 0.004351845593130586}}
{"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// Nonrecursive implementation of depth_first_visit_impl submitted by\n// Bruce Barr, schmoost <at> yahoo.com, May/June 2003.\n//\n// (C) Copyright Bruce Barr, 2003\n// Permission to copy, use, modify, sell and distribute this software\n// is granted provided this copyright notice appears in all copies.\n// This software is provided \"as is\" without express or implied\n// warranty, and with no claim as to its suitability for any purpose.\n\n\n\n#ifndef BOOST_GRAPH_RECURSIVE_DFS_HPP\n#define BOOST_GRAPH_RECURSIVE_DFS_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/visitors.hpp>\n#include <boost/graph/named_function_params.hpp>\n\n#include <boost/ref.hpp>\n#include <boost/implicit_cast.hpp>\n\n#include <vector>\n#include <utility>\n\nnamespace boost {\n\n  template <class Visitor, class Graph>\n  class DFSVisitorConcept {\n  public:\n    void constraints() {\n      function_requires< CopyConstructibleConcept<Visitor> >();\n      vis.initialize_vertex(u, g);\n      vis.start_vertex(u, g);\n      vis.discover_vertex(u, g);\n      vis.examine_edge(e, g);\n      vis.tree_edge(e, g);\n      vis.back_edge(e, g);\n      vis.forward_or_cross_edge(e, g);\n      vis.finish_vertex(u, g);\n    }\n  private:\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  namespace detail {\n\n    struct nontruth2 {\n      template<class T, class T2>\n      bool operator()(const T&, const T2&) const { return false; }\n    };\n\n\n// Define BOOST_RECURSIVE_DFS to use older, recursive version.\n// It is retained for a while in order to perform performance\n// comparison.\n#ifndef BOOST_RECURSIVE_DFS\n\n    // If the vertex u and the iterators ei and ei_end are thought of as the\n    // context of the algorithm, each push and pop from the stack could\n    // be thought of as a context shift.\n    // Each pass through \"while (ei != ei_end)\" may refer to the out-edges of\n    // an entirely different vertex, because the context of the algorithm\n    // shifts every time a white adjacent vertex is discovered.\n    // The corresponding context shift back from the adjacent vertex occurs\n    // after all of its out-edges have been examined.\n    //\n    // See http://lists.boost.org/MailArchives/boost/msg48752.php for FAQ.\n\n    template <class IncidenceGraph, class DFSVisitor, class ColorMap,\n            class TerminatorFunc>\n    void depth_first_visit_impl\n      (const IncidenceGraph& g,\n       typename graph_traits<IncidenceGraph>::vertex_descriptor u,\n       DFSVisitor& vis,\n       ColorMap color, TerminatorFunc func = TerminatorFunc())\n    {\n      function_requires<IncidenceGraphConcept<IncidenceGraph> >();\n      function_requires<DFSVisitorConcept<DFSVisitor, IncidenceGraph> >();\n      typedef typename graph_traits<IncidenceGraph>::vertex_descriptor Vertex;\n      function_requires< ReadWritePropertyMapConcept<ColorMap, Vertex> >();\n      typedef typename property_traits<ColorMap>::value_type ColorValue;\n      function_requires< ColorValueConcept<ColorValue> >();\n      typedef color_traits<ColorValue> Color;\n      typedef typename graph_traits<IncidenceGraph>::out_edge_iterator Iter;\n      typedef std::pair<Vertex, std::pair<Iter, Iter> > VertexInfo;\n\n      Iter ei, ei_end;\n      std::vector<VertexInfo> stack;\n\n      // Possible optimization for vector\n      //stack.reserve(num_vertices(g));\n\n      typedef typename unwrap_reference<TerminatorFunc>::type TF;\n\n      put(color, u, Color::gray());\n      vis.discover_vertex(u, g);\n      tie(ei, ei_end) = out_edges(u, g);\n      // Variable is needed to workaround a borland bug.\n      TF& fn = static_cast<TF&>(func);\n      if (fn(u, g)) {\n          // If this vertex terminates the search, we push empty range\n          stack.push_back(std::make_pair(u, std::make_pair(ei_end, ei_end)));\n      } else {\n          stack.push_back(std::make_pair(u, std::make_pair(ei, ei_end)));\n      }\n      while (!stack.empty()) {\n        VertexInfo& back = stack.back();\n        u = back.first;\n        tie(ei, ei_end) = back.second;\n        stack.pop_back();\n        while (ei != ei_end) {\n          Vertex v = target(*ei, g);\n          vis.examine_edge(*ei, g);\n          ColorValue v_color = get(color, v);\n          if (v_color == Color::white()) {\n            vis.tree_edge(*ei, g);\n            stack.push_back(std::make_pair(u, std::make_pair(++ei, ei_end)));\n            u = v;\n            put(color, u, Color::gray());\n            vis.discover_vertex(u, g);\n            tie(ei, ei_end) = out_edges(u, g);\n            if (fn(u, g)) {\n                ei = ei_end;\n            }\n          } else if (v_color == Color::gray()) {\n            vis.back_edge(*ei, g);\n            ++ei;\n          } else {\n            vis.forward_or_cross_edge(*ei, g);\n            ++ei;\n          }\n        }\n        put(color, u, Color::black());\n        vis.finish_vertex(u, g);\n      }\n    }\n\n#else // BOOST_RECURSIVE_DFS is defined\n\n    template <class IncidenceGraph, class DFSVisitor, class ColorMap,\n              class TerminatorFunc>\n    void depth_first_visit_impl\n      (const IncidenceGraph& g,\n       typename graph_traits<IncidenceGraph>::vertex_descriptor u,\n       DFSVisitor& vis,  // pass-by-reference here, important!\n       ColorMap color, TerminatorFunc func)\n    {\n      function_requires<IncidenceGraphConcept<IncidenceGraph> >();\n      function_requires<DFSVisitorConcept<DFSVisitor, IncidenceGraph> >();\n      typedef typename graph_traits<IncidenceGraph>::vertex_descriptor Vertex;\n      function_requires< ReadWritePropertyMapConcept<ColorMap, Vertex> >();\n      typedef typename property_traits<ColorMap>::value_type ColorValue;\n      function_requires< ColorValueConcept<ColorValue> >();\n      typedef color_traits<ColorValue> Color;\n      typename graph_traits<IncidenceGraph>::out_edge_iterator ei, ei_end;\n\n      put(color, u, Color::gray());          vis.discover_vertex(u, g);\n\n      typedef typename unwrap_reference<TerminatorFunc>::type TF;\n      // Variable is needed to workaround a borland bug.\n      TF& fn = static_cast<TF&>(func);\n      if (!fn(u, g))\n        for (tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {\n          Vertex v = target(*ei, g);           vis.examine_edge(*ei, g);\n          ColorValue v_color = get(color, v);\n          if (v_color == Color::white()) {     vis.tree_edge(*ei, g);\n          depth_first_visit_impl(g, v, vis, color, func);\n          } else if (v_color == Color::gray()) vis.back_edge(*ei, g);\n          else                                 vis.forward_or_cross_edge(*ei, g);\n        }\n      put(color, u, Color::black());         vis.finish_vertex(u, g);\n    }\n\n#endif\n\n  } // namespace detail\n\n  template <class VertexListGraph, class DFSVisitor, class ColorMap>\n  void\n  depth_first_search(const VertexListGraph& g, DFSVisitor vis, ColorMap color,\n                     typename graph_traits<VertexListGraph>::vertex_descriptor start_vertex)\n  {\n    typedef typename graph_traits<VertexListGraph>::vertex_descriptor Vertex;\n    function_requires<DFSVisitorConcept<DFSVisitor, VertexListGraph> >();\n    typedef typename property_traits<ColorMap>::value_type ColorValue;\n    typedef color_traits<ColorValue> Color;\n\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());       vis.initialize_vertex(*ui, g);\n    }\n\n    if (start_vertex != implicit_cast<Vertex>(*vertices(g).first)){ vis.start_vertex(start_vertex, g);\n      detail::depth_first_visit_impl(g, start_vertex, vis, color,\n                                     detail::nontruth2());\n    }\n\n    for (tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui) {\n      ColorValue u_color = get(color, *ui);\n      if (u_color == Color::white()) {       vis.start_vertex(*ui, g);\n        detail::depth_first_visit_impl(g, *ui, vis, color, detail::nontruth2());\n      }\n    }\n  }\n\n  template <class VertexListGraph, class DFSVisitor, class ColorMap>\n  void\n  depth_first_search(const VertexListGraph& g, DFSVisitor vis, ColorMap color)\n  {\n    depth_first_search(g, vis, color, *vertices(g).first);\n  }\n\n  namespace detail {\n    template <class ColorMap>\n    struct dfs_dispatch {\n\n      template <class VertexListGraph, class Vertex, class DFSVisitor,\n                class P, class T, class R>\n      static void\n      apply(const VertexListGraph& g, DFSVisitor vis, Vertex start_vertex,\n            const bgl_named_params<P, T, R>&,\n            ColorMap color)\n      {\n        depth_first_search(g, vis, color, start_vertex);\n      }\n    };\n\n    template <>\n    struct dfs_dispatch<detail::error_property_not_found> {\n      template <class VertexListGraph, class Vertex, class DFSVisitor,\n                class P, class T, class R>\n      static void\n      apply(const VertexListGraph& g, DFSVisitor vis, Vertex start_vertex,\n            const bgl_named_params<P, T, R>& params,\n            detail::error_property_not_found)\n      {\n        std::vector<default_color_type> color_vec(num_vertices(g));\n        default_color_type c = white_color; // avoid warning about un-init\n        depth_first_search\n          (g, vis, make_iterator_property_map\n           (color_vec.begin(),\n            choose_const_pmap(get_param(params, vertex_index),\n                              g, vertex_index), c),\n           start_vertex);\n      }\n    };\n  } // namespace detail\n\n\n  template <class Visitors = null_visitor>\n  class dfs_visitor {\n  public:\n    dfs_visitor() { }\n    dfs_visitor(Visitors vis) : m_vis(vis) { }\n\n    template <class Vertex, class Graph>\n    void initialize_vertex(Vertex u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_initialize_vertex());\n    }\n    template <class Vertex, class Graph>\n    void start_vertex(Vertex u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_start_vertex());\n    }\n    template <class Vertex, class Graph>\n    void discover_vertex(Vertex u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_discover_vertex());\n    }\n    template <class Edge, class Graph>\n    void examine_edge(Edge u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_examine_edge());\n    }\n    template <class Edge, class Graph>\n    void tree_edge(Edge u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_tree_edge());\n    }\n    template <class Edge, class Graph>\n    void back_edge(Edge u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_back_edge());\n    }\n    template <class Edge, class Graph>\n    void forward_or_cross_edge(Edge u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_forward_or_cross_edge());\n    }\n    template <class Vertex, class Graph>\n    void finish_vertex(Vertex u, const Graph& g) {\n      invoke_visitors(m_vis, u, g, ::boost::on_finish_vertex());\n    }\n\n    BOOST_GRAPH_EVENT_STUB(on_initialize_vertex,dfs)\n    BOOST_GRAPH_EVENT_STUB(on_start_vertex,dfs)\n    BOOST_GRAPH_EVENT_STUB(on_discover_vertex,dfs)\n    BOOST_GRAPH_EVENT_STUB(on_examine_edge,dfs)\n    BOOST_GRAPH_EVENT_STUB(on_tree_edge,dfs)\n    BOOST_GRAPH_EVENT_STUB(on_back_edge,dfs)\n    BOOST_GRAPH_EVENT_STUB(on_forward_or_cross_edge,dfs)\n    BOOST_GRAPH_EVENT_STUB(on_finish_vertex,dfs)\n\n  protected:\n    Visitors m_vis;\n  };\n  template <class Visitors>\n  dfs_visitor<Visitors>\n  make_dfs_visitor(Visitors vis) {\n    return dfs_visitor<Visitors>(vis);\n  }\n  typedef dfs_visitor<> default_dfs_visitor;\n\n\n  // Named Parameter Variant\n  template <class VertexListGraph, class P, class T, class R>\n  void\n  depth_first_search(const VertexListGraph& g,\n                     const bgl_named_params<P, T, R>& params)\n  {\n    typedef typename property_value< bgl_named_params<P, T, R>,\n      vertex_color_t>::type C;\n    detail::dfs_dispatch<C>::apply\n      (g,\n       choose_param(get_param(params, graph_visitor),\n                    make_dfs_visitor(null_visitor())),\n       choose_param(get_param(params, root_vertex_t()),\n                    *vertices(g).first),\n       params,\n       get_param(params, vertex_color)\n       );\n  }\n\n  template <class IncidenceGraph, class DFSVisitor, class ColorMap>\n  void depth_first_visit\n    (const IncidenceGraph& g,\n     typename graph_traits<IncidenceGraph>::vertex_descriptor u,\n     DFSVisitor vis, ColorMap color)\n  {\n    vis.start_vertex(u, g);\n    detail::depth_first_visit_impl(g, u, vis, color, detail::nontruth2());\n  }\n\n  template <class IncidenceGraph, class DFSVisitor, class ColorMap,\n            class TerminatorFunc>\n  void depth_first_visit\n    (const IncidenceGraph& g,\n     typename graph_traits<IncidenceGraph>::vertex_descriptor u,\n     DFSVisitor vis, ColorMap color, TerminatorFunc func = TerminatorFunc())\n  {\n    vis.start_vertex(u, g);\n    detail::depth_first_visit_impl(g, u, vis, color, func);\n  }\n\n\n} // namespace boost\n\n\n#endif\n", "meta": {"hexsha": "440cc1ba1e6c45f233a85611a694f52ddcd51a9c", "size": 14233, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/depth_first_search.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/graph/depth_first_search.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/graph/depth_first_search.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": 36.7777777778, "max_line_length": 102, "alphanum_fraction": 0.659453383, "num_tokens": 3360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11124120945399738, "lm_q2_score": 0.03904829090900819, "lm_q1q2_score": 0.004343779107829601}}
{"text": "/*\n  Author(s):      Matthew Celnik (msc37)\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2008 Matthew S Celnik.\n\n  File purpose:\n    Implementation of the Ensemble class declared in the\n    swp_ensemble.h header file.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser 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 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_ensemble.h\"\n#include \"swp_particle_model.h\"\n#include \"swp_kmc_simulator.h\"\n#include \"swp_PAH_primary.h\"\n#include \"swp_kmc_pah_structure.h\"\n#include \"swp_kmc_structure_comp.h\"\n#include \"swp_kmc_typedef.h\"\n#include \"swp_kmc_pah_process.h\"\n\n#include <cmath>\n#include <vector>\n#include <stdexcept>\n#include <cassert>\n#include <limits>\n#include <functional>\n#include <algorithm>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n\nusing namespace Sweep;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor.\nSweep::Ensemble::Ensemble(void)\n{\n\tm_kmcsimulator= NULL;\n    init();\n}\n\n// Initialising constructor.\nSweep::Ensemble::Ensemble(unsigned int count)\n: m_tree(count)\n{\n    // Call initialisation routine.\n    //If there are no particles, do not initialise binary tree\n    //Instead, initialise the ensemble to zero and skip the binary tree\n    if (count ==0)\n        init();\n\n    else\n    //Initialise binary tree, which also initialises the ensemble\n        Initialise(count);\n}\n\n// Copy contructor.\nSweep::Ensemble::Ensemble(const Sweep::Ensemble &copy)\n:m_tree(copy.m_tree)\n{\n    // Use assignment operator.\n    *this = copy;\n}\n\n// Stream-reading constructor.\nSweep::Ensemble::Ensemble(std::istream &in, const Sweep::ParticleModel &model)\n{\n    Deserialize(in, model);\n}\n\n// Destructor.\nSweep::Ensemble::~Ensemble(void)\n{\n\tdelete     m_kmcsimulator;\n    // Clear the ensemble.\n    Clear();\n}\n\n\n// OPERATOR OVERLOADING.\n\n// Assignment operator.\nEnsemble & Sweep::Ensemble::operator=(const Sweep::Ensemble &rhs)\n{\n    if (this != &rhs) {\n        // Clear current particles.\n        Clear();\n\n        if (rhs.m_capacity > 0) {\n            // Resize particle vector.\n            m_particles.resize(rhs.m_capacity, NULL);\n\n            // Capacity.\n            m_levels   = rhs.m_levels;\n            m_capacity = rhs.m_capacity;\n            m_halfcap  = rhs.m_halfcap;\n            m_count    = rhs.m_count;\n            //m_numofInceptedPAH = rhs.m_numofInceptedPAH;\n            // Scaling.\n            m_ncont      = rhs.m_ncont;\n            m_contfactor = rhs.m_contfactor;\n            m_contwarn   = rhs.m_contwarn;\n            m_wtdcontfctr = rhs.m_wtdcontfctr;\n            // Doubling.\n            m_maxcount   = rhs.m_maxcount;\n            m_ndble      = rhs.m_ndble;\n            m_dbleactive = rhs.m_dbleactive;\n            m_dblecutoff = rhs.m_dblecutoff;\n            m_dblelimit  = rhs.m_dblelimit;\n            m_dbleslack  = rhs.m_dbleslack;\n            m_dbleon     = rhs.m_dbleon;\n\n            // Copy particle vector.\n            for (unsigned int i=0; i!=rhs.Count(); ++i) {\n                m_particles[i] = rhs.m_particles[i]->Clone();\n            }\n\n\t\t\t// Copy any tracked particles\n\t\t\tm_tracked_number = rhs.m_tracked_number;\n\t\t\tm_tracked_particles.resize(rhs.m_tracked_number, NULL);\n\t\t\tfor (unsigned int i=0; i!=rhs.m_tracked_number; ++i) {\n                m_tracked_particles[i] = rhs.m_tracked_particles[i]->Clone();\n            }\n\n            // Hybrid particle-number/particle model variables\n            // ===============================================\n            m_hybrid_threshold = rhs.m_hybrid_threshold;\n            if (rhs.m_hybrid_threshold > 0)\n            {\n                m_pn_particles.resize(rhs.m_hybrid_threshold, NULL);\n                if (rhs.m_pn_particles[0] != NULL) \n                {\n                    for (unsigned int i = 0; i != rhs.GetHybridThreshold(); ++i) {\n                        m_pn_particles[i] = rhs.m_pn_particles[i]->Clone();\n                    }\n                }\n\n                m_particle_numbers.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_diameters.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_diameters2.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_diameters_1.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_diameters_2.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_diameters2_mass_1_2.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_mass_1_2.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_mass.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_mass2.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_mass3.resize(rhs.m_hybrid_threshold, 0);\n                m_pn_diameters3.resize(rhs.m_hybrid_threshold, 0);\n                m_hybrid_threshold = rhs.m_hybrid_threshold;\n\t\t\t\t\n                // Copy vectors.\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_particle_numbers[i] = rhs.m_particle_numbers[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_diameters[i] = rhs.m_pn_diameters[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_diameters2[i] = rhs.m_pn_diameters2[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_diameters_1[i] = rhs.m_pn_diameters_1[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_diameters_2[i] = rhs.m_pn_diameters_2[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_diameters2_mass_1_2[i] = rhs.m_pn_diameters2_mass_1_2[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_mass_1_2[i] = rhs.m_pn_mass_1_2[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_mass[i] = rhs.m_pn_mass[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_mass2[i] = rhs.m_pn_mass2[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_mass3[i] = rhs.m_pn_mass3[i];\n                }\n                for (unsigned int i = 0; i != rhs.m_hybrid_threshold; ++i) {\n                    m_pn_diameters3[i] = rhs.m_pn_diameters3[i];\n                }\n                m_total_number = rhs.m_total_number;\n                m_total_diameter = rhs.m_total_diameter;\n                m_total_diameter2 = rhs.m_total_diameter2;\n                m_total_diameter_1 = rhs.m_total_diameter_1;\n                m_total_diameter_2 = rhs.m_total_diameter_2;\n                m_total_diameter2_mass_1_2 = rhs.m_total_diameter2_mass_1_2;\n                m_total_mass_1_2 = rhs.m_total_mass_1_2;\n                m_total_mass = rhs.m_total_mass;\n                m_total_mass2 = rhs.m_total_mass2;\n                m_total_mass3 = rhs.m_total_mass3;\n                m_total_diameter3 = rhs.m_total_diameter3;\n                m_total_component = rhs.m_total_component;\n            }\n            // ===============================================\n\n            m_tree.resize(m_capacity);\n            rebuildTree();\n        }\n    }\n    return *this;\n}\n\n\n/*!\n * @param os    Output stream\n * @param net   Ensemble object to print\n * @return      Output stream\n */\nstd::ostream& Sweep::operator<<(\n        std::ostream &os,\n        const Sweep::Ensemble &e)\n{\n  os << \"[Ensemble],\";\n  os << \" nmax=\" << e.Capacity();\n  os << \" n(t)=\" << e.Count();\n  os << \"\\n\";\n  return os;\n}\n\n// INITIALISATION.\n\n/*!\n * @param[in]   capacity    New size of ensemble\n *\n * Any particles in the ensemble will be destroyed\n */\nvoid Sweep::Ensemble::Initialise(unsigned int capacity)\n{\n    // Clear current ensemble.\n    Clear();\n\n    //Check that there is no ensemble with zero capacity\n    if (capacity == 0)\n        throw std::invalid_argument(\"Cannot create a binary tree for an ensemble with zero capacity! (Sweep::Ensemble::Initialise)\");\n\n    // Calculate nearest power of 2 capacity.  Ensemble capacity must be a power\n    // of 2.  This constraint is due to the binary tree implementation.\n    double rl    = log((double)capacity) / log(2.0);\n    m_levels   = static_cast<int>(rl + 0.5);\n\n    // Capacity is 2^levels, which is most efficiently calculated with a bit shift.\n    // Note that 1 has the binary representation (8 bits only for brevity) 00000001.\n    // The left shift used here moves bits left the specified numer of places,\n    // while filling the right hand places with 0.  Bits at the left hand end of\n    // the number are discarded when shifted out of the range of the data type.\n    // For example 5 << 3 or with 5 in binary notation 00000101 << 3 == 00101000 == 40 == 5 * 2^3.\n    // In particular 1 << n == 2^n.\n    m_capacity = 1 << m_levels;\n\n    m_halfcap  = m_capacity / 2;\n\n    m_count    = 0;\n    //m_numofInceptedPAH = 0;\n\n    // Reserve memory for ensemble.\n    m_particles.resize(m_capacity, NULL);\n\n    m_tree.resize(m_capacity);\n\n    // Initialise scaling.\n    m_ncont      = 0;\n    m_wtdcontfctr= 1.0;\n    m_contfactor = (double)(m_capacity) / (double)(m_capacity+1);\n    m_contwarn   = false;\n\n    // Initialise doubling.\n    m_maxcount   = 0;\n    m_ndble      = 0;\n    m_dbleon     = true;\n    m_dbleactive = false;\n    //m_dblecutoff = (int)(3.0 * (double)m_capacity / 4.0 / 4.0);\n\tm_dblecutoff = (int)(3.0 * (double)m_capacity / 4.0 );\n\t//m_dblecutoff = m_capacity+10;\n\n\tm_dbleslack = (unsigned int)pow(2.0, (int)((m_levels - 5)>0 ? m_levels - 5 : 0));\n\t//m_dbleslack = (int) m_capacity*0.075;\n\t//m_dbleslack = m_dbleslack / 4.0;\n\t//m_dblelimit = m_halfcap/4.0 - m_dbleslack;\n\tm_dblelimit = m_halfcap - m_dbleslack;\n\n\tm_tracked_number = 0;\n    // ===============================================\n    m_total_number = 0;\n    m_total_diameter = 0.0;\n    m_total_diameter2 = 0.0;\n    m_total_diameter_1 = 0.0;\n    m_total_diameter_2 = 0.0;\n    m_total_diameter2_mass_1_2 = 0.0;\n    m_total_mass_1_2 = 0.0;\n    m_total_mass = 0.0;\n    m_total_mass2 = 0.0;\n    m_total_mass3 = 0.0;\n    m_total_diameter3 = 0.0;\n    m_total_component = 0;\n    m_particle_numbers.resize(m_hybrid_threshold, 0);\n    m_pn_diameters.resize(m_hybrid_threshold, 0);\n    m_pn_diameters2.resize(m_hybrid_threshold, 0);\n    m_pn_diameters_1.resize(m_hybrid_threshold, 0);\n    m_pn_diameters_2.resize(m_hybrid_threshold, 0);\n    m_pn_diameters2_mass_1_2.resize(m_hybrid_threshold, 0);\n    m_pn_mass_1_2.resize(m_hybrid_threshold, 0);\n    m_pn_mass.resize(m_hybrid_threshold, 0);\n    m_pn_mass2.resize(m_hybrid_threshold, 0);\n    m_pn_mass3.resize(m_hybrid_threshold, 0);\n    m_pn_diameters3.resize(m_hybrid_threshold, 0);\n    m_pn_particles.resize(m_hybrid_threshold, NULL);\n    // ===============================================\n}\n\n/*!\n * Turn on (true) or off (false) doubling.\n *\n * @param val   Switch for doubling.\n */\nvoid Sweep::Ensemble::SetDoubling(const bool val) {\n    m_dbleon = val;\n}\n\nunsigned int Sweep::Ensemble::DoubleLimit() {\n\treturn m_dblelimit;\n}\n\nbool Sweep::Ensemble::IsDoublingOn() {\n\treturn m_dbleactive;\n}\n\n/**\n * Initialise the ensemble to hold particles of the type specified\n * by the model and containing the particular particles contained\n * in the range [first, last).  This is equivalent to multiple applications\n * of Add on an Ensemble instance after a call to Initialise(m_capacity).\n *\n *@param[in]        first      Iterator to first in range of particle pointers to insert\n *@param[in]        last       Iterator to one past end of range of particle pointers to insert\n *@param[in,out]    rng        Random number generator\n */\nvoid Sweep::Ensemble::SetParticles(std::list<Particle*>::iterator first, std::list<Particle*>::iterator last,\n                                   rng_type &rng)\n{\n    // Clear any existing particles\n    for(iterator it = m_particles.begin(); it != m_particles.end(); ++it) {\n        delete *it;\n    }\n    m_particles.assign(m_capacity, NULL);\n\n    unsigned count = 0;\n    // Read up to m_capacity particles straight into the array\n    while((first != last) && (count < m_capacity)) {\n        m_particles[count++] = (*first++);\n    }\n\n    // Now we have to decide whether or not to accept particles\n    while(first != last) {\n        // Possible index in which to store this particle\n        boost::uniform_smallint<unsigned> indexGenerator(0, count);\n        const unsigned possibleIndex = indexGenerator(rng);\n\n        // Accept the index with probability m_capacity / count\n        if(possibleIndex < m_capacity) {\n            delete m_particles[possibleIndex];\n            m_particles[possibleIndex] = *first;\n        }\n        else {\n            delete *first;\n        }\n        ++count;\n        ++first;\n    }\n\n    if(count > m_capacity) {\n        // Some particles were thrown away and we must rescale\n        m_count = m_capacity;\n        m_ncont = 0;\n        m_wtdcontfctr = 1.0;\n\n        iterator it = begin();\n        const iterator itEnd = end();\n        while(it != itEnd) {\n            (*it)->setStatisticalWeight((*it)->getStatisticalWeight() * static_cast<double>(count) / static_cast<double>(m_capacity));\n            ++it;\n        }\n    }\n    else {\n        m_count = count;\n        m_ncont = 0;\n        m_wtdcontfctr = 1.0;\n    }\n    m_maxcount = m_count;\n\n    //std::cout << m_count << \" particles set on ensemble of capacity \" << m_capacity << '\\n';\n\n    // Initialise scaling.\n\n    m_contwarn   = false;\n\n    // Initialise doubling.\n    m_ndble      = 0;\n    m_dbleon     = true;\n\n    // Check for doubling activation.\n    if (!m_dbleactive && ((m_count + m_total_number) >= (m_dblecutoff-1))) {\n        m_dbleactive = true;\n    } else\n        m_dbleactive = false;\n\n    // Build the tree with the weights for the new particles.\n    rebuildTree();\n\n    assert(m_tree.size() == m_count);\n}\n\nSweep::KMC_ARS::KMCSimulator* Sweep::Ensemble::Simulator(void)\n{   \n\treturn m_kmcsimulator;\n}\n\nvoid Sweep::Ensemble::SetSimulator(Sweep::GasProfile& gp)\n{   \n    Sweep::KMC_ARS::KMCSimulator* kmc = new Sweep::KMC_ARS::KMCSimulator(gp);\n    m_kmcsimulator= kmc;\n    m_kmcsimulator->TestGP();\n}\n\n\n\n// PARTICLE ADDITION AND REMOVAL.\n\n// Returns a pointer to the particle with the given index.\nParticle *const Sweep::Ensemble::At(unsigned int i)\n{\n    // Check that the index in within range, then return the particle.\n    if (i < m_count) {\n        return m_particles[i];\n    } else {\n        return NULL;\n    }\n}\n\n// Returns a pointer to the particle with the given index.\nconst Particle *const Sweep::Ensemble::At(unsigned int i) const\n{\n    // Check that the index in within range, then return the particle.\n    if (i < m_count) {\n        return m_particles[i];\n    } else {\n        return NULL;\n    }\n}\n    \n// Get a specific particle out of the particle-number list using template array\nParticle *const Sweep::Ensemble::GetPNParticleAt(unsigned int index)\n{\n    // Check that the index in within range, then return the particle.\n    if (index < m_hybrid_threshold) {\n        return m_pn_particles[index];\n    }\n    else {\n        return NULL;\n    }\n}\n\n/*!\n * @param[in,out]   sp          Particle to add to the ensemble\n * @param[in,out]   rng         Random number generator\n *\n * @return      Index of added particle\n *\n * Particles must be heap allocated, because the ensemble takes the\n * address of sp and, by default, calls delete on the resulting pointer\n * when the particle is no longer needed.  It would probably make\n * sense to change the type of the first argument to Particle* to\n * reflect the fact that the ensemble mainly deals with the pointer.\n *\n */\nint Sweep::Ensemble::Add(Particle &sp, rng_type &rng, int i2, bool hybrid_event_flag)\n{\n    // Check for doubling activation.\n    if (!m_dbleactive && ((m_count + m_total_number) >= m_dblecutoff-1)) {\n        m_dbleactive = true;\n        printf(\"sweep: Particle doubling activated.\\n\");\n    }\n\n    // Check ensemble for space, if there is not enough space then need\n    // to generate some by contracting the ensemble.\n    int i = -1;\n    if (m_count < m_capacity) {\n        // There is space in the tree for a new particle.\n        i = -1;\n    } else {\n        // We must contract the ensemble to accommodate a new particle.\n        boost::uniform_smallint<int> indexDistrib(0, m_capacity);\n        boost::variate_generator<Sweep::rng_type&, boost::uniform_smallint<int> > indexGenerator(rng, indexDistrib);\n        i = indexGenerator();\n\t\t\n        // Check if adding a particle from the particle-number list during coagulation. \n        // In this case, we can't remove the last particle (index=m_capacity) or the\n        // paired coagulating particle (index=i2) as this would void the coagulation event.\n        if (hybrid_event_flag)\n        {\n            while (i == m_capacity || i == i2) \n                i = indexGenerator(); \n        }\n\n        // Account for particle weights in sample volume contraction\n        // (not as neat as using ncont but necessary if weighted or hybrid particles)\n        double wsp = sp.getStatisticalWeight();\n        double wi = wsp;\n        if (i < m_capacity)\n            wi = m_particles[i]->getStatisticalWeight();\n        double wtot = m_tree.head().Property(iW) + m_total_number;\n        m_wtdcontfctr *= (wtot + wsp - wi);\n        m_wtdcontfctr *= 1.0 / (wtot + wsp);\n\n        ++m_ncont;\n        if (!m_contwarn && ((double)(m_ncont)/(double)m_capacity > 0.01)) {\n            m_contwarn = true;\n            printf(\"sweep: Ensemble contracting too often; \"\n                   \"possible stiffness issue.\\n\");\n        }\n    }\n\n    if (i < 0) {\n        // We are adding a new particle.\n        i=m_count++;\n        m_particles[i] = &sp;\n        m_tree.push_back(tree_type::value_type(sp, m_particles.begin() + i));\n        //m_numofInceptedPAH++;\n\n\t\t//Add particle to tracked list if number of tracked particles is below the desired number\n\t\tif (m_tracked_particles.size() < m_tracked_number){\n\t\t\tm_tracked_particles.push_back(&sp);\n\t\t\tsp.setTracking(); //Initialise tracking\n\t\t}\n\n    } else if ((unsigned)i < m_capacity) {\n        // Replace an existing particle (if i=m_capacity) then\n        // we are removing the new particle, so just ignore it.\n\t\tReplace(i, sp);\n\n    } else {\n        // The new particle is to be removed immediately\n        assert(static_cast<unsigned int>(i) == m_capacity);\n        delete &sp;\n    }\n\n    m_maxcount = std::max(m_maxcount, m_count);\n\n    assert(m_tree.size() == m_count);\n\n    return i;\n}\n\n// Store template particle at a specific index\nint Sweep::Ensemble::SetPNParticle(Particle &sp, unsigned int index)\n{\n\tif (index < m_hybrid_threshold)\n\t{\n\t\tm_pn_particles[index] = &sp;\n\t\treturn 0;\n\t}\n\telse\n\t\treturn -1;\n}\n\nint Sweep::Ensemble::CheckforPAH(Sweep::KMC_ARS::PAHStructure &m_PAH, double t, int ind)\n{\n\titerator it1;\n\tint count = 0;\n\tfor (it1 = begin(); it1 != end(); it1++){\n\t\t//First, check if this particle is updated to the correct time\n\t\tif ((*it1)->LastUpdateTime() == t && count > ind){\n\t\t\tAggModels::PAHPrimary *pah =\n\t\t\t\tdynamic_cast<AggModels::PAHPrimary*>((*it1)->Primary());\n\t\t\t//Check if this particle contains a single primary with a single PAH with the same \n\t\t\t//amount of hydrogens and carbons\n\t\t\tif (pah->NumPAH() == 1){\n\t\t\t\tif (pah->NumCarbon() == m_PAH.numofC() && pah->NumHydrogen() == m_PAH.numofH() \n\t\t\t\t\t&& pah->NumRings() == m_PAH.numofRings()\n\t\t\t\t\t&& pah->NumLoneRings5() == m_PAH.numofLoneRings5()\n\t\t\t\t\t&& pah->NumEmbeddedRings5() == m_PAH.numofEmbeddedRings5()){\n\n\t\t\t\t\tstd::map<KMC_ARS::kmcSiteType, KMC_ARS::svector> sitemapInput = m_PAH.GetSiteMap();\n\t\t\t\t\tstd::map<KMC_ARS::kmcSiteType, KMC_ARS::svector> sitemapComp = (*(pah->GetPAHVector())[0]).GetPAHStruct()->GetSiteMap();\n\t\t\t\t\tif (sitemapInput[KMC_ARS::FE].size() == sitemapComp[KMC_ARS::FE].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::ZZ].size() == sitemapComp[KMC_ARS::ZZ].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::AC].size() == sitemapComp[KMC_ARS::AC].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::BY6].size() == sitemapComp[KMC_ARS::BY6].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::BY5].size() == sitemapComp[KMC_ARS::BY5].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::R5].size() == sitemapComp[KMC_ARS::R5].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::RFE].size() == sitemapComp[KMC_ARS::RFE].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::RZZ].size() == sitemapComp[KMC_ARS::RZZ].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::RAC].size() == sitemapComp[KMC_ARS::RAC].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::RBY5].size() == sitemapComp[KMC_ARS::RBY5].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::RFER].size() == sitemapComp[KMC_ARS::RFER].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::RZZR].size() == sitemapComp[KMC_ARS::RZZR].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::RACR].size() == sitemapComp[KMC_ARS::RACR].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::FE3].size() == sitemapComp[KMC_ARS::FE3].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::FE2].size() == sitemapComp[KMC_ARS::FE2].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::AC_FE3].size() == sitemapComp[KMC_ARS::AC_FE3].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::BY5_FE3].size() == sitemapComp[KMC_ARS::BY5_FE3].size() &&\n\t\t\t\t\t\tsitemapInput[KMC_ARS::FE_HACA].size() == sitemapComp[KMC_ARS::FE_HACA].size()){\n\t\t\t\t\t\treturn count;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcount++;\n\t}\n\treturn -1;\n}\n\n/*!\n * @param[in]   i       Index of particle to remove\n * @param[in]   fdel    True if delete should be called on removed particle\n *\n * Calls to remove may invalidate some or all iterators and indices\n * referring to particles in the ensemble.\n */\nvoid Sweep::Ensemble::Remove(unsigned int i, bool fdel)\n{\n    //if (m_particles[i]->Primary()->AggID() ==AggModels::PAH_KMC_ID)\n    //    {\n    //        const Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n    //        rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(m_particles[i]->Primary());\n    //        if (rhsparticle->Pyrene()!=0)\n    //        {\n    //            --m_numofInceptedPAH;\n    //        }\n    //    }\n    //SetNumOfInceptedPAH(-1,m_particles[i]->Primary());\n\n\t// See if IWDSA is being used. If so, do not attempt doubling at the end of this routine.\n\tbool doubling = true;\n\tif (m_particles[i]->Primary()->AggID() == AggModels::PAH_KMC_ID){\n\t\tif (m_particles[i]->Primary()->ParticleModel()->Components(0)->WeightedPAHs()){\n\t\t\tdoubling = false;\n\t\t}\n\t}\n\t\n\t//Set tracked pointer to null\n\tif (m_tracked_number > 0){\n\t\tfor (unsigned int ii = 0; ii < m_tracked_particles.size(); ++ii){\n\t\t\tif (m_tracked_particles[ii] == m_particles[i]) m_tracked_particles[ii] = NULL;\n\t\t}\n\t}\n\n\t// Check that particle index is valid.\n    if (i<m_count-1) {\n        // First delete particle from memory, then\n        // overwrite it with the last particle, which\n        // is subsequently removed from the vector.\n        if (fdel) delete m_particles[i];\n        --m_count;\n        m_particles[i] = m_particles[m_count];\n        m_particles[m_count] = NULL;\n\n        // Iterator to the particle that is being removed\n        iterator itPart = m_particles.begin() + i;\n        m_tree.replace(m_tree.begin() + i, tree_type::value_type(**itPart, itPart));\n        m_tree.pop_back();\n\n    } else if (i==m_count-1) {\n        // This is the last particle in the ensemble, we don't\n        // need to swap it with another, just delete it.\n\n        // Erase particle.\n        if (fdel) delete m_particles[i];\n        m_particles[i] = NULL;\n        --m_count;\n\n        m_tree.pop_back();\n    }\n\n    // Particle removal might reduce the particle count\n    // sufficiently to require particle doubling.\n\t// But only do so if not using IWDSA as otherwise ensemble is likely to overflow during next LPDA\n\tif(doubling) dble();\n\n    assert(m_tree.size() == m_count);\n}\n\n// Removes invalid particles from the ensemble.\nvoid Sweep::Ensemble::RemoveInvalids(void)\n{\n    // This function loops forward through the list finding invalid\n    // particles and backwards finding valid particles.  Once an invalid\n    // and a valid particle are found they are swapped.  This results in\n    // all the invalid particles being collected at the end of the vector,\n    // from where they can be deleted.\n\n    // Rearrange the particle list in m_particles so that all the valid particles\n    // are in the range [m_particles.begin(), validEnd) and all the invalid\n    // particles are in the range [validEnd, m_particles.end()).\n    iterator validEnd = std::partition(m_particles.begin(),\n                                       m_particles.begin() + m_count,\n                                       std::mem_fun(&Particle::IsValid));\n\n    // Update the number of particles in the tree\n    m_count = validEnd - m_particles.begin();\n\n    // Now delete the invalid particles and nullify the corresponding pointers\n    while(validEnd != m_particles.end()) {\n\t\t//Set tracked pointer to null\n\t\tif (m_tracked_number > 0){\n\t\t\tfor (unsigned int ii = 0; ii < m_tracked_particles.size(); ++ii){\n\t\t\t\tif (m_tracked_particles[ii] == (*validEnd)) m_tracked_particles[ii] = NULL;\n\t\t\t}\n\t\t}\n\n\t\t// delete particle\n        delete *validEnd;\n        *validEnd = NULL;\n        ++validEnd;\n    }\n\n\n    // Rebuild the binary tree structure\n    rebuildTree();\n\n    // Stop doubling because the number of particles has dropped from above\n    // m_dblelimit during this function, which means a rapid loss of particles\n    // so doubling will make the sample volume needlessly large.\n    if((m_count + m_total_number) < m_capacity - m_dblecutoff) {\n        m_dbleactive = false;\n    }\n\n    // If we removed too many invalid particles then we'll have to double.\n    dble();\n    assert(m_tree.size() == m_count);\n}\n\n/*!\n * @param[in]       i       Index of particle to replace\n * @param[in,out]   sp      New particle to use\n *\n * Particles must be heap allocated, because the ensemble takes the\n * address of sp and, by default, calls delete on the resulting pointer\n * when the particle is no longer needed.  It would probably make\n * sense to change the type of the second argument to Particle* to\n * reflect the fact that the ensemble mainly deals with the pointer.\n *\n */\nvoid Sweep::Ensemble::Replace(unsigned int i, Particle &sp)\n{\n    // if (m_particles[i]->Primary()->AggID() ==AggModels::PAH_KMC_ID)\n    //{\n    //    const Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n    //    rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(m_particles[i]->Primary());\n    //    if (rhsparticle->Pyrene()!=0)\n    //    {\n    //        m_numofInceptedPAH--;\n    //        std::cout<<\"Warning: it removes a starting pah before adding a new one\"<<std::endl;\n    //    }\n    //    m_numofInceptedPAH++;\n    //}\n    //SetNumOfInceptedPAH(-1, m_particles[i]->Primary());\n    //SetNumOfInceptedPAH(1);\n    // Check index is within range.\n    if (i<m_count) {\n\t\t//If particle that is being replaced set tracked pointer to null\n\t\tif (m_tracked_number > 0){\n\t\t\tfor (unsigned int j = 0; j < m_tracked_particles.size(); j++){\n\t\t\t\tif (m_tracked_particles[j] == m_particles[i]) m_tracked_particles[j] = NULL;\n\t\t\t}\n\t\t}\n\n        // First delete current particle, then\n        // set pointer to new particle.\n        delete m_particles[i];\n        m_particles[i] = &sp;\n\n        m_tree.replace(m_tree.begin() + i, tree_type::value_type(sp, m_particles.begin() + i));\n    }\n    assert(m_tree.size() == m_count);\n}\n\n/*!\n *  Clears all particles from the ensemble, deleting them to release the\n *  memory and reseting all details of the ensemble except its capacity\n */\nvoid Sweep::Ensemble::Clear() {\n    ClearMain();\n}\n\n\n/*!\n *  Clears all main particles from the ensemble, deleting them to release the\n *  memory\n */\nvoid Sweep::Ensemble::ClearMain()\n{\n    // Delete particles from memory and delete vectors.\n    for (PartPtrVector::size_type i = 0; i != m_particles.size(); ++i) {\n        delete m_particles[i];\n        m_particles[i] = NULL;\n    }\n    m_count = 0;\n    //m_numofInceptedPAH = 0;\n\n    m_ncont = 0; // No contractions any more.\n    m_wtdcontfctr = 1.0;\n\n    m_tree.clear();\n\n    // Reset doubling.\n    m_maxcount   = 0;\n    m_ndble      = 0;\n    m_dbleactive = false;\n\n\t// clear tracked particles since particles have been deleted\n\tm_tracked_particles.clear();\n\n    // Hybrid particle-number/particle model variables\n    // ===============================================\n    m_total_number = 0;\n    m_total_component = 0;\n    m_total_diameter = 0.0;\n    m_total_diameter2 = 0.0;\n    m_total_diameter_1 = 0.0;\n    m_total_diameter_2 = 0.0;\n    m_total_diameter2_mass_1_2 = 0.0;\n    m_total_mass_1_2 = 0.0;\n    m_total_mass = 0.0;\n    m_total_mass2 = 0.0;\n    m_total_mass3 = 0.0;\n    m_total_diameter3 = 0.0;\n    for (PartPtrVector::size_type i = 0; i != m_pn_particles.size(); ++i) {\n        delete m_pn_particles[i];\n        m_pn_particles[i] = NULL;\n    }\n    // ===============================================\n}\n\n// SELECTING PARTICLES.\n\n/*!\n * @param[in,out]   rng    Random number generator\n *\n * @return      Index of a uniformly selected particle from the ensemble\n */\nint Sweep::Ensemble::Select(rng_type &rng) const\n{\n    assert(m_tree.size() == m_count);\n\n    // Set up the rng sample\n    boost::uniform_smallint<int> indexDistrib(0, m_count - 1);\n    boost::variate_generator<Sweep::rng_type&, boost::uniform_smallint<int> > indexGenerator(rng, indexDistrib);\n\n    // Take one sample and return it\n    return indexGenerator();\n}\n\n\n/*!\n * @param[in]       id     Property by which to weight particle selection\n * @param[in,out]   rng    Random number generator\n *\n * @return      Index of selected particle\n *\n * id must refer to a basic property from the ParticleData class\n */\nint Sweep::Ensemble::Select(Sweep::PropID id, rng_type &rng) const\n{\n    assert(m_tree.size() == m_count);\n\n    // This routine uses the binary tree to select a particle weighted\n    // by a given particle property (by index).\n\n    // Do not try to use the tree for uniform selection\n    if(id == Sweep::iUniform)\n        return Select(rng);\n\n    // Calculate random number weighted by sum of desired property (wtid).\n    // Set up the rng sample\n    boost::uniform_01<rng_type&, double> unifDistrib(rng);\n    double r = unifDistrib() * m_tree.head().Property(id);\n\n    WeightExtractor we(id);\n    assert(abs((m_tree.head().Property(id) - we(m_tree.head()))/m_tree.head().Property(id)) < 1e-9);\n    tree_type::const_iterator it2 = m_tree.select(r, we);\n\n    return (it2 - m_tree.begin());\n}\n\n// For hybrid particle method:\n// use previously selected random number multiplied by\n// overall sum, less the bin sum, instead of newly generated one\n/*!\n* @param[in]       id     Property by which to weight particle selection\n* @param[in,out]   rng    Random number generator\n*\n* @return      Index of selected particle\n*\n* id must refer to a basic property from the ParticleData class\n*/\nint Sweep::Ensemble::Select_usingGivenRand(Sweep::PropID id, double rng_number, rng_type &rng) const\n{\n    assert(m_tree.size() == m_count);\n\n    // This routine uses the binary tree to select a particle weighted\n    // by a given particle property (by index).\n\n    // Do not try to use the tree for uniform selection\n    if (id == Sweep::iUniform)\n        return Select(rng);\n\n    double r = rng_number;\n\n    WeightExtractor we(id);\n    assert(abs((m_tree.head().Property(id) - we(m_tree.head())) / m_tree.head().Property(id)) < 1e-9);\n    tree_type::const_iterator it2 = m_tree.select(r, we);\n    \n    return (it2 - m_tree.begin());\n}\n\n// SCALING AND PARTICLE DOUBLING.\n\n// Returns the scaling factor due to internal ensemble processes.\ndouble Sweep::Ensemble::Scaling() const\n{\n    // The scaling factor includes the contraction term and the doubling term.\n    // For weighted particles, the contraction factor should also depend\n    // on the weight of the removed particle otherwise number density not conserved. \n\tif (m_hybrid_threshold > 0)\n\t\treturn m_wtdcontfctr * pow(2.0, (double)m_ndble);\n\telse\n\t\treturn pow(m_contfactor, (double)m_ncont) * pow(2.0,(double)m_ndble);\n}\n\n// Resets the ensemble scaling.\nvoid Sweep::Ensemble::ResetScaling()\n{\n    m_ncont = 0;\n    m_wtdcontfctr = 1.0;\n    m_ndble = 0;\n    m_contwarn = false;\n}\n\n\n// GET SUMS OF PROPERTIES.\n\n// Returns a ParticleData object which contains property\n// sums for all particles in the ensemble.\nconst Sweep::Ensemble::particle_cache_type & Sweep::Ensemble::GetSums(void) const\n{\n    return m_tree.head();\n}\n\n// Returns the sum of a property in the ParticleData class\n// over all particles.\ndouble Sweep::Ensemble::GetSum(Sweep::PropID id) const\n{\n    if(id != Sweep::iUniform)\n        return m_tree.head().Property(id);\n    else\n        return m_count;\n}\n\n/*!\n * Returns the fitting factor 'alpha' for the particle ensemble. Reference is\n * Appel, J. et al (2000) Combustion & Flame 121, 122-136, also known as the\n * ABF soot model.\n *\n *  alpha = tanh(a/log10{mu1} + b)\n *\n *  a = 12.65 - 0.00563 * T\n *  b = -1.38 + 0.00068 * T\n *  mu1 = average number of C atoms per particle\n *\n * Note that mu1 is called the 'reduced first size moment' and is usually the\n * average mass of particles in the ensemble; however in the referenced\n * version the mass is represented by the number of carbon atoms per particle.\n * See Frenklach & Wang (1994) in Soot Formation in Combustion: Mechanisms\n * and Models pp 165.\n *\n * Here the average mass is first estimated using the Tree Cache, then the\n * number of C atoms using the the molecular weight of carbon (hard-coded).\n * Could automatically get MW through something like:\n * m_particles[0]->Primary()->ParticleModel()->Components()[0]->MolWt()\n *\n * @param[in]   T   Local temperature\n *\n * @return          Alpha for the ensemble (ABF model)\n */\ndouble Sweep::Ensemble::Alpha(double T) const {\n    double alpha(0.0), mu1(0.0);\n\n    // Get mu1 (average mass per particle)\n    // Use the cache for MUCH faster calculation.\n    double mW = Count()>0 ? GetSum(iWM) : 0.0;\n    double invTotalWeight = Count()>0 ? 1.0/GetSum(iW) : 0.0;\n    mu1 = mW * invTotalWeight * Sweep::NA / 0.01201;    // Mw in kg/mol\n\n    // Now find alpha\n    if (mu1 > 0.0) {\n        double a = 12.65 - 0.00563 * T;\n        double b = -1.38 + 0.00068 * T;\n        alpha = std::max(0.0, tanh((a / log10(mu1)) + b));\n    }\n\n    return alpha;\n}\n\n\n// Hybrid particle-number/particle model functions\n// ===============================================\n\n// Update functions\nvoid Sweep::Ensemble::UpdateNumberAtIndex(unsigned int index, int update)\n{\n    m_particle_numbers[index] += update;\n}\nvoid Sweep::Ensemble::UpdateTotalsWithIndex(unsigned int index, double change)\n{\n    m_total_diameter += change * m_pn_diameters[index];\n    m_total_diameter2 += change * m_pn_diameters2[index];\n    m_total_diameter_1 += change * m_pn_diameters_1[index];\n    m_total_diameter_2 += change * m_pn_diameters_2[index];\n    m_total_diameter2_mass_1_2 += change * m_pn_diameters2_mass_1_2[index];\n    m_total_mass_1_2 += change * m_pn_mass_1_2[index];\n    m_total_mass += change * m_pn_mass[index];\n    m_total_mass2 += change * m_pn_mass2[index];\n    m_total_mass3 += change * m_pn_mass3[index];\n    m_total_diameter3 += change * m_pn_diameters3[index];\n    m_total_component += change * index;\n}\nvoid Sweep::Ensemble::UpdateTotalsWithIndices(unsigned int i1, unsigned int i2)\n{\n    m_total_diameter += m_particle_numbers[i1] * (m_pn_diameters[i2] - m_pn_diameters[i1]);\n    m_total_diameter2 += m_particle_numbers[i1] * (m_pn_diameters2[i2] - m_pn_diameters2[i1]);\n    m_total_diameter_1 += m_particle_numbers[i1] * (m_pn_diameters_1[i2] - m_pn_diameters_1[i1]);\n    m_total_diameter_2 += m_particle_numbers[i1] * (m_pn_diameters_2[i2] - m_pn_diameters_2[i1]);\n    m_total_diameter2_mass_1_2 += m_particle_numbers[i1] * (m_pn_diameters2_mass_1_2[i2] - m_pn_diameters2_mass_1_2[i1]);\n    m_total_mass_1_2 += m_particle_numbers[i1] * (m_pn_mass_1_2[i2] - m_pn_mass_1_2[i1]);\n    m_total_mass += m_particle_numbers[i1] * (m_pn_mass[i2] - m_pn_mass[i1]);\n    m_total_mass2 += m_particle_numbers[i1] * (m_pn_mass2[i2] - m_pn_mass2[i1]);\n    m_total_mass3 += m_particle_numbers[i1] * (m_pn_mass3[i2] - m_pn_mass3[i1]);\n    m_total_diameter3 += m_particle_numbers[i1] * (m_pn_diameters3[i2] - m_pn_diameters3[i1]);\n    m_total_component += m_particle_numbers[i1] * (i2 - i1);\n}\n\n// For doubling algorithm\nvoid Sweep::Ensemble::DoubleTotals()\n{\n    m_total_diameter *= 2.0;\n    m_total_diameter2 *= 2.0;\n    m_total_diameter_1 *= 2.0;\n    m_total_diameter_2 *= 2.0;\n    m_total_diameter2_mass_1_2 *= 2.0;\n    m_total_mass_1_2 *= 2.0;\n    m_total_mass *= 2.0;\n    m_total_mass2 *= 2.0;\n    m_total_mass3 *= 2.0;\n    m_total_diameter3 *= 2.0;\n    m_total_component *= 2;\n    m_total_number *= 2;\n}\n\n// Functions to get parameters\ndouble Sweep::Ensemble::GetTotalDiameter() const { \n    if (m_total_number > 0)\n        return m_total_diameter;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalDiameter2() const {\n    if (m_total_number > 0)\n        return m_total_diameter2;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalDiameter_1() const {\n    if (m_total_number > 0)\n        return m_total_diameter_1;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalDiameter_2() const {\n    if (m_total_number > 0)\n        return m_total_diameter_2;\n    else\n    return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalDiameter3() const {\n    if (m_total_number > 0)\n        return m_total_diameter3;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalDiameter2_mass_1_2() const {\n    if (m_total_number > 0)\n        return m_total_diameter2_mass_1_2;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalMass_1_2() const {\n    if (m_total_number > 0)\n        return m_total_mass_1_2;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalMass() const {\n    if (m_total_number > 0)\n        return m_total_mass;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalMass2() const {\n    if (m_total_number > 0)\n        return m_total_mass2;\n    else\n        return 0.0;\n}\ndouble Sweep::Ensemble::GetTotalMass3() const {\n    if (m_total_number > 0)\n        return m_total_mass3;\n    else\n        return 0.0;\n}\nunsigned int Sweep::Ensemble::GetTotalComponent() const {\n    if (m_total_number > 0)\n        return m_total_component;\n    else\n        return 0;\n}\nunsigned int Sweep::Ensemble::NumberAtIndex(unsigned int index) const { \n    if (m_total_number > 0)\n        return m_particle_numbers[index];\n    else\n        return 0;\n}\ndouble Sweep::Ensemble::PropertyAtIndex(Sweep::PropID prop, unsigned int index) const\n{\n    double return_val;\n    switch (prop) {\n        case iDcol:\n            return_val = m_pn_diameters[index];\n            break;\n        case iDW:\n            return_val = m_pn_diameters[index];\n            break;\n        case iD2:\n            return_val = m_pn_diameters2[index];\n            break;\n        case iD2W:\n            return_val = m_pn_diameters2[index];\n            break;\n        case iD_1:\n            return_val = m_pn_diameters_1[index];\n            break;\n        case iD_1W:\n            return_val = m_pn_diameters_1[index];\n            break;\n        case iD_2:\n            return_val = m_pn_diameters_2[index];\n            break;\n        case iD_2W:\n            return_val = m_pn_diameters_2[index];\n            break;\n        case iM_1_2:\n            return_val = m_pn_mass_1_2[index];\n            break;\n        case iM_1_2W:\n            return_val = m_pn_mass_1_2[index];\n            break;\n        case iD2_M_1_2:\n            return_val = m_pn_diameters2_mass_1_2[index];\n            break;\n        case iD2_M_1_2W:\n            return_val = m_pn_diameters2_mass_1_2[index];\n            break;\n        case iW:\n            return_val = m_particle_numbers[index];\n            break;\n        case iUniform:\n                return_val = 1.0;\n                break;\n        case iM:\n            return_val = m_pn_mass[index];\n            break;\n    }\n    return return_val;\n}\ndouble Sweep::Ensemble::GetPropertyTotal(Sweep::PropID prop) const\n{\n    double return_val = 0.0;\n    if (m_total_number > 0)\n    {\n        switch (prop) {\n            case iDcol:\n                return_val = m_total_diameter;\n                break;\n            case iDW:\n                return_val = m_total_diameter;\n                break;\n            case iD2:\n                return_val = m_total_diameter2;\n                break;\n            case iD2W:\n                return_val = m_total_diameter2;\n                break;\n            case iD_1:\n                return_val = m_total_diameter_1;\n                break;\n            case iD_1W:\n                return_val = m_total_diameter_1;\n                break;\n            case iD_2:\n                return_val = m_total_diameter_2;\n                break;\n            case iD_2W:\n                return_val = m_total_diameter_2;\n                break;\n            case iM_1_2:\n                return_val = m_total_mass_1_2;\n                break;\n            case iM_1_2W:\n                return_val = m_total_mass_1_2;\n                break;\n            case iD2_M_1_2:\n                return_val = m_total_diameter2_mass_1_2;\n                break;\n            case iD2_M_1_2W:\n                return_val = m_total_diameter2_mass_1_2;\n                break;\n            case iW:\n                return_val = m_total_number;\n                break;\n            case iUniform:\n                return_val = m_total_number;\n                break;\n            case iM:\n                return_val = m_total_mass;\n                break;\n        }\n    }\n    return return_val;\n}\n\n// Reset functions\nvoid Sweep::Ensemble::ResetNumberAtIndex(unsigned int index)\n{\n    m_particle_numbers[index] = 0;\n}\n\n// Set functions\nvoid Sweep::Ensemble::InitialiseParticleNumberModel()\n{\n    m_particle_numbers.resize(m_hybrid_threshold, 0);\n    m_pn_mass.resize(m_hybrid_threshold, 0);\n    m_pn_diameters3.resize(m_hybrid_threshold, 0);\n    m_pn_diameters.resize(m_hybrid_threshold, 0);\n    m_pn_diameters2.resize(m_hybrid_threshold, 0);\n    m_pn_diameters_1.resize(m_hybrid_threshold, 0);\n    m_pn_diameters_2.resize(m_hybrid_threshold, 0);\n    m_pn_mass2.resize(m_hybrid_threshold, 0);\n    m_pn_mass3.resize(m_hybrid_threshold, 0);\n    m_pn_mass_1_2.resize(m_hybrid_threshold, 0);\n    m_pn_diameters2_mass_1_2.resize(m_hybrid_threshold, 0);\n}\nvoid Sweep::Ensemble::InitialiseDiameters(double molecularWeight, double density)\n{\n    double expon = 1.0 / 3.0;\n    for (unsigned int i = 1; i < m_hybrid_threshold; ++i){\n        m_pn_mass[i] = (i / NA) * (molecularWeight);\n        m_pn_diameters3[i] = m_pn_mass[i] * 6.0 / (PI * density);\n        m_pn_diameters[i] = pow(m_pn_diameters3[i], expon);\n        m_pn_diameters2[i] = m_pn_diameters[i] * m_pn_diameters[i];\n        m_pn_diameters_1[i] = 1.0 / m_pn_diameters[i];\n        m_pn_diameters_2[i] = m_pn_diameters_1[i] * m_pn_diameters_1[i];\n        m_pn_mass2[i] = (m_pn_mass[i] * m_pn_mass[i]);\n        m_pn_mass3[i] = (m_pn_mass2[i] * m_pn_mass[i]);\n        m_pn_mass_1_2[i] = 1.0 / sqrt(m_pn_mass[i]);\n        m_pn_diameters2_mass_1_2[i] = m_pn_diameters2[i] * m_pn_mass_1_2[i];\n    }\n}\nunsigned int Sweep::Ensemble::SetTotalParticleNumber() {\n    m_total_number = 0;\n    for (unsigned int i = 0; i < m_hybrid_threshold; ++i){\n        m_total_number += m_particle_numbers[i];\n    }\n    return m_total_number;\n}\n\n// Recalculate property sums to account for increasing round-off error over time\n// It was found that not doing this regularly leads to inability to find particle \n// suitable for coagulation terms.\nvoid Sweep::Ensemble::RecalcPNPropertySums()\n{\n     m_total_diameter = 0.0;\n     m_total_diameter2 = 0.0;\n     m_total_diameter_1 = 0.0;\n     m_total_diameter_2 = 0.0;\n     m_total_diameter2_mass_1_2 = 0.0;\n     m_total_mass_1_2 = 0.0;\n     m_total_mass = 0.0;\n     m_total_mass2 = 0.0;\n     m_total_mass3 = 0.0;\n     m_total_diameter3 = 0.0;\n     double n_index = 0.0;\n\n     for (int i = 0; i < m_hybrid_threshold; ++i)\n     {\n         n_index = (double)m_particle_numbers[i];\n         if (n_index > 0)\n         {\n             m_total_diameter += n_index * m_pn_diameters[i];\n             m_total_diameter2 += n_index * m_pn_diameters2[i];\n             m_total_diameter_1 += n_index * m_pn_diameters_1[i];\n             m_total_diameter_2 += n_index * m_pn_diameters_2[i];\n             m_total_diameter2_mass_1_2 += n_index * m_pn_diameters2_mass_1_2[i];\n             m_total_mass_1_2 += n_index * m_pn_mass_1_2[i];\n             m_total_mass += n_index * m_pn_mass[i];\n             m_total_mass2 += n_index * m_pn_mass2[i];\n             m_total_mass3 += n_index * m_pn_mass3[i];\n             m_total_diameter3 += n_index * m_pn_diameters3[i];\n         }\n     }\n}\n// ===============================================\n\n// UPDATE ENSEMBLE.\n\n/*!\n * @param[in]   i       Index of particle which has been updated\n *\n * This method tells the ensemble that the particle at index i\n * has been changed by the calling code, so that the ensemble\n * can update its internal data structures to reflect the new\n * particle properties.  This allows for coagulation in place,\n * rather than particle copying during coagulation.\n */\nvoid Sweep::Ensemble::Update(unsigned int i)\n{\n    m_tree.replace(m_tree.begin() + i, tree_type::value_type(*m_particles[i], m_particles.begin() + i));\n}\n\n/*!\n * Replace the contents of the weights tree\n */\nvoid Ensemble::rebuildTree() {\n\n    // Iterators to loop over all the particles\n    iterator itPart = begin();\n    const iterator itPartEnd = end();\n\n    // Build up new data for binary tree\n    std::vector<std::pair<tree_type::weight_type, tree_type::return_pointer_type> > newTreeValues;\n    newTreeValues.reserve(m_count);\n    while(itPart != itPartEnd) {\n        newTreeValues.push_back(std::make_pair(static_cast<tree_type::weight_type>(**itPart), itPart));\n        ++itPart;\n    }\n\n    // Put the data into the tree\n    m_tree.assign(newTreeValues.begin(), newTreeValues.end());\n}\n\n// PRIVATE FUNCTIONS.\n\n/*!\n * The doubling algorithm is activated if the number of particles\n * in the ensemble falls below half capacity.  It copies the whole particle\n * list and changes the scaling factor to keep it consistent.  Once the\n * ensemble is back above half full, the routine updates the binary tree.\n *\n *@exception    std::runtime_error  Attempt to double with 0 particles\n */\nvoid Sweep::Ensemble::dble()\n{\n    // The doubling algorithm is activated if the number of particles\n    // in the ensemble falls below half capacity.  It copies the whole particle\n    // list and changes the scaling factor to keep it consistent.  Once the\n    // ensemble is back above half full, the routine updates the binary tree.\n\n    // Check that doubling is on and the activation condition has been met.\n    if (m_dbleon && m_dbleactive && (m_count + m_total_number) > 0) {\n        const unsigned originalCount = m_count;\n\t\tbool proceed = true;\n\n        // Continue while there are too few particles in the ensemble.\n        while ((m_count + m_total_number) < m_dblelimit && proceed) {\n            /*if(m_count == 0) {\n                throw std::runtime_error(\"Attempt to double particle ensemble with 0 particles\");\n            }*/\n\t\t\tstd::cout << \"Doubling!\" <<std::endl;\n\t\t\tstd::cout << m_count+ m_total_number << std::endl;\n\n\t\t\tbool IWDSA = false;\n\n            if (m_count > 0)\n            {\n            // Copy particles.\n            const size_t prevCount = m_count;\n\t\t\tint ii = 0;\n\t\t\tif (m_particles[0]->Primary()->AggID() == AggModels::PAH_KMC_ID){\n\t\t\t\tIWDSA = m_particles[0]->Primary()->ParticleModel()->Components(0)->WeightedPAHs();\n\t\t\t}\n            for (size_t i = 0; i != prevCount; ++i) {\n\n            //if (m_particles[i]->Primary()->AggID() ==AggModels::PAH_KMC_ID)\n            //{\n            //    const Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n            //    rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(m_particles[i]->Primary());\n            //    // if not 0, it is a pyrene\n            //    if (rhsparticle->Pyrene()!=0)\n            //        m_numofInceptedPAH++;\n            //}\n\t\t\t\tint numberPAH = 0;\n\t\t\t\tif (IWDSA){\n\t\t\t\t\tconst Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n\t\t\t\t\tif (m_particles[i]->Primary()->AggID() == AggModels::PAH_KMC_ID){\n\n\t\t\t\t\t\trhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(m_particles[i]->Primary());\n\t\t\t\t\t\tnumberPAH = rhsparticle->NumPAH();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (numberPAH > 1 || !IWDSA){ //If this particle is not just a single PAH\n\t\t\t\t\t\n\t\t\t\t\tsize_t iCopy = prevCount + ii;\n\t\t\t\t\t// Create a copy of a particle and add it to the ensemble.\n\t\t\t\t\tm_particles[iCopy] = m_particles[i]->Clone();\n\n\t\t\t\t\t// Keep count of the added particles\n\t\t\t\t\t++m_count;\n\t\t\t\t\t++ii;\n\t\t\t\t}\n\t\t\t\telse{ //If this particle is a single PAH, double its statistical weight\n\t\t\t\t\tdouble oldweight = m_particles[i]->getStatisticalWeight();\n\t\t\t\t\tm_particles[i]->setStatisticalWeight(2.0*oldweight);\n\t\t\t\t\tUpdate(i);\n\t\t\t\t}\n            }\n\t}\n        // Double particle-number counts\n        if (m_total_number > 0)\n        {\n            for (unsigned int i = 0; i < m_hybrid_threshold; ++i)\n            {\n                m_particle_numbers[i] *= 2.0;\n            }\n            DoubleTotals();\n        }\n\n            // Update scaling.\n            ++m_ndble;\n\n\t\t\tstd::cout << \"Doubling done\" << std::endl;\n\t\t\tstd::cout << m_count + m_total_number << std::endl;\n\t\t\tif (IWDSA) proceed = false;\n        }\n\n        m_maxcount = std::max(m_maxcount, m_count);\n\n        // Reset the contents of the binary tree to match the new population, if it has been changed\n        if(originalCount < m_count)\n            rebuildTree();\n\n\t\t//Remove tracking flags from untracked duplicates\n\t\tif (m_tracked_number > 0){\n\t\t\t//check all particle in the ensemble\n\t\t\tfor (int j = 0; j != m_count; j++) {\n\t\t\t\t//if particle is not tracked then unflag primaries\n\t\t\t\tbool track_flag = false;\n\t\t\t\tfor (unsigned int k = 0; k < m_tracked_particles.size(); k++){\n\t\t\t\t\tif (m_particles[j] == m_tracked_particles[k]) track_flag = true;\n\t\t\t\t}\n\t\t\t\tif (track_flag == false) m_particles[j]->removeTracking();\n\t\t\t}\n\t\t}\n    }\n}\n\n/*!\n * Empty the tree and pass of list of pointers to the particles in\n * the tree to the caller, which must take ownership of them.  This\n * clears all scaling information in the tree, but leaves all the\n * storage allocated.\n */\nSweep::PartPtrList Sweep::Ensemble::TakeParticles() {\n    // Copy the pointers to particles\n    PartPtrList listOfParticles(begin(), end());\n\n    // Now set the pointers in m_particles to NULL so that cannot be used\n    // to delete the particles that will now be owned by the caller\n    iterator it = begin();\n    const iterator itEnd = end();\n    while(it != itEnd) {\n        *it++ = NULL;\n    }\n\n    // Reset the tree and other data\n    ClearMain();\n\n    return listOfParticles;\n}\n\n/*\n * @brief Writes the object to a binary stream.\n *\n * @param        out                 Output binary stream\n *\n * @exception    invalid_argument    Stream not ready\n */\nvoid Sweep::Ensemble::Serialize(std::ostream &out) const\n{\n    const unsigned int trueval  = 1;\n    const unsigned int falseval = 0;\n\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Output ensemble capacity.\n        unsigned int n = (unsigned int)m_capacity;\n        out.write((char*)&n, sizeof(n));\n\n        // Nothing more to do if ensemble has 0 capacity\n        if(n == 0)\n            return;\n\n        // Output ensemble particle count.\n        n = (unsigned int)m_count;\n        out.write((char*)&n, sizeof(n));\n\n        // Output the particles.\n\t\tstd::set<void*> uniquePAHAdresses;\n        for (unsigned int i=0; i!=m_count; ++i) {\n            m_particles[i]->Serialize(out, &uniquePAHAdresses);\n        }\n\n        // Output number of contractions.\n        n = (unsigned int)m_ncont;\n        out.write((char*)&n, sizeof(n));\n\n        // Output final contraction factor.\n        double wcf = m_wtdcontfctr;\n        out.write((char*)&wcf, sizeof(wcf));\n\n        // Output number of doublings.\n        n = (unsigned int)m_ndble;\n        out.write((char*)&n, sizeof(n));\n\n        // Output if doubling is active.\n        if (m_dbleactive) {\n            out.write((char*)&trueval, sizeof(trueval));\n        } else {\n            out.write((char*)&falseval, sizeof(falseval));\n        }\n\n        // Output if doubling is turned on.\n        if (m_dbleon) {\n            out.write((char*)&trueval, sizeof(trueval));\n        } else {\n            out.write((char*)&falseval, sizeof(falseval));\n        }\n\n        // Contraction warning flag.\n        if (m_contwarn) {\n            out.write((char*)&trueval, sizeof(trueval));\n        } else {\n            out.write((char*)&falseval, sizeof(falseval));\n        }\t\n\n        // For hybrid particle-number/particle model\n        n = m_hybrid_threshold;\n        out.write((char*)&n, sizeof(n));\n        if (m_hybrid_threshold > 0)\n        {\n            n = m_total_number;\n            out.write((char*)&n, sizeof(n));\n\n            // Output all elements in the data vector.\n            fvector::const_iterator i;\n            std::vector<unsigned int>::const_iterator j;\n            for (j = m_particle_numbers.begin(); j != m_particle_numbers.end(); j++) {\n                out.write((char*)&(*j), sizeof(*j));\n            }\n            for (i = m_pn_diameters.begin(); i != m_pn_diameters.end(); i++) {\n                out.write((char*)&(*i), sizeof(*i));\n            }\n            for (i = m_pn_mass.begin(); i != m_pn_mass.end(); i++) {\n                out.write((char*)&(*i), sizeof(*i));\n            }\n        }\n\n    } else {\n        throw std::invalid_argument(\"Output stream not ready \"\n                               \"(Sweep, Ensemble::Serialize).\");\n    }\n}\n\n/*\n * @brief Reads the object from the binary stream.\n *\n * @param[in,out]    in                  Input binary stream\n * @param[in]        model\t             Particle model defining interpretation of particle data\n *\n * @exception        invalid_argument    Stream not ready\n * @exception        runtime_error       Invalid serialized version number\n */\nvoid Sweep::Ensemble::Deserialize(std::istream &in, const Sweep::ParticleModel &model)\n{\n    Clear();\n\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        unsigned int n = 0;\n\n        switch (version) {\n            case 0:\n\t\t\t{\n                // Read the ensemble capacity.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n\n                // capacity of 0 should mean the ensemble was never initialised\n                if (n == 0){\n                    init();\n                    return;\n                }\n                Initialise(n);\n\n                // Read the particle count.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                m_count = n;\n\n                // Read the particles.\n                // Provide a way to detect multiple instances of PAHs\n                std::map<void*, boost::shared_ptr<AggModels::PAHPrimary> > duplicates;\n                for (unsigned int i=0; i!=m_count; ++i) {\n                    Particle *p = new Particle(in, model, &duplicates);\n                    m_particles[i] = p;\n                }\n\n                // Read number of contractions.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                m_ncont = n;\n\n                // Read the final contraction factor\n                double wcf = 0.0;\n                in.read(reinterpret_cast<char*>(&wcf), sizeof(wcf));\n                m_wtdcontfctr = wcf;\n\n                // Read number of doublings.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                m_ndble = n;\n\n                // Read if doubling is active.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                if (n==1) {\n                    m_dbleactive = true;\n                } else {\n                    m_dbleactive = false;\n                }\n\n                // Read if doubling is turned on.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                if (n==1) {\n                    m_dbleon = true;\n                } else {\n                    m_dbleon = false;\n                }\n\n                // Read contraction warning flag.\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                if (n==1) {\n                    m_contwarn = true;\n                } else {\n                    m_contwarn = false;\n                }\n\n                // Hybrid particle-number/particle model\n                in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                m_hybrid_threshold = n;\n\n                // Fill the data vector.\n                if (m_hybrid_threshold > 0)\n                {\n                    in.read(reinterpret_cast<char*>(&n), sizeof(n));\n                    m_total_number = n;\n\n                    double val;\n                    unsigned int num;\n                    m_particle_numbers.reserve(m_hybrid_threshold);\n                    m_pn_diameters.reserve(m_hybrid_threshold);\n                    m_pn_mass.reserve(m_hybrid_threshold);\n                    for (unsigned int i = 0; i < m_hybrid_threshold; i++) {\n                        in.read(reinterpret_cast<char*>(&num), sizeof(num));\n                        m_particle_numbers.push_back(num);\n                    }\n                    for (unsigned int i = 0; i < m_hybrid_threshold; i++) {\n                        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                        m_pn_diameters.push_back(val);\n                    }\n                    for (unsigned int i = 0; i < m_hybrid_threshold; i++) {\n                        in.read(reinterpret_cast<char*>(&val), sizeof(val));\n                        m_pn_mass.push_back(val);\n                    }\n                }\n\t\t\t\n                // Calculate binary tree.\n                rebuildTree();\n\n                break;\n\t\t\t}\n            default:\n                throw std::runtime_error(\"Serialized version number is invalid \"\n                                    \"(Sweep, Ensemble::Deserialize).\");\n        }\n    } else {\n        throw std::invalid_argument(\"Input stream not ready \"\n                               \"(Sweep, Ensemble::Deserialize).\");\n    }\n}\n\n// MEMORY MANAGEMENT.\n\n// Releases all memory resources used by the ensemble.\nvoid Sweep::Ensemble::releaseMem(void)\n{\n    // Delete particles from memory and delete vectors.\n    for (int i=0; i!=(int)m_particles.size(); ++i) {\n        delete m_particles[i];\n        m_particles[i] = NULL;\n    }\n    m_particles.clear();\n\n\t// Also clear the tracked pointers.\n    m_tracked_particles.clear();\n\n    // Delete particle-number components from memory and delete vectors.\n    for (int i = 0; i != (int)m_pn_particles.size(); ++i) {\n        delete m_pn_particles[i];\n        m_pn_particles[i] = NULL;\n        }\n    m_pn_particles.clear();\n    m_pn_diameters.clear();\n    m_pn_diameters2.clear();\n    m_pn_diameters3.clear();\n    m_pn_diameters_1.clear();\n    m_pn_diameters_2.clear();\n    m_pn_diameters2_mass_1_2.clear();\n    m_pn_mass.clear();\n    m_pn_mass2.clear();\n    m_pn_mass3.clear();\n    m_pn_mass_1_2.clear();\n    m_particle_numbers.clear();\n    fvector().swap(m_pn_diameters);\n    fvector().swap(m_pn_diameters2);\n    fvector().swap(m_pn_diameters3);\n    fvector().swap(m_pn_diameters_1);\n    fvector().swap(m_pn_diameters_2);\n    fvector().swap(m_pn_diameters2_mass_1_2);\n    fvector().swap(m_pn_mass);\n    fvector().swap(m_pn_mass2);\n    fvector().swap(m_pn_mass3);\n    fvector().swap(m_pn_mass_1_2);\n}\n\n// Sets the ensemble to its initial condition.  Used in constructors.\nvoid Sweep::Ensemble::init(void)\n{\n    releaseMem();\n\n    // Capacity.\n    m_levels     = 0;\n    m_capacity   = 0;\n    m_halfcap    = 0;\n    m_count      = 0;\n    //m_numofInceptedPAH = 0;\n\n    // Scaling.\n    m_contfactor = 0;\n    m_ncont      = 0;\n    m_wtdcontfctr = 1.0;\n    m_contwarn   = false;\n\n    // Doubling algorithm.\n    m_maxcount   = 0;\n    m_ndble      = 0;\n    m_dbleactive = false;\n    m_dblecutoff = 0;\n    m_dblelimit  = 0;\n    m_dbleslack  = 0;\n    m_dbleon     = true;\n\n\tm_tracked_number = 0;\n\n    // Hybrid particle-number/particle model parameters\n    // ===============================================\n    m_hybrid_threshold = 0;\n    m_total_number = 0;\n    m_total_diameter = 0.0;\n    m_total_diameter2 = 0.0;\n    m_total_diameter_1 = 0.0;\n    m_total_diameter_2 = 0.0;\n    m_total_diameter2_mass_1_2 = 0.0;\n    m_total_mass_1_2 = 0.0;\n    m_total_mass = 0.0;\n    m_total_mass2 = 0.0;\n    m_total_mass3 = 0.0;\n    m_total_diameter3 = 0.0;\n    m_total_component = 0;\n    // ===============================================\n}\n\n//int Sweep::Ensemble::NumOfInceptedPAH() const\n//{\n    //int numofpyrene = 0;\n    //for (int i =0;i<m_count;i++){\n    //    const Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n    //    rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(m_particles[i]->Primary());\n\n    //    numofpyrene += rhsparticle->InceptedPAH();\n    //    }\n    //if (numofpyrene!= m_numofInceptedPAH)\n    //    std::cout<<\"something goes wrong, the number ofPAH in ensemble is not consistent\"<<std::endl;\n    //return numofpyrene;\n//    return m_numofInceptedPAH;\n//}\n\n/*!\n * Iterate through all the stochastic particles and count the number of incepted PAHs of type k\n *\n * An incepted PAH is a stochastic particle made up of a single primary and a single PAH matching the gas transfer species (PAH that bridges gas-phase profile and MOPS)\n */\nint Sweep::Ensemble::NumOfInceptedPAH(int Model_ID, const int k) const\n{\n    int numOfInceptedPAHs = 0;\n\n    if (Model_ID == AggModels::Spherical_ID || Model_ID == AggModels::BinTree_ID) {\n        for (int i = 0; i < m_count; i++){\n            if (m_particles[i]->Primary()->InceptedPAH()) {\n                numOfInceptedPAHs += 1;\n            }\n        }\n    } else {\n        for (int i = 0; i < m_count; i++){\n            const Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n            rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(m_particles[i]->Primary());\n\n            numOfInceptedPAHs += rhsparticle->InceptedPAH(k);\n        }\n    }\n\n    return numOfInceptedPAHs;\n}\n\nint Sweep::Ensemble::IndexOfInceptedPAH(int Model_ID, const int k) const\n{\n    if (Model_ID == AggModels::Spherical_ID) {\n        for (int i =m_count-1;i>=0;--i){\n            if (m_particles[i]->Primary()->InceptedPAH())\n                return i;\n\t    }\n    } else {\n        for (int i =m_count-1;i>=0;--i){\n            const Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n            rhsparticle = dynamic_cast<const AggModels::PAHPrimary*>(m_particles[i]->Primary());\n            if (rhsparticle->InceptedPAH(k) == 1)\n                return i;\n        }\n    }\n\n    return -1;\n}\n\n//void Sweep::Ensemble::SetNumOfInceptedPAH(int m_amount, Sweep::AggModels::Primary *m_primary)\n//{\n//    if (m_primary->AggID() ==AggModels::PAH_KMC_ID)\n//    {\n//        //m_primary->ParticleModel()->IsPyreneInception()\n//        const Sweep::AggModels::PAHPrimary *rhsparticle = NULL;\n//        rhsparticle = dynamic_cast<const Sweep::AggModels::PAHPrimary*>(m_primary);\n//\n//        if (rhsparticle->InceptedPAH()!=0)\n//            // rhsparticle is pyrene\n//            SetNumOfInceptedPAH(m_amount);\n//    }\n//\n//}\n//void Sweep::Ensemble::SetNumOfInceptedPAH(int m_amount)\n//{\n//    m_numofInceptedPAH += m_amount;\n//}\n/*!\n * @param[in]   id      Index of property which will be extracted\n */\nEnsemble::WeightExtractor::WeightExtractor(const Sweep::PropID id)\n: mId(id)\n{}\n\n/*!\n * @param[in]   cache   Particle cache from which to extract a weight\n *\n * @return      The weight extracted from the cache\n */\ndouble Ensemble::WeightExtractor::operator()(const particle_cache_type& cache) const {\n    return cache.Property(mId);\n}\n\n// PARTICLE TRACKING OUTPUT FOR VIDEOS\n\n/*!\n* Updates tracking after a coagulation event\n*\n* @param[in] p_old\t\tindex of old particle that will be removed\n* @param[in] p_merged\tindex of new merged particle\n*\n* Note: if p_merged is already tracked then both copies will be kept.\n*/\nvoid Sweep::Ensemble::UpdateTracking(int p_old, int p_merged){\n\n\t//Check if the new particle is already being tracked\n\tbool merged_tracked = false;\n\tfor (unsigned int i = 0; i < m_tracked_particles.size(); i++){\n\t\tif (m_tracked_particles[i] == m_particles[p_merged])\n\t\t\tmerged_tracked = true;\n\t}\n\n\t//Replace tracking poiner of old particle with new particle,\n\t//unless the merged particle is already being tracked\n\tfor (unsigned int i = 0; i < m_tracked_particles.size(); i++){\n\t\tif (m_tracked_particles[i] == m_particles[p_old] && merged_tracked == false)\n\t\t\tm_tracked_particles[i] = m_particles[p_merged];\n\t}\n}\n\n//! Returns a pointer to the given tracked particle.\nconst Particle *const Sweep::Ensemble::TrackedAt(unsigned int i) const\n{\n    // Check that the index in within range, then return the particle.\n\tif ((int)i <= (int)(m_tracked_particles.size() - 1)) {\n        return m_tracked_particles[i];\n    } else {\n        return NULL;\n    }\n}\n\n//! Set number of particle tracked for videos\nvoid Sweep::Ensemble::SetParticleTrackingNumber(unsigned int val)\n{\n\tm_tracked_number = val;\n}\n\n//! Initialise tracking of initial population \nvoid Sweep::Ensemble::InitialiseParticleTracking(){\n\t\n\tunsigned int i = 0;\n\twhile(i < m_tracked_number && i<m_count){\n\t\tm_tracked_particles[i] = m_particles[i];\n\t\t//initialise tracking of primary\n\t\tm_tracked_particles[i]->setTracking();\n\t\ti++;\n\t}\n}\n\n//! Return number of particles currently being tracked for videos\nunsigned int Sweep::Ensemble::TrackedParticleNumber() const\n{\n\treturn m_tracked_particles.size();\n}", "meta": {"hexsha": "e88372ab11282e4bd4d14bf2266b3396bdd884c5", "size": 67073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_ensemble.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_ensemble.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_ensemble.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 33.4695608782, "max_line_length": 168, "alphanum_fraction": 0.6125713775, "num_tokens": 17881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781086512112404, "lm_q2_score": 0.024053551801287282, "lm_q1q2_score": 0.004276982855022663}}
{"text": "// Copyright (c) Jeremy Siek 2001\r\n// Copyright (c) Douglas Gregor 2004\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// NOTE: this final is generated by libs/graph/doc/biconnected_components.w\r\n\r\n#ifndef BOOST_GRAPH_BICONNECTED_COMPONENTS_HPP\r\n#define BOOST_GRAPH_BICONNECTED_COMPONENTS_HPP\r\n\r\n#include <stack>\r\n#include <vector>\r\n#include <algorithm> // for std::min and std::max\r\n#include <boost/config.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/depth_first_search.hpp>\r\n#include <boost/graph/graph_utility.hpp>\r\n#include <boost/concept/assert.hpp>\r\n#include <boost/assert.hpp>\r\n\r\nnamespace boost\r\n{\r\nnamespace detail\r\n{\r\n    template < typename ComponentMap, typename DiscoverTimeMap,\r\n        typename LowPointMap, typename PredecessorMap, typename OutputIterator,\r\n        typename Stack, typename ArticulationVector, typename IndexMap,\r\n        typename DFSVisitor >\r\n    struct biconnected_components_visitor : public dfs_visitor<>\r\n    {\r\n        biconnected_components_visitor(ComponentMap comp, std::size_t& c,\r\n            std::size_t& children_of_root, DiscoverTimeMap dtm,\r\n            std::size_t& dfs_time, LowPointMap lowpt, PredecessorMap pred,\r\n            OutputIterator out, Stack& S,\r\n            ArticulationVector& is_articulation_point, IndexMap index_map,\r\n            DFSVisitor vis)\r\n        : comp(comp)\r\n        , c(c)\r\n        , children_of_root(children_of_root)\r\n        , dtm(dtm)\r\n        , dfs_time(dfs_time)\r\n        , lowpt(lowpt)\r\n        , pred(pred)\r\n        , out(out)\r\n        , S(S)\r\n        , is_articulation_point(is_articulation_point)\r\n        , index_map(index_map)\r\n        , vis(vis)\r\n        {\r\n        }\r\n\r\n        template < typename Vertex, typename Graph >\r\n        void initialize_vertex(const Vertex& u, Graph& g)\r\n        {\r\n            put(pred, u, u);\r\n            vis.initialize_vertex(u, g);\r\n        }\r\n\r\n        template < typename Vertex, typename Graph >\r\n        void start_vertex(const Vertex& u, Graph& g)\r\n        {\r\n            children_of_root = 0;\r\n            vis.start_vertex(u, g);\r\n        }\r\n\r\n        template < typename Vertex, typename Graph >\r\n        void discover_vertex(const Vertex& u, Graph& g)\r\n        {\r\n            put(dtm, u, ++dfs_time);\r\n            put(lowpt, u, get(dtm, u));\r\n            vis.discover_vertex(u, g);\r\n        }\r\n\r\n        template < typename Edge, typename Graph >\r\n        void examine_edge(const Edge& e, Graph& g)\r\n        {\r\n            vis.examine_edge(e, g);\r\n        }\r\n\r\n        template < typename Edge, typename Graph >\r\n        void tree_edge(const Edge& e, Graph& g)\r\n        {\r\n            typename boost::graph_traits< Graph >::vertex_descriptor src\r\n                = source(e, g);\r\n            typename boost::graph_traits< Graph >::vertex_descriptor tgt\r\n                = target(e, g);\r\n\r\n            S.push(e);\r\n            put(pred, tgt, src);\r\n            if (get(pred, src) == src)\r\n            {\r\n                ++children_of_root;\r\n            }\r\n            vis.tree_edge(e, g);\r\n        }\r\n\r\n        template < typename Edge, typename Graph >\r\n        void back_edge(const Edge& e, Graph& g)\r\n        {\r\n            BOOST_USING_STD_MIN();\r\n\r\n            typename boost::graph_traits< Graph >::vertex_descriptor src\r\n                = source(e, g);\r\n            typename boost::graph_traits< Graph >::vertex_descriptor tgt\r\n                = target(e, g);\r\n            if (tgt != get(pred, src))\r\n            {\r\n                S.push(e);\r\n                put(lowpt, src,\r\n                    min BOOST_PREVENT_MACRO_SUBSTITUTION(\r\n                        get(lowpt, src), get(dtm, tgt)));\r\n            }\r\n            vis.back_edge(e, g);\r\n        }\r\n\r\n        template < typename Edge, typename Graph >\r\n        void forward_or_cross_edge(const Edge& e, Graph& g)\r\n        {\r\n            vis.forward_or_cross_edge(e, g);\r\n        }\r\n\r\n        template < typename Vertex, typename Graph >\r\n        void finish_vertex(const Vertex& u, Graph& g)\r\n        {\r\n            BOOST_USING_STD_MIN();\r\n            Vertex parent = get(pred, u);\r\n            if (parent == u)\r\n            { // Root of tree is special\r\n                is_articulation_point[get(index_map, u)]\r\n                    = (children_of_root > 1);\r\n            }\r\n            else\r\n            {\r\n                put(lowpt, parent,\r\n                    min BOOST_PREVENT_MACRO_SUBSTITUTION(\r\n                        get(lowpt, parent), get(lowpt, u)));\r\n                if (get(lowpt, u) >= get(dtm, parent))\r\n                {\r\n                    is_articulation_point[get(index_map, parent)] = true;\r\n                    while (get(dtm, source(S.top(), g)) >= get(dtm, u))\r\n                    {\r\n                        put(comp, S.top(), c);\r\n                        S.pop();\r\n                    }\r\n                    BOOST_ASSERT(source(S.top(), g) == parent);\r\n                    BOOST_ASSERT(target(S.top(), g) == u);\r\n                    put(comp, S.top(), c);\r\n                    S.pop();\r\n                    ++c;\r\n                }\r\n            }\r\n            if (is_articulation_point[get(index_map, u)])\r\n            {\r\n                *out++ = u;\r\n            }\r\n            vis.finish_vertex(u, g);\r\n        }\r\n\r\n        ComponentMap comp;\r\n        std::size_t& c;\r\n        std::size_t& children_of_root;\r\n        DiscoverTimeMap dtm;\r\n        std::size_t& dfs_time;\r\n        LowPointMap lowpt;\r\n        PredecessorMap pred;\r\n        OutputIterator out;\r\n        Stack& S;\r\n        ArticulationVector& is_articulation_point;\r\n        IndexMap index_map;\r\n        DFSVisitor vis;\r\n    };\r\n\r\n    template < typename Graph, typename ComponentMap, typename OutputIterator,\r\n        typename VertexIndexMap, typename DiscoverTimeMap, typename LowPointMap,\r\n        typename PredecessorMap, typename DFSVisitor >\r\n    std::pair< std::size_t, OutputIterator > biconnected_components_impl(\r\n        const Graph& g, ComponentMap comp, OutputIterator out,\r\n        VertexIndexMap index_map, DiscoverTimeMap dtm, LowPointMap lowpt,\r\n        PredecessorMap pred, DFSVisitor dfs_vis)\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        BOOST_CONCEPT_ASSERT((VertexListGraphConcept< Graph >));\r\n        BOOST_CONCEPT_ASSERT((IncidenceGraphConcept< Graph >));\r\n        BOOST_CONCEPT_ASSERT(\r\n            (WritablePropertyMapConcept< ComponentMap, edge_t >));\r\n        BOOST_CONCEPT_ASSERT(\r\n            (ReadWritePropertyMapConcept< DiscoverTimeMap, vertex_t >));\r\n        BOOST_CONCEPT_ASSERT(\r\n            (ReadWritePropertyMapConcept< LowPointMap, vertex_t >));\r\n        BOOST_CONCEPT_ASSERT(\r\n            (ReadWritePropertyMapConcept< PredecessorMap, vertex_t >));\r\n\r\n        std::size_t num_components = 0;\r\n        std::size_t children_of_root;\r\n        std::size_t dfs_time = 0;\r\n        std::stack< edge_t > S;\r\n        std::vector< char > is_articulation_point(num_vertices(g));\r\n\r\n        biconnected_components_visitor< ComponentMap, DiscoverTimeMap,\r\n            LowPointMap, PredecessorMap, OutputIterator, std::stack< edge_t >,\r\n            std::vector< char >, VertexIndexMap, DFSVisitor >\r\n            vis(comp, num_components, children_of_root, dtm, dfs_time, lowpt,\r\n                pred, out, S, is_articulation_point, index_map, dfs_vis);\r\n\r\n        depth_first_search(g, visitor(vis).vertex_index_map(index_map));\r\n\r\n        return std::pair< std::size_t, OutputIterator >(\r\n            num_components, vis.out);\r\n    }\r\n\r\n    template < typename PredecessorMap > struct bicomp_dispatch3\r\n    {\r\n        template < typename Graph, typename ComponentMap,\r\n            typename OutputIterator, typename VertexIndexMap,\r\n            typename DiscoverTimeMap, typename LowPointMap, class P, class T,\r\n            class R >\r\n        static std::pair< std::size_t, OutputIterator > apply(const Graph& g,\r\n            ComponentMap comp, OutputIterator out, VertexIndexMap index_map,\r\n            DiscoverTimeMap dtm, LowPointMap lowpt,\r\n            const bgl_named_params< P, T, R >& params, PredecessorMap pred)\r\n        {\r\n            return biconnected_components_impl(g, comp, out, index_map, dtm,\r\n                lowpt, pred,\r\n                choose_param(get_param(params, graph_visitor),\r\n                    make_dfs_visitor(null_visitor())));\r\n        }\r\n    };\r\n\r\n    template <> struct bicomp_dispatch3< param_not_found >\r\n    {\r\n        template < typename Graph, typename ComponentMap,\r\n            typename OutputIterator, typename VertexIndexMap,\r\n            typename DiscoverTimeMap, typename LowPointMap, class P, class T,\r\n            class R >\r\n        static std::pair< std::size_t, OutputIterator > apply(const Graph& g,\r\n            ComponentMap comp, OutputIterator out, VertexIndexMap index_map,\r\n            DiscoverTimeMap dtm, LowPointMap lowpt,\r\n            const bgl_named_params< P, T, R >& params, param_not_found)\r\n        {\r\n            typedef typename graph_traits< Graph >::vertex_descriptor vertex_t;\r\n            std::vector< vertex_t > pred(num_vertices(g));\r\n            vertex_t vert = graph_traits< Graph >::null_vertex();\r\n\r\n            return biconnected_components_impl(g, comp, out, index_map, dtm,\r\n                lowpt,\r\n                make_iterator_property_map(pred.begin(), index_map, vert),\r\n                choose_param(get_param(params, graph_visitor),\r\n                    make_dfs_visitor(null_visitor())));\r\n        }\r\n    };\r\n\r\n    template < typename LowPointMap > struct bicomp_dispatch2\r\n    {\r\n        template < typename Graph, typename ComponentMap,\r\n            typename OutputIterator, typename VertexIndexMap,\r\n            typename DiscoverTimeMap, typename P, typename T, typename R >\r\n        static std::pair< std::size_t, OutputIterator > apply(const Graph& g,\r\n            ComponentMap comp, OutputIterator out, VertexIndexMap index_map,\r\n            DiscoverTimeMap dtm, const bgl_named_params< P, T, R >& params,\r\n            LowPointMap lowpt)\r\n        {\r\n            typedef typename get_param_type< vertex_predecessor_t,\r\n                bgl_named_params< P, T, R > >::type dispatch_type;\r\n\r\n            return bicomp_dispatch3< dispatch_type >::apply(g, comp, out,\r\n                index_map, dtm, lowpt, params,\r\n                get_param(params, vertex_predecessor));\r\n        }\r\n    };\r\n\r\n    template <> struct bicomp_dispatch2< param_not_found >\r\n    {\r\n        template < typename Graph, typename ComponentMap,\r\n            typename OutputIterator, typename VertexIndexMap,\r\n            typename DiscoverTimeMap, typename P, typename T, typename R >\r\n        static std::pair< std::size_t, OutputIterator > apply(const Graph& g,\r\n            ComponentMap comp, OutputIterator out, VertexIndexMap index_map,\r\n            DiscoverTimeMap dtm, const bgl_named_params< P, T, R >& params,\r\n            param_not_found)\r\n        {\r\n            typedef typename graph_traits< Graph >::vertices_size_type\r\n                vertices_size_type;\r\n            std::vector< vertices_size_type > lowpt(num_vertices(g));\r\n            vertices_size_type vst(0);\r\n\r\n            typedef typename get_param_type< vertex_predecessor_t,\r\n                bgl_named_params< P, T, R > >::type dispatch_type;\r\n\r\n            return bicomp_dispatch3< dispatch_type >::apply(g, comp, out,\r\n                index_map, dtm,\r\n                make_iterator_property_map(lowpt.begin(), index_map, vst),\r\n                params, get_param(params, vertex_predecessor));\r\n        }\r\n    };\r\n\r\n    template < typename DiscoverTimeMap > struct bicomp_dispatch1\r\n    {\r\n        template < typename Graph, typename ComponentMap,\r\n            typename OutputIterator, typename VertexIndexMap, class P, class T,\r\n            class R >\r\n        static std::pair< std::size_t, OutputIterator > apply(const Graph& g,\r\n            ComponentMap comp, OutputIterator out, VertexIndexMap index_map,\r\n            const bgl_named_params< P, T, R >& params, DiscoverTimeMap dtm)\r\n        {\r\n            typedef typename get_param_type< vertex_lowpoint_t,\r\n                bgl_named_params< P, T, R > >::type dispatch_type;\r\n\r\n            return bicomp_dispatch2< dispatch_type >::apply(g, comp, out,\r\n                index_map, dtm, params, get_param(params, vertex_lowpoint));\r\n        }\r\n    };\r\n\r\n    template <> struct bicomp_dispatch1< param_not_found >\r\n    {\r\n        template < typename Graph, typename ComponentMap,\r\n            typename OutputIterator, typename VertexIndexMap, class P, class T,\r\n            class R >\r\n        static std::pair< std::size_t, OutputIterator > apply(const Graph& g,\r\n            ComponentMap comp, OutputIterator out, VertexIndexMap index_map,\r\n            const bgl_named_params< P, T, R >& params, param_not_found)\r\n        {\r\n            typedef typename graph_traits< Graph >::vertices_size_type\r\n                vertices_size_type;\r\n            std::vector< vertices_size_type > discover_time(num_vertices(g));\r\n            vertices_size_type vst(0);\r\n\r\n            typedef typename get_param_type< vertex_lowpoint_t,\r\n                bgl_named_params< P, T, R > >::type dispatch_type;\r\n\r\n            return bicomp_dispatch2< dispatch_type >::apply(g, comp, out,\r\n                index_map,\r\n                make_iterator_property_map(\r\n                    discover_time.begin(), index_map, vst),\r\n                params, get_param(params, vertex_lowpoint));\r\n        }\r\n    };\r\n\r\n}\r\n\r\ntemplate < typename Graph, typename ComponentMap, typename OutputIterator,\r\n    typename DiscoverTimeMap, typename LowPointMap >\r\nstd::pair< std::size_t, OutputIterator > biconnected_components(const Graph& g,\r\n    ComponentMap comp, OutputIterator out, DiscoverTimeMap dtm,\r\n    LowPointMap lowpt)\r\n{\r\n    typedef param_not_found dispatch_type;\r\n\r\n    return detail::bicomp_dispatch3< dispatch_type >::apply(g, comp, out,\r\n        get(vertex_index, g), dtm, lowpt,\r\n        bgl_named_params< int, buffer_param_t >(0), param_not_found());\r\n}\r\n\r\ntemplate < typename Graph, typename ComponentMap, typename OutputIterator,\r\n    typename P, typename T, typename R >\r\nstd::pair< std::size_t, OutputIterator > biconnected_components(const Graph& g,\r\n    ComponentMap comp, OutputIterator out,\r\n    const bgl_named_params< P, T, R >& params)\r\n{\r\n    typedef typename get_param_type< vertex_discover_time_t,\r\n        bgl_named_params< P, T, R > >::type dispatch_type;\r\n\r\n    return detail::bicomp_dispatch1< dispatch_type >::apply(g, comp, out,\r\n        choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n        params, get_param(params, vertex_discover_time));\r\n}\r\n\r\ntemplate < typename Graph, typename ComponentMap, typename OutputIterator >\r\nstd::pair< std::size_t, OutputIterator > biconnected_components(\r\n    const Graph& g, ComponentMap comp, OutputIterator out)\r\n{\r\n    return biconnected_components(\r\n        g, comp, out, bgl_named_params< int, buffer_param_t >(0));\r\n}\r\n\r\nnamespace graph_detail\r\n{\r\n    struct dummy_output_iterator\r\n    {\r\n        typedef std::output_iterator_tag iterator_category;\r\n        typedef void value_type;\r\n        typedef void pointer;\r\n        typedef void difference_type;\r\n\r\n        struct reference\r\n        {\r\n            template < typename T > reference& operator=(const T&)\r\n            {\r\n                return *this;\r\n            }\r\n        };\r\n\r\n        reference operator*() const { return reference(); }\r\n        dummy_output_iterator& operator++() { return *this; }\r\n        dummy_output_iterator operator++(int) { return *this; }\r\n    };\r\n} // end namespace graph_detail\r\n\r\ntemplate < typename Graph, typename ComponentMap, typename P, typename T,\r\n    typename R >\r\nstd::size_t biconnected_components(const Graph& g, ComponentMap comp,\r\n    const bgl_named_params< P, T, R >& params)\r\n{\r\n    return biconnected_components(\r\n        g, comp, graph_detail::dummy_output_iterator(), params)\r\n        .first;\r\n}\r\n\r\ntemplate < typename Graph, typename ComponentMap >\r\nstd::size_t biconnected_components(const Graph& g, ComponentMap comp)\r\n{\r\n    return biconnected_components(\r\n        g, comp, graph_detail::dummy_output_iterator())\r\n        .first;\r\n}\r\n\r\ntemplate < typename Graph, typename OutputIterator, typename P, typename T,\r\n    typename R >\r\nOutputIterator articulation_points(const Graph& g, OutputIterator out,\r\n    const bgl_named_params< P, T, R >& params)\r\n{\r\n    return biconnected_components(g, dummy_property_map(), out, params).second;\r\n}\r\n\r\ntemplate < typename Graph, typename OutputIterator >\r\nOutputIterator articulation_points(const Graph& g, OutputIterator out)\r\n{\r\n    return biconnected_components(g, dummy_property_map(), out,\r\n        bgl_named_params< int, buffer_param_t >(0))\r\n        .second;\r\n}\r\n\r\n} // namespace boost\r\n\r\n#endif /* BOOST_GRAPH_BICONNECTED_COMPONENTS_HPP */\r\n", "meta": {"hexsha": "c4918ede908a8d035ed9a248ad337e84588541ac", "size": 17141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/biconnected_components.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/biconnected_components.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/biconnected_components.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 38.8684807256, "max_line_length": 81, "alphanum_fraction": 0.6035820547, "num_tokens": 3664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850021044189, "lm_q2_score": 0.017442482788934906, "lm_q1q2_score": 0.004274890931032401}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"nwchem.h\"\n#include <votca/ctp/segment.h>\n#include <votca/xtp/qminterface.h>\n#include <votca/xtp/basisset.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n#include <stdio.h>\n#include <iomanip>\n\n\n\n\nnamespace votca {\n    namespace xtp {\n       using namespace std;\n\n        void NWChem::Initialize(tools::Property &options) {\n\n            // NWChem file names\n            string fileName = \"system\";\n\n            _input_file_name = fileName + \".nw\";\n            _log_file_name = fileName + \".log\";\n            _shell_file_name = fileName + \".sh\";\n            _orb_file_name = fileName + \".movecs\";\n\n            string key = \"package\";\n            string _name = options.get(key + \".name\").as<string> ();\n\n            if (_name != \"nwchem\") {\n                cerr << \"Tried to use \" << _name << \" package. \";\n                throw std::runtime_error(\"Wrong options file\");\n            }\n\n            _executable = options.get(key + \".executable\").as<string> ();\n            _charge = options.get(key + \".charge\").as<int> ();\n            _spin = options.get(key + \".spin\").as<int> ();\n            _options = options.get(key + \".options\").as<string> ();\n            _memory = options.get(key + \".memory\").as<string> ();\n            _threads = options.get(key + \".threads\").as<int> ();\n            _scratch_dir = options.get(key + \".scratch\").as<string> ();\n            _cleanup = options.get(key + \".cleanup\").as<string> ();\n            \n            _basisset_name = options.get(key + \".basisset\").as<std::string> ();\n            _write_basis_set = options.get(key + \".writebasisset\").as<bool> ();\n            _write_pseudopotentials = options.get(key + \".writepseudopotentials\").as<bool> ();\n            \n            if ( _write_pseudopotentials )  _ecp_name = options.get(key + \".ecp\").as<std::string> ();\n\n            if (options.exists(key + \".outputVxc\")) {\n                _output_Vxc = options.get(key + \".outputVxc\").as<bool> ();\n            } else _output_Vxc = false;\n            // check whether options string contains vxc output, the _outputVxc is set to true\n            std::string::size_type iop_pos = _options.find(\" intermediate tXC matrix\");\n            if (iop_pos != std::string::npos) {\n                if (_output_Vxc) {\n                    cout << \"=== You do not have to specify outputting Vxc twice. Next time remove \"\n                            \"the print \"\"intermediate tXC matrix\"\" part from your options string. Please continue\" << endl;\n                } else {\n                    cout << \"=== So you do not want to output Vxc but still put it in the options string? \"\n                            \"I will assume that you want to output Vxc, be more consistent next time. \" << endl;\n                }\n                _output_Vxc = true;\n            }\n            else if (_output_Vxc == true) {\n                _options = _options + \"\\n\\ndft\\nprint \\\"intermediate tXC matrix\\\"\\nvectors input system.movecs\\nnoscf\\nend\\ntask dft\";\n            }\n\n            // check if the optimize keyword is present, if yes, read updated coords\n            iop_pos = _options.find(\" optimize\");\n            if (iop_pos != std::string::npos) {\n                _is_optimization = true;\n            } else {\n                _is_optimization = false;\n            }\n\n            // check if the esp keyword is present, if yes, get the charges and save them\n            iop_pos = _options.find(\" esp\");\n            if (iop_pos != std::string::npos) {\n                _get_charges = true;\n            } else {\n                _get_charges = false;\n            }\n  \n\n            // check if the guess should be prepared, if yes, append the guess later\n            _write_guess = false;\n            iop_pos = _options.find(\"iterations 1 \");\n            if (iop_pos != std::string::npos) _write_guess = true;\n            iop_pos = _options.find(\"iterations 1\\n\");\n            if (iop_pos != std::string::npos) _write_guess = true;\n        }\n\n         /* For QM/MM the molecules in the MM environment are represented by\n         * their atomic partial charge distributions. Triggered by the option\n         * keyword \"set bq background\" NWChem expects them in x,y,z,q format in the\n         * backround.crg file.\n         */\n        \n        void NWChem::WriteChargeOption(){\n              std::string::size_type iop_pos = _options.find(\"set bq background\");\n              if (iop_pos != std::string::npos) {\n                _options = _options + \"\\n set bq background\";\n              }\n        }\n       \n\n        int NWChem::WriteBackgroundCharges(ofstream& nw_file) {\n\n            int numberofcharges=0;\n            boost::format fmt(\"%1$+1.7f %2$+1.7f %3$+1.7f %4$+1.7f\");\n              for (std::shared_ptr<ctp::PolarSeg> seg:_PolarSegments) {\n                for (ctp::APolarSite* site:*seg) {\n                    string sitestring=boost::str(fmt % ((site->getPos().getX())*votca::tools::conv::nm2ang) \n                            % (site->getPos().getY()*votca::tools::conv::nm2ang) \n                            % (site->getPos().getZ()*votca::tools::conv::nm2ang) \n                            % site->getQ00());\n                    if (site->getQ00() != 0.0){\n                      nw_file << sitestring << endl;\n                      numberofcharges++;\n                    }\n                    if (site->getRank() > 0 || _with_polarization ) {\n                        std::vector< std::vector<double> > _split_multipoles = SplitMultipoles(site);\n                        for (const auto& mpoles:_split_multipoles){\n                           string multipole=boost::str( fmt % mpoles[0] % mpoles[1] % mpoles[2] % mpoles[3]);\n                            nw_file << multipole << endl;\n                            numberofcharges++;\n\n                        }\n                    }\n                }\n            }\n            nw_file << endl;\n            return numberofcharges;\n        }\n        \n\n        bool NWChem::WriteGuess(Orbitals& orbitals){\n          ofstream orb_file;\n          std::string orb_file_name_full = _run_dir + \"/\" + _orb_file_name;\n          // get name of temporary ascii file and open it\n          std::vector<std::string> results;\n          boost::algorithm::split(results, _orb_file_name, boost::is_any_of(\".\"), boost::algorithm::token_compress_on);\n          std::string orb_file_name_ascii = _run_dir + \"/\" + results.front() + \".mos\";\n          orb_file.open(orb_file_name_ascii.c_str());\n          \n          // header\n          orb_file << \"#generated by VOTCA\\nbasisum\\ngeomsum\\n\\nscf\\nFri Sep 13 00:00:00 2013\\nscf\\n1\\n\\n8\\nao basis\\n1\\n\" << flush;\n          int size_of_basis = (orbitals.MOEnergies()).size();\n          orb_file << size_of_basis << endl;\n          orb_file << size_of_basis << endl;\n          ReorderMOsBack(orbitals);\n          int level = 1;\n          int ncolumns = 3;\n          // write occupations as double in three columns\n          // occupied levels\n          int column = 1;\n          for (int i = 0; i < orbitals.getNumberOfElectrons(); i++) {\n            orb_file << FortranFormat(2.0);\n            if (column == ncolumns) {\n              orb_file << endl;\n              column = 0;\n            }\n            column++;\n          }\n          // unoccupied levels\n          for (int i = orbitals.getNumberOfElectrons(); i < size_of_basis; i++) {\n            orb_file << FortranFormat(0.0);\n            if (column == ncolumns) {\n              orb_file << endl;\n              column = 0;\n            }\n            column++;\n          }\n          // extra endl\n          if (column != 1) {\n            orb_file << endl;\n          }\n          \n          // write all energies in same format\n          column = 1;\n          for (int i=0;i<orbitals.MOEnergies().size();++i) {\n            double energy = (orbitals.MOEnergies())[i];\n            orb_file << FortranFormat(energy);\n            if (column == ncolumns) {\n              orb_file << endl;\n              column = 0;\n            }\n            column++;\n          }\n          if (column != 1) orb_file << endl;\n          \n          // write coefficients in same format\n          for (int i=0;i<orbitals.MOCoefficients().cols();++i) {\n            Eigen::VectorXd mr=orbitals.MOCoefficients().col(i);\n            column = 1;\n            for (unsigned j = 0; j < mr.size(); ++j) {\n              orb_file << FortranFormat(mr[j]);\n              if (column == ncolumns) {\n                orb_file << endl;\n                column = 0;\n              }\n              column++;\n            }\n            level++;\n            if (column != 1) orb_file << endl;\n          }\n          orb_file << \" 0.0000   0.0000\" << endl;\n          orb_file.close();\n          // now convert this ascii file to binary\n          std::string command;\n          command = \"cd \" + _run_dir + \"; asc2mov 5000 system.mos system.movecs > convert.log\";\n          int i = std::system(command.c_str());\n          if (i == 0) {\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Converted MO file from ascii to binary\" << flush;\n          } else {\n            CTP_LOG(ctp::logERROR, *_pLog) << \"Conversion of binary MO file to binary failed. \" << flush;\n            return false;\n          }\n          return true;\n        }\n\n        /**\n         * Prepares the *.nw file from a vector of segments\n         * Appends a guess constructed from monomer orbitals if supplied\n         */\n        bool NWChem::WriteInputFile(Orbitals& orbitals){\n\n           \n            std::string temp_suffix = \"/id\";\n            std::string scratch_dir_backup = _scratch_dir;\n            std::ofstream nw_file;\n            std::ofstream crg_file;\n\n            std::string nw_file_name_full = _run_dir + \"/\" + _input_file_name;\n            std::string crg_file_name_full = _run_dir + \"/background.crg\";\n\n            nw_file.open(nw_file_name_full.c_str());\n            // header\n            nw_file << \"geometry noautoz noautosym\" << endl;\n\n            std::vector< QMAtom* > qmatoms = orbitals.QMAtoms();\n          \n            for (const QMAtom* atom:qmatoms) {\n                tools::vec pos=atom->getPos()*tools::conv::bohr2ang;\n                    nw_file << setw(3) << atom->getType().c_str()\n                            << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getX()\n                            << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getY()\n                            << setw(12) << setiosflags(ios::fixed) << setprecision(5) << pos.getZ()\n                            << endl;      \n            }\n            nw_file << \"end\\n\";\n            if (_write_charges) {\n                // part for the MM charge coordinates\n                crg_file.open(crg_file_name_full.c_str());\n                int numberofcharges=WriteBackgroundCharges(crg_file);\n                crg_file << endl;\n                crg_file.close();\n                nw_file<<endl;\n                nw_file<<\"set bq:max_nbq \"<<numberofcharges<<endl;\n                nw_file<<\"bq background\"<<endl;\n                nw_file<<\"load background.crg format 1 2 3 4\"<<endl;\n                nw_file<<\"end\\n\"<<endl;\n            }\n            \n            if(_write_basis_set){\n              WriteBasisset(nw_file,qmatoms);\n            }\n            \n            if(_write_pseudopotentials){\n              WriteECP(nw_file,qmatoms);\n            }\n\n            // write charge of the molecule\n            nw_file << \"\\ncharge \" << _charge << \"\\n\";\n           \n            // writing scratch_dir info\n            if (_scratch_dir != \"\") {\n                std::string _temp(\"scratch_dir \" + _scratch_dir + temp_suffix + \"\\n\");\n                nw_file << _temp;\n            }\n            if(_charge!=0.0){\n              std::string dft=\"dft\";\n              if(_options.find(dft) != std::string::npos){\n                int dftpos=_options.find(dft);\n                dftpos+=dft.size();\n                std::string openshell=\"\\nodft\\n\" +(boost::format(\"mult %1%\\n\") % _spin).str();\n                _options.insert(dftpos,openshell,0,openshell.size());\n              }else{\n                throw runtime_error(\"NWCHEM: dft input data missing\");     \n              }\n            }\n            nw_file << _options << \"\\n\";\n            if (_write_guess) {         \n                 bool worked=WriteGuess(orbitals);\n                 if(!worked){\n                    return false;\n                 }   \n            }\n\n            nw_file << endl;\n            nw_file.close();\n            // and now generate a shell script to run both jobs, if neccessary\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Setting the scratch dir to \" << _scratch_dir + temp_suffix << flush;\n\n            _scratch_dir = scratch_dir_backup + temp_suffix;\n\n            WriteShellScript();\n            _scratch_dir = scratch_dir_backup;\n\n            return true;\n        }\n        \n\n        \n\n        bool NWChem::WriteShellScript() {\n            ofstream shell_file;\n            std::string shell_file_name_full = _run_dir + \"/\" + _shell_file_name;\n            shell_file.open(shell_file_name_full.c_str());\n            shell_file << \"#!/bin/bash\" << endl;\n            shell_file << \"mkdir -p \" << _scratch_dir << endl;\n            if (_threads == 1) {\n                shell_file << _executable << \" \" << _input_file_name << \" > \" << _log_file_name << \" 2> run.error\" << endl;\n            } else {\n                shell_file << \"mpirun -np \" << boost::lexical_cast<std::string>(_threads) << \" \" << _executable << \" \" << _input_file_name << \" > \" << _log_file_name << \" 2> run.error\" << endl;\n            }\n            shell_file.close();\n            return true;\n        }\n\n        /**\n         * Runs the NWChem job.\n         */\n        bool NWChem::Run( Orbitals& orbitals ) {\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Running NWChem job\" << flush;\n\n            if (std::system(NULL)) {\n\n                // NWChem overrides input information, if *.db and *.movecs files are present\n                // better trash the old version\n                std::string file_name = _run_dir + \"/system.db\";\n                remove(file_name.c_str());\n                file_name = _run_dir + \"/\" + _log_file_name;\n                remove(file_name.c_str());\n               \n                std::string command = \"cd \" + _run_dir + \"; sh \" + _shell_file_name;\n    \n                int check = std::system(command.c_str());\n                if (check == -1) {\n                    CTP_LOG(ctp::logERROR, *_pLog) << _input_file_name << \" failed to start\" << flush;\n                    return false;\n                }\n\n                if (CheckLogFile()) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Finished NWChem job\" << flush;\n                    return true;\n                } else {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"NWChem job failed\" << flush;\n                    return false;\n                }\n            } else {\n                CTP_LOG(ctp::logERROR, *_pLog) << _input_file_name << \" failed to start\" << flush;\n                return false;\n            }\n\n            return true;\n        }\n\n        /**\n         * Cleans up after the NWChem job\n         */\n        void NWChem::CleanUp() {\n\n            // cleaning up the generated files\n            if (_cleanup.size() != 0) {\n                tools::Tokenizer tok_cleanup(_cleanup, \",\");\n                std::vector <std::string> cleanup_info;\n                tok_cleanup.ToVector(cleanup_info);\n                for (const std::string& substring:cleanup_info) {\n                    if (substring== \"nw\") {\n                        std::string file_name = _run_dir + \"/\" + _input_file_name;\n                        remove(file_name.c_str());\n                    }\n\n                    if (substring == \"db\") {\n                        std::string file_name = _run_dir + \"/system.db\";\n                        remove(file_name.c_str());\n                    }\n\n                    if (substring == \"log\") {\n                        std::string file_name = _run_dir + \"/\" + _log_file_name;\n                        remove(file_name.c_str());\n                    }\n\n                    if (substring == \"movecs\") {\n                        std::string file_name = _run_dir + \"/\" + _orb_file_name;\n                        remove(file_name.c_str());\n                    }\n\n                    if (substring == \"gridpts\") {\n                        std::string file_name = _run_dir + \"/system.gridpts.*\";\n                        remove(file_name.c_str());\n                    }\n                }\n            }\n\n        }\n\n        /**\n         * Reads in the MO coefficients from a NWChem movecs file\n         */\n        bool NWChem::ParseOrbitalsFile(Orbitals& orbitals) {\n            std::map <int, std::vector<double> > coefficients;\n            std::map <int, double> energies;\n            std::map <int, double> occupancy;\n\n            std::string line;\n            unsigned levels = 0;\n            //unsigned _level;\n            unsigned basis_size = 0;\n            int number_of_electrons = 0;\n\n            /* maybe we DO need to convert from fortran binary to ASCII first to avoid\n             compiler-dependent issues */\n            std::string orb_file_name_bin = _run_dir + \"/\" + _orb_file_name;\n            std::string command;\n            command = \"cd \" + _run_dir + \"; mov2asc 10000 system.movecs system.mos > convert.log\";\n            int i = std::system(command.c_str());\n            if (i == 0) {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"Converted MO file from binary to ascii\" << flush;\n            } else {\n                CTP_LOG(ctp::logERROR, *_pLog) << \"Conversion of binary MO file to ascii failed. \" << flush;\n                return false;\n            }\n\n            // opening the ascii MO file\n            std::string orb_file_name_full = _run_dir + \"/\" + \"system.mos\";\n            std::ifstream input_file(orb_file_name_full.c_str());\n\n            if (input_file.fail()) {\n                CTP_LOG(ctp::logERROR, *_pLog) << \"File \" << orb_file_name_full << \" with molecular orbitals is not found \" << flush;\n                return false;\n            } else {\n                CTP_LOG(ctp::logDEBUG, *_pLog) << \"Reading MOs from \" << orb_file_name_full << flush;\n            }\n\n            // the first 12 lines are garbage info\n            for (i = 1; i < 13; i++) {\n                getline(input_file, line);\n            }\n            // next line has basis set size\n            input_file >> basis_size;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Basis set size: \" << basis_size << flush;\n\n\n            // next line has number of stored MOs\n            input_file >> levels;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Energy levels: \" << levels << flush;\n\n            /* next lines contain information about occupation of the MOs\n             *  - each line has 3 numbers\n             *  - from _occ we can determine the number of electrons/2 */\n            int n_lines = ((levels - 1) / 3);\n            int n_rest = levels - 3 * n_lines;\n            // read in the data\n            int imo = 0;\n            for (i = 1; i <= n_lines; i++) {\n                for (int j = 0; j < 3; j++) {\n                    input_file >> occupancy[ imo ];\n                    if (occupancy[ imo ] == 2.0) {\n                        number_of_electrons++;\n                    }\n                    imo++;\n                }\n            }\n            if (n_rest != 0) {\n                for (i = 0; i < n_rest; i++) {\n                    input_file >> occupancy[ imo ];\n                    imo++;\n                }\n            }\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Alpha electrons: \" << number_of_electrons << flush;\n\n            int occupied_levels = number_of_electrons;\n            int unoccupied_levels = levels - occupied_levels;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Occupied levels: \" << occupied_levels << flush;\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Unoccupied levels: \" << unoccupied_levels << flush;\n\n            // reset index and read MO energies the same way\n            imo = 0;\n            for (i = 1; i <= n_lines; i++) {\n                for (int j = 0; j < 3; j++) {\n                    input_file >> energies[ imo ];\n                    imo++;\n                }\n            }\n            if (n_rest != 0) {\n                for (i = 0; i < n_rest; i++) {\n                    input_file >> energies[ imo ];\n                    imo++;\n                }\n            }\n\n\n            // Now, the same for the coefficients\n            double coef;\n            for (unsigned imo = 0; imo < levels; imo++) {\n                for (i = 1; i <= n_lines; i++) {\n                    for (int j = 0; j < 3; j++) {\n                        input_file >> coef;\n                        coefficients[ imo ].push_back(coef);\n                    }\n                }\n                if (n_rest != 0) {\n                    for (i = 0; i < n_rest; i++) {\n                        input_file >> coef;\n                        coefficients[ imo ].push_back(coef);\n                    }\n                }\n            }\n\n\n\n\n            // copying information to the orbitals object\n            orbitals.setBasisSetSize(basis_size);\n            orbitals.setNumberOfElectrons(number_of_electrons);\n            orbitals.setNumberOfLevels(occupied_levels, unoccupied_levels);\n            // copying energies to a matrix\n            orbitals.MOEnergies().resize(levels);\n            //_level = 1;\n            for (int i = 0; i < orbitals.MOEnergies().size(); i++) {\n                orbitals.MOEnergies()[i] = energies[ i ];\n            }\n\n\n            // copying orbitals to the matrix\n            (orbitals.MOCoefficients()).resize(levels, basis_size);\n            for (int i = 0; i < orbitals.MOCoefficients().rows(); i++) {\n                for (int j = 0; j < orbitals.MOCoefficients().cols(); j++) {\n                    orbitals.MOCoefficients()(j, i) = coefficients[i][j];\n                }\n            }\n            \n            // when all is done, we can trash the ascii file\n            std::string file_name = _run_dir + \"/system.mos\";\n            remove(file_name.c_str());\n\n\n            ReorderOutput(orbitals);\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Done reading MOs\" << flush;\n\n            return true;\n        }\n\n        bool NWChem::CheckLogFile() {\n\n            // check if the log file exists\n            \n            ifstream input_file((_run_dir + \"/\" + _log_file_name).c_str());\n\n            if (input_file.fail()) {\n                CTP_LOG(ctp::logERROR, *_pLog) << \"NWChem LOG is not found\" << flush;\n                return false;\n            };\n\n            if (input_file.peek() == std::ifstream::traits_type::eof()) {\n                CTP_LOG(ctp::logERROR, *_pLog) << \"NWChem run failed. Check OpenMPI version!\" << flush;\n                return false;\n            };\n\n\n\n            /* Checking the log file is a pain in the *** since NWChem throws an error\n             * for our 'iterations 1'  runs (even though it outputs the required data\n             * correctly. The only way that works for both scf and noscf runs is to\n             * check for \"Total DFT energy\" near the end of the log file.\n             */\n\n            input_file.seekg(0, ios_base::end); // go to the EOF\n            char ch;\n            std::string::size_type total_energy_pos = std::string::npos;\n            std::string::size_type diis_pos = std::string::npos;\n            do {\n                // get the beginning of the line\n                do {\n                    input_file.seekg(-2, ios_base::cur);\n                    input_file.get(ch);\n                    //cout << \"\\nNext Char: \" << ch << \" TELL G \" <<  (int)_input_file.tellg() << endl;\n                } while (ch != '\\n' || (int) input_file.tellg() == -1);\n\n                std::string line;\n                getline(input_file, line); // Read the current line\n                total_energy_pos = line.find(\"Total DFT energy\");\n                diis_pos = line.find(\"diis\");\n                // whatever is found first, determines the completeness of the file\n                if (total_energy_pos != std::string::npos) {\n                    return true;\n                } else if (diis_pos != std::string::npos) {\n                    CTP_LOG(ctp::logERROR, *_pLog) << \"NWChem LOG is incomplete\" << flush;\n                    return false;\n                } else {\n                    // go to previous line\n                    //_input_file.get(ch);\n                    do {\n                        input_file.seekg(-2, ios_base::cur);\n                        input_file.get(ch);\n                        //cout << \"\\nChar: \" << ch << endl;\n                    } while (ch != '\\n' || (int) input_file.tellg() == -1);\n                }\n            } while (total_energy_pos == std::string::npos && diis_pos == std::string::npos);\n\n\n            input_file.close();\n            return true;\n        }\n\n        \n\n        /**\n         * Parses the Gaussian Log file and stores data in the Orbitals object\n         */\n        bool NWChem::ParseLogFile(Orbitals& orbitals) {\n\n            double conv_Hrt_eV = tools::conv::hrt2ev;\n\n            std::string line;\n            std::vector<std::string> results;\n\n            bool has_overlap_matrix = false;\n            bool has_charges = false;\n            bool has_qm_energy = false;\n            bool has_self_energy = false;\n            bool has_basis_set_size = false;\n\n            bool found_optimization = false;\n            int basis_set_size = 0;\n\n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Parsing \" << _log_file_name << flush;\n            std::string log_file_name_full = _run_dir + \"/\" + _log_file_name;\n            // check if LOG file is complete\n            if (!CheckLogFile()) return false;\n\n            // save qmpackage name\n            orbitals.setQMpackage(\"nwchem\");\n            orbitals.setDFTbasis(_basisset_name);\n\n\n\n            if (_write_pseudopotentials) {\n                orbitals.setECP(_ecp_name);\n            } \n            // set _found_optimization to true if this is a run without optimization\n            if (!_is_optimization) {\n                found_optimization = true;\n            }\n\n            // Start parsing the file line by line\n            ifstream input_file(log_file_name_full.c_str());\n            while (input_file) {\n\n                getline(input_file, line);\n                boost::trim(line);\n\n                /*\n                 * basis set size (is only required for overlap matrix reading, rest is\n                 * in orbitals file and could be skipped\n                 */\n                std::string::size_type basis_pos = line.find(\"number of functions\");\n                if (basis_pos != std::string::npos) {\n                    //cout << _line << endl;\n                    boost::algorithm::split(results, line, boost::is_any_of(\":\"), boost::algorithm::token_compress_on);\n                    has_basis_set_size = true;\n                    std::string bf = results.back();\n                    boost::trim(bf);\n                    basis_set_size = boost::lexical_cast<int>(bf);\n                    orbitals.setBasisSetSize(basis_set_size);\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Basis functions: \" << basis_set_size << flush;\n                }\n\n                /*\n                 * Total DFT energy\n                 */\n                std::string::size_type energy_pos = line.find(\"Total DFT energy\");\n                if (energy_pos != std::string::npos) {\n                    boost::algorithm::split(results, line, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n                    std::string energy = results.back();\n                    boost::trim(energy);\n                    orbitals.setQMEnergy(conv_Hrt_eV * boost::lexical_cast<double>(energy));\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << (boost::format(\"QM energy[eV]: %4.6f \") % orbitals.getQMEnergy()).str() << flush;\n                    has_qm_energy = true;\n                    // _orbitals._has_qm_energy = true;\n\n                }\n\n                /*\n                 *  Partial charges from the input file\n                 */\n                std::string::size_type charge_pos = line.find(\"ESP\");\n                if (charge_pos != std::string::npos && _get_charges) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Getting charges\" << flush;\n                    has_charges = true;\n                    // two empty lines\n                    getline(input_file, line);\n                    getline(input_file, line);\n\n                    // now starts the data in format\n                    // _id type x y z q\n\n                    std::vector<std::string> row=GetLineAndSplit(input_file, \"\\t \");\n                    int nfields = row.size();\n\n                    while (nfields == 6) {\n                        int atom_id = boost::lexical_cast< int >(row.at(0));\n                        std::string atom_type = row.at(1);\n                        double atom_charge = boost::lexical_cast< double >(row.at(5));\n                        row=GetLineAndSplit(input_file, \"\\t \");\n                        nfields = row.size();\n                        QMAtom* pAtom;\n                        if (orbitals.hasQMAtoms() == false) {\n                            pAtom =orbitals.AddAtom(atom_id - 1,atom_type,tools::vec(0.0));\n                        } else {\n                            pAtom = orbitals.QMAtoms().at(atom_id - 1);\n                        }\n                        pAtom->setPartialcharge(atom_charge);\n                        }\n                }\n\n\n                /*\n                 * Coordinates of the final configuration\n                 * depending on whether it is an optimization or not\n                 */\n\n\n                if (_is_optimization) {\n                    std::string::size_type optimize_pos = line.find(\"Optimization converged\");\n                    if (optimize_pos != std::string::npos) {\n                        found_optimization = true;\n                    }\n                }\n                \n\n                std::string::size_type coordinates_pos = line.find(\"Output coordinates\");\n\n                if (found_optimization && coordinates_pos != std::string::npos) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Getting the coordinates\" << flush;\n\n                    //_has_coordinates = true;\n                    bool has_QMAtoms = orbitals.hasQMAtoms();\n\n                    // three garbage lines\n                    getline(input_file, line);\n                    getline(input_file, line);\n                    getline(input_file, line);\n                    // now starts the data in format\n                    // _id type Qnuc x y z\n                     std::vector<std::string> row=GetLineAndSplit(input_file, \"\\t \");\n                    int nfields = row.size();\n                    \n                    while (nfields == 6) {\n                        int atom_id = boost::lexical_cast< int >(row.at(0))-1;\n                        std::string _atom_type = row.at(1);\n                        double x = boost::lexical_cast<double>(row.at(3));\n                        double y = boost::lexical_cast<double>(row.at(4));\n                        double z = boost::lexical_cast<double>(row.at(5));\n                        tools::vec pos=tools::vec(x,y,z);\n                        pos*=tools::conv::ang2bohr;\n                        if (has_QMAtoms == false) {\n                            orbitals.AddAtom(atom_id,_atom_type, pos);\n                        } else{\n                            QMAtom* pAtom = orbitals.QMAtoms().at(atom_id);\n                            pAtom->setPos(pos); \n                        }\n                        atom_id++;\n                        row=GetLineAndSplit(input_file, \"\\t \");\n                        nfields = row.size();\n                    }\n                }        \n                \n                /*\n                 * Vxc matrix\n                 * stored after the global array: g vxc\n                 */\n                if(_output_Vxc){\n                std::string::size_type vxc_pos = line.find(\"global array: g vxc\");\n                if (vxc_pos != std::string::npos) {\n\n\n                    // prepare the container\n                    Eigen::MatrixXd vxc = orbitals.AOVxc();\n                    vxc.resize(basis_set_size,basis_set_size);\n\n\n                    //_has_vxc_matrix = true;\n                    std::vector<int> j_indeces;\n\n                    int n_blocks = 1 + ((basis_set_size - 1) / 6);\n                    //cout << _n_blocks;\n\n                    for (int block = 0; block < n_blocks; block++) {\n                        // first line is garbage\n                        getline(input_file, line);\n                        // second line gives the j index in the matrix\n                        getline(input_file, line);\n                        boost::tokenizer<> tok(line);\n\n                        /// COMPILATION IS BROKEN DUE TO A BUG IN BOOST 1.53\n                        std::transform(tok.begin(), tok.end(), std::back_inserter(j_indeces), &boost::lexical_cast<int, std::string>);\n\n                        // third line is garbage again\n                        getline(input_file, line);\n\n                        // read the block of max _basis_size lines + the following header\n                        for (int i = 0; i < basis_set_size; i++) {\n                            std::vector<std::string> row=GetLineAndSplit(input_file, \"\\t \");\n                            int i_index = boost::lexical_cast<int>(row.front());\n                            row.erase(row.begin());\n\n                            std::vector<int>::iterator j_iter = j_indeces.begin();\n\n                            for (std::string& coefficient: row) {\n\n                                int j_index = *j_iter;\n                                vxc(i_index - 1, j_index - 1) = boost::lexical_cast<double>(coefficient);\n                                vxc(j_index - 1, i_index - 1) = boost::lexical_cast<double>(coefficient);\n                                j_iter++;\n\n                            }\n\n\n                        }\n\n                        // clear the index for the next block\n                        j_indeces.clear();\n                    } // end of the blocks\n                    \n                    \n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Read the Vxc matrix\" << flush;\n\n                }\n                }\n\n                /* Check for ScaHFX = factor of HF exchange included in functional */\n                std::string::size_type HFX_pos = line.find(\"Hartree-Fock (Exact) Exchange\");\n                if (HFX_pos != std::string::npos) {\n                    boost::algorithm::split(results, line, boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n                    double ScaHFX = boost::lexical_cast<double>(results.back());\n                    orbitals.setScaHFX(ScaHFX);\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"DFT with \" << ScaHFX << \" of HF exchange!\" << flush;\n                }\n\n\n\n\n                /*\n                 * overlap matrix\n                 * stored after the global array: Temp Over line\n                 */\n                std::string::size_type overlap_pos = line.find(\"global array: Temp Over\");\n                if (overlap_pos != std::string::npos) {\n\n                    // prepare the container\n                    (orbitals.AOOverlap()).resize(basis_set_size,basis_set_size);\n\n                    has_overlap_matrix = true;\n                    std::vector<int> j_indeces;\n\n                    int n_blocks = 1 + ((basis_set_size - 1) / 6);\n\n                    for (int block = 0; block < n_blocks; block++) {\n                        // first line is garbage\n                        getline(input_file, line);\n                        // second line gives the j index in the matrix\n                        getline(input_file, line);\n                        boost::tokenizer<> tok(line);\n\n                        /// COMPILATION IS BROKEN DUE TO A BUG IN BOOST 1.53\n                        std::transform(tok.begin(), tok.end(), std::back_inserter(j_indeces), &boost::lexical_cast<int, std::string>);\n\n                        // third line is garbage again\n                        getline(input_file, line);\n\n                        // read the block of max _basis_size lines + the following header\n                        for (int i = 0; i < basis_set_size; i++) {\n                            std::vector<std::string> row=GetLineAndSplit(input_file, \"\\t \");\n\n\n                            int i_index = boost::lexical_cast<int>(row.front());\n                            row.erase(row.begin());\n\n                            std::vector<int>::iterator j_iter = j_indeces.begin();\n\n                           for (std::string& coefficient: row) {\n                                int j_index = *j_iter;\n                                orbitals.AOOverlap()(i_index - 1, j_index - 1) = boost::lexical_cast<double>(coefficient);\n                                orbitals.AOOverlap()(j_index - 1, i_index - 1) = boost::lexical_cast<double>(coefficient);\n                                j_iter++;\n                            }\n\n\n                        }\n\n                        // clear the index for the next block\n                        j_indeces.clear();\n                    } // end of the blocks\n                    \n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Read the overlap matrix\" << flush;\n                } // end of the if \"Overlap\" found\n\n                /*\n                 * TODO Self-energy of external charges\n                 */\n                std::string::size_type self_energy_pos = line.find(\"Self energy of the charges\");\n\n                if (self_energy_pos != std::string::npos) {\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Getting the self energy\\n\";\n                    std::vector<std::string> block;\n                    std::vector<std::string> energy;\n                    boost::algorithm::split(block, line, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n                    boost::algorithm::split(energy, block[1], boost::is_any_of(\"\\t \"), boost::algorithm::token_compress_on);\n\n                    orbitals.setSelfEnergy(conv_Hrt_eV * boost::lexical_cast<double> (energy[1]));\n\n                    CTP_LOG(ctp::logDEBUG, *_pLog) << \"Self energy \" << orbitals.getSelfEnergy() << flush;\n\n                }\n\n                // check if all information has been accumulated and quit\n                if (has_basis_set_size &&\n                        has_overlap_matrix &&\n                        has_charges &&\n                        has_qm_energy &&\n                        has_self_energy\n                        ) break;\n\n            } // end of reading the file line-by-line\n            \n            CTP_LOG(ctp::logDEBUG, *_pLog) << \"Done parsing\" << flush;\n            return true;\n        }\n        \n        void NWChem::WriteBasisset(ofstream& nw_file, std::vector<QMAtom*>& qmatoms) {\n\n      std::vector<std::string> UniqueElements = FindUniqueElements(qmatoms);\n      BasisSet bs;\n      bs.LoadBasisSet(_basisset_name);\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \"Loaded Basis Set \" << _basisset_name << flush;\n      nw_file << \"basis spherical\" << endl;\n      for (const std::string& element_name : UniqueElements) {\n        const Element& element = bs.getElement(element_name);\n        for (const Shell& shell : element) {\n          //nwchem can only use S,P,SP,D,F,G shells so we split them up if not SP\n          if (!shell.isCombined()) {\n            // shell type, number primitives, scale factor\n            nw_file << element_name << \" \" << boost::algorithm::to_lower_copy(shell.getType()) << endl;\n            for (const GaussianPrimitive& gaussian : shell) {\n              for (unsigned _icontr = 0; _icontr < gaussian._contraction.size(); _icontr++) {\n                if (gaussian._contraction[_icontr] != 0.0) {\n                  nw_file << FortranFormat(gaussian._decay) << \" \" << FortranFormat(gaussian._contraction[_icontr]) << endl;\n                }\n              }\n            }\n          } else {\n            string type = shell.getType();\n            for (unsigned i = 0; i < type.size(); ++i) {\n              string subtype = string(type, i, 1);\n              nw_file << element_name << \" \" << boost::algorithm::to_lower_copy(subtype) << endl;\n\n              for (const GaussianPrimitive& gaussian : shell) {\n                nw_file << FortranFormat(gaussian._decay) << \" \" << FortranFormat(gaussian._contraction[FindLmax(subtype)]) << endl;\n              }\n            }\n          }\n        }\n      }\n      nw_file << \"end\\n\";\n      nw_file << endl;\n\n      return;\n    }\n        \n    void NWChem::WriteECP(ofstream& nw_file, std::vector<QMAtom*>& qmatoms) {\n\n      std::vector<std::string> UniqueElements = FindUniqueElements(qmatoms);\n\n      BasisSet ecp;\n      ecp.LoadPseudopotentialSet(_ecp_name);\n\n      CTP_LOG(ctp::logDEBUG, *_pLog) << \"Loaded Pseudopotentials \" << _ecp_name << flush;\n\n      for (const std::string& element_name : UniqueElements) {\n        try {\n          ecp.getElement(element_name);\n        } catch (std::runtime_error& error) {\n          CTP_LOG(ctp::logDEBUG, *_pLog) << \"No pseudopotential for \" << element_name << \" available\" << flush;\n          continue;\n        }\n        const Element& element = ecp.getElement(element_name);\n        // element name, [possibly indeces of centers], zero to indicate the end\n        nw_file << element_name << \" nelec \" << element.getNcore() << endl;\n        for (const Shell& shell : element) {\n          string shelltype = shell.getType();\n          if (shell.getLmax() == element.getLmax()) {\n            shelltype = \"ul\";\n          }\n          nw_file << element_name << \" \" << shelltype << endl;\n          for (const GaussianPrimitive& gaussian : shell) {\n            nw_file << \"    \" << gaussian._power << \" \" << FortranFormat(gaussian._decay) << \" \" << FortranFormat(gaussian._contraction[0]) << endl;\n          }\n        }\n      }\n      nw_file << \"end\\n\";\n      nw_file << endl;\n      return;\n    }\n\n             \n\n        std::string NWChem::FortranFormat(const double &number) {\n            std::stringstream ssnumber;\n            if (number >= 0) {\n                ssnumber << \"    \";\n            } else {\n                ssnumber << \"   \";\n            }\n            ssnumber << setiosflags(ios::fixed) << setprecision(15) << std::scientific << number;\n            std::string snumber = ssnumber.str();\n            return snumber;\n        }\n\n\n\n\n    }\n}\n", "meta": {"hexsha": "1443931902646c52c8331eebaeb1e286d70ab1c1", "size": 43375, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/qmpackages/nwchem.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/qmpackages/nwchem.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/qmpackages/nwchem.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9584513692, "max_line_length": 193, "alphanum_fraction": 0.4819827089, "num_tokens": 9583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706244, "lm_q2_score": 0.01941934850166898, "lm_q1q2_score": 0.004220553063701723}}
{"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, 2018, 2019.\r\n// Modifications copyright (c) 2017-2019, 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_INIT_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_INIT_HPP\r\n\r\n#include <cstdlib>\r\n#include <string>\r\n#include <vector>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n#include <boost/mpl/find.hpp>\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/range.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/condition.hpp>\r\n\r\n#include <boost/geometry/srs/projections/dpar.hpp>\r\n#include <boost/geometry/srs/projections/impl/dms_parser.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_datum_set.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_datums.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_ell_set.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_units.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/proj4.hpp>\r\n#include <boost/geometry/srs/projections/spar.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry { namespace projections\r\n{\r\n\r\n\r\nnamespace detail\r\n{\r\n\r\n/************************************************************************/\r\n/*                           pj_init_proj()                             */\r\n/************************************************************************/\r\n\r\ntemplate <typename T>\r\ninline void pj_init_proj(srs::detail::proj4_parameters const& params,\r\n                         parameters<T> & par)\r\n{\r\n    par.id = pj_get_param_s(params, \"proj\");\r\n}\r\n\r\ntemplate <typename T>\r\ninline void pj_init_proj(srs::dpar::parameters<T> const& params,\r\n                         parameters<T> & par)\r\n{\r\n    typename srs::dpar::parameters<T>::const_iterator it = pj_param_find(params, srs::dpar::proj);\r\n    if (it != params.end())\r\n    {\r\n        par.id = static_cast<srs::dpar::value_proj>(it->template get_value<int>());\r\n    }\r\n}\r\n\r\ntemplate <typename T, BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX>\r\ninline void pj_init_proj(srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& ,\r\n                         parameters<T> & par)\r\n{\r\n    typedef srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> params_type;\r\n    typedef typename geometry::tuples::find_if\r\n        <\r\n            params_type,\r\n            srs::spar::detail::is_param_tr<srs::spar::detail::proj_traits>::pred\r\n        >::type proj_type;\r\n\r\n    static const bool is_found = geometry::tuples::is_found<proj_type>::value;\r\n\r\n    BOOST_MPL_ASSERT_MSG((is_found), PROJECTION_NOT_NAMED, (params_type));\r\n\r\n    par.id = srs::spar::detail::proj_traits<proj_type>::id;\r\n}\r\n\r\n/************************************************************************/\r\n/*                           pj_init_units()                            */\r\n/************************************************************************/\r\n\r\ntemplate <typename T, bool Vertical>\r\ninline void pj_init_units(srs::detail::proj4_parameters const& params,\r\n                          T & to_meter,\r\n                          T & fr_meter,\r\n                          T const& default_to_meter,\r\n                          T const& default_fr_meter)\r\n{\r\n    std::string s;\r\n    std::string units = pj_get_param_s(params, Vertical ? \"vunits\" : \"units\");\r\n    if (! units.empty())\r\n    {\r\n        static const int n = sizeof(pj_units) / sizeof(pj_units[0]);\r\n        int index = -1;\r\n        for (int i = 0; i < n && index == -1; i++)\r\n        {\r\n            if(pj_units[i].id == units)\r\n            {\r\n                index = i;\r\n            }\r\n        }\r\n\r\n        if (index == -1) {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unknow_unit_id) );\r\n        }\r\n        s = pj_units[index].to_meter;\r\n    }\r\n\r\n    if (s.empty())\r\n    {\r\n        s = pj_get_param_s(params, Vertical ? \"vto_meter\" : \"to_meter\");\r\n    }\r\n\r\n    // TODO: numerator and denominator could be taken from pj_units\r\n    if (! s.empty())\r\n    {\r\n        std::size_t const pos = s.find('/');\r\n        if (pos == std::string::npos)\r\n        {\r\n            to_meter = geometry::str_cast<T>(s);\r\n        }\r\n        else\r\n        {\r\n            T const numerator = geometry::str_cast<T>(s.substr(0, pos));\r\n            T const denominator = geometry::str_cast<T>(s.substr(pos + 1));\r\n            if (numerator == 0.0 || denominator == 0.0)\r\n            {\r\n                BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );\r\n            }\r\n            to_meter = numerator / denominator;\r\n        }\r\n        if (to_meter == 0.0)\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );\r\n        }\r\n        fr_meter = 1. / to_meter;\r\n    }\r\n    else\r\n    {\r\n        to_meter = default_to_meter;\r\n        fr_meter = default_fr_meter;\r\n    }\r\n}\r\n\r\ntemplate <typename T, bool Vertical>\r\ninline void pj_init_units(srs::dpar::parameters<T> const& params,\r\n                          T & to_meter,\r\n                          T & fr_meter,\r\n                          T const& default_to_meter,\r\n                          T const& default_fr_meter)\r\n{\r\n    typename srs::dpar::parameters<T>::const_iterator\r\n        it = pj_param_find(params, Vertical ? srs::dpar::vunits : srs::dpar::units);\r\n    if (it != params.end())\r\n    {\r\n        static const int n = sizeof(pj_units) / sizeof(pj_units[0]);\r\n        const int i = it->template get_value<int>();\r\n        if (i >= 0 && i < n)\r\n        {\r\n            T const numerator = pj_units[i].numerator;\r\n            T const denominator = pj_units[i].denominator;\r\n            if (numerator == 0.0 || denominator == 0.0)\r\n            {\r\n                BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );\r\n            }\r\n            to_meter = numerator / denominator;\r\n            fr_meter = 1. / to_meter;\r\n        }\r\n        else\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unknow_unit_id) );\r\n        }\r\n    }\r\n    else\r\n    {\r\n        it = pj_param_find(params, Vertical ? srs::dpar::vto_meter : srs::dpar::to_meter);\r\n        if (it != params.end())\r\n        {\r\n            to_meter = it->template get_value<T>();\r\n            fr_meter = 1. / to_meter;\r\n        }\r\n        else\r\n        {\r\n            to_meter = default_to_meter;\r\n            fr_meter = default_fr_meter;\r\n        }\r\n    }\r\n}\r\n\r\ntemplate\r\n<\r\n    typename Params,\r\n    bool Vertical,\r\n    int UnitsI = geometry::tuples::find_index_if\r\n        <\r\n            Params,\r\n            boost::mpl::if_c\r\n                <\r\n                    Vertical,\r\n                    srs::spar::detail::is_param_t<srs::spar::vunits>,\r\n                    srs::spar::detail::is_param_tr<srs::spar::detail::units_traits>\r\n                >::type::template pred\r\n        >::value,\r\n    int ToMeterI = geometry::tuples::find_index_if\r\n        <\r\n            Params,\r\n            boost::mpl::if_c\r\n                <\r\n                    Vertical,\r\n                    srs::spar::detail::is_param_t<srs::spar::vto_meter>,\r\n                    srs::spar::detail::is_param_t<srs::spar::to_meter>\r\n                >::type::template pred\r\n        >::value,\r\n    int N = boost::tuples::length<Params>::value\r\n>\r\nstruct pj_init_units_static\r\n    : pj_init_units_static<Params, Vertical, UnitsI, N, N>\r\n{};\r\n\r\ntemplate <typename Params, bool Vertical, int UnitsI, int N>\r\nstruct pj_init_units_static<Params, Vertical, UnitsI, N, N>\r\n{\r\n    static const int n = sizeof(pj_units) / sizeof(pj_units[0]);\r\n    static const int i = srs::spar::detail::units_traits\r\n                    <\r\n                        typename boost::tuples::element<UnitsI, Params>::type\r\n                    >::id;\r\n    static const bool is_valid = i >= 0 && i < n;\r\n\r\n    BOOST_MPL_ASSERT_MSG((is_valid), UNKNOWN_UNIT_ID, (Params));\r\n\r\n    template <typename T>\r\n    static void apply(Params const& ,\r\n                      T & to_meter, T & fr_meter,\r\n                      T const& , T const& )\r\n    {\r\n        T const numerator = pj_units[i].numerator;\r\n        T const denominator = pj_units[i].denominator;\r\n        if (numerator == 0.0 || denominator == 0.0)\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );\r\n        }\r\n        to_meter = numerator / denominator;\r\n        fr_meter = 1. / to_meter;\r\n    }\r\n};\r\n\r\ntemplate <typename Params, bool Vertical, int ToMeterI, int N>\r\nstruct pj_init_units_static<Params, Vertical, N, ToMeterI, N>\r\n{\r\n    template <typename T>\r\n    static void apply(Params const& params,\r\n                      T & to_meter, T & fr_meter,\r\n                      T const& , T const& )\r\n    {\r\n        to_meter = boost::tuples::get<ToMeterI>(params).value;\r\n        fr_meter = 1. / to_meter;\r\n    }\r\n};\r\n\r\ntemplate <typename Params, bool Vertical, int N>\r\nstruct pj_init_units_static<Params, Vertical, N, N, N>\r\n{\r\n    template <typename T>\r\n    static void apply(Params const& ,\r\n                      T & to_meter, T & fr_meter,\r\n                      T const& default_to_meter, T const& default_fr_meter)\r\n    {\r\n        to_meter = default_to_meter;\r\n        fr_meter = default_fr_meter;\r\n    }\r\n};\r\n\r\ntemplate <typename T, bool Vertical, BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX>\r\ninline void pj_init_units(srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& params,\r\n                          T & to_meter,\r\n                          T & fr_meter,\r\n                          T const& default_to_meter,\r\n                          T const& default_fr_meter)\r\n{\r\n    pj_init_units_static\r\n        <\r\n            srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX>,\r\n            Vertical\r\n        >::apply(params, to_meter, fr_meter, default_to_meter, default_fr_meter);\r\n}\r\n\r\n/************************************************************************/\r\n/*                           pj_init_pm()                               */\r\n/************************************************************************/\r\n\r\ntemplate <typename T>\r\ninline void pj_init_pm(srs::detail::proj4_parameters const& params, T& val)\r\n{\r\n    std::string pm = pj_get_param_s(params, \"pm\");\r\n    if (! pm.empty())\r\n    {\r\n        int n = sizeof(pj_prime_meridians) / sizeof(pj_prime_meridians[0]);\r\n        for (int i = 0; i < n ; i++)\r\n        {\r\n            if(pj_prime_meridians[i].id == pm)\r\n            {\r\n                val = pj_prime_meridians[i].deg * math::d2r<T>();\r\n                return;\r\n            }\r\n        }\r\n\r\n        // TODO: Is this try-catch needed?\r\n        // In other cases the bad_str_cast exception is simply thrown\r\n        BOOST_TRY\r\n        {\r\n            val = dms_parser<T, true>::apply(pm).angle();\r\n            return;\r\n        }\r\n        BOOST_CATCH(geometry::bad_str_cast const&)\r\n        {\r\n            BOOST_THROW_EXCEPTION( projection_exception(error_unknown_prime_meridian) );\r\n        }\r\n        BOOST_CATCH_END\r\n    }\r\n    \r\n    val = 0.0;\r\n}\r\n\r\ntemplate <typename T>\r\ninline void pj_init_pm(srs::dpar::parameters<T> const& params, T& val)\r\n{\r\n    typename srs::dpar::parameters<T>::const_iterator it = pj_param_find(params, srs::dpar::pm);\r\n    if (it != params.end())\r\n    {\r\n        if (it->template is_value_set<int>())\r\n        {\r\n            int n = sizeof(pj_prime_meridians) / sizeof(pj_prime_meridians[0]);\r\n            int i = it->template get_value<int>();\r\n            if (i >= 0 && i < n)\r\n            {\r\n                val = pj_prime_meridians[i].deg * math::d2r<T>();\r\n                return;\r\n            }\r\n            else\r\n            {\r\n                BOOST_THROW_EXCEPTION( projection_exception(error_unknown_prime_meridian) );\r\n            }\r\n        }\r\n        else if (it->template is_value_set<T>())\r\n        {\r\n            val = it->template get_value<T>() * math::d2r<T>();\r\n            return;\r\n        }\r\n    }\r\n\r\n    val = 0.0;\r\n}\r\n\r\ntemplate\r\n<\r\n    typename Params,\r\n    int I = geometry::tuples::find_index_if\r\n        <\r\n            Params,\r\n            srs::spar::detail::is_param_tr<srs::spar::detail::pm_traits>::pred\r\n        >::value,\r\n    int N = boost::tuples::length<Params>::value\r\n>\r\nstruct pj_init_pm_static\r\n{\r\n    template <typename T>\r\n    static void apply(Params const& params, T & val)\r\n    {\r\n        typedef typename boost::tuples::element<I, Params>::type param_type;\r\n\r\n        val = srs::spar::detail::pm_traits<param_type>::value(boost::tuples::get<I>(params));\r\n    }\r\n};\r\ntemplate <typename Params, int N>\r\nstruct pj_init_pm_static<Params, N, N>\r\n{\r\n    template <typename T>\r\n    static void apply(Params const& , T & val)\r\n    {\r\n        val = 0;\r\n    }\r\n};\r\n\r\ntemplate <typename T, BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX>\r\ninline void pj_init_pm(srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& params, T& val)\r\n{\r\n    pj_init_pm_static\r\n        <\r\n            srs::spar::parameters<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX>\r\n        >::apply(params, val);\r\n}\r\n\r\n/************************************************************************/\r\n/*                              pj_init()                               */\r\n/*                                                                      */\r\n/*      Main entry point for initialing a PJ projections                */\r\n/*      definition.                                                     */\r\n/************************************************************************/\r\ntemplate <typename T, typename Params>\r\ninline parameters<T> pj_init(Params const& params)\r\n{\r\n    parameters<T> pin;\r\n\r\n    // find projection -> implemented in projection factory\r\n    pj_init_proj(params, pin);\r\n    // exception thrown in projection<>\r\n    // TODO: consider throwing here both projection_unknown_id_exception and\r\n    // projection_not_named_exception in order to throw before other exceptions\r\n    //if (pin.name.empty())\r\n    //{ BOOST_THROW_EXCEPTION( projection_not_named_exception() ); }\r\n\r\n    // NOTE: proj4 gets defaults from \"proj_def.dat\".\r\n    // In Boost.Geometry this is emulated by manually setting them in\r\n    // pj_ell_init and projections aea, lcc and lagrng\r\n    \r\n    /* set datum parameters */\r\n    pj_datum_init(params, pin);\r\n\r\n    /* set ellipsoid/sphere parameters */\r\n    pj_ell_init(params, pin.a, pin.es);\r\n\r\n    pin.a_orig = pin.a;\r\n    pin.es_orig = pin.es;\r\n\r\n    pin.e = sqrt(pin.es);\r\n    pin.ra = 1. / pin.a;\r\n    pin.one_es = 1. - pin.es;\r\n    if (pin.one_es == 0.) {\r\n        BOOST_THROW_EXCEPTION( projection_exception(error_eccentricity_is_one) );\r\n    }\r\n    pin.rone_es = 1./pin.one_es;\r\n\r\n    /* Now that we have ellipse information check for WGS84 datum */\r\n    if( pin.datum_type == datum_3param\r\n        && pin.datum_params[0] == 0.0\r\n        && pin.datum_params[1] == 0.0\r\n        && pin.datum_params[2] == 0.0\r\n        && pin.a == 6378137.0\r\n        && geometry::math::abs(pin.es - 0.006694379990) < 0.000000000050 )/*WGS84/GRS80*/\r\n    {\r\n        pin.datum_type = datum_wgs84;\r\n    }\r\n\r\n    /* set pin.geoc coordinate system */\r\n    pin.geoc = (pin.es && pj_get_param_b<srs::spar::geoc>(params, \"geoc\", srs::dpar::geoc));\r\n\r\n    /* over-ranging flag */\r\n    pin.over = pj_get_param_b<srs::spar::over>(params, \"over\", srs::dpar::over);\r\n\r\n    /* longitude center for wrapping */\r\n    pin.is_long_wrap_set = pj_param_r<srs::spar::lon_wrap>(params, \"lon_wrap\", srs::dpar::lon_wrap, pin.long_wrap_center);\r\n\r\n    /* central meridian */\r\n    pin.lam0 = pj_get_param_r<T, srs::spar::lon_0>(params, \"lon_0\", srs::dpar::lon_0);\r\n\r\n    /* central latitude */\r\n    pin.phi0 = pj_get_param_r<T, srs::spar::lat_0>(params, \"lat_0\", srs::dpar::lat_0);\r\n\r\n    /* false easting and northing */\r\n    pin.x0 = pj_get_param_f<T, srs::spar::x_0>(params, \"x_0\", srs::dpar::x_0);\r\n    pin.y0 = pj_get_param_f<T, srs::spar::y_0>(params, \"y_0\", srs::dpar::y_0);\r\n\r\n    /* general scaling factor */\r\n    if (pj_param_f<srs::spar::k_0>(params, \"k_0\", srs::dpar::k_0, pin.k0)) {\r\n        /* empty */\r\n    } else if (pj_param_f<srs::spar::k>(params, \"k\", srs::dpar::k, pin.k0)) {\r\n        /* empty */\r\n    } else\r\n        pin.k0 = 1.;\r\n    if (pin.k0 <= 0.) {\r\n        BOOST_THROW_EXCEPTION( projection_exception(error_k_less_than_zero) );\r\n    }\r\n\r\n    /* set units */\r\n    pj_init_units<T, false>(params, pin.to_meter, pin.fr_meter, 1., 1.);\r\n    pj_init_units<T, true>(params, pin.vto_meter, pin.vfr_meter, pin.to_meter, pin.fr_meter);\r\n\r\n    /* prime meridian */\r\n    pj_init_pm(params, pin.from_greenwich);\r\n\r\n    return pin;\r\n}\r\n\r\n\r\n} // namespace detail\r\n}}} // namespace boost::geometry::projections\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_INIT_HPP\r\n", "meta": {"hexsha": "c8d51b32b0ecc65f6f61857022813c30d28420ee", "size": 18571, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/srs/projections/impl/pj_init.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/geometry/srs/projections/impl/pj_init.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/geometry/srs/projections/impl/pj_init.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": 35.3060836502, "max_line_length": 123, "alphanum_fraction": 0.565397663, "num_tokens": 4368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238002450622283, "lm_q2_score": 0.0259573572919855, "lm_q1q2_score": 0.004214956313189387}}
{"text": "#ifndef CMDSTAN_COMMAND_HPP\n#define CMDSTAN_COMMAND_HPP\n\n#include <boost/date_time/posix_time/posix_time_types.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/random/additive_combine.hpp>  // L'Ecuyer RNG\n#include <boost/random/uniform_real_distribution.hpp>\n\n#include <stan/version.hpp>\n#include <stan/io/cmd_line.hpp>\n#include <stan/io/dump.hpp>\n#include <stan/io/json/json_data.hpp>\n#include <stan/io/json/json_data_handler.hpp>\n#include <stan/io/json/json_error.hpp>\n#include <stan/io/json/json_handler.hpp>\n#include <stan/io/json/json_parser.hpp>\n\n#include <stan/services/arguments/arg_adapt.hpp>\n#include <stan/services/arguments/arg_adapt_delta.hpp>\n#include <stan/services/arguments/arg_adapt_engaged.hpp>\n#include <stan/services/arguments/arg_adapt_gamma.hpp>\n#include <stan/services/arguments/arg_adapt_init_buffer.hpp>\n#include <stan/services/arguments/arg_adapt_kappa.hpp>\n#include <stan/services/arguments/arg_adapt_t0.hpp>\n#include <stan/services/arguments/arg_adapt_term_buffer.hpp>\n#include <stan/services/arguments/arg_adapt_window.hpp>\n#include <stan/services/arguments/arg_bfgs.hpp>\n#include <stan/services/arguments/arg_data.hpp>\n#include <stan/services/arguments/arg_data_file.hpp>\n#include <stan/services/arguments/arg_dense_e.hpp>\n#include <stan/services/arguments/arg_diag_e.hpp>\n#include <stan/services/arguments/arg_diagnose.hpp>\n#include <stan/services/arguments/arg_diagnostic_file.hpp>\n#include <stan/services/arguments/arg_engine.hpp>\n#include <stan/services/arguments/arg_fail.hpp>\n#include <stan/services/arguments/arg_fixed_param.hpp>\n#include <stan/services/arguments/arg_history_size.hpp>\n#include <stan/services/arguments/arg_hmc.hpp>\n#include <stan/services/arguments/arg_id.hpp>\n#include <stan/services/arguments/arg_init.hpp>\n#include <stan/services/arguments/arg_init_alpha.hpp>\n#include <stan/services/arguments/arg_int_time.hpp>\n#include <stan/services/arguments/arg_iter.hpp>\n#include <stan/services/arguments/arg_lbfgs.hpp>\n#include <stan/services/arguments/arg_max_depth.hpp>\n#include <stan/services/arguments/arg_method.hpp>\n#include <stan/services/arguments/arg_metric.hpp>\n#include <stan/services/arguments/arg_newton.hpp>\n#include <stan/services/arguments/arg_num_samples.hpp>\n#include <stan/services/arguments/arg_num_warmup.hpp>\n#include <stan/services/arguments/arg_nuts.hpp>\n#include <stan/services/arguments/arg_optimize.hpp>\n#include <stan/services/arguments/arg_optimize_algo.hpp>\n#include <stan/services/arguments/arg_output.hpp>\n#include <stan/services/arguments/arg_output_file.hpp>\n#include <stan/services/arguments/arg_random.hpp>\n#include <stan/services/arguments/arg_refresh.hpp>\n#include <stan/services/arguments/arg_rwm.hpp>\n#include <stan/services/arguments/arg_sample.hpp>\n#include <stan/services/arguments/arg_sample_algo.hpp>\n#include <stan/services/arguments/arg_save_iterations.hpp>\n#include <stan/services/arguments/arg_save_warmup.hpp>\n#include <stan/services/arguments/arg_seed.hpp>\n#include <stan/services/arguments/arg_static.hpp>\n#include <stan/services/arguments/arg_stepsize.hpp>\n#include <stan/services/arguments/arg_stepsize_jitter.hpp>\n#include <stan/services/arguments/arg_test.hpp>\n#include <stan/services/arguments/arg_test_grad_eps.hpp>\n#include <stan/services/arguments/arg_test_grad_err.hpp>\n#include <stan/services/arguments/arg_test_gradient.hpp>\n#include <stan/services/arguments/arg_thin.hpp>\n#include <stan/services/arguments/arg_tolerance.hpp>\n#include <stan/services/arguments/arg_unit_e.hpp>\n#include <stan/services/arguments/argument.hpp>\n#include <stan/services/arguments/argument_parser.hpp>\n#include <stan/services/arguments/argument_probe.hpp>\n#include <stan/services/arguments/categorical_argument.hpp>\n#include <stan/services/arguments/list_argument.hpp>\n#include <stan/services/arguments/singleton_argument.hpp>\n#include <stan/services/arguments/unvalued_argument.hpp>\n#include <stan/services/arguments/valued_argument.hpp>\n#include <stan/services/sample/mcmc_writer.hpp>\n#include <stan/mcmc/fixed_param_sampler.hpp>\n#include <stan/mcmc/hmc/static/adapt_unit_e_static_hmc.hpp>\n#include <stan/mcmc/hmc/static/adapt_diag_e_static_hmc.hpp>\n#include <stan/mcmc/hmc/static/adapt_dense_e_static_hmc.hpp>\n#include <stan/mcmc/hmc/nuts/adapt_unit_e_nuts.hpp>\n#include <stan/mcmc/hmc/nuts/adapt_diag_e_nuts.hpp>\n#include <stan/mcmc/hmc/nuts/adapt_dense_e_nuts.hpp>\n\n#include <stan/model/gradient.hpp>\n#include <stan/model/test_gradients.hpp>\n\n#include <stan/optimization/newton.hpp>\n#include <stan/optimization/bfgs.hpp>\n\n#include <stan/variational/advi.hpp>\n\n#include <stan/services/init/initialize_state.hpp>\n#include <stan/services/io/do_print.hpp>\n#include <stan/services/io/write_error_msg.hpp>\n#include <stan/services/io/write_iteration.hpp>\n#include <stan/services/io/write_model.hpp>\n#include <stan/services/io/write_stan.hpp>\n#include <stan/services/mcmc/sample.hpp>\n#include <stan/services/mcmc/warmup.hpp>\n#include <stan/services/optimize/do_bfgs_optimize.hpp>\n#include <stan/services/sample/init_adapt.hpp>\n#include <stan/services/sample/init_nuts.hpp>\n#include <stan/services/sample/init_static_hmc.hpp>\n#include <stan/services/sample/init_windowed_adapt.hpp>\n#include <stan/services/sample/generate_transitions.hpp>\n#include <stan/services/sample/progress.hpp>\n\n#include <stan/interface_callbacks/interrupt/noop.hpp>\n#include <stan/interface_callbacks/var_context_factory/dump_factory.hpp>\n#include <stan/interface_callbacks/writer/base_writer.hpp>\n#include <stan/interface_callbacks/writer/stream_writer.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace stan {\n  namespace services {\n\n    class null_fstream : public std::fstream {\n    public:\n      null_fstream() {}\n    };\n\n    template <class Model>\n    int command(int argc, const char* argv[]) {\n      stan::interface_callbacks::writer::stream_writer info(std::cout);\n      stan::interface_callbacks::writer::stream_writer err(std::cout);\n      \n      std::vector<stan::services::argument*> valid_arguments;\n      valid_arguments.push_back(new stan::services::arg_id());\n      valid_arguments.push_back(new stan::services::arg_data());\n      valid_arguments.push_back(new stan::services::arg_init());\n      valid_arguments.push_back(new stan::services::arg_random());\n      valid_arguments.push_back(new stan::services::arg_output());\n\n      stan::services::argument_parser parser(valid_arguments);\n      int err_code = parser.parse_args(argc, argv, info, err);\n      if (err_code != 0) {\n        std::cout << \"Failed to parse arguments, terminating Stan\" << std::endl;\n        return err_code;\n      }\n\n      if (parser.help_printed())\n        return err_code;\n\n      //////////////////////////////////////////////////\n      //                  Input/Output                //\n      //////////////////////////////////////////////////\n\n      // Data input\n      std::string data_file\n        = dynamic_cast<stan::services::string_argument*>\n        (parser.arg(\"data\")->arg(\"file\"))->value();\n\n      std::fstream data_stream(data_file.c_str(),\n                               std::fstream::in);\n      if (data_file != \"\" && (data_stream.rdstate() & std::ifstream::failbit)) {\n        std::cout << std::endl;\n        std::cout << \"Can't open specified data file, \\\"\" << data_file << \"\\\"\" << std::endl;\n        return stan::services::error_codes::NOINPUT;\n      }\n      stan::io::dump data_var_context(data_stream);\n      data_stream.close();\n      \n      // Sample output\n      std::string output_file = dynamic_cast<stan::services::string_argument*>(\n                                parser.arg(\"output\")->arg(\"file\"))->value();\n      std::fstream* output_stream = 0;\n      if (output_file != \"\") {\n        output_stream = new std::fstream(output_file.c_str(),\n                                         std::fstream::out);\n      } else {\n        output_stream = new null_fstream();\n      }\n\n      \n      // Diagnostic output\n      std::string diagnostic_file\n        = dynamic_cast<stan::services::string_argument*>\n          (parser.arg(\"output\")->arg(\"diagnostic_file\"))->value();\n\n      std::fstream* diagnostic_stream = 0;\n      if (diagnostic_file != \"\") {\n        diagnostic_stream = new std::fstream(diagnostic_file.c_str(),\n                                             std::fstream::out);\n      } else {\n        diagnostic_stream = new null_fstream();\n      }\n\n      // Refresh rate\n      int refresh = dynamic_cast<stan::services::int_argument*>(\n                    parser.arg(\"output\")->arg(\"refresh\"))->value();\n      \n      // Identification\n      unsigned int id = dynamic_cast<stan::services::int_argument*>\n        (parser.arg(\"id\"))->value();\n\n      stan::interface_callbacks::writer::stream_writer\n        sample_writer(*output_stream, \"# \"),\n        diagnostic_writer(*diagnostic_stream, \"# \");\n\n      //////////////////////////////////////////////////\n      //            Random number generator           //\n      //////////////////////////////////////////////////\n\n      unsigned int random_seed = 0;\n\n      stan::services::u_int_argument* random_arg\n        = dynamic_cast<stan::services::u_int_argument*>\n        (parser.arg(\"random\")->arg(\"seed\"));\n\n      if (random_arg->is_default()) {\n        random_seed\n          = (boost::posix_time::microsec_clock::universal_time() -\n             boost::posix_time::ptime(boost::posix_time::min_date_time))\n          .total_milliseconds();\n\n        random_arg->set_value(random_seed);\n\n      } else {\n        random_seed = random_arg->value();\n      }\n\n      typedef boost::ecuyer1988 rng_t;  // (2**50 = 1T samples, 1000 chains)\n      rng_t base_rng(random_seed);\n\n      // Advance generator to avoid process conflicts\n      static boost::uintmax_t DISCARD_STRIDE\n        = static_cast<boost::uintmax_t>(1) << 50;\n      base_rng.discard(DISCARD_STRIDE * (id - 1));\n\n\n      //////////////////////////////////////////////////\n      //                Initialize Model              //\n      //////////////////////////////////////////////////\n\n      Model model(data_var_context, &std::cout);\n\n      Eigen::VectorXd cont_params = Eigen::VectorXd::Zero(model.num_params_r());\n\n      parser.print(info);\n      info();\n      \n      if (output_stream) {\n        io::write_stan(sample_writer);\n        io::write_model(sample_writer, model.model_name());\n        parser.print(sample_writer);\n      }\n\n      if (diagnostic_stream) {\n        io::write_stan(diagnostic_writer);\n        io::write_model(diagnostic_writer, model.model_name());\n        parser.print(diagnostic_writer);\n      }\n\n      std::string init = dynamic_cast<stan::services::string_argument*>(\n                         parser.arg(\"init\"))->value();\n\n      interface_callbacks::var_context_factory::dump_factory var_context_factory;\n      if (!init::initialize_state<interface_callbacks::var_context_factory::dump_factory>\n          (init, cont_params, model, base_rng, info,\n           var_context_factory))\n        return stan::services::error_codes::SOFTWARE;\n\n      //////////////////////////////////////////////////\n      //               Model Diagnostics              //\n      //////////////////////////////////////////////////\n\n      if (parser.arg(\"method\")->arg(\"diagnose\")) {\n        std::vector<double> cont_vector(cont_params.size());\n        for (int i = 0; i < cont_params.size(); ++i)\n          cont_vector.at(i) = cont_params(i);\n        std::vector<int> disc_vector;\n\n        stan::services::list_argument* test = dynamic_cast<stan::services::list_argument*>\n                              (parser.arg(\"method\")->arg(\"diagnose\")->arg(\"test\"));\n\n        if (test->value() == \"gradient\") {\n          std::cout << std::endl << \"TEST GRADIENT MODE\" << std::endl;\n\n          double epsilon = dynamic_cast<stan::services::real_argument*>\n                           (test->arg(\"gradient\")->arg(\"epsilon\"))->value();\n\n          double error = dynamic_cast<stan::services::real_argument*>\n                         (test->arg(\"gradient\")->arg(\"error\"))->value();\n\n          int num_failed\n            = stan::model::test_gradients<true, true>\n            (model, cont_vector, disc_vector,\n             epsilon, error, info);\n\n          if (output_stream) {\n            num_failed\n              = stan::model::test_gradients<true, true>\n              (model, cont_vector, disc_vector,\n               epsilon, error, sample_writer);\n          }\n\n          if (diagnostic_stream) {\n            num_failed\n              = stan::model::test_gradients<true, true>\n              (model, cont_vector, disc_vector,\n               epsilon, error, diagnostic_writer);\n          }\n\n          (void) num_failed; // FIXME: do something with the number failed\n\n          return stan::services::error_codes::OK;\n\n        }\n      }\n\n      //////////////////////////////////////////////////\n      //           Optimization Algorithms            //\n      //////////////////////////////////////////////////\n\n      if (parser.arg(\"method\")->arg(\"optimize\")) {\n        std::vector<double> cont_vector(cont_params.size());\n        for (int i = 0; i < cont_params.size(); ++i)\n          cont_vector.at(i) = cont_params(i);\n        std::vector<int> disc_vector;\n\n        stan::services::list_argument* algo = dynamic_cast<stan::services::list_argument*>\n                              (parser.arg(\"method\")->arg(\"optimize\")->arg(\"algorithm\"));\n\n        int num_iterations = dynamic_cast<stan::services::int_argument*>(\n                             parser.arg(\"method\")->arg(\"optimize\")->arg(\"iter\"))->value();\n\n        bool save_iterations\n          = dynamic_cast<stan::services::bool_argument*>(parser.arg(\"method\")\n                                         ->arg(\"optimize\")\n                                         ->arg(\"save_iterations\"))->value();\n        if (output_stream) {\n          std::vector<std::string> names;\n          names.push_back(\"lp__\");\n          model.constrained_param_names(names, true, true);\n\n          (*output_stream) << names.at(0);\n          for (size_t i = 1; i < names.size(); ++i) {\n            (*output_stream) << \",\" << names.at(i);\n          }\n          (*output_stream) << std::endl;\n        }\n\n        double lp(0);\n        int return_code = stan::services::error_codes::CONFIG;\n        if (algo->value() == \"newton\") {\n          std::vector<double> gradient;\n          try {\n            lp = model.template log_prob<false, false>\n              (cont_vector, disc_vector, &std::cout);\n          } catch (const std::exception& e) {\n            io::write_error_msg(err, e);\n            lp = -std::numeric_limits<double>::infinity();\n          }\n\n          std::cout << \"initial log joint probability = \" << lp << std::endl;\n          if (save_iterations) {\n            io::write_iteration(model, base_rng,\n                                lp, cont_vector, disc_vector,\n                                info, sample_writer);\n          }\n\n          double lastlp = lp * 1.1;\n          int m = 0;\n          std::cout << \"(lp - lastlp) / lp > 1e-8: \"\n                    << ((lp - lastlp) / fabs(lp)) << std::endl;\n          while ((lp - lastlp) / fabs(lp) > 1e-8) {\n            lastlp = lp;\n            lp = stan::optimization::newton_step\n              (model, cont_vector, disc_vector);\n            std::cout << \"Iteration \";\n            std::cout << std::setw(2) << (m + 1) << \". \";\n            std::cout << \"Log joint probability = \" << std::setw(10) << lp;\n            std::cout << \". Improved by \" << (lp - lastlp) << \".\";\n            std::cout << std::endl;\n            std::cout.flush();\n            m++;\n\n            if (save_iterations) {\n              io::write_iteration(model, base_rng,\n                                  lp, cont_vector, disc_vector,\n                                  info, sample_writer);\n            }\n          }\n          return_code = stan::services::error_codes::OK;\n        } else if (algo->value() == \"bfgs\") {\n          interface_callbacks::interrupt::noop callback;\n          typedef stan::optimization::BFGSLineSearch\n            <Model,stan::optimization::BFGSUpdate_HInv<> > Optimizer;\n          Optimizer bfgs(model, cont_vector, disc_vector, &std::cout);\n\n          bfgs._ls_opts.alpha0 = dynamic_cast<stan::services::real_argument*>(\n                         algo->arg(\"bfgs\")->arg(\"init_alpha\"))->value();\n          bfgs._conv_opts.tolAbsF = dynamic_cast<stan::services::real_argument*>(\n                         algo->arg(\"bfgs\")->arg(\"tol_obj\"))->value();\n          bfgs._conv_opts.tolRelF = dynamic_cast<stan::services::real_argument*>(\n                         algo->arg(\"bfgs\")->arg(\"tol_rel_obj\"))->value();\n          bfgs._conv_opts.tolAbsGrad = dynamic_cast<stan::services::real_argument*>(\n                         algo->arg(\"bfgs\")->arg(\"tol_grad\"))->value();\n          bfgs._conv_opts.tolRelGrad = dynamic_cast<stan::services::real_argument*>(\n                         algo->arg(\"bfgs\")->arg(\"tol_rel_grad\"))->value();\n          bfgs._conv_opts.tolAbsX = dynamic_cast<stan::services::real_argument*>(\n                         algo->arg(\"bfgs\")->arg(\"tol_param\"))->value();\n          bfgs._conv_opts.maxIts = num_iterations;\n\n          return_code = optimize::do_bfgs_optimize(model,bfgs, base_rng,\n                                                   lp, cont_vector, disc_vector,\n                                                   sample_writer, info,\n                                                   save_iterations, refresh,\n                                                   callback);\n        } else if (algo->value() == \"lbfgs\") {\n          interface_callbacks::interrupt::noop callback;\n          typedef stan::optimization::BFGSLineSearch\n            <Model,stan::optimization::LBFGSUpdate<> > Optimizer;\n\n          Optimizer bfgs(model, cont_vector, disc_vector, &std::cout);\n\n          bfgs.get_qnupdate().set_history_size(dynamic_cast<services::int_argument*>(\n                         algo->arg(\"lbfgs\")->arg(\"history_size\"))->value());\n          bfgs._ls_opts.alpha0 = dynamic_cast<services::real_argument*>(\n                         algo->arg(\"lbfgs\")->arg(\"init_alpha\"))->value();\n          bfgs._conv_opts.tolAbsF = dynamic_cast<services::real_argument*>(\n                         algo->arg(\"lbfgs\")->arg(\"tol_obj\"))->value();\n          bfgs._conv_opts.tolRelF = dynamic_cast<services::real_argument*>(\n                         algo->arg(\"lbfgs\")->arg(\"tol_rel_obj\"))->value();\n          bfgs._conv_opts.tolAbsGrad = dynamic_cast<services::real_argument*>(\n                         algo->arg(\"lbfgs\")->arg(\"tol_grad\"))->value();\n          bfgs._conv_opts.tolRelGrad = dynamic_cast<services::real_argument*>(\n                         algo->arg(\"lbfgs\")->arg(\"tol_rel_grad\"))->value();\n          bfgs._conv_opts.tolAbsX = dynamic_cast<services::real_argument*>(\n                         algo->arg(\"lbfgs\")->arg(\"tol_param\"))->value();\n          bfgs._conv_opts.maxIts = num_iterations;\n\n          return_code = optimize::do_bfgs_optimize(model, bfgs, base_rng,\n                                                   lp, cont_vector, disc_vector,\n                                                   sample_writer, info,\n                                                   save_iterations, refresh,\n                                                   callback);\n        } else {\n          return_code = stan::services::error_codes::CONFIG;\n        }\n\n        io::write_iteration(model, base_rng,\n                            lp, cont_vector, disc_vector,\n                            info, sample_writer);\n        output_stream->close();\n        diagnostic_stream->close();\n        delete output_stream;\n        delete diagnostic_stream;\n        return return_code;\n      }\n\n      //////////////////////////////////////////////////\n      //              Sampling Algorithms             //\n      //////////////////////////////////////////////////\n\n      if (parser.arg(\"method\")->arg(\"sample\")) {\n        // Check timing\n        clock_t start_check = clock();\n\n        double init_log_prob;\n        Eigen::VectorXd init_grad = Eigen::VectorXd::Zero(model.num_params_r());\n\n        stan::model::gradient(model, cont_params, init_log_prob,\n                              init_grad, &std::cout);\n\n        clock_t end_check = clock();\n        double deltaT\n          = static_cast<double>(end_check - start_check) / CLOCKS_PER_SEC;\n\n        std::cout << std::endl;\n        std::cout << \"Gradient evaluation took \" << deltaT\n                  << \" seconds\" << std::endl;\n        std::cout << \"1000 transitions using 10 leapfrog steps \"\n                  << \"per transition would take \"\n                  << 1e4 * deltaT << \" seconds.\" << std::endl;\n        std::cout << \"Adjust your expectations accordingly!\"\n                  << std::endl << std::endl;\n        std::cout << std::endl;\n\n        stan::services::sample::mcmc_writer<Model,\n                                            interface_callbacks::writer::stream_writer,\n                                            interface_callbacks::writer::stream_writer,\n                                            interface_callbacks::writer::stream_writer>\n          writer(sample_writer, diagnostic_writer, info);\n\n        // Sampling parameters\n        int num_warmup = dynamic_cast<stan::services::int_argument*>(\n                          parser.arg(\"method\")->arg(\"sample\")->arg(\"num_warmup\"))->value();\n\n        int num_samples = dynamic_cast<stan::services::int_argument*>(\n                          parser.arg(\"method\")->arg(\"sample\")->arg(\"num_samples\"))->value();\n\n        int num_thin = dynamic_cast<stan::services::int_argument*>(\n                       parser.arg(\"method\")->arg(\"sample\")->arg(\"thin\"))->value();\n\n        bool save_warmup = dynamic_cast<stan::services::bool_argument*>(\n                           parser.arg(\"method\")->arg(\"sample\")->arg(\"save_warmup\"))->value();\n\n        stan::mcmc::sample s(cont_params, 0, 0);\n\n        double warmDeltaT;\n        double sampleDeltaT;\n\n        // Sampler\n        stan::mcmc::base_mcmc* sampler_ptr = 0;\n\n        stan::services::list_argument* algo\n          = dynamic_cast<stan::services::list_argument*>\n            (parser.arg(\"method\")->arg(\"sample\")->arg(\"algorithm\"));\n\n        stan::services::categorical_argument* adapt\n          = dynamic_cast<stan::services::categorical_argument*>\n            (parser.arg(\"method\")->arg(\"sample\")->arg(\"adapt\"));\n        bool adapt_engaged\n          = dynamic_cast<stan::services::bool_argument*>(adapt->arg(\"engaged\"))\n            ->value();\n\n        if (model.num_params_r() == 0 && algo->value() != \"fixed_param\") {\n          std::cout\n            << \"Must use algorithm=fixed_param for \"\n            << \"model that has no parameters.\"\n            << std::endl;\n          return -1;\n        }\n\n        if (algo->value() == \"fixed_param\") {\n          sampler_ptr = new stan::mcmc::fixed_param_sampler();\n\n          adapt_engaged = false;\n\n          if (num_warmup != 0) {\n            std::cout << \"Warning: warmup will be skipped \"\n                      << \"for the fixed parameter sampler!\"\n                      << std::endl;\n            num_warmup = 0;\n          }\n\n        } else if (algo->value() == \"rwm\") {\n          std::cout << algo->arg(\"rwm\")->description() << std::endl;\n          return 0;\n\n        } else if (algo->value() == \"hmc\") {\n          int engine_index = 0;\n\n          stan::services::list_argument* engine\n            = dynamic_cast<stan::services::list_argument*>\n              (algo->arg(\"hmc\")->arg(\"engine\"));\n\n          if (engine->value() == \"static\") {\n            engine_index = 0;\n          } else if (engine->value() == \"nuts\") {\n            engine_index = 1;\n          }\n\n          int metric_index = 0;\n          stan::services::list_argument* metric\n            = dynamic_cast<stan::services::list_argument*>\n              (algo->arg(\"hmc\")->arg(\"metric\"));\n          if (metric->value() == \"unit_e\") {\n            metric_index = 0;\n          } else if (metric->value() == \"diag_e\") {\n            metric_index = 1;\n          } else if (metric->value() == \"dense_e\") {\n            metric_index = 2;\n          }\n\n          int sampler_select = engine_index\n            + 10 * metric_index\n            + 100 * static_cast<int>(adapt_engaged);\n\n          switch (sampler_select) {\n            case 0: {\n              typedef stan::mcmc::unit_e_static_hmc<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_static_hmc<sampler>(sampler_ptr, algo))\n                return 0;\n              break;\n            }\n\n            case 1: {\n              typedef stan::mcmc::unit_e_nuts<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_nuts<sampler>(sampler_ptr, algo))\n                return 0;\n              break;\n            }\n\n            case 10: {\n              typedef stan::mcmc::diag_e_static_hmc<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_static_hmc<sampler>(sampler_ptr, algo))\n                return 0;\n              break;\n            }\n\n            case 11: {\n              typedef stan::mcmc::diag_e_nuts<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_nuts<sampler>(sampler_ptr, algo))\n                return 0;\n              break;\n            }\n\n            case 20: {\n              typedef stan::mcmc::dense_e_static_hmc<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_static_hmc<sampler>(sampler_ptr, algo))\n                return 0;\n              break;\n            }\n\n            case 21: {\n              typedef stan::mcmc::dense_e_nuts<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_nuts<sampler>(sampler_ptr, algo))\n                return 0;\n              break;\n            }\n\n            case 100: {\n              typedef stan::mcmc::adapt_unit_e_static_hmc<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_static_hmc<sampler>(sampler_ptr, algo))\n                return 0;\n              if (!sample::init_adapt<sampler>(sampler_ptr,\n                                               adapt, cont_params,\n                                               info, err))\n                return 0;\n              break;\n            }\n\n            case 101: {\n              typedef stan::mcmc::adapt_unit_e_nuts<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_nuts<sampler>(sampler_ptr, algo))\n                return 0;\n              if (!sample::init_adapt<sampler>(sampler_ptr,\n                                               adapt, cont_params,\n                                               info, err))\n                return 0;\n              break;\n            }\n\n            case 110: {\n              typedef stan::mcmc::adapt_diag_e_static_hmc<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_static_hmc<sampler>(sampler_ptr, algo))\n                return 0;\n              if (!sample::init_windowed_adapt<sampler>(sampler_ptr, adapt, num_warmup,\n                                                        cont_params, info, err))\n                return 0;\n              break;\n            }\n\n            case 111: {\n              typedef stan::mcmc::adapt_diag_e_nuts<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_nuts<sampler>(sampler_ptr, algo))\n                return 0;\n              if (!sample::init_windowed_adapt<sampler>(sampler_ptr, adapt, num_warmup,\n                                                        cont_params, info, err))\n                return 0;\n              break;\n            }\n\n            case 120: {\n              typedef stan::mcmc::adapt_dense_e_static_hmc<Model, rng_t>\n                sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_static_hmc<sampler>(sampler_ptr, algo))\n                return 0;\n              if (!sample::init_windowed_adapt<sampler>(sampler_ptr, adapt, num_warmup,\n                                                        cont_params, info, err))\n                return 0;\n              break;\n            }\n\n            case 121: {\n              typedef stan::mcmc::adapt_dense_e_nuts<Model, rng_t> sampler;\n              sampler_ptr = new sampler(model, base_rng);\n              if (!sample::init_nuts<sampler>(sampler_ptr, algo))\n                return 0;\n              if (!sample::init_windowed_adapt<sampler>(sampler_ptr, adapt, num_warmup,\n                                                        cont_params, info, err))\n                return 0;\n              break;\n            }\n\n            default:\n              std::cout << \"No sampler matching HMC specification!\"\n                        << std::endl;\n              return 0;\n          }\n        }\n\n        // Headers\n        writer.write_sample_names(s, sampler_ptr, model);\n        writer.write_diagnostic_names(s, sampler_ptr, model);\n\n        std::string prefix = \"\";\n        std::string suffix = \"\\n\";\n        interface_callbacks::interrupt::noop startTransitionCallback;\n\n        // Warm-Up\n        clock_t start = clock();\n\n\n        mcmc::warmup<Model, rng_t>(sampler_ptr, num_warmup, num_samples, num_thin,\n                                   refresh, save_warmup,\n                                   writer,\n                                   s, model, base_rng,\n                                   prefix, suffix, std::cout,\n                                   startTransitionCallback,\n                                   info, err);\n\n        clock_t end = clock();\n        warmDeltaT = static_cast<double>(end - start) / CLOCKS_PER_SEC;\n\n        if (adapt_engaged) {\n          dynamic_cast<stan::mcmc::base_adapter*>(sampler_ptr)\n            ->disengage_adaptation();\n          writer.write_adapt_finish(sampler_ptr);\n        }\n\n        // Sampling\n        start = clock();\n\n        mcmc::sample<Model, rng_t>\n          (sampler_ptr, num_warmup, num_samples, num_thin,\n           refresh, true,\n           writer,\n           s, model, base_rng,\n           prefix, suffix, std::cout,\n           startTransitionCallback,\n           info, err);\n\n        end = clock();\n        sampleDeltaT = static_cast<double>(end - start) / CLOCKS_PER_SEC;\n\n        writer.write_timing(warmDeltaT, sampleDeltaT);\n\n        if (sampler_ptr)\n          delete sampler_ptr;\n      }\n\n      //////////////////////////////////////////////////\n      //           VARIATIONAL Algorithms             //\n      //////////////////////////////////////////////////\n\n\n      if (parser.arg(\"method\")->arg(\"variational\")) {\n        stan::services::list_argument* algo\n          = dynamic_cast<stan::services::list_argument*>(parser.arg(\"method\")\n            ->arg(\"variational\")->arg(\"algorithm\"));\n\n        int grad_samples = dynamic_cast<stan::services::int_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")\n                               ->arg(\"grad_samples\"))->value();\n\n        int elbo_samples = dynamic_cast<stan::services::int_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")\n                               ->arg(\"elbo_samples\"))->value();\n\n        int max_iterations = dynamic_cast<stan::services::int_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")\n                               ->arg(\"iter\"))->value();\n\n        double tol_rel_obj = dynamic_cast<stan::services::real_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")\n                               ->arg(\"tol_rel_obj\"))->value();\n\n        double eta = dynamic_cast<stan::services::real_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")\n                               ->arg(\"eta\"))->value();\n\n        bool adapt_engaged = dynamic_cast<stan::services::bool_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")->arg(\"adapt\")\n                                                   ->arg(\"engaged\"))->value();\n\n        int adapt_iterations = dynamic_cast<stan::services::int_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")->arg(\"adapt\")\n                                                   ->arg(\"iter\"))->value();\n\n        int eval_elbo = dynamic_cast<stan::services::int_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")\n                               ->arg(\"eval_elbo\"))->value();\n\n        int output_samples = dynamic_cast<stan::services::int_argument*>\n          (parser.arg(\"method\")->arg(\"variational\")\n                               ->arg(\"output_samples\"))->value();\n\n        // Check timing\n        clock_t start_check = clock();\n\n        double init_log_prob;\n        Eigen::VectorXd init_grad\n          = Eigen::VectorXd::Zero(model.num_params_r());\n\n        stan::model::gradient(model, cont_params, init_log_prob,\n                              init_grad, &std::cout);\n\n        clock_t end_check = clock();\n        double deltaT\n          = static_cast<double>(end_check - start_check) / CLOCKS_PER_SEC;\n\n        std::cout << std::endl;\n        std::cout << \"This is Automatic Differentiation Variational Inference.\";\n        std::cout << std::endl;\n\n        std::cout << std::endl;\n        std::cout << \"(EXPERIMENTAL ALGORITHM: expect frequent updates to the\"\n                  << \" procedure.)\";\n        std::cout << std::endl;\n\n        std::cout << std::endl;\n        std::cout << \"Gradient evaluation took \" << deltaT\n                  << \" seconds\" << std::endl;\n        std::cout << \"1000 iterations under these settings should take \"\n                  << 1e3 * grad_samples * deltaT << \" seconds.\" << std::endl;\n        std::cout << \"Adjust your expectations accordingly!\";\n        std::cout << std::endl;\n        std::cout << std::endl;\n\n        if (algo->value() == \"fullrank\") {\n          std::vector<std::string> names;\n          names.push_back(\"lp__\");\n          model.constrained_param_names(names, true, true);\n\n          sample_writer(names);\n\n          stan::variational::advi<Model,\n                                  stan::variational::normal_fullrank,\n                                  rng_t>\n            cmd_advi(model,\n                     cont_params,\n                     base_rng,\n                     grad_samples,\n                     elbo_samples,\n                     eval_elbo,\n                     output_samples);\n          cmd_advi.run(eta, adapt_engaged, adapt_iterations,\n                       tol_rel_obj, max_iterations,\n                       info, sample_writer, diagnostic_writer);\n        }\n\n        if (algo->value() == \"meanfield\") {\n          std::vector<std::string> names;\n          names.push_back(\"lp__\");\n          model.constrained_param_names(names, true, true);\n          sample_writer(names);\n          \n          stan::variational::advi<Model,\n                                  stan::variational::normal_meanfield,\n                                  rng_t>\n            cmd_advi(model,\n                     cont_params,\n                     base_rng,\n                     grad_samples,\n                     elbo_samples,\n                     eval_elbo,\n                     output_samples);\n          cmd_advi.run(eta, adapt_engaged, adapt_iterations,\n                       tol_rel_obj, max_iterations,\n                       info, sample_writer, diagnostic_writer);\n        }\n      }\n\n      if (output_stream) {\n        output_stream->close();\n        delete output_stream;\n      }\n\n      if (diagnostic_stream) {\n        diagnostic_stream->close();\n        delete diagnostic_stream;\n      }\n\n      for (size_t i = 0; i < valid_arguments.size(); ++i)\n        delete valid_arguments.at(i);\n\n      return 0;\n    }\n\n  }  // namespace services\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "f42324ccbfcbe16a99d204eb1ee50c08b2732d0b", "size": 36042, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/src/cmdstan/command.hpp", "max_stars_repo_name": "guillefix/BayesianTumourGrowth", "max_stars_repo_head_hexsha": "c5d9fbb4dba27c0a66a4ae28adbd1cc1518a336c", "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": "cmdstan/src/cmdstan/command.hpp", "max_issues_repo_name": "guillefix/BayesianTumourGrowth", "max_issues_repo_head_hexsha": "c5d9fbb4dba27c0a66a4ae28adbd1cc1518a336c", "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": "cmdstan/src/cmdstan/command.hpp", "max_forks_repo_name": "guillefix/BayesianTumourGrowth", "max_forks_repo_head_hexsha": "c5d9fbb4dba27c0a66a4ae28adbd1cc1518a336c", "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.0022197558, "max_line_length": 93, "alphanum_fraction": 0.5534654015, "num_tokens": 7711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.014957089721657348, "lm_q1q2_score": 0.004209009098773625}}
{"text": "/**********************************************************************************/\n/* This file is part of spla project                                              */\n/* https://github.com/JetBrains-Research/spla                                     */\n/**********************************************************************************/\n/* MIT License                                                                    */\n/*                                                                                */\n/* Copyright (c) 2021 JetBrains-Research                                          */\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 SPLA_SPLAMASKBYKEY_HPP\n#define SPLA_SPLAMASKBYKEY_HPP\n\n#include <boost/compute.hpp>\n#include <boost/compute/detail/iterator_range_size.hpp>\n#include <boost/compute/iterator/zip_iterator.hpp>\n\nnamespace spla {\n\n    /**\n     * @addtogroup Internal\n     * @{\n     */\n\n    namespace detail {\n\n        class BalancedPathKernel : public boost::compute::detail::meta_kernel {\n        public:\n            unsigned int tile_size;\n\n            BalancedPathKernel() : meta_kernel(\"__spla_balanced_path\") {\n                tile_size = 4;\n            }\n\n            template<class InputIterator1, class InputIterator2,\n                     class OutputIterator1, class OutputIterator2,\n                     class Compare>\n            void set_range(InputIterator1 first1,\n                           InputIterator1 last1,\n                           InputIterator2 first2,\n                           InputIterator2 last2,\n                           OutputIterator1 result_a,\n                           OutputIterator2 result_b,\n                           Compare comp) {\n                using namespace boost::compute;\n\n                typedef typename std::iterator_traits<InputIterator1>::value_type value_type;\n\n                m_a_count = boost::compute::detail::iterator_range_size(first1, last1);\n                m_a_count_arg = add_arg<uint_>(\"a_count\");\n\n                m_b_count = boost::compute::detail::iterator_range_size(first2, last2);\n                m_b_count_arg = add_arg<uint_>(\"b_count\");\n\n                *this << \"uint i = get_global_id(0);\\n\"\n                      << \"uint target = (i+1)*\" << tile_size << \";\\n\"\n                      << \"uint start = max(convert_int(0),convert_int(target)-convert_int(b_count));\\n\"\n                      << \"uint end = min(target,a_count);\\n\"\n                      << \"uint a_index, b_index;\\n\"\n                      << \"while(start<end)\\n\"\n                      << \"{\\n\"\n                      << \"   a_index = (start + end)/2;\\n\"\n                      << \"   b_index = target - a_index - 1;\\n\"\n                      << \"   if(!(\" << comp(first2[expr<uint_>(\"b_index\")], first1[expr<uint_>(\"a_index\")]) << \"))\\n\"\n                      << \"       start = a_index + 1;\\n\"\n                      << \"   else end = a_index;\\n\"\n                      << \"}\\n\"\n                      << \"a_index = start;\\n\"\n                      << \"b_index = target - start;\\n\"\n                      << \"if(b_index < b_count)\\n\"\n                      << \"{\\n\"\n                      << \"   \" << decl<const value_type>(\"x\") << \" = \" << first2[expr<uint_>(\"b_index\")] << \";\\n\"\n                      << \"   uint a_start = 0, a_end = a_index, a_mid;\\n\"\n                      << \"   uint b_start = 0, b_end = b_index, b_mid;\\n\"\n                      << \"   while(a_start<a_end)\\n\"\n                      << \"   {\\n\"\n                      << \"       a_mid = (a_start + a_end)/2;\\n\"\n                      << \"       if(\" << comp(first1[expr<uint_>(\"a_mid\")], expr<value_type>(\"x\")) << \")\\n\"\n                      << \"           a_start = a_mid+1;\\n\"\n                      << \"       else a_end = a_mid;\\n\"\n                      << \"   }\\n\"\n                      << \"   while(b_start<b_end)\\n\"\n                      << \"   {\\n\"\n                      << \"       b_mid = (b_start + b_end)/2;\\n\"\n                      << \"       if(\" << comp(first2[expr<uint_>(\"b_mid\")], expr<value_type>(\"x\")) << \")\\n\"\n                      << \"           b_start = b_mid+1;\\n\"\n                      << \"       else b_end = b_mid;\\n\"\n                      << \"   }\\n\"\n                      << \"   uint a_run = a_index - a_start;\\n\"\n                      << \"   uint b_run = b_index - b_start;\\n\"\n                      << \"   uint x_count = a_run + b_run;\\n\"\n                      << \"   uint b_advance = max(x_count / 2, x_count - a_run);\\n\"\n                      << \"   b_end = min(b_count, b_start + b_advance + 1);\\n\"\n                      << \"   uint temp_start = b_index, temp_end = b_end, temp_mid;\"\n                      << \"   while(temp_start < temp_end)\\n\"\n                      << \"   {\\n\"\n                      << \"       temp_mid = (temp_start + temp_end + 1)/2;\\n\"\n                      << \"       if(\" << comp(expr<value_type>(\"x\"), first2[expr<uint_>(\"temp_mid\")]) << \")\\n\"\n                      << \"           temp_end = temp_mid-1;\\n\"\n                      << \"       else temp_start = temp_mid;\\n\"\n                      << \"   }\\n\"\n                      << \"   b_run = temp_start - b_start + 1;\\n\"\n                      << \"   b_advance = min(b_advance, b_run);\\n\"\n                      << \"   uint a_advance = x_count - b_advance;\\n\"\n                      << \"   uint star = convert_uint((a_advance == b_advance + 1) \"\n                      << \"&& (b_advance < b_run));\\n\"\n                      << \"   a_index = a_start + a_advance;\\n\"\n                      << \"   b_index = target - a_index + star;\\n\"\n                      << \"}\\n\"\n                      << result_a[expr<uint_>(\"i\")] << \" = a_index;\\n\"\n                      << result_b[expr<uint_>(\"i\")] << \" = b_index;\\n\";\n            }\n\n            boost::compute::event exec(boost::compute::command_queue &queue) {\n                using namespace boost::compute;\n\n                if ((m_a_count + m_b_count) / tile_size == 0) {\n                    return boost::compute::event();\n                }\n\n                set_arg(m_a_count_arg, uint_(m_a_count));\n                set_arg(m_b_count_arg, uint_(m_b_count));\n\n                return exec_1d(queue, 0, (m_a_count + m_b_count) / tile_size);\n            }\n\n        private:\n            std::size_t m_a_count;\n            std::size_t m_a_count_arg;\n            std::size_t m_b_count;\n            std::size_t m_b_count_arg;\n        };\n\n        /** Serial pre-process intersection kernel to count actual results count (but do not intersect) */\n        class SerialIntersectionCountKernel : boost::compute::detail::meta_kernel {\n        public:\n            SerialIntersectionCountKernel() : meta_kernel(\"__spla_serial_intersection_count\") {\n            }\n\n            template<class InputIterator1,\n                     class InputIterator2,\n                     class InputIterator3,\n                     class InputIterator4,\n                     class OutputIterator,\n                     class Compare,\n                     class Equals>\n            void set_range(InputIterator1 maskFirst,\n                           InputIterator2 keyFirsts,\n                           InputIterator3 tile_first1,\n                           InputIterator3 tile_last1,\n                           InputIterator4 tile_first2,\n                           OutputIterator counts,\n                           Compare compare,\n                           Equals equals,\n                           bool complement) {\n                using uint_ = boost::compute::uint_;\n                m_count = boost::compute::detail::iterator_range_size(tile_first1, tile_last1) - 1;\n\n                *this << \"uint i = get_global_id(0);\\n\"\n                      << \"uint start1 = \" << tile_first1[expr<uint_>(\"i\")] << \";\\n\"\n                      << \"uint end1 = \" << tile_first1[expr<uint_>(\"i+1\")] << \";\\n\"\n                      << \"uint start2 = \" << tile_first2[expr<uint_>(\"i\")] << \";\\n\"\n                      << \"uint end2 = \" << tile_first2[expr<uint_>(\"i+1\")] << \";\\n\"\n                      << \"uint count = 0;\\n\"\n                      << \"while(start1<end1 && start2<end2)\\n\"\n                      << \"{\\n\";\n\n                if (complement) {\n                    *this << \"   if(\" << equals(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"   {\\n\"\n                          << \"       start1++; start2++;\\n\"\n                          << \"   }\\n\"\n                          << \"   else if(\" << compare(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"       start1++;\\n\"\n                          << \"   else\\n\"\n                          << \"   {\\n\"\n                          << \"       count++; start2++;\\n\"\n                          << \"   }\\n\";\n                } else {\n                    *this << \"   if(\" << equals(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"   {\\n\"\n                          << \"       count++;\\n\"\n                          << \"       start1++; start2++;\\n\"\n                          << \"   }\\n\"\n                          << \"   else if(\" << compare(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"       start1++;\\n\"\n                          << \"   else start2++;\\n\";\n                }\n\n                *this << \"}\\n\";\n\n                if (complement)\n                    *this << counts[expr<uint_>(\"i\")] << \" = count + (end2 - start2);\\n\";\n                else\n                    *this << counts[expr<uint_>(\"i\")] << \" = count;\\n\";\n            }\n\n            boost::compute::event exec(boost::compute::command_queue &queue) {\n                if (m_count == 0) {\n                    return boost::compute::event();\n                }\n\n                return exec_1d(queue, 0, m_count);\n            }\n\n        private:\n            std::size_t m_count = 0;\n        };\n\n        class SerialIntersectionKernel : boost::compute::detail::meta_kernel {\n        public:\n            SerialIntersectionKernel() : meta_kernel(\"__spla_serial_intersection\") {\n            }\n\n            template<class InputIterator1,\n                     class InputIterator2,\n                     class InputIterator3,\n                     class InputIterator4,\n                     class InputIterator5,\n                     class Compare,\n                     class Equals,\n                     class AssignResult>\n            void set_range(InputIterator1 maskFirst,\n                           InputIterator2 keyFirsts,\n                           InputIterator3 tile_first1,\n                           InputIterator3 tile_last1,\n                           InputIterator4 tile_first2,\n                           InputIterator5 counts,\n                           Compare compare,\n                           Equals equals,\n                           AssignResult assignResult,\n                           bool complement) {\n                using uint_ = boost::compute::uint_;\n                m_count = boost::compute::detail::iterator_range_size(tile_first1, tile_last1) - 1;\n\n                *this << \"uint i = get_global_id(0);\\n\"\n                      << \"uint start1 = \" << tile_first1[expr<uint_>(\"i\")] << \";\\n\"\n                      << \"uint end1 = \" << tile_first1[expr<uint_>(\"i+1\")] << \";\\n\"\n                      << \"uint start2 = \" << tile_first2[expr<uint_>(\"i\")] << \";\\n\"\n                      << \"uint end2 = \" << tile_first2[expr<uint_>(\"i+1\")] << \";\\n\"\n                      << \"uint count = \" << counts[expr<uint_>(\"i\")] << \";\\n\"\n                      << \"while(start1<end1 && start2<end2)\\n\"\n                      << \"{\\n\";\n\n                if (complement) {\n                    *this << \"   if(\" << equals(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"   {\\n\"\n                          << \"       start1++; start2++;\\n\"\n                          << \"   }\\n\"\n                          << \"   else if(\" << compare(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"       start1++;\\n\"\n                          << \"   else\\n\"\n                          << \"   {\\n\";\n                    assignResult(*this, expr<uint_>(\"count\"), expr<uint_>(\"start2\"));\n                    *this << \"       count++; start2++;\\n\"\n                          << \"   }\\n\";\n                } else {\n                    *this << \"   if(\" << equals(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"   {\\n\";\n                    assignResult(*this, expr<uint_>(\"count\"), expr<uint_>(\"start2\"));\n                    *this << \"       count++;\\n\"\n                          << \"       start1++; start2++;\\n\"\n                          << \"   }\\n\"\n                          << \"   else if(\" << compare(maskFirst[expr<uint_>(\"start1\")], keyFirsts[expr<uint_>(\"start2\")]) << \")\\n\"\n                          << \"       start1++;\\n\"\n                          << \"   else start2++;\\n\";\n                }\n\n                *this << \"}\\n\";\n\n                if (complement) {\n                    *this << \"while (start2 < end2)\\n\"\n                          << \"{\\n\";\n                    assignResult(*this, expr<uint_>(\"count\"), expr<uint_>(\"start2\"));\n                    *this << \"    count++; start2++;\"\n                          << \"}\\n\";\n                }\n            }\n\n            boost::compute::event exec(boost::compute::command_queue &queue) {\n                if (m_count == 0) {\n                    return boost::compute::event();\n                }\n\n                return exec_1d(queue, 0, m_count);\n            }\n\n        private:\n            std::size_t m_count = 0;\n        };\n\n        template<\n                typename InputMask,\n                typename InputKey,\n                typename Compare,\n                typename Equals,\n                typename ResizeResult,\n                typename AssignResult>\n        std::size_t MaskByKey(InputMask maskFirst,\n                              InputKey keyFirst,\n                              Compare compare,\n                              Equals equals,\n                              ResizeResult resizeResult,\n                              AssignResult assignResult,\n                              std::size_t maskCount,\n                              std::size_t keyCount,\n                              bool complement,\n                              boost::compute::command_queue &queue) {\n            using namespace boost;\n            std::size_t tileSize = 8;\n\n            compute::vector<compute::uint_> tileA((maskCount + keyCount + tileSize - 1) / tileSize + 1, queue.get_context());\n            compute::vector<compute::uint_> tileB((maskCount + keyCount + tileSize - 1) / tileSize + 1, queue.get_context());\n\n            // Tile the sets\n            detail::BalancedPathKernel balancedPathKernel;\n            balancedPathKernel.tile_size = tileSize;\n            balancedPathKernel.set_range(maskFirst, maskFirst + maskCount,\n                                         keyFirst, keyFirst + keyCount,\n                                         tileA.begin() + 1, tileB.begin() + 1,\n                                         compare);\n            fill_n(tileA.begin(), 1, 0, queue);\n            fill_n(tileB.begin(), 1, 0, queue);\n            balancedPathKernel.exec(queue);\n\n            fill_n(tileA.end() - 1, 1, maskCount, queue);\n            fill_n(tileB.end() - 1, 1, keyCount, queue);\n\n            compute::vector<compute::uint_> counts((maskCount + keyCount + tileSize - 1) / tileSize + 1, queue.get_context());\n            compute::fill_n(counts.end() - 1, 1, 0, queue);\n\n            // Find result intersections count and offsets to write result of each tile\n            detail::SerialIntersectionCountKernel intersectionCountKernel;\n            intersectionCountKernel.set_range(maskFirst, keyFirst,\n                                              tileA.begin(), tileA.end(),\n                                              tileB.begin(),\n                                              counts.begin(),\n                                              compare, equals, complement);\n            intersectionCountKernel.exec(queue);\n\n            // Compute actual counts offsets\n            exclusive_scan(counts.begin(), counts.end(), counts.begin(), queue);\n\n            // Get result count and resize buffers\n            std::size_t resultCount = (counts.end() - 1).read(queue);\n            resizeResult(resultCount);\n\n            // Find result intersections\n            detail::SerialIntersectionKernel intersectionKernel;\n            intersectionKernel.set_range(maskFirst, keyFirst, tileA.begin(), tileA.end(),\n                                         tileB.begin(),\n                                         counts.begin(),\n                                         compare, equals, assignResult, complement);\n            intersectionKernel.exec(queue);\n\n            return resultCount;\n        }\n\n    }// namespace detail\n\n    /**\n     * @brief Mask intersection algorithm.\n     *\n     * Finds the intersection of the sorted mask range with the sorted\n     * keys range and stores it in range starting at resultKeys.\n     *\n     * @note Automatically resizes result containers to result count size.\n     * @note Use complement flag to apply direct or inverse (complement) mask\n     *\n     * @param mask Mask elements\n     * @param keys Keys elements\n     * @param resultKeys Result keys elements\n     * @param complement Pass true to apply !mask (complementary mask)\n     * @param queue Command queue to perform operations on\n     *\n     * @return Count of values in intersected region\n     */\n    inline std::size_t MaskKeys(const boost::compute::vector<unsigned int> &mask,\n                                const boost::compute::vector<unsigned int> &keys,\n                                boost::compute::vector<unsigned int> &resultKeys,\n                                bool complement,\n                                boost::compute::command_queue &queue) {\n        using namespace boost;\n        using MetaKernel = boost::compute::detail::meta_kernel;\n        using MetaIdx = boost::compute::detail::meta_kernel_variable<boost::compute::uint_>;\n\n        auto resizeResult = [&](std::size_t size) {\n            resultKeys.resize(size);\n        };\n\n        auto assignResult = [&](MetaKernel &kernel, const MetaIdx &dst, const MetaIdx &src) {\n            kernel << resultKeys.begin()[dst] << \" = \" << keys.begin()[src] << \";\\n\";\n        };\n\n        if (mask.empty() || keys.empty()) {\n            resizeResult(0);\n            return 0;\n        }\n\n        using compute::lambda::_1;\n        using compute::lambda::_2;\n\n        return detail::MaskByKey(mask.begin(),\n                                 keys.begin(),\n                                 _1 < _2,\n                                 _1 == _2,\n                                 resizeResult,\n                                 assignResult,\n                                 mask.size(),\n                                 keys.size(),\n                                 complement,\n                                 queue);\n    }\n\n    /**\n     * @brief Mask intersection algorithm.\n     *\n     * Finds the intersection of the sorted mask range with the sorted\n     * keys range and stores it in range starting at resultKeys.\n     *\n     * @note Manages associated values with keys.\n     * @note Automatically resizes result containers to result count size.\n     * @note Use complement flag to apply direct or inverse (complement) mask\n     *\n     * @param mask Mask elements\n     * @param keys Keys elements\n     * @param values Associated with keys values\n     * @param resultKeys Result keys elements\n     * @param resultValues Result values associated with result keys.\n     * @param complement Pass true to apply !mask (complementary mask)\n     * @param queue Command queue to perform operations on\n     *\n     * @return Count of values in intersected region\n     */\n    inline std::size_t MaskByKeys(const boost::compute::vector<unsigned int> &mask,\n                                  const boost::compute::vector<unsigned int> &keys,\n                                  const boost::compute::vector<unsigned int> &values,\n                                  boost::compute::vector<unsigned int> &resultKeys,\n                                  boost::compute::vector<unsigned int> &resultValues,\n                                  bool complement,\n                                  boost::compute::command_queue &queue) {\n        using namespace boost;\n        using MetaKernel = boost::compute::detail::meta_kernel;\n        using MetaIdx = boost::compute::detail::meta_kernel_variable<boost::compute::uint_>;\n\n        assert(keys.size() == values.size());\n\n        auto resizeResult = [&](std::size_t size) {\n            resultKeys.resize(size);\n            resultValues.resize(size);\n        };\n\n        auto assignResult = [&](MetaKernel &kernel, const MetaIdx &dst, const MetaIdx &src) {\n            kernel << resultKeys.begin()[dst] << \" = \" << keys.begin()[src] << \";\\n\"\n                   << resultValues.begin()[dst] << \" = \" << values.begin()[src] << \";\\n\";\n        };\n\n        if (mask.empty() || keys.empty()) {\n            resizeResult(0);\n            return 0;\n        }\n\n        using compute::lambda::_1;\n        using compute::lambda::_2;\n\n        return detail::MaskByKey(mask.begin(),\n                                 keys.begin(),\n                                 _1 < _2,\n                                 _1 == _2,\n                                 resizeResult,\n                                 assignResult,\n                                 mask.size(),\n                                 keys.size(),\n                                 complement,\n                                 queue);\n    }\n\n    /**\n     * @brief Mask intersection algorithm.\n     *\n     * Finds the intersection of the sorted pair mask range with the sorted\n     * pair keys range and stores it in range starting at resultKeys.\n     *\n     * @note Interprets keys as pairs, where first and second elements stored in separate arrays.\n     * @note Automatically resizes result containers to result count size.\n     * @note Use complement flag to apply direct or inverse (complement) mask\n     *\n     * @param mask1 Mask first elements\n     * @param mask2 Mask second elements\n     * @param keys1 Keys first elements\n     * @param keys2 Keys second elements\n     * @param resultKeys1 Result keys first elements\n     * @param resultKeys2 Result keys second elements\n     * @param complement Pass true to apply !mask (complementary mask)\n     * @param queue Command queue to perform operations on\n     *\n     * @return Count of values in intersected region\n     */\n    inline std::size_t MaskPairKeys(const boost::compute::vector<unsigned int> &mask1,\n                                    const boost::compute::vector<unsigned int> &mask2,\n                                    const boost::compute::vector<unsigned int> &keys1,\n                                    const boost::compute::vector<unsigned int> &keys2,\n                                    boost::compute::vector<unsigned int> &resultKeys1,\n                                    boost::compute::vector<unsigned int> &resultKeys2,\n                                    bool complement,\n                                    boost::compute::command_queue &queue) {\n        using namespace boost;\n        using MetaKernel = boost::compute::detail::meta_kernel;\n        using MetaIdx = boost::compute::detail::meta_kernel_variable<boost::compute::uint_>;\n\n        assert(mask1.size() == mask2.size());\n        assert(keys1.size() == keys2.size());\n\n        auto resizeResult = [&](std::size_t size) {\n            resultKeys1.resize(size);\n            resultKeys2.resize(size);\n        };\n\n        auto assignResult = [&](MetaKernel &kernel, const MetaIdx &dst, const MetaIdx &src) {\n            kernel << resultKeys1.begin()[dst] << \" = \" << keys1.begin()[src] << \";\\n\"\n                   << resultKeys2.begin()[dst] << \" = \" << keys2.begin()[src] << \";\\n\";\n        };\n\n        if (mask1.empty() || keys1.empty()) {\n            resizeResult(0);\n            return 0;\n        }\n\n        using compute::lambda::_1;\n        using compute::lambda::_2;\n        using compute::lambda::get;\n\n        return detail::MaskByKey(compute::make_zip_iterator(boost::make_tuple(mask1.begin(), mask2.begin())),\n                                 compute::make_zip_iterator(boost::make_tuple(keys1.begin(), keys2.begin())),\n                                 get<0>(_1) < get<0>(_2) || (get<0>(_1) == get<0>(_2) && get<1>(_1) < get<1>(_2)),\n                                 get<0>(_1) == get<0>(_2) && get<1>(_1) == get<1>(_2),\n                                 resizeResult,\n                                 assignResult,\n                                 mask1.size(),\n                                 keys1.size(),\n                                 complement,\n                                 queue);\n    }\n\n    /**\n     * @brief Mask intersection algorithm.\n     *\n     * Finds the intersection of the sorted pair mask range with the sorted\n     * pair keys range and stores it in range starting at resultKeys.\n     *\n     * @note Manages associated values with keys.\n     * @note Interprets keys as pairs, where first and second elements stored in separate arrays.\n     * @note Automatically resizes result containers to result count size.\n     * @note Use complement flag to apply direct or inverse (complement) mask\n     *\n     * @param mask1 Mask first elements\n     * @param mask2 Mask second elements\n     * @param keys1 Keys first elements\n     * @param keys2 Keys second elements\n     * @param values Associated with keys values\n     * @param resultKeys1 Result keys first elements\n     * @param resultKeys2 Result keys second elements\n     * @param resultValues Result values associated with result keys.\n     * @param complement Pass true to apply !mask (complementary mask)\n     * @param queue Command queue to perform operations on\n     *\n     * @return Count of values in intersected region\n     */\n    inline std::size_t MaskByPairKeys(const boost::compute::vector<unsigned int> &mask1,\n                                      const boost::compute::vector<unsigned int> &mask2,\n                                      const boost::compute::vector<unsigned int> &keys1,\n                                      const boost::compute::vector<unsigned int> &keys2,\n                                      const boost::compute::vector<unsigned int> &values,\n                                      boost::compute::vector<unsigned int> &resultKeys1,\n                                      boost::compute::vector<unsigned int> &resultKeys2,\n                                      boost::compute::vector<unsigned int> &resultValues,\n                                      bool complement,\n                                      boost::compute::command_queue &queue) {\n        using namespace boost;\n        using MetaKernel = boost::compute::detail::meta_kernel;\n        using MetaIdx = boost::compute::detail::meta_kernel_variable<boost::compute::uint_>;\n\n        assert(mask1.size() == mask2.size());\n        assert(keys1.size() == keys2.size());\n        assert(keys1.size() == values.size());\n\n        auto resizeResult = [&](std::size_t size) {\n            resultKeys1.resize(size);\n            resultKeys2.resize(size);\n            resultValues.resize(size);\n        };\n\n        auto assignResult = [&](MetaKernel &kernel, const MetaIdx &dst, const MetaIdx &src) {\n            kernel << resultKeys1.begin()[dst] << \" = \" << keys1.begin()[src] << \";\\n\"\n                   << resultKeys2.begin()[dst] << \" = \" << keys2.begin()[src] << \";\\n\"\n                   << resultValues.begin()[dst] << \" = \" << values.begin()[src] << \";\\n\";\n        };\n\n        if (mask1.empty() || keys1.empty()) {\n            resizeResult(0);\n            return 0;\n        }\n\n        using compute::lambda::_1;\n        using compute::lambda::_2;\n        using compute::lambda::get;\n\n        return detail::MaskByKey(compute::make_zip_iterator(boost::make_tuple(mask1.begin(), mask2.begin())),\n                                 compute::make_zip_iterator(boost::make_tuple(keys1.begin(), keys2.begin())),\n                                 get<0>(_1) < get<0>(_2) || (get<0>(_1) == get<0>(_2) && get<1>(_1) < get<1>(_2)),\n                                 get<0>(_1) == get<0>(_2) && get<1>(_1) == get<1>(_2),\n                                 resizeResult,\n                                 assignResult,\n                                 mask1.size(),\n                                 keys1.size(),\n                                 complement,\n                                 queue);\n    }\n\n    /**\n     * @}\n     */\n\n}// namespace spla\n\n#endif//SPLA_SPLAMASKBYKEY_HPP", "meta": {"hexsha": "17e6662c1e6b234efebc9b676450a1bec665bde8", "size": 30555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/compute/SplaMaskByKey.hpp", "max_stars_repo_name": "JetBrains-Research/spla", "max_stars_repo_head_hexsha": "9b353d68420bc69c322023d239f8bb0977308b9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-09-24T03:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T09:09:01.000Z", "max_issues_repo_path": "sources/compute/SplaMaskByKey.hpp", "max_issues_repo_name": "JetBrains-Research/spla", "max_issues_repo_head_hexsha": "9b353d68420bc69c322023d239f8bb0977308b9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 78.0, "max_issues_repo_issues_event_min_datetime": "2021-09-11T09:39:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T19:50:07.000Z", "max_forks_repo_path": "sources/compute/SplaMaskByKey.hpp", "max_forks_repo_name": "JetBrains-Research/spla", "max_forks_repo_head_hexsha": "9b353d68420bc69c322023d239f8bb0977308b9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T15:43:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T11:29:52.000Z", "avg_line_length": 47.5194401244, "max_line_length": 130, "alphanum_fraction": 0.4583210604, "num_tokens": 6184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646699291617, "lm_q2_score": 0.02556521661455869, "lm_q1q2_score": 0.004205899115335796}}
{"text": "// origami_potential.cpp\n\n#include \"origami_potential.h\"\n#include \"nearest_neighbour.h\"\n\n#include <fstream>\n#include <iostream>\n#include <utility>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/serialization/unordered_map.hpp>\n#include <boost/serialization/utility.hpp>\n\nnamespace potential {\n\nusing std::cout;\n\nusing nearestNeighbour::calc_comp_seq;\nusing utility::Occupancy;\nusing utility::OrigamiMisuse;\n\nbool check_domain_orientations_opposing(Domain& cd_i, Domain& cd_j) {\n    bool domain_orientations_opposing {true};\n    if (cd_i.m_ore != -cd_j.m_ore) {\n        domain_orientations_opposing = false;\n        return domain_orientations_opposing;\n    }\n    return domain_orientations_opposing;\n}\n\nbool check_domains_exist_and_bound(vector<Domain*> cdv) {\n    bool exists_and_bound {true};\n    for (auto cd: cdv) {\n        if (cd == nullptr) {\n            exists_and_bound = false;\n            break;\n        }\n        bool cd_bound {cd->m_state == Occupancy::bound};\n        if (not cd_bound) {\n            exists_and_bound = false;\n            break;\n        }\n    }\n\n    return exists_and_bound;\n}\n\nbool doubly_contiguous(Domain* cd_1, Domain* cd_2) {\n\n    if (cd_1->m_c != cd_2->m_c or cd_2->m_d != cd_1->m_d + 1) {\n        return false;\n    }\n\n    Domain* cd_bound_1 {cd_1->m_bound_domain};\n    Domain* cd_bound_2 {cd_2->m_bound_domain};\n    if (cd_bound_1->m_c != cd_bound_2->m_c) {\n        return false;\n    }\n\n    if (abs(cd_bound_2->m_d - cd_bound_1->m_d) == 1) {\n        return true;\n    }\n\n    return false;\n}\n\nbool check_pair_stacked(Domain* cd_1, Domain* cd_2) {\n    bool stacked {false};\n    if (cd_1->m_d > cd_2->m_d) {\n        Domain* hold {cd_1};\n        cd_1 = cd_2;\n        cd_2 = hold;\n    }\n    VectorThree ndr {cd_2->m_pos - cd_1->m_pos};\n    if (ndr != cd_1->m_ore and ndr != -cd_1->m_ore) {\n        stacked = cd_1->check_twist_constraint(ndr, *cd_2);\n    }\n\n    return stacked;\n}\n\nint check_junction_stacking_penalty(\n        Domain& cd_j1,\n        Domain& cd_j2,\n        Domain& cd_j3,\n        Domain& cd_j4,\n        Domain& cd_k1,\n        Domain& cd_k2) {\n\n    int stacking_penalty {0};\n    VectorThree ndr_k1 {cd_k2.m_pos - cd_k1.m_pos};\n    if (ndr_k1 == cd_k1.m_ore) {\n        VectorThree ndr_1 {cd_j2.m_pos - cd_j1.m_pos};\n        if (cd_j1.m_d > cd_j2.m_d) {\n            ndr_1 = -ndr_1;\n        }\n        VectorThree ndr_3 {cd_j4.m_pos - cd_j3.m_pos};\n        if (cd_j3.m_d > cd_j4.m_d) {\n            ndr_3 = -ndr_3;\n        }\n        if (ndr_1 == ndr_3) {\n            stacking_penalty = 2;\n        }\n        else if (ndr_1 == -ndr_3) {\n            stacking_penalty = 0;\n        }\n        else {\n            stacking_penalty = 1;\n        }\n        //                cout << stacking_penalty << \" (\" << cd_j1.m_c << \" \"\n        //                << cd_j1.m_d\n        //                     << \"), (\" << cd_j2.m_c << \" \" << cd_j2.m_d << \"),\n        //                     (\" << cd_j3.m_c\n        //                     << \" \" << cd_j3.m_d << \"), (\" << cd_j4.m_c << \" \"\n        //                     << cd_j4.m_d\n        //                     << \"), (\" << cd_k1.m_c << \" \" << cd_k1.m_d << \"),\n        //                     (\" << cd_k2.m_c\n        //                     << \" \" << cd_k2.m_d << \")\\n\";\n    }\n    return stacking_penalty;\n}\n\nBindingPotential::BindingPotential(OrigamiPotential& pot): m_pot {pot} {}\n\nDeltaConfig BindingPotential::bind_domains(Domain& cd_i, Domain& cd_j) {\n\n    m_delta_config = {};\n    m_constraints_violated = false;\n    if (not check_domain_orientations_opposing(cd_i, cd_j)) {\n        m_constraints_violated = true;\n        return {};\n    }\n\n    calc_stacking_and_steric_terms(cd_i, cd_j);\n    if (m_constraints_violated) {\n        return {};\n    }\n    m_delta_config.e += m_pot.hybridization_energy(cd_i, cd_j);\n\n    return m_delta_config;\n}\n\nDeltaConfig BindingPotential::check_stacking(Domain& cd_i, Domain& cd_j) {\n\n    m_delta_config = {};\n    m_constraints_violated = false;\n    calc_stacking_and_steric_terms(cd_i, cd_j);\n\n    return m_delta_config;\n}\n\nvoid BindingPotential::check_triplet_single_stacking(\n        Domain* cd_h1,\n        Domain* cd_h2,\n        Domain* cd_h3) {\n\n    VectorThree ndr_1 {cd_h2->m_pos - cd_h1->m_pos};\n    if (ndr_1 == cd_h1->m_ore) {\n        return;\n    }\n    VectorThree ndr_2 {cd_h3->m_pos - cd_h2->m_pos};\n    if (ndr_1 != ndr_2) {\n        m_delta_config.e -= m_pot.stacking_energy(*cd_h2, *cd_h3);\n        m_delta_config.stacked_pairs -= 1;\n        //                cout << \"(\" << cd_h1->m_c << \" \" << cd_h1->m_d << \"),\n        //                (\" << cd_h2->m_c\n        //                     << \" \" << cd_h2->m_d << \"), (\" << cd_h3->m_c << \"\n        //                     \" << cd_h3->m_d\n        //                     << \")\\n\";\n    }\n}\n\nvoid BindingPotential::check_triplet_double_stacking(\n        Domain* cd_h1,\n        Domain* cd_h2,\n        Domain* cd_h3) {\n\n    VectorThree ndr_1 {cd_h2->m_pos - cd_h1->m_pos};\n    VectorThree ndr_2 {cd_h3->m_pos - cd_h2->m_pos};\n    if (ndr_1 != ndr_2) {\n        m_delta_config.e -= m_pot.stacking_energy(*cd_h1, *cd_h2) / 2;\n        m_delta_config.e -= m_pot.stacking_energy(*cd_h2, *cd_h3) / 2;\n        m_delta_config.stacked_pairs -= 1;\n        //                cout << \"(\" << cd_h1->m_c << \" \" << cd_h1->m_d << \"),\n        //                (\" << cd_h2->m_c\n        //                     << \" \" << cd_h2->m_d << \"), (\" << cd_h3->m_c << \"\n        //                     \" << cd_h3->m_d\n        //                     << \")\\n\";\n    }\n}\n\nvoid BindingPotential::check_triply_contig_helix(\n        Domain* cd_h1,\n        Domain* cd_h2,\n        Domain* cd_h3) {\n\n    VectorThree ndr_1 {cd_h2->m_pos - cd_h1->m_pos};\n    VectorThree ndr_2 {cd_h3->m_pos - cd_h2->m_pos};\n    if (ndr_1 != ndr_2) {\n        m_constraints_violated = true;\n    }\n}\n\nvoid JunctionBindingPotential::calc_stacking_and_steric_terms(\n        Domain& cd_i,\n        Domain& cd_j) {\n\n    int j {0};\n    for (auto cd: {&cd_i, &cd_j}) {\n        check_constraints(cd, j);\n        if (m_constraints_violated) {\n            return;\n        }\n        j++;\n    }\n    check_central_triplet_stacking_combos(cd_i, cd_j);\n}\n\nvoid JunctionBindingPotential::check_constraints(Domain* cd, int j) {\n    for (int i: {-1, 0}) {\n        Domain* cd_1 {*cd + i};\n        Domain* cd_2 {*cd + (i + 1)};\n        if (not check_domains_exist_and_bound({cd_1, cd_2})) {\n            continue;\n        }\n        Domain& cd_bound_1 {*cd_1->m_bound_domain};\n        Domain& cd_bound_2 {*cd_2->m_bound_domain};\n        bool bound_same_chain {cd_bound_1.m_c == cd_bound_2.m_c};\n        if (bound_same_chain) {\n\n            // Same helix case\n            if (cd_bound_1.m_d == cd_bound_2.m_d - 1) {\n                check_doubly_contig_helix_pair(cd_1, cd_2, i, j);\n            }\n\n            // Crossover case\n            else if (cd_bound_1.m_d == cd_bound_2.m_d + 1) {\n                check_doubly_contig_junction_pair(cd_1, cd_2);\n            }\n\n            // Not doubly contiguous\n            else {\n                check_regular_pair_constraints(cd_1, cd_2, i);\n            }\n        }\n        else {\n            check_regular_pair_constraints(cd_1, cd_2, i);\n        }\n        if (m_constraints_violated) {\n            return;\n        }\n    }\n    Domain* cd_prev {*cd + -1};\n    Domain* cd_forw {*cd + 1};\n    if (check_domains_exist_and_bound({cd_prev, cd_forw})) {\n        if (check_pair_stacked(cd, cd_forw)) {\n            if (check_pair_stacked(cd_prev, cd)) {\n                if (doubly_contiguous(cd_prev, cd) and\n                    doubly_contiguous(cd, cd_forw)) {\n                    check_triply_contig_helix(cd_prev, cd, cd_forw);\n                    if (m_constraints_violated) {\n                        return;\n                    }\n                }\n                check_triplet_double_stacking(cd_prev, cd, cd_forw);\n            }\n            else {\n                check_triplet_single_stacking(cd_prev, cd, cd_forw);\n            }\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_regular_pair_constraints(\n        Domain* cd_1,\n        Domain* cd_2,\n        int i) {\n\n    VectorThree ndr {cd_2->m_pos - cd_1->m_pos};\n    if (not cd_1->check_kink_constraint(ndr, *cd_2)) {\n        m_constraints_violated = true;\n        return;\n    }\n    if (check_pair_stacked(cd_1, cd_2)) {\n        m_delta_config.e += m_pot.stacking_energy(*cd_1, *cd_2);\n        m_delta_config.stacked_pairs += 1;\n        //                cout << cd_1->m_c << \" \" << cd_1->m_d << \", \" <<\n        //                cd_2->m_c << \" \"\n        //                     << cd_2->m_d << \"\\n\";\n        if (i == -1) {\n            check_backward_single_junction(cd_1, cd_2);\n        }\n        else {\n            check_forward_single_junction(cd_1, cd_2);\n        }\n    }\n    else {\n        check_central_single_junction(cd_1, cd_2);\n    }\n\n    if (i == -1) {\n        check_backward_triplet_stacking_combos(cd_1, cd_2, i);\n    }\n    else {\n        check_forward_triplet_stacking_combos(cd_1, cd_2, i);\n    }\n}\n\nvoid JunctionBindingPotential::check_doubly_contig_helix_pair(\n        Domain* cd_1,\n        Domain* cd_2,\n        int i,\n        int j) {\n\n    VectorThree ndr {cd_2->m_pos - cd_1->m_pos};\n    if (ndr == cd_1->m_ore or ndr == -cd_1->m_ore) {\n        m_constraints_violated = true;\n    }\n    else if (cd_1->check_twist_constraint(ndr, *cd_2)) {\n        if (j == 0) {\n            m_delta_config.e += m_pot.stacking_energy(*cd_1, *cd_2);\n            m_delta_config.stacked_pairs += 1;\n            //                        cout << cd_1->m_c << \" \" << cd_1->m_d <<\n            //                        \", \" << cd_2->m_c << \" \"\n            //                             << cd_2->m_d << \"\\n\";\n        }\n        if (i == -1) {\n            check_backward_triplet_stacking_combos(cd_1, cd_2, i);\n            check_backward_single_junction(cd_1, cd_2);\n        }\n        else {\n            check_forward_triplet_stacking_combos(cd_1, cd_2, i);\n            check_forward_single_junction(cd_1, cd_2);\n        }\n    }\n    else {\n        m_constraints_violated = true;\n    }\n}\n\nvoid JunctionBindingPotential::check_doubly_contig_junction_pair(\n        Domain* cd_1,\n        Domain* cd_2) {\n\n    Domain* cd_j1 {*cd_1 + -1};\n    Domain* cd_j2 {cd_1};\n    Domain* cd_j3;\n    Domain* cd_j4;\n    Domain* cd_k1 {cd_1};\n    Domain* cd_k2 {cd_2};\n    VectorThree ndr {cd_k2->m_pos - cd_k1->m_pos};\n    if (cd_k1->m_ore != ndr) {\n        m_constraints_violated = true;\n        return;\n    }\n    cd_j3 = cd_k2;\n    cd_j4 = *cd_k2 + 1;\n    if (check_domains_exist_and_bound({cd_j4})) {\n        if (check_domains_exist_and_bound({cd_j1})) {\n            check_junction(cd_j1, cd_j2, cd_j3, cd_j4, cd_k1, cd_k2);\n        }\n        if (check_pair_stacked(cd_j3, cd_j4)) {\n            check_triplet_single_stacking(cd_k1, cd_k2, cd_j4);\n        }\n    }\n\n    cd_j3 = cd_k2->m_bound_domain;\n    cd_j4 = *cd_j3 + -1;\n    if (check_domains_exist_and_bound({cd_j4})) {\n        if (check_domains_exist_and_bound({cd_j1})) {\n            check_junction(cd_j1, cd_j2, cd_j3, cd_j4, cd_k1, cd_k2);\n        }\n        if (check_pair_stacked(cd_j4, cd_j3)) {\n            check_triplet_single_stacking(cd_k1, cd_k2, cd_j4);\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_backward_triplet_stacking_combos(\n        Domain* cd_1,\n        Domain* cd_2,\n        int i) {\n\n    Domain* cd_h1;\n    Domain* cd_h2;\n    Domain* cd_h3;\n    cd_h2 = cd_1;\n    cd_h3 = cd_2;\n    if (not check_pair_stacked(cd_h2, cd_h3)) {\n        return;\n    }\n    bool h2_h3_doubly_contig {doubly_contiguous(cd_h2, cd_h3)};\n\n    // Check same chain\n    cd_h1 = *cd_1 + -1;\n    if (check_domains_exist_and_bound({cd_h1})) {\n        if (check_pair_stacked(cd_h1, cd_h2)) {\n            if (h2_h3_doubly_contig and doubly_contiguous(cd_h1, cd_h2)) {\n                check_triply_contig_helix(cd_h1, cd_h2, cd_h3);\n                if (m_constraints_violated) {\n                    return;\n                }\n            }\n            check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n        }\n        else {\n            check_triplet_single_stacking(cd_h1, cd_h2, cd_h3);\n        }\n    }\n\n    // Check helices that extend to bound chain\n    Domain* cd_h2_prev {cd_h1};\n    cd_h1 = *(cd_1->m_bound_domain) + 1;\n    if (check_domains_exist_and_bound({cd_h1}) and\n        cd_h1->m_bound_domain != cd_h3 and not h2_h3_doubly_contig) {\n        if (check_pair_stacked(cd_1->m_bound_domain, cd_h1)) {\n            check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n        }\n    }\n    cd_h1 = *(cd_1->m_bound_domain) + -1;\n    if (check_domains_exist_and_bound({cd_h1}) and\n        cd_h1->m_bound_domain != cd_h2_prev and not h2_h3_doubly_contig) {\n        if (check_pair_stacked(cd_h1, cd_1->m_bound_domain)) {\n            check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n        }\n        else {\n            check_triplet_single_stacking(cd_h1, cd_1->m_bound_domain, cd_h3);\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_forward_triplet_stacking_combos(\n        Domain* cd_1,\n        Domain* cd_2,\n        int i) {\n\n    Domain* cd_h1;\n    Domain* cd_h2;\n    Domain* cd_h3;\n    cd_h2 = cd_2;\n    cd_h1 = cd_1;\n    bool first_pair_stacked {check_pair_stacked(cd_h1, cd_h2)};\n    bool h1_h2_doubly_contig {doubly_contiguous(cd_h1, cd_h2)};\n\n    // Check same chain\n    cd_h3 = *(cd_2) + 1;\n    if (check_domains_exist_and_bound({cd_h3})) {\n        bool second_pair_stacked {check_pair_stacked(cd_h2, cd_h3)};\n        if (first_pair_stacked and second_pair_stacked) {\n            if (h1_h2_doubly_contig and doubly_contiguous(cd_h2, cd_h3)) {\n                check_triply_contig_helix(cd_h1, cd_h2, cd_h3);\n                if (m_constraints_violated) {\n                    return;\n                }\n            }\n            check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n        }\n        else if (second_pair_stacked) {\n            check_triplet_single_stacking(cd_h1, cd_h2, cd_h3);\n        }\n    }\n\n    // Check helices that extend to bound chain\n    Domain* cd_h2_next {cd_h3};\n    cd_h3 = *(cd_2->m_bound_domain) + 1;\n    if (check_domains_exist_and_bound({cd_h3}) and\n        cd_h3->m_bound_domain != cd_h2_next and not h1_h2_doubly_contig) {\n        if (check_pair_stacked(cd_2->m_bound_domain, cd_h3)) {\n            if (first_pair_stacked) {\n                check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n            }\n            else {\n                check_triplet_single_stacking(cd_h1, cd_h2, cd_h3);\n            }\n        }\n    }\n    cd_h3 = *(cd_2->m_bound_domain) + -1;\n    if (check_domains_exist_and_bound({cd_h3}) and\n        cd_h3->m_bound_domain != cd_h1 and not h1_h2_doubly_contig) {\n        if (check_pair_stacked(cd_h3, cd_2->m_bound_domain)) {\n            if (first_pair_stacked) {\n                check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n            }\n            else {\n                check_triplet_single_stacking(cd_h1, cd_h2, cd_h3);\n            }\n        }\n        else if (first_pair_stacked) {\n            check_triplet_single_stacking(cd_h3, cd_2->m_bound_domain, cd_h1);\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_central_triplet_stacking_combos(\n        Domain& cd_i,\n        Domain& cd_j) {\n\n    Domain* cd_h1 {cd_i + -1};\n    Domain* cd_h2 {&cd_i};\n    Domain* cd_h3;\n    cd_h3 = cd_j + 1;\n    Domain* cd_h2_next {cd_i + 1};\n    if (check_domains_exist_and_bound({cd_h1, cd_h3}) and\n        cd_h3->m_bound_domain != cd_h2_next and\n        (not doubly_contiguous(cd_h1, cd_h2))) {\n        if (check_pair_stacked(&cd_j, cd_h3)) {\n            if (check_pair_stacked(cd_h1, cd_h2)) {\n                check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n            }\n            else {\n                check_triplet_single_stacking(cd_h1, cd_h2, cd_h3);\n            }\n        }\n    }\n    cd_h3 = cd_j + -1;\n    if (check_domains_exist_and_bound({cd_h1, cd_h3}) and\n        cd_h3->m_bound_domain != cd_h1 and\n        (not doubly_contiguous(cd_h1, cd_h2))) {\n        if (check_pair_stacked(cd_h1, cd_h2)) {\n            if (check_pair_stacked(cd_h3, &cd_j)) {\n                check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n            }\n            else {\n                check_triplet_single_stacking(cd_h3, &cd_j, cd_h1);\n            }\n        }\n        else if (check_pair_stacked(cd_h3, &cd_j)) {\n            check_triplet_single_stacking(cd_h1, cd_h2, cd_h3);\n        }\n    }\n\n    cd_h2 = &cd_i;\n    cd_h3 = cd_i + 1;\n    cd_h1 = cd_j + 1;\n    Domain* cd_h2_prev {cd_i + -1};\n    if (check_domains_exist_and_bound({cd_h1, cd_h3}) and\n        cd_h1->m_bound_domain != cd_h3 and\n        (not doubly_contiguous(cd_h2, cd_h3))) {\n        if (check_pair_stacked(&cd_j, cd_h1) and\n            check_pair_stacked(cd_h2, cd_h3)) {\n            check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n        }\n    }\n    cd_h1 = cd_j + -1;\n    if (check_domains_exist_and_bound({cd_h1, cd_h3}) and\n        cd_h1->m_bound_domain != cd_h2_prev and\n        (not doubly_contiguous(cd_h2, cd_h3))) {\n        if (check_pair_stacked(cd_h2, cd_h3)) {\n            if (check_pair_stacked(cd_h1, &cd_j)) {\n                check_triplet_double_stacking(cd_h1, cd_h2, cd_h3);\n            }\n            else {\n                check_triplet_single_stacking(cd_h1, &cd_j, cd_h3);\n            }\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_backward_single_junction(\n        Domain* cd_1,\n        Domain* cd_2) {\n\n    // Passed domains are the second junction pair\n    Domain* cd_j1;\n    Domain* cd_j2;\n    Domain* cd_j3 {cd_1};\n    Domain* cd_j4 {cd_2};\n    Domain* cd_k1;\n    Domain* cd_k2;\n\n    // Find possible kink pair combinations\n    vector<pair<Domain*, Domain*>> first_sel {};\n\n    // Add kink pair that is the same chain as the first junction pair\n    Domain* cd_j3_bac {cd_j3->m_backward_domain};\n    first_sel.push_back({cd_j3, cd_j3_bac});\n\n    // Add kink pairs that are on the chain bound to j3\n    Domain* cd_j3_bound {cd_j3->m_bound_domain};\n    Domain* cd_j4_bound {cd_j4->m_bound_domain};\n    Domain* cd_j3_bound_for {cd_j3_bound->m_forward_domain};\n    Domain* cd_j3_bound_bac {cd_j3_bound->m_backward_domain};\n    if (cd_j3->m_bound_domain->m_c == cd_j4->m_bound_domain->m_c) {\n        int diff {cd_j4_bound->m_d - cd_j3_bound->m_d};\n\n        // Must prevent double counting\n        if (abs(diff) == 1 and cd_j3->m_c > cd_j3_bound->m_c) {\n            return;\n        }\n        if (diff == 1) {\n            first_sel.push_back({cd_j3_bound, cd_j3_bound_bac});\n        }\n        else {\n            first_sel.push_back({cd_j3_bound, cd_j3_bound_for});\n            first_sel.push_back({cd_j3_bound, cd_j3_bound_bac});\n        }\n    }\n    else if (\n            check_domains_exist_and_bound({cd_j3_bac, cd_j3_bound_bac}) and\n            cd_j3_bac->m_bound_domain == cd_j3_bound_bac) {\n        first_sel.push_back({cd_j3_bound, cd_j3_bound_for});\n    }\n    else if (\n            check_domains_exist_and_bound({cd_j3_bac, cd_j3_bound_for}) and\n            cd_j3_bac->m_bound_domain == cd_j3_bound_for) {\n        first_sel.push_back({cd_j3_bound, cd_j3_bound_bac});\n    }\n    else {\n        first_sel.push_back({cd_j3_bound, cd_j3_bound_for});\n        first_sel.push_back({cd_j3_bound, cd_j3_bound_bac});\n    }\n    for (auto sel1: first_sel) {\n        cd_k2 = sel1.first;\n        cd_k1 = sel1.second;\n        if (not check_domains_exist_and_bound({cd_k1})) {\n            continue;\n        }\n\n        // If kink is stacked, not a kink\n        if (check_pair_stacked(cd_k1, cd_k2)) {\n            continue;\n        }\n\n        // Find possible second junction pairs\n        vector<pair<Domain*, Domain*>> second_sel {};\n\n        // Add junction that is on the same chain as the kink pair\n        int dir {cd_k1->m_d - cd_k2->m_d};\n        Domain* cd_k1_next {*cd_k1 + dir};\n        second_sel.push_back({cd_k1, cd_k1_next});\n\n        // Add junction pairs that are on chain bound to k2\n        Domain* cd_k1_bound {cd_k1->m_bound_domain};\n        Domain* cd_k1_bound_for {cd_k1_bound->m_forward_domain};\n        Domain* cd_k1_bound_bac {cd_k1_bound->m_backward_domain};\n        if (check_domains_exist_and_bound({cd_k1_next})) {\n\n            // Prevent double counting\n            Domain* cd_k1_next_bound {cd_k1_next->m_bound_domain};\n            if (cd_k1_bound_for != cd_k1_next_bound) {\n                second_sel.push_back({cd_k1_bound, cd_k1_bound_for});\n            }\n            if (cd_k1_bound_bac != cd_k1_next_bound) {\n                second_sel.push_back({cd_k1_bound, cd_k1_bound_bac});\n            }\n        }\n        else {\n            second_sel.push_back({cd_k1_bound, cd_k1_bound_for});\n            second_sel.push_back({cd_k1_bound, cd_k1_bound_bac});\n        }\n        for (auto sel2: second_sel) {\n            cd_j2 = sel2.first;\n            cd_j1 = sel2.second;\n            if (not check_domains_exist_and_bound({cd_j1})) {\n                continue;\n            }\n            check_junction(cd_j1, cd_j2, cd_j3, cd_j4, cd_k1, cd_k2);\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_forward_single_junction(\n        Domain* cd_1,\n        Domain* cd_2) {\n\n    // Passed domains are the first junction pair\n    Domain* cd_j1 {cd_1};\n    Domain* cd_j2 {cd_2};\n    Domain* cd_j3;\n    Domain* cd_j4;\n    Domain* cd_k1;\n    Domain* cd_k2;\n\n    // Find possible kink pair combinations\n    vector<pair<Domain*, Domain*>> first_sel {};\n\n    // Add kink pair that is the same chain as the first junction pair\n    Domain* cd_j2_for {cd_j2->m_forward_domain};\n    first_sel.push_back({cd_j2, cd_j2_for});\n\n    // Add kink pairs that are on the chain bound to j2\n    Domain* cd_j1_bound {cd_j1->m_bound_domain};\n    Domain* cd_j2_bound {cd_j2->m_bound_domain};\n    Domain* cd_j2_bound_for {cd_j2_bound->m_forward_domain};\n    Domain* cd_j2_bound_bac {cd_j2_bound->m_backward_domain};\n    if (cd_j1_bound->m_c == cd_j2_bound->m_c) {\n        int diff {cd_j2_bound->m_d - cd_j1_bound->m_d};\n\n        // Must prevent double counting\n        if (abs(diff) == 1 and cd_j1->m_c > cd_j1_bound->m_c) {\n            return;\n        }\n        if (diff == 1) {\n            first_sel.push_back({cd_j2_bound, cd_j2_bound_for});\n        }\n        else {\n            first_sel.push_back({cd_j2_bound, cd_j2_bound_for});\n            first_sel.push_back({cd_j2_bound, cd_j2_bound_bac});\n        }\n    }\n    // What if it is doubly contig on both sides?\n    else if (\n            check_domains_exist_and_bound({cd_j2_for, cd_j2_bound_bac}) and\n            cd_j2_for->m_bound_domain == cd_j2_bound_bac) {\n        first_sel.push_back({cd_j2_bound, cd_j2_bound_for});\n    }\n    else if (\n            check_domains_exist_and_bound({cd_j2_for, cd_j2_bound_for}) and\n            cd_j2_for->m_bound_domain == cd_j2_bound_for) {\n        first_sel.push_back({cd_j2_bound, cd_j2_bound_bac});\n    }\n    else {\n        first_sel.push_back({cd_j2_bound, cd_j2_bound_for});\n        first_sel.push_back({cd_j2_bound, cd_j2_bound_bac});\n    }\n    for (auto sel1: first_sel) {\n        cd_k1 = sel1.first;\n        cd_k2 = sel1.second;\n        if (not check_domains_exist_and_bound({cd_k2})) {\n            continue;\n        }\n\n        // If kink is stacked, not a kink\n        if (check_pair_stacked(cd_k1, cd_k2)) {\n            continue;\n        }\n\n        // Find possible second junction pairs\n        vector<pair<Domain*, Domain*>> second_sel {};\n\n        // Add junction that is on the same chain as the kink pair\n        int dir {cd_k2->m_d - cd_k1->m_d};\n        Domain* cd_k2_next {*cd_k2 + dir};\n        second_sel.push_back({cd_k2, cd_k2_next});\n\n        // Add junction pairs that are on chain bound to k2\n        Domain* cd_k2_bound {cd_k2->m_bound_domain};\n        Domain* cd_k2_bound_for {cd_k2_bound->m_forward_domain};\n        Domain* cd_k2_bound_bac {cd_k2_bound->m_backward_domain};\n        if (check_domains_exist_and_bound({cd_k2_next})) {\n\n            // Prevent double counting\n            Domain* cd_k2_next_bound {cd_k2_next->m_bound_domain};\n            if (cd_k2_bound_for != cd_k2_next_bound) {\n                second_sel.push_back({cd_k2_bound, cd_k2_bound_for});\n            }\n            if (cd_k2_bound_bac != cd_k2_next_bound) {\n                second_sel.push_back({cd_k2_bound, cd_k2_bound_bac});\n            }\n        }\n        else {\n            second_sel.push_back({cd_k2_bound, cd_k2_bound_for});\n            second_sel.push_back({cd_k2_bound, cd_k2_bound_bac});\n        }\n        for (auto sel2: second_sel) {\n            cd_j3 = sel2.first;\n            cd_j4 = sel2.second;\n            if (not check_domains_exist_and_bound({cd_j4})) {\n                continue;\n            }\n            check_junction(cd_j1, cd_j2, cd_j3, cd_j4, cd_k1, cd_k2);\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_central_single_junction(\n        Domain* cd_1,\n        Domain* cd_2) {\n\n    // Passed domains are the kink pair\n    Domain* cd_j1;\n    Domain* cd_j2;\n    Domain* cd_j3;\n    Domain* cd_j4;\n    Domain* cd_k1 {cd_1};\n    Domain* cd_k2 {cd_2};\n\n    // Kinked pair cannot be doubly contiguous\n    if (cd_k1->m_bound_domain->m_c == cd_k2->m_bound_domain->m_c and\n        abs(cd_k1->m_bound_domain->m_d - cd_k2->m_bound_domain->m_d) == 1) {\n        return;\n    }\n\n    // Find possible first junction pairs\n    vector<pair<Domain*, Domain*>> first_sel {};\n\n    // Add first junction pair that is on the same chain as the kink pair\n    Domain* cd_k1_bac {cd_k1->m_backward_domain};\n    first_sel.push_back({cd_k1, cd_k1_bac});\n\n    // Add first junction pairs bound to k1\n    Domain* cd_k1_bound {cd_k1->m_bound_domain};\n    Domain* cd_k1_bound_for {cd_k1_bound->m_forward_domain};\n    Domain* cd_k1_bound_bac {cd_k1_bound->m_backward_domain};\n    if (check_domains_exist_and_bound({cd_k1_bac})) {\n\n        // If j1 and j2 are doubly contiguous, then this will be double\n        // counted\n        Domain* cd_k1_bac_bound {cd_k1_bac->m_bound_domain};\n        if (cd_k1_bound_for != cd_k1_bac_bound) {\n            first_sel.push_back({cd_k1_bound, cd_k1_bound_for});\n        }\n        if (cd_k1_bound_bac != cd_k1_bac_bound) {\n            first_sel.push_back({cd_k1_bound, cd_k1_bound_bac});\n        }\n    }\n    else {\n        first_sel.push_back({cd_k1_bound, cd_k1_bound_for});\n        first_sel.push_back({cd_k1_bound, cd_k1_bound_bac});\n    }\n    for (auto sel1: first_sel) {\n        cd_j2 = sel1.first;\n        cd_j1 = sel1.second;\n        if (not check_domains_exist_and_bound({cd_j1})) {\n            continue;\n        }\n\n        // Find possible second junction pairs\n        vector<pair<Domain*, Domain*>> second_sel {};\n\n        // Add junction pair that is on the same chain as the kink pair\n        Domain* cd_k2_for {cd_k2->m_forward_domain};\n        second_sel.push_back({cd_k2, cd_k2_for});\n\n        // Add junction pairs that are on chain bound to k2\n        Domain* cd_k2_bound {cd_k2->m_bound_domain};\n        Domain* cd_k2_bound_for {cd_k2_bound->m_forward_domain};\n        Domain* cd_k2_bound_bac {cd_k2_bound->m_backward_domain};\n        if (check_domains_exist_and_bound({cd_k2_for})) {\n\n            // If j3 and j4 are doubly contiguous, then this will be double\n            // counted\n            Domain* cd_k2_for_bound {cd_k2_for->m_bound_domain};\n            if (cd_k2_bound_for != cd_k2_for_bound) {\n                second_sel.push_back({cd_k2_bound, cd_k2_bound_for});\n            }\n            if (cd_k2_bound_bac != cd_k2_for_bound) {\n                second_sel.push_back({cd_k2_bound, cd_k2_bound_bac});\n            }\n        }\n        else {\n            second_sel.push_back({cd_k2_bound, cd_k2_bound_for});\n            second_sel.push_back({cd_k2_bound, cd_k2_bound_bac});\n        }\n        for (auto sel2: second_sel) {\n            cd_j3 = sel2.first;\n            cd_j4 = sel2.second;\n            if (not check_domains_exist_and_bound({cd_j4})) {\n                continue;\n            }\n            check_junction(cd_j1, cd_j2, cd_j3, cd_j4, cd_k1, cd_k2);\n        }\n    }\n}\n\nvoid JunctionBindingPotential::check_junction(\n        Domain* cd_j1,\n        Domain* cd_j2,\n        Domain* cd_j3,\n        Domain* cd_j4,\n        Domain* cd_k1,\n        Domain* cd_k2) {\n\n    // Put domains in order along chain\n    Domain* hold;\n    if (cd_k1->m_d > cd_k2->m_d) {\n        hold = cd_k1;\n        cd_k1 = cd_k2;\n        cd_k2 = hold;\n        hold = cd_j1;\n        cd_j1 = cd_j4;\n        cd_j4 = hold;\n        hold = cd_j2;\n        cd_j2 = cd_j3;\n        cd_j3 = hold;\n    }\n    // this is inefficient for three quarter domains\n    if (not(check_pair_stacked(cd_j1, cd_j2) and\n            check_pair_stacked(cd_j3, cd_j4))) {\n        return;\n    }\n    if (not cd_j1->check_junction_constraint(\n                *cd_j2, *cd_j3, *cd_j4, *cd_k1, *cd_k2)) {\n        m_constraints_violated = true;\n        return;\n    }\n    auto stacking_penalty {check_junction_stacking_penalty(\n            *cd_j1, *cd_j2, *cd_j3, *cd_j4, *cd_k1, *cd_k2)};\n    if (stacking_penalty == 1) {\n        m_delta_config.e -= m_pot.stacking_energy(*cd_j1, *cd_j2) / 2;\n        m_delta_config.e -= m_pot.stacking_energy(*cd_j3, *cd_j4) / 2;\n        m_delta_config.stacked_pairs -= 1;\n    }\n    else if (stacking_penalty == 2) {\n        m_delta_config.e -= m_pot.stacking_energy(*cd_j1, *cd_j2);\n        m_delta_config.e -= m_pot.stacking_energy(*cd_j3, *cd_j4);\n        m_delta_config.stacked_pairs -= 2;\n    }\n}\n\nMisbindingPotential::MisbindingPotential(OrigamiPotential& pot): m_pot {pot} {}\n\ndouble OpposingMisbindingPotential::bind_domains(Domain& cd_i, Domain& cd_j) {\n    m_constraints_violated = true;\n    if (not check_domain_orientations_opposing(cd_i, cd_j)) {\n        return 0;\n    }\n    m_constraints_violated = false;\n    return m_pot.hybridization_energy(cd_i, cd_j);\n}\n\ndouble DisallowedMisbindingPotential::bind_domains(Domain&, Domain&) {\n    m_constraints_violated = true;\n    return 0;\n}\n\nOrigamiPotential::OrigamiPotential(\n        const vector<vector<int>> identities,\n        const vector<vector<string>>& sequences,\n        const vector<double> enthalpies,\n        const vector<double> entropies,\n        InputParameters& params):\n        m_energy_filebase {params.m_energy_filebase},\n        m_temp {params.m_temp},\n        m_cation_M {params.m_cation_M},\n        m_identities {identities},\n        m_sequences {sequences},\n        m_complementary_enthalpies {enthalpies},\n        m_complementary_entropies {entropies},\n        m_stacking_pot {params.m_stacking_pot},\n        m_hybridization_pot {params.m_hybridization_pot},\n        m_apply_mean_field_cor {params.m_apply_mean_field_cor} {\n\n    if (params.m_binding_pot == \"FourBody\") {\n        m_binding_pot = new JunctionBindingPotential(*this);\n    }\n    else {\n        std::cout << \"No such binding potential\";\n    }\n\n    if (params.m_misbinding_pot == \"Opposing\") {\n        m_misbinding_pot = new OpposingMisbindingPotential(*this);\n    }\n    else if (params.m_misbinding_pot == \"Disallowed\") {\n        m_misbinding_pot = new DisallowedMisbindingPotential(*this);\n    }\n    else {\n        std::cout << \"No such binding potential\";\n    }\n\n    if (m_stacking_pot == \"Constant\") {\n        m_stacking_ene = params.m_stacking_ene;\n    }\n\n    if (m_hybridization_pot == \"Uniform\") {\n        m_binding_h = params.m_binding_h;\n        m_binding_s = params.m_binding_s;\n        m_misbinding_h = params.m_misbinding_h;\n        m_misbinding_s = params.m_misbinding_s;\n    }\n    if (m_hybridization_pot == \"Specified\") {\n        m_misbinding_h = params.m_misbinding_h;\n        m_misbinding_s = params.m_misbinding_s;\n    }\n\n    get_energies();\n}\n\nOrigamiPotential::~OrigamiPotential() {\n    delete m_binding_pot;\n    delete m_misbinding_pot;\n}\n\nvoid OrigamiPotential::update_temp(double temp, double stacking_mult) {\n\n    // Update hybridization and stacking energy tables\n    m_temp = temp;\n    pair<double, double> key {temp, stacking_mult};\n    if (m_stacking_energy_tables.count(key) == 0) {\n\n        // THIS ONLY WORKS FOR CONSTANT STACKING\n        double old_stacking_ene {m_stacking_ene};\n        m_stacking_ene *= stacking_mult;\n        get_energies();\n        m_stacking_ene = old_stacking_ene;\n        m_hybridization_energy_tables[temp] = m_hybridization_energies;\n        m_hybridization_enthalpy_tables[temp] = m_hybridization_enthalpies;\n        m_hybridization_entropy_tables[temp] = m_hybridization_entropies;\n        m_stacking_energy_tables[key] = m_stacking_energies;\n    }\n    else {\n        m_hybridization_energies = m_hybridization_energy_tables[temp];\n        m_hybridization_enthalpies = m_hybridization_enthalpy_tables[temp];\n        m_hybridization_entropies = m_hybridization_entropy_tables[temp];\n        m_stacking_energies = m_stacking_energy_tables[key];\n    }\n}\n\nvoid OrigamiPotential::get_energies() {\n    // Get S, H, and G for all possible interactions and store\n    /*if (m_energy_filebase.size() != 0) {\n        if (not read_energies_from_file()) {\n            calc_energies();\n        }\n    }\n    else {\n    */\n    calc_energies();\n    //}\n}\n\nvoid OrigamiPotential::calc_energies() {\n    // Calculate S, H, and G for all possible interactions and store\n\n    ThermoOfHybrid DH_DS {nearestNeighbour::calc_unitless_init_thermo(m_temp)};\n    m_init_enthalpy = DH_DS.enthalpy;\n    m_init_entropy = DH_DS.entropy;\n    m_init_energy = m_init_enthalpy - m_init_entropy;\n\n    // Loop through all pairs of sequences\n    for (size_t c_i {0}; c_i != m_identities.size(); c_i++) {\n        for (size_t c_j {0}; c_j != m_identities.size(); c_j++) {\n            size_t c_i_length {m_identities[c_i].size()};\n            size_t c_j_length {m_identities[c_j].size()};\n            for (size_t d_i {0}; d_i != c_i_length; d_i++) {\n                int d_i_ident {m_identities[c_i][d_i]};\n                for (size_t d_j {0}; d_j != c_j_length; d_j++) {\n                    int d_j_ident {m_identities[c_j][d_j]};\n                    pair<int, int> key {d_i_ident, d_j_ident};\n                    if (m_hybridization_pot == \"NearestNeighbour\") {\n                        string seq_i {m_sequences[c_i][d_i]};\n                        string seq_j {m_sequences[c_j][d_j]};\n                        calc_hybridization_energy(seq_i, seq_j, key);\n                    }\n                    else if (m_hybridization_pot == \"Uniform\") {\n                        calc_hybridization_energy(key);\n                    }\n                    else if (m_hybridization_pot == \"Specified\") {\n                        set_hybridization_energy(key);\n                    }\n                    else {\n                        std::cout << \"No such hybridization potential\";\n                    }\n\n                    if (m_stacking_pot == \"SequenceSpecific\") {\n                        string seq_i {m_sequences[c_i][d_i]};\n                        string seq_j {m_sequences[c_j][d_j]};\n                        calc_stacking_energy(seq_i, seq_j, key);\n                    }\n                    else if (m_stacking_pot == \"Constant\") {\n                        calc_stacking_energy(key);\n                    }\n                    else {\n                        std::cout << \"No such stacking potential\";\n                    }\n                }\n            }\n        }\n    }\n    write_energies_to_file();\n}\n\nvoid OrigamiPotential::calc_hybridization_energy(\n        string seq_i,\n        string seq_j,\n        pair<int, int> key) {\n\n    double H_hyb {0};\n    double S_hyb {0};\n    vector<string> comp_seqs {\n            nearestNeighbour::find_longest_contig_complement(seq_i, seq_j)};\n    int N {0};\n\n    // No interaction if no complementary sequence\n    if (comp_seqs.size() == 0) {\n        H_hyb = 0;\n        S_hyb = 0;\n    }\n    else {\n\n        // Take average value of H and S of all equal length comp seqs\n        for (auto comp_seq: comp_seqs) {\n            ThermoOfHybrid DH_DS {\n                    nearestNeighbour::calc_unitless_hybridization_thermo(\n                            comp_seq, m_temp, m_cation_M)};\n            H_hyb += DH_DS.enthalpy - m_init_enthalpy;\n            S_hyb += DH_DS.entropy - m_init_entropy;\n            N++;\n        }\n        H_hyb /= N;\n        S_hyb /= N;\n\n        S_hyb += log(6);\n\n        if (key.first == -key.second) {\n            if (m_apply_mean_field_cor) {\n                S_hyb += 3 * log(6);\n            }\n\n            // Check that sequences are complementary if they should be\n            if (comp_seqs[0].size() != seq_i.size() and\n                seq_i.size() == seq_j.size()) {\n                cout << \"Sequences that should be complementary are not\\n\";\n                throw OrigamiMisuse {};\n            }\n        }\n\n        // Check that sequences are not complementary if they shouldn't be\n        else {\n            if (comp_seqs[0].size() == seq_i.size() and\n                seq_i.size() == seq_j.size()) {\n                cout << \"Sequences that should not be complementary are\\n\";\n                throw OrigamiMisuse {};\n            }\n        }\n    }\n\n    m_hybridization_enthalpies[key] = H_hyb;\n    m_hybridization_entropies[key] = S_hyb;\n    m_hybridization_energies[key] = H_hyb - S_hyb;\n}\n\nvoid OrigamiPotential::calc_hybridization_energy(pair<int, int> key) {\n    double H_hyb {0};\n    double S_hyb {0};\n    if (key.first == -key.second) {\n        H_hyb = m_binding_h / m_temp;\n        S_hyb = m_binding_s;\n        if (m_apply_mean_field_cor) {\n            S_hyb += 3 * log(6);\n        }\n    }\n    else {\n        H_hyb = m_misbinding_h / m_temp;\n        S_hyb = m_misbinding_s;\n    }\n\n    S_hyb += log(6);\n\n    m_hybridization_enthalpies[key] = H_hyb;\n    m_hybridization_entropies[key] = S_hyb;\n    m_hybridization_energies[key] = H_hyb - S_hyb;\n}\n\nvoid OrigamiPotential::set_hybridization_energy(pair<int, int> key) {\n    double H_hyb {0};\n    double S_hyb {0};\n    if (key.first == -key.second) {\n        int i {std::abs(key.first) - 1};\n        H_hyb = m_complementary_enthalpies[i] / m_temp;\n        S_hyb = m_complementary_entropies[i];\n        if (m_apply_mean_field_cor) {\n            S_hyb += 3 * log(6);\n        }\n    }\n    else {\n        H_hyb = m_misbinding_h / m_temp;\n        S_hyb = m_misbinding_s;\n    }\n\n    S_hyb += log(6);\n\n    m_hybridization_enthalpies[key] = H_hyb;\n    m_hybridization_entropies[key] = S_hyb;\n    m_hybridization_energies[key] = H_hyb - S_hyb;\n}\n\nvoid OrigamiPotential::calc_stacking_energy(\n        string seq_i,\n        string seq_j,\n        pair<int, int> key) {\n\n    double s_energy {nearestNeighbour::calc_seq_spec_stacking_energy(\n            seq_i, seq_j, m_temp, m_cation_M)};\n    m_stacking_energies[key] = s_energy;\n}\n\nvoid OrigamiPotential::calc_stacking_energy(pair<int, int> key) {\n    m_stacking_energies[key] = m_stacking_ene / m_temp;\n}\n\nbool OrigamiPotential::read_energies_from_file() {\n\n    // Read energies from file, return false if not present\n    string temp_string {\"_\" + std::to_string(static_cast<int>(m_temp))};\n\n    // Hybridization free energies, enthalpies, entropies\n    string henergy_filename {m_energy_filebase + temp_string + \".hene\"};\n    string hhenergy_filename {m_energy_filebase + temp_string + \".hhene\"};\n    string hsenergy_filename {m_energy_filebase + temp_string + \".hsene\"};\n\n    // Stacking energies\n    string senergy_filename {m_energy_filebase + temp_string + \".sene\"};\n\n    std::ifstream henergy_file {henergy_filename};\n    std::ifstream hhenergy_file {henergy_filename};\n    std::ifstream hsenergy_file {henergy_filename};\n    std::ifstream senergy_file {senergy_filename};\n\n    bool files_present {\n            henergy_file and hhenergy_file and hsenergy_file and senergy_file};\n    if (files_present) {\n        boost::archive::text_iarchive h_arch {henergy_file};\n        h_arch >> m_hybridization_energies;\n        boost::archive::text_iarchive hh_arch {hhenergy_file};\n        hh_arch >> m_hybridization_enthalpies;\n        boost::archive::text_iarchive hs_arch {hsenergy_file};\n        hs_arch >> m_hybridization_entropies;\n        boost::archive::text_iarchive s_arch {senergy_file};\n        s_arch >> m_stacking_energies;\n    }\n\n    return files_present;\n}\n\nvoid OrigamiPotential::write_energies_to_file() {\n    string temp_string {\"_\" + std::to_string(static_cast<int>(m_temp))};\n\n    // Hybridization energies, enthalpies, entropies\n    string henergy_filename {m_energy_filebase + temp_string + \".hene\"};\n    string hhenergy_filename {m_energy_filebase + temp_string + \".hhene\"};\n    string hsenergy_filename {m_energy_filebase + temp_string + \".hsene\"};\n\n    // Stacking energies\n    string senergy_filename {m_energy_filebase + temp_string + \".sene\"};\n\n    std::ofstream henergy_file {henergy_filename};\n    boost::archive::text_oarchive h_arch {henergy_file};\n    h_arch << m_hybridization_energies;\n    std::ofstream hhenergy_file {hhenergy_filename};\n    boost::archive::text_oarchive hh_arch {hhenergy_file};\n    hh_arch << m_hybridization_enthalpies;\n    std::ofstream hsenergy_file {hsenergy_filename};\n    boost::archive::text_oarchive hs_arch {hsenergy_file};\n    hs_arch << m_hybridization_entropies;\n    std::ofstream senergy_file {senergy_filename};\n    boost::archive::text_oarchive s_arch {senergy_file};\n    s_arch << m_stacking_energies;\n}\n\nDeltaConfig OrigamiPotential::bind_domain(Domain& cd_i) {\n    m_constraints_violated = false;\n    Domain& cd_j {*cd_i.m_bound_domain};\n    bool comp {check_domains_complementary(cd_i, cd_j)};\n    DeltaConfig delta_config {};\n    if (comp) {\n        delta_config = m_binding_pot->bind_domains(cd_i, cd_j);\n        m_constraints_violated = m_binding_pot->m_constraints_violated;\n    }\n    else {\n        delta_config.e += m_misbinding_pot->bind_domains(cd_i, cd_j);\n        m_constraints_violated = m_misbinding_pot->m_constraints_violated;\n    }\n    // DEBUG\n    /*if (not m_constraints_violated) {\n        if (cd_i.m_backward_domain != nullptr and\n    cd_i.m_backward_domain->m_state != Occupancy::unassigned) { VectorThree ndr\n    {cd_i.m_pos - cd_i.m_backward_domain->m_pos}; if (ndr.abssum() != 1) { cout\n    << \"Contiguous domains not on adjacent sites\\n\"; throw OrigamiMisuse {};\n            }\n        }\n        if (cd_i.m_forward_domain != nullptr and cd_i.m_forward_domain->m_state\n    != Occupancy::unassigned) { VectorThree ndr {cd_i.m_pos -\n    cd_i.m_forward_domain->m_pos}; if (ndr.abssum() != 1) { cout << \"Contiguous\n    domains not on adjacent sites\\n\"; throw OrigamiMisuse {};\n            }\n        }\n    }*/\n\n    return delta_config;\n}\n\nDeltaConfig OrigamiPotential::check_stacking(Domain& cd_i, Domain& cd_j) {\n\n    return m_binding_pot->check_stacking(cd_i, cd_j);\n}\n\ndouble OrigamiPotential::hybridization_energy(\n        const Domain& cd_i,\n        const Domain& cd_j) const {\n    pair<int, int> key {cd_i.m_d_ident, cd_j.m_d_ident};\n    return m_hybridization_energies.at(key);\n}\n\ndouble OrigamiPotential::hybridization_enthalpy(\n        const Domain& cd_i,\n        const Domain& cd_j) const {\n    pair<int, int> key {cd_i.m_d_ident, cd_j.m_d_ident};\n    return m_hybridization_enthalpies.at(key);\n}\n\ndouble OrigamiPotential::hybridization_entropy(\n        const Domain& cd_i,\n        const Domain& cd_j) const {\n    pair<int, int> key {cd_i.m_d_ident, cd_j.m_d_ident};\n    return m_hybridization_entropies.at(key);\n}\n\ndouble OrigamiPotential::init_enthalpy() const { return m_init_enthalpy; }\n\ndouble OrigamiPotential::init_entropy() const { return m_init_entropy; }\n\ndouble OrigamiPotential::init_energy() const { return m_init_energy; }\n\ndouble OrigamiPotential::stacking_energy(const Domain& cd_i, const Domain& cd_j)\n        const {\n    pair<int, int> key {cd_i.m_d_ident, cd_j.m_d_ident};\n    return m_stacking_energies.at(key);\n}\n\nbool OrigamiPotential::check_domains_complementary(Domain& cd_i, Domain& cd_j) {\n    bool comp;\n    if (cd_i.m_d_ident == -cd_j.m_d_ident) {\n        comp = true;\n    }\n    else {\n        comp = false;\n    }\n    return comp;\n}\n} // namespace potential\n", "meta": {"hexsha": "16dcc6b6753338946dedc47cfdf9d3bd73e966b2", "size": 43850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/origami_potential.cpp", "max_stars_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_stars_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-12T13:18:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-12T13:18:53.000Z", "max_issues_repo_path": "src/origami_potential.cpp", "max_issues_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_issues_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/origami_potential.cpp", "max_forks_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_forks_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_forks_repo_licenses": ["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.1443688587, "max_line_length": 80, "alphanum_fraction": 0.5991562144, "num_tokens": 12267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109132967757, "lm_q2_score": 0.02161533457465327, "lm_q1q2_score": 0.004096561798044399}}
{"text": "/*-\n * SPDX-License-Identifier: BSD-2-Clause\n * \n * Copyright (c) 2020 NKI/AVL, Netherlands Cancer Institute\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#include <fcntl.h>\n#include <iomanip>\n#include <random>\n#include <fstream>\n#include <filesystem>\n#include <mutex>\n\n#include <boost/program_options.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <zeep/http/daemon.hpp>\n#include <zeep/http/server.hpp>\n#include <zeep/http/html-controller.hpp>\n#include <zeep/http/rest-controller.hpp>\n#include <zeep/crypto.hpp>\n\n#include \"cif++/Secondary.hpp\"\n// #include \"cif++/Statistics.hpp\"\n#include \"cif++/CifUtils.hpp\"\n#include \"cif++/Cif++.hpp\"\n#include \"cif++/Structure.hpp\"\n#include \"cif++/Compound.hpp\"\n\n#include <zeep/json/element.hpp>\n\n#ifdef _MSC_VER\n//MSVC stdlib.h definitions\n#define STDIN_FILENO 0\n#define STDOUT_FILENO 1\n#define STDERR_FILENO 2\n#endif\n\nnamespace po = boost::program_options;\nnamespace fs = std::filesystem;\nnamespace ba = boost::algorithm;\n\nstd::string VERSION_STRING;\n\nusing mmcif::Atom;\nusing mmcif::Point;\nusing mmcif::Structure;\nusing mmcif::Monomer;\nusing mmcif::Polymer;\n\nusing json = zeep::json::element;\n\n// --------------------------------------------------------------------\n// simple integer compression, based somewhat on MRS code\n\nclass OBitStream\n{\n  public:\n\tOBitStream(std::vector<uint8_t>& buffer)\n\t\t: m_buffer(buffer)\n\t{\n\t\tm_buffer.push_back(0);\n\t}\n\n\tOBitStream(const OBitStream&) = delete;\n\tOBitStream& operator=(const OBitStream&) = delete;\n\n\tvoid writebit(bool bit)\n\t{\n\t\tif (bit)\n\t\t\tm_buffer.back() |= 1 << m_bitOffset;\n\t\t\n\t\tif (--m_bitOffset < 0)\n\t\t{\n\t\t\tm_buffer.push_back(0);\n\t\t\tm_bitOffset = 7;\n\t\t}\n\t}\n\n\t// write fixed size\n\tvoid write(uint32_t value, int bits)\n\t{\n\t\twhile (bits-- > 0)\n\t\t{\n\t\t\tif (value & (1UL << bits))\n\t\t\t\tm_buffer.back() |= 1 << m_bitOffset;\n\t\t\t\n\t\t\tif (--m_bitOffset < 0)\n\t\t\t{\n\t\t\t\tm_buffer.push_back(0);\n\t\t\t\tm_bitOffset = 7;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid sync()\n\t{\n\t\twritebit(0);\n\n\t\twhile (m_bitOffset != 7)\n\t\t\twritebit(1);\n\t}\n\n\tconst uint8_t* data() const\t\t\t\t\t{ return m_buffer.data(); }\n\tsize_t size() const\t\t\t\t\t\t\t{ return m_buffer.size(); }\n\n\tfriend void WriteArray(OBitStream& bs, const std::vector<uint32_t>& data);\n\n  private:\n\tstd::vector<uint8_t>& m_buffer;\n\tint m_bitOffset = 7;\n};\n\nclass IBitStream\n{\n  public:\n\tIBitStream(const uint8_t* data)\n\t\t: m_data(data), m_byte(*m_data++), m_bitOffset(7) {}\n\n\tIBitStream(const OBitStream& bits)\n\t\t: IBitStream(bits.data()) {}\n\n\tIBitStream(const IBitStream&) = delete;\n\tIBitStream& operator=(const IBitStream&) = delete;\n\n\tuint32_t read(int bc)\n\t{\n\t\tuint32_t result = 0;\n\n\t\twhile (bc > 0)\n\t\t{\n\t\t\tstatic const uint8_t kM[] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF };\n\n\t\t\tint bw = m_bitOffset + 1;\n\t\t\tif (bw > bc)\n\t\t\t\tbw = bc;\n\n\t\t\tm_bitOffset -= bw;\n\t\t\tresult = result << bw | (kM[bw] & (m_byte >> (m_bitOffset + 1)));\n\n\t\t\tif (m_bitOffset < 0)\n\t\t\t{\n\t\t\t\tm_byte = *m_data++;\n\t\t\t\tm_bitOffset = 7;\n\t\t\t}\n\n\t\t\tbc -= bw;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tfriend std::vector<uint32_t> ReadArray(IBitStream& bs);\n\n  private:\n\tconst uint8_t* m_data;\n\tuint8_t m_byte;\n\tint m_bitOffset;\n};\n\n// --------------------------------------------------------------------\n//    Arrays\n//    This is a simplified version of the array compression routines in MRS\n//    Only supported datatype is uint32_t and only supported width it 24 bit.\n\nstruct Selector\n{\n\tint32_t databits;\n\tuint32_t span;\n} const kSelectors[16] = {\n\t{  0, 1 },\n\t{ -4, 1 },\n\t{ -2, 1 }, { -2, 2 },\n\t{ -1, 1 }, { -1, 2 }, { -1, 4 },\n\t{  0, 1 }, {  0, 2 }, {  0, 4 },\n\t{  1, 1 }, {  1, 2 }, {  1, 4 },\n\t{  2, 1 }, {  2, 2 },\n\t{  4, 1 }\n};\n \n// store ints of at most 24 bits, should be enough.\nconst uint32_t kStartWidth = 8, kMaxWidth = 24;\n \ninline uint32_t bitWidth(uint32_t v)\n{\n\tuint32_t result = 0;\n\twhile (v > 0)\n\t{\n\t\tv >>= 1;\n\t\t++result;\n\t}\n\treturn result;\n}\n\nvoid CompressSimpleArraySelector(OBitStream& inBits, const std::vector<uint32_t>& inArray)\n{\n\tint32_t width = kStartWidth;\n\n\tint32_t bn[4];\n\tuint32_t dv[4];\n\tuint32_t bc = 0;\n\tauto a = inArray.begin(), e = inArray.end();\n\n\twhile (a != e or bc > 0)\n\t{\n\t\twhile (bc < 4 and a != e)\n\t\t{\n\t\t\tdv[bc] = *a++;\n\t\t\tbn[bc] = bitWidth(dv[bc]);\n\t\t\t++bc;\n\t\t}\n\n\t\tuint32_t s = 0;\n\t\tint32_t c = bn[0] - kMaxWidth;\n\n\t\tfor (uint32_t i = 1; i < 16; ++i)\n\t\t{\n\t\t\tif (kSelectors[i].span > bc)\n\t\t\t\tcontinue;\n\n\t\t\tint32_t w = width + kSelectors[i].databits;\n\n\t\t\tif (static_cast<uint32_t>(w) > kMaxWidth)\n\t\t\t\tcontinue;\n\n\t\t\tbool fits = true;\n\t\t\tint32_t waste = 0;\n\n\t\t\tswitch (kSelectors[i].span)\n\t\t\t{\n\t\t\t\tcase 4:\n\t\t\t\t\tfits = fits and bn[3] <= w;\n\t\t\t\t\twaste += w - bn[3];\n\t\t\t\t\t[[fallthrough]];\n\t\t\t\tcase 3:\n\t\t\t\t\tfits = fits and bn[2] <= w;\n\t\t\t\t\twaste += w - bn[2];\n\t\t\t\t\t[[fallthrough]];\n\t\t\t\tcase 2:\n\t\t\t\t\tfits = fits and bn[1] <= w;\n\t\t\t\t\twaste += w - bn[1];\n\t\t\t\t\t[[fallthrough]];\n\t\t\t\tcase 1:\n\t\t\t\t\tfits = fits and bn[0] <= w;\n\t\t\t\t\twaste += w - bn[0];\n\t\t\t}\n\n\t\t\tif (fits == false)\n\t\t\t\tcontinue;\n\n\t\t\tint32_t n = (kSelectors[i].span - 1) * 4 - waste;\n\n\t\t\tif (n > c)\n\t\t\t{\n\t\t\t\ts = i;\n\t\t\t\tc = n;\n\t\t\t}\n\t\t}\n\n\t\tif (s == 0)\n\t\t\twidth = kMaxWidth;\n\t\telse\n\t\t\twidth += kSelectors[s].databits;\n\n\t\tuint32_t n = kSelectors[s].span;\n\n\t\tinBits.write(s, 4);\n\n\t\tif (width > 0)\n\t\t{\n\t\t\tfor (uint32_t i = 0; i < n; ++i)\n\t\t\t\tinBits.write(dv[i], width);\n\t\t}\n\n\t\tbc -= n;\n\n\t\tif (bc > 0)\n\t\t{\n\t\t\tfor (uint32_t i = 0; i < (4 - n); ++i)\n\t\t\t{\n\t\t\t\tbn[i] = bn[i + n];\n\t\t\t\tdv[i] = dv[i + n];\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid DecompressSimpleArraySelector(IBitStream& inBits, std::vector<uint32_t>& outArray)\n{\n\tuint32_t width = kStartWidth;\n\tuint32_t span = 0;\n\t\n\t// The array should be initilialized to the expected size!\n\tauto size = outArray.size();\n\tauto a = outArray.begin();\n\n\twhile (size-- > 0)\n\t{\n\t\tif (span == 0)\n\t\t{\n\t\t\tuint32_t selector = inBits.read(4);\n\t\t\tspan = kSelectors[selector].span;\n\n\t\t\tif (selector == 0)\n\t\t\t\twidth = kMaxWidth;\n\t\t\telse\n\t\t\t\twidth += kSelectors[selector].databits;\n\t\t}\n\n\t\tif (width > 0)\n\t\t\t*a++ = inBits.read(width);\n\t\telse\n\t\t\t*a++ = 0;\n\n\t\t--span;\n\t}\n}\n\n// --------------------------------------------------------------------\n\nenum class SecStrType : char\n{\n\thelix = 'H',\n\tstrand = 'E',\n\tother = '.',\n\tcis = 'c',\n\tprepro = 'p'\n};\n\nstd::ostream& operator<<(std::ostream& os, SecStrType ss)\n{\n\tswitch (ss)\n\t{\n\t\tcase SecStrType::helix: os << \"helix\"; break;\n\t\tcase SecStrType::strand: os << \"strand\"; break;\n\t\tcase SecStrType::other: os << \"other\"; break;\n\t\tcase SecStrType::cis: os << \"cis\"; break;\n\t\tcase SecStrType::prepro: os << \"prepro\"; break;\n\t}\n\n\treturn os;\n}\n\n// --------------------------------------------------------------------\n// The header for the data blocks as written in de resource\n\nstruct StoredData\n{\n\tchar\t\taa[3];\n\tSecStrType\tss;\n\tfloat\t\tmean, mean_vs_random, sd, sd_vs_random, binSpacing;\n\tuint32_t\toffset;\t\t\t// offset into compressed data area\n};\n\nclass Data\n{\n\tfriend class DataTable;\n\n  public:\n\tData(Data&& d)\n\t\t: aa(d.aa), ss(d.ss), mean(d.mean), sd(d.sd)\n\t\t, mean_vs_random(d.mean_vs_random), sd_vs_random(d.sd_vs_random)\n\t\t, binSpacing(d.binSpacing), counts(move(d.counts))\n\t\t, dim(d.dim), d2(d.d2)\n\t{\n\t}\n\n\tData(const Data&) = delete;\n\tData& operator=(const Data&) = delete;\n\n\tData(const char* type, const std::string& aa, SecStrType ss, std::istream& is);\n\tData(bool torsion, const StoredData& data, const uint8_t* bits);\n\n\tvoid store(StoredData& data, std::vector<uint8_t>& databits);\n\n\tfloat interpolatedCount(float phi, float a2) const;\n\tfloat zscore(float a1, float a2) const\n\t{\n\t\treturn (interpolatedCount(a1, a2) - mean) / sd;\n\t}\n\n\tvoid dump() const\n\t{\n\t\tfor (size_t i = 0; i < counts.size(); ++i)\n\t\t{\n\t\t\tfloat a1, a2;\n\t\t\tstd::tie(a1, a2) = angles(i);\n\t\t\tstd::cout << a1 << ' ' << a2 << ' ' << counts[i] << std::endl;\n\t\t}\n\t}\n\n  private:\n\n\tstd::string aa;\n\tSecStrType ss;\n\tfloat mean, sd, mean_vs_random, sd_vs_random;\n\tfloat binSpacing;\n\tstd::vector<uint32_t> counts;\n\n\t// calculated\n\tsize_t dim;\n\tbool d2;\n\t\n\tfloat count(size_t a1Ix, size_t a2Ix) const\n\t{\n\t\ta1Ix %= dim;\n\t\ta2Ix %= dim;\n\t\treturn d2 ? counts.at(a1Ix * dim + a2Ix) : counts.at(a1Ix);\n\t}\n\n\tsize_t index(float a1, float a2 = 0) const\n\t{\n\t\tsize_t x = 0, y = 0;\n\n\t\tif (d2)\n\t\t{\n\t\t\tx = static_cast<size_t>((a1 + 180) / binSpacing);\n\t\t\ty = static_cast<size_t>((a2 + 180) / binSpacing);\n\t\t}\n\t\telse\n\t\t\ty = static_cast<size_t>((a1 + 180) / binSpacing);\n\n\t\treturn x * (360 / binSpacing) + y;\n\t}\n\n\tstd::tuple<float,float> angles(size_t index) const\n\t{\n\t\tsize_t x = index / dim;\n\t\tsize_t y = index % dim;\n\n\t\treturn std::make_tuple(x * binSpacing - 180, y * binSpacing - 180);\n\t}\n};\n\nData::Data(const char* type, const std::string& aa, SecStrType ss, std::istream& is)\n\t: aa(aa), ss(ss)\n{\n\t// example:\n\t// 14400 bins, aver 19.2878, sd 15.4453, binspacing 3\n\t// torsion vs random: 2.0553 2.8287\n\tstatic const std::regex\n\t\tkRX1(R\"((\\d+) bins, aver ([-+]?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?), sd ([-+]?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?), binspacing ([-+]?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?))\"),\n\t\tkRX2(R\"((torsion|rama) vs random: ([-+]?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?) ([-+]?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?))\");\n\n\tstd::string line;\n\tgetline(is, line);\n\n\td2 = strcmp(type, \"torsion\") != 0 or std::set<std::string>{\"CYS\", \"SER\", \"THR\", \"VAL\"}.count(aa) == 0;\n\n\tstd::smatch m;\n\tif (not std::regex_match(line, m, kRX1))\n\t\tthrow std::runtime_error(\"Invalid file\");\n\n\tsize_t nBins = stoi(m[1]);\n\tmean = stof(m[2]);\n\tsd = stof(m[3]);\n\tbinSpacing = stof(m[4]);\n\n\tdim = static_cast<size_t>(360 / binSpacing);\n\tif ((d2 and nBins != dim * dim) or (not d2 and nBins != dim))\n\t\tthrow std::runtime_error(\"Unexpected number of bins\");\n\n\tcounts.resize(nBins);\n\n\tgetline(is, line);\n\n\tif (not std::regex_match(line, m, kRX2) or m[1] != type)\n\t\tthrow std::runtime_error(\"Invalid file\");\n\t\n\tmean_vs_random = stof(m[2]);\n\tsd_vs_random = stof(m[3]);\n\n\tfor (size_t i = 0; i < nBins; ++i)\n\t{\n\t\tfloat a1, a2;\n\t\tuint32_t count;\n\n\t\tif (d2)\n\t\t\tis >> a1 >> a2 >> count;\n\t\telse\n\t\t\tis >> a1 >> count;\n\n\t\tif (is.eof())\n\t\t\tthrow std::runtime_error(\"truncated file?\");\n\t\t\n\t\tcounts.at(index(a1, a2)) = count;\n\t}\n}\n\nData::Data(bool torsion, const StoredData& data, const uint8_t* databits)\n{\n\taa.assign(data.aa, data.aa + 3);\n\tss = data.ss;\n\tmean = data.mean;\n\tmean_vs_random = data.mean_vs_random;\n\tsd = data.sd;\n\tsd_vs_random = data.sd_vs_random;\n\tbinSpacing = data.binSpacing;\n\t\n\td2 = not torsion or std::set<std::string>{\"CYS\", \"SER\", \"THR\", \"VAL\"}.count(aa) == 0;\n\n\tsize_t nBins = static_cast<size_t>(360 / binSpacing);\n\tdim = nBins;\n\n\tif (d2)\n\t\tnBins *= nBins;\n\n\tcounts.insert(counts.begin(), nBins, 0);\n\n\tIBitStream bits(databits + data.offset);\n\tDecompressSimpleArraySelector(bits, counts);\n}\n\nvoid Data::store(StoredData& data, std::vector<uint8_t>& databits)\n{\n\tassert(aa.length() == 3);\n\tcopy(aa.begin(), aa.end(), data.aa);\n\tdata.ss = ss;\n\tdata.mean = mean;\n\tdata.sd = sd;\n\tdata.mean_vs_random = mean_vs_random;\n\tdata.sd_vs_random = sd_vs_random;\n\tdata.offset = databits.size();\n\tdata.binSpacing = binSpacing;\n\t\n\tOBitStream bits(databits);\n\tCompressSimpleArraySelector(bits, counts);\n\tbits.sync();\n}\n\nfloat Data::interpolatedCount(float a1, float a2) const\n{\n\tconst size_t N = dim;\n\n\tfloat result;\n\n\tif (d2)\n\t{\n\t\tsize_t a1FloorIx = static_cast<size_t>(N * (a1 + 180) / 360);\n\t\tsize_t a2FloorIx = static_cast<size_t>(N * (a2 + 180) / 360);\n\t\t\n\t\tsize_t a1CeilIx = (a1FloorIx + 1);\n\t\tsize_t a2CeilIx = (a2FloorIx + 1);\n\n\t\tfloat a1FloorAngle = (a1FloorIx * 360.0f) / N - 180;\n\t\tfloat a2FloorAngle = (a2FloorIx * 360.0f) / N - 180;\n\n\t\tfloat a1CeilAngle = (a1CeilIx * 360.0f) / N - 180;\n\t\tfloat a2CeilAngle = (a2CeilIx * 360.0f) / N - 180;\n\n\t\tfloat a1Factor = a1CeilIx > a1FloorIx ? (a1 - a1FloorAngle) / (a1CeilAngle - a1FloorAngle) : 1;\n\t\tfloat a2Factor = a2CeilIx > a2FloorIx ? (a2 - a2FloorAngle) / (a2CeilAngle - a2FloorAngle) : 1;\n\n\t\tfloat c1 = count(a1FloorIx, a2FloorIx) + (count(a1CeilIx, a2FloorIx) - count(a1FloorIx, a2FloorIx)) * a1Factor;\n\t\tfloat c2 = count(a1FloorIx, a2CeilIx) + (count(a1CeilIx, a2CeilIx) - count(a1FloorIx, a2CeilIx)) * a1Factor;\n\t\t\n\t\tresult = c1 + (c2 - c1) * a2Factor;\n\t}\n\telse\n\t{\n\t\tsize_t a1FloorIx = static_cast<size_t>(N * (a1 + 180) / 360);\n\t\tsize_t a1CeilIx = (a1FloorIx + 1);\n\n\t\tfloat a1FloorAngle = (a1FloorIx * 360.0f) / N - 180;\n\t\tfloat a1CeilAngle = (a1CeilIx * 360.0f) / N - 180;\n\n\t\tfloat a1Factor = a1CeilIx > a1FloorIx ? (a1 - a1FloorAngle) / (a1CeilAngle - a1FloorAngle) : 1;\n\n\t\tresult = count(a1FloorIx, 0) + (count(a1CeilIx, 0) - count(a1FloorIx, 0)) * a1Factor;\n\t}\n\n\treturn result;\n}\n\nvoid buildDataFile(fs::path dir)\n{\n\tusing namespace std::literals;\n\n\t// first read the global mean and sd\n\n\tfloat mean_torsion, sd_torsion, mean_ramachandran, sd_ramachandran;\n\n\tstd::ifstream in(dir / \"zscores_proteins.txt\");\n\tstd::string line;\n\tconst std::regex krx(R\"((Rama|Rota): average ([-+]?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?), sd ([-+]?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?))\");\n\n\twhile (getline(in, line))\n\t{\n\t\tstd::smatch m;\n\t\tif (not std::regex_match(line, m, krx))\n\t\t\tcontinue;\n\n\t\tif (m[1] == \"Rama\")\n\t\t{\n\t\t\tmean_ramachandran = stof(m[2]);\n\t\t\tsd_ramachandran = stof(m[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmean_torsion = stof(m[2]);\n\t\t\tsd_torsion = stof(m[3]);\n\t\t}\n\t}\n\n\tstd::vector<StoredData> data;\n\tstd::vector<uint8_t> bits;\n\n\t// first ramachandran counts\n\tfor (auto aa: mmcif::kAAMap)\n\t{\n\t\tfor (std::pair<SecStrType, const char*> ss: {\n\t\t\t\tstd::make_pair(SecStrType::helix, \"helix\"),\n\t\t\t\tstd::make_pair(SecStrType::strand, \"strand\"),\n\t\t\t\tstd::make_pair(SecStrType::other, \"other\") })\n\t\t{\n\t\t\tauto p = dir / (\"rama_count_\"s + ss.second + '_' + aa.first + \".txt\");\n\t\t\tif (not fs::exists(p))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tstd::ifstream f(p);\n\t\t\tData d(\"rama\", aa.first, ss.first, f);\n\n\t\t\tStoredData sd = { };\n\t\t\td.store(sd, bits);\n\t\t\tdata.push_back(sd);\n\t\t}\n\t}\n\n\tfor (std::tuple<SecStrType, const char*, const char*> ss: {\n\t\t\tstd::make_tuple(SecStrType::cis, \"PRO\", \"cis_PRO\"),\n\t\t\tstd::make_tuple(SecStrType::prepro, \"***\", \"prepro_all_noGIV\"),\n\t\t\tstd::make_tuple(SecStrType::prepro, \"GLY\", \"prepro_GLY\"),\n\t\t\tstd::make_tuple(SecStrType::prepro, \"IV_\", \"prepro_ILEVAL\") })\n\t{\n\t\tauto p = dir / (\"rama_count_\"s + std::get<2>(ss) + \".txt\");\n\t\tif (not fs::exists(p))\n\t\t\tcontinue;\n\t\t\n\t\tstd::ifstream f(p);\n\t\tData d(\"rama\", std::get<1>(ss), std::get<0>(ss), f);\n\n\t\tStoredData sd = { };\n\t\td.store(sd, bits);\n\t\tdata.push_back(sd);\n\t}\n\n\tdata.push_back({});\n\n\tif (fs::exists(\"rama-data.bin\"))\n\t\tfs::remove(\"rama-data.bin\");\n\tstd::ofstream out(\"rama-data.bin\", std::ios::binary);\n\tif (not out.is_open())\n\t\tthrow std::runtime_error(\"Could not create rama-data.bin file\");\n\tout.write(reinterpret_cast<char*>(&mean_ramachandran), sizeof(mean_ramachandran));\n\tout.write(reinterpret_cast<char*>(&sd_ramachandran), sizeof(sd_ramachandran));\n\tout.write(reinterpret_cast<char*>(data.data()), data.size() * sizeof(StoredData));\n\tout.write(reinterpret_cast<char*>(bits.data()), bits.size());\n\tout.close();\n\n\tdata.clear();\n\tbits.clear();\n\n\t// next torsion counts\n\tfor (auto aa: mmcif::kAAMap)\n\t{\n\t\tfor (std::pair<SecStrType, const char*> ss: {\n\t\t\t\tstd::make_pair(SecStrType::helix, \"helix\"),\n\t\t\t\tstd::make_pair(SecStrType::strand, \"strand\"),\n\t\t\t\tstd::make_pair(SecStrType::other, \"other\") })\n\t\t{\n\t\t\tauto p = dir / (\"torsion_count_\"s + ss.second + '_' + aa.first + \".txt\");\n\t\t\tif (not fs::exists(p))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tstd::ifstream f(p);\n\t\t\tData d(\"torsion\", aa.first, ss.first, f);\n\n\t\t\tStoredData sd = { };\n\t\t\td.store(sd, bits);\n\t\t\tdata.push_back(sd);\n\t\t}\n\t}\n\n\tdata.push_back({});\n\n\tif (fs::exists(\"torsion-data.bin\"))\n\t\tfs::remove(\"torsion-data.bin\");\n\tout.open(\"torsion-data.bin\", std::ios::binary);\n\tif (not out.is_open())\n\t\tthrow std::runtime_error(\"Could not create torsion-data.bin file\");\n\tout.write(reinterpret_cast<char*>(&mean_torsion), sizeof(mean_torsion));\n\tout.write(reinterpret_cast<char*>(&sd_torsion), sizeof(sd_torsion));\n\tout.write(reinterpret_cast<char*>(data.data()), data.size() * sizeof(StoredData));\n\tout.write(reinterpret_cast<char*>(bits.data()), bits.size());\n\tout.close();\n}\n\n// --------------------------------------------------------------------\n\nclass DataTable\n{\n  public:\n\n\tstatic DataTable& instance()\n\t{\n\t\tstatic DataTable sInstance;\n\t\treturn sInstance;\n\t}\n\n\tconst Data& loadTorsionData(const std::string& aa, SecStrType ss) const;\n\tconst Data& loadRamachandranData(const std::string& aa, SecStrType ss) const;\n\n\tfloat mean_torsion() const\t\t{ return m_mean_torsion; }\n\tfloat sd_torsion() const\t\t{ return m_sd_torsion; }\n\tfloat mean_ramachandran() const\t{ return m_mean_ramachandran; }\n\tfloat sd_ramachandran() const\t{ return m_sd_ramachandran; }\n\n  private:\n\n\tDataTable(const DataTable& ) = delete;\n\tDataTable& operator=(const DataTable&) = delete;\n\n\tDataTable();\n\n\tvoid load(const char* name, std::vector<Data>& table, float& mean, float& sd);\n\n\tstd::vector<Data>\tm_torsion, m_ramachandran;\n\n\tfloat m_mean_torsion, m_sd_torsion, m_mean_ramachandran, m_sd_ramachandran;\n};\n\nDataTable::DataTable()\n{\n\tload(\"torsion-data.bin\", m_torsion, m_mean_torsion, m_sd_torsion);\n\tload(\"rama-data.bin\", m_ramachandran, m_mean_ramachandran, m_sd_ramachandran);\n}\n\nconst Data& DataTable::loadTorsionData(const std::string& aa, SecStrType ss) const\n{\n\tauto i = find_if(m_torsion.begin(), m_torsion.end(), [aa, ss](auto& d)\n\t\t{ return d.aa == aa and d.ss == ss; });\n\tif (i == m_torsion.end())\n\t\tthrow std::runtime_error(\"Data missing for aa = \" + aa + \" and ss = '\" + static_cast<char>(ss) + '\\'');\n\n\treturn *i;\n}\n\nconst Data& DataTable::loadRamachandranData(const std::string& aa, SecStrType ss) const\n{\n\tstd::vector<Data>::const_iterator i;\n\n\tswitch (ss)\n\t{\n\t\tcase SecStrType::cis:\n\t\t\ti = find_if(m_ramachandran.begin(), m_ramachandran.end(), [](auto& d) { return d.ss == SecStrType::cis and d.aa == \"PRO\"; });\n\t\t\tbreak;\n\n\t\tcase SecStrType::prepro:\n\t\t\ti = find_if(m_ramachandran.begin(), m_ramachandran.end(), [aa](auto& d) {\n\t\t\t\t\tbool result = false;\n\t\t\t\t\tif (d.ss == SecStrType::prepro)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (aa == \"GLY\")\n\t\t\t\t\t\t\tresult = d.aa == \"GLY\";\n\t\t\t\t\t\telse if (aa == \"ILE\" or aa == \"VAL\")\n\t\t\t\t\t\t\tresult = d.aa == \"IV_\";\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tresult = d.aa == \"***\";\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t});\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\ti = find_if(m_ramachandran.begin(), m_ramachandran.end(), [aa, ss](auto& d)\n\t\t\t\t{ return d.aa == aa and d.ss == ss; });\n\t\t\tbreak;\n\t}\n\n\tif (i == m_ramachandran.end())\n\t\tthrow std::runtime_error(\"Data missing for aa= \" + aa + \" and ss = '\" + static_cast<char>(ss) + '\\'');\n\t\n\treturn *i;\n}\n\nvoid DataTable::load(const char* name, std::vector<Data>& table, float& mean, float& sd)\n{\n\tusing namespace std::literals;\n\n\tauto rfd = cif::loadResource(name);\n\n\tif (not rfd)\n\t\tthrow std::runtime_error(\"Missing resource \"s + name);\n\n\trfd->seekg(0, rfd->end);\n\tauto size = rfd->tellg();\n\trfd->seekg(0, rfd->beg);\n\n\tconst float* fv = new float[size / sizeof(float) + 1];\n\trfd->read(reinterpret_cast<char*>(const_cast<float*>(fv)), size);\n\n\tmean = fv[0];\n\tsd = fv[1];\n\n\tconst StoredData* data = reinterpret_cast<const StoredData*>(fv + 2);\n\tsize_t ix = 0;\n\twhile (data[ix].aa[0] != 0)\n\t\t++ix;\n\t\n\tsize_t n = ix;\n\tconst uint8_t* bits = reinterpret_cast<const uint8_t*>(fv + 2) + (n + 1) * sizeof(StoredData);\n\n\tfor (ix = 0; ix < n; ++ix)\n\t\ttable.emplace_back(strcmp(name, \"torsion-data.bin\") == 0, data[ix], bits);\n}\n\n// --------------------------------------------------------------------\n\nfloat jackknife(const std::vector<float>& zScorePerResidue)\n{\n\t// jackknife variance estimate, see: https://en.wikipedia.org/wiki/Jackknife_resampling\n\n\tconst size_t N = zScorePerResidue.size();\n\tdouble zScoreSum = accumulate(zScorePerResidue.begin(), zScorePerResidue.end(), 0.0);\n\tstd::vector<double> scores(N);\n\n\tDataTable& tbl = DataTable::instance();\n\n\tdouble scoreSum = 0;\n\tfor (size_t i = 0; i < zScorePerResidue.size(); ++i)\n\t{\n\t\tdouble score = (zScoreSum - zScorePerResidue[i]) / (N - 1);\n\t\tscore = (score - tbl.mean_ramachandran()) / tbl.sd_ramachandran();\n\t\tscores[i] = score;\n\t\tscoreSum += score;\n\t}\n\n\tdouble avg = scoreSum / N;\n\tdouble sumD = accumulate(scores.begin(), scores.end(), 0.0, [avg](double a, double z) { return a + (z - avg) * (z - avg); });\n\n\treturn sqrt((N - 1) * sumD / N);\n}\n\n// --------------------------------------------------------------------\n\njson calculateZScores(const Structure& structure)\n{\n\tmmcif::DSSP dssp(structure, 3, false);\n\tauto& tbl = DataTable::instance();\n\n\tdouble ramaZScoreSum = 0;\n\tsize_t ramaZScoreCount = 0;\n\tdouble torsZScoreSum = 0;\n\tsize_t torsZScoreCount = 0;\n\n\tjson residues;\n\tstd::vector<float> ramaZScorePerResidue, torsZScorePerResidue;\n\n\tfor (auto& poly: structure.polymers())\n\t{\n\t\tfor (size_t i = 1; i + 1 < poly.size(); ++i)\n\t\t{\n\t\t\tauto& res = poly[i];\n\n\t\t\tauto phi = res.phi();\n\t\t\tauto psi = res.psi();\n\n\t\t\tif (phi == 360 or psi == 360)\n\t\t\t\tcontinue;\n\n\t\t\tstd::tuple<std::string,int,std::string,std::string> pdbID = structure.MapLabelToPDB(res.asymID(), res.seqID(), res.compoundID(), res.authSeqID());\n\n\t\t\tjson residue = {\n\t\t\t\t{ \"asymID\", res.asymID() },\n\t\t\t\t{ \"seqID\", res.seqID() },\n\t\t\t\t{ \"compID\", res.compoundID() },\n\t\t\t\t{ \"pdb\", {\n\t\t\t\t\t{ \"strandID\", std::get<0>(pdbID) },\n\t\t\t\t\t{ \"seqNum\", std::get<1>(pdbID) },\n\t\t\t\t\t{ \"compID\", std::get<2>(pdbID) },\n\t\t\t\t\t{ \"insCode\", std::get<3>(pdbID) }\n\t\t\t\t}}\n\t\t\t};\n\n\t\t\tstd::string aa = res.compoundID();\n\n\t\t\t// remap some common modified amino acids\n\t\t\tif (aa == \"MSE\")\n\t\t\t{\n\t\t\t\tif (cif::VERBOSE > 1)\n\t\t\t\t\tstd::cerr << \"Replacing MSE with MET\" << std::endl;\n\t\t\t\taa = \"MET\";\n\t\t\t}\n\t\t\telse if (aa == \"HYP\")\n\t\t\t{\n\t\t\t\tif (cif::VERBOSE > 1)\n\t\t\t\t\tstd::cerr << \"Replacing HYP with PRO\" << std::endl;\n\n\t\t\t\taa = \"PRO\";\n\t\t\t}\n\t\t\telse if (aa == \"ASX\")\n\t\t\t{\n\t\t\t\tif (cif::VERBOSE > 1)\n\t\t\t\t\tstd::cerr << \"Replacing ASX with ASP\" << std::endl;\n\n\t\t\t\taa = \"ASP\";\n\t\t\t}\n\t\t\telse if (aa == \"GLX\")\n\t\t\t{\n\t\t\t\tif (cif::VERBOSE > 1)\n\t\t\t\t\tstd::cerr << \"Replacing GLX with GLU\" << std::endl;\n\n\t\t\t\taa = \"GLU\";\n\t\t\t}\n\t\t\telse if (mmcif::kAAMap.find(aa) == mmcif::kAAMap.end())\n\t\t\t{\n\t\t\t\tif (cif::VERBOSE)\n\t\t\t\t\tstd::cerr << \"Replacing \" << aa << \" with ALA\" << std::endl;\n\n\t\t\t\taa = \"ALA\";\n\t\t\t}\n\t\t\t\n\t\t\tSecStrType tors_ss, rama_ss;\n\n\t\t\tswitch (dssp(res))\n\t\t\t{\n\t\t\t\tcase mmcif::ssAlphahelix:\ttors_ss = SecStrType::helix; break;\n\t\t\t\tcase mmcif::ssStrand:\t\ttors_ss = SecStrType::strand; break;\n\t\t\t\tdefault:\t\t\t\t\ttors_ss = SecStrType::other; break;\n\t\t\t}\n\n\t\t\tif (aa != \"PRO\" and poly[i + 1].compoundID() == \"PRO\")\n\t\t\t\trama_ss = SecStrType::prepro;\n\t\t\telse if (aa == \"PRO\" && res.isCis())\n\t\t\t\trama_ss = SecStrType::cis;\n\t\t\telse\n\t\t\t\trama_ss = tors_ss;\n\n#pragma warning \"todo\"\n\t\t\tauto& rd = tbl.loadRamachandranData(aa, rama_ss);\n\n\t\t\tauto zr = rd.zscore(phi, psi);\n\n\t\t\tresidue[\"ramachandran\"] =\n\t\t\t{\n\t\t\t\t{ \"ss-type\", boost::lexical_cast<std::string>(rama_ss) },\n\t\t\t\t{ \"z-score\", zr }\n\t\t\t};\n\n\t\t\tramaZScorePerResidue.push_back(zr);\n\n\t\t\tramaZScoreSum += zr;\n\t\t\t++ramaZScoreCount;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfloat zt = nan(\"1\");\n\n\t\t\t\tauto chiCount = res.nrOfChis();\n\t\t\t\tif (chiCount)\n\t\t\t\t{\n\t\t\t\t\tfloat chi1 = res.chi(0);\n\t\t\t\t\tfloat chi2 = chiCount > 1 ? res.chi(1) : 0;\n\n\t\t\t\t\tauto& td = tbl.loadTorsionData(aa, tors_ss);\n\n\t\t\t\t\tzt = td.zscore(chi1, chi2);\n\n\t\t\t\t\ttorsZScoreSum += zt;\n\t\t\t\t\t++torsZScoreCount;\n\n\t\t\t\t\ttorsZScorePerResidue.push_back(zt);\n\n\t\t\t\t\tresidue[\"torsion\"] =\n\t\t\t\t\t{\n\t\t\t\t\t\t{ \"ss-type\", boost::lexical_cast<std::string>(tors_ss) },\n\t\t\t\t\t\t{ \"z-score\", zt }\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (const std::exception& e)\n\t\t\t{\n\t\t\t\tif (cif::VERBOSE)\n\t\t\t\t\tstd::cerr << e.what() << '\\n';\n\t\t\t}\n\n\t\t\tresidues.push_back(residue);\n\t\t}\n\t}\n\n\tfloat ramaVsRand = ramaZScoreSum / ramaZScoreCount;\n\tfloat torsVsRand = torsZScoreSum / torsZScoreCount;\n\n\tfloat jackknifeRama = jackknife(ramaZScorePerResidue);\n\tfloat jackknifeTors = jackknife(torsZScorePerResidue);\n\n\treturn {\n\t\t{ \"ramachandran-z\", ((ramaVsRand - tbl.mean_ramachandran()) / tbl.sd_ramachandran()) },\n\t\t{ \"ramachandran-jackknife-sd\", jackknifeRama },\n\t\t{ \"torsion-z\", ((torsVsRand - tbl.mean_torsion()) / tbl.sd_torsion()) },\n\t\t{ \"torsion-jackknife-sd\", jackknifeTors },\n\t\t{ \"residues\", residues },\n\t};\n}\n\n// --------------------------------------------------------------------\n#if WEBSERVICE\n\nclass tortoize_html_controller : public zeep::http::html_controller\n{\n  public:\n\ttortoize_html_controller()\n\t\t: zeep::http::html_controller(\"tortoize\")\n\t{\n\t\tmount(\"{css,scripts,fonts,images,favicon}/\", &tortoize_html_controller::handle_file);\n\t\tmount(\"{favicon.ico,browserconfig.xml,manifest.json}\", &tortoize_html_controller::handle_file);\n\t\tmount(\"\", &tortoize_html_controller::index);\n\t}\n\n\tvoid index(const zeep::http::request& request, const zeep::http::scope& scope, zeep::http::reply& reply)\n\t{\n\t\tget_template_processor().create_reply_from_template(\"index\", scope, reply);\n\t}\n};\n\n// --------------------------------------------------------------------\n\nclass tortoize_rest_controller : public zeep::http::rest_controller\n{\n  public:\n\ttortoize_rest_controller()\n\t\t: zeep::http::rest_controller(\"\")\n\t\t, m_tempdir(fs::temp_directory_path() / \"tortoize-ws\")\n\t{\n\t\tfs::create_directories(m_tempdir);\n\n\t\tmap_post_request(\"tortoize\", &tortoize_rest_controller::calculate, \"data\", \"dict\");\n\t}\n\n\tjson calculate(const std::string& file, const std::string& dict)\n\t{\n\t\t// First store dictionary, just in case\n\n\t\tfs::path dictFile;\n\n\t\tif (not dict.empty())\\\n\t\t{\n\t\t\tdictFile = m_tempdir / (\"dict-\" + std::to_string(m_next_dict_nr++));\n\t\t\tstd::ofstream tmpFile(dictFile);\n\t\t\ttmpFile << dict;\n\n\t\t\tmmcif::CompoundFactory::instance().pushDictionary(dictFile);\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t// --------------------------------------------------------------------\n\t\t\t\n\t\t\tjson data{\n\t\t\t\t{ \"software\",\n\t\t\t\t\t{\n\t\t\t\t\t\t{ \"name\", \"tortoize\" },\n\t\t\t\t\t\t{ \"version\", VERSION_STRING },\n\t\t\t\t\t\t{ \"reference\", \"Sobolev et al. A Global Ramachandran Score Identifies Protein Structures with Unlikely Stereochemistry, Structure (2020)\" },\n\t\t\t\t\t\t{ \"reference-doi\", \"https://doi.org/10.1016/j.str.2020.08.005\" }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// --------------------------------------------------------------------\n\n\t\t\tmmcif::File f(file.data(), file.length());\n\n\t\t\tstd::set<uint32_t> models;\n\t\t\tfor (auto r: f.data()[\"atom_site\"])\n\t\t\t{\n\t\t\t\tif (not r[\"pdbx_PDB_model_num\"].empty())\n\t\t\t\t\tmodels.insert(r[\"pdbx_PDB_model_num\"].as<uint32_t>());\n\t\t\t}\n\n\t\t\tif (models.empty())\n\t\t\t\tmodels.insert(0);\n\n\t\t\tfor (auto model: models)\n\t\t\t{\n\t\t\t\tStructure structure(f, model);\n\t\t\t\tdata[\"model\"][std::to_string(model)] = calculateZScores(structure);\n\t\t\t}\n\n\t\t\tif (not dictFile.empty())\n\t\t\t{\n\t\t\t\tmmcif::CompoundFactory::instance().popDictionary();\n\t\t\t\tfs::remove(dictFile);\n\t\t\t}\n\n\t\t\treturn data;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tstd::error_code ec;\n\n\t\t\tif (not dictFile.empty())\n\t\t\t{\n\t\t\t\tmmcif::CompoundFactory::instance().popDictionary();\n\t\t\t\tfs::remove(dictFile);\n\t\t\t}\n\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tfs::path m_tempdir;\n\tsize_t m_next_dict_nr = 1;\n};\n\nint start_server(int argc, char* argv[])\n{\n\tusing namespace std::literals;\n\tnamespace zh = zeep::http;\n\n\tmmcif::CompoundFactory::init(true);\n\n\tint result = 0;\n\n\tpo::options_description visible_options(PACKAGE_NAME \" [options] input [output]\");\n\tvisible_options.add_options()\n\t\t(\"log\",\t\tpo::value<std::string>(),\t\"Write log to this file\")\n\t\t\n\t\t(\"help,h\",\t\t\t\t\t\t\t\t\"Display help message\")\n\t\t(\"version\",\t\t\t\t\t\t\t\t\"Print version\")\n\n\t\t(\"address\",\tpo::value<std::string>()->default_value(\"0.0.0.0\"),\t\t\"External address\")\n\t\t(\"port\",\tpo::value<uint16_t>()->default_value(10350),\t\t\t\"Port to listen to\")\n\t\t(\"user,u\",\tpo::value<std::string>()->default_value(\"www-data\"),\t\"User to run the daemon\")\n\n\t\t(\"no-daemon,F\",\t\t\t\t\t\t\t\"Do not fork into background\" )\n\n\t\t(\"verbose,v\",\t\t\t\t\t\t\t\"verbose output\")\n\t\t;\n\t\n\tpo::options_description hidden_options(\"hidden options\");\n\thidden_options.add_options()\n\t\t(\"command\", po::value<std::string>(),\t\"The command to execute\")\n\t\t(\"debug,d\",\tpo::value<int>(),\t\t\t\"Debug level (for even more verbose output)\")\n\t\t;\n\n\tpo::options_description cmdline_options;\n\tcmdline_options.add(visible_options).add(hidden_options);\n\n\tpo::positional_options_description p;\n\tp.add(\"command\", 1);\n\t\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n\t\n\tpo::notify(vm);\n\t\n\t// --------------------------------------------------------------------\n\t\n\tstd::string secret;\n\tif (vm.count(\"secret\"))\n\t\tsecret = vm[\"secret\"].as<std::string>();\n\telse\n\t{\n\t\tsecret = zeep::encode_base64(zeep::random_hash());\n\t\tstd::cerr << \"starting with created secret \" << secret << std::endl;\n\t}\n\n\tstd::string user = vm[\"user\"].as<std::string>();\n\tstd::string address = vm[\"address\"].as<std::string>();\n\tuint16_t port = vm[\"port\"].as<uint16_t>();\n\n\tzh::daemon server([&]()\n\t{\n\t\tauto s = new zeep::http::server();\n\n#if DEBUG\n\t\ts->set_template_processor(new zeep::http::file_based_html_template_processor(\"docroot\"));\n#else\n\t\ts->set_template_processor(new zeep::http::rsrc_based_html_template_processor());\n#endif\n\t\ts->add_controller(new tortoize_rest_controller());\n\t\ts->add_controller(new tortoize_html_controller());\n\t\treturn s;\n\t}, PACKAGE_NAME );\n\n\tstd::string command = vm[\"command\"].as<std::string>();\n\n\tif (command == \"start\")\n\t{\n\t\tstd::cout << \"starting server at http://\" << address << ':' << port << '/' << std::endl;\n\n\t\tif (vm.count(\"no-daemon\"))\n\t\t\tresult = server.run_foreground(address, port);\n\t\telse\n\t\t\tresult = server.start(address, port, 2, 2, user);\n\t\t// server.start(vm.count(\"no-daemon\"), address, port, 2, user);\n\t\t// // result = daemon::start(vm.count(\"no-daemon\"), port, user);\n\t}\n\telse if (command == \"stop\")\n\t\tresult = server.stop();\n\telse if (command == \"status\")\n\t\tresult = server.status();\n\telse if (command == \"reload\")\n\t\tresult = server.reload();\n\telse\n\t{\n\t\tstd::cerr << \"Invalid command\" << std::endl;\n\t\tresult = 1;\n\t}\n\n\treturn result;\n}\n#endif\n\n// --------------------------------------------------------------------\n\nint pr_main(int argc, char* argv[])\n{\n\tusing namespace std::literals;\n\n#if WEBSERVICE\n\tif (argc > 2 and argv[1] == \"server\"s)\n\t\treturn start_server(argc - 1, argv + 1);\n#endif\n\n\tpo::options_description visible_options(fs::path(argv[0]).filename().string() + \" [options] input [output]\");\n\tvisible_options.add_options()\n\t\t(\"log\",\t\tpo::value<std::string>(),\t\"Write log to this file\")\n\t\t\n\t\t(\"dict\",\tpo::value<std::vector<std::string>>(),\n\t\t\t\t\t\t\t\t\t\t\t\t\"Dictionary file containing restraints for residues in this specific target, can be specified multiple times.\")\n\n\t\t(\"help,h\",\t\t\t\t\t\t\t\t\"Display help message\")\n\t\t(\"version\",\t\t\t\t\t\t\t\t\"Print version\")\n\n\t\t(\"verbose,v\",\t\t\t\t\t\t\t\"verbose output\")\n\t\t;\n\t\n\tpo::options_description hidden_options(\"hidden options\");\n\thidden_options.add_options()\n\t\t(\"xyzin\",\tpo::value<std::string>(),\t\"coordinates file\")\n\t\t(\"output\",\tpo::value<std::string>(),\t\"Output to this file\")\n\t\t(\"debug,d\",\tpo::value<int>(),\t\t\t\"Debug level (for even more verbose output)\")\n\t\t(\"build\",\tpo::value<std::string>(),\t\"Build a binary data table\")\n\t\t;\n\n\tpo::options_description cmdline_options;\n\tcmdline_options.add(visible_options).add(hidden_options);\n\n\tpo::positional_options_description p;\n\tp.add(\"xyzin\", 1);\n\tp.add(\"output\", 1);\n\t\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n\t\n\tpo::notify(vm);\n\n\t// --------------------------------------------------------------------\n\n\tif (vm.count(\"version\"))\n\t{\n\t\tstd::cout << argv[0] << \" version \" << VERSION_STRING << std::endl;\n\t\texit(0);\n\t}\n\n\tif (vm.count(\"help\"))\n\t{\n\t\tstd::cout << visible_options << std::endl\n\t\t\t << std::endl\n\t\t\t << R\"(Tortoize validates protein structure models by checking the \nRamachandran plot and side-chain rotamer distributions. Quality\nZ-scores are given at the residue level and at the model level \n(ramachandran-z and torsions-z). Higher scores are better. To compare \nmodels or to describe the reliability of the model Z-scores jackknife-\nbased standard deviations are also reported (ramachandran-jackknife-sd \nand torsion-jackknife-sd).\n\nReferences: \n- Sobolev et al. A Global Ramachandran Score Identifies Protein \n  Structures with Unlikely Stereochemistry, Structure (2020),\n  DOI: https://doi.org/10.1016/j.str.2020.08.005\n- Van Beusekom et al. Homology-based loop modeling yields more complete\n  crystallographic  protein structures, IUCrJ (2018),\n  DOI: https://doi.org/10.1107/S2052252518010552\n- Hooft et al. Objectively judging the quality of a protein structure\n  from a Ramachandran plot, CABIOS (1993),\n  DOI: https://doi.org/10.1093/bioinformatics/13.4.425 \n)\" << std::endl\n\t\t\t << std::endl;\n\t\texit(0);\n\t}\n\t\n\tif (vm.count(\"build\"))\n\t{\n\t\tbuildDataFile(vm[\"build\"].as<std::string>());\n\t\texit(0);\n\t}\n\n\tif (vm.count(\"xyzin\") == 0)\n\t{\n\t\tstd::cerr << \"Input file not specified\" << std::endl;\n\t\texit(1);\n\t}\n\n\tcif::VERBOSE = vm.count(\"verbose\") != 0;\n\tif (vm.count(\"debug\"))\n\t\tcif::VERBOSE = vm[\"debug\"].as<int>();\n\n\tif (vm.count(\"log\"))\n\t{\n\t\tif (not vm.count(\"output\"))\n\t\t{\n\t\t\tstd::cerr << \"If you specify a log file, you should also specify an output file\" << std::endl;\n\t\t\texit(1);\n\t\t}\n\n\t\tstd::string logFile = vm[\"log\"].as<std::string>();\n\t\t\n\t\t// open the log file\n\t\tint fd = open(logFile.c_str(), O_CREAT|O_RDWR, 0644);\n\t\tif (fd < 0)\n\t\t\tthrow std::runtime_error(\"Opening log file \" + logFile + \" failed: \" + strerror(errno));\n\t\n\t\t// redirect stdout and stderr to the log file\n\t\tdup2(fd, STDOUT_FILENO);\n\t\tdup2(fd, STDERR_FILENO);\n\t\tclose(fd);\n\t}\n\n\tif (vm.count(\"dict\"))\n\t{\n\t\tfor (auto dict: vm[\"dict\"].as<std::vector<std::string>>())\n\t\t\tmmcif::CompoundFactory::instance().pushDictionary(dict);\n\t}\n\n\t// --------------------------------------------------------------------\n\t\n\tjson data{\n\t\t{ \"software\",\n\t\t\t{\n\t\t\t\t{ \"name\", \"tortoize\" },\n\t\t\t\t{ \"version\", VERSION_STRING },\n\t\t\t\t{ \"reference\", \"Sobolev et al. A Global Ramachandran Score Identifies Protein Structures with Unlikely Stereochemistry, Structure (2020)\" },\n\t\t\t\t{ \"reference-doi\", \"https://doi.org/10.1016/j.str.2020.08.005\" }\n\t\t\t}\n\t\t}\n\t};\n\n\t// --------------------------------------------------------------------\n\n\tmmcif::File f(vm[\"xyzin\"].as<std::string>());\n\n\tstd::set<uint32_t> models;\n\tfor (auto r: f.data()[\"atom_site\"])\n\t{\n\t\tif (not r[\"pdbx_PDB_model_num\"].empty())\n\t\t\tmodels.insert(r[\"pdbx_PDB_model_num\"].as<uint32_t>());\n\t}\n\n\tif (models.empty())\n\t\tmodels.insert(0);\n\n\tfor (auto model: models)\n\t{\n\t\tStructure structure(f, model);\n\n\t\tdata[\"model\"][std::to_string(model)] = calculateZScores(structure);\n\t}\n\n\tif (vm.count(\"output\"))\n\t{\n\t\tstd::ofstream of(vm[\"output\"].as<std::string>());\n\t\tif (not of.is_open())\n\t\t{\n\t\t\tstd::cerr << \"Could not open output file\" << std::endl;\n\t\t\texit(1);\n\t\t}\n\t\tof << data;\n\t}\n\telse\n\t\tstd::cout << data << std::endl;\n\t\n\treturn 0;\n}\n\n// --------------------------------------------------------------------\n\nnamespace {\n\tstd::string gVersionNr, gVersionDate;\n}\n\nvoid load_version_info()\n{\n\tconst std::regex\n\t\trxVersionNr(R\"(build-(\\d+)-g[0-9a-f]{7}(-dirty)?)\"),\n\t\trxVersionDate(R\"(Date: +(\\d{4}-\\d{2}-\\d{2}).*)\"),\n\t\trxVersionNr2(R\"(tortoize-version: (\\d+(?:\\.\\d+)+))\");\n\n#include \"revision.hpp\"\n\n\tstruct membuf : public std::streambuf\n\t{\n\t\tmembuf(char* data, size_t length)       { this->setg(data, data, data + length); }\n\t} buffer(const_cast<char*>(kRevision), sizeof(kRevision));\n\n\tstd::istream is(&buffer);\n\n\tstd::string line;\n\n\twhile (getline(is, line))\n\t{\n\t\tstd::smatch m;\n\n\t\tif (std::regex_match(line, m, rxVersionNr))\n\t\t{\n\t\t\tgVersionNr = m[1];\n\t\t\tif (m[2].matched)\n\t\t\t\tgVersionNr += '*';\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (std::regex_match(line, m, rxVersionDate))\n\t\t{\n\t\t\tgVersionDate = m[1];\n\t\t\tcontinue;\n\t\t}\n\n\t\t// always the first, replace with more specific if followed by the other info\n\t\tif (std::regex_match(line, m, rxVersionNr2))\n\t\t{\n\t\t\tgVersionNr = m[1];\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tif (not VERSION_STRING.empty())\n\t\tVERSION_STRING += \"\\n\";\n\tVERSION_STRING += gVersionNr + \" \" + gVersionDate;\n}\n\nstd::string get_version_nr()\n{\n\treturn gVersionNr/* + '/' + cif::get_version_nr()*/;\n}\n\nstd::string get_version_date()\n{\n\treturn gVersionDate;\n}\n\n// --------------------------------------------------------------------\n\n// recursively print exception whats:\nvoid print_what (const std::exception& e)\n{\n\tstd::cerr << e.what() << std::endl;\n\ttry\n\t{\n\t\tstd::rethrow_if_nested(e);\n\t}\n\tcatch (const std::exception& nested)\n\t{\n\t\tstd::cerr << \" >> \";\n\t\tprint_what(nested);\n\t}\n}\n\n#if not defined(TORTOIZE_TEST_NO_MAIN)\n\nint main(int argc, char* argv[])\n{\n\tint result = -1;\n\t\n\ttry\n\t{\n\t\tload_version_info();\n\t\t\n\t\tresult = pr_main(argc, argv);\n\t}\n\tcatch (std::exception& ex)\n\t{\n\t\tprint_what(ex);\n\t\texit(1);\n\t}\n\n\treturn result;\n}\n\n#endif", "meta": {"hexsha": "4c6386abeb8b18c503ac024b97e640d70842f2e6", "size": 37409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tortoize.cpp", "max_stars_repo_name": "PDB-REDO/tortoize", "max_stars_repo_head_hexsha": "90e0d9fcea0b771d58ecec844b4f853a14ea346c", "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/tortoize.cpp", "max_issues_repo_name": "PDB-REDO/tortoize", "max_issues_repo_head_hexsha": "90e0d9fcea0b771d58ecec844b4f853a14ea346c", "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/tortoize.cpp", "max_forks_repo_name": "PDB-REDO/tortoize", "max_forks_repo_head_hexsha": "90e0d9fcea0b771d58ecec844b4f853a14ea346c", "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.7577763071, "max_line_length": 160, "alphanum_fraction": 0.6138362426, "num_tokens": 11647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109132967757, "lm_q2_score": 0.02161533453526184, "lm_q1q2_score": 0.0040965617905788934}}
{"text": "// Copyright (c) 2018, Ryo Currency Project\n// Portions copyright (c) 2014-2018, The Monero Project\n//\n// Portions of this file are available under BSD-3 license. Please see ORIGINAL-LICENSE for details\n// All rights reserved.\n//\n// Authors and copyright holders give permission for following:\n//\n// 1. Redistribution and use in source and binary forms WITHOUT modification.\n//\n// 2. Modification of the source form for your own personal use.\n//\n// As long as the following conditions are met:\n//\n// 3. You must not distribute modified copies of the work to third parties. This includes\n//    posting the work online, or hosting copies of the modified work for download.\n//\n// 4. Any derivative version of this work is also covered by this license, including point 8.\n//\n// 5. Neither the name of the copyright holders nor the names of the authors may be\n//    used to endorse or promote products derived from this software without specific\n//    prior written permission.\n//\n// 6. You agree that this licence is governed by and shall be construed in accordance\n//    with the laws of England and Wales.\n//\n// 7. You agree to submit all disputes arising out of or in connection with this licence\n//    to the exclusive jurisdiction of the Courts of England and Wales.\n//\n// Authors and copyright holders agree that:\n//\n// 8. This licence expires and the work covered by it is released into the\n//    public domain on 1st of February 2019\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/*!\n * \\file electrum-words.cpp\n * \n * \\brief Mnemonic seed generation and wallet restoration from them.\n * \n * This file and its header file are for translating Electrum-style word lists\n * into their equivalent byte representations for cross-compatibility with\n * that method of \"backing up\" one's wallet keys.\n */\n\n#include \"mnemonics/electrum-words.h\"\n#include \"crypto/crypto.h\" // for declaration of crypto::secret_key\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/join.hpp>\n#include <boost/crc.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/locale.hpp>\n#include \"common/boost_locale.hpp\"\n#include <cassert>\n#include <cstdint>\n#include <fstream>\n#include <map>\n#include <stdexcept>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"chinese_simplified.h\"\n#include \"dutch.h\"\n#include \"english.h\"\n#include \"esperanto.h\"\n#include \"french.h\"\n#include \"german.h\"\n#include \"italian.h\"\n#include \"japanese.h\"\n#include \"language_base.h\"\n#include \"lojban.h\"\n#include \"portuguese.h\"\n#include \"russian.h\"\n#include \"singleton.h\"\n#include \"spanish.h\"\n\n/*!\n * \\namespace crypto\n * \n * \\brief crypto namespace.\n */\nnamespace crypto\n{\n// Polynomial chosen using https://users.ece.cmu.edu/~koopman/crc/\n// Params width=12  poly=0x987  init=0x000  refin=false  refout=false  xorout=0x000  check=0xf1a  residue=0x000\nconst uint16_t crc12_table[256] = {\n\t0x000, 0x987, 0xa89, 0x30e, 0xc95, 0x512, 0x61c, 0xf9b, 0x0ad, 0x92a, 0xa24, 0x3a3, 0xc38, 0x5bf, 0x6b1, 0xf36,\n\t0x15a, 0x8dd, 0xbd3, 0x254, 0xdcf, 0x448, 0x746, 0xec1, 0x1f7, 0x870, 0xb7e, 0x2f9, 0xd62, 0x4e5, 0x7eb, 0xe6c,\n\t0x2b4, 0xb33, 0x83d, 0x1ba, 0xe21, 0x7a6, 0x4a8, 0xd2f, 0x219, 0xb9e, 0x890, 0x117, 0xe8c, 0x70b, 0x405, 0xd82,\n\t0x3ee, 0xa69, 0x967, 0x0e0, 0xf7b, 0x6fc, 0x5f2, 0xc75, 0x343, 0xac4, 0x9ca, 0x04d, 0xfd6, 0x651, 0x55f, 0xcd8,\n\t0x568, 0xcef, 0xfe1, 0x666, 0x9fd, 0x07a, 0x374, 0xaf3, 0x5c5, 0xc42, 0xf4c, 0x6cb, 0x950, 0x0d7, 0x3d9, 0xa5e,\n\t0x432, 0xdb5, 0xebb, 0x73c, 0x8a7, 0x120, 0x22e, 0xba9, 0x49f, 0xd18, 0xe16, 0x791, 0x80a, 0x18d, 0x283, 0xb04,\n\t0x7dc, 0xe5b, 0xd55, 0x4d2, 0xb49, 0x2ce, 0x1c0, 0x847, 0x771, 0xef6, 0xdf8, 0x47f, 0xbe4, 0x263, 0x16d, 0x8ea,\n\t0x686, 0xf01, 0xc0f, 0x588, 0xa13, 0x394, 0x09a, 0x91d, 0x62b, 0xfac, 0xca2, 0x525, 0xabe, 0x339, 0x037, 0x9b0,\n\t0xad0, 0x357, 0x059, 0x9de, 0x645, 0xfc2, 0xccc, 0x54b, 0xa7d, 0x3fa, 0x0f4, 0x973, 0x6e8, 0xf6f, 0xc61, 0x5e6,\n\t0xb8a, 0x20d, 0x103, 0x884, 0x71f, 0xe98, 0xd96, 0x411, 0xb27, 0x2a0, 0x1ae, 0x829, 0x7b2, 0xe35, 0xd3b, 0x4bc,\n\t0x864, 0x1e3, 0x2ed, 0xb6a, 0x4f1, 0xd76, 0xe78, 0x7ff, 0x8c9, 0x14e, 0x240, 0xbc7, 0x45c, 0xddb, 0xed5, 0x752,\n\t0x93e, 0x0b9, 0x3b7, 0xa30, 0x5ab, 0xc2c, 0xf22, 0x6a5, 0x993, 0x014, 0x31a, 0xa9d, 0x506, 0xc81, 0xf8f, 0x608,\n\t0xfb8, 0x63f, 0x531, 0xcb6, 0x32d, 0xaaa, 0x9a4, 0x023, 0xf15, 0x692, 0x59c, 0xc1b, 0x380, 0xa07, 0x909, 0x08e,\n\t0xee2, 0x765, 0x46b, 0xdec, 0x277, 0xbf0, 0x8fe, 0x179, 0xe4f, 0x7c8, 0x4c6, 0xd41, 0x2da, 0xb5d, 0x853, 0x1d4,\n\t0xd0c, 0x48b, 0x785, 0xe02, 0x199, 0x81e, 0xb10, 0x297, 0xda1, 0x426, 0x728, 0xeaf, 0x134, 0x8b3, 0xbbd, 0x23a,\n\t0xc56, 0x5d1, 0x6df, 0xf58, 0x0c3, 0x944, 0xa4a, 0x3cd, 0xcfb, 0x57c, 0x672, 0xff5, 0x06e, 0x9e9, 0xae7, 0x360};\n\ninline void update_crc12(uint32_t &crcv, uint8_t data)\n{\n\tuint8_t idx = uint8_t((crcv >> 4) ^ data);\n\tcrcv = crc12_table[idx] ^ (crcv << 8);\n}\n\nuint32_t calc_crc12(const crypto::secret_key_16 &key, uint8_t extra)\n{\n\tuint32_t crcv = 0;\n\tfor(size_t i = 0; i < 16; i++)\n\t\tupdate_crc12(crcv, tools::unwrap(key).data[i]);\n\tupdate_crc12(crcv, extra);\n\treturn crcv & 0xfff;\n}\n\n/*!\n   * \\namespace crypto::ElectrumWords\n   * \n   * \\brief Mnemonic seed word generation and wallet restoration helper functions.\n   */\n/*!\n   * \\brief Finds the word list that contains the seed words and puts the indices\n   *        where matches occured in matched_indices.\n   * \\param  seed            List of words to match.\n   * \\param  has_checksum    The seed has a checksum word (maybe not checked).\n   * \\param  matched_indices The indices where the seed words were found are added to this.\n   * \\param  language        Language instance pointer to write to after it is found.\n   * \\return                 true if all the words were present in some language false if not.\n   */\nbool find_seed_language(const std::vector<std::string> &seed, Language::Base **language)\n{\n\t// Yes, I don't like std::pair\n\tstruct sort_pair\n\t{\n\t\tLanguage::Base *inst;\n\t\tsize_t score;\n\n\t\tinline bool operator<(const sort_pair &oth) const { return score < oth.score; }\n\t};\n\n\t// If there's a new language added, add an instance of it here.\n\tstd::vector<sort_pair> language_instances({{Language::Singleton<Language::Chinese_Simplified>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::English>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Dutch>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::French>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Spanish>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::German>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Italian>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Portuguese>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Japanese>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Russian>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Esperanto>::instance(), 0},\n\t\t\t\t\t\t\t\t\t\t\t   {Language::Singleton<Language::Lojban>::instance(), 0}});\n\n\t// Assumption here is that the end user will spell more words correctly than get at random in a foreign lang\n\tfor(sort_pair &pair : language_instances)\n\t{\n\t\tconst std::unordered_map<std::string, uint32_t> &word_map = pair.inst->get_word_map();\n\t\tfor(const std::string &word : seed)\n\t\t{\n\t\t\tif(word_map.count(word) > 0)\n\t\t\t\tpair.score++;\n\t\t}\n\t}\n\n\tstd::sort(language_instances.begin(), language_instances.end());\n\n\tif(language_instances.back().score > 0)\n\t{\n\t\t*language = language_instances.back().inst;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool match_words(const Language::Base &lang, const std::vector<std::string> &seed, std::vector<uint32_t> &matched_indices)\n{\n\tsize_t trim_size = lang.get_unique_prefix_length();\n\tconst std::unordered_map<std::string, uint32_t> &trimmed_word_map = lang.get_trimmed_word_map();\n\tmatched_indices.reserve(seed.size());\n\n\tfor(const std::string &word : seed)\n\t{\n\t\tstd::string trimmed_word = Language::utf8prefix(word, trim_size);\n\t\tif(trimmed_word_map.count(trimmed_word) > 0)\n\t\t\tmatched_indices.push_back(trimmed_word_map.at(trimmed_word));\n\t\telse\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nnamespace Electrum\n{\n\n/*!\n     * \\brief Gets a list of seed languages that are supported.\n     * \\param languages The vector is set to the list of languages.\n     */\nconst std::vector<const Language::Base *> &get_language_list()\n{\n\tstatic const std::vector<const Language::Base *> language_instances({Language::Singleton<Language::German>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::English>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Spanish>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::French>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Italian>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Dutch>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Portuguese>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Russian>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Japanese>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Chinese_Simplified>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Esperanto>::instance(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Language::Singleton<Language::Lojban>::instance()});\n\treturn language_instances;\n}\n\nvoid get_language_list(std::vector<std::string> &languages, bool english)\n{\n\tconst std::vector<const Language::Base *> language_instances = get_language_list();\n\tfor(std::vector<const Language::Base *>::const_iterator it = language_instances.begin();\n\t\tit != language_instances.end(); it++)\n\t{\n\t\tlanguages.push_back(english ? (*it)->get_english_language_name() : (*it)->get_language_name());\n\t}\n}\n\nstd::string get_english_name_for(const std::string &name)\n{\n\tconst std::vector<const Language::Base *> language_instances = get_language_list();\n\tfor(std::vector<const Language::Base *>::const_iterator it = language_instances.begin();\n\t\tit != language_instances.end(); it++)\n\t{\n\t\tif((*it)->get_language_name() == name)\n\t\t\treturn (*it)->get_english_language_name();\n\t}\n\treturn \"<language not found>\";\n}\n\nstd::string verify_language_input(std::string input)\n{\n\tboost_locale_init();\n\tinput = boost::locale::to_title(input);\n\n\tfor(const Language::Base* lng : get_language_list())\n\t{\n\t\tif(lng->get_language_name() == input)\n\t\t\treturn lng->get_language_name();\n\t\t\n\t\tif(lng->get_english_language_name() == input)\n\t\t\treturn lng->get_language_name();\n\t}\n\treturn \"\";\n}\n}\n\nnamespace Electrum14Words\n{\nbool words_to_bytes(std::string words, crypto::secret_key_16 &dst, uint8_t &extra, std::string &language_name)\n{\n\tstd::vector<std::string> seed;\n\n\tboost::algorithm::trim(words);\n\tboost::split(seed, words, boost::is_any_of(\" \"), boost::token_compress_on);\n\n\tif(seed.size() != 14 && seed.size() != 12)\n\t\treturn false;\n\n\tLanguage::Base *language;\n\tif(!find_seed_language(seed, &language))\n\t\treturn false;\n\n\tstd::vector<uint32_t> matched_indices;\n\tif(!match_words(*language, seed, matched_indices))\n\t\treturn false;\n\n\tlanguage_name = language->get_language_name();\n\tuint32_t word_list_length = language->get_word_list().size();\n\n\tuint32_t *out = (uint32_t *)tools::unwrap(dst).data;\n\tfor(unsigned int i = 0; i < seed.size() / 3; i++)\n\t{\n\t\tuint32_t val;\n\t\tuint32_t w1, w2, w3;\n\t\tw1 = matched_indices[i * 3];\n\t\tw2 = matched_indices[i * 3 + 1];\n\t\tw3 = matched_indices[i * 3 + 2];\n\n\t\tval = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length) +\n\t\t\t  word_list_length * word_list_length * (((word_list_length - w2) + w3) % word_list_length);\n\n\t\tif(!(val % word_list_length == w1))\n\t\t\treturn false;\n\t\tout[i] = val;\n\t}\n\n\tif(seed.size() == 14)\n\t{\n\t\tuint32_t val;\n\t\tuint32_t w1, w2;\n\t\tw1 = matched_indices[12];\n\t\tw2 = matched_indices[13];\n\n\t\tval = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length);\n\t\tval &= 0xfffff; // 20 bytes\n\n\t\textra = uint8_t(val & 0xff);\n\t\tval >>= 8;\n\n\t\tif(calc_crc12(dst, extra) != val)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool bytes_to_words(const crypto::secret_key_16 &src, uint8_t extra, std::string &words, const std::string &language_name)\n{\n\tconst std::vector<const Language::Base *> &lng_insts = Electrum::get_language_list();\n\tconst Language::Base *language = nullptr;\n\tfor(const Language::Base *b : lng_insts)\n\t{\n\t\tif(b->get_language_name() == language_name || b->get_english_language_name() == language_name)\n\t\t{\n\t\t\tlanguage = b;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(language == nullptr)\n\t\treturn false;\n\n\tconst std::vector<std::string> &word_list = language->get_word_list();\n\n\tuint32_t word_list_length = word_list.size();\n\tconst uint32_t *psrc = (const uint32_t *)tools::unwrap(src).data;\n\tfor(unsigned int i = 0; i < 4; i++, words += ' ')\n\t{\n\t\tuint32_t w1, w2, w3;\n\t\tuint32_t val = psrc[i];\n\n\t\tw1 = val % word_list_length;\n\t\tw2 = ((val / word_list_length) + w1) % word_list_length;\n\t\tw3 = (((val / word_list_length) / word_list_length) + w2) % word_list_length;\n\n\t\twords += word_list[w1];\n\t\twords += ' ';\n\t\twords += word_list[w2];\n\t\twords += ' ';\n\t\twords += word_list[w3];\n\t}\n\n\tuint32_t w1, w2;\n\tuint32_t checksum = calc_crc12(src, extra);\n\tchecksum <<= 8;\n\tchecksum |= extra;\n\n\tw1 = checksum % word_list_length;\n\tw2 = ((checksum / word_list_length) + w1) % word_list_length;\n\twords += word_list[w1];\n\twords += ' ';\n\twords += word_list[w2];\n\n\treturn true;\n}\n}\n\nnamespace Electrum25Words\n{\n/*!\n   * \\brief Creates a checksum index in the word list array on the list of words.\n   * \\param  word_list            Vector of words\n   * \\param unique_prefix_length  the prefix length of each word to use for checksum\n   * \\return                      Checksum index\n   */\nuint32_t create_checksum_index(const std::vector<std::string> &word_list, uint32_t unique_prefix_length)\n{\n\tstd::string trimmed_words = \"\";\n\n\tfor(std::vector<std::string>::const_iterator it = word_list.begin(); it != word_list.end(); it++)\n\t{\n\t\tif(it->length() > unique_prefix_length)\n\t\t{\n\t\t\ttrimmed_words += Language::utf8prefix(*it, unique_prefix_length);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttrimmed_words += *it;\n\t\t}\n\t}\n\tboost::crc_32_type result;\n\tresult.process_bytes(trimmed_words.data(), trimmed_words.length());\n\treturn result.checksum() % seed_length;\n}\n\n/*!\n   * \\brief Does the checksum test on the seed passed.\n   * \\param seed                  Vector of seed words\n   * \\param unique_prefix_length  the prefix length of each word to use for checksum\n   * \\return                      True if the test passed false if not.\n   */\nbool checksum_test(std::vector<std::string> seed, uint32_t unique_prefix_length)\n{\n\tif(seed.empty())\n\t\treturn false;\n\t// The last word is the checksum.\n\tstd::string last_word = seed.back();\n\tseed.pop_back();\n\n\tstd::string checksum = seed[create_checksum_index(seed, unique_prefix_length)];\n\n\tstd::string trimmed_checksum = checksum.length() > unique_prefix_length ? Language::utf8prefix(checksum, unique_prefix_length) : checksum;\n\tstd::string trimmed_last_word = last_word.length() > unique_prefix_length ? Language::utf8prefix(last_word, unique_prefix_length) : last_word;\n\treturn trimmed_checksum == trimmed_last_word;\n}\n\n/*!\n     * \\brief Converts seed words to bytes (secret key).\n     * \\param  words           String containing the words separated by spaces.\n     * \\param  dst             To put the secret data restored from the words.\n     * \\param  len             The number of bytes to expect, 0 if unknown\n     * \\param  duplicate       If true and len is not zero, we accept half the data, and duplicate it\n     * \\param  language_name   Language of the seed as found gets written here.\n     * \\return                 false if not a multiple of 3 words, or if word is not in the words list\n     */\nbool words_to_bytes(std::string words, std::string &dst, size_t len, std::string &language_name)\n{\n\tstd::vector<std::string> seed;\n\n\tboost::algorithm::trim(words);\n\tboost::split(seed, words, boost::is_any_of(\" \"), boost::token_compress_on);\n\n\tif(len % 4)\n\t\treturn false;\n\n\tif(seed.size() == 26) //Last word is a funky sumo attempt at a second checksum, ignore it\n\t\tseed.pop_back();\n\n\tbool has_checksum = true;\n\tif(len)\n\t{\n\t\t// error on non-compliant word list\n\t\tconst size_t expected = len * 8 * 3 / 32;\n\t\tif(seed.size() != expected / 2 && seed.size() != expected && seed.size() != expected + 1)\n\t\t\treturn false;\n\n\t\t// If it is seed with a checksum.\n\t\thas_checksum = seed.size() == (expected + 1);\n\t}\n\n\tLanguage::Base *language;\n\tif(!find_seed_language(seed, &language))\n\t\treturn false;\n\n\tstd::vector<uint32_t> matched_indices;\n\tif(!match_words(*language, seed, matched_indices))\n\t\treturn false;\n\n\tlanguage_name = language->get_language_name();\n\tuint32_t word_list_length = language->get_word_list().size();\n\n\tif(has_checksum)\n\t{\n\t\tif(!checksum_test(seed, language->get_unique_prefix_length()))\n\t\t{\n\t\t\t// Checksum fail\n\t\t\treturn false;\n\t\t}\n\t\tseed.pop_back();\n\t}\n\n\tfor(unsigned int i = 0; i < seed.size() / 3; i++)\n\t{\n\t\tuint32_t val;\n\t\tuint32_t w1, w2, w3;\n\t\tw1 = matched_indices[i * 3];\n\t\tw2 = matched_indices[i * 3 + 1];\n\t\tw3 = matched_indices[i * 3 + 2];\n\n\t\tval = w1 + word_list_length * (((word_list_length - w1) + w2) % word_list_length) +\n\t\t\t  word_list_length * word_list_length * (((word_list_length - w2) + w3) % word_list_length);\n\n\t\tif(!(val % word_list_length == w1))\n\t\t\treturn false;\n\n\t\tdst.append((const char *)&val, 4); // copy 4 bytes to position\n\t}\n\n\treturn true;\n}\n\n/*!\n     * \\brief Converts seed words to bytes (secret key).\n     * \\param  words           String containing the words separated by spaces.\n     * \\param  dst             To put the secret key restored from the words.\n     * \\param  language_name   Language of the seed as found gets written here.\n     * \\return                 false if not a multiple of 3 words, or if word is not in the words list\n     */\nbool words_to_bytes(std::string words, crypto::secret_key &dst, std::string &language_name)\n{\n\tstd::string s;\n\tif(!words_to_bytes(words, s, sizeof(dst), language_name))\n\t\treturn false;\n\tif(s.size() != sizeof(dst))\n\t\treturn false;\n\tdst = *(const crypto::secret_key *)s.data();\n\treturn true;\n}\n\n/*!\n     * \\brief Converts bytes (secret key) to seed words.\n     * \\param  src           Secret key\n     * \\param  words         Space delimited concatenated words get written here.\n     * \\param  language_name Seed language name\n     * \\return               true if successful false if not. Unsuccessful if wrong key size.\n     */\nbool bytes_to_words(const char *src, size_t len, std::string &words, const std::string &language_name)\n{\n\tif(len % 4 != 0 || len == 0)\n\t\treturn false;\n\n\tconst std::vector<const Language::Base *> &lng_insts = Electrum::get_language_list();\n\tconst Language::Base *language = nullptr;\n\tfor(const Language::Base *b : lng_insts)\n\t{\n\t\tif(b->get_language_name() == language_name || b->get_english_language_name() == language_name)\n\t\t{\n\t\t\tlanguage = b;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(language == nullptr)\n\t\treturn false;\n\n\tconst std::vector<std::string> &word_list = language->get_word_list();\n\t// To store the words for random access to add the checksum word later.\n\tstd::vector<std::string> words_store;\n\n\tuint32_t word_list_length = word_list.size();\n\t// 4 bytes -> 3 words.  8 digits base 16 -> 3 digits base 1626\n\tfor(unsigned int i = 0; i < len / 4; i++, words += ' ')\n\t{\n\t\tuint32_t w1, w2, w3;\n\n\t\tuint32_t val;\n\n\t\tmemcpy(&val, src + (i * 4), 4);\n\n\t\tw1 = val % word_list_length;\n\t\tw2 = ((val / word_list_length) + w1) % word_list_length;\n\t\tw3 = (((val / word_list_length) / word_list_length) + w2) % word_list_length;\n\n\t\twords += word_list[w1];\n\t\twords += ' ';\n\t\twords += word_list[w2];\n\t\twords += ' ';\n\t\twords += word_list[w3];\n\n\t\twords_store.push_back(word_list[w1]);\n\t\twords_store.push_back(word_list[w2]);\n\t\twords_store.push_back(word_list[w3]);\n\t}\n\n\twords.pop_back();\n\twords += (' ' + words_store[create_checksum_index(words_store, language->get_unique_prefix_length())]);\n\treturn true;\n}\n\nbool bytes_to_words(const crypto::secret_key &src, std::string &words, const std::string &language_name)\n{\n\treturn bytes_to_words(src.data, sizeof(src), words, language_name);\n}\n}\n}\n", "meta": {"hexsha": "28af2ff76ecb37d2d49b28b27cbac81af9076dc6", "size": 20750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mnemonics/electrum-words.cpp", "max_stars_repo_name": "cryptoseyed/ryo-currency", "max_stars_repo_head_hexsha": "362ed1b70c82c06a27131aeb1f9ec456df29b8e5", "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/mnemonics/electrum-words.cpp", "max_issues_repo_name": "cryptoseyed/ryo-currency", "max_issues_repo_head_hexsha": "362ed1b70c82c06a27131aeb1f9ec456df29b8e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mnemonics/electrum-words.cpp", "max_forks_repo_name": "cryptoseyed/ryo-currency", "max_forks_repo_head_hexsha": "362ed1b70c82c06a27131aeb1f9ec456df29b8e5", "max_forks_repo_licenses": ["BSD-3-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.2292020374, "max_line_length": 143, "alphanum_fraction": 0.6864578313, "num_tokens": 6261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952108675195603, "lm_q2_score": 0.021615332486907682, "lm_q1q2_score": 0.004096561303423604}}
{"text": "//\n// Created by veyry_p on 7/11/15.\n//\n\n#include <iostream>\n#include <chrono>\n#include <numeric>\n#include <SFML/Graphics/Sprite.hpp>\n#include <SFML/Graphics/Texture.hpp>\n#include <SFML/Graphics/RectangleShape.hpp>\n#include <SFML/Graphics/RenderTexture.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n#include \"strong-classifier.h\"\n#include \"../features/four-rectangles-feature.h\"\n#include \"../features/three-horizontal-rectangles-feature.h\"\n#include \"../config.h\"\n#include \"../features/two-vertical-rectangles-feature.h\"\n#include \"../features/two-horizontal-rectangles-feature.h\"\n#include \"../features/three-vertical-rectangles-feature.h\"\n\nextern void select_best_gpu(int featureNum, int testNum, bool * valids, double * weights, double validweight, int * featureIndex,\n    int* index, bool* good, double* error);\n\nnamespace violajones\n{\n  StrongClassifier::StrongClassifier(std::vector<WeakClassifier> classifiers)\n          : classifiers_{classifiers}\n  {\n    long double galpha = 0;\n    for (auto& classifier : classifiers)\n      galpha += classifier.alpha_;\n\n    global_alpha_ = galpha;\n  }\n\n  bool StrongClassifier::check(Window win, std::shared_ptr<IntegralImage> image)\n  {\n    long double sumvalues = 0.0;\n    for (auto& weakclass : classifiers_)\n      sumvalues += weakclass.get_value(win, image);\n\n    bool tmp = sumvalues >= (global_alpha_ / 2.0);\n    if (Config::debug_classifier_check)\n      std::cout << \"StrongClassifier::check \" << tmp\n      << \" - sumvalues: \" << sumvalues\n      << \" global_alpha: \" << global_alpha_ << std::endl;\n\n    return tmp;\n  }\n\n  void StrongClassifier::save(std::string path)\n  {\n    std::ofstream fs;\n    fs.open(path);\n    for (auto& classif : classifiers_)\n      fs << classif.alpha_ << \" \"\n      << classif.threshold_ << \" \"\n      << (int)classif.parity_ << \" \"\n      << classif.feature_->get_type() << \" \"\n      << classif.feature_->frame.top_left.x << \" \"\n      << classif.feature_->frame.top_left.y << \" \"\n      << classif.feature_->frame.width << \" \"\n      << classif.feature_->frame.height << std::endl;\n    fs.close();\n  }\n\n  StrongClassifier StrongClassifier::load_from_file(std::string path)\n  {\n    std::function<WeakClassifier(std::string&)> restore_classifier =\n            [](std::string& s) {\n              std::vector<std::string> tokens;\n              boost::split(tokens, s, boost::is_any_of(\" ;\"));\n              double alpha = std::stod(tokens[0]);\n              int threshold = std::stoi(tokens[1]);\n              char parity = (char) std::stoi(tokens[2]);\n              std::string feature_type = tokens[3];\n\n              int featurex = std::stoi(tokens[4]);\n              int featurey = std::stoi(tokens[5]);\n              int featurewidth = std::stoi(tokens[6]);\n              int featureheight = std::stoi(tokens[7]);\n\n              Rectangle feature_frame(Point(featurex, featurey), featurewidth, featureheight);\n              if (feature_type == \"FourRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity, std::make_shared<FourRectanglesFeature>(feature_frame));\n              else if (feature_type == \"ThreeHorizontalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<ThreeHorizontalRectanglesFeature>(feature_frame));\n              else if (feature_type == \"ThreeVerticalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<ThreeVerticalRectanglesFeature>(feature_frame));\n              else if (feature_type == \"TwoHorizontalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<TwoHorizontalRectanglesFeature>(feature_frame));\n              else if (feature_type == \"TwoVerticalRectanglesFeature\")\n                return WeakClassifier(alpha, threshold, parity,\n                                      std::make_shared<TwoVerticalRectanglesFeature>(feature_frame));\n\n              std::cerr << \"Fatal Error: feature_type \" << feature_type << std::endl;\n              return WeakClassifier(alpha, threshold, parity, std::make_shared<FourRectanglesFeature>(feature_frame));\n            };\n\n    std::ifstream infile(path);\n    std::string line;\n    std::vector<WeakClassifier> classifiers;\n    while (std::getline(infile, line))\n      classifiers.push_back(restore_classifier(line));\n    return StrongClassifier(classifiers);\n  }\n\n  StrongClassifier StrongClassifier::train(std::string tests_dir)\n  {\n    std::cout << \"Initializing Trainer ...\\n\"\n    << \"Loading trainer tests ...\" << std::endl;\n    auto start = std::chrono::steady_clock::now();\n    auto tests_set = load_tests_set(tests_dir);\n    \n    auto& tests = tests_set.first;\n    auto& features_values = tests_set.second;\n    int ncached_features = 0;\n\n    std::cout << \"loading the features\\n\";\n    /*\n    if (Config::parallelized)\n      tbb::parallel_for_each(features_values.begin(), features_values.end(),\n                             [&ncached_features](FeatureValues& ftvalues) {\n                               if (ftvalues.values_.size())\n                                 ++ncached_features;\n                             });\n    else\n    */\n      for (FeatureValues& ftvalues : features_values)\n        if (ftvalues.values_.size())\n          ++ncached_features;\n\n    std::cout << \"loading the features completed\\n\";\n\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double> diff = end - start;\n\n    std::cout << \"Tests loaded in \" << diff.count() << \" seconds (\"\n    << ncached_features * 100 / features_values.size()\n    << \"% cached)\\n Launching training...\" << std::endl;\n\n    std::vector<WeakClassifier> classifiers;\n    unsigned ipass = 1;\n    auto global_start = std::chrono::steady_clock::now();\n\n    std::cout<<\"Need \"<<Config::learn_pass<<\" pass\"<<std::endl;\n\n    // Bo Li\n    int featureNum = features_values.size();\n    int testNum = tests.size();\n    int * featureIndexfeatures_values = (int *)malloc(featureNum * testNum * sizeof(int));\n    //std::cout << \" Feature test index in gpu is \";\n    for(int i=0; i<featureNum; ++i){\n      for(int j=0; j<testNum; ++j){\n        featureIndexfeatures_values[i*testNum + j] = features_values[i].values_[j].test_index_;\n        //std::cout<<featureIndexfeatures_values[i*testNum + j]<<\" \";\n      }\n      //std::cout<<std::endl;\n    }\n\n    //Read Only Data\n    size_t bytesV = testNum * sizeof( bool );\n    bool * valids = (bool*)malloc(bytesV);\n    size_t bytesF = testNum*sizeof(double);\n    double* weights = (double*)malloc(bytesF);\n\n    //Each Iteration Best\n      int* indexResult = (int*)malloc(featureNum*sizeof(int));\n      bool* goodResult = (bool*)malloc(featureNum*sizeof(bool));\n      double* errorResult = (double*)malloc(featureNum*sizeof(double));\n\n    while (ipass <= Config::learn_pass)\n    {\n      start = std::chrono::steady_clock::now();\n      std::cout << ipass << \"/\" << Config::learn_pass << \" trainer pass...\" << std::endl;\n      double weightsum = std::accumulate(tests.begin(), tests.end(), 0.0,\n                                         [](double acc, TestImage& t) { return t.weight_ + acc; });\n\n      double validweight = 0.0;\n      for (size_t i = 0; i < tests.size(); ++i)\n      {\n        tests[i].weight_ = tests[i].weight_ / weightsum;\n        if (tests[i].valid_)\n          validweight += tests[i].weight_;\n      }\n\n\n      TestWeakClassifier best(features_values[0], 0, 1, std::numeric_limits<double>::max());\n      /*\n      if (Config::parallelized)\n      {\n        tbb::parallel_for_each(features_values.begin(), features_values.end(),\n                               [&](FeatureValues& fv) {\n                                 auto new_classifier = TestWeakClassifier::train(tests, validweight, fv);\n                                 tbb::mutex::scoped_lock lock;\n                                 lock.acquire(mutex);\n                                 if (best.errors_ > new_classifier.errors_)\n                                   best = new_classifier;\n                                 lock.release();\n                               });\n      }\n      else\n      */\n\n      for(int i=0; i<testNum; ++i){\n          valids[i] = tests[i].valid_;\n          weights[i] = tests[i].weight_;\n          //std::cout << valids[i] << \" with \"<< weights[i] << std::endl;\n      }\n\n      auto GPUstart = std::chrono::steady_clock::now();\n      select_best_gpu(featureNum, testNum, valids, weights, validweight, featureIndexfeatures_values,\n         indexResult, goodResult, errorResult);\n      auto GPUend = std::chrono::steady_clock::now();\n\n      int b_index = 0;\n      bool b_good = 0;\n      double b_error = std::numeric_limits<double>::max();\n      int f_index = 0;\n      for(int i=0; i<featureNum; ++i) {\n        //std::cout << i << \"th training result is \" << errorResult[i] << \" with index \" << indexResult[i] <<std::endl;\n        if(errorResult[i] < b_error){\n          b_error = errorResult[i];\n          b_good = goodResult[i];\n          b_index = indexResult[i];\n          f_index = i;\n        }\n      }\n      std::chrono::duration<double> GPUdiff = GPUend - GPUstart;\n      TestWeakClassifier bestGPU(features_values[f_index], \n          features_values[f_index].values_[b_index].value_ + ((b_good)?1:-1), b_good, b_error);\n      std::cout << \"GPU New weak classifier selected in \" << GPUdiff.count() << \" seconds (error score : \"\n      << bestGPU.errors_ << \")\\n\"\n      << \"X: \" << bestGPU.feature_.feature_->frame.top_left.x\n      << \" Y: \" << bestGPU.feature_.feature_->frame.top_left.y\n      << \" - Width: \" << bestGPU.feature_.feature_->frame.width\n      << \" Height: \" << bestGPU.feature_.feature_->frame.height << std::endl;\n\n      //Bo Li CPU\n      /*\n      auto CPUstart = std::chrono::steady_clock::now();\n      std::for_each(features_values.begin(), features_values.end(),\n                      [&](FeatureValues& fv) {\n                        \n                        auto new_classifier = TestWeakClassifier::train(tests, validweight, fv);\n                        //std::cout << \" New Featrue CPU is \" << new_classifier.errors_ << \" errors \\n\";\n                        if (best.errors_ > new_classifier.errors_)\n                          best = new_classifier;\n                      });\n      auto CPUend = std::chrono::steady_clock::now();\n      std::chrono::duration<double> CPUdiff = CPUend - CPUstart;\n\n      std::cout << \"CPU New weak classifier selected in \" << CPUdiff.count() << \" seconds (error score : \"\n      << best.errors_ << \")\\n\"\n      << \"X: \" << best.feature_.feature_->frame.top_left.x\n      << \" Y: \" << best.feature_.feature_->frame.top_left.y\n      << \" - Width: \" << best.feature_.feature_->frame.width\n      << \" Height: \" << best.feature_.feature_->frame.height << std::endl;\n      */\n      best = bestGPU;\n      double beta = best.errors_ / (1.0 - best.errors_);\n      if (beta < 1.0 / 100000000)\n        beta = 1.0 / 100000000;\n\n      for (FeatureValue& featurevalue : best.feature_.values_)\n        if (best.check(featurevalue.value_) == tests[featurevalue.test_index_].valid_)\n          tests[featurevalue.test_index_].weight_ *= beta;\n\n      auto alpha = std::log(1.0 / beta);\n      classifiers.push_back(best.get_classifier(alpha));\n      ++ipass;\n    }\n\n    free(valids);\n    free(weights);\n    free(indexResult);\n    free(goodResult);\n    free(errorResult);\n    auto global_end = std::chrono::steady_clock::now();\n    diff = global_end - global_start;\n    std::cout << \"Training finished in \" << diff.count()\n    << \" secs.\" << std::endl;\n    return StrongClassifier(classifiers);\n  }\n\n  std::pair<std::vector<TestImage>,\n          std::vector<FeatureValues> > StrongClassifier::load_tests_set(std::string tests_dir)\n  {\n    std::string gooddir = tests_dir + \"/good\";\n    std::string baddir = tests_dir + \"/bad\";\n    auto good = load_images(gooddir);\n    auto bad = load_images(baddir);\n\n    double goodweight = 1.0 / (2 * good.size());\n    double badweight = 1.0 / (2 * bad.size());\n\n    std::cout << \"Image size is \" <<  good[0]->width << \" * \" << good[0]->height << std::endl;\n\n    std::cout << \" Computing IntegralImage\\n\";\n    auto startI = std::chrono::steady_clock::now();\n\n    std::vector<TestImage> tests;\n    for (size_t i = 0; i < good.size(); ++i)\n      tests.push_back(TestImage(*good[i], goodweight, true));\n\n    for (auto i = good.size(); i < good.size() + bad.size(); ++i)\n      tests.push_back(TestImage(*bad[i - good.size()], badweight, false));\n\n    std::cout << \" completed IntegralImage\\n\";\n    auto endI = std::chrono::steady_clock::now();\n    std::chrono::duration<double> diffI = endI - startI;\n    std::cout << \"Computing IntegralImage in \" << diffI.count() << \" seconds.\"<< std::endl;\n\n    std::cout << \" Computing feature Values\\n\";\n    auto start = std::chrono::steady_clock::now();\n\n    auto features_values = compute_features_values(tests);\n    std::cout << \" completed feature Values\\n\";\n    auto end = std::chrono::steady_clock::now();\n    std::chrono::duration<double> diff = end - start;\n    std::cout << \"Computing Featrues in \" << diff.count() << \" seconds.\"<< std::endl;\n\n    return std::pair<std::vector<TestImage>, std::vector<FeatureValues>>(tests, features_values);\n  }\n\n  std::vector<FeatureValues> StrongClassifier::compute_features_values(std::vector<TestImage> tests)\n  {\n    std::vector<std::shared_ptr<Feature> > features = Window::list_features();\n    std::vector<FeatureValues> features_values;\n    std::cout << \"We have \"<<features.size() << \" featrues to compute\\n\";\n    for (size_t i = 0; i < features.size(); ++i)\n    {\n      if(i%100==0)\n        std::cout << \"Computing \"<< i<< \"th feature Values\\n\";\n      auto values = FeatureValue::compute_all_values_sorted(tests, *features[i]);\n      features_values.push_back(FeatureValues(features[i], values));\n    }\n    return features_values;\n  }\n\n  std::shared_ptr<GreyImage> StrongClassifier::load_image(std::string imagepath)\n  {\n    sf::Image sfimage;\n    sfimage.loadFromFile(imagepath);\n    if (sfimage.getSize().x != Config::window_width || sfimage.getSize().y != Config::window_height)\n    {\n      std::cerr << \"Invalid image size (must be \"\n      << Config::window_width << \"*\"\n      << Config::window_height << \"): \"\n      << imagepath << std::endl;\n      exit(1);\n    }\n    return std::make_shared<GreyImage>(GreyImage(sfimage));\n  }\n\n  std::vector <std::shared_ptr<GreyImage>> StrongClassifier::load_images(std::string dir)\n  {\n    namespace fs = boost::filesystem;\n    fs::path path(dir);\n    fs::directory_iterator end_itr;\n    std::vector<std::shared_ptr<GreyImage>> images;\n\n    size_t number_loaded = 0;\n    /*\n    if (Config::parallelized)\n    {\n      std::vector<std::string> strings;\n      for (fs::directory_iterator iter(path);\n           iter != end_itr && (number_loaded < Config::number_load || !Config::number_load);\n           ++iter, ++number_loaded)\n        if (fs::is_regular_file(iter->status()))\n          strings.push_back(iter->path().string());\n\n      tbb::parallel_for_each(strings.begin(), strings.end(),\n                             [&](std::string string) {\n                               images.push_back(load_image(string));\n                             });\n    }\n    else \n    */\n    if (fs::exists(path) && fs::is_directory(path))\n      for (fs::directory_iterator iter(path);\n           iter != end_itr && (number_loaded < Config::number_load || !Config::number_load);\n           ++iter, ++number_loaded)\n        if (fs::is_regular_file(iter->status()))\n          images.push_back(load_image(iter->path().string()));\n\n    std::cout << \"Loaded \" << images.size() << \" in \" << dir << std::endl;\n    if (!images.size())\n    {\n      std::cerr << \"Error: no images has been loaded from: \" << dir << std::endl;\n      exit(0);\n    }\n\n    return images;\n  }\n}", "meta": {"hexsha": "c4ed62305d8cb2337004540f4a215f94d9e77831", "size": 15896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trainer/strong-classifier.cpp", "max_stars_repo_name": "ice-tea/FaceDetection", "max_stars_repo_head_hexsha": "ba416d6d387cff11a7bf24a8b543da5e00057084", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/trainer/strong-classifier.cpp", "max_issues_repo_name": "ice-tea/FaceDetection", "max_issues_repo_head_hexsha": "ba416d6d387cff11a7bf24a8b543da5e00057084", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/trainer/strong-classifier.cpp", "max_forks_repo_name": "ice-tea/FaceDetection", "max_forks_repo_head_hexsha": "ba416d6d387cff11a7bf24a8b543da5e00057084", "max_forks_repo_licenses": ["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.6408977556, "max_line_length": 129, "alphanum_fraction": 0.5966909914, "num_tokens": 3776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.011508149212625801, "lm_q1q2_score": 0.004053190660759825}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// This file is a part of the PadallelFDTD Finite-Difference Time-Domain\n// simulation library. It is released under the MIT License. You should have\n// received a copy of the MIT License along with ParallelFDTD.  If not, see\n// http://www.opensource.org/licenses/mit-license.php\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// For details, see the LICENSE file\n//\n// (C) 2013-2014 Jukka Saarelma\n// Aalto University School of Science\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <algorithm>\n#include <Python.h>\n#include <boost/cstdint.hpp>\n#include <boost/python.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/numpy.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include <numpy/arrayobject.h>\n#include \"App.h\"\n#include \"kernels/visualizationUtils.h\"\n#include \"kernels/voxelizationUtils.h\"\n\nnamespace GLOBAL {\n  static FDTD::App* currentApp;\n  static volatile bool interrupt = false;\n}\n\n\nusing namespace boost::python;\n\nboost::python::object toNumpyArray(unsigned int* data, long int size) {\n      boost::python::numpy::dtype dt = boost::python::numpy::dtype::get_builtin<unsigned int>();\n      boost::python::tuple shape = boost::python::make_tuple(size);\n      boost::python::tuple stride = boost::python::make_tuple(size);\n      boost::python::object owner;\n      boost::python::numpy::ndarray array =\n      boost::python::numpy::from_data(data, dt, shape, stride, owner);\n\n    /* The problem of returning arr is twofold: firstly the user can modify\n      the data which will betray the const-correctness\n      Secondly the lifetime of the data is managed by the C++ API and not the\n      lifetime of the numpy array whatsoever. But we have a simple solution..\n     */\n\n       return array.copy(); // copy the object. numpy owns the copy now.\n}\n\nboost::python::object toNumpyArray(float* data, long int size) {\n      boost::python::numpy::dtype dt = boost::python::numpy::dtype::get_builtin<float>();\n      boost::python::tuple shape = boost::python::make_tuple(size);\n      boost::python::tuple stride = boost::python::make_tuple(size);\n      boost::python::object owner;\n      boost::python::numpy::ndarray array =\n      boost::python::numpy::from_data(data, dt, shape, stride, owner);\n\n      return array.copy(); // copy the object. numpy owns the copy now.\n}\n\nboost::python::object toNumpyArray(double* data, long int size) {\n      boost::python::numpy::dtype dt = boost::python::numpy::dtype::get_builtin<double>();\n      boost::python::tuple shape = boost::python::make_tuple(size);\n      boost::python::tuple stride = boost::python::make_tuple(size);\n      boost::python::object owner;\n      boost::python::numpy::ndarray array =\n      boost::python::numpy::from_data(data, dt, shape, stride, owner);\n\n    // create a PyObject * from pointer and data\n      return array.copy(); // copy the object. numpy owns the copy now.\n}\n\nboost::python::object toNumpyArray(unsigned char* data, long int size) {\n    boost::python::numpy::dtype dt = boost::python::numpy::dtype::get_builtin<char>();\n    boost::python::tuple shape = boost::python::make_tuple(size);\n    boost::python::tuple stride = boost::python::make_tuple(size);\n    boost::python::object owner;\n    boost::python::numpy::ndarray array =\n    boost::python::numpy::from_data(data, dt, shape, stride, owner);\n\n      return array.copy(); // copy the object. numpy owns the copy now.\n}\n\nvoid FDTD::App::initializeGeometryPy(boost::python::list indices,\n                                     boost::python::list vertices) {\n  int v_len = (int)boost::python::len(vertices);\n  int i_len = (int)boost::python::len(indices);\n  std::vector<float> std_vertices(v_len, 0.f);\n  std::vector<unsigned int> std_indices(i_len, 0);\n\n  for(int i = 0; i < v_len; i++)\n    std_vertices.at(i) = boost::python::extract<float>(vertices[i]);\n\n  for(int i = 0; i < i_len; i++)\n    std_indices.at(i) = boost::python::extract<unsigned int>(indices[i]);\n\n  this->m_geometry.initialize(std_indices, std_vertices);\n  this->has_geometry_ = true;\n}\n\nboost::python::object FDTD::App::getVoxelization(boost::python::list indices,\n                                                 boost::python::list vertices,\n                                                 boost::python::list material_coefficients,\n                                                 int voxelization_type,\n                                                 float dx) {\n  unsigned char* d_position_idx = (unsigned char*)NULL;\n  unsigned char* d_material_idx = (unsigned char*)NULL;\n  uint3 voxelization_dim = make_uint3(0,0,0);\n\n  this->initializeGeometryPy(indices, vertices);\n\n  unsigned int number_of_triangles = this->m_geometry.getNumberOfTriangles();\n\n  this->addSurfaceMaterials(material_coefficients,\n                            number_of_triangles,\n                            20);\n\n  if(voxelization_type == 0)\n    voxelizeGeometry_solid(m_geometry.getVerticePtr(),\n                           m_geometry.getIndexPtr(),\n                           m_materials.getMaterialIdxPtr(),\n                           m_geometry.getNumberOfTriangles(),\n                           m_geometry.getNumberOfVertices(),\n                           m_materials.getNumberOfUniqueMaterials(),\n                           (double)dx,\n                           &d_position_idx,\n                           &d_material_idx,\n                           &voxelization_dim);\n\n\n  if(voxelization_type == 1) {\n    voxelizeGeometry_surface_6_separating(m_geometry.getVerticePtr(),\n                                         m_geometry.getIndexPtr(),\n                                         m_materials.getMaterialIdxPtr(),\n                                         m_geometry.getNumberOfTriangles(),\n                                         m_geometry.getNumberOfVertices(),\n                                         m_materials.getNumberOfUniqueMaterials(),\n                                         (double) m_parameters.getDx(),\n                                         &d_position_idx,\n                                         &d_material_idx,\n                                         &voxelization_dim,\n                                         0,voxelization_dim.z);\n  }\n\n  unsigned int num_elems = voxelization_dim.x*voxelization_dim.y*voxelization_dim.z;\n  unsigned char* h_position_idx;\n  unsigned char* h_material_idx;\n  boost::python::list result;\n  h_position_idx = fromDevice<unsigned char>(num_elems, d_position_idx, 0);\n  h_material_idx = fromDevice<unsigned char>(num_elems, d_material_idx, 0);\n  result.append(toNumpyArray(h_position_idx, num_elems));\n  result.append(toNumpyArray(h_material_idx, num_elems));\n  result.append(toNumpyArray((unsigned int*)&voxelization_dim, 3));\n  free(h_position_idx);\n  free(h_material_idx);\n  destroyMem(d_position_idx);\n  destroyMem(d_material_idx);\n  return result;\n}\n\nvoid FDTD::App::initializeDomainPy(boost::python::numpy::ndarray position_idx,\n                                   boost::python::numpy::ndarray material_idx,\n                                   unsigned int dim_x,\n                                   unsigned int dim_y,\n                                   unsigned int dim_z) {\n  log_msg<LOG_INFO>(L\"App::initializeDomainPy - begin\");\n  mesh_size_t p_len = (mesh_size_t)boost::python::len(position_idx);\n  mesh_size_t m_len = (mesh_size_t)boost::python::len(material_idx);\n\n\n  if(p_len != dim_x*dim_y*dim_z || m_len !=dim_x*dim_y*dim_z) {\n    log_msg<LOG_WARNING>(L\"App::initializeGeometryPy, dimensions do not match\"\n                         L\"with the size of the domain, x: %u y:%u z:%u, \"\n                         L\"num pos: %u num mat: %u\")\n                         % dim_x % dim_y % dim_z % p_len % m_len;\n   }\n  clock_t start_t;\n  clock_t end_t;\n  start_t = clock();\n  std::vector<unsigned char> std_pos(p_len, 0);\n  unsigned char* ps = (unsigned char*)PyArray_GETPTR1(((PyArrayObject*)position_idx.ptr()), 0);\n\n  for(mesh_size_t i = 0; i < p_len; i++)\n    std_pos.at(i) = ps[i];\n\n  end_t = clock()-start_t;\n  log_msg<LOG_INFO>(L\"App::initializeDomainPy - time copy pos: %f seconds\")\n          % ((float)end_t/CLOCKS_PER_SEC);\n\n  start_t = clock();\n  std::vector<unsigned char> std_mat(m_len, 0);\n  unsigned char* ms = (unsigned char*)PyArray_GETPTR1(((PyArrayObject*)material_idx.ptr()), 0);\n\n  for(mesh_size_t i = 0; i < m_len; i++)\n    std_mat.at(i) = ms[i];\n\n  end_t = clock()-start_t;\n  log_msg<LOG_INFO>(L\"App::initializeDomainPy - time copy mat: %f seconds\")\n            % ((float)end_t/CLOCKS_PER_SEC);\n\n  this->initializeDomain(&std_pos[0], &std_mat[0], dim_x, dim_y, dim_z);\n}\n\nvoid FDTD::App::setSliceXY(boost::python::numpy::ndarray slice,\n                           unsigned int dim_x, unsigned int dim_y,\n                           int slice_idx) {\n  int s_len = (int)boost::python::len(slice);\n  if(s_len != dim_x*dim_y) {\n    std::cout<<\"FDTD::App::setSliceXY: slice size does not match \"\n               \"the given dimensions\"<<std::endl;\n    return;\n  }\n\n  if(this->m_mesh.isDouble()) {\n    int dev_i = 0;\n    mesh_size_t element = 0;\n    this->m_mesh.getElementIdxAndDevice(0,0,slice_idx, &dev_i, &element);\n    double* d_dest = this->m_mesh.getPressureDoublePtrAt(dev_i)+element;\n    //double* h_src = (double*)slice.ptr()->data;\n    double* h_src = (double*)PyArray_DATA((PyArrayObject*)slice.ptr());\n    copyHostToDevice<double>(s_len, d_dest, h_src, dev_i);\n  }\n  else {\n    int dev_i = 0;\n    mesh_size_t element = 0;\n    this->m_mesh.getElementIdxAndDevice(0,0,slice_idx, &dev_i, &element);\n    //float* h_src = (float*)((PyArrayObject*)slice.ptr())->data;\n    float* h_src = (float*)PyArray_DATA((PyArrayObject*)slice.ptr());\n    float* d_dest = this->m_mesh.getPressurePtrAt(dev_i)+element;\n    copyHostToDevice<float>(s_len, d_dest, h_src, dev_i);\n  }\n}\n\nvoid FDTD::App::initializeSimulationPy() {\n  GLOBAL::currentApp = this;\n\n  if(this->has_geometry_)\n    this->initializeMesh(2);\n\n  unsigned int step = this->m_parameters.getNumSteps();\n  this->responses_.assign(m_parameters.getNumSteps()*m_parameters.getNumReceivers(), 0.f);\n}\n\nvoid FDTD::App::setLayerIndicesPy(boost::python::list indices,\n                                  std::string name) {\n  int i_len = (int)boost::python::len(indices);\n  std::vector<int> std_indices(i_len, 0.f);\n  for(int i = 0; i < i_len; i++)\n    std_indices.at(i) = boost::python::extract<int>(indices[i]);\n\n  this->m_geometry.setLayerIndices(std_indices, name);\n}\n\nvoid FDTD::App::addSurfaceMaterials(boost::python::list material_coefficients,\n                                    unsigned int number_of_surfaces,\n                                    unsigned int number_of_coefficients) {\n  int m_len = (int)boost::python::len(material_coefficients);\n  std::vector<float> std_mat(m_len, 0.f);\n  for(int i = 0; i < m_len; i++) {\n    std_mat.at(i) = boost::python::extract<float>(material_coefficients[i]);\n  }\n  this->m_materials.addMaterials(&std_mat[0],\n                                 number_of_surfaces,\n                                 number_of_coefficients);\n}\n\nvoid FDTD::App::addSourceDataFloat(boost::python::list src_data,\n                                   int num_steps,\n                                   int num_sources) {\n  std::vector<float> std_src_data(num_steps*num_sources, 0.0);\n  for(int j = 0; j < num_sources; j++) {\n    for(int i = 0; i < num_steps; i++) {\n      int idx =j*num_steps+i;\n      std_src_data.at(idx) = boost::python::extract<float>(src_data[idx]);\n    }\n  }\n  this->m_parameters.addInputData(std_src_data);\n}\n\nvoid FDTD::App::addSourceDataDouble(boost::python::list src_data,\n                              int num_steps,\n                              int num_sources) {\n  std::vector<double> std_src_data(num_steps*num_sources, 0.0);\n  for(int j = 0; j < num_sources; j++) {\n    for(int i = 0; i < num_steps; i++) {\n      int idx =j*num_steps+i;\n      std_src_data.at(idx) = boost::python::extract<double>(src_data[idx]);\n    }\n  }\n  this->m_parameters.addInputDataDouble(std_src_data);\n}\n\nboost::python::object FDTD::App::getSlice(int orientation,\n                                          int slice_idx) {\n  float* pressure_data = NULL;\n  unsigned char* position_data = NULL;\n  unsigned int d_x = 0;\n  unsigned int d_y = 0;\n  if(orientation == 0) {d_x = this->m_mesh.getDimX(); d_y = this->m_mesh.getDimY();};\n  if(orientation == 1) {d_x = this->m_mesh.getDimX(); d_y = this->m_mesh.getDimZ();};\n  if(orientation == 2) {d_x = this->m_mesh.getDimY(); d_y = this->m_mesh.getDimZ();};\n\n  captureCurrentSlice(&this->m_mesh, &pressure_data, &position_data,\n                      slice_idx, orientation);\n\n  boost::python::object ret = toNumpyArray(pressure_data, d_x*d_y);\n  free(pressure_data);\n  free(position_data);\n  return ret;\n}\n\nboost::python::list FDTD::App::getMeshDimensionsPy() {\n  boost::python::list result;\n  mesh_size_t dim_x = this->m_mesh.getDimX();\n  mesh_size_t dim_y = this->m_mesh.getDimY();\n  mesh_size_t dim_z = this->m_mesh.getDimZ();\n  result.append(dim_x);\n  result.append(dim_y);\n  result.append(dim_z);\n  return result;\n}\n\n/// Following convertion code taken from:\n/// http://stackoverflow.com/questions/26595350/extracting-unsigned-char-from-array-of-numpy-uint8\n/// @brief Converter type that enables automatic conversions between NumPy\n///        scalars and C++ types.\ntemplate <typename T, NPY_TYPES NumPyScalarType>\nstruct enable_numpy_scalar_converter\n{\n  enable_numpy_scalar_converter() {\n    // Required NumPy call in order to use the NumPy C API within another\n    // extension module.\n    _import_array();\n\n    boost::python::converter::registry::push_back(\n      &convertible,\n      &construct,\n      boost::python::type_id<T>());\n  }\n\n  static void* convertible(PyObject* object) {\n    // The object is convertible if all of the following are true:\n    // - is a valid object.\n    // - is a numpy array scalar.\n    // - its descriptor type matches the type for this converter.\n    return (\n      object &&                                                    // Valid\n      PyArray_CheckScalar(object) &&                               // Scalar\n      PyArray_DescrFromScalar(object)->type_num == NumPyScalarType // Match\n    )\n      ? object // The Python object can be converted.\n      : NULL;\n  }\n\n  static void construct(\n    PyObject* object,\n    boost::python::converter::rvalue_from_python_stage1_data* data) {\n    // Obtain a handle to the memory block that the converter has allocated\n    // for the C++ type.\n    namespace python = boost::python;\n    typedef python::converter::rvalue_from_python_storage<T> storage_type;\n    void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;\n\n    // Extract the array scalar type directly into the storage.\n    PyArray_ScalarAsCtype(object, storage);\n\n    // Set convertible to indicate success.\n    data->convertible = storage;\n  }\n};\n\nBOOST_PYTHON_MODULE(liblibPyFDTD) {\n  //boost::python::numpy::set_module_and_type(\"numpy\", \"ndarray\");\n\n  enable_numpy_scalar_converter<boost::uint8_t, NPY_UBYTE>();\n\n  class_< std::vector<float> >(\"std_vec_float\")\n    .def(vector_indexing_suite< std::vector<float> >() )\n    ;\n\n  class_< std::vector<double> >(\"std_vec_double\")\n    .def(vector_indexing_suite< std::vector<double> >() )\n    ;\n\n  class_<FDTD::App>(\"App\")\n    .def(\"initializeDevices\", &FDTD::App::initializeDevices)\n    .def(\"initializeGeometryFromFile\", &FDTD::App::initializeGeometryFromFile)\n    .def(\"initializeGeometryPy\", &FDTD::App::initializeGeometryPy)\n    .def(\"initializeSimulationPy\", &FDTD::App::initializeSimulationPy)\n    .def(\"initializeDomainPy\", &FDTD::App::initializeDomainPy)\n    .def(\"setLayerIndices\", &FDTD::App::setLayerIndicesPy)\n    .def(\"setVoxelizationType\", &FDTD::App::setVoxelizationType)\n    .def(\"setDouble\", &FDTD::App::setDouble)\n    .def(\"setCapturedB\", &FDTD::App::setCapturedB)\n    .def(\"setCaptureId\", &FDTD::App::setCaptureId)\n    .def(\"setSpatialFs\", &FDTD::App::setSpatialFs)\n    .def(\"setNumSteps\", &FDTD::App::setNumSteps )\n    .def(\"setUpdateType\", &FDTD::App::setUpdateType)\n    .def(\"setUniformMaterial\", &FDTD::App::setUniformMaterial)\n    .def(\"setSliceXY\", &FDTD::App::setSliceXY)\n    .def(\"addSource\", &FDTD::App::addSource)\n    .def(\"addSourceDataFloat\", &FDTD::App::addSourceDataFloat)\n    .def(\"addSourceDataDouble\", &FDTD::App::addSourceDataDouble)\n    .def(\"addReceiver\", &FDTD::App::addReceiver)\n    .def(\"addSurfaceMaterials\", &FDTD::App::addSurfaceMaterials)\n    .def(\"addSliceToCapture\", &FDTD::App::addSliceToCapture)\n    .def(\"getSlice\", &FDTD::App::getSlice)\n    .def(\"getResponse\", &FDTD::App::getResponse)\n    .def(\"getResponseDouble\", &FDTD::App::getResponseDouble)\n    .def(\"getMvox\", &FDTD::App::getMvoxPerSec)\n    .def(\"getNumElems\", &FDTD::App::getNumElements)\n    .def(\"getMeshDimensions\", &FDTD::App::getMeshDimensionsPy)\n    .def(\"getEyring\", &FDTD::App::getEyring)\n    .def(\"getSabine\", &FDTD::App::getSabine)\n    .def(\"getVolume\", &FDTD::App::getVolume)\n    .def(\"getVoxelization\", &FDTD::App::getVoxelization)\n    .def(\"forcePartitionTo\", &FDTD::App::setForcePartitionTo)\n    .def(\"runSimulation\", &FDTD::App::runSimulation)\n    .def(\"runCapture\", &FDTD::App::runCapture)\n    .def(\"executeStep\", &FDTD::App::executeStep)\n    .def(\"close\", &FDTD::App::close)\n    #ifdef COMPILE_VISUALIZATION\n    .def(\"runVisualization\", &FDTD::App::runVisualization)\n    #endif\n    ;\n}\n", "meta": {"hexsha": "bf9b5b98ab74c25b8e836aa6994fd3724f23be8b", "size": 17997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AppPy.cpp", "max_stars_repo_name": "bijulette/ParallelFDTD", "max_stars_repo_head_hexsha": "8e1fde06998d5468a657b3bd5652cf118ee50ba7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T14:11:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T14:11:16.000Z", "max_issues_repo_path": "src/AppPy.cpp", "max_issues_repo_name": "bijulette/ParallelFDTD", "max_issues_repo_head_hexsha": "8e1fde06998d5468a657b3bd5652cf118ee50ba7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AppPy.cpp", "max_forks_repo_name": "bijulette/ParallelFDTD", "max_forks_repo_head_hexsha": "8e1fde06998d5468a657b3bd5652cf118ee50ba7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T07:21:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T22:08:37.000Z", "avg_line_length": 40.9954441913, "max_line_length": 98, "alphanum_fraction": 0.635717064, "num_tokens": 4477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1602660243061182, "lm_q2_score": 0.025178843529337067, "lm_q1q2_score": 0.004035313149072681}}
{"text": "//\r\n// $Id$\r\n//\r\n//\r\n// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>\r\n//\r\n// Copyright 2009 Vanderbilt University - Nashville, TN 37232\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n\r\n\r\n#define PWIZ_SOURCE\r\n\r\n\r\n#include \"SpectrumList_Bruker.hpp\"\r\n#include \"pwiz/utility/chemistry/Chemistry.hpp\"\r\n\r\n\r\n#ifdef PWIZ_READER_BRUKER\r\n#include \"pwiz/data/msdata/MSData.hpp\"\r\n#include \"pwiz/utility/misc/automation_vector.h\"\r\n#include \"pwiz/utility/misc/Filesystem.hpp\"\r\n#include \"pwiz/utility/misc/Std.hpp\"\r\n#include \"pwiz/utility/misc/IntegerSet.hpp\"\r\n#include \"pwiz/utility/misc/SHA1Calculator.hpp\"\r\n#include \"pwiz/utility/minimxml/XMLWriter.hpp\"\r\n#include <boost/range/algorithm/find_if.hpp>\r\n#include <boost/spirit/include/karma.hpp>\r\n\r\n\r\nusing namespace pwiz::util;\r\nusing namespace pwiz::minimxml;\r\nusing namespace pwiz::vendor_api::Bruker;\r\n\r\n\r\nnamespace pwiz {\r\nnamespace msdata {\r\nnamespace detail {\r\n\r\nusing namespace Bruker;\r\n\r\n\r\nPWIZ_API_DECL\r\nSpectrumList_Bruker::SpectrumList_Bruker(MSData& msd,\r\n                                         const string& rootpath,\r\n                                         Reader_Bruker_Format format,\r\n                                         CompassDataPtr compassDataPtr,\r\n                                         const Reader::Config& config)\r\n:   msd_(msd), rootpath_(rootpath), format_(format),\r\n    compassDataPtr_(compassDataPtr), config_(config),\r\n    size_(0)\r\n{\r\n    fillSourceList();\r\n    createIndex();\r\n}\r\n\r\n\r\nPWIZ_API_DECL size_t SpectrumList_Bruker::size() const\r\n{\r\n    return size_;\r\n}\r\n\r\n\r\nPWIZ_API_DECL const SpectrumIdentity& SpectrumList_Bruker::spectrumIdentity(size_t index) const\r\n{\r\n    if (index >= size_)\r\n        throw runtime_error((\"[SpectrumList_Bruker::spectrumIdentity()] Bad index: \" \r\n                            + lexical_cast<string>(index)).c_str());\r\n    return index_[index];\r\n}\r\n\r\n\r\nPWIZ_API_DECL size_t SpectrumList_Bruker::find(const string& id) const\r\n{\r\n    boost::container::flat_map<string, size_t>::const_iterator scanItr = idToIndexMap_.find(id);\r\n    if (scanItr == idToIndexMap_.end())\r\n    {\r\n        if (format_ == Reader_Bruker_Format_TDF)\r\n        {\r\n            try\r\n            {\r\n                int frame = msdata::id::valueAs<int>(id, \"frame\");\r\n                int scan = msdata::id::valueAs<int>(id, \"scan\");\r\n                return compassDataPtr_->getSpectrumIndex(frame, scan);\r\n            }\r\n            catch (exception&)\r\n            {\r\n                // fall through and return size_ (id not found)\r\n            }\r\n        }\r\n        \r\n        return checkNativeIdFindResult(size_, id);\r\n    }\r\n    return scanItr->second;\r\n}\r\n\r\n\r\nMSSpectrumPtr SpectrumList_Bruker::getMSSpectrumPtr(size_t scan, vendor_api::Bruker::DetailLevel detailLevel) const\r\n{\r\n    if (format_ == Reader_Bruker_Format_FID)\r\n    {\r\n        compassDataPtr_ = CompassData::create(sourcePaths_[scan].string());\r\n        return compassDataPtr_->getMSSpectrum(1, detailLevel);\r\n    }\r\n\r\n    return compassDataPtr_->getMSSpectrum(scan, detailLevel);\r\n}\r\n\r\n\r\nPWIZ_API_DECL SpectrumPtr SpectrumList_Bruker::spectrum(size_t index, bool getBinaryData) const\r\n{\r\n    return spectrum(index, getBinaryData, MSLevelsNone);\r\n}\r\n\r\nPWIZ_API_DECL SpectrumPtr SpectrumList_Bruker::spectrum(size_t index, DetailLevel detailLevel) const \r\n{\r\n    return spectrum(index, detailLevel, MSLevelsNone);\r\n}\r\n\r\nPWIZ_API_DECL SpectrumPtr SpectrumList_Bruker::spectrum(size_t index, bool getBinaryData, const pwiz::util::IntegerSet& msLevelsToCentroid) const\r\n{\r\n    return spectrum(index, getBinaryData ? DetailLevel_FullData : DetailLevel_FullMetadata, msLevelsToCentroid);\r\n}\r\n\r\nPWIZ_API_DECL SpectrumPtr SpectrumList_Bruker::spectrum(size_t index, DetailLevel detailLevel, const pwiz::util::IntegerSet& msLevelsToCentroid) const \r\n{ \r\n    if (index >= size_)\r\n        throw runtime_error((\"[SpectrumList_Bruker::spectrum()] Bad index: \" \r\n                            + lexical_cast<string>(index)).c_str());\r\n\r\n    // allocate a new Spectrum\r\n    SpectrumPtr result(new Spectrum);\r\n    if (!result.get())\r\n        throw runtime_error(\"[SpectrumList_Bruker::spectrum()] Allocation error.\");\r\n\r\n    vendor_api::Bruker::DetailLevel brukerDetailLevel;\r\n    switch (detailLevel)\r\n    {\r\n        case DetailLevel_InstantMetadata:\r\n        case DetailLevel_FastMetadata:\r\n            brukerDetailLevel = vendor_api::Bruker::DetailLevel_InstantMetadata;\r\n            break;\r\n\r\n        case DetailLevel_FullMetadata:\r\n            brukerDetailLevel = vendor_api::Bruker::DetailLevel_FullMetadata;\r\n            break;\r\n\r\n        default:\r\n        case DetailLevel_FullData:\r\n            brukerDetailLevel = vendor_api::Bruker::DetailLevel_FullData;\r\n            break;\r\n    }\r\n\r\n    const IndexEntry& si = index_[index];\r\n    result->index = si.index;\r\n    result->id = si.id;\r\n\r\n    // the scan element may be empty for MALDI spectra, but it's required for a valid file\r\n    result->scanList.scans.push_back(Scan());\r\n    Scan& scan = result->scanList.scans[0];\r\n    scan.instrumentConfigurationPtr = msd_.run.defaultInstrumentConfigurationPtr;\r\n\r\n    //try\r\n    //{\r\n        // is this spectrum from the LC interface?\r\n        if (si.collection > -1)\r\n        {\r\n            // fill the spectrum from the LC interface\r\n            LCSpectrumSourcePtr source = compassDataPtr_->getLCSource(si.source);\r\n            LCSpectrumPtr spectrum = compassDataPtr_->getLCSpectrum(si.source, si.scan);\r\n\r\n            if (source->getXAxisUnit() == LCUnit_NanoMeter)\r\n                result->set(MS_EMR_spectrum);\r\n            else\r\n                throw runtime_error(\"[SpectrumList_Bruker::spectrum()] unexpected XAxisUnit\");\r\n\r\n            double scanTime = spectrum->getTime();\r\n            if (scanTime > 0)\r\n                scan.set(MS_scan_start_time, scanTime, UO_minute);\r\n\r\n            result->set(MS_profile_spectrum);\r\n\r\n            vector<double> lcX;\r\n            source->getXAxis(lcX);\r\n\r\n            if (detailLevel == DetailLevel_FullData)\r\n            {\r\n                result->setMZIntensityArrays(vector<double>(), vector<double>(), MS_number_of_detector_counts);\r\n                result->defaultArrayLength = lcX.size();\r\n\r\n                BinaryDataArrayPtr mzArray = result->getMZArray();\r\n                vector<CVParam>::iterator itr = boost::range::find_if(mzArray->cvParams, CVParamIs(MS_m_z_array));\r\n                *itr = CVParam(MS_wavelength_array);\r\n\r\n                swap(mzArray->data, lcX);\r\n\r\n                vector<double> lcY;\r\n                spectrum->getData(lcY);\r\n                swap(result->getIntensityArray()->data, lcY);\r\n            }\r\n            else\r\n                result->defaultArrayLength = lcX.size();\r\n\r\n            return result;\r\n        }\r\n\r\n        // get the spectrum from MS interface; for FID formats scan is 0-based, else it's 1-based\r\n        MSSpectrumPtr spectrum = getMSSpectrumPtr(si.scan, brukerDetailLevel);\r\n\r\n        result->cvParams.reserve(8); // Anticipate about this many CVParams\r\n\r\n        int msLevel = spectrum->getMSMSStage();\r\n        result->set(MS_ms_level, msLevel);\r\n\r\n        if (msLevel == 1)\r\n            result->set(MS_MS1_spectrum);\r\n        else\r\n            result->set(MS_MSn_spectrum);\r\n\r\n        double scanTime = spectrum->getRetentionTime();\r\n        if (scanTime > 0)\r\n            scan.set(MS_scan_start_time, scanTime, UO_second);\r\n\r\n        pair<double, double> scanRange = spectrum->getScanRange();\r\n        if (scanRange.first > 0 && scanRange.second > 0)\r\n            scan.scanWindows.push_back(ScanWindow(scanRange.first, scanRange.second, MS_m_z));\r\n\r\n        IonPolarity polarity = spectrum->getPolarity();\r\n        switch (polarity)\r\n        {\r\n            case IonPolarity_Negative:\r\n                result->set(MS_negative_scan);\r\n                break;\r\n            case IonPolarity_Positive:\r\n                result->set(MS_positive_scan);\r\n                break;\r\n            default:\r\n                break;\r\n        }\r\n\r\n        //sd.set(MS_base_peak_m_z, pScanStats_->BPM);\r\n        if (spectrum->getTIC() > 0)\r\n        {\r\n            result->set(MS_base_peak_intensity, spectrum->getBPI());\r\n            result->set(MS_total_ion_current, spectrum->getTIC());\r\n        }\r\n\r\n        double oneOverK0 = spectrum->oneOverK0();\r\n        if (oneOverK0 > 0)\r\n        {\r\n            scan.set(MS_inverse_reduced_ion_mobility, oneOverK0, MS_Vs_cm_2);\r\n            int windowGroup = spectrum->getWindowGroup();\r\n            if (windowGroup > 0)\r\n                scan.userParams.push_back(UserParam(\"windowGroup\", lexical_cast<string>(windowGroup))); // diaPASEF data\r\n        }\r\n\r\n        if (detailLevel == DetailLevel_InstantMetadata)\r\n            return result;\r\n\r\n        if (msLevel > 1)\r\n        {\r\n            Precursor precursor;\r\n\r\n            vector<double> fragMZs, isolMZs;\r\n            vector<FragmentationMode> fragModes;\r\n            vector<IsolationMode> isolModes;\r\n\r\n            spectrum->getFragmentationData(fragMZs, fragModes);\r\n\r\n            if (!fragMZs.empty())\r\n            {\r\n                spectrum->getIsolationData(isolMZs, isolModes);\r\n\r\n                for (size_t i = 0; i < fragMZs.size(); ++i)\r\n                {\r\n                    if (fragMZs[i] > 0)\r\n                    {\r\n                        SelectedIon selectedIon(fragMZs[i]);\r\n\r\n                        int charge = spectrum->getChargeState();\r\n                        if (charge > 0)\r\n                            selectedIon.set(MS_charge_state, charge);\r\n\r\n                        switch (fragModes[i])\r\n                        {\r\n                            case FragmentationMode_CID:\r\n                                precursor.activation.set(MS_CID);\r\n                                break;\r\n                            case FragmentationMode_ETD:\r\n                                precursor.activation.set(MS_ETD);\r\n                                break;\r\n                            case FragmentationMode_CIDETD_CID:\r\n                                precursor.activation.set(MS_CID);\r\n                                precursor.activation.set(MS_ETD);\r\n                                break;\r\n                            case FragmentationMode_CIDETD_ETD:\r\n                                precursor.activation.set(MS_CID);\r\n                                precursor.activation.set(MS_ETD);\r\n                                break;\r\n                            case FragmentationMode_ISCID:\r\n                                precursor.activation.set(MS_in_source_collision_induced_dissociation);\r\n                                break;\r\n                            case FragmentationMode_ECD:\r\n                                precursor.activation.set(MS_ECD);\r\n                                break;\r\n                            case FragmentationMode_IRMPD:\r\n                                precursor.activation.set(MS_IRMPD);\r\n                                break;\r\n                            case FragmentationMode_PTR:\r\n                                break;\r\n                        }\r\n                        //precursor.activation.set(MS_collision_energy, pExScanStats_->CollisionEnergy);\r\n\r\n                        precursor.selectedIons.push_back(selectedIon);\r\n                    }\r\n\r\n                    if (isolMZs[i] > 0)\r\n                    {\r\n                        precursor.isolationWindow.set(MS_isolation_window_target_m_z, isolMZs[i], MS_m_z);\r\n\r\n                        double isolationWidth = spectrum->getIsolationWidth();\r\n                        if (isolationWidth > 0)\r\n                        {\r\n                            precursor.isolationWindow.set(MS_isolation_window_lower_offset, isolationWidth / 2, MS_m_z);\r\n                            precursor.isolationWindow.set(MS_isolation_window_upper_offset, isolationWidth / 2, MS_m_z);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (precursor.selectedIons.size() > 0 || !precursor.isolationWindow.empty())\r\n                result->precursors.push_back(precursor);\r\n        }\r\n\r\n        if (detailLevel == DetailLevel_FastMetadata)\r\n            return result;\r\n\r\n        // Enumerating merged scan numbers is not instant.\r\n        IntegerSet scanNumbers = spectrum->getMergedScanNumbers();\r\n        if (config_.combineIonMobilitySpectra)\r\n        {\r\n            result->scanList.set(MS_sum_of_spectra);\r\n            if (scanNumbers.size() < 100)\r\n            {\r\n                using namespace boost::spirit::karma;\r\n                auto frameScanPair = compassDataPtr_->getFrameScanPair(si.scan);\r\n                generate(std::back_insert_iterator<std::string>(scan.spectrumID),\r\n                         \"frame=\" << int_ << \" scan=\" << int_,\r\n                         frameScanPair.frame, *scanNumbers.begin());\r\n\r\n                vector<Scan>& scans = result->scanList.scans;\r\n                scans.reserve(scanNumbers.size());\r\n                for (auto itr = ++scanNumbers.begin(); itr != scanNumbers.end(); ++itr)\r\n                {\r\n                    scans.push_back(Scan());\r\n                    scans.back().instrumentConfigurationPtr = msd_.run.defaultInstrumentConfigurationPtr;\r\n                    generate(std::back_insert_iterator<std::string>(scans.back().spectrumID),\r\n                             \"frame=\" << int_ << \" scan=\" << int_,\r\n                             frameScanPair.frame, *itr);\r\n\r\n                    // CONSIDER: do we need this? all scan times will be the same and it's rather verbose\r\n                    //if (scanTime > 0)\r\n                    //    scans.back().set(MS_scan_start_time, scanTime, UO_second);\r\n\r\n                    // CONSIDER: do we need this? all scan ranges will be the same and it's very verbose!\r\n                    //if (scanRange.first > 0 && scanRange.second > 0)\r\n                    //    scans.back().scanWindows.push_back(ScanWindow(scanRange.first, scanRange.second, MS_m_z));\r\n                }\r\n            }\r\n        }\r\n        else\r\n            result->scanList.set(MS_no_combination);\r\n\r\n        //sd.set(MS_lowest_observed_m_z, minObservedMz);\r\n        //sd.set(MS_highest_observed_m_z, maxObservedMz);\r\n\r\n        if (detailLevel == DetailLevel_FullData)\r\n        {\r\n            bool getLineData = msLevelsToCentroid.contains(msLevel);\r\n\r\n            result->setMZIntensityArrays(vector<double>(), vector<double>(), MS_number_of_detector_counts);\r\n\r\n            if (config_.combineIonMobilitySpectra)\r\n            {\r\n                auto& mz = result->getMZArray()->data;\r\n                auto& intensity = result->getIntensityArray()->data;\r\n\r\n                result->set(MS_centroid_spectrum); // TIMS is always centroided\r\n\r\n                BinaryDataArrayPtr mobility(new BinaryDataArray);\r\n                result->binaryDataArrayPtrs.push_back(mobility);\r\n                CVParam arrayType(MS_mean_inverse_reduced_ion_mobility_array);\r\n                arrayType.units = MS_Vs_cm_2;\r\n                mobility->cvParams.emplace_back(arrayType);\r\n\r\n                spectrum->getCombinedSpectrumData(mz, intensity, mobility->data, config_.sortAndJitter);\r\n                result->defaultArrayLength = mz.size();\r\n            }\r\n            else\r\n            {\r\n                automation_vector<double> mzArray, intensityArray;\r\n                if (!getLineData)\r\n                {\r\n                    spectrum->getProfileData(mzArray, intensityArray);\r\n                    if (mzArray.size() == 0)\r\n                        getLineData = true;  // We preferred profile, but there isn't any - try centroided\r\n                    else\r\n                        result->set(MS_profile_spectrum);\r\n                }\r\n\r\n                if (getLineData)\r\n                {\r\n                    result->set(MS_centroid_spectrum); // Declare this as centroided data even if scan is empty\r\n                    spectrum->getLineData(mzArray, intensityArray);\r\n                    if (mzArray.size() > 0 && msLevelsToCentroid.contains(msLevel))\r\n                    {\r\n                        result->set(MS_profile_spectrum); // let SpectrumList_PeakPicker know this was probably also a profile spectrum, but doesn't need conversion (actually checking for profile data is crazy slow)\r\n                    }\r\n                }\r\n                result->getMZArray()->data.assign(mzArray.begin(), mzArray.end());\r\n                result->getIntensityArray()->data.assign(intensityArray.begin(), intensityArray.end());\r\n                result->defaultArrayLength = mzArray.size();\r\n            }\r\n        }\r\n        else if (detailLevel == DetailLevel_FullMetadata)\r\n        {\r\n            if (config_.combineIonMobilitySpectra)\r\n            {\r\n                result->defaultArrayLength = spectrum->getCombinedSpectrumDataSize();\r\n                result->set(MS_centroid_spectrum); // TIMS is always centroided\r\n            }\r\n            else\r\n            {\r\n                // N.B.: just getting the data size from the Bruker API is quite expensive.\r\n                if (msLevelsToCentroid.contains(msLevel) || ((result->defaultArrayLength = spectrum->getProfileDataSize())==0))\r\n                {\r\n                    result->defaultArrayLength = spectrum->getLineDataSize();\r\n                    result->set(MS_centroid_spectrum);\r\n                }\r\n                else\r\n                {\r\n                    result->set(MS_profile_spectrum);\r\n                }\r\n            }\r\n        }\r\n    /*}\r\n    catch (_com_error& e) // not caught by either std::exception or '...'\r\n    {\r\n        throw runtime_error(string(\"[SpectrumList_Bruker::spectrum()] COM error: \") +\r\n                            (const char*)e.Description());\r\n    }*/\r\n\r\n    return result;\r\n}\r\n\r\n    \r\nnamespace {\r\n\r\nvoid recursivelyEnumerateFIDs(vector<bfs::path>& fidPaths, const bfs::path& rootpath)\r\n{\r\n    const static bfs::directory_iterator endItr = bfs::directory_iterator();\r\n\r\n    if (rootpath.leaf() == \"fid\")\r\n        fidPaths.push_back(rootpath.branch_path());\r\n    else if (bfs::is_directory(rootpath))\r\n    {\r\n        for (bfs::directory_iterator itr(rootpath); itr != endItr; ++itr)\r\n            recursivelyEnumerateFIDs(fidPaths, itr->path());\r\n    }\r\n}\r\n\r\nvoid addSource(MSData& msd, const bfs::path& sourcePath, const bfs::path& rootPath)\r\n{\r\n    SourceFilePtr sourceFile(new SourceFile);\r\n    sourceFile->id = sourcePath.string();\r\n    sourceFile->name = BFS_STRING(sourcePath.leaf());\r\n\r\n    // sourcePath: <source>\\Analysis.yep|<source>\\Analysis.baf|<source>\\fid\r\n    // rootPath: c:\\path\\to\\<source>[\\Analysis.yep|Analysis.baf|fid]\r\n    bfs::path location = rootPath.has_branch_path() ?\r\n                         BFS_COMPLETE(rootPath.branch_path() / sourcePath) :\r\n                         BFS_COMPLETE(sourcePath); // uses initial path\r\n    sourceFile->location = \"file://\" + location.branch_path().string();\r\n\r\n    msd.fileDescription.sourceFilePtrs.push_back(sourceFile);\r\n}\r\n\r\n} // namespace\r\n\r\n\r\n#if BOOST_FILESYSTEM_VERSION == 2\r\n# define NATIVE_PATH_SLASH \"/\"\r\n#else\r\n# define NATIVE_PATH_SLASH \"\\\\\"\r\n#endif\r\n\r\n\r\nPWIZ_API_DECL void SpectrumList_Bruker::fillSourceList()\r\n{\r\n    switch (format_)\r\n    {\r\n        case Reader_Bruker_Format_FID:\r\n            recursivelyEnumerateFIDs(sourcePaths_, rootpath_);\r\n\r\n            // each fid's source path is a directory but the source file is the fid\r\n            for (size_t i=0; i < sourcePaths_.size(); ++i)\r\n            {\r\n                // in \"/foo/bar/1/1SRef/fid\", replace \"/foo/bar/\" with \"\" so relativePath is \"1/1SRef/fid\"\r\n                bfs::path relativePath = sourcePaths_[i] / \"fid\";\r\n                if (rootpath_.has_branch_path())\r\n                    relativePath = bal::replace_first_copy(relativePath.string(), rootpath_.branch_path().string() + NATIVE_PATH_SLASH, \"\");\r\n                relativePath = bal::replace_all_copy(relativePath.string(), NATIVE_PATH_SLASH, \"/\");\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_FID_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_FID_format);\r\n            }\r\n            break;\r\n\r\n        // a YEP's source path is the same as the source file\r\n        case Reader_Bruker_Format_YEP:\r\n            {\r\n                sourcePaths_.push_back(rootpath_ / \"Analysis.yep\");\r\n                // strip parent path to get \"bar.d/Analysis.yep\"\r\n                bfs::path relativePath = bfs::path(rootpath_.filename()) / \"Analysis.yep\";\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_Agilent_YEP_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_Agilent_YEP_format);\r\n                msd_.run.defaultSourceFilePtr = msd_.fileDescription.sourceFilePtrs.back();\r\n            }\r\n            break;\r\n\r\n        // a BAF's source path is the same as the source file\r\n        case Reader_Bruker_Format_BAF:\r\n            {\r\n                sourcePaths_.push_back(rootpath_ / \"Analysis.baf\");\r\n                // strip parent path to get \"bar.d/Analysis.baf\"\r\n                bfs::path relativePath = bfs::path(rootpath_.filename()) / \"Analysis.baf\";\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_BAF_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_BAF_format);\r\n                msd_.run.defaultSourceFilePtr = msd_.fileDescription.sourceFilePtrs.back();\r\n            }\r\n            break;\r\n\r\n        // a TDF's source path is the same as the source file\r\n        case Reader_Bruker_Format_TDF:\r\n            {\r\n                sourcePaths_.push_back(rootpath_ / \"Analysis.tdf\");\r\n                // strip parent path to get \"bar.d/Analysis.tdf\"\r\n                bfs::path relativePath = bfs::path(rootpath_.filename()) / \"Analysis.tdf\";\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_TDF_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_TDF_format);\r\n                msd_.run.defaultSourceFilePtr = msd_.fileDescription.sourceFilePtrs.back();\r\n            }\r\n\r\n            {\r\n                sourcePaths_.push_back(rootpath_ / \"Analysis.tdf_bin\");\r\n                // strip parent path to get \"bar.d/Analysis.tdf_bin\"\r\n                bfs::path relativePath = bfs::path(rootpath_.filename()) / \"Analysis.tdf_bin\";\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_TDF_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_TDF_format);\r\n            }\r\n            break;\r\n\r\n        // a BAF/U2 combo has two sources, with different nativeID formats\r\n        case Reader_Bruker_Format_BAF_and_U2:\r\n            {\r\n                sourcePaths_.push_back(rootpath_ / \"Analysis.baf\");\r\n                // strip parent path to get \"bar.d/Analysis.baf\"\r\n                bfs::path relativePath = bfs::path(rootpath_.filename()) / \"Analysis.baf\";\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_BAF_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_BAF_format);\r\n                msd_.run.defaultSourceFilePtr = msd_.fileDescription.sourceFilePtrs.back();\r\n            }\r\n\r\n            {\r\n                sourcePaths_.push_back(bfs::change_extension(rootpath_, \".u2\"));\r\n                // in \"/foo/bar.d/bar.u2\", replace \"/foo/\" with \"\" so relativePath is \"bar.d/bar.u2\"\r\n                bfs::path relativePath = sourcePaths_.back();\r\n                if (rootpath_.has_branch_path())\r\n                    relativePath = bal::replace_first_copy(relativePath.string(), rootpath_.branch_path().string() + NATIVE_PATH_SLASH, \"\");\r\n                relativePath = bal::replace_all_copy(relativePath.string(), NATIVE_PATH_SLASH, \"/\");\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_U2_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_U2_format);\r\n            }\r\n            break;\r\n\r\n        case Reader_Bruker_Format_U2:\r\n            {\r\n                sourcePaths_.push_back(bfs::change_extension(rootpath_, \".u2\"));\r\n                // in \"/foo/bar.d/bar.u2\", replace \"/foo/\" with \"\" so relativePath is \"bar.d/bar.u2\"\r\n                bfs::path relativePath = sourcePaths_.back();\r\n                if (rootpath_.has_branch_path())\r\n                    relativePath = bal::replace_first_copy(relativePath.string(), rootpath_.branch_path().string() + NATIVE_PATH_SLASH, \"\");\r\n                relativePath = bal::replace_all_copy(relativePath.string(), NATIVE_PATH_SLASH, \"/\");\r\n                addSource(msd_, relativePath, rootpath_);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_U2_nativeID_format);\r\n                msd_.fileDescription.sourceFilePtrs.back()->set(MS_Bruker_U2_format);\r\n                msd_.run.defaultSourceFilePtr = msd_.fileDescription.sourceFilePtrs.back();\r\n            }\r\n            break;\r\n    }\r\n}\r\n\r\nPWIZ_API_DECL void SpectrumList_Bruker::createIndex()\r\n{\r\n    using namespace boost::spirit::karma;\r\n    map<std::string, size_t> idToIndexTempMap;\r\n\r\n    if (format_ == Reader_Bruker_Format_U2 ||\r\n        format_ == Reader_Bruker_Format_BAF_and_U2)\r\n    {\r\n        msd_.fileDescription.fileContent.set(MS_EMR_spectrum);\r\n\r\n        for (size_t i=0, end=compassDataPtr_->getLCSourceCount(); i < end; ++i)\r\n        {\r\n            LCSpectrumSourcePtr source = compassDataPtr_->getLCSource(i);\r\n\r\n            for (size_t scan=0, end=compassDataPtr_->getLCSpectrumCount(i); scan < end; ++scan)\r\n            {\r\n                index_.push_back(IndexEntry());\r\n                IndexEntry& si = index_.back();\r\n                si.source = i;\r\n                si.collection = source->getCollectionId();\r\n                si.scan = scan;\r\n                si.index = index_.size()-1;\r\n                si.id = \"collection=\" + lexical_cast<std::string>(si.collection) +\r\n                        \" scan=\" + lexical_cast<std::string>(si.scan);\r\n                idToIndexTempMap[si.id] = si.index;\r\n            }\r\n        }\r\n    }\r\n\r\n    if (format_ == Reader_Bruker_Format_FID)\r\n    {\r\n        int scan = -1;\r\n        BOOST_FOREACH(const SourceFilePtr& sf, msd_.fileDescription.sourceFilePtrs)\r\n        {\r\n            index_.push_back(IndexEntry());\r\n            IndexEntry& si = index_.back();\r\n            si.source = si.collection = -1;\r\n            si.index = index_.size()-1;\r\n            si.scan = ++scan;\r\n            si.id = \"file=\" + encode_xml_id_copy(sf->id);\r\n            idToIndexTempMap[si.id] = si.index;\r\n        }\r\n    }\r\n    else if (format_ == Reader_Bruker_Format_TDF)\r\n    {\r\n        index_.reserve(compassDataPtr_->getMSSpectrumCount());\r\n        for (size_t scan = 1, end = compassDataPtr_->getMSSpectrumCount(); scan <= end; ++scan)\r\n        {\r\n            index_.emplace_back(IndexEntry());\r\n            IndexEntry& si = index_.back();\r\n            si.source = si.collection = -1;\r\n            si.index = index_.size() - 1;\r\n            si.scan = scan;\r\n            auto frameScanPair = compassDataPtr_->getFrameScanPair(scan);\r\n            std::back_insert_iterator<std::string> sink(si.id);\r\n            if (config_.combineIonMobilitySpectra)\r\n            {\r\n                generate(sink,\r\n                         \"merged=\" << int_ << \" frame=\" << int_ << \" scanStart=\" << int_ << \" scanEnd=\" << int_,\r\n                         si.index, frameScanPair.frame, frameScanPair.scanStart, frameScanPair.scanEnd);\r\n                idToIndexTempMap[si.id] = si.index;\r\n            }\r\n            else // not inserting into idToIndexTempMap (instead uses on-the-fly logic in find())\r\n                generate(sink,\r\n                         \"frame=\" << int_ << \" scan=\" << int_,\r\n                         frameScanPair.frame, frameScanPair.scanStart);\r\n        }\r\n    }\r\n    else if (format_ != Reader_Bruker_Format_U2)\r\n    {\r\n        for (size_t scan=1, end=compassDataPtr_->getMSSpectrumCount(); scan <= end; ++scan)\r\n        {\r\n            index_.push_back(IndexEntry());\r\n            IndexEntry& si = index_.back();\r\n            si.source = si.collection = -1;\r\n            si.index = index_.size()-1;\r\n            si.scan = scan;\r\n            std::back_insert_iterator<std::string> sink(si.id);\r\n            generate(sink,\r\n                     \"scan=\" << int_,\r\n                     si.scan);\r\n            idToIndexTempMap[si.id] = si.index;\r\n        }\r\n    }\r\n\r\n    idToIndexMap_.reserve(idToIndexTempMap.size());\r\n    idToIndexMap_.insert(boost::container::ordered_unique_range, idToIndexTempMap.begin(), idToIndexTempMap.end());\r\n    size_ = index_.size();\r\n}\r\n\r\nPWIZ_API_DECL bool SpectrumList_Bruker::hasIonMobility() const\r\n{\r\n    return format_ == Reader_Bruker_Format_TDF;\r\n}\r\n\r\nPWIZ_API_DECL bool SpectrumList_Bruker::hasPASEF() const\r\n{\r\n    return compassDataPtr_->hasPASEFData();\r\n}\r\n\r\nPWIZ_API_DECL bool SpectrumList_Bruker::canConvertIonMobilityAndCCS() const\r\n{\r\n    return format_ == Reader_Bruker_Format_TDF;\r\n}\r\n\r\n// Per email thread Aug 22 2017 bpratt, mattc, Bruker's SvenB:\r\n// The gas is nitrogen(14.0067 AMU) and the temperature is(according to Sven) assumed to be 305K.\r\nstatic const double ccs_conversion_factor = 18509.863216340458;\r\nstatic const double MolWeightGas = 14.0067;\r\nstatic const double Temperature = 305;\r\n\r\nPWIZ_API_DECL double SpectrumList_Bruker::ionMobilityToCCS(double inverseK0, double mz, int charge) const\r\n{\r\n    double MolWeight = mz * abs(charge) + chemistry::Electron * charge;\r\n    double ReducedMass = MolWeight * MolWeightGas / (MolWeight + MolWeightGas);\r\n    double K0 = (inverseK0 == 0) ? 0 : (1.0 / inverseK0);\r\n    double ccs = ccs_conversion_factor * abs(charge) / (sqrt(ReducedMass * Temperature) * K0);\r\n    return ccs;    // in Angstrom^2\r\n}\r\n\r\nPWIZ_API_DECL double SpectrumList_Bruker::ccsToIonMobility(double ccs, double mz, int charge) const\r\n{\r\n    double MolWeight = mz * abs(charge) + chemistry::Electron * charge;\r\n    double ReducedMass = MolWeight * MolWeightGas / (MolWeight + MolWeightGas);\r\n    double K0 = ccs_conversion_factor * abs(charge) / (sqrt(ReducedMass * Temperature) * ccs);\r\n    return K0 == 0 ? 0 : 1 / K0;    // in Vs/cm^2\r\n}\r\n\r\n\r\n\r\n} // detail\r\n} // msdata\r\n} // pwiz\r\n\r\n\r\n#else // PWIZ_READER_BRUKER\r\n\r\n//\r\n// non-MSVC implementation\r\n//\r\n\r\nnamespace pwiz {\r\nnamespace msdata {\r\nnamespace detail {\r\n\r\nnamespace {const SpectrumIdentity emptyIdentity;}\r\n\r\nsize_t SpectrumList_Bruker::size() const {return 0;}\r\nconst SpectrumIdentity& SpectrumList_Bruker::spectrumIdentity(size_t index) const {return emptyIdentity;}\r\nsize_t SpectrumList_Bruker::find(const std::string& id) const {return 0;}\r\nSpectrumPtr SpectrumList_Bruker::spectrum(size_t index, bool getBinaryData) const {return SpectrumPtr();}\r\nSpectrumPtr SpectrumList_Bruker::spectrum(size_t index, DetailLevel detailLevel) const {return SpectrumPtr();}\r\nSpectrumPtr SpectrumList_Bruker::spectrum(size_t index, bool getBinaryData, const pwiz::util::IntegerSet& msLevelsToCentroid) const {return SpectrumPtr();}\r\nSpectrumPtr SpectrumList_Bruker::spectrum(size_t index, DetailLevel detailLevel, const pwiz::util::IntegerSet& msLevelsToCentroid) const {return SpectrumPtr();}\r\nbool SpectrumList_Bruker::hasIonMobility() const { return false; }\r\nbool SpectrumList_Bruker::hasPASEF() const { return false; }\r\nbool SpectrumList_Bruker::canConvertIonMobilityAndCCS() const { return false; }\r\ndouble SpectrumList_Bruker::ionMobilityToCCS(double ionMobility, double mz, int charge) const {return 0;}\r\ndouble SpectrumList_Bruker::ccsToIonMobility(double ccs, double mz, int charge) const {return 0;}\r\n} // detail\r\n} // msdata\r\n} // pwiz\r\n\r\n#endif // PWIZ_READER_BRUKER\r\n", "meta": {"hexsha": "33ea4a3fe1045c16e3d80fff58ceb1dbbb2697bf", "size": 32664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/data/vendor_readers/Bruker/SpectrumList_Bruker.cpp", "max_stars_repo_name": "rfellers/pwiz", "max_stars_repo_head_hexsha": "df8e8b28591f581e6ce249fca885250f055fc541", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pwiz/data/vendor_readers/Bruker/SpectrumList_Bruker.cpp", "max_issues_repo_name": "rfellers/pwiz", "max_issues_repo_head_hexsha": "df8e8b28591f581e6ce249fca885250f055fc541", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/data/vendor_readers/Bruker/SpectrumList_Bruker.cpp", "max_forks_repo_name": "rfellers/pwiz", "max_forks_repo_head_hexsha": "df8e8b28591f581e6ce249fca885250f055fc541", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6632653061, "max_line_length": 216, "alphanum_fraction": 0.5848334558, "num_tokens": 7256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1175721397294269, "lm_q2_score": 0.03358950879422127, "lm_q1q2_score": 0.003949190421396997}}
{"text": "////////////////////////////////////////////////////////////////////////////\r\n//! \\file    util.cpp\r\n//! \\date    February 2018\r\n//! \\author  Eric Barnett\r\n//!          Marc-Antoine Lacasse\r\n//!\r\n//! Copyright (C) 2018 Eric Barnett         <e.barnett@robotiq.com>\r\n//! Copyright (C) 2018 Marc-Antoine Lacasse <malacasse@robotiq.com>\r\n//! Copyright (C) 2018 Clément Gosselin     <gosselin@gmc.ulaval.ca>\r\n//!\r\n//! \\brief Time, file IO, and general std::vector functions\r\n//!\r\n//! This file is part of BA, a bisection algorithm for time-optimal trajectory\r\n//! planning\r\n//!\r\n//! This Source Code Form is subject to the terms of the Berkeley Software\r\n//! Distribution (BSD) 3-clause license . If a copy of the BSD license was not\r\n//! distributed with this file, you can obtain one at\r\n//! https://opensource.org/licenses/BSD-3-Clause.\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)\r\n  #define isWin\r\n#endif\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n// Includes\r\n////////////////////////////////////////////////////////////////////////////////\r\n#include \"util.h\"\r\n#ifdef _MSC_VER\r\n#define NOMINMAX // for std::min\r\n#endif\r\n#ifdef isWin\r\n  #include <windows.h> // for cpu time tracking\r\n  #include <io.h> // for function doesFileExist()\r\n#else //Linux\r\n  #include \"stdio.h\" //for file IO\r\n  #include <unistd.h> // for function doesFileExist(): for testing for file existence\r\n#endif\r\n\r\n#include <Eigen/Dense>\r\nusing namespace Eigen;\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief getTime\r\n//!\r\n//! get the current time (for computation time tracking)\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nTime getTime(void)\r\n{\r\n  Time time;\r\n  #ifdef isWin\r\n     LARGE_INTEGER count,freq;\r\n     QueryPerformanceCounter(&count);\r\n     QueryPerformanceFrequency(&freq);\r\n     time.a=(int64_t)count.QuadPart;\r\n     time.b=(int64_t)freq.QuadPart;\r\n  #else\r\n    struct timespec CurrentTime;\r\n    clock_gettime(CLOCK_REALTIME, &CurrentTime);\r\n    time.a=(int64_t)CurrentTime.tv_sec;\r\n    time.b=(int64_t)CurrentTime.tv_nsec;\r\n  #endif\r\n  return time;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief diffTime\r\n//!\r\n//! Compute the difference between two time structs (for computation time tracking)\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\ndouble diffTime(const Time &endTime,const Time &startTime)\r\n{\r\n  double dTime;\r\n  #ifdef isWin\r\n    dTime=(double)(endTime.a-startTime.a)/(double)startTime.b;\r\n  #else\r\n    if(endTime.b < startTime.b)\r\n         dTime=(double)(endTime.a-startTime.a)-1+(double)(endTime.b-startTime.b+1.0e9)/1.0e9;\r\n    else dTime=(double)(endTime.a-startTime.a)  +(double)(endTime.b-startTime.b)/1.0e9;\r\n  #endif\r\n  return dTime;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief NextLine\r\n//!\r\n//!Rread in characters one at a time from a file until end-of-line or\r\n//! end-of-file is reached\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint NextLine(FILE *fid)\r\n{\r\n  int c=0, EOL=10;\r\n  while (c!=EOL && c!=EOF) c=fgetc(fid);\r\n  return c;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief doesFileExist\r\n//!\r\n//! Check for file existence\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint doesFileExist(const char *fname)\r\n{\r\n#ifdef isWin\r\n  if(_access(fname, 0) == 0)\r\n    return 0; // exists\r\n  else\r\n    return -1; // does not exist\r\n#else // Linux\r\n  if( access( fname, F_OK ) != -1 )\r\n    return 0; // exists\r\n  else\r\n    return -1; // does not exist\r\n#endif\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief doesFileExist\r\n//!\r\n//! Make a directory if it does not exist\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint mkDirIfNec(const char *dirname)\r\n{\r\n   int retVal = 0;\r\n#ifdef isWin\r\n   if(!CreateDirectoryA(dirname ,NULL))\r\n   {\r\n      retVal = -1;\r\n   }\r\n#else\r\n   if(mkdir(dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1 )\r\n   {\r\n      retVal = -1;\r\n   }\r\n#endif\r\n\r\n   return retVal;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief readChar\r\n//!\r\n//! read in a char array and store it in a std::string\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nstd::string readChar(FILE *fid,int &readCountTotal)\r\n{\r\n   char tmpStr[80];\r\n   std::string outStr;\r\n   readCountTotal+=fscanf(fid,\"%s\",tmpStr);\r\n   NextLine(fid);\r\n   outStr=tmpStr;\r\n   return(outStr);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief readInt\r\n//!\r\n//! read in an int\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint readInt(FILE *fid,int &readCountTotal)\r\n{\r\n   int tmpInt;\r\n   readCountTotal+=fscanf(fid,\"%d\",&tmpInt);\r\n   NextLine(fid);\r\n   return(tmpInt);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief readDouble\r\n//!\r\n//! read in a double\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\ndouble readDouble(FILE *fid,int &readCountTotal)\r\n{\r\n   double tmpDouble;\r\n   readCountTotal+=fscanf(fid,\"%lf\",&tmpDouble);\r\n   NextLine(fid);\r\n   return(tmpDouble);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief readDoubleVector\r\n//!\r\n//! read in a vector of doubles\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nstd::vector<double> readDoubleVector(FILE *fid,\r\n                                     int &readCountTotal,\r\n                                     const int vectorLen)\r\n{\r\n\r\n   std::vector<double> tmpVect(vectorLen);\r\n\r\n   for(int i=0;i<vectorLen;i++)\r\n   {\r\n      readCountTotal += fscanf(fid,\"%lf\", &tmpVect[i]);\r\n   }\r\n   NextLine(fid);\r\n\r\n   return tmpVect;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief readBool\r\n//!\r\n//! read in a bool\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nbool readBool(FILE *fid,int &readCountTotal)\r\n{\r\n   return(readInt(fid,readCountTotal)==1);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief normalizeArcLength\r\n//!\r\n//! Normalize the monotonic vector s to lie in the range 0 and 1\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint normalizeArcLength(std::vector<double> &s)\r\n{\r\n  s=(1.0/s[s.size()-1])*s;\r\n  return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief smooth\r\n//!\r\n//! moving average filter for a vector of data\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint smooth(std::vector<double>&x,int w)\r\n{\r\n   int n = (int)x.size();\r\n   w = std::min(w,n);\r\n   int wMid = w/2 + w%2 - 1;\r\n   w = 2*wMid + 1;\r\n\r\n   std::vector<double> x2(n);\r\n   double xt, xte;\r\n\r\n   x2[0] = x[0];\r\n   x2[n-1] = x[n-1];\r\n\r\n   for(int i=1; i<wMid; ++i)\r\n   {\r\n      xt = 0;\r\n      xte = 0;\r\n      int nPtsT = 2*i+1;\r\n      for(int j=0; j<nPtsT; ++j)\r\n      {\r\n         xt += x[j];\r\n         xte += x[n-j-1];\r\n      }\r\n      x2[i] = xt/nPtsT;\r\n      x2[n-i-1] = xte/nPtsT;\r\n   }\r\n   for(int i=wMid; i<n-wMid; ++i)\r\n   {\r\n      xt=0;\r\n      for(int j=i-wMid; j<i+wMid+1; ++j) xt += x[j];\r\n      x2[i] = xt/w;\r\n   }\r\n   x = x2;\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief minsmooth\r\n//!\r\n//! minimum of a moving window for a vector\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint minsmooth(std::vector<double>&x,int w)\r\n{\r\n   int n = (int)x.size();\r\n   w = std::min(w,n);\r\n   int wMid = w/2 + w%2 - 1;\r\n   w = 2*wMid + 1;\r\n\r\n   std::vector<double> x2(n);\r\n   double xt, xte;\r\n\r\n   x2[0] = x[0];\r\n   x2[n-1] = x[n-1];\r\n\r\n   for(int i=1; i<wMid; ++i)\r\n   {\r\n      xt = x[0];\r\n      xte = x[n-1];\r\n      int nPtsT = 2*i + 1;\r\n      for(int j=1; j<nPtsT; ++j)\r\n      {\r\n         xt  = std::min(xt,x[j]);\r\n         xte = std::min(xte,x[n-j-1]);\r\n      }\r\n      x2[i] = xt;\r\n      x2[n-i-1] = xte;\r\n   }\r\n   for(int i=wMid; i<n-wMid; ++i)\r\n   {\r\n      xt = x[i-wMid];\r\n      for(int j=i-wMid+1;j<i+wMid+1; ++j) xt = std::min(xt,x[j]);\r\n      x2[i] = xt;\r\n   }\r\n\r\n   smooth(x2, w);\r\n   for(int i=0; i<n; ++i) x[i] = std::min(x[i], x2[i]);\r\n\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief decimate\r\n//!\r\n//! decimate a vector of data\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint decimate(std::vector<double>&x,int w)\r\n{\r\n  int nIn=(int)x.size();\r\n  int nOut=(nIn-1)/w+1;\r\n  for(int i=0;i<nOut;i++) x[i]=x[w*i];\r\n  if(w*(nOut-1)+1 != nIn) x[nOut-1]=x[nIn-1];\r\n\r\n  x.resize(nOut);\r\n  return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief solveQuadratic\r\n//!\r\n//! Solve the quadratic equation Ax^2 + Bx + C = 0 for x\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint solveQuadratic(const double A,const double B,const double C,\r\n  double &sol1,double &sol2)\r\n{\r\n\r\n  if(std::abs(A)<1e-308)\r\n  {\r\n    if(std::abs(B)<1e-308) return -2; // infinite solutions\r\n    sol1=-C/B; sol2=sol1;\r\n    return 0;\r\n  }\r\n\r\n  double rad,den,F1,F2;\r\n  rad=B*B-4*A*C;\r\n  if(rad<0) return -1;\r\n\r\n  den=2*A;\r\n  F1=-B/den; F2=std::sqrt(rad)/den;\r\n\r\n  sol1=F1+F2;\r\n  sol2=F1-F2;\r\n\r\n  return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief findMedian\r\n//!\r\n//! Find the median value for a vector of data\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\ndouble findMedian(std::vector <double> &x)\r\n{\r\n  size_t nPts=x.size();\r\n  std::vector<double> xSorted=x;\r\n  std::sort (xSorted.begin(), xSorted.end());\r\n  bool isOdd=nPts%2==1; // % is the MOD operator\r\n  double xMED;\r\n  size_t midPt=nPts/2;\r\n  if(isOdd) xMED=xSorted[midPt];\r\n  else      xMED=.5*(xSorted[midPt-1]+xSorted[midPt]);\r\n\r\n  return(xMED);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief LUsolve\r\n//!\r\n//! Solve linear system using LU decomposition or SVD\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nbool solveLinSys(const std::vector<std::vector<double>> &Av,\r\n               const std::vector<double> &bv, std::vector<double> &xv,const bool isSVD)\r\n{\r\n  bool isIllCond=false;\r\n  double minCondNum=100.0*std::numeric_limits<double>::epsilon();\r\n\r\n  int i,j,dim=(int)bv.size();\r\n\r\n  MatrixXd A(dim,dim);\r\n  VectorXd b(dim),x(dim);\r\n\r\n  for(i=0;i<dim;i++)\r\n  {\r\n    for(j=0;j<dim;j++) A(i,j)=Av[i][j];\r\n    b[i]=bv[i];\r\n  }\r\n\r\n  if(isSVD)\r\n  {\r\n    JacobiSVD<MatrixXd> A_svd(A, ComputeThinU | ComputeThinV);\r\n    double condNum = A_svd.singularValues()(0)\r\n        / A_svd.singularValues()(A_svd.singularValues().size()-1);\r\n    if(condNum<minCondNum) {isIllCond=true; return isIllCond;}\r\n    x=A_svd.solve(b);\r\n  }\r\n  else x = A.lu().solve(b);\r\n\r\n  for(i=0;i<dim;i++) xv[i]=x[i];\r\n  return isIllCond;\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief remClosePts\r\n//!\r\n//! remove close pts in input data\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint remClosePts(std::vector<std::vector<double>> &x,\r\n                    std::vector<std::vector<double>> &y,\r\n                    double xThresh)\r\n{\r\n  printf(\"remClosePts():  ||dtheta||_min=%f deg imposed. \",xThresh);\r\n\r\n  double dthetaThreshSQ=xThresh*xThresh;\r\n  double dtheta,dthetaSQsum;\r\n  bool anyRem=false;\r\n  int i,j,curPt;\r\n  int nPts=(int)x[0].size();\r\n  int nPtsi=nPts;\r\n  std::vector<double> isRem(nPts);\r\n\r\n  int xLen=(int)x.size();\r\n  int yLen=(int)y.size();\r\n\r\n  // A minimum point-to-point distance threshold is imposed\r\n  // At each iteration, only non-adjacent points can be designated for removal\r\n  while(1)\r\n  {\r\n    anyRem=false;\r\n\r\n    // Points are tagged for removal\r\n    for(i=1;i<nPts;i++)\r\n    {\r\n      dthetaSQsum=0;\r\n      for(j=0;j<xLen;j++)\r\n      {\r\n        dtheta=x[j][i]-x[j][i-1];\r\n        dthetaSQsum+=dtheta*dtheta;\r\n      }\r\n      if(dthetaSQsum<dthetaThreshSQ && !isRem[i-1])\r\n      {\r\n        isRem[i]=true;\r\n        anyRem=true;\r\n      }\r\n    }\r\n    if(isRem[nPts-1] && nPts>2)\r\n    {\r\n      isRem[nPts-1]=false;\r\n      isRem[nPts-2]=true;\r\n      isRem[nPts-3]=false;\r\n    }\r\n    curPt=0;\r\n    if(anyRem)\r\n    {\r\n      // Tagged points are removed from the trajectory\r\n      for(i=0;i<nPts;i++)\r\n      {\r\n        if(!isRem[i])\r\n        {\r\n          for(j=0;j<xLen;j++) x[j][curPt]= x[j][i];\r\n          if(yLen>0)\r\n          {\r\n             for(j=0;j<yLen;j++) y[j][curPt]= y[j][i];\r\n          }\r\n          curPt++;\r\n        }\r\n      }\r\n      nPts=curPt;\r\n      for(j=0;j<xLen;j++) x[j].resize(curPt);\r\n      if(yLen>0)\r\n      {\r\n         for(j=0;j<yLen;j++) y[j].resize(curPt);\r\n      }\r\n      isRem.assign(nPts,false);\r\n    }\r\n    else break;\r\n  }\r\n  printf(\" before %d points; after %d points\\n\",nPtsi,nPts);\r\n  return 0;\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief aa2q\r\n//!\r\n//! axis-angle to quaternion orientation\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nstd::array<double,4> aa2q(std::array<double,3> aa)\r\n{\r\n   std::array<double,4> q;\r\n   double theta=std::sqrt(aa[0]*aa[0] + aa[1]*aa[1] + aa[2]*aa[2]);\r\n\r\n   if(theta<1e-6)\r\n   {\r\n      q={1.0,0.0,0.0,0.0};\r\n   }\r\n   else\r\n   {\r\n      double sin_half_theta=std::sin(0.5*theta);\r\n      q[0]=std::cos(0.5*theta);\r\n      for(int i=0; i<3; i++)\r\n      {\r\n         q[i+1]=aa[i]*sin_half_theta/theta;\r\n      }\r\n   }\r\n   return q;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief q2aa\r\n//!\r\n//! quaternion to axis-angle orientation\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nstd::array<double,3> q2aa(std::array<double,4> q)\r\n{\r\n   std::array<double,3> aa;\r\n   double norme=std::sqrt(q[1]*q[1] + q[2]*q[2] + q[3]*q[3]);\r\n\r\n   if(norme<1e-6)\r\n   {\r\n      aa={0.0,0.0,0.0};\r\n   }\r\n   else\r\n   {\r\n      double theta=2.0*std::atan2(norme,q[0])/norme;\r\n      for(int i=0; i<3; i++)\r\n      {\r\n         aa[i]=theta*q[i+1];\r\n      }\r\n   }\r\n   return aa;\r\n}\r\n\r\n", "meta": {"hexsha": "16ef3b959837b13583f432c1064abdbf7bda3fea", "size": 14943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "batotp/util.cpp", "max_stars_repo_name": "lpdon/batotp", "max_stars_repo_head_hexsha": "f6b807dc10a8a7756adeb48223f426614af5aed6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-05-17T02:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:30:18.000Z", "max_issues_repo_path": "batotp/util.cpp", "max_issues_repo_name": "lpdon/batotp", "max_issues_repo_head_hexsha": "f6b807dc10a8a7756adeb48223f426614af5aed6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-02T07:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-02T07:31:29.000Z", "max_forks_repo_path": "batotp/util.cpp", "max_forks_repo_name": "lpdon/batotp", "max_forks_repo_head_hexsha": "f6b807dc10a8a7756adeb48223f426614af5aed6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T19:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T10:44:36.000Z", "avg_line_length": 25.675257732, "max_line_length": 94, "alphanum_fraction": 0.419393696, "num_tokens": 3706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734041427965, "lm_q2_score": 0.046724962774365095, "lm_q1q2_score": 0.0038640301523962146}}
{"text": "// $Id$\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n//  Contribution from Roger Sayle\n#include <vector>\n#include <DataStructs/ExplicitBitVect.h>\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/SmilesParse/SmilesParse.h>\n#include <GraphMol/Substruct/SubstructMatch.h>\n#include <GraphMol/MolOps.h>\n\n#include <RDGeneral/BoostStartInclude.h>\n#include <boost/flyweight.hpp>\n#include <boost/flyweight/no_tracking.hpp>\n#include <RDGeneral/BoostEndInclude.h>\n\nnamespace {\nstruct Patterns {\n  RDKit::ROMol *bit_8;\n  RDKit::ROMol *bit_11;\n  RDKit::ROMol *bit_13;\n  RDKit::ROMol *bit_14;\n  RDKit::ROMol *bit_15;\n  RDKit::ROMol *bit_16;\n  RDKit::ROMol *bit_17;\n  RDKit::ROMol *bit_19;\n  RDKit::ROMol *bit_20;\n  RDKit::ROMol *bit_21;\n  RDKit::ROMol *bit_22;\n  RDKit::ROMol *bit_23;\n  RDKit::ROMol *bit_24;\n  RDKit::ROMol *bit_25;\n  RDKit::ROMol *bit_26;\n  RDKit::ROMol *bit_28;\n  RDKit::ROMol *bit_30;\n  RDKit::ROMol *bit_31;\n  RDKit::ROMol *bit_32;\n  RDKit::ROMol *bit_33;\n  RDKit::ROMol *bit_34;\n  RDKit::ROMol *bit_36;\n  RDKit::ROMol *bit_37;\n  RDKit::ROMol *bit_38;\n  RDKit::ROMol *bit_39;\n  RDKit::ROMol *bit_40;\n  RDKit::ROMol *bit_41;\n  RDKit::ROMol *bit_43;\n  RDKit::ROMol *bit_44;\n  RDKit::ROMol *bit_45;\n  RDKit::ROMol *bit_47;\n  RDKit::ROMol *bit_48;\n  RDKit::ROMol *bit_49;\n  RDKit::ROMol *bit_50;\n  RDKit::ROMol *bit_51;\n  RDKit::ROMol *bit_52;\n  RDKit::ROMol *bit_53;\n  RDKit::ROMol *bit_54;\n  RDKit::ROMol *bit_55;\n  RDKit::ROMol *bit_56;\n  RDKit::ROMol *bit_57;\n  RDKit::ROMol *bit_58;\n  RDKit::ROMol *bit_59;\n  RDKit::ROMol *bit_60;\n  RDKit::ROMol *bit_61;\n  RDKit::ROMol *bit_62;\n  RDKit::ROMol *bit_63;\n  RDKit::ROMol *bit_64;\n  RDKit::ROMol *bit_65;\n  RDKit::ROMol *bit_66;\n  RDKit::ROMol *bit_67;\n  RDKit::ROMol *bit_68;\n  RDKit::ROMol *bit_69;\n  RDKit::ROMol *bit_70;\n  RDKit::ROMol *bit_71;\n  RDKit::ROMol *bit_72;\n  RDKit::ROMol *bit_73;\n  RDKit::ROMol *bit_74;\n  RDKit::ROMol *bit_75;\n  RDKit::ROMol *bit_76;\n  RDKit::ROMol *bit_77;\n  RDKit::ROMol *bit_78;\n  RDKit::ROMol *bit_79;\n  RDKit::ROMol *bit_80;\n  RDKit::ROMol *bit_81;\n  RDKit::ROMol *bit_82;\n  RDKit::ROMol *bit_83;\n  RDKit::ROMol *bit_84;\n  RDKit::ROMol *bit_85;\n  RDKit::ROMol *bit_86;\n  RDKit::ROMol *bit_87;\n  RDKit::ROMol *bit_89;\n  RDKit::ROMol *bit_90;\n  RDKit::ROMol *bit_91;\n  RDKit::ROMol *bit_92;\n  RDKit::ROMol *bit_93;\n  RDKit::ROMol *bit_94;\n  RDKit::ROMol *bit_95;\n  RDKit::ROMol *bit_96;\n  RDKit::ROMol *bit_97;\n  RDKit::ROMol *bit_98;\n  RDKit::ROMol *bit_99;\n  RDKit::ROMol *bit_100;\n  RDKit::ROMol *bit_101;\n  RDKit::ROMol *bit_102;\n  RDKit::ROMol *bit_104;\n  RDKit::ROMol *bit_105;\n  RDKit::ROMol *bit_106;\n  RDKit::ROMol *bit_107;\n  RDKit::ROMol *bit_108;\n  RDKit::ROMol *bit_109;\n  RDKit::ROMol *bit_110;\n  RDKit::ROMol *bit_111;\n  RDKit::ROMol *bit_112;\n  RDKit::ROMol *bit_113;\n  RDKit::ROMol *bit_114;\n  RDKit::ROMol *bit_115;\n  RDKit::ROMol *bit_116;\n  RDKit::ROMol *bit_117;\n  RDKit::ROMol *bit_118;\n  RDKit::ROMol *bit_119;\n  RDKit::ROMol *bit_120;\n  RDKit::ROMol *bit_121;\n  RDKit::ROMol *bit_122;\n  RDKit::ROMol *bit_123;\n  RDKit::ROMol *bit_124;\n  RDKit::ROMol *bit_126;\n  RDKit::ROMol *bit_127;\n  RDKit::ROMol *bit_128;\n  RDKit::ROMol *bit_129;\n  RDKit::ROMol *bit_131;\n  RDKit::ROMol *bit_132;\n  RDKit::ROMol *bit_133;\n  RDKit::ROMol *bit_135;\n  RDKit::ROMol *bit_136;\n  RDKit::ROMol *bit_137;\n  RDKit::ROMol *bit_138;\n  RDKit::ROMol *bit_139;\n  RDKit::ROMol *bit_140;\n  RDKit::ROMol *bit_141;\n  RDKit::ROMol *bit_142;\n  RDKit::ROMol *bit_144;\n  RDKit::ROMol *bit_145;\n  RDKit::ROMol *bit_147;\n  RDKit::ROMol *bit_148;\n  RDKit::ROMol *bit_149;\n  RDKit::ROMol *bit_150;\n  RDKit::ROMol *bit_151;\n  RDKit::ROMol *bit_152;\n  RDKit::ROMol *bit_154;\n  RDKit::ROMol *bit_155;\n  RDKit::ROMol *bit_156;\n  RDKit::ROMol *bit_157;\n  RDKit::ROMol *bit_158;\n  RDKit::ROMol *bit_162;\n  RDKit::ROMol *bit_165;\n  Patterns()\n      : bit_8(RDKit::SmartsToMol(\"[!#6!#1]1~*~*~*~1\")),\n        bit_11(RDKit::SmartsToMol(\"*1~*~*~*~1\")),\n        bit_13(RDKit::SmartsToMol(\"[#8]~[#7](~[#6])~[#6]\")),\n        bit_14(RDKit::SmartsToMol(\"[#16]-[#16]\")),\n        bit_15(RDKit::SmartsToMol(\"[#8]~[#6](~[#8])~[#8]\")),\n        bit_16(RDKit::SmartsToMol(\"[!#6!#1]1~*~*~1\")),\n        bit_17(RDKit::SmartsToMol(\"[#6]#[#6]\")),\n        bit_19(RDKit::SmartsToMol(\"*1~*~*~*~*~*~*~1\")),\n        bit_20(RDKit::SmartsToMol(\"[#14]\")),\n        bit_21(RDKit::SmartsToMol(\"[#6]=[#6](~[!#6!#1])~[!#6!#1]\")),\n        bit_22(RDKit::SmartsToMol(\"*1~*~*~1\")),\n        bit_23(RDKit::SmartsToMol(\"[#7]~[#6](~[#8])~[#8]\")),\n        bit_24(RDKit::SmartsToMol(\"[#7]-[#8]\")),\n        bit_25(RDKit::SmartsToMol(\"[#7]~[#6](~[#7])~[#7]\")),\n        bit_26(RDKit::SmartsToMol(\"[#6]=@[#6](@*)@*\")),\n        bit_28(RDKit::SmartsToMol(\"[!#6!#1]~[CH2]~[!#6!#1]\")),\n        bit_30(RDKit::SmartsToMol(\"[#6]~[!#6!#1](~[#6])(~[#6])~*\")),\n        bit_31(RDKit::SmartsToMol(\"[!#6!#1]~[F,Cl,Br,I]\")),\n        bit_32(RDKit::SmartsToMol(\"[#6]~[#16]~[#7]\")),\n        bit_33(RDKit::SmartsToMol(\"[#7]~[#16]\")),\n        bit_34(RDKit::SmartsToMol(\"[CH2]=*\")),\n        bit_36(RDKit::SmartsToMol(\"[#16R]\")),\n        bit_37(RDKit::SmartsToMol(\"[#7]~[#6](~[#8])~[#7]\")),\n        bit_38(RDKit::SmartsToMol(\"[#7]~[#6](~[#6])~[#7]\")),\n        bit_39(RDKit::SmartsToMol(\"[#8]~[#16](~[#8])~[#8]\")),\n        bit_40(RDKit::SmartsToMol(\"[#16]-[#8]\")),\n        bit_41(RDKit::SmartsToMol(\"[#6]#[#7]\")),\n        bit_43(RDKit::SmartsToMol(\"[!#6!#1!H0]~*~[!#6!#1!H0]\")),\n        bit_44(RDKit::SmartsToMol(\n            \"[!#1;!#6;!#7;!#8;!#9;!#14;!#15;!#16;!#17;!#35;!#53]\")),\n        bit_45(RDKit::SmartsToMol(\"[#6]=[#6]~[#7]\")),\n        bit_47(RDKit::SmartsToMol(\"[#16]~*~[#7]\")),\n        bit_48(RDKit::SmartsToMol(\"[#8]~[!#6!#1](~[#8])~[#8]\")),\n        bit_49(RDKit::SmartsToMol(\"[!+0]\")),\n        bit_50(RDKit::SmartsToMol(\"[#6]=[#6](~[#6])~[#6]\")),\n        bit_51(RDKit::SmartsToMol(\"[#6]~[#16]~[#8]\")),\n        bit_52(RDKit::SmartsToMol(\"[#7]~[#7]\")),\n        bit_53(RDKit::SmartsToMol(\"[!#6!#1!H0]~*~*~*~[!#6!#1!H0]\")),\n        bit_54(RDKit::SmartsToMol(\"[!#6!#1!H0]~*~*~[!#6!#1!H0]\")),\n        bit_55(RDKit::SmartsToMol(\"[#8]~[#16]~[#8]\")),\n        bit_56(RDKit::SmartsToMol(\"[#8]~[#7](~[#8])~[#6]\")),\n        bit_57(RDKit::SmartsToMol(\"[#8R]\")),\n        bit_58(RDKit::SmartsToMol(\"[!#6!#1]~[#16]~[!#6!#1]\")),\n        bit_59(RDKit::SmartsToMol(\"[#16]!:*:*\")),\n        bit_60(RDKit::SmartsToMol(\"[#16]=[#8]\")),\n        bit_61(RDKit::SmartsToMol(\"*~[#16](~*)~*\")),\n        bit_62(RDKit::SmartsToMol(\"*@*!@*@*\")),\n        bit_63(RDKit::SmartsToMol(\"[#7]=[#8]\")),\n        bit_64(RDKit::SmartsToMol(\"*@*!@[#16]\")),\n        bit_65(RDKit::SmartsToMol(\"c:n\")),\n        bit_66(RDKit::SmartsToMol(\"[#6]~[#6](~[#6])(~[#6])~*\")),\n        bit_67(RDKit::SmartsToMol(\"[!#6!#1]~[#16]\")),\n        bit_68(RDKit::SmartsToMol(\"[!#6!#1!H0]~[!#6!#1!H0]\")),\n        bit_69(RDKit::SmartsToMol(\"[!#6!#1]~[!#6!#1!H0]\")),\n        bit_70(RDKit::SmartsToMol(\"[!#6!#1]~[#7]~[!#6!#1]\")),\n        bit_71(RDKit::SmartsToMol(\"[#7]~[#8]\")),\n        bit_72(RDKit::SmartsToMol(\"[#8]~*~*~[#8]\")),\n        bit_73(RDKit::SmartsToMol(\"[#16]=*\")),\n        bit_74(RDKit::SmartsToMol(\"[CH3]~*~[CH3]\")),\n        bit_75(RDKit::SmartsToMol(\"*!@[#7]@*\")),\n        bit_76(RDKit::SmartsToMol(\"[#6]=[#6](~*)~*\")),\n        bit_77(RDKit::SmartsToMol(\"[#7]~*~[#7]\")),\n        bit_78(RDKit::SmartsToMol(\"[#6]=[#7]\")),\n        bit_79(RDKit::SmartsToMol(\"[#7]~*~*~[#7]\")),\n        bit_80(RDKit::SmartsToMol(\"[#7]~*~*~*~[#7]\")),\n        bit_81(RDKit::SmartsToMol(\"[#16]~*(~*)~*\")),\n        bit_82(RDKit::SmartsToMol(\"*~[CH2]~[!#6!#1!H0]\")),\n        bit_83(RDKit::SmartsToMol(\"[!#6!#1]1~*~*~*~*~1\")),\n        bit_84(RDKit::SmartsToMol(\"[NH2]\")),\n        bit_85(RDKit::SmartsToMol(\"[#6]~[#7](~[#6])~[#6]\")),\n        bit_86(RDKit::SmartsToMol(\"[C;H2,H3][!#6!#1][C;H2,H3]\")),\n        bit_87(RDKit::SmartsToMol(\"[F,Cl,Br,I]!@*@*\")),\n        bit_89(RDKit::SmartsToMol(\"[#8]~*~*~*~[#8]\")),\n        bit_90(RDKit::SmartsToMol(\n            \"[$([!#6!#1!H0]~*~*~[CH2]~*),$([!#6!#1!H0R]1@[R]@[R]@[CH2R]1),$([!#\"\n            \"6!#1!H0]~[R]1@[R]@[CH2R]1)]\")),\n        bit_91(RDKit::SmartsToMol(\n            \"[$([!#6!#1!H0]~*~*~*~[CH2]~*),$([!#6!#1!H0R]1@[R]@[R]@[R]@[CH2R]1)\"\n            \",$([!#6!#1!H0]~[R]1@[R]@[R]@[CH2R]1),$([!#6!#1!H0]~*~[R]1@[R]@[\"\n            \"CH2R]1)]\")),\n        bit_92(RDKit::SmartsToMol(\"[#8]~[#6](~[#7])~[#6]\")),\n        bit_93(RDKit::SmartsToMol(\"[!#6!#1]~[CH3]\")),\n        bit_94(RDKit::SmartsToMol(\"[!#6!#1]~[#7]\")),\n        bit_95(RDKit::SmartsToMol(\"[#7]~*~*~[#8]\")),\n        bit_96(RDKit::SmartsToMol(\"*1~*~*~*~*~1\")),\n        bit_97(RDKit::SmartsToMol(\"[#7]~*~*~*~[#8]\")),\n        bit_98(RDKit::SmartsToMol(\"[!#6!#1]1~*~*~*~*~*~1\")),\n        bit_99(RDKit::SmartsToMol(\"[#6]=[#6]\")),\n        bit_100(RDKit::SmartsToMol(\"*~[CH2]~[#7]\")),\n        bit_101(RDKit::SmartsToMol(\n            \"[$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@\"\n            \"[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]\"\n            \"1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[\"\n            \"R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[\"\n            \"R]@[R]@[R]@[R]@[R]@[R]@1),$([R]1@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[R]@[\"\n            \"R]@[R]@[R]@[R]@[R]@1)]\")),\n        bit_102(RDKit::SmartsToMol(\"[!#6!#1]~[#8]\")),\n        bit_104(RDKit::SmartsToMol(\"[!#6!#1!H0]~*~[CH2]~*\")),\n        bit_105(RDKit::SmartsToMol(\"*@*(@*)@*\")),\n        bit_106(RDKit::SmartsToMol(\"[!#6!#1]~*(~[!#6!#1])~[!#6!#1]\")),\n        bit_107(RDKit::SmartsToMol(\"[F,Cl,Br,I]~*(~*)~*\")),\n        bit_108(RDKit::SmartsToMol(\"[CH3]~*~*~*~[CH2]~*\")),\n        bit_109(RDKit::SmartsToMol(\"*~[CH2]~[#8]\")),\n        bit_110(RDKit::SmartsToMol(\"[#7]~[#6]~[#8]\")),\n        bit_111(RDKit::SmartsToMol(\"[#7]~*~[CH2]~*\")),\n        bit_112(RDKit::SmartsToMol(\"*~*(~*)(~*)~*\")),\n        bit_113(RDKit::SmartsToMol(\"[#8]!:*:*\")),\n        bit_114(RDKit::SmartsToMol(\"[CH3]~[CH2]~*\")),\n        bit_115(RDKit::SmartsToMol(\"[CH3]~*~[CH2]~*\")),\n        bit_116(\n            RDKit::SmartsToMol(\"[$([CH3]~*~*~[CH2]~*),$([CH3]~*1~*~[CH2]1)]\")),\n        bit_117(RDKit::SmartsToMol(\"[#7]~*~[#8]\")),\n        bit_118(RDKit::SmartsToMol(\"[$(*~[CH2]~[CH2]~*),$(*1~[CH2]~[CH2]1)]\")),\n        bit_119(RDKit::SmartsToMol(\"[#7]=*\")),\n        bit_120(RDKit::SmartsToMol(\"[!#6R]\")),\n        bit_121(RDKit::SmartsToMol(\"[#7R]\")),\n        bit_122(RDKit::SmartsToMol(\"*~[#7](~*)~*\")),\n        bit_123(RDKit::SmartsToMol(\"[#8]~[#6]~[#8]\")),\n        bit_124(RDKit::SmartsToMol(\"[!#6!#1]~[!#6!#1]\")),\n        bit_126(RDKit::SmartsToMol(\"*!@[#8]!@*\")),\n        bit_127(RDKit::SmartsToMol(\"*@*!@[#8]\")),\n        bit_128(RDKit::SmartsToMol(\n            \"[$(*~[CH2]~*~*~*~[CH2]~*),$([R]1@[CH2R]@[R]@[R]@[R]@[CH2R]1),$(*~[\"\n            \"CH2]~[R]1@[R]@[R]@[CH2R]1),$(*~[CH2]~*~[R]1@[R]@[CH2R]1)]\")),\n        bit_129(RDKit::SmartsToMol(\n            \"[$(*~[CH2]~*~*~[CH2]~*),$([R]1@[CH2]@[R]@[R]@[CH2R]1),$(*~[CH2]~[\"\n            \"R]1@[R]@[CH2R]1)]\")),\n        bit_131(RDKit::SmartsToMol(\"[!#6!#1!H0]\")),\n        bit_132(RDKit::SmartsToMol(\"[#8]~*~[CH2]~*\")),\n        bit_133(RDKit::SmartsToMol(\"*@*!@[#7]\")),\n        bit_135(RDKit::SmartsToMol(\"[#7]!:*:*\")),\n        bit_136(RDKit::SmartsToMol(\"[#8]=*\")),\n        bit_137(RDKit::SmartsToMol(\"[!C!cR]\")),\n        bit_138(RDKit::SmartsToMol(\"[!#6!#1]~[CH2]~*\")),\n        bit_139(RDKit::SmartsToMol(\"[O!H0]\")),\n        bit_140(RDKit::SmartsToMol(\"[#8]\")),\n        bit_141(RDKit::SmartsToMol(\"[CH3]\")),\n        bit_142(RDKit::SmartsToMol(\"[#7]\")),\n        bit_144(RDKit::SmartsToMol(\"*!:*:*!:*\")),\n        bit_145(RDKit::SmartsToMol(\"*1~*~*~*~*~*~1\")),\n        bit_147(\n            RDKit::SmartsToMol(\"[$(*~[CH2]~[CH2]~*),$([R]1@[CH2R]@[CH2R]1)]\")),\n        bit_148(RDKit::SmartsToMol(\"*~[!#6!#1](~*)~*\")),\n        bit_149(RDKit::SmartsToMol(\"[C;H3,H4]\")),\n        bit_150(RDKit::SmartsToMol(\"*!@*@*!@*\")),\n        bit_151(RDKit::SmartsToMol(\"[#7!H0]\")),\n        bit_152(RDKit::SmartsToMol(\"[#8]~[#6](~[#6])~[#6]\")),\n        bit_154(RDKit::SmartsToMol(\"[#6]=[#8]\")),\n        bit_155(RDKit::SmartsToMol(\"*!@[CH2]!@*\")),\n        bit_156(RDKit::SmartsToMol(\"[#7]~*(~*)~*\")),\n        bit_157(RDKit::SmartsToMol(\"[#6]-[#8]\")),\n        bit_158(RDKit::SmartsToMol(\"[#6]-[#7]\")),\n        bit_162(RDKit::SmartsToMol(\"a\")),\n        bit_165(RDKit::SmartsToMol(\"[R]\")) {}\n};\n\nboost::flyweight<std::vector<Patterns *>, boost::flyweights::no_tracking> gpats;\nvoid GenerateFP(const RDKit::ROMol &mol, ExplicitBitVect &fp) {\n  if (gpats.get().size() == 0) {\n    std::vector<Patterns *> ps;\n    ps.push_back(new Patterns());\n    gpats = ps;\n  }\n  const Patterns &pats = *(gpats.get().front());\n  PRECONDITION(fp.size() == 167, \"bad fingerprint\");\n  fp.clearBits();\n\n  if (!mol.getNumAtoms()) return;\n\n  std::vector<RDKit::MatchVectType> matches;\n  RDKit::RWMol::ConstAtomIterator atom;\n  RDKit::MatchVectType match;\n  unsigned int count;\n\n  for (atom = mol.beginAtoms(); atom != mol.endAtoms(); ++atom)\n    switch ((*atom)->getAtomicNum()) {\n      case 3:\n      case 11:\n      case 19:\n      case 37:\n      case 55:\n      case 87:\n        fp.setBit(35);\n        break;\n      case 4:\n      case 12:\n      case 20:\n      case 38:\n      case 56:\n      case 88:\n        fp.setBit(10);\n        break;\n      case 5:\n      case 13:\n      case 31:\n      case 49:\n      case 81:\n        fp.setBit(18);\n        break;\n      case 9:\n        fp.setBit(42);\n        fp.setBit(134);\n        break;\n      case 15:\n        fp.setBit(29);\n        break;\n      case 16:\n        fp.setBit(88);\n        break;\n      case 17:\n        fp.setBit(103);\n        fp.setBit(134);\n        break;\n      case 21:\n      case 22:\n      case 39:\n      case 40:\n      case 72:\n        fp.setBit(5);\n        break;\n      case 23:\n      case 24:\n      case 25:\n      case 41:\n      case 42:\n      case 43:\n      case 73:\n      case 74:\n      case 75:\n        fp.setBit(7);\n        break;\n      case 26:\n      case 27:\n      case 28:\n      case 44:\n      case 45:\n      case 46:\n      case 76:\n      case 77:\n      case 78:\n        fp.setBit(9);\n        break;\n      case 29:\n      case 30:\n      case 47:\n      case 48:\n      case 79:\n      case 80:\n        fp.setBit(12);\n        break;\n      case 32:\n      case 33:\n      case 34:\n      case 50:\n      case 51:\n      case 52:\n      case 82:\n      case 83:\n      case 84:\n        fp.setBit(3);\n        break;\n      case 35:\n        fp.setBit(46);\n        fp.setBit(134);\n        break;\n      case 53:\n        fp.setBit(27);\n        fp.setBit(134);\n        break;\n      case 57:\n      case 58:\n      case 59:\n      case 60:\n      case 61:\n      case 62:\n      case 63:\n      case 64:\n      case 65:\n      case 66:\n      case 67:\n      case 68:\n      case 69:\n      case 70:\n      case 71:\n        fp.setBit(6);\n        break;\n      case 89:\n      case 90:\n      case 91:\n      case 92:\n      case 93:\n      case 94:\n      case 95:\n      case 96:\n      case 97:\n      case 98:\n      case 99:\n      case 100:\n      case 101:\n      case 102:\n      case 103:\n        fp.setBit(4);\n        break;\n      case 104:\n        fp.setBit(2);\n        break;\n    }\n\n  if (RDKit::SubstructMatch(mol, *pats.bit_8, match, true)) fp.setBit(8);\n  if (RDKit::SubstructMatch(mol, *pats.bit_11, match, true)) fp.setBit(11);\n  if (RDKit::SubstructMatch(mol, *pats.bit_13, match, true)) fp.setBit(13);\n  if (RDKit::SubstructMatch(mol, *pats.bit_14, match, true)) fp.setBit(14);\n  if (RDKit::SubstructMatch(mol, *pats.bit_15, match, true)) fp.setBit(15);\n  if (RDKit::SubstructMatch(mol, *pats.bit_16, match, true)) fp.setBit(16);\n  if (RDKit::SubstructMatch(mol, *pats.bit_17, match, true)) fp.setBit(17);\n  if (RDKit::SubstructMatch(mol, *pats.bit_19, match, true)) fp.setBit(19);\n  if (RDKit::SubstructMatch(mol, *pats.bit_20, match, true)) fp.setBit(20);\n  if (RDKit::SubstructMatch(mol, *pats.bit_21, match, true)) fp.setBit(21);\n  if (RDKit::SubstructMatch(mol, *pats.bit_22, match, true)) fp.setBit(22);\n  if (RDKit::SubstructMatch(mol, *pats.bit_23, match, true)) fp.setBit(23);\n  if (RDKit::SubstructMatch(mol, *pats.bit_24, match, true)) fp.setBit(24);\n  if (RDKit::SubstructMatch(mol, *pats.bit_25, match, true)) fp.setBit(25);\n  if (RDKit::SubstructMatch(mol, *pats.bit_26, match, true)) fp.setBit(26);\n  if (RDKit::SubstructMatch(mol, *pats.bit_28, match, true)) fp.setBit(28);\n  if (RDKit::SubstructMatch(mol, *pats.bit_30, match, true)) fp.setBit(30);\n  if (RDKit::SubstructMatch(mol, *pats.bit_31, match, true)) fp.setBit(31);\n  if (RDKit::SubstructMatch(mol, *pats.bit_32, match, true)) fp.setBit(32);\n  if (RDKit::SubstructMatch(mol, *pats.bit_33, match, true)) fp.setBit(33);\n  if (RDKit::SubstructMatch(mol, *pats.bit_34, match, true)) fp.setBit(34);\n  if (RDKit::SubstructMatch(mol, *pats.bit_36, match, true)) fp.setBit(36);\n  if (RDKit::SubstructMatch(mol, *pats.bit_37, match, true)) fp.setBit(37);\n  if (RDKit::SubstructMatch(mol, *pats.bit_38, match, true)) fp.setBit(38);\n  if (RDKit::SubstructMatch(mol, *pats.bit_39, match, true)) fp.setBit(39);\n  if (RDKit::SubstructMatch(mol, *pats.bit_40, match, true)) fp.setBit(40);\n  if (RDKit::SubstructMatch(mol, *pats.bit_41, match, true)) fp.setBit(41);\n  if (RDKit::SubstructMatch(mol, *pats.bit_43, match, true)) fp.setBit(43);\n  if (RDKit::SubstructMatch(mol, *pats.bit_44, match, true)) fp.setBit(44);\n  if (RDKit::SubstructMatch(mol, *pats.bit_45, match, true)) fp.setBit(45);\n  if (RDKit::SubstructMatch(mol, *pats.bit_47, match, true)) fp.setBit(47);\n  if (RDKit::SubstructMatch(mol, *pats.bit_48, match, true)) fp.setBit(48);\n  if (RDKit::SubstructMatch(mol, *pats.bit_49, match, true)) fp.setBit(49);\n  if (RDKit::SubstructMatch(mol, *pats.bit_50, match, true)) fp.setBit(50);\n  if (RDKit::SubstructMatch(mol, *pats.bit_51, match, true)) fp.setBit(51);\n  if (RDKit::SubstructMatch(mol, *pats.bit_52, match, true)) fp.setBit(52);\n  if (RDKit::SubstructMatch(mol, *pats.bit_53, match, true)) fp.setBit(53);\n  if (RDKit::SubstructMatch(mol, *pats.bit_54, match, true)) fp.setBit(54);\n  if (RDKit::SubstructMatch(mol, *pats.bit_55, match, true)) fp.setBit(55);\n  if (RDKit::SubstructMatch(mol, *pats.bit_56, match, true)) fp.setBit(56);\n  if (RDKit::SubstructMatch(mol, *pats.bit_57, match, true)) fp.setBit(57);\n  if (RDKit::SubstructMatch(mol, *pats.bit_58, match, true)) fp.setBit(58);\n  if (RDKit::SubstructMatch(mol, *pats.bit_59, match, true)) fp.setBit(59);\n  if (RDKit::SubstructMatch(mol, *pats.bit_60, match, true)) fp.setBit(60);\n  if (RDKit::SubstructMatch(mol, *pats.bit_61, match, true)) fp.setBit(61);\n  if (RDKit::SubstructMatch(mol, *pats.bit_62, match, true)) fp.setBit(62);\n  if (RDKit::SubstructMatch(mol, *pats.bit_63, match, true)) fp.setBit(63);\n  if (RDKit::SubstructMatch(mol, *pats.bit_64, match, true)) fp.setBit(64);\n  if (RDKit::SubstructMatch(mol, *pats.bit_65, match, true)) fp.setBit(65);\n  if (RDKit::SubstructMatch(mol, *pats.bit_66, match, true)) fp.setBit(66);\n  if (RDKit::SubstructMatch(mol, *pats.bit_67, match, true)) fp.setBit(67);\n  if (RDKit::SubstructMatch(mol, *pats.bit_68, match, true)) fp.setBit(68);\n  if (RDKit::SubstructMatch(mol, *pats.bit_69, match, true)) fp.setBit(69);\n  if (RDKit::SubstructMatch(mol, *pats.bit_70, match, true)) fp.setBit(70);\n  if (RDKit::SubstructMatch(mol, *pats.bit_71, match, true)) fp.setBit(71);\n  if (RDKit::SubstructMatch(mol, *pats.bit_72, match, true)) fp.setBit(72);\n  if (RDKit::SubstructMatch(mol, *pats.bit_73, match, true)) fp.setBit(73);\n  if (RDKit::SubstructMatch(mol, *pats.bit_74, match, true)) fp.setBit(74);\n  if (RDKit::SubstructMatch(mol, *pats.bit_75, match, true)) fp.setBit(75);\n  if (RDKit::SubstructMatch(mol, *pats.bit_76, match, true)) fp.setBit(76);\n  if (RDKit::SubstructMatch(mol, *pats.bit_77, match, true)) fp.setBit(77);\n  if (RDKit::SubstructMatch(mol, *pats.bit_78, match, true)) fp.setBit(78);\n  if (RDKit::SubstructMatch(mol, *pats.bit_79, match, true)) fp.setBit(79);\n  if (RDKit::SubstructMatch(mol, *pats.bit_80, match, true)) fp.setBit(80);\n  if (RDKit::SubstructMatch(mol, *pats.bit_81, match, true)) fp.setBit(81);\n  if (RDKit::SubstructMatch(mol, *pats.bit_82, match, true)) fp.setBit(82);\n  if (RDKit::SubstructMatch(mol, *pats.bit_83, match, true)) fp.setBit(83);\n  if (RDKit::SubstructMatch(mol, *pats.bit_84, match, true)) fp.setBit(84);\n  if (RDKit::SubstructMatch(mol, *pats.bit_85, match, true)) fp.setBit(85);\n  if (RDKit::SubstructMatch(mol, *pats.bit_86, match, true)) fp.setBit(86);\n  if (RDKit::SubstructMatch(mol, *pats.bit_87, match, true)) fp.setBit(87);\n  if (RDKit::SubstructMatch(mol, *pats.bit_89, match, true)) fp.setBit(89);\n  if (RDKit::SubstructMatch(mol, *pats.bit_90, match, true)) fp.setBit(90);\n  if (RDKit::SubstructMatch(mol, *pats.bit_91, match, true)) fp.setBit(91);\n  if (RDKit::SubstructMatch(mol, *pats.bit_92, match, true)) fp.setBit(92);\n  if (RDKit::SubstructMatch(mol, *pats.bit_93, match, true)) fp.setBit(93);\n  if (RDKit::SubstructMatch(mol, *pats.bit_94, match, true)) fp.setBit(94);\n  if (RDKit::SubstructMatch(mol, *pats.bit_95, match, true)) fp.setBit(95);\n  if (RDKit::SubstructMatch(mol, *pats.bit_96, match, true)) fp.setBit(96);\n  if (RDKit::SubstructMatch(mol, *pats.bit_97, match, true)) fp.setBit(97);\n  if (RDKit::SubstructMatch(mol, *pats.bit_98, match, true)) fp.setBit(98);\n  if (RDKit::SubstructMatch(mol, *pats.bit_99, match, true)) fp.setBit(99);\n  if (RDKit::SubstructMatch(mol, *pats.bit_100, match, true)) fp.setBit(100);\n  if (RDKit::SubstructMatch(mol, *pats.bit_101, match, true)) fp.setBit(101);\n  if (RDKit::SubstructMatch(mol, *pats.bit_102, match, true)) fp.setBit(102);\n  if (RDKit::SubstructMatch(mol, *pats.bit_104, match, true)) fp.setBit(104);\n  if (RDKit::SubstructMatch(mol, *pats.bit_105, match, true)) fp.setBit(105);\n  if (RDKit::SubstructMatch(mol, *pats.bit_106, match, true)) fp.setBit(106);\n  if (RDKit::SubstructMatch(mol, *pats.bit_107, match, true)) fp.setBit(107);\n  if (RDKit::SubstructMatch(mol, *pats.bit_108, match, true)) fp.setBit(108);\n  if (RDKit::SubstructMatch(mol, *pats.bit_109, match, true)) fp.setBit(109);\n  if (RDKit::SubstructMatch(mol, *pats.bit_110, match, true)) fp.setBit(110);\n  if (RDKit::SubstructMatch(mol, *pats.bit_111, match, true)) fp.setBit(111);\n  if (RDKit::SubstructMatch(mol, *pats.bit_112, match, true)) fp.setBit(112);\n  if (RDKit::SubstructMatch(mol, *pats.bit_113, match, true)) fp.setBit(113);\n  if (RDKit::SubstructMatch(mol, *pats.bit_114, match, true)) fp.setBit(114);\n  if (RDKit::SubstructMatch(mol, *pats.bit_115, match, true)) fp.setBit(115);\n  if (RDKit::SubstructMatch(mol, *pats.bit_116, match, true)) fp.setBit(116);\n  if (RDKit::SubstructMatch(mol, *pats.bit_117, match, true)) fp.setBit(117);\n  if (RDKit::SubstructMatch(mol, *pats.bit_118, matches, true, true) > 1)\n    fp.setBit(118);\n  if (RDKit::SubstructMatch(mol, *pats.bit_119, match, true)) fp.setBit(119);\n  if (RDKit::SubstructMatch(mol, *pats.bit_120, matches, true, true) > 1)\n    fp.setBit(120);\n  if (RDKit::SubstructMatch(mol, *pats.bit_121, match, true)) fp.setBit(121);\n  if (RDKit::SubstructMatch(mol, *pats.bit_122, match, true)) fp.setBit(122);\n  if (RDKit::SubstructMatch(mol, *pats.bit_123, match, true)) fp.setBit(123);\n  count = RDKit::SubstructMatch(mol, *pats.bit_124, matches, true, true);\n  if (count > 0) fp.setBit(124);\n  if (count > 1) fp.setBit(130);\n  if (RDKit::SubstructMatch(mol, *pats.bit_126, match, true)) fp.setBit(126);\n  count = RDKit::SubstructMatch(mol, *pats.bit_127, matches, true, true);\n  if (count > 1) fp.setBit(127);\n  if (count > 0) fp.setBit(143);\n  if (RDKit::SubstructMatch(mol, *pats.bit_128, match, true)) fp.setBit(128);\n  if (RDKit::SubstructMatch(mol, *pats.bit_129, match, true)) fp.setBit(129);\n  if (RDKit::SubstructMatch(mol, *pats.bit_131, matches, true, true) > 1)\n    fp.setBit(131);\n  if (RDKit::SubstructMatch(mol, *pats.bit_132, match, true)) fp.setBit(132);\n  if (RDKit::SubstructMatch(mol, *pats.bit_133, match, true)) fp.setBit(133);\n  if (RDKit::SubstructMatch(mol, *pats.bit_135, match, true)) fp.setBit(135);\n  if (RDKit::SubstructMatch(mol, *pats.bit_136, matches, true, true) > 1)\n    fp.setBit(136);\n  if (RDKit::SubstructMatch(mol, *pats.bit_137, match, true)) fp.setBit(137);\n  count = RDKit::SubstructMatch(mol, *pats.bit_138, matches, true, true);\n  if (count > 1) fp.setBit(138);\n  if (count > 0) fp.setBit(153);\n  if (RDKit::SubstructMatch(mol, *pats.bit_139, match, true)) fp.setBit(139);\n  count = RDKit::SubstructMatch(mol, *pats.bit_140, matches, true, true);\n  if (count > 3) fp.setBit(140);\n  if (count > 2) fp.setBit(146);\n  if (count > 1) fp.setBit(159);\n  if (count > 0) fp.setBit(164);\n  if (RDKit::SubstructMatch(mol, *pats.bit_141, matches, true, true) > 2)\n    fp.setBit(141);\n  count = RDKit::SubstructMatch(mol, *pats.bit_142, matches, true, true);\n  if (count > 1) fp.setBit(142);\n  if (count > 0) fp.setBit(161);\n  if (RDKit::SubstructMatch(mol, *pats.bit_144, match, true)) fp.setBit(144);\n  count = RDKit::SubstructMatch(mol, *pats.bit_145, matches, true, true);\n  if (count > 1) fp.setBit(145);\n  if (count > 0) fp.setBit(163);\n  if (RDKit::SubstructMatch(mol, *pats.bit_147, match, true)) fp.setBit(147);\n  if (RDKit::SubstructMatch(mol, *pats.bit_148, match, true)) fp.setBit(148);\n  count = RDKit::SubstructMatch(mol, *pats.bit_149, matches, true, true);\n  if (count > 1) fp.setBit(149);\n  if (count > 0) fp.setBit(160);\n  if (RDKit::SubstructMatch(mol, *pats.bit_150, match, true)) fp.setBit(150);\n  if (RDKit::SubstructMatch(mol, *pats.bit_151, match, true)) fp.setBit(151);\n  if (RDKit::SubstructMatch(mol, *pats.bit_152, match, true)) fp.setBit(152);\n  if (RDKit::SubstructMatch(mol, *pats.bit_154, match, true)) fp.setBit(154);\n  if (RDKit::SubstructMatch(mol, *pats.bit_155, match, true)) fp.setBit(155);\n  if (RDKit::SubstructMatch(mol, *pats.bit_156, match, true)) fp.setBit(156);\n  if (RDKit::SubstructMatch(mol, *pats.bit_157, match, true)) fp.setBit(157);\n  if (RDKit::SubstructMatch(mol, *pats.bit_158, match, true)) fp.setBit(158);\n  if (RDKit::SubstructMatch(mol, *pats.bit_162, match, true)) fp.setBit(162);\n  if (RDKit::SubstructMatch(mol, *pats.bit_165, match, true)) fp.setBit(165);\n\n  /* BIT 125 */\n  RDKit::RingInfo *info = mol.getRingInfo();\n  unsigned int ringcount = info->numRings();\n  unsigned int nArom = 0;\n  for (unsigned int i = 0; i < ringcount; i++) {\n    bool isArom = true;\n    const std::vector<int> *ring = &info->bondRings()[i];\n    std::vector<int>::const_iterator iter;\n    for (iter = ring->begin(); iter != ring->end(); ++iter)\n      if (!mol.getBondWithIdx(*iter)->getIsAromatic()) {\n        isArom = false;\n        break;\n      }\n    if (isArom) {\n      if (nArom) {\n        fp.setBit(125);\n        break;\n      } else\n        nArom++;\n    }\n  }\n\n  /* BIT 166 */\n  std::vector<int> mapping;\n  if (RDKit::MolOps::getMolFrags(mol, mapping) > 1) fp.setBit(166);\n}\n}  // end of local anonymous namespace\n\nnamespace RDKit {\nnamespace MACCSFingerprints {\nExplicitBitVect *getFingerprintAsBitVect(const ROMol &mol) {\n  ExplicitBitVect *fp = new ExplicitBitVect(167);\n  GenerateFP(mol, *fp);\n  return fp;\n}\n}\n}\n", "meta": {"hexsha": "3a34cfeed871c879c556327154c627a605ed2966", "size": 27200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Fingerprints/MACCS.cpp", "max_stars_repo_name": "docking-org/rdk", "max_stars_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_stars_repo_licenses": ["PostgreSQL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/GraphMol/Fingerprints/MACCS.cpp", "max_issues_repo_name": "docking-org/rdk", "max_issues_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/GraphMol/Fingerprints/MACCS.cpp", "max_forks_repo_name": "docking-org/rdk", "max_forks_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-04T02:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T01:18:46.000Z", "avg_line_length": 40.9638554217, "max_line_length": 80, "alphanum_fraction": 0.5879044118, "num_tokens": 11176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683200276421697, "lm_q2_score": 0.01495708546798522, "lm_q1q2_score": 0.0038414582162582095}}
{"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 \"UnitFactory.hpp\"\r\n\r\n#include \"ScaleFactory.hpp\"\r\n#include \"QuantityRegex.hpp\"\r\n#include \"SIUnit.hpp\"\r\n#include \"SIUnit_Impl.hpp\"\r\n#include \"IPUnit.hpp\"\r\n#include \"IPUnit_Impl.hpp\"\r\n#include \"BTUUnit.hpp\"\r\n#include \"BTUUnit_Impl.hpp\"\r\n#include \"CFMUnit.hpp\"\r\n#include \"CFMUnit_Impl.hpp\"\r\n#include \"GPDUnit.hpp\"\r\n#include \"GPDUnit_Impl.hpp\"\r\n#include \"MPHUnit.hpp\"\r\n#include \"MPHUnit_Impl.hpp\"\r\n#include \"WhUnit.hpp\"\r\n#include \"WhUnit_Impl.hpp\"\r\n#include \"ThermUnit.hpp\"\r\n#include \"ThermUnit_Impl.hpp\"\r\n#include \"Misc1Unit.hpp\"\r\n#include \"Misc1Unit_Impl.hpp\"\r\n#include \"CelsiusUnit.hpp\"\r\n#include \"CelsiusUnit_Impl.hpp\"\r\n#include \"FahrenheitUnit.hpp\"\r\n#include \"FahrenheitUnit_Impl.hpp\"\r\n\r\n#include \"../core/Exception.hpp\"\r\n#include \"../core/Containers.hpp\"\r\n#include \"../core/Assert.hpp\"\r\n\r\n#include <boost/pointer_cast.hpp>\r\n\r\n#include <map>\r\n#include <vector>\r\n\r\nnamespace openstudio{\r\n\r\nbool UnitFactorySingleton::registerUnit(CreateUnitCallback createFn,UnitSystem system) {\r\n\r\n  Unit thisUnit = createFn();\r\n  std::string standardString = thisUnit.standardString(false);\r\n  std::string prettyString = thisUnit.prettyString(false);\r\n\r\n  StandardStringCallbackMap::value_type callbackMapEntry(standardString,createFn);\r\n\r\n  // register the callback in main map\r\n  bool result = m_callbackMaps[UnitSystem(UnitSystem::Mixed)].insert(callbackMapEntry).second;\r\n  // already registered--recover if possible\r\n  if (!result) {\r\n    std::stringstream message;\r\n    message << \"A callback function for \" << standardString << \" is already registered\"\r\n            << \" and there is not enough information to resolve the conflict. \"\r\n            << \"Note that C and F are assumed to not conflict--all other units use K and R.\";\r\n    // mask registry in main map, save in case need to reconstitute\r\n    m_callbackMaps[UnitSystem(UnitSystem::Mixed)][standardString] = 0;\r\n\r\n    // make sure string registered elsewhere\r\n    bool found(false);\r\n    for (const auto & callbackMap : m_callbackMaps)\r\n    {\r\n      if ((callbackMap.first == UnitSystem::Mixed) || (callbackMap.first == system)) {\r\n        continue;\r\n      }\r\n      auto lookupPair = callbackMap.second.find(standardString);\r\n      if (lookupPair != callbackMap.second.end()) {\r\n        found = true;\r\n        break;\r\n      }\r\n    }\r\n\r\n    if (!found) {\r\n      LOG_AND_THROW(message.str());\r\n    }\r\n\r\n  } // if already registered in m_callbackMap\r\n\r\n  // register the callback in system-specific map\r\n  result = m_callbackMaps[system].insert(callbackMapEntry).second;\r\n  if (!result && (system != UnitSystem::Mixed)) {\r\n    return result;\r\n  }\r\n\r\n  // register standardString as a pseudonym for itself\r\n  registerEquivalentString(standardString,standardString);\r\n\r\n  // register prettyString if applicable\r\n  if (prettyString != \"\") {\r\n\r\n    // get prettyString from standardString\r\n    m_prettyStringLookupMap.insert(PrettyStringLookupMap::value_type(standardString,prettyString));\r\n\r\n    // get standardString from prettyString\r\n    registerEquivalentString(prettyString,standardString);\r\n\r\n    // be able to print things like 1/J\r\n    Unit clonedUnit = thisUnit.clone();\r\n    clonedUnit.setPrettyString(\"\");\r\n    std::string tempPrettyString = boost::regex_replace(prettyString,\r\n                                                        boost::regex(\"person\"),\r\n                                                        \"people\");\r\n    Unit prettyUnit = parseUnitString(tempPrettyString);\r\n    clonedUnit.pow(-1,1,false); std::string clonedUnitString = clonedUnit.standardString(false);\r\n    prettyUnit.pow(-1,1,false); std::string prettyUnitString = prettyUnit.standardString(false);\r\n    m_prettyStringLookupMap.insert(\r\n          PrettyStringLookupMap::value_type(clonedUnitString,prettyUnitString));\r\n  }\r\n\r\n  return result;\r\n}\r\n\r\nbool UnitFactorySingleton::registerEquivalentString(const std::string& equivalentString,\r\n                                                    const std::string& standardString) {\r\n  // register the pair\r\n  bool result = m_standardStringLookupMap.insert(\r\n      StandardStringLookupMap::value_type(equivalentString,StringVector(1u,standardString))).second;\r\n\r\n  if (!result) {\r\n    // equivalentString is already a key. add this one\r\n    m_standardStringLookupMap[equivalentString].push_back(standardString);\r\n  }\r\n\r\n  return result;\r\n}\r\n\r\nboost::optional<Unit> UnitFactorySingleton::createUnit(const std::string& unitString,\r\n                                                       UnitSystem system) const\r\n{\r\n  if (m_callbackMaps.size() == 0) {\r\n    LOG(Warn,\"UnitFactorySingleton::createUnit called, but the maps appear to be empty.\");\r\n  }\r\n\r\n  std::string resultCacheKey = unitString + \" in unit system \" + system.valueName();\r\n  ResultCacheMap::const_iterator findIt = m_resultCacheMap.find(resultCacheKey);\r\n  if (findIt != m_resultCacheMap.end()){\r\n    return findIt->second;\r\n  }\r\n\r\n  if (!unitString.empty() && !isUnit(unitString)) {\r\n    LOG(Error,unitString << \" is not properly formatted.\");\r\n    m_resultCacheMap[resultCacheKey] = boost::none;\r\n    return boost::none;\r\n  }\r\n\r\n  OptionalUnit result = createUnitSimple(unitString,system);\r\n  if (result) {\r\n    m_resultCacheMap[resultCacheKey] = result;\r\n    return *result;\r\n  }\r\n\r\n  // no luck--start parsing\r\n  std::string wUnitString(unitString);\r\n  ScaleConstant scale = ScaleFactory::instance().createScale(0);\r\n\r\n  if (isScaledUnit(wUnitString)) {\r\n    std::pair<std::string,std::string> scaleAndUnit = decomposeScaledUnitString(wUnitString);\r\n    scale = ScaleFactory::instance().createScale(scaleAndUnit.first);\r\n    if (scale().value == 0.0) {\r\n      LOG(Error,\"Scaled unit string \" << wUnitString << \" uses invalid scale abbreviation \"\r\n          << scaleAndUnit.first << \".\");\r\n      m_resultCacheMap[resultCacheKey] = boost::none;\r\n      return boost::none;\r\n    }\r\n    wUnitString = scaleAndUnit.second;\r\n  }\r\n\r\n  // wUnitString should now be compound unit\r\n  std::pair< std::vector<std::string>,std::vector<std::string> > atomicUnits =\r\n      decomposeCompoundUnitString(wUnitString);\r\n  // loop through numerator\r\n  std::vector<std::string>::const_iterator atomicUnitIter;\r\n  std::vector<std::string>::const_iterator vectorEnd = atomicUnits.first.end();\r\n  std::pair<std::string,int> atomicUnit;\r\n  for (atomicUnitIter = atomicUnits.first.begin(); atomicUnitIter != vectorEnd; ++atomicUnitIter) {\r\n    // decompose into baseUnit and exponent\r\n    atomicUnit = decomposeAtomicUnitString(*atomicUnitIter);\r\n    // look for baseUnit\r\n    OptionalUnit baseUnit = createUnitSimple(atomicUnit.first,system);\r\n    if (!baseUnit) {\r\n      // decompose into scale, baseUnit\r\n      std::pair<std::string,std::string> scaleAndBaseUnit = extractScaleAbbreviation(atomicUnit.first);\r\n      if (!scaleAndBaseUnit.first.empty()) {\r\n        baseUnit = createUnitSimple(scaleAndBaseUnit.second,system);\r\n        if (!baseUnit) {\r\n          baseUnit = Unit();\r\n          baseUnit->setBaseUnitExponent(scaleAndBaseUnit.second,1);\r\n        }\r\n        baseUnit->setScale(scaleAndBaseUnit.first);\r\n      }\r\n      else {\r\n        baseUnit = Unit();\r\n        baseUnit->setBaseUnitExponent(atomicUnit.first,1);\r\n      }\r\n    }\r\n    baseUnit->pow(atomicUnit.second);\r\n    if (!result) {\r\n      result = baseUnit;\r\n    }\r\n    else {\r\n      result = (*result) * (*baseUnit);\r\n    }\r\n  }\r\n  // loop through denominator\r\n  vectorEnd = atomicUnits.second.end();\r\n  for (atomicUnitIter = atomicUnits.second.begin(); atomicUnitIter != vectorEnd; ++atomicUnitIter) {\r\n    // decompose into baseUnit and exponent\r\n    atomicUnit = decomposeAtomicUnitString(*atomicUnitIter);\r\n    // look for baseUnit\r\n    OptionalUnit baseUnit = createUnitSimple(atomicUnit.first,system);\r\n    if (!baseUnit) {\r\n      // decompose into scale, baseUnit\r\n      std::pair<std::string,std::string> scaleAndBaseUnit = extractScaleAbbreviation(atomicUnit.first);\r\n      if (!scaleAndBaseUnit.first.empty()) {\r\n        baseUnit = createUnitSimple(scaleAndBaseUnit.second,system);\r\n        if (!baseUnit) {\r\n          LOG(Info,scaleAndBaseUnit.second << \" is not a registered baseUnit (in the selected system). \"\r\n              << \"Returning it as-is in a mixed Unit (not SI, IP, etc.).\");\r\n          baseUnit = Unit();\r\n          baseUnit->setBaseUnitExponent(scaleAndBaseUnit.second,1);\r\n        }\r\n        baseUnit->setScale(scaleAndBaseUnit.first);\r\n      }\r\n      else {\r\n        LOG(Info,scaleAndBaseUnit.second << \" is not a registered baseUnit (in the selected system). \"\r\n              << \"Returning it as-is in a mixed Unit (not SI, IP, etc.).\");\r\n        baseUnit = Unit();\r\n        baseUnit->setBaseUnitExponent(atomicUnit.first,1);\r\n      }\r\n    }\r\n    baseUnit->pow(atomicUnit.second);\r\n    if (!result) {\r\n      baseUnit->pow(-1);\r\n      result = baseUnit;\r\n    }\r\n    else {\r\n      result = (*result) / (*baseUnit);\r\n    }\r\n  }\r\n\r\n  OS_ASSERT(result);\r\n\r\n  // impose overall scale\r\n  if (scale().exponent != 0) {\r\n    ScaleOpReturnType resultScale = scale()*result->scale();\r\n    result->setScale(resultScale.first().exponent);\r\n  }\r\n\r\n  m_resultCacheMap[resultCacheKey] = result;\r\n  return result;\r\n}\r\n\r\nboost::optional<Unit> UnitFactorySingleton::createUnitSimple(const std::string& unitString,\r\n                                                             UnitSystem system) const\r\n{\r\n  if (unitString.empty()) {\r\n    Unit result = createDimensionlessUnit(system);\r\n    if (OptionalTemperatureUnit T = result.optionalCast<TemperatureUnit>()) {\r\n      T->setAsRelative();\r\n    }\r\n    return result;\r\n  }\r\n\r\n  OptionalUnit candidate;\r\n  StandardStringLookupMap::const_iterator lookupPair;\r\n  auto standardStringMapEnd = m_standardStringLookupMap.end();\r\n  lookupPair = m_standardStringLookupMap.find(unitString);\r\n  if (lookupPair != standardStringMapEnd) {\r\n\r\n    // unitString is registered\r\n    for (const std::string& standardString : lookupPair->second) {\r\n\r\n      // instantiate the standardString\r\n      CallbackMapMap::const_iterator callbackMap;\r\n      StandardStringCallbackMap::const_iterator callbackPair;\r\n      OptionalUnit temp;\r\n      // try base map\r\n      callbackMap = m_callbackMaps.find(UnitSystem(UnitSystem::Mixed));\r\n      OS_ASSERT(callbackMap != m_callbackMaps.end());\r\n      callbackPair = callbackMap->second.find(standardString);\r\n      if ((callbackPair != callbackMap->second.end()) && (callbackPair->second != NULL)) {\r\n        temp = callbackPair->second();\r\n      }\r\n      else {\r\n        // try system map\r\n        callbackMap = m_callbackMaps.find(system);\r\n        if (callbackMap != m_callbackMaps.end()) {\r\n          callbackPair = callbackMap->second.find(standardString);\r\n          if ((callbackPair != callbackMap->second.end()) && (callbackPair->second != NULL)) {\r\n            temp = callbackPair->second();\r\n          }\r\n        }\r\n\r\n        // try all other maps\r\n        if (!temp) {\r\n          for (int sysValue : UnitSystem::getValues()) {\r\n            UnitSystem tempSystem(sysValue);\r\n            if ((tempSystem == UnitSystem::Mixed) || (tempSystem == system)) {\r\n              continue;\r\n            }\r\n            callbackMap = m_callbackMaps.find(tempSystem);\r\n            if (callbackMap != m_callbackMaps.end()) {\r\n              callbackPair = callbackMap->second.find(standardString);\r\n              if ((callbackPair != callbackMap->second.end()) && (callbackPair->second != NULL)) {\r\n                temp = callbackPair->second();\r\n                break;\r\n              }\r\n            }\r\n          }\r\n        }\r\n      }\r\n\r\n      OS_ASSERT(temp);\r\n\r\n      // decide whether to keep temp\r\n      if (!candidate || (temp->system() == system)) {\r\n        candidate = temp;\r\n      }\r\n\r\n      // decide whether to keep looking\r\n      if ((candidate->system() == system) || (system == UnitSystem::Mixed)) {\r\n        break;\r\n      }\r\n\r\n    } // foreach\r\n\r\n  } // if\r\n\r\n  return candidate;\r\n}\r\n\r\nstd::string UnitFactorySingleton::lookupPrettyString(const std::string& standardString) const {\r\n\r\n  PrettyStringLookupMap::const_iterator lookupPair;\r\n  lookupPair = m_prettyStringLookupMap.find(standardString);\r\n  if (lookupPair == m_prettyStringLookupMap.end()) {\r\n    return \"\";\r\n  }\r\n  else {\r\n    return lookupPair->second;\r\n  }\r\n\r\n}\r\n\r\nUnitFactorySingleton::UnitFactorySingleton() {\r\n\r\n  // Celsius Base Units ========================================================\r\n  registerUnit(createCelsiusTemperature);\r\n\r\n\r\n  // Fahrenheit Base Units =====================================================\r\n  registerUnit(createFahrenheitTemperature);\r\n\r\n\r\n  // SI Base Units =============================================================\r\n  registerUnit(createSIMass);\r\n  registerUnit(createSILength,UnitSystem::SI);\r\n  registerUnit(createSITime,UnitSystem::SI);\r\n  registerUnit(createSITemperature,UnitSystem::SI);\r\n  registerUnit(createSIElectricCurrent,UnitSystem::SI);\r\n  registerUnit(createSILuminousIntensity,UnitSystem::SI);\r\n  registerUnit(createSIAmountOfSubstance,UnitSystem::SI);\r\n  registerUnit(createSIAngle,UnitSystem::SI);\r\n  registerUnit(createSISolidAngle,UnitSystem::SI);\r\n  registerUnit(createSIPeople,UnitSystem::SI);\r\n  registerUnit(createSICycle,UnitSystem::SI);\r\n\r\n  // SI Derived Units ==========================================================\r\n  registerUnit(createSIForce);\r\n  registerUnit(createSIEnergy);\r\n  registerUnit(createSIPower);\r\n  registerUnit(createSIElectricCharge,UnitSystem::SI);\r\n  registerUnit(createSIElectricalPotential,UnitSystem::SI);\r\n  registerUnit(createSIElectricCapacitance);\r\n  registerUnit(createSIElectricResistance);\r\n  registerUnit(createSIMagneticFlux);\r\n  registerUnit(createSIMagneticFieldStrength);\r\n  registerUnit(createSIInductance);\r\n  registerUnit(createSILuminousFlux,UnitSystem::SI);\r\n  registerUnit(createSIIlluminance,UnitSystem::SI);\r\n  registerUnit(createSIFrequency,UnitSystem::SI);\r\n\r\n  // SI Common Compound Units ==================================================\r\n  registerUnit(createSIEnergyUseIntensity);\r\n  registerUnit(createSIPowerDensity,UnitSystem::SI);\r\n  registerUnit(createSIPowerPerPerson,UnitSystem::SI);\r\n  registerUnit(createSIPressure);\r\n  registerUnit(createSIThermalConductance);\r\n  registerUnit(createSIThermalResistance);\r\n  registerUnit(createSIHeatCapacity);\r\n\r\n\r\n  // IP Base Units =============================================================\r\n  registerUnit(createIPMass);\r\n  registerUnit(createIPLength,UnitSystem::IP);\r\n  registerUnit(createIPTime,UnitSystem::IP);\r\n  registerUnit(createIPTemperature,UnitSystem::IP);\r\n  registerUnit(createIPElectricCurrent,UnitSystem::IP);\r\n  registerUnit(createIPLuminousIntensity,UnitSystem::IP);\r\n  registerUnit(createIPAmountOfSubstance,UnitSystem::IP);\r\n  registerUnit(createIPAngle,UnitSystem::IP);\r\n  registerUnit(createIPSolidAngle,UnitSystem::IP);\r\n  registerUnit(createIPPeople,UnitSystem::IP);\r\n  registerUnit(createIPCycle,UnitSystem::IP);\r\n\r\n  // IP Derived Units ==========================================================\r\n  registerUnit(createIPForce);\r\n  registerUnit(createIPEnergy); // ft*lb-f\r\n  registerUnit(createIPPower); // ft*lb-f/s\r\n  registerUnit(createIPElectricCharge,UnitSystem::IP);\r\n  registerUnit(createIPLuminousFlux,UnitSystem::IP);\r\n  registerUnit(createIPIlluminance,UnitSystem::IP);\r\n  registerUnit(createIPFrequency,UnitSystem::IP);\r\n\r\n\r\n  // BTU Base Units ============================================================\r\n  registerUnit(createBTUEnergy);\r\n  registerUnit(createBTULength,UnitSystem::BTU);\r\n  registerUnit(createBTUTime,UnitSystem::BTU);\r\n  registerUnit(createBTUTemperature,UnitSystem::BTU);\r\n  registerUnit(createBTUElectricCurrent,UnitSystem::BTU);\r\n  registerUnit(createBTULuminousIntensity,UnitSystem::BTU);\r\n  registerUnit(createBTUAmountOfSubstance,UnitSystem::BTU);\r\n  registerUnit(createBTUAngle,UnitSystem::BTU);\r\n  registerUnit(createBTUSolidAngle,UnitSystem::BTU);\r\n  registerUnit(createBTUPeople,UnitSystem::BTU);\r\n  registerUnit(createBTUCycle,UnitSystem::BTU);\r\n\r\n  // BTU Derived Units =========================================================\r\n  registerUnit(createBTUPower);\r\n  registerUnit(createBTULuminousFlux,UnitSystem::BTU);\r\n  registerUnit(createBTUIlluminance,UnitSystem::BTU);\r\n\r\n\r\n  // CFM Base Units ============================================================\r\n  registerUnit(createCFMLength,UnitSystem::CFM);\r\n  registerUnit(createCFMTime);\r\n  registerUnit(createCFMPower);\r\n  registerUnit(createCFMTemperature,UnitSystem::CFM);\r\n  registerUnit(createCFMElectricCurrent,UnitSystem::CFM);\r\n  registerUnit(createCFMLuminousIntensity,UnitSystem::CFM);\r\n  registerUnit(createCFMAmountOfSubstance,UnitSystem::CFM);\r\n  registerUnit(createCFMAngle,UnitSystem::CFM);\r\n  registerUnit(createCFMSolidAngle,UnitSystem::CFM);\r\n  registerUnit(createCFMPeople,UnitSystem::CFM);\r\n  registerUnit(createCFMCycle,UnitSystem::CFM);\r\n\r\n  // CFM Derived Units =========================================================\r\n  registerUnit(createCFMVolumetricFlowrate);\r\n  registerUnit(createCFMLuminousFlux,UnitSystem::CFM);\r\n  registerUnit(createCFMIlluminance,UnitSystem::CFM);\r\n  registerUnit(createCFMFrequency);\r\n\r\n\r\n  // GPD Base Units ============================================================\r\n  registerUnit(createGPDPressure);\r\n  registerUnit(createGPDLength);\r\n  registerUnit(createGPDTime,UnitSystem::GPD);\r\n  registerUnit(createGPDTemperature,UnitSystem::GPD);\r\n  registerUnit(createGPDElectricCurrent,UnitSystem::GPD);\r\n  registerUnit(createGPDLuminousIntensity,UnitSystem::GPD);\r\n  registerUnit(createGPDAmountOfSubstance,UnitSystem::GPD);\r\n  registerUnit(createGPDAngle,UnitSystem::GPD);\r\n  registerUnit(createGPDSolidAngle,UnitSystem::GPD);\r\n  registerUnit(createGPDPeople,UnitSystem::GPD);\r\n  registerUnit(createGPDCycle,UnitSystem::GPD);\r\n\r\n  // GPD Derived Units =========================================================\r\n  registerUnit(createGPDVolume);\r\n  registerUnit(createGPDVolumetricFlowrate);\r\n  registerUnit(createGPDLuminousFlux,UnitSystem::GPD);\r\n\r\n\r\n  // MPH Base Units ============================================================\r\n  registerUnit(createMPHPressure);\r\n  registerUnit(createMPHLength);\r\n  registerUnit(createMPHTime,UnitSystem::MPH);\r\n  registerUnit(createMPHTemperature,UnitSystem::MPH);\r\n  registerUnit(createMPHElectricCurrent,UnitSystem::MPH);\r\n  registerUnit(createMPHLuminousIntensity,UnitSystem::MPH);\r\n  registerUnit(createMPHAmountOfSubstance,UnitSystem::MPH);\r\n  registerUnit(createMPHAngle,UnitSystem::MPH);\r\n  registerUnit(createMPHSolidAngle,UnitSystem::MPH);\r\n  registerUnit(createMPHPeople,UnitSystem::MPH);\r\n  registerUnit(createMPHCycle,UnitSystem::MPH);\r\n\r\n  // MPH Derived Units =========================================================\r\n  registerUnit(createMPHVelocity);\r\n  registerUnit(createMPHLuminousFlux,UnitSystem::MPH);\r\n\r\n\r\n  // Wh Base Units =============================================================\r\n  registerUnit(createWhPower);\r\n  registerUnit(createWhTime,UnitSystem::Wh);\r\n  registerUnit(createWhLength,UnitSystem::Wh);\r\n  registerUnit(createWhTemperature,UnitSystem::Wh);\r\n  registerUnit(createWhElectricCurrent,UnitSystem::Wh);\r\n  registerUnit(createWhLuminousIntensity,UnitSystem::Wh);\r\n  registerUnit(createWhAmountOfSubstance,UnitSystem::Wh);\r\n  registerUnit(createWhAngle,UnitSystem::Wh);\r\n  registerUnit(createWhSolidAngle,UnitSystem::Wh);\r\n  registerUnit(createWhPeople,UnitSystem::Wh);\r\n  registerUnit(createWhCycle,UnitSystem::Wh);\r\n\r\n  // Wh Derived Units ==========================================================\r\n  registerUnit(createWhEnergy);\r\n  registerUnit(createWhElectricalPotential,UnitSystem::Wh);\r\n  registerUnit(createWhLuminousFlux,UnitSystem::Wh);\r\n  registerUnit(createWhIlluminance,UnitSystem::Wh);\r\n\r\n\r\n  // Therm Base Units ==========================================================\r\n  registerUnit(createThermEnergy);\r\n  registerUnit(createThermLength);\r\n  registerUnit(createThermTime);\r\n  registerUnit(createThermTemperature,UnitSystem::Therm);\r\n  registerUnit(createThermElectricCurrent,UnitSystem::Therm);\r\n  registerUnit(createThermLuminousIntensity,UnitSystem::Therm);\r\n  registerUnit(createThermAmountOfSubstance,UnitSystem::Therm);\r\n  registerUnit(createThermAngle,UnitSystem::Therm);\r\n  registerUnit(createThermSolidAngle,UnitSystem::Therm);\r\n  registerUnit(createThermPeople,UnitSystem::Therm);\r\n  registerUnit(createThermCycle,UnitSystem::Therm);\r\n\r\n  // Therm Derived Units =======================================================\r\n  registerUnit(createThermLuminousFlux,UnitSystem::Therm);\r\n\r\n\r\n  // Misc1 Base Units ==========================================================\r\n  registerUnit(createMisc1Pressure);\r\n  registerUnit(createMisc1Length);\r\n  registerUnit(createMisc1Time,UnitSystem::Misc1);\r\n  registerUnit(createMisc1Temperature,UnitSystem::Misc1);\r\n  registerUnit(createMisc1ElectricCurrent,UnitSystem::Misc1);\r\n  registerUnit(createMisc1LuminousIntensity,UnitSystem::Misc1);\r\n  registerUnit(createMisc1AmountOfSubstance,UnitSystem::Misc1);\r\n  registerUnit(createMisc1Angle,UnitSystem::Misc1);\r\n  registerUnit(createMisc1SolidAngle,UnitSystem::Misc1);\r\n  registerUnit(createMisc1People,UnitSystem::Misc1);\r\n  registerUnit(createMisc1Cycle,UnitSystem::Misc1);\r\n\r\n  // Misc1 Derived Units =======================================================\r\n  registerUnit(createMisc1Volume);\r\n  registerUnit(createMisc1LuminousFlux,UnitSystem::Misc1);\r\n\r\n  // Mixed Derived Units =======================================================\r\n  registerUnit(createIPPowerDensity);\r\n  registerUnit(createIPPressure);\r\n\r\n  // Equivalent Strings ========================================================\r\n  registerEquivalentString(\"person\",\"people\");\r\n  registerEquivalentString(\"cycles\",\"cycle\");\r\n  registerEquivalentString(\"lb\",\"lb_m\");\r\n  registerEquivalentString(\"CFM\",\"ft^3/min\");\r\n  registerEquivalentString(\"Therm\",\"therm\");\r\n  registerEquivalentString(\"thm\",\"therm\");\r\n  registerEquivalentString(\"mile\",\"mi\");\r\n  registerEquivalentString(\"miles\",\"mi\");\r\n  registerEquivalentString(\"days\",\"day\");\r\n  registerEquivalentString(\"year\",\"yr\");\r\n  registerEquivalentString(\"years\",\"yr\");\r\n  registerEquivalentString(\"hr\",\"h\");\r\n  registerEquivalentString(\"hrs\",\"h\");\r\n}\r\n\r\nUnitSystem getSystem(const std::string& unitString) {\r\n\r\n  OptionalUnit unit;\r\n\r\n  // pick up preferred unit system for strings like \"C\" and \"F\"\r\n  unit = createUnit(unitString,UnitSystem::Mixed);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::SI);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::IP);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::BTU);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::CFM);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::GPD);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::MPH);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Wh);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Therm);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Misc1);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Celsius);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Fahrenheit);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit->system();\r\n  }\r\n\r\n  return UnitSystem::Mixed;\r\n}\r\n\r\nbool isInSystem(const std::string& unitString, UnitSystem system) {\r\n  OptionalUnit unit = createUnit(unitString,system);\r\n  if (unit && ((unit->system() == system) || (system == UnitSystem::Mixed))) {\r\n    return true;\r\n  }\r\n  return false;\r\n}\r\n\r\nbool containsRegisteredBaseUnit(const std::string& unitString) {\r\n  if (isUnitString(unitString)) {\r\n    Unit u = createUnit(unitString).get();\r\n    StringVector bus = u.baseUnits();\r\n    for (const std::string& bu : bus) {\r\n      if (getSystem(bu) != UnitSystem::Mixed) {\r\n        return true;\r\n      }\r\n    }\r\n  }\r\n  return false;\r\n}\r\n\r\nstd::string extractUnitString(const std::string& text) {\r\n  boost::smatch m;\r\n  std::string wtext(text);\r\n  std::string result;\r\n\r\n  // first handle people/100 m^2\r\n  if (boost::regex_search(wtext,m,regexEmbeddedDirectScaledUnit())) {\r\n    // main match at 1, 5, 9, or 13\r\n    for (unsigned i = 1; i < 14; i += 4) {\r\n      result = std::string(m[i].first,m[i].second);\r\n      if (!result.empty()) { \r\n        return result;\r\n      }\r\n    }\r\n  }\r\n\r\n  std::string::const_iterator wbegin = wtext.begin();\r\n  std::string::const_iterator wend = wtext.end();\r\n\r\n  while (boost::regex_search(wbegin, wend, m,regexEmbeddedUnit())) {\r\n    unsigned i = 1;\r\n    result = std::string(m[i].first,m[i].second);\r\n    while (result.empty()) {\r\n      ++i;\r\n      if (i < m.size()) { result = std::string(m[i].first,m[i].second); }\r\n      else { break; }\r\n    }\r\n    if (containsRegisteredBaseUnit(result)) { break; }\r\n    result.clear();\r\n    wbegin = m[0].second;\r\n  }\r\n\r\n  return result;\r\n}\r\n\r\nstd::string convertToStandardForm(const std::string& unitString) {\r\n  std::string result(unitString);\r\n  if (isDirectScaledUnit(unitString)) {\r\n    std::pair<std::string,std::pair<unsigned,std::string> > fragments = \r\n        decomposeDirectScaledUnit(unitString);\r\n    ScaleConstant s;\r\n    s = ScaleFactory::instance().createScale(-static_cast<int>(fragments.second.first));\r\n    if (s().value != 0.0) {\r\n      std::stringstream ss;\r\n      ss << s().abbr << \"(\";\r\n      if (!fragments.second.second.empty()) {\r\n        ss << fragments.first << fragments.second.second;\r\n      }\r\n      else {\r\n        fragments.first.resize(fragments.first.size() - 1); // remove '/'\r\n        ss << fragments.first;\r\n      }\r\n      ss << \")\";\r\n      result = ss.str();\r\n    }\r\n  }\r\n  return result;\r\n}\r\n\r\nstd::string replaceUnitString(const std::string& text,const std::string& newUnitString) {\r\n  std::string toReplace = extractUnitString(text);\r\n  std::string result(text);\r\n  if (!toReplace.empty()) {\r\n    result = boost::regex_replace(text,boost::regex(toReplace,boost::regex_constants::literal),\r\n                                  newUnitString,boost::regex_constants::format_literal);\r\n  }\r\n  return result;\r\n}\r\n\r\nbool isUnitString(const std::string& unitString) {\r\n  OptionalUnit unit = createUnit(unitString);\r\n  return unit;\r\n}\r\n\r\nUnit createDimensionlessUnit(UnitSystem system) {\r\n  switch (system.value()) {\r\n  case UnitSystem::Mixed:\r\n    return Unit();\r\n  case UnitSystem::SI:\r\n    return SIUnit();\r\n  case UnitSystem::IP:\r\n    return IPUnit();\r\n  case UnitSystem::BTU:\r\n    return BTUUnit();\r\n  case UnitSystem::CFM:\r\n    return CFMUnit();\r\n  case UnitSystem::GPD:\r\n    return GPDUnit();\r\n  case UnitSystem::MPH:\r\n    return MPHUnit();\r\n  case UnitSystem::Therm:\r\n    return ThermUnit();\r\n  case UnitSystem::Wh:\r\n    return WhUnit();\r\n  case UnitSystem::Misc1:\r\n    return Misc1Unit();\r\n  case UnitSystem::Celsius:\r\n    return CelsiusUnit();\r\n  case UnitSystem::Fahrenheit:\r\n    return FahrenheitUnit();\r\n  default:\r\n    OS_ASSERT(false);\r\n  }\r\n  return Unit();\r\n}\r\n\r\nboost::optional<Unit> createUnit(const std::string& unitString,UnitSystem system) {\r\n  return UnitFactory::instance().createUnit(unitString,system);\r\n}\r\n\r\nboost::optional<Unit> createUnit(const std::string& unitString) {\r\n  OptionalUnit unit;\r\n\r\n  // pick up preferred unit system for strings like \"C\" and \"F\"\r\n  unit = createUnit(unitString,UnitSystem::Mixed);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::SI);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::IP);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::BTU);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::CFM);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::GPD);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::MPH);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Wh);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Therm);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Misc1);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Celsius);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  unit = createUnit(unitString,UnitSystem::Fahrenheit);\r\n  if (unit && (unit->system() != UnitSystem::Mixed)) {\r\n    return unit;\r\n  }\r\n\r\n  return createUnit(unitString,UnitSystem::Mixed);\r\n}\r\n\r\nbool unitStringsEqual(const std::string& uStr1,const std::string& uStr2) {\r\n  if (isUnitString(uStr1) && isUnitString(uStr2)) {\r\n    Unit u1 = createUnit(uStr1).get();\r\n    Unit u2 = createUnit(uStr2).get();\r\n    return (u1 == u2);\r\n  }\r\n  return false;\r\n}\r\n\r\nUnit createIPPowerDensity() {\r\n  Unit result;\r\n  result.setBaseUnitExponent(\"kg\",1);\r\n  result.setBaseUnitExponent(\"m\",2);\r\n  result.setBaseUnitExponent(\"s\",-3);\r\n  result.setBaseUnitExponent(\"ft\",-2);\r\n  result.setPrettyString(\"W/ft^2\");\r\n  return result;\r\n}\r\n\r\nUnit createGPMVolumetricFlowrate() {\r\n  Unit result;\r\n  result.setBaseUnitExponent(\"crgal\",3);\r\n  result.setBaseUnitExponent(\"min\",-1);\r\n  result.setPrettyString(\"gal/min\");\r\n  return result;\r\n}\r\n\r\nUnit createIPPressure() {\r\n  Unit result;\r\n  result.setBaseUnitExponent(\"lb_f\",1);\r\n  result.setBaseUnitExponent(\"in\",-2);\r\n  result.setPrettyString(\"psi\");\r\n  return result;\r\n}\r\n\r\n} // openstudio\r\n", "meta": {"hexsha": "1b5d3078244e552d231ff1052558bb5d65d7b80b", "size": 31550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/units/UnitFactory.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/units/UnitFactory.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/units/UnitFactory.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": 35.6094808126, "max_line_length": 105, "alphanum_fraction": 0.6494453249, "num_tokens": 7407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405756657543826, "lm_q2_score": 0.024798163033404527, "lm_q1q2_score": 0.00382034465246729}}
{"text": "// Copyright (c) 2017-2020, 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\n#include \"version.h\"\n#include \"protocol.hpp\"\n#include <unordered_map>\n#include <set>\n#include <utility>\n#include <boost/endian/conversion.hpp>\n#include <common/apply_permutation.h>\n#include <common/json_util.h>\n#include <crypto/hmac-keccak.h>\n#include <ringct/rctSigs.h>\n#include <ringct/bulletproofs.h>\n#include \"cryptonote_config.h\"\n#include <sodium.h>\n#include <sodium/crypto_verify_32.h>\n#include <sodium/crypto_aead_chacha20poly1305.h>\n\n#define GET_FIELD_STRING(name, type, jtype) field_##name = std::string(json[#name].GetString(), json[#name].GetStringLength())\n#define GET_FIELD_OTHER(name, type, jtype) field_##name = static_cast<type>(json[#name].Get##jtype())\n\n#define GET_STRING_FROM_JSON(json, name, type, mandatory, def) \\\n  GET_FIELD_FROM_JSON_EX(json, name, type, String, mandatory, def, GET_FIELD_STRING)\n\n#define GET_FIELD_FROM_JSON(json, name, type, jtype, mandatory, def) \\\n  GET_FIELD_FROM_JSON_EX(json, name, type, jtype, mandatory, def, GET_FIELD_OTHER)\n\n#define GET_FIELD_FROM_JSON_EX(json, name, type, jtype, mandatory, def, VAL) \\\n  type field_##name = static_cast<type>(def);                        \\\n  bool field_##name##_found = false;                                 \\\n  (void)field_##name##_found;                                        \\\n  do if (json.HasMember(#name))                                      \\\n  {                                                                  \\\n    if (json[#name].Is##jtype())                                     \\\n    {                                                                \\\n      VAL(name, type, jtype);                                        \\\n      field_##name##_found = true;                                   \\\n    }                                                                \\\n    else                                                             \\\n    {                                                                \\\n      throw std::invalid_argument(\"Field \" #name \" found in JSON, but not \" #jtype); \\\n    }                                                                \\\n  }                                                                  \\\n  else if (mandatory)                                                \\\n  {                                                                  \\\n    throw std::invalid_argument(\"Field \" #name \" not found in JSON\");\\\n  } while(0)\n\n\nnamespace hw{\nnamespace trezor{\nnamespace protocol{\n\n  std::string key_to_string(const ::crypto::ec_point & key){\n    return std::string(key.data, sizeof(key.data));\n  }\n\n  std::string key_to_string(const ::crypto::ec_scalar & key){\n    return std::string(key.data, sizeof(key.data));\n  }\n\n  std::string key_to_string(const ::crypto::hash & key){\n    return std::string(key.data, sizeof(key.data));\n  }\n\n  std::string key_to_string(const ::rct::key & key){\n    return std::string(reinterpret_cast<const char*>(key.bytes), sizeof(key.bytes));\n  }\n\n  void string_to_key(::crypto::ec_scalar & key, const std::string & str){\n    if (str.size() != sizeof(key.data)){\n      throw std::invalid_argument(std::string(\"Key has to have \") + std::to_string(sizeof(key.data)) + \" B\");\n    }\n    memcpy(key.data, str.data(), sizeof(key.data));\n  }\n\n  void string_to_key(::crypto::ec_point & key, const std::string & str){\n    if (str.size() != sizeof(key.data)){\n      throw std::invalid_argument(std::string(\"Key has to have \") + std::to_string(sizeof(key.data)) + \" B\");\n    }\n    memcpy(key.data, str.data(), sizeof(key.data));\n  }\n\n  void string_to_key(::rct::key & key, const std::string & str){\n    if (str.size() != sizeof(key.bytes)){\n      throw std::invalid_argument(std::string(\"Key has to have \") + std::to_string(sizeof(key.bytes)) + \" B\");\n    }\n    memcpy(key.bytes, str.data(), sizeof(key.bytes));\n  }\n\nnamespace crypto {\nnamespace chacha {\n\n  void decrypt(const void* ciphertext, size_t length, const uint8_t* key, const uint8_t* iv, char* plaintext, size_t *plaintext_len){\n    CHECK_AND_ASSERT_THROW_MES(length >= TAG_SIZE, \"Ciphertext length too small\");\n    CHECK_AND_ASSERT_THROW_MES(!plaintext_len || *plaintext_len >= (length - TAG_SIZE), \"Plaintext length too small\");\n\n    unsigned long long int res_len = plaintext_len ? *plaintext_len : length;\n    auto r = crypto_aead_chacha20poly1305_ietf_decrypt(\n        reinterpret_cast<unsigned char *>(plaintext), &res_len, nullptr,\n        static_cast<const unsigned char *>(ciphertext), length, nullptr, 0, iv, key);\n\n    if (r != 0){\n      throw exc::Poly1305TagInvalid();\n    }\n\n    if (plaintext_len){\n      *plaintext_len = (size_t) res_len;\n    }\n  }\n\n}\n}\n\n\n// Cold Key image sync\nnamespace ki {\n\n  bool key_image_data(wallet_shim * wallet,\n                      const std::vector<tools::wallet2::transfer_details> & transfers,\n                      std::vector<MoneroTransferDetails> & res)\n  {\n    for(auto & td : transfers){\n      ::crypto::public_key tx_pub_key = wallet->get_tx_pub_key_from_received_outs(td);\n      const std::vector<::crypto::public_key> additional_tx_pub_keys = cryptonote::get_additional_tx_pub_keys_from_extra(td.m_tx);\n\n      res.emplace_back();\n      auto & cres = res.back();\n\n      cres.set_out_key(key_to_string(boost::get<cryptonote::txout_to_key>(td.m_tx.vout[td.m_internal_output_index].target).key));\n      cres.set_tx_pub_key(key_to_string(tx_pub_key));\n      cres.set_internal_output_index(td.m_internal_output_index);\n      for(auto & aux : additional_tx_pub_keys){\n        cres.add_additional_tx_pub_keys(key_to_string(aux));\n      }\n    }\n\n    return true;\n  }\n\n  std::string compute_hash(const MoneroTransferDetails & rr){\n    KECCAK_CTX kck;\n    uint8_t md[32];\n\n    CHECK_AND_ASSERT_THROW_MES(rr.out_key().size() == 32, \"Invalid out_key size\");\n    CHECK_AND_ASSERT_THROW_MES(rr.tx_pub_key().size() == 32, \"Invalid tx_pub_key size\");\n\n    keccak_init(&kck);\n    keccak_update(&kck, reinterpret_cast<const uint8_t *>(rr.out_key().data()), 32);\n    keccak_update(&kck, reinterpret_cast<const uint8_t *>(rr.tx_pub_key().data()), 32);\n    for (const auto &aux : rr.additional_tx_pub_keys()){\n      CHECK_AND_ASSERT_THROW_MES(aux.size() == 32, \"Invalid aux size\");\n      keccak_update(&kck, reinterpret_cast<const uint8_t *>(aux.data()), 32);\n    }\n\n    auto index_serialized = tools::get_varint_data(rr.internal_output_index());\n    keccak_update(&kck, reinterpret_cast<const uint8_t *>(index_serialized.data()), index_serialized.size());\n    keccak_finish(&kck, md);\n    return std::string(reinterpret_cast<const char*>(md), sizeof(md));\n  }\n\n  void generate_commitment(std::vector<MoneroTransferDetails> & mtds,\n                           const std::vector<tools::wallet2::transfer_details> & transfers,\n                           std::shared_ptr<messages::monero::MoneroKeyImageExportInitRequest> & req)\n  {\n    req = std::make_shared<messages::monero::MoneroKeyImageExportInitRequest>();\n\n    KECCAK_CTX kck;\n    uint8_t final_hash[32];\n    keccak_init(&kck);\n\n    for(auto &cur : mtds){\n      auto hash = compute_hash(cur);\n      keccak_update(&kck, reinterpret_cast<const uint8_t *>(hash.data()), hash.size());\n    }\n    keccak_finish(&kck, final_hash);\n\n    req = std::make_shared<messages::monero::MoneroKeyImageExportInitRequest>();\n    req->set_hash(std::string(reinterpret_cast<const char*>(final_hash), 32));\n    req->set_num(transfers.size());\n\n    std::unordered_map<uint32_t, std::set<uint32_t>> sub_indices;\n    for (auto &cur : transfers){\n      auto search = sub_indices.emplace(cur.m_subaddr_index.major, std::set<uint32_t>());\n      auto & st = search.first->second;\n      st.insert(cur.m_subaddr_index.minor);\n    }\n\n    for (auto& x: sub_indices){\n      auto subs = req->add_subs();\n      subs->set_account(x.first);\n      for(auto minor : x.second){\n        subs->add_minor_indices(minor);\n      }\n    }\n  }\n\n  void live_refresh_ack(const ::crypto::secret_key & view_key_priv,\n                        const ::crypto::public_key& out_key,\n                        const std::shared_ptr<messages::monero::MoneroLiveRefreshStepAck> & ack,\n                        ::cryptonote::keypair& in_ephemeral,\n                        ::crypto::key_image& ki)\n  {\n    std::string str_out_key(out_key.data, sizeof(out_key.data));\n    auto enc_key = protocol::tx::compute_enc_key(view_key_priv, str_out_key, ack->salt());\n\n    const size_t len_ciphertext = ack->key_image().size();  // IV || keys\n    CHECK_AND_ASSERT_THROW_MES(len_ciphertext > crypto::chacha::IV_SIZE + crypto::chacha::TAG_SIZE, \"Invalid size\");\n\n    size_t ki_len = len_ciphertext - crypto::chacha::IV_SIZE - crypto::chacha::TAG_SIZE;\n    std::unique_ptr<uint8_t[]> plaintext(new uint8_t[ki_len]);\n    uint8_t * buff = plaintext.get();\n\n    protocol::crypto::chacha::decrypt(\n        ack->key_image().data() + crypto::chacha::IV_SIZE,\n        len_ciphertext - crypto::chacha::IV_SIZE,\n        reinterpret_cast<const uint8_t *>(enc_key.data),\n        reinterpret_cast<const uint8_t *>(ack->key_image().data()),\n        reinterpret_cast<char *>(buff), &ki_len);\n\n    CHECK_AND_ASSERT_THROW_MES(ki_len == 3*32, \"Invalid size\");\n    ::crypto::signature sig{};\n    memcpy(ki.data, buff, 32);\n    memcpy(sig.c.data, buff + 32, 32);\n    memcpy(sig.r.data, buff + 64, 32);\n    in_ephemeral.pub = out_key;\n    in_ephemeral.sec = ::crypto::null_skey;\n\n    // Verification\n    std::vector<const ::crypto::public_key*> pkeys;\n    pkeys.push_back(&out_key);\n\n    CHECK_AND_ASSERT_THROW_MES(rct::scalarmultKey(rct::ki2rct(ki), rct::curveOrder()) == rct::identity(),\n                               \"Key image out of validity domain: key image \" << epee::string_tools::pod_to_hex(ki));\n\n    CHECK_AND_ASSERT_THROW_MES(::crypto::check_ring_signature((const ::crypto::hash&)ki, ki, pkeys, &sig),\n                               \"Signature failed for key image \" << epee::string_tools::pod_to_hex(ki)\n                                                                 << \", signature \" + epee::string_tools::pod_to_hex(sig)\n                                                                 << \", pubkey \" + epee::string_tools::pod_to_hex(*pkeys[0]));\n  }\n}\n\n// Cold transaction signing\nnamespace tx {\n\n  void translate_address(MoneroAccountPublicAddress * dst, const cryptonote::account_public_address * src){\n    dst->set_view_public_key(key_to_string(src->m_view_public_key));\n    dst->set_spend_public_key(key_to_string(src->m_spend_public_key));\n  }\n\n  void translate_dst_entry(MoneroTransactionDestinationEntry * dst, const cryptonote::tx_destination_entry * src){\n    dst->set_amount(src->amount);\n    dst->set_is_subaddress(src->is_subaddress);\n    dst->set_is_integrated(src->is_integrated);\n    dst->set_original(src->original);\n    translate_address(dst->mutable_addr(), &(src->addr));\n  }\n\n  void translate_src_entry(MoneroTransactionSourceEntry * dst, const cryptonote::tx_source_entry * src){\n    for(auto & cur : src->outputs){\n      auto out = dst->add_outputs();\n      out->set_idx(cur.first);\n      translate_rct_key(out->mutable_key(), &(cur.second));\n    }\n\n    dst->set_real_output(src->real_output);\n    dst->set_real_out_tx_key(key_to_string(src->real_out_tx_key));\n    for(auto & cur : src->real_out_additional_tx_keys){\n      dst->add_real_out_additional_tx_keys(key_to_string(cur));\n    }\n\n    dst->set_real_output_in_tx_index(src->real_output_in_tx_index);\n    dst->set_amount(src->amount);\n    dst->set_rct(src->rct);\n    dst->set_mask(key_to_string(src->mask));\n    translate_klrki(dst->mutable_multisig_klrki(), &(src->multisig_kLRki));\n  }\n\n  void translate_klrki(MoneroMultisigKLRki * dst, const rct::multisig_kLRki * src){\n    dst->set_k(key_to_string(src->k));\n    dst->set_l(key_to_string(src->L));\n    dst->set_r(key_to_string(src->R));\n    dst->set_ki(key_to_string(src->ki));\n  }\n\n  void translate_rct_key(MoneroRctKey * dst, const rct::ctkey * src){\n    dst->set_dest(key_to_string(src->dest));\n    dst->set_commitment(key_to_string(src->mask));\n  }\n\n  std::string hash_addr(const MoneroAccountPublicAddress * addr, std::optional<uint64_t> amount, std::optional<bool> is_subaddr){\n    return hash_addr(addr->spend_public_key(), addr->view_public_key(), amount, is_subaddr);\n  }\n\n  std::string hash_addr(const std::string & spend_key, const std::string & view_key, std::optional<uint64_t> amount, std::optional<bool> is_subaddr){\n    ::crypto::public_key spend{}, view{};\n    if (spend_key.size() != 32 || view_key.size() != 32){\n      throw std::invalid_argument(\"Public keys have invalid sizes\");\n    }\n\n    memcpy(spend.data, spend_key.data(), 32);\n    memcpy(view.data, view_key.data(), 32);\n    return hash_addr(&spend, &view, amount, is_subaddr);\n  }\n\n  std::string hash_addr(const ::crypto::public_key * spend_key, const ::crypto::public_key * view_key, std::optional<uint64_t> amount, std::optional<bool> is_subaddr){\n    char buff[64+8+1];\n    size_t offset = 0;\n\n    memcpy(buff + offset, spend_key->data, 32); offset += 32;\n    memcpy(buff + offset, view_key->data, 32); offset += 32;\n\n    if (amount){\n      memcpy(buff + offset, (uint8_t*) &(amount.get()), sizeof(amount.get())); offset += sizeof(amount.get());\n    }\n\n    if (is_subaddr){\n      buff[offset] = is_subaddr.get();\n      offset += 1;\n    }\n\n    return std::string(buff, offset);\n  }\n\n  ::crypto::secret_key compute_enc_key(const ::crypto::secret_key & private_view_key, const std::string & aux, const std::string & salt)\n  {\n    uint8_t hash[32];\n    KECCAK_CTX ctx;\n    ::crypto::secret_key res;\n\n    keccak_init(&ctx);\n    keccak_update(&ctx, (const uint8_t *) private_view_key.data, sizeof(private_view_key.data));\n    if (!aux.empty()){\n      keccak_update(&ctx, (const uint8_t *) aux.data(), aux.size());\n    }\n    keccak_finish(&ctx, hash);\n    keccak(hash, sizeof(hash), hash, sizeof(hash));\n\n    hmac_keccak_hash(hash, (const uint8_t *) salt.data(), salt.size(), hash, sizeof(hash));\n    memcpy(res.data, hash, sizeof(hash));\n    memwipe(hash, sizeof(hash));\n    return res;\n  }\n\n  TData::TData() {\n    rsig_type = 0;\n    bp_version = 0;\n    cur_input_idx = 0;\n    cur_output_idx = 0;\n    cur_batch_idx = 0;\n    cur_output_in_batch_idx = 0;\n  }\n\n  Signer::Signer(wallet_shim *wallet2, const unsigned_tx_set * unsigned_tx, size_t tx_idx, hw::tx_aux_data * aux_data) {\n    m_wallet2 = wallet2;\n    m_unsigned_tx = unsigned_tx;\n    m_aux_data = aux_data;\n    m_tx_idx = tx_idx;\n    m_ct.tx_data = cur_tx();\n    m_multisig = false;\n    m_client_version = 1;\n  }\n\n  void Signer::extract_payment_id(){\n    const std::vector<uint8_t>& tx_extra = cur_tx().extra;\n    m_ct.tsx_data.set_payment_id(\"\");\n\n    std::vector<cryptonote::tx_extra_field> tx_extra_fields;\n    cryptonote::parse_tx_extra(tx_extra, tx_extra_fields); // ok if partially parsed\n    cryptonote::tx_extra_nonce extra_nonce;\n\n    ::crypto::hash payment_id{};\n    if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))\n    {\n      ::crypto::hash8 payment_id8{};\n      if(cryptonote::get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))\n      {\n        m_ct.tsx_data.set_payment_id(std::string(payment_id8.data, 8));\n      }\n      else if (cryptonote::get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))\n      {\n        m_ct.tsx_data.set_payment_id(std::string(payment_id.data, 32));\n      }\n    }\n  }\n\n  static unsigned get_rsig_type(const rct::RCTConfig &rct_config, size_t num_outputs){\n    if (rct_config.range_proof_type == rct::RangeProofBorromean){\n      return rct::RangeProofBorromean;\n    } else if (num_outputs > BULLETPROOF_MAX_OUTPUTS){\n      return rct::RangeProofMultiOutputBulletproof;\n    } else {\n      return rct::RangeProofPaddedBulletproof;\n    }\n  }\n\n  static void generate_rsig_batch_sizes(std::vector<uint64_t> &batches, unsigned rsig_type, size_t num_outputs){\n    size_t amount_batched = 0;\n\n    while(amount_batched < num_outputs){\n      if (rsig_type == rct::RangeProofBorromean || rsig_type == rct::RangeProofBulletproof) {\n        batches.push_back(1);\n        amount_batched += 1;\n\n      } else if (rsig_type == rct::RangeProofPaddedBulletproof){\n        if (num_outputs > BULLETPROOF_MAX_OUTPUTS){\n          throw std::invalid_argument(\"BP padded can support only BULLETPROOF_MAX_OUTPUTS statements\");\n        }\n        batches.push_back(num_outputs);\n        amount_batched += num_outputs;\n\n      } else if (rsig_type == rct::RangeProofMultiOutputBulletproof){\n        size_t batch_size = 1;\n        while (batch_size * 2 + amount_batched <= num_outputs && batch_size * 2 <= BULLETPROOF_MAX_OUTPUTS){\n          batch_size *= 2;\n        }\n        batch_size = std::min(batch_size, num_outputs - amount_batched);\n        batches.push_back(batch_size);\n        amount_batched += batch_size;\n\n      } else {\n        throw std::invalid_argument(\"Unknown rsig type\");\n      }\n    }\n  }\n\n  void Signer::compute_integrated_indices(TsxData * tsx_data){\n    if (m_aux_data == nullptr || m_aux_data->tx_recipients.empty()){\n      return;\n    }\n\n    auto & chg = tsx_data->change_dts();\n    std::string change_hash = hash_addr(&chg.addr(), chg.amount(), chg.is_subaddress());\n\n    std::vector<uint32_t> integrated_indices;\n    std::set<std::string> integrated_hashes;\n    for (auto & cur : m_aux_data->tx_recipients){\n      if (!cur.has_payment_id){\n        continue;\n      }\n      integrated_hashes.emplace(hash_addr(&cur.address.m_spend_public_key, &cur.address.m_view_public_key));\n    }\n\n    ssize_t idx = -1;\n    for (auto & cur : tsx_data->outputs()){\n      idx += 1;\n\n      std::string c_hash = hash_addr(&cur.addr(), cur.amount(), cur.is_subaddress());\n      if (c_hash == change_hash || cur.is_subaddress()){\n        continue;\n      }\n\n      c_hash = hash_addr(&cur.addr());\n      if (integrated_hashes.find(c_hash) != integrated_hashes.end()){\n        integrated_indices.push_back((uint32_t)idx);\n      }\n    }\n\n    if (!integrated_indices.empty()){\n      assign_to_repeatable(tsx_data->mutable_integrated_indices(), integrated_indices.begin(), integrated_indices.end());\n    }\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionInitRequest> Signer::step_init(){\n    // extract payment ID from construction data\n    auto & tsx_data = m_ct.tsx_data;\n    auto & tx = cur_tx();\n\n    m_ct.tx.version = 2;\n    m_ct.tx.unlock_time = tx.unlock_time;\n    m_client_version = (m_aux_data->client_version ? m_aux_data->client_version.get() : 1);\n\n    tsx_data.set_version(1);\n    tsx_data.set_client_version(client_version());\n    tsx_data.set_unlock_time(tx.unlock_time);\n    tsx_data.set_num_inputs(static_cast<google::protobuf::uint32>(tx.sources.size()));\n    tsx_data.set_mixin(static_cast<google::protobuf::uint32>(tx.sources[0].outputs.size() - 1));\n    tsx_data.set_account(tx.subaddr_account);\n    tsx_data.set_monero_version(std::string(SUMOKOIN_VERSION) + \"|\" + SUMOKOIN_VERSION_TAG);\n    tsx_data.set_hard_fork(m_aux_data->hard_fork ? m_aux_data->hard_fork.get() : 0);\n    assign_to_repeatable(tsx_data.mutable_minor_indices(), tx.subaddr_indices.begin(), tx.subaddr_indices.end());\n\n    // Rsig decision\n    auto rsig_data = tsx_data.mutable_rsig_data();\n    m_ct.rsig_type = get_rsig_type(tx.rct_config, tx.splitted_dsts.size());\n    rsig_data->set_rsig_type(m_ct.rsig_type);\n    if (tx.rct_config.range_proof_type != rct::RangeProofBorromean){\n      m_ct.bp_version = (m_aux_data->bp_version ? m_aux_data->bp_version.get() : 1);\n      rsig_data->set_bp_version((uint32_t) m_ct.bp_version);\n    }\n\n    generate_rsig_batch_sizes(m_ct.grouping_vct, m_ct.rsig_type, tx.splitted_dsts.size());\n    assign_to_repeatable(rsig_data->mutable_grouping(), m_ct.grouping_vct.begin(), m_ct.grouping_vct.end());\n\n    translate_dst_entry(tsx_data.mutable_change_dts(), &(tx.change_dts));\n    for(auto & cur : tx.splitted_dsts){\n      auto dst = tsx_data.mutable_outputs()->Add();\n      translate_dst_entry(dst, &cur);\n    }\n\n    compute_integrated_indices(&tsx_data);\n\n    int64_t fee = 0;\n    for(auto & cur_in : tx.sources){\n      fee += cur_in.amount;\n    }\n    for(auto & cur_out : tx.splitted_dsts){\n      fee -= cur_out.amount;\n    }\n    if (fee < 0){\n      throw std::invalid_argument(\"Fee cannot be negative\");\n    }\n\n    tsx_data.set_fee(static_cast<google::protobuf::uint64>(fee));\n    this->extract_payment_id();\n\n    auto init_req = std::make_shared<messages::monero::MoneroTransactionInitRequest>();\n    init_req->set_version(0);\n    init_req->mutable_tsx_data()->CopyFrom(tsx_data);\n    return init_req;\n  }\n\n  void Signer::step_init_ack(std::shared_ptr<const messages::monero::MoneroTransactionInitAck> ack){\n    if (ack->has_rsig_data()){\n      m_ct.rsig_param = std::make_shared<MoneroRsigData>(ack->rsig_data());\n    }\n\n    assign_from_repeatable(&(m_ct.tx_out_entr_hmacs), ack->hmacs().begin(), ack->hmacs().end());\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionSetInputRequest> Signer::step_set_input(size_t idx){\n    CHECK_AND_ASSERT_THROW_MES(idx < cur_tx().sources.size(), \"Invalid source index\");\n    m_ct.cur_input_idx = idx;\n    auto res = std::make_shared<messages::monero::MoneroTransactionSetInputRequest>();\n    translate_src_entry(res->mutable_src_entr(), &(cur_tx().sources[idx]));\n    return res;\n  }\n\n  void Signer::step_set_input_ack(std::shared_ptr<const messages::monero::MoneroTransactionSetInputAck> ack){\n    auto & vini_str = ack->vini();\n\n    cryptonote::txin_v vini;\n    if (!cn_deserialize(vini_str.data(), vini_str.size(), vini)){\n      throw exc::ProtocolException(\"Cannot deserialize vin[i]\");\n    }\n\n    m_ct.tx.vin.emplace_back(vini);\n    m_ct.tx_in_hmacs.push_back(ack->vini_hmac());\n    m_ct.pseudo_outs.push_back(ack->pseudo_out());\n    m_ct.pseudo_outs_hmac.push_back(ack->pseudo_out_hmac());\n    m_ct.alphas.push_back(ack->pseudo_out_alpha());\n    m_ct.spend_encs.push_back(ack->spend_key());\n  }\n\n  void Signer::sort_ki(){\n    const size_t input_size = cur_tx().sources.size();\n\n    m_ct.source_permutation.clear();\n    for (size_t n = 0; n < input_size; ++n){\n      m_ct.source_permutation.push_back(n);\n    }\n\n    CHECK_AND_ASSERT_THROW_MES(m_ct.tx.vin.size() == input_size, \"Invalid vector size\");\n    std::sort(m_ct.source_permutation.begin(), m_ct.source_permutation.end(), [&](const size_t i0, const size_t i1) {\n      const cryptonote::txin_to_key &tk0 = boost::get<cryptonote::txin_to_key>(m_ct.tx.vin[i0]);\n      const cryptonote::txin_to_key &tk1 = boost::get<cryptonote::txin_to_key>(m_ct.tx.vin[i1]);\n      return memcmp(&tk0.k_image, &tk1.k_image, sizeof(tk0.k_image)) > 0;\n    });\n\n    CHECK_AND_ASSERT_THROW_MES(m_ct.tx_in_hmacs.size() == input_size, \"Invalid vector size\");\n    CHECK_AND_ASSERT_THROW_MES(m_ct.pseudo_outs.size() == input_size, \"Invalid vector size\");\n    CHECK_AND_ASSERT_THROW_MES(m_ct.pseudo_outs_hmac.size() == input_size, \"Invalid vector size\");\n    CHECK_AND_ASSERT_THROW_MES(m_ct.alphas.size() == input_size, \"Invalid vector size\");\n    CHECK_AND_ASSERT_THROW_MES(m_ct.spend_encs.size() == input_size, \"Invalid vector size\");\n    CHECK_AND_ASSERT_THROW_MES(m_ct.tx_data.sources.size() == input_size, \"Invalid vector size\");\n\n    tools::apply_permutation(m_ct.source_permutation, [&](size_t i0, size_t i1){\n      std::swap(m_ct.tx.vin[i0], m_ct.tx.vin[i1]);\n      std::swap(m_ct.tx_in_hmacs[i0], m_ct.tx_in_hmacs[i1]);\n      std::swap(m_ct.pseudo_outs[i0], m_ct.pseudo_outs[i1]);\n      std::swap(m_ct.pseudo_outs_hmac[i0], m_ct.pseudo_outs_hmac[i1]);\n      std::swap(m_ct.alphas[i0], m_ct.alphas[i1]);\n      std::swap(m_ct.spend_encs[i0], m_ct.spend_encs[i1]);\n      std::swap(m_ct.tx_data.sources[i0], m_ct.tx_data.sources[i1]);\n    });\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionInputsPermutationRequest> Signer::step_permutation(){\n    sort_ki();\n\n    auto res = std::make_shared<messages::monero::MoneroTransactionInputsPermutationRequest>();\n    assign_to_repeatable(res->mutable_perm(), m_ct.source_permutation.begin(), m_ct.source_permutation.end());\n\n    return res;\n  }\n\n  void Signer::step_permutation_ack(std::shared_ptr<const messages::monero::MoneroTransactionInputsPermutationAck> ack){\n\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionInputViniRequest> Signer::step_set_vini_input(size_t idx){\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx_data.sources.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx.vin.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx_in_hmacs.size(), \"Invalid transaction index\");\n\n    m_ct.cur_input_idx = idx;\n    auto tx = m_ct.tx_data;\n    auto res = std::make_shared<messages::monero::MoneroTransactionInputViniRequest>();\n    auto & vini = m_ct.tx.vin[idx];\n    translate_src_entry(res->mutable_src_entr(), &(tx.sources[idx]));\n    res->set_vini(cryptonote::t_serializable_object_to_blob(vini));\n    res->set_vini_hmac(m_ct.tx_in_hmacs[idx]);\n\n    if (client_version() == 0) {\n      CHECK_AND_ASSERT_THROW_MES(idx < m_ct.pseudo_outs.size(), \"Invalid transaction index\");\n      CHECK_AND_ASSERT_THROW_MES(idx < m_ct.pseudo_outs_hmac.size(), \"Invalid transaction index\");\n      res->set_pseudo_out(m_ct.pseudo_outs[idx]);\n      res->set_pseudo_out_hmac(m_ct.pseudo_outs_hmac[idx]);\n    }\n\n    return res;\n  }\n\n  void Signer::step_set_vini_input_ack(std::shared_ptr<const messages::monero::MoneroTransactionInputViniAck> ack){\n\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionAllInputsSetRequest> Signer::step_all_inputs_set(){\n    return std::make_shared<messages::monero::MoneroTransactionAllInputsSetRequest>();\n  }\n\n  void Signer::step_all_inputs_set_ack(std::shared_ptr<const messages::monero::MoneroTransactionAllInputsSetAck> ack){\n    if (client_version() > 0 || !is_offloading()){\n      return;\n    }\n\n    // If offloading, expect rsig configuration.\n    if (!ack->has_rsig_data()){\n      throw exc::ProtocolException(\"Rsig offloading requires rsig param\");\n    }\n\n    auto & rsig_data = ack->rsig_data();\n    if (!rsig_data.has_mask()){\n      throw exc::ProtocolException(\"Gamma masks not present in offloaded version\");\n    }\n\n    auto & mask = rsig_data.mask();\n    if (mask.size() != 32 * num_outputs()){\n      throw exc::ProtocolException(\"Invalid number of gamma masks\");\n    }\n\n    m_ct.rsig_gamma.reserve(num_outputs());\n    for(size_t c=0; c < num_outputs(); ++c){\n      rct::key cmask{};\n      memcpy(cmask.bytes, mask.data() + c * 32, 32);\n      m_ct.rsig_gamma.emplace_back(cmask);\n    }\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionSetOutputRequest> Signer::step_set_output(size_t idx){\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx_data.splitted_dsts.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx_out_entr_hmacs.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(is_req_bulletproof(), \"Borromean rsig not supported\");\n\n    m_ct.cur_output_idx = idx;\n    m_ct.cur_output_in_batch_idx += 1;   // assumes sequential call to step_set_output()\n\n    auto res = std::make_shared<messages::monero::MoneroTransactionSetOutputRequest>();\n    auto & cur_dst = m_ct.tx_data.splitted_dsts[idx];\n    translate_dst_entry(res->mutable_dst_entr(), &cur_dst);\n    res->set_dst_entr_hmac(m_ct.tx_out_entr_hmacs[idx]);\n\n    // Range sig offloading to the host\n    // ClientV0 sends offloaded BP with the last message in the batch.\n    // ClientV1 needs additional message after the last message in the batch as BP uses deterministic masks.\n    if (client_version() == 0 && is_offloading() && should_compute_bp_now()) {\n      auto rsig_data = res->mutable_rsig_data();\n      compute_bproof(*rsig_data);\n    }\n\n    return res;\n  }\n\n  void Signer::step_set_output_ack(std::shared_ptr<const messages::monero::MoneroTransactionSetOutputAck> ack){\n    cryptonote::tx_out tx_out;\n    rct::Bulletproof bproof{};\n    rct::ctkey out_pk{};\n    rct::ecdhTuple ecdh{};\n\n    bool has_rsig = false;\n    std::string rsig_buff;\n\n    if (ack->has_rsig_data()){\n      auto & rsig_data = ack->rsig_data();\n\n      if (rsig_data.has_rsig() && !rsig_data.rsig().empty()){\n        has_rsig = true;\n        rsig_buff = rsig_data.rsig();\n      }\n\n      if (client_version() >= 1 && rsig_data.has_mask()){\n        rct::key cmask{};\n        string_to_key(cmask, rsig_data.mask());\n        m_ct.rsig_gamma.emplace_back(cmask);\n      }\n    }\n\n    if (!cn_deserialize(ack->tx_out(), tx_out)){\n      throw exc::ProtocolException(\"Cannot deserialize vout[i]\");\n    }\n\n    if (!cn_deserialize(ack->out_pk(), out_pk)){\n      throw exc::ProtocolException(\"Cannot deserialize out_pk\");\n    }\n\n    if (m_ct.bp_version <= 1) {\n      if (!cn_deserialize(ack->ecdh_info(), ecdh)){\n        throw exc::ProtocolException(\"Cannot deserialize ecdhtuple\");\n      }\n    } else {\n      CHECK_AND_ASSERT_THROW_MES(8 == ack->ecdh_info().size(), \"Invalid ECDH.amount size\");\n      memcpy(ecdh.amount.bytes, ack->ecdh_info().data(), 8);\n    }\n\n    if (has_rsig && is_req_bulletproof() && !cn_deserialize(rsig_buff, bproof)){\n      throw exc::ProtocolException(\"Cannot deserialize bulletproof rangesig\");\n    }\n\n    m_ct.tx.vout.emplace_back(tx_out);\n    m_ct.tx_out_hmacs.push_back(ack->vouti_hmac());\n    m_ct.tx_out_pk.emplace_back(out_pk);\n    m_ct.tx_out_ecdh.emplace_back(ecdh);\n\n    // ClientV0, if no rsig was generated on Trezor, do not continue.\n    // ClientV1+ generates BP after all masks in the current batch are generated\n    if (!has_rsig || (client_version() >= 1 && is_offloading())){\n      return;\n    }\n\n    process_bproof(bproof);\n    m_ct.cur_batch_idx += 1;\n    m_ct.cur_output_in_batch_idx = 0;\n  }\n\n  bool Signer::should_compute_bp_now() const {\n    CHECK_AND_ASSERT_THROW_MES(m_ct.cur_batch_idx < m_ct.grouping_vct.size(), \"Invalid batch index\");\n    return m_ct.grouping_vct[m_ct.cur_batch_idx] <= m_ct.cur_output_in_batch_idx;\n  }\n\n  void Signer::compute_bproof(messages::monero::MoneroTransactionRsigData & rsig_data){\n    auto batch_size = m_ct.grouping_vct[m_ct.cur_batch_idx];\n    std::vector<uint64_t> amounts;\n    rct::keyV masks;\n    CHECK_AND_ASSERT_THROW_MES(m_ct.cur_output_idx + 1 >= batch_size, \"Invalid index for batching\");\n\n    for(size_t i = 0; i < batch_size; ++i){\n      const size_t bidx = 1 + m_ct.cur_output_idx - batch_size + i;\n      CHECK_AND_ASSERT_THROW_MES(bidx < m_ct.tx_data.splitted_dsts.size(), \"Invalid gamma index\");\n      CHECK_AND_ASSERT_THROW_MES(bidx < m_ct.rsig_gamma.size(), \"Invalid gamma index\");\n\n      amounts.push_back(m_ct.tx_data.splitted_dsts[bidx].amount);\n      masks.push_back(m_ct.rsig_gamma[bidx]);\n    }\n\n    auto bp = bulletproof_PROVE(amounts, masks);\n    auto serRsig = cn_serialize(bp);\n    m_ct.tx_out_rsigs.emplace_back(bp);\n    rsig_data.set_rsig(serRsig);\n  }\n\n  void Signer::process_bproof(rct::Bulletproof & bproof){\n    CHECK_AND_ASSERT_THROW_MES(m_ct.cur_batch_idx < m_ct.grouping_vct.size(), \"Invalid batch index\");\n    auto batch_size = m_ct.grouping_vct[m_ct.cur_batch_idx];\n    for (size_t i = 0; i < batch_size; ++i){\n      const size_t bidx = 1 + m_ct.cur_output_idx - batch_size + i;\n      CHECK_AND_ASSERT_THROW_MES(bidx < m_ct.tx_out_pk.size(), \"Invalid out index\");\n\n      rct::key commitment = m_ct.tx_out_pk[bidx].mask;\n      commitment = rct::scalarmultKey(commitment, rct::INV_EIGHT);\n      bproof.V.push_back(commitment);\n    }\n\n    m_ct.tx_out_rsigs.emplace_back(bproof);\n    if (!rct::bulletproof_VERIFY(boost::get<rct::Bulletproof>(m_ct.tx_out_rsigs.back()))) {\n      throw exc::ProtocolException(\"Returned range signature is invalid\");\n    }\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionSetOutputRequest> Signer::step_rsig(size_t idx){\n    if (client_version() == 0 || !is_offloading() || !should_compute_bp_now()){\n      return nullptr;\n    }\n\n    auto res = std::make_shared<messages::monero::MoneroTransactionSetOutputRequest>();\n    auto & cur_dst = m_ct.tx_data.splitted_dsts[idx];\n    translate_dst_entry(res->mutable_dst_entr(), &cur_dst);\n    res->set_dst_entr_hmac(m_ct.tx_out_entr_hmacs[idx]);\n\n    compute_bproof(*(res->mutable_rsig_data()));\n    res->set_is_offloaded_bp(true);\n    return res;\n  }\n\n  void Signer::step_set_rsig_ack(std::shared_ptr<const messages::monero::MoneroTransactionSetOutputAck> ack){\n    m_ct.cur_batch_idx += 1;\n    m_ct.cur_output_in_batch_idx = 0;\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionAllOutSetRequest> Signer::step_all_outs_set(){\n    return std::make_shared<messages::monero::MoneroTransactionAllOutSetRequest>();\n  }\n\n  void Signer::step_all_outs_set_ack(std::shared_ptr<const messages::monero::MoneroTransactionAllOutSetAck> ack, hw::device &hwdev){\n    m_ct.rv = std::make_shared<rct::rctSig>();\n    m_ct.rv->txnFee = ack->rv().txn_fee();\n    m_ct.rv->type = static_cast<uint8_t>(ack->rv().rv_type());\n    string_to_key(m_ct.rv->message, ack->rv().message());\n\n    // Extra copy\n    m_ct.tx.extra.clear();\n    auto extra = ack->extra();\n    auto extra_data = extra.data();\n    m_ct.tx.extra.reserve(extra.size());\n    for(size_t i = 0; i < extra.size(); ++i){\n      m_ct.tx.extra.push_back(static_cast<uint8_t>(extra_data[i]));\n    }\n\n    ::crypto::hash tx_prefix_hash{};\n    cryptonote::get_transaction_prefix_hash(m_ct.tx, tx_prefix_hash);\n    m_ct.tx_prefix_hash = key_to_string(tx_prefix_hash);\n    if (crypto_verify_32(reinterpret_cast<const unsigned char *>(tx_prefix_hash.data),\n        reinterpret_cast<const unsigned char *>(ack->tx_prefix_hash().data()))){\n      throw exc::proto::SecurityException(\"Transaction prefix has does not match to the computed value\");\n    }\n\n    // RctSig\n    auto num_sources = m_ct.tx_data.sources.size();\n    if (is_simple() || is_req_bulletproof()){\n      auto dst = &m_ct.rv->pseudoOuts;\n      if (is_bulletproof()){\n        dst = &m_ct.rv->p.pseudoOuts;\n      }\n\n      dst->clear();\n      for (const auto &pseudo_out : m_ct.pseudo_outs) {\n        dst->emplace_back();\n        string_to_key(dst->back(), pseudo_out);\n      }\n\n      m_ct.rv->mixRing.resize(num_sources);\n    } else {\n      m_ct.rv->mixRing.resize(m_ct.tsx_data.mixin());\n      m_ct.rv->mixRing[0].resize(num_sources);\n    }\n\n    CHECK_AND_ASSERT_THROW_MES(m_ct.tx_out_pk.size() == m_ct.tx_out_ecdh.size(), \"Invalid vector sizes\");\n    for(size_t i = 0; i < m_ct.tx_out_ecdh.size(); ++i){\n      m_ct.rv->outPk.push_back(m_ct.tx_out_pk[i]);\n      m_ct.rv->ecdhInfo.push_back(m_ct.tx_out_ecdh[i]);\n    }\n\n    for(size_t i = 0; i < m_ct.tx_out_rsigs.size(); ++i){\n      if (is_bulletproof()){\n        m_ct.rv->p.bulletproofs.push_back(boost::get<rct::Bulletproof>(m_ct.tx_out_rsigs[i]));\n      } else {\n        m_ct.rv->p.rangeSigs.push_back(boost::get<rct::rangeSig>(m_ct.tx_out_rsigs[i]));\n      }\n    }\n\n    rct::key hash_computed = rct::get_pre_mlsag_hash(*(m_ct.rv), hwdev);\n    auto & hash = ack->full_message_hash();\n\n    if (hash.size() != 32){\n      throw exc::ProtocolException(\"Returned mlsag hash has invalid size\");\n    }\n\n    if (crypto_verify_32(reinterpret_cast<const unsigned char *>(hash_computed.bytes),\n                         reinterpret_cast<const unsigned char *>(hash.data()))){\n      throw exc::proto::SecurityException(\"Computed MLSAG does not match\");\n    }\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionSignInputRequest> Signer::step_sign_input(size_t idx){\n    m_ct.cur_input_idx = idx;\n\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx_data.sources.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx.vin.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.tx_in_hmacs.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.alphas.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.spend_encs.size(), \"Invalid transaction index\");\n\n    auto res = std::make_shared<messages::monero::MoneroTransactionSignInputRequest>();\n    translate_src_entry(res->mutable_src_entr(), &(m_ct.tx_data.sources[idx]));\n    res->set_vini(cryptonote::t_serializable_object_to_blob(m_ct.tx.vin[idx]));\n    res->set_vini_hmac(m_ct.tx_in_hmacs[idx]);\n    res->set_pseudo_out_alpha(m_ct.alphas[idx]);\n    res->set_spend_key(m_ct.spend_encs[idx]);\n\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.pseudo_outs.size(), \"Invalid transaction index\");\n    CHECK_AND_ASSERT_THROW_MES(idx < m_ct.pseudo_outs_hmac.size(), \"Invalid transaction index\");\n    res->set_pseudo_out(m_ct.pseudo_outs[idx]);\n    res->set_pseudo_out_hmac(m_ct.pseudo_outs_hmac[idx]);\n    return res;\n  }\n\n  void Signer::step_sign_input_ack(std::shared_ptr<const messages::monero::MoneroTransactionSignInputAck> ack){\n    rct::mgSig mg;\n    if (!cn_deserialize(ack->signature(), mg)){\n      throw exc::ProtocolException(\"Cannot deserialize mg[i]\");\n    }\n\n    // Sync updated pseudo_outputs, client_version>=1, HF10+\n    if (client_version() >= 1 && ack->has_pseudo_out()){\n      CHECK_AND_ASSERT_THROW_MES(m_ct.cur_input_idx < m_ct.pseudo_outs.size(), \"Invalid pseudo-out index\");\n      m_ct.pseudo_outs[m_ct.cur_input_idx] = ack->pseudo_out();\n      if (is_bulletproof()){\n        CHECK_AND_ASSERT_THROW_MES(m_ct.cur_input_idx < m_ct.rv->p.pseudoOuts.size(), \"Invalid pseudo-out index\");\n        string_to_key(m_ct.rv->p.pseudoOuts[m_ct.cur_input_idx], ack->pseudo_out());\n      } else {\n        CHECK_AND_ASSERT_THROW_MES(m_ct.cur_input_idx < m_ct.rv->pseudoOuts.size(), \"Invalid pseudo-out index\");\n        string_to_key(m_ct.rv->pseudoOuts[m_ct.cur_input_idx], ack->pseudo_out());\n      }\n    }\n\n    m_ct.rv->p.MGs.push_back(mg);\n  }\n\n  std::shared_ptr<messages::monero::MoneroTransactionFinalRequest> Signer::step_final(){\n    m_ct.tx.rct_signatures = *(m_ct.rv);\n    return std::make_shared<messages::monero::MoneroTransactionFinalRequest>();\n  }\n\n  void Signer::step_final_ack(std::shared_ptr<const messages::monero::MoneroTransactionFinalAck> ack){\n    if (m_multisig){\n      auto & cout_key = ack->cout_key();\n      for(auto & cur : m_ct.couts){\n        if (cur.size() != crypto::chacha::IV_SIZE + 32){\n          throw std::invalid_argument(\"Encrypted cout has invalid length\");\n        }\n\n        char buff[32];\n        auto data = cur.data();\n\n        crypto::chacha::decrypt(data + crypto::chacha::IV_SIZE, 32, reinterpret_cast<const uint8_t *>(cout_key.data()), reinterpret_cast<const uint8_t *>(data), buff);\n        m_ct.couts_dec.emplace_back(buff, 32);\n      }\n    }\n\n    m_ct.enc_salt1 = ack->salt();\n    m_ct.enc_salt2 = ack->rand_mult();\n    m_ct.enc_keys = ack->tx_enc_keys();\n  }\n\n  std::string Signer::store_tx_aux_info(){\n    rapidjson::StringBuffer sb;\n    rapidjson::Writer<rapidjson::StringBuffer> writer(sb);\n\n    rapidjson::Document json;\n    json.SetObject();\n\n    rapidjson::Value valueS(rapidjson::kStringType);\n    rapidjson::Value valueI(rapidjson::kNumberType);\n\n    valueI.SetInt(1);\n    json.AddMember(\"version\", valueI, json.GetAllocator());\n\n    valueS.SetString(m_ct.enc_salt1.c_str(), m_ct.enc_salt1.size());\n    json.AddMember(\"salt1\", valueS, json.GetAllocator());\n\n    valueS.SetString(m_ct.enc_salt2.c_str(), m_ct.enc_salt2.size());\n    json.AddMember(\"salt2\", valueS, json.GetAllocator());\n\n    valueS.SetString(m_ct.tx_prefix_hash.c_str(), m_ct.tx_prefix_hash.size());\n    json.AddMember(\"tx_prefix_hash\", valueS, json.GetAllocator());\n\n    valueS.SetString(m_ct.enc_keys.c_str(), m_ct.enc_keys.size());\n    json.AddMember(\"enc_keys\", valueS, json.GetAllocator());\n\n    json.Accept(writer);\n    return sb.GetString();\n  }\n\n  void load_tx_key_data(hw::device_cold::tx_key_data_t & res, const std::string & data)\n  {\n    rapidjson::Document json;\n\n    // The contents should be JSON if the wallet follows the new format.\n    if (json.Parse(data.c_str()).HasParseError())\n    {\n      throw std::invalid_argument(\"Data parsing error\");\n    }\n    else if(!json.IsObject())\n    {\n      throw std::invalid_argument(\"Data parsing error - not an object\");\n    }\n\n    GET_FIELD_FROM_JSON(json, version, int, Int, true, -1);\n    GET_STRING_FROM_JSON(json, salt1, std::string, true, std::string());\n    GET_STRING_FROM_JSON(json, salt2, std::string, true, std::string());\n    GET_STRING_FROM_JSON(json, enc_keys, std::string, true, std::string());\n    GET_STRING_FROM_JSON(json, tx_prefix_hash, std::string, false, std::string());\n\n    if (field_version != 1)\n    {\n      throw std::invalid_argument(\"Unknown version\");\n    }\n\n    res.salt1 = field_salt1;\n    res.salt2 = field_salt2;\n    res.tx_enc_keys = field_enc_keys;\n    res.tx_prefix_hash = field_tx_prefix_hash;\n  }\n\n  std::shared_ptr<messages::monero::MoneroGetTxKeyRequest> get_tx_key(\n      const hw::device_cold::tx_key_data_t & tx_data)\n  {\n    auto req = std::make_shared<messages::monero::MoneroGetTxKeyRequest>();\n    req->set_salt1(tx_data.salt1);\n    req->set_salt2(tx_data.salt2);\n    req->set_tx_enc_keys(tx_data.tx_enc_keys);\n    req->set_tx_prefix_hash(tx_data.tx_prefix_hash);\n    req->set_reason(0);\n\n    return req;\n  }\n\n  void get_tx_key_ack(\n      std::vector<::crypto::secret_key> & tx_keys,\n      const std::string & tx_prefix_hash,\n      const ::crypto::secret_key & view_key_priv,\n      std::shared_ptr<const messages::monero::MoneroGetTxKeyAck> ack\n  )\n  {\n    auto enc_key = protocol::tx::compute_enc_key(view_key_priv, tx_prefix_hash, ack->salt());\n    auto & encrypted_keys = ack->has_tx_derivations() ? ack->tx_derivations() : ack->tx_keys();\n\n    const size_t len_ciphertext = encrypted_keys.size();  // IV || keys || TAG\n    CHECK_AND_ASSERT_THROW_MES(len_ciphertext > crypto::chacha::IV_SIZE + crypto::chacha::TAG_SIZE, \"Invalid size\");\n\n    size_t keys_len = len_ciphertext - crypto::chacha::IV_SIZE - crypto::chacha::TAG_SIZE;\n    std::unique_ptr<uint8_t[]> plaintext(new uint8_t[keys_len]);\n\n    protocol::crypto::chacha::decrypt(\n        encrypted_keys.data() + crypto::chacha::IV_SIZE,\n        len_ciphertext - crypto::chacha::IV_SIZE,\n        reinterpret_cast<const uint8_t *>(enc_key.data),\n        reinterpret_cast<const uint8_t *>(encrypted_keys.data()),\n        reinterpret_cast<char *>(plaintext.get()), &keys_len);\n\n    CHECK_AND_ASSERT_THROW_MES(keys_len % 32 == 0, \"Invalid size\");\n    tx_keys.resize(keys_len / 32);\n\n    for(unsigned i = 0; i < keys_len / 32; ++i)\n    {\n      memcpy(tx_keys[i].data, plaintext.get() + 32 * i, 32);\n    }\n    memwipe(plaintext.get(), keys_len);\n  }\n\n}\n}\n}\n}\n", "meta": {"hexsha": "9c17650c84e0f40e2c858d86202085800cf9bfc4", "size": 43735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/device_trezor/trezor/protocol.cpp", "max_stars_repo_name": "blackrangersoftware/brs-sumokoin-core", "max_stars_repo_head_hexsha": "c3bc89ebbe10f595093acb2afd62387ba1a6d10b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/device_trezor/trezor/protocol.cpp", "max_issues_repo_name": "blackrangersoftware/brs-sumokoin-core", "max_issues_repo_head_hexsha": "c3bc89ebbe10f595093acb2afd62387ba1a6d10b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/device_trezor/trezor/protocol.cpp", "max_forks_repo_name": "blackrangersoftware/brs-sumokoin-core", "max_forks_repo_head_hexsha": "c3bc89ebbe10f595093acb2afd62387ba1a6d10b", "max_forks_repo_licenses": ["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.087076077, "max_line_length": 167, "alphanum_fraction": 0.6752029267, "num_tokens": 11383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.01302048803134377, "lm_q1q2_score": 0.0037053184569089204}}
{"text": "/*\n\nCopyright (c) 2005-2018, 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 ABSTRACTNUMERICALMETHOD_HPP_\n#define ABSTRACTNUMERICALMETHOD_HPP_\n\n#include <boost/shared_ptr.hpp>\n#include \"ChasteSerialization.hpp\"\n#include \"ClassIsAbstract.hpp\"\n#include \"Identifiable.hpp\"\n\n#include \"AbstractOffLatticeCellPopulation.hpp\"\n#include \"AbstractForce.hpp\"\n\n/**\n * An abstract class representing a numerical method for off lattice cell based simulations.\n *\n * Numerical methods have access to the cell population and the force collection.\n * The method is then responsible for evaluating forces at whatever times and positions\n * are required, then updating all node positions.\n */\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM=ELEMENT_DIM>\nclass AbstractNumericalMethod : public Identifiable\n{\n    friend class TestNumericalMethods;\n\nprivate:\n\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n\n    /**\n     * Save or restore the simulation.\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 & mUseAdaptiveTimestep;\n        archive & mUseUpdateNodeLocation;\n        archive & mGhostNodeForcesEnabled;\n    }\n\nprotected:\n\n    /** Pointer to the cell population being updated by this method*/\n    AbstractOffLatticeCellPopulation<ELEMENT_DIM,SPACE_DIM>* mpCellPopulation;\n\n    /** Pointer to the force collection to apply*/\n    std::vector<boost::shared_ptr<AbstractForce<ELEMENT_DIM, SPACE_DIM> > >* mpForceCollection;\n\n    /**\n     * Whether the numerical method uses an adaptive time step.\n     * Initialized to false in the AbstractNumericalMethod constructor.\n     */\n    bool mUseAdaptiveTimestep;\n\n    /**\n     * A boolean flag indicating whether non-forward Euler methods are supported for this type of cell\n     * population. Allows us to fall back to the old method of updating node positions for populations\n     * that require it (This is only for NodeBasedCellPopulationWithBuskeUpdates).\n     *\n     * Initialized to false in the AbstractNumericalMethod constructor.\n     *\n     * \\todo #2087 Consider replacing this with static_casts\n     */\n    bool mUseUpdateNodeLocation;\n\n    /**\n     * A boolean indicating whether this cell population type contains ghost nodes.\n     * Initialized to true in the AbstractNumericalMethod constructor.\n     */\n    bool mGhostNodeForcesEnabled;\n\n    /**\n     * Computes and returns the force on each node, including the damping factor\n     * @return A vector of applied forces\n     */\n    std::vector<c_vector<double, SPACE_DIM> > ComputeForcesIncludingDamping();\n\n    /**\n     * Saves the current location of each cell in the population in a vector.\n     * @return A vector of cell positions\n     */\n    std::vector<c_vector<double, SPACE_DIM> > SaveCurrentLocations();\n\n    /**\n     * Updates a single node's position, taking into account periodic boundary conditions\n     *\n     * @param nodeIndex Index of the node to update\n     * @param newPosition C_vector holding the new node position\n     */\n     void SafeNodePositionUpdate(unsigned nodeIndex, c_vector<double, SPACE_DIM> newPosition);\n\n    /**\n     * Detects whether a node has exceeded the acceptable displacement for one timestep.\n     * If a step size exception has occurred, it either causes the simulation to terminate or,\n     * in adaptive simulations, the exception is caught and the step size is reduced in response.\n     *\n     * @param nodeIndex Index of the node being examined\n     * @param displacement Displacement of the node this step\n     * @param dt Time step size\n     */\n    void DetectStepSizeExceptions(unsigned nodeIndex, c_vector<double,SPACE_DIM>& displacement, double dt);\n\npublic:\n\n    /**\n     * Constructor.\n     * No input parameters are required, allowing the numerical method to be created first, then passed to\n     * the simulation. The cell population and force collection pointers are then set by the simulation in\n     * its constructor.\n     */\n    AbstractNumericalMethod<ELEMENT_DIM,SPACE_DIM>();\n\n    /**\n     * Destructor.\n     */\n    virtual ~AbstractNumericalMethod<ELEMENT_DIM,SPACE_DIM>();\n\n    /**\n     * Sets the pointer to the cell population updated by this method\n     *\n     * @param pPopulation Pointer to an AbstractOffLattice cell population\n     */\n    void SetCellPopulation(AbstractOffLatticeCellPopulation<ELEMENT_DIM,SPACE_DIM>* pPopulation);\n\n    /**\n     * Sets the pointer to the force collection applied by this method\n     *\n     * @param pForces Pointer to the simulation's force collection\n     */\n    void SetForceCollection(std::vector<boost::shared_ptr<AbstractForce<ELEMENT_DIM, SPACE_DIM> > >* pForces);\n\n    /**\n     * Set mUseAdaptiveTimestep.\n     *\n     * @param useAdaptiveTimestep whether to use an adaptive time step\n     */\n    void SetUseAdaptiveTimestep(bool useAdaptiveTimestep);\n\n    /**\n     * Set mUseUpdateNodeLocation.\n     *\n     * @param useUpdateNodeLocation whether to use the population method UpdateNodeLocations()\n     */\n    void SetUseUpdateNodeLocation(bool useUpdateNodeLocation);\n\n    /**\n     * Get mUseUpdateNodeLocation.\n     *\n     * @return whether the population method UpdateNodeLocations() is being used\n     */\n    bool GetUseUpdateNodeLocation();\n\n    /**\n     * @return whether the numerical method uses an adaptive time step.\n     */\n    bool HasAdaptiveTimestep();\n\n    /**\n     * Updates node positions according to Newton's 2nd law with overdamping.\n     *\n     * As this method is pure virtual, it must be overridden\n     * in subclasses.\n     *\n     * @param dt Time step size\n     */\n    virtual void UpdateAllNodePositions(double dt)=0;\n\n    /**\n     * Saves the name of the numerical method to the parameters file\n     *\n     * @param rParamsFile Reference to the parameter output filestream\n     */\n    void OutputNumericalMethodInfo(out_stream& rParamsFile);\n\n    /**\n     * Saves any additional numerical method details to the parameters file.\n     *\n     * @param rParamsFile Reference to the parameter output filestream\n     */\n    virtual void OutputNumericalMethodParameters(out_stream& rParamsFile);\n};\n\nTEMPLATED_CLASS_IS_ABSTRACT_2_UNSIGNED(AbstractNumericalMethod)\n\n#endif /*ABSTRACTNUMERICALMETHOD_HPP_*/\n", "meta": {"hexsha": "73c9d490a95502401ced1941f993411baedbaa6b", "size": 8001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/simulation/numerical_methods/AbstractNumericalMethod.hpp", "max_stars_repo_name": "joeyshuttleworth/Chaste", "max_stars_repo_head_hexsha": "0d9a912fd735ac7bac86f9f2d250637c1d7308ba", "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": "cell_based/src/simulation/numerical_methods/AbstractNumericalMethod.hpp", "max_issues_repo_name": "joeyshuttleworth/Chaste", "max_issues_repo_head_hexsha": "0d9a912fd735ac7bac86f9f2d250637c1d7308ba", "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": "cell_based/src/simulation/numerical_methods/AbstractNumericalMethod.hpp", "max_forks_repo_name": "joeyshuttleworth/Chaste", "max_forks_repo_head_hexsha": "0d9a912fd735ac7bac86f9f2d250637c1d7308ba", "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": 35.8789237668, "max_line_length": 110, "alphanum_fraction": 0.7317835271, "num_tokens": 1677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2254166158350767, "lm_q2_score": 0.016403028759680152, "lm_q1q2_score": 0.0036975152324525353}}
{"text": "/*\n * Gamedev Framework (gf)\n * Copyright (C) 2016-2022 Julien Bernard\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#include <gf/Map.h>\n\n#include <iostream>\n#include <limits>\n\n#include <gf/Geometry.h>\n#include <gf/VectorOps.h>\n\n#include <boost/heap/binomial_heap.hpp>\n\nnamespace gf {\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\ninline namespace v1 {\n#endif\n\n  SquareMap::SquareMap(Vector2i size)\n  : m_cells(size, None)\n  {\n\n  }\n\n  Vector2i SquareMap::getSize() const {\n    return m_cells.getSize();\n  }\n\n  PositionRange<int> SquareMap::getRange() const {\n    return m_cells.getPositionRange();\n  }\n\n  void SquareMap::setCell(Vector2i pos, Flags<CellProperty> flags) {\n    m_cells(pos) = flags;\n  }\n\n  void SquareMap::reset(Flags<CellProperty> flags) {\n    for (auto& cell : m_cells) {\n      cell = flags;\n    }\n  }\n\n  void SquareMap::setTransparent(Vector2i pos, bool transparent) {\n    if (transparent) {\n      m_cells(pos).set(CellProperty::Transparent);\n    } else {\n      m_cells(pos).reset(CellProperty::Transparent);\n    }\n  }\n\n  bool SquareMap::isTransparent(Vector2i pos) const {\n    return m_cells(pos).test(CellProperty::Transparent);\n  }\n\n  void SquareMap::setWalkable(Vector2i pos, bool walkable) {\n    if (walkable) {\n      m_cells(pos).set(CellProperty::Walkable);\n    } else {\n      m_cells(pos).reset(CellProperty::Walkable);\n    }\n  }\n\n  bool SquareMap::isWalkable(Vector2i pos) const {\n    return m_cells(pos).test(CellProperty::Walkable);\n  }\n\n  void SquareMap::setEmpty(Vector2i pos) {\n    m_cells(pos) = EmptyCell;\n  }\n\n  /*\n   * FoV\n   */\n\n  void SquareMap::clearFieldOfVision() {\n    for (auto& cell : m_cells) {\n      cell.reset(CellProperty::Visible);\n    }\n  }\n\n  void SquareMap::clearExplored() {\n    for (auto& cell : m_cells) {\n      cell.reset(CellProperty::Explored);\n    }\n  }\n\n  namespace {\n\n    void postProcessMap(Array2D<Flags<CellProperty>, int>& cells, Vector2i q0, Vector2i q1, Vector2i step) {\n      int xLo, xHi, yLo, yHi;\n      std::tie(xLo, xHi) = std::minmax(q0.x, q1.x);\n      std::tie(yLo, yHi) = std::minmax(q0.y, q1.y);\n\n      for (int y = yLo; y <= yHi; ++y) {\n        for (int x = xLo; x <= xHi; ++x) {\n          if (!cells.isValid({ x, y })) {\n            continue;\n          }\n\n          if (!cells({ x, y }).test(CellProperty::Visible) || !cells({ x, y }).test(CellProperty::Transparent)) {\n            continue;\n          }\n\n          int x2 = x + step.x;\n          int y2 = y + step.y;\n\n          if (xLo <= x2 && x2 <= xHi) {\n            gf::Vector2i target = { x2, y };\n\n            if (cells.isValid(target) && !cells(target).test(CellProperty::Transparent)) {\n              cells(target).set(CellProperty::Visible);\n            }\n          }\n\n          if (yLo <= y2 && y2 <= yHi) {\n            gf::Vector2i target = { x, y2 };\n\n            if (cells.isValid(target) && !cells(target).test(CellProperty::Transparent)) {\n              cells(target).set(CellProperty::Visible);\n            }\n          }\n\n          if (xLo <= x2 && x2 <= xHi && yLo <= y2 && y2 <= yHi) {\n            gf::Vector2i target = { x2, y2 };\n\n            if (cells.isValid(target) && !cells(target).test(CellProperty::Transparent)) {\n              cells(target).set(CellProperty::Visible);\n            }\n          }\n        }\n      }\n    }\n\n    void castRay(Array2D<Flags<CellProperty>, int>& cells, Vector2i p0, Vector2i p1, int maxRadius2, FieldOfVisionLimit limit, Flags<CellProperty> modification) {\n      Bresenham bresenham(p0, p1);\n      Vector2i curr;\n      bool blocked = false;\n\n      while (!bresenham.step(curr)) {\n        if (!cells.isValid(curr)) {\n          return;\n        }\n\n        if (maxRadius2 > 0) {\n          int radius2 = gf::squareDistance(p0, curr);\n\n          if (radius2 > maxRadius2) {\n            return;\n          }\n        }\n\n        if (!blocked && !cells(curr).test(CellProperty::Transparent)) {\n          blocked = true;\n        } else if (blocked) {\n          return; // wall\n        }\n\n        if (limit == FieldOfVisionLimit::Included || !blocked) {\n          cells(curr) |= modification;\n        }\n      }\n    }\n\n    void computeBasicFov(Array2D<Flags<CellProperty>, int>& cells, Vector2i pos, int maxRadius, FieldOfVisionLimit limit, Flags<CellProperty> modification) {\n      RangeI xRange = cells.getColRange();\n      RangeI yRange = cells.getRowRange();\n\n      int maxRadius2 = maxRadius * maxRadius;\n\n      if (maxRadius > 0) {\n        xRange.lo = std::max(xRange.lo, pos.x - maxRadius);\n        xRange.hi = std::min(xRange.hi, pos.x + maxRadius);\n        yRange.lo = std::max(yRange.lo, pos.y - maxRadius);\n        yRange.hi = std::min(yRange.hi, pos.y + maxRadius);\n      } else {\n        maxRadius2 = 0;\n      }\n\n      cells(pos) |= modification;\n\n      for (auto x : xRange) {\n        castRay(cells, pos, { x, yRange.lo }, maxRadius2, limit, modification);\n        castRay(cells, pos, { x, yRange.hi }, maxRadius2, limit, modification);\n      }\n\n      for (auto y : yRange) {\n        castRay(cells, pos, { xRange.lo, y }, maxRadius2, limit, modification);\n        castRay(cells, pos, { xRange.hi, y }, maxRadius2, limit, modification);\n      }\n\n      if (limit == FieldOfVisionLimit::Included) {\n        postProcessMap(cells, pos, { xRange.lo, yRange.lo }, { -1, -1 });\n        postProcessMap(cells, pos, { xRange.hi, yRange.lo }, {  1, -1 });\n        postProcessMap(cells, pos, { xRange.lo, yRange.hi }, { -1,  1 });\n        postProcessMap(cells, pos, { xRange.hi, yRange.hi }, {  1,  1 });\n      }\n    }\n\n    void computeGenericFieldOfVision(Array2D<Flags<CellProperty>, int>& cells, Vector2i pos, int maxRadius, FieldOfVisionLimit limit, FieldOfVision algorithm, Flags<CellProperty> modification) {\n      switch (algorithm) {\n        case FieldOfVision::Basic:\n          computeBasicFov(cells, pos, maxRadius, limit, modification);\n          break;\n\n        default:\n          break;\n      }\n    }\n\n  } // anonymous namespace\n\n  void SquareMap::computeFieldOfVision(Vector2i pos, int maxRadius, FieldOfVisionLimit limit, FieldOfVision algorithm) {\n    computeGenericFieldOfVision(m_cells, pos, maxRadius, limit, algorithm, CellProperty::Visible | CellProperty::Explored);\n  }\n\n  void SquareMap::computeLocalFieldOfVision(Vector2i pos, int maxRadius, FieldOfVisionLimit limit, FieldOfVision algorithm) {\n    computeGenericFieldOfVision(m_cells, pos, maxRadius, limit, algorithm, CellProperty::Visible);\n  }\n\n  bool SquareMap::isInFieldOfVision(Vector2i pos) const {\n    return m_cells(pos).test(CellProperty::Visible);\n  }\n\n  bool SquareMap::isExplored(Vector2i pos) const {\n    return m_cells(pos).test(CellProperty::Explored);\n  }\n\n  /*\n   * Route\n   */\n\n  namespace {\n\n    // Dijkstra\n\n    struct DijkstraHeapData {\n      Vector2i position;\n      float distance;\n    };\n\n    bool operator<(const DijkstraHeapData& lhs, const DijkstraHeapData& rhs) {\n      return lhs.distance > rhs.distance;\n    }\n\n    using DijkstraHeap = boost::heap::binomial_heap<DijkstraHeapData>;\n\n    struct DijkstraResultData {\n      float distance;\n      Vector2i previous;\n      DijkstraHeap::handle_type handle;\n    };\n\n    std::vector<Vector2i> computeDijkstra(const Array2D<Flags<CellProperty>, int>& cells, Vector2i origin, Vector2i target, float diagonalCost) {\n      DijkstraResultData defaultResult;\n      defaultResult.distance = std::numeric_limits<float>::infinity();\n      defaultResult.previous = { -1, -1 };\n\n      Array2D<DijkstraResultData, int> results(cells.getSize(), defaultResult);\n\n      results(origin).distance = 0.0f;\n\n      DijkstraHeap heap;\n\n      for (auto position : cells.getPositionRange()) {\n        const auto& cell = cells(position);\n\n        if (!cell.test(CellProperty::Walkable)) {\n          continue;\n        }\n\n        DijkstraHeapData data;\n        data.position = position;\n        data.distance = results(position).distance;\n\n        results(position).handle = heap.push(data);\n      }\n\n      while (!heap.empty()) {\n        DijkstraHeapData data = heap.top();\n        heap.pop();\n\n        for (auto position : cells.get8NeighborsRange(data.position)) {\n          assert(position != data.position);\n\n          const Flags<CellProperty>& value = cells(position);\n\n          if (!value.test(CellProperty::Walkable)) {\n            continue;\n          }\n\n          bool isDiagonal = (gf::manhattanDistance(data.position, position) == 2);\n\n          if (isDiagonal && diagonalCost == 0) {\n            continue;\n          }\n\n          float newDistance = results(data.position).distance + (isDiagonal ? diagonalCost : 1.0f);\n\n          if (newDistance < results(position).distance) {\n            auto& result = results(position);\n            result.distance = newDistance;\n            result.previous = data.position;\n\n            assert((*result.handle).position == position);\n            (*result.handle).distance = newDistance;\n            heap.increase(result.handle);\n          }\n        }\n      }\n\n      std::vector<Vector2i> route;\n      Vector2i curr = target;\n\n      while (curr != origin) {\n        if (curr.x == -1 || curr.y == -1) {\n          return {};\n        }\n        route.push_back(curr);\n        curr = results(curr).previous;\n      }\n\n      route.push_back(origin);\n      std::reverse(route.begin(), route.end());\n\n      assert(!route.empty());\n\n      return route;\n    }\n\n\n    // AStar\n\n    struct AStarHeapData {\n      Vector2i position;\n      float priority;\n    };\n\n    bool operator<(const AStarHeapData& lhs, const AStarHeapData& rhs) {\n      return lhs.priority > rhs.priority;\n    }\n\n    using AStarHeap = boost::heap::binomial_heap<AStarHeapData>;\n\n    enum class AStarState {\n      None,\n      Open,\n      Closed,\n    };\n\n    struct AStarResultData {\n      float distance;\n      Vector2i previous;\n      AStarState state;\n      AStarHeap::handle_type handle;\n    };\n\n    std::vector<Vector2i> computeAStar(const Array2D<Flags<CellProperty>, int>& cells, Vector2i origin, Vector2i target, float diagonalCost) {\n      AStarResultData defaultResult;\n      defaultResult.distance = std::numeric_limits<float>::infinity();\n      defaultResult.previous = { -1, -1 };\n      defaultResult.state = AStarState::None;\n\n      Array2D<AStarResultData, int> results(cells.getSize(), defaultResult);\n\n      results(origin).distance = 0.0f;\n      results(origin).state = AStarState::Open;\n\n      AStarHeap heap;\n      results(origin).handle = heap.push({ origin, 0.0f });\n\n      // see http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#heuristics-for-grid-maps\n      auto heuristic = [diagonalCost](Vector2i p0, Vector2i p1) {\n        if (diagonalCost == 0) {\n          return 1.0f * gf::manhattanDistance(p0, p1);\n        }\n\n        Vector2i d = gf::abs(p0 - p1);\n        return 1.0f * (d.x + d.y) + (diagonalCost - 2.0f) * std::min(d.x, d.y);\n      };\n\n      while (!heap.empty()) {\n        AStarHeapData data = heap.top();\n        heap.pop();\n\n        assert(results(data.position).state == AStarState::Open);\n\n        if (data.position == target) {\n          break;\n        }\n\n        results(data.position).state = AStarState::Closed;\n\n        for (auto position : cells.get8NeighborsRange(data.position)) {\n          assert(position != data.position);\n\n          const Flags<CellProperty>& value = cells(position);\n\n          if (!value.test(CellProperty::Walkable)) {\n            continue;\n          }\n\n          if (results(position).state == AStarState::Closed) {\n            continue;\n          }\n\n          bool isDiagonal = (gf::manhattanDistance(data.position, position) == 2);\n\n          if (isDiagonal && diagonalCost == 0) {\n            continue;\n          }\n\n          float newDistance = results(data.position).distance + (isDiagonal ? diagonalCost : 1.0f);\n\n          if (newDistance < results(position).distance) {\n            auto& result = results(position);\n            result.distance = newDistance;\n            result.previous = data.position;\n\n            float priority = newDistance + heuristic(position, target) * 1.001f;\n\n            if (result.state == AStarState::Open) {\n              assert((*result.handle).position == position);\n\n              if ((*result.handle).priority != priority) {\n                (*result.handle).priority = priority;\n                heap.update(result.handle);\n              }\n            } else {\n              assert(result.state == AStarState::None);\n              result.handle = heap.push({ position, priority });\n              result.state = AStarState::Open;\n            }\n          }\n        }\n      }\n\n      std::vector<Vector2i> route;\n      Vector2i curr = target;\n\n      while (curr != origin) {\n        if (curr.x == -1 || curr.y == -1) {\n          return {};\n        }\n\n        route.push_back(curr);\n        curr = results(curr).previous;\n      }\n\n      route.push_back(origin);\n      std::reverse(route.begin(), route.end());\n\n      assert(!route.empty());\n\n      return route;\n    }\n\n  } // anonymous namespace\n\n\n  std::vector<Vector2i> SquareMap::computeRoute(Vector2i origin, Vector2i target, float diagonalCost, Route algorithm) {\n    switch (algorithm) {\n      case Route::Dijkstra:\n        return computeDijkstra(m_cells, origin, target, diagonalCost);\n\n      case Route::AStar:\n        return computeAStar(m_cells, origin, target, diagonalCost);\n    }\n\n    return { };\n  }\n\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n}\n#endif\n}\n", "meta": {"hexsha": "fcbd4618744970abd338193f86af632b63f7003d", "size": 14145, "ext": "cc", "lang": "C++", "max_stars_repo_path": "library/core/Map.cc", "max_stars_repo_name": "TheCubeOfFire/gf", "max_stars_repo_head_hexsha": "f9587d46add949191fb075f143472033e51920c9", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library/core/Map.cc", "max_issues_repo_name": "TheCubeOfFire/gf", "max_issues_repo_head_hexsha": "f9587d46add949191fb075f143472033e51920c9", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/core/Map.cc", "max_forks_repo_name": "TheCubeOfFire/gf", "max_forks_repo_head_hexsha": "f9587d46add949191fb075f143472033e51920c9", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6336032389, "max_line_length": 194, "alphanum_fraction": 0.6015553199, "num_tokens": 3512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18242551491653522, "lm_q2_score": 0.02002344147220405, "lm_q1q2_score": 0.0036527866209679297}}
{"text": "#ifndef __TRANSFORM_UTILS__\n#define __TRANSFORM_UTILS__\n\n/**\n * Copyright (c) 2018, University Osnabrück\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 University Osnabrück 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 University Osnabrück 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 * TransformUtils.hpp\n *\n *  @date August 08, 2019\n *  @author Thomas Wiemann\n */\n\n#include \"lvr2/types/MatrixTypes.hpp\"\n#include \"lvr2/io/Model.hpp\"\n#include \"lvr2/io/CoordinateTransform.hpp\"\n\n#include <Eigen/Dense>\n\nnamespace lvr2\n{\n\n/**\n * @brief   Computes a Euler representation from the given transformation matrix\n * \n * @param  position     Will contain the position\n * @param  angles       Will contain the rotation angles in radians\n * @param  mat          The transformation matrix\n */\ntemplate<typename T>\nvoid getPoseFromMatrix(BaseVector<T>& position, BaseVector<T>& angles, const Transform<T>& mat);\n\n/**\n * @brief Transforms a registration matrix according to the given\n *        transformation matrix, i.e., applies @ref transform to @ref registration\n * \n * @param transform             A transformation matrix\n * @param registration          A matrix representing a registration (i.e. transformation) that\n * @return Transform<T>         The transformed registration matrix\n */\ntemplate<typename T>\nTransform<T> transformRegistration(const Transform<T>& transform, const Transform<T>& registration);\n\n/**\n * @brief   Transforms an slam6d transformation matrix into an Eigen 4x4 matrix.\n */\ntemplate<typename T>\nTransform<T> buildTransformation(T* alignxf);\n\n/**\n * @brief   Transforms (scale and switch coordinates) and reduces a model\n *          containing point cloud data using a modulo filter. Use this\n *          function the convert between different coordinate systems.\n *\n * @param   model       A model containing point cloud data\n * @param   modulo      The reduction factor for the modulo filter. Set to\n *                      1 to keep the original resolution.\n * @param   sx          Scaling factor in x direction\n * @param   sy          Scaling factor in y direction\n * @param   sz          Scaling factor in z direction\n * @param   xPos        Position of the x position in the input data, i.e,\n *                      \"which array position has the x coordinate that is written\n *                      to the output data in the input data\"\n * @param   yPos        Same as with xPos for y.\n * @param   zPos        Same as with xPos for z.\n */\ntemplate<typename T>\nvoid transformAndReducePointCloud(ModelPtr model, int modulo, \n        const T& sx, const T& sy, const T& sz, \n        const unsigned char& xPos, \n        const unsigned char& yPos, \n        const unsigned char& zPos);\n\n/**\n * @brief  Transforms (scale and switch coordinates) and reduces a model\n *         containing point cloud data using a modulo filter. Use this\n *         function the convert between different coordinate systems.          \n * \n * @param model         A model containing point cloud data \n * @param modulo        The reduction factor for the modulo filter. Set to\n *                      1 to keep the original resolution.\n * @param c             The coordinate transformation applied to the \\ref model\n */\ntemplate<typename T>\nvoid transformAndReducePointCloud(ModelPtr& model, int modulo, const CoordinateTransform<T>& c);\n\n/**\n * @brief   Transforms a model containing a point cloud according to the given\n *          transformation (usually from a .frames file)\n * @param   A model containing point cloud data.\n * @param   A transformation.\n */\ntemplate<typename T>\nvoid transformPointCloud(ModelPtr model, const Transform<T>& transformation);\n\n/**\n * @brief   Transforms the given source frame according to the given coordinate\n *          transform struct \n * \n * @param   frame           Source frame\n * @param   ct               Coordinate system transformation\n * @return                  The transformed frame\n */\ntemplate<typename T>\nTransform<T> transformFrame(const Transform<T>& frame, const CoordinateTransform<T>& ct);\n\n/**\n * @brief    Computes the inverse transformation from the given \n *          transformation matrix, which means if transform encodes\n *          the transformation A->B, the return will transform from \n *          B to A.\n * \n * @param transform             A transformation matrix\n * @return Transform<T>         The inverse transformation\n */\ntemplate<typename T>\nTransform<T> inverseTransform(const Transform<T>& transform);\n\n/**\n * @brief   Converts a Pose to a Matrix.\n * \n * @param position  The position of the Pose\n * @param rotation  The rotation in radians\n * @return          The Matrix representation of the Pose\n */\ntemplate<typename T>\nTransform<T> poseToMatrix(const Vector3<T>& position, const Vector3<T>& rotation);\n\n/**\n * @brief   Extracts the Pose from a Matrix\n * \n * @param pose      A Matrix representing a Pose\n * @param position  Output for the position of the Pose\n * @param rotation  Output for the rotation in radians\n */\ntemplate<typename T>\nvoid matrixToPose(const Transform<T>& mat, Vector3<T>& position, Vector3<T>& rotation);\n\n/**\n * @brief Converts a transformation matrix that is used in riegl coordinate system into\n *        a transformation matrix that is used in slam6d coordinate system.\n *\n * @param    in    The transformation matrix in riegl coordinate system\n *\n * @return The transformation matrix in slam6d coordinate system\n */\ntemplate <typename T>\nstatic Transform<T> rieglToSLAM6DTransform(const Transform<T>& in)\n{\n       Transform<T> ret;\n\n        ret(0) = in(5);\n        ret(1) = -in(9);\n        ret(2) = -in(1);\n        ret(3) = -in(13);\n        ret(4) = -in(6);\n        ret(5) = in(10);\n        ret(6) = in(2);\n        ret(7) = in(14);\n        ret(8) = -in(4);\n        ret(9) = in(8);\n        ret(10) = in(0);\n        ret(11) = in(12);\n        ret(12) = -100*in(7);\n        ret(13) = 100*in(11);\n        ret(14) = 100*in(3);\n        ret(15) = in(15);\n\n        return ret;\n}\n\n/**\n * @brief Converts a transformation matrix that is used in slam6d coordinate system into\n *        a transformation matrix that is used in riegl coordinate system.\n *\n * @param    in    The transformation matrix in slam6d coordinate system\n *\n * @return The transformation matrix in riegl coordinate system\n */\ntemplate <typename T>\nstatic Transform<T> slam6dToRieglTransform(const Transform<T> &in)\n{\n    Transform<T> ret;\n\n    ret(0) = in(10);\n    ret(1) = -in(2);\n    ret(2) = in(6);\n    ret(3) = in(14)/100.0;\n    ret(4) = -in(8);\n    ret(5) = in(0);\n    ret(6) = -in(4);\n    ret(7) = -in(12)/100.0;\n    ret(8) = in(9);\n    ret(9) = -in(1);\n    ret(10) = in(5);\n    ret(11) = in(13)/100.0;\n    ret(12) = in(11);\n    ret(13) = -in(3);\n    ret(14) = in(7);\n    ret(15) = in(15);\n\n    return ret;\n}\n\ntemplate <typename T>\nstatic Vector3<T> slam6DToRieglPoint(const Vector3<T> &in)\n{\n    return Vector3<T>(\n        in.coeff(2)   / static_cast<T>(100.0),\n        - in.coeff(0) / static_cast<T>(100.0),\n        in.coeff(1)   / static_cast<T>(100.0)\n    );\n}\n\n/////////////////////////////////\n// Change Coodinate Systems\n/////////////////////////////////\n\n///////////////////////\n// 1) CS -> LVR\n//////////////\n\n/**\n * @brief Slam6D to LVR coordinate change: Point\n * \n *  Slam6D\n * \n *     y  z    \n *     | /\n *     |/___ x\n *     \n *  - x: right\n *  - y: up\n *  - z: front\n *  - scale: cm\n * \n *  LVR / ROS\n *        z  x    \n *        | /\n *   y ___|/ \n * \n *  - x: front\n *  - y: left\n *  - z: up\n *  - scale: m\n * \n */\ntemplate <typename T>\nstatic Vector3<T> slam6dToLvr(const Vector3<T>& in)\n{\n    return Vector3<T>(\n        in.coeff(2) / static_cast<T>(100.0),\n        - in.coeff(0) / static_cast<T>(100.0),\n        in.coeff(1) / static_cast<T>(100.0)\n    );\n}\n\ntemplate<typename T>\nstatic Rotation<T> slam6dToLvr(const Rotation<T>& in)\n{\n    Rotation<T> ret;\n    \n    // use coeff functions to access elements without range check\n    // should be faster?\n\n    // OLD CODE: why transpose?\n    // ret.coeffRef(0, 0) =  in.coeff(2, 2);\n    // ret.coeffRef(0, 1) = -in.coeff(0, 2);\n    // ret.coeffRef(0, 2) =  in.coeff(1, 2);\n    // ret.coeffRef(1, 0) = -in.coeff(2, 0);\n    // ret.coeffRef(1, 1) =  in.coeff(0, 0);\n    // ret.coeffRef(1, 2) = -in.coeff(1, 0);\n    // ret.coeffRef(2, 0) =  in.coeff(2, 1);\n    // ret.coeffRef(2, 1) = -in.coeff(0, 1);\n    // ret.coeffRef(2, 2) =  in.coeff(1, 1);\n\n    ret.coeffRef(0, 0) =  in.coeff(2, 2);\n    ret.coeffRef(1, 0) = -in.coeff(0, 2);\n    ret.coeffRef(2, 0) =  in.coeff(1, 2);\n    ret.coeffRef(0, 1) = -in.coeff(2, 0);\n    ret.coeffRef(1, 1) =  in.coeff(0, 0);\n    ret.coeffRef(2, 1) = -in.coeff(1, 0);\n    ret.coeffRef(0, 2) =  in.coeff(2, 1);\n    ret.coeffRef(1, 2) = -in.coeff(0, 1);\n    ret.coeffRef(2, 2) =  in.coeff(1, 1);\n    \n    return ret;\n}\n\ntemplate <typename T>\nstatic Transform<T> slam6dToLvr(const Transform<T> &in)\n{\n    Transform<T> ret;\n\n    // Rotation\n    const Rotation<T> R = in.template block<3,3>(0,0);\n    ret.template block<3,3>(0,0) = slam6dToLvr(R);\n\n    // Translation\n    ret.coeffRef(0, 3) =  in.coeff(2, 3)/static_cast<T>(100.0);\n    ret.coeffRef(1, 3) = -in.coeff(0, 3)/static_cast<T>(100.0);\n    ret.coeffRef(2, 3) =  in.coeff(1, 3)/static_cast<T>(100.0);\n    ret.coeffRef(3, 0) =  in.coeff(3, 2)/static_cast<T>(100.0);\n    ret.coeffRef(3, 1) = -in.coeff(3, 0)/static_cast<T>(100.0);\n    ret.coeffRef(3, 2) =  in.coeff(3, 1)/static_cast<T>(100.0);\n    ret.coeffRef(3, 3) =  in.coeff(3, 3);\n\n    return ret;\n}\n\n/**\n * @brief OpenCV to Lvr coordinate change: Point\n * \n *  OpenCV\n * \n *        z    \n *       /\n *      /___ x\n *     |\n *     |\n *     y\n *  \n *  - x: right\n *  - y: down\n *  - z: front\n *  - scale: m\n * \n *  LVR / ROS\n *        z  x    \n *        | /\n *   y ___|/ \n * \n *  - x: front\n *  - y: left\n *  - z: up\n *  - scale: m\n * \n */\ntemplate <typename T>\nstatic Vector3<T> openCvToLvr(const Vector3<T>& in)\n{\n    return Vector3<T>(\n        in.coeff(2),\n        -in.coeff(0),\n        -in.coeff(1)\n    );\n}\n\ntemplate <typename T>\nstatic Rotation<T> openCvToLvr(const Rotation<T> &in)\n{\n    Rotation<T> ret;\n\n    ret.coeffRef(0,0) =  in.coeff(2,2);\n    ret.coeffRef(0,1) = -in.coeff(2,0);\n    ret.coeffRef(0,2) = -in.coeff(2,1);\n    ret.coeffRef(1,0) = -in.coeff(0,2);\n    ret.coeffRef(1,1) =  in.coeff(0,0);\n    ret.coeffRef(1,2) =  in.coeff(0,1);\n    ret.coeffRef(2,0) = -in.coeff(1,2);\n    ret.coeffRef(2,1) =  in.coeff(1,0);\n    ret.coeffRef(2,2) =  in.coeff(1,1);\n\n    return ret;\n}\n\ntemplate <typename T>\nstatic Transform<T> openCvToLvr(const Transform<T> &in)\n{\n    Transform<T> ret;\n\n    const Rotation<T> R = in.template block<3,3>(0,0);\n    ret.template block<3,3>(0,0) = openCvToLvr(R);\n\n    ret.coeffRef(0,3) =  in.coeff(2,3);\n    ret.coeffRef(1,3) = -in.coeff(0,3);\n    ret.coeffRef(2,3) = -in.coeff(1,3);\n\n    ret.coeffRef(3,0) =  in.coeff(3,2);\n    ret.coeffRef(3,1) = -in.coeff(3,0);\n    ret.coeffRef(3,2) = -in.coeff(3,1);\n\n    ret.coeffRef(3,3) =  in.coeff(3,3);\n\n    return ret;\n}\n\n\n////////////////\n// 2) Lvr -> CS\n////////////////\n\n\n\n/**\n * @brief Lvr to Slam6D coordinate change: Point\n * \n *  Slam6D\n * \n *     y  z    \n *     | /\n *     |/___ x\n *     \n *  - x: right\n *  - y: up\n *  - z: front\n *  - scale: cm\n * \n *  LVR / ROS\n *        z  x    \n *        | /\n *   y ___|/ \n * \n *  - x: front\n *  - y: left\n *  - z: up\n *  - scale: m\n */\ntemplate <typename T>\nstatic Vector3<T> lvrToSlam6d(const Vector3<T>& in)\n{\n    return Vector3<T>(\n        -in.coeff(1) * static_cast<T>(100.0),\n        in.coeff(2) * static_cast<T>(100.0),\n        in.coeff(0) * static_cast<T>(100.0)\n    );\n}\n\ntemplate<typename T>\nstatic Rotation<T> lvrToSlam6d(const Rotation<T>& in)\n{\n    Rotation<T> ret;\n    \n    // use coeff functions to access elements without range check\n    // should be faster?\n\n    // OLD CODE: why transpose?\n    // ret.coeffRef(0, 0) =  in.coeff(1, 1); // in.coeff(1, 1)\n    // ret.coeffRef(0, 1) = -in.coeff(2, 1); // in.coeff(1, 2)\n    // ret.coeffRef(0, 2) = -in.coeff(0, 1); // in.coeff(1, 0)\n    // ret.coeffRef(1, 0) = -in.coeff(1, 2);\n    // ret.coeffRef(1, 1) =  in.coeff(2, 2);\n    // ret.coeffRef(1, 2) =  in.coeff(0, 2);\n    // ret.coeffRef(2, 0) = -in.coeff(1, 0);\n    // ret.coeffRef(2, 1) =  in.coeff(2, 0);\n    // ret.coeffRef(2, 2) =  in.coeff(0, 0);\n\n    ret.coeffRef(0, 0) =  in.coeff(1, 1); // in.coeff(1, 1)\n    ret.coeffRef(1, 0) = -in.coeff(2, 1); // in.coeff(1, 2)\n    ret.coeffRef(2, 0) = -in.coeff(0, 1); // in.coeff(1, 0)\n    ret.coeffRef(0, 1) = -in.coeff(1, 2);\n    ret.coeffRef(1, 1) =  in.coeff(2, 2);\n    ret.coeffRef(2, 1) =  in.coeff(0, 2);\n    ret.coeffRef(0, 2) = -in.coeff(1, 0);\n    ret.coeffRef(1, 2) =  in.coeff(2, 0);\n    ret.coeffRef(2, 2) =  in.coeff(0, 0);\n    \n    return ret;\n}\n\ntemplate <typename T>\nstatic Transform<T> lvrToSlam6d(const Transform<T> &in)\n{\n    Transform<T> ret;\n\n    // Rotation\n    const Rotation<T> R = in.template block<3,3>(0,0);\n    ret.template block<3,3>(0,0) = lvrToSlam6d(R);\n\n    // Translation\n    ret.coeffRef(0, 3) = -static_cast<T>(100.0) * in.coeff(1, 3);\n    ret.coeffRef(1, 3) =  static_cast<T>(100.0) * in.coeff(2, 3);\n    ret.coeffRef(2, 3) =  static_cast<T>(100.0) * in.coeff(0, 3);\n    ret.coeffRef(3, 0) = -static_cast<T>(100.0) * in.coeff(3, 1);\n    ret.coeffRef(3, 1) =  static_cast<T>(100.0) * in.coeff(3, 2);\n    ret.coeffRef(3, 2) =  static_cast<T>(100.0) * in.coeff(3, 0);\n\n    ret.coeffRef(3, 3) = in.coeff(3, 3);\n\n    return ret;\n}\n\n\n\n/**\n * @brief Lvr to OpenCV coordinate change: Point\n * \n *  OpenCV\n * \n *        z    \n *       /\n *      /___ x\n *     |\n *     |\n *     y\n *  \n * - x: right\n * - y: down\n * - z: front\n * - scale: m\n * \n *  LVR / ROS\n *        z  x    \n *        | /\n *   y ___|/ \n * \n *  - x: front\n *  - y: left\n *  - z: up\n *  - scale: m\n * \n */\ntemplate <typename T>\nstatic Vector3<T> lvrToOpenCv(const Vector3<T>& in)\n{\n    return Vector3<T>(\n        -in.coeff(1),\n        -in.coeff(2),\n        in.coeff(0)\n    );\n}\n\ntemplate <typename T>\nstatic Rotation<T> lvrToOpenCv(const Rotation<T>& in)\n{\n    Rotation<T> ret;\n\n    ret.coeffRef(0,0) =  in.coeff(1,1);\n    ret.coeffRef(0,1) =  in.coeff(1,2);\n    ret.coeffRef(0,2) = -in.coeff(1,0);\n    ret.coeffRef(1,0) =  in.coeff(2,1);\n    ret.coeffRef(1,1) =  in.coeff(2,2);\n    ret.coeffRef(1,2) = -in.coeff(2,0);\n    ret.coeffRef(2,0) = -in.coeff(0,1);\n    ret.coeffRef(2,1) = -in.coeff(0,2);\n    ret.coeffRef(2,2) =  in.coeff(0,0);\n\n    return ret;\n}\n\ntemplate <typename T>\nstatic Transform<T> lvrToOpenCv(const Transform<T> &in)\n{\n    Transform<T> ret;\n\n    const Rotation<T> R = in.template block<3,3>(0,0);\n    ret.template block<3,3>(0,0) = lvrToOpenCv(R);\n\n    ret.coeffRef(0,3) = -in.coeff(1,3);\n    ret.coeffRef(1,3) = -in.coeff(2,3);\n    ret.coeffRef(2,3) =  in.coeff(0,3);\n\n    ret.coeffRef(3,0) = -in.coeff(3,1);\n    ret.coeffRef(3,1) = -in.coeff(3,2);\n    ret.coeffRef(3,2) =  in.coeff(3,0);\n\n    ret.coeffRef(3,3) =  in.coeff(3,3);\n\n    return ret;\n}\n\ntemplate<typename T>\nvoid extrinsicsToEuler(Extrinsics<T> mat, T* pose)\n{\n    T *m = mat.data();\n    if (pose != 0)\n    {\n        float _trX, _trY;\n        if (m[0] > 0.0)\n        {\n            pose[4] = asin(m[8]);\n        }\n        else\n        {\n            pose[4] = (float)M_PI - asin(m[8]);\n        }\n        // rPosTheta[1] =  asin( m[8]);      // Calculate Y-axis angle\n\n        float C = cos(pose[4]);\n        if (fabs(C) > 0.005)\n        {                     // Gimball lock?\n            _trX = m[10] / C; // No, so get X-axis angle\n            _trY = -m[9] / C;\n            pose[3] = atan2(_trY, _trX);\n            _trX = m[0] / C; // Get Z-axis angle\n            _trY = -m[4] / C;\n            pose[5] = atan2(_trY, _trX);\n        }\n        else\n        {                  // Gimball lock has occurred\n            pose[3] = 0.0; // Set X-axis angle to zero\n            _trX = m[5];   //1          // And calculate Z-axis angle\n            _trY = m[1];   //2\n            pose[5] = atan2(_trY, _trX);\n        }\n\n        // cout << pose[3] << \" \" << pose[4] << \" \" << pose[5] << endl;\n\n        pose[0] = m[12];\n        pose[1] = m[13];\n        pose[2] = m[14];\n    }\n}\n\ntemplate<typename T>\nvoid eigenToEuler(Transform<T>& mat, T* pose)\n{\n    T *m = mat.data();\n    if (pose != 0)\n    {\n        float _trX, _trY;\n        if (m[0] > 0.0)\n        {\n            pose[4] = asin(m[8]);\n        }\n        else\n        {\n            pose[4] = (float)M_PI - asin(m[8]);\n        }\n        // rPosTheta[1] =  asin( m[8]);      // Calculate Y-axis angle\n\n        float C = cos(pose[4]);\n        if (fabs(C) > 0.005)\n        {                     // Gimball lock?\n            _trX = m[10] / C; // No, so get X-axis angle\n            _trY = -m[9] / C;\n            pose[3] = atan2(_trY, _trX);\n            _trX = m[0] / C; // Get Z-axis angle\n            _trY = -m[4] / C;\n            pose[5] = atan2(_trY, _trX);\n        }\n        else\n        {                  // Gimball lock has occurred\n            pose[3] = 0.0; // Set X-axis angle to zero\n            _trX = m[5];   //1          // And calculate Z-axis angle\n            _trY = m[1];   //2\n            pose[5] = atan2(_trY, _trX);\n        }\n\n        // cout << pose[3] << \" \" << pose[4] << \" \" << pose[5] << endl;\n\n        pose[0] = m[12];\n        pose[1] = m[13];\n        pose[2] = m[14];\n    }\n}\n\n\n\n} // namespace lvr2\n\n#include \"TransformUtils.tcc\"\n\n#endif\n", "meta": {"hexsha": "20f69dcc5db6fa23773e50a25e82875a2c6fbc94", "size": 18718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lvr2/registration/TransformUtils.hpp", "max_stars_repo_name": "uos/lvr", "max_stars_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2019-06-19T15:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T03:08:24.000Z", "max_issues_repo_path": "include/lvr2/registration/TransformUtils.hpp", "max_issues_repo_name": "uos/lvr", "max_issues_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T16:19:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:31:25.000Z", "max_forks_repo_path": "include/lvr2/registration/TransformUtils.hpp", "max_forks_repo_name": "uos/lvr", "max_forks_repo_head_hexsha": "9bb03a30441b027c39db967318877e03725112d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-04-16T11:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-26T07:47:44.000Z", "avg_line_length": 27.5670103093, "max_line_length": 100, "alphanum_fraction": 0.567208035, "num_tokens": 5894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535945, "lm_q2_score": 0.014957083409757198, "lm_q1q2_score": 0.0036226897911578854}}
{"text": "//=======================================================================\r\n// Copyright (C) 2012 Flavio De Lorenzi (fdlorenzi@gmail.com)\r\n// Copyright (C) 2013 Jakob Lykke Andersen, University of Southern Denmark\r\n// (jlandersen@imada.sdu.dk)\r\n//\r\n// The algorithm implemented here is derived from original ideas by\r\n// Pasquale Foggia and colaborators. For further information see\r\n// e.g. Cordella et al. 2001, 2004.\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// Revision History:\r\n//   8 April 2013: Fixed a typo in vf2_print_callback. (Flavio De Lorenzi)\r\n\r\n#ifndef BOOST_VF2_SUB_GRAPH_ISO_HPP\r\n#define BOOST_VF2_SUB_GRAPH_ISO_HPP\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <iterator>\r\n#include <vector>\r\n#include <utility>\r\n\r\n#include <boost/assert.hpp>\r\n#include <boost/concept/assert.hpp>\r\n#include <boost/concept_check.hpp>\r\n#include <boost/graph/graph_utility.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/mcgregor_common_subgraphs.hpp> // for always_equivalent\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/type_traits/has_less.hpp>\r\n#include <boost/mpl/int.hpp>\r\n#include <boost/range/algorithm/sort.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n#include <boost/utility/enable_if.hpp>\r\n\r\n#ifndef BOOST_GRAPH_ITERATION_MACROS_HPP\r\n#define BOOST_ISO_INCLUDED_ITER_MACROS // local macro, see bottom of file\r\n#include <boost/graph/iteration_macros.hpp>\r\n#endif\r\n\r\nnamespace boost\r\n{\r\n\r\n// Default print_callback\r\ntemplate < typename Graph1, typename Graph2 > struct vf2_print_callback\r\n{\r\n\r\n    vf2_print_callback(const Graph1& graph1, const Graph2& graph2)\r\n    : graph1_(graph1), graph2_(graph2)\r\n    {\r\n    }\r\n\r\n    template < typename CorrespondenceMap1To2, typename CorrespondenceMap2To1 >\r\n    bool operator()(CorrespondenceMap1To2 f, CorrespondenceMap2To1) const\r\n    {\r\n\r\n        // Print (sub)graph isomorphism map\r\n        BGL_FORALL_VERTICES_T(v, graph1_, Graph1)\r\n        std::cout << '(' << get(vertex_index_t(), graph1_, v) << \", \"\r\n                  << get(vertex_index_t(), graph2_, get(f, v)) << \") \";\r\n\r\n        std::cout << std::endl;\r\n\r\n        return true;\r\n    }\r\n\r\nprivate:\r\n    const Graph1& graph1_;\r\n    const Graph2& graph2_;\r\n};\r\n\r\nnamespace detail\r\n{\r\n\r\n    // State associated with a single graph (graph_this)\r\n    template < typename GraphThis, typename GraphOther, typename IndexMapThis,\r\n        typename IndexMapOther >\r\n    class base_state\r\n    {\r\n\r\n        typedef typename graph_traits< GraphThis >::vertex_descriptor\r\n            vertex_this_type;\r\n        typedef typename graph_traits< GraphOther >::vertex_descriptor\r\n            vertex_other_type;\r\n\r\n        typedef\r\n            typename graph_traits< GraphThis >::vertices_size_type size_type;\r\n\r\n        const GraphThis& graph_this_;\r\n        const GraphOther& graph_other_;\r\n\r\n        IndexMapThis index_map_this_;\r\n        IndexMapOther index_map_other_;\r\n\r\n        std::vector< vertex_other_type > core_vec_;\r\n        typedef iterator_property_map<\r\n            typename std::vector< vertex_other_type >::iterator, IndexMapThis,\r\n            vertex_other_type, vertex_other_type& >\r\n            core_map_type;\r\n        core_map_type core_;\r\n\r\n        std::vector< size_type > in_vec_, out_vec_;\r\n        typedef iterator_property_map<\r\n            typename std::vector< size_type >::iterator, IndexMapThis,\r\n            size_type, size_type& >\r\n            in_out_map_type;\r\n        in_out_map_type in_, out_;\r\n\r\n        size_type term_in_count_, term_out_count_, term_both_count_,\r\n            core_count_;\r\n\r\n        // Forbidden\r\n        base_state(const base_state&);\r\n        base_state& operator=(const base_state&);\r\n\r\n    public:\r\n        base_state(const GraphThis& graph_this, const GraphOther& graph_other,\r\n            IndexMapThis index_map_this, IndexMapOther index_map_other)\r\n        : graph_this_(graph_this)\r\n        , graph_other_(graph_other)\r\n        , index_map_this_(index_map_this)\r\n        , index_map_other_(index_map_other)\r\n        , core_vec_(num_vertices(graph_this_),\r\n              graph_traits< GraphOther >::null_vertex())\r\n        , core_(core_vec_.begin(), index_map_this_)\r\n        , in_vec_(num_vertices(graph_this_), 0)\r\n        , out_vec_(num_vertices(graph_this_), 0)\r\n        , in_(in_vec_.begin(), index_map_this_)\r\n        , out_(out_vec_.begin(), index_map_this_)\r\n        , term_in_count_(0)\r\n        , term_out_count_(0)\r\n        , term_both_count_(0)\r\n        , core_count_(0)\r\n        {\r\n        }\r\n\r\n        // Adds a vertex pair to the state of graph graph_this\r\n        void push(\r\n            const vertex_this_type& v_this, const vertex_other_type& v_other)\r\n        {\r\n\r\n            ++core_count_;\r\n\r\n            put(core_, v_this, v_other);\r\n\r\n            if (!get(in_, v_this))\r\n            {\r\n                put(in_, v_this, core_count_);\r\n                ++term_in_count_;\r\n                if (get(out_, v_this))\r\n                    ++term_both_count_;\r\n            }\r\n\r\n            if (!get(out_, v_this))\r\n            {\r\n                put(out_, v_this, core_count_);\r\n                ++term_out_count_;\r\n                if (get(in_, v_this))\r\n                    ++term_both_count_;\r\n            }\r\n\r\n            BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis)\r\n            {\r\n                vertex_this_type w = source(e, graph_this_);\r\n                if (!get(in_, w))\r\n                {\r\n                    put(in_, w, core_count_);\r\n                    ++term_in_count_;\r\n                    if (get(out_, w))\r\n                        ++term_both_count_;\r\n                }\r\n            }\r\n\r\n            BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis)\r\n            {\r\n                vertex_this_type w = target(e, graph_this_);\r\n                if (!get(out_, w))\r\n                {\r\n                    put(out_, w, core_count_);\r\n                    ++term_out_count_;\r\n                    if (get(in_, w))\r\n                        ++term_both_count_;\r\n                }\r\n            }\r\n        }\r\n\r\n        // Removes vertex pair from state of graph_this\r\n        void pop(const vertex_this_type& v_this, const vertex_other_type&)\r\n        {\r\n\r\n            if (!core_count_)\r\n                return;\r\n\r\n            if (get(in_, v_this) == core_count_)\r\n            {\r\n                put(in_, v_this, 0);\r\n                --term_in_count_;\r\n                if (get(out_, v_this))\r\n                    --term_both_count_;\r\n            }\r\n\r\n            BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis)\r\n            {\r\n                vertex_this_type w = source(e, graph_this_);\r\n                if (get(in_, w) == core_count_)\r\n                {\r\n                    put(in_, w, 0);\r\n                    --term_in_count_;\r\n                    if (get(out_, w))\r\n                        --term_both_count_;\r\n                }\r\n            }\r\n\r\n            if (get(out_, v_this) == core_count_)\r\n            {\r\n                put(out_, v_this, 0);\r\n                --term_out_count_;\r\n                if (get(in_, v_this))\r\n                    --term_both_count_;\r\n            }\r\n\r\n            BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis)\r\n            {\r\n                vertex_this_type w = target(e, graph_this_);\r\n                if (get(out_, w) == core_count_)\r\n                {\r\n                    put(out_, w, 0);\r\n                    --term_out_count_;\r\n                    if (get(in_, w))\r\n                        --term_both_count_;\r\n                }\r\n            }\r\n            put(core_, v_this, graph_traits< GraphOther >::null_vertex());\r\n\r\n            --core_count_;\r\n        }\r\n\r\n        // Returns true if the in-terminal set is not empty\r\n        bool term_in() const { return core_count_ < term_in_count_; }\r\n\r\n        // Returns true if vertex belongs to the in-terminal set\r\n        bool term_in(const vertex_this_type& v) const\r\n        {\r\n            return (get(in_, v) > 0)\r\n                && (get(core_, v) == graph_traits< GraphOther >::null_vertex());\r\n        }\r\n\r\n        // Returns true if the out-terminal set is not empty\r\n        bool term_out() const { return core_count_ < term_out_count_; }\r\n\r\n        // Returns true if vertex belongs to the out-terminal set\r\n        bool term_out(const vertex_this_type& v) const\r\n        {\r\n            return (get(out_, v) > 0)\r\n                && (get(core_, v) == graph_traits< GraphOther >::null_vertex());\r\n        }\r\n\r\n        // Returns true of both (in- and out-terminal) sets are not empty\r\n        bool term_both() const { return core_count_ < term_both_count_; }\r\n\r\n        // Returns true if vertex belongs to both (in- and out-terminal) sets\r\n        bool term_both(const vertex_this_type& v) const\r\n        {\r\n            return (get(in_, v) > 0) && (get(out_, v) > 0)\r\n                && (get(core_, v) == graph_traits< GraphOther >::null_vertex());\r\n        }\r\n\r\n        // Returns true if vertex belongs to the core map, i.e. it is in the\r\n        // present mapping\r\n        bool in_core(const vertex_this_type& v) const\r\n        {\r\n            return get(core_, v) != graph_traits< GraphOther >::null_vertex();\r\n        }\r\n\r\n        // Returns the number of vertices in the mapping\r\n        size_type count() const { return core_count_; }\r\n\r\n        // Returns the image (in graph_other) of vertex v (in graph_this)\r\n        vertex_other_type core(const vertex_this_type& v) const\r\n        {\r\n            return get(core_, v);\r\n        }\r\n\r\n        // Returns the mapping\r\n        core_map_type get_map() const { return core_; }\r\n\r\n        // Returns the \"time\" (or depth) when vertex was added to the\r\n        // in-terminal set\r\n        size_type in_depth(const vertex_this_type& v) const\r\n        {\r\n            return get(in_, v);\r\n        }\r\n\r\n        // Returns the \"time\" (or depth) when vertex was added to the\r\n        // out-terminal set\r\n        size_type out_depth(const vertex_this_type& v) const\r\n        {\r\n            return get(out_, v);\r\n        }\r\n\r\n        // Returns the terminal set counts\r\n        boost::tuple< size_type, size_type, size_type > term_set() const\r\n        {\r\n            return boost::make_tuple(\r\n                term_in_count_, term_out_count_, term_both_count_);\r\n        }\r\n    };\r\n\r\n    // Function object that checks whether a valid edge\r\n    // exists. For multi-graphs matched edges are excluded\r\n    template < typename Graph, typename Enable = void >\r\n    struct equivalent_edge_exists\r\n    {\r\n        typedef\r\n            typename boost::graph_traits< Graph >::edge_descriptor edge_type;\r\n\r\n        BOOST_CONCEPT_ASSERT((LessThanComparable< edge_type >));\r\n\r\n        template < typename EdgePredicate >\r\n        bool operator()(typename graph_traits< Graph >::vertex_descriptor s,\r\n            typename graph_traits< Graph >::vertex_descriptor t,\r\n            EdgePredicate is_valid_edge, const Graph& g)\r\n        {\r\n\r\n            BGL_FORALL_OUTEDGES_T(s, e, g, Graph)\r\n            {\r\n                if ((target(e, g) == t) && is_valid_edge(e)\r\n                    && (matched_edges_.find(e) == matched_edges_.end()))\r\n                {\r\n                    matched_edges_.insert(e);\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n    private:\r\n        std::set< edge_type > matched_edges_;\r\n    };\r\n\r\n    template < typename Graph >\r\n    struct equivalent_edge_exists< Graph,\r\n        typename boost::disable_if< is_multigraph< Graph > >::type >\r\n    {\r\n        template < typename EdgePredicate >\r\n        bool operator()(typename graph_traits< Graph >::vertex_descriptor s,\r\n            typename graph_traits< Graph >::vertex_descriptor t,\r\n            EdgePredicate is_valid_edge, const Graph& g)\r\n        {\r\n\r\n            typename graph_traits< Graph >::edge_descriptor e;\r\n            bool found;\r\n            boost::tie(e, found) = edge(s, t, g);\r\n            if (!found)\r\n                return false;\r\n            else if (is_valid_edge(e))\r\n                return true;\r\n\r\n            return false;\r\n        }\r\n    };\r\n\r\n    // Generates a predicate for edge e1 given  a binary predicate and a\r\n    // fixed edge e2\r\n    template < typename Graph1, typename Graph2,\r\n        typename EdgeEquivalencePredicate >\r\n    struct edge1_predicate\r\n    {\r\n\r\n        edge1_predicate(EdgeEquivalencePredicate edge_comp,\r\n            typename graph_traits< Graph2 >::edge_descriptor e2)\r\n        : edge_comp_(edge_comp), e2_(e2)\r\n        {\r\n        }\r\n\r\n        bool operator()(typename graph_traits< Graph1 >::edge_descriptor e1)\r\n        {\r\n            return edge_comp_(e1, e2_);\r\n        }\r\n\r\n        EdgeEquivalencePredicate edge_comp_;\r\n        typename graph_traits< Graph2 >::edge_descriptor e2_;\r\n    };\r\n\r\n    // Generates a predicate for edge e2 given given a binary predicate and a\r\n    // fixed edge e1\r\n    template < typename Graph1, typename Graph2,\r\n        typename EdgeEquivalencePredicate >\r\n    struct edge2_predicate\r\n    {\r\n\r\n        edge2_predicate(EdgeEquivalencePredicate edge_comp,\r\n            typename graph_traits< Graph1 >::edge_descriptor e1)\r\n        : edge_comp_(edge_comp), e1_(e1)\r\n        {\r\n        }\r\n\r\n        bool operator()(typename graph_traits< Graph2 >::edge_descriptor e2)\r\n        {\r\n            return edge_comp_(e1_, e2);\r\n        }\r\n\r\n        EdgeEquivalencePredicate edge_comp_;\r\n        typename graph_traits< Graph1 >::edge_descriptor e1_;\r\n    };\r\n\r\n    enum problem_selector\r\n    {\r\n        subgraph_mono,\r\n        subgraph_iso,\r\n        isomorphism\r\n    };\r\n\r\n    // The actual state associated with both graphs\r\n    template < typename Graph1, typename Graph2, typename IndexMap1,\r\n        typename IndexMap2, typename EdgeEquivalencePredicate,\r\n        typename VertexEquivalencePredicate, typename SubGraphIsoMapCallback,\r\n        problem_selector problem_selection >\r\n    class state\r\n    {\r\n\r\n        typedef typename graph_traits< Graph1 >::vertex_descriptor vertex1_type;\r\n        typedef typename graph_traits< Graph2 >::vertex_descriptor vertex2_type;\r\n\r\n        typedef typename graph_traits< Graph1 >::edge_descriptor edge1_type;\r\n        typedef typename graph_traits< Graph2 >::edge_descriptor edge2_type;\r\n\r\n        typedef typename graph_traits< Graph1 >::vertices_size_type\r\n            graph1_size_type;\r\n        typedef typename graph_traits< Graph2 >::vertices_size_type\r\n            graph2_size_type;\r\n\r\n        const Graph1& graph1_;\r\n        const Graph2& graph2_;\r\n\r\n        IndexMap1 index_map1_;\r\n\r\n        EdgeEquivalencePredicate edge_comp_;\r\n        VertexEquivalencePredicate vertex_comp_;\r\n\r\n        base_state< Graph1, Graph2, IndexMap1, IndexMap2 > state1_;\r\n        base_state< Graph2, Graph1, IndexMap2, IndexMap1 > state2_;\r\n\r\n        // Three helper functions used in Feasibility and Valid functions to\r\n        // test terminal set counts when testing for:\r\n        // - graph sub-graph monomorphism, or\r\n        inline bool comp_term_sets(graph1_size_type a, graph2_size_type b,\r\n            boost::mpl::int_< subgraph_mono >) const\r\n        {\r\n            return a <= b;\r\n        }\r\n\r\n        // - graph sub-graph isomorphism, or\r\n        inline bool comp_term_sets(graph1_size_type a, graph2_size_type b,\r\n            boost::mpl::int_< subgraph_iso >) const\r\n        {\r\n            return a <= b;\r\n        }\r\n\r\n        // - graph isomorphism\r\n        inline bool comp_term_sets(graph1_size_type a, graph2_size_type b,\r\n            boost::mpl::int_< isomorphism >) const\r\n        {\r\n            return a == b;\r\n        }\r\n\r\n        // Forbidden\r\n        state(const state&);\r\n        state& operator=(const state&);\r\n\r\n    public:\r\n        state(const Graph1& graph1, const Graph2& graph2, IndexMap1 index_map1,\r\n            IndexMap2 index_map2, EdgeEquivalencePredicate edge_comp,\r\n            VertexEquivalencePredicate vertex_comp)\r\n        : graph1_(graph1)\r\n        , graph2_(graph2)\r\n        , index_map1_(index_map1)\r\n        , edge_comp_(edge_comp)\r\n        , vertex_comp_(vertex_comp)\r\n        , state1_(graph1, graph2, index_map1, index_map2)\r\n        , state2_(graph2, graph1, index_map2, index_map1)\r\n        {\r\n        }\r\n\r\n        // Add vertex pair to the state\r\n        void push(const vertex1_type& v, const vertex2_type& w)\r\n        {\r\n            state1_.push(v, w);\r\n            state2_.push(w, v);\r\n        }\r\n\r\n        // Remove vertex pair from state\r\n        void pop(const vertex1_type& v, const vertex2_type&)\r\n        {\r\n            vertex2_type w = state1_.core(v);\r\n            state1_.pop(v, w);\r\n            state2_.pop(w, v);\r\n        }\r\n\r\n        // Checks the feasibility of a new vertex pair\r\n        bool feasible(const vertex1_type& v_new, const vertex2_type& w_new)\r\n        {\r\n\r\n            if (!vertex_comp_(v_new, w_new))\r\n                return false;\r\n\r\n            // graph1\r\n            graph1_size_type term_in1_count = 0, term_out1_count = 0,\r\n                             rest1_count = 0;\r\n\r\n            {\r\n                equivalent_edge_exists< Graph2 > edge2_exists;\r\n\r\n                BGL_FORALL_INEDGES_T(v_new, e1, graph1_, Graph1)\r\n                {\r\n                    vertex1_type v = source(e1, graph1_);\r\n\r\n                    if (state1_.in_core(v) || (v == v_new))\r\n                    {\r\n                        vertex2_type w = w_new;\r\n                        if (v != v_new)\r\n                            w = state1_.core(v);\r\n                        if (!edge2_exists(w, w_new,\r\n                                edge2_predicate< Graph1, Graph2,\r\n                                    EdgeEquivalencePredicate >(edge_comp_, e1),\r\n                                graph2_))\r\n                            return false;\r\n                    }\r\n                    else\r\n                    {\r\n                        if (0 < state1_.in_depth(v))\r\n                            ++term_in1_count;\r\n                        if (0 < state1_.out_depth(v))\r\n                            ++term_out1_count;\r\n                        if ((state1_.in_depth(v) == 0)\r\n                            && (state1_.out_depth(v) == 0))\r\n                            ++rest1_count;\r\n                    }\r\n                }\r\n            }\r\n\r\n            {\r\n                equivalent_edge_exists< Graph2 > edge2_exists;\r\n\r\n                BGL_FORALL_OUTEDGES_T(v_new, e1, graph1_, Graph1)\r\n                {\r\n                    vertex1_type v = target(e1, graph1_);\r\n                    if (state1_.in_core(v) || (v == v_new))\r\n                    {\r\n                        vertex2_type w = w_new;\r\n                        if (v != v_new)\r\n                            w = state1_.core(v);\r\n\r\n                        if (!edge2_exists(w_new, w,\r\n                                edge2_predicate< Graph1, Graph2,\r\n                                    EdgeEquivalencePredicate >(edge_comp_, e1),\r\n                                graph2_))\r\n                            return false;\r\n                    }\r\n                    else\r\n                    {\r\n                        if (0 < state1_.in_depth(v))\r\n                            ++term_in1_count;\r\n                        if (0 < state1_.out_depth(v))\r\n                            ++term_out1_count;\r\n                        if ((state1_.in_depth(v) == 0)\r\n                            && (state1_.out_depth(v) == 0))\r\n                            ++rest1_count;\r\n                    }\r\n                }\r\n            }\r\n\r\n            // graph2\r\n            graph2_size_type term_out2_count = 0, term_in2_count = 0,\r\n                             rest2_count = 0;\r\n\r\n            {\r\n                equivalent_edge_exists< Graph1 > edge1_exists;\r\n\r\n                BGL_FORALL_INEDGES_T(w_new, e2, graph2_, Graph2)\r\n                {\r\n                    vertex2_type w = source(e2, graph2_);\r\n                    if (state2_.in_core(w) || (w == w_new))\r\n                    {\r\n                        if (problem_selection != subgraph_mono)\r\n                        {\r\n                            vertex1_type v = v_new;\r\n                            if (w != w_new)\r\n                                v = state2_.core(w);\r\n\r\n                            if (!edge1_exists(v, v_new,\r\n                                    edge1_predicate< Graph1, Graph2,\r\n                                        EdgeEquivalencePredicate >(\r\n                                        edge_comp_, e2),\r\n                                    graph1_))\r\n                                return false;\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        if (0 < state2_.in_depth(w))\r\n                            ++term_in2_count;\r\n                        if (0 < state2_.out_depth(w))\r\n                            ++term_out2_count;\r\n                        if ((state2_.in_depth(w) == 0)\r\n                            && (state2_.out_depth(w) == 0))\r\n                            ++rest2_count;\r\n                    }\r\n                }\r\n            }\r\n\r\n            {\r\n                equivalent_edge_exists< Graph1 > edge1_exists;\r\n\r\n                BGL_FORALL_OUTEDGES_T(w_new, e2, graph2_, Graph2)\r\n                {\r\n                    vertex2_type w = target(e2, graph2_);\r\n                    if (state2_.in_core(w) || (w == w_new))\r\n                    {\r\n                        if (problem_selection != subgraph_mono)\r\n                        {\r\n                            vertex1_type v = v_new;\r\n                            if (w != w_new)\r\n                                v = state2_.core(w);\r\n\r\n                            if (!edge1_exists(v_new, v,\r\n                                    edge1_predicate< Graph1, Graph2,\r\n                                        EdgeEquivalencePredicate >(\r\n                                        edge_comp_, e2),\r\n                                    graph1_))\r\n                                return false;\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        if (0 < state2_.in_depth(w))\r\n                            ++term_in2_count;\r\n                        if (0 < state2_.out_depth(w))\r\n                            ++term_out2_count;\r\n                        if ((state2_.in_depth(w) == 0)\r\n                            && (state2_.out_depth(w) == 0))\r\n                            ++rest2_count;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (problem_selection != subgraph_mono)\r\n            { // subgraph_iso and isomorphism\r\n                return comp_term_sets(term_in1_count, term_in2_count,\r\n                           boost::mpl::int_< problem_selection >())\r\n                    && comp_term_sets(term_out1_count, term_out2_count,\r\n                        boost::mpl::int_< problem_selection >())\r\n                    && comp_term_sets(rest1_count, rest2_count,\r\n                        boost::mpl::int_< problem_selection >());\r\n            }\r\n            else\r\n            { // subgraph_mono\r\n                return comp_term_sets(term_in1_count, term_in2_count,\r\n                           boost::mpl::int_< problem_selection >())\r\n                    && comp_term_sets(term_out1_count, term_out2_count,\r\n                        boost::mpl::int_< problem_selection >())\r\n                    && comp_term_sets(\r\n                        term_in1_count + term_out1_count + rest1_count,\r\n                        term_in2_count + term_out2_count + rest2_count,\r\n                        boost::mpl::int_< problem_selection >());\r\n            }\r\n        }\r\n\r\n        // Returns true if vertex v in graph1 is a possible candidate to\r\n        // be added to the current state\r\n        bool possible_candidate1(const vertex1_type& v) const\r\n        {\r\n            if (state1_.term_both() && state2_.term_both())\r\n                return state1_.term_both(v);\r\n            else if (state1_.term_out() && state2_.term_out())\r\n                return state1_.term_out(v);\r\n            else if (state1_.term_in() && state2_.term_in())\r\n                return state1_.term_in(v);\r\n            else\r\n                return !state1_.in_core(v);\r\n        }\r\n\r\n        // Returns true if vertex w in graph2 is a possible candidate to\r\n        // be added to the current state\r\n        bool possible_candidate2(const vertex2_type& w) const\r\n        {\r\n            if (state1_.term_both() && state2_.term_both())\r\n                return state2_.term_both(w);\r\n            else if (state1_.term_out() && state2_.term_out())\r\n                return state2_.term_out(w);\r\n            else if (state1_.term_in() && state2_.term_in())\r\n                return state2_.term_in(w);\r\n            else\r\n                return !state2_.in_core(w);\r\n        }\r\n\r\n        // Returns true if a mapping was found\r\n        bool success() const\r\n        {\r\n            return state1_.count() == num_vertices(graph1_);\r\n        }\r\n\r\n        // Returns true if a state is valid\r\n        bool valid() const\r\n        {\r\n            boost::tuple< graph1_size_type, graph1_size_type, graph1_size_type >\r\n                term1;\r\n            boost::tuple< graph2_size_type, graph2_size_type, graph2_size_type >\r\n                term2;\r\n\r\n            term1 = state1_.term_set();\r\n            term2 = state2_.term_set();\r\n\r\n            return comp_term_sets(boost::get< 0 >(term1),\r\n                       boost::get< 0 >(term2),\r\n                       boost::mpl::int_< problem_selection >())\r\n                && comp_term_sets(boost::get< 1 >(term1),\r\n                    boost::get< 1 >(term2),\r\n                    boost::mpl::int_< problem_selection >())\r\n                && comp_term_sets(boost::get< 2 >(term1),\r\n                    boost::get< 2 >(term2),\r\n                    boost::mpl::int_< problem_selection >());\r\n        }\r\n\r\n        // Calls the user_callback with a graph (sub)graph mapping\r\n        bool call_back(SubGraphIsoMapCallback user_callback) const\r\n        {\r\n            return user_callback(state1_.get_map(), state2_.get_map());\r\n        }\r\n    };\r\n\r\n    // Data structure to keep info used for back tracking during\r\n    // matching process\r\n    template < typename Graph1, typename Graph2, typename VertexOrder1 >\r\n    struct vf2_match_continuation\r\n    {\r\n        typename VertexOrder1::const_iterator graph1_verts_iter;\r\n        typename graph_traits< Graph2 >::vertex_iterator graph2_verts_iter;\r\n    };\r\n\r\n    // Non-recursive method that explores state space using a depth-first\r\n    // search strategy.  At each depth possible pairs candidate are compute\r\n    // and tested for feasibility to extend the mapping. If a complete\r\n    // mapping is found, the mapping is output to user_callback in the form\r\n    // of a correspondence map (graph1 to graph2). Returning false from the\r\n    // user_callback will terminate the search. Function match will return\r\n    // true if the entire search space was explored.\r\n    template < typename Graph1, typename Graph2, typename IndexMap1,\r\n        typename IndexMap2, typename VertexOrder1,\r\n        typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\r\n        typename SubGraphIsoMapCallback, problem_selector problem_selection >\r\n    bool match(const Graph1& graph1, const Graph2& graph2,\r\n        SubGraphIsoMapCallback user_callback, const VertexOrder1& vertex_order1,\r\n        state< Graph1, Graph2, IndexMap1, IndexMap2, EdgeEquivalencePredicate,\r\n            VertexEquivalencePredicate, SubGraphIsoMapCallback,\r\n            problem_selection >& s)\r\n    {\r\n\r\n        typename VertexOrder1::const_iterator graph1_verts_iter;\r\n\r\n        typedef typename graph_traits< Graph2 >::vertex_iterator\r\n            vertex2_iterator_type;\r\n        vertex2_iterator_type graph2_verts_iter, graph2_verts_iter_end;\r\n\r\n        typedef vf2_match_continuation< Graph1, Graph2, VertexOrder1 >\r\n            match_continuation_type;\r\n        std::vector< match_continuation_type > k;\r\n        bool found_match = false;\r\n\r\n    recur:\r\n        if (s.success())\r\n        {\r\n            if (!s.call_back(user_callback))\r\n                return true;\r\n            found_match = true;\r\n\r\n            goto back_track;\r\n        }\r\n\r\n        if (!s.valid())\r\n            goto back_track;\r\n\r\n        graph1_verts_iter = vertex_order1.begin();\r\n        while (graph1_verts_iter != vertex_order1.end()\r\n            && !s.possible_candidate1(*graph1_verts_iter))\r\n        {\r\n            ++graph1_verts_iter;\r\n        }\r\n\r\n        boost::tie(graph2_verts_iter, graph2_verts_iter_end) = vertices(graph2);\r\n        while (graph2_verts_iter != graph2_verts_iter_end)\r\n        {\r\n            if (s.possible_candidate2(*graph2_verts_iter))\r\n            {\r\n                if (s.feasible(*graph1_verts_iter, *graph2_verts_iter))\r\n                {\r\n                    match_continuation_type kk;\r\n                    kk.graph1_verts_iter = graph1_verts_iter;\r\n                    kk.graph2_verts_iter = graph2_verts_iter;\r\n                    k.push_back(kk);\r\n\r\n                    s.push(*graph1_verts_iter, *graph2_verts_iter);\r\n                    goto recur;\r\n                }\r\n            }\r\n        graph2_loop:\r\n            ++graph2_verts_iter;\r\n        }\r\n\r\n    back_track:\r\n        if (k.empty())\r\n            return found_match;\r\n\r\n        const match_continuation_type kk = k.back();\r\n        graph1_verts_iter = kk.graph1_verts_iter;\r\n        graph2_verts_iter = kk.graph2_verts_iter;\r\n        k.pop_back();\r\n\r\n        s.pop(*graph1_verts_iter, *graph2_verts_iter);\r\n\r\n        goto graph2_loop;\r\n    }\r\n\r\n    // Used to sort nodes by in/out degrees\r\n    template < typename Graph > struct vertex_in_out_degree_cmp\r\n    {\r\n        typedef typename graph_traits< Graph >::vertex_descriptor vertex_type;\r\n\r\n        vertex_in_out_degree_cmp(const Graph& graph) : graph_(graph) {}\r\n\r\n        bool operator()(const vertex_type& v, const vertex_type& w) const\r\n        {\r\n            // lexicographical comparison\r\n            return std::make_pair(in_degree(v, graph_), out_degree(v, graph_))\r\n                < std::make_pair(in_degree(w, graph_), out_degree(w, graph_));\r\n        }\r\n\r\n        const Graph& graph_;\r\n    };\r\n\r\n    // Used to sort nodes by multiplicity of in/out degrees\r\n    template < typename Graph, typename FrequencyMap >\r\n    struct vertex_frequency_degree_cmp\r\n    {\r\n        typedef typename graph_traits< Graph >::vertex_descriptor vertex_type;\r\n\r\n        vertex_frequency_degree_cmp(const Graph& graph, FrequencyMap freq)\r\n        : graph_(graph), freq_(freq)\r\n        {\r\n        }\r\n\r\n        bool operator()(const vertex_type& v, const vertex_type& w) const\r\n        {\r\n            // lexicographical comparison\r\n            return std::make_pair(\r\n                       freq_[v], in_degree(v, graph_) + out_degree(v, graph_))\r\n                < std::make_pair(\r\n                    freq_[w], in_degree(w, graph_) + out_degree(w, graph_));\r\n        }\r\n\r\n        const Graph& graph_;\r\n        FrequencyMap freq_;\r\n    };\r\n\r\n    // Sorts vertices of a graph by multiplicity of in/out degrees\r\n    template < typename Graph, typename IndexMap, typename VertexOrder >\r\n    void sort_vertices(\r\n        const Graph& graph, IndexMap index_map, VertexOrder& order)\r\n    {\r\n        typedef typename graph_traits< Graph >::vertices_size_type size_type;\r\n\r\n        boost::range::sort(order, vertex_in_out_degree_cmp< Graph >(graph));\r\n\r\n        std::vector< size_type > freq_vec(num_vertices(graph), 0);\r\n        typedef iterator_property_map<\r\n            typename std::vector< size_type >::iterator, IndexMap, size_type,\r\n            size_type& >\r\n            frequency_map_type;\r\n\r\n        frequency_map_type freq\r\n            = make_iterator_property_map(freq_vec.begin(), index_map);\r\n\r\n        typedef typename VertexOrder::iterator order_iterator;\r\n\r\n        for (order_iterator order_iter = order.begin();\r\n             order_iter != order.end();)\r\n        {\r\n            size_type count = 0;\r\n            for (order_iterator count_iter = order_iter;\r\n                 (count_iter != order.end())\r\n                 && (in_degree(*order_iter, graph)\r\n                     == in_degree(*count_iter, graph))\r\n                 && (out_degree(*order_iter, graph)\r\n                     == out_degree(*count_iter, graph));\r\n                 ++count_iter)\r\n                ++count;\r\n\r\n            for (size_type i = 0; i < count; ++i)\r\n            {\r\n                freq[*order_iter] = count;\r\n                ++order_iter;\r\n            }\r\n        }\r\n\r\n        boost::range::sort(order,\r\n            vertex_frequency_degree_cmp< Graph, frequency_map_type >(\r\n                graph, freq));\r\n    }\r\n\r\n    // Enumerates all graph sub-graph mono-/iso-morphism mappings between graphs\r\n    // graph_small and graph_large. Continues until user_callback returns true\r\n    // or the search space has been fully explored.\r\n    template < problem_selector problem_selection, typename GraphSmall,\r\n        typename GraphLarge, typename IndexMapSmall, typename IndexMapLarge,\r\n        typename VertexOrderSmall, typename EdgeEquivalencePredicate,\r\n        typename VertexEquivalencePredicate, typename SubGraphIsoMapCallback >\r\n    bool vf2_subgraph_morphism(const GraphSmall& graph_small,\r\n        const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback,\r\n        IndexMapSmall index_map_small, IndexMapLarge index_map_large,\r\n        const VertexOrderSmall& vertex_order_small,\r\n        EdgeEquivalencePredicate edge_comp,\r\n        VertexEquivalencePredicate vertex_comp)\r\n    {\r\n\r\n        // Graph requirements\r\n        BOOST_CONCEPT_ASSERT((BidirectionalGraphConcept< GraphSmall >));\r\n        BOOST_CONCEPT_ASSERT((VertexListGraphConcept< GraphSmall >));\r\n        BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< GraphSmall >));\r\n        BOOST_CONCEPT_ASSERT((AdjacencyMatrixConcept< GraphSmall >));\r\n\r\n        BOOST_CONCEPT_ASSERT((BidirectionalGraphConcept< GraphLarge >));\r\n        BOOST_CONCEPT_ASSERT((VertexListGraphConcept< GraphLarge >));\r\n        BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< GraphLarge >));\r\n        BOOST_CONCEPT_ASSERT((AdjacencyMatrixConcept< GraphLarge >));\r\n\r\n        typedef typename graph_traits< GraphSmall >::vertex_descriptor\r\n            vertex_small_type;\r\n        typedef typename graph_traits< GraphLarge >::vertex_descriptor\r\n            vertex_large_type;\r\n\r\n        typedef typename graph_traits< GraphSmall >::vertices_size_type\r\n            size_type_small;\r\n        typedef typename graph_traits< GraphLarge >::vertices_size_type\r\n            size_type_large;\r\n\r\n        // Property map requirements\r\n        BOOST_CONCEPT_ASSERT(\r\n            (ReadablePropertyMapConcept< IndexMapSmall, vertex_small_type >));\r\n        typedef typename property_traits< IndexMapSmall >::value_type\r\n            IndexMapSmallValue;\r\n        BOOST_STATIC_ASSERT(\r\n            (is_convertible< IndexMapSmallValue, size_type_small >::value));\r\n\r\n        BOOST_CONCEPT_ASSERT(\r\n            (ReadablePropertyMapConcept< IndexMapLarge, vertex_large_type >));\r\n        typedef typename property_traits< IndexMapLarge >::value_type\r\n            IndexMapLargeValue;\r\n        BOOST_STATIC_ASSERT(\r\n            (is_convertible< IndexMapLargeValue, size_type_large >::value));\r\n\r\n        // Edge & vertex requirements\r\n        typedef typename graph_traits< GraphSmall >::edge_descriptor\r\n            edge_small_type;\r\n        typedef typename graph_traits< GraphLarge >::edge_descriptor\r\n            edge_large_type;\r\n\r\n        BOOST_CONCEPT_ASSERT((BinaryPredicateConcept< EdgeEquivalencePredicate,\r\n            edge_small_type, edge_large_type >));\r\n\r\n        BOOST_CONCEPT_ASSERT(\r\n            (BinaryPredicateConcept< VertexEquivalencePredicate,\r\n                vertex_small_type, vertex_large_type >));\r\n\r\n        // Vertex order requirements\r\n        BOOST_CONCEPT_ASSERT((ContainerConcept< VertexOrderSmall >));\r\n        typedef typename VertexOrderSmall::value_type order_value_type;\r\n        BOOST_STATIC_ASSERT(\r\n            (is_same< vertex_small_type, order_value_type >::value));\r\n        BOOST_ASSERT(num_vertices(graph_small) == vertex_order_small.size());\r\n\r\n        if (num_vertices(graph_small) > num_vertices(graph_large))\r\n            return false;\r\n\r\n        typename graph_traits< GraphSmall >::edges_size_type num_edges_small\r\n            = num_edges(graph_small);\r\n        typename graph_traits< GraphLarge >::edges_size_type num_edges_large\r\n            = num_edges(graph_large);\r\n\r\n        // Double the number of edges for undirected graphs: each edge counts as\r\n        // in-edge and out-edge\r\n        if (is_undirected(graph_small))\r\n            num_edges_small *= 2;\r\n        if (is_undirected(graph_large))\r\n            num_edges_large *= 2;\r\n        if (num_edges_small > num_edges_large)\r\n            return false;\r\n\r\n        detail::state< GraphSmall, GraphLarge, IndexMapSmall, IndexMapLarge,\r\n            EdgeEquivalencePredicate, VertexEquivalencePredicate,\r\n            SubGraphIsoMapCallback, problem_selection >\r\n            s(graph_small, graph_large, index_map_small, index_map_large,\r\n                edge_comp, vertex_comp);\r\n\r\n        return detail::match(\r\n            graph_small, graph_large, user_callback, vertex_order_small, s);\r\n    }\r\n\r\n} // namespace detail\r\n\r\n// Returns vertex order (vertices sorted by multiplicity of in/out degrees)\r\ntemplate < typename Graph >\r\nstd::vector< typename graph_traits< Graph >::vertex_descriptor >\r\nvertex_order_by_mult(const Graph& graph)\r\n{\r\n\r\n    std::vector< typename graph_traits< Graph >::vertex_descriptor >\r\n        vertex_order;\r\n    std::copy(vertices(graph).first, vertices(graph).second,\r\n        std::back_inserter(vertex_order));\r\n\r\n    detail::sort_vertices(graph, get(vertex_index, graph), vertex_order);\r\n    return vertex_order;\r\n}\r\n\r\n// Enumerates all graph sub-graph monomorphism mappings between graphs\r\n// graph_small and graph_large. Continues until user_callback returns true or\r\n// the search space has been fully explored.\r\ntemplate < typename GraphSmall, typename GraphLarge, typename IndexMapSmall,\r\n    typename IndexMapLarge, typename VertexOrderSmall,\r\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\r\n    typename SubGraphIsoMapCallback >\r\nbool vf2_subgraph_mono(const GraphSmall& graph_small,\r\n    const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback,\r\n    IndexMapSmall index_map_small, IndexMapLarge index_map_large,\r\n    const VertexOrderSmall& vertex_order_small,\r\n    EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp)\r\n{\r\n    return detail::vf2_subgraph_morphism< detail::subgraph_mono >(graph_small,\r\n        graph_large, user_callback, index_map_small, index_map_large,\r\n        vertex_order_small, edge_comp, vertex_comp);\r\n}\r\n\r\n// All default interface for vf2_subgraph_iso\r\ntemplate < typename GraphSmall, typename GraphLarge,\r\n    typename SubGraphIsoMapCallback >\r\nbool vf2_subgraph_mono(const GraphSmall& graph_small,\r\n    const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback)\r\n{\r\n    return vf2_subgraph_mono(graph_small, graph_large, user_callback,\r\n        get(vertex_index, graph_small), get(vertex_index, graph_large),\r\n        vertex_order_by_mult(graph_small), always_equivalent(),\r\n        always_equivalent());\r\n}\r\n\r\n// Named parameter interface of vf2_subgraph_iso\r\ntemplate < typename GraphSmall, typename GraphLarge, typename VertexOrderSmall,\r\n    typename SubGraphIsoMapCallback, typename Param, typename Tag,\r\n    typename Rest >\r\nbool vf2_subgraph_mono(const GraphSmall& graph_small,\r\n    const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback,\r\n    const VertexOrderSmall& vertex_order_small,\r\n    const bgl_named_params< Param, Tag, Rest >& params)\r\n{\r\n    return vf2_subgraph_mono(graph_small, graph_large, user_callback,\r\n        choose_const_pmap(\r\n            get_param(params, vertex_index1), graph_small, vertex_index),\r\n        choose_const_pmap(\r\n            get_param(params, vertex_index2), graph_large, vertex_index),\r\n        vertex_order_small,\r\n        choose_param(\r\n            get_param(params, edges_equivalent_t()), always_equivalent()),\r\n        choose_param(\r\n            get_param(params, vertices_equivalent_t()), always_equivalent()));\r\n}\r\n\r\n// Enumerates all graph sub-graph isomorphism mappings between graphs\r\n// graph_small and graph_large. Continues until user_callback returns true or\r\n// the search space has been fully explored.\r\ntemplate < typename GraphSmall, typename GraphLarge, typename IndexMapSmall,\r\n    typename IndexMapLarge, typename VertexOrderSmall,\r\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\r\n    typename SubGraphIsoMapCallback >\r\nbool vf2_subgraph_iso(const GraphSmall& graph_small,\r\n    const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback,\r\n    IndexMapSmall index_map_small, IndexMapLarge index_map_large,\r\n    const VertexOrderSmall& vertex_order_small,\r\n    EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp)\r\n{\r\n    return detail::vf2_subgraph_morphism< detail::subgraph_iso >(graph_small,\r\n        graph_large, user_callback, index_map_small, index_map_large,\r\n        vertex_order_small, edge_comp, vertex_comp);\r\n}\r\n\r\n// All default interface for vf2_subgraph_iso\r\ntemplate < typename GraphSmall, typename GraphLarge,\r\n    typename SubGraphIsoMapCallback >\r\nbool vf2_subgraph_iso(const GraphSmall& graph_small,\r\n    const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback)\r\n{\r\n\r\n    return vf2_subgraph_iso(graph_small, graph_large, user_callback,\r\n        get(vertex_index, graph_small), get(vertex_index, graph_large),\r\n        vertex_order_by_mult(graph_small), always_equivalent(),\r\n        always_equivalent());\r\n}\r\n\r\n// Named parameter interface of vf2_subgraph_iso\r\ntemplate < typename GraphSmall, typename GraphLarge, typename VertexOrderSmall,\r\n    typename SubGraphIsoMapCallback, typename Param, typename Tag,\r\n    typename Rest >\r\nbool vf2_subgraph_iso(const GraphSmall& graph_small,\r\n    const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback,\r\n    const VertexOrderSmall& vertex_order_small,\r\n    const bgl_named_params< Param, Tag, Rest >& params)\r\n{\r\n\r\n    return vf2_subgraph_iso(graph_small, graph_large, user_callback,\r\n        choose_const_pmap(\r\n            get_param(params, vertex_index1), graph_small, vertex_index),\r\n        choose_const_pmap(\r\n            get_param(params, vertex_index2), graph_large, vertex_index),\r\n        vertex_order_small,\r\n        choose_param(\r\n            get_param(params, edges_equivalent_t()), always_equivalent()),\r\n        choose_param(\r\n            get_param(params, vertices_equivalent_t()), always_equivalent()));\r\n}\r\n\r\n// Enumerates all isomorphism mappings between graphs graph1_ and graph2_.\r\n// Continues until user_callback returns true or the search space has been\r\n// fully explored.\r\ntemplate < typename Graph1, typename Graph2, typename IndexMap1,\r\n    typename IndexMap2, typename VertexOrder1,\r\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate,\r\n    typename GraphIsoMapCallback >\r\nbool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,\r\n    GraphIsoMapCallback user_callback, IndexMap1 index_map1,\r\n    IndexMap2 index_map2, const VertexOrder1& vertex_order1,\r\n    EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp)\r\n{\r\n\r\n    // Graph requirements\r\n    BOOST_CONCEPT_ASSERT((BidirectionalGraphConcept< Graph1 >));\r\n    BOOST_CONCEPT_ASSERT((VertexListGraphConcept< Graph1 >));\r\n    BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< Graph1 >));\r\n    BOOST_CONCEPT_ASSERT((AdjacencyMatrixConcept< Graph1 >));\r\n\r\n    BOOST_CONCEPT_ASSERT((BidirectionalGraphConcept< Graph2 >));\r\n    BOOST_CONCEPT_ASSERT((VertexListGraphConcept< Graph2 >));\r\n    BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< Graph2 >));\r\n    BOOST_CONCEPT_ASSERT((AdjacencyMatrixConcept< Graph2 >));\r\n\r\n    typedef typename graph_traits< Graph1 >::vertex_descriptor vertex1_type;\r\n    typedef typename graph_traits< Graph2 >::vertex_descriptor vertex2_type;\r\n\r\n    typedef typename graph_traits< Graph1 >::vertices_size_type size_type1;\r\n    typedef typename graph_traits< Graph2 >::vertices_size_type size_type2;\r\n\r\n    // Property map requirements\r\n    BOOST_CONCEPT_ASSERT(\r\n        (ReadablePropertyMapConcept< IndexMap1, vertex1_type >));\r\n    typedef typename property_traits< IndexMap1 >::value_type IndexMap1Value;\r\n    BOOST_STATIC_ASSERT((is_convertible< IndexMap1Value, size_type1 >::value));\r\n\r\n    BOOST_CONCEPT_ASSERT(\r\n        (ReadablePropertyMapConcept< IndexMap2, vertex2_type >));\r\n    typedef typename property_traits< IndexMap2 >::value_type IndexMap2Value;\r\n    BOOST_STATIC_ASSERT((is_convertible< IndexMap2Value, size_type2 >::value));\r\n\r\n    // Edge & vertex requirements\r\n    typedef typename graph_traits< Graph1 >::edge_descriptor edge1_type;\r\n    typedef typename graph_traits< Graph2 >::edge_descriptor edge2_type;\r\n\r\n    BOOST_CONCEPT_ASSERT((BinaryPredicateConcept< EdgeEquivalencePredicate,\r\n        edge1_type, edge2_type >));\r\n\r\n    BOOST_CONCEPT_ASSERT((BinaryPredicateConcept< VertexEquivalencePredicate,\r\n        vertex1_type, vertex2_type >));\r\n\r\n    // Vertex order requirements\r\n    BOOST_CONCEPT_ASSERT((ContainerConcept< VertexOrder1 >));\r\n    typedef typename VertexOrder1::value_type order_value_type;\r\n    BOOST_STATIC_ASSERT((is_same< vertex1_type, order_value_type >::value));\r\n    BOOST_ASSERT(num_vertices(graph1) == vertex_order1.size());\r\n\r\n    if (num_vertices(graph1) != num_vertices(graph2))\r\n        return false;\r\n\r\n    typename graph_traits< Graph1 >::edges_size_type num_edges1\r\n        = num_edges(graph1);\r\n    typename graph_traits< Graph2 >::edges_size_type num_edges2\r\n        = num_edges(graph2);\r\n\r\n    // Double the number of edges for undirected graphs: each edge counts as\r\n    // in-edge and out-edge\r\n    if (is_undirected(graph1))\r\n        num_edges1 *= 2;\r\n    if (is_undirected(graph2))\r\n        num_edges2 *= 2;\r\n    if (num_edges1 != num_edges2)\r\n        return false;\r\n\r\n    detail::state< Graph1, Graph2, IndexMap1, IndexMap2,\r\n        EdgeEquivalencePredicate, VertexEquivalencePredicate,\r\n        GraphIsoMapCallback, detail::isomorphism >\r\n        s(graph1, graph2, index_map1, index_map2, edge_comp, vertex_comp);\r\n\r\n    return detail::match(graph1, graph2, user_callback, vertex_order1, s);\r\n}\r\n\r\n// All default interface for vf2_graph_iso\r\ntemplate < typename Graph1, typename Graph2, typename GraphIsoMapCallback >\r\nbool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,\r\n    GraphIsoMapCallback user_callback)\r\n{\r\n\r\n    return vf2_graph_iso(graph1, graph2, user_callback,\r\n        get(vertex_index, graph1), get(vertex_index, graph2),\r\n        vertex_order_by_mult(graph1), always_equivalent(), always_equivalent());\r\n}\r\n\r\n// Named parameter interface of vf2_graph_iso\r\ntemplate < typename Graph1, typename Graph2, typename VertexOrder1,\r\n    typename GraphIsoMapCallback, typename Param, typename Tag, typename Rest >\r\nbool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,\r\n    GraphIsoMapCallback user_callback, const VertexOrder1& vertex_order1,\r\n    const bgl_named_params< Param, Tag, Rest >& params)\r\n{\r\n\r\n    return vf2_graph_iso(graph1, graph2, user_callback,\r\n        choose_const_pmap(\r\n            get_param(params, vertex_index1), graph1, vertex_index),\r\n        choose_const_pmap(\r\n            get_param(params, vertex_index2), graph2, vertex_index),\r\n        vertex_order1,\r\n        choose_param(\r\n            get_param(params, edges_equivalent_t()), always_equivalent()),\r\n        choose_param(\r\n            get_param(params, vertices_equivalent_t()), always_equivalent()));\r\n}\r\n\r\n// Verifies a graph (sub)graph isomorphism map\r\ntemplate < typename Graph1, typename Graph2, typename CorresponenceMap1To2,\r\n    typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate >\r\ninline bool verify_vf2_subgraph_iso(const Graph1& graph1, const Graph2& graph2,\r\n    const CorresponenceMap1To2 f, EdgeEquivalencePredicate edge_comp,\r\n    VertexEquivalencePredicate vertex_comp)\r\n{\r\n\r\n    BOOST_CONCEPT_ASSERT((EdgeListGraphConcept< Graph1 >));\r\n    BOOST_CONCEPT_ASSERT((AdjacencyMatrixConcept< Graph2 >));\r\n\r\n    detail::equivalent_edge_exists< Graph2 > edge2_exists;\r\n\r\n    BGL_FORALL_EDGES_T(e1, graph1, Graph1)\r\n    {\r\n        typename graph_traits< Graph1 >::vertex_descriptor s1, t1;\r\n        typename graph_traits< Graph2 >::vertex_descriptor s2, t2;\r\n\r\n        s1 = source(e1, graph1);\r\n        t1 = target(e1, graph1);\r\n        s2 = get(f, s1);\r\n        t2 = get(f, t1);\r\n\r\n        if (!vertex_comp(s1, s2) || !vertex_comp(t1, t2))\r\n            return false;\r\n\r\n        typename graph_traits< Graph2 >::edge_descriptor e2;\r\n\r\n        if (!edge2_exists(s2, t2,\r\n                detail::edge2_predicate< Graph1, Graph2,\r\n                    EdgeEquivalencePredicate >(edge_comp, e1),\r\n                graph2))\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n// Variant of verify_subgraph_iso with all default parameters\r\ntemplate < typename Graph1, typename Graph2, typename CorresponenceMap1To2 >\r\ninline bool verify_vf2_subgraph_iso(\r\n    const Graph1& graph1, const Graph2& graph2, const CorresponenceMap1To2 f)\r\n{\r\n    return verify_vf2_subgraph_iso(\r\n        graph1, graph2, f, always_equivalent(), always_equivalent());\r\n}\r\n\r\n} // namespace boost\r\n\r\n#ifdef BOOST_ISO_INCLUDED_ITER_MACROS\r\n#undef BOOST_ISO_INCLUDED_ITER_MACROS\r\n#include <boost/graph/iteration_macros_undef.hpp>\r\n#endif\r\n\r\n#endif // BOOST_VF2_SUB_GRAPH_ISO_HPP\r\n", "meta": {"hexsha": "1fc2733eae6796ba7843d8fd65e95c2cd61f8ed4", "size": 49886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/vf2_sub_graph_iso.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/vf2_sub_graph_iso.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/vf2_sub_graph_iso.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 38.3149001536, "max_line_length": 81, "alphanum_fraction": 0.5914485026, "num_tokens": 10387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1688569605068544, "lm_q2_score": 0.021287351017316616, "lm_q1q2_score": 0.0035945173900265785}}
{"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#include <boost/scoped_array.hpp>\n#include \"VtkMeshWriter.hpp\"\n#include \"DistributedTetrahedralMesh.hpp\"\n#include \"MixedDimensionMesh.hpp\"\n#include \"NodesOnlyMesh.hpp\"\n\n#ifdef CHASTE_VTK\n#include \"vtkQuadraticTetra.h\"\n#include \"vtkQuadraticTriangle.h\"\n\n\n///////////////////////////////////////////////////////////////////////////////////\n// Implementation\n///////////////////////////////////////////////////////////////////////////////////\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nVtkMeshWriter<ELEMENT_DIM, SPACE_DIM>::VtkMeshWriter(const std::string& rDirectory,\n                     const std::string& rBaseName,\n                     const bool& rCleanDirectory)\n    : AbstractTetrahedralMeshWriter<ELEMENT_DIM, SPACE_DIM>(rDirectory, rBaseName, rCleanDirectory),\n      mWriteParallelFiles(false)\n{\n    this->mIndexFromZero = true;\n\n    // Dubious, since we shouldn't yet know what any details of the mesh are.\n    mpVtkUnstructedMesh = vtkUnstructuredGrid::New();\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nVtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::~VtkMeshWriter()\n{\n    mpVtkUnstructedMesh->Delete(); // Reference counted\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::MakeVtkMesh()\n{\n    //Construct nodes aka as Points\n    vtkPoints* p_pts = vtkPoints::New(VTK_DOUBLE);\n    p_pts->GetData()->SetName(\"Vertex positions\");\n    for (unsigned item_num=0; item_num<this->GetNumNodes(); item_num++)\n    {\n        std::vector<double> current_item = this->GetNextNode(); //this->mNodeData[item_num];\n        // Add zeroes if the dimension is below 3\n        for (unsigned dim=SPACE_DIM; dim<3; dim++)\n        {\n            current_item.push_back(0.0);//For y and z-coordinates if necessary\n        }\n        assert(current_item.size() == 3);\n        p_pts->InsertPoint(item_num, current_item[0], current_item[1], current_item[2]);\n    }\n    mpVtkUnstructedMesh->SetPoints(p_pts);\n    p_pts->Delete(); //Reference counted\n\n    //Construct elements aka Cells\n    for (unsigned item_num=0; item_num<this->GetNumElements(); item_num++)\n    {\n        std::vector<unsigned> current_element = this->GetNextElement().NodeIndices; // this->mElementData[item_num];\n\n        assert((current_element.size() == ELEMENT_DIM + 1) || (current_element.size() == (ELEMENT_DIM+1)*(ELEMENT_DIM+2)/2));\n\n        vtkCell* p_cell=nullptr;\n        if (ELEMENT_DIM == 3 && current_element.size() == 4)\n        {\n            p_cell = vtkTetra::New();\n        }\n        else if (ELEMENT_DIM == 3 && current_element.size() == 10)\n        {\n            p_cell = vtkQuadraticTetra::New();\n        }\n        else if (ELEMENT_DIM == 2 && current_element.size() == 3)\n        {\n            p_cell = vtkTriangle::New();\n        }\n        else if (ELEMENT_DIM == 2 && current_element.size() == 6)\n        {\n            p_cell = vtkQuadraticTriangle::New();\n        }\n        else if (ELEMENT_DIM == 1)\n        {\n            p_cell = vtkLine::New();\n        }\n\n        //Set the linear nodes\n        vtkIdList* p_cell_id_list = p_cell->GetPointIds();\n        for (unsigned j = 0; j < current_element.size(); ++j)\n        {\n            p_cell_id_list->SetId(j, current_element[j]);\n        }\n\n        //VTK defines the node ordering in quadratic triangles differently to Chaste, so they must be treated as a special case\n        if (SPACE_DIM == 2 && current_element.size() == 6)\n        {\n            p_cell_id_list->SetId(3, current_element[5]);\n            p_cell_id_list->SetId(4, current_element[3]);\n            p_cell_id_list->SetId(5, current_element[4]);\n        }\n\n        mpVtkUnstructedMesh->InsertNextCell(p_cell->GetCellType(), p_cell_id_list);\n        p_cell->Delete(); //Reference counted\n    }\n\n    if (SPACE_DIM > 1)\n    {\n        /// \\todo #2351 Temporary workaround for parallel writer\n        for (unsigned item_num=0; item_num<this->GetNumBoundaryFaces(); item_num++)\n        {\n            this->GetNextBoundaryElement();\n        }\n    }\n\n    //If necessary, construct cables\n    if (this->GetNumCableElements() > 0)\n    {\n        AugmentCellData();\n        //Make a blank cell radius data for the regular elements\n        std::vector<double> radii(this->GetNumElements(), 0.0);\n        for (unsigned item_num=0; item_num<this->GetNumCableElements(); item_num++)\n        {\n            ElementData cable_element_data = this->GetNextCableElement();\n            std::vector<unsigned> current_element = cable_element_data.NodeIndices;\n            radii.push_back(cable_element_data.AttributeValue);\n            assert(current_element.size() == 2);\n            vtkCell* p_cell=vtkLine::New();\n            vtkIdList* p_cell_id_list = p_cell->GetPointIds();\n            for (unsigned j = 0; j < 2; ++j)\n            {\n                p_cell_id_list->SetId(j, current_element[j]);\n            }\n            mpVtkUnstructedMesh->InsertNextCell(p_cell->GetCellType(), p_cell_id_list);\n            p_cell->Delete(); //Reference counted\n        }\n        AddCellData(\"Cable radius\", radii);\n\n    }\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddProvenance(std::string fileName)\n{\n    std::string comment = \"<!-- \" + ChasteBuildInfo::GetProvenanceString() + \"-->\";\n\n    out_stream p_vtu_file = this->mpOutputFileHandler->OpenOutputFile(fileName, std::ios::out | std::ios::app);\n\n    *p_vtu_file << \"\\n\" << comment << \"\\n\";\n    p_vtu_file->close();\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::WriteFiles()\n{\n    // Using separate scope here to make sure file is properly closed before re-opening it to add provenance info.\n    {\n        MakeVtkMesh();\n        assert(mpVtkUnstructedMesh->CheckAttributes() == 0);\n        vtkXMLUnstructuredGridWriter* p_writer = vtkXMLUnstructuredGridWriter::New();\n#if VTK_MAJOR_VERSION >= 6\n        p_writer->SetInputData(mpVtkUnstructedMesh);\n#else\n        p_writer->SetInput(mpVtkUnstructedMesh);\n#endif\n        std::string vtk_file_name = this->mpOutputFileHandler->GetOutputDirectoryFullPath() + this->mBaseName+\".vtu\";\n        p_writer->SetFileName(vtk_file_name.c_str());\n        //p_writer->PrintSelf(std::cout, vtkIndent());\n        p_writer->Write();\n        p_writer->Delete(); //Reference counted\n    }\n\n    AddProvenance(this->mBaseName + \".vtu\");\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddCellData(std::string dataName, std::vector<double> dataPayload)\n{\n    vtkDoubleArray* p_scalars = vtkDoubleArray::New();\n    p_scalars->SetName(dataName.c_str());\n    for (unsigned i=0; i<dataPayload.size(); i++)\n    {\n        p_scalars->InsertNextValue(dataPayload[i]);\n    }\n\n    vtkCellData* p_cell_data = mpVtkUnstructedMesh->GetCellData();\n    p_cell_data->AddArray(p_scalars);\n    p_scalars->Delete(); //Reference counted\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AugmentCellData()\n{\n    unsigned num_cell_arrays = mpVtkUnstructedMesh->GetCellData()->GetNumberOfArrays();\n    for (unsigned i = 0; i < num_cell_arrays; i++)\n    {\n        vtkDataArray* array = mpVtkUnstructedMesh->GetCellData()->GetArray(i);\n\n        //Check data was the correct size before the cables were added\n        unsigned num_cable_pads = this->GetNumCableElements();\n        if (mWriteParallelFiles)\n        {\n            assert((unsigned)array->GetNumberOfTuples() == this->mpDistributedMesh->GetNumLocalElements());\n            num_cable_pads =  this->mpMixedMesh->GetNumLocalCableElements();\n        }\n        else\n        {\n            assert((unsigned)array->GetNumberOfTuples() == this->GetNumElements());\n        }\n\n        //Check that tuples of size 3 will be big enough for padding the rest of the data\n        assert(array->GetNumberOfComponents() <= 3);\n        double null_data[3] = {0.0, 0.0, 0.0};\n\n        //Pad data\n        for (unsigned new_index = 0; new_index <  num_cable_pads; new_index++)\n        {\n            array->InsertNextTuple(null_data);\n        }\n    }\n}\n\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddCellData(std::string dataName, std::vector<c_vector<double, SPACE_DIM> > dataPayload)\n{\n    vtkDoubleArray* p_vectors = vtkDoubleArray::New();\n    p_vectors->SetName(dataName.c_str());\n    p_vectors->SetNumberOfComponents(3);\n    for (unsigned i=0; i<dataPayload.size(); i++)\n    {\n        for (unsigned j=0; j<SPACE_DIM; j++)\n        {\n            p_vectors->InsertNextValue(dataPayload[i][j]);\n        }\n        //When SPACE_DIM<3, then pad\n        for (unsigned j=SPACE_DIM; j<3; j++)\n        {\n            p_vectors->InsertNextValue(0.0);\n        }\n    }\n\n    vtkCellData* p_cell_data = mpVtkUnstructedMesh->GetCellData();\n    p_cell_data->AddArray(p_vectors);\n    p_vectors->Delete(); //Reference counted\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddTensorCellData(std::string dataName, std::vector<c_vector<double,SPACE_DIM*(SPACE_DIM+1)/2> > dataPayload)\n{\n    assert(SPACE_DIM != 1);    // LCOV_EXCL_LINE\n\n    vtkDoubleArray* p_vectors = vtkDoubleArray::New();\n    p_vectors->SetName(dataName.c_str());\n    p_vectors->SetNumberOfComponents(SPACE_DIM*SPACE_DIM);\n    for (unsigned i=0; i<dataPayload.size(); i++)\n    {\n        if (SPACE_DIM == 2)\n        {\n            p_vectors->InsertNextValue(dataPayload[i](0)); //a11\n            p_vectors->InsertNextValue(dataPayload[i](1)); //a12\n            p_vectors->InsertNextValue(dataPayload[i](1)); //a21\n            p_vectors->InsertNextValue(dataPayload[i](2)); //a22\n        }\n        else if (SPACE_DIM == 3)\n        {\n            p_vectors->InsertNextValue(dataPayload[i](0)); //a11\n            p_vectors->InsertNextValue(dataPayload[i](1)); //a12\n            p_vectors->InsertNextValue(dataPayload[i](2)); //a13\n            p_vectors->InsertNextValue(dataPayload[i](1)); //a21\n            p_vectors->InsertNextValue(dataPayload[i](3)); //a22\n            p_vectors->InsertNextValue(dataPayload[i](4)); //a23\n            p_vectors->InsertNextValue(dataPayload[i](2)); //a31\n            p_vectors->InsertNextValue(dataPayload[i](4)); //a32\n            p_vectors->InsertNextValue(dataPayload[i](5)); //a33\n        }\n    }\n\n    vtkCellData* p_cell_data = mpVtkUnstructedMesh->GetCellData();\n    p_cell_data->AddArray(p_vectors);\n    p_vectors->Delete(); //Reference counted\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddTensorCellData(std::string dataName, std::vector<c_matrix<double,SPACE_DIM,SPACE_DIM> > dataPayload)\n{\n    assert(SPACE_DIM != 1);    // LCOV_EXCL_LINE\n\n    vtkDoubleArray* p_vectors = vtkDoubleArray::New();\n    p_vectors->SetName(dataName.c_str());\n    p_vectors->SetNumberOfComponents(SPACE_DIM*SPACE_DIM);\n    for (unsigned i=0; i<dataPayload.size(); i++)\n    {\n        if (SPACE_DIM == 2)\n        {\n            p_vectors->InsertNextValue(dataPayload[i](0,0)); //a11\n            p_vectors->InsertNextValue(dataPayload[i](0,1)); //a12\n            p_vectors->InsertNextValue(dataPayload[i](1,0)); //a21\n            p_vectors->InsertNextValue(dataPayload[i](1,1)); //a22\n        }\n        else if (SPACE_DIM == 3)\n        {\n            p_vectors->InsertNextValue(dataPayload[i](0,0)); //a11\n            p_vectors->InsertNextValue(dataPayload[i](0,1)); //a12\n            p_vectors->InsertNextValue(dataPayload[i](0,2)); //a13\n            p_vectors->InsertNextValue(dataPayload[i](1,0)); //a21\n            p_vectors->InsertNextValue(dataPayload[i](1,1)); //a22\n            p_vectors->InsertNextValue(dataPayload[i](1,2)); //a23\n            p_vectors->InsertNextValue(dataPayload[i](2,0)); //a31\n            p_vectors->InsertNextValue(dataPayload[i](2,1)); //a32\n            p_vectors->InsertNextValue(dataPayload[i](2,2)); //a33\n        }\n    }\n\n    vtkCellData* p_cell_data = mpVtkUnstructedMesh->GetCellData();\n    p_cell_data->AddArray(p_vectors);\n    p_vectors->Delete(); //Reference counted\n}\n\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddPointData(std::string dataName, std::vector<double> dataPayload)\n{\n    vtkDoubleArray* p_scalars = vtkDoubleArray::New();\n    p_scalars->SetName(dataName.c_str());\n\n    if (mWriteParallelFiles && this->mpDistributedMesh != nullptr)\n    {\n        // In parallel, the vector we pass will only contain the values from the privately owned nodes.\n        // To get the values from the halo nodes (which will be inserted at the end of the vector we need to\n        // communicate with the equivalent vectors on other processes.\n\n        // resize the payload data to include halos\n        assert( dataPayload.size() == this->mpDistributedMesh->GetNumLocalNodes() );\n        dataPayload.resize( this->mpDistributedMesh->GetNumLocalNodes() + this->mpDistributedMesh->GetNumHaloNodes() );\n\n\n        // then do the communication\n        for ( unsigned rank_offset = 1; rank_offset < PetscTools::GetNumProcs(); rank_offset++ )\n        {\n            unsigned send_to      = (PetscTools::GetMyRank() + rank_offset) % (PetscTools::GetNumProcs());\n            unsigned receive_from = (PetscTools::GetMyRank() + PetscTools::GetNumProcs()- rank_offset ) % (PetscTools::GetNumProcs());\n\n            unsigned number_of_nodes_to_send    = mNodesToSendPerProcess[send_to].size();\n            unsigned number_of_nodes_to_receive = mNodesToReceivePerProcess[receive_from].size();\n\n            boost::scoped_array<double> send_data(new double[number_of_nodes_to_send]);\n            boost::scoped_array<double> receive_data(new double[number_of_nodes_to_receive]);\n            // Pack\n            for (unsigned node = 0; node < number_of_nodes_to_send; node++)\n            {\n                unsigned global_node_index = mNodesToSendPerProcess[send_to][node];\n                unsigned local_node_index = global_node_index\n                            - this->mpDistributedMesh->GetDistributedVectorFactory()->GetLow();\n                send_data[node] = dataPayload[local_node_index];\n            }\n            {\n                // Send\n                int ret;\n                MPI_Status status;\n                ret = MPI_Sendrecv(send_data.get(), number_of_nodes_to_send,\n                                   MPI_DOUBLE,\n                                   send_to, 0,\n                                   receive_data.get(),  number_of_nodes_to_receive,\n                                   MPI_DOUBLE,\n                                   receive_from, 0,\n                                   PETSC_COMM_WORLD, &status);\n                UNUSED_OPT(ret);\n                assert ( ret == MPI_SUCCESS );\n            }\n\n            // Unpack\n            for ( unsigned node = 0; node < number_of_nodes_to_receive; node++ )\n            {\n                unsigned global_node_index = mNodesToReceivePerProcess[receive_from][node];\n                unsigned halo_index = mGlobalToNodeIndexMap[global_node_index];\n                assert( halo_index >= this->mpDistributedMesh->GetNumLocalNodes() );\n                dataPayload[halo_index] = receive_data[node];\n            }\n\n        }\n    }\n\n    for (unsigned i=0; i<dataPayload.size(); i++)\n    {\n        p_scalars->InsertNextValue(dataPayload[i]);\n    }\n\n    vtkPointData* p_point_data = mpVtkUnstructedMesh->GetPointData();\n    p_point_data->AddArray(p_scalars);\n    p_scalars->Delete(); //Reference counted\n}\n\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddPointData(std::string dataName, std::vector<c_vector<double, SPACE_DIM> > dataPayload)\n{\n    vtkDoubleArray* p_vectors = vtkDoubleArray::New();\n    p_vectors->SetName(dataName.c_str());\n\n    if (mWriteParallelFiles)\n    {\n        // In parallel, the vector we pass will only contain the values from the privately owned nodes.\n        // To get the values from the halo nodes (which will be inserted at the end of the vector we need to\n        // communicate with the equivalent vectors on other processes.\n\n        // resize the payload data to include halos\n        assert( dataPayload.size() == this->mpDistributedMesh->GetNumLocalNodes() );\n        dataPayload.resize( this->mpDistributedMesh->GetNumLocalNodes() + this->mpDistributedMesh->GetNumHaloNodes() );\n\n        // then do the communication\n        for ( unsigned rank_offset = 1; rank_offset < PetscTools::GetNumProcs(); rank_offset++ )\n        {\n            unsigned send_to      = (PetscTools::GetMyRank() + rank_offset) % (PetscTools::GetNumProcs());\n            unsigned receive_from = (PetscTools::GetMyRank() + PetscTools::GetNumProcs()- rank_offset ) % (PetscTools::GetNumProcs());\n\n            unsigned number_of_nodes_to_send    = mNodesToSendPerProcess[send_to].size();\n            unsigned number_of_nodes_to_receive = mNodesToReceivePerProcess[receive_from].size();\n\n            boost::scoped_array<double> send_data(new double[number_of_nodes_to_send * SPACE_DIM]);\n            boost::scoped_array<double> receive_data(new double[number_of_nodes_to_receive * SPACE_DIM]);\n\n            for (unsigned node = 0; node < number_of_nodes_to_send; node++)\n            {\n                unsigned global_node_index = mNodesToSendPerProcess[send_to][node];\n                unsigned local_node_index = global_node_index\n                            - this->mpDistributedMesh->GetDistributedVectorFactory()->GetLow();\n                for (unsigned j=0; j<SPACE_DIM; j++)\n                {\n                    send_data[ node*SPACE_DIM + j ] = dataPayload[local_node_index][j];\n                }\n            }\n\n                int ret;\n                MPI_Status status;\n                ret = MPI_Sendrecv(send_data.get(), number_of_nodes_to_send * SPACE_DIM,\n                                   MPI_DOUBLE,\n                                   send_to, 0,\n                                   receive_data.get(),  number_of_nodes_to_receive * SPACE_DIM,\n                                   MPI_DOUBLE,\n                                   receive_from, 0,\n                                   PETSC_COMM_WORLD, &status);\n                UNUSED_OPT(ret);\n                assert ( ret == MPI_SUCCESS );\n\n            // Unpack\n            for ( unsigned node = 0; node < number_of_nodes_to_receive; node++ )\n            {\n                unsigned global_node_index = mNodesToReceivePerProcess[receive_from][node];\n                unsigned halo_index = mGlobalToNodeIndexMap[global_node_index];\n                assert( halo_index >= this->mpDistributedMesh->GetNumLocalNodes() );\n                for (unsigned j=0; j<SPACE_DIM; j++)\n                {\n                    dataPayload[halo_index][j] = receive_data[ node*SPACE_DIM + j ];\n                }\n            }\n        }\n    }\n\n    p_vectors->SetNumberOfComponents(3);\n    for (unsigned i=0; i<dataPayload.size(); i++)\n    {\n        for (unsigned j=0; j<SPACE_DIM; j++)\n        {\n            p_vectors->InsertNextValue(dataPayload[i][j]);\n        }\n        //When SPACE_DIM<3, then pad\n        for (unsigned j=SPACE_DIM; j<3; j++)\n        {\n            p_vectors->InsertNextValue(0.0);\n        }\n    }\n\n    vtkPointData* p_point_data = mpVtkUnstructedMesh->GetPointData();\n    p_point_data->AddArray(p_vectors);\n    p_vectors->Delete(); //Reference counted\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::AddTensorPointData(std::string dataName, std::vector<c_matrix<double,SPACE_DIM,SPACE_DIM> > dataPayload)\n{\n    assert(SPACE_DIM != 1);    // LCOV_EXCL_LINE\n\n    vtkDoubleArray* p_vectors = vtkDoubleArray::New();\n    p_vectors->SetName(dataName.c_str());\n    p_vectors->SetNumberOfComponents(SPACE_DIM*SPACE_DIM);\n    for (unsigned i=0; i<dataPayload.size(); i++)\n    {\n        if (SPACE_DIM == 2)\n        {\n            p_vectors->InsertNextValue(dataPayload[i](0,0)); //a11\n            p_vectors->InsertNextValue(dataPayload[i](0,1)); //a12\n            p_vectors->InsertNextValue(dataPayload[i](1,0)); //a21\n            p_vectors->InsertNextValue(dataPayload[i](1,1)); //a22\n        }\n        else if (SPACE_DIM == 3)\n        {\n            p_vectors->InsertNextValue(dataPayload[i](0,0)); //a11\n            p_vectors->InsertNextValue(dataPayload[i](0,1)); //a12\n            p_vectors->InsertNextValue(dataPayload[i](0,2)); //a13\n            p_vectors->InsertNextValue(dataPayload[i](1,0)); //a21\n            p_vectors->InsertNextValue(dataPayload[i](1,1)); //a22\n            p_vectors->InsertNextValue(dataPayload[i](1,2)); //a23\n            p_vectors->InsertNextValue(dataPayload[i](2,0)); //a31\n            p_vectors->InsertNextValue(dataPayload[i](2,1)); //a32\n            p_vectors->InsertNextValue(dataPayload[i](2,2)); //a33\n        }\n    }\n\n    vtkPointData* p_point_data = mpVtkUnstructedMesh->GetPointData();\n    p_point_data->AddArray(p_vectors);\n    p_vectors->Delete(); //Reference counted\n}\n\ntemplate <unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM,SPACE_DIM>::SetParallelFiles( AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>& rMesh )\n{\n    //Have we got a distributed mesh?\n    this->mpDistributedMesh = dynamic_cast<DistributedTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* >(&rMesh);\n    mpNodesOnlyMesh = dynamic_cast<NodesOnlyMesh<SPACE_DIM>* >(&rMesh);\n\n    if (this->mpDistributedMesh == nullptr && mpNodesOnlyMesh == nullptr)\n    {\n        EXCEPTION(\"Cannot write parallel files using a sequential mesh\");\n    }\n\n    if (PetscTools::IsSequential())\n    {\n        return;     // mWriteParallelFiles is not set sequentially (so we don't set up data exchange machinery)\n    }\n\n    mWriteParallelFiles = true;\n\n    // Populate the global to node index map (as this will be required to add point data)\n\n    //Node index that we are writing to VTK (index into mNodes and mHaloNodes as if they were concatenated)\n    unsigned index = 0;\n\n    // Owned nodes\n    for (typename AbstractMesh<ELEMENT_DIM,SPACE_DIM>::NodeIterator node_iter = rMesh.GetNodeIteratorBegin();\n         node_iter != rMesh.GetNodeIteratorEnd();\n         ++node_iter)\n    {\n        mGlobalToNodeIndexMap[node_iter->GetIndex()] = index;\n        index++;\n    }\n\n    // Halo nodes\n    if (this->mpDistributedMesh)\n    {\n        for (typename DistributedTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>::HaloNodeIterator halo_iter=this->mpDistributedMesh->GetHaloNodeIteratorBegin();\n                halo_iter != this->mpDistributedMesh->GetHaloNodeIteratorEnd();\n                ++halo_iter)\n        {\n            mGlobalToNodeIndexMap[(*halo_iter)->GetIndex()] = index;\n            index++;\n        }\n\n        //Calculate the halo exchange so that node-wise payloads can be communicated\n        this->mpDistributedMesh->CalculateNodeExchange( mNodesToSendPerProcess, mNodesToReceivePerProcess );\n    }\n}\n\n///\\todo #1322 Mesh should be const\ntemplate<unsigned ELEMENT_DIM, unsigned SPACE_DIM>\nvoid VtkMeshWriter<ELEMENT_DIM, SPACE_DIM>::WriteFilesUsingMesh(\n      AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>& rMesh,\n      bool keepOriginalElementIndexing)\n{\n    // Have we got a parallel mesh?\n    this->mpDistributedMesh = dynamic_cast<DistributedTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* >(&rMesh);\n    this->mpMixedMesh = dynamic_cast<MixedDimensionMesh<ELEMENT_DIM,SPACE_DIM>* >(&rMesh);\n\n    if (PetscTools::IsSequential() || !mWriteParallelFiles || (this->mpDistributedMesh == nullptr && mpNodesOnlyMesh == nullptr))\n    {\n        AbstractTetrahedralMeshWriter<ELEMENT_DIM,SPACE_DIM>::WriteFilesUsingMesh( rMesh,keepOriginalElementIndexing );\n    }\n    else\n    {\n        //Make the local mesh into a VtkMesh\n        vtkPoints* p_pts = vtkPoints::New(VTK_DOUBLE);\n        p_pts->GetData()->SetName(\"Vertex positions\");\n\n        // Owned nodes\n        for (typename AbstractMesh<ELEMENT_DIM,SPACE_DIM>::NodeIterator node_iter = rMesh.GetNodeIteratorBegin();\n             node_iter != rMesh.GetNodeIteratorEnd();\n             ++node_iter)\n        {\n            c_vector<double, SPACE_DIM> current_item = node_iter->rGetLocation();\n            if (SPACE_DIM == 3)\n            {\n                p_pts->InsertNextPoint(current_item[0], current_item[1], current_item[2]);\n            }\n            else if (SPACE_DIM == 2)\n            {\n                p_pts->InsertNextPoint(current_item[0], current_item[1], 0.0);\n            }\n            else // (SPACE_DIM == 1)\n            {\n                p_pts->InsertNextPoint(current_item[0], 0.0, 0.0);\n            }\n        }\n\n        // Halo nodes\n        if (this->mpDistributedMesh)\n        {\n            for (typename DistributedTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>::HaloNodeIterator halo_iter=this->mpDistributedMesh->GetHaloNodeIteratorBegin();\n                    halo_iter != this->mpDistributedMesh->GetHaloNodeIteratorEnd();\n                    ++halo_iter)\n            {\n                c_vector<double, SPACE_DIM> current_item = (*halo_iter)->rGetLocation();\n                if (SPACE_DIM == 3)\n                {\n                    p_pts->InsertNextPoint(current_item[0], current_item[1], current_item[2]);\n                }\n                else if (SPACE_DIM == 2)\n                {\n                    p_pts->InsertNextPoint(current_item[0], current_item[1], 0.0);\n                }\n                else // (SPACE_DIM == 1)\n                {\n                    p_pts->InsertNextPoint(current_item[0], 0.0, 0.0);\n                }\n            }\n        }\n\n        mpVtkUnstructedMesh->SetPoints(p_pts);\n        p_pts->Delete(); //Reference counted\n\n        for (typename AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>::ElementIterator elem_iter = rMesh.GetElementIteratorBegin();\n             elem_iter != rMesh.GetElementIteratorEnd();\n             ++elem_iter)\n        {\n\n            vtkCell* p_cell=nullptr;\n            ///\\todo This ought to look exactly like the other MakeVtkMesh\n            if (ELEMENT_DIM == 3)\n            {\n                p_cell = vtkTetra::New();\n            }\n            else if (ELEMENT_DIM == 2)\n            {\n                p_cell = vtkTriangle::New();\n            }\n            else //(ELEMENT_DIM == 1)\n            {\n                p_cell = vtkLine::New();\n            }\n            vtkIdList* p_cell_id_list = p_cell->GetPointIds();\n            for (unsigned j = 0; j < ELEMENT_DIM+1; ++j)\n            {\n                unsigned global_node_index = elem_iter->GetNodeGlobalIndex(j);\n                p_cell_id_list->SetId(j, mGlobalToNodeIndexMap[global_node_index]);\n            }\n            mpVtkUnstructedMesh->InsertNextCell(p_cell->GetCellType(), p_cell_id_list);\n            p_cell->Delete(); //Reference counted\n        }\n        //If necessary, construct cables\n        if (this->mpMixedMesh )\n        {\n            AugmentCellData();\n            //Make a blank cell radius data for the regular elements\n            std::vector<double> radii(this->mpMixedMesh->GetNumLocalElements(), 0.0);\n            for (typename MixedDimensionMesh<ELEMENT_DIM,SPACE_DIM>::CableElementIterator elem_iter = this->mpMixedMesh->GetCableElementIteratorBegin();\n                 elem_iter != this->mpMixedMesh->GetCableElementIteratorEnd();\n                 ++elem_iter)\n            {\n                radii.push_back((*elem_iter)->GetAttribute());\n                vtkCell* p_cell=vtkLine::New();\n                vtkIdList* p_cell_id_list = p_cell->GetPointIds();\n                for (unsigned j = 0; j < 2; ++j)\n                {\n                    unsigned global_node_index = (*elem_iter)->GetNodeGlobalIndex(j);\n                    p_cell_id_list->SetId(j, mGlobalToNodeIndexMap[global_node_index]);\n                }\n                mpVtkUnstructedMesh->InsertNextCell(p_cell->GetCellType(), p_cell_id_list);\n                p_cell->Delete(); //Reference counted\n            }\n            AddCellData(\"Cable radius\", radii);\n        }\n\n\n        //This block is to guard the mesh writers (vtkXMLPUnstructuredGridWriter) so that they\n        //go out of scope, flush buffers and close files\n        {\n            assert(mpVtkUnstructedMesh->CheckAttributes() == 0);\n            vtkXMLPUnstructuredGridWriter* p_writer = vtkXMLPUnstructuredGridWriter::New();\n\n            p_writer->SetDataModeToBinary();\n\n            p_writer->SetNumberOfPieces(PetscTools::GetNumProcs());\n            //p_writer->SetGhostLevel(-1);\n            p_writer->SetStartPiece(PetscTools::GetMyRank());\n            p_writer->SetEndPiece(PetscTools::GetMyRank());\n\n\n#if VTK_MAJOR_VERSION >= 6\n            p_writer->SetInputData(mpVtkUnstructedMesh);\n#else\n            p_writer->SetInput(mpVtkUnstructedMesh);\n#endif\n            std::string pvtk_file_name = this->mpOutputFileHandler->GetOutputDirectoryFullPath() + this->mBaseName+ \".pvtu\";\n            p_writer->SetFileName(pvtk_file_name.c_str());\n            //p_writer->PrintSelf(std::cout, vtkIndent());\n            p_writer->Write();\n            p_writer->Delete(); //Reference counted\n        }\n\n        // Add provenance to the individual files\n        std::stringstream filepath;\n        filepath << this->mBaseName << \"_\" << PetscTools::GetMyRank() << \".vtu\";\n        AddProvenance(filepath.str());\n        /// Add to the main file \\todo #1494 Do we need a barrier?\n        if (PetscTools::AmMaster())\n        {\n            AddProvenance(this->mBaseName+ \".pvtu\");\n        }\n    }\n}\n\n// Explicit instantiation\ntemplate class VtkMeshWriter<1,1>;\ntemplate class VtkMeshWriter<1,2>;\ntemplate class VtkMeshWriter<1,3>;\ntemplate class VtkMeshWriter<2,2>; // Actually used\ntemplate class VtkMeshWriter<2,3>;\ntemplate class VtkMeshWriter<3,3>; // Actually used\n\n#endif //CHASTE_VTK\n", "meta": {"hexsha": "f5313d08c2e1bbe5ec01e9e0ab67b1e0c3a808ca", "size": 31348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mesh/src/writer/VtkMeshWriter.cpp", "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": "mesh/src/writer/VtkMeshWriter.cpp", "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": "mesh/src/writer/VtkMeshWriter.cpp", "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": 41.2473684211, "max_line_length": 157, "alphanum_fraction": 0.6285249458, "num_tokens": 7512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713268216242657, "lm_q2_score": 0.019124034829185073, "lm_q1q2_score": 0.0035787319313530658}}
{"text": "//=============================================================================================================\n/**\n * @file     main.cpp\n * @author   Daniel Strohmeier <Daniel.Strohmeier@tu-ilmenau.de>;\n *           Lorenz Esch <lesch@mgh.harvard.edu>\n * @since    0.1.0\n * @date     March, 2018\n *\n * @section  LICENSE\n *\n * Copyright (C) 2018, Daniel Strohmeier, 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    Example of the computation of spectra, PSD and CSD\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include <math.h>\n#include <disp/plots/plot.h>\n#include <utils/spectral.h>\n#include <utils/generics/applicationlogger.h>\n#include <mne/mne.h>\n\n//=============================================================================================================\n// Eigen\n//=============================================================================================================\n\n#include <Eigen/Core>\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QApplication>\n#include <QtMath>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace DISPLIB;\nusing namespace UTILSLIB;\n\n//=============================================================================================================\n// MAIN\n//=============================================================================================================\n\n//=============================================================================================================\n/**\n * The function main marks the entry point of the program.\n * By default, main has the storage class extern.\n *\n * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.\n * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.\n * @return the value that was set to exit() (which is 0 if exit() is called via quit()).\n */\nint main(int argc, char *argv[])\n{\n    qInstallMessageHandler(ApplicationLogger::customLogWriter);\n    QApplication a(argc, argv);\n\n    // Generate input data\n    int iNSamples = 500;\n    double dSampFreq = 23.0;\n    MatrixXd inputData = MatrixXd::Random(2, iNSamples);\n    for (int n = 0; n < iNSamples; n++) {\n        inputData(0, n) += 10.0 * sin(2.0 * M_PI *  10. * n / iNSamples );\n        inputData(0, n) += 10.0 * sin(2.0 * M_PI * 100. * n / iNSamples);\n        inputData(0, n) += 10.0 * sin(2.0 * M_PI * 200. * n / iNSamples);\n\n        inputData(1, n) += 10.0 * sin(2.0 * M_PI *  50. * n / iNSamples);\n        inputData(1, n) += 10.0 * sin(2.0 * M_PI * 100. * n / iNSamples);\n        inputData(1, n) += 10.0 * sin(2.0 * M_PI * 150. * n / iNSamples);\n    }\n\n    //Generate hanning window\n    QPair<MatrixXd, VectorXd> tapers = Spectral::generateTapers(iNSamples, \"hanning\");\n    MatrixXd matTaps = tapers.first;\n    VectorXd vecTapWeights = tapers.second;\n\n    //Plot hanning window\n    VectorXd hann = matTaps.row(0).transpose();\n    Plot plotWindow(hann);\n    plotWindow.setTitle(\"Hanning window\");\n    plotWindow.setXLabel(\"X Axes\");\n    plotWindow.setYLabel(\"Y Axes\");\n    plotWindow.setWindowTitle(\"Corresponding function to MATLABs plot\");\n    plotWindow.show();\n\n    //Compute Spectrum of first row of input data\n    int iNfft = iNSamples;\n    MatrixXcd matTapSpectrumSeed = Spectral::computeTaperedSpectraRow(inputData.row(0), matTaps, iNfft);\n\n    //Compute PSD\n    RowVectorXd vecPsd = Spectral::psdFromTaperedSpectra(matTapSpectrumSeed, vecTapWeights, iNfft, dSampFreq);\n\n    //Plot PSD\n    VectorXd psd = vecPsd.transpose();\n    Plot plotPsd(psd);\n    plotPsd.setTitle(\"PSD of Row 0\");\n    plotPsd.setXLabel(\"X Axes\");\n    plotPsd.setYLabel(\"Y Axes\");\n    plotPsd.setWindowTitle(\"Corresponding function to MATLABs plot\");\n    plotPsd.show();\n\n    //Check PSD\n    VectorXd psdTest = matTapSpectrumSeed.row(0).cwiseAbs2().transpose();\n    psdTest *= 2.0;\n    psdTest(0) /= 2.0;\n    if (iNfft % 2 == 0){\n        psdTest.tail(1) /= 2.0;\n    }\n    //Normalization\n    psdTest /= dSampFreq;\n\n    //Plot PSDTest\n    Plot plotPsdTest(psdTest);\n    plotPsdTest.setTitle(\"PSD of Row 0\");\n    plotPsdTest.setXLabel(\"X Axes\");\n    plotPsdTest.setYLabel(\"Y Axes\");\n    plotPsdTest.setWindowTitle(\"Corresponding function to MATLABs plot\");\n    plotPsdTest.show();\n\n    //Compute CSD of matTapSpectrumSeed and matTapSpectrumSeed\n    //The real part should be equivalent to the PSD of matTapSpectrumSeed)\n    RowVectorXcd vecCsdSeed = Spectral::csdFromTaperedSpectra(matTapSpectrumSeed, matTapSpectrumSeed, vecTapWeights, vecTapWeights, iNfft, dSampFreq);\n    VectorXd psdTest2 = vecCsdSeed.real();\n\n    //Plot PSDTest2\n    Plot plotPsdTest2(psdTest2);\n    plotPsdTest2.setTitle(\"PSD of Row 0\");\n    plotPsdTest2.setXLabel(\"X Axes\");\n    plotPsdTest2.setYLabel(\"Y Axes\");\n    plotPsdTest2.setWindowTitle(\"Corresponding function to MATLABs plot\");\n    plotPsdTest2.show();\n\n    //Check that sums of different psds of the same signal are equal\n    qDebug()<<psd.sum();\n    qDebug()<<psdTest.sum();\n    qDebug()<<psdTest2.sum();\n    RowVectorXd data_hann = inputData.row(0).cwiseProduct(matTaps.row(0));\n    qDebug()<<data_hann.row(0).cwiseAbs2().sum() * double(iNSamples) / dSampFreq;\n\n    //Compute Spectrum of second row of input data\n    MatrixXcd matTapSpectrumTarget = Spectral::computeTaperedSpectraRow(inputData.row(1), matTaps, iNfft);\n\n    //Compute CSD between seed and target\n    RowVectorXcd vecCsd = Spectral::csdFromTaperedSpectra(matTapSpectrumSeed, matTapSpectrumTarget, vecTapWeights, vecTapWeights, iNfft, dSampFreq);\n\n    //Plot real part of CSD\n    VectorXd csd = vecCsd.transpose().real();\n    Plot plotCsd(csd);\n    plotCsd.setTitle(\"Real part of the CSD of Row 0 and 1\");\n    plotCsd.setXLabel(\"X Axes\");\n    plotCsd.setYLabel(\"Y Axes\");\n    plotCsd.setWindowTitle(\"Corresponding function to MATLABs plot\");\n    plotCsd.show();\n\n    return a.exec();\n}\n", "meta": {"hexsha": "4405109deb1192ffdd95fc1608f7c11263cb3382", "size": 8130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ex_spectral/main.cpp", "max_stars_repo_name": "imsorryk/mne-cpp", "max_stars_repo_head_hexsha": "82c8bab48ee87dadfdc450afcc9fa707ad7b7de0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-14T20:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-29T20:17:57.000Z", "max_issues_repo_path": "examples/ex_spectral/main.cpp", "max_issues_repo_name": "imsorryk/mne-cpp", "max_issues_repo_head_hexsha": "82c8bab48ee87dadfdc450afcc9fa707ad7b7de0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/ex_spectral/main.cpp", "max_forks_repo_name": "imsorryk/mne-cpp", "max_forks_repo_head_hexsha": "82c8bab48ee87dadfdc450afcc9fa707ad7b7de0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-15T17:46:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T17:46:25.000Z", "avg_line_length": 44.1847826087, "max_line_length": 235, "alphanum_fraction": 0.5869618696, "num_tokens": 1906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940488158881, "lm_q2_score": 0.017176706968422117, "lm_q1q2_score": 0.003553758450020931}}
{"text": "/*\n * drakeUtil.cpp\n *\n *  Created on: Jun 19, 2013\n *      Author: russt\n */\n\n#include \"drakeUtil.h\"\n#include <string.h>\n#include <string>\n#include <math.h>\n#include <limits>\n#include <Eigen/Dense>\n#include <stdexcept>\n\nusing namespace std;\nusing namespace Eigen;\n\nbool isa(const mxArray* mxa, const char* class_str)\n// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab\n{\n  mxArray* plhs;\n  mxArray* prhs[2];\n  prhs[0] = const_cast<mxArray*>(mxa);\n  prhs[1] = mxCreateString(class_str);\n  mexCallMATLAB(1, &plhs, 2, prhs, \"isa\");\n  bool tf = *mxGetLogicals(plhs);\n  mxDestroyArray(plhs);\n  mxDestroyArray(prhs[1]);\n  return tf;\n}\n\nbool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)\n{\n  int i;\n  mxArray* ex = mexCallMATLABWithTrap(nlhs, plhs, nrhs, prhs, filename);\n  if (ex) {\n    mexPrintf(\"DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\\n\", filename);\n    for (i = 0; i < nrhs; i++)\n      mexCallMATLAB(0, NULL, 1, &prhs[i], \"disp\");\n    mxArray *report;\n    mexCallMATLAB(1, &report, 1, &ex, \"getReport\");\n    char *errmsg = mxArrayToString(report);\n    mexPrintf(errmsg);\n    mxFree(errmsg);\n    mxDestroyArray(report);\n    mexErrMsgIdAndTxt(\"Drake:mexCallMATLABsafe:CallbackError\", \"Error in MATLAB callback.\\nSee additional debugging information above\");\n    mxDestroyArray(ex);\n    return true;\n  }\n  for (i = 0; i < nlhs; i++)\n    if (!plhs[i]) {\n      mexPrintf(\"Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\\n\", filename);\n      for (i = 0; i < nrhs; i++)\n        mexCallMATLAB(0, NULL, 1, &prhs[i], \"disp\");\n      mexErrMsgIdAndTxt(\"Drake:mexCallMATLABsafe:NotEnoughOutputs\", \"Asked for %d outputs, but function only returned %d\\n\", nrhs, i);\n      return true;\n    }\n  return false;\n}\n\n\n/*\n * @param subclass_name (optional) if you want to call a class that derives from\n * DrakeMexPointer (e.g. so that you can refer to it as something more specific in\n * your matlab code), then you can pass in the alternative name here.  The constructor\n * for this class must take the same inputs as the DrakeMexPointer constructor.\n */\nmxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)\n{\n  mxClassID cid;\n  if (sizeof(ptr) == 4) cid = mxUINT32_CLASS;\n  else if (sizeof(ptr) == 8) cid = mxUINT64_CLASS;\n  else mexErrMsgIdAndTxt(\"Drake:constructDrakeMexPointer:PointerSize\", \"Are you on a 32-bit machine or 64-bit machine??\");\n\n  int nrhs = 3 + num_additional_inputs;\n  mxArray *plhs[1];\n  mxArray **prhs;  \n  prhs = new mxArray*[nrhs];\n\n  prhs[0] = mxCreateNumericMatrix(1, 1, cid, mxREAL);\n  memcpy(mxGetData(prhs[0]), &ptr, sizeof(ptr));\n\n  prhs[1] = mxCreateString(mexFunctionName());\n\n  prhs[2] = mxCreateString(name);\n\n  for (int i = 0; i < num_additional_inputs; i++)\n    prhs[3+i] = delete_fcn_additional_inputs[i];\n\n//  mexPrintf(\"deleteMethod = %s\\n name =%s\\n\", deleteMethod,name);\n\n  // call matlab to construct mex pointer object\n  if (subclass_name) {\n    mexCallMATLABsafe(1, plhs, nrhs, prhs, subclass_name);\n    if (!isa(plhs[0], \"DrakeMexPointer\")) {\n      mxDestroyArray(plhs[0]);\n      mexErrMsgIdAndTxt(\"Drake:createDrakeMexPointer:InvalidSubclass\", \"subclass_name is not a valid subclass of DrakeMexPointer\");\n    }\n  }\n  else\n    mexCallMATLABsafe(1, plhs, nrhs, prhs, \"DrakeMexPointer\");\n\n  mexLock();\n\n//  mexPrintf(\"incrementing lock count\\n\");\n\n  delete[] prhs;\n  return plhs[0];\n}\n\nvoid* getDrakeMexPointer(const mxArray* mx)\n{\n  void* ptr = NULL;\n\n  // todo: optimize this by caching the pointer values, as described in\n  // http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590\n  mxArray* ptrArray = mxGetProperty(mx, 0, \"ptr\");\n\n  if (!ptrArray)\n    mexErrMsgIdAndTxt(\"Drake:getDrakeMexPointer:BadInputs\", \"cannot retrieve 'ptr' field from this mxArray.  are you sure it's a valid DrakeMexPointer object?\");\n\n  switch (sizeof(void*)) { \n    case 4:\n      if (!mxIsUint32(ptrArray))\n        mexErrMsgIdAndTxt(\"Drake:getDrakeMexPointer:BadPointerSize\", \"DrakeMexPointer expected a 32-bit ptr field but got something else\");        \n      break;\n    case 8:\n      if (!mxIsUint64(ptrArray))\n        mexErrMsgIdAndTxt(\"Drake:getDrakeMexPointer:BadPointerSize\", \"DrakeMexPointer expected a 64-bit ptr field but got something else\");        \n      break;\n    default:\n      mexErrMsgIdAndTxt(\"Drake:getDrakeMexPointer:BadPointerSize\", \"DrakeMexPointer got a pointer that was neither 32-bit nor 64-bit.\");\n  }\n\n  if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray) != 1)\n    mexErrMsgIdAndTxt(\"Drake:getDrakeMexPointer:BadInputs\",\"the ptr property of this DrakeMexPointer does not appear to contain a valid pointer\");\n  memcpy(&ptr, mxGetData(ptrArray), sizeof(ptr));     // note: could use a reinterpret_cast here instead\n\n  return ptr;\n}\n\ndouble angleAverage(double theta1, double theta2) {\n  // Computes the average between two angles by averaging points on the unit\n  // circle and taking the arctan of the result.\n  //   see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities\n  // theta1 is a scalar or column vector of angles (rad)\n  // theta2 is a scalar or column vector of angles (rad)\n\n  double x_mean = 0.5 * (cos(theta1) + cos(theta2));\n  double y_mean = 0.5 * (sin(theta1) + sin(theta2));\n\n  double angle_mean = atan2(y_mean, x_mean);\n\n  return angle_mean;\n}\n\nstd::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)\n{\n  // TODO: implement multi-column version\n  using namespace Eigen;\n\n  if (abs(normal.squaredNorm() - 1.0) > 1e-12) {\n    mexErrMsgIdAndTxt(\"Drake:resolveCenterOfPressure:BadInputs\", \"normal should be a unit vector\");\n  }\n\n  Vector3d cop;\n  double normal_torque_at_cop;\n\n  double fz = normal.dot(force);\n  bool cop_exists = abs(fz) > 1e-12;\n\n  if (cop_exists) {\n    auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);\n    double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);\n    auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;\n    cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;\n    auto torque_at_cop = torque - cop.cross(force);\n    normal_torque_at_cop = normal.dot(torque_at_cop);\n  }\n  else {\n    cop.setConstant(std::numeric_limits<double>::quiet_NaN());\n    normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();\n  }\n  return std::pair<Vector3d, double>(cop, normal_torque_at_cop);\n}\n\ndouble * mxGetPrSafe(const mxArray *pobj) {\n  if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt(\"Drake:mxGetPrSafe:BadInputs\", \"mxGetPr can only be called on arguments which correspond to Matlab doubles\");\n  return mxGetPr(pobj);\n}\n\nmxArray* mxGetPropertySafe(const mxArray* array, std::string const& field_name) {\n  return mxGetPropertySafe(array, 0, field_name);\n}\n\nmxArray* mxGetPropertySafe(const mxArray* array, size_t index, std::string const& field_name)\n{\n  mxArray* ret = mxGetProperty(array, index, field_name.c_str());\n  if (!ret)\n  {\n    mexErrMsgIdAndTxt(\"Drake:mxGetPropertySafe\", (\"Field not found: \" + field_name).c_str());\n  }\n  return ret;\n}\n\nmxArray* mxGetFieldSafe(const mxArray* array, std::string const& field_name) {\n  return mxGetFieldSafe(array, 0, field_name);\n}\n\nmxArray* mxGetFieldSafe(const mxArray* array, size_t index, std::string const& field_name)\n{\n  mxArray* ret = mxGetField(array, index, field_name.c_str());\n  if (!ret)\n  {\n    mexErrMsgIdAndTxt(\"Drake:mxGetFieldSafe\", (\"Field not found: \" + field_name).c_str());\n  }\n  return ret;\n}\n\nvoid mxSetFieldSafe(mxArray* array, size_t index, std::string const & fieldname, mxArray* data)\n{\n  int fieldnum;\n  fieldnum = mxGetFieldNumber(array, fieldname.c_str());\n  if (fieldnum < 0) {\n    fieldnum = mxAddField(array, fieldname.c_str());\n  }\n  mxSetFieldByNumber(array, index, fieldnum, data);\n}\n\nconst std::vector<double> matlabToStdVector(const mxArray* in) {\n  // works for both row vectors and column vectors\n  if (mxGetM(in) != 1 && mxGetN(in) != 1)\n    throw runtime_error(\"Not a vector\");\n  double* data = mxGetPrSafe(in);\n  return std::vector<double>(data, data + mxGetNumberOfElements(in));\n}\n\nint sub2ind(mwSize ndims, const mwSize* dims, const mwSize* sub) {\n  int stride = 1;\n  int ret = 0;\n  for (int i = 0; i < ndims; i++) {\n    ret += sub[i] * stride;\n    stride *= dims[i];\n  }\n  return ret;\n}\n\nvoid sizecheck(const mxArray* mat, int M, int N) {\n  if (mxGetM(mat) != M) {\n    mexErrMsgIdAndTxt(\"Drake:WrongSize\", \"wrong number of rows. Expected: %d but got: %d\", M, mxGetM(mat));\n  }\n  if (mxGetN(mat) != N) {\n    mexErrMsgIdAndTxt(\"Drake:WrongSize\", \"wrong number of columns. Expected: %d but got: %d\", N, mxGetN(mat));\n  }\n  return;\n}\n\n//builds a matlab sparse matrix in mex from a given eigen matrix\n//the caller is responsible for destroying the resulting array\ntemplate <typename Derived>\nmxArray* eigenToMatlabSparse(MatrixBase<Derived> const & M, int & num_non_zero) \n{\n  const mwSize rows = M.rows();\n  const mwSize cols = M.cols();\n\n  vector<mwIndex> ir;\n  vector<mwIndex> jc;\n  vector<double> pr;\n\n  mwSize cumulative_nonzero = 0;\n  jc.push_back(cumulative_nonzero);\n  double eps = std::numeric_limits<double>::epsilon();\n  for (mwIndex j = 0; j < cols; j++) {\n    for (mwIndex i = 0; i < rows; i++)  {\n      double value = M(i, j);\n      \n      if (value > eps || value < -eps) {\n        ir.push_back(i);\n        pr.push_back(value);\n        cumulative_nonzero++;\n      }\n    }\n    jc.push_back(cumulative_nonzero);\n  }\n\n  mxArray* sparse_mex = mxCreateSparse(rows, cols, cumulative_nonzero, mxREAL);\n  \n  memcpy((double*)mxGetPr(sparse_mex), pr.data(), cumulative_nonzero * sizeof(double));\n  memcpy((int*)mxGetIr(sparse_mex), ir.data(), cumulative_nonzero * sizeof(mwIndex));\n  memcpy((int *)mxGetJc(sparse_mex), jc.data(), (cols + 1) * sizeof(mwIndex));\n\n  num_non_zero = cumulative_nonzero;\n  return sparse_mex;\n}\n\ntemplate DLLEXPORT mxArray* eigenToMatlabSparse(MatrixBase< MatrixXd > const &, int &) ;\ntemplate DLLEXPORT mxArray* eigenToMatlabSparse(MatrixBase< Map< MatrixXd> > const &, int &) ;\n", "meta": {"hexsha": "169a610c970c6dbc4ba9f4913e8c8b16c382eb5d", "size": 10346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/drakeUtil.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/drakeUtil.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/drakeUtil.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.602006689, "max_line_length": 169, "alphanum_fraction": 0.7005606031, "num_tokens": 2971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1329642436335826, "lm_q2_score": 0.026355351221026283, "lm_q1q2_score": 0.0035043193408011777}}
{"text": "/*\n * Copyright (c) 2006, Yuuki Takano (ytakanoster@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 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 writers 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 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#ifndef BN_HPP\n#define BN_HPP\n\n\n#include \"common.hpp\"\n\n#include <stdio.h>\n\n#include <arpa/inet.h>\n\n#include <exception>\n#include <iostream>\n#include <string>\n\n#include <boost/functional/hash.hpp>\n\nnamespace libcage {\n// this is a sizeof(T) * N bytes integer class\n// T should be unsigned\n// T should not be long long\n        template <typename T, int N>\n        class bn\n        {\n        public:\n                bn();\n                bn(const bn<T, N> &rhs);\n                bn(T rhs);\n\n                ~bn(){};\n\n                // for assign\n                bn<T, N>        operator =(const bn<T, N> &rhs);\n                bn<T, N>        operator =(T rhs);\n\n                // for addition\n                bn<T, N>        operator +(const bn<T, N> &rhs) const;\n                bn<T, N>        operator +(T rhs) const;\n                bn<T, N>        operator +=(const bn<T, N> &rhs);\n                bn<T, N>        operator +=(T rhs);\n                // friend bn<T, N> operator +<T, N>(T lhs, const bn<T, N> &rhs);\n\n                // for substraction\n                bn<T, N>        operator -(const bn<T, N> &rhs) const;\n                bn<T, N>        operator -(T rhs) const;\n                bn<T, N>        operator -=(const bn<T, N> &rhs);\n                bn<T, N>        operator -=(T rhs);\n                // friend bn<T, N> operator -<T, N>(T lhs, const bn<T, N> &rhs);\n\n                // for multiplication\n                bn<T, N>        operator *(const bn<T, N> &rhs) const;\n                bn<T, N>        operator *(T rhs) const;\n                bn<T, N>        operator *=(const bn<T, N> &rhs);\n                bn<T, N>        operator *=(T rhs);\n                // friend bn<T, N> operator *<T, N>(T lhs, const bn<T, N> &rhs);\n\n                // for exclusive or\n                bn<T, N>        operator ^(const bn<T, N> &rhs) const;\n                bn<T, N>        operator ^(T rhs) const;\n                bn<T, N>        operator ^=(const bn<T, N> &rhs);\n                bn<T, N>        operator ^=(T rhs);\n\n                // for and\n                bn<T, N>        operator &(const bn<T, N> &rhs) const;\n                bn<T, N>        operator &(T rhs) const;\n                bn<T, N>        operator &=(const bn<T, N> &rhs);\n                bn<T, N>        operator &=(T rhs);\n\n                // for not\n                bn<T, N>        operator ~();\n\n                // for multiplication with double\n                bn<T, N>        operator *(double rhs) const;\n                bn<T, N>        operator *=(double rhs);\n                // friend bn<T, N> operator *<T, N>(double lhs, const bn<T, N> &rhs);\n\n                // for shift\n                bn<T, N>        operator <<(int rhs) const;\n                bn<T, N>        operator >>(int rhs) const;\n                bn<T, N>        operator <<=(int rhs);\n                bn<T, N>        operator >>=(int rhs);\n\n                // for comparison\n                bool            operator ==(const bn<T, N> &rhs) const;\n                bool            operator !=(const bn<T, N> &rhs) const;\n                bool            operator <=(const bn<T, N> &rhs) const;\n                bool            operator >=(const bn<T, N> &rhs) const;\n                bool            operator <(const bn<T, N> &rhs) const;\n                bool            operator >(const bn<T, N> &rhs) const;\n\n                                operator T() const { return m_num[N - 1]; }\n                                operator T&() { return m_num[N - 1]; }\n\n\n                void            fill_zero();\n                void            fill_max();\n                void            to_binary(void *buf, int len) const;\n                void            from_binary(const void *buf, int len);\n                bool            is_zero() const;\n\n                std::string     to_string() const;\n\n                size_t          hash_value() const;\n\n//  operator -(const bn &rhs);\n//  operator *(const bn &rhs);\n\n#ifdef DEBUG\n                void            dump() const;\n#endif\n\n        private:\n                T               m_num[N];\n\n                static uint64_t m_exp_mask;\n\n                void            shift_right(int bits, T arr[], int size) const;\n                void            shift_left(int bits, T arr[], int size) const;\n\n        };\n\n\n\n// using namespace std;\n\n        template <typename T, int N>\n        uint64_t\n        bn<T, N>::m_exp_mask = (((uint64_t)1 << 11) - 1) << 52;\n\n        template <typename T, int N>\n        bn<T, N>::bn()\n        {\n\n        }\n\n        template <typename T, int N>\n        bn<T, N>::bn(const bn<T, N> &rhs)\n        {\n                for (int i = 0; i < N; i++)\n                        m_num[i] = rhs.m_num[i];\n        }\n\n        template <typename T, int N>\n        bn<T, N>::bn(T rhs)\n        {\n                *this = rhs;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator =(const bn<T, N> &rhs)\n        {\n                for (int i = 0; i < N; i++)\n                        m_num[i] = rhs.m_num[i];\n\n                return *this;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator =(T rhs)\n        {\n                for (int i = 0; i < N - 1; i++)\n                        m_num[i] = 0;\n\n                m_num[N - 1] = rhs;\n\n                return *this;\n        }\n\n#define PLUS_BN()                                       \\\n        do {                                            \\\n                T               carry = 0;              \\\n                T               tmp;                    \\\n                                                        \\\n                for (int i = N - 1; i >= 0; i--) {      \\\n                        tmp = m_num[i] + rhs.m_num[i];  \\\n                        if (tmp < m_num[i]) {           \\\n                                tmp = tmp + carry;      \\\n                                carry = 1;              \\\n                        } else {                        \\\n                                tmp = tmp + carry;      \\\n                                if (tmp < carry)        \\\n                                        carry = 1;      \\\n                                else                    \\\n                                        carry = 0;      \\\n                        }                               \\\n                        n.m_num[i] = tmp;               \\\n                }                                       \\\n                                                        \\\n                return n;                               \\\n        } while (0);\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator +(const bn<T, N> &rhs) const\n        {\n                bn<T, N>        n;\n\n                PLUS_BN();\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator +=(const bn<T, N> &rhs)\n        {\n                bn<T, N>       &n = *this;\n\n                PLUS_BN();\n        }\n\n#undef PLUS_BN\n\n#define PLUS_T()                                        \\\n        do{                                             \\\n                T               carry;                  \\\n                T               tmp;                    \\\n                                                        \\\n                tmp = m_num[N - 1] + rhs;               \\\n                if (tmp < m_num[N - 1])                 \\\n                        carry = 1;                      \\\n                else                                    \\\n                        carry = 0;                      \\\n                                                        \\\n                n.m_num[N - 1] = tmp;                   \\\n                                                        \\\n                for (int i = N - 2; i >= 0; i--) {      \\\n                        tmp = m_num[i] + carry;         \\\n                        if (tmp < m_num[i])             \\\n                                carry = 1;              \\\n                        else                            \\\n                                carry = 0;              \\\n                        n.m_num[i] = tmp;               \\\n                }                                       \\\n                                                        \\\n                return n;                               \\\n        } while (0);\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator +(T rhs) const\n        {\n                bn<T, N>        n;\n\n                PLUS_T();\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator +=(T rhs)\n        {\n                bn<T, N>       &n = *this;\n\n                PLUS_T();\n        }\n\n#undef PLUS_T\n\n/*\n  template <typename T, int N>\n  bn<T, N>\n  operator +(T lhs, const bn<T, N> &rhs)\n  {\n  return rhs + lhs;\n  }\n*/\n\n#define MINUS_BN()                                      \\\n        do {                                            \\\n                T               borrow = 0;             \\\n                T               tmp;                    \\\n                                                        \\\n                for (int i = N - 1; i >= 0; i--) {      \\\n                        tmp = m_num[i] - rhs.m_num[i];  \\\n                        if (tmp > m_num[i]) {           \\\n                                tmp = tmp - borrow;     \\\n                                borrow = 1;             \\\n                        } else {                        \\\n                                tmp = tmp - borrow;     \\\n                                if (tmp == (T)-1)       \\\n                                        borrow = 1;     \\\n                                else                    \\\n                                        borrow = 0;     \\\n                        }                               \\\n                        n.m_num[i] = tmp;               \\\n                }                                       \\\n                                                        \\\n                return n;                               \\\n        } while (0);\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator -(const bn<T, N> &rhs) const\n        {\n                bn<T, N>        n;\n\n                MINUS_BN();\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator -=(const bn<T, N> &rhs)\n        {\n                bn<T, N>       &n = *this;\n\n                MINUS_BN();\n        }\n\n#undef MINUS_BN\n\n#define MINUS_T()                                       \\\n        do {                                            \\\n                T               borrow;                 \\\n                T               tmp;                    \\\n                                                        \\\n                tmp = m_num[N - 1] - rhs;               \\\n                if (tmp > m_num[N - 1])                 \\\n                        borrow = 1;                     \\\n                else                                    \\\n                        borrow = 0;                     \\\n                                                        \\\n                n.m_num[N - 1] = tmp;                   \\\n                                                        \\\n                for (int i = N - 2; i >= 0; i--) {      \\\n                        tmp = m_num[i] - borrow;        \\\n                        if (tmp > m_num[i])             \\\n                                borrow = 1;             \\\n                        else                            \\\n                                borrow = 0;             \\\n                        n.m_num[i] = tmp;               \\\n                }                                       \\\n                                                        \\\n                return n;                               \\\n                                                        \\\n        } while (0);\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator -(T rhs) const\n        {\n                bn<T, N>        n;\n\n                MINUS_T();\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator -=(T rhs)\n        {\n                bn<T, N>       &n = *this;\n\n                MINUS_T();\n        }\n\n#undef MINUS_T\n\n/*\n  template <typename T, int N>\n  bn<T, N>\n  operator -(T lhs, const bn<T, N> &rhs)\n  {\n  return rhs - lhs;\n  }\n*/\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator *(const bn<T, N> &rhs) const\n        {\n                bn<T, N>        n;\n                T               carry;\n                uint64_t        u;\n                int             i, j;\n\n                for (i = 0; i < N; i++)\n                        n.m_num[i] = 0;\n\n                for (i = N - 1; i >= 0; i--) {\n                        carry = 0;\n                        for (j = N - 1; j >= 0; j--) {\n                                int ij = N - 1 - (N - 1 - i + N - 1 - j);\n                                if (ij >= 0) {\n                                        u = (uint64_t)n.m_num[ij] +\n                                                (uint64_t)rhs.m_num[j] *\n                                                (uint64_t)m_num[i] +\n                                                (uint64_t)carry;\n                                        n.m_num[ij] = u &\n                                                (((uint64_t)1 <<\n                                                  sizeof(m_num[0]) * 8) - 1);\n                                        carry = u >> sizeof(m_num[0]) * 8;\n                                }\n                        }\n                }\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator *=(const bn<T, N> &rhs)\n        {\n                *this = *this * rhs;\n\n                return *this;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator *(T rhs) const\n        {\n                bn<T, N>        n;\n                T               carry;\n                uint64_t        u;\n                int             i;\n\n                for (i = 0; i < N; i++)\n                        n.m_num[i] = 0;\n\n                for (i = N - 1; i >= 0; i--) {\n                        carry = 0;\n                        u = (uint64_t)n.m_num[i] +\n                                (uint64_t)rhs *\n                                (uint64_t)m_num[i] +\n                                (uint64_t)carry;\n                        n.m_num[i] = u & (((uint64_t)1 <<\n                                           sizeof(m_num[0]) * 8) - 1);\n                        carry = u >> sizeof(m_num[0]) * 8;\n                }\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator *=(T rhs)\n        {\n                *this = *this * rhs;\n\n                return *this;\n        }\n\n/*\n  template <typename T, int N>\n  bn<T, N>\n  operator *(T lhs, const bn<T, N> &rhs)\n  {\n  bn<T, N>        n;\n\n  n = rhs * lhs;\n\n  return n;\n  }\n*/\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator ^(const bn<T, N> &rhs) const\n        {\n                bn<T, N>        n;\n                int             i;\n\n                for (i = 0; i < N; i++) {\n                        n.m_num[i] = m_num[i] ^ rhs.m_num[i];\n                }\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator ^=(const bn<T, N> &rhs)\n        {\n                int i;\n                for (i = 0; i < N; i++) {\n                        m_num[i] ^= rhs.m_num[i];\n                }\n\n                return *this;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator ^(T rhs) const\n        {\n                bn<T, N>        n;\n\n                n = *this;\n                n.m_rhs[0] ^= rhs;\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator ^=(T rhs)\n        {\n                m_num[0] ^= rhs;\n\n                return *this;\n        }\n\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator &(const bn<T, N> &rhs) const\n        {\n                bn<T, N>        n;\n                int             i;\n\n                for (i = 0; i < N; i++) {\n                        n.m_num[i] = m_num[i] & rhs.m_num[i];\n                }\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator &=(const bn<T, N> &rhs)\n        {\n                int i;\n                for (i = 0; i < N; i++) {\n                        m_num[i] &= rhs.m_num[i];\n                }\n\n                return *this;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator &(T rhs) const\n        {\n                bn<T, N>        n;\n\n                n = *this;\n                n.m_rhs[0] &= rhs;\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator &=(T rhs)\n        {\n                m_num[0] &= rhs;\n\n                return *this;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator ~()\n        {\n                bn<T, N>        n;\n\n                for (int i = 0; i < N; i++)\n                        n.m_num[i] = ~m_num[i];\n\n                return n;\n        }\n\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator *(double rhs) const\n        {\n                bn<T, N>        n;\n                T               flo[2 * N];\n                T               result[2 * N];\n                T               carry;\n                uint64_t      bits;\n                uint64_t      decimal;\n                uint64_t      mask;\n                uint64_t      u;\n                long long       exp_part;\n                int             shift;\n                int             i, j;\n\n                memcpy(&bits, &rhs, sizeof(bits));\n\n                // bits = *((uint64_t*)&rhs);\n\n                decimal = bits << 12;\n                exp_part = bits & m_exp_mask;\n                exp_part >>= 52;\n                exp_part -= 1023;\n\n                memset(flo, 0, sizeof(flo));\n\n                flo[N - 1] = 1;\n\n                shift = sizeof(decimal) / sizeof(flo[0]);\n                shift = (shift - 1) * 8 * sizeof(flo[0]);\n\n                mask = ~(T)0;\n\n                for (i = N; i < 2 * N && shift >= 0;\n                     shift -= sizeof(flo[0]) * 8, i++)\n                        flo[i] = (T)((decimal >> shift) & mask);\n\n                shift_left((int)exp_part, flo, sizeof(flo) / sizeof(flo[0]));\n\n                for (i = 0; i < N; i++)\n                        result[i] = 0;\n\n                for (i = N - 1; i >= 0; i--) {\n                        carry = 0;\n                        for (j = 2 * N - 1; j >= 0; j--) {\n                                int ij = 2 * N - 1 -\n                                        (N - 1 - i + 2 * N - 1 - j);\n                                if (ij >= 0) {\n                                        u = (uint64_t)result[ij] +\n                                                (uint64_t)flo[j] *\n                                                (uint64_t)m_num[i] +\n                                                (uint64_t)carry;\n                                        result[ij] = (T)(u &\n                                                         (((uint64_t)1 <<\n                                                           sizeof(result[0]) *\n                                                           8) - 1));\n                                        carry = (T)(u >> sizeof(result[0]) * 8);\n                                }\n                        }\n                }\n\n                for (int i = 0; i < N; i++)\n                        n.m_num[i] = result[i];\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator *=(double rhs)\n        {\n                *this = *this * rhs;\n\n                return *this;\n        }\n\n/*\n  template <typename T, int N>\n  bn<T, N>\n  operator *(double lhs, const bn<T, N> &rhs)\n  {\n  bn<T, N>        n;\n\n  n = rhs * lhs;\n\n  return n;\n  }\n*/\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator <<(int rhs) const\n        {\n                bn<T, N>        n(*this);\n\n                shift_left(rhs, n.m_num, N);\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator >>(int rhs) const\n        {\n                bn<T, N>        n(*this);\n\n                shift_right(rhs, n.m_num, N);\n\n                return n;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator <<=(int rhs)\n        {\n                shift_left(rhs, m_num, N);\n\n                return *this;\n        }\n\n        template <typename T, int N>\n        bn<T, N>\n        bn<T, N>::operator >>=(int rhs)\n        {\n                shift_right(rhs, m_num, N);\n\n                return *this;\n        }\n\n        template <typename T, int N>\n        bool\n        bn<T, N>::operator ==(const bn<T, N> &rhs) const\n        {\n                for (int i = 0; i < N; i++)\n                        if (m_num[i] != rhs.m_num[i])\n                                return false;\n\n                return true;\n        }\n\n        template <typename T, int N>\n        bool\n        bn<T, N>::operator !=(const bn<T, N> &rhs) const\n        {\n                return !(*this == rhs);\n        }\n\n        template <typename T, int N>\n        bool\n        bn<T, N>::operator <=(const bn<T, N> &rhs) const\n        {\n                return !(*this > rhs);\n        }\n\n        template <typename T, int N>\n        bool\n        bn<T, N>::operator >=(const bn<T, N> &rhs) const\n        {\n                return !(*this < rhs);\n        }\n\n        template <typename T, int N>\n        bool\n        bn<T, N>::operator <(const bn<T, N> &rhs) const\n        {\n                for (int i = 0; i < N; i++)\n                        if (m_num[i] < rhs.m_num[i])\n                                return true;\n                        else if (m_num[i] > rhs.m_num[i])\n                                return false;\n\n                return false;\n        }\n\n        template <typename T, int N>\n        bool\n        bn<T, N>::operator >(const bn<T, N> &rhs) const\n        {\n                for (int i = 0; i < N; i++)\n                        if (m_num[i] > rhs.m_num[i])\n                                return true;\n                        else if (m_num[i] < rhs.m_num[i])\n                                return false;\n\n                return false;\n        }\n\n        template <typename T, int N>\n        void\n        bn<T, N>::shift_right(int bits, T arr[], int size) const\n        {\n                T               mask;\n                int             n, m;\n                int             i;\n\n                if (bits < 0) {\n                        shift_left(abs(bits), arr, size);\n                        return;\n                }\n\n                n = bits / (sizeof(arr[0]) * 8);\n                m = bits % (sizeof(arr[0]) * 8);\n\n                for (i = size - 1; i >= n; i--)\n                        arr[i] = arr[i - n];\n\n                for (i = 0; i < n; i++)\n                        arr[i] = 0;\n\n                if (m == 0 || n >= size)\n                        return;\n\n                for (i = size - 1; i >= n + 1; i--) {\n                        arr[i] >>= m;\n\n                        mask = 1;\n                        mask <<= m;\n                        mask--;\n\n                        arr[i] |= (mask & arr[i - 1]) <<\n                                (sizeof(arr[0]) * 8 - m);\n                }\n\n                arr[n] >>= m;\n        }\n\n        template <typename T, int N>\n        void\n        bn<T, N>::shift_left(int bits, T arr[], int size) const\n        {\n                int             n, m;\n                int             i;\n\n                if (bits < 0) {\n                        shift_right(abs(bits), arr, size);\n                        return;\n                }\n\n                n = bits / (sizeof(arr[0]) * 8);\n                m = bits % (sizeof(arr[0]) * 8);\n\n                for (i = 0; i < size - n; i++)\n                        arr[i] = arr[i + n];\n\n                for (i = size - n; i < size; i++)\n                        arr[i] = 0;\n\n                if (m == 0 || n >= size)\n                        return;\n\n                for (i = 0; i < size - n; i++) {\n                        T msb;\n\n                        msb = arr[i + 1];\n                        msb >>= sizeof(T) * 8 - m;\n\n                        arr[i] <<= m;\n                        arr[i] |= msb;\n                }\n\n                arr[i] <<= m;\n        }\n\n        template <typename T, int N>\n        void\n        bn<T, N>::fill_zero()\n        {\n                memset(m_num, 0, N * sizeof(T));\n        }\n\n        template <typename T, int N>\n        void\n        bn<T, N>::fill_max()\n        {\n                for (int i = 0; i < N; i++)\n                        m_num[i] = ~(T)0;\n        }\n\n        template <typename T, int N>\n        void\n        bn<T, N>::to_binary(void *buf, int len) const\n        {\n                T              *num;\n                int             i;\n\n                num = (T*)buf;\n\n                for (i = 0; len >= (int)sizeof(T); i++, len -= (int)sizeof(T)) {\n                        if (sizeof(T) == 4) {\n                                uint32_t n = (uint32_t)m_num[i];\n                                num[i] = htonl(n);\n                        } else if (sizeof(T) == 2) {\n                                uint16_t n = (uint16_t)m_num[i];\n                                num[i] = htons(n);\n                        } else if (sizeof(T) == 1) {\n                                num[i] = m_num[i];\n                        }\n                }\n        }\n\n        template <typename T, int N>\n        void\n        bn<T, N>::from_binary(const void *buf, int len)\n        {\n                const T        *num;\n                int             i;\n\n                num = (T*)buf;\n\n                memset(m_num, 0, sizeof(m_num));\n\n                for (i = 0; i < N && len >= (int)sizeof(T);\n                     i++, len -= (int)sizeof(T))\n                {\n                        if (sizeof(T) == 4) {\n                                uint32_t n = (uint32_t)num[i];\n                                m_num[i] = ntohl(n);\n                        } else if (sizeof(T) == 2) {\n                                uint16_t n = (uint16_t)num[i];\n                                m_num[i] = ntohs(n);\n                        }else if (sizeof(T) == 1) {\n                                m_num[i] = num[i];\n                        }\n                }\n        }\n\n        template <typename T, int N>\n        bool\n        bn<T, N>::is_zero() const\n        {\n                T               zero = 0;\n\n                for (int i = 0; i < N; i++)\n                        if (m_num[i] != zero)\n                                return false;\n\n                return true;\n        }\n\n        static const char *hexstr[16] = {\"0\", \"1\", \"2\", \"3\",\n                                         \"4\", \"5\", \"6\", \"7\",\n                                         \"8\", \"9\", \"a\", \"b\",\n                                         \"c\", \"d\", \"e\", \"f\"};\n\n        template <typename T, int N>\n        std::string\n        bn<T, N>::to_string() const\n        {\n                T               num[N];\n                unsigned int    i;\n                char           *p;\n                std::string     str;\n\n                to_binary((char*)num, sizeof(num));\n\n                try {\n                        str = \"\";\n                        p = (char*)num;\n\n                        for (i = 0; i < sizeof(T) * N; i++) {\n                                uint8_t t1, t2;\n                                t1 = (0x00f0 & (p[i])) >> 4;\n                                t2 = 0x000f & (p[i]);\n                                str += hexstr[t1];\n                                str += hexstr[t2];\n                        }\n                } catch(std::exception &e) {\n                        std::cerr << \"get_string(): \" << e.what() << std::endl;\n                        return str;\n                }\n\n                return str;\n        }\n\n        template <typename T, int N>\n        size_t\n        bn<T, N>::hash_value() const\n        {\n                size_t h = 0;\n\n                for (int i = 0; i < N; i++) {\n                        boost::hash_combine(h, m_num[i]);\n                }\n\n                return h;\n\n        }\n\n#ifdef DEBUG\n        template <typename T, int N>\n        void\n        bn<T, N>::dump() const\n        {\n                std::string     str;\n                int             i;\n                char           *p;\n\n                str = \"\";\n                p = (char*)m_num;\n\n                std::cout << \"0x\";\n                for (i = 0; i < sizeof(T) * N; i++) {\n                        uint8_t t1, t2;\n                        t1 = (0x00f0 & (p[i])) >> 4;\n                        t2 = 0x000f & (p[i]);\n                        str += hexstr[t1];\n                        str += hexstr[t2];\n                }\n                std::cout << str << std::endl;\n        }\n#endif\n\n        typedef bn<uint32_t, 4> uint128_t;\n        typedef bn<uint32_t, 5> uint160_t;\n\n        inline\n        size_t\n        hash_value(const uint128_t &num)\n        {\n                return num.hash_value();\n        }\n\n        inline\n        size_t\n        hash_value(const uint160_t &num)\n        {\n                return num.hash_value();\n        }\n}\n\n#endif // BN_HPP\n", "meta": {"hexsha": "aece9237318c5a11788d44ec757d3faf8a03794a", "size": 31329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/bn.hpp", "max_stars_repo_name": "jb55/libcage", "max_stars_repo_head_hexsha": "7d39947a5c73bfba2e0b68513ded7a9de0d8dac6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-29T11:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-29T11:00:09.000Z", "max_issues_repo_path": "src/bn.hpp", "max_issues_repo_name": "jb55/libcage", "max_issues_repo_head_hexsha": "7d39947a5c73bfba2e0b68513ded7a9de0d8dac6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bn.hpp", "max_forks_repo_name": "jb55/libcage", "max_forks_repo_head_hexsha": "7d39947a5c73bfba2e0b68513ded7a9de0d8dac6", "max_forks_repo_licenses": ["BSD-3-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.5947265625, "max_line_length": 85, "alphanum_fraction": 0.3054996968, "num_tokens": 6901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940488158881, "lm_q2_score": 0.016914913452567824, "lm_q1q2_score": 0.00349959492957209}}
{"text": "//=============================================================================================================\n/**\n* @file     rthpis.cpp\n* @author   Chiran Doshi <chiran.doshi@childrens.harvard.edu>;\n*           Lorenz Esch <Lorenz.Esch@ntu-ilmenau.de>;\n*           Limin Sun <liminsun@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n*\n* @version  1.0\n* @date     November, 2016\n*\n* @section  LICENSE\n*\n* Copyright (C) 2016, Chiran Doshi, Lorenz Esch, Limin Sun, and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief     implementation of the RtHPIS Class.\n*\n*/\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"rthpis.h\"\n\n#include <fiff/fiff_dig_point_set.h>\n\n#include <utils/ioutils.h>\n\n#include <iostream>\n#include <fiff/fiff_cov.h>\n#include <fstream>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// EIGEN INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Dense>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QDebug>\n#include <QFuture>\n#include <QtConcurrent/QtConcurrent>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace RTPROCESSINGLIB;\nusing namespace FIFFLIB;\nusing namespace Eigen;\nusing namespace IOBUFFER;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\nstd::vector <double> m_base_arr;\n\nEigen::MatrixXd pinv(Eigen::MatrixXd a)\n{\n    double epsilon = std::numeric_limits<double>::epsilon();\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n    double tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs()(0);\n    return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(),0).matrix().asDiagonal() * svd.matrixU().adjoint();\n}\n\n\n/*********************************************************************************\n * magnetic_dipole leadfield for a magnetic dipole in an infinite medium\n * The function has been compared with matlab magnetic_dipole and it gives same output\n *********************************************************************************/\n\nEigen::MatrixXd magnetic_dipole(Eigen::MatrixXd pos, Eigen::MatrixXd pnt, Eigen::MatrixXd ori) {\n\n    double u0 = 1e-7;\n    int nchan;\n    Eigen::MatrixXd r, r2, r5, x, y, z, mx, my, mz, Tx, Ty, Tz, lf, temp;\n\n    nchan = pnt.rows();\n\n    // Shift the magnetometers so that the dipole is in the origin\n    pnt.array().col(0) -= pos(0);pnt.array().col(1) -= pos(1);pnt.array().col(2) -= pos(2);\n\n    r = pnt.array().square().rowwise().sum().sqrt();\n\n   r2 = r5 = x = y = z = mx = my = mz = Tx = Ty = Tz = lf = Eigen::MatrixXd::Zero(nchan,3);\n\n    for(int i = 0;i < nchan;i++) {\n            r2.row(i).array().fill(pow(r(i),2));\n            r5.row(i).array().fill(pow(r(i),5));\n    }\n\n    for(int i = 0;i < nchan;i++) {\n        x.row(i).array().fill(pnt(i,0));\n        y.row(i).array().fill(pnt(i,1));\n        z.row(i).array().fill(pnt(i,2));\n    }\n    mx.col(0).array().fill(1);my.col(1).array().fill(1);mz.col(2).array().fill(1);\n\n    Tx = 3 * x.cwiseProduct(pnt) - mx.cwiseProduct(r2);\n    Ty = 3 * y.cwiseProduct(pnt) - my.cwiseProduct(r2);\n    Tz = 3 * z.cwiseProduct(pnt) - mz.cwiseProduct(r2);\n\n    for(int i = 0;i < nchan;i++) {\n        lf(i,0) = Tx.row(i).dot(ori.row(i));\n        lf(i,1) = Ty.row(i).dot(ori.row(i));\n        lf(i,2) = Tz.row(i).dot(ori.row(i));\n    }\n\n    for(int i = 0;i < nchan;i++) {\n        for(int j = 0;j < 3;j++) {\n            lf(i,j) = u0 * lf(i,j)/(4 * M_PI * r5(i,j));\n        }\n    }\n    return lf;\n}\n\n\n/*********************************************************************************\n * ft_compute_leadfield computes a forward solution for a dipole in a a volume\n * conductor model. The forward solution is expressed as the leadfield\n * matrix (Nchan*3), where each column corresponds with the potential or field\n * distributions on all sensors for one of the x,y,z-orientations of the dipole.\n * The function has been compared with matlab ft_compute_leadfield and it gives\n * same output\n *********************************************************************************/\n\nEigen::MatrixXd ft_compute_leadfield(Eigen::MatrixXd pos, struct sens sensors)\n{\n\n    Eigen::MatrixXd pnt, ori, lf;\n\n    pnt = sensors.coilpos; // position of each coil\n    ori = sensors.coilori; // orientation of each coil\n\n    lf = magnetic_dipole(pos, pnt, ori);\n\n    lf = sensors.tra * lf;\n\n    return lf;\n}\n\n\n/*********************************************************************************\n * dipfitError computes the error between measured and model data\n * and can be used for non-linear fitting of dipole position.\n * The function has been compared with matlab dipfit_error and it gives\n * same output\n *********************************************************************************/\n\ndipError dipfitError(Eigen::MatrixXd pos, Eigen::MatrixXd data, struct sens sensors)\n{\n    // Variable Declaration\n    struct dipError e;\n    Eigen::MatrixXd lf, dif;\n\n    // Compute lead field for a magnetic dipole in infinite vacuum\n    lf = ft_compute_leadfield(pos, sensors);\n\n    e.moment = pinv(lf) * data;\n\n    dif = data - lf * e.moment;\n\n    e.error = dif.array().square().sum()/data.array().square().sum();\n\n    e.numIterations = 0;\n\n    return e;\n}\n\n\n/*********************************************************************************\n * Compare function for sorting\n *********************************************************************************/\n\nbool compare(sortStruct a, sortStruct b)\n{\n    return (a.base_arr < b.base_arr);\n}\n\n\n/*********************************************************************************\n * fminsearch Multidimensional unconstrained nonlinear minimization (Nelder-Mead).\n * X = fminsearch(X0, maxiter, maxfun, display, data, sensors) starts at X0 and\n * attempts to find a local minimizer\n *********************************************************************************/\n\nEigen::MatrixXd fminsearch(Eigen::MatrixXd pos,\n                           int maxiter,\n                           int maxfun,\n                           int display,\n                           Eigen::MatrixXd data,\n                           struct sens sensors,\n                           int &simplex_numitr)\n{\n    double tolx, tolf, rho, chi, psi, sigma, func_evals, usual_delta, zero_term_delta, temp1, temp2;\n    std::string header, how;\n    int n, itercount, prnt;\n    Eigen::MatrixXd onesn, two2np1, one2n, v, y, v1, tempX1, tempX2, xbar, xr, x, xe, xc, xcc, xin;\n    std::vector <double> fv, fv1;\n    std::vector <int> idx;\n\n    dipError tempdip, fxr, fxe, fxc, fxcc;\n\n    //tolx = tolf = 1e-4;\n    // Seok\n    tolx = tolf = 1e-9;\n\n    switch(display) {\n        case 0:\n            prnt = 0;\n            break;\n        default:\n            prnt = 1;\n    }\n\n    header = \" Iteration   Func-count     min f(x) Procedure\";\n\n    n = pos.cols();\n\n    // Initialize parameters\n    rho = 1; chi = 2; psi = 0.5; sigma = 0.5;\n    onesn = Eigen::MatrixXd::Ones(1,n);\n    two2np1 = one2n = Eigen::MatrixXd::Zero(1,n);\n\n    for(int i = 0;i < n;i++) {\n        two2np1(i) = 1 + i;\n        one2n(i) = i;\n    }\n\n    v = v1 = Eigen::MatrixXd::Zero(n, n+1);\n    fv.resize(n+1);\n    idx.resize(n+1);\n    fv1.resize(n+1);\n\n    for(int i = 0;i < n; i++) {\n        v(i,0) = pos(i);\n    }\n\n    tempdip = dipfitError(pos, data, sensors);\n    fv[0] = tempdip.error;\n\n    func_evals = 1;\n    itercount = 0;\n    how = \"\";\n\n    // Continue setting up the initial simplex.\n    // Following improvement suggested by L.Pfeffer at Stanford\n    usual_delta = 0.05;             // 5 percent deltas for non-zero terms\n    zero_term_delta = 0.00025;      // Even smaller delta for zero elements of x\n    xin = pos.transpose();\n\n    for(int j = 0;j < n;j++) {\n        y = xin;\n\n        if(y(j) != 0) {\n            y(j) = (1 + usual_delta) * y(j);\n        } else {\n            y(j) = zero_term_delta;\n        }\n\n        v.col(j+1).array() = y;\n        pos = y.transpose();\n        tempdip = dipfitError(pos, data, sensors);\n        fv[j+1] = tempdip.error;\n    }\n\n    // Sort elements of fv\n    std::vector<sortStruct> vecSortStruct;\n\n    for (int i = 0; i < fv.size(); i++) {\n        sortStruct structTemp;\n        structTemp.base_arr = fv[i];\n        structTemp.idx = i;\n        vecSortStruct.push_back(structTemp);\n    }\n\n    sort (vecSortStruct.begin(), vecSortStruct.end(), compare);\n\n    for (int i = 0; i < vecSortStruct.size(); i++) {\n        idx[i] = vecSortStruct[i].idx;\n    }\n\n    for (int i = 0;i < n+1;i++) {\n        v1.col(i) = v.col(idx[i]);\n        fv1[i] = fv[idx[i]];\n    }\n\n    v = v1;fv = fv1;\n\n    how = \"initial simplex\";\n    itercount = itercount + 1;\n    func_evals = n + 1;\n\n    tempX1 = Eigen::MatrixXd::Zero(1,n);\n\n    while ((func_evals < maxfun) && (itercount < maxiter)) {\n\n        for (int i = 0;i < n;i++) {\n            tempX1(i) = abs(fv[0] - fv[i+1]);\n        }\n\n        temp1 = tempX1.maxCoeff();\n\n        tempX2 = Eigen::MatrixXd::Zero(n,n);\n\n        for(int i = 0;i < n;i++) {\n            tempX2.col(i) = v.col(i+1) -  v.col(0);\n        }\n\n        tempX2 = tempX2.array().abs();\n\n        temp2 = tempX2.maxCoeff();\n\n        if((temp1 <= tolf) && (temp2 <= tolx)) {\n            break;\n        }\n\n        xbar = v.block(0,0,n,n).rowwise().sum();\n        xbar /= n;\n\n        xr = (1+rho) * xbar - rho * v.block(0,n,v.rows(),1);\n\n        x = xr.transpose();\n        //std::cout << \"Iteration Count: \" << itercount << \":\" << x << std::endl;\n\n        fxr = dipfitError(x, data, sensors);\n\n        func_evals = func_evals+1;\n\n        if (fxr.error < fv[0]) {\n            // Calculate the expansion point\n            xe = (1 + rho * chi) * xbar - rho * chi * v.col(v.cols()-1);\n            x = xe.transpose();\n            fxe = dipfitError(x, data, sensors);\n            func_evals = func_evals+1;\n\n            if(fxe.error < fxr.error) {\n                v.col(v.cols()-1) = xe;\n                fv[n] = fxe.error;\n                how = \"expand\";\n            }\n            else {\n                v.col(v.cols()-1) = xr;\n                fv[n] = fxr.error;\n                how = \"reflect\";\n            }\n        }\n        else {\n            if(fxr.error < fv[n-1]) {\n                v.col(v.cols()-1) = xr;\n                fv[n] = fxr.error;\n                how = \"reflect\";\n            }\n            else { // fxr.error >= fv[:,n-1]\n                // Perform contraction\n                if(fxr.error < fv[n]) {\n                    // Perform an outside contraction\n                    xc = (1 + psi * rho) * xbar - psi * rho * v.col(v.cols()-1);\n                    x = xc.transpose();\n                    fxc = dipfitError(x, data, sensors);\n                    func_evals = func_evals + 1;\n\n                    if(fxc.error <= fxr.error) {\n                        v.col(v.cols()-1) = xc;\n                        fv[n] = fxc.error;\n                        how = \"contract outside\";\n                    }\n                    else {\n                        // perform a shrink\n                        how = \"shrink\";\n                    }\n                }\n                else {\n                    xcc = (1 - psi) * xbar + psi * v.col(v.cols()-1);\n                    x = xcc.transpose();\n                    fxcc = dipfitError(x, data, sensors);\n                    func_evals = func_evals+1;\n                    if(fxcc.error < fv[n]) {\n                        v.col(v.cols()-1) = xcc;\n                        fv[n] = fxcc.error;\n                        how = \"contract inside\";\n                    }\n                    else {\n                        // perform a shrink\n                        how = \"shrink\";\n                    }\n                }\n                if(how.compare(\"shrink\") == 0) {\n                    for(int j = 1;j < n+1;j++) {\n                        v.col(j).array() = v.col(0).array() + sigma * (v.col(j).array() - v.col(0).array());\n                        x = v.col(j).array().transpose();\n                        tempdip = dipfitError(x,data, sensors);\n                        fv[j] = tempdip.error;\n                    }\n                }\n            }\n        }\n\n        // Sort elements of fv\n        vecSortStruct.clear();\n\n        for (int i = 0; i < fv.size(); i++) {\n            sortStruct structTemp;\n            structTemp.base_arr = fv[i];\n            structTemp.idx = i;\n            vecSortStruct.push_back(structTemp);\n        }\n\n        sort (vecSortStruct.begin(), vecSortStruct.end(), compare);\n\n        for (int i = 0; i < vecSortStruct.size(); i++) {\n            idx[i] = vecSortStruct[i].idx;\n        }\n\n        for (int i = 0;i < n+1;i++) {\n            v1.col(i) = v.col(idx[i]);\n            fv1[i] = fv[idx[i]];\n        }\n\n        v = v1;\n        fv = fv1;\n        itercount = itercount + 1;\n    } // end of while loop\n//    }while(dipfitError(x, data, sensors).error > 0.1);\n\n    x = v.col(0).transpose();\n\n    // Seok\n    simplex_numitr = itercount;\n\n    return x;\n}\n\n\n/*********************************************************************************\n * dipfit function is adapted from Fieldtrip Software. It has been\n * heavily edited for use with MNE Scan Software\n *********************************************************************************/\n\nvoid doDipfitConcurrent(QPair<QPair<Eigen::RowVectorXd, Eigen::VectorXd>, QPair<dipError, sens>> &lCoilData)\n{\n    // Initialize variables\n    Eigen::RowVectorXd currentCoil = lCoilData.first.first;\n    Eigen::VectorXd currentData = lCoilData.first.second;\n    sens currentSensors = lCoilData.second.second;\n\n    int display = 0;\n    int maxiter = 500;\n    int simplex_numitr = 0;\n\n    lCoilData.first.first = fminsearch(currentCoil,\n                                       maxiter,\n                                       2 * maxiter * currentCoil.cols(),\n                                       display,\n                                       currentData,\n                                       currentSensors,\n                                       simplex_numitr);\n\n    lCoilData.second.first = dipfitError(currentCoil, currentData, currentSensors);\n    lCoilData.second.first.numIterations = simplex_numitr;\n}\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nRtHPIS::RtHPIS(FiffInfo::SPtr p_pFiffInfo, QObject *parent)\n: QThread(parent)\n, m_pFiffInfo(p_pFiffInfo)\n, m_bIsRunning(false)\n, m_sHPIResourceDir(\"./HPIFittingDebug\")\n{\n}\n\n\n//*************************************************************************************************************\n\nRtHPIS::~RtHPIS()\n{\n    if(this->isRunning()){\n        stop();\n    }\n}\n\n\n//*************************************************************************************************************\n\nvoid RtHPIS::singleHPIFit(const MatrixXd& t_mat,\n                          FiffCoordTrans& transDevHead,\n                          const QVector<int>& vFreqs,\n                          QVector<double>& vGof,\n                          FiffDigPointSet& fittedPointSet)\n{\n    vGof.clear();\n\n    struct sens sensors;\n    struct coilParam coil;\n    int numCh = m_pFiffInfo->nchan;\n    int samF = m_pFiffInfo->sfreq;\n    int samLoc = t_mat.cols(); // minimum samples required to localize numLoc times in a second\n\n    //Get HPI coils from digitizers and set number of coils\n    int numCoils = 0;\n    QList<FiffDigPoint> lHPIPoints;\n\n    for(int i = 0; i < m_pFiffInfo->dig.size(); ++i) {\n        if(m_pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) {\n            numCoils++;\n            lHPIPoints.append(m_pFiffInfo->dig[i]);\n        }\n    }\n\n    //Set coil frequencies\n    Eigen::VectorXd coilfreq(numCoils);\n\n    if(vFreqs.size() >= numCoils) {\n        for(int i = 0; i < numCoils; ++i) {\n            coilfreq[i] = vFreqs.at(i);\n            qDebug() << coilfreq[i] << \"Hz\";\n        }\n    } else {\n        qDebug()<< \"RtHPIS::singleHPIFit - Not enough coil frequencies specified. Returning.\";\n        return;\n    }\n\n    // Initialize HPI coils location and moment\n    coil.pos = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.mom = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.dpfiterror = Eigen::VectorXd::Zero(numCoils);\n    coil.dpfitnumitr = Eigen::VectorXd::Zero(numCoils);\n\n    // Generate simulated data\n    Eigen::MatrixXd simsig(samLoc,numCoils*2);\n    Eigen::VectorXd time(samLoc);\n\n    for (int i = 0; i < samLoc; ++i) {\n        time[i] = i*1.0/samF;\n    }\n\n    for(int i = 0; i < numCoils; ++i) {\n        for(int j = 0; j < samLoc; ++j) {\n            simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]);\n            simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]);\n        }\n    }\n\n    // Create digitized HPI coil position matrix\n    Eigen::MatrixXd headHPI(numCoils,3);\n\n    // check the m_pFiffInfo->dig information. If dig is empty, set the headHPI is 0;\n    if (lHPIPoints.size() > 0) {\n        for (int i = 0; i < lHPIPoints.size(); ++i) {\n            headHPI(i,0) = lHPIPoints.at(i).r[0];\n            headHPI(i,1) = lHPIPoints.at(i).r[1];\n            headHPI(i,2) = lHPIPoints.at(i).r[2];\n        }\n    } else {\n        for (int i = 0; i < numCoils; ++i) {\n            headHPI(i,0) = 0;\n            headHPI(i,1) = 0;\n            headHPI(i,2) = 0;\n        }\n\n        qDebug() << \"\\n \\n \\n\";\n        qDebug()<< \"    **********************************************************\";\n        qDebug()<< \"   *************************************************************\";\n        qDebug()<< \"  ***************************************************************\";\n        qDebug()<< \"******************************************************************\";\n        qDebug()<< \"********    You forget to load polhemus HPI information!   *********\";\n        qDebug()<< \"***********  Please stop running and load it properly!   **********\";\n        qDebug()<< \"******************************************************************\";\n        qDebug()<< \" ****************************************************************\";\n        qDebug()<< \"  **************************************************************\";\n        qDebug()<< \"   ************************************************************\";\n        qDebug()<< \"    **********************************************************\";\n        qDebug() << \"\\n \\n \\n\";\n    }\n\n    // Get the indices of inner layer channels and exclude bad channels. Only supports babymeg and vectorview magnetometers for hpi fitting.\n    QVector<int> innerind(0);\n    for (int i = 0; i < numCh; ++i) {\n        if(m_pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG ||\n                m_pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_MAG_T1 ||\n                m_pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_MAG_T2 ||\n                m_pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_MAG_T3) {\n            // Check if the sensor is bad, if not append to innerind\n            if(!(m_pFiffInfo->bads.contains(m_pFiffInfo->ch_names.at(i)))) {\n                innerind.append(i);\n            }\n        }\n    }\n\n    // Initialize inner layer sensors\n    sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3);\n    sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size());\n\n    for(int i = 0; i < innerind.size(); i++) {\n        sensors.coilpos(i,0) = m_pFiffInfo->chs[innerind.at(i)].chpos.r0[0];\n        sensors.coilpos(i,1) = m_pFiffInfo->chs[innerind.at(i)].chpos.r0[1];\n        sensors.coilpos(i,2) = m_pFiffInfo->chs[innerind.at(i)].chpos.r0[2];\n        sensors.coilori(i,0) = m_pFiffInfo->chs[innerind.at(i)].chpos.ez[0];\n        sensors.coilori(i,1) = m_pFiffInfo->chs[innerind.at(i)].chpos.ez[1];\n        sensors.coilori(i,2) = m_pFiffInfo->chs[innerind.at(i)].chpos.ez[2];\n    }\n\n    Eigen::MatrixXd topo(innerind.size(), numCoils*2);\n    Eigen::MatrixXd amp(innerind.size(), numCoils);\n    Eigen::MatrixXd ampC(innerind.size(), numCoils);\n\n    // Get the data from inner layer channels\n    Eigen::MatrixXd innerdata(innerind.size(), t_mat.cols());\n\n    for(int j = 0; j < innerind.size(); ++j) {\n        innerdata.row(j) << t_mat.row(innerind[j]);\n    }\n\n    // Calculate topo\n    topo = innerdata * pinv(simsig).transpose(); // topo: # of good inner channel x 8\n\n    // Select sine or cosine component depending on the relative size\n    amp  = topo.leftCols(numCoils); // amp: # of good inner channel x 4\n    ampC = topo.rightCols(numCoils);\n\n    for (int j = 0; j < numCoils; ++j) {\n       float nS = 0.0;\n       float nC = 0.0;\n       for (int i = 0; i < innerind.size(); i++) {\n           nS += amp(i,j)*amp(i,j);\n           nC += ampC(i,j)*ampC(i,j);\n       }\n\n       if (nC > nS) {\n         for (int i = 0; i < innerind.size(); i++)\n           amp(i,j) = ampC(i,j);\n       }\n    }\n\n    //Find good seed point/starting point for the coil position in 3D space\n    //Find biggest amplitude per pickup coil (sensor) and store corresponding sensor channel index\n    VectorXi chIdcs(numCoils);\n\n    for (int j = 0; j < numCoils; j++) {\n        double maxVal = 0;\n        int chIdx = 0;\n\n        for (int i = 0; i < amp.rows(); ++i) {\n            if(abs(amp(i,j)) > maxVal) {\n                maxVal = abs(amp(i,j));\n\n                if(chIdx < innerind.size()) {\n                    chIdx = innerind.at(i);\n                }\n            }\n        }\n\n        chIdcs(j) = chIdx;\n    }\n\n    //Generate seed point by projection the found channel position 3cm inwards\n    Eigen::MatrixXd coilPos = Eigen::MatrixXd::Zero(numCoils,3);\n\n    for (int j = 0; j < chIdcs.rows(); ++j) {\n        int chIdx = chIdcs(j);\n\n        if(chIdx < m_pFiffInfo->chs.size()) {\n            double x = m_pFiffInfo->chs.at(chIdcs(j)).chpos.r0[0];\n            double y = m_pFiffInfo->chs.at(chIdcs(j)).chpos.r0[1];\n            double z = m_pFiffInfo->chs.at(chIdcs(j)).chpos.r0[2];\n\n            coilPos(j,0) = -1 * m_pFiffInfo->chs.at(chIdcs(j)).chpos.ez[0] * 0.03 + x;\n            coilPos(j,1) = -1 * m_pFiffInfo->chs.at(chIdcs(j)).chpos.ez[1] * 0.03 + y;\n            coilPos(j,2) = -1 * m_pFiffInfo->chs.at(chIdcs(j)).chpos.ez[2] * 0.03 + z;\n        }\n\n        std::cout << \"RtHPIS::singleHPIFit - Coil \" << j << \" max value index \" << chIdx << std::endl;\n    }\n\n    coil.pos = coilPos;\n    coil = dipfit(coil, sensors, amp, numCoils);\n\n    Eigen::Matrix4d trans = computeTransformation(headHPI,coil.pos);\n\n    // Store the final result to fiff info\n    // Set final device/head matrix and its inverse to the fiff info\n    transDevHead.from = 1;\n    transDevHead.to = 4;\n\n    for(int r = 0; r < 4; ++r) {\n        for(int c = 0; c < 4 ; ++c) {\n            transDevHead.trans(r,c) = trans(r,c);\n        }\n    }\n\n    // Also store the inverse\n    transDevHead.invtrans = transDevHead.trans.inverse();\n\n    //Calculate GOF\n    MatrixXd temp = coil.pos;\n    temp.conservativeResize(coil.pos.rows(),coil.pos.cols()+1);\n\n    temp.block(0,3,numCoils,1).setOnes();\n    temp.transposeInPlace();\n\n    MatrixXd testPos = trans * temp;\n    MatrixXd diffPos = testPos.block(0,0,3,numCoils) - headHPI.transpose();\n\n    for(int i = 0; i < diffPos.cols(); ++i) {\n        vGof.append(diffPos.col(i).norm());\n    }\n\n    //Generate final fitted points and store in digitizer set\n    for(int i = 0; i < coil.pos.rows(); ++i) {\n        FiffDigPoint digPoint;\n        digPoint.kind = FIFFV_POINT_EEG;\n        digPoint.ident = i;\n        digPoint.r[0] = coil.pos(i,0);\n        digPoint.r[1] = coil.pos(i,1);\n        digPoint.r[2] = coil.pos(i,2);\n\n        fittedPointSet << digPoint;\n    }\n\n    // DEBUG HPI fitting and write debug results\n//    std::cout << std::endl << std::endl << \"RtHPIS::singleHPIFit - Initial seed point for HPI coils\" << std::endl << coil.pos << std::endl;\n\n//    std::cout << std::endl << std::endl << \"RtHPIS::singleHPIFit - temp\" << std::endl << temp << std::endl;\n\n//    std::cout << std::endl << std::endl << \"RtHPIS::singleHPIFit - testPos\" << std::endl << testPos << std::endl;\n\n//    std::cout << std::endl << std::endl << \"RtHPIS::singleHPIFit - Diff fitted - original\" << std::endl << diffPos << std::endl;\n\n//    std::cout << std::endl << std::endl << \"RtHPIS::singleHPIFit - dev/head trans\" << std::endl << trans << std::endl;\n\n    QString sTimeStamp = QDateTime::currentDateTime().toString(\"yyMMdd_hhmmss\");\n\n    if(!QDir(m_sHPIResourceDir).exists()) {\n        QDir().mkdir(m_sHPIResourceDir);\n    }\n\n    UTILSLIB::IOUtils::write_eigen_matrix(coilPos, QString(\"%1/%2_coilPosSeed_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n\n    UTILSLIB::IOUtils::write_eigen_matrix(coil.pos, QString(\"%1/%2_coilPos_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n\n    UTILSLIB::IOUtils::write_eigen_matrix(headHPI, QString(\"%1/%2_headHPI_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n\n    MatrixXd testPosCut = testPos.transpose();//block(0,0,3,4);\n    UTILSLIB::IOUtils::write_eigen_matrix(testPosCut, QString(\"%1/%2_testPos_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n\n    MatrixXi idx_mat(chIdcs.rows(),1);\n    idx_mat.col(0) = chIdcs;\n    UTILSLIB::IOUtils::write_eigen_matrix(idx_mat, QString(\"%1/%2_idx_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n\n    MatrixXd coilFreq_mat(coilfreq.rows(),1);\n    coilFreq_mat.col(0) = coilfreq;\n    UTILSLIB::IOUtils::write_eigen_matrix(coilFreq_mat, QString(\"%1/%2_coilFreq_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n\n    UTILSLIB::IOUtils::write_eigen_matrix(diffPos, QString(\"%1/%2_diffPos_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n\n    UTILSLIB::IOUtils::write_eigen_matrix(amp, QString(\"%1/%2_amp_mat\").arg(m_sHPIResourceDir).arg(sTimeStamp));\n}\n\n\n//*************************************************************************************************************\n\nvoid RtHPIS::append(const MatrixXd &p_DataSegment)\n{\n    m_mutex.lock();\n\n    if(!m_pRawMatrixBuffer) {\n        m_pRawMatrixBuffer = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(8, p_DataSegment.rows(), p_DataSegment.cols()));\n    }\n\n    m_pRawMatrixBuffer->push(&p_DataSegment);\n\n    m_mutex.unlock();\n}\n\n\n//*************************************************************************************************************\n\nbool RtHPIS::start()\n{\n    //Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated.\n    if(this->isRunning()) {\n        QThread::wait();\n    }\n\n    m_bIsRunning = true;\n    QThread::start();\n\n    return true;\n}\n\n\n//*************************************************************************************************************\n\nbool RtHPIS::stop()\n{\n    m_bIsRunning = false;\n\n    m_pRawMatrixBuffer->releaseFromPop();\n\n    m_pRawMatrixBuffer->clear();\n\n    return true;\n}\n\n\n//*************************************************************************************************************\n\ncoilParam RtHPIS::dipfit(struct coilParam coil, struct sens sensors, Eigen::MatrixXd data, int numCoils)\n{\n    //Do this in conncurrent mode\n    //Generate QList structure which can be handled by the QConcurrent framework\n    QList<QPair<QPair<Eigen::RowVectorXd, Eigen::VectorXd>, QPair<dipError, sens> > > lCoilData;\n\n    for(qint32 i = 0; i < numCoils; ++i) {\n        QPair<QPair<Eigen::RowVectorXd, Eigen::VectorXd>, QPair<dipError, sens> >  coilPair;\n        coilPair.first.first = coil.pos.row(i);\n        coilPair.first.second = data.col(i);\n        coilPair.second.second = sensors;\n\n        lCoilData.append(coilPair);\n    }\n\n    //Do the concurrent filtering\n    if(!lCoilData.isEmpty()) {\n//        for(int l = 0; l < lCoilData.size(); ++l) {\n//            doDipfitConcurrent(lCoilData[l]);\n//        }\n\n        QFuture<void> future = QtConcurrent::map(lCoilData,\n                                             doDipfitConcurrent);\n        future.waitForFinished();\n\n        //Transform results to final coil information\n        for(qint32 i = 0; i < lCoilData.size(); ++i) {\n            coil.pos.row(i) = lCoilData.at(i).first.first;\n            coil.mom = lCoilData.at(i).second.first.moment.transpose();\n            coil.dpfiterror(i) = lCoilData.at(i).second.first.error;\n            coil.dpfitnumitr(i) = lCoilData.at(i).second.first.numIterations;\n\n            qDebug()<< \"RtHPIS::dipfit - Itr steps for coil \" << i << \" =\" <<coil.dpfitnumitr(i);\n        }\n    }\n\n    return coil;\n}\n\n\n//*************************************************************************************************************\n\nEigen::Matrix4d RtHPIS::computeTransformation(Eigen::MatrixXd NH, Eigen::MatrixXd BT)\n{\n    Eigen::MatrixXd xdiff, ydiff, zdiff, C, Q;\n    Eigen::Matrix4d transFinal = Eigen::Matrix4d::Identity(4,4);\n    Eigen::Matrix4d Rot = Eigen::Matrix4d::Zero(4,4);\n    Eigen::Matrix4d Trans = Eigen::Matrix4d::Identity(4,4);\n    double meanx,meany,meanz,normf;\n\n    for(int i = 0; i < 15; ++i) {\n        // Calcualte translation\n        xdiff = NH.col(0) - BT.col(0);\n        ydiff = NH.col(1) - BT.col(1);\n        zdiff = NH.col(2) - BT.col(2);\n\n        meanx = xdiff.mean();\n        meany = ydiff.mean();\n        meanz = zdiff.mean();\n\n        // Apply translation\n        for (int j = 0; j < BT.rows(); ++j) {\n            BT(j,0) = BT(j,0) + meanx;\n            BT(j,1) = BT(j,1) + meany;\n            BT(j,2) = BT(j,2) + meanz;\n        }\n\n        // Estimate rotation component\n        C = BT.transpose() * NH;\n\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd(C ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n        Q = svd.matrixU() * svd.matrixV().transpose();\n\n        // Apply rotation on translated points\n        BT = BT * Q;\n\n        // Calculate GOF\n        normf = (NH.transpose()-BT.transpose()).norm();\n\n        // Store rotation part to transformation matrix\n        Rot(3,3) = 1;\n        for(int j = 0; j < 3; ++j) {\n            for(int k = 0; k < 3; ++k) {\n                Rot(j,k) = Q(k,j);\n            }\n        }\n\n        // Store translation part to transformation matrix\n        Trans(0,3) = meanx;\n        Trans(1,3) = meany;\n        Trans(2,3) = meanz;\n\n        // Safe rotation and translation to final amtrix for next iteration step\n        transFinal = Rot * Trans * transFinal;\n    }\n\n    return transFinal;\n}\n\n\n//*************************************************************************************************************\n\nvoid RtHPIS::run()\n{\n    struct sens sensors;\n    struct coilParam coil;\n    int numCoils = 4;\n    int numCh = m_pFiffInfo->nchan;\n    int samF = m_pFiffInfo->sfreq;\n    int numLoc = 1, numBlock, samLoc; // numLoc : Number of times to localize in a second\n    samLoc = samF/numLoc; // minimum samples required to localize numLoc times in a second\n    Eigen::VectorXd coilfreq(numCoils);\n//    coilfreq[0] = 154; coilfreq[1] = 158;coilfreq[2] = 162;coilfreq[3] = 166;\n    coilfreq[0] = 155; coilfreq[1] = 165; coilfreq[2] = 190; coilfreq[3] = 200;\n\n    qDebug()<< \"======= coil driving frequency (Hz)======== \";\n    qDebug() << coilfreq[0] << \", \" << coilfreq[1] << \", \" << coilfreq[2] << \", \" << coilfreq[3];\n\n    // Initialize HPI coils location and moment\n    coil.pos = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.mom = Eigen::MatrixXd::Zero(numCoils,3);\n    coil.dpfiterror = Eigen::VectorXd::Zero(numCoils);\n    coil.dpfitnumitr = Eigen::VectorXd::Zero(numCoils);\n\n    // Generate simulated data\n    Eigen::MatrixXd simsig(samLoc,numCoils*2);\n    Eigen::VectorXd time(samLoc);\n\n    for (int i = 0;i < samLoc;i++) time[i] = i*1.0/samF;\n\n//    std::ofstream outsin;\n//    outsin.open (\"C:/Users/babyMEG/Desktop/Seok/sin.txt\");\n//    std::ofstream outcos;\n//    outcos.open (\"C:/Users/babyMEG/Desktop/Seok/cos.txt\");\n\n    for(int i=0;i<numCoils;i++) {\n        for(int j=0;j<samLoc;j++) {\n            simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]);\n            simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]);\n\n//            outsin <<simsig(j,i)<<\" \";\n//            outcos <<simsig(j,i+numCoils) << \" \";\n        }\n//            outsin <<\"\\n\";\n//            outcos <<\"\\n\";\n    }\n\n//    outsin.close();\n//    outcos.close();\n\n    //====== Seok 2016. 3.25 ==========================================\n    // Get the indices of trigger channels\n//    QVector<int> trigind(0);\n//    for (int i = 0, k = 0 ;i < numCh;i++) {\n//        if(m_pFiffInfo->chs[i].coil_type == 3) {\n//            k++;\n//            if (k >= 9 && k <= 12) {\n//                qDebug() << \"trigger channel found ...\"  << i;\n//                trigind.append(i);\n//            }\n//            if (k >=9 && k <=12) {\n//                qDebug() << \"HPI trigger channel found ...\"  << i;\n//                trigind.append(i);\n//            }\n//        }\n//    }\n//    qDebug() << \"trigind: \" << trigind.length();\n    //==================================================================\n\n    //load polhemus HPI\n    Eigen::MatrixXd headHPI(numCoils,3);\n\n    // check the m_pFiffInfo->dig information. If dig is empty, set the headHPI is 0;\n    if (m_pFiffInfo->dig.size()>0)\n    {\n        for (int i=0;i<numCoils;i++) {\n            headHPI(i,0) = m_pFiffInfo->dig.at(i+3).r[0];\n            headHPI(i,1) = m_pFiffInfo->dig.at(i+3).r[1];\n            headHPI(i,2) = m_pFiffInfo->dig.at(i+3).r[2];\n        }\n    }\n    else\n    {\n        for (int i=0;i<numCoils;i++) {\n            headHPI(i,0) = 0;headHPI(i,1) = 0;headHPI(i,2) = 0;\n        }\n        qDebug() << \"\\n \\n \\n\";\n        qDebug()<< \"    **********************************************************\";\n        qDebug()<< \"   *************************************************************\";\n        qDebug()<< \"  ***************************************************************\";\n        qDebug()<< \"******************************************************************\";\n        qDebug()<< \"********    You forget to load polhemus HPI information!   *********\";\n        qDebug()<< \"***********  Please stop running and load it propoerly!  **********\";\n        qDebug()<< \"******************************************************************\";\n        qDebug()<< \" ****************************************************************\";\n        qDebug()<< \"  **************************************************************\";\n        qDebug()<< \"   ************************************************************\";\n        qDebug()<< \"    **********************************************************\";\n        qDebug() << \"\\n \\n \\n\";\n\n    }\n\n    Eigen::Matrix4d trans;\n    QVector<MatrixXd> buffer;\n    double phase;\n\n//    qDebug() << \"samLoc (1024): \" << samLoc;\n//    int OUT_FLAG = 0;\n//    int OUT_RAW = 0;\n//    std::ofstream outinnerdata;\n//    outinnerdata.open (\"C:/Users/babyMEG/Desktop/Seok/innerdata.txt\");\n//    std::ofstream outtrigdata;\n//    outtrigdata.open (\"C:/Users/babyMEG/Desktop/Seok/trigdata.txt\");\n\n//    std::ofstream outtopo;\n//    outtopo.open (\"C:/Users/babyMEG/Desktop/Seok/topo.txt\");\n//    std::ofstream outamp;\n//    outamp.open (\"C:/Users/babyMEG/Desktop/Seok/amp.txt\");\n//    std::ofstream outphase;\n//    outphase.open (\"C:/Users/babyMEG/Desktop/Seok/phase.txt\");\n//    std::ofstream outxfm;\n//    outxfm.open (\"C:/Users/babyMEG/Desktop/Seok/xfm.txt\");\n//    std::ofstream outcoilp;\n//    outcoilp.open (\"C:/Users/babyMEG/Desktop/Seok/coilp.txt\");\n//    std::ofstream outcoilm;\n//    outcoilm.open (\"C:/Users/babyMEG/Desktop/Seok/coilm.txt\");\n//    std::ofstream outdpfiterror;\n//    outdpfiterror.open (\"C:/Users/babyMEG/Desktop/Seok/dpfiterror.txt\");\n//    std::ofstream outdpfitnumitr;\n//    outdpfitnumitr.open (\"C:/Users/babyMEG/Desktop/Seok/dpfitnumitr.txt\");\n\n    // --------------------------------------\n    int itimerMatAlloc,itimerLocCoils,itimerTransMulti,itimerPhase,itimerDipFit,itimerCompTrans,itimerBufFull;\n\n    QElapsedTimer timerBufFull;\n    QElapsedTimer timerMatAlloc;\n    QElapsedTimer timerAll;\n    QElapsedTimer timerLocCoils;\n    QElapsedTimer timerTransMulti;\n    QElapsedTimer timerPhase;\n    QElapsedTimer timerDipFit;\n\n    QElapsedTimer timerCompTrans;\n\n    while(m_bIsRunning)\n    {\n\n        // Get the indices of inner layer channels\n        QVector<int> innerind(0);\n        for (int i = 0;i < numCh;i++) {\n            if(m_pFiffInfo->chs[i].chpos.coil_type == 7002) {\n                // Check if the sensor is bad, if not append to innerind\n                if(!(m_pFiffInfo->bads.contains(m_pFiffInfo->ch_names.at(i)))) innerind.append(i);\n            }\n        }\n\n        //qDebug() << \"innerind (number of inlayer channels): \" << innerind.size();\n\n        // Initialize inner layer sensors\n        sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3);\n        sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3);\n        sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size());\n\n        for(int i=0;i<innerind.size();i++) {\n            sensors.coilpos(i,0) = m_pFiffInfo->chs[innerind.at(i)].chpos.r0[0];\n            sensors.coilpos(i,1) = m_pFiffInfo->chs[innerind.at(i)].chpos.r0[1];\n            sensors.coilpos(i,2) = m_pFiffInfo->chs[innerind.at(i)].chpos.r0[2];\n            sensors.coilori(i,0) = m_pFiffInfo->chs[innerind.at(i)].chpos.ez[0];\n            sensors.coilori(i,1) = m_pFiffInfo->chs[innerind.at(i)].chpos.ez[1];\n            sensors.coilori(i,2) = m_pFiffInfo->chs[innerind.at(i)].chpos.ez[2];\n        }\n\n        Eigen::MatrixXd topo(innerind.size(),numCoils*2);\n        Eigen::MatrixXd amp(innerind.size(),numCoils);\n\n\n        if(m_pRawMatrixBuffer)\n        {\n            //m_mutex.lock();\n            MatrixXd t_mat = m_pRawMatrixBuffer->pop();\n            //m_mutex.unlock();\n\n            buffer.append(t_mat);\n\n            timerAll.start();\n            qDebug() << \"buffer(size): \" << buffer.length();\n            qDebug() << \"t_mat(size): \" << t_mat.rows() << \" x \" << t_mat.cols();\n\n            //If enough data has been stored in the buffer\n            if(buffer.size()*t_mat.cols() >= samLoc)\n            {\n                timerBufFull.start();\n\n                timerMatAlloc.start();\n\n                Eigen::MatrixXd alldata(t_mat.rows(),buffer.size()*t_mat.cols());\n\n                // Concatenate data into a matrix\n                for(int i=0;i<buffer.size();i++)\n                    alldata << buffer[i];\n\n//                // Get the data from inner layer channels\n                Eigen::MatrixXd innerdata(innerind.size(),samLoc);\n//                Eigen::MatrixXd trigdata(trigind.size(),samLoc);\n\n                numBlock = alldata.cols()/samLoc;\n\n                itimerMatAlloc = timerMatAlloc.elapsed();\n\n                // Loop for localizing coils\n\n                timerLocCoils.start();\n\n                for(int i = 0;i<numBlock;i++) {\n                    for(int j = 0;j < innerind.size();j++){\n                        innerdata.row(j) << alldata.block(innerind[j],i*samLoc,1,samLoc);\n//                        if (OUT_RAW == 1) {\n//                            for (int k = 0; k < innerdata.cols(); k++)\n//                                outinnerdata << innerdata(j,k) << \" \";\n//                        }\n                   }\n//                    for(int j = 0;j < trigind.size();j++){\n//                        trigdata.row(j) << alldata.block(trigind[j],i*samLoc,1,samLoc);\n//                        if (OUT_RAW == 1) {\n//                            for (int k = 0; k < trigdata.cols(); k++)\n//                                outtrigdata << trigdata(j,k) << \" \";\n//                        }\n//                   }\n//                    if (OUT_RAW == 1) {\n//                       outinnerdata << \"\\n\";\n//                       outtrigdata << \"\\n\";\n//                   }\n                }\n\n                itimerLocCoils = timerLocCoils.elapsed();\n\n//                    qDebug() << \"numBlock: \" << numBlock;\n//                    qDebug() << \"alldata: \" << alldata.rows() << \" x \" << alldata.cols();\n//                    qDebug() << \"innerdata: \" << innerdata.rows() << \" x \" << innerdata.cols();\n//                    qDebug() << \"trigdata: \" << trigdata.rows() << \" x \" << trigdata.cols();\n\n                timerTransMulti.start();\n                    // topo: # of good inner channel x 8\n                    topo = innerdata * pinv(simsig).transpose();\n\n                itimerTransMulti = timerTransMulti.elapsed();\n\n                    //topo = innerdata * pinv(trigdata.transpose()).transpose();\n                    //qDebug() << \"topo: \" << topo.rows() << \" \" << topo.cols();\n\n//                    for (int i =0; i<numCoils; i++) {\n//                        for (int j =0; j< innerind.size(); j++)\n//                            outtopo << topo(j,i) << \" \";\n//\n//                        outtopo << \"\\n\";\n//                    }\n\n\n                // amp: # of good inner channel x 4\n                timerPhase.start();\n\n                amp = (topo.leftCols(numCoils).array().square() + topo.rightCols(numCoils).array().square()).array().sqrt();\n                //amp = (topo.array().square()).array().sqrt();\n                //qDebug() << \"amp: \" << amp.rows() << \" \" << amp.cols();\n\n                for (int i = 0;i < numCoils;i++) {\n                    for (int j = 0;j < innerind.size();j++) {\n                        phase = atan2(topo(j,i+numCoils),topo(j,i)) * 180/M_PI;\n                        if(phase < 0)\n                            phase = 360 + phase;\n\n                        if(phase <= 90)\n                            phase = 1;\n                        else if(phase > 90 || phase <= 270)\n                            phase = -1;\n                        else phase = 1;\n\n                        amp(j,i) = amp(j,i) * phase;\n\n//                            if (OUT_FLAG == 1) {\n//                                outamp << amp(j,i) << \" \";\n//                                outphase << phase << \" \";\n//                            }\n                    }\n//                        if (OUT_FLAG == 1) {\n//                            outamp << \"\\n\";\n//                            outphase << \"\\n\";\n//                        }\n                }\n\n                itimerPhase = timerPhase.elapsed();\n\n//                    coil.pos(0,0) = 22; coil.pos(0,1) = 60; coil.pos(0,2) = 20;\n//                    coil.pos(1,0) = 32; coil.pos(1,1) = 48; coil.pos(1,2) = 34;\n//                    coil.pos(2,0) = 35; coil.pos(2,1) = 10; coil.pos(2,2) = 48;\n//                    coil.pos(3,0) = 60; coil.pos(3,1) =  4; coil.pos(3,2) = 12;\n//                    coil.pos(0,0) = 0; coil.pos(0,1) = 0; coil.pos(0,2) = 0;\n//                    coil.pos(1,0) = 0; coil.pos(1,1) = 0; coil.pos(1,2) = 0;\n//                    coil.pos(2,0) = 0; coil.pos(2,1) = 0; coil.pos(2,2) = 0;\n//                    coil.pos(3,0) = 0; coil.pos(3,1) = 0; coil.pos(3,2) = 0;\n\n                timerDipFit.start();\n\n                //coil.pos = Eigen::MatrixXd::Zero(numCoils,3);\n                coil = dipfit(coil, sensors, amp, numCoils);\n                itimerDipFit = timerDipFit.elapsed();\n\n\n//                    qDebug()<<\"HPI head \"<<headHPI(0,0)<<\" \"<<headHPI(0,1)<<\" \"<<headHPI(0,2);\n//                    qDebug()<<\"HPI head \"<<headHPI(1,0)<<\" \"<<headHPI(1,1)<<\" \"<<headHPI(1,2);\n//                    qDebug()<<\"HPI head \"<<headHPI(2,0)<<\" \"<<headHPI(2,1)<<\" \"<<headHPI(2,2);\n//                    qDebug()<<\"HPI head \"<<headHPI(3,0)<<\" \"<<headHPI(3,1)<<\" \"<<headHPI(3,2);\n\n\n//                    qDebug()<<\"HPI device \"<<1e3*coil.pos(0,0)<<\" \"<<1e3*coil.pos(0,1)<<\" \"<<1e3*coil.pos(0,2);\n//                    qDebug()<<\"HPI device \"<<1e3*coil.pos(1,0)<<\" \"<<1e3*coil.pos(1,1)<<\" \"<<1e3*coil.pos(1,2);\n//                    qDebug()<<\"HPI device \"<<1e3*coil.pos(2,0)<<\" \"<<1e3*coil.pos(2,1)<<\" \"<<1e3*coil.pos(2,2);\n//                    qDebug()<<\"HPI device \"<<1e3*coil.pos(3,0)<<\" \"<<1e3*coil.pos(3,1)<<\" \"<<1e3*coil.pos(3,2);\n//                    qDebug()<<\"HPI dpfit error \"<<coil.dpfiterror(0) <<\" \"<<coil.dpfiterror(1) <<\" \"<<coil.dpfiterror (2)<<\" \" << coil.dpfiterror(3);\n\n                    //outcoilp << \"   coil position\" << \"\\n\";\n//                    if (OUT_FLAG == 1) {\n//                        outcoilp <<coil.pos(0,0)<<\" \"<<coil.pos(0,1)<<\" \"<<coil.pos(0,2) <<\"\\n\";\n//                        outcoilp <<coil.pos(1,0)<<\" \"<<coil.pos(1,1)<<\" \"<<coil.pos(1,2) <<\"\\n\";\n//                        outcoilp <<coil.pos(2,0)<<\" \"<<coil.pos(2,1)<<\" \"<<coil.pos(2,2) <<\"\\n\";\n//                        outcoilp <<coil.pos(3,0)<<\" \"<<coil.pos(3,1)<<\" \"<<coil.pos(3,2) <<\"\\n\";\n\n//                        outcoilm <<coil.mom(0,0)<<\" \"<<coil.mom(0,1)<<\" \"<<coil.mom(0,2) <<\"\\n\";\n//                        outcoilm <<coil.mom(1,0)<<\" \"<<coil.mom(1,1)<<\" \"<<coil.mom(1,2) <<\"\\n\";\n//                        outcoilm <<coil.mom(2,0)<<\" \"<<coil.mom(2,1)<<\" \"<<coil.mom(2,2) <<\"\\n\";\n//                        outcoilm <<coil.mom(3,0)<<\" \"<<coil.mom(3,1)<<\" \"<<coil.mom(3,2) <<\"\\n\";\n\n//                        outdpfiterror << coil.dpfiterror(0) <<\" \"<<coil.dpfiterror(1) <<\" \"<<coil.dpfiterror(2) <<\" \" << coil.dpfiterror(3) <<\"\\n\";\n//                        outdpfitnumitr << coil.dpfitnumitr(0) <<\" \"<<coil.dpfitnumitr(1) <<\" \"<<coil.dpfitnumitr(2) <<\" \" << coil.dpfitnumitr(3) <<\"\\n\";\n//                    }\n\n                timerCompTrans.start();\n                trans = computeTransformation(coil.pos,headHPI);\n\n                qDebug()<<\"Write to FiffInfo Start\";\n\n                for(int ti =0; ti<4;ti++)\n                    for(int tj=0;tj<4;tj++)\n                        m_pFiffInfo->dev_head_t.trans(ti,tj) = trans(ti,tj);\n\n                qDebug()<<\"Write to FiffInfo End\";\n\n                itimerCompTrans = timerCompTrans.elapsed();\n\n                    qDebug()<<\"**** rotation ------- dev2head transformation ************\";\n                    qDebug()<< trans(0,0)<<\" \"<<trans(0,1)<<\" \"<<trans(0,2);\n                    qDebug()<< trans(1,0)<<\" \"<<trans(1,1)<<\" \"<<trans(1,2);\n                    qDebug()<< trans(2,0)<<\" \"<<trans(2,1)<<\" \"<<trans(2,2);\n                    qDebug()<<\"**** translation(dx,dy,dz) - dev2head transformation ***********\";\n                    qDebug()<< 1e3*trans(0,3)<<\" \"<<1e3*trans(1,3)<<\" \"<<1e3*trans(2,3);\n\n/*                     if (OUT_FLAG == 1) {\n                    //outxfm << \"   rotation\" << \"\\n\";\n                    outxfm << trans(0,0)<<\" \"<<trans(0,1)<<\" \"<<trans(0,2) <<\" \"<< trans(0,3)<<\"\\n\";\n                    outxfm << trans(1,0)<<\" \"<<trans(1,1)<<\" \"<<trans(1,2) <<\" \"<< trans(1,3)<<\"\\n\";\n                    outxfm << trans(2,0)<<\" \"<<trans(2,1)<<\" \"<<trans(2,2) <<\" \"<< trans(2,3)<<\"\\n\";\n                    }\n*/\n                itimerBufFull = timerBufFull.elapsed();\n\n                buffer.clear();\n\n                qDebug() << \"\";\n                qDebug() << \"RtHPIS::run() - All\" << timerAll.elapsed() << \"milliseconds\";\n                qDebug() << \"\";\n                qDebug() << \"RtHPIS::run() - itimerMatAlloc\" << itimerMatAlloc << \"milliseconds\";\n                qDebug() << \"RtHPIS::run() - itimerLocCoils\" << itimerLocCoils << \"milliseconds\";\n                qDebug() << \"RtHPIS::run() - itimerTransMulti\" << itimerTransMulti << \"milliseconds\";\n                qDebug() << \"RtHPIS::run() - itimerPhase\" << itimerPhase << \"milliseconds\";\n                qDebug() << \"RtHPIS::run() - itimerDipFit\" << itimerDipFit << \"milliseconds\";\n                qDebug() << \"RtHPIS::run() - itimerCompTrans\" << itimerCompTrans << \"milliseconds\";\n                qDebug() << \"RtHPIS::run() - itimerBufFull\" << itimerBufFull << \"milliseconds\";\n            }\n\n\n        }//m_pRawMatrixBuffer\n    }  //End of while statement\n\n    //m_bIsRunning\n//    outinnerdata.close();\n//    outtrigdata.close();\n//    outtopo.close();\n//    outamp.close();\n//    outphase.close();\n//    outxfm.close();\n//    outcoilp.close();\n//    outcoilm.close();\n//    outdpfiterror.close();\n//    outdpfitnumitr.close();\n\n}\n\n\n\n/*\nGoodness of fit (for MNE HPI GOF)is\n\ng = 1 - sum(e_k^2)/sum(y_k^2)\n\nwhere\n\ny_k is the measured signal in channel k\n\ne_k = y_k - y’_k, the difference of y_k and the signal predicted by the model\n*/\n", "meta": {"hexsha": "34610be61cbacda7a5e432f4739622e5302b25d1", "size": 51110, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/rtProcessing/rthpis.cpp", "max_stars_repo_name": "LostSign/mne-cpp", "max_stars_repo_head_hexsha": "39b0add0de0a17201dba8707bf08b9493dec7810", "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": "MNE/rtProcessing/rthpis.cpp", "max_issues_repo_name": "LostSign/mne-cpp", "max_issues_repo_head_hexsha": "39b0add0de0a17201dba8707bf08b9493dec7810", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/rtProcessing/rthpis.cpp", "max_forks_repo_name": "LostSign/mne-cpp", "max_forks_repo_head_hexsha": "39b0add0de0a17201dba8707bf08b9493dec7810", "max_forks_repo_licenses": ["BSD-3-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.608535688, "max_line_length": 238, "alphanum_fraction": 0.4754842497, "num_tokens": 13232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000710997428738, "lm_q2_score": 0.015663650607110523, "lm_q1q2_score": 0.0034461145017173783}}
{"text": "#ifndef STAN_LANG_TORSTEN_GRAMMARS_SEMANTIC_ACTIONS_DEF_CPP\n#define STAN_LANG_TORSTEN_GRAMMARS_SEMANTIC_ACTIONS_DEF_CPP\n\n#include <stan/io/program_reader.hpp>\n#include <stan/lang/ast.hpp>\n#include <stan/lang/grammars/iterator_typedefs.hpp>\n#include <stan/lang/grammars/semantic_actions.hpp>\n#include <stan/torsten/semantic_actions.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/recursive_variant.hpp>\n#include <cstddef>\n#include <limits>\n#include <climits>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <set>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\nstruct torsten_types {\n  static const double_type t_dbl;\n  static const int_type t_int;\n  static const vector_type t_vec;\n  static const bare_expr_type t_dbl_1;\n  static const bare_expr_type t_int_1;\n  static const bare_expr_type t_dbl_2;\n  static const bare_expr_type t_int_2;\n  const bare_expr_type sys_result_type;\n\n  torsten_types(bare_expr_type return_t) :\n    sys_result_type(return_t)\n  {}\n};\n\nconst double_type torsten_types::t_dbl = double_type();\nconst int_type torsten_types::t_int = int_type();\nconst vector_type torsten_types::t_vec = vector_type();\nconst bare_expr_type torsten_types::t_dbl_1 = bare_array_type(t_dbl, 1);\nconst bare_expr_type torsten_types::t_int_1 = bare_array_type(t_int, 1);\nconst bare_expr_type torsten_types::t_dbl_2 = bare_array_type(t_dbl, 2);\nconst bare_expr_type torsten_types::t_int_2 = bare_array_type(t_int, 2);\n\n/**********************************\n   univariate_integral\n**********************************/\n\ntemplate <class T>\nvoid validate_univariate_integral(const T& univar_fun,\n                                  const variable_map& var_map,\n                                  bool& pass,\n                                  std::ostream& error_msgs) {\npass = true;\ntorsten_types pmx_t(torsten_types::t_dbl);\n  std::vector<bare_expr_type> sys_arg_types;\n\n  if (univar_fun.integration_function_name_ == \"univariate_integral_rk45\"\n      || univar_fun.integration_function_name_ == \"univariate_integral_bdf\"){\n    sys_arg_types.push_back(torsten_types::t_dbl);\n    sys_arg_types.push_back(torsten_types::t_dbl_1);\n    sys_arg_types.push_back(torsten_types::t_dbl_1);\n    sys_arg_types.push_back(torsten_types::t_int_1);\n  }\n  function_signature_t system_signature(pmx_t.sys_result_type, sys_arg_types);\n  if (!function_signatures::instance()\n      .is_defined(univar_fun.system_function_name_, system_signature)) {\n    error_msgs << \"first argument to \"\n               << univar_fun.integration_function_name_\n               << \" must be the name of a function with signature\"\n               << \" (real, real[], real[], int[]) : real \";\n    pass = false;\n  }\n  // test regular argument types\n  if (univar_fun.t0_.bare_type() != torsten_types::t_dbl) {\n    error_msgs << \"second argument to \"\n               << univar_fun.integration_function_name_\n               << \" must have type real for time limit;\"\n               << \" found type=\"\n               << univar_fun.t0_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (univar_fun.t1_.bare_type() != torsten_types::t_dbl) {\n    error_msgs << \"third argument to \"\n               << univar_fun.integration_function_name_\n               << \" must have type real for time limit;\"\n               << \" found type=\"\n               << univar_fun.t1_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (univar_fun.theta_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"fourth argument to \"\n               << univar_fun.integration_function_name_\n               << \" must have type real[] for parameters;\"\n               << \" found type=\"\n               << univar_fun.theta_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (univar_fun.x_r_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"fifth argument to \"\n               << univar_fun.integration_function_name_\n               << \" must have type real[] for real data; found type=\"\n               << univar_fun.x_r_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (univar_fun.x_i_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"sixth argument to \"\n               << univar_fun.integration_function_name_\n               << \" must have type int[] for integer data; found type=\"\n               << univar_fun.x_i_.bare_type()\n               << \". \";\n    pass = false;\n  }\n}\n\nvoid validate_univariate_integral_control::operator()(\n                                                      const univariate_integral_control& univar_fun,\n                                                      const variable_map& var_map,\n                                                      bool& pass,\n                                                      std::ostream& error_msgs) const {\n  validate_univariate_integral(univar_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_univariate_integral_control>\nvalidate_univariate_integral_control_f;\n\nbool data_only_expression::operator()(const univariate_integral_control& x)\n  const {\n  return boost::apply_visitor(*this, x.t0_.expr_)\n    && boost::apply_visitor(*this, x.t1_.expr_)\n    && boost::apply_visitor(*this, x.theta_.expr_);\n}\n\ntemplate void assign_lhs::operator()(expression&,\n                                     const univariate_integral_control&)\n  const;\n\n/**********************************\n   generalOdeModel\n**********************************/\n\ntemplate <class T>\nvoid validate_generalOdeModel_non_control_args(const T& ode_fun,\n                              const variable_map& var_map,\n                              bool& pass,\n                              std::ostream& error_msgs) {\n  pass = true;\n\n  torsten_types pmx_t(torsten_types::t_dbl_1);\n  std::vector<bare_expr_type> sys_arg_types;\n  std::string expected_signature;\n\n  // build expected function argument type for generalOdeModel\n  if (ode_fun.integration_function_name_ == \"generalOdeModel_rk45\"\n      || ode_fun.integration_function_name_ == \"generalOdeModel_bdf\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_adams\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_bdf\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_rk45\"\n      ) {\n    sys_arg_types.push_back(torsten_types::t_dbl);  // t0\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // y\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // theta\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // x_r\n    sys_arg_types.push_back(torsten_types::t_int_1);  // x_i\n    expected_signature = \"(real, real[], real[], real[], int[]) : real[]\";\n  }\n\n  // build expected function argument type for mixOdeModel\n  if (ode_fun.integration_function_name_ == \"mixOde1CptModel_rk45\"\n      || ode_fun.integration_function_name_ == \"mixOde1CptModel_bdf\"\n      || ode_fun.integration_function_name_ == \"mixOde2CptModel_rk45\"\n      || ode_fun.integration_function_name_ == \"mixOde2CptModel_bdf\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_onecpt_bdf\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_onecpt_rk45\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_twocpt_bdf\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_twocpt_rk45\"\n      ) {\n    sys_arg_types.push_back(torsten_types::t_dbl);  // t0\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // y\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // y_PK\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // theta\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // x_r\n    sys_arg_types.push_back(torsten_types::t_int_1);  // x_i\n    expected_signature = \"(real, real[], real[], real[], real[], int[]) : real[]\";  // NOLINT\n  }\n\n  function_signature_t system_signature(pmx_t.sys_result_type, sys_arg_types);\n\n  // test function argument type\n  if (!function_signatures::instance()\n      .is_defined(ode_fun.system_function_name_, system_signature)) {\n    error_msgs << \"1st argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be a function with signature \"\n               << expected_signature << \" \";\n    pass = false;\n  }\n\n  // test regular argument types\n  if (!ode_fun.nCmt_.bare_type().is_int_type()) {\n    error_msgs << \"2nd argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int\"\n               << \" for number of compartments\"\n               << \"; found type=\"\n               << ode_fun.nCmt_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.time_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"3rd argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for time\"\n               << \"; found type=\"\n               << ode_fun.time_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.amt_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"4th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for amount\"\n               << \"; found type=\"\n               << ode_fun.amt_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.rate_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"5th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for rate\"\n               << \"; found type=\"\n               << ode_fun.rate_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.ii_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"6th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for inter-dose interval\"\n               << \"; found type=\"\n               << ode_fun.ii_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.evid_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"7th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for event ID\"\n               << \"; found type=\"\n               << ode_fun.evid_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.cmt_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"8th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for compartment ID\"\n               << \"; found type=\"\n               << ode_fun.cmt_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.addl_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"9th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for number of additional doses\"\n               << \"; found type=\"\n               << ode_fun.addl_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.ss_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"10th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for steady state flags\"\n               << \"; found type=\"\n               << ode_fun.ss_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if ((ode_fun.pMatrix_.bare_type() != torsten_types::t_dbl_2)\n      && (ode_fun.pMatrix_.bare_type() != torsten_types::t_dbl_1)) {\n    error_msgs << \"11th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[] or real[ , ]\"\n               << \" for ODE parameters\"\n               << \"; found type=\"\n               << ode_fun.pMatrix_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if ((ode_fun.biovar_.bare_type() != torsten_types::t_dbl_2)\n      && (ode_fun.biovar_.bare_type() != torsten_types::t_dbl_1)) {\n    error_msgs << \"12th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[] or real[ , ]\"\n               << \" for bioavailability\"\n               << \"; found type=\"\n               << ode_fun.biovar_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if ((ode_fun.tlag_.bare_type() != torsten_types::t_dbl_2)\n      && (ode_fun.tlag_.bare_type() != torsten_types::t_dbl_1)) {\n    error_msgs << \"13th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[] or real[ , ]\"\n               << \" for lag times\"\n               << \"; found type=\"\n               << ode_fun.tlag_.bare_type()\n               << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.nCmt_, var_map)) {\n    error_msgs << \"2nd argument to \"\n               << ode_fun.integration_function_name_\n               << \" for number of compartments\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.evid_, var_map)) {\n    error_msgs << \"3rd argument to \"\n               << ode_fun.integration_function_name_\n               << \" for event ID\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.cmt_, var_map)) {\n    error_msgs << \"8th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for compartment ID\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.addl_, var_map)) {\n    error_msgs << \"9th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for number of additional doses\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.ss_, var_map)) {\n    error_msgs << \"10th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for steady state flags\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n}\n\ntemplate <class T>\nvoid validate_generalOdeModel_control_args(const T& ode_fun,\n                                           const variable_map& var_map,\n                                           bool& pass,\n                                           std::ostream& error_msgs) {\n  if (!ode_fun.rel_tol_.bare_type().is_primitive()) {\n    error_msgs << \"14th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for relative tolerance\"\n               << \"; found type=\"\n               << ode_fun.rel_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.abs_tol_.bare_type().is_primitive()) {\n    error_msgs << \"15th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for absolute tolerance\"\n               << \"; found type=\"\n               << ode_fun.abs_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.max_num_steps_.bare_type().is_primitive()) {\n    error_msgs << \"16th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for maximum number of steps\"\n               << \"; found type=\"\n               << ode_fun.max_num_steps_.bare_type()\n               << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.rel_tol_, var_map)) {\n    error_msgs << \"14th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for relative tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.abs_tol_, var_map)) {\n    error_msgs << \"15th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for absolute tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.max_num_steps_, var_map)) {\n    error_msgs << \"16th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for maximum number of steps\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n}\n\n/********************************************\n   pmx_solve_xxx with algebra solver controls\n********************************************/\n\ntemplate <class T>\nvoid validate_generalOdeModel_control_ss_args(const T& ode_fun,\n                                              const variable_map& var_map,\n                                              bool& pass,\n                                              std::ostream& error_msgs) {\n  if (!ode_fun.rel_tol_.bare_type().is_primitive()) {\n    error_msgs << \"14th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for relative tolerance\"\n               << \"; found type=\"\n               << ode_fun.rel_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.abs_tol_.bare_type().is_primitive()) {\n    error_msgs << \"15th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for absolute tolerance\"\n               << \"; found type=\"\n               << ode_fun.abs_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.max_num_steps_.bare_type().is_primitive()) {\n    error_msgs << \"16th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for maximum number of steps\"\n               << \"; found type=\"\n               << ode_fun.max_num_steps_.bare_type()\n               << \". \";\n    pass = false;\n  }\n\n  if (!ode_fun.ss_rel_tol_.bare_type().is_primitive()) {\n    error_msgs << \"17th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for relative tolerance\"\n               << \"; found type=\"\n               << ode_fun.rel_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.ss_abs_tol_.bare_type().is_primitive()) {\n    error_msgs << \"18th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for absolute tolerance\"\n               << \"; found type=\"\n               << ode_fun.abs_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.ss_max_num_steps_.bare_type().is_primitive()) {\n    error_msgs << \"19th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for maximum number of steps\"\n               << \"; found type=\"\n               << ode_fun.max_num_steps_.bare_type()\n               << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.rel_tol_, var_map)) {\n    error_msgs << \"14th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for relative tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.abs_tol_, var_map)) {\n    error_msgs << \"15th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for absolute tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.max_num_steps_, var_map)) {\n    error_msgs << \"16th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for maximum number of steps\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n\n  if (has_var(ode_fun.ss_rel_tol_, var_map)) {\n    error_msgs << \"17th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for relative tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.ss_abs_tol_, var_map)) {\n    error_msgs << \"18th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for absolute tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.ss_max_num_steps_, var_map)) {\n    error_msgs << \"19th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for maximum number of steps\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n}\n\n/**********************************\n   pmx_solve_group\n**********************************/\ntemplate <class T>\nvoid validate_pmx_solve_group_non_control_args(const T& ode_fun,\n                              const variable_map& var_map,\n                              bool& pass,\n                              std::ostream& error_msgs) {\n  pass = true;\n\n  torsten_types pmx_t(torsten_types::t_dbl_1);\n  std::vector<bare_expr_type> sys_arg_types;\n  std::string expected_signature;\n\n  // build expected function argument type for generalOdeModel\n  if (   ode_fun.integration_function_name_ == \"pmx_solve_group_rk45\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_group_adams\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_group_bdf\") {\n    sys_arg_types.push_back(torsten_types::t_dbl);  // t0\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // y\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // theta\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // x_r\n    sys_arg_types.push_back(torsten_types::t_int_1);  // x_i\n    expected_signature = \"(real, real[], real[], real[], int[]) : real[]\";\n  }\n\n  // build expected function argument type for mixOdeModel\n  if (ode_fun.integration_function_name_ == \"pmx_solve_group_onecpt_rk45\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_group_onecpt_bdf\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_group_twocpt_rk45\"\n      || ode_fun.integration_function_name_ == \"pmx_solve_group_twocpt_bdf\") {\n    sys_arg_types.push_back(torsten_types::t_dbl);  // t0\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // y\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // y_PK\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // theta\n    sys_arg_types.push_back(torsten_types::t_dbl_1);  // x_r\n    sys_arg_types.push_back(torsten_types::t_int_1);  // x_i\n    expected_signature = \"(real, real[], real[], real[], real[], int[]) : real[]\";  // NOLINT\n  }\n\n  function_signature_t system_signature(pmx_t.sys_result_type, sys_arg_types);\n\n  // test function argument type\n  if (!function_signatures::instance()\n      .is_defined(ode_fun.system_function_name_, system_signature)) {\n    error_msgs << \"1st argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be a function with signature \"\n               << expected_signature << \" \";\n    pass = false;\n  }\n\n  // test regular argument types\n  if (!ode_fun.nCmt_.bare_type().is_int_type()) {\n    error_msgs << \"2nd argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int\"\n               << \" for nCmt (number of compartments)\"\n               << \"; found type=\"\n               << ode_fun.nCmt_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.len_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"3rd argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for len\"\n               << \"; found type=\"\n               << ode_fun.time_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.time_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"4th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for time\"\n               << \"; found type=\"\n               << ode_fun.time_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.amt_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"5th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for amount\"\n               << \"; found type=\"\n               << ode_fun.amt_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.rate_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"6th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for rate\"\n               << \"; found type=\"\n               << ode_fun.rate_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.ii_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"7th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[]\"\n               << \" for inter-dose interval\"\n               << \"; found type=\"\n               << ode_fun.ii_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.evid_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"8th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for event ID\"\n               << \"; found type=\"\n               << ode_fun.evid_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.cmt_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"9th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for compartment ID\"\n               << \"; found type=\"\n               << ode_fun.cmt_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.addl_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"10th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for number of additional doses\"\n               << \"; found type=\"\n               << ode_fun.addl_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.ss_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"11th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type int[]\"\n               << \" for steady state flags\"\n               << \"; found type=\"\n               << ode_fun.ss_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if ((ode_fun.pMatrix_.bare_type() != torsten_types::t_dbl_2)\n      && (ode_fun.pMatrix_.bare_type() != torsten_types::t_dbl_1)) {\n    error_msgs << \"12th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[] or real[ , ]\"\n               << \" for ODE parameters\"\n               << \"; found type=\"\n               << ode_fun.pMatrix_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if ((ode_fun.biovar_.bare_type() != torsten_types::t_dbl_2)\n      && (ode_fun.biovar_.bare_type() != torsten_types::t_dbl_1)) {\n    error_msgs << \"13th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[] or real[ , ]\"\n               << \" for bioavailability\"\n               << \"; found type=\"\n               << ode_fun.biovar_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if ((ode_fun.tlag_.bare_type() != torsten_types::t_dbl_2)\n      && (ode_fun.tlag_.bare_type() != torsten_types::t_dbl_1)) {\n    error_msgs << \"14th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real[] or real[ , ]\"\n               << \" for lag times\"\n               << \"; found type=\"\n               << ode_fun.tlag_.bare_type()\n               << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.nCmt_, var_map)) {\n    error_msgs << \"second argument to \"\n               << ode_fun.integration_function_name_\n               << \" for number of compartments\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.evid_, var_map)) {\n    error_msgs << \"seventh argument to \"\n               << ode_fun.integration_function_name_\n               << \" for event ID\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.cmt_, var_map)) {\n    error_msgs << \"eighth argument to \"\n               << ode_fun.integration_function_name_\n               << \" for compartment ID\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.addl_, var_map)) {\n    error_msgs << \"ninth argument to \"\n               << ode_fun.integration_function_name_\n               << \" for number of additional doses\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.ss_, var_map)) {\n    error_msgs << \"tenth argument to \"\n               << ode_fun.integration_function_name_\n               << \" for steady state flags\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n}\n\ntemplate <class T>\nvoid validate_pmx_solve_group_control_args(const T& ode_fun,\n                                           const variable_map& var_map,\n                                           bool& pass,\n                                           std::ostream& error_msgs) {\n  if (!ode_fun.rel_tol_.bare_type().is_primitive()) {\n    error_msgs << \"15th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for relative tolerance\"\n               << \"; found type=\"\n               << ode_fun.rel_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.abs_tol_.bare_type().is_primitive()) {\n    error_msgs << \"16th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for absolute tolerance\"\n               << \"; found type=\"\n               << ode_fun.abs_tol_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.max_num_steps_.bare_type().is_primitive()) {\n    error_msgs << \"17th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be type real or int\"\n               << \" for maximum number of steps\"\n               << \"; found type=\"\n               << ode_fun.max_num_steps_.bare_type()\n               << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.rel_tol_, var_map)) {\n    error_msgs << \"15th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for relative tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.abs_tol_, var_map)) {\n    error_msgs << \"16th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for absolute tolerance\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  if (has_var(ode_fun.max_num_steps_, var_map)) {\n    error_msgs << \"17th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for maximum number of steps\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n}\n\n/*********************************\n  pmx_integrate_ode\n *********************************/\ntemplate <class T>\nvoid validate_pmx_integrate_ode_non_control_args(const T& ode_fun,\n                                                 const variable_map& var_map,\n                                                 bool& pass,\n                                                 std::ostream& error_msgs) {\n  pass = true;\n  // test function argument type\n  torsten_types pmx_t(torsten_types::t_dbl_1);\n  std::vector<bare_expr_type> sys_arg_types;\n  sys_arg_types.push_back(torsten_types::t_dbl);\n  sys_arg_types.push_back(torsten_types::t_dbl_1);\n  sys_arg_types.push_back(torsten_types::t_dbl_1);\n  sys_arg_types.push_back(torsten_types::t_dbl_1);\n  sys_arg_types.push_back(torsten_types::t_int_1);\n  function_signature_t system_signature(pmx_t.sys_result_type, sys_arg_types);\n  if (!function_signatures::instance()\n      .is_defined(ode_fun.system_function_name_, system_signature)) {\n    error_msgs << \"1st argument to \"\n               << ode_fun.integration_function_name_\n               << \" must be a function with signature\"\n               << \" (real, real[], real[], real[], int[]) : real[] \";\n    pass = false;\n  }\n\n  // test regular argument types\n  if (ode_fun.y0_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"2nd argument to \"\n               << ode_fun.integration_function_name_\n               << \" must have type real[] for intial system state;\"\n               << \" found type=\"\n               << ode_fun.y0_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (!ode_fun.t0_.bare_type().is_primitive()) {\n    error_msgs << \"3rd argument to \"\n               << ode_fun.integration_function_name_\n               << \" must have type real or int for initial time;\"\n               << \" found type=\"\n               << ode_fun.t0_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.ts_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"4th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must have type real[]\"\n               << \" for requested solution times; found type=\"\n               << ode_fun.ts_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.theta_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"5th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must have type real[] for parameters; found type=\"\n               << ode_fun.theta_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.x_.bare_type() != torsten_types::t_dbl_1) {\n    error_msgs << \"6th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must have type real[] for real data; found type=\"\n               << ode_fun.x_.bare_type()\n               << \". \";\n    pass = false;\n  }\n  if (ode_fun.x_int_.bare_type() != torsten_types::t_int_1) {\n    error_msgs << \"7th argument to \"\n               << ode_fun.integration_function_name_\n               << \" must have type int[] for integer data; found type=\"\n               << ode_fun.x_int_.bare_type()\n               << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.t0_, var_map)) {\n    error_msgs << \"3rd argument to \"\n               << ode_fun.integration_function_name_\n               << \" (initial times)\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n  // if (has_var(ode_fun.ts_, var_map)) {\n  //   error_msgs << \"4th argument to \"\n  //              << ode_fun.integration_function_name_\n  //              << \" (solution times)\"\n  //              << \" must be data only and not reference parameters\";\n  //   pass = false;\n  // }\n  if (has_var(ode_fun.x_, var_map)) {\n    error_msgs << \"6th argument to \"\n               << ode_fun.integration_function_name_\n               << \" for real data\"\n               << \" must be data only and not reference parameters\";\n    pass = false;\n  }\n}\n\nvoid validate_pmx_integrate_ode::operator()(const pmx_integrate_ode& ode_fun,\n                                            const variable_map& var_map,\n                                            bool& pass,\n                                            std::ostream& error_msgs) const {\n  validate_pmx_integrate_ode_non_control_args(ode_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_pmx_integrate_ode>\nvalidate_pmx_integrate_ode_f;\n\nbool data_only_expression::operator()(const pmx_integrate_ode& x) const {\n  return boost::apply_visitor(*this, x.y0_.expr_)\n    && boost::apply_visitor(*this, x.theta_.expr_);\n}\n\ntemplate void assign_lhs::operator()(expression&, const pmx_integrate_ode&) const;\n\n/*********************************\n  pmx_integrate_ode_control\n *********************************/\nvoid validate_pmx_integrate_ode_control:: operator()(const pmx_integrate_ode_control &ode_fun,\n                                                     const variable_map &var_map,\n                                                     bool &pass, std::ostream &error_msgs) const {\n  validate_pmx_integrate_ode_non_control_args(ode_fun, var_map, pass, error_msgs);\n  if (!ode_fun.rel_tol_.bare_type().is_primitive()) {\n    error_msgs << \"Eighth argument to \" << ode_fun.integration_function_name_\n               << \" (relative tolerance) must have type real or int;\"\n               << \" found type=\" << ode_fun.rel_tol_.bare_type() << \". \";\n    pass = false;\n  }\n  if (!ode_fun.abs_tol_.bare_type().is_primitive()) {\n    error_msgs << \"Ninth argument to \" << ode_fun.integration_function_name_\n               << \" (absolute tolerance) must have type real or int;\"\n               << \" found type=\" << ode_fun.abs_tol_.bare_type() << \". \";\n    pass = false;\n  }\n  if (!ode_fun.max_num_steps_.bare_type().is_primitive()) {\n    error_msgs << \"Tenth argument to \" << ode_fun.integration_function_name_\n               << \" (max steps) must have type real or int;\"\n               << \" found type=\" << ode_fun.max_num_steps_.bare_type() << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.rel_tol_, var_map)) {\n    error_msgs << \"Eighth argument to \" << ode_fun.integration_function_name_\n               << \" (relative tolerance) must be data only\"\n               << \" and not depend on parameters.\";\n    pass = false;\n  }\n  if (has_var(ode_fun.abs_tol_, var_map)) {\n    error_msgs << \"Ninth argument to \" << ode_fun.integration_function_name_\n               << \" (absolute tolerance ) must be data only\"\n               << \" and not depend parameters.\";\n    pass = false;\n  }\n  if (has_var(ode_fun.max_num_steps_, var_map)) {\n    error_msgs << \"Tenth argument to \" << ode_fun.integration_function_name_\n               << \" (max steps) must be data only\"\n               << \" and not depend on parameters.\";\n    pass = false;\n  }\n}\nboost::phoenix::function<validate_pmx_integrate_ode_control> validate_pmx_integrate_ode_control_f;\n\nbool data_only_expression::operator()(const pmx_integrate_ode_control& x) const {\n  return boost::apply_visitor(*this, x.y0_.expr_)\n    && boost::apply_visitor(*this, x.theta_.expr_);\n}\n\ntemplate void assign_lhs::operator()(expression &, const pmx_integrate_ode_control &) const;\n\n/*********************************\n  pmx_integrate_ode_group\n *********************************/\n    template <class T>\n    void validate_pmx_integrate_ode_group_non_control_args(const T& ode_fun,\n                                                           const variable_map& var_map,\n                                                           bool& pass,\n                                                           std::ostream& error_msgs) {\n      pass = true;\n      // test function argument type\n      torsten_types pmx_t(torsten_types::t_dbl_1);\n      std::vector<bare_expr_type> sys_arg_types;\n      sys_arg_types.push_back(torsten_types::t_dbl);\n      sys_arg_types.push_back(torsten_types::t_dbl_1);\n      sys_arg_types.push_back(torsten_types::t_dbl_1);\n      sys_arg_types.push_back(torsten_types::t_dbl_1);\n      sys_arg_types.push_back(torsten_types::t_int_1);\n      function_signature_t system_signature(pmx_t.sys_result_type, sys_arg_types);\n      if (!function_signatures::instance()\n          .is_defined(ode_fun.system_function_name_, system_signature)) {\n        error_msgs << \"1st argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must be a function with signature\"\n                   << \" (real, real[], real[], real[], int[]) : real[] \";\n        pass = false;\n      }\n\n      // test regular argument types\n      if (ode_fun.y0_.bare_type() != torsten_types::t_dbl_2) {\n        error_msgs << \"2nd argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must have type real[ , ] for intial system state;\"\n                   << \" found type=\"\n                   << ode_fun.y0_.bare_type()\n                   << \". \";\n        pass = false;\n      }\n      if (!ode_fun.t0_.bare_type().is_primitive()) {\n        error_msgs << \"3rd argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must have type real or int for initial time;\"\n                   << \" found type=\"\n                   << ode_fun.t0_.bare_type()\n                   << \". \";\n        pass = false;\n      }\n      if (ode_fun.len_.bare_type() != torsten_types::t_int_1) {\n        error_msgs << \"4th argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must have type int[]\"\n                   << \" for length of each ODE's times within ragged array; found type=\"\n                   << ode_fun.len_.bare_type()\n                   << \". \";\n        pass = false;\n      }\n      if (ode_fun.ts_.bare_type() != torsten_types::t_dbl_1) {\n        error_msgs << \"5th argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must have type real[]\"\n                   << \" for requested solution times; found type=\"\n                   << ode_fun.ts_.bare_type()\n                   << \". \";\n        pass = false;\n      }\n      if (ode_fun.theta_.bare_type() != torsten_types::t_dbl_2) {\n        error_msgs << \"6th argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must have type real[ , ] for parameters; found type=\"\n                   << ode_fun.theta_.bare_type()\n                   << \". \";\n        pass = false;\n      }\n      if (ode_fun.x_.bare_type() != torsten_types::t_dbl_2) {\n        error_msgs << \"7th argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must have type real[ , ] for real data; found type=\"\n                   << ode_fun.x_.bare_type()\n                   << \". \";\n        pass = false;\n      }\n      if (ode_fun.x_int_.bare_type() != torsten_types::t_int_2) {\n        error_msgs << \"8th argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" must have type int[ , ] for integer data; found type=\"\n                   << ode_fun.x_int_.bare_type()\n                   << \". \";\n        pass = false;\n      }\n\n      // test data-only variables do not have parameters (int locals OK)\n      if (has_var(ode_fun.t0_, var_map)) {\n        error_msgs << \"3rd argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" (initial times)\"\n                   << \" must be data only and not reference parameters\";\n        pass = false;\n      }\n      if (has_var(ode_fun.ts_, var_map)) {\n        error_msgs << \"5th argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" (solution times)\"\n                   << \" must be data only and not reference parameters\";\n        pass = false;\n      }\n      if (has_var(ode_fun.x_, var_map)) {\n        error_msgs << \"7th argument to \"\n                   << ode_fun.integration_function_name_\n                   << \" for real data\"\n                   << \" must be data only and not reference parameters\";\n        pass = false;\n      }\n\n      // collect ODE functor names to be used in MPI master-slave control\n      pmx_integrate_ode_group::CALLED_FUNCTORS.push_back(ode_fun.system_function_name_);\n    }\n\n/*****************\n generalOdeModel_control\n*****************/\n\nvoid validate_generalOdeModel_control::operator()(\n                      const generalOdeModel_control& ode_fun,\n                      const variable_map& var_map,\n                      bool& pass,\n                      std::ostream& error_msgs) const {\n  validate_generalOdeModel_non_control_args(ode_fun, var_map, pass, error_msgs);\n  validate_generalOdeModel_control_args(ode_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_generalOdeModel_control>\nvalidate_generalOdeModel_control_f;\n\nbool data_only_expression::operator()(const generalOdeModel_control& x)\n  const {\n  return ((((((boost::apply_visitor(*this, x.time_.expr_)\n               && boost::apply_visitor(*this, x.amt_.expr_)))\n             && boost::apply_visitor(*this, x.rate_.expr_)\n             && boost::apply_visitor(*this, x.ii_.expr_))\n            && boost::apply_visitor(*this, x.pMatrix_.expr_))\n           && boost::apply_visitor(*this, x.biovar_.expr_))\n          && boost::apply_visitor(*this, x.tlag_.expr_));\n}  // include all arguments with a template type\n\ntemplate void assign_lhs::operator()(expression&,\n                                     const generalOdeModel_control&)\n  const;\n\n/*****************\n generalOdeModel_control_ss\n*****************/\n\nvoid validate_generalOdeModel_control_ss::operator()(\n                      const generalOdeModel_control_ss& ode_fun,\n                      const variable_map& var_map,\n                      bool& pass,\n                      std::ostream& error_msgs) const {\n  validate_generalOdeModel_non_control_args(ode_fun, var_map, pass, error_msgs);\n  validate_generalOdeModel_control_ss_args(ode_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_generalOdeModel_control_ss>\nvalidate_generalOdeModel_control_ss_f;\n\nbool data_only_expression::operator()(const generalOdeModel_control_ss& x)\n  const {\n  return ((((((boost::apply_visitor(*this, x.time_.expr_)\n               && boost::apply_visitor(*this, x.amt_.expr_)))\n             && boost::apply_visitor(*this, x.rate_.expr_)\n             && boost::apply_visitor(*this, x.ii_.expr_))\n            && boost::apply_visitor(*this, x.pMatrix_.expr_))\n           && boost::apply_visitor(*this, x.biovar_.expr_))\n          && boost::apply_visitor(*this, x.tlag_.expr_));\n}  // include all arguments with a template type\n\ntemplate void assign_lhs::operator()(expression&,\n                                     const generalOdeModel_control_ss&)\n  const;\n\n/*****************\n generalOdeModel\n*****************/\n\nvoid validate_generalOdeModel::operator()(\n                      const generalOdeModel& ode_fun,\n                      const variable_map& var_map,\n                      bool& pass,\n                      std::ostream& error_msgs) const {\n  validate_generalOdeModel_non_control_args(ode_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_generalOdeModel>\nvalidate_generalOdeModel_f;\n\nbool data_only_expression::operator()(const generalOdeModel& x)\n  const {\n  return ((((((boost::apply_visitor(*this, x.time_.expr_)\n               && boost::apply_visitor(*this, x.amt_.expr_)))\n             && boost::apply_visitor(*this, x.rate_.expr_)\n             && boost::apply_visitor(*this, x.ii_.expr_))\n            && boost::apply_visitor(*this, x.pMatrix_.expr_))\n           && boost::apply_visitor(*this, x.biovar_.expr_))\n          && boost::apply_visitor(*this, x.tlag_.expr_));\n}\n\ntemplate void assign_lhs::operator()(expression&,\n                                     const generalOdeModel&)\n  const;\n\n/*****************\n pmx_solve_group\n*****************/\n\nvoid validate_pmx_solve_group::operator()(\n                      const pmx_solve_group& ode_fun,\n                      const variable_map& var_map,\n                      bool& pass,\n                      std::ostream& error_msgs) const {\n  validate_pmx_solve_group_non_control_args(ode_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_pmx_solve_group>\nvalidate_pmx_solve_group_f;\n\nbool data_only_expression::operator()(const pmx_solve_group& x)\n  const {\n  return ((((((boost::apply_visitor(*this, x.time_.expr_)\n               && boost::apply_visitor(*this, x.amt_.expr_)))\n             && boost::apply_visitor(*this, x.rate_.expr_)\n             && boost::apply_visitor(*this, x.ii_.expr_))\n            && boost::apply_visitor(*this, x.pMatrix_.expr_))\n           && boost::apply_visitor(*this, x.biovar_.expr_))\n          && boost::apply_visitor(*this, x.tlag_.expr_));\n}\n\ntemplate void assign_lhs::operator()(expression&,\n                                     const pmx_solve_group&)\n  const;\n\n/***********************\n pmx_solve_group_control\n***********************/\n\nvoid validate_pmx_solve_group_control::operator()(\n                      const pmx_solve_group_control& ode_fun,\n                      const variable_map& var_map,\n                      bool& pass,\n                      std::ostream& error_msgs) const {\n  validate_pmx_solve_group_non_control_args(ode_fun, var_map, pass, error_msgs);\n  validate_pmx_solve_group_control_args(ode_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_pmx_solve_group_control>\nvalidate_pmx_solve_group_control_f;\n\nbool data_only_expression::operator()(const pmx_solve_group_control& x)\n  const {\n  return ((((((boost::apply_visitor(*this, x.time_.expr_)\n               && boost::apply_visitor(*this, x.amt_.expr_)))\n             && boost::apply_visitor(*this, x.rate_.expr_)\n             && boost::apply_visitor(*this, x.ii_.expr_))\n            && boost::apply_visitor(*this, x.pMatrix_.expr_))\n           && boost::apply_visitor(*this, x.biovar_.expr_))\n          && boost::apply_visitor(*this, x.tlag_.expr_));\n}\n\ntemplate void assign_lhs::operator()(expression&,\n                                     const pmx_solve_group_control&)\n  const;\n\n/*************************\n pmx_integrate_ode_group\n*************************/\n\nvoid validate_pmx_integrate_ode_group::operator()(\n                      const pmx_integrate_ode_group& ode_fun,\n                      const variable_map& var_map,\n                      bool& pass,\n                      std::ostream& error_msgs) const {\n  validate_pmx_integrate_ode_group_non_control_args(ode_fun, var_map, pass, error_msgs);\n}\nboost::phoenix::function<validate_pmx_integrate_ode_group>\nvalidate_pmx_integrate_ode_group_f;\n\nbool data_only_expression::operator()(const pmx_integrate_ode_group& x) const {\n  return boost::apply_visitor(*this, x.y0_.expr_)\n    && boost::apply_visitor(*this, x.theta_.expr_);\n}\n\ntemplate void assign_lhs::operator()(expression&, const pmx_integrate_ode_group&) const;\n\n/*********************************\n  pmx_integrate_ode_group_control\n *********************************/\nvoid validate_pmx_integrate_ode_group_control::operator()(const pmx_integrate_ode_group_control &ode_fun,\n                                                          const variable_map &var_map,\n                                                          bool &pass, std::ostream &error_msgs) const {\n  validate_pmx_integrate_ode_group_non_control_args(ode_fun, var_map, pass, error_msgs);\n  if (!ode_fun.rel_tol_.bare_type().is_primitive()) {\n    error_msgs << \"Eighth argument to \" << ode_fun.integration_function_name_\n               << \" (relative tolerance) must have type real or int;\"\n               << \" found type=\" << ode_fun.rel_tol_.bare_type() << \". \";\n    pass = false;\n  }\n  if (!ode_fun.abs_tol_.bare_type().is_primitive()) {\n    error_msgs << \"Ninth argument to \" << ode_fun.integration_function_name_\n               << \" (absolute tolerance) must have type real or int;\"\n               << \" found type=\" << ode_fun.abs_tol_.bare_type() << \". \";\n    pass = false;\n  }\n  if (!ode_fun.max_num_steps_.bare_type().is_primitive()) {\n    error_msgs << \"Tenth argument to \" << ode_fun.integration_function_name_\n               << \" (max steps) must have type real or int;\"\n               << \" found type=\" << ode_fun.max_num_steps_.bare_type() << \". \";\n    pass = false;\n  }\n\n  // test data-only variables do not have parameters (int locals OK)\n  if (has_var(ode_fun.rel_tol_, var_map)) {\n    error_msgs << \"Eighth argument to \" << ode_fun.integration_function_name_\n               << \" (relative tolerance) must be data only\"\n               << \" and not depend on parameters.\";\n    pass = false;\n  }\n  if (has_var(ode_fun.abs_tol_, var_map)) {\n    error_msgs << \"Ninth argument to \" << ode_fun.integration_function_name_\n               << \" (absolute tolerance ) must be data only\"\n               << \" and not depend parameters.\";\n    pass = false;\n  }\n  if (has_var(ode_fun.max_num_steps_, var_map)) {\n    error_msgs << \"Tenth argument to \" << ode_fun.integration_function_name_\n               << \" (max steps) must be data only\"\n               << \" and not depend on parameters.\";\n    pass = false;\n  }\n}\nboost::phoenix::function<validate_pmx_integrate_ode_group_control> validate_pmx_integrate_ode_group_control_f;\n\nbool data_only_expression::operator()(const pmx_integrate_ode_group_control& x) const {\n  return boost::apply_visitor(*this, x.y0_.expr_)\n    && boost::apply_visitor(*this, x.theta_.expr_);\n}\n\ntemplate void assign_lhs::operator()(expression&, const pmx_integrate_ode_group_control&) const;\n\n#endif\n", "meta": {"hexsha": "8752639cea27bfa5b2b9e4cbafa38196d4a1063d", "size": 53453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stan/torsten/semantic_actions_def.cpp", "max_stars_repo_name": "yizhang-cae/torsten-stan", "max_stars_repo_head_hexsha": "e8660206177e86d1a6a2ec2195b70c3d9ecf5e0b", "max_stars_repo_licenses": ["CC-BY-3.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-17T07:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-17T07:53:04.000Z", "max_issues_repo_path": "src/stan/torsten/semantic_actions_def.cpp", "max_issues_repo_name": "yizhang-cae/torsten-stan", "max_issues_repo_head_hexsha": "e8660206177e86d1a6a2ec2195b70c3d9ecf5e0b", "max_issues_repo_licenses": ["CC-BY-3.0", "BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T20:01:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-08T18:38:59.000Z", "max_forks_repo_path": "src/stan/torsten/semantic_actions_def.cpp", "max_forks_repo_name": "yizhang-cae/torsten-stan", "max_forks_repo_head_hexsha": "e8660206177e86d1a6a2ec2195b70c3d9ecf5e0b", "max_forks_repo_licenses": ["CC-BY-3.0", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-05T18:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-05T18:03:46.000Z", "avg_line_length": 39.6829992576, "max_line_length": 110, "alphanum_fraction": 0.5687613417, "num_tokens": 12246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1732881888514755, "lm_q2_score": 0.019124035527986447, "lm_q1q2_score": 0.0033139694801760425}}
{"text": "/*\n\n Ripser: a lean C++ code for computation of Vietoris-Rips persistence barcodes\n\n MIT License\n\n Copyright (c) 2015–2019 Ulrich Bauer\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 are under no obligation whatsoever to provide any bug fixes, patches, or\n upgrades to the features, functionality or performance of the source code\n (\"Enhancements\") to anyone; however, if you choose to make your Enhancements\n available either publicly, or directly to the author of this software, without\n imposing a separate written license agreement for such Enhancements, then you\n hereby grant the following license: a non-exclusive, royalty-free perpetual\n license to install, use, modify, prepare derivative works, incorporate into\n other computer software, distribute, and sublicense such enhancements or\n derivative works thereof, in binary and source code form.\n\n*/\n\n//#define USE_COEFFICIENTS\n\n#define INDICATE_PROGRESS\n//#define PRINT_PERSISTENCE_PAIRS\n\n//#define USE_SERIAL\n//#define USE_SHUFFLED_SERIAL\n\n#if defined(USE_SERIAL) || defined(USE_SHUFFLED_SERIAL)\n#define USING_SERIAL\n#define USE_SERIAL_ATOMIC_REF\n#endif\n\n#if !(defined USING_SERIAL)\n#define USE_TRIVIAL_CONCURRENT_HASHMAP\n#endif\n\n//#define USE_GOOGLE_HASHMAP\n\n//#define USE_TBB_HASHMAP\n\n#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <queue>\n#include <sstream>\n#include <unordered_map>\n\n#include <thread>\n#include <future>\n#include <atomic_ref.hpp>\n#include <reclamation.hpp>\n\n#include <counting_iterator.hpp>\n\n#ifndef USING_SERIAL\n#include <boost/sort/parallel/sort.hpp>\n#endif\n\n#ifdef USE_SHUFFLED_SERIAL\n#include <random>\n#endif\n\n#ifdef USE_PARALLEL_STL\n#include <execution>\n#endif\n\n#ifdef USE_TBB\n#include <tbb/tbb.h>\n#include <tbb/parallel_sort.h>\n#endif\n\n#ifdef USE_GOOGLE_HASHMAP\n#include <sparsehash/dense_hash_map>\ntemplate <class Key, class T, class H, class E>\nclass hash_map : public google::dense_hash_map<Key, T, H, E> {\npublic:\n\texplicit hash_map() : google::dense_hash_map<Key, T, H, E>() { this->set_empty_key(-1); }\n\tinline void reserve(size_t hint) { this->resize(hint); }\n};\n#elif defined(USE_TBB_HASHMAP)\n#include <tbb/concurrent_unordered_map.h>\ntemplate <class Key, class T, class H, class E>\nclass hash_map : public tbb::concurrent_unordered_map<Key, T, H, E>\n{\n    public:\n        using Parent = tbb::concurrent_unordered_map<Key, T, H, E>;\n        using iterator = typename Parent::iterator;\n\n        Key key(iterator it) const { return it->first; }\n        T   value(iterator it) const { return it->second; }\n\n        bool update(iterator it, T& expected, T desired) { it->second = desired; return true; }\n\n        template<class F>\n        void foreach(const F& f) const  { for(auto& x : (*this)) f(x); }\n\n        void reserve(size_t hint) {}\n};\n#elif defined(USE_TRIVIAL_CONCURRENT_HASHMAP)\n#include <trivial_concurrent_hash_map.hpp>\ntemplate <class Key, class T, class H, class E>\nclass hash_map : public mrzv::trivial_concurrent_hash_map<Key, T, H, E> {};\n#else\ntemplate <class Key, class T, class H, class E>\nclass hash_map : public std::unordered_map<Key, T, H, E>\n{\n    public:\n        using Parent = std::unordered_map<Key,T,H,E>;\n        using iterator = typename Parent::iterator;\n\n        Key key(iterator it) const { return it->first; }\n        T   value(iterator it) const { return it->second; }\n\n        bool update(iterator it, T& expected, T desired) { it->second = desired; return true; }\n\n        template<class F>\n        void foreach(const F& f) const  { for(auto& x : (*this)) f(x); }\n};\n#endif\n\ntypedef float value_t;\ntypedef int64_t index_t;\ntypedef uint16_t coefficient_t;\n\n#ifdef INDICATE_PROGRESS\nstatic const std::chrono::milliseconds time_step(40);\n#endif\n\nstatic const std::string clear_line(\"\\r\\033[K\");\n\nstatic const size_t num_coefficient_bits = 8;\nstatic const index_t coefficient_mask = (static_cast<index_t>(1) << num_coefficient_bits) - 1;\n\nstatic const index_t max_simplex_index =\n    (1l << (8 * sizeof(index_t) - 1 - num_coefficient_bits)) - 1;\n\nvoid check_overflow(index_t i) {\n\tif\n#ifdef USE_COEFFICIENTS\n\t    (i > max_simplex_index)\n#else\n\t    (i < 0)\n#endif\n\t\tthrow std::overflow_error(\"simplex index \" + std::to_string((uint64_t)i) +\n\t\t                          \" in filtration is larger than maximum index \" +\n\t\t                          std::to_string(max_simplex_index));\n}\n\nclass binomial_coeff_table {\n\tstd::vector<std::vector<index_t>> B;\n\npublic:\n\tbinomial_coeff_table(index_t n, index_t k) : B(n + 1) {\n\t\tfor (index_t i = 0; i <= n; ++i) {\n\t\t\tB[i].resize(k + 1, 0);\n\t\t\tB[i][0] = 1;\n\t\t\tfor (index_t j = 1; j < std::min(i, k + 1); ++j)\n\t\t\t\tB[i][j] = B[i - 1][j - 1] + B[i - 1][j];\n\t\t\tif (i <= k) B[i][i] = 1;\n\t\t\tcheck_overflow(B[i][std::min(i >> 1, k)]);\n\t\t}\n\t}\n\n\tindex_t operator()(index_t n, index_t k) const {\n\t\tassert(n < B.size() && k < B[n].size() && n >= k - 1);\n\t\treturn B[n][k];\n\t}\n};\n\nbool is_prime(const coefficient_t n) {\n\tif (!(n & 1) || n < 2) return n == 2;\n\tfor (coefficient_t p = 3; p <= n / p; p += 2)\n\t\tif (!(n % p)) return false;\n\treturn true;\n}\n\nstd::vector<coefficient_t> multiplicative_inverse_vector(const coefficient_t m) {\n\tstd::vector<coefficient_t> inverse(m);\n\tinverse[1] = 1;\n\t// m = a * (m / a) + m % a\n\t// Multipying with inverse(a) * inverse(m % a):\n\t// 0 = inverse(m % a) * (m / a) + inverse(a)  (mod m)\n\tfor (coefficient_t a = 2; a < m; ++a) inverse[a] = m - (inverse[m % a] * (m / a)) % m;\n\treturn inverse;\n}\n\n#ifdef USE_COEFFICIENTS\n\ntypedef index_t entry_t;\n\nentry_t make_entry(index_t i, coefficient_t c) { return (i << num_coefficient_bits) | c; }\nindex_t get_index(const entry_t& e) { return (e >> num_coefficient_bits); }\nindex_t get_coefficient(const entry_t& e) { return (e & coefficient_mask); }\nvoid set_coefficient(entry_t& e, const coefficient_t c) { e = (e & ~coefficient_mask) | c; }\n\n//std::ostream& operator<<(std::ostream& stream, const entry_t& e) {\n//    stream << get_index(e) << \":\" << get_coefficient(e);\n//    return stream;\n//}\n\n#else\n\ntypedef index_t entry_t;\nconst index_t get_index(const entry_t& i) { return i; }\nindex_t get_coefficient(const entry_t& i) { return 1; }\nentry_t make_entry(index_t _index, coefficient_t _value) { return entry_t(_index); }\nvoid set_coefficient(entry_t& e, const coefficient_t c) {}\n\n#endif\n\nconst entry_t& get_entry(const entry_t& e) { return e; }\n\ntypedef std::pair<value_t, index_t> diameter_index_t;\nvalue_t get_diameter(const diameter_index_t& i) { return i.first; }\nindex_t get_index(const diameter_index_t& i) { return i.second; }\n\ntypedef std::pair<index_t, value_t> index_diameter_t;\nindex_t get_index(const index_diameter_t& i) { return i.first; }\nvalue_t get_diameter(const index_diameter_t& i) { return i.second; }\n\nstruct diameter_entry_t : std::pair<value_t, entry_t> {\n\tusing std::pair<value_t, entry_t>::pair;\n\tdiameter_entry_t(value_t _diameter, index_t _index, coefficient_t _coefficient)\n\t    : diameter_entry_t(_diameter, make_entry(_index, _coefficient)) {}\n\tdiameter_entry_t(const diameter_index_t& _diameter_index, coefficient_t _coefficient)\n\t    : diameter_entry_t(get_diameter(_diameter_index),\n\t                       make_entry(get_index(_diameter_index), _coefficient)) {}\n\tdiameter_entry_t(const index_t& _index) : diameter_entry_t(0, _index, 0) {}\n};\n\nconst entry_t& get_entry(const diameter_entry_t& p) { return p.second; }\nentry_t& get_entry(diameter_entry_t& p) { return p.second; }\nconst index_t get_index(const diameter_entry_t& p) { return get_index(get_entry(p)); }\nconst coefficient_t get_coefficient(const diameter_entry_t& p) {\n\treturn get_coefficient(get_entry(p));\n}\nconst value_t& get_diameter(const diameter_entry_t& p) { return p.first; }\nvoid set_coefficient(diameter_entry_t& p, const coefficient_t c) {\n\tset_coefficient(get_entry(p), c);\n}\n\ntemplate <typename Entry> struct greater_diameter_or_smaller_index {\n\tbool operator()(const Entry& a, const Entry& b) const {\n\t\treturn (get_diameter(a) > get_diameter(b)) ||\n\t\t       ((get_diameter(a) == get_diameter(b)) && (get_index(a) < get_index(b)));\n\t}\n};\n\nenum compressed_matrix_layout { LOWER_TRIANGULAR, UPPER_TRIANGULAR };\n\ntemplate <compressed_matrix_layout Layout> struct compressed_distance_matrix {\n\tstd::vector<value_t> distances;\n\tstd::vector<value_t*> rows;\n\n\tcompressed_distance_matrix(std::vector<value_t>&& _distances)\n\t    : distances(std::move(_distances)), rows((1 + std::sqrt(1 + 8 * distances.size())) / 2) {\n\t\tassert(distances.size() == size() * (size() - 1) / 2);\n\t\tinit_rows();\n\t}\n\n\ttemplate <typename DistanceMatrix>\n\tcompressed_distance_matrix(const DistanceMatrix& mat)\n\t    : distances(mat.size() * (mat.size() - 1) / 2), rows(mat.size()) {\n\t\tinit_rows();\n\n\t\tfor (size_t i = 1; i < size(); ++i)\n\t\t\tfor (size_t j = 0; j < i; ++j) rows[i][j] = mat(i, j);\n\t}\n\n\tvalue_t operator()(const index_t i, const index_t j) const;\n\tsize_t size() const { return rows.size(); }\n\tvoid init_rows();\n};\n\ntypedef compressed_distance_matrix<LOWER_TRIANGULAR> compressed_lower_distance_matrix;\ntypedef compressed_distance_matrix<UPPER_TRIANGULAR> compressed_upper_distance_matrix;\n\ntemplate <> void compressed_lower_distance_matrix::init_rows() {\n\tvalue_t* pointer = &distances[0];\n\tfor (size_t i = 1; i < size(); ++i) {\n\t\trows[i] = pointer;\n\t\tpointer += i;\n\t}\n}\n\ntemplate <> void compressed_upper_distance_matrix::init_rows() {\n\tvalue_t* pointer = &distances[0] - 1;\n\tfor (size_t i = 0; i < size() - 1; ++i) {\n\t\trows[i] = pointer;\n\t\tpointer += size() - i - 2;\n\t}\n}\n\ntemplate <>\nvalue_t compressed_lower_distance_matrix::operator()(const index_t i, const index_t j) const {\n\treturn i == j ? 0 : i < j ? rows[j][i] : rows[i][j];\n}\n\ntemplate <>\nvalue_t compressed_upper_distance_matrix::operator()(const index_t i, const index_t j) const {\n\treturn i == j ? 0 : i > j ? rows[j][i] : rows[i][j];\n}\n\nstruct sparse_distance_matrix {\n\tstd::vector<std::vector<index_diameter_t>> neighbors;\n\n\tindex_t num_edges;\n\n\tsparse_distance_matrix(std::vector<std::vector<index_diameter_t>>&& _neighbors,\n\t                       index_t _num_edges)\n\t    : neighbors(std::move(_neighbors)), num_edges(_num_edges) {}\n\n\ttemplate <typename DistanceMatrix>\n\tsparse_distance_matrix(const DistanceMatrix& mat, const value_t threshold)\n\t    : neighbors(mat.size()), num_edges(0) {\n\n\t\tfor (size_t i = 0; i < size(); ++i)\n\t\t\tfor (size_t j = 0; j < size(); ++j)\n\t\t\t\tif (i != j && mat(i, j) <= threshold) {\n\t\t\t\t\t++num_edges;\n\t\t\t\t\tneighbors[i].push_back({j, mat(i, j)});\n\t\t\t\t}\n\t}\n\n\tsize_t size() const { return neighbors.size(); }\n};\n\nstruct euclidean_distance_matrix {\n\tstd::vector<std::vector<value_t>> points;\n\n\teuclidean_distance_matrix(std::vector<std::vector<value_t>>&& _points)\n\t    : points(std::move(_points)) {\n\t\tfor (auto p : points) { assert(p.size() == points.front().size()); }\n\t}\n\n\tvalue_t operator()(const index_t i, const index_t j) const {\n\t\tassert(i < points.size());\n\t\tassert(j < points.size());\n\t\treturn std::sqrt(std::inner_product(\n\t\t    points[i].begin(), points[i].end(), points[j].begin(), value_t(), std::plus<value_t>(),\n\t\t    [](value_t u, value_t v) { return (u - v) * (u - v); }));\n\t}\n\n\tsize_t size() const { return points.size(); }\n};\n\nclass union_find {\n\tstd::vector<index_t> parent;\n\tstd::vector<uint8_t> rank;\n\npublic:\n\tunion_find(const index_t n) : parent(n), rank(n, 0) {\n\t\tfor (index_t i = 0; i < n; ++i) parent[i] = i;\n\t}\n\n\tindex_t find(index_t x) {\n\t\tindex_t y = x, z;\n\t\twhile ((z = parent[y]) != y) y = z;\n\t\twhile ((z = parent[x]) != y) {\n\t\t\tparent[x] = y;\n\t\t\tx = z;\n\t\t}\n\t\treturn z;\n\t}\n\n\tvoid link(index_t x, index_t y) {\n\t\tif ((x = find(x)) == (y = find(y))) return;\n\t\tif (rank[x] > rank[y])\n\t\t\tparent[y] = x;\n\t\telse {\n\t\t\tparent[x] = y;\n\t\t\tif (rank[x] == rank[y]) ++rank[y];\n\t\t}\n\t}\n};\n\ntemplate <typename T> T begin(std::pair<T, T>& p) { return p.first; }\ntemplate <typename T> T end(std::pair<T, T>& p) { return p.second; }\n\ntemplate <typename ValueType> class compressed_sparse_matrix {\n    std::vector<std::vector<ValueType>*> columns;\n\npublic:\n    using Column = std::vector<ValueType>;\n\n    compressed_sparse_matrix(size_t n):\n        columns(n, nullptr)                                 {}\n    ~compressed_sparse_matrix()                             { for(Column* x : columns) delete x; }\n\n    size_t size() const { return columns.size(); }\n\n    Column* column(const index_t index)\n        { return mrzv::atomic_ref<Column*>(columns[index]).load(); }\n\n    Column* exchange(const index_t index, Column* desired)\n        { return mrzv::atomic_ref<Column*>(columns[index]).exchange(desired); }\n\n    void store(const index_t index, Column* desired)\n        { return mrzv::atomic_ref<Column*>(columns[index]).store(desired); }\n\n    bool update(const index_t index, Column*& expected, Column* desired)\n        { return mrzv::atomic_ref<Column*>(columns[index]).compare_exchange_weak(expected, desired); }\n};\n\n\ntemplate <class Predicate>\nindex_t get_max(index_t top, const index_t bottom, const Predicate pred) {\n\tif (!pred(top)) {\n\t\tindex_t count = top - bottom;\n\t\twhile (count > 0) {\n\t\t\tindex_t step = count >> 1, mid = top - step;\n\t\t\tif (!pred(mid)) {\n\t\t\t\ttop = mid - 1;\n\t\t\t\tcount -= step + 1;\n\t\t\t} else\n\t\t\t\tcount = step;\n\t\t}\n\t}\n\treturn top;\n}\n\ntemplate <typename DistanceMatrix> class ripser {\n\tconst DistanceMatrix dist;\n\tconst index_t n, dim_max;\n\tconst value_t threshold;\n\tconst float ratio;\n\tconst coefficient_t modulus;\n\tconst unsigned num_threads;\n\tconst binomial_coeff_table binomial_coeff;\n\tconst std::vector<coefficient_t> multiplicative_inverse;\n\n\tstruct entry_hash {\n\t\tstd::size_t operator()(const entry_t& e) const {\n\t\t\treturn std::hash<index_t>()(::get_index(e));\n\t\t}\n\t};\n\n\tstruct equal_index {\n\t\tbool operator()(const entry_t& e, const entry_t& f) const {\n\t\t\treturn ::get_index(e) == ::get_index(f);\n\t\t}\n\t};\n\n\ttypedef hash_map<entry_t, entry_t, entry_hash, equal_index> entry_hash_map;\n\n\ttypedef compressed_sparse_matrix<diameter_entry_t> Matrix;\n\ttypedef typename Matrix::Column MatrixColumn;\n\n\ttypedef std::priority_queue<diameter_entry_t, std::vector<diameter_entry_t>,\n\t\t\t                    greater_diameter_or_smaller_index<diameter_entry_t>> WorkingColumn;\n\npublic:\n\tripser(DistanceMatrix&& _dist, index_t _dim_max, value_t _threshold, float _ratio,\n\t       coefficient_t _modulus, unsigned _num_threads)\n\t    : dist(std::move(_dist)), n(dist.size()),\n\t      dim_max(std::min(_dim_max, index_t(dist.size() - 2))), threshold(_threshold),\n\t      ratio(_ratio), modulus(_modulus),\n#ifndef USING_SERIAL\n\t\t  num_threads((_num_threads == 0 ? std::thread::hardware_concurrency() : _num_threads)),\n#else\n\t\t  num_threads(1),\n#endif\n\t\t  binomial_coeff(n, dim_max + 2),\n\t      multiplicative_inverse(multiplicative_inverse_vector(_modulus)) {}\n\n\tindex_t get_max_vertex(const index_t idx, const index_t k, const index_t n) const {\n\t\treturn get_max(n, k - 1, [&](index_t w) -> bool { return (binomial_coeff(w, k) <= idx); });\n\t}\n\n\tindex_t get_edge_index(const index_t i, const index_t j) const {\n\t\treturn binomial_coeff(i, 2) + j;\n\t}\n\n\ttemplate <typename OutputIterator>\n\tOutputIterator get_simplex_vertices(index_t idx, const index_t dim, index_t n,\n\t                                    OutputIterator out) const {\n\t\t--n;\n\t\tfor (index_t k = dim + 1; k > 0; --k) {\n\t\t\tn = get_max_vertex(idx, k, n);\n\t\t\t*out++ = n;\n\t\t\tidx -= binomial_coeff(n, k);\n\t\t}\n\t\treturn out;\n\t}\n\n\tclass simplex_coboundary_enumerator;\n\n\tvoid assemble_columns_to_reduce(std::vector<diameter_index_t>& simplices,\n\t                                std::vector<diameter_index_t>& columns_to_reduce,\n\t                                entry_hash_map& pivot_column_index, index_t dim) {\n\n#ifdef INDICATE_PROGRESS\n\t\tstd::cerr << clear_line << \"assembling columns\" << std::flush;\n\t\tstd::chrono::steady_clock::time_point next = std::chrono::steady_clock::now() + time_step;\n#endif\n\n\t\t--dim;\n\t\tcolumns_to_reduce.clear();\n\t\tstd::vector<diameter_index_t> next_simplices;\n\n\t\tconst size_t chunk_size = 1024;\n\t\tstd::atomic<size_t> achunk {0};\n#ifdef INDICATE_PROGRESS\n\t\tstd::atomic<int> progress {0};\n#endif\n\n\t\tstd::vector<std::vector<diameter_index_t>> next_simplices_vec(num_threads), columns_to_reduce_vec(num_threads);\n#if defined(USE_TBB)\n\t\ttbb::parallel_for<unsigned>(0, num_threads,\n\t\t\t\t[&](unsigned i) {\n#else\n\t\tstd::vector<std::future<void>> handles;\n\t\tfor (unsigned i = 0; i < num_threads; ++i)\n\t\t\thandles.emplace_back(std::async(std::launch::async, [&,i]() {\n#endif\n\t\t\t\tstd::vector<diameter_index_t>& next_simplices    = next_simplices_vec[i];\n\t\t\t\tstd::vector<diameter_index_t>& columns_to_reduce = columns_to_reduce_vec[i];\n#ifdef INDICATE_PROGRESS\n\t\t\t\tint indicate_progress = progress++;\n#endif\n\t\t\t\tsize_t cur_chunk = achunk++;\n\t\t\t\twhile(cur_chunk * chunk_size < simplices.size()) {\n\t\t\t\t\tsize_t from = cur_chunk * chunk_size;\n\t\t\t\t\tsize_t to   = std::min((cur_chunk + 1) * chunk_size, simplices.size());\n\n\t\t\t\t\tfor (size_t idx = from; idx < to; ++idx) {\n\t\t\t\t\t\tauto& simplex = simplices[idx];\n\t\t\t\t\t\tsimplex_coboundary_enumerator cofacets(diameter_entry_t(simplex, 1), dim, *this);\n\t\t\t\t\t\twhile (cofacets.has_next(false)) {\n#ifdef INDICATE_PROGRESS\n\t\t\t\t\t\t\tif (indicate_progress == 0) {\n\t\t\t\t\t\t\t\tif (std::chrono::steady_clock::now() > next) {\n\t\t\t\t\t\t\t\t\tstd::cerr << clear_line << \"assembling columns (processing \"\n\t\t\t\t\t\t\t\t\t\t\t  << idx << \"/\" << simplices.size() << \" simplices)\" << std::flush;\n\t\t\t\t\t\t\t\t\tnext = std::chrono::steady_clock::now() + time_step;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\t\tauto cofacet = cofacets.next();\n\t\t\t\t\t\t\tif (get_diameter(cofacet) <= threshold) {\n\n\t\t\t\t\t\t\t\tnext_simplices.push_back({get_diameter(cofacet), get_index(cofacet)});\n\n\t\t\t\t\t\t\t\tif (pivot_column_index.find(get_entry(cofacet)) == pivot_column_index.end())\n\t\t\t\t\t\t\t\t\tcolumns_to_reduce.push_back({get_diameter(cofacet), get_index(cofacet)});\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\tcur_chunk = achunk++;\n\t\t\t\t}\n#if defined(USE_TBB)\n            });\n#else\n\t\t\t}));\n        handles.clear();\n#endif\n\n\t\t// figure out offsets to put everything together and resize\n\t\tstd::vector<size_t> simplices_prefix { 0 }, columns_to_reduce_prefix { 0 };\n\t\tfor (unsigned i = 0; i < num_threads; ++i) {\n\t\t\tsimplices_prefix.push_back(simplices_prefix.back() + next_simplices_vec[i].size());\n\t\t\tcolumns_to_reduce_prefix.push_back(columns_to_reduce_prefix.back() + columns_to_reduce_vec[i].size());\n\t\t}\n\t\tnext_simplices.resize(simplices_prefix.back());\n\t\tcolumns_to_reduce.resize(columns_to_reduce_prefix.back());\n\n\t\t// copy into the arrays\n#if defined(USE_TBB)\n\t\ttbb::parallel_for<unsigned>(0, num_threads,\n\t\t\t\t[&](unsigned i) {\n#else\n\t\tfor (unsigned i = 0; i < num_threads; ++i)\n\t\t\thandles.emplace_back(std::async(std::launch::async, [&,i]() {\n#endif\n\t\t\t\tsize_t k = 0;\n\t\t\t\tfor (size_t j = simplices_prefix[i]; j < simplices_prefix[i+1]; ++j)\n\t\t\t\t\tnext_simplices[j] = next_simplices_vec[i][k++];\n\t\t\t\t\n\t\t\t\tk = 0;\n\t\t\t\tfor (size_t j = columns_to_reduce_prefix[i]; j < columns_to_reduce_prefix[i+1]; ++j)\n\t\t\t\t\tcolumns_to_reduce[j] = columns_to_reduce_vec[i][k++];\n#if defined(USE_TBB)\n            });\n#else\n\t\t\t}));\n\t\thandles.clear();\t\t// force execution\n#endif\n\n\t\tsimplices.swap(next_simplices);\n\n#ifdef INDICATE_PROGRESS\n\t\tstd::cerr << clear_line << \"sorting \" << columns_to_reduce.size() << \" columns\"\n\t\t          << std::flush;\n#endif\n\n#ifdef USING_SERIAL\n\t\tstd::sort(columns_to_reduce.begin(), columns_to_reduce.end(),\n\t\t          greater_diameter_or_smaller_index<diameter_index_t>());\n#elif defined(USE_TBB)\n\t\ttbb::parallel_sort(columns_to_reduce.begin(), columns_to_reduce.end(),\n\t\t          greater_diameter_or_smaller_index<diameter_index_t>());\n#else\n\t\tboost::sort::parallel::parallel_sort(columns_to_reduce.begin(), columns_to_reduce.end(),\n\t\t\t\t  greater_diameter_or_smaller_index<diameter_index_t>(), num_threads);\n#endif\n#ifdef INDICATE_PROGRESS\n\t\tstd::cerr << clear_line << std::flush;\n#endif\n\t}\n\n\tvoid compute_dim_0_pairs(std::vector<diameter_index_t>& edges,\n\t                         std::vector<diameter_index_t>& columns_to_reduce) {\n#ifdef PRINT_PERSISTENCE_PAIRS\n\t\tstd::cout << \"persistence intervals in dim 0:\" << std::endl;\n#endif\n\n\t\tunion_find dset(n);\n\n\t\tedges = get_edges();\n\t\tstd::sort(edges.rbegin(), edges.rend(),\n\t\t          greater_diameter_or_smaller_index<diameter_index_t>());\n\t\tstd::vector<index_t> vertices_of_edge(2);\n\t\tfor (auto e : edges) {\n\t\t\tget_simplex_vertices(get_index(e), 1, n, vertices_of_edge.rbegin());\n\t\t\tindex_t u = dset.find(vertices_of_edge[0]), v = dset.find(vertices_of_edge[1]);\n\n\t\t\tif (u != v) {\n#ifdef PRINT_PERSISTENCE_PAIRS\n\t\t\t\tif (get_diameter(e) != 0)\n\t\t\t\t\tstd::cout << \" [0,\" << get_diameter(e) << \")\" << std::endl;\n#endif\n\t\t\t\tdset.link(u, v);\n\t\t\t} else\n\t\t\t\tcolumns_to_reduce.push_back(e);\n\t\t}\n\t\tstd::reverse(columns_to_reduce.begin(), columns_to_reduce.end());\n\n#ifdef PRINT_PERSISTENCE_PAIRS\n\t\tfor (index_t i = 0; i < n; ++i)\n\t\t\tif (dset.find(i) == i) std::cout << \" [0, )\" << std::endl;\n#endif\n\t}\n\n\tdiameter_entry_t pop_pivot(WorkingColumn& column) {\n\t\tdiameter_entry_t pivot(-1);\n#ifdef USE_COEFFICIENTS\n\t\twhile (!column.empty()) {\n\t\t\tif (get_coefficient(pivot) == 0)\n\t\t\t\tpivot = column.top();\n\t\t\telse if (get_index(column.top()) != get_index(pivot))\n\t\t\t\treturn pivot;\n\t\t\telse\n\t\t\t\tset_coefficient(pivot,\n\t\t\t\t                (get_coefficient(pivot) + get_coefficient(column.top())) % modulus);\n\t\t\tcolumn.pop();\n\t\t}\n\t\treturn (get_coefficient(pivot) == 0) ? -1 : pivot;\n#else\n\t\twhile (!column.empty()) {\n\t\t\tpivot = column.top();\n\t\t\tcolumn.pop();\n\t\t\tif (column.empty() || get_index(column.top()) != get_index(pivot)) return pivot;\n\t\t\tcolumn.pop();\n\t\t}\n\t\treturn -1;\n#endif\n\t}\n\n\tdiameter_entry_t get_pivot(WorkingColumn& column) {\n\t\tdiameter_entry_t result = pop_pivot(column);\n\t\tif (get_index(result) != -1) column.push(result);\n\t\treturn result;\n\t}\n\n\tstd::pair<diameter_entry_t,bool> init_coboundary_and_get_pivot(const diameter_entry_t simplex,\n\t                                               WorkingColumn& working_coboundary, const index_t& dim,\n\t                                               entry_hash_map& pivot_column_index, Matrix& reduction_matrix,\n\t\t\t\t\t\t\t\t\t\t\t\t   const size_t index_column_to_reduce) {\n\t\tthread_local static std::vector<diameter_entry_t> cofacet_entries;\n\t\tbool check_for_emergent_pair = true;\n\t\tcofacet_entries.clear();\n\t\tsimplex_coboundary_enumerator cofacets(simplex, dim, *this);\n\t\twhile (cofacets.has_next()) {\n\t\t\tdiameter_entry_t cofacet = cofacets.next();\n\t\t\tif (get_diameter(cofacet) <= threshold) {\n\t\t\t\tcofacet_entries.push_back(cofacet);\n\t\t\t\tif (check_for_emergent_pair && (get_diameter(simplex) == get_diameter(cofacet))) {\n\t\t\t\t\tif (pivot_column_index.find(get_entry(cofacet)) == pivot_column_index.end()) {\n\t\t\t\t\t\tif (pivot_column_index.insert({get_entry(cofacet), make_entry(index_column_to_reduce, get_coefficient(cofacet))}).second)\n\t\t\t\t\t\t\treturn { cofacet, true };\n\t\t\t\t\t}\n\t\t\t\t\tcheck_for_emergent_pair = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (auto cofacet : cofacet_entries) working_coboundary.push(cofacet);\n\t\treturn { get_pivot(working_coboundary), false };\n\t}\n\n\tvoid add_simplex_coboundary(const diameter_entry_t simplex, const index_t& dim,\n\t                            WorkingColumn& working_reduction_column, WorkingColumn& working_coboundary, bool add_diagonal = true) {\n\t\tif (add_diagonal) working_reduction_column.push(simplex);\n\t\tsimplex_coboundary_enumerator cofacets(simplex, dim, *this);\n\t\twhile (cofacets.has_next()) {\n\t\t\tdiameter_entry_t cofacet = cofacets.next();\n\t\t\tif (get_diameter(cofacet) <= threshold) working_coboundary.push(cofacet);\n\t\t}\n\t}\n\n\tvoid add_coboundary(MatrixColumn* reduction_column_to_add,\n\t                    const std::vector<diameter_index_t>& columns_to_reduce,\n\t                    const size_t index_column_to_add, const coefficient_t factor, const size_t& dim,\n\t                    WorkingColumn& working_reduction_column, WorkingColumn& working_coboundary, bool add_diagonal = true) {\n\t\tdiameter_entry_t column_to_add(columns_to_reduce[index_column_to_add], factor);\n\t\tadd_simplex_coboundary(column_to_add, dim, working_reduction_column, working_coboundary, add_diagonal);\n\n\t\tif (!reduction_column_to_add) return;\n\t\tfor (diameter_entry_t simplex : *reduction_column_to_add) {\n\t\t\tset_coefficient(simplex, get_coefficient(simplex) * factor % modulus);\n\t\t\tadd_simplex_coboundary(simplex, dim, working_reduction_column, working_coboundary);\n\t\t}\n\t}\n\n\tMatrixColumn* generate_column(WorkingColumn&& working_reduction_column) {\n\t\tif (working_reduction_column.empty())\n\t\t\treturn nullptr;\n\n\t\tMatrixColumn column;\n\t\twhile (true) {\n\t\t\tdiameter_entry_t e = pop_pivot(working_reduction_column);\n\t\t\tif (get_index(e) == -1) break;\n\t\t\tassert(get_coefficient(e) > 0);\n\t\t\tcolumn.push_back(e);\n\t\t}\n\n\t\tif (column.empty()) return nullptr;\n\t\treturn new MatrixColumn(std::move(column));\n\t}\n\n\ttemplate<class F>\n\tvoid foreach(const std::vector<diameter_index_t>& columns_to_reduce, const F& f) {\n#if defined(INDICATE_PROGRESS) && !defined(USE_SERIAL)\n\t\tstd::atomic<int> progress(0);\n\t\tstd::cerr << clear_line << \"Starting reduction of \" << columns_to_reduce.size() << \" columns\" << std::endl;\n#endif\n#ifdef USE_SERIAL\n\t\tint epoch_counter = 0;\n\t\tmrzv::MemoryManager<MatrixColumn> memory_manager(epoch_counter, 1);\n\n\t\tfor (size_t index_column_to_reduce = 0; index_column_to_reduce < columns_to_reduce.size();\n\t\t     ++index_column_to_reduce) {\n\t\t\tsize_t next = f(index_column_to_reduce, true, memory_manager);\n\t\t\tassert(next == index_column_to_reduce);\n\t\t}\n#elif defined(USE_SHUFFLED_SERIAL) // meant for debugging\n\t\tstd::vector<size_t> indices(mrzv::counting_iterator(0), mrzv::counting_iterator(columns_to_reduce.size()));\n\t\tstd::random_device rd;\n\t\tstd::mt19937 g(rd());\n\t\tstd::shuffle(indices.begin(), indices.end(), g);\n\n\t\tint epoch_counter = 0;\n\t\tmrzv::MemoryManager<MatrixColumn> memory_manager(epoch_counter, 1);\n\n\t\tsize_t count = 0;\n\t\tfor (size_t index_column_to_reduce : indices) {\n\t\t\tbool first = true;\n\t\t\tsize_t next;\n\t\t\tdo {\n\t\t\t\tnext = index_column_to_reduce;\n\t\t\t\tindex_column_to_reduce = f(next, first, memory_manager);\n\t\t\t\tfirst = false;\n\t\t\t} while (next != index_column_to_reduce);\n\n\t\t\tif (++count == 1024) {\n\t\t\t\tmemory_manager.quiescent();\n\t\t\t\tcount = 0;\n\t\t\t}\n\t\t}\n#elif defined(USE_PARALLEL_STL)\n\t\tint epoch_counter = 0;\n\t\tstd::for_each(std::execution::par, mrzv::counting_iterator(0), mrzv::counting_iterator(columns_to_reduce.size()),\n\t\t\t\t[&](size_t index_column_to_reduce) {\n\t\t\tthread_local int count = 0;\n\t\t\tthread_local mrzv::MemoryManager<MatrixColumn> memory_manager(epoch_counter, std::thread::hardware_concurrency());\n\n\t\t\tbool first = true;\n\t\t\tsize_t next;\n\t\t\tdo {\n\t\t\t\tnext = index_column_to_reduce;\n\t\t\t\tindex_column_to_reduce = f(next, first, memory_manager);\n\t\t\t\tfirst = false;\n\t\t\t} while (next != index_column_to_reduce);\n\n\t\t\tif (++count == 1024) {\n\t\t\t\tmemory_manager.quiescent();\n\t\t\t\tcount = 0;\n\t\t\t}\n\t\t});\n#elif defined(USE_TBB)\n\t\tint epoch_counter = 0;\n\t\ttbb::parallel_for<size_t>(0, columns_to_reduce.size(),\n\t\t\t\t[&](size_t index_column_to_reduce) {\n\t\t\tthread_local int count = 0;\n\t\t\tthread_local mrzv::MemoryManager<MatrixColumn> memory_manager(epoch_counter, num_threads);\n\n\t\t\tbool first = true;\n\t\t\tsize_t next;\n\t\t\tdo {\n\t\t\t\tnext = index_column_to_reduce;\n\t\t\t\tindex_column_to_reduce = f(next, first, memory_manager);\n\t\t\t\tfirst = false;\n\t\t\t} while (next != index_column_to_reduce);\n\n\t\t\tif (++count == 1024) {\n\t\t\t\tmemory_manager.quiescent();\n\t\t\t\tcount = 0;\n\t\t\t}\n\t\t});\n#else\t// default: hand-rolled chunking\n\t\tconst size_t chunk_size = 1024;\n\t\tsize_t chunk = 0;\n\t\tunsigned n_threads = num_threads;\n\n\t\tint epoch_counter = 0;\n\t\tstd::vector<std::thread> threads;\n\t\tfor (unsigned t = 0; t < n_threads; ++t)\n\t\t\tthreads.emplace_back([&]() {\n\t\t\t\tmrzv::atomic_ref<size_t> achunk(chunk);\n\n\t\t\t\tmrzv::MemoryManager<MatrixColumn> memory_manager(epoch_counter, n_threads);\n\n#ifdef INDICATE_PROGRESS\n\t\t\t\tint indicate_progress = progress++;\n\t\t\t\tstd::chrono::steady_clock::time_point next = std::chrono::steady_clock::now() + time_step;\n#endif\n\t\t\t\t\n\t\t\t\tsize_t cur_chunk = achunk++;\n\t\t\t\twhile(cur_chunk * chunk_size < columns_to_reduce.size()) {\n\t\t\t\t\tsize_t from = cur_chunk * chunk_size;\n\t\t\t\t\tsize_t to   = std::min((cur_chunk + 1) * chunk_size, columns_to_reduce.size());\n#ifdef INDICATE_PROGRESS\n\t\t\t\t\tif (indicate_progress == 0) {\n\t\t\t\t\t\tif (std::chrono::steady_clock::now() > next) {\n\t\t\t\t\t\t\tstd::cerr << clear_line << \"reducing columns \" << from << \" - \" << to\n\t\t\t\t\t\t\t\t\t  << \"/\" << columns_to_reduce.size()\n\t\t\t\t\t\t\t\t\t  << std::flush;\n\t\t\t\t\t\t\tnext = std::chrono::steady_clock::now() + time_step;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t\tfor (size_t idx = from; idx < to; ++idx) {\n\t\t\t\t\t\tsize_t index_column_to_reduce = idx;\n\t\t\t\t\t\tbool first = true;\n\t\t\t\t\t\tsize_t next;\n\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\tnext = index_column_to_reduce;\n\t\t\t\t\t\t\tindex_column_to_reduce = f(next, first, memory_manager);\n\t\t\t\t\t\t\tfirst = false;\n\t\t\t\t\t\t} while (next != index_column_to_reduce);\n\t\t\t\t\t}\n\t\t\t\t\tcur_chunk = achunk++;\n\t\t\t\t\tmemory_manager.quiescent();\n\t\t\t\t}\n\t\t\t});\n\n\t\tfor (auto& thread : threads)\n\t\t\tthread.join();\n#endif\n\t}\n\n\t// debug only\n\tdiameter_entry_t get_column_pivot(MatrixColumn* column,\n\t                    const std::vector<diameter_index_t>& columns_to_reduce,\n\t                    const size_t index, const coefficient_t factor, const size_t& dim) {\n\t\tWorkingColumn tmp_working_reduction_column, tmp_working_coboundary;\n\t\tadd_coboundary(column, columns_to_reduce, index,\n\t\t\t\t\t   1, dim, tmp_working_reduction_column, tmp_working_coboundary);\n\t\treturn get_pivot(tmp_working_coboundary);\n\t}\n\n\tvoid compute_pairs(const std::vector<diameter_index_t>& columns_to_reduce,\n\t                   entry_hash_map& pivot_column_index, const index_t dim) {\n\n#if defined(PRINT_PERSISTENCE_PAIRS)\n\t\tstd::cout << \"persistence intervals in dim \" << dim << \":\" << std::endl;\n#endif\n\n\t\tMatrix reduction_matrix(columns_to_reduce.size());\n\n#if defined(PRINT_PERSISTENCE_PAIRS) && !defined(USING_SERIAL)\n\t\t// extra vector is a work-around inability to store floats in the hash_map\n\t\ttypedef hash_map<entry_t, size_t, entry_hash, equal_index> entry_diameter_index_map;\n\t\tstd::atomic<size_t> last_diameter_index { 0 };\n\t\tstd::vector<value_t> diameters(columns_to_reduce.size());\n\t\tentry_diameter_index_map deaths;\n\t\tdeaths.reserve(columns_to_reduce.size());\n#endif\n\n#if defined(INDICATE_PROGRESS) && defined(USING_SERIAL)\n\t\tstd::chrono::steady_clock::time_point next = std::chrono::steady_clock::now() + time_step;\n#endif\n\t\tforeach(columns_to_reduce, [&](index_t index_column_to_reduce, bool first, mrzv::MemoryManager<MatrixColumn>& memory_manager) {\n\t\t\tdiameter_entry_t column_to_reduce(columns_to_reduce[index_column_to_reduce], 1);\n\t\t\tvalue_t diameter = get_diameter(column_to_reduce);\n\n\t\t\tWorkingColumn working_reduction_column, working_coboundary;\n\n\t\t\tdiameter_entry_t pivot;\n\t\t\tif (first) {\n\t\t\t\tbool emergent;\n\t\t\t\tstd::tie(pivot,emergent) = init_coboundary_and_get_pivot(\n\t\t\t\t\tcolumn_to_reduce, working_coboundary, dim, pivot_column_index, reduction_matrix, index_column_to_reduce);\n\t\t\t\tif (emergent)\n\t\t\t\t\treturn index_column_to_reduce;\n\t\t\t} else {\n\t\t\t\tMatrixColumn* reduction_column_to_reduce = reduction_matrix.column(index_column_to_reduce);\n\t\t\t\tadd_coboundary(reduction_column_to_reduce, columns_to_reduce, index_column_to_reduce,\n\t\t\t\t\t\t\t   1, dim, working_reduction_column, working_coboundary, false);\n\t\t\t\tpivot = get_pivot(working_coboundary);\n\t\t\t}\n\n\t\t\twhile (true) {\n#if defined(INDICATE_PROGRESS) && defined(USING_SERIAL)\n\t\t\t\tif (std::chrono::steady_clock::now() > next) {\n\t\t\t\t\tstd::cerr << clear_line << \"reducing column \" << index_column_to_reduce + 1\n\t\t\t\t\t          << \"/\" << columns_to_reduce.size() << \" (diameter \" << diameter << \")\"\n\t\t\t\t\t          << std::flush;\n\t\t\t\t\tnext = std::chrono::steady_clock::now() + time_step;\n\t\t\t\t}\n#endif\n\t\t\t\tif (get_index(pivot) != -1) {\n\t\t\t\t\tauto pair = pivot_column_index.find(get_entry(pivot));\n\t\t\t\t\tif (pair != pivot_column_index.end()) {\n\t\t\t\t\t\tentry_t old_entry_column_to_add;\n\t\t\t\t\t\tindex_t index_column_to_add;\n\t\t\t\t\t\tMatrixColumn* reduction_column_to_add;\n\t\t\t\t\t\tentry_t entry_column_to_add = pivot_column_index.value(pair);\n\t\t\t\t\t\tdo\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\told_entry_column_to_add = entry_column_to_add;\n\n\t\t\t\t\t\t\tindex_column_to_add = get_index(entry_column_to_add);\n\n\t\t\t\t\t\t\treduction_column_to_add = reduction_matrix.column(index_column_to_add);\n\n\t\t\t\t\t\t\t// this is a weaker check than in the original lockfree\n\t\t\t\t\t\t\t// persistence paper (it would suffice that the pivot\n\t\t\t\t\t\t\t// in reduction_column_to_add) hasn't changed, but\n\t\t\t\t\t\t\t// given that matrix V is stored, rather than matrix R,\n\t\t\t\t\t\t\t// it's easier to check that pivot_column_index entry\n\t\t\t\t\t\t\t// we read hasn't changed\n\t\t\t\t\t\t\t// TODO: think through memory orders, and whether we need to adjust anything\n\t\t\t\t\t\t\tentry_column_to_add = pivot_column_index.value(pair);\n\t\t\t\t\t\t} while (old_entry_column_to_add != entry_column_to_add);\n\n\t\t\t\t\t\tif (index_column_to_add < index_column_to_reduce)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// pivot to the left; usual reduction\n\t\t\t\t\t\t\tcoefficient_t factor =\n\t\t\t\t\t\t\t\tmodulus - get_coefficient(pivot) *\n\t\t\t\t\t\t\t\t\t\t\t  multiplicative_inverse[get_coefficient(entry_column_to_add)] %\n\t\t\t\t\t\t\t\t\t\t\t  modulus;\n\n\t\t\t\t\t\t\tadd_coboundary(reduction_column_to_add, columns_to_reduce, index_column_to_add,\n\t\t\t\t\t\t\t\t\t\t   factor, dim, working_reduction_column, working_coboundary);\n\n\t\t\t\t\t\t\tpivot = get_pivot(working_coboundary);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// pivot to the right\n\t\t\t\t\t\t\tMatrixColumn* new_column = generate_column(std::move(working_reduction_column));\n\t\t\t\t\t\t\tMatrixColumn* previous = reduction_matrix.exchange(index_column_to_reduce, new_column);\n\t\t\t\t\t\t\tassert(get_index(get_column_pivot(new_column, columns_to_reduce, index_column_to_reduce, 1, dim)) == get_index(pivot));\n\t\t\t\t\t\t\tmemory_manager.retire(previous);\n\n\t\t\t\t\t\t\tif (pivot_column_index.update(pair, entry_column_to_add, make_entry(index_column_to_reduce, get_coefficient(pivot)))) {\n\t\t\t\t\t\t\t\treturn index_column_to_add;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontinue; // re-read the pair\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n#if defined(PRINT_PERSISTENCE_PAIRS) && defined(USING_SERIAL)\n\t\t\t\t\t\tvalue_t death = get_diameter(pivot);\n\t\t\t\t\t\tif (death > diameter * ratio) {\n#ifdef INDICATE_PROGRESS\n\t\t\t\t\t\t\tstd::cerr << clear_line << std::flush;\n#endif\n\t\t\t\t\t\t\tstd::cout << \" [\" << diameter << \",\" << death << \")\" << (first ? \"\" : \" <- correction\") << std::endl;\n\t\t\t\t\t\t}\n#endif\n#if defined(PRINT_PERSISTENCE_PAIRS) && !defined(USING_SERIAL)\n\t\t\t\t\t\tsize_t location = last_diameter_index++;\n\t\t\t\t\t\tdiameters[location] = get_diameter(pivot);\n\t\t\t\t\t\tdeaths.insert({get_entry(pivot), location});\n#endif\n\t\t\t\t\t\tMatrixColumn* new_column = generate_column(std::move(working_reduction_column));\n\t\t\t\t\t\tMatrixColumn* previous = reduction_matrix.exchange(index_column_to_reduce, new_column);\n\t\t\t\t\t\tmemory_manager.retire(previous);\n\n\t\t\t\t\t\tassert(get_index(get_column_pivot(new_column, columns_to_reduce, index_column_to_reduce, 1, dim)) == get_index(pivot));\n\n\t\t\t\t\t\t// equivalent to CAS in the original algorithm\n\t\t\t\t\t\tauto insertion_result = pivot_column_index.insert({get_entry(pivot), make_entry(index_column_to_reduce, get_coefficient(pivot))});\n\t\t\t\t\t\tif (!insertion_result.second)\t\t// failed to insert, somebody got there before us, continue reduction\n\t\t\t\t\t\t\tcontinue;\t\t\t\t\t\t// TODO: insertion_result.first is the new pair; could elide and extra atomic load\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: these will need special attention, if output happens after the reduction, not during\n#if defined(PRINT_PERSISTENCE_PAIRS) && defined(USING_SERIAL)\n#ifdef INDICATE_PROGRESS\n\t\t\t\t\tstd::cerr << clear_line << std::flush;\n#endif\n\t\t\t\t\tstd::cout << \" [\" << diameter << \", )\" << (first ? \"\" : \" <- correction\") << std::endl;\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn index_column_to_reduce;\n\t\t});\n#if defined(INDICATE_PROGRESS)\n\t\tstd::cerr << clear_line << std::flush;\n#endif\n#if defined(PRINT_PERSISTENCE_PAIRS) && !defined(USING_SERIAL)\n\t\tpivot_column_index.foreach([&](const typename entry_hash_map::value_type& x) {\n\t\t\tauto it = deaths.find(x.first);\n\t\t\tif (it == deaths.end()) return;\n\t\t\tvalue_t death = diameters[it->second];\n\t\t\tvalue_t birth = get_diameter(columns_to_reduce[get_index(x.second)]);\n\t\t\tif (death > birth * ratio)\n\t\t\t\tstd::cout << \" [\" << birth << \",\" << death << \")\" << std::endl;\n\t\t});\n\t\t// TODO: this doesn't print unpaired values\n#endif\n\t}\n\n\tstd::vector<diameter_index_t> get_edges();\n\n\tvoid compute_barcodes() {\n\t\tstd::vector<diameter_index_t> simplices, columns_to_reduce;\n\n\t\tcompute_dim_0_pairs(simplices, columns_to_reduce);\n\n\t\tfor (index_t dim = 1; dim <= dim_max; ++dim) {\n\t\t\tentry_hash_map pivot_column_index;\n\t\t\tpivot_column_index.reserve(columns_to_reduce.size());\n\n\t\t\tcompute_pairs(columns_to_reduce, pivot_column_index, dim);\n\n\t\t\tif (dim < dim_max)\n\t\t\t\tassemble_columns_to_reduce(simplices, columns_to_reduce, pivot_column_index,\n\t\t\t\t                           dim + 1);\n\t\t}\n\t}\n};\n\ntemplate <> class ripser<compressed_lower_distance_matrix>::simplex_coboundary_enumerator {\n\tindex_t idx_below, idx_above, v, k;\n\tstd::vector<index_t> vertices;\n\tconst diameter_entry_t simplex;\n\tconst coefficient_t modulus;\n\tconst compressed_lower_distance_matrix& dist;\n\tconst binomial_coeff_table& binomial_coeff;\n\npublic:\n\tsimplex_coboundary_enumerator(const diameter_entry_t _simplex, const index_t _dim,\n\t                              const ripser& parent)\n\t    : idx_below(get_index(_simplex)), idx_above(0), v(parent.n - 1), k(_dim + 1),\n\t      vertices(_dim + 1), simplex(_simplex), modulus(parent.modulus), dist(parent.dist),\n\t      binomial_coeff(parent.binomial_coeff) {\n\t\tparent.get_simplex_vertices(get_index(_simplex), _dim, parent.n, vertices.rbegin());\n\t}\n\n\tbool has_next(bool all_cofacets = true) {\n\t\treturn (v >= k && (all_cofacets || binomial_coeff(v, k) > idx_below));\n\t}\n\n\tdiameter_entry_t next() {\n\t\twhile ((binomial_coeff(v, k) <= idx_below)) {\n\t\t\tidx_below -= binomial_coeff(v, k);\n\t\t\tidx_above += binomial_coeff(v, k + 1);\n\t\t\t--v;\n\t\t\t--k;\n\t\t\tassert(k != -1);\n\t\t}\n\t\tvalue_t cofacet_diameter = get_diameter(simplex);\n\t\tfor (index_t w : vertices) cofacet_diameter = std::max(cofacet_diameter, dist(v, w));\n\t\tindex_t cofacet_index = idx_above + binomial_coeff(v--, k + 1) + idx_below;\n\t\tcoefficient_t cofacet_coefficient =\n\t\t    (k & 1 ? modulus - 1 : 1) * get_coefficient(simplex) % modulus;\n\t\treturn diameter_entry_t(cofacet_diameter, cofacet_index, cofacet_coefficient);\n\t}\n};\n\ntemplate <> class ripser<sparse_distance_matrix>::simplex_coboundary_enumerator {\n\tconst ripser& parent;\n\tindex_t idx_below, idx_above, k;\n\tstd::vector<index_t> vertices;\n\tconst diameter_entry_t simplex;\n\tconst coefficient_t modulus;\n\tconst sparse_distance_matrix& dist;\n\tconst binomial_coeff_table& binomial_coeff;\n\tstatic thread_local std::vector<std::vector<index_diameter_t>::const_reverse_iterator> neighbor_it;\n\tstatic thread_local std::vector<std::vector<index_diameter_t>::const_reverse_iterator> neighbor_end;\n\tindex_diameter_t neighbor;\n\npublic:\n\tsimplex_coboundary_enumerator(const diameter_entry_t _simplex, const index_t _dim,\n\t                              const ripser& _parent)\n\t    : parent(_parent), idx_below(get_index(_simplex)), idx_above(0), k(_dim + 1),\n\t      vertices(_dim + 1), simplex(_simplex), modulus(parent.modulus), dist(parent.dist),\n\t      binomial_coeff(parent.binomial_coeff) {\n\t\tneighbor_it.clear();\n\t\tneighbor_end.clear();\n\n\t\tparent.get_simplex_vertices(idx_below, _dim, parent.n, vertices.rbegin());\n\t\tfor (auto v : vertices) {\n\t\t\tneighbor_it.push_back(dist.neighbors[v].rbegin());\n\t\t\tneighbor_end.push_back(dist.neighbors[v].rend());\n\t\t}\n\t}\n\n\tbool has_next(bool all_cofacets = true) {\n\t\tfor (auto &it0 = neighbor_it[0], &end0 = neighbor_end[0]; it0 != end0; ++it0) {\n\t\t\tneighbor = *it0;\n\t\t\tfor (size_t idx = 1; idx < neighbor_it.size(); ++idx) {\n\t\t\t\tauto &it = neighbor_it[idx], end = neighbor_end[idx];\n\t\t\t\twhile (get_index(*it) > get_index(neighbor))\n\t\t\t\t\tif (++it == end) return false;\n\t\t\t\tif (get_index(*it) != get_index(neighbor))\n\t\t\t\t\tgoto continue_outer;\n\t\t\t\telse\n\t\t\t\t\tneighbor = std::max(neighbor, *it);\n\t\t\t}\n\t\t\twhile (k > 0 && vertices[k - 1] > get_index(neighbor)) {\n\t\t\t\tif (!all_cofacets) return false;\n\t\t\t\tidx_below -= binomial_coeff(vertices[k - 1], k);\n\t\t\t\tidx_above += binomial_coeff(vertices[k - 1], k + 1);\n\t\t\t\t--k;\n\t\t\t}\n\t\t\treturn true;\n\t\tcontinue_outer:;\n\t\t}\n\t\treturn false;\n\t}\n\n\tdiameter_entry_t next() {\n\t\t++neighbor_it[0];\n\t\tvalue_t cofacet_diameter = std::max(get_diameter(simplex), get_diameter(neighbor));\n\t\tindex_t cofacet_index = idx_above + binomial_coeff(get_index(neighbor), k + 1) + idx_below;\n\t\tcoefficient_t cofacet_coefficient =\n\t\t    (k & 1 ? modulus - 1 : 1) * get_coefficient(simplex) % modulus;\n\t\treturn diameter_entry_t(cofacet_diameter, cofacet_index, cofacet_coefficient);\n\t}\n};\n\nthread_local std::vector<std::vector<index_diameter_t>::const_reverse_iterator> ripser<sparse_distance_matrix>::simplex_coboundary_enumerator::neighbor_it;\nthread_local std::vector<std::vector<index_diameter_t>::const_reverse_iterator> ripser<sparse_distance_matrix>::simplex_coboundary_enumerator::neighbor_end;\n\ntemplate <> std::vector<diameter_index_t> ripser<compressed_lower_distance_matrix>::get_edges() {\n\tstd::vector<diameter_index_t> edges;\n\tstd::vector<index_t> vertices(2);\n\tfor (index_t index = binomial_coeff(n, 2); index-- > 0;) {\n\t\tget_simplex_vertices(index, 1, dist.size(), vertices.rbegin());\n\t\tvalue_t length = dist(vertices[0], vertices[1]);\n\t\tif (length <= threshold) edges.push_back({length, index});\n\t}\n\treturn edges;\n}\n\ntemplate <> std::vector<diameter_index_t> ripser<sparse_distance_matrix>::get_edges() {\n\tstd::vector<diameter_index_t> edges;\n\tfor (index_t i = 0; i < n; ++i)\n\t\tfor (auto n : dist.neighbors[i]) {\n\t\t\tindex_t j = get_index(n);\n\t\t\tif (i > j) edges.push_back({get_diameter(n), get_edge_index(i, j)});\n\t\t}\n\treturn edges;\n}\n\nenum file_format {\n\tLOWER_DISTANCE_MATRIX,\n\tUPPER_DISTANCE_MATRIX,\n\tDISTANCE_MATRIX,\n\tPOINT_CLOUD,\n\tDIPHA,\n\tSPARSE,\n\tBINARY\n};\n\nstatic const uint16_t endian_check(0xff00);\nstatic const bool is_big_endian = *reinterpret_cast<const uint8_t*>(&endian_check);\n\ntemplate <typename T> T read(std::istream& input_stream) {\n\tT result;\n\tchar* p = reinterpret_cast<char*>(&result);\n\tif (input_stream.read(p, sizeof(T)).gcount() != sizeof(T)) return T();\n\tif (is_big_endian) std::reverse(p, p + sizeof(T));\n\treturn result;\n}\n\ncompressed_lower_distance_matrix read_point_cloud(std::istream& input_stream) {\n\tstd::vector<std::vector<value_t>> points;\n\n\tstd::string line;\n\tvalue_t value;\n\twhile (std::getline(input_stream, line)) {\n\t\tstd::vector<value_t> point;\n\t\tstd::istringstream s(line);\n\t\twhile (s >> value) {\n\t\t\tpoint.push_back(value);\n\t\t\ts.ignore();\n\t\t}\n\t\tif (!point.empty()) points.push_back(point);\n\t\tassert(point.size() == points.front().size());\n\t}\n\n\teuclidean_distance_matrix eucl_dist(std::move(points));\n\tindex_t n = eucl_dist.size();\n\tstd::cout << \"point cloud with \" << n << \" points in dimension \"\n\t          << eucl_dist.points.front().size() << std::endl;\n\n\tstd::vector<value_t> distances;\n\tfor (int i = 0; i < n; ++i)\n\t\tfor (int j = 0; j < i; ++j) distances.push_back(eucl_dist(i, j));\n\n\treturn compressed_lower_distance_matrix(std::move(distances));\n}\n\nsparse_distance_matrix read_sparse_distance_matrix(std::istream& input_stream) {\n\tstd::vector<std::vector<index_diameter_t>> neighbors;\n\tindex_t num_edges = 0;\n\n\tstd::string line;\n\twhile (std::getline(input_stream, line)) {\n\t\tstd::istringstream s(line);\n\t\tsize_t i, j;\n\t\tvalue_t value;\n\t\ts >> i;\n\t\ts >> j;\n\t\ts >> value;\n\t\tif (i != j) {\n\t\t\tneighbors.resize(std::max({neighbors.size(), i + 1, j + 1}));\n\t\t\tneighbors[i].push_back({j, value});\n\t\t\tneighbors[j].push_back({i, value});\n\t\t\t++num_edges;\n\t\t}\n\t}\n\n\tfor (size_t i = 0; i < neighbors.size(); ++i)\n\t\tstd::sort(neighbors[i].begin(), neighbors[i].end());\n\n\treturn sparse_distance_matrix(std::move(neighbors), num_edges);\n}\n\ncompressed_lower_distance_matrix read_lower_distance_matrix(std::istream& input_stream) {\n\tstd::vector<value_t> distances;\n\tvalue_t value;\n\twhile (input_stream >> value) {\n\t\tdistances.push_back(value);\n\t\tinput_stream.ignore();\n\t}\n\n\treturn compressed_lower_distance_matrix(std::move(distances));\n}\n\ncompressed_lower_distance_matrix read_upper_distance_matrix(std::istream& input_stream) {\n\tstd::vector<value_t> distances;\n\tvalue_t value;\n\twhile (input_stream >> value) {\n\t\tdistances.push_back(value);\n\t\tinput_stream.ignore();\n\t}\n\n\treturn compressed_lower_distance_matrix(compressed_upper_distance_matrix(std::move(distances)));\n}\n\ncompressed_lower_distance_matrix read_distance_matrix(std::istream& input_stream) {\n\tstd::vector<value_t> distances;\n\n\tstd::string line;\n\tvalue_t value;\n\tfor (int i = 0; std::getline(input_stream, line); ++i) {\n\t\tstd::istringstream s(line);\n\t\tfor (int j = 0; j < i && s >> value; ++j) {\n\t\t\tdistances.push_back(value);\n\t\t\ts.ignore();\n\t\t}\n\t}\n\n\treturn compressed_lower_distance_matrix(std::move(distances));\n}\n\ncompressed_lower_distance_matrix read_dipha(std::istream& input_stream) {\n\tif (read<int64_t>(input_stream) != 8067171840) {\n\t\tstd::cerr << \"input is not a Dipha file (magic number: 8067171840)\" << std::endl;\n\t\texit(-1);\n\t}\n\n\tif (read<int64_t>(input_stream) != 7) {\n\t\tstd::cerr << \"input is not a Dipha distance matrix (file type: 7)\" << std::endl;\n\t\texit(-1);\n\t}\n\n\tindex_t n = read<int64_t>(input_stream);\n\n\tstd::vector<value_t> distances;\n\n\tfor (int i = 0; i < n; ++i)\n\t\tfor (int j = 0; j < n; ++j)\n\t\t\tif (i > j)\n\t\t\t\tdistances.push_back(read<double>(input_stream));\n\t\t\telse\n\t\t\t\tread<double>(input_stream);\n\n\treturn compressed_lower_distance_matrix(std::move(distances));\n}\n\ncompressed_lower_distance_matrix read_binary(std::istream& input_stream) {\n\tstd::vector<value_t> distances;\n\twhile (!input_stream.eof()) distances.push_back(read<value_t>(input_stream));\n\treturn compressed_lower_distance_matrix(std::move(distances));\n}\n\ncompressed_lower_distance_matrix read_file(std::istream& input_stream, const file_format format) {\n\tswitch (format) {\n\tcase LOWER_DISTANCE_MATRIX:\n\t\treturn read_lower_distance_matrix(input_stream);\n\tcase UPPER_DISTANCE_MATRIX:\n\t\treturn read_upper_distance_matrix(input_stream);\n\tcase DISTANCE_MATRIX:\n\t\treturn read_distance_matrix(input_stream);\n\tcase POINT_CLOUD:\n\t\treturn read_point_cloud(input_stream);\n\tcase DIPHA:\n\t\treturn read_dipha(input_stream);\n\tdefault:\n\t\treturn read_binary(input_stream);\n\t}\n}\n\nvoid print_usage_and_exit(int exit_code) {\n\tstd::cerr\n\t    << \"Usage: \"\n\t    << \"ripser \"\n\t    << \"[options] [filename]\" << std::endl\n\t    << std::endl\n\t    << \"Options:\" << std::endl\n\t    << std::endl\n\t    << \"  --help           print this screen\" << std::endl\n\t    << \"  --format         use the specified file format for the input. Options are:\"\n\t    << std::endl\n\t    << \"                     lower-distance (lower triangular distance matrix; default)\"\n\t    << std::endl\n\t    << \"                     upper-distance (upper triangular distance matrix)\" << std::endl\n\t    << \"                     distance       (full distance matrix)\" << std::endl\n\t    << \"                     point-cloud    (point cloud in Euclidean space)\" << std::endl\n\t    << \"                     dipha          (distance matrix in DIPHA file format)\" << std::endl\n\t    << \"                     sparse         (sparse distance matrix in sparse triplet format)\"\n\t    << std::endl\n\t    << \"                     binary         (lower triangular distance matrix in binary format)\"\n\t    << std::endl\n\t    << \"  --dim <k>        compute persistent homology up to dimension k\" << std::endl\n\t    << \"  --threshold <t>  compute Rips complexes up to diameter t\" << std::endl\n#ifdef USE_COEFFICIENTS\n\t    << \"  --modulus <p>    compute homology with coefficients in the prime field Z/pZ\"\n\t    << std::endl\n#endif\n#ifndef USING_SERIAL\n\t    << \"  --threads <t>    number of threads to use\"\n\t    << std::endl\n#endif\n\t    << \"  --ratio <r>      only show persistence pairs with death/birth ratio > r\" << std::endl\n\t    << std::endl;\n\texit(exit_code);\n}\n\nint main(int argc, char** argv) {\n\tconst char* filename = nullptr;\n\n\tfile_format format = DISTANCE_MATRIX;\n\n\tindex_t dim_max = 1;\n\tvalue_t threshold = std::numeric_limits<value_t>::max();\n\tfloat ratio = 1;\n\tcoefficient_t modulus = 2;\n\tunsigned num_threads = 0;\n\n\tfor (index_t i = 1; i < argc; ++i) {\n\t\tconst std::string arg(argv[i]);\n\t\tif (arg == \"--help\") {\n\t\t\tprint_usage_and_exit(0);\n\t\t} else if (arg == \"--dim\") {\n\t\t\tstd::string parameter = std::string(argv[++i]);\n\t\t\tsize_t next_pos;\n\t\t\tdim_max = std::stol(parameter, &next_pos);\n\t\t\tif (next_pos != parameter.size()) print_usage_and_exit(-1);\n\t\t} else if (arg == \"--threshold\") {\n\t\t\tstd::string parameter = std::string(argv[++i]);\n\t\t\tsize_t next_pos;\n\t\t\tthreshold = std::stof(parameter, &next_pos);\n\t\t\tif (next_pos != parameter.size()) print_usage_and_exit(-1);\n\t\t} else if (arg == \"--ratio\") {\n\t\t\tstd::string parameter = std::string(argv[++i]);\n\t\t\tsize_t next_pos;\n\t\t\tratio = std::stof(parameter, &next_pos);\n\t\t\tif (next_pos != parameter.size()) print_usage_and_exit(-1);\n\t\t} else if (arg == \"--format\") {\n\t\t\tstd::string parameter = std::string(argv[++i]);\n\t\t\tif (parameter.rfind(\"lower\", 0) == 0)\n\t\t\t\tformat = LOWER_DISTANCE_MATRIX;\n\t\t\telse if (parameter.rfind(\"upper\", 0) == 0)\n\t\t\t\tformat = UPPER_DISTANCE_MATRIX;\n\t\t\telse if (parameter.rfind(\"dist\", 0) == 0)\n\t\t\t\tformat = DISTANCE_MATRIX;\n\t\t\telse if (parameter.rfind(\"point\", 0) == 0)\n\t\t\t\tformat = POINT_CLOUD;\n\t\t\telse if (parameter == \"dipha\")\n\t\t\t\tformat = DIPHA;\n\t\t\telse if (parameter == \"sparse\")\n\t\t\t\tformat = SPARSE;\n\t\t\telse if (parameter == \"binary\")\n\t\t\t\tformat = BINARY;\n\t\t\telse\n\t\t\t\tprint_usage_and_exit(-1);\n#ifdef USE_COEFFICIENTS\n\t\t} else if (arg == \"--modulus\") {\n\t\t\tstd::string parameter = std::string(argv[++i]);\n\t\t\tsize_t next_pos;\n\t\t\tmodulus = std::stol(parameter, &next_pos);\n\t\t\tif (next_pos != parameter.size() || !is_prime(modulus)) print_usage_and_exit(-1);\n#endif\n#ifndef USING_SERIAL\n\t\t} else if (arg == \"--threads\") {\n\t\t\tstd::string parameter = std::string(argv[++i]);\n\t\t\tsize_t next_pos;\n\t\t\tnum_threads = std::stol(parameter, &next_pos);\n\t\t\tif (next_pos != parameter.size() || !is_prime(modulus)) print_usage_and_exit(-1);\n#endif\n\t\t} else {\n\t\t\tif (filename) { print_usage_and_exit(-1); }\n\t\t\tfilename = argv[i];\n\t\t}\n\t}\n\n#ifdef USE_TBB\n\ttbb::task_scheduler_init init(num_threads);\n#endif\n\n\tstd::ifstream file_stream(filename);\n\tif (filename && file_stream.fail()) {\n\t\tstd::cerr << \"couldn't open file \" << filename << std::endl;\n\t\texit(-1);\n\t}\n\n\tif (format == SPARSE) {\n\t\tsparse_distance_matrix dist =\n\t\t    read_sparse_distance_matrix(filename ? file_stream : std::cin);\n\t\tstd::cout << \"sparse distance matrix with \" << dist.size() << \" points and \"\n\t\t          << dist.num_edges << \"/\" << (dist.size() * (dist.size() - 1)) / 2 << \" entries\"\n\t\t          << std::endl;\n\n\t\tripser<sparse_distance_matrix>(std::move(dist), dim_max, threshold, ratio, modulus, num_threads)\n\t\t    .compute_barcodes();\n\t} else {\n\t\tcompressed_lower_distance_matrix dist =\n\t\t    read_file(filename ? file_stream : std::cin, format);\n\n\t\tvalue_t min = std::numeric_limits<value_t>::infinity(),\n\t\t        max = -std::numeric_limits<value_t>::infinity(), max_finite = max;\n\t\tint num_edges = 0;\n\n\t\tif (threshold == std::numeric_limits<value_t>::max()) {\n\t\t\tvalue_t enclosing_radius = std::numeric_limits<value_t>::infinity();\n\t\t\tfor (size_t i = 0; i < dist.size(); ++i) {\n\t\t\t\tvalue_t r_i = -std::numeric_limits<value_t>::infinity();\n\t\t\t\tfor (size_t j = 0; j < dist.size(); ++j) r_i = std::max(r_i, dist(i, j));\n\t\t\t\tenclosing_radius = std::min(enclosing_radius, r_i);\n\t\t\t}\n\t\t\tthreshold = enclosing_radius;\n\t\t}\n\n\t\tfor (auto d : dist.distances) {\n\t\t\tmin = std::min(min, d);\n\t\t\tmax = std::max(max, d);\n\t\t\tmax_finite =\n\t\t\t    d != std::numeric_limits<value_t>::infinity() ? std::max(max, d) : max_finite;\n\t\t\tif (d <= threshold) ++num_edges;\n\t\t}\n\t\tstd::cout << \"value range: [\" << min << \",\" << max_finite << \"]\" << std::endl;\n\n\t\tif (threshold >= max) {\n\t\t\tstd::cout << \"distance matrix with \" << dist.size() << \" points\" << std::endl;\n\t\t\tripser<compressed_lower_distance_matrix>(std::move(dist), dim_max, threshold, ratio,\n\t\t\t                                         modulus, num_threads)\n\t\t\t    .compute_barcodes();\n\t\t} else {\n\t\t\tstd::cout << \"sparse distance matrix with \" << dist.size() << \" points and \"\n\t\t\t          << num_edges << \"/\" << (dist.size() * dist.size() - 1) / 2 << \" entries\"\n\t\t\t          << std::endl;\n\n\t\t\tripser<sparse_distance_matrix>(sparse_distance_matrix(std::move(dist), threshold),\n\t\t\t                               dim_max, threshold, ratio, modulus, num_threads)\n\t\t\t    .compute_barcodes();\n\t\t}\n\t\texit(0);\n\t}\n}\n", "meta": {"hexsha": "0c82aa4ca6a4f749b26db08a26ca4ac63bf6b2a0", "size": 53326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ripser.cpp", "max_stars_repo_name": "mrzv/ripser", "max_stars_repo_head_hexsha": "625be2cae6f239b3179c40d43234837b213b2185", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-11T11:36:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T18:20:42.000Z", "max_issues_repo_path": "ripser.cpp", "max_issues_repo_name": "mrzv/ripser", "max_issues_repo_head_hexsha": "625be2cae6f239b3179c40d43234837b213b2185", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ripser.cpp", "max_forks_repo_name": "mrzv/ripser", "max_forks_repo_head_hexsha": "625be2cae6f239b3179c40d43234837b213b2185", "max_forks_repo_licenses": ["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.7853881279, "max_line_length": 156, "alphanum_fraction": 0.6829314031, "num_tokens": 14057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817434481176185, "lm_q2_score": 0.020023441362554767, "lm_q1q2_score": 0.003167194718398832}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_StandardParticleSimulationManager_def.hpp\n//! \\author Alex Robinson\n//! \\brief  Standard particle simulation manager definition\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_STANDARD_PARTICLE_SIMULATION_MANAGER_DEF_HPP\n#define MONTE_CARLO_STANDARD_PARTICLE_SIMULATION_MANAGER_DEF_HPP\n\n// Boost Includes\n#include <boost/mpl/find.hpp>\n#include <boost/mpl/deref.hpp>\n#include <boost/mpl/next_prior.hpp>\n#include <boost/mpl/begin_end.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_ParticleModeTypeTraits.hpp\"\n#include \"MonteCarlo_CollisionForcer.hpp\"\n#include \"MonteCarlo_StandardCollisionForcer.hpp\"\n\nnamespace MonteCarlo{\n\nnamespace Details{\n\n// The mode initialization helper class\ntemplate<typename BeginParticleIterator, typename EndParticleIterator>\nstruct ModeInitializationHelper\n{\n  //! Initialize simulate particle functors map\n  template<typename Manager>\n  static inline void initializeSimulateParticleFunctions( Manager& manager )\n  {\n    typedef typename boost::mpl::deref<BeginParticleIterator>::type ParticleStateType;\n\n    manager.template addSimulateParticleFunction<ParticleStateType>();\n\n    ModeInitializationHelper<typename boost::mpl::next<BeginParticleIterator>::type,EndParticleIterator>::initializeSimulateParticleFunctions( manager );\n  }\n};\n\n// End initialization\ntemplate<typename EndParticleIterator>\nstruct ModeInitializationHelper<EndParticleIterator,EndParticleIterator>\n{\n  //! Initialize simulate particle functors map\n  template<typename Manager>\n  static inline void initializeSimulateParticleFunctions( Manager& manager )\n  { /* ... */ }\n};\n\n} // end Details namespace\n\n// Constructor\ntemplate<ParticleModeType mode>\nStandardParticleSimulationManager<mode>::StandardParticleSimulationManager(\n                 const std::string& simulation_name,\n                 const std::string& archive_type,\n                 const std::shared_ptr<const FilledGeometryModel>& model,\n                 const std::shared_ptr<ParticleSource>& source,\n                 const std::shared_ptr<EventHandler>& event_handler,\n                 const std::shared_ptr<const WeightWindow> weight_windows,\n                 const std::shared_ptr<const CollisionForcer> collision_forcer,\n                 const std::shared_ptr<const SimulationProperties>& properties,\n                 const uint64_t next_history,\n                 const uint64_t rendezvous_number,\n                 const bool use_single_rendezvous_file )\n  : ParticleSimulationManager( simulation_name,\n                               archive_type,\n                               model,\n                               source,\n                               event_handler,\n                               weight_windows,\n                               collision_forcer,\n                               properties,\n                               next_history,\n                               rendezvous_number,\n                               use_single_rendezvous_file )\n{\n  Details::ModeInitializationHelper<typename boost::mpl::begin<typename ParticleModeTypeTraits<mode>::ActiveParticles>::type,typename boost::mpl::end<typename ParticleModeTypeTraits<mode>::ActiveParticles>::type>::initializeSimulateParticleFunctions( *this );\n}\n\n// Simulate an unresolved particle\ntemplate<ParticleModeType mode>\nvoid StandardParticleSimulationManager<mode>::simulateUnresolvedParticle(\n                                            ParticleState& unresolved_particle,\n                                            ParticleBank& bank,\n                                            const bool source_particle )\n{\n  SimulateParticleFunctionMap::const_iterator simulation_function_it =\n    d_simulate_particle_function_map.find( unresolved_particle.getParticleType() );\n\n  // Only simulate the particle if there is a simulation function associated\n  // with the type\n  if( simulation_function_it != d_simulate_particle_function_map.end() )\n  {\n    simulation_function_it->second( unresolved_particle, bank, source_particle );\n  }\n  else\n    unresolved_particle.setAsGone();\n}\n\n// Add simulate particle function for particle type\ntemplate<ParticleModeType mode>\ntemplate<typename State>\nvoid StandardParticleSimulationManager<mode>::addSimulateParticleFunction()\n{\n  constexpr const ParticleType particle_type = State::type;\n\n  // Make sure that the state is compatible with the mode\n  testPrecondition( MonteCarlo::isParticleTypeCompatible<mode>( particle_type ) );\n\n  if( this->getCollisionForcer().hasForcedCollisionCells( particle_type ) )\n  {\n    d_simulate_particle_function_map[particle_type] =\n      std::bind<void>( &ParticleSimulationManager::simulateParticleAlternative<State>,\n                       std::ref( *this ),\n                       std::placeholders::_1,\n                       std::placeholders::_2,\n                       std::placeholders::_3 );\n  }\n  else\n  {\n    d_simulate_particle_function_map[particle_type] =\n      std::bind<void>( &ParticleSimulationManager::simulateParticle<State>,\n                       std::ref( *this ),\n                       std::placeholders::_1,\n                       std::placeholders::_2,\n                       std::placeholders::_3 );\n  }\n}\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_STANDARD_PARTICLE_SIMULATION_MANAGER_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_StandardParticleSimulationManager_def.hpp\n//---------------------------------------------------------------------------//\n\n", "meta": {"hexsha": "dc539e0cee41cdf1f2d85aafcbc374170391d1c4", "size": 5640, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/manager/src/MonteCarlo_StandardParticleSimulationManager_def.hpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "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/manager/src/MonteCarlo_StandardParticleSimulationManager_def.hpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/manager/src/MonteCarlo_StandardParticleSimulationManager_def.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-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.7183098592, "max_line_length": 259, "alphanum_fraction": 0.6462765957, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414886038616345, "lm_q2_score": 0.02194825423466667, "lm_q1q2_score": 0.0031638158353929865}}
{"text": "/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n\n/*! \n * \\file calibrate_share_weight_visitor.cpp\n * \\ingroup Objects\n * \\brief The CalibrateShareWeightVisitor class source file.\n * \\author Pralit Patel\n */\n\n#include \"util/base/include/definitions.h\"\n#include <cassert>\n#include <boost/math/tr1.hpp>\n\n#include \"util/base/include/calibrate_share_weight_visitor.h\"\n#include \"technologies/include/technology_container.h\"\n#include \"technologies/include/itechnology.h\"\n#include \"sectors/include/subsector.h\"\n#include \"sectors/include/sector.h\"\n#include \"containers/include/gdp.h\"\n#include \"util/logger/include/ilogger.h\"\n#include \"functions/include/idiscrete_choice.hpp\"\n\nusing namespace std;\n\nextern Scenario* scenario;\n\n/*!\n * \\brief Constructor\n * \\param aRegionName Name of the region if starting the visiting below the\n *        region level.\n */\nCalibrateShareWeightVisitor::CalibrateShareWeightVisitor( const string& aRegionName, const GDP* aGDP )\n:mCurrentRegionName( aRegionName ), mGDP( aGDP )\n{\n}\n\nvoid CalibrateShareWeightVisitor::startVisitSector( const Sector* aSector, const int aPeriod ) {\n    mCurrentSectorName = aSector->getName();\n}\n\nvoid CalibrateShareWeightVisitor::endVisitSector( const Sector* aSector, const int aPeriod ) {\n    // Doing subsector calibration in sector rather than in subsector because we will need access \n    // to all of the subsectors at the same time.  Also we need to do this in end visit sector\n    // because the subsector can't be calculated until we have gotten the correct share weights\n    // for the technologies.\n\n    // Find out if we need to do calibration, make sure we do not have a mix of calibrated/non-calibrated\n    // subsectors, and figure out the largest subsector to make the other subsectors anchored by it.\n    int anchorIndex = -1;\n    bool hasCalValues = false;\n    double maxCalValue = 0;\n    int numCalSubsectors = 0;\n    double totalCalValue = 0;\n    for( int subsectorIndex = 0; subsectorIndex < aSector->mSubsectors.size(); ++subsectorIndex ) {\n        double currCalValue = aSector->mSubsectors[ subsectorIndex ]->getTotalCalOutputs( aPeriod );\n        bool isAllFixed = aSector->mSubsectors[ subsectorIndex ]->containsOnlyFixedOutputTechnologies( aPeriod )\n            || aSector->mSubsectors[ subsectorIndex ]->mShareWeights[ aPeriod ] == 0;\n\n        // check if the subsector is calibrated\n        if( hasCalValues && currCalValue == 0 && !isAllFixed ) {\n            // warn that we mixed calibrated and variable technologies\n            ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n            ILogger& calibrationLog = ILogger::getLogger( \"calibration_log\" );\n            mainLog.setLevel( ILogger::WARNING );\n            calibrationLog.setLevel( ILogger::WARNING );\n            mainLog << \"Mixed calibrated and variable subsectors or read a zero calibration value in Region: \"\n                << mCurrentRegionName << \" in sector: \" << mCurrentSectorName\n                << \" for Subsector: \" << aSector->mSubsectors[ subsectorIndex ]->getName() << endl;\n            calibrationLog << \"Mixed calibrated and variable subsectors or read a zero calibration value in Region: \"\n                << mCurrentRegionName << \" in sector: \" << mCurrentSectorName\n                << \" for Subsector: \" << aSector->mSubsectors[ subsectorIndex ]->getName() << endl;\n        }\n        else if( currCalValue > 0 ) {\n            hasCalValues = true;\n        }\n\n        // If the calibrated value > 0 then increase the number of subsectors to calibrate\n        // and include it in the total sum.\n        if( currCalValue > 0 ) {\n            ++numCalSubsectors;\n            totalCalValue += currCalValue;\n        }\n\n        // attempt to locate the largest subsector\n        if( currCalValue > maxCalValue ) {\n            maxCalValue = currCalValue;\n            anchorIndex = subsectorIndex;\n        }\n    }\n\n    // If we are using the abosolute choice function, then we need to\n    // set the base cost for the model.  We will calculate an appropriate\n    // base cost and let the discrete choice function use it if it needs it.\n\n    // The base cost is equal to the highest cost subsector that has a share if we\n    // have calibration data.  Otherwise, it is equal to the highest cost subsector\n    // that has a valid cost; otherwise, we may be in trouble if a user did not\n    // parse a value.\n    double baseCost = 0;\n    for( int subsectorIndex = 0; subsectorIndex < aSector->mSubsectors.size(); ++subsectorIndex ) {\n        double currCost = aSector->mSubsectors[ subsectorIndex ]->getPrice( mGDP, aPeriod );\n        if( !boost::math::isnan( currCost )  && currCost > baseCost &&\n            ( ( hasCalValues && aSector->mSubsectors[ subsectorIndex ]->getTotalCalOutputs( aPeriod ) > 0 ) || !hasCalValues ) )\n        {\n            baseCost = currCost;\n        }\n    }\n    // In the case where there is only one subsector we will reset the base-price\n    // to one as the sharing should not matter.\n    if( baseCost == 0 && aSector->mSubsectors.size() == 1 ) {\n        baseCost = 1;\n    }\n    // baseCost may still be zero and if a user did not parse a base cost an error\n    // will be generated.\n    aSector->mDiscreteChoiceModel->setBaseValue( baseCost );\n\n    // do calibration if we have cal values and there are more than one subsector in this nest\n    if( hasCalValues && numCalSubsectors > 1 ) {\t\n        // we should have found a subsector to have share weights anchored\n        assert( anchorIndex != -1 );\n        const double scaledGdpPerCapita = mGDP->getBestScaledGDPperCap( aPeriod );\n        const double anchorPrice = aSector->mSubsectors[ anchorIndex ]->getPrice( mGDP, aPeriod );\n        const double anchorShare = ( aSector->mSubsectors[ anchorIndex ]->getTotalCalOutputs( aPeriod )\n            / totalCalValue ) / pow( scaledGdpPerCapita, aSector->mSubsectors[ anchorIndex ]->mFuelPrefElasticity[ aPeriod ] );\n        assert( anchorShare > 0 );\n        \n        for( int subsectorIndex = 0; subsectorIndex < aSector->mSubsectors.size(); ++subsectorIndex ) {\n            Subsector* currSubsector = aSector->mSubsectors[ subsectorIndex ];\n            double currShare = ( currSubsector->getTotalCalOutputs( aPeriod ) / totalCalValue )\n                / pow( scaledGdpPerCapita, currSubsector->mFuelPrefElasticity[ aPeriod ] );\n\n            // only set the share weight for valid subsectors\n            if( currShare > 0 ) {\n                double currPrice = currSubsector->getPrice( mGDP, aPeriod );\n\n                double currShareWeight = aSector->mDiscreteChoiceModel->calcShareWeight( currShare, currPrice,\n                     anchorShare, anchorPrice, aPeriod );\n                currSubsector->mShareWeights[ aPeriod ] = currShareWeight; \n            }\n        }\n    }\n\n    mCurrentSectorName.clear();\n}\n\nvoid CalibrateShareWeightVisitor::startVisitSubsector( const Subsector* aSubsector, const int aPeriod ) {\n    // Doing technology calibration in subsector rather than in technology because we will need access \n    // to all of the technologies at the same time.\n\n    // First we need to make sure that the technologies have calculated their costs.\n    // We will also find the largest technology in terms of output so that we can anchor the share weights\n    // by that technology and we will also make sure that we do not have a inconsistent set of\n    // technologies with and without calibration values.\n    const bool hasRequired = false;\n    const string requiredName = \"\";\n    int anchorTechIndex = -1;\n    bool hasCalValues = false;\n    double maxCalValue = -1;\n    int numlCalTechs = 0;\n    double totalCalValue = 0;\n    for( int techIndex = 0; techIndex < aSubsector->mTechContainers.size(); ++techIndex ) {\n        ITechnology* currTech = aSubsector->mTechContainers[ techIndex ]->getNewVintageTechnology( aPeriod );\n        // call calc cost to make sure they are up to date\n        currTech->calcCost( mCurrentRegionName, mCurrentSectorName, aPeriod );\n\n        double currCalValue = currTech->getCalibrationOutput( hasRequired, requiredName, aPeriod );\n        bool isAvailable = currTech->isAvailable( aPeriod );\n\n        // check if we have calibrated technologies\n        if( hasCalValues && currCalValue == -1 && isAvailable ) {\n            // log that we have inconsistent calibrated and variable technologies\n            ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n            mainLog.setLevel( ILogger::WARNING );\n            ILogger& calibrationLog = ILogger::getLogger( \"calibration_log\" );\n            calibrationLog.setLevel( ILogger::WARNING );\n            mainLog << \"Mixed calibrated and variable subsectors in Region: \" << mCurrentRegionName\n                << \" in sector: \" << mCurrentSectorName\n                << \" for technology: \" << currTech->getName()  << endl;\n            calibrationLog << \"Mixed calibrated and variable subsectors in Region: \" << mCurrentRegionName\n                << \" in sector: \" << mCurrentSectorName\n                << \" for technology: \" << currTech->getName()  << endl;\n        }\n        else if( isAvailable && currCalValue != -1 ) {\n            hasCalValues = true;\n        }\n\n        // If the calibrated value > 0 then increase the number of technologies to calibrate\n        // and include it in the total sum.\n        if( currCalValue > 0 ) {\n            ++numlCalTechs;\n            totalCalValue += currCalValue;\n        }\n\n        // attempt to locate the largest technology\n        if( currCalValue > maxCalValue ) {\n            maxCalValue = currCalValue;\n            anchorTechIndex = techIndex;\n        }\n    }\n\n    // The base cost is equal to the highest cost subsector that has a share if we\n    // have calibration data.  Otherwise, it is equal to the highest cost subsector\n    // that has a valid cost; otherwise, we may be in trouble if a user did not\n    // parse a value.\n    double baseCost = 0;\n    for( int techIndex = 0; techIndex < aSubsector->mTechContainers.size(); ++techIndex ) {\n        double currCost = aSubsector->mTechContainers[ techIndex ]->getNewVintageTechnology( aPeriod )\n            ->getCost( aPeriod );\n        double calValue = aSubsector->mTechContainers[ techIndex ]->getNewVintageTechnology( aPeriod )->getCalibrationOutput( hasRequired, requiredName, aPeriod );\n        if( !boost::math::isnan( currCost ) && currCost > baseCost && ( ( hasCalValues && calValue > 0 ) || !hasCalValues ) ) {\n            baseCost = currCost;\n        }\n    }\n    // In the case where there is only one subsector we will reset the base-price\n    // to one as the sharing should not matter.\n    if( baseCost == 0 && aSubsector->mTechContainers.size() == 1 ) {\n        baseCost = 1;\n    }\n    // baseCost may still be zero and if a user did not parse a base cost an error\n    // will be generated.  \n    aSubsector->mDiscreteChoiceModel->setBaseValue( baseCost );\n\n    // do calibration if we have cal values and there are more than one technologies in this nest\n    if( hasCalValues && numlCalTechs > 1 ) {\n        // we should have found a technology to have share weights anchored by\n        assert( anchorTechIndex != -1 );\n        const ITechnology* anchorTech = aSubsector->mTechContainers[ anchorTechIndex ]->getNewVintageTechnology( aPeriod );\n        const double scaledGdpPerCapita = mGDP->getBestScaledGDPperCap( aPeriod );\n        const double anchorPrice = anchorTech->getCost( aPeriod );\n        const double anchorShare = ( anchorTech->getCalibrationOutput( hasRequired, requiredName, aPeriod )\n            / totalCalValue ) / pow( scaledGdpPerCapita, anchorTech->calcFuelPrefElasticity( aPeriod ) );\n        \n        for( int techIndex = 0; techIndex < aSubsector->mTechContainers.size(); ++techIndex ) {\n            ITechnology* currTech = aSubsector->mTechContainers[ techIndex ]->getNewVintageTechnology( aPeriod );\n            double currShare = ( currTech->getCalibrationOutput( hasRequired, requiredName, aPeriod ) / totalCalValue )\n                / pow( scaledGdpPerCapita, currTech->calcFuelPrefElasticity( aPeriod ) );\n\n            // only set share weights for valid technologies\n            if( currShare > 0 ) {\n                double currPrice = currTech->getCost( aPeriod );\n                double currShareWeight = aSubsector->mDiscreteChoiceModel->calcShareWeight( currShare, currPrice,\n                    anchorShare, anchorPrice, aPeriod );\n                currTech->setShareWeight( currShareWeight ); \n            }\n        }\n    }\n}\n", "meta": {"hexsha": "d7a3b8aae1474e308ccf51334aac27878884081f", "size": 14047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp", "max_stars_repo_name": "Silviameteoro/GCAM-LAC", "max_stars_repo_head_hexsha": "a93912f91530ea741712c77b3545400725429730", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-28T04:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T04:10:11.000Z", "max_issues_repo_path": "cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp", "max_issues_repo_name": "Silviameteoro/GCAM-LAC", "max_issues_repo_head_hexsha": "a93912f91530ea741712c77b3545400725429730", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cvs/objects/util/base/source/calibrate_share_weight_visitor.cpp", "max_forks_repo_name": "Silviameteoro/GCAM-LAC", "max_forks_repo_head_hexsha": "a93912f91530ea741712c77b3545400725429730", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-26T05:56:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T10:29:30.000Z", "avg_line_length": 50.3476702509, "max_line_length": 163, "alphanum_fraction": 0.6765857478, "num_tokens": 3374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436781101874467, "lm_q2_score": 0.015906394977364253, "lm_q1q2_score": 0.0030916911729498447}}
{"text": "#include <ros/package.h>\n#include <signal.h>\n#include <boost/filesystem.hpp>\n#include <chrono>\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <ctime>\n#include <ratio>\n#include \"kacanopen/core/canopen_error.h\"\n#include \"kacanopen/core/core.h\"\n#include \"kacanopen/core/logger.h\"\n#include \"kacanopen/master/device.h\"\n#include \"kacanopen/master/master.h\"\n#include \"kacanopen/tools/device_rpdo.h\"\n#include \"kacanopen/tools/device_tpdo.h\"\n#include \"kacanopen/core/logger.h\"\n#include \"kacanopen/ros_bridge/bridge.h\"\n#include \"kacanopen/ros_bridge/entry_publisher.h\"\n#include \"kacanopen/ros_bridge/entry_subscriber.h\"\n#include \"kacanopen/ros_bridge/joint_state_publisher.h\"\n#include \"kacanopen/ros_bridge/joint_state_subscriber.h\"\n\n#include \"hexa_package/drivesFeedBack.h\"\n#include \"hexa_package/drivesAction.h\"\n#include \"hexa_package/sensor.h\"\n#include \"hexa_package/setting.h\"\n\n#include <chrono>\n#include <memory>\n#include <thread>\n#include <string>\n\n\n\n/* For setting the process's priority (setpriority) */\n#include <sys/resource.h>\n/* For pid_t and getpid() */\n#include <unistd.h>\n#include <sys/types.h>\n/* For locking the program in RAM (mlockall) to prevent swapping */\n#include <sys/mman.h>\n/* clock_gettime, struct timespec, etc. */\n#include <time.h>\n\n\nusing namespace std;\n\nvoid control();\n\nstatic volatile int keepRunning = 1;\n\nvoid intHandler(int dummy) {\n    (void) dummy;\n    keepRunning = 0;\n\n    printf(\"trying to stop process %d\\n\", getpid());\n    std::this_thread::sleep_for(std::chrono::microseconds(1000));\n    /*do something*/\n    printf(\"killing process %d\\n\", getpid());\n    ros::shutdown();\n\n    //TODO check device available and then set current\n    // Currentleft = 0;\n    // Currentright = 0;\n    // device_1->set_entry(\"current_mode_setting_value\", Currentleft, kaco::WriteAccessMethod::pdo);\n    // device->set_entry(\"current_mode_setting_value\", Currentright, kaco::WriteAccessMethod::pdo);\n\n    exit(0);\n}\n\nbool printDeviceInfo(std::shared_ptr <kaco::Device> device) {\n    try {\n        std::string display_device_type;\n        auto device_type =\n                device->get_entry(0x1000, 0x0, kaco::ReadAccessMethod::sdo);\n        if (131474 == static_cast<uint32_t>(device_type))\n            display_device_type = \"DS402\";  // 131474 is the type number for DS-402;\n        auto device_name =\n                device->get_entry(0x1008, 0x0, kaco::ReadAccessMethod::sdo);\n        auto vendor_id =\n                device->get_entry(0x1018, 0x01, kaco::ReadAccessMethod::sdo);\n        auto product_id =\n                device->get_entry(0x1018, 0x02, kaco::ReadAccessMethod::sdo);\n        auto revision =\n                device->get_entry(0x1018, 0x03, kaco::ReadAccessMethod::sdo);\n\n        auto serial_no =\n                device->get_entry(0x1018, 0x04, kaco::ReadAccessMethod::sdo);\n\n        std::cout << \"\" << std::endl;\n        std::cout << \"\" << std::endl;\n        std::cout << \"*************************************************************\"\n                  << std::endl;\n        std::cout << \"*************************************************************\"\n                  << std::endl;\n        std::cout << \"* Device Name found as '\" << device_name << \"'\" << std::endl;\n        std::cout << \"* Device Type found as CiA-\" << display_device_type << \"'\"\n                  << std::endl;\n        std::cout << \"* Vendor ID=\" << vendor_id << std::endl;\n        std::cout << \"* Product ID=\" << product_id << std::endl;\n        std::cout << \"* Serial Number=\" << serial_no << std::endl;\n        std::cout << \"* Revision Number=\" << revision << std::endl;\n        std::cout << \"*************************************************************\"\n                  << std::endl;\n        std::cout << \"*************************************************************\"\n                  << std::endl;\n        std::cout << \"\" << std::endl;\n        std::cout << \"\" << std::endl;\n        return true;\n    } catch (...) {\n        std::cout << \"Exception occured while acquiring device information.!\"\n                  << std::endl;\n        return false;\n    }\n}\n\nvoid initializeDevice(std::shared_ptr <kaco::Device> device,\n                      uint16_t heartbeat_interval, uint8_t node_id) {\n    // set the our desired heartbeat_interval time\n    device->set_entry(0x1017, 0x0, heartbeat_interval,\n                      kaco::WriteAccessMethod::sdo);\n\n\n    // Mater side Periodic Tranmit pdo1 value initialization\n    device->set_entry(\"current_mode_setting_value\", static_cast<int16_t>(0x0), kaco::WriteAccessMethod::sdo);\n\n    device->set_entry(\"controlword\", static_cast<uint16_t>(0x0006),\n                      kaco::WriteAccessMethod::sdo);\n\n    // Master side tpdo1 mapping\n    device->add_transmit_pdo_mapping(\n            0x200 + node_id, {{\"current_mode_setting_value\", 0},\n                              {\"controlword\",                2}},\n            kaco::TransmissionType::ON_CHANGE,\n            std::chrono::milliseconds(5)); //kaco::TransmissionType::PERIODIC - ON_CHANGE\n\n    // Master side RPDO mapping starts here; This must be in line with device\n    // side TPDOs\n\n    // Master side rpdo1 mapping\n\n    device->add_receive_pdo_mapping(0x180 + node_id, \"position_actual_value\",\n                                    0);                                 // 32bit\n\n    device->add_receive_pdo_mapping(0x180 + node_id, \"statusword\", 4);  // 16bit\n\n    device->add_receive_pdo_mapping(0x180 + node_id, \"current_actual_value\",\n                                    6);                                 // 16bit\n\n    // Master side RPDO mapping ends here\n\n    /***************** TPDO MAPPING in DEVICE *****************/\n    /// Device side TPDO mapping starts here. This must be in line with the\n    /// master side RPDOs.\n\n    // Device side tpdo1 mapping entries and mapping\n    std::vector <uint32_t> tpdo1_entries_to_be_mapped = {0x60640020, 0x60410010, 0x60780010};\n\n    map_tpdo_in_device(TPDO_1, tpdo1_entries_to_be_mapped, 255, device);\n\n\n    // Device side tpdo2 mapping entries and mapping\n    std::vector <uint32_t> tpdo2_entries_to_be_mapped = {0x60640020, 0x60410010, 0x60780010};\n\n    map_tpdo_in_device(TPDO_2, tpdo2_entries_to_be_mapped, 255, device);\n\n    /// Device side TPDO mapping ends here;\n\n\n    /***************** RPDO MAPPING in DEVICE *****************/\n    /// Device side RPDO mapping starts here.This must be in line with the\n    /// master side TPDOs.\n    std::vector <uint32_t> rpdo1_entries_to_be_mapped = {\n            0x20300010, 0x60400010,\n    };\n    map_rpdo_in_device(RPDO_1, rpdo1_entries_to_be_mapped, 255, device);\n    /// Device side RPDO mapping ends here\n\n    // Try to clear all possible errors in the CANOpen device\n    device->set_entry(\"controlword\", static_cast<uint16_t>(0x0080),\n                      kaco::WriteAccessMethod::sdo);\n\n}\n\n\nusing namespace std::chrono;\n\n// Create device pointer\nstd::shared_ptr <kaco::Device> device;\nstd::shared_ptr <kaco::Device> device_1;\n\n\nvolatile bool found_node = false;\nvolatile bool device_connected = false;\nstd::mutex device_mutex;\nvolatile bool found_node_1 = false;\nvolatile bool device_connected_1 = false;\nstd::mutex device_mutex_1;\n\n\nbool messageRecievedFromController = false;\n\nhigh_resolution_clock::time_point lastTime = high_resolution_clock::now();\n\n\n\n// void chatterCallback0(const std_msgs::Int16::ConstPtr& msg){\n//   duration<double, std::milli> time_take_to_this = high_resolution_clock::now() - lastTime;\n//   double currentTime = time_take_to_this.count() ;\n//   lastTime = high_resolution_clock::now();\n//   messageRecievedFromController = true;\n//   if((device_connected){\n//     cout << msg->data << \"\\t\" << currentTime << \"\\n\" ;\n//     device->set_entry(\"current_mode_setting_value\", msg->data,\n//                             kaco::WriteAccessMethod::pdo);\n//     // device->set_entry(\"controlword\", static_cast<uint16_t>(0x000F),\n//     //                         kaco::WriteAccessMethod::pdo);\n//   }\n// }\n\n// void chatterCallback1(const std_msgs::Int16::ConstPtr& msg){\n//   messageRecievedFromController = true;\n//   if((device_connected_1){\n//     device_1->set_entry(\"current_mode_setting_value\", msg->data,\n//                             kaco::WriteAccessMethod::pdo);\n//   }\n// }\n\n\n\n\n// void actionSubscriberCallback(const hexa_package::drivesAction::ConstPtr& msg){\n//   duration<double, std::milli> time_take_to_this = high_resolution_clock::now() - lastTime;\n//   double currentTime = time_take_to_this.count() ;\n//   lastTime = high_resolution_clock::now();\n//   messageRecievedFromController = true;\n//   if((currentTime > 6 || currentTime < 1)\n//   cout << currentTime << \"\\n\" ;\n//   if((device_connected && device_connected_1) {\n//     // cout << msg->current0;\n//     device->set_entry(\"current_mode_setting_value\", msg->current0, kaco::WriteAccessMethod::pdo);\n//     device_1->set_entry(\"current_mode_setting_value\", msg->current1, kaco::WriteAccessMethod::pdo);\n//   }\n\n// }\n\n\n#define MAX_SAFE_STACK (8 * 1024)\n\nvoid stack_prefault(void) {\n    unsigned char dummy[MAX_SAFE_STACK];\n    memset(dummy, 0, MAX_SAFE_STACK);\n}\n\nint16_t Currentleft = 0;\nint16_t Currentright = 0;\nint32_t LoadcellRightHip = 0;\nint32_t LoadcellLeftHip = 0;\n\nint16_t actual_curr_0 = 0;\nint16_t actual_curr_1 = 0;\nint32_t actual_position_0 = 0;\nint32_t actual_position_1 = 0;\nint32_t P_RH = 50;//30;\nint32_t P_LH = 50;//30;\nlong double Force_RH = 0;\nlong double Force_LH = 0;\nint32_t timer_right = 100;\nint32_t timer_left = 100;\nint32_t Assist_Right = 2000;\nint32_t Assist_Left = 2000;\nint32_t delay_time = 0;\nint32_t Assist_Delay = 0;\nstring control_algorithm = \"assist_as_needed\";\nstring control_algorithm_right = \"zero_impedance\";\nstring control_algorithm_left = \"zero_impedance\";\n\nvoid getSensorData(const hexa_package::sensor::ConstPtr &msg) {\n    //cout  << endl << msg->loadcell1 << endl;\n\n    duration<double, std::milli> time_take_to_this = high_resolution_clock::now() - lastTime;\n    double currentTime = time_take_to_this.count();\n    lastTime = high_resolution_clock::now();\n    //Todo print time for debug\n    // cout << currentTime << \"\\n\" ;\n    LoadcellRightHip = msg->loadcell1;\n    LoadcellLeftHip = msg->loadcell0;\n}\n\n\nvoid getSettingData(const hexa_package::setting::ConstPtr &msg) {\n\n    control_algorithm = msg->assist_algorithm;\n    control_algorithm_right = msg->right_leg_algorithm;\n    control_algorithm_left = msg->left_leg_algorithm;\n    Assist_Right = msg->right_assistive_force * 30;\n    Assist_Left = msg->left_assistive_force * 30;\n    timer_right = msg->right_assistive_time;\n    timer_left = msg->left_assistive_time;\n\n    // In time based assist always one of the legs is zero impedance mode\n    if (control_algorithm == \"time_based_assist\") {\n        if (control_algorithm_left == \"assist_as_needed\") {\n            delay_time = msg->assist_delay_left;\n            Assist_Delay = msg->left_assistive_force * 30;\n        }\n        if (control_algorithm_right == \"assist_as_needed\") {\n            delay_time = msg->assist_delay_right;\n            Assist_Delay = msg->right_assistive_force * 30;\n        }\n    }\n    cout << \"GUI Settings\" << endl << msg->assist_algorithm << endl << msg->left_leg_algorithm << endl\n         << msg->right_leg_algorithm << endl << Assist_Right << endl << Assist_Left\n         << endl << timer_right << endl << timer_left << endl << delay_time << endl;\n\n}\n\n\nint main(int argc, char *argv[]) {\n\n\n    cpu_set_t set;\n    //CPU_ZERO(&set);\n    //CPU_SET(3, &set);\n\n    //if (sched_setaffinity(0, sizeof(set), &set))\n    //{\n    //       printf(\"Setting CPU affinity failed!\\n\");\n    //      return -1;\n    //}\n    struct sched_param param = {};\n    param.sched_priority = sched_get_priority_max(SCHED_FIFO);\n    printf(\"Using priority %i.\\n\", param.sched_priority);\n    if (sched_setscheduler(0, SCHED_FIFO, &param) == -1) {\n        perror(\"sched_setscheduler failed\\n\");\n    }\n\n    if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {\n        printf(\"mlockall failed\\n\");\n        return -1;\n    }\n\n    stack_prefault();\n\n\n\n\n\n    // Create bridge\n    ros::init(argc, argv, \"hexa_node4\");\n    kaco::Bridge bridge;\n    ros::NodeHandle n;\n\n    //ros::AsyncSpinner spinner(4); // Use 2 threads\n    //spinner.start();\n    //ros::waitForShutdown();\n\n    ros::Rate loop_rate(200);\n\n\n\n\n    // Signal handleing\n    signal(SIGINT, intHandler);\n\n    // Define Publisher\n    // ros::Publisher chatter_pub0 = n.advertise<std_msgs::Int16>(\"actualCurrent0\", 1000);\n    // ros::Publisher chatter_pub1 = n.advertise<std_msgs::Int16>(\"actualCurrent1\", 1000);\n    // ros::Publisher postion_message_publisher_0 = n.advertise<std_msgs::Int32>(\"actualPosition0\", 1000);\n    // ros::Publisher postion_message_publisher_1 = n.advertise<std_msgs::Int32>(\"actualPosition1\", 1000);\n    ros::Publisher drivesFeedBack_publisher = n.advertise<hexa_package::drivesFeedBack>(\"drivesFeedBack\", 10000);\n\n    // ----------- //\n    // Preferences //\n    // ----------- //\n\n    // The node ID of the slave we want to communicate with.\n    const uint8_t node_id_0 = 7;\n    const uint8_t node_id_1 = 1;\n\n    const std::string busname = \"can0\";\n\n    const std::string baudrate = \"1M\";\n\n    const uint16_t heartbeat_interval = 1000;\n\n    // Set the heartbeat time out, after which the system should detect slave\n    // disconnection; values can be \"250\", \"500\", \"1000\" and \"2000\" millisecond.\n    // Temporary disabled the timeout parameters; A gloabl 2 second time is now\n    // used in device_alive and device_dead callback\n    // const uint16_t heartbeat_timeout = heartbeat_interval * 3;\n\n    // -------------- //\n    // Initialization //\n    // -------------- //\n\n    // Create core.\n    kaco::Core core;\n\n\n    std::cout << \"Starting Core (connect to the driver and start the receiver \"\n                 \"thread)...Hi\"\n              << std::endl;\n    if (!core.start(busname, baudrate)) {\n        std::cout << \"Starting core failed.\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    // This will be set to true by the callback below.\n\n    std::cout << \"Registering a callback which is called when a device is \"\n                 \"detected via NMT...\"\n              << std::endl;\n    // make sure that the node is reset and goes back to NMT preoperational\n    core.nmt.send_nmt_message(node_id_0, kaco::NMT::Command::reset_node);\n    core.nmt.send_nmt_message(node_id_1, kaco::NMT::Command::reset_node);\n    core.nmt.register_device_alive_callback([&](const uint8_t new_node_id) {\n//        cout << \"node found \\n\";\n        // Check if this is the node we are looking for.\n        if (new_node_id == node_id_0) {\n            // lock\n            if (!found_node) {\n                found_node = true;\n                // Lock device mutex\n                //TODO check why?\n                std::lock_guard <std::mutex> lock(device_mutex);\n                try {\n                    // Initialize the device\n                    device.reset(new kaco::Device(core, node_id_0));\n                    std::string path = ros::package::getPath(\"kacanopen\");\n\n                    boost::filesystem::path full_path = \"/home/pi/hexa_workspace/src/hexa_package/edsFiles/epos2_347717.eds\";\n\n                    device->load_dictionary_from_eds(full_path.string());\n                    //std::cout << \"Printing Device Object Dictionary\" << std::endl;\n                    //device->print_dictionary(); // this print all eds dictionary\n                    core.nmt.send_nmt_message(node_id_0,\n                                              kaco::NMT::Command::enter_preoperational);\n\n                    initializeDevice(device, heartbeat_interval, node_id_0);\n                    int8_t set_mode_of_operation = -3;\n\n                    std::this_thread::sleep_for(std::chrono::microseconds(5000));\n\n\n                    device->set_entry(0x6060, 0x00, set_mode_of_operation,\n                                      kaco::WriteAccessMethod::sdo);\n\n                    device->start();\n                    //printDeviceInfo(device);\n                    device_connected = true;\n\n                } catch (const std::exception &exc) {\n                    std::cout << \"Exception in device alive!\" << std::endl;\n                    std::cerr << exc.what();\n                    found_node = false;\n                    device_connected = false;\n                }\n            }\n        }\n        if (new_node_id == node_id_1) {\n            // lock\n            if (!found_node_1) {\n                found_node_1 = true;\n                // Lock device mutex\n                std::lock_guard <std::mutex> lock(device_mutex_1);\n                try {\n                    // Initialize the device\n                    device_1.reset(new kaco::Device(core, node_id_1));\n                    std::string path = ros::package::getPath(\"kacanopen\");\n\n                    boost::filesystem::path full_path = \"/home/pi/hexa_workspace/src/hexa_package/edsFiles/epos2_347717.eds\";\n\n                    device_1->load_dictionary_from_eds(full_path.string());\n                    core.nmt.send_nmt_message(node_id_1,\n                                              kaco::NMT::Command::enter_preoperational);\n\n                    initializeDevice(device_1, heartbeat_interval, node_id_1);\n\n                    int8_t set_mode_of_operation = -3;\n\n                    std::this_thread::sleep_for(std::chrono::microseconds(5000));\n\n                    device_1->set_entry(0x6060, 0x00, set_mode_of_operation,\n                                        kaco::WriteAccessMethod::sdo);\n\n                    device_1->start();\n                    //printDeviceInfo(device_1);\n                    device_connected_1 = true;\n\n                } catch (const std::exception &exc) {\n                    std::cout << \"Exception in device alive!\" << std::endl;\n                    std::cerr << exc.what();\n                    found_node_1 = false;\n                    device_connected_1 = false;\n                }\n            }\n        }\n    });\n\n\n    int loopCounter = 0;\n    high_resolution_clock::time_point lastTime = high_resolution_clock::now();\n\n    high_resolution_clock::time_point startprogramm = high_resolution_clock::now();\n\n\n    std::cout << \"start subscring .. .. . .\" << endl;\n    ros::Subscriber loadCell1Sub = n.subscribe(\"sensor\", 1000, getSensorData);\n    ros::Subscriber settingsSub = n.subscribe(\"setting\", 1000, getSettingData);\n\n    // Define a lamda expression\n    auto f = []() {\n        ros::spin();\n        //or\n        //ros::spinOnce();\n        //std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n\n    };\n\n// Pass f and its parameters to thread\n// object constructor as\n    std::thread thread_object(f);\n\n\n    while (!(device_connected && device_connected_1)) {\n        cout << \"waiting for drives\\n\";\n        std::this_thread::sleep_for(std::chrono::milliseconds(2000));\n    }\n\n\n    //waite for sensor data\n\n    while (!(LoadcellRightHip != 0 && LoadcellLeftHip != 0)) {\n        cout << \"waiting for sensor data\\n\";\n        std::this_thread::sleep_for(std::chrono::milliseconds(2000));\n    }\n\n\n\n    //ros::Subscriber actionSubscriber = n.subscribe(\"drivesAction\", 1000, actionSubscriberCallback);\n\n\n    device->set_entry(\"controlword\", static_cast<uint16_t>(0x000F),\n                      kaco::WriteAccessMethod::pdo);\n\n    device_1->set_entry(\"controlword\", static_cast<uint16_t>(0x000F),\n                        kaco::WriteAccessMethod::pdo);\n\n    cout << \"\\noperational\\n\";\n    while (keepRunning) {\n        high_resolution_clock::time_point startloop = high_resolution_clock::now();\n        if (device_connected && device_connected_1) {\n\n            // Lock device mutex\n            //todo check why?\n            std::lock_guard <std::mutex> lock(device_mutex);\n\n            try {\n\n                // duration<double, std::milli> time_take_to_this = high_resolution_clock::now() - startprogramm;\n                // double currentTime = time_take_to_this.count() ;\n                actual_curr_0 =\n                        device->get_entry(\"current_actual_value\",\n                                          kaco::ReadAccessMethod::cache);\n                //pdo_request_and_wait\n                actual_curr_1 =\n                        device_1->get_entry(\"current_actual_value\",\n                                            kaco::ReadAccessMethod::cache);\n\n                actual_position_0 =\n                        device->get_entry(\"position_actual_value\",\n                                          kaco::ReadAccessMethod::cache);\n\n                actual_position_1 =\n                        device_1->get_entry(\"position_actual_value\",\n                                            kaco::ReadAccessMethod::cache);\n\n                //cout << actual_curr_0 << \" \" << actual_curr_1 << \"\\n\";\n                //cout << actual_position_0 << \" \" << actual_position_1 << \"\\n\";\n                duration<double, std::milli> time_span = high_resolution_clock::now() - lastTime;\n\n                lastTime = high_resolution_clock::now();\n\n                // device_1->set_entry(\"current_mode_setting_value\", static_cast<int16_t>(1000),\n                //                   kaco::WriteAccessMethod::pdo);\n\n                // device_1->set_entry(\"current_mode_setting_value\", desiredCurrent,\n                //                   kaco::WriteAccessMethod::pdo);\n\n                // device_1->set_entry(\"current_mode_setting_value\", static_cast<int16_t>(1000),\n                //                   kaco::WriteAccessMethod::pdo);\n\n                // device->set_entry(\"controlword\", static_cast<uint16_t>(0x000F),\n                //                   kaco::WriteAccessMethod::pdo);\n\n                // device_1->set_entry(\"controlword\", static_cast<uint16_t>(0x000F),\n                //                   kaco::WriteAccessMethod::pdo);\n\n                loopCounter = loopCounter + 1;\n\n\n                // Publish This Message\n                // std_msgs::Int16 msg0;\n                // msg0.data = actual_curr_0;\n                // chatter_pub0.publish(msg0);\n\n                // std_msgs::Int16 msg1;\n                // msg1.data = actual_curr_1;\n                // chatter_pub1.publish(msg1);\n\n                // static int32_t actual_position_0_old = -970;\n                // static int32_t actual_position_1_old = -970;\n                // // Publish postion message\n                // if(messageRecievedFromController && actual_position_0_old != actual_position_0 ){\n                //   actual_position_0_old = actual_position_0;\n                //   std_msgs::Int32 postionMessage0;\n                //   postionMessage0.data = actual_position_0;\n                //   postion_message_publisher_0.publish(postionMessage0);\n                // }\n\n\n                // if(messageRecievedFromController && actual_position_1_old != actual_position_1){\n                //   actual_position_1_old = actual_position_1;\n                //   std_msgs::Int32 postionMessage1;\n                //   postionMessage1.data = actual_position_1;\n                //   postion_message_publisher_1.publish(postionMessage1);\n                // }\n\n\n\n                hexa_package::drivesFeedBack drivesFeedBack;\n                drivesFeedBack.actualPosition0 = actual_position_0;\n                drivesFeedBack.actualPosition1 = actual_position_1;\n                drivesFeedBack.loadcell0 = Force_LH;\n                drivesFeedBack.loadcell1 = Force_RH;\n                drivesFeedBack_publisher.publish(drivesFeedBack);\n\n\n                control();\n\n\n                device->set_entry(\"current_mode_setting_value\", Currentleft, kaco::WriteAccessMethod::pdo);\n                device_1->set_entry(\"current_mode_setting_value\", Currentright, kaco::WriteAccessMethod::pdo);\n\n            } catch (const std::exception &exc) {\n\n                std::cout << \"Exception in main!\" << std::endl;\n                std::cerr << exc.what();\n\n\n\n                //turn off device\n                Currentleft = 0;\n                Currentright = 0;\n                device_1->set_entry(\"current_mode_setting_value\", Currentleft, kaco::WriteAccessMethod::pdo);\n                device->set_entry(\"current_mode_setting_value\", Currentright, kaco::WriteAccessMethod::pdo);\n            }\n        }\n        // duration<double, std::milli> loop_calculation_time_span = high_resolution_clock::now() - startloop;\n        // // Sleep\n        // if((unsigned int)loop_calculation_time_span.count() < 5 ){\n        //   std::this_thread::sleep_for(std::chrono::milliseconds(5 - (unsigned int)loop_calculation_time_span.count() ));\n        // }else{\n        //   std::this_thread::sleep_for(std::chrono::microseconds(100));\n        // }\n        // ros::spinOnce();\n        loop_rate.sleep();\n        //ros::Rate.sleep();\n    }\n\n    std::cout << \"Finished.\" << std::endl;\n    return EXIT_SUCCESS;\n};\n\n\nvoid control() {\n\n\n    static long double a_filter = 0.01;\n    static long double pi = 3.14;\n    static long double D_Time;\n    static long double D_time = D_Time = 0.005;\n    static long double Current_Limit = 3000;\n\n    static long double Assist_R = 0;\n    static long double Assist_L = 0;\n\n//# Feedback\n// long double LoadcellRightHip = 0;\n// long double LoadcellLeftHip = 0;\n    static long double PositionActualValueright = actual_position_1;\n    PositionActualValueright = actual_position_1;\n    static long double PositionActualValueleft = actual_position_0;\n    PositionActualValueleft = actual_position_0;\n    static long double VelocityActualValueright = 0;\n    static long double VelocityActualValueleft = 0;\n\n    static long double CurrentActualValueright = actual_curr_1;\n    CurrentActualValueright = actual_curr_1;\n    static long double CurrentActualValueleft = actual_curr_0;\n    CurrentActualValueleft = actual_curr_0;\n\n\n    static long double Zero_Impedance_Gain = 1;\n\n    static long double I_R = 0.1;\n    static long double C_R = 1.5;\n    static long double FK_R = 1.5;\n    static long double MgL_R = 0.5;\n    static long double PID_Gain_R = 0.3;\n    static long double N_RH = 100;\n\n    static long double I_L = 0.1;\n    static long double C_L = 1.5;\n    static long double FK_L = 1.5;\n    static long double MgL_L = 0.5;\n    static long double PID_Gain_L = 0.5;\n    static long double N_LH = 100;\n\n    //# initial value\n\n    static long double Flt_Vel_RH_old = 0;\n    static long double Flt_Vel_LH_old = 0;\n    static long double L_Assist = 755;\n    static long double R_Assist = 750;\n    static long double R_o = 0;\n    static long double L_o = 0;\n    static long double Flt_Acc_RH_old = 0;\n    static long double Flt_Acc_LH_old = 0;\n    static long double ef_RH_old = 0;\n    static long double ef_LH_old = 0;\n    static long double PD_RH_old = 0;\n    static long double PD_LH_old = 0;\n\n    static long double D_RH = 0.1;\n    static long double D_LH = 0.1;\n    static long double timer_r = 0;\n    static long double timer_l = 0;\n    static long double Moving_Average_RH[8] = {0, 0, 0, 0, 0, 0, 0, 0};\n    static long double Moving_Average_LH[8] = {0, 0, 0, 0, 0, 0, 0, 0};\n    static long double Moving_Average_FR[8] = {0, 0, 0, 0, 0, 0, 0, 0};\n    static long double Moving_Average_FL[8] = {0, 0, 0, 0, 0, 0, 0, 0};\n    static long double Velocity_RH = 0;\n    static long double Velocity_LH = 0;\n    static long double Theta_RH = 0;\n    static long double Theta_LH = 0;\n    static long double Flt_Vel_RH = 0;\n    static long double Flt_Vel_LH = 0;\n    static long double Flt_Acc_RH = 0;\n    static long double Flt_Acc_LH = 0;\n    static long double ACC_RH = 0;\n    static long double ACC_LH = 0;\n    static long double SUM_Vel_R = 0;\n    static long double SUM_Vel_L = 0;\n    static long double SUM_Tau_R = 0;\n    static long double SUM_Tau_L = 0;\n    static long double ef_RH = 0;\n    static long double ef_LH = 0;\n    static long double SIGN_Theta_dt_RH = 0;\n    static long double SIGN_Theta_dt_LH = 0;\n    static long double ef_RH_dt = 0;\n    static long double ef_LH_dt = 0;\n    static long double PD_RH = 0;\n    static long double PD_LH = 0;\n    static long double Trq_RH_Zero_Impedance = 0;\n    static long double Trq_LH_Zero_Impedance = 0;\n    static long double R_i = 0;\n    static long double L_i = 0;\n    static long double timer_delay = 0;\n    static long double R_Assist_Delay = 0;\n    static long double L_Assist_Delay = 0;\n    static long double Theta_dt_RH = 0;\n    static long double Theta_dt_LH = 0;\n\n\n    Force_RH = 0.07 * (-0.023306 * (LoadcellRightHip) + 458.15 - 6.0) - 12.75;\n    Force_LH = 0.07 * (-0.023359 * (LoadcellLeftHip) + 756.79 - 6.0) - 1;\n\n    Moving_Average_RH[1] = Moving_Average_RH[2];\n    Moving_Average_RH[2] = Moving_Average_RH[3];\n    Moving_Average_RH[3] = Moving_Average_RH[4];\n    Moving_Average_RH[4] = Moving_Average_RH[5];\n    Moving_Average_RH[5] = Moving_Average_RH[6];\n    Moving_Average_RH[6] = Moving_Average_RH[7];\n    Moving_Average_RH[7] = Moving_Average_RH[8];\n    Moving_Average_RH[8] = Velocity_RH;\n\n    Moving_Average_LH[1] = Moving_Average_LH[2];\n    Moving_Average_LH[2] = Moving_Average_LH[3];\n    Moving_Average_LH[3] = Moving_Average_LH[4];\n    Moving_Average_LH[4] = Moving_Average_LH[5];\n    Moving_Average_LH[5] = Moving_Average_LH[6];\n    Moving_Average_LH[6] = Moving_Average_LH[7];\n    Moving_Average_LH[7] = Moving_Average_LH[8];\n    Moving_Average_LH[8] = Velocity_LH;\n\n    Moving_Average_FR[1] = Moving_Average_FR[2];\n    Moving_Average_FR[2] = Moving_Average_FR[3];\n    Moving_Average_FR[3] = Moving_Average_FR[4];\n    Moving_Average_FR[4] = Moving_Average_FR[5];\n    Moving_Average_FR[5] = Moving_Average_FR[6];\n    Moving_Average_FR[6] = Moving_Average_FR[7];\n    Moving_Average_FR[7] = Moving_Average_FR[8];\n    Moving_Average_FR[8] = Force_RH;\n\n    Moving_Average_FL[1] = Moving_Average_FL[2];\n    Moving_Average_FL[2] = Moving_Average_FL[3];\n    Moving_Average_FL[3] = Moving_Average_FL[4];\n    Moving_Average_FL[4] = Moving_Average_FL[5];\n    Moving_Average_FL[5] = Moving_Average_FL[6];\n    Moving_Average_FL[6] = Moving_Average_FL[7];\n    Moving_Average_FL[7] = Moving_Average_FL[8];\n    Moving_Average_FL[8] = Force_LH;\n\n    // Theta\n    Theta_RH = -(2 * pi / (4800)) * PositionActualValueright;\n    Theta_LH = +(2 * pi / (4800)) * PositionActualValueleft;\n\n    // Velocity With Filter\n    Flt_Vel_RH = (1 - D_Time / a_filter) * Flt_Vel_RH_old + (Theta_RH) * D_Time / a_filter;\n    Flt_Vel_LH = (1 - D_Time / a_filter) * Flt_Vel_LH_old + (Theta_LH) * D_Time / a_filter;\n\n    Velocity_RH = (Flt_Vel_RH - Flt_Vel_RH_old) / D_Time;\n    Velocity_LH = (Flt_Vel_LH - Flt_Vel_LH_old) / D_Time;\n\n    Flt_Vel_RH_old = Flt_Vel_RH;\n    Flt_Vel_LH_old = Flt_Vel_LH;\n\n    // Velocity Filter\n    Flt_Acc_RH = (1 - D_Time / a_filter) * Flt_Acc_RH_old + (Velocity_RH) * D_Time / a_filter;\n    Flt_Acc_LH = (1 - D_Time / a_filter) * Flt_Acc_LH_old + (Velocity_LH) * D_Time / a_filter;\n\n    // Acceleration\n    ACC_RH = (Flt_Acc_RH - Flt_Acc_RH_old) / D_Time;\n    ACC_LH = (Flt_Acc_LH - Flt_Acc_LH_old) / D_Time;\n\n    Flt_Acc_RH_old = Flt_Acc_RH;\n    Flt_Acc_LH_old = Flt_Acc_LH;\n\n// Moving Average\n    SUM_Vel_R = (Moving_Average_RH[1] + Moving_Average_RH[2] + Moving_Average_RH[3] + Moving_Average_RH[4] +\n                 Moving_Average_RH[5] + Moving_Average_RH[6] + Moving_Average_RH[7] + Moving_Average_RH[8]) / 8;\n    SUM_Vel_L = (Moving_Average_LH[1] + Moving_Average_LH[2] + Moving_Average_LH[3] + Moving_Average_LH[4] +\n                 Moving_Average_LH[5] + Moving_Average_LH[6] + Moving_Average_LH[7] + Moving_Average_LH[8]) / 8;\n\n    SUM_Tau_R = -(Moving_Average_FR[1] + Moving_Average_FR[2] + Moving_Average_FR[3] + Moving_Average_FR[4] +\n                  Moving_Average_FR[5] + Moving_Average_FR[6] + Moving_Average_FR[7] + Moving_Average_FR[8]) / 8;\n    SUM_Tau_L = -(Moving_Average_FL[1] + Moving_Average_FL[2] + Moving_Average_FL[3] + Moving_Average_FL[4] +\n                  Moving_Average_FL[5] + Moving_Average_FL[6] + Moving_Average_FL[7] + Moving_Average_FL[8]) / 8;\n\n\n    // Identification\n    if (Force_RH > 0) {\n        SIGN_Theta_dt_RH = -1;\n    } else if (Force_RH < 0) {\n        SIGN_Theta_dt_RH = +1;\n    } else {\n        SIGN_Theta_dt_RH = 0;\n    }\n\n    if (Force_LH > 0) {\n        SIGN_Theta_dt_LH = -1;\n    } else if (Force_LH < 0) {\n        SIGN_Theta_dt_LH = +1;\n    } else {\n        SIGN_Theta_dt_LH = 0;\n    }\n\n    // PD Code\n    ef_RH = 0 - Force_RH;\n    ef_LH = 0 - Force_LH;\n\n    ef_RH_dt = (ef_RH - ef_RH_old) / D_time;\n    ef_LH_dt = (ef_LH - ef_LH_old) / D_time;\n\n    PD_RH = (1 - N_RH * D_time) * PD_RH_old + N_RH * P_RH * D_time * (ef_RH) + (P_RH + N_RH * D_RH) * D_time * ef_RH_dt;\n    PD_LH = (1 - N_LH * D_time) * PD_LH_old + N_LH * P_LH * D_time * (ef_LH) + (P_LH + N_LH * D_LH) * D_time * ef_LH_dt;\n\n    ef_RH_dt = (ef_RH - ef_RH_old) / D_time;\n    ef_LH_dt = (ef_LH - ef_LH_old) / D_time;\n\n    PD_RH = (1 - N_RH * D_time) * PD_RH_old + N_RH * P_RH * D_time * (ef_RH) + (P_RH + N_RH * D_RH) * D_time * ef_RH_dt;\n    PD_LH = (1 - N_LH * D_time) * PD_LH_old + N_LH * P_LH * D_time * (ef_LH) + (P_LH + N_LH * D_LH) * D_time * ef_LH_dt;\n\n    ef_RH_old = ef_RH;\n    ef_LH_old = ef_LH;\n\n    PD_RH_old = PD_RH;\n    PD_LH_old = PD_LH;\n\n    //Zero Impedance\n    Trq_RH_Zero_Impedance =\n            -(I_R * ACC_RH + C_R * Theta_dt_RH + FK_R * SIGN_Theta_dt_RH + MgL_R * sin(Theta_RH) +\n              PID_Gain_R * PD_RH) / 0.0369;\n    Trq_LH_Zero_Impedance =\n            (I_L * ACC_LH + C_L * Theta_dt_LH + FK_L * SIGN_Theta_dt_LH + MgL_L * sin(Theta_LH) +\n             PID_Gain_L * PD_LH) / 0.0369;\n\n    // Assist as Needed\n    if (control_algorithm == \"assist_as_needed\") {\n        if (timer_r > timer_right) {\n            R_o = 0;\n        } else if (Velocity_RH > 0.2 && Velocity_LH <= 0.0 && R_i == 0) {\n            R_o = 1;\n            R_i = 1;\n            L_i = 0;\n        }\n\n        if (timer_l > timer_left) {\n            L_o = 0;\n        } else if (Velocity_LH > 0.2 && Velocity_RH <= 0.0 && L_i == 0) {\n            L_o = 1;\n            R_i = 0;\n            L_i = 1;\n        }\n\n        if (R_o == 1) {\n            timer_r = timer_r + 1;\n            R_Assist = -Assist_Right; // this value came from GUI;\n        } else if (R_o == 0) {\n            timer_r = 0;\n            R_Assist = 0;\n        }\n\n        if (L_o == 1) {\n            timer_l = timer_l + 1;\n            L_Assist = Assist_Left;\n        } else if (L_o == 0) {\n            timer_l = 0;\n            L_Assist = 0;\n        }\n    }\n\n    if (control_algorithm == \"time_based_assist\") {\n        // Time based assist for right leg\n        if (control_algorithm_right == \"assist_as_needed\") {\n            if (timer_r > timer_right) {\n                R_o = 0;\n            } else if (timer_delay >= delay_time && R_i == 0) {\n                R_o = 1;\n                R_i = 1;\n                L_i = 0;\n                timer_delay = 0;\n            }\n\n            if (timer_l > timer_left) {\n                L_o = 0;\n            } else if (SUM_Vel_L >= 0.1 && SUM_Vel_R <= 0.0 && L_i == 0) {\n                L_o = 1;\n                R_i = 0;\n                L_i = 1;\n            }\n\n\n            if (L_i == 1) {\n                timer_delay = timer_delay + 1;\n            }\n\n            if (R_o == 1) {\n                timer_r = timer_r + 1;\n                R_Assist_Delay = -Assist_Delay;\n            } else if (R_o == 0) {\n                timer_r = 0;\n                R_Assist_Delay = 0;\n            }\n\n            if (L_o == 1) {\n                timer_l = timer_l + 1;\n                L_Assist_Delay = Trq_LH_Zero_Impedance;\n            } else if (L_o == 0) {\n                timer_l = 0;\n                L_Assist = Trq_LH_Zero_Impedance;\n            }\n        }\n        // Time based assist for left leg\n//        cout<<\"control_algorithm_left: \"<<control_algorithm_left<<endl;\n        if (control_algorithm_left == \"assist_as_needed\") {\n            if (timer_r > timer_right) {\n                R_o = 0;\n            } else if (SUM_Vel_R >= 0.1 && SUM_Vel_L <= 0.0 && R_i == 0) {\n                R_o = 1;\n                R_i = 1;\n                L_i = 0;\n            }\n\n            if (timer_l > timer_left) {\n                L_o = 0;\n            } else if (timer_delay >= delay_time && L_i == 0) {\n                L_o = 1;\n                R_i = 0;\n                L_i = 1;\n                timer_delay = 0;\n            }\n\n            if (R_i == 1) {\n                timer_delay = timer_delay + 1;\n            }\n\n            if (R_o == 1) {\n                timer_r = timer_r + 1;\n                R_Assist_Delay = Trq_RH_Zero_Impedance;\n            } else if (R_o == 0) {\n                timer_r = 0;\n                R_Assist_Delay = Trq_RH_Zero_Impedance;\n            }\n\n            if (L_o == 1) {\n                timer_l = timer_l + 1;\n                L_Assist_Delay = Assist_Delay;\n            } else if (L_o == 0) {\n                timer_l = 0;\n                L_Assist_Delay = 0;\n            }\n        }\n    }\n\n    // Send TO Derive\n\n    // Right Left Control\n    if (control_algorithm_right == \"zero_impedance\") {\n        Currentright = int(Trq_RH_Zero_Impedance);\n    }\n    if (control_algorithm_right == \"assist_as_needed\") {\n        Currentright = int(R_Assist);\n    }\n    if (control_algorithm == \"time_based_assist\") {\n        Currentright = int(R_Assist_Delay);\n//        cout << \"R Assist: \" << Currentright << endl;\n    }\n\n    // Left Leg Control\n    if (control_algorithm_left == \"zero_impedance\") {\n        Currentleft = int(Trq_LH_Zero_Impedance);\n    }\n    if (control_algorithm_left == \"assist_as_needed\") {\n        Currentleft = int(L_Assist);\n    }\n\n    if (control_algorithm == \"time_based_assist\") {\n        Currentleft = int(L_Assist_Delay);\n//        cout<<\"Timer : \"<<timer_delay<<endl;\n    }\n\n\n    static int loopCounter;\n    loopCounter++;\n    //Currentright = 200 * sin(loopCounter / 200.00);\n    //Currentleft = 200 * sin(loopCounter / 200.00);\n\n    // # desiredCurrentRight.publish(int(Currentright))\n    // # desiredCurrentLeft.publish(int(Currentleft))\n\n    // # drivesFeedBack df\n    // # df.actualCurrent0 = Currentleft\n    // # df.actualCurrent1 = Currentright\n    // drives_action.publish(drivesAction(int(Currentleft), int(Currentright)))\n\n    // #desiredCurrentRight.publish(int(500))\n    // #desiredCurrentLeft.publish(int(500))\n    // # if((loopCounter % 1 == 0):\n    // #     print(\"time:\" + str(time.time()) + \"\\tForce_LH:\" + str(Force_LH) + \"\\tForce_RH:\" + str(Force_RH) +\"\\tCurrentleft:\" + str(Currentleft) + \"\\tCurrentright:\" + str(Currentright) + \"\\tCurrentActualValueright:\" + str(CurrentActualValueright) + \"\\tCurrentActualValueleft\" + str(CurrentActualValueleft) + \"\\tLoadcellLeftHip:\" + str(LoadcellLeftHip) + \"\\tLoadcellRightHip:\" + str(LoadcellRightHip) + \"\\tPositionActualValueleft:\" + str(PositionActualValueleft)  + \"\\tPositionActualValueright:\" + str(PositionActualValueright)) \n    // loopCounter = loopCounter + 1\n    // #print(\"time:\" + str(time.time()) )\n    //rate.sleep()\n    //  if((loopCounter % 40)\n    //  cout << \"time:\" << \"str(time.time())\" << \"\\tForce_LH:\" << (Force_LH) << \"\\tForce_RH:\" << (Force_RH) << \"\\tCurrentleft:\" <<(Currentleft) << \"\\tCurrentright:\" << (Currentright) << \"\\tCurrentActualValueright:\" << (CurrentActualValueright) << \"\\tCurrentActualValueleft\" << (CurrentActualValueleft) << \"\\tLoadcellLeftHip:\" << (LoadcellLeftHip) << \"\\tLoadcellRightHip:\" << (LoadcellRightHip) << \"\\tPositionActualValueleft:\" << (PositionActualValueleft)  << \"\\tPositionActualValueright:\" << (PositionActualValueright) << endl ;\n    //cout << Force_LH << \"\\tForce_RH:\" << (Force_RH) << \"\\n\";\n// cout << LoadcellRightHip;\n\n    // duration<double, std::milli> time_take_to_this = high_resolution_clock::now() - lastTime;\n    // double currentTime = time_take_to_this.count() ;\n    // lastTime = high_resolution_clock::now();\n    // cout << currentTime << \"\\n\" ;\n\n\n}\n", "meta": {"hexsha": "9e2ec7896190fb04038ee08825350fc845302b93", "size": 39677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hexa_package/src/cpp_node4.cpp", "max_stars_repo_name": "FUMRobotics/FUMHexa", "max_stars_repo_head_hexsha": "c52eebe8cd70a5a5d765a138c6f31080d8815762", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-29T15:28:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T15:28:16.000Z", "max_issues_repo_path": "src/hexa_package/src/cpp_node4.cpp", "max_issues_repo_name": "FUMRobotics/FUMHexa", "max_issues_repo_head_hexsha": "c52eebe8cd70a5a5d765a138c6f31080d8815762", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hexa_package/src/cpp_node4.cpp", "max_forks_repo_name": "FUMRobotics/FUMHexa", "max_forks_repo_head_hexsha": "c52eebe8cd70a5a5d765a138c6f31080d8815762", "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.7720111214, "max_line_length": 530, "alphanum_fraction": 0.5969201301, "num_tokens": 10741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1403362494900832, "lm_q2_score": 0.021948254514558344, "lm_q1q2_score": 0.0030801357214269047}}
{"text": "//=============================================================================================================\n/**\n * @file     hpifit.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>;\n *           Ruben Dörfel <doerfelruben@aol.com>;\n *           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n * @since    0.1.0\n * @date     March, 2017\n *\n * @section  LICENSE\n *\n * Copyright (C) 2017, Lorenz Esch, Matti Hamalainen. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n *       following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n *       the following disclaimer in the documentation and/or other materials provided with the distribution.\n *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n *       to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief    HPIFit class defintion.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"hpifit.h\"\n#include \"hpifitdata.h\"\n#include \"sensorset.h\"\n#include \"hpidataupdater.h\"\n#include \"signalmodel.h\"\n#include \"hpimodelparameters.h\"\n\n#include <utils/ioutils.h>\n#include <utils/mnemath.h>\n\n#include <iostream>\n#include <vector>\n#include <numeric>\n#include <fiff/fiff_cov.h>\n#include <fiff/fiff_dig_point_set.h>\n#include <fstream>\n\n#include <fwd/fwd_coil_set.h>\n\n//=============================================================================================================\n// EIGEN INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Dense>\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QVector>\n#include <QFuture>\n#include <QtConcurrent/QtConcurrent>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace INVERSELIB;\nusing namespace FIFFLIB;\nusing namespace FWDLIB;\n\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\n//=============================================================================================================\n\nHPIFit::HPIFit(const SensorSet& sensorSet)\n    : m_sensors(sensorSet),\n      m_signalModel(SignalModel())\n{\n\n}\n\n//=============================================================================================================\n\nvoid HPIFit::checkForUpdate(const SensorSet &sensorSet)\n{\n    if(m_sensors != sensorSet) {\n        m_sensors = sensorSet;\n    }\n}\n\n//=============================================================================================================\n\nvoid HPIFit::fit(const MatrixXd& matProjectedData,\n                 const MatrixXd& matProjectors,\n                 const HpiModelParameters& hpiModelParameters,\n                 const MatrixXd& matCoilsHead,\n                 HpiFitResult& hpiFitResult)\n{\n    fit(matProjectedData,matProjectors,hpiModelParameters,matCoilsHead,false,hpiFitResult);\n}\n\n//=============================================================================================================\n\nvoid HPIFit::fit(const MatrixXd& matProjectedData,\n                 const MatrixXd& matProjectors,\n                 const HpiModelParameters& hpiModelParameters,\n                 const MatrixXd& matCoilsHead,\n                 const bool bOrderFrequencies,\n                 HpiFitResult& hpiFitResult)\n{\n    if(matProjectedData.rows() != matProjectors.rows()) {\n        std::cout<< \"HPIFit::fit - Projector and data dimensions do not match. Returning.\"<<std::endl;\n        return;\n    } else if(hpiModelParameters.iNHpiCoils()!= matCoilsHead.rows()) {\n        std::cout<< \"HPIFit::fit - Number of coils and hpi digitizers do not match. Returning.\"<<std::endl;\n        return;\n    } else if(matProjectedData.rows()==0 || matProjectors.rows()==0) {\n        std::cout<< \"HPIFit::fit - No data or Projectors passed. Returning.\"<<std::endl;\n        return;\n    } else if(m_sensors.ncoils() != matProjectedData.rows()) {\n        std::cout<< \"HPIFit::fit - Number of channels in sensors and data do not match. Returning.\"<<std::endl;\n        return;\n    }\n\n    const MatrixXd matAmplitudes = computeAmplitudes(matProjectedData,\n                                                     hpiModelParameters);\n\n    const MatrixXd matCoilsSeed = computeSeedPoints(matAmplitudes,\n                                                    hpiFitResult.devHeadTrans,\n                                                    hpiFitResult.errorDistances,\n                                                    matCoilsHead);\n\n    CoilParam fittedCoilParams = dipfit(matCoilsSeed,\n                                        m_sensors,\n                                        matAmplitudes,\n                                        hpiModelParameters.iNHpiCoils(),\n                                        matProjectors,\n                                        500,\n                                        1e-9f);\n\n    if(bOrderFrequencies) {\n        const std::vector<int> vecOrder = findCoilOrder(fittedCoilParams.pos,\n                                                        matCoilsHead);\n\n        fittedCoilParams.pos = order(vecOrder,fittedCoilParams.pos);\n        hpiFitResult.hpiFreqs = order(vecOrder,hpiModelParameters.vecHpiFreqs());\n    }\n\n    hpiFitResult.GoF = computeGoF(fittedCoilParams.dpfiterror);\n\n    hpiFitResult.fittedCoils = getFittedPointSet(fittedCoilParams.pos);\n\n    hpiFitResult.devHeadTrans = computeDeviceHeadTransformation(fittedCoilParams.pos,\n                                                                matCoilsHead);\n\n    hpiFitResult.errorDistances = computeEstimationError(fittedCoilParams.pos,\n                                                         matCoilsHead,\n                                                         hpiFitResult.devHeadTrans);\n}\n\n//=============================================================================================================\n\nEigen::MatrixXd HPIFit::computeAmplitudes(const Eigen::MatrixXd& matProjectedData,\n                                          const HpiModelParameters& hpiModelParameters)\n{\n    // fit model\n    MatrixXd matTopo = m_signalModel.fitData(hpiModelParameters,matProjectedData);\n    matTopo.transposeInPlace();\n\n    // split into sine and cosine amplitudes\n    const int iNumCoils = hpiModelParameters.iNHpiCoils();\n\n    MatrixXd matAmpSine(matProjectedData.cols(), iNumCoils);\n    MatrixXd matAmpCosine(matProjectedData.cols(), iNumCoils);\n\n    matAmpSine = matTopo.leftCols(iNumCoils);\n    matAmpCosine = matTopo.middleCols(iNumCoils,iNumCoils);\n\n    // Select sine or cosine component depending on their contributions to the amplitudes\n    for(int j = 0; j < iNumCoils; ++j) {\n        float fNS = 0.0;\n        float fNC = 0.0;\n        fNS = matAmpSine.col(j).array().square().sum();\n        fNC = matAmpCosine.col(j).array().square().sum();\n        if(fNC > fNS) {\n            matAmpSine.col(j) = matAmpCosine.col(j);\n        }\n    }\n\n    return matAmpSine;\n}\n\n//=============================================================================================================\n\nEigen::MatrixXd HPIFit::computeSeedPoints(const Eigen::MatrixXd& matAmplitudes,\n                                          const FIFFLIB::FiffCoordTrans& transDevHead,\n                                          const QVector<double>& vecError,\n                                          const Eigen::MatrixXd& matCoilsHead)\n{\n    const int iNumCoils = matCoilsHead.rows();\n    MatrixXd matCoilsSeed = MatrixXd::Zero(iNumCoils,3);\n\n    const double dError = std::accumulate(vecError.begin(), vecError.end(), .0) / vecError.size();\n\n    if(transDevHead.trans != MatrixXd::Identity(4,4).cast<float>() && dError < 0.010) {\n        // if good last fit, use old trafo\n        matCoilsSeed = transDevHead.apply_inverse_trans(matCoilsHead.cast<float>()).cast<double>();\n    } else {\n        // if not, find max amplitudes in channels\n        VectorXi vecChIdcs(iNumCoils);\n\n        for (int j = 0; j < iNumCoils; j++) {\n            int iChIdx = 0;\n            VectorXd::Index indMax;\n            matAmplitudes.col(j).maxCoeff(&indMax);\n            if(indMax < m_sensors.ncoils()) {\n                iChIdx = indMax;\n            }\n            vecChIdcs(j) = iChIdx;\n        }\n        // and go 3 cm inwards from max channels\n        for (int j = 0; j < vecChIdcs.rows(); ++j) {\n            if(vecChIdcs(j) < m_sensors.ncoils()) {\n                Vector3d r0 = m_sensors.r0(vecChIdcs(j));\n                Vector3d ez = m_sensors.ez(vecChIdcs(j));\n                matCoilsSeed.row(j) = (-1 * ez * 0.03 + r0);\n            }\n        }\n    }\n    return matCoilsSeed;\n}\n\n//=============================================================================================================\n\nCoilParam HPIFit::dipfit(const MatrixXd matCoilsSeed,\n                         const SensorSet& sensors,\n                         const MatrixXd& matData,\n                         const int iNumCoils,\n                         const MatrixXd& matProjectors,\n                         const int iMaxIterations,\n                         const float fAbortError)\n{\n    //Do this in conncurrent mode\n    //Generate QList structure which can be handled by the QConcurrent framework\n    QList<HPIFitData> lCoilData;\n\n    for(qint32 i = 0; i < iNumCoils; ++i) {\n        HPIFitData coilData;\n        coilData.m_coilPos = matCoilsSeed.row(i);\n        coilData.m_sensorData = matData.col(i);\n        coilData.m_sensors = sensors;\n        coilData.m_matProjector = matProjectors;\n        coilData.m_iMaxIterations = iMaxIterations;\n        coilData.m_fAbortError = fAbortError;\n\n        lCoilData.append(coilData);\n    }\n    //Do the concurrent filtering\n    CoilParam coil(iNumCoils);\n\n    if(!lCoilData.isEmpty()) {\n        //        //Do sequential\n        //        for(int l = 0; l < lCoilData.size(); ++l) {\n        //            doDipfitConcurrent(lCoilData[l]);\n        //        }\n\n        //Do concurrent\n        QFuture<void> future = QtConcurrent::map(lCoilData,\n                                                 &HPIFitData::doDipfitConcurrent);\n        future.waitForFinished();\n\n\n        //Transform results to final coil information\n        for(qint32 i = 0; i < lCoilData.size(); ++i) {\n            coil.pos.row(i) = lCoilData.at(i).m_coilPos;\n            coil.mom = lCoilData.at(i).m_errorInfo.moment.transpose();\n            coil.dpfiterror(i) = lCoilData.at(i).m_errorInfo.error;\n            coil.dpfitnumitr(i) = lCoilData.at(i).m_errorInfo.numIterations;\n\n            //std::cout<<std::endl<< \"HPIFit::dipfit - Itr steps for coil \" << i << \" =\" <<coil.dpfitnumitr(i);\n        }\n    }\n    return coil;\n}\n\n//=============================================================================================================\n\nstd::vector<int> HPIFit::findCoilOrder(const MatrixXd& matCoilsDev,\n                                       const MatrixXd& matCoilsHead)\n{\n    // extract digitized and fitted coils\n    MatrixXd matCoilTemp = matCoilsDev;\n    const int iNumCoils = matCoilsDev.rows();\n\n    std::vector<int> vecOrder(iNumCoils);\n    std::iota(vecOrder.begin(), vecOrder.end(), 0);;\n\n    // maximum 10 mm mean error\n    const double dErrorMin = 0.010;\n    double dErrorActual = 0.0;\n    double dErrorBest = dErrorMin;\n\n    MatrixXd matTrans(4,4);\n    std::vector<int> vecOrderBest = vecOrder;\n\n    bool bSuccess = false;\n    // permutation\n    do {\n        for(int i = 0; i < iNumCoils; i++) {\n            matCoilTemp.row(i) =  matCoilsDev.row(vecOrder[i]);\n        }\n        matTrans = computeTransformation(matCoilsHead,matCoilTemp);\n        dErrorActual = objectTrans(matCoilsHead,matCoilTemp,matTrans);\n        if(dErrorActual < dErrorMin && dErrorActual < dErrorBest) {\n            // exit\n            dErrorBest = dErrorActual;\n            vecOrderBest = vecOrder;\n            bSuccess = true;\n        }\n    } while (std::next_permutation(vecOrder.begin(), vecOrder.end()));\n    return vecOrderBest;\n}\n\n//=============================================================================================================\n\ndouble HPIFit::objectTrans(const MatrixXd& matHeadCoil,\n                           const MatrixXd& matCoil,\n                           const MatrixXd& matTrans)\n{\n    // Compute the fiducial registration error - the lower, the better.\n    const int iNumCoils = matHeadCoil.rows();\n    MatrixXd matTemp = matCoil;\n\n    // homogeneous coordinates\n    matTemp.conservativeResize(matCoil.rows(),matCoil.cols()+1);\n    matTemp.block(0,3,iNumCoils,1).setOnes();\n    matTemp.transposeInPlace();\n\n    // apply transformation\n    MatrixXd matTestPos = matTrans * matTemp;\n\n    // remove\n    MatrixXd matDiff = matTestPos.block(0,0,3,iNumCoils) - matHeadCoil.transpose();\n    VectorXd vecError = matDiff.colwise().norm();\n\n    // compute error\n    double dError = matDiff.colwise().norm().mean();;\n\n    return dError;\n}\n\n//=============================================================================================================\n\nEigen::MatrixXd HPIFit::order(const std::vector<int>& vecOrder,\n                              const Eigen::MatrixXd& matToOrder)\n{\n    const int iNumCoils = vecOrder.size();\n    MatrixXd matToOrderTemp = matToOrder;\n\n    for(int i = 0; i < iNumCoils; i++) {\n        matToOrderTemp.row(i) =  matToOrder.row(vecOrder[i]);\n    }\n    return matToOrderTemp;\n}\n\n//=============================================================================================================\n\nQVector<int> HPIFit::order(const std::vector<int>& vecOrder,\n                           const QVector<int>& vecToOrder)\n{\n    const int iNumCoils = vecOrder.size();\n    QVector<int> vecToOrderTemp = vecToOrder;\n\n    for(int i = 0; i < iNumCoils; i++) {\n        vecToOrderTemp[i] =  vecToOrder[vecOrder[i]];\n    }\n    return vecToOrderTemp;\n}\n\n//=============================================================================================================\n\nEigen::VectorXd HPIFit::computeGoF(const Eigen::VectorXd& vecDipFitError)\n{\n    VectorXd vecGoF(vecDipFitError.size());\n    for(int i = 0; i < vecDipFitError.size(); ++i) {\n        vecGoF(i) = 1 - vecDipFitError(i);\n    }\n    return vecGoF;\n}\n\n//=============================================================================================================\n\nFIFFLIB::FiffCoordTrans HPIFit::computeDeviceHeadTransformation(const Eigen::MatrixXd& matCoilsDev,\n                                                                const Eigen::MatrixXd& matCoilsHead)\n{\n    const MatrixXd matTrans = computeTransformation(matCoilsHead,matCoilsDev);\n    return FiffCoordTrans::make(1,4,matTrans.cast<float>(),true);\n}\n\n//=============================================================================================================\n\nEigen::Matrix4d HPIFit::computeTransformation(Eigen::MatrixXd matNH, MatrixXd matBT)\n{\n    MatrixXd matXdiff, matYdiff, matZdiff, matC, matQ;\n    Matrix4d matTransFinal = Matrix4d::Identity(4,4);\n    Matrix4d matRot = Matrix4d::Zero(4,4);\n    Matrix4d matTrans = Matrix4d::Identity(4,4);\n    double dMeanX,dMeanY,dMeanZ,dNormf;\n\n    for(int i = 0; i < 15; ++i) {\n        // Calculate mean translation for all points -> centroid of both data sets\n        matXdiff = matNH.col(0) - matBT.col(0);\n        matYdiff = matNH.col(1) - matBT.col(1);\n        matZdiff = matNH.col(2) - matBT.col(2);\n\n        dMeanX = matXdiff.mean();\n        dMeanY = matYdiff.mean();\n        dMeanZ = matZdiff.mean();\n\n        // Apply translation -> bring both data sets to the same center location\n        for (int j = 0; j < matBT.rows(); ++j) {\n            matBT(j,0) = matBT(j,0) + dMeanX;\n            matBT(j,1) = matBT(j,1) + dMeanY;\n            matBT(j,2) = matBT(j,2) + dMeanZ;\n        }\n\n        // Estimate rotation component\n        matC = matBT.transpose() * matNH;\n\n        JacobiSVD< MatrixXd > svd(matC ,Eigen::ComputeThinU | ComputeThinV);\n\n        matQ = svd.matrixU() * svd.matrixV().transpose();\n\n        //Handle special reflection case\n        if(matQ.determinant() < 0) {\n            matQ(0,2) = matQ(0,2) * -1;\n            matQ(1,2) = matQ(1,2) * -1;\n            matQ(2,2) = matQ(2,2) * -1;\n        }\n\n        // Apply rotation on translated points\n        matBT = matBT * matQ;\n\n        // Calculate GOF\n        dNormf = (matNH.transpose()-matBT.transpose()).norm();\n\n        // Store rotation part to transformation matrix\n        matRot(3,3) = 1;\n        for(int j = 0; j < 3; ++j) {\n            for(int k = 0; k < 3; ++k) {\n                matRot(j,k) = matQ(k,j);\n            }\n        }\n\n        // Store translation part to transformation matrix\n        matTrans(0,3) = dMeanX;\n        matTrans(1,3) = dMeanY;\n        matTrans(2,3) = dMeanZ;\n\n        // Safe rotation and translation to final matrix for next iteration step\n        // This step is safe to do since we change one of the input point sets (matBT)\n        // ToDo: Replace this for loop with a least square solution process\n        matTransFinal = matRot * matTrans * matTransFinal;\n    }\n    return matTransFinal;\n}\n\n//=============================================================================================================\n\nQVector<double> HPIFit::computeEstimationError(const Eigen::MatrixXd& matCoilsDev,\n                                               const Eigen::MatrixXd& matCoilsHead,\n                                               const FIFFLIB::FiffCoordTrans& transDevHead)\n{\n    //Calculate Error\n    MatrixXd matTemp = matCoilsDev;\n    MatrixXd matTestPos = transDevHead.apply_trans(matTemp.cast<float>()).cast<double>();\n    MatrixXd matDiffPos = matTestPos - matCoilsHead;\n\n    // compute error\n    int iNumCoils = matCoilsDev.rows();\n    QVector<double> vecError(iNumCoils);\n    for(int i = 0; i < matDiffPos.rows(); ++i) {\n        vecError[i] = matDiffPos.row(i).norm();\n    }\n    return vecError;\n}\n\n//=============================================================================================================\n\nFIFFLIB::FiffDigPointSet HPIFit::getFittedPointSet(const Eigen::MatrixXd& matCoilsDev)\n{\n    FiffDigPointSet fittedPointSet;\n    const int iNumCoils = matCoilsDev.rows();\n\n    for(int i = 0; i < iNumCoils; ++i) {\n        FiffDigPoint digPoint;\n        digPoint.kind = FIFFV_POINT_EEG; //Store as EEG so they have a different color\n        digPoint.ident = i;\n        digPoint.r[0] = matCoilsDev(i,0);\n        digPoint.r[1] = matCoilsDev(i,1);\n        digPoint.r[2] = matCoilsDev(i,2);\n\n        fittedPointSet << digPoint;\n    }\n    return fittedPointSet;\n}\n\n//=============================================================================================================\n\nvoid HPIFit::storeHeadPosition(float fTime,\n                               const Eigen::MatrixXf& transDevHead,\n                               Eigen::MatrixXd& matPosition,\n                               const Eigen::VectorXd& vecGoF,\n                               const QVector<double>& vecError)\n\n{\n    Matrix3f matRot = transDevHead.block(0,0,3,3);\n\n    Eigen::Quaternionf quatHPI(matRot);\n    double dError = std::accumulate(vecError.begin(), vecError.end(), .0) / vecError.size();     // HPI estimation Error\n\n    matPosition.conservativeResize(matPosition.rows()+1, 10);\n    matPosition(matPosition.rows()-1,0) = fTime;\n    matPosition(matPosition.rows()-1,1) = quatHPI.x();\n    matPosition(matPosition.rows()-1,2) = quatHPI.y();\n    matPosition(matPosition.rows()-1,3) = quatHPI.z();\n    matPosition(matPosition.rows()-1,4) = transDevHead(0,3);\n    matPosition(matPosition.rows()-1,5) = transDevHead(1,3);\n    matPosition(matPosition.rows()-1,6) = transDevHead(2,3);\n    matPosition(matPosition.rows()-1,7) = vecGoF.mean();\n    matPosition(matPosition.rows()-1,8) = dError;\n    matPosition(matPosition.rows()-1,9) = 0;\n}\n\n", "meta": {"hexsha": "6310dba291937225bca8943c5a005e730f0d4aa5", "size": 21785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/inverse/hpiFit/hpifit.cpp", "max_stars_repo_name": "Zeitproblem/mne-cpp", "max_stars_repo_head_hexsha": "38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2", "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/inverse/hpiFit/hpifit.cpp", "max_issues_repo_name": "Zeitproblem/mne-cpp", "max_issues_repo_head_hexsha": "38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/inverse/hpiFit/hpifit.cpp", "max_forks_repo_name": "Zeitproblem/mne-cpp", "max_forks_repo_head_hexsha": "38bc3ba5213bbb06dab0ff4593a44ce8e9c0cbe2", "max_forks_repo_licenses": ["BSD-3-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.3942133816, "max_line_length": 120, "alphanum_fraction": 0.5150332798, "num_tokens": 4881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624720889436, "lm_q2_score": 0.012821214125143138, "lm_q1q2_score": 0.0030324254495405225}}
{"text": "///// \\file   python_module_walras.cpp\n/////\n///// \\brief\n/////\n///// \\authors    Maarten P. Scholl\n///// \\date       2020-10-11\n///// \\copyright  Copyright 2017-2020 The Institute for New Economic Thinking,\n/////             Oxford Martin School, University of Oxford\n/////\n/////             Licensed under the Apache License, Version 2.0 (the \"License\");\n/////             you may not use this file except in compliance with the License.\n/////             You may obtain a copy of the License at\n/////\n/////                 http://www.apache.org/licenses/LICENSE-2.0\n/////\n/////             Unless required by applicable law or agreed to in writing,\n/////             software distributed under the License is distributed on an \"AS\n/////             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n/////             express or implied. See the License for the specific language\n/////             governing permissions and limitations under the License.\n/////\n/////             You may obtain instructions to fulfill the attribution\n/////             requirements in CITATION.cff\n/////\n//#include <esl/economics/markets/walras/python_module_walras.hpp>\n//#include <esl/economics/markets/walras/price_setter.hpp>\n//#include <esl/economics/markets/walras/tatonnement.hpp>\n//\n//#include <esl/law/property_collection.hpp>\n//\n//\n//\n//#ifdef WITH_PYTHON\n//\n//#include <esl/simulation/python_module_simulation.hpp>\n//\n//#include <utility>\n//\n//#define BOOST_BIND_GLOBAL_PLACEHOLDERS\n//#include <boost/python.hpp>\n//#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n//using boost::python::init;\n//using boost::python::no_init;\n//using boost::python::object;\n//using boost::python::enum_;\n//using boost::python::class_;\n//using boost::python::dict;\n//using boost::python::list;\n//using boost::python::len;\n//using boost::python::make_tuple;\n//using boost::python::extract;\n//using boost::python::wrapper;\n//using boost::python::vector_indexing_suite;\n//\n//using namespace esl::economics::markets;\n//using namespace esl::economics::markets::tatonnement;\n//\n//\n//\n//template<typename object_t_>\n//void do_release(typename boost::shared_ptr<object_t_> const&, object_t_*)\n//{\n//\n//}\n//\n//template<typename object_t_>\n//typename std::shared_ptr<object_t_> to_std(typename boost::shared_ptr<object_t_> const& p)\n//{\n//    return std::shared_ptr<object_t_>(p.get(), [p](auto &&PH1)\n//        {\n//          return do_release<object_t_>(p, std::forward<decltype(PH1)>(PH1));\n//        });\n//\n//}\n//\n//template<typename object_t_>\n//boost::shared_ptr<object_t_> to_boost(std::shared_ptr<object_t_>& ptr)\n//{\n//    return boost::shared_ptr<object_t_>(ptr.get(), [ptr](object_t_ *) mutable\n//                                        {\n//                                            ptr.reset();\n//                                        });\n//}\n//\n//\n//class python_differentiable_order_message\n//    : public esl::economics::markets::walras::differentiable_order_message\n//        , public wrapper<esl::economics::markets::walras::differentiable_order_message>\n//{\n//public:\n//    python_differentiable_order_message(\n//        const esl::simulation::python_module::python_identity &sender       = esl::simulation::python_module::python_identity(),\n//        const esl::simulation::python_module::python_identity& recipient     = esl::simulation::python_module::python_identity(),\n//        esl::simulation::time_point sent         = esl::simulation::time_point(),\n//        esl::simulation::time_point received     = esl::simulation::time_point())\n//        : esl::economics::markets::walras::differentiable_order_message\n//              ( esl::reinterpret_identity_cast<esl::agent>(sender)\n//                  , esl::reinterpret_identity_cast<esl::agent>(recipient)\n//                  , sent\n//                  , received)\n//        , wrapper<esl::economics::markets::walras::differentiable_order_message>()\n//    {\n//\n//    }\n//\n//    // the default implementation is to demand zero for all\n//    [[nodiscard]] std::map<esl::identity<esl::law::property>, esl::variable> excess_demand(const std::map<\n//        esl::identity<esl::law::property>\n//        , std::tuple<esl::economics::markets::quote, esl::variable>> &quotes) const override\n//    {\n//        dict quotes_;\n//\n//        for(const auto &[i, v]: quotes){\n//            auto t = make_tuple(std::get<0>(v), esl::value(std::get<1>(v)));\n//            quotes_.setdefault(i, t);\n//        }\n//\n//        // specify the type, so that the return value is converted to python::object\n//        object return_value_ = get_override(\"excess_demand\")(quotes_);\n//        dict excess_ = extract<dict>(return_value_);\n//        auto keys = list(excess_.keys());\n//        auto values = list(excess_.values());\n//\n//        std::map<esl::identity<esl::law::property>, esl::variable> result_;\n//\n//        for(int i = 0; i < len(keys); ++i) {\n//            extract<esl::identity<esl::law::property>> extractor(keys[i]);\n//            extract<double> value_extractor(values[i]);\n//            if(extractor.check() && value_extractor.check()) {\n//                auto key   = extractor();\n//                auto value = value_extractor();\n//\n//                result_.emplace(key, esl::variable(value));\n//            }\n//        }\n//\n//        return result_;\n//    }\n//};\n//\n//\n/////\n///// \\brief  Excess demand model wrapper\n/////\n//class python_excess_demand_model\n//: public excess_demand_model\n//, public wrapper<excess_demand_model>\n//{\n//public:\n//    explicit python_excess_demand_model(esl::law::property_map<quote> initial_quotes)\n//        : excess_demand_model(std::move(initial_quotes))\n//        , wrapper<excess_demand_model>()\n//    {\n//\n//    }\n//};\n//\n/////\n///// \\brief  Helper funciton\n/////\n///// \\param e\n///// \\return\n//dict clear_market(python_excess_demand_model *e)\n//{\n//    auto quotes_ = e->compute_clearing_quotes();\n//    dict result_;\n//\n//    if(quotes_.has_value()){\n//        //LOG(trace) << \"clear_market has_value\" << std::endl;\n//        for(const auto &[k,v]: quotes_.value()){\n//            //LOG(trace) << k <<\" = \" << v << std::endl;\n//            result_.setdefault(k, v);\n//        }\n//    }\n//\n//    return result_;\n//}\n//\n//\n/////\n///// \\brief  Constructor wrapper that deals with the Python-supplied mapping\n/////\n///// \\param  Python dict with property base pointers as keys, and quote s as value\n///// \\return\n//boost::shared_ptr<python_excess_demand_model> excess_demand_model_python_constructor(const dict &d)\n//{\n//    esl::law::property_map<quote> pm;\n//\n//    list keys = list(d.keys());\n//    list values = list(d.values());\n//\n//    for (int i = 0; i < len(keys); ++i) {\n//        extract<boost::shared_ptr<esl::law::property>> extractor(keys[i]);\n//        extract<quote> value_extractor(values[i]);\n//        if (extractor.check() && value_extractor.check()){\n//            auto key = extractor();\n//            auto value = value_extractor();\n//\n//            pm.try_emplace(to_std(key), value);\n//        }\n//    }\n//\n//    auto model_ = boost::make_shared<python_excess_demand_model>(pm);\n//    model_->methods =\n//        { python_excess_demand_model::derivative_free_root\n//        , python_excess_demand_model::derivative_free_minimization};\n//\n//    return model_;\n//}\n//\n///*\n//list get_differentiable_order_message(const excess_demand_model* e)\n//{\n//\n//    boost::shared_ptr<walras::differentiable_order_message>\n//    e->excess_demand_functions_\n//}*/\n//\n////\n//typedef std::vector<boost::shared_ptr<walras::differentiable_order_message>> messages_t;\n//\n/////\n///// \\brief  converts the list of demand messages to Python\n/////\n///// \\param e\n///// \\return\n//messages_t get_excess_demand_functions(const excess_demand_model &e)\n//{\n//    std::vector<boost::shared_ptr<walras::differentiable_order_message>> result_;\n//    for(auto m: e.excess_demand_functions_){\n//        result_.push_back(to_boost(m));\n//    }\n//    return result_;\n//}\n//\n/////\n///// \\brief  accepts Python list back to\n/////\n///// \\param e\n///// \\param l\n//void set_excess_demand_functions(excess_demand_model &e, const list& l)\n//{\n//    std::vector<boost::shared_ptr<walras::differentiable_order_message>> result_;\n//    e.excess_demand_functions_.clear();\n//    for(int i = 0; i < len(l); ++i){\n//        extract<boost::shared_ptr<python_differentiable_order_message>> extractor(l[i]);\n//        e.excess_demand_functions_.push_back(to_std(extractor()));\n//    }\n//}\n//\n//BOOST_PYTHON_MODULE(_walras)\n//{\n//    enum_<excess_demand_model::solver>(\"solver\")\n//        // TODO: implement automatic differentiation for Python\n//        //.value(\"root\", excess_demand_model::root)\n//        //.value(\"minimization\", excess_demand_model::minimization)\n//        .value(\"derivative_free_root\", excess_demand_model::derivative_free_root)\n//        .value(\"derivative_free_minimization\", excess_demand_model::derivative_free_minimization)\n//        .export_values()\n//        ;\n//\n//    class_< python_differentiable_order_message, boost::noncopyable>\n//        (\"differentiable_order_message\",\n//         init< esl::simulation::python_module::python_identity\n//              ,esl::simulation::python_module::python_identity\n//              , esl::simulation::time_point\n//              ,esl::simulation::time_point\n//              >())\n//        .add_property(\"supply\", &walras::differentiable_order_message::supply)\n//        ;\n//\n//    // expose vector of messages to Python\n//    class_<messages_t>(\"messages_t\").def(vector_indexing_suite<messages_t>() );\n//\n//    class_<python_excess_demand_model, boost::noncopyable>(\"excess_demand_model\", no_init) // non-trivial constructor\n//        .def(\"__init__\", make_constructor(&excess_demand_model_python_constructor))\n//        .def_readwrite(\"circuit_breaker\", &excess_demand_model::circuit_breaker)\n//        .def_readwrite(\"methods\", &excess_demand_model::methods)\n//        .def_readwrite(\"quotes\", &excess_demand_model::quotes)\n//        .def(\"compute_clearing_quotes\", &clear_market)\n//        .add_property(\"excess_demand_functions\", &get_excess_demand_functions, &set_excess_demand_functions)\n//        ;\n//}\n//\n//#endif\n", "meta": {"hexsha": "f3ecb68fafb16bb7a133ee948588eaedb5ac3af7", "size": 10174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "esl/economics/markets/walras/python_module_walras.cpp", "max_stars_repo_name": "vishalbelsare/ESL", "max_stars_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T12:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T10:40:29.000Z", "max_issues_repo_path": "esl/economics/markets/walras/python_module_walras.cpp", "max_issues_repo_name": "vishalbelsare/ESL", "max_issues_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-20T04:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T06:18:33.000Z", "max_forks_repo_path": "esl/economics/markets/walras/python_module_walras.cpp", "max_forks_repo_name": "vishalbelsare/ESL", "max_forks_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T15:59:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T17:28:24.000Z", "avg_line_length": 35.5734265734, "max_line_length": 131, "alphanum_fraction": 0.6269903676, "num_tokens": 2426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651622568252118, "lm_q2_score": 0.012821214148718322, "lm_q1q2_score": 0.0030324251791221963}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_CollisionHandlerFactory.hpp\n//! \\author Alex Robinson\n//! \\brief  Collision handler factory class declaration.\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include <boost/unordered_set.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_CollisionHandlerFactory.hpp\"\n#include \"MonteCarlo_AtomicRelaxationModelFactory.hpp\"\n#include \"MonteCarlo_IncoherentModelType.hpp\"\n#include \"MonteCarlo_BremsstrahlungAngularDistributionType.hpp\"\n#include \"MonteCarlo_NuclideFactory.hpp\"\n#include \"MonteCarlo_PhotoatomFactory.hpp\"\n#include \"MonteCarlo_ElectroatomFactory.hpp\"\n#include \"MonteCarlo_AtomicRelaxationModelFactory.hpp\"\n#include \"MonteCarlo_SimulationGeneralProperties.hpp\"\n#include \"MonteCarlo_SimulationNeutronProperties.hpp\"\n#include \"MonteCarlo_SimulationPhotonProperties.hpp\"\n#include \"MonteCarlo_SimulationElectronProperties.hpp\"\n#include \"Utility_ArrayString.hpp\"\n#include \"Utility_ExceptionTestMacros.hpp\"\n#include \"Utility_ExceptionCatchMacros.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\nCollisionHandlerFactory::CollisionHandlerFactory( std::ostream* os_warn )\n  : d_os_warn( os_warn )\n{\n  // Make sure the output stream is valid\n  testPrecondition( os_warn != NULL );\n}\n\n// Initialize the collision handler\n/*! \\details Make sure the simulation properties have been set \n * (in MonteCarlo::SimulationGeneralProperties etc) before running this factory\n * method. The properties can influence how this factory method behaves.\n */\nvoid CollisionHandlerFactory::initializeHandler(\n\t\t     const Teuchos::ParameterList& material_reps,\n\t\t     const Teuchos::ParameterList& cross_sections_table_info,\n\t\t     const std::string& cross_sections_xml_directory )\n{\n  // Validate the materials\n  Teuchos::ParameterList::ConstIterator it = material_reps.begin();\n\n  boost::unordered_set<Geometry::ModuleTraits::InternalCellHandle> \n    material_ids;\n  \n  while( it != material_reps.end() )\n  {\n    const Teuchos::ParameterList& material_rep = \n      Teuchos::any_cast<Teuchos::ParameterList>( it->second.getAny() );\n\n    CollisionHandlerFactory::validateMaterialRep( material_rep,\n\t\t\t\t\t\t  material_ids );\n\n    ++it;\n  }\n  \n  material_ids.clear();\n\n  // Validate the material ids\n  this->validateMaterialIds( material_reps );\n  \n  // Extract the cross section table alias map\n  Teuchos::ParameterList alias_map_list;\n  \n  try{\n    alias_map_list = cross_sections_table_info.sublist( \"alias map\" );\n  }\n  EXCEPTION_CATCH_AND_EXIT( std::exception, \n\t\t\t    \"Error: The cross_sections.xml file in \" \n\t\t\t    << cross_sections_xml_directory << \n\t\t\t    \" is invalid - the 'alias_map' ParameterList \"\n\t\t\t    \"is not defined!\" );\n  \n  // Create the set of all nuclides/atoms needed to construct materials\n  boost::unordered_set<std::string> aliases;\n\n  CollisionHandlerFactory::createAliasSet( material_reps, \n\t\t\t\t\t   alias_map_list,\n\t\t\t\t\t   aliases );\n\n  // Create the material id data maps\n  boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                       Teuchos::Array<double> > material_id_fraction_map;\n  boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                       Teuchos::Array<std::string> > material_id_component_map;\n  \n  CollisionHandlerFactory::createMaterialIdDataMaps( \n\t\t\t\t\t\t   material_reps,\n\t\t\t\t\t\t   material_id_fraction_map,\n\t\t\t\t\t\t   material_id_component_map );\n\n  // Create the cell id data maps\n  boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n\t\t       std::vector<std::string> > cell_id_mat_id_map;\n  \n  boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n\t\t       std::vector<std::string> > cell_id_density_map;\n\n  this->createCellIdDataMaps( cell_id_mat_id_map, cell_id_density_map );\n\n  // Initialize an atomic relaxation model factory\n  Teuchos::RCP<AtomicRelaxationModelFactory> atomic_relaxation_model_factory(\n\t\t\t\t\t    new AtomicRelaxationModelFactory );\n\n  // Load the cross section data\n  switch( SimulationGeneralProperties::getParticleMode() )\n  {\n  case NEUTRON_MODE:\n  {\n    this->createNeutronMaterials( cross_sections_table_info,\n\t\t\t\t  cross_sections_xml_directory,\n\t\t\t\t  material_id_fraction_map,\n\t\t\t\t  material_id_component_map,\n\t\t\t\t  aliases,\n\t\t\t\t  cell_id_mat_id_map,\n\t\t\t\t  cell_id_density_map,\n\t\t\t\t  false,\n\t\t\t\t  false );\n    break;\n  }\n  case PHOTON_MODE:\n  {\n    this->createPhotonMaterials( \n\t\t     cross_sections_table_info,\n\t\t     cross_sections_xml_directory,\n\t\t     material_id_fraction_map,\n\t\t     material_id_component_map,\n\t\t     aliases,\n\t\t     cell_id_mat_id_map,\n\t\t     cell_id_density_map,\n\t\t     atomic_relaxation_model_factory,\n\t\t     SimulationPhotonProperties::getNumberOfPhotonHashGridBins(),\n\t\t     SimulationPhotonProperties::getIncoherentModelType(),\n\t\t     SimulationPhotonProperties::getKahnSamplingCutoffEnergy(),\n\t\t     SimulationPhotonProperties::isDetailedPairProductionModeOn(),\n\t\t     SimulationPhotonProperties::isAtomicRelaxationModeOn(),\n\t\t     SimulationPhotonProperties::isPhotonuclearInteractionModeOn() );\n    break;\n  }\n  case NEUTRON_PHOTON_MODE:\n  {\n    *d_os_warn << \"Warning: Neutron-Photon mode is not fully supported!\" \n\t      << std::endl;\n    \n    this->createNeutronMaterials( cross_sections_table_info,\n\t\t\t\t  cross_sections_xml_directory,\n\t\t\t\t  material_id_fraction_map,\n\t\t\t\t  material_id_component_map,\n\t\t\t\t  aliases,\n\t\t\t\t  cell_id_mat_id_map,\n\t\t\t\t  cell_id_density_map,\n\t\t\t\t  false,\n\t\t\t\t  true );\n\n    this->createPhotonMaterials(\n\t\t     cross_sections_table_info,\n\t\t     cross_sections_xml_directory,\n\t\t     material_id_fraction_map,\n\t\t     material_id_component_map,\n\t\t     aliases,\n\t\t     cell_id_mat_id_map,\n\t\t     cell_id_density_map,\n\t\t     atomic_relaxation_model_factory,\n\t\t     SimulationPhotonProperties::getNumberOfPhotonHashGridBins(),\n\t\t     SimulationPhotonProperties::getIncoherentModelType(),\n\t\t     SimulationPhotonProperties::getKahnSamplingCutoffEnergy(),\n\t\t     SimulationPhotonProperties::isDetailedPairProductionModeOn(),\n\t\t     SimulationPhotonProperties::isAtomicRelaxationModeOn(),\n\t\t     SimulationPhotonProperties::isPhotonuclearInteractionModeOn() );\n    break;\n  }\n  case ELECTRON_MODE:\n  {\n    this->createElectronMaterials(\n\t\t     cross_sections_table_info,\n\t\t     cross_sections_xml_directory,\n\t\t     material_id_fraction_map,\n\t\t     material_id_component_map,\n\t\t     aliases,\n\t\t     cell_id_mat_id_map,\n\t\t     cell_id_density_map,\n\t\t     atomic_relaxation_model_factory,\n\t\t     SimulationElectronProperties::getNumberOfElectronHashGridBins(),\n\t\t     SimulationElectronProperties::getBremsstrahlungAngularDistributionFunction(),\n\t\t     SimulationElectronProperties::isAtomicRelaxationModeOn(),\n\t\t     SimulationElectronProperties::getElasticCutoffAngle() );\n    break;\n  }\n  default:\n    THROW_EXCEPTION( std::logic_error,\n\t\t     \"Error: \" << SimulationGeneralProperties::getParticleMode() <<\n\t\t     \" is not currently supported!\" );\n  }\t    \n}\n\n// Validate a material representation\nvoid CollisionHandlerFactory::validateMaterialRep( \n\t      const Teuchos::ParameterList& material_rep,\n\t      boost::unordered_set<Geometry::ModuleTraits::InternalCellHandle>&\n\t      material_ids )\n{\n  // Make sure the id is present\n  TEST_FOR_EXCEPTION( !material_rep.isParameter( \"Id\" ),\n\t\t      InvalidMaterialRepresentation,\n\t\t      \"Error: a material must have an id specified!\" );\n\n  // Make sure the id is unique\n  TEST_FOR_EXCEPTION( material_ids.find( material_rep.get<unsigned>( \"Id\" ) )!=\n\t\t      material_ids.end(),\n\t\t      InvalidMaterialRepresentation,\n\t\t      \"Error: a materials id must be unique (material id \"\n\t\t      << material_rep.get<unsigned>( \"Id\" ) <<\n\t\t      \" appears more than once)!\" );\n\n  material_ids.insert( material_rep.get<unsigned>( \"Id\" ) );\n\n  // Make sure the isotopes that make up the material are specified\n  TEST_FOR_EXCEPTION( !material_rep.isParameter( \"Isotopes\" ),\n\t\t      InvalidMaterialRepresentation,\n\t\t      \"Error: a material must have isotopes specified!\" );\n\n  // Make sure the isotope fractions are specified\n  TEST_FOR_EXCEPTION( !material_rep.isParameter( \"Fractions\" ),\n\t\t      InvalidMaterialRepresentation,\n\t\t      \"Error: a material must have isotope fractions \"\n\t\t      \"specified!\" );\n}\n\n// Create the set of all nuclides/atoms needed to construct materials\nvoid CollisionHandlerFactory::createAliasSet( \n\t\t       const Teuchos::ParameterList& material_reps,\n\t\t       const Teuchos::ParameterList& cross_sections_alias_map,\n\t\t       boost::unordered_set<std::string>& nuclides )\n{\n  Teuchos::ParameterList::ConstIterator it = material_reps.begin();\n\n  while( it != material_reps.end() )\n  {\n    const Teuchos::ParameterList& material_rep = \n      Teuchos::any_cast<Teuchos::ParameterList>( it->second.getAny() );\n\n    const Teuchos::Array<std::string>& material_isotopes = \n      material_rep.get<Teuchos::Array<std::string> >( \"Isotopes\" );\n\n    for( unsigned i = 0; i < material_isotopes.size(); ++i )\n    {\n      // The name is a key - store the mapped name\n      if( cross_sections_alias_map.isParameter( material_isotopes[i] ) )\n      {\n\tstd::string mapped_alias;\n\ttry{ \n\t  mapped_alias = \n\t    cross_sections_alias_map.get<std::string>( material_isotopes[i] );\n        }\n\tEXCEPTION_CATCH_AND_EXIT( Teuchos::Exceptions::InvalidParameter,\n\t\t\t\t  \"Error: cross section alias map entry \"\n\t\t\t\t  << material_isotopes[i] <<\n\t\t\t\t  \"is invalid! Please fix this entry.\" );\n\n\tnuclides.insert( mapped_alias );\t   \n      }\n      // The name is not a key - store the name\n      else\n\tnuclides.insert( material_isotopes[i] );\n    }\n    \n    ++it;\n  }\n}\n\n// Create the material id data maps\nvoid CollisionHandlerFactory::createMaterialIdDataMaps(\n     const Teuchos::ParameterList& material_reps,\n     boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                          Teuchos::Array<double> >& material_id_fraction_map,\n     boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                       Teuchos::Array<std::string> >& material_id_component_map )\n{\n  Teuchos::ParameterList::ConstIterator it = material_reps.begin();\n\n  while( it != material_reps.end() )\n  {\n    const Teuchos::ParameterList& material_rep = \n      Teuchos::any_cast<Teuchos::ParameterList>( it->second.getAny() );\n    \n    const Utility::ArrayString& array_string = \n      material_rep.get<Utility::ArrayString>( \"Fractions\" );\n\n    Teuchos::Array<double> material_fractions;\n\n    try{\n      material_fractions = array_string.getConcreteArray<double>();\n    }\n    EXCEPTION_CATCH_RETHROW_AS( Teuchos::InvalidArrayStringRepresentation,\n\t\t\t\tInvalidMaterialRepresentation,\n\t\t\t\t\"Error: The fractions requested for \"\n\t\t\t\t\"material \" << material_rep.name() << \n\t\t\t\t\" are not valid!\" );      \n\n    const Teuchos::Array<std::string>& material_isotopes = \n      material_rep.get<Teuchos::Array<std::string> >( \"Isotopes\" );\n\n    TEST_FOR_EXCEPTION( material_fractions.size() != material_isotopes.size(),\n\t\t\tInvalidMaterialRepresentation,\n\t\t\t\"Error: The number of fractions does not \"\n\t\t\t\"equal the number of isotopes in material \"\n\t\t\t<< material_rep.name() << \"!\" );\n\n    material_id_fraction_map[material_rep.get<unsigned>( \"Id\" )] = \n      material_fractions;\n\n    material_id_component_map[material_rep.get<unsigned>( \"Id\" )] = \n      material_isotopes;\n    \n    ++it;\n  }\n}\n\n// Create the neutron materials\nvoid CollisionHandlerFactory::createNeutronMaterials( \n   const Teuchos::ParameterList& cross_sections_table_info,\n   const std::string& cross_sections_xml_directory,\n   const boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                            Teuchos::Array<double> >& material_id_fraction_map,\n   const boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                      Teuchos::Array<std::string> >& material_id_component_map,\n   const boost::unordered_set<std::string>& nuclide_aliases,\n   const boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n                              std::vector<std::string> >& cell_id_mat_id_map,\n   const boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n                               std::vector<std::string> >& cell_id_density_map,\n   const bool use_unresolved_resonance_data,\n   const bool use_photon_production_data )\n{\n  // Load the nuclides of interest\n  NuclideFactory nuclide_factory( cross_sections_xml_directory,\n\t\t\t\t  cross_sections_table_info,\n\t\t\t\t  nuclide_aliases,\n\t\t\t\t  use_unresolved_resonance_data,\n\t\t\t\t  use_photon_production_data,\n\t\t\t\t  d_os_warn );\n\n  boost::unordered_map<std::string,Teuchos::RCP<Nuclide> > nuclide_map;\n\n  nuclide_factory.createNuclideMap( nuclide_map );\n\n  // Create the material name data maps\n  boost::unordered_map<std::string,Teuchos::RCP<NeutronMaterial> >\n    material_name_pointer_map;\n  \n  boost::unordered_map<std::string,\n                   Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >\n    material_name_cell_ids_map;\n\n  CollisionHandlerFactory::createMaterialNameDataMaps( \n\t\t\t\t\t\t  material_id_fraction_map,\n\t\t\t\t\t\t  material_id_component_map,\n\t\t\t\t\t\t  nuclide_map,\n\t\t\t\t\t\t  cell_id_mat_id_map,\n\t\t\t\t\t\t  cell_id_density_map,\n\t\t\t\t\t\t  material_name_pointer_map,\n\t\t\t\t\t\t  material_name_cell_ids_map );\n\n  // Register materials with the collision handler\n  CollisionHandlerFactory::registerMaterials( material_name_pointer_map,\n\t\t\t\t\t      material_name_cell_ids_map );\n}\n\n// Create the photon materials\nvoid CollisionHandlerFactory::createPhotonMaterials(\n   const Teuchos::ParameterList& cross_sections_table_info,\n   const std::string& cross_sections_xml_directory,\n   const boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                            Teuchos::Array<double> >& material_id_fraction_map,\n   const boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n                      Teuchos::Array<std::string> >& material_id_component_map,\n   const boost::unordered_set<std::string>& photoatom_aliases,\n   const boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n                              std::vector<std::string> >& cell_id_mat_id_map,\n   const boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n                               std::vector<std::string> >& cell_id_density_map,\n   const Teuchos::RCP<AtomicRelaxationModelFactory>& \n   atomic_relaxation_model_factory,\n   const unsigned hash_grid_bins,\n   const IncoherentModelType incoherent_model,\n   const double kahn_sampling_cutoff_energy,\n   const bool use_detailed_pair_production_data,\n   const bool use_atomic_relaxation_data,\n   const bool use_photonuclear_data )\n{\n  boost::unordered_map<std::string,Teuchos::RCP<Photoatom> > photoatom_map;\n\n  // Load the photonuclides of interest\n  if( use_photonuclear_data )\n  {\n    THROW_EXCEPTION( std::logic_error,\n\t\t     \"Error: Photonuclear data is not currently supported!\" );\n  }\n  // Load the photoatoms of interest\n  else\n  {\n    PhotoatomFactory photoatom_factory( cross_sections_xml_directory,\n\t\t\t\t\tcross_sections_table_info,\n\t\t\t\t\tphotoatom_aliases,\n\t\t\t\t\tatomic_relaxation_model_factory,\n\t\t\t\t\thash_grid_bins,\n\t\t\t\t\tincoherent_model,\n\t\t\t\t\tkahn_sampling_cutoff_energy,\n\t\t\t\t\tuse_detailed_pair_production_data,\n\t\t\t\t\tuse_atomic_relaxation_data,\n\t\t\t\t\td_os_warn );\n    \n    photoatom_factory.createPhotoatomMap( photoatom_map );\n  }\n\n  // Create the material name data maps\n  boost::unordered_map<std::string,Teuchos::RCP<PhotonMaterial> >\n    material_name_pointer_map;\n  \n  boost::unordered_map<std::string,\n                   Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >\n    material_name_cell_ids_map;\n\n  CollisionHandlerFactory::createMaterialNameDataMaps( \n\t\t\t\t\t\t  material_id_fraction_map,\n\t\t\t\t\t\t  material_id_component_map,\n\t\t\t\t\t\t  photoatom_map,\n\t\t\t\t\t\t  cell_id_mat_id_map,\n\t\t\t\t\t\t  cell_id_density_map,\n\t\t\t\t\t\t  material_name_pointer_map,\n\t\t\t\t\t\t  material_name_cell_ids_map );\n\n  // Register materials with the collision handler\n  CollisionHandlerFactory::registerMaterials( material_name_pointer_map,\n\t\t\t\t\t      material_name_cell_ids_map );\n}\n\n// Create the electron materials\nvoid CollisionHandlerFactory::createElectronMaterials(\n   const Teuchos::ParameterList& cross_sections_table_info,\n   const std::string& cross_sections_xml_directory,\n   const boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n   Teuchos::Array<double> >& material_id_fraction_map,\n   const boost::unordered_map<ModuleTraits::InternalMaterialHandle,\n   Teuchos::Array<std::string> >& material_id_component_map,\n   const boost::unordered_set<std::string>& electroatom_aliases,\n   const boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n   std::vector<std::string> >& cell_id_mat_id_map,\n   const boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,\n   std::vector<std::string> >& cell_id_density_map,\n   const Teuchos::RCP<AtomicRelaxationModelFactory>& \n    atomic_relaxation_model_factory,\n   const unsigned hash_grid_bins,\n   const BremsstrahlungAngularDistributionType photon_distribution_function,\n   const bool use_atomic_relaxation_data,\n   const double cutoff_angle )\n{\n  boost::unordered_map<std::string,Teuchos::RCP<Electroatom> > electroatom_map;\n\n  ElectroatomFactory electroatom_factory( cross_sections_xml_directory,\n                                          cross_sections_table_info,\n\t\t\t\t\t                      electroatom_aliases,\n                                          atomic_relaxation_model_factory,\n                                          hash_grid_bins,\n                                          photon_distribution_function,\n                                          use_atomic_relaxation_data,\n                                          cutoff_angle,\n\t\t\t\t\t  d_os_warn );\n    \n  electroatom_factory.createElectroatomMap( electroatom_map );\n\n  // Create the material name data maps\n  boost::unordered_map<std::string,Teuchos::RCP<ElectronMaterial> >\n    material_name_pointer_map;\n  \n  boost::unordered_map<std::string,\n                   Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >\n    material_name_cell_ids_map;\n\n  CollisionHandlerFactory::createMaterialNameDataMaps( \n\t\t\t\t\t\t  material_id_fraction_map,\n\t\t\t\t\t\t  material_id_component_map,\n\t\t\t\t\t\t  electroatom_map,\n\t\t\t\t\t\t  cell_id_mat_id_map,\n\t\t\t\t\t\t  cell_id_density_map,\n\t\t\t\t\t\t  material_name_pointer_map,\n\t\t\t\t\t\t  material_name_cell_ids_map );\n\n  // Register materials with the collision handler\n  CollisionHandlerFactory::registerMaterials( material_name_pointer_map,\n                                              material_name_cell_ids_map );\n}\n\n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_CollisionHandlerFactory.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "6f2e3fbed31171134f46c1740b33d7d3c359842a", "size": 18846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_CollisionHandlerFactory.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_CollisionHandlerFactory.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_CollisionHandlerFactory.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": 37.025540275, "max_line_length": 84, "alphanum_fraction": 0.7085853762, "num_tokens": 4050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561048856673274, "lm_q2_score": 0.018546562443914547, "lm_q1q2_score": 0.0028952090098292283}}
{"text": "/*\n * LEGAL NOTICE\n * This computer software was prepared by Battelle Memorial Institute,\n * hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n * with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n * CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n * LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n * sentence must appear on any copies of this computer software.\n * \n * EXPORT CONTROL\n * User agrees that the Software will not be shipped, transferred or\n * exported into any country or used in any manner prohibited by the\n * United States Export Administration Act or any other applicable\n * export laws, restrictions or regulations (collectively the \"Export Laws\").\n * Export of the Software may require some form of license or other\n * authority from the U.S. Government, and failure to obtain such\n * export control license may result in criminal liability under\n * U.S. laws. In addition, if the Software is identified as export controlled\n * items under the Export Laws, User represents and warrants that User\n * is not a citizen, or otherwise located within, an embargoed nation\n * (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n *     and that User is not otherwise prohibited\n * under the Export Laws from receiving the Software.\n * \n * Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n * Distributed as open-source under the terms of the Educational Community \n * License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n * \n * For further details, see: http://www.globalchange.umd.edu/models/gcam/\n * \n */\n\n/*! \n* \\file get_glm_data.h\n* \\ingroup Objects\n* \\brief The GetGLMData class source file.\n*\n* \\author Pralit Patel\n* \\author Sonny Kim\n*/\n\n#include <boost/lexical_cast.hpp>\n\n#include \"util/base/include/definitions.h\"\n\n#include \"reporting/include/get_glm_data.h\"\n#include \"containers/include/region.h\"\n#include \"land_allocator/include/land_leaf.h\"\n#include \"land_allocator/include/aland_allocator_item.h\"\n#include \"technologies/include/ag_production_technology.h\"\n#include \"ccarbon_model/include/icarbon_calc.h\"\n#include \"containers/include/scenario.h\"\n#include \"util/base/include/model_time.h\"\n\nusing namespace std;\nusing namespace objects;\n\nextern Scenario* scenario;\n\n//! Default Constructor\nGetGLMData::GetGLMData()\n{\n     //TODO: Hard coding renames here for the moment.  These should be read-in\n     // through data or otherwise set exogenously to allow felxability in changes\n     // to regional or land cover categorization.\n     // mRegionMap[ GCAM Region ] = GLM Region\n     mRegionMap[ \"USA\" ] = \"USA\";\n     mRegionMap[ \"Canada\" ] = \"Canada\";\n     mRegionMap[ \"Western Europe\" ] = \"Western Europe\";\n     mRegionMap[ \"Japan\" ] = \"Japan\";\n     mRegionMap[ \"Australia_NZ\" ] = \"Australia_NZ\";\n     mRegionMap[ \"Former Soviet Union\" ] = \"Former Soviet Union\";\n     mRegionMap[ \"China\" ] = \"China\";\n     mRegionMap[ \"Middle East\" ] = \"Middle East\";\n     mRegionMap[ \"Africa\" ] = \"Africa\";\n     mRegionMap[ \"Latin America\" ] = \"Latin America\";\n     mRegionMap[ \"Southeast Asia\" ] = \"Southeast Asia\";\n     mRegionMap[ \"Eastern Europe\" ] = \"Eastern Europe\";\n     mRegionMap[ \"Korea\" ] = \"Korea\";\n     mRegionMap[ \"India\" ] = \"India\";\n\n     mLandMap[ \"biomass\" ] = \"Cropland\";\n     mLandMap[ \"eucalyptus\" ] = \"Cropland\";\n     mLandMap[ \"miscanthus\" ] = \"Cropland\";\n     mLandMap[ \"willow\" ] = \"Cropland\";\n     mLandMap[ \"Jatropha\" ] = \"Cropland\";\n\n     mLandMap[ \"Corn\" ] = \"Cropland\";\n     mLandMap[ \"FiberCrop\" ] = \"Cropland\";\n     mLandMap[ \"OtherArableLand\" ] = \"Cropland\";\n     mLandMap[ \"OtherGrain\" ] = \"Cropland\";\n     mLandMap[ \"Rice\" ] = \"Cropland\";\n     mLandMap[ \"SugarCrop\" ] = \"Cropland\";\n     mLandMap[ \"Wheat\" ] = \"Cropland\";\n\n     mLandMap[ \"OilCrop\" ] = \"Cropland\";\n     mLandMap[ \"PalmFruit\" ] = \"Cropland\";\n\n     mLandMap[ \"MiscCrop\" ] = \"Cropland\";\n     mLandMap[ \"Root_Tuber\" ] = \"Cropland\";\n\n     mLandMap[ \"FodderHerb\" ] = \"Cropland\";\n     mLandMap[ \"FodderGrass\" ] = \"Cropland\";\n\n     mLandMap[ \"Forest\" ] = \"Forest\";\n     mLandMap[ \"UnmanagedForest\" ] = \"Forest\";\n\n     mLandMap[ \"Grassland\" ] = \"Grassland\";\n     mLandMap[ \"Shrubland\" ] = \"Grassland\";\n     mLandMap[ \"Tundra\" ] = \"Grassland\";\n\n     mLandMap[ \"Pasture\" ] = \"Pasture\";\n     mLandMap[ \"UnmanagedPasture\" ] = \"Pasture\";\n\n     mLandMap[ \"UrbanLand\" ] = \"Build-up\";\n\n     mLandMap[ \"RockIceDesert\" ] = \"Other Land\";\n\n     // Crop name mapping for crop production\n     mCropMap[ \"Forest\" ] = \"Forest\";\n\n     // Land name mapping for carbon densities\n     // TODO: create these mappings\n}\n\n/*!\n * \\brief Get the land cover for a given GLM region and land category in the given year.\n * \\details If data was requested for and unknown region/AEZ/category/year -1 will be returned.\n * \\param aGLMRegionName A region name.\n * \\param aAEZ The AEZ number.\n * \\param aGLMLandCategory A land cover category.\n * \\param aYear A GCAM model year in which to get data.  TODO: do we want to allow interpolating?\n * \\return The requested land cover or -1 for error.\n */\ndouble GetGLMData::getLandCover( const string& aGLMRegionName,\n                                 const int aAEZ,\n                                 const string& aGLMLandCategory,\n                                 const int aYear ) const\n{\n    const Modeltime* modeltime = scenario->getModeltime();\n    const int modelPeriod = modeltime->getyr_to_per( aYear );\n    if( modelPeriod == 0 ) {\n        return -1;\n    }\n    RegAEZLandMap::const_iterator regionIt = mLandCoverData.find( aGLMRegionName );\n    if( regionIt != mLandCoverData.end() ) {\n        map<int, map<string, PeriodVector<double> > >::const_iterator aezIt = \n            (*regionIt).second.find( aAEZ );\n        if( aezIt != (*regionIt).second.end() ) {\n            map<string, PeriodVector<double> >::const_iterator categoryIt = \n                (*aezIt).second.find( aGLMLandCategory );\n            if( categoryIt != (*aezIt).second.end() ) {\n                return (*categoryIt).second[ modelPeriod ];\n            }\n        }\n    }\n\n    // Did not find the region/category\n    return -1;\n}\n\n/*!\n * \\brief Get the crop production in carbon for a given GLM region and category in the given year.\n * \\details If data was requested for and unknown region/AEZ/category/year -1 will be returned.\n * \\param aGLMRegionName A region name.\n * \\param aAEZ The AEZ number.\n * \\param aGLMLandCategory A crop category.\n * \\param aYear A GCAM model year in which to get data.  TODO: do we want to allow interpolating?\n * \\return The requested crop production or -1 for error.\n * \\warning Only Forest is currently available and it's units are in tC.\n */\ndouble GetGLMData::getProductionInCarbon( const string& aGLMRegionName,\n                                          const int aAEZ,\n                                          const string& aGLMCrop,\n                                          const int aYear ) const\n{\n    const Modeltime* modeltime = scenario->getModeltime();\n    const int modelPeriod = modeltime->getyr_to_per( aYear );\n    if( modelPeriod == 0 ) {\n        return -1;\n    }\n    RegAEZLandMap::const_iterator regionIt = mProductionData.find( aGLMRegionName );\n    if( regionIt != mProductionData.end() ) {\n        map<int, map<string, PeriodVector<double> > >::const_iterator aezIt = \n            (*regionIt).second.find( aAEZ );\n        if( aezIt != (*regionIt).second.end() ) {\n            map<string, PeriodVector<double> >::const_iterator categoryIt = \n                (*aezIt).second.find( aGLMCrop );\n            if( categoryIt != (*aezIt).second.end() ) {\n                return (*categoryIt).second[ modelPeriod ];\n            }\n        }\n    }\n\n    // Did not find the region/category\n    return -1;\n}\n\n/*!\n * \\brief Get the above and below carbon densities for a given GLM region and land category in the given year.\n * \\details If data was requested for and unknown region/AEZ/category/year -1 will be returned.\n * \\param aGLMRegionName A region name.\n * \\param aAEZ The AEZ number.\n * \\param aGLMLandCategory A land cover category.\n * \\param aYear A GCAM model year in which to get data.  TODO: do we want to allow interpolating?\n * \\return A pair of (above, below) carbon densities.  In case of error both values with be -1.\n */\npair<double, double> GetGLMData::getCarbonDensity( const string& aGLMRegionName,\n                                                   const int aAEZ,\n                                                   const string& aGLMLandCategory,\n                                                   const int aYear ) const\n{\n    CarbonDensityMap::const_iterator regionIt = mCarbonDensityData.find( aGLMRegionName );\n    if( regionIt != mCarbonDensityData.end() ) {\n        map<int, map<string, map<int, pair<double, double> > > >::const_iterator aezIt = \n            (*regionIt).second.find( aAEZ );\n        if( aezIt != (*regionIt).second.end() ) {\n            map<string, map<int, pair<double, double> > >::const_iterator categoryIt = \n                (*aezIt).second.find( aGLMLandCategory );\n            if( categoryIt != (*aezIt).second.end() ) {\n                map<int, pair<double, double> >::const_iterator yearIt = \n                    (*categoryIt).second.find( aYear );\n                if( yearIt != (*categoryIt).second.end() ) {\n                    return (*yearIt).second;\n                }\n            }\n        }\n    }\n\n    // Did not find the region/category\n    return make_pair<double, double>( -1, -1 );\n}\n\nvoid GetGLMData::startVisitRegion( const Region* aRegion, const int aPeriod ) {\n    // Store GLM region for later use when we have data to store\n    mCurrentGLMRegionName = doMapLookup( mRegionMap, aRegion->getName() );\n}\n\nvoid GetGLMData::startVisitLandLeaf( const LandLeaf* aLandLeaf, const int aPeriod ) {\n    const Modeltime* modeltime = scenario->getModeltime();\n    // Allow summing of individual periods or all periods (the -1 flag)\n    const int startPeriod = aPeriod == -1 ? 0 : aPeriod;\n    const int endPeriod = aPeriod == -1 ? modeltime->getmaxper() - 1 : aPeriod;\n    pair<string, int> nameAEZ = parseTypeAndAEZFromName( aLandLeaf->getName() );\n    PeriodVector<double>& data = mLandCoverData[ mCurrentGLMRegionName ][ nameAEZ.second ][ doMapLookup( mLandMap, nameAEZ.first ) ];\n    for( int period = startPeriod; period <= endPeriod; ++period ) {\n        data[ period ] += aLandLeaf->getLandAllocation( aLandLeaf->getName(), period );\n    }\n\n    // TODO: behavior if different GCAM land types that are mapped to the same GLM land type\n    // have different carbon densities this will likely not give the expeceted result.\n    map<int, pair<double, double> >& carbonDensities = mCarbonDensityData[ mCurrentGLMRegionName ][ nameAEZ.second ][ doMapLookup( mLandMapForDensities, nameAEZ.first ) ];\n    const int startYear = modeltime->getper_to_yr( startPeriod );\n    const int endYear = modeltime->getper_to_yr( endPeriod );\n    for( int year = startYear; year <= endYear; ++year ) {\n        pair<double, double>& density = carbonDensities[ year ];\n        density.first = aLandLeaf->getCarbonContentCalc()->getActualAboveGroundCarbonDensity( year );\n        density.second = aLandLeaf->getCarbonContentCalc()->getActualBelowGroundCarbonDensity( year );\n    }\n}\n\nvoid GetGLMData::startVisitAgProductionTechnology( const AgProductionTechnology* aAgTech, const int aPeriod ) {\n    pair<string, int> nameAEZ = parseTypeAndAEZFromName( aAgTech->getName() );\n    if( nameAEZ.first == \"Forest\" ) {\n        // Note the hard coding of the forest to carbon conversion factor\n        // The output of the forest technology is in billion m^3 and we want\n        // the production in tC so this conversion factor is tC / billion m^3\n        const double B_CUBIC_METER_FOREST_TO_CARBON = 0.288 * 1e9;\n\n        const Modeltime* modeltime = scenario->getModeltime();\n        // Technologies have special behavior when visiting such that aPeriod is really\n        // the end period and we must loop from 0.\n        PeriodVector<double>& data = mProductionData[ mCurrentGLMRegionName ][ nameAEZ.second ][ doMapLookup( mCropMap, nameAEZ.first ) ];\n        for( int period = 0; period <= aPeriod; ++period ) {\n            data[ period ] +=\n                aAgTech->getOutput( period ) * B_CUBIC_METER_FOREST_TO_CARBON;\n        }\n    }\n}\n\n/*!\n * \\brief A helper method to do a rename lookup from a GCAM name to a GLM name.\n * \\details If an explicit rename was not provided the GCAM name will be used.\n * \\param The name lookup map.\n * \\param The name to translate.\n * \\return The GLM name if a lookup exists otherwise just the GCAM name.\n */\nconst string& GetGLMData::doMapLookup( const map<string, string>& aLookupMap, const string& aKey ) {\n    map<string, string>::const_iterator lookupIt = aLookupMap.find( aKey );\n    if( lookupIt != aLookupMap.end() ) {\n        return (*lookupIt).second;\n    }\n    else {\n        // TODO: warn?\n        return aKey;\n    }\n}\n\npair<string, int> GetGLMData::parseTypeAndAEZFromName( const string& aGCAMName ) {\n    size_t index = aGCAMName.find( \"AEZ\" );\n    if( index == string::npos ) {\n        // TODO: warn?\n        return make_pair<string, int>( aGCAMName, 0 );\n    }\n    else {\n        string typeName( aGCAMName, 0, index);\n        string aezStr( aGCAMName, index + 3, string::npos );\n        int aez = boost::lexical_cast<int>( aezStr );\n        return make_pair<string, int>( typeName, aez );\n    }\n}\n\n", "meta": {"hexsha": "044c0afa011e168a2b719d2e20784da28adb1865", "size": 13449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/lnd/clm/src/iac/giac/gcam/cvs/objects/reporting/source/get_glm_data.cpp", "max_stars_repo_name": "E3SM-Project/iESM", "max_stars_repo_head_hexsha": "2a1013a3d85a11d935f1b2a8187a8bbcd75d115d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-05-15T02:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T18:27:31.000Z", "max_issues_repo_path": "models/lnd/clm/src/iac/giac/gcam/cvs/objects/reporting/source/get_glm_data.cpp", "max_issues_repo_name": "zhangyue292/iESM", "max_issues_repo_head_hexsha": "2a1013a3d85a11d935f1b2a8187a8bbcd75d115d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-12T18:41:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-12T15:18:49.000Z", "max_forks_repo_path": "models/lnd/clm/src/iac/giac/gcam/cvs/objects/reporting/source/get_glm_data.cpp", "max_forks_repo_name": "zhangyue292/iESM", "max_forks_repo_head_hexsha": "2a1013a3d85a11d935f1b2a8187a8bbcd75d115d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T02:10:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T17:45:49.000Z", "avg_line_length": 42.9680511182, "max_line_length": 171, "alphanum_fraction": 0.6524648673, "num_tokens": 3516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203223393803666, "lm_q2_score": 0.018546562749059203, "lm_q1q2_score": 0.002819675366611445}}
{"text": "//=============================================================================================================\n/**\n* @file     fiff_coord_trans_old.cpp\n* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     January, 2017\n*\n* @section  LICENSE\n*\n* Copyright (C) 2017, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Implementation of the FiffCoordTransOld Class.\n*\n*/\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"fiff_coord_trans_old.h\"\n\n#include <fiff/fiff_tag.h>\n\n#include <QFile>\n\n\n#include <Eigen/Dense>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace Eigen;\nusing namespace FIFFLIB;\nusing namespace FIFFLIB;\n\n\n\n\n#ifndef TRUE\n#define TRUE 1\n#endif\n\n#ifndef FALSE\n#define FALSE 0\n#endif\n\n\n#ifndef FAIL\n#define FAIL -1\n#endif\n\n#ifndef OK\n#define OK 0\n#endif\n\n\n\n#define X_20 0\n#define Y_20 1\n#define Z_20 2\n\n\n\n#define FREE_20(x) if ((char *)(x) != NULL) free((char *)(x))\n\n\n#define MALLOC_20(x,t) (t *)malloc((x)*sizeof(t))\n\n\n\n#define MAXWORD 1000\n\n\nstatic void skip_comments(FILE *in)\n\n{\n    int c;\n\n    while (1) {\n        c = fgetc(in);\n        if (c == '#') {\n            for (c = fgetc(in); c != EOF && c != '\\n'; c = fgetc(in))\n                ;\n        }\n        else {\n            ungetc(c,in);\n            return;\n        }\n    }\n}\n\n\nstatic int whitespace(int c)\n\n{\n    if (c == '\\t' || c == '\\n' || c == ' ')\n        return TRUE;\n    else\n        return FALSE;\n}\n\nstatic int whitespace_quote(int c, int inquote)\n\n{\n    if (inquote)\n        return (c == '\"');\n    else\n        return (c == '\\t' || c == '\\n' || c == ' ');\n}\n\n\nstatic char *next_word_20(FILE *in)\n\n{\n    char *next = MALLOC_20(MAXWORD,char);\n    int c;\n    int  p,k;\n    int  inquote;\n\n    skip_comments(in);\n\n    inquote = FALSE;\n    for (k = 0, p = 0, c = fgetc(in); c != EOF && !whitespace_quote(c,inquote) ; c = fgetc(in), k++) {\n        if (k == 0 && c == '\"')\n            inquote = TRUE;\n        else\n            next[p++] = c;\n    }\n    if (c == EOF && k == 0) {\n        FREE_20(next);\n        return NULL;\n    }\n    else\n        next[p] = '\\0';\n    if (c != EOF) {\n        for (k = 0, c = fgetc(in); whitespace(c) ; c = fgetc(in), k++)\n            ;\n        if (c != EOF)\n            ungetc(c,in);\n    }\n#ifdef DEBUG\n    if (next)\n        printf(\"<%s>\\n\",next);\n#endif\n    return next;\n}\n\n\nstatic int get_fval_20(FILE *in, float *fval)\n{\n    char *next = next_word_20(in);\n    if (next == NULL) {\n        qWarning(\"bad integer\");\n        return FAIL;\n    }\n    else if (sscanf(next,\"%g\",fval) != 1) {\n        qWarning(\"bad floating point number : %s\",next);\n        FREE_20(next);\n        return FAIL;\n    }\n    FREE_20(next);\n    return OK;\n}\n\n\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nFiffCoordTransOld::FiffCoordTransOld()\n{\n\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld::FiffCoordTransOld(const FiffCoordTransOld &p_FiffCoordTransOld)\n{\n    this->from = p_FiffCoordTransOld.from;\n    this->to = p_FiffCoordTransOld.to;\n\n    for (int j = 0; j < 3; j++) {\n        this->move[j] = p_FiffCoordTransOld.move[j];\n        this->invmove[j] = p_FiffCoordTransOld.invmove[j];\n        for (int k = 0; k < 3; k++) {\n            this->rot(j,k) = p_FiffCoordTransOld.rot(j,k);\n            this->invrot(j,k) = p_FiffCoordTransOld.invrot(j,k);\n        }\n    }\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::catenate(FiffCoordTransOld *t1, FiffCoordTransOld *t2)\n{\n    FiffCoordTransOld* t = new FiffCoordTransOld;\n    int j,k,p;\n\n    t->to   = t1->to;\n    t->from = t2->from;\n\n    for (j = 0; j < 3; j++) {\n        t->move[j] = t1->move[j];\n        for (k = 0; k < 3; k++) {\n            t->rot(j,k) = 0.0;\n            t->move[j] += t1->rot(j,k)*t2->move[k];\n            for (p = 0; p < 3; p++)\n                t->rot(j,k) += t1->rot(j,p)*t2->rot(p,k);\n        }\n    }\n    add_inverse(t);\n    return (t);\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld::FiffCoordTransOld(int from, int to, float rot[3][3], float move[3])\n{\n    this->from = from;\n    this->to   = to;\n\n    for (int j = 0; j < 3; j++) {\n        this->move[j] = move[j];\n        for (int k = 0; k < 3; k++)\n            this->rot(j,k) = rot[j][k];\n    }\n    add_inverse(this);\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld::~FiffCoordTransOld()\n{\n\n}\n\n\n//*************************************************************************************************************\n\nint FiffCoordTransOld::add_inverse(FiffCoordTransOld *t)\n{\n    int   j,k;\n    Matrix4f m;\n\n    for (j = 0; j < 3; j++) {\n        for (k = 0; k < 3; k++)\n            m(j,k) = t->rot(j,k);\n        m(j,3) = t->move[j];\n    }\n    for (k = 0; k < 3; k++)\n        m(3,k) = 0.0;\n    m(3,3) = 1.0;\n\n    m = m.inverse().eval();\n\n    for (j = 0; j < 3; j++) {\n        for (k = 0; k < 3; k++)\n            t->invrot(j,k) = m(j,k);\n        t->invmove[j] = m(j,3);\n    }\n    return OK;\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::fiff_invert_transform() const\n{\n    FiffCoordTransOld* ti = new FiffCoordTransOld;\n    int j,k;\n\n    for (j = 0; j < 3; j++) {\n        ti->move[j] = this->invmove[j];\n        ti->invmove[j] = this->move[j];\n        for (k = 0; k < 3; k++) {\n            ti->rot(j,k)    = this->invrot(j,k);\n            ti->invrot(j,k) = this->rot(j,k);\n        }\n    }\n    ti->from = this->to;\n    ti->to   = this->from;\n    return (ti);\n}\n\n\n//*************************************************************************************************************\n\nvoid FiffCoordTransOld::fiff_coord_trans(float r[], const FiffCoordTransOld *t, int do_move)\n/*\n* Apply coordinate transformation\n*/\n{\n    int j,k;\n    float res[3];\n\n    for (j = 0; j < 3; j++) {\n        res[j] = (do_move ? t->move[j] :  0.0);\n        for (k = 0; k < 3; k++)\n            res[j] += t->rot(j,k)*r[k];\n    }\n    for (j = 0; j < 3; j++)\n        r[j] = res[j];\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::fiff_combine_transforms(int from, int to, FiffCoordTransOld *t1, FiffCoordTransOld *t2)\n/*\n* Combine two coordinate transformations\n* to yield a transform from 'from' system\n* to 'to' system.\n*\n* Return NULL if this fails\n*\n*/\n{\n    FiffCoordTransOld* t = NULL;\n    int swapped = 0;\n    FiffCoordTransOld* temp;\n    /*\n       * We have a total of eight possibilities:\n       * four without swapping and four with\n       */\n    while (1) {\n        if (t1->to == to && t2->from == from) {\n            t1 = new FiffCoordTransOld(*t1);\n            t2 = new FiffCoordTransOld(*t2);\n            break;\n        }\n        else if (t1->from == to && t2->from == from) {\n            FiffCoordTransOld* tmp_t1 = t1;\n            t1 = tmp_t1->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t1;\n            t2 = new FiffCoordTransOld(*t2);\n            break;\n        }\n        else if (t1->to == to && t2->to == from) {\n            t1 = new FiffCoordTransOld(*t1);\n            FiffCoordTransOld* tmp_t2 = t2;\n            t2 = tmp_t2->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t2;\n            break;\n        }\n        else if (t1->from == to && t2->to == from) {\n            FiffCoordTransOld* tmp_t1 = t1;\n            t1 = tmp_t1->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t1;\n            FiffCoordTransOld* tmp_t2 = t2;\n            t2 = tmp_t2->fiff_invert_transform();//Memory leak here!!\n            delete tmp_t2;\n            break;\n        }\n        if (swapped) {  /* Already swapped and not found */\n            qCritical(\"Cannot combine coordinate transforms\");\n            return (t);\n        }\n        temp = t1;      /* Try it swapped as well */\n        t1 = t2;\n        t2 = temp;\n        swapped = 1;\n    }\n    if (t1->from  != t2->to)    /* Transforms must match on the other side as well */\n        qCritical (\"Cannot combine coordinate transforms\");\n    else                        /* We can do it directly */\n        t = catenate(t1,t2);\n    FREE_20(t1); FREE_20(t2);\n    return (t);\n}\n\n\n//*************************************************************************************************************\n\nvoid FiffCoordTransOld::fiff_coord_trans_inv(float r[], FiffCoordTransOld *t, int do_move)\n/*\n* Apply inverse coordinate transformation\n*/\n{\n    int j,k;\n    float res[3];\n\n    for (j = 0; j < 3; j++) {\n        res[j] = (do_move ? t->invmove[j] :  0.0);\n        for (k = 0; k < 3; k++)\n            res[j] += t->invrot(j,k)*r[k];\n    }\n    for (j = 0; j < 3; j++)\n        r[j] = res[j];\n}\n\n\n//*************************************************************************************************************\n\ntypedef struct {\n    int frame;\n    const char *name;\n} frameNameRec;\n\nconst char *FiffCoordTransOld::mne_coord_frame_name(int frame)\n{\n    static frameNameRec frames[] = {\n        {FIFFV_COORD_UNKNOWN,\"unknown\"},\n        {FIFFV_COORD_DEVICE,\"MEG device\"},\n        {FIFFV_COORD_ISOTRAK,\"isotrak\"},\n        {FIFFV_COORD_HPI,\"hpi\"},\n        {FIFFV_COORD_HEAD,\"head\"},\n        {FIFFV_COORD_MRI,\"MRI (surface RAS)\"},\n        {FIFFV_MNE_COORD_MRI_VOXEL, \"MRI voxel\"},\n        {FIFFV_COORD_MRI_SLICE,\"MRI slice\"},\n        {FIFFV_COORD_MRI_DISPLAY,\"MRI display\"},\n        {FIFFV_MNE_COORD_CTF_DEVICE,\"CTF MEG device\"},\n        {FIFFV_MNE_COORD_CTF_HEAD,\"CTF/4D/KIT head\"},\n        {FIFFV_MNE_COORD_RAS,\"RAS (non-zero origin)\"},\n        {FIFFV_MNE_COORD_MNI_TAL,\"MNI Talairach\"},\n        {FIFFV_MNE_COORD_FS_TAL_GTZ,\"Talairach (MNI z > 0)\"},\n        {FIFFV_MNE_COORD_FS_TAL_LTZ,\"Talairach (MNI z < 0)\"},\n        {-1,\"unknown\"}\n    };\n    int k;\n    for (k = 0; frames[k].frame != -1; k++) {\n        if (frame == frames[k].frame)\n            return frames[k].name;\n    }\n    return frames[k].name;\n}\n\n\n//*************************************************************************************************************\n\nvoid FiffCoordTransOld::mne_print_coord_transform_label(FILE *log, char *label, FiffCoordTransOld *t)\n{\n    int k,p;\n    int frame;\n    if (!label || strlen(label) == 0)\n        fprintf(log,\"Coordinate transformation: \");\n    else\n        fprintf(log,\"%s\",label);\n    for (frame = t->from, k = 0; k < 2; k++) {\n        if (k == 0) {\n            fprintf(log,\"%s -> \",mne_coord_frame_name(frame));\n            frame = t->to;\n        }\n        else {\n            fprintf(log,\"%s\\n\",mne_coord_frame_name(frame));\n            for (p = 0; p < 3; p++)\n                fprintf(log,\"\\t% 8.6f % 8.6f % 8.6f\\t% 7.2f mm\\n\",\n                        t->rot(p,X_20),t->rot(p,Y_20),t->rot(p,Z_20),1000*t->move[p]);\n            fprintf(log,\"\\t% 8.6f % 8.6f % 8.6f  % 7.2f\\n\",0.0,0.0,0.0,1.0);\n        }\n    }\n}\n\n\n//*************************************************************************************************************\n\nvoid FiffCoordTransOld::mne_print_coord_transform(FILE *log, FiffCoordTransOld *t)\n{\n    mne_print_coord_transform_label(log,NULL,t);\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_transform(const QString &name, int from, int to)\n/*\n          * Read the specified coordinate transformation\n          */\n{\n    QFile file(name);\n    FiffStream::SPtr stream(new FiffStream(&file));\n\n\n    FiffCoordTransOld* res = NULL;\n    //    fiffFile       in = NULL;\n    FiffTag::SPtr t_pTag;\n    //    fiffTagRec     tag;\n    //    fiffDirEntry   dir;\n    fiff_int_t kind, pos;\n    int k;\n\n    //    tag.data = NULL;\n    //    if ((in = fiff_open(name.toUtf8().data())) == NULL)\n    //        goto out;\n    if(!stream->open())\n        goto out;\n\n    for (k = 0; k < stream->dir().size(); k++) {\n        kind = stream->dir()[k]->kind;\n        pos  = stream->dir()[k]->pos;\n        if (kind == FIFF_COORD_TRANS) {\n            //            if (fiff_read_this_tag (in->fd,dir->pos,&tag) == FIFF_FAIL)\n            //                goto out;\n            //            res = (fiffCoordTrans)tag.data;\n            if (!stream->read_tag(t_pTag,pos))\n                goto out;\n\n            res = FiffCoordTransOld::read_helper( t_pTag );\n            if (res->from == from && res->to == to) {\n                //                tag.data = NULL;\n                goto out;\n            }\n            else if (res->from == to && res->to == from) {\n                FiffCoordTransOld* tmp_res = res;\n                res = tmp_res->fiff_invert_transform();//Memory leak here!!\n                delete tmp_res;\n                goto out;\n            }\n            res = NULL;\n        }\n    }\n    qCritical(\"No suitable coordinate transformation found in %s.\",name.toUtf8().data());\n    goto out;\n\nout : {\n        //        FREE(tag.data);\n        //        fiff_close(in);\n        stream->close();\n        return res;\n    }\n\n    return res;\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_transform_from_node(FiffStream::SPtr &stream, const FiffDirNode::SPtr &node, int from, int to)\n/*\n* Read the specified coordinate transformation\n*/\n{\n    FiffCoordTransOld* res = NULL;\n    FiffTag::SPtr t_pTag;\n    //    fiffTagRec     tag;\n    //    fiffDirEntry   dir;\n    fiff_int_t kind, pos;\n    int k;\n\n    //    tag.data = NULL;\n    for (k = 0; k < node->nent(); k++)\n        kind = node->dir[k]->kind;\n    pos  = node->dir[k]->pos;\n    if (kind == FIFF_COORD_TRANS) {\n        //            if (fiff_read_this_tag (in->fd,dir->pos,&tag) == FIFF_FAIL)\n        //                goto out;\n        //            res = (fiffCoordTrans)tag.data;\n        if (!stream->read_tag(t_pTag,pos))\n            goto out;\n        res = FiffCoordTransOld::read_helper( t_pTag );\n        if (res->from == from && res->to == to) {\n            //                tag.data = NULL;\n            goto out;\n        }\n        else if (res->from == to && res->to == from) {\n            FiffCoordTransOld* tmp_res = res;\n            res = tmp_res->fiff_invert_transform();//Memory leak here!!\n            delete tmp_res;\n            goto out;\n        }\n        res = NULL;\n    }\n    printf(\"No suitable coordinate transformation found\");\n    goto out;\n\nout : {\n        //        FREE(tag.data);\n        return res;\n    }\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_mri_transform(const QString &name)\n/*\n          * Read the MRI -> HEAD coordinate transformation\n          */\n{\n    return mne_read_transform(name,FIFFV_COORD_MRI,FIFFV_COORD_HEAD);\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_meas_transform(const QString &name)\n/*\n* Read the MEG device -> HEAD coordinate transformation\n*/\n{\n    return mne_read_transform(name,FIFFV_COORD_DEVICE,FIFFV_COORD_HEAD);\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_transform_ascii(char *name, int from, int to)\n/*\n* Read the Neuromag -> FreeSurfer transformation matrix\n*/\n{\n    FILE *in = NULL;\n    FiffCoordTransOld* t = NULL;\n    float rot[3][3];\n    float move[3];\n    int   k;\n    float dum;\n\n    if ((in = fopen(name,\"r\")) == NULL) {\n        qCritical(name);\n        goto bad;\n    }\n    for (k = 0; k < 3; k++) {\n        if (get_fval_20(in,rot[k]+X_20) == FAIL)\n            goto noread;\n        if (get_fval_20(in,rot[k]+Y_20) == FAIL)\n            goto noread;\n        if (get_fval_20(in,rot[k]+Z_20) == FAIL)\n            goto noread;\n        if (get_fval_20(in,move+k) == FAIL)\n            goto noread;\n    }\n    for (k = 0; k < 4; k++) {\n        if (get_fval_20(in,&dum) == FAIL)\n            goto noread;\n    }\n    fclose(in);\n    for (k = 0; k < 3; k++)\n        move[k] = move[k]/1000.0;\n    t  = new FiffCoordTransOld(from, to, rot, move );\n    return t;\n\nnoread : {\n        qCritical(\"Cannot read the coordinate transformation\");\n        goto bad;\n    }\n\nbad : {\n        if(t)\n            delete t;\n        if (in != NULL)\n            fclose(in);\n        return NULL;\n    }\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::mne_read_FShead2mri_transform(char *name)\n{\n    return mne_read_transform_ascii(name,FIFFV_COORD_HEAD,FIFFV_COORD_MRI);\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::mne_identity_transform(int from, int to)\n{\n    float rot[3][3] = { { 1.0, 0.0, 0.0 },\n                        { 0.0, 1.0, 0.0 },\n                        { 0.0, 0.0, 1.0 } };\n    float move[] = { 0.0, 0.0, 0.0 };\n    return new FiffCoordTransOld(from,to,rot,move);\n}\n\n\n//*************************************************************************************************************\n\nFiffCoordTransOld *FiffCoordTransOld::read_helper( FIFFLIB::FiffTag::SPtr& tag)\n{\n    FiffCoordTransOld* p_FiffCoordTrans = NULL;\n    if(tag->isMatrix() || tag->getType() != FIFFT_COORD_TRANS_STRUCT || tag->data() == NULL)\n        return p_FiffCoordTrans;\n    else\n    {\n        p_FiffCoordTrans = new FiffCoordTransOld;\n        qint32* t_pInt32 = (qint32*)tag->data();\n        p_FiffCoordTrans->from = t_pInt32[0];\n        p_FiffCoordTrans->to = t_pInt32[1];\n\n        float* t_pFloat = (float*)tag->data();\n        int count = 0;\n        int r, c;\n        for (r = 0; r < 3; ++r) {\n            p_FiffCoordTrans->move[r] = t_pFloat[11+r];\n            for (c = 0; c < 3; ++c) {\n                p_FiffCoordTrans->rot(r,c) = t_pFloat[2+count];\n                ++count;\n            }\n        }\n\n        count = 0;\n        for (r = 0; r < 3; ++r) {\n            p_FiffCoordTrans->invmove[r] = t_pFloat[23+r];\n            for (c = 0; c < 3; ++c) {\n                p_FiffCoordTrans->invrot(r,c) = t_pFloat[14+count];\n                ++count;\n            }\n        }\n\n        return p_FiffCoordTrans;\n    }\n}\n", "meta": {"hexsha": "1ba1ee226fa436001c8482427eaa2099c8f258cf", "size": 21084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/fiff/c/fiff_coord_trans_old.cpp", "max_stars_repo_name": "13grife37/mne-cpp-swpold", "max_stars_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T20:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-26T16:30:25.000Z", "max_issues_repo_path": "MNE/fiff/c/fiff_coord_trans_old.cpp", "max_issues_repo_name": "13grife37/mne-cpp-swpold", "max_issues_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/fiff/c/fiff_coord_trans_old.cpp", "max_forks_repo_name": "13grife37/mne-cpp-swpold", "max_forks_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T15:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-23T15:55:31.000Z", "avg_line_length": 28.6467391304, "max_line_length": 141, "alphanum_fraction": 0.4596376399, "num_tokens": 5382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.010652508641112389, "lm_q1q2_score": 0.002672850630460956}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2018 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 <deque>\n#include <limits>\n#include <boost/circular_buffer.hpp>\n#include <comma/io/stream.h>\n#include <comma/csv/stream.h>\n#include <comma/csv/traits.h>\n#include \"../../visiting/traits.h\"\n\nnamespace {\n\n\nvoid bash_completion( unsigned const ac, char const * const * av )\n{\n    static char const* arguments[] =\n    {\n        \" turn decelerate\",\n        \" --binary -b --delimiter -d --fields -f --flush --format --full-xpath --help -h --quote --precision --verbose -v\",\n        \" --input-fields --output-fields --output-format\",\n        \" --deceleration -c\",\n        \" --max-acceleration\",\n        \" --min-points-separation --min-gap -g\",\n        \" --approach-speed -s\",\n        \" --sharp-turn-angle -t\",\n        \" --stop-on-sharp-turn --pivot -p\"\n    };\n    std::cout << arguments << std::endl;\n    exit( 0 );\n}\n\nvoid operations( unsigned const indent_count = 0 )\n{\n    auto const indent = std::string( indent_count, ' ' );\n    std::cerr << indent << \"decelerate; moderate sudden decreases in speed with given deceleration.\" << std::endl;\n    std::cerr << indent << \"turn; set the speed on curves in the plan based on given centripetal acceleration.\" << std::endl;\n}\n\nvoid usage( bool const verbose )\n{\n    static const char* const indent=\"    \";\n\n    std::cerr << std::endl;\n    std::cerr << \"read trajectory points, append speed moderated according to turn angle, max lateral acceleration, etc\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"Usage:\" << std::endl;\n    std::cerr << indent << comma::verbose.app_name() << \" <operation> [<options>...]\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"Operations:\" << std::endl;\n    operations(4);\n    std::cerr << std::endl;\n    std::cerr << \"Options:\" << std::endl;\n    std::cerr << \"    decelerate:\" << std::endl;\n    std::cerr << \"        --deceleration, -c=<deceleration>; deceleration by which to moderate sudden decreases in speed.\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"    turn:\" << std::endl;\n    std::cerr << \"        --approach-speed, -a=<speed>; approach with this speed for waypoints with sharp turns.\" << std::endl;\n    std::cerr << \"        --max-acceleration, -c=<acceleration>; maximum centripetal acceleration allowed.\" << std::endl;\n    std::cerr << \"        --min-points-separation, --min-gap, -g=<distance>; default=0.01; minimum distance between points for their consideration in the operation.\" << std::endl;\n    std::cerr << \"        --sharp-turn-angle, -t=<angle>; default=1.57; assign 'approach-speed' for waypoints having turn angle greater than this.\" << std::endl;\n    std::cerr << \"        --speed, -s=[<speed>]; use this speed if it is not in input fields.\" << std::endl;\n    std::cerr << \"        --stop-on-sharp-turn, --pivot, -p; on sharp turns (i.e. waypoints set with 'approach-speed'), output extra point with relative heading and no speed.\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"Info:\" << std::endl;\n    std::cerr << \"    --input-fields; print input fields to stdout and exit.\" << std::endl;\n    std::cerr << \"    --output-fields; print output fields to stdout and exit.\" << std::endl;\n    std::cerr << \"    --output-format; print output fields to stdout and exit.\" << std::endl;\n    std::cerr << std::endl;\n    if( verbose ) { std::cerr << \"Csv options:\" << std::endl << comma::csv::options::usage( \"x,y,z,speed\" ) << std::endl; }\n    else { std::cerr << \"Csv options: run --help --verbose for more info...\" << std::endl; }\n    std::cerr << std::endl;\n    std::cerr << \"Examples:\" << std::endl;\n    std::cerr << \"    ( echo '0.0,0.0'; echo '0.3,0.3'; echo '0.6,0.6'; echo '0.6,0.9'; echo '0.6,1.2'; echo '0.9,1.2'; echo '1.2,1.2'; echo '1.5,0.9'; echo '1.8,0.6' ) > trajectory.csv\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"    control-speed turn --fields=x,y --max-acceleration=0.5 --approach-speed=0.2 --speed=1 --pivot < trajectory.csv > moderated.csv\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"    control-speed decelerate --fields=x,y,speed --deceleration=0.5 < moderated.csv > decelerated.csv\" << std::endl;\n    std::cerr << std::endl;\n}\n\nnamespace generic\n{\nstruct input_t\n{\n    Eigen::Vector3d coordinates;\n    double speed;\n\n    input_t( double sp = 0.0 ) : coordinates( Eigen::Vector3d::Zero() ), speed( sp ) {}\n};\n}\n\nnamespace turn\n{\nstruct output_t\n{\n    double moderated_speed;\n    double relative_heading;\n\n    output_t( double sp = 0.0 ) : moderated_speed( sp ), relative_heading( 0.0 ) {}\n};\n\nstruct record_t\n{\n    generic::input_t input;\n    output_t output;\n    std::string line;\n    //...debug...\n    //double angle;\n    //double radius;\n\n    record_t( generic::input_t const& in, comma::csv::input_stream< generic::input_t > const& istrm, comma::csv::options const& csv )\n        : input( in )\n        , output( in.speed )\n        , line()\n        //...debug...\n        //, angle( 0 )\n        //, radius( 0 )\n    {\n        if( csv.binary() )\n        {\n            line.resize( csv.format().size() );\n            ::memcpy( &line[ 0 ], istrm.binary().last(), csv.format().size() );\n        }\n        else\n        {\n            line = comma::join( istrm.ascii().last(), csv.delimiter );\n        }\n    }\n\n    void write( comma::csv::output_stream< output_t >& ostrm, comma::csv::options const& csv )\n    {\n        ostrm.append( line, output );\n        if( csv.binary() && csv.flush ) { std::cout.flush(); }\n        //...debug...\n        //std::cerr << line << csv.delimiter << output.moderated_speed << csv.delimiter << angle << csv.delimiter << radius << std::endl;\n    }\n};\n}\n\nnamespace deceleration\n{\nstruct record_t\n{\n    generic::input_t input;\n    std::string line;\n    //...debug...\n    //double angle;\n    //double radius;\n\n    record_t( generic::input_t const& in, comma::csv::input_stream< generic::input_t > const& istrm, comma::csv::options const& csv )\n        : input( in )\n        , line()\n        //...debug...\n        //, angle( 0 )\n        //, radius( 0 )\n    {\n        if( csv.binary() )\n        {\n            line.resize( csv.format().size() );\n            ::memcpy( &line[ 0 ], istrm.binary().last(), csv.format().size() );\n        }\n        else { line = comma::join( istrm.ascii().last(), csv.delimiter ); }\n    }\n\n    void write( comma::csv::output_stream< generic::input_t >& ostrm, comma::csv::options const& csv )\n    {\n        ostrm.write( input, line );\n        if( csv.binary() && csv.flush ) { std::cout.flush(); }\n        //...debug...\n        //std::cerr << line << csv.delimiter << input.speed << csv.delimiter << angle << csv.delimiter << radius << std::endl;\n    }\n};\n}\n\nvoid handle_info_options( comma::command_line_options const& options )\n{\n    if( options.exists( \"--input-fields\" ) ) { std::cout << comma::join( comma::csv::names< generic::input_t >( false ), ',' ) << std::endl; exit( 0 ); }\n}\n\ndouble radius_calc( Eigen::Vector3d const& p1, Eigen::Vector3d const& p2, Eigen::Vector3d const& p3 )\n{\n    auto const side1 = ( p2 - p1 ).norm();\n    auto const side2 = ( p3 - p2 ).norm();\n    auto const side3 = ( p3 - p1 ).norm();\n    auto const perimeter_half = ( side1 + side2 + side3 ) / 2;\n    auto area = perimeter_half * ( perimeter_half - side1 ) * ( perimeter_half - side2 ) * ( perimeter_half - side3 ); // Heron's Equation\n\n    if( comma::math::less( 0.0, area ) )\n    {\n        area = std::sqrt( area );\n        return ( side1 * side2 * side3 ) / ( 4.0 * area );\n    }\n    else\n    {\n        return comma::math::less( side1, side3 ) && comma::math::less( side2, side3 ) ? std::numeric_limits< double >::max() : 0.0;\n    }\n}\n\ndouble angle_calc( Eigen::Vector3d const& p1, Eigen::Vector3d const& p2, Eigen::Vector3d const& p3 )\n{\n    auto angle_axis = Eigen::AngleAxis< double >( Eigen::Quaternion< double >::FromTwoVectors( p2 - p1, p3 - p2 ) );\n    //...debug...\n    //std::cerr << std::setprecision(16)\n    //          << p1.x() << ',' << p1.y() << ',' << p1.z() << ','\n    //          << p2.x() << ',' << p2.y() << ',' << p2.z() << ','\n    //          << p3.x() << ',' << p3.y() << ',' << p3.z() << ','\n    //          << angle_axis.angle() << ',' << angle_axis.axis().x() << ',' << angle_axis.axis().y() << ',' << angle_axis.axis().z() << std::endl;\n    return angle_axis.angle() * ( comma::math::less( angle_axis.axis().z(), 0.0 ) ? -1 : 1 );\n}\n\n}\n\nnamespace comma { namespace visiting {\n\ntemplate <> struct traits< generic::input_t >\n{\n    template < typename K, typename V > static void visit ( const K&, generic::input_t& t, V& v )\n    {\n        v.apply( \"coordinates\", t.coordinates );\n        v.apply( \"speed\", t.speed );\n    }\n\n    template < typename K, typename V > static void visit ( const K&, const generic::input_t& t, V& v )\n    {\n        v.apply( \"coordinates\", t.coordinates );\n        v.apply( \"speed\", t.speed );\n    }\n};\n\ntemplate <> struct traits< turn::output_t >\n{\n    template < typename K, typename V > static void visit ( const K&, turn::output_t& t, V& v )\n    {\n        v.apply( \"moderated_speed\", t.moderated_speed );\n        v.apply( \"relative_heading\", t.relative_heading );\n    }\n\n    template < typename K, typename V > static void visit ( const K&, const turn::output_t& t, V& v )\n    {\n        v.apply( \"moderated_speed\", t.moderated_speed );\n        v.apply( \"relative_heading\", t.relative_heading );\n    }\n};\n\n}}\n\nint main( int ac, char* av[] )\n{\n    try\n    {\n        comma::command_line_options options( ac, av, usage );\n        if( options.exists( \"--bash-completion\" ) ) bash_completion( ac, av );\n        handle_info_options( options );\n\n        std::vector< std::string > operations = options.unnamed( \"\",\"--binary,-b,--delimiter,-d,--fields,-f,--flush,--format,--full-xpath,--help,-h,--quote,--precision,--verbose,-v,--input-fields,--output-fields,--output-format,--deceleration,--max-acceleration,-c,--approach-speed,-a,--sharp-turn-angle,-t,--speed,-s,--stop-on-sharp-turn,--pivot,-p,--min-points-separation,--min-gap,-g\" );\n        if( operations.size() != 1 ) { std::cerr << comma::verbose.app_name() << \": expected one operation, got \" << operations.size() << \": \" << comma::join( operations, ' ' ) << std::endl; return 1; }\n\n        comma::csv::options csv( options );\n        if( csv.fields.empty() ) { csv.fields = \"x,y,z,speed\"; }\n        csv.full_xpath = false;\n\n        if( \"turn\" == operations[ 0 ] )\n        {\n            if( !( csv.has_field( \"speed\" ) || options.exists( \"--speed,-s\" ) ) )\n            { std::cerr << comma::verbose.app_name() << \": speed must be present in input fields or command line options.\" << std::endl; return 1; }\n\n            comma::csv::options out_csv( csv );\n            auto const pivot = options.exists( \"--stop-on-sharp-turn,--pivot,-p\" );\n            out_csv.fields = \"moderated_speed\"; if( pivot ) { out_csv.fields.append( \",relative_heading\" ); }\n            if( options.exists( \"--output-fields\" ) ) { std::cout << out_csv.fields << std::endl; return 0; }\n            if( options.exists( \"--output-format\" ) ) { std::cout << comma::csv::format::value< turn::output_t >( out_csv.fields, true ) << std::endl; return 0; }\n\n            auto const speed = options.value< double >( \"--speed,-s\", 0.0 );\n            auto const max_acceleration = options.value< double >( \"--max-acceleration,-c\" );\n            auto const approach_speed = options.value< double >( \"--approach-speed,-a\" );\n            auto const sharp_turn_angle = options.value< double >( \"--sharp-turn-angle,-t\", 1.57 ); // near 90 degrees\n            auto const min_points_gap = options.value< double >( \"--min-points-separation,--min-gap,-g\", 0.01 );\n            auto const spot_turn_radius = approach_speed * approach_speed / max_acceleration;\n\n            auto unique_points = 0U;\n            std::deque< turn::record_t > que;\n\n            comma::csv::input_stream< generic::input_t > istrm( std::cin, csv, generic::input_t( speed ) );\n            comma::csv::output_stream< turn::output_t > ostrm( std::cout, out_csv );\n\n            while( istrm.ready() || ( std::cin.good() && !std::cin.eof() ) )\n            {\n                auto input = istrm.read(); if( !input ) break;\n                if( que.empty() || ( input->coordinates - que.back().input.coordinates ).norm() >= min_points_gap ) { unique_points++; }\n                que.emplace_back( *input, istrm, csv );\n\n                if( 3U == unique_points )\n                {\n                    auto relevant_index = que.size() - 2U;\n                    auto const angle = angle_calc( que.front().input.coordinates, que[ relevant_index ].input.coordinates, que.back().input.coordinates );\n                    auto const radius = radius_calc( que.front().input.coordinates, que[ relevant_index ].input.coordinates, que.back().input.coordinates );\n\n                    if( comma::math::less( std::fabs( angle ), sharp_turn_angle ) && comma::math::less( spot_turn_radius, radius ) )\n                    {\n                        auto updated_speed = std::sqrt( max_acceleration * radius );\n                        que[ relevant_index ].output.moderated_speed = std::max( approach_speed, std::min( que[ relevant_index ].input.speed, updated_speed ) );\n                    }\n                    else\n                    {\n                        que[ relevant_index ].output.moderated_speed = std::min( que[ relevant_index ].input.speed, approach_speed );\n                        if( pivot )\n                        {\n                            auto temp = que.back();\n                            que.back() = que[ relevant_index ];\n                            que.back().output.moderated_speed = 0;\n                            que.back().output.relative_heading = angle;\n                            que.push_back( temp );\n                        }\n                    }\n                    while( 2 < que.size() ) { que.front().write( ostrm, csv ); que.pop_front(); }\n                    unique_points = 2;\n                }\n            }\n            for( auto ii = 0U; ii < que.size(); ii++ ) { que[ ii ].write( ostrm, csv ); }\n            return 0;\n        }\n        else if( \"decelerate\" == operations[ 0 ] )\n        {\n            comma::csv::input_stream< generic::input_t > istrm( std::cin, csv );\n\n            comma::csv::output_stream< generic::input_t > ostrm( std::cout, csv );\n            std::deque< deceleration::record_t > que;\n\n            auto const deceleration = options.value< double >( \"--deceleration,-c\" );\n            auto max_speed = 0.0;\n            while( istrm.ready() || ( std::cin.good() && !std::cin.eof() ) )\n            {\n                auto input = istrm.read(); if( !input ) break;\n                que.emplace_back( *input, istrm, csv );\n\n                max_speed = std::max( que.back().input.speed, max_speed );\n                auto const affected_distance = max_speed * max_speed / ( 2 * deceleration ); // kinematic equation with min_speed = 0.0\n\n                auto curri = que.rbegin();\n                auto previ = curri + 1;\n                double updated_speed, distance;\n\n                for( ; previ != que.rend()\n                         && ( comma::math::less( 0.0, distance = ( curri->input.coordinates - previ->input.coordinates ).norm() )\n                           || comma::math::less( 0.0, curri->input.speed ) )\n                         && comma::math::less( updated_speed = std::sqrt( curri->input.speed * curri->input.speed + 2 * deceleration * distance )\n                                             , previ->input.speed )\n                     ; previ++, curri++ )\n                {\n                    previ->input.speed = updated_speed;\n                }\n                while(( que.back().input.coordinates - que.front().input.coordinates ).norm() > affected_distance )\n                {\n                    que.front().write( ostrm, csv );\n                    que.pop_front();\n                }\n            }\n            for( auto ii = 0U; ii < que.size(); ii++ ) { que[ ii ].write( ostrm, csv ); }\n            return 0;\n        }\n        std::cerr << comma::verbose.app_name() << \": unknown operation: \" <<  operations[ 0 ] << std::endl;\n        return 1;\n    }\n    catch( std::exception& ex ) { std::cerr << comma::verbose.app_name() << \": \" << ex.what() << std::endl; }\n    catch( ... ) { std::cerr << comma::verbose.app_name() << \": unknown exception\" << std::endl; }\n    return 1;\n}\n\n", "meta": {"hexsha": "3d83a5d63393ba5196a43465c61072de2a09f754", "size": 18094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "control/applications/control-speed.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": "control/applications/control-speed.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": "control/applications/control-speed.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": 45.6919191919, "max_line_length": 390, "alphanum_fraction": 0.5694705427, "num_tokens": 4659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1645164792819756, "lm_q2_score": 0.016152833134883526, "lm_q1q2_score": 0.0026574072377802747}}
{"text": "/******************************************************************************\n *   Copyright (C) 2006-2020 by the GIMLi development team                    *\n *   Carsten Rücker carsten@resistivity.net                                   *\n *                                                                            *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");          *\n *   you may not use this file except in compliance with the License.         *\n *   You may obtain a copy of the License at                                  *\n *                                                                            *\n *       http://www.apache.org/licenses/LICENSE-2.0                           *\n *                                                                            *\n *   Unless required by applicable law or agreed to in writing, software      *\n *   distributed under the License is distributed on an \"AS IS\" BASIS,        *\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n *   See the License for the specific language governing permissions and      *\n *   limitations under the License.                                           *\n *                                                                            *\n ******************************************************************************/\n\n#include \"mesh.h\"\n\n#include \"kdtreeWrapper.h\"\n#include \"memwatch.h\"\n#include \"meshentities.h\"\n#include \"node.h\"\n#include \"line.h\"\n#include \"shape.h\"\n\n#include \"sparsematrix.h\"\n#include \"stopwatch.h\"\n\n#include <boost/bind.hpp>\n\n#include <map>\n\nnamespace GIMLI{\n\nstd::ostream & operator << (std::ostream & str, const Mesh & mesh){\n    str << \"\\tNodes: \" << mesh.nodeCount() << \"\\tCells: \" << mesh.cellCount() << \"\\tBoundaries: \" << mesh.boundaryCount();\n    return str;\n}\n\nMesh::Mesh(Index dim, bool isGeometry)\n    : dimension_(dim),\n    rangesKnown_(false),\n    neighborsKnown_(false),\n    tree_(NULL),\n    staticGeometry_(true),\n    isGeometry_(isGeometry){\n\n    oldTet10NumberingStyle_ = true;\n    cellToBoundaryInterpolationCache_ = 0;\n}\n\nMesh::Mesh(const std::string & filename, bool createNeighborInfos)\n    : rangesKnown_(false),\n    neighborsKnown_(false),\n    tree_(NULL),\n    staticGeometry_(true),\n    isGeometry_(false){\n    dimension_ = 3;\n    oldTet10NumberingStyle_ = true;\n    cellToBoundaryInterpolationCache_ = 0;\n    load(filename, createNeighborInfos);\n}\n\nMesh::Mesh(const Mesh & mesh)\n    : rangesKnown_(false),\n    neighborsKnown_(false),\n    tree_(NULL),\n    staticGeometry_(true),\n    isGeometry_(false){\n\n    oldTet10NumberingStyle_ = true;\n    cellToBoundaryInterpolationCache_ = 0;\n    copy_(mesh);\n}\n\nMesh & Mesh::operator = (const Mesh & mesh){\n    if (this != & mesh){\n        copy_(mesh);\n    } return *this;\n}\n\nvoid Mesh::copy_(const Mesh & mesh){\n    clear();\n    rangesKnown_ = false;\n    setStaticGeometry(mesh.staticGeometry());\n    dimension_ = mesh.dim();\n    nodeVector_.reserve(mesh.nodeCount());\n    secNodeVector_.reserve(mesh.secondaryNodeCount());\n\n    for (Index i = 0; i < mesh.nodeCount(); i ++){\n        this->createNode(mesh.node(i));\n    }\n\n    for (Index i = 0; i < mesh.secondaryNodeCount(); i ++){\n        this->createSecondaryNode(mesh.secondaryNode(i).pos());\n    }\n\n    boundaryVector_.reserve(mesh.boundaryCount());\n    for (Index i = 0; i < mesh.boundaryCount(); i ++){\n        this->createBoundary(mesh.boundary(i));\n    }\n\n    cellVector_.reserve(mesh.cellCount());\n    for (Index i = 0; i < mesh.cellCount(); i ++){\n        this->createCell(mesh.cell(i));\n    }\n\n    for (Index i = 0; i < mesh.regionMarkers().size(); i ++){\n        this->addRegionMarker(mesh.regionMarkers()[i]);\n    }\n    for (Index i = 0; i < mesh.holeMarker().size(); i ++){\n        this->addHoleMarker(mesh.holeMarker()[i]);\n    }\n\n    // we don't need expensive tests for copying\n    setGeometry(mesh.isGeometry());\n    setDataMap(mesh.dataMap());\n    setCellAttributes(mesh.cellAttributes());\n\n    if (mesh.neighborsKnown()){\n        this->createNeighborInfos(true);\n    }\n//     std::cout << \"COPY mesh \" << mesh.cell(0) << \" \" << cell(0) << std::endl;\n}\n\nMesh::~Mesh(){\n    clear();\n}\n\nvoid Mesh::setStaticGeometry(bool stat){\n    staticGeometry_ = stat;\n}\n\nvoid Mesh::setGeometry(bool b) {\n    isGeometry_ = b;\n}\n\nvoid Mesh::clear(){\n    if (tree_) {\n        deletePtr()(tree_);\n        tree_ = NULL;\n    }\n\n    for_each(cellVector_.begin(), cellVector_.end(), deletePtr());\n    cellVector_.clear();\n\n    for_each(boundaryVector_.begin(), boundaryVector_.end(), deletePtr());\n    boundaryVector_.clear();\n\n    for_each(nodeVector_.begin(), nodeVector_.end(), deletePtr());\n    nodeVector_.clear();\n\n    for_each(secNodeVector_.begin(), secNodeVector_.end(), deletePtr());\n    secNodeVector_.clear();\n\n    if (cellToBoundaryInterpolationCache_){\n        delete cellToBoundaryInterpolationCache_;\n    }\n\n    rangesKnown_ = false;\n    neighborsKnown_ = false;\n}\n\nNode * Mesh::createNode_(const RVector3 & pos, int marker){\n    rangesKnown_ = false;\n    Index id = nodeCount();\n    nodeVector_.push_back(new Node(pos));\n    nodeVector_.back()->setMarker(marker);\n    nodeVector_.back()->setId(id);\n    return nodeVector_.back();\n}\n\nNode * Mesh::createNodeGC_(const RVector3 & pos, int marker){\n    if (this->isGeometry_){\n        // __M\n        Index oldCount = this->nodeCount();\n        Node *n = this->createNodeWithCheck(pos);\n        n->setMarker(marker);\n\n        if ((this->dim() == 3) and (this->nodeCount() > oldCount)){\n\n            for (auto *b: this->boundaryVector_){\n            // for (Index i = 0; i < this->boundaryVector_.size(); i ++ ){\n            //     Boundary *b = this->boundaryVector_[i];\n                // __MS(b->rtti())\n                if (b->rtti() == MESH_POLYGON_FACE_RTTI){\n                    // __MS(pos)\n                    // __MS(b->center())\n                    if (b->shape().touch(n->pos())){\n                        //  __MS(pos)\n                        //  __MS(b->node(0).pos() << \" \" << b->node(1).pos()\n                        //       << \" \"<< b->node(2).pos())\n                        // __MS(*b)\n                        dynamic_cast< PolygonFace* >(b)->insertNode(n);\n                    }\n                } else {\n                        // __MS(*b)\n                        // log(Error, \"Adding a node in a non Polygon Face is not supported.\");\n                }\n            }\n        }\n        return n;\n    } else {\n        return this->createNode_(pos, marker);\n    }\n}\n\nNode * Mesh::createNode(const Node & node){\n    return createNodeGC_(node.pos(), node.marker());\n}\n\nNode * Mesh::createNode(double x, double y, double z, int marker){\n    return createNodeGC_(RVector3(x, y, z), marker);\n}\n\nNode * Mesh::createNode(const RVector3 & pos, int marker){\n    return createNodeGC_(pos, marker);\n}\n\nNode & Mesh::secondaryNode(Index i) {\n    ASSERT_RANGE(i, 0, this->secondaryNodeCount())\n    return *secNodeVector_[i];\n}\n\nNode & Mesh::secondaryNode(Index i) const {\n    ASSERT_RANGE(i, 0, this->secondaryNodeCount())\n    return *secNodeVector_[i];\n}\n\nNode * Mesh::createSecondaryNode_(const RVector3 & pos){\n    Index id = this->secondaryNodeCount();\n    secNodeVector_.push_back(new Node(pos));\n    secNodeVector_.back()->setId(this->nodeCount() + id);\n    return secNodeVector_.back();\n}\n\nNode * Mesh::createSecondaryNode(const RVector3 & pos, double tol){\n    bool useTree = false;\n    if (tol > 0.0){\n        fillKDTree_();\n        useTree = true;\n\n        Node * refNode = tree_->nearest(pos);\n        if (refNode){\n            if (pos.distance(refNode->pos()) < tol) {\n                return refNode;\n            }\n        }\n    }\n    Node *newNode = createSecondaryNode_(pos);\n    if (useTree) tree_->insert(newNode);\n    return newNode;\n}\n\nNode * Mesh::createNodeWithCheck(const RVector3 & pos, double tol, bool warn, bool edgeCheck){\n    bool useTree = false;\n    if (tol > -1.0){\n        fillKDTree_();\n        useTree = true;\n\n        Node * refNode = tree_->nearest(pos);\n        if (refNode){\n            if (pos.distance(refNode->pos()) < tol) {\n                if (warn) log(LogType::Warning,\n                                         \"Duplicated node found for: \" + str(pos));\n                return refNode;\n            }\n        }\n\n    //     for (Index i = 0, imax = nodeVector_.size(); i < imax; i++){\n    //         if (pos.distance(nodeVector_[i]->pos()) < 1e-6) return nodeVector_[i];\n    //     }\n    }\n\n    Node * newNode = this->createNode_(pos, 0);\n    if (useTree) tree_->insert(newNode);\n\n    if (edgeCheck){\n        if (this->dim() != 2){\n            if (warn || debug()) log(LogType::Warning,\n                \"edgeCheck is currently only supported for 2d meshes\");\n        } else {\n            ///// TODO refaktor in extra function\n            for (Index i = 0; i < this->boundaryVector_.size(); i ++ ){\n                Boundary *b = this->boundaryVector_[i];\n                if (b->rtti() == MESH_EDGE_RTTI){\n                    int pIn;\n                    Line(b->node(0).pos(), b->node(1).pos()).touch1(newNode->pos(), pIn);\n                    if (pIn == 3){\n                        Node *n1 = &b->node(0);\n                        Node *n2 = &b->node(1);\n                        // __MS(*n1)\n                        // __MS(*n2)\n                        // __MS(*newNode)\n                        dynamic_cast< Edge * >(b)->setNodes(*n1, *newNode);\n                        this->createEdge(*newNode, *n2, b->marker());\n                        break;\n                    }\n                } else {\n                    log(LogType::Error,\n                        \"edge split is currently only supported for 2d edges\");\n                }\n            }\n        }\n    }\n\n    return newNode;\n}\n\nBoundary * Mesh::createBoundary(const IndexArray & idx, int marker, bool check){\n    std::vector < Node * > nodes(idx.size());\n    for (Index i = 0; i < idx.size(); i ++ ) nodes[i] = &this->node(idx[i]);\n    if (isGeometry_){\n        return createPolygonFace(nodes, marker, check);\n    }\n    return createBoundary(nodes, marker, check);\n}\n\nBoundary * Mesh::createBoundary(std::vector < Node * > & nodes, int marker, bool check){\n    switch (nodes.size()){\n        case 1: return createBoundaryChecked_< NodeBoundary >(nodes, marker, check); break;\n        case 2: return createBoundaryChecked_< Edge >(nodes, marker, check); break;\n        case 3: {\n            if (dimension_ == 2)\n                return createBoundaryChecked_< Edge3 >(nodes, marker, check);\n            return createBoundaryChecked_< TriangleFace >(nodes, marker, check); } break;\n        case 4: return createBoundaryChecked_< QuadrangleFace >(nodes, marker, check); break;\n        case 6: return createBoundaryChecked_< Triangle6Face >(nodes, marker, check); break;\n        case 8: return createBoundaryChecked_< Quadrangle8Face >(nodes, marker, check); break;\n        default:\n            return createBoundaryChecked_< PolygonFace >(nodes, marker, check); break;\n    }\n    std::cout << WHERE_AM_I << \"WHERE_AM_I << cannot determine boundary for nodes: \" << nodes.size() << std::endl;\n    return NULL;\n}\n\nBoundary * Mesh::createBoundary(const Boundary & bound, bool check){\n    // only work for copy meshes where all nodes already copied\n    std::vector < Node * > nodes(bound.nodeCount());\n    for (Index i = 0; i < bound.nodeCount(); i ++) nodes[i] = &node(bound.node(i).id());\n\n    Boundary *b = 0;\n\n    if (bound.rtti() == MESH_POLYGON_FACE_RTTI){\n        const PolygonFace & f = dynamic_cast< const PolygonFace & >(bound);\n        b = createBoundaryChecked_< PolygonFace >(nodes, bound.marker(), check);\n        for (Index i = 0; i < f.subfaceCount(); i ++ ){\n            dynamic_cast< PolygonFace* >(b)->addSubface(\n                this->nodes(ids(f.subface(i))));\n        }\n        for (Index i = 0; i < f.holeMarkers().size(); i ++ ){\n            dynamic_cast< PolygonFace* >(b)->addHoleMarker(f.holeMarkers()[i]);\n        }\n\n    } else {\n        b = createBoundary(nodes, bound.marker(), check);\n    }\n\n    for (Index j = 0; j < bound.secondaryNodes().size(); j ++){\n        b->addSecondaryNode(& this->node(bound.secondaryNodes()[j]->id()));\n    }\n    return b;\n}\n\nBoundary * Mesh::createBoundary(const Cell & cell, bool check){\n    std::vector < Node * > nodes(cell.nodeCount());\n    for (Index i = 0; i < cell.nodeCount(); i ++) nodes[i] = &node(cell.node(i).id());\n    return createBoundary(nodes, cell.marker(), check);\n}\n\nBoundary * Mesh::createNodeBoundary(Node & n1, int marker, bool check){\n    std::vector < Node * > nodes(1); nodes[0] = & n1;\n    return createBoundaryChecked_< NodeBoundary >(nodes, marker, check);\n}\n\nBoundary * Mesh::createEdge(Node & n1, Node & n2, int marker, bool check){\n    std::vector < Node * > nodes(2);  nodes[0] = & n1; nodes[1] = & n2;\n    return createBoundaryChecked_< Edge >(nodes, marker, check);\n}\n\nBoundary * Mesh::createEdge3(Node & n1, Node & n2, Node & n3, int marker, bool check){\n    std::vector < Node * > nodes(3); nodes[0] = & n1; nodes[1] = & n2; nodes[2] = & n3;\n    return createBoundaryChecked_< Edge3 >(nodes, marker, check);\n}\n\nBoundary * Mesh::createTriangleFace(Node & n1, Node & n2, Node & n3, int marker, bool check){\n    std::vector < Node * > nodes(3);  nodes[0] = & n1; nodes[1] = & n2; nodes[2] = & n3;\n    return createBoundaryChecked_< TriangleFace >(nodes, marker, check);\n}\n\nBoundary * Mesh::createQuadrangleFace(Node & n1, Node & n2, Node & n3, Node & n4, int marker, bool check){\n    std::vector < Node * > nodes(4);  nodes[0] = & n1; nodes[1] = & n2; nodes[2] = & n3, nodes[3] = & n4;\n    return createBoundaryChecked_< QuadrangleFace >(nodes, marker, check);\n}\n\nBoundary * Mesh::createPolygonFace(std::vector < Node * > & nodes, int marker, bool check){\n    return createBoundaryChecked_< PolygonFace >(nodes, marker, check);\n}\n\nCell * Mesh::createCell(int marker){\n    std::vector < Node * > nodes(0);\n    return createCell_< Cell >(nodes, marker, cellCount());\n}\n\nCell * Mesh::createCell(const IndexArray & idx, int marker){\n    std::vector < Node * > nodes(idx.size());\n    for (Index i = 0; i < idx.size(); i ++ ) nodes[i] = &this->node(idx[i]);\n    return createCell(nodes, marker);\n}\n\nCell * Mesh::createCell(std::vector < Node * > & nodes, int marker){\n    switch (nodes.size()){\n        case 0: return createCell_< Cell >(nodes, marker, cellCount()); break;\n        case 2: return createCell_< EdgeCell >(nodes, marker, cellCount()); break;\n        case 3:\n            switch (dimension_){\n                case 1: return createCell_< Edge3Cell >(nodes, marker, cellCount()); break;\n                case 2: return createCell_< Triangle >(nodes, marker, cellCount()); break;\n            }\n            break;\n        case 4:\n            switch (dimension_){\n                case 2: return createCell_< Quadrangle >(nodes, marker, cellCount()); break;\n                case 3: return createCell_< Tetrahedron >(nodes, marker, cellCount()); break;\n            }\n            break;\n        case 5: return createCell_< Pyramid >(nodes, marker, cellCount()); break;\n        case 6:\n            switch (dimension_){\n                case 2: return createCell_< Triangle6 >(nodes, marker, cellCount()); break;\n                case 3: return createCell_< TriPrism >(nodes, marker, cellCount()); break;\n            }\n            break;\n        case 8:\n            switch (dimension_){\n                case 2: return createCell_< Quadrangle8 >(nodes, marker, cellCount()); break;\n                case 3: return createCell_< Hexahedron >(nodes, marker, cellCount()); break;\n            }\n            break;\n        case 10: return createCell_< Tetrahedron10 >(nodes, marker, cellCount()); break;\n        case 13: return createCell_< Pyramid13 >(nodes, marker, cellCount()); break;\n        case 15: return createCell_< TriPrism15 >(nodes, marker, cellCount()); break;\n        case 20: return createCell_< Hexahedron20 >(nodes, marker, cellCount()); break;\n\n    }\n    std::cout << WHERE_AM_I << \"WHERE_AM_I << cannot determine cell for nodes: \" << nodes.size() << \" for dim: \" << dimension_ << std::endl;\n    return NULL;\n}\n\nCell * Mesh::createCell(const Cell & cell){\n    std::vector < Node * > nodes(cell.nodeCount());\n    for (Index i = 0; i < cell.nodeCount(); i ++) nodes[i] = &node(cell.node(i).id());\n\n    Cell *c = createCell(nodes, cell.marker());\n    for (Index j = 0; j < cell.secondaryNodes().size(); j ++){\n        c->addSecondaryNode(& this->node(cell.secondaryNodes()[j]->id()));\n    }\n    return c;\n}\n\nCell * Mesh::createTriangle(Node & n1, Node & n2, Node & n3, int marker){\n    std::vector < Node * > nodes(3);  nodes[0] = & n1; nodes[1] = & n2; nodes[2] = & n3;\n    return createCell_< Triangle >(nodes, marker, cellCount());\n}\n\nCell * Mesh::createQuadrangle(Node & n1, Node & n2, Node & n3, Node & n4, int marker){\n    std::vector < Node * > nodes(4);\n    nodes[0] = & n1; nodes[1] = & n2; nodes[2] = & n3; nodes[3] = & n4;\n    return createCell_< Quadrangle >(nodes, marker, cellCount());\n}\n\nCell * Mesh::createTetrahedron(Node & n1, Node & n2, Node & n3, Node & n4, int marker){\n    std::vector < Node * > nodes(4);\n    nodes[0] = & n1; nodes[1] = & n2; nodes[2] = & n3; nodes[3] = & n4;\n    return createCell_< Tetrahedron >(nodes, marker, cellCount());\n}\n\nCell * Mesh::copyCell(const Cell & cell, double tol){\n    std::vector < Node * > nodes(cell.nodeCount());\n    for (Index i = 0; i < nodes.size(); i ++) {\n        nodes[i] = createNodeWithCheck(cell.node(i).pos(), tol);\n        nodes[i]->setMarker(cell.node(i).marker());\n    }\n    Cell * c = createCell(nodes);\n\n    c->setMarker(cell.marker());\n    c->setAttribute(cell.attribute());\n    return c;\n}\n\nBoundary * findSecParent(const std::vector < Node * > & v){\n    std::set < MeshEntity * > common;\n\n    for (auto *n: v){\n        common.insert(n->secondaryParent());\n    }\n    if (common.size() == 1) {\n        return  dynamic_cast < Boundary * >(*common.begin());\n    }\n    return 0;\n}\nBoundary * Mesh::copyBoundary(const Boundary & bound, double tol, bool check){\n\n    std::vector < Node * > nodes(bound.nodeCount());\n    bool isFreeFace = false;\n    bool isSubFace = false;\n\n    std::vector < Node * > conNodes;\n    std::vector < Node * > secNodes;\n    std::vector < Node * > subNodes;\n\n    // __M\n\n    for (Index i = 0; i < nodes.size(); i ++) {\n        nodes[i] = createNode(bound.node(i).pos(), tol);\n        nodes[i]->setMarker(bound.node(i).marker());\n        // __MS(nodes[i]->state())\n        switch (nodes[i]->state()){\n            case NodeState::No:\n                // at least one node is not in boundary\n                isFreeFace = true; break;\n            case NodeState::Secondary:\n                secNodes.push_back(nodes[i]); break;\n                // __MS(*nodes[i])\n            case NodeState::Connected:\n                conNodes.push_back(nodes[i]); break;\n        }\n    }\n    Boundary * b = 0;\n    Boundary * parent = 0;\n\n    if (bound.rtti() == MESH_POLYGON_FACE_RTTI){\n\n        Boundary * conParent = findBoundary(conNodes);\n        Boundary * secParent = findSecParent(secNodes);\n\n        // __MS(\"sizes:\" << conNodes.size() <<\" \" <<secNodes.size())\n        // __MS(\"parents: \" << conParent <<\" \" << secParent)\n\n        if (!isFreeFace){\n            conParent = findBoundary(conNodes);\n\n            if (conNodes.size() && secNodes.size()){\n                if (conParent != secParent){\n                    isFreeFace = true;\n                }\n                subNodes = conNodes;\n                subNodes.insert(subNodes.end(), secNodes.begin(), secNodes.end());\n                parent = secParent;\n            }\n            if (conNodes.size()){\n                if (!conParent){\n                    isFreeFace = true;\n                }\n                subNodes = conNodes;\n                parent = conParent;\n            }\n            if (secNodes.size()){\n                if(!secParent){\n                    isFreeFace = true;\n                }\n                subNodes = secNodes;\n                parent = secParent;\n            }\n        }\n\n        if (isFreeFace){\n            b = createBoundaryChecked_< PolygonFace >(nodes,\n                                                      bound.marker(), check);\n            parent = b;\n        } else {\n            if (subNodes.size() > 2){\n                if (parent){\n                    for (auto *n: secNodes){\n                        parent->delSecondaryNode(n);\n                    }\n                    dynamic_cast< PolygonFace * >(parent)->addSubface(subNodes);\n                } else {\n                    log(Error, \"no parent boundary\");\n                }\n                b = parent;\n            }\n        }\n        const PolygonFace & f = dynamic_cast< const PolygonFace & >(bound);\n        if (f.subfaceCount() > 0){\n            log(Error, \"Can't yet copy a boundary with subfaces\");\n        }\n\n        for (Index i = 0; i < f.holeMarkers().size(); i ++ ){\n            dynamic_cast< PolygonFace* >(parent)->addHoleMarker(\n                                                    f.holeMarkers()[i]);\n        }\n    } else { // if no Polygonface\n        b = createBoundary(nodes, bound.marker(), check);\n    }\n\n    return b;\n}\n\nNode & Mesh::node(Index i) {\n    if (i > nodeCount() - 1){\n        if (i < nodeCount() + secondaryNodeCount())\n            return this->secondaryNode(i - this->nodeCount());\n        std::cerr << WHERE_AM_I << \" requested node: \" << i << \" does not exist.\" << std::endl;\n    } return *nodeVector_[i];\n}\n\nNode & Mesh::node(Index i) const {\n    if (i > nodeCount() - 1){\n        if (i < nodeCount() + secondaryNodeCount())\n            return this->secondaryNode(i - this->nodeCount());\n        std::cerr << WHERE_AM_I << \" requested node: \" << i << \" does not exist.\" << std::endl;\n    } return *nodeVector_[i];\n}\n\nCell & Mesh::cell(Index i) const {\n    if (i > cellCount() - 1){\n      std::cerr << WHERE_AM_I << \" requested cell: \" << i << \" does not exist.\" << std::endl;\n    } return *cellVector_[i];\n}\n\nCell & Mesh::cell(Index i) {\n    if (i > cellCount() - 1){\n      std::cerr << WHERE_AM_I << \" requested cell: \" << i << \" does not exist.\" << std::endl;\n    } return *cellVector_[i];\n}\n\nBoundary & Mesh::boundary(Index i) const {\n    if (i > boundaryCount() - 1){\n      std::cerr << WHERE_AM_I << \" requested boundary: \" << i << \" does not exist.\" << std::endl;\n    } return *boundaryVector_[i];\n}\n\nBoundary & Mesh::boundary(Index i) {\n    if (i > boundaryCount() - 1){\n      std::cerr << WHERE_AM_I << \" requested boundary: \" << i << \" does not exist.\" << std::endl;\n    } return *boundaryVector_[i];\n}\n\nvoid Mesh::findRange_() const{\n    if (!rangesKnown_ || !staticGeometry_){\n        minRange_ = RVector3(MAX_DOUBLE, MAX_DOUBLE, MAX_DOUBLE);\n        maxRange_ = -minRange_;\n        for (Index i=0; i < nodeVector_.size(); i ++){\n            for (Index j=0; j < 3; j ++){\n                minRange_[j] = min(nodeVector_[i]->pos()[j], minRange_[j]);\n                maxRange_[j] = max(nodeVector_[i]->pos()[j], maxRange_[j]);\n            }\n        }\n        rangesKnown_ = true;\n    }\n}\n\nMesh Mesh::createHull() const{\n    Mesh out(3);\n    out.createHull_(*this);\n    return out;\n}\n\nvoid Mesh::createHull_(const Mesh & mesh){\n\n    if (this->dim() == 3 && mesh.dim() == 2){\n        clear();\n        rangesKnown_ = false;\n        nodeVector_.reserve(mesh.nodeCount());\n        for (Index i = 0; i < mesh.nodeCount(); i ++) createNode(mesh.node(i));\n\n        boundaryVector_.reserve(mesh.cellCount());\n        for (Index i = 0; i < mesh.cellCount(); i ++) createBoundary(mesh.cell(i));\n    } else {\n        std::cerr << WHERE_AM_I << \" increasing dimension fails, you should set the dimension for this mesh to 3\" << std::endl;\n    }\n}\n\nIndex Mesh::findNearestNode(const RVector3 & pos){\n    fillKDTree_();\n    return tree_->nearest(pos)->id();\n}\n\nIndexArray cellIDX__;\n\nCell * Mesh::findCellBySlopeSearch_(const RVector3 & pos, Cell * start,\n                                    size_t & count, bool useTagging) const {\n\n    Cell * cell = start;\n\n    Index cellCounter = 0; //** for avoiding infinite loop\n    do {\n        if (useTagging && cell->tagged()) {\n            cell = NULL;\n        } else {\n            cell->tag();\n            cellIDX__.push_back(cell->id());\n            RVector sf;\n\n//             std::cout << cellIDX__.size() << \" testpos: \" << pos << std::endl;\n//             std::cout << \"cell: \" << *cell << \" touch: \" << cell->shape().isInside(pos, true) << std::endl;\n//             for (Index i = 0; i < cell->nodeCount() ; i ++){\n//                 std::cout << cell->node(i)<< std::endl;\n//             }\n\n            if (cell->shape().isInside(pos, sf, false)) {\n                return cell;\n            } else {\n\n                if (!neighborsKnown_){\n                    const_cast<Mesh*>(this)->createNeighborInfosCell_(cell);\n//                     for (Index j = 0; j < cell->neighborCellCount(); j++){\n//                          cell->findNeighborCell(j);\n//                     }\n                }\n\n//                 for (Index i = 0; i < cell->neighborCellCount(); i ++ ){\n//                     if (cell->neighborCell(i)){\n//                         std::cout << \"\\t \" << i << \" \" << *cell->neighborCell(i) << std::endl;\n//                     } else {\n//                         std::cout << \"\\t \" << i << \" \" << 0 << std::endl;\n//                     }\n//                 }\n\n                cell = cell->neighborCell(sf);\n\n//                 std::cout << \"sf: \" << sf << std::endl;\n//                 std::cout << \"neighCell \" << cell << std::endl;\n            }\n            count++;\n            if (count == 50){\n//                 std::cout << \"testpos: \" << pos << std::endl;\n//                 std::cout << \"cell: \" << this->cell(cellIDX__.back()) << std::endl;\n//                 for (Index i = 0;\n//                      i < this->cell(cellIDX__.back()).nodeCount(); i ++){\n//                     std::cout << this->cell(cellIDX__.back()).node(i)<< std::endl;\n//                 }\n                if (debug()){\n                    std::cout << WHERE_AM_I << \" exit with submesh \" << cellIDX__.size() << std::endl;\n                    std::cout << \"probably cant find a cell for \" << pos << std::endl;\n\n                    Mesh subMesh; subMesh.createMeshByCellIdx(*this, cellIDX__);\n\n                    subMesh.exportVTK(\"submesh\");\n                    this->exportVTK(\"submeshParent\");\n                }\n                return NULL;\n            }\n        }\n    } while (++cellCounter < cellCount() && cell);\n\n    return NULL;\n}\n\nCell * Mesh::findCell(const RVector3 & pos, size_t & count,\n                      bool extensive) const {\n    bool bruteForce = false;\n    Cell * cell = NULL;\n\n    if (bruteForce){\n        for (Index i = 0; i < this->cellCount(); i ++) {\n            count++;\n            if (cellVector_[i]->shape().isInside(pos)){\n                cell = cellVector_[i];\n//                 std::cout << \"testpos: \" << pos << std::endl;\n//                 std::cout << \"cell: \" << *cell<< std::endl;\n                break;\n            }\n        }\n    } else {\n        Stopwatch swatch(true);\n        cellIDX__.clear();\n        count = 0;\n        fillKDTree_();\n        Node * refNode = tree_->nearest(pos);\n\n        if (!refNode){\n            std::cout << \"pos: \" << pos << std::endl;\n            throwError(WHERE_AM_I +\n                       \" no nearest node to pos. This is a empty mesh\");\n        }\n        if (refNode->cellSet().empty()){\n            std::cout << \"Node: \" << *refNode << std::endl;\n            throwError(WHERE_AM_I +\n                       \" no cells for this node. This is a corrupt mesh\");\n        }\n//         std::cout << \"Node: \" << *refNode << std::endl;\n\n        // small fast precheck to avoid strange behaviour for symmetric SF.\n        for (std::set< Cell * >::iterator it = refNode->cellSet().begin();\n             it != refNode->cellSet().end(); it ++){\n//             std::cout << (*it)->id() << std::endl;\n\n           if ((*it)->shape().isInside(pos, false)) return *it;\n\n        }\n\n        cell = findCellBySlopeSearch_(pos, *refNode->cellSet().begin(),\n                                      count, false);\n        if (cell) return cell;\n\n//         exportVTK(\"slopesearch\");\n//         exit(0);\n        if (extensive || 0){\n//             __M\n//             std::cout << \"More expensive test here\" << std::endl;\n            cellIDX__.clear();\n            std::for_each(cellVector_.begin(), cellVector_.end(), std::mem_fn(&Cell::untag));\n            //!** *sigh, no luck with simple kd-tree search, try more expensive full slope search\n            count = 0;\n            for (Index i = 0; i < this->cellCount(); i ++) {\n                cell = cellVector_[i];\n                cell = findCellBySlopeSearch_(pos, cell, count, true);\n                if (cell) {\n\n                    break;\n                }\n            }\n        } else {\n            return NULL;\n        }\n  //      std::cout << \" n: \" << count;\n    }\n    return cell;\n}\n\nstd::vector < Cell * > Mesh::findCellsAlongRay(const RVector3 & start,\n                                               const RVector3 & dir,\n                                               PosVector & pos) const {\n    pos.clear();\n    Pos d(dir);\n    d.normalize();\n    std::vector < Cell * > cells;\n\n    RVector3 inPos(start);\n\n    if (!this->findCell(inPos, false)){\n        inPos = tree_->nearest(inPos)->pos();\n    }\n\n    pos.push_back(inPos);\n\n    double stepTol = 1e-5;\n\n    while (1){\n        Cell *c = this->findCell(inPos + dir*stepTol, false);\n        if (!c) break;\n\n        RVector3 outPos(false);\n        for (Index i = 0; i < c->boundaryCount(); i++){\n            Shape * s = c->boundary(i)->pShape();\n\n            if (s->intersectRay(inPos, dir, outPos)){\n                if (outPos != inPos){\n                    outPos.setValid(true);\n                    break;\n                } else {\n                    outPos.setValid(false);\n                }\n            }\n        }\n\n        if (outPos.valid()){\n            pos.push_back(outPos);\n            cells.push_back(c);\n            inPos = outPos;\n        }\n    }\n    return cells;\n}\n\nstd::vector < Boundary * > Mesh::findBoundaryByMarker(int marker) const {\n    return findBoundaryByMarker(marker, marker + 1);\n}\n\nstd::vector < Boundary * > Mesh::findBoundaryByMarker(int from, int to) const {\n//     __MS(from)\n    std::vector < Boundary * > vBounds;\n    vBounds.reserve(boundaryCount());\n\n    for (std::vector< Boundary * >::const_iterator it = boundaryVector_.begin();\n         it != boundaryVector_.end(); it++){\n\n        if ((*it)->marker() >= from && (*it)->marker() < to) vBounds.push_back((*it));\n    }\n\n    return vBounds;\n}\n\nvoid Mesh::setBoundaryMarkers(const IVector & marker){\n    ASSERT_EQUAL(boundaryCount(), marker.size())\n    for (Index i = 0; i < boundaryVector_.size(); i ++){\n        boundaryVector_[i]->setMarker(marker[i]);\n    }\n}\n\nvoid Mesh::setBoundaryMarkers(const IndexArray & ids, int marker){\n    for (IndexArray::iterator it = ids.begin(); it != ids.end(); it++){\n        if (*it < boundaryCount()){\n            boundaryVector_[*it]->setMarker(marker);\n        }\n    }\n}\n\nstd::vector < Cell * > Mesh::findCellByMarker(int from, int to) const {\n    if (to == -1) to = MAX_INT;\n    else if (to == 0) to = from + 1;\n\n    std::vector < Cell * > vCell;\n    vCell.reserve(cellCount());\n    for(std::vector< Cell * >::const_iterator it = cellVector_.begin();\n                                               it != cellVector_.end(); it++){\n        if ((*it)->marker() >= from && (*it)->marker() < to) vCell.push_back((*it));\n    }\n    return vCell;\n}\n\nstd::vector < Cell * > Mesh::findCellByAttribute(double from, double to) const {\n    std::vector < Cell * > vCell;\n    vCell.reserve(cellCount());\n\n    if (to < TOLERANCE){\n        for (Index i = 0; i < cellCount(); i ++){\n            if ((cell(i).attribute() - from) < TOLERANCE) vCell.push_back(cellVector_[i]);\n        }\n    } else {\n        if (to == -1) to = MAX_DOUBLE;\n        for (Index i = 0; i < cellCount(); i ++){\n            if (cell(i).attribute() >= from && cell(i).attribute() < to)\n                vCell.push_back(cellVector_[i]);\n        }\n    }\n    return vCell;\n}\n\nIndex Mesh::nodeCount(bool withSecNodes) const {\n    if (withSecNodes) return nodeVector_.size() + secNodeVector_.size();\n    return nodeVector_.size();\n}\n\nstd::vector< Node * > Mesh::nodes(const IndexArray & ids) const{\n    std::vector < Node * > v(ids.size());\n    for (Index i = 0; i < ids.size(); i ++) v[i] = &node(ids[i]);\n    return v;\n}\n\nstd::vector < Node * > Mesh::nodes(const BVector & b) const{\n    return nodes(find(b));\n}\n\nstd::vector< Cell * > Mesh::cells(const IndexArray & ids) const {\n    std::vector < Cell * > v(ids.size());\n    for (Index i = 0; i < ids.size(); i ++) v[i] = cellVector_[ids[i]];\n    return v;\n}\n\nstd::vector < Cell * > Mesh::cells(const BVector & b) const{\n    return cells(find(b));\n}\n\nstd::vector< Boundary * > Mesh::boundaries(const IndexArray & ids) const{\n    std::vector < Boundary * > v(ids.size());\n    for (Index i = 0; i < ids.size(); i ++) v[i] = boundaryVector_[ids[i]];\n    return v;\n}\n\nstd::vector < Boundary * > Mesh::boundaries(const BVector & b) const{\n    return boundaries(find(b));\n}\n\nvoid Mesh::setCellMarkers(const IndexArray & ids, int marker){\n    for(IndexArray::iterator it = ids.begin(); it != ids.end(); it++){\n        if (*it < cellCount()){\n            cellVector_[*it]->setMarker(marker);\n        }\n    }\n}\n\nvoid Mesh::setCellMarkers(const IVector & markers){\n    ASSERT_EQUAL(markers.size(), cellVector_.size())\n\n    for (Index i = 0; i < cellVector_.size(); i ++){\n        cellVector_[i]->setMarker(markers[i]);\n    }\n}\n\nvoid Mesh::setCellMarkers(const RVector & attribute){\n    if (attribute.size() >= cellVector_.size()){\n        for (Index i = 0; i < cellVector_.size(); i ++){\n            cellVector_[i]->setMarker(int(attribute[i]));\n        }\n    } else {\n        throwError(\"Mesh::setCellMarker: attribute size to small: \" +\n            str(attribute.size()) + \" < \" + str(cellCount()));\n    }\n}\n\nIVector Mesh::cellMarkers() const{\n    IVector tmp(cellCount());\n    std::transform(cellVector_.begin(), cellVector_.end(), tmp.begin(),\n                    std::mem_fn(&Cell::marker));\n    return tmp;\n}\n\nIndexArray Mesh::findNodesIdxByMarker(int marker) const {\n    return find(this->nodeMarkers() == marker);\n}\n\n// std::list < Index > Mesh::findListNodesIdxByMarker(int marker) const {\n//     std::list < Index > idx;\n//     for (Index i = 0; i < nodeCount(); i ++) {\n//         if (node(i).marker() == marker) idx.push_back(i);\n//     }\n//     return idx;\n// }\n\nPosVector Mesh::positions(bool withSecNodes) const {\n    IndexArray idx(this->nodeCount(withSecNodes));\n    std::generate(idx.begin(), idx.end(), IncrementSequence< Index >(0));\n    return this->positions(idx);\n}\n\nPosVector Mesh::positions(const IndexArray & idx) const {\n    PosVector pos(idx.size());\n    for (Index i = 0; i < idx.size(); i ++) { pos[i] = node(idx[i]).pos(); }\n    return pos;\n}\n\nIndexArray Mesh::nodeIDs(bool withSecNodes) const{\n    IndexArray ids(this->nodeCount(withSecNodes));\n    std::transform(nodeVector_.begin(), nodeVector_.end(), ids.begin(),\n                   std::mem_fn(&Node::id));\n    return ids;\n}\nvoid Mesh::setNodeIDs(IndexArray & ids){\n    for (Index i = 0; i < ids.size(); i ++) {\n        nodeVector_[i]->setId(ids[i]);\n    }\n}\n\nPosVector Mesh::cellCenters() const {\n    PosVector pos(this->cellCount());\n    std::transform(cellVector_.begin(), cellVector_.end(), pos.begin(),\n                   std::mem_fn(&Cell::center));\n    return pos;\n}\n\nPosVector Mesh::boundaryCenters() const {\n    PosVector pos(this->boundaryCount());\n    std::transform(boundaryVector_.begin(), boundaryVector_.end(), pos.begin(),\n                   std::mem_fn(&Boundary::center));\n    return pos;\n}\n\nRVector & Mesh::cellSizes() const{\n\n    if (cellSizesCache_.size() != cellCount()){\n        cellSizesCache_.resize(cellCount());\n\n        std::transform(cellVector_.begin(), cellVector_.end(),\n                       cellSizesCache_.begin(),\n                       std::mem_fn(&Cell::size));\n    } else {\n        if (!staticGeometry_){\n            cellSizesCache_.resize(0);\n            return this->cellSizes();\n        }\n    }\n\n    return cellSizesCache_;\n}\n\nRVector & Mesh::boundarySizes() const{\n    if (boundarySizesCache_.size() != boundaryCount()){\n        boundarySizesCache_.resize(boundaryCount());\n\n        std::transform(boundaryVector_.begin(), boundaryVector_.end(),\n                       boundarySizesCache_.begin(),\n                       std::mem_fn(&MeshEntity::size));\n    } else {\n        if (!staticGeometry_){\n            boundarySizesCache_.resize(0);\n            return this->boundarySizes();\n        }\n    }\n\n    return boundarySizesCache_;\n}\n\nPosVector & Mesh::boundarySizedNormals() const {\n    if (boundarySizedNormCache_.size() != boundaryCount()){\n        boundarySizedNormCache_.resize(boundaryCount());\n\n        for (Index i = 0; i < boundaryCount(); i ++){\n            if (dim()==1){\n                Cell *c = boundaryVector_[i]->leftCell();\n                if (!c) c = boundaryVector_[i]->rightCell();\n                boundarySizedNormCache_[i] = boundaryVector_[i]->norm(*c);\n            } else {\n                boundarySizedNormCache_[i] = boundaryVector_[i]->norm() * boundaryVector_[i]->size();\n            }\n        }\n\n    } else {\n        if (!staticGeometry_){\n            boundarySizedNormCache_.resize(0);\n            return this->boundarySizedNormals();\n        }\n    }\n\n    return boundarySizedNormCache_;\n}\n\nvoid Mesh::sortNodes(const IndexArray & perm){\n\n    for (Index i = 0; i < nodeVector_.size(); i ++) nodeVector_[i]->setId(perm[i]);\n  //    sort(nodeVector_.begin(), nodeVector_.end(), std::less< int >(mem_fn(&BaseEntity::id)));\n    sort(nodeVector_.begin(), nodeVector_.end(), lesserId< Node >);\n}\n\nvoid Mesh::recountNodes(){\n    __MS(\"is in use?\")\n    for (Index i = 0; i < nodeVector_.size(); i ++) nodeVector_[i]->setId(i);\n}\n\nMesh Mesh::createH2() const {\n    Mesh ret(this->dimension());\n    ret.createRefined_(*this, false, true);\n    ret.setCellAttributes(ret.cellMarkers());\n    return ret;\n}\n\nMesh Mesh::createP2() const {\n    Mesh ret(this->dimension());\n    ret.createRefined_(*this, true, false);\n    return ret;\n}\n\nint markerT(Node * n0, Node * n1){\n    if (n0->marker() == -99 && n1->marker() == -99) return -1;\n    if (n0->marker() == -99) return n1->marker();\n    if (n1->marker() == -99) return n0->marker();\n    if (n0->marker() == n1->marker()) return n1->marker();\n    else return 0;\n}\n\nNode * Mesh::createRefinementNode_(Node * n0, Node * n1, std::map< std::pair < Index, Index >, Node * > & nodeMatrix){\n    Node * n = nodeMatrix[std::make_pair(n0->id(), n1->id())];\n\n    if (!n){\n        if (n0 == n1){\n            n = this->createNode(n0->pos(), n0->marker()) ;\n            nodeMatrix[std::make_pair(n0->id(), n0->id())] = n;\n        } else {\n            n = this->createNode((n0->pos() + n1->pos()) / 2.0, markerT(n0, n1));\n            nodeMatrix[std::make_pair(n0->id(), n1->id())] = n;\n            nodeMatrix[std::make_pair(n1->id(), n0->id())] = n;\n        }\n    }\n    return n;\n}\n\nvoid Mesh::createRefined_(const Mesh & mesh, bool p2, bool h2){\n    if (this == &mesh) {\n        log(Error, WHERE_AM_I, \"This mesh and the given mesh need to be different instances.\");\n        return;\n    }\n    this->clear();\n\n    std::map< std::pair < Index, Index >, Node * > nodeMatrix;\n\n    for (Index i = 0, imax = mesh.nodeCount(); i < imax; i ++) {\n        this->createRefinementNode_(&mesh.node(i), &mesh.node(i), nodeMatrix);\n    }\n\n    std::vector < Node * > n;\n    for (Index i = 0, imax = mesh.cellCount(); i < imax; i ++){\n        const Cell & c = mesh.cell(i);\n        Index cID = i;\n\n        switch (c.rtti()){\n            case MESH_EDGE_CELL_RTTI:\n                n.resize(3);\n                n[0] = &node(mesh.cell(i).node(0).id());\n                n[1] = &node(mesh.cell(i).node(1).id());\n                n[2] = createRefinementNode_(n[0], n[1], nodeMatrix);\n\n                if (h2){\n                    std::vector < Node * > e1(2);\n                    e1[0] = n[0]; e1[1] = n[2];\n                    this->createCell(e1, cID);\n                    e1[0] = n[2]; e1[1] = n[1];\n                    this->createCell(e1, cID);\n                }\n                break;\n            case MESH_TRIANGLE_RTTI:\n                n.resize(6);\n                n[0] = &node(mesh.cell(i).node(0).id());\n                n[1] = &node(mesh.cell(i).node(1).id());\n                n[2] = &node(mesh.cell(i).node(2).id());\n\n                n[3] = createRefinementNode_(n[0], n[1], nodeMatrix);\n                n[4] = createRefinementNode_(n[1], n[2], nodeMatrix);\n                n[5] = createRefinementNode_(n[2], n[0], nodeMatrix);\n\n                if (h2){\n                    this->createTriangle(*n[0], *n[3], *n[5], cID);\n                    this->createTriangle(*n[1], *n[4], *n[3], cID);\n                    this->createTriangle(*n[2], *n[5], *n[4], cID);\n                    this->createTriangle(*n[3], *n[4], *n[5], cID);\n                }\n\n                break;\n            case MESH_QUADRANGLE_RTTI:\n                n.resize(8);\n                n[0] = &node(mesh.cell(i).node(0).id());\n                n[1] = &node(mesh.cell(i).node(1).id());\n                n[2] = &node(mesh.cell(i).node(2).id());\n                n[3] = &node(mesh.cell(i).node(3).id());\n\n                n[4] = createRefinementNode_(n[0], n[1], nodeMatrix);\n                n[5] = createRefinementNode_(n[1], n[2], nodeMatrix);\n                n[6] = createRefinementNode_(n[2], n[3], nodeMatrix);\n                n[7] = createRefinementNode_(n[3], n[0], nodeMatrix);\n\n                if (h2){\n                    Node *n8 = this->createNode(c.shape().xyz(RVector3(0.5, 0.5)));\n                    this->createQuadrangle(*n[0], *n[4], *n8, *n[7], cID);\n                    this->createQuadrangle(*n[1], *n[5], *n8, *n[4], cID);\n                    this->createQuadrangle(*n[2], *n[6], *n8, *n[5], cID);\n                    this->createQuadrangle(*n[3], *n[7], *n8, *n[6], cID);\n                }\n\n                break;\n            case MESH_TETRAHEDRON_RTTI:\n                n.resize(10);\n                if (oldTet10NumberingStyle_){\n\n                    for (Index j = 0; j < n.size(); j ++) {\n\n                        n[j] = createRefinementNode_(& this->node(c.node(Tet10NodeSplitZienk[j][0]).id()),\n                                                        & this->node(c.node(Tet10NodeSplitZienk[j][1]).id()),\n                                                        nodeMatrix);\n                    }\n\n                    if (h2){\n                        this->createTetrahedron(*n[4], *n[6], *n[5], *n[0], cID);\n                        this->createTetrahedron(*n[4], *n[5], *n[6], *n[9], cID);\n                        this->createTetrahedron(*n[7], *n[9], *n[4], *n[1], cID);\n                        this->createTetrahedron(*n[7], *n[4], *n[9], *n[5], cID);\n                        this->createTetrahedron(*n[8], *n[7], *n[5], *n[2], cID);\n                        this->createTetrahedron(*n[8], *n[5], *n[7], *n[9], cID);\n                        this->createTetrahedron(*n[6], *n[9], *n[8], *n[3], cID);\n                        this->createTetrahedron(*n[6], *n[8], *n[9], *n[5], cID);\n                    }\n\n                } else {\n                    for (Index j = 0; j < n.size(); j ++) {\n                        n[j] = createRefinementNode_(& this->node(c.node(Tet10NodeSplit[j][0]).id()),\n                                                        & this->node(c.node(Tet10NodeSplit[j][1]).id()),\n                                                        nodeMatrix);\n                    }\n\n                    if (h2){\n                        THROW_TO_IMPL\n                    }\n                }\n\n                break;\n            case MESH_HEXAHEDRON_RTTI:\n                n.resize(20);\n                for (Index j = 0; j < n.size(); j ++) {\n                    n[j] = createRefinementNode_(& this->node(c.node(Hex20NodeSplit[j][0]).id()),\n                                                 & this->node(c.node(Hex20NodeSplit[j][1]).id()),\n                                                 nodeMatrix);\n                }\n                if (h2){\n/* 27 new nodes 3 x 9 = 8 nodes + 12 edges + 6 facets + 1 center\n          7-----14------6  \\n\n         /|            /|  \\n\n        / |           / |  \\n\n      15 19  -21-    13 18 \\n\n      /   |     24  /   |  \\n\n     /    |        /    |  \\n\n    4-----12------5  23 |  \\n\n    | 25  3-----10|-----2  \\n\n    |    /        |    /   \\n\n   16   / -22-    17  /    \\n\n    | 11    -20-  |  9     \\n\n    | /           | /      \\n\n    |/            |/       \\n\n    0------8------1        \\n\n\n*/\n                    Node *n20 = createRefinementNode_(n[8], n[10], nodeMatrix);\n                    Node *n21 = createRefinementNode_(n[12], n[14], nodeMatrix);\n                    Node *n22 = createRefinementNode_(n[8], n[12], nodeMatrix);\n                    Node *n23 = createRefinementNode_(n[9], n[13], nodeMatrix);\n                    Node *n24 = createRefinementNode_(n[10], n[14], nodeMatrix);\n                    Node *n25 = createRefinementNode_(n[11], n[15], nodeMatrix);\n\n                    Node *n26 = createRefinementNode_(n20, n21, nodeMatrix);\n\n                    std::vector < Node* > ns(8);\n                    Node *n1_[]={ n[0], n[8], n20, n[11], n[16], n22, n26, n25 }; std::copy(&n1_[0], &n1_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n2_[]= { n[8], n[1], n[9], n20, n22, n[17], n23, n26 };  std::copy(&n2_[0], &n2_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n3_[]= { n[11], n20, n[10], n[3], n25, n26, n24, n[19] };  std::copy(&n3_[0], &n3_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n4_[]= { n20, n[9], n[2], n[10], n26, n23, n[18], n24 };  std::copy(&n4_[0], &n4_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n5_[]= { n[16], n22, n26, n25, n[4], n[12], n21, n[15] };  std::copy(&n5_[0], &n5_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n6_[]= { n22, n[17], n23, n26, n[12], n[5], n[13], n21 };  std::copy(&n6_[0], &n6_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n7_[]= { n25, n26, n24, n[19], n[15], n21, n[14], n[7] };  std::copy(&n7_[0], &n7_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n8_[]= { n26, n23, n[18], n24, n21, n[13], n[6], n[14] };  std::copy(&n8_[0], &n8_[8], &ns[0]);\n                    this->createCell(ns, cID);\n\n                }\n\n                break;\n            case MESH_TRIPRISM_RTTI:\n                n.resize(15);\n                for (Index j = 0; j < n.size(); j ++) {\n                    n[j] = createRefinementNode_(& this->node(c.node(Prism15NodeSplit[j][0]).id()),\n                                                 & this->node(c.node(Prism15NodeSplit[j][1]).id()),\n                                                 nodeMatrix);\n                }\n                if (h2){\n\n                    Node *nf1 = createRefinementNode_(n[6], n[9], nodeMatrix);\n                    Node *nf2 = createRefinementNode_(n[7], n[10], nodeMatrix);\n                    Node *nf3 = createRefinementNode_(n[8], n[11], nodeMatrix);\n\n                    std::vector < Node* > ns(6);\n                    Node *n1_[]={ n[0], n[6], n[8], n[12], nf1, nf3 }; std::copy(&n1_[0], &n1_[6], &ns[0]);\n                    this->createCell(ns, cID);\n                    Node *n2_[]={ n[1], n[7], n[6], n[13], nf2, nf1 }; std::copy(&n2_[0], &n2_[6], &ns[0]);\n                    this->createCell(ns, cID);\n                    Node *n3_[]={ n[2], n[8], n[7], n[14], nf3, nf2 }; std::copy(&n3_[0], &n3_[6], &ns[0]);\n                    this->createCell(ns, cID);\n                    Node *n4_[]={ n[6], n[7], n[8], nf1, nf2, nf3 }; std::copy(&n4_[0], &n4_[6], &ns[0]);\n                    this->createCell(ns, cID);\n\n                    Node *n5_[]={ n[12], nf1, nf3, n[3], n[9], n[11] }; std::copy(&n5_[0], &n5_[6], &ns[0]);\n                    this->createCell(ns, cID);\n                    Node *n6_[]={ n[13], nf2, nf1, n[4], n[10], n[9] }; std::copy(&n6_[0], &n6_[6], &ns[0]);\n                    this->createCell(ns, cID);\n                    Node *n7_[]={ n[14], nf3, nf2, n[5], n[11], n[10] }; std::copy(&n7_[0], &n7_[6], &ns[0]);\n                    this->createCell(ns, cID);\n                    Node *n8_[]={ nf1, nf2, nf3, n[9], n[10], n[11] }; std::copy(&n8_[0], &n8_[6], &ns[0]);\n                    this->createCell(ns, cID);\n\n                }\n                break;\n            case MESH_PYRAMID_RTTI:\n                n.resize(13);\n                for (Index j = 0; j < n.size(); j ++) {\n                    n[j] = createRefinementNode_(& this->node(c.node(Pyramid13NodeSplit[j][0]).id()),\n                                                    & this->node(c.node(Pyramid13NodeSplit[j][1]).id()),\n                                                    nodeMatrix);\n                }\n                if (h2){\n                    log(Error, \"Sorry, p2-refine for an already p2-refined mesh is not supported.\");\n                    THROW_TO_IMPL\n                }\n                break;\n            default: std::cerr << c.rtti() <<\" \" << std::endl; THROW_TO_IMPL  break;\n        }\n\n        if (p2 && !h2){\n            createCell(n, cID);\n        }\n\n    } // for_each cell\n\n    for (Index i = 0; i < mesh.boundaryCount(); i++){\n\n        const Boundary & b = mesh.boundary(i);\n\n        switch (b.rtti()){\n            case MESH_BOUNDARY_NODE_RTTI:\n                n.resize(1);\n                n[0] = &node(b.node(0).id());\n                break;\n            case MESH_EDGE_RTTI:\n                n.resize(3);\n                n[0] = &node(b.node(0).id());\n                n[1] = &node(b.node(1).id());\n                n[2] = createRefinementNode_(n[0], n[1], nodeMatrix);\n                break;\n            case MESH_TRIANGLEFACE_RTTI:\n                n.resize(6);\n                n[0] = &node(b.node(0).id());\n                n[1] = &node(b.node(1).id());\n                n[2] = &node(b.node(2).id());\n\n                n[3] = createRefinementNode_(n[0], n[1], nodeMatrix);\n                n[4] = createRefinementNode_(n[1], n[2], nodeMatrix);\n                n[5] = createRefinementNode_(n[2], n[0], nodeMatrix);\n                break;\n            case MESH_QUADRANGLEFACE_RTTI:\n                n.resize(8);\n                n[0] = &node(b.node(0).id());\n                n[1] = &node(b.node(1).id());\n                n[2] = &node(b.node(2).id());\n                n[3] = &node(b.node(3).id());\n\n                n[4] = createRefinementNode_(n[0], n[1], nodeMatrix);\n                n[5] = createRefinementNode_(n[1], n[2], nodeMatrix);\n                n[6] = createRefinementNode_(n[2], n[3], nodeMatrix);\n                n[7] = createRefinementNode_(n[3], n[0], nodeMatrix);\n                break;\n            default: std::cerr << b.rtti() <<\" \" << std::endl; THROW_TO_IMPL  break;\n        }\n\n        if (p2 && !h2){\n            createBoundary(n, b.marker());\n        } else {\n            switch (b.rtti()){\n                case MESH_BOUNDARY_NODE_RTTI:\n                    this->createBoundary(n, b.marker());\n                    break;\n                case MESH_EDGE_RTTI:\n                    this->createEdge(*n[0], *n[2], b.marker());\n                    this->createEdge(*n[2], *n[1], b.marker());\n                    break;\n                case MESH_TRIANGLEFACE_RTTI:\n                    this->createTriangleFace(*n[0], *n[3], *n[5], b.marker());\n                    this->createTriangleFace(*n[1], *n[4], *n[3], b.marker());\n                    this->createTriangleFace(*n[2], *n[5], *n[4], b.marker());\n                    this->createTriangleFace(*n[3], *n[4], *n[5], b.marker());\n                    break;\n                case MESH_QUADRANGLEFACE_RTTI:\n                    /*\n                     * 3---6---2\n                     * |   |   |\n                     * 7---8---5\n                     * |   |   |\n                     * 0---4---1\n                    */\n                    Node *n8 = nodeMatrix[std::make_pair(n[4]->id(), n[6]->id())];\n                    if (!n8) n8 = createRefinementNode_(n[5], n[7], nodeMatrix);\n\n                    this->createQuadrangleFace(*n[0], *n[4], *n8, *n[7], b.marker());\n                    this->createQuadrangleFace(*n[1], *n[5], *n8, *n[4], b.marker());\n                    this->createQuadrangleFace(*n[2], *n[6], *n8, *n[5], b.marker());\n                    this->createQuadrangleFace(*n[3], *n[7], *n8, *n[6], b.marker());\n\n                    break;\n\n            }\n        } // if not p2\n    } // for_each boundary\n\n    //! Copy data if available\n    for (std::map < std::string, RVector >::const_iterator\n         it = mesh.dataMap().begin(); it != mesh.dataMap().end(); it ++){\n\n        if (it->second.size() == mesh.cellCount()){\n            addData(it->first, it->second(this->cellMarkers()));\n        } else if (it->second.size() == mesh.nodeCount()){\n            THROW_TO_IMPL\n        } else if (it->second.size() == mesh.boundaryCount()){\n            THROW_TO_IMPL\n        }\n    }\n    //! copy original marker into the new mesh\n    this->setCellMarkers(RVector(mesh.cellMarkers())(this->cellMarkers()));\n\n}\n\nvoid Mesh::cleanNeighborInfos(){\n    //std::cout << \"Mesh::cleanNeighborInfos()\"<< std::endl;\n    for (Index i = 0; i < cellCount(); i ++){\n        cell(i).cleanNeighborInfos();\n    }\n    for (Index i = 0; i < boundaryCount(); i ++){\n        boundary(i).setLeftCell(NULL);\n        boundary(i).setRightCell(NULL);\n    }\n}\n\nvoid Mesh::createNeighborInfos(bool force){\n//     double med = 0.;\n//     __MS(neighborsKnown_ << \" \" <<force)\n    if (!neighborsKnown_ || force){\n        this->cleanNeighborInfos();\n\n//         Stopwatch sw(true);\n\n        for (Index i = 0; i < cellCount(); i ++){\n//            if (i%10000 ==0) __MS(i);\n            createNeighborInfosCell_(&cell(i));\n//             med+=sw.duration(true);\n        }\n        neighborsKnown_ = true;\n    } else {\n//         __M\n    }\n\n//     std::cout << med << \" \" << med/cellCount() << std::endl;\n}\n\nvoid Mesh::fixBoundaryDirections(){\n    createNeighborInfos();\n    for (Index i = 0; i < this->boundaryCount(); i ++ ){\n        Boundary * b = this->boundaryVector_[i];\n        // __MS(b)\n        if (b->leftCell() != NULL && b->rightCell() == NULL){\n            if (!b->normShowsOutside(*b->leftCell())){\n                //\n                b->swapNorm();\n            }\n        }\n        if (b->leftCell() == NULL && b->rightCell() != NULL){\n            if (!b->normShowsOutside(*b->rightCell())){\n                // __MS(b)\n                b->setLeftCell(b->rightCell());\n                b->setRightCell(NULL);\n                b->swapNorm();\n            }\n        }\n    }\n}\n\nvoid Mesh::createNeighborInfosCell_(Cell *c){\n\n    for (Index j = 0; j < c->boundaryCount(); j++){\n        if (c->neighborCell(j)) continue;\n\n        c->findNeighborCell(j);\n        std::vector < Node * > nodes(c->boundaryNodes(j));\n//         __M\n//         std::cout << *c << std::endl;\n//\n//         std::cout << findBoundary(nodes) << std::endl;\n//         __M\n        Boundary * bound = createBoundary(nodes, 0);\n\n//         Boundary * bound = findBoundary(*nodes[0], *nodes[1], *nodes[2]);\n//         Boundary * bound = findBoundary(nodes);\n//         if (!bound) {\n//             bound = createBoundary_< TriangleFace >(nodes, 0, boundaryCount());\n//         }\n\n        bool cellIsLeft = true;\n        if (bound->shape().nodeCount() == 2) {\n            cellIsLeft = (c->boundaryNodes(j)[0]->id() == bound->node(0).id());\n        } else if (bound->shape().nodeCount() > 2) {\n            // normal vector of boundary shows outside for left cell ... every boundary needs a left cell\n            if (bound->normShowsOutside(*c)){\n                cellIsLeft = true;\n            } else {\n                cellIsLeft = false;\n            }\n        }\n\n        if (bound->leftCell() == NULL && cellIsLeft) {\n            if (bound->rightCell() == c){\n                //* we were already here .. no need to do it again\n                continue;\n            }\n            bound->setLeftCell(c);\n            if (c->neighborCell(j) && bound->rightCell() == NULL) bound->setRightCell(c->neighborCell(j));\n\n        } else if (bound->rightCell() == NULL){\n            if (bound->leftCell() == c){\n                //* we were already here .. no need to do it again\n                continue;\n            } else {\n                bound->setRightCell(c);\n                if (c->neighborCell(j) && bound->leftCell() == NULL ) bound->setLeftCell(c->neighborCell(j));\n            }\n        }\n\n//         if (!bound->leftCell()){\n//             std::cout << *bound << \" \" << bound->leftCell() << \" \" << *bound->rightCell() << std::endl;\n//             throwError(WHERE + \" Ooops, crosscheck -- every boundary need left cell.\");\n//         }\n\n//         std::cout << bound->id() << \" \" << bound->leftCell() << \" \" << bound->rightCell() << std::endl;\n\n        //** cross check;\n        if (((bound->leftCell() != c) && (bound->rightCell() != c)) ||\n            (bound->leftCell() == bound->rightCell())){\n//             std::cerr << *c << std::endl;\n//             std::cerr << *bound << std::endl;\n//             std::cerr << bound->leftCell() << \" \" << bound->rightCell() << std::endl;\n//             if (bound->leftCell()){\n//                 std::cerr << *bound->leftCell() << std::endl;\n//             }\n//             if (bound->rightCell()){\n//                 std::cerr << *bound->rightCell() << std::endl;\n//             }\n\n\n        } else {\n//                     std::cout << nBounds << std::endl;\n//                     std::cerr << bound->leftCell() << \" \" << bound->rightCell() << std::endl;\n        }\n    } // for_each boundary in cell\n}\n\nvoid Mesh::create1DGrid(const RVector & x){\n    this->clear();\n    this->setDimension(1);\n    if (unique(sort(x)).size() != x.size()) {\n        std::cerr << WHERE_AM_I << \"Warning! there are non-unique values in pos\" << std::endl;\n    }\n\n    if (x.size() > 1){\n        this->createNode(x[0], 0.0, 0.0);\n        for (Index i = 1; i < x.size(); i ++){\n            this->createNode(x[i], 0.0, 0.0);\n            std::vector < Node * > nodes(2);\n            nodes[0] = & node(nodeCount() - 2);\n            nodes[1] = & node(nodeCount() - 1);\n            this->createCell(nodes);\n        }\n        this->createNeighborInfos();\n\n        for (Index i = 0; i < boundaryCount(); i ++){\n            if (boundary(i).leftCell() == NULL || boundary(i).rightCell() == NULL){\n                if (std::fabs(boundary(i).node(0).pos()[0] - x[0]) < TOLERANCE) {\n                    boundary(i).setMarker(1);\n                } else if (std::fabs(boundary(i).node(0).pos()[0] - x[x.size()-1]) < TOLERANCE){\n                    boundary(i).setMarker(2);\n                }\n            }\n        }\n\n    } else {\n        std::cerr << WHERE_AM_I << \"Warning! there are too few positions given: \"\n                << x.size() << std::endl;\n    }\n}\n\nvoid Mesh::create2DGrid(const RVector & x, const RVector & y, int markerType,\n                        bool worldBoundaryMarker){\n\n    this->clear();\n    this->setDimension(2);\n    if (unique(sort(x)).size() != x.size()) {\n        std::cerr << WHERE_AM_I << \"Warning! there are non-unique values in pos\" << std::endl;\n    }\n\n    if (unique(sort(y)).size() != y.size()) {\n        std::cerr << WHERE_AM_I << \"Warning! there are non-unique values in pos\" << std::endl;\n    }\n\n    int marker = 0;\n    if (x.size() > 1 && y.size() > 1){\n        for (Index i = 0; i < y.size(); i ++){\n            if (i > 0 && markerType == 2) marker++;\n\n            for (Index j = 0; j < x.size(); j ++){\n                this->createNode(x[j], y[i], 0.0);\n\n                if (i > 0 && j > 0){\n                    if (markerType == 1 || markerType == 12) marker++;\n                    std::vector < Node * > nodes(4);\n                    nodes[3] = & node(this->nodeCount() - 2);\n                    nodes[2] = & node(this->nodeCount() - 1);\n                    nodes[1] = & node(this->nodeCount() - 1 - x.size());\n                    nodes[0] = & node(this->nodeCount() - 2 - x.size());\n\n                    this->createCell(nodes, marker);\n\n//                     this->createTriangle(*nodes[1], *nodes[2], *nodes[3], marker);\n//                     this->createTriangle(*nodes[0], *nodes[1], *nodes[3], marker);\n\n                }\n            }\n            if (markerType == 1) marker = 0;\n        }\n        this->createNeighborInfos();\n\n        for (Index i = 0; i < boundaryCount(); i ++){\n            if (boundary(i).leftCell() == NULL || boundary(i).rightCell() == NULL){\n                // Left\n                if (worldBoundaryMarker){\n                    if (std::abs(boundary(i).norm()[0] + 1.0) < TOLERANCE)\n                        boundary(i).setMarker(MARKER_BOUND_HOMOGEN_NEUMANN);\n                    // Right\n                    else if (std::abs(boundary(i).norm()[0] - 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n                    // Top\n                    else if (std::abs(boundary(i).norm()[1] - 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n                    // Bottom\n                    else if (std::abs(boundary(i).norm()[1] + 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n                } else {\n                    if (std::abs(boundary(i).norm()[0] + 1.0) < TOLERANCE) boundary(i).setMarker(1);\n                    // Right\n                    else if (std::abs(boundary(i).norm()[0] - 1.0) < TOLERANCE) boundary(i).setMarker(2);\n                    // Top\n                    else if (std::abs(boundary(i).norm()[1] - 1.0) < TOLERANCE) boundary(i).setMarker(3);\n                    // Bottom\n                    else if (std::abs(boundary(i).norm()[1] + 1.0) < TOLERANCE) boundary(i).setMarker(4);\n                }\n            }\n        }\n\n    } else {\n        std::cerr << WHERE_AM_I << \"Warning! there are too few positions given: \"\n            << x.size() << \" \" << y.size() << std::endl;\n    }\n}\n\nvoid Mesh::create3DGrid(const RVector & x, const RVector & y, const RVector & z,\n                        int markerType, bool worldBoundaryMarker){\n\n    this->clear();\n    this->setDimension(3);\n    if (unique(sort(x)).size() != x.size()) {\n        std::cerr << WHERE_AM_I << \"Warning! there are non-unique values in pos\" << std::endl;\n    }\n\n    if (unique(sort(y)).size() != y.size()) {\n        std::cerr << WHERE_AM_I << \"Warning! there are non-unique values in pos\" << std::endl;\n    }\n\n    if (unique(sort(z)).size() != z.size()) {\n        std::cerr << WHERE_AM_I << \"Warning! there are non-unique values in pos\" << std::endl;\n    }\n\n    int marker = 0;\n    if (x.size() > 1 && y.size() > 1 && z.size() > 1){\n        for (Index k = 0; k < z.size(); k ++){\n\n            if (k > 0 && markerType == 3) marker++; //** count only increasing z\n\n            for (Index j = 0; j < y.size(); j ++){\n\n                if (j > 0 && markerType == 2) marker++;  //** count increasing y or yz\n                if (j > 0 && k > 0 && markerType == 23) marker++;  //** count increasing y or yz\n\n                for (Index i = 0; i < x.size(); i ++){ //**  count increasing x, yz, xz or xyz\n\n                    this->createNode(x[i], y[j], z[k]);\n\n                    if (i > 0 && j > 0 && k > 0){\n                        if (markerType == 1 || markerType == 12 || markerType == 13 || markerType == 123) marker++; //** increasing y\n\n                        std::vector < Node * > nodes(8);\n\n                        nodes[7] = & node(this->nodeCount() - 2);\n                        nodes[6] = & node(this->nodeCount() - 1);\n                        nodes[5] = & node(this->nodeCount() - 1 - x.size());\n                        nodes[4] = & node(this->nodeCount() - 2 - x.size());\n\n                        nodes[3] = & node(this->nodeCount() - 2 - x.size() * y.size());\n                        nodes[2] = & node(this->nodeCount() - 1 - x.size() * y.size());\n                        nodes[1] = & node(this->nodeCount() - 1 - x.size() - x.size() * y.size());\n                        nodes[0] = & node(this->nodeCount() - 2 - x.size() - x.size() * y.size());\n                        this->createCell(nodes, marker);\n                    } //** first row/column/layer\n                } //** x loop (i)\n                if (markerType == 1) marker = 0;\n                if (j > 0 && k > 0 && markerType == 13) marker -= (x.size() - 1);\n            } //** y loop (j)\n//            if (k > 0 && markerType == 13) marker -= (x.size() - 1) * (y.size() - 1);\n            if (k > 0 && markerType == 13) marker += (x.size() - 1);\n            if (markerType == 2 || markerType == 12) marker = 0;\n        } //** z loop (k)\n        this->createNeighborInfos();\n\n        for (Index i = 0; i < boundaryCount(); i ++){\n            if (boundary(i).leftCell() == NULL || boundary(i).rightCell() == NULL){\n\n                if (worldBoundaryMarker){\n                    // Left\n                    if (std::abs(boundary(i).norm()[0] + 1.0) < TOLERANCE)\n                        boundary(i).setMarker(MARKER_BOUND_HOMOGEN_NEUMANN);\n                    // Right\n                    else if (std::abs(boundary(i).norm()[0] - 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n                    // Top\n                    else if (std::abs(boundary(i).norm()[2] - 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n                    // Bottom\n                    else if (std::abs(boundary(i).norm()[2] + 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n                    // Front\n                    else if (std::abs(boundary(i).norm()[1] - 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n                    // Back\n                    else if (std::abs(boundary(i).norm()[1] + 1.0) < TOLERANCE) boundary(i).setMarker(MARKER_BOUND_MIXED);\n\n                } else {\n                    // Left\n                    if (std::abs(boundary(i).norm()[0] + 1.0) < TOLERANCE) boundary(i).setMarker(1);\n                    // Right\n                    else if (std::abs(boundary(i).norm()[0] - 1.0) < TOLERANCE) boundary(i).setMarker(2);\n                    // Top\n                    else if (std::abs(boundary(i).norm()[2] - 1.0) < TOLERANCE) boundary(i).setMarker(3);\n                    // Bottom\n                    else if (std::abs(boundary(i).norm()[2] + 1.0) < TOLERANCE) boundary(i).setMarker(4);\n                    // Front\n                    else if (std::abs(boundary(i).norm()[1] - 1.0) < TOLERANCE) boundary(i).setMarker(5);\n                    // Back\n                    else if (std::abs(boundary(i).norm()[1] + 1.0) < TOLERANCE) boundary(i).setMarker(6);\n                }\n            }\n        }\n    } else {\n        std::cerr << WHERE_AM_I << \"Warning! there are too few positions given: \"\n            << x.size() << \" \" << y.size() << \" \" << z.size() << std::endl;\n    }\n}\n\nvoid Mesh::createMeshByBoundaries(const Mesh & mesh, const std::vector < Boundary * > & bounds){\n    if (this == &mesh) {\n        log(Error, WHERE_AM_I, \"This mesh and the given mesh need to be different instances.\");\n        return;\n    }\n    this->clear();\n    this->setDimension(mesh.dim());\n\n    std::map < int, Node* > nodeMap;\n\n    //** Create new nodes\n    for (size_t i = 0; i < bounds.size(); i ++){\n        MeshEntity * ent = bounds[i];\n        for (Index j = 0; j < ent->nodeCount(); j ++){\n             if (nodeMap.count(ent->node(j).id()) == 0){\n                 nodeMap[ent->node(j).id()] = this->createNode(ent->node(j));\n             }\n        }\n    }\n\n    //! Create new boundaries\n    for (size_t i = 0; i < bounds.size(); i ++){\n        MeshEntity * ent = bounds[i];\n        std::vector < Node * > nodes(ent->nodeCount());\n        for (Index j = 0; j < nodes.size(); j ++){\n            nodes[j] = nodeMap[ent->node(j).id()];\n        }\n\n        createBoundary(nodes, bounds[i]->marker());\n    }\n\n}\n\nvoid Mesh::createMeshByCells(const Mesh & mesh, const std::vector < Cell * > & cells){\n    if (this == &mesh) {\n        log(Error, WHERE_AM_I, \"This mesh and the given mesh need to be different instances.\");\n        return;\n    }\n    this->clear();\n    this->setDimension(mesh.dim());\n\n    std::map < int, Node* > nodeMap;\n    IndexArray idxList;\n\n    //** Create new nodes\n    for (Index i = 0; i < cells.size(); i ++){\n\n        Cell * cell = cells[i];\n\n        for (Index j = 0; j < cell->nodeCount(); j ++){\n            if (nodeMap.count(cell->node(j).id()) == 0){\n\n                nodeMap[cell->node(j).id()] =\n                        this->createNode(cell->node(j).pos(),\n                                         cell->node(j).marker());\n            }\n        }\n    }\n\n    //! Create new cells\n    for (Index i = 0; i < cells.size(); i ++){\n        Cell * cell = cells[i];\n\n        std::vector < Node * > nodes(cell->nodeCount());\n\n        for (Index j = 0; j < nodes.size(); j ++){\n            nodes[j] = nodeMap[cell->node(j).id()];\n        }\n\n        createCell(nodes, cell->marker());\n        idxList.push_back(cell->id());\n    }\n\n    //! copy all boundary with marker != 0\n    for (Index i = 0, imax = mesh.boundaryCount(); i < imax; i ++){\n        Boundary * bound = &mesh.boundary(i);\n\n        if (bound->marker() != 0){\n            bool inside = true;\n            std::vector < Node * > nodes(bound->nodeCount());\n\n            for (Index j = 0, jmax = bound->nodeCount(); j < jmax; j ++){\n                if (nodeMap.find(bound->node(j).id()) != nodeMap.end()) {\n                    nodes[j] = nodeMap[bound->node(j).id()];\n                } else {\n                    inside = false;\n                    break;\n                }\n            }\n            if (inside){\n                //! check that all nodes have a common cell\n                if (findCommonCell(nodes, false)){\n                    createBoundary(nodes, bound->marker());\n                }\n            }\n        }\n    }\n\n    //! Copy data if available\n    for (std::map < std::string, RVector >::const_iterator\n         it = mesh.dataMap().begin(); it != mesh.dataMap().end(); it ++){\n\n        if (it->second.size() == mesh.cellCount()){\n            addData(it->first, it->second(idxList));\n        } else if (it->second.size() == mesh.nodeCount()){\n            THROW_TO_IMPL\n        } else if (it->second.size() == mesh.boundaryCount()){\n            THROW_TO_IMPL\n        }\n    }\n\n    //! Create all remaining boundaries\n    createNeighborInfos();\n}\n\n\nvoid Mesh::createMeshByCellIdx(const Mesh & mesh, const IndexArray & idxListIn){\n    if (this == &mesh) {\n        log(Error, WHERE_AM_I, \"This mesh and the given mesh need to be different instances.\");\n        return;\n    }\n    this->clear();\n    this->setDimension(mesh.dim());\n\n    IndexArray idxList = unique(sort(idxListIn));\n\n    if (idxList.size() != idxListIn.size()){\n        std::cerr << \"This should not happen: double values in idxListIn: \"\n                  << str(idxListIn.size()) << \" \"\n                  << str(idxList.size()) << std::endl;\n    }\n\n    return createMeshByCells(mesh, mesh.cells(idxList));\n}\n\nMesh Mesh::createMeshByCellIdx(const IndexArray & idxList){\n    Mesh mesh(dimension());\n    mesh.createMeshByCellIdx(*this, idxList);\n    return mesh;\n}\n\nvoid Mesh::createMeshByMarker(const Mesh & mesh, int from, int to){\n    if (this == &mesh) {\n        log(Error, WHERE_AM_I, \"This mesh and the given mesh need to be different instances.\");\n        return;\n    }\n    if (to == -1) to = MAX_INT;\n    else if (to == 0) to = from + 1;\n\n    IndexArray cellIdx;\n\n    for (Index i = 0; i < mesh.cellCount(); i ++){\n        if (mesh.cell(i).marker() >= from && mesh.cell(i).marker() < to){\n            cellIdx.push_back(i);\n        }\n    }\n    createMeshByCellIdx(mesh, cellIdx);\n}\n\nMesh Mesh::createSubMesh(const std::vector< Cell * > & cells) const {\n    Mesh mesh(dimension());\n    mesh.createMeshByCells(*this, cells);\n    return mesh;\n}\n\nMesh Mesh::createSubMesh(const std::vector< Boundary * > & bounds) const {\n    Mesh mesh(dimension());\n    mesh.createMeshByBoundaries(*this, bounds);\n    return mesh;\n}\n\nMesh Mesh::createSubMesh(const std::vector< Node * > & nodes) const {\n    Mesh mesh(dimension());\n    THROW_TO_IMPL\n    return mesh;\n}\n\n\nvoid Mesh::addData(const std::string & name, const RVector & data) {\n  //  std::cout << \"add export Data: \" << name << \" \" << min(data) << \" \"  << max(data) << std::endl;\n    if (dataMap_.count(name)){\n        dataMap_[name] = data;\n    } else {\n        dataMap_.insert(std::make_pair(name, data));\n    }\n}\n\nRVector Mesh::data(const std::string & name) const {\n    if (dataMap_.count(name)){\n        return dataMap_.find(name)->second;\n    } else {\n        throwError(\" Warning!! requested export 'data' vector \" + name +\n        \" does not exist.\");\n    }\n    return RVector(0);\n}\n\nvoid Mesh::clearData(){\n    dataMap_.clear();\n}\n\nvoid Mesh::dataInfo() const{\n    if (dataMap_.empty()){\n        std::cout << \"No data.\" << std::endl;\n    } else {\n        for (std::map < std::string, RVector >::const_iterator\n            it = dataMap_.begin(); it != dataMap_.end(); it ++){\n            std::cout << it->first << \": \" << str(it->second.size()) << std::endl;\n        }\n    }\n}\n\nIVector Mesh::nodeMarkers() const {\n    IVector tmp(nodeCount());\n    std::transform(nodeVector_.begin(), nodeVector_.end(), tmp.begin(), std::mem_fn(& Node::marker));\n    return tmp;\n}\n\nIVector Mesh::boundaryMarkers() const {\n    IVector tmp(boundaryCount());\n    std::transform(boundaryVector_.begin(), boundaryVector_.end(), tmp.begin(),\n                   std::mem_fn(&Boundary::marker));\n    return tmp;\n}\n\nRVector Mesh::cellAttributes() const{\n    #ifdef _MSC_VER\n\tstd::vector < double > tmp(cellCount());\n    std::transform(cellVector_.begin(), cellVector_.end(), tmp.begin(),\n                    std::mem_fn(&Cell::attribute));\n\treturn tmp;\n\t#else\n\tRVector tmp(cellCount());\n    std::transform(cellVector_.begin(), cellVector_.end(), tmp.begin(),\n                    std::mem_fn(&Cell::attribute));\n    return tmp;\n\t#endif\n}\n\nvoid Mesh::setCellAttributes(const RVector & attr){\n    if (attr.size() != (uint)cellCount()){\n        throwError(WHERE_AM_I + \" std::vector attr.size() != cellCount()\" + str(attr.size()) + \" \" + str(cellCount()));\n    }\n    for (Index i = 0; i < cellCount(); i ++) cell(i).setAttribute(attr[i]);\n}\n\nvoid Mesh::setCellAttributes(double attr){\n    for (Index i = 0; i < cellCount(); i ++) cell(i).setAttribute(attr);\n}\n\nvoid Mesh::mapCellAttributes(const std::map < float, float > & aMap){\n    std::map< float, float >::const_iterator itm;\n\n    if (aMap.size() != 0){\n        for (Index i = 0, imax = cellCount(); i < imax; i++){\n            itm = aMap.find(float(cell(i).marker()));\n            if (itm != aMap.end()) cell(i).setAttribute((*itm).second);\n        }\n    }\n}\n\nvoid Mesh::mapBoundaryMarker(const std::map < int, int > & aMap){\n    std::map< int, int >::const_iterator itm;\n    if (aMap.size() != 0){\n        for (Index i = 0, imax = boundaryCount(); i < imax; i++){\n            itm = aMap.find(boundary(i).marker());\n            if (itm != aMap.end()){\n\t       boundary(i).setMarker((*itm).second);\n            }\n        }\n    }\n}\nvoid Mesh::prolongateEmptyCellsValues(RVector & vals, double background) const {\n    IndexArray emptyList(find(abs(vals) < TOLERANCE));\n    if (emptyList.size() == 0) return;\n\n    if (background > -9e99){\n        vals[emptyList] = background;\n        return;\n    }\n    bool smooth = false;\n    bool horizontalWeight = true;\n    Index prolongatedValues = 0;\n\n    if (emptyList.size() > 0){\n        if (deepDebug()) {\n            std::cout << \"Prolongate \" << emptyList.size()\n                      << \" empty cells. (\" << this->cellCount() << \")\" << std::endl;\n        }\n\n        std::map< Cell*, double > prolongationMap;\n        Cell * cell;\n        RVector3 XY(1., 1., 0.);\n        if (this->dim() == 2) XY[1] = 0.0;\n\n        for (Index i = 0; i < emptyList.size(); i ++){\n            cell = &this->cell(emptyList[i]);\n\n            double weight = 0.0;\n            double val = 0.0;\n            for (Index j = 0; j < cell->neighborCellCount(); j ++){\n                Cell * nCell = cell->neighborCell(j);\n                if (nCell){\n                    if (abs(vals[nCell->id()]) > TOLERANCE){\n                        if (horizontalWeight){\n                            Boundary * b=findCommonBoundary(*nCell, *cell);\n                            if (b){\n                                double zWeight = (b->norm()*XY).abs() + 1e-6;\n                                val += vals[nCell->id()] * zWeight;\n                                weight += zWeight;\n                            }\n                        } else {\n                            val += vals[nCell->id()];\n                            weight += 1.0;\n                        }\n                    }\n                }\n            }\n            if (weight > 1e-8) {\n                prolongatedValues ++;\n                if (smooth){\n                    vals[cell->id()] = val / weight;\n                } else {\n                    prolongationMap[cell] = val / weight;\n                }\n            }\n        }\n\n        if (!smooth){\n            for (auto & x: prolongationMap){\n                vals[x.first->id()] = x.second;\n            }\n        }\n        if (!prolongatedValues){\n            this->exportVTK(\"fillEmptyCellsFail\");\n            log(Warning, \"cannot fill emptyList: see fillEmptyCellsFail.vtk. Fill up empty with.\", emptyList.size(), mean(vals));\n            vals[emptyList] = mean(vals);\n            exit(1);\n        }\n        prolongateEmptyCellsValues(vals, background);\n    }\n}\nvoid Mesh::geometryChanged(){\n    rangesKnown_ = false;\n    staticGeometry_ = false;\n}\nMesh & Mesh::transform(const RMatrix & mat){\n//         std::for_each(nodeVector_.begin(), nodeVector_.end(),\n//                        bind2nd(std::mem_fn(&Node::pos().transform), mat));\n    for (auto &n: nodeVector_) n->transform(mat);\n    for (auto &n: holeMarker_) n.transform(mat);\n    for (auto &n: regionMarker_) n.transform(mat);\n\n    if (isGeometry_){\n        for (auto &b: boundaryVector_){\n            if (b->rtti() == MESH_POLYGON_FACE_RTTI){\n                for (auto &p: dynamic_cast< PolygonFace * >(b)->holeMarkers()){\n                    p.transform(mat);\n                }\n            }\n        }\n    }\n    geometryChanged();\n    return *this;\n}\n\nMesh & Mesh::scale(const RVector3 & s){\n    for (auto &n: nodeVector_) n->scale(s);\n    for (auto &n: holeMarker_) n.scale(s);\n    for (auto &n: regionMarker_) n.scale(s);\n\n    if (isGeometry_){\n        for (auto &b: boundaryVector_){\n            if (b->rtti() == MESH_POLYGON_FACE_RTTI){\n                for (auto &p: dynamic_cast< PolygonFace * >(b)->holeMarkers()){\n                    p.scale(s);\n                }\n            }\n        }\n    }\n    geometryChanged();\n    return *this;\n}\n\nMesh & Mesh::translate(const RVector3 & t){\n    for (auto &n: nodeVector_) n->translate(t);\n    for (auto &n: holeMarker_) n.translate(t);\n    for (auto &n: regionMarker_) n.translate(t);\n\n    if (isGeometry_){\n        for (auto &b: boundaryVector_){\n            if (b->rtti() == MESH_POLYGON_FACE_RTTI){\n                for (auto &p: dynamic_cast< PolygonFace * >(b)->holeMarkers()){\n                    p.translate(t);\n                }\n            }\n        }\n    }\n    geometryChanged();\n    return *this;\n}\n\nMesh & Mesh::rotate(const RVector3 & r){\n    for (auto &n: nodeVector_) n->rotate(r);\n    for (auto &n: holeMarker_) n.rotate(r);\n    for (auto &n: regionMarker_) n.rotate(r);\n\n    if (isGeometry_){\n        for (auto &b: boundaryVector_){\n            if (b->rtti() == MESH_POLYGON_FACE_RTTI){\n                for (auto &p: dynamic_cast< PolygonFace * >(b)->holeMarkers()){\n                    p.rotate(r);\n                }\n            }\n        }\n    }\n    geometryChanged();\n    return *this;\n}\n\nMesh & Mesh::deform(const R3Vector & eps, double magnify){\n    ASSERT_VEC_SIZE(eps, this->nodeCount())\n    for (auto &n: nodeVector_) n->translate(magnify * eps[n->id()]);\n    geometryChanged();\n    return *this;\n}\n\nMesh & Mesh::deform(const RVector & eps, double magnify){\n    Index dof = this->nodeCount();\n    ASSERT_VEC_SIZE(eps, dof *this->dim())\n\n    if (this->dim() == 1){\n        for (auto &n: nodeVector_) n->translate(magnify * eps[n->id()]);\n    } else if (this->dim() == 2){\n        for (auto &n: nodeVector_){\n            n->translate(magnify * eps[n->id()],\n                         magnify * eps[n->id() + dof]);\n        }\n    } else if (this->dim() == 3){\n        for (auto *n: nodeVector_)\n            n->translate(magnify * eps[n->id()],\n                         magnify * eps[n->id() + dof],\n                         magnify * eps[n->id() + 2 * dof]);\n    }\n    geometryChanged();\n    return *this;\n}\n\nvoid Mesh::swapCoordinates(Index i, Index j){\n    for (auto &n: nodeVector_) n->swap(i,j);\n    for (auto &n: holeMarker_) n.swap(i,j);\n    for (auto &n: regionMarker_) n.swap(i,j);\n\n    if (isGeometry_){\n        for (auto &b: boundaryVector_){\n            if (b->rtti() == MESH_POLYGON_FACE_RTTI){\n                for (auto &p: dynamic_cast< PolygonFace * >(b)->holeMarkers()){\n                    p.swap(i,j);\n                }\n            }\n        }\n    }\n    geometryChanged();\n}\n\n\nvoid Mesh::relax(){\n   THROW_TO_IMPL\n   //  int E = 0;\n\n//     for (int T = 6; T >= 3; T--){\n//       for (int s = 0; s < Ns; s++){\n// \tif (side[s].mark == 0){\n// \t  if ((node[side[s].a].mark == 0) &&\n// \t       (node[side[s].b].mark == 0) &&\n// \t       (node[side[s].c].mark == 0) &&\n// \t       (node[side[s].d].mark == 0)) {\n// \t    E = node[side[s].c].Nne + node[side[s].d].Nne - node[side[s].a].Nne - node[side[s].b].Nne;\n\n// \t    if (E == T) {\n// \t      node[side[s].a].Nne++; node[side[s].b].Nne++;\n// \t      node[side[s].c].Nne--; node[side[s].d].Nne--;\n// \t      swap_side(s);\n// \t    }\n// \t  }\n// \t}\n//       }\n//     }\n  }\n\nvoid Mesh::smooth(bool nodeMoving, bool edgeSliding, uint smoothFunction, uint smoothIteration){\n    createNeighborInfos();\n\n    for (Index j = 0; j < smoothIteration; j++){\n//         if (edgeSwapping) {\n//             for (Index i = 0; i < boundaryCount(); i++) dynamic_cast< Edge & >(boundary(i)).swap(1);\n//         }\n        if (nodeMoving) {\n            for (Index i = 0; i < nodeCount(); i++) {\n                bool forbidMove = (node(i).marker() != 0);\n\n                std::pair < Boundary *, Boundary * > slide(0, 0);\n                bool noSlide = false;\n                for (std::set< Boundary * >::iterator it = node(i).boundSet().begin();\n                     it != node(i).boundSet().end(); it ++){\n\n                    if ((*it)->marker() != 0){\n                        if (slide.first == 0){\n                            slide.first = (*it);\n                        } else {\n\n                            if (slide.second == 0){\n                                if (slide.first->norm() == (*it)->norm()){\n                                    slide.second = (*it);\n                                } else {\n                                    // two marker bounds with different norm -> corner\n                                    noSlide = true;\n                                }\n                            } else {\n                                // more than two marker bounds -> corner\n                                noSlide = true;\n                            }\n                        }\n                    }\n\n                    if (edgeSliding) {\n                        forbidMove = forbidMove || noSlide;\n                    }else {\n                        forbidMove = forbidMove || (*it)->marker() != 0;\n                    }\n\n                    if (!edgeSliding){\n                        forbidMove = forbidMove || ((*it)->leftCell() == NULL || (*it)->rightCell() == NULL);\n                    }\n\n                    if (forbidMove) break;\n                }\n\n                if (!forbidMove) {\n                    if (slide.first && slide.second){\n                    // move weighted with itself as double weight .. results in slight slide\n                        node(i).setPos((\n                                slide.first->node(0).pos() +\n                                slide.first->node(1).pos() +\n                                slide.second->node(0).pos() +\n                                slide.second->node(1).pos()) / 4.0);\n                    } else {\n                        node(i).smooth(smoothFunction);\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid Mesh::fillKDTree_() const {\n\n    if (!tree_) tree_ = new KDTreeWrapper();\n\n    if (tree_->size() != nodeCount(true)){\n        if (tree_->size() == 0){\n\n            for_each(nodeVector_.begin(), nodeVector_.end(), boost::bind(&KDTreeWrapper::insert, tree_, _1));\n            for_each(secNodeVector_.begin(), secNodeVector_.end(), boost::bind(&KDTreeWrapper::insert, tree_, _1));\n\n            tree_->tree()->optimize();\n        } else {\n            throwError(WHERE_AM_I + str(this) + \" kd-tree is only partially filled: this should no happen: nodeCount = \" + str(nodeCount())\n                                      + \" tree-size() \" + str(tree_->size()));\n        }\n    }\n\n}\n\nvoid Mesh::addRegionMarker(const RegionMarker & reg){\n    regionMarker_.push_back(reg);\n}\n\nvoid Mesh::addRegionMarker(const RVector3 & pos, int marker, double area){\n    if (area < 0) {\n        addHoleMarker(pos);\n    } else {\n        regionMarker_.push_back(RegionMarker(pos, marker, area));\n    }\n}\n\nvoid Mesh::addHoleMarker(const RVector3 & pos){\n    holeMarker_.push_back(pos);\n}\n\nvoid Mesh::interpolationMatrix(const PosVector & q, RSparseMapMatrix & I){\n    I.resize(q.size(), this->nodeCount());\n\n    Index count = 0;\n    Cell * c = 0;\n    RVector cI;\n\n    for (Index i = 0; i < q.size(); i ++ ){\n        c = this->findCell(q[i], count, false);\n        if (c){\n            cI.resize(c->nodeCount());\n            c->N(c->shape().rst(q[i]), cI);\n\n            for (Index j = 0; j < c->nodeCount(); j ++){\n                I.addVal(i, c->ids()[j], cI[j]);\n            }\n        }\n    }\n}\n\nRSparseMapMatrix Mesh::interpolationMatrix(const PosVector & q){\n    RSparseMapMatrix I;\n    interpolationMatrix(q, I);\n    return I;\n}\n\nRSparseMapMatrix & Mesh::cellToBoundaryInterpolation() const {\n    if (!cellToBoundaryInterpolationCache_){\n        if (!neighborsKnown_){\n            throwError(\"Please call once createNeighborInfos() for the given mesh.\");\n        }\n\n        cellToBoundaryInterpolationCache_ = new RSparseMapMatrix(this->boundaryCount(),\n                                                                 this->cellCount());\n        for (Index i = 0; i < boundaryCount(); i ++){\n            Boundary * b = boundaryVector_[i];\n            Cell * lC = b->leftCell();\n            Cell * rC = b->rightCell();\n\n            double df1 = 0.0;\n            double df2 = 0.0;\n\n            bool harmonic = false;\n            if (lC) df1 = b->center().distance(lC->center());\n            if (rC) df2 = b->center().distance(rC->center());\n            double d12 = (df1 + df2);\n\n            if (lC && rC){\n                if (harmonic){\n                    THROW_TO_IMPL\n                } else {\n                    cellToBoundaryInterpolationCache_->addVal(b->id(), lC->id(), df2/d12);\n                    cellToBoundaryInterpolationCache_->addVal(b->id(), rC->id(), -df2/d12 + 1.0);\n                }\n            } else if (lC){\n                cellToBoundaryInterpolationCache_->addVal(b->id(), lC->id(), 1.0);\n            } else {\n                throwError(WHERE_AM_I + \" this should not happen\");\n            }\n        }\n    } else {\n        if (!staticGeometry_){\n            delete cellToBoundaryInterpolationCache_;\n            cellToBoundaryInterpolationCache_ = 0;\n            return this->cellToBoundaryInterpolation();\n        }\n    }\n\n    return *cellToBoundaryInterpolationCache_;\n}\n\nPosVector Mesh::cellDataToBoundaryGradient(const RVector & cellData) const {\n    return cellDataToBoundaryGradient(cellData,\n      boundaryDataToCellGradient(this->cellToBoundaryInterpolation()*cellData));\n}\n\nPosVector Mesh::cellDataToBoundaryGradient(const RVector & cellData,\n                                          const PosVector & cellGrad) const{\n    if (!neighborsKnown_){\n        throwError(\"Please call once createNeighborInfos() for the given mesh.\");\n    }\n    PosVector ret(boundaryCount());\n\n    for (Index i = 0; i < boundaryCount(); i ++){\n        Boundary * b = boundaryVector_[i];\n        Cell * lC = b->leftCell();\n        Cell * rC = b->rightCell();\n\n        RVector3 grad(0.0, 0.0, 0.0);\n        RVector3 tangent((b->node(1).pos() - b->node(0).pos()).norm());\n\n        if (lC && rC){\n            double df1 = b->center().distance(lC->center());\n            double df2 = b->center().distance(rC->center());\n\n            ret[b->id()] = b->norm()*(cellData[rC->id()] - cellData[lC->id()]) / (df1+df2);\n\n            ret[b->id()] += tangent * (tangent.dot(cellGrad[lC->id()]) +\n                                       tangent.dot(cellGrad[rC->id()])) * 0.5;\n        } else if(lC){\n            ret[b->id()] = tangent * tangent.dot(cellGrad[lC->id()]);\n        }\n    }\n    return ret;\n}\n\nPosVector Mesh::boundaryDataToCellGradient(const RVector & v) const{\n    if (!neighborsKnown_){\n        throwError(\"Please call once createNeighborInfos() for the given mesh.\");\n    }\n    PosVector ret(this->cellCount());\n\n    const PosVector & flow = this->boundarySizedNormals();\n    RVector3 vec(0.0, 0.0, 0.0);\n    for (Index i = 0; i < this->boundaryCount(); i ++ ){\n        Boundary * b = this->boundaryVector_[i];\n        vec = flow[b->id()] * v[b->id()];\n\n        if (b->leftCell()){\n            ret[b->leftCell()->id()] += vec;\n        }\n        if (b->rightCell()){\n            ret[b->rightCell()->id()] -= vec;\n        }\n    }\n    for (Index i = 0; i < ret.size(); i ++ ){\n        ret[i] /= cellVector_[i]->size();\n    }\n    return ret;\n}\n\nRVector Mesh::divergence(const PosVector & V) const{\n    RVector ret(this->cellCount());\n\n    if (!neighborsKnown_){\n        throwError(\"Please call once createNeighborInfos() for the given mesh.\");\n    }\n\n    ASSERT_EQUAL(V.size(), this->boundaryCount());\n\n    const PosVector & normB = this->boundarySizedNormals();\n\n    for (Index i = 0; i < this->boundaryCount(); i ++){\n        Boundary * b = this->boundaryVector_[i];\n//         __MS(normB[b->id()] << \" \" << V[b->id()])\n        double vec = normB[b->id()].dot(V[b->id()]);\n\n        if (b->leftCell()){\n            ret[b->leftCell()->id()] += vec;\n        }\n        if (b->rightCell()){\n            ret[b->rightCell()->id()] -= vec;\n        }\n    }\n    return ret / this->cellSizes();\n}\n\nRegionMarker * Mesh::regionMarker(SIndex marker){\n    for (Index i = 0; i < this->regionMarker_.size(); i++){\n        if (this->regionMarker_[i].marker() == marker){\n            return & this->regionMarker_[i];\n        }\n    }\n    throwError(\"There is no regionMarker with marker = \" + str(marker));\n    return 0;\n}\n\nIndex Mesh::hash() const {\n    return GIMLI::hash(this->positions(true),\n                       this->cellMarkers(),\n                       this->boundaryMarkers(),\n                       this->nodeMarkers(),\n                       this->dataMap_);\n}\n\n} // namespace GIMLI\n", "meta": {"hexsha": "84ff4404e12f2a259b31219e1f941c6c8baa7d6a", "size": 91783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/mesh.cpp", "max_stars_repo_name": "baender/gimli", "max_stars_repo_head_hexsha": "eb9a2204669cf11209b9577472f61ac70217a191", "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": "core/src/mesh.cpp", "max_issues_repo_name": "baender/gimli", "max_issues_repo_head_hexsha": "eb9a2204669cf11209b9577472f61ac70217a191", "max_issues_repo_licenses": ["Apache-2.0"], "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/mesh.cpp", "max_forks_repo_name": "baender/gimli", "max_forks_repo_head_hexsha": "eb9a2204669cf11209b9577472f61ac70217a191", "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.5610228594, "max_line_length": 140, "alphanum_fraction": 0.4931523267, "num_tokens": 24069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.136608397056381, "lm_q2_score": 0.018833130613229138, "lm_q1q2_score": 0.0025727637846266905}}
{"text": "\n/*****************************************************************************\n*\n* Copyright (c) 2003-2020 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014-2017 by Centre for Geoscience Computing (GeoComp)\n* Development from 2019 by School of Earth and Environmental Sciences\n**\n*****************************************************************************/\n\n#include \"Data.h\"\n#include \"DataVector.h\"\n#include \"FileWriter.h\"\n#include \"Utils.h\"\n\n#include <cstring>\n#include <fstream>\n#ifndef _WIN32\n# include <unistd.h>\n#endif // _WIN32\n\n#include <boost/python.hpp>\n#include <boost/scoped_array.hpp>\n\n#ifdef ESYS_HAVE_BOOST_NUMPY\n#include <boost/python/numpy.hpp>\n#include \"DataTypes.h\"\n#endif\n\nnamespace bp = boost::python;\n\n#ifndef OVERLORDPATH\n#define OVERLORDPATH \"\"\n#endif\n\nnamespace escript {\n\nint getSvnVersion()\n{\n#ifdef SVN_VERSION\n    return SVN_VERSION;\n#else\n    return 0;\n#endif\n}\n\n// This is probably not very robust, but it works on Savanna today and is\n// useful for performance analysis\nint get_core_id()\n{\n    int processor_num=-1;\n#ifdef CORE_ID1\n    FILE *fp;\n    int i, count_spaces=0;\n    char fname[100];\n    char buf[1000];\n\n    sprintf(fname, \"/proc/%d/stat\", getpid());\n    fp = fopen(fname, \"r\");\n    if (fp == NULL) return(-1);\n    fgets(buf, 1000, fp);\n    fclose(fp);\n\n    for (i=strlen(buf)-1; i>=0; i--) {\n        if (buf[i] == ' ') count_spaces++;\n        if (count_spaces == 4) break;\n    }\n    processor_num = atoi(&buf[i+1]);\n#endif\n    return processor_num;\n}\n\nvoid setNumberOfThreads(int num_threads)\n{\n#ifdef _OPENMP\n    omp_set_num_threads(num_threads);\n#endif\n}\n\nint getNumberOfThreads()\n{\n#ifdef _OPENMP\n    return omp_get_max_threads();\n#else\n    return 1;\n#endif\n}\n\nint getMPISizeWorld()\n{\n    int mpi_num = 1;\n#ifdef ESYS_MPI\n    MPI_Comm_size(MPI_COMM_WORLD, &mpi_num);\n#endif\n    return mpi_num;\n}\n\nint getMPIRankWorld()\n{\n    int mpi_iam = 0;\n#ifdef ESYS_MPI\n    MPI_Comm_rank(MPI_COMM_WORLD, &mpi_iam);\n#endif\n    return mpi_iam;\n}\n\nint getMPIWorldMax(int val)\n{\n#ifdef ESYS_MPI\n    int val2 = val;\n    int out = val;\n    MPI_Allreduce(&val2, &out, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);\n#else\n    int out = val;\n#endif\n    return out;\n}\n\nint getMPIWorldSum(int val)\n{\n#ifdef ESYS_MPI\n    int val2 = val;\n    int out = 0;\n    MPI_Allreduce(&val2, &out, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n#else\n    int out = val;\n#endif\n    return out;\n}\n\nvoid printParallelThreadCnt()\n{\n    char hname[64];\n\n#ifdef HAVE_GETHOSTNAME\n    gethostname(hname, 64);\n    hname[63] = '\\0';\n#else\n    strcpy(hname, \"unknown host\");\n#endif\n\n    const int mpi_num = getMPISizeWorld();\n    const int mpi_iam = getMPIRankWorld();\n\n#pragma omp parallel\n    {\n        int omp_iam=0, omp_num=1;\n#ifdef _OPENMP\n        omp_iam = omp_get_thread_num();\n        omp_num = omp_get_num_threads();\n#endif\n#pragma omp critical (printthrdcount)\n        printf(\"printParallelThreadCounts: MPI=%03d/%03d OpenMP=%03d/%03d \"\n               \"running on %s core %d\\n\", mpi_iam, mpi_num, omp_iam, omp_num,\n               hname, get_core_id());\n    }\n}\n\n#define CHILD_FAIL 2\n#define CHILD_COMPLETE 4\n\n#ifndef _WIN32\n#ifdef ESYS_MPI\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <errno.h>\n#include <arpa/inet.h>\nint prepareSocket(unsigned short *port, int *key)\n{\n    if (getMPIRankWorld() != 0)\n        return 0;\n    int sfd = socket(AF_INET, SOCK_STREAM, 0);\n    if (sfd < 0) {\n        perror(\"socket creation failure\");\n        return -1;\n    }\n    int opt = 1;\n    if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int)) < 0) {\n        perror(\"socket option setting failure\");\n        close(sfd);\n        return -1;\n    }\n\n    struct sockaddr_in addr;\n    addr.sin_family = AF_INET;\n    addr.sin_port = htons(0);\n    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n    memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));\n\n    if (bind(sfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {\n        perror(\"bind failure\");\n        close(sfd);\n        return -1;\n    }\n\n    if (listen(sfd, SOMAXCONN) < 0) {\n        perror(\"listen failure\");\n        close(sfd);\n        return -1;\n    }\n\n    struct sockaddr actual;\n    unsigned int size = sizeof(actual);\n    if (getsockname(sfd, &actual, &size) < 0) {\n        perror(\"failed when determining bound port number\");\n        close(sfd);\n        return -1;\n    }\n\n    //if size > sizeof(actual), some info was truncated, but certainly not port\n\n    *port = ntohs(((struct sockaddr_in *) &actual)->sin_port);\n\n    unsigned int seed = time(NULL) % UINT_MAX;\n    *key = rand_r(&seed);\n    return sfd;\n}\n\nint check_data(unsigned int max, fd_set *all, fd_set *valid, int key, int sfd)\n{\n    int ret = 0;\n    for (int i = 0; i <= max; i++) {\n        if (i == sfd)\n            continue;\n        if (FD_ISSET(i, all)) {\n            int provided = 0;\n            if (recv(i, &provided, sizeof(int), MSG_WAITALL) == sizeof(int)\n                    && provided == key) {\n                char deadspace[1024];\n                while ((provided = recv(i, deadspace, 1024, 0))) {\n                    if (provided == -1) {\n                        if (errno == EAGAIN || errno == EWOULDBLOCK) {\n                            continue;\n                        } else {\n                            perror(\"connection failure\");\n                            return CHILD_FAIL;\n                        }\n                    }\n                }\n                return CHILD_COMPLETE;\n            } else {\n                FD_CLR(i, all);\n                close(i);\n            }\n        }\n    }\n    return ret;\n}\n\nvoid close_all(unsigned int maxfd, fd_set *all)\n{\n    for (int i = 0; i <= maxfd; i++) {\n        if (FD_ISSET(i, all))\n            close(i);\n    }\n}\n\nint waitForCompletion(int sfd, int key)\n{\n    if (getMPIRankWorld() != 0)\n        return 0;\n    int timeout = 10; //max of 10 seconds with no communication\n\n    fd_set all, valid;\n    FD_ZERO(&all);\n    FD_ZERO(&valid);\n    FD_SET(sfd, &all);\n    time_t last_good_time = time(NULL);\n    unsigned int maxfd = sfd;\n    while (time(NULL) - last_good_time < timeout) {\n        struct timeval timer = {1,0}; //1 sec, 0 usec\n        int count = select(maxfd + 1, &all, NULL, NULL, &timer);\n        if (count == -1) { //error\n            if (errno == EINTR) {\n                continue; //just a signal, continue as we were\n            } else {\n                perror(\"socket operation error\");\n                close(sfd);\n                return -1;\n            }\n        } else if (FD_ISSET(sfd, &all)) { //new connection\n            int connection = accept(sfd, NULL, NULL);\n            if (connection > maxfd)\n                maxfd = connection;\n            FD_SET(connection, &all);\n            FD_CLR(connection, &valid);\n            time(&last_good_time);\n            count--;\n        }\n        if (count > 0) { //something to read, either connection key or state\n            int res = check_data(maxfd, &all, &valid, key, sfd);\n            if (res == CHILD_FAIL) {\n                return -1;\n            } else if (res == CHILD_COMPLETE) {\n                close_all(maxfd, &all);\n                return 0;\n            }\n        }\n    }\n    close_all(maxfd, &all);\n    fprintf(stderr, \"Connection to child process timed out\\n\");\n    return -1;\n}\n#endif //ESYS_MPI\n#endif //not _WIN32\n\nint runMPIProgram(bp::list args)\n{\n#ifdef ESYS_MPI\n    unsigned short port = 0;\n    int key = 0;\n    int sock = prepareSocket(&port, &key);\n    if (getMPIWorldSum(sock) < 0)\n        return -1;\n    char portstr[20] = {'\\0'}, keystr[20] = {'\\0'};\n    sprintf(portstr, \"%d\", port);\n    sprintf(keystr, \"%d\", key);\n\n    int nargs = bp::extract<int>(args.attr(\"__len__\")());\n    // make room for port, key and terminator\n    char** c_args = new char*[nargs + 3];\n    c_args[0] = portstr;\n    c_args[1] = keystr;\n    std::vector<std::string> cpp_args(nargs);\n    // skip command name in argument list\n    for (int i = 0; i < nargs; i++) {\n        cpp_args[i] = bp::extract<std::string>(args[i]);\n        c_args[i+2] = const_cast<char*>(cpp_args[i].c_str());\n    }\n    c_args[nargs+2] = NULL;\n\n    MPI_Info info;\n    MPI_Info_create(&info);\n    // force the gmsh process to run on this host as well for network comm\n    char hostname[MPI_MAX_PROCESSOR_NAME];\n    int temp = MPI_MAX_PROCESSOR_NAME;\n    MPI_Get_processor_name(hostname, &temp);\n    char hoststr[] = \"host\"; //for warnings\n    MPI_Info_set(info, hoststr, hostname);\n    MPI_Comm intercomm;\n    int errors;\n    char c_cmd[] = OVERLORDPATH\"escript-overlord\";\n    MPI_Comm_spawn(c_cmd, c_args, 1, info, 0, MPI_COMM_WORLD, &intercomm, &errors);\n    MPI_Info_free(&info);\n    delete[] c_args;\n    if (errors != MPI_SUCCESS)\n        return errors;\n    return getMPIWorldMax(waitForCompletion(sock, key));\n#else //#ifdef ESYS_MPI\n    std::string cmd;\n    int nargs = bp::extract<int>(args.attr(\"__len__\")());\n    for (int i = 0; i < nargs; i++) {\n        cmd += bp::extract<std::string>(args[i]);\n        cmd += \" \";\n    }\n    return system(cmd.c_str());\n#endif //#ifdef ESYS_MPI/else\n}\n#undef CHILD_COMPLETE\n#undef CHILD_FAIL\n\ndouble getMachinePrecision()\n{\n    return std::numeric_limits<double>::epsilon();\n}\n\ndouble getMaxFloat()\n{\n    return std::numeric_limits<double>::max();\n}\n\nvoid MPIBarrierWorld()\n{\n#ifdef ESYS_MPI\n    if (!NoCOMM_WORLD::active()) {\n        MPI_Barrier(MPI_COMM_WORLD );\n    } else {\n        throw EsysException(\"Attempt to use MPI_COMM_WORLD while it is blocked.\");\n    }\n#endif\n}\n\nvoid saveDataCSV(const std::string& filename, bp::dict arg,\n                 const std::string& sep, const std::string& csep, bool refid, bool append)\n{\n    bp::list keys = arg.keys();\n    int numdata = bp::extract<int>(arg.attr(\"__len__\")());\n\n    bool hasmask = arg.has_key(\"mask\");\n    Data mask;\n    if (hasmask) {\n        mask = bp::extract<escript::Data>(arg[\"mask\"]);\n        if (mask.getDataPointRank() != 0) {\n            throw DataException(\"saveDataCSV: mask must be scalar.\");\n        }\n        keys.remove(\"mask\");\n        numdata--;\n    }\n    if (numdata < 1) {\n        throw DataException(\"saveDataCSV: no data to save specified.\");\n    }\n\n    std::vector<int> step(numdata);\n    std::vector<std::string> names(numdata);\n    std::vector<Data> data(numdata);\n    std::vector<int> fstypes(numdata+int(hasmask)); // FunctionSpace types for each data for interpolation\n\n    keys.sort(); // to get some predictable order to things\n\n    // We need to interpret the samples correctly even if they are different\n    // types. For this reason, we should iterate over samples...\n    for (int i=0; i<numdata; ++i) {\n        names[i] = bp::extract<std::string>(keys[i]);\n        data[i] = bp::extract<escript::Data>(arg[keys[i]]);\n        fstypes[i] = data[i].getFunctionSpace().getTypeCode();\n        step[i] = (data[i].actsExpanded() ? DataTypes::noValues(data[i].getDataPointShape()) : 0);\n\n        if (i > 0) {\n            if (data[i].getDomain()!=data[i-1].getDomain()) {\n                throw DataException(\"saveDataCSV: all data must be on the same domain.\");\n            }\n        }\n        if (data[i].isComplex()) {\n            throw DataException(\"saveDataCSV: complex values must be separated into components before calling this.\");\n        }\n    }\n\n    if (hasmask) {\n        if (mask.getDomain() != data[0].getDomain())\n            throw DataException(\"saveDataCSV: mask domain must be the same as the data domain.\");\n        fstypes[numdata] = mask.getFunctionSpace().getTypeCode();\n    }\n\n    int bestfnspace = 0;\n    if (!data[0].getDomain()->commonFunctionSpace(fstypes, bestfnspace)) {\n        throw DataException(\"saveDataCSV: FunctionSpaces of data are incompatible\");\n    }\n\n\n    // now we interpolate all data to the same type\n    FunctionSpace best(data[0].getDomain(), bestfnspace);\n    for (int i=0; i<numdata; ++i) {\n        data[i] = data[i].interpolate(best);\n    }\n    if (hasmask)\n        mask = mask.interpolate(best);\n\n    // these must be the same for all data\n    int numsamples = data[0].getNumSamples();\n    int dpps = data[0].getNumDataPointsPerSample();\n    std::ostringstream os;\n    bool first = true;\n\n    if (data[0].getDomain()->getMPIRank() == 0) {\n        for (int i=0; i<numdata; ++i) {\n            const DataTypes::ShapeType& s=data[i].getDataPointShape();\n            switch (data[i].getDataPointRank()) {\n                case 0:\n                    if (!first) {\n                        os << sep;\n                    } else {\n                        first=false;\n                        if(refid){\n                            os << \"Ref_ID\" << sep;\n                        }\n                    }\n                    os << names[i];\n                    break;\n\n                case 1:\n                    for (int j=0; j<s[0]; ++j) {\n                        if (!first) {\n                            os << sep;\n                        } else {\n                            first=false;\n                            if(refid){\n                                os << \"Ref_ID\" << sep;\n                            }\n                        }\n                        os << names[i] << csep << j;\n                    }\n                    break;\n\n                case 2:\n                    for (int j=0; j<s[0]; ++j) {\n                        for (int k=0; k<s[1]; ++k) {\n                            if (!first) {\n                                os << sep;\n                            } else {\n                                first=false;\n                                if(refid){\n                                    os << \"Ref_ID\" << sep;\n                                }\n                            }\n                            os << names[i] << csep << k << csep << j;\n                        }\n                    }\n                    break;\n\n                case 3:\n                    for (int j=0; j<s[0]; ++j) {\n                        for (int k=0; k<s[1]; ++k) {\n                            for (int l=0; l<s[2]; ++l) {\n                                if (!first) {\n                                    os << sep;\n                                } else {\n                                    first=false;\n                                    if(refid){\n                                        os << \"Ref_ID\" << sep;\n                                    }\n                                }\n                                os << names[i] << csep << k << csep << j\n                                   << csep << l;\n                            }\n                        }\n                    }\n                    break;\n\n                case 4:\n                    for (int j=0; j<s[0]; ++j) {\n                        for (int k=0; k<s[1]; ++k) {\n                            for (int l=0; l<s[2]; ++l) {\n                                for (int m=0; m<s[3]; ++m) {\n                                    if (!first) {\n                                        os << sep;\n                                    } else {\n                                        first=false;\n                                        if(refid){\n                                            os << \"Ref_ID\" << sep;\n                                        }\n                                    }\n                                    os << names[i] << csep << k << csep << j\n                                       << csep << l << csep << m;\n                                }\n                            }\n                        }\n                    }\n                    break;\n\n                default:\n                    throw DataException(\"saveDataCSV: Illegal rank\");\n            }\n        }\n        os << std::endl;\n    }\n\n    const double* masksample = NULL;\n\n    // does the mask act expanded?\n    // Are there mask value for each point in the sample?\n    bool expandedmask = false;\n    // do we output this row?\n    bool wantrow = true;\n    if (hasmask && mask.actsExpanded()) {\n        expandedmask=true;\n    }\n    os.setf(std::ios_base::scientific, std::ios_base::floatfield);\n    os.precision(15);\n\n    // errors prior to this point will occur on all processes anyway\n    // so there is no need to explicitly notify other ranks\n    int error = 0;\n    std::string localmsg;\n    try {\n        std::vector<int> offset(numdata);\n        std::vector<const DataTypes::real_t*> samples(numdata);\n#ifdef ESYS_MPI\n        // Loop over the MPI ranks\n        for(int token = 0; token < data[0].getDomain()->getMPISize(); token++)\n        {\n            data[0].getDomain()->MPIBarrier();\n            if(data[0].getDomain()->getMPIRank() != token)\n                continue;\n#endif\n\n\t    \tconst DataTypes::real_t onlyreal=0;\n            for (int i=0; i<numsamples; ++i) {\n                if (!best.ownSample(i)) {\n                    continue;\n                }\n                wantrow = true;\n                for (int d=0; d<numdata; ++d) {\n                    samples[d] = data[d].getSampleDataRO(i, onlyreal);\n                }\n                if (hasmask) {\n                    masksample = mask.getSampleDataRO(i, onlyreal);\n                    if (!expandedmask) {\n                        // mask controls whole sample\n                        if (masksample[0] <= 0) {\n                            wantrow = false;\n                        }\n                    }\n                }\n                for (int j=0; j<dpps; ++j) {\n                    // now we need to check if this point is masked off\n                    if (expandedmask) {\n                        // masks are scalar so the relevant value is at [j]\n                        wantrow = (masksample[j]>0);\n                    }\n                    if (wantrow) {\n                        bool needsep = false;\n                        // If necessary, write the element id to the output stream\n                        if(refid){\n                            os << best.getReferenceIDOfSample(i) << sep;\n                        }\n                        for (int d = 0; d < numdata; ++d) {\n                            DataTypes::pointToStream(os, samples[d],\n                                data[d].getDataPointShape(), offset[d], needsep, sep);\n                            needsep = true;\n                            offset[d] += step[d];\n                        }\n                        os << std::endl;\n                    }\n                }\n                for (int d = 0; d<numdata; d++) {\n                    offset[d]=0;\n                }\n            }\n#ifdef ESYS_MPI\n        }\n#endif\n    } catch (EsysException* e) {\n        error=1;\n        if (data[0].getDomain()->getMPISize()==1) {\n            throw;\n        } else {\n            localmsg=e->what();\n        }\n    } catch (...) {\n        error=1;\n        if (data[0].getDomain()->getMPISize()==1) {\n            throw;\n        }\n    }\n\n#ifdef ESYS_MPI\n    MPI_Comm com = data[0].getDomain()->getMPIComm();\n    int rerror = 0;\n    MPI_Allreduce(&error, &rerror, 1, MPI_INT, MPI_MAX, com);\n    error = rerror;\n#else\n    MPI_Comm com = MPI_COMM_NULL;\n#endif\n\n    if (error) {\n        if (localmsg.empty()) {\n            throw DataException(\"saveDataCSV: error building output\");\n        }\n        throw DataException(std::string(\"saveDataCSV:\")+localmsg);\n    }\n\n    // at this point os will contain the text to be written\n    FileWriter fw(com);\n    if (!fw.openFile(filename, 0, false, append)) {\n        throw DataException(\"saveDataCSV: unable to open file for writing\");\n    }\n    error = !fw.writeOrdered(os);\n    fw.close();\n\n    data[0].getDomain()->MPIBarrier();\n\n    if (error)\n        throw DataException(\"saveDataCSV: Error writing to file\");\n}\n\n#ifdef ESYS_HAVE_BOOST_NUMPY\nboost::python::list getNumpy(boost::python::dict arg)\n{\n    // Initialise boost python numpy\n    bp::numpy::initialize();\n\n    // Extract the key information and the number of data ppoints\n    bp::list keys = arg.keys();\n    int numdata = bp::extract<int>(arg.attr(\"__len__\")());\n\n    // Process the mask information\n    bool hasmask = arg.has_key(\"mask\");\n    Data mask;\n    if (hasmask) {\n        mask = bp::extract<escript::Data>(arg[\"mask\"]);\n\n        // Possible error: Mask is not scalar\n        if (mask.getDataPointRank() != 0) {\n            throw DataException(\"getNumpy: mask must be scalar.\");\n        }\n\n        keys.remove(\"mask\");\n        numdata--;\n    }\n\n    // Possible error: User forgot to pass some data\n    if (numdata < 1) {\n        throw DataException(\"getNumpy: no data to save specified.\");\n    }\n\n    // Initialise vectors\n    std::vector<int> step(numdata);\n    std::vector<std::string> names(numdata);\n    std::vector<Data> data(numdata);\n    std::vector<int> fstypes(numdata+int(hasmask)); // FunctionSpace types for each data for interpolation\n\n    // We need to interpret the samples correctly even if they are different\n    // types. For this reason, we should iterate over samples...\n    for (int i = 0; i < numdata; ++i) {\n        names[i] = bp::extract<std::string>(keys[i]);\n        data[i] = bp::extract<escript::Data>(arg[keys[i]]);\n        fstypes[i] = data[i].getFunctionSpace().getTypeCode();\n        step[i] = (data[i].actsExpanded() ? DataTypes::noValues(data[i].getDataPointShape()) : 0);\n\n        // Possible error: The data are on different domains\n        if (i > 0) {\n            if (data[i].getDomain()!=data[i-1].getDomain()) {\n                throw DataException(\"getNumpy: all data must be on the same domain.\");\n            }\n        }\n    }\n\n    // Check for complex data\n    bool have_complex = false;\n    for (int i = 0; i < numdata; ++i){\n        if(data[i].isComplex()){\n            have_complex = true;\n        }\n    }\n\n    if (hasmask) {\n        //Possible error: Mask domain is different to the data domain\n        if (mask.getDomain() != data[0].getDomain())\n            throw DataException(\"getNumpy: mask domain must be the same as the data domain.\");\n\n        // Get the mask fs code\n        fstypes[numdata] = mask.getFunctionSpace().getTypeCode();\n    }\n\n    // Possible error: Functionspaces are incompatible so interpolation isn't possible\n    int bestfnspace = 0;\n    if (!data[0].getDomain()->commonFunctionSpace(fstypes, bestfnspace)) {\n        throw DataException(\"getNumpy: FunctionSpaces of data are incompatible\");\n    }\n\n    // Interpolate the data onto the same function space\n    FunctionSpace best(data[0].getDomain(), bestfnspace);\n    for (int i=0; i<numdata; ++i) {\n        data[i] = data[i].interpolate(best);\n    }\n    if (hasmask)\n        mask = mask.interpolate(best);\n\n    // This are needed below\n    const DataTypes::real_t onlyreal = 0;\n    const DataTypes::cplx_t gotcomplex = 0.0;\n\n    // Work out how big the ndarrays have to be\n    int arraylength = 0;\n    int numsamples = data[0].getNumSamples();\n    int dpps = data[0].getNumDataPointsPerSample();\n    if(hasmask){\n        #pragma omp parallel for\n        for(int i = 0; i < numsamples * dpps; i++){\n            arraylength += (bool) *mask.getSampleDataRO(i, onlyreal);\n        }\n    } else {\n        arraylength = dpps * numsamples;\n    }\n\n    //Work out how many rows each array should have\n    std::vector<int> spaces(numdata);\n    signed int total = 0;\n    spaces[0] = 0;\n    for(int i = 0; i < numdata; i++){\n        total += data[i].getShapeProduct();\n        spaces[i+1] = total;\n    }\n\n    // Initialise the numpy ndarray\n    bp::tuple arrayshape = bp::make_tuple(total, arraylength);\n    bp::numpy::dtype datatype = bp::numpy::dtype::get_builtin<double>();\n    if(have_complex){\n        datatype = bp::numpy::dtype::get_builtin<std::complex<double>>();\n    }\n    bp::numpy::ndarray dataArray = bp::numpy::zeros(arrayshape, datatype);\n\n    // Initialise variables\n    const double* masksample = NULL;\n    bool expandedmask = false;              // does the mask act expanded?\n    bool wantrow = true;                    // do we output this row?\n    if (hasmask && mask.actsExpanded()) {\n        expandedmask=true;\n    }\n\n    // Make everything more complicated.\n    if(have_complex){\n        for(int i = 0; i < numdata; i++){\n            if(!data[i].isComplex()){\n                data[i].complicate();\n            }\n        }\n    }\n\n    int error = 0;\n    int maskcounter = 0;\n    std::string localmsg;\n    try {\n        std::vector<int> offset(numdata);\n        std::vector<const DataTypes::real_t*> samplesR(numdata);\n        std::vector<const DataTypes::cplx_t*> samplesC(numdata);\n\n        for (int i = 0; i < numsamples; ++i) {\n\n            // If this MPI process does not own the sample then continue\n            if (!best.ownSample(i)) {\n                continue;\n            }\n\n            // Get the sample data\n            for (int d = 0; d < numdata; ++d) {\n                // if(have_complex){\n                if(data[d].isComplex()){\n                    samplesC[d] = data[d].getSampleDataRO(i, gotcomplex);\n                } else {\n                    samplesR[d] = data[d].getSampleDataRO(i, onlyreal);\n                }\n            }\n\n            // Work out if we want to get this row\n            wantrow = true;\n            if (hasmask) {\n                masksample = mask.getSampleDataRO(i, onlyreal);\n                if (!expandedmask) {\n                    // mask controls whole sample\n                    if (masksample[0] <= 0) {\n                        wantrow = false;\n                    }\n                }\n            }\n\n            // Loop over data points in the sample\n            for (int j = 0; j < dpps; ++j) {\n\n                // now we need to check if this point is masked off\n                if (expandedmask) {\n                    // masks are scalar so the relevant value is at [j]\n                    wantrow = (masksample[j]>0);\n                }\n\n                // If we want the row then add it to the array\n                if (wantrow) {\n                    for (int d = 0; d < numdata; ++d) {\n\n                        if(have_complex){\n                            DataTypes::pointToNumpyArray(dataArray, samplesC[d],\n                                data[d].getDataPointShape(), offset[d], spaces[d], hasmask ? maskcounter : i+j*numsamples);\n                        } else {\n\n                            DataTypes::pointToNumpyArray(dataArray, samplesR[d],\n                                data[d].getDataPointShape(), offset[d], spaces[d], hasmask ? maskcounter : i+j*numsamples);\n                        }\n\n                        offset[d] += step[d];\n                        maskcounter++;\n                    }\n                }\n            }\n\n            // Reset\n            for (int d = 0; d < numdata; d++) {\n                offset[d] = 0;\n            }\n\n        }\n    } catch (EsysException* e) {\n        error=1;\n        if (data[0].getDomain()->getMPISize()==1) {\n            throw;\n        } else {\n            localmsg=e->what();\n        }\n    } catch (...) {\n        error=1;\n        if (data[0].getDomain()->getMPISize()==1) {\n            throw;\n        }\n    }\n\n#ifdef ESYS_MPI\n    MPI_Comm com = data[0].getDomain()->getMPIComm();\n    int rerror = 0;\n    MPI_Allreduce(&error, &rerror, 1, MPI_INT, MPI_MAX, com);\n    error = rerror;\n#endif\n\n    if (error) {\n        if (localmsg.empty()) {\n            throw DataException(\"getNumpy: error building output\");\n        }\n        throw DataException(std::string(\"getNumpy:\")+localmsg);\n    }\n\n    // MPI Barrier\n    data[0].getDomain()->MPIBarrier();\n\n    // Other, unknown errors\n    if (error)\n        throw DataException(\"getNumpy: Unknown error.\");\n\n    // Put everything into a list to return to python\n    bp::list answer;\n    for(int i = 0; i < numdata; i++){\n        bp::numpy::ndarray temp = bp::numpy::zeros(bp::make_tuple(data[i].getShapeProduct(), arraylength), datatype);\n        for(int j = 0; j < data[i].getShapeProduct(); j++){\n            temp[j] = dataArray[spaces[i]+j];\n        }\n        answer.append(names[i]);\n        answer.append(temp);\n    }\n\n    // Print out the ndarray to the console - used during debugging\n    // std::cout << \"Finished array:\\n\" << bp::extract<char const *>(bp::str(dataArray)) << std::endl;\n\n    return answer;\n}\n#else\nvoid getNumpy(bp::dict arg){\n    throw DataException(\"getNumpy: Error - Please recompile escripts with the boost numpy library\");\n}\n#endif\n\n#ifdef ESYS_HAVE_BOOST_NUMPY\nboost::python::numpy::ndarray convertToNumpy(escript::Data data)\n{\n    // Initialise boost numpy\n    // Py_Initialize();\n    boost::python::numpy::initialize();\n\n    // Check to see if we have complex data\n    bool have_complex = data.isComplex();\n\n    // Work out how many data points there are\n    int numDataPoints = data.getNumSamples();\n    int dpps = data.getNumDataPointsPerSample();\n\n    // Work out the data point shape\n    std::vector<int> shape = data.getDataPointShape();\n    if(shape.size() == 0){ // If we have scalar data, the shape will be ()\n        shape.push_back(1);\n    }\n\n    // Work out the shape\n    int dimensions = data.getShapeProduct();\n\n    // Initialise the ndarray\n    boost::python::tuple arrayshape = boost::python::make_tuple(dimensions, dpps * numDataPoints);\n    boost::python::numpy::dtype datatype = boost::python::numpy::dtype::get_builtin<double>();\n    if (have_complex) {\n        datatype = boost::python::numpy::dtype::get_builtin<std::complex<double>>();\n    }\n    boost::python::numpy::ndarray dataArray = boost::python::numpy::zeros(arrayshape, datatype);\n\n    // Initialise variables\n    std::string localmsg;\n    std::vector<const DataTypes::real_t*> samplesR(1);\n\n    // This is needed below in getSampleDataRO\n    const DataTypes::real_t onlyreal = 0;\n    const DataTypes::cplx_t onlycomplex = 0;\n\n// #pragma omp parallel for\n    for (int i = 0; i < numDataPoints; ++i) {\n        for (int j = 0; j < shape[0]; j++) {\n            if(have_complex){\n                dataArray[j][i] = *(data.getSampleDataRO(i, onlycomplex)+j);\n            } else {\n                dataArray[j][i] = *(data.getSampleDataRO(i, onlyreal)+j);\n            }\n        }\n    }\n\n    // Print out the ndarray to the console - used during debugging\n    // std::cout << \"Finished array:\\n\" << bp::extract<char const *>(bp::str(dataArray)) << std::endl;\n\n    return dataArray;\n}\n#else\nvoid convertToNumpy(escript::Data data){\n    throw DataException(\"getNumpy: Error - Please recompile escripts with the boost numpy library\");\n}\n#endif\n\nvoid resolveGroup(bp::object obj)\n{\n    int len=0;\n    try {\n        len=bp::extract<int>(obj.attr(\"__len__\")());\n    }\n    catch(...)\n    {\n        // tell python the error isn't there anymore\n        PyErr_Clear();\n        throw DataException(\"resolveGroup: sequence object expected.\");\n    }\n    std::vector<DataLazy*> dats;\n    std::vector<Data*> dp;\n    for (int i=0; i<len; ++i) {\n        Data* p=0;\n        try {\n            p = bp::extract<Data*>(obj[i]);\n        } catch(...) {\n            PyErr_Clear();\n            throw DataException(\"resolveGroup: only accepts Data objects.\");\n        }\n        if (p->isLazy()) {\n            dats.push_back(dynamic_cast<DataLazy*>(p->borrowData()));\n            dp.push_back(p);\n        }\n    }\n    if (!dats.empty()) {\n        dats[0]->resolveGroupWorker(dats);\n    }\n\n    // all the data will be identities now but still lazy\n    // convert it to ready\n    for (int i=dp.size()-1; i>=0; --i)\n        dp[i]->resolve();\n}\n\n\n} // end of namespace\n", "meta": {"hexsha": "1e99c02b1e15cf105ebf941171af1fcd34a8af73", "size": 31526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "escriptcore/src/Utils.cpp", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "escriptcore/src/Utils.cpp", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "escriptcore/src/Utils.cpp", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4599033816, "max_line_length": 123, "alphanum_fraction": 0.5166212015, "num_tokens": 7647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10818895743752079, "lm_q2_score": 0.02368946974850243, "lm_q1q2_score": 0.0025629390343381657}}
{"text": "\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ASTRONOMY_IO_CARD_HPP\n#define BOOST_ASTRONOMY_IO_CARD_HPP\n\n#include <string>\n#include <sstream>\n\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/type.hpp>\n\n#include <boost/astronomy/exception/fits_exception.hpp>\n\nnamespace boost { namespace astronomy { namespace io {\n\n//!structure to store a card (80 byte key value pairs as well as comments and history cards)\nstruct card\n{\nprivate:\n    std::string card_;\n\npublic:\n    card()\n    {\n        this->card_.reserve(80);\n    }\n    //! creating card from const char*\n    //! it will read 80 char from provided pointer\n    card(char const* c) : card()\n    {\n        this->card_.assign(c, 80);\n    }\n\n    //!a string is expected with lenght no more than 80 chars \n    //!this string will be directly stored in the card\n    //!string must follow all the standerd of the key, value and comment for card\n    card(std::string str) : card()\n    {\n        if (str.length() > 80)\n        {\n            throw invalid_card_length_exception();\n        }\n        this->card_ = str.append(80 - str.length(), ' ');\n    }\n\n    //!key, value and optional comments are expected\n    //!all the values will be directly stored as provided so necessary spaces befor values must be provided\n    //!spaces after the keyword and value will be taken care implicitly\n    card\n    (\n        std::string const& key,\n        std::string const& value,\n        std::string const& comment = \"\"\n    )\n    {\n        if (key.length() > 8)\n        {\n            throw invalid_key_length_exception();\n        }\n        if ((comment.length() > 0) && (value.length() + comment.length() > 68))\n        {\n            throw invalid_value_length_exception();\n        }\n        else if (value.length() > 70)\n        {\n            throw invalid_value_length_exception();\n        }\n\n        if (comment.length())\n        {\n            this->card_ = std::string(key).append(8 - key.length(), ' ') +\n                \"= \" + value + \" /\" + comment +\n                std::string(\"\").append(68 - value.length() + comment.length(), ' ');\n        }\n        else\n        {\n            this->card_ = std::string(key).append(8 - key.length(), ' ') + \"= \" +\n                std::string(value).append(70 - key.length(), ' ');\n        }\n    }\n\n    //!this overload supports date and string types\n    //!key, value and optional comments are expected\n    //!all the values will be directly stored as provided so necessary spaces befor values must be provided\n    //!spaces after the keyword and value will be taken care implicitly\n    void create_card\n    (\n        std::string const& key,\n        std::string const& value,\n        std::string const& comment = \"\"\n    )\n    {\n        if (key.length() > 8)\n        {\n            throw invalid_key_length_exception();\n        }\n        if ((comment.length() > 0) && (value.length() + comment.length() > 68))\n        {\n            throw invalid_value_length_exception();\n        }\n        else if (value.length() > 70)\n        {\n            throw invalid_value_length_exception();\n        }\n\n        if (comment.length())\n        {\n            this->card_ = std::string(key).append(8 - key.length(), ' ') +\n                \"= \" + value + \" /\" + comment +\n                std::string(\"\").append(68 - value.length() + comment.length(), ' ');\n        }\n        else\n        {\n            this->card_ = std::string(key).append(8 - key.length(), ' ') +\n                \"= \" + std::string(value).append(70 - key.length(), ' ');\n        }\n    }\n\n    //!create card with boolean value\n    void create_card(std::string const& key, bool value, std::string const& comment = \"\")\n    {\n        if (value)\n        {\n            create_card(key, std::string(\"T\").insert(0, ' ', 19), comment);\n        }\n        else\n        {\n            create_card(key, std::string(\"F\").insert(0, ' ', 19), comment);\n        }\n    }\n\n    //!create card with numeric value\n    template <typename Value>\n    void create_card(std::string const& key, Value value, std::string const& comment = \"\")\n    {\n        std::ostringstream stream;\n        stream << value;\n\n        std::string val = stream.str();\n        val.insert(0, ' ', 20 - val.length());\n        create_card(key, val, comment);\n    }\n\n    //!create card for complex value\n    template <typename Real, typename Imaginary>\n    void create_card\n    (\n        std::string const& key,\n        Real real,\n        Imaginary imaginary,\n        std::string const& comment = \"\"\n    )\n    {\n        std::ostringstream stream;\n        stream << real << \", \" << imaginary;\n\n        std::string value = \"(\" + stream.str() + \")\";\n\n        create_card(key, value, comment);\n    }\n\n    //! to create comment, history or balnk keyword cards\n    //! value will be put from column 11\n    void create_commentary_card(std::string const& key, std::string const& value)\n    {\n        if (key.length() > 8)\n        {\n            throw invalid_key_length_exception();\n        }\n        if (value.length() > 70)\n        {\n            throw invalid_value_length_exception();\n        }\n\n        this->card_ = std::string(key).append(8 - key.length(), ' ') +\n            \"  \" + std::string(value).append(70 - key.length(), ' ');\n    }\n\n    //!if whole value is set to true then string is returned with trailing spaces\n    std::string key(bool whole = false) const\n    {\n        if (whole)\n        {\n            return this->card_.substr(0, 8);\n        }\n        return boost::algorithm::trim_copy(this->card_.substr(0, 8));\n    }\n\n    /*!\n    return types can be int, float, double, bool, string\n    (date and complex numbers are returned as string surrounded in single quotes or in brackets)\n    */\n    template <typename ReturnType>\n    ReturnType value() const\n    {\n        return value_imp(boost::type<ReturnType>());\n    }\n\n    //!returns value portion of card with comment as std::string \n    std::string value_with_comment() const\n    {\n        return this->card_.substr(10);\n    }\n\n    //!set value of current card\n    void value(std::string const& value)\n    {\n        if (this->key().length() == 0)\n        {\n            throw key_not_defined_exception();\n        }\n        if (value.length() > 70)\n        {\n            throw invalid_value_length_exception();\n        }\n        this->card_.append(70 - value.length(), ' ');\n    }\n\nprivate:\n\n    template <typename ReturnType>\n    ReturnType value_imp(boost::type<ReturnType>) const\n    {\n        std::string val = boost::algorithm::trim_copy(\n            this->card_.substr(10, this->card_.find('/') - 10));\n        return boost::lexical_cast<ReturnType>(val);\n    }\n\n    bool value_imp(boost::type<bool>) const\n    {\n        std::string val = boost::algorithm::trim_copy(\n            this->card_.substr(10, this->card_.find('/') - 10));\n        if (val == \"T\")\n        {\n            return true;\n        }\n        return false;\n    }\n\n};\n\n}}} //namespace boost\n#endif // !BOOST_ASTRONOMY_IO_CARD_HPP\n\n", "meta": {"hexsha": "30f9f5311a8fd8af2edcecfc56710eb433f61018", "size": 7122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/io/card.hpp", "max_stars_repo_name": "Solariii/astronomy", "max_stars_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/astronomy/io/card.hpp", "max_issues_repo_name": "Solariii/astronomy", "max_issues_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/astronomy/io/card.hpp", "max_forks_repo_name": "Solariii/astronomy", "max_forks_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6024096386, "max_line_length": 107, "alphanum_fraction": 0.5582701488, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08882029963593542, "lm_q2_score": 0.02843603304485266, "lm_q1q2_score": 0.002525696975501174}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Data_ElectronPhotonRelaxationDataContainer.hpp\n//! \\author Alex Robinson, Luke Kersting\n//! \\brief  The native electron-photon-relaxation data container class decl.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef DATA_ELECTRON_PHOTON_RELAXATION_DATA_CONTAINER_HPP\n#define DATA_ELECTRON_PHOTON_RELAXATION_DATA_CONTAINER_HPP\n\n// Std Lib Includes\n#include <vector>\n#include <set>\n#include <map>\n#include <utility>\n#include <string>\n\n// Boost Includes\n#include <boost/serialization/split_member.hpp>\n\n// FRENSIE Includes\n#include \"Utility_StandardArchivableObject.hpp\"\n#include \"Utility_StandardSerializableObject.hpp\"\n\nnamespace Data{\n\n/*! The electron-photon-relaxation data container\n * \\details Linear-linear interpolation should be used for all data.\n */\nclass ElectronPhotonRelaxationDataContainer : public Utility::StandardArchivableObject<ElectronPhotonRelaxationDataContainer,false>, public Utility::StandardSerializableObject<ElectronPhotonRelaxationDataContainer,false>\n{\n\npublic:\n\n  //! Constructor (from saved archive)\n  ElectronPhotonRelaxationDataContainer( \n\t\t  const std::string& archive_name,\n                  const Utility::ArchivableObject::ArchiveType archive_type =\n\t\t  Utility::ArchivableObject::XML_ARCHIVE );\n\n  //! Destructor\n  virtual ~ElectronPhotonRelaxationDataContainer()\n  { /* ... */ }\n\n//---------------------------------------------------------------------------//\n// GET RELAXATION DATA\n//---------------------------------------------------------------------------//\n\n  //! Return the atomic number\n  unsigned getAtomicNumber() const;\n\n  //! Return the atomic subshells \n  const std::set<unsigned>& getSubshells() const;\n\n  //! Return the occupancy for a subshell\n  double getSubshellOccupancy( const unsigned subshell ) const;\n\n  //! Return the binding energy for a subshell\n  double getSubshellBindingEnergy( const unsigned subshell ) const;\n\n  //! Return if there is relaxation data\n  bool hasRelaxationData() const;\n\n  //! Return if the subshell has relaxation data\n  bool hasSubshellRelaxationData( const unsigned subshell ) const;\n\n  //! Return the number of transitions that can fill a subshell vacancy\n  unsigned getSubshellRelaxationTransitions( const unsigned subshell ) const;\n\n  //! Return the relaxation vacancies for a subshell\n  const std::vector<std::pair<unsigned,unsigned> >&\n  getSubshellRelaxationVacancies( const unsigned subshell ) const;\n\n  //! Return the relaxation particle energies for a subshell\n  const std::vector<double>& getSubshellRelaxationParticleEnergies(\n\t\t\t\t\t       const unsigned subshell ) const;\n\n  //! Return the relaxation probabilities for a subshell\n  const std::vector<double>& getSubshellRelaxationProbabilities(\n\t\t\t\t\t       const unsigned subshell ) const;\n\n//---------------------------------------------------------------------------//\n// GET PHOTON DATA \n//---------------------------------------------------------------------------//\n\n  //! Return the Compton profile momentum grid \n  const std::vector<double>& getComptonProfileMomentumGrid(\n\t\t\t\t\t       const unsigned subshell ) const;\n\n  //! Return the Compton profile for a subshell\n  const std::vector<double>& getComptonProfile(const unsigned subshell ) const;\n\n  //! Return the occupation number momentum grid \n  const std::vector<double>& getOccupationNumberMomentumGrid(\n\t\t\t\t\t       const unsigned subshell ) const;\n  \n  //! Return the occupation number for a subshell\n  const std::vector<double>& getOccupationNumber(\n\t\t\t\t\t       const unsigned subshell ) const;\n\n  //! Return the Waller-Hartree scattering function momentum grid\n  const std::vector<double>& \n  getWallerHartreeScatteringFunctionMomentumGrid() const;\n\n  //! Return the Waller-Hartree scattering function\n  const std::vector<double>& getWallerHartreeScatteringFunction() const;\n  \n  //! Return the Waller-Hartree atomic form factor momentum grid\n  const std::vector<double>&\n  getWallerHartreeAtomicFormFactorMomentumGrid() const;\n\n  //! Return the Waller-Hartree atomic form factor\n  const std::vector<double>& getWallerHartreeAtomicFormFactor() const;\n\n  //! Return the photon energy grid\n  const std::vector<double>& getPhotonEnergyGrid() const;\n\n  //! Return the average heating numbers\n  const std::vector<double>& getAveragePhotonHeatingNumbers() const;\n\n  //! Return the Waller-Hartree (WH) incoherent photon cross section \n  const std::vector<double>& \n  getWallerHartreeIncoherentCrossSection() const;\n\n  //! Return the WH incoherent photon cross section threshold energy bin index\n  unsigned\n  getWallerHartreeIncoherentCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the impluse approx. (IA) incoherent photon cross section\n  const std::vector<double>&\n  getImpulseApproxIncoherentCrossSection() const;\n\n  //! Return the IA incoherent photon cross section threshold energy bin index\n  unsigned\n  getImpulseApproxIncoherentCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the subshell Impulse approx. incoherent photon cross section\n  const std::vector<double>&\n  getImpulseApproxSubshellIncoherentCrossSection( \n\t\t\t\t\t       const unsigned subshell ) const;\n\n  //! Return the subshell IA incoherent photon cs threshold energy bin index\n  unsigned\n  getImpulseApproxSubshellIncoherentCrossSectionThresholdEnergyIndex( \n\t\t\t\t\t       const unsigned subshell ) const;\n\n  //! Return the Waller-Hartree coherent cross section\n  const std::vector<double>&\n  getWallerHartreeCoherentCrossSection() const;\n\n  //! Return the Waller-Hartree coherent cs threshold energy bin index\n  unsigned\n  getWallerHartreeCoherentCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the pair production cross section\n  const std::vector<double>&\n  getPairProductionCrossSection() const;\n\n  //! Return the pair production cross section threshold energy bin index\n  unsigned getPairProductionCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the Photoelectric effect cross section\n  const std::vector<double>& getPhotoelectricCrossSection() const;\n\n  //! Return the Photoelectric effect cross section theshold energy bin index\n  unsigned getPhotoelectricCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the Photoelectric effect cross section for a subshell\n  const std::vector<double>&\n  getSubshellPhotoelectricCrossSection( const unsigned subshell ) const;\n\n  //! Return the subshell Photoelectric effect cross section threshold index\n  unsigned\n  getSubshellPhotoelectricCrossSectionThresholdEnergyIndex( \n\t\t\t\t\t       const unsigned subshell ) const;\n\n  //! Return the Waller-Hartree total cross section\n  const std::vector<double>& getWallerHartreeTotalCrossSection() const;\n\n  //! Return the impulse approx. total cross section\n  const std::vector<double>& getImpulseApproxTotalCrossSection() const;\n\n\n//---------------------------------------------------------------------------//\n// GET ELECTRON DATA \n//---------------------------------------------------------------------------//\n\n  //! Return the upper cutoff scattering angle below which moment preserving elastic scattering is used\n  double getCutoffAngle() const;\n\n  //! Return the elastic angular energy grid\n  const std::vector<double>& getElasticAngularEnergyGrid() const;\n\n  //! Return the analog elastic scattering angles for an incoming energy\n  const std::vector<double>& getAnalogElasticAngles(\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the analog elastic scatering pdf for an incoming energy\n  const std::vector<double>& getAnalogElasticPDF(\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the screened Rutherford elastic normalization constants\n  const std::vector<double>& getScreenedRutherfordNormalizationConstant() const;\n\n  //! Return Moliere's screening constant\n  const std::vector<double>& getMoliereScreeningConstant() const;\n\n  //! Return the moment preserving elastic discrete angles for an incoming energy\n  const std::vector<double>& getMomentPreservingElasticDiscreteAngles(\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the moment preserving elastic weights for an incoming energy\n  const std::vector<double>& getMomentPreservingElasticWeights(\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the electroionization energy grid for the recoil electron spectrum for a subshell\n  const std::vector<double>& getElectroionizationEnergyGrid( \n                           const unsigned subshell ) const;\n\n  //! Return the electroionization recoil energy for a subshell and incoming energy\n  const std::vector<double>& getElectroionizationRecoilEnergy( \n                           const unsigned subshell,\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the electroionization recoil energy pdf for a subshell and incoming energy\n  const std::vector<double>& getElectroionizationRecoilPDF( \n                           const unsigned subshell,\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the bremsstrahlung energy grid for the secondary photon spectrum\n  const std::vector<double>& getBremsstrahlungEnergyGrid() const;\n\n  //! Return the bremsstrahlung photon energy for an incoming energy\n  const std::vector<double>& getBremsstrahlungPhotonEnergy(\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the bremsstrahlung photon energy pdf for an incoming energy\n  const std::vector<double>& getBremsstrahlungPhotonPDF(\n\t\t\t\t\t       const double incoming_energy ) const;\n\n  //! Return the atomic excitation average energy loss energy grid\n  const std::vector<double>& getAtomicExcitationEnergyGrid() const;\n\n  //! Return the atomic excitation average energy loss\n  const std::vector<double>& getAtomicExcitationEnergyLoss() const;\n\n  //! Return the electron energy grid\n  const std::vector<double>& getElectronEnergyGrid() const;\n\n  //! Return the elastic electron cross section below mu = 0.999999\n  const std::vector<double>& getCutoffElasticCrossSection() const;\n\n  //! Return the cutoff elastic cross section threshold energy bin index\n  unsigned getCutoffElasticCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the screened Rutherford elastic electron cross section\n  const std::vector<double>& getScreenedRutherfordElasticCrossSection() const;\n\n  //! Return the screened Rutherford elastic cross section threshold energy bin index\n  unsigned getScreenedRutherfordElasticCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the total elastic electron cross section\n  const std::vector<double>& getTotalElasticCrossSection() const;\n\n  //! Return the total elastic cross section threshold energy bin index\n  unsigned getTotalElasticCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the Moment Preserving (MP) elastic electron cross section\n  const std::vector<double>& getMomentPreservingCrossSection() const;\n\n  //! Return the MP elastic cross section threshold energy bin index\n  unsigned getMomentPreservingCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the electroionization electron cross section for a subshell\n  const std::vector<double>& \n    getElectroionizationCrossSection( const unsigned subshell ) const;\n\n  //! Return the electroionization cross section threshold energy bin index for a subshell\n  unsigned getElectroionizationCrossSectionThresholdEnergyIndex( \n    const unsigned subshell ) const;\n\n  //! Return the bremsstrahlung electron cross section\n  const std::vector<double>& getBremsstrahlungCrossSection() const;\n\n  //! Return the bremsstrahlung cross section threshold energy bin index\n  unsigned getBremsstrahlungCrossSectionThresholdEnergyIndex() const;\n\n  //! Return the atomic excitation electron cross section\n  const std::vector<double>& getAtomicExcitationCrossSection() const;\n\n  //! Return the atomic excitation cross section threshold energy bin index\n  unsigned getAtomicExcitationCrossSectionThresholdEnergyIndex() const;\n\nprotected:\n\n  //! Default constructor\n  ElectronPhotonRelaxationDataContainer()\n  { /* ... */ }\n\n//---------------------------------------------------------------------------//\n// SET RELAXATION DATA\n//---------------------------------------------------------------------------//\n\n  //! Set the atomic number\n  void setAtomicNumber( const unsigned atomic_number );\n  \n  //! Set the atomic subshells\n  void setSubshells( const std::set<unsigned>& subshells );\n\n  //! Set the occupancy for a subshell\n  void setSubshellOccupancy( const unsigned subshell,\n\t\t\t     const double occupancy );\n  \n  //! Set the binding energy for a subshell\n  void setSubshellBindingEnergy( const unsigned subshell,\n\t\t\t\t const double binding_energy );\n\n  //! Set the number of transitions that can fill a subshell vacancy\n  void setSubshellRelaxationTransitions( const unsigned subshell,\n\t\t\t\t\t const unsigned transitions );\n\n  //! Set the relaxation vacancies for a subshell\n  void setSubshellRelaxationVacancies( \n      const unsigned subshell,\n      const std::vector<std::pair<unsigned,unsigned> >& relaxation_vacancies );\n\n  //! Set the relaxation particle energies for a subshell\n  void setSubshellRelaxationParticleEnergies(\n\t\t     const unsigned subshell,\n\t\t     const std::vector<double>& relaxation_particle_energies );\n\n  //! Set the relaxation probabilities for a subshell\n  void setSubshellRelaxationProbabilities( \n\t\t\t const unsigned subshell,\n\t\t\t const std::vector<double>& relaxation_probabilities );\n  \n//---------------------------------------------------------------------------//\n// SET PHOTON DATA \n//---------------------------------------------------------------------------//\n\n  //! Set the Compton profile momentum grid \n  void setComptonProfileMomentumGrid(\n\t\t    const unsigned subshell,\n\t\t    const std::vector<double>& compton_profile_momentum_grid );\n  \n  //! Set the Compton profile for a subshell\n  void setComptonProfile( const unsigned subshell,\n\t\t\t  const std::vector<double>& compton_profile );\n  \n  //! Set the occupation number momentum grid \n  void setOccupationNumberMomentumGrid( \n\t\t   const unsigned subshell,\n\t\t   const std::vector<double>& occupation_number_momentum_grid );\n  \n  //! Set the occupation number for a subshell\n  void setOccupationNumber( const unsigned subshell,\n\t\t\t   const std::vector<double>& occupation_number );\n\n  //! Set the Waller-Hartree scattering function momentum grid\n  void setWallerHartreeScatteringFunctionMomentumGrid(\n\t\t\t\t    const std::vector<double>& momentum_grid );\n  \n  //! Set the Waller-Hartree scattering function \n  void setWallerHartreeScatteringFunction(\n\t\t\t      const std::vector<double>& scattering_function );\n\n  //! Set the Waller-Hartree atomic form factor momentum grid\n  void setWallerHartreeAtomicFormFactorMomentumGrid(\n\t\t\t\t    const std::vector<double>& momentum_grid );\n  \n  //! Set the Waller-Hartree atomic form factor \n  void setWallerHartreeAtomicFormFactor(\n\t\t\t       const std::vector<double>& atomic_form_factor );\n  \n  //! Set the photon energy grid\n  void setPhotonEnergyGrid( const std::vector<double>& energy_grid );\n\n  //! Set the average photon heating numbers\n  void setAveragePhotonHeatingNumbers( \n\t\t\t\t  const std::vector<double>& heating_numbers );\n  \n  //! Set the incoherent photon cross section using Waller-Hartree (WH) theory\n  void setWallerHartreeIncoherentCrossSection(\n\t\t\t const std::vector<double>& incoherent_cross_section );\n\n  //! Set the WH incoherent cross section threshold energy bin index\n  void setWallerHartreeIncoherentCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t        const unsigned index );\n  \n  //! Set the incoherent photon cross section using the impulse approx. (IA)\n  void setImpulseApproxIncoherentCrossSection(\n\t\t\t const std::vector<double>& incoherent_cross_section );\n\n  //! Set the IA incoherent photon cross section threshold energy bin index\n  void setImpulseApproxIncoherentCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t\tconst unsigned index );\n\n  //! Set the IA subshell incoherent photon cross section\n  void setImpulseApproxSubshellIncoherentCrossSection(\n\t\t\t const unsigned subshell,\n\t\t\t const std::vector<double>& incoherent_cross_section );\n\n  //! Set the IA subshell incoherent photon cs threshold energy bin index\n  void setImpulseApproxSubshellIncoherentCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t       const unsigned subshell,\n\t\t\t\t\t\t       const unsigned index );\n  \n  //! Set the WH coherent cross section \n  void setWallerHartreeCoherentCrossSection(\n\t\t\t   const std::vector<double>& coherent_cross_section );\n\n  //! Set the WH coherent cross section threshold energy bin index\n  void setWallerHartreeCoherentCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t\tconst unsigned index );\n  \n  //! Set the pair production cross section\n  void setPairProductionCrossSection(\n\t\t    const std::vector<double>& pair_production_cross_section );\n\n  //! Set the pair production cross section threshold energy bin index\n  void setPairProductionCrossSectionThresholdEnergyIndex( \n\t\t\t\t\t\t\tconst unsigned index );\n\n  //! Set the Photoelectric effect cross section\n  void setPhotoelectricCrossSection(\n\t\t      const std::vector<double>& photoelectric_cross_section );\n\n  //! Set the Photoelectric effect cross section threshold energy bin index\n  void setPhotoelectricCrossSectionThresholdEnergyIndex(const unsigned index );\n  \n  //! Set the Photoelectric effect cross section for a subshell\n  void setSubshellPhotoelectricCrossSection( \n\t\t      const unsigned subshell,\n\t\t      const std::vector<double>& photoelectric_cross_section );\n  \n  //! Set the subshell Photoelectric effect cross section threshold index\n  void setSubshellPhotoelectricCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t       const unsigned subshell,\n\t\t\t\t\t\t       const unsigned index );\n\n  //! Set the Waller-Hartree total cross section\n  void setWallerHartreeTotalCrossSection( \n\t\t\t      const std::vector<double>& total_cross_section );\n\n  //! Set the impulse approx. total cross section\n  void setImpulseApproxTotalCrossSection(\n\t\t\t      const std::vector<double>& total_cross_section );\n\n//---------------------------------------------------------------------------//\n// SET ELECTRON DATA \n//---------------------------------------------------------------------------//\n\n  //! Set the elastic cutoff angle\n  void setCutoffAngle( const double cutoff_angle );\n\n  //! Set the elastic angular energy grid\n  void setElasticAngularEnergyGrid( \n    const std::vector<double>& angular_energy_grid );\n\n  //! Set the elastic scattering angles for an incoming energy\n  void setAnalogElasticAnglesAtEnergy( \n    const double incoming_energy,\n    const std::vector<double>& elastic_angles );\n\n  //! Set the elastic scattering pdf for an incoming energy\n  void setAnalogElasticPDFAtEnergy( \n    const double incoming_energy,\n    const std::vector<double>& elastic_pdf );\n\n  //! Set the elastic scattering angles\n  void setAnalogElasticAngles(\n    const std::map<double,std::vector<double> >& elastic_angles );\n\n  //! Set the elastic scattering pdf\n  void setAnalogElasticPDF(\n    const std::map<double,std::vector<double> >& elastic_pdf );\n\n  //! Set the screened Rutherford elastic normalization constant\n  void setScreenedRutherfordNormalizationConstant(\n    const std::vector<double>& screened_rutherford_normalization_constant );\n\n  //! Set Moliere's screening constant\n  void setMoliereScreeningConstant(\n    const std::vector<double>& moliere_screening_constant );\n\n  //! Set the moment preserving elastic discrete angles for an incoming energy\n  void setMomentPreservingElasticDiscreteAngles(\n\tconst double incoming_energy,\n\tconst std::vector<double>& moment_preserving_elastic_discrete_angles );\n\n  //! Set the moment preserving elastic weights for an incoming energy\n  void setMomentPreservingElasticWeights( \n\tconst double incoming_energy,\n\tconst std::vector<double>& moment_preserving_elastic_weights );\n\n  //! Set the electroionization energy grid for the recoil electron spectrum\n  void setElectroionizationEnergyGrid(\n    const unsigned subshell, \n    const std::vector<double>& electroionization_energy_grid );\n\n  //! Set the electroionization recoil energy for an incoming energy and subshell\n  void setElectroionizationRecoilEnergyAtIncomingEnergy( \n    const unsigned subshell, \n    const double incoming_energy,\n    const std::vector<double>& electroionization_recoil_energy );\n\n  //! Set the electroionization recoil energy pdf for an incoming energy and subshell\n  void setElectroionizationRecoilPDFAtIncomingEnergy(\n    const unsigned subshell,\n    const double incoming_energy,\n    const std::vector<double>& electroionization_recoil_pdf );\n\n  //! Set electroionization recoil energy for all incoming energies in a subshell\n  void setElectroionizationRecoilEnergy(\n    const unsigned subshell,\n    const std::map<double,std::vector<double> >& electroionization_recoil_energy );\n\n  //! Set electroionization recoil energy pdf for all incoming energies in a subshell\n  void setElectroionizationRecoilPDF(\n    const unsigned subshell,\n    const std::map<double,std::vector<double> >& electroionization_recoil_pdf );\n\n  //! Set the bremsstrahlung energy grid for the secondary photon spectrum\n  void setBremsstrahlungEnergyGrid( \n    const std::vector<double>& bremsstrahlung_energy_grid );\n\n  //! Set the bremsstrahlung photon energy for an incoming energy\n  void setBremsstrahlungPhotonEnergyAtIncomingEnergy(\n    const double incoming_energy,\n    const std::vector<double>& bremsstrahlung_photon_energy );\n\n  //! Set the bremsstrahlung photon energy pdf for an incoming energy\n  void setBremsstrahlungPhotonPDFAtIncomingEnergy(\n    const double incoming_energy,\n    const std::vector<double>&  bremsstrahlung_photon_pdf );\n\n  //! Set all the bremsstrahlung photon energy data\n  void setBremsstrahlungPhotonEnergy(\n    const std::map<double,std::vector<double> >& bremsstrahlung_photon_energy );\n\n  //! Set all the bremsstrahlung photon energy pdf data\n  void setBremsstrahlungPhotonPDF(\n    const std::map<double,std::vector<double> >&  bremsstrahlung_photon_pdf );\n\n  //! Set the atomic excitation average energy loss energy grid\n  void setAtomicExcitationEnergyGrid( \n    const std::vector<double>& atomic_excitation_energy_grid );\n\n  //! Set the atomic excitation average energy loss\n  void setAtomicExcitationEnergyLoss( \n            const std::vector<double>& atomic_excitation_energy_loss );\n  \n  //! Set the electron energy grid\n  void setElectronEnergyGrid( const std::vector<double>& energy_grid );\n\n  //! Set the elastic electron cross section below mu = 0.999999\n  void setCutoffElasticCrossSection( \n    const std::vector<double>& cutoff_elastic_cross_section );\n\n  //! Set the elastic cutoff cross section threshold energy bin index\n  void setCutoffElasticCrossSectionThresholdEnergyIndex( const unsigned index );\n\n  //! Set the screened Rutherford elastic electron cross section\n  void setScreenedRutherfordElasticCrossSection( \n    const std::vector<double>& total_elastic_cross_section );\n\n  //! Set the screened Rutherford elastic cross section threshold energy bin index\n  void setScreenedRutherfordElasticCrossSectionThresholdEnergyIndex( const unsigned index );\n\n  //! Set the total elastic electron cross section\n  void setTotalElasticCrossSection( \n    const std::vector<double>& total_elastic_cross_section );\n\n  //! Set the total elastic cross section threshold energy bin index\n  void setTotalElasticCrossSectionThresholdEnergyIndex( const unsigned index );\n\n  //! Set the moment preserving elastic electron cross section using Moment Preserving (MP) theory\n  void setMomentPreservingCrossSection(\n\t\t\t const std::vector<double>& moment_preserving_elastic_cross_section );\n\n  //! Set the MP moment preserving elastic cross section threshold energy bin index\n  void setMomentPreservingCrossSectionThresholdEnergyIndex(\n\t\t\t\t\t\t        const unsigned index );\n\n  //! Set the electroionization electron cross section for a subshell\n  void setElectroionizationCrossSection( const unsigned subshell,\n\t\t\t const std::vector<double>& electroionization_cross_section );\n\n  //! Set the electroionization cross section threshold energy bin index\n  void setElectroionizationCrossSectionThresholdEnergyIndex( \n             const unsigned subshell,\n             const unsigned index );\n\n  //! Set the bremsstrahlung electron cross section \n  void setBremsstrahlungCrossSection(\n\t\t\t const std::vector<double>& bremsstrahlung_cross_section );\n\n  //! Set the bremsstrahlung cross section threshold energy bin index\n  void setBremsstrahlungCrossSectionThresholdEnergyIndex( \n                                const unsigned index );\n\n  //! Set the atomic excitation electron cross section \n  void setAtomicExcitationCrossSection(\n\t\t\t const std::vector<double>& atomic_excitation_cross_section );\n\n  //! Set the bremsstrahlung cross section threshold energy bin index\n  void setAtomicExcitationCrossSectionThresholdEnergyIndex( \n                                const unsigned index );\n\nprivate:\n\n  // Test if a value is less than or equal to zero\n  static bool isValueLessThanOrEqualToZero( const double value );\n\n  // Test if a value is less than zero\n  static bool isValueLessThanZero( const double value );\n\n  // Test if a value is greater than one\n  static bool isValueGreaterThanOne( const double value );\n\n  // Test if a value is less than minus one\n  static bool isValueLessThanMinusOne( const double value );\n\n  // Save the data to an archive\n  template<typename Archive>\n  void save( Archive& ar, const unsigned version ) const;\n  \n  // Load the data 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//---------------------------------------------------------------------------//\n// RELAXATION DATA\n//---------------------------------------------------------------------------//\n\n  // The atomic number\n  unsigned d_atomic_number;\n\n  // The atomic subshells (ENDF designators)\n  std::set<unsigned> d_subshells;\n\n  // The subshell occupancies\n  std::map<unsigned,double> d_subshell_occupancies;\n\n  // The subshell binding energies\n  std::map<unsigned,double> d_subshell_binding_energies;\n\n  // The subshell relaxation transitions\n  std::map<unsigned,unsigned> d_relaxation_transitions;\n\n  // The subshell relaxation vacancies\n  std::map<unsigned,std::vector<std::pair<unsigned,unsigned> > >\n  d_relaxation_vacancies;\n\n  // The subshell relaxation particle energies\n  std::map<unsigned,std::vector<double> > d_relaxation_particle_energies;\n\n  // The subshell relaxation probabilities\n  std::map<unsigned,std::vector<double> > d_relaxation_probabilities;\n\n//---------------------------------------------------------------------------//\n// PHOTON DATA\n//---------------------------------------------------------------------------//\n\n  // The Compton profile momentum grids (me*c units)\n  std::map<unsigned,std::vector<double> > d_compton_profile_momentum_grids;\n\n  // The subshell Compton profiles ((me*c)^-1 units)\n  std::map<unsigned,std::vector<double> > d_compton_profiles;\n\n  // The occupation number momentum grids\n  std::map<unsigned,std::vector<double> > d_occupation_number_momentum_grids;\n\n  // The subshell occupation numbers\n  std::map<unsigned,std::vector<double> > d_occupation_numbers;\n\n  // The Waller-Hartree scattering function momentum grid (1/cm)\n  std::vector<double> d_waller_hartree_scattering_function_momentum_grid;\n\n  // The Waller-Hartree scattering function\n  std::vector<double> d_waller_hartree_scattering_function;\n\n  // The Waller-Hartree atomic form factor momentum grid (1/cm)\n  std::vector<double> d_waller_hartree_atomic_form_factor_momentum_grid;\n\n  // The Waller-Hartree atomic form factor\n  std::vector<double> d_waller_hartree_atomic_form_factor;\n\n  // The photon energy grid (MeV)\n  std::vector<double> d_photon_energy_grid;\n  \n  // The average heating numbers\n  std::vector<double> d_average_photon_heating_numbers;\n\n  // The Waller-Hartree incoherent photon cross section (b)\n  std::vector<double> d_waller_hartree_incoherent_cross_section;\n\n  // The Waller-Hartree incoherent photon cross section threshold energy index\n  unsigned d_waller_hartree_incoherent_cross_section_threshold_index;\n\n  // The impulse approx. incoherent photon cross section (b)\n  std::vector<double> d_impulse_approx_incoherent_cross_section;\n\n  // The impulse approx. incoherent photon cross section threshold energy index\n  unsigned d_impulse_approx_incoherent_cross_section_threshold_index;\n\n  // The impulse approx. subshell incoherent photon cross sections (b)\n  std::map<unsigned,std::vector<double> > \n  d_impulse_approx_subshell_incoherent_cross_sections;\n\n  // The impulse approx. subshell incoherent photon cross section thes. indices\n  std::map<unsigned,unsigned> \n  d_impulse_approx_subshell_incoherent_cross_section_theshold_indices;\n\n  // The Waller-Hartree coherent cross section (b)\n  std::vector<double> d_waller_hartree_coherent_cross_section;\n\n  // The Waller-Hartree coherent cross section threshold energy index\n  unsigned d_waller_hartree_coherent_cross_section_threshold_index;\n\n  // The pair production cross section (b)\n  std::vector<double> d_pair_production_cross_section;\n  \n  // The pair production cross section threshold energy index\n  unsigned d_pair_production_cross_section_threshold_index;\n\n  // The photoelectric effect cross section (b)\n  std::vector<double> d_photoelectric_cross_section;\n\n  // The photoelectric effect cross section energy index\n  unsigned d_photoelectric_cross_section_threshold_index;\n\n  // The subshell photoelectric effect cross sections (b)\n  std::map<unsigned,std::vector<double> > \n  d_subshell_photoelectric_cross_sections;\n\n  // The subshell photoelectric effect cross section threshold indices\n  std::map<unsigned,unsigned> \n  d_subshell_photoelectric_cross_section_threshold_indices;\n\n  // The Waller-Hartree total cross section (b)\n  std::vector<double> d_waller_hartree_total_cross_section;\n\n  // The impulse approx. total cross section (b)\n  std::vector<double> d_impulse_approx_total_cross_section;\n\n\n//---------------------------------------------------------------------------//\n// ELECTRON DATA \n//---------------------------------------------------------------------------//\n\n  // The elastic cutoff angle\n  double d_cutoff_angle;\n\n  // The elastic angular energy grid (MeV)\n  std::vector<double> d_angular_energy_grid;\n\n  // The analog elastic scattering angles\n  std::map<double,std::vector<double> > d_analog_elastic_angles;\n\n  // The analog elastic scattering pdf\n  std::map<double,std::vector<double> > d_analog_elastic_pdf;\n\n  // The screened rutherford normalization constant for elastic scattering\n  std::vector<double> d_screened_rutherford_normalization_constant;\n\n  // Moliere's screening constant\n  std::vector<double> d_moliere_screening_constant;\n\n  // The moment preserving elastic discrete angles\n  std::map<double,std::vector<double> > d_moment_preserving_elastic_discrete_angles;\n\n  // The moment preserving elastic weights\n  std::map<double,std::vector<double> > d_moment_preserving_elastic_weights;\n\n  // The electroionization energy grid (MeV) for a subshell\n  std::map<unsigned,std::vector<double> > d_electroionization_energy_grid;\n\n  // The electroionization recoil energy for subshell and incoming energy\n  std::map<unsigned,std::map<double,std::vector<double> > > \n    d_electroionization_recoil_energy;\n\n  // The electroionization recoil pdf for subshell and incoming energy\n  std::map<unsigned,std::map<double,std::vector<double> > > \n    d_electroionization_recoil_pdf;\n\n  // The bremsstrahlung energy grid (MeV)\n  std::vector<double> d_bremsstrahlung_energy_grid;\n\n  // The bremsstrahlung photon energy\n  std::map<double,std::vector<double> > d_bremsstrahlung_photon_energy;\n\n  // The bremsstrahlung photon pdf\n  std::map<double,std::vector<double> > d_bremsstrahlung_photon_pdf;\n\n  // The atomic excitation energy grid (MeV)\n  std::vector<double> d_atomic_excitation_energy_grid;\n\n  // The atomic excitation energy loss\n  std::vector<double> d_atomic_excitation_energy_loss;\n\n  // The electron energy grid (MeV)\n  std::vector<double> d_electron_energy_grid;\n\n  // The cutoff elastic electron cross section (b)\n  std::vector<double> d_cutoff_elastic_cross_section;\n\n  // The cutoff elastic electron cross section threshold energy index\n  unsigned d_cutoff_elastic_cross_section_threshold_index;\n\n  // The screened rutherford elastic electron cross section (b)\n  std::vector<double> d_screened_rutherford_elastic_cross_section;\n\n  // The screened rutherford elastic electron cross section threshold energy index\n  unsigned d_screened_rutherford_elastic_cross_section_threshold_index;\n\n  // The total elastic electron cross section (b)\n  std::vector<double> d_total_elastic_cross_section;\n\n  // The total elastic electron cross section threshold energy index\n  unsigned d_total_elastic_cross_section_threshold_index;\n\n  // The Moment Preserving elastic electron cross section (b)\n  std::vector<double> d_moment_preserving_elastic_cross_section;\n\n  // The Moment Preserving elastic electron cross section threshold energy index\n  unsigned d_moment_preserving_elastic_cross_section_threshold_index;\n\n  // The electroionization subshell electron cross section (b)\n  std::map<unsigned,std::vector<double> > \n    d_electroionization_subshell_cross_section;\n\n  // The hard elastic electron cross section threshold energy index\n  std::map<unsigned,unsigned>\n    d_electroionization_subshell_cross_section_threshold_index;\n\n  // The bremsstrahlung electron cross section (b)\n  std::vector<double> d_bremsstrahlung_cross_section;\n\n  // The bremsstrahlung electron cross section threshold energy index\n  unsigned d_bremsstrahlung_cross_section_threshold_index;\n\n  // The atomic excitation electron cross section (b)\n  std::vector<double> d_atomic_excitation_cross_section;\n\n  // The atomic excitation electron cross section threshold energy index\n  unsigned d_atomic_excitation_cross_section_threshold_index;\n};\n\n} // end Data namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"Data_ElectronPhotonRelaxationDataContainer_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end DATA_ELECTRON_PHOTON_RELAXATION_DATA_CONTAINER_HPP\n\n//---------------------------------------------------------------------------//\n// end Data_ElectronPhotonRelaxationDataContainer.hpp\n//---------------------------------------------------------------------------//\n\n", "meta": {"hexsha": "b1d75dcdc6484f6b828ffbf5a85bce1406cecc6c", "size": 34688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/data/native/src/Data_ElectronPhotonRelaxationDataContainer.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/data/native/src/Data_ElectronPhotonRelaxationDataContainer.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/data/native/src/Data_ElectronPhotonRelaxationDataContainer.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": 39.7798165138, "max_line_length": 220, "alphanum_fraction": 0.7283210332, "num_tokens": 7376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296423676207597, "lm_q2_score": 0.01590639538555799, "lm_q1q2_score": 0.002114981722076525}}
{"text": "/// \\file   legal_entity.hpp\n///\n/// \\brief\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2018-04-28\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#ifndef ESL_LEGAL_ENTITY_HPP\n#define ESL_LEGAL_ENTITY_HPP\n\n#include <array>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include <boost/serialization/nvp.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <cassert>\n\nnamespace esl::law {\n\n    struct legal_entity\n    {\n\n    };\n\n    ///\n    /// \\brief  legal_entity implements the Legal Entity Identifier system\n    /// described in ISO 17442.\n    ///\n    struct iso_17442\n    {\n        ///\n        /// \\brief The local part describing the local issuing party of the LEI.\n        ///\n        const std::array<char, 4> local;\n\n        ///\n        /// \\brief  The code part describing uniquely a firm that is in the\n        /// issuing party's business area.\n        ///\n        const std::array<char, 12> code;\n\n        ///\n        /// \\brief  Constructs a LEI from the local part and the code part.\n        /// \\param local    The local part describing the local issuing party of\n        /// the LEI. \\param code     The code part describing uniquely a firm\n        /// that is in the issuing party's business area.\n        constexpr iso_17442(const std::array<char, 4> &local = {'0'},\n                               const std::array<char, 12> &code = {'0'})\n        : local(local), code(code)\n        {\n\n        }\n\n        ///\n        /// \\param text The LEI in string form. Assumes the string contains only\n        /// the LEI (20 digits). Tests the reserved\n        ///             digits (which are assumed to be '00') and tests the\n        ///             checksum (compared to computed value), when assertions\n        ///             are enabled.\n        explicit iso_17442(const std::string &text)\n        : local {text[0], text[1], text[2], text[3]}\n        , code {text[6],  text[7],  text[8],  text[9],  text[10], text[11],\n                text[12], text[13], text[14], text[15], text[16], text[17]}\n        {\n            assert(18 == text.length() || 20 == text.length());\n            for(auto i = 0; i < 4; ++i) {\n                assert('0' <= text[i] && '9' >= text[i]);\n            }\n            assert('0' == text[4] && '0' == text[5]);\n            for(auto i = 6; i < 18; ++i) {\n                assert(('0' <= text[i] && '9' >= text[i])\n                       || ('A' <= text[i] && 'Z' >= text[i]));\n            }\n\n            if(20 == text.length()){\n                auto checksum_ = this->checksum();\n                assert(text[18] == std::get<0>(checksum_)\n                       && text[19] == std::get<1>(checksum_));\n            }\n        }\n\n        ///\n        /// \\brief  creates a valid (but fictional) LEI code from a hash. By\n        /// default the issuing unit is set to 0000, which\n        ///         as of 2019-03 is not used[1], therefore it can be assumed we\n        ///         don't collide with existing legal entities. However, there\n        ///         can be collisions in the space of 36^12 possible LEI's\n        ///\n        /// [1] https://www.leiroc.org/faq/index.htm\n        /// @return Fictional LEI code based on the given hash.\n        ///\n        template<typename hashable_t_>\n        static iso_17442 create(const hashable_t_ &h,\n                                   const std::array<char, 4> local = {'0', '0',\n                                                                      '0', '0'})\n        {\n\n            constexpr std::array<char, 36> table_ = {\n                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',\n                'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n                'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};\n\n            auto integer_ = std::hash<hashable_t_>()(h);\n\n            std::array<char, 12> code_ = {};\n\n            for(size_t i = 0; i < code_.size(); ++i) {\n                code_[i] = table_[integer_ % table_.size()];\n                integer_ /= table_.size();\n            }\n\n            return iso_17442(local, code_);\n        }\n\n        ///\n        /// \\brief  Computes the two digit checksum which is specified in ISO\n        ///         17442. Uses uint128_t in the computation, as\n        ///         at least log2(10^4 * 10^2 * 10^(12*2) * 10^2) = 106.301699\n        ///         bits are required. For this, Boost.MultiPrecision is\n        ///         required (which chooses the platform-appropriate integer\n        ///         model).\n        ///\n        /// \\return The checksum digits (not integer values)\n        [[nodiscard]] std::tuple<char, char> checksum() const\n        {\n            boost::multiprecision::uint128_t sum_{0};\n\n            for(auto i = 0; i < 4; ++i) {\n                sum_ *= 10;\n                sum_ += local[i] - '0';\n            }\n            sum_ *= 100;\n            for(auto i = 0; i < 12; ++i) {\n                if('0' <= code[i] && '9' >= code[i]) {\n                    sum_ *= 10;\n                    sum_ += code[i] - '0';\n                } else {\n                    sum_ *= 100;\n                    sum_ += code[i] - 'A' + 10;\n                }\n            }\n            sum_ *= 100;\n            const uint8_t check_ = static_cast<uint8_t>(98 - (sum_ % 97));\n\n            return {static_cast<char>(check_ / 10 + '0'),\n                    static_cast<char>(check_ % 10 + '0')};\n        }\n\n        ///\n        /// \\brief  Only the local part and the code part are serialised, as the\n        /// reserved digits are always '00' and the\n        ///         checksum can be cheaply computed when rendering.\n        ///\n        /// \\tparam archive_t\n        /// \\param archive\n        /// \\param version\n        template<class archive_t>\n        void serialize(archive_t &archive, const unsigned int version)\n        {\n            (void)version;\n            archive &boost::serialization::make_nvp(\n                \"local\", const_cast<std::array<char, 4> &>(local));\n            archive &boost::serialization::make_nvp(\n                \"code\", const_cast<std::array<char, 12> &>(code));\n        }\n\n        ///\n        /// \\brief  Renders the LEI: this asserts the reserved digits are '00',\n        /// and freshly computes the checksum. \\param o \\param le \\return The\n        /// modified output stream\n        friend std::ostream &operator << (std::ostream &o, const iso_17442 &le)\n        {\n            o.write(le.local.data(), le.local.size());\n            o << \"00\";\n            o.write(le.code.data(), le.code.size());\n            auto checksum_ = le.checksum();\n            o << std::get<0>(checksum_) << std::get<1>(checksum_);\n            return o;\n        }\n    };\n\n}  // namespace esl::law\n\n#ifdef WITH_MPI\n#include <boost/mpi.hpp>\nnamespace boost::mpi {\n        template<>\n    struct is_mpi_datatype<esl::law::legal_entity>\n    : mpl::true_\n    {\n\n    };\n\n    template<>\n    struct is_mpi_datatype<esl::law::iso_17442>\n    : mpl::false_\n    {\n\n    };\n}      // namespace boost::mpi\n#endif  // WITH_MPI\n\n#endif  // ESL_LEGAL_ENTITY_HPP\n", "meta": {"hexsha": "ce5f8d651a456cf5b93c7a8c6309c9c411d9d8be", "size": 7958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "esl/law/legal_entity.hpp", "max_stars_repo_name": "vishalbelsare/ESL", "max_stars_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T12:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T10:40:29.000Z", "max_issues_repo_path": "esl/law/legal_entity.hpp", "max_issues_repo_name": "vishalbelsare/ESL", "max_issues_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-20T04:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T06:18:33.000Z", "max_forks_repo_path": "esl/law/legal_entity.hpp", "max_forks_repo_name": "vishalbelsare/ESL", "max_forks_repo_head_hexsha": "cea6feda1e588d5f441742dbb1e4c5479b47d357", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T15:59:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T17:28:24.000Z", "avg_line_length": 35.3688888889, "max_line_length": 80, "alphanum_fraction": 0.4977381252, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06853748732424027, "lm_q2_score": 0.028436032427331594, "lm_q1q2_score": 0.0019489342120399243}}
{"text": "/*\n * drakeUtil.cpp\n *\n *  Created on: Jun 19, 2013\n *      Author: russt\n */\n\n#include \"drakeUtil.h\"\n#include <string.h>\n#include <string>\n#include <math.h>\n#include <limits>\n#include <Eigen/Dense>\n\nusing namespace std;\n\nbool isa(const mxArray* mxa, const char* class_str)\n// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab\n{\n  mxArray* plhs;\n  mxArray* prhs[2];\n  prhs[0] = const_cast<mxArray*>(mxa);\n  prhs[1] = mxCreateString(class_str);\n  mexCallMATLAB(1,&plhs,2,prhs,\"isa\");\n  bool tf = *mxGetLogicals(plhs);\n  mxDestroyArray(plhs);\n  mxDestroyArray(prhs[1]);\n  return tf;\n}\n\nbool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)\n{\n  int i;\n  mxArray* ex = mexCallMATLABWithTrap(nlhs,plhs,nrhs,prhs,filename);\n  if (ex) {\n    mexPrintf(\"DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\\n\",filename);\n    for (i=0; i<nrhs; i++)\n      mexCallMATLAB(0,NULL,1,&prhs[i],\"disp\");\n    mxArray *report;\n    mexCallMATLAB(1,&report,1,&ex,\"getReport\");\n    char *errmsg = mxArrayToString(report);\n    mexPrintf(errmsg);\n    mxFree(errmsg);\n    mxDestroyArray(report);\n    mexErrMsgIdAndTxt(\"Drake:mexCallMATLABsafe:CallbackError\", \"Error in MATLAB callback.\\nSee additional debugging information above\");\n    mxDestroyArray(ex);\n    return true;\n  }\n  for (i=0; i<nlhs; i++)\n    if (!plhs[i]) {\n      mexPrintf(\"Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\\n\", filename);\n      for (i=0; i<nrhs; i++)\n        mexCallMATLAB(0,NULL,1,&prhs[i],\"disp\");\n      mexErrMsgIdAndTxt(\"Drake:mexCallMATLABsafe:NotEnoughOutputs\",\"Asked for %d outputs, but function only returned %d\\n\",nrhs,i);\n      return true;\n    }\n  return false;\n}\n\n\n/*\n * @param subclass_name (optional) if you want to call a class that derives from\n * DrakeMexPointer (e.g. so that you can refer to it as something more specific in\n * your matlab code), then you can pass in the alternative name here.  The constructor\n * for this class must take the same inputs as the DrakeMexPointer constructor.\n */\nmxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)\n{\n\tmxClassID cid;\n\tif (sizeof(ptr)==4) cid = mxUINT32_CLASS;\n\telse if (sizeof(ptr)==8) cid = mxUINT64_CLASS;\n  else mexErrMsgIdAndTxt(\"Drake:constructDrakeMexPointer:PointerSize\",\"Are you on a 32-bit machine or 64-bit machine??\");\n\n\tint nrhs=3+num_additional_inputs;\n\tmxArray *plhs[1];\n  mxArray **prhs;  prhs = new mxArray*[nrhs];\n\n\tprhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);\n  memcpy(mxGetData(prhs[0]),&ptr,sizeof(ptr));\n\n\tprhs[1] = mxCreateString(mexFunctionName());\n\n  prhs[2] = mxCreateString(name);\n\n  for (int i=0; i<num_additional_inputs; i++)\n    prhs[3+i] = delete_fcn_additional_inputs[i];\n\n//  mexPrintf(\"deleteMethod = %s\\n name =%s\\n\", deleteMethod,name);\n\n  // call matlab to construct mex pointer object\n  if (subclass_name) {\n    mexCallMATLABsafe(1,plhs,nrhs,prhs,subclass_name);\n    if (!isa(plhs[0],\"DrakeMexPointer\")) {\n      mxDestroyArray(plhs[0]);\n      mexErrMsgIdAndTxt(\"Drake:createDrakeMexPointer:InvalidSubclass\",\"subclass_name is not a valid subclass of DrakeMexPointer\");\n    }\n  }\n  else\n    mexCallMATLABsafe(1,plhs,nrhs,prhs,\"DrakeMexPointer\");\n\n  mexLock();\n\n//  mexPrintf(\"incrementing lock count\\n\");\n\n  delete[] prhs;\n  return plhs[0];\n}\n\nvoid* getDrakeMexPointer(const mxArray* mx)\n{\n\tvoid* ptr = NULL;\n\n\t// todo: optimize this by caching the pointer values, as described in\n\t// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590\n\tmxArray* ptrArray = mxGetProperty(mx,0,\"ptr\");\n\tif (!ptrArray)\n\t\tmexErrMsgIdAndTxt(\"Drake:getDrakeMexPointer:BadInputs\",\"cannot retrieve 'ptr' field from this mxArray.  are you sure it's a valid DrakeMexPointer object?\");\n\n  if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray)!=1)\n    mexErrMsgIdAndTxt(\"Drake:getDrakeMexPointer:BadInputs\",\"the ptr property of this DrakeMexPointer does not appear to contain a valid pointer\");\n  memcpy(&ptr,mxGetData(ptrArray),sizeof(ptr));     // note: could use a reinterpret_cast here instead\n\n  return ptr;\n}\n\ndouble angleAverage(double theta1, double theta2) {\n  // Computes the average between two angles by averaging points on the unit\n  // circle and taking the arctan of the result.\n  //   see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities\n  // theta1 is a scalar or column vector of angles (rad)\n  // theta2 is a scalar or column vector of angles (rad)\n\n  double x_mean = 0.5*(cos(theta1)+cos(theta2));\n  double y_mean = 0.5*(sin(theta1)+sin(theta2));\n\n  double angle_mean = atan2(y_mean,x_mean);\n\n  return angle_mean;\n}\n\nstd::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)\n{\n  // TODO: implement multi-column version\n  using namespace Eigen;\n\n  if (abs(normal.squaredNorm() - 1.0) > 1e-12) {\n    mexErrMsgIdAndTxt(\"Drake:resolveCenterOfPressure:BadInputs\", \"normal should be a unit vector\");\n  }\n\n  Vector3d cop;\n  double normal_torque_at_cop;\n\n  double fz = normal.dot(force);\n  bool cop_exists = abs(fz) > 1e-12;\n\n  if (cop_exists) {\n    auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);\n    double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);\n    auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;\n    cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;\n    auto torque_at_cop = torque - cop.cross(force);\n    normal_torque_at_cop = normal.dot(torque_at_cop);\n  }\n  else {\n    cop.setConstant(std::numeric_limits<double>::quiet_NaN());\n    normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();\n  }\n  return std::pair<Vector3d, double>(cop, normal_torque_at_cop);\n}\n", "meta": {"hexsha": "0fcda06bfa0b2f0c9a4a5ad0d6a75a2782221116", "size": 6005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/drakeUtil.cpp", "max_stars_repo_name": "andybarry/drake", "max_stars_repo_head_hexsha": "61428cff8cb523314cd87105821148519460a0b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/drakeUtil.cpp", "max_issues_repo_name": "andybarry/drake", "max_issues_repo_head_hexsha": "61428cff8cb523314cd87105821148519460a0b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/drakeUtil.cpp", "max_forks_repo_name": "andybarry/drake", "max_forks_repo_head_hexsha": "61428cff8cb523314cd87105821148519460a0b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T18:52:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T18:52:51.000Z", "avg_line_length": 35.3235294118, "max_line_length": 169, "alphanum_fraction": 0.7210657785, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12085323882332896, "lm_q2_score": 0.01518905034039856, "lm_q1q2_score": 0.0018356459282877534}}
{"text": "#pragma once\n#ifndef SMPLX_UTIL_63B0803D_E0C7_4529_A796_9F6ED269E89F\n#define SMPLX_UTIL_63B0803D_E0C7_4529_A796_9F6ED269E89F\n#include \"smplx/defs.hpp\"\n\n#include <random>\n\n#define _SMPLX_ASSERT(x)                                                 \\\n    do {                                                                 \\\n        if (!(x)) {                                                      \\\n            std::cerr << \"smplx assertion FAILED: \\\"\" << #x << \"\\\" (\"    \\\n                      << (bool)(x) << \")\\n  at \" << __FILE__ << \" line \" \\\n                      << __LINE__ << \"\\n\";                               \\\n            std::exit(1);                                                \\\n        }                                                                \\\n    } while (0)\n#define _SMPLX_ASSERT_EQ(x, y)                                            \\\n    do {                                                                  \\\n        if ((x) != (y)) {                                                 \\\n            std::cerr << \"smplx assertion FAILED: \" << #x << \" == \" << #y \\\n                      << \" (\" << (x) << \" != \" << (y) << \")\\n  at \"       \\\n                      << __FILE__ << \" line \" << __LINE__ << \"\\n\";        \\\n            std::exit(1);                                                 \\\n        }                                                                 \\\n    } while (0)\n#define _SMPLX_ASSERT_NE(x, y)                                            \\\n    do {                                                                  \\\n        if ((x) == (y)) {                                                 \\\n            std::cerr << \"smplx assertion FAILED: \" << #x << \" != \" << #y \\\n                      << \" (\" << (x) << \" == \" << (y) << \")\\n  at \"       \\\n                      << __FILE__ << \" line \" << __LINE__ << \"\\n\";        \\\n            std::exit(1);                                                 \\\n        }                                                                 \\\n    } while (0)\n#define _SMPLX_ASSERT_LE(x, y)                                                 \\\n    do {                                                                       \\\n        if ((x) > (y)) {                                                       \\\n            std::cerr << \"smplx assertion FAILED: \" << #x << \" <= \" << #y      \\\n                      << \" (\" << (x) << \" > \" << (y) << \")\\n  at \" << __FILE__ \\\n                      << \" line \" << __LINE__ << \"\\n\";                         \\\n            std::exit(1);                                                      \\\n        }                                                                      \\\n    } while (0)\n#define _SMPLX_ASSERT_LT(x, y)                                           \\\n    do {                                                                 \\\n        if ((x) >= (y)) {                                                \\\n            std::cerr << \"smplx assertion FAILED: \" << #x << \" < \" << #y \\\n                      << \" (\" << (x) << \" >= \" << (y) << \")\\n  at \"      \\\n                      << __FILE__ << \" line \" << __LINE__ << \"\\n\";       \\\n            std::exit(1);                                                \\\n        }                                                                \\\n    } while (0)\n\n#include <chrono>\n#define _SMPLX_BEGIN_PROFILE \\\n    auto start = std::chrono::high_resolution_clock::now()\n#define _SMPLX_PROFILE(x)                                                      \\\n    do {                                                                       \\\n        double _delta = std::chrono::duration<double, std::milli>(             \\\n                            std::chrono::high_resolution_clock::now() - start) \\\n                            .count();                                          \\\n        printf(\"%s: %f ms = %f fps\\n\", #x, _delta, 1e3f / _delta);             \\\n        start = std::chrono::high_resolution_clock::now();                     \\\n    } while (false)\n#define _SMPLX_PROFILE_STEPS(x, stp)                                  \\\n    do {                                                              \\\n        printf(\"%s: %f ms / step\\n\", #x,                              \\\n               std::chrono::duration<double, std::milli>(             \\\n                   std::chrono::high_resolution_clock::now() - start) \\\n                       .count() /                                     \\\n                   (stp));                                            \\\n        start = std::chrono::high_resolution_clock::now();            \\\n    } while (false)\n\n#include <Eigen/Geometry>\n\nnamespace smplx {\nnamespace util {\n\nconst char* gender_to_str(Gender gender);\nGender parse_gender(std::string str);  // Copy intended\n\n// Angle-axis to rotation matrix using custom implementation\ntemplate <class T, int Option = Eigen::ColMajor>\ninline Eigen::Matrix<T, 3, 3, Option> rodrigues(\n    const Eigen::Ref<const Eigen::Matrix<T, 3, 1>>& vec) {\n    const T theta = vec.norm();\n    const Eigen::Matrix<T, 3, 3, Option> eye =\n        Eigen::Matrix<T, 3, 3, Option>::Identity();\n\n    if (std::fabs(theta) < 1e-5f)\n        return eye;\n    else {\n        const T c = std::cos(theta);\n        const T s = std::sin(theta);\n        const Eigen::Matrix<T, 3, 1> r = vec / theta;\n        Eigen::Matrix<T, 3, 3, Option> skew;\n        skew << 0, -r.z(), r.y(), r.z(), 0, -r.x(), -r.y(), r.x(), 0;\n        return c * eye + (1 - c) * r * r.transpose() + s * skew;\n    }\n}\n\n// Angle-axis to rotation matrix through Eigen quaternion\n// (slightly slower than rodrigues, not useful)\ntemplate <class T, int Option = Eigen::ColMajor>\ninline Eigen::Matrix<T, 3, 3, Option> rodrigues_eigen(\n    const Eigen::Ref<const Eigen::Matrix<T, 3, 1>>& vec) {\n    return Eigen::template AngleAxis<T>(vec.norm(), vec / vec.norm())\n        .toRotationMatrix();\n}\n\n// Affine transformation matrix (hopefully) faster multiplication\n// bottom row omitted\ntemplate <class T, int Option = Eigen::ColMajor>\ninline void mul_affine(\n    const Eigen::Ref<const Eigen::Matrix<T, 3, 4, Option>>& a,\n    Eigen::Ref<Eigen::Matrix<T, 3, 4, Option>> b) {\n    b.template leftCols<3>() =\n        a.template leftCols<3>() * b.template leftCols<3>();\n    b.template rightCols<1>() =\n        a.template rightCols<1>() +\n        a.template leftCols<3>() * b.template rightCols<1>();\n}\n\n// Affine transformation matrix 'in-place' inverse\ntemplate <class T, int Option = Eigen::ColMajor>\ninline void inv_affine(Eigen::Ref<Eigen::Matrix<T, 3, 4, Option>> a) {\n    a.template leftCols<3>() = a.template leftCols<3>().inverse();\n    a.template rightCols<1>() =\n        -a.template leftCols<3>() * a.template rightCols<1>();\n}\n\n// Homogeneous transformation matrix in-place inverse\ntemplate <class T, int Option = Eigen::ColMajor>\ninline void inv_homogeneous(Eigen::Ref<Eigen::Matrix<T, 3, 4, Option>> a) {\n    a.template leftCols<3>().transposeInPlace();\n    a.template rightCols<1>() =\n        -a.template leftCols<3>() * a.template rightCols<1>();\n}\n\n// Path resolve helper: return a valid path to file in data/\nstd::string find_data_file(const std::string& data_path);\n\n// Create color from integer\nEigen::Vector3f auto_color(size_t color_index);\n\n// Create table of num_colors colors, shape (num_colors, 3) row-major\nPoints auto_color_table(size_t num_colors);\n\n// Set matrix to iid multivariate normal\ntemplate <class Mat>\nvoid set_randn(Mat& m, float mean = 0.0f, float variance = 1.0f) {\n    thread_local std::mt19937 rg{std::random_device{}()};\n    std::normal_distribution<float> dist(mean, variance);\n    for (size_t i = 0; i < m.rows(); ++i) {\n        for (size_t j = 0; j < m.cols(); ++j) {\n            m(i, j) = dist(rg);\n        }\n    }\n}\n\n}  // namespace util\n}  // namespace smplx\n\n#endif  // ifndef SMPLX_UTIL_63B0803D_E0C7_4529_A796_9F6ED269E89F\n", "meta": {"hexsha": "3f19abf87dd15d4a29716bf83f502ffb1f4d8a83", "size": 7847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smplx/util.hpp", "max_stars_repo_name": "liangjin2007/smplxpp", "max_stars_repo_head_hexsha": "9a0d1cea136ea924628a9a031fa673fc9531dd85", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2020-07-10T03:22:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T21:22:18.000Z", "max_issues_repo_path": "include/smplx/util.hpp", "max_issues_repo_name": "liangjin2007/smplxpp", "max_issues_repo_head_hexsha": "9a0d1cea136ea924628a9a031fa673fc9531dd85", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-07-13T05:59:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-09T03:53:01.000Z", "max_forks_repo_path": "include/smplx/util.hpp", "max_forks_repo_name": "liangjin2007/smplxpp", "max_forks_repo_head_hexsha": "9a0d1cea136ea924628a9a031fa673fc9531dd85", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T03:22:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T19:09:41.000Z", "avg_line_length": 47.2710843373, "max_line_length": 80, "alphanum_fraction": 0.4055052886, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734719655744, "lm_q2_score": 0.02194825507434171, "lm_q1q2_score": 0.00181506247024144}}
{"text": "#include <boost/algorithm/string/join.hpp>\n#include <mbgl/style/expression/collator.hpp>\n#include <mbgl/style/expression/compound_expression.hpp>\n#include <mbgl/style/expression/check_subtype.hpp>\n#include <mbgl/style/expression/util.hpp>\n#include <mbgl/style/conversion_impl.hpp>\n#include <mbgl/tile/geometry_tile_data.hpp>\n#include <mbgl/math/log2.hpp>\n#include <mbgl/util/i18n.hpp>\n#include <mbgl/util/ignore.hpp>\n#include <mbgl/util/string.hpp>\n#include <mbgl/util/platform.hpp>\n#include <mbgl/util/variant.hpp>\n\n#include <mapbox/eternal.hpp>\n\n#include <cmath>\n#include <limits>\n\nnamespace mbgl {\nnamespace style {\nnamespace expression {\n\n/*\n    Represents the parameter list for an expression that takes an arbitrary\n    number of arguments (of a specific type).\n*/\nstruct VarargsType { type::Type type; };\n\nbool operator==(const VarargsType& lhs, const VarargsType& rhs) {\n    return lhs.type == rhs.type;\n}\n\ntemplate <typename T>\nstruct Varargs : std::vector<T> {\n    template <class... Args>\n    explicit Varargs(Args&&... args) : std::vector<T>(std::forward<Args>(args)...) {}\n};\n\nnamespace detail {\n// Base class for the Signature<Fn> structs that are used to determine\n// each CompoundExpression definition's type::Type data from the type of its\n// \"evaluate\" function.\nstruct SignatureBase {\n    using Args = std::vector<std::unique_ptr<Expression>>;\n\n    SignatureBase(type::Type result_, variant<std::vector<type::Type>, VarargsType> params_, std::string name_) :\n        result(std::move(result_)),\n        params(std::move(params_)),\n        name(std::move(name_))\n    {}\n    virtual ~SignatureBase() = default;\n\n    virtual EvaluationResult apply(const EvaluationContext&, const Args&) const = 0;\n\n    type::Type result;\n    variant<std::vector<type::Type>, VarargsType> params;\n    std::string name;\n};\n\n/*\n    The Signature<Fn> structs are wrappers around an \"evaluate()\" function whose\n    purpose is to extract the necessary Type data from the evaluate function's\n    type.  There are three key (partial) specializations:\n \n    Signature<R (Params...)>:\n    Wraps a simple evaluate function (const T0&, const T1&, ...) -> Result<U>\n \n    Signature<R (const Varargs<T>&)>:\n    Wraps an evaluate function that takes an arbitrary number of arguments (via\n    a Varargs<T>, which is just an alias for std::vector).\n \n    Signature<R (const EvaluationContext&, Params...)>:\n    Wraps an evaluate function that needs to access the expression evaluation\n    parameters in addition to its subexpressions, i.e.,\n    (const EvaluationParams&, const T0&, const T1&, ...) -> Result<U>.  Needed\n    for expressions like [\"zoom\"], [\"get\", key], etc.\n \n    In each of the above evaluate signatures, T0, T1, etc. are the types of\n    the successfully evaluated subexpressions.\n*/\ntemplate <class, class Enable = void>\nstruct Signature;\n\n// Simple evaluate function (const T0&, const T1&, ...) -> Result<U>\ntemplate <class R, class... Params>\nstruct Signature<R (Params...)> : SignatureBase {\n    Signature(R (*evaluate_)(Params...), const std::string& name_)\n        : SignatureBase(valueTypeToExpressionType<std::decay_t<typename R::Value>>(),\n                        std::vector<type::Type>{valueTypeToExpressionType<std::decay_t<Params>>()...},\n                        name_),\n          evaluate(evaluate_) {}\n\n    EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override {\n        return applyImpl(evaluationParameters, args, std::index_sequence_for<Params...>{});\n    }\n\n    R (*evaluate)(Params...);\n\nprivate:\n    template <std::size_t ...I>\n    EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence<I...>) const {\n        std::array<Value, sizeof...(Params)> evaluated;\n        for (std::size_t i = 0; i < sizeof...(Params); ++i) {\n            const EvaluationResult evaluatedArg = args.at(i)->evaluate(evaluationParameters);\n            if (!evaluatedArg) return evaluatedArg.error();\n            evaluated[i] = *evaluatedArg;\n        }\n        const R value = evaluate(*fromExpressionValue<std::decay_t<Params>>(evaluated[I])...);\n        if (!value) return value.error();\n        return *value;\n    }\n};\n\n// Varargs evaluate function (const Varargs<T>&) -> Result<U>\ntemplate <class R, typename T>\nstruct Signature<R (const Varargs<T>&)> : SignatureBase {\n    Signature(R (*evaluate_)(const Varargs<T>&), const std::string& name_)\n        : SignatureBase(valueTypeToExpressionType<std::decay_t<typename R::Value>>(),\n                        VarargsType{valueTypeToExpressionType<T>()},\n                        name_),\n          evaluate(evaluate_) {}\n\n    EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override {\n        Varargs<T> evaluated;\n        evaluated.reserve(args.size());\n        for (const auto& arg : args) {\n            const EvaluationResult evaluatedArg = arg->evaluate(evaluationParameters);\n            if(!evaluatedArg) return evaluatedArg.error();\n            evaluated.push_back(*fromExpressionValue<std::decay_t<T>>(*evaluatedArg));\n        }\n        const R value = evaluate(evaluated);\n        if (!value) return value.error();\n        return *value;\n    }\n\n    R (*evaluate)(const Varargs<T>&);\n};\n\n// Evaluate function needing parameter access,\n// (const EvaluationParams&, const T0&, const T1&, ...) -> Result<U>\ntemplate <class R, class... Params>\nstruct Signature<R (const EvaluationContext&, Params...)> : SignatureBase {\n    Signature(R (*evaluate_)(const EvaluationContext&, Params...), const std::string& name_)\n        : SignatureBase(valueTypeToExpressionType<std::decay_t<typename R::Value>>(),\n                        std::vector<type::Type>{valueTypeToExpressionType<std::decay_t<Params>>()...},\n                        name_),\n          evaluate(evaluate_) {}\n\n    EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override {\n        return applyImpl(evaluationParameters, args, std::index_sequence_for<Params...>{});\n    }\n\nprivate:\n    template <std::size_t ...I>\n    EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence<I...>) const {\n        std::array<Value, sizeof...(Params)> evaluated;\n        for (std::size_t i = 0; i < sizeof...(Params); ++i) {\n            const EvaluationResult evaluatedArg = args.at(i)->evaluate(evaluationParameters);\n            if (!evaluatedArg) return evaluatedArg.error();\n            evaluated[i] = *evaluatedArg;\n        }\n        const R value = evaluate(evaluationParameters, *fromExpressionValue<std::decay_t<Params>>(evaluated[I])...);\n        if (!value) return value.error();\n        return *value;\n    }\n\n    R (*evaluate)(const EvaluationContext&, Params...);\n};\n    \n// Evaluate function needing EvaluationContext and Varargs\n// (const EvaluationContext&, const Varargs<T>&) -> Result<U>\ntemplate <class R, typename T>\nstruct Signature<R (const EvaluationContext&, const Varargs<T>&)> : SignatureBase {\n    Signature(R (*evaluate_)(const EvaluationContext&, const Varargs<T>&), const std::string& name_)\n        : SignatureBase(valueTypeToExpressionType<std::decay_t<typename R::Value>>(),\n                        VarargsType{valueTypeToExpressionType<T>()},\n                        name_),\n          evaluate(evaluate_) {}\n\n    EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override {\n        Varargs<T> evaluated;\n        evaluated.reserve(args.size());\n        for (const auto& arg : args) {\n            const EvaluationResult evaluatedArg = arg->evaluate(evaluationParameters);\n            if(!evaluatedArg) return evaluatedArg.error();\n            evaluated.push_back(*fromExpressionValue<std::decay_t<T>>(*evaluatedArg));\n        }\n        const R value = evaluate(evaluationParameters, evaluated);\n        if (!value) return value.error();\n        return *value;\n    }\n\n    R (*evaluate)(const EvaluationContext&, const Varargs<T>&);\n};\n\n// Machinery to pull out function type from lambdas.\ntemplate <class, class = void>\nstruct SignatureType;\n\ntemplate <class T, class R, class... Params>\nstruct SignatureType<R (T::*)(Params...) const>\n{ using Type = R (Params...);  };\n\ntemplate <class Lambda>\nstruct SignatureType<Lambda, std::enable_if_t<std::is_class<Lambda>::value>>\n{ using Type = typename SignatureType<decltype(&Lambda::operator())>::Type; };\n\ntemplate <typename Fn>\nstatic std::unique_ptr<detail::SignatureBase> makeSignature(std::string name, Fn evaluateFunction) {\n    return std::make_unique<Signature<typename SignatureType<Fn>::Type>>(evaluateFunction, std::move(name));\n}\n\n} // namespace detail\n\nValue featureIdAsExpressionValue(const EvaluationContext& params) {\n    assert(params.feature);\n    auto id = params.feature->getID();\n    if (id.is<NullValue>()) return Null;\n    return id.match([](const auto& idid) {\n        return toExpressionValue(mbgl::Value(idid));\n    });\n};\n\noptional<Value> featurePropertyAsExpressionValue(const EvaluationContext& params, const std::string& key) {\n    assert(params.feature);\n    auto property = params.feature->getValue(key);\n    return property ? toExpressionValue(*property) : optional<Value>();\n};\n\noptional<std::string> featureTypeAsString(FeatureType type) {\n    switch(type) {\n    case FeatureType::Point:\n        return optional<std::string>(\"Point\");\n    case FeatureType::LineString:\n        return optional<std::string>(\"LineString\");\n    case FeatureType::Polygon:\n        return optional<std::string>(\"Polygon\");\n    case FeatureType::Unknown:\n        return optional<std::string>(\"Unknown\");\n    default:\n        return {};\n    }\n};\n\noptional<double> featurePropertyAsDouble(const EvaluationContext& params, const std::string& key) {\n    assert(params.feature);\n    auto property = params.feature->getValue(key);\n    if (!property) return {};\n    return property->match([](double value) { return value; },\n                           [](uint64_t value) -> optional<double> { return {static_cast<double>(value)}; },\n                           [](int64_t value) -> optional<double> { return {static_cast<double>(value)}; },\n                           [](const auto&) -> optional<double> { return {}; });\n};\n\noptional<std::string> featurePropertyAsString(const EvaluationContext& params, const std::string& key) {\n    assert(params.feature);\n    auto property = params.feature->getValue(key);\n    if (!property) return {};\n    return property->match([](std::string value) { return value; },\n                           [](const auto&) { return optional<std::string>(); });\n};\n\noptional<double> featureIdAsDouble(const EvaluationContext& params) {\n    assert(params.feature);\n    auto id = params.feature->getID();\n    return id.match([](double value) { return value; },\n                    [](uint64_t value) -> optional<double> { return {static_cast<double>(value)}; },\n                    [](int64_t value) -> optional<double> { return {static_cast<double>(value)}; },\n                    [](const auto&) -> optional<double> { return {}; });\n};\n\noptional<std::string> featureIdAsString(const EvaluationContext& params) {\n    assert(params.feature);\n    auto id = params.feature->getID();\n    return id.match([](std::string value) { return value; }, [](const auto&) { return optional<std::string>(); });\n};\n\nconst auto& eCompoundExpression() {\n    static auto signature = detail::makeSignature(\"e\", []() -> Result<double> { return 2.718281828459045; });\n    return signature;\n}\n\nconst auto& piCompoundExpression() {\n    static auto signature = detail::makeSignature(\"pi\", []() -> Result<double> { return 3.141592653589793; });\n    return signature;\n}\n\nconst auto& ln2CompoundExpression() {\n    static auto signature = detail::makeSignature(\"ln2\", []() -> Result<double> { return 0.6931471805599453; });\n    return signature;\n}\n\nconst auto& typeofCompoundExpression() {\n    static auto signature = detail::makeSignature(\"typeof\", [](const Value& v) -> Result<std::string> { return toString(typeOf(v)); });\n    return signature;\n}\n\nconst auto& toRgbaCompoundExpression() {\n    static auto signature = detail::makeSignature(\"to-rgba\", [](const Color& color) -> Result<std::array<double, 4>> {\n        return color.toArray();\n    });\n    return signature;\n}\n\nconst auto& rgbaCompoundExpression() {\n    static auto signature = detail::makeSignature(\"rgba\", [](double r, double g, double b, double a) { return rgba(r, g, b, a); });\n    return signature;\n}\n\nconst auto& rgbCompoundExpression() {\n    static auto signature = detail::makeSignature(\"rgb\", [](double r, double g, double b) { return rgba(r, g, b, 1.0f); });\n    return signature;\n}\n\nconst auto& zoomCompoundExpression() {\n    static auto signature = detail::makeSignature(\"zoom\", [](const EvaluationContext& params) -> Result<double> {\n        if (!params.zoom) {\n            return EvaluationError {\n                \"The 'zoom' expression is unavailable in the current evaluation context.\"\n            };\n        }\n        return *(params.zoom);\n    });\n    return signature;\n}\n\nconst auto& heatmapDensityCompoundExpression() {\n    static auto signature = detail::makeSignature(\"heatmap-density\", [](const EvaluationContext& params) -> Result<double> {\n        if (!params.colorRampParameter) {\n            return EvaluationError {\n                \"The 'heatmap-density' expression is unavailable in the current evaluation context.\"\n            };\n        }\n        return *(params.colorRampParameter);\n    });\n    return signature;\n}\n\nconst auto& lineProgressCompoundExpression() {\n    static auto signature = detail::makeSignature(\"line-progress\", [](const EvaluationContext& params) -> Result<double> {\n        if (!params.colorRampParameter) {\n            return EvaluationError {\n                \"The 'line-progress' expression is unavailable in the current evaluation context.\"\n            };\n        }\n        return *(params.colorRampParameter);\n    });\n    return signature;\n}\n\nconst auto& accumulatedCompoundExpression() {\n    const static auto signature = detail::makeSignature(\"accumulated\", [](const EvaluationContext& params) -> Result<Value> {\n        if (!params.accumulated) {\n            return EvaluationError {\n                \"The 'accumulated' expression is unavailable in the current evaluation context.\"\n            };\n        }\n        return Value(toExpressionValue(*params.accumulated));\n    });\n    return signature;\n}\n    \nconst auto& hasContextCompoundExpression() {\n    static auto signature = detail::makeSignature(\"has\", [](const EvaluationContext& params, const std::string& key) -> Result<bool> {\n        if (!params.feature) {\n            return EvaluationError {\n                \"Feature data is unavailable in the current evaluation context.\"\n            };\n        }\n\n        return static_cast<bool>(params.feature->getValue(key));\n    });\n    return signature;\n}\n\nconst auto& hasObjectCompoundExpression() {\n    static auto signature = detail::makeSignature(\"has\", [](const std::string& key, const std::unordered_map<std::string, Value>& object) -> Result<bool> {\n        return object.find(key) != object.end();\n    });\n    return signature;\n}\n\nconst auto& getContextCompoundExpression() {\n    static auto signature = detail::makeSignature(\"get\", [](const EvaluationContext& params, const std::string& key) -> Result<Value> {\n        if (!params.feature) {\n            return EvaluationError {\n                \"Feature data is unavailable in the current evaluation context.\"\n            };\n        }\n\n        auto propertyValue = params.feature->getValue(key);\n        if (!propertyValue) {\n            return Null;\n        }\n        return Value(toExpressionValue(*propertyValue));\n    });\n    return signature;\n}\n\nconst auto& getObjectCompoundExpression() {\n    static auto signature = detail::makeSignature(\"get\", [](const std::string& key, const std::unordered_map<std::string, Value>& object) -> Result<Value> {\n        if (object.find(key) == object.end()) {\n            return Null;\n        }\n        return object.at(key);\n    });\n    return signature;\n}\n\nconst auto& propertiesCompoundExpression() {\n    static auto signature = detail::makeSignature(\"properties\", [](const EvaluationContext& params) -> Result<std::unordered_map<std::string, Value>> {\n        if (!params.feature) {\n            return EvaluationError {\n                \"Feature data is unavailable in the current evaluation context.\"\n            };\n        }\n        std::unordered_map<std::string, Value> result;\n        const PropertyMap& properties = params.feature->getProperties();\n        result.reserve(properties.size());\n        for (const auto& entry : properties) {\n            result[entry.first] = toExpressionValue(entry.second);\n        }\n        return result;\n    });\n    return signature;\n}\n\nconst auto& geometryTypeCompoundExpression() {\n    static auto signature = detail::makeSignature(\"geometry-type\", [](const EvaluationContext& params) -> Result<std::string> {\n        if (!params.feature) {\n            return EvaluationError {\n                \"Feature data is unavailable in the current evaluation context.\"\n            };\n        }\n\n        auto type = params.feature->getType();\n        if (type == FeatureType::Point) {\n            return \"Point\";\n        } else if (type == FeatureType::LineString) {\n            return \"LineString\";\n        } else if (type == FeatureType::Polygon) {\n            return \"Polygon\";\n        } else {\n            return \"Unknown\";\n        }\n    });\n    return signature;\n}\n\nconst auto& idCompoundExpression() {\n    static auto signature = detail::makeSignature(\"id\", [](const EvaluationContext& params) -> Result<Value> {\n        if (!params.feature) {\n            return EvaluationError {\n                \"Feature data is unavailable in the current evaluation context.\"\n            };\n        }\n\n        auto id = params.feature->getID();\n        return id.match(\n            [](const auto& idValue) {\n                return toExpressionValue(mbgl::Value(idValue));\n            }\n        );\n    });\n    return signature;\n}\n\nconst auto& plusCompoundExpression() {\n    static auto signature = detail::makeSignature(\"+\", [](const Varargs<double>& args) -> Result<double> {\n        double sum = 0.0f;\n        for (auto arg : args) {\n            sum += arg;\n        }\n        return sum;\n    });\n    return signature;\n}\n\nconst auto& minusCompoundExpression() {\n    static auto signature = detail::makeSignature(\"-\", [](double a, double b) -> Result<double> { return a - b; });\n    return signature;\n}\n\nconst auto& negateCompoundExpression() {\n    static auto signature = detail::makeSignature(\"-\", [](double a) -> Result<double> { return -a; });\n    return signature;\n}\n\nconst auto& multiplyCompoundExpression() {\n    static auto signature = detail::makeSignature(\"*\", [](const Varargs<double>& args) -> Result<double> {\n        double prod = 1.0f;\n        for (auto arg : args) {\n            prod *= arg;\n        }\n        return prod;\n    });\n    return signature;\n}\n\nconst auto& divideCompoundExpression() {\n    static auto signature = detail::makeSignature(\"/\", [](double a, double b) -> Result<double> {\n        if (b == 0) {\n            if (a == 0) return std::numeric_limits<double>::quiet_NaN();\n            double inf = std::numeric_limits<double>::infinity();\n            if (a > 0) return inf;\n            if (a < 0) return -inf;\n        }\n        return a / b;\n    });\n    return signature;\n}\n\nconst auto& modCompoundExpression() {\n    static auto signature = detail::makeSignature(\"%\", [](double a, double b) -> Result<double> { return fmod(a, b); });\n    return signature;\n}\n\nconst auto& powCompoundExpression() {\n    static auto signature = detail::makeSignature(\"^\", [](double a, double b) -> Result<double> { return pow(a, b); });\n    return signature;\n}\n\nconst auto& sqrtCompoundExpression() {\n    static auto signature = detail::makeSignature(\"sqrt\", [](double x) -> Result<double> { return sqrt(x); });\n    return signature;\n}\n\nconst auto& log10CompoundExpression() {\n    static auto signature = detail::makeSignature(\"log10\", [](double x) -> Result<double> { return log10(x); });\n    return signature;\n}\n\nconst auto& lnCompoundExpression() {\n    static auto signature = detail::makeSignature(\"ln\", [](double x) -> Result<double> { return log(x); });\n    return signature;\n}\n\nconst auto& log2CompoundExpression() {\n    static auto signature = detail::makeSignature(\"log2\", [](double x) -> Result<double> { return util::log2(x); });\n    return signature;\n}\n\nconst auto& sinCompoundExpression() {\n    static auto signature = detail::makeSignature(\"sin\", [](double x) -> Result<double> { return sin(x); });\n    return signature;\n}\n\nconst auto& cosCompoundExpression() {\n    static auto signature = detail::makeSignature(\"cos\", [](double x) -> Result<double> { return cos(x); });\n    return signature;\n}\n\nconst auto& tanCompoundExpression() {\n    static auto signature = detail::makeSignature(\"tan\", [](double x) -> Result<double> { return tan(x); });\n    return signature;\n}\n\nconst auto& asinCompoundExpression() {\n    static auto signature = detail::makeSignature(\"asin\", [](double x) -> Result<double> { return asin(x); });\n    return signature;\n}\n\nconst auto& acosCompoundExpression() {\n    static auto signature = detail::makeSignature(\"acos\", [](double x) -> Result<double> { return acos(x); });\n    return signature;\n}\n\nconst auto& atanCompoundExpression() {\n    static auto signature = detail::makeSignature(\"atan\", [](double x) -> Result<double> { return atan(x); });\n    return signature;\n}\n\nconst auto& minCompoundExpression() {\n    static auto signature = detail::makeSignature(\"min\", [](const Varargs<double>& args) -> Result<double> {\n        double result = std::numeric_limits<double>::infinity();\n        for (double arg : args) {\n            result = fmin(arg, result);\n        }\n        return result;\n    });\n    return signature;\n}\n\nconst auto& maxCompoundExpression() {\n    static auto signature = detail::makeSignature(\"max\", [](const Varargs<double>& args) -> Result<double> {\n        double result = -std::numeric_limits<double>::infinity();\n        for (double arg : args) {\n            result = fmax(arg, result);\n        }\n        return result;\n    });\n    return signature;\n}\n\nconst auto& roundCompoundExpression() {\n    static auto signature = detail::makeSignature(\"round\", [](double x) -> Result<double> { return ::round(x); });\n    return signature;\n}\n\nconst auto& floorCompoundExpression() {\n    static auto signature = detail::makeSignature(\"floor\", [](double x) -> Result<double> { return std::floor(x); });\n    return signature;\n}\n\nconst auto& ceilCompoundExpression() {\n    static auto signature = detail::makeSignature(\"ceil\", [](double x) -> Result<double> { return std::ceil(x); });\n    return signature;\n}\n\nconst auto& absCompoundExpression() {\n    static auto signature = detail::makeSignature(\"abs\", [](double x) -> Result<double> { return std::abs(x); });\n    return signature;\n}\n\nconst auto& notCompoundExpression() {\n    static auto signature = detail::makeSignature(\"!\", [](bool e) -> Result<bool> { return !e; });\n    return signature;\n}\n\nconst auto& isSupportedScriptCompoundExpression() {\n    static auto signature = detail::makeSignature(\"is-supported-script\", [](const std::string& x) -> Result<bool> {\n        return util::i18n::isStringInSupportedScript(x);\n    });\n    return signature;\n}\n\nconst auto& upcaseCompoundExpression() {\n    static auto signature = detail::makeSignature(\"upcase\", [](const std::string& input) -> Result<std::string> {\n        return platform::uppercase(input);\n    });\n    return signature;\n}\n\nconst auto& downcaseCompoundExpression() {\n    static auto signature = detail::makeSignature(\"downcase\", [](const std::string& input) -> Result<std::string> {\n        return platform::lowercase(input);\n    });\n    return signature;\n}\n\nconst auto& concatCompoundExpression() {\n    static auto signature = detail::makeSignature(\"concat\", [](const Varargs<Value>& args) -> Result<std::string> {\n        std::string s;\n        for (const Value& arg : args) {\n            s += toString(arg);\n        }\n        return s;\n    });\n    return signature;\n}\n\nconst auto& resolvedLocaleCompoundExpression() {\n    static auto signature = detail::makeSignature(\"resolved-locale\", [](const Collator& collator) -> Result<std::string> {\n        return collator.resolvedLocale();\n    });\n    return signature;\n}\n\nconst auto& errorCompoundExpression() {\n    static auto signature = detail::makeSignature(\"error\", [](const std::string& input) -> Result<type::ErrorType> {\n        return EvaluationError { input };\n    });\n    return signature;\n}\n\nconst auto& featureStateCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"feature-state\", [](const EvaluationContext& params, const std::string& key) -> Result<Value> {\n            mbgl::Value state;\n            if (params.featureState != nullptr) {\n                auto it = params.featureState->find(key);\n                if (it != params.featureState->end()) {\n                    state = mbgl::Value(it->second);\n                }\n            }\n            return toExpressionValue(state);\n        });\n    return signature;\n}\n\n// Legacy Filters\nconst auto& filterEqualsCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-==\", [](const EvaluationContext& params, const std::string& key, const Value &lhs) -> Result<bool> {\n        const auto rhs = featurePropertyAsExpressionValue(params, key);\n        return rhs ? lhs == *rhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterIdEqualsCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-id-==\", [](const EvaluationContext& params, const Value &lhs) -> Result<bool> {\n        return lhs == featureIdAsExpressionValue(params);\n    });\n    return signature;\n}\n\nconst auto& filterTypeEqualsCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-type-==\", [](const EvaluationContext& params, const std::string &lhs) -> Result<bool> {\n        if (!params.feature) return false;\n        return featureTypeAsString(params.feature->getType()) == lhs;\n    });\n    return signature;\n}\n\nconst auto& filterLessThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-<\", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result<bool> {\n        auto rhs = featurePropertyAsDouble(params, key);\n        return rhs ? rhs < lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterLessThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter-<\",\n        [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result<bool> {\n            auto rhs = featurePropertyAsString(params, key);\n            return rhs ? rhs < lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterIdLessThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-id-<\", [](const EvaluationContext& params, double lhs) -> Result<bool> {\n        auto rhs = featureIdAsDouble(params);\n        return rhs ? rhs < lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterIdLessThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter-id-<\", [](const EvaluationContext& params, const std::string& lhs) -> Result<bool> {\n            auto rhs = featureIdAsString(params);\n            return rhs ? rhs < lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterMoreThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter->\", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result<bool> {\n        auto rhs = featurePropertyAsDouble(params, key);\n        return rhs ? rhs > lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterMoreThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter->\",\n        [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result<bool> {\n            auto rhs = featurePropertyAsString(params, key);\n            return rhs ? rhs > lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterIdMoreThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-id->\", [](const EvaluationContext& params, double lhs) -> Result<bool> {\n        auto rhs = featureIdAsDouble(params);\n        return rhs ? rhs > lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterIdMoreThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter-id->\", [](const EvaluationContext& params, const std::string& lhs) -> Result<bool> {\n            auto rhs = featureIdAsString(params);\n            return rhs ? rhs > lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterLessOrEqualThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-<=\", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result<bool> {\n        auto rhs = featurePropertyAsDouble(params, key);\n        return rhs ? rhs <= lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterLessOrEqualThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter-<=\",\n        [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result<bool> {\n            auto rhs = featurePropertyAsString(params, key);\n            return rhs ? rhs <= lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterIdLessOrEqualThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-id-<=\", [](const EvaluationContext& params, double lhs) -> Result<bool> {\n        auto rhs = featureIdAsDouble(params);\n        return rhs ? rhs <= lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterIdLessOrEqualThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter-id-<=\", [](const EvaluationContext& params, const std::string& lhs) -> Result<bool> {\n            auto rhs = featureIdAsString(params);\n            return rhs ? rhs <= lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterGreaterOrEqualThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter->=\", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result<bool> {\n        auto rhs = featurePropertyAsDouble(params, key);\n        return rhs ? rhs >= lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterGreaterOrEqualThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter->=\",\n        [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result<bool> {\n            auto rhs = featurePropertyAsString(params, key);\n            return rhs ? rhs >= lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterIdGreaterOrEqualThanNumberCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-id->=\", [](const EvaluationContext& params, double lhs) -> Result<bool> {\n        auto rhs = featureIdAsDouble(params);\n        return rhs ? rhs >= lhs : false;\n    });\n    return signature;\n}\n\nconst auto& filterIdGreaterOrEqualThanStringCompoundExpression() {\n    static auto signature = detail::makeSignature(\n        \"filter-id->=\", [](const EvaluationContext& params, const std::string& lhs) -> Result<bool> {\n            auto rhs = featureIdAsString(params);\n            return rhs ? rhs >= lhs : false;\n        });\n    return signature;\n}\n\nconst auto& filterHasCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-has\", [](const EvaluationContext& params, const std::string& key) -> Result<bool> {\n        assert(params.feature);\n        return bool(params.feature->getValue(key));\n    });\n    return signature;\n}\n\nconst auto& filterHasIdCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-has-id\", [](const EvaluationContext& params) -> Result<bool> {\n        assert(params.feature);\n        return !params.feature->getID().is<NullValue>();\n    });\n    return signature;\n}\n\nconst auto& filterTypeInCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-type-in\", [](const EvaluationContext& params, const Varargs<std::string>& types) -> Result<bool> {\n        assert(params.feature);\n        optional<std::string> type = featureTypeAsString(params.feature->getType());\n        return std::find(types.begin(), types.end(), type) != types.end();\n    });\n    return signature;\n}\n\nconst auto& filterIdInCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-id-in\", [](const EvaluationContext& params, const Varargs<Value>& ids) -> Result<bool> {\n        auto id = featureIdAsExpressionValue(params);\n        return std::find(ids.begin(), ids.end(), id) != ids.end();\n    });\n    return signature;\n}\n\n\nconst auto& filterInCompoundExpression() {\n    static auto signature = detail::makeSignature(\"filter-in\", [](const EvaluationContext& params, const Varargs<Value>& varargs) -> Result<bool> {\n        if (varargs.size() < 2) return false;\n        assert(varargs[0].is<std::string>());\n        auto value = featurePropertyAsExpressionValue(params, varargs[0].get<std::string>());\n        return value ? std::find(varargs.begin() + 1, varargs.end(), *value) != varargs.end() : false;\n    });\n    return signature;\n}\n\nusing ParseCompoundFunction = const std::unique_ptr<detail::SignatureBase>& (*)();\nMAPBOX_ETERNAL_CONSTEXPR const auto compoundExpressionRegistry =\n    mapbox::eternal::hash_map<mapbox::eternal::string, ParseCompoundFunction>({\n        {\"e\", eCompoundExpression},\n        {\"pi\", piCompoundExpression},\n        {\"ln2\", ln2CompoundExpression},\n        {\"typeof\", typeofCompoundExpression},\n        {\"to-rgba\", toRgbaCompoundExpression},\n        {\"rgba\", rgbaCompoundExpression},\n        {\"rgb\", rgbCompoundExpression},\n        {\"zoom\", zoomCompoundExpression},\n        {\"heatmap-density\", heatmapDensityCompoundExpression},\n        {\"line-progress\", lineProgressCompoundExpression},\n        {\"accumulated\", accumulatedCompoundExpression},\n        {\"has\", hasContextCompoundExpression},\n        {\"has\", hasObjectCompoundExpression},\n        {\"get\", getContextCompoundExpression},\n        {\"get\", getObjectCompoundExpression},\n        {\"properties\", propertiesCompoundExpression},\n        {\"geometry-type\", geometryTypeCompoundExpression},\n        {\"id\", idCompoundExpression},\n        {\"+\", plusCompoundExpression},\n        {\"-\", minusCompoundExpression},\n        {\"-\", negateCompoundExpression},\n        {\"*\", multiplyCompoundExpression},\n        {\"/\", divideCompoundExpression},\n        {\"%\", modCompoundExpression},\n        {\"^\", powCompoundExpression},\n        {\"sqrt\", sqrtCompoundExpression},\n        {\"log10\", log10CompoundExpression},\n        {\"ln\", lnCompoundExpression},\n        {\"log2\", log2CompoundExpression},\n        {\"sin\", sinCompoundExpression},\n        {\"cos\", cosCompoundExpression},\n        {\"tan\", tanCompoundExpression},\n        {\"asin\", asinCompoundExpression},\n        {\"acos\", acosCompoundExpression},\n        {\"atan\", atanCompoundExpression},\n        {\"min\", minCompoundExpression},\n        {\"max\", maxCompoundExpression},\n        {\"round\", roundCompoundExpression},\n        {\"floor\", floorCompoundExpression},\n        {\"ceil\", ceilCompoundExpression},\n        {\"abs\", absCompoundExpression},\n        {\"!\", notCompoundExpression},\n        {\"is-supported-script\", isSupportedScriptCompoundExpression},\n        {\"upcase\", upcaseCompoundExpression},\n        {\"downcase\", downcaseCompoundExpression},\n        {\"concat\", concatCompoundExpression},\n        {\"resolved-locale\", resolvedLocaleCompoundExpression},\n        {\"error\", errorCompoundExpression},\n        {\"feature-state\", featureStateCompoundExpression},\n        // Legacy Filters\n        {\"filter-==\", filterEqualsCompoundExpression},\n        {\"filter-id-==\", filterIdEqualsCompoundExpression},\n        {\"filter-type-==\", filterTypeEqualsCompoundExpression},\n        {\"filter-<\", filterLessThanNumberCompoundExpression},\n        {\"filter-<\", filterLessThanStringCompoundExpression},\n        {\"filter-id-<\", filterIdLessThanNumberCompoundExpression},\n        {\"filter-id-<\", filterIdLessThanStringCompoundExpression},\n        {\"filter->\", filterMoreThanNumberCompoundExpression},\n        {\"filter->\", filterMoreThanStringCompoundExpression},\n        {\"filter-id->\", filterIdMoreThanNumberCompoundExpression},\n        {\"filter-id->\", filterIdMoreThanStringCompoundExpression},\n        {\"filter-<=\", filterLessOrEqualThanNumberCompoundExpression},\n        {\"filter-<=\", filterLessOrEqualThanStringCompoundExpression},\n        {\"filter-id-<=\", filterIdLessOrEqualThanNumberCompoundExpression},\n        {\"filter-id-<=\", filterIdLessOrEqualThanStringCompoundExpression},\n        {\"filter->=\", filterGreaterOrEqualThanNumberCompoundExpression},\n        {\"filter->=\", filterGreaterOrEqualThanStringCompoundExpression},\n        {\"filter-id->=\", filterIdGreaterOrEqualThanNumberCompoundExpression},\n        {\"filter-id->=\", filterIdGreaterOrEqualThanStringCompoundExpression},\n        {\"filter-has\", filterHasCompoundExpression},\n        {\"filter-has-id\", filterHasIdCompoundExpression},\n        {\"filter-type-in\", filterTypeInCompoundExpression},\n        {\"filter-id-in\", filterIdInCompoundExpression},\n        {\"filter-in\", filterInCompoundExpression},\n    });\n\nusing namespace mbgl::style::conversion;\n\nusing DefinitionIterator = decltype(compoundExpressionRegistry)::const_iterator;\nusing Definitions = std::pair<DefinitionIterator, DefinitionIterator>;\n\nstd::string expectedTypesError(const Definitions& definitions,\n                               const std::vector<std::unique_ptr<Expression>>& args) {\n    std::vector<std::string> availableOverloads; // Only used if there are no overloads with matching number of args\n    std::vector<std::string> overloads;\n    for (auto it = definitions.first; it != definitions.second; ++it) {\n        const auto& signature = it->second();\n        signature->params.match(\n        [&](const VarargsType& varargs) {\n            std::string overload = \"(\" + toString(varargs.type) + \")\";\n            overloads.push_back(overload);\n        },\n        [&](const std::vector<type::Type>& params) {\n            std::string overload = \"(\";\n            bool first = true;\n            for (const type::Type& param : params) {\n                if (!first) overload += \", \";\n                overload += toString(param);\n                first = false;\n            }\n            overload += \")\";\n            if (params.size() == args.size()) {\n                overloads.push_back(overload);\n            } else {\n                availableOverloads.push_back(overload);\n            }\n        }\n        );\n    }\n    std::string signatures = overloads.empty() ?\n        boost::algorithm::join(availableOverloads, \" | \") :\n        boost::algorithm::join(overloads, \" | \");\n    \n    std::string actualTypes;\n    for (const auto& arg : args) {\n        if (!actualTypes.empty()) {\n            actualTypes += \", \";\n        }\n        actualTypes += toString(arg->getType());\n    }\n    \n    return \"Expected arguments of type \" + signatures + \", but found (\" + actualTypes + \") instead.\";\n}\n\nstatic ParseResult createCompoundExpression(const Definitions& definitions,\n                                            std::vector<std::unique_ptr<Expression>> args,\n                                            ParsingContext& ctx)\n{\n    ParsingContext signatureContext(ctx.getKey());\n\n    for (auto it = definitions.first; it != definitions.second; ++it) {\n        const auto& signature = it->second();\n        signatureContext.clearErrors();\n\n        if (signature->params.is<std::vector<type::Type>>()) {\n            const std::vector<type::Type>& params = signature->params.get<std::vector<type::Type>>();\n            if (params.size() != args.size()) {\n                signatureContext.error(\n                    \"Expected \" + util::toString(params.size()) +\n                    \" arguments, but found \" + util::toString(args.size()) + \" instead.\"\n                );\n                continue;\n            }\n\n            for (std::size_t i = 0; i < args.size(); i++) {\n                const std::unique_ptr<Expression>& arg = args[i];\n                optional<std::string> err = type::checkSubtype(params.at(i), arg->getType());\n                if (err) {\n                    signatureContext.error(*err, i + 1);\n                }\n            }\n        } else if (signature->params.is<VarargsType>()) {\n            const type::Type& paramType = signature->params.get<VarargsType>().type;\n            for (std::size_t i = 0; i < args.size(); i++) {\n                const std::unique_ptr<Expression>& arg = args[i];\n                optional<std::string> err = type::checkSubtype(paramType, arg->getType());\n                if (err) {\n                    signatureContext.error(*err, i + 1);\n                }\n            }\n        }\n\n        if (signatureContext.getErrors().empty()) {\n            return ParseResult(std::make_unique<CompoundExpression>(*signature, std::move(args)));\n        }\n    }\n\n    if (definitions.second - definitions.first == 1) {\n        ctx.appendErrors(std::move(signatureContext));\n    } else {\n        ctx.error(expectedTypesError(definitions, args));\n    }\n\n    return ParseResult();\n}\n\nParseResult parseCompoundExpression(const std::string& name, const Convertible& value, ParsingContext& ctx) {\n    assert(isArray(value) && arrayLength(value) > 0);\n\n    const auto definitions = compoundExpressionRegistry.equal_range(name.c_str());\n    if (definitions.first == definitions.second) {\n        ctx.error(\n             R\"(Unknown expression \")\" + name + R\"(\". If you wanted a literal array, use [\"literal\", [...]].)\",\n            0\n        );\n        return ParseResult();\n    }\n\n    auto length = arrayLength(value);\n    \n    for (auto it = definitions.first; it != definitions.second; ++it) {\n        const auto& signature = it->second();\n\n        if (\n            signature->params.is<VarargsType>() ||\n            signature->params.get<std::vector<type::Type>>().size() == length - 1\n            ) {\n            // First parse all the args, potentially coercing to the\n            // types expected by this overload.\n            ctx.clearErrors();\n            bool argParseFailed = false;\n            std::vector<std::unique_ptr<Expression>> args;\n            args.reserve(length - 1);\n\n            for (std::size_t i = 1; i < length; i++) {\n                optional<type::Type> expected = signature->params.match(\n                    [](const VarargsType& varargs) { return varargs.type; },\n                    [&](const std::vector<type::Type>& params_) { return params_[i - 1]; }\n                );\n\n                auto parsed = ctx.parse(arrayMember(value, i), i, expected);\n                if (!parsed) {\n                    argParseFailed = true;\n                    break;\n                }\n                args.push_back(std::move(*parsed));\n            }\n            if (argParseFailed) {\n                // Couldn't coerce args of this overload to expected type, move\n                // on to next one.\n                continue;\n            } else {\n                ParseResult parseWithArgs = createCompoundExpression(definitions, std::move(args), ctx);\n                if (parseWithArgs) {\n                    return parseWithArgs;\n                }\n            }\n        }\n    }\n    // The args couldn't be coerced to any of the expected types.\n    // Parse the arguments again without expected types just for the error message\n    ctx.clearErrors();\n    std::vector<std::unique_ptr<Expression>> args;\n    args.reserve(length - 1);\n    \n    for (std::size_t i = 1; i < length; i++) {\n        auto parsed = ctx.parse(arrayMember(value, i), i);\n        if (!parsed) {\n            return ParseResult();\n        }\n        args.push_back(std::move(*parsed));\n    }\n\n    ctx.error(expectedTypesError(definitions, args));\n\n    return ParseResult();\n}\n\nParseResult createCompoundExpression(const std::string& name,\n                                     std::vector<std::unique_ptr<Expression>> args,\n                                     ParsingContext& ctx)\n{\n    return createCompoundExpression(compoundExpressionRegistry.equal_range(name.c_str()), std::move(args), ctx);\n}\n\nCompoundExpression::CompoundExpression(const detail::SignatureBase& signature_, std::vector<std::unique_ptr<Expression>> args_) :\n    Expression(Kind::CompoundExpression, signature_.result),\n    signature(signature_),\n    args(std::move(args_))\n{}\n\nstd::string CompoundExpression::getOperator() const {\n    return signature.name;\n}\n\nEvaluationResult CompoundExpression::evaluate(const EvaluationContext& evaluationParams) const {\n    return signature.apply(evaluationParams, args);\n}\n\noptional<std::size_t> CompoundExpression::getParameterCount() const {\n    return signature.params.match([&](const VarargsType&) -> optional<std::size_t> { return {}; },\n                                  [&](const std::vector<type::Type>& p) -> optional<std::size_t> { return p.size(); });\n}\n\nstd::vector<optional<Value>> CompoundExpression::possibleOutputs() const {\n    return { nullopt };\n}\n\nvoid CompoundExpression::eachChild(const std::function<void(const Expression&)>& visit) const {\n    for (const std::unique_ptr<Expression>& e : args) {\n        visit(*e);\n    }\n}\n\nbool CompoundExpression::operator==(const Expression& e) const {\n    if (e.getKind() == Kind::CompoundExpression) {\n        auto rhs = static_cast<const CompoundExpression*>(&e);\n        return signature.name == rhs->signature.name &&\n            signature.result == rhs->signature.result &&\n            signature.params == rhs->signature.params &&\n            Expression::childrenEqual(args, rhs->args);\n    }\n    return false;\n}\n\nbool CompoundExpression::exists(const std::string& name) {\n    return compoundExpressionRegistry.contains(name.c_str());\n}\n\n} // namespace expression\n} // namespace style\n} // namespace mbgl\n", "meta": {"hexsha": "bae0258aa0c5f6a904da621a8d96a06b5c9a5ff6", "size": 46379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mbgl/style/expression/compound_expression.cpp", "max_stars_repo_name": "meowcoder/mapbox-gl-native", "max_stars_repo_head_hexsha": "b8edc2399b9640498ccbbbb5b8f058c63d070933", "max_stars_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_stars_count": 4234.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T08:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:13:55.000Z", "max_issues_repo_path": "src/mbgl/style/expression/compound_expression.cpp", "max_issues_repo_name": "meowcoder/mapbox-gl-native", "max_issues_repo_head_hexsha": "b8edc2399b9640498ccbbbb5b8f058c63d070933", "max_issues_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_issues_count": 12771.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T20:27:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T18:14:44.000Z", "max_forks_repo_path": "src/mbgl/style/expression/compound_expression.cpp", "max_forks_repo_name": "meowcoder/mapbox-gl-native", "max_forks_repo_head_hexsha": "b8edc2399b9640498ccbbbb5b8f058c63d070933", "max_forks_repo_licenses": ["BSD-2-Clause", "BSD-3-Clause"], "max_forks_count": 1571.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T08:24:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T06:30:53.000Z", "avg_line_length": 38.8108786611, "max_line_length": 158, "alphanum_fraction": 0.6348778542, "num_tokens": 9965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1710612001304791, "lm_q2_score": 0.009412588415317832, "lm_q1q2_score": 0.0016101286706585126}}
{"text": "// [===========================================================================]\n// [                                M o n e t a                                ]\n// [---------------------------------------------------------------------------]\n// [                                                                           ]\n// [                          Copyright (C) 2005-2015                          ]\n// [                      Rodrigo Madera <madera@acm.org>                      ]\n// [                                                                           ]\n// [---------------------------------------------------------------------------]\n// [         Distributed under the Boost Software License, Version 1.0         ]\n// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]\n// [===========================================================================]\n\n#pragma once\n#include <boost/mpl/bool.hpp>\n\n// TODO: Clean this up, MPLize and PPize it and create fork on GitHub to give back to the community.\n// From: https://github.com/jaredhoberock/is_call_possible\n// With inspiration from: Roman Perepelitsa\n\n// inspired by Roman Perepelitsa's presentation from comp.lang.c++.moderated\n// based on the implementation here: http://www.rsdn.ru/forum/cpp/2759773.1.aspx\n\nnamespace is_call_possible_detail {\n\ttemplate<typename T> struct add_reference     { typedef T& type; };\n\ttemplate<typename T> struct add_reference<T&> { typedef T& type; };\n} // end is_call_possible_detail\n\n#define DEFINE_HAS_MEMBER_FUNCTION(trait_name, member_function_name)                                         \\\n                                                                                                             \\\ntemplate<typename T, typename Signature>                                                                     \\\nclass trait_name;                                                                                            \\\n                                                                                                             \\\ntemplate<typename T, typename Result>                                                                        \\\nclass trait_name<T, Result(void)>                                                                            \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name();                                                                          \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(), &U::member_function_name>* = 0);                    \\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};                                                                                                           \\\n                                                                                                             \\\ntemplate<typename T, typename Result, typename Arg>                                                          \\\nclass trait_name<T, Result(Arg)>                                                                             \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name(Arg);                                                                       \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(Arg), &U::member_function_name>* = 0);                 \\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};                                                                                                           \\\n                                                                                                             \\\ntemplate<typename T, typename Result, typename Arg1, typename Arg2>                                          \\\nclass trait_name<T, Result(Arg1,Arg2)>                                                                       \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name(Arg1,Arg2);                                                                 \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(Arg1,Arg2), &U::member_function_name>* = 0);           \\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};                                                                                                           \\\n                                                                                                             \\\ntemplate<typename T, typename Result, typename Arg1, typename Arg2, typename Arg3>                           \\\nclass trait_name<T, Result(Arg1,Arg2,Arg3)>                                                                  \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name(Arg1,Arg2,Arg3);                                                            \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(Arg1,Arg2,Arg3), &U::member_function_name>* = 0);      \\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};                                                                                                           \\\n                                                                                                             \\\ntemplate<typename T, typename Result, typename Arg1, typename Arg2, typename Arg3, typename Arg4>            \\\nclass trait_name<T, Result(Arg1,Arg2,Arg3,Arg4)>                                                             \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name(Arg1,Arg2,Arg3,Arg4);                                                       \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(Arg1,Arg2,Arg3,Arg4), &U::member_function_name>* = 0); \\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};                                                                                                           \\\n                                                                                                             \\\ntemplate<typename T, typename Result, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> \\\nclass trait_name<T, Result(Arg1,Arg2,Arg3,Arg4,Arg5)>                                                        \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name(Arg1,Arg2,Arg3,Arg4,Arg5);                                                  \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(Arg1,Arg2,Arg3,Arg4,Arg5), &U::member_function_name>* = 0); \\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};                                                                                                           \\\n                                                                                                             \\\ntemplate<typename T, typename Result, class T0, class T1, class T2, class T3, class T4, class T5>            \\\nclass trait_name<T, Result(T0,T1,T2,T3,T4,T5)>                                                               \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name(T0,T1,T2,T3,T4,T5);                                                         \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(T0,T1,T2,T3,T4,T5), &U::member_function_name>* = 0);   \\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};                                                                                                           \\\n                                                                                                             \\\ntemplate<typename T, typename Result, class T0, class T1, class T2, class T3, class T4, class T5, class T6>  \\\nclass trait_name<T, Result(T0,T1,T2,T3,T4,T5,T6)>                                                            \\\n{                                                                                                            \\\n   class yes { char m; };                                                                                    \\\n   class no { yes m[2]; };                                                                                   \\\n   struct base_mixin                                                                                         \\\n   {                                                                                                         \\\n     Result member_function_name(T0,T1,T2,T3,T4,T5,T6);                                                      \\\n   };                                                                                                        \\\n   struct base : public T, public base_mixin {};                                                             \\\n   template <typename U, U t>  class helper{};                                                               \\\n   template <typename U>                                                                                     \\\n   static no deduce(U*, helper<Result (base_mixin::*)(T0,T1,T2,T3,T4,T5,T6), &U::member_function_name>* = 0);\\\n   static yes deduce(...);                                                                                   \\\npublic:                                                                                                      \\\n   static const bool value = sizeof(yes) == sizeof(deduce(static_cast<base*>(0)));                           \\\n   static const boost::mpl::bool_<value> type;                                                               \\\n};\n\nnamespace is_call_possible_detail { \n   template <typename T>\n   class void_exp_result {}; \n\n   template <typename T, typename U> \n   U const& operator,(U const&, void_exp_result<T>); \n\n   template <typename T, typename U> \n   U& operator,(U&, void_exp_result<T>); \n\n   template <typename src_type, typename dest_type> \n   struct clone_constness { typedef dest_type type; }; \n\n   template <typename src_type, typename dest_type> \n   struct clone_constness<const src_type, dest_type> { \n     typedef const dest_type type; \n   }; \n} \n\n#define DEFINE_IS_CALL_POSSIBLE(trait_name, member_function_name)                                                       \\\nnamespace moneta { namespace traits { namespace detail {                                                                \\\nnamespace trait_name##_detail                                                                                           \\\n{                                                                                                                       \\\nDEFINE_HAS_MEMBER_FUNCTION(has_member, member_function_name)                                                            \\\n}                                                                                                                       \\\n                                                                                                                        \\\ntemplate <typename T, typename Signature>                                                                               \\\nstruct trait_name                                                                                                       \\\n{                                                                                                                       \\\n  private:                                                                                                              \\\n   class yes {};                                                                                                        \\\n   class no { yes m[2]; };                                                                                              \\\n   struct derived : public T                                                                                            \\\n   {                                                                                                                    \\\n     using T::member_function_name;                                                                                     \\\n     no member_function_name(...) const;                                                                                \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   typedef typename is_call_possible_detail::clone_constness<T, derived>::type derived_type;                            \\\n                                                                                                                        \\\n   template <typename U, typename Result>                                                                               \\\n   struct return_value_check                                                                                            \\\n   {                                                                                                                    \\\n     static yes deduce(Result);                                                                                         \\\n     static no deduce(...);                                                                                             \\\n     static no deduce(no);                                                                                              \\\n     static no deduce(is_call_possible_detail::void_exp_result<T>);                                                     \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename U>                                                                                                \\\n   struct return_value_check<U, void>                                                                                   \\\n   {                                                                                                                    \\\n     static yes deduce(...);                                                                                            \\\n     static no deduce(no);                                                                                              \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <bool has_the_member_of_interest, typename F>                                                               \\\n   struct impl                                                                                                          \\\n   {                                                                                                                    \\\n     static const bool value = false;                                                                                   \\\n     typedef boost::mpl::bool_<value> type;                                                                             \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename Result, typename Arg>                                                                             \\\n   struct impl<true, Result(Arg)>                                                                                       \\\n   {                                                                                                                    \\\n     static typename is_call_possible_detail::add_reference<derived_type>::type test_me;                                \\\n     static typename is_call_possible_detail::add_reference<Arg>::type          arg;                                    \\\n                                                                                                                        \\\n     static const bool value =                                                                                          \\\n       sizeof(                                                                                                          \\\n            return_value_check<T, Result>::deduce(                                                                      \\\n             (test_me.member_function_name(arg), is_call_possible_detail::void_exp_result<T>())                         \\\n                         )                                                                                              \\\n            ) == sizeof(yes);                                                                                           \\\n     typedef boost::mpl::bool_<value> type;                                                                        \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename Result, typename Arg1, typename Arg2>                                                             \\\n   struct impl<true, Result(Arg1,Arg2)>                                                                                 \\\n   {                                                                                                                    \\\n     static typename is_call_possible_detail::add_reference<derived_type>::type test_me;                                \\\n     static typename is_call_possible_detail::add_reference<Arg1>::type         arg1;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg2>::type         arg2;                                   \\\n                                                                                                                        \\\n     static const bool value =                                                                                          \\\n       sizeof(                                                                                                          \\\n            return_value_check<T, Result>::deduce(                                                                      \\\n             (test_me.member_function_name(arg1,arg2), is_call_possible_detail::void_exp_result<T>())                   \\\n                         )                                                                                              \\\n            ) == sizeof(yes);                                                                                           \\\n     typedef boost::mpl::bool_<value> type;                                                                             \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename Result, typename Arg1, typename Arg2, typename Arg3>                                              \\\n   struct impl<true, Result(Arg1,Arg2,Arg3)>                                                                            \\\n   {                                                                                                                    \\\n     static typename is_call_possible_detail::add_reference<derived_type>::type test_me;                                \\\n     static typename is_call_possible_detail::add_reference<Arg1>::type         arg1;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg2>::type         arg2;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg3>::type         arg3;                                   \\\n                                                                                                                        \\\n     static const bool value =                                                                                          \\\n       sizeof(                                                                                                          \\\n            return_value_check<T, Result>::deduce(                                                                      \\\n             (test_me.member_function_name(arg1,arg2,arg3), is_call_possible_detail::void_exp_result<T>())              \\\n                         )                                                                                              \\\n            ) == sizeof(yes);                                                                                           \\\n     typedef boost::mpl::bool_<value> type;                                                                             \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename Result, typename Arg1, typename Arg2, typename Arg3, typename Arg4>                               \\\n   struct impl<true, Result(Arg1,Arg2,Arg3,Arg4)>                                                                       \\\n   {                                                                                                                    \\\n     static typename is_call_possible_detail::add_reference<derived_type>::type test_me;                                \\\n     static typename is_call_possible_detail::add_reference<Arg1>::type         arg1;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg2>::type         arg2;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg3>::type         arg3;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg4>::type         arg4;                                   \\\n                                                                                                                        \\\n     static const bool value =                                                                                          \\\n       sizeof(                                                                                                          \\\n            return_value_check<T, Result>::deduce(                                                                      \\\n             (test_me.member_function_name(arg1,arg2,arg3,arg4), is_call_possible_detail::void_exp_result<T>())         \\\n                         )                                                                                              \\\n            ) == sizeof(yes);                                                                                           \\\n     typedef boost::mpl::bool_<value> type;                                                                             \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename Result, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5>                \\\n   struct impl<true, Result(Arg1,Arg2,Arg3,Arg4,Arg5)>                                                                  \\\n   {                                                                                                                    \\\n     static typename is_call_possible_detail::add_reference<derived_type>::type test_me;                                \\\n     static typename is_call_possible_detail::add_reference<Arg1>::type         arg1;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg2>::type         arg2;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg3>::type         arg3;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg4>::type         arg4;                                   \\\n     static typename is_call_possible_detail::add_reference<Arg5>::type         arg5;                                   \\\n                                                                                                                        \\\n     static const bool value =                                                                                          \\\n       sizeof(                                                                                                          \\\n            return_value_check<T, Result>::deduce(                                                                      \\\n             (test_me.member_function_name(arg1,arg2,arg3,arg4,arg5), is_call_possible_detail::void_exp_result<T>())    \\\n                         )                                                                                              \\\n            ) == sizeof(yes);                                                                                           \\\n     typedef boost::mpl::bool_<value> type;                                                                             \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename Result, class T0, class T1, class T2, class T3, class T4, class T5>                               \\\n   struct impl<true, Result(T0,T1,T2,T3,T4,T5)>                                                                         \\\n   {                                                                                                                    \\\n     static typename is_call_possible_detail::add_reference<derived_type>::type test_me;                                \\\n     static typename is_call_possible_detail::add_reference<T0>::type         arg1;                                     \\\n     static typename is_call_possible_detail::add_reference<T1>::type         arg2;                                     \\\n     static typename is_call_possible_detail::add_reference<T2>::type         arg3;                                     \\\n     static typename is_call_possible_detail::add_reference<T3>::type         arg4;                                     \\\n     static typename is_call_possible_detail::add_reference<T4>::type         arg5;                                     \\\n     static typename is_call_possible_detail::add_reference<T5>::type         arg6;                                     \\\n                                                                                                                        \\\n     static const bool value =                                                                                          \\\n       sizeof(                                                                                                          \\\n            return_value_check<T, Result>::deduce(                                                                      \\\n             (test_me.member_function_name(arg1,arg2,arg3,arg4,arg5,arg6), is_call_possible_detail::void_exp_result<T>()) \\\n                         )                                                                                              \\\n            ) == sizeof(yes);                                                                                           \\\n     typedef boost::mpl::bool_<value> type;                                                                             \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n   template <typename Result, class T0, class T1, class T2, class T3, class T4, class T5, class T6>                     \\\n   struct impl<true, Result(T0,T1,T2,T3,T4,T5,T6)>                                                                      \\\n   {                                                                                                                    \\\n     static typename is_call_possible_detail::add_reference<derived_type>::type test_me;                                \\\n     static typename is_call_possible_detail::add_reference<T0>::type         arg1;                                     \\\n     static typename is_call_possible_detail::add_reference<T1>::type         arg2;                                     \\\n     static typename is_call_possible_detail::add_reference<T2>::type         arg3;                                     \\\n     static typename is_call_possible_detail::add_reference<T3>::type         arg4;                                     \\\n     static typename is_call_possible_detail::add_reference<T4>::type         arg5;                                     \\\n     static typename is_call_possible_detail::add_reference<T5>::type         arg6;                                     \\\n     static typename is_call_possible_detail::add_reference<T5>::type         arg7;                                     \\\n                                                                                                                        \\\n     static const bool value =                                                                                          \\\n       sizeof(                                                                                                          \\\n            return_value_check<T, Result>::deduce(                                                                      \\\n             (test_me.member_function_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7), is_call_possible_detail::void_exp_result<T>()) \\\n                         )                                                                                              \\\n            ) == sizeof(yes);                                                                                           \\\n     typedef boost::mpl::bool_<value> type;                                                                             \\\n   };                                                                                                                   \\\n                                                                                                                        \\\n  public:                                                                                                               \\\n    static const bool value = impl<trait_name##_detail::has_member<T,Signature>::value, Signature>::value;              \\\n    typedef boost::mpl::bool_<value> type;                                                                              \\\n};                                                                                                                      \\\n}}}\n", "meta": {"hexsha": "80a9f92a103404d7cfb2b1601f5fd31267f4df20", "size": 40495, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/moneta/traits/detail/pp/is_method_callable_spec.hxx", "max_stars_repo_name": "madera/Moneta", "max_stars_repo_head_hexsha": "4c0da911bceb511d7d1133699b0d85216bb63d74", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-10-09T12:11:54.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-20T15:34:33.000Z", "max_issues_repo_path": "include/moneta/traits/detail/pp/is_method_callable_spec.hxx", "max_issues_repo_name": "madera/Moneta", "max_issues_repo_head_hexsha": "4c0da911bceb511d7d1133699b0d85216bb63d74", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-07-04T20:31:32.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-04T20:44:58.000Z", "max_forks_repo_path": "include/moneta/traits/detail/pp/is_method_callable_spec.hxx", "max_forks_repo_name": "madera/Moneta", "max_forks_repo_head_hexsha": "4c0da911bceb511d7d1133699b0d85216bb63d74", "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": 106.8469656992, "max_line_length": 128, "alphanum_fraction": 0.2365477219, "num_tokens": 4462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.061875982263751246, "lm_q2_score": 0.0247981618171964, "lm_q1q2_score": 0.0015344106207744778}}
{"text": "/**********************************************************************\r\n *  Copyright (c) 2008-2013, 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 <analysis/UncertaintyDescription.hpp>\r\n#include <analysis/UncertaintyDescription_Impl.hpp>\r\n\r\n#include <analysis/GenericUncertaintyDescription.hpp>\r\n\r\n#include <utilities/core/Assert.hpp>\r\n#include <utilities/core/Finder.hpp>\r\n#include <utilities/core/Json.hpp>\r\n\r\n#include <boost/foreach.hpp>\r\n#include <boost/bind.hpp>\r\n\r\nnamespace openstudio {\r\nnamespace analysis {\r\n\r\nnamespace detail {\r\n\r\n  UncertaintyDescription_Impl::UncertaintyDescription_Impl(const UncertaintyDescriptionType& type)\r\n    : m_type(type)\r\n  {\r\n    OS_ASSERT(this->type() != UncertaintyDescriptionType::Generic);\r\n    populateAttributeDescriptions();\r\n    restoreDefaults();\r\n  }\r\n\r\n  UncertaintyDescription_Impl::UncertaintyDescription_Impl(const UncertaintyDescriptionType& type,\r\n                                                           const std::vector<Attribute>& attributes)\r\n    : m_type(type),\r\n      m_attributes(attributes)\r\n  {\r\n    OS_ASSERT(this->type() != UncertaintyDescriptionType::Generic);\r\n    populateAttributeDescriptions();\r\n  }\r\n\r\n  UncertaintyDescription_Impl::UncertaintyDescription_Impl(const UncertaintyDescription_Impl& other)\r\n    : m_type(other.type()),\r\n      m_attributes(other.attributes(true)),\r\n      m_attributeDescriptions(other.attributeDescriptions())\r\n  {\r\n    OS_ASSERT(type() != UncertaintyDescriptionType::Generic);\r\n  }\r\n\r\n  UncertaintyDescriptionType UncertaintyDescription_Impl::type() const {\r\n    return m_type;\r\n  }\r\n\r\n  std::vector<Attribute> UncertaintyDescription_Impl::attributes(bool clones) const {\r\n    if (clones) {\r\n      AttributeVector result;\r\n      BOOST_FOREACH(const Attribute& attribute,m_attributes) {\r\n        result.push_back(attribute.clone());\r\n      }            \r\n      return result;\r\n    }\r\n    return m_attributes;\r\n  }\r\n\r\n  Attribute UncertaintyDescription_Impl::getAttribute(const std::string& attributeName, bool clone) const {\r\n    OptionalAttribute result = findByName<Attribute>(m_attributes,attributeName,true);\r\n    OS_ASSERT(result);\r\n    if (clone) {\r\n      return result->clone();\r\n    }\r\n    return result.get();\r\n  }\r\n\r\n  bool UncertaintyDescription_Impl::isSet(const std::string& attributeName) const {\r\n    return findByName<Attribute>(m_attributes,attributeName,true);\r\n  }\r\n\r\n  std::vector<AttributeDescription> UncertaintyDescription_Impl::attributeDescriptions() const {\r\n    return m_attributeDescriptions;\r\n  }\r\n\r\n  AttributeDescription UncertaintyDescription_Impl::getAttributeDescription(\r\n    const std::string& attributeName) const\r\n  {\r\n    OptionalAttributeDescription result = findStructByName<AttributeDescription>(m_attributeDescriptions,\r\n                                                                                 attributeName,\r\n                                                                                 true);\r\n    OS_ASSERT(result);\r\n    return result.get();\r\n  }\r\n\r\n  bool UncertaintyDescription_Impl::hasDescription(const std::string& attributeName) const {\r\n    return findStructByName<AttributeDescription>(m_attributeDescriptions,attributeName,true);\r\n  }\r\n\r\n  bool UncertaintyDescription_Impl::isComplete() const {\r\n    BOOST_FOREACH(const AttributeDescription& desc,attributeDescriptions()) {\r\n      if (desc.required && !isSet(desc.name)) {\r\n        return false;\r\n      }\r\n    }\r\n    return true;\r\n  }\r\n\r\n  bool UncertaintyDescription_Impl::setAttribute(const Attribute& candidate, bool check) {\r\n    if (check) {\r\n      if (!hasDescription(candidate.name()) || \r\n          !isConsistent(candidate,getAttributeDescription(candidate.name()))) \r\n      {\r\n        return false;\r\n      }\r\n    }\r\n    if (isSet(candidate.name())) {\r\n      Attribute myCopy = getAttribute(candidate.name(),false);\r\n      if (myCopy.valueType() == AttributeValueType::AttributeVector) {\r\n        myCopy.setValue(candidate.valueAsAttributeVector());\r\n      }\r\n      else {\r\n        myCopy.setValue(candidate.valueAsQVariant());\r\n      }\r\n    }\r\n    else {\r\n      m_attributes.push_back(candidate.clone());\r\n      bool ok = prepareForDisplay(m_attributes.back(),getAttributeDescription(candidate.name()));\r\n      OS_ASSERT(ok);\r\n    }\r\n    return true;\r\n  }\r\n\r\n  bool UncertaintyDescription_Impl::clearAttribute(const std::string& attributeName, bool check) {\r\n    if (check) {\r\n      if (!hasDescription(attributeName)) {\r\n        return false;\r\n      }\r\n      AttributeDescription desc = getAttributeDescription(attributeName);\r\n      if (desc.required) {\r\n        return false;\r\n      }\r\n    }   \r\n    AttributeVector::iterator it = findIteratorByName<Attribute>(m_attributes,attributeName,true);\r\n    if (it == m_attributes.end()) {\r\n      return false;\r\n    }\r\n    m_attributes.erase(it);\r\n    return true;\r\n  }\r\n\r\n  void UncertaintyDescription_Impl::restoreDefaults() {\r\n    m_attributes.clear();\r\n    std::vector<double> vectorValue(2);\r\n    switch (type().value()) {\r\n      case UncertaintyDescriptionType::normal_uncertain :\r\n        setAttribute(Attribute(\"means\",0.0),false);\r\n        setAttribute(Attribute(\"std_deviations\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::lognormal_uncertain :\r\n        setAttribute(Attribute(\"means\",1.0),false);\r\n        setAttribute(Attribute(\"std_deviations\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::uniform_uncertain :\r\n        setAttribute(Attribute(\"lower_bounds\",0.0),false);\r\n        setAttribute(Attribute(\"upper_bounds\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::loguniform_uncertain :\r\n        setAttribute(Attribute(\"lower_bounds\",0.1),false);\r\n        setAttribute(Attribute(\"upper_bounds\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::triangular_uncertain :\r\n        setAttribute(Attribute(\"modes\",0.5),false);\r\n        setAttribute(Attribute(\"lower_bounds\",0.0),false);\r\n        setAttribute(Attribute(\"upper_bounds\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::exponential_uncertain :\r\n        setAttribute(Attribute(\"betas\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::beta_uncertain :\r\n        setAttribute(Attribute(\"alphas\",2.0),false);\r\n        setAttribute(Attribute(\"betas\",2.0),false);\r\n        setAttribute(Attribute(\"lower_bounds\",0.0),false);\r\n        setAttribute(Attribute(\"upper_bounds\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::gamma_uncertain :\r\n        setAttribute(Attribute(\"alphas\",2.0),false);\r\n        setAttribute(Attribute(\"betas\",0.5),false);\r\n       break;\r\n      case UncertaintyDescriptionType::gumbel_uncertain :\r\n        setAttribute(Attribute(\"alphas\",1.0),false);\r\n        setAttribute(Attribute(\"betas\",2.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::frechet_uncertain :\r\n        setAttribute(Attribute(\"alphas\",2.0),false);\r\n        setAttribute(Attribute(\"betas\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::weibull_uncertain :\r\n        setAttribute(Attribute(\"alphas\",1.0),false);\r\n        setAttribute(Attribute(\"betas\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::histogram_bin_uncertain :\r\n        vectorValue[0] = 0.0;\r\n        vectorValue[1] = 1.0;\r\n        setAttribute(createAttributeFromVector(\"abscissas\",vectorValue),false);\r\n        vectorValue[0] = 1.0;\r\n        vectorValue[1] = 0.0;\r\n        setAttribute(createAttributeFromVector(\"counts\",vectorValue),false);\r\n       break;\r\n      case UncertaintyDescriptionType::poisson_uncertain :\r\n        setAttribute(Attribute(\"lambdas\",1.0),false);\r\n       break;\r\n      case UncertaintyDescriptionType::binomial_uncertain :\r\n        setAttribute(Attribute(\"prob_per_trial\",0.5),false);\r\n        setAttribute(Attribute(\"num_trials\",20),false);\r\n       break;\r\n      case UncertaintyDescriptionType::negative_binomial_uncertain :\r\n        setAttribute(Attribute(\"prob_per_trial\",0.5),false);\r\n        setAttribute(Attribute(\"num_trials\",20),false);\r\n       break;\r\n      case UncertaintyDescriptionType::geometric_uncertain :\r\n        setAttribute(Attribute(\"prob_per_trial\",0.5),false);\r\n       break;\r\n      case UncertaintyDescriptionType::hypergeometric_uncertain :\r\n        setAttribute(Attribute(\"total_population\",20),false);\r\n        setAttribute(Attribute(\"selected_population\",10),false);\r\n        setAttribute(Attribute(\"num_drawn\",10),false);\r\n       break;\r\n      case UncertaintyDescriptionType::histogram_point_uncertain :\r\n        vectorValue[0] = 0.0;\r\n        vectorValue[1] = 1.0;\r\n        setAttribute(createAttributeFromVector(\"abscissas\",vectorValue),false);\r\n        vectorValue[0] = 1.0;\r\n        vectorValue[1] = 1.0;\r\n        setAttribute(createAttributeFromVector(\"counts\",vectorValue),false);\r\n       break;\r\n      default :\r\n        OS_ASSERT(false);\r\n    }\r\n  }\r\n\r\n  void UncertaintyDescription_Impl::populateAttributeDescriptions() {\r\n    switch (type().value()) {\r\n      case UncertaintyDescriptionType::normal_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"means\",\r\n                                                               \"Mean\",\r\n                                                               \"The mean value of this (optionally bounded) normal distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"std_deviations\",\r\n                                                               \"Standard Deviation\",\r\n                                                               \"The standard deviation of this (optionally bounded) normal distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lower_bounds\",\r\n                                                               \"Lower Bound\",\r\n                                                               \"The lower bound of the region from which samples are drawn\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false,\r\n                                                               QVariant(QString(\"-DBL_MAX\"))));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"upper_bounds\",\r\n                                                               \"Upper Bound\",\r\n                                                               \"The upper bound of the region from which samples are drawn\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false,\r\n                                                               QVariant(QString(\"+DBL_MAX\"))));\r\n       break;\r\n       case UncertaintyDescriptionType::lognormal_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"means\",\r\n                                                               \"Mean\",\r\n                                                               \"The mean value of this (optionally bounded) lognormal distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"std_deviations\",\r\n                                                               \"Standard Deviation\",\r\n                                                               \"The standard deviation of this (optionally bounded) lognormal distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"error_factors\",\r\n                                                               \"Error Factor\",\r\n                                                               \"The error factor of this (optionally bounded) lognormal distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lambdas\",\r\n                                                               \"Lambda\",\r\n                                                               \"The mean value (lambda) of the underlying normal distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"zetas\",\r\n                                                               \"Zeta\",\r\n                                                               \"The standard deviation (zeta) of the underlying normal distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lower_bounds\",\r\n                                                               \"Lower Bound\",\r\n                                                               \"The lower bound of the region from which samples are drawn\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false,\r\n                                                               QVariant(QString(\"0\"))));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"upper_bounds\",\r\n                                                               \"Upper Bound\",\r\n                                                               \"The upper bound of the region from which samples are drawn\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               false,\r\n                                                               QVariant(QString(\"+DBL_MAX\"))));\r\n       break;\r\n       case UncertaintyDescriptionType::uniform_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lower_bounds\",\r\n                                                               \"Lower Bound\",\r\n                                                               \"The lower bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"upper_bounds\",\r\n                                                               \"Upper Bound\",\r\n                                                               \"The upper bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::loguniform_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lower_bounds\",\r\n                                                               \"Lower Bound\",\r\n                                                               \"The lower bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"upper_bounds\",\r\n                                                               \"Upper Bound\",\r\n                                                               \"The upper bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::triangular_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"modes\",\r\n                                                               \"Mode\",\r\n                                                               \"The mode of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lower_bounds\",\r\n                                                               \"Lower Bound\",\r\n                                                               \"The lower bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"upper_bounds\",\r\n                                                               \"Upper Bound\",\r\n                                                               \"The upper bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::exponential_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"betas\",\r\n                                                               \"Beta\",\r\n                                                               \"The beta parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::beta_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"alphas\",\r\n                                                               \"Alpha\",\r\n                                                               \"The alpha parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"betas\",\r\n                                                               \"Beta\",\r\n                                                               \"The beta parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lower_bounds\",\r\n                                                               \"Lower Bound\",\r\n                                                               \"The lower bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"upper_bounds\",\r\n                                                               \"Upper Bound\",\r\n                                                               \"The upper bound of the sampling region\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::gamma_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"alphas\",\r\n                                                               \"Alpha\",\r\n                                                               \"The alpha parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"betas\",\r\n                                                               \"Beta\",\r\n                                                               \"The beta parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::gumbel_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"alphas\",\r\n                                                               \"Alpha\",\r\n                                                               \"The alpha parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"betas\",\r\n                                                               \"Beta\",\r\n                                                               \"The beta parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::frechet_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"alphas\",\r\n                                                               \"Alpha\",\r\n                                                               \"The alpha parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"betas\",\r\n                                                               \"Beta\",\r\n                                                               \"The beta parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::weibull_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"alphas\",\r\n                                                               \"Alpha\",\r\n                                                               \"The alpha parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"betas\",\r\n                                                               \"Beta\",\r\n                                                               \"The beta parameter of the distribution\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::histogram_bin_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"abscissas\",\r\n                                                               \"Abscissas\",\r\n                                                               \"The abscissa values ('x' coordinates) that define the histogram bins\",\r\n                                                               AttributeValueType(AttributeValueType::AttributeVector), // of type double\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"counts\",\r\n                                                               \"Counts\",\r\n                                                               \"The count or frequency associated with a bin\",\r\n                                                               AttributeValueType(AttributeValueType::AttributeVector), // of type double\r\n                                                               false));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"ordinates\",\r\n                                                               \"Ordinates\",\r\n                                                               \"The 'y' coordinates associated with the abscissa\",\r\n                                                               AttributeValueType(AttributeValueType::AttributeVector), // of type double\r\n                                                               false));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"num_pairs\",\r\n                                                               \"Number of Pairs\",\r\n                                                               \"The number of pairs of (x,counts) or (x,ordinates) that have been defined\",\r\n                                                               AttributeValueType(AttributeValueType::Integer),\r\n                                                               false));\r\n       break;\r\n       case UncertaintyDescriptionType::poisson_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"lambdas\",\r\n                                                               \"Lambda\",\r\n                                                               \"The number of expected occurances in the time interval\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::binomial_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"prob_per_trial\",\r\n                                                               \"Probability Per Trial\",\r\n                                                               \"The probability of failure per trial\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"num_trials\",\r\n                                                               \"Number of Trials\",\r\n                                                               \"The number of trials\",\r\n                                                               AttributeValueType(AttributeValueType::Integer),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::negative_binomial_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"prob_per_trial\",\r\n                                                               \"Probability Per Trial\",\r\n                                                               \"The probability of success per trial\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"num_trials\",\r\n                                                               \"Number of Trials\",\r\n                                                               \"The number of trials\",\r\n                                                               AttributeValueType(AttributeValueType::Integer),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::geometric_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"prob_per_trial\",\r\n                                                               \"Probability Per Trial\",\r\n                                                               \"The probability of failure per trial\",\r\n                                                               AttributeValueType(AttributeValueType::Double),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::hypergeometric_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"total_population\",\r\n                                                               \"Total Population\",\r\n                                                               \"The total population from which samples are drawn\",\r\n                                                               AttributeValueType(AttributeValueType::Integer),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"selected_population\",\r\n                                                               \"Selected Population\",\r\n                                                               \"The number of items in the selected population (e.g., the number of white balls)\",\r\n                                                               AttributeValueType(AttributeValueType::Integer),\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"num_drawn\",\r\n                                                               \"Number Drawn\",\r\n                                                               \"The number of items (e.g., balls) drawn\",\r\n                                                               AttributeValueType(AttributeValueType::Integer),\r\n                                                               true));\r\n       break;\r\n       case UncertaintyDescriptionType::histogram_point_uncertain :\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"abscissas\",\r\n                                                               \"Abscissas\",\r\n                                                               \"The abscissa values ('x' coordinates) that define the histogram bins\",\r\n                                                               AttributeValueType(AttributeValueType::AttributeVector), // of type double\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"counts\",\r\n                                                               \"Counts\",\r\n                                                               \"The count or frequency associated with a bin\",\r\n                                                               AttributeValueType(AttributeValueType::AttributeVector), // of type double\r\n                                                               true));\r\n        m_attributeDescriptions.push_back(AttributeDescription(\"num_pairs\",\r\n                                                               \"Number of Pairs\",\r\n                                                               \"The number of pairs of (x,counts) or (x,ordinates) that have been defined\",\r\n                                                               AttributeValueType(AttributeValueType::Integer),\r\n                                                               false));\r\n       break;\r\n      default :\r\n        OS_ASSERT(false);\r\n    }\r\n  }\r\n\r\n} // detail\r\n\r\nUncertaintyDescription UncertaintyDescription::clone() const {\r\n  boost::shared_ptr<detail::UncertaintyDescription_Impl> cloneImpl(\r\n      new detail::UncertaintyDescription_Impl(*impl()));\r\n  return UncertaintyDescription(cloneImpl);\r\n}\r\n  \r\nstd::vector<UncertaintyDescriptionType> UncertaintyDescription::validTypes(\r\n  const VariableValueType& variableValueType)\r\n{\r\n  UncertaintyDescriptionTypeVector result;\r\n  if (variableValueType == VariableValueType::Continuous) {\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::normal_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::lognormal_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::uniform_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::loguniform_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::triangular_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::exponential_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::beta_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::gamma_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::gumbel_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::frechet_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::weibull_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::histogram_bin_uncertain));\r\n  }\r\n  else if (variableValueType == VariableValueType::Discrete) {\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::poisson_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::binomial_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::negative_binomial_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::geometric_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::hypergeometric_uncertain));\r\n    result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::histogram_point_uncertain));\r\n  }\r\n  return result;\r\n}\r\n\r\nstd::vector<UncertaintyDescriptionType> UncertaintyDescription::validTypes(\r\n  const VariableValueType& variableValueType,\r\n  const UncertaintyType& uncertaintyType)\r\n{\r\n  UncertaintyDescriptionTypeVector result;\r\n  if (uncertaintyType == UncertaintyType::Aleatory) {\r\n    if (variableValueType == VariableValueType::Continuous) {\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::normal_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::lognormal_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::uniform_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::loguniform_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::triangular_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::exponential_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::beta_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::gamma_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::gumbel_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::frechet_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::weibull_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::histogram_bin_uncertain));\r\n    }\r\n    else if (variableValueType == VariableValueType::Discrete) {\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::poisson_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::binomial_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::negative_binomial_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::geometric_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::hypergeometric_uncertain));\r\n      result.push_back(UncertaintyDescriptionType(UncertaintyDescriptionType::histogram_point_uncertain));\r\n    }\r\n  }\r\n  return result;\r\n}\r\n\r\nUncertaintyDescriptionType UncertaintyDescription::type() const {\r\n  return impl()->type();\r\n}\r\n\r\nvoid UncertaintyDescription::restoreDefaults() {\r\n  return impl()->restoreDefaults();\r\n}\r\n\r\nUncertaintyDescription::UncertaintyDescription(boost::shared_ptr<detail::UncertaintyDescription_Impl> impl) \r\n  : m_impl(impl)\r\n{}\r\n\r\nboost::shared_ptr<detail::UncertaintyDescription_Impl> UncertaintyDescription::impl() const {\r\n  return m_impl;\r\n}\r\n\r\nnamespace detail {\r\n\r\n  QVariant toVariant(const UncertaintyDescription& udesc) {\r\n    GenericUncertaintyDescription generic = udesc.cast<GenericUncertaintyDescription>();\r\n\r\n    QVariantMap udescMap;\r\n    udescMap[\"type\"] = toQString(generic.actualType().valueName());\r\n    if (!generic.attributes().empty()) {\r\n      QVariantList attributesList;\r\n      Q_FOREACH(const Attribute& attribute,generic.attributes()) {\r\n        attributesList.push_back(openstudio::detail::toVariant(attribute));\r\n      }\r\n      udescMap[\"attributes\"] = QVariant(attributesList);\r\n    }\r\n\r\n    return QVariant(udescMap);\r\n  }\r\n\r\n  UncertaintyDescription toUncertaintyDescription(const QVariant& variant,\r\n                                                  const VersionString& version)\r\n  {\r\n    QVariantMap map = variant.toMap();\r\n\r\n    AttributeVector attributes = deserializeUnorderedVector(\r\n          map[\"attributes\"].toList(),\r\n          boost::function<Attribute (const QVariant&)>(boost::bind(openstudio::detail::toAttribute,_1,version)));\r\n\r\n    GenericUncertaintyDescription result(UncertaintyDescriptionType(map[\"type\"].toString().toStdString()),\r\n                                         attributes);\r\n\r\n    return result.cast<UncertaintyDescription>();\r\n  }\r\n\r\n} // detail\r\n\r\n} // analysis\r\n} // openstudio\r\n", "meta": {"hexsha": "930c760140b1bc726f5ee7d6088427a854e07643", "size": 39674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/analysis/UncertaintyDescription.cpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openstudiocore/src/analysis/UncertaintyDescription.cpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/analysis/UncertaintyDescription.cpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.6636085627, "max_line_length": 147, "alphanum_fraction": 0.5074608056, "num_tokens": 5565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07696083781311953, "lm_q2_score": 0.01941934821791753, "lm_q1q2_score": 0.001494529308635643}}
{"text": "/*\n * Copyright 2020 Tier IV, 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\n// Copyright (c) 2019, Map IV, Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// * 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 Map IV, Inc. nor the names of its contributors\n//   may be used to endorse or promote products derived from this software\n//   without specific prior written permission.\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 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 * tag_serial_driver.cpp\n * Tamagawa IMU Driver\n * Author MapIV Sekino\n * Ver 1.00 2019/4/4\n */\n\n#include <fcntl.h>\n#include <math.h>\n#include <signal.h>\n#include <stdio.h>\n#include <termios.h>\n#include <unistd.h>\n#include <string>\n#include \"ros/ros.h\"\n#include \"sensor_msgs/Imu.h\"\n#include \"std_msgs/Int32.h\"\n\n#include <sys/ioctl.h>\n\nstd::string device = \"/dev/ttyUSB0\";\nstd::string imu_type = \"noGPS\";\nstd::string rate = \"50\";\n\nstruct termios old_conf_tio;\nstruct termios conf_tio;\n\nint fd;\nint counter;\nint raw_data;\n\nsensor_msgs::Imu imu_msg;\n\nint serial_setup(const char * device)\n{\n  int fd = open(device, O_RDWR);\n\n  speed_t BAUDRATE = B115200;\n\n  conf_tio.c_cflag += CREAD;   // 受信有効\n  conf_tio.c_cflag += CLOCAL;  // ローカルライン（モデム制御なし）\n  conf_tio.c_cflag += CS8;     // データビット:8bit\n  conf_tio.c_cflag += 0;       // ストップビット:1bit\n  conf_tio.c_cflag += 0;\n\n  cfsetispeed(&conf_tio, BAUDRATE);\n  cfsetospeed(&conf_tio, BAUDRATE);\n\n  tcsetattr(fd, TCSANOW, &conf_tio);\n  ioctl(fd, TCSETS, &conf_tio);\n  return fd;\n}\n\nvoid receive_ver_req(const std_msgs::Int32::ConstPtr & msg)\n{\n  char ver_req[] = \"$TSC,VER*29\\x0d\\x0a\";\n  int ver_req_data = write(fd, ver_req, sizeof(ver_req));\n  ROS_INFO(\"Send Version Request:%s\", ver_req);\n}\n\nvoid receive_offset_cancel_req(const std_msgs::Int32::ConstPtr & msg)\n{\n  char offset_cancel_req[32];\n  sprintf(offset_cancel_req, \"$TSC,OFC,%d\\x0d\\x0a\", msg->data);\n  int offset_cancel_req_data = write(fd, offset_cancel_req, sizeof(offset_cancel_req));\n  ROS_INFO(\"Send Offset Cancel Request:%s\", offset_cancel_req);\n}\n\nvoid receive_heading_reset_req(const std_msgs::Int32::ConstPtr & msg)\n{\n  char heading_reset_req[] = \"$TSC,HRST*29\\x0d\\x0a\";\n  int heading_reset_req_data = write(fd, heading_reset_req, sizeof(heading_reset_req));\n  ROS_INFO(\"Send Heading reset Request:%s\", heading_reset_req);\n}\n\nvoid shutdown_cmd(int sig)\n{\n  tcsetattr(fd, TCSANOW, &old_conf_tio);  // Revert to previous settings\n  close(fd);\n  ROS_INFO(\"Port closed\");\n  ros::shutdown();\n}\n\n#include <boost/asio.hpp>\nusing namespace boost::asio;\n\nint main(int argc, char ** argv)\n{\n  ros::init(argc, argv, \"tag_serial_driver\", ros::init_options::NoSigintHandler);\n  ros::NodeHandle n;\n  ros::Publisher pub = n.advertise<sensor_msgs::Imu>(\"imu/data_raw\", 1000);\n  ros::Subscriber sub1 = n.subscribe(\"receive_ver_req\", 10, receive_ver_req);\n  ros::Subscriber sub2 = n.subscribe(\"receive_offset_cancel_req\", 10, receive_offset_cancel_req);\n  ros::Subscriber sub3 = n.subscribe(\"receive_heading_reset_req\", 10, receive_heading_reset_req);\n\n  ros::NodeHandle nh(\"~\");\n  std::string imu_frame_id = \"imu\";\n  nh.getParam(\"imu_frame_id\", imu_frame_id);\n\n  std::string port = \"/dev/ttyUSB0\";\n  nh.getParam(\"port\", port);\n\n  io_service io;\n  serial_port serial_port(io, port.c_str());\n  serial_port.set_option(serial_port_base::baud_rate(115200));\n  serial_port.set_option(serial_port_base::character_size(8));\n  serial_port.set_option(serial_port_base::flow_control(serial_port_base::flow_control::none));\n  serial_port.set_option(serial_port_base::parity(serial_port_base::parity::none));\n  serial_port.set_option(serial_port_base::stop_bits(serial_port_base::stop_bits::one));\n\n  std::string wbuf = \"$TSC,BIN,30\\x0d\\x0a\";\n  std::size_t length;\n  serial_port.write_some(buffer(wbuf));\n\n  ros::Rate loop_rate(30);\n\n  imu_msg.orientation.x = 0.0;\n  imu_msg.orientation.y = 0.0;\n  imu_msg.orientation.z = 0.0;\n  imu_msg.orientation.w = 1.0;\n\n  while (ros::ok()) {\n    ros::spinOnce();\n\n    boost::asio::streambuf response;\n    boost::asio::read_until(serial_port, response, \"\\n\");\n    std::string rbuf(\n      boost::asio::buffers_begin(response.data()), boost::asio::buffers_end(response.data()));\n\n    length = rbuf.size();\n    size_t len = response.size();\n\n    if (length > 0) {\n      if (rbuf[5] == 'B' && rbuf[6] == 'I' && rbuf[7] == 'N' && rbuf[8] == ',' && length == 58) {\n        imu_msg.header.frame_id = imu_frame_id;\n        imu_msg.header.stamp = ros::Time::now();\n\n        counter = ((rbuf[11] << 8) & 0x0000FF00) | (rbuf[12] & 0x000000FF);\n        raw_data = ((((rbuf[15] << 8) & 0xFFFFFF00) | (rbuf[16] & 0x000000FF)));\n        imu_msg.angular_velocity.x =\n          raw_data * (200 / pow(2, 15)) * M_PI / 180;  // LSB & unit [deg/s] => [rad/s]\n        raw_data = ((((rbuf[17] << 8) & 0xFFFFFF00) | (rbuf[18] & 0x000000FF)));\n        imu_msg.angular_velocity.y =\n          raw_data * (200 / pow(2, 15)) * M_PI / 180;  // LSB & unit [deg/s] => [rad/s]\n        raw_data = ((((rbuf[19] << 8) & 0xFFFFFF00) | (rbuf[20] & 0x000000FF)));\n        imu_msg.angular_velocity.z =\n          raw_data * (200 / pow(2, 15)) * M_PI / 180;  // LSB & unit [deg/s] => [rad/s]\n        raw_data = ((((rbuf[21] << 8) & 0xFFFFFF00) | (rbuf[22] & 0x000000FF)));\n        imu_msg.linear_acceleration.x = raw_data * (100 / pow(2, 15));  // LSB & unit [m/s^2]\n        raw_data = ((((rbuf[23] << 8) & 0xFFFFFF00) | (rbuf[24] & 0x000000FF)));\n        imu_msg.linear_acceleration.y = raw_data * (100 / pow(2, 15));  // LSB & unit [m/s^2]\n        raw_data = ((((rbuf[25] << 8) & 0xFFFFFF00) | (rbuf[26] & 0x000000FF)));\n        imu_msg.linear_acceleration.z = raw_data * (100 / pow(2, 15));  // LSB & unit [m/s^2]\n\n        pub.publish(imu_msg);\n\n      } else if (rbuf[5] == 'V' && rbuf[6] == 'E' && rbuf[7] == 'R' && rbuf[8] == ',') {\n        ROS_DEBUG(\"%s\", rbuf.c_str());\n      }\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "e408fd4037fe4845fdee910f3db0c3bb763597c7", "size": 7541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tag_serial_driver.cpp", "max_stars_repo_name": "esteve/tamagawa_imu_driver", "max_stars_repo_head_hexsha": "cb2a519ec5a0f4d69bf2ab6f3945c123bc80389b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-27T14:26:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T14:26:35.000Z", "max_issues_repo_path": "src/tag_serial_driver.cpp", "max_issues_repo_name": "esteve/tamagawa_imu_driver", "max_issues_repo_head_hexsha": "cb2a519ec5a0f4d69bf2ab6f3945c123bc80389b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T08:55:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T05:38:31.000Z", "max_forks_repo_path": "src/tag_serial_driver.cpp", "max_forks_repo_name": "esteve/tamagawa_imu_driver", "max_forks_repo_head_hexsha": "cb2a519ec5a0f4d69bf2ab6f3945c123bc80389b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-02T03:03:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T09:38:05.000Z", "avg_line_length": 36.6067961165, "max_line_length": 97, "alphanum_fraction": 0.6821376475, "num_tokens": 2174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07263671037579261, "lm_q2_score": 0.018264278051270327, "lm_q1q2_score": 0.0013266570750330687}}
{"text": "//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n// Lua plugin for Zen Scripting\r\n//\r\n// Copyright (C) 2001 - 2016 Raymond A. Richards\r\n//\r\n//  This software is provided 'as-is', without any express or implied\r\n//  warranty.  In no event will the authors be held liable for any damages\r\n//  arising from the use of this software.\r\n//\r\n//  Permission is granted to anyone to use this software for any purpose,\r\n//  including commercial applications, and to alter it and redistribute it\r\n//  freely, subject to the following restrictions:\r\n//\r\n//  1. The origin of this software must not be misrepresented; you must not\r\n//     claim that you wrote the original software. If you use this software\r\n//     in a product, an acknowledgment in the product documentation would be\r\n//     appreciated but is not required.\r\n//  2. Altered source versions must be plainly marked as such, and must not be\r\n//     misrepresented as being the original software.\r\n//  3. This notice may not be removed or altered from any source distribution.\r\n//\r\n//  Tony Richards trichards@indiezen.com\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nextern \"C\" {\r\n#include <lauxlib.h>\r\n#include <lualib.h>\r\n#include <lua.h>\r\n}\r\n\r\n#include \"LuaEngine.hpp\"\r\n#include \"LuaModule.hpp\"\r\n#include \"Config.hpp\"\r\n\r\n#include <Zen/Core/Scripting/I_ScriptModule.hpp>\r\n#include <Zen/Core/Scripting/I_ObjectReference.hpp>\r\n\r\n#include <Zen/Core/Math/Matrix4.hpp>\r\n#include <Zen/Core/Math/Point3.hpp>\r\n#include <Zen/Core/Math/Vector3.hpp>\r\n#include <Zen/Core/Math/Vector4.hpp>\r\n#include <Zen/Core/Math/Radian.hpp>\r\n#include <Zen/Core/Math/Degree.hpp>\r\n#include <Zen/Core/Math/Quaternion4.hpp>\r\n\r\n#include <Zen/Core/Utility/runtime_exception.hpp>\r\n\r\n#include <boost/bind.hpp>\r\n#include <boost/function.hpp>\r\n\r\n#include <iostream>\r\n\r\n#include <stdio.h>\r\n#ifndef WIN32\r\n#include <stdint.h>\r\n#endif\r\n#include <stdlib.h>\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nnamespace Zen {\r\nnamespace ZLua {\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nLuaEngine::LuaEngine()\r\n{\r\n#if 0\r\n    m_pHeap =\r\n        pObjectHeap_type(new LuaHeap(this),\r\n        boost::bind(&LuaEngine::onDestroyObjectHeap,this,_1));\r\n#endif\r\n\r\n    // http://www.lua.org/pil/24.1.html\r\n    m_pLua = lua_open();\r\n\r\n    registerModules();\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nLuaEngine::~LuaEngine()\r\n{\r\n    lua_close(m_pLua);\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nScripting::I_ObjectHeap&\r\nLuaEngine::heap()\r\n{\r\n    //return *m_pHeap;\r\n    throw Utility::runtime_exception(\"LuaEngine::heap(): Error, not implemented\");\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nstatic\r\nstd::string\r\ngetLuaErrorString(int _error)\r\n{\r\n    std::string errorMessage;\r\n\r\n    switch(_error)\r\n    {\r\n    case LUA_ERRSYNTAX:\r\n        errorMessage = \"Lua syntax error\";\r\n        break;\r\n    case LUA_ERRMEM:\r\n        errorMessage = \"Lua out of memory error\";\r\n        break;\r\n    case LUA_ERRRUN:\r\n        errorMessage = \"Lua runtime error\";\r\n        break;\r\n    case LUA_ERRERR:\r\n        errorMessage = \"Lua fatal error\";\r\n        break;\r\n    case LUA_ERRFILE:\r\n        errorMessage = \"Lua file not found error\";\r\n        break;\r\n    case LUA_YIELD:\r\n        errorMessage = \"Lua yield\";\r\n        break;\r\n    }\r\n\r\n    return errorMessage;\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nbool\r\nLuaEngine::executeScript(const std::string& _fileName)\r\n{\r\n    int luaTop = lua_gettop(m_pLua);\r\n\r\n    // TODO This should really use a resource manager, but for now just do it this way\r\n    int error;\r\n\r\n    // Load a file.  The chunk is on top of the stack.\r\n    if ((error = luaL_loadfile(m_pLua, _fileName.c_str())) != 0)\r\n    {\r\n        std::stringstream errString;\r\n        errString << getLuaErrorString(error)\r\n            << \" while loading file \" << _fileName << \".\" << std::endl;\r\n\r\n        errString << lua_tostring(m_pLua, -1) << std::endl;\r\n\r\n        // Pop the error message off the stack.\r\n        lua_pop(m_pLua, 1);\r\n\r\n        throw Utility::runtime_exception(errString.str());\r\n    }\r\n\r\n    int errorHandler = 0;\r\n\r\n    lua_getglobal(m_pLua, \"errorHandler\");\r\n    if (!lua_isnil(m_pLua, lua_gettop(m_pLua)))\r\n    {\r\n        // Set the error handler\r\n        errorHandler = -2;\r\n    }\r\n\r\n    // Duplicate the chunk so we can keep a reference to it.\r\n    // This also makes the chunk be on the top of the stack.\r\n    lua_pushvalue(m_pLua, -2);\r\n\r\n    // Call the chunk.\r\n    if (error = lua_pcall(m_pLua, 0, 0, errorHandler) != 0)\r\n    {\r\n        std::stringstream errString;\r\n        errString << getLuaErrorString(error) << \" \"\r\n            << lua_tostring(m_pLua, -1) << std::endl;\r\n\r\n        lua_getglobal(m_pLua, \"errorHandler\");\r\n\r\n        if (!lua_isnil(m_pLua, lua_gettop(m_pLua)))\r\n        {\r\n            lua_pushstring(m_pLua, errString.str().c_str());\r\n            lua_pcall(m_pLua, 1, 0, 0);\r\n        }\r\n        else\r\n        {\r\n            // TODO No errorHandler function exists.  Should this\r\n            // throw an exception or should an error message be output?\r\n            // For now just output an error message.\r\n            std::cout << errString.str() << std::endl;\r\n        }\r\n\r\n        // Who knows what's leftover on the stack?  Just \r\n        // punt and set it to where we know it should be.\r\n        lua_settop(m_pLua, luaTop + 2);\r\n    }\r\n\r\n    // Pop the errorHandler and the initial chunk.\r\n    lua_pop(m_pLua, 2);\r\n\r\n    // TODO Verify that luaTop hasn't changed.\r\n    luaTop = lua_gettop(m_pLua);\r\n\r\n    return true;\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nstatic int new_Point3(lua_State *L, Math::Point3 _point3);\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nenum TYPES\r\n{\r\n    OBJECT_REFERENCE_TYPE,\r\n    INT_TYPE,\r\n    UINT_TYPE,\r\n    STRING_TYPE,\r\n    REAL_TYPE,\r\n    POINT3_TYPE,\r\n    VOID_TYPE\r\n};\r\n\r\nclass TypeHandler\r\n{\r\npublic:\r\n\ttypedef boost::function<std::string(boost::any&)>\t\tConvertToStringFunction_type;\r\n\ttypedef boost::function<void(lua_State*, boost::any&)>\tPushArgumentFunction_type;\r\n\r\n\tTypeHandler(TYPES _type,\r\n\t\t\tConvertToStringFunction_type _convertToStringFunction,\r\n\t\t\tPushArgumentFunction_type _pushArgumentFunction)\r\n\t:\tm_type(_type)\r\n\t,\tm_convertToStringFunction(_convertToStringFunction)\r\n\t,\tm_pushArgumentFunction(_pushArgumentFunction)\r\n\t{\r\n\r\n\t}\r\n\r\n\tTypeHandler(const TypeHandler& _right)\r\n\t{\r\n\t\tclone(_right);\r\n\t}\r\n\r\n\tTypeHandler& operator=(const TypeHandler& _right)\r\n\t{\r\n\t\treturn clone(_right);\r\n\t}\r\n\r\n\tTypeHandler& clone(const TypeHandler& _right)\r\n\t{\r\n\t\tm_type = _right.m_type;\r\n\t\tm_convertToStringFunction = _right.m_convertToStringFunction;\r\n\t\tm_pushArgumentFunction = _right.m_pushArgumentFunction;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tstd::string convertToString(boost::any& _value)\r\n\t{\r\n\t\treturn m_convertToStringFunction(_value);\r\n\t}\r\n\r\n\tvoid pushArgument(lua_State* _pLuaState, boost::any& _value)\r\n\t{\r\n\t\treturn m_pushArgumentFunction(_pLuaState, _value);\r\n\t}\r\n\r\n\tTYPES getType()\r\n\t{\r\n\t\treturn m_type;\r\n\t}\r\n\r\n\r\nprivate:\r\n\tTYPES \t\t\t\t\t\t\tm_type;\r\n\tConvertToStringFunction_type \tm_convertToStringFunction;\r\n\tPushArgumentFunction_type \t\tm_pushArgumentFunction;\r\n\r\n};\r\n\r\ntypedef std::map<std::string, TypeHandler*> TypeMap_type;\r\nstatic TypeMap_type sm_typeMap;\r\n\r\nstatic bool sm_initialized = false;\r\n\r\nstatic std::string convertIntToString(boost::any& _value)\r\n{\r\n\tstd::stringstream stream;\r\n\tstream << boost::any_cast<int>(_value);\r\n\treturn stream.str();\r\n}\r\n\r\nstatic void pushInt(lua_State* L, boost::any& _value)\r\n{\r\n    int value = boost::any_cast<int>(_value);\r\n    lua_pushinteger(L, value);\r\n}\r\n\r\nstatic std::string convertUIntToString(boost::any& _value)\r\n{\r\n    std::stringstream stream;\r\n    stream << boost::any_cast<unsigned int>(_value);\r\n    return stream.str();\r\n}\r\n\r\nstatic void pushUInt(lua_State* L, boost::any& _value)\r\n{\r\n    int value = boost::any_cast<unsigned int>(_value);\r\n    lua_pushinteger(L, value);\r\n}\r\n\r\nstatic std::string convertStringToString(boost::any& _value)\r\n{\r\n\tstd::string value = boost::any_cast<std::string>(_value);\r\n\treturn value;\r\n}\r\n\r\nstatic void pushString(lua_State* L, boost::any& _value)\r\n{\r\n    std::string value = boost::any_cast<std::string>(_value);\r\n    lua_pushstring(L, value.c_str());\r\n}\r\n\r\nstatic std::string convertRealToString(boost::any& _value)\r\n{\r\n\tstd::stringstream stream;\r\n\tstream << boost::any_cast<Math::Real>(_value);\r\n\treturn stream.str();\r\n}\r\n\r\nstatic void pushReal(lua_State* L, boost::any& _value)\r\n{\r\n    Math::Real value = boost::any_cast<Math::Real>(_value);\r\n    lua_pushnumber(L, value);\r\n}\r\n\r\nstatic std::string convertPoint3ToString(boost::any& _value)\r\n{\r\n\tstd::stringstream stream;\r\n\tMath::Point3 value = boost::any_cast<Math::Point3>(_value);\r\n\tstream << value.m_x << \" \" << value.m_y << \" \" << value.m_z;\r\n\treturn stream.str();\r\n}\r\n\r\nstatic void pushPoint3(lua_State* L, boost::any& _value)\r\n{\r\n    new_Point3(L, boost::any_cast<Math::Point3>(_value));\r\n}\r\n\r\nstatic std::string convertVoidToString(boost::any& _value)\r\n{\r\n\treturn std::string(\"<void>\");\r\n}\r\n\r\nstatic void pushVoid(lua_State* L, boost::any& _value)\r\n{\r\n\tlua_pushnil(L);\r\n}\r\n\r\nstatic std::string convertObjectToString(boost::any& _value)\r\n{\r\n\tthrow Zen::Utility::runtime_exception(\"Error, cannot convert an object to a string.\");\r\n}\r\n\r\nstatic void pushObject(lua_State* L, boost::any& _value)\r\n{\r\n    Scripting::I_ObjectReference* pObj = boost::any_cast<Scripting::I_ObjectReference*>(_value);\r\n    lua_rawgeti(L, LUA_REGISTRYINDEX, (uintptr_t)pObj->getScriptUserData());\r\n}\r\n\r\nstatic void initTypeHuntMaps()\r\n{\r\n    if (sm_initialized)\r\n    {\r\n    \treturn ;\r\n    }\r\n\r\n    sm_initialized = true;\r\n    sm_typeMap[typeid(Scripting::I_ObjectReference*).name()] = new TypeHandler(OBJECT_REFERENCE_TYPE, convertObjectToString, pushObject);\r\n    sm_typeMap[typeid(int).name()] = new TypeHandler(INT_TYPE, convertIntToString, pushInt);\r\n    sm_typeMap[typeid(unsigned int).name()] = new TypeHandler(UINT_TYPE, convertUIntToString, pushUInt);\r\n    sm_typeMap[typeid(std::string).name()] = new TypeHandler(STRING_TYPE, convertStringToString, pushString);\r\n    sm_typeMap[typeid(Math::Real).name()] = new TypeHandler(REAL_TYPE, convertRealToString, pushReal);\r\n    sm_typeMap[typeid(Math::Point3).name()] = new TypeHandler(POINT3_TYPE, convertPoint3ToString, pushPoint3);\r\n    sm_typeMap[typeid(void).name()] = new TypeHandler(VOID_TYPE, convertVoidToString, pushVoid);\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nvoid\r\nLuaEngine::executeMethod(boost::any& _object, boost::any& _method, std::vector<boost::any>& _parms)\r\n{\r\n\tinitTypeHuntMaps();\r\n\r\n    lua_State* const L = getState();\r\n\r\n    int object;\r\n\r\n    TypeMap_type::iterator pType = sm_typeMap.find(_object.type().name());\r\n    if (pType != sm_typeMap.end())\r\n    {\r\n        switch(pType->second->getType())\r\n        {\r\n        case OBJECT_REFERENCE_TYPE:\r\n            object = (uintptr_t)(boost::any_cast<Scripting::I_ObjectReference*>(_object)->getScriptUserData());\r\n            break;\r\n        case INT_TYPE:\r\n            object = boost::any_cast<int>(_object);\r\n            break;\r\n        default:\r\n            // TODO Error?\r\n            return;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // TODO Error?\r\n        return;\r\n    }\r\n\r\n    int method = boost::any_cast<int>(_method);\r\n\r\n    lua_rawgeti(L, LUA_REGISTRYINDEX, method);\r\n    lua_rawgeti(L, LUA_REGISTRYINDEX, object);\r\n\r\n    int parms = 1;\r\n\r\n    for(std::vector<boost::any>::iterator iter = _parms.begin(); iter != _parms.end(); iter++)\r\n    {\r\n        pType = sm_typeMap.find(iter->type().name());\r\n        if (pType == sm_typeMap.end())\r\n        {\r\n            std::cout << \"Error, undefined parameter type \" << iter->type().name() << \" in LuaEngine::executeMethod: \" << iter->type().name() << std::endl;\r\n            return;\r\n        }\r\n\r\n        pType->second->pushArgument(L, *iter);\r\n        parms++;\r\n    }\r\n\r\n    if (lua_pcall(m_pLua, parms, 0, 0) != 0)\r\n    {\r\n        std::string errString = lua_tostring(m_pLua, -1);\r\n        std::cout << errString << std::endl;\r\n    }\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nLuaEngine::pScriptModule_type\r\nLuaEngine::createScriptModule(const std::string& _moduleName, const std::string& _docString)\r\n{\r\n    return pScriptModule_type(new LuaModule(this, _moduleName, _docString),\r\n        boost::bind(&LuaEngine::onDestroyScriptModule,this,_1));\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nLuaTypeMap&\r\nLuaEngine::getTypeMap()\r\n{\r\n    return m_typeMap;\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n#if 0\r\nLuaEngine::pObjectReference_type\r\nLuaEngine::getObject(PyObject* _pObject)\r\n{\r\n    return m_objectMap[_pObject];\r\n}\r\n#endif\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n#if 0\r\nvoid\r\nLuaEngine::setObject(PyObject* _pPyObject, pObjectReference_type _pCPPObject)\r\n{\r\n    // Isn't there a better way to do this?  Is there a way to use the PyObject to store the\r\n    // raw C++ pointer?  For now, we just use this map.\r\n    m_objectMap[_pPyObject] = _pCPPObject;\r\n}\r\n#endif\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nvoid\r\nLuaEngine::onDestroyObjectHeap(wpObjectHeap_type _pObjectHeap)\r\n{\r\n    /// Fire the ObjectHeap's onDestroyEvent\r\n    _pObjectHeap->onDestroyEvent(_pObjectHeap);\r\n\r\n    /// Delete the ObjectHeap\r\n    LuaHeap* pObjectHeap = dynamic_cast<LuaHeap*>(_pObjectHeap.get());\r\n\r\n    if( pObjectHeap )\r\n    {\r\n        delete pObjectHeap;\r\n    }\r\n    else\r\n    {\r\n        throw Utility::runtime_exception(\"Zen::ZLua::LuaEngine::onDestroyObjectHeap() : _pObjectHeap is an invalid LuaHeap.\");\r\n    }\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nvoid\r\nLuaEngine::onDestroyScriptModule(wpScriptModule_type _pScriptModule)\r\n{\r\n    /// Fire the ScriptModule's onDestroyEvent\r\n    _pScriptModule->onDestroyEvent(_pScriptModule);\r\n\r\n    /// Delete the ScriptModule\r\n    LuaModule* pScriptModule = dynamic_cast<LuaModule*>(_pScriptModule.get());\r\n\r\n    if( pScriptModule )\r\n    {\r\n        delete pScriptModule;\r\n    }\r\n    else\r\n    {\r\n        throw Utility::runtime_exception(\"Zen::ZLua::LuaEngine::onDestroyScriptModule() : _pScriptModule is an invalid LuaModule.\");\r\n    }\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nstatic Math::Real checkReal(lua_State *L, int idx)\r\n{\r\n    luaL_argcheck(L, lua_isnumber(L, idx), idx, \"Real expected\");\r\n    return (Math::Real)lua_tonumber(L, idx);\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nstatic const char* sm_pMatrix4 = \"Matrix4\";\r\n\r\nstatic Math::Matrix4* checkMatrix4(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Math::Matrix4* pMatrix4 = (Math::Matrix4*)luaL_checkudata(L, -1, sm_pMatrix4);\r\n    luaL_argcheck(L, pMatrix4 != NULL, idx, \"Matrix4 expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pMatrix4;\r\n}\r\n\r\nstatic int new_Matrix4 (lua_State *L)\r\n{\r\n    const int top = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int table = lua_gettop(L);\r\n\r\n    Math::Matrix4* pMatrix4 = new (lua_newuserdata(L, sizeof(Math::Matrix4))) Math::Matrix4(Math::Matrix4::INIT_IDENTITY);\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, table, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pMatrix4);\r\n    lua_setmetatable(L, table);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pMatrix4);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    // Initialize up to 4x4 matrix\r\n    for(int x = 1; x < 17; x++)\r\n    {\r\n        if (x < top)\r\n        {\r\n            pMatrix4->m_array[x - 1] =  (Zen::Math::Real)lua_tonumber(L, x);\r\n        }\r\n        else\r\n        {\r\n            pMatrix4->m_array[x - 1] = 0.0f;\r\n        }\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\n\r\nstatic int setXRotation_Matrix4(lua_State *L)\r\n{\r\n    Math::Matrix4* pMatrix4 = checkMatrix4(L, 1);\r\n    Math::Radian rotation(checkReal(L, 2));\r\n\r\n    pMatrix4->setXRotation(rotation);\r\n    return 0;\r\n}\r\n\r\nstatic int setYRotation_Matrix4(lua_State *L)\r\n{\r\n    Math::Matrix4* pMatrix4 = checkMatrix4(L, 1);\r\n    Math::Radian rotation(checkReal(L, 2));\r\n\r\n    pMatrix4->setYRotation(rotation);\r\n    return 0;\r\n}\r\n\r\nstatic int setZRotation_Matrix4(lua_State *L)\r\n{\r\n    Math::Matrix4* pMatrix4 = checkMatrix4(L, 1);\r\n    Math::Radian rotation(checkReal(L, 2));\r\n\r\n    pMatrix4->setZRotation(rotation);\r\n    return 0;\r\n}\r\n\r\nstatic int setXYZRotation_Matrix4(lua_State *L)\r\n{\r\n    Math::Matrix4* pMatrix4 = checkMatrix4(L, 1);\r\n    Math::Radian xRotation(checkReal(L, 2));\r\n    Math::Radian yRotation(checkReal(L, 3));\r\n    Math::Radian zRotation(checkReal(L, 4));\r\n\r\n    pMatrix4->setXYZRotation(xRotation, yRotation, zRotation);\r\n    return 0;\r\n}\r\n\r\nstatic int setPosition_Matrix4(lua_State *L)\r\n{\r\n    Math::Matrix4* pMatrix4 = checkMatrix4(L, 1);\r\n    Math::Radian x(checkReal(L, 2));\r\n    Math::Radian y(checkReal(L, 3));\r\n    Math::Radian z(checkReal(L, 4));\r\n\r\n    pMatrix4->setPosition(x,y,z);\r\n    return 0;\r\n}\r\n\r\nstatic const struct luaL_reg MatrixLib [] = {\r\n    {\"setXRotation\", setXRotation_Matrix4},\r\n    {\"setYRotation\", setYRotation_Matrix4},\r\n    {\"setZRotation\", setZRotation_Matrix4},\r\n    {\"setXYZRotation\", setXYZRotation_Matrix4},\r\n    {\"setPosition\", setPosition_Matrix4},\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nstatic const char* sm_pRadian = \"Radian\";\r\n\r\nstatic Math::Radian* checkRadian(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Math::Radian* pRadian = (Math::Radian*)luaL_checkudata(L, -1, sm_pRadian);\r\n    luaL_argcheck(L, pRadian != NULL, idx, \"Radian expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pRadian;\r\n}\r\n\r\nstatic int new_Radian(lua_State* L)\r\n{\r\n    const int top = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int table = lua_gettop(L);\r\n\r\n    Math::Radian* pRadian = new (lua_newuserdata(L, sizeof(Math::Radian))) Math::Radian();\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, table, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pRadian);\r\n    lua_setmetatable(L, table);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pRadian);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    if( 1 <= top )\r\n    {\r\n        *pRadian = (Zen::Math::Real)lua_tonumber(L, 1);\r\n    }\r\n    else\r\n    {\r\n        *pRadian = 0.0f;\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\nstatic const struct luaL_reg RadianLib [] = {\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nstatic const char* sm_pDegree = \"Degree\";\r\n\r\nstatic Math::Degree* checkDegree(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Math::Degree* pDegree = (Math::Degree*)luaL_checkudata(L, -1, sm_pDegree);\r\n    luaL_argcheck(L, pDegree != NULL, idx, \"Degree expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pDegree;\r\n}\r\n\r\nstatic int new_Degree(lua_State* L)\r\n{\r\n    const int top = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int table = lua_gettop(L);\r\n\r\n    Math::Degree* pDegree = new (lua_newuserdata(L, sizeof(Math::Degree))) Math::Degree();\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, table, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pRadian);\r\n    lua_setmetatable(L, table);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pRadian);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    if( 1 <= top )\r\n    {\r\n        *pDegree = (Zen::Math::Real)lua_tonumber(L, 1);\r\n    }\r\n    else\r\n    {\r\n        *pDegree = 0.0f;\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\nstatic const struct luaL_reg DegreeLib [] = {\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nstatic const char* sm_pPoint3= \"Point3\";\r\n\r\nstatic Math::Point3* checkPoint3(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Math::Point3* pPoint3 = (Math::Point3*)luaL_checkudata(L, -1, sm_pPoint3);\r\n    luaL_argcheck(L, pPoint3 != NULL, idx, \"Point3 expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pPoint3;\r\n}\r\n\r\nstatic int new_Point3 (lua_State *L, Math::Point3 _point3)\r\n{\r\n    const int top = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int table = lua_gettop(L);\r\n\r\n    Math::Point3* pPoint3 = new (lua_newuserdata(L, sizeof(Math::Point3))) Math::Point3(_point3);\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, table, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pPoint3);\r\n    lua_setmetatable(L, table);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pPoint3);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    return 1;\r\n}\r\n\r\nstatic int new_Point3NoArgs(lua_State *L)\r\n{\r\n    return new_Point3(L, Math::Point3());\r\n}\r\n\r\nstatic int setX_Point3(lua_State *L)\r\n{\r\n    Math::Point3* pPoint3 = checkPoint3(L, 1);\r\n    Math::Real value = checkReal(L, 2);\r\n\r\n    pPoint3->setX(value);\r\n    return 0;\r\n}\r\n\r\nstatic int setY_Point3(lua_State *L)\r\n{\r\n    Math::Point3* pPoint3 = checkPoint3(L, 1);\r\n    Math::Real value = checkReal(L, 2);\r\n\r\n    pPoint3->setY(value);\r\n    return 0;\r\n}\r\n\r\nstatic int setZ_Point3(lua_State *L)\r\n{\r\n    Math::Point3* pPoint3 = checkPoint3(L, 1);\r\n    Math::Real value = checkReal(L, 2);\r\n\r\n    pPoint3->setZ(value);\r\n    return 0;\r\n}\r\n\r\n\r\nstatic int getX_Point3(lua_State *L)\r\n{\r\n    Math::Point3* pPoint3 = checkPoint3(L, 1);\r\n\r\n    lua_pushnumber(L, pPoint3->getX());\r\n    return 1;\r\n}\r\n\r\nstatic int getY_Point3(lua_State *L)\r\n{\r\n    Math::Point3* pPoint3 = checkPoint3(L, 1);\r\n\r\n    lua_pushnumber(L, pPoint3->getY());\r\n    return 1;\r\n}\r\n\r\nstatic int getZ_Point3(lua_State *L)\r\n{\r\n    Math::Point3* pPoint3 = checkPoint3(L, 1);\r\n\r\n    lua_pushnumber(L, pPoint3->getZ());\r\n    return 1;\r\n}\r\n\r\nstatic const struct luaL_reg Point3Lib [] = {\r\n    {\"setX\", setX_Point3},\r\n    {\"setY\", setY_Point3},\r\n    {\"setZ\", setZ_Point3},\r\n    {\"getX\", getX_Point3},\r\n    {\"getY\", getY_Point3},\r\n    {\"getZ\", getZ_Point3},\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nstatic const char* sm_pVector3 = \"Vector3\";\r\n\r\nstatic Math::Vector3* checkVector3(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Math::Vector3* pVector3 = (Math::Vector3*)luaL_checkudata(L, -1, sm_pVector3);\r\n    luaL_argcheck(L, pVector3 != NULL, idx, \"Vector3 expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pVector3;\r\n}\r\n\r\nstatic int new_Vector3 (lua_State *L)\r\n{\r\n    const int top = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int table = lua_gettop(L);\r\n\r\n    Math::Vector3* pVector3 = new (lua_newuserdata(L, sizeof(Math::Vector3))) Math::Vector3();\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, table, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pVector3);\r\n    lua_setmetatable(L, table);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pVector3);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    for(int x = 1; x < 4; x++)\r\n    {\r\n        if (x <= top)\r\n        {\r\n            pVector3->m_array[x - 1] = (Zen::Math::Real)lua_tonumber(L, x);\r\n        }\r\n        else\r\n        {\r\n            pVector3->m_array[x - 1] = 0.0f;\r\n        }\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\nstatic int destroy_Vector3(lua_State *L)\r\n{\r\n    /// TODO Determine if lua takes care of deleting the pointer automatically\r\n    /// Had problems with the commented code below.\r\n    //Math::Vector3* pVector3 = checkVector3(L,1);\r\n    //if (pVector3 != NULL)\r\n    //{\r\n    //    delete pVector3;\r\n    //}\r\n    return 0;\r\n}\r\n\r\nstatic int setX_Vector3(lua_State *L)\r\n{\r\n    Math::Vector3* pVector3 = checkVector3(L, 1);\r\n    pVector3->m_x = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setY_Vector3(lua_State *L)\r\n{\r\n    Math::Vector3* pVector3 = checkVector3(L, 1);\r\n    pVector3->m_y = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setZ_Vector3(lua_State *L)\r\n{\r\n    Math::Vector3* pVector3 = checkVector3(L, 1);\r\n    pVector3->m_z = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int getX_Vector3(lua_State *L)\r\n{\r\n    Math::Vector3* pVector3 = checkVector3(L, 1);\r\n\r\n    lua_pushnumber(L, pVector3->m_x);\r\n    return 1;\r\n}\r\n\r\nstatic int getY_Vector3(lua_State *L)\r\n{\r\n    Math::Vector3* pVector3 = checkVector3(L, 1);\r\n\r\n    lua_pushnumber(L, pVector3->m_y);\r\n    return 1;\r\n}\r\n\r\nstatic int getZ_Vector3(lua_State *L)\r\n{\r\n    Math::Vector3* pVector3 = checkVector3(L, 1);\r\n\r\n    lua_pushnumber(L, pVector3->m_z);\r\n    return 1;\r\n}\r\n\r\nstatic int add_Vector3(lua_State *L)\r\n{\r\n    new_Vector3(L);\r\n    Math::Vector3* pVector3A = checkVector3(L,1);\r\n    Math::Vector3* pVector3B = checkVector3(L,2);\r\n    Math::Vector3* pVectorResult = checkVector3(L,3);\r\n\r\n    *pVectorResult = *pVector3A + *pVector3B;\r\n\r\n    return 1;\r\n}\r\n\r\nstatic const struct luaL_reg Vector3Lib [] = {\r\n    {\"setX\", setX_Vector3},\r\n    {\"setY\", setY_Vector3},\r\n    {\"setZ\", setZ_Vector3},\r\n    {\"getX\", getX_Vector3},\r\n    {\"getY\", getY_Vector3},\r\n    {\"getZ\", getZ_Vector3},\r\n    {\"add\", add_Vector3},\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nstatic const char* sm_pVector4= \"Vector4\";\r\n\r\nstatic Math::Vector4* checkVector4(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Math::Vector4* pVector4 = (Math::Vector4*)luaL_checkudata(L, -1, sm_pVector4);\r\n    luaL_argcheck(L, pVector4 != NULL, idx, \"Vector4 expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pVector4;\r\n}\r\n\r\nstatic int new_Vector4 (lua_State *L)\r\n{\r\n    const int top = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int table = lua_gettop(L);\r\n\r\n    Math::Vector4* pVector4 = new (lua_newuserdata(L, sizeof(Math::Vector4))) Math::Vector4();\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, table, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pVector4);\r\n    lua_setmetatable(L, table);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pVector4);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    for(int x = 1; x < 5; x++)\r\n    {\r\n        if (x <= top)\r\n        {\r\n            pVector4->m_array[x - 1] = (Zen::Math::Real)lua_tonumber(L, x);\r\n        }\r\n        else\r\n        {\r\n            pVector4->m_array[x - 1] = 0.0f;\r\n        }\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\nstatic int setX_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n    pVector4->m_x = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setY_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n    pVector4->m_y = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setZ_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n    pVector4->m_z = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setW_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n    pVector4->m_w = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int getX_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n\r\n    lua_pushnumber(L, pVector4->m_x);\r\n    return 1;\r\n}\r\n\r\nstatic int getY_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n\r\n    lua_pushnumber(L, pVector4->m_y);\r\n    return 1;\r\n}\r\n\r\nstatic int getZ_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n\r\n    lua_pushnumber(L, pVector4->m_z);\r\n    return 1;\r\n}\r\n\r\nstatic int getW_Vector4(lua_State *L)\r\n{\r\n    Math::Vector4* pVector4 = checkVector4(L, 1);\r\n\r\n    lua_pushnumber(L, pVector4->m_w);\r\n    return 1;\r\n}\r\n\r\nstatic const struct luaL_reg Vector4Lib [] = {\r\n    {\"setX\", setX_Vector4},\r\n    {\"setY\", setY_Vector4},\r\n    {\"setZ\", setZ_Vector4},\r\n    {\"setW\", setW_Vector4},\r\n    {\"getX\", getX_Vector4},\r\n    {\"getY\", getY_Vector4},\r\n    {\"getZ\", getZ_Vector4},\r\n    {\"getW\", getW_Vector4},\r\n    {NULL, NULL}\r\n};\r\n\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\nstatic const char* sm_pQuaternion4 = \"Quaternion4\";\r\n\r\nstatic Math::Quaternion4* checkQuaternion4(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Math::Quaternion4* pQuaternion4 = (Math::Quaternion4*)luaL_checkudata(L, -1, sm_pQuaternion4);\r\n    luaL_argcheck(L, pQuaternion4 != NULL, idx, \"Quaternion4 expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pQuaternion4;\r\n}\r\n\r\nstatic int new_Quaternion4 (lua_State *L)\r\n{\r\n    const int top = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int table = lua_gettop(L);\r\n\r\n    Math::Quaternion4* pQuaternion4 = new (lua_newuserdata(L, sizeof(Math::Quaternion4))) Math::Quaternion4();\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, table, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pQuaternion4);\r\n    lua_setmetatable(L, table);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pQuaternion4);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    for(int x = 1; x < 5; x++)\r\n    {\r\n        if (x <= top)\r\n        {\r\n            pQuaternion4->m_array[x - 1] = (Zen::Math::Real)lua_tonumber(L, x);\r\n        }\r\n        else\r\n        {\r\n            pQuaternion4->m_array[x - 1] = 0.0f;\r\n        }\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\nstatic int setX_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n    pQuaternion4->m_x = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setY_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n    pQuaternion4->m_y = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setZ_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n    pQuaternion4->m_z = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int setW_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n    pQuaternion4->m_w = checkReal(L, 2);\r\n    return 0;\r\n}\r\n\r\nstatic int getX_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n\r\n    lua_pushnumber(L, pQuaternion4->m_x);\r\n    return 1;\r\n}\r\n\r\nstatic int getY_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n\r\n    lua_pushnumber(L, pQuaternion4->m_y);\r\n    return 1;\r\n}\r\n\r\nstatic int getZ_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n\r\n    lua_pushnumber(L, pQuaternion4->m_z);\r\n    return 1;\r\n}\r\n\r\nstatic int getW_Quaternion4(lua_State *L)\r\n{\r\n    Math::Quaternion4* pQuaternion4 = checkQuaternion4(L, 1);\r\n\r\n    lua_pushnumber(L, pQuaternion4->m_w);\r\n    return 1;\r\n}\r\n\r\nstatic const struct luaL_reg Quaternion4Lib [] = {\r\n    {\"setX\", setX_Quaternion4},\r\n    {\"setY\", setY_Quaternion4},\r\n    {\"setZ\", setZ_Quaternion4},\r\n    {\"setW\", setW_Quaternion4},\r\n    {\"getX\", getX_Quaternion4},\r\n    {\"getY\", getY_Quaternion4},\r\n    {\"getZ\", getZ_Quaternion4},\r\n    {\"getW\", getW_Quaternion4},\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nstatic const luaL_Reg MathLib[] = {\r\n    {sm_pMatrix4,       new_Matrix4},\r\n    {sm_pVector3,       new_Vector3},\r\n    {sm_pVector4,       new_Vector4},\r\n    {sm_pPoint3,        new_Point3NoArgs},\r\n    {sm_pRadian,        new_Radian},\r\n    {sm_pDegree,        new_Degree},\r\n    {sm_pQuaternion4,   new_Quaternion4},\r\n    {NULL, NULL}\r\n};\r\n\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nstatic const char* sm_pConfig = \"Config\";\r\n\r\nstatic Config* checkConfig(lua_State *L, int idx)\r\n{\r\n    lua_pushliteral(L, \"__zen_userdata\");\r\n    lua_gettable(L, idx);\r\n\r\n    Config* pConfig = (Config*)luaL_checkudata(L, -1, sm_pConfig);\r\n    luaL_argcheck(L, pConfig != NULL, idx, \"Config expected\");\r\n    lua_pop(L, 1);\r\n\r\n    return pConfig;\r\n}\r\n\r\nstatic int new_Config (lua_State *L)\r\n{\r\n\tinitTypeHuntMaps();\r\n\r\n\t// Save the top of the stack.\r\n\t// This is the first parameter to the Utility.Config(table);\r\n    const int firstArgument = lua_gettop(L);\r\n\r\n    lua_newtable(L);\r\n    const int newTable = lua_gettop(L);\r\n\r\n    // In-place creation of a Config\r\n    Config* pConfig = new (lua_newuserdata(L, sizeof(Config))) Config;\r\n    const int userdata = lua_gettop(L);\r\n\r\n    // T[\"__zen_userdata\"] = UD\r\n    lua_pushvalue(L, userdata);\r\n    lua_setfield(L, newTable, \"__zen_userdata\");\r\n\r\n    // Get the meta table for this class type and set it for this object\r\n    luaL_getmetatable(L, sm_pConfig);\r\n    lua_setmetatable(L, newTable);\r\n\r\n    // Get the meta table for this class type and set it for the user data\r\n    luaL_getmetatable(L, sm_pConfig);\r\n    lua_setmetatable(L, userdata);\r\n\r\n    // Pop the userdata so only the table is left\r\n    lua_pop(L, 1);\r\n\r\n    // Iterate through the first argument, which should be a table.\r\n    // Push nil as the first key\r\n    lua_pushnil(L);\r\n    int x = 0;\r\n\r\n    // Loop through the items in the first argument\r\n    // using the top of the stack as the key.  The first\r\n    // iteration is nil, subsequent iterations are the key.\r\n    // lua_next pushes the next key, next value onto the stack in\r\n    // that order.\r\n    while (lua_next(L, firstArgument) != 0)\r\n    {\r\n    \tx++;\r\n\r\n    \t// Get the type of the key and verify that it's a string\r\n    \tif (lua_type(L, -2) != LUA_TSTRING)\r\n    \t{\r\n    \t\t// If it's not a string, display an error message.\r\n    \t\tstd::cout << \"Error: argument \" << x << \" to Utility.Config() must be a string and not \"\r\n    \t\t\t\t<< lua_typename(L, -2) << \" for key \" << lua_tostring(L, -2);\r\n\r\n    \t\t// Break out of the loop.\r\n    \t\tbreak;\r\n    \t}\r\n\r\n    \t// Get the key and the value for this iteration\r\n    \tconst std::string key = lua_tostring(L, -2);\r\n    \tconst std::string value = lua_tostring(L, -1);\r\n\r\n    \t// Save the value in the map using the key.\r\n    \tpConfig->m_config[key] = value;\r\n\r\n    \t// Pop the value off the stack.  Leave the key on the stack so that\r\n    \t// the lua_next can use it.\r\n    \tlua_pop(L, 1);\r\n    }\r\n\r\n    return 1;\r\n}\r\n\r\nstatic const struct luaL_reg ConfigLib [] = {\r\n\t// TODO Add getter / setter methods?\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nstatic const luaL_Reg UtilityLib[] = {\r\n    {sm_pConfig,       \tnew_Config},\r\n    {NULL, NULL}\r\n};\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\nvoid\r\nLuaEngine::registerModules()\r\n{\r\n    lua_State* const L = getState();\r\n\r\n    luaL_openlibs(L);\r\n\r\n    int libTop = lua_gettop(L);\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    luaL_register(L, \"Math\", MathLib);\r\n\r\n    int mathTop = lua_gettop(L);\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    // Register the Matrix meta table\r\n    luaL_newmetatable(L, sm_pMatrix4);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    luaL_openlib(L, NULL, MatrixLib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    int top2 = lua_gettop(L);\r\n    assert(mathTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    // Register the Point3 meta table\r\n    luaL_newmetatable(L, sm_pPoint3);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    luaL_openlib(L, NULL, Point3Lib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    assert(mathTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    // Register the Radian meta table\r\n    luaL_newmetatable(L, sm_pRadian);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    luaL_openlib(L, NULL, RadianLib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    assert(mathTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    // Register the Degree meta table\r\n    luaL_newmetatable(L, sm_pDegree);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    luaL_openlib(L, NULL, DegreeLib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    assert(mathTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    // Register the Vector3 meta table\r\n    luaL_newmetatable(L, sm_pVector3);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    // metatable.__gc function\r\n    lua_pushstring(L, \"__gc\");\r\n    lua_pushcfunction(L, destroy_Vector3);\r\n    lua_settable(L, -3);\r\n\r\n    // metatable.__add function\r\n    lua_pushstring(L, \"__add\");\r\n    lua_pushcfunction(L, add_Vector3);\r\n    lua_settable(L, -3);\r\n    \r\n    luaL_openlib(L, NULL, Vector3Lib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    assert(mathTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    // Register the Vector4 meta table\r\n    luaL_newmetatable(L, sm_pVector4);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    luaL_openlib(L, NULL, Vector4Lib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    assert(mathTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    // Register the Quaternion4 meta table\r\n    luaL_newmetatable(L, sm_pQuaternion4);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    luaL_openlib(L, NULL, Quaternion4Lib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    assert(mathTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    lua_pop(L,1);\r\n    assert(libTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    luaL_register(L, \"Utility\", UtilityLib);\r\n\r\n    int utilityTop = lua_gettop(L);\r\n\r\n    // Register the Config meta table\r\n    luaL_newmetatable(L, sm_pConfig);\r\n\r\n    // metatable.__index = metatable\r\n    lua_pushstring(L, \"__index\");\r\n    lua_pushvalue(L, -2);\r\n    lua_settable(L, -3);\r\n\r\n    luaL_openlib(L, NULL, ConfigLib, 0);\r\n\r\n    // Pop the metatable\r\n    lua_pop(L, 1);\r\n    assert(utilityTop == lua_gettop(L));\r\n\r\n    //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n\r\n    lua_pop(L, 1);\r\n    assert(libTop == lua_gettop(L));\r\n}\r\n\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n}   // namespace ZLua\r\n}   // namespace Zen\r\n//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\r\n", "meta": {"hexsha": "12421a73070d4721d4dd2dcdb32f5c89a437c418", "size": 41257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/LuaEngine.cpp", "max_stars_repo_name": "indie-zen-plugins/ZLua", "max_stars_repo_head_hexsha": "6fff6e889a27152ed85b0c0c0786e6b8706f2247", "max_stars_repo_licenses": ["MIT"], "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/LuaEngine.cpp", "max_issues_repo_name": "indie-zen-plugins/ZLua", "max_issues_repo_head_hexsha": "6fff6e889a27152ed85b0c0c0786e6b8706f2247", "max_issues_repo_licenses": ["MIT"], "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/LuaEngine.cpp", "max_forks_repo_name": "indie-zen-plugins/ZLua", "max_forks_repo_head_hexsha": "6fff6e889a27152ed85b0c0c0786e6b8706f2247", "max_forks_repo_licenses": ["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.9125896934, "max_line_length": 156, "alphanum_fraction": 0.575272075, "num_tokens": 10806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04535257926399331, "lm_q2_score": 0.015663649630670577, "lm_q1q2_score": 0.0007103869114384069}}
